{"text": "//\n// Copyright Jason Rice 2017\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 NBDL_WEBSOCKET_DETAIL_SEND_HANDSHAKE_RESPONSE_HPP\n#define NBDL_WEBSOCKET_DETAIL_SEND_HANDSHAKE_RESPONSE_HPP\n\n#include <nbdl/detail/beast_sha1.hpp>\n#include <nbdl/promise.hpp>\n#include <nbdl/util/base64_encode.hpp>\n#include <nbdl/websocket/detail/get_auth_token.hpp>\n#include <nbdl/websocket/detail/parse_handshake_request.hpp>\n\n#include <array>\n#include <boost/asio.hpp>\n#include <string_view>\n\nnamespace nbdl::websocket::detail\n{\n  namespace asio = boost::asio;\n  using asio::ip::tcp;\n  using namespace std::string_view_literals;\n  using std::string_view;\n\n  inline std::string generate_accept_token(std::string const& key)\n  {\n    namespace sha1 = nbdl::detail::beast_sha1;\n    using nbdl::util::base64_encode;\n\n    constexpr string_view guid = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"sv;\n    std::array<unsigned char, 20> digest{};\n    sha1::sha1_context ctx{};\n\n    sha1::init(ctx);\n    sha1::update(ctx, key.data(), key.length());\n    sha1::update(ctx, guid.data(), guid.size());\n    sha1::finish(ctx, digest.data());\n\n    return base64_encode(digest);\n  }\n\n  struct send_handshake_response_fn\n  {\n    template <typename Resolver>\n    auto operator()(Resolver& resolver, tcp::socket& socket, handshake_info_t const& handshake_info)\n    {\n      auto const& [websocket_key, cookies] = handshake_info;\n      accept_token = generate_accept_token(websocket_key);\n\n      const Buffers buffers{{\n        asio::buffer(response_start)\n      , asio::buffer(accept_token)\n      , asio::buffer(response_end)\n      }};\n\n      asio::async_write(socket, buffers, [&, cookies = cookies](std::error_code error_code, std::size_t)\n      {\n        if (error_code)\n        {\n          resolver.reject(error_code);\n        }\n        else\n        {\n          resolver.resolve(socket, detail::get_auth_token(cookies));\n        }\n      });\n    }\n\n  private:\n\n    using Buffers = std::array<asio::const_buffer, 3>;\n\n    static constexpr string_view response_start = string_view(\n      \"HTTP/1.1 101 Switching Protocols\"\n      \"\\r\\n\"\n      \"Upgrade: websocket\"\n      \"\\r\\n\"\n      \"Connection: Upgrade\"\n      \"\\r\\n\"\n      \"Sec-WebSocket-Accept: \"\n    );\n    static constexpr string_view response_end = string_view(\"\\r\\n\\r\\n\");\n\n    std::string accept_token{};\n  };\n\n  constexpr auto send_handshake_response = [] { return nbdl::promise(send_handshake_response_fn{}); };\n}\n\n#endif\n", "meta": {"hexsha": "098626231263d533bdbb27b7e348473b47714bea", "size": 2553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nbdl/websocket/detail/send_handshake_response.hpp", "max_stars_repo_name": "ricejasonf/nbdl", "max_stars_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-06-20T01:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:27.000Z", "max_issues_repo_path": "include/nbdl/websocket/detail/send_handshake_response.hpp", "max_issues_repo_name": "ricejasonf/nbdl", "max_issues_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T23:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-17T19:01:40.000Z", "max_forks_repo_path": "include/nbdl/websocket/detail/send_handshake_response.hpp", "max_forks_repo_name": "ricejasonf/nbdl", "max_forks_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:23:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-09T17:54:25.000Z", "avg_line_length": 27.4516129032, "max_line_length": 104, "alphanum_fraction": 0.6811594203, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.1999737555233125}}
{"text": "//\n//  statistics.hpp\n//  ndnrtc\n//\n//  Copyright 2013 Regents of the University of California\n//  For licensing details see the LICENSE file.\n//\n//  Author:  Peter Gusev \n//  Created: 8/21/13\n//\n\n#ifndef ndnrtc_statistics_h\n#define ndnrtc_statistics_h\n\n#include <string>\n#include <map>\n#include <stdexcept>\n#include <iostream>\n#include <iomanip>\n\n#include <boost/shared_ptr.hpp>\n\nnamespace ndnrtc {\n    namespace statistics {\n        enum class Indicator {\n                // general\n                Timestamp,  // NDN-RTC timestamp when statistics were captured\n                \n                // consumer\n                // buffer\n                AcquiredNum,                    // PlaybackQueue\n                AcquiredKeyNum,                 // PlaybackQueue\n                DroppedNum,                     // Buffer\n                DroppedKeyNum,                  // Buffer\n                AssembledNum,                   // Buffer\n                AssembledKeyNum,                // Buffer\n                RecoveredNum,                   // VideoPlayout\n                RecoveredKeyNum,                // VideoPlayout\n                RescuedNum,                     // VideoPlayout\n                RescuedKeyNum,                  // VideoPlayout\n                IncompleteNum,                  // Buffer\n                IncompleteKeyNum,               // Buffer\n                BufferTargetSize,               // RemoteStreamImpl\n                BufferPlayableSize,             // PlaybackQueue\n                BufferReservedSize,             // PlaybackQueue\n                CurrentProducerFramerate,       // BufferControl\n                VerifySuccess,                  // SampleValidator\n                VerifyFailure,                  // SampleValidator\n                LatencyControlStable,           // LatencyControl\n                LatencyControlCommand,          // LatencyControl\n                FrameFetchAvgDelta,             // Buffer\n                FrameFetchAvgKey,               // Buffer\n                \n                // playout\n                LastPlayedNo,                   // VideoPlayout\n                LastPlayedDeltaNo,              // VideoPlayout\n                LastPlayedKeyNo,                // VideoPlayout\n                PlayedNum,                      // VideoPlayout\n                PlayedKeyNum,                   // VideoPlayout\n                SkippedNum,                     // VideoPlayout\n                LatencyEstimated,\n                \n                // pipeliner\n                SegmentsDeltaAvgNum,            // SampleEstimator\n                SegmentsKeyAvgNum,              // SampleEstimator\n                SegmentsDeltaParityAvgNum,      // SampleEstimator\n                SegmentsKeyParityAvgNum,        // SampleEstimator\n                RtxNum,\n                RebufferingsNum,                // PipelineControlStateMachine\n                RequestedNum,                   // Pipeliner\n                RequestedKeyNum,                // Pipeliner\n                DW,                             // InterestControl\n                W,                              // InterestControl\n                SegmentsReceivedNum,            // SegmentController\n                TimeoutsNum,                    // SegmentController\n                NacksNum,                       // SegmentController\n                AppNackNum,                     // SegmentController\n                Darr,                           // LatencyControl\n                BytesReceived,                  // SegmentController\n                RawBytesReceived,               // SegmentController\n                State,                          // PipelineControlStateMachine\n                DoubleRtFrames,                 // Pipeliner\n                DoubleRtFramesKey,              // Pipeliner\n                \n                // DRD estimator\n                DrdOriginalEstimation,          // BufferControl\n                DrdCachedEstimation,            // BufferControl\n                \n                // interest queue\n                QueueSize,                      // InterestQueue\n                InterestsSentNum,               // InterestQueue\n                \n                // producer\n                //media thread\n                BytesPublished,\n                RawBytesPublished,\n                PublishedSegmentsNum,\n                ProcessedNum,\n                PublishedNum,\n                PublishedKeyNum,\n                InterestsReceivedNum,\n                SignNum,\n                \n                // encoder\n                // DroppedNum, // borrowed from buffer (above)\n                EncodedNum,\n                \n                // capturer\n                CapturedNum\n        };\n        \n        class StatisticsStorage {\n        public:\n                typedef std::map<Indicator, double> StatRepo;\n                static const std::map<Indicator, std::string> IndicatorNames;\n                static const std::map<Indicator, std::string> IndicatorKeywords;\n                \n                static StatisticsStorage*\n                createConsumerStatistics()\n                { return new StatisticsStorage(StatisticsStorage::ConsumerStatRepo); }\n                \n                static StatisticsStorage*\n                createProducerStatistics()\n                { return new StatisticsStorage(StatisticsStorage::ProducerStatRepo); }\n                \n                StatisticsStorage(const StatisticsStorage& statisticsStorage):\n                inidicatorNames_(StatisticsStorage::IndicatorNames),\n                indicators_(statisticsStorage.getIndicators()){}\n                ~StatisticsStorage(){}\n                \n                // may throw an exception if indicator is not present in the repo\n                void\n                updateIndicator(const statistics::Indicator& indicator,\n                                const double& value) throw(std::out_of_range);\n                \n                StatRepo\n                getIndicators() const;\n                \n                StatisticsStorage&\n                operator=(const StatisticsStorage& other)\n                {\n                    indicators_ = other.getIndicators();\n                    return *this;\n                }\n                \n                double&\n                operator[](const statistics::Indicator& indicator)\n                { return indicators_.at(indicator); }\n                \n                friend std::ostream& operator<<(std::ostream& os,\n                                                const StatisticsStorage& storage)\n                {\n                    for (auto& it:storage.indicators_)\n                    {\n                        try {\n                            os << std::fixed\n                            << storage.inidicatorNames_.at(it.first) << \"\\t\"\n                            << std::setprecision(2) << it.second << std::endl;\n                        }\n                        catch (...) {\n                        }\n                    }\n                    \n                    return os;\n                }\n        private:\n                StatisticsStorage(const StatRepo& indicators):indicators_(indicators){}\n                \n                const std::map<Indicator, std::string> inidicatorNames_;\n                static const StatRepo ConsumerStatRepo;\n                static const StatRepo ProducerStatRepo;\n                StatRepo indicators_;\n        };\n\n        class StatObject {\n        public:\n            StatObject(const boost::shared_ptr<StatisticsStorage>& statStorage):statStorage_(statStorage){}\n            \n            virtual ~StatObject(){}\n            \n        protected:\n            boost::shared_ptr<StatisticsStorage> statStorage_;\n        };\n    };\n}\n\n#endif\n", "meta": {"hexsha": "754958823f7169517d45aee4e9706274912b35e0", "size": 7778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/include/statistics.hpp", "max_stars_repo_name": "luckiday/ndnrtc", "max_stars_repo_head_hexsha": "ea224ce8d9f01d164925448c7424cf0f0caa4b07", "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": "cpp/include/statistics.hpp", "max_issues_repo_name": "luckiday/ndnrtc", "max_issues_repo_head_hexsha": "ea224ce8d9f01d164925448c7424cf0f0caa4b07", "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": "cpp/include/statistics.hpp", "max_forks_repo_name": "luckiday/ndnrtc", "max_forks_repo_head_hexsha": "ea224ce8d9f01d164925448c7424cf0f0caa4b07", "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.3723404255, "max_line_length": 107, "alphanum_fraction": 0.4456158395, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "#pragma once\r\n\r\n#include <memory>\r\n#include <vector>\r\n#include <Eigen\\Dense>\r\n\r\nnamespace dynaman {\r\n\tclass arfModelLinearBase\r\n\t{\r\n\tpublic:\r\n\t\t~arfModelLinearBase();\r\n\t\tvirtual Eigen::MatrixXf arf(const Eigen::MatrixXf& posRel, const Eigen::MatrixXf& eulerAnglesAUTD) = 0;\r\n\t\tvirtual Eigen::MatrixXf arf(const Eigen::MatrixXf& posRel, const std::vector<Eigen::Matrix3f>& rots) = 0;\r\n\t};\r\n\r\n\tclass arfModelTabular : public arfModelLinearBase\r\n\t{\r\n\tprivate:\r\n\t\tEigen::VectorXf m_tableDistance;\r\n\t\tEigen::VectorXf m_tableAngle;\r\n\t\tEigen::MatrixXf m_tableForce;\r\n\r\n\t\tEigen::MatrixXf arfFromDirections(const Eigen::MatrixXf& posRel, const Eigen::MatrixXf& directionsAutd);\r\n\r\n\tpublic:\r\n\t\tarfModelTabular(const Eigen::VectorXf& tableDistance, const Eigen::VectorXf& tableAngle, const Eigen::MatrixXf& tableForce);\r\n\t\tEigen::MatrixXf arf(const Eigen::MatrixXf& posRel, const Eigen::MatrixXf& eulerAnglesAutd) override;\r\n\t\tEigen::MatrixXf arf(const Eigen::MatrixXf& posRel, const std::vector<Eigen::Matrix3f>& rots) override;\r\n\t};\r\n\r\n\tclass arfModelFocusSphereR100 : public arfModelTabular\r\n\t{\r\n\tpublic:\r\n\t\tarfModelFocusSphereR100();\r\n\r\n\tprivate:\r\n\t\tEigen::VectorXf tableDistances() const;\r\n\t\tEigen::VectorXf tableAngles() const;\r\n\t\tEigen::MatrixXf tableForces() const;\r\n\t};\r\n\r\n\tclass arfModelFocusSphereR50 : public arfModelTabular {\r\n\tpublic:\r\n\t\tarfModelFocusSphereR50();\r\n\r\n\tprivate:\r\n\t\tEigen::VectorXf tableDistances() const;\r\n\t\tEigen::VectorXf tableAngles() const;\r\n\t\tEigen::MatrixXf tableForces() const;\r\n\t};\r\n}\r\n", "meta": {"hexsha": "8321aa61615608c2ed447219a5123ecdb768a947", "size": 1512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/arfModel.hpp", "max_stars_repo_name": "shinolab/dynamic-manipulation", "max_stars_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "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": "inc/arfModel.hpp", "max_issues_repo_name": "shinolab/dynamic-manipulation", "max_issues_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_issues_repo_licenses": ["MIT"], "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/arfModel.hpp", "max_forks_repo_name": "shinolab/dynamic-manipulation", "max_forks_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_forks_repo_licenses": ["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.0769230769, "max_line_length": 127, "alphanum_fraction": 0.7321428571, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "#include <ros/ros.h>\n#include <pcl_ros/point_cloud.h>\n#include <boost/foreach.hpp>\n\n#include <iostream>\n#include <thread>\n#include <vector>\n\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/search/search.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/segmentation/region_growing_rgb.h>\n#include <pcl/filters/voxel_grid.h>\n\n\n#include <ros/ros.h>\n#include <sensor_msgs/PointCloud2.h>\n// PCL specific includes\n#include <pcl/ros/conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n\nros::Publisher pub;\n\nvoid\ncloud_cb (const sensor_msgs::PointCloud2ConstPtr& input)\n{\n  // Convert the sensor_msgs/PointCloud2 data to pcl/PointCloud\n  pcl::PointCloud <pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud <pcl::PointXYZRGB>);\n  pcl::fromROSMsg (*input, *cloud);\n\n\n  std::cout << \"test: \" << cloud->points[4]  << std::endl;\n  std::cout << \"test2: \" << cloud->points[4].rgb << cloud->points[4].r << cloud->points[4].g << cloud->points[4].b << std::endl;\n\n  pcl::search::Search <pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>);\n\n  pcl::PointCloud <pcl::PointXYZRGB>::Ptr cloud_filtered (new pcl::PointCloud <pcl::PointXYZRGB>);\n  // Perform the actual filtering\n  pcl::VoxelGrid<pcl::PointXYZRGB> sor;\n  sor.setInputCloud (cloud);\n  float voxel_size = 0.04;\n  sor.setMinimumPointsNumberPerVoxel(3);\n  sor.setLeafSize (voxel_size, voxel_size, voxel_size);\n  sor.filter (*cloud_filtered);\n\n  pcl::IndicesPtr indices (new std::vector <int>);\n  pcl::PassThrough<pcl::PointXYZRGB> pass;\n  pass.setInputCloud (cloud_filtered);\n  pass.setFilterFieldName (\"z\");\n  pass.setFilterLimits (0.0, 5.0);\n  pass.filter (*indices);\n\n  pcl::RegionGrowingRGB<pcl::PointXYZRGB> reg;\n  reg.setInputCloud (cloud_filtered);\n  reg.setIndices (indices);\n  reg.setSearchMethod (tree);\n  reg.setDistanceThreshold (0.06);\n  reg.setPointColorThreshold (6);\n  reg.setRegionColorThreshold (2);\n  reg.setMinClusterSize (60);\n  reg.setMaxClusterSize (5000);\n\n  std::vector <pcl::PointIndices> clusters;\n  reg.extract (clusters);\n\n  pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud ();\n\n  sensor_msgs::PointCloud2 output;\n\n  pcl::toROSMsg(*colored_cloud,output);\n  output.header.frame_id = input->header.frame_id;\n\n  // Publish the data\n  pub.publish (output);\n}\n\nint\nmain (int argc, char** argv)\n{\n  // Initialize ROS\n  ros::init (argc, argv, \"segment_rgb\");\n  ros::NodeHandle nh;\n\n  // Create a ROS subscriber for the input point cloud\n  ros::Subscriber sub = nh.subscribe (\"/camera/depth/color/points\", 1, cloud_cb);\n\n  // Create a ROS publisher for the output point cloud\n  pub = nh.advertise<sensor_msgs::PointCloud2> (\"output_rgb\", 1);\n\n  // Spin\n  ros::spin ();\n}\n\n\n\n/*\ntypedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud;\n\nvoid callback(const PointCloud::ConstPtr& msg)\n{\n  printf (\"Cloud: width = %d, height = %d\\n\", msg->width, msg->height);\n\n  pcl::PointCloud <pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud <pcl::PointXYZRGB>);\n//  BOOST_FOREACH (cloud, msg->points);\n\n//  pcl::visualization::CloudViewer viewer (\"Cluster viewer\");\n//  viewer.showCloud (cloud);\n\n//  pcl::search::Search <pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>);\n\n//  pcl::IndicesPtr indices (new std::vector <int>);\n//  pcl::PassThrough<pcl::PointXYZRGB> pass;\n//  pass.setInputCloud (cloud);\n//  pass.setFilterFieldName (\"z\");\n//  pass.setFilterLimits (0.0, 5.0);\n//  pass.filter (*indices);\n\n//  pcl::RegionGrowingRGB<pcl::PointXYZRGB> reg;\n//  reg.setInputCloud (cloud);\n//  reg.setIndices (indices);\n//  reg.setSearchMethod (tree);\n//  reg.setDistanceThreshold (10);\n//  reg.setPointColorThreshold (6);\n//  reg.setRegionColorThreshold (5);\n//  reg.setMinClusterSize (600);\n\n//  std::vector <pcl::PointIndices> clusters;\n//  reg.extract (clusters);\n\n//  pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud ();\n//  pcl::visualization::CloudViewer viewer (\"Cluster viewer\");\n//  viewer.showCloud (colored_cloud);\n\n}\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"sub_pcl\");\n  ros::NodeHandle nh;\n  ros::Subscriber sub = nh.subscribe<PointCloud>(\"points2\", 1, callback);\n  ros::spin();\n}\n*/\n", "meta": {"hexsha": "fdd080facf1e868de9fd048e113c79e866b00d41", "size": 4272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "camera/src/segment_rgb.cpp", "max_stars_repo_name": "miriamschmelzer/SegSlam", "max_stars_repo_head_hexsha": "4b4f8226636a0b3e04b2dad0be244681548fd44a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-11T13:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T13:55:52.000Z", "max_issues_repo_path": "camera/src/segment_rgb.cpp", "max_issues_repo_name": "miriamschmelzer/SegSlam", "max_issues_repo_head_hexsha": "4b4f8226636a0b3e04b2dad0be244681548fd44a", "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": "camera/src/segment_rgb.cpp", "max_forks_repo_name": "miriamschmelzer/SegSlam", "max_forks_repo_head_hexsha": "4b4f8226636a0b3e04b2dad0be244681548fd44a", "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.8648648649, "max_line_length": 128, "alphanum_fraction": 0.7052902622, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "#include <iostream>\n#include <openssl/sha.h>\n#include \"patternsearch.h\"\n#include <openssl/aes.h>\n#include \"main.h\"\n#include <openssl/evp.h>\n#include <boost/thread.hpp>\n#include \"util.h\"\n\nnamespace patternsearch\n{\n\t#define PSUEDORANDOM_DATA_SIZE 30 //2^30 = 1GB\n    #define PSUEDORANDOM_DATA_CHUNK_SIZE 6 //2^6 = 64 bytes //must be same as SHA512_DIGEST_LENGTH 64\n    #define L2CACHE_TARGET 12 // 2^12 = 4096 bytes\n    #define AES_ITERATIONS 15\n\n\t// useful constants\n    uint32_t psuedoRandomDataSize=(1<<PSUEDORANDOM_DATA_SIZE); //2^30 = 1GB\n    uint32_t cacheMemorySize = (1<<L2CACHE_TARGET); //2^12 = 4096 bytes\n    uint32_t chunks=(1<<(PSUEDORANDOM_DATA_SIZE-PSUEDORANDOM_DATA_CHUNK_SIZE)); //2^(30-6) = 16 mil\n    uint32_t chunkSize=(1<<(PSUEDORANDOM_DATA_CHUNK_SIZE)); //2^6 = 64 bytes\n    uint32_t comparisonSize=(1<<(PSUEDORANDOM_DATA_SIZE-L2CACHE_TARGET)); //2^(30-12) = 256K\n\t\n\tvoid static SHA512Filler(char *mainMemoryPsuedoRandomData, int threadNumber, int totalThreads,uint256 midHash){\n\t\t//Generate psuedo random data to store in main memory\n\t\tunsigned char hash_tmp[sizeof(midHash)];\n\t\tmemcpy((char*)&hash_tmp[0], (char*)&midHash, sizeof(midHash) );\n\t\tuint32_t* index = (uint32_t*)hash_tmp;\n\t\tuint32_t chunksToProcess=chunks/totalThreads;\n\t\tuint32_t startChunk=threadNumber*chunksToProcess;\n\t\tfor( uint32_t i = startChunk; i < startChunk+chunksToProcess;  i++){\n            //This changes the first character of hash_tmp\n\t\t\t*index = i;\n            SHA512((unsigned char*)hash_tmp, sizeof(hash_tmp), (unsigned char*)&(mainMemoryPsuedoRandomData[i*chunkSize]));\n\t\t}\n\t}\n\t\n\tvoid static aesSearch(char *mainMemoryPsuedoRandomData, int threadNumber, int totalThreads, std::vector< std::pair<uint32_t,uint32_t> > *results, boost::mutex *mtx){\n\t\t//Allocate temporary memory\n\t\tunsigned char *cacheMemoryOperatingData;\n\t\tunsigned char *cacheMemoryOperatingData2;\t\n\t\tcacheMemoryOperatingData=new unsigned char[cacheMemorySize+16];\n\t\tcacheMemoryOperatingData2=new unsigned char[cacheMemorySize];\n\t\n\t\t//Create references to data as 32 bit arrays\n\t\tuint32_t* cacheMemoryOperatingData32 = (uint32_t*)cacheMemoryOperatingData;\n\t\tuint32_t* cacheMemoryOperatingData322 = (uint32_t*)cacheMemoryOperatingData2;\n        //uint32_t* mainMemoryPsuedoRandomData32 = (uint32_t*)mainMemoryPsuedoRandomData;\n\t\t\n\t\t//Search for pattern in psuedorandom data\n\t\t\n\t\tunsigned char key[32] = {0};\n\t\tunsigned char iv[AES_BLOCK_SIZE];\n\t\tint outlen1, outlen2;\n        unsigned int useEVP = GetArg(\"-useevp\", 1);\n\t\t\n\t\t//Iterate over the data\n\t\tint searchNumber=comparisonSize/totalThreads;\n\t\tint startLoc=threadNumber*searchNumber;\n\t\tfor(uint32_t k=startLoc;k<startLoc+searchNumber;k++){\n\t\t\t\n            //copy data to first l2 cache\n\t\t\tmemcpy((char*)&cacheMemoryOperatingData[0], (char*)&mainMemoryPsuedoRandomData[k*cacheMemorySize], cacheMemorySize);\n\t\t\t\n\t\t\tfor(int j=0;j<AES_ITERATIONS;j++){\n\n                //use last 4 bytes of first cache as next location\n\t\t\t\tuint32_t nextLocation = cacheMemoryOperatingData32[(cacheMemorySize/4)-1]%comparisonSize;\n\n\t\t\t\t//Copy data from indicated location to second l2 cache -\n\t\t\t\tmemcpy((char*)&cacheMemoryOperatingData2[0], (char*)&mainMemoryPsuedoRandomData[nextLocation*cacheMemorySize], cacheMemorySize);\n\n\t\t\t\t//XOR location data into second cache\n\t\t\t\tfor(uint32_t i = 0; i < cacheMemorySize/4; i++){\n\t\t\t\t\tcacheMemoryOperatingData322[i] = cacheMemoryOperatingData32[i] ^ cacheMemoryOperatingData322[i];\n\t\t\t\t}\n\n\t\t\t\t//AES Encrypt using last 256bits of Xorred value as key\n\t\t\t\t//AES_set_encrypt_key((unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-32], 256, &AESkey);\n\t\t\t\t\n\t\t\t\t//Use last X bits as initial vector\n\t\t\t\t\n\t\t\t\t//AES CBC encrypt data in cache 2, place it into cache 1, ready for the next round\n\t\t\t\t//AES_cbc_encrypt((unsigned char*)&cacheMemoryOperatingData2[0], (unsigned char*)&cacheMemoryOperatingData[0], cacheMemorySize, &AESkey, iv, AES_ENCRYPT);\n\t\t\t\tif(useEVP){\n\t\t\tEVP_CIPHER_CTX          *ctx = EVP_CIPHER_CTX_new();\n\t\t\t\t\tmemcpy(key,(unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-32],32);\n\t\t\t\t\tmemcpy(iv,(unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-AES_BLOCK_SIZE],AES_BLOCK_SIZE);\n\t\t\t\t\tEVP_EncryptInit(ctx, EVP_aes_256_cbc(), key, iv);\n\t\t\t\t\tEVP_EncryptUpdate(ctx, cacheMemoryOperatingData, &outlen1, cacheMemoryOperatingData2, cacheMemorySize);\n\t\t\t\t\tEVP_EncryptFinal(ctx, cacheMemoryOperatingData + outlen1, &outlen2);\n\t\t\t\t\tEVP_CIPHER_CTX_cleanup(ctx);\n\t\t\t\t}else{\n\t\t\t\t\tAES_KEY AESkey;\n\t\t\t\t\tAES_set_encrypt_key((unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-32], 256, &AESkey);\t\t\t\n\t\t\t\t\tmemcpy(iv,(unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-AES_BLOCK_SIZE],AES_BLOCK_SIZE);\n\t\t\t\t\tAES_cbc_encrypt((unsigned char*)&cacheMemoryOperatingData2[0], (unsigned char*)&cacheMemoryOperatingData[0], cacheMemorySize, &AESkey, iv, AES_ENCRYPT);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//use last X bits as solution\n\t\t\tuint32_t solution=cacheMemoryOperatingData32[(cacheMemorySize/4)-1]%comparisonSize;\n            if(solution<1000){\n\t\t\t\tuint32_t proofOfCalculation=cacheMemoryOperatingData32[(cacheMemorySize/4)-2];\n                //LogPrintf(\"found solution - %d / %u / %u\\n\",k,solution,proofOfCalculation);\n\t\t\t\tboost::mutex::scoped_lock lck(*mtx);\n\t\t\t\t(*results).push_back( std::make_pair( k, proofOfCalculation ) );\n\t\t\t}\n\t\t}\n\t\t\n\t\t//free memory\n\t\tdelete [] cacheMemoryOperatingData;\n\t\tdelete [] cacheMemoryOperatingData2;\n\t}\n\t\n    std::vector< std::pair<uint32_t,uint32_t> > pattern_search( uint256 midHash, char *mainMemoryPsuedoRandomData, int totalThreads){\n\n            boost::this_thread::disable_interruption di;\n\n\t\tstd::vector< std::pair<uint32_t,uint32_t> > results;\n\t\t\n        //clock_t t1 = clock();\n\t\tboost::thread_group* sha512Threads = new boost::thread_group();\n\t\tchar *threadsComplete;\n\t\tthreadsComplete=new char[totalThreads];\n\t\tfor (int i = 0; i < totalThreads; i++){\n\t\t\tsha512Threads->create_thread(boost::bind(&SHA512Filler, mainMemoryPsuedoRandomData, i,totalThreads,midHash));\n\t\t}\n\t\t//Wait for all threads to complete\n\t\tsha512Threads->join_all();\n\t\t\n        //clock_t t2 = clock();\n        //LogPrintf(\"create sha512 data %d\\n\",((double)t2-(double)t1)/CLOCKS_PER_SEC);\n\n\t\tboost::mutex mtx;\n\t\tboost::thread_group* aesThreads = new boost::thread_group();\n\t\tthreadsComplete=new char[totalThreads];\n\t\tfor (int i = 0; i < totalThreads; i++){\n\t\t\taesThreads->create_thread(boost::bind(&aesSearch, mainMemoryPsuedoRandomData, i,totalThreads,&results, &mtx));\n\t\t}\n\t\t//Wait for all threads to complete\n\t\taesThreads->join_all();\n\n        //clock_t t3 = clock();\n        //LogPrintf(\"aes search %d\\n\",((double)t3-(double)t2)/CLOCKS_PER_SEC);\n\n\t\tdelete aesThreads;\n\t\tdelete sha512Threads;\n            boost::this_thread::restore_interruption ri(di);\n\t\treturn results;\n\t}\n\t\n\t\n\t\n    bool pattern_verify( uint256 midHash, uint32_t a, uint32_t b ){\n\t\t//return false;\n\t\t\n\t\tclock_t t1 = clock();\n\t\t\n\t\t//Basic check\n        if( a >= comparisonSize ) return false;\n\t\t\n\t\t//Allocate memory required\n\t\tunsigned char *cacheMemoryOperatingData;\n\t\tunsigned char *cacheMemoryOperatingData2;\t\n\t\tcacheMemoryOperatingData=new unsigned char[cacheMemorySize+16];\n\t\tcacheMemoryOperatingData2=new unsigned char[cacheMemorySize];\n\t\tuint32_t* cacheMemoryOperatingData32 = (uint32_t*)cacheMemoryOperatingData;\n\t\tuint32_t* cacheMemoryOperatingData322 = (uint32_t*)cacheMemoryOperatingData2;\n\t\t\n\t\tunsigned char  hash_tmp[sizeof(midHash)];\n\t\tmemcpy((char*)&hash_tmp[0], (char*)&midHash, sizeof(midHash) );\n\t\tuint32_t* index = (uint32_t*)hash_tmp;\n\t\t\n\t\tuint32_t startLocation=a*cacheMemorySize/chunkSize;\n\t\tuint32_t finishLocation=startLocation+(cacheMemorySize/chunkSize);\n\t\t\t\n        //copy data to first l2 cache\n\t\tfor( uint32_t i = startLocation; i <  finishLocation;  i++){\n\t\t\t*index = i;\n\t\t\tSHA512((unsigned char*)hash_tmp, sizeof(hash_tmp), (unsigned char*)&(cacheMemoryOperatingData[(i-startLocation)*chunkSize]));\n\t\t}\n\t\t\n        unsigned int useEVP = GetArg(\"-useevp\", 1);\n\n        //allow override for AESNI testing\n        /*if(midHash==0){\n            useEVP=0;\n        }else if(midHash==1){\n            useEVP=1;\n        }*/\n\n        unsigned char key[32] = {0};\n\t\tunsigned char iv[AES_BLOCK_SIZE];\n\t\tint outlen1, outlen2;\n\t\t\n\t\t//memset(cacheMemoryOperatingData2,0,cacheMemorySize);\n\t\tfor(int j=0;j<AES_ITERATIONS;j++){\n\t\t\t\n\t\t\t//use last 4 bits as next location\n\t\t\tstartLocation = (cacheMemoryOperatingData32[(cacheMemorySize/4)-1]%comparisonSize)*cacheMemorySize/chunkSize;\n\t\t\tfinishLocation=startLocation+(cacheMemorySize/chunkSize);\n\t\t\tfor( uint32_t i = startLocation; i <  finishLocation;  i++){\n\t\t\t\t*index = i;\n\t\t\t\tSHA512((unsigned char*)hash_tmp, sizeof(hash_tmp), (unsigned char*)&(cacheMemoryOperatingData2[(i-startLocation)*chunkSize]));\n\t\t\t}\n\n\t\t\t//XOR location data into second cache\n\t\t\tfor(uint32_t i = 0; i < cacheMemorySize/4; i++){\n\t\t\t\tcacheMemoryOperatingData322[i] = cacheMemoryOperatingData32[i] ^ cacheMemoryOperatingData322[i];\n\t\t\t}\n\t\t\t\t\n\t\t\t//AES Encrypt using last 256bits as key\n\t\t\t\n\t\t\tif(useEVP){\nEVP_CIPHER_CTX          *ctx = EVP_CIPHER_CTX_new();\n\t\t\t\tmemcpy(key,(unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-32],32);\n\t\t\t\tmemcpy(iv,(unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-AES_BLOCK_SIZE],AES_BLOCK_SIZE);\n\t\t\t\tEVP_EncryptInit(ctx, EVP_aes_256_cbc(), key, iv);\n\t\t\t\tEVP_EncryptUpdate(ctx, cacheMemoryOperatingData, &outlen1, cacheMemoryOperatingData2, cacheMemorySize);\n\t\t\t\tEVP_EncryptFinal(ctx, cacheMemoryOperatingData + outlen1, &outlen2);\n\t\t\t\tEVP_CIPHER_CTX_cleanup(ctx);\n\t\t\t}else{\n\t\t\t\tAES_KEY AESkey;\n\t\t\t\tAES_set_encrypt_key((unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-32], 256, &AESkey);\t\t\t\n\t\t\t\tmemcpy(iv,(unsigned char*)&cacheMemoryOperatingData2[cacheMemorySize-AES_BLOCK_SIZE],AES_BLOCK_SIZE);\n\t\t\t\tAES_cbc_encrypt((unsigned char*)&cacheMemoryOperatingData2[0], (unsigned char*)&cacheMemoryOperatingData[0], cacheMemorySize, &AESkey, iv, AES_ENCRYPT);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\t\n\t\t//use last X bits as solution\n\t\tuint32_t solution=cacheMemoryOperatingData32[(cacheMemorySize/4)-1]%comparisonSize;\n\t\tuint32_t proofOfCalculation=cacheMemoryOperatingData32[(cacheMemorySize/4)-2];\n        //LogPrintf(\"verify solution - %d / %u / %u\\n\",a,solution,proofOfCalculation);\n\t\t\n\t\t//free memory\n\t\tdelete [] cacheMemoryOperatingData;\n\t\tdelete [] cacheMemoryOperatingData2;\t\t\n\n        clock_t t2 = clock();\n        //LogPrintf(\"verify %d\\n\",((double)t2-(double)t1)/CLOCKS_PER_SEC);\n\n        if(solution<1000 && proofOfCalculation==b){\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\n\t}\n}\n", "meta": {"hexsha": "e8466d4f4e27787b928e875d4499d324ffc1cf76", "size": 10494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/patternsearch.cpp", "max_stars_repo_name": "EuropecoinEUORG/Europecoin-V3", "max_stars_repo_head_hexsha": "cd75cae731e037632ab7f0fcbe7ab557eec64640", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-22T00:16:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T01:18:41.000Z", "max_issues_repo_path": "src/patternsearch.cpp", "max_issues_repo_name": "EuropecoinEUORG/Europecoin-V3", "max_issues_repo_head_hexsha": "cd75cae731e037632ab7f0fcbe7ab557eec64640", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-21T01:53:12.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-21T01:53:12.000Z", "max_forks_repo_path": "src/patternsearch.cpp", "max_forks_repo_name": "EuropecoinEUORG/Europecoin-V3", "max_forks_repo_head_hexsha": "cd75cae731e037632ab7f0fcbe7ab557eec64640", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T02:08:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-18T02:08:35.000Z", "avg_line_length": 41.6428571429, "max_line_length": 166, "alphanum_fraction": 0.7238421955, "num_tokens": 2944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.2845759981489974, "lm_q1q2_score": 0.19992318876815676}}
{"text": "#include <stdio.h>\n#include <string>\n#include <map>\n#include <fstream>\n#include \"llvm/Support/raw_ostream.h\"\n#include <cstdio>\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <array>\n#include <regex>\n#include \"helper.h\"\n#include \"klee/ExecutionState.h\"\n#include \"Executor.h\"\n#include <cmath>\n#include <math.h>\n#include <vector>\n#include <boost/lambda/lambda.hpp>\n#include <boost/math/distributions/beta.hpp>\n#include \"TeleScopeHandler.h\"\n\nusing namespace klee;\nusing namespace std;\nusing namespace llvm;\n\n//==============================================\n//============= TeleScopeHandler ===============\n//==============================================\n\nTeleScopeHandler::TeleScopeHandler(int n)\n{\n   numLoop = n;\n}\n\nint TeleScopeHandler::ProcessAllPaths(vector<ExecutionState *> states)\n{\n   LOG(LOG_MASK_TS, \"Telescoping done, final result is %g\",\n       TeleScopeData::finalResult / numLoop);\n   return 0;\n}\n\nint TeleScopeHandler::ts_init_handler(ExecutionState *state,\n                                      int small_thres, int real_thres)\n{\n   state->tsData.ts_init(state, small_thres, real_thres);\n   return 0;\n}\n\nint TeleScopeHandler::ts_pkt_handler(ExecutionState *state,\n                                      int pktID, int cur_reg)\n{\n   assert(state == state->tsData.getState());\n   state->tsData.ts_pkt(pktID, cur_reg);\n   return 0;\n}\n\nint TeleScopeHandler::ts_handler(ExecutionState *state, int cur_reg)\n{\n   assert(state == state->tsData.getState());\n   state->tsData.ts_final(cur_reg);\n   return 0;\n}\n\nint TeleScopeHandler::ts_cmin_pkt_handler(ExecutionState *state,\n                                          int pktID)\n{\n   assert(state == state->tsData.getState());\n   int cmin_max = state->cmin->getMaxValue();\n   state->tsData.ts_pkt(pktID, cmin_max);\n   return 0;\n}\n\nint TeleScopeHandler::ts_cmin_handler(ExecutionState *state)\n{\n   assert(state == state->tsData.getState());\n   int cmin_max = state->cmin->getMaxValue();\n   state->tsData.ts_final(cmin_max);\n   return 0;\n}\n\n\n//==============================================\n//============= TeleScopeData ==================\n//==============================================\n\ndouble TeleScopeData::finalResult = 0.0;\n\nTeleScopeData::TeleScopeData():\n   reg(0),\n   smallThres(0),\n   realThres(0),\n   pktProbs(0)\n{}\n\nTeleScopeData::TeleScopeData(const TeleScopeData &_tsData):\n   state(_tsData.state),\n   reg(_tsData.reg),\n   smallThres(_tsData.smallThres),\n   realThres(_tsData.realThres),\n   perPktProbs(_tsData.perPktProbs),\n   pktProbs(_tsData.pktProbs),\n   pktRegs(_tsData.pktRegs)\n{\n\n}\n\nvoid TeleScopeData::dump()\n{\n   uint32_t i;\n   LOG(LOG_MASK_TS, \"state %d has %ld pkt probs\", state->id, perPktProbs.size());\n   for (i = 0; i < pktProbs.size(); i ++) {\n      LOG(LOG_MASK_TS, \"pkt[%d] prob=%g\", i, perPktProbs[i])\n   }\n\n   LOG(LOG_MASK_TS, \"state %d has %ld pkt regs\", state->id, pktRegs.size());\n   for (i = 0; i < pktRegs.size(); i ++) {\n      LOG(LOG_MASK_TS, \"pkt[%d] reg=%d\", i, pktRegs[i])\n   }\n}\n\nint TeleScopeData::ts_init(ExecutionState *s, int small_thres, int real_thres)\n{\n   LOG(LOG_MASK_TS, \"Initing TsData, small thres=%d, real thres=%d\",\n       small_thres, real_thres);\n   state = s;\n   smallThres = small_thres;\n   realThres  = real_thres;\n   return 0;\n}\n\nint TeleScopeData::ts_pkt(int pktID, int cur_reg)\n{\n   //LOG(LOG_MASK_TS, \"Updating TsData for pkt=%d, pathProb=%g, reg: %d->%d\",\n   //    pktID, state->getPathProb(), reg, cur_reg);\n\n   if (int(pktRegs.size()) != pktID) {\n      WARN(\"pktregs size=%ld, pktID=%d\\n\", pktRegs.size(), pktID);\n      assert(0);\n   }\n   assert(int(pktRegs.size()) == pktID);\n   assert(int(perPktProbs.size()) == pktID);\n   assert(int(pktProbs.size()) == pktID);\n\n   reg = cur_reg;\n\n   // TODO; Update per-packet constraints and probs\n   double pathProb = state->getPathProb();\n   pktProbs.push_back(pathProb);\n   if (pktID == 0) {\n      perPktProbs.push_back(pathProb);\n   } else {\n      double lastProb = pktProbs[pktID - 1];\n      perPktProbs.push_back(pathProb / lastProb);\n   }\n   pktRegs.push_back(cur_reg);\n\n   return 0;\n}\n\nbool AlmostEqual2sComplement(float A, float B, int maxUlps)\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(maxUlps > 0 && maxUlps < 4 * 1024 * 1024);\n    int aInt = *(int*)&A;\n    // Make aInt lexicographically ordered as a twos-complement int\n    if (aInt < 0)\n        aInt = 0x80000000 - aInt;\n    // Make bInt lexicographically ordered as a twos-complement int\n    int bInt = *(int*)&B;\n    if (bInt < 0)\n        bInt = 0x80000000 - bInt;\n    int intDiff = abs(aInt - bInt);\n    if (intDiff <= maxUlps)\n        return true;\n    return false;\n}\n\nstatic int checkVectorSame(vector<double> v)\n{\n   int ret = 0;\n   double first = v[0];\n   for (auto val: v) {\n      if (!AlmostEqual2sComplement(val, first, 1)) {\n         ret = 1;\n      }\n   }\n   if (ret == 0) {\n      return 0;\n   }\n\n   assert(ret == 1);\n   double second = v[1];\n   for (uint32_t i = 2; i < v.size(); i ++) {\n      if (!AlmostEqual2sComplement(v[i], second, 1)) {\n         ret = 2;\n      }\n   }\n   return ret;\n}\n\nTeleScopeData::PeriodicityType TeleScopeData::ts_periodicity()\n{\n   // TODO: for now, we only distinguish two types by comparing\n   // TODO: Also check per-packet constraint for periodicity\n\n   int ret = checkVectorSame(perPktProbs);\n   if (ret == 0) {\n      return REPEAT_ALL;\n   } else if (ret == 1) {\n      return REPEAT_FROM_SECOND;\n   } else {\n      return NO_PERIODICITY;\n   }\n}\n\nint TeleScopeData::ts_final(int cur_reg)\n{\n   assert(reg == cur_reg);\n   //LOG(LOG_MASK_TS, \"Telescoping state %d with reg=%d, smallThres=%d, real=%d\",\n   //    state->id, reg, smallThres, realThres);\n\n   // check if this state is telescopable\n   if (reg == smallThres) {\n      LOG(LOG_MASK_TS, \"state %d (cur_reg = smallThres = %d) \"\n          \"seems telescopable\", state->id, reg);\n      dump();\n\n      // infer the final prob result\n      double result = 0.0;\n      TeleScopeData::PeriodicityType ptype = ts_periodicity();\n\n      if (ptype == NO_PERIODICITY) {\n         LOG(LOG_MASK_TS, \"state %d turns out not telescopable\", state->id);\n      } else {\n         if (ptype == REPEAT_ALL) {\n            result = pow(perPktProbs[0], realThres);\n         } else if (ptype == REPEAT_FROM_SECOND) {\n            result = perPktProbs[0] * pow(perPktProbs[1], realThres-1);\n         }\n         LOG(LOG_MASK_TS, \"telescoping state %d inferred prob of reg==%d is %g\",\n             state->id, realThres, result);\n         finalResult += result;\n      }\n   } else {\n      //LOG(LOG_MASK_TS, \"state %d (cur_reg=%d smallThres=%d) \"\n      //    \"seems not telescopable\", state->id, cur_reg, smallThres);\n   }\n\n   return 0;\n}\n", "meta": {"hexsha": "28e6f733d816b25b575c8eac2557a139099cc607", "size": 6741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/Core/TeleScopeHandler.cpp", "max_stars_repo_name": "qiaokang92/P4wn", "max_stars_repo_head_hexsha": "cd2418de2dff238f67508898e3bfdf2aae1889a4", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-12-26T07:18:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:46:13.000Z", "max_issues_repo_path": "lib/Core/TeleScopeHandler.cpp", "max_issues_repo_name": "qiaokang92/P4wn", "max_issues_repo_head_hexsha": "cd2418de2dff238f67508898e3bfdf2aae1889a4", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T03:54:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T04:22:29.000Z", "max_forks_repo_path": "lib/Core/TeleScopeHandler.cpp", "max_forks_repo_name": "qiaokang92/P4wn", "max_forks_repo_head_hexsha": "cd2418de2dff238f67508898e3bfdf2aae1889a4", "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": 26.75, "max_line_length": 81, "alphanum_fraction": 0.6105919003, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.1999069973789492}}
{"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_PREDICATES_FUNCTIONS_SIMD_SSE_SSE2_IS_EQZ_HPP_INCLUDED\n#define BOOST_SIMD_PREDICATES_FUNCTIONS_SIMD_SSE_SSE2_IS_EQZ_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n#include <boost/simd/predicates/functions/is_eqz.hpp>\n#include <boost/simd/include/functions/simd/is_equal.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n#include <boost/simd/swar/functions/details/shuffle.hpp>\n#include <boost/dispatch/meta/downgrade.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( is_eqz_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_ < int64_<A0>\n                                              , boost::simd::tag::sse_\n                                              >\n                                      ))\n                                    )\n  {\n    typedef typename meta::as_logical<A0>::type result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      typedef typename dispatch::meta::downgrade<A0>::type          base;\n\n      const base tmp1 = boost::simd::bitwise_cast<base>(is_eqz(boost::simd::bitwise_cast<base>(a0)));\n      const base tmp2 = details::shuffle<1,0,3,2>(tmp1);\n      return boost::simd::bitwise_cast<result_type>(b_and(tmp1, tmp2));\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "c810834b6d372d17429e85c506476c688486df5e", "size": 1958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/predicates/functions/simd/sse/sse2/is_eqz.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/predicates/functions/simd/sse/sse2/is_eqz.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/predicates/functions/simd/sse/sse2/is_eqz.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": 42.5652173913, "max_line_length": 101, "alphanum_fraction": 0.5515832482, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.199853527169048}}
{"text": "/* methods.cpp */\n\n#include \"linalg.h\"\n#include \"methods.h\"\n#include \"structs.h\"\n\n#include <Python.h>\n#include <math.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n\nextern \"C\"\n{\n    void _ETS_IK(PyObject *ets, int n, double *q, double *Tep, double *ret)\n    {\n        // double E;\n        double *Te = (double *)PyMem_RawCalloc(16, sizeof(double));\n        double *e = (double *)PyMem_RawCalloc(6, sizeof(double));\n\n        double *a = (double *)PyMem_RawCalloc(6, sizeof(double));\n        // a[0] = 1.0;\n        // a[1] = 4.0;\n        // a[2] = 2.0;\n        // a[3] = 5.0;\n        // a[4] = 3.0;\n        // a[5] = 6.0;\n        a[0] = 1.0;\n        a[1] = 2.0;\n        a[2] = 3.0;\n        a[3] = 4.0;\n        a[4] = 5.0;\n        a[5] = 6.0;\n        double *b = (double *)PyMem_RawCalloc(12, sizeof(double));\n        b[0] = 11.0;\n        b[1] = 15.0;\n        b[2] = 19.0;\n        b[3] = 12.0;\n        b[4] = 16.0;\n        b[5] = 20.0;\n        b[6] = 13.0;\n        b[7] = 17.0;\n        b[8] = 21.0;\n        b[9] = 14.0;\n        b[10] = 18.0;\n        b[11] = 22.0;\n        // b[0] = 11.0;\n        // b[1] = 12.0;\n        // b[2] = 13.0;\n        // b[3] = 14.0;\n        // b[4] = 15.0;\n        // b[5] = 16.0;\n        // b[6] = 17.0;\n        // b[7] = 18.0;\n        // b[8] = 19.0;\n        // b[9] = 20.0;\n        // b[10] = 21.0;\n        // b[11] = 22.0;\n\n        // double *U = (double *)PyMem_RawCalloc(16, sizeof(double));\n        // double *invU = (double *)PyMem_RawCalloc(16, sizeof(double));\n        // double *temp = (double *)PyMem_RawCalloc(16, sizeof(double));\n        // double *ret = (double *)PyMem_RawCalloc(16, sizeof(double));\n        // Py_ssize_t m;\n        int arrived = 0, iter = 0;\n\n        while (arrived == 0 && iter < 500)\n        {\n            // Current pose Te\n            // _ETS_fkine(ets, q, (double *)NULL, NULL, Te);\n\n            // Angle axis error e\n            _angle_axis(Te, Tep, e);\n\n            // Squared error E\n            // E = 0.5 * e @ We @ e\n            // E = 0.5 * (e[0] * e[0] + e[1] * e[1] + e[2] * e[2] + e[3] * e[3] + e[4] * e[4] + e[5] * e[5]);\n        }\n\n        // _ETS_fkine(ets, q, (double *)NULL, NULL, Te);\n\n        // for (int i = 0; i < 2; i++)\n        // {\n        //     for (int j = 0; j < 4; j++)\n        //     {\n        //         ret[i * 4 + j] = 0.0;\n        //     }\n        // }\n\n        // _mult_T(2, 3, 0, a, 3, 4, 0, b, ret);\n        // _mult_T(3, 2, 1, a, 3, 4, 0, b, ret);\n        // _mult_T(3, 2, 1, a, 4, 3, 1, b, ret);\n        // _mult_T(2, 3, 0, a, 4, 3, 1, b, ret);\n\n        // int j = 0;\n    }\n\n    void _ETS_hessian(int n, MapMatrixJc &J, MapMatrixHr &H)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            for (int i = j; i < n; i++)\n            {\n                H.block<3, 1>(j * 6, i) = J.block<3, 1>(3, j).cross(J.block<3, 1>(0, i));\n                H.block<3, 1>(j * 6 + 3, i) = J.block<3, 1>(3, j).cross(J.block<3, 1>(3, i));\n\n                if (i != j)\n                {\n                    H.block<3, 1>(i * 6, j) = H.block<3, 1>(j * 6, i);\n                    H.block<3, 1>(i * 6 + 3, j) = Eigen::Vector3d::Zero();\n                }\n            }\n        }\n    }\n\n    void _ETS_jacob0(ETS *ets, double *q, double *tool, MapMatrixJc &eJ)\n    {\n        // ET *et;\n        // double T[16];\n        // MapMatrix4dc eT(T);\n        // Matrix4dc U;\n        // Matrix4dc invU;\n        // Matrix4dc temp;\n        // Matrix4dc ret;\n\n        // int j = 0;\n\n        // U = Eigen::Matrix4d::Identity();\n\n        // // Get the forward  kinematics into T\n        // _ETS_fkine(ets, q, (double *)NULL, tool, eT);\n\n        // for (int i = 0; i < ets->m; i++)\n        // {\n        //     et = ets->ets[i];\n\n        //     if (et->isjoint)\n        //     {\n        //         _ET_T(et, &ret(0), q[et->jindex]);\n        //         temp = U * ret;\n        //         U = temp;\n\n        //         if (i == ets->m - 1 && tool != NULL)\n        //         {\n        //             MapMatrix4dc e_tool(tool);\n        //             temp = U * e_tool;\n        //             U = temp;\n        //         }\n\n        //         _inv(&U(0), &invU(0));\n        //         temp = invU * eT;\n\n        //         if (et->axis == 0)\n        //         {\n        //             eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 2) * temp(1, 3) - U(Eigen::seq(0, 2), 1) * temp(2, 3);\n\n        //             eJ(Eigen::seq(3, 5), j) = U(Eigen::seq(0, 2), 0);\n        //         }\n        //         else if (et->axis == 1)\n        //         {\n        //             eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 0) * temp(2, 3) - U(Eigen::seq(0, 2), 2) * temp(0, 3);\n        //             eJ(Eigen::seq(3, 5), j) = U(Eigen::seq(0, 2), 1);\n        //         }\n        //         else if (et->axis == 2)\n        //         {\n        //             eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 1) * temp(0, 3) - U(Eigen::seq(0, 2), 0) * temp(1, 3);\n        //             eJ(Eigen::seq(3, 5), j) = U(Eigen::seq(0, 2), 2);\n        //         }\n        //         else if (et->axis == 3)\n        //         {\n        //             eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 0);\n        //             eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n        //         }\n        //         else if (et->axis == 4)\n        //         {\n        //             eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 1);\n        //             eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n        //         }\n        //         else if (et->axis == 5)\n        //         {\n        //             eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 2);\n        //             eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n        //         }\n        //         j++;\n        //     }\n        //     else\n        //     {\n        //         _ET_T(et, &ret(0), q[et->jindex]);\n        //         temp = U * ret;\n        //         U = temp;\n        //     }\n        // }\n\n        ET *et;\n        Eigen::Matrix<double, 6, Eigen::Dynamic> tJ(6, ets->n);\n        double T[16];\n        MapMatrix4dc eT(T);\n        Matrix4dc U = Eigen::Matrix4d::Identity();\n        Matrix4dc invU;\n        Matrix4dc temp;\n        Matrix4dc ret;\n        int j = ets->n - 1;\n\n        if (tool != NULL)\n        {\n            Matrix4dc e_tool(tool);\n            temp = e_tool * U;\n            U = temp;\n        }\n\n        for (int i = ets->m - 1; i >= 0; i--)\n        {\n            et = ets->ets[i];\n\n            if (et->isjoint)\n            {\n                if (et->axis == 0)\n                {\n                    tJ(Eigen::seq(0, 2), j) = U(2, Eigen::seq(0, 2)) * U(1, 3) - U(1, Eigen::seq(0, 2)) * U(2, 3);\n                    tJ(Eigen::seq(3, 5), j) = U(0, Eigen::seq(0, 2));\n                }\n                else if (et->axis == 1)\n                {\n                    tJ(Eigen::seq(0, 2), j) = U(0, Eigen::seq(0, 2)) * U(2, 3) - U(2, Eigen::seq(0, 2)) * U(0, 3);\n                    tJ(Eigen::seq(3, 5), j) = U(1, Eigen::seq(0, 2));\n                }\n                else if (et->axis == 2)\n                {\n                    tJ(Eigen::seq(0, 2), j) = U(1, Eigen::seq(0, 2)) * U(0, 3) - U(0, Eigen::seq(0, 2)) * U(1, 3);\n                    tJ(Eigen::seq(3, 5), j) = U(2, Eigen::seq(0, 2));\n                }\n                else if (et->axis == 3)\n                {\n                    tJ(Eigen::seq(0, 2), j) = U(0, Eigen::seq(0, 2));\n                    tJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n                }\n                else if (et->axis == 4)\n                {\n                    tJ(Eigen::seq(0, 2), j) = U(1, Eigen::seq(0, 2));\n                    tJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n                }\n                else if (et->axis == 5)\n                {\n                    tJ(Eigen::seq(0, 2), j) = U(2, Eigen::seq(0, 2));\n                    tJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n                }\n\n                _ET_T(et, &ret(0), q[et->jindex]);\n                temp = ret * U;\n                U = temp;\n                j--;\n            }\n            else\n            {\n                _ET_T(et, &ret(0), q[et->jindex]);\n                temp = ret * U;\n                U = temp;\n            }\n        }\n\n        Eigen::Matrix<double, 6, 6> ev;\n        ev.topLeftCorner<3, 3>() = U.topLeftCorner<3, 3>();\n        ev.topRightCorner<3, 3>() = Eigen::Matrix3d::Zero();\n        ev.bottomLeftCorner<3, 3>() = Eigen::Matrix3d::Zero();\n        ev.bottomRightCorner<3, 3>() = U.topLeftCorner<3, 3>();\n        eJ = ev * tJ;\n    }\n\n    void _ETS_jacobe(ETS *ets, double *q, double *tool, MapMatrixJc &eJ)\n    {\n        ET *et;\n        double T[16];\n        MapMatrix4dc eT(T);\n        Matrix4dc U = Eigen::Matrix4d::Identity();\n        Matrix4dc invU;\n        Matrix4dc temp;\n        Matrix4dc ret;\n        int j = ets->n - 1;\n\n        if (tool != NULL)\n        {\n            Matrix4dc e_tool(tool);\n            temp = e_tool * U;\n            U = temp;\n        }\n\n        for (int i = ets->m - 1; i >= 0; i--)\n        {\n            et = ets->ets[i];\n\n            if (et->isjoint)\n            {\n                if (et->axis == 0)\n                {\n                    eJ(Eigen::seq(0, 2), j) = U(2, Eigen::seq(0, 2)) * U(1, 3) - U(1, Eigen::seq(0, 2)) * U(2, 3);\n                    eJ(Eigen::seq(3, 5), j) = U(0, Eigen::seq(0, 2));\n                }\n                else if (et->axis == 1)\n                {\n                    eJ(Eigen::seq(0, 2), j) = U(0, Eigen::seq(0, 2)) * U(2, 3) - U(2, Eigen::seq(0, 2)) * U(0, 3);\n                    eJ(Eigen::seq(3, 5), j) = U(1, Eigen::seq(0, 2));\n                }\n                else if (et->axis == 2)\n                {\n                    eJ(Eigen::seq(0, 2), j) = U(1, Eigen::seq(0, 2)) * U(0, 3) - U(0, Eigen::seq(0, 2)) * U(1, 3);\n                    eJ(Eigen::seq(3, 5), j) = U(2, Eigen::seq(0, 2));\n                }\n                else if (et->axis == 3)\n                {\n                    eJ(Eigen::seq(0, 2), j) = U(0, Eigen::seq(0, 2));\n                    eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n                }\n                else if (et->axis == 4)\n                {\n                    eJ(Eigen::seq(0, 2), j) = U(1, Eigen::seq(0, 2));\n                    eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n                }\n                else if (et->axis == 5)\n                {\n                    eJ(Eigen::seq(0, 2), j) = U(2, Eigen::seq(0, 2));\n                    eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n                }\n\n                _ET_T(et, &ret(0), q[et->jindex]);\n                temp = ret * U;\n                U = temp;\n                j--;\n            }\n            else\n            {\n                _ET_T(et, &ret(0), q[et->jindex]);\n                temp = ret * U;\n                U = temp;\n            }\n        }\n    }\n\n    void _ETS_fkine(ETS *ets, double *q, double *base, double *tool, MapMatrix4dc &e_ret)\n    {\n        ET *et;\n        Matrix4dc temp;\n        Matrix4dc current;\n\n        if (base != NULL)\n        {\n            MapMatrix4dc e_base(base);\n            current = e_base;\n        }\n        else\n        {\n            current = Eigen::Matrix4d::Identity();\n        }\n\n        for (int i = 0; i < ets->m; i++)\n        {\n            et = ets->ets[i];\n\n            _ET_T(et, &e_ret(0), q[et->jindex]);\n            temp = current * e_ret;\n            current = temp;\n        }\n\n        if (tool != NULL)\n        {\n            MapMatrix4dc e_tool(tool);\n            e_ret = current * e_tool;\n        }\n        else\n        {\n            e_ret = current;\n        }\n    }\n\n    void _ET_T(ET *et, double *ret, double eta)\n    {\n        // Check if static and return static transform\n        if (!et->isjoint)\n        {\n            _copy(et->T, ret);\n            return;\n        }\n\n        if (et->isflip)\n        {\n            eta = -eta;\n        }\n\n        // Calculate ET trasform based on eta\n        et->op(ret, eta);\n    }\n\n} /* extern \"C\" */", "meta": {"hexsha": "0d9b8d0ac106b747241d41383ab500c9fcae6e17", "size": 11994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "roboticstoolbox/core/methods.cpp", "max_stars_repo_name": "Russ76/robotics-toolbox-python", "max_stars_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "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": "roboticstoolbox/core/methods.cpp", "max_issues_repo_name": "Russ76/robotics-toolbox-python", "max_issues_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "roboticstoolbox/core/methods.cpp", "max_forks_repo_name": "Russ76/robotics-toolbox-python", "max_forks_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_forks_repo_licenses": ["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.5969387755, "max_line_length": 123, "alphanum_fraction": 0.3490078373, "num_tokens": 4130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.19985351043313856}}
{"text": "#include <bits/stdc++.h>\n#include <gflags/gflags.h>\n#include <sol.hpp>\n#include <TH/THTensor.h>\n#include \"objects_detection_lib.hpp\"\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <boost/filesystem.hpp>\n#include <boost/gil/gil_all.hpp>\n\n#include <sys/stat.h>\n\nusing namespace boost::filesystem;\nusing namespace cv;\nusing namespace std;\n\nDEFINE_string(config, \"\", \"configuration\");\nDEFINE_string(model, \"\", \"model\");\nDEFINE_string(input, \"\", \"input\");\nDEFINE_string(output, \"\", \"output\");\nDEFINE_int32(realtime, 1, \"realtime\");\nDEFINE_int32(batchSize, 8, \"batch size\");\nDEFINE_int32(width, 640, \"width\");\nDEFINE_int32(height, 480, \"height\");\nDEFINE_double(threshold, 0.5, \"threshold\");\nint main(int argc, char* argv[]) {\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  \n  // Initialize torch and load model\n  sol::state lua;\n  lua.open_libraries();\n\n  lua.script(\"require 'torch'; require 'cunn'; require 'cudnn'; require 'image';\");\n  lua.script(\"torch.setdefaulttensortype('torch.FloatTensor');\");\n  //lua.script(\"cudnn.benchmark = true;\");\n  lua.script(\"cudnn.fastest = true;\");\n\n  lua.script(\"m = torch.load('\" + FLAGS_model + \"'):cuda();\");\n  lua.script(\"m:evaluate();\");\n\n  stringstream ss; ss << \"input = torch.FloatTensor(\" << FLAGS_batchSize << \", 3, 224, 224);\";\n  lua.script(ss.str());\n\n  THFloatTensor *input = lua[\"input\"];\n  float *data = input->storage->data;\n\n  // warm up\n  auto start = chrono::high_resolution_clock::now();\n  for (int i=0; i < 100; i++) {\n    lua.script(\"result = m:forward(input:cuda()):float();\");\n  }\n\n  // Initialize region proposal \n  objects_detection::init_objects_detection(FLAGS_config, false /*use_ground_plane*/, false /*use_stixels*/);\n\n  // Set up input and start \n  VideoCapture cap;\n  deque<path> files;\n  map<double, string> timestamped_files;\n  if (FLAGS_input == \"\") {\n    cap.open(1);\n    cap.set(CV_CAP_PROP_FRAME_WIDTH, FLAGS_width);\n    cap.set(CV_CAP_PROP_FRAME_HEIGHT, FLAGS_height);\n  } else {\n    path p(FLAGS_input);\n    assert(exists(p));\n    if (is_regular_file(p)) {\n      files.push_back(p);\n    } else {\n      path log = p / \"log.txt\";\n      if (FLAGS_realtime && exists(log)) {\n        ifstream in(log.string(), fstream::in);\n        int frame; double time;\n        while(in >> frame >> time) {\n          stringstream ss; ss << setw(4) << setfill('0') << frame+1 << \".png\";\n          timestamped_files[time] = FLAGS_input + \"/\" + ss.str();\n        }\n      } else {\n        FLAGS_realtime = 0;\n        copy(directory_iterator(p), directory_iterator(), back_inserter(files));\n        sort(files.begin(), files.end());\n      }\n    }\n  }\n    \n  VideoWriter outputVideo, proposalVideo;\n  if (FLAGS_output == \"\") {\n    namedWindow(\"Proposals\");\n    namedWindow(\"Output\");\n  } else {\n    mkdir(FLAGS_output.c_str(), 0777);\n    outputVideo.open((path(FLAGS_output) / \"output.avi\").string(), CV_FOURCC('M', 'J', 'P', 'G'), 30, Size(FLAGS_width, FLAGS_height));\n    proposalVideo.open((path(FLAGS_output) / \"proposal.avi\").string(), CV_FOURCC('M', 'J', 'P', 'G'), 30, Size(FLAGS_width, FLAGS_height));\n  }\n\n  double cur_timestamp = 0;\n  double video_timestamp = 0;\n  int num_proposals = 0;\n  int num_frames = 0;\n  while(true) {\n    path filename;\n    double timestamp;\n    Mat image; \n    if (FLAGS_input == \"\") {\n      timestamp = 0;\n      cap >> image;\n    } else if (timestamped_files.size() > 0) {\n      timestamp = cur_timestamp;\n      auto it = --timestamped_files.upper_bound(timestamp);\n      filename = it->second;\n      cout << filename << endl;\n      image = imread(filename.string(), CV_LOAD_IMAGE_COLOR);\n      if (++it == timestamped_files.end()) timestamped_files.clear();\n    } else {\n      if (files.empty()) break;\n      timestamp = timestamp + 1/30.;\n      filename = files.front();\n      image = imread(filename.string(), CV_LOAD_IMAGE_COLOR);\n      files.pop_front(); \n    }\n    if (image.rows != FLAGS_height || image.cols != FLAGS_width) {\n      resize(image, image, Size(FLAGS_width, FLAGS_height));\n    }\n\n    cout << timestamp << \" processing \" << filename << endl;\n    num_frames++;\n    auto start = chrono::high_resolution_clock::now();\n\n    objects_detection::input_image_const_view_t input_view =\n      boost::gil::interleaved_view(image.cols, image.rows,\n        reinterpret_cast<boost::gil::rgb8c_pixel_t*>(image.data), static_cast<size_t>(image.step));\n\n    objects_detection::set_monocular_image(input_view);\n    objects_detection::compute();\n\n    std::vector<doppia::Detection2d> detections = objects_detection::get_detections();\n    cout << detections.size() << \" regions detected.\" << endl;\n    num_proposals += detections.size();\n    \n    Mat proposals = image.clone();\n  \n    int detected = 0;\n    for (int i = 0; i < detections.size(); i += FLAGS_batchSize) {\n      vector<Rect> bboxes;\n      for (int j = 0, e = min(FLAGS_batchSize, (int)detections.size()-i); j < e; j++) {\n        auto d = detections[i+j];\n        int l = max(0, (int)d.bounding_box.min_corner().x()), t = max(0, (int)d.bounding_box.min_corner().y());\n        Rect r(l, t, min(FLAGS_width-1, (int)d.bounding_box.max_corner().x()) - l + 1, min(FLAGS_height-1, (int)d.bounding_box.max_corner().y()) - t + 1);\n        rectangle(proposals, r, Scalar(0, 0, 255));\n        bboxes.push_back(r);\n\n        Mat patch;\n        image(r).convertTo(patch, CV_32FC3, 1/255.0);\n        resize(patch, patch, Size(224, 224));\n\n        float *D = (float*)patch.data;\n        int step = 3*patch.cols;\n        for (int r = 0, R = patch.rows; r < R; r++) {\n          for (int c = 0, C = patch.cols; c < C; c++) {\n            data[j*3*224*224 +             r*224 + c] = (D[step*r + 3*c+2] - 0.485) / 0.229;\n            data[j*3*224*224 +   224*224 + r*224 + c] = (D[step*r + 3*c+1] - 0.456) / 0.224;\n            data[j*3*224*224 + 2*224*224 + r*224 + c] = (D[step*r + 3*c] - 0.406) / 0.225;\n          }\n        }\n      }\n\n      lua.script(\"result = m:forward(input:cuda()):float();\");\n      THFloatTensor *result = lua[\"result\"];\n      for (int j = 0, e = min(FLAGS_batchSize, (int)detections.size()-i); j < e; j++) {\n        float neg = exp(result->storage->data[j*2]), pos = exp(result->storage->data[j*2+1]);\n        float p = pos / (pos + neg);\n        if (p >= FLAGS_threshold) {\n          detected++;\n          rectangle(image, bboxes[j], Scalar(0, 0, 255 * p));\n        }\n      }\n    }\n    cout << detected << \" pedestrians detected.\" << endl;\n\n    auto elapsed = chrono::duration<double>(chrono::high_resolution_clock::now() - start).count();\n    cur_timestamp = cur_timestamp + elapsed;\n\n    if (FLAGS_output == \"\") {\n      imshow(\"Proposals\", proposals);\n      imshow(\"Output\", image);\n      waitKey(1);\n    } else {\n      do {\n        outputVideo << image;\n        proposalVideo << proposals;\n        video_timestamp += 1/30.;        \n      } while (FLAGS_realtime && video_timestamp < cur_timestamp);\n    }\n  }\n  cout << \"Done! Time/frame: \" << cur_timestamp * 1000 / num_frames << \"ms. #Proposals/frame: \" << num_proposals * 1.0 / num_frames << endl;\n  if (FLAGS_output == \"\") waitKey(0);\n  return 0;\n}\n", "meta": {"hexsha": "84d575864cac25c6b44c5e2a22c14d899286539f", "size": 7141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tx1/forward.cpp", "max_stars_repo_name": "noranart/Pedestrian-Detection-in-TX1", "max_stars_repo_head_hexsha": "7c31c38338fa9d01db25690e30d04ae9bd6a2f74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-27T19:11:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T13:46:58.000Z", "max_issues_repo_path": "tx1/forward.cpp", "max_issues_repo_name": "noranart/Pedestrian-Detection-in-TX1", "max_issues_repo_head_hexsha": "7c31c38338fa9d01db25690e30d04ae9bd6a2f74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tx1/forward.cpp", "max_forks_repo_name": "noranart/Pedestrian-Detection-in-TX1", "max_forks_repo_head_hexsha": "7c31c38338fa9d01db25690e30d04ae9bd6a2f74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-06-26T23:32:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-04T01:14:14.000Z", "avg_line_length": 35.3514851485, "max_line_length": 154, "alphanum_fraction": 0.6095784904, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.19969821234659385}}
{"text": "#include <FpCoreTest.h>\n#include <boost/shared_ptr.hpp>\n#include <gtest/gtest.h>\n#include <fruitpunch/Resources/Raw.h>\n#include <fruitpunch/Physics/PhysicsBox.h>\n\nusing namespace std;\nusing namespace boost;\nusing namespace fp_core::physics;\n\n// ---------------------------------------------------------------------------\n// Test Class\n// ---------------------------------------------------------------------------\n\nclass PhysicsBoxTest : public FpCoreTest {\nprotected:\n  string mPath;\n\n  virtual void SetUp() {\n\tinitEnvironment();\n  }\n};\n\nTEST_F(PhysicsBoxTest, Constructor) {\n\tPhysicsBox box(300,400);\n\tboost::shared_ptr<b2PolygonShape> shape = static_pointer_cast<b2PolygonShape>(box.getBox2dShape(1.0f));\n\tASSERT_EQ(4, shape->GetVertexCount());\n\tASSERT_EQ(300, shape->GetVertex(1).x - shape->GetVertex(0).x);\n\tASSERT_EQ(400, shape->GetVertex(2).y - shape->GetVertex(0).y);\n}\n", "meta": {"hexsha": "6b25a54bba1ac8249271461c93859e47253eedd2", "size": 878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fp_core/src/test/src/Physics/PhysicsBox.cpp", "max_stars_repo_name": "submain/fruitpunch", "max_stars_repo_head_hexsha": "31773128238830d3d335c1915877dc0db56836cd", "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": "fp_core/src/test/src/Physics/PhysicsBox.cpp", "max_issues_repo_name": "submain/fruitpunch", "max_issues_repo_head_hexsha": "31773128238830d3d335c1915877dc0db56836cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fp_core/src/test/src/Physics/PhysicsBox.cpp", "max_forks_repo_name": "submain/fruitpunch", "max_forks_repo_head_hexsha": "31773128238830d3d335c1915877dc0db56836cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-14T02:51:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-14T02:51:47.000Z", "avg_line_length": 28.3225806452, "max_line_length": 104, "alphanum_fraction": 0.6127562642, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562748}}
{"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\u00e4nkt), 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_POW_INCLUDE\n#define MTL_POW_INCLUDE\n\n#include <boost/numeric/mtl/vector/map_view.hpp>\n\nnamespace mtl {\n    \n    namespace vec {\n\n        /// Raise Vector \\a v to power \\a exp\n        template <typename Vector, typename Exponent>\n        pow_by_view<Vector, Exponent> pow(const Vector& v, const Exponent& exp)\n        {\n            return pow_by_view<Vector, Exponent>(v, exp);\n        }\n        \n    } // namespace vec\n\n} // namespace mtl\n\n#endif // MTL_POW_INCLUDE\n", "meta": {"hexsha": "4fd672ba7ccbb7c2de4c1a1977c934d68d1eb8a4", "size": 924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/pow.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/pow.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/pow.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": 27.1764705882, "max_line_length": 94, "alphanum_fraction": 0.6645021645, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.19958119293562748}}
{"text": "#ifndef KGRAPH_VALUE_TYPE\n#define KGRAPH_VALUE_TYPE float\n#endif\n\n\n#include <cctype>\n#include <type_traits>\n#include <iostream>\n#include <boost/timer/timer.hpp>\n#include <boost/program_options.hpp>\n#include <sys/time.h>\n#include <cctype>\n#include <random>\n#include <iomanip>\n#include <type_traits>\n#include <boost/timer/timer.hpp>\n#include <boost/tr1/random.hpp>\n#include <boost/format.hpp>\n#include <boost/program_options.hpp>\n\n#include \"kgraph.h\"\n#include \"kgraph-data.h\"\n\nusing namespace boost::timer;\nusing namespace std;\nusing namespace boost;\nusing namespace kgraph;\nnamespace po = boost::program_options; \n\n\ntypedef KGRAPH_VALUE_TYPE value_type;\n\nint main(int argc, char *argv[]) {\n    string data_path;\n    string output_path;\n    KGraph::IndexParams params;\n    unsigned D;\n    unsigned skip;\n    unsigned gap;\n    unsigned synthetic;\n    float noise;\n\n    bool lshkit = true;\n\n    po::options_description desc_visible(\"General options\");\n    desc_visible.add_options()\n    (\"help,h\", \"produce help message.\")\n    (\"version,v\", \"print version information.\")\n    (\"data\", po::value(&data_path), \"input path\")\n    (\"output\", po::value(&output_path), \"output path\")\n    (\",K\", po::value(&params.K)->default_value(default_K), \"number of nearest neighbor\")\n    (\"controls,C\", po::value(&params.controls)->default_value(default_controls), \"number of control pounsigneds\")\n    ;\n\n    po::options_description desc_hidden(\"Expert options\");\n    desc_hidden.add_options()\n    (\"iterations,I\", po::value(&params.iterations)->default_value(default_iterations), \"\")\n    (\",S\", po::value(&params.S)->default_value(default_S), \"\")\n    (\",R\", po::value(&params.R)->default_value(default_R), \"\")\n    (\",L\", po::value(&params.L)->default_value(default_L), \"\")\n    (\"delta\", po::value(&params.delta)->default_value(default_delta), \"\")\n    (\"recall\", po::value(&params.recall)->default_value(default_recall), \"\")\n    (\"prune\", po::value(&params.prune)->default_value(default_prune), \"\")\n    (\"noise\", po::value(&noise)->default_value(0), \"noise\")\n    (\"seed\", po::value(&params.seed)->default_value(default_seed), \"\")\n    (\"dim,D\", po::value(&D), \"dimension, see format\")\n    (\"skip\", po::value(&skip)->default_value(0), \"see format\")\n    (\"gap\", po::value(&gap)->default_value(0), \"see format\")\n    (\"raw\", \"read raw binary file, need to specify D.\")\n    (\"synthetic\", po::value(&synthetic)->default_value(0), \"generate synthetic data, for performance evaluation only, specify number of points\")\n    ;\n\n    po::options_description desc(\"Allowed options\");\n    desc.add(desc_visible).add(desc_hidden);\n\n    po::positional_options_description p;\n    p.add(\"data\", 1);\n    p.add(\"output\", 1);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n    po::notify(vm);\n\n    if (vm.count(\"raw\") == 1) {\n        lshkit = false;\n    }\n\n    if (vm.count(\"version\")) {\n        cout << \"KGraph version \" << KGraph::version() << endl;\n        return 0;\n    }\n\n    if (vm.count(\"help\")\n            || (synthetic && (vm.count(\"dim\") == 0 || vm.count(\"data\")))\n            || (!synthetic && (vm.count(\"data\") == 0 || (vm.count(\"dim\") == 0 && !lshkit)))) {\n        cout << \"Usage: index [OTHER OPTIONS]... INPUT [OUTPUT]\" << endl;\n        cout << desc_visible << endl;\n        cout << desc_hidden << endl;\n        return 0;\n    }\n\n    if (params.S == 0) {\n        params.S = params.K;\n    }\n\n    if (lshkit && (synthetic == 0)) {   // read dimension information from the data file\n        static const unsigned LSHKIT_HEADER = 3;\n        ifstream is(data_path.c_str(), ios::binary);\n        unsigned header[LSHKIT_HEADER]; /* entry size, row, col */\n        is.read((char *)header, sizeof header);\n        BOOST_VERIFY(is);\n        BOOST_VERIFY(header[0] == sizeof(value_type));\n        is.close();\n        D = header[2];\n        skip = LSHKIT_HEADER * sizeof(unsigned);\n        gap = 0;\n    }\n\n    Matrix<value_type> data;\n    if (synthetic) {\n        if (!std::is_floating_point<value_type>::value) {\n            throw runtime_error(\"synthetic data not implemented for non-floating-point values.\");\n        }\n        data.resize(synthetic, D);\n        cerr << \"Generating synthetic data...\" << endl;\n        default_random_engine rng(params.seed);\n        uniform_real_distribution<double> distribution(-1.0, 1.0);\n        data.zero(); // important to do that\n        for (unsigned i = 0; i < synthetic; ++i) {\n            value_type *row = data[i];\n            for (unsigned j = 0; j < D; ++j) {\n                row[j] = distribution(rng);\n            }\n        }\n    }\n    else {\n        data.load(data_path, D, skip, gap);\n    }\n    if (noise != 0) {\n        if (!std::is_floating_point<value_type>::value) {\n            throw runtime_error(\"noise injection not implemented for non-floating-point value.\");\n        }\n        tr1::ranlux64_base_01 rng;\n        double sum = 0, sum2 = 0;\n        for (unsigned i = 0; i < data.size(); ++i) {\n            for (unsigned j = 0; j < data.dim(); ++j) {\n                value_type v = data[i][j];\n                sum += v;\n                sum2 += v * v;\n            }\n        }\n        double total = double(data.size()) * data.dim();\n        double avg2 = sum2 / total, avg = sum / total;\n        double dev = sqrt(avg2 - avg * avg);\n        cerr << \"Adding Gaussian noise w/ \" << noise << \"x sigma(\" << dev << \")...\" << endl;\n        boost::normal_distribution<double> gaussian(0, noise * dev);\n        for (unsigned i = 0; i < data.size(); ++i) {\n            for (unsigned j = 0; j < data.dim(); ++j) {\n                data[i][j] += gaussian(rng);\n            }\n        }\n    }\n\n    MatrixOracle<value_type, metric::l2sqr> oracle(data);\n    KGraph::IndexInfo info;\n    KGraph *kgraph = KGraph::create(); //(oracle, params, &info);\n    {\n        auto_cpu_timer timer;\n        kgraph->build(oracle, params, output_path.c_str(), &info);\n        cerr << info.stop_condition << endl;\n    }\n\n    if (output_path.size()) {\n     \n      //Note that we modify the index save procedure to reduce index size    \n      //kgraph->save(output_path.c_str());\n    }\n\n  \n    \n    delete kgraph;\n\n    return 0;\n}\n", "meta": {"hexsha": "a984deab85ce581a40c3e9e17583974a960205e4", "size": 6180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algorithms/KGraph/src/kgraph_index.cpp", "max_stars_repo_name": "sourabhpoddar404/nns_benchmark", "max_stars_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 150.0, "max_stars_repo_stars_event_min_datetime": "2016-06-03T16:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T05:32:56.000Z", "max_issues_repo_path": "algorithms/KGraph/src/kgraph_index.cpp", "max_issues_repo_name": "sourabhpoddar404/nns_benchmark", "max_issues_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-06-03T13:43:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T07:42:02.000Z", "max_forks_repo_path": "algorithms/KGraph/src/kgraph_index.cpp", "max_forks_repo_name": "sourabhpoddar404/nns_benchmark", "max_forks_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2016-05-18T05:53:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T19:57:52.000Z", "avg_line_length": 33.4054054054, "max_line_length": 144, "alphanum_fraction": 0.5920711974, "num_tokens": 1564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"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#include \"graph.hh\"\n#include \"graph_filtering.hh\"\n\n#include <boost/graph/isomorphism.hpp>\n\nusing namespace graph_tool;\nusing namespace boost;\n\nstruct check_iso\n{\n\n    template <class Graph1, class Graph2, class IsoMap, class InvMap,\n              class VertexIndexMap>\n    void operator()(Graph1& g1, Graph2* g2, InvMap cinv_map1, InvMap cinv_map2,\n                    int64_t max_inv, IsoMap map, VertexIndexMap index1,\n                    VertexIndexMap index2, bool& result) const\n    {\n        auto inv_map1 = cinv_map1.get_unchecked(num_vertices(g1));\n        auto inv_map2 = cinv_map2.get_unchecked(num_vertices(*g2));\n\n        vinv_t<decltype(inv_map1)> vinv1(inv_map1, max_inv);\n        vinv_t<decltype(inv_map2)> vinv2(inv_map2, max_inv);\n\n        result = isomorphism(g1, *g2,\n                             isomorphism_map(map.get_unchecked(num_vertices(g1))).\n                             vertex_invariant1(vinv1).\n                             vertex_invariant2(vinv2).\n                             vertex_index1_map(index1).\n                             vertex_index2_map(index2));\n    }\n\n    template <class Prop>\n    struct vinv_t\n    {\n        vinv_t(Prop& prop, int64_t max)\n            : _prop(prop), _max(max) {}\n        Prop& _prop;\n        int64_t _max;\n\n        template <class Vertex>\n        int64_t operator()(Vertex v) const\n        {\n            return _prop[v];\n        };\n\n        int64_t max() const { return _max; }\n\n        typedef int64_t result_type;\n        typedef size_t argument_type;\n    };\n};\n\nstruct directed_graph_view_pointers:\n    mpl::transform<graph_tool::detail::always_directed,\n                   mpl::quote1<std::add_pointer> >::type {};\n\nstruct undirected_graph_view_pointers:\n    mpl::transform<graph_tool::detail::never_directed,\n                   mpl::quote1<std::add_pointer> >::type {};\n\ntypedef property_map_types::apply<integer_types,\n                                  GraphInterface::vertex_index_map_t,\n                                  mpl::bool_<false> >::type\n    vertex_props_t;\n\nbool check_isomorphism(GraphInterface& gi1, GraphInterface& gi2,\n                       boost::any ainv_map1, boost::any ainv_map2,\n                       int64_t max_inv, boost::any aiso_map)\n{\n    bool result;\n\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        iso_map_t;\n    auto iso_map = any_cast<iso_map_t>(aiso_map);\n\n    typedef property_map_type::apply<int64_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        inv_map_t;\n    auto inv_map1 = any_cast<inv_map_t>(ainv_map1);\n    auto inv_map2 = any_cast<inv_map_t>(ainv_map2);\n\n    if (gi1.GetDirected() != gi2.GetDirected())\n        return false;\n    if (gi1.GetDirected())\n    {\n        run_action<graph_tool::detail::always_directed>()\n            (gi1, std::bind(check_iso(),\n                            placeholders::_1, placeholders::_2,\n                            inv_map1, inv_map2, max_inv, iso_map,\n                            gi1.GetVertexIndex(),\n                            gi2.GetVertexIndex(), std::ref(result)),\n             directed_graph_view_pointers())\n            (gi2.GetGraphView());\n    }\n    else\n    {\n        run_action<graph_tool::detail::never_directed>()\n            (gi1, std::bind(check_iso(),\n                            placeholders::_1, placeholders::_2,\n                            inv_map1, inv_map2, max_inv, iso_map,\n                            gi1.GetVertexIndex(),\n                            gi2.GetVertexIndex(), std::ref(result)),\n             undirected_graph_view_pointers())\n            (gi2.GetGraphView());\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "4412be9a632088941bd67d475e6c60195e83aa06", "size": 4497, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/topology/graph_isomorphism.cc", "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/topology/graph_isomorphism.cc", "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/topology/graph_isomorphism.cc", "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": 35.4094488189, "max_line_length": 82, "alphanum_fraction": 0.5981765622, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"svm_test_input.hpp\"\n#include \"../src/svm_impl/classifiers_generator.h\"\n#include \"../src/svm_impl/regressions_generator.h\"\n#include \"../src/svm_impl/regression_params.hpp\"\n#include \"../src/svm_impl/classifier_params.hpp\"\n#include \"../src/svm_impl/svm_model.h\"\n#include <limits>\n#include <stdexcept>\n#include <iostream>\n\nnamespace \n{\n\nconst mlmodels::class_data labels = { 0, 0, 1, 1, 0, 2, 1, 2, 1, 0 };\n\nconst mlmodels::training_data dataf = make_multi_array<mlmodels::value_type, 10, 2>(\n        { { 100.f, 10.f }, \n          { 150.f, 10.f }, \n          { 600.f, 200.f }, \n          { 600.f, 10.f }, \n          { 10.f, 100.f }, \n          { 455.f, 10.f }, \n          { 345.f, 255.f }, \n          { 10.f, 501.f }, \n          { 401.f, 255.f }, \n          { 30.f, 150.f } \n        }\n);\n\n}   // end of namespace\n\nBOOST_AUTO_TEST_CASE(test_invalid_data_for_model)\n{\n    using namespace mlmodels;\n    auto model = svm::classifier::create_model(svm::classifier::c_rbf_train{}, \n                        training_data{}, class_data{}\n            );\n    BOOST_TEST((model.get() == nullptr), \"we are expecting to fail in model generation as we have invalid data for the model\");\n    // while it should be the same - test for regression type as well\n    model = svm::regression::create_model(svm::regression::epsilon_linear_train{},\n                            training_data{}, class_data{}\n            );\n    BOOST_TEST((model.get() == nullptr), \"we are expecting to fail in model generation as we have invalid data for the model\");\n}\n\nBOOST_AUTO_TEST_CASE(test_train_model)\n{\n    using namespace mlmodels;\n    try {\n        auto model = svm::classifier::create_model(svm::classifier::nu_poly_train{}, train_data, train_labels);\n        BOOST_TEST((model.get() != nullptr), \"we are expecting to successfully pass training with this - if not then we have an anexpected issue here\");\n    } catch (const std::exception& e) {\n        BOOST_TEST(false, \"failed to create model: \"<<e.what());\n    } catch (...) {\n        BOOST_TEST(false, \"unexpted failure in generating the model\");\n    }\n\n    // now lets try to do the same for regression\n    try {\n//        std::cout<<\"start training on epsilon_rbf_train\"<<std::endl;\n        auto model = svm::regression::create_model(svm::regression::epsilon_rbf_train{}, dataf, labels);\n //       std::cout<<\"finish\"<<std::endl;\n        BOOST_TEST((model.get() != nullptr), \"we are expecting to successfully pass training with this - if not then we have an anexpected issue here\");\n    } catch (const std::exception& e) {\n        BOOST_TEST(false, \"failed to create model: \"<<e.what());\n    } catch (...) {\n        BOOST_TEST(false, \"unexpted failure in generating the model\");\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_invalid_prediction)\n{\n    using namespace mlmodels;\n    // create invalid model\n    auto model = svm::classifier::create_model(svm::classifier::nu_linear_train{}, \n                        training_data{}, class_data{}\n            );\n    BOOST_TEST_REQUIRE((model.get() == nullptr), \"we are expecting to fail in model generation as we have invalid data for the model\");\n    auto ret = svm::predict(model, labels);\n    BOOST_TEST(ret == std::numeric_limits<value_type>::max());\n    auto ret2 = svm::test(model, dataf);\n    BOOST_TEST(ret2.empty());\n    model = svm::regression::create_model(svm::regression::epsilon_sig_train{},\n                            training_data{}, class_data{}\n            );\n    BOOST_TEST((model.get() == nullptr), \"we are expecting to fail in model generation as we have invalid data for the model\");\n    ret = svm::predict(model, labels);\n    BOOST_TEST(ret == std::numeric_limits<value_type>::max());\n    ret2 = svm::test(model, dataf);\n    BOOST_TEST(ret2.empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_invalid_model_train_args)\n{\n    using namespace mlmodels;\n    // by passing labels and data with the a different number of elements\n    // want to see if this is not accepted\n    try {\n        auto model = svm::regression::create_model(svm::regression::nu_sig_train{}, dataf, train_labels);\n        BOOST_TEST((model.get() == nullptr), \"we should get invalid model with these values\");\n    } catch (const std::exception&) {\n        BOOST_TEST(false, \"we should get an empty model\");\n    } catch (...) {\n        BOOST_TEST(false, \"we should not get a starndard exception, got some other exception\");\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_invalid_prediction_data_for_model)\n{\n    using namespace mlmodels;\n    // make sure that if we are passing wrong number of features we would fail to predict\n    try {\n        auto model = svm::classifier::create_model(svm::classifier::c_linear_train{}, train_data, train_labels);\n        BOOST_TEST_REQUIRE((model.get() != nullptr), \"failed to train the model!!\");\n        // now try to run prediction and test, and see that it would fail since we are passing the wrong number of features\n        auto ret = svm::test(model, dataf);\n        BOOST_TEST(ret.empty(), \"the args to the model test is wrong - wrong number of features, should return empty\"); \n        auto ret2 = svm::predict(model, labels);\n        BOOST_TEST((ret2 == std::numeric_limits<value_type>::max()), \"the args to predict are wrong, we pass the wrong number of features\");\n    } catch (...) {\n        BOOST_TEST(false, \"we should not get any exception here\");\n    }\n}\nBOOST_AUTO_TEST_CASE(test_prediction_is_valid_return_value)\n{\n    using namespace mlmodels;\n    // do the same for regression model\n    try {\n        //auto model = svm::regression::create_model(svm::regression::epsilon_linear_train{}, dataf, labels);\n        auto model = svm::classifier::create_model(svm::classifier::c_linear_train{}, dataf, labels);\n        BOOST_TEST_REQUIRE((model.get() != nullptr), \"failed to train the model!!\");\n        // pass a row of valid size for prediction\n        const class_data row{11.f, 110.f};\n        auto ret = svm::test(model, dataf);\n        BOOST_TEST(not ret.empty(), \"the args to the model test is  - good, should not return empty\"); \n        auto ret2 = svm::predict(model, row);\n        BOOST_TEST((ret2 != std::numeric_limits<value_type>::max()), \"the args to predict are good, we pass good number of features\");\n    } catch (...) {\n        BOOST_TEST(false, \"we should not get any exception here\");\n    }\n    return;\n    // in this test we would make sure that if we are passing a valid arguments we are getting\n    // valid results - by valid it means that they are not out of bound, but we are not checking \n    // if this is a correct prediction mathematically\n    try {\n        auto model = svm::classifier::create_model(svm::classifier::c_linear_train{}, train_data, train_labels);\n        BOOST_TEST_REQUIRE((model.get() != nullptr), \"failed to train the model!!\");\n        // pass a row of valid size for prediction\n        const class_data row{0.0416667, -1,-0.333333, -0.283019, -0.260274, 1, 1, 0.343511, 1, -1, -1, -0.333333, -1};\n        auto ret = svm::test(model, test_data);\n        BOOST_TEST(not ret.empty(), \"the args to the model test is  - good, should not return empty\"); \n        auto ret2 = svm::predict(model, row);\n        BOOST_TEST((ret2 != std::numeric_limits<value_type>::max()), \"the args to predict are good, we pass good number of features\");\n    } catch (...) {\n        BOOST_TEST(false, \"we should not get any exception here\");\n    }\n    \n}\n\n", "meta": {"hexsha": "c002886ed68b022ca51ee222b10b835e3fc086b1", "size": 7407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/ml_models/ut/test_svm_impl.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "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/libs/ml_models/ut/test_svm_impl.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "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/libs/ml_models/ut/test_svm_impl.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["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.0062111801, "max_line_length": 152, "alphanum_fraction": 0.6484406642, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "#include \"dvs_hot_pixel_filter/utils.h\"\n\n#include <boost/filesystem.hpp>\n#include <gflags/gflags.h>\n#include <iostream>\n\n#include <rosbag/bag.h>\n#include <rosbag/view.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/Imu.h>\n\nDECLARE_bool(no_stats);\n\nnamespace dvs_hot_pixel_filter {\nnamespace utils {\n\nconst std::string OUTPUT_FOLDER = \"./stats/\";\n\nbool parse_arguments(int argc, char* argv[],\n                     std::string* path_to_input_rosbag)\n{\n  if(argc < 2)\n  {\n    std::cerr << \"Error: not enough input arguments.\\n\"\n        \"Usage:\\n\\trosrun dvs_hot_pixel_filter hot_pixel_filter path_to_bag.bag\\n\\n\"\n        \"Additional (optional) command-line flags include:\\n\"\n        \"\\t--n_hot_pix=<number_of_hot_pixels>\\n\"\n        \"\\t--n_std=<number_of_standard_deviations>\\n\"\n        \"\\t--no_stats (do not save stats on disk)\"<< std::endl;\n    return false;\n  }\n\n  *path_to_input_rosbag = std::string(argv[1]);\n  std::cout << \"Input bag: \" << *path_to_input_rosbag << std::endl;\n  return true;\n}\n\nvoid write_histogram_image(const std::string filename,\n                           const cv::Mat& histogram,\n                           const std::vector<cv::Point>& hot_pixels)\n{\n  cv::Mat display_image;\n\n  if (!hot_pixels.empty())\n  {\n    cv::Vec3b colour = cv::Vec3b(255, 0, 0);\n    cv::Mat local_hist;\n    histogram.copyTo(local_hist);\n    // create mask\n    cv::Mat mask = cv::Mat::zeros(histogram.size(), CV_8UC1);\n    for (auto point : hot_pixels)\n    {\n      mask.at<uint8_t>(point) = 1;\n    }\n    double max;\n    cv::minMaxLoc(local_hist, nullptr, &max);\n    local_hist.setTo(max, mask);\n    cv::normalize(local_hist, display_image, 0, 255, cv::NORM_MINMAX, CV_8UC1);\n    cv::applyColorMap(display_image, display_image, cv::COLORMAP_HOT);\n    display_image.setTo(colour, mask);\n  }\n  else\n  {\n    cv::normalize(histogram, display_image, 0, 255, cv::NORM_MINMAX, CV_8UC1);\n    cv::applyColorMap(display_image, display_image, cv::COLORMAP_HOT);\n  }\n\n  cv::Mat large_image;\n  cv::resize(display_image, large_image, cv::Size(), 3, 3, cv::INTER_NEAREST);\n  cv::imwrite(filename, large_image);\n}\n\nstd::string extract_bag_name(const std::string fullname)\n{\n  int pos = 0;\n  int len = fullname.length();\n  // go from the back to the first forward- or back-slash.\n  for (int i = len; i > 0; i--)\n  {\n    if (fullname[i] == '/' || fullname[i] == '\\\\')\n    {\n      pos = i + 1;\n      break;\n    }\n  }\n  int count = 4;\n  // now go from there to the first '.'\n  for (int i = 0; i < len; i++)\n  {\n    if (fullname[pos + i] == '.')\n    {\n      count = i;\n      break;\n    }\n  }\n  std::string bag_name = fullname.substr(pos, count);\n  return bag_name;\n}\n\nvoid build_histograms(rosbag::View& view,\n                      topic_mats& histograms)\n{\n  std::cout << \"Building event count histogram(s)...\" << std::endl;\n\n  std::vector<std::string> seen_topics;\n  for(const rosbag::MessageInstance& m : view)\n  {\n    if(m.getDataType() == \"dvs_msgs/EventArray\")\n    {\n      const std::string topic_name = m.getTopic();\n      // pointer to the message\n      dvs_msgs::EventArrayConstPtr s = m.instantiate<dvs_msgs::EventArray>();\n      const cv::Size msg_size = cv::Size(s->width, s->height);\n\n      cv::Mat& histogram = histograms[topic_name];\n\n      // initialise event_count_histogram if we haven't seen the topic yet\n      if ( !contains(topic_name, seen_topics) )\n      {\n        histogram = cv::Mat::zeros(msg_size, CV_64FC1);\n        seen_topics.push_back(topic_name);\n        std::cout << \"added \" << topic_name << \" to seen_topics\" << std::endl;\n      }\n\n      if (msg_size != histogram.size())\n      {\n        std::cerr << \"Error: a new event message in \" << topic_name <<\n        \" does not match the existing topic histogram size.\\n message: \" <<\n        msg_size << \"\\t histogram: \" << histogram.size() << std::endl;\n        return;\n      }\n\n      for(auto e : s->events)\n      {\n        // accumulate events without discrimination\n        histogram.at<double>(e.y, e.x)++;\n      }\n    }\n  }\n\n  std::cout << \"...done!\" << std::endl;\n}\n\nvoid detect_hot_pixels(const topic_mats& histograms_by_topic,\n                       const double& num_std_devs,\n                       const int num_hot_pixels,\n                       topic_points& hot_pixels_by_topic)\n{\n  for(const auto& topic : histograms_by_topic)\n    {\n      const std::string topic_name = topic.first;\n      const cv::Mat& histogram = topic.second;\n      std::vector<cv::Point>& hot_pixels = hot_pixels_by_topic[topic_name];\n      if (num_hot_pixels == -1)\n      {\n        // auto-detect hot pixels\n        double threshold;\n        dvs_hot_pixel_filter::utils::find_threshold(\n            histogram, num_std_devs, threshold);\n        dvs_hot_pixel_filter::utils::hot_pixels_by_threshold(\n            histogram, threshold, hot_pixels);\n      }\n      else\n      {\n        // user-specified number of hot pixels\n        dvs_hot_pixel_filter::utils::hot_pixels_by_ranking(\n            histogram, num_hot_pixels, hot_pixels);\n      }\n    }\n}\n\nvoid hot_pixels_by_threshold(const cv::Mat& histogram,\n                             const double& threshold,\n                             std::vector<cv::Point>& hot_pixels)\n{\n  for (int y = 0; y < histogram.rows; y++)\n  {\n    for (int x = 0; x < histogram.cols; x++)\n    {\n      if (histogram.at<double>(y, x) > threshold)\n      {\n        hot_pixels.push_back(cv::Point(x, y));\n      }\n    }\n  }\n}\nvoid hot_pixels_by_ranking(const cv::Mat& histogram,\n                           const double& num_hot_pixels,\n                           std::vector<cv::Point>& hot_pixels)\n{\n  cv::Mat local_hist;\n  histogram.copyTo(local_hist);\n\n  for (int i = 0; i < num_hot_pixels; i++)\n  {\n    double max;\n    cv::Point maxLoc;\n    cv::minMaxLoc(local_hist, nullptr, &max, nullptr, &maxLoc);\n\n    hot_pixels.push_back(maxLoc);\n    local_hist.at<double>(maxLoc) = 0;\n  }\n}\n\nvoid find_threshold(const cv::Mat& histogram,\n                    const double num_std_devs,\n                    double& threshold)\n{\n  cv::Scalar mean_Scalar, stdDev_Scalar;\n  cv::meanStdDev(histogram, mean_Scalar, stdDev_Scalar, histogram > 0);\n\n  const double mean = mean_Scalar[0];\n  const double stdDev = stdDev_Scalar[0];\n  threshold = mean + num_std_devs*stdDev;\n}\n\nvoid write_all_msgs(rosbag::View& view,\n                    topic_points& hot_pixels_by_topic,\n                    rosbag::Bag& output_bag)\n{\n  constexpr int log_every_n_messages = 10000;\n  const uint32_t num_messages = view.size();\n  uint32_t message_index = 0;\n  std::cout << \"Writing...\" << std::endl;\n  // write the new rosbag without hot pixels by iterating over all messages\n  for(rosbag::MessageInstance const m : view)\n  {\n    write_msg(\n        m, hot_pixels_by_topic, output_bag);\n    if(message_index++ % log_every_n_messages == 0)\n    {\n      std::cout << \"Message: \" << message_index << \" / \" << num_messages << std::endl;\n    }\n  }\n\n  std::cout << \"Message: \" << num_messages << \" / \" << num_messages << std::endl;\n  std::cout << \"...done!\" << std::endl;\n}\n\nvoid write_event_msg(const std::string topic_name,\n                     const dvs_msgs::EventArrayConstPtr event_array_ptr,\n                     const std::vector<cv::Point>& hot_pixels,\n                     rosbag::Bag& output_bag)\n{\n  std::vector<dvs_msgs::Event> events;\n  for(auto e : event_array_ptr->events)\n  {\n    if (!contains(cv::Point(e.x, e.y), hot_pixels))\n    {\n      events.push_back(e);\n    }\n  }\n\n  if (events.size() > 0)\n  {\n  // Write new event array message to output rosbag\n\n  dvs_msgs::EventArray event_array_msg;\n  event_array_msg.events = events;\n  event_array_msg.width = event_array_ptr->width;\n  event_array_msg.height = event_array_ptr->height;\n  event_array_msg.header.stamp = events.back().ts;\n\n  output_bag.write(topic_name, event_array_msg.header.stamp, event_array_msg);\n  }\n}\n\nvoid write_msg(const rosbag::MessageInstance& m,\n               topic_points& hot_pixels_topic,\n               rosbag::Bag& output_bag)\n{\n  if(m.getDataType() == \"dvs_msgs/EventArray\")\n  {\n    const std::string topic_name = m.getTopic();\n    std::vector<cv::Point>& hot_pixels = hot_pixels_topic[topic_name];\n    dvs_msgs::EventArrayConstPtr event_array_ptr = m.instantiate<dvs_msgs::EventArray>();\n    write_event_msg(topic_name, event_array_ptr, hot_pixels, output_bag);\n\n  }\n  else if(m.getDataType() == \"sensor_msgs/Image\")\n  {\n    sensor_msgs::ImageConstPtr img_msg = m.instantiate<sensor_msgs::Image>();\n    output_bag.write(m.getTopic(), img_msg->header.stamp, m);\n  }\n  else if(m.getDataType() == \"sensor_msgs/Imu\")\n  {\n    sensor_msgs::ImuConstPtr imu_msg = m.instantiate<sensor_msgs::Imu>();\n    output_bag.write(m.getTopic(), imu_msg->header.stamp, m);\n  }\n  else\n  {\n    output_bag.write(m.getTopic(), m.getTime(), m);\n  }\n}\n\nstd::string usable_filename(const std::string filename_in)\n{\n  std::string filename = filename_in;\n  std::replace( filename.begin(), filename.end(), '/', '_'); // replace all '/' to '_'\n  std::replace( filename.begin(), filename.end(), '\\\\', '_'); // replace all '\\' to '_'\n  return filename;\n}\n\nvoid write_hot_pixels(const std::string filename,\n                      const std::vector<cv::Point>& hot_pixels)\n{\n  std::ofstream hot_pixels_file;\n  hot_pixels_file.open(filename);\n  // the important part\n  for (const auto& point : hot_pixels)\n  {\n    hot_pixels_file << point.x << \", \" << point.y << \"\\n\";\n  }\n  hot_pixels_file.close();\n}\n\nvoid save_stats(const std::string bag_name,\n                 const std::string topic_name,\n                 const cv::Mat& histogram,\n                 const std::vector<cv::Point>& hot_pixels,\n                 const bool one_topic)\n{\n  cv::Mat histogram_after;\n  histogram.copyTo(histogram_after);\n  for (auto point : hot_pixels)\n  {\n    histogram_after.at<double>(point) = 0;\n  }\n\n  const double num_events = cv::sum(histogram)[0];\n  const double num_events_after = cv::sum(histogram_after)[0];\n  const double percent_events_discarded = (1 - num_events_after/num_events)*100;\n\n  std::cout << std::setprecision(4) << topic_name << \"\\t\" << num_events <<\n      \"\\t\" << hot_pixels.size() << \"\\t\\t0\\t(before)\" << std::endl;\n\n  std::cout << std::setprecision(4) << topic_name << \"\\t\" << num_events_after <<\n      \"\\t0\\t\\t\" << percent_events_discarded << \"\\t(after)\" << std::endl;\n\n  if (!FLAGS_no_stats)\n  {\n    // save images\n    std::string dstDir = OUTPUT_FOLDER + bag_name + \"/\";\n    if (!one_topic)\n    {\n      dstDir += usable_filename(topic_name) + \"/\";\n    }\n    boost::filesystem::create_directories(dstDir); // create if needed\n    std::string fname_b = dstDir + \"hist_before.png\";\n    std::string fname_a = dstDir + \"hist_after.png\";\n    std::string fname_hp = dstDir + \"hot_pixels.txt\";\n\n    write_histogram_image(fname_b, histogram);\n    write_histogram_image(fname_a, histogram_after, hot_pixels);\n    write_hot_pixels(fname_hp, hot_pixels);\n  }\n}\n\n}  // namespace utils\n}  // namespace dvs_hot_pixel_filter\n", "meta": {"hexsha": "b44c487b41c6529e99e2cc7654cb1ac5c9ab77a3", "size": 10907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dvs_hot_pixel_filter/src/utils.cpp", "max_stars_repo_name": "Tobias-Fischer/dvs_tools", "max_stars_repo_head_hexsha": "10d88232f6376c4b95941baa26358929a6356a87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T12:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T19:19:21.000Z", "max_issues_repo_path": "dvs_hot_pixel_filter/src/utils.cpp", "max_issues_repo_name": "Tobias-Fischer/dvs_tools", "max_issues_repo_head_hexsha": "10d88232f6376c4b95941baa26358929a6356a87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dvs_hot_pixel_filter/src/utils.cpp", "max_forks_repo_name": "Tobias-Fischer/dvs_tools", "max_forks_repo_head_hexsha": "10d88232f6376c4b95941baa26358929a6356a87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T16:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T00:22:04.000Z", "avg_line_length": 30.2132963989, "max_line_length": 89, "alphanum_fraction": 0.6262033556, "num_tokens": 2830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "//\n// main.cpp\n// ~~~~~~~~\n//\n// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)\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#include <iostream>\n#include <string>\n#include <boost/asio.hpp>\n#include <boost/bind.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/regex.hpp>\n#include \"server.hpp\"\n\nusing namespace http::server ;\nusing namespace std ;\n\nclass TileHandler: public request_handler {\npublic:\n    void handle_request(const request& req, reply& rep) {\n\n        boost::smatch m ;\n        boost::regex_match(req.path_, m, rx_) ;\n\n        int zoom = stoi(m.str(1)) ;\n        int tx = stoi(m.str(2)) ;\n        int ty = stoi(m.str(3)) ;\n        string extension = m.str(4) ;\n\n        cout << tx << ' ' << ty << ' ' << zoom << endl ;\n    }\n\n     static boost::regex rx_ ;\n};\n\nboost::regex TileHandler::rx_(R\"(/map/[^/]+/tiles/[^/]+/(\\d+)/(\\d+)/(\\d+)\\.([^/]+))\") ;\n\nclass Factory: public request_handler_factory {\npublic:\n    Factory() = default ;\n\n    std::shared_ptr<request_handler> create(const request &req) {\n        boost::smatch m ;\n        if ( boost::regex_match(req.path_, m, TileHandler::rx_) )\n             return std::shared_ptr<request_handler>(new TileHandler()) ;\n        else\n            return nullptr ;\n    }\n};\n\nint main(int argc, char* argv[])\n{\n  try\n  {\n    // Check command line arguments.\n    if (argc != 5)\n    {\n      std::cerr << \"Usage: http_server <address> <port> <threads> <doc_root>\\n\";\n      std::cerr << \"  For IPv4, try:\\n\";\n      std::cerr << \"    receiver 0.0.0.0 80 1 .\\n\";\n      std::cerr << \"  For IPv6, try:\\n\";\n      std::cerr << \"    receiver 0::0 80 1 .\\n\";\n      return 1;\n    }\n\n    // Initialise the server.\n    std::size_t num_threads = boost::lexical_cast<std::size_t>(argv[3]);\n    http::server::server s(make_shared<Factory>(), argv[1], argv[2], num_threads);\n\n    // Run the server until stopped.\n    s.run();\n  }\n  catch (std::exception& e)\n  {\n    std::cerr << \"exception: \" << e.what() << \"\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "b0851980af7d75bcaf5df0f857f9c721a2dc5535", "size": 2119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "malasiot/wsrv", "max_stars_repo_head_hexsha": "b61344ecb6e528cbe6e7f8348d2df466a3920a42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-05-11T21:44:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:35:56.000Z", "max_issues_repo_path": "src/server/main.cpp", "max_issues_repo_name": "malasiot/mftools", "max_issues_repo_head_hexsha": "1edeec673110cdd5fa904ff2ff88289b6c3ec324", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2016-10-27T10:10:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-07T21:27:02.000Z", "max_forks_repo_path": "src/server/main.cpp", "max_forks_repo_name": "malasiot/mftools", "max_forks_repo_head_hexsha": "1edeec673110cdd5fa904ff2ff88289b6c3ec324", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-10-17T08:18:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T11:44:23.000Z", "avg_line_length": 25.2261904762, "max_line_length": 87, "alphanum_fraction": 0.5832940066, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.19958119293562743}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// Copyright 2019 FZI Research Center for Information Technology\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\n//-----------------------------------------------------------------------------\n/*!\\file    DampedLeastSquaresSolver.cpp\n *\n * \\author  Stefan Scherzinger <scherzin@fzi.de>\n * \\date    2020/03/27\n *\n */\n//-----------------------------------------------------------------------------\n\n// this package\n#include <cartesian_controller_base/DampedLeastSquaresSolver.h>\n\n// Pluginlib\n#include <pluginlib/class_list_macros.h>\n\n// other\n#include <boost/algorithm/clamp.hpp>\n\n/**\n * \\class cartesian_controller_base::DampedLeastSquaresSolver \n *\n * Users may explicitly specify this solver with \\a \"damped_least_squares\" as \\a\n * ik_solver in their controllers.yaml configuration file for each controller:\n *\n * \\code{.yaml}\n * <name_of_your_controller>:\n *     type: \"<type_of_your_controller>\"\n *     ik_solver: \"damped_least_squares\"\n *     ...\n *\n *     solver:\n *         ...\n *         damped_least_squares:\n *             alpha: 0.5\n * \\endcode\n *\n */\nPLUGINLIB_EXPORT_CLASS(cartesian_controller_base::DampedLeastSquaresSolver, cartesian_controller_base::IKSolver)\n\n\n\n\n\nnamespace cartesian_controller_base{\n\n  DampedLeastSquaresSolver::DampedLeastSquaresSolver()\n    : m_alpha(0.01)\n  {\n  }\n\n  DampedLeastSquaresSolver::~DampedLeastSquaresSolver(){}\n\n  trajectory_msgs::JointTrajectoryPoint DampedLeastSquaresSolver::getJointControlCmds(\n        ros::Duration period,\n        const ctrl::Vector6D& net_force)\n  {\n    // Compute joint jacobian\n    m_jnt_jacobian_solver->JntToJac(m_current_positions,m_jnt_jacobian);\n\n    // Compute joint velocities according to:\n    // \\f$ \\dot{q} = ( J^T J + \\alpha^2 I )^{-1} J^T f \\f$\n    ctrl::MatrixND identity;\n    identity.setIdentity(m_number_joints, m_number_joints);\n\n    m_current_velocities.data =\n      (m_jnt_jacobian.data.transpose() * m_jnt_jacobian.data\n       + m_alpha * m_alpha * identity).inverse() * m_jnt_jacobian.data.transpose() * net_force;\n\n    // Integrate once, starting with zero motion\n    m_current_positions.data = m_last_positions.data + 0.5 * m_current_velocities.data * period.toSec();\n\n    // Make sure positions stay in allowed margins\n    applyJointLimits();\n\n    // Apply results\n    trajectory_msgs::JointTrajectoryPoint control_cmd;\n    for (int i = 0; i < m_number_joints; ++i)\n    {\n      control_cmd.positions.push_back(m_current_positions(i));\n      control_cmd.velocities.push_back(m_current_velocities(i));\n\n      // Accelerations should be left empty. Those values will be interpreted\n      // by most hardware joint drivers as max. tolerated values. As a\n      // consequence, the robot will move very slowly.\n    }\n    control_cmd.time_from_start = period; // valid for this duration\n\n    return control_cmd;\n  }\n\n  bool DampedLeastSquaresSolver::init(ros::NodeHandle& nh,\n                                      const KDL::Chain& chain,\n                                      const KDL::JntArray& upper_pos_limits,\n                                      const KDL::JntArray& lower_pos_limits)\n  {\n    IKSolver::init(nh, chain, upper_pos_limits, lower_pos_limits);\n\n    m_jnt_jacobian_solver.reset(new KDL::ChainJntToJacSolver(m_chain));\n    m_jnt_jacobian.resize(m_number_joints);\n\n    // Connect dynamic reconfigure and overwrite the default values with values\n    // on the parameter server. This is done automatically if parameters with\n    // the according names exist.\n    m_callback_type = boost::bind(\n        &DampedLeastSquaresSolver::dynamicReconfigureCallback, this, _1, _2);\n\n    m_dyn_conf_server.reset(\n        new dynamic_reconfigure::Server<IKConfig>(\n          ros::NodeHandle(nh.getNamespace() + \"/solver/damped_least_squares\")));\n    m_dyn_conf_server->setCallback(m_callback_type);\n    return true;\n  }\n\n    void DampedLeastSquaresSolver::dynamicReconfigureCallback(IKConfig& config, uint32_t level)\n    {\n      m_alpha = config.alpha;\n    }\n\n} // namespace\n", "meta": {"hexsha": "66a6b5321963265b1c504330bdc6a1eb9809c44f", "size": 5588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cartesian_controller_base/src/DampedLeastSquaresSolver.cpp", "max_stars_repo_name": "graziegrazie/cartesian_controllers", "max_stars_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2019-11-01T07:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T08:14:52.000Z", "max_issues_repo_path": "cartesian_controller_base/src/DampedLeastSquaresSolver.cpp", "max_issues_repo_name": "graziegrazie/cartesian_controllers", "max_issues_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T20:40:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:17:50.000Z", "max_forks_repo_path": "cartesian_controller_base/src/DampedLeastSquaresSolver.cpp", "max_forks_repo_name": "graziegrazie/cartesian_controllers", "max_forks_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2019-11-01T07:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T08:26:35.000Z", "avg_line_length": 37.2533333333, "max_line_length": 112, "alphanum_fraction": 0.6791338583, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.1995602419113094}}
{"text": "#ifndef __SUPERREACTIONNETWORK_CPP_\n#define __SUPERREACTIONNETWORK_CPP_\n\n#include <queue>\n#include <boost/property_tree/json_parser.hpp> //for json_reader\n#include <boost/property_tree/xml_parser.hpp> //for write_xml\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/limits.hpp>\n#include <boost/graph/grid_graph.hpp>\n#include <numeric>\n\n#include <math.h> /* log */\n\n#include \"../../../include/tools/misc/misc_template.h\"\n#include \"../../../include/reactionNetwork/superReactionNetwork/superReactionNetwork.h\"\n\n//infinitesimal dt\n#define INFINITESIMAL_DT 1.0E-14\n\nnamespace reactionNetwork_sr {\n\n\tsuperReactionNetwork::superReactionNetwork(std::vector<double> uncertainties, std::size_t random_seed_for_this_core, std::string cwd_in)\n\t{\n\n\t\t//current working directory\n\t\tthis->cwd = cwd_in;\n\n\t\t//read configuration file \"setting.json\"\n\t\tboost::property_tree::read_json(this->cwd + std::string(\"/input/setting.json\"), rnk_pt, std::locale());\n\t\tread_init_config();\n\n\t\t//random seed for this core\n\t\tthis->random_seed_for_this_core = static_cast<boost::uint32_t>(random_seed_for_this_core);\n\n\t\trand = new random_sr::random(this->random_seed_for_this_core);\n\n\t\tstd::vector<VertexPair> edgeVector; std::vector<EdgeProperties_graph> edgePro; std::vector<VertexProperties_graph> vertex_info;\n\t\tread_chem_out_spe_for_network_info(edgeVector, edgePro, vertex_info);\n\n\t\tset_species_initial_concentration();\n\n\t\t//initialize graph\n\t\tinitGraph(edgeVector, edgePro);\n\t\tupdate_vertex_info(vertex_info);\n\n\t\tthis->follow_hypothesized_atom = this->check_hypothesized_atom();\n\t\tthis->condense_chatterings = this->check_condense_chatterings();\n\n\t\t//read reaction constraint or species constraint information from file, then set whether apply pathway constraint\n\t\tthis->update_pathway_constraint_from_file_rnk();\n\t\tthis->apply_pathway_constraint = this->check_apply_pathway_constraint();\n\n\t\t//update super atom info\n\t\tthis->update_super_atom_info(rnk_pt.get<std::string>(\"pathway.super_atom\"));\n\t\tif (this->follow_hypothesized_atom) {\n\t\t\tthis->read_atom_scheme();\n\t\t\tthis->update_hypothesized_atom_info(rnk_pt.get<std::string>(\"pathway.atom_followed\"));\n\t\t}\n\t\tset_spe_out_reaction_info();\n\t\tset_reaction_out_spe_info();\n\t\tset_out_spe_index_branching_ratio_map_map_with_constraint();\n\n\t\t//set terminal species\n\t\tset_terminal_spe();\n\n\t\tinitiate_M_matrix();\n\t\tinitiate_R_matrix();\n\n\t\tset_is_reaction_rate_nonzero_from_setting_file();\n\n\t\t//print();\n\t\t//print_network();\n\t\t//std::cout << \"test\" << std::endl;\n\t\t//print_initial_spe_label_json();\n\n\t}\n\n\tsuperReactionNetwork::~superReactionNetwork()\n\t{\n\t\tdelete rand;\n\t}\n\n\t////Read initial configuration file named \"setting.cfg\"\n\tbool superReactionNetwork::read_init_config()\n\t{\n\t\tset_min_time(this->rnk_pt.get<cf_parser::my_time_t>(\"time.min_time\"));\n\t\tset_max_time(this->rnk_pt.get<cf_parser::my_time_t>(\"time.max_time\"));\n\t\tset_sys_min_time(this->rnk_pt.get<cf_parser::my_time_t>(\"time.sys_min_time\"));\n\t\tset_absolute_end_t(this->rnk_pt.get<cf_parser::my_time_t>(\"pathway.end_t\") * this->rnk_pt.get<cf_parser::my_time_t>(\"time.tau\"));\n\n\t\treturn true;\n\t}\n\n\tvoid superReactionNetwork::read_chem_out_spe_for_network_info(const std::string & cwd, std::vector<rsp::element_info>& element_v, std::vector<rsp::spe_info_base> &species_network_v, std::vector<rsp::reaction_info_base> &reaction_network_v, rsp::spe_name_index_map_t & spe_name_index_map, std::vector<VertexPair>& edgeVector, std::vector<EdgeProperties_graph>& edgePro, std::vector<VertexProperties_graph>& vertex_info, bool w2f)\n\t{\n\t\t/*\n\t\t* read species information\n\t\t*/\n\t\tstd::vector<rsp::spe_info> species_v;\n\t\t//read element, species and reaction information\n\t\trsp::relationshipParser::read_chem_out_ele_spe(element_v, species_v, spe_name_index_map, cwd + \"/input/chem.out\");\n\n\t\tfor (std::size_t i = 0; i < species_v.size(); ++i) {/*for1*/\n\t\t\trsp::spe_info_base species_network_temp;\n\t\t\tspecies_network_temp.prob_max = species_v[i].prob_max;\n\t\t\tspecies_network_temp.prob_min = species_v[i].prob_min;\n\t\t\tspecies_network_temp.reaction_k_index_s_coef_v = species_v[i].reaction_k_index_s_coef_v;\n\t\t\tspecies_network_temp.spe_component = species_v[i].spe_component;\n\t\t\tspecies_network_temp.spe_conc = species_v[i].spe_conc;\n\t\t\tspecies_network_temp.spe_index = species_v[i].spe_index;\n\t\t\tspecies_network_temp.spe_name = species_v[i].spe_name;\n\t\t\tspecies_network_temp.survival_probability = species_v[i].survival_probability;\n\n\t\t\tspecies_network_v.push_back(species_network_temp);\n\t\t}/*for1*/\n\n\t\t //update vetex information, here our vertex just store the index of vextex in species space, look the difinition of VertexProperties_graph\n\t\tvertex_info.resize(species_network_v.size());\n\t\tfor (std::size_t i = 0; i < species_network_v.size(); ++i) {\n\t\t\tvertex_info[i].vertex = species_network_v[i].spe_index;\n\t\t}\n\n\n\t\t/*\n\t\t* read reaction information\n\t\t*/\n\t\tstd::vector<rsp::reaction_info> reaction_v;\n\t\t//include duplicated reactions\n\t\trsp::relationshipParser::read_chem_out_reaction(species_v, reaction_v, spe_name_index_map, cwd + \"/input/chem.out\");\n\t\trsp::relationshipParser::set_reaction_net_reactant_product(reaction_v);\n\t\t//reactionNetwork and chemkin index lookup table, notice chemkin index is Fortran index style\n\t\trsp::reactionNetwork_chemkin_index_map_t reactionNetwork_chemkin_index_map;\n\t\trsp::relationshipParser::read_reactionNetwork_chemkin_index_map(reactionNetwork_chemkin_index_map, cwd + \"/input/chem.out\");\n\n\n\t\trsp::index_int_t edge_counter = 0;\n\t\t//construct A->B transition\n\t\tEdgeProperties_graph edgePro_tmp;\n\n\t\tfor (rsp::reactionNetwork_chemkin_index_map_t::const_iterator itr = reactionNetwork_chemkin_index_map.begin(); itr != reactionNetwork_chemkin_index_map.end(); ++itr) {\n\t\t\trsp::reaction_info_base reaction_info_base_temp;\n\t\t\t//just need the first one if have multiple duplicated reactions\n\t\t\t//std::cout << itr->first << \"\\t-->\\t\";\n\t\t\t//std::cout << itr->second[0] << \"\\t\";\n\t\t\t//need to convert Fortran style index into C++ style index\n\t\t\trsp::index_int_t reaction_v_ind = static_cast<rsp::index_int_t>(abs(itr->second[0])) - 1;\n\t\t\t//std::cout << reaction_v[reaction_v_ind].reaction_name << \"\\t\";\n\t\t\t//std::cout << reaction_v[reaction_v_ind].reaction_direction << \"\\n\";\n\n\t\t\t//forward reaction\n\t\t\tif (itr->second[0] > 0) {\n\t\t\t\treaction_info_base_temp.reaction_direction = rsp::forward;\n\n\t\t\t\t//edge vector\n\t\t\t\tfor (std::size_t i = 0; i < reaction_v[reaction_v_ind].net_reactant.size(); ++i) {/*for i*/\n\t\t\t\t\tfor (std::size_t j = 0; j < reaction_v[reaction_v_ind].net_product.size(); ++j) {/*for j*/\n\t\t\t\t\t\t//std::cout << \"[\" << reaction_v[reaction_v_ind].net_reactant[i].first << \",\" << reaction_v[reaction_v_ind].net_product[j].first << \"]\" << \"\\t\";\n\t\t\t\t\t\tedgeVector.push_back(std::make_pair(reaction_v[reaction_v_ind].net_reactant[i].first, reaction_v[reaction_v_ind].net_product[j].first));\n\t\t\t\t\t\tedgePro_tmp.edge_index = edge_counter; ++edge_counter;\n\t\t\t\t\t\tedgePro_tmp.reaction_index = itr->first;\n\t\t\t\t\t\tedgePro_tmp.s_coef_reactant = reaction_v[reaction_v_ind].net_reactant[i].second;\n\t\t\t\t\t\tedgePro_tmp.s_coef_product = reaction_v[reaction_v_ind].net_product[j].second;\n\n\t\t\t\t\t\tedgePro.push_back(edgePro_tmp);\n\n\t\t\t\t\t}/*for j*/\n\t\t\t\t}/*for i*/\n\t\t\t\t //std::cout << std::endl;\n\t\t\t}/*if*/\n\t\t\t //backward reaction\n\t\t\telse if (itr->second[0] < 0) {\n\t\t\t\treaction_info_base_temp.reaction_direction = rsp::backward;\n\t\t\t\t//edge vector\n\t\t\t\tfor (std::size_t i = 0; i < reaction_v[reaction_v_ind].net_product.size(); ++i) {/*for i*/\n\t\t\t\t\tfor (std::size_t j = 0; j < reaction_v[reaction_v_ind].net_reactant.size(); ++j) {/*for j*/\n\t\t\t\t\t\t//std::cout << \"[\" << reaction_v[reaction_v_ind].net_product[i].first << \",\" << reaction_v[reaction_v_ind].net_reactant[j].first << \"]\" << \"\\t\";\n\t\t\t\t\t\tedgeVector.push_back(std::make_pair(reaction_v[reaction_v_ind].net_product[i].first, reaction_v[reaction_v_ind].net_reactant[j].first));\n\t\t\t\t\t\tedgePro_tmp.edge_index = edge_counter; ++edge_counter;\n\t\t\t\t\t\tedgePro_tmp.reaction_index = itr->first;\n\t\t\t\t\t\tedgePro_tmp.s_coef_reactant = reaction_v[reaction_v_ind].net_product[i].second;\n\t\t\t\t\t\tedgePro_tmp.s_coef_product = reaction_v[reaction_v_ind].net_reactant[j].second;\n\n\t\t\t\t\t\tedgePro.push_back(edgePro_tmp);\n\n\t\t\t\t\t}/*for j*/\n\n\t\t\t\t}/*for i*/\n\n\n\t\t\t}/*else if*/\n\t\t\treaction_info_base_temp.reaction_name = reaction_v[reaction_v_ind].reaction_name;\n\t\t\treaction_network_v.push_back(reaction_info_base_temp);\n\n\t\t}/*for*/\n\n\t\tif (w2f == true)\n\t\t{\n\t\t\trsp::relationshipParser::spe_information_s2f(species_v, cwd + std::string(\"/input/species_labelling.csv\"));\n\t\t\trsp::relationshipParser::spe_information_s2json(species_v, cwd + std::string(\"/input/species_information.json\"));\n\n\t\t\trsp::relationshipParser::reaction_information_s2f(species_v, reaction_v, reactionNetwork_chemkin_index_map, cwd + std::string(\"/input/reaction_labelling.csv\"));\n\t\t\trsp::relationshipParser::reaction_information_s2json(species_v, reaction_v, reactionNetwork_chemkin_index_map, cwd + std::string(\"/input/reaction_information.json\"));\n\t\t}\n\t}\n\n\tvoid superReactionNetwork::read_chem_out_spe_for_network_info(std::vector<VertexPair> &edgeVector, std::vector<EdgeProperties_graph> &edgePro, std::vector<VertexProperties_graph>& vertex_info)\n\t{\n\n\t\tread_chem_out_spe_for_network_info(this->cwd, this->element_v, this->species_network_v, this->reaction_network_v, this->spe_name_index_map, edgeVector, edgePro, vertex_info);\n\t}\n\n\tvoid superReactionNetwork::update_super_atom_info(std::string super_atom)\n\t{\n\t\tthis->super_atom = super_atom;\n\t\tfor (std::size_t i = 0; i < this->species_network_v.size(); ++i) {\n\t\t\tthis->species_network_v[i].spe_component[super_atom] = 0;\n\n\t\t\tfor (auto x : this->element_v)\n\t\t\t\tthis->species_network_v[i].spe_component[super_atom] += this->species_network_v[i].spe_component[x.ele_name];\n\t\t}\n\n\t}\n\n\tvoid superReactionNetwork::read_atom_scheme()\n\t{\n\t\tboost::property_tree::read_json(this->cwd + std::string(\"/input/atom_scheme.json\"), this->rnk_atom_scheme, std::locale());\n\t}\n\n\tbool superReactionNetwork::check_hypothesized_atom()\n\t{\n\t\tif (rnk_pt.get<std::string>(\"pathway.atom_followed\") == rnk_pt.get<std::string>(\"pathway.super_atom\"))\n\t\t\treturn false;\n\t\tfor (auto x : this->element_v) {\n\t\t\tif (rnk_pt.get<std::string>(\"pathway.atom_followed\") == x.ele_name)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid superReactionNetwork::update_hypothesized_atom_info(std::string hypothesized_atom)\n\t{\n\t\tauto ha_dict = this->rnk_atom_scheme.get_child(hypothesized_atom);\n\n\t\tfor (std::size_t i = 0; i < this->species_network_v.size(); ++i) {\n\t\t\tthis->species_network_v[i].spe_component[hypothesized_atom] = 0;\n\t\t}\n\n\t\tfor (auto key1 : ha_dict) {\n\t\t\tstd::string spe_name = boost::lexical_cast<std::string>(key1.first);\n\t\t\trsp::index_int_t spe_idx = this->spe_name_index_map[spe_name];\n\t\t\trsp::index_int_t coef = boost::lexical_cast<rsp::index_int_t>(key1.second.get_value<double>());\n\t\t\tthis->species_network_v[spe_idx].spe_component[hypothesized_atom] = coef;\n\t\t}\n\t}\n\n\tbool superReactionNetwork::check_condense_chatterings()\n\t{\n\t\tif (this->rnk_pt.get<std::string>(\"network.condense_chatterings\") == \"yes\") {\n\t\t\tstd::cout << \"\\ncondense chatterings.\\n\";\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tvoid superReactionNetwork::update_pathway_constraint_from_file_rnk()\n\t{\n\t\t// check reaction constraint\n\t\tfor (auto key1 : this->rnk_pt.get_child(\"pathway.species_sink_reaction_constraint\")) {\n\n\t\t\trsp::index_int_t species_idx = boost::lexical_cast<rsp::index_int_t>(std::stoi(key1.first));\n\t\t\tstd::unordered_set< rsp::index_int_t > reaction_set;\n\t\t\tfor (auto key2 : key1.second) {\n\t\t\t\trsp::index_int_t x = key2.second.get_value<rsp::index_int_t>();\n\t\t\t\t//std::cout << x;\n\t\t\t\treaction_set.insert(x);\n\t\t\t}\n\n\t\t\tthis->sp_pathway_constarint_rnk->species_sink_reaction_set_map[species_idx] = reaction_set;\n\t\t}\n\n\t\tif (this->sp_pathway_constarint_rnk->species_sink_reaction_set_map.size() > 0)\n\t\t\tthis->sp_pathway_constarint_rnk->species_sink_through_reaction_constraint = true;\n\t\telse\n\t\t\tthis->sp_pathway_constarint_rnk->species_sink_through_reaction_constraint = false;\n\n\t\t// check species constraint\n\t\tfor (auto key1 : this->rnk_pt.get_child(\"pathway.reaction_out_species_constraint\")) {\n\n\t\t\trsp::index_int_t reaction_idx = boost::lexical_cast<rsp::index_int_t>(std::stoi(key1.first));\n\t\t\tstd::unordered_set< rsp::index_int_t > species_set;\n\t\t\tfor (auto key2 : key1.second) {\n\t\t\t\trsp::index_int_t x = key2.second.get_value<rsp::index_int_t>();\n\t\t\t\t//std::cout << x;\n\t\t\t\tspecies_set.insert(x);\n\t\t\t}\n\n\t\t\tthis->sp_pathway_constarint_rnk->reaction_out_species_set_map[reaction_idx] = species_set;\n\t\t}\n\t\tif (this->sp_pathway_constarint_rnk->reaction_out_species_set_map.size() > 0)\n\t\t\tthis->sp_pathway_constarint_rnk->reaction_out_species_constraint = true;\n\t\telse\n\t\t\tthis->sp_pathway_constarint_rnk->reaction_out_species_constraint = false;\n\n\t\t// general not allowed out species constraint\n\t\tfor (auto key1 : this->rnk_pt.get_child(\"pathway.not_allowed_out_species\"))\n\t\t{\n\t\t\tthis->sp_pathway_constarint_rnk->not_allowed_out_species_set.insert(key1.second.get_value<size_t>());\n\t\t}\n\t\tif (this->sp_pathway_constarint_rnk->not_allowed_out_species_set.size() > 0)\n\t\t\tthis->sp_pathway_constarint_rnk->not_allowed_out_species_constraint = true;\n\t\telse\n\t\t\tthis->sp_pathway_constarint_rnk->not_allowed_out_species_constraint = false;\n\n\t\t// must react species set\n\t\tfor (auto key1 : this->rnk_pt.get_child(\"pathway.must_react_species\"))\n\t\t{\n\t\t\tthis->sp_pathway_constarint_rnk->must_react_species_set.insert(key1.second.get_value<size_t>());\n\t\t}\n\n\t}\n\n\tbool superReactionNetwork::check_apply_pathway_constraint()\n\t{\n\t\t// two conditions, 1) pathway.apply_pathway_constraint set to be yes,\n\t\t// 2) either \"reaction_constraint\" is set or \"species_constraint\" is et\n\t\tif (this->rnk_pt.get<std::string>(\"pathway.apply_pathway_constraint\") == std::string(\"yes\")) {\n\t\t\tif (this->sp_pathway_constarint_rnk->species_sink_through_reaction_constraint == true ||\n\t\t\t\tthis->sp_pathway_constarint_rnk->reaction_out_species_constraint == true ||\n\t\t\t\tthis->sp_pathway_constarint_rnk->not_allowed_out_species_constraint == true)\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tvoid superReactionNetwork::set_species_initial_concentration()\n\t{\n\t\t//read with json_parser as property_tree\n\t\tfor (auto key1 : this->rnk_pt.get_child(\"chem_init.species_index_concentration\")) {\n\t\t\tthis->species_network_v[boost::lexical_cast<std::size_t>(key1.first)].spe_conc =\n\t\t\t\tkey1.second.get_value<double>()*this->rnk_pt.get<double>(\"SOHR_init.massConservationFactor\");\n\t\t}\n\n\t\tif (this->rnk_pt.get<std::string>(\"propagator.normalize_initial_concentration\") == \"yes\") {\n\t\t\t//renormalization\n\t\t\tdouble total_conc = 0.0;\n\t\t\tfor (std::size_t i = 0; i < this->species_network_v.size(); ++i) {\n\t\t\t\ttotal_conc += this->species_network_v[i].spe_conc;\n\t\t\t}//for\n\n\t\t\tfor (std::size_t i = 0; i < this->species_network_v.size(); ++i) {\n\t\t\t\tthis->species_network_v[i].spe_conc /= total_conc;\n\t\t\t}//for\n\t\t}//if\n\n\t}//set_initial_concentration\n\n\trsp::my_time_t superReactionNetwork::get_max_time() const\n\t{\n\t\treturn this->max_time;\n\t}\n\n\trsp::my_time_t superReactionNetwork::return_tau() const\n\t{\n\t\treturn this->rnk_pt.get<rsp::my_time_t>(\"time.tau\");\n\t}\n\n\trsp::index_int_t superReactionNetwork::return_initial_spe() const\n\t{\n\t\treturn this->rnk_pt.get<rsp::index_int_t>(\"pathway.init_spe\");\n\t}\n\n\tvoid superReactionNetwork::set_terminal_spe()\n\t{\n\t\t//86 and 89 are terminal species, they transform to each other very fast\n\t\tstd::set<rsp::index_int_t> terminal_spe_index;\n\n\t\tfor (auto key1 : this->rnk_pt.get_child(\"pathway.terminal_species\")) {\n\t\t\t//std::cout<<key1.second.get_value<std::size_t>()<<std::endl;\n\t\t\tterminal_spe_index.insert(key1.second.get_value<rsp::index_int_t>());\n\t\t}\n\n\t\t//search network also, if a species has no out reaction or out species\n\t\t//it shall be a terminal species\n\t\t//under current atom scheme, followed a species\n\t\tstd::string atom_followed = this->rnk_pt.get<std::string>(\"pathway.atom_followed\");\n\n\t\tfor (auto x : this->species_network_v) {\n\t\t\tif (x.reaction_k_index_s_coef_v.size() == 0) {\n\t\t\t\tterminal_spe_index.insert(x.spe_index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbool no_out_spe = true;\n\t\t\t// search all out reactions\n\t\t\tfor (auto y : x.reaction_k_index_s_coef_v) {\n\t\t\t\tauto rxn_idx = y.first;\n\n\t\t\t\t// search all out species\n\t\t\t\tfor (auto s : reaction_network_v[rxn_idx].out_spe_index_branching_ratio_map_map_with_constraint.at(atom_followed)) {\n\t\t\t\t\tif (s.second > 0) {\n\t\t\t\t\t\tno_out_spe = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (no_out_spe == false) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (no_out_spe == true) {\n\t\t\t\tterminal_spe_index.insert(x.spe_index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tthis->terminal_species = terminal_spe_index;\n\t}\n\n\n\tvoid superReactionNetwork::initGraph(const vector<VertexPair>& edgeVector, const std::vector<EdgeProperties_graph>& edgePro)\n\t{\n\t\tfor (std::size_t i = 0; i < edgeVector.size(); ++i)\n\t\t{\n\t\t\tAddEdge(edgeVector[i].first, edgeVector[i].second, edgePro[i]);\n\t\t}//for\n\n\t\t//update edge index\n\t\trsp::index_int_t count = 0;\n\t\tfor (edge_range_t er = getEdges(); er.first != er.second; ++er.first)\n\t\t{\n\t\t\tedge_index_to_edge_iterator.push_back(er.first);\n\t\t\tproperties(*er.first).edge_index = count++;\n\t\t}//for\n\t\tnum_edges = get_num_edges();\n\t\tnum_vertices = get_num_vertices();\n\t\t//edge_index_map=get(edge_index, graph);\n\t}\n\n\tvoid superReactionNetwork::update_vertex_info(const std::vector<VertexProperties_graph>& vertex_info) {\n\t\tvertex_range_t vp;\n\t\tint count = 0;\n\t\tfor (vp = vertices(graph); vp.first != vp.second; ++vp.first, ++count)\n\t\t{\n\t\t\tproperties(*vp.first).vertex = vertex_info[count].vertex;\n\t\t\t//std::cout << properties(*vp.first).vertex << std::endl;\n\t\t}\n\t}\n\n\tvoid superReactionNetwork::set_spe_out_reaction_info()\n\t{\n\t\tmt::vector_sr<rsp::reaction_index_s_coef_t > reaction_index_s_coef_v;\n\t\tfor (rsp::index_int_t i = 0; i < (rsp::index_int_t)this->species_network_v.size(); ++i) {\n\t\t\t//terminal species\n\t\t\tif (std::find(this->terminal_species.begin(), this->terminal_species.end(), i) != this->terminal_species.end())\n\t\t\t\tcontinue;\n\t\t\treaction_index_s_coef_v.clear();\n\t\t\tsearch_for_out_reaction(i, reaction_index_s_coef_v);\n\t\t\tthis->species_network_v[i].reaction_k_index_s_coef_v = reaction_index_s_coef_v;\n\t\t}\n\n\t}\n\n\t/*\n\t * search out edge reactions of a species, record the reactant stoichoimetric coefficient\n\t */\n\tvoid superReactionNetwork::search_for_out_reaction(vertex_t vertex, mt::vector_sr<rsp::reaction_index_s_coef_t > & reaction_index_s_coef_v) {\n\t\tif (vertex >= (vertex_t)getVertexCount())\n\t\t\treturn;\n\t\tfor (out_edge_range_t itr = getOutEdges(vertex); itr.first != itr.second; ++itr.first) {\n\t\t\treaction_index_s_coef_v.insert_sr(std::make_pair(properties(*itr.first).reaction_index, properties(*itr.first).s_coef_reactant));\n\t\t}\n\n\t}\n\n\tbool superReactionNetwork::search_for_out_spe(rsp::index_int_t reaction_index, std::vector<rsp::spe_index_weight_t>& out_spe_index_weight_v, std::string atom_followed)\n\t{\n\t\tmt::vector_sr<rsp::spe_index_weight_t > out_spe_index_weight_v_tmp;\n\n\t\tboost::property_map<GraphContainer, vertex_index_t>::type vertex_id = get(vertex_index, graph);\n\t\tstd::pair<vertex_iter, vertex_iter> vp;\n\t\tfor (edge_range_t er = getEdges(); er.first != er.second; ++er.first) {//for\n\t\t\t//if found\n\t\t\tif (properties(*er.first).reaction_index == reaction_index) {//if\n\t\t\t\tstd::size_t spe_index = get(vertex_id, target(*er.first, graph));\n\t\t\t\t//ignore duplicate elements\n\t\t\t\tout_spe_index_weight_v_tmp.insert_sr(\n\t\t\t\t\tstd::make_pair(spe_index,\n\t\t\t\t\t\t/*spe index*/properties(*er.first).s_coef_product* this->species_network_v[spe_index].spe_component[atom_followed] /*weight*/)\n\t\t\t\t);\n\n\t\t\t}//if\n\t\t}//for\n\n\t\tout_spe_index_weight_v = out_spe_index_weight_v_tmp;\n\n\t\treturn true;\n\t}\n\n\tbool superReactionNetwork::set_reaction_out_spe_info(std::string atom_followed)\n\t{\n\t\tstd::vector<rsp::spe_index_weight_t > out_spe_index_weight_v_tmp;\n\t\tfor (rsp::index_int_t i = 0; i < (rsp::index_int_t)this->reaction_network_v.size(); ++i) {\n\t\t\tout_spe_index_weight_v_tmp.clear();\n\t\t\tsearch_for_out_spe(i, out_spe_index_weight_v_tmp, atom_followed);\n\t\t\tthis->reaction_network_v[i].out_spe_index_weight_v_map[atom_followed] = out_spe_index_weight_v_tmp;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvoid superReactionNetwork::set_reaction_out_spe_info()\n\t{\n\t\tfor (auto x : this->element_v)\n\t\t\tthis->set_reaction_out_spe_info(x.ele_name);\n\t\t//super atom\n\t\tthis->set_reaction_out_spe_info(rnk_pt.get<std::string>(\"pathway.super_atom\"));\n\t\tif (this->follow_hypothesized_atom) {\n\t\t\tthis->set_reaction_out_spe_info(rnk_pt.get<std::string>(\"pathway.atom_followed\"));\n\t\t}\n\t}\n\n\tvoid superReactionNetwork::set_out_spe_index_branching_ratio_map_map_with_constraint(std::string atom_followed)\n\t{\n\n\t\tfor (std::size_t r_index = 0; r_index < this->reaction_network_v.size(); ++r_index) {\n\t\t\t// remember to check constraint first\n\n\t\t\tdouble prob_total = 0.0;\n\t\t\t////calcualte out spe total weight for a reaction\n\t\t\t//for (std::size_t i = 0; i < reaction_network_v[r_index].out_spe_index_weight_v_map[atom_followed].size(); ++i) {\n\t\t\t//\tprob_total += reaction_network_v[r_index].out_spe_index_weight_v_map[atom_followed][i].second;\n\t\t\t//}\n\n\t\t\tfor (auto s_i_w : reaction_network_v[r_index].out_spe_index_weight_v_map[atom_followed]) {\n\t\t\t\tauto s_idx = s_i_w.first;\n\t\t\t\tauto w = s_i_w.second;\n\n\t\t\t\t// not allowed out species constraint\n\t\t\t\tif (this->sp_pathway_constarint_rnk->not_allowed_out_species_constraint == true &&\n\t\t\t\t\tthis->sp_pathway_constarint_rnk->not_allowed_out_species_set.count(s_idx) > 0)\n\t\t\t\t\tcontinue;\n\t\t\t\t// reaction out species constraint\n\t\t\t\tif (this->sp_pathway_constarint_rnk->reaction_out_species_constraint == true &&\n\t\t\t\t\tthis->sp_pathway_constarint_rnk->reaction_out_species_set_map.count(r_index) > 0 &&\n\t\t\t\t\tthis->sp_pathway_constarint_rnk->reaction_out_species_set_map.at(r_index).count(s_idx) == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t//otherwise, take this out species into account\n\t\t\t\tprob_total += w;\n\t\t\t}\n\n\t\t\tdouble reverse_p_t = 0.0;\n\t\t\tif (prob_total > 0.0)\n\t\t\t\treverse_p_t = 1.0 / prob_total;\n\t\t\t//calculate the fraction\n\t\t\tfor (auto s_i_w : reaction_network_v[r_index].out_spe_index_weight_v_map[atom_followed]) {\n\t\t\t\tauto s_idx = s_i_w.first;\n\t\t\t\tauto w = s_i_w.second;\n\n\t\t\t\t// not allowed out species constraint\n\t\t\t\tif (this->sp_pathway_constarint_rnk->not_allowed_out_species_constraint == true &&\n\t\t\t\t\tthis->sp_pathway_constarint_rnk->not_allowed_out_species_set.count(s_idx) > 0) {\n\t\t\t\t\treaction_network_v[r_index].out_spe_index_branching_ratio_map_map_with_constraint[atom_followed][s_idx] = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// reaction out species constraint\n\t\t\t\tif (this->sp_pathway_constarint_rnk->reaction_out_species_constraint == true &&\n\t\t\t\t\tthis->sp_pathway_constarint_rnk->reaction_out_species_set_map.count(r_index) > 0 &&\n\t\t\t\t\tthis->sp_pathway_constarint_rnk->reaction_out_species_set_map.at(r_index).count(s_idx) == 0)\n\t\t\t\t{\n\t\t\t\t\treaction_network_v[r_index].out_spe_index_branching_ratio_map_map_with_constraint[atom_followed][s_idx] = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//otherwise, take this out species into account\n\t\t\t\treaction_network_v[r_index].out_spe_index_branching_ratio_map_map_with_constraint[atom_followed][s_idx] = w * reverse_p_t;\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tvoid superReactionNetwork::set_out_spe_index_branching_ratio_map_map_with_constraint()\n\t{\n\t\tfor (auto x : this->element_v)\n\t\t\tthis->set_out_spe_index_branching_ratio_map_map_with_constraint(x.ele_name);\n\t\t//super atom\n\t\tthis->set_out_spe_index_branching_ratio_map_map_with_constraint(rnk_pt.get<std::string>(\"pathway.super_atom\"));\n\t\tif (this->follow_hypothesized_atom) {\n\t\t\tthis->set_out_spe_index_branching_ratio_map_map_with_constraint(rnk_pt.get<std::string>(\"pathway.atom_followed\"));\n\t\t}\n\t}\n\n\n\tvoid superReactionNetwork::print_network(std::string filename)\n\t{\n\t\tstd::ofstream fn((this->cwd + filename).c_str());\n\t\tfn << \"Id,Label,Size\\n\";\n\t\tfor (std::size_t i = 0; i < this->species_network_v.size(); ++i) {\n\t\t\t//\t\tfn<<i<<\",\"<<species_network_v[i].spe_name<<\",\"<<\"1.0\"<<std::endl;\n\t\t\tfn << i << \",\" << species_network_v[i].spe_name << std::endl;\n\t\t}\n\n\t\tstd::ofstream fe((this->cwd + std::string(\"/output/edge.csv\")).c_str());\n\t\tfe << \"Source,Target,Label,Weight\\n\";\n\n\t\t//this->update_reaction_rate(target_time);\n\t\tstd::pair<vertex_iter, vertex_iter> vp;\n\t\tboost::property_map<GraphContainer, vertex_index_t>::type vertex_id = get(vertex_index, graph);\n\t\tfor (edge_range_t er = getEdges(); er.first != er.second; ++er.first) {\n\t\t\tfe << get(vertex_id, source(*er.first, graph)) << \",\" << get(vertex_id, target(*er.first, graph)) << \",\";\n\t\t\tfe << properties(*er.first).edge_index << \",\" << this->reaction_network_v[properties(*er.first).reaction_index].reaction_rate << std::endl;\n\t\t}\n\n\t\tfe.clear(); fe.close();\n\t}\n\n\tvoid superReactionNetwork::print()\n\t{\n\n\t\t////test random number generator\n\t\t//std::ofstream fout((this->cwd + std::string(\"/output/random.csv\")).c_str());\n\t\t//for (size_t i = 0; i < 1000; ++i) {\n\t\t//\tfout << std::setprecision(10) << this->rand->random01() << std::endl;\n\t\t//}\n\t\t//fout.clear(); fout.close();\n\n\t\t////\tfor(size_t i=0; i<10; ++i){\n\t\t////\t\tstd::cout<<random_min_max(generator, 0.0, 10.0)<<std::endl;\n\t\t////\t}\n\n\t\t//std::cout << \"Current path is : \" << cwd << std::endl;\n\t\t//for (rsp::spe_name_index_map_t::const_iterator itr = spe_name_index_map.begin(); itr != spe_name_index_map.end(); ++itr) {\n\t\t//\tstd::cout << \"spe name:\\t\" << itr->first << \"\\tindex:\\t\" << itr->second << std::endl;\n\t\t//}\n\n\n\n\t\t////species info\n\t\t//for (size_t i = 0; i < species_network_v.size(); ++i) {\n\t\t//\tstd::cout << species_network_v[i].spe_name << \"\\n\";\n\t\t//\tfor (rsp::spe_component_t::const_iterator itr = species_network_v[i].spe_component.begin(); itr != species_network_v[i].spe_component.end(); ++itr)\n\t\t//\t\tstd::cout << \"\\t-->\" << itr->first << \"\\t\" << itr->second << std::endl;\n\t\t//}\n\n\n\t\t//std::cout << \"\\nnum_vertices: \" << num_vertices << std::endl;\n\t\t//std::cout << \"num_edges: \" << num_edges << std::endl;\n\n\t\t//boost::property_map<GraphContainer, vertex_index_t>::type vertex_id = get(vertex_index, graph);\n\n\t\t//std::cout << \"\\nvertices(g) = \\n\";\n\t\t//std::pair<vertex_iter, vertex_iter> vp;\n\t\t//for (vp = vertices(graph); vp.first != vp.second; ++vp.first) {//for\n\t\t//\tstd::cout << get(vertex_id, *vp.first) << \" \";\n\t\t//\tstd::cout << properties(*vp.first).vertex << std::endl;\n\t\t//}//for\n\t\t//std::cout << std::endl;\n\t\t////vertices properties\n\n\n\t\t//std::cout << \"edges(g) = \\n\";\n\n\t\t//for (edge_range_t er = getEdges(); er.first != er.second; ++er.first) {\n\t\t//\tstd::cout << \"(\" << get(vertex_id, source(*er.first, graph))\n\t\t//\t\t<< \",\" << get(vertex_id, target(*er.first, graph)) << \") \";\n\t\t//\tstd::cout << properties(*er.first).edge_index << \" \" << properties(*er.first).reaction_index <<\n\t\t//\t\t\" \" << properties(*er.first).s_coef_reactant << \" \" << properties(*er.first).s_coef_product << std::endl;\n\t\t//}\n\n\t\t//for (edge_range_t er = getEdges(); er.first != er.second; ++er.first) {\n\t\t//\tstd::cout << \"(\" << species_network_v[get(vertex_id, source(*er.first, graph))].spe_name\n\t\t//\t\t<< \",\" << species_network_v[get(vertex_id, target(*er.first, graph))].spe_name << \") \";\n\t\t//\tstd::cout << properties(*er.first).edge_index << \" \" << properties(*er.first).reaction_index <<\n\t\t//\t\t\" \" << properties(*er.first).s_coef_reactant << \" \" << properties(*er.first).s_coef_product << std::endl;\n\t\t//}\n\n\n\t\t/*\n\t\t * generate Mathematica Format graph input file\n\t\t * DirectedEdge[\"A\", \"B\"]\n\t\t */\n\n\t\t //\tfor (edge_range_t er=getEdges(); er.first!=er.second; ++er.first){\n\t\t //\t\tstd::cout << \"DirectedEdge[\\\"\" <<species_network_v[get(vertex_id, source(*er.first, graph))].spe_name\n\t\t //\t\t\t\t\t\t\t\t\t\t\t\t\t\t<< \"\\\", \\\"\" << species_network_v[get(vertex_id, target(*er.first, graph))].spe_name << \"\\\"]\"<<std::endl;\n\t\t //\t}\n\n\n\t\t //edge_index_map=get(edge_index, graph);\n\t\t //test edge_index and edge number inside graph\n\t\t //edge_iterator is not random access iterator, doesn't support offset dereference operator a[n]\n\t\t //only support a++ or a-- and dereference *a operator\n\t\t//std::cout << \"MISC edge index:\" << std::endl;\n\t\t////\tedge_range_t er_t= getEdges();\n\t\t//size_t edge_index_t = 2;\n\t\t//edge_iter iter_e = this->edge_index_to_edge_iterator[edge_index_t];\n\t\t//std::cout << \"(\" << get(vertex_id, source(*iter_e, graph))\n\t\t//\t<< \",\" << get(vertex_id, target(*iter_e, graph)) << \") \";\n\t\t//std::cout << properties(*iter_e).edge_index << std::endl;\n\n\n\n\t\t////species out reaction info\n\t\t//for (std::size_t i = 0; i < species_network_v.size(); ++i) {\n\t\t//\tstd::cout << i << \"\\t\" << species_network_v[i].reaction_k_index_s_coef_v.size() << std::endl;\n\t\t//}\n\n\t\t////reaction out spe info\n\t\t//std::string atom_followed(\"H\");\n\t\t//for (std::size_t i = 0; i < reaction_network_v.size(); ++i) {\n\t\t//\tstd::cout << i << \"\\t\" << reaction_network_v[i].out_spe_index_weight_v_map[atom_followed].size() << std::endl;\n\t\t//}\n\n\t\t////std::cout << \"haha:\\t\" << std::endl;\n\t\t//for (std::size_t i = 0; i < species_network_v[2].reaction_k_index_s_coef_v.size(); ++i) {\n\t\t//\tstd::cout << species_network_v[2].reaction_k_index_s_coef_v[i].first << \"\\t\" << species_network_v[2].reaction_k_index_s_coef_v[i].second << std::endl;\n\t\t//}\n\n\n\t\t////reaction rates test\n\t\t//std::cout << \"reaction rates:\\n\";\n\t\t//for (auto x : reaction_network_v) {\n\t\t//\tstd::cout << x.reaction_rate << std::endl;\n\t\t//}\n\n\t\t//for (size_t i = 0; i < this->species_network_v.size(); i++)\n\t\t//{\n\t\t//\tstd::cout << i << \"\\t\" << this->species_network_v[i].spe_name << \", \";\n\t\t//\tfor (auto x : this->species_network_v[i].reaction_k_index_s_coef_v)\n\t\t//\t\tstd::cout << x.first << \"\\t\" << x.second << \", \";\n\t\t//\tstd::cout << \"\\n\";\n\t\t//}\n\n\t\trsp::reactionNetwork_chemkin_index_map_t reactionNetwork_chemkin_index_map;\n\t\trsp::relationshipParser::read_reactionNetwork_chemkin_index_map(reactionNetwork_chemkin_index_map, this->cwd + \"/input/chem.out\");\n\n\t\tstd::string atom_followed(\"O\");\n\t\tstd::ofstream fout((this->cwd + std::string(\"/output/species_reaction_index_helper_\") + atom_followed + std::string(\".csv\")).c_str());\n\n\t\tfor (size_t i = 0; i < this->species_network_v.size(); i++)\n\t\t{\n\t\t\tfout << this->species_network_v[i].spe_name << \"\\n\";\n\t\t\tfor (size_t j = 0; j < this->species_network_v.size(); j++)\n\t\t\t{\n\t\t\t\tif (i < j) {\n\t\t\t\t\tauto p = this->get_R_matrix_element(atom_followed, i, j);\n\t\t\t\t\tif (p.size() > 0) {\n\t\t\t\t\t\tfout << \"\\t-->\" << this->species_network_v[j].spe_name << \"\\n\\t\\t\";\n\t\t\t\t\t\tfor (size_t k = 0; k < p.size(); k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//this is edge index, one-step path, a path with only one reaction\n\t\t\t\t\t\t\t//edge index to reaction index\n\t\t\t\t\t\t\tauto iter_e = edge_index_to_edge_iterator[p[k][0]];\n\t\t\t\t\t\t\tauto reaction_index = this->properties(*iter_e).reaction_index;\n\t\t\t\t\t\t\t//fout << this->reaction_network_v[reaction_index].reaction_name;\n\n\t\t\t\t\t\t\tauto reaction_index_in_paper = reactionNetwork_chemkin_index_map[reaction_index].front();\n\n\t\t\t\t\t\t\tif (reaction_index_in_paper > 0)\n\t\t\t\t\t\t\t\tfout << \"R\" << abs(reaction_index_in_paper) - 1;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t/*fout << \"R\" << -1 * (abs(reaction_index_in_paper) - 1);*/\n\t\t\t\t\t\t\t\tfout << \"R\" << abs(reaction_index_in_paper) - 1 << \"*\";\n\n\t\t\t\t\t\t\tif (k != p.size() - 1)\n\t\t\t\t\t\t\t\tfout << \",\";\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tfout << \"\\n\";\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\tfout.clear(); fout.close();\n\n\n\t}\n\n\tvoid superReactionNetwork::print_initial_spe_label_json(std::string filename) const\n\t{\n\t\tstd::ofstream fout((cwd + filename).c_str());\n\t\tfout << \"{\\n\";\n\n\t\tfor (std::size_t i = 0; i < species_network_v.size(); ++i)\n\t\t{\n\t\t\tstd::size_t NofAtoms = 0;\n\t\t\tstd::size_t TypesofAtoms = 0;\n\t\t\tfout << \"\\\"\" << i << \"\\\":\\n\" << \"{\";\n\t\t\tfout << \"\\\"name\\\":\" << \"\\\"\" << species_network_v[i].spe_name << \"\\\",\\n\";\n\t\t\tfout << \"\\\"structure\\\":\" << \"\\\"\" << species_network_v[i].spe_name << \"\\\",\\n\";\n\n\t\t\tfor (rsp::spe_component_t::const_iterator itr = species_network_v[i].spe_component.begin(); itr != species_network_v[i].spe_component.end(); ++itr) {\n\t\t\t\tNofAtoms += itr->second;\n\t\t\t\tif (itr->second != 0)\n\t\t\t\t\tTypesofAtoms += 1;\n\t\t\t}\n\t\t\tfout << \"\\\"TotalNofAtoms\\\":\" << \"\\\"\" << NofAtoms << \"\\\",\\n\";\n\t\t\tfout << \"\\\"TypesofAtoms\\\":\" << \"\\\"\" << TypesofAtoms << \"\\\",\\n\";\n\n\t\t\tfor (rsp::spe_component_t::const_iterator itr = species_network_v[i].spe_component.begin(); itr != species_network_v[i].spe_component.end(); ++itr) {\n\t\t\t\tif (itr->second != 0)\n\t\t\t\t\tfout << \"\\\"\" << itr->first << \"\\\"\" << \":\" << \"\\\"\" << itr->second << \"\\\",\\n\";\n\t\t\t}\n\n\t\t\tfout << \"\\\"TypesofChemicalMoiety\\\":\" << \"\\\"\" << \"\\\",\\n\";\n\n\t\t\tfor (std::size_t j = 0; j < NofAtoms; ++j) {\n\t\t\t\tfout << \"\\\"\\\":\\\"\\\"\";\n\t\t\t\tif (j != NofAtoms - 1)\n\t\t\t\t\tfout << \",\\n\";\n\t\t\t}\n\t\t\tfout << std::endl << \"}\";\n\t\t\tif (i != species_network_v.size() - 1)\n\t\t\t\tfout << \",\";\n\t\t\tfout << \"\\n\";\n\t\t}\n\n\t\tfout << \"}\\n\";\n\t\tfout.close();\n\n\t}\n\n\n\trsp::index_int_t superReactionNetwork::spe_random_pick_next_reaction(vertex_t curr_spe)\n\t{\n\t\t//probability vector\n\t\tstd::vector<double> prob(this->species_network_v[curr_spe].reaction_k_index_s_coef_v.size());\n\t\tfor (std::size_t i = 0; i < prob.size(); ++i) {\n\t\t\tprob[i] = this->species_network_v[curr_spe].reaction_k_index_s_coef_v[i].second* //s_coef_product\n\t\t\t\tthis->reaction_network_v[this->species_network_v[curr_spe].reaction_k_index_s_coef_v[i].first].reaction_rate;\n\t\t}\n\n\t\treturn this->species_network_v[curr_spe].reaction_k_index_s_coef_v[\n\t\t\trand->return_index_randomly_given_probability_vector(prob)\n\t\t].first;\n\t}\n\n\tvertex_t superReactionNetwork::reaction_random_pick_next_spe(rsp::index_int_t reaction_index, std::string atom_followed)\n\t{\n\t\t//probability vector\n\t\tstd::vector<double> prob(this->reaction_network_v[reaction_index].out_spe_index_weight_v_map.at(atom_followed).size());\n\t\tfor (std::size_t i = 0; i < this->reaction_network_v[reaction_index].out_spe_index_weight_v_map.at(atom_followed).size(); ++i) {\n\t\t\t//prob[i] = this->reaction_network_v[reaction_index].out_spe_index_weight_v_map[atom_followed][i].second;\n\n\t\t\tauto s_i = this->reaction_network_v[reaction_index].out_spe_index_weight_v_map.at(atom_followed)[i].first;\n\t\t\tprob[i] = this->reaction_network_v[reaction_index].out_spe_index_branching_ratio_map_map_with_constraint.at(atom_followed).at(s_i);\n\t\t}\n\n\t\treturn this->reaction_network_v[reaction_index].out_spe_index_weight_v_map[atom_followed][\n\t\t\trand->return_index_randomly_given_probability_vector(prob)\n\t\t].first;\n\t}\n\n\tvertex_t reactionNetwork_sr::superReactionNetwork::spe_random_pick_next_spe(rsp::index_int_t curr_spe, std::string atom_followed)\n\t{\n\t\tauto spe_rxn_c1_c2_map = this->sp_all_species_group_rnk->out_species_rxns.at(curr_spe);\n\n\t\tstd::vector<double> prob(spe_rxn_c1_c2_map.size(), 0.0);\n\t\tstd::vector<rsp::index_int_t> spe_index(spe_rxn_c1_c2_map.size(), 0);\n\n\t\tsize_t i = 0;\n\t\tfor (auto s_rxn_c1_c2 : spe_rxn_c1_c2_map)\n\t\t{\n\t\t\tauto next_spe = s_rxn_c1_c2.first;\n\t\t\tspe_index[i] = next_spe;\n\t\t\tprob[i] = spe_spe_branching_ratio(s_rxn_c1_c2.second, -1.0, curr_spe, next_spe, atom_followed, false);\n\n\t\t\t++i;\n\t\t}\n\n\t\treturn spe_index[rand->return_index_randomly_given_probability_vector(prob)];\n\t}\n\n\n\tvoid superReactionNetwork::split_atom_followed_and_pathway(std::string str_in, std::string &atom_followed, std::string &pathway) const\n\t{\n\t\tatom_followed.clear();\n\t\tpathway.clear();\n\n\t\t//find first S, record position\n\t\tauto found = str_in.find(std::string(\"S\"));\n\t\tatom_followed = str_in.substr(0, found);\n\t\t//std::cout<< atom_followed << std::endl;\n\t\tpathway = str_in.substr(found);\n\t\t//std::cout << pathway << std::endl;\n\n\t\t//return true;\n\t}\n\n\tbool superReactionNetwork::parse_pathway_to_vector(std::string pathway_in, std::vector<rsp::index_int_t>& spe_vec, std::vector<rsp::index_int_t>& reaction_vec) const\n\t{\n\t\tspe_vec.resize(0);\n\t\treaction_vec.resize(0);\n\n\t\tconst char* pattern1 = \"(S\\\\d+(?:R[-]?\\\\d+)?)\";\n\t\tboost::regex re1(pattern1);\n\n\t\tboost::sregex_iterator it1(pathway_in.begin(), pathway_in.end(), re1);\n\t\tboost::sregex_iterator end1;\n\t\tstd::vector<std::string> reaction_spe;\n\t\tfor (; it1 != end1; ++it1) {\n\t\t\treaction_spe.push_back(it1->str());\n\t\t}\n\n\t\tconst char* pattern2 = \"S(\\\\d+)(?:R(-?\\\\d+))?\";\n\t\tboost::regex re2(pattern2);\n\n\t\tfor (size_t i = 0; i < reaction_spe.size(); i++)\n\t\t{\n\t\t\tstd::vector<std::string> rxn_s_idx_str;\n\n\t\t\tboost::smatch result2;\n\t\t\tif (boost::regex_search(reaction_spe[i], result2, re2)) {\n\t\t\t\tfor (std::size_t mi = 1; mi < result2.size(); ++mi) {\n\t\t\t\t\tstring s_rxn_idx(result2[mi].first, result2[mi].second);\n\t\t\t\t\trxn_s_idx_str.push_back(s_rxn_idx);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tspe_vec.push_back(boost::lexical_cast<rsp::index_int_t>(rxn_s_idx_str[0]));\n\n\t\t\tif (rxn_s_idx_str[1] != std::string(\"\"))\n\t\t\t\treaction_vec.push_back(boost::lexical_cast<rsp::index_int_t>(rxn_s_idx_str[1]));\n\t\t\telse {\n\t\t\t\t//not the last species\n\t\t\t\tif (i != reaction_spe.size() - 1)\n\t\t\t\t\treaction_vec.push_back(INT_MAX);\n\t\t\t}\n\n\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tint reactionNetwork_sr::superReactionNetwork::get_number_of_elements() const\n\t{\n\t\treturn this->element_v.size();\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::set_reaction_rate(vertex_t i, double reaction_rate)\n\t{\n\t\tthis->reaction_network_v[i].reaction_rate = reaction_rate;\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::set_is_reaction_rate_nonzero_from_setting_file()\n\t{\n\t\tfor (auto key : this->rnk_pt.get_child(\"pathway.non_zero_rate_reaction\")) {\n\t\t\tthis->reaction_network_v[key.second.get_value<std::size_t>()].is_reaction_rate_nonzero = true;\n\t\t}\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::set_is_reaction_rate_nonzero_from_previous_iteration()\n\t{\n\t\t//time, half of pathway end time\n\t\tdouble time = 0.5 * this->rnk_pt.get<double>(\"time.tau\");\n\t\tthis->update_reaction_rate(time);\n\t\tfor (std::size_t i = 0; i < this->reaction_network_v.size(); ++i) {\n\t\t\tif (this->reaction_network_v[i].reaction_rate > 0)\n\t\t\t\tthis->reaction_network_v[i].is_reaction_rate_nonzero = true;\n\t\t\telse\n\t\t\t\tthis->reaction_network_v[i].is_reaction_rate_nonzero = false;\n\t\t}\n\t}\n\n\tdouble superReactionNetwork::prob_spe_will_react_in_a_time_range(double init_time, double end_time, size_t curr_spe)\n\t{\n\t\t//pathway constraint case and current species is on the list\n\t\t//in this case, we are making a assumption, that current species must react\n\t\tif (this->apply_pathway_constraint == true && this->sp_pathway_constarint_rnk->must_react_species_set.count(curr_spe) > 0) {\n\t\t\treturn 1.0;\n\t\t}\n\n\t\t// ############################################################################\n\t\t// don't apply_pathway_constraint case or current speices don't have to react\n\t\t// ############################################################################\n\n\t\t////set pathway end time\n\t\t//set_pathway_end_time(pathway_end_time);\n\t\tset_spe_prob_max_at_a_time(init_time, end_time, curr_spe);\n\t\treturn species_network_v[curr_spe].prob_max;\n\n\t}\n\n\tdouble superReactionNetwork::spe_out_by_a_reaction_branching_ratio(rsp::index_int_t curr_spe, rsp::index_int_t next_reaction)\n\t{\n\n\t\t//pathway constraint case and current species is on the list\n\t\tif (this->apply_pathway_constraint == true && this->sp_pathway_constarint_rnk->species_sink_reaction_set_map.count(curr_spe) > 0) {\n\t\t\tif (this->sp_pathway_constarint_rnk->species_sink_through_reaction_constraint == false)\n\t\t\t\treturn 0.0;\n\n\t\t\t//current reaction not on the list\n\t\t\tif (this->sp_pathway_constarint_rnk->species_sink_reaction_set_map.at(curr_spe).count(next_reaction) == 0)\n\t\t\t\treturn 0.0;\n\n\t\t\t// calculate this actually\n\t\t\tdouble prob_total = 0.0, prob_target_reaction = 0.0;\n\t\t\tfor (std::size_t i = 0; i < this->species_network_v[curr_spe].reaction_k_index_s_coef_v.size(); ++i) {//for\n\t\t\t\tauto r_idx = this->species_network_v[curr_spe].reaction_k_index_s_coef_v[i].first;\n\t\t\t\t//found next reaction\n\t\t\t\tif (r_idx == next_reaction) {\n\t\t\t\t\tprob_target_reaction = this->species_network_v[curr_spe].reaction_k_index_s_coef_v[i].second* //s_coef_product\n\t\t\t\t\t\tthis->reaction_network_v[r_idx].reaction_rate; //reaction rate\n\t\t\t\t\tprob_total += prob_target_reaction;\n\t\t\t\t}\n\t\t\t\t//not found next reaction\n\t\t\t\telse {\n\t\t\t\t\t// not a candidate reaction\n\t\t\t\t\tif (this->sp_pathway_constarint_rnk->species_sink_reaction_set_map.at(curr_spe).count(r_idx) == 0)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tprob_total += this->species_network_v[curr_spe].reaction_k_index_s_coef_v[i].second* //s_coef_product\n\t\t\t\t\t\tthis->reaction_network_v[r_idx].reaction_rate; //reaction rate\n\t\t\t\t}\n\t\t\t}//for\n\n\t\t\tdouble reaction_branching_ratio;\n\t\t\t//it prob_total ==0.0, it must because I set it to be zero artificially\n\t\t\t//it depends\n\t\t\tif (prob_total == 0.0) {\n\t\t\t\treaction_branching_ratio = 1.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treaction_branching_ratio = prob_target_reaction / prob_total;\n\t\t\t}\n\n\t\t\treturn reaction_branching_ratio;\n\n\t\t} // apply_pathway_constraint and current species is on the list\n\n\n\t\t// ############################################################################\n\t\t// don't apply_pathway_constraint case or current speices is not on the list\n\t\t// ############################################################################\n\n\t\t//probability\n\t\tdouble prob_total = 0.0, prob_target_reaction = 0.0;\n\t\tfor (std::size_t i = 0; i < this->species_network_v[curr_spe].reaction_k_index_s_coef_v.size(); ++i) {//for\n\t\t\tauto r_idx = this->species_network_v[curr_spe].reaction_k_index_s_coef_v[i].first;\n\t\t\t//found next reaction\n\t\t\tif (r_idx == next_reaction) {\n\t\t\t\tprob_target_reaction = this->species_network_v[curr_spe].reaction_k_index_s_coef_v[i].second* //s_coef_product\n\t\t\t\t\tthis->reaction_network_v[r_idx].reaction_rate; //reaction rate\n\t\t\t\tprob_total += prob_target_reaction;\n\t\t\t}\n\t\t\t//not found next reaction\n\t\t\telse {\n\t\t\t\tprob_total += this->species_network_v[curr_spe].reaction_k_index_s_coef_v[i].second* //s_coef_product\n\t\t\t\t\tthis->reaction_network_v[r_idx].reaction_rate; //reaction rate\n\t\t\t}\n\t\t}//for\n\n\t\tdouble reaction_branching_ratio;\n\t\t//it prob_total ==0.0, it must because I set it to be zero artificially\n\t\t//it depends\n\t\tif (prob_total == 0.0) {\n\t\t\treaction_branching_ratio = 1.0;\n\t\t}\n\t\telse {\n\t\t\treaction_branching_ratio = prob_target_reaction / prob_total;\n\t\t}\n\n\t\treturn reaction_branching_ratio;\n\t}\n\n\tstd::pair<double, double> superReactionNetwork::reaction_spe_branching_ratio_separately(double reaction_time, rsp::index_int_t curr_spe, rsp::index_int_t next_reaction, rsp::index_int_t next_spe, std::string atom_followed, bool update_reaction_rate)\n\t{\n\t\t//update rate in the reaction network\n\t\tif (update_reaction_rate == true)\n\t\t\tthis->update_reaction_rate(reaction_time, curr_spe);\n\n\t\tdouble reaction_branching_ratio = spe_out_by_a_reaction_branching_ratio(curr_spe, next_reaction);\n\n\t\tdouble spe_branching_ratio = 0.0;\n\t\t//next species found\n\t\tif (this->reaction_network_v[next_reaction].out_spe_index_branching_ratio_map_map_with_constraint[atom_followed].count(next_spe) > 0)\n\t\t\tspe_branching_ratio = this->reaction_network_v[next_reaction].out_spe_index_branching_ratio_map_map_with_constraint[atom_followed].at(next_spe);\n\n\t\treturn std::make_pair(reaction_branching_ratio, spe_branching_ratio);\n\t}\n\n\tdouble reactionNetwork_sr::superReactionNetwork::reaction_spe_branching_ratio(double reaction_time, rsp::index_int_t curr_spe, rsp::index_int_t next_reaction, rsp::index_int_t next_spe, std::string atom_followed, bool update_reaction_rate)\n\t{\n\t\t//reaction branching ratio\n\t\tdouble rbr = 0.0;\n\t\t//species branching ratio\n\t\tdouble sbr = 0.0;\n\t\tstd::tie(rbr, sbr) = reaction_spe_branching_ratio_separately(reaction_time, curr_spe, next_reaction, next_spe, atom_followed, update_reaction_rate);\n\n\t\treturn rbr * sbr;\n\t}\n\n\tdouble reactionNetwork_sr::superReactionNetwork::spe_spe_branching_ratio(const std::vector<species_group_sr::rxn_c1_c2>& rxn_c1_c2_vec,\n\t\tdouble reaction_time, rsp::index_int_t curr_spe, rsp::index_int_t next_spe, std::string atom_followed, bool update_reaction_rate)\n\t{\n\t\tdouble ratio_tmp = 0.0;\n\t\tfor (auto rxn_c1_c2 : rxn_c1_c2_vec) {\n\t\t\tauto reaction_index = rxn_c1_c2.r_idx;\n\t\t\t//whether to update reaction rates, is deferred to sub-routine to decice\n\t\t\tratio_tmp += reaction_spe_branching_ratio(reaction_time, curr_spe, reaction_index, next_spe, atom_followed, update_reaction_rate);\n\t\t}\n\t\treturn ratio_tmp;\n\t}\n\n\twhen_where_t superReactionNetwork::chattering_group_move_one_step(int chattering_group_id, double time, std::string & curr_pathway, std::string atom_followed)\n\t{\n\t\t//totally condense chattering, for A<=>B, make new species Z, adding up all internal possiblities\n\t\twhen_where_t when_where;\n\n\t\t//actually move two steps, (1) from one chattering species to another chattering species\n\t\t//(2) from chattering species to the outside\n\t\t/*step 1*/\n\t\tauto next_vertex1 = this->inside_chattering_group_random_pick_next_spe(chattering_group_id, time);\n\n\t\t//if this->condense_chatterings == true \n\t\t//Just don't record chattering group as a reaction, don't record the internal species\n\t\tif (this->condense_chatterings == false) {\n\t\t\tcurr_pathway += \"R\";\n\t\t\t//negative reaction index represent chattering group number\n\t\t\t//since there is no -1 * 0, which means, to the first chattering_group_id 0, negative 0 is still 0,\n\t\t\t//negative sign will not show on pathway string, here we make it to be -1*(chattering_group_id+1)\n\t\t\tcurr_pathway += boost::lexical_cast<std::string>(-1 * (chattering_group_id + rsp::INDICATOR));\n\n\t\t\tcurr_pathway += \"S\";\n\t\t\tcurr_pathway += boost::lexical_cast<std::string>(next_vertex1);\n\t\t\t/*step 1*/\n\t\t}\n\n\t\t/*step 2*/\n\t\t//update rate in the reaction network\n\t\tupdate_reaction_rate(time, next_vertex1);\n\n\t\trsp::index_int_t next_reaction_index2 = spe_random_pick_next_reaction(next_vertex1);\n\t\t//random pick next spe\n\t\tvertex_t next_vertex2 = reaction_random_pick_next_spe(next_reaction_index2, atom_followed);\n\n\t\tcurr_pathway += \"R\";\n\t\tcurr_pathway += boost::lexical_cast<std::string>(next_reaction_index2);\n\n\t\tcurr_pathway += \"S\";\n\t\tcurr_pathway += boost::lexical_cast<std::string>(next_vertex2);\n\n\t\twhen_where.first = time;\n\t\twhen_where.second = next_vertex2;\n\t\t/*step 2*/\n\n\t\treturn when_where;\n\t}\n\n\twhen_where_t superReactionNetwork::pathway_move_one_step(double time, vertex_t curr_spe, std::string & curr_pathway, std::string atom_followed)\n\t{\n\t\t//Monte-Carlo simulation\n\t\t//generate the random number u_1 between 0 and 1.0\n\t\tdouble u_1 = 0.0;\n\t\tdo {\n\t\t\tu_1 = rand->random01();\n\t\t} while (u_1 == 1.0);\n\t\twhen_where_t when_where(0.0, curr_spe);\n\n\n\t\tint chattering_group_id = this->species_network_v[curr_spe].chattering_group_id;\n\t\t//none chattering case\n\t\tif (chattering_group_id == -1) {\n\t\t\ttime = reaction_time_from_importance_sampling_without_cutoff(time, curr_spe, u_1);\n\t\t\tif (time > this->absolute_end_t) {\n\t\t\t\t//if curr_vertex is a terminal species, should return here\n\t\t\t\twhen_where.first = time;\n\t\t\t\treturn when_where;\n\t\t\t}\n\n\t\t\t//update rate in the reaction network\n\t\t\tupdate_reaction_rate(time, curr_spe);\n\t\t\trsp::index_int_t next_reaction_index = spe_random_pick_next_reaction(curr_spe);\n\t\t\t//random pick next spe\n\t\t\tvertex_t next_vertex = reaction_random_pick_next_spe(next_reaction_index, atom_followed);\n\n\t\t\tcurr_pathway += \"R\";\n\t\t\tcurr_pathway += boost::lexical_cast<std::string>(next_reaction_index);\n\n\t\t\tcurr_pathway += \"S\";\n\t\t\tcurr_pathway += boost::lexical_cast<std::string>(next_vertex);\n\n\t\t\twhen_where.first = time;\n\t\t\twhen_where.second = next_vertex;\n\n\t\t\treturn when_where;\n\t\t}\n\t\t//chattering case\n\t\t//if it is chattering, and it is the first time reach chattering group, \"move one step\"\n\t\t//is actually move two steps, add reaction \"G_{group index}\"\n\t\telse {\n\t\t\t//calculate time from total drc of chattering species\n\t\t\ttime = chattering_group_reaction_time_from_importance_sampling_without_cutoff(time, chattering_group_id, u_1);\n\n\t\t\t//time out of range, stop and return\n\t\t\tif (time > this->absolute_end_t) {\n\t\t\t\twhen_where.first = time;\n\t\t\t\treturn when_where;\n\t\t\t}\n\n\t\t\twhen_where = this->chattering_group_move_one_step(chattering_group_id, time, curr_pathway, atom_followed);\n\n\t\t\treturn when_where;\n\t\t}\n\n\n\t}\n\n\tstd::string superReactionNetwork::pathway_sim_once(double init_time, double end_time, vertex_t init_spe, std::string atom_followed)\n\t{\n\t\t//set the pathway end time\n\t\tset_absolute_end_t(end_time);\n\t\tstd::string curr_pathway;\n\t\twhen_where_t when_where(init_time, init_spe);\n\n\t\t//initial species\n\t\tcurr_pathway += \"S\";\n\t\tcurr_pathway += boost::lexical_cast<std::string>(init_spe);\n\n\t\twhile (when_where.first < absolute_end_t) {\n\t\t\twhen_where = pathway_move_one_step(when_where.first, when_where.second, curr_pathway, atom_followed);\n\t\t}\n\n\t\treturn curr_pathway;\n\t}\n\n\twhen_where_t superReactionNetwork::species_chattering_group_move_one_step(int chattering_group_id, double time, std::string & curr_pathway, std::string atom_followed)\n\t{\n\t\t//totally condense chattering, for A<=>B, make new species Z, adding up all internal possiblities\n\t\twhen_where_t when_where;\n\n\t\t//actually move two steps, (1) from one chattering species to another chattering species\n\t\t//(2) from chattering species to the outside\n\t\t/*step 1*/\n\t\tauto next_vertex1 = this->inside_chattering_group_random_pick_next_spe(chattering_group_id, time);\n\n\t\t//if this->condense_chatterings == true \n\t\t//Just don't record chattering group as a reaction, don't record the internal species\n\t\tif (this->condense_chatterings == false) {\n\t\t\tcurr_pathway += \"R\";\n\t\t\t//negative reaction index represent chattering group number\n\t\t\t//since there is no -1 * 0, which means, to the first chattering_group_id 0, negative 0 is still 0,\n\t\t\t//negative sign will not show on pathway string, here we make it to be -1*(chattering_group_id+1)\n\t\t\tcurr_pathway += boost::lexical_cast<std::string>(-1 * (chattering_group_id + rsp::INDICATOR));\n\n\t\t\tcurr_pathway += \"S\";\n\t\t\tcurr_pathway += boost::lexical_cast<std::string>(next_vertex1);\n\t\t\t/*step 1*/\n\t\t}\n\n\t\t/*step 2*/\n\t\t//update rate in the reaction network\n\t\tupdate_reaction_rate(time, next_vertex1);\n\n\t\t//random pick next spe\n\t\tvertex_t next_vertex2 = spe_random_pick_next_spe(next_vertex1, atom_followed);\n\n\t\tcurr_pathway += \"S\";\n\t\tcurr_pathway += boost::lexical_cast<std::string>(next_vertex2);\n\n\t\twhen_where.first = time;\n\t\twhen_where.second = next_vertex2;\n\t\t/*step 2*/\n\n\t\treturn when_where;\n\t}\n\n\twhen_where_t reactionNetwork_sr::superReactionNetwork::species_pathway_move_one_step(double time, vertex_t curr_spe, std::string & curr_pathway, std::string atom_followed)\n\t{\n\t\t//Monte-Carlo simulation\n\t\t//generate the random number u_1 between 0 and 1.0\n\t\tdouble u_1 = 0.0;\n\t\tdo {\n\t\t\tu_1 = rand->random01();\n\t\t} while (u_1 == 1.0);\n\t\twhen_where_t when_where(0.0, curr_spe);\n\n\n\t\tint chattering_group_id = this->species_network_v[curr_spe].chattering_group_id;\n\t\t//none chattering case\n\t\tif (chattering_group_id == -1) {\n\t\t\ttime = reaction_time_from_importance_sampling_without_cutoff(time, curr_spe, u_1);\n\t\t\tif (time > this->absolute_end_t) {\n\t\t\t\t//if curr_vertex is a terminal species, should return here\n\t\t\t\twhen_where.first = time;\n\t\t\t\treturn when_where;\n\t\t\t}\n\n\t\t\t//update rate in the reaction network\n\t\t\tupdate_reaction_rate(time, curr_spe);\n\t\t\t//random pick next spe\n\t\t\tvertex_t next_vertex = spe_random_pick_next_spe(curr_spe, atom_followed);\n\n\t\t\tcurr_pathway += \"S\";\n\t\t\tcurr_pathway += boost::lexical_cast<std::string>(next_vertex);\n\n\t\t\twhen_where.first = time;\n\t\t\twhen_where.second = next_vertex;\n\n\t\t\treturn when_where;\n\t\t}\n\t\t//chattering case\n\t\t//if it is chattering, and it is the first time reach chattering group, \"move one step\"\n\t\t//is actually move two steps, add reaction \"G_{group index}\"\n\t\telse {\n\t\t\t//calculate time from total drc of chattering species\n\t\t\ttime = chattering_group_reaction_time_from_importance_sampling_without_cutoff(time, chattering_group_id, u_1);\n\n\t\t\t//time out of range, stop and return\n\t\t\tif (time > this->absolute_end_t) {\n\t\t\t\twhen_where.first = time;\n\t\t\t\treturn when_where;\n\t\t\t}\n\n\t\t\twhen_where = this->species_chattering_group_move_one_step(chattering_group_id, time, curr_pathway, atom_followed);\n\n\t\t\treturn when_where;\n\t\t}\n\n\t}\n\n\tstd::string reactionNetwork_sr::superReactionNetwork::species_pathway_sim_once(double init_time, double end_time, vertex_t init_spe, std::string atom_followed)\n\t{\n\t\t//set the pathway end time\n\t\tset_absolute_end_t(end_time);\n\t\tstd::string curr_pathway;\n\t\twhen_where_t when_where(init_time, init_spe);\n\n\t\t//initial species\n\t\tcurr_pathway += \"S\";\n\t\tcurr_pathway += boost::lexical_cast<std::string>(init_spe);\n\n\t\twhile (when_where.first < absolute_end_t) {\n\t\t\twhen_where = species_pathway_move_one_step(when_where.first, when_where.second, curr_pathway, atom_followed);\n\t\t}\n\n\t\treturn curr_pathway;\n\t}\n\n\tstd::pair<double, double> superReactionNetwork::pathway_prob_sim_move_one_step(double &when_time, vertex_t curr_spe, rsp::index_int_t next_reaction, vertex_t next_spe, std::string atom_followed)\n\t{\n\t\tif (when_time >= (absolute_end_t - INFINITESIMAL_DT)) {\n\t\t\t//return std::make_pair(1.0, 1.0);\n\t\t\treturn std::make_pair(0.0, 0.0);\n\t\t}\n\n\t\tthis->set_spe_prob_max_at_a_time(when_time, absolute_end_t, curr_spe);\n\n\t\tdouble u_1;\n\t\tif (species_network_v[curr_spe].prob_max > 0.0) {\n\t\t\tu_1 = rand->random_min_max(0, species_network_v[curr_spe].prob_max);\n\t\t}\n\t\telse {\n\t\t\tu_1 = 0.0;\n\t\t\t//u_1 = INFINITESIMAL_DT;\n\t\t}\n\n\t\twhen_time = reaction_time_from_importance_sampling(when_time, curr_spe, u_1);\n\n\t\t//pathway_prob *= reaction_spe_branching_ratio(when_time, curr_spe, next_reaction, next_spe, atom_followed);\n\t\treturn reaction_spe_branching_ratio_separately(when_time, curr_spe, next_reaction, next_spe, atom_followed);\n\n\t}\n\n\tbool superReactionNetwork::chattering_group_pathway_prob_sim_move_one_step(int chattering_group_id, const std::vector<rsp::index_int_t> &spe_vec, const std::vector<rsp::index_int_t> &reaction_vec, std::size_t &i, double &when_time, const double end_time, double & pathway_prob, std::string atom_followed, bool spe_branching)\n\t{\n\t\t//add time delay first, regenerate random number, inverse to get exact time, get steady state time first\n\t\t//then calculate steady state ratios\n\t\tdouble chattering_group_prob = prob_chattering_group_will_react_in_a_time_range(when_time, end_time, chattering_group_id);\n\t\tpathway_prob *= chattering_group_prob;\n\n\t\t//avoid problems around boundary\n\t\tif (when_time < (absolute_end_t - INFINITESIMAL_DT)) {\n\t\t\tdouble u_1 = 1.0;\n\t\t\tif (chattering_group_prob > 0.0) {\n\t\t\t\tu_1 = rand->random_min_max(0, chattering_group_prob);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tu_1 = 0.0;\n\t\t\t\t//u_1 = INFINITESIMAL_DT;\n\t\t\t}\n\n\t\t\twhen_time = chattering_group_reaction_time_from_importance_sampling_without_cutoff(when_time, chattering_group_id, u_1);\n\n\t\t\tif (this->condense_chatterings == true) {\n\t\t\t\t/*step 1*/\n\t\t\t\t//based on drc at this time, calculate probability going out by that direction\n\t\t\t\tauto drc_prob_unnormalized = this->chattering_group_probability_vector(chattering_group_id, when_time);\n\t\t\t\tdouble drc_prob_sum = std::accumulate(drc_prob_unnormalized.begin(), drc_prob_unnormalized.end(), 0.0);\n\t\t\t\t//make sure there is at least one direction out, there is no, dead end, return 0.0 probability\n\t\t\t\tif (drc_prob_sum <= 0.0) {\n\t\t\t\t\tpathway_prob = 0.0;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\n\t\t\t\tdouble chattering_group_total_prob = 0.0;\n\t\t\t\t//don't know the species leaving the chattering group, gonna search\n\t\t\t\tfor (auto s_i : this->sp_chattering_rnk->species_chattering_group_mat[chattering_group_id]) {\n\t\t\t\t\t//fot species s_i, search wether it has desired reaction as a sink reaction\n\t\t\t\t\tfor (auto r_coef : this->species_network_v[s_i].reaction_k_index_s_coef_v) {\n\t\t\t\t\t\tif (r_coef.first == reaction_vec[i]) {\n\t\t\t\t\t\t\tauto tmp = drc_prob_unnormalized[this->sp_chattering_rnk->spe_idx_2_chattering_group_id_idx[s_i].second] / drc_prob_sum;\n\t\t\t\t\t\t\tauto r_s_br = reaction_spe_branching_ratio_separately(when_time, s_i, reaction_vec[i], spe_vec[i + 1], atom_followed);\n\t\t\t\t\t\t\ttmp *= r_s_br.first;\n\t\t\t\t\t\t\tif (spe_branching == true)\n\t\t\t\t\t\t\t\ttmp *= r_s_br.second;\n\t\t\t\t\t\t\tchattering_group_total_prob += tmp;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tpathway_prob *= chattering_group_total_prob;\n\t\t\t\t//move one step in this case\n\t\t\t\ti += 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t/*step 1*/\n\t\t\t\t//based on drc at this time, calculate probability going out by that direction\n\t\t\t\tauto drc_prob_unnormalized = this->chattering_group_probability_vector(chattering_group_id, when_time);\n\t\t\t\tdouble drc_prob_sum = std::accumulate(drc_prob_unnormalized.begin(), drc_prob_unnormalized.end(), 0.0);\n\t\t\t\t//make sure there is at least one direction out, there is no, dead end, return 0.0 probability\n\t\t\t\tif (drc_prob_sum <= 0.0)\n\t\t\t\t\treturn false;\n\t\t\t\t//notice out species is spe_vec[i + 1], next_species1\n\t\t\t\tpathway_prob *= drc_prob_unnormalized[this->sp_chattering_rnk->spe_idx_2_chattering_group_id_idx[spe_vec[i + 1]].second] / drc_prob_sum;\n\t\t\t\t/*step 1*/\n\t\t\t\t/*step 2*/\n\t\t\t\tauto r_s_br = reaction_spe_branching_ratio_separately(when_time, spe_vec[i + 1], reaction_vec[i + 1], spe_vec[i + 2], atom_followed);\n\t\t\t\tpathway_prob *= r_s_br.first;\n\t\t\t\tif (spe_branching == true)\n\t\t\t\t\tpathway_prob *= r_s_br.second;\n\t\t\t\t/*step 2*/\n\t\t\t\t//move two steps actually\n\t\t\t\ti += 2;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}//boundary time problem\n\t\telse {\n\t\t\t// gotta to change i\n\t\t\tif (this->condense_chatterings == true) {\n\t\t\t\t//move one step actually\n\t\t\t\ti += 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//move two steps instead\n\t\t\t\ti += 2;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tdouble superReactionNetwork::pathway_prob_input_pathway_sim_once(double const init_time, const double end_time, const std::vector<rsp::index_int_t> &spe_vec, const std::vector<rsp::index_int_t> &reaction_vec, std::string atom_followed, bool spe_branching, bool terminal_sp)\n\t{\n\t\t//set pathway end time\n\t\tset_absolute_end_t(end_time);\n\n\t\t//basically, we assume there must be a reaction at the beginning, so should multiply be the 1-P_min(tau=0|t;S^{0})\n\t\tdouble pathway_prob = 1.0;\n\t\t//save one step reaction branching ratio and species branching ratio\n\t\tdouble r_br = 1.0, s_br = 1.0;\n\t\tdouble when_time = init_time;\n\n\t\t//start from the first reaction\n\t\tfor (size_t i = 0; i < spe_vec.size() - 1;)\n\t\t{\n\t\t\tint chattering_group_id = this->species_network_v[spe_vec[i]].chattering_group_id;\n\n\t\t\t//none-chattering reaction\n\t\t\tif (chattering_group_id == -1) {\n\t\t\t\tpathway_prob *= prob_spe_will_react_in_a_time_range(when_time, end_time, spe_vec[i]);\n\t\t\t\tstd::tie(r_br, s_br) = pathway_prob_sim_move_one_step(when_time, spe_vec[i], reaction_vec[i], spe_vec[i + 1], atom_followed);\n\n\t\t\t\tpathway_prob *= r_br;\n\n\t\t\t\tif (spe_branching == true)\n\t\t\t\t\tpathway_prob *= s_br;\n\n\t\t\t\t//move one step\n\t\t\t\t++i;\n\t\t\t}\n\t\t\t//chattering reaction, chattering case\n\t\t\telse {\n\t\t\t\tauto good_chattering_prob = this->chattering_group_pathway_prob_sim_move_one_step(chattering_group_id, spe_vec, reaction_vec, i, when_time, end_time, pathway_prob, atom_followed, spe_branching);\n\t\t\t\tif (!good_chattering_prob)\n\t\t\t\t\treturn 0.0;\n\t\t\t}//if chattering case\n\n\t\t}\n\n\t\t//got to multiply by P_min or says (1-P_max)\n\t\tset_spe_prob_max_at_a_time(when_time, end_time, spe_vec.back());\n\n\t\tif (terminal_sp == true)\n\t\t\tpathway_prob *= (1 - species_network_v[spe_vec.back()].prob_max);\n\n\t\treturn pathway_prob;\n\t}\n\n\n\tdouble reactionNetwork_sr::superReactionNetwork::species_pathway_prob_sim_move_one_step(double &when_time, vertex_t curr_spe, vertex_t next_spe, std::string atom_followed)\n\t{\n\t\tif (when_time >= (absolute_end_t - INFINITESIMAL_DT)) {\n\t\t\t//return 1.0;\n\t\t\treturn 0.0;\n\t\t}\n\n\t\tthis->set_spe_prob_max_at_a_time(when_time, absolute_end_t, curr_spe);\n\n\t\tdouble u_1;\n\t\tif (species_network_v[curr_spe].prob_max > 0.0) {\n\t\t\tu_1 = rand->random_min_max(0, species_network_v[curr_spe].prob_max);\n\t\t}\n\t\telse {\n\t\t\tu_1 = 0.0;\n\t\t\t//u_1 = INFINITESIMAL_DT;\n\t\t}\n\n\t\twhen_time = reaction_time_from_importance_sampling(when_time, curr_spe, u_1);\n\n\t\t//pathway_prob *= spe_spe_branching_ratio(this->sp_all_species_group_rnk->out_species_rxns.at(curr_spe).at(next_spe),\n\t\t//\twhen_time, curr_spe, next_spe, atom_followed, true);\n\n\t\treturn spe_spe_branching_ratio(this->sp_all_species_group_rnk->out_species_rxns.at(curr_spe).at(next_spe),\n\t\t\twhen_time, curr_spe, next_spe, atom_followed, true);\n\t}\n\n\tbool superReactionNetwork::species_chattering_group_pathway_prob_sim_move_one_step(int chattering_group_id, const std::vector<rsp::index_int_t>& spe_vec, std::size_t & i, double & when_time, const double end_time, double & pathway_prob, std::string atom_followed)\n\t{\n\t\t//add time delay first, regenerate random number, inverse to get exact time, get steady state time first\n\t\t//then calculate steady state ratios\n\t\tdouble chattering_group_prob = prob_chattering_group_will_react_in_a_time_range(when_time, end_time, chattering_group_id);\n\t\tpathway_prob *= chattering_group_prob;\n\n\t\t//avoid problems around boundary\n\t\tif (when_time < (end_time - INFINITESIMAL_DT)) {\n\t\t\tdouble u_1 = 1.0;\n\t\t\tif (chattering_group_prob > 0.0) {\n\t\t\t\tu_1 = rand->random_min_max(0, chattering_group_prob);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tu_1 = 0.0;\n\t\t\t\t//u_1 = INFINITESIMAL_DT;\n\t\t\t}\n\n\t\t\twhen_time = chattering_group_reaction_time_from_importance_sampling_without_cutoff(when_time, chattering_group_id, u_1);\n\n\t\t\tif (this->condense_chatterings == true) {\n\t\t\t\t/*step 1*/\n\t\t\t\t//based on drc at this time, calculate probability going out by that direction\n\t\t\t\tauto drc_prob_unnormalized = this->chattering_group_probability_vector(chattering_group_id, when_time);\n\t\t\t\tdouble drc_prob_sum = std::accumulate(drc_prob_unnormalized.begin(), drc_prob_unnormalized.end(), 0.0);\n\t\t\t\t//make sure there is at least one direction out, there is no, dead end, return 0.0 probability\n\t\t\t\tif (drc_prob_sum <= 0.0) {\n\t\t\t\t\tpathway_prob = 0.0;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\n\t\t\t\tdouble chattering_group_total_prob = 0.0;\n\t\t\t\t//don't know the species leaving the chattering group, gonna search\n\t\t\t\tfor (auto s_i : this->sp_chattering_rnk->species_chattering_group_mat[chattering_group_id]) {\n\t\t\t\t\t//fot species s_i, search wether it has desired species as a sink species\n\t\t\t\t\tif (this->sp_all_species_group_rnk->out_species_rxns.at(s_i).count(spe_vec[i + 1]) >= 1) {\n\t\t\t\t\t\tauto tmp = drc_prob_unnormalized[this->sp_chattering_rnk->spe_idx_2_chattering_group_id_idx[s_i].second] / drc_prob_sum;\n\t\t\t\t\t\ttmp *= spe_spe_branching_ratio(this->sp_all_species_group_rnk->out_species_rxns.at(s_i).at(spe_vec[i + 1]),\n\t\t\t\t\t\t\twhen_time, s_i, spe_vec[i + 1], atom_followed, true);\n\t\t\t\t\t\tchattering_group_total_prob += tmp;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpathway_prob *= chattering_group_total_prob;\n\t\t\t\t//move one step in this case\n\t\t\t\ti += 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t/*step 1*/\n\t\t\t\t//based on drc at this time, calculate probability going out by that direction\n\t\t\t\tauto drc_prob_unnormalized = this->chattering_group_probability_vector(chattering_group_id, when_time);\n\t\t\t\tdouble drc_prob_sum = std::accumulate(drc_prob_unnormalized.begin(), drc_prob_unnormalized.end(), 0.0);\n\t\t\t\t//make sure there is at least one direction out, there is no, dead end, return 0.0 probability\n\t\t\t\tif (drc_prob_sum <= 0.0)\n\t\t\t\t\treturn false;\n\t\t\t\t//notice out species is spe_vec[i + 1], next_species1\n\t\t\t\tpathway_prob *= drc_prob_unnormalized[this->sp_chattering_rnk->spe_idx_2_chattering_group_id_idx[spe_vec[i + 1]].second] / drc_prob_sum;\n\t\t\t\t/*step 1*/\n\n\t\t\t\t/*step 2*/\n\t\t\t\tpathway_prob *= spe_spe_branching_ratio(this->sp_all_species_group_rnk->out_species_rxns.at(spe_vec[i + 1]).at(spe_vec[i + 2]),\n\t\t\t\t\twhen_time, spe_vec[i + 1], spe_vec[i + 2], atom_followed, true);\n\t\t\t\t/*step 2*/\n\t\t\t\t//move two steps actually\n\t\t\t\ti += 2;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}//boundary time problem\n\t\telse {\n\t\t\t// gotta to change i\n\t\t\tif (this->condense_chatterings == true) {\n\t\t\t\t//move one step actually\n\t\t\t\ti += 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//move two steps instead\n\t\t\t\ti += 2;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tdouble reactionNetwork_sr::superReactionNetwork::species_pathway_prob_input_pathway_sim_once(const double init_time, const double end_time, const std::vector<rsp::index_int_t>& spe_vec, const std::vector<rsp::index_int_t>& reaction_vec, std::string atom_followed)\n\t{\n\t\t//set pathway end time\n\t\tset_absolute_end_t(end_time);\n\n\t\t//basically, we assume there must be a reaction at the beginning, so should multiply be the 1-P_min(tau=0|t;S^{0})\n\t\tdouble pathway_prob = 1.0;\n\t\tdouble when_time = init_time;\n\n\t\t//start from the first reaction\n\t\tfor (size_t i = 0; i < spe_vec.size() - 1;)\n\t\t{\n\t\t\tint chattering_group_id = this->species_network_v[spe_vec[i]].chattering_group_id;\n\n\t\t\t//none-chattering reaction\n\t\t\tif (chattering_group_id == -1) {\n\t\t\t\tpathway_prob *= prob_spe_will_react_in_a_time_range(when_time, end_time, spe_vec[i]);\n\t\t\t\tpathway_prob *= species_pathway_prob_sim_move_one_step(when_time, spe_vec[i], spe_vec[i + 1], atom_followed);\n\t\t\t\t//move one step\n\t\t\t\t++i;\n\t\t\t}\n\t\t\t//chattering reaction, chattering case\n\t\t\telse {\n\t\t\t\tauto good_chattering_group_prob = this->species_chattering_group_pathway_prob_sim_move_one_step(chattering_group_id, spe_vec, i, when_time, end_time, pathway_prob, atom_followed);\n\t\t\t\tif (!good_chattering_group_prob)\n\t\t\t\t\treturn 0.0;\n\t\t\t}//if chattering case\n\n\t\t}\n\n\t\t//got to multiply by P_min or says (1-P_max)\n\t\tset_spe_prob_max_at_a_time(when_time, end_time, spe_vec.back());\n\n\t\tpathway_prob *= (1 - species_network_v[spe_vec.back()].prob_max);\n\n\t\treturn pathway_prob;\n\t}\n\n\n\tdouble superReactionNetwork::pathway_AT_sim_move_one_step(double when_time, vertex_t curr_spe)\n\t{\n\t\tif (when_time >= (absolute_end_t - INFINITESIMAL_DT)) {\n\t\t\treturn when_time;\n\t\t}\n\n\t\tthis->set_spe_prob_max_at_a_time(when_time, absolute_end_t, curr_spe);\n\n\t\tdouble u_1;\n\t\tif (species_network_v[curr_spe].prob_max > 0.0) {\n\t\t\tu_1 = rand->random_min_max(0, species_network_v[curr_spe].prob_max);\n\t\t}\n\t\telse {\n\t\t\tu_1 = 0.0;\n\t\t\t//u_1 = INFINITESIMAL_DT;\n\t\t}\n\n\t\twhen_time = reaction_time_from_importance_sampling(when_time, curr_spe, u_1);\n\n\t\treturn when_time;\n\t}\n\n\tdouble superReactionNetwork::pathway_AT_input_pathway_sim_once(const double init_time, const double end_time, const std::vector<rsp::index_int_t>& spe_vec, const std::vector<rsp::index_int_t>& reaction_vec)\n\t{\n\t\t//set pathway end time\n\t\tset_absolute_end_t(end_time);\n\n\t\t//basically, we assume there must be a reaction at the beginning, so should multiply be the 1-P_min(tau=0|t;S^{0})\n\t\tdouble when_time = init_time;\n\n\t\t//start from the first reaction\n\t\tfor (size_t i = 0; i < reaction_vec.size();)\n\t\t{\n\t\t\t//none-chattering reaction\n\t\t\tif (reaction_vec[i] >= 0) {\n\t\t\t\twhen_time = pathway_AT_sim_move_one_step(when_time, spe_vec[i]);\n\t\t\t\t//move one step\n\t\t\t\t++i;\n\t\t\t}\n\t\t\t//chattering reaction, chattering case\n\t\t\telse {\n\t\t\t\tint chattering_group_id = this->species_network_v[spe_vec[i]].chattering_group_id;\n\n\t\t\t\t//add time delay first, regenerate random number, inverse to get exact time, get steady state time first\n\t\t\t\t//then calculate steady state ratios\n\t\t\t\tdouble chattering_group_prob = prob_chattering_group_will_react_in_a_time_range(when_time, end_time, chattering_group_id);\n\n\t\t\t\t//avoid problems around boundary\n\t\t\t\tif (when_time < (absolute_end_t - INFINITESIMAL_DT)) {\n\t\t\t\t\tdouble u_1 = 1.0;\n\t\t\t\t\tif (chattering_group_prob > 0.0) {\n\t\t\t\t\t\tu_1 = rand->random_min_max(0, chattering_group_prob);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tu_1 = 0.0;\n\t\t\t\t\t\t//u_1 = INFINITESIMAL_DT;\n\t\t\t\t\t}\n\n\t\t\t\t\twhen_time = chattering_group_reaction_time_from_importance_sampling_without_cutoff(when_time, chattering_group_id, u_1);\n\t\t\t\t}//boundary time problem\n\n\t\t\t\tif (this->condense_chatterings == true) {\n\t\t\t\t\t//move one step actually\n\t\t\t\t\ti += 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//move two steps instead\n\t\t\t\t\ti += 2;\n\t\t\t\t}\n\n\t\t\t}//if chattering case\n\t\t}\n\n\t\treturn when_time;\n\t}\n\n\tdouble superReactionNetwork::pathway_AT_no_IT_input_pathway_sim_once(const double init_time, const double end_time, const std::vector<rsp::index_int_t>& spe_vec, const std::vector<rsp::index_int_t>& reaction_vec)\n\t{\n\t\t//set pathway end time\n\t\tset_absolute_end_t(end_time);\n\n\t\t//basically, we assume there must be a reaction at the beginning, so should multiply be the 1-P_min(tau=0|t;S^{0})\n\t\tdouble when_time = init_time;\n\n\t\tbool is_IT = false;\n\t\tdouble IT = 0.0;\n\n\t\t//start from the first reaction\n\t\tfor (size_t i = 0; i < reaction_vec.size();)\n\t\t{\n\t\t\t//none-chattering reaction\n\t\t\tif (reaction_vec[i] >= 0) {\n\t\t\t\twhen_time = pathway_AT_sim_move_one_step(when_time, spe_vec[i]);\n\n\t\t\t\tif (is_IT == false) {\n\t\t\t\t\tis_IT = true;\n\t\t\t\t\tIT = when_time;\n\t\t\t\t}\n\n\t\t\t\t//move one step\n\t\t\t\t++i;\n\t\t\t}\n\t\t\t//chattering reaction, chattering case\n\t\t\telse {\n\t\t\t\tint chattering_group_id = this->species_network_v[spe_vec[i]].chattering_group_id;\n\n\t\t\t\t//add time delay first, regenerate random number, inverse to get exact time, get steady state time first\n\t\t\t\t//then calculate steady state ratios\n\t\t\t\tdouble chattering_group_prob = prob_chattering_group_will_react_in_a_time_range(when_time, end_time, chattering_group_id);\n\n\t\t\t\t//avoid problems around boundary\n\t\t\t\tif (when_time < (absolute_end_t - INFINITESIMAL_DT)) {\n\t\t\t\t\tdouble u_1 = 1.0;\n\t\t\t\t\tif (chattering_group_prob > 0.0) {\n\t\t\t\t\t\tu_1 = rand->random_min_max(0, chattering_group_prob);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tu_1 = 0.0;\n\t\t\t\t\t\t//u_1 = INFINITESIMAL_DT;\n\t\t\t\t\t}\n\n\n\t\t\t\t\twhen_time = chattering_group_reaction_time_from_importance_sampling_without_cutoff(when_time, chattering_group_id, u_1);\n\n\t\t\t\t\tif (is_IT == false) {\n\t\t\t\t\t\tis_IT = true;\n\t\t\t\t\t\tIT = when_time;\n\t\t\t\t\t}\n\n\t\t\t\t}//boundary time problem\n\n\t\t\t\tif (this->condense_chatterings == true) {\n\t\t\t\t\t//move one step actually\n\t\t\t\t\ti += 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//move two steps instead\n\t\t\t\t\ti += 2;\n\t\t\t\t}\n\n\t\t\t}//if chattering case\n\n\t\t}\n\n\t\treturn when_time - IT;\n\t}\n\n\tstd::pair<double, double> superReactionNetwork::pathway_AT_with_SP_input_pathway_sim_once(const double init_time, const double end_time, const std::vector<rsp::index_int_t>& spe_vec, const std::vector<rsp::index_int_t>& reaction_vec)\n\t{\n\t\t//set pathway end time\n\t\tset_absolute_end_t(end_time);\n\n\t\t//basically, we assume there must be a reaction at the beginning, so should multiply be the 1-P_min(tau=0|t;S^{0})\n\t\tdouble when_time = init_time;\n\n\t\t//start from the first reaction\n\t\tfor (size_t i = 0; i < reaction_vec.size();)\n\t\t{\n\t\t\t//none-chattering reaction\n\t\t\tif (reaction_vec[i] >= 0) {\n\t\t\t\twhen_time = pathway_AT_sim_move_one_step(when_time, spe_vec[i]);\n\t\t\t\t//move one step\n\t\t\t\t++i;\n\t\t\t}\n\t\t\t//chattering reaction, chattering case\n\t\t\telse {\n\t\t\t\tint chattering_group_id = this->species_network_v[spe_vec[i]].chattering_group_id;\n\n\t\t\t\t//add time delay first, regenerate random number, inverse to get exact time, get steady state time first\n\t\t\t\t//then calculate steady state ratios\n\t\t\t\tdouble chattering_group_prob = prob_chattering_group_will_react_in_a_time_range(when_time, end_time, chattering_group_id);\n\n\t\t\t\t//avoid problems around boundary\n\t\t\t\tif (when_time < (absolute_end_t - INFINITESIMAL_DT)) {\n\t\t\t\t\tdouble u_1 = 1.0;\n\t\t\t\t\tif (chattering_group_prob > 0.0) {\n\t\t\t\t\t\tu_1 = rand->random_min_max(0, chattering_group_prob);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tu_1 = 0.0;\n\t\t\t\t\t\t//u_1 = INFINITESIMAL_DT;\n\t\t\t\t\t}\n\n\t\t\t\t\twhen_time = chattering_group_reaction_time_from_importance_sampling_without_cutoff(when_time, chattering_group_id, u_1);\n\t\t\t\t}//boundary time problem\n\n\t\t\t\tif (this->condense_chatterings == true) {\n\t\t\t\t\t//move one step actually\n\t\t\t\t\ti += 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//move two steps instead\n\t\t\t\t\ti += 2;\n\t\t\t\t}\n\n\t\t\t}//if chattering case\n\t\t}\n\n\n\t\t//got to multiply by P_min or says (1-P_max)\n\t\tset_spe_prob_max_at_a_time(when_time, end_time, spe_vec.back());\n\n\t\treturn std::make_pair(when_time, 1 - species_network_v[spe_vec.back()].prob_max);\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::initiate_M_matrix(std::string atom_followed)\n\t{\n\t\t//resize and initialization\n\t\tthis->atom_M_matrix[atom_followed].resize(this->species_network_v.size());\n\t\tfor (std::size_t i = 0; i < this->atom_M_matrix[atom_followed].size(); ++i)\n\t\t\tthis->atom_M_matrix[atom_followed][i].resize(this->species_network_v.size());\n\t\tfor (std::size_t i = 0; i < this->atom_M_matrix[atom_followed].size(); ++i)\n\t\t\tfor (std::size_t j = 0; j < this->atom_M_matrix[atom_followed][i].size(); ++j)\n\t\t\t\tthis->atom_M_matrix[atom_followed][i][j] = 0;\n\n\t\t//actually build M-matrix\n\t\tfor (std::size_t i = 0; i < this->atom_M_matrix[atom_followed].size(); ++i) {\n\t\t\tfor (std::size_t j = 0; j < this->species_network_v[i].reaction_k_index_s_coef_v.size(); ++j) {\n\t\t\t\tfor (std::size_t k = 0; k < this->reaction_network_v[this->species_network_v[i].reaction_k_index_s_coef_v[j].first].out_spe_index_weight_v_map[atom_followed].size(); ++k) {\n\t\t\t\t\t//both contains atom followed\n\t\t\t\t\tif (this->species_network_v[i].spe_component[atom_followed] != 0 && this->species_network_v[this->reaction_network_v[this->species_network_v[i].reaction_k_index_s_coef_v[j].first].out_spe_index_weight_v_map[atom_followed][k].first].spe_component[atom_followed] != 0) {\n\t\t\t\t\t\tthis->atom_M_matrix[atom_followed][i][this->reaction_network_v[this->species_network_v[i].reaction_k_index_s_coef_v[j].first].out_spe_index_weight_v_map[atom_followed][k].first] += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::initiate_M_matrix()\n\t{\n\t\tfor (auto x : this->element_v)\n\t\t\tthis->initiate_M_matrix(x.ele_name);\n\n\t\tthis->initiate_M_matrix(rnk_pt.get<std::string>(\"pathway.super_atom\"));\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::print_M_matrix(std::string atom_followed)\n\t{\n\t\tfor (std::size_t i = 0; i < this->atom_M_matrix[atom_followed].size(); ++i) {\n\t\t\tstd::cout << i << \",\\t\" << this->species_network_v[i].spe_name << \",\\t\";\n\t\t\tfor (std::size_t j = 0; j < this->atom_M_matrix[atom_followed][i].size(); ++j) {\n\t\t\t\tstd::cout << this->atom_M_matrix[atom_followed][i][j] << \"\\t\";\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n\n\t}\n\n\tmatrix_sr::size_t_matrix_t reactionNetwork_sr::superReactionNetwork::return_M_matrix(std::string atom_followed)\n\t{\n\t\treturn this->atom_M_matrix[atom_followed];\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::initiate_R_matrix_v1(std::string atom_followed)\n\t{\n\t\t//resize and initialization\n\t\tthis->atom_R_matrix[atom_followed].resize(this->species_network_v.size());\n\t\tfor (std::size_t i = 0; i < this->atom_R_matrix[atom_followed].size(); ++i)\n\t\t\tthis->atom_R_matrix[atom_followed][i].resize(this->species_network_v.size());\n\t\tfor (std::size_t i = 0; i < this->atom_R_matrix[atom_followed].size(); ++i)\n\t\t\tfor (std::size_t j = 0; j < this->atom_R_matrix[atom_followed][i].size(); ++j)\n\t\t\t\tthis->atom_R_matrix[atom_followed][i][j] = {};\n\n\t\t//actually build M-matrix\n\t\tfor (std::size_t i = 0; i < this->atom_R_matrix[atom_followed].size(); ++i) {\n\t\t\tfor (std::size_t j = 0; j < this->species_network_v[i].reaction_k_index_s_coef_v.size(); ++j) {\n\t\t\t\tfor (std::size_t k = 0; k < this->reaction_network_v[this->species_network_v[i].reaction_k_index_s_coef_v[j].first].out_spe_index_weight_v_map[atom_followed].size(); ++k) {\n\t\t\t\t\t//both contains atom followed\n\t\t\t\t\tif (this->species_network_v[i].spe_component[atom_followed] != 0 && this->species_network_v[this->reaction_network_v[this->species_network_v[i].reaction_k_index_s_coef_v[j].first].out_spe_index_weight_v_map[atom_followed][k].first].spe_component[atom_followed] != 0) {\n\t\t\t\t\t\tthis->atom_R_matrix[atom_followed][i][this->reaction_network_v[this->species_network_v[i].reaction_k_index_s_coef_v[j].first].out_spe_index_weight_v_map[atom_followed][k].first].push_back({ this->species_network_v[i].reaction_k_index_s_coef_v[j].first });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::initiate_R_matrix_v2(std::string atom_followed)\n\t{\n\t\t//resize and initialization\n\t\tthis->atom_R_matrix[atom_followed].resize(this->species_network_v.size());\n\t\tfor (std::size_t i = 0; i < this->atom_R_matrix[atom_followed].size(); ++i)\n\t\t\tthis->atom_R_matrix[atom_followed][i].resize(this->species_network_v.size());\n\t\tfor (std::size_t i = 0; i < this->atom_R_matrix[atom_followed].size(); ++i)\n\t\t\tfor (std::size_t j = 0; j < this->atom_R_matrix[atom_followed][i].size(); ++j)\n\t\t\t\tthis->atom_R_matrix[atom_followed][i][j] = {};\n\n\t\t//iterate over all edges\n\t\tedge_iter iter_beg, iter_end;\n\t\tboost::tie(iter_beg, iter_end) = getEdges();\n\t\t//source and target index\n\t\tstd::size_t s_i, t_i;\n\t\tfor (; iter_beg != iter_end; ++iter_beg) {\n\t\t\ts_i = boost::source(*iter_beg, this->graph);\n\t\t\tt_i = boost::target(*iter_beg, this->graph);\n\n\t\t\tif (species_network_v[s_i].spe_component[atom_followed] != 0 && species_network_v[t_i].spe_component[atom_followed] != 0)\n\t\t\t\tthis->atom_R_matrix[atom_followed][s_i][t_i].push_back({ properties(*iter_beg).edge_index });\n\t\t}\n\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::initiate_R_matrix()\n\t{\n\t\tfor (auto x : this->element_v)\n\t\t\t//this->initiate_R_matrix_v1(x.ele_name);\n\t\t\tthis->initiate_R_matrix_v2(x.ele_name);\n\n\t\tthis->initiate_R_matrix_v2(this->rnk_pt.get<std::string>(\"pathway.super_atom\"));\n\t}\n\n\tmatrix_sr::path_R_matrix_t reactionNetwork_sr::superReactionNetwork::return_R_matrix(std::string atom_followed)\n\t{\n\t\treturn this->atom_R_matrix[atom_followed];\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::print_R_matrix(std::string atom_followed)\n\t{\n\t\tfor (std::size_t i = 0; i < this->atom_R_matrix[atom_followed].size(); ++i) {\n\t\t\tstd::cout << i << \",\\t\" << this->species_network_v[i].spe_name << \",\\t\";\n\t\t\tfor (std::size_t j = 0; j < this->atom_R_matrix[atom_followed][i].size(); ++j) {\n\t\t\t\t//std::cout << \"(\" << i << \",\" << j << \")\\t\";\n\t\t\t\tstd::cout << \"(\" << this->species_network_v[i].spe_name << \",\" << this->species_network_v[j].spe_name << \")\\t\";\n\t\t\t\tif (this->atom_R_matrix[atom_followed][i][j].size() == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (std::size_t k = 0; k < this->atom_R_matrix[atom_followed][i][j].size(); ++k) {\n\t\t\t\t\tfor (std::size_t l = 0; l < this->atom_R_matrix[atom_followed][i][j][k].size(); ++l)\n\t\t\t\t\t\tstd::cout << this->atom_R_matrix[atom_followed][i][j][k][l] << \"\\t\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n\n\tstd::size_t reactionNetwork_sr::superReactionNetwork::get_M_matrix_element(std::string atom_followed, std::size_t i, std::size_t j)\n\t{\n\t\treturn this->atom_M_matrix[atom_followed][i][j];\n\t}\n\n\tmatrix_sr::path_R_matrix_element_t reactionNetwork_sr::superReactionNetwork::get_R_matrix_element(std::string atom_followed, std::size_t i, std::size_t j)\n\t{\n\t\treturn this->atom_R_matrix[atom_followed][i][j];\n\t}\n\n\tstd::string reactionNetwork_sr::superReactionNetwork::R_matrix_path_representation_to_string(matrix_sr::path_t p)\n\t{\n\t\tstd::string path_t;\n\t\tif (p.size() > 0) {\n\t\t\tedge_iter iter_e = edge_index_to_edge_iterator[p[0]];\n\t\t\tpath_t += std::string(\"S\") + boost::lexical_cast<std::string>(boost::source(*iter_e, this->graph));\n\n\t\t\tfor (std::size_t i = 0; i < p.size(); ++i) {\n\t\t\t\titer_e = edge_index_to_edge_iterator[p[i]];\n\t\t\t\tpath_t += std::string(\"R\") + boost::lexical_cast<std::string>(properties(*iter_e).reaction_index);\n\t\t\t\tpath_t += std::string(\"S\") + boost::lexical_cast<std::string>(boost::target(*iter_e, this->graph));\n\t\t\t}\n\t\t}\n\t\treturn path_t;\n\t}\n\n\tbool reactionNetwork_sr::superReactionNetwork::contains_zero_reaction_rate_reactions(matrix_sr::path_t p)\n\t{\n\t\t//arrow guard\n\t\tif (p.size() == 0)\n\t\t\treturn false;\n\t\tfor (auto x : p) {\n\t\t\tedge_iter iter_e = edge_index_to_edge_iterator[x];\n\t\t\tif (reaction_network_v[properties(*iter_e).reaction_index].is_reaction_rate_nonzero == false)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tstd::vector<std::string> reactionNetwork_sr::superReactionNetwork::get_path_string_element_i_j(const matrix_sr::path_R_matrix_t &pRm, std::size_t i, std::size_t j)\n\t{\n\t\tif (pRm.size() == 0)\n\t\t\treturn std::vector<std::string>(1, std::string(\"S\") + boost::lexical_cast<std::string>(i));\n\n\t\tmatrix_sr::path_R_matrix_element_t p = pRm[i][j];\n\t\tstd::vector<std::string> vs;\n\n\t\tfor (auto x : p) {\n\t\t\tstd::string ps = R_matrix_path_representation_to_string(x);\n\t\t\tif (!ps.empty())\n\t\t\t\tvs.push_back(ps);\n\t\t}\n\t\treturn vs;\n\t}\n\n\tstd::vector<std::string> reactionNetwork_sr::superReactionNetwork::get_path_string_update_matrix_element_i_j_topN(matrix_sr::path_R_matrix_t &pRm, const std::size_t i, const std::size_t j,\n\t\tconst std::string atom_followed, const std::size_t topN, const double start_time, const double end_time)\n\t{\n\t\tif (pRm.size() == 0)\n\t\t\treturn std::vector<std::string>(1, std::string(\"S\") + boost::lexical_cast<std::string>(i));\n\n\t\tmatrix_sr::path_R_matrix_element_t p = pRm[i][j];\n\t\tmatrix_sr::path_R_matrix_element_t p_new;\n\t\tstd::multimap<double, std::pair<std::string, std::size_t>, std::greater<double> > prob_path_map;\n\n\t\t//if there is less than topN path, do nothing\n\t\t//if there are more than topN path, delete the unimportant ones\n\t\tfor (std::size_t k = 0; k < p.size(); ++k) {\n\t\t\tstd::string ps = R_matrix_path_representation_to_string(p[k]);\n\t\t\tdouble prob = calculate_path_weight_based_on_path_probability(ps, atom_followed, start_time, end_time);\n\n\t\t\tif (prob_path_map.size() < topN) {\n\t\t\t\tprob_path_map.insert(std::make_pair(prob, std::make_pair(ps, k)));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (prob <= prob_path_map.crbegin()->first)\n\t\t\t\t\tcontinue;\n\t\t\t\telse {\n\t\t\t\t\tprob_path_map.erase(std::prev(prob_path_map.end()));\n\t\t\t\t\tprob_path_map.insert(std::make_pair(prob, std::make_pair(ps, k)));\n\t\t\t\t}\n\t\t\t} //if <topN\n\n\t\t}\n\n\t\tfor (auto x : prob_path_map) {\n\t\t\tp_new.push_back(p[x.second.second]);\n\t\t}\n\n\t\t//update matrix\n\t\tif (p_new.size() == 0)\n\t\t\tp_new = {};\n\t\tpRm[i][j].clear();\n\t\tpRm[i][j] = p_new;\n\n\t\tstd::vector<std::string> vs;\n\t\tfor (auto x : p_new) {\n\t\t\tstd::string ps = R_matrix_path_representation_to_string(x);\n\t\t\tif (!ps.empty())\n\t\t\t\tvs.push_back(ps);\n\t\t}\n\n\t\treturn vs;\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::path_string_vector_s2f(std::vector<std::string> vs, std::string filename)\n\t{\n\t\tstd::ofstream fout(filename.c_str());\n\t\tfor (auto x : vs)\n\t\t\tfout << x << std::endl;\n\n\t\tfout.close(); fout.clear();\n\t}\n\n\tvoid reactionNetwork_sr::superReactionNetwork::heuristic_path_string_vector_s2f(std::string atom_followed, std::size_t n, std::string filename)\n\t{\n\t\tstd::unordered_set<std::string> us;\n\t\tfor (std::size_t k = 0; k <= n; ++k) {\n\t\t\tauto pRmn = matrix_sr::matrix_power(this->atom_R_matrix[atom_followed], k);\n\t\t\tfor (auto key : this->rnk_pt.get_child(\"chem_init.species_index_concentration\")) {\n\t\t\t\tstd::size_t si = boost::lexical_cast<std::size_t>(key.first);\n\t\t\t\t//doesn't contain atom_followed\n\t\t\t\tif (species_network_v[si].spe_component.at(atom_followed) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (k == 0) {\n\t\t\t\t\tus.insert(std::string(\"S\") + boost::lexical_cast<std::string>(si));\n\t\t\t\t\t//std::cout << std::string(\"S\") + boost::lexical_cast<std::string>(si) << std::endl;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (std::size_t sj = 0; sj < this->species_network_v.size(); ++sj) {\n\t\t\t\t\tauto vs = this->get_path_string_update_matrix_element_i_j_topN(pRmn, si, sj);\n\t\t\t\t\tfor (auto s : vs)\n\t\t\t\t\t\tus.insert(s);\n\t\t\t\t\t//std::cout << s << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\t//save to file\n\t\tstd::ofstream fout(filename.c_str());\n\t\tfor (auto s : us)\n\t\t\tfout << s << std::endl;\n\t\tfout.close(); fout.clear();\n\t}\n\n\tvoid superReactionNetwork::heuristic_path_string_vector_si_sj_n_s2f(std::string atom_followed, std::size_t si, std::size_t sj, std::size_t n, std::string filename)\n\t{\n\t\tstd::unordered_set<std::string> us;\n\t\tfor (std::size_t k = 0; k <= n; ++k) {\n\t\t\tauto pRmn = matrix_sr::matrix_power(this->atom_R_matrix[atom_followed], k);\n\n\t\t\tif (k == 0) {\n\t\t\t\tus.insert(std::string(\"S\") + boost::lexical_cast<std::string>(si));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tauto vs = this->get_path_string_update_matrix_element_i_j_topN(pRmn, si, sj);\n\t\t\tfor (auto s : vs)\n\t\t\t\tus.insert(s);\n\t\t}\n\n\t\t//save to file\n\t\tstd::ofstream fout(filename.c_str());\n\t\tfor (auto s : us)\n\t\t\tfout << s << std::endl;\n\t\tfout.close(); fout.clear();\n\t}\n\n\tstd::set<std::string> reactionNetwork_sr::superReactionNetwork::heuristic_path_string_vector_s2m(std::string atom_followed, std::size_t n)\n\t{\n\t\tstd::set<std::string> us;\n\t\tfor (std::size_t k = 0; k <= n; ++k) {\n\t\t\tauto pRmn = matrix_sr::matrix_power(this->atom_R_matrix[atom_followed], k);\n\t\t\tfor (auto key : this->rnk_pt.get_child(\"chem_init.species_index_concentration\")) {\n\t\t\t\tstd::size_t si = boost::lexical_cast<std::size_t>(key.first);\n\t\t\t\t//doesn't contain atom_followed\n\t\t\t\tif (species_network_v[si].spe_component.at(atom_followed) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (k == 0) {\n\t\t\t\t\tus.insert(std::string(\"S\") + boost::lexical_cast<std::string>(si));\n\t\t\t\t\t//std::cout << std::string(\"S\") + boost::lexical_cast<std::string>(si) << std::endl;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (std::size_t sj = 0; sj < this->species_network_v.size(); ++sj) {\n\t\t\t\t\tauto vs = this->get_path_string_update_matrix_element_i_j_topN(pRmn, si, sj);\n\t\t\t\t\tfor (auto s : vs)\n\t\t\t\t\t\tus.insert(s);\n\t\t\t\t\t//std::cout << s << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\treturn us;\n\t}\n\n\tstd::set<std::string> reactionNetwork_sr::superReactionNetwork::heuristic_path_string_vector_sorted_based_on_path_length(std::string atom_followed, std::size_t n, std::size_t topN)\n\t{\n\t\tstd::vector<std::multimap<double, std::string> > p_map_v(this->species_network_v.size());\n\n\t\tmatrix_sr::path_R_matrix_t pRmn;\n\t\tfor (std::size_t k = 0; k <= n; ++k) {\n\t\t\t//auto pRmn = matrix_sr::matrix_power(this->atom_R_matrix[atom_followed], k);\n\t\t\tif (k == 0)\n\t\t\t\tpRmn = matrix_sr::path_R_matrix_t();\n\t\t\telse if (k == 1)\n\t\t\t\tpRmn = this->atom_R_matrix[atom_followed];\n\t\t\telse\n\t\t\t\tpRmn = matrix_sr::matrix_multiplication(pRmn, this->atom_R_matrix[atom_followed]);\n\n\t\t\tfor (auto key : this->rnk_pt.get_child(\"chem_init.species_index_concentration\")) {\n\t\t\t\tstd::size_t si = boost::lexical_cast<std::size_t>(key.first);\n\t\t\t\t//doesn't contain atom_followed\n\t\t\t\tif (species_network_v[si].spe_component.at(atom_followed) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (k == 0) {\n\t\t\t\t\tstd::string path_name = std::string(\"S\") + boost::lexical_cast<std::string>(si);\n\t\t\t\t\tp_map_v[si].insert(std::make_pair(calculate_path_weight_path_length(path_name), path_name));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (std::size_t sj = 0; sj < this->species_network_v.size(); ++sj) {\n\t\t\t\t\tauto vs = this->get_path_string_update_matrix_element_i_j_topN(pRmn, si, sj);\n\t\t\t\t\tfor (auto s : vs) {\n\t\t\t\t\t\tdouble prob = calculate_path_weight_path_length(s);\n\t\t\t\t\t\tif (p_map_v[sj].size() < topN) {\n\t\t\t\t\t\t\tp_map_v[sj].insert(std::make_pair(prob, s));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (prob >= p_map_v[sj].crbegin()->first)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tp_map_v[sj].erase(std::prev(p_map_v[sj].end()));\n\t\t\t\t\t\t\t\tp_map_v[sj].insert(std::make_pair(prob, s));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} //if <topN\n\n\n\t\t\t\t\t} //auto s\n\t\t\t\t} //sj\n\t\t\t}\n\n\t\t}\n\t\tstd::set<std::string> us;\n\t\tfor (auto pmv : p_map_v)\n\t\t\tfor (auto ps : pmv)\n\t\t\t\t//add atom followed to the beging of path\n\t\t\t\tus.insert(atom_followed + ps.second);\n\n\t\treturn us;\n\t}\n\n\tstd::set<std::string> reactionNetwork_sr::superReactionNetwork::heuristic_path_string_vector_sorted_based_on_path_prob(std::string atom_followed, std::size_t n, std::size_t topN, double end_time_ratio)\n\t{\n\t\tstd::vector<std::multimap<double, std::string, std::greater<double> > > prob_path_map_v(this->species_network_v.size());\n\t\tmatrix_sr::path_R_matrix_t pRmn;\n\t\tfor (std::size_t k = 0; k <= n; ++k) {\n\t\t\t//auto pRmn = matrix_sr::matrix_power(this->atom_R_matrix[atom_followed], k);\n\t\t\tif (k == 0)\n\t\t\t\tpRmn = matrix_sr::path_R_matrix_t();\n\t\t\telse if (k == 1)\n\t\t\t\tpRmn = this->atom_R_matrix[atom_followed];\n\t\t\telse\n\t\t\t\tpRmn = matrix_sr::matrix_multiplication(pRmn, this->atom_R_matrix[atom_followed]);\n\n\t\t\tauto species_with_initial_concentration = return_species_index_with_initial_concentration();\n\t\t\tauto species_without_initial_concentration = return_species_index_without_initial_concentration();\n\n\t\t\t//species with initial concentration\n\t\t\tfor (auto si : species_with_initial_concentration) {\n\t\t\t\t//doesn't contain atom_followed\n\t\t\t\tif (species_network_v[si].spe_component.at(atom_followed) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (k == 0) {\n\t\t\t\t\tstd::string path_name = std::string(\"S\") + boost::lexical_cast<std::string>(si);\n\t\t\t\t\tprob_path_map_v[si].insert(std::make_pair(calculate_path_weight_based_on_path_probability(path_name, atom_followed, 0.0, end_time_ratio*this->rnk_pt.get<double>(\"time.tau\")), path_name));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t//in the mean time, we should change the matrix element so that it doesn't contain too many elements\n\t\t\t\t//become too big-->lots of memory\n\t\t\t\tfor (std::size_t sj = 0; sj < this->species_network_v.size(); ++sj) {\n\t\t\t\t\t//be a little cautious, a little open, 10*topN\n\t\t\t\t\tauto vs = this->get_path_string_update_matrix_element_i_j_topN(pRmn, si, sj, atom_followed, 10 * topN, 0.0, end_time_ratio*this->rnk_pt.get<double>(\"time.tau\"));\n\t\t\t\t\tfor (auto s : vs) {\n\t\t\t\t\t\tdouble prob = calculate_path_weight_based_on_path_probability(s, atom_followed, 0.0, end_time_ratio*this->rnk_pt.get<double>(\"time.tau\"));\n\t\t\t\t\t\tif (prob_path_map_v[sj].size() < topN) {\n\t\t\t\t\t\t\tprob_path_map_v[sj].insert(std::make_pair(prob, s));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (prob <= prob_path_map_v[sj].crbegin()->first)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tprob_path_map_v[sj].erase(std::prev(prob_path_map_v[sj].end()));\n\t\t\t\t\t\t\t\tprob_path_map_v[sj].insert(std::make_pair(prob, s));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} //if <topN\n\n\n\t\t\t\t\t} //auto s\n\t\t\t\t} //sj\n\t\t\t}\n\n\t\t\t//species without initial concentration, still need to update matrix elements\n\t\t\tfor (auto si : species_without_initial_concentration) {\n\t\t\t\tfor (std::size_t sj = 0; sj < this->species_network_v.size(); ++sj)\n\t\t\t\t\t//be a little cautious, a little open, 10*topN\n\t\t\t\t\tthis->get_path_string_update_matrix_element_i_j_topN(pRmn, si, sj, atom_followed, 10 * topN, 0.0, end_time_ratio*this->rnk_pt.get<double>(\"time.tau\"));\n\t\t\t}\n\n\t\t}\n\t\tstd::set<std::string> us;\n\t\tfor (auto pmv : prob_path_map_v)\n\t\t\tfor (auto ps : pmv)\n\t\t\t\t//add atom followed to the beging of path\n\t\t\t\tus.insert(atom_followed + ps.second);\n\n\t\treturn us;\n\t}\n\n\tdouble reactionNetwork_sr::superReactionNetwork::calculate_path_weight_path_length(std::string path)\n\t{\n\t\treturn (double)(std::count(path.begin(), path.end(), 'S'));\n\t}\n\n\tdouble reactionNetwork_sr::superReactionNetwork::calculate_path_weight_based_on_path_probability(std::string path, std::string atom_followed, double start_time, double end_time)\n\t{\n\t\tstd::vector<rsp::index_int_t> spe_vec; std::vector<rsp::index_int_t> reaction_vec;\n\t\tdouble prob = 0.0;\n\t\tthis->parse_pathway_to_vector(path, spe_vec, reaction_vec);\n\t\tprob = pathway_prob_input_pathway_sim_once(start_time, end_time, spe_vec, reaction_vec, atom_followed);\n\n\t\t//take the initial concentration of initial species into account\n\t\tif (this->species_network_v[spe_vec[0]].spe_conc != 0)\n\t\t\tprob *= this->species_network_v[spe_vec[0]].spe_conc;\n\n\t\tprob *= this->species_network_v[spe_vec[0]].spe_component[atom_followed];\n\t\tprob /= this->species_network_v[spe_vec.back()].spe_component[atom_followed];\n\n\t\treturn prob;\n\t}\n\n\tstd::size_t reactionNetwork_sr::superReactionNetwork::heuristic_path_string_vector_by_stage_number_path_length_all_elements(const std::size_t stage_n, std::string filename, std::size_t topN)\n\t{\n\t\tassert(stage_n >= 0);\n\t\t//fetch path length first\n\t\tstd::vector<std::size_t> path_n_v;\n\t\tfor (auto key : this->rnk_pt.get_child(\"pathway.max_path_length\"))\n\t\t\tpath_n_v.push_back(key.second.get_value<std::size_t>());\n\n\t\tstd::size_t path_n;\n\t\t//if iteration n is less than path_n_v lenght, fetch by index, otherwise take the last element\n\t\tif (stage_n < path_n_v.size())\n\t\t\tpath_n = path_n_v[stage_n];\n\t\telse\n\t\t\tpath_n = path_n_v.back();\n\n\t\tif (stage_n == 0)\n\t\t\tthis->set_is_reaction_rate_nonzero_from_setting_file();\n\t\telse\n\t\t\tthis->set_is_reaction_rate_nonzero_from_previous_iteration();\n\n\t\tstd::vector<set<std::string> > all_path_2;\n\n\t\tfor (auto x : this->element_v) {\n\t\t\tall_path_2.push_back(this->heuristic_path_string_vector_sorted_based_on_path_length(x.ele_name, path_n, topN));\n\t\t}\n\n\t\tset<std::string> all_path;\n\t\tfor (auto us : all_path_2)\n\t\t\tfor (auto s : us)\n\t\t\t\tall_path.insert(s);\n\n\t\t//save to file\n\t\tstd::ofstream fout(filename.c_str());\n\t\tfor (auto x : all_path)\n\t\t\tfout << x << std::endl;\n\t\tfout.close(); fout.clear();\n\n\t\treturn this->element_v.size();\n\t}\n\n\tstd::size_t reactionNetwork_sr::superReactionNetwork::heuristic_path_string_vector_by_stage_number_path_prob_all_elements(const std::size_t stage_n, std::string filename, std::size_t topN, double end_time_ratio)\n\t{\n\t\tassert(stage_n >= 0);\n\t\t//fetch path length first\n\t\tstd::vector<std::size_t> path_n_v;\n\t\tfor (auto key : this->rnk_pt.get_child(\"pathway.max_path_length\"))\n\t\t\tpath_n_v.push_back(key.second.get_value<std::size_t>());\n\n\t\tstd::size_t path_n;\n\t\t//if iteration n is less than path_n_v lenght, fetch by index, otherwise take the last element\n\t\tif (stage_n < path_n_v.size())\n\t\t\tpath_n = path_n_v[stage_n];\n\t\telse\n\t\t\tpath_n = path_n_v.back();\n\n\t\tif (stage_n == 0)\n\t\t\tthis->set_is_reaction_rate_nonzero_from_setting_file();\n\t\telse\n\t\t\tthis->set_is_reaction_rate_nonzero_from_previous_iteration();\n\n\t\tstd::vector<set<std::string> > all_path_2;\n\n\t\tfor (auto x : this->element_v) {\n\t\t\tall_path_2.push_back(this->heuristic_path_string_vector_sorted_based_on_path_prob(x.ele_name, path_n, topN, end_time_ratio));\n\t\t}\n\n\t\tset<std::string> all_path;\n\t\tfor (auto us : all_path_2)\n\t\t\tfor (auto s : us)\n\t\t\t\tall_path.insert(s);\n\n\t\t//save to file\n\t\tstd::ofstream fout(filename.c_str());\n\t\tfor (auto x : all_path)\n\t\t\tfout << x << std::endl;\n\t\tfout.close(); fout.clear();\n\n\t\treturn this->element_v.size();\n\t}\n\n\tstd::size_t reactionNetwork_sr::superReactionNetwork::heuristic_path_string_vector_by_stage_number_path_prob_all_elements_s2m(const std::size_t stage_n, std::vector<std::string> &path_all_v, std::size_t topN, double end_time_ratio)\n\t{\n\t\tpath_all_v.resize(0);\n\n\t\tassert(stage_n >= 0);\n\t\t//fetch path length first\n\t\tstd::vector<std::size_t> path_n_v;\n\t\tfor (auto key : this->rnk_pt.get_child(\"pathway.max_path_length\"))\n\t\t\tpath_n_v.push_back(key.second.get_value<std::size_t>());\n\n\t\tstd::size_t path_n;\n\t\t//if iteration n is less than path_n_v lenght, fetch by index, otherwise take the last element\n\t\tif (stage_n < path_n_v.size())\n\t\t\tpath_n = path_n_v[stage_n];\n\t\telse\n\t\t\tpath_n = path_n_v.back();\n\n\t\tif (stage_n == 0)\n\t\t\tthis->set_is_reaction_rate_nonzero_from_setting_file();\n\t\telse\n\t\t\tthis->set_is_reaction_rate_nonzero_from_previous_iteration();\n\n\t\tstd::vector<set<std::string> > all_path_2;\n\n\t\tfor (auto x : this->element_v) {\n\t\t\tall_path_2.push_back(this->heuristic_path_string_vector_sorted_based_on_path_prob(x.ele_name, path_n, topN, end_time_ratio));\n\t\t}\n\n\t\tset<std::string> all_path;\n\t\tfor (auto us : all_path_2)\n\t\t\tfor (auto s : us)\n\t\t\t\tall_path.insert(s);\n\t\tfor (auto p : all_path)\n\t\t\tpath_all_v.push_back(p);\n\n\t\treturn this->element_v.size();\n\n\t}\n\n\n\tstd::size_t reactionNetwork_sr::superReactionNetwork::heuristic_path_string_vector_by_stage_number_path_prob_super_element(const std::size_t stage_n, std::string filename, std::size_t topN, double end_time_ratio)\n\t{\n\t\tassert(stage_n >= 0);\n\t\t//fetch path length first\n\t\tstd::vector<std::size_t> path_n_v;\n\t\tfor (auto key : this->rnk_pt.get_child(\"pathway.max_path_length\"))\n\t\t\tpath_n_v.push_back(key.second.get_value<std::size_t>());\n\n\t\tstd::size_t path_n;\n\t\t//if iteration n is less than path_n_v lenght, fetch by index, otherwise take the last element\n\t\tif (stage_n < path_n_v.size())\n\t\t\tpath_n = path_n_v[stage_n];\n\t\telse\n\t\t\tpath_n = path_n_v.back();\n\n\t\tif (stage_n == 0)\n\t\t\tthis->set_is_reaction_rate_nonzero_from_setting_file();\n\t\telse\n\t\t\tthis->set_is_reaction_rate_nonzero_from_previous_iteration();\n\n\t\tauto us = this->heuristic_path_string_vector_sorted_based_on_path_prob(this->rnk_pt.get<std::string>(\"pathway.super_atom\"), path_n, topN, end_time_ratio);\n\n\t\t//save to file\n\t\tstd::ofstream fout(filename.c_str());\n\t\tfor (auto x : us)\n\t\t\tfout << x << std::endl;\n\t\tfout.close(); fout.clear();\n\n\t\treturn 1;\n\t}\n\n\tstd::set<std::size_t> reactionNetwork_sr::superReactionNetwork::return_species_index_with_initial_concentration() const\n\t{\n\t\tstd::set<std::size_t> species_with_initial_concentration;\n\t\tfor (auto key : this->rnk_pt.get_child(\"chem_init.species_index_concentration\")) {\n\t\t\tspecies_with_initial_concentration.insert(boost::lexical_cast<std::size_t>(key.first));\n\t\t}\n\t\treturn species_with_initial_concentration;\n\t}\n\n\tstd::set<std::size_t> reactionNetwork_sr::superReactionNetwork::return_species_index_without_initial_concentration() const\n\t{\n\t\tauto species_with_initial_concentration = return_species_index_with_initial_concentration();\n\t\tstd::set<std::size_t> species_without_initial_concentration;\n\n\t\tfor (std::size_t i = 0; i < this->species_network_v.size(); ++i) {\n\t\t\t//not in species_with_initial_concentration\n\t\t\tif (species_with_initial_concentration.count(i) == 0)\n\t\t\t\tspecies_without_initial_concentration.insert(i);\n\t\t}\n\t\treturn species_without_initial_concentration;\n\t}\n\n\tstd::set<std::pair<std::size_t, double> > reactionNetwork_sr::superReactionNetwork::return_species_index_and_initial_concentration() const\n\t{\n\t\tstd::set<std::pair<std::size_t, double> > species_concentration;\n\n\t\tfor (auto key : this->rnk_pt.get_child(\"chem_init.species_index_concentration\")) {\n\t\t\tspecies_concentration.emplace(boost::lexical_cast<std::size_t>(key.first), key.second.get_value<double>());\n\t\t}\n\t\treturn species_concentration;\n\t}\n\n\n\tvoid reactionNetwork_sr::superReactionNetwork::generate_path_by_running_monte_carlo_trajectory_s2m(std::vector<statistics > &statistics_v, std::size_t Ntrajectory, std::string atom_followed, double end_time_ratio)\n\t{\n\t\t//std::vector<statistics > statistics_v(this->species_network_v.size());\n\n\t\tauto species_with_initial_concentration = return_species_index_with_initial_concentration();\n\n\t\t//species with initial concentration, initial concentration is not zero\n\t\tfor (auto si : species_with_initial_concentration) {\n\t\t\t//doesn't contain atom_followed\n\t\t\tif (species_network_v[si].spe_component.at(atom_followed) == 0)\n\t\t\t\tcontinue;\n\n\t\t\t//contain atom_followed\n\t\t\tstd::string str_tmp;\n\t\t\tfor (std::size_t ti = 0; ti < Ntrajectory; ++ti) {\n\t\t\t\tstr_tmp = this->pathway_sim_once(0.0, end_time_ratio*this->rnk_pt.get<double>(\"time.tau\"), si, atom_followed);\n\t\t\t\t//put the atom followed in front\n\t\t\t\tstatistics_v[si].insert_pathway_stat(atom_followed + str_tmp);\n\t\t\t} //for\n\t\t} //for\n\n\t} //generate_path_by_running_monte_carlo_trajectory_s2m\n\n\tstd::size_t reactionNetwork_sr::superReactionNetwork::generate_path_by_running_monte_carlo_trajectory_all_elements_s2m(std::vector<statistics>& statistics_v, std::size_t Ntrajectory, double end_time_ratio)\n\t{\n\t\tfor (auto x : this->element_v) {\n\t\t\tgenerate_path_by_running_monte_carlo_trajectory_s2m(statistics_v, Ntrajectory, x.ele_name, end_time_ratio);\n\t\t}\n\t\treturn this->element_v.size();\n\t}\n\n\tstd::vector<rsp::element_info> reactionNetwork_sr::superReactionNetwork::return_element_vecotr() const\n\t{\n\t\treturn this->element_v;\n\t}\n\n\n\n}/*namespace reactionNetwork_sr*/\n\n#endif\n", "meta": {"hexsha": "e579b5ab429a0553974669a5154443fcba09cde0", "size": 98148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reactionNetwork/superReactionNetwork/superReactionNetwork.cpp", "max_stars_repo_name": "AdamPI314/SOHR", "max_stars_repo_head_hexsha": "eec472ec98c69ce58d8dee1bc5bfc4a2bf9063c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T23:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T18:13:50.000Z", "max_issues_repo_path": "src/reactionNetwork/superReactionNetwork/superReactionNetwork.cpp", "max_issues_repo_name": "AdamPI314/SOHR", "max_issues_repo_head_hexsha": "eec472ec98c69ce58d8dee1bc5bfc4a2bf9063c6", "max_issues_repo_licenses": ["MIT"], "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/reactionNetwork/superReactionNetwork/superReactionNetwork.cpp", "max_forks_repo_name": "AdamPI314/SOHR", "max_forks_repo_head_hexsha": "eec472ec98c69ce58d8dee1bc5bfc4a2bf9063c6", "max_forks_repo_licenses": ["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.2643274854, "max_line_length": 429, "alphanum_fraction": 0.7144516445, "num_tokens": 28139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.1995452819719607}}
{"text": "#include \"Wad.h\"\r\n\r\n#include <boost/algorithm/string.hpp>\r\n\r\n#include <cctype>\r\n#include <cmath>\r\n#include <cstdlib>\r\n#include <iostream>\r\n\r\n#include \"IO.h\"\r\n\r\nnamespace {\r\n\tconst auto sqrt2 = std::sqrt(2.0);\r\n\r\n\tvoid ApplyAlphaSections(Image& pTex) {\r\n\t\tstd::vector<unsigned char> pRGBTexture(pTex.width * pTex.height * 4, 0x00);\r\n\r\n\t\t// Color pRGBTexture totally blue\r\n\t\tfor (int i = 0; i < pTex.height * pTex.width; i++)\r\n\t\t\tpRGBTexture[i * 4 + 2] = 255;\r\n\r\n\t\tfor (int y = 0; y < pTex.height; y++) {\r\n\t\t\tfor (int x = 0; x < pTex.width; x++) {\r\n\t\t\t\tint index = y * pTex.width + x;\r\n\r\n\t\t\t\tif ((pTex.data[index * 4] == 0) && (pTex.data[index * 4 + 1] == 0) && (pTex.data[index * 4 + 2] == 255)) {\r\n\t\t\t\t\t// Blue color signifies a transparent portion of the texture. zero alpha for blending and\r\n\t\t\t\t\t// to get rid of blue edges choose the average color of the nearest non blue pixels\r\n\r\n\t\t\t\t\t//First set pixel black and transparent\r\n\t\t\t\t\tpTex.data[index * 4 + 2] = 0;\r\n\t\t\t\t\tpTex.data[index * 4 + 3] = 0;\r\n\r\n\t\t\t\t\tint count = 0;\r\n\t\t\t\t\tunsigned int RGBColorSum[3] = {0, 0, 0};\r\n\r\n\t\t\t\t\t//left above pixel\r\n\t\t\t\t\tif ((x > 0) && (y > 0)) {\r\n\t\t\t\t\t\tint iPixel = ((y - 1) * pTex.width + (x - 1)) * 4;\r\n\t\t\t\t\t\tif (!((pTex.data[iPixel] == 0) && (pTex.data[iPixel + 1] == 0) && (pTex.data[iPixel + 2] == 255))) {\r\n\t\t\t\t\t\t\tRGBColorSum[0] += (unsigned int)((float)pTex.data[iPixel + 0] * sqrt2);\r\n\t\t\t\t\t\t\tRGBColorSum[1] += (unsigned int)((float)pTex.data[iPixel + 1] * sqrt2);\r\n\t\t\t\t\t\t\tRGBColorSum[2] += (unsigned int)((float)pTex.data[iPixel + 2] * sqrt2);\r\n\t\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//above pixel\r\n\t\t\t\t\tif ((x >= 0) && (y > 0)) {\r\n\t\t\t\t\t\tint iPixel = ((y - 1) * pTex.width + x) * 4;\r\n\t\t\t\t\t\tif (!((pTex.data[iPixel] == 0) && (pTex.data[iPixel + 1] == 0) && (pTex.data[iPixel + 2] == 255))) {\r\n\t\t\t\t\t\t\tRGBColorSum[0] += pTex.data[iPixel];\r\n\t\t\t\t\t\t\tRGBColorSum[1] += pTex.data[iPixel + 1];\r\n\t\t\t\t\t\t\tRGBColorSum[2] += pTex.data[iPixel + 2];\r\n\t\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//right above pixel\r\n\t\t\t\t\tif ((x < pTex.width - 1) && (y > 0)) {\r\n\t\t\t\t\t\tint iPixel = ((y - 1) * pTex.width + (x + 1)) * 4;\r\n\t\t\t\t\t\tif (!((pTex.data[iPixel] == 0) && (pTex.data[iPixel + 1] == 0) && (pTex.data[iPixel + 2] == 255))) {\r\n\t\t\t\t\t\t\tRGBColorSum[0] += (unsigned int)((float)pTex.data[iPixel + 0] * sqrt2);\r\n\t\t\t\t\t\t\tRGBColorSum[1] += (unsigned int)((float)pTex.data[iPixel + 1] * sqrt2);\r\n\t\t\t\t\t\t\tRGBColorSum[2] += (unsigned int)((float)pTex.data[iPixel + 2] * sqrt2);\r\n\t\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//left pixel\r\n\t\t\t\t\tif (x > 0) {\r\n\t\t\t\t\t\tint iPixel = (y * pTex.width + (x - 1)) * 4;\r\n\t\t\t\t\t\tif (!((pTex.data[iPixel] == 0) && (pTex.data[iPixel + 1] == 0) && (pTex.data[iPixel + 2] == 255))) {\r\n\t\t\t\t\t\t\tRGBColorSum[0] += pTex.data[iPixel];\r\n\t\t\t\t\t\t\tRGBColorSum[1] += pTex.data[iPixel + 1];\r\n\t\t\t\t\t\t\tRGBColorSum[2] += pTex.data[iPixel + 2];\r\n\t\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//right pixel\r\n\t\t\t\t\tif (x < pTex.width - 1) {\r\n\t\t\t\t\t\tint iPixel = (y * pTex.width + (x + 1)) * 4;\r\n\t\t\t\t\t\tif (!((pTex.data[iPixel] == 0) && (pTex.data[iPixel + 1] == 0) && (pTex.data[iPixel + 2] == 255))) {\r\n\t\t\t\t\t\t\tRGBColorSum[0] += pTex.data[iPixel];\r\n\t\t\t\t\t\t\tRGBColorSum[1] += pTex.data[iPixel + 1];\r\n\t\t\t\t\t\t\tRGBColorSum[2] += pTex.data[iPixel + 2];\r\n\t\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//left underneath pixel\r\n\t\t\t\t\tif ((x > 0) && (y < pTex.height - 1)) {\r\n\t\t\t\t\t\tint iPixel = ((y + 1) * pTex.width + (x - 1)) * 4;\r\n\t\t\t\t\t\tif (!((pTex.data[iPixel] == 0) && (pTex.data[iPixel + 1] == 0) && (pTex.data[iPixel + 2] == 255))) {\r\n\t\t\t\t\t\t\tRGBColorSum[0] += (unsigned int)((float)pTex.data[iPixel + 0] * sqrt2);\r\n\t\t\t\t\t\t\tRGBColorSum[1] += (unsigned int)((float)pTex.data[iPixel + 1] * sqrt2);\r\n\t\t\t\t\t\t\tRGBColorSum[2] += (unsigned int)((float)pTex.data[iPixel + 2] * sqrt2);\r\n\t\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//underneath pixel\r\n\t\t\t\t\tif ((x >= 0) && (y < pTex.height - 1)) {\r\n\t\t\t\t\t\tint iPixel = ((y + 1) * pTex.width + x) * 4;\r\n\t\t\t\t\t\tif (!((pTex.data[iPixel] == 0) && (pTex.data[iPixel + 1] == 0) && (pTex.data[iPixel + 2] == 255))) {\r\n\t\t\t\t\t\t\tRGBColorSum[0] += pTex.data[iPixel];\r\n\t\t\t\t\t\t\tRGBColorSum[1] += pTex.data[iPixel + 1];\r\n\t\t\t\t\t\t\tRGBColorSum[2] += pTex.data[iPixel + 2];\r\n\t\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//right underneath pixel\r\n\t\t\t\t\tif ((x < pTex.width - 1) && (y < pTex.height - 1)) {\r\n\t\t\t\t\t\tint iPixel = ((y + 1) * pTex.width + (x + 1)) * 4;\r\n\t\t\t\t\t\tif (!((pTex.data[iPixel] == 0) && (pTex.data[iPixel + 1] == 0) && (pTex.data[iPixel + 2] == 255))) {\r\n\t\t\t\t\t\t\tRGBColorSum[0] += (unsigned int)((float)pTex.data[iPixel + 0] * sqrt2);\r\n\t\t\t\t\t\t\tRGBColorSum[1] += (unsigned int)((float)pTex.data[iPixel + 1] * sqrt2);\r\n\t\t\t\t\t\t\tRGBColorSum[2] += (unsigned int)((float)pTex.data[iPixel + 2] * sqrt2);\r\n\t\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (count > 0) {\r\n\t\t\t\t\t\tRGBColorSum[0] /= count;\r\n\t\t\t\t\t\tRGBColorSum[1] /= count;\r\n\t\t\t\t\t\tRGBColorSum[2] /= count;\r\n\r\n\t\t\t\t\t\tpRGBTexture[index * 4 + 0] = RGBColorSum[0];\r\n\t\t\t\t\t\tpRGBTexture[index * 4 + 1] = RGBColorSum[1];\r\n\t\t\t\t\t\tpRGBTexture[index * 4 + 2] = RGBColorSum[2];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Merge pTex and pRGBTexture\r\n\t\tfor (int y = 0; y < pTex.height; y++) {\r\n\t\t\tfor (int x = 0; x < pTex.width; x++) {\r\n\t\t\t\tint index = y * pTex.width + x;\r\n\r\n\t\t\t\tif ((pRGBTexture[index * 4] != 0) || (pRGBTexture[index * 4 + 1] != 0) || (pRGBTexture[index * 4 + 2] != 255) || (pRGBTexture[index * 4 + 3] != 0))\r\n\t\t\t\t\tmemcpy(&pTex.data[index * 4], &pRGBTexture[index * 4], sizeof(unsigned char) * 4);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tauto texNameLess(const char* a, const char* b) {\r\n#ifdef WIN32\r\n\t\treturn _stricmp(a, b) < 0;\r\n#else\r\n\t\treturn strcasecmp(a, b) < 0;\r\n#endif\r\n\t}\r\n\r\n\tauto texNameEqual(const char* a, const char* b) {\r\n#ifdef WIN32\r\n\t\treturn _stricmp(a, b) == 0;\r\n#else\r\n\t\treturn strcasecmp(a, b) == 0;\r\n#endif\r\n\t}\r\n}\r\n\r\nWad::Wad(const fs::path& path)\r\n\t: wadFile(path, std::ios::binary) {\r\n\tif (!wadFile)\r\n\t\tthrow std::ios::failure(\"Failed to open file \" + path.string() + \" for reading\");\r\n\twadFile.exceptions(std::ios::badbit | std::ios::failbit);\r\n\tLoadDirectory();\r\n}\r\n\r\nauto Wad::loadTexture(const char* name) -> std::optional<MipmapTexture> {\r\n\tauto rawTex = GetTexture(name);\r\n\tif (rawTex.empty())\r\n\t\treturn {};\r\n\r\n\tMipmapTexture tex;\r\n\tCreateMipTexture(rawTex, tex);\r\n\treturn tex;\r\n}\r\n\r\nauto Wad::LoadDecalTexture(const char* name) -> std::optional<MipmapTexture> {\r\n\tauto rawTex = GetTexture(name);\r\n\tif (rawTex.empty())\r\n\t\treturn {};\r\n\r\n\tMipmapTexture tex;\r\n\tCreateDecalTexture(rawTex, tex);\r\n\treturn tex;\r\n}\r\n\r\nvoid Wad::LoadDirectory() {\r\n\tauto header = read<WadHeader>(wadFile);\r\n\r\n\t// check magic\r\n\tif (header.magic[0] != 'W' || header.magic[1] != 'A' || header.magic[2] != 'D' || (header.magic[3] != '2' && header.magic[3] != '3'))\r\n\t\tthrow std::ios::failure(\"Unknown WAD magic number: \" + std::string(header.magic, 4));\r\n\r\n\t// read and sort directory\r\n\tdirEntries.resize(header.nDir);\r\n\twadFile.seekg(header.dirOffset);\r\n\treadVector(wadFile, dirEntries);\r\n\r\n\tstd::sort(begin(dirEntries), end(dirEntries), [](const WadDirEntry& a, const WadDirEntry& b) {\r\n\t\treturn texNameLess(a.name, b.name);\r\n\t});\r\n}\r\n\r\nauto Wad::GetTexture(const char* name) -> std::vector<uint8_t> {\r\n\tconst auto it = std::lower_bound(begin(dirEntries), end(dirEntries), name, [](const WadDirEntry& e, const char* name) {\r\n\t\treturn texNameLess(e.name, name);\r\n\t});\r\n\r\n\tif (it == end(dirEntries) || !texNameEqual(it->name, name))\r\n\t\treturn {};\r\n\r\n\t// we can only handle uncompressed formats\r\n\tif (it->compressed)\r\n\t\tthrow std::runtime_error(\"WAD texture cannot be loaded. Cannot read compressed items\");\r\n\r\n\twadFile.seekg(it->nFilePos);\r\n\treturn readVector<uint8_t>(wadFile, it->nSize);\r\n}\r\n\r\nvoid Wad::CreateMipTexture(const std::vector<uint8_t>& rawTexture, MipmapTexture& mipTex) {\r\n\tconst auto* rawMipTex = (bsp30::MipTex*)rawTexture.data();\r\n\r\n\tauto width = rawMipTex->width;\r\n\tauto height = rawMipTex->height;\r\n\tconst auto palOffset = rawMipTex->offsets[3] + (width / 8) * (height / 8) + 2;\r\n\tconst auto* palette = rawTexture.data() + palOffset;\r\n\r\n\tfor (int level = 0; level < bsp30::MIPLEVELS; level++) {\r\n\t\tconst auto* pixel = &(rawTexture[rawMipTex->offsets[level]]);\r\n\r\n\t\tauto& img = mipTex.Img[level];\r\n\t\timg.channels = 4;\r\n\t\timg.width = width;\r\n\t\timg.height = height;\r\n\t\timg.data.resize(width * height * 4);\r\n\r\n\t\tfor (int i = 0; i < height * width; i++) {\r\n\t\t\tint palIndex = pixel[i] * 3;\r\n\r\n\t\t\timg.data[i * 4 + 0] = palette[palIndex + 0];\r\n\t\t\timg.data[i * 4 + 1] = palette[palIndex + 1];\r\n\t\t\timg.data[i * 4 + 2] = palette[palIndex + 2];\r\n\t\t\timg.data[i * 4 + 3] = 255;\r\n\t\t}\r\n\r\n\t\tApplyAlphaSections(mipTex.Img[level]);\r\n\r\n\t\twidth /= 2;\r\n\t\theight /= 2;\r\n\t}\r\n}\r\n\r\nvoid Wad::CreateDecalTexture(const std::vector<uint8_t>& rawTexture, MipmapTexture& mipTex) {\r\n\tconst auto* rawMipTex = (bsp30::MipTex*)rawTexture.data();\r\n\r\n\tauto width = rawMipTex->width;\r\n\tauto height = rawMipTex->height;\r\n\tconst auto palOffset = rawMipTex->offsets[3] + (width / 8) * (height / 8) + 2;\r\n\tconst auto* palette = rawTexture.data() + palOffset;\r\n\tconst auto* color = palette + 255 * 3;\r\n\r\n\tfor (int level = 0; level < bsp30::MIPLEVELS; level++) {\r\n\t\tconst auto* pixel = &(rawTexture[rawMipTex->offsets[level]]);\r\n\r\n\t\tauto& img = mipTex.Img[level];\r\n\t\timg.channels = 4;\r\n\t\timg.width = width;\r\n\t\timg.height = height;\r\n\t\timg.data.resize(width * height * 4);\r\n\r\n\t\tfor (int i = 0; i < height * width; i++) {\r\n\t\t\tint palIndex = pixel[i] * 3;\r\n\r\n\t\t\timg.data[i * 4 + 0] = color[0];\r\n\t\t\timg.data[i * 4 + 1] = color[1];\r\n\t\t\timg.data[i * 4 + 2] = color[2];\r\n\t\t\timg.data[i * 4 + 3] = 255 - palette[palIndex];\r\n\t\t}\r\n\r\n\t\tApplyAlphaSections(mipTex.Img[level]);\r\n\r\n\t\twidth /= 2;\r\n\t\theight /= 2;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "1b12b656bfe6d473b058bf6faeb4ae0a09d3c98d", "size": 9574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Wad.cpp", "max_stars_repo_name": "bernhardmgruber/hlbsp", "max_stars_repo_head_hexsha": "a2144818fb6e747409dcd93cab97cea7f055dbfd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-04-16T19:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T04:12:20.000Z", "max_issues_repo_path": "src/Wad.cpp", "max_issues_repo_name": "bernhardmgruber/hlbsp", "max_issues_repo_head_hexsha": "a2144818fb6e747409dcd93cab97cea7f055dbfd", "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/Wad.cpp", "max_forks_repo_name": "bernhardmgruber/hlbsp", "max_forks_repo_head_hexsha": "a2144818fb6e747409dcd93cab97cea7f055dbfd", "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.6757679181, "max_line_length": 152, "alphanum_fraction": 0.5592228953, "num_tokens": 3233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.19954528197196067}}
{"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 <thread>\n#include <numeric>\n#include <atomic>\n#include <bitset>\n#include <fstream>\n#include <unordered_map>\n\n#include <boost/format.hpp>\n#include <boost/assert.hpp>\n\n#include \"app/pretty_printer.h\"\n#include \"ps/base/algorithm.h\"\n#include \"ps/base/board_combination_iterator.h\"\n#include \"ps/base/cards.h\"\n#include \"ps/base/cards.h\"\n#include \"ps/base/frontend.h\"\n#include \"ps/base/holdem_board_decl.h\"\n#include \"ps/base/rank_hasher.h\"\n#include \"ps/base/suit_hasher.h\"\n#include \"ps/base/tree.h\"\n\n#include \"ps/detail/tree_printer.h\"\n\n#include \"ps/eval/class_cache.h\"\n#include \"ps/eval/pass_mask_eval.h\"\n#include \"ps/eval/instruction.h\"\n\n#include \"ps/support/config.h\"\n#include \"ps/support/index_sequence.h\"\n\n#include <boost/timer/timer.hpp>\n\n#include <boost/log/trivial.hpp>\n\n#include <Eigen/Dense>\n\n#include \"ps/support/command.h\"\n\n#include <boost/iterator/indirect_iterator.hpp>\n#include \"ps/eval/holdem_class_vector_cache.h\"\n\n\n/*\n * 2 player\n        \n        player ev\n        =========\n \n        ---+---------------\n        f_ | 0\n        pf | sb+bb\n        pp | 2*S*Ev - (S-sb)\n\n        ---+---------------\n        pf | 0\n        pp | 2*S*Ev - (S-bb)\n        \n\n        total value\n        ===========\n\n\n        ---+---------------\n        f_ | -sb\n        pf | bb\n        pp | 2*S*Ev - S\n        \n        ---+---------------\n        pf | -sb\n        pp | 2*S*Ev - S\n\n\n\n\n\n                2 players\n\n                             P1         P2\n                        -- (fold) -->                 f\n                        -- (push) --> (fold) -->      pf\n                        -- (push) --> (call) -->      pp\n                             \n                3 players\n                             P1         P2         P3\n                        -- (fold) --> (fold)              ff\n                        -- (fold) --> (push) --> (fold)   fpf\n                        -- (fold) --> (push) --> (call)   fpp\n                        -- (push) --> (fold) --> (fold)   pff\n                        -- (push) --> (fold) --> (call)   pfp\n                        -- (push) --> (call) --> (fold)   ppf\n                        -- (push) --> (call) --> (call)   ppp\n\n\n\n                f(2) -> g({pp,pf,fp,ff}) -> {pp,pf,fp,ff} \\ { perm : all actions fold before last player }\n                                                             \\------- always size 2 (n, as f*f, f*p -----/\n\n                => |f(2)| = |{pp,pf,fp,ff}| - |{fp,ff}| \n                => |f(3)| = |{ppp,ppf,pfp,pff,fpp,fpf,ffp,fff}| - |{ffp,fff}| = 2 ^ 3 - 2 = 6\n\n                    f(3) = {ppp,ppf,pfp,pff,fpp,fpf,ff}\n                        \n                    q(0) = {ppp,ppf,pfp,pff},{fpp,fpf,ff}\n                            ^   ^   ^   ^     ^   ^   ^\n\n                    q(1) = {ppp,ppf},{pfp,pff},{fpp,fpf},{ff}\n                            _^  _^    _^  _^    _^  _^    _^\n                    \n                    q(2) = {ppp},{ppf},{pfp},{pff},{fpp},{fpf },{ff}\n                            __^   __^   __^   __^   __^   __^\n\n\n\n */\n\nnamespace ps {\n\n        inline Eigen::VectorXd choose_push_fold(Eigen::VectorXd const& push, Eigen::VectorXd const& fold){\n                Eigen::VectorXd result(169);\n                result.fill(.0);\n                for(holdem_class_id id=0;id!=169;++id){\n                        if( push(id) >= fold(id) ){\n                                result(id) = 1.0;\n                        }\n                }\n                return result;\n        }\n        inline Eigen::VectorXd clamp(Eigen::VectorXd s){\n                for(holdem_class_id idx=0;idx!=169;++idx){\n                        s(idx) = ( s(idx) < .5 ? .0 : 1. );\n                }\n                return s;\n        }\n\n        \n\n        \n\n        \n        struct eval_tree_node;\n\n        struct gt_context{\n                gt_context(size_t num_players, double eff, double sb, double bb)\n                        :num_players_{num_players},\n                        eff_(eff),\n                        sb_(sb),\n                        bb_(bb)\n                {}\n                size_t num_players()const{ return num_players_; }\n                double eff()const{ return eff_; }\n                double sb()const{ return sb_; }\n                double bb()const{ return bb_; }\n\n                gt_context& use_game_tree(std::shared_ptr<eval_tree_node> gt){\n                        gt_ = gt;\n                        return *this;\n                }\n                gt_context& use_cache(class_cache const& cc){\n                        cc_ = &cc;\n                        return *this;\n                }\n                \n                std::shared_ptr<eval_tree_node> root()const{\n                        return gt_;\n                }\n                class_cache const* cc()const{\n                        return cc_;\n                }\n                \n                friend std::ostream& operator<<(std::ostream& ostr, gt_context const& self){\n                        ostr << \"eff_ = \" << self.eff_;\n                        ostr << \", sb_ = \" << self.sb_;\n                        ostr << \", bb_ = \" << self.bb_;\n                        return ostr;\n                }\n        private:\n                size_t num_players_;\n                double eff_;\n                double sb_;\n                double bb_;\n\n                std::shared_ptr<eval_tree_node> gt_;\n                class_cache const* cc_;\n        };\n\n        double eval_prob_from_key(std::string const& key, Eigen::VectorXd const& vec){\n                enum{ Debug = 0 };\n                static std::unordered_map<std::string, size_t> reg_alloc = {\n                                     //  Player\n                        { \"\"  , 0 }, //   0\n                        { \"p\" , 1 }, //   1\n                        { \"f\" , 2 }, //   1\n                        { \"pp\", 3 }, //   2\n                        { \"pf\", 4 }, //   2\n                        { \"fp\", 5 }  //   2\n                };\n                double result = 1.0;\n                std::string sub;\n                std::stringstream dbg;\n                for(size_t idx=0;idx!=key.size();++idx){\n                        if( reg_alloc.count(sub) == 0 ){\n                                throw std::domain_error(\"bad\");\n                        }\n                        auto reg = reg_alloc[sub];\n                        switch(key[idx]){\n                        case 'p':\n                        case 'P':\n                        {\n                                dbg << \"P<\" << reg << \",\" << ( vec[reg] ) << \">\";\n                                result *= vec[reg];\n                                sub += 'p';\n                                break;\n                        }\n                        case 'f':\n                        case 'F':\n                        {\n                                dbg << \"F<\" << reg << \",\" << ( 1 - vec[reg] )<<\">\";\n                                result *= ( 1 - vec[reg] );\n                                sub += 'f';\n                                break;\n                        }}\n                }\n                if( Debug ) std::cout << dbg.str() << \"\\n\";\n                return result;\n        }\n        void __eval_prob_from_key_test(){\n                Eigen::VectorXd v(6);\n                double a =  0.2; // <nothing>\n                double b =  0.3; // p\n                double c =  0.5; // f\n                double d =  0.7; // pp\n                double e = 0.11; // pf\n                double f = 0.13; // fp\n                \n                double A = ( 1.0 - a);\n                double B = ( 1.0 - b);\n                double C = ( 1.0 - c);\n                double D = ( 1.0 - d);\n                double E = ( 1.0 - e);\n                double F = ( 1.0 - f);\n\n                v[0] = a;\n                v[1] = b;\n                v[2] = c;\n                v[3] = d;\n                v[4] = e;\n                v[5] = f;\n\n                auto check = [](std::string const& expr_s, auto expr,\n                                std::string const& exp_s, auto exp){\n                        double epsilon = 1e-3;\n                        if( ! (std::fabs(expr - exp) < epsilon ) ){\n                                std::stringstream sstr;\n                                sstr << std::fixed;\n                                sstr << expr_s << \"=\" << expr << \", \";\n                                sstr << exp_s << \"=\" << exp;\n                                throw std::domain_error(sstr.str());\n                        }\n                };\n                #define check(expr,exp) check(#expr, expr, #exp, exp)\n                check( eval_prob_from_key(\"p\"  , v), a    );\n                check( eval_prob_from_key(\"f\"  , v), A    );\n                check( eval_prob_from_key(\"pp\" , v), a*b  );\n                check( eval_prob_from_key(\"pf\" , v), a*B  );\n                check( eval_prob_from_key(\"fp\" , v), A*c  );\n                check( eval_prob_from_key(\"ff\" , v), A*C  );\n                \n                check( eval_prob_from_key(\"ppp\" , v), a*b*d  );\n                check( eval_prob_from_key(\"pfp\" , v), a*B*e  );\n                check( eval_prob_from_key(\"fpp\" , v), A*c*f  );\n                //check( eval_prob_from_key(\"ffp\" , v), A*C  );\n                check( eval_prob_from_key(\"ppf\" , v), a*b*D  );\n                check( eval_prob_from_key(\"pff\" , v), a*B*E  );\n                check( eval_prob_from_key(\"fpf\" , v), A*c*F  );\n                //check( eval_prob_from_key(\"fff\" , v), A*C  );\n\n                \n                #undef check\n\n        }\n        static int __eval_prob_from_key_test_mem = ( __eval_prob_from_key_test(), 0 );\n\n\n\n        struct eval_tree_node{\n                /*\n                        \\param[out]  out   A vector of size ctx.num_players(), which will be \n                                           used to hold the probability weight result\n  \n                        \\param[in]   ctx   A gt_context for sb,bb,eff etc\n\n                        \\param[in]   vec   A holdem class vector, representing the combination\n                                           of hand deals between the players. For any N-player\n                                           game, any hand deal can be represented of some \n                                           N-tuple of holdem class ids.\n\n                        \\param[in]   s     A probability realization of the strategy vector.\n                                           This is equivalent to\n                                                P(c=c0)P(c=c1|x)P(c=c2|xx)...,\n                                           ie each \n                 */\n                virtual void evaluate(Eigen::VectorXd& out,\n                                      gt_context const& ctx,\n                                      holdem_class_vector const& vec,\n                                      Eigen::VectorXd const& s)=0;\n                virtual void display(std::ostream& ostr = std::cout)const=0;\n        };\n        struct eval_tree_node_static : eval_tree_node{\n                explicit eval_tree_node_static(std::string const& key, Eigen::VectorXd vec):\n                        key_{key}, vec_{vec}\n                {}\n\n                virtual void evaluate(Eigen::VectorXd& out,\n                                      gt_context const& ctx,\n                                      holdem_class_vector const& vec,\n                                      Eigen::VectorXd const& s)override\n                {\n                        auto p = eval_prob_from_key(key_, s);\n                        //std::cout << \"--\" << key_ << \" => \" << p << \"\\n\";\n                        for(size_t idx=0;idx!=vec_.size();++idx){\n                                out[idx] += vec_[idx] * p;\n                        }\n                        //out += vec_ * p;\n                        out[vec.size()] += p;\n                }\n                virtual void display(std::ostream& ostr = std::cout)const override{\n                        ostr << \"Static{\" << key_\n                                          << \", \" << vector_to_string(vec_) << \"\\n\";\n                }\n        private:\n                std::string key_;\n                Eigen::VectorXd vec_;\n        };\n\n        #if 0\n        struct eval_tree_node_eval : eval_tree_node{\n                template<class... Args>\n                explicit\n                eval_tree_node_eval(Args&&...)\n                {\n                        v_mask_.resize(2);\n                        v_mask_.fill(1);\n                }\n                virtual void evaluate(Eigen::VectorXd& out,\n                                      double p,\n                                      gt_context const& ctx,\n                                      holdem_class_vector const& vec,\n                                      Eigen::VectorXd const& s)override\n                {\n                        auto q = factor(s);\n                        p *= q;\n                        if( std::fabs(p) < 0.001 )\n                                return;\n\n                        auto ev = ctx.cc()->LookupVector(vec);\n\n                        auto equity_vec = ( v_mask_.size() * ev - v_mask_ ) * ctx.eff() * p;\n\n                        out += equity_vec;\n                        out[vec.size()] += p;\n                }\n                virtual void display(std::ostream& ostr = std::cout)const override{\n                        ostr << \"Eval{\" << vector_to_string(v_mask_) << \"\\n\";\n                }\n        private:\n                Eigen::VectorXd v_mask_;\n        };\n        #endif\n\n        struct eval_tree_node_eval : eval_tree_node{\n                enum{ Debug = 0 };\n                explicit\n                eval_tree_node_eval(std::string const& key,\n                                    std::vector<size_t> perm,\n                                    Eigen::VectorXd const& dead_money,\n                                    Eigen::VectorXd const& active)\n                        :key_(key), perm_{perm}, dead_money_{dead_money}, active_{active}\n                        ,pot_amt_{active_.sum() + dead_money_.sum()}\n                {\n\n                        delta_proto_.resize(dead_money_.size()+1);\n                        delta_proto_.fill(0);\n                        for(size_t idx=0;idx!=active_.size();++idx){\n                                delta_proto_[idx] -= active_[idx];\n                                delta_proto_[idx] -= dead_money_[idx];\n                        }\n                        \n                        if( Debug ){\n                                std::cout << \"perm => \" << detail::to_string(perm) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,perm)\n                                std::cout << \"dead_money_ => \" << vector_to_string(dead_money_) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,dead_money_)\n                                std::cout << \"active_ => \" << vector_to_string(active_) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,active_)\n                                std::cout << \"delta_proto_ => \" << vector_to_string(delta_proto_) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,delta_proto_)\n                                std::cout << \"pot_amt_ => \" << pot_amt_ << \"\\n\"; // __CandyPrint__(cxx-print-scalar,pot_amt_)\n                        }\n\n                }\n                virtual void evaluate(Eigen::VectorXd& out,\n                                      gt_context const& ctx,\n                                      holdem_class_vector const& cv,\n                                      Eigen::VectorXd const& s)override\n                {\n                        auto p = eval_prob_from_key(key_, s);\n\n                        //std::cout << \"--\" << key_ << \" => \" << p << \"\\n\";\n\n                        // short circuit for optimization purposes\n                        if( std::fabs(p) < 0.001 )\n                                return;\n\n                        holdem_class_vector tmp;\n                        for(auto _ : perm_ ){\n                                tmp.push_back(cv[_]);\n                        }\n                        \n                        auto ev = ctx.cc()->LookupVector(tmp);\n                        \n\n                        Eigen::VectorXd delta = delta_proto_;\n\n                        size_t ev_idx = 0;\n                        for( auto _ :perm_ ){\n                                delta[_] += pot_amt_ * ev[ev_idx];\n                                ++ev_idx;\n                        }\n\n                        //std::cout << \"key=\" << key_ << \",p\" << p << \", cv=\" << cv << \", delta=\" << vector_to_string(delta) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,vector_to_string(delta))\n                        delta *= p;\n\n\n                        out += delta;\n                        // for checking\n                        out[ctx.num_players()] += p;\n                }\n                virtual void display(std::ostream& ostr = std::cout)const override{\n                        ostr << \"Eval{\" << key_ \n                                        << \", \" << detail::to_string(perm_)\n                                        << \", \" << vector_to_string(dead_money_)\n                                        << \", \" << vector_to_string(active_) \n                             << \"}\\n\";\n                }\n        private:\n                std::string key_;\n                std::vector<size_t> perm_;\n                Eigen::VectorXd dead_money_;\n                Eigen::VectorXd active_;\n                Eigen::VectorXd delta_proto_;\n                double pot_amt_;\n        };\n\n        struct eval_tree_non_terminal\n                : public eval_tree_node\n                , public std::vector<std::shared_ptr<eval_tree_node> >\n        {\n                virtual void evaluate(Eigen::VectorXd& out,\n                                      gt_context const& ctx,\n                                      holdem_class_vector const& vec,\n                                      Eigen::VectorXd const& s)override\n                {\n                        //std::cout << \"Begin{}\\n\";\n                        for(auto& ptr : *this){\n                                ptr->evaluate(out, ctx, vec, s);\n                        }\n                        //std::cout << \"End{}\\n\";\n                }\n                virtual void display(std::ostream& ostr = std::cout)const override{\n                        ostr << \"Begin{}\\n\";\n                        for(auto const& ptr : *this){\n                                ptr->display(ostr);\n                        }\n                        ostr << \"End{}\\n\";\n                }\n        };\n        \n        struct hu_eval_tree_flat : eval_tree_non_terminal{\n                explicit\n                hu_eval_tree_flat( gt_context const& ctx){\n                        Eigen::VectorXd v_f_{2};\n                        v_f_(0) = -ctx.sb();\n                        v_f_(1) =  ctx.sb();\n                        auto n_f_ = std::make_shared<eval_tree_node_static>(\"f\", v_f_);\n                        push_back(n_f_);\n\n                        Eigen::VectorXd v_pf{2};\n                        v_pf(0) =  ctx.bb();\n                        v_pf(1) = -ctx.bb();\n                        auto n_pf = std::make_shared<eval_tree_node_static>(\"pf\", v_pf);\n                        push_back(n_pf);\n\n                        Eigen::VectorXd dead_money = Eigen::VectorXd::Zero(2);\n                        Eigen::VectorXd active{2};\n                        active[0] = ctx.eff();\n                        active[1] = ctx.eff();\n                        auto n_pp = std::make_shared<eval_tree_node_eval>(\"pp\", std::vector<size_t>{0,1}, dead_money, active);\n                        //auto n_pp = std::make_shared<eval_tree_node_eval>();\n                        push_back(n_pp);\n                }\n        };\n\n        #if 0\n        struct hu_eval_tree : eval_tree_non_terminal{\n                explicit\n                hu_eval_tree( gt_context const& ctx){\n\n\n                        Eigen::VectorXd v_f_{2};\n                        v_f_(0) = -ctx.sb();\n                        v_f_(1) =  ctx.sb();\n                        auto n_f_ = std::make_shared<eval_tree_node_static>(v_f_);\n                        n_f_->not_times(0);\n                        push_back(n_f_);\n\n                        auto n_p_ = std::make_shared<eval_tree_non_terminal>();\n                        n_p_->times(0);\n\n                        Eigen::VectorXd v_pf{2};\n                        v_pf(0) =  ctx.bb();\n                        v_pf(1) = -ctx.bb();\n                        auto n_pf = std::make_shared<eval_tree_node_static>(v_pf);\n                        n_pf->not_times(1);\n                        n_p_->push_back(n_pf);\n\n                        Eigen::VectorXd dead_money = Eigen::VectorXd::Zero(2);\n                        Eigen::VectorXd active{2};\n                        active[0] = ctx.eff();\n                        active[1] = ctx.eff();\n                        auto n_pp = std::make_shared<eval_tree_node_eval>(std::vector<size_t>{0,1}, dead_money, active);\n                        //auto n_pp = std::make_shared<eval_tree_node_eval>();\n                        n_pp->times(1);\n                        n_p_->push_back(n_pp);\n\n                        push_back(n_p_);\n\n                }\n        };\n        #endif\n\n        struct three_way_eval_tree : eval_tree_non_terminal{\n                explicit\n                three_way_eval_tree( gt_context const& ctx){\n\n                        // p p p \n\n                        size_t num_players = 3;\n                                \n\n                        Eigen::VectorXd stacks{num_players};\n                        for(size_t idx=0;idx!=num_players;++idx){\n                                stacks[idx] = ctx.eff();\n                        }\n\n\n                        Eigen::VectorXd v_blinds{num_players};\n                        v_blinds.fill(0.0);\n                        v_blinds[1] = ctx.sb();\n                        v_blinds[2] = ctx.bb();\n\n                        auto make_static = [&](std::string const& key, size_t target){\n                                Eigen::VectorXd sv = -v_blinds;\n                                sv[target] += v_blinds.sum();\n                                auto ptr = std::make_shared<eval_tree_node_static>(key, sv);\n                                return ptr;\n                        };\n\n                        for(unsigned long long mask = ( 1 << num_players ); mask != 0;){\n                                --mask;\n                                std::bitset<32> bs = {mask};\n\n\n                                std::string key;\n                                std::vector<size_t> perm;\n                                Eigen::VectorXd dead_money = Eigen::VectorXd::Zero(3);\n                                Eigen::VectorXd active     = Eigen::VectorXd::Zero(3);\n\n                                for(size_t idx=0;idx!= num_players;++idx){\n                                        if( bs.test(idx) ){\n                                                active[idx] = stacks[idx];\n                                                perm.push_back(idx);\n                                                key += \"p\";\n                                        } else{\n                                                dead_money[idx] = v_blinds[idx];\n                                                key += \"f\";\n                                        }\n                                }\n\n                                if( bs.count() == 0 )\n                                        continue;\n                                if( bs.count() == 1 && bs.test(num_players-1) ){\n                                        // walk\n                                        std::string degenerate_key(num_players-1, 'f');\n                                        auto walk = make_static(degenerate_key, num_players-1);\n                                        push_back(walk);\n                                } else if( bs.count() == 1 ){\n                                        // steal \n                                        auto steal = make_static(key, perm[0]);\n                                        push_back(steal);\n                                } else { \n                                        // push call\n\n                                        auto allin = std::make_shared<eval_tree_node_eval>(key, perm, dead_money, active);\n                                        push_back(allin);\n                                }\n                                \n                        }\n                }\n        };\n        \n\n        // returns a vector each players hand value\n        Eigen::VectorXd combination_value(gt_context const& ctx,\n                                          holdem_class_vector const& vec,\n                                          Eigen::VectorXd const& s){\n                Eigen::VectorXd result{vec.size()+1};\n                result.fill(.0);\n                ctx.root()->evaluate(result, ctx, vec,s);\n                //std::cout << \"result[vec.size()] => \" << result[vec.size()] << \"\\n\"; // __CandyPrint__(cxx-print-scalar,result[vec.size()])\n\n                return result;\n        }\n\n        /*\n                \\param[in]  idx  The index of the strategy vector, for example\n                                 for hu index 0 is for sb to push, whilst index\n                                 1 is for bb to call a push (given the action p),\n                                 ie \n                                        Index |Player|  key  | Given |   P\n                                        ------+------+-------+-------+------\n                                          0   |   0  |   p   |       | P(p)\n                                          1   |   1  |   pp  |   p   | P(p|p)\n\n                                For three player this canonical mapping doesn't\n                                apply, we have\n                                        \n                                        Index |Player|  Key  | Given |   P\n                                        ------+------+-------+-------+------\n                                          0   |   0  |   p   |       | P(p)\n                                          1   |   1  |   pp  |   p   | P(p|p)\n                                          2   |   1  |   fp  |   f   | P(p|f)\n                                          3   |   2  |   ppp |   pp  | P(p|pp)\n                                          4   |   2  |   pfp |   pf  | P(p|pf)\n                                          5   |   2  |   fpp |   fp  | P(p|fp)\n        */\n        Eigen::VectorXd unilateral_detail(gt_context const& ctx,\n                                          size_t idx,\n                                          std::vector<Eigen::VectorXd> const& S)\n        {\n                Eigen::VectorXd result(169);\n                result.fill(.0);\n                        \n                Eigen::VectorXd s(S.size());\n\n                auto player_idx = [](auto id){\n                        switch(id){\n                        case 0:\n                                return 0;\n                        case 1:\n                        case 2:\n                                return 1;\n                        case 3:\n                        case 4:\n                        case 5:\n                                return 2;\n                        }\n                        PS_UNREACHABLE();\n                };\n\n                if( ctx.num_players() == 3 ){\n                        for(auto const& _ : *Memory_ThreePlayerClassVector){\n                                auto const& cv = _.cv;\n                                // create a view of the vector, nothing fancy\n                                //\n                                // The strategy vector is of size 2,6,etc, each a vector of size 169\n                                // for a realization, we want to take \n                                for(size_t j=0;j!=s.size();++j){\n                                        s[j] = S[j][cv[player_idx(j)]];\n                                }\n                                auto meta_result = combination_value(ctx, cv, s);\n                                result(cv[player_idx(idx)]) += _.prob * meta_result[player_idx(idx)];\n                        }\n                } else {\n                        for(holdem_class_perm_iterator iter(ctx.num_players()),end;iter!=end;++iter){\n\n                                auto const& cv = *iter;\n                                auto p = cv.prob();\n                                // create a view of the vector, nothing fancy\n                                for(size_t idx=0;idx!=s.size();++idx){\n                                        s[idx] = S[idx][cv[idx]];\n                                }\n                                auto meta_result = combination_value(ctx, cv, s);\n                                result(cv[idx]) += p * meta_result[idx];\n                        }\n                }\n\n                return result;\n        }\n        \n        Eigen::VectorXd unilateral_maximal_exploitable(gt_context const& ctx, size_t idx, std::vector<Eigen::VectorXd> const& S)\n        {\n\n                enum{ Dp = 4 };\n                enum{ Debug = 0};\n                static Eigen::VectorXd fold_s = Eigen::VectorXd::Zero(169);\n                static Eigen::VectorXd push_s = Eigen::VectorXd::Ones(169);\n                if(Debug) std::cout << \"============== idx = \" << idx << \" =====================\\n\";\n                auto copy = S;\n                copy[idx] = push_s;\n                auto push = unilateral_detail(ctx, idx, copy);\n                if(Debug) pretty_print_strat(push, Dp);\n\n                copy[idx] = fold_s;\n                auto fold = unilateral_detail(ctx, idx, copy);\n                if(Debug) pretty_print_strat(fold, Dp);\n\n                return choose_push_fold(push, fold);\n        }\n\n\n\n\n\n        \n\n        struct solver{\n                virtual std::vector<Eigen::VectorXd> step(gt_context const& ctx,\n                                                          std::vector<Eigen::VectorXd> const& state)=0;\n        };\n        struct maximal_exploitable_solver_uniform : solver{\n                explicit maximal_exploitable_solver_uniform(double factor = 0.05):factor_{factor}{}\n                virtual std::vector<Eigen::VectorXd> step(gt_context const& ctx,\n                                                          std::vector<Eigen::VectorXd> const& state)override\n                {\n                        std::vector<Eigen::VectorXd> result(state.size());\n                        \n                        //for(size_t idx=0;idx!=state.size();++idx){\n                        for(size_t idx=state.size();idx!=0;){\n                                --idx;\n\n                                auto counter = unilateral_maximal_exploitable(ctx,idx, state);\n                                result[idx] = state[idx] * ( 1.0 - factor_ ) + counter * factor_;\n                        }\n                        return result;\n                }\n        private:\n                double factor_;\n        };\n        struct maximal_exploitable_solver_uniform_mt : solver{\n                explicit maximal_exploitable_solver_uniform_mt(double factor = 0.05):factor_{factor}{}\n                virtual std::vector<Eigen::VectorXd> step(gt_context const& ctx,\n                                                          std::vector<Eigen::VectorXd> const& state)override\n                {\n                        boost::timer::auto_cpu_timer at;\n                        using result_t = std::future<std::tuple<size_t, Eigen::VectorXd> >;\n                        std::vector<result_t> tmp;\n                        for(size_t idx=0;idx!=state.size();++idx){\n                                auto fut = std::async(std::launch::async, [idx,&ctx,&state,this](){\n                                        return std::make_tuple(idx,unilateral_maximal_exploitable(ctx,idx, state));\n                                });\n                                tmp.emplace_back(std::move(fut));\n                        }\n                        std::cout << \"tmp.size() => \" << tmp.size() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,tmp.size())\n                        std::vector<Eigen::VectorXd> result(state.size());\n                        for(auto& _ : tmp){\n                                auto ret = _.get();\n                                auto idx            = std::get<0>(ret);\n                                auto const& counter = std::get<1>(ret);\n                                result[idx] = state[idx] * ( 1.0 - factor_ ) + counter * factor_;\n                        }\n                        return result;\n                }\n        private:\n                double factor_;\n        };\n\n\n        struct cond_single_strategy_lp1{\n                using state_t = std::vector<Eigen::VectorXd>;\n                cond_single_strategy_lp1(size_t idx, double epsilon)\n                        :idx_(idx),\n                        epsilon_(epsilon)\n                {}\n                bool operator()(state_t const& from, state_t const& to)const{\n                        auto d = from[idx_] - to[idx_];\n                        auto norm = d.lpNorm<1>();\n                        auto cond = ( norm < epsilon_ );\n                        std::cout << \"norm => \" << norm << \"\\n\"; // __CandyPrint__(cxx-print-scalar,norm)\n                        return cond;\n                }\n        private:\n                size_t idx_;\n                double epsilon_;\n        };\n\n        struct make_solver{\n                \n                enum{ DefaultMaxIter = 400 };\n\n                using state_t         = std::vector<Eigen::VectorXd>;\n                using step_observer_t = std::function<void(state_t const&)>;\n                using stoppage_condition_t = std::function<bool(state_t const&, state_t const&)>;\n\n                explicit make_solver(gt_context const& ctx){\n                        ctx_ = &ctx;\n                }\n                make_solver& use_solver(std::shared_ptr<solver> s){\n                        solver_ = s;\n                        return *this;\n                }\n                make_solver& max_steps(size_t n){\n                        max_steps_ = n;\n                        return *this;\n                }\n                make_solver& init_state(std::vector<Eigen::VectorXd> const& s0){\n                        state0_ = s0;\n                        return *this;\n                }\n                make_solver& observer(step_observer_t obs){\n                        obs_.push_back(obs);\n                        return *this;\n                }\n                make_solver& stoppage_condition(stoppage_condition_t cond){\n                        stop_cond_ = cond;\n                        return *this;\n                }\n                std::vector<Eigen::VectorXd> run(){\n\n                        BOOST_ASSERT(ctx_ );\n                        BOOST_ASSERT(solver_ );\n                        BOOST_ASSERT(state0_.size() );\n                        BOOST_ASSERT( stop_cond_ );\n\n                        std::vector<Eigen::VectorXd> state = state0_;\n                        for(auto& _ : obs_){\n                                _(state);\n                        }\n\n                        for(size_t idx=0;idx<max_steps_;++idx){\n\n                                auto next = solver_->step(*ctx_, state);\n\n                                if( stop_cond_(state, next) ){\n                                        state[0] = clamp(state[0]);\n                                        state[1] = clamp(state[1]);\n                                        return state;\n                                }\n                                state = next;\n                                for(auto& _ : obs_){\n                                        _(state);\n                                }\n\n                        }\n\n                        std::vector<Eigen::VectorXd> result;\n                        result.push_back(Eigen::VectorXd::Zero(169));\n                        result.push_back(Eigen::VectorXd::Zero(169));\n\n                        BOOST_LOG_TRIVIAL(warning) << \"Failed to converge solve ctx = \" << *ctx_;\n                        return result;\n                }\n        private:\n                gt_context const* ctx_;\n                std::shared_ptr<solver> solver_;\n                std::vector<Eigen::VectorXd> state0_;\n                std::vector<step_observer_t > obs_;\n                stoppage_condition_t stop_cond_;\n                size_t max_steps_{DefaultMaxIter};\n        };\n\n\n\n\n\n\nstruct HeadUpSolverCmd : Command{\n        explicit\n        HeadUpSolverCmd(std::vector<std::string> const& args):args_{args}{}\n        virtual int Execute()override{\n                class_cache cc;\n\t\n                std::string cache_name{\".cc.bin\"};\n                try{\n                        cc.load(cache_name);\n                }catch(std::exception const& e){\n                        std::cerr << \"Failed to load (\" << e.what() << \")\\n\";\n                        throw;\n                }\n\n\n                size_t num_players = 2;\n\n                // create a vector of num_players of zero vectors\n                std::vector<Eigen::VectorXd> state0( ( num_players == 2 ? 2 : 6 ) , Eigen::VectorXd::Zero(169));\n                for(auto& _ : state0){\n                        _.fill(0.5);\n                }\n                \n\n                using result_t = std::future<std::tuple<double, std::vector<Eigen::VectorXd> > >;\n                std::vector<result_t> tmp;\n\n                gt_context gtctx(num_players, 10, .5, 1.);\n\n                #if 0\n                hu_eval_tree{gtctx}.display();\n                hu_eval_tree_flat{gtctx}.display();\n                three_way_eval_tree{gtctx}.display();\n                #endif\n\n\n                auto solve = [&](auto num_players, auto eff){\n                        gt_context gtctx(num_players, eff, .5, 1.);\n                        std::shared_ptr<eval_tree_node> gt;\n                        switch(num_players){\n                        case 2:\n                                gt = std::make_shared<hu_eval_tree_flat>(gtctx);\n                                break;\n                        case 3:\n                                gt = std::make_shared<three_way_eval_tree>(gtctx);\n                                break;\n                        default:\n                                BOOST_THROW_EXCEPTION(std::domain_error(\"unsupported\"));\n                        }\n                        gt->display();\n                        gtctx.use_game_tree(gt);\n\n                        gtctx.use_cache(cc);\n                        auto result = make_solver(gtctx)\n                                .use_solver(std::make_shared<maximal_exploitable_solver_uniform_mt>())\n                                .stoppage_condition(cond_single_strategy_lp1(0, 0.1))\n                                .init_state(state0)\n                                #if 1\n                                .observer([](auto const& vec){\n                                          static std::vector<std::string> v = { \"\"  , \"p\" , \"f\" , \"pp\", \"pf\", \"fp\" };\n                                          for(size_t idx=0;idx!=vec.size();++idx){\n                                                  std::cout << \"--------\" << v[idx] << \"-------------\\n\";\n                                                  pretty_print_strat(vec[idx], 2);\n                                          }\n                                })\n                                #endif\n                                .run();\n                        return result;\n                };\n\n                auto enque = [&](double eff){\n                        tmp.push_back(std::async([&,num_players, eff](){\n                                auto result = solve(num_players, eff);\n                                return std::make_tuple(eff, result);\n                        }));\n                };\n                #if 0\n                for(double eff = 5.0;eff <= 50.0;eff+=1){\n                        enque(eff);\n                }\n                #else\n                enque(10);\n                #endif\n\n                #if 1\n                Eigen::VectorXd s0(169);\n                s0.fill(.0);\n                Eigen::VectorXd s1(169);\n                s1.fill(.0);\n                for(auto& _ : tmp){\n                        auto aux = _.get();\n                        auto eff = std::get<0>(aux);\n                        auto const& vec = std::get<1>(aux);\n                        for(size_t idx=0;idx!=169;++idx){\n                                s0(idx) = std::max(s0(idx), eff*vec[0](idx));\n                                s1(idx) = std::max(s1(idx), eff*vec[1](idx));\n                        }\n                }\n                \n                pretty_print_strat(s0, 1);\n                pretty_print_strat(s1, 1);\n\n\n\n\n                #if 0\n                auto order_cards = [](auto const& strat){\n                        struct HandAux{\n                                HandAux(size_t id_, double level_)\n                                        :id(id_),\n                                        level(level_),\n                                        decl{&holdem_hand_decl::get(id)}\n                                {}\n                                size_t id;\n                                double level;\n                                holdem_hand_decl const* decl;\n                                double cum_{.0};\n                        };\n                        std::vector<HandAux> aux;\n                        for(size_t idx=0;idx!=strat.size();++idx){\n                                aux.emplace_back(idx, strat[idx]);\n                        }\n                        // first sort by level\n                        std::sort( aux.begin(), aux.end(), [](auto const& l, auto const& r){\n                                return l.level > r.level;\n                        });\n                        holdem_hand_vector result;\n                        for(auto const& _ : aux){\n                                result.push_back(_.id);\n                        }\n                        \n\n                        return result;\n                };\n                #endif\n\n\n                #endif\n\n                #if 0\n                for(auto& _ : tmp){\n                        auto aux = _.get();\n                        auto const& vec = std::get<1>(aux);\n                        for(auto const& s : vec ){\n                                pretty_print_strat(s, 2);\n                        }\n                }\n                #endif\n\n\n\n                return EXIT_SUCCESS;\n        }\nprivate:\n        std::vector<std::string> const& args_;\n};\nstatic TrivialCommandDecl<HeadUpSolverCmd> HeadsUpSolverCmdDecl{\"heads-up-solver\"};\n        \n} // end namespace ps\n", "meta": {"hexsha": "71364aa8d61dee31b88585e37a05fc853f3caadb", "size": 43683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Trash/cmd_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/cmd_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/cmd_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": 41.2492917847, "max_line_length": 193, "alphanum_fraction": 0.3745164023, "num_tokens": 8350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.19954527822674611}}
{"text": "//\n// Created by dragos on 31.10.2018.\n//\n\n#include \"cegis.h\"\n#include \"cfg_algos.h\"\n#include <algorithm>\n#include <fstream>\n#include <boost/functional/hash.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n\nstd::pair<bool, z3::expr> cegis::deduce(z3::solver &slv) {\n  const auto &asserts = slv.assertions();\n  return {false, sigma.ctx().bool_val(true)};\n}\n\nz3::expr cegis::run() {\n  auto occs = occurences(sigma);\n  auto typed = typed_occurences(sigma);\n  std::set<std::string> non_consts;\n  for (const auto &p : occs) {\n    if (p.first.find(\"pre_call\") == std::string::npos) {\n      non_consts.emplace(p.first);\n    }\n  }\n  z3::solver slv(sigma.ctx());\n  auto nsigma = !sigma;\n  auto &ctx = sigma.ctx();\n  auto expand_bools = sigma;\n  while (true) {\n    if (slv.check() != z3::check_result::sat) {\n      return sigma.ctx().bool_val(false);\n    }\n    slv.push();\n    slv.add(nsigma);\n    auto cr2 = slv.check();\n    if (cr2 == z3::check_result::sat) {\n      auto cex = slv.get_model();\n      slv.pop();\n      auto deduced = deduce(slv);\n      auto res = deduced.first;\n      auto C = deduced.second;\n      if (res) {\n        return C;\n      } else {\n        auto sz = cex.size();\n        z3::expr_vector rep(ctx), with(ctx);\n        std::set<std::string> found;\n        for (unsigned i = 0; i != sz; ++i) {\n          auto fd = cex.get_const_decl(i);\n          auto v = cex.get_const_interp(fd);\n          if (fd.name().str().find(\"pre_call\") == std::string::npos) {\n            found.emplace(fd.name().str());\n            // means input variable\n            rep.push_back(fd());\n            with.push_back(v);\n          }\n        }\n        std::set<std::string> unfound;\n        std::set_difference(non_consts.begin(), non_consts.end(), found.begin(),\n                            found.end(), std::inserter(unfound, unfound.end()));\n        for (const auto &uf : unfound) {\n          auto tp = typed.find(uf)->second;\n          rep.push_back(ctx.constant(uf.c_str(), tp));\n          if (tp.is_bool()) {\n            with.push_back(ctx.bool_val(true));\n          } else {\n            with.push_back(ctx.num_val(0, tp));\n          }\n        }\n        slv.add(sigma.substitute(rep, with).simplify());\n      }\n    } else {\n      slv.pop();\n      return z3::mk_and(slv.assertions());\n    }\n  }\n}\n\nz3::expr cegis::replace_constants(const z3::expr &old) {\n  if (old.is_app()) {\n    if (old.decl().decl_kind() == Z3_OP_FALSE ||\n        old.decl().decl_kind() == Z3_OP_TRUE) {\n      return ctx().bool_const(next().c_str());\n    }\n    if (old.decl().decl_kind() == Z3_OP_DT_CONSTRUCTOR) {\n      return ctx().constant(next().c_str(), old.get_sort());\n    }\n    if (old.is_const()) {\n      if (old.decl().decl_kind() == Z3_OP_UNINTERPRETED) {\n        return old;\n      } else if (old.decl().decl_kind() == Z3_OP_BNUM) {\n        return ctx().constant(next().c_str(), old.get_sort());\n      }\n    }\n    auto num = old.num_args();\n    z3::expr_vector quoi(ctx());\n    for (unsigned i = 0; i != num; ++i) {\n      auto arg = old.arg(i);\n      quoi.push_back(replace_constants(arg));\n    }\n    return old.decl()(quoi);\n  } else if (old.is_numeral()) {\n    return ctx().constant(next().c_str(), old.get_sort());\n  }\n\n  return old;\n}\n\nstd::unordered_map<z3::expr, std::unordered_set<std::string>>\nunconstrained(const z3::expr &e, const std::map<std::string, unsigned> &occs) {\n  std::unordered_map<z3::expr, std::unordered_set<std::string>> ucterms;\n  std::function<void(const z3::expr &, std::vector<std::string> &)> lam;\n  lam = [&](const z3::expr &e, std::vector<std::string> &bounds) -> void {\n    if (e.is_app()) {\n      if (e.is_const() && e.decl().decl_kind() == Z3_OP_UNINTERPRETED)\n        return;\n      if (e.decl().decl_kind() == Z3_OP_DT_CONSTRUCTOR)\n        return;\n      if (e.decl().decl_kind() == Z3_OP_BNUM)\n        return;\n      std::vector<z3::expr> vars;\n      std::vector<z3::expr> nonvars;\n      for (unsigned i = 0; i != e.num_args(); ++i) {\n        if ((e.arg(i).is_const() &&\n             e.arg(i).decl().decl_kind() == Z3_OP_UNINTERPRETED) ||\n            e.arg(i).is_var()) {\n          vars.push_back(e.arg(i));\n        } else {\n          nonvars.push_back(e.arg(i));\n        }\n      }\n      bool uc = true;\n      std::unordered_set<std::string> involved;\n      for (auto &v : vars) {\n        std::string declname;\n        if (v.is_const()) {\n          declname = v.decl().name().str();\n        } else if (v.is_var()) {\n          declname = bounds[bounds.size() - 1 - Z3_get_index_value(v.ctx(), v)];\n        }\n        auto I = occs.find(declname);\n        if (I == occs.end() || I->second != 1) {\n          uc = false;\n        } else {\n          involved.emplace(declname);\n        }\n      }\n      if (e.is_eq() || e.decl().decl_kind() == Z3_OP_BADD) {\n        if (involved.size() == 1) {\n          ucterms[e] = std::move(involved);\n        } else {\n          for (auto &ex : nonvars) {\n            lam(ex, bounds);\n          }\n        }\n      } else {\n        if (nonvars.empty()) {\n          if (uc) {\n            ucterms[e] = std::move(involved);\n          }\n        } else {\n          for (auto &ex : nonvars) {\n            lam(ex, bounds);\n          }\n        }\n      }\n    } else if (e.is_quantifier()) {\n      auto nrs = Z3_get_quantifier_num_bound(e.ctx(), e);\n      for (unsigned i = 0; i != nrs; ++i) {\n        z3::symbol nm(e.ctx(), Z3_get_quantifier_bound_name(e.ctx(), e, i));\n        bounds.push_back(nm.str());\n      }\n      lam(e.body(), bounds);\n      for (unsigned i = 0; i != nrs; ++i)\n        bounds.pop_back();\n    } else if (e.is_var()) {\n      return;\n    }\n  };\n  std::vector<std::string> bounds;\n  lam(e, bounds);\n  return ucterms;\n};\n\nz3::expr remove_unconstrained(const z3::expr &expr,\n                              std::map<std::string, unsigned> &occurs) {\n  if (!expr.is_quantifier())\n    return expr;\n  auto nr = Z3_get_quantifier_num_bound(expr.ctx(), expr);\n  std::vector<z3::sort> sorts;\n  std::vector<std::string> names;\n  std::unordered_set<std::string> remove;\n  for (unsigned i = 0; i != nr; ++i) {\n    auto qname = Z3_get_quantifier_bound_name(expr.ctx(), expr, i);\n    z3::symbol symbol(expr.ctx(), qname);\n    names.push_back(symbol.str());\n    auto qsort = Z3_get_quantifier_bound_sort(expr.ctx(), expr, i);\n    z3::sort srt(expr.ctx(), qsort);\n    sorts.push_back(srt);\n  }\n  z3::expr_vector subs(expr.ctx());\n  for (unsigned i = 0; i != nr; ++i) {\n    subs.push_back(\n        expr.ctx().constant(names[nr - 1 - i].c_str(), sorts[nr - 1 - i]));\n  }\n  auto qfexpr = expr;\n  qfexpr = qfexpr.body().substitute(subs);\n  for (unsigned i = 0; i != nr; ++i) {\n    subs[i] = expr.ctx().constant(names[i].c_str(), sorts[i]);\n  }\n\n  BUG_CHECK(!qfexpr.is_quantifier(),\n            \"quantifier found even though not expecting one %1%\", qfexpr);\n\n  auto crt = qfexpr;\n  cegis c(expr);\n  bool change = true;\n  auto crtoccurences = occurs;\n  std::unordered_set<std::string> interesting;\n  std::transform(\n      occurs.begin(), occurs.end(),\n      std::inserter(interesting, interesting.begin()),\n      [](const std::pair<std::string, unsigned> &x) { return x.first; });\n  do {\n    LOG4(\"step: \" << crt);\n    change = false;\n    auto ucd = unconstrained(crt, crtoccurences);\n    for (auto &uc : ucd) {\n      LOG4(\"uc: \" << uc.first << Z3_get_ast_id(uc.first.ctx(), uc.first));\n      auto fresh = z3::expr(expr.ctx(), Z3_mk_fresh_const(expr.ctx(), \"v__\",\n                                                          uc.first.get_sort()));\n      auto fname = fresh.decl().name().str();\n      change = true;\n      z3::expr_vector src(uc.first.ctx());\n      src.push_back(uc.first);\n      z3::expr_vector dst(uc.first.ctx());\n      dst.push_back(fresh);\n      crt = crt.substitute(src, dst).simplify();\n      LOG4(\"after substitution:\" << crt << \" \");\n      interesting.emplace(fname);\n      remove.insert(uc.second.begin(), uc.second.end());\n      for (auto &rm : uc.second)\n        LOG4(\"removing \" << rm);\n      names.push_back(fname);\n      sorts.push_back(fresh.get_sort());\n      subs.push_back(fresh);\n    }\n    if (change) {\n      auto nocs = c.occurences(crt);\n      crtoccurences.clear();\n      for (auto &n : nocs) {\n        if (interesting.count(n.first))\n          crtoccurences.emplace(n);\n      }\n    }\n  } while (change);\n\n  z3::expr_vector qs(expr.ctx());\n  for (unsigned i = 0; i != names.size(); ++i) {\n    if (!remove.count(names[i])) {\n      qs.push_back(subs[i]);\n    }\n  }\n  return z3::forall(qs, crt);\n}\n\nstd::map<std::string, unsigned> occurences(const z3::expr &expr,\n                                           std::vector<std::string> &bounds) {\n  if (expr.is_const()) {\n    if (expr.decl().decl_kind() == Z3_OP_UNINTERPRETED) {\n      return {{expr.decl().name().str(), 1}};\n    }\n    return {};\n  } else if (expr.is_var()) {\n    auto idx = Z3_get_index_value(expr.ctx(), expr);\n    return {{bounds[bounds.size() - idx - 1], 1}};\n  }\n  std::map<std::string, unsigned> res;\n  if (expr.is_app()) {\n    auto num = expr.num_args();\n    for (unsigned i = 0; i != num; ++i) {\n      auto arg = expr.arg(i);\n      auto evd = occurences(arg, bounds);\n      if (res.empty()) {\n        res = std::move(evd);\n      } else {\n        for (const auto &pr : evd) {\n          auto rib = res.emplace(pr);\n          if (!rib.second) {\n            rib.first->second += pr.second;\n          }\n        }\n      }\n    }\n  } else if (expr.is_quantifier()) {\n    auto body = expr.body();\n    auto nrs = Z3_get_quantifier_num_bound(expr.ctx(), expr);\n    for (unsigned i = 0; i != nrs; ++i) {\n      z3::symbol nm(expr.ctx(),\n                    Z3_get_quantifier_bound_name(expr.ctx(), expr, i));\n      bounds.push_back(nm.str());\n    }\n    auto occs = occurences(body, bounds);\n    for (unsigned i = 0; i != nrs; ++i)\n      bounds.pop_back();\n    return std::move(occs);\n  }\n  return res;\n}\n\nstd::map<std::string, unsigned> cegis::occurences(const z3::expr &expr) {\n  std::vector<std::string> bounds;\n  return ::occurences(expr, bounds);\n}\n\nstd::map<std::string, z3::sort> typed_occurences(const z3::expr &expr) {\n  if (expr.is_const()) {\n    if (expr.decl().decl_kind() == Z3_OP_UNINTERPRETED) {\n      return {{expr.decl().name().str(), expr.get_sort()}};\n    }\n    return {};\n  }\n  std::map<std::string, z3::sort> res;\n  if (expr.is_app()) {\n    auto num = expr.num_args();\n    for (unsigned i = 0; i != num; ++i) {\n      auto arg = expr.arg(i);\n      auto evd = typed_occurences(arg);\n      if (res.empty()) {\n        res = std::move(evd);\n      } else {\n        for (const auto &pr : evd) {\n          auto rib = res.emplace(pr);\n          if (!rib.second) {\n            rib.first->second = pr.second;\n          }\n        }\n      }\n    }\n  }\n  return res;\n}\n\nstd::vector<z3::expr> cegis::atoms(const z3::expr &expr,\n                                   const std::string &what) {\n  if (expr.get_sort().is_bool() && expr.is_app()) {\n    auto decl = expr.decl();\n    if (decl.decl_kind() == Z3_OP_AND || decl.decl_kind() == Z3_OP_OR ||\n        decl.decl_kind() == Z3_OP_NOT || decl.decl_kind() == Z3_OP_IMPLIES) {\n      // nothing to do here , will be handled below\n    } else {\n      auto occs = occurences(expr);\n      if (occs.count(what)) {\n        return {expr};\n      }\n    }\n  }\n  std::vector<z3::expr> res;\n  if (expr.is_app()) {\n    auto num = expr.num_args();\n    for (unsigned i = 0; i != num; ++i) {\n      auto arg = expr.arg(i);\n      auto evd = atoms(arg, what);\n      if (res.empty()) {\n        res = std::move(evd);\n      } else {\n        res.insert(res.end(), evd.begin(), evd.end());\n      }\n    }\n  }\n  return res;\n}\n\nbool is_unconstrained(const z3::expr &src,\n                      const std::map<std::string, unsigned> &occs) {\n  if (src.is_app()) {\n    if (src.is_bool()) {\n      if (src.is_app() && src.decl().decl_kind() == Z3_OP_TRUE)\n        return false;\n      if (src.is_app() && src.decl().decl_kind() == Z3_OP_FALSE)\n        return false;\n      const auto &decl = src.decl();\n      if (decl.decl_kind() == Z3_OP_EQ) {\n        auto arg1 = src.arg(0);\n        auto arg2 = src.arg(1);\n        if (is_unconstrained(arg1, occs) || is_unconstrained(arg2, occs)) {\n          return true;\n        } else {\n          if (arg1.is_app() && arg1.decl().decl_kind() == Z3_OP_BAND &&\n              arg2.is_app() && arg2.decl().decl_kind() == Z3_OP_BAND) {\n            auto arg11 = arg1.arg(0);\n            auto arg12 = arg1.arg(1);\n            auto arg21 = arg2.arg(0);\n            auto arg22 = arg2.arg(1);\n            if (z3::eq(arg12, arg22) && (is_unconstrained(arg11, occs) ||\n                                         is_unconstrained(arg21, occs))) {\n              return true;\n            }\n          } else if (arg1.is_app() && arg1.decl().decl_kind() == Z3_OP_BNOT &&\n                     arg2.is_app() && arg2.decl().decl_kind() == Z3_OP_BNOT) {\n            // the bv rewriter does this for some yet undisclosed reasons\n            auto arg11 = arg1.arg(0);\n            auto arg21 = arg2.arg(0);\n            if (arg11.is_app() && arg11.decl().decl_kind() == Z3_OP_BOR &&\n                arg21.is_app() && arg21.decl().decl_kind() == Z3_OP_BOR) {\n              if (arg11.num_args() == 2 && 2 == arg21.num_args()) {\n                auto arg111 = arg11.arg(0);\n                auto arg112 = arg11.arg(1);\n                auto arg211 = arg21.arg(0);\n                auto arg212 = arg21.arg(1);\n                if (arg111.is_app() &&\n                    arg111.decl().decl_kind() == Z3_OP_BNOT &&\n                    arg112.is_app() &&\n                    arg112.decl().decl_kind() == Z3_OP_BNOT &&\n                    arg211.is_app() &&\n                    arg211.decl().decl_kind() == Z3_OP_BNOT &&\n                    arg212.is_app() &&\n                    arg212.decl().decl_kind() == Z3_OP_BNOT) {\n                  if (z3::eq(arg212.arg(0), arg112.arg(0)) &&\n                      (is_unconstrained(arg111, occs) ||\n                       is_unconstrained(arg211, occs))) {\n                    return true;\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n    if (src.is_app() && src.decl().decl_kind() == Z3_OP_BNUM)\n      return false;\n    if (src.is_const() && src.decl().decl_kind() == Z3_OP_UNINTERPRETED)\n      return occs.find(src.decl().name().str())->second == 1;\n    auto num = src.num_args();\n    bool uncnstrd = true;\n    for (unsigned i = 0; i != num; ++i) {\n      if (!is_unconstrained(src.arg(i), occs)) {\n        uncnstrd = false;\n        break;\n      }\n    }\n    if (uncnstrd)\n      return true;\n  }\n  return false;\n}\n\nbool any_occurence(const std::string &ct, const z3::expr &target) {\n  if (target.is_app()) {\n    if (target.decl().decl_kind() == Z3_OP_TRUE ||\n        target.decl().decl_kind() == Z3_OP_FALSE ||\n        target.decl().decl_kind() == Z3_OP_BNUM ||\n        target.decl().decl_kind() == Z3_OP_DT_CONSTRUCTOR)\n      return false;\n    if (target.is_const())\n      return target.decl().name().str() == ct;\n    for (unsigned i = 0; i != target.num_args(); ++i)\n      if (any_occurence(ct, target.arg(i)))\n        return true;\n  }\n  return false;\n}\n\nbool any_occurence(const z3::func_decl &ct, const z3::expr &target) {\n  return any_occurence(ct.name().str(), target);\n}\n\nz3::expr_vector generate_necessary_abstraction(\n    z3::solver *pslv, z3::solver *pdual_slv,\n    std::unordered_set<z3::expr> &ctrld,\n    const std::unordered_set<z3::expr> &may_control) {\n  z3::context *context = &pslv->ctx();\n  auto cr = pslv->check();\n  z3::expr_vector control_blocks(*context);\n  unsigned int nr_push = 0;\n  while (cr == z3::check_result::sat) {\n    auto model = pslv->get_model();\n    z3::expr_vector assumptions(*context);\n    for (const auto &e : ctrld) {\n      auto ev = model.eval(e);\n      switch (ev.bool_value()) {\n      case Z3_L_TRUE:\n        assumptions.push_back(e);\n        break;\n      case Z3_L_FALSE:\n        assumptions.push_back(!e);\n      default:\n        break;\n      }\n    }\n    std::stringstream ss;\n    for (unsigned i = 0; i != assumptions.size(); ++i) {\n      ss << assumptions[i] << ';';\n    }\n    LOG4(\"assumptions: \" << ss.str());\n    auto dual_res = pdual_slv->check(assumptions);\n    switch (dual_res) {\n    case z3::check_result::unsat: {\n      auto uc = pdual_slv->unsat_core();\n      std::stringstream ss;\n      for (unsigned i = 0; i != uc.size(); ++i) {\n        ss << uc[i] << ';';\n      }\n      LOG4(\"core: \" << ss.str());\n      control_blocks.push_back(!z3::mk_and(uc));\n      nr_push++;\n      pslv->push();\n      pslv->add(!z3::mk_and(uc));\n      break;\n    }\n    case z3::check_result::sat: {\n      LOG4(\"can't do with current abstraction, need to refine\");\n      bool changed = false;\n      pdual_slv->push();\n      for (unsigned i = 0; i != assumptions.size(); ++i) {\n        pdual_slv->add(assumptions[i]);\n      }\n      z3::expr_vector old_assumptions(pdual_slv->ctx());\n      for (unsigned i = 0; i != assumptions.size(); ++i) {\n        old_assumptions.push_back(assumptions[i]);\n      }\n      assumptions.resize(0);\n      for (auto &m : may_control) {\n        if (ctrld.find(m) == ctrld.end()) {\n          changed = true;\n          auto ev = model.eval(m);\n          switch (ev.bool_value()) {\n          case Z3_L_TRUE:\n            assumptions.push_back(m);\n            break;\n          case Z3_L_FALSE:\n            assumptions.push_back(!m);\n          default:\n            break;\n          }\n        }\n      }\n      z3::expr_vector core(pdual_slv->ctx());\n      if (!changed) {\n        LOG3(\"can't control this behavior\");\n      } else {\n        auto cr = pdual_slv->check(assumptions);\n        if (cr == z3::check_result::sat) {\n          core = assumptions;\n          LOG3(\"can't control this behavior\");\n        } else {\n          core = pdual_slv->unsat_core();\n          for (unsigned i = 0, e = core.size(); i != e; ++i) {\n            auto a = core[i];\n            if (a.decl().decl_kind() == Z3_OP_NOT) {\n              ctrld.emplace(a.arg(0));\n            } else {\n              ctrld.emplace(a);\n            }\n          }\n          for (unsigned i = 0, e = old_assumptions.size(); i != e; ++i) {\n            core.push_back(old_assumptions[i]);\n          }\n          control_blocks.push_back(!z3::mk_and(core));\n        }\n      }\n      pdual_slv->pop();\n      nr_push++;\n      pslv->push();\n      pslv->add(!z3::mk_and(core));\n      break;\n    }\n    default:\n      BUG(\"???\");\n    }\n    cr = pslv->check();\n  }\n  if (nr_push)\n    pslv->pop(nr_push);\n  return control_blocks;\n}\n\nz3::expr_vector generate_necessary_abstraction_2(\n    z3::expr &rho_a, z3::solver *pslv, z3::solver *pdual_slv,\n    std::unordered_set<z3::expr> &ctrld,\n    const std::unordered_set<z3::expr> &may_control) {\n  z3::context *context = &pslv->ctx();\n  z3::solver rho_solver(*context);\n  rho_solver.add(rho_a);\n  auto cr = pslv->check();\n  z3::expr_vector control_blocks(*context);\n  unsigned int nr_push = 0;\n  while (cr == z3::check_result::sat) {\n    auto model = pslv->get_model();\n    auto rhoeval = model.eval(rho_a).bool_value();\n    if (rhoeval == Z3_L_FALSE) {\n      auto ct_sz = model.num_consts();\n      z3::expr_vector kill_this(*context);\n      for (unsigned i = 0; i != ct_sz; ++i) {\n        auto cd = model.get_const_decl(i);\n        auto ci = model.get_const_interp(cd);\n        kill_this.push_back(cd() == ci);\n      }\n      BUG_CHECK(rho_solver.check(kill_this) == z3::check_result::unsat,\n                \"rho solver should be unsat in this model\");\n      nr_push++;\n      pslv->push();\n      pslv->add(!z3::mk_and(rho_solver.unsat_core()));\n    } else {\n      z3::expr_vector assumptions(*context);\n      for (const auto &e : ctrld) {\n        auto ev = model.eval(e);\n        switch (ev.bool_value()) {\n        case Z3_L_TRUE:\n          assumptions.push_back(e);\n          break;\n        case Z3_L_FALSE:\n          assumptions.push_back(!e);\n        default:\n          break;\n        }\n      }\n      std::stringstream ss;\n      for (unsigned i = 0; i != assumptions.size(); ++i) {\n        ss << assumptions[i] << ';';\n      }\n      LOG4(\"assumptions: \" << ss.str());\n      auto dual_res = pdual_slv->check(assumptions);\n      switch (dual_res) {\n      case z3::check_result::unsat: {\n        auto uc = pdual_slv->unsat_core();\n        std::stringstream ss;\n        for (unsigned i = 0; i != uc.size(); ++i) {\n          ss << uc[i] << ';';\n        }\n        LOG4(\"core: \" << ss.str());\n        control_blocks.push_back(!z3::mk_and(uc));\n        nr_push++;\n        pslv->push();\n        pslv->add(!z3::mk_and(uc));\n        break;\n      }\n      case z3::check_result::sat: {\n        LOG4(\"can't do with current abstraction, need to refine\");\n        bool changed = false;\n        pdual_slv->push();\n        for (unsigned i = 0; i != assumptions.size(); ++i) {\n          pdual_slv->add(assumptions[i]);\n        }\n        z3::expr_vector old_assumptions(pdual_slv->ctx());\n        for (unsigned i = 0; i != assumptions.size(); ++i) {\n          old_assumptions.push_back(assumptions[i]);\n        }\n        assumptions.resize(0);\n        for (auto &m : may_control) {\n          if (ctrld.find(m) == ctrld.end()) {\n            changed = true;\n            auto ev = model.eval(m);\n            switch (ev.bool_value()) {\n            case Z3_L_TRUE:\n              assumptions.push_back(m);\n              break;\n            case Z3_L_FALSE:\n              assumptions.push_back(!m);\n            default:\n              break;\n            }\n          }\n        }\n        z3::expr_vector core(pdual_slv->ctx());\n        if (!changed) {\n          LOG3(\"can't control this behavior\");\n        } else {\n          auto cr = pdual_slv->check(assumptions);\n          if (cr == z3::check_result::sat) {\n            core = assumptions;\n            LOG3(\"can't control this behavior\");\n          } else {\n            core = pdual_slv->unsat_core();\n            for (unsigned i = 0, e = core.size(); i != e; ++i) {\n              auto a = core[i];\n              if (a.decl().decl_kind() == Z3_OP_NOT) {\n                ctrld.emplace(a.arg(0));\n              } else {\n                ctrld.emplace(a);\n              }\n            }\n            for (unsigned i = 0, e = old_assumptions.size(); i != e; ++i) {\n              core.push_back(old_assumptions[i]);\n            }\n            control_blocks.push_back(!z3::mk_and(core));\n          }\n        }\n        pdual_slv->pop();\n        nr_push++;\n        pslv->push();\n        pslv->add(!z3::mk_and(core));\n      } break;\n      default:\n        BUG(\"???\");\n      }\n    }\n    cr = pslv->check();\n  }\n  if (nr_push)\n    pslv->pop(nr_push);\n  return control_blocks;\n}\n\nz3::expr_vector\ngenerate_necessary_abstraction(z3::solver *pslv, z3::solver *pdual_slv,\n                               std::unordered_set<z3::expr> &ctrld) {\n  std::unordered_set<z3::expr> may_control;\n  return generate_necessary_abstraction(pslv, pdual_slv, ctrld, may_control);\n}\n\nz3::expr merge_or(const z3::expr &e1, const z3::expr &e2) {\n  if (e1.is_app() && e1.decl().decl_kind() == Z3_OP_AND && e2.is_app() &&\n      e2.decl().decl_kind() == Z3_OP_AND) {\n    auto nargs1 = e1.num_args();\n    auto nargs2 = e2.num_args();\n    unsigned int idx = 0;\n    z3::expr_vector evec(e1.ctx());\n    while (idx < nargs1 && idx < nargs2) {\n      auto arg1 = e1.arg(idx);\n      auto arg2 = e2.arg(idx);\n      if (!z3::eq(arg1, arg2)) {\n        break;\n      }\n      evec.push_back(arg1);\n      ++idx;\n    }\n    z3::expr conj1 = e1.ctx().bool_val(true);\n    for (unsigned i = idx; i < nargs1; ++i)\n      conj1 = conj1 && e1.arg(i);\n    z3::expr conj2 = e2.ctx().bool_val(true);\n    for (unsigned i = idx; i < nargs2; ++i)\n      conj2 = conj2 && e2.arg(i);\n    evec.push_back(conj1 || conj2);\n    return z3::mk_and(evec);\n  }\n  return e1 || e2;\n}\n\ntemplate <typename T, typename Fun> void toFixPoint(T &obj, Fun f) {\n  bool change = true;\n  while (change) {\n    change = f(obj);\n  }\n};\n\nvoid packet_solver(z3::expr_vector &assertions, packet_theory &pt) {\n  z3::solver slv(assertions.ctx());\n  auto dumpAssertions = [](std::ostream &os, const z3::expr_vector &assertions,\n                           std::string n) {\n    os << n << \":===============\\n\";\n    for (unsigned i = 0, nr = assertions.size(); i != nr; ++i) {\n      os << assertions[i] << '\\n';\n    }\n    os << \"===============\";\n  };\n  auto assertionString = [&dumpAssertions](const z3::expr_vector &assertions,\n                                           std::string n) {\n    std::stringstream ss;\n    dumpAssertions(ss, assertions, n);\n    return ss.str();\n  };\n\n  auto replacefun = [&](z3::expr_vector &src, z3::expr_vector &dst,\n                        z3::expr_vector &cp) -> bool {\n    bool change = false;\n    for (unsigned i = 0, nr = assertions.size(); i != nr; ++i) {\n      auto e = assertions[i];\n      auto newe = e.substitute(src, dst).simplify();\n      if (!z3::eq(e, newe)) {\n        change = true;\n        LOG4(\"replace: \" << e << \" -> \" << newe);\n      }\n      cp.push_back(newe);\n    }\n    return change;\n  };\n\n  auto replaceEqualities = [&](z3::expr_vector &assertions) {\n    std::unordered_map<z3::expr, z3::expr> replace;\n    z3::expr_vector cp(assertions.ctx());\n    z3::expr_vector src(assertions.ctx());\n    z3::expr_vector dst(assertions.ctx());\n    auto nr = assertions.size();\n    for (unsigned i = 0; i != nr; ++i) {\n      auto e = assertions[i];\n      if (e.is_eq()) {\n        auto e1 = e.arg(0);\n        auto e2 = e.arg(1);\n        if (z3::eq(e1.get_sort(), pt.packetSort)) {\n          if (pt.isConst(e1) && pt.isConst(e2)) {\n            auto replace1 = replace.count(e1) != 0;\n            auto replace2 = replace.count(e2) != 0;\n            z3::expr what(assertions.ctx());\n            z3::expr with(assertions.ctx());\n            if (!replace1 || !replace2) {\n              if (!replace1) {\n                what = e1;\n                with = e2;\n              } else if (!replace2) {\n                what = e2;\n                with = e1;\n              }\n              auto I = replace.find(with);\n              src.push_back(what);\n              if (I != replace.end()) {\n                replace.emplace(what, I->second);\n                dst.push_back(I->second);\n              } else {\n                replace.emplace(what, with);\n                dst.push_back(with);\n              }\n            }\n          }\n        }\n      }\n    }\n    auto c = replacefun(src, dst, cp);\n    assertions = cp;\n    return c;\n  };\n  toFixPoint(assertions, replaceEqualities);\n  LOG4(assertionString(assertions, \"fold equalities\"));\n  // push equalities inwards\n  auto pushEqualities = [&](z3::expr_vector &assertions) {\n    bool change = false;\n    auto nr = assertions.size();\n    z3::expr_vector cp(assertions.ctx());\n    z3::expr_vector src(assertions.ctx());\n    z3::expr_vector dst(assertions.ctx());\n    std::unordered_map<z3::expr, z3::expr> replace;\n    for (unsigned i = 0; i != nr; ++i) {\n      auto e = assertions[i];\n      if (e.is_eq()) {\n        auto e1 = e.arg(0);\n        auto e2 = e.arg(1);\n        if (pt.isPacket(e1)) {\n          auto e1const = pt.isConst(e1);\n          auto e2const = pt.isConst(e2);\n          z3::expr rep(e1.ctx());\n          z3::expr with(e1.ctx());\n          if (e1const != e2const) {\n            if (e1const) {\n              rep = e1;\n              with = e2;\n            } else {\n              rep = e2;\n              with = e1;\n            }\n            replace.emplace(rep, with);\n          } else if (e1const) {\n            BUG(\"expecting (= p constructor), got %1%\", e);\n          }\n        }\n      }\n    }\n    for (auto &rep : replace) {\n      src.push_back(rep.first);\n      dst.push_back(rep.second);\n    }\n    for (unsigned i = 0; i != nr; ++i) {\n      auto e = assertions[i];\n      auto newe = e.substitute(src, dst).simplify();\n      if (!z3::eq(newe, e)) {\n        change = true;\n      }\n      cp.push_back(newe);\n    }\n    assertions = cp;\n    return change;\n  };\n  toFixPoint(assertions, pushEqualities);\n  LOG4(assertionString(assertions, \"push equalities\"));\n  auto eliminatePrependPrepend = [&](z3::expr_vector &assertions) {\n    z3::expr_vector src(assertions.ctx());\n    z3::expr_vector dst(assertions.ctx());\n    auto nr = assertions.size();\n    for (unsigned i = 0; i != nr; ++i) {\n      auto e = assertions[i];\n      recurse(e,\n              [&](const z3::expr &ex) {\n                if (pt.isPacket(ex) && pt.isPrepend(ex)) {\n                  auto e1 = ex.arg(1);\n                  if (pt.isPrepend(e1)) {\n                    auto p = ex.arg(0);\n                    auto c = e1.arg(0);\n                    auto d = e1.arg(1);\n                    src.push_back(ex);\n                    dst.push_back(pt.prepend(pt.prepend(p, c), d));\n                  }\n                }\n                return true;\n              },\n              [](const z3::expr &) {});\n    }\n    z3::expr_vector cp(assertions.ctx());\n    auto c = replacefun(src, dst, cp);\n    assertions = cp;\n    return c;\n  };\n  toFixPoint(assertions, eliminatePrependPrepend);\n  LOG4(assertionString(assertions, \"trans\"));\n  // post re-write checks:\n  auto emitHandling = [&](z3::expr_vector &assertions) {\n    bool change = false;\n    std::unordered_map<z3::expr, z3::expr> replace;\n    for (unsigned i = 0, e = assertions.size(); i != e; ++i) {\n      if (assertions[i].is_eq()) {\n        auto e1 = assertions[i].arg(0);\n        auto e2 = assertions[i].arg(1);\n        if (pt.isPacket(e1)) {\n          if (pt.isPrepend(e1) && pt.isPrepend(e2)) {\n            auto e12 = e1.arg(1);\n            auto e22 = e2.arg(1);\n            auto ex12 = pt.isEmit(e12.decl());\n            auto ex22 = pt.isEmit(e22.decl());\n            if (ex12 && ex22) {\n              if (*ex12 == *ex22) {\n                replace.emplace(assertions[i], e12.arg(0) == e22.arg(0) &&\n                                                   e1.arg(0) == e2.arg(0));\n                assertions.push_back(e12.arg(0) == e22.arg(0));\n                assertions.push_back(e1.arg(0) == e2.arg(0));\n              } else {\n                unsigned N = 0;\n                unsigned M = 0;\n                z3::expr x(assertions.ctx());\n                z3::expr y(assertions.ctx());\n                z3::expr p1(assertions.ctx());\n                z3::expr p2(assertions.ctx());\n                if (*ex12 < *ex22) {\n                  N = *ex22;\n                  M = *ex12;\n                  p1 = e2.arg(0);\n                  p2 = e1.arg(0);\n                  x = e22.arg(0);\n                  y = e12.arg(0);\n                } else {\n                  N = *ex12;\n                  M = *ex22;\n                  p1 = e1.arg(0);\n                  p2 = e2.arg(0);\n                  x = e12.arg(0);\n                  y = e22.arg(0);\n                }\n                auto p2_ = z3::to_expr(\n                    assertions.ctx(),\n                    Z3_mk_fresh_const(assertions.ctx(), \"pack\", pt.packetSort));\n                auto x2_ = z3::to_expr(\n                    assertions.ctx(),\n                    Z3_mk_fresh_const(assertions.ctx(), \"x\",\n                                      assertions.ctx().bv_sort(N - M)));\n                assertions.push_back(y == x.extract(N - 1, N - M));\n                assertions.push_back(p2 ==\n                                     pt.prepend(p2_, pt.emit(N - M)(x2_)));\n                assertions.push_back(x2_ == x.extract(N - M - 1, 0));\n                assertions.push_back(p2_ == p1);\n              }\n              change = true;\n              Z3_ast_vector_set(assertions.ctx(), assertions, i,\n                                assertions.ctx().bool_val(true));\n            }\n          }\n        }\n      }\n    }\n    return change;\n  };\n  toFixPoint(assertions, emitHandling);\n  LOG4(assertionString(assertions, \"emitHandling\"));\n}\n\nz3::expr cegis::generate_forall(const z3::expr &src,\n                                const std::map<std::string, unsigned> &occs) {\n  auto &ctx = src.ctx();\n  if (is_unconstrained(src, occs)) {\n    std::cerr << \"yup, unconstrained statement... \" << src << '\\n';\n    return ctx.bool_val(true);\n  } else {\n    std::cerr << \"not unconstrained statement... \" << src << '\\n';\n    return ctx.bool_val(false);\n  }\n  z3::expr_vector rep(ctx), with(ctx);\n  auto typed = typed_occurences(src);\n  for (auto &occ : occs) {\n    if (occ.second == 1) {\n      with.push_back(ctx.constant((occ.first + \"__\").c_str(),\n                                  typed.find(occ.first)->second));\n      rep.push_back(\n          ctx.constant(occ.first.c_str(), typed.find(occ.first)->second));\n    }\n  }\n  auto ebody = z3::expr(src).substitute(rep, with);\n  auto existvars = with;\n  rep = z3::expr_vector(ctx);\n  with = z3::expr_vector(ctx);\n  for (auto &occ : occs) {\n    if (occ.second > 1) {\n      with.push_back(ctx.constant((occ.first + \"__\").c_str(),\n                                  typed.find(occ.first)->second));\n      rep.push_back(\n          ctx.constant(occ.first.c_str(), typed.find(occ.first)->second));\n    }\n  }\n  auto body = ebody.substitute(rep, with);\n  with.push_back(ctx.constant(\"value____\", src.get_sort()));\n  return z3::forall(with, z3::exists(existvars, with.back() == body));\n}\n\nz3::expr cegis::simplify(z3::expr sigma) {\n  z3::context &ctx = sigma.ctx();\n  auto m = occurences(sigma);\n  std::map<std::string, unsigned> level_1_unconstrained;\n  std::copy_if(\n      m.begin(), m.end(),\n      std::inserter(level_1_unconstrained, level_1_unconstrained.end()),\n      [&](const std::pair<std::string, unsigned> &pr) {\n        // level of quantification == 2 && number of occurences == 1 =>\n        // need to just check if I can simply slash all formulas\n        return pr.first.find(\"pre_call\") == std::string::npos && pr.second == 1;\n      });\n  z3::expr_vector rep(ctx), with(ctx);\n  auto tmp_nr = 0;\n  for (const auto &p : level_1_unconstrained) {\n    auto exprs = atoms(sigma, p.first);\n    if (!exprs.empty()) {\n      for (const auto &e : exprs) {\n        auto eoccs = occurences(e);\n        try {\n          std::map<std::string, unsigned> all_occs;\n          for (const auto &p : m) {\n            if (p.first.find(\"pre_call\") != std::string::npos &&\n                eoccs.count(p.first)) {\n              all_occs.emplace(p.first, 2);\n            } else {\n              if (eoccs.count(p.first)) {\n                all_occs.emplace(p);\n              }\n            }\n          }\n          auto fall = is_unconstrained(e, all_occs);\n          if (fall) {\n            rep.push_back(e);\n            std::string tmp = \"tmp\";\n            tmp += std::to_string(tmp_nr++);\n            with.push_back(ctx.constant(tmp.c_str(), e.get_sort()));\n          }\n        } catch (z3::exception &e) {\n          std::cerr << e << '\\n';\n          throw e;\n        }\n      }\n    }\n  }\n  return sigma.substitute(rep, with).simplify();\n}\n\nnamespace analysis {\nvoid get_extra_controls(z3::solver &context,\n                        const std::unordered_set<z3::expr> &hints,\n                        const std::string &check_against,\n                        z3::expr_vector &evec) {\n  LOG4(\"starting inference loop for \" << check_against);\n  std::unordered_set<z3::expr> all_living_things, known;\n  auto nr_assertions = context.assertions().size();\n  auto assertions = context.assertions();\n  for (unsigned i = 0; i != nr_assertions; ++i) {\n    auto flat_context = assertions[i];\n    get_atoms(flat_context, all_living_things,\n              [&](const std::string &nm) { return check_against == nm; });\n  }\n  for (auto &hint : hints) {\n    get_atoms(hint, all_living_things,\n              [&](const std::string &nm) { return check_against == nm; });\n  }\n  for (auto &e : all_living_things) {\n    context.push();\n    context.add(!e);\n    if (context.check() == z3::check_result::unsat) {\n      // nothing\n      if (e.decl().decl_kind() != Z3_OP_EQ) {\n        known.emplace(e.ctx().bool_val(true));\n      } else {\n        auto e0 = e.arg(0);\n        auto e1 = e.arg(1);\n        if (e0.decl().decl_kind() == Z3_OP_UNINTERPRETED &&\n            check_against == e0.decl().name().str()) {\n          known.emplace(e1);\n        } else if (e1.decl().decl_kind() == Z3_OP_UNINTERPRETED &&\n                   check_against == e1.decl().name().str()) {\n          known.emplace(e0);\n        }\n      }\n    } else {\n      context.pop();\n      context.push();\n      context.add(e);\n      if (context.check() == z3::check_result::unsat) {\n        if (e.decl().decl_kind() == Z3_OP_EQ) {\n          auto e0 = e.arg(0);\n          auto e1 = e.arg(1);\n          if (e0.is_bool()) {\n            known.emplace(!e1);\n          }\n        } else {\n          known.emplace(e.ctx().bool_val(false));\n        }\n      }\n    }\n    context.pop();\n  }\n  for (const auto &exp : known) {\n    auto e = controls_expr(exp);\n    LOG4(\"inference computed \" << e);\n    evec.push_back(e);\n  }\n}\n\nbool get_extra_control_bt(\n    z3::solver &context, z3::solver &ctx2,\n    const std::set<std::string> &may_control,\n    const std::unordered_set<z3::expr> &hints, std::set<std::string> &processed,\n    std::map<std::string, z3::expr_vector> &known_inferences,\n    z3::expr_vector &do_add) {\n  z3::context &ctx = context.ctx();\n  bool is_changed = true;\n  unsigned int nr_pushes = 0;\n  while (ctx2.check() == z3::check_result::sat) {\n    is_changed = false;\n    auto model = ctx2.get_model();\n    auto model_size = model.num_consts();\n    std::unordered_set<std::string> uncontrolled;\n    z3::expr_vector block(ctx);\n    z3::expr_vector exprs(ctx);\n    for (unsigned i = 0; i != model_size; ++i) {\n      auto ct = model.get_const_decl(i);\n      if (ct.name().str().find(\"controls_\") != std::string::npos &&\n          ct.range().is_bool()) {\n        auto in = model.get_const_interp(ct);\n        switch (in.bool_value()) {\n        case Z3_L_FALSE:\n          block.push_back(!ct());\n          if (processed.find(ct.name().str().substr(9)) == processed.end()) {\n            uncontrolled.emplace(ct.name().str().substr(9));\n            auto I = known_inferences.find(ct.name().str().substr(9));\n            if (I != known_inferences.end()) {\n              for (unsigned idx = 0, e = I->second.size(); idx != e; ++idx) {\n                exprs.push_back(I->second[idx]);\n              }\n            } else {\n              z3::expr_vector new_vec(ctx);\n              get_extra_controls(context, hints, ct.name().str().substr(9),\n                                 new_vec);\n              known_inferences.emplace(ct.name().str().substr(9), new_vec)\n                  .first;\n              for (unsigned idx = 0, e = new_vec.size(); idx != e; ++idx) {\n                exprs.push_back(new_vec[idx]);\n              }\n            }\n          }\n          break;\n        case Z3_L_TRUE:\n          block.push_back(ct());\n        case Z3_L_UNDEF:\n          break;\n        }\n      }\n    }\n    unsigned sz = exprs.size();\n    // add consequences\n    for (unsigned i = 0; i != sz; ++i) {\n      auto e = exprs[i];\n      ctx2.push();\n      ctx2.add(e);\n      auto cr = ctx2.check();\n      ctx2.pop();\n      if (cr == z3::check_result::sat) {\n        is_changed = true;\n        ctx2.push();\n        ++nr_pushes;\n        ctx2.add(!e);\n      }\n    }\n    if (!is_changed) {\n      z3::expr_vector assumptions(ctx);\n      for (const auto &mc : may_control) {\n        assumptions.push_back(control_var(ctx, mc));\n      }\n      auto cr = ctx2.check(assumptions);\n      if (cr != z3::check_result::unsat) {\n        LOG4(\"oh, snap...\");\n        return false;\n      } else {\n        for (unsigned i = 0; i != model_size; ++i) {\n          auto ct = model.get_const_decl(i);\n          if (ct.name().str().find(\"controls_\") != std::string::npos &&\n              ct.range().is_bool() &&\n              may_control.count(ct.name().str().substr(9))) {\n            auto v = model.get_const_interp(ct).bool_value();\n            if (v == Z3_L_FALSE) {\n              do_add.push_back(ct());\n            }\n          }\n        }\n      }\n    } else {\n      auto old_size = do_add.size();\n      processed.insert(uncontrolled.begin(), uncontrolled.end());\n      if (!get_extra_control_bt(context, ctx2, may_control, hints, processed,\n                                known_inferences, do_add))\n        return false;\n      for (auto n : uncontrolled) {\n        processed.erase(n);\n      }\n      if (nr_pushes) {\n        ctx2.pop(nr_pushes);\n        nr_pushes = 0;\n      }\n      if (do_add.size() != old_size) {\n        for (auto i = old_size; i != do_add.size(); ++i)\n          ctx2.add(do_add[i]);\n      }\n    }\n    ctx2.add(!z3::mk_and(block));\n    block.resize(0);\n  }\n  return true;\n}\n\nz3::expr controls_expr(const z3::expr &need_to) {\n  std::set<std::string> must_control;\n  recurse(need_to,\n          [&](const z3::expr &e) {\n            if (e.is_app() && e.num_args() == 0 &&\n                e.decl().decl_kind() == Z3_OP_UNINTERPRETED) {\n              must_control.emplace(e.decl().name().str());\n              return false;\n            } else {\n              return true;\n            }\n          },\n          [](const z3::expr &) {});\n  z3::expr_vector evec(need_to.ctx());\n  for (const auto &s : must_control) {\n    evec.push_back(control_var(need_to.ctx(), s));\n  }\n  return z3::mk_and(evec);\n}\n\nz3::expr control_var(z3::context &ctx, const std::string &s) {\n  std::stringstream ss;\n  ss << \"controls_\" << s;\n  return ctx.bool_const(ss.str().c_str());\n}\n\nbool get_extra_control(z3::solver &context, z3::expr &must_control,\n                       const std::set<std::string> &controls,\n                       const std::set<std::string> &may_control,\n                       const std::unordered_set<z3::expr> &hints,\n                       z3::expr_vector &do_add) {\n  z3::solver ctx2(context.ctx());\n  for (const auto &ctrl : controls) {\n    ctx2.add(control_var(ctx2.ctx(), ctrl));\n  }\n  for (unsigned i = 0, e = do_add.size(); i != e; ++i) {\n    ctx2.add(do_add[i]);\n  }\n  auto old_sz = do_add.size();\n  LOG4(\"must control \" << must_control);\n  ctx2.add(!controls_expr(must_control));\n  std::set<std::string> visited;\n  std::map<std::string, z3::expr_vector> known_inferences;\n  auto rest = get_extra_control_bt(context, ctx2, may_control, hints, visited,\n                                   known_inferences, do_add);\n  LOG4(\"result \" << must_control);\n  for (unsigned i = old_sz; i != do_add.size(); ++i) {\n    LOG4(\"means \" << do_add[i]);\n  }\n  return rest;\n}\n\nstd::unordered_set<z3::expr> get_atoms(const z3::expr &flat_context) {\n  std::unordered_set<z3::expr> atoms;\n  get_atoms(flat_context, atoms, [](const std::string &) { return true; });\n  return atoms;\n}\n}\n\nunsigned packet_solver_::termid(const z3::expr &e) {\n  auto EMI = index.emplace(e, index.size());\n  if (EMI.second)\n    revindex.emplace_back(e);\n  return EMI.first->second;\n}\n\nvoid packet_solver_::add(z3::expr e) {\n  // auto nnfe = to_nnf(e);\n  // auto atoms = analysis::get_atoms(nnfe);\n  // for (auto &at : atoms) {\n  //   bool isth = false;\n  //   recurse(at, [&](const z3::expr &ex) {\n  //     if (pt.isPacket(ex)) {\n  //       auto before = revindex.size();\n  //       auto nr = termid(ex);\n  //       if (nr == before) {\n  //         // new term found\n  //         if (!pt.isConst(ex))\n  //           free_terms.emplace(nr);\n  //       }\n  //       isth = true;\n  //     }\n  //     return true;\n  //   });\n  //   if (isth) {\n  //     theory_atoms.emplace(at);\n  //     if (at.is_eq()) {\n  //       auto e0 = at.arg(0);\n  //       auto e1 = at.arg(1);\n  //       if (!pt.isConst(e0)) {\n  //         if (pt.isConst(e1)) {\n  //           std::swap(e0, e1);\n  //         } else {\n  //           BUG(\"can't handle arbitrary equations, only between var to term \"\n  //               \"%1%\",\n  //               at);\n  //         }\n  //       }\n  //       free_terms.erase(termid(e1));\n  //     }\n  //   }\n  // }\n  // for (auto tid : free_terms) {\n  //   // make up new variables for terms which have no variables\n  //   // implicitly attached. i.e. modelEmit_XXX\n  //   auto oldterm = revindex[tid];\n  //   if (pt.isZero(oldterm)) continue;\n  //   BUG_CHECK(pt.isEmit(oldterm.decl()), \"new terms must be emits, but %1% found\", oldterm);\n  //   auto tdumb = z3::to_expr(ctx(), Z3_mk_fresh_const(ctx(), \"pack\", pt.packetSort));\n  //   dumb_vars.emplace(tid, tdumb);\n  // }\n  // unsigned int crt_polarity = 0;\n  // recurse(nnfe, [&crt_polarity](const z3::expr &e) {\n  //   if (e.is_not()) crt_polarity++;\n  //   return true;\n  // }, [this, &crt_polarity](const z3::expr &e) {\n  //   if (e.is_not()) {\n  //     crt_polarity--;\n  //     return;\n  //   }\n  //   if (theory_atoms.count(e)) {\n  //     auto EMI = theory_atoms_polarity.emplace(e, 1 << (crt_polarity % 2));\n  //     if (!EMI.second) {\n  //       EMI.first->second |= (1 << (crt_polarity % 2));\n  //     }\n  //   }\n  // });\n  // for (const auto &pol : theory_atoms_polarity) {\n  //   if (pol.second != 1) {\n  //     BUG(\"bipolar atom %1% %2%\", pol.first, pol.second);\n  //   }\n  // }\n  //  s.add(e.substitute(src, dst));\n  s.add(e);\n}\n\nanalysis::node_t node_from_exp(const z3::expr &e) {\n  analysis::node_t n;\n  return n.clone(e.hash());\n}\n\nz3::check_result packet_solver_::check() {\n  START(solve);\n  auto cr = s.check();\n  END(solve);\n  START(refine);\n  while (cr == z3::check_result::sat) {\n    auto model = s.get_model();\n    for (const auto &that : theory_atoms) {\n      auto evd = model.eval(that);\n      auto bv = evd.bool_value();\n      if (bv != Z3_L_UNDEF) {\n        auto b = (bv == Z3_L_TRUE);\n        if (that.is_eq()) {\n          if (!b) {\n            std::ofstream dump(\"dump_wrong.smt\");\n            dump << s << '\\n';\n            dump << \"(check-sat)\";\n            dump.close();\n            BUG(\"can't handle neq in %1%\", that);\n          }\n        } else {\n          BUG(\"can't handle anything other than eq in %1%\", that);\n        }\n      }\n    }\n    cr = s.check();\n  }\n  END(refine);\n  auto dref = DURATION(refine);\n  auto d = DURATION(solve);\n\n  std::cerr << \"check result:\" << cr << \" #assertions:\" << s.assertions().size()\n            << \" time:\" << d << \"ms, refined in \" << dref << \"ms\\n\";\n  return cr;\n}\n\nz3::check_result packet_solver_::check(z3::expr_vector &evec) {\n  START(solve);\n  auto cr = s.check(evec);\n  END(solve);\n  auto d = DURATION(solve);\n  std::cerr << \"check assumptions result:\" << cr\n            << \" #assertions:\" << s.assertions().size()\n            << \" #assumptions:\" << evec.size() << \" time:\" << d << \"ms\\n\";\n  return cr;\n}\n\nz3::expr_vector packet_solver_::unsat_core() const {\n  START(unsatCore);\n  auto r = s.unsat_core();\n  END(unsatCore);\n  auto d = DURATION(unsatCore);\n  std::cerr << \"unsat core result:\" << r.size() << \" time:\" << d << \" ms\\n\";\n  return r;\n}\n\nz3::model packet_solver_::get_model() const {\n  START(getModel);\n  auto m = s.get_model();\n  END(getModel);\n  auto d = DURATION(getModel);\n  std::cerr << \"get model time:\" << d << \"ms\\n\";\n  return m;\n}\n\nvoid packet_solver_::pop(unsigned int n) { s.pop(n); }\n\nvoid packet_solver_::push() { s.push(); }\n\nstd::ostream &operator<<(std::ostream &os, const packet_solver_ &ps) {\n  return os << ps.s;\n}\n\nz3::expr remove_packets(const z3::expr &expr, packet_theory &pt) {\n  if (!expr.is_quantifier()) {\n    return expr;\n  }\n  auto &ctx = expr.ctx();\n  std::vector<std::pair<std::string, z3::sort>> sorted;\n\n  std::vector<unsigned> occurences;\n  auto numbounds = Z3_get_quantifier_num_bound(expr.ctx(), expr);\n  Z3_symbol syms[numbounds];\n  Z3_sort sorts[numbounds];\n  for (unsigned i = 0; i != numbounds; ++i) {\n    auto sm = Z3_get_quantifier_bound_name(ctx, expr, i);\n    auto str = Z3_get_symbol_string(ctx, sm);\n    auto srt = z3::to_sort(ctx, Z3_get_quantifier_bound_sort(ctx, expr, i));\n    sorted.emplace_back(str, srt);\n    syms[i] = sm;\n    sorts[i] = srt;\n  }\n  auto body = expr.body();\n  z3::expr_vector src(ctx);\n  z3::expr_vector dst(ctx);\n  recurse(body, [&](const z3::expr &e) {\n    if (e.is_and() || e.is_or() || e.is_implies() || e.is_ite() || e.is_not())\n      return true;\n    if (e.is_eq()) {\n      if (pt.isPacket(e.arg(0))) {\n        src.push_back(e);\n        dst.push_back(ctx.bool_val(true));\n      }\n      return false;\n    }\n    return true;\n  });\n  body = body.substitute(src, dst);\n  return z3::to_expr(ctx,\n                     Z3_mk_quantifier(ctx, Z3_is_quantifier_forall(ctx, expr),\n                                      Z3_get_quantifier_weight(ctx, expr), 0,\n                                      nullptr, numbounds, sorts, syms, body));\n}\n\nz3::expr chunkify(const z3::expr &expr) {\n  if (!expr.is_quantifier()) {\n    return expr;\n  }\n  auto &ctx = expr.ctx();\n  std::vector<std::pair<std::string, z3::sort>> sorted;\n  std::vector<unsigned> occurences;\n  auto numbounds = Z3_get_quantifier_num_bound(expr.ctx(), expr);\n  for (unsigned i = 0; i != numbounds; ++i) {\n    auto sm = Z3_get_quantifier_bound_name(ctx, expr, i);\n    auto str = Z3_get_symbol_string(ctx, sm);\n    auto srt = z3::to_sort(ctx, Z3_get_quantifier_bound_sort(ctx, expr, i));\n    sorted.emplace_back(str, srt);\n  }\n  occurences.resize(numbounds, 0);\n  auto body = expr.body();\n  recurse(body, [](const z3::expr &e) {\n    if (e.is_quantifier())\n      BUG(\"no nested quantifiers allowed %1%\", e);\n    return true;\n  });\n  recurse(body, [&](const z3::expr &e) {\n    if (e.is_var()) {\n      auto idx = Z3_get_index_value(e.ctx(), e);\n      occurences[numbounds - idx - 1]++;\n    }\n    return true;\n  });\n  auto body_ = body;\n  std::vector<unsigned> remove;\n  std::vector<z3::expr> add;\n  for (unsigned j = 0; j != numbounds; ++j) {\n    auto occs = occurences[j];\n    if (occs > 1 && sorted[j].second.is_bv()) {\n      std::unordered_set<z3::expr> terms;\n      LOG4(sorted[j].first << \" occurs #\" << occs);\n      recurse(body, [&](const z3::expr &e) {\n        if (e.is_app()) {\n          for (unsigned i = 0; i != e.num_args(); ++i) {\n            if (e.arg(i).is_var()) {\n              auto idx = numbounds - Z3_get_index_value(e.ctx(), e.arg(i)) - 1;\n              if (idx == j) {\n                LOG4(\"in term:\" << e);\n                terms.emplace(e);\n              }\n            }\n          }\n        }\n        return true;\n      });\n      std::set<unsigned> intervals({0, sorted[j].second.bv_size()});\n      std::map<std::pair<unsigned, unsigned>, z3::expr> extracts;\n      for (auto &term : terms) {\n        if (term.decl().decl_kind() == Z3_OP_EXTRACT) {\n          auto lo = Z3_get_decl_int_parameter(ctx, term.decl(), 1);\n          auto hi = Z3_get_decl_int_parameter(ctx, term.decl(), 0);\n          intervals.emplace(lo);\n          intervals.emplace(hi + 1);\n          extracts.emplace(std::make_pair(lo, hi + 1), term);\n        }\n      }\n      if (intervals.size() <= 2)\n        continue;\n      auto I = intervals.begin();\n      auto crt = *I;\n      ++I;\n      std::map<unsigned, std::pair<unsigned, z3::expr>> cover;\n      for (; I != intervals.end(); ++I) {\n        auto Zi = z3::to_expr(\n            ctx, Z3_mk_fresh_const(ctx, \"x\", ctx.bv_sort(*I - crt)));\n        cover.emplace(crt, std::make_pair(*I, Zi));\n        crt = *I;\n      }\n      if (cover.size() == 1)\n        continue;\n      z3::expr_vector src(ctx);\n      z3::expr_vector dst(ctx);\n      for (auto &ex : extracts) {\n        auto c = cover.find(ex.first.first)->second;\n        z3::expr_vector evec(ctx);\n        while (c.first <= ex.first.second) {\n          evec.push_back(c.second);\n          c = cover.find(c.first)->second;\n        }\n        z3::expr pleaserep(ctx);\n        if (evec.size() == 1)\n          pleaserep = evec.back();\n        else\n          pleaserep = z3::concat(evec);\n        src.push_back(ex.second);\n        dst.push_back(pleaserep);\n      }\n      body_ = body_.substitute(src, dst);\n      z3::expr_vector cov(ctx);\n      for (auto &x : cover) {\n        cov.push_back(x.second.second);\n        add.push_back(x.second.second);\n      }\n      z3::expr cove = z3::concat(cov);\n      recurse(body, [&](const z3::expr &e) {\n        if (e.is_var()) {\n          auto idx = numbounds - Z3_get_index_value(e.ctx(), e) - 1;\n          if (idx == j) {\n            src.push_back(e);\n            dst.push_back(cove);\n          }\n        }\n        return true;\n      });\n      body_ = body_.substitute(src, dst);\n      remove.push_back(j);\n    }\n  }\n\n  std::vector<z3::expr> freshes;\n  z3::expr_vector src(ctx);\n  z3::expr_vector dst(ctx);\n\n  for (auto &p : sorted) {\n    freshes.push_back(\n        z3::to_expr(ctx, Z3_mk_fresh_const(ctx, p.first.c_str(), p.second)));\n  }\n  recurse(body, [&](const z3::expr &ex) {\n    if (ex.is_var()) {\n      auto idx = numbounds - Z3_get_index_value(ex.ctx(), ex) - 1;\n      src.push_back(ex);\n      dst.push_back(freshes[idx]);\n    }\n    return true;\n  });\n  body_ = body_.substitute(src, dst);\n  z3::expr_vector newbounds(ctx);\n  for (unsigned i = 0; i != numbounds; ++i) {\n    if (!std::binary_search(remove.begin(), remove.end(), i)) {\n      newbounds.push_back(freshes[i]);\n    }\n  }\n  for (const auto &ex : add) {\n    newbounds.push_back(ex);\n  }\n  return z3::forall(newbounds, body_);\n}\n\npacket_solver_::packet_solver_(z3::solver &s, packet_theory &pt)\n    : s(s), pt(pt) {\n  s.set(\"macro_finder\", true);\n  termid(pt.zero());\n}\n\nvoid packet_solver_::makeAxioms() {\n  // saturate extracts\n  auto made = pt.make_axioms();\n  for (unsigned i = 0, e = made.size(); i != e; ++i) {\n    s.add(made[i]);\n  }\n  //  bool saturated = false;\n  //  while (!saturated) {\n  //    auto oldsize = pt.packetExtracts.size();\n  //    std::set<unsigned> alsoadd;\n  //    for (auto &pex : pt.packetExtracts) {\n  //      for (auto &pem : pt.packetEmits) {\n  //        auto N = pex.first;\n  //        auto M = pem.first;\n  //        while (N > M) {\n  //          (void)alsoadd.emplace(N - M);\n  //          N -= M;\n  //        }\n  //      }\n  //    }\n  //    for (auto als : alsoadd) {\n  //      pt.extract(als);\n  //    }\n  //    saturated = oldsize == pt.packetExtracts.size();\n  //  }\n  //  LOG4(\"#packetExtracts:\" << pt.packetExtracts.size());\n  //  {\n  //    auto observation = [](const z3::expr &e) { return e; };\n  //    auto pack = ctx().constant(\"p\", pt.packetSort);\n  //    auto c = ctx().constant(\"c\", pt.packetSort);\n  //    auto d = ctx().constant(\"d\", pt.packetSort);\n  //    auto ast = new Z3_ast[1];\n  //    ast[0] = observation(pt.prepend(pack, pt.zero()));\n  //    auto ppat = new Z3_pattern[1];\n  //    ppat[0] = Z3_mk_pattern(ctx(), 1, ast);\n  //    Z3_inc_ref(ctx(), Z3_pattern_to_ast(ctx(), ppat[0]));\n  //    BUG_CHECK(ctx().check_error() == Z3_OK, \"not ok \");\n  //\n  //    auto ppack = new Z3_app[1];\n  //    ppack[0] = pack;\n  //    //    s.add(z3::to_expr(\n  //    //        ctx(), Z3_mk_forall_const(ctx(), 0, 1, ppack, 1, ppat,\n  //    //                                  observation(pt.prepend(pack,\n  //    pt.zero()))\n  //    //                                  ==\n  //    //                                      observation(pack))));\n  //    LOG4(\"made forall\");\n  //    ast[0] = observation(pt.prepend(pt.zero(), pack));\n  //    ppat[0] = Z3_mk_pattern(ctx(), 1, ast);\n  //    Z3_inc_ref(ctx(), Z3_pattern_to_ast(ctx(), ppat[0]));\n  //    BUG_CHECK(ctx().check_error() == Z3_OK, \"not ok \");\n  //    //    s.add(z3::to_expr(\n  //    //        ctx(), Z3_mk_forall_const(ctx(), 0, 1, ppack, 1, ppat,\n  //    //                                  observation(pt.prepend(pt.zero(),\n  //    pack))\n  //    //                                  ==\n  //    //                                      observation(pack))));\n  //    LOG4(\"made forall 2\");\n  //    ast[0] = observation(pt.prepend(pack, pt.prepend(c, d)));\n  //    ppat[0] = Z3_mk_pattern(ctx(), 1, ast);\n  //    Z3_inc_ref(ctx(), Z3_pattern_to_ast(ctx(), ppat[0]));\n  //\n  //    auto apps = new Z3_app[3];\n  //    apps[0] = pack;\n  //    apps[1] = c;\n  //    apps[2] = d;\n  //    //    s.add(z3::to_expr(\n  //    //        ctx(), Z3_mk_forall_const(\n  //    //                   ctx(), 0, 3, apps, 1, ppat,\n  //    //                   observation(pt.prepend(pack, pt.prepend(c, d))) ==\n  //    //                       observation(pt.prepend(pt.prepend(pack, c),\n  //    d)))));\n  //\n  //    for (auto &pem : pt.packetEmits) {\n  //      auto X = ctx().bv_const(\"x\", pem.first);\n  //      s.add(z3::forall(X, pt.length(pt.emit(pem.first)(X)) ==\n  //                              ctx().num_val(pem.first, ctx().int_sort())));\n  //    }\n  //    s.add(z3::forall(pack, pt.length(pack) >= 0));\n  //    s.add(z3::forall(\n  //        pack, z3::implies(pt.length(pack) == ctx().num_val(0,\n  //        ctx().int_sort()),\n  //                          pack == pt.zero())));\n  //    s.add(pt.length(pt.zero()) == ctx().num_val(0, ctx().int_sort()));\n  //\n  //    //    for (auto &pem : pt.packetEmits) {\n  //    //      auto X = ctx().bv_const(\"x\", pem.first);\n  //    //      s.add(z3::forall(X, pt.emit(pem.first)(X) != pt.zero()));\n  //    //    }\n  //    //    {\n  //    //      auto c = ctx().constant(\"c\", pt.packetSort);\n  //    //      auto d = ctx().constant(\"d\", pt.packetSort);\n  //    //      z3::expr_vector expr_vector(ctx());\n  //    //      expr_vector.push_back(c);\n  //    //      expr_vector.push_back(d);\n  //    //      s.add(z3::forall(expr_vector,\n  //    //                       lenfun(pt.prepend(c, d)) == lenfun(c) +\n  //    //                       lenfun(d)));\n  //    //    }\n  //  }\n}\npacket_theory::packet_theory(z3::context &context)\n    : context(context), packetSort(context), bsort(context.bv_sort(1)),\n      zero(context), prepend(context), length(context), constructor(context),\n      projections(context) {\n  //  packetSort = ctx().seq_sort(bsort);\n  packetSort = ctx().uninterpreted_sort(\"packet\");\n  zero = ctx().function(\"modelZero\", 0, nullptr, packetSort);\n  length = ctx().function(\"length\", packetSort, ctx().int_sort());\n  //  const char *names[2] = {\"length\", \"arr\"};\n  //  z3::sort sorts[2] = {ctx().int_sort(), ctx().bv_sort(4096)};\n  //  constructor = ctx().tuple_sort(\"packet\", 2, names, sorts, projections);\n  //  packetSort = constructor.range();\n  //  z3::sort_vector emp(context);\n  //  zero = ctx().function(\"modelZero\", emp, packetSort);\n  prepend = ctx().function(\"modelPrepend\", packetSort, packetSort, packetSort);\n  //  length = projections[0];\n}\n\nnamespace z3 {\nz3::expr forall(z3::expr_vector &xs, const z3::expr &b,\n                z3::expr_vector &patterns) {\n  array<Z3_app> vars(xs);\n  array<Z3_pattern> pats(patterns.size());\n  for (unsigned i = 0; i != patterns.size(); ++i) {\n    array<Z3_ast> asts(1);\n    asts[0] = patterns[i];\n    pats[i] = Z3_mk_pattern(b.ctx(), 1, asts.ptr());\n    Z3_inc_ref(b.ctx(), Z3_pattern_to_ast(b.ctx(), pats[i]));\n  }\n  Z3_ast r = Z3_mk_forall_const(b.ctx(), 0, vars.size(), vars.ptr(),\n                                pats.size(), pats.ptr(), b);\n  b.check_error();\n  return expr(b.ctx(), r);\n}\nz3::expr forall(const z3::expr &x1, const z3::expr &b,\n                z3::expr_vector &patterns) {\n  z3::expr_vector evec(b.ctx());\n  evec.push_back(x1);\n  return forall(evec, b, patterns);\n}\n}\n\nz3::expr_vector packet_theory::make_axioms() {\n  z3::expr_vector axes(ctx());\n  //  for (auto &pem : packetEmits) {\n  //    auto x = ctx().bv_const(\"x\", pem.first);\n  //    auto p = ctx().constant(\"p\", packetSort);\n  //    z3::expr_vector bounds(ctx());\n  //    bounds.push_back(x);\n  //    bounds.push_back(p);\n  //    axes.push_back(\n  //        z3::forall(bounds,\n  //                   pem.second(p, x) ==\n  //                       z3::concat(p, reverse(pem.first)(x)).extract(4095,\n  //                       0)));\n  //  }\n  for (auto &padv : packetAdvances) {\n    auto p = ctx().constant(\"p\", packetSort);\n    axes.push_back(\n        z3::forall(p, padv.second(p) ==\n                          z3::zext(p.extract(4095, padv.first), padv.first)));\n  }\n\n  for (auto &pex : packetExtracts) {\n    auto p = ctx().constant(\"p\", packetSort);\n    axes.push_back(z3::forall(p, pex.second(p) == p.extract(pex.first - 1, 0)));\n  }\n  for (auto &r : rotates) {\n    auto x = ctx().bv_const(\"x\", r.first);\n\n    z3::expr_vector concd(ctx());\n    for (unsigned i = 0; i != r.first; ++i) {\n      concd.push_back(x.extract(i, i));\n    }\n    axes.push_back(z3::forall(x, r.second(x) == z3::concat(concd)));\n    //    z3::expr_vector patterns(ctx());\n    //    patterns.push_back(r.second(r.second(x)));\n    //    axes.push_back(z3::forall(x, r.second(r.second(x)) == x, patterns));\n  }\n  axes.push_back(zero() == ctx().bv_val(0, 4096));\n  return axes;\n}\n", "meta": {"hexsha": "708c922a7232eb2fcbd60ac2a854f846f09c1729", "size": 60186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "backends/analysis/cegis.cpp", "max_stars_repo_name": "shellqiqi/bf4", "max_stars_repo_head_hexsha": "6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-02T12:15:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T12:15:41.000Z", "max_issues_repo_path": "backends/analysis/cegis.cpp", "max_issues_repo_name": "shellqiqi/bf4", "max_issues_repo_head_hexsha": "6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f", "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": "backends/analysis/cegis.cpp", "max_forks_repo_name": "shellqiqi/bf4", "max_forks_repo_head_hexsha": "6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f", "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.1056105611, "max_line_length": 95, "alphanum_fraction": 0.5205695677, "num_tokens": 16903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19954527448153153}}
{"text": "/*\n   Copyright (c) 2018-2019 Nokia.\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 * This source code is part of the near-RT RIC (RAN Intelligent Controller)\n * platform project (RICP).\n*/\n\n#include \"config.h\"\n#include \"private/error.hpp\"\n#include \"private/abort.hpp\"\n#include \"private/asyncstorageimpl.hpp\"\n#include \"private/configurationreader.hpp\"\n#include \"private/asyncdummystorage.hpp\"\n#include \"private/engine.hpp\"\n#include \"private/logger.hpp\"\n#if HAVE_REDIS\n#include \"private/redis/asyncredisstorage.hpp\"\n#endif\n\n#include <boost/optional/optional_io.hpp>\n#include <boost/crc.hpp>\n\nusing namespace shareddatalayer;\nusing namespace shareddatalayer::redis;\n\nnamespace\n{\n        std::shared_ptr<AsyncDatabaseDiscovery> asyncDatabaseDiscoveryCreator(std::shared_ptr<Engine> engine,\n                                                                              const std::string& ns,\n                                                                              const DatabaseConfiguration& databaseConfiguration,\n                                                                              const boost::optional<std::size_t>& addressIndex,\n                                                                              std::shared_ptr<Logger> logger)\n        {\n            return AsyncDatabaseDiscovery::create(engine,\n                                                  ns,\n                                                  databaseConfiguration,\n                                                  addressIndex,\n                                                  logger);\n        }\n\n        std::uint32_t crc32(const std::string& s)\n        {\n           boost::crc_32_type result;\n           result.process_bytes(s.data(), s.size());\n           return result.checksum();\n        }\n\n        std::uint32_t getClusterHashIndex(const std::string& s, const size_t count)\n        {\n            return crc32(s)%count;\n        }\n}\n\nAsyncStorageImpl::AsyncStorageImpl(std::shared_ptr<Engine> engine,\n                                   const boost::optional<PublisherId>& pId,\n                                   std::shared_ptr<Logger> logger):\n    engine(engine),\n    databaseConfiguration(std::make_shared<DatabaseConfigurationImpl>()),\n    namespaceConfigurations(std::make_shared<NamespaceConfigurationsImpl>()),\n    publisherId(pId),\n    logger(logger),\n    asyncDatabaseDiscoveryCreator(::asyncDatabaseDiscoveryCreator)\n{\n    ConfigurationReader configurationReader(logger);\n    configurationReader.readDatabaseConfiguration(std::ref(*databaseConfiguration));\n    configurationReader.readNamespaceConfigurations(std::ref(*namespaceConfigurations));\n}\n\n// Meant for UT usage\nAsyncStorageImpl::AsyncStorageImpl(std::shared_ptr<Engine> engine,\n                                   const boost::optional<PublisherId>& pId,\n                                   std::shared_ptr<DatabaseConfiguration> databaseConfiguration,\n                                   std::shared_ptr<NamespaceConfigurations> namespaceConfigurations,\n                                   std::shared_ptr<Logger> logger,\n                                   const AsyncDatabaseDiscoveryCreator& asyncDatabaseDiscoveryCreator):\n    engine(engine),\n    databaseConfiguration(databaseConfiguration),\n    namespaceConfigurations(namespaceConfigurations),\n    publisherId(pId),\n    logger(logger),\n    asyncDatabaseDiscoveryCreator(asyncDatabaseDiscoveryCreator)\n{\n}\n\nvoid AsyncStorageImpl::setAsyncRedisStorageHandlersForCluster(const std::string& ns)\n{\n    static auto serverCount = databaseConfiguration->getServerAddresses().size();\n    for (std::size_t addrIndex = 0; addrIndex < serverCount; addrIndex++)\n    {\n        auto redisHandler = std::make_shared<AsyncRedisStorage>(engine,\n                                                                asyncDatabaseDiscoveryCreator(\n                                                                        engine,\n                                                                        ns,\n                                                                        std::ref(*databaseConfiguration),\n                                                                        addrIndex,\n                                                                        logger),\n                                                                publisherId,\n                                                                namespaceConfigurations,\n                                                                logger);\n        asyncStorages.push_back(redisHandler);\n    }\n}\n\nvoid AsyncStorageImpl::setAsyncRedisStorageHandlers(const std::string& ns)\n{\n    if (DatabaseConfiguration::DbType::SDL_STANDALONE_CLUSTER == databaseConfiguration->getDbType() ||\n        DatabaseConfiguration::DbType::SDL_SENTINEL_CLUSTER == databaseConfiguration->getDbType())\n    {\n            setAsyncRedisStorageHandlersForCluster(ns);\n            return;\n    }\n    auto redisHandler = std::make_shared<AsyncRedisStorage>(engine,\n                                                            asyncDatabaseDiscoveryCreator(\n                                                                    engine,\n                                                                    ns,\n                                                                    std::ref(*databaseConfiguration),\n                                                                    boost::none,\n                                                                    logger),\n                                                            publisherId,\n                                                            namespaceConfigurations,\n                                                            logger);\n    asyncStorages.push_back(redisHandler);\n}\n\nAsyncStorage& AsyncStorageImpl::getAsyncRedisStorageHandler(const std::string& ns)\n{\n    std::size_t handlerIndex{0};\n    if (DatabaseConfiguration::DbType::SDL_STANDALONE_CLUSTER == databaseConfiguration->getDbType() ||\n        DatabaseConfiguration::DbType::SDL_SENTINEL_CLUSTER == databaseConfiguration->getDbType())\n        handlerIndex = getClusterHashIndex(ns, databaseConfiguration->getServerAddresses().size());\n    return *asyncStorages.at(handlerIndex);\n}\n\nAsyncStorage& AsyncStorageImpl::getRedisHandler(const std::string& ns)\n{\n#if HAVE_REDIS\n    if (asyncStorages.empty())\n            setAsyncRedisStorageHandlers(ns);\n\n    return getAsyncRedisStorageHandler(ns);\n#else\n    logger->error() << \"Redis operations cannot be performed, Redis not enabled\";\n    SHAREDDATALAYER_ABORT(\"Invalid configuration.\");\n#endif\n}\n\nAsyncStorage& AsyncStorageImpl::getDummyHandler()\n{\n    static AsyncDummyStorage dummyHandler{engine};\n    return dummyHandler;\n}\n\nAsyncStorage& AsyncStorageImpl::getOperationHandler(const std::string& ns)\n{\n    if (namespaceConfigurations->isDbBackendUseEnabled(ns))\n        return getRedisHandler(ns);\n\n    return getDummyHandler();\n}\n\nint AsyncStorageImpl::fd() const\n{\n    return engine->fd();\n}\n\nvoid AsyncStorageImpl::handleEvents()\n{\n    engine->handleEvents();\n}\n\nvoid AsyncStorageImpl::waitReadyAsync(const Namespace& ns,\n                                      const ReadyAck& readyAck)\n{\n    getOperationHandler(ns).waitReadyAsync(ns, readyAck);\n}\n\nvoid AsyncStorageImpl::setAsync(const Namespace& ns,\n                                const DataMap& dataMap,\n                                const ModifyAck& modifyAck)\n{\n    getOperationHandler(ns).setAsync(ns, dataMap, modifyAck);\n}\n\nvoid AsyncStorageImpl::setIfAsync(const Namespace& ns,\n                                  const Key& key,\n                                  const Data& oldData,\n                                  const Data& newData,\n                                  const ModifyIfAck& modifyIfAck)\n{\n    getOperationHandler(ns).setIfAsync(ns, key, oldData, newData, modifyIfAck);\n}\n\nvoid AsyncStorageImpl::removeIfAsync(const Namespace& ns,\n                                     const Key& key,\n                                     const Data& data,\n                                     const ModifyIfAck& modifyIfAck)\n{\n    getOperationHandler(ns).removeIfAsync(ns, key, data, modifyIfAck);\n}\n\nvoid AsyncStorageImpl::setIfNotExistsAsync(const Namespace& ns,\n                                           const Key& key,\n                                           const Data& data,\n                                           const ModifyIfAck& modifyIfAck)\n{\n    getOperationHandler(ns).setIfNotExistsAsync(ns, key, data, modifyIfAck);\n}\n\nvoid AsyncStorageImpl::getAsync(const Namespace& ns,\n                                const Keys& keys,\n                                const GetAck& getAck)\n{\n    getOperationHandler(ns).getAsync(ns, keys, getAck);\n}\n\nvoid AsyncStorageImpl::removeAsync(const Namespace& ns,\n                                   const Keys& keys,\n                                   const ModifyAck& modifyAck)\n{\n    getOperationHandler(ns).removeAsync(ns, keys, modifyAck);\n}\n\nvoid AsyncStorageImpl::findKeysAsync(const Namespace& ns,\n                                     const std::string& keyPrefix,\n                                     const FindKeysAck& findKeysAck)\n{\n    getOperationHandler(ns).findKeysAsync(ns, keyPrefix, findKeysAck);\n}\n\nvoid AsyncStorageImpl::listKeys(const Namespace& ns,\n                                const std::string& pattern,\n                                const FindKeysAck& findKeysAck)\n{\n    getOperationHandler(ns).listKeys(ns, pattern, findKeysAck);\n}\n\nvoid AsyncStorageImpl::removeAllAsync(const Namespace& ns,\n                                       const ModifyAck& modifyAck)\n{\n    getOperationHandler(ns).removeAllAsync(ns, modifyAck);\n}\n", "meta": {"hexsha": "0d6d683ab5019acaf1fb105ce94fef31504e4738", "size": 10179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/asyncstorageimpl.cpp", "max_stars_repo_name": "o-ran-sc/ric-plt-sdl", "max_stars_repo_head_hexsha": "782df7475cbe2f823042f731f1cd877eb525b228", "max_stars_repo_licenses": ["Apache-2.0", "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/asyncstorageimpl.cpp", "max_issues_repo_name": "o-ran-sc/ric-plt-sdl", "max_issues_repo_head_hexsha": "782df7475cbe2f823042f731f1cd877eb525b228", "max_issues_repo_licenses": ["Apache-2.0", "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/asyncstorageimpl.cpp", "max_forks_repo_name": "o-ran-sc/ric-plt-sdl", "max_forks_repo_head_hexsha": "782df7475cbe2f823042f731f1cd877eb525b228", "max_forks_repo_licenses": ["Apache-2.0", "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": 39.76171875, "max_line_length": 129, "alphanum_fraction": 0.5540819334, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19954527448153153}}
{"text": "#include <ros/ros.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <stdio.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include <tms_msg_db/TmsdbGetData.h>\n#include <tms_msg_db/TmsdbStamped.h>\n#include <tms_msg_db/Tmsdb.h>\n\n#define PORT 65001\n#define MAX_COUNT 100\n#define DB_WRITE 10\n#define PEAK 700\n#define NOT_PEAK 500\n#define MIN_INTERVAL 300\n#define PI 3.14159265\n\nusing namespace std;\n\nclass tms_ss_whs1\n{\nprivate:\n\tros::NodeHandle nh;\n\tros::Publisher db_pub;\n\tint sock;\npublic:\n\tfloat temp=0;\n\tint rate=0,p_rate=0;\n\tint msec=0,p_msec=0;\n\tint hakei[MAX_COUNT] = {0};\n\tint count=0;\n\tdouble roll,pitch;\n\tint db_count=0;\n\tint last_peak_time=-1;\n\tvoid spin()\n\t{\n\t\twhile(ros::ok()){\n\t\t\tint rcvmsg[3];\n\t\t\tint n = recv(sock,rcvmsg,sizeof(rcvmsg),0);\n\t\t\tif(n<1){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tp_msec=msec;\n\t\t\tmsec = (rcvmsg[0]>>16)&0xffff;\n\t\t\thakei[count] = (rcvmsg[0]&0xffff);\n\t\t\ttemp = ((rcvmsg[1]>>16)&0xffff)*0.01;\n\t\t\tfloat acc_x = (((short)(rcvmsg[1]&0xffff)<<16)>>16)*0.01;\n\t\t\tfloat acc_y = (rcvmsg[2]>>16)*0.01;\n\t\t\tfloat acc_z = (((short)(rcvmsg[2]&0xffff)<<16)>>16)*0.01;\n\n\t\t\tif(msec==p_msec) msec+=8;\n\t\t\telse if(msec==(p_msec-8)) msec+=16;\n\t\t\telse if(msec==(p_msec-16)) msec+=24;\n\t\t\telse if(msec==(p_msec-24)) msec+=32;\n\n\t\t\tdouble G = sqrt(acc_x*acc_x+acc_y*acc_y+acc_z*acc_z);\n\t\t\tif(acc_y != 0){\n\t\t\t\troll = asin(-acc_x/G);\n\t\t\t\tpitch = atan(acc_z/acc_y);\n\t\t\t}\n\n\t\t\tROS_INFO(\"msec:%d hakei:%d rate:%d\",msec,hakei[count],rate);\n\n\t\t\tint interval = msec-last_peak_time;\n\t\t\tif(interval<-MIN_INTERVAL) interval+=60000;\n\n\t\t\tif(hakei[count]>PEAK&&interval>MIN_INTERVAL){\n\t\t\t\tif(last_peak_time==-1)\n\t\t\t\tlast_peak_time = msec;\n\t\t\t\telse{\n\t\t\t\t\tp_rate = rate;\n\t\t\t\t\trate = (int)(1000.0 / (double)interval * 60.0);\n\t\t\t\t\tif(rate<30) rate = 0;\n\t\t\t\t\telse if(rate>200) rate = p_rate;\n\t\t\t\t\tlast_peak_time = msec;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcount++;\n\t\t\tdb_count++;\n\n\t\t\tif(db_count>=DB_WRITE){\n\t\t\t\tdb_count=0;\n\t\t\t\tdb_write(1);\n\t\t\t}\n\n\t\t\tif(count>=MAX_COUNT){\n\t\t\t\tcount=0;\n\t\t\t}\n\t\t\tros::spinOnce();\n\t\t}\n\t\tdb_write(0);\n\t\tclose(sock);\n\t}\n\tvoid db_write(int state)\n\t{\n\t\tchar data[500];\n\t\tchar buf[8];\n\t\tconst char *c1 = \"{\";\n\t\tstrcpy(data,c1);\n\t\tstrcat(data,\"\\\"temp\\\":\");\n\t\tsprintf(buf,\"%.2f\",temp);\n\t\tstrcat(data,buf);\n\t\tstrcat(data,\", \\\"rate\\\":\");\n\t\tsprintf(buf,\"%d\",rate);\n\t\tstrcat(data,buf);\n\t\tstrcat(data,\", \\\"wave\\\":[\");\n\t\tfor(int i=0;i<MAX_COUNT;i++){\n\t\t\tint j = ((count+i)>=MAX_COUNT) ? (count+i-MAX_COUNT) : count+i;\n\t\t\tsprintf(buf,\"%d\",hakei[j]);\n\t\t\tstrcat(data,buf);\n\t\t\tif(i!=MAX_COUNT-1) strcat(data,\",\");\n\t\t}\n\t\tstrcat(data,\"]\");\n\t\tstrcat(data,\"}\");\n\n\t\tros::Time now = ros::Time::now() + ros::Duration(9*60*60); // GMT +9\n\t\ttms_msg_db::TmsdbStamped db_msg;\n\n\t\tstd::string frame_id(\"/world\");\n\t\tdb_msg.header.frame_id = frame_id;\n\t\tdb_msg.header.stamp = now;\n\t\tdb_msg.tmsdb.clear();\n\t\ttms_msg_db::Tmsdb tmpData;\n\n\t\ttmpData.time    = boost::posix_time::to_iso_extended_string(now.toBoost());\n\t\ttmpData.name    = \"whs1_mybeat\";\n\t\ttmpData.id      = 3021;\n\t\ttmpData.place   = 5001;\n\t\ttmpData.sensor  = 3021;\n\t\ttmpData.state   = state;\n\t\ttmpData.rr\t\t\t= roll;\n\t\ttmpData.rp \t\t\t= pitch;\n\t\ttmpData.ry\t\t\t= 0;\n\n\t\ttmpData.note=data;\n\t\tdb_msg.tmsdb.push_back(tmpData);\n\t\tdb_pub.publish(db_msg);\n\t}\n\ttms_ss_whs1()\n\t{\n\t\tdb_pub=nh.advertise<tms_msg_db::TmsdbStamped> (\"tms_db_data\", 1000);\n\t\tsock = socket(AF_INET,SOCK_DGRAM,0);\n\t\tstruct sockaddr_in s_address;\n\t\ts_address.sin_family=AF_INET;\n\t\ts_address.sin_addr.s_addr=INADDR_ANY;\n\t\ts_address.sin_port=htons(PORT);\n\t\tconst int on = 1;\n\t\tsetsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));\n    setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));\n\t\tbind(sock,(struct sockaddr *)&s_address,sizeof(s_address));\n\t\tint val=1;\n\t\tioctl(sock,FIONBIO,&val);\n\t\tROS_INFO(\"tms_ss_whs1 ready...\");\n\t}\n};\n\nint main(int argc, char **argv)\n{\n\tros::init(argc,argv,\"tms_ss_whs1\");\n\ttms_ss_whs1 whs1;\n\twhs1.spin();\n\treturn 0;\n}\n", "meta": {"hexsha": "7219367441b6bce44f11d5be65044bb061137881", "size": 3965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tms_ss/tms_ss_whs1/src/main.cpp", "max_stars_repo_name": "robotpilot/ros_tms", "max_stars_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T06:58:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T07:49:37.000Z", "max_issues_repo_path": "tms_ss/tms_ss_whs1/src/main.cpp", "max_issues_repo_name": "robotpilot/ros_tms", "max_issues_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 114.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T06:42:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T05:54:04.000Z", "max_forks_repo_path": "tms_ss/tms_ss_whs1/src/main.cpp", "max_forks_repo_name": "robotpilot/ros_tms", "max_forks_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-03-27T08:35:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T13:05:31.000Z", "avg_line_length": 23.0523255814, "max_line_length": 77, "alphanum_fraction": 0.6433795712, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1995452744815315}}
{"text": "#include <QApplication>\n#include \"Scene_polyhedron_selection_item.h\"\n#include <CGAL/Polygon_mesh_processing/compute_normal.h>\n#include <CGAL/Polygon_mesh_processing/repair.h>\n#include <CGAL/boost/graph/dijkstra_shortest_paths.h>\n#include <CGAL/boost/graph/helpers.h>\n#include <CGAL/property_map.h>\n#include <CGAL/Handle_hash_function.h>\n#include <CGAL/Unique_hash_map.h>\n\n#include <boost/unordered_map.hpp>\n#include <boost/unordered_set.hpp>\n#include <boost/range.hpp>\n\n#include <exception>\n#include <functional>\n#include <limits>\n#include <set>\n#include <utility>\n#include <vector>\n\n#include \"triangulate_primitive.h\"\n\n#ifdef USE_SURFACE_MESH\ntypedef Scene_surface_mesh_item Scene_face_graph_item;\n#else\ntypedef Scene_polyhedron_item Scene_face_graph_item;\n#endif\n\ntypedef Scene_face_graph_item::Face_graph Face_graph;\ntypedef boost::property_map<Face_graph,CGAL::vertex_point_t>::type VPmap;\ntypedef boost::property_map<Face_graph,CGAL::vertex_point_t>::const_type constVPmap;\n\ntypedef Scene_face_graph_item::Vertex_selection_map Vertex_selection_map;\n\ntypedef boost::graph_traits<Face_graph>::vertex_descriptor fg_vertex_descriptor;\ntypedef boost::graph_traits<Face_graph>::face_descriptor fg_face_descriptor;\ntypedef boost::graph_traits<Face_graph>::edge_descriptor fg_edge_descriptor;\ntypedef boost::graph_traits<Face_graph>::halfedge_descriptor fg_halfedge_descriptor;\n\nstruct Scene_polyhedron_selection_item_priv{\n\n  typedef Scene_facegraph_item_k_ring_selection::Active_handle Active_handle;\n  typedef boost::unordered_set<fg_vertex_descriptor, CGAL::Handle_hash_function>    Selection_set_vertex;\n  typedef boost::unordered_set<fg_face_descriptor, CGAL::Handle_hash_function>      Selection_set_facet;\n  typedef boost::unordered_set<fg_edge_descriptor, CGAL::Handle_hash_function>    Selection_set_edge;\n  struct vertex_on_path\n  {\n    fg_vertex_descriptor vertex;\n    bool is_constrained;\n  };\n\n  Scene_polyhedron_selection_item_priv(Scene_polyhedron_selection_item* parent):\n    item(parent)\n  {\n  }\n\n  void initializeBuffers(CGAL::Three::Viewer_interface *viewer) const;\n  void initialize_temp_buffers(CGAL::Three::Viewer_interface *viewer) const;\n  void initialize_HL_buffers(CGAL::Three::Viewer_interface *viewer) const;\n  void computeElements() const;\n  void compute_any_elements(std::vector<float> &p_facets, std::vector<float> &p_lines, std::vector<float> &p_points, std::vector<float> &p_normals,\n                            const Selection_set_vertex& p_sel_vertex, const Selection_set_facet &p_sel_facet, const Selection_set_edge &p_sel_edges) const;\n  void compute_temp_elements() const;\n  void compute_HL_elements() const;\n  void triangulate_facet(fg_face_descriptor, Kernel::Vector_3 normal,\n                         std::vector<float> &p_facets,std::vector<float> &p_normals) const;\n  void tempInstructions(QString s1, QString s2);\n\n  void computeAndDisplayPath();\n  void addVertexToPath(fg_vertex_descriptor, vertex_on_path &);\n\n  enum VAOs{\n    Facets = 0,\n    TempFacets,\n    Edges,\n    TempEdges,\n    Points,\n    TempPoints,\n    FixedPoints,\n    HLPoints,\n    HLEdges,\n    HLFacets,\n    NumberOfVaos\n  };\n  enum VBOs{\n    VertexFacets = 0,\n    NormalFacets,\n    VertexEdges,\n    VertexPoints,\n    VertexTempFacets,\n    NormalTempFacets,\n    VertexTempEdges,\n    VertexTempPoints,\n    VertexFixedPoints,\n    ColorFixedPoints,\n    VertexHLPoints,\n    VertexHLEdges,\n    VertexHLFacets,\n    NormalHLFacets,\n    NumberOfVbos\n  };\n\n  QList<vertex_on_path> path;\n  QList<fg_vertex_descriptor> constrained_vertices;\n  bool is_path_selecting;\n  bool poly_need_update;\n  mutable bool are_temp_buffers_filled;\n  //Specifies Selection/edition mode\n  bool first_selected;\n  int operation_mode;\n  QString m_temp_instructs;\n  bool is_treated;\n  fg_vertex_descriptor to_split_vh;\n  fg_face_descriptor to_split_fh;\n  fg_edge_descriptor to_join_ed;\n  Active_handle::Type original_sel_mode;\n  //Only needed for the triangulation\n  Face_graph* poly;\n  CGAL::Unique_hash_map<fg_face_descriptor, Kernel::Vector_3>  face_normals_map;\n  CGAL::Unique_hash_map<fg_vertex_descriptor, Kernel::Vector_3>  vertex_normals_map;\n  boost::associative_property_map< CGAL::Unique_hash_map<fg_face_descriptor, Kernel::Vector_3> >\n    nf_pmap;\n  boost::associative_property_map< CGAL::Unique_hash_map<fg_vertex_descriptor, Kernel::Vector_3> >\n    nv_pmap;\n  Scene_face_graph_item::ManipulatedFrame *manipulated_frame;\n  bool ready_to_move;\n\n  Vertex_selection_map vertex_selection_map()\n  {\n    return item->poly_item->vertex_selection_map();\n  }\n\n  Face_graph* polyhedron() { return poly; }\n  const Face_graph* polyhedron()const { return poly; }\n\n  bool canAddFace(fg_halfedge_descriptor hc, Scene_polyhedron_selection_item::fg_halfedge_descriptor t);\n  bool canAddFaceAndVertex(Scene_polyhedron_selection_item::fg_halfedge_descriptor hc, Scene_polyhedron_selection_item::fg_halfedge_descriptor t);\n\n  mutable std::vector<float> positions_facets;\n  mutable std::vector<float> normals;\n  mutable std::vector<float> positions_lines;\n  mutable std::vector<float> positions_points;\n  mutable std::size_t nb_facets;\n  mutable std::size_t nb_points;\n  mutable std::size_t nb_lines;\n\n  mutable std::vector<float> positions_temp_facets;\n  mutable std::vector<float> positions_fixed_points;\n  mutable std::vector<float> color_fixed_points;\n  mutable std::vector<float> temp_normals;\n  mutable std::vector<float> positions_temp_lines;\n  mutable std::vector<float> positions_temp_points;\n  mutable std::vector<float> positions_HL_facets;\n  mutable std::vector<float> HL_normals;\n  mutable std::vector<float> positions_HL_lines;\n  mutable std::vector<float> positions_HL_points;\n\n  mutable std::size_t nb_temp_facets;\n  mutable std::size_t nb_temp_points;\n  mutable std::size_t nb_temp_lines;\n  mutable std::size_t nb_fixed_points;\n\n  mutable QOpenGLShaderProgram *program;\n  mutable bool are_HL_buffers_filled;\n  Scene_polyhedron_selection_item* item;\n};\n\n\nvoid Scene_polyhedron_selection_item_priv::initializeBuffers(CGAL::Three::Viewer_interface *viewer)const\n{\n  //vao containing the data for the facets\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_WITH_LIGHT, viewer);\n    program->bind();\n\n    item->vaos[Facets]->bind();\n    item->buffers[VertexFacets].bind();\n    item->buffers[VertexFacets].allocate(positions_facets.data(),\n                        static_cast<int>(positions_facets.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexFacets].release();\n\n\n\n    item->buffers[NormalFacets].bind();\n    item->buffers[NormalFacets].allocate(normals.data(),\n                        static_cast<int>(normals.size()*sizeof(float)));\n    program->enableAttributeArray(\"normals\");\n    program->setAttributeBuffer(\"normals\",GL_FLOAT,0,3);\n    item->buffers[NormalFacets].release();\n\n    item->vaos[Facets]->release();\n    program->release();\n\n  }\n  //vao containing the data for the  lines\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_NO_SELECTION, viewer);\n    program->bind();\n    item->vaos[Edges]->bind();\n\n    item->buffers[VertexEdges].bind();\n    item->buffers[VertexEdges].allocate(positions_lines.data(),\n                        static_cast<int>(positions_lines.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexEdges].release();\n\n    program->release();\n\n    item->vaos[Edges]->release();\n\n  }\n  //vao containing the data for the points\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_NO_SELECTION, viewer);\n    program->bind();\n    item->vaos[Points]->bind();\n\n    item->buffers[VertexPoints].bind();\n    item->buffers[VertexPoints].allocate(positions_points.data(),\n                        static_cast<int>(positions_points.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexPoints].release();\n    program->release();\n\n    item->vaos[Points]->release();\n  }\n\n  nb_facets = positions_facets.size();\n  positions_facets.resize(0);\n  std::vector<float>(positions_facets).swap(positions_facets);\n\n  normals.resize(0);\n  std::vector<float>(normals).swap(normals);\n\n  nb_lines = positions_lines.size();\n  positions_lines.resize(0);\n  std::vector<float>(positions_lines).swap(positions_lines);\n\n  nb_points = positions_points.size();\n  positions_points.resize(0);\n  std::vector<float>(positions_points).swap(positions_points);\n  item->are_buffers_filled = true;\n}\n\nvoid Scene_polyhedron_selection_item_priv::initialize_temp_buffers(CGAL::Three::Viewer_interface *viewer)const\n{\n  //vao containing the data for the temp facets\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_WITH_LIGHT, viewer);\n    program->bind();\n\n    item->vaos[TempFacets]->bind();\n    item->buffers[VertexTempFacets].bind();\n    item->buffers[VertexTempFacets].allocate(positions_temp_facets.data(),\n                        static_cast<int>(positions_temp_facets.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexTempFacets].release();\n\n\n\n    item->buffers[NormalTempFacets].bind();\n    item->buffers[NormalTempFacets].allocate(temp_normals.data(),\n                        static_cast<int>(temp_normals.size()*sizeof(float)));\n    program->enableAttributeArray(\"normals\");\n    program->setAttributeBuffer(\"normals\",GL_FLOAT,0,3);\n    item->buffers[NormalTempFacets].release();\n\n    item->vaos[TempFacets]->release();\n    program->release();\n  }\n  //vao containing the data for the temp lines\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_NO_SELECTION, viewer);\n    program->bind();\n    item->vaos[TempEdges]->bind();\n\n    item->buffers[VertexTempEdges].bind();\n    item->buffers[VertexTempEdges].allocate(positions_temp_lines.data(),\n                        static_cast<int>(positions_temp_lines.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexTempEdges].release();\n\n    program->release();\n\n    item->vaos[TempEdges]->release();\n\n  }\n  //vaos containing the data for the temp points\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_NO_SELECTION, viewer);\n    program->bind();\n    item->vaos[TempPoints]->bind();\n\n    item->buffers[VertexTempPoints].bind();\n    item->buffers[VertexTempPoints].allocate(positions_temp_points.data(),\n                        static_cast<int>(positions_temp_points.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexTempPoints].release();\n    item->vaos[TempPoints]->release();\n\n    item->vaos[FixedPoints]->bind();\n\n    item->buffers[VertexFixedPoints].bind();\n    item->buffers[VertexFixedPoints].allocate(positions_fixed_points.data(),\n                        static_cast<int>(positions_fixed_points.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexFixedPoints].release();\n    item->buffers[ColorFixedPoints].bind();\n    item->buffers[ColorFixedPoints].allocate(color_fixed_points.data(),\n                        static_cast<int>(color_fixed_points.size()*sizeof(float)));\n    program->enableAttributeArray(\"colors\");\n    program->setAttributeBuffer(\"colors\",GL_FLOAT,0,3);\n    item->buffers[ColorFixedPoints].release();\n    item->vaos[FixedPoints]->release();\n\n    program->release();\n  }\n  nb_temp_facets = positions_temp_facets.size();\n  positions_temp_facets.resize(0);\n  std::vector<float>(positions_temp_facets).swap(positions_temp_facets);\n\n  temp_normals.resize(0);\n  std::vector<float>(temp_normals).swap(temp_normals);\n\n  nb_temp_lines = positions_temp_lines.size();\n  positions_temp_lines.resize(0);\n  std::vector<float>(positions_temp_lines).swap(positions_temp_lines);\n\n  nb_temp_points = positions_temp_points.size();\n  positions_temp_points.resize(0);\n  std::vector<float>(positions_temp_points).swap(positions_temp_points);\n\n  nb_fixed_points = positions_fixed_points.size();\n  positions_fixed_points.resize(0);\n  std::vector<float>(positions_fixed_points).swap(positions_fixed_points);\n  are_temp_buffers_filled = true;\n}\nvoid Scene_polyhedron_selection_item_priv::initialize_HL_buffers(CGAL::Three::Viewer_interface *viewer)const\n{\n  //vao containing the data for the temp facets\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_WITH_LIGHT, viewer);\n    program->bind();\n\n    item->vaos[HLFacets]->bind();\n    item->buffers[VertexHLFacets].bind();\n    item->buffers[VertexHLFacets].allocate(positions_HL_facets.data(),\n                        static_cast<int>(positions_HL_facets.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexHLFacets].release();\n\n\n    item->buffers[NormalHLFacets].bind();\n    item->buffers[NormalHLFacets].allocate(HL_normals.data(),\n                        static_cast<int>(HL_normals.size()*sizeof(float)));\n    program->enableAttributeArray(\"normals\");\n    program->setAttributeBuffer(\"normals\",GL_FLOAT,0,3);\n    item->buffers[NormalHLFacets].release();\n\n    item->vaos[HLFacets]->release();\n    program->release();\n\n  }\n  //vao containing the data for the temp lines\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_NO_SELECTION, viewer);\n    program->bind();\n    item->vaos[HLEdges]->bind();\n\n    item->buffers[VertexHLEdges].bind();\n    item->buffers[VertexHLEdges].allocate(positions_HL_lines.data(),\n                        static_cast<int>(positions_HL_lines.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexHLEdges].release();\n\n    program->release();\n\n    item->vaos[HLEdges]->release();\n\n  }\n  //vao containing the data for the temp points\n  {\n    program = item->getShaderProgram(Scene_polyhedron_selection_item::PROGRAM_NO_SELECTION, viewer);\n    program->bind();\n    item->vaos[HLPoints]->bind();\n\n    item->buffers[VertexHLPoints].bind();\n    item->buffers[VertexHLPoints].allocate(positions_HL_points.data(),\n                        static_cast<int>(positions_HL_points.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    item->buffers[VertexHLPoints].release();\n\n    program->release();\n\n    item->vaos[HLPoints]->release();\n  }\n  are_HL_buffers_filled = true;\n}\ntemplate<typename TypeWithXYZ, typename ContainerWithPushBack>\nvoid push_back_xyz(const TypeWithXYZ& t,\n                   ContainerWithPushBack& vector)\n{\n  vector.push_back(t.x());\n  vector.push_back(t.y());\n  vector.push_back(t.z());\n}\n\ntypedef Kernel Traits;\n\n//Make sure all the facets are triangles\ntypedef Traits::Point_3\t            Point_3;\ntypedef Traits::Point_3\t            Point;\ntypedef Traits::Vector_3\t    Vector;\n\nvoid\nScene_polyhedron_selection_item_priv::triangulate_facet(fg_face_descriptor fit,const Vector normal,\n                                                   std::vector<float> &p_facets,std::vector<float> &p_normals ) const\n{\n  typedef FacetTriangulator<Face_graph, Kernel, fg_vertex_descriptor> FT;\n  double diagonal;\n  if(item->poly_item->diagonalBbox() != std::numeric_limits<double>::infinity())\n    diagonal = item->poly_item->diagonalBbox();\n  else\n    diagonal = 0.0;\n  FT triangulation(fit,normal,poly,diagonal);\n    //iterates on the internal faces to add the vertices to the positions\n    //and the normals to the appropriate vectors\n    for(FT::CDT::Finite_faces_iterator\n        ffit = triangulation.cdt->finite_faces_begin(),\n        end = triangulation.cdt->finite_faces_end();\n        ffit != end; ++ffit)\n    {\n        if(ffit->info().is_external)\n            continue;\n\n        push_back_xyz(ffit->vertex(0)->point(), p_facets);\n        push_back_xyz(ffit->vertex(1)->point(), p_facets);\n        push_back_xyz(ffit->vertex(2)->point(), p_facets);\n\n        push_back_xyz(normal, p_normals);\n        push_back_xyz(normal, p_normals);\n        push_back_xyz(normal, p_normals);\n    }\n}\n\n\nvoid Scene_polyhedron_selection_item_priv::compute_any_elements(std::vector<float>& p_facets, std::vector<float>& p_lines, std::vector<float>& p_points, std::vector<float>& p_normals,\n                                                           const Selection_set_vertex& p_sel_vertices, const Selection_set_facet& p_sel_facets, const Selection_set_edge& p_sel_edges)const\n{\n    const qglviewer::Vec offset = static_cast<CGAL::Three::Viewer_interface*>(QGLViewer::QGLViewerPool().first())->offset();\n    p_facets.clear();\n    p_lines.clear();\n    p_points.clear();\n    p_normals.clear();\n    //The facet\n\n    if(!poly)\n      return;\n\n    VPmap vpm = get(CGAL::vertex_point,*poly);\n    for(Selection_set_facet::iterator\n        it = p_sel_facets.begin(),\n        end = p_sel_facets.end();\n        it != end; it++)\n    {\n      fg_face_descriptor f = (*it);\n      if (f == boost::graph_traits<Face_graph>::null_face())\n        continue;\n      Vector nf = get(nf_pmap, f);\n      if(is_triangle(halfedge(f,*poly),*poly))\n      {\n        p_normals.push_back(nf.x());\n        p_normals.push_back(nf.y());\n        p_normals.push_back(nf.z());\n\n        p_normals.push_back(nf.x());\n        p_normals.push_back(nf.y());\n        p_normals.push_back(nf.z());\n\n        p_normals.push_back(nf.x());\n        p_normals.push_back(nf.y());\n        p_normals.push_back(nf.z());\n\n\n        BOOST_FOREACH(fg_halfedge_descriptor he, halfedges_around_face(halfedge(f,*polyhedron()), *polyhedron()))\n        {\n          const Point& p = get(vpm,target(he,*poly));\n          p_facets.push_back(p.x()+offset.x);\n          p_facets.push_back(p.y()+offset.y);\n          p_facets.push_back(p.z()+offset.z);\n        }\n      }\n      else if (is_quad(halfedge(f,*poly), *poly))\n      {\n        Kernel::Vector_3 v_offset(offset.x, offset.y, offset.z);\n        Vector nf = get(nf_pmap, f);\n        {\n          //1st half-quad\n          const Point& p0 = get(vpm,target(halfedge(f,*poly),*poly));\n          const Point& p1 = get(vpm,target(next(halfedge(f,*poly),*poly),*poly));\n          const Point& p2 = get(vpm,target(next(next(halfedge(f,*poly),*poly),*poly),*poly));\n\n          push_back_xyz(p0+v_offset, p_facets);\n          push_back_xyz(p1+v_offset, p_facets);\n          push_back_xyz(p2+v_offset, p_facets);\n\n          push_back_xyz(nf, p_normals);\n          push_back_xyz(nf, p_normals);\n          push_back_xyz(nf, p_normals);\n        }\n        {\n          //2nd half-quad\n          const Point& p0 = get(vpm, target(next(next(halfedge(f,*poly),*poly),*poly),*poly));\n          const Point& p1 = get(vpm, target(prev(halfedge(f,*poly),*poly),*poly));\n          const Point& p2 = get(vpm, target(halfedge(f,*poly),*poly));\n\n          push_back_xyz(p0+v_offset, p_facets);\n          push_back_xyz(p1+v_offset, p_facets);\n          push_back_xyz(p2+v_offset, p_facets);\n\n          push_back_xyz(nf, p_normals);\n          push_back_xyz(nf, p_normals);\n          push_back_xyz(nf, p_normals);\n        }\n      }\n      else\n      {\n        triangulate_facet(f, nf, p_facets, p_normals);\n      }\n    }\n\n    //The Lines\n    {\n\n        for(Selection_set_edge::iterator it = p_sel_edges.begin(); it != p_sel_edges.end(); ++it) {\n          const Point& a = get(vpm, target(halfedge(*it,*poly),*poly));\n          const Point& b = get(vpm, target(opposite((halfedge(*it,*poly)),*poly),*poly));\n            p_lines.push_back(a.x()+offset.x);\n            p_lines.push_back(a.y()+offset.y);\n            p_lines.push_back(a.z()+offset.z);\n\n            p_lines.push_back(b.x()+offset.x);\n            p_lines.push_back(b.y()+offset.y);\n            p_lines.push_back(b.z()+offset.z);\n        }\n\n    }\n    //The points\n    {\n        for(Selection_set_vertex::iterator\n            it = p_sel_vertices.begin(),\n            end = p_sel_vertices.end();\n            it != end; ++it)\n        {\n          const Point& p = get(vpm, *it);\n            p_points.push_back(p.x()+offset.x);\n            p_points.push_back(p.y()+offset.y);\n            p_points.push_back(p.z()+offset.z);\n        }\n    }\n}\nvoid Scene_polyhedron_selection_item_priv::computeElements()const\n{\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  compute_any_elements(positions_facets, positions_lines, positions_points, normals,\n                       item->selected_vertices, item->selected_facets, item->selected_edges);\n  QApplication::restoreOverrideCursor();\n}\nvoid Scene_polyhedron_selection_item_priv::compute_temp_elements()const\n{\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  compute_any_elements(positions_temp_facets, positions_temp_lines, positions_temp_points, temp_normals,\n                       item->temp_selected_vertices, item->temp_selected_facets, item->temp_selected_edges);\n  //The fixed points\n  {\n    const qglviewer::Vec offset = static_cast<CGAL::Three::Viewer_interface*>(QGLViewer::QGLViewerPool().first())->offset();\n    color_fixed_points.clear();\n    positions_fixed_points.clear();\n    int i=0;\n\n    constVPmap vpm = get(CGAL::vertex_point,*polyhedron());\n\n    for(Scene_polyhedron_selection_item::Selection_set_vertex::iterator\n        it = item->fixed_vertices.begin(),\n        end = item->fixed_vertices.end();\n        it != end; ++it)\n    {\n      const Point& p = get(vpm,*it);\n      positions_fixed_points.push_back(p.x()+offset.x);\n      positions_fixed_points.push_back(p.y()+offset.y);\n      positions_fixed_points.push_back(p.z()+offset.z);\n\n      if(*it == constrained_vertices.first()|| *it == constrained_vertices.last())\n      {\n        color_fixed_points.push_back(0.0);\n        color_fixed_points.push_back(0.0);\n        color_fixed_points.push_back(1.0);\n      }\n      else\n      {\n        color_fixed_points.push_back(1.0);\n        color_fixed_points.push_back(0.0);\n        color_fixed_points.push_back(0.0);\n      }\n      i++;\n    }\n  }\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Scene_polyhedron_selection_item_priv::compute_HL_elements()const\n{\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  compute_any_elements(positions_HL_facets, positions_HL_lines, positions_HL_points, HL_normals,\n                       item->HL_selected_vertices, item->HL_selected_facets, item->HL_selected_edges);\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Scene_polyhedron_selection_item::draw(CGAL::Three::Viewer_interface* viewer) const\n{\n  GLfloat offset_factor;\n  GLfloat offset_units;\n  if(!d->are_HL_buffers_filled)\n  {\n    d->compute_HL_elements();\n    d->initialize_HL_buffers(viewer);\n  }\n\n  viewer->glGetFloatv(GL_POLYGON_OFFSET_FACTOR, &offset_factor);\n  viewer->glGetFloatv(GL_POLYGON_OFFSET_UNITS, &offset_units);\n  glPolygonOffset(0.5f, 0.9f);\n  vaos[Scene_polyhedron_selection_item_priv::HLFacets]->bind();\n  d->program = getShaderProgram(PROGRAM_WITH_LIGHT);\n  attribBuffers(viewer,PROGRAM_WITH_LIGHT);\n  d->program->bind();\n  d->program->setAttributeValue(\"colors\",QColor(255,153,51));\n  viewer->glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(d->positions_HL_facets.size())/3);\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::HLFacets]->release();\n\n  if(!d->are_temp_buffers_filled)\n  {\n    d->compute_temp_elements();\n    d->initialize_temp_buffers(viewer);\n  }\n  vaos[Scene_polyhedron_selection_item_priv::TempFacets]->bind();\n  d->program = getShaderProgram(PROGRAM_WITH_LIGHT);\n  attribBuffers(viewer,PROGRAM_WITH_LIGHT);\n  d->program->bind();\n  d->program->setAttributeValue(\"colors\",QColor(0,255,0));\n  viewer->glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(d->nb_temp_facets/3));\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::TempFacets]->release();\n  if(!are_buffers_filled)\n  {\n    d->computeElements();\n    d->initializeBuffers(viewer);\n  }\n\n  vaos[Scene_polyhedron_selection_item_priv::TempFacets]->bind();\n  d->program = getShaderProgram(PROGRAM_WITH_LIGHT);\n  attribBuffers(viewer,PROGRAM_WITH_LIGHT);\n\n  d->program->bind();\n  d->program->setAttributeValue(\"colors\",QColor(0,255,0));\n  viewer->glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(d->nb_temp_facets/3));\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::TempFacets]->release();\n\n  if(!are_buffers_filled)\n  {\n    d->computeElements();\n    d->initializeBuffers(viewer);\n  }\n  vaos[Scene_polyhedron_selection_item_priv::Facets]->bind();\n  d->program = getShaderProgram(PROGRAM_WITH_LIGHT);\n  attribBuffers(viewer,PROGRAM_WITH_LIGHT);\n  d->program->bind();\n  d->program->setAttributeValue(\"colors\",this->color());\n  viewer->glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(d->nb_facets/3));\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::Facets]->release();\n\n  glEnable(GL_POLYGON_OFFSET_LINE);\n  viewer->glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);\n  glPolygonOffset(0.0f, 1.5f);\n  drawEdges(viewer);\n  glDisable(GL_POLYGON_OFFSET_LINE);\n  viewer->glPolygonMode(GL_FRONT_AND_BACK,GL_POINT);\n  glPolygonOffset(offset_factor, offset_units);\n  drawPoints(viewer);\n  viewer->glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);\n}\n\nvoid Scene_polyhedron_selection_item::drawEdges(CGAL::Three::Viewer_interface* viewer) const\n{\n\n  viewer->glLineWidth(3.f);\n\n  if(!d->are_HL_buffers_filled)\n  {\n    d->compute_HL_elements();\n    d->initialize_HL_buffers(viewer);\n  }\n\n  vaos[Scene_polyhedron_selection_item_priv::HLEdges]->bind();\n  d->program = getShaderProgram(PROGRAM_NO_SELECTION);\n  attribBuffers(viewer,PROGRAM_NO_SELECTION);\n  d->program->bind();\n\n  d->program->setAttributeValue(\"colors\",QColor(255,153,51));\n  viewer->glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(d->positions_HL_lines.size()/3));\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::HLEdges]->release();\n\n  if(!d->are_temp_buffers_filled)\n  {\n    d->compute_temp_elements();\n    d->initialize_temp_buffers(viewer);\n  }\n\n  vaos[Scene_polyhedron_selection_item_priv::TempEdges]->bind();\n  d->program = getShaderProgram(PROGRAM_NO_SELECTION);\n  attribBuffers(viewer,PROGRAM_NO_SELECTION);\n  d->program->bind();\n\n  d->program->setAttributeValue(\"colors\",QColor(0,200,0));\n  viewer->glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(d->nb_temp_lines/3));\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::TempEdges]->release();\n  viewer->glLineWidth(3.0f);\n  if(!are_buffers_filled)\n  {\n    d->computeElements();\n    d->initializeBuffers(viewer);\n  }\n\n  vaos[Scene_polyhedron_selection_item_priv::Edges]->bind();\n  d->program = getShaderProgram(PROGRAM_NO_SELECTION);\n  attribBuffers(viewer,PROGRAM_NO_SELECTION);\n  d->program->bind();\n\n  d->program->setAttributeValue(\"colors\",QColor(255,\n                                                color().blue()/2,\n                                                color().green()/2));\n  viewer->glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(d->nb_lines/3));\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::Edges]->release();\n\n\n  viewer->glLineWidth(1.f);\n}\n\nvoid Scene_polyhedron_selection_item::drawPoints(CGAL::Three::Viewer_interface* viewer) const\n{\n  viewer->glPointSize(5.5f);\n\n  if(!d->are_HL_buffers_filled)\n  {\n    d->compute_HL_elements();\n    d->initialize_HL_buffers(viewer);\n  }\n  vaos[Scene_polyhedron_selection_item_priv::HLPoints]->bind();\n  d->program = getShaderProgram(PROGRAM_NO_SELECTION);\n  attribBuffers(viewer,PROGRAM_NO_SELECTION);\n  d->program->bind();\n  d->program->setAttributeValue(\"colors\",QColor(255,153,51));\n  viewer->glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(d->positions_HL_points.size()/3));\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::HLPoints]->release();\n\n  if(!d->are_temp_buffers_filled)\n  {\n    d->compute_temp_elements();\n    d->initialize_temp_buffers(viewer);\n  }\n  viewer->glPointSize(5.5f);\n\n  vaos[Scene_polyhedron_selection_item_priv::TempPoints]->bind();\n  d->program = getShaderProgram(PROGRAM_NO_SELECTION);\n  attribBuffers(viewer,PROGRAM_NO_SELECTION);\n  d->program->bind();\n  d->program->setAttributeValue(\"colors\",QColor(0,50,0));\n  viewer->glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(d->nb_temp_points/3));\n  vaos[Scene_polyhedron_selection_item_priv::TempPoints]->release();\n  vaos[Scene_polyhedron_selection_item_priv::FixedPoints]->bind();\n  viewer->glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(d->nb_fixed_points/3));\n  d->program->release();\n  vaos[Scene_polyhedron_selection_item_priv::FixedPoints]->release();\n  if(!are_buffers_filled)\n  {\n    d->computeElements();\n    d->initializeBuffers(viewer);\n  }\n  vaos[Scene_polyhedron_selection_item_priv::Points]->bind();\n  d->program = getShaderProgram(PROGRAM_NO_SELECTION);\n  attribBuffers(viewer,PROGRAM_NO_SELECTION);\n  d->program->bind();\n  d->program->setAttributeValue(\"colors\",QColor(255,\n                                                (std::min)(color().blue()+color().red(), 255),\n                                                (std::min)(color().green()+color().red(), 255)));\n  viewer->glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(d->nb_points/3));\n  d->program->release();\n  vaos[Points]->release();\n\n  viewer->glPointSize(1.f);\n}\n\n\nvoid Scene_polyhedron_selection_item::inverse_selection()\n{\n  switch(k_ring_selector.active_handle_type)\n  {\n  case Active_handle::VERTEX:\n  {\n    Selection_set_vertex temp_select = selected_vertices;\n    select_all();\n    Q_FOREACH(fg_vertex_descriptor vh, temp_select)\n    {\n      selected_vertices.erase(vh);\n    }\n    break;\n  }\n  case Active_handle::EDGE:\n  {\n    Selection_set_edge temp_select = selected_edges;\n    select_all();\n    Q_FOREACH(fg_edge_descriptor ed , temp_select)\n      selected_edges.erase(ed);\n    break;\n  }\n  default:\n  {\n    Selection_set_facet temp_select = selected_facets;\n    select_all();\n    Q_FOREACH(fg_face_descriptor fh, temp_select)\n      selected_facets.erase(fh);\n    break;\n  }\n  }\n  invalidateOpenGLBuffers();\n  QGLViewer* v = *QGLViewer::QGLViewerPool().begin();\n  v->update();\n}\n\nvoid Scene_polyhedron_selection_item::set_operation_mode(int mode)\n{\n  k_ring_selector.setEditMode(true);\n  Q_EMIT updateInstructions(QString(\"SHIFT + left click to apply operation.\"));\n  switch(mode)\n  {\n  case -2:\n    set_active_handle_type(d->original_sel_mode);\n    Q_EMIT updateInstructions(\"Select two vertices to create the path between them. (1/2)\");\n    break;\n  case -1:\n    //restore original selection_type\n    set_active_handle_type(d->original_sel_mode);\n    clearHL();\n    k_ring_selector.setEditMode(false);\n    break;\n    //Join vertex\n  case 0:\n    Q_EMIT updateInstructions(\"Select the edge with extremities you want to join.\");\n    //set the selection type to Edge\n    set_active_handle_type(static_cast<Active_handle::Type>(2));\n    break;\n    //Split vertex\n  case 1:\n    Q_EMIT updateInstructions(\"Select the vertex you want to split. (1/3)\");\n    //set the selection type to Vertex\n    set_active_handle_type(static_cast<Active_handle::Type>(0));\n    break;\n    //Split edge\n  case 2:\n    Q_EMIT updateInstructions(\"Select the edge you want to split.\");\n    //set the selection type to Edge\n    set_active_handle_type(static_cast<Active_handle::Type>(2));\n    break;\n    //Join face\n  case 3:\n    Q_EMIT updateInstructions(\"Select the edge separating the faces you want to join.\");\n    //set the selection type to Edge\n    set_active_handle_type(static_cast<Active_handle::Type>(2));\n    break;\n    //Split face\n  case 4:\n    Q_EMIT updateInstructions(\"Select the facet you want to split (degree >= 4). (1/3)\");\n    //set the selection type to Facet\n    set_active_handle_type(static_cast<Active_handle::Type>(1));\n    break;\n    //Collapse edge\n  case 5:\n    Q_EMIT updateInstructions(\"Select the edge you want to collapse.\");\n    //set the selection type to Edge\n    set_active_handle_type(static_cast<Active_handle::Type>(2));\n    break;\n    //Flip edge\n  case 6:\n    Q_EMIT updateInstructions(\"Select the edge you want to flip.\");\n    //set the selection type to Edge\n    set_active_handle_type(static_cast<Active_handle::Type>(2));\n    break;\n    //Add center vertex\n  case 7:\n    Q_EMIT updateInstructions(\"Select a facet.\");\n    //set the selection type to Facet\n    set_active_handle_type(static_cast<Active_handle::Type>(1));\n    break;\n    //Remove center vertex\n  case 8:\n    Q_EMIT updateInstructions(\"Select the vertex you want to remove.\");\n    //set the selection type to vertex\n    set_active_handle_type(static_cast<Active_handle::Type>(0));\n    break;\n    //Add vertex and face to border\n  case 9:\n    Q_EMIT updateInstructions(\"Select a border edge. (1/2)\");\n    //set the selection type to Edge\n    set_active_handle_type(static_cast<Active_handle::Type>(2));\n    break;\n    //Add face to border\n  case 10:\n    Q_EMIT updateInstructions(\"Select a border edge. (1/2)\");\n    //set the selection type to Edge\n    set_active_handle_type(static_cast<Active_handle::Type>(2));\n    break;\n  case 11:\n    Q_EMIT updateInstructions(\"Select a vertex. (1/2)\");\n    //set the selection type to Edge\n    set_active_handle_type(static_cast<Active_handle::Type>(0));\n    break;\n  default:\n    break;\n  }\n  d->operation_mode = mode;\n}\ntemplate<typename HandleRange>\nbool Scene_polyhedron_selection_item::treat_classic_selection(const HandleRange& selection)\n{\n  typedef typename HandleRange::value_type HandleType;\n  Selection_traits<HandleType, Scene_polyhedron_selection_item> tr(this);\n  bool any_change = false;\n  if(is_insert) {\n    BOOST_FOREACH(HandleType h, selection)\n        any_change |= tr.container().insert(h).second;\n  }\n  else{\n    BOOST_FOREACH(HandleType h, selection)\n        any_change |= (tr.container().erase(h)!=0);\n  }\n  if(any_change) { invalidateOpenGLBuffers(); Q_EMIT itemChanged(); }\n  return any_change;\n}\n\nbool Scene_polyhedron_selection_item::treat_selection(const std::set<fg_vertex_descriptor>& selection)\n{\n  VPmap vpm = get(CGAL::vertex_point, *polyhedron());\n  if(!d->is_treated)\n  {\n    fg_vertex_descriptor vh = *selection.begin();\n    Selection_traits<fg_vertex_descriptor, Scene_polyhedron_selection_item> tr(this);\n    switch(d->operation_mode)\n    {\n    //classic selection\n    case -2:\n    case -1:\n    {\n      if(!d->is_path_selecting)\n      {\n        return treat_classic_selection(selection);\n      }\n      else\n      {\n        if(is_insert)\n        {\n          selectPath(*selection.begin());\n          invalidateOpenGLBuffers();\n          Q_EMIT itemChanged();\n        }\n      }\n      return false;\n      break;\n    }\n      //Split vertex\n    case 1:\n    {\n      //save VH\n      d->to_split_vh = vh;\n      temp_selected_vertices.insert(d->to_split_vh);\n      //set to select facet\n      set_active_handle_type(static_cast<Active_handle::Type>(1));\n      invalidateOpenGLBuffers();\n      Q_EMIT updateInstructions(\"Select first facet. (2/3)\");\n      break;\n    }\n      //Split face\n    case 4:\n    {\n      static fg_vertex_descriptor s;\n      static fg_halfedge_descriptor h1,h2;\n      static bool found_h1(false), found_h2(false);\n      if(!d->first_selected)\n      {\n          //Is the vertex on the face ?\n        BOOST_FOREACH(fg_halfedge_descriptor hafc, halfedges_around_face(halfedge(d->to_split_fh,*polyhedron()), *polyhedron()))\n          {\n            if(target(hafc,*polyhedron())==vh)\n            {\n              h1 = hafc;\n              s = vh;\n              found_h1 = true;\n                break;\n            }\n          }\n          if(!found_h1)\n          {\n            d->tempInstructions(\"Vertex not selected : The vertex is not on the face.\",\n                             \"Select the first vertex. (2/3)\");\n          }\n          else\n          {\n            d->first_selected = true;\n            temp_selected_vertices.insert(s);\n            invalidateOpenGLBuffers();\n            Q_EMIT updateInstructions(\"Select the second vertex (3/3)\");\n          }\n      }\n      else\n      {\n        bool is_same(false), are_next(false);\n        for(int i=0; i<1; i++) //seems useless but allow the use of break.\n        {\n          //Is the vertex on the face ?\n          BOOST_FOREACH(fg_halfedge_descriptor hafc, halfedges_around_face(halfedge(d->to_split_fh,*polyhedron()), *polyhedron()))\n            if(target(hafc,*polyhedron())==vh)\n          {\n            h2 = hafc;\n            found_h2 = true;\n            break;\n          }\n          if(!found_h2)\n          {\n            break;\n          }\n          //Are they different ?\n          if(h1 == h2)\n          {\n            is_same = true;\n            break;\n          }\n          is_same = false;\n          //Are they directly following each other?\n          if(next(h1, *polyhedron()) == h2 ||\n             next(h2, *polyhedron()) == h1)\n          {\n            are_next = true;\n            break;\n          }\n          are_next = false;\n        }\n        if(!found_h2)\n          d->tempInstructions(\"Vertex not selected : The vertex is not on the face.\",\n                           \"Select the second vertex (3/3).\");\n        else if(is_same)\n          d->tempInstructions(\"Vertex not selected : The vertices must be different.\",\n                           \"Select the second vertex (3/3).\");\n        else if(are_next)\n          d->tempInstructions(\"Vertex not selected : The vertices must not directly follow each other.\",\n                           \"Select the second vertex (3/3).\");\n        else\n        {\n          CGAL::Euler::split_face(h1,h2, *polyhedron());\n          d->first_selected = false;\n          temp_selected_vertices.clear();\n          temp_selected_facets.clear();\n          compute_normal_maps();\n          invalidateOpenGLBuffers();\n          //reset selection type to Facet\n          set_active_handle_type(static_cast<Active_handle::Type>(1));\n          d->tempInstructions(\"Face split.\",\n                           \"Select a facet (1/3).\");\n          polyhedron_item()->invalidateOpenGLBuffers();\n        }\n      }\n      break;\n    }\n      //Remove center vertex\n    case 8:\n    {\n      bool has_hole = false;\n      BOOST_FOREACH(fg_halfedge_descriptor hc, halfedges_around_target(vh,*polyhedron()))\n      {\n        if(is_border(hc,*polyhedron()))\n        {\n          has_hole = true;\n          break;\n        }\n      }\n      if(!has_hole)\n      {\n        CGAL::Euler::remove_center_vertex(halfedge(vh,*polyhedron()),*polyhedron());\n        compute_normal_maps();\n        polyhedron_item()->invalidateOpenGLBuffers();\n      }\n      else\n      {\n        d->tempInstructions(\"Vertex not selected : There must be no hole incident to the selection.\",\n                         \"Select the vertex you want to remove.\");\n      }\n      break;\n    }\n    case 11:\n      QGLViewer* viewer = *QGLViewer::QGLViewerPool().begin();\n      const qglviewer::Vec offset = static_cast<CGAL::Three::Viewer_interface*>(viewer)->offset();\n      if(viewer->manipulatedFrame() != d->manipulated_frame)\n      {\n        temp_selected_vertices.insert(vh);\n        k_ring_selector.setEditMode(false);\n        const Point_3& p = get(vpm,vh);\n        d->manipulated_frame->setPosition(p.x()+offset.x, p.y()+offset.y, p.z()+offset.z);\n        viewer->setManipulatedFrame(d->manipulated_frame);\n        connect(d->manipulated_frame, SIGNAL(modified()), this, SLOT(updateTick()));\n        invalidateOpenGLBuffers();\n        Q_EMIT updateInstructions(\"Ctrl+Right-click to move the point. \\nHit Ctrl+Z to leave the selection. (2/2)\");\n      }\n      else\n      {\n        temp_selected_vertices.clear();\n        temp_selected_vertices.insert(vh);\n        const Point_3& p = get(vpm,vh);\n        d->manipulated_frame->setPosition(p.x()+offset.x, p.y()+offset.y, p.z()+offset.z);\n        invalidateOpenGLBuffers();\n      }\n      break;\n    }\n  }\n  d->is_treated = true;\n  //Keeps the item from trying to draw primitive that has just been deleted.\n  clearHL();\n  return false;\n}\n\n//returns true if halfedge's facet's degree >= degree\n/*\nstd::size_t facet_degree(fg_halfedge_descriptor h, const Face_graph& polyhedron)\n{\n  return degree(h,polyhedron);\n}\n*/\nbool Scene_polyhedron_selection_item:: treat_selection(const std::set<fg_edge_descriptor>& selection)\n{\n  VPmap vpm = get(CGAL::vertex_point, *polyhedron());\n  fg_edge_descriptor ed =  *selection.begin();\n  if(!d->is_treated)\n  {\n    Selection_traits<fg_edge_descriptor, Scene_polyhedron_selection_item> tr(this);\n    switch(d->operation_mode)\n    {\n    //classic selection\n    case -1:\n    {\n      return treat_classic_selection(selection);\n      break;\n    }\n      //Join vertex\n    case 0:\n      if(boost::distance(CGAL::halfedges_around_face(halfedge(ed, *polyhedron()), *polyhedron())) < 4\n           ||\n         boost::distance(CGAL::halfedges_around_face(opposite(halfedge(ed, *polyhedron()),*polyhedron()),*polyhedron()))< 4)\n        {\n          d->tempInstructions(\"Edge not selected: the incident facets must have a degree of at least 4.\",\n                           \"Select the edge with extremities you want to join.\");\n        }\n        else\n        {\n          fg_halfedge_descriptor targt = halfedge(ed, *polyhedron());\n          Point S,T;\n          S = get(vpm, source(targt, *polyhedron()));\n          T = get(vpm, target(targt, *polyhedron()));\n          put(vpm, target(CGAL::Euler::join_vertex(targt,*polyhedron()),*polyhedron()), Point(0.5*(S.x()+T.x()), 0.5*(S.y()+T.y()), 0.5*(S.z()+T.z())));\n          d->tempInstructions(\"Vertices joined.\",\n                           \"Select the edge with extremities you want to join.\");\n          compute_normal_maps();\n          invalidateOpenGLBuffers();\n          polyhedron_item()->invalidateOpenGLBuffers();\n        }\n      break;\n      //Split edge\n    case 2:\n    {\n\n      Point_3 a(get(vpm,target(halfedge(ed, *polyhedron()),*polyhedron()))),\n        b(get(vpm,target(opposite(halfedge(ed, *polyhedron()),*polyhedron()),*polyhedron())));\n      fg_halfedge_descriptor hhandle = CGAL::Euler::split_edge(halfedge(ed, *polyhedron()),*polyhedron());\n        Point_3 p((b.x()+a.x())/2.0, (b.y()+a.y())/2.0,(b.z()+a.z())/2.0);\n\n        put(vpm, target(hhandle,*polyhedron()), p);\n        invalidateOpenGLBuffers();\n        poly_item->invalidateOpenGLBuffers();\n        compute_normal_maps();\n        d->tempInstructions(\"Edge splitted.\",\n                            \"Select the edge you want to split.\");\n        break;\n    }\n      //Join face\n    case 3:\n        if(out_degree(source(halfedge(ed,*polyhedron()),*polyhedron()),*polyhedron())<3 ||\n           out_degree(target(halfedge(ed,*polyhedron()),*polyhedron()),*polyhedron())<3)\n          d->tempInstructions(\"Faces not joined : the two ends of the edge must have a degree of at least 3.\",\n                           \"Select the edge separating the faces you want to join.\");\n        else\n        {\n          CGAL::Euler::join_face(halfedge(ed, *polyhedron()), *polyhedron());\n          compute_normal_maps();\n          poly_item->invalidateOpenGLBuffers();\n        }\n      break;\n      //Collapse edge\n    case 5:\n        if(!is_triangle_mesh(*polyhedron()))\n        {\n          d->tempInstructions(\"Edge not collapsed : the graph must be triangulated.\",\n                           \"Select the edge you want to collapse.\");\n        }\n        else if(!CGAL::Euler::does_satisfy_link_condition(ed, *polyhedron()))\n        {\n          d->tempInstructions(\"Edge not collapsed : link condition not satidfied.\",\n                           \"Select the edge you want to collapse.\");\n        }\n        else\n        {\n          fg_halfedge_descriptor targt = halfedge(ed, *polyhedron());\n          Point S,T;\n          S = get(vpm, source(targt, *polyhedron()));\n          T = get(vpm, target(targt, *polyhedron()));\n\n          put(vpm, CGAL::Euler::collapse_edge(ed, *polyhedron()), Point(0.5*(S.x()+T.x()), 0.5*(S.y()+T.y()), 0.5*(S.z()+T.z())));\n          compute_normal_maps();\n          polyhedron_item()->invalidateOpenGLBuffers();\n\n          d->tempInstructions(\"Edge collapsed.\",\n                           \"Select the edge you want to collapse.\");\n        }\n      break;\n      //Flip edge\n    case 6:\n\n        //check preconditions\n      if(boost::distance(CGAL::halfedges_around_face(halfedge(ed, *polyhedron()),*polyhedron())) == 3 \n         && \n         boost::distance(CGAL::halfedges_around_face(opposite(halfedge(ed, *polyhedron()),*polyhedron()),*polyhedron())) == 3)\n        {\n          CGAL::Euler::flip_edge(halfedge(ed, *polyhedron()), *polyhedron());\n          polyhedron_item()->invalidateOpenGLBuffers();\n          compute_normal_maps();\n        }\n        else\n        {\n          d->tempInstructions(\"Edge not selected : incident facets must be triangles.\",\n                           \"Select the edge you want to flip.\");\n        }\n\n      break;\n      //Add vertex and face to border\n    case 9:\n    {\n      static fg_halfedge_descriptor t;\n      if(!d->first_selected)\n      {\n          bool found = false;\n          fg_halfedge_descriptor hc = halfedge(ed, *polyhedron());\n          if(is_border(hc,*polyhedron()))\n          {\n            t = hc;\n            found = true;\n          }\n          else if(is_border(opposite(hc,*polyhedron()),*polyhedron()))\n          {\n            t = opposite(hc,*polyhedron());\n            found = true;\n          }\n          if(found)\n          {\n            d->first_selected = true;\n            temp_selected_edges.insert(edge(t, *polyhedron()));\n            temp_selected_vertices.insert(target(t,*polyhedron()));\n            invalidateOpenGLBuffers();\n            Q_EMIT updateInstructions(\"Select second edge. (2/2)\");\n          }\n          else\n          {\n            d->tempInstructions(\"Edge not selected : no border found.\",\n                             \"Select a border edge. (1/2)\");\n          }\n      }\n      else\n      {\n        fg_halfedge_descriptor hc = halfedge(ed, *polyhedron());\n        if(d->canAddFaceAndVertex(hc, t))\n        {\n          d->first_selected = false;\n\n\n          temp_selected_edges.clear();\n          temp_selected_vertices.clear();\n          compute_normal_maps();\n          invalidateOpenGLBuffers();\n          polyhedron_item()->invalidateOpenGLBuffers();\n          d->tempInstructions(\"Face and vertex added.\",\n                           \"Select a border edge. (1/2)\");\n        }\n      }\n      break;\n    }\n      //Add face to border\n    case 10:\n    {\n      static fg_halfedge_descriptor t;\n      if(!d->first_selected)\n      {\n          bool found = false;\n          fg_halfedge_descriptor hc = halfedge(ed, *polyhedron());\n          if(is_border(hc,*polyhedron()))\n          {\n            t = hc;\n            found = true;\n          }\n          else if(is_border(opposite(hc,*polyhedron()),*polyhedron()))\n          {\n            t = opposite(hc,*polyhedron());\n            found = true;\n          }\n          if(found)\n          {\n            d->first_selected = true;\n            temp_selected_edges.insert(edge(t, *polyhedron()));\n            temp_selected_vertices.insert(target(t,*polyhedron()));\n            invalidateOpenGLBuffers();\n            Q_EMIT updateInstructions(\"Select second edge. (2/2)\");\n            set_active_handle_type(static_cast<Active_handle::Type>(2));\n          }\n          else\n          {\n            d->tempInstructions(\"Edge not selected : no border found.\",\n                             \"Select a border edge. (1/2)\");\n          }\n      }\n      else\n      {\n        fg_halfedge_descriptor hc = halfedge(ed, *polyhedron());\n        if(d->canAddFace(hc, t))\n        {\n          d->first_selected = false;\n          temp_selected_vertices.clear();\n          temp_selected_edges.clear();\n          compute_normal_maps();\n          invalidateOpenGLBuffers();\n          polyhedron_item()->invalidateOpenGLBuffers();\n          d->tempInstructions(\"Face added.\",\n                           \"Select a border edge. (1/2)\");\n        }\n      }\n      break;\n    }\n    }\n  }\n  d->is_treated = true;\n  //Keeps the item from trying to draw primitive that has just been deleted.\n  clearHL();\n  return false;\n}\n\nbool Scene_polyhedron_selection_item::treat_selection(const std::vector<fg_face_descriptor>& selection)\n{\n  return treat_classic_selection(selection);\n}\n\nbool Scene_polyhedron_selection_item::treat_selection(const std::set<fg_face_descriptor>& selection)\n{\n  VPmap vpm = get(CGAL::vertex_point,*polyhedron());\n  if(!d->is_treated)\n  {\n    fg_face_descriptor fh = *selection.begin();\n    Selection_traits<fg_face_descriptor, Scene_polyhedron_selection_item> tr(this);\n    switch(d->operation_mode)\n    {\n    //classic selection\n    case -1:\n    {\n      return treat_classic_selection(selection);\n      break;\n    }\n    //Split vertex\n    case 1:\n    {\n      static fg_halfedge_descriptor h1;\n      //stores first fh and emit change label\n      if(!d->first_selected)\n      {\n          bool found = false;\n          //test preco\n          BOOST_FOREACH(fg_halfedge_descriptor hafc, halfedges_around_face(halfedge(fh,*polyhedron()),*polyhedron()))\n          {\n            if(target(hafc,*polyhedron())==d->to_split_vh)\n            {\n              h1 = hafc;\n              found = true;\n              break;\n            }\n          }\n          if(found)\n          {\n            d->first_selected = true;\n            temp_selected_facets.insert(fh);\n            invalidateOpenGLBuffers();\n            Q_EMIT updateInstructions(\"Select the second facet. (3/3)\");\n          }\n          else\n            d->tempInstructions(\"Facet not selected : no valid halfedge\",\n                             \"Select first facet. (2/3)\");\n      }\n      //call the function with point and facets.\n      else\n      {\n          //get the right halfedges\n          fg_halfedge_descriptor h2;\n          bool found = false;\n          BOOST_FOREACH(fg_halfedge_descriptor hafc, halfedges_around_face(halfedge(fh,*polyhedron()),*polyhedron()))\n          {\n            if(target(hafc,*polyhedron())==d->to_split_vh)\n            {\n              h2 = hafc;\n              found = true;\n              break;\n            }\n          }\n\n          if(found &&(h1 != h2))\n          {\n            fg_halfedge_descriptor hhandle = CGAL::Euler::split_vertex(h1,h2,*polyhedron());\n\n            temp_selected_facets.clear();\n            Point_3 p1t = get(vpm, target(h1,*polyhedron()));\n            Point_3 p1s = get(vpm, target(opposite(h1,*polyhedron()),*polyhedron()));\n            double x =  p1t.x() + 0.01 * (p1s.x() - p1t.x());\n            double y =  p1t.y() + 0.01 * (p1s.y() - p1t.y());\n            double z =  p1t.z() + 0.01 * (p1s.z() - p1t.z());\n            put(vpm, target(opposite(hhandle,*polyhedron()),*polyhedron()), Point_3(x,y,z));;\n            d->first_selected = false;\n            temp_selected_vertices.clear();\n            compute_normal_maps();\n            invalidateOpenGLBuffers();\n            //reset selection mode\n            set_active_handle_type(static_cast<Active_handle::Type>(0));\n            poly_item->invalidateOpenGLBuffers();\n            d->tempInstructions(\"Vertex splitted.\", \"Select the vertex you want splitted. (1/3)\");\n          }\n          else if(h1 == h2)\n          {\n             d->tempInstructions(\"Facet not selected : same as the first.\", \"Select the second facet. (3/3)\");\n          }\n          else\n          {\n            d->tempInstructions(\"Facet not selected : no valid halfedge.\", \"Select the second facet. (3/3)\");\n          }\n      }\n      break;\n    }\n      //Split face\n    case 4:\n      if(is_triangle(halfedge(fh,*d->poly), *d->poly))\n      {\n        d->tempInstructions(\"Facet not selected : Facet must not be a triangle.\",\n                         \"Select the facet you want to split (degree >= 4). (1/3)\");\n      }\n      else\n      {\n        d->to_split_fh = fh;\n        temp_selected_facets.insert(d->to_split_fh);\n        compute_normal_maps();\n        invalidateOpenGLBuffers();\n        //set to select vertex\n        set_active_handle_type(static_cast<Active_handle::Type>(0));\n        Q_EMIT updateInstructions(\"Select first vertex. (2/3)\");\n      }\n      break;\n      //Add center vertex\n    case 7:\n      if(is_border(halfedge(fh,*polyhedron()),*polyhedron()))\n        {\n          d->tempInstructions(\"Facet not selected : Facet must not be null.\",\n                           \"Select a Facet. (1/3)\");\n        }\n        else\n        {\n          double x(0), y(0), z(0);\n          int total(0);\n\n          BOOST_FOREACH(fg_halfedge_descriptor hafc, halfedges_around_face(halfedge(fh,*polyhedron()),*polyhedron()))\n          {\n            fg_vertex_descriptor vd = target(hafc,*polyhedron());\n            Point_3& p = get(vpm,vd);\n            x+= p.x(); y+=p.y(); z+=p.z();\n            total++;\n          }\n          fg_halfedge_descriptor hhandle = CGAL::Euler::add_center_vertex(halfedge(fh,*polyhedron()), *polyhedron());\n          if(total !=0)\n            put(vpm, target(hhandle,*polyhedron()), Point_3(x/(double)total, y/(double)total, z/(double)total));\n          compute_normal_maps();\n          poly_item->invalidateOpenGLBuffers();\n\n        }\n      break;\n    }\n  }\n  d->is_treated = true;\n  //Keeps the item from trying to draw primitive that has just been deleted.\n  clearHL();\n  return false;\n}\n\nvoid Scene_polyhedron_selection_item_priv::tempInstructions(QString s1, QString s2)\n{\n  m_temp_instructs = s2;\n  Q_EMIT item->updateInstructions(QString(\"<font color='red'>%1</font>\").arg(s1));\n  QTimer timer;\n  timer.singleShot(5500, item, SLOT(emitTempInstruct()));\n}\nvoid Scene_polyhedron_selection_item::emitTempInstruct()\n{\n  Q_EMIT updateInstructions(QString(\"<font color='black'>%1</font>\").arg(d->m_temp_instructs));\n}\n\n/// An exception used while catching a throw that stops Dijkstra's algorithm\n/// once the shortest path to a target has been found.\nclass Dijkstra_end_exception : public std::exception\n{\n  const char* what() const throw ()\n  {\n    return \"Dijkstra shortest path: reached the target vertex.\";\n  }\n};\n\n/// Visitor to stop Dijkstra's algorithm once the given target turns 'BLACK',\n/// that is when the target has been examined through all its incident edges and\n/// the shortest path is thus known.\nclass Stop_at_target_Dijkstra_visitor : boost::default_dijkstra_visitor\n{\n  fg_vertex_descriptor destination_vd;\n\npublic:\n  Stop_at_target_Dijkstra_visitor(fg_vertex_descriptor destination_vd)\n    : destination_vd(destination_vd)\n  { }\n\n  void initialize_vertex(const fg_vertex_descriptor& /*s*/, const Face_graph& /*mesh*/) const { }\n  void examine_vertex(const fg_vertex_descriptor& /*s*/, const Face_graph& /*mesh*/) const { }\n  void examine_edge(const fg_edge_descriptor& /*e*/, const Face_graph& /*mesh*/) const { }\n  void edge_relaxed(const fg_edge_descriptor& /*e*/, const Face_graph& /*mesh*/) const { }\n  void discover_vertex(const fg_vertex_descriptor& /*s*/, const Face_graph& /*mesh*/) const { }\n  void edge_not_relaxed(const fg_edge_descriptor& /*e*/, const Face_graph& /*mesh*/) const { }\n  void finish_vertex(const fg_vertex_descriptor &vd, const Face_graph& /* mesh*/) const\n  {\n    if(vd == destination_vd)\n      throw Dijkstra_end_exception();\n  }\n};\n\nvoid Scene_polyhedron_selection_item_priv::computeAndDisplayPath()\n{\n  item->temp_selected_edges.clear();\n  path.clear();\n\n  typedef boost::unordered_map<fg_vertex_descriptor, fg_vertex_descriptor>     Pred_umap;\n  typedef boost::associative_property_map<Pred_umap>                     Pred_pmap;\n\n  Pred_umap predecessor;\n  Pred_pmap pred_pmap(predecessor);\n\n  vertex_on_path vop;\n  QList<fg_vertex_descriptor>::iterator it;\n  for(it = constrained_vertices.begin(); it!=constrained_vertices.end()-1; ++it)\n  {\n    fg_vertex_descriptor t(*it), s(*(it+1));\n    Stop_at_target_Dijkstra_visitor vis(t);\n\n    try\n    {\n      boost::dijkstra_shortest_paths(*item->polyhedron(), s,\n                                     boost::predecessor_map(pred_pmap).visitor(vis));\n    }\n    catch (const std::exception& e)\n    {\n      std::cout << e.what() << std::endl;\n    }\n\n    // Walk back from target to source and collect vertices along the way\n    do\n    {\n      vop.vertex = t;\n      if(constrained_vertices.contains(t))\n      {\n        vop.is_constrained = true;\n      }\n      else\n        vop.is_constrained = false;\n      path.append(vop);\n      t = get(pred_pmap, t);\n    }\n    while(t != s);\n  }\n\n  // Add the last vertex\n  vop.vertex = constrained_vertices.last();\n  vop.is_constrained = true;\n  path.append(vop);\n\n  // Display path\n  QList<vertex_on_path>::iterator path_it;\n  for(path_it = path.begin(); path_it!=path.end()-1; ++path_it)\n  {\n    std::pair<fg_halfedge_descriptor, bool> h = halfedge((path_it+1)->vertex,path_it->vertex,*item->polyhedron());\n    if(h.second)\n      item->temp_selected_edges.insert(edge(h.first, *item->polyhedron()));\n  }\n}\n\nvoid Scene_polyhedron_selection_item_priv::addVertexToPath(fg_vertex_descriptor vh, vertex_on_path &first)\n{\n  vertex_on_path source;\n  source.vertex = vh;\n  source.is_constrained = true;\n  path.append(source);\n  first = source;\n}\nvoid Scene_polyhedron_selection_item::selectPath(fg_vertex_descriptor vh)\n{\n\n  bool replace = !temp_selected_edges.empty();\n  static Scene_polyhedron_selection_item_priv::vertex_on_path first;\n  if(!d->first_selected)\n  {\n    //if the path doesnt exist, add the vertex as the source of the path.\n    if(!replace)\n    {\n      d->addVertexToPath(vh, first);\n    }\n    //if the path exists, get the vertex_on_path corresponding to the selected vertex.\n    else\n    {\n      //The first vertex of the path can not be moved, but you can close your path on it to make a loop.\n      bool alone = true;\n      QList<Scene_polyhedron_selection_item_priv::vertex_on_path>::iterator it;\n      for(it = d->path.begin(); it!=d->path.end(); ++it)\n      {\n        if(it->vertex == vh&& it!=d->path.begin())\n          alone = false;\n      }\n      if(d->path.begin()->vertex == vh )\n        if(alone)\n        {\n          d->constrained_vertices.append(vh); //if the path loops, the indexOf may be invalid, hence the check.\n          //Display the new path\n          d->computeAndDisplayPath();\n          d->first_selected = false;\n          d->constrained_vertices.clear();\n          fixed_vertices.clear();\n          for(it = d->path.begin(); it!=d->path.end(); ++it)\n          {\n            if(it->is_constrained )\n            {\n              d->constrained_vertices.append(it->vertex);\n              fixed_vertices.insert(it->vertex);\n            }\n          }\n\n          return;\n        }\n      bool found = false;\n      Q_FOREACH(Scene_polyhedron_selection_item_priv::vertex_on_path vop, d->path)\n      {\n        if(vop.vertex == vh)\n        {\n          first = vop;\n          found = true;\n          break;\n        }\n      }\n      if(!found)//add new end_point;\n      {\n        d->constrained_vertices.append(vh);\n        //Display the new path\n        d->computeAndDisplayPath();\n        d->first_selected = false;\n        d->constrained_vertices.clear();\n        fixed_vertices.clear();\n        for(it = d->path.begin(); it!=d->path.end(); ++it)\n        {\n          if(it->is_constrained )\n          {\n            d->constrained_vertices.append(it->vertex);\n            fixed_vertices.insert(it->vertex);\n          }\n        }\n\n        return;\n      }\n    }\n    temp_selected_vertices.insert(vh);\n    d->first_selected = true;\n  }\n  else\n  {\n    if(!replace)\n    {\n      d->constrained_vertices.append(vh);\n      temp_selected_vertices.erase(first.vertex);\n\n      updateInstructions(\"You can select a vertex on the green path to move it. \"\n                         \"If you do so, it will become a red fixed point. \"\n                         \"The path will be recomputed to go through that point. \"\n                         \"Click on 'Add to selection' to validate the selection.   (2/2)\");\n    }\n    else\n    {\n      bool is_same(false), alone(true);\n      if( (vh == d->constrained_vertices.first() && first.vertex == d->constrained_vertices.last())\n          || (vh == d->constrained_vertices.last() && first.vertex == d->constrained_vertices.first()))\n\n      {\n        is_same = true;\n      }\n      if(first.vertex == d->path.begin()->vertex)\n        alone =false;\n      bool is_last = true;\n      //find the previous constrained vertex on path\n      Scene_polyhedron_selection_item_priv::vertex_on_path closest = d->path.last();\n      QList<Scene_polyhedron_selection_item_priv::vertex_on_path>::iterator it;\n      int index = 0;\n      int closest_index = 0;\n      //get first's index\n      for(it = d->path.begin(); it!=d->path.end(); ++it)\n      {\n        bool end_of_path_is_prio = true;//makes the end of the path prioritary over the other points when there is a conflict\n        if(first.vertex == (d->path.end()-1)->vertex)\n          if(it != d->path.end()-1)\n            end_of_path_is_prio = false;\n        //makes the end of the path prioritary over the other points when there is a conflict\n        if(it->vertex == first.vertex &&\n           !(it == d->path.begin())&&// makes the begining of the path impossible to move\n           end_of_path_is_prio)\n        {\n          if(it!=d->path.end()-1 &&! is_same )\n          {\n            d->constrained_vertices.removeAll(it->vertex);\n            if(!alone)\n              d->constrained_vertices.prepend(it->vertex);\n          }\n          d->path.erase(it);\n          break;\n        }\n        if(it->is_constrained)\n          closest_index++;\n        index++;\n      }\n      //get first constrained vertex following first in path\n      for(it = d->path.begin() + index; it!=d->path.end(); ++it)\n      {\n        if(it->is_constrained )\n        {\n          is_last = false;\n          closest = *it;\n          break;\n        }\n      }\n      //mark the new vertex as constrained before closest.\n      temp_selected_vertices.erase(first.vertex);\n      //check if the vertex is contained several times in the path\n      if(!is_last)\n      {\n        d->constrained_vertices.insert(closest_index, vh);//cannot really use indexOf in case a fixed_point is used several times\n      }\n      else\n        d->constrained_vertices.replace(d->constrained_vertices.size()-1, vh);\n\n\n    }\n    //Display the new path\n    d->computeAndDisplayPath();\n    d->first_selected = false;\n  }\n  //update constrained_vertices\n  d->constrained_vertices.clear();\n  fixed_vertices.clear();\n  QList<Scene_polyhedron_selection_item_priv::vertex_on_path>::iterator it;\n  for(it = d->path.begin(); it!=d->path.end(); ++it)\n  {\n    if(it->is_constrained )\n    {\n      d->constrained_vertices.append(it->vertex);\n      fixed_vertices.insert(it->vertex);\n    }\n  }\n}\n\n\nvoid Scene_polyhedron_selection_item::on_Ctrlz_pressed()\n{\n  d->path.clear();\n  d->constrained_vertices.clear();\n  fixed_vertices.clear();\n  validateMoveVertex();\n  d->first_selected = false;\n  temp_selected_vertices.clear();\n  temp_selected_edges.clear();\n  temp_selected_facets.clear();\n  d->are_temp_buffers_filled = false;\n  set_operation_mode(d->operation_mode);\n  Q_EMIT itemChanged();\n}\n\nScene_polyhedron_selection_item::Scene_polyhedron_selection_item()\n  : Scene_polyhedron_item_decorator(NULL, false)\n{\n  d = new Scene_polyhedron_selection_item_priv(this);\n  d->original_sel_mode = static_cast<Active_handle::Type>(0);\n  d->operation_mode = -1;\n  for(int i=0; i<Scene_polyhedron_selection_item_priv::NumberOfVaos; i++)\n  {\n    addVaos(i);\n    vaos[i]->create();\n  }\n\n  for(int i=0; i<Scene_polyhedron_selection_item_priv::NumberOfVbos; i++)\n  {\n    buffers[i].create();\n  }\n  d->nb_facets = 0;\n  d->nb_points = 0;\n  d->nb_lines = 0;\n  this->setColor(QColor(87,87,87));\n  d->first_selected = false;\n  d->is_treated = false;\n  d->poly_need_update = false;\n  d->are_temp_buffers_filled = false;\n  d->poly = NULL;\n  d->ready_to_move = false;\n}\n\nScene_polyhedron_selection_item::Scene_polyhedron_selection_item(Scene_face_graph_item* poly_item, QMainWindow* mw)\n  : Scene_polyhedron_item_decorator(NULL, false)\n{\n  d = new Scene_polyhedron_selection_item_priv(this);\n  d->original_sel_mode = static_cast<Active_handle::Type>(0);\n  d->operation_mode = -1;\n  d->nb_facets = 0;\n  d->nb_points = 0;\n  d->nb_lines = 0;\n\n  for(int i=0; i<Scene_polyhedron_selection_item_priv::NumberOfVaos; i++)\n  {\n    addVaos(i);\n    vaos[i]->create();\n  }\n\n  for(int i=0; i<Scene_polyhedron_selection_item_priv::NumberOfVbos; i++)\n  {\n    buffers[i].create();\n  }\n  d->poly = NULL;\n  init(poly_item, mw);\n  this->setColor(QColor(87,87,87));\n  invalidateOpenGLBuffers();\n  compute_normal_maps();\n  d->first_selected = false;\n  d->is_treated = false;\n  d->poly_need_update = false;\n  d->ready_to_move = false;\n\n}\n\nScene_polyhedron_selection_item::~Scene_polyhedron_selection_item()\n{\n  delete d;\n  QGLViewer* v = *QGLViewer::QGLViewerPool().begin();\n  CGAL::Three::Viewer_interface* viewer = dynamic_cast<CGAL::Three::Viewer_interface*>(v);\n  viewer->setBindingSelect();\n}\n\nvoid Scene_polyhedron_selection_item::setPathSelection(bool b) {\n  k_ring_selector.setEditMode(b);\n  d->is_path_selecting = b;\n  if(d->is_path_selecting){\n    int ind = 0;\n    boost::property_map<Face_graph,CGAL::vertex_selection_t>::type vsm =\n      get(CGAL::vertex_selection,*polyhedron());\n    BOOST_FOREACH(fg_vertex_descriptor vd, vertices(*polyhedron())){\n      put(vsm,vd, ind++);\n    }\n  }\n}\n\nvoid Scene_polyhedron_selection_item::update_poly()\n{\n  if(d->poly_need_update)\n    poly_item->invalidateOpenGLBuffers();\n}\n\nvoid Scene_polyhedron_selection_item::resetIsTreated() { d->is_treated = false;}\n\nvoid Scene_polyhedron_selection_item::invalidateOpenGLBuffers() {\n\n  // do not use decorator function, which calls changed on poly_item which cause deletion of AABB\n    //  poly_item->invalidateOpenGLBuffers();\n      are_buffers_filled = false;\n      d->are_temp_buffers_filled = false;\n      d->poly = polyhedron();\n      compute_bbox();\n}\n\nvoid Scene_polyhedron_selection_item::add_to_selection()\n{\n  Q_FOREACH(fg_edge_descriptor ed, temp_selected_edges)\n  {\n    selected_edges.insert(ed);\n    temp_selected_edges.erase(ed);\n  }\n  on_Ctrlz_pressed();\n  invalidateOpenGLBuffers();\n  QGLViewer* v = *QGLViewer::QGLViewerPool().begin();\n  v->update();\n  d->tempInstructions(\"Path added to selection.\",\n                   \"Select two vertices to create the path between them. (1/2)\");\n}\n\nvoid Scene_polyhedron_selection_item::save_handleType()\n{\n  d->original_sel_mode = get_active_handle_type();\n}\nvoid Scene_polyhedron_selection_item::compute_normal_maps()\n{\n\n  d->face_normals_map.clear();\n  d->vertex_normals_map.clear();\n  d->nf_pmap = boost::associative_property_map< CGAL::Unique_hash_map<fg_face_descriptor, Kernel::Vector_3> >(d->face_normals_map);\n  d->nv_pmap = boost::associative_property_map< CGAL::Unique_hash_map<fg_vertex_descriptor, Kernel::Vector_3> >(d->vertex_normals_map);\n  PMP::compute_normals(*d->poly, d->nv_pmap, d->nf_pmap);\n}\n\nvoid Scene_polyhedron_selection_item::updateTick()\n{\n    d->ready_to_move = true;\n    QTimer::singleShot(0,this,SLOT(moveVertex()));\n}\n\n\nvoid Scene_polyhedron_selection_item::moveVertex()\n{\n  if(d->ready_to_move)\n  {\n     const qglviewer::Vec offset = static_cast<CGAL::Three::Viewer_interface*>(QGLViewer::QGLViewerPool().first())->offset();\n    fg_vertex_descriptor vh = *temp_selected_vertices.begin();\n\n    VPmap vpm = get(CGAL::vertex_point,*polyhedron());\n    put(vpm, vh, Point_3(d->manipulated_frame->position().x-offset.x,\n                         d->manipulated_frame->position().y-offset.y,\n                         d->manipulated_frame->position().z-offset.z));\n    invalidateOpenGLBuffers();\n    poly_item->invalidateOpenGLBuffers();\n    d->ready_to_move = false;\n  }\n}\n\nvoid Scene_polyhedron_selection_item::validateMoveVertex()\n{\n  temp_selected_vertices.clear();\n  QGLViewer* viewer = *QGLViewer::QGLViewerPool().begin();\n  k_ring_selector.setEditMode(true);\n  viewer->setManipulatedFrame(NULL);\n  invalidateOpenGLBuffers();\n  Q_EMIT updateInstructions(\"Select a vertex. (1/2)\");\n}\n\n\nbool Scene_polyhedron_selection_item_priv::canAddFace(fg_halfedge_descriptor hc, fg_halfedge_descriptor t)\n{\n  bool found(false),  is_border_h(false);\n\n  //if the selected halfedge is not a border, stop and signal it.\n  if(is_border(hc,*polyhedron()))\n    is_border_h = true;\n  else if(is_border(opposite(hc,*polyhedron()),*polyhedron()))\n  {\n    hc = opposite(hc,*polyhedron());\n    is_border_h = true;\n  }\n  if(!is_border_h)\n  {\n    tempInstructions(\"Edge not selected : no shared border found.\",\n                     \"Select the second edge. (2/2)\");\n    return false;\n  }\n  //if the halfedges are the same, stop and signal it.\n  if(hc == t)\n  {\n    tempInstructions(\"Edge not selected : halfedges must be different.\",\n                     \"Select the second edge. (2/2)\");\n    return false;\n  }\n  //if the halfedges are adjacent, stop and signal it.\n  if(next(t, *item->polyhedron()) == hc || next(hc, *item->polyhedron()) == t)\n  {\n    tempInstructions(\"Edge not selected : halfedges must not be adjacent.\",\n                     \"Select the second edge. (2/2)\");\n    return false;\n  }\n\n  //if the halfedges are not on the same border, stop and signal it.\n  fg_halfedge_descriptor iterator = next(t, *item->polyhedron());\n  while(iterator != t)\n  {\n    if(iterator == hc)\n    {\n      found = true;\n      fg_halfedge_descriptor res =\n          CGAL::Euler::add_face_to_border(t,hc, *item->polyhedron());\n\n      if(CGAL::is_degenerate_triangle_face(res, *item->polyhedron(), get(CGAL::vertex_point, *item->polyhedron()), Kernel()))\n      {\n        CGAL::Euler::remove_face(res, *item->polyhedron());\n        tempInstructions(\"Edge not selected : resulting facet is degenerated.\",\n                         \"Select the second edge. (2/2)\");\n        return false;\n      }\n      break;\n    }\n    iterator = next(iterator, *item->polyhedron());\n  }\n  if(!found)\n  {\n    tempInstructions(\"Edge not selected : no shared border found.\",\n                     \"Select the second edge. (2/2)\");\n    return false;\n  }\n  return true;\n}\n\nbool Scene_polyhedron_selection_item_priv::canAddFaceAndVertex(fg_halfedge_descriptor hc, fg_halfedge_descriptor t)\n{\n  bool found(false),  is_border_h(false);\n\n  //if the selected halfedge is not a border, stop and signal it.\n  if(is_border(hc,*polyhedron()))\n    is_border_h = true;\n  else if(is_border(opposite(hc,*polyhedron()),*polyhedron()))\n  {\n    hc = opposite(hc,*polyhedron());\n    is_border_h = true;\n  }\n  if(!is_border_h)\n  {\n    tempInstructions(\"Edge not selected : no shared border found.\",\n                     \"Select the second edge. (2/2)\");\n    return false;\n  }\n  //if the halfedges are the same, stop and signal it.\n  if(hc == t)\n  {\n    tempInstructions(\"Edge not selected : halfedges must be different.\",\n                     \"Select the second edge. (2/2)\");\n    return false;\n  }\n\n  //if the halfedges are not on the same border, stop and signal it.\n  fg_halfedge_descriptor iterator = next(t, *item->polyhedron());\n  while(iterator != t)\n  {\n    if(iterator == hc)\n    {\n      found = true;\n      CGAL::Euler::add_vertex_and_face_to_border(hc,t, *item->polyhedron());\n      break;\n    }\n    iterator = next(iterator, *item->polyhedron());\n  }\n  if(!found)\n  {\n    tempInstructions(\"Edge not selected : no shared border found.\",\n                     \"Select the second edge. (2/2)\");\n    return false;\n  }\n  return true;\n}\n\nvoid Scene_polyhedron_selection_item::clearHL()\n{\n  HL_selected_edges.clear();\n  HL_selected_facets.clear();\n  HL_selected_vertices.clear();\n  d->are_HL_buffers_filled = false;\n  Q_EMIT itemChanged();\n}\nvoid Scene_polyhedron_selection_item::selected_HL(const std::set<fg_vertex_descriptor>& m)\n{\n  HL_selected_edges.clear();\n  HL_selected_facets.clear();\n  HL_selected_vertices.clear();\n  HL_selected_vertices.insert(*m.begin());\n\n  d->are_HL_buffers_filled = false;\n  Q_EMIT itemChanged();\n}\n\nvoid Scene_polyhedron_selection_item::selected_HL(const std::set<fg_face_descriptor>& m)\n{\n  HL_selected_edges.clear();\n  HL_selected_facets.clear();\n  HL_selected_vertices.clear();\n  HL_selected_facets.insert(*m.begin());\n  d->are_HL_buffers_filled = false;\n  Q_EMIT itemChanged();\n}\n\nvoid Scene_polyhedron_selection_item::selected_HL(const std::set<fg_edge_descriptor>& m)\n{\n  HL_selected_edges.clear();\n  HL_selected_facets.clear();\n  HL_selected_vertices.clear();\n  HL_selected_edges.insert(*m.begin());\n  d->are_HL_buffers_filled = false;\n  Q_EMIT itemChanged();\n}\n\nvoid Scene_polyhedron_selection_item::init(Scene_face_graph_item* poly_item, QMainWindow* mw)\n{\n  this->poly_item = poly_item;\n  d->poly =poly_item->polyhedron();\n  connect(poly_item, SIGNAL(item_is_about_to_be_changed()), this, SLOT(poly_item_changed()));\n  //parameters type must be of the same name here and there, so they must be hardcoded.\n  connect(&k_ring_selector, SIGNAL(selected(const std::set<fg_vertex_descriptor>&)), this,\n    SLOT(selected(const std::set<fg_vertex_descriptor>&)));\n\n  connect(&k_ring_selector, SIGNAL(selected(const std::set<fg_face_descriptor>&)), this,\n    SLOT(selected(const std::set<fg_face_descriptor>&)));\n\n  connect(&k_ring_selector, SIGNAL(selected(const std::set<fg_edge_descriptor>&)), this,\n    SLOT(selected(const std::set<fg_edge_descriptor>&)));\n\n  connect(&k_ring_selector, SIGNAL(selected_HL(const std::set<fg_vertex_descriptor>&)), this,\n          SLOT(selected_HL(const std::set<fg_vertex_descriptor>&)));\n\n  connect(&k_ring_selector, SIGNAL(selected_HL(const std::set<fg_face_descriptor>&)), this,\n          SLOT(selected_HL(const std::set<fg_face_descriptor>&)));\n\n  connect(&k_ring_selector, SIGNAL(selected_HL(const std::set<fg_edge_descriptor>&)), this,\n          SLOT(selected_HL(const std::set<fg_edge_descriptor>&)));\n  connect(&k_ring_selector, SIGNAL(clearHL()), this,\n          SLOT(clearHL()));\n  connect(poly_item, SIGNAL(selection_done()), this, SLOT(update_poly()));\n  connect(&k_ring_selector, SIGNAL(endSelection()), this,SLOT(endSelection()));\n  connect(&k_ring_selector, SIGNAL(toogle_insert(bool)), this,SLOT(toggle_insert(bool)));\n  connect(&k_ring_selector,SIGNAL(isCurrentlySelected(Scene_facegraph_item_k_ring_selection*)), this, SIGNAL(isCurrentlySelected(Scene_facegraph_item_k_ring_selection*)));\n   k_ring_selector.init(poly_item, mw, Active_handle::VERTEX, -1);\n  connect(&k_ring_selector, SIGNAL(resetIsTreated()), this, SLOT(resetIsTreated()));\n  QGLViewer* viewer = *QGLViewer::QGLViewerPool().begin();\n  d->manipulated_frame = new ManipulatedFrame();\n  viewer->installEventFilter(this);\n  mw->installEventFilter(this);\n}\n\nvoid Scene_polyhedron_selection_item::select_all_NT()\n{\n  BOOST_FOREACH(fg_face_descriptor fd, faces(*polyhedron())){\n    if(! is_triangle(halfedge(fd,*polyhedron()), *polyhedron()))\n    selected_facets.insert(fd);\n  }\n  invalidateOpenGLBuffers();\n  Q_EMIT itemChanged();\n}\n\nvoid Scene_polyhedron_selection_item::selection_changed(bool b)\n{\n  QGLViewer* v = *QGLViewer::QGLViewerPool().begin();\n  CGAL::Three::Viewer_interface* viewer = dynamic_cast<CGAL::Three::Viewer_interface*>(v);\n  if(!viewer)\n      return;\n\n  if(!b)\n  {\n    viewer->setBindingSelect();\n  }\n  else\n  {\n    viewer->setNoBinding();\n  }\n}\n\nvoid Scene_polyhedron_selection_item::printPrimitiveId(QPoint p, CGAL::Three::Viewer_interface* viewer)\n{\n  d->item->polyhedron_item()->printPrimitiveId(p, viewer);\n}\nbool Scene_polyhedron_selection_item::printVertexIds(CGAL::Three::Viewer_interface* viewer) const\n{\n  return d->item->polyhedron_item()->printVertexIds(viewer);\n  return false;\n}\nbool Scene_polyhedron_selection_item::printEdgeIds(CGAL::Three::Viewer_interface* viewer) const\n{\n  d->item->polyhedron_item()->printEdgeIds(viewer);\n  return false;\n}\nbool Scene_polyhedron_selection_item::printFaceIds(CGAL::Three::Viewer_interface* viewer) const\n{\n  return d->item->polyhedron_item()->printFaceIds(viewer);\n  return false;\n}\nvoid Scene_polyhedron_selection_item::printAllIds(CGAL::Three::Viewer_interface* viewer)\n{\n  d->item->polyhedron_item()->printAllIds(viewer);\n}\nbool Scene_polyhedron_selection_item::testDisplayId(double x, double y, double z, CGAL::Three::Viewer_interface* viewer)const\n{\n  return d->item->polyhedron_item()->testDisplayId(x, y, z, viewer);\n  return false;\n}\n\nbool Scene_polyhedron_selection_item::shouldDisplayIds(CGAL::Three::Scene_item *current_item) const\n{\n  return d->item->polyhedron_item() == current_item;\n  return false;\n}\n", "meta": {"hexsha": "5f982baab6a60fc03f5cc0eed2b854ffd9dff6a4", "size": 76465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Scene_polyhedron_selection_item.cpp", "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": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Scene_polyhedron_selection_item.cpp", "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": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Scene_polyhedron_selection_item.cpp", "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": 34.0601336303, "max_line_length": 187, "alphanum_fraction": 0.6589289217, "num_tokens": 18739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19954526899827854}}
{"text": "//\n//  main.cpp\n//  sthlm\n//\n//  Created by Jilin Zhang on 2/14/17.\n//  Copyright \u00a9 2017 Jilin Zhang. All rights reserved.\n//\n\n\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include \"unordered_map\"\n#include <sstream>\n#include <vector>\n#include <stdlib.h>\n#include <math.h>\n#include <iomanip>\n#include <algorithm>\n#include <boost/program_options.hpp>\n//#include \"omp.h\"\n#include \"kseq.h\"\n#include <zlib.h>\n\nKSEQ_INIT(gzFile,gzread);\n\n//\nstruct Unitscore{\n    long count;\n    double discore;\n    double monoscore;\n};\n\nstd::unordered_map<std::string, Unitscore > kstore;\n\n\n//g++ -std=c++11 main.cpp -o rmap\n//g++ -std=c++11 main.cpp -o rmap -lboost_program_options -lz\n/*\n basemap[] works by storing a very small array that maps a base to\n its complement, by dereferencing the array with the ASCII char's\n decimal value as the index\n (int) 'A' = 65;\n (int) 'C' = 67;\n (int) 'G' = 71;\n (int) 'T' = 84;\n (int) 'a' = 97;\n (int) 'c' = 99;\n (int) 'g' = 103;\n (int) 't' = 116;\n (int) 'N' = 78;\n (int) 'U' = 85;\n (int) 'u' = 117;\n for example: basemap['A'] => basemap[65] => 'T' etc.\n */\nstatic const char basemap[255] =\n{\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /*   0 -   9 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /*  10 -  19 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /*  20 -  29 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /*  30 -  39 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /*  40 -  49 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /*  50 -  59 */\n    '\\0', '\\0', '\\0', '\\0', '\\0',  'U', '\\0',  'G', '\\0', '\\0', /*  60 -  69 */\n    '\\0',  'C', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0',  'N', '\\0', /*  70 -  79 */\n    '\\0', '\\0', '\\0', '\\0',  'A',  'A', '\\0', '\\0', '\\0', '\\0', /*  80 -  89 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0',  'u', '\\0',  'g', /*  90 -  99 */\n    '\\0', '\\0', '\\0',  'c', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 100 - 109 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0',  'a',  'a', '\\0', '\\0', /* 110 - 119 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 120 - 129 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 130 - 139 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 140 - 149 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 150 - 159 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 160 - 169 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 170 - 179 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 180 - 189 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 190 - 199 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 200 - 209 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 210 - 219 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 220 - 229 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 230 - 239 */\n    '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 240 - 249 */\n    '\\0', '\\0', '\\0', '\\0', '\\0'                                /* 250 - 254 */\n};\n\nvoid fetch_matrix(std::unordered_map<std::string, std::vector<double> > *map, std::string str, int ind, double count);\nvoid show_matrix(std::unordered_map<std::string, std::vector<double> > *x);\nvoid kmerizing (std::string *id, std::string* seq,  int kmer, int gap, std::string* name, std::unordered_map<std::string, std::vector<double> > *map);\ndouble monoscoring(std::string subseq, std::unordered_map<std::string, std::vector<double> > *map, int gap_len=0, int gap_pos=0);\ndouble discoring(std::string subseq, std::unordered_map<std::string, std::vector<double> > *map, int gap_len=0, int gap_pos=0);\ninline double singleStringScore(double x, std::string* s, long p, std::unordered_map<std::string, std::vector<double> > *m);\ninline double pairStringScore(double x, std::string* s, long sp, std::unordered_map<std::string,std::vector<double> > *m);\nvoid Matrixfile(const char*x, std::unordered_map<std::string, std::vector<double> > *y, double pseudo_count);\nint listParser(const char* list_name, std::string* names, int* length, std::unordered_map<std::string, std::vector<double> >* map,double pcount);\nstd::string seq_revcomp(std::string str);\nvoid GenomeMap(std::string *id, std::string *seq, long monoLen, std::string *mname, std::unordered_map<std::string, std::vector<double> >* map );\nvoid hashOut();\nvoid unCenterCorr();\n\n\n\ntemplate<class T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v){\n         copy(v.begin(), v.end(), std::ostream_iterator<T>(os, \" \"));\n         return os;\n}\n\nint main(int argc,   char * argv[]) {\n    \n    std::unordered_map<std::string, std::vector<double> > matrixmap[100];\n    int motif_len[100];\n    std::string names_motif[100];\n    double pseudo_count=0.00001;\n    int motif_counts=0;\n    char list_name[100],fasta_name[100];\n    int kmer_length, gap_length;\n    bool kmerflag=false ,outflag=false,corrflag=false, revcomflag=false;\n    \n    \n    boost::program_options::options_description desc(\"Allowed options:\");\n    desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"fasta\", boost::program_options::value<std::string>(), \"input sequence file\")\n    (\"list\", boost::program_options::value<std::string> (), \"specify a list of motifs\")\n    (\"motif\", boost::program_options::value<std::string>(), \"specify one motif file\")\n    (\"kmer,k\", boost::program_options::value<int>(&kmer_length)->default_value(8), \"specify the kmer length\")\n    (\"gap,g\", boost::program_options::value<int>(&gap_length)->default_value(0), \"specify the gap length\")\n    (\"kmerflag,f\", boost::program_options::bool_switch(&kmerflag), \"flag to switch to the kmer counting-score procedure\")\n    (\"revcomp,r\",boost::program_options::bool_switch(&revcomflag),\"reverse compliment sequence\")\n    (\"output,o\",boost::program_options::bool_switch(&outflag),\"output the kmer count-score\")\n    (\"corr,c\",boost::program_options::bool_switch(&corrflag),\"output the correlation score (un centered cosine)\")\n    ;\n    boost::program_options::variables_map vm;\n    boost::program_options::positional_options_description p;\n    p.add(\"fasta\",-1);\n    boost::program_options::store(boost::program_options::command_line_parser(argc,argv).options(desc).positional(p).run(), vm);\n    boost::program_options::notify(vm);\n    \n    if (vm.count(\"list\"))\n    {\n        const char* temx=vm[\"list\"].as<std::string >().c_str();\n        motif_counts= listParser(temx,names_motif, motif_len, matrixmap, pseudo_count);\n    }\n    if (vm.count(\"motif\")) {\n        const char* temname =vm[\"motif\"].as<std::string>().c_str();\n        motif_counts=1;\n        strcpy(list_name,temname);\n        names_motif[0]=(std::string) list_name;\n        Matrixfile(temname, matrixmap, pseudo_count);\n    }\n    if (vm.count(\"fasta\"))\n    {\n        const char * fastaname=vm[\"fasta\"].as<std::string>().c_str();\n        motif_len[0]=matrixmap[0].at(\"A\").size();\n        strcpy(fasta_name, fastaname );\n    }\n    if (vm.count(\"help\")) {\n        std::cout << \"Usage:\" << argv[0] << \" [options]\\n\";\n        std::cout << desc;\n        return 0;\n    }\n\n    \n\n// Load fasta sequence one by one;\n    gzFile fp;\n    kseq_t *seq;\n    int l;\n    fp=gzopen(fasta_name, \"r\");\n    seq=kseq_init(fp);\n    while((l=kseq_read(seq)) >=0){\n        std::string seqnametmp, seqtmp;\n        seqnametmp= &seq->name.s[0];\n        seqtmp= &seq->seq.s[0];\n        if(revcomflag)\n            seqtmp=seq_revcomp(seqtmp);\n        \n        for(int i=0;i < motif_counts ; i++){\n            if(kmerflag)\n                kmerizing(&seqnametmp, &seqtmp,kmer_length,gap_length,&names_motif[i], &matrixmap[i]);\n            else\n                GenomeMap(&seqnametmp, &seqtmp,motif_len[i],&names_motif[i], &matrixmap[i]);\n        }\n    }\n    kseq_destroy(seq);\n    gzclose(fp);\n    if(kmerflag && outflag)\n        hashOut();\n    if(kmerflag && corrflag)\n        unCenterCorr();\n\n    return 0;\n}\n\n//output the kmer count-score table\nvoid hashOut(){\n    for(auto it=kstore.begin(); it !=kstore.end(); it++)\n        std::cout<<it->first << \"\\t\" << it->second.count<< \"\\t\" << it->second.discore <<std::endl;\n//        std::cout<<it->first << \"\\t\" << it->second.count<< \"\\t\" << it->second.discore << \"\\t\" << it->second.monoscore <<std::endl;\n\n}\n\n// function to calculate the uncentred the correlation, cosine\nvoid unCenterCorr(){\n    double sumx,sumy, sumz, sumxz, sumxy;\n    for(auto it=kstore.begin(); it !=kstore.end(); it++){\n        sumx+=it->second.count * it->second.count;\n        sumy+=it->second.discore * it->second.discore ;\n        sumz+=it->second.monoscore * it->second.monoscore  ;\n        sumxy+= it->second.count * it->second.discore;\n        sumxz+= it->second.count * it->second.monoscore;\n    }\n//    std::cout << sumxy/sqrt(sumx *sumy)<< \"\\t\" << sumxz/sqrt(sumx *sumz) << std::endl;\n    std::cout << sumxy/sqrt(sumx *sumy)<< std::endl;\n}\n\n// function to score all the locus in the sequence\nvoid GenomeMap(std::string *id, std::string *seq, long monoLen, std::string *mname, std::unordered_map<std::string, std::vector<double> >* map ){\n    unsigned long slen =seq->size();\n    \n    std::transform(seq->begin(), seq->end(), seq->begin(),::toupper);\n    std::replace(seq->begin(),seq->end(),'T','U');\n    \n    for(long i=0; i < slen - monoLen +1 ; i++){\n        std::string subseq=seq->substr(i,monoLen);\n        if(subseq.find(\"N\") != std::string::npos)\n            continue;\n        double mscore=0,dscore=0,rc_mscore=0,rc_dscore=0;\n        std::string rc_subseq=seq_revcomp(subseq);\n        \n        mscore=singleStringScore(mscore, &subseq, 0, map);\n        dscore= pairStringScore(dscore, &subseq,0, map);\n        rc_mscore=singleStringScore(rc_mscore, &rc_subseq, 0,map);\n        rc_dscore=pairStringScore(rc_dscore,&rc_subseq,0,map);\n        std::cout << *id << \"\\t\"<< i << \"\\t\" << std::setprecision(5) <<mscore << std::fixed <<\":\"  << std::setprecision(5) <<dscore <<std::fixed << \"\\t+\\t\" << *mname <<std::endl;\n        std::cout << *id << \"\\t\"<< i << \"\\t\" << std::setprecision(5) <<rc_mscore <<std::fixed << \":\"  << std::setprecision(5) <<rc_dscore << std::fixed <<\"\\t-\\t\" <<*mname <<std::endl;\n    }    \n}\n\n// read the motif list\nint listParser(const char* list_name, std::string* names, int* length, std::unordered_map<std::string, std::vector<double> >* map,double pcount){\n    std::fstream motif_list;\n    char motif_file_name[100];\n    motif_list.open(list_name);\n    int motif_line=0;\n    \n    while( motif_list.getline( motif_file_name,100) ){\n        Matrixfile(motif_file_name, &map[motif_line],  pcount);\n//        std::cout << motif_file_name << std::endl;\n        length[motif_line]=(int) (map[motif_line])[\"A\"].size();\n        names[motif_line]=(std::string) motif_file_name;\n        ++motif_line;\n    }\n//    std::cout << motif_line << \" motifs loaded \\n\"<<std::endl;\n    return motif_line;\n}\n\n//process the matrix input\nvoid Matrixfile(const char* x, std::unordered_map<std::string, std::vector<double> > *y, double pseudo_count){\n    std::fstream file;\n    file.open(x);\n    \n    while(!file.is_open()){\n        std::cout << \"Something wrong with the filename\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    }\n    int line_count=0;\n    std::string iss;\n    while(getline(file, iss)){\n        line_count++;\n        if(line_count <=2){\n            continue;\n        }\n        else if(line_count >=3  and line_count <=18){\n            fetch_matrix(y, iss, 1, pseudo_count);\n        }\n        else if(line_count >=19 && line_count<=22){\n            fetch_matrix(y, iss, 2, pseudo_count);\n        }\n    }\n}\n\n//show the matrix and output or the screen\nvoid show_matrix(std::unordered_map<std::string, std::vector<double> > *x){\n    for(auto it=(*x).begin(); it !=(*x).end(); it++){\n        std::cout << it->first << \"\\t\";\n        std::vector<double> tem= it->second;\n        for( int i=0; i< tem.size(); ++i)\n            std::cout <<  \"\\t\" <<  tem[i];\n        std::cout << std::endl;\n    }\n}\nstd::string seq_revcomp(std::string str){\n    std::string rc_seq;\n    for(int i=str.size()-1; i>=0; --i){\n        rc_seq += (char) basemap[(int)str[i]];\n    }\n    return rc_seq;\n}\n\n//store the matrix into map table\nvoid fetch_matrix(std::unordered_map<std::string, std::vector<double> > *map, std::string str, int ind, double count){\n    std::vector<std::string> matrix;\n    std::stringstream ms(str);\n    std::string units;\n    while(ms >> units){\n        matrix.push_back(units);\n    }\n    unsigned long matrix_length_raw=matrix.size();\n    std::string base_name= matrix.back();\n    long matrix_length_new;\n    if(ind ==1){\n        base_name=base_name.substr(0,2);\n        matrix_length_new=matrix_length_raw-2;\n    }\n    else if(ind==2){\n        base_name=base_name.substr(14,1);\n        matrix_length_new=matrix_length_raw-1;\n    }\n    double new_matrix[matrix_length_new];\n    std::vector<double> hallo (new_matrix,new_matrix+ matrix_length_new);\n    for(int i=0; i< matrix_length_new; i++){\n        std::string::size_type sz;\n        hallo[i]= std::stod(matrix[i], &sz);\n        if(ind ==1)\n            hallo[i] = std::log2((hallo[i]+ count)/(0.0625 + count));\n        else\n            hallo[i] = std::log2((hallo[i]+ count)/(0.25+ count));\n    }\n    map->insert({base_name,hallo});\n//    return map;\n}\n\n//function to generate the kmer count-score table\nvoid kmerizing (std::string* id, std::string* seq,  int kmer, int gap, std::string* name, std::unordered_map<std::string, std::vector<double> > *map){\n    std::transform(seq->begin(), seq->end(), seq->begin(),::toupper);\n    std::replace(seq->begin(),seq->end(),'T','U');\n    unsigned long seq_length=seq->size();\n    int raw_kseq_len=kmer+gap;\n\n    for(unsigned long i=0; i < seq_length-raw_kseq_len +1; i++){\n        std::string subseq=seq->substr(i,raw_kseq_len);\n        if(subseq.find(\"N\") != std::string::npos)\n            continue;\n        \n        if(gap >0){\n            for (int ii=1; ii <kmer ;ii++){\n                double mscore,dscore;\n                mscore=monoscoring(subseq, map, gap,ii);\n                dscore=discoring(subseq, map, gap,ii);\n                std::string tem=subseq;\n                tem.replace(ii,gap, gap, '-' );\n\n                if(kstore.find(tem) != kstore.end()){\n                    kstore[tem].count +=1;\n                }\n                else\n                    kstore.insert({tem,{1,dscore,mscore}});\n            }\n        }\n        else{\n            double mscore,dscore,rc_mscore, rc_dscore;\n            //         std::string rc_subseq=seq_revcomp(subseq);\n            mscore=monoscoring(subseq, map, 0,0);\n            dscore=discoring(subseq, map, 0,0);\n            std::string tem=subseq;\n            \n            if(kstore.find(tem) != kstore.end()){\n                kstore[tem].count +=1;\n            }\n            else\n                kstore.insert({tem,{1,dscore,mscore}});\n        }\n\n\n//        double mscore,dscore,rc_mscore,rc_dscore;\n//        std::string rc_subseq=seq_revcomp(subseq);\n//        mscore=monoscoring(subseq, map, 0,0);\n//        dscore=discoring(subseq, map, 0,0);\n//\n//        rc_mscore=monoscoring(rc_subseq, map, 0,0);\n//        rc_dscore=discoring(rc_subseq, map, 0,0);\n//        std::cout << *id << \"\\t\"<< i << \"\\t\" << std::setprecision(5) <<mscore << std::fixed <<\":\"  << std::setprecision(5) <<dscore <<std::fixed << \"\\t+\\t\" << *name <<std::endl;\n//        std::cout << *id << \"\\t\"<< i << \"\\t\" << std::setprecision(5) <<rc_mscore <<std::fixed << \":\"  << std::setprecision(5) <<rc_dscore << std::fixed <<\"\\t-\\t\" <<*name <<std::endl;\n//\n    }\n}\n\n// The scoring function using the linear model only, which has considered all the conditions\ndouble monoscoring(std::string subseq, std::unordered_map<std::string, std::vector<double> > *map, int gap_len, int gap_pos){\n    long monoLen=(*map)[\"A\"].size();\n    if(gap_len >0)\n        subseq.replace(gap_pos,gap_len, gap_len, '-' );\n    \n    long kseq_prime_len= subseq.size();\n    long cycle=kseq_prime_len+ monoLen;\n    std::string valid_seq;\n    double maximum_score=-1000;\n    for(int p=0; p < cycle -1 ; p++){\n        long pos;\n        double score=0;\n        if(p <kseq_prime_len-1){\n            if(monoLen >= kseq_prime_len){\n                valid_seq=subseq.substr(kseq_prime_len-(p+1),p+1);\n                pos=0;\n            }\n            else if(monoLen < kseq_prime_len){\n                pos=0;\n                if(p <monoLen -1)\n                    valid_seq=subseq.substr(kseq_prime_len-(p+1));\n                else\n                    valid_seq=subseq.substr(kseq_prime_len-(p+1),monoLen);\n            }\n        }\n        else if(p >=kseq_prime_len -1){\n            if(monoLen >=kseq_prime_len){\n                pos=p+1-kseq_prime_len;\n                if(p <monoLen-1)\n                    valid_seq=subseq;\n                else\n                    valid_seq=subseq.substr(0,kseq_prime_len+monoLen-p-1);\n                }\n            else{\n                valid_seq=subseq.substr(0,kseq_prime_len-(p-monoLen) -1);\n                pos=p+1-kseq_prime_len;\n            }\n        }\n        score= singleStringScore(score, &valid_seq, pos, map);\n        maximum_score=(score>maximum_score)?score:maximum_score;\n    }\n    return maximum_score ;\n}\n// The scoring function for the dependency matrix\ndouble discoring(std::string subseq, std::unordered_map<std::string, std::vector<double> > *map, int gap_len, int gap_pos){\n    if(gap_len >0)\n        subseq.replace(gap_pos,gap_len,gap_len,'-');\n    long monoLen=(*map)[\"A\"].size();\n    long kseq_prime_len=subseq.size();\n    double maximum_score=-1000;\n    if(monoLen %2 ==0){ //matrix length is even\n        for(int p=0; p < monoLen + kseq_prime_len -1; p++){\n            std::string subs;\n            double score=0;\n            long pos;\n            if( p< monoLen/2){\n                if( p < kseq_prime_len-1){\n                    subs=subseq.substr(kseq_prime_len-1-p,p+1); //for kmers longer than the 1/2 matrix length\n                    pos=0;\n                }\n                else if(p >=kseq_prime_len-1){  //for kmers shorter than the 1/2 marix length\n                    subs=subseq;\n                    pos=p-kseq_prime_len+1;\n                }\n                score= singleStringScore(score, &subs, pos, map);\n                maximum_score=(score > maximum_score)?score:maximum_score;\n            }\n            else if(p >= monoLen/2   && (p - monoLen/2 < kseq_prime_len -1)){\n                std::string left_seq; // leftover from the kmer which has been cut for dinucleotide matrix\n                long single_pos;\n                if(kseq_prime_len <= monoLen && kseq_prime_len >= 0.5 * monoLen){\n                    if(2*(p-(monoLen/2 -1)) <=kseq_prime_len){\n                        subs=subseq.substr(kseq_prime_len-2*(p-(monoLen/2 -1)),2*(p-(monoLen/2 -1)));\n                        single_pos=p+1-subs.size();\n                        if(p+1 >= kseq_prime_len){\n                            pos=p+1-kseq_prime_len;\n                            left_seq=subseq.substr(0,kseq_prime_len-2*(p-(monoLen/2-1))); //if($kseq_prime_len-2*($p-($mono_len/2 -1)) > 0);\n                        }\n                        else{\n                            pos=0;\n                            left_seq=subseq.substr(kseq_prime_len-(p+1),p+1-2*(p-(monoLen/2-1)));\n                        }\n                    }\n                    else{\n                        subs=subseq.substr(0,2*(kseq_prime_len-(p+1-(monoLen-1)/2 )+1) );\n                        pos=p-kseq_prime_len+1+subs.size();\n                        single_pos=p+1-kseq_prime_len;\n                        if(p >= monoLen  ){\n                            std::string left_seq_pre=subseq.substr(2*(kseq_prime_len-(p-(monoLen/2-1))));\n                            left_seq=left_seq_pre.substr(0,kseq_prime_len-(p+1-monoLen)-subs.size());\n                        }\n                        else\n                            left_seq=subseq.substr(2*(kseq_prime_len-(p-(monoLen/2 -1))));\n                    }\n//                    std::cout << subseq<< \"\\t\" << subs << \"\\t\" << single_pos << \"\\t\" << pos << std::endl;\n                }\n                else if(kseq_prime_len > monoLen){\n                    std::string left_seq_pre;\n                    if(p < monoLen-1){\n                        subs=subseq.substr(kseq_prime_len-2*(p-(monoLen/2 -1)),2*(p-(monoLen/2 -1)));\n                        if(2*(p-(monoLen/2 -1)) <kseq_prime_len)\n                            left_seq_pre =subseq.substr(0,kseq_prime_len-2*(p-(monoLen/2 -1)));\n                        left_seq=left_seq_pre.substr(kseq_prime_len - (p+1));\n                        pos=0;\n                        single_pos=p+1-subs.size();\n                    }\n                    else if( p >= monoLen-1 && p <= kseq_prime_len-1){\n                        subs=subseq.substr(kseq_prime_len-(p+1),monoLen);\n                        pos=0;\n                        single_pos=0;\n                        \n                    }\n                    else if(p > kseq_prime_len -1){\n                        subs=subseq.substr(0,2*(kseq_prime_len-(p-(monoLen/2 -1))));\n                        left_seq_pre=subseq.substr(2*(kseq_prime_len-(p-(monoLen/2 -1))));\n                        left_seq=left_seq_pre.substr(0, left_seq_pre.size()-(p+1-monoLen));\n                        pos=p-kseq_prime_len+1+subs.size();\n                        single_pos=p+1-kseq_prime_len;\n                    }\n//                    std::cout << subseq<< \"\\t\" << subs << \"\\t\" << single_pos << \"\\t\" << pos << std::endl;\n                }\n                else if(kseq_prime_len <  0.5 * monoLen){\n                    if(2*(p-(monoLen/2 -1)) <=kseq_prime_len){\n                        subs=subseq.substr(kseq_prime_len-2*(p-(monoLen/2 -1)),2*(p-(monoLen/2 -1)));\n                        pos=p+1-kseq_prime_len;\n                        left_seq=subseq.substr(0,kseq_prime_len-2*(p-(monoLen/2 -1)));\n                        single_pos=p+1-subs.size();\n\n                    }\n                    else{\n                        subs=subseq.substr(0,2*(kseq_prime_len-(p-(monoLen/2 -1))));\n                        pos=p-kseq_prime_len+1+subs.size();\n                        left_seq=subseq.substr(2*(kseq_prime_len-(p-(monoLen/2 -1))));\n                        single_pos=p+1-kseq_prime_len;\n                    }\n                }\n\n                score=pairStringScore(score,&subs,single_pos,map);\n//                std::cout << subseq<< \"\\t\" << subs << \"\\t\" << single_pos << \"\\t\" << pos << std::endl;\n\n                if(!left_seq.empty())\n                    score= singleStringScore(score, &left_seq, pos, map);\n                maximum_score=(score > maximum_score)?score:maximum_score;\n            }\n            else if(p >= monoLen/2 + kseq_prime_len -1){\n                if(p <monoLen){\n                    subs=subseq;\n                    pos=p+1-kseq_prime_len;\n                }\n                else if(p >= monoLen){\n                    subs=subseq.substr(0,kseq_prime_len-(p-monoLen)-1);\n                    pos=p+1-kseq_prime_len;\n                }\n                score= singleStringScore(score, &subs, pos, map);\n                maximum_score=(score > maximum_score)?score:maximum_score;\n            }\n        }\n    }\n    else{\n        for(int p=0; p < monoLen + kseq_prime_len -1; p++){\n            std::string subs;\n            double score=0;\n            long pos;\n            if( p < (monoLen-1)/2){\n                if(p < kseq_prime_len-1){\n                    subs=subseq.substr(kseq_prime_len-1-p,p+1); // for kmers longer than the 1/2 matrix length\n                    pos=0;\n                }\n                else if(p >=kseq_prime_len-1){  //for kmers shorter than the 1/2marix length\n                    subs=subseq;\n                    pos=p-kseq_prime_len+1;\n                }\n                score= singleStringScore(score, &subs, pos, map);\n                maximum_score=(score > maximum_score)?score:maximum_score;\n            }\n            else if(p >= (monoLen-1)/2  && (p - (monoLen-1)/2 <= kseq_prime_len -1)){\n                std::string left_seq;\n                long single_pos;\n                if(kseq_prime_len <= monoLen && kseq_prime_len >= 0.5 * (monoLen-1)){\n                    if(2*(p-(monoLen-1)/2 ) <=kseq_prime_len-1){\n                        subs=subseq.substr(kseq_prime_len-2*(p+1-(monoLen-1)/2)+1,2*(p+1-(monoLen-1)/2)-1);\n                        single_pos=p+1-subs.size();\n                        pos=0;\n                        if(p+1 >= kseq_prime_len){\n                            pos=p+1-kseq_prime_len;\n                            left_seq=subseq.substr(0,kseq_prime_len-2*(p-(monoLen-1)/2)-1); //if($kseq_prime_len-2*($    p-($mono_len/2 -1)) > 0);\n                        }\n                        else{\n                            pos=0;\n                            left_seq=subseq.substr(kseq_prime_len-(p+1),p+1-2*(p-(monoLen-1)/2)-1);\n                        }\n                    }\n                    else{\n                        subs=subseq.substr(0,2*(kseq_prime_len-(p+1-(monoLen-1)/2 ))+1);\n                        pos= p-kseq_prime_len+1+subs.size();\n                        single_pos=p+1-kseq_prime_len;\n                        if(p >= monoLen){\n                            std::string left_seq_pre=subseq.substr(2*(kseq_prime_len-(p+1-(monoLen-1)/2))+1);\n                            left_seq=left_seq_pre.substr(0,kseq_prime_len-(p+1-monoLen)-subs.size());\n                        }\n                        else{\n                            left_seq=subseq.substr(2*(kseq_prime_len-(p+1-(monoLen-1)/2))+1);\n                        }\n                    }\n                }\n                else if( kseq_prime_len > monoLen){\n                    std::string left_seq_pre;\n                    if(p < monoLen-1){\n                        subs=subseq.substr(kseq_prime_len-2*(p+1-(monoLen-1)/2)+1,2*(p+1-(monoLen-1)/2)+1);\n                        if(2*(p-(monoLen/2 -1)) < kseq_prime_len)\n                            left_seq_pre=subseq.substr(0,kseq_prime_len-2*(p+1-(monoLen-1)/2)+1);\n                        left_seq=left_seq_pre.substr(kseq_prime_len - (p+1));\n                        pos=0;\n                        single_pos=p+1-subs.size();\n                        }\n                    else if( p >= monoLen-1 && p <= kseq_prime_len-1){\n                        subs=subseq.substr(kseq_prime_len-(p+1),monoLen);\n                        pos=0;\n                        single_pos=0;\n                        }\n                    else if(p > kseq_prime_len -1){\n                        subs=subseq.substr(0,2*(kseq_prime_len-(p+1-(monoLen-1)/2 ))+1);\n                        left_seq_pre=subseq.substr(2*(kseq_prime_len-(p+1-(monoLen-1)/2 ))+1);\n                        left_seq=left_seq_pre.substr(0, left_seq_pre.size()-(p+1-monoLen));\n                        pos=p-kseq_prime_len+1+subs.size();\n                        single_pos=p+1-kseq_prime_len;\n                    }\n                }\n                else if(kseq_prime_len <  0.5 * (monoLen-1)){\n                    if(2*(p-(monoLen-1)/2 ) <=kseq_prime_len-1){\n                        subs=subseq.substr(kseq_prime_len-2*(p+1-(monoLen-1)/2)+1,2*(p+1-(monoLen-1)/2)+1);\n                        pos=p+1-kseq_prime_len;\n                        left_seq=subseq.substr(0,kseq_prime_len-2*(p-(monoLen-1)/2)-1);\n                        single_pos=p+1-subs.size();\n                    }\n                    else{\n                        subs=subseq.substr(0,2*(kseq_prime_len-(p+1-(monoLen-1)/2))+1);\n                        pos= p-kseq_prime_len+1+ subs.size();\n                        left_seq=subseq.substr(2*(kseq_prime_len-(p+1-(monoLen-1)/2))+1);\n                        single_pos=p+1-kseq_prime_len;\n                    }\n                }\n                score=pairStringScore(score,&subs,single_pos,map);\n                if(!left_seq.empty())\n                    score= singleStringScore(score, &left_seq, pos, map);\n                maximum_score=(score > maximum_score)?score:maximum_score;\n            }\n            else if(p >= (monoLen-1)/2 +kseq_prime_len -1){\n                if(p <monoLen){\n                    subs=subseq;\n                    pos=p+1-kseq_prime_len;\n                    }\n                else if(p >= monoLen){\n                    subs=subseq.substr(0,kseq_prime_len-(p-monoLen)-1);\n                    pos=p+1-kseq_prime_len;\n                }\n                score= singleStringScore(score, &subs, pos, map);\n                maximum_score=(score > maximum_score )?score:maximum_score;\n            }\n        }\n    }\n    return maximum_score;\n}\n//sub-routines for the dangling sequence\ninline double singleStringScore(double x, std::string* s, long p, std::unordered_map<std::string, std::vector<double> > *m){\n    for(int j=0; j<s->size(); j++){\n        std::string letter=s->substr(j,1);\n        if(letter == \"-\")\n            continue;\n        x+= (*m)[letter][p+j];\n    }\n    return x;\n}\n//sub-routines for the paired sequence\ninline double pairStringScore(double x, std::string * s, long sp, std::unordered_map<std::string,std::vector<double> > *m){\n    long subs_len=s->size();\n    long diLen=(*m)[\"AA\"].size();\n    int half_subs_len;\n    if(subs_len %2==0)\n        half_subs_len=0.5* subs_len ;\n    else\n        half_subs_len=0.5* (subs_len-1) ;\n    \n    for (int j=0; j <= half_subs_len -1 ; j++){\n        std::string letterA=s->substr(j,1);\n        std::string letterB=s->substr(subs_len-j-1,1);\n        std::string letter;\n\n        if(letterA ==\"-\" && letterB==\"-\")\n            continue;\n        else if(letterA ==\"-\" ||letterB==\"-\"){\n            long spos;\n            if(letterB==\"-\"){\n                spos=sp +j ;\n                letter=letterA;\n            }//#letterA is not gap so use the postion from the subs' beginning\n            else if(letterA==\"-\"){\n                spos=sp+(subs_len-1)-j; //#B is not gap, so from the end of subs\n                letter=letterB;\n            }\n            x+=(*m)[letter][spos];\n        }\n        else{\n            letter=letterA+letterB;\n//            std::cout << *s << \"\\t\" << letter  << \"\\t\" << diLen-half_subs_len+j<< std::endl;\n            x+=(*m)[letter][diLen-half_subs_len+j];\n        }\n    }\n    return x;\n}\n\n\n\n", "meta": {"hexsha": "f6c00cf8b848a561d8ada4ce1375ca87d7befdb3", "size": 30345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "zhjilin/rmap", "max_stars_repo_head_hexsha": "44dd7e336303181c53733a3fa30cdd274c08fa5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-27T06:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-06T22:14:40.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "zhjilin/rmap", "max_issues_repo_head_hexsha": "44dd7e336303181c53733a3fa30cdd274c08fa5d", "max_issues_repo_licenses": ["MIT"], "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": "zhjilin/rmap", "max_forks_repo_head_hexsha": "44dd7e336303181c53733a3fa30cdd274c08fa5d", "max_forks_repo_licenses": ["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.1036931818, "max_line_length": 184, "alphanum_fraction": 0.5074971165, "num_tokens": 8549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.19954526699110245}}
{"text": "/*\n\nCopyright (c) 2005-2021, 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\n#ifndef EXTENDEDBIDOMAINTISSUE_HPP_\n#define EXTENDEDBIDOMAINTISSUE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include <vector>\n#include \"UblasMatrixInclude.hpp\"\n\n#include \"AbstractStimulusFunction.hpp\"\n#include \"AbstractStimulusFactory.hpp\"\n#include \"AbstractConductivityTensors.hpp\"\n\n#include \"AbstractCardiacTissue.hpp\"\n\n/**\n * Class that provides functionalities to specify a tissue within the context of the extended bidomain framework.\n *\n * The extended bidomain equations are of the form:\n *\n *  - div ( sigma_i1 grad Phi_1 ) + Am1*Cm1*d(phi_1)/dt - Am2*Cm2*d(phi_e)/dt + Am1*I_ion1 - Am1*I_stim1 + Amgap*G_gap*(phi_1 - phi_2)\n *  - div ( sigma_i2 grad Phi_2 ) + Am2*Cm2*d(phi_2)/dt - Am2*Cm2*d(phi_e)/dt + Am2*I_ion2 - Am2*I_stim2 - Amgap*G_gap*(phi_1 - phi_2)\n *   div ( sigma_e grad Phi_e ) + div ( sigma_i1 grad Phi_1 ) + div ( sigma_i2 grad Phi_2 )  = I_stim\n *\n *   The unknowns are:\n *\n *   - Phi_1 (intracellular potential of the first cell).\n *   - Phi_2 (intracellular potential of the second cell).\n *   - Phi_e (extracellular potential).\n *\n *   Am1, Am2 and Amgap are surface-to-volume ratios for first cell, second cell and gap junction. User can set their values.\n *   Cm1 and cm2 are capaciatnce values of first and second cell respectively\n *   sigma_i1 and sigma_i2 are intracellular conductivity tensors of first and second cell respectively\n *   sigma_e is the conductivity tensor for the extracellular space\n *   G_gap is the conductance (in ms/cm2) of the gap junction channel.\n *\n *\n *\n */\ntemplate <unsigned SPACE_DIM>\nclass ExtendedBidomainTissue : public virtual AbstractCardiacTissue<SPACE_DIM>\n{\nprivate:\n    friend class TestExtendedBidomainTissue; // for testing.\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the member variables.\n     *\n     * @param archive\n     * @param version\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & boost::serialization::base_object<AbstractCardiacTissue<SPACE_DIM> >(*this);\n        // Conductivity tensors are dealt with by HeartConfig, and the caches get regenerated.\n\n        archive & mAmFirstCell;\n        archive & mAmSecondCell;\n        archive & mAmGap;\n        archive & mCmFirstCell;\n        archive & mCmSecondCell;\n        archive & mGGap;\n        archive & mUserSuppliedExtracellularStimulus;\n    }\n\n    /** Intracellular conductivity tensors for the second cell.*/\n    AbstractConductivityTensors<SPACE_DIM, SPACE_DIM> *mpIntracellularConductivityTensorsSecondCell;\n\n    /**\n     * Stores the values of the conductivities for the second cell. Accessible via get and set methods. The problem class will set it\n     * This variable is a convenient interface for other classes. It is used to fill in mpIntracellularConductivityTensorsSecondCell.\n     */\n    c_vector<double, SPACE_DIM>  mIntracellularConductivitiesSecondCell;\n\n\n    /** Extracellular conductivity tensors. */\n    AbstractConductivityTensors<SPACE_DIM, SPACE_DIM> *mpExtracellularConductivityTensors;\n\n    /**\n     *  Cache containing all the stimulus currents for each node,\n     *  replicated over all processes.\n     */\n    ReplicatableVector mExtracellularStimulusCacheReplicated;\n\n    /**\n     *  Cache containing all the stimulus currents for each node,\n     *  replicated over all processes.\n     */\n    ReplicatableVector mGgapCacheReplicated;\n\n    /**\n     *  Cache containing all the ionic currents for each node for the seconed cell,\n     *  replicated over all processes.\n     */\n    ReplicatableVector mIionicCacheReplicatedSecondCell;\n\n    /**\n     *  Cache containing all the stimulus currents for each node for the second cell,\n     *  replicated over all processes.\n     */\n    ReplicatableVector mIntracellularStimulusCacheReplicatedSecondCell;\n\n    /** The vector of cells (the second one). Distributed. */\n    std::vector< AbstractCardiacCellInterface* > mCellsDistributedSecondCell;\n\n    /** The vector of stimuli for the extracellular stimulus. Distributed. */\n    std::vector<boost::shared_ptr<AbstractStimulusFunction> > mExtracellularStimuliDistributed;\n\n    /** The vector of gap junction conductances. Distributed*/\n    std::vector<double> mGgapDistributed;\n\n    /**the Am for the first cell, set by the problem class and picked up by the assembler*/\n    double mAmFirstCell;\n    /**the Am for the second cell, set by the problem class and picked up by the assembler*/\n    double mAmSecondCell;\n    /**the Am for the gap junction, set by the problem class and picked up by the assembler*/\n    double mAmGap;\n    /**the Cm for the first cell, set by the problem class and picked up by the assembler*/\n    double mCmFirstCell;\n    /**the Cm for the second cell, set by the problem class and picked up by the assembler*/\n    double mCmSecondCell;\n    /**the conductance of the gap junction, in mS/cm2. Set by the problem class and picked up by the assembler*/\n    double mGGap;\n\n    /**\n     * Whether the extracellular stimulus that is passed in was supplied by the user or not\n     * (it could be the default zero implementation). Initialise to false (user did not pass in anything).\n     */\n    bool mUserSuppliedExtracellularStimulus;\n\n    /**\n     * Convenience method for extracellular conductivity tensors creation\n     */\n    void CreateExtracellularConductivityTensors();\n\n    /**\n     * The parent class AbstractCardiacTissue has a method UpdateCaches that updates some caches of general use.\n     * This method updates more caches that are specific to extended bidomain problems, namely:\n     *\n     * - Iionic and intracellular stimulus for the second cell\n     * - Extracellular stimulus\n     * - Gap junction conductivities (Ggap)\n     *\n     * It is typically called right after the UpdateCaches method in the parent class.\n     *\n     * @param globalIndex  global index of the entry to update\n     * @param localIndex  local index of the entry to update\n     * @param nextTime  the next PDE time point, at which to evaluate the stimulus current\n     */\n    void UpdateAdditionalCaches(unsigned globalIndex, unsigned localIndex, double nextTime);\n\n    /**\n     * The parent class AbstractCardiacTissue has a method ReplicateCaches that replicates some caches of general use.\n     * This method replicates more caches that are specific to extended bidomain problems, namely:\n     *\n     * - Iionic and intracellular stimulus for the second cell\n     * - Extracellular stimulus\n     * - Gap junction conductivities (Ggap)\n     *\n     * It is typically called right after the ReplicateCaches method in the parent class.\n     */\n    void ReplicateAdditionalCaches();\n\n    /** vector of regions for Ggap heterogeneities*/\n    std::vector<boost::shared_ptr<AbstractChasteRegion<SPACE_DIM> > > mGgapHeterogeneityRegions;\n    /**values of heterogeneous Ggaps corresponding to mGgapHeterogeneityRegions. This has the same size as mGgapHeterogeneityRegions*/\n    std::vector<double> mGgapValues;\n\npublic:\n\n    /**\n     * Constructor sets up extracellular conductivity tensors.\n     * @param pCellFactory factory to pass on to the base class constructor\n     * @param pCellFactorySecondCell factory to pass on to the base class constructor for the second cell\n     * @param pExtracellularStimulusFactory factory for creating extracellular stimuli\n     */\n    ExtendedBidomainTissue(AbstractCardiacCellFactory<SPACE_DIM>* pCellFactory, AbstractCardiacCellFactory<SPACE_DIM>* pCellFactorySecondCell, AbstractStimulusFactory<SPACE_DIM>* pExtracellularStimulusFactory);\n\n    /**\n     *  Archiving constructor\n     * @param rCellsDistributed  local cell models (recovered from archive)\n     * @param rSecondCellsDistributed  local cell models for second cells (recovered from archive)\n     * @param rExtraStimuliDistributed local extracellular stimuli (recovered from archive)\n     * @param rGgapsDistributed distributed Ggaps (recovered from archive)\n     * @param pMesh  a pointer to the AbstractTetrahedral mesh (recovered from archive).\n     * @param intracellularConductivitiesSecondCell a vector with the orthotropic conductivities for the second cell (this is needed because the second cell values may not be taken from HeartConfig as the the ones for the first cell are).\n     */\n    ExtendedBidomainTissue(std::vector<AbstractCardiacCellInterface*> & rCellsDistributed,\n                           std::vector<AbstractCardiacCellInterface*> & rSecondCellsDistributed,\n                           std::vector<boost::shared_ptr<AbstractStimulusFunction> > & rExtraStimuliDistributed,\n                           std::vector<double>& rGgapsDistributed,\n                           AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>* pMesh,\n                           c_vector<double, SPACE_DIM>  intracellularConductivitiesSecondCell);\n\n    /**\n     * Destructor\n     */\n    virtual ~ExtendedBidomainTissue();\n\n    /**\n     * Sets the value of the conductivities for the second cell.\n     *\n     * @param conductivities the conductivities to be set.\n     */\n    void SetIntracellularConductivitiesSecondCell(c_vector<double, SPACE_DIM> conductivities);\n\n    /**\n     * @return a pointer to the second cell\n     *\n     * @param globalIndex the global index in the mesh\n     */\n    AbstractCardiacCellInterface* GetCardiacSecondCell( unsigned globalIndex );\n\n\n    /**\n     * @return a pointer to the extracellular stimulus. Useful for testing\n     *\n     * @param globalIndex the global index in the mesh\n     */\n    boost::shared_ptr<AbstractStimulusFunction> GetExtracellularStimulus( unsigned globalIndex );\n\n    /**\n     *  @return a reference to the vector of distributed cells (second cell). Needed for archiving.\n     */\n    const std::vector<AbstractCardiacCellInterface*>& rGetSecondCellsDistributed() const;\n\n    /**\n     *  @return a reference to the vector of distributed values of Ggaps. Needed for archiving.\n     */\n    const std::vector<double>& rGetGapsDistributed() const;\n\n\n    /**\n     *  @return a reference to the vector of distributed extracellular stimuli. Needed for archiving.\n     */\n    const std::vector<boost::shared_ptr<AbstractStimulusFunction> >& rGetExtracellularStimulusDistributed() const;\n\n\n    /**\n     * @return the intracellular conductivities of the second cell\n     */\n    c_vector<double, SPACE_DIM> GetIntracellularConductivitiesSecondCell() const;\n\n    /**\n     * Integrate the cell ODEs and update ionic current etc for each of the\n     * cells, between the two times provided. This is a re-implementation from the version in the base class.\n     *\n     * @param existingSolution  the current voltage solution vector\n     * @param time  the current simulation time\n     * @param nextTime  when to simulate the cells until\n     * @param updateVoltage (unused here)\n     */\n    virtual void SolveCellSystems(Vec existingSolution, double time, double nextTime, bool updateVoltage = false);\n\n    /**\n     * Convenience method for intracellular conductivity tensors creation for the second cell\n     */\n    void CreateIntracellularConductivityTensorSecondCell();\n\n    /**\n     *  Set the values of mCellHeterogeneityRegions and mGgapValues for the heterogeneities of Ggap.\n     *\n     *  @param rGgapHeterogeneityRegions a vector of (pointers to) heterogeneity regions for gap junctions\n     *  @param rGgapValues a vector (of the same size as rGgapHeterogeneityRegions) with the respective values of Ggap for every region.\n     */\n    void SetGgapHeterogeneities ( std::vector<boost::shared_ptr<AbstractChasteRegion<SPACE_DIM> > > & rGgapHeterogeneityRegions, std::vector<double> rGgapValues);\n\n    /**\n     * Create the pattern of Ggap across the mesh based upon mCellHeterogeneityRegions, mGgapValues and mGgap. This will fill in mGgapDistributed.\n     * It will set mGgap everywhere except in  the areas mCellHeterogeneityRegions[i] where it will put mGgapValues[i] instead.\n     * If mCellHeterogeneityRegions (and mGgapValues) are empty, mGgap will be set everywhere.\n     */\n    void CreateGGapConductivities();\n\n    /**\n     * @return the extracellular conductivity tensor for the given element\n     * @param elementIndex  index of the element of interest\n     */\n     const c_matrix<double, SPACE_DIM, SPACE_DIM>& rGetExtracellularConductivityTensor(unsigned elementIndex);\n\n     /**\n      * @return the intracellular conductivity tensor for the given element for tehs econd cell\n      * @param elementIndex  index of the element of interest\n      */\n      const c_matrix<double, SPACE_DIM, SPACE_DIM>& rGetIntracellularConductivityTensorSecondCell(unsigned elementIndex);\n\n\n     /** @return the entire ionic current cache for the second cell*/\n     ReplicatableVector& rGetIionicCacheReplicatedSecondCell();\n\n     /** @return the entire stimulus current cache for the second cell*/\n     ReplicatableVector& rGetIntracellularStimulusCacheReplicatedSecondCell();\n\n     /** @return the extracellular stimulus*/\n     ReplicatableVector& rGetExtracellularStimulusCacheReplicated();\n\n     /** @return the values of ggap*/\n     ReplicatableVector& rGetGgapCacheReplicated();\n\n     /**\n      * @return Am for the first cell\n      */\n     double GetAmFirstCell();\n\n     /**\n      * @return Am for the second cell\n      */\n     double GetAmSecondCell();\n\n     /**\n      * @return Am for the gap junction\n      */\n     double GetAmGap();\n\n     /**\n      * @return Cm for the first cell\n      */\n     double GetCmFirstCell();\n\n     /**\n      * @return Cm for the second cell\n      */\n     double GetCmSecondCell();\n\n     /**\n      *  @return the conducatnce of the gap junction (mGGap)\n      */\n     double GetGGap();\n\n     /**\n      * @param value Am for the first cell\n      */\n     void SetAmFirstCell(double value);\n\n     /**\n      * @param value Am for the second cell\n      */\n     void SetAmSecondCell(double value);\n\n     /**\n      * @param value Am for the gap junction\n      */\n     void SetAmGap(double value);\n\n     /**\n      * @param value Cm for the first cell\n      */\n     void SetCmFirstCell(double value);\n\n     /**\n      * @param value Cm for the first cell\n      */\n     void SetCmSecondCell(double value);\n\n     /**\n      * @param value conductance, in mS of the gap junction\n      */\n     void SetGGap(double value);\n\n     /**\n      * This method gives access to the member variable mUserSuppliedExtracellularStimulus,\n      * which is false by default but turned true if the user supplies an extracellular stimulus\n      * in any form.\n      *\n      * @return true if the user supplied an extracellular stimulus.\n      */\n     bool HasTheUserSuppliedExtracellularStimulus();\n\n     /**\n      * This method allows modifications of the  mUserSuppliedExtracellularStimulus flag (false by default).\n      * Other classes (e.g., Problem classes) can use this method to tell the Tissue that the user\n      * specified an extracellular stimulus.\n      *\n      * @param flag ; true if you want to tell the Tissue object that the user supplied an extracellular stimulus explicitly\n      */\n     void SetUserSuppliedExtracellularStimulus(bool flag);\n\n\n     /**\n      * This method is the equivalent of SaveCardiacCells in the abstract class but save both cells of the extended bidomain tissue\n      *\n      * @param archive  the master archive; cells will actually be written to the process-specific archive.\n      * @param version\n      */\n     template<class Archive>\n     void SaveExtendedBidomainCells(Archive & archive, const unsigned int version) const\n     {\n         Archive& r_archive = *ProcessSpecificArchive<Archive>::Get();\n         const std::vector<AbstractCardiacCellInterface*> & r_cells_distributed = this->rGetCellsDistributed();\n         const std::vector<AbstractCardiacCellInterface*> & r_cells_distributed_second_cell = rGetSecondCellsDistributed();\n         const std::vector<double> & r_ggaps_distributed = rGetGapsDistributed();\n\n         r_archive & this->mpDistributedVectorFactory; // Needed when loading\n         const unsigned num_cells = r_cells_distributed.size();\n         r_archive & num_cells;\n         for (unsigned i=0; i<num_cells; i++)\n         {\n             AbstractDynamicallyLoadableEntity* p_entity = dynamic_cast<AbstractDynamicallyLoadableEntity*>(r_cells_distributed[i]);\n             bool is_dynamic = (p_entity != NULL);\n             r_archive & is_dynamic;\n             if (is_dynamic)\n             {\n #ifdef CHASTE_CAN_CHECKPOINT_DLLS\n                 ///\\todo Dynamically loaded cell models aren't saved to archive in extended Bidomain\n                 NEVER_REACHED;\n                 //r_archive & p_entity->GetLoader()->GetLoadableModulePath();\n #else\n                 // We should have thrown an exception before this point\n                 NEVER_REACHED;\n #endif // CHASTE_CAN_CHECKPOINT_DLLS\n             }\n             r_archive & r_cells_distributed[i];\n             r_archive & r_cells_distributed_second_cell[i];\n             r_archive & r_ggaps_distributed[i];\n         }\n     }\n\n     /**\n      * Load our tissue from an archive. This is the equivalent of LoadCardiacCells in the abstract class.\n      * it loads the two cells instead of only one.\n      *\n      * Handles the checkpoint migration case, deleting loaded cells immediately if they are\n      * not local to this process.\n      *\n      * @param archive  the process-specific archive to load from\n      * @param version  archive version\n      * @param rCells  vector to fill in with pointers to local cells\n      * @param rSecondCells vector to fill in with pointers to the second cells\n      * @param rGgaps vector of values of gap junctions\n      * @param pMesh  the mesh, so we can get at the node permutation, if any\n      */\n     template<class Archive>\n     static void LoadExtendedBidomainCells(Archive & archive, const unsigned int version,\n                                  std::vector<AbstractCardiacCellInterface*>& rCells,\n                                  std::vector<AbstractCardiacCellInterface*>& rSecondCells,\n                                  std::vector<double>& rGgaps,\n                                  AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>* pMesh)\n     {\n         assert(pMesh!=NULL);\n         DistributedVectorFactory* p_factory;\n         archive & p_factory;\n         unsigned num_cells;\n         archive & num_cells;\n         rCells.resize(p_factory->GetLocalOwnership());\n         rSecondCells.resize(p_factory->GetLocalOwnership());\n         rGgaps.resize(p_factory->GetLocalOwnership());\n #ifndef NDEBUG\n         // Paranoia\n         assert(rCells.size() == rSecondCells.size());\n         for (unsigned i=0; i<rCells.size(); i++)\n         {\n             assert(rCells[i] == NULL);\n             assert(rSecondCells[i] == NULL);\n         }\n #endif\n\n         // We don't store a cell index in the archive, so need to work out what global\n         // index this tissue starts up.  If we're migrating (so have an\n         // original factory) we use the original low index; otherwise we use the current\n         // low index.\n         unsigned index_low = p_factory->GetOriginalFactory() ? p_factory->GetOriginalFactory()->GetLow() : p_factory->GetLow();\n\n         for (unsigned local_index=0; local_index<num_cells; local_index++)\n         {\n             unsigned global_index = index_low + local_index;\n             unsigned new_local_index = global_index - p_factory->GetLow();\n             bool local = p_factory->IsGlobalIndexLocal(global_index);\n\n             bool is_dynamic;\n             archive & is_dynamic;\n\n             if (is_dynamic)\n             {\n #ifdef CHASTE_CAN_CHECKPOINT_DLLS\n                 ///\\todo Dynamically loaded cell models aren't loaded from archive in extended Bidomain\n                 NEVER_REACHED;\n                 // Ensure the shared object file for this cell model is loaded.\n                 // We need to do this here, rather than in the class' serialization code,\n                 // because that code won't be available until this is done...\n//                 std::string shared_object_path;\n//                 archive & shared_object_path;\n//                 DynamicModelLoaderRegistry::Instance()->GetLoader(shared_object_path);\n #else\n                 // Could only happen on Mac OS X, and will probably be trapped earlier.\n                 NEVER_REACHED;\n #endif // CHASTE_CAN_CHECKPOINT_DLLS\n             }\n\n             AbstractCardiacCellInterface* p_cell;\n             AbstractCardiacCellInterface* p_second_cell;\n             double g_gap;\n             archive & p_cell;\n             archive & p_second_cell;\n             archive & g_gap;\n             if (local)\n             {\n                 rCells[new_local_index] = p_cell; // Add to local cells\n                 rSecondCells[new_local_index] = p_second_cell;\n                 rGgaps[new_local_index] = g_gap;\n             }\n             else\n             {\n                 //not sure how to cover this, we are already looping over local cells...\n                 NEVER_REACHED;\n                // Non-local real cell, so free the memory.\n                // delete p_cell;\n                // delete p_second_cell;\n             }\n         }\n     }\n\n     /**\n      * This method is the equivalent of SaveCardiacCells but Saves the extracellular stimulus instead\n      *\n      * @param archive  the master archive; cells will actually be written to the process-specific archive.\n      * @param version\n      */\n     template<class Archive>\n     void SaveExtracellularStimulus(Archive & archive, const unsigned int version) const\n     {\n         Archive& r_archive = *ProcessSpecificArchive<Archive>::Get();\n         const std::vector<boost::shared_ptr<AbstractStimulusFunction> > & r_stimulus_distributed = rGetExtracellularStimulusDistributed();\n         r_archive & this->mpDistributedVectorFactory; // Needed when loading\n         const unsigned num_cells = r_stimulus_distributed.size();\n         r_archive & num_cells;\n         for (unsigned i=0; i<num_cells; i++)\n         {\n             r_archive & r_stimulus_distributed[i];\n         }\n     }\n\n     /**\n      * This method is the equivalent of LoadCardiacCells but Load the extracellular stimulus instead\n      *\n      * @param archive  the master archive; cells will actually be written to the process-specific archive.\n      * @param version\n      * @param rStimuli the extracellular stimuli (will be filled from the archive).\n      * @param pMesh the mesh (needed to work out number of nodes). Here it is assumed we have already unarchived the mesh somewhere and the pointer passed in is not NULL.\n      */\n     template<class Archive>\n     void LoadExtracellularStimulus(Archive & archive, const unsigned int version,\n                                               std::vector<boost::shared_ptr<AbstractStimulusFunction> >& rStimuli,\n                                               AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>* pMesh)\n     {\n\n        DistributedVectorFactory* p_factory;\n        archive & p_factory;\n        unsigned num_cells;\n        archive & num_cells;\n        rStimuli.resize(p_factory->GetLocalOwnership());\n#ifndef NDEBUG\n          // Paranoia\n          for (unsigned i=0; i<rStimuli.size(); i++)\n          {\n              assert(rStimuli[i] == NULL);\n          }\n#endif\n\n        // We don't store a cell index in the archive, so need to work out what global\n        // index this tissue starts up.  If we're migrating (so have an\n        // original factory) we use the original low index; otherwise we use the current\n        // low index.\n        unsigned index_low = p_factory->GetOriginalFactory() ? p_factory->GetOriginalFactory()->GetLow() : p_factory->GetLow();\n\n        assert(pMesh!=NULL);\n        //unsigned num_cells = pMesh->GetNumNodes();\n        for (unsigned local_index=0; local_index<num_cells; local_index++)\n        {\n          unsigned global_index = index_low + local_index;\n\n          unsigned new_local_index = global_index - p_factory->GetLow();\n          bool local = p_factory->IsGlobalIndexLocal(global_index);\n\n          boost::shared_ptr<AbstractStimulusFunction> p_stim;\n          archive & p_stim;//get from archive\n\n          if (local)\n          {\n              rStimuli[new_local_index] = p_stim; // Add stimulus to local cells\n          }\n          //otherwise we should delete, but I think shared pointers delete themselves?\n        }\n    }\n};\n\n // Declare identifier for the serializer\n #include \"SerializationExportWrapper.hpp\"\n EXPORT_TEMPLATE_CLASS_SAME_DIMS(ExtendedBidomainTissue)\n\n namespace boost\n {\n namespace serialization\n {\n\n template<class Archive, unsigned SPACE_DIM>\n inline void save_construct_data(\n     Archive & ar, const ExtendedBidomainTissue<SPACE_DIM> * t, const unsigned int file_version)\n {\n     //archive the conductivity tensor of the second cell (which may not be dealt with by heartconfig)\n     c_vector<double, SPACE_DIM>  intracellular_conductivities_second_cell = t->GetIntracellularConductivitiesSecondCell();\n     //note that simple: ar & intracellular_conductivities_second_cell may not be liked by some boost versions\n     for (unsigned i = 0; i < SPACE_DIM; i++)\n     {\n         ar & intracellular_conductivities_second_cell(i);\n     }\n\n     const AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>* p_mesh = t->pGetMesh();\n     ar & p_mesh;\n\n     // Don't use the std::vector serialization for cardiac cells, so that we can load them\n     // more cleverly when migrating checkpoints.\n     t->SaveExtendedBidomainCells(ar, file_version);\n     t->SaveExtracellularStimulus(ar, file_version);\n\n     // Creation of conductivity tensors are called by constructor and uses HeartConfig. So make sure that it is\n     // archived too (needs doing before construction so appears here instead of usual archive location).\n     HeartConfig* p_config = HeartConfig::Instance();\n     ar & *p_config;\n     ar & p_config;\n }\n\n /**\n  * Allow us to not need a default constructor, by specifying how Boost should\n  * instantiate an instance (using existing constructor)\n  */\n template<class Archive, unsigned SPACE_DIM>\n inline void load_construct_data(\n     Archive & ar, ExtendedBidomainTissue<SPACE_DIM> * t, const unsigned int file_version)\n {\n     //Load conductivities of the conductivity of the second cell.\n     c_vector<double, SPACE_DIM>  intra_cond_second_cell;\n     //note that simple: ar & intra_cond_second_cell may not be liked by some boost versions\n     for (unsigned i = 0; i < SPACE_DIM; i++)\n     {\n         double cond;\n         ar & cond;\n         intra_cond_second_cell(i) = cond;\n     }\n\n\n     std::vector<AbstractCardiacCellInterface*> cells_distributed;\n     std::vector<AbstractCardiacCellInterface*> cells_distributed_second_cell;\n     std::vector<boost::shared_ptr<AbstractStimulusFunction> > extra_stim;\n     std::vector<double> g_gaps;\n     AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>* p_mesh;\n     ar & p_mesh;\n\n     // Load only the cells we actually own\n     t->LoadExtendedBidomainCells(\n             *ProcessSpecificArchive<Archive>::Get(), file_version, cells_distributed, cells_distributed_second_cell, g_gaps, p_mesh);\n\n     t->LoadExtracellularStimulus(\n             *ProcessSpecificArchive<Archive>::Get(), file_version, extra_stim, p_mesh);\n\n     // CreateIntracellularConductivityTensor() is called by AbstractCardiacTissue constructor and uses HeartConfig.\n     // (as does CreateExtracellularConductivityTensor). So make sure that it is\n     // archived too (needs doing before construction so appears here instead of usual archive location).\n     HeartConfig* p_config = HeartConfig::Instance();\n     ar & *p_config;\n     ar & p_config;\n\n     ::new(t)ExtendedBidomainTissue<SPACE_DIM>(cells_distributed, cells_distributed_second_cell, extra_stim, g_gaps, p_mesh, intra_cond_second_cell);\n }\n }\n } // namespace ...\n\n#endif /*EXTENDEDBIDOMAINTISSUE_HPP_*/\n", "meta": {"hexsha": "c8e0609243796ce52c296fdf002c83bb07e32696", "size": 29619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/tissue/ExtendedBidomainTissue.hpp", "max_stars_repo_name": "mdp19pn/Chaste", "max_stars_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T08:32:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T11:39:26.000Z", "max_issues_repo_path": "heart/src/tissue/ExtendedBidomainTissue.hpp", "max_issues_repo_name": "mdp19pn/Chaste", "max_issues_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-06-14T13:48:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T10:42:07.000Z", "max_forks_repo_path": "heart/src/tissue/ExtendedBidomainTissue.hpp", "max_forks_repo_name": "mdp19pn/Chaste", "max_forks_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T13:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T18:57:35.000Z", "avg_line_length": 41.8939179632, "max_line_length": 238, "alphanum_fraction": 0.6877004625, "num_tokens": 6697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3812195803163618, "lm_q1q2_score": 0.1995380857505491}}
{"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_FAST_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FAST_HPP_INCLUDED\n\n#include <boost/simd/config.hpp>\n#include <boost/simd/detail/decorator.hpp>\n#include <boost/simd/detail/dispatch.hpp>\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n  @ingroup group-decorator\n\n    calls a version of the functor\n      that can do some agressive optimization at the cost of certain\n      properties or corner cases of the original functor.\n\n      These losses are of the `fast_math` kind.\n\n    @par Semantic\n\n    @code\n    T r = fast_(func)(< func parameters >);\n    @endcode\n\n  **/\n  template<typename T> auto fast_(T const& x) {}\n\n} }\n#endif\n\nnamespace boost { namespace simd\n{\n  struct fast_tag : decorator_<fast_tag>\n  {\n    using parent = decorator_<fast_tag>;\n  };\n\n  const detail::decorator<fast_tag> fast_ = {};\n} }\n\n#endif\n", "meta": {"hexsha": "55ee4d1d693d2911452349f5e9130c0c1fd9c575", "size": 1252, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/fast.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/fast.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/fast.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": 24.0769230769, "max_line_length": 100, "alphanum_fraction": 0.5974440895, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "#include <mutex>\n#include <memory>\n#include <iostream>\n#include <boost/format.hpp>\n\n#include <pcl/filters/filter.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/common/transforms.h>\n\n#include <ros/ros.h>\n#include <pcl_ros/point_cloud.h>\n#include <tf_conversions/tf_eigen.h>\n#include <tf/transform_broadcaster.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/time_synchronizer.h>\n\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <visualization_msgs/MarkerArray.h>\n\n#include <nodelet/nodelet.h>\n#include <pluginlib/class_list_macros.h>\n\n#include <hdl_people_tracking/ClusterArray.h>\n\n#include <hdl_people_detection/people_detector.h>\n#include <hdl_people_detection/background_subtractor.hpp>\n\nnamespace hdl_people_detection {\n\n/**\n * @brief A nodelet to detect people using a 3D LIDAR\n */\nclass HdlPeopleDetectionNodelet : public nodelet::Nodelet {\npublic:\n  using PointT = pcl::PointXYZI;\n\n  HdlPeopleDetectionNodelet() {}\n  virtual ~HdlPeopleDetectionNodelet() {}\n\n  void onInit() override {\n    nh = getNodeHandle();\n    mt_nh = getMTNodeHandle();\n    private_nh = getPrivateNodeHandle();\n\n    initialize_params();\n\n    // publishers\n    backsub_points_pub = private_nh.advertise<sensor_msgs::PointCloud2>(\"backsub_points\", 5);\n    cluster_points_pub = private_nh.advertise<sensor_msgs::PointCloud2>(\"cluster_points\", 5);\n    human_points_pub = private_nh.advertise<sensor_msgs::PointCloud2>(\"human_points\", 5);\n    detection_markers_pub = private_nh.advertise<visualization_msgs::MarkerArray>(\"detection_markers\", 5);\n\n    backsub_voxel_points_pub = private_nh.advertise<sensor_msgs::PointCloud2>(\"backsub_voxel_points\", 1, true);\n    backsub_voxel_markers_pub = private_nh.advertise<visualization_msgs::Marker>(\"backsub_voxel_marker\", 1, true);\n\n    clusters_pub = private_nh.advertise<hdl_people_tracking::ClusterArray>(\"clusters\", 10);\n\n    // subscribers\n    globalmap_sub = nh.subscribe(\"/globalmap\", 1, &HdlPeopleDetectionNodelet::globalmap_callback, this);\n    if(private_nh.param<bool>(\"static_sensor\", false)) {\n      static_points_sub = mt_nh.subscribe(\"/velodyne_points\", 32, &HdlPeopleDetectionNodelet::callback_static, this);\n    } else {\n      odom_sub.reset(new message_filters::Subscriber<nav_msgs::Odometry>(mt_nh, \"/odom\", 20));\n      points_sub.reset(new message_filters::Subscriber<sensor_msgs::PointCloud2>(mt_nh, \"/velodyne_points\", 20));\n      sync.reset(new message_filters::TimeSynchronizer<nav_msgs::Odometry, sensor_msgs::PointCloud2>(*odom_sub, *points_sub, 20));\n      sync->registerCallback(boost::bind(&HdlPeopleDetectionNodelet::callback, this, _1, _2));\n    }\n  }\n\nprivate:\n  /**\n   * @brief initialize_params\n   */\n  void initialize_params() {\n    double downsample_resolution = private_nh.param<double>(\"downsample_resolution\", 0.1);\n    boost::shared_ptr<pcl::VoxelGrid<PointT>> voxelgrid(new pcl::VoxelGrid<PointT>());\n    voxelgrid->setLeafSize(downsample_resolution, downsample_resolution, downsample_resolution);\n    downsample_filter = voxelgrid;\n\n    NODELET_INFO(\"create people detector\");\n    detector.reset(new PeopleDetector(private_nh));\n  }\n\n  /**\n   * @brief in case the sensor is fixed\n   * @param points_msg\n   */\n  void callback_static(const sensor_msgs::PointCloud2ConstPtr& points_msg) {\n    if(!globalmap) {\n      NODELET_INFO(\"constructing globalmap from a points msg\");\n      globalmap_callback(points_msg);\n      NODELET_INFO(\"done\");\n      return;\n    }\n\n    pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>());\n    pcl::fromROSMsg(*points_msg, *cloud);\n    if(cloud->empty()) {\n      NODELET_ERROR(\"cloud is empty!!\");\n      return;\n    }\n\n    // downsampling\n    pcl::PointCloud<PointT>::Ptr downsampled(new pcl::PointCloud<PointT>());\n    downsample_filter->setInputCloud(cloud);\n    downsample_filter->filter(*downsampled);\n    downsampled->header = cloud->header;\n    cloud = downsampled;\n\n    // background subtraction and people detection\n    auto filtered = backsub->filter(cloud);\n    auto clusters = detector->detect(filtered);\n\n    publish_msgs(points_msg->header.stamp, filtered, clusters);\n  }\n\n  /**\n   * @brief callback\n   * @param odom_msg    sensor pose\n   * @param points_msg  point cloud\n   */\n  void callback(const nav_msgs::OdometryConstPtr& odom_msg, const sensor_msgs::PointCloud2ConstPtr& points_msg) {\n    if(!globalmap) {\n      NODELET_ERROR(\"globalmap has not been received!!\");\n      return;\n    }\n\n    pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>());\n    pcl::fromROSMsg(*points_msg, *cloud);\n    if(cloud->empty()) {\n      NODELET_ERROR(\"cloud is empty!!\");\n      return;\n    }\n\n    // downsampling\n    pcl::PointCloud<PointT>::Ptr downsampled(new pcl::PointCloud<PointT>());\n    downsample_filter->setInputCloud(cloud);\n    downsample_filter->filter(*downsampled);\n    downsampled->header = cloud->header;\n    cloud = downsampled;\n\n    // transform #cloud into the globalmap space\n    const auto& position = odom_msg->pose.pose.position;\n    const auto& orientation = odom_msg->pose.pose.orientation;\n    Eigen::Matrix4f transform = Eigen::Matrix4f::Identity();\n    transform.block<3, 1>(0, 3) = Eigen::Vector3f(position.x, position.y, position.z);\n    transform.block<3, 3>(0, 0) = Eigen::Quaternionf(orientation.w, orientation.x, orientation.y, orientation.z).toRotationMatrix();\n    pcl::transformPointCloud(*cloud, *cloud, transform);\n    cloud->header.frame_id = globalmap->header.frame_id;\n\n    // background subtraction and people detection\n    auto filtered = backsub->filter(cloud);\n    auto clusters = detector->detect(filtered);\n\n    publish_msgs(points_msg->header.stamp, filtered, clusters);\n  }\n\n  void globalmap_callback(const sensor_msgs::PointCloud2ConstPtr& points_msg) {\n    NODELET_INFO(\"globalmap received!\");\n    pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>());\n    pcl::fromROSMsg(*points_msg, *cloud);\n    globalmap = cloud;\n\n    NODELET_INFO(\"background subtractor constructed\");\n    double backsub_resolution = private_nh.param<double>(\"backsub_resolution\", 0.2);\n    int backsub_occupancy_thresh = private_nh.param<int>(\"backsub_occupancy_thresh\", 2);\n\n    backsub.reset(new BackgroundSubtractor());\n    backsub->setVoxelSize(backsub_resolution, backsub_resolution, backsub_resolution);\n    backsub->setOccupancyThresh(backsub_occupancy_thresh);\n    backsub->setBackgroundCloud(globalmap);\n\n    backsub_voxel_markers_pub.publish(backsub->create_voxel_marker());\n    backsub_voxel_points_pub.publish(backsub->voxels());\n  }\n\nprivate:\n  /**\n   * @brief publish messages\n   * @param stamp\n   * @param filtered\n   * @param clusters\n   */\n  void publish_msgs(const ros::Time& stamp, const pcl::PointCloud<pcl::PointXYZI>::Ptr& filtered, const std::vector<Cluster::Ptr>& clusters) const {\n    if(clusters_pub.getNumSubscribers()) {\n      hdl_people_tracking::ClusterArrayPtr clusters_msg(new hdl_people_tracking::ClusterArray());\n      clusters_msg->header.frame_id = globalmap->header.frame_id;\n      clusters_msg->header.stamp = stamp;\n\n      clusters_msg->clusters.resize(clusters.size());\n      for(int i=0; i<clusters.size(); i++) {\n        auto& cluster_msg = clusters_msg->clusters[i];\n        cluster_msg.is_human = clusters[i]->is_human;\n        cluster_msg.min_pt.x = clusters[i]->min_pt.x();\n        cluster_msg.min_pt.y = clusters[i]->min_pt.y();\n        cluster_msg.min_pt.z = clusters[i]->min_pt.z();\n\n        cluster_msg.max_pt.x = clusters[i]->max_pt.x();\n        cluster_msg.max_pt.y = clusters[i]->max_pt.y();\n        cluster_msg.max_pt.z = clusters[i]->max_pt.z();\n\n        cluster_msg.size.x = clusters[i]->size.x();\n        cluster_msg.size.y = clusters[i]->size.y();\n        cluster_msg.size.z = clusters[i]->size.z();\n\n        cluster_msg.centroid.x = clusters[i]->centroid.x();\n        cluster_msg.centroid.y = clusters[i]->centroid.y();\n        cluster_msg.centroid.z = clusters[i]->centroid.z();\n      }\n\n      clusters_pub.publish(clusters_msg);\n    }\n\n    if(backsub_points_pub.getNumSubscribers()) {\n      backsub_points_pub.publish(filtered);\n    }\n\n    if(cluster_points_pub.getNumSubscribers()) {\n      pcl::PointCloud<pcl::PointXYZI>::Ptr accum(new pcl::PointCloud<pcl::PointXYZI>());\n      for(const auto& cluster : clusters) {\n        std::copy(cluster->cloud->begin(), cluster->cloud->end(), std::back_inserter(accum->points));\n      }\n      accum->width = accum->size();\n      accum->height = 1;\n      accum->is_dense = false;\n\n      accum->header.stamp = filtered->header.stamp;\n      accum->header.frame_id = globalmap->header.frame_id;\n\n      cluster_points_pub.publish(accum);\n    }\n\n    if(human_points_pub.getNumSubscribers()) {\n      pcl::PointCloud<pcl::PointXYZI>::Ptr accum(new pcl::PointCloud<pcl::PointXYZI>());\n      for(const auto& cluster : clusters) {\n        if(cluster->is_human){\n          std::copy(cluster->cloud->begin(), cluster->cloud->end(), std::back_inserter(accum->points));\n        }\n      }\n      accum->width = accum->size();\n      accum->height = 1;\n      accum->is_dense = false;\n\n      accum->header.stamp = filtered->header.stamp;\n      accum->header.frame_id = globalmap->header.frame_id;\n\n      human_points_pub.publish(accum);\n    }\n\n    if(detection_markers_pub.getNumSubscribers()) {\n      detection_markers_pub.publish(create_markers(stamp, clusters));\n    }\n  }\n\n  visualization_msgs::MarkerArrayConstPtr create_markers(const ros::Time& stamp, const std::vector<Cluster::Ptr>& clusters) const {\n    visualization_msgs::MarkerArrayPtr markers(new visualization_msgs::MarkerArray());\n    markers->markers.reserve(clusters.size());\n\n    for(int i=0; i<clusters.size(); i++) {\n      if(!clusters[i]->is_human) {\n        continue;\n      }\n\n      visualization_msgs::Marker cluster_marker;\n      cluster_marker.header.stamp = stamp;\n      cluster_marker.header.frame_id = globalmap->header.frame_id;\n      cluster_marker.action = visualization_msgs::Marker::ADD;\n      cluster_marker.lifetime = ros::Duration(0.5);\n      cluster_marker.ns = (boost::format(\"cluster%d\") % i).str();\n      cluster_marker.type = visualization_msgs::Marker::CUBE;\n\n      cluster_marker.pose.position.x = clusters[i]->centroid.x();\n      cluster_marker.pose.position.y = clusters[i]->centroid.y();\n      cluster_marker.pose.position.z = clusters[i]->centroid.z();\n      cluster_marker.pose.orientation.w = 1.0;\n\n      cluster_marker.color.r = 0.0;\n      cluster_marker.color.g = 0.0;\n      cluster_marker.color.b = 1.0;\n      cluster_marker.color.a = 0.4;\n\n      cluster_marker.scale.x = clusters[i]->size.x();\n      cluster_marker.scale.y = clusters[i]->size.y();\n      cluster_marker.scale.z = clusters[i]->size.z();\n\n      markers->markers.push_back(cluster_marker);\n    }\n\n    return markers;\n  }\n\nprivate:\n  // ROS\n  ros::NodeHandle nh;\n  ros::NodeHandle mt_nh;\n  ros::NodeHandle private_nh;\n\n  // subscribers\n  std::unique_ptr<message_filters::Subscriber<nav_msgs::Odometry>> odom_sub;\n  std::unique_ptr<message_filters::Subscriber<sensor_msgs::PointCloud2>> points_sub;\n  std::unique_ptr<message_filters::TimeSynchronizer<nav_msgs::Odometry, sensor_msgs::PointCloud2>> sync;\n\n  ros::Subscriber globalmap_sub;\n  ros::Subscriber static_points_sub;\n\n  // publishers\n  ros::Publisher backsub_points_pub;\n  ros::Publisher backsub_voxel_points_pub;\n\n  ros::Publisher cluster_points_pub;\n  ros::Publisher human_points_pub;\n\n  ros::Publisher detection_markers_pub;\n  ros::Publisher backsub_voxel_markers_pub;\n\n  ros::Publisher clusters_pub;\n\n  // global map\n  pcl::PointCloud<PointT>::Ptr globalmap;\n\n  pcl::Filter<PointT>::Ptr downsample_filter;\n  std::unique_ptr<BackgroundSubtractor> backsub;\n  std::unique_ptr<PeopleDetector> detector;\n\n};\n\n}\n\nPLUGINLIB_EXPORT_CLASS(hdl_people_detection::HdlPeopleDetectionNodelet, nodelet::Nodelet)\n", "meta": {"hexsha": "889577d5f23768f950109f1c52fa8c78d363dae0", "size": 11834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/hdl_people_detection_nodelet.cpp", "max_stars_repo_name": "shangzhouye/hdl_people_tracking", "max_stars_repo_head_hexsha": "ba1dd664439bedd8b5f99113326ffca4703d4aeb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "apps/hdl_people_detection_nodelet.cpp", "max_issues_repo_name": "shangzhouye/hdl_people_tracking", "max_issues_repo_head_hexsha": "ba1dd664439bedd8b5f99113326ffca4703d4aeb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "apps/hdl_people_detection_nodelet.cpp", "max_forks_repo_name": "shangzhouye/hdl_people_tracking", "max_forks_repo_head_hexsha": "ba1dd664439bedd8b5f99113326ffca4703d4aeb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 35.6445783133, "max_line_length": 148, "alphanum_fraction": 0.7071150921, "num_tokens": 2819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "/****\n   Copyright 2005-2007, Moshe Looks and Novamente 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#include \"moses/moses.h\"\n#include \"moses/optimization.h\"\n#include \"moses/scoring_functions.h\"\n#include <boost/lexical_cast.hpp>\n#include \"reduct/reduct.h\"\n#include <iostream>\n\nusing namespace moses;\nusing namespace reduct;\nusing namespace boost;\nusing namespace std;\n\nint main(int argc,char** argv) { \n  vtree tr;\n  while (cin.good()) {\n    cin >> tr;\n    if (!cin.good())\n      break;\n    \n    logical_reduce(tr);\n\n    representation rep(logical_reduction(),tr,infer_tree_type(tr));\n    \n    vtree tmp(rep.exemplar());\n\n    for (int i=0;i<10;++i) { \n      cout << rep.exemplar() << endl;\n\n      eda::instance inst(rep.fields().packed_width());\n      for (eda::field_set::disc_iterator it=rep.fields().begin_raw(inst);\n\t   it!=rep.fields().end_raw(inst);++it)\n\tit.randomize();\t\n      \n      cout << rep.fields().stream(inst) << endl;\n      rep.transform(inst);\n      cout << rep.exemplar() << endl;\n\n      rep.clear_exemplar();\n      assert(tmp==rep.exemplar());\n    }\n  }\n}\n", "meta": {"hexsha": "a2c46e1223b10d34b13960d4248a88e9fce75a9b", "size": 1594, "ext": "cc", "lang": "C++", "max_stars_repo_path": "moses2/main/build-representation.cc", "max_stars_repo_name": "moshelooks/moses", "max_stars_repo_head_hexsha": "81568276877f24c2cb1ca5649d44e22fba6f44b2", "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": "moses2/main/build-representation.cc", "max_issues_repo_name": "moshelooks/moses", "max_issues_repo_head_hexsha": "81568276877f24c2cb1ca5649d44e22fba6f44b2", "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": "moses2/main/build-representation.cc", "max_forks_repo_name": "moshelooks/moses", "max_forks_repo_head_hexsha": "81568276877f24c2cb1ca5649d44e22fba6f44b2", "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.0169491525, "max_line_length": 75, "alphanum_fraction": 0.6706398996, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "#include <bits/stdc++.h>\n#include <zlib.h>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\n\nuint64_t l3_access_cycle_count = 38;\nuint64_t total_dyn_ins_count = 163607974;\ndouble dyn_ins_count_inc_ratio=0.013;\n\n#define BUFFER_SIZE 2048\n#define FANIN 100\n#define FANIN_THRESHOLD 10\n\n\nuint64_t find_prefetch_index(vector<pair<string,uint64_t>> &current_lb_record)\n{\n    uint64_t running_cycle_count = 0;\n    for(uint64_t i = 0; i < current_lb_record.size(); i++)\n    {\n        running_cycle_count+=current_lb_record[i].second;\n        if(running_cycle_count>=l3_access_cycle_count)return i;\n    }\n    return current_lb_record.size()-1;\n}\n\nbool find_prefetch_index_for_multiple_samples_with_fanin(string missed_pc, vector<vector<pair<string,uint64_t>>> &current_lb_record_list, vector<string> &result)\n{\n    set<string> candidates_array[FANIN];\n    uint64_t candidates_array_count[FANIN];\n    for(uint64_t i=0;i<FANIN;i++)candidates_array_count[i]=0;\n    uint64_t current_index = 0;\n    for(int i = 0; i< current_lb_record_list.size(); i++)\n    {\n        uint64_t start_index = find_prefetch_index(current_lb_record_list[i]);\n        if(start_index==current_lb_record_list[i].size())return false;\n        start_index+=1;\n        bool not_found = true;\n        int j = 0;\n        for(j=0; j< current_index; j++)\n        {\n            set<string> &candidates = candidates_array[j];\n            \n            set<string> tmp;\n            for(int k = start_index; k<current_lb_record_list[i].size();k++)\n            {\n                string pc = current_lb_record_list[i][k].first;\n                if(pc!=missed_pc)\n                {\n                    if(candidates.find(pc)!=candidates.end())\n                    {\n                        tmp.insert(pc);\n                    }\n                }\n            }\n            if(tmp.size()!=0)\n            {\n                not_found = false;\n                candidates.clear();\n                for(auto it: tmp)\n                {\n                    candidates.insert(it);\n                }\n                candidates_array_count[j]++;\n                break;\n            }\n        }\n        if(not_found)\n        {\n            current_index+=1;\n            if(current_index>=FANIN)return false;\n            for(int k = start_index; k< current_lb_record_list[i].size();k++)\n            {\n                string pc = current_lb_record_list[i][k].first;\n                if(pc!=missed_pc)\n                {\n                    candidates_array[current_index].insert(pc);\n                }\n            }\n            if(candidates_array[current_index].size()<1)return false;\n        }\n        else\n        {\n            //j contains the first found set\n        }\n    }\n    \n    vector<pair<uint64_t,string>> sorted_result;\n    for(int j=0;j< current_index; j++)\n    {\n        set<string> &candidates = candidates_array[j];\n        if(candidates.size()<1)continue;\n        vector<pair<int,string>> sorted_candidates;\n        for(auto it: candidates)\n        {\n            int total_distance = 0;\n            for(int i = 0; i< current_lb_record_list.size();i++)\n            {\n                for(int k=0;k<current_lb_record_list[i].size();k++)\n                {\n                    if(current_lb_record_list[i][k].first == it)\n                    {\n                        total_distance+=k;\n                        break;\n                    }\n                }\n            }\n            sorted_candidates.push_back(make_pair(total_distance,it));\n        }\n        sort(sorted_candidates.begin(), sorted_candidates.end());\n        //for(int i = 0; i< sorted_candidates.size(); i++)cout<<sorted_candidates[i].second<<\";\"<<sorted_candidates[i].first<<\",\";\n        //cout<<sorted_candidates[0].second<<endl;\n        sorted_result.push_back(make_pair(candidates_array_count[j],sorted_candidates[0].second));\n    }\n    sort(sorted_result.begin(),sorted_result.end());\n    reverse(sorted_result.begin(),sorted_result.end());\n    result.clear();\n    for(int j=0;j<sorted_result.size();j++)\n    {\n        result.push_back(sorted_result[j].second);\n        if(j>=FANIN_THRESHOLD-1)break;\n    }\n    return true;\n}\n\nbool find_prefetch_index_for_multiple_samples(string missed_pc, vector<vector<pair<string,uint64_t>>> &current_lb_record_list, string &result)\n{\n    result=\"\";\n    set<string> candidates;\n    uint64_t start_index = find_prefetch_index(current_lb_record_list[0]);\n    start_index+=1;\n    if(start_index==current_lb_record_list[0].size())\n    {\n        //cout<<\"Not found\\n\";\n        return false;\n    }\n    for(int i = start_index; i<current_lb_record_list[0].size();i++)\n    {\n        string pc = current_lb_record_list[0][i].first;\n        if(pc!=missed_pc)\n        {\n            candidates.insert(pc);\n        }\n    }\n    bool found = true;\n    for(int i = 1; i< current_lb_record_list.size(); i++)\n    {\n        set<string> tmp;\n        start_index = find_prefetch_index(current_lb_record_list[i]);\n        start_index+=1;\n        if(start_index==current_lb_record_list[i].size())\n        {\n            found = false;\n            break;\n        }\n        for(int j = start_index; j<current_lb_record_list[i].size();j++)\n        {\n            string pc = current_lb_record_list[i][j].first;\n            if(pc!=missed_pc)\n            {\n                if(candidates.find(pc)!=candidates.end())\n                {\n                    tmp.insert(pc);\n                }\n            }\n        }\n        if(tmp.size()==0)\n        {\n            found = false;\n            break;\n        }\n        candidates.clear();\n        for(auto it: tmp)\n        {\n            candidates.insert(it);\n        }\n    }\n    if(found)\n    {\n        vector<pair<int,string>> sorted_candidates;\n        for(auto it: candidates)\n        {\n            int total_distance = 0;\n            for(int i = 0; i< current_lb_record_list.size();i++)\n            {\n                for(int j=0;j<current_lb_record_list[i].size();j++)\n                {\n                    if(current_lb_record_list[i][j].first == it)\n                    {\n                        total_distance+=j;\n                        break;\n                    }\n                }\n            }\n            sorted_candidates.push_back(make_pair(total_distance,it));\n        }\n        sort(sorted_candidates.begin(), sorted_candidates.end());\n        //for(int i = 0; i< sorted_candidates.size(); i++)cout<<sorted_candidates[i].second<<\";\"<<sorted_candidates[i].first<<\",\";\n        //cout<<sorted_candidates[0].second<<endl;\n        result = sorted_candidates[0].second;\n        return true;\n    }\n    else\n    {\n        //cout<<\"Not found\\n\";\n        return false;\n    }\n}\n\nuint64_t string_to_u64(string a)\n{\n    istringstream iss(a);\n    uint64_t value;\n    iss>>value;\n    return value;\n}\n\nvoid check_pc_miss_same_cache_line(string cache_line_address, string pc)\n{\n    assert((string_to_u64(pc)>>6)==string_to_u64(cache_line_address));\n}\n\nint main(int argc, char *argv[])\n{\n    if(argc<2)\n    {\n        cerr << \"Usage ./exec data_file_path\\n\";\n        return -1;\n    }\n    gzFile data_file = gzopen(argv[1], \"rb\");\n    if(!data_file)\n    {\n        cerr << \"Invalid data_file_path\\n\";\n        return -1;\n    }\n    char buffer[BUFFER_SIZE];\n    memset(buffer, 0, BUFFER_SIZE);\n    if(gzbuffer(data_file, BUFFER_SIZE*128) == -1)\n    {\n        cerr << \"GZ Input file buffer set unsuccessfull\\n\";\n        return -1;\n    }\n    string line;\n    vector<string> parsed;\n    string cache_line_address,pc;\n    unordered_map<string,vector<vector<pair<string,uint64_t>>>> profile;\n    unordered_map<string,uint64_t> miss_counts;\n    while( gzgets(data_file,buffer,BUFFER_SIZE) != Z_NULL )\n    {\n        line=buffer;\n        boost::trim_if(line,boost::is_any_of(\",\\n\"));\n        boost::split(parsed,line,boost::is_any_of(\",\\n\"),boost::token_compress_on);\n        //for(int i =0;i<parsed.size();i++)cerr<<parsed[i]<<\",\";\n        //cerr<<endl;\n        if(parsed.size()<3)\n        {\n            cerr << \"LBR data contains less than 3 branch records\\n\";\n            return -1;\n        }\n        cache_line_address = parsed[0];\n        pc = parsed[1];\n        check_pc_miss_same_cache_line(cache_line_address, pc);\n        vector<string> current_record;\n        vector<pair<string,uint64_t>> current_lb_record;\n        for(int i=2;i<parsed.size();i++)\n        {\n            //cerr<<parsed[i]<<endl;\n            boost::split(current_record,parsed[i],boost::is_any_of(\";\"),boost::token_compress_on);\n            if(current_record.size() != 2)\n            {\n                cerr << \"LB-record does not contain exactly 2 entries\\n\";\n                return -1;\n            }\n            current_lb_record.push_back(make_pair(current_record[0],stoi(current_record[1])));\n        }\n        if(profile.find(pc)==profile.end())\n        {\n            profile[pc]=vector<vector<pair<string,uint64_t>>>();\n            miss_counts[pc]=0;\n        }\n        profile[pc].push_back(current_lb_record);\n        miss_counts[pc]+=1;\n    }\n    vector<pair<uint64_t,string>> sorted_miss_pcs;\n    for(auto it: miss_counts)\n    {\n        sorted_miss_pcs.push_back(make_pair(it.second, it.first));\n    }\n    sort(sorted_miss_pcs.begin(), sorted_miss_pcs.end());\n    reverse(sorted_miss_pcs.begin(), sorted_miss_pcs.end());\n    uint64_t permissible_prefetch_count = dyn_ins_count_inc_ratio * total_dyn_ins_count;\n    uint64_t current_running_count = 0;\n    \n    unordered_map<string,set<string>> bbl_address_prefetch_map;\n    \n    for(int i=0;i<sorted_miss_pcs.size();i++)\n    {\n        //cout<<sorted_miss_pcs[i].second<<\",\"<<sorted_miss_pcs[i].first<<\",\";\n        string pc = sorted_miss_pcs[i].second;\n        if(profile[pc].size()>1)\n        {\n            /*string result;\n            bool is_found = find_prefetch_index_for_multiple_samples(pc, profile[pc],result);\n            if(is_found)cout<<result;\n            else\n            {*/\n            vector<string> results;\n            bool is_found = find_prefetch_index_for_multiple_samples_with_fanin(pc, profile[pc],results);\n            if(is_found)\n            {\n                //for(int j=0;j<results.size();j++)cout<<results[j]<<\",\";\n                for(int j = 0;j<results.size();j++)\n                {\n                    string bbl_address = results[j];\n                    if(bbl_address_prefetch_map.find(bbl_address)==bbl_address_prefetch_map.end())\n                    {\n                        bbl_address_prefetch_map[bbl_address]=set<string>();\n                    }\n                    bbl_address_prefetch_map[bbl_address].insert(pc);\n                }\n            }\n            //}\n        }\n        else if(profile[pc].size()==1)\n        {\n            uint64_t index = find_prefetch_index(profile[pc][0]);\n            index+=1;\n            if(index==profile[pc][0].size())\n            {\n                //cerr<<\"No good prefetch position found\\n\";\n            }\n            else\n            {\n                //cout<<profile[pc][0][index].first<<\"->\"<<profile[pc][0][index-1].first<<\"\\n\";\n                //cout<<profile[pc][0][index].first;\n                \n                string bbl_address = profile[pc][0][index].first;\n                if(bbl_address_prefetch_map.find(bbl_address)==bbl_address_prefetch_map.end())\n                {\n                    bbl_address_prefetch_map[bbl_address]=set<string>();\n                }\n                bbl_address_prefetch_map[bbl_address].insert(pc);\n            }\n        }\n        else\n        {\n            cerr<<\"Miss without lbr profile\\n\";\n            return -1;\n        }\n        //cout<<endl;\n        \n        current_running_count+=sorted_miss_pcs[i].first;\n        if(current_running_count>=permissible_prefetch_count)break;\n    }\n    \n    for(auto it:bbl_address_prefetch_map)\n    {\n        cout<<it.first<<\" \"<<it.second.size();\n        for(auto set_it: it.second)\n        {\n            cout<<\" \"<<set_it;\n        }\n        cout<<endl;\n    }\n}\n", "meta": {"hexsha": "cd1f36341820ea888ff00b1a50c8567a1c895043", "size": 11918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ispy/parse_lbr.cpp", "max_stars_repo_name": "efeslab/frontsuite", "max_stars_repo_head_hexsha": "a9adc3f0dbf335d6096897ed40e5264892031cfe", "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": "ispy/parse_lbr.cpp", "max_issues_repo_name": "efeslab/frontsuite", "max_issues_repo_head_hexsha": "a9adc3f0dbf335d6096897ed40e5264892031cfe", "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": "ispy/parse_lbr.cpp", "max_forks_repo_name": "efeslab/frontsuite", "max_forks_repo_head_hexsha": "a9adc3f0dbf335d6096897ed40e5264892031cfe", "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.5628415301, "max_line_length": 161, "alphanum_fraction": 0.5443027354, "num_tokens": 2693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "#include <string.h>\n#include <iostream>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\nusing namespace std;\nusing namespace boost::property_tree;\n\n#include <map>\n#include <string>\n#include <iostream>\n#include <string.h>\n\n#include <fc/crypto/elliptic.hpp>\n#include <fc/crypto/ripemd160.hpp>\n#include <fc/crypto/base58.hpp>\n#include <fc/crypto/sha512.hpp>\n#include <fc/io/json.hpp>\n#include <fc/reflect/reflect.hpp>\n#include <fc/io/raw.hpp>\n#include <fc/variant_object.hpp>\n#include <fc/exception/exception.hpp>\n#include <graphene/chain/pts_address.hpp>\n#include <graphene/chain/protocol/address.hpp>\n\n#include \"wallet_lib.hpp\"\n\nusing namespace std;\n\nstruct binary_key\n{\n  binary_key(){}\n  uint32_t check = 0;\n  fc::ecc::public_key_data data;\n};\n\nFC_REFLECT( binary_key, (data)(check) )\n\nstd::string key_to_wif(const fc::sha256& secret )\n{\n  const size_t size_of_data_to_hash = sizeof(secret) + 1;\n  const size_t size_of_hash_bytes = 4;\n  char data[size_of_data_to_hash + size_of_hash_bytes];\n  data[0] = (char)0x80;\n  memcpy(&data[1], (char*)&secret, sizeof(secret));\n  fc::sha256 digest = fc::sha256::hash(data, size_of_data_to_hash);\n  digest = fc::sha256::hash(digest);\n  memcpy(data + size_of_data_to_hash, (char*)&digest, size_of_hash_bytes);\n  return fc::to_base58(data, sizeof(data));\n}\n\n/*\n * global parameters to hold the keys\n */\n\n//cybex_priv_key_type active_priv_key, owner_priv_key, memo_priv_key;\n\nstatic map<string, fc::ecc::private_key> stored_keys;\nstatic string default_public_key = \"\";\n\n\nvoid set_default_public_key(string pub_key_base58_str)\n{\n  default_public_key = pub_key_base58_str;\n}\n\nvoid clear_user_key()\n{\n    stored_keys.clear();\n}\n\nvoid add_user_key(string public_key, fc::ecc::private_key key)\n{\n    stored_keys.insert(map<string, fc::ecc::private_key>::value_type(public_key, key));\n}\n\nfc::ecc::private_key& get_private_key(string public_key)\n{\n    map<string, fc::ecc::private_key>::iterator iter;\n\n    if(public_key == \"\")\n        iter = stored_keys.find(default_public_key);\n    else\n        iter = stored_keys.find(public_key);\n    if(iter != stored_keys.end())\n        return iter->second;\n\n    FC_THROW_EXCEPTION(fc::exception, \"private key not found\");\n}\n\nfc::mutable_variant_object get_dev_key(string type, string secret)\n{\n  fc::ecc::private_key priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(secret)));\n  string private_key = key_to_wif( priv_key );\n  fc::ecc::public_key pub_key = priv_key.get_public_key();\n  struct binary_key bkey;\n  bkey.data = pub_key.serialize();\n  bkey.check = fc::ripemd160::hash( bkey.data.data, bkey.data.size() )._hash[0];\n  \n  auto data = fc::raw::pack( bkey );\n  string public_key = \"CYB\" + fc::to_base58( data.data(), data.size() );\n  \n  auto dat = pub_key.serialize();\n  fc::ripemd160 addr = fc::ripemd160::hash( fc::sha512::hash( dat.data, sizeof( dat ) ) );\n  fc::array<char,24> bin_addr;\n  \n  memcpy( (char*)&bin_addr, (char*)&addr, sizeof( addr ) );\n  auto checksum = fc::ripemd160::hash( (char*)&addr, sizeof( addr ) );\n  memcpy( ((char*)&bin_addr)+20, (char*)&checksum._hash[0], 4 );\n  string address = \"CYB\" + fc::to_base58( bin_addr.data, sizeof( bin_addr ) );\n  \n  graphene::chain::pts_address compress_pts_addr(pub_key, true, 56);\n  graphene::chain::pts_address uncompress_pts_addr(pub_key, false, 56);\n  \n  fc::mutable_variant_object mvo;\n  mvo( \"private_key\", private_key)\n  ( \"public_key\", public_key)\n  ( \"address\", address)\n  ( \"compressed\", string(graphene::chain::address(compress_pts_addr)))\n  ( \"uncompressed\", string(graphene::chain::address(uncompress_pts_addr)))\n  ;\n\n  add_user_key(public_key, priv_key);\n  if(type == \"active\")\n    default_public_key = public_key;\n\n  return mvo;\n  //return fc::json::to_string(mvo);\n}\n\nstring get_user_key(string user_name, string password)\n{\n  clear_user_key();\n  fc::mutable_variant_object mvo;\n  mvo(\"active-key\", get_dev_key(\"active\", user_name + \"active\" + password))\n     (\"owner-key\", get_dev_key(\"owner\", user_name + \"owner\" + password))\n     (\"memo-key\", get_dev_key(\"memo\", user_name + \"memo\" + password))\n  ;\n  return fc::json::to_string(mvo);\n}\n", "meta": {"hexsha": "20282c1288c424f7e81349eef13e1ef1ef1f3508", "size": 4150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Recika/bitshare-core/get_dev_key.cpp", "max_stars_repo_name": "qingcai518/Recika", "max_stars_repo_head_hexsha": "06b3870ef07f2135c5ed99f6d7f5dddf773aeec6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T16:09:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-14T16:09:02.000Z", "max_issues_repo_path": "Recika/bitshare-core/get_dev_key.cpp", "max_issues_repo_name": "qingcai518/Recika", "max_issues_repo_head_hexsha": "06b3870ef07f2135c5ed99f6d7f5dddf773aeec6", "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": "Recika/bitshare-core/get_dev_key.cpp", "max_forks_repo_name": "qingcai518/Recika", "max_forks_repo_head_hexsha": "06b3870ef07f2135c5ed99f6d7f5dddf773aeec6", "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.4326241135, "max_line_length": 101, "alphanum_fraction": 0.7106024096, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "/* PREM NIRMAL\n   Fordham RCV Lab\n   Fordham University\n   Bronx NY 10458\n*/\n/*\n  07/2012\n  An implemtation of Churchill and Vardy's VHiSS algorithm,\n  using David Lowe's SIFT feature extractor.\n*/\n\n#include <cstdio>\n#include <iostream>\n#include <cv.h>\n#include <highgui.h>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include \"Aria.h\"\n\n#include \"defs.h\"\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\n\n#define HOMEIMAGE \"data/home.pgm\"\n#define HOMEKEY \"data/home.key\"\n#define IMG_WIDTH 1771\n#define IMG_HEIGHT 270\n#define DISTANCE 400\n#define EPS 2\n#define PERCENT 60\n\n/* -------------------- Local function prototypes ------------------------ */\nVector2d FindMatches(Image im1, Keypoint keys1, Image im2, Keypoint keys2, int imageCount);\nKeypoint CheckForMatch(Keypoint key, Keypoint klist);\nint DistSquared(Keypoint k1, Keypoint k2);\nImage CombineImagesHorizontally(Image im1, Image im2);\nImage CombineImagesVertically(Image im1, Image im2);\nIplImage *rotateImage(const IplImage *src, float angleDegrees);\n/*----------------------------- Routines ----------------------------------*/\nint main (int argc, char **argv)\n{\n  Image im1 = NULL, im2 = NULL;\n  Keypoint k1 = NULL, k2 = NULL;\n  int imageCount=1;\n  char imageName[100], keypointName[100], command[256];\n  double alpha;\n  Vector2d move;\n\n  /* ROBOT DECLARATIONS */\n  ArArgumentParser parser(&argc, argv); // set up our parser\n  ArSimpleConnector simpleConnector(&parser); // set up our simple connector\n  ArRobot robot; // declare robot object\n  //  ArSonarDevice sonar;\n  \n  /* INITIALIZATION OF CONNECTION TO ROBOT */\n  Aria::init(); // mandatory init\n  parser.loadDefaultArguments(); // load the default arguments \n  if (!simpleConnector.parseArgs() // check command line args\n      || !parser.checkHelpAndWarnUnparsed(1))\n    {    \n      simpleConnector.logOptions();\n      Aria::shutdown();\n      return 1;\n    }\n  if (!simpleConnector.connectRobot(&robot)) // ask for connection to robot\n    {\n      printf(\"Could not connect to robot... exiting\\n\");\n      Aria::shutdown();\n      return 1;\n    }\n\n  /* INITIALIZATION OF ROBOT*/\n  robot.runAsync(true); // commands processed in separate thread\n  robot.enableMotors(); // turn the power to the motors on\n  //  robot.addRangeDevice(&sonar); // add sonar (THIS IS UNNECCESARY FOR VH)\n  ArUtil::sleep(1000); // sleep time allows robot to initialise sonar, motors, etc\n\n  robot.setRotVelMax(30);\n  robot.setTransVelMax(80);\n\n  /*** CAPTURE HOME IMAGE ***/\n  cout<<endl<<\"Place robot at goal location, to capture home image..\"<<endl\n      <<\"Then press ENTER.\";\n  cin.get();\n  ArUtil::sleep(1000);\n  IplImage *homeImage, *homeGray;\n  system(\"mplayer tv:// -tv width=1024:height=768:device=/dev/video1:outfmt=rgb24 -frames 1 -vo jpeg:outdir=data\");\n  sleep(1);\n  system(\"mv data/00000001.jpg data/home.jpg\");\n  sleep(1);\n  system(\"./omnicamtools_test calib_results.txt data/home.jpg\");\n  sleep(1);\n  system(\"mv unwarped_image.jpg data/temphome.jpg\");\n \n  cout<<\"Home image captured and unwarped.\"<<endl;\n  \n  homeImage=cvLoadImage(\"data/temphome.jpg\",1);\n  homeGray=cvCreateImage(cvGetSize(homeImage),IPL_DEPTH_8U,1);\n  cvCvtColor(homeImage,homeGray,CV_RGB2GRAY);\n  cvReleaseImage(&homeImage);\n  cout<<\"Resizing home image..\"<<endl;\n  homeImage=cvCreateImage( cvSize((int)(homeGray->width*PERCENT/100),(int)(homeGray->height*PERCENT/100)), homeGray->depth, homeGray->nChannels );\n  cvResize(homeGray,homeImage);\n  cvReleaseImage(&homeGray);\n  homeImage=rotateImage(homeImage,180); // rotate by 180 deg\n  cvSaveImage(\"data/home.pgm\",homeImage);\n  remove(\"data/temphome.jpg\");\n  //  remove(\"data/home.jpg\");\n  \n  sleep(1);\n  \n  /*** OBTAIN SIFT FEATURES ***/\n  cout<<endl<<\"Obtaining SIFT features from home image and storing as home.key..\"<<endl;\n  system(\"./sift <data/home.pgm > data/home.key\");\n  /*** -------------------- ***/\n  sleep(2);\n  /******************************/\n\n  cout<<endl<<\"Now position robot away from goal location, \"\n      <<\"and press ENTER to home\";\n  cin.get();\n\n  IplImage *image,*gray;\n  char buf[100];\n  vector<double> angleList; angleList.clear();\n  vector<int> signList; signList.clear();\n\n  do\n    {  \n      robot.stop();\n      ArUtil::sleep(1000);\n\n      system(\"mplayer tv:// -tv width=1024:height=768:device=/dev/video1:outfmt=rgb24 -frames 1 -vo jpeg:outdir=data\");\n      sleep(1);\n      system(\"mv data/00000001.jpg data/image.jpg\");\n      sleep(1);\n      system(\"./omnicamtools_test calib_results.txt data/image.jpg\");\n      sleep(1);\n      sprintf(buf,\"mv data/image.jpg data/img%d.jpg\",imageCount);\n      system(buf);\n      system(\"mv unwarped_image.jpg data/image.jpg\");\n      \n      cout<<endl<<\"Current image captured and unwarped.\"<<endl;\n\n      /* load temp.jpg into img */\n      image=cvLoadImage(\"data/image.jpg\",1);\n      ArUtil::sleep(1000);\n      gray=cvCreateImage(cvGetSize(image),IPL_DEPTH_8U,1);\n      cvCvtColor(image,gray,CV_RGB2GRAY);\n      cvReleaseImage(&image);\n      image=cvCreateImage( cvSize((int)(gray->width*PERCENT/100),(int)(gray->height*PERCENT/100)), gray->depth, gray->nChannels );\n      cvResize(gray,image);\n      sprintf(imageName,\"data/image%d.pgm\",imageCount);\n      image=rotateImage(image,180); // rotate by 180 deg\n      cvSaveImage(imageName,image);\n      sprintf(keypointName,\"data/image%d.key\",imageCount);\n      remove(\"data/image.jpg\");\n      cvReleaseImage(&gray);\n      cvReleaseImage(&image);\n\n      /*** OBTAIN SIFT FEATURES ***/\n      snprintf(command,256,\"./sift <%s >%s\",imageName,keypointName);\n      system(command);\n      /*** -------------------- ***/\n\n      im1=ReadPGMFile(HOMEIMAGE);\n      k1=ReadKeyFile(HOMEKEY);\n      im2=ReadPGMFile(imageName);\n      k2=ReadKeyFile(keypointName);\n  \n      /* determine movement vector using SIFT features */\n      move=FindMatches(im1, k1, im2, k2,imageCount);\n      alpha=move(0)*180/M_PI;\n\n      angleList.push_back(alpha);\n      signList.push_back((int)move(1));\n\n      if(alpha!=alpha)\n\t{\n\t  cout<<\"Alpha = \"<<alpha<<endl;\n\t  cout<<\"Unable to complete homing. Exiting..\"<<endl;\n\t  return -1;\n\t}\n      else// if(fabs(alpha)>=EPS && alpha==alpha)\n\t{\n\t  cout<<\"Robot orienting by \"<<alpha<<\"degrees. \";\n\t  if(move(1)>0)\n\t    cout<<\"and moving forwards by \"<<DISTANCE<<\"mm\"<<endl;\n\t  else\n\t    cout<<\"and moving backwards by \"<<DISTANCE<<\"mm\"<<endl;\n\n\t  ArUtil::sleep(1000);\n\t  robot.setDeltaHeading(alpha); // orient robot towards goal\n\t  ArUtil::sleep(2000);\n\t  robot.move(DISTANCE*move(1)); // move forwards or backwards depending on move(1)\n\t  ArUtil::sleep(4000+(DISTANCE*10));\n\t}\n      imageCount++;\n    }\n  while(imageCount<10);\n\n  cout<<\"Log of all angles and direction:\"<<endl;\n  vector<double>::iterator dit;\n  vector<int>::iterator iit;\n  for(dit=angleList.begin(),iit=signList.begin();dit!=angleList.end();dit++,iit++)\n    cout<<\"\\talpha=\"<<*dit<<\", sign=\"<<*iit<<endl;\n\n  angleList.clear();\n  signList.clear();\n\n  return 0;\n}\n/* Given a pair of images and their keypoints, pick the first keypoint\n   from one image and find its closest match in the second set of\n   keypoints.\n*/\nVector2d FindMatches(Image im1, Keypoint keys1, Image im2, Keypoint keys2, int imageCount)\n{\n  Keypoint k,match;\n  int count=0;\n  double alpha=0,delta=0;\n  //  vector< Vector2d,aligned_allocator<Vector2d> > unitVec;\n  Image result;\n  result=CombineImagesVertically(im1,im2);\n\n  vector<Keypoint> mPOS1, mPOS2, mNEG1, mNEG2;\n  vector<double> thetaPOS, thetaNEG;\n  Vector2d move;\n\n  /* Match the keys in list keys1 to their best matches in keys2 */\n  for(k=keys1;k!=NULL;k=k->next) // home image\n    {\n      match=CheckForMatch(k,keys2); // k = home img, keys2 = current image\n      if(match!=NULL) \n\t{\n\t  delta = k->scale - match->scale;\n\t  DrawLine(result, (int) k->row, (int) k->col,\n\t\t   (int) (match->row + im1->rows), (int) match->col);\n\n\t  // STORE mPOS and mNEG\n\t  if(delta>=0)\n\t    {\n\t      mPOS1.push_back(k);\n\t      mPOS2.push_back(match);\n\t      // 360 degrees field of view\n\t      thetaPOS.push_back((match->col*(2*M_PI/IMG_WIDTH)) - M_PI);\n\t    }\n\t  if(delta<0)\n\t    {\n\t      mNEG1.push_back(k);\n\t      mNEG2.push_back(match);\n\t      // 360 degrees field of view\n\t      thetaNEG.push_back((match->col*(2*M_PI/IMG_WIDTH)) - M_PI);\n\t    }\n\t  count++;\n\t}//end if(match..\n    }//end for(k=keys1..\n\n  FILE *matched;\n  char matchfileName[100];\n  sprintf(matchfileName,\"data/matched%d.pgm\",imageCount);\n  matched=fopen(matchfileName,\"w\");\n  WritePGM(matched, result);\n  free_img(result);\n  fclose(matched);\n  cout<<\"Wrote '\"<<matchfileName<<\"'.\\n\";\n\n  if(count==0)\n    {\n      cout<<\"No matches found. Exiting..\\n\";\n      abort();\n    }\n  \n  fprintf(stderr,\"Found a total of %d matches.\\n\", count);\n\n  double POSthetaAverage, NEGthetaAverage;\n  vector<double>::iterator pit,nit;\n  double sintheta=0, costheta=0;\n  for(pit=thetaPOS.begin();pit!=thetaPOS.end();pit++)\n    {\n      sintheta+=sin(*pit);\n      costheta+=cos(*pit);\n    }\n  if(sintheta!=0 && costheta!=0)\n    POSthetaAverage=atan(sintheta/costheta);\n  else\n    POSthetaAverage=0;\n\n  sintheta=0; costheta=0;\n\n  for(nit=thetaNEG.begin();nit!=thetaNEG.end();nit++)\n    {\n      sintheta+=sin(*nit);\n      costheta+=cos(*nit);\n    }\n  if(sintheta!=0 && costheta!=0)\n    NEGthetaAverage=atan(sintheta/costheta);\n  else\n    NEGthetaAverage=0;\n\n  sintheta=0; costheta=0;\n\n  double s,c;\n  cout<<\"sin(POSthetaAverage) = \"<<sin(POSthetaAverage)<<endl;\n  cout<<\"cos(POSthetaAverage) = \"<<cos(POSthetaAverage)<<endl;\n  cout<<\"sin(NEGthetaAverage) = \"<<sin(NEGthetaAverage)<<endl;\n  cout<<\"cos(NEGthetaAverage) = \"<<cos(NEGthetaAverage)<<endl;\n\n  s=thetaPOS.size()*sin(POSthetaAverage) + thetaNEG.size()*(sin(NEGthetaAverage)+M_PI);\n  c=thetaPOS.size()*cos(POSthetaAverage) + thetaNEG.size()*(cos(NEGthetaAverage)+M_PI);\n\n  cout<<\"thetaPOS.size(): \"<<thetaPOS.size()<<\" thetaNEG.size(): \"<<thetaNEG.size()<<endl;\n\n  double sign=1;\n  if (fabs(atan2(s,c))>=(M_PI/2))\n    sign=-1;\n  else sign=1;\n  cout<<\"s = \"<<s<<\", c = \"<<c<<endl;\n  cout<<\"atan2(s,c) = \"<<atan2(s,c)<<endl;\n  alpha=atan2(s,c);\n\n  /** CLEAR MEMORY **/\n  mPOS1.clear(); mPOS2.clear();\n  mNEG1.clear(); mNEG2.clear();\n  thetaPOS.clear(); thetaNEG.clear();\n\n  move(0)=alpha;\n  move(1)=sign;\n\n  return move;\n\n}//end void FindMatches..\n\n\n/* This searches through the keypoints in klist for the two closest\n   matches to key.  If the closest is less than 0.6 times distance to\n   second closest, then return the closest match.  Otherwise, return\n   NULL.\n*/\nKeypoint CheckForMatch(Keypoint key, Keypoint klist)\n{\n  int dsq, distsq1 = 100000000, distsq2 = 100000000;\n  Keypoint k, minkey = NULL;\n\n  /* Find the two closest matches, and put their squared distances in\n     distsq1 and distsq2.\n  */\n  for (k = klist; k != NULL; k = k->next) {\n    dsq = DistSquared(key, k);\n\n    if (dsq < distsq1) {\n      distsq2 = distsq1;\n      distsq1 = dsq;\n      minkey = k;\n    } else if (dsq < distsq2) {\n      distsq2 = dsq;\n    }\n  }\n\n  /* Check whether closest distance is less than 0.6 of second. */\n  if (10 * 10 * distsq1 < 6 * 6 * distsq2)\n    return minkey;\n  else return NULL;\n}\n\n\n/* Return squared distance between two keypoint descriptors.\n */\nint DistSquared(Keypoint k1, Keypoint k2)\n{\n  int i, dif, distsq = 0;\n  unsigned char *pk1, *pk2;\n\n  pk1 = k1->descrip;\n  pk2 = k2->descrip;\n\n  for (i = 0; i < 128; i++) {\n    dif = (int) *pk1++ - (int) *pk2++;\n    distsq += dif * dif;\n  }\n  return distsq;\n}\n\nImage CombineImagesHorizontally(Image im1, Image im2)\n{\n  int rows, cols, r, c;\n  Image result;\n  rows = MAX(im1->rows,im2->rows);\n  cols = im1->cols+im2->cols;\n  result = CreateImage(rows,cols);\n  /* Set all pixels to 0,5, so that blank regions are grey. */\n  for (r = 0; r < rows; r++)\n    for (c = 0; c < cols; c++)\n      result->pixels[r][c] = 0.5;\n  /* Copy images into result. */\n  for (r = 0; r < im1->rows; r++)\n    for (c = 0; c < im1->cols; c++)\n      result->pixels[r][c] = im1->pixels[r][c];\n  for (r = 0; r < im2->rows; r++)\n    for (c = 0; c < im2->cols; c++)\n      result->pixels[r][c+im1->cols] = im2->pixels[r][c];\n\n  return result;\n}\n\nImage CombineImagesVertically(Image im1, Image im2)\n{\n  int rows, cols, r, c;\n  Image result;\n\n  rows = im1->rows + im2->rows;\n  cols = MAX(im1->cols, im2->cols);\n  result = CreateImage(rows, cols);\n\n  /* Set all pixels to 0,5, so that blank regions are grey. */\n  for (r = 0; r < rows; r++)\n    for (c = 0; c < cols; c++)\n      result->pixels[r][c] = 0.5;\n\n  /* Copy images into result. */\n  for (r = 0; r < im1->rows; r++)\n    for (c = 0; c < im1->cols; c++)\n      result->pixels[r][c] = im1->pixels[r][c];\n  for (r = 0; r < im2->rows; r++)\n    for (c = 0; c < im2->cols; c++)\n      result->pixels[r + im1->rows][c] = im2->pixels[r][c];\n\n  return result;\n}\n\n// Rotate the image clockwise (or counter-clockwise if negative).\n// Remember to free the returned image.\nIplImage *rotateImage(const IplImage *src, float angleDegrees)\n{\n  // Create a map_matrix, where the left 2x2 matrix\n  // is the transform and the right 2x1 is the dimensions.\n  float m[6];\n  CvMat M = cvMat(2, 3, CV_32F, m);\n  int w = src->width;\n  int h = src->height;\n  float angleRadians = angleDegrees * ((float)CV_PI / 180.0f);\n  m[0] = (float)( cos(angleRadians) );\n  m[1] = (float)( sin(angleRadians) );\n  m[3] = -m[1];\n  m[4] = m[0];\n  m[2] = w*0.5f;  \n  m[5] = h*0.5f;  \n\n  // Make a spare image for the result\n  CvSize sizeRotated;\n  sizeRotated.width = cvRound(w);\n  sizeRotated.height = cvRound(h);\n\n  // Rotate\n  IplImage *imageRotated = cvCreateImage( sizeRotated,\n\t\t\t\t\t  src->depth, src->nChannels );\n\n  // Transform the image\n  cvGetQuadrangleSubPix( src, imageRotated, &M);\n\n  return imageRotated;\n}\n", "meta": {"hexsha": "a5c001f0c60162186c7761431cc379a21a047dbf", "size": 13628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vh.cpp", "max_stars_repo_name": "premnirmal/Homing-in-Scale-Space", "max_stars_repo_head_hexsha": "b7740058faea0cffc34dbe05dcce557f19a17a01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-03T00:31:21.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-03T00:31:21.000Z", "max_issues_repo_path": "vh.cpp", "max_issues_repo_name": "premnirmal/Homing-in-Scale-Space", "max_issues_repo_head_hexsha": "b7740058faea0cffc34dbe05dcce557f19a17a01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vh.cpp", "max_forks_repo_name": "premnirmal/Homing-in-Scale-Space", "max_forks_repo_head_hexsha": "b7740058faea0cffc34dbe05dcce557f19a17a01", "max_forks_repo_licenses": ["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.2446351931, "max_line_length": 146, "alphanum_fraction": 0.6372174934, "num_tokens": 4127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "#include \"visualization/feature-matches-visualization.h\"\n\n#include <vector>\n\n#include <Eigen/Dense>\n#include <aslam/cameras/camera.h>\n#include <aslam/matcher/match-helpers.h>\n#include <aslam/matcher/match-visualization.h>\n#include <glog/logging.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\nnamespace visualization {\n\nvoid saveOpenCvMatchesAndFeaturesAsImage(\n    const aslam::VisualFrame& frame_A, const cv::Mat& image_A,\n    const aslam::VisualFrame& frame_B, const cv::Mat& image_B,\n    const aslam::OpenCvMatches& matches_A_B, const std::string& filename,\n    aslam::FeatureVisualizationType visualization_type, vi_map::VIMap* map) {\n  CHECK_NOTNULL(map);\n\n  if (matches_A_B.empty()) {\n    VLOG(1) << \"No matches found.\";\n  }\n\n  if (frame_A.getNumKeypointMeasurements() == 0 ||\n      frame_B.getNumKeypointMeasurements() == 0) {\n    VLOG(1) << \"No features found.\";\n    return;\n  }\n\n  // Scale the keypoint score to sth we can visualize.\n  const Eigen::Matrix2Xd& key_point_matrix_A(frame_A.getKeypointMeasurements());\n  const Eigen::Matrix2Xd& key_point_matrix_B(frame_B.getKeypointMeasurements());\n  const Eigen::VectorXd& key_point_scores_A = frame_A.getKeypointScores();\n  const Eigen::VectorXd& key_point_scores_B = frame_B.getKeypointScores();\n  const double max_score =\n      std::max(key_point_scores_A.maxCoeff(), key_point_scores_B.maxCoeff());\n  const double min_score =\n      std::min(key_point_scores_A.minCoeff(), key_point_scores_B.minCoeff());\n  const double score_range = std::max(max_score - min_score, 1.0);\n  const double max_key_point_size = 30.0;\n  const double min_key_point_size = 5.0;\n\n  const Eigen::VectorXd& key_point_orientation_A =\n      frame_A.getKeypointOrientations();\n  const Eigen::VectorXd& key_point_orientation_B =\n      frame_B.getKeypointOrientations();\n\n  // Convert the keypoints to cv::KeyPoint.\n  std::vector<cv::KeyPoint> key_points_A, key_points_B;\n  for (uint i = 0; i < frame_A.getNumKeypointMeasurements(); ++i) {\n    double key_point_size = std::max(\n        (key_point_scores_A(i) - min_score) / score_range * max_key_point_size,\n        min_key_point_size);\n    key_points_A.emplace_back(\n        cv::KeyPoint(\n            key_point_matrix_A(0, i), key_point_matrix_A(1, i), key_point_size,\n            key_point_orientation_A(i)));\n  }\n  for (uint i = 0; i < frame_B.getNumKeypointMeasurements(); ++i) {\n    double key_point_size = std::max(\n        (key_point_scores_B(i) - min_score) / score_range * max_key_point_size,\n        min_key_point_size);\n    key_points_B.emplace_back(\n        cv::KeyPoint(\n            key_point_matrix_B(0, i), key_point_matrix_B(1, i), key_point_size,\n            key_point_orientation_B(i)));\n  }\n\n  // Convert color images to grayscale if necessary.\n  cv::Mat grayscale_image_A, grayscale_image_B;\n  bool is_color_image = image_A.channels() == 3;\n  if (is_color_image) {\n    cv::cvtColor(image_A, grayscale_image_A, CV_BGR2GRAY);\n    cv::cvtColor(image_B, grayscale_image_B, CV_BGR2GRAY);\n  } else {\n    grayscale_image_A = image_A;\n    grayscale_image_B = image_B;\n  }\n\n  // Write features and matches to image file.\n  cv::Mat images_w_matches;\n  aslam::drawKeyPointsAndMatches(\n      grayscale_image_A, key_points_A, grayscale_image_B, key_points_B,\n      matches_A_B, visualization_type, &images_w_matches);\n  cv::imwrite(filename, images_w_matches);\n}\n\nvoid saveOpenCvMatchesAndFeaturesAsImage(\n    const aslam::VisualFrame& frame_A, const aslam::VisualFrame& frame_B,\n    const aslam::OpenCvMatches& matches_A_B, const std::string& filename,\n    aslam::FeatureVisualizationType visualization_type, vi_map::VIMap* map) {\n  CHECK_NOTNULL(map);\n\n  if (!frame_A.hasRawImage() || !frame_B.hasRawImage()) {\n    LOG(ERROR) << \"One of the frames has no image!\";\n    return;\n  }\n\n  cv::Mat image_A = frame_A.getRawImage();\n  cv::Mat image_B = frame_B.getRawImage();\n\n  if (image_A.empty() || image_B.empty()) {\n    LOG(ERROR) << \"One of the images is empty!\";\n    return;\n  }\n\n  saveOpenCvMatchesAndFeaturesAsImage(\n      frame_A, image_A, frame_B, image_B, matches_A_B, filename,\n      visualization_type, map);\n}\n\nvoid saveOpenCvMatchesAndFeaturesAsImage(\n    const aslam::VisualFrame& frame_A, const vi_map::Vertex& vertex_A,\n    const aslam::VisualFrame& frame_B, const vi_map::Vertex& vertex_B,\n    const aslam::OpenCvMatches& matches_A_B, const std::string& filename,\n    aslam::FeatureVisualizationType visualization_type,\n    const backend::ResourceType image_resource_type, vi_map::VIMap* map) {\n  CHECK_NOTNULL(map);\n\n  const unsigned int current_frame_idx =\n      vertex_A.getVisualFrameIndex(frame_A.getId());\n  const unsigned int next_frame_idx =\n      vertex_B.getVisualFrameIndex(frame_B.getId());\n\n  // Load image resources.\n  cv::Mat image_A, image_B;\n  if (!map->getFrameResource<cv::Mat>(\n          vertex_A, current_frame_idx, image_resource_type, &image_A)) {\n    LOG(ERROR) << \"Frame \" << current_frame_idx << \" of vertex \"\n               << vertex_A.id() << \" has no resource of type \"\n               << static_cast<int>(image_resource_type);\n    return;\n  }\n  if (!map->getFrameResource<cv::Mat>(\n          vertex_B, next_frame_idx, image_resource_type, &image_B)) {\n    LOG(ERROR) << \"Frame \" << next_frame_idx << \" of vertex \" << vertex_B.id()\n               << \" has no resource of type \"\n               << static_cast<int>(image_resource_type);\n    return;\n  }\n\n  saveOpenCvMatchesAndFeaturesAsImage(\n      frame_A, image_A, frame_B, image_B, matches_A_B, filename,\n      visualization_type, map);\n}\n\nvoid saveLandmarkMatchesAndFeaturesAsImage(\n    const aslam::VisualFrame& frame_A, const vi_map::Vertex& vertex_A,\n    const aslam::VisualFrame& frame_B, const vi_map::Vertex& vertex_B,\n    const std::string& filename,\n    aslam::FeatureVisualizationType visualization_type,\n    const backend::ResourceType image_resource_type, vi_map::VIMap* map) {\n  CHECK_NOTNULL(map);\n\n  aslam::OpenCvMatches matches_A_B;\n  int index_A = 0;\n  int index_B = 0;\n  float distance = 0.0;\n  const unsigned int current_frame_idx =\n      vertex_A.getVisualFrameIndex(frame_A.getId());\n  const unsigned int next_frame_idx =\n      vertex_B.getVisualFrameIndex(frame_B.getId());\n\n  vi_map::LandmarkIdList landmark_ids_A;\n  vi_map::LandmarkIdList landmark_ids_B;\n  vertex_A.getFrameObservedLandmarkIds(current_frame_idx, &landmark_ids_A);\n  vertex_B.getFrameObservedLandmarkIds(next_frame_idx, &landmark_ids_B);\n\n  for (const vi_map::LandmarkId& landmark_id_A : landmark_ids_A) {\n    for (const vi_map::LandmarkId& landmark_id_B : landmark_ids_B) {\n      if (landmark_id_A.isValid() && landmark_id_B.isValid()) {\n        if (landmark_id_A == landmark_id_B) {\n          vi_map::Landmark landmark = map->getLandmark(landmark_id_A);\n          const vi_map::KeypointIdentifierList& observations =\n              landmark.getObservations();\n          bool found_observation_for_current_vertex = false;\n          bool found_observation_for_next_vertex = false;\n\n          for (vi_map::KeypointIdentifier observation : observations) {\n            if (observation.frame_id.vertex_id == vertex_A.id() &&\n                observation.frame_id.frame_index == current_frame_idx) {\n              found_observation_for_current_vertex = true;\n              index_A = observation.keypoint_index;\n              distance = static_cast<float>(frame_A.getKeypointScore(index_A));\n            } else if (\n                observation.frame_id.vertex_id == vertex_B.id() &&\n                observation.frame_id.frame_index == next_frame_idx) {\n              found_observation_for_next_vertex = true;\n              index_B = observation.keypoint_index;\n              distance = static_cast<float>(frame_B.getKeypointScore(index_B));\n            }\n          }\n          if (found_observation_for_current_vertex &&\n              found_observation_for_next_vertex) {\n            matches_A_B.push_back(cv::DMatch(index_A, index_B, distance));\n          }\n        }\n      }\n    }\n  }\n  saveOpenCvMatchesAndFeaturesAsImage(\n      frame_A, vertex_A, frame_B, vertex_B, matches_A_B, filename,\n      visualization_type, image_resource_type, map);\n}\n}  // namespace visualization\n", "meta": {"hexsha": "17f2584a6f65b64fec251bace6396e6be4d5deac", "size": 8173, "ext": "cc", "lang": "C++", "max_stars_repo_path": "visualization/src/feature-matches-visualization.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": "visualization/src/feature-matches-visualization.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": "visualization/src/feature-matches-visualization.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": 39.2932692308, "max_line_length": 80, "alphanum_fraction": 0.7039030956, "num_tokens": 2054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.1995380783911481}}
{"text": "//   Copyright 2015 Patrick Putnam\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 CLOTHO_BATCH_CROSSOVER_TASK_POPULATION_SPACE_HPP_\n#define CLOTHO_BATCH_CROSSOVER_TASK_POPULATION_SPACE_HPP_\n\n#include \"clotho/data_spaces/population_space/population_space.hpp\"\n#include <boost/random/bernoulli_distribution.hpp>\n#include \"clotho/data_spaces/crossover/position_classifier.hpp\"\n#include \"clotho/data_spaces/generators/position_distribution_helper.hpp\"\n#include \"clotho/data_spaces/generators/crossover_event_distribution_helper.hpp\"\n\n#include \"clotho/data_spaces/crossover/block_crossover.hpp\"\n\nnamespace clotho {\nnamespace genetics {\n\ntemplate < class RNG, class MatePairType, class BlockType, class WeightType, class AlleleSpaceType >\nclass batch_crossover_task< RNG, MatePairType, population_space< BlockType, WeightType > , AlleleSpaceType > : public task {\npublic:\n    typedef batch_crossover_task< RNG, MatePairType, population_space< BlockType, WeightType >, AlleleSpaceType > self_type;\n\n    typedef population_space< BlockType, WeightType >   space_type;\n    typedef AlleleSpaceType                             allele_type;\n    typedef RNG                                         random_engine_type;\n\n    typedef typename space_type::genome_type            genome_type;\n\n    typedef typename space_type::individual_type        individual_type;\n\n    typedef MatePairType                                        mate_pair_type;\n    typedef typename mate_pair_type::iterator                   iterator;\n    typedef typename mate_pair_type::const_iterator             const_iterator;\n\n    typedef PositionClassifier< typename allele_type::position_vector >          classifier_type;\n    typedef typename classifier_type::event_type                                event_type;\n\n    typedef typename position_distribution_helper< typename allele_type::position_type >::type position_distribution_type;\n    typedef typename crossover_event_distribution_helper< double >::type event_distribution_type;\n\n    batch_crossover_task( random_engine_type * rng, space_type * parent, space_type * offspring, allele_type * alleles, unsigned int off_idx, const_iterator first, const_iterator last, double recomb_rate, double seq_bias ) :\n        m_rng(rng)\n        , m_parental( parent )\n        , m_offspring( offspring )\n        , m_alleles( alleles )\n        , m_parents(first, last)\n        , m_offspring_index(off_idx)\n        , m_recomb_rate(recomb_rate)\n        , m_seq_bias( seq_bias )\n    { }\n\n    batch_crossover_task( const self_type & other ) :\n        m_rng( other.m_rng )\n        , m_parental( other.m_parental )\n        , m_offspring( other.m_offspring )\n        , m_alleles( other.m_alleles )\n        , m_parents( other.m_parents )\n        , m_offspring_index( other.m_offspring_index )\n        , m_recomb_rate( other.m_recomb_rate )\n        , m_seq_bias( other.m_seq_bias )\n    { }\n\n    void operator()() {\n        event_distribution_type     event_dist( m_recomb_rate);\n        boost::random::bernoulli_distribution< double > bias_dist( m_seq_bias);\n\n        iterator mate_it = m_parents.begin(), mate_end = m_parents.end();\n\n#ifdef DEBUGGING\n        BOOST_LOG_TRIVIAL(debug) << \"Starting batch crossover task\";\n#endif // DEBUGGING\n        size_t i = m_offspring_index;\n        while( mate_it != mate_end ) {\n            \n            assert( mate_it->first < m_parental->individual_count() );\n\n            unsigned int offs = mate_it->first;\n\n            individual_type ind = m_parental->getIndividual( offs );\n            genome_type c0 = m_offspring->create_sequence();\n\n            event_type evts;\n\n            fill_events( evts, event_dist( *m_rng ) );\n            classifier_type cfier0( &m_alleles->getPositions(), evts );\n            bool _swap = bias_dist( *m_rng );\n\n#ifdef DEBUGGING\n//            BOOST_LOG_TRIVIAL(debug) << mate_it->first << \"; Crossover s0: \" << ind.first << \" - \" << ind.first.size() << \"; s1: \" << ind.second << \" - \" << ind.second.size() << \"; child: \" << c0.first << \"; event size: \" << evts.size();\n#endif  // DEBUGGING\n            run_crossover_task( cfier0, ind.first, ind.second, c0, _swap );\n\n            assert( mate_it->second < m_parental->individual_count() );\n\n            genome_type c1 = m_offspring->create_sequence();\n            ind = m_parental->getIndividual( mate_it->second );\n#ifdef DEBUGGING\n//            BOOST_LOG_TRIVIAL(debug) << mate_it->second << \"; Crossover s0: \" << ind.first << \" - \" << ind.first.size() << \"; s1: \" << ind.second << \" - \" << ind.second.size() << \"; child: \" << c1.first << \"; event size: \" << evts.size();\n#endif  // DEBUGGING\n\n            event_type evts1;\n\n            fill_events( evts1, event_dist( *m_rng ) );\n\n            classifier_type cfier1( &m_alleles->getPositions(), evts1 );\n\n            _swap = bias_dist( *m_rng );\n            run_crossover_task( cfier1, ind.first, ind.second, c1, _swap);\n\n            m_offspring->setIndividual( i++, c0, c1 );\n\n            ++mate_it;\n        }\n\n#ifdef DEBUGGING\n        BOOST_LOG_TRIVIAL(debug) << \"End Batch Crossover Task\";\n#endif // DEBUGGING\n    }\n\n    virtual ~batch_crossover_task() {}\n\nprotected:\n\n    inline void fill_events( event_type & evt, unsigned int N ) {\n        while( N-- ) {\n            evt.push_back( m_pos_dist( *m_rng ) );\n        }\n    }\n\n    event_type make_events( unsigned int N ) {\n        event_type res;\n\n        while( N-- ) {\n            res.push_back( m_pos_dist( *m_rng ) );\n        }\n\n        return res;\n    }\n\n    void run_crossover_task( classifier_type & cls, genome_type & top, genome_type & bottom, genome_type & res, bool should_swap_strands ) {\n\n        if( cls.event_count() == 0 ) {\n            // there are no crossover cls\n            // therefore, offspring strand will be a copy of the top strand\n            res = ((should_swap_strands) ? bottom : top);\n        } else if( should_swap_strands ) {\n            run_crossover_task( cls, bottom, top, res );\n        } else {\n            run_crossover_task( cls, top, bottom, res );\n        }\n    }\n\n    void run_crossover_task( classifier_type & cls, genome_type & top, genome_type & bottom, genome_type & res ) {\n        typedef typename space_type::base_genome_type::sequence_type::const_sequence_iterator const_iterator;\n        typedef block_crossover< classifier_type, BlockType >       crossover_type;\n        typedef BlockType                                           block_type;\n\n        crossover_type xover( cls );\n        \n        const_iterator tb, te, bb, be;\n        if( top ) {\n            tb = top->begin_sequence();\n            te = top->end_sequence();\n        } else {\n            te = tb;\n        }\n\n        if( bottom ) {\n            bb = bottom->begin_sequence();\n            be = bottom->end_sequence();\n        } else {\n            be = bb;\n        }\n\n        unsigned int i = 0;\n//        bool top_equal = true;\n//        bool bottom_equal = true;\n        while( true ) {\n            if( tb == te ) {\n                while( bb != be ) {\n                    const block_type t = crossover_type::bit_helper_type::ALL_UNSET;\n                    const block_type b = *bb++;\n                    const block_type o = xover.crossover( t, b, i );\n//                    top_equal = top_equal && (o == t );\n//                    bottom_equal = bottom_equal && (o == b);\n                    res->append_sequence(o);\n                    i += crossover_type::bit_helper_type::BITS_PER_BLOCK;\n                }\n                break;\n            } else if( bb == be ) {\n                while( tb != te ) {\n                    const block_type t = *tb++;\n                    const block_type b = crossover_type::bit_helper_type::ALL_UNSET;\n                    const block_type o = xover.crossover( t, b, i );\n//                    bottom_equal = bottom_equal && (o == b );\n//                    top_equal = top_equal && (o == t);\n                    res->append_sequence(o);\n                    i += crossover_type::bit_helper_type::BITS_PER_BLOCK;\n                }\n                break;\n            }\n\n            const block_type t = *tb++;\n            const block_type b = *bb++;\n\n            const block_type o = xover.crossover(t, b, i );\n\n//            bottom_equal = bottom_equal && (o == b );\n//            top_equal = top_equal && (o == t);\n\n            res->append_sequence( o );\n            i += crossover_type::bit_helper_type::BITS_PER_BLOCK;\n        }\n\n//        if( top_equal ) {\n//            res = top;\n//        } else if( bottom_equal ) {\n//            res = bottom;\n//        }\n    }\n\n    random_engine_type  * m_rng;\n    space_type          * m_parental, * m_offspring;\n    allele_type         * m_alleles;\n\n    mate_pair_type m_parents;\n\n    unsigned int m_offspring_index;\n\n    double m_recomb_rate, m_seq_bias;\n\n    position_distribution_type  m_pos_dist;\n};\n\n}   // namespace genetics\n}   // namespace clotho\n\n#endif  // CLOTHO_BATCH_CROSSOVER_TASK_POPULATION_SPACE_HPP_\n\n", "meta": {"hexsha": "d01e2a82e2e6865cf7697b49bff11a2cf6a85125", "size": 9480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clotho/data_spaces/crossover/batch_crossover_task_population_space.hpp", "max_stars_repo_name": "putnampp/clotho", "max_stars_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T21:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:26:54.000Z", "max_issues_repo_path": "include/clotho/data_spaces/crossover/batch_crossover_task_population_space.hpp", "max_issues_repo_name": "putnampp/clotho", "max_issues_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T21:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-23T12:41:00.000Z", "max_forks_repo_path": "include/clotho/data_spaces/crossover/batch_crossover_task_population_space.hpp", "max_forks_repo_name": "putnampp/clotho", "max_forks_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "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": 37.92, "max_line_length": 240, "alphanum_fraction": 0.6014767932, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.1995380783911481}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2020-2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, 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_STRATEGIES_INDEX_SPHERICAL_HPP\n#define BOOST_GEOMETRY_STRATEGIES_INDEX_SPHERICAL_HPP\n\n\n#include <boost/geometry/strategies/distance/spherical.hpp>\n#include <boost/geometry/strategies/index/services.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace index\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename RadiusTypeOrSphere, typename CalculationType>\nclass spherical\n    : public strategies::distance::detail::spherical<RadiusTypeOrSphere, CalculationType>\n{\n    using base_t = strategies::distance::detail::spherical<RadiusTypeOrSphere, CalculationType>;\n\npublic:\n    spherical() = default;\n\n    template <typename RadiusOrSphere>\n    explicit spherical(RadiusOrSphere const& radius_or_sphere)\n        : base_t(radius_or_sphere)\n    {}\n};\n\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\ntemplate <typename CalculationType = void>\nclass spherical\n    : public strategies::index::detail::spherical<void, CalculationType>\n{};\n\n\nnamespace services\n{\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, spherical_tag>\n{\n    using type = strategies::index::spherical<>;\n};\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, spherical_equatorial_tag>\n{\n    using type = strategies::index::spherical<>;\n};\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, spherical_polar_tag>\n{\n    using type = strategies::index::spherical<>;\n};\n\n\n} // namespace services\n\n\n}}}} // namespace boost::geometry::strategy::index\n\n#endif // BOOST_GEOMETRY_STRATEGIES_INDEX_SPHERICAL_HPP\n", "meta": {"hexsha": "c3502207b796df3decc50e2f5bc54e4de1501fbf", "size": 1827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/index/spherical.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/strategies/index/spherical.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/strategies/index/spherical.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": 22.2804878049, "max_line_length": 96, "alphanum_fraction": 0.7717569787, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.1995380783911481}}
{"text": "// Copyright <disenone>\n\n#include <unordered_map>\n#include <iostream>\n#include <vector>\n#include <cmath>\n\n#define BOOST_TEST_MODULE test_cross\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/included/unit_test.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/range/irange.hpp>\n\n#include <common/nuid.hpp>\n#include <common/silence_unused.hpp>\n#include <cross/cross.hpp>\n\n// #include <gperftools/profiler.h>\n\nusing namespace aoi;\nusing namespace aoi::cross;\n\nBOOST_AUTO_TEST_SUITE(test_cross)\n\nclass Player;\n\n\nclass CrossAoiTest: public CrossAoi {\n public:\n  CrossAoiTest(): CrossAoi(0, 0, 0, 0, 0, 0, 0) {}\n\n  CrossAoiTest(float map_bound_xmin, float map_bound_xmax, float map_bound_zmin,\n               float map_bound_zmax, size_t beacon_x, size_t beacon_z, float beacon_radius)\n    : CrossAoi(map_bound_xmin, map_bound_xmax, map_bound_zmin,\n               map_bound_zmax, beacon_x, beacon_z, beacon_radius)\n  {}\n\nfriend class Player;\n};\n\n\nclass Player {\n public:\n  Player() : nuid_(GenNuid()), pos_(0, 0, 0) {}\n  Player(Nuid nuid, Pos pos) : nuid_(nuid), pos_(pos) {}\n\n public:\n  inline Nuid AddSensor(float radius, bool log = false) {\n    auto sensor_id = GenNuid();\n    aoi_->AddSensor(nuid_, sensor_id, radius);\n    if (log) {\n      printf(\"Player %lu Add Sensor %lu, radius %f\\n\", nuid_, sensor_id, radius);\n    }\n    return sensor_id;\n  }\n\n  inline void AddToAoi(CrossAoiTest* aoi, bool log = false) {\n    aoi_ = aoi;\n    aoi_->AddPlayer(nuid_, pos_.x, pos_.y, pos_.z);\n    player_aoi_ = aoi_->player_map_.find(nuid_)->second.get();\n\n    if (log) {\n      printf(\"Add Player: %lu, Pos(%f, %f, %f)\\n\",\n            nuid_, pos_.x, pos_.y, pos_.z);\n    }\n  }\n\n  inline void RemoveFromAoi(bool log = false) {\n    if (log) {\n      printf(\"Remove Player: %lu, Pos(%f, %f, %f)\\n\",\n            nuid_, pos_.x, pos_.y, pos_.z);\n    }\n    aoi_->RemovePlayer(nuid_);\n    aoi_ = nullptr;\n    player_aoi_ = nullptr;\n  }\n\n  inline void MoveDelta(float x, float y, float z) {\n    MoveTo(pos_.x + x, pos_.y + y, pos_.z + z);\n  }\n\n  inline void MoveTo(float x, float y, float z, bool log = false) {\n    pos_.Set(x, y, z);\n    if (aoi_) {\n      aoi_->UpdatePos(nuid_, x, y, z);\n    }\n\n    if (log) {\n      printf(\"Player %lu MoveTo (%f, %f, %f)\\n\",\n            nuid_, x, y, z);\n    }\n  }\n\n public:\n  Nuid nuid_;\n  Pos pos_;\n\n  PlayerAoi *player_aoi_;\n  CrossAoiTest *aoi_;\n};\n\n\nvoid PrintAoiUpdateInfos(const AoiUpdateInfos &info) {\n  printf(\"=========================== update_infos\\n\");\n  for (auto &elem : info) {\n    auto& update_info = elem.second;\n    printf(\"Player: %lu; update sensors size: %lu\\n\",\n           update_info.nuid, update_info.sensor_update_list.size());\n    for (auto &sensor : update_info.sensor_update_list) {\n      printf(\"  Sensor_id: %lu, \\n\", sensor.sensor_id);\n\n      printf(\"    enters: (%lu)[\", sensor.enters.size());\n      for (auto &nuid : sensor.enters) {\n        printf(\"%lu, \", nuid);\n      }\n      printf(\"]\\n\");\n\n      printf(\"    leaves: (%lu)[\", sensor.leaves.size());\n      for (auto &nuid : sensor.leaves) {\n        printf(\"%lu,\", nuid);\n      }\n      printf(\"]\\n\");\n    }\n  }\n  printf(\"===========================\\n\\n\");\n}\n\n\nvoid CheckUpdateInfos(const AoiUpdateInfos &update_infos, const AoiUpdateInfos &require_infos) {\n  // BOOST_TEST_REQUIRE((update_infos == require_infos));\n  BOOST_TEST_REQUIRE((update_infos.size() == require_infos.size()));\n  for (const auto &pair : update_infos) {\n    auto &update_info = pair.second;\n    BOOST_TEST_REQUIRE((require_infos.find(update_info.nuid) != require_infos.end()));\n    auto &require_info = require_infos.find(update_info.nuid)->second;\n\n    BOOST_TEST_REQUIRE(\n      (update_info.sensor_update_list.size() == require_info.sensor_update_list.size()));\n\n    for (size_t i =0; i < update_info.sensor_update_list.size(); ++i) {\n      auto &sensor_info = update_info.sensor_update_list[i];\n      auto &require_sensor_info = require_info.sensor_update_list[i];\n      BOOST_TEST_REQUIRE((sensor_info.sensor_id == require_sensor_info.sensor_id));\n      BOOST_TEST_REQUIRE((sensor_info.enters == require_sensor_info.enters));\n      BOOST_TEST_REQUIRE((sensor_info.leaves == require_sensor_info.leaves));\n    }\n  }\n}\n\n\nvoid TestSimple(bool log = false) {\n  CrossAoiTest cross_aoi(-1000, 1000, -1000, 1000, 3, 3, 5);\n\n  Player player1{GenNuid(), {0, 0, 0}};\n  player1.AddToAoi(&cross_aoi, log);\n  auto sensor_id1 = player1.AddSensor(10, log);\n\n  Player player2{GenNuid(), {0, 0, 0}};\n  player2.AddToAoi(&cross_aoi, log);\n  auto sensor_id2 = player2.AddSensor(5, log);\n\n  auto update_infos = cross_aoi.Tick();\n  if (log) PrintAoiUpdateInfos(update_infos);\n  if (log) cross_aoi.PrintAllNodeList();\n\n  AoiUpdateInfos require_infos = {\n      {player1.nuid_, {player1.nuid_, {{sensor_id1, {player2.nuid_}, {}}}}},\n      {player2.nuid_, {player2.nuid_, {{sensor_id2, {player1.nuid_}, {}}}}},\n  };\n  CheckUpdateInfos(update_infos, require_infos);\n\n  // player2 move to (6, 0, 0)\n  player2.MoveTo(6, 0, 0, log);\n\n  update_infos = cross_aoi.Tick();\n  if (log) PrintAoiUpdateInfos(update_infos);\n\n  require_infos = {\n      {player2.nuid_, {player2.nuid_, {{sensor_id2, {}, {player1.nuid_}}}}},\n    };\n  CheckUpdateInfos(update_infos, require_infos);\n\n  // player2 move to (600, 0, 100)\n  if (log) cross_aoi.PrintAllNodeList();\n  player2.MoveTo(600, 0, 100, log);\n  update_infos = cross_aoi.Tick();\n  if (log) cross_aoi.PrintAllNodeList();\n  if (log) PrintAoiUpdateInfos(update_infos);\n  require_infos = {\n      {player1.nuid_, {player1.nuid_, {{sensor_id1, {}, {player2.nuid_}}}}},\n    };\n  CheckUpdateInfos(update_infos, require_infos);\n\n  player1.MoveTo(601, 100, 101, log);\n  if (log) cross_aoi.PrintAllNodeList();\n  update_infos = cross_aoi.Tick();\n  if (log) PrintAoiUpdateInfos(update_infos);\n  require_infos = {\n      {player1.nuid_, {player1.nuid_, {{sensor_id1, {player2.nuid_}, {}}}}},\n      {player2.nuid_, {player2.nuid_, {{sensor_id2, {player1.nuid_}, {}}}}},\n  };\n  CheckUpdateInfos(update_infos, require_infos);\n\n  player2.RemoveFromAoi(log);\n  update_infos = cross_aoi.Tick();\n  if (log) PrintAoiUpdateInfos(update_infos);\n  require_infos = {\n      {player1.nuid_, {player1.nuid_, {{sensor_id1, {}, {player2.nuid_}}}}},\n  };\n  CheckUpdateInfos(update_infos, require_infos);\n  if (log) cross_aoi.PrintAllNodeList();\n}\n\n\nBOOST_AUTO_TEST_CASE(test_simple) {\n  bool log = false;\n  TestSimple(log);\n}\n\n\nstd::vector<Player> GenPlayers(const size_t player_num, const float map_size) {\n  std::vector<Player> players(player_num);\n\n  boost::random::mt19937 random_generator(std::time(0));\n  boost::random::uniform_real_distribution<float> pos_generator(-map_size, map_size);\n\n  for (int i : boost::irange(player_num)) {\n    auto &player = players[i];\n    player.pos_.Set(pos_generator(random_generator), 0, pos_generator(random_generator));\n  }\n\n  BOOST_TEST_REQUIRE((players.size() == player_num));\n  return players;\n}\n\n\nstd::vector<Pos> GenMovements(const size_t player_num, const float length) {\n  std::vector<Pos> movements;\n  movements.reserve(player_num);\n\n  boost::random::mt19937 random_generator(std::time(0));\n  boost::random::uniform_real_distribution<float> angle_gen(0, 360);\n  for (int UNUSED(i) : boost::irange(player_num)) {\n    float angle = angle_gen(random_generator);\n    float radian = 2 * M_PI * angle / 360;\n    movements.emplace_back(std::cos(radian) * length, 0, std::sin(radian) * length);\n  }\n\n  return movements;\n}\n\nvoid TestOneMilestone(std::vector<Player> *players, const size_t player_num,\n                      const float map_size) {\n  printf(\"\\n===Begin Milestore: player_num = %lu, map_size = (%f, %f)\\n\",\n         player_num, -map_size, map_size);\n\n  boost::timer::cpu_timer run_timer;\n  int times = 1;\n  std::vector<CrossAoiTest> cross_aois;\n  for (auto UNUSED(i) : boost::irange(times)) {\n    cross_aois.emplace_back(-map_size, map_size, -map_size, map_size, 3, 3, 100);\n  }\n  // ProfilerStart(\"a.prof\");\n  for (auto &cross_aoi : cross_aois) {\n    for (auto &player : *players) {\n      player.AddToAoi(&cross_aoi);\n      player.AddSensor(100);\n    }\n    BOOST_TEST_REQUIRE((cross_aoi.GetPlayerMap().size() == player_num + 9));\n  }\n  // ProfilerStop();\n  run_timer.stop();\n  printf(\"Add Player (%i times)\", times);\n  std::cout << run_timer.format();\n\n  for (auto &cross_aoi : cross_aois) {\n    cross_aoi.Tick();\n  }\n\n  run_timer.start();\n  for (auto &cross_aoi : cross_aois) {\n    cross_aoi.Tick();\n  }\n  run_timer.stop();\n\n  printf(\"Tick (%i times)\", times);\n  std::cout << run_timer.format();\n\n  float speed = 6;\n  float delta_time = 0.1;\n  auto movements = GenMovements(player_num, delta_time * speed);\n  times = 1 / delta_time;\n  run_timer.start();\n  for (int UNUSED(t) : boost::irange(times)) {\n    for (int i : boost::irange(player_num)) {\n      auto &player = players->at(i);\n      auto &move = movements[i];\n      player.MoveDelta(move.x, move.y, move.z);\n    }\n  }\n  run_timer.stop();\n  printf(\"Update Pos (%i times)\", times);\n  std::cout << run_timer.format();\n\n  printf(\"===End Milestore\\n\");\n}\n\n\nBOOST_AUTO_TEST_CASE(test_milestone) {\n  for (size_t player_num : {100, 1000, 10000}) {\n    for (float map_size : {50, 100, 1000, 10000}) {\n      auto players = GenPlayers(player_num, map_size);\n      TestOneMilestone(&players, player_num, map_size);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5b5665d5859f24b5d1138016bc44c3ed8d1051cd", "size": 9407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_cross.cpp", "max_stars_repo_name": "disenone/AoiTesting", "max_stars_repo_head_hexsha": "3e72c211ae6e83f9acf2bc480d8e9689dd74d7b6", "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_cross.cpp", "max_issues_repo_name": "disenone/AoiTesting", "max_issues_repo_head_hexsha": "3e72c211ae6e83f9acf2bc480d8e9689dd74d7b6", "max_issues_repo_licenses": ["MIT"], "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_cross.cpp", "max_forks_repo_name": "disenone/AoiTesting", "max_forks_repo_head_hexsha": "3e72c211ae6e83f9acf2bc480d8e9689dd74d7b6", "max_forks_repo_licenses": ["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.3052959502, "max_line_length": 96, "alphanum_fraction": 0.6598277878, "num_tokens": 2748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19953807839114804}}
{"text": "/**************************************************************************\\\n *\n *  This file is part of the Coin 3D visualization library.\n *  Copyright (C) by Kongsberg Oil & Gas Technologies.\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU General Public License\n *  (\"GPL\") version 2 as published by the Free Software Foundation.\n *  See the file LICENSE.GPL at the root directory of this source\n *  distribution for additional information about the GNU GPL.\n *\n *  For using Coin with software that can not be combined with the GNU\n *  GPL, and for taking advantage of the additional benefits of our\n *  support services, please contact Kongsberg Oil & Gas Technologies\n *  about acquiring a Coin Professional Edition License.\n *\n *  See http://www.coin3d.org/ for more information.\n *\n *  Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.\n *  http://www.sim.no/  sales@sim.no  coin-support@coin3d.org\n *\n\\**************************************************************************/\n\n#include <Inventor/engines/SoHeightMapToNormalMap.h>\n\n#include <boost/scoped_array.hpp>\n\n#include <Inventor/SbVec3f.h>\n#include <Inventor/SbImage.h>\n#include \"engines/SoSubEngineP.h\"\n\n/*!\n  \\class SoHeightMapToNormalMap SoHeightMapToNormalMap.h Inventor/engines/SoHeightMapToNormalMap.h\n  \\brief Engine for computing a normal map from a height map.\n\n  This engine will create a normal map texture from a height map texture.\n  You can use it in an Inventor file like this:\n\n  \\code\n  Texture2 {\n    image = HeightMapToNormalMap {\n      sourceImage = Texture2 { filename \"HeightMap.jpg\" } . image\n    } . image\n  }\n  \\endcode\n\n  Be aware that the field connections will remain active, so both\n  Texture2 nodes and the HeightMapToNormalMap engine will be kept resident\n  in memory (unless you intervene manually and detach the engine) even\n  though only the \"outer\" Texture2 node is needed. This can give quite\n  a big memory use overhead.\n\n  \\ingroup engines\n  \\COIN_CLASS_EXTENSION\n  \\since Coin 3.0\n*/\n\n/*!\n  \\enum SoHeightMapToNormalMap::NormalMapFormat\n  Enumeration of available normal map formats.\n*/\n\n/*!\n  \\var SoHeightMapToNormalMap::NormalMapFormat SoHeightMapToNormalMap::INT8\n  Encode the normals as a 3 component byte texture.\n  This is the only option for now, as long as float textures are not conveniently\n  supported in Coin.\n*/\n\n/*!\n  \\var SoMFEnum SoHeightMapToNormalMap::format\n  This setting decides what kind of normal map is generated.  For now, only the\n  INT8 format is available, and it is the default value.\n*/\n\nSO_ENGINE_SOURCE(SoHeightMapToNormalMap);\n\n/*!\n  Class initializer.\n*/\nvoid\nSoHeightMapToNormalMap::initClass(void)\n{\n  SO_ENGINE_INTERNAL_INIT_CLASS(SoHeightMapToNormalMap);\n}\n\n/*!\n  Constructor.\n*/\nSoHeightMapToNormalMap::SoHeightMapToNormalMap(void)\n{\n  SO_ENGINE_INTERNAL_CONSTRUCTOR(SoHeightMapToNormalMap);\n\n  SO_ENGINE_ADD_INPUT(format, (INT8));\n\n  SO_ENGINE_DEFINE_ENUM_VALUE(NormalMapFormat, INT8);\n  SO_ENGINE_SET_SF_ENUM_TYPE(format, NormalMapFormat);\n}\n\n/*!\n  Static function for computing a normal map from a height map.\n  This function can be used directly without any engine instantiation.\n*/\nvoid\nSoHeightMapToNormalMap::convert(const unsigned char * srcptr, SbVec2s size, int nc, SbImage & dst_out)\n{\n  float dx, dy;\n  int width = size[0];\n  int height = size[1];\n  boost::scoped_array<unsigned char> dstarray(new unsigned char[width*height*3]);\n  unsigned char * dstptr = dstarray.get();\n  unsigned char red;\n  SbVec3f n;\n\n#define GET_PIXEL_RED(x_, y_) \\\n  srcptr[(y_)*width*nc + (x_)*nc]\n\n  for (int y = 0; y < height; y++) {\n    for (int x = 0; x < width; x++) {\n      // do Y Sobel filter\n      red = GET_PIXEL_RED((x-1+width) % width, (y+1) % height);\n      dy  = static_cast<float>(red) / 255.0f * -1.0f;\n\n      red = GET_PIXEL_RED(x % width, (y+1) % height);\n      dy += static_cast<float>(red) / 255.0f * -2.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, (y+1) % height);\n      dy += static_cast<float>(red) / 255.0f * -1.0f;\n\n      red = GET_PIXEL_RED((x-1+width) % width, (y-1+height) % height);\n      dy += static_cast<float>(red) / 255.0f *  1.0f;\n\n      red = GET_PIXEL_RED(x % width, (y-1+height) % height);\n      dy += static_cast<float>(red) / 255.0f *  2.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, (y-1+height) % height);\n      dy += static_cast<float>(red) / 255.0f *  1.0f;\n\n      // Do X Sobel filter\n      red = GET_PIXEL_RED((x-1+width) % width, (y-1+height) % height);\n      dx  = static_cast<float>(red) / 255.0f * -1.0f;\n\n      red = GET_PIXEL_RED((x-1+width) % width, y % height);\n      dx += static_cast<float>(red) / 255.0f * -2.0f;\n\n      red = GET_PIXEL_RED((x-1+width) % width, (y+1) % height);\n      dx += static_cast<float>(red) / 255.0f * -1.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, (y-1+height) % height);\n      dx += static_cast<float>(red) / 255.0f *  1.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, y % height);\n      dx += static_cast<float>(red) / 255.0f *  2.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, (y+1) % height);\n      dx += static_cast<float>(red) / 255.0f *  1.0f;\n\n      n[0] = -dx;\n      n[1] = -dy;\n      n[2] = 1.0f;\n      (void) n.normalize();\n\n      *dstptr++ = static_cast<unsigned char>(SbMin((n[0]+1.0f) * 128.0f, 255.0f));\n      *dstptr++ = static_cast<unsigned char>(SbMin((n[1]+1.0f) * 128.0f, 255.0f));\n      *dstptr++ = static_cast<unsigned char>(SbMin((n[2]+1.0f) * 128.0f, 255.0f));\n    }\n  }\n#undef GET_PIXEL_RED\n  dst_out.setValue(size, 3, dstarray.get());\n}\n\nvoid\nSoHeightMapToNormalMap::inputChanged(SoField * which)\n{\n  // in case we need to override later\n  inherited::inputChanged(which);\n}\n\nvoid\nSoHeightMapToNormalMap::evaluate(void)\n{\n  SbVec2s size;\n  int nc;\n  const unsigned char * ptr =\n    static_cast<const unsigned char *>(sourceImage.getValue(size, nc));\n\n  SbImage targetimg;\n  SoHeightMapToNormalMap::convert(ptr, size, nc, targetimg);\n\n  ptr = static_cast<const unsigned char *>(targetimg.getValue(size, nc));\n  SO_ENGINE_OUTPUT(image, SoSFImage, setValue(size, nc, ptr));\n}\n", "meta": {"hexsha": "886b255d172e83d8498c5ecec13f2b09d3b1d02f", "size": 6093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grasp_generation/graspitmodified_lm/Coin-3.1.3/src/engines/SoHeightMapToNormalMap.cpp", "max_stars_repo_name": "KraftOreo/EBM_Hand", "max_stars_repo_head_hexsha": "9ab1722c196b7eb99b4c3ecc85cef6e8b1887053", "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": "grasp_generation/graspitmodified_lm/Coin-3.1.3/src/engines/SoHeightMapToNormalMap.cpp", "max_issues_repo_name": "KraftOreo/EBM_Hand", "max_issues_repo_head_hexsha": "9ab1722c196b7eb99b4c3ecc85cef6e8b1887053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grasp_generation/graspitmodified_lm/Coin-3.1.3/src/engines/SoHeightMapToNormalMap.cpp", "max_forks_repo_name": "KraftOreo/EBM_Hand", "max_forks_repo_head_hexsha": "9ab1722c196b7eb99b4c3ecc85cef6e8b1887053", "max_forks_repo_licenses": ["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.5699481865, "max_line_length": 102, "alphanum_fraction": 0.6638765797, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807272299745}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Ion Gaztanaga 2015-2015. 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// See http://www.boost.org/libs/container for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#define BOOST_CONTAINER_SOURCE\n#include <boost/container/detail/config_begin.hpp>\n#include <boost/container/detail/min_max.hpp>\n#include <boost/container/detail/workaround.hpp>\n#include <boost/container/pmr/global_resource.hpp>\n#include <boost/container/pmr/monotonic_buffer_resource.hpp>\n#include <boost/container/throw_exception.hpp>\n#include <boost/intrusive/detail/math.hpp>\n#include <cstddef>\n\nnamespace\n{\n\n#ifdef BOOST_HAS_INTPTR_T\ntypedef boost::uintptr_t uintptr_type;\n#else\ntypedef std::size_t uintptr_type;\n#endif\n\nstatic const std::size_t minimum_buffer_size = 2 * sizeof(void*);\n\n} // namespace\n\nnamespace boost\n{\nnamespace container\n{\nnamespace pmr\n{\n\nvoid monotonic_buffer_resource::increase_next_buffer()\n{\n    m_next_buffer_size = (std::size_t(-1) / 2 < m_next_buffer_size)\n                             ? std::size_t(-1)\n                             : m_next_buffer_size * 2;\n}\n\nvoid monotonic_buffer_resource::increase_next_buffer_at_least_to(\n    std::size_t minimum_size)\n{\n    if (m_next_buffer_size < minimum_size)\n    {\n        if (bi::detail::is_pow2(minimum_size))\n        {\n            m_next_buffer_size = minimum_size;\n        }\n        else if (std::size_t(-1) / 2 < minimum_size)\n        {\n            m_next_buffer_size = minimum_size;\n        }\n        else\n        {\n            m_next_buffer_size = bi::detail::ceil_pow2(minimum_size);\n        }\n    }\n}\n\nmonotonic_buffer_resource::monotonic_buffer_resource(memory_resource* upstream)\n    BOOST_NOEXCEPT\n    : m_memory_blocks(upstream ? *upstream : *get_default_resource()),\n      m_current_buffer(0),\n      m_current_buffer_size(0u),\n      m_next_buffer_size(initial_next_buffer_size),\n      m_initial_buffer(0),\n      m_initial_buffer_size(0u)\n{\n}\n\nmonotonic_buffer_resource::monotonic_buffer_resource(\n    std::size_t initial_size, memory_resource* upstream) BOOST_NOEXCEPT\n    : m_memory_blocks(upstream ? *upstream : *get_default_resource()),\n      m_current_buffer(0),\n      m_current_buffer_size(0u),\n      m_next_buffer_size(minimum_buffer_size),\n      m_initial_buffer(0),\n      m_initial_buffer_size(0u)\n{ // In case initial_size is zero\n    this->increase_next_buffer_at_least_to(initial_size + !initial_size);\n}\n\nmonotonic_buffer_resource::monotonic_buffer_resource(\n    void* buffer, std::size_t buffer_size,\n    memory_resource* upstream) BOOST_NOEXCEPT\n    : m_memory_blocks(upstream ? *upstream : *get_default_resource()),\n      m_current_buffer(buffer),\n      m_current_buffer_size(buffer_size),\n      m_next_buffer_size(\n          bi::detail::previous_or_equal_pow2(boost::container::dtl::max_value(\n              buffer_size, std::size_t(initial_next_buffer_size)))),\n      m_initial_buffer(buffer),\n      m_initial_buffer_size(buffer_size)\n{\n    this->increase_next_buffer();\n}\n\nmonotonic_buffer_resource::~monotonic_buffer_resource()\n{\n    this->release();\n}\n\nvoid monotonic_buffer_resource::release() BOOST_NOEXCEPT\n{\n    m_memory_blocks.release();\n    m_current_buffer = m_initial_buffer;\n    m_current_buffer_size = m_initial_buffer_size;\n    m_next_buffer_size = initial_next_buffer_size;\n}\n\nmemory_resource*\n    monotonic_buffer_resource::upstream_resource() const BOOST_NOEXCEPT\n{\n    return &m_memory_blocks.upstream_resource();\n}\n\nstd::size_t monotonic_buffer_resource::remaining_storage(\n    std::size_t alignment,\n    std::size_t& wasted_due_to_alignment) const BOOST_NOEXCEPT\n{\n    const uintptr_type up_alignment_minus1 = alignment - 1u;\n    const uintptr_type up_alignment_mask = ~up_alignment_minus1;\n    const uintptr_type up_addr = uintptr_type(m_current_buffer);\n    const uintptr_type up_aligned_addr =\n        (up_addr + up_alignment_minus1) & up_alignment_mask;\n    wasted_due_to_alignment = std::size_t(up_aligned_addr - up_addr);\n    return m_current_buffer_size <= wasted_due_to_alignment\n               ? 0u\n               : m_current_buffer_size - wasted_due_to_alignment;\n}\n\nstd::size_t monotonic_buffer_resource::remaining_storage(\n    std::size_t alignment) const BOOST_NOEXCEPT\n{\n    std::size_t ignore_this;\n    return this->remaining_storage(alignment, ignore_this);\n}\n\nconst void* monotonic_buffer_resource::current_buffer() const BOOST_NOEXCEPT\n{\n    return m_current_buffer;\n}\n\nstd::size_t monotonic_buffer_resource::next_buffer_size() const BOOST_NOEXCEPT\n{\n    return m_next_buffer_size;\n}\n\nvoid* monotonic_buffer_resource::allocate_from_current(std::size_t aligner,\n                                                       std::size_t bytes)\n{\n    char* p = (char*)m_current_buffer + aligner;\n    m_current_buffer = p + bytes;\n    m_current_buffer_size -= aligner + bytes;\n    return p;\n}\n\nvoid* monotonic_buffer_resource::do_allocate(std::size_t bytes,\n                                             std::size_t alignment)\n{\n    if (alignment > memory_resource::max_align)\n        throw_bad_alloc();\n\n    // See if there is room in current buffer\n    std::size_t aligner = 0u;\n    if (this->remaining_storage(alignment, aligner) < bytes)\n    {\n        // Update next_buffer_size to at least bytes\n        this->increase_next_buffer_at_least_to(bytes);\n        // Now allocate and update internal data\n        m_current_buffer = (char*)m_memory_blocks.allocate(m_next_buffer_size);\n        m_current_buffer_size = m_next_buffer_size;\n        this->increase_next_buffer();\n    }\n    // Enough internal storage, extract from it\n    return this->allocate_from_current(aligner, bytes);\n}\n\nvoid monotonic_buffer_resource::do_deallocate(\n    void* p, std::size_t bytes, std::size_t alignment) BOOST_NOEXCEPT\n{\n    (void)p;\n    (void)bytes;\n    (void)alignment;\n}\n\nbool monotonic_buffer_resource::do_is_equal(const memory_resource& other) const\n    BOOST_NOEXCEPT\n{\n    return this == dynamic_cast<const monotonic_buffer_resource*>(&other);\n}\n\n} // namespace pmr\n} // namespace container\n} // namespace boost\n\n#include <boost/container/detail/config_end.hpp>\n", "meta": {"hexsha": "c80d57a74d53d4931690e2d2fd40ecb86b8b1ffd", "size": 6314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/container/src/monotonic_buffer_resource.cpp", "max_stars_repo_name": "sotaoverride/backup", "max_stars_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/container/src/monotonic_buffer_resource.cpp", "max_issues_repo_name": "sotaoverride/backup", "max_issues_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/container/src/monotonic_buffer_resource.cpp", "max_forks_repo_name": "sotaoverride/backup", "max_forks_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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.6504854369, "max_line_length": 79, "alphanum_fraction": 0.6992397846, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.19943325222513325}}
{"text": "/**\n * Copyright (c) 2017 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#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <boost/iostreams/restrict.hpp>\n\n#include \"dbglog/dbglog.hpp\"\n\n#include \"utility/expect.hpp\"\n#include \"utility/binaryio.hpp\"\n\n#include \"math/math.hpp\"\n#include \"math/geometry.hpp\"\n#include \"math/transform.hpp\"\n\n#include \"imgproc/scanconversion.hpp\"\n\n#include \"half/half.hpp\"\n\n#include \"../storage/error.hpp\"\n\n#include \"mesh.hpp\"\n#include \"meshio.hpp\"\n#include \"multifile.hpp\"\n#include \"math.hpp\"\n#include \"tileindex.hpp\"\n\nnamespace fs = boost::filesystem;\nnamespace bio = boost::iostreams;\nnamespace bin = utility::binaryio;\n\nnamespace half = half_float::detail;\n\nnamespace vtslibs { namespace vts {\n\nnamespace {\n\n/** Geo coordinates to coverage mask mapping.\n * NB: result is in pixel system: pixel centers have integral indices\n */\nmath::Matrix4 geo2mask(const math::Extents2 &extents\n                              , const math::Size2 &gridSize)\n{\n    math::Matrix4 trafo(boost::numeric::ublas::identity_matrix<double>(4));\n\n    auto es(size(extents));\n\n    // scales\n    math::Size2f scale(gridSize.width / es.width\n                       , gridSize.height / es.height);\n\n    // scale to grid\n    trafo(0, 0) = scale.width;\n    trafo(1, 1) = -scale.height;\n\n    // move to origin\n    trafo(0, 3) = -extents.ll(0) * scale.width;\n    trafo(1, 3) = extents.ur(1) * scale.height;\n\n    return trafo;\n}\n\nvoid updateCoverage(Mesh::CoverageMask &cm, const SubMesh &sm\n                    , const math::Extents2 &sdsExtents\n                    , std::uint8_t smIndex)\n{\n    const auto rasterSize(cm.size());\n    auto trafo(geo2mask(sdsExtents, rasterSize));\n\n    std::vector<imgproc::Scanline> scanlines;\n    cv::Point3f tri[3];\n    for (const auto &face : sm.faces) {\n        for (int i : { 0, 1, 2 }) {\n            auto p(transform(trafo, sm.vertices[face[i]]));\n            tri[i].x = p(0); tri[i].y = p(1); tri[i].z = p(2);\n        }\n\n        scanlines.clear();\n        imgproc::scanConvertTriangle(tri, 0, rasterSize.height, scanlines);\n\n        for (const auto &sl : scanlines) {\n            imgproc::processScanline\n                (sl, 0, rasterSize.width, [&](int x, int y, float)\n            {\n                cm.set(x, y, smIndex + 1);\n            });\n        }\n    }\n}\n\n} // namespace\n\nvoid updateCoverage(Mesh &mesh, const SubMesh &sm\n                    , const math::Extents2 &sdsExtents\n                    , std::uint8_t smIndex)\n{\n    updateCoverage(mesh.coverageMask, sm, sdsExtents, smIndex);\n}\n\nvoid generateCoverage(Mesh &mesh, const math::Extents2 &sdsExtents)\n{\n    mesh.createCoverage(false);\n\n    std::uint8_t smIndex(0);\n    for (const auto &sm : mesh) {\n        updateCoverage(mesh, sm, sdsExtents, smIndex++);\n    }\n}\n\nvoid generateMeshMask(MeshMask &mask, const Mesh &mesh\n                      , const math::Extents2 &sdsExtents)\n{\n    mask.createCoverage(false);\n    mask.surfaceReferences.clear();\n\n    std::uint8_t smIndex(0);\n    for (const auto &sm : mesh) {\n        updateCoverage(mask.coverageMask, sm, sdsExtents, smIndex++);\n        mask.surfaceReferences.push_back(sm.surfaceReference);\n    }\n}\n\n} } // namespace vtslibs::vts\n", "meta": {"hexsha": "c01764a3e21ece86c657d5bed0292f761fe6d334", "size": 4522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vts-libs/vts/meshcoverage.cpp", "max_stars_repo_name": "melowntech/vts-libs", "max_stars_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-20T01:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T06:54:51.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/meshcoverage.cpp", "max_issues_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_issues_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T15:21:29.000Z", "max_forks_repo_path": "externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/meshcoverage.cpp", "max_forks_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_forks_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:10:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:10:07.000Z", "avg_line_length": 30.7619047619, "max_line_length": 78, "alphanum_fraction": 0.6656346749, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1994332522251332}}
{"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_REDUCTION_FUNCTIONS_SIMD_SSE_SSE2_COMPARE_EQUAL_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_REDUCTION_FUNCTIONS_SIMD_SSE_SSE2_COMPARE_EQUAL_HPP_INCLUDED\n\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n#include <boost/simd/toolbox/reduction/functions/compare_equal.hpp>\n#include <boost/simd/include/functions/simd/is_equal.hpp>\n#include <boost/simd/sdk/simd/logical.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::compare_equal_, boost::simd::tag::sse2_\n                            , (A0)\n                            , ((simd_<double_<A0>,boost::simd::tag::sse_>))\n                              ((simd_<double_<A0>,boost::simd::tag::sse_>))\n                            )\n  {\n    typedef typename meta::scalar_of<A0>::type  sA0;\n    typedef typename meta::as_logical<sA0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return result_type(_mm_movemask_pd(eq(a0,a1)) == 0X03); }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::compare_equal_, boost::simd::tag::sse2_\n                            , (A0)\n                            , ((simd_<single_<A0>,boost::simd::tag::sse_>))\n                              ((simd_<single_<A0>,boost::simd::tag::sse_>))\n                            )\n  {\n    typedef typename meta::scalar_of<A0>::type  sA0;\n    typedef typename meta::as_logical<sA0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return  result_type(_mm_movemask_ps(eq(a0,a1)) == 0X0F); }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::compare_equal_, boost::simd::tag::sse2_\n                            , (A0)\n                            , ((simd_<integer_<A0>,boost::simd::tag::sse_>))\n                              ((simd_<integer_<A0>,boost::simd::tag::sse_>))\n                            )\n  {\n    typedef typename meta::scalar_of<A0>::type  sA0;\n    typedef typename meta::as_logical<sA0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return  result_type(_mm_movemask_epi8(eq(a0,a1)) == 0X0FFFF);\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "e9174a6bc75e27090537fed559cd61f4217d4f9b", "size": 2630, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/reduction/include/boost/simd/toolbox/reduction/functions/simd/sse/sse2/compare_equal.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/reduction/include/boost/simd/toolbox/reduction/functions/simd/sse/sse2/compare_equal.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/reduction/include/boost/simd/toolbox/reduction/functions/simd/sse/sse2/compare_equal.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": 44.5762711864, "max_line_length": 98, "alphanum_fraction": 0.5790874525, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.19935273930884823}}
{"text": "#define BOOST_TEST_MODULE \"test_read_afm_fitting_interaction\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/core/SimulatorTraits.hpp>\n#include <mjolnir/core/BoundaryCondition.hpp>\n#include <mjolnir/forcefield/AFMFit/AFMFitInteraction.hpp>\n#include <mjolnir/input/read_external_interaction.hpp>\n\nBOOST_AUTO_TEST_CASE(read_afm_fitting_interaction)\n{\n    mjolnir::LoggerManager::set_default_logger(\"test_read_afm_fitting_interaction.log\");\n    using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using namespace toml::literals;\n    const toml::value v = u8R\"(\n        interaction = \"AFMFlexibleFitting\"\n        k           = 100.0\n        gamma       =   1.0\n        pixel_x     =  10.0\n        pixel_y     =  10.0\n        sigma_x     =   2.0\n        sigma_y     =   2.0\n        length_x    =   5\n        length_y    =   5\n        z0          = 0.0\n        cutoff      = 5.0\n        margin      = 0.5\n        image       = [\n            0.0, 0.0, 0.0, 0.0, 0.0,\n            0.0, 0.0, 0.0, 0.0, 0.0,\n            0.0, 0.0, 0.5, 1.0, 0.5,\n            0.0, 0.0, 1.0, 2.0, 1.0,\n            0.0, 0.0, 0.5, 1.0, 0.5,\n        ]\n        parameters  = [\n        {index = 0, radius = 1.0},\n        {index = 1, radius = 2.0},\n        {index = 4, radius = 3.0},\n        {index = 5, radius = 4.0},\n        ]\n    )\"_toml;\n\n    const auto base = mjolnir::read_external_interaction<traits_type>(v);\n    BOOST_TEST(static_cast<bool>(base));\n\n    const auto derv = dynamic_cast<\n        const mjolnir::AFMFitInteraction<traits_type>*>(base.get());\n    BOOST_TEST(static_cast<bool>(derv));\n\n    BOOST_TEST(derv->k() == 100.0);\n    BOOST_TEST(derv->gamma   () ==  1.0);\n    BOOST_TEST(derv->pixel_x () == 10.0);\n    BOOST_TEST(derv->pixel_y () == 10.0);\n    BOOST_TEST(derv->sigma_x () ==  2.0);\n    BOOST_TEST(derv->sigma_y () ==  2.0);\n    BOOST_TEST(derv->length_x() ==  5u );\n    BOOST_TEST(derv->length_y() ==  5u );\n    BOOST_TEST(derv->z0      () ==  0.0);\n    BOOST_TEST(derv->cutoff  () ==  5.0);\n    BOOST_TEST(derv->margin  () ==  0.5);\n\n    BOOST_TEST_REQUIRE(derv->participants().size() == 4u);\n    BOOST_TEST_REQUIRE(derv->participants().at(0)  == 0u);\n    BOOST_TEST_REQUIRE(derv->participants().at(1)  == 1u);\n    BOOST_TEST_REQUIRE(derv->participants().at(2)  == 4u);\n    BOOST_TEST_REQUIRE(derv->participants().at(3)  == 5u);\n\n    BOOST_TEST(derv->parameters().at(0) == 1.0);\n    BOOST_TEST(derv->parameters().at(1) == 2.0);\n    BOOST_TEST(derv->parameters().at(4) == 3.0);\n    BOOST_TEST(derv->parameters().at(5) == 4.0);\n\n    BOOST_TEST(derv->image().at( 0) == 0.0);\n    BOOST_TEST(derv->image().at( 1) == 0.0);\n    BOOST_TEST(derv->image().at( 2) == 0.0);\n    BOOST_TEST(derv->image().at( 3) == 0.0);\n    BOOST_TEST(derv->image().at( 4) == 0.0);\n    BOOST_TEST(derv->image().at( 5) == 0.0);\n    BOOST_TEST(derv->image().at( 6) == 0.0);\n    BOOST_TEST(derv->image().at( 7) == 0.0);\n    BOOST_TEST(derv->image().at( 8) == 0.0);\n    BOOST_TEST(derv->image().at( 9) == 0.0);\n    BOOST_TEST(derv->image().at(10) == 0.0);\n    BOOST_TEST(derv->image().at(11) == 0.0);\n    BOOST_TEST(derv->image().at(12) == 0.5);\n    BOOST_TEST(derv->image().at(13) == 1.0);\n    BOOST_TEST(derv->image().at(14) == 0.5);\n    BOOST_TEST(derv->image().at(15) == 0.0);\n    BOOST_TEST(derv->image().at(16) == 0.0);\n    BOOST_TEST(derv->image().at(17) == 1.0);\n    BOOST_TEST(derv->image().at(18) == 2.0);\n    BOOST_TEST(derv->image().at(19) == 1.0);\n    BOOST_TEST(derv->image().at(20) == 0.0);\n    BOOST_TEST(derv->image().at(21) == 0.0);\n    BOOST_TEST(derv->image().at(22) == 0.5);\n    BOOST_TEST(derv->image().at(23) == 1.0);\n    BOOST_TEST(derv->image().at(24) == 0.5);\n}\n", "meta": {"hexsha": "148ebc6def938b8d433fd8c4dbda00705d337d1c", "size": 3774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_read_afm_fitting_interaction.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T15:47:51.000Z", "max_issues_repo_path": "test/core/test_read_afm_fitting_interaction.cpp", "max_issues_repo_name": "Mjolnir-MD/Mjolnir", "max_issues_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T08:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T08:26:36.000Z", "max_forks_repo_path": "test/core/test_read_afm_fitting_interaction.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T11:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:38:00.000Z", "avg_line_length": 36.640776699, "max_line_length": 88, "alphanum_fraction": 0.5720720721, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.19925681226562397}}
{"text": "/*\n * Copyright 2020 Robert Bosch GmbH\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 * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * \\file noisy_object_sensor.cpp\n */\n\n#include <Eigen/Geometry>  // for Isometry3d, Vector3d\n#include <memory>          // for shared_ptr<>\n#include <random>          // for random_device\n#include <string>          // for string\n\n#include <cloe/component.hpp>                // for Component, Json\n#include <cloe/component/frustum.hpp>        // for Frustum\n#include <cloe/component/object.hpp>         // for Object\n#include <cloe/component/object_sensor.hpp>  // for ObjectSensor\n#include <cloe/conf/action.hpp>              // for actions::ConfigureFactory\n#include <cloe/plugin.hpp>                   // for EXPORT_CLOE_PLUGIN\n#include <cloe/registrar.hpp>                // for Registrar\n#include <cloe/sync.hpp>                     // for Sync\n#include <cloe/trigger/set_action.hpp>       // for actions::SetVariableActionFactory\n#include \"noise_data.hpp\"                    // for NoiseData, NoiseConf\n\nnamespace cloe {\n\nenum class ObjectField { Translation, Velocity, Acceleration };\n\n// clang-format off\nENUM_SERIALIZATION(ObjectField, ({\n    {ObjectField::Translation, \"translation\"},\n    {ObjectField::Velocity, \"velocity\"},\n    {ObjectField::Acceleration, \"acceleration\"},\n}))\n// clang-format on\n\nnamespace component {\n\nvoid apply_noise_xy(Eigen::Vector3d* vec, const NoiseConf& noise) {\n  vec->x() = vec->x() + noise.get();\n  vec->y() = vec->y() + noise.get();\n}\n\nvoid add_noise_translation(Object* obj, const NoiseConf* noise) {\n  Eigen::Vector3d transl = obj->pose.translation();\n  apply_noise_xy(&transl, *noise);\n  obj->pose.translation() = transl;\n}\n\nvoid add_noise_velocity(Object* obj, const NoiseConf* noise) {\n  Eigen::Vector3d vel = obj->velocity;\n  apply_noise_xy(&vel, *noise);\n  obj->velocity = vel;\n}\n\nvoid add_noise_acceleration(Object* obj, const NoiseConf* noise) {\n  Eigen::Vector3d accel = obj->acceleration;\n  apply_noise_xy(&accel, *noise);\n  obj->acceleration = accel;\n}\n\nclass ObjectNoiseConf : public NoiseConf {\n public:\n  ObjectNoiseConf() = default;\n\n  virtual ~ObjectNoiseConf() noexcept = default;\n\n  /**\n   * Add noise to target parameter.\n   */\n  std::function<void(Object*)> apply;\n\n  /**\n   * Set the appropriate target function.\n   */\n  void set_target() {\n    using namespace std::placeholders;  // for _1\n    switch (target_) {\n      case ObjectField::Translation:\n        apply = std::bind(add_noise_translation, _1, this);\n        break;\n      case ObjectField::Velocity:\n        apply = std::bind(add_noise_velocity, _1, this);\n        break;\n      case ObjectField::Acceleration:\n        apply = std::bind(add_noise_acceleration, _1, this);\n        break;\n    }\n  }\n\n  CONFABLE_SCHEMA(ObjectNoiseConf) {\n    return Schema{\n        NoiseConf::schema_impl(),\n        fable::schema::PropertyList<fable::schema::Box>{\n            // clang-format off\n            {\"target\", Schema(&target_, \"data field of the object the noise should be applied to\")},\n            // clang-format on\n        },\n    };\n  }\n\n  void to_json(Json& j) const override {\n    NoiseConf::to_json(j);\n    j = Json{\n        {\"target\", target_},\n    };\n  }\n\n private:\n  ObjectField target_{ObjectField::Translation};\n};\n\nstruct NoisyObjectSensorConf : public NoisySensorConf {\n  /// List of noisy object parameters.\n  std::vector<ObjectNoiseConf> noisy_params;\n\n  CONFABLE_SCHEMA(NoisyObjectSensorConf) {\n    return Schema{\n        NoisySensorConf::schema_impl(),\n        fable::schema::PropertyList<fable::schema::Box>{\n            // clang-format off\n              {\"noise\", Schema(&noisy_params, \"configure noisy parameters\")},\n            // clang-format on\n        },\n    };\n  }\n\n  void to_json(Json& j) const override {\n    NoisySensorConf::to_json(j);\n    j = Json{\n        {\"noise\", noisy_params},\n    };\n  }\n};\n\nclass NoisyObjectSensor : public ObjectSensor {\n public:\n  NoisyObjectSensor(const std::string& name, const NoisyObjectSensorConf& conf,\n                    std::shared_ptr<ObjectSensor> obs)\n      : ObjectSensor(name), config_(conf), sensor_(obs) {\n    reset_random();\n  }\n\n  virtual ~NoisyObjectSensor() noexcept = default;\n\n  const Objects& sensed_objects() const override {\n    if (cached_) {\n      return objects_;\n    }\n    for (const auto& o : sensor_->sensed_objects()) {\n      auto obj = apply_noise(o);\n      if (obj) {\n        objects_.push_back(obj);\n      }\n    }\n    cached_ = true;\n    return objects_;\n  }\n\n  const Frustum& frustum() const override { return sensor_->frustum(); }\n\n  const Eigen::Isometry3d& mount_pose() const override { return sensor_->mount_pose(); }\n\n  /**\n   * Process the underlying sensor and clear the cache.\n   *\n   * We could process and create the filtered list of objects now, but we can\n   * also delay it (lazy computation) and only do it when absolutely necessary.\n   * This comes at the minor cost of checking whether cached_ is true every\n   * time sensed_objects() is called.\n   */\n  Duration process(const Sync& sync) override {\n    // This currently shouldn't do anything, but this class acts as a prototype\n    // for How It Should Be Done.\n    Duration t = ObjectSensor::process(sync);\n    if (t < sync.time()) {\n      return t;\n    }\n\n    // Process the underlying sensor and clear the cache.\n    t = sensor_->process(sync);\n    clear_cache();\n    return t;\n  }\n\n  void reset() override {\n    ObjectSensor::reset();\n    sensor_->reset();\n    clear_cache();\n    reset_random();\n  }\n\n  void abort() override {\n    ObjectSensor::abort();\n    sensor_->abort();\n  }\n\n  void enroll(Registrar& r) override {\n    r.register_action(std::make_unique<actions::ConfigureFactory>(\n        &config_, \"config\", \"configure noisy object component\"));\n    r.register_action<actions::SetVariableActionFactory<bool>>(\n        \"noise_activation\", \"switch sensor noise on/off\", \"enable\", &config_.enabled);\n  }\n\n protected:\n  std::shared_ptr<Object> apply_noise(const std::shared_ptr<Object>& o) const {\n    if (!config_.enabled) {\n      return o;\n    }\n    auto obj = std::make_shared<Object>(*o);\n\n    for (auto& np : config_.noisy_params) {\n      np.apply(obj.get());\n    }\n    return obj;\n  }\n\n  void reset_random() {\n    // Reset the sensor's \"master\" seed, if applicable.\n    unsigned long seed = config_.seed;\n    if (seed == 0) {\n      std::random_device r;\n      do {\n        seed = r();\n      } while (seed == 0);\n\n      if (config_.reuse_seed) {\n        config_.seed = seed;\n      }\n    }\n    for (auto& np : config_.noisy_params) {\n      np.set_target();\n      np.reset(seed);\n      ++seed;\n    }\n  }\n\n  void clear_cache() {\n    objects_.clear();\n    cached_ = false;\n  }\n\n private:\n  NoisyObjectSensorConf config_;\n  std::shared_ptr<ObjectSensor> sensor_;\n  mutable bool cached_;\n  mutable Objects objects_;\n};\n\nDEFINE_COMPONENT_FACTORY(NoisyObjectSensorFactory, NoisyObjectSensorConf, \"noisy_object_sensor\",\n                         \"add gaussian noise to object sensor output\")\n\nDEFINE_COMPONENT_FACTORY_MAKE(NoisyObjectSensorFactory, NoisyObjectSensor, ObjectSensor)\n\n}  // namespace component\n}  // namespace cloe\n\nEXPORT_CLOE_PLUGIN(cloe::component::NoisyObjectSensorFactory)\n", "meta": {"hexsha": "e814da5f0de3bddb2bcdec9159ac57f74b123254", "size": 7714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugins/noisy_sensor/src/noisy_object_sensor.cpp", "max_stars_repo_name": "Sidharth-S-S/cloe", "max_stars_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T18:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:35:28.000Z", "max_issues_repo_path": "plugins/noisy_sensor/src/noisy_object_sensor.cpp", "max_issues_repo_name": "Sidharth-S-S/cloe", "max_issues_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-20T10:13:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:27:19.000Z", "max_forks_repo_path": "plugins/noisy_sensor/src/noisy_object_sensor.cpp", "max_forks_repo_name": "Sidharth-S-S/cloe", "max_forks_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T08:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T10:09:53.000Z", "avg_line_length": 28.3602941176, "max_line_length": 100, "alphanum_fraction": 0.6516722842, "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.19925681226562397}}
{"text": "#include \"mutation_annotated_tree.hpp\"\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <iomanip>\n#include <iostream>\n\n// Uses one-hot encoding if base is unambiguous\n// A:1,C:2,G:4,T:8\nint8_t Mutation_Annotated_Tree::get_nuc_id (char nuc) {\n    int8_t ret = 0b1111;\n    switch(nuc) {\n        case 'a':\n        case 'A': ret = 0b1;\n                  break;\n        case 'c':\n        case 'C': ret = 0b10;\n                  break;\n        case 'g':\n        case 'G': ret = 0b100; \n                  break;\n        case 't':\n        case 'T': ret = 0b1000; \n                  break;\n        case 'R': ret = 0b101;\n                  break;\n        case 'Y': ret = 0b1010;\n                  break;\n        case 'S': ret = 0b110;\n                  break;\n        case 'W': ret = 0b1001;\n                  break;\n        case 'K': ret = 0b1100;\n                  break;\n        case 'M': ret = 0b11;\n                  break;\n        case 'B': ret = 0b1110;\n                  break;\n        case 'D': ret = 0b1101;\n                  break;\n        case 'H': ret = 0b1011;\n                  break;\n        case 'V': ret = 0b111;\n        case 'n':\n        case 'N': \n        default: ret = 0b1111;\n                 break;\n    }\n    return ret;\n}\n\n// Sets bits at positions specified by nuc_vec to 1 in int8\nint8_t Mutation_Annotated_Tree::get_nuc_id (std::vector<int8_t> nuc_vec) {\n    int8_t ret = 0;\n    int8_t one = 1;\n    for (auto nuc: nuc_vec) {\n        assert((nuc >= 0) && (nuc <=3));\n        ret += (one << nuc);\n    }\n    return ret;\n}\n\n// Convert nuc_id back to IUPAC base \nchar Mutation_Annotated_Tree::get_nuc (int8_t nuc_id) {\n    char ret = 'N';\n    //assert ((nuc_id >= 1) && (nuc_id <= 15));\n    switch(nuc_id) {\n        case 1: ret = 'A';\n                break;\n        case 2: ret = 'C';\n                break;\n        case 3: ret = 'M';\n                break;\n        case 4: ret = 'G';\n                break;\n        case 5: ret = 'R';\n                break;\n        case 6: ret = 'S';\n                break;\n        case 7: ret = 'V';\n                break;\n        case 8: ret = 'T';\n                break;\n        case 9: ret = 'W';\n                break;\n        case 10: ret = 'Y';\n                break;\n        case 11: ret = 'H';\n                break;\n        case 12: ret = 'K';\n                break;\n        case 13: ret = 'D';\n                break;\n        case 14: ret = 'B';\n                break;\n        default: ret = 'N';\n                 break;\n    }\n    return ret;\n}\n\n// A:0, C:1, G:2, T:3 \nint8_t Mutation_Annotated_Tree::get_nt (int8_t nuc_id) {\n    int8_t ret = 0;\n    switch(nuc_id) {\n        case 1: ret = 0;\n                break;\n        case 2: ret = 1;\n                break;\n        case 4: ret = 2;\n                break;\n        case 8: ret = 3;\n                break;\n        default: ret = -1;\n                 break;\n    }\n    return ret;\n}\n\nstd::vector<int8_t> Mutation_Annotated_Tree::get_nuc_vec (char c) {\n    switch (c) {\n        case 'a':\n        case 'A': return std::vector<int8_t>{0};\n        case 'c':\n        case 'C': return std::vector<int8_t>{1};\n        case 'g':\n        case 'G': return std::vector<int8_t>{2};\n        case 't':\n        case 'T': return std::vector<int8_t>{3};\n        case 'R': return std::vector<int8_t>{0,2};\n        case 'Y': return std::vector<int8_t>{1,3};\n        case 'S': return std::vector<int8_t>{1,2};\n        case 'W': return std::vector<int8_t>{0,3};\n        case 'K': return std::vector<int8_t>{2,3};\n        case 'M': return std::vector<int8_t>{0,1};\n        case 'B': return std::vector<int8_t>{1,2,3};\n        case 'D': return std::vector<int8_t>{0,2,3};\n        case 'H': return std::vector<int8_t>{0,1,3};\n        case 'V': return std::vector<int8_t>{0,1,2};\n        case 'n':\n        case 'N': return std::vector<int8_t>{0,1,2,3};\n        default: return std::vector<int8_t>{0,1,2,3};\n    }\n}\n\nstd::vector<int8_t> Mutation_Annotated_Tree::get_nuc_vec_from_id (int8_t nuc_id) {\n    return get_nuc_vec(get_nuc(nuc_id));\n}\n\n// Get newick stringstream for the input subtree rooted at some node (node) in \n// the input tree T. Boolean arguments decide whether\n// internal node ids and branch lengths are printed. If last boolean argument is\n// set, branch lengths from input tree are retained, otherwise, branch length\n// for a branch is equal to the number of mutations annotated on that branch \nvoid Mutation_Annotated_Tree::write_newick_string (std::stringstream& ss, const Mutation_Annotated_Tree::Tree& T, Mutation_Annotated_Tree::Node* node, bool print_internal, bool print_branch_len, bool retain_original_branch_len, bool uncondense_leaves) {\n    TIMEIT();\n\n    std::vector<Node*> traversal = T.depth_first_expansion(node);\n    size_t level_offset = node->level-1;\n    size_t curr_level = 0;\n    bool prev_open = true;\n\n    std::stack<std::string> node_stack;\n    std::stack<float> branch_length_stack;\n\n    for (auto n: traversal) {\n        size_t level = n->level-level_offset;\n        float branch_length = n->branch_length;\n        if (!retain_original_branch_len) {\n            branch_length = static_cast<float>(n->mutations.size());\n        }\n        if (curr_level < level) {\n            if (!prev_open) {\n                ss << ',';\n            }\n            size_t l = level - 1;\n            if (curr_level > 1) {\n                l = level - curr_level;\n            }\n            for (size_t i=0; i < l; i++) {\n                ss << '(';\n                prev_open = true;\n            }\n            if (n->is_leaf()) {\n                if (uncondense_leaves && (T.condensed_nodes.find(n->identifier) != T.condensed_nodes.end())) {\n                    auto cn = T.condensed_nodes.at(n->identifier);\n                    auto cn_size = cn.size();\n                    for (size_t idx = 0; idx < cn_size; idx++) {\n                        ss << cn[idx];\n                        if (idx+1 < cn_size) {\n                            ss << ',';\n                        }\n                    }\n                }\n                else {\n                    ss << n->identifier;\n                }\n                if ((print_branch_len) && (branch_length >= 0)) {\n                    ss << ':';\n                    ss << branch_length;\n                }\n                prev_open = false;\n            }\n            else {\n                node_stack.push(n->identifier);\n                branch_length_stack.push(branch_length);\n            }\n        }\n        else if (curr_level > level) {\n            prev_open = false;\n            for (size_t i = level; i < curr_level; i++) {\n                ss << ')';\n                if (print_internal){\n                    ss << node_stack.top();\n                }\n                if ((print_branch_len) && (branch_length_stack.top() >= 0)) {\n                    ss << ':';\n                    ss << branch_length_stack.top();\n                }\n                node_stack.pop();\n                branch_length_stack.pop();\n            }\n            if (n->is_leaf()) {\n                if (uncondense_leaves && (T.condensed_nodes.find(n->identifier) != T.condensed_nodes.end())) {\n                    auto cn = T.condensed_nodes.at(n->identifier);\n                    ss << ',';\n                    auto cn_size = cn.size();\n                    for (size_t idx = 0; idx < cn_size; idx++) {\n                        ss << cn[idx];\n                        if (idx+1 < cn_size) {\n                            ss << ',';\n                        }\n                    }\n                }\n                else {\n                    ss << ',';\n                    ss << n->identifier;\n                }\n                if ((print_branch_len) && (branch_length >= 0)) {\n                    ss << ':';\n                    ss << branch_length;\n                }\n            }\n            else {\n                node_stack.push(n->identifier);\n                branch_length_stack.push(branch_length);\n            }\n        }\n        else {\n            prev_open = false;\n            if (n->is_leaf()) {\n                if (uncondense_leaves && (T.condensed_nodes.find(n->identifier) != T.condensed_nodes.end())) {\n                    auto cn = T.condensed_nodes.at(n->identifier);\n                    ss << ',';\n                    auto cn_size = cn.size();\n                    for (size_t idx = 0; idx < cn_size; idx++) {\n                        ss << cn[idx];\n                        if (idx+1 < cn_size) {\n                            ss << ',';\n                        }\n                    }\n                }\n                else {\n                    ss << ',';\n                    ss << n->identifier;\n                }\n                if ((print_branch_len) && (branch_length >= 0)) {\n                    ss << ':';\n                    ss << branch_length;\n                }\n            }\n            else {\n                node_stack.push(n->identifier);\n                branch_length_stack.push(branch_length);\n            }\n        }\n        curr_level = level;\n    }\n    size_t remaining = node_stack.size();\n    for (size_t i = 0; i < remaining; i++) {\n        ss << ')';\n        if (print_internal) {\n            ss << node_stack.top();\n        }\n        if ((print_branch_len) && (branch_length_stack.top() >= 0)) {\n            ss << ':';\n            ss << branch_length_stack.top();\n        }\n        node_stack.pop();\n        branch_length_stack.pop();\n    }\n\n    ss << ';';\n}\n\nstd::string Mutation_Annotated_Tree::get_newick_string (const Mutation_Annotated_Tree::Tree& T, Mutation_Annotated_Tree::Node* node, bool print_internal, bool print_branch_len, bool retain_original_branch_len, bool uncondense_leaves) {\n    std::stringstream newick_ss;\n    write_newick_string(newick_ss, T, node, print_internal, print_branch_len, retain_original_branch_len, uncondense_leaves);\n    return newick_ss.str();\n}\n\nstd::string Mutation_Annotated_Tree::get_newick_string (const Tree& T, bool print_internal, bool print_branch_len, bool retain_original_branch_len, bool uncondense_leaves) {\n    return get_newick_string(T, T.root, print_internal, print_branch_len, retain_original_branch_len, uncondense_leaves);\n}\n\n// Split string into words for a specific delimiter delim\nvoid Mutation_Annotated_Tree::string_split (std::string const& s, char delim, std::vector<std::string>& words) {\n    TIMEIT();\n    size_t start_pos = 0, end_pos = 0;\n    while ((end_pos = s.find(delim, start_pos)) != std::string::npos) {\n        if ((end_pos == start_pos) || end_pos >= s.length()) {\n            break;\n        }\n        words.emplace_back(s.substr(start_pos, end_pos-start_pos));\n        start_pos = end_pos+1;\n    }\n    auto last = s.substr(start_pos, s.size()-start_pos);\n    if (last != \"\") {\n        words.push_back(std::move(last));\n    }\n    \n}\n\n// Split string into words (delimited by space, tabs etc.)\nvoid Mutation_Annotated_Tree::string_split (std::string s, std::vector<std::string>& words) {\n    std::string curr = \"\";\n    std::vector<std::string> ret;\n    \n    // Used to split string around spaces.\n    std::istringstream ss(s);\n\n    std::string word;\n    // Traverse through all words\n    while (ss >> word) {\n        words.push_back(std::move(word));\n    };\n}\n\nMutation_Annotated_Tree::Tree Mutation_Annotated_Tree::create_tree_from_newick_string (std::string newick_string) {\n    TIMEIT();\n    Tree T;\n\n    std::vector<std::string> leaves;\n    std::vector<size_t> num_open;\n    std::vector<size_t> num_close;\n    std::vector<std::queue<float>> branch_len (128);  // will be resized later if needed\n    size_t level = 0;\n\n    std::vector<std::string> s1;\n    string_split(newick_string, ',', s1);\n\n    num_open.reserve(s1.size());\n    num_close.reserve(s1.size());\n\n    for (auto s: s1) {\n        size_t no = 0;\n        size_t nc = 0;\n        bool stop = false;\n        bool branch_start = false;\n        std::string leaf = \"\";\n        std::string branch = \"\";\n        for (auto c: s) {\n            if (c == ':') {\n                stop = true;\n                branch = \"\";\n                branch_start = true;\n            }\n            else if (c == '(') {\n                no++;\n                level++;\n                if (branch_len.size() <= level) {\n                  branch_len.resize(level*2);\n                }\n            }\n            else if (c == ')') {\n                stop = true;\n                nc++;\n                float len = (branch.size() > 0) ? std::stof(branch) : -1.0;\n                branch_len[level].push(len);\n                level--;\n                branch_start = false;\n            }\n            else if (!stop) {\n                leaf += c;\n                branch_start = false;\n            }\n            else if (branch_start) {\n                if (isdigit(c)  || c == '.' || c == 'e' || c == 'E' || c == '-' || c == '+') {\n                    branch += c;\n                }\n            }\n        }\n        leaves.push_back(std::move(leaf));\n        num_open.push_back(no);\n        num_close.push_back(nc);\n        float len = (branch.size() > 0) ? std::stof(branch) : -1.0;\n        branch_len[level].push(len);\n    }\n\n    if (level != 0) {\n        fprintf(stderr, \"ERROR: incorrect Newick format!\\n\");\n        exit(1);\n    }\n\n    T.curr_internal_node = 0;\n    std::stack<Node*> parent_stack;\n\n    for (size_t i=0; i<leaves.size(); i++) {\n        auto leaf = leaves[i];\n        auto no = num_open[i];\n        auto nc = num_close[i];\n        for (size_t j=0; j<no; j++) {\n            std::string nid = std::to_string(++T.curr_internal_node);\n            Node* new_node = NULL;\n            if (parent_stack.size() == 0) {\n                new_node = T.create_node(nid, branch_len[level].front());\n            }\n            else {\n                new_node = T.create_node(nid, parent_stack.top(), branch_len[level].front());\n            }\n            branch_len[level].pop();\n            level++;\n            parent_stack.push(new_node);\n        }\n        T.create_node(leaf, parent_stack.top(), branch_len[level].front());\n        branch_len[level].pop();\n        for (size_t j=0; j<nc; j++) {\n            parent_stack.pop();\n            level--;\n        }\n    }\n\n    if (T.root == NULL) {\n        fprintf(stderr, \"WARNING: Tree found empty!\\n\");\n    }\n\n    return T;\n}\n\nMutation_Annotated_Tree::Tree Mutation_Annotated_Tree::create_tree_from_newick (std::string filename) {\n    std::ifstream infile(filename);\n    if (!infile) {\n        fprintf(stderr, \"ERROR: Could not open the tree file: %s!\\n\", filename.c_str());\n        exit(1);\n    }\n    std::string newick_string;\n    std::getline(infile, newick_string);\n\n    return create_tree_from_newick_string(newick_string);\n}\n\nMutation_Annotated_Tree::Tree Mutation_Annotated_Tree::load_mutation_annotated_tree (std::string filename) {\n    TIMEIT();\n    Tree tree;\n\n    Parsimony::data data;\n\n    std::ifstream inpfile(filename, std::ios::in | std::ios::binary);\n    if (!inpfile) {\n        fprintf(stderr, \"ERROR: Could not load the mutation-annotated tree object from file: %s!\\n\", filename.c_str());\n        exit(1);\n    }\n\n    // Boost library used to stream the contents of the input protobuf file in\n    // uncompressed or compressed .gz format\n    if (filename.find(\".gz\\0\") != std::string::npos) {\n        boost::iostreams::filtering_istream instream;\n        try {\n            instream.push(boost::iostreams::gzip_decompressor());\n            instream.push(inpfile);\n        }\n        catch(const boost::iostreams::gzip_error& e) {\n            std::cout << e.what() << '\\n';\n        }\n\n        data.ParseFromIstream(&instream);\n        inpfile.close();\n    }\n    else {\n        data.ParseFromIstream(&inpfile);\n        inpfile.close();\n    }\n\n    //check if the pb has a metadata field\n    bool hasmeta = (data.metadata_size()>0);\n    if (!hasmeta) {\n        fprintf(stderr, \"WARNING: This pb does not include any metadata. Filling in default values\\n\");\n    }\n    tree = create_tree_from_newick_string(data.newick());\n    auto dfs = tree.depth_first_expansion();\n    static tbb::affinity_partitioner ap;\n    tbb::parallel_for( tbb::blocked_range<size_t>(0, dfs.size()),\n            [&](tbb::blocked_range<size_t> r) {\n            for (size_t idx = r.begin(); idx < r.end(); idx++) {\n               auto node = dfs[idx];\n               auto mutation_list = data.node_mutations(idx);\n               if (hasmeta) {\n                   for (int k = 0; k < data.metadata(idx).clade_annotations_size(); k++) {\n                       node->clade_annotations.emplace_back(data.metadata(idx).clade_annotations(k)); \n                   }\n               } \n               for (int k = 0; k < mutation_list.mutation_size(); k++) {\n                  auto mut = mutation_list.mutation(k);\n                  Mutation m;\n                  m.chrom = mut.chromosome();\n                  m.position = mut.position();\n                  if (!m.is_masked()) {\n                     m.ref_nuc = (1 << mut.ref_nuc());\n                     m.par_nuc = (1 << mut.par_nuc());\n                     m.is_missing = false;\n                     std::vector<int8_t> nuc_vec(mut.mut_nuc_size());\n                     for (int n = 0; n < mut.mut_nuc_size(); n++) {\n                        nuc_vec[n] = mut.mut_nuc(n);\n                     }\n                     m.mut_nuc = get_nuc_id(nuc_vec);\n                     if (m.mut_nuc != m.par_nuc) {\n                         node->add_mutation(m);\n                     }\n                  }\n                  else {\n                      // Mutation masked\n                      m.ref_nuc = 0;\n                      m.par_nuc = 0;\n                      m.mut_nuc = 0;\n                      node->add_mutation(m);\n                  }\n               }\n               if (!std::is_sorted(node->mutations.begin(), node->mutations.end())) {\n                   fprintf(stderr, \"WARNING: Mutations not sorted!\\n\");\n                   std::sort(node->mutations.begin(), node->mutations.end());\n               }\n            }\n        }, ap);\n\n    size_t num_condensed_nodes = static_cast<size_t>(data.condensed_nodes_size());\n    tbb::parallel_for( tbb::blocked_range<size_t>(0, num_condensed_nodes),\n            [&](tbb::blocked_range<size_t> r) {\n            for (size_t idx = r.begin(); idx < r.end(); idx++) {\n               auto cn = data.condensed_nodes(idx);\n               tree.condensed_nodes.emplace(std::pair<std::string, std::vector<std::string>>(cn.node_name(), std::vector<std::string>(cn.condensed_leaves_size())));\n               for (int k = 0; k < cn.condensed_leaves_size(); k++) {\n                  tree.condensed_nodes[cn.node_name()][k] = cn.condensed_leaves(k);\n                  tree.condensed_leaves.emplace(cn.condensed_leaves(k));\n               }\n            }\n    }, ap);\n\n    return tree;\n}\n\nvoid Mutation_Annotated_Tree::save_mutation_annotated_tree (Mutation_Annotated_Tree::Tree tree, std::string filename) {\n    TIMEIT();\n    Parsimony::data data;\n    data.set_newick(get_newick_string(tree, false, true, true));\n\n    auto dfs = tree.depth_first_expansion();\n\n    for (size_t idx = 0; idx < dfs.size(); idx++) {\n        auto meta = data.add_metadata();\n        for (size_t k = 0; k < dfs[idx]->clade_annotations.size(); k++) {\n            meta->add_clade_annotations(dfs[idx]->clade_annotations[k]);\n        }\n        auto mutation_list = data.add_node_mutations();\n        for (auto m: dfs[idx]->mutations) {\n            auto mut = mutation_list->add_mutation();\n            mut->set_chromosome(m.chrom);\n            mut->set_position(m.position);\n            \n            if (m.is_masked()) {\n                mut->set_ref_nuc(-1);\n                mut->set_par_nuc(-1);\n            }\n            else {\n                int8_t j = get_nt(m.ref_nuc);\n                assert (j >= 0);\n                mut->set_ref_nuc(j);\n\n                j = get_nt(m.par_nuc);\n                assert(j >= 0);\n                mut->set_par_nuc(j);\n\n                mut->clear_mut_nuc();\n                for (auto nuc: get_nuc_vec_from_id(m.mut_nuc)) {\n                    mut->add_mut_nuc(nuc);\n                }\n            }\n        }\n    }\n\n    // Add condensed nodes\n    for (auto cn: tree.condensed_nodes) {\n        auto cn_ptr = data.add_condensed_nodes();\n        cn_ptr->set_node_name(cn.first);\n        for (auto lid: cn.second) {\n            cn_ptr->add_condensed_leaves(lid);\n        }\n    }\n\n    // Boost library used to stream the contents to the output protobuf file in\n    // uncompressed or compressed .gz format\n    std::ofstream outfile(filename, std::ios::out | std::ios::binary);\n    boost::iostreams::filtering_streambuf< boost::iostreams::output> outbuf;\n        \n    if (filename.find(\".gz\\0\") != std::string::npos) {\n        try {\n            outbuf.push(boost::iostreams::gzip_compressor());\n            outbuf.push(outfile);\n            std::ostream outstream(&outbuf);\n            data.SerializeToOstream(&outstream);\n            boost::iostreams::close(outbuf);\n            outfile.close();\n        }\n        catch(const boost::iostreams::gzip_error& e) {\n            std::cout << e.what() << '\\n';\n        }\n    }\n    else {\n        data.SerializeToOstream(&outfile);\n        outfile.close();\n    }\n}\n\n/* === Node === */\nbool Mutation_Annotated_Tree::Node::is_leaf () {\n    return (children.size() == 0);\n}\n\nbool Mutation_Annotated_Tree::Node::is_root() {\n    return (parent == NULL);\n}\n\nMutation_Annotated_Tree::Node::Node() {\n    level = 0;\n    identifier = \"\";\n    parent = NULL;\n    branch_length = -1.0;\n    clade_annotations.clear();\n    mutations.clear();\n}\n\nMutation_Annotated_Tree::Node::Node (std::string id, float len) {\n    identifier = id;\n    parent = NULL;\n    level = 1;\n    branch_length = len;\n    mutations.clear();\n}\n\nMutation_Annotated_Tree::Node::Node (std::string id, Node* p, float len) {\n    identifier = id;\n    parent = p;\n    level = p->level + 1;\n    branch_length = len;\n    mutations.clear();\n}\n\n// Assumes mutations are added in chronological order. If a new mutation occurs\n// at the same position, it should either be updated to the new allele or\n// removed entirely (in case of reversal mutation)\nvoid Mutation_Annotated_Tree::Node::add_mutation (Mutation mut) {\n    auto iter = std::lower_bound(mutations.begin(), mutations.end(), mut);\n    // check if mutation at the same position has occured before\n    if ((iter != mutations.end()) && (iter->position == mut.position)) {\n        // update to new allele\n        if (iter->par_nuc != mut.mut_nuc) {\n            iter->mut_nuc = mut.mut_nuc;\n        }\n        //reversal mutation\n        else {\n            std::vector<Mutation> tmp;\n            for (auto m: mutations) {\n                if (m.position != iter->position) {\n                    tmp.emplace_back(m.copy());\n                }\n            }\n            mutations.clear();\n            for (auto m: tmp) {\n                mutations.emplace_back(m.copy());\n            }\n        }\n    }\n    // new mutation\n    else {\n        mutations.insert(iter, mut);\n    }\n}\n\nvoid Mutation_Annotated_Tree::Node::clear_mutations() {\n    mutations.clear();\n}\n\nvoid Mutation_Annotated_Tree::Node::clear_annotations() {\n    clade_annotations.clear();\n}\n\n/* === Tree === */\nsize_t Mutation_Annotated_Tree::Tree::get_max_level () const {\n    size_t max_level = 0;\n    for (auto x: all_nodes) {\n        if (x.second->level > max_level) {\n            max_level = x.second->level;\n        }\n    }\n    return max_level;\n}\n        \nsize_t Mutation_Annotated_Tree::Tree::get_num_annotations () const {\n    size_t ret = 0;\n    if (root != NULL) {\n        ret = root->clade_annotations.size();\n    }\n    return ret;\n}\n        \nvoid Mutation_Annotated_Tree::Tree::rename_node(std::string old_nid, std::string new_nid) {\n    auto n = get_node(old_nid);\n    if (n != NULL) {\n        n->identifier = new_nid;\n        all_nodes.erase(old_nid);\n        all_nodes[new_nid] = n;\n    }\n    else {\n        fprintf(stderr, \"ERROR: %s not found in the Tree!\\n\", old_nid.c_str());\n        exit(1);\n    }\n}\n\nstd::vector<Mutation_Annotated_Tree::Node*> Mutation_Annotated_Tree::Tree::get_leaves(std::string nid) {\n    std::vector<Node*> leaves;\n    if (nid == \"\") {\n        if (root == NULL) {\n            return leaves;\n        }\n        nid = root->identifier;\n    }\n    Node* node = all_nodes[nid];\n\n    std::queue<Node*> remaining_nodes;\n    remaining_nodes.push(node);\n    while (remaining_nodes.size() > 0) {\n        Node* curr_node = remaining_nodes.front();\n        if (curr_node->children.size() == 0)\n            leaves.push_back(curr_node);\n        remaining_nodes.pop();\n        for (auto c: curr_node->children) {\n            remaining_nodes.push(c);\n        }\n    }\n    return leaves;\n}\n\nstd::vector<std::string> Mutation_Annotated_Tree::Tree::get_leaves_ids(std::string nid) {\n    std::vector<std::string> leaves_ids;\n    if (nid == \"\") {\n        if (root == NULL) {\n            return leaves_ids;\n        }\n        nid = root->identifier;\n    }\n    Node* node = all_nodes[nid];\n\n    std::queue<Node*> remaining_nodes;\n    remaining_nodes.push(node);\n    while (remaining_nodes.size() > 0) {\n        Node* curr_node = remaining_nodes.front();\n        if (curr_node->children.size() == 0)\n            leaves_ids.push_back(curr_node->identifier);\n        remaining_nodes.pop();\n        for (auto c: curr_node->children) {\n            remaining_nodes.push(c);\n        }\n    }\n    return leaves_ids;\n}\n\nsize_t Mutation_Annotated_Tree::Tree::get_num_leaves(Node* node) {\n    if (node == NULL) {\n        node = root;\n    }\n\n    if (node->is_leaf()) {\n        return 1;\n    }\n    size_t num_leaves = 0;\n    for (auto c: node->children) {\n        num_leaves += get_num_leaves(c);\n    }\n    return num_leaves;\n}\n\nMutation_Annotated_Tree::Node* Mutation_Annotated_Tree::Tree::create_node (std::string const& identifier, float branch_len, size_t num_annotations) {\n    all_nodes.clear();\n    Node* n = new Node(identifier, branch_len);\n    for (size_t k=0; k < num_annotations; k++) {\n        n->clade_annotations.emplace_back(\"\");\n    }\n    root = n;\n    all_nodes[identifier] = root;\n    return n;\n}\n\nMutation_Annotated_Tree::Node* Mutation_Annotated_Tree::Tree::create_node (std::string const& identifier, Node* par, float branch_len) {\n    if (all_nodes.find(identifier) != all_nodes.end()) {\n        fprintf(stderr, \"Error: %s already in the tree!\\n\", identifier.c_str());\n        exit(1);\n    }\n    Node* n = new Node(identifier, par, branch_len);\n    size_t num_annotations = get_num_annotations();\n    for (size_t k=0; k < num_annotations; k++) {\n        n->clade_annotations.emplace_back(\"\");\n    }\n    all_nodes[identifier] = n;\n    par->children.push_back(n);\n    return n;\n}\n\nMutation_Annotated_Tree::Node* Mutation_Annotated_Tree::Tree::create_node (std::string const& identifier, std::string const& parent_id, float branch_len) {\n    Node* par = all_nodes[parent_id];\n    return create_node(identifier, par, branch_len);\n}\n\nMutation_Annotated_Tree::Node* Mutation_Annotated_Tree::Tree::get_node (std::string nid) const {\n    if (all_nodes.find(nid) != all_nodes.end()) {\n        return all_nodes.at(nid);\n    }\n    return NULL;\n\n}\n\nbool Mutation_Annotated_Tree::Tree::is_ancestor (std::string anc_id, std::string nid) const {\n    Node* node = get_node(nid);\n    while (node->parent != NULL) {\n        node = node->parent;\n        if (node->identifier == anc_id) {\n            return true;\n        }\n    }\n    return false; \n}\n\nstd::vector<Mutation_Annotated_Tree::Node*> Mutation_Annotated_Tree::Tree::rsearch (const std::string& nid, bool include_self) const {\n    std::vector<Node*> ancestors;\n    Node* node = get_node(nid);\n    if (node==NULL) {\n        return ancestors;\n    }    \n    if (include_self) {\n        ancestors.push_back(node);\n    }\n    while (node->parent != NULL) {\n        ancestors.push_back(node->parent);\n        node = node->parent;\n    }\n    return ancestors;\n}\n\nvoid Mutation_Annotated_Tree::Tree::remove_node_helper (std::string nid, bool move_level) { \n    auto it = all_nodes.find(nid);\n    if (it == all_nodes.end()) {\n        fprintf(stderr, \"ERROR: Tried to remove node identifier %s but it was not found!\\n\", nid.c_str());\n        exit(1);\n    }\n    Node* source = it->second;\n    Node* curr_parent = source->parent;\n    \n    if (curr_parent != NULL) {\n        // Remove source from curr_parent\n        auto iter = std::find(curr_parent->children.begin(), curr_parent->children.end(), source);\n        assert (iter != curr_parent->children.end());\n        curr_parent->children.erase(iter);\n\n        // Remove parent if it no longer has any children\n        if (curr_parent->children.size() == 0) {\n            if (curr_parent == root) {\n                fprintf(stderr, \"ERROR: Tree empty!\\n\");\n                exit(1);\n            }\n            remove_node_helper (curr_parent->identifier, move_level);\n        }\n        // Move the remaining child one level up if it is the only child of its parent \n        else if (move_level && (curr_parent->children.size() == 1)) {\n            auto child = curr_parent->children[0];\n            if (curr_parent->parent != NULL) {\n                for (size_t k=0; k < curr_parent->clade_annotations.size(); k++) {\n                    if (child->clade_annotations[k] == \"\") {\n                        child->clade_annotations[k] = curr_parent->clade_annotations[k];\n                    }\n                }\n                child->parent = curr_parent->parent;\n                child->level = curr_parent->parent->level + 1;\n                child->branch_length += curr_parent->branch_length;\n\n                std::vector<Mutation> tmp;\n                for (auto m: child->mutations) {\n                    tmp.emplace_back(m.copy());\n                }\n\n                //Clear and add back mutations in chrono order\n                child->clear_mutations();\n                for (auto m: curr_parent->mutations) {\n                    child->add_mutation(m.copy());\n                }\n                for (auto m: tmp) {\n                    child->add_mutation(m.copy());\n                }\n\n                curr_parent->parent->children.push_back(child);\n                \n                iter = std::find(curr_parent->parent->children.begin(), curr_parent->parent->children.end(), curr_parent);\n                assert(iter != curr_parent->parent->children.end());\n                curr_parent->parent->children.erase(iter);\n                \n                // Update levels of source descendants\n                std::queue<Node*> remaining_nodes;\n                remaining_nodes.push(child);\n                while (remaining_nodes.size() > 0) {\n                    Node* curr_node = remaining_nodes.front();\n                    remaining_nodes.pop();\n                    curr_node->level = curr_node->parent->level + 1;\n                    for (auto c: curr_node->children) {\n                        remaining_nodes.push(c);\n                    }\n                }\n            }\n\n            auto par_it = all_nodes.find(curr_parent->identifier);\n            assert (par_it != all_nodes.end());\n            all_nodes.erase(par_it);\n            delete curr_parent;\n        }\n    }\n\n    //Remove source and descendants from all_nodes\n    std::queue<Node*> desc;\n    desc.push(source);\n    while (desc.size() > 0) {\n        Node* curr_node = desc.front();\n        desc.pop();\n        for (auto c: curr_node->children) {\n            desc.push(c);\n        }\n        it = all_nodes.find(curr_node->identifier);\n        all_nodes.erase(it);\n        delete curr_node;\n    }\n}\n\nvoid Mutation_Annotated_Tree::Tree::remove_node (std::string nid, bool move_level) { \n    TIMEIT();\n    remove_node_helper (nid, move_level);\n}\n\nvoid Mutation_Annotated_Tree::Tree::move_node (std::string source_id, std::string dest_id, bool move_level) {\n    Node* source = all_nodes[source_id];\n    Node* destination = all_nodes[dest_id];\n    Node* curr_parent = source->parent;\n\n    source->parent = destination;\n    source->branch_length = -1.0; // Invalidate source branch length\n\n    destination->children.push_back(source);\n\n    // Remove source from curr_parent\n    auto iter = std::find(curr_parent->children.begin(), curr_parent->children.end(), source);\n    curr_parent->children.erase(iter);\n    if (curr_parent->children.size() == 0) {\n        remove_node(curr_parent->identifier, move_level);\n    }\n    \n    // Update levels of source descendants\n    std::queue<Node*> remaining_nodes;\n    remaining_nodes.push(source);\n    while (remaining_nodes.size() > 0) {\n        Node* curr_node = remaining_nodes.front();\n        remaining_nodes.pop();\n        curr_node->level = curr_node->parent->level + 1;\n        for (auto c: curr_node->children) {\n            remaining_nodes.push(c);\n        }\n    }\n}\n\nstd::vector<Mutation_Annotated_Tree::Node*> Mutation_Annotated_Tree::Tree::breadth_first_expansion(std::string nid) {\n    std::vector<Node*> traversal;\n    \n    if (nid == \"\") {\n        if (root == NULL) {\n            return traversal;\n        }\n        nid = root->identifier;\n    }\n\n    Node* node = all_nodes[nid];\n\n    std::queue<Node*> remaining_nodes;\n    remaining_nodes.push(node);\n    while (remaining_nodes.size() > 0) {\n        Node* curr_node = remaining_nodes.front();\n        traversal.push_back(curr_node);\n        remaining_nodes.pop();\n        for (auto c: curr_node->children) {\n            remaining_nodes.push(c);\n        }\n    }\n\n    return traversal;\n}\n\nvoid Mutation_Annotated_Tree::Tree::depth_first_expansion_helper(Mutation_Annotated_Tree::Node* node, std::vector<Mutation_Annotated_Tree::Node*>& vec) const {\n    vec.push_back(node);\n    for (auto c: node->children) {\n        depth_first_expansion_helper(c, vec);\n    }\n}\n\nstd::vector<Mutation_Annotated_Tree::Node*> Mutation_Annotated_Tree::Tree::depth_first_expansion(Mutation_Annotated_Tree::Node* node) const {\n    TIMEIT();\n    std::vector<Node*> traversal;\n    if (node == NULL) {\n        node = root;\n    }\n    if (node == NULL) {\n        return traversal;\n    }\n    depth_first_expansion_helper(node, traversal);\n    return traversal;\n}\n\nsize_t Mutation_Annotated_Tree::Tree::get_parsimony_score() {\n    size_t score = 0;\n    auto dfs = depth_first_expansion();\n    for (auto n: dfs) {\n        score += n->mutations.size();\n    }\n    return score;\n}\n\nvoid Mutation_Annotated_Tree::Tree::condense_leaves(std::vector<std::string> missing_samples) {\n    if (condensed_nodes.size() > 0) {\n        fprintf(stderr, \"WARNING: tree contains condensed nodes. It may be condensed already!\\n\");\n    }\n\n    auto tree_leaves = get_leaves_ids();\n    for (auto l1_id: tree_leaves) {\n        std::vector<Node*> polytomy_nodes;\n\n        auto l1 = get_node(l1_id);\n        if (l1 == NULL) {\n            continue;\n        }\n        if (std::find(missing_samples.begin(), missing_samples.end(), l1->identifier) != missing_samples.end()) {\n            continue;\n        }\n        if (l1->mutations.size() > 0) {\n            continue;\n        }\n\n        for (auto l2: l1->parent->children) {\n                if (std::find(missing_samples.begin(), missing_samples.end(), l2->identifier) != missing_samples.end()) {\n                    continue;\n                }\n            if (l2->is_leaf() && (get_node(l2->identifier) != NULL) && (l2->mutations.size() == 0)) {\n                polytomy_nodes.push_back(l2);\n            }\n        }\n        if (polytomy_nodes.size() > 1) {\n            std::string new_node_name = \"node_\" + std::to_string(1+condensed_nodes.size()) + \"_condensed_\" + std::to_string(polytomy_nodes.size()) + \"_leaves\";\n            \n            auto curr_node = get_node(l1->identifier);\n            auto new_node = create_node(new_node_name, curr_node->parent, l1->branch_length);\n\n            new_node->clear_mutations();\n            \n            condensed_nodes[new_node_name] = std::vector<std::string>(polytomy_nodes.size());\n\n            for (size_t it = 0; it < polytomy_nodes.size(); it++) {\n                condensed_nodes[new_node_name][it] = polytomy_nodes[it]->identifier;\n                remove_node(polytomy_nodes[it]->identifier, false);\n            }\n        }\n    }\n}\n\nvoid Mutation_Annotated_Tree::Tree::uncondense_leaves() {\n    tbb::mutex tbb_lock;\n    static tbb::affinity_partitioner ap;\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, condensed_nodes.size()),\n            [&](tbb::blocked_range<size_t> r) {\n            for (size_t it = r.begin(); it < r.end(); it++) {\n                auto cn = condensed_nodes.begin();\n                std::advance(cn, it);\n\n                tbb_lock.lock();\n                auto n = get_node(cn->first);\n                tbb_lock.unlock();\n                auto par = (n->parent != NULL) ? n->parent : n;\n\n                size_t num_samples = cn->second.size();\n\n                if (num_samples > 0) {\n                    tbb_lock.lock();\n                    rename_node(n->identifier, cn->second[0]);\n                    tbb_lock.unlock();\n                }\n\n                for (size_t s = 1; s < num_samples; s++) {\n                    tbb_lock.lock();\n                    auto new_n = create_node(cn->second[s], par, n->branch_length);\n                    tbb_lock.unlock();\n                    for (auto m: n->mutations) {\n                        new_n->add_mutation(m.copy());\n                    }\n                }\n            }\n        }, ap);\n    condensed_nodes.clear();\n    condensed_leaves.clear();\n}\n\n\nvoid Mutation_Annotated_Tree::Tree::collapse_tree() {\n    auto bfs = breadth_first_expansion();\n\n    for (size_t idx = 1; idx < bfs.size(); idx++) {\n        auto node = bfs[idx];\n        auto mutations = node->mutations;        \n        if (mutations.size() == 0) {\n            auto parent = node->parent;\n            auto children = node->children;\n            for (auto child: children) {\n                move_node(child->identifier, parent->identifier, false);\n            }\n        }\n        //If internal node has one child, the child can be moved up one level\n        else if (node->children.size() == 1) {\n            auto child = node->children.front();\n            auto parent = node->parent;\n            for (auto m: mutations) {\n                child->add_mutation(m.copy());\n            }\n            move_node(child->identifier, parent->identifier, false);\n        }\n    }\n}\n\nMutation_Annotated_Tree::Tree Mutation_Annotated_Tree::get_tree_copy(const Mutation_Annotated_Tree::Tree& tree, const std::string& identifier) {\n    TIMEIT();\n    auto root = tree.root;\n    if (identifier != \"\") {\n        root = tree.get_node(identifier);\n    }\n    \n    Tree copy = create_tree_from_newick_string (get_newick_string(tree, root, true, true));\n\n    std::vector<Node*> dfs1;\n    std::vector<Node*> dfs2;\n\n    static tbb::affinity_partitioner ap;\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, 2),\n            [&](tbb::blocked_range<size_t> r) {\n            for (size_t k=r.begin(); k<r.end(); ++k){\n              if (k==0) {\n                dfs1 = tree.depth_first_expansion(root);\n              }\n              else {\n                dfs2 = copy.depth_first_expansion();\n              }\n            }\n            }, ap);\n\n\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, dfs1.size()),\n            [&](tbb::blocked_range<size_t> r) {\n            for (size_t k=r.begin(); k<r.end(); ++k){\n              auto n1 = dfs1[k];\n              auto n2 = dfs2[k];\n              n2->clade_annotations.resize(n1->clade_annotations.size());\n              for (size_t i=0; i<n1->clade_annotations.size(); i++) {\n                 n2->clade_annotations[i] = n1->clade_annotations[i];\n              }\n              for (auto m: n1->mutations) {\n                Mutation m2 = m.copy();\n                n2->add_mutation(m2);\n                }\n              }\n            }, ap);\n\n    size_t num_condensed_nodes = static_cast<size_t>(tree.condensed_nodes.size());\n    tbb::parallel_for( tbb::blocked_range<size_t>(0, num_condensed_nodes),\n            [&](tbb::blocked_range<size_t> r) {\n            for (size_t idx = r.begin(); idx < r.end(); idx++) {\n               auto cn = tree.condensed_nodes.begin(); \n               std::advance(cn, idx);\n               copy.condensed_nodes.insert(std::pair<std::string, std::vector<std::string>>(cn->first, std::vector<std::string>(cn->second.size())));\n               for (size_t k = 0; k < cn->second.size(); k++) {\n                  copy.condensed_nodes[cn->first][k] = cn->second[k];\n                  copy.condensed_leaves.insert(cn->second[k]);\n               }\n            }\n    }, ap);\n\n    return copy;\n}\n\n// Get the last common ancestor of two node identifiers. Return NULL if does not\n// exist\nMutation_Annotated_Tree::Node* Mutation_Annotated_Tree::LCA (const Mutation_Annotated_Tree::Tree& tree, const std::string& nid1, const std::string& nid2) {\n    TIMEIT();\n    \n    if ((tree.get_node(nid1) == NULL) || (tree.get_node(nid2) == NULL)) {\n        return NULL;\n    }\n\n    auto n2_ancestors = tree.rsearch(nid2, true);\n\n    for (auto anc1: tree.rsearch(nid1, true)) {\n        for (auto anc2: n2_ancestors) {\n            if (anc1 == anc2) {\n                return anc1;\n            }\n        }\n    }\n\n    return NULL;\n}\n\n// Extract the subtree consisting of the specified set of samples. This routine\n// maintains the internal node names of the input tree. Mutations are copied\n// from the tree such that the path of mutations from root to the sample is\n// same as the original tree.\nMutation_Annotated_Tree::Tree Mutation_Annotated_Tree::get_subtree (const Mutation_Annotated_Tree::Tree& tree, const std::vector<std::string>& samples) {\n    TIMEIT();\n    Tree subtree;\n\n    // Set of leaf and internal nodes corresponding to the subtree\n    tbb::concurrent_unordered_set<Node*> subtree_nodes;\n    // Maintain a set of all ancestors of a sample for each sample\n    std::vector<tbb::concurrent_unordered_set<Node*>> all_ancestors(samples.size());\n\n    static tbb::affinity_partitioner ap;\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, samples.size()),\n            [&](tbb::blocked_range<size_t> r) {\n            for (size_t k=r.begin(); k<r.end(); ++k){\n               subtree_nodes.insert(tree.get_node(samples[k]));\n               for (auto anc: tree.rsearch(samples[k], true)) {\n                   all_ancestors[k].insert(anc);\n               }\n            }\n    }, ap);\n\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, samples.size()),\n            [&](tbb::blocked_range<size_t> r) {\n            for (size_t i=r.begin(); i<r.end(); ++i){\n               for (size_t j=i+1; j<samples.size(); ++j){\n                   for (auto anc: tree.rsearch(samples[i], true)) {\n                      if (all_ancestors[j].find(anc) != all_ancestors[j].end()) {\n                         subtree_nodes.insert(anc);\n                         break;\n                      }\n                   }\n               }\n            }\n    }, ap);\n    \n    auto dfs = tree.depth_first_expansion();\n    size_t num_annotations = tree.get_num_annotations();\n\n    std::stack<Node*> last_subtree_node;\n    for (auto n: dfs) {\n        // If the node is in subtree_nodes, it should be added to the subtree\n        if (subtree_nodes.find(n) != subtree_nodes.end()) {\n            Node* subtree_parent = NULL;\n            if (last_subtree_node.size() > 0) {\n                while (!tree.is_ancestor(last_subtree_node.top()->identifier, n->identifier)) {\n                    last_subtree_node.pop();\n                }\n                subtree_parent = last_subtree_node.top();\n            }\n            // Add as root of the subtree\n            if (subtree_parent == NULL) {\n                // for root node, need to size the annotations vector\n                Node* new_node = subtree.create_node(n->identifier, -1.0, num_annotations);\n                // need to assign any clade annotations which would belong to that root as well\n                for (size_t k = 0; k < num_annotations; k++) {\n                    if (n->clade_annotations[k] != \"\") {\n                        new_node->clade_annotations[k] = n->clade_annotations[k];\n                    }\n                }\n                std::vector<Node*> root_to_node = tree.rsearch(n->identifier, true); \n                std::reverse(root_to_node.begin(), root_to_node.end());\n                root_to_node.emplace_back(n);\n\n                for (auto curr: root_to_node) {\n                    for (auto m: curr->mutations) {\n                        new_node->add_mutation(m);\n                    }\n                }\n            }\n            // Add to the parent identified\n            else {\n                Node* new_node = subtree.create_node(n->identifier, subtree_parent->identifier);\n\n                auto par_to_node = tree.rsearch(n->identifier, true);\n                std::reverse(par_to_node.begin(), par_to_node.end());\n                par_to_node.erase(par_to_node.begin(), std::find(par_to_node.begin(), par_to_node.end(), subtree_parent)+1);\n\n\n                for (auto curr: par_to_node) {\n                    for (size_t k = 0; k < num_annotations; k++) {\n                        if (curr->clade_annotations[k] != \"\") {\n                            new_node->clade_annotations[k] = curr->clade_annotations[k];\n                        }\n                    }\n                    for (auto m: curr->mutations) {\n                        new_node->add_mutation(m);\n                    }\n                }\n            }\n            last_subtree_node.push(n);\n        }\n    }\n\n    subtree.curr_internal_node = tree.curr_internal_node;\n\n    return subtree;\n}\n\nvoid Mutation_Annotated_Tree::clear_tree(Mutation_Annotated_Tree::Tree& T) {\n    for (auto n: T.depth_first_expansion()) {\n        delete(n);\n    }\n}\n", "meta": {"hexsha": "102e7a092081b58d37f2ac38a5147d4af33ffd04", "size": 45733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mutation_annotated_tree.cpp", "max_stars_repo_name": "lgozasht/usher", "max_stars_repo_head_hexsha": "4afe8e59a5d60ee9516a52111c1852b2d6fb53df", "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/mutation_annotated_tree.cpp", "max_issues_repo_name": "lgozasht/usher", "max_issues_repo_head_hexsha": "4afe8e59a5d60ee9516a52111c1852b2d6fb53df", "max_issues_repo_licenses": ["MIT"], "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/mutation_annotated_tree.cpp", "max_forks_repo_name": "lgozasht/usher", "max_forks_repo_head_hexsha": "4afe8e59a5d60ee9516a52111c1852b2d6fb53df", "max_forks_repo_licenses": ["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.3340840841, "max_line_length": 253, "alphanum_fraction": 0.5329849343, "num_tokens": 10801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19925680465702822}}
{"text": "#include <boost/algorithm/hex.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.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 \"./comparerLogic.h\"\n\nusing namespace std;\n\nusing namespace nil::crypto3::zk::components;\nusing namespace nil::crypto3::zk::snark;\n\n\nushort INVALID_PROOF_RETURN_CODE = 200;\n\nstd::string convert_byteblob_to_hex_string(std::vector<std::uint8_t> blob) {\n    // convert byte_blob to hex string and print it to output\n    std::string hex;\n    hex.reserve(blob.size() * 2);\n    boost::algorithm::hex(blob.begin(), blob.end(), back_inserter(hex));\n    return hex;\n}\n\nvoid save_byteblob(std::vector<std::uint8_t> byteblob, boost::filesystem::path fname) {\n    boost::filesystem::ofstream out(fname);\n    for (const auto &v : byteblob) {\n        out << v;\n    }\n    out.close();\n}\n\nstd::vector<std::uint8_t> load_byteblob(boost::filesystem::path fname) {\n    boost::filesystem::ifstream stream(fname, std::ios::in | std::ios::binary);\n    std::vector<std::uint8_t> contents((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());\n    if (contents.size() == 0) {\n        throw std::ios_base::failure(\"Empty file\");\n    }\n    return contents;\n}\n\n\n// proving key\n\nvoid save_proving_key(scheme_type::proving_key_type pk, boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(pk);\n    save_byteblob(byteblob, fname);\n}\n\nscheme_type::proving_key_type load_proving_key(boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = load_byteblob(fname);\n    nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n    return nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::proving_key_process(\n        byteblob.cbegin(),\n        byteblob.cend(),\n        processingStatus);\n}\n\n// verification key\n\nvoid save_verification_key(scheme_type::verification_key_type vk, boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(vk);\n    save_byteblob(byteblob, fname);\n}\n\nscheme_type::verification_key_type load_verification_key(boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = load_byteblob(fname);\n    nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n    return nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::verification_key_process(\n        byteblob.cbegin(),\n        byteblob.cend(),\n        processingStatus);\n}\n\n// proof\n\nvoid save_proof(scheme_type::proof_type proof, boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(proof);\n    save_byteblob(byteblob, fname);\n}\n\nscheme_type::proof_type load_proof(boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = load_byteblob(fname);\n    nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n    return nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::proof_process(\n        byteblob.cbegin(),\n        byteblob.cend(),\n        processingStatus);\n}\n\n\n//  primary input\n\nvoid save_primary_input(zk::snark::r1cs_primary_input<field_type> primary_input, boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(primary_input);\n    save_byteblob(byteblob, fname);\n}\n\nzk::snark::r1cs_primary_input<field_type> load_primary_input(boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = load_byteblob(fname);\n    nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n    return nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::primary_input_process(\n        byteblob.cbegin(),\n        byteblob.cend(),\n        processingStatus);\n}\n\n\nint setup_keys(boost::filesystem::path pk_path, boost::filesystem::path vk_path) {\n\n    blueprint<field_type> bp;\n    ComparerLogic comparerLogic(bp);\n    comparerLogic.generate_r1cs_constraints(bp);\n\n    cout << \"Blueprint size: \" << bp.num_variables() << endl;\n    cout << \"Generating constraint system...\" << endl;\n    const r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system();\n    cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n\n    cout << \"Generating keypair...\" << endl;\n    scheme_type::keypair_type keypair = generate<scheme_type>(constraint_system);\n\n    cout << \"Saving proving key to a file \" << pk_path<< endl;\n    save_proving_key(keypair.first, pk_path);\n\n    cout << \"Saving verification key to a file \" << vk_path << endl;\n    save_verification_key(keypair.second, vk_path);\n\n    return 0;\n}\n\nint create_proof(boost::filesystem::path pk_path, boost::filesystem::path proof_path, boost::filesystem::path pi_path, int minYear, int maxYear, int year) {\n\n    cout << \"Loading proving key from a file \" << pk_path << endl;\n    typename scheme_type::proving_key_type pk = load_proving_key(pk_path);\n\n    blueprint<field_type> bp;\n    ComparerLogic comparerLogic(bp);\n\n    cout << \"Generating constraint system...\" << endl;\n    comparerLogic.generate_r1cs_constraints(bp);\n\n    cout << \"Generating witness...\" << endl;\n    comparerLogic.generate_r1cs_witness(bp, minYear, maxYear, year);\n\n    cout << \"Blueprint is satisfied: \" << bp.is_satisfied() << endl;\n\n    if (!bp.is_satisfied()) {\n        return INVALID_PROOF_RETURN_CODE;\n    }\n\n    cout << \"Generating proof...\" << endl;\n    const scheme_type::proof_type proof = prove<scheme_type>(pk, bp.primary_input(), bp.auxiliary_input());\n\n    cout << \"Saving proof to file \" << proof_path << endl;\n    save_proof(proof, proof_path);\n\n    cout << \"Saving primary input to file \" << pi_path << endl;\n    save_primary_input(bp.primary_input(), pi_path);\n    return 0;\n}\n\nint verify_proof(boost::filesystem::path proof_path, boost::filesystem::path vk_path, boost::filesystem::path pi_path) {\n\n    cout << \"Loading proof from a file \" << proof_path << endl;\n    typename scheme_type::proof_type proof = load_proof(proof_path);\n\n    cout << \"Loading primary input from a file \" << pi_path << endl;\n    r1cs_primary_input<field_type> input = load_primary_input(pi_path);\n\n    cout << \"Loading verification key from a file \" << vk_path << endl;\n    typename scheme_type::verification_key_type vk = load_verification_key(vk_path);\n\n    // verify\n    using basic_proof_system = r1cs_gg_ppzksnark<curve_type>;\n    const bool verified = verify<basic_proof_system>(vk, input, proof);\n    cout << \"Verification status: \" << verified << endl;\n\n    return verified ? 0 : INVALID_PROOF_RETURN_CODE;\n}\n\nint main(int argc, char *argv[]) {\n    int maxYear, minYear, year;\n    boost::filesystem::path pk_path, vk_path, proof_path, pi_path;\n    // bool hexFlag;\n\n    boost::program_options::options_description options(\"CLI Proof Generator\");\n    options.add_options()\n    // (\"hex,h\", boost::program_options::bool_switch(&hexFlag), \"print only hex proof to output\")\n    (\"minYear,minYear\", boost::program_options::value<int>(&minYear)->default_value(0))\n    (\"maxYear,maxYear\", boost::program_options::value<int>(&maxYear)->default_value(100))\n    (\"year,year\", boost::program_options::value<int>(&year)->default_value(18))\n    (\"proving-key-path,pk\", boost::program_options::value<boost::filesystem::path>(&pk_path)->default_value(\"proving.key\"))\n    (\"verification-key-path,vk\", boost::program_options::value<boost::filesystem::path>(&vk_path)->default_value(\"verification.key\"))\n    (\"proof-path,p\", boost::program_options::value<boost::filesystem::path>(&proof_path)->default_value(\"proof\"))\n    (\"primary-input-path,pi\", boost::program_options::value<boost::filesystem::path>(&pi_path)->default_value(\"primary.input\"));\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).run(), vm);\n    boost::program_options::notify(vm);\n\n    cout << setprecision(16);\n\n    if (!argv[1]) {\n        cout << \"Please select a command: [setup/prove/verify]\" << endl;\n        return 0;\n    }\n    else if (string(argv[1]) == \"setup\") {\n        // Generate proving.key & verification.key\n        return setup_keys(pk_path, vk_path);\n    } else if (string(argv[1]) == \"prove\") {\n        return create_proof(pk_path, proof_path, pi_path, minYear, maxYear, year);\n    } else if (string(argv[1]) == \"verify\") {\n        return verify_proof(proof_path, pi_path, vk_path);\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "1d889df6e208be6bd21c6658dea0e5cd212821f8", "size": 9043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/bin/main.cpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "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/bin/main.cpp", "max_issues_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_issues_repo_licenses": ["MIT"], "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/bin/main.cpp", "max_forks_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 39.6622807018, "max_line_length": 156, "alphanum_fraction": 0.7160234435, "num_tokens": 2225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.19925680465702822}}
{"text": "#define _LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS\n#include \"matching.h\"\n\n#include <boost/histogram/ostream.hpp>\n#include <cstdint>\n#include <fstream>\n#include <gsl/gsl>\n#include <iterator>\n#include <opencv2/core/base.hpp>\n#include <opencv2/core/mat.hpp>\n#include <opencv2/core/types.hpp>\n#include <opencv2/features2d.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#include <sens_loc/analysis/distance.h>\n#include <sens_loc/io/histogram.h>\n#include <sens_loc/io/image.h>\n#include <sens_loc/util/console.h>\n#include <sens_loc/util/thread_analysis.h>\n#include <util/batch_visitor.h>\n#include <util/statistic_visitor.h>\n\nusing namespace cv;\nusing namespace std;\nusing namespace gsl;\n\nnamespace {\n\nstruct descriptor_stat_data {\n    descriptor_stat_data() = default;\n\n    void insert_matches(gsl::span<DMatch> matches,\n                        int               descriptor_count) noexcept {\n        lock_guard l{_mutex};\n        transform(begin(matches), end(matches),\n                  back_inserter(_global_minimal_distances),\n                  [](const DMatch& m) { return m.distance; });\n        _total_descriptors += descriptor_count;\n    }\n\n    pair<vector<float>, int64_t> extract() noexcept {\n        lock_guard                   l{_mutex};\n        pair<vector<float>, int64_t> p{move(_global_minimal_distances),\n                                       _total_descriptors};\n        _global_minimal_distances = vector<float>();\n        _total_descriptors        = 0UL;\n        return p;\n    }\n\n  private:\n    mutex                                   _mutex;\n    vector<float> _global_minimal_distances GUARDED_BY(_mutex);\n    int64_t _total_descriptors              GUARDED_BY(_mutex) = 0L;\n};\n\nclass matching {\n  public:\n    matching(descriptor_stat_data& accumulated_data,\n             NormTypes             norm_to_use,\n             bool                  crosscheck,\n             string_view           input_pattern,\n             optional<string_view> output_pattern,\n             optional<string_view> original_files) noexcept\n        : accumulated_data{accumulated_data}\n        , matcher{BFMatcher::create(norm_to_use, crosscheck)}\n        , input_pattern{input_pattern}\n        , output_pattern{output_pattern}\n        , original_images{original_files} {\n        // XOR is true if both operands have the same value.\n        Expects(!(output_pattern.has_value() ^ original_images.has_value()) &&\n                \"Either both or none are set\");\n    }\n\n    void operator()(int idx,\n                    optional<vector<KeyPoint>> /*keypoints*/,  // NOLINT\n                    optional<Mat> descriptors) noexcept {\n        Expects(descriptors.has_value());\n        if (descriptors->rows == 0)\n            return;\n\n        try {\n            const int         previous_idx = idx - 1;\n            const FileStorage previous_img = sens_loc::io::open_feature_file(\n                fmt::format(input_pattern, previous_idx));\n            Mat previous_descriptors =\n                sens_loc::io::load_descriptors(previous_img);\n\n            vector<DMatch> matches;\n            matcher->match(*descriptors, previous_descriptors, matches);\n            accumulated_data.insert_matches(matches, descriptors->rows);\n\n            // Plot the matching between the descriptors of the previous and the\n            // current frame.\n            if (output_pattern) {\n                const vector<KeyPoint> previous_keypoints =\n                    sens_loc::io::load_keypoints(previous_img);\n\n                const FileStorage this_feature =\n                    sens_loc::io::open_feature_file(\n                        fmt::format(input_pattern, idx));\n                const vector<KeyPoint> this_keypoints =\n                    sens_loc::io::load_keypoints(this_feature);\n\n                const string img_p1 = fmt::format(*original_images, idx - 1);\n                const string img_p2 = fmt::format(*original_images, idx);\n                auto         img1   = sens_loc::io::load_as_8bit_gray(img_p1);\n                auto         img2   = sens_loc::io::load_as_8bit_gray(img_p2);\n\n                if (!img1 || !img2)\n                    return;\n\n                Mat out_img;\n                drawMatches(img2->data(), this_keypoints, img1->data(),\n                            previous_keypoints, matches, out_img,\n                            Scalar(0, 0, 255), Scalar(255, 0, 0));\n\n                const string output = fmt::format(*output_pattern, idx);\n                imwrite(output, out_img);\n            }\n        } catch (...) {\n            std::cerr << sens_loc::util::err{}\n                      << \"Could not initialize data for idx: \" << idx << \"\\n\";\n            return;\n        }\n    }\n\n    size_t postprocess(const optional<string>& stat_file,\n                       const optional<string>& matched_distance_histo) {\n        auto [distances, total_descriptors] = accumulated_data.extract();\n        if (distances.empty())\n            return 0UL;\n\n        sort(begin(distances), end(distances));\n        const auto                   dist_bins = 25;\n        sens_loc::analysis::distance distance_stat{distances, dist_bins};\n\n        if (stat_file) {\n            cv::FileStorage stat_out{*stat_file,\n                                     cv::FileStorage::WRITE |\n                                         cv::FileStorage::FORMAT_YAML};\n            stat_out.writeComment(\n                \"The following values contain the results of the statistical \"\n                \"analysis for descriptor distance to the closest descriptor \"\n                \"after matching\");\n            write(stat_out, \"match_distance\", distance_stat.get_statistic());\n            stat_out.release();\n        } else {\n            cout << \"==== Match Distances\\n\"\n                 << \"total count:    \" << total_descriptors << \"\\n\"\n                 << \"matched count:  \" << distances.size() << \"\\n\"\n                 << \"matched/total:  \"\n                 << narrow_cast<double>(distances.size()) /\n                        narrow_cast<double>(total_descriptors)\n                 << \"\\n\"\n                 << \"min:            \" << distance_stat.min() << \"\\n\"\n                 << \"max:            \" << distance_stat.max() << \"\\n\"\n                 << \"median:         \" << distance_stat.median() << \"\\n\"\n                 << \"mean:           \" << distance_stat.mean() << \"\\n\"\n                 << \"Variance:       \" << distance_stat.variance() << \"\\n\"\n                 << \"StdDev:         \" << distance_stat.stddev() << \"\\n\"\n                 << \"Skewness:       \" << distance_stat.skewness() << \"\\n\";\n        }\n        if (matched_distance_histo) {\n            std::ofstream gnuplot_data{*matched_distance_histo};\n            gnuplot_data << sens_loc::io::to_gnuplot(distance_stat.histogram())\n                         << std::endl;\n        } else {\n            cout << distance_stat.histogram() << \"\\n\";\n        }\n        return distances.size();\n    }\n\n  private:\n    descriptor_stat_data& accumulated_data;\n\n    Ptr<BFMatcher>        matcher;\n    string_view           input_pattern;\n    optional<string_view> output_pattern;\n    optional<string_view> original_images;\n};\n}  // namespace\n\nnamespace sens_loc::apps {\nint analyze_matching(util::processing_input       in,\n                     NormTypes                    norm_to_use,\n                     bool                         crosscheck,\n                     const optional<string>&      stat_file,\n                     const optional<string>&      matched_distance_histo,\n                     const optional<string_view>& output_pattern,\n                     const optional<string_view>& original_files) {\n    Expects(in.start < in.end && \"Matching requires at least 2 images\");\n    using visitor = statistic_visitor<matching, required_data::descriptors>;\n    descriptor_stat_data data;\n    auto analysis_v = visitor{/*input_pattern=*/in.input_pattern,\n                              /*accumulated_data=*/data,\n                              /*norm_to_use=*/norm_to_use,\n                              /*crosscheck=*/crosscheck,\n                              /*input_pattern=*/in.input_pattern,\n                              /*output_pattern=*/output_pattern,\n                              /*original_files=*/original_files};\n\n    auto f = parallel_visitation(\n        in.start + 1,  // Because two consecutive images are matched, the first\n                       // index is skipped. This requires \"backwards\" matching.\n        in.end, analysis_v);\n    size_t n_elements = f.postprocess(stat_file, matched_distance_histo);\n\n    return n_elements > 0UL ? 0 : 1;\n}\n}  // namespace sens_loc::apps\n", "meta": {"hexsha": "753b10e79cbd22ced74beb8bd928d30d349fd554", "size": 8629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/apps/feature_performance/matching.cpp", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/apps/feature_performance/matching.cpp", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "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/apps/feature_performance/matching.cpp", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "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.8957345972, "max_line_length": 80, "alphanum_fraction": 0.5541777726, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.19925680085273043}}
{"text": "/**\n *****************************************************************************\n * @author     This file is part of tinyram_snark, developed by SCIPR Lab\n *             and contributors (see AUTHORS).\n * @copyright  MIT license (see LICENSE file)\n *****************************************************************************/\n#include <fstream>\n#include <iostream>\n#ifndef MINDEPS\n#include <boost/program_options.hpp>\n#endif\n\n#include <tinyram_snark/common/default_types/tinyram_ppzksnark_pp.hpp>\n#include <tinyram_snark/relations/ram_computations/rams/tinyram/tinyram_params.hpp>\n#include <tinyram_snark/zk_proof_systems/ppzksnark/ram_ppzksnark/ram_ppzksnark.hpp>\n\n#ifndef MINDEPS\nnamespace po = boost::program_options;\n\nbool process_prover_command_line(const int argc, const char** argv,\n                                 std::string &processed_assembly_fn,\n                                 std::string &proving_key_fn,\n                                 std::string &primary_input_fn,\n                                 std::string &auxiliary_input_fn,\n                                 std::string &proof_fn)\n{\n    try\n    {\n        po::options_description desc(\"Usage\");\n        desc.add_options()\n            (\"help\", \"print this help message\")\n            (\"processed_assembly\", po::value<std::string>(&processed_assembly_fn)->required())\n            (\"proving_key\", po::value<std::string>(&proving_key_fn)->required())\n            (\"primary_input\", po::value<std::string>(&primary_input_fn)->required())\n            (\"auxiliary_input\", po::value<std::string>(&auxiliary_input_fn)->required())\n            (\"proof\", po::value<std::string>(&proof_fn)->required());\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if (vm.count(\"help\"))\n        {\n            std::cout << desc << \"\\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#endif\n\nusing namespace tinyram_snark;\n\nint main(int argc, const char * argv[])\n{\n    default_tinyram_ppzksnark_pp::init_public_params();\n\n#ifdef MINDEPS\n    std::string processed_assembly_fn = \"processed_assembly.txt\";\n    std::string proving_key_fn = \"proving_key.txt\";\n    std::string primary_input_fn = \"primary_input.txt\";\n    std::string auxiliary_input_fn = \"auxiliary_input.txt\";\n    std::string proof_fn = \"proof.txt\";\n#else\n    std::string processed_assembly_fn;\n    std::string proving_key_fn;\n    std::string primary_input_fn;\n    std::string auxiliary_input_fn;\n    std::string proof_fn;\n\n    if (!process_prover_command_line(argc, argv, processed_assembly_fn,\n                                     proving_key_fn, primary_input_fn, auxiliary_input_fn, proof_fn))\n    {\n        return 1;\n    }\n#endif\n    libff::start_profiling();\n\n    /* load everything */\n    libff::enter_block(\"Deserialize proving key\");\n    ram_ppzksnark_proving_key<default_tinyram_ppzksnark_pp> pk;\n    std::ifstream pk_file(proving_key_fn);\n    pk_file >> pk;\n    pk_file.close();\n    libff::leave_block(\"Deserialize proving key\");\n\n    std::ifstream processed(processed_assembly_fn);\n    tinyram_program program = load_preprocessed_program(pk.ap, processed);\n\n    std::ifstream f_primary_input(primary_input_fn);\n    std::ifstream f_auxiliary_input(auxiliary_input_fn);\n    tinyram_input_tape primary_input = load_tape(f_primary_input);\n    tinyram_input_tape auxiliary_input = load_tape(f_auxiliary_input);\n\n    const ram_boot_trace<default_tinyram_ppzksnark_pp> boot_trace = tinyram_boot_trace_from_program_and_input(pk.ap, pk.primary_input_size_bound, program, primary_input);\n    const ram_ppzksnark_proof<default_tinyram_ppzksnark_pp> proof = ram_ppzksnark_prover<default_tinyram_ppzksnark_pp>(pk, boot_trace,  auxiliary_input);\n\n    libff::enter_block(\"Serialize proof\");\n    std::ofstream proof_file(proof_fn);\n    proof_file << proof;\n    proof_file.close();\n    libff::leave_block(\"Serialize proof\");\n}\n", "meta": {"hexsha": "9c6250531311e4189fe6674ebd19e5a2710962b7", "size": 4047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tinyram_snark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_prover.cpp", "max_stars_repo_name": "alittlehorse/osprey", "max_stars_repo_head_hexsha": "22f290a7de3413a847e3dc33c96328752cc37f47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-03-04T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T11:50:40.000Z", "max_issues_repo_path": "tinyram_snark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_prover.cpp", "max_issues_repo_name": "alittlehorse/osprey", "max_issues_repo_head_hexsha": "22f290a7de3413a847e3dc33c96328752cc37f47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tinyram_snark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_prover.cpp", "max_forks_repo_name": "alittlehorse/osprey", "max_forks_repo_head_hexsha": "22f290a7de3413a847e3dc33c96328752cc37f47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T15:50:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T15:50:15.000Z", "avg_line_length": 36.4594594595, "max_line_length": 170, "alphanum_fraction": 0.6419570052, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19925679704843258}}
{"text": "#ifndef DQN_HPP_\r\n#define DQN_HPP_\r\n\r\n#include <memory>\r\n#include <random>\r\n#include <tuple>\r\n#include <unordered_map>\r\n#include <vector>\r\n#include <ale_interface.hpp>\r\n#include <caffe/caffe.hpp>\r\n#include <boost/functional/hash.hpp>\r\n#include <boost/optional.hpp>\r\n\r\nnamespace dqn\r\n{\r\nconstexpr auto kRawFrameHeight       = 210;\r\nconstexpr auto kRawFrameWidth        = 160;\r\nconstexpr auto kCroppedFrameSize     = 84;\r\nconstexpr auto kCroppedFrameDataSize = kCroppedFrameSize * kCroppedFrameSize;\r\nconstexpr auto kOutputCount          = 18;\r\n\r\nconstexpr auto last_action_layer_name = \"last_action_input_layer\";\r\n\r\nconstexpr auto frames_layer_name = \"frames_input_layer\";\r\nconstexpr auto cont_layer_name   = \"cont_input_layer\";\r\nconstexpr auto target_layer_name = \"target_input_layer\";\r\nconstexpr auto filter_layer_name = \"filter_input_layer\";\r\n\r\nconstexpr auto train_last_action_blob_name  = \"actions\";\r\nconstexpr auto test_last_action_blob_name  = \"last_actions\";\r\n\r\nconstexpr auto train_frames_blob_name = \"frames\";\r\nconstexpr auto test_frames_blob_name  = \"all_frames\";\r\n\r\nconstexpr auto target_blob_name       = \"target\";\r\nconstexpr auto filter_blob_name       = \"filter\";\r\nconstexpr auto cont_blob_name         = \"cont\";\r\nconstexpr auto q_values_blob_name     = \"q_values\";\r\n\r\nconstexpr auto ip1Size = 512;\r\nconstexpr auto lstmSize = 512;\r\n\r\nusing LastAction       = std::vector<Action>;\r\nusing LastActionBatch  = std::vector<LastAction>;\r\n\r\nusing FrameData        = std::array<uint8_t, kCroppedFrameDataSize>;\r\nusing FrameDataSp      = std::shared_ptr<FrameData>;\r\nusing InputFrames      = std::vector<FrameDataSp>;\r\nusing InputFramesBatch = std::vector<InputFrames>;\r\nusing Transition       = std::tuple<Action, FrameDataSp, Action, float,\r\n      boost::optional<FrameDataSp> >;\r\nusing Episode          = std::vector<Transition>;\r\nusing ReplayMemory     = std::deque<Episode>;\r\nusing MemoryLayer      = caffe::MemoryDataLayer<float>;\r\nusing FrameVec         = std::vector<FrameDataSp>;\r\n\r\nusing ActionValue = std::pair<Action, float>;\r\nusing SolverSp = std::shared_ptr<caffe::Solver<float>>;\r\nusing NetSp = boost::shared_ptr<caffe::Net<float>>;\r\n\r\n/**\r\n * Deep Q-Network\r\n */\r\nclass DQN\r\n{\r\npublic:\r\n    DQN(const ActionVect& legal_actions,\r\n        const int replay_memory_capacity,\r\n        const double gamma,\r\n        const int clone_frequency,\r\n        const int unroll,\r\n        const int minibatch_size,\r\n        const int frames_per_timestep);\r\n\r\n    // Initialize DQN. Must be called before calling any other method.\r\n    void Initialize(caffe::SolverParameter& solver_param);\r\n\r\n    // Create the caffe net .prototxt\r\n    caffe::NetParameter CreateNet(bool unroll1_is_lstm);\r\n\r\n    // Load a trained model from a file.\r\n    void LoadTrainedModel(const std::string& model_file);\r\n\r\n    // Restore solving from a solver file.\r\n    void RestoreSolver(const std::string& solver_file);\r\n\r\n    // Snapshot the model/solver/replay memory. Produces files:\r\n    // snapshot_prefix_iter_N.[caffemodel|solverstate|replaymem]. Optionally\r\n    // removes snapshots that share the same prefix but have a lower\r\n    // iteration number.\r\n    void Snapshot(const std::string& snapshot_prefix, bool remove_old=false,\r\n                  bool snapshot_memory=true);\r\n\r\n    // A specialized method for producing a high-score\r\n    // snapshot. Optionally remove older HiScore snapshots\r\n    void SnapshotHiScore(const std::string& snapshot_prefix,\r\n                         double avg_score, double std_dev,\r\n                         bool remove_old=true);\r\n\r\n    // Select an action by epsilon-greedy. If cont is false, LSTM state\r\n    // will be reset. cont should be true only at start of new episodes.\r\n    Action SelectAction(const InputFrames& frames, const LastAction& last_action, double epsilon, bool cont);\r\n\r\n    // Select a batch of actions by epsilon-greedy.\r\n    ActionVect SelectActions(const InputFramesBatch& frames_batch,\r\n\t\t\t\t\t\t\t const LastActionBatch& last_action_batch,\r\n                             double epsilon, bool cont);\r\n\r\n    // Add an episode to the replay memory\r\n    void RememberEpisode(const Episode& episode);\r\n\r\n    // Update DQN. Returns the number of solver steps executed.\r\n///    int UpdateSequential();\r\n    // Updates from a random minibatch of experiences\r\n    int UpdateRandom();\r\n\r\n    // Clear the replay memory\r\n    void ClearReplayMemory();\r\n\r\n    // Save the replay memory to a gzipped compressed file\r\n    void SnapshotReplayMemory(const std::string& filename);\r\n\r\n    // Load the replay memory from a gzipped compressed file\r\n    void LoadReplayMemory(const std::string& filename);\r\n\r\n    // Get the number of episodes stored in the replay memory\r\n    int memory_episodes() const\r\n    {\r\n        return replay_memory_.size();\r\n    }\r\n\r\n    // Get the number of transitions store in the replay memory\r\n    int memory_size() const\r\n    {\r\n        return replay_memory_size_;\r\n    }\r\n\r\n    // Return the current iteration of the solver\r\n    int current_iteration() const\r\n    {\r\n        return solver_->iter();\r\n    }\r\n\r\n    void CloneTestNet()\r\n    {\r\n        CloneNet(*test_net_);\r\n    }\r\n\r\n    // Benchmark the speed of the learning by doing some number of\r\n    // iterations of updates and selects. random_updates toggles\r\n    // random/sequential updating.\r\n    //void Benchmark(int iterations, bool random_updates);\r\n\r\n    // Obscures the screen by zeroing everything with a given probability.\r\n    void ObscureScreen(FrameDataSp& screen, double obscure_prob);\r\n    // Re-Display the last seen screen with probability prob\r\n    void RedisplayScreen(FrameDataSp& screen, double prob);\r\n\r\n    // Returns the number of transitions in the last episode added to\r\n    // the memory or 0 if the memory is empty.\r\n    int GetLastEpisodeSize();\r\n\r\nprotected:\r\n    // Clone the given net and store the result in clone_net_\r\n    void CloneNet(caffe::Net<float>& net);\r\n\r\n    // Given a set of input frames and a network, select an\r\n    // action. Returns the action and the estimated Q-Value.\r\n\tActionValue SelectActionGreedily(caffe::Net<float>& net,\r\n                                     const InputFrames& last_frames,\r\n                                     const Action& last_action,\r\n                                     bool cont);\r\n\r\n    // Given a vector of frames, return a batch of selected actions + values.\r\n\tstd::vector<ActionValue> SelectActionGreedily(caffe::Net<float>& net,\r\n\t\t\t\t\t\t\t\t\t\t\t\t   const InputFramesBatch& frames_batch,\r\n                                                   const LastActionBatch& last_action_batch,\r\n                                                   bool cont);\r\n\r\n    // Input data into the Frames/Target/Filter layers of the given\r\n    // net. This must be done before forward is called.\r\n    void InputDataIntoLayers(caffe::Net<float>& net,\r\n                             float* frames_input,\r\n\t\t\t\t\t\t\t float* last_action_input,\r\n                             float* cont_input,\r\n                             float* target_input,\r\n                             float* filter_input);\r\n\r\nprotected:\r\n    int unroll_; // Number of steps to unroll recurrent layers\r\n    int minibatch_size_; // Size of each minibatch\r\n    int frames_per_timestep_; // History of frames given at each timestep\r\n    int frames_per_forward_; // Number of frames needed by each forward\r\n\r\n    // Size of the input blobs to the memory layers\r\n    int frame_input_size_TRAIN_, target_input_size_TRAIN_,\r\n        filter_input_size_TRAIN_, cont_input_size_TRAIN_,\r\n\t\tlast_action_input_size_TRAIN_;\r\n    int frame_input_size_TEST_, cont_input_size_TEST_,\r\n\t\tlast_action_input_size_TEST_;\r\n\r\n    const ActionVect legal_actions_;\r\n    const int replay_memory_capacity_;\r\n    const double gamma_;\r\n    const int clone_frequency_; // How often (steps) the clone_net is updated\r\n    int replay_memory_size_; // Number of transitions in replay memory\r\n    ReplayMemory replay_memory_;\r\n    SolverSp solver_;\r\n    NetSp net_; // The primary network used for action selection.\r\n    NetSp test_net_; // Net used for testing\r\n    NetSp clone_net_; // Clone used to generate targets.\r\n    int last_clone_iter_; // Iteration in which the net was last cloned\r\n    std::mt19937 random_engine;\r\n    float smoothed_loss_;\r\n    std::vector<uint8_t> last_displayed_screen_; // Used in RedisplayScreen\r\n};\r\n\r\n/**\r\n * Returns a vector of filenames matching a given regular expression.\r\n */\r\nstd::vector<std::string> FilesMatchingRegexp(const std::string& regexp);\r\n\r\n/**\r\n * Removes snapshots starting with snapshot_prefix that have an\r\n * iteration less than min_iter. Does not remove high-score snapshots.\r\n */\r\nvoid RemoveSnapshots(const std::string& snapshot_prefix, int min_iter);\r\n\r\n/**\r\n * Look for the latest snapshot to resume from. Returns a string\r\n * containing the path to the .solverstate. Returns empty string if\r\n * none is found. Will only return if the snapshot contains all of:\r\n * .solverstate,.caffemodel,.replaymemory\r\n */\r\nstd::string FindLatestSnapshot(const std::string& snapshot_prefix);\r\n/**\r\n * Returns a list of high score snapshots\r\n */\r\nstd::vector<std::string> GetHiScoreSnapshots(const std::string& snapshot_prefix);\r\n\r\n/**\r\n * Look for the best HiScore matching the given snapshot prefix\r\n */\r\nfloat FindHiScore(const std::string& snapshot_prefix);\r\n\r\n/**\r\n * Remove all high-score snapshots matching the given snapshot prefix\r\n */\r\nvoid RemoveHiScoreSnapshots(const std::string& snapshot_prefix);\r\n\r\n/**\r\n * Preprocess an ALE screen (downsampling & grayscaling). Optionally\r\n * obscure the screen to make ALE into a POMDP.\r\n */\r\nFrameDataSp PreprocessScreen(const ALEScreen& raw_screen);\r\n\r\n}\r\n\r\n#endif /* DQN_HPP_ */\r\n", "meta": {"hexsha": "8a14cdfe101ffb293e899216b2b8c254b79d7555", "size": 9684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dqn.hpp", "max_stars_repo_name": "bit1029public/ADRQN", "max_stars_repo_head_hexsha": "c2390359599dadd5a5077e9ec4df11ed1a2a891c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-06T02:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T02:50:13.000Z", "max_issues_repo_path": "dqn.hpp", "max_issues_repo_name": "bit1029public/ADRQN", "max_issues_repo_head_hexsha": "c2390359599dadd5a5077e9ec4df11ed1a2a891c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dqn.hpp", "max_forks_repo_name": "bit1029public/ADRQN", "max_forks_repo_head_hexsha": "c2390359599dadd5a5077e9ec4df11ed1a2a891c", "max_forks_repo_licenses": ["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.2461538462, "max_line_length": 110, "alphanum_fraction": 0.6829822387, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, 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_STRATEGIES_AZIMUTH_GEOGRAPHIC_HPP\n#define BOOST_GEOMETRY_STRATEGIES_AZIMUTH_GEOGRAPHIC_HPP\n\n\n// TODO: move this file to boost/geometry/strategy\n#include <boost/geometry/strategies/geographic/azimuth.hpp>\n\n#include <boost/geometry/strategies/azimuth/services.hpp>\n#include <boost/geometry/strategies/detail.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace azimuth\n{\n\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic : strategies::detail::geographic_base<Spheroid>\n{\n    using base_t = strategies::detail::geographic_base<Spheroid>;\n\npublic:\n    geographic()\n        : base_t()\n    {}\n\n    explicit geographic(Spheroid const& spheroid)\n        : base_t(spheroid)\n    {}\n\n    auto azimuth() const\n    {\n        return strategy::azimuth::geographic\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n};\n\n\nnamespace services\n{\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<Point1, Point2, geographic_tag, geographic_tag>\n{\n    using type = strategies::azimuth::geographic<>;\n};\n\n\ntemplate <typename FP, typename S, typename CT>\nstruct strategy_converter<strategy::azimuth::geographic<FP, S, CT> >\n{\n    static auto get(strategy::azimuth::geographic<FP, S, CT> const& strategy)\n    {\n        return strategies::azimuth::geographic<FP, S, CT>(strategy.model());\n    }\n};\n\n} // namespace services\n\n}} // namespace strategies::azimuth\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_AZIMUTH_GEOGRAPHIC_HPP\n", "meta": {"hexsha": "a4fac5e60c7f5d8e15f12b7e08d6bc92598b9bb4", "size": 1916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/geographic.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/geographic.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/geographic.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": 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": 23.3658536585, "max_line_length": 77, "alphanum_fraction": 0.7212943633, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}}
{"text": "/*\n\nCopyright (c) 2005-2017, 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#ifndef DYNAMICALLY_LOADABLE_LR91_HPP_\n#define DYNAMICALLY_LOADABLE_LR91_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractCardiacCell.hpp\"\n#include \"AbstractStimulusFunction.hpp\"\n#include \"AbstractDynamicallyLoadableEntity.hpp\"\n#include <vector>\n\n/**\n * This class represents the Luo-Rudy 1991 system of equations,\n * with support for being compiled into a .so and loaded at run-time.\n */\nclass DynamicallyLoadableLr91 : public AbstractCardiacCell, public AbstractDynamicallyLoadableEntity\n{\nprivate:\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the member variables.\n     *\n     * @param archive\n     * @param version\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & boost::serialization::base_object<AbstractCardiacCell>(*this);\n        archive & boost::serialization::base_object<AbstractDynamicallyLoadableEntity>(*this);\n    }\n\n    /* Constants for the model */\n\n    /** membrane capcaitance*/\n    static const double membrane_C;\n    /** Faraday constant*/\n    static const double membrane_F;\n    /** Universal gas constant*/\n    static const double membrane_R;\n    /** Temeperature*/\n    static const double membrane_T;\n    /** Reversal potentila for background current*/\n    static const double background_current_E_b;\n    /** Maximal conductance for background current*/\n    static const double background_current_g_b;\n    /** Maximal conductance for sodium current*/\n    static const double fast_sodium_current_g_Na;\n    /** Intracellular potassium concentration*/\n    static const double ionic_concentrations_Ki;\n    /** Extracellular potassium concentration*/\n    static const double ionic_concentrations_Ko;\n    /** Intracellular sodium concentration*/\n    static const double ionic_concentrations_Nai;\n    /** Extracellular sodium concentration*/\n    static const double ionic_concentrations_Nao;\n    /** Maximal conductance for plateau current*/\n    static const double plateau_potassium_current_g_Kp;\n    /** Permeability ratio Na/K for potassium currents*/\n    static const double time_dependent_potassium_current_PR_NaK;\n\n    /** Another parameter, which is a function of the above */\n    double fast_sodium_current_E_Na;\n\n    /**\n     *  Range-checking on the current values of the state variables. Make sure\n     *  all gating variables have are within zero and one, and all concentrations\n     *  are positive\n     */\n    void VerifyStateVariables();\n\npublic:\n    /**\n     * Constructor\n     *\n     * @param pSolver is a pointer to the ODE solver\n     * @param pIntracellularStimulus is a pointer to the intracellular stimulus\n     */\n    DynamicallyLoadableLr91(boost::shared_ptr<AbstractIvpOdeSolver> pSolver,\n                            boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus);\n\n    /**\n     * Destructor\n     */\n    ~DynamicallyLoadableLr91();\n\n    /**\n     * Fill in a vector representing the RHS of the Luo-Rudy 1991 system\n     * of Odes at each time step, y' = [y1' ... yn'].\n     * Some ODE solver will call this function repeatedly to solve for y = [y1 ... yn].\n     *\n     * @param time  the current time, in milliseconds\n     * @param rY  current values of the state variables\n     * @param rDY  to be filled in with derivatives\n     */\n    void EvaluateYDerivatives(double time, const std::vector<double> &rY, std::vector<double> &rDY);\n\n    /**\n     * Returns the ionic current\n     *\n     * @param pStateVariables  optional state at which to evaluate the current\n     * @return the total ionic current\n     */\n    double GetIIonic(const std::vector<double>* pStateVariables=NULL);\n\n    /**\n     * Get the intracellular calcium concentration\n     *\n     * @return the intracellular calcium concentration\n     */\n    double GetIntracellularCalciumConcentration();\n};\n\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(DynamicallyLoadableLr91)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Allow us to not need a default constructor, by specifying how Boost should\n * instantiate a DynamicallyLoadableLr91 instance.\n */\ntemplate<class Archive>\ninline void save_construct_data(\n    Archive & ar, const DynamicallyLoadableLr91 * t, const unsigned int file_version)\n{\n    const boost::shared_ptr<AbstractIvpOdeSolver> p_solver = t->GetSolver();\n    const boost::shared_ptr<AbstractStimulusFunction> p_stimulus = t->GetStimulusFunction();\n    ar << p_solver;\n    ar << p_stimulus;\n}\n\n/**\n * Allow us to not need a default constructor, by specifying how Boost should\n * instantiate a DynamicallyLoadableLr91 instance (using existing constructor).\n *\n * NB this constructor allocates memory for the other member variables too.\n */\ntemplate<class Archive>\ninline void load_construct_data(\n    Archive & ar, DynamicallyLoadableLr91 * t, const unsigned int file_version)\n{\n\n    boost::shared_ptr<AbstractIvpOdeSolver> p_solver;\n    boost::shared_ptr<AbstractStimulusFunction> p_stimulus;\n    ar >> p_solver;\n    ar >> p_stimulus;\n    ::new(t)DynamicallyLoadableLr91(p_solver, p_stimulus);\n}\n}\n} // namespace ...\n\n#endif // DYNAMICALLY_LOADABLE_LR91_HPP_\n", "meta": {"hexsha": "db29541aa4ab790498a2f7dea676522c73a5284e", "size": 6939, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/dynamic/DynamicallyLoadableLr91.hpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": "heart/dynamic/DynamicallyLoadableLr91.hpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": "heart/dynamic/DynamicallyLoadableLr91.hpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": 36.3298429319, "max_line_length": 100, "alphanum_fraction": 0.7410289667, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}}
{"text": "#include \"pch_bullet.h\"\n#include <iostream>\n#include <numeric>\n#include \"Foregrounds.h\"\n#include \"CausalityApplication.h\"\n#include \"Common\\PrimitiveVisualizer.h\"\n#include \"Common\\Extern\\cpplinq.hpp\"\n#include <boost\\format.hpp>\n\nusing namespace Causality;\nusing namespace DirectX;\nusing namespace DirectX::Scene;\nusing namespace std;\nusing namespace Platform;\nusing namespace Eigen;\nusing namespace concurrency;\nusing namespace DirectX::Visualizers;\nextern wstring ResourcesDirectory;\n\n//std::unique_ptr<DirectX::GeometricPrimitive> HandPhysicalModel::s_pCylinder;\n//std::unique_ptr<DirectX::GeometricPrimitive> HandPhysicalModel::s_pSphere;\n\nconst static wstring SkyBoxTextures[6] = {\n\tResourcesDirectory + wstring(L\"Textures\\\\SkyBox\\\\GrimmNight\\\\Right.dds\"),\n\tResourcesDirectory + wstring(L\"Textures\\\\SkyBox\\\\GrimmNight\\\\Left.dds\"),\n\tResourcesDirectory + wstring(L\"Textures\\\\SkyBox\\\\GrimmNight\\\\Top.dds\"),\n\tResourcesDirectory + wstring(L\"Textures\\\\SkyBox\\\\GrimmNight\\\\Bottom.dds\"),\n\tResourcesDirectory + wstring(L\"Textures\\\\SkyBox\\\\GrimmNight\\\\Front.dds\"),\n\tResourcesDirectory + wstring(L\"Textures\\\\SkyBox\\\\GrimmNight\\\\Back.dds\"),\n};\n\n//std::unique_ptr<btBroadphaseInterface>               pBroadphase = nullptr;\n//// Set up the collision configuration and dispatcher\n//std::unique_ptr<btDefaultCollisionConfiguration>     pCollisionConfiguration = nullptr;\n//std::unique_ptr<btCollisionDispatcher>               pDispatcher = nullptr;\n//// The actual physics solver\n//std::unique_ptr<btSequentialImpulseConstraintSolver> pSolver = nullptr;\n\nstd::queue<std::unique_ptr<WorldBranch>> WorldBranch::BranchPool;\n\n\nfloat ShapeSimiliarity(const Eigen::VectorXf& v1, const Eigen::VectorXf& v2)\n{\n\tauto v = v1 - v2;\n\t//dis = sqrt(v.dot(v);\n\t//1.414 - dis;\n\tauto theta = XMScalarACosEst(v1.dot(v2) * XMScalarReciprocalSqrtEst(v1.dot(v1) * v2.dot(v2))); // Difference in angular [0,pi/4]\n\tauto rhlo = abs(sqrt(v1.dot(v1)) - sqrtf(v2.dot(v2)));\t// Difference in length [0,sqrt(2)]\n\treturn 1.0f - 0.5f * (0.3f * rhlo / sqrtf(2.0f) + 0.7f * theta / (XM_PIDIV4));\n}\n\nCausality::WorldScene::WorldScene(const std::shared_ptr<DirectX::DeviceResources>& pResouce, const DirectX::ILocatable* pCamera)\n\t: States(pResouce->GetD3DDevice())\n\t, m_pCameraLocation(pCamera)\n{\n\tm_HaveHands = false;\n\tm_showTrace = true;\n\tLoadAsync(pResouce->GetD3DDevice());\n}\n\nWorldScene::~WorldScene()\n{\n}\n\nconst float fingerRadius = 0.006f;\nconst float fingerLength = 0.02f;\n\nclass XmlModelLoader\n{\n};\n\nWorldBranch::WorldBranch()\n{\n\tpBroadphase.reset(new btDbvtBroadphase());\n\n\t// Set up the collision configuration and dispatcher\n\tpCollisionConfiguration.reset(new btDefaultCollisionConfiguration());\n\tpDispatcher.reset(new btCollisionDispatcher(pCollisionConfiguration.get()));\n\n\t// The actual physics solver\n\tpSolver.reset(new btSequentialImpulseConstraintSolver());\n\t// The world.\n\tpDynamicsWorld.reset(new btDiscreteDynamicsWorld(pDispatcher.get(), pBroadphase.get(), pSolver.get(), pCollisionConfiguration.get()));\n\tpDynamicsWorld->setGravity(btVector3(0, -1.0f, 0));\n\n\tIsEnabled = false;\n}\n\nvoid Causality::WorldScene::LoadAsync(ID3D11Device* pDevice)\n{\n\n\tm_loadingComplete = false;\n\tpBackground = nullptr;\n\n\t//CD3D11_DEFAULT d;\n\t//CD3D11_RASTERIZER_DESC Desc(d);\n\t//Desc.MultisampleEnable = TRUE;\n\t//ThrowIfFailed(pDevice->CreateRasterizerState(&Desc, &pRSState));\n\n\tconcurrency::task<void> load_models([this, pDevice]() {\n\t\t{\n\t\t\tlock_guard<mutex> guard(m_RenderLock);\n\t\t\tWorldBranch::InitializeBranchPool(1);\n\t\t\tWorldTree = WorldBranch::DemandCreate(\"Root\");\n\n\t\t\t//std::vector<AffineTransform> subjectTrans(30);\n\t\t\t//subjectTrans.resize(20);\n\t\t\t//for (size_t i = 0; i < 20; i++)\n\t\t\t//{\n\t\t\t//\tsubjectTrans[i].Scale = XMVectorReplicate(1.1f + 0.15f * i);// XMMatrixTranslation(0, 0, i*(-150.f));\n\t\t\t//}\n\t\t\t//WorldTree->Fork(subjectTrans);\n\n\t\t\tWorldTree->Enable(DirectX::AffineTransform::Identity());\n\t\t}\n\n\t\t//m_pFramesPool.reset(new WorldBranchPool);\n\t\t//m_pFramesPool->Initialize(30);\n\t\t//{\n\t\t//\tlock_guard<mutex> guard(m_RenderLock);\n\t\t//\tfor (size_t i = 0; i < 30; i++)\n\t\t//\t{\n\t\t//\t\tm_StateFrames.push_back(m_pFramesPool->DemandCreate());\n\t\t//\t\tauto pFrame = m_StateFrames.back();\n\t\t//\t\t//pFrame->Initialize();\n\t\t//\t\tpFrame->SubjectTransform.Scale = XMVectorReplicate(1.0f + 0.1f * i);// XMMatrixTranslation(0, 0, i*(-150.f));\n\t\t//\t}\n\t\t//\tm_StateFrames.front()->Enable(DirectX::AffineTransform::Identity());\n\t\t//}\n\n\t\tauto Directory = App::Current()->GetResourcesDirectory();\n\t\tauto ModelDirectory = Directory / \"Models\";\n\t\tauto TextureDirectory = Directory / \"Textures\";\n\t\tauto texDir = TextureDirectory.wstring();\n\t\tpEffect = std::make_shared<BasicEffect>(pDevice);\n\t\tpEffect->SetVertexColorEnabled(false);\n\t\tpEffect->SetTextureEnabled(true);\n\t\t//pEffect->SetLightingEnabled(true);\n\t\tpEffect->EnableDefaultLighting();\n\t\t{\n\t\t\tvoid const* shaderByteCode;\n\t\t\tsize_t byteCodeLength;\n\t\t\tpEffect->GetVertexShaderBytecode(&shaderByteCode, &byteCodeLength);\n\t\t\tpInputLayout = CreateInputLayout<VertexPositionNormalTexture>(pDevice, shaderByteCode, byteCodeLength);\n\t\t}\n\n\t\t//pBackground = std::make_unique<SkyDome>(pDevice, SkyBoxTextures);\n\n\t\tauto sceneFile = Directory / \"Foregrounds.xml\";\n\t\ttinyxml2::XMLDocument sceneDoc;\n\t\tsceneDoc.LoadFile(sceneFile.string().c_str());\n\t\tauto scene = sceneDoc.FirstChildElement(\"scene\");\n\t\tauto node = scene->FirstChildElement();\n\t\twhile (node)\n\t\t{\n\t\t\tif (!strcmp(node->Name(), \"obj\"))\n\t\t\t{\n\t\t\t\tauto path = node->Attribute(\"src\");\n\t\t\t\tif (path != nullptr && strlen(path) != 0)\n\t\t\t\t{\n\t\t\t\t\tauto pModel = std::make_shared<ShapedGeomrtricModel>();\n\t\t\t\t\tGeometryModel::CreateFromObjFile(pModel.get(), pDevice, (ModelDirectory / path).wstring(), texDir);\n\n\t\t\t\t\tXMFLOAT3 v = pModel->BoundOrientedBox.Extents;\n\t\t\t\t\tv.y /= v.x;\n\t\t\t\t\tv.z /= v.x;\n\t\t\t\t\tm_ModelFeatures[pModel->Name] = Eigen::Vector2f(v.y, v.z);\n\t\t\t\t\tstd::cout << \"[Model] f(\" << pModel->Name << \") = \" << m_ModelFeatures[pModel->Name] << std::endl;\n\n\t\t\t\t\tfloat scale = 1.0f;\n\t\t\t\t\tfloat mass = 1.0f;\n\t\t\t\t\tVector3 pos;\n\n\t\t\t\t\tauto attr = node->Attribute(\"scale\");\n\t\t\t\t\tif (attr != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tstringstream ss(attr);\n\n\t\t\t\t\t\tss >> scale;\n\t\t\t\t\t\t//model->SetScale(XMVectorReplicate(scale));\n\t\t\t\t\t}\n\t\t\t\t\tattr = node->Attribute(\"position\");\n\t\t\t\t\tif (attr != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tstringstream ss(attr);\n\n\t\t\t\t\t\tchar ch;\n\t\t\t\t\t\tss >> pos.x >> ch >> pos.y >> ch >> pos.z;\n\t\t\t\t\t\t//model->SetPosition(pos);\n\t\t\t\t\t}\n\n\t\t\t\t\tattr = node->Attribute(\"mass\");\n\t\t\t\t\tif (attr)\n\t\t\t\t\t\tmass = (float) atof(attr);\n\n\t\t\t\t\tAddObject(pModel, mass, pos, DirectX::Quaternion::Identity, DirectX::Vector3(scale));\n\n\t\t\t\t\t//auto pShape = model->CreateCollisionShape();\n\t\t\t\t\t//pShape->setLocalScaling(btVector3(scale, scale, scale));\n\t\t\t\t\t//btVector3 minb, maxb;\n\t\t\t\t\t//model->InitializePhysics(pDynamicsWorld, pShape, mass, pos, XMQuaternionIdentity());\n\t\t\t\t\t//model->GetBulletRigid()->setFriction(1.0f);\n\t\t\t\t\t//{\n\t\t\t\t\t//\tstd::lock_guard<mutex> guard(m_RenderLock);\n\t\t\t\t\t//\tModels.push_back(model);\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (!strcmp(node->Name(), \"cube\"))\n\t\t\t{\n\t\t\t\tVector3 extent(1.0f);\n\t\t\t\tVector3 pos;\n\t\t\t\tColor color(255, 255, 255, 255);\n\t\t\t\tstring name(\"cube\");\n\t\t\t\tfloat mass = 1.0f;\n\t\t\t\tauto attr = node->Attribute(\"extent\");\n\t\t\t\tif (attr != nullptr)\n\t\t\t\t{\n\t\t\t\t\tstringstream ss(attr);\n\t\t\t\t\tchar ch;\n\t\t\t\t\tss >> extent.x >> ch >> extent.y >> ch >> extent.z;\n\t\t\t\t}\n\t\t\t\tattr = node->Attribute(\"position\");\n\t\t\t\tif (attr != nullptr)\n\t\t\t\t{\n\t\t\t\t\tstringstream ss(attr);\n\n\t\t\t\t\tchar ch;\n\t\t\t\t\tss >> pos.x >> ch >> pos.y >> ch >> pos.z;\n\t\t\t\t}\n\t\t\t\tattr = node->Attribute(\"color\");\n\t\t\t\tif (attr != nullptr)\n\t\t\t\t{\n\t\t\t\t\tstringstream ss(attr);\n\n\t\t\t\t\tchar ch;\n\t\t\t\t\tss >> color.x >> ch >> color.y >> ch >> color.z;\n\t\t\t\t\tif (!ss.eof())\n\t\t\t\t\t\tss >> ch >> color.w;\n\t\t\t\t\tcolor = color.ToVector4() / 255;\n\t\t\t\t\tcolor.Saturate();\n\t\t\t\t}\n\t\t\t\tattr = node->Attribute(\"name\");\n\t\t\t\tif (attr)\n\t\t\t\t\tname = attr;\n\n\t\t\t\tattr = node->Attribute(\"mass\");\n\t\t\t\tif (attr)\n\t\t\t\t\tmass = (float) atof(attr);\n\n\t\t\t\tauto pModel = make_shared<CubeModel>(name, extent, (XMVECTOR) color);\n\n\t\t\t\tXMFLOAT3 v = pModel->BoundOrientedBox.Extents;\n\t\t\t\tv.y /= v.x;\n\t\t\t\tv.z /= v.x;\n\t\t\t\tm_ModelFeatures[pModel->Name] = Eigen::Vector2f(v.y, v.z);\n\n\t\t\t\tAddObject(pModel, mass, pos, DirectX::Quaternion::Identity, DirectX::Vector3::One);\n\t\t\t\t//auto pShape = pModel->CreateCollisionShape();\n\t\t\t\t//pModel->InitializePhysics(nullptr, pShape, mass, pos);\n\t\t\t\t//pModel->Enable(pDynamicsWorld);\n\t\t\t\t//pModel->GetBulletRigid()->setFriction(1.0f);\n\t\t\t\t//{\n\t\t\t\t//\tstd::lock_guard<mutex> guard(m_RenderLock);\n\t\t\t\t//\tModels.push_back(pModel);\n\t\t\t\t//}\n\t\t\t}\n\t\t\tnode = node->NextSiblingElement();\n\t\t}\n\n\t\tm_loadingComplete = true;\n\t});\n}\n\nvoid Causality::WorldScene::SetViewIdenpendntCameraPosition(const DirectX::ILocatable * pCamera)\n{\n\tm_pCameraLocation = pCamera;\n}\n\nvoid Causality::WorldScene::Render(ID3D11DeviceContext * pContext)\n{\n\tif (pBackground)\n\t\tpBackground->Render(pContext);\n\n\t{\n\t\tpContext->IASetInputLayout(pInputLayout.Get());\n\t\tauto pAWrap = States.AnisotropicWrap();\n\t\tpContext->PSSetSamplers(0, 1, &pAWrap);\n\t\tpContext->RSSetState(pRSState.Get());\n\t\tstd::lock_guard<mutex> guard(m_RenderLock);\n\t\t\n\t\tBoundingOrientedBox modelBox;\n\t\tusing namespace cpplinq;\n\n\t\t// Render models\n\t\tfor (const auto& model : Models)\n\t\t{\n\t\t\tauto superposition = ModelStates[model->Name];\n\t\t\tfor (const auto& state : superposition)\n\t\t\t{\n\t\t\t\tauto mat = state.TransformMatrix();\n\t\t\t\tmodel->LocalMatrix = state.TransformMatrix(); //.first->GetRigidTransformMatrix();\n\t\t\t\tmodel->Opticity = state.Probability; //state.second;\n\n\t\t\t\tmodel->BoundOrientedBox.Transform(modelBox, mat);\n\t\t\t\t// Render if in the view frustum\n\n\t\t\t\tif (ViewFrutum.Contains(modelBox) != ContainmentType::DISJOINT)\n\t\t\t\t\tmodel->Render(pContext, pEffect.get());\n\t\t\t}\n\t\t}\n\n\t\tfor (const auto& branch : WorldTree->leaves())\n\t\t{\n\t\t\t\t//Subjects\n\t\t\t\tfor (const auto& item : branch.Subjects)\n\t\t\t\t{\n\t\t\t\t\tif (item.second)\n\t\t\t\t\t{\n\t\t\t\t\t\titem.second->Opticity = branch.Liklyhood();\n\t\t\t\t\t\titem.second->Render(pContext, nullptr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t}\n\n\n\n\tg_PrimitiveDrawer.Begin();\n\n\tVector3 conners[8];\n\n\tViewFrutum.GetCorners(conners);\n\tDrawBox(conners, Colors::Pink);\n\tBoundingOrientedBox obox;\n\tBoundingBox box;\n\t{\n\t\t//Draw axias\n\t\tDrawAxis();\n\t\t//g_PrimitiveDrawer.DrawQuad({ 1.0f,0,1.0f }, { -1.0f,0,1.0f }, { -1.0f,0,-1.0f }, { 1.0f,0,-1.0f }, Colors::Pink);\n\n\n\t\tauto& fh = m_HandDescriptionFeature;\n\n\t\t{\n\t\t\tstd::lock_guard<mutex> guard(m_RenderLock);\n\t\t\tauto s = Models.size();\n\t\t\tif (m_HaveHands)\n\t\t\t\tstd::cout << \"Detail Similarity = {\";\n\t\t\tfor (size_t i = 0; i < s; i++)\n\t\t\t{\n\t\t\t\tconst auto& model = Models[i];\n\t\t\t\tobox = model->GetOrientedBoundingBox();\n\t\t\t\tif (ViewFrutum.Contains(obox) != ContainmentType::DISJOINT)\n\t\t\t\t{\n\t\t\t\t\tobox.GetCorners(conners);\n\t\t\t\t\tDrawBox(conners, DirectX::Colors::DarkGreen);\n\t\t\t\t}\n\t\t\t\tif (m_HaveHands)\n\t\t\t\t{\n\t\t\t\t\tauto fm = m_ModelFeatures[model->Name];\n\n\t\t\t\t\tauto similarity = ShapeSimiliarity(fm, fh);\n\t\t\t\t\tm_ModelDetailSimilarity[model->Name] = similarity;\n\t\t\t\t\tstd::cout << model->Name << ':' << similarity << \" , \";\n\t\t\t\t\tColor c = Color::Lerp({ 1,0,0 }, { 0,1,0 }, similarity);\n\t\t\t\t\tfor (size_t i = 0; i < 8; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tg_PrimitiveDrawer.DrawSphere(conners[i], 0.005f * similarity, c);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tauto pModel = dynamic_cast<CompositeModel*>(model.get());\n\t\t\t\tXMMATRIX transform = model->GetWorldMatrix();\n\t\t\t\tif (pModel)\n\t\t\t\t{\n\t\t\t\t\tfor (const auto& part : pModel->Parts)\n\t\t\t\t\t{\n\t\t\t\t\t\tpart->BoundOrientedBox.Transform(obox, transform);\n\t\t\t\t\t\tif (ViewFrutum.Intersects(obox))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tobox.GetCorners(conners);\n\t\t\t\t\t\t\tDrawBox(conners, DirectX::Colors::Orange);\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\tif (m_HaveHands)\n\t\t\tstd::cout << '}' << std::endl;\n\t}\n\n\tif (m_HaveHands)\n\t{\n\n\t\t//for (auto& pRigid : m_HandRigids)\n\t\t//{\n\t\t//\tg_PrimitiveDrawer.DrawSphere(pRigid->GetPosition(), 0.01f, Colors::Pink);\n\t\t//}\n\n\t\tauto pCamera = App::Current()->GetPrimaryCamera();\n\n\t\tXMMATRIX leap2world = m_FrameTransform;// XMMatrixScalingFromVector(XMVectorReplicate(0.001f)) * XMMatrixTranslation(0,0,-1.0) * XMMatrixRotationQuaternion(pCamera->GetOrientation()) * XMMatrixTranslationFromVector((XMVECTOR)pCamera->GetPosition());\n\t\tstd::lock_guard<mutex> guard(m_HandFrameMutex);\n\t\tfor (const auto& hand : m_Frame.hands())\n\t\t{\n\t\t\tauto palmPosition = XMVector3Transform(hand.palmPosition().toVector3<Vector3>(), leap2world);\n\t\t\tg_PrimitiveDrawer.DrawSphere(palmPosition, 0.02f, Colors::YellowGreen);\n\t\t\t//for (const auto& finger : hand.fingers())\n\t\t\t//{\n\t\t\t//\tfor (size_t i = 0; i < 4; i++)\n\t\t\t//\t{\n\t\t\t//\t\tconst auto & bone = finger.bone((Leap::Bone::Type)i);\n\t\t\t//\t\tXMVECTOR bJ = XMVector3Transform(bone.prevJoint().toVector3<Vector3>(), leap2world);\n\t\t\t//\t\tXMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world);\n\t\t\t//\t\t//if (i == 0)\n\t\t\t//\t\t//\tg_PrimitiveDrawer.DrawSphere(bJ, 0.01f, DirectX::Colors::Lime);\n\n\t\t\t//\t\t//// The unit of leap is millimeter\n\t\t\t//\t\t//g_PrimitiveDrawer.DrawSphere(eJ, 0.01f, DirectX::Colors::Lime);\n\t\t\t//\t\tg_PrimitiveDrawer.DrawLine(bJ, eJ, DirectX::Colors::White);\n\t\t\t//\t}\n\t\t\t//}\n\t\t}\n\n\t\t// NOT VALIAD!~!!!!!\n\t\t//if (m_HandTrace.size() > 0 && m_showTrace)\n\t\t//{\n\t\t//\tstd::lock_guard<mutex> guard(m_RenderLock);\n\t\t//\t//auto pJoints = m_HandTrace.linearize();\n\t\t//\tm_CurrentHandBoundingBox.GetCorners(conners);\n\t\t//\tDrawBox(conners, Colors::LimeGreen);\n\t\t//\tm_HandTraceBoundingBox.GetCorners(conners);\n\t\t//\tDrawBox(conners, Colors::YellowGreen);\n\t\t//\tm_HandTraceModel.Primitives.clear();\n\t\t//\tfor (int i = m_HandTrace.size() - 1; i >= std::max<int>(0, (int) m_HandTrace.size() - TraceLength); i--)\n\t\t//\t{\n\t\t//\t\tconst auto& h = m_HandTrace[i];\n\t\t//\t\tfloat radius = (i + 1 - std::max<int>(0, m_HandTrace.size() - TraceLength)) / (std::min<float>(m_HandTrace.size(), TraceLength));\n\t\t//\t\tfor (size_t j = 0; j < h.size(); j++)\n\t\t//\t\t{\n\t\t//\t\t\t//m_HandTraceModel.Primitives.emplace_back(h[j], 0.02f);\n\t\t//\t\t\tg_PrimitiveDrawer.DrawSphere(h[j], 0.005f * radius, Colors::LimeGreen);\n\t\t//\t\t}\n\t\t//\t}\n\t\t//}\n\t}\n\tg_PrimitiveDrawer.End();\n\n\t//if (m_HandTrace.size() > 0)\n\t//{\n\t//\tif (!pBatch)\n\t//\t{\n\t//\t\tpBatch = std::make_unique<PrimitiveBatch<VertexPositionNormal>>(pContext, 204800,40960);\n\t//\t}\n\t//\tm_HandTraceModel.SetISO(0.33333f);\n\t//\tm_HandTraceModel.Update();\n\t//\tm_HandTraceModel.Tessellate(m_HandTraceVertices, m_HandTraceIndices, 0.005f);\n\t//\tpBatch->Begin();\n\t//\tpEffect->SetDiffuseColor(Colors::LimeGreen);\n\t//\t//pEffect->SetEmissiveColor(Colors::LimeGreen);\n\t//\tpEffect->SetTextureEnabled(false);\n\t//\tpEffect->SetWorld(XMMatrixIdentity());\n\t//\tpEffect->Apply(pContext);\n\t//\tpBatch->DrawIndexed(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, m_HandTraceIndices.data(), m_HandTraceIndices.size(), m_HandTraceVertices.data(), m_HandTraceVertices.size());\n\t//\tpBatch->End();\n\t//}\n\n}\n\nvoid Causality::WorldScene::DrawAxis()\n{\n\tg_PrimitiveDrawer.DrawSphere({ 0,0,0,0.02 }, Colors::Red);\n\tg_PrimitiveDrawer.DrawLine({ -5,0,0 }, { 5,0,0 }, Colors::Red);\n\tg_PrimitiveDrawer.DrawLine({ 0,-5,0 }, { 0,5,0 }, Colors::Green);\n\tg_PrimitiveDrawer.DrawLine({ 0,0,-5 }, { 0,0,5 }, Colors::Blue);\n\tg_PrimitiveDrawer.DrawTriangle({ 5.05f,0,0 }, { 4.95,0.05,0 }, { 4.95,-0.05,0 }, Colors::Red);\n\tg_PrimitiveDrawer.DrawTriangle({ 5.05f,0,0 }, { 4.95,-0.05,0 }, { 4.95,0.05,0 }, Colors::Red);\n\tg_PrimitiveDrawer.DrawTriangle({ 5.05f,0,0 }, { 4.95,0,0.05 }, { 4.95,0,-0.05 }, Colors::Red);\n\tg_PrimitiveDrawer.DrawTriangle({ 5.05f,0,0 }, { 4.95,0,-0.05 }, { 4.95,0,0.05 }, Colors::Red);\n\tg_PrimitiveDrawer.DrawTriangle({ 0,5.05f,0 }, { -0.05,4.95,0 }, { 0.05,4.95,0 }, Colors::Green);\n\tg_PrimitiveDrawer.DrawTriangle({ 0,5.05f,0 }, { 0.05,4.95,0 }, { -0.05,4.95,0 }, Colors::Green);\n\tg_PrimitiveDrawer.DrawTriangle({ 0,5.05f,0 }, { 0.0,4.95,-0.05 }, { 0,4.95,0.05 }, Colors::Green);\n\tg_PrimitiveDrawer.DrawTriangle({ 0,5.05f,0 }, { 0.0,4.95,0.05 }, { 0,4.95,-0.05 }, Colors::Green);\n\tg_PrimitiveDrawer.DrawTriangle({ 0,0,5.05f }, { 0.05,0,4.95 }, { -0.05,0,4.95 }, Colors::Blue);\n\tg_PrimitiveDrawer.DrawTriangle({ 0,0,5.05f }, { -0.05,0,4.95 }, { 0.05,0,4.95 }, Colors::Blue);\n\tg_PrimitiveDrawer.DrawTriangle({ 0,0,5.05f }, { 0,0.05,4.95 }, { 0,-0.05,4.95 }, Colors::Blue);\n\tg_PrimitiveDrawer.DrawTriangle({ 0,0,5.05f }, { 0,-0.05,4.95 }, { 0,0.05,4.95 }, Colors::Blue);\n\n}\n\nvoid Causality::WorldScene::DrawBox(DirectX::SimpleMath::Vector3  conners [], DirectX::CXMVECTOR color)\n{\n\tg_PrimitiveDrawer.DrawLine(conners[0], conners[1], color);\n\tg_PrimitiveDrawer.DrawLine(conners[1], conners[2], color);\n\tg_PrimitiveDrawer.DrawLine(conners[2], conners[3], color);\n\tg_PrimitiveDrawer.DrawLine(conners[3], conners[0], color);\n\n\tg_PrimitiveDrawer.DrawLine(conners[3], conners[7], color);\n\tg_PrimitiveDrawer.DrawLine(conners[2], conners[6], color);\n\tg_PrimitiveDrawer.DrawLine(conners[1], conners[5], color);\n\tg_PrimitiveDrawer.DrawLine(conners[0], conners[4], color);\n\n\tg_PrimitiveDrawer.DrawLine(conners[4], conners[5], color);\n\tg_PrimitiveDrawer.DrawLine(conners[5], conners[6], color);\n\tg_PrimitiveDrawer.DrawLine(conners[6], conners[7], color);\n\tg_PrimitiveDrawer.DrawLine(conners[7], conners[4], color);\n\n}\n\nvoid XM_CALLCONV Causality::WorldScene::UpdateViewMatrix(DirectX::FXMMATRIX view, DirectX::CXMMATRIX projection)\n{\n\tif (pEffect)\n\t{\n\t\tpEffect->SetView(view);\n\t\tpEffect->SetProjection(projection);\n\t}\n\tif (pBackground)\n\t{\n\t\tpBackground->UpdateViewMatrix(view,projection);\n\t}\n\tg_PrimitiveDrawer.SetView(view);\n\tg_PrimitiveDrawer.SetProjection( projection);\n\t\n\t// BoundingFrustum is assumpt Left-Handed\n\tBoundingFrustumExtension::CreateFromMatrixRH(ViewFrutum, projection);\n\t//BoundingFrustum::CreateFromMatrix(ViewFrutum, projection);\n\t// Fix the RH-projection matrix\n\t//XMStoreFloat4((XMFLOAT4*) &ViewFrutum.RightSlope, -XMLoadFloat4((XMFLOAT4*) &ViewFrutum.RightSlope));\n\t//XMStoreFloat2((XMFLOAT2*) &ViewFrutum.Near, -XMLoadFloat2((XMFLOAT2*) &ViewFrutum.Near));\n\t//ViewFrutum.LeftSlope = -ViewFrutum.LeftSlope;\n\t//ViewFrutum.RightSlope = -ViewFrutum.RightSlope;\n\t//ViewFrutum.TopSlope = -ViewFrutum.TopSlope;\n\t//ViewFrutum.BottomSlope = -ViewFrutum.BottomSlope;\n\t//ViewFrutum.Near = -ViewFrutum.Near;\n\t//ViewFrutum.Far = -ViewFrutum.Far;\n\tXMVECTOR det;\n\tauto invView = view;\n\t//invView.r[2] = -invView.r[2];\n\tinvView = XMMatrixInverse(&det, invView);\n\t//invView.r[2] = -invView.r[2];\n\t//XMVECTOR temp = invView.r[2];\n\t//invView.r[2] = invView.r[1];\n\t//invView.r[1] = temp;\n\tViewFrutum.Transform(ViewFrutum,invView);\n\t// Fix the RH-inv-view-matrix to LH-equalulent by swap row-y with row-z\n\t//XMStoreFloat3(&ViewFrutum.Origin, invView.r[3]);\n\n\t//XMStoreFloat4(&ViewFrutum.Orientation, XMQuaternionRotationMatrix(invView));;\n\n\t//for (const auto& item : m_HandModels)\n\t//{\n\t//\tif (item.second)\n\t//\t\titem.second->UpdateViewMatrix(view);\n\t//}\n}\n\n//void XM_CALLCONV Causality::WorldScene::UpdateProjectionMatrix(DirectX::FXMMATRIX projection)\n//{\n//\tif (pEffect)\n//\t\tpEffect->SetProjection(projection);\n//\tif (pBackground)\n//\t\tpBackground->UpdateProjectionMatrix(projection);\n//\t\n//\tg_PrimitiveDrawer.SetProjection(projection);\n//}\n\nvoid Causality::WorldScene::UpdateAnimation(StepTimer const & timer)\n{\n\t{\n\t\tlock_guard<mutex> guard(m_RenderLock);\n\t\tusing namespace cpplinq;\n\t\tusing namespace std::placeholders;\n\t\tfloat stepTime = (float) timer.GetElapsedSeconds();\n\t\tWorldTree->Evolution(stepTime, m_Frame, m_FrameTransform);\n\t\tModelStates = WorldTree->CaculateSuperposition();\n\t}\n\n\tif (m_HandTrace.size() > 0)\n\t{\n\t\t{ // Critia section\n\t\t\tstd::lock_guard<mutex> guard(m_HandFrameMutex);\n\t\t\tconst int plotSize = 45;\n\t\t\tBoundingOrientedBox::CreateFromPoints(m_CurrentHandBoundingBox, m_HandTrace.back().size(), m_HandTrace.back().data(), sizeof(Vector3));\n\t\t\tm_TracePoints.clear();\n\t\t\tColor color = Colors::LimeGreen;\n\t\t\tfor (int i = m_HandTrace.size() - 1; i >= std::max(0, (int) m_HandTrace.size() - plotSize); i--)\n\t\t\t{\n\t\t\t\tconst auto& h = m_HandTrace[i];\n\t\t\t\t//float radius = (i + 1 - std::max(0U, m_HandTrace.size() - plotSize)) / (std::min<float>(m_HandTrace.size(), plotSize));\n\t\t\t\tfor (size_t j = 0; j < h.size(); j++)\n\t\t\t\t{\n\t\t\t\t\t//g_PrimitiveDrawer.DrawSphere(h[j], 0.005 * radius, color);\n\t\t\t\t\tm_TracePoints.push_back(h[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//for (const auto& pModel : Children)\n\t\t\t//{\n\t\t\t//\t//btCollisionWorld::RayResultCallback\n\t\t\t//\tauto pRigid = dynamic_cast<PhysicalGeometryModel*>(pModel.get());\n\t\t\t//\tpRigid->GetBulletRigid()->checkCollideWith()\n\t\t\t//}\n\t\t\t//auto pBat = dynamic_cast<PhysicalGeometryModel*>(Children[0].get());\n\t\t\t//pBat->SetPosition(vector_cast<Vector3>(m_Frame.hands().frontmost().palmPosition()));\n\t\t}\n\t\tCreateBoundingOrientedBoxFromPoints(m_HandTraceBoundingBox, m_TracePoints.size(), m_TracePoints.data(), sizeof(Vector3));\n\t\tXMFLOAT3 v = m_HandTraceBoundingBox.Extents;\n\t\tm_HandDescriptionFeature = Eigen::Vector2f(v.y / v.x, v.z / v.x);\n\n\t\t// ASSUMPTION: Extends is sorted from!\n\n\n\t\t//XMMATRIX invTrans = XMMatrixAffineTransformation(g_XMOne / XMVectorReplicate(m_HandTraceBoundingBox.Extents.x), XMVectorZero(), XMQuaternionInverse(XMLoadFloat4(&m_HandTraceBoundingBox.Orientation)), -XMLoadFloat3(&m_HandTraceBoundingBox.Center));\n\t\t//int sampleCount = std::min<int>(m_TraceSamples.size(), TraceLength)*m_TraceSamples[0].size();\n\t\t//for (const auto& model : Children)\n\t\t//{\n\t\t//\tauto pModel = dynamic_cast<Model*>(model.get());\n\t\t//\tauto inCount = 0;\n\t\t//\tif (pModel)\n\t\t//\t{\n\t\t//\t\tauto obox = model->GetOrientedBoundingBox();\n\t\t//\t\tXMMATRIX fowTrans = XMMatrixAffineTransformation(XMVectorReplicate(obox.Extents.x), XMVectorZero(), XMQuaternionIdentity(), XMVectorZero());\n\t\t//\t\tfowTrans = invTrans * fowTrans;\n\t\t//\t\tauto pSample = m_TraceSamples.back().data() + m_TraceSamples.back().size()-1;\n\t\t//\t\tfor (size_t i = 0; i < sampleCount; i++)\n\t\t//\t\t{\n\t\t//\t\t\tconst auto& point = pSample[-i];\n\t\t//\t\t\tXMVECTOR p = XMVector3Transform(point, fowTrans);\n\t\t//\t\t\tint j;\n\t\t//\t\t\tfor ( j = 0; j < pModel->Parts.size(); j++)\n\t\t//\t\t\t{\n\t\t//\t\t\t\tif (pModel->Parts[j].BoundOrientedBox.Contains(p))\n\t\t//\t\t\t\t\tbreak;\n\t\t//\t\t\t}\n\t\t//\t\t\tif (j >= pModel->Parts.size())\n\t\t//\t\t\t\tinCount++;\n\t\t//\t\t}\n\t\t//\t}\n\t\t//\tm_ModelDetailSimilarity[model->Name] = (float) inCount / (float)sampleCount;\n\t\t//}\n\n\n\n\t}\n\n\t//if (pGroundRigid)\n\t//\tpGroundRigid->setLinearVelocity({ 0,-1.0f,0 });\n\n\n\n\t//pDynamicsWorld->stepSimulation(timer.GetElapsedSeconds(), 10);\n\n\t//for (auto& obj : Children)\n\t//{\n\t//\tauto s = (rand() % 1000) / 1000.0;\n\t//\tobj->Rotate(XMQuaternionRotationRollPitchYaw(0, 0.5f * timer.GetElapsedSeconds(), 0));\n\t//}\n}\n\nvoid Causality::WorldScene::OnHandsTracked(const UserHandsEventArgs & e)\n{\n\tm_HaveHands = true;\n\t//const auto& hand = e.sender.frame().hands().frontmost();\n\t//size_t i = 0;\n\t//\n\t//XMMATRIX leap2world = e.toWorldTransform;\n\t//for (const auto& finger : hand.fingers())\n\t//{\n\t//\tXMVECTOR bJ = XMVector3Transform(finger.bone((Leap::Bone::Type)0).prevJoint().toVector3<Vector3>(), leap2world);\n\t//\tauto pState = m_HandRigids[i]->GetBulletRigid()->getMotionState();\n\t//\tauto transform = btTransform::getIdentity();\n\t//\ttransform.setOrigin(vector_cast<btVector3>(bJ));\n\t//\tif (!pState)\n\t//\t{\n\t//\t\tpState = new btDefaultMotionState(transform);\n\t//\t\tm_HandRigids[i]->GetBulletRigid()->setMotionState(pState);\n\t//\t}\n\t//\telse\n\t//\t\tpState->setWorldTransform(transform);\n\t//\t\n\n\t//\ti++;\n\t//\tfor (size_t boneIdx = 0; boneIdx < 4; boneIdx++) // bone idx\n\t//\t{\n\t//\t\tconst auto & bone = finger.bone((Leap::Bone::Type)boneIdx);\n\t//\t\tXMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world);\n\n\t//\t\tauto pState = m_HandRigids[i]->GetBulletRigid()->getMotionState();\n\t//\t\tauto transform = btTransform::getIdentity();\n\t//\t\ttransform.setOrigin(vector_cast<btVector3>(eJ));\n\t//\t\tif (!pState)\n\t//\t\t{\n\t//\t\t\tpState = new btDefaultMotionState(transform);\n\t//\t\t\tm_HandRigids[i]->GetBulletRigid()->setMotionState(pState);\n\t//\t\t}\n\t//\t\telse\n\t//\t\t\tpState->setWorldTransform(transform);\n\n\t//\t\ti++;\n\t//\t}\n\t//}\n\n\tm_Frame = e.sender.frame();\n\tfor (auto& branch : WorldTree->leaves())\n\t{\n\t\tfor (const auto& hand : m_Frame.hands())\n\t\t{\n\t\t\tauto & subjects = branch.Subjects;\n\t\t\tbranch.AddSubjectiveObject(hand,e.toWorldTransform);\n\t\t\t//if (!subjects[hand.id()])\n\t\t\t//{\n\t\t\t//\tsubjects[hand.id()].reset(\n\t\t\t//\t\tnew HandPhysicalModel(\n\t\t\t//\t\tpFrame->pDynamicsWorld,\n\t\t\t//\t\thand, e.toWorldTransform,\n\t\t\t//\t\tpFrame->SubjectTransform)\n\t\t\t//\t\t);\n\t\t\t//\t//for (const auto& itm : pFrame->Objects)\n\t\t\t//\t//{\n\t\t\t//\t//\tconst auto& pObj = itm.second;\n\t\t\t//\t//\tif (!pObj->GetBulletRigid()->isStaticOrKinematicObject())\n\t\t\t//\t//\t{\n\t\t\t//\t//\t\tfor (const auto& bone : subjects[hand.id()]->Rigids())\n\t\t\t//\t//\t\t\tpObj->GetBulletRigid()->setIgnoreCollisionCheck(bone.get(), false);\n\t\t\t//\t//\t}\n\t\t\t//\t//}\n\t\t\t//}\n\t\t}\n\t}\n\n\t//for (size_t j = 0; j < i; j++)\n\t//{\n\t//\tpDynamicsWorld->addRigidBody(m_HandRigids[j]->GetBulletRigid());\n\t//\tm_HandRigids[j]->GetBulletRigid()->setGravity({ 0,0,0 });\n\t//}\n}\n\nvoid Causality::WorldScene::OnHandsTrackLost(const UserHandsEventArgs & e)\n{\n\tm_Frame = e.sender.frame();\n\tm_FrameTransform = e.toWorldTransform;\n\tif (m_Frame.hands().count() == 0)\n\t{\n\t\tm_HaveHands = false;\n\t\tstd::lock_guard<mutex> guard(m_HandFrameMutex);\n\t\tm_HandTrace.clear();\n\t\tm_TraceSamples.clear();\n\t\tWorldTree->Collapse();\n\t\t//for (const auto &pRigid : m_HandRigids)\n\t\t//{\n\t\t//\tpDynamicsWorld->removeRigidBody(pRigid->GetBulletRigid());\n\t\t//}\n\t}\n}\n\nvoid Causality::WorldScene::OnHandsMove(const UserHandsEventArgs & e)\n{\n\tstd::lock_guard<mutex> guard(m_HandFrameMutex);\n\tm_Frame = e.sender.frame();\n\tm_FrameTransform = e.toWorldTransform;\n\tXMMATRIX leap2world = m_FrameTransform;\n\t//std::array<DirectX::Vector3, 25> joints;\n\tstd::vector<DirectX::BoundingOrientedBox> handBoxes;\n\tfloat fingerStdev = 0.02f;\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\tstd::normal_distribution<float> normalDist(0, fingerStdev);\n\tstd::uniform_real<float> uniformDist;\n\n\t// Caculate moving trace\n\tint handIdx = 0;\n\tfor (const auto& hand : m_Frame.hands())\n\t{\n\t\tint fingerIdx = 0; // hand idx\n\t\tm_HandTrace.emplace_back();\n\t\tm_TraceSamples.emplace_back();\n\t\tauto& samples = m_TraceSamples.back();\n\t\tauto& joints = m_HandTrace.back();\n\t\tfor (const auto& finger : hand.fingers())\n\t\t{\n\t\t\tXMVECTOR bJ = XMVector3Transform(finger.bone((Leap::Bone::Type)0).prevJoint().toVector3<Vector3>(), leap2world);\n\t\t\tjoints[fingerIdx * 5] = bJ;\n\t\t\tfor (size_t boneIdx = 0; boneIdx < 4; boneIdx++) // bone idx\n\t\t\t{\n\t\t\t\tconst auto & bone = finger.bone((Leap::Bone::Type)boneIdx);\n\t\t\t\tXMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world);\n\t\t\t\tjoints[fingerIdx * 5 + boneIdx + 1] = eJ;\n\n\n\t\t\t\t//auto dir = eJ - bJ;\n\t\t\t\t//float dis = XMVectorGetX(XMVector3Length(dir));\n\t\t\t\t//if (abs(dis) < 0.001)\n\t\t\t\t//\tcontinue;\n\t\t\t\t//XMVECTOR rot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, dir);\n\t\t\t\t//bJ = eJ;\n\t\t\t\t//for (size_t k = 0; k < 100; k++) // bone idx\n\t\t\t\t//{\n\t\t\t\t//\tfloat x = normalDist(gen);\n\t\t\t\t//\tfloat h = uniformDist(gen);\n\t\t\t\t//\tfloat z = normalDist(gen);\n\t\t\t\t//\tXMVECTOR disp = XMVectorSet(x, h*dis, z, 1);\n\t\t\t\t//\tdisp = XMVector3Rotate(disp, rot);\n\t\t\t\t//\tdisp += bJ;\n\t\t\t\t//\tsamples[(fingerIdx * 4 + boneIdx) * 100 + k] = disp;\n\t\t\t\t//}\n\t\t\t}\n\t\t\tfingerIdx++;\n\t\t}\n\t\thandIdx++;\n\t\twhile (m_HandTrace.size() > 60)\n\t\t{\n\t\t\tm_HandTrace.pop_front();\n\t\t\t//m_TraceSamples.pop_front();\n\t\t}\n\n\t\t// Cone intersection test section\n\t\t//Vector3 rayEnd = XMVector3Transform(hand.palmPosition().toVector3<Vector3>(), leap2world);\n\t\t//Vector3 rayBegin = m_pCameraLocation->GetPosition();\n\t\t//auto pConeShape = new btConeShape(100, XM_PI / 16 * 100);\n\t\t//auto pCollisionCone = new btCollisionObject();\n\t\t//pCollisionCone->setCollisionShape(pConeShape);\n\t\t//btTransform trans(\n\t\t//\tvector_cast<btQuaternion>(XMQuaternionRotationVectorToVector(g_XMIdentityR1, rayEnd - rayBegin)),\n\t\t//\tvector_cast<btVector3>(rayBegin));\n\t\t//pCollisionCone->setWorldTransform(trans);\n\t\t//class Callback : public btDynamicsWorld::ContactResultCallback\n\t\t//{\n\t\t//public:\n\t\t//\tconst IModelNode* pModel;\n\t\t//\tCallback() {}\n\n\t\t//\tvoid SetModel(const IModelNode* pModel)\n\t\t//\t{\n\t\t//\t\tthis->pModel = pModel;\n\t\t//\t}\n\t\t//\tCallback(const IModelNode* pModel)\n\t\t//\t\t: pModel(pModel)\n\t\t//\t{\n\t\t//\t}\n\t\t//\tvirtual\tbtScalar\taddSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1)\n\t\t//\t{\n\t\t//\t\tcout << \"point frustrum contact with \"<< pModel->Name << endl;\n\t\t//\t\treturn 0;\n\t\t//\t}\n\t\t//};\n\t\t//static map<string, Callback> callbackTable;\n\n\n\t\t//for (const auto& model : Children)\n\t\t//{\n\t\t//\tauto pRigid = dynamic_cast<PhysicalRigid*>(model.get());\n\t\t//\tcallbackTable[model->Name].SetModel(model.get());\n\t\t//\tpDynamicsWorld->contactPairTest(pRigid->GetBulletRigid(), pCollisionCone, callbackTable[model->Name]);\n\t\t//}\n\t}\n\n\t//int i = 0;\n\t//const auto& hand = m_Frame.hands().frontmost();\n\t//for (const auto& finger : hand.fingers())\n\t//{\n\t//\tXMVECTOR bJ = XMVector3Transform(finger.bone((Leap::Bone::Type)0).prevJoint().toVector3<Vector3>(), leap2world);\n\t//\tauto pState = m_HandRigids[i]->GetBulletRigid()->getMotionState();\n\t//\tauto transform = btTransform::getIdentity();\n\t//\ttransform.setOrigin(vector_cast<btVector3>(bJ));\n\t//\tm_HandRigids[i]->GetBulletRigid()->proceedToTransform(transform);\n\n\n\t//\ti++;\n\t//\tfor (size_t boneIdx = 0; boneIdx < 4; boneIdx++) // bone idx\n\t//\t{\n\t//\t\tconst auto & bone = finger.bone((Leap::Bone::Type)boneIdx);\n\t//\t\tXMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world);\n\n\t//\t\tauto pState = m_HandRigids[i]->GetBulletRigid()->getMotionState();\n\t//\t\tauto transform = btTransform::getIdentity();\n\t//\t\ttransform.setOrigin(vector_cast<btVector3>(eJ));\n\t//\t\tm_HandRigids[i]->GetBulletRigid()->proceedToTransform(transform);\n\n\t//\t\ti++;\n\t//\t}\n\t//}\n\n\n\tstd::cout << \"[Leap] Hands Move.\" << std::endl;\n}\n\nvoid Causality::WorldScene::OnKeyDown(const KeyboardEventArgs & e)\n{\n}\n\nvoid Causality::WorldScene::OnKeyUp(const KeyboardEventArgs & e)\n{\n\tif (e.Key == 'T')\n\t\tm_showTrace = !m_showTrace;\n}\n\nvoid Causality::WorldScene::AddObject(const std::shared_ptr<IModelNode>& pModel, float mass, const DirectX::Vector3 & Position, const DirectX::Quaternion & Orientation, const Vector3 & Scale)\n{\n\tlock_guard<mutex> guard(m_RenderLock);\n\tModels.push_back(pModel);\n\tauto pShaped = dynamic_cast<IShaped*>(pModel.get());\n\tauto pShape = pShaped->CreateCollisionShape();\n\tpShape->setLocalScaling(vector_cast<btVector3>(Scale));\n\n\tWorldTree->AddDynamicObject(pModel->Name, pShape, mass, Position, Orientation);\n\t//for (const auto& pFrame : m_StateFrames)\n\t//{\n\t//\tauto pObject = std::shared_ptr<PhysicalRigid>(new PhysicalRigid());\n\t//\tpObject->InitializePhysics(pFrame->pDynamicsWorld, pShape, mass, Position, Orientation);\n\t//\tpObject->GetBulletRigid()->setFriction(1.0f);\n\t//\tpObject->GetBulletRigid()->setDamping(0.8, 0.9);\n\t//\tpObject->GetBulletRigid()->setRestitution(0.0);\n\t//\tpFrame->Objects[pModel->Name] = pObject;\n\t//}\n}\n\nstd::pair<DirectX::Vector3, DirectX::Quaternion> XM_CALLCONV CaculateCylinderTransform(FXMVECTOR P1, FXMVECTOR P2)\n{\n\tstd::pair<DirectX::Vector3, DirectX::Quaternion> trans;\n\tauto center = XMVectorAdd(P1, P2);\n\tcenter = XMVectorMultiply(center, g_XMOneHalf);\n\tauto dir = XMVectorSubtract(P1, P2);\n\tauto scale = XMVector3Length(dir);\n\tXMVECTOR rot;\n\tif (XMVector4Equal(dir, g_XMZero))\n\t\trot = XMQuaternionIdentity();\n\telse\n\t\trot = XMQuaternionRotationVectorToVector(g_XMIdentityR1.v, dir);\n\ttrans.first = center;\n\ttrans.second = rot;\n\treturn trans;\n}\n\nXMMATRIX Causality::HandPhysicalModel::CaculateLocalMatrix(const Leap::Hand & hand, const DirectX::Matrix4x4 & leapTransform)\n{\n\tXMVECTOR palmCenter = hand.palmPosition().toVector3<Vector3>();\n\treturn XMMatrixScalingFromCenter(m_InheritTransform.Scale, palmCenter) * ((RigidTransform&) m_InheritTransform).TransformMatrix() * (XMMATRIX) leapTransform;\n\n}\n\n\nCausality::HandPhysicalModel::HandPhysicalModel\n(const std::shared_ptr<btDynamicsWorld> &pWorld,\nconst Leap::Hand & hand, const DirectX::Matrix4x4 & leapTransform,\nconst DirectX::AffineTransform &inheritTransform)\n: m_Hand(hand)\n{\n\tColor.G(0.5f);\n\tColor.B(0.5f);\n\n\tId = hand.id();\n\tm_InheritTransform = inheritTransform;\n\n\tLocalMatrix = CaculateLocalMatrix(hand, leapTransform);\n\tXMMATRIX leap2world = LocalMatrix;\n\tint j = 0;\n\tfor (const auto& finger : m_Hand.fingers())\n\t{\n\t\tfor (size_t i = 0; i < 4; i++)\n\t\t{\n\t\t\tconst auto & bone = finger.bone((Leap::Bone::Type)i);\n\t\t\tXMVECTOR bJ = XMVector3Transform(bone.prevJoint().toVector3<Vector3>(), leap2world);\n\t\t\tXMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world);\n\t\t\tm_Bones[i + j * 4].first = bJ;\n\t\t\tm_Bones[i + j * 4].second = eJ;\n\n\t\t\t// Initalize rigid hand model\n\t\t\tauto center = 0.5f * XMVectorAdd(bJ, eJ);\n\t\t\tauto dir = XMVectorSubtract(eJ, bJ);\n\t\t\tauto height = std::max(XMVectorGetX(XMVector3Length(dir)), fingerLength);\n\t\t\tXMVECTOR rot;\n\t\t\tif (XMVector4Equal(dir, g_XMZero))\n\t\t\t\trot = XMQuaternionIdentity();\n\t\t\telse\n\t\t\t\trot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, dir);\n\t\t\tshared_ptr<btCapsuleShape> pShape(new btCapsuleShape(fingerRadius, height));\n\n\t\t\t// Scaling in Y axis is encapsled in bJ and eJ\n\t\t\tbtVector3 scl = vector_cast<btVector3>(m_InheritTransform.Scale);\n\t\t\tscl.setY(1.0f);\n\t\t\tpShape->setLocalScaling(scl);\n\n\t\t\tm_HandRigids.emplace_back(new PhysicalRigid());\n\t\t\tconst auto & pRigid = m_HandRigids.back();\n\t\t\t//pRigid->GetBulletRigid()->setGravity({ 0,0,0 });\n\t\t\tpRigid->InitializePhysics(nullptr, pShape, 0, center, rot);\n\t\t\tconst auto& body = pRigid->GetBulletRigid();\n\t\t\tbody->setFriction(1.0f);\n\t\t\tbody->setRestitution(0.0f);\n\t\t\tbody->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);\n\t\t\tbody->setActivationState(DISABLE_DEACTIVATION);\n\t\t\t//body->setAngularFactor(0.0f); // Rotation Along Y not affact\n\n\t\t\tpRigid->Enable(pWorld);\n\t\t}\n\t}\n\n\t//for (size_t i = 0; i < m_HandRigids.size(); i++)\n\t//{\n\t//\tfor (size_t j = 0; j < m_HandRigids.size(); j++)\n\t//\t{\n\t//\t\tif (i != j)\n\t//\t\t\tm_HandRigids[i]->GetBulletRigid()->setIgnoreCollisionCheck(m_HandRigids[j]->GetBulletRigid(), true);\n\t//\t}\n\t//}\n\n}\n\nbool Causality::HandPhysicalModel::Update(const Leap::Frame & frame, const DirectX::Matrix4x4 & leapTransform)\n{\n\tm_Hand = frame.hand(Id);\n\n\tif (m_Hand.isValid())\n\t{\n\t\tXMMATRIX transform = CaculateLocalMatrix(m_Hand, leapTransform);\n\t\tLocalMatrix = transform;\n\t\tColor.R(m_Hand.grabStrength());\n\t\tLostFrames = 0;\n\t\tint j = 0;\n\t\tfor (const auto& finger : m_Hand.fingers())\n\t\t{\n\t\t\tfor (size_t i = 0; i < 4; i++)\n\t\t\t{\n\t\t\t\tconst auto & bone = finger.bone((Leap::Bone::Type)i);\n\t\t\t\tXMVECTOR bJ = XMVector3Transform(bone.prevJoint().toVector3<Vector3>(), transform);\n\t\t\t\tXMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), transform);\n\t\t\t\tm_Bones[i + j * 4].first = bJ;\n\t\t\t\tm_Bones[i + j * 4].second = eJ;\n\n\t\t\t\t// Rigid hand model\n\n\t\t\t\tauto & pRigid = m_HandRigids[i + j * 4];\n\t\t\t\tif (!pRigid->IsEnabled())\n\t\t\t\t\tpRigid->Enable();\n\t\t\t\tauto center = 0.5f * XMVectorAdd(bJ, eJ);\n\t\t\t\tauto dir = XMVectorSubtract(eJ, bJ);\n\t\t\t\tXMVECTOR rot;\n\t\t\t\tif (XMVector4Equal(dir, g_XMZero))\n\t\t\t\t\trot = XMQuaternionIdentity();\n\t\t\t\telse\n\t\t\t\t\trot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, dir);\n\t\t\t\tauto trans = btTransform(vector_cast<btQuaternion>(rot), vector_cast<btVector3>(center));\n\t\t\t\tpRigid->GetBulletRigid()->getMotionState()->setWorldTransform(trans);\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tfor (auto& pRigid : m_HandRigids)\n\t\t{\n\t\t\tpRigid->Disable();\n\t\t}\n\t\tLostFrames++;\n\t\treturn false;\n\t}\n}\n\n// Inherited via IModelNode\n\nvoid Causality::HandPhysicalModel::Render(ID3D11DeviceContext * pContext, DirectX::IEffect * pEffect)\n{\n\tXMMATRIX leap2world = LocalMatrix;\n\t//auto palmPosition = XMVector3Transform(m_Hand.palmPosition().toVector3<Vector3>(), leap2world);\n\t//g_PrimitiveDrawer.DrawSphere(palmPosition, 0.02f, Colors::YellowGreen);\n\tColor.A(Opticity);\n\tXMVECTOR color = Color;\n\t//color = XMVectorSetW(color, Opticity);\n\n\t//g_PrimitiveDrawer.Begin();\n\t//for (const auto& bone : m_Bones)\n\t//{\n\t//\t//g_PrimitiveDrawer.DrawSphere(bone.second, fingerRadius, jC);\n\t//\tg_PrimitiveDrawer.DrawCylinder(bone.first, bone.second, fingerRadius * m_InheritTransform.Scale.x, color);\n\t//}\n\t//g_PrimitiveDrawer.End();\n\n\tfor (const auto& pRigid : m_HandRigids)\n\t{\n\t\tg_PrimitiveDrawer.DrawCylinder(\n\t\t\tpRigid->GetPosition(),\n\t\t\tXMVector3Rotate(g_XMIdentityR1, pRigid->GetOrientation()),\n\t\t\tdynamic_cast<btCapsuleShape*>(pRigid->GetBulletShape())->getHalfHeight() * 2,\n\t\t\tfingerRadius * m_InheritTransform.Scale.x,\n\t\t\tcolor);\n\t}\n\n\t//for (const auto& finger : m_Hand.fingers())\n\t//{\n\t//\tfor (size_t i = 0; i < 4; i++)\n\t//\t{\n\t//\t\tconst auto & bone = finger.bone((Leap::Bone::Type)i);\n\t//\t\tXMVECTOR bJ = XMVector3Transform(bone.prevJoint().toVector3<Vector3>(), leap2world);\n\t//\t\tXMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world);\n\t//\t\t//g_PrimitiveDrawer.DrawLine(bJ, eJ, Colors::LimeGreen);\n\t//\t\t//g_PrimitiveDrawer.DrawCube(bJ, g_XMOne * 0.03, g_XMIdentityR3, Colors::Red);\n\t//\t\tg_PrimitiveDrawer.DrawCylinder(bJ, eJ,0.015f,Colors::LimeGreen);\n\n\t//\t\t//auto center = 0.5f * XMVectorAdd(bJ, eJ);\n\t//\t\t//auto dir = XMVectorSubtract(eJ, bJ);\n\t//\t\t//auto scale = XMVector3Length(dir);\n\t//\t\t//XMVECTOR rot;\n\t//\t\t//if (XMVector4LessOrEqual(XMVector3LengthSq(dir), XMVectorReplicate(0.01f)))\n\t//\t\t//\trot = XMQuaternionIdentity();\n\t//\t\t//else\n\t//\t\t//\trot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, dir);\n\t//\t\t//XMMATRIX world = XMMatrixAffineTransformation(scale, g_XMZero, rot, center);\n\t//\t\t//s_pCylinder->Draw(world, ViewMatrix, ProjectionMatrix,Colors::LimeGreen);\n\t//\t}\n\t//}\n}\n\ninline void debug_assert(bool condition)\n{\n#ifdef DEBUG\n\tif (!condition)\n\t{\n\t\t_CrtDbgBreak();\n\t\t//std::cout << \"assert failed.\" << std::endl;\n\t}\n#endif\n}\n\n// normalized feild intensity equalent charge\nXMVECTOR XM_CALLCONV FieldSegmentToPoint(FXMVECTOR P, FXMVECTOR L0, FXMVECTOR L1)\n{\n\tif (XMVector4NearEqual(L0, L1, XMVectorReplicate(0.001f)))\n\t{\n\t\tXMVECTOR v = XMVectorAdd(L0, L1);\n\t\tv = XMVectorMultiply(v, g_XMOneHalf);\n\t\tv = XMVectorSubtract(v, P);\n\t\tXMVECTOR d = XMVector3LengthSq(v);\n\t\tv = XMVector3Normalize(v);\n\t\tv /= d;\n\t\treturn v;\n\t}\n\n\tXMVECTOR s = XMVectorSubtract(L1, L0);\n\tXMVECTOR v0 = XMVectorSubtract(L0, P);\n\tXMVECTOR v1 = XMVectorSubtract(L1, P);\n\n\tXMMATRIX Rot;\n\tRot.r[1] = XMVector3Normalize(s);\n\tRot.r[2] = XMVector3Cross(v0, v1);\n\tRot.r[2] = XMVector3Normalize(Rot.r[2]);\n\tRot.r[0] = XMVector3Cross(Rot.r[1], Rot.r[2]);\n\tRot.r[3] = g_XMIdentityR3;\n\n\t// Rotated to standard question:\n\t//  Y\n\t//  ^     *y1\n\t//  |     |\n\t//--o-----|x0----->X\n\t//  |     |\n\t//\t|     |\n\t//\t      *y0\n\t// Close form solution of the intergral : f(y0,y1) = <-y/(x0*sqrt(x0^2+y^2)),1/sqrt(x0^2+y^2),0> | (y0,y1)\n\tXMVECTOR Ds = XMVector3ReciprocalLength(s);\n\tXMVECTOR Ps = XMVector3Dot(v0, s);\n\tXMVECTOR Y0 = XMVectorMultiply(Ps, Ds);\n\n\tPs = XMVector3Dot(v1, s);\n\tXMVECTOR Y1 = XMVectorMultiply(Ps, Ds);\n\n\tXMVECTOR X0 = XMVector3LengthSq(v1);\n\tPs = XMVectorMultiply(Y1, Y1);\n\tX0 = XMVectorSubtract(X0, Ps);\n\t//debug_assert(XMVector4GreaterOrEqual(X0, XMVectorZero()));\n\tXMVECTOR R0 = XMVectorMultiplyAdd(Y0, Y0, X0);\n\tXMVECTOR R1 = XMVectorMultiplyAdd(Y1, Y1, X0);\n\tR0 = XMVectorReciprocalSqrt(R0);\n\tR1 = XMVectorReciprocalSqrt(R1);\n\n\tXMVECTOR Ry = XMVectorSubtract(R1, R0);\n\n\tR0 = XMVectorMultiply(R0, Y0);\n\tR1 = XMVectorMultiply(R1, Y1);\n\tXMVECTOR Rx = XMVectorSubtract(R0, R1);\n\tX0 = XMVectorReciprocalSqrt(X0);\n\t//debug_assert(!XMVectorGetIntX(XMVectorIsNaN(X0)));\n\tRx = XMVectorMultiply(Rx, X0);\n\tRx = XMVectorSelect(Rx, Ry, g_XMSelect0101);\n\t// Field intensity in P centered coordinate\n\tRx = XMVectorAndInt(Rx, g_XMSelect1100);\n\n\tRx = XMVectorMultiply(Rx, Ds);\n\tRx = XMVector3Transform(Rx, Rot);\n\n\t//debug_assert(!XMVectorGetIntX(XMVectorIsNaN(Rx)));\n\treturn Rx;\n}\n\nDirectX::XMVECTOR XM_CALLCONV Causality::HandPhysicalModel::FieldAtPoint(DirectX::FXMVECTOR P)\n{\n\t// Palm push force \n\t//XMVECTOR palmP = m_Hand.palmPosition().toVector3<Vector3>();\n\t//XMVECTOR palmN = m_Hand.palmNormal().toVector3<Vector3>();\n\t//auto dis = XMVectorSubtract(P,palmP);\n\t//auto mag = XMVectorReciprocal(XMVector3LengthSq(dis));\n\t//dis = XMVector3Normalize(dis);\n\t//auto fac = XMVector3Dot(dis, palmN);\n\t//mag = XMVectorMultiply(fac, mag);\n\t//return XMVectorMultiply(dis, mag);\n\n\tXMVECTOR field = XMVectorZero();\n\tfor (const auto& bone : m_Bones)\n\t{\n\t\tXMVECTOR v0 = bone.first;\n\t\tXMVECTOR v1 = bone.second;\n\t\tXMVECTOR f = FieldSegmentToPoint(P, v0, v1);\n\t\tfield += f;\n\t\t//XMVECTOR l = XMVector3LengthSq(XMVectorSubtract(v1,v0));\n\t}\n\treturn field;\n}\n\ninline Causality::CubeModel::CubeModel(const std::string & name, DirectX::FXMVECTOR extend, DirectX::FXMVECTOR color)\n{\n\tName = name;\n\tm_Color = color;\n\n\tXMStoreFloat3(&BoundBox.Extents, extend);\n\tXMStoreFloat3(&BoundOrientedBox.Extents, extend);\n}\n\nstd::shared_ptr<btCollisionShape> Causality::CubeModel::CreateCollisionShape()\n{\n\tstd::shared_ptr<btCollisionShape> pShape;\n\tpShape.reset(new btBoxShape(vector_cast<btVector3>(BoundBox.Extents)));\n\treturn pShape;\n}\n\nvoid Causality::CubeModel::Render(ID3D11DeviceContext * pContext, DirectX::IEffect * pEffect)\n{\n\tXMVECTOR extent = XMLoadFloat3(&BoundBox.Extents);\n\tXMMATRIX world = GetWorldMatrix();\n\t//XMVECTOR scale, pos, rot;\n\tXMVECTOR color = m_Color;\n\tcolor = XMVectorSetW(color, Opticity);\n\tg_PrimitiveDrawer.DrawCube(extent, world, color);\n}\n\n// !!!Current don't support dynamic scaling for each state now!!!\ninline std::shared_ptr<btCollisionShape> Causality::ShapedGeomrtricModel::CreateCollisionShape()\n{\n\tif (!m_pShape)\n\t{\n\t\tbtTransform trans;\n\t\tstd::shared_ptr<btCompoundShape> pShape(new btCompoundShape());\n\t\t//trans.setOrigin(vector_cast<btVector3>(model->BoundOrientedBox.Center));\n\t\t//trans.setRotation(vector_cast<btQuaternion>(model->BoundOrientedBox.Orientation));\n\t\t//pShape->addChildShape(trans, new btBoxShape(vector_cast<btVector3>(model->BoundOrientedBox.Extents)));\n\t\tfor (const auto& part : Parts)\n\t\t{\n\t\t\ttrans.setOrigin(vector_cast<btVector3>(part->BoundOrientedBox.Center));\n\t\t\ttrans.setRotation(vector_cast<btQuaternion>(part->BoundOrientedBox.Orientation));\n\t\t\tpShape->addChildShape(trans, new btBoxShape(vector_cast<btVector3>(part->BoundOrientedBox.Extents)));\n\t\t}\n\t\tm_pShape = pShape;\n\t\treturn m_pShape;\n\t}\n\telse\n\t{\n\t\treturn m_pShape;\n\t}\n}\n\nvoid Causality::WorldBranch::InitializeBranchPool(int size, bool autoExpandation)\n{\n\tfor (size_t i = 0; i < 30; i++)\n\t{\n\t\tBranchPool.emplace(new WorldBranch());\n\t}\n}\n\nvoid Causality::WorldBranch::Reset()\n{\n\tfor (const auto& pair : Items)\n\t{\n\t\tpair.second->Disable();\n\t}\n\tItems.clear();\n}\n\nvoid Causality::WorldBranch::Collapse()\n{\n\t//using namespace cpplinq;\n\t//using cref = decltype(m_StateFrames)::const_reference;\n\t//auto mlh = from(m_StateFrames)\n\t//\t>> where([](cref pFrame) {return pFrame->IsEnabled; })\n\t//\t>> max([](cref pFrame)->float {return pFrame->Liklyhood(); });\n\t//WordBranch master_frame;\n\t////for (auto & pFrame : m_StateFrames)\n\t////{\n\t////\tif (pFrame->Liklyhood() < mlh)\n\t////\t{\n\t////\t\tpFrame->Disable();\n\t////\t\tm_pFramesPool->Recycle(std::move(pFrame));\n\t////\t}\n\t////\telse\n\t////\t{\n\t////\t\tmaster_frame = std::move(pFrame);\n\t////\t}\n\t////}\n\t//m_StateFrames.clear();\n\t//m_StateFrames.push_back(std::move(master_frame));\n}\n\nSuperpositionMap Causality::WorldBranch::CaculateSuperposition()\n{\n\tusing namespace cpplinq;\n\tSuperpositionMap SuperStates;\n\n\tauto itr = this->begin();\n\tauto eitr = this->end();\n\n\tNormalizeLiklyhood(CaculateLiklyhood());\n\n\tauto pItem = Items.begin();\n\tfor (size_t i = 0; i < Items.size(); i++,++pItem)\n\t{\n\t\tconst auto& pModel = pItem->second;\n\t\tauto& distribution = SuperStates[pItem->first];\n\t\t//auto&  = state.StatesDistribution;\n\t\tint j = 0;\n\n\t\tfor (const auto& branch : leaves())\n\t\t{\n\t\t\tif (!branch.IsEnabled)\n\t\t\t\tcontinue;\n\n\t\t\tauto itrObj = branch.Items.find(pItem->first);\n\n\t\t\tif (itrObj == branch.Items.end())\n\t\t\t\tcontinue;\n\t\t\tauto pNew = itrObj->second;\n\n\t\t\tProblistiscAffineTransform tNew;\n\t\t\ttNew.Translation = pNew->GetPosition();\n\t\t\ttNew.Rotation = pNew->GetOrientation();\n\t\t\ttNew.Scale = pNew->GetScale();\n\t\t\ttNew.Probability = branch.Liklyhood();\n\n\t\t\tauto itr = std::find_if(distribution.begin(), distribution.end(),\n\t\t\t\t[&tNew](std::remove_reference_t<decltype(distribution)>::const_reference trans) -> bool\n\t\t\t{\n\t\t\t\treturn trans.NearEqual(tNew);\n\t\t\t});\n\n\t\t\tif (itr == distribution.end())\n\t\t\t{\n\t\t\t\tdistribution.push_back(tNew);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\titr->Probability += tNew.Probability;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t}\n\n\treturn SuperStates;\n}\n\nvoid Causality::WorldBranch::InternalEvolution(float timeStep, const Leap::Frame & frame, const DirectX::Matrix4x4 & leapTransform)\n{\n\tauto& subjects = Subjects;\n\n\tBoundingSphere sphere;\n\n\t//if (!is_leaf()) return;\n\tfor (auto itr = subjects.begin(); itr != subjects.end(); )\n\t{\n\t\tbool result = itr->second->Update(frame, leapTransform);\n\t\t// Remove hands lost track for 60+ frames\n\t\tif (!result)\n\t\t{\n\t\t\tif (itr->second->LostFramesCount() > 60)\n\t\t\t\titr = subjects.erase(itr);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//std::vector<PhysicalRigid*> collideObjects;\n\n\t\t\t//for (auto& item : Items)\n\t\t\t//{\n\t\t\t//\tbtVector3 c;\n\t\t\t//\titem.second->GetBulletShape()->getBoundingSphere(c, sphere.Radius);\n\t\t\t//\tsphere.Center = vector_cast<Vector3>(sphere.Center);\n\t\t\t//\tif (itr->second->OperatingFrustum().Contains(sphere) != ContainmentType::DISJOINT)\n\t\t\t//\t{\n\t\t\t//\t\tcollideObjects.push_back(item.second.get());\n\t\t\t//\t}\n\t\t\t//}\n\t\t\t//if (collideObjects.size() > 0)\n\t\t\t//{\n\t\t\t//\tFork(collideObjects);\n\t\t\t//}\n\n\n\t\t\t//const auto &pHand = itr->second;\n\t\t\t//for (auto& item : pFrame->Objects)\n\t\t\t//{\n\t\t\t//\tconst auto& pObj = item.second;\n\t\t\t//\tif (pObj->GetBulletRigid()->isStaticObject())\n\t\t\t//\t\tcontinue;\n\t\t\t//\t//pObj->GetBulletShape()->\n\t\t\t//\tauto force = pHand->FieldAtPoint(pObj->GetPosition()) * 0.00001f;\n\t\t\t//\tpObj->GetBulletRigid()->clearForces();\n\t\t\t//\t//vector_cast<btVector3>(force) * 0.01f\n\t\t\t//\tstd::cout << item.first << \" : \" << Vector3(force) << std::endl;\n\t\t\t//\tpObj->GetBulletRigid()->applyCentralForce(vector_cast<btVector3>(force));\n\t\t\t//\tpObj->GetBulletRigid()->activate();\n\t\t\t//}\n\t\t\t++itr;\n\t\t}\n\t}\n\tpDynamicsWorld->stepSimulation(timeStep, 10);\n}\n\nfloat Causality::WorldBranch::CaculateLiklyhood()\n{\n\tif (is_leaf())\n\t{\n\t\tif (IsEnabled)\n\t\t\t_Liklyhood = 1;\n\t\telse\n\t\t\t_Liklyhood = 0;\n\t\treturn _Liklyhood;\n\t}\n\telse\n\t{\n\t\t_Liklyhood = 0;\n\t\tfor (auto& branch : children())\n\t\t{\n\t\t\t_Liklyhood += branch.CaculateLiklyhood();\n\t\t}\n\t\treturn _Liklyhood;\n\t}\n}\n\nvoid Causality::WorldBranch::NormalizeLiklyhood(float total)\n{\n\tfor (auto& branch : nodes_in_tree())\n\t{\n\t\tbranch._Liklyhood /= total;\n\t}\n}\n\nvoid Causality::WorldBranch::AddSubjectiveObject(const Leap::Hand & hand, const DirectX::Matrix4x4& leapTransform)\n{\n\tif (!Subjects[hand.id()])\n\t{\n\t\tSubjects[hand.id()].reset(\n\t\t\tnew HandPhysicalModel(\n\t\t\tpDynamicsWorld,\n\t\t\thand, leapTransform,\n\t\t\tSubjectTransform)\n\t\t\t);\n\t\t//for (const auto& itm : pFrame->Objects)\n\t\t//{\n\t\t//\tconst auto& pObj = itm.second;\n\t\t//\tif (!pObj->GetBulletRigid()->isStaticOrKinematicObject())\n\t\t//\t{\n\t\t//\t\tfor (const auto& bone : subjects[hand.id()]->Rigids())\n\t\t//\t\t\tpObj->GetBulletRigid()->setIgnoreCollisionCheck(bone.get(), false);\n\t\t//\t}\n\t\t//}\n\t}\n}\n\nvoid Causality::WorldBranch::AddDynamicObject(const std::string &name, const std::shared_ptr<btCollisionShape> &pShape, float mass, const DirectX::Vector3 & Position, const DirectX::Quaternion & Orientation)\n{\n\tfor (auto& branch : nodes_in_tree())\n\t{\n\t\tauto pObject = std::shared_ptr<PhysicalRigid>(new PhysicalRigid());\n\t\tpObject->InitializePhysics(branch.pDynamicsWorld, pShape, mass, Position, Orientation);\n\t\tpObject->GetBulletRigid()->setFriction(1.0f);\n\t\tpObject->GetBulletRigid()->setDamping(0.8f, 0.9f);\n\t\tpObject->GetBulletRigid()->setRestitution(0.0);\n\t\tbranch.Items[name] = pObject;\n\t}\n}\n\nvoid Causality::WorldBranch::Evolution(float timeStep, const Leap::Frame & frame, const DirectX::Matrix4x4 & leapTransform)\n{\n\tusing namespace cpplinq;\n\tvector<reference_wrapper<WorldBranch>> leaves;\n\n\n\n\t//auto levr = this->leaves();\n\tcopy(this->leaves_begin(), leaves_end(), back_inserter(leaves));\n\n\tauto branchEvolution = [timeStep, &frame, &leapTransform](WorldBranch& branch) {\n\t\tbranch.InternalEvolution(timeStep,frame, leapTransform);\n\t};\n\t//auto branchEvolution = std::bind(&WorldBranch::InternalEvolution, placeholders::_1, frame, leapTransform);\n\n\tif (leaves.size() >= 10)\n\t\tconcurrency::parallel_for_each(leaves.begin(), leaves.end(), branchEvolution);\n\telse\n\t\tfor_each(leaves.begin(), leaves.end(), branchEvolution);\n}\n\nvoid Causality::WorldBranch::Fork(const std::vector<PhysicalRigid*>& focusObjects)\n{\n\t//int i = 0;\n\t//for (const auto& obj : focusObjects)\n\t//{\n\t//\tauto branch = DemandCreate((boost::format(\"%s/%d\") % this->Name % i++).str());\n\t//}\n}\n\nvoid Causality::WorldBranch::Fork(const std::vector<DirectX::AffineTransform>& subjectTransforms)\n{\n\tfor (int i = subjectTransforms.size() - 1; i >= 0; --i)\n\t{\n\t\tconst auto& trans = subjectTransforms[i];\n\t\tauto branch = DemandCreate((boost::format(\"%s/%d\") % this->Name % i).str());\n\t\tbranch->Enable(trans);\n\t\tappend_children_front(branch.release());\n\t\t//branch->SubjectTransform = trans;\n\t}\n}\nstd::unique_ptr<WorldBranch> Causality::WorldBranch::DemandCreate(const string& branchName)\n{\n\tif (!BranchPool.empty())\n\t{\n\t\tauto frame = std::move(BranchPool.front());\n\t\tBranchPool.pop();\n\t\tframe->Name = branchName;\n\t\treturn frame;\n\t}\n\telse\n\t\treturn nullptr;\n}\n\nvoid Causality::WorldBranch::Recycle(std::unique_ptr<WorldBranch>&& pFrame)\n{\n\tpFrame->Reset();\n\tBranchPool.push(std::move(pFrame));\n}\n\n//inline void Causality::SkeletonModel::Render(ID3D11DeviceContext * pContext, DirectX::IEffect * pEffect)\n//{\n//\tg_PrimitiveDrawer.DrawCylinder(Joints[0],Joints[1].Position)\n//}\n", "meta": {"hexsha": "9d09ab5479200b17fcdfacb91a37167835f67963", "size": 49418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Causality/Foregrounds.cpp", "max_stars_repo_name": "ArcEarth/SrInspection", "max_stars_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-13T18:30:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:20:34.000Z", "max_issues_repo_path": "Causality/Foregrounds.cpp", "max_issues_repo_name": "ArcEarth/SrInspection", "max_issues_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Causality/Foregrounds.cpp", "max_forks_repo_name": "ArcEarth/SrInspection", "max_forks_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T14:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-12T16:15:18.000Z", "avg_line_length": 31.9031633312, "max_line_length": 251, "alphanum_fraction": 0.6812295115, "num_tokens": 15560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}}
{"text": "/*\n * Copyright (c) 2017 Peter Conrad, and other contributors.\n *\n * The 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\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#include <boost/test/unit_test.hpp>\n\n#include <graphene/chain/hardfork.hpp>\n\n#include <graphene/chain/market_object.hpp>\n\n#include \"../common/database_fixture.hpp\"\n\nusing namespace graphene::chain;\nusing namespace graphene::chain::test;\n\nBOOST_FIXTURE_TEST_SUITE(market_tests, database_fixture)\n\nBOOST_AUTO_TEST_CASE(issue_338_etc)\n{ try {\n   generate_blocks(HARDFORK_615_TIME); // get around Graphene issue #615 feed expiration bug\n   generate_block();\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n   asset_id_type usd_id = bitusd.id;\n   asset_id_type core_id = core.id;\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));\n   call_order_id_type call3_id = call3.id;\n   transfer(borrower, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // adjust price feed to get call_order into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // This order slightly below the call price will not be matched #606\n   limit_order_id_type sell_low = create_sell_order(seller, bitusd.amount(7), core.amount(59))->id;\n   // This order above the MSSP will not be matched\n   limit_order_id_type sell_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;\n   // This would match but is blocked by sell_low?! #606\n   limit_order_id_type sell_med = create_sell_order(seller, bitusd.amount(7), core.amount(60))->id;\n\n   cancel_limit_order( sell_med(db) );\n   cancel_limit_order( sell_high(db) );\n   cancel_limit_order( sell_low(db) );\n\n   // current implementation: an incoming limit order will be filled at the\n   // requested price #338\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(7), core.amount(60)) );\n   BOOST_CHECK_EQUAL( 993, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 60, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 993, call.debt.value );\n   BOOST_CHECK_EQUAL( 14940, call.collateral.value );\n\n   limit_order_id_type buy_low = create_sell_order(buyer, asset(90), bitusd.amount(10))->id;\n   // margin call takes precedence\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(7), core.amount(60)) );\n   BOOST_CHECK_EQUAL( 986, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 120, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 986, call.debt.value );\n   BOOST_CHECK_EQUAL( 14880, call.collateral.value );\n\n   limit_order_id_type buy_med = create_sell_order(buyer, asset(105), bitusd.amount(10))->id;\n   // margin call takes precedence\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(7), core.amount(70)) );\n   BOOST_CHECK_EQUAL( 979, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 190, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 979, call.debt.value );\n   BOOST_CHECK_EQUAL( 14810, call.collateral.value );\n\n   limit_order_id_type buy_high = create_sell_order(buyer, asset(115), bitusd.amount(10))->id;\n   // margin call still has precedence (!) #625\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(7), core.amount(77)) );\n   BOOST_CHECK_EQUAL( 972, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 267, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 972, call.debt.value );\n   BOOST_CHECK_EQUAL( 14733, call.collateral.value );\n\n   cancel_limit_order( buy_high(db) );\n   cancel_limit_order( buy_med(db) );\n   cancel_limit_order( buy_low(db) );\n\n   // call with more usd\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700), core.amount(7700)) );\n   BOOST_CHECK_EQUAL( 272, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 7967, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 272, call.debt.value );\n   BOOST_CHECK_EQUAL( 7033, call.collateral.value );\n\n   // at this moment, collateralization of call is 7033 / 272 = 25.8\n   // collateralization of call2 is 15500 / 1000 = 15.5\n   // collateralization of call3 is 16000 / 1000 = 16\n\n   // call more, still matches with the first call order #343\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(10), core.amount(110)) );\n   BOOST_CHECK_EQUAL( 262, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 8077, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 262, call.debt.value );\n   BOOST_CHECK_EQUAL( 6923, call.collateral.value );\n\n   // at this moment, collateralization of call is 6923 / 262 = 26.4\n   // collateralization of call2 is 15500 / 1000 = 15.5\n   // collateralization of call3 is 16000 / 1000 = 16\n\n   // force settle\n   force_settle( seller, bitusd.amount(10) );\n   BOOST_CHECK_EQUAL( 252, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 8077, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 262, call.debt.value );\n   BOOST_CHECK_EQUAL( 6923, call.collateral.value );\n\n   // generate blocks to let the settle order execute (price feed will expire after it)\n   generate_blocks( HARDFORK_615_TIME + fc::hours(25) );\n   // call2 get settled #343\n   BOOST_CHECK_EQUAL( 252, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 8177, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 262, call_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 6923, call_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 990, call2_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 15400, call2_id(db).collateral.value );\n\n   set_expiration( db, trx );\n   update_feed_producers( usd_id(db), {feedproducer_id} );\n\n   // at this moment, collateralization of call is 8177 / 252 = 32.4\n   // collateralization of call2 is 15400 / 990 = 15.5\n   // collateralization of call3 is 16000 / 1000 = 16\n\n   // adjust price feed to get call2 into black swan territory, but not the first call order\n   current_feed.settlement_price = asset(1, usd_id) / asset(20, core_id);\n   publish_feed( usd_id(db), feedproducer_id(db), current_feed );\n   // settlement price = 1/20, mssp = 1/22\n\n   // black swan event doesn't occur #649\n   BOOST_CHECK( !usd_id(db).bitasset_data(db).has_settlement() );\n\n   // generate a block\n   generate_block();\n\n   set_expiration( db, trx );\n   update_feed_producers( usd_id(db), {feedproducer_id} );\n\n   // adjust price feed back\n   current_feed.settlement_price = asset(1, usd_id) / asset(10, core_id);\n   publish_feed( usd_id(db), feedproducer_id(db), current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   transfer(borrower2_id, seller_id, asset(1000, usd_id));\n   transfer(borrower3_id, seller_id, asset(1000, usd_id));\n\n   // Re-create sell_low, slightly below the call price, will not be matched, will expire soon\n   sell_low = create_sell_order(seller_id(db), asset(7, usd_id), asset(59), db.head_block_time()+fc::seconds(300) )->id;\n   // This would match but is blocked by sell_low, it has an amount same as call's debt which will be full filled later\n   sell_med = create_sell_order(seller_id(db), asset(262, usd_id), asset(2620))->id; // 1/10\n   // Another big order above sell_med, blocked\n   limit_order_id_type sell_med2 = create_sell_order(seller_id(db), asset(1200, usd_id), asset(12120))->id; // 1/10.1\n   // Another small order above sell_med2, blocked\n   limit_order_id_type sell_med3 = create_sell_order(seller_id(db), asset(120, usd_id), asset(1224))->id; // 1/10.2\n\n   // generate a block, sell_low will expire\n   BOOST_TEST_MESSAGE( \"Expire sell_low\" );\n   generate_blocks( HARDFORK_615_TIME + fc::hours(26) );\n   BOOST_CHECK( db.find<limit_order_object>( sell_low ) == nullptr );\n\n   // #453 multiple order matching issue occurs\n   BOOST_CHECK( db.find<limit_order_object>( sell_med ) == nullptr ); // sell_med get filled\n   BOOST_CHECK( db.find<limit_order_object>( sell_med2 ) != nullptr ); // sell_med2 is still there\n   BOOST_CHECK( db.find<limit_order_object>( sell_med3 ) == nullptr ); // sell_med3 get filled\n   BOOST_CHECK( db.find<call_order_object>( call_id ) == nullptr ); // the first call order get filled\n   BOOST_CHECK( db.find<call_order_object>( call2_id ) == nullptr ); // the second call order get filled\n   BOOST_CHECK( db.find<call_order_object>( call3_id ) != nullptr ); // the third call order is still there\n\n\n} FC_LOG_AND_RETHROW() }\n\nBOOST_AUTO_TEST_CASE(hardfork_core_338_test)\n{ try {\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_343_TIME - mi); // assume all hard forks occur at same time\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n   asset_id_type usd_id = bitusd.id;\n   asset_id_type core_id = core.id;\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));\n   call_order_id_type call3_id = call3.id;\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // adjust price feed to get call_order into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // This sell order above MSSP will not be matched with a call\n   create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;\n\n   BOOST_CHECK_EQUAL( 2993, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // This buy order is too low will not be matched with a sell order\n   limit_order_id_type buy_low = create_sell_order(buyer, asset(90), bitusd.amount(10))->id;\n   // This buy order at MSSP will be matched only if no margin call (margin call takes precedence)\n   limit_order_id_type buy_med = create_sell_order(buyer, asset(110), bitusd.amount(10))->id;\n   // This buy order above MSSP will be matched with a sell order (limit order with better price takes precedence)\n   limit_order_id_type buy_high = create_sell_order(buyer, asset(111), bitusd.amount(10))->id;\n\n   BOOST_CHECK_EQUAL( 0, get_balance(buyer, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 90 - 110 - 111, get_balance(buyer, core) );\n\n   // This order slightly below the call price will be matched: #606 fixed\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700), core.amount(5900) ) );\n\n   // firstly it will match with buy_high, at buy_high's price: #625 fixed\n   BOOST_CHECK( !db.find<limit_order_object>( buy_high ) );\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_med )->for_sale.value, 110 );\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 90 );\n\n   // buy_high pays 111 CORE, receives 10 USD goes to buyer's balance\n   BOOST_CHECK_EQUAL( 10, get_balance(buyer, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 90 - 110 - 111, get_balance(buyer, core) );\n   // sell order pays 10 USD, receives 111 CORE, remaining 690 USD for sale, still at price 7/59\n\n   // then it will match with call, at mssp: 1/11 = 690/7590 : #338 fixed\n   BOOST_CHECK_EQUAL( 2293, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 7701, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 310, call.debt.value );\n   BOOST_CHECK_EQUAL( 7410, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call3.collateral.value );\n\n   // call's call_price will be updated after the match, to 741/31/1.75 CORE/USD = 2964/217\n   // it's above settlement price (10/1) so won't be margin called again\n   BOOST_CHECK( price(asset(2964),asset(217,usd_id)) == call.call_price );\n\n   // This would match with call before, but would match with call2 after #343 fixed\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700), core.amount(6000) ) );\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_med )->for_sale.value, 110 );\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 90 );\n\n   // fill price would be mssp: 1/11 = 700/7700 : #338 fixed\n   BOOST_CHECK_EQUAL( 1593, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 15401, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 310, call.debt.value );\n   BOOST_CHECK_EQUAL( 7410, call.collateral.value );\n   BOOST_CHECK_EQUAL( 300, call2.debt.value );\n   BOOST_CHECK_EQUAL( 7800, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call3.collateral.value );\n   // call2's call_price will be updated after the match, to 78/3/1.75 CORE/USD = 312/21\n   BOOST_CHECK( price(asset(312),asset(21,usd_id)) == call2.call_price );\n   // it's above settlement price (10/1) so won't be margin called\n\n   // at this moment, collateralization of call is 7410 / 310 = 23.9\n   // collateralization of call2 is 7800 / 300 = 26\n   // collateralization of call3 is 16000 / 1000 = 16\n\n   // force settle\n   force_settle( seller, bitusd.amount(10) );\n\n   BOOST_CHECK_EQUAL( 1583, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 15401, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 310, call.debt.value );\n   BOOST_CHECK_EQUAL( 7410, call.collateral.value );\n   BOOST_CHECK_EQUAL( 300, call2.debt.value );\n   BOOST_CHECK_EQUAL( 7800, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call3.collateral.value );\n\n   // generate blocks to let the settle order execute (price feed will expire after it)\n   generate_block();\n   generate_blocks( db.head_block_time() + fc::hours(24) );\n\n   // call3 get settled, at settlement price 1/10: #343 fixed\n   BOOST_CHECK_EQUAL( 1583, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 15501, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 310, call_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 7410, call_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 300, call2_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 7800, call2_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 990, call3_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 15900, call3_id(db).collateral.value );\n\n   set_expiration( db, trx );\n   update_feed_producers( usd_id(db), {feedproducer_id} );\n\n   // at this moment, collateralization of call is 7410 / 310 = 23.9\n   // collateralization of call2 is 7800 / 300 = 26\n   // collateralization of call3 is 15900 / 990 = 16.06\n\n   // adjust price feed to get call3 into black swan territory, but not the other call orders\n   // Note: after hard fork, black swan should occur when callateralization < mssp, but not at < feed\n   current_feed.settlement_price = asset(1, usd_id) / asset(16, core_id);\n   publish_feed( usd_id(db), feedproducer_id(db), current_feed );\n   // settlement price = 1/16, mssp = 10/176\n\n   // black swan event will occur: #649 fixed\n   BOOST_CHECK( usd_id(db).bitasset_data(db).has_settlement() );\n   // short positions will be closed\n   BOOST_CHECK( !db.find<call_order_object>( call_id ) );\n   BOOST_CHECK( !db.find<call_order_object>( call2_id ) );\n   BOOST_CHECK( !db.find<call_order_object>( call3_id ) );\n\n   // generate a block\n   generate_block();\n\n\n} FC_LOG_AND_RETHROW() }\n\nBOOST_AUTO_TEST_CASE(hardfork_core_453_test)\n{ try {\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_453_TIME - mi); // assume all hard forks occur at same time\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n   asset_id_type usd_id = bitusd.id;\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));\n   call_order_id_type call3_id = call3.id;\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // no margin call so far\n\n   // This order would match call when it's margin called, it has an amount same as call's debt which will be full filled later\n   limit_order_id_type sell_med = create_sell_order(seller_id(db), asset(1000, usd_id), asset(10000))->id; // 1/10\n   // Another big order above sell_med, amount bigger than call2's debt\n   limit_order_id_type sell_med2 = create_sell_order(seller_id(db), asset(1200, usd_id), asset(12120))->id; // 1/10.1\n   // Another small order above sell_med2\n   limit_order_id_type sell_med3 = create_sell_order(seller_id(db), asset(120, usd_id), asset(1224))->id; // 1/10.2\n\n   // adjust price feed to get the call orders  into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // Fixed #453 multiple order matching issue occurs\n   BOOST_CHECK( !db.find<limit_order_object>( sell_med ) ); // sell_med get filled\n   BOOST_CHECK( !db.find<limit_order_object>( sell_med2 ) ); // sell_med2 get filled\n   BOOST_CHECK( !db.find<limit_order_object>( sell_med3 ) ); // sell_med3 get filled\n   BOOST_CHECK( !db.find<call_order_object>( call_id ) ); // the first call order get filled\n   BOOST_CHECK( !db.find<call_order_object>( call2_id ) ); // the second call order get filled\n   BOOST_CHECK( db.find<call_order_object>( call3_id ) ); // the third call order is still there\n\n   // generate a block\n   generate_block();\n\n\n} FC_LOG_AND_RETHROW() }\n\n/***\n * Tests (big) limit order matching logic after #625 got fixed\n */\nBOOST_AUTO_TEST_CASE(hardfork_core_625_big_limit_order_test)\n{ try {\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_625_TIME - mi); // assume all hard forks occur at same time\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(buyer2)(buyer3)(seller)(borrower)(borrower2)(borrower3)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, buyer2_id, asset(init_balance));\n   transfer(committee_account, buyer3_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 500% collateral, call price is 25/1.75 CORE/USD = 100/7\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(25000));\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 25000, call3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );\n   BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );\n   BOOST_CHECK_EQUAL( init_balance - 25000, get_balance(borrower3, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower3, bitusd) );\n\n   // adjust price feed to get call and call2 (but not call3) into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // This sell order above MSSP will not be matched with a call\n   limit_order_id_type sell_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_high )->for_sale.value, 7 );\n\n   BOOST_CHECK_EQUAL( 2993, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // This buy order is too low will not be matched with a sell order\n   limit_order_id_type buy_low = create_sell_order(buyer, asset(80), bitusd.amount(10))->id;\n   // This buy order at MSSP will be matched only if no margin call (margin call takes precedence)\n   limit_order_id_type buy_med = create_sell_order(buyer2, asset(11000), bitusd.amount(1000))->id;\n   // This buy order above MSSP will be matched with a sell order (limit order with better price takes precedence)\n   limit_order_id_type buy_high = create_sell_order(buyer3, asset(111), bitusd.amount(10))->id;\n\n   BOOST_CHECK_EQUAL( 0, get_balance(buyer, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(buyer2, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(buyer3, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 80, get_balance(buyer, core) );\n   BOOST_CHECK_EQUAL( init_balance - 11000, get_balance(buyer2, core) );\n   BOOST_CHECK_EQUAL( init_balance - 111, get_balance(buyer3, core) );\n\n   // Create a big sell order slightly below the call price, will be matched with several orders\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700*4), core.amount(5900*4) ) );\n\n   // firstly it will match with buy_high, at buy_high's price\n   BOOST_CHECK( !db.find<limit_order_object>( buy_high ) );\n   // buy_high pays 111 CORE, receives 10 USD goes to buyer3's balance\n   BOOST_CHECK_EQUAL( 10, get_balance(buyer3, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 111, get_balance(buyer3, core) );\n\n   // then it will match with call, at mssp: 1/11 = 1000/11000\n   BOOST_CHECK( !db.find<call_order_object>( call_id ) );\n   // call pays 11000 CORE, receives 1000 USD to cover borrower's position, remaining CORE goes to borrower's balance\n   BOOST_CHECK_EQUAL( init_balance - 11000, get_balance(borrower, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );\n\n   // then it will match with call2, at mssp: 1/11 = 1000/11000\n   BOOST_CHECK( !db.find<call_order_object>( call2_id ) );\n   // call2 pays 11000 CORE, receives 1000 USD to cover borrower2's position, remaining CORE goes to borrower2's balance\n   BOOST_CHECK_EQUAL( init_balance - 11000, get_balance(borrower2, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );\n\n   // then it will match with buy_med, at buy_med's price. Since buy_med is too big, it's partially filled.\n   // buy_med receives the remaining USD of sell order, minus market fees, goes to buyer2's balance\n   BOOST_CHECK_EQUAL( 783, get_balance(buyer2, bitusd) ); // 700*4-10-1000-1000=790, minus 1% market fee 790*100/10000=7\n   BOOST_CHECK_EQUAL( init_balance - 11000, get_balance(buyer2, core) );\n   // buy_med pays at 1/11 = 790/8690\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_med )->for_sale.value, 11000-8690 );\n\n   // call3 is not in margin call territory so won't be matched\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 25000, call3.collateral.value );\n\n   // buy_low's price is too low that won't be matched\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );\n\n   // check seller balance\n   BOOST_CHECK_EQUAL( 193, get_balance(seller, bitusd) ); // 3000 - 7 - 700*4\n   BOOST_CHECK_EQUAL( 30801, get_balance(seller, core) ); // 111 + 11000 + 11000 + 8690\n\n   // Cancel buy_med\n   cancel_limit_order( buy_med(db) );\n   BOOST_CHECK( !db.find<limit_order_object>( buy_med ) );\n   BOOST_CHECK_EQUAL( 783, get_balance(buyer2, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 8690, get_balance(buyer2, core) );\n\n   // Create another sell order slightly below the call price, won't fill\n   limit_order_id_type sell_med = create_sell_order( seller, bitusd.amount(7), core.amount(59) )->id;\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_med )->for_sale.value, 7 );\n   // check seller balance\n   BOOST_CHECK_EQUAL( 193-7, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 30801, get_balance(seller, core) );\n\n   // call3 is not in margin call territory so won't be matched\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 25000, call3.collateral.value );\n\n   // buy_low's price is too low that won't be matched\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );\n\n   // generate a block\n   generate_block();\n\n} FC_LOG_AND_RETHROW() }\n\nBOOST_AUTO_TEST_CASE(hard_fork_453_cross_test)\n{ try { // create orders before hard fork, which will be matched on hard fork\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_453_TIME - mi); // assume all hard forks occur at same time\n   generate_block();\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& biteur = create_bitasset(\"EURBIT\", feedproducer_id);\n   const auto& bitcny = create_bitasset(\"CNYBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n   asset_id_type usd_id = bitusd.id;\n   asset_id_type eur_id = biteur.id;\n   asset_id_type cny_id = bitcny.id;\n   asset_id_type core_id = core.id;\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n   update_feed_producers( biteur, {feedproducer.id} );\n   update_feed_producers( bitcny, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   current_feed.settlement_price = biteur.amount( 1 ) / core.amount(5);\n   publish_feed( biteur, feedproducer, current_feed );\n   current_feed.settlement_price = bitcny.amount( 1 ) / core.amount(5);\n   publish_feed( bitcny, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7\n   const call_order_object& call_usd = *borrow( borrower, bitusd.amount(1000), asset(15000));\n   call_order_id_type call_usd_id = call_usd.id;\n   const call_order_object& call_eur = *borrow( borrower, biteur.amount(1000), asset(15000));\n   call_order_id_type call_eur_id = call_eur.id;\n   const call_order_object& call_cny = *borrow( borrower, bitcny.amount(1000), asset(15000));\n   call_order_id_type call_cny_id = call_cny.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7\n   const call_order_object& call_usd2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));\n   call_order_id_type call_usd2_id = call_usd2.id;\n   const call_order_object& call_eur2 = *borrow( borrower2, biteur.amount(1000), asset(15500));\n   call_order_id_type call_eur2_id = call_eur2.id;\n   const call_order_object& call_cny2 = *borrow( borrower2, bitcny.amount(1000), asset(15500));\n   call_order_id_type call_cny2_id = call_cny2.id;\n   // create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7\n   const call_order_object& call_usd3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));\n   call_order_id_type call_usd3_id = call_usd3.id;\n   const call_order_object& call_eur3 = *borrow( borrower3, biteur.amount(1000), asset(16000));\n   call_order_id_type call_eur3_id = call_eur3.id;\n   const call_order_object& call_cny3 = *borrow( borrower3, bitcny.amount(1000), asset(16000));\n   call_order_id_type call_cny3_id = call_cny3.id;\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n   transfer(borrower, seller, biteur.amount(1000));\n   transfer(borrower2, seller, biteur.amount(1000));\n   transfer(borrower3, seller, biteur.amount(1000));\n   transfer(borrower, seller, bitcny.amount(1000));\n   transfer(borrower2, seller, bitcny.amount(1000));\n   transfer(borrower3, seller, bitcny.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call_usd.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call_usd.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call_usd2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call_usd2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call_usd3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call_usd3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 1000, call_eur.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call_eur.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call_eur2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call_eur2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call_eur3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call_eur3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, biteur) );\n   BOOST_CHECK_EQUAL( 1000, call_cny.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call_cny.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call_cny2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call_cny2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call_cny3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call_cny3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitcny) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // adjust price feed to get call_order into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   current_feed.settlement_price = biteur.amount( 1 ) / core.amount(10);\n   publish_feed( biteur, feedproducer, current_feed );\n   current_feed.settlement_price = bitcny.amount( 1 ) / core.amount(10);\n   publish_feed( bitcny, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // This order below the call price will not be matched before hard fork: 1/8 #606\n   limit_order_id_type sell_usd_low = create_sell_order(seller, bitusd.amount(1000), core.amount(7000))->id;\n   // This is a big order, price below the call price will not be matched before hard fork: 1007/9056 = 1/8 #606\n   limit_order_id_type sell_usd_low2 = create_sell_order(seller, bitusd.amount(1007), core.amount(8056))->id;\n   // This order above the MSSP will not be matched before hard fork\n   limit_order_id_type sell_usd_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;\n   // This would match but is blocked by sell_low?! #606\n   limit_order_id_type sell_usd_med = create_sell_order(seller, bitusd.amount(700), core.amount(6400))->id;\n   // This would match but is blocked by sell_low?! #606\n   limit_order_id_type sell_usd_med2 = create_sell_order(seller, bitusd.amount(7), core.amount(65))->id;\n\n   // This order below the call price will not be matched before hard fork: 1/8 #606\n   limit_order_id_type sell_eur_low = create_sell_order(seller, biteur.amount(1000), core.amount(7000))->id;\n   // This is a big order, price below the call price will not be matched before hard fork: 1007/9056 = 1/8 #606\n   limit_order_id_type sell_eur_low2 = create_sell_order(seller, biteur.amount(1007), core.amount(8056))->id;\n   // This order above the MSSP will not be matched before hard fork\n   limit_order_id_type sell_eur_high = create_sell_order(seller, biteur.amount(7), core.amount(78))->id;\n   // This would match but is blocked by sell_low?! #606\n   limit_order_id_type sell_eur_med = create_sell_order(seller, biteur.amount(700), core.amount(6400))->id;\n   // This would match but is blocked by sell_low?! #606\n   limit_order_id_type sell_eur_med2 = create_sell_order(seller, biteur.amount(7), core.amount(65))->id;\n\n   // This order below the call price will not be matched before hard fork: 1/8 #606\n   limit_order_id_type sell_cny_low = create_sell_order(seller, bitcny.amount(1000), core.amount(7000))->id;\n   // This is a big order, price below the call price will not be matched before hard fork: 1007/9056 = 1/8 #606\n   limit_order_id_type sell_cny_low2 = create_sell_order(seller, bitcny.amount(1007), core.amount(8056))->id;\n   // This order above the MSSP will not be matched before hard fork\n   limit_order_id_type sell_cny_high = create_sell_order(seller, bitcny.amount(7), core.amount(78))->id;\n   // This would match but is blocked by sell_low?! #606\n   limit_order_id_type sell_cny_med = create_sell_order(seller, bitcny.amount(700), core.amount(6400))->id;\n   // This would match but is blocked by sell_low?! #606\n   limit_order_id_type sell_cny_med2 = create_sell_order(seller, bitcny.amount(7), core.amount(65))->id;\n\n   BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, eur_id) );\n   BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, cny_id) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // generate a block to include operations above\n   generate_block();\n   // go over the hard fork, make sure feed doesn't expire\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   // sell_low and call should get matched first\n   BOOST_CHECK( !db.find<limit_order_object>( sell_usd_low ) );\n   BOOST_CHECK( !db.find<call_order_object>( call_usd_id ) );\n   // sell_low2 and call2 should get matched\n   BOOST_CHECK( !db.find<call_order_object>( call_usd2_id ) );\n   // sell_low2 and call3 should get matched: fixed #453\n   BOOST_CHECK( !db.find<limit_order_object>( sell_usd_low2 ) );\n   // sell_med and call3 should get matched\n   BOOST_CHECK( !db.find<limit_order_object>( sell_usd_med ) );\n   // call3 now is not at margin call state, so sell_med2 won't get matched\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_usd_med2 )->for_sale.value, 7 );\n   // sell_high should still be there, didn't match anything\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_usd_high )->for_sale.value, 7 );\n\n   // sell_low and call should get matched first\n   BOOST_CHECK( !db.find<limit_order_object>( sell_eur_low ) );\n   BOOST_CHECK( !db.find<call_order_object>( call_eur_id ) );\n   // sell_low2 and call2 should get matched\n   BOOST_CHECK( !db.find<call_order_object>( call_eur2_id ) );\n   // sell_low2 and call3 should get matched: fixed #453\n   BOOST_CHECK( !db.find<limit_order_object>( sell_eur_low2 ) );\n   // sell_med and call3 should get matched\n   BOOST_CHECK( !db.find<limit_order_object>( sell_eur_med ) );\n   // call3 now is not at margin call state, so sell_med2 won't get matched\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_eur_med2 )->for_sale.value, 7 );\n   // sell_high should still be there, didn't match anything\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_eur_high )->for_sale.value, 7 );\n\n   // sell_low and call should get matched first\n   BOOST_CHECK( !db.find<limit_order_object>( sell_cny_low ) );\n   BOOST_CHECK( !db.find<call_order_object>( call_cny_id ) );\n   // sell_low2 and call2 should get matched\n   BOOST_CHECK( !db.find<call_order_object>( call_cny2_id ) );\n   // sell_low2 and call3 should get matched: fixed #453\n   BOOST_CHECK( !db.find<limit_order_object>( sell_cny_low2 ) );\n   // sell_med and call3 should get matched\n   BOOST_CHECK( !db.find<limit_order_object>( sell_cny_med ) );\n   // call3 now is not at margin call state, so sell_med2 won't get matched\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_cny_med2 )->for_sale.value, 7 );\n   // sell_high should still be there, didn't match anything\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_cny_high )->for_sale.value, 7 );\n\n   // all match price would be limit order price\n   BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, eur_id) );\n   BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, cny_id) );\n   BOOST_CHECK_EQUAL( (7000+8056+6400)*3, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 1000-7-700, call_usd3_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 16000-56-6400, call_usd3_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 1000-7-700, call_eur3_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 16000-56-6400, call_eur3_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 1000-7-700, call_cny3_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 16000-56-6400, call_cny3_id(db).collateral.value );\n   // call3's call_price should be updated: 9544/293/1.75 = 9544*4 / 293*7 = 38176/2051 CORE/USD\n   BOOST_CHECK( price(asset(38176),asset(2051,usd_id)) == call_usd3_id(db).call_price );\n   BOOST_CHECK( price(asset(38176),asset(2051,eur_id)) == call_eur3_id(db).call_price );\n   BOOST_CHECK( price(asset(38176),asset(2051,cny_id)) == call_cny3_id(db).call_price );\n\n   generate_block();\n\n} FC_LOG_AND_RETHROW() }\n\nBOOST_AUTO_TEST_CASE(hard_fork_338_cross_test)\n{ try { // create orders before hard fork, which will be matched on hard fork\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_338_TIME - mi); // assume all hard forks occur at same time\n   generate_block();\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(borrower4)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n   asset_id_type usd_id = bitusd.id;\n   asset_id_type core_id = core.id;\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   transfer(committee_account, borrower4_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));\n   call_order_id_type call3_id = call3.id;\n   // create yet another position with 400% collateral, call price is 20/1.75 CORE/USD = 80/7\n   const call_order_object& call4 = *borrow( borrower4, bitusd.amount(1000), asset(20000));\n   call_order_id_type call4_id = call4.id;\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // adjust price feed to get call_order into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // This order below the call price will not be matched before hard fork: 1/8 #606\n   limit_order_id_type sell_low = create_sell_order(seller, bitusd.amount(1000), core.amount(7000))->id;\n   // This is a big order, price below the call price will not be matched before hard fork: 1007/9056 = 1/8 #606\n   limit_order_id_type sell_low2 = create_sell_order(seller, bitusd.amount(1007), core.amount(8056))->id;\n   // This would match but is blocked by sell_low?! #606\n   limit_order_id_type sell_med = create_sell_order(seller, bitusd.amount(7), core.amount(64))->id;\n\n   // adjust price feed to get call_order into black swan territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(16);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/16, mssp = 10/176\n\n   // due to sell_low, black swan won't occur\n   BOOST_CHECK( !usd_id(db).bitasset_data(db).has_settlement() );\n\n   BOOST_CHECK_EQUAL( 3000-1000-1007-7, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // generate a block to include operations above\n   generate_block();\n   // go over the hard fork, make sure feed doesn't expire\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   // sell_low and call should get matched first\n   BOOST_CHECK( !db.find<limit_order_object>( sell_low ) );\n   BOOST_CHECK( !db.find<call_order_object>( call_id ) );\n   // sell_low2 and call2 should get matched\n   BOOST_CHECK( !db.find<call_order_object>( call2_id ) );\n   // sell_low2 and call3 should get matched: fixed #453\n   BOOST_CHECK( !db.find<limit_order_object>( sell_low2 ) );\n   // sell_med and call3 should get matched\n   BOOST_CHECK( !db.find<limit_order_object>( sell_med ) );\n\n   // at this moment,\n   // collateralization of call3 is (16000-56-64) / (1000-7-7) = 15880/986 = 16.1, it's > 16 but < 17.6\n   // although there is no sell order, it should trigger a black swan event right away,\n   // because after hard fork new limit order won't trigger black swan event\n   BOOST_CHECK( usd_id(db).bitasset_data(db).has_settlement() );\n   BOOST_CHECK( !db.find<call_order_object>( call3_id ) );\n   BOOST_CHECK( !db.find<call_order_object>( call4_id ) );\n\n   // since 16.1 > 16, global settlement should at feed price 16/1\n   // so settlement fund should be 986*16 + 1000*16\n   BOOST_CHECK_EQUAL( 1986*16, usd_id(db).bitasset_data(db).settlement_fund.value );\n   // global settlement price should be 16/1, since no rounding here\n   BOOST_CHECK( price(asset(1,usd_id),asset(16) ) == usd_id(db).bitasset_data(db).settlement_price );\n\n   BOOST_CHECK_EQUAL( 3000-1000-1007-7, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 7000+8056+64, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower3_id, usd_id) );\n   BOOST_CHECK_EQUAL( init_balance-16000+15880-986*16, get_balance(borrower3_id, core_id) );\n   BOOST_CHECK_EQUAL( 1000, get_balance(borrower4_id, usd_id) );\n   BOOST_CHECK_EQUAL( init_balance-1000*16, get_balance(borrower4_id, core_id) );\n\n   generate_block();\n\n} FC_LOG_AND_RETHROW() }\n\nBOOST_AUTO_TEST_CASE(hard_fork_649_cross_test)\n{ try { // create orders before hard fork, which will be matched on hard fork\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_343_TIME - mi); // assume all hard forks occur at same time\n   generate_block();\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(borrower4)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n   asset_id_type usd_id = bitusd.id;\n   asset_id_type core_id = core.id;\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   transfer(committee_account, borrower4_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));\n   call_order_id_type call3_id = call3.id;\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 16000, call3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // adjust price feed to get call_order into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // This would match with call at price 707/6464\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(707), core.amount(6464)) );\n   BOOST_CHECK_EQUAL( 3000-707, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 6464, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 293, call.debt.value );\n   BOOST_CHECK_EQUAL( 8536, call.collateral.value );\n\n   // at this moment,\n   // collateralization of call is 8536 / 293 = 29.1\n   // collateralization of call2 is 15500 / 1000 = 15.5\n   // collateralization of call3 is 16000 / 1000 = 16\n\n   generate_block();\n   set_expiration( db, trx );\n   update_feed_producers( usd_id(db), {feedproducer_id} );\n\n   // adjust price feed to get call_order into black swan territory\n   current_feed.settlement_price = price(asset(1,usd_id) / asset(20));\n   publish_feed( usd_id(db), feedproducer_id(db), current_feed );\n   // settlement price = 1/20, mssp = 1/22\n\n   // due to #649, black swan won't occur\n   BOOST_CHECK( !usd_id(db).bitasset_data(db).has_settlement() );\n\n   // generate a block to include operations above\n   generate_block();\n   BOOST_CHECK( !usd_id(db).bitasset_data(db).has_settlement() );\n   // go over the hard fork, make sure feed doesn't expire\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   // a black swan event should occur\n   BOOST_CHECK( usd_id(db).bitasset_data(db).has_settlement() );\n   BOOST_CHECK( !db.find<call_order_object>( call_id ) );\n   BOOST_CHECK( !db.find<call_order_object>( call2_id ) );\n   BOOST_CHECK( !db.find<call_order_object>( call3_id ) );\n\n   // since least collateral ratio 15.5 < 20, global settlement should execute at price = least collateral ratio 15.5/1\n   // so settlement fund should be 15500 + 15500 + round_up(15.5 * 293)\n   BOOST_CHECK_EQUAL( 15500*2 + (293 * 155 + 9) / 10, usd_id(db).bitasset_data(db).settlement_fund.value );\n   // global settlement price should be settlement_fund/(2000+293), but not 15.5/1 due to rounding\n   BOOST_CHECK( price(asset(2293,usd_id),asset(15500*2+(293*155+9)/10) ) == usd_id(db).bitasset_data(db).settlement_price );\n\n   BOOST_CHECK_EQUAL( 3000-707, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 6464, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower_id, usd_id) );\n   BOOST_CHECK_EQUAL( init_balance-6464-(293*155+9)/10, get_balance(borrower_id, core_id) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower2_id, usd_id) );\n   BOOST_CHECK_EQUAL( init_balance-15500, get_balance(borrower2_id, core_id) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower3_id, usd_id) );\n   BOOST_CHECK_EQUAL( init_balance-15500, get_balance(borrower3_id, core_id) );\n\n   generate_block();\n\n} FC_LOG_AND_RETHROW() }\n\nBOOST_AUTO_TEST_CASE(hard_fork_343_cross_test)\n{ try { // create orders before hard fork, which will be matched on hard fork\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_343_TIME - mi); // assume all hard forks occur at same time\n   generate_block();\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(borrower4)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n   asset_id_type usd_id = bitusd.id;\n   asset_id_type core_id = core.id;\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   transfer(committee_account, borrower4_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 350% collateral, call price is 17.5/1.75 CORE/USD = 77/7\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(17500));\n   call_order_id_type call3_id = call3.id;\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 17500, call3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // adjust price feed to get call_order into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // This would match with call at price 700/6400\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700), core.amount(6400)) );\n   BOOST_CHECK_EQUAL( 3000-700, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 6400, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 300, call.debt.value );\n   BOOST_CHECK_EQUAL( 8600, call.collateral.value );\n\n   // at this moment,\n   // collateralization of call is 8600 / 300 = 28.67\n   // collateralization of call2 is 15500 / 1000 = 15.5\n   // collateralization of call3 is 17500 / 1000 = 17.5\n\n   // generate a block to include operations above\n   generate_block();\n   // go over the hard fork, make sure feed doesn't expire\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   set_expiration( db, trx );\n\n   // This will match with call2 at price 7/77 (#343 fixed)\n   BOOST_CHECK( !create_sell_order(seller_id(db), asset(7*50,usd_id), asset(65*50)) );\n   BOOST_CHECK_EQUAL( 3000-700-7*50, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 6400+77*50, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 300, call_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 8600, call_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 1000-7*50, call2_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 15500-77*50, call2_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 17500, call3_id(db).collateral.value );\n\n   // at this moment,\n   // collateralization of call is 8600 / 300 = 28.67\n   // collateralization of call2 is 11650 / 650 = 17.9\n   // collateralization of call3 is 17500 / 1000 = 17.5\n\n   // This will match with call3 at price 7/77 (#343 fixed)\n   BOOST_CHECK( !create_sell_order(seller_id(db), asset(7,usd_id), asset(65)) );\n   BOOST_CHECK_EQUAL( 3000-700-7*50-7, get_balance(seller_id, usd_id) );\n   BOOST_CHECK_EQUAL( 6400+77*50+77, get_balance(seller_id, core_id) );\n   BOOST_CHECK_EQUAL( 300, call_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 8600, call_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 1000-7*50, call2_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 15500-77*50, call2_id(db).collateral.value );\n   BOOST_CHECK_EQUAL( 1000-7, call3_id(db).debt.value );\n   BOOST_CHECK_EQUAL( 17500-77, call3_id(db).collateral.value );\n\n   // at this moment,\n   // collateralization of call is 8600 / 300 = 28.67\n   // collateralization of call2 is 11650 / 650 = 17.9\n   // collateralization of call3 is 17423 / 993 = 17.55\n\n   // no more margin call now\n   BOOST_CHECK( create_sell_order(seller_id(db), asset(7,usd_id), asset(65)) );\n\n   generate_block();\n\n} FC_LOG_AND_RETHROW() }\n\n/***\n * BSIP38 \"target_collateral_ratio\" test: matching a taker limit order with multiple maker call orders\n */\nBOOST_AUTO_TEST_CASE(target_cr_test_limit_call)\n{ try {\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_834_TIME - mi);\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(buyer2)(buyer3)(seller)(borrower)(borrower2)(borrower3)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, buyer2_id, asset(init_balance));\n   transfer(committee_account, buyer3_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7, tcr 170% is lower than 175%\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000), 1700);\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7, tcr 200% is higher than 175%\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500), 2000);\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 500% collateral, call price is 25/1.75 CORE/USD = 100/7, no tcr\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(25000));\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 25000, call3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );\n   BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );\n   BOOST_CHECK_EQUAL( init_balance - 25000, get_balance(borrower3, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower3, bitusd) );\n\n   // adjust price feed to get call and call2 (but not call3) into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // This sell order above MSSP will not be matched with a call\n   limit_order_id_type sell_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_high )->for_sale.value, 7 );\n\n   BOOST_CHECK_EQUAL( 2993, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // This buy order is too low will not be matched with a sell order\n   limit_order_id_type buy_low = create_sell_order(buyer, asset(80), bitusd.amount(10))->id;\n   // This buy order at MSSP will be matched only if no margin call (margin call takes precedence)\n   limit_order_id_type buy_med = create_sell_order(buyer2, asset(33000), bitusd.amount(3000))->id;\n   // This buy order above MSSP will be matched with a sell order (limit order with better price takes precedence)\n   limit_order_id_type buy_high = create_sell_order(buyer3, asset(111), bitusd.amount(10))->id;\n\n   BOOST_CHECK_EQUAL( 0, get_balance(buyer, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(buyer2, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(buyer3, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 80, get_balance(buyer, core) );\n   BOOST_CHECK_EQUAL( init_balance - 33000, get_balance(buyer2, core) );\n   BOOST_CHECK_EQUAL( init_balance - 111, get_balance(buyer3, core) );\n\n   // call and call2's CR is quite high, and debt amount is quite a lot, assume neither of them will be completely filled\n   price match_price( bitusd.amount(1) / core.amount(11) );\n   share_type call_to_cover = call_id(db).get_max_debt_to_cover(match_price,current_feed.settlement_price,1750);\n   share_type call2_to_cover = call2_id(db).get_max_debt_to_cover(match_price,current_feed.settlement_price,1750);\n   BOOST_CHECK_LT( call_to_cover.value, call_id(db).debt.value );\n   BOOST_CHECK_LT( call2_to_cover.value, call2_id(db).debt.value );\n   // even though call2 has a higher CR, since call's TCR is less than call2's TCR, so we expect call will cover less when called\n   BOOST_CHECK_LT( call_to_cover.value, call2_to_cover.value );\n\n   // Create a big sell order slightly below the call price, will be matched with several orders\n   BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700*4), core.amount(5900*4) ) );\n\n   // firstly it will match with buy_high, at buy_high's price\n   BOOST_CHECK( !db.find<limit_order_object>( buy_high ) );\n   // buy_high pays 111 CORE, receives 10 USD goes to buyer3's balance\n   BOOST_CHECK_EQUAL( 10, get_balance(buyer3, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 111, get_balance(buyer3, core) );\n\n   // then it will match with call, at mssp: 1/11 = 1000/11000\n   const call_order_object* tmp_call = db.find<call_order_object>( call_id );\n   BOOST_CHECK( tmp_call != nullptr );\n\n   // call will receive call_to_cover, pay 11*call_to_cover\n   share_type call_to_pay = call_to_cover * 11;\n   BOOST_CHECK_EQUAL( 1000 - call_to_cover.value, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000 - call_to_pay.value, call.collateral.value );\n   // new collateral ratio should be higher than mcr as well as tcr\n   BOOST_CHECK( call.debt.value * 10 * 1750 < call.collateral.value * 1000 );\n   idump( (call) );\n   // borrower's balance doesn't change\n   BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );\n\n   // the limit order then will match with call2, at mssp: 1/11 = 1000/11000\n   const call_order_object* tmp_call2 = db.find<call_order_object>( call2_id );\n   BOOST_CHECK( tmp_call2 != nullptr );\n\n   // call2 will receive call2_to_cover, pay 11*call2_to_cover\n   share_type call2_to_pay = call2_to_cover * 11;\n   BOOST_CHECK_EQUAL( 1000 - call2_to_cover.value, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500 - call2_to_pay.value, call2.collateral.value );\n   // new collateral ratio should be higher than mcr as well as tcr\n   BOOST_CHECK( call2.debt.value * 10 * 2000 < call2.collateral.value * 1000 );\n   idump( (call2) );\n   // borrower2's balance doesn't change\n   BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );\n\n   // then it will match with buy_med, at buy_med's price. Since buy_med is too big, it's partially filled.\n   // buy_med receives the remaining USD of sell order, minus market fees, goes to buyer2's balance\n   share_type buy_med_get = 700*4 - 10 - call_to_cover - call2_to_cover;\n   share_type buy_med_pay = buy_med_get * 11; // buy_med pays at 1/11\n   buy_med_get -= (buy_med_get/100); // minus 1% market fee\n   BOOST_CHECK_EQUAL( buy_med_get.value, get_balance(buyer2, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 33000, get_balance(buyer2, core) );\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_med )->for_sale.value, 33000-buy_med_pay.value );\n\n   // call3 is not in margin call territory so won't be matched\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 25000, call3.collateral.value );\n\n   // buy_low's price is too low that won't be matched\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );\n\n   // check seller balance\n   BOOST_CHECK_EQUAL( 193, get_balance(seller, bitusd) ); // 3000 - 7 - 700*4\n   BOOST_CHECK_EQUAL( 30801, get_balance(seller, core) ); // 111 + (700*4-10)*11\n\n   // Cancel buy_med\n   cancel_limit_order( buy_med(db) );\n   BOOST_CHECK( !db.find<limit_order_object>( buy_med ) );\n   BOOST_CHECK_EQUAL( buy_med_get.value, get_balance(buyer2, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - buy_med_pay.value, get_balance(buyer2, core) );\n\n   // Create another sell order slightly below the call price, won't fill\n   limit_order_id_type sell_med = create_sell_order( seller, bitusd.amount(7), core.amount(59) )->id;\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_med )->for_sale.value, 7 );\n   // check seller balance\n   BOOST_CHECK_EQUAL( 193-7, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 30801, get_balance(seller, core) );\n\n   // call3 is not in margin call territory so won't be matched\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 25000, call3.collateral.value );\n\n   // buy_low's price is too low that won't be matched\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );\n\n   // generate a block\n   generate_block();\n\n} FC_LOG_AND_RETHROW() }\n\n/***\n * BSIP38 \"target_collateral_ratio\" test: matching a maker limit order with multiple taker call orders\n */\nBOOST_AUTO_TEST_CASE(target_cr_test_call_limit)\n{ try {\n   auto mi = db.get_global_properties().parameters.maintenance_interval;\n   generate_blocks(HARDFORK_CORE_834_TIME - mi);\n   generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);\n\n   set_expiration( db, trx );\n\n   ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));\n\n   const auto& bitusd = create_bitasset(\"USDBIT\", feedproducer_id);\n   const auto& core   = asset_id_type()(db);\n\n   int64_t init_balance(1000000);\n\n   transfer(committee_account, buyer_id, asset(init_balance));\n   transfer(committee_account, borrower_id, asset(init_balance));\n   transfer(committee_account, borrower2_id, asset(init_balance));\n   transfer(committee_account, borrower3_id, asset(init_balance));\n   update_feed_producers( bitusd, {feedproducer.id} );\n\n   price_feed current_feed;\n   current_feed.maintenance_collateral_ratio = 1750;\n   current_feed.maximum_short_squeeze_ratio = 1100;\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);\n   publish_feed( bitusd, feedproducer, current_feed );\n   // start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7, tcr 170% is lower than 175%\n   const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000), 1700);\n   call_order_id_type call_id = call.id;\n   // create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7, tcr 200% is higher than 175%\n   const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500), 2000);\n   call_order_id_type call2_id = call2.id;\n   // create yet another position with 500% collateral, call price is 25/1.75 CORE/USD = 100/7, no tcr\n   const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(25000));\n   transfer(borrower, seller, bitusd.amount(1000));\n   transfer(borrower2, seller, bitusd.amount(1000));\n   transfer(borrower3, seller, bitusd.amount(1000));\n\n   BOOST_CHECK_EQUAL( 1000, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000, call.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500, call2.collateral.value );\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 25000, call3.collateral.value );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n   BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );\n   BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );\n   BOOST_CHECK_EQUAL( init_balance - 25000, get_balance(borrower3, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower3, bitusd) );\n\n   // This sell order above MSSP will not be matched with a call\n   limit_order_id_type sell_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_high )->for_sale.value, 7 );\n\n   BOOST_CHECK_EQUAL( 2993, get_balance(seller, bitusd) );\n   BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );\n\n   // This buy order is too low will not be matched with a sell order\n   limit_order_id_type buy_low = create_sell_order(buyer, asset(80), bitusd.amount(10))->id;\n\n   BOOST_CHECK_EQUAL( 0, get_balance(buyer, bitusd) );\n   BOOST_CHECK_EQUAL( init_balance - 80, get_balance(buyer, core) );\n\n   // Create a sell order which will be matched with several call orders later, price 1/9\n   limit_order_id_type sell_id = create_sell_order(seller, bitusd.amount(500), core.amount(4500) )->id;\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_id )->for_sale.value, 500 );\n\n   // prepare price feed to get call and call2 (but not call3) into margin call territory\n   current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);\n\n   // call and call2's CR is quite high, and debt amount is quite a lot, assume neither of them will be completely filled\n   price match_price = sell_id(db).sell_price;\n   share_type call_to_cover = call_id(db).get_max_debt_to_cover(match_price,current_feed.settlement_price,1750);\n   share_type call2_to_cover = call2_id(db).get_max_debt_to_cover(match_price,current_feed.settlement_price,1750);\n   BOOST_CHECK_LT( call_to_cover.value, call_id(db).debt.value );\n   BOOST_CHECK_LT( call2_to_cover.value, call2_id(db).debt.value );\n   // even though call2 has a higher CR, since call's TCR is less than call2's TCR, so we expect call will cover less when called\n   BOOST_CHECK_LT( call_to_cover.value, call2_to_cover.value );\n\n   // adjust price feed to get call and call2 (but not call3) into margin call territory\n   publish_feed( bitusd, feedproducer, current_feed );\n   // settlement price = 1/10, mssp = 1/11\n\n   // firstly the limit order will match with call, at limit order's price: 1/9\n   const call_order_object* tmp_call = db.find<call_order_object>( call_id );\n   BOOST_CHECK( tmp_call != nullptr );\n\n   // call will receive call_to_cover, pay 9*call_to_cover\n   share_type call_to_pay = call_to_cover * 9;\n   BOOST_CHECK_EQUAL( 1000 - call_to_cover.value, call.debt.value );\n   BOOST_CHECK_EQUAL( 15000 - call_to_pay.value, call.collateral.value );\n   // new collateral ratio should be higher than mcr as well as tcr\n   BOOST_CHECK( call.debt.value * 10 * 1750 < call.collateral.value * 1000 );\n   idump( (call) );\n   // borrower's balance doesn't change\n   BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );\n\n   // the limit order then will match with call2, at limit order's price: 1/9\n   const call_order_object* tmp_call2 = db.find<call_order_object>( call2_id );\n   BOOST_CHECK( tmp_call2 != nullptr );\n\n   // if the limit is big enough, call2 will receive call2_to_cover, pay 11*call2_to_cover\n   // however it's not the case, so call2 will receive less\n   call2_to_cover = 500 - call_to_cover;\n   share_type call2_to_pay = call2_to_cover * 9;\n   BOOST_CHECK_EQUAL( 1000 - call2_to_cover.value, call2.debt.value );\n   BOOST_CHECK_EQUAL( 15500 - call2_to_pay.value, call2.collateral.value );\n   idump( (call2) );\n   // borrower2's balance doesn't change\n   BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );\n   BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );\n\n   // call3 is not in margin call territory so won't be matched\n   BOOST_CHECK_EQUAL( 1000, call3.debt.value );\n   BOOST_CHECK_EQUAL( 25000, call3.collateral.value );\n\n   // sell_id is completely filled\n   BOOST_CHECK( !db.find<limit_order_object>( sell_id ) );\n\n   // check seller balance\n   BOOST_CHECK_EQUAL( 2493, get_balance(seller, bitusd) ); // 3000 - 7 - 500\n   BOOST_CHECK_EQUAL( 4500, get_balance(seller, core) ); // 500*9\n\n   // buy_low's price is too low that won't be matched\n   BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );\n\n   // generate a block\n   generate_block();\n\n} FC_LOG_AND_RETHROW() }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d5021880c4edb8e6d2222ebb2c0f51aa59f90952", "size": 77688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tests/market_tests.cpp", "max_stars_repo_name": "enumivo/eidos-core", "max_stars_repo_head_hexsha": "f614d87a8424253e9c677ef3818b495f5a5e755a", "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/tests/market_tests.cpp", "max_issues_repo_name": "enumivo/eidos-core", "max_issues_repo_head_hexsha": "f614d87a8424253e9c677ef3818b495f5a5e755a", "max_issues_repo_licenses": ["MIT"], "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/tests/market_tests.cpp", "max_forks_repo_name": "enumivo/eidos-core", "max_forks_repo_head_hexsha": "f614d87a8424253e9c677ef3818b495f5a5e755a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.1395973154, "max_line_length": 129, "alphanum_fraction": 0.7387369993, "num_tokens": 22155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255292}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <memory>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/BoundaryConditions/BoundaryCondition.hpp\"\n#include \"Domain/CoordinateMaps/Affine.hpp\"\n#include \"Domain/CoordinateMaps/CoordinateMap.hpp\"\n#include \"Domain/CoordinateMaps/CoordinateMap.tpp\"\n#include \"Domain/CoordinateMaps/ProductMaps.hpp\"\n#include \"Domain/CoordinateMaps/ProductMaps.tpp\"\n#include \"Domain/Creators/AlignedLattice.hpp\"\n#include \"Domain/Creators/DomainCreator.hpp\"\n#include \"Domain/Domain.hpp\"\n#include \"Domain/OptionTags.hpp\"\n#include \"Framework/TestCreation.hpp\"\n#include \"Framework/TestHelpers.hpp\"\n#include \"Helpers/Domain/BoundaryConditions/BoundaryCondition.hpp\"\n#include \"Helpers/Domain/DomainTestHelpers.hpp\"\n#include \"Parallel/RegisterDerivedClassesWithCharm.hpp\"\n\nnamespace Frame {\nstruct Inertial;\n}  // namespace Frame\n\nnamespace domain {\nnamespace {\ntemplate <size_t VolumeDim>\nstd::unique_ptr<domain::BoundaryConditions::BoundaryCondition>\ncreate_boundary_condition() {\n  return std::make_unique<TestHelpers::domain::BoundaryConditions::\n                              TestBoundaryCondition<VolumeDim>>(\n      Direction<VolumeDim>::upper_xi(), 100);\n}\n\ntemplate <size_t VolumeDim>\nvoid test_aligned_blocks(\n    const creators::AlignedLattice<VolumeDim>& aligned_lattice,\n    const std::unique_ptr<domain::BoundaryConditions::BoundaryCondition>&\n        expected_boundary_condition) {\n  Parallel::register_classes_with_charm(\n      typename creators::AlignedLattice<VolumeDim>::maps_list{});\n\n  const auto test_impl = [&expected_boundary_condition,\n                          &aligned_lattice](const auto& domain) {\n    test_initial_domain(domain, aligned_lattice.initial_refinement_levels());\n\n    if (expected_boundary_condition != nullptr) {\n      const auto& blocks = domain.blocks();\n      for (size_t block_id = 0; block_id < blocks.size(); ++block_id) {\n        CAPTURE(block_id);\n        const auto& block = domain.blocks()[block_id];\n        REQUIRE(block.external_boundaries().size() ==\n                block.external_boundary_conditions().size());\n        for (const auto& direction : block.external_boundaries()) {\n          CAPTURE(direction);\n          REQUIRE(block.external_boundary_conditions().count(direction) == 1);\n          REQUIRE(block.external_boundary_conditions().at(direction) !=\n                  nullptr);\n          const auto& bc =\n              dynamic_cast<const TestHelpers::domain::BoundaryConditions::\n                               TestBoundaryCondition<VolumeDim>&>(\n                  *block.external_boundary_conditions().at(direction));\n          const auto& expected_bc =\n              dynamic_cast<const TestHelpers::domain::BoundaryConditions::\n                               TestBoundaryCondition<VolumeDim>&>(\n                  *expected_boundary_condition);\n          CHECK(bc.direction() == expected_bc.direction());\n          CHECK(bc.block_id() == expected_bc.block_id());\n        }\n      }\n    }\n  };\n\n  test_impl(aligned_lattice.create_domain());\n  test_impl(serialize_and_deserialize(aligned_lattice.create_domain()));\n}\n\ntemplate <size_t VolumeDim>\nauto make_domain_creator(const std::string& opt_string,\n                         const bool use_boundary_condition) {\n  if (use_boundary_condition) {\n    return TestHelpers::test_option_tag<\n        domain::OptionTags::DomainCreator<VolumeDim>,\n        TestHelpers::domain::BoundaryConditions::\n            MetavariablesWithBoundaryConditions<\n                VolumeDim, domain::creators::AlignedLattice<VolumeDim>>>(\n        opt_string + std::string{\"  BoundaryCondition:\\n\"\n                                 \"    TestBoundaryCondition:\\n\"\n                                 \"      Direction: upper-xi\\n\"\n                                 \"      BlockId: 100\\n\"});\n  } else {\n    return TestHelpers::test_option_tag<\n        domain::OptionTags::DomainCreator<VolumeDim>,\n        TestHelpers::domain::BoundaryConditions::\n            MetavariablesWithoutBoundaryConditions<\n                VolumeDim, domain::creators::AlignedLattice<VolumeDim>>>(\n        opt_string);\n  }\n}\n}  // namespace\n\nSPECTRE_TEST_CASE(\"Unit.Domain.Creators.AlignedLattice\", \"[Domain][Unit]\") {\n  TestHelpers::domain::BoundaryConditions::register_derived_with_charm();\n\n  for (const bool use_boundary_condition : {true, false}) {\n    const std::unique_ptr<domain::BoundaryConditions::BoundaryCondition>\n        expected_boundary_condition_1d =\n            use_boundary_condition ? create_boundary_condition<1>() : nullptr;\n    const std::unique_ptr<domain::BoundaryConditions::BoundaryCondition>\n        expected_boundary_condition_2d =\n            use_boundary_condition ? create_boundary_condition<2>() : nullptr;\n    const std::unique_ptr<domain::BoundaryConditions::BoundaryCondition>\n        expected_boundary_condition_3d =\n            use_boundary_condition ? create_boundary_condition<3>() : nullptr;\n\n    const auto domain_creator_1d = make_domain_creator<1>(\n        \"AlignedLattice:\\n\"\n        \"  BlockBounds: [[0.1, 2.6, 5.1, 5.2, 7.2]]\\n\" +\n            std::string{use_boundary_condition ? \"\"\n                                               : \"  IsPeriodicIn: [false]\\n\"} +\n            \"  InitialGridPoints: [3]\\n\"\n            \"  InitialLevels: [2]\\n\"\n            \"  RefinedLevels: []\\n\"\n            \"  RefinedGridPoints: []\\n\"\n            \"  BlocksToExclude: []\\n\",\n        use_boundary_condition);\n    const auto* aligned_blocks_creator_1d =\n        dynamic_cast<const creators::AlignedLattice<1>*>(\n            domain_creator_1d.get());\n    test_aligned_blocks(*aligned_blocks_creator_1d,\n                        expected_boundary_condition_1d);\n\n    const auto domain_creator_2d = make_domain_creator<2>(\n        \"AlignedLattice:\\n\"\n        \"  BlockBounds: [[0.1, 2.6, 5.1], [-0.4, 3.2, 6.2, 8.9]]\\n\" +\n            std::string{use_boundary_condition\n                            ? \"\"\n                            : \"  IsPeriodicIn: [false, false]\\n\"} +\n            \"  InitialGridPoints: [3, 4]\\n\"\n            \"  InitialLevels: [2, 1]\\n\"\n            \"  RefinedLevels: []\\n\"\n            \"  RefinedGridPoints: []\\n\"\n            \"  BlocksToExclude: []\\n\",\n        use_boundary_condition);\n    const auto* aligned_blocks_creator_2d =\n        dynamic_cast<const creators::AlignedLattice<2>*>(\n            domain_creator_2d.get());\n    test_aligned_blocks(*aligned_blocks_creator_2d,\n                        expected_boundary_condition_2d);\n\n    const auto domain_creator_3d = make_domain_creator<3>(\n        \"AlignedLattice:\\n\"\n        \"  BlockBounds: [[0.1, 2.6, 5.1], [-0.4, 3.2, 6.2], [-0.2, 3.2]]\\n\" +\n            std::string{use_boundary_condition\n                            ? \"\"\n                            : \"  IsPeriodicIn: [false, false, false]\\n\"} +\n            \"  InitialGridPoints: [3, 4, 5]\\n\"\n            \"  InitialLevels: [2, 1, 0]\\n\"\n            \"  RefinedLevels: []\\n\"\n            \"  RefinedGridPoints: []\\n\"\n            \"  BlocksToExclude: []\\n\",\n        use_boundary_condition);\n    const auto* aligned_blocks_creator_3d =\n        dynamic_cast<const creators::AlignedLattice<3>*>(\n            domain_creator_3d.get());\n    test_aligned_blocks(*aligned_blocks_creator_3d,\n                        expected_boundary_condition_3d);\n\n    const auto cubical_shell_domain = make_domain_creator<3>(\n        \"AlignedLattice:\\n\"\n        \"  BlockBounds: [[0.1, 2.6, 5.1, 6.0], [-0.4, 3.2, 6.2, 7.0], \"\n        \"[-0.2, 3.2, 4.0, 5.2]]\\n\" +\n            std::string{use_boundary_condition\n                            ? \"\"\n                            : \"  IsPeriodicIn: [false, false, false]\\n\"} +\n            \"  InitialGridPoints: [3, 4, 5]\\n\"\n            \"  InitialLevels: [2, 1, 0]\\n\"\n            \"  RefinedLevels: []\\n\"\n            \"  RefinedGridPoints: []\\n\"\n            \"  BlocksToExclude: [[1, 1, 1]]\\n\",\n        use_boundary_condition);\n    const auto* cubical_shell_creator_3d =\n        dynamic_cast<const creators::AlignedLattice<3>*>(\n            cubical_shell_domain.get());\n    test_aligned_blocks(*cubical_shell_creator_3d,\n                        expected_boundary_condition_3d);\n\n    const auto unit_cubical_shell_domain = make_domain_creator<3>(\n        \"AlignedLattice:\\n\"\n        \"  BlockBounds: [[-1.5, -0.5, 0.5, 1.5], [-1.5, -0.5, 0.5, 1.5], \"\n        \"[-1.5, -0.5, 0.5, 1.5]]\\n\" +\n            std::string{use_boundary_condition\n                            ? \"\"\n                            : \"  IsPeriodicIn: [false, false, false]\\n\"} +\n            \"  InitialGridPoints: [5, 5, 5]\\n\"\n            \"  InitialLevels: [1, 1, 1]\\n\"\n            \"  RefinedLevels: []\\n\"\n            \"  RefinedGridPoints: []\\n\"\n            \"  BlocksToExclude: [[1, 1, 1]]\\n\",\n        use_boundary_condition);\n    const auto* unit_cubical_shell_creator_3d =\n        dynamic_cast<const creators::AlignedLattice<3>*>(\n            unit_cubical_shell_domain.get());\n    test_aligned_blocks(*unit_cubical_shell_creator_3d,\n                        expected_boundary_condition_3d);\n  }\n\n  const auto domain_creator_2d_periodic = TestHelpers::test_option_tag<\n      domain::OptionTags::DomainCreator<2>,\n      TestHelpers::domain::BoundaryConditions::\n          MetavariablesWithoutBoundaryConditions<\n              2, domain::creators::AlignedLattice<2>>>(\n      \"AlignedLattice:\\n\"\n      \"  BlockBounds: [[0.1, 2.6, 5.1], [-0.4, 3.2, 6.2, 8.9]]\\n\"\n      \"  IsPeriodicIn: [false, true]\\n\"\n      \"  InitialGridPoints: [3, 4]\\n\"\n      \"  InitialLevels: [2, 1]\\n\"\n      \"  RefinedLevels: []\\n\"\n      \"  RefinedGridPoints: []\\n\"\n      \"  BlocksToExclude: []\\n\");\n  const auto* aligned_blocks_creator_2d_periodic =\n      dynamic_cast<const creators::AlignedLattice<2>*>(\n          domain_creator_2d_periodic.get());\n  test_aligned_blocks(*aligned_blocks_creator_2d_periodic, nullptr);\n\n  const auto domain_creator_3d_periodic = TestHelpers::test_option_tag<\n      domain::OptionTags::DomainCreator<3>,\n      TestHelpers::domain::BoundaryConditions::\n          MetavariablesWithoutBoundaryConditions<\n              3, domain::creators::AlignedLattice<3>>>(\n      \"AlignedLattice:\\n\"\n      \"  BlockBounds: [[0.1, 2.6, 5.1], [-0.4, 3.2, 6.2], [-0.2, 3.2]]\\n\"\n      \"  IsPeriodicIn: [false, true, false]\\n\"\n      \"  InitialGridPoints: [3, 4, 5]\\n\"\n      \"  InitialLevels: [2, 1, 0]\\n\"\n      \"  RefinedLevels: []\\n\"\n      \"  RefinedGridPoints: []\\n\"\n      \"  BlocksToExclude: []\\n\");\n  const auto* aligned_blocks_creator_3d_periodic =\n      dynamic_cast<const creators::AlignedLattice<3>*>(\n          domain_creator_3d_periodic.get());\n  test_aligned_blocks(*aligned_blocks_creator_3d_periodic, nullptr);\n\n  {\n    // Expected domain refinement:\n    // 23 23 67\n    // 23 45 67\n    // 23 XX 45\n    const auto refined_domain = TestHelpers::test_option_tag<\n        domain::OptionTags::DomainCreator<2>,\n        TestHelpers::domain::BoundaryConditions::\n            MetavariablesWithoutBoundaryConditions<\n                2, domain::creators::AlignedLattice<2>>>(\n        \"AlignedLattice:\\n\"\n        \"  BlockBounds: [[70, 71, 72, 73], [90, 91, 92, 93]]\\n\"\n        \"  IsPeriodicIn: [false, false]\\n\"\n        \"  InitialGridPoints: [2, 3]\\n\"\n        \"  InitialLevels: [0, 0]\\n\"\n        \"  BlocksToExclude: [[1, 0]]\\n\"\n        \"  RefinedLevels: []\\n\"\n        \"  RefinedGridPoints:\\n\"\n        \"  - LowerCornerIndex: [1, 0]\\n\"\n        \"    UpperCornerIndex: [3, 2]\\n\"\n        \"    Refinement: [4, 5]\\n\"\n        \"  - LowerCornerIndex: [2, 1]\\n\"\n        \"    UpperCornerIndex: [3, 3]\\n\"\n        \"    Refinement: [6, 7]\");\n    std::unordered_set<\n        std::pair<std::vector<double>, std::array<size_t, 2>>,\n        boost::hash<std::pair<std::vector<double>, std::array<size_t, 2>>>>\n        expected_blocks{{{70.0, 90.0}, {{2, 3}}}, {{72.0, 90.0}, {{4, 5}}},\n                        {{70.0, 91.0}, {{2, 3}}}, {{71.0, 91.0}, {{4, 5}}},\n                        {{72.0, 91.0}, {{6, 7}}}, {{70.0, 92.0}, {{2, 3}}},\n                        {{71.0, 92.0}, {{2, 3}}}, {{72.0, 92.0}, {{6, 7}}}};\n    const auto domain = refined_domain->create_domain();\n    test_initial_domain(domain, refined_domain->initial_refinement_levels());\n\n    const auto& blocks = domain.blocks();\n    const auto extents = refined_domain->initial_extents();\n    REQUIRE(blocks.size() == extents.size());\n    for (size_t i = 0; i < blocks.size(); ++i) {\n      const auto location =\n          blocks[i]\n              .stationary_map()(\n                  tnsr::I<double, 2, Frame::BlockLogical>{{{-1.0, -1.0}}})\n              .get_vector_of_data()\n              .second;\n      INFO(\"Unexpected block\");\n      CAPTURE(location);\n      CAPTURE(extents[i]);\n      CHECK(expected_blocks.erase({location, extents[i]}) == 1);\n    }\n    CAPTURE(expected_blocks);\n    CHECK(expected_blocks.empty());\n  }\n\n  {\n    // Expected domain refinement:\n    // 25 25 46\n    // 25 35 46\n    // 25 XX 35\n    const auto refined_domain = TestHelpers::test_option_tag<\n        domain::OptionTags::DomainCreator<2>,\n        TestHelpers::domain::BoundaryConditions::\n            MetavariablesWithoutBoundaryConditions<\n                2, domain::creators::AlignedLattice<2>>>(\n        \"AlignedLattice:\\n\"\n        \"  BlockBounds: [[70, 71, 72, 73], [90, 91, 92, 93]]\\n\"\n        \"  IsPeriodicIn: [false, false]\\n\"\n        \"  InitialGridPoints: [10, 10]\\n\"\n        \"  InitialLevels: [2, 5]\\n\"\n        \"  BlocksToExclude: [[1, 0]]\\n\"\n        \"  RefinedGridPoints: []\\n\"\n        \"  RefinedLevels:\\n\"\n        \"  - LowerCornerIndex: [1, 0]\\n\"\n        \"    UpperCornerIndex: [3, 2]\\n\"\n        \"    Refinement: [3, 5]\\n\"\n        \"  - LowerCornerIndex: [2, 1]\\n\"\n        \"    UpperCornerIndex: [3, 3]\\n\"\n        \"    Refinement: [4, 6]\");\n    std::unordered_set<\n        std::pair<std::vector<double>, std::array<size_t, 2>>,\n        boost::hash<std::pair<std::vector<double>, std::array<size_t, 2>>>>\n        expected_blocks{{{70.0, 90.0}, {{2, 5}}}, {{72.0, 90.0}, {{3, 5}}},\n                        {{70.0, 91.0}, {{2, 5}}}, {{71.0, 91.0}, {{3, 5}}},\n                        {{72.0, 91.0}, {{4, 6}}}, {{70.0, 92.0}, {{2, 5}}},\n                        {{71.0, 92.0}, {{2, 5}}}, {{72.0, 92.0}, {{4, 6}}}};\n    const auto domain = refined_domain->create_domain();\n    const auto refinement_levels = refined_domain->initial_refinement_levels();\n    test_initial_domain(domain, refinement_levels);\n\n    const auto& blocks = domain.blocks();\n    REQUIRE(blocks.size() == refinement_levels.size());\n    for (size_t i = 0; i < blocks.size(); ++i) {\n      const auto location =\n          blocks[i]\n              .stationary_map()(\n                  tnsr::I<double, 2, Frame::BlockLogical>{{{-1.0, -1.0}}})\n              .get_vector_of_data()\n              .second;\n      INFO(\"Unexpected block\");\n      CAPTURE(location);\n      CAPTURE(refinement_levels[i]);\n      CHECK(expected_blocks.erase({location, refinement_levels[i]}) == 1);\n    }\n    CAPTURE(expected_blocks);\n    CHECK(expected_blocks.empty());\n  }\n\n  CHECK_THROWS_WITH(\n      creators::AlignedLattice<3>({{{{-1.5, -0.5, 0.5, 1.5}},\n                                    {{1.5, -0.5, 0.5, 1.5}},\n                                    {{-1.5, -0.5, 0.5, 1.5}}}},\n                                  {{1, 1, 1}}, {{5, 5, 5}}, {}, {},\n                                  {{{{1, 1, 1}}}}, {{true, false, false}},\n                                  Options::Context{false, {}, 1, 1}),\n      Catch::Matchers::Contains(\n          \"Cannot exclude blocks as well as have periodic boundary\"));\n  CHECK_THROWS_WITH(\n      creators::AlignedLattice<3>({{{{-1.5, -0.5, 0.5, 1.5}},\n                                    {{1.5, -0.5, 0.5, 1.5}},\n                                    {{-1.5, -0.5, 0.5, 1.5}}}},\n                                  {{1, 1, 1}}, {{5, 5, 5}}, {}, {},\n                                  {{{{1, 1, 1}}}}, {{false, true, false}},\n                                  Options::Context{false, {}, 1, 1}),\n      Catch::Matchers::Contains(\n          \"Cannot exclude blocks as well as have periodic boundary\"));\n  CHECK_THROWS_WITH(\n      creators::AlignedLattice<3>({{{{-1.5, -0.5, 0.5, 1.5}},\n                                    {{1.5, -0.5, 0.5, 1.5}},\n                                    {{-1.5, -0.5, 0.5, 1.5}}}},\n                                  {{1, 1, 1}}, {{5, 5, 5}}, {}, {},\n                                  {{{{1, 1, 1}}}}, {{true, false, true}},\n                                  Options::Context{false, {}, 1, 1}),\n      Catch::Matchers::Contains(\n          \"Cannot exclude blocks as well as have periodic boundary\"));\n  CHECK_THROWS_WITH(\n      creators::AlignedLattice<3>(\n          {{{{-1.5, -0.5, 0.5, 1.5}},\n            {{1.5, -0.5, 0.5, 1.5}},\n            {{-1.5, -0.5, 0.5, 1.5}}}},\n          {{1, 1, 1}}, {{5, 5, 5}}, {}, {}, {{{{1, 1, 1}}}},\n          std::make_unique<TestHelpers::domain::BoundaryConditions::\n                               TestPeriodicBoundaryCondition<3>>(),\n          Options::Context{false, {}, 1, 1}),\n      Catch::Matchers::Contains(\n          \"Cannot exclude blocks as well as have periodic boundary\"));\n  CHECK_THROWS_WITH(\n      creators::AlignedLattice<3>(\n          {{{{-1.5, -0.5, 0.5, 1.5}},\n            {{1.5, -0.5, 0.5, 1.5}},\n            {{-1.5, -0.5, 0.5, 1.5}}}},\n          {{1, 1, 1}}, {{5, 5, 5}}, {}, {}, {{{{1, 1, 1}}}},\n          std::make_unique<TestHelpers::domain::BoundaryConditions::\n                               TestNoneBoundaryCondition<3>>(),\n          Options::Context{false, {}, 1, 1}),\n      Catch::Matchers::Contains(\n          \"None boundary condition is not supported. If you would like an \"\n          \"outflow boundary condition, you must use that.\"));\n}\n}  // namespace domain\n", "meta": {"hexsha": "4b4c9cc040e4553a67e63068de5b275dce2efee2", "size": 17842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Domain/Creators/Test_AlignedLattice.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": "tests/Unit/Domain/Creators/Test_AlignedLattice.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": "tests/Unit/Domain/Creators/Test_AlignedLattice.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": 43.3058252427, "max_line_length": 79, "alphanum_fraction": 0.5636699922, "num_tokens": 4867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255292}}
{"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\n#include <boost/lexical_cast.hpp>\n#include <ored/portfolio/creditdefaultswapdata.hpp>\n#include <ored/portfolio/legdata.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\n\nnamespace ore {\nnamespace data {\n\nvoid CreditDefaultSwapData::fromXML(XMLNode* node) {\n    XMLUtils::checkNode(node, \"CreditDefaultSwapData\");\n    issuerId_ = XMLUtils::getChildValue(node, \"IssuerId\");\n    creditCurveId_ = XMLUtils::getChildValue(node, \"CreditCurveId\", true);\n    settlesAccrual_ = XMLUtils::getChildValueAsBool(node, \"SettlesAccrual\", false);       // default = Y\n    paysAtDefaultTime_ = XMLUtils::getChildValueAsBool(node, \"PaysAtDefaultTime\", false); // default = Y\n    XMLNode* tmp = XMLUtils::getChildNode(node, \"ProtectionStart\");\n    if (tmp)\n        protectionStart_ = parseDate(XMLUtils::getNodeValue(tmp)); // null date if empty or missing\n    else\n        protectionStart_ = Date();\n    tmp = XMLUtils::getChildNode(node, \"UpfrontDate\");\n    if (tmp)\n        upfrontDate_ = parseDate(XMLUtils::getNodeValue(tmp)); // null date if empty or mssing\n    else\n        upfrontDate_ = Date();\n    upfrontFee_ = parseReal(XMLUtils::getChildValue(node, \"UpfrontFee\", false)); // zero if empty or missing\n    if (upfrontDate_ == Date()) {\n        QL_REQUIRE(close_enough(upfrontFee_, 0.0), \"CreditDefaultSwapData::fromXML(): UpfronFee not zero (\"\n                                                       << upfrontFee_ << \"), but no upfront data given\");\n        upfrontFee_ = Null<Real>();\n    }\n    leg_.fromXML(XMLUtils::getChildNode(node, \"LegData\"));\n}\n\nXMLNode* CreditDefaultSwapData::toXML(XMLDocument& doc) {\n    XMLNode* node = doc.allocNode(\"CreditDefaultSwapData\");\n    XMLUtils::addChild(doc, node, \"IssuerId\", issuerId_);\n    XMLUtils::addChild(doc, node, \"CreditCurveId\", creditCurveId_);\n    XMLUtils::addChild(doc, node, \"SettlesAccrual\", settlesAccrual_);\n    XMLUtils::addChild(doc, node, \"PaysAtDefaultTime\", paysAtDefaultTime_);\n    if (protectionStart_ != Date()) {\n        std::ostringstream tmp;\n        tmp << QuantLib::io::iso_date(protectionStart_);\n        XMLUtils::addChild(doc, node, \"ProtectionStart\", tmp.str());\n    }\n    if (upfrontDate_ != Date()) {\n        std::ostringstream tmp;\n        tmp << QuantLib::io::iso_date(upfrontDate_);\n        XMLUtils::addChild(doc, node, \"UpfrontDate\", tmp.str());\n    }\n    if (upfrontFee_ != Null<Real>())\n        XMLUtils::addChild(doc, node, \"UpfrontFee\", upfrontFee_);\n    XMLUtils::appendNode(node, leg_.toXML(doc));\n    return node;\n}\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "66f3ff6ee7f735e12803cdf817bcb7e3eb433f4e", "size": 3368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/portfolio/creditdefaultswapdata.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": "OREData/ored/portfolio/creditdefaultswapdata.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": "OREData/ored/portfolio/creditdefaultswapdata.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": 42.6329113924, "max_line_length": 108, "alphanum_fraction": 0.700415677, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255292}}
{"text": "#include \"qpainterwrapper.h\"\n#include <Eigen/src/Core/Array.h>\n#include <QPainterPath>\n#include <iostream>\n\nQPainterWrapper::QPainterWrapper(Gui::CanvasRenderer *p)\n    : p(p),\n      mTimeStart(0.0),\n      mTimeEnd(5.0),\n      mFrequencyScale(FrequencyScale::Mel),\n      mMinFrequency(60),\n      mMaxFrequency(8000),\n      mMaxGain(0)\n{\n}\n\nQRect QPainterWrapper::viewport() const\n{\n    return p->viewport();\n}\n\nvoid QPainterWrapper::setZoom(double scale)\n{\n    p->setZoomScale(scale);\n}\n\nvoid QPainterWrapper::setTimeRange(double start, double end)\n{\n    mTimeStart = start;\n    mTimeEnd = end;\n}\n\nvoid QPainterWrapper::setFrequencyScale(FrequencyScale scale)\n{\n    mFrequencyScale = scale;\n}\n\nvoid QPainterWrapper::setMinFrequency(double minFrequency)\n{\n    mMinFrequency = minFrequency;\n}\n\nvoid QPainterWrapper::setMaxFrequency(double maxFrequency)\n{\n    mMaxFrequency = maxFrequency;\n}\n\nvoid QPainterWrapper::setMaxGain(double maxGain)\n{\n    mMaxGain = maxGain;\n}\n\ndouble QPainterWrapper::transformFrequency(double frequency)\n{\n    return transformFrequency(frequency, mFrequencyScale);\n}\n\ndouble QPainterWrapper::inverseFrequency(double value)\n{\n    return inverseFrequency(value, mFrequencyScale);\n}\n\ndouble QPainterWrapper::mapTimeToX(double time)\n{\n    return mapTimeToX(time, p->viewport().width(), mTimeStart, mTimeEnd);\n}\n\ndouble QPainterWrapper::mapFrequencyToY(double frequency)\n{\n    return mapFrequencyToY(frequency, p->viewport().height(), mFrequencyScale, mMinFrequency, mMaxFrequency);\n}\n\nstatic std::string numberToString(double val)\n{\n    std::stringstream ss;\n    ss << val;\n    return ss.str();\n}\n\nvoid QPainterWrapper::drawTimeAxis()\n{\n    rpm::vector<double> majorTicks;\n    rpm::vector<double> minorTicks;\n    rpm::vector<double> minorMinorTicks;\n\n    int timeStart = std::floor(mTimeStart);\n    int timeEnd = std::ceil(mTimeEnd);\n\n    for (int timeInt = timeStart; timeInt <= timeEnd; ++timeInt) {\n        majorTicks.push_back(timeInt);\n        \n        // No need to be so detailed for negative time stamps.\n        if (timeInt < 0)\n            continue;\n\n        for (int division = 1; division <= 9; ++division) {\n            const double time = timeInt + division / 10.0;\n            if (division == 5)\n                minorTicks.push_back(time);\n            else\n                minorMinorTicks.push_back(time);\n        }\n    }\n\n    int y1 = viewport().height();\n    std::vector<bool> bits(viewport().width(), false);\n    \n    for (const double val : majorTicks) {\n        const double x = mapTimeToX(val);\n        const auto valstr = numberToString(val);\n        QRect rect = p->textBoundsSmall(valstr);\n        rect.translate(x - rect.width() / 2, y1 - 10);\n        bool covered = false;\n        for (int tx = rect.x(); tx <= rect.x() + rect.width(); ++tx) {\n            if (tx >= 0 && tx < bits.size()\n                    && bits[tx]) {\n                covered = true;\n                break;\n            }\n        }\n        p->drawLine(x, y1, x, y1 - 8, Qt::white, 3);\n        if (!covered && val >= 0) {\n            p->drawTextSmallOutlined(x - rect.width() / 2, y1 - 10, Qt::white, valstr, Qt::black);\n            for (int tx = rect.x(); tx <= rect.x() + rect.width(); ++tx) {\n                if (tx >= 0 && tx < bits.size())\n                    bits[tx] = true;\n            }\n        }\n    }\n\n    for (const double val : minorTicks) {\n        const double x = mapTimeToX(val);\n        const auto valstr = numberToString(val);\n        QRect rect = p->textBoundsSmaller(valstr);\n        rect.translate(x - rect.width() / 2, y1 - 10);\n        bool covered = false;\n        for (int tx = rect.x(); tx <= rect.x() + rect.width(); ++tx) {\n            if (tx >= 0 && tx < bits.size()\n                    && bits[tx]) {\n                covered = true;\n                break;\n            }\n        }\n        p->drawLine(x, y1, x, y1 - 4, Qt::white, 2);\n        if (!covered) {\n            p->drawTextSmallerOutlined(x - rect.width() / 2, y1 - 10, Qt::white, valstr, Qt::black);\n            for (int tx = rect.x(); tx <= rect.x() + rect.width(); ++tx) {\n                if (tx >= 0 && tx < bits.size())\n                    bits[tx] = true;\n            }\n        }\n    }\n    \n    for (const double val : minorMinorTicks) {\n        const double x = mapTimeToX(val);\n        p->drawLine(x, y1, x, y1 - 2, Qt::white, 1.5);\n    }\n}\n\nvoid QPainterWrapper::drawFrequencyScale()\n{\n    rpm::vector<double> majorTicks;\n    rpm::vector<double> minorTicks;\n    rpm::vector<double> minorMinorTicks;\n\n    if (mFrequencyScale == FrequencyScale::Linear) {\n        int loFreq = std::floor(mMinFrequency / 1000) * 1000;\n        int hiFreq = std::ceil(mMaxFrequency / 1000) * 1000;\n\n        for (int freqInt = loFreq; freqInt <= hiFreq; freqInt += 1000) {\n            majorTicks.push_back(freqInt);\n\n            for (int division = 1; division <= 9; ++division) {\n                const double freq = freqInt + division * 100.0;\n                if (division == 5)\n                    minorTicks.push_back(freq);\n                else\n                    minorMinorTicks.push_back(freq);\n            }\n        }\n    }\n    else {\n        double loLog = log10(mMinFrequency);\n        double hiLog = log10(mMaxFrequency);\n        int loDecade = (int) floor(loLog);\n\n        double val;\n        double startDecade = pow(10.0, (double) loDecade);\n\n        // Major ticks are the decades.\n        double decade = startDecade;\n        double delta = hiLog - loLog, steps = fabs(delta);\n        double step = delta >= 0 ? 10 : 0.1;\n        double rMin = std::min(mMinFrequency, mMaxFrequency);\n        double rMax = std::max(mMinFrequency, mMaxFrequency);\n        for (int i = 0; i <= steps; ++i) { \n            val = decade;\n            if (val >= rMin && val < rMax) {\n                majorTicks.push_back(val);\n            }\n            decade *= step;\n        }\n\n        // Minor ticks are multiple of decades.\n        decade = startDecade;\n        float start, end, mstep;\n        if (delta > 0) {\n            start = 2; end = 9; mstep = 1;\n        }\n        else {\n            start = 9; end = 2; mstep = -1;\n        }\n        ++steps;\n        for (int i = 0; i <= steps; ++i) {\n            for (int j = start; mstep > 0 ? j <= end : j >= end; j += mstep) {\n                val = decade * j;\n                if (val >= rMin && val < rMax) {\n                    minorTicks.push_back(val);\n                }\n            }\n            decade *= step;\n        }\n\n        // MinorMinor ticks are multiple of decades.\n        decade = startDecade;\n        if (delta > 0) {\n            start = 10; end = 100; mstep = 1;\n        }\n        else {\n            start = 100; end = 10; mstep = -1;\n        }\n        ++steps;\n        for (int i = 0; i <= steps; ++i) {\n            if (decade >= 10.0) {\n                for (int f = start; mstep > 0 ? f <= end : f >= end; f += mstep) {\n                    if ((int) (f / 10) != f / 10.0) {\n                        val = decade * f / 10;\n                        if (val >= rMin && val < rMax) {\n                            minorMinorTicks.push_back(val);\n                        }\n                    }\n                }\n            }\n            decade *= step;\n        }\n    }\n\n    int x1 = viewport().width();\n    std::vector<bool> bits(viewport().height(), false);\n    \n    for (const double val : majorTicks) {\n        const double y = mapFrequencyToY(val);\n        const auto valstr = numberToString(val);\n        QRect rect = p->textBoundsNormal(valstr);\n        rect.translate(x1 - 12 - rect.width(), y + rect.height() / 2);\n        bool covered = false;\n        for (int ty = rect.y(); ty <= rect.y() + rect.height(); ++ty) {\n            if (ty >= 0 && ty < bits.size()\n                    && bits[ty]) {\n                covered = true;\n                break;\n            }\n        }\n        if (covered) {\n            continue;\n        }\n        p->drawLine(x1 - 8, y, x1, y, Qt::white, 3);\n        p->drawTextNormalOutlined(rect.x(), rect.y(), Qt::white, valstr, Qt::black);\n        for (int ty = rect.y(); ty <= rect.y() + rect.height(); ++ty) {\n            if (ty >= 0 && ty < bits.size())\n                bits[ty] = true;\n        }\n    }\n\n    for (const double val : minorTicks) {\n        const double y = mapFrequencyToY(val);\n        const auto valstr = numberToString(val);\n        QRect rect = p->textBoundsSmall(valstr);\n        rect.translate(x1 - 12 - rect.width(), y + rect.height() / 2);\n        bool covered = false;\n        for (int ty = rect.y(); ty <= rect.y() + rect.height(); ++ty) {\n            if (ty >= 0 && ty < bits.size()\n                    && bits[ty]) {\n                covered = true;\n                break;\n            }\n        }\n        if (covered) {\n            continue;\n        }\n        p->drawLine(x1 - 6, y, x1, y, Qt::white, 2);\n        p->drawTextSmallOutlined(rect.x(), rect.y(), Qt::white, valstr, Qt::black);\n        for (int ty = rect.y(); ty <= rect.y() + rect.height(); ++ty) {\n            if (ty >= 0 && ty < bits.size())\n                bits[ty] = true;\n        }\n    }\n\n    for (const double val : minorMinorTicks) {\n        const double y = mapFrequencyToY(val);\n        const auto valstr = numberToString(val);\n        QRect rect = p->textBoundsSmaller(valstr);\n        rect.translate(x1 - 12 - rect.width(), y + rect.height() / 2);\n        bool covered = false;\n        for (int ty = rect.y(); ty <= rect.y() + rect.height(); ++ty) {\n            if (ty >= 0 && ty < bits.size()\n                    && bits[ty]) {\n                covered = true;\n                break;\n            }\n        }\n        if (covered) {\n            continue;\n        }\n        p->drawLine(x1 - 4, y, x1, y, Qt::white, 2);\n        p->drawTextSmallerOutlined(rect.x(), rect.y(), Qt::white, valstr, Qt::black);\n        for (int ty = rect.y(); ty <= rect.y() + rect.height(); ++ty) {\n            if (ty >= 0 && ty < bits.size())\n                bits[ty] = true;\n        }\n    }\n}\n\nvoid QPainterWrapper::drawFrequencyTrack(\n            const TimeTrack<double>::const_iterator& begin,\n            const TimeTrack<double>::const_iterator& end,\n            float radius,\n            const QColor &color)\n{\n    rpm::vector<QPointF> points;\n\n    for (auto it = begin; it != end; ++it) {\n        double time = it->first;\n        double pitch = it->second;\n\n        double x = mapTimeToX(time);\n        double y = mapFrequencyToY(pitch);\n\n        points.emplace_back(x, y);\n    }\n\n    p->drawScatterWithOutline(points, radius, color);\n}\n\nvoid QPainterWrapper::drawFrequencyTrack(\n            const OptionalTimeTrack<double>::const_iterator& begin,\n            const OptionalTimeTrack<double>::const_iterator& end,\n            float radius,\n            const QColor &color)\n{\n    rpm::vector<QPointF> points;\n\n    for (auto it = begin; it != end; ++it) {\n        if (it->second.has_value()) {\n            double time = it->first;\n            double pitch = *(it->second);\n\n            double x = mapTimeToX(time);\n            double y = mapFrequencyToY(pitch);\n\n            points.emplace_back(x, y);\n        }\n    }\n\n    p->drawScatterWithOutline(points, radius, color);\n}\n\n", "meta": {"hexsha": "a3a22c3bb7ef5e09b21227625a9b7844be837390", "size": 11140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gui/qpainterwrapper.cpp", "max_stars_repo_name": "alargepileofash/in-formant", "max_stars_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T20:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T10:58:36.000Z", "max_issues_repo_path": "src/gui/qpainterwrapper.cpp", "max_issues_repo_name": "alargepileofash/in-formant", "max_issues_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-12-06T22:02:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T09:37:56.000Z", "max_forks_repo_path": "src/gui/qpainterwrapper.cpp", "max_forks_repo_name": "alargepileofash/in-formant", "max_forks_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-12-16T16:06:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T15:28:31.000Z", "avg_line_length": 30.2717391304, "max_line_length": 109, "alphanum_fraction": 0.5129263914, "num_tokens": 2862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671083, "lm_q1q2_score": 0.1992332971525529}}
{"text": "/*\n *  Copyright (C) 2018 Naomasa Matsubayashi\n *  Licensed under MIT license, see file LICENSE in this source tree.\n */\n#ifndef UWG_CONFIG_HPP\n#define UWG_CONFIG_HPP\n\n#include <string>\n#include <boost/property_tree/ini_parser.hpp>\n#include <boost/spirit/include/qi_parse.hpp>\n#include <boost/spirit/include/qi_uint.hpp>\n#include <boost/asio.hpp>\n#include <sodium/crypto_scalarmult.h>\n#include <uwg/load_key.hpp>\n#include <uwg/types.hpp>\n#include <uwg/defs.hpp>\n\nnamespace uwg {\n  struct invalid_config {};\n  struct invalid_key {};\n  struct invalid_endpoint {};\n  struct invalid_listen_port {};\n  struct config_t {\n    config_t( boost::asio::io_service &io_service, const std::string &filename ) : self_static_public( wg_key_len, 0 ), self_port( 0 ) {\n      boost::property_tree::ptree root;\n      boost::property_tree::read_ini( filename, root );\n      const auto self_static_private_serialized = root.get_optional< std::string >( \"Interface.PrivateKey\" );\n      if( !self_static_private_serialized )\n        throw invalid_key();\n      const auto listen_port = root.get_optional< uint16_t >( \"Interface.ListenPort\" );\n      if( !listen_port )\n        throw invalid_listen_port();\n      const auto remote_static_public_serialized = root.get_optional< std::string >( \"Peer.PublicKey\" );\n      if( !remote_static_public_serialized )\n        throw invalid_key();\n      const auto remote_address = root.get_optional< std::string >( \"Peer.Endpoint\" );\n      if( !remote_address )\n        throw invalid_endpoint();\n      parse_key( self_static_private_serialized->begin(), self_static_private_serialized->end(), std::back_inserter( self_static_private ) );\n      parse_key( remote_static_public_serialized->begin(), remote_static_public_serialized->end(), std::back_inserter( remote_static_public ) );\n      if( self_static_private.size() != wg_key_len )\n        throw invalid_key();\n      if( remote_static_public.size() != wg_key_len )\n        throw invalid_key();\n      if( crypto_scalarmult_base( self_static_public.data(), self_static_private.data() ) != 0 )\n        throw scalar_mult_failed();\n      const auto remote_address_sep = remote_address->find( ':' );\n      if( remote_address_sep == std::string::npos )\n        throw invalid_endpoint();\n      remote_host = remote_address->substr( 0, remote_address_sep );\n      remote_port = remote_address->substr( remote_address_sep + 1 );\n      boost::asio::ip::udp::resolver resolver( io_service );\n      boost::asio::ip::udp::resolver::query query( remote_host, remote_port );\n      remote_endpoint = *resolver.resolve( query );\n      self_port = *listen_port;\n    }\n    wg_key_type self_static_private;\n    wg_key_type self_static_public;\n    wg_key_type remote_static_public;\n    std::string remote_host;\n    boost::asio::ip::udp::endpoint remote_endpoint;\n    uint16_t self_port;\n    std::string remote_port;\n  };\n}\n\n#endif\n\n", "meta": {"hexsha": "40a7e0f928f390ca119b94b8f112f35a5de063c3", "size": 2877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uwg/config.hpp", "max_stars_repo_name": "Fadis/userspace_wireguard", "max_stars_repo_head_hexsha": "13daa4759c4d96d0e9a112d8c35f680681a6687d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-07-21T04:46:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T06:04:32.000Z", "max_issues_repo_path": "include/uwg/config.hpp", "max_issues_repo_name": "Fadis/userspace_wireguard", "max_issues_repo_head_hexsha": "13daa4759c4d96d0e9a112d8c35f680681a6687d", "max_issues_repo_licenses": ["MIT"], "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/uwg/config.hpp", "max_forks_repo_name": "Fadis/userspace_wireguard", "max_forks_repo_head_hexsha": "13daa4759c4d96d0e9a112d8c35f680681a6687d", "max_forks_repo_licenses": ["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.6956521739, "max_line_length": 144, "alphanum_fraction": 0.7097671185, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19908993984577011}}
{"text": "// Author(s): Wieger Wesselink\n// Copyright: see the accompanying file COPYING or copy at\n// https://github.com/mCRL2org/mCRL2/blob/master/COPYING\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/// \\file txt2pbes_test.cpp\n/// \\brief Add your file description here.\n\n#define BOOST_TEST_MODULE txt2pbes_test\n#include <boost/test/included/unit_test_framework.hpp>\n#include \"mcrl2/pbes/txt2pbes.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::pbes_system;\n\nconst std::string PBESSPEC1 =\n  \"pbes nu X(b: Bool) = exists n: Nat. Y(n) && val(b); \\n\"\n  \"     mu Y(n: Nat)  = X(n >= 10);                    \\n\"\n  \"                                                    \\n\"\n  \"init X(true);                                       \\n\"\n  ;\n\nconst std::string PBESSPEC2 =\n  \"sort DATA = struct d1 | d2;                         \\n\"\n  \"     Enum3 = struct e2_3 | e1_3 | e0_3;             \\n\"\n  \"     Frame = struct frame(getd: DATA, getb: DATA);  \\n\"\n  \"                                                    \\n\"\n  \"glob dc: Frame;                                     \\n\"\n  \"                                                    \\n\"\n  \"pbes nu X(s30_K: Pos, f_K: Frame) =                 \\n\"\n  \"       X(1, f_K);                                   \\n\"\n  \"                                                    \\n\"\n  \"init X(1, dc);                                      \\n\"\n  ;\n\nBOOST_AUTO_TEST_CASE(test_txt2pbes)\n{\n  pbes p;\n  p = txt2pbes(PBESSPEC1);\n  BOOST_CHECK(p.is_well_typed());\n  p = txt2pbes(PBESSPEC2);\n  BOOST_CHECK(p.is_well_typed());\n}\n", "meta": {"hexsha": "5f2c8c63fb7e5cd871806a177fe47bdbe16358bf", "size": 1638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/pbes/test/txt2pbes_test.cpp", "max_stars_repo_name": "Noxsense/mCRL2", "max_stars_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T13:14:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:35:03.000Z", "max_issues_repo_path": "libraries/pbes/test/txt2pbes_test.cpp", "max_issues_repo_name": "Noxsense/mCRL2", "max_issues_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T08:31:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T11:02:41.000Z", "max_forks_repo_path": "libraries/pbes/test/txt2pbes_test.cpp", "max_forks_repo_name": "Noxsense/mCRL2", "max_forks_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2018-04-11T14:09:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T15:57:39.000Z", "avg_line_length": 34.8510638298, "max_line_length": 61, "alphanum_fraction": 0.4816849817, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.19908993103983175}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n Copyright (C) 2017 Aareal Bank AG\n\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 <boost/lexical_cast.hpp>\n#include <ored/portfolio/bond.hpp>\n#include <ored/portfolio/builders/bond.hpp>\n#include <ored/portfolio/fixingdates.hpp>\n#include <ored/portfolio/legdata.hpp>\n#include <ored/portfolio/swap.hpp>\n#include <ored/utilities/indexparser.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ql/cashflows/simplecashflow.hpp>\n#include <ql/instruments/bond.hpp>\n#include <ql/instruments/bonds/zerocouponbond.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\n\nnamespace ore {\nnamespace data {\n\nnamespace {\nLeg joinLegs(const std::vector<Leg>& legs) {\n    Leg masterLeg;\n    for (Size i = 0; i < legs.size(); ++i) {\n        // check if the periods of adjacent legs are consistent\n        if (i > 0) {\n            auto lcpn = boost::dynamic_pointer_cast<Coupon>(legs[i - 1].back());\n            auto fcpn = boost::dynamic_pointer_cast<Coupon>(legs[i].front());\n            QL_REQUIRE(lcpn, \"joinLegs: expected coupon as last cashflow in leg #\" << (i - 1));\n            QL_REQUIRE(fcpn, \"joinLegs: expected coupon as first cashflow in leg #\" << i);\n            QL_REQUIRE(lcpn->accrualEndDate() == fcpn->accrualStartDate(),\n                       \"joinLegs: accrual end date of last coupon in leg #\"\n                           << (i - 1) << \" (\" << lcpn->accrualEndDate()\n                           << \") is not equal to accrual start date of first coupon in leg #\" << i << \" (\"\n                           << fcpn->accrualStartDate() << \")\");\n        }\n        // copy legs together\n        masterLeg.insert(masterLeg.end(), legs[i].begin(), legs[i].end());\n    }\n    return masterLeg;\n}\n} // namespace\n\nvoid Bond::build(const boost::shared_ptr<EngineFactory>& engineFactory) {\n    DLOG(\"Bond::build() called for trade \" << id());\n\n    // Clear the separateLegs_ member here. Should be done in reset() but it is not virtual\n    separateLegs_.clear();\n\n    const boost::shared_ptr<Market> market = engineFactory->market();\n\n    boost::shared_ptr<EngineBuilder> builder = engineFactory->builder(\"Bond\");\n\n    Date issueDate = parseDate(issueDate_);\n    Calendar calendar = parseCalendar(calendar_);\n    Natural settlementDays = boost::lexical_cast<Natural>(settlementDays_);\n    boost::shared_ptr<QuantLib::Bond> bond;\n\n    // FIXME: zero bonds are always long (firstLegIsPayer = false, mult = 1.0)\n    bool firstLegIsPayer = (coupons_.size() == 0) ? false : coupons_[0].isPayer();\n    Real mult = firstLegIsPayer ? -1.0 : 1.0;\n    if (zeroBond_) { // Zero coupon bond\n        bond.reset(new QuantLib::ZeroCouponBond(settlementDays, calendar, faceAmount_, parseDate(maturityDate_)));\n    } else { // Coupon bond\n        for (Size i = 0; i < coupons_.size(); ++i) {\n            bool legIsPayer = coupons_[i].isPayer();\n            QL_REQUIRE(legIsPayer == firstLegIsPayer, \"Bond legs must all have same pay/receive flag\");\n            if (i == 0)\n                currency_ = coupons_[i].currency();\n            else {\n                QL_REQUIRE(currency_ == coupons_[i].currency(), \"leg #\" << i << \" currency (\" << coupons_[i].currency()\n                                                                        << \") not equal to leg #0 currency (\"\n                                                                        << coupons_[0].currency());\n            }\n            Leg leg;\n            auto configuration = builder->configuration(MarketContext::pricing);\n            auto legBuilder = engineFactory->legBuilder(coupons_[i].legType());\n            leg = legBuilder->buildLeg(coupons_[i], engineFactory, configuration);\n            separateLegs_.push_back(leg);\n            \n            // Initialise the set of [index name, leg] index pairs\n            for (const auto& index : coupons_[i].indices()) {\n                nameIndexPairs_.insert(make_pair(index, separateLegs_.size() - 1));\n            }\n\n        } // for coupons_\n        Leg leg = joinLegs(separateLegs_);\n        bond.reset(new QuantLib::Bond(settlementDays, calendar, issueDate, leg));\n        // workaround, QL doesn't register a bond with its leg's cashflows\n        for (auto const& c : leg)\n            bond->registerWith(c);\n    }\n\n    Currency currency = parseCurrency(currency_);\n    boost::shared_ptr<BondEngineBuilder> bondBuilder = boost::dynamic_pointer_cast<BondEngineBuilder>(builder);\n    QL_REQUIRE(bondBuilder, \"No Builder found for Bond: \" << id());\n    bond->setPricingEngine(bondBuilder->engine(currency, creditCurveId_, securityId_, referenceCurveId_));\n    instrument_.reset(new VanillaInstrument(bond, mult));\n\n    npvCurrency_ = currency_;\n    maturity_ = bond->cashflows().back()->date();\n    notional_ = currentNotional(bond->cashflows());\n\n    // Add legs (only 1)\n    legs_ = {bond->cashflows()};\n    legCurrencies_ = {npvCurrency_};\n    legPayers_ = {firstLegIsPayer};\n}\n\nmap<string, set<Date>> Bond::fixings(const Date& settlementDate) const {\n\n    map<string, set<Date>> result;\n\n    for (const auto& nameIndexPair : nameIndexPairs_) {\n        // For clarity\n        string indexName = nameIndexPair.first;\n        Size legNumber = nameIndexPair.second;\n\n        // Get the set of fixing dates for the  [index name, leg index] pair\n        set<Date> dates = fixingDates(separateLegs_[legNumber], settlementDate);\n\n        // Update the results with the fixing dates.\n        if (!dates.empty()) result[indexName].insert(dates.begin(), dates.end());\n    }\n\n    return result;\n}\n\nvoid Bond::fromXML(XMLNode* node) {\n    Trade::fromXML(node);\n    XMLNode* bondNode = XMLUtils::getChildNode(node, \"BondData\");\n    QL_REQUIRE(bondNode, \"No BondData Node\");\n    issuerId_ = XMLUtils::getChildValue(bondNode, \"IssuerId\", true);\n    creditCurveId_ =\n        XMLUtils::getChildValue(bondNode, \"CreditCurveId\", false); // issuer credit term structure not mandatory\n    securityId_ = XMLUtils::getChildValue(bondNode, \"SecurityId\", true);\n    referenceCurveId_ = XMLUtils::getChildValue(bondNode, \"ReferenceCurveId\", true);\n    settlementDays_ = XMLUtils::getChildValue(bondNode, \"SettlementDays\", true);\n    calendar_ = XMLUtils::getChildValue(bondNode, \"Calendar\", true);\n    issueDate_ = XMLUtils::getChildValue(bondNode, \"IssueDate\", true);\n    XMLNode* legNode = XMLUtils::getChildNode(bondNode, \"LegData\");\n    while (legNode != nullptr) {\n        auto ld = createLegData();\n        ld->fromXML(legNode);\n        coupons_.push_back(*boost::static_pointer_cast<LegData>(ld));\n        legNode = XMLUtils::getNextSibling(legNode, \"LegData\");\n    }\n}\n\nboost::shared_ptr<LegData> Bond::createLegData() const { return boost::make_shared<LegData>(); }\n\nXMLNode* Bond::toXML(XMLDocument& doc) {\n    XMLNode* node = Trade::toXML(doc);\n    XMLNode* bondNode = doc.allocNode(\"BondData\");\n    XMLUtils::appendNode(node, bondNode);\n    XMLUtils::addChild(doc, bondNode, \"IssuerId\", issuerId_);\n    XMLUtils::addChild(doc, bondNode, \"CreditCurveId\", creditCurveId_);\n    XMLUtils::addChild(doc, bondNode, \"SecurityId\", securityId_);\n    XMLUtils::addChild(doc, bondNode, \"ReferenceCurveId\", referenceCurveId_);\n    XMLUtils::addChild(doc, bondNode, \"SettlementDays\", settlementDays_);\n    XMLUtils::addChild(doc, bondNode, \"Calendar\", calendar_);\n    XMLUtils::addChild(doc, bondNode, \"IssueDate\", issueDate_);\n    for (auto& c : coupons_)\n        XMLUtils::appendNode(bondNode, c.toXML(doc));\n    return node;\n}\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "824dc62b0f7ded4e0a0f3570a306bb5066b72ea8", "size": 8183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/portfolio/bond.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": "OREData/ored/portfolio/bond.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": "OREData/ored/portfolio/bond.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.5265957447, "max_line_length": 119, "alphanum_fraction": 0.6564829525, "num_tokens": 2009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19908343851403734}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"mitkUltrasoundTransformAndImageMerger.h\"\n\n#include <boost/regex.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <itkImage.h>\n#include <itkImageFileWriter.h>\n\n#include <mitkExceptionMacro.h>\n#include <mitkCameraCalibrationFacade.h>\n#include <mitkImagePixelReadAccessor.h>\n#include <mitkIOUtil.h>\n#include <mitkOpenCVFileIOUtils.h>\n#include <mitkOpenCVMaths.h>\n#include <mitkTrackingAndTimeStampsContainer.h>\n\n#include <niftkFileHelper.h>\n#include <niftkFileIOUtils.h>\n#include <niftkVTKFunctions.h>\n\nnamespace mitk\n{\n\n//-----------------------------------------------------------------------------\nUltrasoundTransformAndImageMerger::~UltrasoundTransformAndImageMerger()\n{\n}\n\n\n//-----------------------------------------------------------------------------\nUltrasoundTransformAndImageMerger::UltrasoundTransformAndImageMerger()\n{\n}\n\n\n//-----------------------------------------------------------------------------\nvoid UltrasoundTransformAndImageMerger::Merge(const std::string& inputMatrixDirectory,\n    const std::string& inputImageDirectory,\n    const std::string& outputImageFileName,\n    const std::string& imageOrientation)\n{\n  cv::Matx44d identityMatrix;\n  mitk::MakeIdentity(identityMatrix);\n\n  mitk::TrackingAndTimeStampsContainer trackingTimeStamps;\n  bool haltOnMatrixReadFailure = true;\n  int badMatrixFiles = trackingTimeStamps.LoadFromDirectory(inputMatrixDirectory, haltOnMatrixReadFailure);\n\n  std::vector<std::string> imageFiles = niftk::GetFilesInDirectory(inputImageDirectory);\n  std::sort(imageFiles.begin(), imageFiles.end());\n\n  // Load all images. OK, so this will eventually run out of memory, but its ok for now.\n  std::vector<mitk::Image::Pointer> images;\n  for (int i = 0; i < imageFiles.size(); i++)\n  {\n    images.push_back(mitk::IOUtil::LoadImage(imageFiles[i]));\n  }\n\n  std::cout << \"Number of matrices=\" << trackingTimeStamps.GetSize() << std::endl;\n  std::cout << \"Number of images=\" << imageFiles.size() << std::endl;\n\n  if (trackingTimeStamps.GetSize() < imageFiles.size())\n  {\n    std::ostringstream errorMessage;\n    errorMessage << \"Loaded \" << trackingTimeStamps.GetSize() << \" matrices, and loaded a difference number of images \" << images.size() << \", and number of images must be less than number of matrices.\" << std::endl;\n    mitkThrow() << errorMessage.str();\n  }\n\n  if (imageFiles.size() != images.size())\n  {\n    std::ostringstream errorMessage;\n    errorMessage << \"Retrieved \" << imageFiles.size() << \" file names for images, but could only load \" << images.size() << \" images!\" << std::endl;\n    mitkThrow() << errorMessage.str();\n  }\n\n  // Now generate output.\n\n  typedef itk::Image<unsigned char, 3> ImageType;\n  ImageType::Pointer outputImage = ImageType::New();\n\n  int sizeX = images[0]->GetDimension(0);\n  int sizeY = images[0]->GetDimension(1);\n\n  ImageType::SizeType size;\n  size[0] = sizeX;\n  size[1] = sizeY;\n  size[2] = images.size();\n\n  ImageType::IndexType offset;\n  offset.Fill(0);\n\n  ImageType::RegionType region;\n  region.SetSize(size);\n  region.SetIndex(offset);\n\n  ImageType::SpacingType spacing;\n  spacing.Fill(1);\n\n  ImageType::PointType origin;\n  origin.Fill(0);\n\n  ImageType::DirectionType direction;\n  direction.SetIdentity();\n\n  outputImage->SetSpacing(spacing);\n  outputImage->SetOrigin(origin);\n  outputImage->SetRegions(region);\n  outputImage->SetDirection(direction);\n  outputImage->Allocate();\n  outputImage->FillBuffer(0);\n\n  // Fill 3D image, slice by slice. This is slow, but we wont do it often.\n  itk::Index<3> inputImageIndex;\n  itk::Index<3> outputImageIndex;\n\n  for (unsigned int i = 0; i < images.size(); i++)\n  {\n    mitk::ImagePixelReadAccessor<unsigned char, 3> readAccess(images[i], images[i]->GetVolumeData(0));\n\n    for (unsigned int y = 0; y < sizeY; y++)\n    {\n      for (unsigned int x = 0; x < sizeX; x++)\n      {\n        inputImageIndex[0] = x;\n        inputImageIndex[1] = y;\n        inputImageIndex[2] = 0;\n\n        outputImageIndex[0] = x;\n        outputImageIndex[1] = y;\n        outputImageIndex[2] = i;\n\n        outputImage->SetPixel(outputImageIndex, readAccess.GetPixelByIndex(inputImageIndex));\n      }\n    }\n  }\n\n  // Now we write a volume. We just output the extra header info required.\n  // The user can manually append it to the file if necessary.\n  std::string outputImgFile = outputImageFileName + \".mhd\";\n  itk::ImageFileWriter<ImageType>::Pointer writer = itk::ImageFileWriter<ImageType>::New();\n  writer->SetFileName(outputImgFile);\n  writer->SetInput(outputImage);\n  writer->Update();\n\n  std::cout << \"Written image data to \" << outputImgFile << std::endl;\n\n  // Read .mhd header file.\n  std::vector<std::string> linesFromMhdFile;\n  std::ifstream fin(outputImgFile.c_str());\n  if ( !fin )\n  {\n    std::ostringstream errorMessage;\n    errorMessage << \"Could not open \" << outputImgFile << \" for reading!\" << std::endl;\n    mitkThrow() << errorMessage.str();\n  }\n  char lineOfText[256];\n  do {\n    fin.getline(lineOfText,256);\n    if (fin.good())\n    {\n      linesFromMhdFile.push_back(std::string(lineOfText));\n      std::cout << \"Read:\" << lineOfText << std::endl;\n    }\n  } while (fin.good());\n  fin.close();\n\n  // Now, re-open file .mhd file to add meta-data.\n  std::ofstream fout(outputImgFile.c_str(), std::ios::out | std::ios::app);\n  if ( !fout )\n  {\n    std::ostringstream errorMessage;\n    errorMessage << \"Could not open \" << outputImgFile << \" for text output!\" << std::endl;\n    mitkThrow() << errorMessage.str();\n  }\n\n  // Write everything except the last string of the existing header.\n  for (unsigned int i = 0; i < linesFromMhdFile.size() - 1; i++)\n  {\n    fout << linesFromMhdFile[i] << std::endl;\n  }\n\n  fout << \"UltrasoundImageOrientation = \" << imageOrientation << std::endl;\n  fout << \"UltrasoundImageType = BRIGHTNESS\" << std::endl;\n\n  std::string oneZero = \"0\";\n  std::string twoZero = \"00\";\n  std::string threeZero = \"000\";\n\n  fout.precision(10);\n\n  boost::regex timeStampFilter ( \"([0-9]{19})(.)*\");\n  boost::cmatch what;\n  std::string timeStampAsString;\n  unsigned long long timeStamp;\n  long long timingError;\n  bool inBounds;\n  unsigned long long timeStampFirstFrame = 0;\n  double timeStampInSeconds = 0;\n  cv::Matx44d interpolatedMatrix;\n\n  for (unsigned int i = 0; i < images.size(); i++)\n  {\n    std::ostringstream suffix;\n    if (i < 10)\n    {\n      suffix << threeZero << i;\n    }\n    else if (i < 100)\n    {\n      suffix << twoZero << i;\n    }\n    else if (i < 1000)\n    {\n      suffix << oneZero << i;\n    }\n    else\n    {\n      suffix << i;\n    }\n\n    std::string nameToMatch = niftk::Basename(imageFiles[i]);\n    if ( boost::regex_match( nameToMatch.c_str(), what, timeStampFilter) )\n    {\n      timeStampAsString = nameToMatch.substr(0, 19);\n      timeStamp = boost::lexical_cast<unsigned long long>(timeStampAsString);\n      if (timeStampFirstFrame == 0)\n      {\n        timeStampFirstFrame = timeStamp;\n      }\n      interpolatedMatrix = trackingTimeStamps.InterpolateMatrix(timeStamp, timingError, inBounds);\n      timeStampInSeconds = (timeStamp - timeStampFirstFrame)/static_cast<double>(1000000000);\n\n      fout << \"Seq_Frame\" << suffix.str() << \"_FrameNumber = \" << i << std::endl;\n      fout << \"Seq_Frame\" << suffix.str() << \"_UnfilteredTimestamp = \" << timeStampInSeconds << std::endl;\n      fout << \"Seq_Frame\" << suffix.str() << \"_Timestamp = \" << timeStampInSeconds << std::endl;\n      fout << \"Seq_Frame\" << suffix.str() << \"_ProbeToTrackerTransform =\";\n\n      for (int r = 0; r < 4; r++)\n      {\n        for (int c = 0; c < 4; c++)\n        {\n          fout << \" \" << interpolatedMatrix(r, c);\n        }\n      }\n      fout << std::endl;\n\n      fout << \"Seq_Frame\" << suffix.str() << \"_ProbeToTrackerTransformStatus = OK\" << std::endl;\n      fout << \"Seq_Frame\" << suffix.str() << \"_ReferenceToTrackerTransform =\";\n      for (int r = 0; r < 4; r++)\n      {\n        for (int c = 0; c < 4; c++)\n        {\n          // We are not actually tracking a reference object.\n          // This is just so that I can get data into fCal.\n          fout << \" \" << identityMatrix(r, c);\n        }\n      }\n      fout << std::endl;\n      fout << \"Seq_Frame\" << suffix.str() << \"_ReferenceToTrackerTransformStatus = OK\" << std::endl;\n      fout << \"Seq_Frame\" << suffix.str() << \"_StylusToTrackerTransform =\";\n      for (int r = 0; r < 4; r++)\n      {\n        for (int c = 0; c < 4; c++)\n        {\n          // We are not actually tracking a stylus object.\n          // This is just so that I can get data into fCal.\n          fout << \" \" << identityMatrix(r, c);\n        }\n      }\n      fout << std::endl;\n      fout << \"Seq_Frame\" << suffix.str() << \"_StylusToTrackerTransformStatus = OK\" << std::endl;\n    }\n    else\n    {\n      std::ostringstream errorMessage;\n      errorMessage << \"Image \" << imageFiles[i] << \" does not look like it contains a time-stamp.\" << std::endl;\n      mitkThrow() << errorMessage.str();\n    }\n  }\n\n  fout << linesFromMhdFile[linesFromMhdFile.size() - 1];\n  fout.close();\n\n  std::cout << \"Written meta-data to \" << outputImgFile << std::endl;\n}\n\n\n//-----------------------------------------------------------------------------\n} // end namespace\n", "meta": {"hexsha": "b0793fcd46d5f82a34688ea262081f2d0a8ff7df", "size": 9635, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "MITK/Modules/OpenCV/UltrasoundCalibration/mitkUltrasoundTransformAndImageMerger.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "MITK/Modules/OpenCV/UltrasoundCalibration/mitkUltrasoundTransformAndImageMerger.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "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": "MITK/Modules/OpenCV/UltrasoundCalibration/mitkUltrasoundTransformAndImageMerger.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 31.6940789474, "max_line_length": 216, "alphanum_fraction": 0.6167099118, "num_tokens": 2453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1990834329050347}}
{"text": "\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <iostream>\n#include <string.h>\n#include <opencv2/opencv.hpp>\n\n\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <map>\n#include <ctime>\n#include <sstream>\n#include <algorithm>\n#include <boost/thread/thread.hpp>\n#include <ros/ros.h>\n#include \"std_msgs/String.h\"\n#include <tf/transform_broadcaster.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Point.h>\n#include <image_transport/image_transport.h>\n#include <cv_bridge/cv_bridge.h>\n\n#include \"colormod.h\" // namespace Color\n#include \"keyboard.h\"\n\n#ifndef Included_MATH_HELPER_H\n#define Included_MATH_HELPER_H\n#include \"math_helper.h\"\n#endif\n#ifndef Included_STRING_CONVERTOR_H\n#define Included_STRING_CONVERTOR_H\n#include \"string_convertor.h\"\n#endif\n\n// MoveIt!\n#include <moveit/robot_model_loader/robot_model_loader.h>\n#include <moveit/robot_model/robot_model.h>\n#include <moveit/robot_state/robot_state.h>\n\n\n// Robot state publishing\n#include <moveit/robot_state/conversions.h>\n#include <moveit_msgs/DisplayRobotState.h>\n\n// Kinematics\n#include <moveit_msgs/GetPositionIK.h>\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Quaternion.h>\n\n//wam\n#include \"wam_msgs/MatrixMN.h\"\n#include \"wam_srvs/JointMove.h\"\n#include \"sensor_msgs/JointState.h\"\n\nusing namespace std;\n\nColor::Modifier c_red(Color::FG_RED);\nColor::Modifier c_yellow(Color::FG_YELLOW);\nColor::Modifier c_green(Color::FG_GREEN);\nColor::Modifier c_default(Color::FG_DEFAULT);\nbool lock = false;\nbool ready_signal1 = false;\nbool ready_signal2 = false;\nbool ready_signal3 = false;\ndouble step_size = 0.02;//m\ndouble angle_step_size = 0.01745329251;//1 degree\n\ndouble current_pos[]={9999,9999,9999,9999,9999,9999, 9999};//initialize as an invalid  value set, stores the current pose\n\nstd::vector<double> fullJointStates; //current joint states, 8 values, including a virtual joint\nstd::vector<double> joint_values; //IK solutions\nmoveit::core::RobotModelPtr kinematic_model;\nstd::vector<std::string>  joint_names;\nros::Publisher robot_state_publisher ;\nint dofNum = 7;\nwam_srvs::JointMove mv_srv;\nros::ServiceClient Joint_move_client ;\n\nbool grasping_mode = false;\nsensor_msgs::JointState grasp_msg;\n\ngeometry_msgs::Pose thisPose;\n\n// void wamPoseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)\n//  {\n//    //cout<<\"wam msgs\"<<endl;\n//     thisPose = msg->pose;\n//     cv::Mat t(3,1,cv::DataType<double>::type);\n//     cv::Mat R(3,3,cv::DataType<double>::type);\n//\n//     t.at<double>(0,0) = thisPose.position.x; t.at<double>(1,0) = thisPose.position.y; t.at<double>(2,0) = thisPose.position.z + 1.365;\n//\n//     tf::Quaternion q(thisPose.orientation.x, thisPose.orientation.y , thisPose.orientation.z, thisPose.orientation.w);\n//     tf::Matrix3x3 rMatrix(q);\n//     for(int i=0;i<3;i++)\n//       for(int j=0;j<3;j++)\n//           R.at<double>(i,j)= rMatrix[i][j];\n//     // current_trans = t;\n//     // current_rot = R;\n//     ready_signal2=true;\n//     //cout<<\"pose callback\"<<endl;\n//  }\n\nconst Eigen::Affine3d comput_fk() //get current end  effector  pose\n{\n  robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model));\n  //fill in the seed\n  kinematic_state->setVariablePositions(current_pos);\n  cout<<\"compute fk current joints \"<<current_pos[0]<<\", \"<<current_pos[1]<<\", \"<<current_pos[2]<<endl;\n  kinematic_state->update();\n  const Eigen::Affine3d end_effector_state = kinematic_state->getGlobalLinkTransform(\"wam/wrist_palm_link\");//table_base\n  ROS_INFO_STREAM(\"FK Translation: \" << end_effector_state.translation());\n  Eigen::Quaterniond rot_q(end_effector_state.rotation());\n  ROS_INFO_STREAM(\"FK Rotation q x: \" << rot_q.x());\n  ROS_INFO_STREAM(\"FK Rotation q y: \" << rot_q.y());\n  ROS_INFO_STREAM(\"FK Rotation q z: \" << rot_q.z());\n  ROS_INFO_STREAM(\"FK Rotation q w: \" << rot_q.w());\n  /* Print end-effector pose. Remember that this is in the model frame */\n  //print out current joints\n  // cout<<\"print out current joints\"<<endl;\n  // kinematic_state->copyJointGroupPositions(joint_model_group, joint_values);\n  // for(std::size_t i=0; i < joint_names.size(); ++i)\n  // {\n  //   ROS_INFO(\"current Joint %s: %f\", joint_names[i].c_str(), joint_values[i]);\n  // }\n  return end_effector_state;\n}\n\nbool comput_IK(geometry_msgs::Pose p)\n{\n  robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model));\n  const robot_state::JointModelGroup* joint_model_group = kinematic_model->getJointModelGroup(\"arm\");//All, it's in the planning group name\n  const std::vector<std::string> &joint_names2 = joint_model_group->getJointModelNames();\n\n  joint_names= joint_names2;\n  joint_names=string_convertor::safeRemoveStringVec(joint_names,0);//first  item of  joint name  is  caused by  mistake\n  cout<<\"joint names count  \"<<joint_names.size()<<endl;\n  //fill in the seed\n  kinematic_state->setVariablePositions(current_pos);\n  cout<<\"compute IK current joints \"<<current_pos[0]<<\", \"<<current_pos[1]<<\", \"<<current_pos[2]<<endl;\n\n  kinematic_state->update();\n\n  bool found_ik = kinematic_state->setFromIK(joint_model_group, p, 10, 0.1);\n  // Now, we can print out the IK solution (if found):\n  if (found_ik)\n  {\n    kinematic_state->copyJointGroupPositions(joint_model_group, joint_values);\n    cout<<c_green<<\"IK solution found: \";\n    for(std::size_t i=0; i < joint_values.size(); ++i)\n    {\n      ROS_INFO(\"IK solution Joint %s: %f\", joint_names[i].c_str(), joint_values[i]);\n      cout<<joint_values[i]<<\",\";\n    }\n    cout<<c_default<<endl;\n  }\n  else\n  {\n    ROS_INFO(\"Did not find IK solution\");\n  }\n  return found_ik;\n}\n\nvoid test_IK_FK()\n{\n  const Eigen::Affine3d end_effector_state = comput_fk();\n  Eigen::Quaterniond rot_q(end_effector_state.rotation());\n  geometry_msgs::Pose pose;\n\n  pose.position.x = end_effector_state.translation()(0);\n  pose.position.y = end_effector_state.translation()(1);\n  pose.position.z = end_effector_state.translation()(2);\n  pose.orientation.x = rot_q.x();\n  pose.orientation.y = rot_q.y();\n  pose.orientation.z = rot_q.z();\n  pose.orientation.w = rot_q.w();\n  cout<<\"using pose to test \"<<endl;\n  cout<<\"x \"<<pose.position.x <<\" y \"<<pose.position.y<<\" z \"<<pose.position.z<<endl;\n  bool ik_found = comput_IK(pose);\n  if(ik_found)\n  {\n\n    ROS_INFO(\"asdaf\");\n  }\n}\nstd::vector<std::string> constructFullJointNames()\n{\n   std::vector<std::string> rts;\n   rts.push_back(\"jaco_arm_0_joint\");\n   rts.push_back(\"jaco_arm_1_joint\");\n   rts.push_back(\"jaco_arm_2_joint\");\n   rts.push_back(\"jaco_arm_3_joint\");\n   rts.push_back(\"jaco_arm_4_joint\");\n   rts.push_back(\"jaco_arm_5_joint\");\n   rts.push_back(\"jaco_finger_joint_0\");\n   rts.push_back(\"jaco_finger_joint_2\");\n   rts.push_back(\"jaco_finger_joint_4\");\n   return rts;\n}\nstd::vector<double> constructFullJoints(double *strs)\n{\n  std::vector<double> rts;\n  int arraySize =(int)(sizeof(strs)/sizeof(*strs));\n  for( size_t i=0;i<arraySize;i++)\n    rts.push_back(strs[i]);\n  return rts;\n}\n//inStr \"0 0 0 0\"\nvoid moveRobotJointValue(std::vector<double> joint_values_t)\n{\n  lock=true;\n  std::vector<float> jnts;\n     for(size_t i=0;i<dofNum;i++)\n     {\n       float newJ = (float)(joint_values_t[i]);\n       jnts.push_back(newJ);\n     }\n  mv_srv.request.joints = jnts;\n  cout<<\"send to robot to the  position \"<<endl;\n  //string_convertor::printOutStdVector(jnts);\n  // cout << \"Press any key to continue...\" << endl;\n  // getchar();\n  Joint_move_client.call(mv_srv);///////////////////////////////////////////////////\n  //boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );\n  lock=false;\n}\nvoid tele_op_keyboard(keyboard::Key k)\n{\n  // if(current_pos[0]==9999)\n  // {\n  //   cout<<c_red<<\"current robot joint state is not updated!\"<<c_default<<endl;\n  //   return  ;\n  // }\n  const Eigen::Affine3d end_effector_state = comput_fk();\n  //ROS_INFO_STREAM(\"Translation: \" << thisPose.position.x <<\" \"<<thisPose.position.y <<\" \" << thisPose.position.z<<endl);\n  //ROS_INFO_STREAM(\"Translation: \" << end_effector_state.translation());\n  // ROS_INFO_STREAM(\"Rotation: \" << end_effector_state.rotation());\n  Eigen::Quaterniond rot_q(end_effector_state.rotation());\n  // ROS_INFO_STREAM(\"Rotation q x: \" << rot_q.x());\n  // ROS_INFO_STREAM(\"Rotation q y: \" << rot_q.y());\n  // ROS_INFO_STREAM(\"Rotation q z: \" << rot_q.z());\n  // ROS_INFO_STREAM(\"Rotation q w: \" << rot_q.w());\n  geometry_msgs::Pose p;\n  p.position.x = end_effector_state.translation()(0);\n  p.position.y = end_effector_state.translation()(1);\n  p.position.z = end_effector_state.translation()(2);\n  p.orientation.x = rot_q.x();\n  p.orientation.y = rot_q.y();\n  p.orientation.z = rot_q.z();\n  p.orientation.w = rot_q.w();\n  //geometry_msgs::Pose pose = thisPose;//save it as present pose\n \t//tf::poseEigenToMsg(end_effector_state, pose);\n\n  std::vector<double> joint_values_temp; //\n  std::vector<double> effort_temp; //\n  bool needEffortControl = false;\n  std::vector<std::string>  joint_names_temp;\n  int ik_needed = 0;//0 no motion neeeded . 1 motion needed  and ik  solution  needed; 2 motion  needed,  but no  need for  ik solution.\n\n  switch (k.code) {\n    case 273://up arrow\n      std::cout << \"move forward\" << '\\n';\n      ik_needed=1;\n      p.position.x = end_effector_state.translation()(0)-step_size;\n      break;\n    case 274://down arrow\n      std::cout << \"move backward\" << '\\n';\n      ik_needed=1;\n      p.position.x = end_effector_state.translation()(0)+step_size;\n      break;\n    case 276://left arrow\n      std::cout << \"move left\" << '\\n';\n      ik_needed=1;\n      p.position.y = end_effector_state.translation()(1)-step_size;\n      break;\n    case 275://right arrow\n      std::cout << \"move right\" << '\\n';\n      ik_needed=1;\n      p.position.y = end_effector_state.translation()(1)+step_size;\n      break;\n    case 97://a\n      std::cout << \"move up\" << '\\n';\n      ik_needed=1;\n      p.position.z = end_effector_state.translation()(2)+step_size;\n      break;\n    case 115://s\n      std::cout << \"move down\" << '\\n';\n      ik_needed=1;\n      p.position.z = end_effector_state.translation()(2)-step_size;\n      break;\n    case 100://d\n      std::cout << \"rotate clockwise\" << '\\n';\n      ik_needed=2;\n      std::vector<double>().swap(joint_values_temp); //clear the vector\n      std::vector<std::string>().swap(joint_names_temp);\n      joint_names_temp.push_back(\"jaco_arm_5_joint\");\n      joint_values_temp.push_back(fullJointStates[6]+angle_step_size);\n      break;\n    case 102://f\n      std::cout << \"rotate  anti-clockwise\" << '\\n';\n      ik_needed=2;\n      std::vector<double>().swap(joint_values_temp); //clear the vector\n      std::vector<std::string>().swap(joint_names_temp);\n      joint_names_temp.push_back(\"jaco_arm_5_joint\");\n      joint_values_temp.push_back(fullJointStates[6]-angle_step_size);\n      break;\n    case 103://g\n      std::cout << \"grasp\" << '\\n';\n      grasping_mode=true;\n      ik_needed=2;\n      std::vector<double>().swap(joint_values_temp); //clear the vector\n      std::vector<std::string>().swap(joint_names_temp);\n      joint_names_temp.push_back(\"jaco_finger_joint_0\");\n      joint_names_temp.push_back(\"jaco_finger_joint_2\");\n      joint_names_temp.push_back(\"jaco_finger_joint_4\");\n      joint_values_temp.push_back(1.0);\n      joint_values_temp.push_back(1.0);\n      joint_values_temp.push_back(1.0);\n      needEffortControl=true;\n      effort_temp.push_back(50);\n      effort_temp.push_back(50);\n      effort_temp.push_back(50);\n      grasp_msg.name = joint_names_temp;\n      grasp_msg.position = joint_values_temp;\n      grasp_msg.effort = effort_temp;\n      break;\n    case 104://h\n      ik_needed=2;\n      std::cout << \"release\" << '\\n';\n      grasping_mode=false;\n      std::vector<double>().swap(joint_values_temp); //clear the vector\n      std::vector<std::string>().swap(joint_names_temp);\n      joint_names_temp.push_back(\"jaco_finger_joint_0\");\n      joint_names_temp.push_back(\"jaco_finger_joint_2\");\n      joint_names_temp.push_back(\"jaco_finger_joint_4\");\n      joint_values_temp.push_back(0);\n      joint_values_temp.push_back(0);\n      joint_values_temp.push_back(0);\n      break;\n    case 106: //j\n     ik_needed=0;\n     std::cout << \"step size increase to maximum: 1 cm\" << '\\n';\n     step_size=0.01;\n     angle_step_size = 0.01745329251;\n     break;\n   case 107: //k\n    ik_needed=0;\n    std::cout << \"step size decrease to minimum: 1 mm\" << '\\n';\n    step_size=0.001;\n    angle_step_size = 0.005;\n    break;\n   case 257://num 1, pose 1\n     ik_needed=2;\n     std::cout << \"go to pre grasp pose 1\" << '\\n';\n     grasping_mode=false;\n     std::vector<double>().swap(joint_values_temp); //clear the vector\n     std::vector<std::string>().swap(joint_names_temp);\n     joint_names_temp=constructFullJointNames();\n     //joint_pos=double[]{-1.3855690196259935, -0.6055034496049199, -0.13711278461549714, -0.26863385237514037, -2.164869929572392, 0.022610752306681192, 0.005429499871134169, 0.002955580646637479, 0.0054895619658141825};//initialize as an invalid  value set\n     joint_values_temp=string_convertor::split2double(\"-1.5067168867631673, -0.7126268917944647, 0.06637582003291165, -0.2569294266773463, -2.261174910063673, -0.07121034017964067, 0.005231278056194277, 0.004921044751721837, 0.005474238319798097\",',');\n     break;\n   case 258://num 2, pose 2\n     ik_needed=2;\n     std::cout << \"go to pre grasp pose 2\" << '\\n';\n     grasping_mode=false;\n     std::vector<double>().swap(joint_values_temp); //clear the vector\n     std::vector<std::string>().swap(joint_names_temp);\n     joint_names_temp=constructFullJointNames();\n     joint_values_temp=string_convertor::split2double(\"-1.6785439713205421, -0.8295996787645588, 0.5727369662738369, -0.15870884433891863, -2.693067655844972, -0.4522102718374619, 0.0050140626796837395, 0.0047726880740635025, 0.005041075119017968\",',');//initialize as an invalid  value set\n     //joint_values_temp=constructFullJoints(joint_pos2);\n     break;\n  }\n  sensor_msgs::JointState msg;\n  if(ik_needed==1)\n  {\n    bool ik_found = comput_IK(p);\n    if(ik_found)\n    {\n      // msg.name = joint_names;\n      // msg.position = joint_values;\n      // cout<<msg<<endl;\n      // robot_state_publisher.publish(msg);\n      moveRobotJointValue(joint_values);\n      ROS_INFO(\"msg published!\");\n    }\n  }\n  else if(ik_needed==2)\n  {\n    msg.name = joint_names_temp;\n    msg.position = joint_values_temp;\n    if(needEffortControl)\n      msg.effort = effort_temp;\n    //cout<<msg<<endl;\n    robot_state_publisher.publish(msg);\n    ROS_INFO(\"msg published!\");\n  }\n}\n\nvoid wamJointsCallback(const sensor_msgs::JointState::ConstPtr& msg)\n {\n    //current_pos=msg->position;\n    //cout<<\"joint pose obtained:\"<<endl;//<<initial_Joint_pose[1]<<endl;\n     //cout<<initial_Joint_pose[0]<<\"  \"<<initial_Joint_pose[1]<<\"  \"<<initial_Joint_pose[2]<<\" \"<<initial_Joint_pose[3]<<\" \"<< initial_Joint_pose[4]\n    // <<\" \"<<initial_Joint_pose[5]<<\" \"<<initial_Joint_pose[6]<<endl;\n    //ready_signal3=true;\n    current_pos[0]=msg->position[0];\n    current_pos[1]=msg->position[1];\n    current_pos[2]=msg->position[2];\n    current_pos[3]=msg->position[3];\n    current_pos[4]=msg->position[4];\n    current_pos[5]=msg->position[5];\n    current_pos[6]=msg->position[6];\n    ready_signal1 = true;\n }\n\n\n\n//===========================MAIN FUNCTION START===========================\n\nint main(int argc, char* argv[]){\n  // Initialize the ROS system and become a node.\n   // if(argc==2)\n   //      numThres = atoi(argv[1]);\n  ros::init(argc, argv, \"tele_op\");\n  ros::NodeHandle n(\"~\");\n  //ros::Subscriber subP = n.subscribe(\"/zeus/wam/pose\", 1, wamPoseCallback);\n  //robot_state_publisher = n.advertise<sensor_msgs::JointState>( \"/jaco/joint_control\", 1000 );\n  //ros::Duration(1).sleep();\n  ros::Subscriber wam_joints_sub=n.subscribe(\"/zeus/wam/joint_states\",1, wamJointsCallback);\n  Joint_move_client = n.serviceClient<wam_srvs::JointMove>(\"/zeus/wam/joint_move\");\n\n\n  robot_model_loader::RobotModelLoader robot_model_loader(\"robot_description\");\n  kinematic_model = robot_model_loader.getModel();\n  ROS_INFO(\"Model frame: %s\", kinematic_model->getModelFrame().c_str());\n\n  robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model));\n  const robot_state::JointModelGroup* joint_model_group = kinematic_model->getJointModelGroup(\"arm\");//All, it's in the planning group name\n  const std::vector<std::string> &joint_names2 = joint_model_group->getJointModelNames();\n  cout<<\"joint names: \"<<joint_names2[2]<<endl;\n  getchar();\n  ready_signal1=false;ready_signal2=false;ready_signal3=false;\n    while(!ready_signal1)\n    {\n      ros::spinOnce();\n      boost::this_thread::sleep( boost::posix_time::milliseconds(100) );\n    }\n\n  //test_IK_FK();\n  //getchar();\n\n  bool allow_repeat=false;\n  int repeat_delay, repeat_interval;\n\n  n.param<bool>( \"allow_repeat\", allow_repeat, false ); // disable by default\n  n.param<int>( \"repeat_delay\", repeat_delay, SDL_DEFAULT_REPEAT_DELAY );\n  n.param<int>( \"repeat_interval\", repeat_interval, SDL_DEFAULT_REPEAT_INTERVAL );\n\n  if ( !allow_repeat ) repeat_delay=0; // disable\n  keyboard::Keyboard kbd( repeat_delay, repeat_interval );\n\n  ros::Rate r(50);\n  cout<<\"========================================================================\"<<endl<<endl;\n  cout<<c_green<<\"Human teaching interface by keyboard teleoperation control\"<<endl<<endl;\n  cout<<c_green<<\"University of Alberta, Vision & Robotics Lab, Jun Jin\"<<c_default<<endl<<endl;\n  cout<<\"========================================================================\"<<endl;\n  cout<<c_yellow<<\"options on the end effector motion:\"<<endl;\n  cout<<\"forward -- Up arrow\"<<endl;\n  cout<<\"backward -- Up arrow\"<<endl;\n  cout<<\"left -- left arrow\"<<endl;\n  cout<<\"right -- right arrow\"<<endl;\n  cout<<\"up -- a\"<<endl;\n  cout<<\"down -- s\"<<endl;\n  cout<<\"rotate clockwise -- d\"<<endl;\n  cout<<\"rotate anti-clockwise -- f\"<<endl;\n  cout<<\"grasping -- g\"<<endl;\n  cout<<\"open gripper -- h\"<<endl;\n  cout<<c_default<<\"--------------------------------------\"<<endl;\n  keyboard::Key k;\n  bool pressed, new_event;\n  while (ros::ok() && kbd.get_key(new_event, pressed, k.code, k.modifiers)) {\n    if (new_event) {\n      k.header.stamp = ros::Time::now();\n      if (pressed)\n         tele_op_keyboard(k);\n    }\n    ros::spinOnce();\n    r.sleep();\n  }\n\n  ros::waitForShutdown();\n}\n", "meta": {"hexsha": "66952a6220738afb1f3d30c75b76de5f818ab0b0", "size": 18420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "7_Baseline_Control/src/main.cpp", "max_stars_repo_name": "atlas-jj/long-range-teleoperation-robot-side", "max_stars_repo_head_hexsha": "91ff5178da6b751f19d5daba48154e7704a686eb", "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": "7_Baseline_Control/src/main.cpp", "max_issues_repo_name": "atlas-jj/long-range-teleoperation-robot-side", "max_issues_repo_head_hexsha": "91ff5178da6b751f19d5daba48154e7704a686eb", "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": "7_Baseline_Control/src/main.cpp", "max_forks_repo_name": "atlas-jj/long-range-teleoperation-robot-side", "max_forks_repo_head_hexsha": "91ff5178da6b751f19d5daba48154e7704a686eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T05:00:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T05:00:13.000Z", "avg_line_length": 36.9138276553, "max_line_length": 290, "alphanum_fraction": 0.6777415852, "num_tokens": 5082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1990834329050347}}
{"text": "#ifndef __fovis_visual_odometry_hpp__\n#define __fovis_visual_odometry_hpp__\n\n#include <stdint.h>\n\n#include <Eigen/Geometry>\n\n#include \"keypoint.hpp\"\n#include \"camera_intrinsics.hpp\"\n#include \"frame.hpp\"\n#include \"depth_source.hpp\"\n#include \"motion_estimation.hpp\"\n#include \"options.hpp\"\n\nnamespace fovis\n{\n\n/**\n * Utility class so that the VisualOdometry class not need\n * EIGEN_MAKE_ALIGNED_OPERATOR_NEW.\n */\nclass VisualOdometryPriv\n{\n  private:\n    friend class VisualOdometry;\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    // best estimate for current position and orientation\n    Eigen::Isometry3d pose;\n\n    // transformation relating reference frame and most recent frame\n    Eigen::Isometry3d ref_to_prev_frame;\n\n    // best estimate of motion from current to previous frame\n    Eigen::Isometry3d motion_estimate;\n    // the 6x6 estimate of the covriance [x-y-z, roll-pitch-yaw];\n    Eigen::MatrixXd motion_estimate_covariance;\n\n    Eigen::Matrix3d initial_homography_est;\n    Eigen::Isometry3d initial_motion_estimate;\n    Eigen::MatrixXd initial_motion_cov;\n};\n\n/**\n * \\ingroup FovisCore\n * \\brief Main visual odometry class.\n * \\code\n * #include <fovis/fovis.hpp>\n * \\endcode\n *\n * This is the primary fovis class for estimating visual odometry.\n *  To use it, you'll need three things:\n * \\li a source of grayscale input images.\n * \\li a \\ref DepthSource that can estimate the distance to as many pixels in the input images as possible.\n * \\li a \\ref Rectification object for converting the source image coordinates\n * to a rectified pinhole projection coordinate system.  This is typically used\n * to correct radial lens distortion.\n *\n * A typical use case for the VisualOdometry class is to repeatedly call\n * processFrame() as new image data is available, which estimates the camera\n * motion and makes the resulting estimation data available via accessor\n * methods.\n *\n * Options to control the behavior of the visual odometry algorithm can be\n * passed in to the constructor using a \\ref VisualOdometryOptions object.\n */\nclass VisualOdometry\n{\n  public:\n    /**\n     * Constructs a new visual odometry estimator.\n     *\n     * \\param rectification specifies the input image dimensions, as well as the\n     * mapping from input image coordinates to rectified image coordinates.\n     * \\param options controls the behavior of the estimation algorithms.  This\n     * is specified as a key/value dictionary.\n     */\n    VisualOdometry(const Rectification* rectification,\n                   const VisualOdometryOptions& options);\n\n    ~VisualOdometry();\n\n    /**\n     * process an input image and estimate the 3D camera motion between \\p gray\n     * and the frame previously passed to this method.  The estimated motion\n     * for the very first frame will always be the identity transform.\n     *\n     * \\param gray a new input image.  The image dimensions must match those\n     * passed in to the constructor, and the image data must be stored in\n     * row-major order, with no pad bytes between rows.  An internal copy of\n     * the image is made, and the input data is no longer needed once this\n     * method returns.\n     * \\param depth_source a source of depth information that can either\n     * provide a depth estimate at each pixel of the input image, or report\n     * that no depth estimate is available.\n     */\n    void processFrame(const uint8_t* gray, DepthSource* depth_source);\n\n    /**\n     * Retrieves the integrated pose estimate.  On initialization, the camera\n     * is positioned at the origin, with +Z pointing along the camera look\n     * vector, +X to the right, and +Y down.\n     */\n    const Eigen::Isometry3d& getPose() {\n      return _p->pose;\n    }\n\n    /**\n     * Retrieve the current reference frame used for motion estimation.  The\n     * reference frame will not change as long as new input frames are easily\n     * matched to it.\n     */\n    const OdometryFrame* getReferenceFrame() const {\n      return _ref_frame;\n    }\n\n    /**\n     * Retrieve the current target frame used for motion estimation.\n     */\n    const OdometryFrame* getTargetFrame() const {\n      return _cur_frame;\n    }\n\n    /**\n     * If this returns true, then the current target frame will become the\n     * reference frame on the next call to processFrame().\n     */\n    bool getChangeReferenceFrames() const {\n      return _change_reference_frames;\n    }\n\n    /**\n     * \\return whether motion estimation succeeded on the most recent call to\n     * processFrame(), or provides a rough failure reason.\n     */\n    MotionEstimateStatusCode getMotionEstimateStatus() const {\n      return _estimator->getMotionEstimateStatus();\n    }\n\n    /**\n     * \\return the estimated camera motion from the previous frame to the\n     * current frame.\n     */\n    const Eigen::Isometry3d& getMotionEstimate() const {\n      return _p->motion_estimate;\n    }\n\n    /**\n     * \\return the covariance matrix resulting from the final nonlinear\n     * least-squares motion estimation step.\n     */\n    const Eigen::MatrixXd& getMotionEstimateCov() const {\n      return _p->motion_estimate_covariance;\n    }\n\n    /**\n     * \\return the \\ref MotionEstimator object used internally.\n     */\n    const MotionEstimator* getMotionEstimator() const {\n      return _estimator;\n    }\n\n    /**\n     * \\return the threshold used by the FAST feature detector.\n     */\n    int getFastThreshold() const {\n      return _fast_threshold;\n    }\n\n    /**\n     * \\return the 2D homography computed during initial rotation estimation.\n     */\n    const Eigen::Matrix3d & getInitialHomography() const {\n      return _p->initial_homography_est;\n    }\n\n    /**\n     * \\return the options passed in to the constructor.\n     */\n    const VisualOdometryOptions& getOptions() const {\n      return _options;\n    }\n\n    /**\n     * \\return a reasonable set of default options that can be passed in to the\n     * constructor if you don't know or care about the options.\n     */\n    static VisualOdometryOptions getDefaultOptions();\n\n    /**\n     * Performs some internal sanity checks and aborts the program on failure.\n     * This is for debugging only.\n     */\n    void sanityCheck() const;\n\n  private:\n    void prepareFrame(OdometryFrame* frame);\n\n    Eigen::Quaterniond estimateInitialRotation(const OdometryFrame* prev,\n                                               const OdometryFrame* cur,\n                                               const Eigen::Isometry3d\n                                               &init_motion_estimate =\n                                               Eigen::Isometry3d::Identity());\n\n    const Rectification* _rectification;\n\n    OdometryFrame* _ref_frame;\n    OdometryFrame* _prev_frame;\n    OdometryFrame* _cur_frame;\n\n    MotionEstimator* _estimator;\n\n    VisualOdometryPriv* _p;\n\n    bool _change_reference_frames;\n\n    long _frame_count;\n\n    // === tuning parameters ===\n\n    int _feature_window_size;\n\n    int _num_pyramid_levels;\n\n    // initial feature detector threshold\n    int _fast_threshold;\n\n    // params for adaptive feature detector threshold\n    int _fast_threshold_min;\n    int _fast_threshold_max;\n    int _target_pixels_per_feature;\n    float _fast_threshold_adaptive_gain;\n\n    bool _use_adaptive_threshold;\n    bool _use_homography_initialization;\n\n    // if there are least this many inliers in the previous motion estimate,\n    // don't change reference frames.\n    int _ref_frame_change_threshold;\n\n    // Which level of the image pyramid to use for initial rotation estimation\n    int _initial_rotation_pyramid_level;\n\n    VisualOdometryOptions _options;\n};\n\n}\n#endif\n", "meta": {"hexsha": "ef3b1101514282435857fc8a6c40a3199d2b4615", "size": 7597, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "navigation_layer/fovis/libfovis/libfovis/libfovis/visual_odometry.hpp", "max_stars_repo_name": "kartavya2000/Anahita", "max_stars_repo_head_hexsha": "9afbf6c238658188df7d0d97b2fec3bd48028c03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-21T15:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T07:52:10.000Z", "max_issues_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/visual_odometry.hpp", "max_issues_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_issues_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T12:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T09:33:14.000Z", "max_forks_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/visual_odometry.hpp", "max_forks_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_forks_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-09-09T12:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T09:28:19.000Z", "avg_line_length": 30.5100401606, "max_line_length": 107, "alphanum_fraction": 0.6880347506, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1990834329050347}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n#include \"CTCInferenceCodeletTestConnection.hpp\"\n\n#include <poplar/Engine.hpp>\n#include <poplar/Graph.hpp>\n#include <poplar/IPUModel.hpp>\n#include <poplar/Type.hpp>\n\n#include <poplibs_support/TestDevice.hpp>\n#include <poplibs_test/CTCInference.hpp>\n#include <poplibs_test/Util.hpp>\n#include <popops/codelets.hpp>\n#include <poputil/VertexTemplates.hpp>\n\n#include <boost/multi_array.hpp>\n\nusing namespace poplar;\nusing namespace poplar::program;\nusing namespace poplibs_test::ctc;\nusing namespace poplibs_test;\nusing namespace poplibs_test::util;\nusing namespace poplibs_support;\nusing namespace poputil;\n\nnamespace poplibs_test {\nnamespace ctc {\ntemplate <typename PartialsType>\nstatic std::vector<Candidate<PartialsType>>\nrunCodeletCommon(poplar::Graph &graph, poplibs_support::TestDevice &device,\n                 poplibs_support::DeviceType deviceType,\n                 poplar::Type partialsType,\n                 const std::vector<Candidate<PartialsType>> &unsortedCandidates,\n                 unsigned beamwidth, unsigned timestep, bool testReduceVertex,\n                 bool profile) {\n  const auto target = graph.getTarget();\n\n  auto complete = graph.addConstant(UNSIGNED_INT, {}, 0u);\n\n  graph.setTileMapping(complete, 0);\n\n  auto cs = graph.addComputeSet(\"cs\");\n  auto vertex = graph.addVertex(\n      cs, templateVertex(testReduceVertex ? \"popnn::CTCReduceCandidates\"\n                                          : \"popnn::CTCRankCandidates\",\n                         partialsType, UNSIGNED_INT));\n  graph.setTileMapping(vertex, 0);\n\n  const auto totalCandidates = unsortedCandidates.size();\n  graph.setInitialValue(vertex[\"totalCandidates\"], totalCandidates);\n\n  if (!testReduceVertex) {\n    graph.setInitialValue(vertex[\"beamwidth\"], beamwidth);\n    graph.setInitialValue(vertex[\"firstCandidateToRank\"], 0);\n    graph.setInitialValue(vertex[\"lastCandidateToRank\"], totalCandidates);\n\n    graph.connect(vertex[\"complete\"], complete);\n  }\n\n  Sequence uploadProg, downloadProg;\n  std::vector<std::pair<std::string, char *>> tmap;\n\n  auto rawCandidates = createAndConnectCandidates(\n      graph, vertex, \"candidate\", partialsType, {totalCandidates}, uploadProg,\n      downloadProg, tmap);\n\n  std::vector<unsigned> candidateParentIn{};\n  std::vector<unsigned> candidateAddendIn{};\n  std::vector<float> candidateBeamProbNonBlankIn{};\n  std::vector<float> candidateBeamProbBlankIn{};\n  std::vector<float> candidateBeamProbTotalIn{};\n\n  for (unsigned c = 0; c < totalCandidates; c++) {\n    candidateParentIn.push_back(unsortedCandidates[c].beam);\n    candidateAddendIn.push_back(unsortedCandidates[c].addend);\n    candidateBeamProbNonBlankIn.push_back(unsortedCandidates[c].pnb);\n    candidateBeamProbBlankIn.push_back(unsortedCandidates[c].pb);\n    candidateBeamProbTotalIn.push_back(unsortedCandidates[c].pTotal);\n  }\n\n  copy(target, candidateParentIn, UNSIGNED_INT, rawCandidates.parent.get());\n  copy(target, candidateAddendIn, UNSIGNED_INT, rawCandidates.addend.get());\n  copy(target, candidateBeamProbNonBlankIn, partialsType,\n       rawCandidates.probNonBlank.get());\n  copy(target, candidateBeamProbBlankIn, partialsType,\n       rawCandidates.probBlank.get());\n  copy(target, candidateBeamProbTotalIn, partialsType,\n       rawCandidates.probTotal.get().get());\n\n  // Outputs\n  CandidateHandles rawSortedCandidates;\n  if (testReduceVertex) {\n    rawSortedCandidates = createAndConnectCandidates(\n        graph, vertex, \"reducedCandidate\", partialsType, {}, uploadProg,\n        downloadProg, tmap);\n  } else {\n    rawSortedCandidates = createAndConnectCandidates(\n        graph, vertex, \"rankedCandidate\", partialsType, {beamwidth}, uploadProg,\n        downloadProg, tmap);\n  }\n  OptionFlags engineOptions;\n  if (profile) {\n    engineOptions.set(\"debug.instrumentCompute\", \"true\");\n  }\n  Sequence prog;\n  prog.add(Execute(cs));\n  Engine engine(graph, Sequence{uploadProg, prog, downloadProg}, engineOptions);\n  attachStreams(engine, tmap);\n  device.bind([&](const Device &d) {\n    engine.load(d);\n    engine.run();\n  });\n\n  const unsigned outSize = testReduceVertex ? 1 : beamwidth;\n  std::vector<unsigned> candidateParentOut(outSize);\n  std::vector<unsigned> candidateAddendOut(outSize);\n\n  // TODO partialsType == float\n  std::vector<float> candidateBeamProbBlankOut(outSize);\n  std::vector<float> candidateBeamProbNonBlankOut(outSize);\n  std::vector<float> candidateBeamProbTotalOut(outSize);\n\n  copy(target, UNSIGNED_INT, rawSortedCandidates.parent.get(),\n       candidateParentOut);\n  copy(target, UNSIGNED_INT, rawSortedCandidates.addend.get(),\n       candidateAddendOut);\n  copy(target, partialsType, rawSortedCandidates.probNonBlank.get(),\n       candidateBeamProbNonBlankOut);\n  copy(target, partialsType, rawSortedCandidates.probBlank.get(),\n       candidateBeamProbBlankOut);\n  copy(target, partialsType, rawSortedCandidates.probTotal.get().get(),\n       candidateBeamProbTotalOut);\n  if (profile && deviceType != DeviceType::Cpu) {\n    engine.printProfileSummary(std::cout,\n                               OptionFlags{{\"showExecutionSteps\", \"true\"}});\n  }\n  std::vector<Candidate<float>> selectedCandidates;\n  for (unsigned i = 0; i < outSize; i++) {\n    selectedCandidates.push_back({candidateParentOut[i], candidateAddendOut[i],\n                                  candidateBeamProbNonBlankOut[i],\n                                  candidateBeamProbBlankOut[i],\n                                  candidateBeamProbTotalOut[i]});\n  }\n  return selectedCandidates;\n}\n\ntemplate <typename PartialsType>\nstd::vector<Candidate<PartialsType>> runRankCandidatesCodelet(\n    poplar::Graph &graph, poplibs_support::TestDevice &device,\n    poplibs_support::DeviceType deviceType, poplar::Type partialsType,\n    const std::vector<Candidate<PartialsType>> &candidates, unsigned beamwidth,\n    unsigned timestep, bool profile) {\n\n  return runCodeletCommon(graph, device, deviceType, partialsType, candidates,\n                          beamwidth, timestep, false, profile);\n}\n\ntemplate <typename PartialsType>\nstd::vector<Candidate<PartialsType>> runReduceCandidatesCodelet(\n    poplar::Graph &graph, poplibs_support::TestDevice &device,\n    poplibs_support::DeviceType deviceType, poplar::Type partialsType,\n    const std::vector<Candidate<PartialsType>> &candidates, unsigned beamwidth,\n    unsigned timestep, bool profile) {\n\n  return runCodeletCommon(graph, device, deviceType, partialsType, candidates,\n                          beamwidth, timestep, true, profile);\n}\n\ntemplate std::vector<Candidate<float>> runRankCandidatesCodelet(\n    poplar::Graph &graph, poplibs_support::TestDevice &device,\n    poplibs_support::DeviceType deviceType, poplar::Type partialsType,\n    const std::vector<Candidate<float>> &candidates, unsigned beamwidth,\n    unsigned timestep, bool profile);\n\ntemplate std::vector<Candidate<float>> runReduceCandidatesCodelet(\n    poplar::Graph &graph, poplibs_support::TestDevice &device,\n    poplibs_support::DeviceType deviceType, poplar::Type partialsType,\n    const std::vector<Candidate<float>> &candidates, unsigned beamwidth,\n    unsigned timestep, bool profile);\n\n} // namespace ctc\n} // namespace poplibs_test\n", "meta": {"hexsha": "ca671a3b83a6d1efb753e23de4373bca96f23f50", "size": 7203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popnn/codelets/CTCInferenceRankAndReduceCandidates.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": "tests/popnn/codelets/CTCInferenceRankAndReduceCandidates.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": "tests/popnn/codelets/CTCInferenceRankAndReduceCandidates.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.5769230769, "max_line_length": 80, "alphanum_fraction": 0.7270581702, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1990834329050347}}
{"text": "// Copyright (c) 2012-2013 The PPCoin 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 <boost/assign/list_of.hpp>\n\n#include \"kernel.h\"\n#include \"db.h\"\n\nusing namespace std;\n\nextern int nStakeMaxAge;\nextern int nStakeTargetSpacing;\n\n// Modifier interval: time to elapse before new modifier is computed\n// Set to 6-hour for production network and 20-minute for test network\nunsigned int nModifierInterval = MODIFIER_INTERVAL;\n\n// Hard checkpoints of stake modifiers to ensure they are deterministic\nstatic std::map<int, unsigned int> mapStakeModifierCheckpoints =\n    boost::assign::map_list_of\n    ( 0, 0x0e00670bu )\n    ;\n\n// Get the last stake modifier and its generation time from a given block\nstatic bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)\n{\n    if (!pindex)\n        return error(\"GetLastStakeModifier: null pindex\");\n    while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())\n        pindex = pindex->pprev;\n    if (!pindex->GeneratedStakeModifier())\n        return error(\"GetLastStakeModifier: no generation at genesis block\");\n    nStakeModifier = pindex->nStakeModifier;\n    nModifierTime = pindex->GetBlockTime();\n    return true;\n}\n\n// Get selection interval section (in seconds)\nstatic int64 GetStakeModifierSelectionIntervalSection(int nSection)\n{\n    assert (nSection >= 0 && nSection < 64);\n    return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));\n}\n\n// Get stake modifier selection interval (in seconds)\nstatic int64 GetStakeModifierSelectionInterval()\n{\n    int64 nSelectionInterval = 0;\n    for (int nSection=0; nSection<64; nSection++)\n        nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);\n    return nSelectionInterval;\n}\n\n// select a block from the candidate blocks in vSortedByTimestamp, excluding\n// already selected blocks in vSelectedBlocks, and with timestamp up to\n// nSelectionIntervalStop.\nstatic bool SelectBlockFromCandidates(\n    vector<pair<int64, uint256> >& vSortedByTimestamp,\n    map<uint256, const CBlockIndex*>& mapSelectedBlocks,\n    int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,\n    const CBlockIndex** pindexSelected)\n{\n    bool fSelected = false;\n    uint256 hashBest = 0;\n    *pindexSelected = (const CBlockIndex*) 0;\n    BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)\n    {\n        if (!mapBlockIndex.count(item.second))\n            return error(\"SelectBlockFromCandidates: failed to find block index for candidate block %s\", item.second.ToString().c_str());\n        const CBlockIndex* pindex = mapBlockIndex[item.second];\n        if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)\n            break;\n        if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)\n            continue;\n        // compute the selection hash by hashing its proof-hash and the\n        // previous proof-of-stake modifier\n        uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();\n        CDataStream ss(SER_GETHASH, 0);\n        ss << hashProof << nStakeModifierPrev;\n        uint256 hashSelection = Hash(ss.begin(), ss.end());\n        // the selection hash is divided by 2**32 so that proof-of-stake block\n        // is always favored over proof-of-work block. this is to preserve\n        // the energy efficiency property\n        if (pindex->IsProofOfStake())\n            hashSelection >>= 32;\n        if (fSelected && hashSelection < hashBest)\n        {\n            hashBest = hashSelection;\n            *pindexSelected = (const CBlockIndex*) pindex;\n        }\n        else if (!fSelected)\n        {\n            fSelected = true;\n            hashBest = hashSelection;\n            *pindexSelected = (const CBlockIndex*) pindex;\n        }\n    }\n    if (fDebug && GetBoolArg(\"-printstakemodifier\"))\n        printf(\"SelectBlockFromCandidates: selection hash=%s\\n\", hashBest.ToString().c_str());\n    return fSelected;\n}\n\n// Stake Modifier (hash modifier of proof-of-stake):\n// The purpose of stake modifier is to prevent a txout (coin) owner from\n// computing future proof-of-stake generated by this txout at the time\n// of transaction confirmation. To meet kernel protocol, the txout\n// must hash with a future stake modifier to generate the proof.\n// Stake modifier consists of bits each of which is contributed from a\n// selected block of a given block group in the past.\n// The selection of a block is based on a hash of the block's proof-hash and\n// the previous stake modifier.\n// Stake modifier is recomputed at a fixed time interval instead of every \n// block. This is to make it difficult for an attacker to gain control of\n// additional bits in the stake modifier, even after generating a chain of\n// blocks.\nbool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)\n{\n    nStakeModifier = 0;\n    fGeneratedStakeModifier = false;\n    if (!pindexPrev)\n    {\n        fGeneratedStakeModifier = true;\n        return true;  // genesis block's modifier is 0\n    }\n    // First find current stake modifier and its generation block time\n    // if it's not old enough, return the same stake modifier\n    int64 nModifierTime = 0;\n    if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))\n        return error(\"ComputeNextStakeModifier: unable to get last modifier\");\n    if (fDebug)\n    {\n        printf(\"ComputeNextStakeModifier: prev modifier=0x%016\"PRI64x\" time=%s\\n\", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());\n    }\n    if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)\n        return true;\n\n    // Sort candidate blocks by timestamp\n    vector<pair<int64, uint256> > vSortedByTimestamp;\n    vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);\n    int64 nSelectionInterval = GetStakeModifierSelectionInterval();\n    int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;\n    const CBlockIndex* pindex = pindexPrev;\n    while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)\n    {\n        vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));\n        pindex = pindex->pprev;\n    }\n    int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;\n    reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());\n    sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());\n\n    // Select 64 blocks from candidate blocks to generate stake modifier\n    uint64 nStakeModifierNew = 0;\n    int64 nSelectionIntervalStop = nSelectionIntervalStart;\n    map<uint256, const CBlockIndex*> mapSelectedBlocks;\n    for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)\n    {\n        // add an interval section to the current selection round\n        nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);\n        // select a block from the candidates of current round\n        if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))\n            return error(\"ComputeNextStakeModifier: unable to select block at round %d\", nRound);\n        // write the entropy bit of the selected block\n        nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);\n        // add the selected block from candidates to selected list\n        mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));\n        if (fDebug && GetBoolArg(\"-printstakemodifier\"))\n            printf(\"ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\\n\",\n                nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());\n    }\n\n    // Print selection map for visualization of the selected blocks\n    if (fDebug && GetBoolArg(\"-printstakemodifier\"))\n    {\n        string strSelectionMap = \"\";\n        // '-' indicates proof-of-work blocks not selected\n        strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');\n        pindex = pindexPrev;\n        while (pindex && pindex->nHeight >= nHeightFirstCandidate)\n        {\n            // '=' indicates proof-of-stake blocks not selected\n            if (pindex->IsProofOfStake())\n                strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, \"=\");\n            pindex = pindex->pprev;\n        }\n        BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)\n        {\n            // 'S' indicates selected proof-of-stake blocks\n            // 'W' indicates selected proof-of-work blocks\n            strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? \"S\" : \"W\");\n        }\n        printf(\"ComputeNextStakeModifier: selection height [%d, %d] map %s\\n\", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());\n    }\n    if (fDebug)\n    {\n        printf(\"ComputeNextStakeModifier: new modifier=0x%016\"PRI64x\" time=%s\\n\", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());\n    }\n\n    nStakeModifier = nStakeModifierNew;\n    fGeneratedStakeModifier = true;\n    return true;\n}\n\n// The stake modifier used to hash for a stake kernel is chosen as the stake\n// modifier about a selection interval later than the coin generating the kernel\nstatic bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)\n{\n    nStakeModifier = 0;\n    if (!mapBlockIndex.count(hashBlockFrom))\n        return error(\"GetKernelStakeModifier() : block not indexed\");\n    const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];\n    nStakeModifierHeight = pindexFrom->nHeight;\n    nStakeModifierTime = pindexFrom->GetBlockTime();\n    int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();\n    const CBlockIndex* pindex = pindexFrom;\n    // loop to find the stake modifier later by a selection interval\n    while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)\n    {\n        if (!pindex->pnext)\n        {   // reached best block; may happen if node is behind on block chain\n            if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))\n                return error(\"GetKernelStakeModifier() : reached best block %s at height %d from block %s\",\n                    pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());\n            else\n                return false;\n        }\n        pindex = pindex->pnext;\n        if (pindex->GeneratedStakeModifier())\n        {\n            nStakeModifierHeight = pindex->nHeight;\n            nStakeModifierTime = pindex->GetBlockTime();\n        }\n    }\n    nStakeModifier = pindex->nStakeModifier;\n    return true;\n}\n\n// nexus kernel protocol\n// coinstake must meet hash target according to the protocol:\n// kernel (input 0) must meet the formula\n//     hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight\n// this ensures that the chance of getting a coinstake is proportional to the\n// amount of coin age one owns.\n// The reason this hash is chosen is the following:\n//   nStakeModifier: \n//       (v0.3) scrambles computation to make it very difficult to precompute\n//              future proof-of-stake at the time of the coin's confirmation\n//       (v0.2) nBits (deprecated): encodes all past block timestamps\n//   txPrev.block.nTime: prevent nodes from guessing a good timestamp to\n//                       generate transaction for future advantage\n//   txPrev.offset: offset of txPrev inside block, to reduce the chance of \n//                  nodes generating coinstake at the same time\n//   txPrev.nTime: reduce the chance of nodes generating coinstake at the same\n//                 time\n//   txPrev.vout.n: output number of txPrev, to reduce the chance of nodes\n//                  generating coinstake at the same time\n//   block/tx hash should not be used here as they can be generated in vast\n//   quantities so as to generate blocks faster, degrading the system back into\n//   a proof-of-work situation.\n//\nbool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, bool fPrintProofOfStake)\n{\n    if (nTimeTx < txPrev.nTime)  // Transaction timestamp violation\n        return error(\"CheckStakeKernelHash() : nTime violation\");\n\n    unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();\n    if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement\n        return error(\"CheckStakeKernelHash() : min age violation\");\n\n    CBigNum bnTargetPerCoinDay;\n    bnTargetPerCoinDay.SetCompact(nBits);\n    int64 nValueIn = txPrev.vout[prevout.n].nValue;\n\n    // v0.3 protocol kernel hash weight starts from 0 at the 30-day min age\n    // this change increases active coins participating the hash and helps\n    // to secure the network when proof-of-stake difficulty is low\n    int64 nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;\n    CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);\n\n    // Calculate hash\n    CDataStream ss(SER_GETHASH, 0);\n    uint64 nStakeModifier = 0;\n    int nStakeModifierHeight = 0;\n    int64 nStakeModifierTime = 0;\n\n    if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))\n        return false;\n    ss << nStakeModifier;\n\n    ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;\n    hashProofOfStake = Hash(ss.begin(), ss.end());\n    if (fPrintProofOfStake)\n    {\n        printf(\"CheckStakeKernelHash() : using modifier 0x%016\"PRI64x\" at height=%d timestamp=%s for block from height=%d timestamp=%s\\n\",\n            nStakeModifier, nStakeModifierHeight,\n            DateTimeStrFormat(nStakeModifierTime).c_str(),\n            mapBlockIndex[blockFrom.GetHash()]->nHeight,\n            DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());\n        printf(\"CheckStakeKernelHash() : check protocol=%s modifier=0x%016\"PRI64x\" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\\n\",\n            \"0.3\",\n            nStakeModifier,\n            nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,\n            hashProofOfStake.ToString().c_str());\n    }\n\n    // Now check if proof-of-stake hash meets target protocol\n    if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)\n        return false;\n    if (fDebug && !fPrintProofOfStake)\n    {\n        printf(\"CheckStakeKernelHash() : using modifier 0x%016\"PRI64x\" at height=%d timestamp=%s for block from height=%d timestamp=%s\\n\",\n            nStakeModifier, nStakeModifierHeight, \n            DateTimeStrFormat(nStakeModifierTime).c_str(),\n            mapBlockIndex[blockFrom.GetHash()]->nHeight,\n            DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());\n        printf(\"CheckStakeKernelHash() : pass protocol=%s modifier=0x%016\"PRI64x\" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\\n\",\n            \"0.3\",\n            nStakeModifier,\n            nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,\n            hashProofOfStake.ToString().c_str());\n    }\n    return true;\n}\n\n// Check kernel hash target and coinstake signature\nbool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake)\n{\n    if (!tx.IsCoinStake())\n        return error(\"CheckProofOfStake() : called on non-coinstake %s\", tx.GetHash().ToString().c_str());\n\n    // Kernel (input 0) must match the stake hash target per coin age (nBits)\n    const CTxIn& txin = tx.vin[0];\n\n    // First try finding the previous transaction in database\n    CTxDB txdb(\"r\");\n    CTransaction txPrev;\n    CTxIndex txindex;\n    if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))\n        return tx.DoS(1, error(\"CheckProofOfStake() : INFO: read txPrev failed\"));  // previous transaction not in main chain, may occur during initial download\n    txdb.Close();\n\n    // Verify signature\n    if (!VerifySignature(txPrev, tx, 0, true, 0))\n        return tx.DoS(100, error(\"CheckProofOfStake() : VerifySignature failed on coinstake %s\", tx.GetHash().ToString().c_str()));\n\n    // Read block header\n    CBlock block;\n    if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))\n        return fDebug? error(\"CheckProofOfStake() : read block failed\") : false; // unable to read block of previous transaction\n\n    if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, fDebug))\n        return tx.DoS(1, error(\"CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s\", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync\n\n    return true;\n}\n\n// Check whether the coinstake timestamp meets protocol\nbool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)\n{\n    // v0.3 protocol\n    return (nTimeBlock == nTimeTx);\n}\n\n// Get stake modifier checksum\nunsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)\n{\n    assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));\n    // Hash previous checksum with flags, hashProofOfStake and nStakeModifier\n    CDataStream ss(SER_GETHASH, 0);\n    if (pindex->pprev)\n        ss << pindex->pprev->nStakeModifierChecksum;\n    ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;\n    uint256 hashChecksum = Hash(ss.begin(), ss.end());\n    hashChecksum >>= (256 - 32);\n    return hashChecksum.Get64();\n}\n\n// Check stake modifier hard checkpoints\nbool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)\n{\n    if (fTestNet) return true; // Testnet has no checkpoints\n    if (mapStakeModifierCheckpoints.count(nHeight))\n        return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];\n    return true;\n}\n", "meta": {"hexsha": "4f364df39d8b2c9665d93d0ccef44593663f4a8c", "size": 18533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kernel.cpp", "max_stars_repo_name": "Skryptex/Nexus-Proof-of-Stake-Coin", "max_stars_repo_head_hexsha": "4aa4d86adcda4c10fa2fdc5139632f2a264ea08c", "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/kernel.cpp", "max_issues_repo_name": "Skryptex/Nexus-Proof-of-Stake-Coin", "max_issues_repo_head_hexsha": "4aa4d86adcda4c10fa2fdc5139632f2a264ea08c", "max_issues_repo_licenses": ["MIT"], "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/kernel.cpp", "max_forks_repo_name": "Skryptex/Nexus-Proof-of-Stake-Coin", "max_forks_repo_head_hexsha": "4aa4d86adcda4c10fa2fdc5139632f2a264ea08c", "max_forks_repo_licenses": ["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.8888888889, "max_line_length": 253, "alphanum_fraction": 0.7015593806, "num_tokens": 4716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.19908342921189096}}
{"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#include <vw/Cartography/PointImageManipulation.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nusing namespace vw;\n\nVector3 cartography::GeodeticToCartesian::operator()( Vector3 const& v ) const {\n  if ( boost::math::isnan(v[2]) )\n    return Vector3();\n  return m_datum.geodetic_to_cartesian(v);\n}\n\nVector3 cartography::CartesianToGeodetic::operator()( Vector3 const& v ) const {\n  if ( v == Vector3() )\n    return Vector3(0,0,std::numeric_limits<double>::quiet_NaN());\n  return m_datum.cartesian_to_geodetic(v);\n}\n\nVector3 cartography::GeodeticToProjection::operator()( Vector3 const& v ) const {\n  if ( boost::math::isnan(v[2]) )\n    return v;\n  Vector2 pix = m_reference.lonlat_to_pixel( subvector(v, 0, 2) );\n  return Vector3( pix[0], pix[1], v[2] );\n}\n\nVector3 cartography::ProjectionToGeodetic::operator()( Vector3 const& v ) const {\n  Vector2 ll = m_reference.pixel_to_lonlat( subvector( v, 0, 2 ) );\n  return Vector3( ll[0], ll[1], v[2] );\n}\n\nVector3 cartography::GeodeticToPoint::operator()( Vector3 const& v ) const {\n  if ( boost::math::isnan(v[2]) )\n    return v;\n  Vector2 pix = m_reference.lonlat_to_point( subvector(v, 0, 2) );\n  return Vector3( pix[0], pix[1], v[2] );\n}\n\nVector3 cartography::PointToGeodetic::operator()( Vector3 const& v ) const {\n  Vector2 ll = m_reference.point_to_lonlat( subvector( v, 0, 2 ) );\n  return Vector3( ll[0], ll[1], v[2] );\n}\n", "meta": {"hexsha": "e925f49edbcfa4c32a5e99f2700ba464212b59eb", "size": 2191, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Cartography/PointImageManipulation.cc", "max_stars_repo_name": "maxerbubba/visionworkbench", "max_stars_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 318.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T16:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T07:12:20.000Z", "max_issues_repo_path": "src/vw/Cartography/PointImageManipulation.cc", "max_issues_repo_name": "maxerbubba/visionworkbench", "max_issues_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-07-30T22:22:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T16:11:55.000Z", "max_forks_repo_path": "src/vw/Cartography/PointImageManipulation.cc", "max_forks_repo_name": "maxerbubba/visionworkbench", "max_forks_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T00:57:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T13:51:40.000Z", "avg_line_length": 37.1355932203, "max_line_length": 81, "alphanum_fraction": 0.7161113647, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.19908342551874725}}
{"text": "#include \"blob.h\"\n#include \"adafFunctions.h\"\n#include \"globalVariables.h\"\n#include \"State.h\"\n#include <fparameters/parameters.h>\n#include <iostream>\n#include <boost/property_tree/ptree.hpp>\n\nvoid blob(State& st)\n{\n\tfactorDensity = GlobalConfig.get<double>(\"factorDensity\");\n\t//tAccBlob = GlobalConfig.get<double>(\"tAccBlob\");    // [lightcurve variability time in sec]\n\t//double tFlare = 5000.0;\n\tdouble sumt = 0.0;\n\tdouble pasoRaux = pow(100.0,1.0/1000);\n\trBlob = schwRadius*1.1;\n\twhile ( sumt < timeAfterFlare) {\n\t\tdouble dr = rBlob*(pasoRaux-1.0);\n\t\tsumt += dr / (-radialVel(rBlob));\n\t\trBlob *= pasoRaux;\n\t}\n\tstd::cout << \"rBlob = \" << rBlob/schwRadius << endl;\n}", "meta": {"hexsha": "0ebc9a767eb419549e21273ffbb971436bb48367", "size": 666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/blob.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/blob.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/blob.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": 28.9565217391, "max_line_length": 94, "alphanum_fraction": 0.6876876877, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.30074557267388247, "lm_q1q2_score": 0.1990703743634497}}
{"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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n\n#include <limits>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"tudat/simulation/estimation_setup/orbitDeterminationTestCases.h\"\n\n\nnamespace tudat\n{\nnamespace unit_tests\n{\nBOOST_AUTO_TEST_SUITE( test_estimation_from_positions )\n\n\n\n//! This test checks, for double states/observables and Time time, if the orbit determination correctly converges\n//! when simulating data, perturbing the dynamical parameters, and then retrieving the original parameters\nBOOST_AUTO_TEST_CASE( test_EstimationFromPosition )\n{\n    for( int simulationType = 0; simulationType < 4; simulationType++ )\n    {\n        std::cout << \"=============================================== Running Case: \" << simulationType << std::endl;\n\n        // Simulate estimated parameter error.\n        Eigen::VectorXd totalError;\n\n        totalError = executePlanetaryParameterEstimation< Time, double >( simulationType ).second;\n\n        // Adjust tolerance based on simulation settings\n        double toleranceMultiplier = 20.0;\n\n\n        // Check error.\n        for( unsigned int j = 0; j < 3; j++ )\n        {\n            BOOST_CHECK_SMALL( totalError( j ), toleranceMultiplier * 5.0E-3 );\n        }\n\n        for( unsigned int j = 0; j < 3; j++ )\n        {\n            BOOST_CHECK_SMALL( totalError( j + 3 ), toleranceMultiplier * 1.0E-7 );\n        }\n\n        BOOST_CHECK_SMALL( totalError( 6 ), toleranceMultiplier * 1.0E3 );\n        std::cout << totalError.transpose( ) << std::endl;\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n}\n\n}\n\n\n", "meta": {"hexsha": "2960c644144c52018ccbd47dd424e97be84c1d84", "size": 1978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/orbit_determination/unitTestEstimationFromIdealDataTimeDouble.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": "tests/src/astro/orbit_determination/unitTestEstimationFromIdealDataTimeDouble.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": "tests/src/astro/orbit_determination/unitTestEstimationFromIdealDataTimeDouble.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": 28.2571428571, "max_line_length": 117, "alphanum_fraction": 0.6648129424, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.19900811535058147}}
{"text": "#pragma once\n\n#include <memory>\n\n#include <boost/dynamic_bitset.hpp>\n\n#include \"abstract_cardinality_estimator.hpp\"\n#include \"operators/operator_scan_predicate.hpp\"\n#include \"statistics/statistics_objects/abstract_histogram.hpp\"\n#include \"statistics/statistics_objects/generic_histogram_builder.hpp\"\n\nnamespace opossum {\n\ntemplate <typename T>\nclass AbstractHistogram;\ntemplate <typename T>\nclass GenericHistogram;\ntemplate <typename T>\nclass AttributeStatistics;\nclass AliasNode;\nclass ProjectionNode;\nclass AggregateNode;\nclass ValidateNode;\nclass PredicateNode;\nclass JoinNode;\nclass UnionNode;\nclass LimitNode;\n\n/**\n * Hyrise's default, statistics-based cardinality estimator\n */\nclass CardinalityEstimator : public AbstractCardinalityEstimator {\n public:\n  std::shared_ptr<AbstractCardinalityEstimator> new_instance() const override;\n\n  Cardinality estimate_cardinality(const std::shared_ptr<const AbstractLQPNode>& lqp) const override;\n  std::shared_ptr<TableStatistics> estimate_statistics(const std::shared_ptr<const AbstractLQPNode>& lqp) const;\n\n  /**\n   * Per-node-type estimation functions\n   * @{\n   */\n  static std::shared_ptr<TableStatistics> estimate_alias_node(\n      const AliasNode& alias_node, const std::shared_ptr<TableStatistics>& input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_projection_node(\n      const ProjectionNode& projection_node, const std::shared_ptr<TableStatistics>& input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_aggregate_node(\n      const AggregateNode& aggregate_node, const std::shared_ptr<TableStatistics>& input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_validate_node(\n      const ValidateNode& validate_node, const std::shared_ptr<TableStatistics>& input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_predicate_node(\n      const PredicateNode& predicate_node, const std::shared_ptr<TableStatistics>& input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_join_node(\n      const JoinNode& join_node, const std::shared_ptr<TableStatistics>& left_input_table_statistics,\n      const std::shared_ptr<TableStatistics>& right_input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_union_node(\n      const UnionNode& union_node, const std::shared_ptr<TableStatistics>& left_input_table_statistics,\n      const std::shared_ptr<TableStatistics>& right_input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_limit_node(\n      const LimitNode& limit_node, const std::shared_ptr<TableStatistics>& input_table_statistics);\n  /** @} */\n\n  /**\n   * Filter estimations\n   * @{\n   */\n\n  /**\n   * Estimate a simple scanning predicate. This function analyses the given predicate and dispatches the actual\n   * estimation algorithm.\n   */\n  static std::shared_ptr<TableStatistics> estimate_operator_scan_predicate(\n      const std::shared_ptr<TableStatistics>& input_table_statistics, const OperatorScanPredicate& predicate);\n\n  /**\n   * Estimation of an equi scan between two histograms. Estimating equi scans without correlation information is\n   * impossible, so this function is restricted to computing an upper bound of the resulting histogram.\n   */\n  template <typename T>\n  static std::shared_ptr<GenericHistogram<T>> estimate_column_vs_column_equi_scan_with_histograms(\n      const AbstractHistogram<T>& left_histogram, const AbstractHistogram<T>& right_histogram) {\n    /**\n     * Column-to-column scan estimation is notoriously hard, selectivities from 0 to 1 are possible for the same histogram\n     * pairs.\n     * Thus, we do the most conservative estimation and compute the upper bound of value- and distinct counts for each\n     * bin pair.\n     */\n\n    auto left_idx = BinID{0};\n    auto right_idx = BinID{0};\n    auto left_bin_count = left_histogram.bin_count();\n    auto right_bin_count = right_histogram.bin_count();\n\n    GenericHistogramBuilder<T> builder;\n\n    for (; left_idx < left_bin_count && right_idx < right_bin_count;) {\n      const auto& left_min = left_histogram.bin_minimum(left_idx);\n      const auto& right_min = right_histogram.bin_minimum(right_idx);\n\n      if (left_min < right_min) {\n        ++left_idx;\n        continue;\n      }\n\n      if (right_min < left_min) {\n        ++right_idx;\n        continue;\n      }\n\n      DebugAssert(left_histogram.bin_maximum(left_idx) == right_histogram.bin_maximum(right_idx),\n                  \"Histogram bin boundaries do not match\");\n\n      const auto height = std::min(left_histogram.bin_height(left_idx), right_histogram.bin_height(right_idx));\n      const auto distinct_count =\n          std::min(left_histogram.bin_distinct_count(left_idx), right_histogram.bin_distinct_count(right_idx));\n\n      if (height > 0 && distinct_count > 0) {\n        builder.add_bin(left_min, left_histogram.bin_maximum(left_idx), height, distinct_count);\n      }\n\n      ++left_idx;\n      ++right_idx;\n    }\n\n    if (builder.empty()) {\n      return nullptr;\n    }\n\n    return builder.build();\n  }\n  /** @} */\n\n  /**\n   * Join estimations\n   * @{\n   */\n  static std::shared_ptr<TableStatistics> estimate_inner_equi_join(const ColumnID left_column_id,\n                                                                   const ColumnID right_column_id,\n                                                                   const TableStatistics& left_input_table_statistics,\n                                                                   const TableStatistics& right_input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_semi_join(const ColumnID left_column_id,\n                                                             const ColumnID right_column_id,\n                                                             const TableStatistics& left_input_table_statistics,\n                                                             const TableStatistics& right_input_table_statistics);\n\n  static std::shared_ptr<TableStatistics> estimate_cross_join(const TableStatistics& left_input_table_statistics,\n                                                              const TableStatistics& right_input_table_statistics);\n\n  template <typename T>\n  static std::shared_ptr<GenericHistogram<T>> estimate_inner_equi_join_with_histograms(\n      const AbstractHistogram<T>& left_histogram, const AbstractHistogram<T>& right_histogram) {\n    /**\n     * left_histogram and right_histogram are turned into \"unified\" histograms by `split_at_bin_bounds`, meaning that\n     * their bins are split so that their bin boundaries match.\n     * E.g., if left_histogram has a single bin [1, 10] and right histogram has a single bin [5, 20] then\n     * unified_left_histogram == {[1, 4], [5, 10]}\n     * unified_right_histogram == {[5, 10], [11, 20]}\n     * The estimation is performed on overlapping bins only, e.g., only the two bins [5, 10] will produce matches.\n     */\n\n    auto unified_left_histogram = left_histogram.split_at_bin_bounds(right_histogram.bin_bounds());\n    auto unified_right_histogram = right_histogram.split_at_bin_bounds(left_histogram.bin_bounds());\n\n    auto left_idx = BinID{0};\n    auto right_idx = BinID{0};\n    auto left_bin_count = unified_left_histogram->bin_count();\n    auto right_bin_count = unified_right_histogram->bin_count();\n\n    GenericHistogramBuilder<T> builder;\n\n    // Iterate over both unified histograms and find overlapping bins\n    for (; left_idx < left_bin_count && right_idx < right_bin_count;) {\n      const auto& left_min = unified_left_histogram->bin_minimum(left_idx);\n      const auto& right_min = unified_right_histogram->bin_minimum(right_idx);\n\n      if (left_min < right_min) {\n        ++left_idx;\n        continue;\n      }\n\n      if (right_min < left_min) {\n        ++right_idx;\n        continue;\n      }\n\n      DebugAssert(unified_left_histogram->bin_maximum(left_idx) == unified_right_histogram->bin_maximum(right_idx),\n                  \"Histogram bin boundaries do not match\");\n\n      // Overlapping bins found, estimate the join for these bins' range\n      const auto [height, distinct_count] = estimate_inner_equi_join_of_bins(  // NOLINT\n          unified_left_histogram->bin_height(left_idx), unified_left_histogram->bin_distinct_count(left_idx),\n          unified_right_histogram->bin_height(right_idx), unified_right_histogram->bin_distinct_count(right_idx));\n\n      if (height > 0) {\n        builder.add_bin(left_min, unified_left_histogram->bin_maximum(left_idx), height, distinct_count);\n      }\n\n      ++left_idx;\n      ++right_idx;\n    }\n\n    return builder.build();\n  }\n\n  /**\n   * Given two HistogramBins with equal bounds and the specified height and distinct counts, estimate the number of\n   * matches and distinct values for an equi-inner join of these two bins using a principle-of-inclusion estimation.\n   * @return {estimated_height, estimated_distinct_count}\n   */\n  static std::pair<HistogramCountType, HistogramCountType> estimate_inner_equi_join_of_bins(\n      const float left_height, const float left_distinct_count, const float right_height,\n      const float right_distinct_count);\n\n  /** @} */\n\n  /**\n   * Helper\n   * @{\n   */\n  static std::shared_ptr<TableStatistics> prune_column_statistics(\n      const std::shared_ptr<TableStatistics>& table_statistics, const std::vector<ColumnID>& pruned_column_ids);\n\n  /** @} */\n};\n}  // namespace opossum\n", "meta": {"hexsha": "2f36aea24f6159d6b587ae44723cf3413630b680", "size": 9398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/statistics/cardinality_estimator.hpp", "max_stars_repo_name": "mrcl-tst/hyrise", "max_stars_repo_head_hexsha": "eec50b39de9f530b0a1732ceb5822b7222f3fe17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 583.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T00:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:24:30.000Z", "max_issues_repo_path": "src/lib/statistics/cardinality_estimator.hpp", "max_issues_repo_name": "mrcl-tst/hyrise", "max_issues_repo_head_hexsha": "eec50b39de9f530b0a1732ceb5822b7222f3fe17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1573.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:47:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:48:03.000Z", "max_forks_repo_path": "src/lib/statistics/cardinality_estimator.hpp", "max_forks_repo_name": "mrcl-tst/hyrise", "max_forks_repo_head_hexsha": "eec50b39de9f530b0a1732ceb5822b7222f3fe17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 145.0, "max_forks_repo_forks_event_min_datetime": "2015-03-09T16:26:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:53:23.000Z", "avg_line_length": 40.1623931624, "max_line_length": 122, "alphanum_fraction": 0.7097254735, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19900811325965842}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2015.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Clemens Groepl $\n// $Authors: $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/EmgFitter1D.h>\n#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/InterpolationModel.h>\n#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>\n#include <OpenMS/CONCEPT/Constants.h>\n#include <OpenMS/CONCEPT/Factory.h>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace OpenMS\n{\n  int EmgFitter1D::EgmFitterFunctor::operator()(const Eigen::VectorXd& x, Eigen::VectorXd& fvec)\n  {\n    Size n = m_data->n;\n    EmgFitter1D::RawDataArrayType set = m_data->set;\n\n    EmgFitter1D::CoordinateType h = x(0);\n    EmgFitter1D::CoordinateType w = x(1);\n    EmgFitter1D::CoordinateType s = x(2);\n    EmgFitter1D::CoordinateType z = x(3);\n\n    EmgFitter1D::CoordinateType Yi = 0.0;\n\n    // iterate over all points of the signal\n    for (Size i = 0; i < n; i++)\n    {\n      double t = set[i].getPos();\n\n      // Simplified EMG\n      Yi = (h * w / s) * sqrt(2.0 * Constants::PI) * exp((pow(w, 2) / (2 * pow(s, 2))) - ((t - z) / s)) / (1 + exp((-2.4055 / sqrt(2.0)) * (((t - z) / w) - w / s)));\n\n      fvec(i) = Yi - set[i].getIntensity();\n    }\n    return 0;\n  }\n\n  // compute Jacobian matrix for the different parameters\n  int EmgFitter1D::EgmFitterFunctor::df(const Eigen::VectorXd& x, Eigen::MatrixXd& J)\n  {\n    Size n =  m_data->n;\n    EmgFitter1D::RawDataArrayType set = m_data->set;\n\n    EmgFitter1D::CoordinateType h = x(0);\n    EmgFitter1D::CoordinateType w = x(1);\n    EmgFitter1D::CoordinateType s = x(2);\n    EmgFitter1D::CoordinateType z = x(3);\n\n    const EmgFitter1D::CoordinateType emg_const = 2.4055;\n    const EmgFitter1D::CoordinateType sqrt_2pi = sqrt(2 * Constants::PI);\n    const EmgFitter1D::CoordinateType sqrt_2 = sqrt(2.0);\n\n    EmgFitter1D::CoordinateType exp1, exp2, exp3 = 0.0;\n    EmgFitter1D::CoordinateType derivative_height, derivative_width, derivative_symmetry, derivative_retention = 0.0;\n\n    // iterate over all points of the signal\n    for (Size i = 0; i < n; i++)\n    {\n      EmgFitter1D::CoordinateType t = set[i].getPos();\n\n      exp1 = exp(((w * w) / (2 * s * s)) - ((t - z) / s));\n      exp2 = (1 + exp((-emg_const / sqrt_2) * (((t - z) / w) - w / s)));\n      exp3 = exp((-emg_const / sqrt_2) * (((t - z) / w) - w / s));\n\n      // f'(h)\n      derivative_height = w / s * sqrt_2pi * exp1 / exp2;\n\n      // f'(h)\n      derivative_width = h / s * sqrt_2pi * exp1 / exp2 + (h * w * w) / (s * s * s) * sqrt_2pi * exp1 / exp2 + (emg_const * h * w) / s * sqrt_2pi * exp1 * (-(t - z) / (w * w) - 1 / s) * exp3 / ((exp2 * exp2) * sqrt_2);\n\n      // f'(s)\n      derivative_symmetry = -h * w / (s * s) * sqrt_2pi * exp1 / exp2 + h * w / s * sqrt_2pi * (-(w * w) / (s * s * s) + (t - z) / (s * s)) * exp1 / exp2 + (emg_const * h * w * w) / (s * s * s) * sqrt_2pi * exp1 * exp3 / ((exp2 * exp2) * sqrt_2);\n\n      // f'(z)\n      derivative_retention = h * w / (s * s) * sqrt_2pi * exp1 / exp2 - (emg_const * h) / s * sqrt_2pi * exp1 * exp3 / ((exp2 * exp2) * sqrt_2);\n\n      // set the jacobian matrix\n      J(i, 0) = derivative_height;\n      J(i, 1) = derivative_width;\n      J(i, 2) = derivative_symmetry;\n      J(i, 3) = derivative_retention;\n    }\n    return 0;\n  }\n\n  EmgFitter1D::EmgFitter1D() :\n    LevMarqFitter1D()\n  {\n    setName(getProductName());\n    defaults_.setValue(\"statistics:variance\", 1.0, \"Variance of the model.\", ListUtils::create<String>(\"advanced\"));\n    defaultsToParam_();\n  }\n\n  EmgFitter1D::EmgFitter1D(const EmgFitter1D& source) :\n    LevMarqFitter1D(source)\n  {\n    setParameters(source.getParameters());\n    updateMembers_();\n  }\n\n  EmgFitter1D::~EmgFitter1D()\n  {\n  }\n\n  EmgFitter1D& EmgFitter1D::operator=(const EmgFitter1D& source)\n  {\n    if (&source == this)\n      return *this;\n\n    LevMarqFitter1D::operator=(source);\n    setParameters(source.getParameters());\n    updateMembers_();\n\n    return *this;\n  }\n\n  EmgFitter1D::QualityType EmgFitter1D::fit1d(const RawDataArrayType& set, InterpolationModel*& model)\n  {\n    // Calculate bounding box\n    CoordinateType min_bb = set[0].getPos(), max_bb = set[0].getPos();\n    for (Size pos = 1; pos < set.size(); ++pos)\n    {\n      CoordinateType tmp = set[pos].getPos();\n      if (min_bb > tmp)\n        min_bb = tmp;\n      if (max_bb < tmp)\n        max_bb = tmp;\n    }\n\n    // Enlarge the bounding box by a few multiples of the standard deviation\n    const CoordinateType stdev = sqrt(statistics_.variance()) * tolerance_stdev_box_;\n    min_bb -= stdev;\n    max_bb += stdev;\n\n\n    // Set advanced parameters for residual_  und jacobian_ method\n    EmgFitter1D::Data d;\n    d.n = set.size();\n    d.set = set;\n\n    // Compute start parameters\n    setInitialParameters_(set);\n\n    // Optimize parameter with Levenberg-Marquardt algorithm\n//    CoordinateType x_init[4] = { height_, width_, symmetry_, retention_ };\n    Eigen::VectorXd x_init(4);\n    x_init(0) = height_;\n    x_init(1) = width_;\n    x_init(2) = symmetry_;\n    x_init(3) = retention_;\n    if (symmetric_ == false)\n    {\n      EgmFitterFunctor functor(4, &d);\n      optimize_(x_init, functor);\n    }\n\n    // Set optimized parameters\n    height_ = x_init[0];\n    width_ = x_init[1];\n    symmetry_ = x_init[2];\n    retention_ = x_init[3];\n\n#ifdef DEBUG_FEATUREFINDER\n    if (getGslStatus_() != \"success\")\n    {\n      std::cout << \"status: \" << getGslStatus_() << std::endl;\n    }\n#endif\n\n    // build model\n    model = static_cast<InterpolationModel*>(Factory<BaseModel<1> >::create(\"EmgModel\"));\n    model->setInterpolationStep(interpolation_step_);\n\n    Param tmp;\n    tmp.setValue(\"bounding_box:min\", min_bb);\n    tmp.setValue(\"bounding_box:max\", max_bb);\n    tmp.setValue(\"statistics:variance\", statistics_.variance());\n    tmp.setValue(\"statistics:mean\", statistics_.mean());\n    tmp.setValue(\"emg:height\", height_);\n    tmp.setValue(\"emg:width\", width_);\n    tmp.setValue(\"emg:symmetry\", symmetry_);\n    tmp.setValue(\"emg:retention\", retention_);\n    model->setParameters(tmp);\n\n\n    // calculate pearson correlation\n    std::vector<float> real_data;\n    real_data.reserve(set.size());\n    std::vector<float> model_data;\n    model_data.reserve(set.size());\n\n    for (Size i = 0; i < set.size(); ++i)\n    {\n      real_data.push_back(set[i].getIntensity());\n      model_data.push_back(model->getIntensity(DPosition<1>(set[i].getPosition())));\n    }\n\n    QualityType correlation = Math::pearsonCorrelationCoefficient(real_data.begin(), real_data.end(), model_data.begin(), model_data.end());\n    if (boost::math::isnan(correlation))\n      correlation = -1.0;\n\n    return correlation;\n  }\n\n  void EmgFitter1D::setInitialParameters_(const RawDataArrayType& set)\n  {\n    // sum over all intensities\n    CoordinateType sum = 0.0;\n    for (Size i = 0; i < set.size(); ++i)\n      sum += set[i].getIntensity();\n\n    // calculate the median\n    Size median = 0;\n    float count = 0.0;\n    for (Size i = 0; i < set.size(); ++i)\n    {\n      count += set[i].getIntensity();\n      if (count <= sum / 2)\n        median = i;\n    }\n\n    // calculate the height of the peak\n    height_ = set[median].getIntensity();\n\n    // calculate retention time\n    retention_ = set[median].getPos();\n\n    // default is an asymmetric peak\n    symmetric_ = false;\n\n    // calculate the symmetry (fronted peak: s<1 , tailed peak: s>1)\n    symmetry_ = fabs(set[set.size() - 1].getPos() - set[median].getPos()) / fabs(set[median].getPos() - set[0].getPos());\n\n    // check the symmetry\n    if (boost::math::isinf(symmetry_) || boost::math::isnan(symmetry_))\n    {\n      symmetric_ = true;\n      symmetry_ = 10;\n    }\n\n    // optimize the symmetry\n    // The computations can lead to an overflow error at very low values of symmetry (s~0).\n    // For s~5 the parameter can be approximated by the Levenberg-Marquardt algorithms.\n    // (the other parameters are much greater than one)\n    if (symmetry_ < 1)\n      symmetry_ += 5;\n\n    // calculate the width of the peak\n    // rt-values with intensity zero are not allowed for calculation of the width\n    // normally: width_ = fabs( set[set.size() - 1].getPos() - set[0].getPos() );\n    // but its better for the emg function to proceed from narrow peaks\n    width_ = symmetry_;\n  }\n\n  void EmgFitter1D::updateMembers_()\n  {\n    LevMarqFitter1D::updateMembers_();\n    statistics_.setVariance(param_.getValue(\"statistics:variance\"));\n  }\n\n}\n", "meta": {"hexsha": "fd7fd650cec18f6fc1381153c274371e6d2fd576", "size": 10382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/TRANSFORMATIONS/FEATUREFINDER/EmgFitter1D.cpp", "max_stars_repo_name": "tomas-pluskal/openms", "max_stars_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_stars_repo_licenses": ["Zlib", "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/openms/source/TRANSFORMATIONS/FEATUREFINDER/EmgFitter1D.cpp", "max_issues_repo_name": "tomas-pluskal/openms", "max_issues_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_issues_repo_licenses": ["Zlib", "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/openms/source/TRANSFORMATIONS/FEATUREFINDER/EmgFitter1D.cpp", "max_forks_repo_name": "tomas-pluskal/openms", "max_forks_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_forks_repo_licenses": ["Zlib", "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.3129251701, "max_line_length": 246, "alphanum_fraction": 0.6230013485, "num_tokens": 2939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19900810574626762}}
{"text": "#include <gamebase/engine/SimpleApplication.h>\n#include <gamebase/engine/CanvasLayout.h>\n#include <gamebase/engine/Button.h>\n#include <gamebase/engine/StaticLabel.h>\n#include <gamebase/engine/StaticTextureRect.h>\n#include <gamebase/engine/Timer.h>\n#include <gamebase/math/IntVector.h>\n#include <gamebase/serial/JsonDeserializer.h>\n#include <boost/lexical_cast.hpp>\n#include <Windows.h>\n\nusing namespace gamebase;\nusing namespace std;\n\nclass Figure\n{\npublic:\n    Figure() {}\n\n    Figure(int startYArg, const Color& colorArg, const vector<IntVec2>& geomArg)\n    {\n        startY = startYArg;\n        color = colorArg;\n        geom = geomArg;\n    }\n\n    void rotateLeft()\n    {\n        for (auto it = geom.begin(); it != geom.end(); ++it)\n            *it = rotate90CCW(*it);\n    }\n\n    void rotateRight()\n    {\n        for (auto it = geom.begin(); it != geom.end(); ++it)\n            *it = rotate90CW(*it);\n    }\n\n    int startY;\n    Color color;\n    vector<IntVec2> geom;\n};\n\nclass MyApp : public SimpleApplication\n{\npublic:\n    void load()\n    {\n        srand(GetTickCount());\n\n        design = deserialize<CanvasLayout>(\"tetris\\\\Design.json\");\n        m_view->addObject(design);\n\n        fieldLayout = design->getChild<CanvasLayout>(\"#field\");\n\n        design->getChild<Button>(\"#restart\")->setCallback(bind(&MyApp::restart, this));\n\n        {\n            vector<IntVec2> geom;\n            geom.push_back(IntVec2(0, 1));\n            geom.push_back(IntVec2(0, 0));\n            geom.push_back(IntVec2(0, -1));\n            geom.push_back(IntVec2(0, -2));\n            figures.push_back(Figure(18, Color(1, 0, 0), geom));\n        }\n\n        {\n            vector<IntVec2> geom;\n            geom.push_back(IntVec2(1, 1));\n            geom.push_back(IntVec2(0, 1));\n            geom.push_back(IntVec2(0, 0));\n            geom.push_back(IntVec2(0, -1));\n            figures.push_back(Figure(18, Color(0, 1, 0), geom));\n        }\n\n        {\n            vector<IntVec2> geom;\n            geom.push_back(IntVec2(-1, 1));\n            geom.push_back(IntVec2(0, 1));\n            geom.push_back(IntVec2(0, 0));\n            geom.push_back(IntVec2(0, -1));\n            figures.push_back(Figure(18, Color(0, 0, 1), geom));\n        }\n\n        {\n            vector<IntVec2> geom;\n            geom.push_back(IntVec2(0, 1));\n            geom.push_back(IntVec2(-1, 0));\n            geom.push_back(IntVec2(0, 0));\n            geom.push_back(IntVec2(1, 0));\n            figures.push_back(Figure(18, Color(1, 0, 1), geom));\n        }\n\n        {\n            vector<IntVec2> geom;\n            geom.push_back(IntVec2(1, 1));\n            geom.push_back(IntVec2(0, 1));\n            geom.push_back(IntVec2(1, 0));\n            geom.push_back(IntVec2(0, 0));\n            figures.push_back(Figure(18, Color(1, 1, 0), geom));\n        }\n\n        {\n            vector<IntVec2> geom;\n            geom.push_back(IntVec2(1, 0));\n            geom.push_back(IntVec2(0, 0));\n            geom.push_back(IntVec2(0, -1));\n            geom.push_back(IntVec2(-1, -1));\n            figures.push_back(Figure(18, Color(0, 1, 1), geom));\n        }\n\n        {\n            vector<IntVec2> geom;\n            geom.push_back(IntVec2(-1, 0));\n            geom.push_back(IntVec2(0, 0));\n            geom.push_back(IntVec2(0, -1));\n            geom.push_back(IntVec2(1, -1));\n            figures.push_back(Figure(18, Color(1, 0.5, 0), geom));\n        }\n\n        record = 0;\n        restart();\n    }\n\n    void restart()\n    {\n        gameover = false;\n        design->getChild<StaticLabel>(\"#gameover\")->setVisible(false);\n        score = 0;\n        design->getChild<StaticLabel>(\"#score\")->setText(\"0\");\n        timer.start();\n        fieldLayout->clear();\n\n        for (int x = 0; x < 10; ++x)\n            for (int y = 0; y < 20; ++y)\n                field[x][y] = -1;\n\n        newFigure();\n    }\n\n    void move()\n    {\n        if (gameover)\n            return;\n\n        if (timer.isPeriod(period))\n        {\n            if (!tryUpdatePos(0, -1))\n            {\n                for (int i = 0; i < curFigure.geom.size(); ++i)\n                {\n                    IntVec2 fullPos = curPos + curFigure.geom[i];\n                    field[fullPos.x][fullPos.y] = textureIds[i];\n                }\n                \n                vector<int> rawsToBurn;\n                for (int y = 0; y < 20; ++y)\n                {\n                    bool hasHole = false;\n                    for (int x = 0; x < 10; ++x)\n                    {\n                        if (field[x][y] == -1)\n                            hasHole = true;\n                    }\n                    if (!hasHole)\n                        rawsToBurn.push_back(y);\n                }\n\n                for (auto it = rawsToBurn.rbegin(); it != rawsToBurn.rend(); ++it)\n                {\n                    int rawY = *it;\n                    for (int x = 0; x < 10; ++x)\n                        fieldLayout->removeObject(field[x][rawY]);\n                    for (int y = rawY; y < 19; ++y)\n                    {\n                        for (int x = 0; x < 10; ++x)\n                        {\n                            field[x][y] = field[x][y + 1];\n                            if (field[x][y] != -1)\n                                adjustTile(field[x][y], IntVec2(x, y));\n                        }\n                    }\n                    for (int x = 0; x < 10; ++x)\n                        field[x][19] = -1;\n                }\n\n                switch (rawsToBurn.size())\n                {\n                case 1: score += 100; break;\n                case 2: score += 300; break;\n                case 3: score += 700; break;\n                case 4: score += 1500; break;\n                }\n\n                if (!rawsToBurn.empty())\n                {\n                    design->getChild<StaticLabel>(\"#score\")->setText(\n                        boost::lexical_cast<string>(score));\n                }\n\n                newFigure();\n            }\n        }\n\n        if (m_inputRegister.keys.isJustPressed(13) || m_inputRegister.keys.isJustPressed('s'))\n        {\n            if (period != 50)\n            {\n                timer.start();\n                period = 50;\n            }\n        }\n\n        if (m_inputRegister.keys.isJustPressed('a'))\n            tryUpdatePos(-1, 0);\n        if (m_inputRegister.keys.isJustPressed('d'))\n            tryUpdatePos(1, 0);\n\n        if (m_inputRegister.keys.isJustPressed('q'))\n        {\n            Figure newFigure = curFigure;\n            newFigure.rotateLeft();\n            if (canPlace(curPos, newFigure))\n            {\n                curFigure = newFigure;\n                adjustCurTiles();\n            }\n        }\n\n        if (m_inputRegister.keys.isJustPressed('e'))\n        {\n            Figure newFigure = curFigure;\n            newFigure.rotateRight();\n            if (canPlace(curPos, newFigure))\n            {\n                curFigure = newFigure;\n                adjustCurTiles();\n            }\n        }\n    }\n\n    bool tryUpdatePos(int xOffset, int yOffset)\n    {\n        auto newPos = curPos;\n        newPos.x += xOffset;\n        newPos.y += yOffset;\n        if (canPlace(newPos, curFigure))\n        {\n            curPos = newPos;\n            adjustCurTiles();\n            return true;\n        }\n        return false;\n    }\n\n    void newFigure()\n    {\n        period = 500;\n        curFigure = figures[rand() % figures.size()];\n        curPos.y = curFigure.startY;\n        if (canPlace(IntVec2(5, curPos.y), curFigure))\n        {\n            curPos.x = 5;\n        }\n        else\n        {\n            gameover = true;\n            design->getChild<StaticLabel>(\"#gameover\")->setVisible(true);\n            if (score > record)\n            {\n                record = score;\n                design->getChild<StaticLabel>(\"#record\")->setText(\n                    boost::lexical_cast<string>(record));\n            }\n            return;\n        }\n\n        textureIds.clear();\n        for (int i = 0; i < curFigure.geom.size(); ++i)\n        {\n            auto tile = deserialize<StaticTextureRect>(\"tetris\\\\Tile.json\");\n            tile->setColor(curFigure.color);\n            textureIds.push_back(fieldLayout->addObject(tile));\n        }\n        adjustCurTiles();\n    }\n\n    bool canPlace(const IntVec2& pos, const Figure& figure)\n    {\n        for (auto it = figure.geom.begin(); it != figure.geom.end(); ++it)\n        {\n            IntVec2 fullPos = pos + *it;\n            if (fullPos.x < 0 || fullPos.x > 9)\n                return false;\n            if (fullPos.y < 0)\n                return false;\n            if (field[fullPos.x][fullPos.y] != -1)\n                return false;\n        }\n        return true;\n    }\n\n    void adjustCurTiles()\n    {\n        for (int i = 0; i < textureIds.size(); ++i)\n        {\n            IntVec2 fullPos = curPos + curFigure.geom[i];\n            adjustTile(textureIds[i], fullPos);\n        }\n    }\n\n    void adjustTile(int id, const IntVec2& pos)\n    {\n        Vec2 vec(pos.x * 32 - 144, pos.y * 32 - 304);\n        auto* tile = fieldLayout->getObject<StaticTextureRect>(id);\n        auto* offset = tile->offset<FixedOffset>();\n        offset->set(vec);\n    }\n\n    shared_ptr<CanvasLayout> design;\n    CanvasLayout* fieldLayout;\n\n    Figure curFigure;\n    vector<int> textureIds;\n    IntVec2 curPos;\n\n    int score;\n    int record;\n\n    bool gameover;\n\n    int field[10][20];\n    Timer timer;\n    int period;\n\n    vector<Figure> figures;\n};\n\nint main(int argc, char** argv)\n{\n    MyApp app;\n    if (!app.init(&argc, argv))\n        return 1;\n    app.run();\n    return 0;\n}\n", "meta": {"hexsha": "abc0637901b84c18864b196067803104f3f679a2", "size": 9552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/games/tetris/main.cpp", "max_stars_repo_name": "TheMrButcher/opengl_lessons", "max_stars_repo_head_hexsha": "76ac96c45773a54a85d49c6994770b0c3496303f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-25T21:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-25T21:15:16.000Z", "max_issues_repo_path": "src/examples/games/tetris/main.cpp", "max_issues_repo_name": "TheMrButcher/gamebase", "max_issues_repo_head_hexsha": "76ac96c45773a54a85d49c6994770b0c3496303f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 375.0, "max_issues_repo_issues_event_min_datetime": "2016-06-04T11:27:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-14T17:11:09.000Z", "max_forks_repo_path": "src/examples/games/tetris/main.cpp", "max_forks_repo_name": "TheMrButcher/gamebase", "max_forks_repo_head_hexsha": "76ac96c45773a54a85d49c6994770b0c3496303f", "max_forks_repo_licenses": ["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.5273775216, "max_line_length": 94, "alphanum_fraction": 0.4658710218, "num_tokens": 2351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.1988623029404297}}
{"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 \"Open3D/Geometry/PointCloud.h\"\n\n#include <Eigen/Dense>\n\n#include \"Open3D/Geometry/KDTreeFlann.h\"\n#include \"Open3D/Utility/Console.h\"\n\nnamespace open3d {\nnamespace geometry {\n\nvoid PointCloud::Clear() {\n    points_.clear();\n    normals_.clear();\n    colors_.clear();\n}\n\nbool PointCloud::IsEmpty() const { return !HasPoints(); }\n\nEigen::Vector3d PointCloud::GetMinBound() const {\n    if (!HasPoints()) {\n        return Eigen::Vector3d(0.0, 0.0, 0.0);\n    }\n    auto itr_x = std::min_element(\n            points_.begin(), points_.end(),\n            [](const Eigen::Vector3d &a, const Eigen::Vector3d &b) {\n                return a(0) < b(0);\n            });\n    auto itr_y = std::min_element(\n            points_.begin(), points_.end(),\n            [](const Eigen::Vector3d &a, const Eigen::Vector3d &b) {\n                return a(1) < b(1);\n            });\n    auto itr_z = std::min_element(\n            points_.begin(), points_.end(),\n            [](const Eigen::Vector3d &a, const Eigen::Vector3d &b) {\n                return a(2) < b(2);\n            });\n    return Eigen::Vector3d((*itr_x)(0), (*itr_y)(1), (*itr_z)(2));\n}\n\nEigen::Vector3d PointCloud::GetMaxBound() const {\n    if (!HasPoints()) {\n        return Eigen::Vector3d(0.0, 0.0, 0.0);\n    }\n    auto itr_x = std::max_element(\n            points_.begin(), points_.end(),\n            [](const Eigen::Vector3d &a, const Eigen::Vector3d &b) {\n                return a(0) < b(0);\n            });\n    auto itr_y = std::max_element(\n            points_.begin(), points_.end(),\n            [](const Eigen::Vector3d &a, const Eigen::Vector3d &b) {\n                return a(1) < b(1);\n            });\n    auto itr_z = std::max_element(\n            points_.begin(), points_.end(),\n            [](const Eigen::Vector3d &a, const Eigen::Vector3d &b) {\n                return a(2) < b(2);\n            });\n    return Eigen::Vector3d((*itr_x)(0), (*itr_y)(1), (*itr_z)(2));\n}\n\nvoid PointCloud::Transform(const Eigen::Matrix4d &transformation) {\n    for (auto &point : points_) {\n        Eigen::Vector4d new_point =\n                transformation *\n                Eigen::Vector4d(point(0), point(1), point(2), 1.0);\n        point = new_point.block<3, 1>(0, 0);\n    }\n    for (auto &normal : normals_) {\n        Eigen::Vector4d new_normal =\n                transformation *\n                Eigen::Vector4d(normal(0), normal(1), normal(2), 0.0);\n        normal = new_normal.block<3, 1>(0, 0);\n    }\n}\n\nPointCloud &PointCloud::operator+=(const PointCloud &cloud) {\n    // We do not use std::vector::insert to combine std::vector because it will\n    // crash if the pointcloud is added to itself.\n    if (cloud.IsEmpty()) return (*this);\n    size_t old_vert_num = points_.size();\n    size_t add_vert_num = cloud.points_.size();\n    size_t new_vert_num = old_vert_num + add_vert_num;\n    if ((!HasPoints() || HasNormals()) && cloud.HasNormals()) {\n        normals_.resize(new_vert_num);\n        for (size_t i = 0; i < add_vert_num; i++)\n            normals_[old_vert_num + i] = cloud.normals_[i];\n    } else {\n        normals_.clear();\n    }\n    if ((!HasPoints() || HasColors()) && cloud.HasColors()) {\n        colors_.resize(new_vert_num);\n        for (size_t i = 0; i < add_vert_num; i++)\n            colors_[old_vert_num + i] = cloud.colors_[i];\n    } else {\n        colors_.clear();\n    }\n    points_.resize(new_vert_num);\n    for (size_t i = 0; i < add_vert_num; i++)\n        points_[old_vert_num + i] = cloud.points_[i];\n    return (*this);\n}\n\nPointCloud PointCloud::operator+(const PointCloud &cloud) const {\n    return (PointCloud(*this) += cloud);\n}\n\nstd::vector<double> ComputePointCloudToPointCloudDistance(\n        const PointCloud &source, const PointCloud &target) {\n    std::vector<double> distances(source.points_.size());\n    KDTreeFlann kdtree;\n    kdtree.SetGeometry(target);\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)source.points_.size(); i++) {\n        std::vector<int> indices(1);\n        std::vector<double> dists(1);\n        if (kdtree.SearchKNN(source.points_[i], 1, indices, dists) == 0) {\n            utility::PrintDebug(\n                    \"[ComputePointCloudToPointCloudDistance] Found a point \"\n                    \"without neighbors.\\n\");\n            distances[i] = 0.0;\n        } else {\n            distances[i] = std::sqrt(dists[0]);\n        }\n    }\n    return distances;\n}\n\nstd::tuple<Eigen::Vector3d, Eigen::Matrix3d> ComputePointCloudMeanAndCovariance(\n        const PointCloud &input) {\n    if (input.IsEmpty()) {\n        return std::make_tuple(Eigen::Vector3d::Zero(),\n                               Eigen::Matrix3d::Identity());\n    }\n    Eigen::Matrix<double, 9, 1> cumulants;\n    cumulants.setZero();\n    for (const auto &point : input.points_) {\n        cumulants(0) += point(0);\n        cumulants(1) += point(1);\n        cumulants(2) += point(2);\n        cumulants(3) += point(0) * point(0);\n        cumulants(4) += point(0) * point(1);\n        cumulants(5) += point(0) * point(2);\n        cumulants(6) += point(1) * point(1);\n        cumulants(7) += point(1) * point(2);\n        cumulants(8) += point(2) * point(2);\n    }\n    cumulants /= (double)input.points_.size();\n    Eigen::Vector3d mean;\n    Eigen::Matrix3d covariance;\n    mean(0) = cumulants(0);\n    mean(1) = cumulants(1);\n    mean(2) = cumulants(2);\n    covariance(0, 0) = cumulants(3) - cumulants(0) * cumulants(0);\n    covariance(1, 1) = cumulants(6) - cumulants(1) * cumulants(1);\n    covariance(2, 2) = cumulants(8) - cumulants(2) * cumulants(2);\n    covariance(0, 1) = cumulants(4) - cumulants(0) * cumulants(1);\n    covariance(1, 0) = covariance(0, 1);\n    covariance(0, 2) = cumulants(5) - cumulants(0) * cumulants(2);\n    covariance(2, 0) = covariance(0, 2);\n    covariance(1, 2) = cumulants(7) - cumulants(1) * cumulants(2);\n    covariance(2, 1) = covariance(1, 2);\n    return std::make_tuple(mean, covariance);\n}\n\nstd::vector<double> ComputePointCloudMahalanobisDistance(\n        const PointCloud &input) {\n    std::vector<double> mahalanobis(input.points_.size());\n    Eigen::Vector3d mean;\n    Eigen::Matrix3d covariance;\n    std::tie(mean, covariance) = ComputePointCloudMeanAndCovariance(input);\n    Eigen::Matrix3d cov_inv = covariance.inverse();\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)input.points_.size(); i++) {\n        Eigen::Vector3d p = input.points_[i] - mean;\n        mahalanobis[i] = std::sqrt(p.transpose() * cov_inv * p);\n    }\n    return mahalanobis;\n}\n\nstd::vector<double> ComputePointCloudNearestNeighborDistance(\n        const PointCloud &input) {\n    std::vector<double> nn_dis(input.points_.size());\n    KDTreeFlann kdtree(input);\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)input.points_.size(); i++) {\n        std::vector<int> indices(2);\n        std::vector<double> dists(2);\n        if (kdtree.SearchKNN(input.points_[i], 2, indices, dists) <= 1) {\n            utility::PrintDebug(\n                    \"[ComputePointCloudNearestNeighborDistance] Found a point \"\n                    \"without neighbors.\\n\");\n            nn_dis[i] = 0.0;\n        } else {\n            nn_dis[i] = std::sqrt(dists[1]);\n        }\n    }\n    return nn_dis;\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "240829ce8a990f8ffc2840a52f8cd2c65047dcaf", "size": 8792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Open3D/Geometry/PointCloud.cpp", "max_stars_repo_name": "martinruenz/Open3D", "max_stars_repo_head_hexsha": "30983e89956dcd233531870ca20e87e6769ba903", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:39:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-07T03:39:54.000Z", "max_issues_repo_path": "src/Open3D/Geometry/PointCloud.cpp", "max_issues_repo_name": "martinruenz/Open3D", "max_issues_repo_head_hexsha": "30983e89956dcd233531870ca20e87e6769ba903", "max_issues_repo_licenses": ["MIT"], "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/Geometry/PointCloud.cpp", "max_forks_repo_name": "martinruenz/Open3D", "max_forks_repo_head_hexsha": "30983e89956dcd233531870ca20e87e6769ba903", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-31T14:30:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-31T14:30:40.000Z", "avg_line_length": 37.2542372881, "max_line_length": 80, "alphanum_fraction": 0.5847361237, "num_tokens": 2365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19886229715274967}}
{"text": "// Copyright 2018 Google 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#include \"gtest/gtest.h\"\n\n#include <Eigen/Core>\n#include \"cpp/sensor_fusion/low_pass_filter.h\"\n\nnamespace mahony_filter {\n\nTEST(LowPassFilterTest, CreateFilter) {\n  LowPassFilter filter(1.0);\n  EXPECT_FALSE(filter.IsInitialized());\n  EXPECT_FALSE(filter.GetIsStatic());\n  EXPECT_EQ(filter.GetNStatic(), 0);\n  EXPECT_EQ(filter.GetRunTime(), 0.0);\n}\n\nTEST(LowPassFilterTest, AddSampleDataToNewFilter) {\n  LowPassFilter filter(1.0);\n  Eigen::Vector3d sample(1.0, 0.0, 0.0);\n  filter.AddSampleData(sample, 1.0);\n\n  EXPECT_EQ(filter.GetFilteredData(), sample);\n  EXPECT_EQ(filter.GetFilteredDataNorm(), 1.0);\n  EXPECT_EQ(filter.GetFilteredDataDirection(), sample);\n  EXPECT_NE(filter.GetLastData(), sample);\n  EXPECT_EQ(filter.GetRunTime(), 0.0)\n      << \"The first sample shouldn't change run_time_s_.\";\n\n  // Adds another sample\n  filter.AddSampleData(Eigen::Vector3d(3.0, 4.0, 0.0), 0.5);\n  EXPECT_EQ(filter.GetRunTime(), 0.5);\n  EXPECT_EQ(filter.GetLastData(), Eigen::Vector3d(3.0, 4.0, 0.0));\n  EXPECT_EQ(filter.GetLastDataDirection(), Eigen::Vector3d(0.6, 0.8, 0.0));\n}\n\nTEST(LowPassFilterTest, CheckStatic) {\n  LowPassFilter filter(1.0);\n  filter.SetIsStatic(true);\n  EXPECT_EQ(filter.GetNStatic(), 1);\n\n  for (int i = 0; i < kContiguousStaticSamples - 2; i++) {\n    filter.SetIsStatic(true);\n    EXPECT_FALSE(filter.GetIsStatic());\n  }\n  filter.SetIsStatic(true);\n  EXPECT_TRUE(filter.GetIsStatic());\n  EXPECT_EQ(filter.GetNStatic(), kContiguousStaticSamples);\n  EXPECT_FALSE(filter.GetIsStaticForN(kContiguousStaticSamples + 1));\n\n  filter.SetIsStatic(false);\n\n  for (int i = 0; i < kContiguousStaticSamples - 1; i++) {\n    filter.SetIsStatic(true);\n    EXPECT_FALSE(filter.GetIsStatic());\n  }\n  filter.SetIsStatic(true);\n  EXPECT_TRUE(filter.GetIsStatic());\n  EXPECT_EQ(filter.GetNStatic(), kContiguousStaticSamples);\n}\n\nTEST(LowPassFilterTest, AddSampleDataTillSettled) {\n  // startup_time_s_ is 1.0.\n  LowPassFilter filter(1.0);\n  filter.AddSampleData(Eigen::Vector3d(1.0, 0.0, 0.0), 1.0);\n  EXPECT_FALSE(filter.HasSettled());\n  filter.AddSampleData(Eigen::Vector3d(1.0, 0.0, 0.0), 2.0);\n  EXPECT_TRUE(filter.HasSettled());\n}\n\nTEST(LowPassFilterTest, ResetSettledFilter) {\n  LowPassFilter filter(1.0);\n  filter.AddSampleData(Eigen::Vector3d(1.0, 0.0, 0.0), 1.0);\n  filter.AddSampleData(Eigen::Vector3d(1.0, 0.0, 0.0), 2.0);\n  EXPECT_TRUE(filter.HasSettled());\n\n  filter.Reset();\n\n  EXPECT_FALSE(filter.HasSettled());\n  EXPECT_FALSE(filter.IsInitialized());\n  EXPECT_FALSE(filter.GetIsStatic());\n  EXPECT_EQ(filter.GetNStatic(), 0);\n  EXPECT_EQ(filter.GetRunTime(), 0);\n}\n\n}  // namespace mahony_filter\n\n", "meta": {"hexsha": "a579aa0516c63366ea9cd31aa78c8e686a1db014", "size": 3199, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/sensor_fusion/low_pass_filter_test.cc", "max_stars_repo_name": "google/vr180", "max_stars_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-12-09T17:58:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T11:43:24.000Z", "max_issues_repo_path": "cpp/sensor_fusion/low_pass_filter_test.cc", "max_issues_repo_name": "google/vr180", "max_issues_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T06:01:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T09:49:29.000Z", "max_forks_repo_path": "cpp/sensor_fusion/low_pass_filter_test.cc", "max_forks_repo_name": "google/vr180", "max_forks_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-05-25T02:18:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:35:03.000Z", "avg_line_length": 31.99, "max_line_length": 75, "alphanum_fraction": 0.7258518287, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19886229715274967}}
{"text": "#ifndef STAN_MCMC_HMC_BASE_HMC_HPP\n#define STAN_MCMC_HMC_BASE_HMC_HPP\n\n#include <stan/services/callbacks/logger.hpp>\n#include <stan/services/callbacks/writer.hpp>\n#include \"stan/algorithms/mcmc/base_mcmc.hpp\"\n#include \"stan/algorithms/hmc/hamiltonians/ps_point.hpp\"\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <cmath>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nnamespace stan {\n  namespace mcmc {\n\n    template <class Model,\n              template<class, class> class Hamiltonian,\n              template<class> class Integrator,\n              class BaseRNG>\n    class base_hmc : public base_mcmc {\n    public:\n      base_hmc(const Model &model, BaseRNG& rng)\n        : base_mcmc(),\n          z_(model.num_params_r()),\n          integrator_(),\n          hamiltonian_(model),\n          rand_int_(rng),\n          rand_uniform_(rand_int_),\n          nom_epsilon_(0.1),\n          epsilon_(nom_epsilon_),\n          epsilon_jitter_(0.0) {}\n\n      /** \n       * format and write stepsize\n       */\n      void\n      write_sampler_stepsize(callbacks::writer& writer) {\n        std::stringstream nominal_stepsize;\n        nominal_stepsize << \"Step size = \" << get_nominal_stepsize();\n        writer(nominal_stepsize.str());\n      }\n\n      /** \n       * write elements of mass matrix\n       */\n      void\n      write_sampler_metric(callbacks::writer& writer) {\n        z_.write_metric(writer);\n      }\n\n      /** \n       * write stepsize and elements of mass matrix\n       */\n      void\n      write_sampler_state(callbacks::writer& writer) {\n        write_sampler_stepsize(writer);\n        write_sampler_metric(writer);\n      }\n\n      void get_sampler_diagnostic_names(std::vector<std::string>& model_names,\n                                        std::vector<std::string>& names) {\n        z_.get_param_names(model_names, names);\n      }\n\n      void get_sampler_diagnostics(std::vector<double>& values) {\n        z_.get_params(values);\n      }\n\n      void seed(const Eigen::VectorXd& q) {\n        z_.q = q;\n      }\n\n      void\n      init_hamiltonian(callbacks::logger& logger) {\n        this->hamiltonian_.init(this->z_, logger);\n      }\n\n      void\n      init_stepsize(callbacks::logger& logger) {\n        ps_point z_init(this->z_);\n\n        // Skip initialization for extreme step sizes\n        if (this->nom_epsilon_ == 0 || this->nom_epsilon_ > 1e7)\n          return;\n\n        this->hamiltonian_.sample_p(this->z_, this->rand_int_);\n        this->hamiltonian_.init(this->z_, logger);\n\n        // Guaranteed to be finite if randomly initialized\n        double H0 = this->hamiltonian_.H(this->z_);\n\n        this->integrator_.evolve(this->z_, this->hamiltonian_,\n                                 this->nom_epsilon_,\n                                 logger);\n\n        double h = this->hamiltonian_.H(this->z_);\n        if (boost::math::isnan(h))\n          h = std::numeric_limits<double>::infinity();\n\n        double delta_H = H0 - h;\n\n        int direction = delta_H > std::log(0.8) ? 1 : -1;\n\n        while (1) {\n          this->z_.ps_point::operator=(z_init);\n\n          this->hamiltonian_.sample_p(this->z_, this->rand_int_);\n          this->hamiltonian_.init(this->z_, logger);\n\n          double H0 = this->hamiltonian_.H(this->z_);\n\n          this->integrator_.evolve(this->z_, this->hamiltonian_,\n                                   this->nom_epsilon_,\n                                   logger);\n\n          double h = this->hamiltonian_.H(this->z_);\n          if (boost::math::isnan(h))\n            h = std::numeric_limits<double>::infinity();\n\n          double delta_H = H0 - h;\n\n          if ((direction == 1) && !(delta_H > std::log(0.8)))\n            break;\n          else if ((direction == -1) && !(delta_H < std::log(0.8)))\n            break;\n          else\n            this->nom_epsilon_\n              = direction == 1\n              ? 2.0 * this->nom_epsilon_\n              : 0.5 * this->nom_epsilon_;\n\n          if (this->nom_epsilon_ > 1e7)\n            throw std::runtime_error(\"Posterior is improper. \"\n                                     \"Please check your model.\");\n          if (this->nom_epsilon_ == 0)\n            throw std::runtime_error(\"No acceptably small step size could \"\n                                     \"be found. Perhaps the posterior is \"\n                                     \"not continuous?\");\n        }\n\n        this->z_.ps_point::operator=(z_init);\n      }\n\n      typename Hamiltonian<Model, BaseRNG>::PointType& z() {\n        return z_;\n      }\n\n      virtual void set_nominal_stepsize(double e) {\n        if (e > 0)\n          nom_epsilon_ = e;\n      }\n\n      double get_nominal_stepsize() {\n        return this->nom_epsilon_;\n      }\n\n      double get_current_stepsize() {\n        return this->epsilon_;\n      }\n\n      virtual void set_stepsize_jitter(double j) {\n        if (j > 0 && j < 1)\n          epsilon_jitter_ = j;\n      }\n\n      double get_stepsize_jitter() {\n        return this->epsilon_jitter_;\n      }\n\n      void sample_stepsize() {\n        this->epsilon_ = this->nom_epsilon_;\n        if (this->epsilon_jitter_)\n          this->epsilon_ *= 1.0\n            + this->epsilon_jitter_ * (2.0 * this->rand_uniform_() - 1.0);\n      }\n\n    protected:\n      typename Hamiltonian<Model, BaseRNG>::PointType z_;\n      Integrator<Hamiltonian<Model, BaseRNG> > integrator_;\n      Hamiltonian<Model, BaseRNG> hamiltonian_;\n\n      BaseRNG& rand_int_;\n\n      // Uniform(0, 1) RNG\n      boost::uniform_01<BaseRNG&> rand_uniform_;\n\n      double nom_epsilon_;\n      double epsilon_;\n      double epsilon_jitter_;\n    };\n\n  }  // mcmc\n}  // stan\n#endif\n", "meta": {"hexsha": "ba1a21df89f6a4366cd7f04a0b2cc0ed2e3dc61e", "size": 5718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/algorithms/hmc/base_hmc.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/algorithms/hmc/base_hmc.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/algorithms/hmc/base_hmc.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": 28.7336683417, "max_line_length": 78, "alphanum_fraction": 0.5640083945, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19886229715274964}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/translation_search/fast_terms.h>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_internal_reference.hpp>\n\nnamespace cctbx { namespace translation_search { namespace boost_python {\n\nnamespace {\n\n  struct fast_terms_wrappers\n  {\n    typedef fast_terms<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      typedef return_internal_reference<> rir;\n      class_<w_t>(\"fast_terms\", no_init)\n        .def(init<af::int3 const&,\n                  bool,\n                  af::const_ref<miller::index<> > const&,\n                  af::const_ref<std::complex<double> > >(\n          (arg(\"gridding\"),\n           arg(\"anomalous_flag\"),\n           arg(\"miller_indices_p1_f_calc\"),\n           arg(\"p1_f_calc\"))))\n        .def(\"summation\", &w_t::summation, rir(),\n          (arg(\"space_group\"),\n           arg(\"miller_indices_f_obs\"),\n           arg(\"m\"),\n           arg(\"f_part\"),\n           arg(\"squared_flag\")))\n        .def(\"fft\", &w_t::fft, rir())\n        .def(\"accu_real_copy\", &w_t::accu_real_copy)\n      ;\n    }\n  };\n\n} // namespace <anoymous>\n\n  void wrap_fast_terms()\n  {\n    fast_terms_wrappers::wrap();\n  }\n\n}}} // namespace cctbx::translation_search::boost_python\n", "meta": {"hexsha": "b374a2d424fcdcf859bd19a9069c01aa2c17e7c1", "size": 1298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/translation_search/boost_python/fast_terms.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": "cctbx/translation_search/boost_python/fast_terms.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": "cctbx/translation_search/boost_python/fast_terms.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": 25.96, "max_line_length": 73, "alphanum_fraction": 0.5963020031, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.1988200713019239}}
{"text": "#include <iostream>\n//#include <iomanip>\n//#include <fstream>\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//#include <cstring>\n\n//#include <unistd.h>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"NRGOpMatRules.hpp\"\n#include \"NRG_main.hpp\"\n#include \"TwoChQS.hpp\"\n\n\n#ifndef pi\n#define pi 3.141592653589793238462643383279502884197169\n#endif\n\n\nvoid CNRGCodeHandler::ModelSwitch(  vector<int> &CommonQNs,\n\t\t\t\t    vector<int> &totSpos,   \n\t\t\t\t    CNRGarray* pAeig,\n\t\t\t\t    CNRGbasisarray* pSingleSite, \n\t\t\t\t    CNRGmatrix* pHN, \n\t\t\t\t    vector<CNRGmatrix> &STLMatArray,\n\t\t\t\t    CNRGthermo* ThermoArray,\n\t\t\t\t    vector<double> &chi_m1){\n\n  // Ok, this can be changed later to reduce the number of parameters \n  // Leave as it is for now.\n\n  // List of Non CNRGcodehandler objects that needs to be set/defined\n\n  // ALL of these have to be DEFINED as fields of CNRGCodeHandler\n  // STLMatArray -> MatArray (but routines need an STL vector... \n  //                          SHOULD DEFINE MatArray as an STL vector in \n  //                          CNRGcodehandler \n  //                          and adapt in the other routines. \n  //                          But leave it for now)\n  //                MatArray enters with 4 elements. Add if you need more.\n  // CommonQNs   -> (input)\n  // totSpos     -> (input)\n  // HN          -> (input)\n  // NumNRGarrays (not really, just set it as NumNRGmats)\n  // ThermoArray -> ThermoSTLArray (ok)\n\n  // Defined here:\n  \n  CNRGmatrix auxNRGMat;\n  vector <double> Params;\n\n  double chi2_m1=0.0; // Second coupling into the same channel!\n\n  // To do: getrid of ThermoArray and STLMatArray: \n  // define them in codehandler class.\n  // get rid of all parameters?\n\n\n\n  ///////////////////////////////////\n  ////   Model specific hamiltonians ///\n  ///////////////////////////////////\n\n// SymNo:\n//  0 - OneChQS\n//  1 - TwoChQS\n//  2 - OneChQSz\n//  3 - OneChQ\n//  4 - TwoChQSP\n//  5 - TwoChQSz\n//  6 - OneChNupPdn\n//  7 - OneChS\n//  8 - OneChSz\n//  9 - OneChPupPdn\n\n// ModelNo:\n//  0 - Anderson\n//  1 - Kondo\n//  2 - Anderson w Holstein phonons\n//  3 - Chain only\n//  4 - CM phonons (2ch only)\n//  5 - SMM (1chQ only)\n//  6 - DQD \n//  7 - Anderson+Local Majorana (1ch NupPdn only)\n//\n\n// NEW: Add zEQ(z) to SuscepImp names.\n//\n\n    char zstring[30];\n    char zvalue[8];\n    strcpy(zstring,\"_zEQ\");\n    if (dEqual(code_z_twist,1.0))\n      strcpy(zvalue,\"1\");\n    else\n      sprintf(zvalue,\"%4.2f\",code_z_twist);\n    strcat(zstring,zvalue);\n    cout << \"Zstring = \" << zstring << endl;\n\n    switch(SymNo){\n    case 0: // OneChQS\n      ////////////////////////////\n      /////                   ////\n      ///// Symmetry: OneChQS ////\n      /////                   ////\n      ////////////////////////////\n      /// Models so far:       ///\n      ///  0 - Anderson        ///\n      ///  1 - Kondo           ///\n      ///  3 - Chain           ///\n      ///  6 - DQD             ///\n      ////////////////////////////\n      switch(ModelNo){\n      case 0: // Single-impurity Anderson model Q,S symmetry\n\n\t// Initialize matrices (OneChQ routines work here!)\n\t// Jul 09: using STMatArray\n\n\t//NumThermoMats=2;\n      \n\t// fN (reduced)\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].UpperTriangular=false;\n\tSTLMatArray[0].CheckForMatEl=OneChQS_cd_check;\n\tSTLMatArray[0].CalcMatEl=OneChQS_fN_MatEl;\n\tSTLMatArray[0].SaveMatYN=false;\n\n\tswitch (calcdens){\n\tcase 0: // OpAvg: n_d(T), n^2_d(T), S^2(T) - NEW (2012)\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false; // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\t  STLMatArray[1]=auxNRGMat; // 1 - ndot (there already)\n\t  STLMatArray[2]=auxNRGMat; // 2 - ndot^2 (there already)\n\t  STLMatArray[3]=auxNRGMat; // 3 - Sdot^2 (there already)\n\t  strcpy(STLMatArray[1].MatName,\"Ndot\");\n\t  strcpy(STLMatArray[2].MatName,\"NdSq\");\n\t  strcpy(STLMatArray[3].MatName,\"SdSq\");\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; // Need to do this after\n\t  // changes in STLMatArray!\n\t  SaveData=false;\n// \t  STLMatArray.pop_back(); // 1 Matrices only\n// \t  STLMatArray.pop_back(); // 1 Matrices only\n// \t  STLMatArray.pop_back(); // 1 Matrices only\n\t  // No Thermo\n\t  NumThermoMats=0;\n\t  break;\n\tcase 1: //Spectral density\n\t  STLMatArray.pop_back(); // 2 Matrices\n\t  STLMatArray.pop_back(); // 2 Matrices\n\t  NumThermoMats=0;\n\t  // cd operator \n\t  STLMatArray[1].NeedOld=true;\n\t  STLMatArray[1].UpperTriangular=false;\n\t  STLMatArray[1].CheckForMatEl=OneChQS_cd_check;\n\t  STLMatArray[1].CalcMatEl=OneChQS_cd_MatEl;\n\t  STLMatArray[1].SaveMatYN=true;\n\t  strcpy(STLMatArray[1].MatName,\"cdot1\");\n\t  NumNRGmats=STLMatArray.size();\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"1chQSAnderson\");\n\t  break;\n\tcase 2: // Thermodynamics ONLY\n//\t  STLMatArray.pop_back(); // 1 Matrix only\n//\t  STLMatArray.pop_back(); // 1 Matrix only\n//\t  STLMatArray.pop_back(); // 1 Matrix only\n// If you want <n_d>(T), use calcdens=0\n// June 2013: I'm changing this. Want to calculate ndot toghether with chi_imp\n//\n\n \t  auxNRGMat.NeedOld=true;\n \t  auxNRGMat.UpperTriangular=false;\n\t  // update procedure only works for 'false'\n \t  auxNRGMat.CalcAvg=true;  // CalcAvg\n \t  auxNRGMat.CheckForMatEl=Diag_check;\n \t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n \t  STLMatArray[1]=auxNRGMat; // 1 - ndot (there already)\n \t  STLMatArray[2]=auxNRGMat; // 2 - ndot^2 (not right now)\n \t  STLMatArray[3]=auxNRGMat; // 3 - Sdot^2 (not right now)\n \t  strcpy(STLMatArray[1].MatName,\"Ndot\");\n \t  strcpy(STLMatArray[2].MatName,\"NdSq\");\n \t  strcpy(STLMatArray[3].MatName,\"SdSq\"); \n////////////\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; // Need to do this after\n\t  // changes in STLMatArray!\n\t  SaveData=false;\n\t  // Thermo\n\t  // Z trick in file name.\n\t  // Changinf chain arq names for 1chQS too (Sep 2010)\n\t  strcpy(ThermoArray[0].ArqName,\"SuscepImp1ChQS_Anderson\");\n\t  strcat(ThermoArray[0].ArqName,zstring);\n\t  strcat(ThermoArray[0].ArqName,\".dat\");\n\t  //\n\t  strcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QS\");\n\t  strcat(ThermoArray[0].ChainArqName,zstring);\n\t  strcat(ThermoArray[0].ChainArqName,\".dat\");\n\t  //\n\t  strcpy(ThermoArray[1].ArqName,\"EntropyImp1ChQS_Anderson\");\n\t  strcat(ThermoArray[1].ArqName,zstring);\n\t  strcat(ThermoArray[1].ArqName,\".dat\");\n\t  //\n\t  strcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QS\");\n\t  strcat(ThermoArray[1].ChainArqName,zstring);\n\t  strcat(ThermoArray[1].ChainArqName,\".dat\");\n\t  ThermoArray[0].Calc=CalcSuscep;\n\t  ThermoArray[0].dImpValue=1.0/8.0; \n\t  ThermoArray[1].Calc=CalcEntropy;\n\t  ThermoArray[1].dImpValue=2.0*log(2.0);\n\t  NumThermoMats=2;\n\t  break;\n\tcase 4: // Dynamical spin susceptibility and <Sz> and <Sz^2> (2015)\n\t  // 5 Matrices\n\t  STLMatArray.push_back(auxNRGMat);\n\t  NumThermoMats=0;\n\t  // <Sz> and <Sz2> operator \n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false;\n\t  // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\n\t  STLMatArray[1]=auxNRGMat; // 1 - Sz dynamical\n\t  STLMatArray[1].SaveMatYN=true;\n\t  STLMatArray[1].CalcAvg=false;\n\t  STLMatArray[1].CalcMatEl=OneChQS_Sz_MatEl;\n\t  strcpy(STLMatArray[1].MatName,\"Szomega\");\n\t  STLMatArray[1].WignerEckartL=1.0; // Needed by DM_NRG later\n\n\n\t  STLMatArray[2]=auxNRGMat; // 2 - Nd dynamical\n\t  STLMatArray[2].SaveMatYN=true;\n\t  STLMatArray[2].CalcAvg=false;\n\t  strcpy(STLMatArray[2].MatName,\"Ndomega\");\n\n\t  STLMatArray[3]=auxNRGMat; // 3 - <Sz2>(T) static\n\t  STLMatArray[3].SaveMatYN=false;\n\t  strcpy(STLMatArray[3].MatName,\"Sz2dot\");\n\n\t  STLMatArray[4]=auxNRGMat; // 4 - <Nd2>(T) static\n\t  STLMatArray[4].SaveMatYN=false;\n\t  strcpy(STLMatArray[4].MatName,\"Nd2dot\");\n\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; // Need to do this after\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"1chQSAnderson\");\n\t  break;\n\tdefault:\n\t  cout << \" calcdens = \" << calcdens << \" not implemented. Exiting. \" << endl;\n\t  exit(0);\n\n\t}\n\t// end switch calcdens\n\n\t// Param for H0\n\tParams.push_back(Lambda);\n\tParams.push_back(HalfLambdaFactor);\n\tParams.push_back(dInitParams[0]); // U\n\tParams.push_back(dInitParams[2]); // ed\n\tParams.push_back(chi_m1[0]); // gamma\n\n\tOneChQS_SetAnderson_Hm1(Params,pAeig,STLMatArray);\n\n\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // Q and S and commont QNs\n\tCommonQNs.push_back(0); // position of Q in old basis\n\tCommonQNs.push_back(1); // position of S in old basis\n\tCommonQNs.push_back(0); // position of Q in SingleSite\n\tCommonQNs.push_back(1); // position of S in SingleSite\n\ttotSpos.push_back(1);   // SU(2) symmetry in position 1\n\t// HN params\n\tpHN->CalcHNMatEl=OneChQS_HN_MatEl;\n\tNumChannels=1;\n\n\n\n\n\tbreak;\n\t// end OneChQS Anderson model set up\n\n      case 1: // Single-impurity Kondo model Q,S symmetry\n\n\n\tNsites0=1;\n\n\t// fN (reduced)\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].UpperTriangular=false;\n\tSTLMatArray[0].CheckForMatEl=OneChQS_cd_check;\n\tSTLMatArray[0].CalcMatEl=OneChQS_fN_MatEl;\n\tSTLMatArray[0].SaveMatYN=false;\n\n\tSTLMatArray.pop_back(); // 1 Matrix only\n\tSTLMatArray.pop_back(); // 1 Matrix only\n\tSTLMatArray.pop_back(); // 1 Matrix only\n\n\tswitch (calcdens){\n\tcase 0: // Levels only\n\t  NumThermoMats=0;\n\t  break;\n\tcase 2: // Thermodynamics\n\t  // Z trick in file name.\n\t  strcpy(ThermoArray[0].ArqName,\"SuscepImp1ChQS_Kondo\");\n\t  strcat(ThermoArray[0].ArqName,zstring);\n\t  strcat(ThermoArray[0].ArqName,\".dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QS\");\n\t  strcat(ThermoArray[0].ChainArqName,zstring);\n\t  strcat(ThermoArray[0].ChainArqName,\".dat\");\n\t  strcpy(ThermoArray[1].ArqName,\"EntropyImp1ChQS_Kondo\");\n\t  strcat(ThermoArray[1].ArqName,zstring);\n\t  strcat(ThermoArray[1].ArqName,\".dat\");\n\t  strcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QS\");\n\t  strcat(ThermoArray[1].ChainArqName,zstring);\n\t  strcat(ThermoArray[1].ChainArqName,\".dat\");\n\t  // Values for the single-impurity Kondo model\n\t  ThermoArray[0].Calc=CalcSuscep;\n\t  ThermoArray[0].dImpValue=1.0/4.0; \n\t  ThermoArray[1].Calc=CalcEntropy;\n\t  ThermoArray[1].dImpValue=log(2.0);\n\t  NumThermoMats=2;\n\t  break;\n      \n\tdefault:\n\t  cout << \" Calculating levels only \" << endl;\n\n\t}\n\t// end switch calcdens\n\n\t// Param for H0\n\tParams.push_back(Lambda);\n\tParams.push_back(HalfLambdaFactor);\n\tParams.push_back(chi_m1[0]); // will become Jtilde\n\n\t//\"chi_m1[0]\"= sqrt(Fsq*rho_0*J_0/pi)/(sqrt(Lambda)*HalfLambdaFactor); \n\n\tcout << \" Fsq = \" << Chains[0].Fsq \n\t     << \" rho0 J0  = \" << Lambda*HalfLambdaFactor*HalfLambdaFactor*chi_m1[0]*chi_m1[0]*pi/Chains[0].Fsq << endl;\n\n\n\tOneChQS_SetKondoH0(Params,pAeig,pSingleSite,STLMatArray);\n\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // Q and S and commont QNs\n\tCommonQNs.push_back(0); // position of Q in old basis\n\tCommonQNs.push_back(1); // position of S in old basis\n\tCommonQNs.push_back(0); // position of Q in SingleSite\n\tCommonQNs.push_back(1); // position of S in SingleSite\n\ttotSpos.push_back(1);   // SU(2) symmetry in position 1\n\t// HN params\n\tpHN->CalcHNMatEl=OneChQS_HN_MatEl;\n\tNumChannels=1;\n\t// Set chi_0 to enter HN!\n\tchi_m1[0]=Chains[0].GetChin(0); // Should be EQUAL to chiN(0,Lambda) if Square\n\tcout << \" chi_0= \" << chi_m1[0] \n\t     << \" Square band chi_0 : \" << chiN(0,Lambda)  \n\t     << endl;\n\n\tbreak;\n\t// end OneChQS Kondo model set up\n\n\n      case 3: // Chain only\n\n\tZeroParams();\n\tNsites0=1;\n\tNumThermoMats=2;\n\n\t// fN (reduced)\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].UpperTriangular=false;\n\tSTLMatArray[0].CheckForMatEl=OneChQS_cd_check;\n\tSTLMatArray[0].CalcMatEl=OneChQS_fN_MatEl;\n\tSTLMatArray.pop_back(); // Only ONE array\n\tSTLMatArray.pop_back(); // Only ONE array\n\tSTLMatArray.pop_back(); // Only ONE array\n\t// Set ChainH0: SingleSite is already set, just get Aeig and STLMatArray.\n\tOneChQS_SetChainH0(pAeig,STLMatArray);\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\tSaveData=false;\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // Q and S and commont QNs\n\tCommonQNs.push_back(0); // position of Q in old basis\n\tCommonQNs.push_back(1); // position of S in old basis\n\tCommonQNs.push_back(0); // position of Q in SingleSite\n\tCommonQNs.push_back(1); // position of S in SingleSite\n\ttotSpos.push_back(1);   // SU(2) symmetry in position 1\n\t// HN params\n\tpHN->CalcHNMatEl=OneChQS_HN_MatEl;\n\tNumChannels=1;\n\tif (BandNo==0){\n\t  chi_m1[0]=chiN(0,Lambda); // is actually chi0 // chiN is a codehandler func\n\t// Valid ONLY for SquareBand, z_twist=1! Check side dot calcs...\n\t}\n\telse{chi_m1[0]=Chains[0].GetChin(0);}\n\t// Need to change chain files for ALL Models!!\n\t//strcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QS.dat\");\n\tstrcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QS\");\n\tstrcat(ThermoArray[0].ChainArqName,zstring);\n\tstrcat(ThermoArray[0].ChainArqName,\".dat\");\n\t//strcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QS.dat\");\n\tstrcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QS\");\n\tstrcat(ThermoArray[1].ChainArqName,zstring);\n\tstrcat(ThermoArray[1].ChainArqName,\".dat\");\n\tbreak;\n\n      case 6: // 1chQS Double Quantum dot\n\n\tcout << \" Implementing DQD case... \" << endl;\n\n\tchi2_m1=sqrt(2.0*dInitParams[4]/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\n\tParams.push_back(Lambda);\n\tParams.push_back(HalfLambdaFactor);\n\tParams.push_back(dInitParams[0]); // U1\n\tParams.push_back(dInitParams[2]); // ed1\n\tParams.push_back(chi_m1[0]); // gamma1\n\tParams.push_back(dInitParams[3]); // U2\n\tParams.push_back(dInitParams[5]); // ed2\n\tParams.push_back(chi2_m1); // gamma2\n\n\t// Question: Can these things be implemented within the subroutine??\n\n\t// fN (reduced)\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].UpperTriangular=false;\n\tSTLMatArray[0].CheckForMatEl=OneChQS_cd_check;\n\tSTLMatArray[0].CalcMatEl=OneChQS_fN_MatEl;\n\n\n\tswitch (calcdens){\n\tcase 0: // Calculates Op averages only\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false; // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\t  STLMatArray[1]=auxNRGMat; // 1 - ndot (there already)\n\t  STLMatArray[2]=auxNRGMat; // 2 - ndot^2 (there already)\n\t  STLMatArray[3]=auxNRGMat; // 3 - Sdot^2 (there already)\n\t  STLMatArray.push_back(auxNRGMat); // 4 - S1 dot S2\n\t  strcpy(STLMatArray[1].MatName,\"Ndqd\");\n\t  strcpy(STLMatArray[2].MatName,\"NdqdSq\");\n\t  strcpy(STLMatArray[3].MatName,\"SdqdSq\");\n\t  strcpy(STLMatArray[4].MatName,\"S1dotS2\");\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; // Need to do this after\n\t  // changes in STLMatArray!\n\t  SaveData=false;\n\t  break;\n\tcase 1: // Calc Spectral functions\n\t  // All operators have the same Checks/MatEls in |Q> basis\n\t  // what changes is the initial set-up\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.CheckForMatEl=OneChQS_cd_check;\n\t  auxNRGMat.CalcMatEl=OneChQS_cd_MatEl;\n\t  auxNRGMat.SaveMatYN=true;\n\t  STLMatArray[1]=auxNRGMat; // 1 - cd1\n\t  STLMatArray[2]=auxNRGMat; // 2 - cd2\n\t  strcpy(STLMatArray[1].MatName,\"cdot1\");\n\t  strcpy(STLMatArray[2].MatName,\"cdot2\");\n\t  STLMatArray.pop_back(); // 3 elements only\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; // Need to do this after\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"DQD\");\n\t  break;\n\tcase 2: // Thermodynamics\n\t  STLMatArray.pop_back(); // 1 Matrix only\n\t  STLMatArray.pop_back(); // 1 Matrix only\n\t  STLMatArray.pop_back(); // 1 Matrix only\n\t  //strcpy(ThermoArray[0].ArqName,\"SuscepImp1ChQS_DQD.dat\");\n\t  //strcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QS.dat\");\n\t  strcpy(ThermoArray[0].ArqName,\"SuscepImp1ChQS_DQD\");\n\t  strcat(ThermoArray[0].ArqName,zstring);\n\t  strcat(ThermoArray[0].ArqName,\".dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QS\");\n\t  strcat(ThermoArray[0].ChainArqName,zstring);\n\t  strcat(ThermoArray[0].ChainArqName,\".dat\");\n\t  //strcpy(ThermoArray[1].ArqName,\"EntropyImp1ChQS_DQD.dat\");\n\t  //strcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QS.dat\");\n\t  strcpy(ThermoArray[1].ArqName,\"EntropyImp1ChQS_DQD\");\n\t  strcat(ThermoArray[1].ArqName,zstring);\n\t  strcat(ThermoArray[1].ArqName,\".dat\");\n\t  strcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QS\");\n\t  strcat(ThermoArray[1].ChainArqName,zstring);\n\t  strcat(ThermoArray[1].ChainArqName,\".dat\");\n\n\t  ThermoArray[0].Calc=CalcSuscep;\n\t  ThermoArray[0].dImpValue=1.0/4.0; // check. Irrelevant, actually.\n\t  ThermoArray[1].Calc=CalcEntropy;\n\t  ThermoArray[1].dImpValue=4.0*log(2.0);\n\t  NumThermoMats=2;\n\t  break;\n      \n\tdefault:\n\t  cout << \" Calculating levels only \" << endl;\n\n\t}\n\t// end switch calcdens\n\n\n\tOneChQS_SetH0_DQD(Params,pAeig,pSingleSite,STLMatArray);\n\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // Q and S and commont QNs\n\tCommonQNs.push_back(0); // position of Q in old basis\n\tCommonQNs.push_back(1); // position of S in old basis\n\tCommonQNs.push_back(0); // position of Q in SingleSite\n\tCommonQNs.push_back(1); // position of S in SingleSite\n\ttotSpos.push_back(1);   // SU(2) symmetry in position 1\n\t// HN params\n\tpHN->CalcHNMatEl=OneChQS_HN_MatEl;\n\tNsites0=1;\n\tNumChannels=1;\n\tchi_m1[0]=chiN(0,Lambda);\n      \n\tbreak;\n   \n      default:\n\tcout << \" Model not implemented for this symmetry. Exiting... \" << endl;\n\texit(0);\n      }\n      // end switch ModelNo\n      break;\n\n    case 1: // TwoChQS\n      ////////////////////////////\n      /////                   ////\n      ///// Symmetry: TwoChQS ////\n      /////                   ////\n      ////////////////////////////\n      /// Models so far:       ///\n      ///  1 - Kondo           ///\n      ///  3 - Chain           ///\n      ////////////////////////////\n      switch(ModelNo){\n      case 1: \n\t// Single-impurity Kondo model Q,S symmetry\n\tcout << \" Implementing the two-Channel Kondo model \" << endl;\n\n\tNsites0=1;\n\tNumThermoMats=2;\n\n\tParams.clear();\n\n\t//Params.push_back(Lambda);\n\t//Params.push_back(HalfLambdaFactor); Do we need this??\n\n\t// Coupling to second channel\n// \tchi2_m1=sqrt(2.0*dInitParams[4]/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\tchi_m1[1]=sqrt(2.0*dInitParams[4]/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\n\tcout << \" FOR NOW, not including the Lambda factor in J1,J2 \" << endl;\n\n\tParams.push_back(dInitParams[1]); // J1\n\tParams.push_back(dInitParams[4]); // J2\n\n\n\tswitch (calcdens){\n\tcase 0: // Levels only\n\t  NumThermoMats=0;\n\t  break;\n\tcase 2:\n\t  // Z trick in file name.\n\t  strcpy(ThermoArray[0].ArqName,\"SuscepImp2ChQS_Kondo\");\n\t  strcat(ThermoArray[0].ArqName,zstring);\n\t  strcat(ThermoArray[0].ArqName,\".dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"SuscepChain2Ch_QS\");\n\t  strcat(ThermoArray[0].ChainArqName,zstring);\n\t  strcat(ThermoArray[0].ChainArqName,\".dat\");\n\t  strcpy(ThermoArray[1].ArqName,\"EntropyImp2ChQS_Kondo\");\n\t  strcat(ThermoArray[1].ArqName,zstring);\n\t  strcat(ThermoArray[1].ArqName,\".dat\");\n\t  strcpy(ThermoArray[1].ChainArqName,\"EntropyChain2Ch_QS\");\n\t  strcat(ThermoArray[1].ChainArqName,zstring);\n\t  strcat(ThermoArray[1].ChainArqName,\".dat\");\n\t  // Values for the single-impurity Kondo model\n\t  ThermoArray[0].Calc=CalcSuscep;\n\t  ThermoArray[0].dImpValue=1.0/4.0; \n\t  ThermoArray[1].Calc=CalcEntropy;\n\t  ThermoArray[1].dImpValue=log(2.0);\n\t  NumThermoMats=2;\n\t  break;\n// \tcase 3:\n// \t  break;\n\tdefault:\n\t  cout << \" Please select calcdens=0 or 2 for TwoChQS_Kondo \" << endl;\n\t  exit(0);\n\t}\n\t// end switch calcdens\n\n\tSTLMatArray.pop_back(); // 2 Matrices\n\tSTLMatArray.pop_back(); // 2 Matrices\n\n\t// fN_ch1 (reduced)\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].UpperTriangular=false; // WHY? Not symmetric\n\tSTLMatArray[0].SaveMatYN=false;\n\tSTLMatArray[0].CheckForMatEl=TwoChQS_cd_check;\n\tSTLMatArray[0].CalcMatEl=TwoChQS_fNch1_MatEl;\n\n\n\t// fN_ch2 (reduced)\n\tSTLMatArray[1].NeedOld=false;\n\tSTLMatArray[1].UpperTriangular=false;  // WHY? Not symmetric\n\tSTLMatArray[1].SaveMatYN=false;\n\tSTLMatArray[1].CheckForMatEl=TwoChQS_cd_check;\n\tSTLMatArray[1].CalcMatEl=TwoChQS_fNch2_MatEl;\n\n\n\tTwoChQS_SetKondoH0(Params,pSingleSite,pAeig,STLMatArray);\n\t// Do I need pAbasis?? Nope...\n\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // Q and S and commont QNs\n\tCommonQNs.push_back(0); // position of Q in old basis\n\tCommonQNs.push_back(1); // position of S in old basis\n\tCommonQNs.push_back(0); // position of Q in SingleSite\n\tCommonQNs.push_back(1); // position of S in SingleSite\n\ttotSpos.push_back(1);   // SU(2) symmetry in position 1\n\t// Hamiltonian/Code params\n\t// Need to check these things. (May 8/2011)\n\tpHN->CalcHNMatEl=TwoChQS_HN_MatEl;\n\tNsites0=1;\n\tNumNRGmats=2;\n\tNumChannels=2; // Not needed...\n\n\t// Is this ok? What if there is a pseudogap?? Solved! (2019)\n\tchi_m1[0]=chiN(0,Lambda);\n// \tchi2_m1=chiN(0,Lambda);\n\tchi_m1[1]=chiN(0,Lambda);\n\tif (BandNo==0){\n\t  chi_m1[0]=chiN(0,Lambda); // is actually chi0 // chiN is a codehandler func\n// \t  chi2_m1=chiN(0,Lambda);\n\t  chi_m1[1]=chiN(0,Lambda);\n\t}\n\t// Valid ONLY for SquareBand, z_twist=1! Check side dot calcs...\n\telse{\n\t  chi_m1[0]=Chains[0].GetChin(0);\n// \t  chi2_m1=Chains[1].GetChin(0);\n\t  chi_m1[1]=Chains[1].GetChin(0);\n\t}\n\t///////////\n\n\n\t// Debugging: Print and Exit\n\tpAeig->PrintEn();\n\t//exit(0);\n\tbreak;\n      case 3: // TwoChQS Chain only\n\n\tZeroParams();\n\tNsites0=1;\n\tNumNRGmats=2;\n\tNumChannels=2;\n\tNumThermoMats=2;\n\n\tstrcpy(ThermoArray[0].ChainArqName,\"SuscepChain2Ch_QS\");\n\tstrcat(ThermoArray[0].ChainArqName,zstring);\n\tstrcat(ThermoArray[0].ChainArqName,\".dat\");\n\tstrcpy(ThermoArray[1].ChainArqName,\"EntropyChain2Ch_QS\");\n\tstrcat(ThermoArray[1].ChainArqName,zstring);\n\tstrcat(ThermoArray[1].ChainArqName,\".dat\");\n\n\n\tSTLMatArray.pop_back(); // 2 Matrices\n\tSTLMatArray.pop_back(); // 2 Matrices\n\t// fN_ch1 (reduced)\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].UpperTriangular=false; // WHY? Not symmetric\n\tSTLMatArray[0].SaveMatYN=false;\n\tSTLMatArray[0].CheckForMatEl=TwoChQS_cd_check;\n\tSTLMatArray[0].CalcMatEl=TwoChQS_fNch1_MatEl;\n\t// fN_ch2 (reduced)\n\tSTLMatArray[1].NeedOld=false;\n\tSTLMatArray[1].UpperTriangular=false;  // WHY? Not symmetric\n\tSTLMatArray[1].SaveMatYN=false;\n\tSTLMatArray[1].CheckForMatEl=TwoChQS_cd_check;\n\tSTLMatArray[1].CalcMatEl=TwoChQS_fNch2_MatEl;\n\n\tTwoChQS_SetH0Chain(pAeig,pSingleSite,STLMatArray);\n\t// Debugging: Print and Exit\n\tpAeig->PrintEn();\n\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // Q and S and commont QNs\n\tCommonQNs.push_back(0); // position of Q in old basis\n\tCommonQNs.push_back(1); // position of S in old basis\n\tCommonQNs.push_back(0); // position of Q in SingleSite\n\tCommonQNs.push_back(1); // position of S in SingleSite\n\ttotSpos.push_back(1);   // SU(2) symmetry in position 1\n\t// Hamiltonian/Code params\n\tpHN->CalcHNMatEl=TwoChQS_HN_MatEl;\n\tif (BandNo==0){\n\t  chi_m1[0]=chiN(0,Lambda); // is actually chi0 // chiN is a codehandler func\n\t  chi_m1[1]=chiN(0,Lambda);\n\t}\n\t// Valid ONLY for SquareBand, z_twist=1! Check side dot calcs...\n\telse{\n\t  chi_m1[0]=Chains[0].GetChin(0);\n\t  chi_m1[1]=Chains[1].GetChin(0);\n\t}\n\t///////////\n\tbreak;\n      default:\n\tcout << \" Model not implemented for this symmetry. Exiting... \" << endl;\n\texit(0);\n      }\n      // end switch ModelNo\n      break;\n\n\n    case 2: // OneChQSz\n      ////////////////////////////\n      /////                    ////\n      ///// Symmetry: OneChQSz ////\n      /////                    ////\n      //////////////////////////////////////\n      /// Models so far:                 ///\n      ///  0 - Anderson (Bfield)         ///\n      ///  3 - Chain                     ///\n      ///  6 - DQD (Zeeman in both dots) ///\n      //////////////////////////////////////\n\n      switch(ModelNo){\n      case 0: // Anderson\n\n\t// Initialize matrices (OneChQ routines work here!)\n\t// Jul 09: using STMatArray\n\n\tSTLMatArray[0].NeedOld=false;\t  \n\tSTLMatArray[0].CheckForMatEl=OneChQ_cd_check; //WHY???\n\tSTLMatArray[0].CalcMatEl=OneChQ_fNup_MatEl;\n\tSTLMatArray[0].SaveMatYN=false;\n\n\tSTLMatArray[1].NeedOld=false;\n\tSTLMatArray[1].CheckForMatEl=OneChQ_cd_check; //WHY???\n\tSTLMatArray[1].CalcMatEl=OneChQ_fNdn_MatEl;\n\tSTLMatArray[1].SaveMatYN=false;\n\n\t// Param for H0\n\tParams.push_back(dInitParams[0]); // U\n\tParams.push_back(dInitParams[2]); // ed\n\tParams.push_back(Lambda);\n\tParams.push_back(HalfLambdaFactor);\n\tParams.push_back(dInitParams[3]);        // Mag Field \n\n\tswitch (calcdens){\n\tcase 0: // OpAvg: n_d(T), S_z(T) -(2013)\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false; // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\t  STLMatArray[2]=auxNRGMat; // 2 - ndot (there already)\n\t  STLMatArray[3]=auxNRGMat; // 3 - Sz (there already)\n\t  strcpy(STLMatArray[2].MatName,\"Ndot\");\n\t  strcpy(STLMatArray[3].MatName,\"Szdot\");\n\t  // changes in STLMatArray!\n\t  SaveData=false;\n\t  // No Thermo\n\t  NumThermoMats=0;\n\t  break;\n \tcase 1: //Spectral density\n\t  // cd_up and cd_dn (OneChQSz_SetAnderson equals \n\t  // MatArray[2,3] to MatArray[0,1]\n\t  STLMatArray[2].NeedOld=true;\n\t  STLMatArray[2].CheckForMatEl=OneChQSz_cdup_check;\n\t  STLMatArray[2].CalcMatEl=OneChQSz_cdup_MatEl;\n\t  STLMatArray[2].SaveMatYN=true;\n\n\t  STLMatArray[3].NeedOld=true;\n\t  STLMatArray[3].CheckForMatEl=OneChQSz_cddn_check;\n\t  STLMatArray[3].CalcMatEl=OneChQSz_cddn_MatEl;\n\t  STLMatArray[3].SaveMatYN=true;\n\n\t  strcpy(STLMatArray[2].MatName,\"cdup\");\n\t  strcpy(STLMatArray[3].MatName,\"cddn\");\n\n\t  cout << \" N = -1\" << endl;\n\t  cout << \" cdN_up : \" << endl;\n\t  STLMatArray[2].PrintAllBlocks();\n\t  cout << \" cdN_dn : \" << endl;\n\t  STLMatArray[3].PrintAllBlocks();\n\n\t  SaveData=true;\n\n \t  break;\n \tcase 2: // Thermodynamics ONLY\n\n\t  STLMatArray.pop_back(); // 2 Matrices only\n\t  STLMatArray.pop_back(); // 2 Matrices only\n\t  strcpy(ThermoArray[0].ArqName,\"SuscepImp1ChQSz\");\n\t  strcat(ThermoArray[0].ArqName,zstring);\n\t  strcat(ThermoArray[0].ArqName,\".dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QSz\");\n\t  strcat(ThermoArray[0].ChainArqName,zstring);\n\t  strcat(ThermoArray[0].ChainArqName,\".dat\");\n\n\t  strcpy(ThermoArray[1].ArqName,\"EntropyImp1ChQSz\");\n\t  strcat(ThermoArray[1].ArqName,zstring);\n\t  strcat(ThermoArray[1].ArqName,\".dat\");\n\t  strcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QSz\");\n\t  strcat(ThermoArray[1].ChainArqName,zstring);\n\t  strcat(ThermoArray[1].ChainArqName,\".dat\");\n\n\t  ThermoArray[0].Calc=CalcSuscep;\n\t  ThermoArray[0].dImpValue=1.0/8.0; // check\n\t  ThermoArray[1].Calc=CalcEntropy;\n\t  ThermoArray[1].dImpValue=2.0*log(2.0);\n\t  NumThermoMats=2;\n\t  SaveData=false;\n\n \t  break;\n\n\tcase 4: // Dynamical spin susceptibility and <Sz> and <Sz^2> (2013)\n\t  // 6 Matrices\n\t  STLMatArray.push_back(auxNRGMat);\n\t  STLMatArray.push_back(auxNRGMat);\n\t  NumThermoMats=0;\n\t  // <Sz> and <Sz2> operator \n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false;\n\t  // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\n\t  STLMatArray[2]=auxNRGMat; // 2 - Sz dynamical\n\t  STLMatArray[2].SaveMatYN=true;\n\t  STLMatArray[2].CalcAvg=false;\n\n\n\t  STLMatArray[3]=auxNRGMat; // 3 - Nd dynamical\n\t  STLMatArray[3].SaveMatYN=true;\n\t  STLMatArray[3].CalcAvg=false;\n\n\t  STLMatArray[4]=auxNRGMat; // 4 - <Sz2>(T) static\n\t  STLMatArray[4].SaveMatYN=false;\n\n\t  STLMatArray[5]=auxNRGMat; // 5 - <Nd2>(T) static\n\t  STLMatArray[5].SaveMatYN=false;\n\n\t  strcpy(STLMatArray[2].MatName,\"Szomega\");\n\t  strcpy(STLMatArray[3].MatName,\"Ndomega\");\n\t  strcpy(STLMatArray[4].MatName,\"Sz2dot\");\n\t  strcpy(STLMatArray[5].MatName,\"Nd2dot\");\n\n\t  NumNRGmats=STLMatArray.size();\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"1chQSzAnderson\");\n\t  break;\n\n \tcase 5: //Spectral density with Self-energy trick\n\t  // 6 Matrices\n\t  STLMatArray.push_back(auxNRGMat);\n\t  STLMatArray.push_back(auxNRGMat);\n\t  // cd_up and cd_dn\n\t  STLMatArray[2].NeedOld=true;\n\t  STLMatArray[2].CheckForMatEl=OneChQSz_cdup_check;\n\t  STLMatArray[2].CalcMatEl=OneChQSz_cdup_MatEl;\n\t  STLMatArray[2].SaveMatYN=true;\n\n\t  STLMatArray[3].NeedOld=true;\n\t  STLMatArray[3].CheckForMatEl=OneChQSz_cddn_check;\n\t  STLMatArray[3].CalcMatEl=OneChQSz_cddn_MatEl;\n\t  STLMatArray[3].SaveMatYN=true;\n\n\t  // <cd_up N_dn> and <cd_dn N_up>\n\t  STLMatArray[4].NeedOld=true;\n\t  STLMatArray[4].CheckForMatEl=OneChQSz_cdup_check;\n\t  STLMatArray[4].CalcMatEl=OneChQSz_cdup_MatEl; // Same Fermi Factor\n\t  STLMatArray[4].SaveMatYN=true;\n\n\t  STLMatArray[5].NeedOld=true;\n\t  STLMatArray[5].CheckForMatEl=OneChQSz_cddn_check;\n\t  STLMatArray[5].CalcMatEl=OneChQSz_cddn_MatEl; // Same Fermi Factor\n\t  STLMatArray[5].SaveMatYN=true;\n\n\t  strcpy(STLMatArray[2].MatName,\"cdup\");\n\t  strcpy(STLMatArray[3].MatName,\"cddn\");\n\t  strcpy(STLMatArray[4].MatName,\"cdupNdn\");\n\t  strcpy(STLMatArray[5].MatName,\"cddnNup\");\n\n\t  SaveData=true;\n\n \t  break;\n\n\tdefault:\n\t  cout << \" calcdens = \" << calcdens << \" not implemented. Exiting. \" << endl;\n\t  exit(0);\n\n\t}\n\t// end switch calcdens\n\n\n\tOneChQSz_SetAnderson_Hm1(Params,pAeig,STLMatArray);\n\n\t////////////////////////\n\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // No of common QNs\n\tCommonQNs.push_back(0); // pos of QN 1 in old\n\tCommonQNs.push_back(1); // pos of QN 2 in old\n\n\tCommonQNs.push_back(0); // pos of QN 1 in SingleSite\n\tCommonQNs.push_back(1); // pos of QN 1 in SingleSite\n\n\t// No total S variables. Leave totSpos empty\n\tpHN->CalcHNMatEl=OneChQSz_HN_MatEl;\n\n\t// Wrap up\n\tNumChannels=1;\n\tNsites0=0;\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\t// changes in STLMatArray!\n\n\n\tbreak;\n\n      case 3: // OneChQSz Chain only\n\n\tZeroParams();\n\tNsites0=1;\n\tNumThermoMats=2;\n\tNumChannels=1;\n\n\t// fN_up and fN_dn\n\t// fd_up\n\tSTLMatArray[0].NeedOld=false;\t  \n\tSTLMatArray[0].UpperTriangular=false;\n\tSTLMatArray[0].CheckForMatEl=OneChQSz_cdup_check; //This should work\n\tSTLMatArray[0].CalcMatEl=OneChQSz_fNup_MatEl;\n\tSTLMatArray[0].SaveMatYN=false;\n\n\t// fd_dn\n\tSTLMatArray[1].NeedOld=false;\n\tSTLMatArray[1].UpperTriangular=false;\n\tSTLMatArray[1].CheckForMatEl=OneChQSz_cddn_check; //This should work\n\tSTLMatArray[1].CalcMatEl=OneChQSz_fNdn_MatEl;\n\tSTLMatArray[1].SaveMatYN=false;\n\n\tSTLMatArray.pop_back(); // Only TWO mats\n\tSTLMatArray.pop_back(); // Only TWO mats\n\t// Set ChainH0: SingleSite is already set, just get Aeig and STLMatArray.\n\tOneChQSz_SetChainH0(pAeig,STLMatArray);\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\tSaveData=false;\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // Q and Sz and commont QNs\n\tCommonQNs.push_back(0); // position of Q in old basis\n\tCommonQNs.push_back(1); // position of Sz in old basis\n\tCommonQNs.push_back(0); // position of Q in SingleSite\n\tCommonQNs.push_back(1); // position of Sz in SingleSite\n\n\t// No total S variables. Leave totSpos empty\n\tpHN->CalcHNMatEl=OneChQSz_HN_MatEl;\n\n\tif (BandNo==0){\n\t  chi_m1[0]=chiN(0,Lambda); // is actually chi0 // chiN is a codehandler func\n\t// Valid ONLY for SquareBand, z_twist=1! Check side dot calcs...\n\t}\n\telse{chi_m1[0]=Chains[0].GetChin(0);}\n\n\tNumNRGmats=STLMatArray.size(); // DO I STILL NEED THIS???\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\t// changes in STLMatArray! \n\n\t// Need to change chain files for ALL Models!!\n\tstrcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QSz\");\n\tstrcat(ThermoArray[0].ChainArqName,zstring);\n\tstrcat(ThermoArray[0].ChainArqName,\".dat\");\n\tstrcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QSz\");\n\tstrcat(ThermoArray[1].ChainArqName,zstring);\n\tstrcat(ThermoArray[1].ChainArqName,\".dat\");\n\tbreak;\n\t// end OneChQSz chain only\n\n      case 6: // OneChQSz DQD (Zeeman in both dots)\n\n\t// Initialize matrices (OneChQ routines work here!)\n\t// Jul 09: using STMatArray\n\t// fd_up\n\tSTLMatArray[0].NeedOld=false;\t  \n\tSTLMatArray[0].CheckForMatEl=OneChQSz_cdup_check; //This should work\n\tSTLMatArray[0].CalcMatEl=OneChQSz_fNup_MatEl;\n\tSTLMatArray[0].SaveMatYN=false;\n\n\t// fd_dn\n\tSTLMatArray[1].NeedOld=false;\n\tSTLMatArray[1].CheckForMatEl=OneChQSz_cddn_check; //This should work\n\tSTLMatArray[1].CalcMatEl=OneChQSz_fNdn_MatEl;\n\tSTLMatArray[1].SaveMatYN=false;\n\n\n\t// Param for H0 (11 parameters)\n\tParams.push_back(Lambda);\n\tParams.push_back(HalfLambdaFactor);\n\n\tParams.push_back(dInitParams[0]); // U1\n\tParams.push_back(dInitParams[2]); // ed1\n\tParams.push_back(chi_m1[0]); // gamma1\n\tParams.push_back(dInitParams[7]); // Bmag1      \n\n\tParams.push_back(dInitParams[3]); // U2\n\tParams.push_back(dInitParams[5]); // ed2\n\tchi2_m1=sqrt(2.0*dInitParams[4]/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\tParams.push_back(chi2_m1); // gamma2\n\tParams.push_back(dInitParams[8]); // Bmag2\n\t  \n\tParams.push_back(dInitParams[6]); // lambda\n\n\n\tswitch (calcdens){\n\tcase 1: // Calculates spectral densities\n\t  // cd_up and cd_dn (OneChQSz_SetAnderson equals \n\t  // c1_up\n\t  STLMatArray[2].NeedOld=true;\n\t  STLMatArray[2].CheckForMatEl=OneChQSz_cdup_check;\n\t  STLMatArray[2].CalcMatEl=OneChQSz_cdup_MatEl;\n\t  STLMatArray[2].SaveMatYN=true;\n\t  strcpy(STLMatArray[2].MatName,\"cdot1_up\");\n\t  // c1_dn\n\t  STLMatArray[3].NeedOld=true;\n\t  STLMatArray[3].CheckForMatEl=OneChQSz_cddn_check;\n\t  STLMatArray[3].CalcMatEl=OneChQSz_cddn_MatEl;\n\t  STLMatArray[3].SaveMatYN=true;\n\t  strcpy(STLMatArray[3].MatName,\"cdot1_dn\");\n\t  // c2_up\n\t  auxNRGMat=STLMatArray[2];\n\t  STLMatArray.push_back(auxNRGMat);\n\t  strcpy(STLMatArray[4].MatName,\"cdot2_up\");\n\t  // c2_dn\n\t  auxNRGMat=STLMatArray[3];\n\t  STLMatArray.push_back(auxNRGMat);\n\t  strcpy(STLMatArray[5].MatName,\"cdot2_dn\");\n\t  // changes in STLMatArray\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"DQD_QSz\");\n\n\t  break;\n\tcase 2: // Thermodynamics for DQD+Zeeman\n\t  STLMatArray.pop_back(); // 2 Matrices only\n\t  STLMatArray.pop_back(); // 2 Matrices only\n\t  //strcpy(ThermoArray[0].ArqName,\"SuscepImp1ChQSz_DQD.dat\");\n\t  strcpy(ThermoArray[0].ArqName,\"SuscepImp1ChQSz_DQD\");\n\t  strcat(ThermoArray[0].ArqName,zstring);\n\t  strcat(ThermoArray[0].ArqName,\".dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"SuscepChain1Ch_QSz\");\n\t  strcat(ThermoArray[0].ChainArqName,zstring);\n\t  strcat(ThermoArray[0].ChainArqName,\".dat\");\n\t  //strcpy(ThermoArray[1].ArqName,\"EntropyImp1ChQSz_DQD.dat\");\n\t  strcpy(ThermoArray[1].ArqName,\"EntropyImp1ChQSz_DQD\");\n\t  strcat(ThermoArray[1].ArqName,zstring);\n\t  strcat(ThermoArray[1].ArqName,\".dat\");\n\t  strcpy(ThermoArray[1].ChainArqName,\"EntropyChain1Ch_QSz\");\n\t  strcat(ThermoArray[1].ChainArqName,zstring);\n\t  strcat(ThermoArray[1].ChainArqName,\".dat\");\n\n\t  ThermoArray[0].Calc=CalcSuscep;\n\t  ThermoArray[0].dImpValue=1.0/4.0; // check\n\t  ThermoArray[1].Calc=CalcEntropy;\n\t  ThermoArray[1].dImpValue=4.0*log(2.0);\n\t  NumThermoMats=2;\n\t  SaveData=false;\n\n\t  break;\n\n\tdefault:\n\t  cout << \" Please select calcdens=1,2 or 3 for 1chQSz_DQD \" << endl;\n\t  exit(0);\n\t}\n\t// end switch calcdens\n\n\tOneChQSz_SetH0_DQD(Params,pAeig,pSingleSite,STLMatArray);\n\n\t// Wrap up\n\tNumChannels=1;\n\tNsites0=1;\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\tif (BandNo==0)\n\t  chi_m1[0]=chiN(0,Lambda); // is actually chi0\n\t// Valid ONLY for SquareBand, z_twist=1! Check side dot calcs...\n\telse\n\t  chi_m1[0]=Chains[0].GetChin(0);\n\t///////////\n\t// BuildBasis params\n\tCommonQNs.push_back(2); // No of common QNs\n\tCommonQNs.push_back(0); // pos of QN 1 in old\n\tCommonQNs.push_back(1); // pos of QN 2 in old\n\tCommonQNs.push_back(0); // pos of QN 1 in SingleSite\n\tCommonQNs.push_back(1); // pos of QN 1 in SingleSite\n\t// No total S variables. Leave totSpos empty\n\tpHN->CalcHNMatEl=OneChQSz_HN_MatEl;\n\n\tbreak;\n\t// end DQD 1chQSz\n\n      default:\n\tcout << \" Model not implemented for this symmetry. Exiting... \" << endl;\n\texit(0);\n      }\n      // end switch ModelNo\n      break;\n    case 3: // OneChQ\n      ///// Symmetry: OneChQ ////\n      ////////////////////////////\n      /////                  ////\n      ///// Symmetry: OneChQ ////\n      /////                  ////\n      ////////////////////////////\n      /// Models so far:       ///\n      ///  0 - Anderson        ///\n      ///  5 - SMM             ///\n      ////////////////////////////\n\n      switch(ModelNo){\n      case 0: // Anderson\n\n\t// Initialize matrices (uncomment later)\n\n\tSTLMatArray[0].NeedOld=false;\t  \n\tSTLMatArray[0].CheckForMatEl=OneChQ_cd_check;\n\tSTLMatArray[0].CalcMatEl=OneChQ_fNup_MatEl;\n\t  \n\tSTLMatArray[1].NeedOld=false;\n\tSTLMatArray[1].CheckForMatEl=OneChQ_cd_check;\n\tSTLMatArray[1].CalcMatEl=OneChQ_fNdn_MatEl;\n\n\t// Sz and Sz2\n\tSTLMatArray[2].NeedOld=true;\n\tSTLMatArray[2].UpperTriangular=false;\n\tSTLMatArray[2].CalcAvg=true;  // CalcAvg\n\tSTLMatArray[2].CheckForMatEl=Diag_check;\n\tSTLMatArray[2].CalcMatEl=ImpOnly_MatEl;\n\tstrcpy(STLMatArray[2].MatName,\"Sz\");\n\n\tSTLMatArray[3].NeedOld=true;\n\tSTLMatArray[3].UpperTriangular=false;\n\tSTLMatArray[3].CalcAvg=true;  // CalcAvg\n\tSTLMatArray[3].CheckForMatEl=Diag_check;\n\tSTLMatArray[3].CalcMatEl=ImpOnly_MatEl;\n\tstrcpy(STLMatArray[3].MatName,\"Sz2\");\n\n\tif (calcdens==1){\n\t  // All operators have the same Checks/MatEls in |Q> basis\n\t  // what changes is the initial set-up\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false;\n\t  auxNRGMat.CheckForMatEl=OneChQ_cd_check;\n\t  auxNRGMat.CalcMatEl=OneChQ_cd_MatEl;\n\t  auxNRGMat.SaveMatYN=true;\n\n\t  STLMatArray.push_back(auxNRGMat); // 4 - cd1_up\n\t  STLMatArray.push_back(auxNRGMat); // 5 - cd1_dn\n\t  //NumNRGarrays=STLMatArray.size(); // do we need NumNRGarrays later?\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; //\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"1chQAnd\");\n\t}\n\telse{\n\t  // Set Thermodynamics\n\t  // Entropy calculation only\n\t  strcpy(ThermoArray[0].ArqName,\"EntropyImp1Ch_Anderson_Q.dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"EntropyChain1Ch_Q.dat\");\n\t  ThermoArray[0].Calc=CalcEntropy;\n\t  ThermoArray[0].dImpValue=2.0*log(2.0);\n\t  //ThermoArray[0].CalcChain=false;\n\t  NumThermoMats=1;\n\t}\n\t// calculate spec function or thermo?\n\n\n\t// Param for H0\n\tParams.push_back(dInitParams[0]); // U\n\tParams.push_back(dInitParams[2]); // ed\n\tParams.push_back(Lambda);\n\tParams.push_back(HalfLambdaFactor);\n\tOneChQ_SetAnderson_Hm1(Params,pAeig,STLMatArray);\n\t//OneChQ_SetAnderson_Hm1_old(Params,&Aeig,MatArray);\n\n\n\t////////////////////////\n\n\t// BuildBasis params\n\tCommonQNs.push_back(1); // No of common QNs\n\tCommonQNs.push_back(0); // pos of QN 1 in old\n\tCommonQNs.push_back(0); // pos of QN 1 in SingleSite\n\t// No total S variables. Leave totSpos empty\n\tpHN->CalcHNMatEl=OneChQ_HN_MatEl;\n\n\tNumChannels=1;\n\tNsites0=0;\n\n\tbreak;\n      case 5: // SMM model\n\n\t// Params for H0\n\tParams.push_back(Lambda);  // Lambda\n\tParams.push_back(HalfLambdaFactor); // Lambda factor\n\n\n\tif (dInitParams.size()>10){\n\t  Params.push_back(dInitParams[0]); // U1\n\t  Params.push_back(dInitParams[2]); // ed1\n\n\t  Params.push_back(dInitParams[3]); // U2\n\t  Params.push_back(dInitParams[5]); // ed2\n \n\t  Params.push_back(dInitParams[6]); // J12\n\n\t  Params.push_back(dInitParams[7]); // BmagPar      \n\t  Params.push_back(dInitParams[8]); // BmagPerp\n\n\t  Params.push_back(dInitParams[9]); // Dz      \n\t  Params.push_back(dInitParams[10]); // B2 anisot\n\n\t  double chi2_m1=sqrt(2.0*dInitParams[4]/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\t  Params.push_back(chi_m1[0]); // gamma1\n\t  Params.push_back(chi2_m1); // gamma2\n\t}\n\telse{\n\t  double U=0.5;\n\t  double ed=-0.5*U;\n\t  Params.push_back(U); // U1\n\t  Params.push_back(ed); // ed1\n\n\t  Params.push_back(0.0); // U2\n\t  Params.push_back(0.0); // ed2\n \n\t  Params.push_back(0.0); // J12\n\n\t  Params.push_back(0.0); // BmagPar      \n\t  Params.push_back(0.0); // BmagPerp\n\n\t  Params.push_back(0.0); // Dz      \n\t  Params.push_back(0.0); // B2 anisot\n\n\t  Params.push_back(chi_m1[0]); // gamma1\n\t  Params.push_back(0.0); // gamma2\n\t}\n\n\n\t// Set rules for MatArray\n\t// Jul 09: using STMatArray\n\n\t// fN_up\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].CheckForMatEl=OneChQ_cd_check;\n\tSTLMatArray[0].CalcMatEl=OneChQ_fNup_MatEl;\n\n\t// fN_dn\n\tSTLMatArray[1].NeedOld=false;\n\tSTLMatArray[1].CheckForMatEl=OneChQ_cd_check;\n\tSTLMatArray[1].CalcMatEl=OneChQ_fNdn_MatEl;\n\n\n\t// Sz and Sz2\n\n\tSTLMatArray[2].NeedOld=true;\n\tSTLMatArray[2].UpperTriangular=false;\n\tSTLMatArray[2].CalcAvg=true;  // CalcAvg\n\tSTLMatArray[2].CheckForMatEl=Diag_check;\n\tSTLMatArray[2].CalcMatEl=ImpOnly_MatEl;\n\tstrcpy(STLMatArray[2].MatName,\"Sz\");\n\n\n\tSTLMatArray[3].NeedOld=true;\n\tSTLMatArray[3].UpperTriangular=false;\n\tSTLMatArray[2].CalcAvg=true;\n\tSTLMatArray[3].CheckForMatEl=Diag_check;\n\tSTLMatArray[3].CalcMatEl=ImpOnly_MatEl;\n\tstrcpy(STLMatArray[3].MatName,\"Sz2\"); \n\n\t// cd1_up, cd1_dn, cd2_up, cd2_dn  \n\t// MatArray is an STL vector!!!\n\tif (calcdens==1){\n\t  // All operators have the same Checks/MatEls in |Q> basis\n\t  // what changes is the initial set-up\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.CheckForMatEl=OneChQ_cd_check;\n\t  auxNRGMat.CalcMatEl=OneChQ_cd_MatEl;\n\t  auxNRGMat.SaveMatYN=true;\n\n\t  STLMatArray.push_back(auxNRGMat); // 4 - cd1_up\n\t  STLMatArray.push_back(auxNRGMat); // 5 - cd1_dn\n\t  STLMatArray.push_back(auxNRGMat); // 6 - cd2_up\n\t  STLMatArray.push_back(auxNRGMat); // 7 - cd2_dn\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; // Need to do this after\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"SMM\");\n      \n\t}\n\telse{\n\t  // Set Thermodynamics\n\t\n\t  // Entropy calculation only\n      \n\t  strcpy(ThermoArray[0].ArqName,\"EntropyImp1Ch_Anderson_Q.dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"EntropyChain1Ch_Q.dat\");\n\t  ThermoArray[0].Calc=CalcEntropy;\n\t  ThermoArray[0].dImpValue=4.0*log(2.0); // Seems to be irrelevant...\n\t  ThermoArray[0].CalcChain=false;\n\t  NumThermoMats=1;\n\t}\n\t// calculate spec function or thermo?\n\n\n\t// Set H0: output pAeig, MatArray\n\n\n\n\tOneChQ_SetSMM_H0(Params,pAeig,pSingleSite,STLMatArray);\n\n\n\t// BuildBasis params\n\tCommonQNs.push_back(1); // No of common QNs\n\tCommonQNs.push_back(0); // pos of QN 1 in old\n\tCommonQNs.push_back(0); // pos of QN 1 in SingleSite\n\t// No total S variables. Leave totSpos empty\n\tpHN->CalcHNMatEl=OneChQ_HN_MatEl;\n\tNsites0=1;\n\tNumChannels=1;\n\n\tchi_m1[0]=chiN(0,Lambda);\n\n\tbreak;\n      default:\n\tcout << \" Model not implemented for this symmetry. Exiting... \" << endl;\n\texit(0);\n      }\n      // end switch ModelNo\n      break;\n\n    case 4: // TwoChQSP\n      switch(ModelNo){\n      ////////////////////////////\n      /////                     ///\n      ///// Symmetry: TwoChQSP  ///\n      /////                     ///\n      ////////////////////////////\n      /// Models so far:       ///\n      ///  4 - CM Phonons (2ch)///\n      ////////////////////////////\n      case 4: // CM Phonons - 2channel\n\tParams.push_back(Lambda);  // Lambda\n\tParams.push_back(HalfLambdaFactor); // Lambda factor\n\n\tParams.push_back(dInitParams[0]); // U1\n\tParams.push_back(dInitParams[2]); // ed1\n\n\tParams.push_back(chi_m1[0]); // sqrt(2gamma1/Pi)/sqrt(L)*HalfLambdaFactor\n\n\tParams.push_back(dInitParams[3]); // w0\n\tParams.push_back(dInitParams[4]); // lambda_ph\n\tParams.push_back(dInitParams[5]); // alpha\n\tParams.push_back(dInitParams[6]); // Nph      \n\n\n\t// Update rules for f_ch1 and fch2\n\n\t// Set rules for MatArray\n\n\t// fN_ch1 (reduced)\n\tMatArray[0].NeedOld=false;\n\tMatArray[0].CheckForMatEl=TwoChQS_cd_check;\n\tMatArray[0].CalcMatEl=TwoChQS_cd_ich1_Phonon_MatEl;\n\n\t// fN_ch2 (reduced)\n\tMatArray[1].NeedOld=false;\n\tMatArray[1].CheckForMatEl=TwoChQSP_fA_check; // mixes parities\n\tMatArray[1].CalcMatEl=TwoChQS_cd_ich2_Phonon_MatEl;\n\n\t//CNRGarray MyTest1;\n       \n\n\t// Set H0, get pAeig and Update MatArray\n\tTwoChQSP_SetH0CMphonon(Params, pAeig,pSingleSite,MatArray);\n\n\n\t// No phonons needed from now on\n\tMatArray[0].CalcMatEl=TwoChQS_fNch1_MatEl;\n\tMatArray[1].CalcMatEl=TwoChQS_fNch2_MatEl;\n\n\n\t// BuildBasis params\n\tCommonQNs.push_back(3); // No of common QNs\n\tCommonQNs.push_back(0); // pos of QN 1 in old\n\tCommonQNs.push_back(1); // pos of QN 2 in old\n\tCommonQNs.push_back(2); // pos of QN 3 in old\n\n\tCommonQNs.push_back(0); // pos of QN 1 in SingleSite\n\tCommonQNs.push_back(1); // pos of QN 2 in SingleSite\n\tCommonQNs.push_back(3); // pos of QN 3 in SingleSite\n\n\tCommonQNs.push_back(2); // Pos of parity in old\n\ttotSpos.push_back(1); // Pos of S in old\n\n\t// Hamiltonian/Code params\n\tpHN->CalcHNMatEl=TwoChQS_HN_MatEl;\n\tNsites0=1;\n\tchi_m1[0]=chiN(0,Lambda);\n\tNumNRGmats=2;\n\tNumChannels=2;\n\tNumThermoMats=2;\n\n\tThermoArray[0].dImpValue=0.0;\n\tThermoArray[1].dImpValue=0.0; // Check this!!\n\n\t// Thermobasics\n\n\tstrcpy(ThermoArray[0].ArqName,\"SuscepImp2Ch_CMphonon_QSP.dat\");\n\tstrcpy(ThermoArray[0].ChainArqName,\"SuscepChain2Ch.dat\");\n\tThermoArray[0].Calc=CalcSuscep;\n  \n\tstrcpy(ThermoArray[1].ArqName,\"EntropyImp2Ch_CMphonon_QSP.dat\");\n\tstrcpy(ThermoArray[1].ChainArqName,\"EntropyChain2Ch.dat\");\n\tThermoArray[1].Calc=CalcEntropy;\n\n\tcout << \" Implementing this model NOW \" << endl;\n\n\tcout << \" fN_ch1 : \" << endl;\n\tMatArray[0].PrintAllBlocks();\n\tcout << \" fN_ch2 : \" << endl;\n\tMatArray[1].PrintAllBlocks();\n \n\tbreak;\n      default:\n\tcout << \" Model not implemented for this symmetry. Exiting... \" << endl;\n\texit(0);\n      }  \n      // end switch ModelNo\n      break;\n\n    case 6: // OneChNupPdn\n      ////////////////////////////////\n      /////                        ///\n      ///// Symmetry: OneChNupPdn  ///\n      /////                        ///\n      ////////////////////////////////\n\n      // BuildBasis params\n      CommonQNs.push_back(2); // No of common QNs\n      CommonQNs.push_back(0); // pos of QN 1 in old\n      CommonQNs.push_back(1); // pos of QN 2 in old\n\n      CommonQNs.push_back(0); // pos of QN 1 in SingleSite\n      CommonQNs.push_back(1); // pos of QN 2 in SingleSite\n\n      CommonQNs.push_back(1); // pos of Parity QN\n      // No total S variables. Leave totSpos empty\n\n      switch(ModelNo){\n      ///////////////////////////////////\n      /// Models so far:              ///\n      ///  3 - Chain only             ///\n      ///  7 - Anderson+Local Majorana///\n      ///////////////////////////////////\n      case 3: // Chain only\n\n\tZeroParams();\n\tNsites0=1; // IS THIS CORRECT? Yes. H_0 is set so we start NRG from H_1\n\tNumThermoMats=1; // Entropy only\n\n\t// Initialize matrices (real matrices)\n\t// fd_up\n\tSTLMatArray[0].NeedOld=false;\t  \n \tSTLMatArray[0].CheckForMatEl=OneChNupPdn_cdup_check;\n  \tSTLMatArray[0].CalcMatEl=OneChNupPdn_fNup_MatEl;\n \t//STLMatArray[0].CalcMatElCplx=OneChNupPdn_fNup_MatElCplx;\n\tSTLMatArray[0].SaveMatYN=false;\n\tSTLMatArray[0].IsComplex=false;\n\n\t// fd_dn\n\tSTLMatArray[1].NeedOld=false;\n \tSTLMatArray[1].CheckForMatEl=OneChNupPdn_cddn_check;\n  \tSTLMatArray[1].CalcMatEl=OneChNupPdn_fNdn_MatEl;\n\tSTLMatArray[1].SaveMatYN=false;\n\tSTLMatArray[1].IsComplex=false;\n\n\tSTLMatArray.pop_back(); // Only TWO arrays\n\tSTLMatArray.pop_back(); // Only TWO arrays\n\n\tOneChNupPdn_SetChainH0(pAeig,STLMatArray);\n\n\t// Set pHN\n\tpHN->CalcHNMatEl=OneChNupPdn_HN_MatEl; // REAL\n\t// Wrap up\n\tNumChannels=1;\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\t// changes in STLMatArray!\n\n\tif (BandNo==0){\n\t  chi_m1[0]=chiN(0,Lambda); // is actually chi0 // chiN is a codehandler func\n\t// Valid ONLY for SquareBand, z_twist=1! Check side dot calcs...\n\t}\n\telse{chi_m1[0]=Chains[0].GetChin(0);}\n\t// Need to change chain files for ALL Models!!\n\tstrcpy(ThermoArray[0].ChainArqName,\"EntropyChain1Ch_NupPdn\");\n\tstrcat(ThermoArray[0].ChainArqName,zstring);\n\tstrcat(ThermoArray[0].ChainArqName,\".dat\");\n\tThermoArray[0].Calc=CalcEntropy;\n\tThermoArray[0].CalcChain=true; // Just to make sure\n\n\tbreak;\n\n      case 7: \n\tcout << \" Majorana + QD effective model \" << endl;\n\n\tParams.push_back(Lambda);  // Lambda\n\tParams.push_back(HalfLambdaFactor); // Lambda factor\n\n\tParams.push_back(dInitParams[0]); // U1\n\tParams.push_back(dInitParams[2]); // ed1\n\tParams.push_back(chi_m1[0]); // sqrt(2gamma1/Pi)/sqrt(L)*HalfLambdaFactor\n\n\tParams.push_back(dInitParams[3]); // Mag Field \n\n\tParams.push_back(dInitParams[4]); // t1\n\tParams.push_back(dInitParams[5]); // t2\n\tParams.push_back(dInitParams[6]); // phi_mag\n\tParams.push_back(dInitParams[7]); // em      \n\n\t// Initialize matrices \n\t// fd_up\n\tSTLMatArray[0].NeedOld=false;\t  \n \tSTLMatArray[0].CheckForMatEl=OneChNupPdn_cdup_check;\n//  \tSTLMatArray[0].CalcMatEl=OneChNupPdn_fNup_MatEl;\n \tSTLMatArray[0].CalcMatElCplx=OneChNupPdn_fNup_MatElCplx;\n\tSTLMatArray[0].SaveMatYN=false;\n\tSTLMatArray[0].IsComplex=true;\n\n\t// fd_dn\n\tSTLMatArray[1].NeedOld=false;\n \tSTLMatArray[1].CheckForMatEl=OneChNupPdn_cddn_check;\n \tSTLMatArray[1].CalcMatElCplx=OneChNupPdn_fNdn_MatElCplx;\n\tSTLMatArray[1].SaveMatYN=false;\n\tSTLMatArray[1].IsComplex=true;\n\n\n\tswitch (calcdens){\n\tcase 0: // OpAvg: n_d(T), S_z(T) -(2014)\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false; // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatElCplx=ImpOnly_MatElCplx;\n\t  auxNRGMat.IsComplex=true;\n\n\t  STLMatArray[2]=auxNRGMat; // 2 - ndot (there already)\n\t  STLMatArray[3]=auxNRGMat; // 3 - Sz (there already)\n\t  strcpy(STLMatArray[2].MatName,\"Ndot\");\n\t  strcpy(STLMatArray[3].MatName,\"Szdot\");\n\t  STLMatArray.push_back(auxNRGMat);\n\t  strcpy(STLMatArray[4].MatName,\"Nf\"); // 4 -Nf\n\t  // changes in STLMatArray!\n\t  SaveData=false;\n\t  // No Thermo\n\t  NumThermoMats=0;\n\t  break;\n \tcase 1: //Spectral density\n\t  // cd_up and cd_dn (OneChQSz_SetAnderson equals \n\t  // MatArray[2,3] to MatArray[0,1]\n\t  STLMatArray[2].NeedOld=true;\n\t  STLMatArray[2].CheckForMatEl=OneChNupPdn_cdup_check;\n\t  STLMatArray[2].CalcMatElCplx=OneChNupPdn_cdup_MatElCplx;\n\t  STLMatArray[2].SaveMatYN=true;\n\t  STLMatArray[2].IsComplex=true;\n\t  strcpy(STLMatArray[2].MatName,\"cd_up\");\n\n\t  STLMatArray[3].NeedOld=true;\n\t  STLMatArray[3].CheckForMatEl=OneChNupPdn_cddn_check;\n\t  STLMatArray[3].CalcMatElCplx=OneChNupPdn_cddn_MatElCplx;\n\t  STLMatArray[3].SaveMatYN=true;\n\t  STLMatArray[3].IsComplex=true;\n\t  strcpy(STLMatArray[3].MatName,\"cd_dn\");\n\n\t  // f_Maj (this looks ok)\n\t  auxNRGMat=STLMatArray[3];\n\t  STLMatArray.push_back(auxNRGMat);\n\t  strcpy(STLMatArray[4].MatName,\"f_Maj\");\n\n\t  // TODO: Add other spectral functions??\n\n\t  cout << \" N = -1: Nothing here\" << endl;\n// \t  cout << \" fdN_up : \" << endl;\n// \t  STLMatArray[0].PrintAllBlocks();\n// \t  cout << \" fdN_dn : \" << endl;\n// \t  STLMatArray[1].PrintAllBlocks();\n// \t  cout << \" cdN_up : \" << endl;\n// \t  STLMatArray[2].PrintAllBlocks();\n// \t  cout << \" cdN_dn : \" << endl;\n// \t  STLMatArray[3].PrintAllBlocks();\n// \t  cout << \" f_Maj : \" << endl;\n// \t  STLMatArray[4].PrintAllBlocks();\n\n\t  SaveData=true;\n\n \t  break;\n\tcase 2:\n\t  cout << \"Entropy calculation (implementing it...)\" << endl;\n\n\t  STLMatArray.pop_back(); // Only TWO arrays\n\t  STLMatArray.pop_back(); // Only TWO arrays\n\n\t  // Need to change chain files for ALL Models!!\n\t  strcpy(ThermoArray[0].ArqName,\"EntropyImp1ChNupPdn_Majorana\");\n\t  strcat(ThermoArray[0].ArqName,zstring);\n\t  strcat(ThermoArray[0].ArqName,\".dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"EntropyChain1Ch_NupPdn\");\n\t  strcat(ThermoArray[0].ChainArqName,zstring);\n\t  strcat(ThermoArray[0].ChainArqName,\".dat\");\n\t  ThermoArray[0].Calc=CalcEntropy;\n\t  ThermoArray[0].dImpValue=3.0*log(2.0); // log(8)\n\t  ThermoArray[0].CalcChain=false;\n\t  NumThermoMats=1;\n\t  SaveData=false;\n\n\t  break;\n\tdefault:\n\t  cout << \" calcdens = \" << calcdens << \" not implemented. Exiting. \" << endl;\n\t  exit(0);\n\t}\n\t// end switch calcdens\n\n\t// actually SetHm1 !\n\tOneChNupPdn_SetH0_AndersonMajorana(Params,pSingleSite,pAeig,STLMatArray);\n\n// \t// BuildBasis params (already out of here)\n\t// Set pHN\n\tpHN->IsComplex=true;\n\tpHN->CalcHNMatElCplx=OneChNupPdn_HN_MatElCplx;\n\n\t// Wrap up\n\tNumChannels=1;\n\tNsites0=0;\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\t// changes in STLMatArray!\n\n\tcout << \" N=-1 ok. Going to N=0... \" << endl;\n\t\n\tcout << \" pAeig is complex ? \" << pAeig->CheckComplex() << endl;\n\n\n\t//exit(0);\n\tbreak;\n      default:\n\tcout << \" Model not implemented for this symmetry. Exiting... \" << endl;\n\texit(0);\n      }  \n      // end switch ModelNo for OneChNupPdn\n      break;\n\n    case 7: // OneChS\n      /////////////////////////////\n      /////                    ////\n      ///// Symmetry: OneChS   ////\n      /////                    ////\n      /////////////////////////////\n      // BuildBasis params\n      CommonQNs.push_back(1); // No of common QNs\n      CommonQNs.push_back(0); // pos of QN 1 in old\n      CommonQNs.push_back(0); // pos of QN 1 in SingleSite\n      \n      totSpos.push_back(0);   // SU(2) symmetry in position 1\n\n      switch(ModelNo){\n      //////////////////////////////////////\n      /// Models so far:                 ///\n      ///  0 - Anderson (SC leads)       ///\n      //////////////////////////////////////\n      case 0: // Single-impurity Anderson model S symmetry with SC leads\n\n\t// Initialize matrices \n\t// Jul 09: using STMatArray\n\n\t// fN (reduced)\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].UpperTriangular=false;\n\tSTLMatArray[0].CheckForMatEl=OneChS_cd_check;\n\tSTLMatArray[0].CalcMatEl=OneChS_fN_MatEl;\n\tSTLMatArray[0].SaveMatYN=false;\n\n\tswitch (calcdens){\n\tcase 0: // OpAvg: n_d(T), n^2_d(T), S^2(T) - NEW (2012)\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false; // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\t  STLMatArray[1]=auxNRGMat; // 1 - ndot (there already)\n\t  STLMatArray[2]=auxNRGMat; // 2 - ndot^2 (there already)\n\t  STLMatArray[3]=auxNRGMat; // 3 - Sdot^2 (there already)\n\t  strcpy(STLMatArray[1].MatName,\"Ndot\");\n\t  strcpy(STLMatArray[2].MatName,\"NdSq\");\n\t  strcpy(STLMatArray[3].MatName,\"SdSq\");\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; // Need to do this after\n\t  // changes in STLMatArray!\n\t  SaveData=false;\n// \t  STLMatArray.pop_back(); // 1 Matrices only\n// \t  STLMatArray.pop_back(); // 1 Matrices only\n// \t  STLMatArray.pop_back(); // 1 Matrices only\n\t  // No Thermo\n\t  NumThermoMats=0;\n\t  break;\n\tcase 1: //Spectral density\n\t  STLMatArray.pop_back(); // 2 Matrices\n\t  STLMatArray.pop_back(); // 2 Matrices\n\t  NumThermoMats=0;\n\t  // cd operator \n\t  STLMatArray[1].NeedOld=true;\n\t  STLMatArray[1].UpperTriangular=false;\n\t  STLMatArray[1].CheckForMatEl=OneChS_cd_check;\n\t  STLMatArray[1].CalcMatEl=OneChS_cd_MatEl;\n\t  STLMatArray[1].SaveMatYN=true;\n\t  strcpy(STLMatArray[1].MatName,\"cdot1\");\n\t  NumNRGmats=STLMatArray.size();\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"1chSAndersonSC\");\n\t  break;\n\tcase 4: // Dynamical spin susceptibility and <Sz> and <Sz^2> (2015)\n\t  // 6 Matrices\n\t  STLMatArray.push_back(auxNRGMat);\n\t  STLMatArray.push_back(auxNRGMat);\n\t  NumThermoMats=0;\n\t  // <Sz> and <Sz2> operator \n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false;\n\t  // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\n\t  STLMatArray[2]=auxNRGMat; // 2 - Sz dynamical\n\t  STLMatArray[2].SaveMatYN=true;\n\t  STLMatArray[2].CalcAvg=false;\n\n\t  STLMatArray[3]=auxNRGMat; // 3 - Nd dynamical\n\t  STLMatArray[3].SaveMatYN=true;\n\t  STLMatArray[3].CalcAvg=false;\n\n\t  STLMatArray[4]=auxNRGMat; // 4 - <Sz2>(T) static\n\t  STLMatArray[4].SaveMatYN=false;\n\n\t  STLMatArray[5]=auxNRGMat; // 5 - <Nd2>(T) static\n\t  STLMatArray[5].SaveMatYN=false;\n\n\t  strcpy(STLMatArray[2].MatName,\"Szomega\");\n\t  strcpy(STLMatArray[3].MatName,\"Ndomega\");\n\t  strcpy(STLMatArray[4].MatName,\"Sz2dot\");\n\t  strcpy(STLMatArray[5].MatName,\"Nd2dot\");\n\n\t  NumNRGmats=STLMatArray.size();\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"1chSAndersonSC\");\n\t  break;\n\n\tdefault:\n\t  cout << \" calcdens = \" << calcdens << \" not implemented. Exiting. \" << endl;\n\t  exit(0);\n\n\t}\n\t// end switch calcdens\n\n\t// Param for H0\n\tParams.push_back(Lambda);\n\tParams.push_back(HalfLambdaFactor);\n\tParams.push_back(dInitParams[0]); // U\n\tParams.push_back(dInitParams[2]); // ed\n\n\tOneChS_SetAnderson_Hm1(Params,pAeig,STLMatArray);\n\n\t// HN params\n\tpHN->CalcHNMatEl=OneChS_HNsc_MatEl;\n\n\t// Wrap up\n\tNumChannels=1;\n\tNsites0=0;\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\t// changes in STLMatArray!\n\n\tbreak;\n\t// end OneChS Anderson model set up\n\n      default:\n\tcout << \" Model not implemented for OneChS symmetry. Exiting... \" << endl;\n\texit(0);\n      }  \n      // end switch ModelNo for OneChS\n      break;\n\n      ///////////////////////\n\n    case 8: // OneChSz\n      /////////////////////////////\n      /////                    ////\n      ///// Symmetry: OneChSz   ////\n      /////                    ////\n      /////////////////////////////\n      // BuildBasis params\n      CommonQNs.push_back(1); // No of common QNs\n      CommonQNs.push_back(0); // pos of QN 1 in old\n      CommonQNs.push_back(0); // pos of QN 1 in SingleSite\n      \n      // No total S variables. Leave totSpos empty\n\n      switch(ModelNo){\n      //////////////////////////////////////\n      /// Models so far:                 ///\n      ///  0 - Anderson (SC leads)       ///\n      //////////////////////////////////////\n      case 0: // Single-impurity Anderson model S symmetry with SC leads\n\n\t// Initialize matrices \n\t// Jul 09: using STMatArray\n\n\t// fNup and fNdn\n\tSTLMatArray[0].NeedOld=false;\n\tSTLMatArray[0].UpperTriangular=false;\n// \tSTLMatArray[0].CheckForMatEl=OneChS_cd_check; // Should work\n\tSTLMatArray[0].CheckForMatEl=OneChSz_cdup_check; // More efficient\n\tSTLMatArray[0].CalcMatEl=OneChSz_fNup_MatEl;\n\tSTLMatArray[0].SaveMatYN=false;\n\n\tSTLMatArray[1].NeedOld=false;\n\tSTLMatArray[1].UpperTriangular=false;\n// \tSTLMatArray[1].CheckForMatEl=OneChS_cd_check; // Should work\n\tSTLMatArray[1].CheckForMatEl=OneChSz_cddn_check; // Should work\n\tSTLMatArray[1].CalcMatEl=OneChSz_fNdn_MatEl;\n\tSTLMatArray[1].SaveMatYN=false;\n\n\n\n\tswitch (calcdens){\n\tcase 0: // OpAvg: n_d(T), Sz(T), Sz(T) - NEW (2012)\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false; // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\t  STLMatArray.push_back(auxNRGMat); // 5 matrices\n\t  STLMatArray[2]=auxNRGMat; // 1 - ndot (there already)\n\t  STLMatArray[3]=auxNRGMat; // 2 - ndot^2 (there already)\n\t  STLMatArray[4]=auxNRGMat; // 3 - Sdot^2 (there already)\n\t  strcpy(STLMatArray[2].MatName,\"Ndot\");\n\t  strcpy(STLMatArray[3].MatName,\"NdSq\");\n\t  strcpy(STLMatArray[4].MatName,\"SdSq\");\n\t  NumNRGmats=STLMatArray.size();\n\t  MatArray=&STLMatArray[0]; // Need to do this after\n\t  // changes in STLMatArray!\n\t  SaveData=false;\n\t  // No Thermo\n\t  NumThermoMats=0;\n\t  break;\n\tcase 1: //Spectral density - 4 matrices (no pop-up)\n\t  NumThermoMats=0;\n\t  // cdup operator \n\t  STLMatArray[2].NeedOld=true;\n\t  STLMatArray[2].UpperTriangular=false;\n// \t  STLMatArray[2].CheckForMatEl=OneChS_cd_check;\n\t  STLMatArray[2].CheckForMatEl=OneChSz_cdup_check;\n\t  STLMatArray[2].CalcMatEl=OneChSz_cdup_MatEl;\n\t  STLMatArray[2].SaveMatYN=true;\n\t  strcpy(STLMatArray[2].MatName,\"cdotup\");\n\t  // cddn operator \n\t  STLMatArray[3].NeedOld=true;\n\t  STLMatArray[3].UpperTriangular=false;\n// \t  STLMatArray[3].CheckForMatEl=OneChS_cd_check;\n\t  STLMatArray[3].CheckForMatEl=OneChSz_cddn_check;\n\t  STLMatArray[3].CalcMatEl=OneChSz_cddn_MatEl;\n\t  STLMatArray[3].SaveMatYN=true;\n\t  strcpy(STLMatArray[3].MatName,\"cdotdn\");\n\n\n\t  NumNRGmats=STLMatArray.size();\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"1chSzAndersonSC\");\n\t  break;\n\tcase 4: // Dynamical spin susceptibility and <Sz> and <Sz^2> (2015)\n\t  /// Stopped here\n\t  // 6 Matrices\n\t  STLMatArray.push_back(auxNRGMat);\n\t  STLMatArray.push_back(auxNRGMat);\n\t  NumThermoMats=0;\n\t  // <Sz> and <Sz2> operator \n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false;\n\t  // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatEl=ImpOnly_MatEl;\n\n\t  STLMatArray[2]=auxNRGMat; // 2 - Sz dynamical\n\t  STLMatArray[2].SaveMatYN=true;\n\t  STLMatArray[2].CalcAvg=false;\n\n\t  STLMatArray[3]=auxNRGMat; // 3 - Nd dynamical\n\t  STLMatArray[3].SaveMatYN=true;\n\t  STLMatArray[3].CalcAvg=false;\n\n\t  STLMatArray[4]=auxNRGMat; // 4 - <Sz2>(T) static\n\t  STLMatArray[4].SaveMatYN=false;\n\n\t  STLMatArray[5]=auxNRGMat; // 5 - <Nd2>(T) static\n\t  STLMatArray[5].SaveMatYN=false;\n\n\t  strcpy(STLMatArray[2].MatName,\"Szomega\");\n\t  strcpy(STLMatArray[3].MatName,\"Ndomega\");\n\t  strcpy(STLMatArray[4].MatName,\"Sz2dot\");\n\t  strcpy(STLMatArray[5].MatName,\"Nd2dot\");\n\n\t  NumNRGmats=STLMatArray.size();\n\t  // changes in STLMatArray!\n\t  SaveData=true;\n\t  strcpy(SaveArraysFileName,\"1chSzAndersonSC\");\n\t  break;\n\n\tdefault:\n\t  cout << \" calcdens = \" << calcdens << \" not implemented. Exiting. \" << endl;\n\t  exit(0);\n\n\t}\n\t// end switch calcdens\n\n\t// Param for H0\n\tParams.push_back(Lambda);\n\tParams.push_back(HalfLambdaFactor);\n\tParams.push_back(dInitParams[0]); // U\n\tParams.push_back(dInitParams[2]); // ed\n\tParams.push_back(dInitParams[4]); // Mag Field.\n       //Note that dInitParams[3] is DeltaSC \n\n\tOneChSz_SetAnderson_Hm1(Params,pAeig,STLMatArray);\n\n\t// HN params\n\tpHN->CalcHNMatEl=OneChSz_HNsc_MatEl;\n\n\tNumChannels=1;\n\n\t// Wrap up\n\tNumChannels=1;\n\tNsites0=0;\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\t// changes in STLMatArray!\n\n\t//exit(0);\n\tbreak;\n\t// end OneChSz Anderson model set up\n\n\n      default:\n\tcout << \" Model not implemented for OneChSz symmetry. Exiting... \" << endl;\n\texit(0);\n      }  \n      // end switch ModelNo for OneChSz\n      break;\n    case 9: // OneChPuPdn\n      //////////////////////////////////\n      /////                         ////\n      ///// Symmetry: OneChPupPdn   ////\n      /////                         ////\n      //////////////////////////////////\n      // BuildBasis params\n      CommonQNs.push_back(2); // No of common QNs\n      CommonQNs.push_back(0); // pos of QN 1 in old\n      CommonQNs.push_back(1); // pos of QN 2 in old\n\n      CommonQNs.push_back(0); // pos of QN 1 in SingleSite\n      CommonQNs.push_back(1); // pos of QN 2 in SingleSite\n\n      CommonQNs.push_back(0); // pos of Parity QN\n      CommonQNs.push_back(1); // pos of Parity QN\n\n      // No total S variables. Leave totSpos empty\n\n      switch(ModelNo){\n      ///////////////////////////////////////\n      /// Models so far:                  ///\n      ///  3 - Chain only                 ///\n      ///  7 - Anderson+ 2 Local Majoranas///\n      ///////////////////////////////////////\n      case 3: // Chain only\n\n\tZeroParams();\n\tNsites0=1; // IS THIS CORRECT? Yes. H_0 is set so we start NRG from H_1\n\tNumThermoMats=1; // Entropy only\n\n\t// Initialize matrices (real matrices)\n\t// fd_up\n\tSTLMatArray[0].NeedOld=false;\t  \n \tSTLMatArray[0].CheckForMatEl=OneChPupPdn_cdup_check;\n  \tSTLMatArray[0].CalcMatEl=OneChPupPdn_fNup_MatEl;\n \t//STLMatArray[0].CalcMatElCplx=OneChNupPdn_fNup_MatElCplx;\n\tSTLMatArray[0].SaveMatYN=false;\n\tSTLMatArray[0].IsComplex=false;\n\n\t// fd_dn\n\tSTLMatArray[1].NeedOld=false;\n \tSTLMatArray[1].CheckForMatEl=OneChPupPdn_cddn_check;\n  \tSTLMatArray[1].CalcMatEl=OneChPupPdn_fNdn_MatEl;\n\tSTLMatArray[1].SaveMatYN=false;\n\tSTLMatArray[1].IsComplex=false;\n\n\tSTLMatArray.pop_back(); // Only TWO arrays\n\tSTLMatArray.pop_back(); // Only TWO arrays\n\n\tOneChPupPdn_SetChainH0(pAeig,STLMatArray);\n\n\t// Set pHN\n\tpHN->CalcHNMatEl=OneChPupPdn_HN_MatEl; // REAL\n\t// Wrap up\n\tNumChannels=1;\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\t// changes in STLMatArray!\n\n\tif (BandNo==0){\n\t  chi_m1[0]=chiN(0,Lambda); // is actually chi0 // chiN is a codehandler func\n\t// Valid ONLY for SquareBand, z_twist=1! Check side dot calcs...\n\t}\n\telse{chi_m1[0]=Chains[0].GetChin(0);}\n\t// Need to change chain files for ALL Models!!\n\tstrcpy(ThermoArray[0].ChainArqName,\"EntropyChain1Ch_PupPdn\");\n\tstrcat(ThermoArray[0].ChainArqName,zstring);\n\tstrcat(ThermoArray[0].ChainArqName,\".dat\");\n\tThermoArray[0].Calc=CalcEntropy;\n\tThermoArray[0].CalcChain=true; // Just to make sure\n\n\tbreak;\n\n// Working on this.\n      case 7: \n\tcout << \" 2 Majoranas + QD effective model \" << endl;\n\n\tParams.push_back(Lambda);  // Lambda\n\tParams.push_back(HalfLambdaFactor); // Lambda factor\n\n\tParams.push_back(dInitParams[0]); // U1\n\tParams.push_back(dInitParams[2]); // ed1\n\tParams.push_back(chi_m1[0]); // sqrt(2gamma1/Pi)/sqrt(L)*HalfLambdaFactor\n\n\tParams.push_back(dInitParams[3]); // Mag Field \n\n\tParams.push_back(dInitParams[4]); // lambdaR (or tR)\n\tParams.push_back(dInitParams[5]); // lambdaL\n\tParams.push_back(dInitParams[6]); // phi/pi\n\n\t// Initialize matrices \n\t// fd_up\n\tSTLMatArray[0].NeedOld=false;\t  \n \tSTLMatArray[0].CheckForMatEl=OneChPupPdn_cdup_check;\n \tSTLMatArray[0].CalcMatElCplx=OneChPupPdn_fNup_MatElCplx;\n\tSTLMatArray[0].SaveMatYN=false;\n\tSTLMatArray[0].IsComplex=true;\n\n\t// fd_dn\n\tSTLMatArray[1].NeedOld=false;\n \tSTLMatArray[1].CheckForMatEl=OneChPupPdn_cddn_check;\n \tSTLMatArray[1].CalcMatElCplx=OneChPupPdn_fNdn_MatElCplx;\n\tSTLMatArray[1].SaveMatYN=false;\n\tSTLMatArray[1].IsComplex=true;\n\n\n\tswitch (calcdens){\n\tcase 0: // OpAvg: n_d(T), S_z(T) -(2014)\n\t  auxNRGMat.NeedOld=true;\n\t  auxNRGMat.UpperTriangular=false; // update procedure only works for 'false'\n\t  auxNRGMat.CalcAvg=true;  // CalcAvg\n\t  auxNRGMat.CheckForMatEl=Diag_check;\n\t  auxNRGMat.CalcMatElCplx=ImpOnly_MatElCplx;\n\t  auxNRGMat.IsComplex=true;\n\n\t  STLMatArray[2]=auxNRGMat; // 2 - ndot (there already)\n\t  STLMatArray[3]=auxNRGMat; // 3 - Sz (there already)\n\t  strcpy(STLMatArray[2].MatName,\"Ndot\");\n\t  strcpy(STLMatArray[3].MatName,\"Szdot\");\n\t  STLMatArray.push_back(auxNRGMat);\n\t  strcpy(STLMatArray[4].MatName,\"Nf\"); // 4 -Nf\n\t  // changes in STLMatArray!\n\t  SaveData=false;\n\t  // No Thermo\n\t  NumThermoMats=0;\n\t  break;\n \tcase 1: //Spectral density\n\t  // cd_up and cd_dn (OneChQSz_SetAnderson equals \n\t  // MatArray[2,3] to MatArray[0,1]\n\t  STLMatArray[2].NeedOld=true;\n\t  STLMatArray[2].CheckForMatEl=OneChPupPdn_cdup_check;\n\t  STLMatArray[2].CalcMatElCplx=OneChPupPdn_cdup_MatElCplx;\n\t  STLMatArray[2].SaveMatYN=true;\n\t  STLMatArray[2].IsComplex=true;\n\t  strcpy(STLMatArray[2].MatName,\"cd_up\");\n\n\n\t  STLMatArray[3].NeedOld=true;\n\t  STLMatArray[3].CheckForMatEl=OneChPupPdn_cddn_check;\n\t  STLMatArray[3].CalcMatElCplx=OneChPupPdn_cddn_MatElCplx;\n\t  STLMatArray[3].SaveMatYN=true;\n\t  STLMatArray[3].IsComplex=true;\n\t  strcpy(STLMatArray[3].MatName,\"cd_dn\");\n\n\t  // f_Maj_up (this looks ok)\n\t  auxNRGMat=STLMatArray[2];\n\t  STLMatArray.push_back(auxNRGMat);\n\t  strcpy(STLMatArray[4].MatName,\"f_MajUp\");\n\n\t  // f_Maj_dn (this looks ok)\n\t  auxNRGMat=STLMatArray[3];\n\t  STLMatArray.push_back(auxNRGMat);\n\t  strcpy(STLMatArray[5].MatName,\"f_MajDn\");\n\n\t  // TODO: Add other spectral functions??\n\n\t  cout << \" N = -1: Nothing here\" << endl;\n// \t  cout << \" fdN_up : \" << endl;\n// \t  STLMatArray[0].PrintAllBlocks();\n// \t  cout << \" fdN_dn : \" << endl;\n// \t  STLMatArray[1].PrintAllBlocks();\n// \t  cout << \" cdN_up : \" << endl;\n// \t  STLMatArray[2].PrintAllBlocks();\n// \t  cout << \" cdN_dn : \" << endl;\n// \t  STLMatArray[3].PrintAllBlocks();\n// \t  cout << \" f_MajUp : \" << endl;\n// \t  STLMatArray[4].PrintAllBlocks();\n// \t  cout << \" f_MajDn : \" << endl;\n// \t  STLMatArray[5].PrintAllBlocks();\n\n\t  SaveData=true;\n\n \t  break;\n\tcase 2:\n\t  cout << \"Entropy calculation (implementing it...)\" << endl;\n\n\t  STLMatArray.pop_back(); // Only TWO arrays\n\t  STLMatArray.pop_back(); // Only TWO arrays\n\n\t  // Need to change chain files for ALL Models!!\n\t  strcpy(ThermoArray[0].ArqName,\"EntropyImp1ChPupPdn_Majorana\");\n\t  strcat(ThermoArray[0].ArqName,zstring);\n\t  strcat(ThermoArray[0].ArqName,\".dat\");\n\t  strcpy(ThermoArray[0].ChainArqName,\"EntropyChain1Ch_PupPdn\");\n\t  strcat(ThermoArray[0].ChainArqName,zstring);\n\t  strcat(ThermoArray[0].ChainArqName,\".dat\");\n\t  ThermoArray[0].Calc=CalcEntropy;\n\t  ThermoArray[0].dImpValue=4.0*log(2.0); // log(16) (check)\n\t  ThermoArray[0].CalcChain=false;\n\t  NumThermoMats=1;\n\t  SaveData=false;\n\n\t  break;\n\tdefault:\n\t  cout << \" calcdens = \" << calcdens << \" not implemented. Exiting. \" << endl;\n\t  exit(0);\n\t}\n\t// end switch calcdens\n\n\t// actually SetHm1 !\n\tOneChPupPdn_SetHm1_AndersonMajorana(Params,pSingleSite,pAeig,STLMatArray);\n\n// \t// BuildBasis params (already out of here)\n\t// Set pHN\n\tpHN->IsComplex=true;\n\tpHN->CalcHNMatElCplx=OneChPupPdn_HN_MatElCplx;\n\n\t// Wrap up\n\tNumChannels=1;\n\tNsites0=0;\n\tNumNRGmats=STLMatArray.size();\n\tMatArray=&STLMatArray[0]; // Need to do this after\n\t                          // changes in STLMatArray!\n\n\tcout << \" N=-1 ok. Going to N=0... \" << endl;\n\t\n\tcout << \" pAeig is complex ? \" << pAeig->CheckComplex() << endl;\n\n\n\t//exit(0);\n\tbreak;\n      default:\n\tcout << \" Model not implemented for this symmetry. Exiting... \" << endl;\n\texit(0);\n      }  \n      // end switch ModelNo for OneChPupPdn\n      break;\n/////////////////////////////    \n    default:\n      cout << \" Symmetry not implemented. Exiting... \" << endl;\n      exit(0);    \n    }\n    // end switch SymNo\n\n}\n// end ModelSwitch\n", "meta": {"hexsha": "c7ed60f152a2d9ae6b8edfc6d13a64d9dca6ac54", "size": 68882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CodeHandler_ModelSwitch.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/CodeHandler_ModelSwitch.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/CodeHandler_ModelSwitch.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": 30.9303996408, "max_line_length": 113, "alphanum_fraction": 0.6741819343, "num_tokens": 23618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752916, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.19874825494268403}}
{"text": "#include \"Time.hpp\"\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include \"foundation/ArgumentException.hpp\"\n#include \"foundation/OutOfRangeException.hpp\"\n\nusing namespace boost::posix_time;\n\nstatic const long ticks_per_day = 24 * 3600 * 1000 * (long)(time_duration::ticks_per_second() / 1000);\n\nclass axis::foundation::date_time::Time::TimeData\n{\nprivate:\n\tboost::posix_time::time_duration _time;\npublic:\n\tTimeData(void) : _time(time_duration::hour_type(0), time_duration::min_type(0), time_duration::sec_type(0))\n\t{\n\t\t// nothing to do here\n\t}\n\tboost::posix_time::time_duration GetTime(void) const\n\t{\n\t\treturn _time;\n\t}\n\tvoid SetTime(const boost::posix_time::time_duration& time)\n\t{\n\t\t_time = time;\n\t}\n\tint GetHours(void) const\n\t{\n\t\treturn _time.hours();\n\t}\n\tint GetMinutes(void) const\n\t{\n\t\treturn _time.minutes();\n\t}\n\tint GetSeconds(void) const\n\t{\n\t\treturn _time.seconds();\n\t}\n\tint GetMilliseconds(void) const\n\t{\n\t\treturn (int)(_time.fractional_seconds()*1000 / boost::posix_time::time_duration::ticks_per_second());\n\t}\n};\n\n\n\naxis::foundation::date_time::Time::Time( void )\n{\n\t_data = new TimeData();\n}\n\naxis::foundation::date_time::Time::Time( const Time& other )\n{\n\t_data = new TimeData();\n\t_data->SetTime(other._data->GetTime());\n}\n\naxis::foundation::date_time::Time::Time( int hours, int minutes, int seconds )\n{\n\ttime_duration t(hours, minutes, seconds);\n\tif (t.total_milliseconds() < 0 || t.total_milliseconds() > ticks_per_day)\n\t{\n\t\tthrow axis::foundation::ArgumentException(_T(\"Invalid time.\"));\n\t}\n\t_data = new TimeData();\n\t_data->SetTime(t);\n}\n\naxis::foundation::date_time::Time::Time( int hours, int minutes, int seconds, int milliseconds )\n{\n\tint millis = (int)(milliseconds * (time_duration::ticks_per_second() / 1000));\n\ttime_duration t(hours, minutes, seconds, millis);\n\tif (t.total_milliseconds() < 0 || t.total_milliseconds() > ticks_per_day)\n\t{\n\t\tthrow axis::foundation::ArgumentException(_T(\"Invalid time.\"));\n\t}\n\t_data = new TimeData();\n\t_data->SetTime(t);\n}\n\naxis::foundation::date_time::Time::~Time( void )\n{\n\tdelete _data;\n}\n\nint axis::foundation::date_time::Time::GetHours( void ) const\n{\n\treturn _data->GetHours();\n}\n\nint axis::foundation::date_time::Time::GetMinutes( void ) const\n{\n\treturn _data->GetMinutes();\n}\n\nint axis::foundation::date_time::Time::GetSeconds( void ) const\n{\n\treturn _data->GetSeconds();\n}\n\nint axis::foundation::date_time::Time::GetMilliseconds( void ) const\n{\n\treturn _data->GetMilliseconds();\n}\n\nlong axis::foundation::date_time::Time::GetTotalMinutes( void ) const\n{\n\treturn GetHours()*60 + GetMinutes();\n}\n\nlong axis::foundation::date_time::Time::GetTotalSeconds( void ) const\n{\n\treturn GetTotalMinutes()*60 + GetSeconds();\n}\n\nlong axis::foundation::date_time::Time::GetTotalMilliseconds( void ) const\n{\n\treturn GetTotalSeconds()*1000 + GetMilliseconds();\n}\n\nbool axis::foundation::date_time::Time::operator<( const Time& other ) const\n{\n\treturn _data->GetTime() < other._data->GetTime();\n}\n\nbool axis::foundation::date_time::Time::operator<=( const Time& other ) const\n{\n\treturn _data->GetTime() <= other._data->GetTime();\n}\n\nbool axis::foundation::date_time::Time::operator>( const Time& other ) const\n{\n\treturn _data->GetTime() > other._data->GetTime();\n}\n\nbool axis::foundation::date_time::Time::operator>=( const Time& other ) const\n{\n\treturn _data->GetTime() >= other._data->GetTime();\n}\n\nbool axis::foundation::date_time::Time::operator==( const Time& other ) const\n{\n\treturn _data->GetTime() == other._data->GetTime();\n}\n\nbool axis::foundation::date_time::Time::operator!=( const Time& other ) const\n{\n\treturn _data->GetTime() != other._data->GetTime();\n}\n\naxis::foundation::date_time::Time& axis::foundation::date_time::Time::operator=( const Time& other )\n{\n\tif (this == &other) return *this;\n\t_data->SetTime(other._data->GetTime());\n\treturn *this;\n}\n\naxis::foundation::date_time::Time axis::foundation::date_time::Time::Now( void )\n{\n\tptime p = microsec_clock::local_time();\n\treturn Time(p.time_of_day().hours(), p.time_of_day().minutes(), \n\t\t\t\tp.time_of_day().seconds(), (int)(p.time_of_day().fractional_seconds() * 1000 / time_duration::ticks_per_second()));\n}\n\naxis::foundation::date_time::Time axis::foundation::date_time::operator+( const Time& time, const Timespan& timespan )\n{\n\tif (timespan.HasWholeDays())\n\t{\n\t\tthrow axis::foundation::ArgumentException(_T(\"Cannot operate on whole days.\"));\n\t}\n\n\ttime_duration t1(time.GetHours(), time.GetMinutes(), time.GetSeconds(), time.GetMilliseconds() * time_duration::ticks_per_second() / 1000);\n\ttime_duration t2(timespan.GetHours(), timespan.GetMinutes(), timespan.GetSeconds(), timespan.GetMilliseconds() * time_duration::ticks_per_second() / 1000);\n\n\ttime_duration t = t1 + t2;\n\tif (t.total_milliseconds() < 0 || t.total_milliseconds() > ticks_per_day)\n\t{\n\t\tthrow axis::foundation::OutOfRangeException(_T(\"Result is not a valid time.\"));\n\t}\n\t\n\treturn Time(t.hours(), t.minutes(), t.seconds(), (int)(t.fractional_seconds() * 1000 / time_duration::ticks_per_second()));\n}\n\naxis::foundation::date_time::Time axis::foundation::date_time::operator-( const Time& time, const Timespan& timespan )\n{\n\tif (timespan.HasWholeDays())\n\t{\n\t\tthrow axis::foundation::ArgumentException(_T(\"Cannot operate on whole days.\"));\n\t}\n\n\ttime_duration t1(time.GetHours(), time.GetMinutes(), time.GetSeconds(), time.GetMilliseconds() * time_duration::ticks_per_second() / 1000);\n\ttime_duration t2(timespan.GetHours(), timespan.GetMinutes(), timespan.GetSeconds(), timespan.GetMilliseconds() * time_duration::ticks_per_second() / 1000);\n\n\ttime_duration t = t1 - t2;\n\tif (t.total_milliseconds() < 0 || t.total_milliseconds() > ticks_per_day)\n\t{\n\t\tthrow axis::foundation::OutOfRangeException(_T(\"Result is not a valid time.\"));\n\t}\n\n\treturn Time(t.hours(), t.minutes(), t.seconds(), (int)(t.fractional_seconds() * 1000 / time_duration::ticks_per_second()));\n}\n\naxis::foundation::date_time::Timespan axis::foundation::date_time::operator-( const Time& t1, const Time& t2 )\n{\n\ttime_duration tm1(t1.GetHours(), t1.GetMinutes(), t1.GetSeconds(), t1.GetMilliseconds() * time_duration::ticks_per_second() / 1000);\n\ttime_duration tm2(t2.GetHours(), t2.GetMinutes(), t2.GetSeconds(), t2.GetMilliseconds() * time_duration::ticks_per_second() / 1000);\n\n\ttime_duration t = tm1 - tm2;\n\n\treturn Timespan(t.hours(), t.minutes(), t.seconds(), (long)(t.fractional_seconds() * 1000 / time_duration::ticks_per_second()));\n}\n", "meta": {"hexsha": "4402bf81fd49833340a1e0a9b0d5d4f44e5f4217", "size": 6402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Axis.SystemBase/foundation/date_time/Time.cpp", "max_stars_repo_name": "renato-yuzup/axis-fem", "max_stars_repo_head_hexsha": "2e8d325eb9c8e99285f513b4c1218ef53eb0ab22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-23T08:49:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T22:07:30.000Z", "max_issues_repo_path": "Axis.SystemBase/foundation/date_time/Time.cpp", "max_issues_repo_name": "renato-yuzup/axis-fem", "max_issues_repo_head_hexsha": "2e8d325eb9c8e99285f513b4c1218ef53eb0ab22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Axis.SystemBase/foundation/date_time/Time.cpp", "max_forks_repo_name": "renato-yuzup/axis-fem", "max_forks_repo_head_hexsha": "2e8d325eb9c8e99285f513b4c1218ef53eb0ab22", "max_forks_repo_licenses": ["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.1981132075, "max_line_length": 156, "alphanum_fraction": 0.7169634489, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19873421324659063}}
{"text": "// Copyright (c) 2019, The Graft Project\n//\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//\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n//\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\n//    materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    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\n// EXPRESS 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\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// 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\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n\n#include <boost/endian/conversion.hpp>\n#include \"cryptmsg.h\"\n#include \"crypto/chacha.h\"\n\nnamespace {\n\nstatic_assert(201103L <= __cplusplus, \"C++11 compiler required\");\n\n#if 0\n//can be used to check manually\n#define native_to_little boost::endian::native_to_big\n#define little_to_native boost::endian::big_to_native\n#else\nusing namespace boost::endian;\n#endif\n\ninline size_t getEncryptChachaSize(size_t plainSize)\n{\n    return plainSize + sizeof(crypto::chacha_iv);\n}\n\nvoid encryptChacha(const uint8_t* plain, size_t plain_size, const crypto::secret_key &skey, uint8_t* cipher)\n{\n  crypto::chacha_key key;\n  crypto::generate_chacha_key(&skey, sizeof(skey), key);\n  crypto::chacha_iv& iv = *reinterpret_cast<crypto::chacha_iv*>(cipher);\n  iv = crypto::rand<crypto::chacha_iv>();\n  crypto::chacha8(plain, plain_size, key, iv, reinterpret_cast<char*>(cipher) + sizeof(iv));\n}\n\nvoid decryptChacha(const uint8_t* cipher, size_t cipher_size, const crypto::secret_key &skey, uint8_t* plain)\n{\n  const size_t prefix_size = sizeof(crypto::chacha_iv);\n  crypto::chacha_key key;\n  crypto::generate_chacha_key(&skey, sizeof(skey), key);\n  const crypto::chacha_iv &iv = *reinterpret_cast<const crypto::chacha_iv*>(cipher);\n  crypto::chacha8(reinterpret_cast<const char*>(cipher) + sizeof(iv), cipher_size - prefix_size, key, iv, reinterpret_cast<char*>(plain));\n}\n\nconstexpr uint8_t cStart = 0xA5;\nconstexpr uint8_t cEnd = 0x5A;\n\n#pragma pack(push, 1)\n\n//Note, native order is little-endian\n\n//SessionX in decrypted form contains session key x and constants to check that the decryption was correct\nstruct SessionX\n{\n    uint8_t cstart; //decrypted value cStart\n    crypto::secret_key x;\n    uint8_t cend; //decrypted value cEnd\n};\n\nstruct XEntry\n{\n    uint32_t Bhash; //xor of B\n    uint8_t cipherX[sizeof(SessionX) + sizeof(crypto::chacha_iv)]; //encrypted SessionX\n};\n\nstruct CryptoMessageHead\n{\n    uint32_t plainSize; //size of decrypted data\n    crypto::public_key R; //random key used to encrypt session key\n    uint16_t count; //recipients count\n    XEntry xentries[1];\n};\n\n#pragma pack(pop)\n\nuint32_t getBhash(const crypto::public_key& B)\n{\n    uint32_t res = 0;\n    static_assert(sizeof(B) % sizeof(res) == 0, \"public key size must be a multiple of 4\");\n    const uint32_t* p = reinterpret_cast<const uint32_t*>(&B);\n    for(int i = 0, cnt = sizeof(B) / sizeof(res); i < cnt; ++i, ++p)\n    {\n        res ^= *p;\n    }\n    return native_to_little(res);\n}\n\n/*!\n * \\brief encryptMsg - encrypts data for recipients using their B public keys (assumed public view keys).\n *\n * The result has following structure [plainSize:32][R:32][count of XEntrys:16][XEntry]...[XEntry][x encrypted data:+8*8]\n * plainSize - size of original data, x encrypted data takes 8 more bytes\n * [XEntry] - [Bhash:32][rBX] pair for each recipient\n * where Bhash - xor of B (aka fingerprint of B, using which recipient can find his entry)\n * [rBX:+8*8] - encrypted X (aka SessionX)\n * [X] = [cstart:8][x:32*8][cend:8]\n *\n * \\param inputSize - input buffer size.\n * \\param input - input buffer to encrypt.\n * \\param BkeysCount - count of B keys.\n * \\param Bkeys - array of B keys for each recipients.\n * \\param outputSize - output buffer size.\n * \\param output - output buffer.\n * \\returns output size required if output==nullptr or outputSize is not enough.\n * returns 0 on error\n */\n\nsize_t encryptMsg(size_t inputSize, const uint8_t* input, size_t BkeysCount, const crypto::public_key* Bkeys, size_t outputSize, uint8_t* output)\n{\n    if(!inputSize || !BkeysCount)\n        return 0;\n\n    //prepare\n    size_t msgHeadSize = sizeof(CryptoMessageHead) + (BkeysCount - 1) * sizeof(XEntry);\n    size_t msgSize = msgHeadSize + getEncryptChachaSize(inputSize);\n    if(outputSize < msgSize)\n        return msgSize;\n    if(!input || !Bkeys || !output)\n        return 0;\n\n    //make decorated session key\n    SessionX X; X.cstart = cStart; X.cend = cEnd;\n    //generate session key X.x\n    {\n        crypto::public_key tmpX;\n        crypto::generate_keys(tmpX,X.x);\n    }\n    //chacha encrypt input with x\n    encryptChacha(input, inputSize, X.x, output + msgHeadSize);\n\n    //fill head\n    CryptoMessageHead& head = *reinterpret_cast<CryptoMessageHead*>(output);\n    head.plainSize = native_to_little(uint32_t(inputSize));\n    crypto::secret_key r;\n    crypto::generate_keys(head.R, r);\n    head.count = native_to_little(uint16_t(BkeysCount));\n    //fill XEntry for each B\n    const crypto::public_key* pB = Bkeys;\n    XEntry* pxe = head.xentries;\n    for(size_t i=0; i<BkeysCount; ++i, ++pxe, ++pB)\n    {\n        const crypto::public_key& B = *pB;\n        XEntry& xe = *pxe;\n        xe.Bhash = getBhash(B);\n        //get rB key\n        crypto::key_derivation rBv;\n        crypto::generate_key_derivation(B, r, rBv);\n        crypto::secret_key rB;\n        crypto::derivation_to_scalar(rBv, 0, rB);\n        //encrypt X with rB key\n        encryptChacha(reinterpret_cast<const uint8_t*>(&X), sizeof(X), rB, xe.cipherX);\n    }\n    return msgSize;\n}\n\n/*!\n * \\brief decryptMsg - (reverse of encryptMsg) decrypts data for one of the recipients using his secret key b.\n *\n * \\param inputSize - input buffer size.\n * \\param input - input buffer to decrypt.\n * \\param bkey - secret key corresponding to one of Bs that were used to encrypt.\n * \\param outputSize - output buffer size.\n * \\param output - output buffer.\n * \\returns output size required if output==nullptr or outputSize is not enough\n * returns 0 on error\n */\n\nsize_t decryptMsg(size_t inputSize, const uint8_t* input, const crypto::secret_key& bkey, size_t outputSize, uint8_t* output)\n{\n    if(!input || inputSize <= sizeof(CryptoMessageHead))\n        return 0;\n    //prepare\n    const CryptoMessageHead& head = *reinterpret_cast<const CryptoMessageHead*>(input);\n    size_t head_count = little_to_native(head.count);\n    size_t head_plainSize = little_to_native(head.plainSize);\n    size_t msgHeadSize = sizeof(CryptoMessageHead) + ((size_t)(head_count - 1)) * sizeof(XEntry);\n    size_t msgSize = msgHeadSize + getEncryptChachaSize(head_plainSize);\n    if(inputSize < msgSize)\n        return 0;\n    if(outputSize < head_plainSize)\n        return head_plainSize;\n    if(!output)\n        return 0;\n\n    //get Bhash from b\n    const crypto::secret_key& b = bkey;\n    uint32_t Bhash;\n    {\n        crypto::public_key B;\n        bool res = crypto::secret_key_to_public_key(bkey, B);\n        if(!res) return false; //corrupted key\n        Bhash = getBhash(B);\n    }\n    //find XEntry for B\n    const XEntry* pxe = head.xentries;\n    for(size_t i=0; i<head_count; ++i, ++pxe)\n    {\n        const XEntry& xe = *pxe;\n        if(xe.Bhash != Bhash) continue;\n        //get bR key\n        crypto::key_derivation bRv;\n        crypto::generate_key_derivation(head.R, b, bRv);\n        crypto::secret_key bR;\n        crypto::derivation_to_scalar(bRv, 0, bR);\n        //decrypt to X\n        SessionX X;\n        decryptChacha(xe.cipherX, sizeof(xe.cipherX), bR, reinterpret_cast<uint8_t*>(&X));\n        if(X.cstart != cStart || X.cend != cEnd) continue;\n        //decrypt with session key\n        decryptChacha(input + msgHeadSize, getEncryptChachaSize(head_plainSize), X.x, output);\n        return head_plainSize;\n    }\n    return 0;\n}\n\n} //namespace\n\nnamespace graft { namespace crypto_tools {\n\nvoid encryptMessage(const std::string& input, const std::vector<crypto::public_key>& Bkeys, std::string& output)\n{\n    assert(!input.empty());\n    //get output size\n    size_t size = encryptMsg( input.size(), nullptr, Bkeys.size(), nullptr, 0, nullptr);\n    assert(0<size);\n    output.resize(size);\n    //encrypt\n    size_t res = encryptMsg( input.size(), reinterpret_cast<const uint8_t*>(input.data()),\n                             Bkeys.size(), &Bkeys[0],\n            output.size(), reinterpret_cast<uint8_t*>(&output[0]));\n    assert(res == size);\n}\n\nvoid encryptMessage(const std::string& input, const crypto::public_key& Bkey, std::string& output)\n{\n    std::vector<crypto::public_key> v(1, Bkey);\n    encryptMessage(input, v, output);\n}\n\nbool decryptMessage(const std::string& input, const crypto::secret_key& bkey, std::string& output)\n{\n    assert(!input.empty());\n    //get output size\n    size_t size = decryptMsg( input.size(), reinterpret_cast<const uint8_t*>(input.data()), bkey, 0, nullptr);\n    if(!size)\n    {\n        output.clear();\n        return false;\n    }\n    output.resize(size);\n    //encrypt\n    size_t res = decryptMsg( input.size(), reinterpret_cast<const uint8_t*>(input.data()),\n                             bkey, output.size(), reinterpret_cast<uint8_t*>(&output[0]));\n    if(!res)\n    {\n        output.clear();\n        return false;\n    }\n    assert(res == size);\n    return true;\n}\n\n}} //namespace graft::crypto_tools\n\n", "meta": {"hexsha": "21c12fa4665bcec6ae5c0443aab97d96896a6bcf", "size": 10329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/cryptmsg.cpp", "max_stars_repo_name": "Fez29/GraftNetwork", "max_stars_repo_head_hexsha": "75c55efdc6f77d7c10639425e695a955e6e59798", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T09:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-03T09:05:40.000Z", "max_issues_repo_path": "src/utils/cryptmsg.cpp", "max_issues_repo_name": "Fez29/GraftNetwork", "max_issues_repo_head_hexsha": "75c55efdc6f77d7c10639425e695a955e6e59798", "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/cryptmsg.cpp", "max_forks_repo_name": "Fez29/GraftNetwork", "max_forks_repo_head_hexsha": "75c55efdc6f77d7c10639425e695a955e6e59798", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T06:59:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-14T06:59:14.000Z", "avg_line_length": 35.7404844291, "max_line_length": 145, "alphanum_fraction": 0.6870945881, "num_tokens": 2701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19873420851062892}}
{"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// File generated at Wed 4 Apr 2018 09:58:31\n\n/**\n * @file MDM_two_scale_ewsb_solver.hpp\n *\n * @brief contains class for solving EWSB when two-scale algorithm is used\n *\n * This file was generated at Wed 4 Apr 2018 09:58:31 with FlexibleSUSY\n * 2.0.1 (git commit: unknown) and SARAH 4.12.2 .\n */\n\n#ifndef MDM_TWO_SCALE_EWSB_SOLVER_H\n#define MDM_TWO_SCALE_EWSB_SOLVER_H\n\n#include \"MDM_ewsb_solver.hpp\"\n#include \"MDM_ewsb_solver_interface.hpp\"\n#include \"error.hpp\"\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\nclass Two_scale;\n\nclass MDM_mass_eigenstates;\n\ntemplate<>\nclass MDM_ewsb_solver<Two_scale> : public MDM_ewsb_solver_interface {\npublic:\n   MDM_ewsb_solver() = default;\n   MDM_ewsb_solver(const MDM_ewsb_solver&) = default;\n   MDM_ewsb_solver(MDM_ewsb_solver&&) = default;\n   virtual ~MDM_ewsb_solver() {}\n   MDM_ewsb_solver& operator=(const MDM_ewsb_solver&) = default;\n   MDM_ewsb_solver& operator=(MDM_ewsb_solver&&) = default;\n\n   virtual void set_loop_order(int l) override { loop_order = l; }\n   virtual void set_number_of_iterations(int n) override { number_of_iterations = n; }\n   virtual void set_precision(double p) override { precision = p; }\n\n   virtual int get_loop_order() const override { return loop_order; }\n   virtual int get_number_of_iterations() const override { return number_of_iterations; }\n   virtual double get_precision() const override { return precision; }\n\n   virtual int solve(MDM_mass_eigenstates&) override;\nprivate:\n   static const int number_of_ewsb_equations = 1;\n   using EWSB_vector_t = Eigen::Matrix<double,number_of_ewsb_equations,1>;\n\n   class EEWSBStepFailed : public Error {\n   public:\n      virtual ~EEWSBStepFailed() {}\n      virtual std::string what() const { return \"Could not perform EWSB step.\"; }\n   };\n\n   int number_of_iterations{100}; ///< maximum number of iterations\n   int loop_order{2};             ///< loop order to solve EWSB at\n   double precision{1.e-5};       ///< precision goal\n\n   void set_ewsb_solution(MDM_mass_eigenstates&, const EWSB_solver*);\n   template <typename It> void set_best_ewsb_solution(MDM_mass_eigenstates&, It, It);\n\n   int solve_tree_level(MDM_mass_eigenstates&);\n   int solve_iteratively(MDM_mass_eigenstates&);\n   int solve_iteratively_at(MDM_mass_eigenstates&, int);\n   int solve_iteratively_with(MDM_mass_eigenstates&, EWSB_solver*, const EWSB_vector_t&);\n\n   EWSB_vector_t initial_guess(const MDM_mass_eigenstates&) const;\n   EWSB_vector_t tadpole_equations(const MDM_mass_eigenstates&) const;\n   EWSB_vector_t ewsb_step(const MDM_mass_eigenstates&) const;\n};\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "4d356af96d0c4ff66987c231c948829ba71defd8", "size": 3452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MDM/MDM_two_scale_ewsb_solver.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MDM/MDM_two_scale_ewsb_solver.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MDM/MDM_two_scale_ewsb_solver.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 36.3368421053, "max_line_length": 89, "alphanum_fraction": 0.7224797219, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1986763547726966}}
{"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/quantizer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\n\n#ifdef USE_GEMMLOWP\n#include \"public/gemmlowp.h\"\n#endif\n\nnamespace caffe {\n\ntemplate<typename Dtype>\ntypename std::enable_if<unsigned_integer_is_same<Dtype>::value, bool>::type\ngemmlowp_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n              const int_tp M, const int_tp N, const int_tp K,\n              const Dtype alpha, const Dtype* A,\n              const Dtype* B, const Dtype beta, Dtype* C,\n              const QuantizerValues* const alpha_quant,\n              const QuantizerValues* const a_quant,\n              const QuantizerValues* const b_quant,\n              const QuantizerValues* const beta_quant,\n              const QuantizerValues* const c_quant) {\n  // No gemmlowp available\n  return false;\n}\n\n#ifdef USE_GEMMLOWP\ntemplate<>\ntypename std::enable_if<unsigned_integer_is_same<uint8_t>::value, bool>::type\ngemmlowp_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n              const int_tp M, const int_tp N, const int_tp K,\n              const uint8_t alpha, const uint8_t* A,\n              const uint8_t* B, const uint8_t beta, uint8_t* C,\n              const QuantizerValues* const alpha_quant,\n              const QuantizerValues* const a_quant,\n              const QuantizerValues* const b_quant,\n              const QuantizerValues* const beta_quant,\n              const QuantizerValues* const c_quant) {\n  CHECK(a_quant && b_quant && c_quant)\n       << \"Integer type requires quantization values.\";\n  if (alpha == 1 && beta == 0 && alpha_quant == nullptr\n                              && beta_quant == nullptr) {\n    const int32_t lhs_offset = -a_quant->get_zero<int32_t>();\n    const int32_t rhs_offset = -b_quant->get_zero<int32_t>();\n\n    gemmlowp::OutputStageQuantizeDownInt32ByFixedPoint quantize_down_stage;\n    quantize_down_stage.result_offset_after_shift =\n        c_quant->get_zero<int32_t>();\n\n    int32_t mult;\n    int8_t shift;\n\n    QuantizerBase::template MultiplicativeQuantVals<int32_t>(\n        a_quant, b_quant, c_quant, &mult, &shift);\n\n    quantize_down_stage.result_fixedpoint_multiplier = mult;\n    quantize_down_stage.result_shift = static_cast<int32_t>(shift);\n\n    if (quantize_down_stage.result_shift < 0) {\n      // Gemmlowp doesn't handle negative exponents\n      return false;\n    }\n\n    gemmlowp::OutputStageSaturatingCastToUint8 saturating_cast_stage;\n    const auto& output_pipeline =\n        std::make_tuple(quantize_down_stage, saturating_cast_stage);\n\n    gemmlowp::GemmContext gemm_context;\n\n    gemmlowp::MatrixMap<uint8_t, gemmlowp::MapOrder::RowMajor> rs(C, M, N);\n\n    if (trans_A == CblasNoTrans && trans_B == CblasNoTrans) {\n      gemmlowp::MatrixMap<const uint8_t, gemmlowp::MapOrder::RowMajor>\n                                                                   lhs(A, M, K);\n      gemmlowp::MatrixMap<const uint8_t, gemmlowp::MapOrder::RowMajor>\n                                                                   rhs(B, K, N);\n      gemmlowp::GemmWithOutputPipeline<uint8_t, uint8_t,\n                                       gemmlowp::DefaultL8R8BitDepthParams>(\n         &gemm_context, lhs, rhs, &rs, lhs_offset, rhs_offset, output_pipeline);\n    } else if (trans_A == CblasNoTrans && trans_B == CblasTrans) {\n      gemmlowp::MatrixMap<const uint8_t, gemmlowp::MapOrder::RowMajor>\n                                                                   lhs(A, M, K);\n      gemmlowp::MatrixMap<const uint8_t, gemmlowp::MapOrder::ColMajor>\n                                                                   rhs(B, K, N);\n      gemmlowp::GemmWithOutputPipeline<uint8_t, uint8_t,\n                                       gemmlowp::DefaultL8R8BitDepthParams>(\n         &gemm_context, lhs, rhs, &rs, lhs_offset, rhs_offset, output_pipeline);\n    } else if (trans_A == CblasTrans && trans_B == CblasNoTrans) {\n      gemmlowp::MatrixMap<const uint8_t, gemmlowp::MapOrder::ColMajor>\n                                                                   lhs(A, M, K);\n      gemmlowp::MatrixMap<const uint8_t, gemmlowp::MapOrder::RowMajor>\n                                                                   rhs(B, K, N);\n      gemmlowp::GemmWithOutputPipeline<uint8_t, uint8_t,\n                                       gemmlowp::DefaultL8R8BitDepthParams>(\n         &gemm_context, lhs, rhs, &rs, lhs_offset, rhs_offset, output_pipeline);\n    } else {\n      gemmlowp::MatrixMap<const uint8_t, gemmlowp::MapOrder::ColMajor>\n                                                                   lhs(A, M, K);\n      gemmlowp::MatrixMap<const uint8_t, gemmlowp::MapOrder::ColMajor>\n                                                                   rhs(B, K, N);\n      gemmlowp::GemmWithOutputPipeline<uint8_t, uint8_t,\n                                       gemmlowp::DefaultL8R8BitDepthParams>(\n         &gemm_context, lhs, rhs, &rs, lhs_offset, rhs_offset, output_pipeline);\n    }\n    return true;\n  }\n  // Gemmlowp can't handle the case\n  return false;\n}\n#endif  // USE_GEMMLOWP\n\n\ntemplate<typename Dtype>\ntypename std::enable_if<unsigned_integer_is_same<Dtype>::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n           const int_tp M, const int_tp N, const int_tp K,\n           const Dtype alpha, const Dtype* A,\n           const Dtype* B, const Dtype beta, Dtype* C,\n           const QuantizerValues* const alpha_quant,\n           const QuantizerValues* const a_quant,\n           const QuantizerValues* const b_quant,\n           const QuantizerValues* const beta_quant,\n           const QuantizerValues* const c_quant) {\n  CHECK(a_quant && b_quant && c_quant)\n       << \"Integer type requires quantization values.\";\n\n  if (gemmlowp_gemm<Dtype>(trans_A, trans_B, M, N, K, alpha, A, B, beta, C,\n                          alpha_quant, a_quant, b_quant, beta_quant, c_quant)) {\n    // Handled by gemmlowp implementation\n    return;\n  }\n\n  typedef typename std::conditional<sizeof(Dtype) == 1, int16_t,\n          typename std::conditional<sizeof(Dtype) == 2, int32_t,\n                                    int64_t>::type>::type Difftype;\n  typedef typename std::conditional<sizeof(Dtype) == 1,\n                                    int32_t, int64_t>::type Acctype;\n\n  // std::cout << \"Difftype: \" << sizeof(Difftype) << std::endl;\n  // std::cout << \"Acctype: \" << sizeof(Acctype) << std::endl;\n\n  int8_t shift_bits = (32 / sizeof(Dtype)) - 1;\n\n  int32_t mult;\n  int8_t shift;\n  int32_t alpha_mult;\n  int8_t alpha_shift;\n  int32_t beta_mult;\n  int8_t beta_shift;\n  Acctype c_max = c_quant->get_max<Acctype>();\n  Acctype c_min = c_quant->get_min<Acctype>();\n  Dtype lhs_off = a_quant->get_zero<Dtype>();\n  Dtype rhs_off = b_quant->get_zero<Dtype>();\n  Dtype alpha_off = alpha_quant ? alpha_quant->get_zero<Dtype>() : Dtype(0);\n  Dtype beta_off = beta_quant ? beta_quant->get_zero<Dtype>() : Dtype(0);\n  const Acctype result_off = c_quant->get_zero<Acctype>();\n\n  QuantizerBase::template MultiplicativeQuantVals<int32_t>(\n      a_quant, b_quant, c_quant, &mult, &shift, shift_bits);\n  QuantizerBase::template MultiplicativeQuantVals<int32_t>(\n      c_quant, alpha_quant, c_quant, &alpha_mult, &alpha_shift, shift_bits);\n  QuantizerBase::template MultiplicativeQuantVals<int32_t>(\n      c_quant, beta_quant, c_quant, &beta_mult, &beta_shift, shift_bits);\n\n  int_tp inc_a = (trans_A == CblasNoTrans) ? 1 : M;\n  int_tp inc_b = (trans_B == CblasNoTrans) ? N : 1;\n  for (int_tp m = 0; m < M; ++m) {\n#pragma omp parallel for\n    for (int_tp n = 0; n < N; ++n) {\n      Acctype acc = Acctype(0);\n      int_tp b_index = trans_B == CblasNoTrans ? n : K * n;\n      int_tp a_index = trans_A == CblasNoTrans ? K * m : m;\n      for (int_tp k = 0; k < K; ++k) {\n        Difftype a_diff = A[a_index] - lhs_off;\n        Difftype b_diff = B[b_index] - rhs_off;\n        // std::cout << \"a_diff: \" << a_diff << std::endl;\n        // std::cout << \"b_diff: \" << b_diff << std::endl;\n        acc += static_cast<Acctype>(a_diff) * static_cast<Acctype>(b_diff);\n        a_index += inc_a;\n        b_index += inc_b;\n      }\n      Acctype reg = acc * (alpha_quant ? Acctype(1) : alpha);\n      // std::cout << \"1: \" << m << \", \"<< n << \": \" << reg << std::endl;\n      // std::cout << \"M: \" << mult << std::endl;\n      // std::cout << \"S: \" << static_cast<int32_t>(shift_bits) << std::endl;\n      reg = static_cast<Acctype>((static_cast<int64_t>(reg) *\n                             static_cast<int64_t>(mult)) / (1ll << shift_bits));\n      // std::cout << \"2: \" << m << \", \"<< n << \": \" << reg << std::endl;\n      if (shift >= 0) {\n        reg = reg >> shift;\n      } else {\n        reg = reg << -shift;\n      }\n      if (alpha_quant) {\n        Difftype alpha_diff = alpha - alpha_off;\n        reg = static_cast<Acctype>(alpha_diff) * static_cast<Acctype>(reg);\n        reg = static_cast<Acctype>((static_cast<int64_t>(reg) *\n                       static_cast<int64_t>(alpha_mult)) / (1ll << shift_bits));\n        if (alpha_shift >= 0) {\n          reg = reg >> alpha_shift;\n        } else {\n          reg = reg << -alpha_shift;\n        }\n      }\n      // std::cout << \"3: \" << m << \", \"<< n << \": \" << reg << std::endl;\n      if (beta_quant) {\n        Difftype beta_diff = beta - beta_off;\n        Difftype c_diff = C[m * N + n] - static_cast<Difftype>(result_off);\n        Acctype creg = static_cast<Acctype>(beta_diff)\n                     * static_cast<Acctype>(c_diff);\n        creg = static_cast<Acctype>((static_cast<int64_t>(creg) *\n                        static_cast<int64_t>(beta_mult)) / (1ll << shift_bits));\n        if (beta_shift >= 0) {\n          creg = creg >> beta_shift;\n        } else {\n          creg = creg << -beta_shift;\n        }\n        reg = reg + creg;\n      } else if (beta == Dtype(1)) {\n        reg = reg + (C[m * N + n] - result_off);\n      }\n      reg = reg + result_off;\n      // std::cout << \"4: \" << m << \", \"<< n << \": \" << reg << std::endl;\n      C[m * N + n] = static_cast<Dtype>(std::min(std::max(reg, c_min), c_max));\n    }\n  }\n}\n\ntemplate<typename Dtype>\ntypename std::enable_if<float_is_same<Dtype>::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n           const int_tp M, const int_tp N, const int_tp K,\n           const Dtype alpha, const Dtype* A,\n           const Dtype* B, const Dtype beta, Dtype* C,\n           const QuantizerValues* const alpha_quant,\n           const QuantizerValues* const a_quant,\n           const QuantizerValues* const b_quant,\n           const QuantizerValues* const beta_quant,\n           const QuantizerValues* const c_quant) {\n  int_tp inc_a = (trans_A == CblasNoTrans) ? 1 : M;\n  int_tp inc_b = (trans_B == CblasNoTrans) ? N : 1;\n  for (int_tp m = 0; m < M; ++m) {\n#pragma omp parallel for\n    for (int_tp n = 0; n < N; ++n) {\n      Dtype acc = 0;\n      int_tp b_index = trans_B == CblasNoTrans ? n : K * n;\n      int_tp a_index = trans_A == CblasNoTrans ? K * m : m;\n      for (int_tp k = 0; k < K; ++k) {\n        acc += A[a_index] * B[b_index];\n        a_index += inc_a;\n        b_index += inc_b;\n      }\n      if (beta != 0) {\n        C[m * N + n] = acc * alpha + beta * C[m * N + n];\n      }\n      else {\n        C[m * N + n] = acc * alpha;\n      }\n    }\n  }\n}\n\ntemplate\ntypename std::enable_if<float_is_same<half_fp>::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n                const int_tp M, const int_tp N, const int_tp K,\n                const half_fp alpha, const half_fp* A,\n                const half_fp* B, const half_fp beta, half_fp* C,\n                const QuantizerValues* const alpha_quant,\n                const QuantizerValues* const a_quant,\n                const QuantizerValues* const b_quant,\n                const QuantizerValues* const beta_quant,\n                const QuantizerValues* const c_quant);\ntemplate\ntypename std::enable_if<unsigned_integer_is_same<uint8_t>::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n                const int_tp M, const int_tp N, const int_tp K,\n                const uint8_t alpha, const uint8_t* A,\n                const uint8_t* B, const uint8_t beta, uint8_t* C,\n                const QuantizerValues* const alpha_quant,\n                const QuantizerValues* const a_quant,\n                const QuantizerValues* const b_quant,\n                const QuantizerValues* const beta_quant,\n                const QuantizerValues* const c_quant);\ntemplate\ntypename std::enable_if<unsigned_integer_is_same<uint16_t>::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n           const int_tp M, const int_tp N, const int_tp K,\n           const uint16_t alpha, const uint16_t* A,\n           const uint16_t* B, const uint16_t beta, uint16_t* C,\n           const QuantizerValues* const alpha_quant,\n           const QuantizerValues* const a_quant,\n           const QuantizerValues* const b_quant,\n           const QuantizerValues* const beta_quant,\n           const QuantizerValues* const c_quant);\ntemplate\ntypename std::enable_if<unsigned_integer_is_same<uint32_t>::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n           const int_tp M, const int_tp N, const int_tp K,\n           const uint32_t alpha, const uint32_t* A,\n           const uint32_t* B, const uint32_t beta, uint32_t* C,\n           const QuantizerValues* const alpha_quant,\n           const QuantizerValues* const a_quant,\n           const QuantizerValues* const b_quant,\n           const QuantizerValues* const beta_quant,\n           const QuantizerValues* const c_quant);\ntemplate\ntypename std::enable_if<unsigned_integer_is_same<uint64_t>::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n           const int_tp M, const int_tp N, const int_tp K,\n           const uint64_t alpha, const uint64_t* A,\n           const uint64_t* B, const uint64_t beta, uint64_t* C,\n           const QuantizerValues* const alpha_quant,\n           const QuantizerValues* const a_quant,\n           const QuantizerValues* const b_quant,\n           const QuantizerValues* const beta_quant,\n           const QuantizerValues* const c_quant);\n\n\ntemplate<>\ntypename std::enable_if<float_is_same<float>::value, void>::type\ncaffe_gemm<float>(const CBLAS_TRANSPOSE trans_A,\n                  const CBLAS_TRANSPOSE trans_B, const int_tp M,\n                  const int_tp N, const int_tp K, const float alpha,\n                  const float* A, const float* B, const float beta,\n                  float* C,\n                  const QuantizerValues* const alpha_quant,\n                  const QuantizerValues* const a_quant,\n                  const QuantizerValues* const b_quant,\n                  const QuantizerValues* const beta_quant,\n                  const QuantizerValues* const c_quant) {\n  int_tp lda = (trans_A == CblasNoTrans) ? K : M;\n  int_tp ldb = (trans_B == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, trans_A, trans_B, M, N, K, alpha, A, lda, B, ldb,\n              beta, C, N);\n}\n\ntemplate<>\ntypename std::enable_if<float_is_same<float>::value, void>::type\ncaffe_gemm<double>(const CBLAS_TRANSPOSE trans_A,\n                   const CBLAS_TRANSPOSE trans_B, const int_tp M,\n                   const int_tp N, const int_tp K, const double alpha,\n                   const double* A, const double* B, const double beta,\n                   double* C,\n                   const QuantizerValues* const alpha_quant,\n                   const QuantizerValues* const a_quant,\n                   const QuantizerValues* const b_quant,\n                   const QuantizerValues* const beta_quant,\n                   const QuantizerValues* const c_quant) {\n  int_tp lda = (trans_A == CblasNoTrans) ? K : M;\n  int_tp ldb = (trans_B == CblasNoTrans) ? N : K;\n  cblas_dgemm(CblasRowMajor, trans_A, trans_B, M, N, K, alpha, A, lda, B, ldb,\n              beta, C, N);\n}\n\n}  // namespace caffe\n\n", "meta": {"hexsha": "22f2132a9b9cfac5717bed60be36a9feb17da95c", "size": 16154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_blas_3.cpp", "max_stars_repo_name": "naibaf7/caffe", "max_stars_repo_head_hexsha": "29960153c828820b1abb55a5792283742f57caa2", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T01:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T17:03:28.000Z", "max_issues_repo_path": "src/caffe/util/math_blas_3.cpp", "max_issues_repo_name": "Miaomz/caffe-opencl", "max_issues_repo_head_hexsha": "505693d54298b89cf83b54778479087cff2f3bd6", "max_issues_repo_licenses": ["Intel", "BSD-2-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T13:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-19T05:00:10.000Z", "max_forks_repo_path": "src/caffe/util/math_blas_3.cpp", "max_forks_repo_name": "Miaomz/caffe-opencl", "max_forks_repo_head_hexsha": "505693d54298b89cf83b54778479087cff2f3bd6", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-07-05T17:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T13:16:02.000Z", "avg_line_length": 44.3791208791, "max_line_length": 80, "alphanum_fraction": 0.6038752012, "num_tokens": 4213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.19863873981225974}}
{"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#include <Eigen/Dense>\n\n#include \"Filter.h\"\n#include \"RAHjoy.h\"\n\n\nRAHjoy::RAHjoy()\n{ init( 0 );\n}\n\nRAHjoy::RAHjoy(const Float hz)\n{ init( hz );\n}\n\nvoid\nRAHjoy::init(const Float hz)\n{ x_max_=JOY_X_MAX;\n  x_min_=JOY_X_MAX;\n  y_max_=JOY_Y_MAX;\n  y_min_=JOY_Y_MAX;\n  x_dead_=JOY_X_DED;\n  y_dead_=JOY_Y_DED;\n  hz_=hz;\n}\n\nRAHjoy::RAHjoy(const Float hz, int xmax, int xmin, int ymax, int ymin)\n{ x_max_=xmax;\n  x_min_=xmin;\n  y_max_=ymax;\n  y_min_=ymin;\n  x_dead_=JOY_X_DED;\n  y_dead_=JOY_Y_DED;\n  hz_=hz;\n}\n\nvoid\nRAHjoy::norm(float &x, float &y, int &b)\n{\n  int xi,yi;\n  int x_sign=1;\n  int y_sign=1;\n\n  joystick_hwread(xi,yi,b);\n  x =  xi;\n  y = -yi; // invert y coord.\n\n  if(x<0)\n  { x=-x;\n    x_sign=-1;\n  }\n  if(y<0)\n  { y=-y;\n    y_sign=-1;\n  }\n\n  x -= x_dead_;\n  x /= x_max_-x_dead_;\n  if( x>1.0 ) x=1.0;\n  if( x<0.0 ) x=0.0;\n  x *= x_sign;\n\n  y -= y_dead_;\n  y /= y_max_-y_dead_;\n  if( y>1.0 ) y=1.0;\n  if( y<0.0 ) y=0.0;\n  y *= y_sign;\n\n} // func joyNorm\n\n\nvoid\nRAHjoy::smooth(float &x, float &y, int &b)\n{\n if( hz_ ) // ONLY USEABLE IF CONSTRUCTED WITH SERVO RATE\n {\n  static int k=0;\n  static Filter Fcx;\n  static Eigen::Vector2d  cx = Eigen::Vector2d::Zero();\n  static Eigen::Vector2d fcx = Eigen::Vector2d::Zero();\n\n  if(k==0)\n  { joystick_calibrate();\n    Fcx.LowPass(cx, hz_,  5);\n  }\n\n  if((++k) > hz_/25 ) // READS AT ~25 Hz\n  { k = 1;\n    float jx,jy;\n    norm(jx,jy,b);\n    cx[0] = jx;\n    cx[1] = jy;\n  }\n\n  fcx = Fcx.Filt( cx );  // DO NOT FILTER BUTTON\n  x = fcx[0];\n  y = fcx[1];\n\n } // if(hz_)\n else        // NO KNOWN SERVO RATE SO RET. ZEROs & ERR\n {\n   x =  0;\n   y =  0;\n   b = -1;\n }\n\n}\n\n\nVector3d\nRAHjoy::joyFill_cx()\n{\n if( hz_ ) // ONLY USEABLE IF CONSTRUCTED WITH SERVO RATE\n {\n  static int k=-1;\n  static Filter Fcx;\n  static Eigen::Vector3d cx = Eigen::Vector3d::Zero(3);\n\n  float joy_x,joy_y;\n  int joy_b;\n\n  if(k==-1)\n  { joystick_calibrate();\n    Fcx.LowPass(cx, hz_,  5);\n  }\n\n  if((++k)%((int)hz_/50)==0)\n  {\n    k=0;\n    norm(joy_x,joy_y,joy_b);\n    if(joy_b == 1)\n    { cx[0] = MAX_JOY_V*joy_x;\n      cx[1] = MAX_JOY_V*joy_y;\n      cx[2] = MAX_JOY_W*0.0  ;\n    }\n    else if(joy_b == 2)\n    { cx[0] = MAX_JOY_V*0.0  ;\n      cx[1] = MAX_JOY_V*joy_y;\n      cx[2] = MAX_JOY_W*(-joy_x);\n    }\n    else if(joy_b == 3)\n    { cx[0] = MAX_JOY_V*joy_x;\n      cx[1] = MAX_JOY_V*joy_y;\n      cx[2] = MAX_JOY_W*(-joy_x);\n    }\n    else\n    { cx[0] = 0.0;\n      cx[1] = 0.0;\n      cx[2] = 0.0;\n    }\n  }\n\n  cx_f = Fcx.Filt(cx);\n } // if(hz_)\n else cx_f.setZero(3);  // NO KNOWN SERVO RATE SO RET. ZEROs\n\n return cx_f;\n}\n", "meta": {"hexsha": "d18dbc6209f497acb9ac5e62e3e52f016e66a084", "size": 3241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RAHjoy.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": "RAHjoy.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": "RAHjoy.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": 18.6264367816, "max_line_length": 72, "alphanum_fraction": 0.5692687442, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19863873458294368}}
{"text": "#ifndef __abstract_MSSMNoFV_onshell_susy_parameters_gm2calc_1_2_0_hpp__\n#define __abstract_MSSMNoFV_onshell_susy_parameters_gm2calc_1_2_0_hpp__\n\n#include <cstddef>\n#include <iostream>\n#include <Eigen/Core>\n#include <ostream>\n#include \"gambit/Backends/abstractbase.hpp\"\n#include \"forward_decls_abstract_classes.hpp\"\n#include \"forward_decls_wrapper_classes.hpp\"\n\n#include \"identification.hpp\"\n\nnamespace CAT_3(BACKENDNAME,_,SAFE_VERSION)\n{\n   \n   \n   namespace gm2calc\n   {\n      class Abstract_MSSMNoFV_onshell_susy_parameters : public virtual AbstractBase\n      {\n         public:\n   \n            virtual void print(::std::basic_ostream<char, std::char_traits<char> >&) const =0;\n   \n            virtual void clear() =0;\n   \n            virtual void set_scale(double) =0;\n   \n            virtual double get_scale() const =0;\n   \n            virtual void set_Yd(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&) =0;\n   \n            virtual void set_Yd(int, int, double) =0;\n   \n            virtual void set_Ye(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&) =0;\n   \n            virtual void set_Ye(int, int, double) =0;\n   \n            virtual void set_Yu(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&) =0;\n   \n            virtual void set_Yu(int, int, double) =0;\n   \n            virtual void set_Mu(double) =0;\n   \n            virtual void set_g1(double) =0;\n   \n            virtual void set_g2(double) =0;\n   \n            virtual void set_g3(double) =0;\n   \n            virtual void set_vd(double) =0;\n   \n            virtual void set_vu(double) =0;\n   \n            virtual const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_Yd() const =0;\n   \n            virtual double get_Yd(int, int) const =0;\n   \n            virtual const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_Ye() const =0;\n   \n            virtual double get_Ye(int, int) const =0;\n   \n            virtual const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_Yu() const =0;\n   \n            virtual double get_Yu(int, int) const =0;\n   \n            virtual double get_Mu() const =0;\n   \n            virtual double get_g1() const =0;\n   \n            virtual double get_g2() const =0;\n   \n            virtual double get_g3() const =0;\n   \n            virtual double get_vd() const =0;\n   \n            virtual double get_vu() const =0;\n   \n         public:\n            virtual void pointer_assign__BOSS(Abstract_MSSMNoFV_onshell_susy_parameters*) =0;\n            virtual Abstract_MSSMNoFV_onshell_susy_parameters* pointer_copy__BOSS() =0;\n   \n         private:\n            MSSMNoFV_onshell_susy_parameters* wptr;\n            bool delete_wrapper;\n         public:\n            MSSMNoFV_onshell_susy_parameters* get_wptr() { return wptr; }\n            void set_wptr(MSSMNoFV_onshell_susy_parameters* wptr_in) { wptr = wptr_in; }\n            bool get_delete_wrapper() { return delete_wrapper; }\n            void set_delete_wrapper(bool del_wrp_in) { delete_wrapper = del_wrp_in; }\n   \n         public:\n            Abstract_MSSMNoFV_onshell_susy_parameters()\n            {\n               wptr = 0;\n               delete_wrapper = false;\n            }\n   \n            Abstract_MSSMNoFV_onshell_susy_parameters(const Abstract_MSSMNoFV_onshell_susy_parameters&)\n            {\n               wptr = 0;\n               delete_wrapper = false;\n            }\n   \n            Abstract_MSSMNoFV_onshell_susy_parameters& operator=(const Abstract_MSSMNoFV_onshell_susy_parameters&) { return *this; }\n   \n            virtual void init_wrapper() =0;\n   \n            MSSMNoFV_onshell_susy_parameters* get_init_wptr()\n            {\n               init_wrapper();\n               return wptr;\n            }\n   \n            MSSMNoFV_onshell_susy_parameters& get_init_wref()\n            {\n               init_wrapper();\n               return *wptr;\n            }\n   \n            virtual ~Abstract_MSSMNoFV_onshell_susy_parameters() =0;\n      };\n   }\n   \n}\n\n\n#include \"gambit/Backends/backend_undefs.hpp\"\n\n\n#endif /* __abstract_MSSMNoFV_onshell_susy_parameters_gm2calc_1_2_0_hpp__ */\n", "meta": {"hexsha": "67e6d8405e244fe6e5515be550e0292579d0bf99", "size": 4011, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/abstract_MSSMNoFV_onshell_susy_parameters.hpp", "max_stars_repo_name": "GambitBSM/gambit_2.0", "max_stars_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T22:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T22:53:26.000Z", "max_issues_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/abstract_MSSMNoFV_onshell_susy_parameters.hpp", "max_issues_repo_name": "GambitBSM/gambit_2.0", "max_issues_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T11:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T17:24:41.000Z", "max_forks_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/abstract_MSSMNoFV_onshell_susy_parameters.hpp", "max_forks_repo_name": "GambitBSM/gambit_2.0", "max_forks_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:31:41.000Z", "avg_line_length": 30.1578947368, "max_line_length": 132, "alphanum_fraction": 0.5923709798, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19863873458294365}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2013-2014 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#include \"ber_sink_b_impl.h\"\n#include <boost/math/special_functions/erf.hpp>\n#include <gnuradio/io_signature.h>\n#include <gnuradio/math.h>\n#include <gnuradio/fft/fft.h>\n#include <volk/volk.h>\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\nnamespace gr {\n  namespace qtgui {\n\n    ber_sink_b::sptr\n    ber_sink_b::make(std::vector<float> esnos, int curves,\n                     int ber_min_errors, float ber_limit,\n                     std::vector<std::string> curvenames,\n                     QWidget *parent)\n    {\n      return gnuradio::get_initial_sptr\n        (new ber_sink_b_impl(esnos, curves,\n                             ber_min_errors, ber_limit,\n                             curvenames, parent));\n    }\n\n    ber_sink_b_impl::ber_sink_b_impl(std::vector<float> esnos, int curves,\n                                     int ber_min_errors, float ber_limit,\n                                     std::vector<std::string> curvenames,\n                                     QWidget *parent)\n      : block(\"ber_sink_b\",\n              io_signature::make(curves*esnos.size()*2, curves*esnos.size()*2, sizeof(unsigned char)),\n              io_signature::make(0, 0, 0)),\n        d_ber_min_errors(ber_min_errors),\n        d_ber_limit(ber_limit),\n        d_parent(parent),\n        d_nconnections(esnos.size()),\n        d_last_time(0)\n    {\n      d_main_gui = NULL;\n\n      // Enough curves for the input streams plus the BPSK AWGN curve.\n      d_curves = curves;\n      d_esno_buffers.reserve(curves + 1);\n      d_ber_buffers.reserve(curves + 1);\n      d_total.reserve(curves * esnos.size());\n      d_total_errors.reserve(curves * esnos.size());\n\n      for(int j = 0; j < curves; j++) {\n\td_esno_buffers.push_back((double*)volk_malloc(esnos.size()*sizeof(double),\n                                                        volk_get_alignment()));\n\td_ber_buffers.push_back((double*)volk_malloc(esnos.size()*sizeof(double),\n                                                        volk_get_alignment()));\n\n        for(int i = 0; i < d_nconnections; i++) {\n          d_esno_buffers[j][i] = esnos[i];\n          d_ber_buffers[j][i] = 0.0;\n          d_total.push_back(0);\n          d_total_errors.push_back(1);\n        }\n      }\n\n      // Now add the known curves\n      d_esno_buffers.push_back((double*)volk_malloc(esnos.size()*sizeof(double),\n                                                      volk_get_alignment()));\n      d_ber_buffers.push_back((double*)volk_malloc(esnos.size()*sizeof(double),\n                                                      volk_get_alignment()));\n      for(size_t i = 0; i < esnos.size(); i++) {\n        double e = pow(10.0, esnos[i]/10.0);\n        d_esno_buffers[curves][i] = esnos[i];\n        d_ber_buffers[curves][i] = log10(0.5*boost::math::erfc(sqrt(e)));\n      }\n\n\n      // Initialize and set up some of the curve visual properties\n      initialize();\n      for(int j= 0; j < curves; j++) {\n        set_line_width(j, 1);\n        //35 unique styles supported\n        set_line_style(j, (j%5) + 1);\n        set_line_marker(j, (j%7));\n      }\n\n      if(curvenames.size() == (unsigned int)curves) {\n        for(int j = 0; j < curves; j++) {\n          if(curvenames[j] != \"\") {\n            set_line_label(j, curvenames[j]);\n          }\n        }\n      }\n\n      set_line_label(d_curves, \"BPSK AWGN\");\n      set_line_style(d_curves, 5);    // non-solid line\n      set_line_marker(d_curves, -1);  // no marker\n      set_line_alpha(d_curves, 0.25); // high transparency\n    }\n\n    ber_sink_b_impl::~ber_sink_b_impl()\n    {\n      if(!d_main_gui->isClosed()) {\n        d_main_gui->close();\n      }\n\n      for(unsigned int i = 0; i < d_esno_buffers.size(); i++) {\n\tvolk_free(d_esno_buffers[i]);\n\tvolk_free(d_ber_buffers[i]);\n      }\n    }\n\n    bool\n    ber_sink_b_impl::check_topology(int ninputs, int noutputs)\n    {\n      return ninputs == (int)(d_curves * d_nconnections * 2);\n    }\n\n    void\n    ber_sink_b_impl::initialize()\n    {\n      if(qApp != NULL) {\n        d_qApplication = qApp;\n      }\n      else {\n        int argc=0;\n        char **argv = NULL;\n        d_qApplication = new QApplication(argc, argv);\n      }\n\n      d_main_gui = new ConstellationDisplayForm(d_esno_buffers.size(), d_parent);\n\n      d_main_gui->setNPoints(d_nconnections);\n      d_main_gui->getPlot()->setAxisTitle(QwtPlot::yLeft, \"LogScale BER\");\n      d_main_gui->getPlot()->setAxisTitle(QwtPlot::xBottom, \"ESNO\");\n      // initialize update time to 10 times a second\n      set_update_time(0.1);\n    }\n\n    void\n    ber_sink_b_impl::exec_()\n    {\n      d_qApplication->exec();\n    }\n\n    QWidget*\n    ber_sink_b_impl::qwidget()\n    {\n      return d_main_gui;\n    }\n\n#ifdef ENABLE_PYTHON\n    PyObject*\n    ber_sink_b_impl::pyqwidget()\n    {\n      PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui);\n      PyObject *retarg = Py_BuildValue(\"N\", w);\n      return retarg;\n    }\n#else\n    void *\n    ber_sink_b_impl::pyqwidget()\n    {\n      return NULL;\n    }\n#endif\n\n    void\n    ber_sink_b_impl::set_y_axis(double min, double max)\n    {\n      d_main_gui->setYaxis(min, max);\n    }\n\n    void\n    ber_sink_b_impl::set_x_axis(double min, double max)\n    {\n      d_main_gui->setXaxis(min, max);\n    }\n\n    void\n    ber_sink_b_impl::set_update_time(double t)\n    {\n      //convert update time to ticks\n      gr::high_res_timer_type tps = gr::high_res_timer_tps();\n      d_update_time = t * tps;\n      d_main_gui->setUpdateTime(t);\n      d_last_time = 0;\n    }\n\n    void\n    ber_sink_b_impl::set_title(const std::string &title)\n    {\n      d_main_gui->setTitle(title.c_str());\n    }\n\n    void\n    ber_sink_b_impl::set_line_label(int which, const std::string &label)\n    {\n      d_main_gui->setLineLabel(which, label.c_str());\n    }\n\n    void\n    ber_sink_b_impl::set_line_color(int which, const std::string &color)\n    {\n      d_main_gui->setLineColor(which, color.c_str());\n    }\n\n    void\n    ber_sink_b_impl::set_line_width(int which, int width)\n    {\n      d_main_gui->setLineWidth(which, width);\n    }\n\n    void\n    ber_sink_b_impl::set_line_style(int which, int style)\n    {\n      d_main_gui->setLineStyle(which, (Qt::PenStyle)style);\n    }\n\n    void\n    ber_sink_b_impl::set_line_marker(int which, int marker)\n    {\n      d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker);\n    }\n\n    void\n    ber_sink_b_impl::set_line_alpha(int which, double alpha)\n    {\n      d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha));\n    }\n\n    void\n    ber_sink_b_impl::set_size(int width, int height)\n    {\n      d_main_gui->resize(QSize(width, height));\n    }\n\n    std::string\n    ber_sink_b_impl::title()\n    {\n      return d_main_gui->title().toStdString();\n    }\n\n    std::string\n    ber_sink_b_impl::line_label(int which)\n    {\n      return d_main_gui->lineLabel(which).toStdString();\n    }\n\n    std::string\n    ber_sink_b_impl::line_color(int which)\n    {\n      return d_main_gui->lineColor(which).toStdString();\n    }\n\n    int\n    ber_sink_b_impl::line_width(int which)\n    {\n      return d_main_gui->lineWidth(which);\n    }\n\n    int\n    ber_sink_b_impl::line_style(int which)\n    {\n      return d_main_gui->lineStyle(which);\n    }\n\n    int\n    ber_sink_b_impl::line_marker(int which)\n    {\n      return d_main_gui->lineMarker(which);\n    }\n\n    double\n    ber_sink_b_impl::line_alpha(int which)\n    {\n      return (double)(d_main_gui->markerAlpha(which))/255.0;\n    }\n\n    int\n    ber_sink_b_impl::nsamps() const\n    {\n      return d_nconnections;\n    }\n\n    void\n    ber_sink_b_impl::enable_menu(bool en)\n    {\n      d_main_gui->enableMenu(en);\n    }\n\n    void\n    ber_sink_b_impl::enable_autoscale(bool en)\n    {\n      d_main_gui->autoScale(en);\n    }\n\n    int\n    ber_sink_b_impl::general_work(int noutput_items,\n                                  gr_vector_int& ninput_items,\n                                  gr_vector_const_void_star &input_items,\n                                  gr_vector_void_star &output_items)\n    {\n      if(gr::high_res_timer_now() - d_last_time > d_update_time) {\n        d_last_time = gr::high_res_timer_now();\n        d_qApplication->postEvent(d_main_gui,\n                                  new ConstUpdateEvent(d_esno_buffers,\n                                                       d_ber_buffers,\n                                                       d_nconnections));\n      }\n\n      //check stopping condition\n      int done=0, maxed=0;\n      for(int j = 0; j < d_curves; ++j) {\n        for(int i = 0; i < d_nconnections; ++i) {\n\n          if(d_total_errors[j * d_nconnections + i] >= d_ber_min_errors) {\n            done++;\n          }\n          else if(log10(((double)d_ber_min_errors)/(d_total[j * d_nconnections + i] * 8.0)) < d_ber_limit) {\n            maxed++;\n          }\n        }\n      }\n\n      if(done+maxed == (int)(d_nconnections * d_curves)) {\n        d_qApplication->postEvent(d_main_gui,\n                                  new ConstUpdateEvent(d_esno_buffers,\n                                                       d_ber_buffers,\n                                                       d_nconnections));\n        return -1;\n      }\n\n      float ber;\n      for(unsigned int i = 0; i < ninput_items.size(); i += 2) {\n\n        if((d_total_errors[i >> 1] < d_ber_min_errors) && \\\n           (log10(((double)d_ber_min_errors)/(d_total[i >> 1] * 8.0)) >= d_ber_limit)) {\n\n          int items = ninput_items[i] <= ninput_items[i+1] ? ninput_items[i] : ninput_items[i+1];\n\n          unsigned char *inbuffer0 = (unsigned char *)input_items[i];\n          unsigned char *inbuffer1 = (unsigned char *)input_items[i+1];\n\n          if(items > 0) {\n            uint32_t ret;\n            for(int j = 0; j < items; j++) {\n              volk_32u_popcnt(&ret, static_cast<uint32_t>(inbuffer0[j]^inbuffer1[j]));\n              d_total_errors[i >> 1] += ret;\n            }\n\n            d_total[i >> 1] += items;\n\n            ber = log10(((double)d_total_errors[i >> 1])/(d_total[i >> 1] * 8.0));\n            d_ber_buffers[i/(d_nconnections * 2)][(i%(d_nconnections * 2)) >> 1] = ber;\n\n          }\n          consume(i, items);\n          consume(i + 1, items);\n\n          if(d_total_errors[i >> 1] >= d_ber_min_errors) {\n            GR_LOG_INFO(d_logger, boost::format(\"    %1% over %2%  -->  %3%\") \\\n                        % d_total_errors[i >> 1] % (d_total[i >> 1] * 8) % ber);\n          }\n          else if(log10(((double)d_ber_min_errors)/(d_total[i >> 1] * 8.0)) < d_ber_limit) {\n            GR_LOG_INFO(d_logger, \"BER Limit Reached\");\n            d_ber_buffers[i/(d_nconnections * 2)][(i%(d_nconnections * 2)) >> 1] = d_ber_limit;\n            d_total_errors[i >> 1] = d_ber_min_errors + 1;\n          }\n        }\n        else {\n          consume(i, ninput_items[i]);\n          consume(i+1, ninput_items[i+1]);\n        }\n      }\n\n      return 0;\n    }\n\n\n  } /* namespace qtgui */\n} /* namespace gr */\n", "meta": {"hexsha": "eb3aa14597b0a0bdfc5eedc927b58cef4d0d1888", "size": 11649, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-qtgui/lib/ber_sink_b_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-qtgui/lib/ber_sink_b_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-qtgui/lib/ber_sink_b_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": 28.9776119403, "max_line_length": 108, "alphanum_fraction": 0.5661430166, "num_tokens": 2981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1986387321847691}}
{"text": "//============================================================================\n// Name        : duohmm.cpp\n// Author      : Jared O'Connell\n// Version     :\n// Copyright   :\n// Description :\n//============================================================================\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iterator>\n#include \"hapmodule.h\"\n#include \"pedigree.h\"\n#include \"hmm.h\"\n#include \"pedhap.h\"\n#include <boost/progress.hpp>\n\nusing namespace std;\n\nint main(int argc,char **argv) {\n  int start,stop;\n  if(argc!=4) {\n    cout << \"Usage: duohmm hapfile famfile genetic_map --corrected output --recombination output --genotypingError output\" << endl;\n    return(0);\n  }\n\n  cout << \"Reading haplotypes from \" << argv[1] <<\".haps\" << endl;\n  Haplotypes haps(argv[1]);\n\n  cout << \"Reading pedigree information from \" << argv[2] << endl;\n\n  pedigree p(argv[2],haps.ids);\n  \n  vector<string> idorder;\n  p.orderSamples(p.pedigrees[0],idorder);\n  for(int i=0;i<idorder.size();i++)\n    cout << i <<\": \"<< idorder[i]<<endl;\n\n  geneticMap gm(argv[3]);\n\n  vector<double> cM;\n  gm.interpolate(haps.positions,cM);\n  for(int i=0;i<30;i++)\n    cout << haps.positions[i] << \"\\t\" << cM[i] << endl;\n\n  DuoHMM duo(haps.positions,gm);\n  cout << \"RHO:\"<<endl;\n  for(int i=0;i<20;i++) {\n    cout << duo.male_rho[i]<<\"\\t\" << duo.male_norho[i]<<\"\\t\" << duo.female_rho[i]<<\"\\t\" << duo.female_norho[i]<<endl;\n  }\n\n  DuoHMM duo2(haps.positions,gm);\n\n  int i1=43;\n  int i2=46;\n  cout << haps.ids[i1] << \"\\t\" << haps.ids[i2] << endl;\n  //checks haplotypes are initialsed\n  for(int i=0;i<30;i++)\n    cout << (int)haps.H[i1*2][i]  << \" \" << (int)haps.H[i1*2+1][i] << \" \" << (int)haps.H[i2*2][i] << \" \" << (int)haps.H[i2*2+1][i] << endl;\n  cout << endl;\n\n  start = 4850;\n  for(int i=start;i<start+20;i++)\n    cout << (int)haps.H[i1*2][i] << \" \" << (int)haps.H[i1*2+1][i] << \" \" << (int)haps.H[i2*2][i] << \" \" << (int)haps.H[i2*2+1][i] << endl;\n  cout << haps.nsnp << \" \" << haps.positions.size()<<endl;\n\n  cout << endl;\n\n  cout << \"Setting haps...\" <<endl;\n  duo2.setHaps(haps.getHap(\"ID305\"),haps.getHap(\"ID089\"),\"2\");  \n  duo.setHaps(haps.getHap(\"ID203\"),haps.getHap(\"ID089\"),\"2\");  \n  cout << \"EM\"<<endl;  \n  duo.EM(5);\n  duo2.EM(5);\n  cout << \"viterbi\" <<endl;\n  duo.viterbi();\n  duo2.viterbi();\n\n  cout << \"Trio HMM\"<<endl;\n  TrioHMM trio(haps.positions,gm);\n  trio.setHaps(haps.getHap(\"ID305\"),haps.getHap(\"ID203\"),haps.getHap(\"ID089\"));  \n  cout << \"EM\"<<endl;\n  trio.EM(5);\n  cout << \"viterbi\"<<endl;\n  trio.viterbi();\n\n  cout << \"printing\"<<endl;\n\n  unsigned char **d = haps.getHap(\"ID305\");\n  unsigned char **m = haps.getHap(\"ID203\");\n  unsigned char **c = haps.getHap(\"ID089\");\n\n\n  start = 0;\n  stop = 7960;\n\n  for(int i=start;i<stop;i++) {\n\n    cout << i << \"\\t\" <<haps.positions[i] << \" \";   \n\n\n    // for(int j=0;j<4;j++)  {\n    //   cout.precision(2);\n    //   cout <<  duo.posterior[j][i]<<\" \";\n    // }\n    cout << \"\\t\" << (int)duo2.stateseq[i]<<\" \"<< (int) duo.stateseq[i] << \"\\t\";\n\n\n    // for(int j=0;j<8;j++)  {\n    //   cout.precision(2);\n    //   cout <<  trio.posterior[j][i]<<\" \";\n    // }\n\n    // for(int j=0;j<8;j++) \n    //   cout <<  trio.alpha[j][i]<<\" \";\n    int s = trio.stateseq[i];\n    cout << \"\\t\" << s << \"\\t\" << 2*(s/4) + s%2 << \" \"<< 2*((s%4)/2) + ((s%2)+1)%2 << \"\\t\";\n\n    cout   << (unsigned int)c[0][i] << (unsigned int)c[1][i] << \" \" << (unsigned int)d[0][i]  << (unsigned int)d[1][i] << \" \" << (unsigned int)m[0][i] << (unsigned int)m[1][i] << \" \" <<  endl;\n  }\n\n  return(0);\n\n  /*\n  for(int i=0;i<20;i++) {\n    cout << duo.scale[i]<<endl;\n    for(int j=0;j<4;j++) \n      cout << duo.alpha[j][i]<<\"\\t\";\n    cout << endl;\n    for(int j=0;j<4;j++) \n      cout << duo.beta[j][i]<<\"\\t\";\n    cout << endl;\n    for(int j=0;j<4;j++) \n      cout << duo.posterior[j][i]<<\"\\t\";\n    cout << endl;\n  }\n  cout << endl;\n\n  start=830;\n  int stop =850;\n\n  for(int i=start;i<stop;i++) {\n    cout << duo.scale[i]<<endl;\n    for(int j=0;j<4;j++) \n      cout << duo.alpha[j][i]<<\"\\t\";\n    cout << endl;\n    for(int j=0;j<4;j++) \n      cout << duo.beta[j][i]<<\"\\t\";\n    cout << endl;\n    for(int j=0;j<4;j++) \n      cout << duo.posterior[j][i]<<\"\\t\";\n    cout << endl;\n  }\n  */\n\n  cout << duo.rho[100] << \" \" << duo.rho[1000] << endl;\n  cout << endl;\n  start = 4850;\n  for(int i=start;i<start+20;i++) {\n    cout << i << \"\\t\";\n    for(int j=0;j<4;j++) \n      cout << duo.posterior[j][i]<<\"\\t\";\n    cout << \"\\t\" << duo.stateseq[i] << endl;\n  }\n\n  cout << \"Making pedhap\"<<endl;\n  pedhap ph(argv[1],argv[2],argv[3]);\n  ph.correct();\n\n  duo.setHaps(ph.haps->getHap(\"ID178\"),ph.haps->getHap(\"ID276\"),\"2\");  \n  cout << \"EM\"<<endl;  \n  duo.EM(10);\n  cout << \"viterbi\" <<endl;\n  duo.viterbi();\n  start = 4850;\n  for(int i=start;i<start+20;i++) {\n    cout << i << \"\\t\";\n    for(int j=0;j<4;j++) \n      cout << duo.posterior[j][i]<<\"\\t\";\n    cout << \"\\t\" << duo.stateseq[i] << endl;\n  }\n  ph.haps->writeHaps(argv[1]);\n  cout <<\"\\nAll tests completed.\\nExiting...\"<<endl;  return(0);\n  \n}\n\n", "meta": {"hexsha": "32113573c040505207fd050433583c7890b3ea36", "size": 5002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test.cpp", "max_stars_repo_name": "jaredo/duohmm", "max_stars_repo_head_hexsha": "95bd3958792aeaa43e9f301ead139e5691d7c165", "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/test.cpp", "max_issues_repo_name": "jaredo/duohmm", "max_issues_repo_head_hexsha": "95bd3958792aeaa43e9f301ead139e5691d7c165", "max_issues_repo_licenses": ["MIT"], "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": "jaredo/duohmm", "max_forks_repo_head_hexsha": "95bd3958792aeaa43e9f301ead139e5691d7c165", "max_forks_repo_licenses": ["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.6063829787, "max_line_length": 192, "alphanum_fraction": 0.5065973611, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19863872935362745}}
{"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_IEEE_FUNCTIONS_SIMD_COMMON_SIGN_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_IEEE_FUNCTIONS_SIMD_COMMON_SIGN_HPP_INCLUDED\n\n#include <boost/simd/toolbox/ieee/functions/sign.hpp>\n#include <boost/simd/include/functions/simd/seladd.hpp>\n#include <boost/simd/include/functions/simd/is_nan.hpp>\n#include <boost/simd/include/functions/simd/negate.hpp>\n#include <boost/simd/include/functions/simd/shrai.hpp>\n#include <boost/simd/include/functions/simd/if_one_else_zero.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/sdk/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::sign_, tag::cpu_,\n                       (A0)(X),\n                       ((simd_<arithmetic_<A0>,X>))\n                      )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      typedef typename meta::scalar_of<A0>::type sA0;\n      return shrai(a0, sizeof(sA0)*8-1)-shrai(-a0, sizeof(sA0)*8-1);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::sign_, tag::cpu_,\n                                    (A0)(X),\n                                    ((simd_<unsigned_<A0>,X>))\n                                   )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      typedef typename meta::scalar_of<A0>::type sA0;\n      return if_one_else_zero(a0); //shri(-a0, sizeof(sA0)*8-1);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::sign_, tag::cpu_,\n                       (A0)(X),\n                       ((simd_<floating_<A0>,X>))\n                      )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      #ifdef BOOST_SIMD_NO_NANS\n      return boost::simd::negate(One<A0>(),a0);\n      #else\n      return seladd(is_nan(a0),boost::simd::negate(One<A0>(),a0),a0);\n      #endif\n    }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "4cbd7d5fa999a8742aca6733da431c750ebd3665", "size": 2397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/sign.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/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/sign.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/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/sign.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": 36.3181818182, "max_line_length": 80, "alphanum_fraction": 0.5753024614, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.19863872695545315}}
{"text": "#include \"bsp.h\"\n#include \"gameobject.h\"\n#include \"material.h\"\n#include \"mesh.h\"\n#include \"texture.h\"\n\nusing glm::clamp;\nusing glm::distance;\nusing glm::dot;\nusing glm::pow;\nusing glm::vec2;\nusing glm::vec3;\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/trim.hpp>\nusing boost::is_any_of;\nusing boost::split;\nusing boost::trim_if;\n\n#include <limits>\n#include <regex>\n#include <stdexcept>\nusing std::ifstream;\nusing std::numeric_limits;\nusing std::regex;\nusing std::runtime_error;\nusing std::sregex_iterator;\nusing std::stoi;\nusing std::stof;\nusing std::string;\nusing std::vector;\nusing std::unordered_map;\n\n// Inches to Meters\nconstexpr float Worldscale = 0.0254f;\n\nvoid BSP::LoadBSPFile(string filename, bool bHDR)\n{\n    pFile.open(filename, ifstream::in | ifstream::binary);\n\n    if (!pFile.is_open())\n    {\n        throw runtime_error(\"Could not open file\");\n    }\n\n    pFile.read(reinterpret_cast<char *>(&g_pBSPHeader), sizeof(g_pBSPHeader));\n\n    if (g_pBSPHeader.ident != IDBSPHEADER)\n    {\n        throw runtime_error(\"Bad signature\");\n    }\n\n    CopyLump(LUMP_MODELS, dmodels);\n    CopyLump(bHDR ? LUMP_LIGHTING_HDR\n             : LUMP_LIGHTING,\n             dlightdata);\n    CopyLump(LUMP_ENTITIES, dentdata);\n    CopyLump(LUMP_VERTEXES, dvertexes);\n    CopyLump(LUMP_TEXINFO, texinfo);\n    CopyLump(LUMP_TEXDATA, dtexdata);\n    CopyLump(LUMP_DISPINFO, g_dispinfo);\n    CopyLump(LUMP_DISP_VERTS, g_DispVerts);\n    CopyLump(bHDR ? LUMP_FACES_HDR\n             : LUMP_FACES,\n             dfaces);\n    CopyLump(LUMP_EDGES, dedges);\n    CopyLump(LUMP_SURFEDGES, dsurfedges);\n    CopyLump(LUMP_TEXDATA_STRING_DATA, g_TexDataStringData);\n    CopyLump(LUMP_TEXDATA_STRING_TABLE, g_TexDataStringTable);\n\n    pFile.close();\n\n    root = new GameObject;\n    root->SetScale(vec3(Worldscale));\n\n    ParseEntities();\n\n    dmodels.clear();\n    dlightdata.clear();\n    dentdata.clear();\n    dvertexes.clear();\n    texinfo.clear();\n    dtexdata.clear();\n    g_dispinfo.clear();\n    g_DispVerts.clear();\n    dfaces.clear();\n    dedges.clear();\n    g_TexDataStringData.clear();\n    g_TexDataStringTable.clear();\n}\n\nvoid BSP::ParseEntities()\n{\n    string s(dentdata.begin(), dentdata.end());\n\n    regex r1(R\"(\\{[^}]*\\})\");\n    regex r2(R\"(\\\"[^\\\"]*\\\")\");\n\n    for (auto it = sregex_iterator(s.begin(), s.end(), r1); it != sregex_iterator(); it++)\n    {\n        unordered_map<string, string> data;\n\n        auto ent = (*it).str();\n\n        for (auto it = sregex_iterator(ent.begin(), ent.end(), r2); it != sregex_iterator(); it++)\n        {\n            auto key = (*it++).str();\n            auto value = (*it).str();\n            trim_if(key, is_any_of(\"\\\"\"));\n            trim_if(value, is_any_of(\"\\\"\"));\n            data[key] = value;\n        }\n\n        GameObject *object;\n\n        if (data[\"classname\"] == \"worldspawn\")\n        {\n            object = BuildModel(0);\n        }\n        else\n        {\n            if (data.find(\"model\") != data.end())\n            {\n                if (data[\"model\"][0] == '*')\n                {\n                    object = BuildModel(stoi(data[\"model\"].substr(1)));\n                }\n                else\n                {\n                    // Studiomodel\n                    object = new GameObject;\n                }\n            }\n            else\n            {\n                object = new GameObject;\n            }\n        }\n\n        if (data.find(\"origin\") != data.end())\n        {\n            vector<string> origin;\n            split(origin, data[\"origin\"], is_any_of(\" \"));\n            object->SetPosition(FlipVector(vec3(stof(origin[0]), stof(origin[1]), stof(origin[2]))) * Worldscale);\n        }\n\n        object->SetParent(root);\n    }\n}\n\nSurface BSP::BuildFace(int index)\n{\n    if (dfaces[index].dispinfo != -1)\n    {\n        return BuildDisplacement(index);\n    }\n\n    Surface surface;\n    surface.index = index;\n\n    for (int i = 1; i < dfaces[index].numedges - 1; i++)\n    {\n        surface.indices.push_back(0);\n        surface.indices.push_back(i);\n        surface.indices.push_back(i + 1);\n    }\n\n    for (int i = dfaces[index].firstedge; i < dfaces[index].firstedge + dfaces[index].numedges; i++)\n    {\n        auto vertex = FlipVector(dsurfedges[i] > 0\n                                 ? dvertexes[dedges[abs(dsurfedges[i])].v[0]]\n                                 : dvertexes[dedges[abs(dsurfedges[i])].v[1]]);\n\n        auto tc1 = dot(vertex, FlipVector(texinfo[dfaces[index].texinfo].textureU))\n                   + texinfo[dfaces[index].texinfo].textureUOffset;\n        auto tc2 = dot(vertex, FlipVector(texinfo[dfaces[index].texinfo].textureV))\n                   + texinfo[dfaces[index].texinfo].textureVOffset;\n        auto tc3 = dot(vertex, FlipVector(texinfo[dfaces[index].texinfo].lightmapU))\n                   + texinfo[dfaces[index].texinfo].lightmapUOffset\n                   + .5f\n                   - dfaces[index].m_LightmapTextureMinsInLuxels[0];\n        auto tc4 = dot(vertex, FlipVector(texinfo[dfaces[index].texinfo].lightmapV))\n                   + texinfo[dfaces[index].texinfo].lightmapVOffset\n                   + .5f\n                   - dfaces[index].m_LightmapTextureMinsInLuxels[1];\n\n        tc1 /= dtexdata[texinfo[dfaces[index].texinfo].texdata].width;\n        tc2 /= dtexdata[texinfo[dfaces[index].texinfo].texdata].height;\n        tc3 /= dfaces[index].m_LightmapTextureSizeInLuxels[0] + 1;\n        tc4 /= dfaces[index].m_LightmapTextureSizeInLuxels[1] + 1;\n\n        surface.vertexes.push_back(\n        {\n            vertex,\n            vec2(tc1, tc2),\n            vec2(tc3, tc4)\n        });\n    }\n\n    return surface;\n}\n\nSurface BSP::BuildDisplacement(int index)\n{\n    Surface surface;\n    surface.index = index;\n\n    vector<vec3> vertexes;\n\n    for (int i = dfaces[index].firstedge; i < dfaces[index].firstedge + dfaces[index].numedges; i++)\n    {\n        vertexes.push_back(dsurfedges[i] > 0\n                           ? dvertexes[dedges[abs(dsurfedges[i])].v[0]]\n                           : dvertexes[dedges[abs(dsurfedges[i])].v[1]]);\n    }\n\n    auto minDist = numeric_limits<float>::max();\n    int minIndex = 0;\n\n    for (int i = 0; i < 4; i++)\n    {\n        auto dist = distance(vertexes[i], g_dispinfo[dfaces[index].dispinfo].startPosition);\n\n        if (dist < minDist)\n        {\n            minDist = dist;\n            minIndex = i;\n        }\n    }\n\n    for (int i = 0; i < minIndex; i++)\n    {\n        auto temp = vertexes[0];\n        vertexes[0] = vertexes[1];\n        vertexes[1] = vertexes[2];\n        vertexes[2] = vertexes[3];\n        vertexes[3] = temp;\n    }\n\n    auto leftEdge = vertexes[1] - vertexes[0];\n    auto rightEdge = vertexes[2] - vertexes[3];\n\n    auto numEdgeVertices = (1 << g_dispinfo[dfaces[index].dispinfo].power) + 1;\n\n    auto subdivideScale = 1.f / (numEdgeVertices - 1);\n\n    auto lightdelta = 1.f / (numEdgeVertices - 1);\n\n    auto leftEdgeStep = leftEdge * subdivideScale;\n    auto rightEdgeStep = rightEdge * subdivideScale;\n\n    for (int i = 0; i < numEdgeVertices; i++)\n    {\n        auto leftEnd = leftEdgeStep * (float) i;\n        leftEnd += vertexes[0];\n        auto rightEnd = rightEdgeStep * (float) i;\n        rightEnd += vertexes[3];\n\n        auto leftRightSeg = rightEnd - leftEnd;\n        auto leftRightStep = leftRightSeg * subdivideScale;\n\n        for (int j = 0; j < numEdgeVertices; j++)\n        {\n            auto dispVertIndex = g_dispinfo[dfaces[index].dispinfo].m_iDispVertStart;\n            dispVertIndex += i * numEdgeVertices + j;\n            auto dispVertInfo = g_DispVerts[dispVertIndex];\n\n            auto flatVertex = leftEnd + (leftRightStep * (float) j);\n\n            auto dispVertex = dispVertInfo.m_vVector * dispVertInfo.m_flDist;\n            dispVertex += flatVertex;\n\n            auto tc1 = dot(flatVertex, texinfo[dfaces[index].texinfo].textureU)\n                       + texinfo[dfaces[index].texinfo].textureUOffset;\n            auto tc2 = dot(flatVertex, texinfo[dfaces[index].texinfo].textureV)\n                       + texinfo[dfaces[index].texinfo].textureVOffset;\n            auto tc3 = lightdelta * j * dfaces[index].m_LightmapTextureSizeInLuxels[0]\n                       + .5f;\n            auto tc4 = lightdelta * i * dfaces[index].m_LightmapTextureSizeInLuxels[1]\n                       + .5f;\n\n            tc1 /= dtexdata[texinfo[dfaces[index].texinfo].texdata].width;\n            tc2 /= dtexdata[texinfo[dfaces[index].texinfo].texdata].height;\n            tc3 /= dfaces[index].m_LightmapTextureSizeInLuxels[0] + 1;\n            tc4 /= dfaces[index].m_LightmapTextureSizeInLuxels[1] + 1;\n\n            surface.vertexes.push_back(\n            {\n                FlipVector(dispVertex),\n                vec2(tc1, tc2),\n                vec2(tc3, tc4)\n            });\n        }\n    }\n\n    for (int i = 0; i < numEdgeVertices - 1; i++)\n    {\n        for (int j = 0; j < numEdgeVertices - 1; j++)\n        {\n            auto index = i * numEdgeVertices + j;\n\n            if (index % 2)\n            {\n                surface.indices.push_back(index + numEdgeVertices);\n                surface.indices.push_back(index + numEdgeVertices + 1);\n                surface.indices.push_back(index + 1);\n                surface.indices.push_back(index + numEdgeVertices);\n                surface.indices.push_back(index + 1);\n                surface.indices.push_back(index);\n            }\n            else\n            {\n                surface.indices.push_back(index + numEdgeVertices + 1);\n                surface.indices.push_back(index + 1);\n                surface.indices.push_back(index);\n                surface.indices.push_back(index + numEdgeVertices);\n                surface.indices.push_back(index + numEdgeVertices + 1);\n                surface.indices.push_back(index);\n            }\n        }\n    }\n\n    return surface;\n}\n\nGameObject *BSP::BuildModel(int index)\n{\n    auto model = new GameObject;\n\n    unordered_map<int, vector<int>> dict;\n\n    for (int i = dmodels[index].firstface; i < dmodels[index].firstface + dmodels[index].numfaces; i++)\n    {\n        dict[dtexdata[texinfo[dfaces[i].texinfo].texdata].nameStringTableID].push_back(i);\n    }\n\n    for (size_t i = 0; i < g_TexDataStringTable.size(); i++)\n    {\n        if (dict.find(i) == dict.end())\n        {\n            continue;\n        }\n\n        vector<uint32_t> indices;\n        vector<Vertex> vertexes;\n        vector<Surface> surfaces;\n\n        for (size_t j = 0; j < dict[i].size(); j++)\n        {\n            if (texinfo[dfaces[dict[i][j]].texinfo].flags & (SURF_SKY | SURF_NODRAW | SURF_HINT | SURF_SKIP))\n            {\n                continue;\n            }\n\n            surfaces.push_back(BuildFace(dict[i][j]));\n        }\n\n        auto submesh = new GameObject;\n        submesh->SetParent(model);\n\n        auto lightmap = PackLightmaps(surfaces);\n\n        for (const auto &surface : surfaces)\n        {\n            auto pointOffset = vertexes.size();\n\n            for (size_t k = 0; k < surface.indices.size(); k++)\n            {\n                indices.push_back(surface.indices[k] + pointOffset);\n            }\n\n            vertexes.insert(vertexes.end(), surface.vertexes.begin(), surface.vertexes.end());\n        }\n\n        auto material = new Material;\n        auto mesh = new Mesh(indices, vertexes);\n\n        material->SetTexture(\"_LightmapTex\", lightmap);\n\n        submesh->AddComponent(material);\n        submesh->AddComponent(mesh);\n    }\n\n    return model;\n}\n\nTexture *BSP::PackLightmaps(vector<Surface> &surfaces)\n{\n    vector<Texture *> lightmaps;\n\n    for (const auto &surface : surfaces)\n    {\n        if (dfaces[surface.index].lightofs == -1)\n        {\n            continue;\n        }\n\n        auto lightmap = new Texture(dfaces[surface.index].m_LightmapTextureSizeInLuxels[0] + 1,\n                                    dfaces[surface.index].m_LightmapTextureSizeInLuxels[1] + 1);\n        auto color = (ColorRGBExp32 *)(dlightdata.data() + dfaces[surface.index].lightofs);\n\n        for (uintmax_t i = 0; i < lightmap->GetArea(); i++)\n        {\n            lightmap->SetPixel(i, Color(clamp<int>(color[i].r * pow(2, color[i].exponent), 0, 255),\n                                        clamp<int>(color[i].g * pow(2, color[i].exponent), 0, 255),\n                                        clamp<int>(color[i].b * pow(2, color[i].exponent), 0, 255),\n                                        255));\n        }\n\n        lightmaps.push_back(lightmap);\n    }\n\n    auto atlas = new Texture(1, 1);\n    auto rc = atlas->PackTextures(lightmaps);\n\n    for (size_t i = 0; i < lightmaps.size(); i++)\n    {\n        delete lightmaps[i];\n    }\n\n    for (size_t i = 0; i < surfaces.size(); i++)\n    {\n        if (dfaces[surfaces[i].index].lightofs == -1)\n        {\n            continue;\n        }\n\n        for (size_t j = 0; j < surfaces[i].vertexes.size(); j++)\n        {\n            auto x = surfaces[i].vertexes[j].uv2.x * rc[i].size.x + rc[i].position.x;\n            auto y = surfaces[i].vertexes[j].uv2.y * rc[i].size.y + rc[i].position.y;\n\n            x /= atlas->GetWidth();\n            y /= atlas->GetHeight();\n\n            surfaces[i].vertexes[j].uv2 = vec2(x, y);\n        }\n    }\n\n    atlas->Apply(false);\n\n    return atlas;\n}\n\ntemplate<typename T>\nvoid BSP::CopyLump(int lump, vector<T> &dest)\n{\n    dest.resize(g_pBSPHeader.lumps[lump].filelen / sizeof(T));\n    pFile.seekg(g_pBSPHeader.lumps[lump].fileofs, pFile.beg);\n    pFile.read(reinterpret_cast<char *>(dest.data()), g_pBSPHeader.lumps[lump].filelen);\n}\n\nvec3 BSP::FlipVector(const vec3 &v)\n{\n    return vec3(v.x, v.z, -v.y);\n}\n", "meta": {"hexsha": "5dbb6fd9b579e8f158fb19b4e524816f9f0c0526", "size": 13550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/bsp/bsp.cpp", "max_stars_repo_name": "gadoofou87/openengine", "max_stars_repo_head_hexsha": "342d85933667c250459975fa88f0b257b9ef06f1", "max_stars_repo_licenses": ["WTFPL"], "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/bsp/bsp.cpp", "max_issues_repo_name": "gadoofou87/openengine", "max_issues_repo_head_hexsha": "342d85933667c250459975fa88f0b257b9ef06f1", "max_issues_repo_licenses": ["WTFPL"], "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/bsp/bsp.cpp", "max_forks_repo_name": "gadoofou87/openengine", "max_forks_repo_head_hexsha": "342d85933667c250459975fa88f0b257b9ef06f1", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6498905908, "max_line_length": 114, "alphanum_fraction": 0.5587453875, "num_tokens": 3524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.1986387231417079}}
{"text": "/*\n *          Copyright Andrey Semashev 2007 - 2015.\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 * \\file   timer.cpp\n * \\author Andrey Semashev\n * \\date   02.12.2007\n *\n * \\brief  This header is the Boost.Log library implementation, see the library documentation\n *         at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.\n */\n\n#include <boost/log/detail/config.hpp>\n#include <boost/log/attributes/timer.hpp>\n#include <boost/log/attributes/attribute_value_impl.hpp>\n\n#if defined(BOOST_WINDOWS) && !defined(BOOST_LOG_NO_QUERY_PERFORMANCE_COUNTER)\n\n#include <boost/assert.hpp>\n#include <boost/cstdint.hpp>\n#if !defined(BOOST_LOG_NO_THREADS)\n#include <boost/log/detail/locks.hpp>\n#include <boost/thread/mutex.hpp>\n#endif\n#include <windows.h>\n#include <boost/log/detail/header.hpp>\n\nnamespace boost {\n\nBOOST_LOG_OPEN_NAMESPACE\n\nnamespace attributes {\n\n//! Factory implementation\nclass BOOST_SYMBOL_VISIBLE timer::impl :\n    public attribute::impl\n{\nprivate:\n#if !defined(BOOST_LOG_NO_THREADS)\n    //! Synchronization mutex type\n    typedef boost::mutex mutex_type;\n    //! Synchronization mutex\n    mutex_type m_Mutex;\n#endif\n    //! Frequency factor for calculating duration\n    double m_FrequencyFactor;\n    //! Last value of the performance counter\n    uint64_t m_LastCounter;\n    //! Elapsed time duration, in microseconds\n    uint64_t m_Duration;\n\npublic:\n    //! Constructor\n    impl() : m_Duration(0)\n    {\n        LARGE_INTEGER li;\n        QueryPerformanceFrequency(&li);\n        BOOST_ASSERT(li.QuadPart != 0LL);\n        m_FrequencyFactor = 1000000.0 / static_cast< double >(li.QuadPart);\n\n        QueryPerformanceCounter(&li);\n        m_LastCounter = static_cast< uint64_t >(li.QuadPart);\n    }\n\n    //! The method returns the actual attribute value. It must not return NULL.\n    attribute_value get_value()\n    {\n        uint64_t duration;\n        {\n            BOOST_LOG_EXPR_IF_MT(log::aux::exclusive_lock_guard< mutex_type > lock(m_Mutex);)\n\n            LARGE_INTEGER li;\n            QueryPerformanceCounter(&li);\n            const uint64_t counter = static_cast< uint64_t >(li.QuadPart);\n            const uint64_t counts = counter - m_LastCounter;\n            m_LastCounter = counter;\n            duration = m_Duration + static_cast< uint64_t >(counts * m_FrequencyFactor);\n            m_Duration = duration;\n        }\n\n        return attribute_value(new attribute_value_impl< value_type >(boost::posix_time::microseconds(duration)));\n    }\n};\n\n//! Constructor\ntimer::timer() : attribute(new impl())\n{\n}\n\n//! Constructor for casting support\ntimer::timer(cast_source const& source) : attribute(source.as< impl >())\n{\n}\n\n} // namespace attributes\n\nBOOST_LOG_CLOSE_NAMESPACE // namespace log\n\n} // namespace boost\n\n#include <boost/log/detail/footer.hpp>\n\n#else // defined(BOOST_WINDOWS) && !defined(BOOST_LOG_NO_QUERY_PERFORMANCE_COUNTER)\n\n#include <boost/log/detail/header.hpp>\n\nnamespace boost {\n\nBOOST_LOG_OPEN_NAMESPACE\n\nnamespace attributes {\n\n//! Factory implementation\nclass BOOST_SYMBOL_VISIBLE timer::impl :\n    public attribute::impl\n{\npublic:\n    //! Time type\n    typedef utc_time_traits::time_type time_type;\n\nprivate:\n    //! Base time point\n    const time_type m_BaseTimePoint;\n\npublic:\n    /*!\n     * Constructor. Starts time counting.\n     */\n    impl() : m_BaseTimePoint(utc_time_traits::get_clock()) {}\n\n    attribute_value get_value() BOOST_OVERRIDE\n    {\n        return attribute_value(new attribute_value_impl< value_type >(\n            utc_time_traits::get_clock() - m_BaseTimePoint));\n    }\n};\n\n//! Constructor\ntimer::timer() : attribute(new impl())\n{\n}\n\n//! Constructor for casting support\ntimer::timer(cast_source const& source) : attribute(source.as< impl >())\n{\n}\n\n} // namespace attributes\n\nBOOST_LOG_CLOSE_NAMESPACE // namespace log\n\n} // namespace boost\n\n#include <boost/log/detail/footer.hpp>\n\n#endif // defined(BOOST_WINDOWS) && !defined(BOOST_LOG_NO_QUERY_PERFORMANCE_COUNTER)\n", "meta": {"hexsha": "db55ea7bcd15504b55f71b23894cbe1c13f700cf", "size": 4076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/log/src/timer.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "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": "console/src/boost_1_78_0/libs/log/src/timer.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "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": "console/src/boost_1_78_0/libs/log/src/timer.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "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": 25.475, "max_line_length": 114, "alphanum_fraction": 0.6984789009, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19863872172613717}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cstring>\n#include <limits>\n//#include <mpi.h>\n//#include <Eigen/Eigenvalues>\n\nenum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};\nclass Physics;\n\n#include \"particle_simulator.hpp\"\n#include \"hdr_time.hpp\"\n#include \"hdr_run.hpp\"\n#include \"vector_x86.hpp\"\n#include \"hdr_dimension.hpp\"\n#include \"hdr_kernel.hpp\"\n#include \"hdr_sph.hpp\"\n#include \"hdr_hgas.hpp\"\n#include \"hdr_bhns.hpp\"\n\nclass SPHAnalysis : public HelmholtzGas {\npublic:\n    SPHAnalysis() {\n        this->id    = 0;\n        this->istar = 0;\n        this->mass  = 0.;\n        this->pos   = 0.;\n        this->vel   = 0.;\n        this->uene  = 0.;\n        this->alph  = 0.;\n        this->alphu = 0.;\n        this->ksr   = 0.;\n        for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->cmps[k] = 0.;\n        }        \n    }\n\n    void readAscii(FILE * fp) {\n        fscanf(fp, \"%lld%lld%lf\", &this->id, &this->istar, &this->mass);      //  3\n        fscanf(fp, \"%lf%lf%lf\", &this->pos[0], &this->pos[1], &this->pos[2]); //  6\n        fscanf(fp, \"%lf%lf%lf\", &this->vel[0], &this->vel[1], &this->vel[2]); //  9\n        fscanf(fp, \"%lf%lf%lf\", &this->acc[0], &this->acc[1], &this->acc[2]); // 12\n        fscanf(fp, \"%lf%lf%lf\", &this->uene, &this->alph, &this->alphu);      // 15\n        fscanf(fp, \"%lf%lf%6d\", &this->dens, &this->ksr,  &this->np);         // 18\n        fscanf(fp, \"%lf%lf%lf\", &this->vsnd, &this->pres, &this->temp);       // 21\n        fscanf(fp, \"%lf%lf%lf\", &this->divv, &this->rotv, &this->bswt);       // 24\n        fscanf(fp, \"%lf%lf%lf\", &this->pot,  &this->abar, &this->zbar);       // 27\n        fscanf(fp, \"%lf\",       &this->enuc);                                 // 28\n        fscanf(fp, \"%lf%lf%lf\", &this->vsmx, &this->udot, &this->dnuc);       // 31\n        for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) {       // 32 -- 44\n            fscanf(fp, \"%lf\", &this->cmps[k]);\n        }\n        fscanf(fp, \"%lf\", &this->pot3);\n        fscanf(fp, \"%lf%lf%lf\", &this->tempmax[0], &this->tempmax[1], &this->tempmax[2]);\n        fscanf(fp, \"%lf\", &this->entr);\n    }\n\n    /*\n    void write(FILE * fp = stdout) {\n        fprintf(fp, \"%8d %2d %+e\",  this->id, this->istar, this->mass);\n        fprintf(fp, \" %+e %+e %+e\", this->pos[0], this->pos[1], this->pos[2]);\n        fprintf(fp, \" %+e %+e %+e\", this->vel[0], this->vel[1], this->vel[2]);\n        fprintf(fp, \" %+e %+e %+e\", this->uene, this->alph, this->alphu);\n        fprintf(fp, \" %+e\", this->ksr);\n        for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n            fprintf(fp, \" %+.3e\", this->cmps[k]);\n        }\n        fprintf(fp, \"\\n\");\n    }\n    */\n\n    inline PS::F64mat calcMomentOfInertia(PS::F64vec xc) {\n        PS::F64mat qq = 0.;\n        PS::F64vec dx = this->pos - xc;\n        PS::F64 r2 = dx * dx;\n        qq.xx = this->mass * (r2 - dx[0] * dx[0]);\n        qq.xy = this->mass * (   - dx[0] * dx[1]);\n        qq.xz = this->mass * (   - dx[0] * dx[2]);\n        qq.yy = this->mass * (r2 - dx[1] * dx[1]);\n        qq.yz = this->mass * (   - dx[1] * dx[2]);\n        qq.zz = this->mass * (r2 - dx[2] * dx[2]);\n        return qq;\n    }\n\n    void copyFromForce(const Physics & physics);\n};\n\nclass BlackHoleNeutronStarAnalysis : public BlackHoleNeutronStar {\npublic:\n    BlackHoleNeutronStarAnalysis() {\n        this->id    = 0;\n        this->istar = 0;\n        this->mass  = 0.;\n        this->pos   = 0.;\n        this->vel   = 0.;\n        this->acc   = 0.;\n        this->eps   = 0.;\n        this->pot   = 0.;\n    }\n\n    void readAscii(FILE * fp) {\n        fscanf(fp, \"%lld%lld%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf\",\n               &this->id, &this->istar, &this->mass,\n               &this->pos[0], &this->pos[1], &this->pos[2],\n               &this->vel[0], &this->vel[1], &this->vel[2],\n               &this->acc[0], &this->acc[1], &this->acc[2],\n               &this->eps, &this->pot);\n    }\n\n    inline PS::F64mat calcMomentOfInertia(PS::F64vec xc) {\n        PS::F64mat qq = 0.;\n        PS::F64vec dx = this->pos - xc;\n        PS::F64 r2 = dx * dx;\n        qq.xx = this->mass * (r2 - dx[0] * dx[0]);\n        qq.xy = this->mass * (   - dx[0] * dx[1]);\n        qq.xz = this->mass * (   - dx[0] * dx[2]);\n        qq.yy = this->mass * (r2 - dx[1] * dx[1]);\n        qq.yz = this->mass * (   - dx[1] * dx[2]);\n        qq.zz = this->mass * (r2 - dx[2] * dx[2]);\n        return qq;\n    }\n};\n\nclass MeshData : public SPHAnalysis {\npublic:\n    PS::F64 tempu;\n\n    MeshData() {\n        this->id    = 0;\n        this->istar = 0;\n        this->mass  = 0.;\n        this->pos   = 0.;\n        this->vel   = 0.;\n        this->uene  = 0.;\n        this->alph  = 0.;\n        this->alphu = 0.;\n        this->ksr   = 0.;\n        for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->cmps[k] = 0.;\n        }        \n    }\n\n    void writeAscii(FILE *fp) {\n        fprintf(fp, \"%8d\", this->id);\n        fprintf(fp, \" %+e %+e %+e\", this->pos[0], this->pos[1], this->pos[2]);\n        fprintf(fp, \" %+e %+e %+e\", this->dens, this->temp, this->tempu);\n        fprintf(fp, \" %+e\", this->vsnd);\n        fprintf(fp, \"\\n\");\n    }\n\n    void copyFromForce(const Physics & physics);\n};\n\ntemplate <class Tmesh>\nvoid generateMeshData(Tmesh & mesh) {\n    if(PS::Comm::getRank() != 0) {\n        return;\n    }\n    PS::F64 xmin = -5e8;\n    PS::F64 xmax = +5e8;\n    PS::S64 nx   = 100;\n    PS::S64 nx3  = nx * nx * nx;\n    PS::F64 dx   = (xmax - xmin) / (PS::F64)nx;\n    mesh.setNumberOfParticleLocal(nx3);\n    for(PS::S64 i = 0; i < nx; i++) {\n        for(PS::S64 j = 0; j < nx; j++) {\n            for(PS::S64 k = 0; k < nx; k++) {\n                PS::S64 id = i * nx * nx + j * nx + k;\n                mesh[id].id     = id;\n                mesh[id].mass   = 0.;\n                mesh[id].pos[0] = xmin + dx * (PS::F64)i;\n                mesh[id].pos[1] = xmin + dx * (PS::F64)j;\n                mesh[id].pos[2] = xmin + dx * (PS::F64)k;\n                mesh[id].ksr    = 1e7;\n                mesh[id].dens   = 0.;\n                mesh[id].temp   = 0.;\n            }\n        }\n    }\n}\n\nclass Physics {\npublic:\n    PS::F64 dens;\n    PS::F64 temp;\n    PS::F64 uene;\n    void clear() {\n        dens = 0.;\n        temp = 0.;\n        uene = 0.;\n    }\n};\n\nvoid SPHAnalysis::copyFromForce(const Physics & physics) {\n    this->dens = physics.dens;\n    this->temp = physics.temp;\n    this->uene = physics.uene;\n}\n\nvoid MeshData::copyFromForce(const Physics & physics) {\n    this->dens = physics.dens;\n    this->temp = physics.temp;\n    this->uene = physics.uene;\n}\n\nclass PhysicsEPI {\npublic:\n    PS::S32    id;\n    PS::F64    mass;\n    PS::F64vec pos;\n    bool       meshornot;\n\n    void copyFromFP(const SPHAnalysis & sph) {\n        this->id   = sph.id;\n        this->mass = sph.mass;        \n        this->pos  = sph.pos;\n        this->meshornot = false;\n    }\n\n    void copyFromFP(const MeshData & mesh) {\n        this->id   = mesh.id;\n        this->mass = mesh.mass;        \n        this->pos  = mesh.pos;\n        this->meshornot = true;\n    }\n\n    PS::F64vec getPos() const {\n        return this->pos;\n    }\n\n};\n\nclass PhysicsEPJ {\npublic:\n    PS::S32    id;\n    PS::F64    mass;\n    PS::F64vec pos;\n    PS::F64    ksr;\n    PS::F64    hinv;\n    PS::F64    dinv;\n    PS::F64    temp;\n    PS::F64    uene;\n    bool       meshornot;\n\n    void copyFromFP(const SPHAnalysis & sph) {\n        this->id   = sph.id;\n        this->mass = sph.mass;        \n        this->pos  = sph.pos;\n        this->ksr  = sph.ksr;\n        this->hinv = 1. / sph.ksr;\n        this->dinv = 1. / sph.dens;\n        this->temp = sph.temp;\n        this->uene = sph.uene;\n        this->meshornot = false;\n    }\n\n    void copyFromFP(const MeshData & mesh) {\n        this->id   = mesh.id;\n        this->mass = mesh.mass;        \n        this->pos  = mesh.pos;\n        this->ksr  = mesh.ksr;\n        this->hinv = 1. / mesh.ksr;\n        this->dinv = 1. / mesh.dens;\n        this->temp = mesh.temp;\n        this->uene = mesh.uene;\n        this->meshornot = true;\n    }\n\n    PS::F64vec getPos() const {\n        return this->pos;\n    }\n\n    PS::F64 getRSearch() const {\n        return this->ksr;\n    }\n\n    void setPos(const PS::F64vec pos_new) {\n        pos = pos_new;\n    }\n};\n\nstruct calcPhysics {\n\n    const PS::F64 ceff0 = +3.342253804929802286e+00;\n    inline PS::F64 kernel0th(const PS::F64 r) {\n        PS::F64 rmin  = ((1. - r > 0.) ? (1. - r) : 0.);\n        PS::F64 rmin2 = rmin * rmin;\n        return ceff0 * rmin2 * rmin2 * (1. + 4. * r);\n    }\n\n    void operator () (const PhysicsEPI * epi,\n                      const PS::S32 nip,\n                      const PhysicsEPJ * epj,\n                      const PS::S32 njp,\n                      Physics * physics) {\n\n        for(PS::S64 i = 0; i < nip; i++) {\n\n            if(!epi[i].meshornot) {\n                continue;\n            }\n\n            PS::F64 dens = 0.;\n            PS::F64 temp = 0.;\n            PS::F64 uene = 0.;\n\n            for(PS::S64 j = 0; j < njp; j++) {\n                PS::F64vec dx  = epi[i].pos - epj[j].pos;\n                PS::F64    r2  = dx * dx;\n                PS::F64    r1  = sqrt(r2);\n                PS::F64    q   = r1 * epj[j].hinv;\n                PS::F64    kw0 = kernel0th(q);\n                PS::F64    hi3 = epj[j].hinv * epj[j].hinv * epj[j].hinv;\n\n                PS::F64 densi = epj[j].mass * hi3 * kw0;\n                PS::F64 tempi = epj[j].mass * hi3 * kw0 * epj[j].temp * epj[j].dinv;\n                PS::F64 uenei = epj[j].mass * hi3 * kw0 * epj[j].uene * epj[j].dinv;\n                dens += ((epj[j].mass != 0.) ? densi : 0.);\n                temp += ((epj[j].mass != 0.) ? tempi : 0.);\n                uene += ((epj[j].mass != 0.) ? uenei : 0.);\n            }\n\n            physics[i].dens = dens;\n            physics[i].temp = temp;\n            physics[i].uene = uene;\n        }\n        \n    }\n\n};\n\ntemplate <class Tdinfo,\n          class Tsph,\n          class Tmesh,\n          class Tphysics>\nvoid calcMeshData(Tdinfo & dinfo,\n                  Tsph & sph,\n                  Tmesh & mesh,\n                  Tphysics & physics) {\n    PS::MT::init_genrand(0);\n    dinfo.decomposeDomainAll(sph);\n    sph.exchangeParticle(dinfo);\n    mesh.exchangeParticle(dinfo);\n    physics.setParticleLocalTree(mesh);\n    physics.setParticleLocalTree(sph, false);\n    physics.calcForceMakingTree(calcPhysics(), dinfo);\n    PS::S64 nmesh = mesh.getNumberOfParticleLocal();\n    for(PS::S64 i = 0; i < nmesh; i++) {\n        mesh[i].copyFromForce(physics.getForce(i));\n    }\n    for(PS::S64 i = 0; i < nmesh; i++) {\n        NR::Nucleon cmps;\n        cmps[1] = cmps[2] = 0.5;\n        PS::F64 dens = mesh[i].dens;\n        PS::F64 uene = mesh[i].uene;\n        PS::F64 temp = mesh[i].temp;\n        PS::F64 tout = 0.;\n        PS::F64 pout, cout, sout;\n        if(dens != 0.) {\n            flash_helmholtz_(&dens, &uene, &temp, cmps.getPointer(),\n                             &pout, &cout, &tout, &sout);\n        }\n        mesh[i].tempu = tout;\n        mesh[i].vsnd  = sout;\n    }\n}\n\ntemplate <class Tsph,\n          class Tbhns>\nvoid shiftCenter(Tsph & sph,\n                 Tbhns & bhns) {\n    PS::S64    nbhns = bhns.getNumberOfParticleLocal();\n    PS::F64vec ploc  = 0.;\n    if(nbhns == 1) {\n        ploc = bhns[0].pos;\n    } else {\n        ploc = 0.;\n    }\n    PS::F64vec pbhns = PS::Comm::getSum(ploc);\n\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        sph[i].pos -= pbhns;\n    }\n}\n\nint main(int argc, char ** argv) {\n    PS::Initialize(argc, argv);\n\n    init_flash_helmholtz_(&CodeUnit::FractionOfCoulombCorrection);\n\n    PS::DomainInfo dinfo;\n    dinfo.initialize();\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n    PS::ParticleSystem<BlackHoleNeutronStarAnalysis> bhns;\n    bhns.initialize();\n    bhns.createParticle(0);\n    bhns.setNumberOfParticleLocal(0);\n    PS::ParticleSystem<MeshData> mesh;\n    mesh.initialize();\n    mesh.createParticle(0);\n    mesh.setNumberOfParticleLocal(0);\n    PS::TreeForForceShort<Physics, PhysicsEPI, PhysicsEPJ>::Scatter physics;\n    physics.initialize(0);\n\n    if(PS::Comm::getRank() == 0) {\n        printf(\"AT comments: NPROCESS %8d\\n\", PS::Comm::getNumberOfProc());\n        printf(\"AT comments: NTHREAD  %8d\\n\", PS::Comm::getNumberOfThread());\n    }\n\n    char idir[1024], otype[1024];\n    PS::S64 ibgn, iend;\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", idir);\n    fscanf(fp, \"%s\", otype);\n    fscanf(fp, \"%lld%lld\", &ibgn, &iend);\n    fclose(fp);\n\n    generateMeshData(mesh);\n\n    for(PS::S64 itime = ibgn; itime <= iend; itime++) {\n        char sfile[1024], bfile[1024];\n        sprintf(sfile, \"%s/sph_t%04d.dat\",  idir, itime);\n        sprintf(bfile, \"%s/bhns_t%04d.dat\", idir, itime);\n        fp = fopen(sfile, \"r\");\n        if(fp == NULL) {\n            continue;\n        }\n        sph.readParticleAscii(sfile);\n        fclose(fp);\n        fp = fopen(bfile, \"r\");\n        if(fp == NULL) {\n            continue;\n        }\n        bhns.readParticleAscii(bfile);\n        fclose(fp);\n\n        shiftCenter(sph, bhns);\n        calcMeshData(dinfo, sph, mesh, physics);\n\n        char ofile[1024];\n        sprintf(ofile, \"%s_t%04d.dat\", otype, itime);\n        mesh.writeParticleAscii(ofile);\n    }\n\n    PS::Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "589d47f79e53d9d02ca0602994975d980a456f46", "size": 13375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.nswd/calc_hotspot/main.cpp", "max_stars_repo_name": "atrtnkw/sph", "max_stars_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-11T00:43:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T13:41:50.000Z", "max_issues_repo_path": "tool.nswd/calc_hotspot/main.cpp", "max_issues_repo_name": "atrtnkw/sph", "max_issues_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_issues_repo_licenses": ["MIT"], "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.nswd/calc_hotspot/main.cpp", "max_forks_repo_name": "atrtnkw/sph", "max_forks_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-06T14:22:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T14:22:25.000Z", "avg_line_length": 29.5253863135, "max_line_length": 89, "alphanum_fraction": 0.484635514, "num_tokens": 4376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1986387217261371}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SIMD_SQRT1PM1_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIMD_SQRT1PM1_HPP_INCLUDED\n\n#include <boost/simd/function/scalar/sqrt1pm1.hpp>\n#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>\n#include <boost/simd/arch/common/simd/function/sqrt1pm1.hpp>\n\n#endif\n", "meta": {"hexsha": "742cf230140cce9a71a9af71e622a4f3059702c3", "size": 685, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/simd/sqrt1pm1.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/simd/sqrt1pm1.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/simd/sqrt1pm1.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": 38.0555555556, "max_line_length": 100, "alphanum_fraction": 0.5708029197, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3557748866829643, "lm_q1q2_score": 0.198638717912392}}
{"text": "#ifndef SLIDE_DETAILS_ALIGN_BOARD_HPP_\n#define SLIDE_DETAILS_ALIGN_BOARD_HPP_\n\n#include <vector>\n#include <boost/format.hpp>\n\n#include \"../AlignBoard.hpp\"\n#include \"util/color.hpp\"\n#include \"util/StopWatch.hpp\"\n\nnamespace slide\n{\n\ntemplate<typename Base>\ninline bool AlignBoard<Base>::extractSrcPiece(const Point src, const Point dst)\n{\n    if(fixed.countRowZero(src.y) == 1 || fixed.countColZero(src.x) == 1){\n        rep(i, 4){\n            const Direction dir(i);\n            const Point tmp = src + Point::delta(dir);\n            if(tmp.isIn(height(), width()) && fixed(tmp) && !isAligned(tmp)){\n                fixed.reset(tmp);\n                if(trajectPiece(src, dst)){\n                    unfixCandidate(tmp);\n                    return true;\n                }\n                fixed.set(tmp);\n            }\n        }\n        return false;\n    }\n    rep(i, 4){\n        const Direction dir(i);\n        const Point tmp = src + Point::delta(dir);\n        if(tmp.isIn(height(), width()) && fixed(tmp)){\n            fixed.reset(tmp);\n            if(trajectPiece(src, dst)){\n                unfixCandidate(tmp);\n                return true;\n            }\n            fixed.set(tmp);\n        }\n    }\n    return false;\n}\n\ntemplate<typename Base> \ninline bool AlignBoard<Base>::moveOneAnyDirection()\n{\n    rep(i, 4){\n        const Direction dir(i);\n        const Point to = selected + Point::delta(dir);\n        if(to.isIn(height(), width()) && !fixed(to)){\n            move(dir);\n            return true;\n        }\n    }\n    return false;\n}\n\ntemplate<typename Base>\nbool AlignBoard<Base>::align(const Point dst)\n{\n    // \u306f\u3058\u3081\u306bselected\u304c\u6e9d\u306b\u3044\u308b\u5834\u5408\u306f\u6e9d\u304b\u3089\u51fa\u308b\n    if(countAdjacentFixedCell(selected) == 3){\n        moveOneAnyDirection();\n    }\n\n\n    const int numRemain = std::min(width() - fixed.countRow(dst.y), height() - fixed.countCol(dst.x));\n    if(numRemain > 2){\n        const Point src = find(correctId(dst));\n        if(src == dst){\n            fixCandidate(dst);\n            return true;\n        }\n\n        if(trajectPiece(src, dst)){\n            fixCandidate(dst);\n            return true;\n        }\n        else{\n            // src\u304c\u6e9d\u306b\u57cb\u307e\u3063\u3066\u3044\u308b\u5834\u5408\u306f\u305d\u306e\u96a3\u63a5\u3059\u308b\u30de\u30b9\u306efixed\u3092\u89e3\u9664\u3057\u3066,\n            // trajectPiece\u3067\u304d\u308b\u304b\u5224\u65ad\u3057, \u6210\u529f\u3057\u305f\u306a\u3089true\u3092\u8fd4\u3059.\n            if(countAdjacentFixedCell(src) == 3){\n                return extractSrcPiece(src, dst);\n            }\n        }\n    }\n    else if(numRemain == 2){\n        bool flag;\n        Point src;\n        if(fixed.countRowZero(dst.y) < fixed.countColZero(dst.x)){\n            if(!Point(dst.y, dst.x+1).isIn(height(), width()) ||\n                (Point(dst.y, dst.x+1).isIn(height(), width()) && fixed(dst.y, dst.x+1))){\n                src = find( (dst+Point(0, -1)).toInt() );\n                if( src == selected ) return false;\n                if(countAdjacentFixedCell(src) == 3){\n                    extractSrcPiece(src, dst);\n                    src = dst;\n                }\n                flag = trajectPiece(src, dst);\n            }\n            else {\n                src = find((dst+Point(0, +1)).toInt());\n                if( src == selected )return false;\n                if(countAdjacentFixedCell(src) == 3){\n                    extractSrcPiece(src, dst);                    \n                    src = dst;\n                }                \n                flag = trajectPiece(src, dst);\n            }\n        } else {\n            if(!Point(dst.y+1, dst.x).isIn(height(), width()) ||\n                (Point(dst.y+1, dst.x).isIn(height(), width()) && fixed(dst.y+1, dst.x))){\n                src = find((dst+Point(-1, 0)).toInt());\n                if( src == selected )return false;\n                if(countAdjacentFixedCell(src) == 3){\n                    extractSrcPiece(src, dst);\n                    src = dst;\n                }\n                flag = trajectPiece(src, dst);\n            } else {\n                src = find( (dst+Point(+1, 0)).toInt() );\n                if( src == selected )return false;\n                if(countAdjacentFixedCell(src) == 3){\n                    extractSrcPiece(src, dst);       \n                    src = dst;             \n                }\n                flag = trajectPiece(src, dst);\n            }\n        }\n        if(flag){\n            fixCandidate(dst);\n            return true;\n        }\n    }\n    else if(numRemain == 1){\n        if(alignLastOne(dst)){\n            fixCandidate(dst);\n            return true;\n        }\n    }\n\n    BOOST_ASSERT(false);\n    return false;\n}\n\ntemplate<typename Base>\nbool AlignBoard<Base>::alignLastOne(Point dst)\n{\n    // dst\u306e\u6a2a\u306enot aligned\u306a\u30de\u30b9\u3092\u63a2\u3059.\n    Point p(0, 0);\n    rep(i, 4){\n        const Direction dir(i);\n        p = dst + Point::delta(dir);\n        if( p.isIn(height(), width()) && fixed(p) && !isAligned(p)){\n            break;\n        };\n    }\n    // \u672c\u6765\u5165\u308b\u3079\u304d\u756a\u53f7src\u3092\u63a2\u3059.\n    Point src = find(p.toInt());\n\n    if(src == dst){\n        return swapAdjacentPiece(src, p);\n    }\n\n    // src\u304c\u5165\u308bto\u306e\u4f4d\u7f6e\u3092\u63a2\u3059.\n    Point to;\n    rep(i, 4){\n        const Direction dir(i);\n        to = p + Point::delta(dir);\n        if( to.isIn(height(), width()) && !fixed(to) && to != dst){\n            break;\n        }\n    }\n\n    // src\u304c\u57cb\u307e\u3063\u3066\u3044\u308b\u5834\u5408\u306f\u307e\u308f\u308a\u306efixed\u3092\u958b\u653e\u3057\u3066\u3068\u3063\u3066\u304f\u308b.\n    if(countAdjacentFixedCell(src) == 3){\n        extractSrcPiece(src, to);\n        src = to;\n    }\n\n    // \u30d4\u30fc\u30b9\u304c\u6b63\u3057\u304f\u52d5\u304b\u305b\u308b\u4f4d\u7f6e\u306b\u3042\u308b\u5834\u5408\n    if(trajectPiece(src, to)){\n        // \u30d4\u30fc\u30b9\u304c\u6b63\u3057\u304f\u52d5\u304b\u305b\u3066\u3082, selected\u304c\u306f\u307e\u3063\u3066\u3057\u307e\u3063\u3066\u3044\u308b\u5834\u5408\u3082\u3042\u308b.\n        fixed.set(to, true);\n        moveToOptimally(dst); // selected\u3060\u3051\u52d5\u304b\u3059\n\n        // 4\u65b9\u5411\u3092\u898b\u3066\u4eca\u3044\u308c\u3088\u3046\u3068\u3057\u3066\u3044\u308b, \u30d6\u30ed\u30c3\u30af\u3092\u3055\u304c\u3057\u3066, \u305d\u306e\u65b9\u5411\u306b\u9032\u3080\n        rep(i, 4){\n            const Direction dir(i);\n            if( (dst+Point::delta(dir)).isIn(height(), width()) &&\n                dst.toInt() == at(dst+Point::delta(dir))){\n                move(dir);\n                fixed.set(dst, true);\n                dst += Point::delta(dir);\n                break;\n            }\n        }\n        rep(i, 4){\n            const Direction dir(i);\n            if( (dst+Point::delta(dir)).isIn(height(), width()) &&\n                dst.toInt() == at(dst+Point::delta(dir))){\n                move(dir);\n                fixed.set(dst+Point::delta(dir), false);\n                break;\n            }\n        }\n        return true;\n    }\n    // \u30d4\u30fc\u30b9\u304c\u52d5\u304b\u305b\u306a\u3044\u5834\u5408\n    else {\n        // std::cout << src.toInt() << \" \" << at(dst) << std::endl;\n        // std::cout << src << \" \" << to << std::endl;\n        std::cout << \"failed\" << std::endl;\n        std::cout << *this << std::endl;\n        //exit(-1);\n        return false;\n    }\n}\n\ntemplate<typename Base>\nbool AlignBoard<Base>::swapAdjacentPiece(Point a, Point b)\n{\n    Direction dir(0);\n    if(a.x == b.x){\n        Point tmp = a + Point(0,-1);\n        if(!tmp.isIn(height(), width()) || fixed(tmp) ){\n            dir = Direction::Left;\n        } else {\n            dir = Direction::Right;\n        }\n        if( (int)(b.y < a.y) == (0 < (static_cast<int>(dir) & 2)) ) {\n            std::swap(a, b);\n        }\n    } else if( a.y == b.y ){\n        Point tmp = a + Point(-1,0);\n        if(!tmp.isIn(height(), width()) || fixed(tmp)){\n            dir = Direction::Up;\n        } else {\n            dir = Direction::Down;\n        }\n        if( (int)(b.x < a.x) == (0 < static_cast<int>(dir) )){\n            std::swap(a, b);\n        }\n    }\n\n    fixed.set(a, false);\n    fixed.set(b, true);\n    moveToOptimally(a);\n    fixed.set(b, false);\n    moveToOptimally(b);\n\n    move( static_cast<Direction>((static_cast<int>(Direction::Down) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Right) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Down) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Left) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Up) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Up) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Right) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Down) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Left) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Down) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Right) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Up) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Up) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Left) + static_cast<int>(dir) ) & 0x03) );\n    move( static_cast<Direction>((static_cast<int>(Direction::Down) + static_cast<int>(dir) ) & 0x03) );\n\n    BOOST_ASSERT( isAligned(a) && isAligned(b) );\n    fixed.set(a, true);\n    fixed.set(b, true);\n    return true;\n}\n\ntemplate<typename Base>\nstd::ostream& operator<<(std::ostream& out, const AlignBoard<Base>& board)\n{\n    std::vector<Point> candidates;\n    board.getCandidates(candidates);\n\n    std::vector<std::vector<bool>> bb(board.height(), std::vector<bool>(board.width(), false));\n    for(Point p : candidates){\n        bb[p.y][p.x] = true;\n    }\n\n    rep(i, board.height()){\n        rep(j, board.width()){\n            out << '|';\n\n            bool changed;\n            if(bb[i][j]){\n                out << util::ForeYellow;\n                changed = true;\n            }\n            else if(!board.fixed(i, j) || !board.isAligned(i, j)){\n                out << util::ForeRed;\n                changed = true;\n            }\n            else{\n                changed = false;\n            }\n\n            if(Point(i, j) == board.selected){\n                out << util::BackGreen;\n                changed = true;\n            }\n\n            out << boost::format(\"%02X\") % int(board(i, j));\n\n            if(changed){\n                out << util::Default;\n            }\n        }\n        out << \"|\\n\";\n    }\n\n    return out;\n}\n\n} // end of namespace slide\n\n#endif\n", "meta": {"hexsha": "e54ab61d120f8a7abe51e6566389edd05d25ebf2", "size": 10157, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/modules/slide/include/slide/details/AlignBoard.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/details/AlignBoard.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/details/AlignBoard.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": 31.2523076923, "max_line_length": 105, "alphanum_fraction": 0.502215221, "num_tokens": 2640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.19860634524013585}}
{"text": "/*\n\tCopyright (C) 2003-2013 by David White <davewx7@gmail.com>\n\t\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, see <http://www.gnu.org/licenses/>.\n*/\n\n#if defined(USE_SHADERS)\n#include <assert.h>\n#include <math.h>\n#include <glm/gtc/type_precision.hpp>\n\n#include <boost/array.hpp>\n\n#include <vector>\n\n#include \"graphics.hpp\"\n#include \"asserts.hpp\"\n#include \"color_utils.hpp\"\n#include \"draw_primitive.hpp\"\n#include \"foreach.hpp\"\n#include \"geometry.hpp\"\n#include \"gles2.hpp\"\n#include \"level.hpp\"\n#include \"raster.hpp\"\n#include \"shaders.hpp\"\n#include \"texture.hpp\"\n\nnamespace graphics\n{\n\nusing namespace gles2;\n\nnamespace\n{\n\nclass rect_primitive : public draw_primitive\n{\npublic:\n\texplicit rect_primitive(const variant& v);\nprivate:\n\tvoid init();\n\n\tvoid handle_draw() const;\n#ifdef USE_ISOMAP\n\tvoid handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const;\n#endif\n\n\tvariant get_value(const std::string& key) const;\n\tvoid set_value(const std::string& key, const variant& value);\n\n\trect area_;\n\tgraphics::color color_;\n\tshader_program_ptr shader_;\n\tmutable std::vector<GLfloat> varray_;\n};\n\nrect_primitive::rect_primitive(const variant& v)\n\t: draw_primitive(v), area_(v[\"area\"]), color_(v[\"color\"]), \n     shader_(gles2::get_simple_shader())\n{\n\tif(v.has_key(\"shader\")) {\n\t\tshader_.reset(new shader_program(v[\"shader\"].as_string()));\n\t}\n\n\tinit();\n}\n\nvoid rect_primitive::init()\n{\n\tvarray_.clear();\n\tvarray_.push_back(area_.x());\n\tvarray_.push_back(area_.y());\n\tvarray_.push_back(area_.x2());\n\tvarray_.push_back(area_.y());\n\tvarray_.push_back(area_.x());\n\tvarray_.push_back(area_.y2());\n\tvarray_.push_back(area_.x2());\n\tvarray_.push_back(area_.y2());\n}\n\nvoid rect_primitive::handle_draw() const\n{\n\tcolor_.set_as_current_color();\n\n\tgles2::manager gles2_manager(shader_);\n\tgles2::active_shader()->prepare_draw();\n\tgles2::active_shader()->shader()->vertex_array(2, GL_FLOAT, 0, 0, &varray_.front());\n\tglDrawArrays(GL_TRIANGLE_STRIP, 0, varray_.size()/2);\n\n\tglColor4f(1.0, 1.0, 1.0, 1.0);\n}\n\n#ifdef USE_ISOMAP\nvoid rect_primitive::handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const\n{\n}\n#endif\n\nvariant rect_primitive::get_value(const std::string& key) const\n{\n\treturn draw_primitive::get_value(key);\n}\n\nvoid rect_primitive::set_value(const std::string& key, const variant& value)\n{\n\tdraw_primitive::set_value(key, value);\n}\n\ntypedef boost::array<GLfloat, 2> FPoint;\n\nclass circle_primitive : public draw_primitive\n{\npublic:\n\texplicit circle_primitive(const variant& v);\n\nprivate:\n\tvoid init();\n\n\tvoid handle_draw() const;\n#ifdef USE_ISOMAP\n\tvoid handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const;\n#endif\n\tvariant get_value(const std::string& key) const;\n\tvoid set_value(const std::string& key, const variant& value);\n\n\tFPoint center_;\n\tfloat radius_;\n\tfloat y_radius_;\n\tfloat stroke_width_;\n\n\tgraphics::color color_;\n\tgraphics::color stroke_color_;\n\n\tshader_program_ptr shader_;\n\n\tmutable std::vector<GLfloat> varray_;\n};\n\ncircle_primitive::circle_primitive(const variant& v)\n   : draw_primitive(v),\n     radius_(v[\"radius\"].as_decimal().as_float()),\n     y_radius_(v[\"y_radius\"].as_decimal(decimal(radius_)).as_float()),\n\t stroke_width_(0.0),\n     shader_(gles2::get_simple_shader())\n{\n\tif(v.has_key(\"shader\")) {\n\t\tshader_.reset(new shader_program(v[\"shader\"].as_string()));\n\t}\n\n\tcenter_[0] = v[\"x\"].as_decimal().as_float();\n\tcenter_[1] = v[\"y\"].as_decimal().as_float();\n\n\tif(v.has_key(\"color\")) {\n\t\tcolor_ = color(v[\"color\"]);\n\t} else {\n\t\tcolor_ = color(200, 0, 0, 255);\n\t}\n\n\tif(v.has_key(\"stroke_color\")) {\n\t\tstroke_color_ = color(v[\"stroke_color\"]);\n\t\tstroke_width_ = v[\"stroke_width\"].as_decimal().as_float();\n\t}\n\n\n\tinit();\n}\n\nvoid circle_primitive::init()\n{\n\tvarray_.clear();\n\tvarray_.push_back(center_[0]);\n\tvarray_.push_back(center_[1]);\n\tfor(double angle = 0; angle < 3.1459*2.0; angle += 0.1) {\n\t\tconst double xpos = center_[0] + radius_*cos(angle);\n\t\tconst double ypos = center_[1] + y_radius_*sin(angle);\n\t\tvarray_.push_back(xpos);\n\t\tvarray_.push_back(ypos);\n\t}\n\n\t//repeat the first coordinate to complete the circle.\n\tvarray_.push_back(varray_[2]);\n\tvarray_.push_back(varray_[3]);\n\n}\n\n#ifdef USE_ISOMAP\nvoid circle_primitive::handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const\n{\n}\n#endif\n\nvoid circle_primitive::handle_draw() const\n{\n\tgles2::manager gles2_manager(shader_);\n\n\tif(color_.a() > 0) {\n\t\tcolor_.set_as_current_color();\n\n\t\tgles2::active_shader()->prepare_draw();\n\t\tgles2::active_shader()->shader()->vertex_array(2, GL_FLOAT, 0, 0, &varray_.front());\n\t\tglDrawArrays(GL_TRIANGLE_FAN, 0, varray_.size()/2);\n\t}\n\n\tif(stroke_color_.a() > 0) {\n\t\tglLineWidth(stroke_width_);\n\t\tstroke_color_.set_as_current_color();\n\n\t\tgles2::active_shader()->prepare_draw();\n        gles2::active_shader()->shader()->disable_vertex_attrib(-1);\n\t\tgles2::active_shader()->shader()->vertex_array(2, GL_FLOAT, 0, 0, &varray_[2]);\n        glDrawArrays(GL_LINE_LOOP, 0, (varray_.size()-2)/2);\n\t}\n\n\tglColor4f(1.0, 1.0, 1.0, 1.0);\n\t\n}\n\nvariant circle_primitive::get_value(const std::string& key) const\n{\n\treturn variant();\n}\n\nvoid circle_primitive::set_value(const std::string& key, const variant& value)\n{\n}\n\nclass arrow_primitive : public draw_primitive\n{\npublic:\n\texplicit arrow_primitive(const variant& v);\n\nprivate:\n\n\tvoid handle_draw() const;\n#ifdef USE_ISOMAP\n\tvoid handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const;\n#endif\n\n\tvariant get_value(const std::string& key) const;\n\tvoid set_value(const std::string& key, const variant& value);\n\n\tvoid set_points(const variant& points);\n\n\tvoid curve(const FPoint& p1, const FPoint& p2, const FPoint& p3, std::vector<FPoint>* out) const;\n\n\tstd::vector<FPoint> points_;\n\tGLfloat granularity_;\n\tint arrow_head_length_;\n\tGLfloat arrow_head_width_;\n\tgraphics::color color_;\n\tint fade_in_length_;\n\n\tGLfloat width_base_, width_head_;\n\n\tmutable std::vector<GLfloat> uvarray_;\n\tmutable std::vector<GLfloat> varray_;\n\tmutable std::vector<unsigned char> carray_;\n\n\ttexture texture_;\n\tGLfloat texture_scale_;\n\n\tvoid calculate_draw_arrays() const;\n};\n\narrow_primitive::arrow_primitive(const variant& v)\n  : draw_primitive(v),\n    granularity_(v[\"granularity\"].as_decimal(decimal(0.005)).as_float()),\n    arrow_head_length_(v[\"arrow_head_length\"].as_int(10)),\n    arrow_head_width_(v[\"arrow_head_width\"].as_decimal(decimal(2.0)).as_float()),\n\tfade_in_length_(v[\"fade_in_length\"].as_int(50)),\n\twidth_base_(v[\"width_base\"].as_decimal(decimal(12.0)).as_float()),\n\twidth_head_(v[\"width_head\"].as_decimal(decimal(5.0)).as_float())\n{\n\tif(v.has_key(\"texture\")) {\n\t\ttexture_ = texture::get(v[\"texture\"].as_string());\n\t\ttexture_scale_ = v[\"texture_scale\"].as_decimal(decimal(1.0)).as_float();\n\t}\n\n\tif(v.has_key(\"color\")) {\n\t\tcolor_ = color(v[\"color\"]);\n\t} else {\n\t\tcolor_ = color(200, 0, 0, 255);\n\t}\n\n\tset_points(v[\"points\"]);\n}\n\nvoid arrow_primitive::calculate_draw_arrays() const\n{\n\tif(!varray_.empty()) {\n\t\treturn;\n\t}\n\n\tstd::vector<FPoint> path;\n\n\tfor(int n = 1; n < points_.size()-1; ++n) {\n\t\tstd::vector<FPoint> new_path;\n\t\tcurve(points_[n-1], points_[n], points_[n+1], &new_path);\n\n\t\tif(path.empty()) {\n\t\t\tpath.swap(new_path);\n\t\t} else {\n\t\t\tassert(path.size() >= new_path.size());\n\t\t\tconst int overlap = path.size()/2;\n\t\t\tfor(int n = 0; n != overlap; ++n) {\n\t\t\t\tconst float ratio = float(n)/float(overlap);\n\t\t\t\tFPoint& value = path[(path.size() - overlap) + n];\n\t\t\t\tFPoint new_value = new_path[n];\n\t\t\t\tvalue[0] = value[0]*(1.0-ratio) + new_value[0]*ratio;\n\t\t\t\tvalue[1] = value[1]*(1.0-ratio) + new_value[1]*ratio;\n\t\t\t}\n\n\t\t\tpath.insert(path.end(), new_path.begin() + overlap, new_path.end());\n\t\t}\n\t}\n\n\tconst GLfloat PathLength = path.size()-1;\n\n\tstd::vector<FPoint> left_path, right_path;\n\tfor(int n = 0; n < path.size()-1; ++n) {\n\t\tconst FPoint& p = path[n];\n\t\tconst FPoint& next = path[n+1];\n\n\t\tFPoint direction;\n\t\tfor(int m = 0; m != 2; ++m) {\n\t\t\tdirection[m] = next[m] - p[m];\n\t\t}\n\n\t\tconst GLfloat vector_length = sqrt(direction[0]*direction[0] + direction[1]*direction[1]);\n\t\tif(vector_length == 0.0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tFPoint unit_direction;\n\t\tfor(int m = 0; m != 2; ++m) {\n\t\t\tunit_direction[m] = direction[m]/vector_length;\n\t\t}\n\t\t\n\t\tFPoint normal_direction_left, normal_direction_right;\n\t\tnormal_direction_left[0] = -unit_direction[1];\n\t\tnormal_direction_left[1] = unit_direction[0];\n\t\tnormal_direction_right[0] = unit_direction[1];\n\t\tnormal_direction_right[1] = -unit_direction[0];\n\n\t\tconst GLfloat ratio = n/PathLength;\n\n\t\tGLfloat arrow_width = width_base_ - (width_base_-width_head_)*ratio;\n\n\t\tconst int time_until_end = path.size()-2 - n;\n\t\tif(time_until_end < arrow_head_length_) {\n\t\t\tarrow_width = arrow_head_width_*time_until_end;\n\t\t}\n\n\t\tFPoint left, right;\n\t\tfor(int m = 0; m != 2; ++m) {\n\t\t\tleft[m] = p[m] + normal_direction_left[m]*arrow_width;\n\t\t\tright[m] = p[m] + normal_direction_right[m]*arrow_width;\n\t\t}\n\n\t\tleft_path.push_back(left);\n\t\tright_path.push_back(right);\n\t}\n\n\tfor(int n = 0; n != left_path.size(); ++n) {\n\t\tvarray_.push_back(left_path[n][0]);\n\t\tvarray_.push_back(left_path[n][1]);\n\t\tvarray_.push_back(right_path[n][0]);\n\t\tvarray_.push_back(right_path[n][1]);\n\n\t\tuvarray_.push_back(n*texture_scale_);\n\t\tuvarray_.push_back(0.0);\n\t\tuvarray_.push_back(n*texture_scale_);\n\t\tuvarray_.push_back(1.0);\n\n\t\tfor(int m = 0; m != 2; ++m) {\n\t\t\tcarray_.push_back(color_.r());\n\t\t\tcarray_.push_back(color_.g());\n\t\t\tcarray_.push_back(color_.b());\n\t\t\tif(n < fade_in_length_) {\n\t\t\t\tcarray_.push_back(int((GLfloat(color_.a())*GLfloat(n)*(255.0/GLfloat(fade_in_length_)))/255.0));\n\t\t\t} else {\n\t\t\t\tcarray_.push_back(color_.a());\n\t\t\t}\n\t\t}\n\t}\n}\n\n#ifdef USE_ISOMAP\nvoid arrow_primitive::handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const\n{\n}\n#endif\n\nvoid arrow_primitive::handle_draw() const\n{\n\tif(points_.size() < 3) {\n\t\treturn;\n\t}\n\n\tcalculate_draw_arrays();\n\n\tgles2::manager gles2_manager(texture_.valid() ? gles2::get_texcol_shader() : gles2::get_simple_col_shader());\n\n\tif(texture_.valid()) {\n\t\tglActiveTexture(GL_TEXTURE0);\n\t\ttexture_.set_as_current_texture();\n\t\tgles2::active_shader()->shader()->texture_array(2, GL_FLOAT, GL_FALSE, 0, &uvarray_[0]);\n\t}\n\n\tgles2::active_shader()->shader()->vertex_array(2, GL_FLOAT, GL_FALSE, 0, &varray_[0]);\n\tgles2::active_shader()->shader()->color_array(4, GL_UNSIGNED_BYTE, GL_TRUE, 0, &carray_[0]);\n\n\tglDrawArrays(GL_TRIANGLE_STRIP, 0, varray_.size()/2);\n}\n\nvariant arrow_primitive::get_value(const std::string& key) const\n{\n\tif(key == \"points\") {\n\t\tstd::vector<variant> result;\n\t\tforeach(const FPoint& p, points_) {\n\t\t\tstd::vector<variant> pos;\n\t\t\tpos.push_back(variant(static_cast<int>(p[0])));\n\t\t\tpos.push_back(variant(static_cast<int>(p[1])));\n\t\t\tresult.push_back(variant(&pos));\n\t\t}\n\n\t\treturn variant(&result);\n\t}\n\tASSERT_LOG(false, \"ILLEGAL KEY IN ARROW: \" << key);\n\treturn variant();\n}\n\nvoid arrow_primitive::set_value(const std::string& key, const variant& value)\n{\n\tif(key == \"points\") {\n\t\tset_points(value);\n\t} else if(key == \"color\") {\n\t\tcolor_ = graphics::color(value);\n\t} else if(key == \"granularity\") {\n\t\tgranularity_ = value.as_decimal().as_float();\n\t} else if(key == \"arrow_head_length\") {\n\t\tarrow_head_length_ = value.as_int();\n\t} else if(key == \"arrow_head_width\") {\n\t\tarrow_head_width_ = value.as_decimal().as_float();\n\t} else if(key == \"fade_in_length\") {\n\t\tfade_in_length_ = value.as_int();\n\t} else if(key == \"width_base\") {\n\t\twidth_base_ = value.as_decimal().as_float();\n\t} else if(key == \"width_head\") {\n\t\twidth_head_ = value.as_decimal().as_float();\n\t} else {\n\t\tASSERT_LOG(false, \"ILLEGAL KEY IN ARROW: \" << key);\n\t}\n\n\tvarray_.clear();\n\tcarray_.clear();\n}\n\nvoid arrow_primitive::set_points(const variant& points)\n{\n\tASSERT_LOG(points.is_list(), \"arrow points is not a list: \" << points.debug_location());\n\n\tpoints_.clear();\n\n\tfor(int n = 0; n != points.num_elements(); ++n) {\n\t\tvariant p = points[n];\n\t\tASSERT_LOG(p.is_list() && p.num_elements() == 2, \"arrow points in invalid format: \" << points.debug_location() << \" : \" << p.write_json());\n\t\tFPoint point;\n\t\tpoint[0] = p[0].as_int();\n\t\tpoint[1] = p[1].as_int();\n\t\tpoints_.push_back(point);\n\t}\n}\n\nvoid arrow_primitive::curve(const FPoint& p0, const FPoint& p1, const FPoint& p2, std::vector<FPoint>* out) const\n{\n\tfor(float t = 0.0; t < 1.0 - granularity_; t += granularity_) {\n\t\tFPoint p;\n\t\tfor(int n = 0; n != 2; ++n) {\n\t\t\t//formula for a bezier curve.\n\t\t\tp[n] = (1-t)*(1-t)*p0[n] + 2*(1-t)*t*p1[n] + t*t*p2[n];\n\t\t}\n\n\t\tout->push_back(p);\n\t}\n}\n\nclass wireframe_box_primitive : public draw_primitive\n{\npublic:\n\texplicit wireframe_box_primitive(const variant& v);\n\nprivate:\n\tDECLARE_CALLABLE(wireframe_box_primitive);\n\n\tvoid init();\n\n\tvoid handle_draw() const;\n#ifdef USE_ISOMAP\n\tvoid handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const;\n#endif\n\n\tglm::vec3 b1_;\n\tglm::vec3 b2_;\n\n\tgraphics::color color_;\n\n\tprogram_ptr shader_;\n\n\tstd::vector<GLfloat> varray_;\n\t\n\tGLuint u_mvp_matrix_;\n\tGLuint a_position_;\n\tGLuint u_color_;\n\n\tglm::vec3 translation_;\n\tglm::vec3 rotation_;\n\tglm::vec3 scale_;\n};\n\nwireframe_box_primitive::wireframe_box_primitive(const variant& v)\n\t: draw_primitive(v), scale_(glm::vec3(1.0f))\n{\n\tif(v.has_key(\"points\")) {\n\t\tASSERT_LOG(v[\"points\"].is_list() && v[\"points\"].num_elements() == 2, \"'points' must be a list of two elements.\");\n\t\tb1_ = variant_to_vec3(v[\"points\"][0]);\n\t\tb2_ = variant_to_vec3(v[\"points\"][1]);\n\t} else {\n\t\tASSERT_LOG(v.has_key(\"point1\") && v.has_key(\"point2\"), \"Must specify 'points' or 'point1' and 'point2' attributes.\");\n\t\tb1_ = variant_to_vec3(v[\"point1\"]);\n\t\tb2_ = variant_to_vec3(v[\"point2\"]);\n\t}\n\tif(v.has_key(\"color\")) {\n\t\tcolor_ = color(v[\"color\"]);\n\t} else {\n\t\tcolor_ = color(200, 0, 0, 255);\n\t}\n\tif(v.has_key(\"translation\")) {\n\t\ttranslation_ = variant_to_vec3(v[\"translation\"]);\n\t}\n\tif(v.has_key(\"scale\")) {\n\t\tscale_ = variant_to_vec3(v[\"scale\"]);\n\t}\n\n\tif(v.has_key(\"shader\")) {\n\t\tshader_ = shader_program::get_global(v[\"shader\"].as_string())->shader();\n\t} else {\n\t\tshader_ = shader_program::get_global(\"line_3d\")->shader();\n\t}\n\tu_mvp_matrix_ = shader_->get_fixed_uniform(\"mvp_matrix\");\n\tu_color_ = shader_->get_fixed_uniform(\"color\");\n\ta_position_ = shader_->get_fixed_attribute(\"vertex\");\n\tASSERT_LOG(u_mvp_matrix_ != -1, \"Error getting mvp_matrix uniform\");\n\tASSERT_LOG(u_color_ != -1, \"Error getting color uniform\");\n\tASSERT_LOG(a_position_ != -1, \"Error getting vertex attribute\");\n\n\tinit();\n}\n\nvoid wireframe_box_primitive::init()\n{\n\tif(b1_.x > b2_.x) {\n\t\tstd::swap(b1_.x, b2_.x);\n\t}\n\tif(b1_.y > b2_.y) {\n\t\tstd::swap(b1_.y, b2_.y);\n\t}\n\tif(b1_.z > b2_.z) {\n\t\tstd::swap(b1_.z, b2_.z);\n\t}\n\n\tvarray_.clear();\n\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z); varray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z); \n\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z); varray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z); \n\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z); varray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z); \n\n\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z); varray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z); \n\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z); varray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z); \n\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z); varray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z); \n\n\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z); varray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z); \n\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z); varray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z); \n\n\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z); varray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z); \n\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z); varray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z); \n\n\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z); varray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z); \n\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z); varray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z); \n}\n\nvoid wireframe_box_primitive::handle_draw() const\n{\n}\n\n#ifdef USE_ISOMAP\nvoid wireframe_box_primitive::handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const\n{\n\tshader_save_context save;\n\tglUseProgram(shader_->get());\n\n\tglm::mat4 model = glm::translate(glm::mat4(), translation_) \n\t\t* glm::translate(glm::mat4(), glm::vec3((b2_.x - b1_.x)/2.0f,(b2_.y - b1_.y)/2.0f,(b2_.z - b1_.z)/2.0f))\n\t\t* glm::scale(glm::mat4(), scale_)\n\t\t* glm::translate(glm::mat4(), glm::vec3((b1_.x - b2_.x)/2.0f,(b1_.y - b2_.y)/2.0f,(b1_.z - b2_.z)/2.0f));\n\tglm::mat4 mvp = camera->projection_mat() * camera->view_mat() * model;\n\tglUniformMatrix4fv(u_mvp_matrix_, 1, GL_FALSE, glm::value_ptr(mvp));\n\n\tglUniform4f(u_color_, color_.r()/255.0f, color_.g()/255.0f, color_.b()/255.0f, color_.a()/255.0f);\n\n\tglEnableVertexAttribArray(a_position_);\n\tglVertexAttribPointer(a_position_, 3, GL_FLOAT, GL_FALSE, 0, &varray_[0]);\n\tglDrawArrays(GL_LINES, 0, varray_.size()/3);\n\tglDisableVertexAttribArray(a_position_);\n}\n#endif\n\nBEGIN_DEFINE_CALLABLE(wireframe_box_primitive, draw_primitive)\n\tDEFINE_FIELD(color, \"[int,int,int,int]\")\n\t\treturn obj.color_.write();\n\tDEFINE_SET_FIELD_TYPE(\"[int,int,int,int]|string\")\n\t\tobj.color_ = graphics::color(value);\n\tDEFINE_FIELD(points, \"[[decimal,decimal,decimal],[decimal,decimal,decimal]]\")\n\t\tstd::vector<variant> v;\n\t\tv.push_back(vec3_to_variant(obj.b1_));\n\t\tv.push_back(vec3_to_variant(obj.b2_));\n\t\treturn variant(&v);\n\tDEFINE_SET_FIELD\n\t\tASSERT_LOG(value.is_list() && value.num_elements() == 2, \"'points' must be a list of two elements.\");\n\t\tobj.b1_ = variant_to_vec3(value[0]);\n\t\tobj.b2_ = variant_to_vec3(value[1]);\n\t\tobj.init();\n\tDEFINE_FIELD(point1, \"[decimal,decimal,decimal]\")\n\t\treturn vec3_to_variant(obj.b1_);\n\tDEFINE_SET_FIELD\n\t\tobj.b1_ = variant_to_vec3(value);\n\t\tobj.init();\n\tDEFINE_FIELD(point1, \"[decimal,decimal,decimal]\")\n\t\treturn vec3_to_variant(obj.b2_);\n\tDEFINE_SET_FIELD\n\t\tobj.b2_ = variant_to_vec3(value);\n\t\tobj.init();\n\tDEFINE_FIELD(translation, \"[decimal,decimal,decimal]\")\n\t\treturn vec3_to_variant(obj.translation_);\n\tDEFINE_SET_FIELD\n\t\tobj.translation_ = variant_to_vec3(value);\n\tDEFINE_FIELD(scale, \"[decimal,decimal,decimal]\")\n\t\treturn vec3_to_variant(obj.scale_);\n\tDEFINE_SET_FIELD\n\t\tobj.scale_ = variant_to_vec3(value);\nEND_DEFINE_CALLABLE(wireframe_box_primitive)\n\n}\n\nclass box_primitive : public draw_primitive\n{\npublic:\n\texplicit box_primitive(const variant& v)\n\t\t: draw_primitive(v), scale_(glm::vec3(1.0f))\n\t{\n\t\tif(v.has_key(\"points\")) {\n\t\t\tASSERT_LOG(v[\"points\"].is_list() && v[\"points\"].num_elements() == 2, \"'points' must be a list of two elements.\");\n\t\t\tb1_ = variant_to_vec3(v[\"points\"][0]);\n\t\t\tb2_ = variant_to_vec3(v[\"points\"][1]);\n\t\t} else {\n\t\t\tASSERT_LOG(v.has_key(\"point1\") && v.has_key(\"point2\"), \"Must specify 'points' or 'point1' and 'point2' attributes.\");\n\t\t\tb1_ = variant_to_vec3(v[\"point1\"]);\n\t\t\tb2_ = variant_to_vec3(v[\"point2\"]);\n\t\t}\n\t\tif(v.has_key(\"color\")) {\n\t\t\tcolor_ = color(v[\"color\"]);\n\t\t} else {\n\t\t\tcolor_ = color(200, 0, 0, 255);\n\t\t}\n\t\tif(v.has_key(\"translation\")) {\n\t\t\ttranslation_ = variant_to_vec3(v[\"translation\"]);\n\t\t}\n\t\tif(v.has_key(\"scale\")) {\n\t\t\tscale_ = variant_to_vec3(v[\"scale\"]);\n\t\t}\n\n\t\tif(v.has_key(\"shader\")) {\n\t\t\tshader_ = shader_program::get_global(v[\"shader\"].as_string())->shader();\n\t\t} else {\n\t\t\tshader_ = shader_program::get_global(\"line_3d\")->shader();\n\t\t}\n\t\tu_mvp_matrix_ = shader_->get_fixed_uniform(\"mvp_matrix\");\n\t\tu_color_ = shader_->get_fixed_uniform(\"color\");\n\t\ta_position_ = shader_->get_fixed_attribute(\"vertex\");\n\t\tASSERT_LOG(u_mvp_matrix_ != -1, \"Error getting mvp_matrix uniform\");\n\t\tASSERT_LOG(u_color_ != -1, \"Error getting color uniform\");\n\t\tASSERT_LOG(a_position_ != -1, \"Error getting vertex attribute\");\n\n\t\tinit();\n\t}\n\tvirtual ~box_primitive()\n\t{}\n\nprivate:\n\tDECLARE_CALLABLE(box_primitive);\n\n\tvoid init()\n\t{\n\t\tif(b1_.x > b2_.x) {\n\t\t\tstd::swap(b1_.x, b2_.x);\n\t\t}\n\t\tif(b1_.y > b2_.y) {\n\t\t\tstd::swap(b1_.y, b2_.y);\n\t\t}\n\t\tif(b1_.z > b2_.z) {\n\t\t\tstd::swap(b1_.z, b2_.z);\n\t\t}\n\n\t\tvarray_.clear();\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z);\n\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z);\n\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z);\n\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z);\n\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b2_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z);\n\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z);\n\n\t\tvarray_.push_back(b2_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b2_.z);\n\t\tvarray_.push_back(b1_.x); varray_.push_back(b1_.y); varray_.push_back(b1_.z);\n\t}\n\n\tvoid handle_draw() const\n\t{}\n\n#ifdef USE_ISOMAP\n\tvoid handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const\n\t{\n\t\tshader_save_context save;\n\t\tglUseProgram(shader_->get());\n\n\t\tglm::mat4 model = glm::translate(glm::mat4(), translation_) \n\t\t\t* glm::translate(glm::mat4(), glm::vec3((b2_.x - b1_.x)/2.0f,(b2_.y - b1_.y)/2.0f,(b2_.z - b1_.z)/2.0f))\n\t\t\t* glm::scale(glm::mat4(), scale_)\n\t\t\t* glm::translate(glm::mat4(), glm::vec3((b1_.x - b2_.x)/2.0f,(b1_.y - b2_.y)/2.0f,(b1_.z - b2_.z)/2.0f));\n\t\tglm::mat4 mvp = camera->projection_mat() * camera->view_mat() * model;\n\t\tglUniformMatrix4fv(u_mvp_matrix_, 1, GL_FALSE, glm::value_ptr(mvp));\n\n\t\tglUniform4f(u_color_, color_.r()/255.0f, color_.g()/255.0f, color_.b()/255.0f, color_.a()/255.0f);\n\n\t\tglEnableVertexAttribArray(a_position_);\n\t\tglVertexAttribPointer(a_position_, 3, GL_FLOAT, GL_FALSE, 0, &varray_[0]);\n\t\tglDrawArrays(GL_TRIANGLES, 0, varray_.size()/3);\n\t\tglDisableVertexAttribArray(a_position_);\n\t}\n#endif\n\n\tglm::vec3 b1_;\n\tglm::vec3 b2_;\n\n\tgraphics::color color_;\n\n\tprogram_ptr shader_;\n\n\tstd::vector<GLfloat> varray_;\n\t\n\tGLuint u_mvp_matrix_;\n\tGLuint a_position_;\n\tGLuint u_color_;\n\n\tglm::vec3 translation_;\n\tglm::vec3 rotation_;\n\tglm::vec3 scale_;\n\n\tbox_primitive();\n\tbox_primitive(const box_primitive&);\n};\n\nBEGIN_DEFINE_CALLABLE(box_primitive, draw_primitive)\n\tDEFINE_FIELD(color, \"[int,int,int,int]\")\n\t\treturn obj.color_.write();\n\tDEFINE_SET_FIELD_TYPE(\"[int,int,int,int]|string\")\n\t\tobj.color_ = graphics::color(value);\n\tDEFINE_FIELD(points, \"[[decimal,decimal,decimal],[decimal,decimal,decimal]]\")\n\t\tstd::vector<variant> v;\n\t\tv.push_back(vec3_to_variant(obj.b1_));\n\t\tv.push_back(vec3_to_variant(obj.b2_));\n\t\treturn variant(&v);\n\tDEFINE_SET_FIELD\n\t\tASSERT_LOG(value.is_list() && value.num_elements() == 2, \"'points' must be a list of two elements.\");\n\t\tobj.b1_ = variant_to_vec3(value[0]);\n\t\tobj.b2_ = variant_to_vec3(value[1]);\n\t\tobj.init();\n\tDEFINE_FIELD(point1, \"[decimal,decimal,decimal]\")\n\t\treturn vec3_to_variant(obj.b1_);\n\tDEFINE_SET_FIELD\n\t\tobj.b1_ = variant_to_vec3(value);\n\t\tobj.init();\n\tDEFINE_FIELD(point1, \"[decimal,decimal,decimal]\")\n\t\treturn vec3_to_variant(obj.b2_);\n\tDEFINE_SET_FIELD\n\t\tobj.b2_ = variant_to_vec3(value);\n\t\tobj.init();\n\tDEFINE_FIELD(translation, \"[decimal,decimal,decimal]\")\n\t\treturn vec3_to_variant(obj.translation_);\n\tDEFINE_SET_FIELD\n\t\tobj.translation_ = variant_to_vec3(value);\n\tDEFINE_FIELD(scale, \"[decimal,decimal,decimal]\")\n\t\treturn vec3_to_variant(obj.scale_);\n\tDEFINE_SET_FIELD\n\t\tobj.scale_ = variant_to_vec3(value);\nEND_DEFINE_CALLABLE(box_primitive)\n\n\nclass line_primitive : public draw_primitive\n{\npublic:\n    line_primitive(const variant& node);\n    ~line_primitive() {}\nvoid handle_draw() const;\n#ifdef USE_ISOMAP\nvoid handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const;\n#endif\nprivate:\n    DECLARE_CALLABLE(line_primitive);\n    void init();\n    shader_program_ptr shader_;\n    int x1_;\n    int y1_;\n    int x2_;\n    int y2_;\n    float width_;\n    graphics::color color1_;\n    graphics::color color2_;\n    graphics::color stroke_color_;\n    bool has_stroke_;\n    std::vector<glm::vec2> v1array_;\n    std::vector<glm::vec2> v2array_;\n    std::vector<glm::u8vec4> carray_;\n    line_primitive();\n    line_primitive(const line_primitive&);\n    line_primitive& operator=(const line_primitive&);\n};\n\nline_primitive::line_primitive(const variant& node)\n    : draw_primitive(node),\n      color1_(node[\"color1\"]),\n      color2_(node[\"color2\"]),\n      width_(1.0f),\n      has_stroke_(false)\n{\n    if(node.has_key(\"shader\")) {\n        shader_.reset(new shader_program(node[\"shader\"].as_string()));\n    } else {\n        shader_ = gles2::get_simple_col_shader();\n    }\n    if(node.has_key(\"p1\") && node.has_key(\"p2\")) {\n        point p1(node[\"p1\"]);\n        x1_ = p1.x;\n        y1_ = p1.y;\n        point p2(node[\"p2\"]);\n        x2_ = p2.x;\n        y2_ = p2.y;\n    } else if(node.has_key(\"area\")) {\n        rect r(node[\"area\"]);\n        x1_ = r.x();\n        y1_ = r.y();\n        x2_ = r.x2();\n        y2_ = r.y2();\n    } else if(node.has_key(\"x1\") && node.has_key(\"y1\") && node.has_key(\"x2\") && node.has_key(\"y2\")) {\n        x1_ = node[\"x1\"].as_int();\n        y1_ = node[\"y1\"].as_int();\n        x2_ = node[\"x2\"].as_int();\n        y2_ = node[\"y2\"].as_int();\n    } else {\n        ASSERT_LOG(false, \"Nothing containing points was found, either p1/p2, area or x1/y1/x2/y2 are required.\");\n    }\n    if(node.has_key(\"width\")) {\n        width_ = static_cast<float>(node[\"width\"].as_decimal().as_float());\n    }\n    if(node.has_key(\"stroke_color\")) {\n        has_stroke_ = true;\n        stroke_color_ = graphics::color(node[\"stroke_color\"]);\n    }\n    init();\n}\n\nvoid line_primitive::init()\n{\n    double theta = std::atan2(static_cast<double>(y2_-y1_),static_cast<double>(x2_-x1_));\n    double wx_half = width_/2.0 * std::sin(theta);\n    double wy_half = width_/2.0 * std::cos(theta);\n\n    v1array_.emplace_back(static_cast<float>(x1_ - wx_half), static_cast<float>(y1_ + wy_half));\n    v1array_.emplace_back(static_cast<float>(x2_ - wx_half), static_cast<float>(y2_ + wy_half));\n    v1array_.emplace_back(static_cast<float>(x1_), static_cast<float>(y1_));\n    v1array_.emplace_back(static_cast<float>(x2_), static_cast<float>(y2_));\n    v1array_.emplace_back(static_cast<float>(x1_ + wx_half), static_cast<float>(y1_ - wy_half));\n    v1array_.emplace_back(static_cast<float>(x2_ + wx_half), static_cast<float>(y2_ - wy_half));\n    carray_.emplace_back(color1_.r(), color1_.g(), color1_.b(), 0);\n    carray_.emplace_back(color2_.r(), color2_.g(), color2_.b(), 0);\n    carray_.emplace_back(color1_.r(), color1_.g(), color1_.b(), color1_.a());\n    carray_.emplace_back(color2_.r(), color2_.g(), color2_.b(), color2_.a());\n    carray_.emplace_back(color1_.r(), color1_.g(), color1_.b(), 0);\n    carray_.emplace_back(color2_.r(), color2_.g(), color2_.b(), 0);\n    v2array_.emplace_back(static_cast<float>(x1_ - wx_half), static_cast<float>(y1_ + wy_half));\n    v2array_.emplace_back(static_cast<float>(x2_ - wx_half), static_cast<float>(y2_ + wy_half));\n    v2array_.emplace_back(static_cast<float>(x2_ + wx_half), static_cast<float>(y2_ - wy_half));\n    v2array_.emplace_back(static_cast<float>(x1_ + wx_half), static_cast<float>(y1_ - wy_half));\n}\n\nvoid line_primitive::handle_draw() const\n{\n    gles2::manager gles2_manager(shader_);\n    gles2::active_shader()->prepare_draw();\n\n    gles2::active_shader()->shader()->vertex_array(2, GL_FLOAT, 0, 0, &v1array_.front());\n    gles2::active_shader()->shader()->color_array(4, GL_UNSIGNED_BYTE, GL_TRUE, 0, &carray_.front());\n    glDrawArrays(GL_TRIANGLE_STRIP, 0, v1array_.size());\n    if(has_stroke_) {\n        stroke_color_.set_as_current_color();\n        // hack\n        gles2::active_shader()->shader()->disable_vertex_attrib(-1);\n        gles2::active_shader()->shader()->vertex_array(2, GL_FLOAT, 0, 0, &v2array_.front());\n        glDrawArrays(GL_LINE_LOOP, 0, v2array_.size());\n        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);\n    }\n}\n\n#ifdef USE_ISOMAP\nvoid line_primitive::handle_draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const\n{\n}\n#endif\n\nBEGIN_DEFINE_CALLABLE(line_primitive, draw_primitive)\n    DEFINE_FIELD(color1, \"[int,int,int,int]\")\n        return obj.color1_.write();\n    DEFINE_SET_FIELD_TYPE(\"[int,int,int,int]|string\")\n        obj.color1_ = graphics::color(value);\n    DEFINE_FIELD(color2, \"[int,int,int,int]\")\n        return obj.color2_.write();\n    DEFINE_SET_FIELD_TYPE(\"[int,int,int,int]|string\")\n        obj.color2_ = graphics::color(value);\n    DEFINE_FIELD(p1, \"[int,int]\")\n        return point(obj.x1_, obj.y1_).write();\n    DEFINE_SET_FIELD\n        point p1(value);\n        obj.x1_ = p1.x;\n        obj.y1_ = p1.y;\n    DEFINE_FIELD(p2, \"[int,int]\")\n        return point(obj.x2_, obj.y2_).write();\n    DEFINE_SET_FIELD\n        point p2(value);\n        obj.x2_ = p2.x;\n        obj.y2_ = p2.y;\nEND_DEFINE_CALLABLE(line_primitive)\n\n\n\ndraw_primitive_ptr draw_primitive::create(const variant& v)\n{\n\tif(v.is_callable()) {\n\t\tdraw_primitive_ptr dp = v.try_convert<draw_primitive>();\n\t\tASSERT_LOG(dp != NULL, \"Couldn't convert callable type to draw_primitive\");\n\t\treturn dp;\n\t}\n\tconst std::string type = v[\"type\"].as_string();\n\tif(type == \"arrow\") {\n\t\treturn new arrow_primitive(v);\n\t} else if(type == \"circle\") {\n\t\treturn new circle_primitive(v);\n\t} else if(type == \"rect\") {\n\t\treturn new rect_primitive(v);\n    } else if(type == \"line\") {\n        return new line_primitive(v);\n\t} else if(type == \"box\") {\n\t\treturn new box_primitive(v);\n\t} else if(type == \"box_wireframe\") {\n\t\treturn new wireframe_box_primitive(v);\n\t}\n\n\tASSERT_LOG(false, \"UNKNOWN DRAW PRIMITIVE TYPE: \" << v[\"type\"].as_string());\n\treturn draw_primitive_ptr();\n}\n\ndraw_primitive::draw_primitive(const variant& v)\n  : src_factor_(GL_SRC_ALPHA), dst_factor_(GL_ONE_MINUS_SRC_ALPHA)\n{\n\tif(v.has_key(\"blend\")) {\n\t\tconst std::string blend_mode = v[\"blend\"].as_string();\n\t\tif(blend_mode == \"overwrite\") {\n\t\t\tsrc_factor_ = GL_ONE;\n\t\t\tdst_factor_ = GL_ZERO;\n\t\t} else {\n\t\t\tASSERT_LOG(false, \"Unrecognized blend mode: \" << blend_mode);\n\t\t}\n\t}\n}\n\nvoid draw_primitive::draw() const\n{\n\tif(src_factor_ != GL_SRC_ALPHA || dst_factor_ != GL_ONE_MINUS_SRC_ALPHA) {\n\t\tglBlendFunc(src_factor_, dst_factor_);\n\t\thandle_draw();\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t} else {\n\t\thandle_draw();\n\t}\n}\n\n#ifdef USE_ISOMAP\nvoid draw_primitive::draw(const lighting_ptr& lighting, const camera_callable_ptr& camera) const\n{\n\tif(src_factor_ != GL_SRC_ALPHA || dst_factor_ != GL_ONE_MINUS_SRC_ALPHA) {\n\t\tglBlendFunc(src_factor_, dst_factor_);\n\t\thandle_draw(lighting, camera);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t} else {\n\t\thandle_draw(lighting, camera);\n\t}\n}\n#endif\n\nBEGIN_DEFINE_CALLABLE_NOBASE(draw_primitive)\n\tDEFINE_FIELD(blend, \"string\")\n\t\tif(obj.src_factor_ == GL_ONE && obj.dst_factor_ == GL_ZERO) {\n\t\t\treturn variant(\"overwrite\");\n\t\t}\n\t\treturn variant(\"normal\");\n\tDEFINE_SET_FIELD\n\t\tif(value.as_string() == \"overwrite\") {\n\t\t\tobj.src_factor_ = GL_ONE;\n\t\t\tobj.dst_factor_ = GL_ZERO;\n\t\t} else if(value.as_string() == \"normal\") {\n\t\t\tobj.src_factor_ = GL_SRC_ALPHA;\n\t\t\tobj.dst_factor_ = GL_ONE_MINUS_SRC_ALPHA;\n\t\t} else {\n\t\t\tASSERT_LOG(false, \"Unrecognized blend mode: \" << value.as_string());\n\t\t}\nEND_DEFINE_CALLABLE(draw_primitive)\n\n}\n#endif\n", "meta": {"hexsha": "f7f8eacc331642d9dd36f41c3c53bac406a16f84", "size": 34359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/draw_primitive.cpp", "max_stars_repo_name": "sweetkristas/anura", "max_stars_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "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": "src/draw_primitive.cpp", "max_issues_repo_name": "sweetkristas/anura", "max_issues_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "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": "src/draw_primitive.cpp", "max_forks_repo_name": "sweetkristas/anura", "max_forks_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "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": 31.638121547, "max_line_length": 157, "alphanum_fraction": 0.6988852993, "num_tokens": 10369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.1986063452401358}}
{"text": "#include \"body_length_detector.hpp\"\n#include \"proxy/http/header.hpp\"\n#include \"proxy/util/misc_strings.hpp\"\n#include \"proxy/util/utils.hpp\"\n#include <boost/logic/tribool.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <vector>\n\nnamespace proxy {\nnamespace http_parser {\n\nconst unsigned long long MAX_LENGTH_BEFORE_LAST_DIGIT = (ULLONG_MAX - 9) / 10;\nconst std::string CHUNKED = \"chunked\";\n\n[[nodiscard]] boost::tuple<bool, http::body_length_representation,\n                           unsigned long long>\ndetect_body_length(http::header_container &headers) {\n  for (http::header_container::name_iterator transfer_encoding_it =\n           headers.find(\"transfer-encoding\");\n       transfer_encoding_it != headers.end(); transfer_encoding_it++) {\n    const http::header &h = *transfer_encoding_it;\n    if (h.value.length() >= CHUNKED.length()) {\n      if (h.value.compare(h.value.length() - CHUNKED.length(), CHUNKED.length(),\n                          CHUNKED) == 0) {\n        return boost::make_tuple(true,\n                                 http::body_length_representation::chunked,\n                                 0ULL /* ignored */);\n      }\n    }\n  }\n\n  http::header_container::name_iterator content_length_it =\n      headers.find(\"content-length\");\n  if (content_length_it != headers.end()) {\n    unsigned long long length = 0ULL;\n    const http::header &h = *content_length_it;\n    for (int i = 0; i < h.value.length(); i++) {\n      if (length <= MAX_LENGTH_BEFORE_LAST_DIGIT) {\n        int digit = util::misc_strings::digit_to_int_safe(h.value[i]);\n        if (digit > -1) {\n          length = length * 10 + digit;\n        } else {\n          return boost::make_tuple(\n              false, http::body_length_representation::none /* ignored */,\n              0ULL /* ignored */);\n        }\n      } else {\n        return boost::make_tuple(\n            false, http::body_length_representation::none /* ignored */,\n            0ULL /* ignored */);\n      }\n    }\n    return boost::make_tuple(\n        true, http::body_length_representation::content_length, length);\n  }\n\n  return boost::make_tuple(true, http::body_length_representation::none,\n                           0ULL /* ignored */);\n}\n\n} // namespace http_parser\n} // namespace proxy", "meta": {"hexsha": "94872c9cd57c23bbb137feeae8855a8106f2150d", "size": 2241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "proxy/http_parser/body_length_detector.cpp", "max_stars_repo_name": "plater-inc/proxy", "max_stars_repo_head_hexsha": "f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda", "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": "proxy/http_parser/body_length_detector.cpp", "max_issues_repo_name": "plater-inc/proxy", "max_issues_repo_head_hexsha": "f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proxy/http_parser/body_length_detector.cpp", "max_forks_repo_name": "plater-inc/proxy", "max_forks_repo_head_hexsha": "f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda", "max_forks_repo_licenses": ["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.1451612903, "max_line_length": 80, "alphanum_fraction": 0.6162427488, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19860634153415052}}
{"text": "/*****************************************************************************\n* Short Title: class Molecule - declaration\n*\n* Comments:\n*\n* <license text>\n*****************************************************************************/\n\n#ifndef MOLECULE_HPP_INCLUDED\n#define MOLECULE_HPP_INCLUDED\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <valarray>\n#include <list>\n#include <set>\n#include <boost/shared_ptr.hpp>\n#include \"Atom_t.hpp\"\n#include \"DistanceTable.hpp\"\n#include \"Matrix.hpp\"\n#include \"Random.hpp\"\n#include \"TraceId_t.hpp\"\n#include \"EmbedPython.hpp\"\n#include \"ChemicalFormula.hpp\"\n#include \"AtomRadiiTable.hpp\"\n\nclass AtomFilter_t;\nclass AtomCost;\nclass AtomOverlap;\nusing NS_LIGA::RandomWeighedGenerator;\n\nenum StructureType { MOLECULE, CRYSTAL };\n\nclass Molecule\n{\n    public:\n\n        // friends\n        friend class AtomSequence;\n        friend class AtomCost;\n        friend bool operator==(const Molecule&, const Molecule&);\n        friend class BondAngleFilter_t;\n        friend class LoneAtomFilter_t;\n\n        // class data\n        // fit parameters\n        static double tol_nbad; // tolerance of normalized badness\n        static double tol_r;    // position tolerance in RelaxAtom\n        static bool promotejump;\n        static bool promoterelax;\n        static bool demoterelax;\n        static double promotefrac;\n        static std::vector<AtomFilter_t*> atom_filters;\n\n        // class methods\n        static void setOutputFormat(const std::string& format);\n\n        // data\n        // unique identifier\n        const long id;\n        std::list<TraceId_t> trace;\n\n        // constructors\n        Molecule();\n        Molecule(const Molecule& M);\n\n        // destructor\n        virtual ~Molecule()  { }\n\n        // operators\n        virtual Molecule& operator=(const Molecule&);\n        virtual Molecule* copy() const;     // create a copy\n\n        // methods - class registration and type info\n        virtual StructureType type() const  { return MOLECULE; }\n        virtual std::string typeStr() const { return \"molecule\"; }\n\n        // methods - molecule configuration\n        virtual void setDistanceTable(const DistanceTable&);\n        void setDistanceTable(const std::vector<double>&);\n        const DistanceTable& getDistanceTable() const;\n        DistanceTable getDistanceTable();\n\n        virtual void setDistReuse(bool);\n        bool getDistReuse() const;\n\n        double getMaxAtomRadius() const;\n\n        // methods - fitness/badness evaluation\n        virtual double cost() const;    // total normalized cost\n        double costDistance() const;    // normalized distance cost\n        double costOverlap() const;     // normalized atom overlap\n        const double& Badness() const;  // total badness\n        void IncBadness(const double& db) const;\n        void DecBadness(const double& db) const;\n        void ResetBadness(double b=0.0) const;\n        const double& Overlap() const;  // total badness\n        void IncOverlap(const double& doverlap) const;\n        void DecOverlap(const double& doverlap) const;\n        void ResetOverlap(double overlap=0.0) const;\n        bool full() const;\n        int countAtoms() const;\n        virtual int countPairs() const;\n        double pairsPerAtom() const;\n        double pairsPerAtomInc() const;\n        int getMaxAtomCount() const;\n        void setChemicalFormula(const std::string&);\n        void setChemicalFormula(const ChemicalFormula& formula);\n        ChemicalFormula getChemicalFormula() const;\n        void setAtomRadiiTable(const std::string&);\n        void setAtomRadiiTable(const AtomRadiiTable& radiitable);\n        const AtomRadiiTable& getAtomRadiiTable() const;\n        void setSamePairRadius(double);\n        const double& getSamePairRadius() const;\n        void reassignPairs();       // improve assignment of distances\n        virtual void recalculate() const;   // recalculate everything\n        virtual AtomCost* getAtomCostCalculator() const;\n        virtual AtomCost* getAtomOverlapCalculator() const;\n        void setAtomCostScale(double sc);\n        void setAtomOverlapScale(double sc);\n\n        // methods - molecule operations\n        virtual void Shift(const R3::Vector& drc);  // cartesian shift\n        void Center();    // center w/r to the center of mass\n\n        // atom operations\n        const Atom_t& getAtom(const int cidx) const  { return *atoms[cidx]; }\n        virtual AtomPtr getNearestAtom(const R3::Vector& rc) const;\n        void Pop(const int cidx);\n        void Pop(const std::list<int>& cidx);\n        virtual void Clear();           // remove all atoms\n        void AddAt(const std::string& smbl, double rx0, double ry0, double rz0);\n        void AddAt(const std::string& smbl, const R3::Vector& rc);\n        void Add(const Atom_t& a);      // add single external atom\n        void Fix(const int cidx);       // mark atom as fixed\n        int NFixed() const;             // count fixed atoms\n        void RelaxAtom(const int cidx); // relax internal atom\n        void RelaxExternalAtom(Atom_t* pa);\n        virtual const std::pair<int*,int*>& Evolve(const int* est_triang);\n        enum DegenerateFlags { NONE=0, FAST=1 };\n        virtual void Degenerate(int Npop, DegenerateFlags=NONE);\n        double getContactRadius(const Atom_t& a0, const Atom_t& a1) const;\n        void FlipSites(int idx0, int idx1);\n        void DownhillOverlapMinimization();\n        void MinimizeSiteOverlap(int idx);\n        std::string PickElementFromBucket() const;\n\n        // IO functions\n        boost::python::object convertToDiffPyStructure() const;\n        virtual void setFromDiffPyStructure(boost::python::object);\n        void ReadFile(const std::string&);  // read from existing file\n        void WriteFile(const std::string&, std::string title=\"\");\n        void WriteStream(std::ostream&, std::string title=\"\") const;\n        void PrintBadness() const;      // total and per-atomic badness\n        void PrintFitness();            // total and per-atomic fitness\n        void CheckIntegrity() const;\n        R3::Vector rxaCheckGradient(const Atom_t* pa) const;\n        double rxaCheckCost(const Atom_t* pa) const;\n\n\n    protected:\n\n        // types\n        typedef std::vector<Atom_t> AtomArray;\n        struct TriangulationAnchor\n        {\n            R3::Vector B0;\n            R3::Vector B1;\n            R3::Vector B2;\n            int count;\n        };\n\n        // class data\n        static std::string output_format;\n\n        // data\n        boost::shared_ptr<DistanceTable> _distance_table;\n        boost::shared_ptr<AtomRadiiTable> _atom_radii_table;\n        std::vector<Atom_t*> atoms;         // atoms in the Molecule\n        std::vector<Atom_t*> atoms_bucket;  // available free atoms\n        std::list<Atom_t> atoms_storage;    // all atom instances\n        mutable SymmetricMatrix<double> pmx_partial_costs;\n        mutable SymmetricMatrix<double> pmx_used_distances;\n        mutable std::set<int> free_pmx_slots;\n        mutable double _badness;        // molecular badness\n        mutable double _overlap;        // total atom overlap\n\n        // methods\n        void AddInternalAt(Atom_t* pa, double rx0, double ry0, double rz0);\n        void AddInternalAt(Atom_t* pa, const R3::Vector& rc);\n        virtual void AddInternal(Atom_t* pa);   // add atom from the storage\n        virtual void addNewAtomPairs(Atom_t* pa);\n        virtual void removeAtomPairs(Atom_t* pa);\n        Atom_t* pickAtomFromBucket() const;\n        int push_good_distances(AtomArray& vta,\n                const RandomWeighedGenerator& rwg, int ntrials);\n        int push_good_triangles(AtomArray& vta,\n                const RandomWeighedGenerator& rwg, int ntrials);\n        int push_good_pyramids(AtomArray& vta,\n                const RandomWeighedGenerator& rwg, int ntrials);\n        virtual const TriangulationAnchor&\n            getLineAnchor(const RandomWeighedGenerator& rwg);\n        virtual const TriangulationAnchor&\n            getPlaneAnchor(const RandomWeighedGenerator& rwg);\n        virtual const TriangulationAnchor&\n            getPyramidAnchor(const RandomWeighedGenerator& rwg);\n        void filter_good_atoms(AtomArray& vta,\n                double evolve_range, double hi_abad);\n        void filter_bucket_atoms(AtomArray& vta);\n        bool check_atom_filters(Atom_t*);\n        virtual void resizePairMatrices(int sz);\n        virtual boost::python::object newDiffPyStructure() const;\n        void recalculateOverlap() const;\n        enum AddRemove { ADD = 1, REMOVE = -1 };\n        void applyOverlapContributions(Atom_t* pa, AddRemove sign);\n        void fetchAtomRadii();\n        void checkAtomIndex(int idx);\n\n    private:\n\n        // class methods\n        static long getUniqueId();\n\n        // data\n        bool _distreuse;\n        double _samepairradius;\n\n        // methods\n        // constructor helper\n        void init();\n        int getPairMatrixIndex();\n        void returnUsedDistances();\n        void rxaCheckEval(const Atom_t*, double*, R3::Vector*) const;\n};\n\n// non-member operators\nbool operator==(const Molecule& m1, const Molecule& m2);\nstd::ostream& operator<<(std::ostream& os, const Molecule& M);\n\n#endif  // MOLECULE_HPP_INCLUDED\n", "meta": {"hexsha": "19b63d28dca865f76a2fb8c0ac8d4fb07130ada0", "size": 9204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Molecule.hpp", "max_stars_repo_name": "pavoljuhas/liga", "max_stars_repo_head_hexsha": "53896275e9df0a916ba6219b407ce3777ce7ba2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-02T18:56:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T18:56:27.000Z", "max_issues_repo_path": "src/Molecule.hpp", "max_issues_repo_name": "pavoljuhas/liga", "max_issues_repo_head_hexsha": "53896275e9df0a916ba6219b407ce3777ce7ba2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-01T18:08:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T18:28:19.000Z", "max_forks_repo_path": "src/Molecule.hpp", "max_forks_repo_name": "pavoljuhas/liga", "max_forks_repo_head_hexsha": "53896275e9df0a916ba6219b407ce3777ce7ba2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-24T00:30:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T01:13:42.000Z", "avg_line_length": 38.0330578512, "max_line_length": 80, "alphanum_fraction": 0.6358105172, "num_tokens": 2080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.19860634153415047}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2010 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iostream>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <vw/Core/Cache.h>\n#include <vw/Core/ProgressCallback.h>\n#include <vw/Math/Matrix.h>\n#include <vw/Image/Palette.h>\n#include <vw/Image/Transform.h>\n#include <vw/FileIO/DiskImageResource.h>\n#include <vw/FileIO/DiskImageResourceGDAL.h>\n#include <vw/FileIO/DiskImageView.h>\n#include <vw/Cartography/GeoReference.h>\n\nusing namespace vw;\nusing namespace vw::math;\nusing namespace vw::cartography;\n\nint main( int argc, char *argv[] ) {\n\n  std::string input_filename, output_filename, copy_filename, tfw_filename;\n  double north_lat=90.0, south_lat=-90.0;\n  double east_lon=180.0, west_lon=-180.0;\n  double proj_lat=0, proj_lon=0, proj_scale=1;\n  unsigned utm_zone;\n  double nudge_x=0, nudge_y=0;\n\n  po::options_description general_options(\"General Options\");\n  general_options.add_options()\n    (\"output-file,o\", po::value<std::string>(&output_filename)->default_value(\"output.tif\"), \"Specify the base output filename\")\n    (\"help,h\", \"Display this help message\");\n\n  po::options_description projection_options(\"Projection Options\");\n  projection_options.add_options()\n    (\"copy\", po::value<std::string>(&copy_filename), \"Copy the projection from the given file\")\n    (\"tfw\", po::value<std::string>(&tfw_filename), \"Create a .tfw sidecar file with the given filename rather than a full copy of the image file\")\n    (\"north\", po::value<double>(&north_lat), \"The northernmost latitude in degrees\")\n    (\"south\", po::value<double>(&south_lat), \"The southernmost latitude in degrees\")\n    (\"east\", po::value<double>(&east_lon), \"The easternmost longitude in degrees\")\n    (\"west\", po::value<double>(&west_lon), \"The westernmost longitude in degrees\")\n    (\"sinusoidal\", \"Assume a sinusoidal projection\")\n    (\"mercator\", \"Assume a Mercator projection\")\n    (\"transverse-mercator\", \"Assume a transverse Mercator projection\")\n    (\"orthographic\", \"Assume an orthographic projection\")\n    (\"stereographic\", \"Assume a stereographic projection\")\n    (\"lambert-azimuthal\", \"Assume a Lambert azimuthal projection\")\n    (\"utm\", po::value<unsigned>(&utm_zone), \"Assume UTM projection with the given zone\")\n    (\"proj-lat\", po::value<double>(&proj_lat), \"The center of projection latitude (if applicable)\")\n    (\"proj-lon\", po::value<double>(&proj_lon), \"The center of projection longitude (if applicable)\")\n    (\"proj-scale\", po::value<double>(&proj_scale), \"The projection scale (if applicable)\")\n    (\"nudge-x\", po::value<double>(&nudge_x), \"Nudge the image, in projected coordinates\")\n    (\"nudge-y\", po::value<double>(&nudge_y), \"Nudge the image, in projected coordinates\")\n    (\"pixel-as-point\", \"Encode that the pixel location (0,0) is the center of the upper left hand pixel (the default, if you specify nothing, is to set the upper left hand corner of the upper left pixel as (0,0) (i.e. PixelAsArea).\");\n\n  po::options_description hidden_options(\"\");\n  hidden_options.add_options()\n    (\"input-file\", po::value<std::string>(&input_filename));\n\n  po::options_description options(\"Allowed Options\");\n  options.add(general_options).add(projection_options).add(hidden_options);\n\n  po::positional_options_description p;\n  p.add(\"input-file\", -1);\n\n  std::ostringstream usage;\n  usage << \"Description: Specify planetary coordinates for an image\" << std::endl << std::endl;\n  usage << \"Usage: \" << argv[0] << \" [options] <filename>...\" << std::endl << std::endl;\n  usage << general_options << std::endl;\n  usage << projection_options << std::endl;\n\n  po::variables_map vm;\n  try {\n    po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );\n    po::notify( vm );\n  } catch(po::error &e) {\n    std::cout << \"An error occured while parsing command line arguments.\\n\";\n    std::cout << \"\\t\" << e.what() << \"\\n\\n\";\n    std::cout << usage.str();\n    return 1;\n  }\n\n  if( vm.count(\"help\") ) {\n    std::cout << usage.str();\n    return 1;\n  }\n\n  if( vm.count(\"input-file\") < 1 ) {\n    std::cout << \"Error: Must specify at least one input file!\" << std::endl << std::endl;\n    std::cout << usage.str();\n    return 1;\n  }\n\n  GeoReference output_georef;\n  output_georef.set_well_known_geogcs(\"WGS84\");\n\n  // Read in georeference info and compute total resolution\n  bool manual = vm.count(\"north\") || vm.count(\"south\") || vm.count(\"east\") || vm.count(\"west\");\n\n  DiskImageResourceGDAL file_resource( input_filename );\n  GeoReference georef;\n  if( vm.count(\"copy\") ) {\n    read_georeference( georef, copy_filename );\n  } else {\n    read_georeference( georef, file_resource );\n  }\n\n  if ( georef.proj4_str() == \"\" ) georef.set_well_known_geogcs(\"WGS84\");\n  if( manual || georef.transform() == identity_matrix<3>() ) {\n    if( manual ) {\n      vw_out() << \"Using manual Plate Carree coordinates: \";\n      georef = GeoReference(georef.datum());\n    } else {\n      vw_out() << \"No georeferencing info found.  Assuming Plate Carree WGS84: \";\n      georef = GeoReference();\n      georef.set_well_known_geogcs(\"WGS84\");\n    }\n    vw_out() << east_lon << \" E to \" << west_lon << \" W, \"\n             << south_lat << \" S to \" << north_lat << \" N.\" << std::endl;\n\n    Matrix3x3 m;\n    m(0,0) = (east_lon - west_lon) / file_resource.cols();\n    m(0,2) = west_lon;\n    m(1,1) = (south_lat - north_lat) / file_resource.rows();\n    m(1,2) = north_lat;\n    m(2,2) = 1;\n    georef.set_transform( m );\n    manual = true;\n  }\n  else if( vm.count(\"sinusoidal\") ) georef.set_sinusoidal(proj_lon);\n  else if( vm.count(\"mercator\") ) georef.set_mercator(proj_lat,proj_lon,proj_scale);\n  else if( vm.count(\"transverse-mercator\") ) georef.set_transverse_mercator(proj_lat,proj_lon,proj_scale);\n  else if( vm.count(\"orthographic\") ) georef.set_orthographic(proj_lat,proj_lon);\n  else if( vm.count(\"stereographic\") ) georef.set_stereographic(proj_lat,proj_lon,proj_scale);\n  else if( vm.count(\"lambert-azimuthal\") ) georef.set_lambert_azimuthal(proj_lat,proj_lon);\n  else if( vm.count(\"utm\") ) georef.set_UTM( utm_zone );\n\n  if (vm.count(\"pixel-as-point\"))\n    georef.set_pixel_interpretation(GeoReference::PixelAsPoint);\n  else // Default: PixelAsArea\n    georef.set_pixel_interpretation(GeoReference::PixelAsArea);\n\n  if( vm.count(\"nudge-x\") || vm.count(\"nudge-y\") ) {\n    Matrix3x3 m = georef.transform();\n    m(0,2) += nudge_x;\n    m(1,2) += nudge_y;\n    georef.set_transform( m );\n  }\n\n  vw_out() << \"Writing file with Proj4 String: \" << georef.proj4_str() << \"\\n\";\n\n  // Our file readers do a better job that GDAL's of coping with large\n  // image files in some cases, so we make a fresh DiskImageView rather\n  // than making an ImageResourceView of the existing GDAL resource.\n\n  if (vm.count(\"tfw\")) {\n    std::ofstream tfw_file(tfw_filename.c_str());\n    tfw_file << georef.transform()(0,0) << \"\\n\";\n    tfw_file << georef.transform()(0,1) << \"\\n\";\n    tfw_file << georef.transform()(1,0) << \"\\n\";\n    tfw_file << georef.transform()(1,1) << \"\\n\";\n    if (vm.count(\"pixel-as-point\")) {\n      tfw_file << georef.transform()(0,2) << \"\\n\";\n      tfw_file << georef.transform()(1,2) << \"\\n\";\n    } else {\n      tfw_file << georef.transform()(0,2) + 0.5*georef.transform()(0,0) << \"\\n\";\n      tfw_file << georef.transform()(1,2) + 0.5*georef.transform()(1,1) << \"\\n\";\n    }\n    tfw_file.close();\n  } else {\n    TerminalProgressCallback bar( \"tools.georef\", \"Writing:\" );\n    switch( file_resource.channel_type() ) {\n    case VW_CHANNEL_INT16:\n      switch( file_resource.pixel_format() ) {\n      case VW_PIXEL_SCALAR: {\n        DiskImageView<int16> input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_GRAY: {\n        DiskImageView<PixelGray<int16> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_GRAYA: {\n        DiskImageView<PixelGrayA<int16> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_RGB: {\n        DiskImageView<PixelRGB<int16> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_RGBA: {\n        DiskImageView<PixelRGBA<int16> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      default: {\n        vw_throw( NoImplErr() << \"Unsupported pixel format: \" << file_resource.pixel_format() );\n        break;\n      }\n      }\n      break;\n    case VW_CHANNEL_UINT16:\n      switch( file_resource.pixel_format() ) {\n      case VW_PIXEL_SCALAR: {\n        DiskImageView<uint16> input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_GRAY: {\n        DiskImageView<PixelGray<uint16> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_GRAYA: {\n        DiskImageView<PixelGrayA<uint16> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_RGB: {\n        DiskImageView<PixelRGB<uint16> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_RGBA: {\n        DiskImageView<PixelRGBA<uint16> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      default: {\n        vw_throw( NoImplErr() << \"Unsupported pixel format: \" << file_resource.pixel_format() );\n        break;\n      }\n      }\n      break;\n    case VW_CHANNEL_FLOAT32:\n      switch( file_resource.pixel_format() ) {\n      case VW_PIXEL_SCALAR: {\n        DiskImageView<float32> input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_GRAY: {\n        DiskImageView<PixelGray<float32> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_GRAYA: {\n        DiskImageView<PixelGrayA<float32> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_RGB: {\n        DiskImageView<PixelRGB<float32> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_RGBA: {\n        DiskImageView<PixelRGBA<float32> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      default: {\n        vw_throw( NoImplErr() << \"Unsupported pixel format: \" << file_resource.pixel_format() );\n        break;\n      }\n      }\n      break;\n    default:\n      switch( file_resource.pixel_format() ) {\n      case VW_PIXEL_SCALAR: {\n        DiskImageView<uint8> input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_GRAY: {\n        DiskImageView<PixelGray<uint8> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_GRAYA: {\n        DiskImageView<PixelGrayA<uint8> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_RGB: {\n        DiskImageView<PixelRGB<uint8> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      case VW_PIXEL_RGBA: {\n        DiskImageView<PixelRGBA<uint8> > input_image( input_filename );\n        write_georeferenced_image( output_filename, input_image, georef, bar );\n        break;\n      }\n      default: {\n        vw_throw( NoImplErr() << \"Unsupported pixel format: \" << file_resource.pixel_format() );\n        break;\n      }\n      }\n      break;\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "eebffe671de276de080ddf53f2bcd0679e7bfd31", "size": 12763, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/tools/georef.cc", "max_stars_repo_name": "tkeemon/visionworkbench", "max_stars_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T04:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T04:06:43.000Z", "max_issues_repo_path": "src/vw/tools/georef.cc", "max_issues_repo_name": "tkeemon/visionworkbench", "max_issues_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_issues_repo_licenses": ["NASA-1.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": "src/vw/tools/georef.cc", "max_forks_repo_name": "tkeemon/visionworkbench", "max_forks_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2707692308, "max_line_length": 234, "alphanum_fraction": 0.663010264, "num_tokens": 3303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.19860634153415047}}
{"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_PPC_VMX_SIMD_FUNCTION_ROL_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_PPC_VMX_SIMD_FUNCTION_ROL_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/detail/assert_utils.hpp>\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/detail/dispatch/meta/as_unsigned.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD( rol_\n                          , (typename A0)\n                          , bs::vmx_\n                          , bs::pack_< bd::unsigned_<A0>, bs::vmx_>\n                          , bs::pack_< bd::unsigned_<A0>, bs::vmx_>\n                          )\n   {\n     BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const\n      {\n        BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"rol : rotation is out of range\");\n        return vec_rl(a0.storage(), a1.storage());\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "781776a03e3fea62bf24bde9e32423e404681b75", "size": 1359, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/ppc/vmx/simd/function/rol.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/ppc/vmx/simd/function/rol.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/ppc/vmx/simd/function/rol.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": 33.975, "max_line_length": 100, "alphanum_fraction": 0.5430463576, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19860633967165775}}
{"text": "//\n// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)\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// Official repository: https://github.com/boostorg/beast\n//\n\n#ifndef BOOST_BEAST_WEBSOCKET_DETAIL_PRNG_IPP\n#define BOOST_BEAST_WEBSOCKET_DETAIL_PRNG_IPP\n\n#include <boost/beast/websocket/detail/prng.hpp>\n#include <boost/beast/core/detail/chacha.hpp>\n#include <boost/beast/core/detail/pcg.hpp>\n#include <atomic>\n#include <cstdlib>\n#include <mutex>\n#include <random>\n\nnamespace boost {\nnamespace beast {\nnamespace websocket {\nnamespace detail {\n\n//------------------------------------------------------------------------------\n\nstd::uint32_t const*\nprng_seed(std::seed_seq* ss)\n{\n    struct data\n    {\n        std::uint32_t v[8];\n\n        explicit\n        data(std::seed_seq* pss)\n        {\n            if(! pss)\n            {\n                std::random_device g;\n                std::seed_seq ss{\n                    g(), g(), g(), g(),\n                    g(), g(), g(), g()};\n                ss.generate(v, v+8);\n            }\n            else\n            {\n                pss->generate(v, v+8);\n            }\n        }\n    };\n    static data const d(ss);\n    return d.v;\n}\n\n//------------------------------------------------------------------------------\n\ninline\nstd::uint32_t\nmake_nonce()\n{\n    static std::atomic<std::uint32_t> nonce{0};\n    return ++nonce;\n}\n\ninline\nbeast::detail::pcg make_pcg()\n{\n    auto const pv = prng_seed();\n    return beast::detail::pcg{\n        ((static_cast<std::uint64_t>(pv[0])<<32)+pv[1]) ^\n        ((static_cast<std::uint64_t>(pv[2])<<32)+pv[3]) ^\n        ((static_cast<std::uint64_t>(pv[4])<<32)+pv[5]) ^\n        ((static_cast<std::uint64_t>(pv[6])<<32)+pv[7]), make_nonce()};\n}\n\n#ifdef BOOST_NO_CXX11_THREAD_LOCAL\n\ninline\nstd::uint32_t\nsecure_generate()\n{\n    struct generator\n    {\n        std::uint32_t operator()()\n        {\n            std::lock_guard<std::mutex> guard{mtx};\n            return gen();\n        }\n\n        beast::detail::chacha<20> gen;\n        std::mutex mtx;\n    };\n    static generator gen{beast::detail::chacha<20>{prng_seed(), make_nonce()}};\n    return gen();\n}\n\ninline\nstd::uint32_t\nfast_generate()\n{\n    struct generator\n    {\n        std::uint32_t operator()()\n        {\n            std::lock_guard<std::mutex> guard{mtx};\n            return gen();\n        }\n\n        beast::detail::pcg gen;\n        std::mutex mtx;\n    };\n    static generator gen{make_pcg()};\n    return gen();\n}\n\n#else\n\ninline\nstd::uint32_t\nsecure_generate()\n{\n    thread_local static beast::detail::chacha<20> gen{prng_seed(), make_nonce()};\n    return gen();\n}\n\ninline\nstd::uint32_t\nfast_generate()\n{\n    thread_local static beast::detail::pcg gen{make_pcg()};\n    return gen();\n}\n\n#endif\n\ngenerator\nmake_prng(bool secure)\n{\n    if (secure)\n        return &secure_generate;\n    else\n        return &fast_generate;\n}\n\n} // detail\n} // websocket\n} // beast\n} // boost\n\n#endif\n", "meta": {"hexsha": "2d4e7f2771d5b590b5b6687b587340b21dd3241c", "size": 3051, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/beast/websocket/detail/prng.ipp", "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/beast/websocket/detail/prng.ipp", "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/beast/websocket/detail/prng.ipp", "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": 20.0723684211, "max_line_length": 81, "alphanum_fraction": 0.5509668961, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.19856297042605522}}
{"text": "#include <ros/ros.h>\n#include <message_filters/subscriber.h>\n#include <geometry_msgs/PointStamped.h>\n#include <moveit/robot_state/robot_state.h>\n#include <moveit/robot_model/robot_model.h>\n#include <humanoid_catching/IKMetric.h>\n#include <moveit/robot_model_loader/robot_model_loader.h>\n#include <tf/transform_listener.h>\n#include <pluginlib/class_loader.h>\n#include <boost/random.hpp>\n\nusing namespace std;\n\nclass IKTester {\nprivate:\n    ros::NodeHandle nh;\n    ros::NodeHandle pnh;\n\n    auto_ptr<message_filters::Subscriber<geometry_msgs::PointStamped> > trialGoalSub;\n    kinematics::KinematicsBasePtr kinematicsSolver;\n    ros::Publisher ikMetricsPub;\n\n    string endEffector;\n    string arm;\n    string commandTopic;\n\n    robot_model::JointModelGroup* jointModelGroup;\n    robot_state::RobotStatePtr kinematicState;\n    boost::shared_ptr<pluginlib::ClassLoader<kinematics::KinematicsBase> > kinematicsLoader;\n\n    //! rng\n    boost::mt19937 rng;\npublic:\n    IKTester() :\n            pnh(\"~\")\n        {\n\n        if (!pnh.getParam(\"end_effector\", endEffector))\n        {\n            ROS_ERROR(\"End effector name must be specified\");\n        }\n        else {\n            ROS_INFO(\"Configuring for end effector: [%s]\", endEffector.c_str());\n        }\n\n        if (!pnh.getParam(\"arm\", arm))\n        {\n            ROS_ERROR(\"Arm name must be specified\");\n        }\n        else {\n            ROS_INFO(\"Configuring for arm: [%s]\", arm.c_str());\n        }\n\n        if (!pnh.getParam(\"command_topic\", commandTopic))\n        {\n            ROS_ERROR(\"Command topic must be specified\");\n        }\n        else {\n            ROS_INFO(\"Subscribing to topic: [%s]\", commandTopic.c_str());\n        }\n\n        // Setup the subscriber\n        trialGoalSub.reset(\n                new message_filters::Subscriber<geometry_msgs::PointStamped>(nh,\n                        commandTopic, 100000));\n        trialGoalSub->registerCallback(boost::bind(&IKTester::goalCallback, this, _1));\n\n        // Setup the publisher\n        ikMetricsPub = nh.advertise<humanoid_catching::IKMetric>(\"ik_metric\", 100000, true);\n\n        robot_model_loader::RobotModelLoader robotModelLoader(\"robot_description\");\n        robot_model::RobotModelPtr kinematicModel = robotModelLoader.getModel();\n\n        kinematicState.reset(new robot_state::RobotState(kinematicModel));\n        kinematicState->setToDefaultValues();\n        jointModelGroup = kinematicModel->getJointModelGroup(arm);\n\n        kinematicsLoader.reset(new pluginlib::ClassLoader<kinematics::KinematicsBase>(\"moveit_core\", \"kinematics::KinematicsBase\"));\n        try {\n            kinematicsSolver = kinematicsLoader->createInstance(\"pr2_arm_kinematics/PR2ArmKinematicsPlugin\");\n        } catch(pluginlib::PluginlibException& ex) //handle the class failing to load\n        {\n            ROS_ERROR(\"The plugin failed to load. Error: %s\", ex.what());\n            throw ex;\n        }\n\n        if(!kinematicsSolver->initialize(\"robot_description\", arm, \"/torso_lift_link\", endEffector, 0.02 /* max error */)) {\n            ROS_ERROR(\"Could not initialize solver\");\n        }\n        else {\n            ROS_INFO(\"Initialized solver successfully\");\n        }\n\n        rng.seed(1000);\n    }\n\nprivate:\n\n    void goalCallback(const geometry_msgs::PointStampedConstPtr& point) {\n\n        ROS_DEBUG(\"Querying for solution\");\n\n        ros::WallTime start = ros::WallTime::now();\n\n        // Create a pose in the default orientation.\n        geometry_msgs::Pose pose;\n        pose.position = point->point;\n        tf::Quaternion identity = tf::createIdentityQuaternion();\n        tf::quaternionTFToMsg(identity, pose.orientation);\n\n        vector<double> jointValues(jointModelGroup->getJointModels().size());\n        vector<double> solution(7);\n        moveit_msgs::MoveItErrorCodes errorCode;\n\n        unsigned int count = 0;\n        for (unsigned int i = 0; i < 50; ++i) {\n            for (unsigned int i = 0; i < jointValues.size(); ++i) {\n                boost::uniform_real<double> range(jointModelGroup->getJointModels()[i]->getVariableBounds()[0].first,\n                                                jointModelGroup->getJointModels()[i]->getVariableBounds()[0].second);\n                boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > getRandom(rng, range);\n                jointValues[i] = getRandom();\n                ROS_DEBUG(\"Set initial position to [%f]\", jointValues[i]);\n            }\n\n            kinematicsSolver->searchPositionIK(pose, jointValues, 0.1 /* timeout */, solution, errorCode);\n            if(errorCode.val == moveit_msgs::MoveItErrorCodes::SUCCESS) {\n                ROS_DEBUG(\"Solution found\");\n                count++;\n            }\n            else {\n                ROS_INFO(\"IK failed %i\", errorCode.val);\n            }\n        }\n\n        humanoid_catching::IKMetric msg;\n        msg.time = ros::Duration((ros::WallTime::now() - start).toSec());\n        msg.was_successful = (count > 0);\n        msg.count = count;\n        ikMetricsPub.publish(msg);\n    }\n};\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"ik_tester\");\n    IKTester ik;\n    ros::spin();\n    return 0;\n}\n\n", "meta": {"hexsha": "d8ce3d690c9eac863aab31d7c4dc040b8c58e17d", "size": 5161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ik_tester.cpp", "max_stars_repo_name": "PositronicsLab/humanoid_catching", "max_stars_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "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/ik_tester.cpp", "max_issues_repo_name": "PositronicsLab/humanoid_catching", "max_issues_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "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/ik_tester.cpp", "max_forks_repo_name": "PositronicsLab/humanoid_catching", "max_forks_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "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.4066666667, "max_line_length": 132, "alphanum_fraction": 0.6215849642, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.19856296369261997}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/MonotisedCentral.hpp\"\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <memory>\n#include <pup.h>\n#include <utility>\n\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Tensor/EagerMath/DeterminantAndInverse.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Structure/Side.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Actions/NormalCovectorAndMagnitude.hpp\"\n#include \"Evolution/Systems/GeneralizedHarmonic/Tags.hpp\"\n#include \"Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/ReconstructWork.tpp\"\n#include \"Evolution/Systems/GrMhd/GhValenciaDivClean/System.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/Tags.hpp\"\n#include \"NumericalAlgorithms/FiniteDifference/MonotisedCentral.hpp\"\n#include \"NumericalAlgorithms/FiniteDifference/Unlimited.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Lapse.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Shift.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/SpatialMetric.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Tags.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"\n#include \"PointwiseFunctions/Hydro/Tags.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace grmhd::GhValenciaDivClean::fd {\nMonotisedCentralPrim::MonotisedCentralPrim(CkMigrateMessage* const msg)\n    : Reconstructor(msg) {}\n\nstd::unique_ptr<Reconstructor> MonotisedCentralPrim::get_clone() const {\n  return std::make_unique<MonotisedCentralPrim>(*this);\n}\n\nvoid MonotisedCentralPrim::pup(PUP::er& p) { Reconstructor::pup(p); }\n\n// NOLINTNEXTLINE\nPUP::able::PUP_ID MonotisedCentralPrim::my_PUP_ID = 0;\n\ntemplate <size_t ThermodynamicDim, typename TagsList>\nvoid MonotisedCentralPrim::reconstruct(\n    const gsl::not_null<std::array<Variables<TagsList>, dim>*>\n        vars_on_lower_face,\n    const gsl::not_null<std::array<Variables<TagsList>, dim>*>\n        vars_on_upper_face,\n    const Variables<hydro::grmhd_tags<DataVector>>& volume_prims,\n    const Variables<typename System::variables_tag::type::tags_list>&\n        volume_spacetime_and_cons_vars,\n    const EquationsOfState::EquationOfState<true, ThermodynamicDim>& eos,\n    const Element<dim>& element,\n    const FixedHashMap<\n        maximum_number_of_neighbors(dim) + 1,\n        std::pair<Direction<dim>, ElementId<dim>>, std::vector<double>,\n        boost::hash<std::pair<Direction<dim>, ElementId<dim>>>>& neighbor_data,\n    const Mesh<dim>& subcell_mesh) const {\n  reconstruct_prims_work<tmpl::list<gr::Tags::SpacetimeMetric<3>>>(\n      vars_on_lower_face, vars_on_upper_face,\n      [](auto upper_face_vars_ptr, auto lower_face_vars_ptr,\n         const auto& volume_vars, const auto& ghost_cell_vars,\n         const auto& subcell_extents, const size_t number_of_variables) {\n        ::fd::reconstruction::monotised_central(\n            upper_face_vars_ptr, lower_face_vars_ptr, volume_vars,\n            ghost_cell_vars, subcell_extents, number_of_variables);\n      },\n      [](auto upper_face_vars_ptr, auto lower_face_vars_ptr,\n         const auto& volume_vars, const auto& ghost_cell_vars,\n         const auto& subcell_extents, const size_t number_of_variables) {\n        ::fd::reconstruction::unlimited<2>(\n            upper_face_vars_ptr, lower_face_vars_ptr, volume_vars,\n            ghost_cell_vars, subcell_extents, number_of_variables);\n      },\n      [](const auto vars_on_face_ptr) {\n        const auto& spacetime_metric =\n            get<gr::Tags::SpacetimeMetric<3>>(*vars_on_face_ptr);\n        auto& spatial_metric =\n            get<gr::Tags::SpatialMetric<3>>(*vars_on_face_ptr);\n        gr::spatial_metric(make_not_null(&spatial_metric), spacetime_metric);\n        auto& inverse_spatial_metric =\n            get<gr::Tags::InverseSpatialMetric<3>>(*vars_on_face_ptr);\n        auto& sqrt_det_spatial_metric =\n            get<gr::Tags::SqrtDetSpatialMetric<>>(*vars_on_face_ptr);\n\n        determinant_and_inverse(make_not_null(&sqrt_det_spatial_metric),\n                                make_not_null(&inverse_spatial_metric),\n                                spatial_metric);\n        get(sqrt_det_spatial_metric) = sqrt(get(sqrt_det_spatial_metric));\n\n        auto& shift = get<gr::Tags::Shift<3>>(*vars_on_face_ptr);\n        gr::shift(make_not_null(&shift), spacetime_metric,\n                  inverse_spatial_metric);\n        gr::lapse(make_not_null(&get<gr::Tags::Lapse<>>(*vars_on_face_ptr)),\n                  shift, spacetime_metric);\n      },\n      volume_prims, volume_spacetime_and_cons_vars, eos, element, neighbor_data,\n      subcell_mesh, ghost_zone_size());\n}\n\ntemplate <size_t ThermodynamicDim, typename TagsList>\nvoid MonotisedCentralPrim::reconstruct_fd_neighbor(\n    const gsl::not_null<Variables<TagsList>*> vars_on_face,\n    const Variables<hydro::grmhd_tags<DataVector>>& subcell_volume_prims,\n    const Variables<tmpl::list<\n        gr::Tags::SpacetimeMetric<3>, GeneralizedHarmonic::Tags::Phi<3>,\n        GeneralizedHarmonic::Tags::Pi<3>>>& subcell_volume_spacetime_metric,\n    const EquationsOfState::EquationOfState<true, ThermodynamicDim>& eos,\n    const Element<dim>& element,\n    const FixedHashMap<\n        maximum_number_of_neighbors(dim) + 1,\n        std::pair<Direction<dim>, ElementId<dim>>, std::vector<double>,\n        boost::hash<std::pair<Direction<dim>, ElementId<dim>>>>& neighbor_data,\n    const Mesh<dim>& subcell_mesh,\n    const Direction<dim> direction_to_reconstruct) const {\n  reconstruct_fd_neighbor_work(\n      vars_on_face,\n      [](const auto tensor_component_on_face_ptr,\n         const auto& tensor_component_volume,\n         const auto& tensor_component_neighbor,\n         const Index<dim>& subcell_extents,\n         const Index<dim>& ghost_data_extents,\n         const Direction<dim>& local_direction_to_reconstruct) {\n        ::fd::reconstruction::reconstruct_neighbor<\n            Side::Lower,\n            ::fd::reconstruction::detail::MonotisedCentralReconstructor>(\n            tensor_component_on_face_ptr, tensor_component_volume,\n            tensor_component_neighbor, subcell_extents, ghost_data_extents,\n            local_direction_to_reconstruct);\n      },\n      [](const auto tensor_component_on_face_ptr,\n         const auto& tensor_component_volume,\n         const auto& tensor_component_neighbor,\n         const Index<dim>& subcell_extents,\n         const Index<dim>& ghost_data_extents,\n         const Direction<dim>& local_direction_to_reconstruct) {\n        ::fd::reconstruction::reconstruct_neighbor<\n            Side::Lower,\n            ::fd::reconstruction::detail::UnlimitedReconstructor<2>>(\n            tensor_component_on_face_ptr, tensor_component_volume,\n            tensor_component_neighbor, subcell_extents, ghost_data_extents,\n            local_direction_to_reconstruct);\n      },\n      [](const auto tensor_component_on_face_ptr,\n         const auto& tensor_component_volume,\n         const auto& tensor_component_neighbor,\n         const Index<dim>& subcell_extents,\n         const Index<dim>& ghost_data_extents,\n         const Direction<dim>& local_direction_to_reconstruct) {\n        ::fd::reconstruction::reconstruct_neighbor<\n            Side::Upper,\n            ::fd::reconstruction::detail::MonotisedCentralReconstructor>(\n            tensor_component_on_face_ptr, tensor_component_volume,\n            tensor_component_neighbor, subcell_extents, ghost_data_extents,\n            local_direction_to_reconstruct);\n      },\n      [](const auto tensor_component_on_face_ptr,\n         const auto& tensor_component_volume,\n         const auto& tensor_component_neighbor,\n         const Index<dim>& subcell_extents,\n         const Index<dim>& ghost_data_extents,\n         const Direction<dim>& local_direction_to_reconstruct) {\n        ::fd::reconstruction::reconstruct_neighbor<\n            Side::Upper,\n            ::fd::reconstruction::detail::UnlimitedReconstructor<2>>(\n            tensor_component_on_face_ptr, tensor_component_volume,\n            tensor_component_neighbor, subcell_extents, ghost_data_extents,\n            local_direction_to_reconstruct);\n      },\n      [](const auto vars_on_face_ptr) {\n        const auto& spacetime_metric =\n            get<gr::Tags::SpacetimeMetric<3>>(*vars_on_face_ptr);\n        auto& spatial_metric =\n            get<gr::Tags::SpatialMetric<3>>(*vars_on_face_ptr);\n        gr::spatial_metric(make_not_null(&spatial_metric), spacetime_metric);\n        auto& inverse_spatial_metric =\n            get<gr::Tags::InverseSpatialMetric<3>>(*vars_on_face_ptr);\n        auto& sqrt_det_spatial_metric =\n            get<gr::Tags::SqrtDetSpatialMetric<>>(*vars_on_face_ptr);\n\n        determinant_and_inverse(make_not_null(&sqrt_det_spatial_metric),\n                                make_not_null(&inverse_spatial_metric),\n                                spatial_metric);\n        get(sqrt_det_spatial_metric) = sqrt(get(sqrt_det_spatial_metric));\n\n        auto& shift = get<gr::Tags::Shift<3>>(*vars_on_face_ptr);\n        gr::shift(make_not_null(&shift), spacetime_metric,\n                  inverse_spatial_metric);\n        gr::lapse(make_not_null(&get<gr::Tags::Lapse<>>(*vars_on_face_ptr)),\n                  shift, spacetime_metric);\n      },\n      subcell_volume_prims, subcell_volume_spacetime_metric, eos, element,\n      neighbor_data, subcell_mesh, direction_to_reconstruct, ghost_zone_size());\n}\n\nbool operator==(const MonotisedCentralPrim& /*lhs*/,\n                const MonotisedCentralPrim& /*rhs*/) {\n  return true;\n}\n\nbool operator!=(const MonotisedCentralPrim& lhs,\n                const MonotisedCentralPrim& rhs) {\n  return not(lhs == rhs);\n}\n\n#define THERMO_DIM(data) BOOST_PP_TUPLE_ELEM(0, data)\n#define TAGS_LIST(data)                                                       \\\n  tmpl::list<                                                                 \\\n      gr::Tags::SpacetimeMetric<3>, GeneralizedHarmonic::Tags::Pi<3>,         \\\n      GeneralizedHarmonic::Tags::Phi<3>, ValenciaDivClean::Tags::TildeD,      \\\n      ValenciaDivClean::Tags::TildeTau,                                       \\\n      ValenciaDivClean::Tags::TildeS<Frame::Inertial>,                        \\\n      ValenciaDivClean::Tags::TildeB<Frame::Inertial>,                        \\\n      ValenciaDivClean::Tags::TildePhi,                                       \\\n      hydro::Tags::RestMassDensity<DataVector>,                               \\\n      hydro::Tags::SpecificInternalEnergy<DataVector>,                        \\\n      hydro::Tags::SpatialVelocity<DataVector, 3>,                            \\\n      hydro::Tags::MagneticField<DataVector, 3>,                              \\\n      hydro::Tags::DivergenceCleaningField<DataVector>,                       \\\n      hydro::Tags::LorentzFactor<DataVector>,                                 \\\n      hydro::Tags::Pressure<DataVector>,                                      \\\n      hydro::Tags::SpecificEnthalpy<DataVector>,                              \\\n      hydro::Tags::LorentzFactorTimesSpatialVelocity<DataVector, 3>,          \\\n      ::Tags::Flux<ValenciaDivClean::Tags::TildeD, tmpl::size_t<3>,           \\\n                   Frame::Inertial>,                                          \\\n      ::Tags::Flux<ValenciaDivClean::Tags::TildeTau, tmpl::size_t<3>,         \\\n                   Frame::Inertial>,                                          \\\n      ::Tags::Flux<ValenciaDivClean::Tags::TildeS<Frame::Inertial>,           \\\n                   tmpl::size_t<3>, Frame::Inertial>,                         \\\n      ::Tags::Flux<ValenciaDivClean::Tags::TildeB<Frame::Inertial>,           \\\n                   tmpl::size_t<3>, Frame::Inertial>,                         \\\n      ::Tags::Flux<ValenciaDivClean::Tags::TildePhi, tmpl::size_t<3>,         \\\n                   Frame::Inertial>,                                          \\\n      gr::Tags::Lapse<>, gr::Tags::Shift<3, Frame::Inertial, DataVector>,     \\\n      gr::Tags::SpatialMetric<3>, gr::Tags::SqrtDetSpatialMetric<DataVector>, \\\n      gr::Tags::InverseSpatialMetric<3, Frame::Inertial, DataVector>,         \\\n      evolution::dg::Actions::detail::NormalVector<3>>\n\n#define INSTANTIATION(r, data)                                                 \\\n  template void MonotisedCentralPrim::reconstruct(                             \\\n      gsl::not_null<std::array<Variables<TAGS_LIST(data)>, 3>*>                \\\n          vars_on_lower_face,                                                  \\\n      gsl::not_null<std::array<Variables<TAGS_LIST(data)>, 3>*>                \\\n          vars_on_upper_face,                                                  \\\n      const Variables<hydro::grmhd_tags<DataVector>>& volume_prims,            \\\n      const Variables<typename System::variables_tag::type::tags_list>&        \\\n          volume_spacetime_and_cons_vars,                                      \\\n      const EquationsOfState::EquationOfState<true, THERMO_DIM(data)>& eos,    \\\n      const Element<3>& element,                                               \\\n      const FixedHashMap<                                                      \\\n          maximum_number_of_neighbors(3) + 1,                                  \\\n          std::pair<Direction<3>, ElementId<3>>, std::vector<double>,          \\\n          boost::hash<std::pair<Direction<3>, ElementId<3>>>>& neighbor_data,  \\\n      const Mesh<3>& subcell_mesh) const;                                      \\\n  template void MonotisedCentralPrim::reconstruct_fd_neighbor(                 \\\n      gsl::not_null<Variables<TAGS_LIST(data)>*> vars_on_face,                 \\\n      const Variables<hydro::grmhd_tags<DataVector>>& subcell_volume_prims,    \\\n      const Variables<tmpl::list<                                              \\\n          gr::Tags::SpacetimeMetric<3>, GeneralizedHarmonic::Tags::Phi<3>,     \\\n          GeneralizedHarmonic::Tags::Pi<3>>>& subcell_volume_spacetime_metric, \\\n      const EquationsOfState::EquationOfState<true, THERMO_DIM(data)>& eos,    \\\n      const Element<3>& element,                                               \\\n      const FixedHashMap<                                                      \\\n          maximum_number_of_neighbors(3) + 1,                                  \\\n          std::pair<Direction<3>, ElementId<3>>, std::vector<double>,          \\\n          boost::hash<std::pair<Direction<3>, ElementId<3>>>>& neighbor_data,  \\\n      const Mesh<3>& subcell_mesh,                                             \\\n      const Direction<3> direction_to_reconstruct) const;\n\nGENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2))\n\n#undef INSTANTIATION\n#undef TAGS_LIST\n#undef THERMO_DIM\n}  // namespace grmhd::GhValenciaDivClean::fd\n", "meta": {"hexsha": "3f40e657f84b7eff37f84db44a4aae8bbfda46b6", "size": 15264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/MonotisedCentral.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/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/MonotisedCentral.cpp", "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/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/MonotisedCentral.cpp", "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": 52.8166089965, "max_line_length": 91, "alphanum_fraction": 0.6326650943, "num_tokens": 3431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.19851793966029452}}
{"text": "// Copyright (c) 2020 - present Advanced Micro Devices, Inc. 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\n// THE SOFTWARE.\n\n#include <boost/scope_exit.hpp>\n#include <gtest/gtest.h>\n#include <math.h>\n#include <stdexcept>\n#include <thread>\n#include <utility>\n#include <vector>\n\n#include \"../client_utils.h\"\n#include \"accuracy_test.h\"\n#include \"fftw_transform.h\"\n#include \"gpubuf.h\"\n#include \"rocfft.h\"\n#include \"rocfft_against_fftw.h\"\n\n// Given an array type, return the name as a string.\nstd::string array_type_name(const rocfft_array_type type)\n{\n    switch(type)\n    {\n    case rocfft_array_type_complex_interleaved:\n        return \"rocfft_array_type_complex_interleaved\";\n    case rocfft_array_type_complex_planar:\n        return \"rocfft_array_type_complex_planar\";\n    case rocfft_array_type_real:\n        return \"rocfft_array_type_real\";\n    case rocfft_array_type_hermitian_interleaved:\n        return \"rocfft_array_type_hermitian_interleaved\";\n    case rocfft_array_type_hermitian_planar:\n        return \"rocfft_array_type_hermitian_planar\";\n    case rocfft_array_type_unset:\n        return \"rocfft_array_type_unset\";\n    }\n    return \"\";\n}\n\n// Function to return a string with the gpu parameters.\nstd::string gpu_params(const std::vector<size_t>&    gpu_ilength_cm,\n                       const std::vector<size_t>&    gpu_istride_cm,\n                       const size_t                  gpu_idist,\n                       const std::vector<size_t>&    gpu_ostride_cm,\n                       const size_t                  gpu_odist,\n                       const size_t                  nbatch,\n                       const rocfft_precision        precision,\n                       const rocfft_result_placement place,\n                       const rocfft_array_type       itype,\n                       const rocfft_array_type       otype)\n{\n    std::stringstream ss;\n    ss << \"\\nGPU params:\\n\";\n    ss << \"\\tgpu_ilength_cm:\";\n    for(auto i : gpu_ilength_cm)\n        ss << \" \" << i;\n    ss << \"\\n\";\n    ss << \"\\tgpu_istride_cm:\";\n    for(auto i : gpu_istride_cm)\n        ss << \" \" << i;\n    ss << \"\\n\";\n    ss << \"\\tgpu_idist: \" << gpu_idist << \"\\n\";\n\n    ss << \"\\tgpu_ostride_cm:\";\n    for(auto i : gpu_ostride_cm)\n        ss << \" \" << i;\n    ss << \"\\n\";\n    ss << \"\\tgpu_odist: \" << gpu_odist << \"\\n\";\n\n    ss << \"\\tbatch: \" << nbatch << \"\\n\";\n\n    if(place == rocfft_placement_inplace)\n        ss << \"\\tin-place\\n\";\n    else\n        ss << \"\\tout-of-place\\n\";\n    ss << \"\\t\" << array_type_name(itype) << \" -> \" << array_type_name(otype) << \"\\n\";\n    if(precision == rocfft_precision_single)\n        ss << \"\\tsingle-precision\\n\";\n    else\n        ss << \"\\tdouble-precision\\n\";\n    return ss.str();\n}\n\n// Compute a FFT using rocFFT and compare with the provided CPU reference computation.\nvoid rocfft_transform(const std::vector<size_t>&                                 length,\n                      const std::vector<size_t>&                                 istride,\n                      const std::vector<size_t>&                                 ostride,\n                      const size_t                                               nbatch,\n                      const rocfft_precision                                     precision,\n                      const rocfft_transform_type                                transformType,\n                      const rocfft_array_type                                    itype,\n                      const rocfft_array_type                                    otype,\n                      const rocfft_result_placement                              place,\n                      const std::vector<size_t>&                                 cpu_istride,\n                      const std::vector<size_t>&                                 cpu_ostride,\n                      const size_t                                               cpu_idist,\n                      const size_t                                               cpu_odist,\n                      const rocfft_array_type                                    cpu_itype,\n                      const rocfft_array_type                                    cpu_otype,\n                      const std::vector<std::vector<char, fftwAllocator<char>>>& cpu_input_copy,\n                      const std::vector<std::vector<char, fftwAllocator<char>>>& cpu_output,\n                      const VectorNorms&                                         cpu_output_norm,\n                      std::thread*                                               cpu_output_thread)\n{\n    // Set up GPU computation:\n\n    if(place == rocfft_placement_inplace)\n    {\n        const auto stridesize = std::min(istride.size(), ostride.size());\n        bool       samestride = true;\n        for(int i = 0; i < stridesize; ++i)\n        {\n            if(istride[i] != ostride[i])\n                samestride = false;\n        }\n        if(!samestride)\n        {\n            // In-place transforms require identical input and output strides.\n            if(verbose)\n            {\n                std::cout << \"istride:\";\n                for(const auto& i : istride)\n                    std::cout << \" \" << i;\n                std::cout << \" ostride0:\";\n                for(const auto& i : ostride)\n                    std::cout << \" \" << i;\n                std::cout << \" differ; skipped for in-place transforms: skipping test\" << std::endl;\n            }\n            // TODO: mark skipped\n            return;\n        }\n        if((transformType == rocfft_transform_type_real_forward\n            || transformType == rocfft_transform_type_real_inverse)\n           && (istride[0] != 1 || ostride[0] != 1))\n        {\n            // In-place real/complex transforms require unit strides.\n            if(verbose)\n            {\n                std::cout << \"istride[0]: \" << istride[0] << \" ostride[0]: \" << ostride[0]\n                          << \" must be unitary for in-place real/complex transforms: skipping test\"\n                          << std::endl;\n            }\n            // TODO: mark skipped\n            return;\n        }\n\n        if((itype == rocfft_array_type_complex_interleaved\n            && otype == rocfft_array_type_complex_planar)\n           || (itype == rocfft_array_type_complex_planar\n               && otype == rocfft_array_type_complex_interleaved))\n        {\n            if(verbose)\n            {\n                std::cout << \"In-place c2c transforms require identical io types; skipped.\\n\";\n            }\n            return;\n        }\n\n        if((itype == rocfft_array_type_real && otype == rocfft_array_type_hermitian_planar)\n           || (itype == rocfft_array_type_hermitian_planar && otype == rocfft_array_type_real))\n        {\n            if(verbose)\n            {\n                std::cout << \"In-place real/complex transforms cannot use planar types; skipped.\\n\";\n            }\n            return;\n        }\n    }\n\n    const size_t dim = length.size();\n\n    auto olength = length;\n    if(transformType == rocfft_transform_type_real_forward)\n        olength[dim - 1] = olength[dim - 1] / 2 + 1;\n\n    auto ilength = length;\n    if(transformType == rocfft_transform_type_real_inverse)\n        ilength[dim - 1] = ilength[dim - 1] / 2 + 1;\n\n    auto gpu_istride = compute_stride(ilength,\n                                      istride,\n                                      place == rocfft_placement_inplace\n                                          && transformType == rocfft_transform_type_real_forward);\n\n    auto gpu_ostride = compute_stride(olength,\n                                      ostride,\n                                      place == rocfft_placement_inplace\n                                          && transformType == rocfft_transform_type_real_inverse);\n\n    const auto gpu_idist = set_idist(place, transformType, length, gpu_istride);\n    const auto gpu_odist = set_odist(place, transformType, length, gpu_ostride);\n\n    rocfft_status fft_status = rocfft_status_success;\n    // Transform parameters from row-major to column-major for rocFFT:\n    auto gpu_length_cm  = length;\n    auto gpu_ilength_cm = ilength;\n    auto gpu_olength_cm = olength;\n    auto gpu_istride_cm = gpu_istride;\n    auto gpu_ostride_cm = gpu_ostride;\n    for(int idx = 0; idx < dim / 2; ++idx)\n    {\n        const auto toidx = dim - idx - 1;\n        std::swap(gpu_istride_cm[idx], gpu_istride_cm[toidx]);\n        std::swap(gpu_ostride_cm[idx], gpu_ostride_cm[toidx]);\n        std::swap(gpu_length_cm[idx], gpu_length_cm[toidx]);\n        std::swap(gpu_ilength_cm[idx], gpu_ilength_cm[toidx]);\n        std::swap(gpu_olength_cm[idx], gpu_olength_cm[toidx]);\n    }\n\n    if(verbose > 1)\n    {\n        std::cout << gpu_params(gpu_ilength_cm,\n                                gpu_istride_cm,\n                                gpu_idist,\n                                gpu_ostride_cm,\n                                gpu_odist,\n                                nbatch,\n                                precision,\n                                place,\n                                itype,\n                                otype)\n                  << std::flush;\n    }\n\n    // Create FFT description\n    rocfft_plan_description desc = NULL;\n    fft_status                   = rocfft_plan_description_create(&desc);\n    EXPECT_TRUE(fft_status == rocfft_status_success) << \"rocFFT description creation failure\";\n    const std::vector<size_t> ioffset = {0, 0};\n    const std::vector<size_t> ooffset = {0, 0};\n    fft_status                        = rocfft_plan_description_set_data_layout(desc,\n                                                         itype,\n                                                         otype,\n                                                         ioffset.data(),\n                                                         ooffset.data(),\n                                                         gpu_istride_cm.size(),\n                                                         gpu_istride_cm.data(),\n                                                         gpu_idist,\n                                                         gpu_ostride_cm.size(),\n                                                         gpu_ostride_cm.data(),\n                                                         gpu_odist);\n    EXPECT_TRUE(fft_status == rocfft_status_success)\n        << \"rocFFT data layout failure: \" << fft_status;\n\n    // Create the plan\n    rocfft_plan gpu_plan = NULL;\n    fft_status           = rocfft_plan_create(&gpu_plan,\n                                    place,\n                                    transformType,\n                                    precision,\n                                    gpu_length_cm.size(),\n                                    gpu_length_cm.data(),\n                                    nbatch,\n                                    desc);\n    EXPECT_TRUE(fft_status == rocfft_status_success) << \"rocFFT plan creation failure\";\n\n    // Create execution info\n    rocfft_execution_info info = NULL;\n    fft_status                 = rocfft_execution_info_create(&info);\n    EXPECT_TRUE(fft_status == rocfft_status_success) << \"rocFFT execution info creation failure\";\n    size_t workbuffersize = 0;\n    fft_status            = rocfft_plan_get_work_buffer_size(gpu_plan, &workbuffersize);\n    EXPECT_TRUE(fft_status == rocfft_status_success) << \"rocFFT get buffer size get failure\";\n\n    // Number of value in input and output variables.\n    const size_t isize = nbatch * gpu_idist;\n    const size_t osize = nbatch * gpu_odist;\n\n    // Sizes of individual input and output variables\n    const size_t isize_t = var_size<size_t>(precision, itype);\n    const size_t osize_t = var_size<size_t>(precision, otype);\n\n    // Numbers of input and output buffers:\n    const int nibuffer\n        = (itype == rocfft_array_type_complex_planar || itype == rocfft_array_type_hermitian_planar)\n              ? 2\n              : 1;\n    const int nobuffer\n        = (otype == rocfft_array_type_complex_planar || otype == rocfft_array_type_hermitian_planar)\n              ? 2\n              : 1;\n\n    // Check if the problem fits on the device; if it doesn't skip it.\n    if(!vram_fits_problem(nibuffer * isize * isize_t,\n                          (place == rocfft_placement_inplace) ? 0 : nobuffer * osize * osize_t,\n                          workbuffersize))\n    {\n        rocfft_plan_destroy(gpu_plan);\n        rocfft_plan_description_destroy(desc);\n        rocfft_execution_info_destroy(info);\n\n        if(verbose)\n        {\n            std::cout << \"Problem won't fit on device; skipped\\n\";\n        }\n        // TODO: mark as skipped via gtest.\n        return;\n    }\n\n    hipError_t hip_status = hipSuccess;\n\n    // Allocate work memory and associate with the execution info\n    gpubuf wbuffer;\n    if(workbuffersize > 0)\n    {\n        hip_status = wbuffer.alloc(workbuffersize);\n        EXPECT_TRUE(hip_status == hipSuccess) << \"hipMalloc failure for work buffer\";\n        fft_status = rocfft_execution_info_set_work_buffer(info, wbuffer.data(), workbuffersize);\n        EXPECT_TRUE(fft_status == rocfft_status_success) << \"rocFFT set work buffer failure\";\n    }\n\n    // Formatted input data:\n    auto gpu_input = allocate_host_buffer<fftwAllocator<char>>(\n        precision, itype, length, gpu_istride, gpu_idist, nbatch);\n\n    // Copy from contiguous_input to input.\n    copy_buffers(cpu_input_copy,\n                 gpu_input,\n                 ilength,\n                 nbatch,\n                 precision,\n                 cpu_itype,\n                 cpu_istride,\n                 cpu_idist,\n                 itype,\n                 gpu_istride,\n                 gpu_idist);\n\n    if(verbose > 4)\n    {\n        std::cout << \"GPU input:\\n\";\n        printbuffer(precision, itype, gpu_input, ilength, gpu_istride, nbatch, gpu_idist);\n    }\n    if(verbose > 5)\n    {\n        std::cout << \"flat GPU input:\\n\";\n        printbuffer_flat(precision, itype, gpu_input, gpu_idist);\n    }\n\n    // GPU input and output buffers:\n    auto                ibuffer_sizes = buffer_sizes(precision, itype, gpu_idist, nbatch);\n    std::vector<gpubuf> ibuffer(ibuffer_sizes.size());\n    std::vector<void*>  pibuffer(ibuffer_sizes.size());\n    for(unsigned int i = 0; i < ibuffer.size(); ++i)\n    {\n        hip_status = ibuffer[i].alloc(ibuffer_sizes[i]);\n        ASSERT_TRUE(hip_status == hipSuccess)\n            << \"hipMalloc failure for input buffer \" << i << \" size \" << ibuffer_sizes[i]\n            << gpu_params(gpu_ilength_cm,\n                          gpu_istride_cm,\n                          gpu_idist,\n                          gpu_ostride_cm,\n                          gpu_odist,\n                          nbatch,\n                          precision,\n                          place,\n                          itype,\n                          otype);\n        pibuffer[i] = ibuffer[i].data();\n    }\n\n    std::vector<gpubuf>  obuffer_data;\n    std::vector<gpubuf>* obuffer = &obuffer_data;\n    if(place == rocfft_placement_inplace)\n    {\n        obuffer = &ibuffer;\n    }\n    else\n    {\n        auto obuffer_sizes = buffer_sizes(precision, otype, gpu_odist, nbatch);\n        obuffer_data.resize(obuffer_sizes.size());\n        for(unsigned int i = 0; i < obuffer_data.size(); ++i)\n        {\n            hip_status = obuffer_data[i].alloc(obuffer_sizes[i]);\n            ASSERT_TRUE(hip_status == hipSuccess)\n                << \"hipMalloc failure for output buffer \" << i << \" size \" << obuffer_sizes[i]\n                << gpu_params(gpu_ilength_cm,\n                              gpu_istride_cm,\n                              gpu_idist,\n                              gpu_ostride_cm,\n                              gpu_odist,\n                              nbatch,\n                              precision,\n                              place,\n                              itype,\n                              otype);\n        }\n    }\n    std::vector<void*> pobuffer(obuffer->size());\n    for(unsigned int i = 0; i < obuffer->size(); ++i)\n    {\n        pobuffer[i] = obuffer->at(i).data();\n    }\n\n    // Copy the input data to the GPU:\n    for(int idx = 0; idx < gpu_input.size(); ++idx)\n    {\n        hip_status = hipMemcpy(ibuffer[idx].data(),\n                               gpu_input[idx].data(),\n                               gpu_input[idx].size(),\n                               hipMemcpyHostToDevice);\n        EXPECT_TRUE(hip_status == hipSuccess) << \"hipMemcpy failure\";\n    }\n\n    // Execute the transform:\n    fft_status = rocfft_execute(gpu_plan, // plan\n                                (void**)pibuffer.data(), // in buffers\n                                (void**)pobuffer.data(), // out buffers\n                                info); // execution info\n    EXPECT_TRUE(fft_status == rocfft_status_success) << \"rocFFT plan execution failure\";\n\n    // Copy the data back to the host:\n    auto gpu_output = allocate_host_buffer<fftwAllocator<char>>(\n        precision, otype, olength, gpu_ostride, gpu_odist, nbatch);\n    for(int idx = 0; idx < gpu_output.size(); ++idx)\n    {\n        hip_status = hipMemcpy(gpu_output[idx].data(),\n                               obuffer->at(idx).data(),\n                               gpu_output[idx].size(),\n                               hipMemcpyDeviceToHost);\n        EXPECT_TRUE(hip_status == hipSuccess) << \"hipMemcpy failure\";\n    }\n\n    if(verbose > 2)\n    {\n        std::cout << \"GPU output:\\n\";\n        printbuffer(precision, otype, gpu_output, olength, gpu_ostride, nbatch, gpu_odist);\n    }\n    if(verbose > 5)\n    {\n        std::cout << \"flat GPU output:\\n\";\n        printbuffer_flat(precision, otype, gpu_output, gpu_odist);\n    }\n\n    // Compute the Linfinity and L2 norm of the GPU output:\n    VectorNorms gpu_norm;\n    std::thread normthread([&]() {\n        gpu_norm = norm(gpu_output, olength, nbatch, precision, otype, gpu_ostride, gpu_odist);\n    });\n    if(cpu_output_thread && cpu_output_thread->joinable())\n        cpu_output_thread->join();\n\n    // Compute the l-infinity and l-2 distance between the CPU and GPU output:\n    std::vector<std::pair<size_t, size_t>> linf_failures;\n    const auto                             total_length\n        = std::accumulate(length.begin(), length.end(), 1, std::multiplies<size_t>());\n    const double linf_cutoff = type_epsilon(precision) * cpu_output_norm.l_inf * log2(total_length);\n    auto         diff        = distance(cpu_output,\n                         gpu_output,\n                         olength,\n                         nbatch,\n                         precision,\n                         cpu_otype,\n                         cpu_ostride,\n                         cpu_odist,\n                         otype,\n                         gpu_ostride,\n                         gpu_odist,\n                         linf_failures,\n                         linf_cutoff);\n    normthread.join();\n\n    if(verbose > 1)\n    {\n        std::cout << \"GPU output Linf norm: \" << gpu_norm.l_inf << \"\\n\";\n        std::cout << \"GPU output L2 norm:   \" << gpu_norm.l_2 << \"\\n\";\n        std::cout << \"GPU linf norm failures:\";\n        std::sort(linf_failures.begin(), linf_failures.end());\n        for(const auto& i : linf_failures)\n        {\n            std::cout << \" (\" << i.first << \",\" << i.second << \")\";\n        }\n        std::cout << std::endl;\n    }\n\n    EXPECT_TRUE(std::isfinite(gpu_norm.l_inf)) << gpu_params(gpu_ilength_cm,\n                                                             gpu_istride_cm,\n                                                             gpu_idist,\n                                                             gpu_ostride_cm,\n                                                             gpu_odist,\n                                                             nbatch,\n                                                             precision,\n                                                             place,\n                                                             itype,\n                                                             otype);\n    EXPECT_TRUE(std::isfinite(gpu_norm.l_2)) << gpu_params(gpu_ilength_cm,\n                                                           gpu_istride_cm,\n                                                           gpu_idist,\n                                                           gpu_ostride_cm,\n                                                           gpu_odist,\n                                                           nbatch,\n                                                           precision,\n                                                           place,\n                                                           itype,\n                                                           otype);\n\n    if(verbose > 1)\n    {\n        std::cout << \"L2 diff: \" << diff.l_2 << \"\\n\";\n        std::cout << \"Linf diff: \" << diff.l_inf << \"\\n\";\n    }\n\n    // TODO: handle case where norm is zero?\n    EXPECT_TRUE(diff.l_inf < linf_cutoff)\n        << \"Linf test failed.  Linf:\" << diff.l_inf\n        << \"\\tnormalized Linf: \" << diff.l_inf / cpu_output_norm.l_inf\n        << \"\\tcutoff: \" << linf_cutoff\n        << gpu_params(gpu_ilength_cm,\n                      gpu_istride_cm,\n                      gpu_idist,\n                      gpu_ostride_cm,\n                      gpu_odist,\n                      nbatch,\n                      precision,\n                      place,\n                      itype,\n                      otype);\n\n    EXPECT_TRUE(diff.l_2 / cpu_output_norm.l_2 < sqrt(log2(total_length)) * type_epsilon(precision))\n        << \"L2 test failed. L2: \" << diff.l_2\n        << \"\\tnormalized L2: \" << diff.l_2 / cpu_output_norm.l_2\n        << \"\\tepsilon: \" << sqrt(log2(total_length)) * type_epsilon(precision)\n        << gpu_params(gpu_ilength_cm,\n                      gpu_istride_cm,\n                      gpu_idist,\n                      gpu_ostride_cm,\n                      gpu_odist,\n                      nbatch,\n                      precision,\n                      place,\n                      itype,\n                      otype);\n\n    rocfft_plan_destroy(gpu_plan);\n    gpu_plan = NULL;\n    rocfft_plan_description_destroy(desc);\n    desc = NULL;\n    rocfft_execution_info_destroy(info);\n    info = NULL;\n}\n\n// Test for comparison between FFTW and rocFFT.\nTEST_P(accuracy_test, vs_fftw)\n{\n    const std::vector<size_t>                  length        = std::get<0>(GetParam());\n    const std::vector<std::vector<size_t>>     istride_range = std::get<1>(GetParam());\n    const std::vector<std::vector<size_t>>     ostride_range = std::get<2>(GetParam());\n    const std::vector<size_t>                  batch_range   = std::get<3>(GetParam());\n    const rocfft_precision                     precision     = std::get<4>(GetParam());\n    const rocfft_transform_type                transformType = std::get<5>(GetParam());\n    const std::vector<rocfft_result_placement> place_range   = std::get<6>(GetParam());\n\n    // NB: Input data is row-major.\n\n    const size_t dim = length.size();\n\n    // Input cpu parameters:\n    auto ilength = length;\n    if(transformType == rocfft_transform_type_real_inverse)\n        ilength[dim - 1] = ilength[dim - 1] / 2 + 1;\n    const auto cpu_istride = compute_stride(ilength);\n    const auto cpu_itype   = contiguous_itype(transformType);\n    const auto cpu_idist\n        = set_idist(rocfft_placement_notinplace, transformType, length, cpu_istride);\n\n    // Output cpu parameters:\n    auto olength = length;\n    if(transformType == rocfft_transform_type_real_forward)\n        olength[dim - 1] = olength[dim - 1] / 2 + 1;\n    const auto cpu_ostride = compute_stride(olength);\n    const auto cpu_odist\n        = set_odist(rocfft_placement_notinplace, transformType, length, cpu_ostride);\n    auto cpu_otype = contiguous_otype(transformType);\n    if(verbose > 3)\n    {\n        std::cout << \"CPU  params:\\n\";\n        std::cout << \"\\tilength:\";\n        for(auto i : ilength)\n            std::cout << \" \" << i;\n        std::cout << \"\\n\";\n        std::cout << \"\\tcpu_istride:\";\n        for(auto i : cpu_istride)\n            std::cout << \" \" << i;\n        std::cout << \"\\n\";\n        std::cout << \"\\tcpu_idist: \" << cpu_idist << std::endl;\n\n        std::cout << \"\\tolength:\";\n        for(auto i : olength)\n            std::cout << \" \" << i;\n        std::cout << \"\\n\";\n        std::cout << \"\\tcpu_ostride:\";\n        for(auto i : cpu_ostride)\n            std::cout << \" \" << i;\n        std::cout << \"\\n\";\n        std::cout << \"\\tcpu_odist: \" << cpu_odist << std::endl;\n    }\n\n    const size_t nbatch = *std::max_element(batch_range.begin(), batch_range.end());\n\n    // Generate the data:\n    auto cpu_input = compute_input<fftwAllocator<char>>(\n        precision, cpu_itype, length, cpu_istride, cpu_idist, nbatch);\n    auto cpu_input_copy = cpu_input; // copy of input (might get overwritten by FFTW).\n\n    // Compute the Linfinity and L2 norm of the CPU output:\n    VectorNorms cpu_input_norm;\n    std::thread cpu_input_norm_thread([&]() {\n        cpu_input_norm\n            = norm(cpu_input, ilength, nbatch, precision, cpu_itype, cpu_istride, cpu_idist);\n        if(verbose > 2)\n        {\n            std::cout << \"CPU Input Linf norm:  \" << cpu_input_norm.l_inf << \"\\n\";\n            std::cout << \"CPU Input L2 norm:    \" << cpu_input_norm.l_2 << \"\\n\";\n        }\n    });\n    if(verbose > 3)\n    {\n        std::cout << \"CPU input:\\n\";\n        printbuffer(precision, cpu_itype, cpu_input, ilength, cpu_istride, nbatch, cpu_idist);\n    }\n\n    // FFTW computation\n    // NB: FFTW may overwrite input, even for out-of-place transforms.\n    decltype(cpu_input) cpu_output;\n    VectorNorms         cpu_output_norm;\n    std::thread         cpu_output_thread([&]() {\n        cpu_output = fftw_via_rocfft(length,\n                                     cpu_istride,\n                                     cpu_ostride,\n                                     nbatch,\n                                     cpu_idist,\n                                     cpu_odist,\n                                     precision,\n                                     transformType,\n                                     cpu_input);\n        // Compute the Linfinity and L2 norm of the CPU output:\n        cpu_output_norm\n            = norm(cpu_output, olength, nbatch, precision, cpu_otype, cpu_ostride, cpu_odist);\n        if(verbose > 2)\n        {\n            std::cout << \"CPU Output Linf norm: \" << cpu_output_norm.l_inf << \"\\n\";\n            std::cout << \"CPU Output L2 norm:   \" << cpu_output_norm.l_2 << \"\\n\";\n        }\n        if(verbose > 3)\n        {\n            std::cout << \"CPU output:\\n\";\n            printbuffer(precision, cpu_otype, cpu_output, olength, cpu_ostride, nbatch, cpu_odist);\n        }\n    });\n    // clean up threads if transform throws\n    BOOST_SCOPE_EXIT_ALL(&cpu_output_thread, &cpu_input_norm_thread)\n    {\n        if(cpu_output_thread.joinable())\n            cpu_output_thread.join();\n        if(cpu_input_norm_thread.joinable())\n            cpu_input_norm_thread.join();\n    };\n\n    // Set up GPU computations:\n    for(const auto nbatch : batch_range)\n    {\n        for(const auto place : place_range)\n        {\n            for(const auto iotype : iotypes(transformType, place))\n            {\n                const rocfft_array_type itype = iotype.first;\n                const rocfft_array_type otype = iotype.second;\n                for(const auto istride : istride_range)\n                {\n                    for(const auto ostride : ostride_range)\n                    {\n                        if(verbose)\n                        {\n                            print_params(length,\n                                         istride,\n                                         ostride,\n                                         nbatch,\n                                         place,\n                                         precision,\n                                         transformType,\n                                         itype,\n                                         otype);\n                        }\n\n                        rocfft_transform(length,\n                                         istride,\n                                         ostride,\n                                         nbatch,\n                                         precision,\n                                         transformType,\n                                         itype,\n                                         otype,\n                                         place,\n                                         cpu_istride,\n                                         cpu_ostride,\n                                         cpu_idist,\n                                         cpu_odist,\n                                         cpu_itype,\n                                         cpu_otype,\n                                         cpu_input_copy,\n                                         cpu_output,\n                                         cpu_output_norm,\n                                         &cpu_output_thread);\n                    }\n                }\n            }\n        }\n    }\n\n    cpu_input_norm_thread.join();\n    ASSERT_TRUE(std::isfinite(cpu_input_norm.l_inf));\n    ASSERT_TRUE(std::isfinite(cpu_input_norm.l_2));\n\n    if(cpu_output_thread.joinable())\n        cpu_output_thread.join();\n    ASSERT_TRUE(std::isfinite(cpu_output_norm.l_inf));\n    ASSERT_TRUE(std::isfinite(cpu_output_norm.l_2));\n\n    SUCCEED();\n}\n", "meta": {"hexsha": "6e67a74e287d3bbf0f6bf260c28e3d7d39e9c7d0", "size": 30541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clients/tests/accuracy_test.cpp", "max_stars_repo_name": "alexshuang/rocFFT", "max_stars_repo_head_hexsha": "48d3d7daead41463efcec80f988408be812ecaf7", "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": "clients/tests/accuracy_test.cpp", "max_issues_repo_name": "alexshuang/rocFFT", "max_issues_repo_head_hexsha": "48d3d7daead41463efcec80f988408be812ecaf7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clients/tests/accuracy_test.cpp", "max_forks_repo_name": "alexshuang/rocFFT", "max_forks_repo_head_hexsha": "48d3d7daead41463efcec80f988408be812ecaf7", "max_forks_repo_licenses": ["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.3834688347, "max_line_length": 100, "alphanum_fraction": 0.4922563112, "num_tokens": 6281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19846836749957103}}
{"text": "/*=============================================================================\n    Copyright (c) 2009 Christopher Schmidt\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#ifndef BOOST_FUSION_VIEW_REVERSE_VIEW_DETAIL_AT_IMPL_HPP\n#define BOOST_FUSION_VIEW_REVERSE_VIEW_DETAIL_AT_IMPL_HPP\n\n#include <boost/fusion/support/config.hpp>\n#include <boost/fusion/sequence/intrinsic/at.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/int.hpp>\n\nnamespace boost { namespace fusion { namespace extension\n{\n    template <typename>\n    struct at_impl;\n\n    template <>\n    struct at_impl<reverse_view_tag>\n    {\n        template <typename Seq, typename N>\n        struct apply\n        {\n            typedef mpl::minus<typename Seq::size, mpl::int_<1>, N> real_n;\n\n            typedef typename\n                result_of::at<typename Seq::seq_type, real_n>::type\n            type;\n\n            BOOST_FUSION_GPU_ENABLED\n            static type\n            call(Seq& seq)\n            {\n                return fusion::at<real_n>(seq.seq);\n            }\n        };\n    };\n}}}\n\n#endif\n", "meta": {"hexsha": "ebad8f352475fa7e8b8fa7cd8dc92a06a505576d", "size": 1261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/fusion/view/reverse_view/detail/at_impl.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "3party/boost/boost/fusion/view/reverse_view/detail/at_impl.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/fusion/view/reverse_view/detail/at_impl.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 28.6590909091, "max_line_length": 80, "alphanum_fraction": 0.5622521808, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19846836749957103}}
{"text": "// Copyright (c) 2015-2021 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 \"duplicate_allele_fraction.hpp\"\n\n#include <algorithm>\n#include <iterator>\n#include <cassert>\n\n#include <boost/variant.hpp>\n\n#include \"io/variant/vcf_record.hpp\"\n#include \"allele_depth.hpp\"\n#include \"duplicate_allele_depth.hpp\"\n\nnamespace octopus { namespace csr {\n\nconst std::string DuplicateAlleleFraction::name_ = \"DAF\";\n\nstd::unique_ptr<Measure> DuplicateAlleleFraction::do_clone() const\n{\n    return std::make_unique<DuplicateAlleleFraction>(*this);\n}\n\nMeasure::ValueType DuplicateAlleleFraction::get_value_type() const\n{\n    return double {};\n}\n\nMeasure::ResultType DuplicateAlleleFraction::do_evaluate(const VcfRecord& call, const FacetMap& facets) const\n{\n    const auto allele_depths = boost::get<Array<Array<Optional<ValueType>>>>(AlleleDepth{}.evaluate(call, facets));\n    const auto duplicate_allele_depths = boost::get<Array<Array<Optional<ValueType>>>>(DuplicateAlleleDepth{}.evaluate(call, facets));\n    const auto num_alleles = call.alt().size() + 1;\n    assert(allele_depths.size() == duplicate_allele_depths.size());\n    Array<Array<Optional<ValueType>>> result(allele_depths.size(), Array<Optional<ValueType>>(num_alleles));\n    for (std::size_t s {0}; s < allele_depths.size(); ++s) {\n        assert(allele_depths[s].size() == num_alleles && duplicate_allele_depths[s].size() == num_alleles);\n        for (std::size_t a {0}; a < num_alleles; ++a) {\n            if (allele_depths[s][a] && duplicate_allele_depths[s][a]) {\n                const auto allele_depth = boost::get<std::size_t>(*allele_depths[s][a]);\n                if (allele_depth > 0) {\n                    result[s][a] = static_cast<double>(boost::get<std::size_t>(*duplicate_allele_depths[s][a])) / allele_depth;\n                } else {\n                    result[s][a] = 0.0;\n                }\n            }\n        }\n    }\n    return result;\n}\n\nMeasure::ResultCardinality DuplicateAlleleFraction::do_cardinality() const noexcept\n{\n    return ResultCardinality::samples_and_alleles;\n}\n\nconst std::string& DuplicateAlleleFraction::do_name() const\n{\n    return name_;\n}\n\nstd::string DuplicateAlleleFraction::do_describe() const\n{\n    return \"Fraction of realigned reads supporting ALT alleles identified as duplicates\";\n}\n\nstd::vector<std::string> DuplicateAlleleFraction::do_requirements() const\n{\n    \n    return {\"Samples\", \"OverlappingReads\", \"ReadAssignments\"};\n}\n\nboost::optional<Measure::Aggregator> DuplicateAlleleFraction::do_aggregator() const noexcept\n{\n    return Measure::Aggregator::max_tail;\n}\n\n} // namespace csr\n} // namespace octopus\n", "meta": {"hexsha": "c14a3d99cb7191d5c2f799e04a40420a218348df", "size": 2683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/csr/measures/duplicate_allele_fraction.cpp", "max_stars_repo_name": "Schaudge/octopus", "max_stars_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "src/core/csr/measures/duplicate_allele_fraction.cpp", "max_issues_repo_name": "Schaudge/octopus", "max_issues_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "src/core/csr/measures/duplicate_allele_fraction.cpp", "max_forks_repo_name": "Schaudge/octopus", "max_forks_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 33.1234567901, "max_line_length": 134, "alphanum_fraction": 0.6973537085, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "#include \"Avatar.h\"\n#include <string>\n#include <boost/filesystem.hpp>\n#include <cnpy.h>\n\n#include \"Version.h\"\n#include \"Util.h\"\n#include \"UtilCnpy.h\"\n\n#include \"internal/AvatarHelpers.h\"\n\nnamespace ark {\n// SMPL model loading code\nAvatarModel::AvatarModel(const std::string& model_dir,\n                         bool limit_one_joint_per_point)\n    : MODEL_DIR(model_dir) {\n    using namespace boost::filesystem;\n    path modelPath = model_dir.empty()\n                         ? util::resolveRootPath(\"data/avatar-model\")\n                         : model_dir;\n    path npzPath = modelPath / \"model.npz\";\n    path posePriorPath = modelPath / \"pose_prior.txt\";\n    if (exists(npzPath)) {\n        // New (npz) format\n        cnpy::npz_t npz = cnpy::npz_load(npzPath.string());\n        size_t n_verts = npz[\"v_template\"].shape[0];\n        size_t n_joints = npz[\"kintree_table\"].shape[1];\n        size_t n_faces = npz[\"f\"].shape[0];\n        size_t n_shape_blends = npz[\"shapedirs\"].shape[2];\n        size_t n_blend_shapes = n_shape_blends;\n\n        using util::assertShape;\n\n        // Load kintree\n        const auto& kttable_raw = npz.at(\"kintree_table\");\n        parent.resize(n_joints);\n        parent.noalias() = util::loadUintMatrix(kttable_raw, 2, n_joints)\n                               .template topRows<1>()\n                               .cast<int>()\n                               .transpose();\n        _ARK_ASSERT_EQ(parent[0], -1);\n\n        // Load base template\n        const auto& verts_raw = npz.at(\"v_template\");\n        assertShape(verts_raw, {n_verts, 3});\n        baseCloud.noalias() =\n            util::loadFloatMatrix(verts_raw, 1, n_verts * 3).transpose();\n\n        // Load triangle mesh\n        const auto& faces_raw = npz.at(\"f\");\n        assertShape(faces_raw, {n_faces, 3});\n        mesh =\n            util::loadUintMatrix(faces_raw, n_faces, 3).transpose().cast<int>();\n\n        // Load joint regressor\n        const auto& jreg_raw = npz.at(\"J_regressor\");\n        assertShape(jreg_raw, {n_joints, n_verts});\n        jointRegressor.resize(n_joints, n_verts);\n        jointRegressor = util::loadFloatMatrix(jreg_raw, n_joints, n_verts)\n                             .transpose()\n                             .sparseView();\n        jointRegressor.makeCompressed();\n\n        // Load LBS weights\n        const auto& wt_raw = npz.at(\"weights\");\n        assertShape(wt_raw, {n_verts, n_joints});\n        weights.resize(n_joints, n_verts);\n        weights = util::loadFloatMatrix(wt_raw, n_verts, n_joints)\n                      .transpose()\n                      .sparseView();\n        weights.makeCompressed();\n\n        // (Compatibility with existing code)\n        assignedJoints.resize(n_verts);\n        assignedPoints.resize(n_joints);\n        for (int k = 0; k < weights.outerSize(); ++k) {\n            for (Eigen::SparseMatrix<double>::InnerIterator it(weights, k); it;\n                 ++it) {\n                int r = it.row(), c = it.col();\n                double wt = it.value();\n                if (wt > 1e-12) {\n                    assignedJoints[c].push_back({wt, r});\n                    assignedPoints[r].push_back({wt, c});\n                }\n            }\n        }\n        for (int i = 0; i < n_joints; ++i) {\n            std::sort(assignedPoints[i].begin(), assignedPoints[i].end(),\n                      std::greater<std::pair<double, int>>());\n        }\n        for (int i = 0; i < n_verts; ++i) {\n            std::sort(assignedJoints[i].begin(), assignedJoints[i].end(),\n                      std::greater<std::pair<double, int>>());\n        }\n\n        // Blend shapes\n        keyClouds.resize(3 * n_verts, n_blend_shapes);\n        // Load shape-dep blend shapes\n        const auto& sb_raw = npz.at(\"shapedirs\");\n        assertShape(sb_raw, {n_verts, 3, n_shape_blends});\n        keyClouds.leftCols(n_shape_blends).noalias() =\n            util::loadFloatMatrix(sb_raw, 3 * n_verts, n_shape_blends);\n\n        // Load pose-dep blend shapes\n        // (currently not used for efficiency reasons)\n        // const auto& pb_raw = npz.at(\"posedirs\");\n        // assertShape(pb_raw, {n_verts, 3, n_pose_blends});\n        // keyClouds.template rightCols<n_pose_blends>().noalias() =\n        //     util::loadFloatMatrix(pb_raw, 3 * n_verts, n_pose_blends);\n\n        // Compute the joint shape regressor\n        useJointShapeRegressor = true;\n        initialJointPos.noalias() =\n            Eigen::Map<Eigen::Matrix<double, 3, Eigen::Dynamic>>(\n                baseCloud.data(), 3, n_verts) *\n            jointRegressor;\n        jointShapeRegBase.noalias() = Eigen::template Map<Eigen::VectorXd>(\n            initialJointPos.data(),\n            initialJointPos.rows() * initialJointPos.cols(), 1);\n        jointShapeReg.resize(3 * n_joints, n_shape_blends);\n        for (int i = 0; i < n_shape_blends; ++i) {\n            Eigen::Map<Eigen::Matrix<double, 3, Eigen::Dynamic>> keyVertsIn(\n                keyClouds.col(i).data(), 3, n_verts);\n            Eigen::Map<Eigen::Matrix<double, 3, Eigen::Dynamic>> jointsOut(\n                jointShapeReg.col(i).data(), 3, n_joints);\n            jointsOut.noalias() = keyVertsIn * jointRegressor;\n        }\n    } else {\n        std::cerr << \"WARNING: Using deprecated ad-hoc SMPL model format; \"\n                     \"please download SMPL .npz model and place it at \"\n                     \"data/avatar-model/model.npz\\n\";\n        // Old ad-hoc format\n        path skelPath = modelPath / \"skeleton.txt\";\n        path jrPath = modelPath / \"joint_regressor.txt\";\n        path jsrPath = modelPath / \"joint_shape_regressor.txt\";\n        path meshPath = modelPath / \"mesh.txt\";\n\n        baseCloud =\n            loadPCDToPointVectorFast((modelPath / \"model.pcd\").string());\n\n        int nJoints, nPoints;\n        // Read skeleton file\n        std::ifstream skel(skelPath.string());\n        if (!skel) {\n            std::cerr\n                << \"ERROR: Avatar model is invalid, skeleton file not found\\n\";\n            std::exit(0);\n        }\n        skel >> nJoints >> nPoints;\n\n        // Assume joints are given in topologically sorted order\n        parent.resize(nJoints);\n        initialJointPos.resize(3, nJoints);\n        for (int i = 0; i < nJoints; ++i) {\n            int id;\n            std::string _name;  // throw away\n\n            skel >> id;\n            skel >> parent[id];\n            skel >> _name >> initialJointPos(0, i) >> initialJointPos(1, i) >>\n                initialJointPos(2, i);\n        }\n        parent[0] =\n            -1;  // This should be in skeleton file, but just to make sure\n\n        if (!skel) {\n            std::cerr\n                << \"ERROR: Invalid avatar skeleton file: joint assignments \"\n                   \"are not present\\n\";\n            std::exit(0);\n        }\n\n        // Process joint assignments\n        weights.resize(nJoints, nPoints);\n        weights.reserve(3 * nPoints);\n        assignedPoints.resize(nJoints);\n        for (int i = 0; i < nJoints; ++i) {\n            assignedPoints[i].reserve(7000 / nJoints);\n        }\n        assignedJoints.resize(nPoints);\n        for (int i = 0; i < nPoints; ++i) {\n            int nEntries;\n            skel >> nEntries;\n            assignedJoints[i].reserve(nEntries);\n            for (int j = 0; j < nEntries; ++j) {\n                int joint;\n                double w;\n                skel >> joint >> w;\n                assignedJoints[i].emplace_back(w, joint);\n                weights.insert(joint, i) = w;\n            }\n            std::sort(assignedJoints[i].begin(), assignedJoints[i].end(),\n                      [](const std::pair<double, int>& a,\n                         const std::pair<double, int>& b) {\n                          return a.first > b.first;\n                      });\n            if (limit_one_joint_per_point) {\n                assignedJoints[i].resize(1);\n                assignedJoints[i].shrink_to_fit();\n                assignedJoints[i][0].first = 1.0;\n                assignedPoints[assignedJoints[i][0].second].emplace_back(1.0,\n                                                                         i);\n            } else {\n                for (int j = 0; j < nEntries; ++j) {\n                    assignedPoints[assignedJoints[i][j].second].emplace_back(\n                        assignedJoints[i][j].first, i);\n                }\n            }\n        }\n\n        // Load all shape keys\n        path keyPath = modelPath / \"shapekey\";\n        if (is_directory(keyPath)) {\n            int nShapeKeys = 0;\n            for (directory_iterator it(keyPath); it != directory_iterator();\n                 ++it)\n                ++nShapeKeys;\n            keyClouds.resize(3 * nPoints, nShapeKeys);\n\n            int i = 0;\n            for (directory_iterator it(keyPath); it != directory_iterator();\n                 ++it) {\n                keyClouds.col(i) =\n                    loadPCDToPointVectorFast(it->path().string());\n                ++i;\n            }\n        } else {\n            std::cerr << \"WARNING: no shape key directory found for avatar\\n\";\n        }\n\n        // Load joint regressor / joint shape regressor\n        std::ifstream jsr(jsrPath.string());\n        if (jsr) {\n            int nShapeKeys;\n            jsr >> nShapeKeys;\n            jointShapeRegBase.resize(nJoints * 3);\n            jointShapeReg.resize(nJoints * 3, nShapeKeys);\n            for (int i = 0; i < jointShapeRegBase.rows(); ++i) {\n                jsr >> jointShapeRegBase(i);\n            }\n            for (int i = 0; i < jointShapeReg.rows(); ++i) {\n                for (int j = 0; j < jointShapeReg.cols(); ++j) {\n                    jsr >> jointShapeReg(i, j);\n                }\n            }\n            useJointShapeRegressor = true;\n            jsr.close();\n        } else {\n            std::ifstream jr(jrPath.string());\n            jointRegressor = Eigen::SparseMatrix<double>(nPoints, nJoints);\n            if (jr) {\n                jr >> nJoints;\n                jointRegressor.reserve(nJoints * 10);\n                for (int i = 0; i < nJoints; ++i) {\n                    int nEntries;\n                    jr >> nEntries;\n                    int pointIdx;\n                    double val;\n                    for (int j = 0; j < nEntries; ++j) {\n                        jr >> pointIdx >> val;\n                        jointRegressor.insert(pointIdx, i) = val;\n                    }\n                }\n                jr.close();\n            } else {\n                std::cerr << \"WARNING: neither joint regressor nor joint shape \"\n                             \"regressor found, model may be inaccurate with \"\n                             \"nonzero shapekey weights\\n\";\n            }\n            useJointShapeRegressor = false;\n        }\n\n        // Maybe load mesh\n        std::ifstream meshFile(meshPath.string());\n        if (meshFile) {\n            int nFaces;\n            meshFile >> nFaces;\n            mesh.resize(3, nFaces);\n            for (int i = 0; i < nFaces; ++i) {\n                meshFile >> mesh(0, i) >> mesh(1, i) >> mesh(2, i);\n            }\n        } else {\n            std::cerr\n                << \"WARNING: mesh not found, maybe you are using an older \"\n                   \"version of avatar data files? \"\n                   \"Some functions will not work.\\n\";\n        }\n    }\n\n    size_t totalAssignments = 0;\n    for (size_t i = 0; i < assignedJoints.size(); ++i) {\n        totalAssignments += assignedJoints[i].size();\n    }\n\n    // Maybe load pose prior\n    posePrior.load(posePriorPath.string());\n}\n}  // namespace ark\n", "meta": {"hexsha": "bc6227663bc688be93086a18612e59c7396bb5dc", "size": 11523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AvatarModel.cpp", "max_stars_repo_name": "jyuatsfl/avatar", "max_stars_repo_head_hexsha": "8bbb5d72fda0857e04d0c76329f32162f6d98a92", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T09:47:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T01:41:28.000Z", "max_issues_repo_path": "AvatarModel.cpp", "max_issues_repo_name": "SFM2020/avatar", "max_issues_repo_head_hexsha": "8c03dbdf4eed15219797285dbac6ca04e8f1b6f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-07-08T03:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T12:24:33.000Z", "max_forks_repo_path": "AvatarModel.cpp", "max_forks_repo_name": "SFM2020/avatar", "max_forks_repo_head_hexsha": "8c03dbdf4eed15219797285dbac6ca04e8f1b6f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-06-10T09:47:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T09:54:46.000Z", "avg_line_length": 38.5384615385, "max_line_length": 80, "alphanum_fraction": 0.5084613382, "num_tokens": 2746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19846836176953064}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2014-2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, 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_ALGORITHMS_DETAIL_DISTANCE_LINEAR_OR_AREAL_TO_AREAL_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_LINEAR_OR_AREAL_TO_AREAL_HPP\n\n#include <boost/geometry/algorithms/detail/distance/linear_to_linear.hpp>\n#include <boost/geometry/algorithms/detail/distance/strategy_utils.hpp>\n#include <boost/geometry/algorithms/intersects.hpp>\n\n#include <boost/geometry/core/point_type.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace distance\n{\n\n\ntemplate <typename Linear, typename Areal, typename Strategies>\nstruct linear_to_areal\n{\n    typedef distance::return_t<Linear, Areal, Strategies> return_type;\n\n    static inline return_type apply(Linear const& linear,\n                                    Areal const& areal,\n                                    Strategies const& strategies)\n    {\n        if ( geometry::intersects(linear, areal, strategies) )\n        {\n            return return_type(0);\n        }\n\n        return linear_to_linear\n            <\n                Linear, Areal, Strategies\n            >::apply(linear, areal, strategies, false);\n    }\n\n\n    static inline return_type apply(Areal const& areal,\n                                    Linear const& linear,\n                                    Strategies const& strategies)\n    {\n        return apply(linear, areal, strategies);\n    }\n};\n\ntemplate <typename Areal1, typename Areal2, typename Strategies>\nstruct areal_to_areal\n{\n    typedef distance::return_t<Areal1, Areal2, Strategies> return_type;\n\n    static inline return_type apply(Areal1 const& areal1,\n                                    Areal2 const& areal2,\n                                    Strategies const& strategies)\n    {\n        if ( geometry::intersects(areal1, areal2, strategies) )\n        {\n            return return_type(0);\n        }\n\n        return linear_to_linear\n            <\n                Areal1, Areal2, Strategies\n            >::apply(areal1, areal2, strategies, false);\n    }\n};\n\n\n}} // namespace detail::distance\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate <typename Linear, typename Areal, typename Strategy>\nstruct distance\n    <\n        Linear, Areal, Strategy,\n        linear_tag, areal_tag, \n        strategy_tag_distance_point_segment, false\n    >\n    : detail::distance::linear_to_areal\n        <\n            Linear, Areal, Strategy\n        >\n{};\n\ntemplate <typename Areal, typename Linear, typename Strategy>\nstruct distance\n    <\n        Areal, Linear, Strategy,\n        areal_tag, linear_tag, \n        strategy_tag_distance_point_segment, false\n    >\n    : detail::distance::linear_to_areal\n        <\n            Linear, Areal, Strategy\n        >\n{};\n\n\ntemplate <typename Areal1, typename Areal2, typename Strategy>\nstruct distance\n    <\n        Areal1, Areal2, Strategy,\n        areal_tag, areal_tag, \n        strategy_tag_distance_point_segment, false\n    >\n    : detail::distance::areal_to_areal\n        <\n            Areal1, Areal2, Strategy\n        >\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_LINEAR_OR_AREAL_TO_AREAL_HPP\n", "meta": {"hexsha": "e4cb41a358bd0f9b9e7d9db3d67495623e1f12f0", "size": 3623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/algorithms/detail/distance/linear_or_areal_to_areal.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/algorithms/detail/distance/linear_or_areal_to_areal.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/algorithms/detail/distance/linear_or_areal_to_areal.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": 26.4452554745, "max_line_length": 80, "alphanum_fraction": 0.6549820591, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.19844911642067464}}
{"text": "#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC push_options\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx\")\n#include<bits/stdc++.h>\n//#include <xmmintrin.h>\n//#include <immintrin.h>\nusing namespace::std;\n__attribute__((constructor))void init(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(15);}\n//#include<ext/pb_ds/assoc_container.hpp>\n//#include<ext/pb_ds/tree_policy.hpp>\n//#include <ext/pb_ds/priority_queue.hpp>\n//#include<ext/pb_ds/tag_and_trait.hpp>\n// #include <boost/multiprecision/cpp_dec_float.hpp>\n// #include <boost/multiprecision/cpp_int.hpp>\n// namespace mp = boost::multiprecision;\n// typedef mp::number<mp::cpp_dec_float<0>> cdouble;\n// typedef mp::cpp_int cint;\n//template<typename T>using pbds=__gnu_pbds::tree<T,__gnu_pbds::null_type,less<T>,__gnu_pbds::rb_tree_tag,__gnu_pbds::tree_order_statistics_node_update>;\n//template<typename T>using pbds_map=__gnu_pbds::tree<T,T,less<T>,__gnu_pbds::rb_tree_tag,__gnu_pbds::tree_order_statistics_node_update>;\n//template<typename T,typename E>using hash_map=__gnu_pbds::gp_hash_table<T,E>;\n//template<typename T>using pqueue =__gnu_pbds::priority_queue<T, greater<T>,__gnu_pbds::rc_binomial_heap_tag>;\ntypedef int lint;\n#define INF (1LL<<30)\n#define IINF (1<<30)\n#define EPS (1e-10)\n#define endl ('\\n')\n#define MOD 1000000007LL\n//#define MOD 998244353LL\ntypedef vector<lint> vec;\ntypedef vector<vector<lint>> mat;\ntypedef vector<vector<vector<lint>>> mat3;\ntypedef vector<string> svec;\ntypedef vector<vector<string>> smat;\ntemplate<typename T>inline void numout(T t){bool f=0;for(auto i:t){cout<<(f?\" \":\"\")<<i<INF/2?i:\"INF\";f=1;}cout<<endl;}\ntemplate<typename T>inline void numout2(T t){for(auto i:t)numout(i);}\ntemplate<typename T>inline void output(T t){bool f=0;for(auto i:t){cout<<(f?\" \":\"\")<<i;f=1;}cout<<endl;}\ntemplate<typename T>inline void output2(T t){for(auto i:t)output(i);}\ntemplate<typename T>inline void _output(T t){bool f=0;for(lint i=0;i<t.size();i++){cout<<f?\"\":\" \"<<t[i];f=1;}cout<<endl;}\ntemplate<typename T>inline void _output2(T t){for(lint i=0;i<t.size();i++)output(t[i]);}\n#define rep(i,n) for(lint i=0;i<lint(n);++i)\n#define repi(i,a,b) for(lint i=lint(a);i<(lint)(b);++i)\n#define rrep(i,n) for(lint i=lint(n)-1;i>=0;--i)\n#define rrepi(i,a,b) for(lint i=lint(b)-1;i>=lint(a);--i)\n#define irep(i) for(lint i=0;;++i)\n#define all(n) begin(n),end(n)\n#define dist(a,b,c,d) sqrt(pow(a-c,2)+pow(b-d,2))\ninline lint gcd(lint A,lint B){return B?gcd(B,A%B):A;}\ninline lint lcm(lint A,lint B){return A/gcd(A,B)*B;}\n// inline cint cgcd(cint A,cint B){return B?cgcd(B,A%B):A;}\n// inline cint clcm(cint A,cint B){return A/cgcd(A,B)*B;}\nbool chmin(auto& s,const auto& t){bool res=s>t;s=min(s,t);return res;}\nbool chmax(auto& s,const auto& t){bool res=s<t;s=max(s,t);return res;}\nconst vector<lint> dx={1,0,-1,0,1,1,-1,-1};\nconst vector<lint> dy={0,1,0,-1,-1,1,-1};\n#define SUM(v) accumulate(all(v),0LL)\nauto call=[](auto f,auto... args){return f(f,args...);};\n\nunsigned long xor128(){ \n    static unsigned long x=123456789,y=362436069,z=521288629,w=88675123; \n    unsigned long t; \n    t=(x^(x<<11));x=y;y=z;z=w; return( w=(w^(w>>19))^(t^(t>>8)) ); \n} \n\ndouble timer(auto f){\n    auto s=chrono::system_clock::now();\n    f();\n    auto e=chrono::system_clock::now();\n    return std::chrono::duration_cast<std::chrono::milliseconds>(e-s).count(); \n}\n\nint main(){\n    lint h,w;\n    cin>>w>>h;\n    cin.ignore();\n    vector<string>s(h);\n    rep(i,h){\n        getline(cin,s[i]);\n    }\n    lint idx=0;\n    vector<vector<lint>> point(h,vector<lint>(w));\n    // game loop\n    vector<lint>pre(5,0);\n    auto f=[&](){\n        int myScore;\n        int opponentScore;\n        cin >> myScore >> opponentScore; cin.ignore();\n        int visiblePacCount; // all your pacs and enemy pacs in sight\n        cin >> visiblePacCount; cin.ignore();\n        vector<pair<lint,lint>> enemy;\n        vector<tuple<lint,lint,lint>> player;\n        for (int i = 0; i < visiblePacCount; i++) {\n            int pacId; // pac number (unique within a team)\n            bool mine; // true if this pac is yours\n            int _x; // position in the grid\n            int _y; // position in the grid\n            string typeId; // unused in wood leagues\n            int speedTurnsLeft; // unused in wood leagues\n            int abilityCooldown; // unused in wood leagues\n            cin >> pacId >> mine >> _y >> _x >> typeId >> speedTurnsLeft >> abilityCooldown; cin.ignore();\n            if(mine){\n                player.emplace_back(_x,_y,pacId);\n            }else{\n                enemy.emplace_back(_x,_y);\n            }\n        }\n        vector<vector<lint>>v(player.size(),vec(4,0));\n        for(auto e:enemy){\n            rep(i,player.size()){\n                lint mx=get<0>(player[i]),my=get<1>(player[i]);\n                rep(j,4){\n                    lint x=(mx+dx[j]+h)%h,y=(my+dy[j]+w)%w;\n                    while(x>=h)x-=h;\n                    while(y>=w)y-=w;\n                    if((abs(x-e.first)+abs(y-e.second))<=1){\n                        v[i][j]--;\n                    }\n                }\n            }\n        }\n        rep(k,player.size()){\n            rep(i,player.size()){\n                lint mx=get<0>(player[i]),my=get<1>(player[i]);\n                lint ex=get<0>(player[k]),ey=get<1>(player[k]);\n                rep(j,4){\n                    lint x=(mx+dx[j]+h)%h,y=(my+dy[j]+w)%w;\n                    if((abs(x-ex)+abs(y-ey))<=1){\n                        v[i][j]--;\n                    }\n                }\n            }\n        }\n        int pellet; // all pellets in sight\n        cin >> pellet; cin.ignore();\n        rep(k,pellet){\n            int x;\n            int y;\n            int value; // amount of points this pellet is worth\n            cin >> y >> x >> value; cin.ignore();\n            rep(i,player.size()){\n                lint mx=get<0>(player[i]),my=get<1>(player[i]);\n                rep(j,4){\n                    lint tx=(mx+dx[j]+h)%h,ty=(my+dy[j]+w)%w;\n                    if((abs(tx-x)+abs(ty-y))==0)v[i][j]+=value;\n                }\n            }\n        }\n        rep(k,player.size()){\n            v[k][(pre[k]+2)&3]--;\n            lint mx=get<0>(player[k]),my=get<1>(player[k]);\n            tuple<lint,lint,lint> mn=make_tuple(-INF,mx,my);\n            rep(i,4){\n                lint tx=(mx+dx[i]+h)%h,ty=(my+dy[i]+w)%w;\n                if(s[tx][ty]=='#')continue;\n                if(get<0>(mn)<=v[k][i]){\n                    mn=make_tuple(v[k][i],tx,ty);\n                    pre[get<2>(player[k])]=i;\n                }\n            }\n            if(get<0>(mn)<0){\n                vector<lint>tmp;\n                rep(j,4){\n                    lint tx=(mx+dx[j]+h)%h,ty=(my+dy[j]+w)%w;\n                    if(s[tx][ty]=='#')continue;\n                    if(v[k][j]==0){\n                        tmp.push_back(j);\n                    }\n                }\n                if(tmp.size()==0){\n                    tmp.push_back(pre[k]);\n                }\n                lint i=tmp[myScore%tmp.size()];\n                mn=make_tuple(v[k][i],(mx+dx[i]+h)%h,(my+dy[i]+w)%w);\n                pre[get<2>(player[k])]=i;\n                idx=(idx+i)%4;\n            }\n            //point[get<2>(mn)][get<1>(mn)]+=v[mx][my]*0.3;\n            //point[get<2>(mn)][get<1>(mn)]--;\n            if(k)cout<<\"|\";\n            cout<<\"MOVE \"<<get<2>(player[k])<<\" \"<<get<2>(mn)<<\" \"<<get<1>(mn);\n        }\n        cout<<endl;\n         // MOVE <pacId> <x> <y>\n    };\n    while(1){\n        cerr<<timer(f)<<endl;\n    }\n}", "meta": {"hexsha": "d0f01c3303de1dd73eba351fe48060026874b878", "size": 7547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "oldlib/codingame/temp.cpp", "max_stars_repo_name": "hotman78/cpplib", "max_stars_repo_head_hexsha": "c2f85c8741cdd0b731a5aa828b28b38c70c8d699", "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": "oldlib/codingame/temp.cpp", "max_issues_repo_name": "hotman78/cpplib", "max_issues_repo_head_hexsha": "c2f85c8741cdd0b731a5aa828b28b38c70c8d699", "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": "oldlib/codingame/temp.cpp", "max_forks_repo_name": "hotman78/cpplib", "max_forks_repo_head_hexsha": "c2f85c8741cdd0b731a5aa828b28b38c70c8d699", "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": 40.1436170213, "max_line_length": 153, "alphanum_fraction": 0.531734464, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1982999913425756}}
{"text": "#include \"alexandria.hpp\"\n\n#include <iostream>\n\n#include <boost/algorithm/string.hpp>\n\n#include <sophiatx/utilities/key_conversion.hpp>\n#include <sophiatx/protocol/transaction.hpp>\n\n#include <fc/io/json.hpp>\n#include <fc/real128.hpp>\n#include <fc/crypto/base58.hpp>\n#include <fc/crypto/aes.hpp>\n#include <fc/crypto/rand.hpp>\n#include <fc/crypto/hex.hpp>\n#include <fc/api.hpp>\n\n\nusing namespace sophiatx::utilities;\nusing namespace sophiatx::protocol;\nusing namespace fc::ecc;\nusing namespace std;\n\nnamespace {\n\nstruct memo_data {\n\n   static std::optional<memo_data> from_string( string str ) {\n      try {\n         if( str.size() > sizeof(memo_data)) {\n            auto data = fc::from_base58( str );\n            auto m  = fc::raw::unpack_from_vector<memo_data>( data, 0 );\n            FC_ASSERT( string(m) == str );\n            return m;\n         }\n      } catch ( ... ) {}\n      return std::optional<memo_data>();\n   }\n\n   int64_t         nonce = 0;\n   uint64_t        check = 0;\n   vector<char>    encrypted;\n\n   operator string()const {\n      auto data = fc::raw::pack_to_vector(*this);\n      auto base58 = fc::to_base58( data );\n      return base58;\n   }\n};\n\n\nbool generate_private_key(char *private_key, char *public_key) {\n   try {\n      private_key_type priv_key = fc::ecc::private_key::generate();\n      public_key_type pub_key = priv_key.get_public_key();\n      strcpy(private_key, key_to_wif(priv_key).c_str());\n      auto public_key_str = fc::json::to_string(pub_key);\n      strcpy(public_key, public_key_str.substr(1, public_key_str.size() - 2).c_str());\n      return true;\n   } catch (const fc::exception& e) {\n      return false;\n   }\n}\n\nbool get_public_key(const char *private_key, char *public_key) {\n   if(private_key) {\n      try {\n         auto priv_key = sophiatx::utilities::wif_to_key(string(private_key));\n         if(priv_key) {\n            public_key_type pub_key = priv_key->get_public_key();\n            auto public_key_str = fc::json::to_string(pub_key);\n            strcpy(public_key, public_key_str.substr(1, public_key_str.size() - 2).c_str());\n            return true;\n         }\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\nbool generate_key_pair_from_brain_key(const char *brain_key, char *private_key, char *public_key) {\n   if(brain_key) {\n      try {\n         fc::sha512 h = fc::sha512::hash(string(brain_key) + \" 0\");\n         auto priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h));\n         public_key_type pub_key = priv_key.get_public_key();\n         strcpy(private_key, key_to_wif(priv_key).c_str());\n         auto public_key_str = fc::json::to_string(pub_key);\n         strcpy(public_key, public_key_str.substr(1, public_key_str.size() - 2).c_str());\n         return true;\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\nbool get_transaction_digest(const char *transaction, const char *chain_id, char *digest) {\n   if(transaction && chain_id) {\n      try {\n         string tx_str(transaction);\n         fc::variant v = fc::json::from_string( tx_str, fc::json::strict_parser );\n         signed_transaction stx;\n         fc::from_variant( v, stx);\n         digest_type dig = stx.sig_digest(fc::sha256(string(chain_id)));\n         strcpy(digest, dig.str().c_str());\n         return true;\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\nbool sign_digest(const char *digest, const char *private_key, char *signed_digest) {\n   if(digest && private_key) {\n      try {\n         fc::sha256 dig(string(digest, strlen(digest)));\n         string private_k_str(private_key);\n         auto priv_key = sophiatx::utilities::wif_to_key(private_k_str);\n         if(priv_key) {\n            auto sig = priv_key->sign_compact(dig, fc::ecc::bip_0062);\n            string result = fc::json::to_string(sig);\n            strcpy(signed_digest, result.substr(1, result.size() - 2).c_str());\n            return true;\n         }\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\nbool add_signature(const char *transaction, const char *signature, char *signed_tx) {\n   if(transaction && signature) {\n      try {\n         string tx_str(transaction);\n         fc::variant v = fc::json::from_string( tx_str, fc::json::strict_parser );\n         signed_transaction stx;\n         fc::from_variant( v, stx );\n\n         compact_signature sig;\n         fc::from_hex( string(signature), (char*)sig.begin(), sizeof(compact_signature) );\n\n         stx.signatures.push_back(sig);\n         strcpy(signed_tx, fc::json::to_string(stx).c_str());\n         return true;\n\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\nbool verify_signature(const char *digest, const char *public_key, const char *signed_digest) {\n   if(digest && public_key && signed_digest) {\n      try {\n         fc::sha256 dig(string(digest, strlen(digest)));\n\n         fc::variant v = fc::json::from_string( string(public_key), fc::json::relaxed_parser );\n         public_key_type pub_key;\n         fc::from_variant( v, pub_key );\n\n         compact_signature sig;\n         fc::from_hex( string(signed_digest), (char*)sig.begin(), sizeof(compact_signature) );\n\n         if(pub_key == fc::ecc::public_key::recover_key(sig, dig, fc::ecc::bip_0062)) {\n            return true;\n         }\n\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\n\nbool encrypt_memo(const char *memo, const char *private_key, const char *public_key, char *encrypted_memo) {\n   if(memo && private_key && public_key) {\n      try {\n         memo_data m;\n\n         auto priv_key = sophiatx::utilities::wif_to_key(string(private_key));\n\n         if(priv_key) {\n            fc::variant v = fc::json::from_string( string(public_key), fc::json::relaxed_parser );\n            public_key_type pub_key;\n            fc::from_variant( v, pub_key );\n\n            m.nonce = fc::time_point::now().time_since_epoch().count();\n\n            auto shared_secret = priv_key->get_shared_secret( pub_key );\n\n            fc::sha512::encoder enc;\n            fc::raw::pack( enc, m.nonce );\n            fc::raw::pack( enc, shared_secret );\n            auto encrypt_key = enc.result();\n\n            m.encrypted = fc::aes_encrypt( encrypt_key, fc::raw::pack_to_vector(string(memo)) );\n            m.check = fc::sha256::hash( encrypt_key )._hash[0];\n            strcpy(encrypted_memo, string(m).c_str());\n            return true;\n         }\n\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\nbool decrypt_memo(const char *memo, const char *private_key, const char* public_key, char *decrypted_memo) {\n   if(memo && private_key) {\n      try {\n         string str_memo(memo);\n         auto m = memo_data::from_string( str_memo );\n\n         if( m ) {\n            fc::sha512 shared_secret;\n            auto priv_key = sophiatx::utilities::wif_to_key(string(private_key));\n            if(priv_key) {\n               fc::variant v = fc::json::from_string( string(public_key), fc::json::relaxed_parser );\n               public_key_type pub_key;\n               fc::from_variant( v, pub_key );\n\n               shared_secret = priv_key->get_shared_secret(pub_key);\n\n               fc::sha512::encoder enc;\n               fc::raw::pack( enc, m->nonce );\n               fc::raw::pack( enc, shared_secret );\n               auto encryption_key = enc.result();\n\n               uint64_t check = fc::sha256::hash( encryption_key )._hash[0];\n               if( check != m->check ) return false;\n\n               vector<char> decrypted = fc::aes_decrypt( encryption_key, m->encrypted );\n               strcpy(decrypted_memo, fc::raw::unpack_from_vector<std::string>( decrypted, 0 ).c_str());\n\n               return true;\n            }\n         }\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\nbool get_shared_secret(const char *private_key, const char* public_key, char *shared_secret) {\n   if(public_key && private_key) {\n      try {\n            fc::sha512 shared_sec;\n            auto priv_key = sophiatx::utilities::wif_to_key(string(private_key));\n            if(priv_key) {\n               fc::variant v = fc::json::from_string( string(public_key), fc::json::relaxed_parser );\n               public_key_type pub_key;\n               fc::from_variant( v, pub_key );\n\n               shared_sec = priv_key->get_shared_secret(pub_key);\n               strcpy(shared_secret, shared_sec.str().c_str());\n\n               return true;\n         }\n      } catch (const fc::exception& e) {\n         return false;\n      }\n   }\n   return false;\n}\n\nbool base64_decode(const char *input, char *output) {\n   try {\n      auto out = fc::base64_decode(string(input));\n      strcpy(output, out.c_str());\n   } catch (const fc::exception& e) {\n      return false;\n   }\n   return true;\n}\n\nbool base64_encode(const char *input, char *output) {\n   try {\n      auto out = fc::base64_encode(string(input));\n      strcpy(output, out.c_str());\n   } catch (const fc::exception& e) {\n      return false;\n   }\n   return true;\n}\n\n} //\n\nFC_REFLECT( memo_data, (nonce)(check)(encrypted) )\n", "meta": {"hexsha": "da6ca6220b8371337ea9caf16f4834d76f4083b4", "size": 9246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/alexandria/alexandria.cpp", "max_stars_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_stars_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-07-25T20:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T03:14:09.000Z", "max_issues_repo_path": "programs/alexandria/alexandria.cpp", "max_issues_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_issues_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T17:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-25T13:38:11.000Z", "max_forks_repo_path": "programs/alexandria/alexandria.cpp", "max_forks_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_forks_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-07-25T14:34:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-03T13:29:37.000Z", "avg_line_length": 31.1313131313, "max_line_length": 108, "alphanum_fraction": 0.5986372485, "num_tokens": 2256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.19829998741013213}}
{"text": "#pragma once\n\n#include \"MPU9255.hpp\"\n#include <boost/endian/arithmetic.hpp>\n#include <Eigen/Dense>\n\nnamespace icarus\n{\n    namespace mpu9255 {\n        enum ActiveLevel : uint8_t\n        {\n            high,\n            low,\n        };\n\n        enum PinMode : uint8_t\n        {\n            pushPull,\n            openDrain,\n        };\n\n        enum class AccelerometerRange : uint8_t\n        {\n            g2,\n            g4,\n            g8,\n            g16,\n        };\n\n        enum class GyroscopeRange : uint8_t\n        {\n            dps250,\n            dps500,\n            dps1000,\n            dps2000,\n        };\n\n        enum class ClockSource : uint8_t\n        {\n            internal20MHz = 0,\n            bestAvailable = 1,\n            stopped = 7\n        };\n\n        struct SampleRateDivider\n        {\n            enum { address = 25 };\n            uint8_t divider;\n        };\n\n        struct Configuration\n        {\n            enum { address = 26 };\n            uint8_t digitalLowPassFilter : 3;\n            uint8_t fSync : 3;\n            uint8_t fifoMode : 1;\n        };\n\n        struct AccelerometerConfiguration1\n        {\n            enum { address = 28 };\n            uint8_t : 3;\n            AccelerometerRange fullScaleSelect : 2;\n            bool zAxisSelfTest : 1;\n            bool yAxisSelfTest : 1;\n            bool xAxisSelfTest : 1;\n        };\n\n        struct AccelerometerConfiguration2\n        {\n            enum { address = 29 };\n            uint8_t digitalLowPassFilterConfiguration : 3;\n            bool disableLowPassFilter : 1;\n        };\n\n        struct GyroscopeConfiguration\n        {\n            enum { address = 27 };\n            uint8_t fChoiceB : 2;\n            uint8_t : 1;\n            GyroscopeRange fullScaleRange : 2;\n            bool zAxisSelfTest : 1;\n            bool yAxisSelfTest : 1;\n            bool xAxisSelfTest : 1;\n        };\n\n        struct TemperatureRegister\n        {\n            enum { address = 65 };\n            boost::endian::big_int16_t temperature;\n        };\n\n        struct AccelerometerMeasurements\n        {\n            enum { address = 59 };\n            Eigen::Matrix<boost::endian::big_int16_t, 3, 1> acceleration;\n        };\n\n        struct GyroscopeMeasurements\n        {\n            enum { address = 67 };\n            Eigen::Matrix<boost::endian::big_int16_t, 3, 1> angularVelocity;\n        };\n\n        struct InterruptBypassConfiguration\n        {\n            enum { address = 55 };\n\n            uint8_t : 1;\n            bool enableBypass : 1;\n            bool enableFsyncInterrupt : 1;\n            ActiveLevel fsyncActiveLevel : 1;\n            bool clearInterruptOnRead : 1;\n            bool latchInterrputPin : 1;\n            PinMode interruptPinMode : 1;\n            ActiveLevel interruptPinLevel : 1;\n        };\n\n        struct PowerManagement1\n        {\n            enum { address = 107 };\n            ClockSource clockSelect : 3;\n            bool powerDownProportionalToAbsoulteTemperatureVoltageGenerator : 1;\n            bool gyroscopeStandby : 1;\n            bool cycle : 1;\n            bool sleep : 1;\n            bool hardReset : 1;\n        };\n\n        struct WhoAmI\n        {\n            enum { address = 117 };\n            uint8_t id;\n        };\n    }\n\n    template<typename RegisterBank>\n    MPU9255<RegisterBank>::MPU9255(RegisterBank * device) :\n        mDevice(device),\n        mGyroscopeScaleRange(0)\n    {}\n\n    template<typename RegisterBank>\n    void MPU9255<RegisterBank>::initialize()\n    {\n        using namespace mpu9255;\n\n        mDevice->template read<WhoAmI>([](auto & reg){\n            if (reg.id != 0x73) {\n                std::stringstream ss;\n                    ss << \"Unrecognized device on the bus. Expected MPU9255: id: \"\n                    << std::hex << 0x73 << \", got: \" << int(reg.id);\n                throw std::runtime_error(ss.str());\n            }\n        });\n\n        mDevice->template write<AccelerometerConfiguration1>([](auto & config) {\n            config.fullScaleSelect = AccelerometerRange::g8;\n        });\n        constexpr float STANDARD_GRAVITY =  9.80665;\n        mAccelerationScale = STANDARD_GRAVITY / 4096.0;\n\n        mDevice->template write<AccelerometerConfiguration2>([](auto & config) {\n            config.disableLowPassFilter = false;\n            config.digitalLowPassFilterConfiguration = 2;\n        });\n\n        mDevice->template write<Configuration>([](auto & config) {\n            config.digitalLowPassFilter = 2;\n            config.fSync = 0;\n            config.fifoMode = 0;\n        });\n\n        mDevice->template write<GyroscopeConfiguration>([](auto & config) {\n            config.fChoiceB = 0;\n            config.fullScaleRange = mpu9255::GyroscopeRange::dps250;\n        });\n\n        mDevice->template write<PowerManagement1>([](auto & config) {\n            config.clockSelect = mpu9255::ClockSource::bestAvailable;\n            config.powerDownProportionalToAbsoulteTemperatureVoltageGenerator = false;\n            config.gyroscopeStandby = false;\n            config.cycle = false;\n            config.sleep = false;\n            config.hardReset = false;\n        });\n    }\n\n    template<typename RegisterBank>\n    void MPU9255<RegisterBank>::i2cBypass(bool enable)\n    {\n        using namespace mpu9255;\n\n        mDevice->template write<InterruptBypassConfiguration>([enable](auto & config) {\n            config.enableBypass = enable;\n        });\n    }\n\n    template<typename RegisterBank>\n    void MPU9255<RegisterBank>::read()\n    {\n        using namespace mpu9255;\n\n        mDevice->template read<TemperatureRegister>([this](auto const& reg){\n            constexpr float KELVINS_PER_LSB = 1.0 / 333.87;\n            constexpr float OFFSET_FROM_ABSOLUTE_ZERO = 294.15;\n            mTemperature = static_cast<float>(reg.temperature) * KELVINS_PER_LSB + OFFSET_FROM_ABSOLUTE_ZERO;\n        });\n\n        mDevice->template read<AccelerometerMeasurements>([this](auto const& reg){\n            mAcceleration = reg.acceleration.template cast<float>() * mAccelerationScale;\n        });\n\n        int newRange;\n        mDevice->template read<GyroscopeMeasurements>([this, &newRange](auto const& reg){\n            constexpr float radiansPerDegree = (2 * M_PI) / 360.0;\n            constexpr float baseSensitivity = 1.0 / 131.0 * radiansPerDegree;\n\n            float const sensitivity = (1 << mGyroscopeScaleRange) * baseSensitivity;\n            mAngularVelocity = reg.angularVelocity.template cast<float>() * sensitivity;\n\n            constexpr int highBound = 23170; // reading above which we attempt to increase full scale select\n            constexpr int lowBound = 8192; // reading below which we attempt to decrease full scale select\n            int const maximum = reg.angularVelocity.template cast<int>().cwiseAbs().maxCoeff();\n            if (maximum > highBound && mGyroscopeScaleRange < 3) {\n                newRange = mGyroscopeScaleRange + 1;\n            } else if (maximum < lowBound && mGyroscopeScaleRange > 0) {\n                newRange = mGyroscopeScaleRange - 1;\n            } else {\n                newRange = mGyroscopeScaleRange;\n            }\n        });\n\n        if (newRange != mGyroscopeScaleRange) {\n            mDevice->template write<mpu9255::GyroscopeConfiguration>([=](auto & config) {\n                config.fChoiceB = 0;\n                config.fullScaleRange = (mpu9255::GyroscopeRange) newRange;\n            });\n\n            mGyroscopeScaleRange = newRange;\n        }\n    }\n}", "meta": {"hexsha": "f5ef0c2ad63833f37b355ed9754f1fe015482918", "size": 7440, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icarus/include/icarus/sensor/MPU9255_impl.hpp", "max_stars_repo_name": "Icarus-Quadro/Icarus", "max_stars_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "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": "icarus/include/icarus/sensor/MPU9255_impl.hpp", "max_issues_repo_name": "Icarus-Quadro/Icarus", "max_issues_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "icarus/include/icarus/sensor/MPU9255_impl.hpp", "max_forks_repo_name": "Icarus-Quadro/Icarus", "max_forks_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_forks_repo_licenses": ["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.6172839506, "max_line_length": 109, "alphanum_fraction": 0.551344086, "num_tokens": 1730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19829998652805772}}
{"text": "/****************************************************************************\n*\n*    Copyright (c) 2019 Vivante Corporation\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 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\n*    DEALINGS IN THE SOFTWARE.\n*\n*****************************************************************************/\n\n#pragma once\n\n#include <backendsCommon/CpuTensorHandle.hpp>\n#include <backendsCommon/Workload.hpp>\n#include <backendsCommon/WorkloadData.hpp>\n#include <boost/log/trivial.hpp>\n#include \"TNpuWorkloads.hpp\"\n\nnamespace armnn {\ntemplate <typename armnn::DataType... DataTypes>\nclass NpuL2NormalizationWorkload\n    : public TNpuWorkload<L2NormalizationQueueDescriptor, DataTypes...> {\n   public:\n    using base_type = TNpuWorkload<L2NormalizationQueueDescriptor, DataTypes...>;\n    explicit NpuL2NormalizationWorkload(const L2NormalizationQueueDescriptor& descriptor,\n                                        const WorkloadInfo& info)\n        : TNpuWorkload<L2NormalizationQueueDescriptor, DataTypes...>(descriptor, info),\n          m_Eps(descriptor.m_Parameters.m_Eps),\n          m_DataLayout(descriptor.m_Parameters.m_DataLayout) {\n        // Add input operand\n        // Only 1 input\n        std::vector<uint32_t> inOperandIds;\n        NpuTensorHandler* inputTensorHandle =\n            dynamic_cast<NpuTensorHandler*>(descriptor.m_Inputs[0]);\n        uint32_t inputOperandId = this->AddOperandAndSetValue(\n            inputTensorHandle->GetTensorInfo(), inputTensorHandle->GetShape(), nullptr);\n        inOperandIds.push_back(inputOperandId);\n\n        // Add layout operand\n        int32_t layoutCode = m_DataLayout == armnn::DataLayout::NCHW\n                                 ? int32_t(nnrt::DataLayout::NCHW)\n                                 : int32_t(nnrt::DataLayout::NHWC);\n        inOperandIds.push_back(this->AddOperandAndSetValue(layoutCode));\n\n        // Add output operand\n        std::vector<uint32_t> outOperandIds;\n        NpuTensorHandler* outputTensorHandle =\n            dynamic_cast<NpuTensorHandler*>(descriptor.m_Outputs[0]);\n        uint32_t outputTensorId = this->AddOperandAndSetValue(\n            outputTensorHandle->GetTensorInfo(), outputTensorHandle->GetShape(), nullptr);\n        outOperandIds.push_back(outputTensorId);\n\n        this->AddOperation(nnrt::OperationType::L2_NORMALIZATION,\n                           inOperandIds.size(),\n                           inOperandIds.data(),\n                           outOperandIds.size(),\n                           outOperandIds.data());\n    }\n\n   private:\n    // Used to avoid dividing by zero.\n    float m_Eps;\n    // The data layout to be used (NCHW, NHWC).\n    DataLayout m_DataLayout;\n};\nusing NpuL2NormalizationFloat32Workload = NpuL2NormalizationWorkload<armnn::DataType::Float32>;\nusing NpuL2NormalizationFloat16Workload = NpuL2NormalizationWorkload<armnn::DataType::Float16>;\nusing NpuL2NormalizationUint8Workload =\n    NpuL2NormalizationWorkload<armnn::DataType::QuantisedAsymm8>;\n}  // namespace armnn\n", "meta": {"hexsha": "d78b922d0d1ece06280e754a6bdfe2d165489f7f", "size": 3988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuL2NormalizationWorkload.hpp", "max_stars_repo_name": "phytec-mirrors/nn-imx", "max_stars_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "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": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuL2NormalizationWorkload.hpp", "max_issues_repo_name": "phytec-mirrors/nn-imx", "max_issues_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuL2NormalizationWorkload.hpp", "max_forks_repo_name": "phytec-mirrors/nn-imx", "max_forks_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "max_forks_repo_licenses": ["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.9176470588, "max_line_length": 95, "alphanum_fraction": 0.6720160481, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19829998652805772}}
{"text": "/**\n * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * This program is free software: you can redistribute it and/or modify\n * it 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 * 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 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 this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n#include <bitcoin/bitcoin/wallet/hd_private.hpp>\n\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <utility>\n#include <boost/program_options.hpp>\n#include <bitcoin/bitcoin/constants.hpp>\n#include <bitcoin/bitcoin/define.hpp>\n#include <bitcoin/bitcoin/formats/base_58.hpp>\n#include <bitcoin/bitcoin/math/checksum.hpp>\n#include <bitcoin/bitcoin/math/elliptic_curve.hpp>\n#include <bitcoin/bitcoin/math/hash.hpp>\n#include <bitcoin/bitcoin/math/limits.hpp>\n#include <bitcoin/bitcoin/utility/assert.hpp>\n#include <bitcoin/bitcoin/utility/container_source.hpp>\n#include <bitcoin/bitcoin/utility/data.hpp>\n#include <bitcoin/bitcoin/utility/endian.hpp>\n#include <bitcoin/bitcoin/utility/istream_reader.hpp>\n#include <bitcoin/bitcoin/utility/serializer.hpp>\n#include <bitcoin/bitcoin/wallet/ec_private.hpp>\n#include <bitcoin/bitcoin/wallet/ec_public.hpp>\n\nnamespace libbitcoin {\nnamespace wallet {\n\nconst uint64_t hd_private::mainnet = to_prefixes(76066276,\n    hd_public::mainnet);\n\nconst uint64_t hd_private::testnet = to_prefixes(70615956,\n    hd_public::testnet);\n\nhd_private::hd_private()\n  : hd_public(), secret_(null_hash)\n{\n}\n\nhd_private::hd_private(const hd_private& other)\n  : hd_public(other), secret_(other.secret_)\n{\n}\n\nhd_private::hd_private(const data_chunk& seed, uint64_t prefixes)\n  : hd_private(from_seed(seed, prefixes))\n{\n}\n\n// This reads the private version and sets the public to mainnet.\nhd_private::hd_private(const hd_key& private_key)\n  : hd_private(from_key(private_key, hd_public::mainnet))\n{\n}\n\n// This reads the private version and sets the public to mainnet.\nhd_private::hd_private(const std::string& encoded)\n    : hd_private(from_string(encoded, hd_public::mainnet))\n{\n}\n\n// This reads the private version and sets the public.\nhd_private::hd_private(const hd_key& private_key, uint32_t prefix)\n  : hd_private(from_key(private_key, prefix))\n{\n}\n\n// This validates the private version and sets the public.\nhd_private::hd_private(const hd_key& private_key, uint64_t prefixes)\n  : hd_private(from_key(private_key, prefixes))\n{\n}\n\n// This reads the private version and sets the public.\nhd_private::hd_private(const std::string& encoded, uint32_t prefix)\n  : hd_private(from_string(encoded, prefix))\n{\n}\n\n// This validates the private version and sets the public.\nhd_private::hd_private(const std::string& encoded, uint64_t prefixes)\n  : hd_private(from_string(encoded, prefixes))\n{\n}\n\nhd_private::hd_private(const ec_secret& secret,\n    const hd_chain_code& chain_code, const hd_lineage& lineage)\n  : hd_public(from_secret(secret, chain_code, lineage)),\n    secret_(secret)\n{\n}\n\n// Factories.\n// ----------------------------------------------------------------------------\n\nhd_private hd_private::from_seed(data_slice seed, uint64_t prefixes)\n{\n    // This is a magic constant from BIP32.\n    static const data_chunk magic(to_chunk(\"Bitcoin seed\"));\n\n    const auto intermediate = split(hmac_sha512_hash(seed, magic));\n\n    // The key is invalid if parse256(IL) >= n or 0:\n    if (!verify(intermediate.left))\n        return{};\n\n    const auto master = hd_lineage\n    {\n        prefixes,\n        0x00,\n        0x00000000,\n        0x00000000\n    };\n\n    return hd_private(intermediate.left, intermediate.right, master);\n}\n\nhd_private hd_private::from_key(const hd_key& key, uint32_t public_prefix)\n{\n    const auto prefix = from_big_endian_unsafe<uint32_t>(key.begin());\n    return from_key(key, to_prefixes(prefix, public_prefix));\n}\n\nhd_private hd_private::from_key(const hd_key& key, uint64_t prefixes)\n{\n    stream_source<hd_key> istream(key);\n    istream_reader reader(istream);\n\n    const auto prefix = reader.read_4_bytes_big_endian();\n    const auto depth = reader.read_byte();\n    const auto parent = reader.read_4_bytes_big_endian();\n    const auto child = reader.read_4_bytes_big_endian();\n    const auto chain = reader.read_forward<hd_chain_code_size>();\n    reader.read_byte();\n    const auto secret = reader.read_forward<ec_secret_size>();\n\n    // Validate the prefix against the provided value.\n    if (prefix != to_prefix(prefixes))\n        return{};\n\n    const hd_lineage lineage\n    {\n        prefixes,\n        depth,\n        parent,\n        child\n    };\n\n    return hd_private(secret, chain, lineage);\n}\n\nhd_private hd_private::from_string(const std::string& encoded,\n    uint32_t public_prefix)\n{\n    hd_key key;\n    if (!decode_base58(key, encoded))\n        return{};\n\n    return hd_private(from_key(key, public_prefix));\n}\n\nhd_private hd_private::from_string(const std::string& encoded,\n    uint64_t prefixes)\n{\n    hd_key key;\n    return decode_base58(key, encoded) ? hd_private(key, prefixes) :\n        hd_private{};\n}\n\n// Cast operators.\n// ----------------------------------------------------------------------------\n\nhd_private::operator const ec_secret&() const\n{\n    return secret_;\n}\n\n// Serializer.\n// ----------------------------------------------------------------------------\n\nstd::string hd_private::encoded() const\n{\n    return encode_base58(to_hd_key());\n}\n\n/// Accessors.\n// ----------------------------------------------------------------------------\n\nconst ec_secret& hd_private::secret() const\n{\n    return secret_;\n}\n\n// Methods.\n// ----------------------------------------------------------------------------\n\n// HD keys do not carry a payment address prefix (just like WIF).\n// So we are currently not converting to ec_public or ec_private.\n\nhd_key hd_private::to_hd_key() const\n{\n    static constexpr uint8_t private_key_padding = 0x00;\n\n    hd_key out;\n    build_checked_array(out,\n    {\n        to_big_endian(to_prefix(lineage_.prefixes)),\n        to_array(lineage_.depth),\n        to_big_endian(lineage_.parent_fingerprint),\n        to_big_endian(lineage_.child_number),\n        chain_,\n        to_array(private_key_padding),\n        secret_\n    });\n\n    return out;\n}\n\nhd_public hd_private::to_public() const\n{\n    return hd_public(((hd_public)*this).to_hd_key(),\n        hd_public::to_prefix(lineage_.prefixes));\n}\n\nhd_private hd_private::derive_private(uint32_t index) const\n{\n    constexpr uint8_t depth = 0;\n\n    const auto data = (index >= hd_first_hardened_key) ?\n        splice(to_array(depth), secret_, to_big_endian(index)) :\n        splice(point_, to_big_endian(index));\n\n    const auto intermediate = split(hmac_sha512_hash(data, chain_));\n\n    // The child key ki is (parse256(IL) + kpar) mod n:\n    auto child = secret_;\n    if (!ec_add(child, intermediate.left))\n        return{};\n\n    if (lineage_.depth == max_uint8)\n        return{};\n\n    const hd_lineage lineage\n    {\n        lineage_.prefixes,\n        static_cast<uint8_t>(lineage_.depth + 1),\n        fingerprint(),\n        index\n    };\n\n    return hd_private(child, intermediate.right, lineage);\n}\n\nhd_public hd_private::derive_public(uint32_t index) const\n{\n    return derive_private(index).to_public();\n}\n\n// Operators.\n// ----------------------------------------------------------------------------\n\nhd_private& hd_private::operator=(hd_private other)\n{\n    swap(*this, other);\n    return *this;\n}\n\nbool hd_private::operator<(const hd_private& other) const\n{\n    return encoded() < other.encoded();\n}\n\nbool hd_private::operator==(const hd_private& other) const\n{\n    return secret_ == other.secret_ && valid_ == other.valid_ &&\n        chain_ == other.chain_ && lineage_ == other.lineage_ &&\n        point_ == other.point_;\n}\n\nbool hd_private::operator!=(const hd_private& other) const\n{\n    return !(*this == other);\n}\n\n// We must assume mainnet for public version here.\n// When converting this to public a clone of this key should be used, with the\n// public version specified - after validating the private version.\nstd::istream& operator>>(std::istream& in, hd_private& to)\n{\n    std::string value;\n    in >> value;\n    to = hd_private(value, hd_public::mainnet);\n\n    if (!to)\n    {\n        using namespace boost::program_options;\n        BOOST_THROW_EXCEPTION(invalid_option_value(value));\n    }\n\n    return in;\n}\n\nstd::ostream& operator<<(std::ostream& out, const hd_private& of)\n{\n    out << of.encoded();\n    return out;\n}\n\n// friend function, see: stackoverflow.com/a/5695855/1172329\nvoid swap(hd_private& left, hd_private& right)\n{\n    using std::swap;\n\n    // Must be unqualified (no std namespace).\n    swap(static_cast<hd_public&>(left), static_cast<hd_public&>(right));\n    swap(left.secret_, right.secret_);\n}\n\n} // namespace wallet\n} // namespace libbitcoin\n", "meta": {"hexsha": "57d2ddf6e4691287ca0564876e7700f780014697", "size": 9213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/libbitcoin/src/wallet/hd_private.cpp", "max_stars_repo_name": "anatolse/beam", "max_stars_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 631.0, "max_stars_repo_stars_event_min_datetime": "2018-11-10T05:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:21:00.000Z", "max_issues_repo_path": "3rdparty/libbitcoin/src/wallet/hd_private.cpp", "max_issues_repo_name": "anatolse/beam", "max_issues_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1824.0, "max_issues_repo_issues_event_min_datetime": "2018-11-08T11:32:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T12:33:03.000Z", "max_forks_repo_path": "3rdparty/libbitcoin/src/wallet/hd_private.cpp", "max_forks_repo_name": "anatolse/beam", "max_forks_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 216.0, "max_forks_repo_forks_event_min_datetime": "2018-11-12T08:07:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T20:50:19.000Z", "avg_line_length": 27.3382789318, "max_line_length": 79, "alphanum_fraction": 0.6748073375, "num_tokens": 2086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1982999817135397}}
{"text": "#ifndef STAN_SERVICES_EXPERIMENTAL_ADVI_LOWRANK_HPP\n#define STAN_SERVICES_EXPERIMENTAL_ADVI_LOWRANK_HPP\n\n#include <stan/callbacks/interrupt.hpp>\n#include <stan/callbacks/logger.hpp>\n#include <stan/callbacks/writer.hpp>\n#include <stan/services/util/experimental_message.hpp>\n#include <stan/services/util/initialize.hpp>\n#include <stan/services/util/create_rng.hpp>\n#include <stan/io/var_context.hpp>\n#include <stan/variational/advi.hpp>\n#include <boost/random/additive_combine.hpp>\n#include <string>\n#include <vector>\n\nnamespace stan {\nnamespace services {\nnamespace experimental {\nnamespace advi {\n\n/**\n * Runs low rank ADVI.\n *\n * @tparam Model A model implementation\n * @param[in] model Input model to test (with data already instantiated)\n * @param[in] init var context for initialization\n * @param[in] random_seed random seed for the random number generator\n * @param[in] chain chain id to advance the random number generator\n * @param[in] init_radius radius to initialize\n * @param[in] grad_samples number of samples for Monte Carlo estimate\n *   of gradients\n * @param[in] elbo_samples number of samples for Monte Carlo estimate\n *   of ELBO\n * @param[in] max_iterations maximum number of iterations\n * @param[in] tol_rel_obj convergence tolerance on the relative norm\n *   of the objective\n * @param[in] rank the rank of the approximation\n * @param[in] eta stepsize scaling parameter for variational inference\n * @param[in] adapt_engaged adaptation engaged?\n * @param[in] adapt_iterations number of iterations for eta adaptation\n * @param[in] eval_elbo evaluate ELBO every Nth iteration\n * @param[in] output_samples number of posterior samples to draw and\n *   save\n * @param[in,out] interrupt callback to be called every iteration\n * @param[in,out] logger Logger for messages\n * @param[in,out] init_writer Writer callback for unconstrained inits\n * @param[in,out] parameter_writer output for parameter values\n * @param[in,out] diagnostic_writer output for diagnostic values\n * @return error_codes::OK if successful\n */\ntemplate <class Model>\nint lowrank(Model& model, const stan::io::var_context& init,\n              unsigned int random_seed, unsigned int chain, double init_radius,\n              int grad_samples, int elbo_samples, int max_iterations,\n              double eta, int eval_window, double window_size, double rhat_cut, \n              double mcse_cut, double ess_cut, int num_chains, \n              bool adapt_engaged, int adapt_iterations, int output_samples,\n              callbacks::interrupt& interrupt, callbacks::logger& logger,\n              callbacks::writer& init_writer,\n              callbacks::writer& parameter_writer,\n\t    callbacks::writer& diagnostic_writer, size_t rank) {\n// int lowrank(Model& model, const stan::io::var_context& init,\n//             unsigned int random_seed, unsigned int chain, double init_radius,\n//             int grad_samples, int elbo_samples, int max_iterations,\n//             double tol_rel_obj, int rank, double eta, bool adapt_engaged,\n//             int adapt_iterations, int eval_elbo, int output_samples,\n//             callbacks::interrupt& interrupt, callbacks::logger& logger,\n//             callbacks::writer& init_writer, callbacks::writer& parameter_writer,\n//             callbacks::writer& diagnostic_writer) {\n  util::experimental_message(logger);\n\n  boost::ecuyer1988 rng = util::create_rng(random_seed, chain);\n\n  std::vector<int> disc_vector;\n  std::vector<double> cont_vector = util::initialize(\n      model, init, rng, init_radius, true, logger, init_writer);\n\n  std::vector<std::string> names;\n  names.push_back(\"lp__\");\n  names.push_back(\"log_p__\");\n  names.push_back(\"log_g__\");\n  names.push_back(\"chain_id__\");\n  model.constrained_param_names(names, true, true);\n  parameter_writer(names);\n\n  Eigen::VectorXd cont_params\n      = Eigen::Map<Eigen::VectorXd>(&cont_vector[0], cont_vector.size(), 1);\n\n  stan::variational::advi_lowrank<Model, boost::ecuyer1988> cmd_advi(\n      model, cont_params, rng, rank, grad_samples, elbo_samples, output_samples);\n  cmd_advi.run(eta, adapt_engaged, adapt_iterations,\n\t       max_iterations, eval_window, window_size, rhat_cut, mcse_cut,\n\t       ess_cut, num_chains, logger, parameter_writer, diagnostic_writer);\n  // cmd_advi.run(eta, adapt_engaged, adapt_iterations, tol_rel_obj,\n  //              max_iterations, logger, parameter_writer, diagnostic_writer);\n\n  return 0;\n}\n}  // namespace advi\n}  // namespace experimental\n}  // namespace services\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "fdf959db1f1a4b3a20119031e33b8b84cadd0353", "size": 4505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/services/experimental/advi/lowrank.hpp", "max_stars_repo_name": "stephensrmmartin/stan", "max_stars_repo_head_hexsha": "e95c7bc9814792204ae8d900a1b47dfd17d88c0b", "max_stars_repo_licenses": ["CC-BY-3.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": "src/stan/services/experimental/advi/lowrank.hpp", "max_issues_repo_name": "stephensrmmartin/stan", "max_issues_repo_head_hexsha": "e95c7bc9814792204ae8d900a1b47dfd17d88c0b", "max_issues_repo_licenses": ["CC-BY-3.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/stan/services/experimental/advi/lowrank.hpp", "max_forks_repo_name": "stephensrmmartin/stan", "max_forks_repo_head_hexsha": "e95c7bc9814792204ae8d900a1b47dfd17d88c0b", "max_forks_repo_licenses": ["CC-BY-3.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": 43.3173076923, "max_line_length": 83, "alphanum_fraction": 0.7316315205, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19810703325200968}}
{"text": "#include <GL/glew.h>\n#include \"SplineWindow.h\"\n#include \"dart/external/lodepng/lodepng.h\"\n#include \"Functions.h\"\n#include <algorithm>\n#include <fstream>\n#include <boost/filesystem.hpp>\n#include <GL/glut.h>\nusing namespace GUI;\nusing namespace dart::simulation;\nusing namespace dart::dynamics;\n\nSplineWindow::\nSplineWindow(std::string motion, std::string record, std::string record_type)\n\t:GLUTWindow(),mTrackCamera(false),mIsRotate(false),mIsAuto(false), mTimeStep(1 / 30.0), mDrawRef2(false)\n{\n\tthis->mTotalFrame = 0;\n\n\tstd::string skel_path = std::string(CAR_DIR)+std::string(\"/character/\") + std::string(REF_CHARACTER_TYPE) + std::string(\".xml\");\n\t\n\tthis->mRef = new DPhy::Character(skel_path);\n\tthis->mRef3 = new DPhy::Character(skel_path); \n\n\tDPhy::SetSkeletonColor(this->mRef->GetSkeleton(), Eigen::Vector4d(235./255., 235./255., 235./255., 1.0));\n\tDPhy::SetSkeletonColor(this->mRef3->GetSkeleton(), Eigen::Vector4d(87./255., 235./255., 87./255., 1.0));\n\n\tif(record_type.compare(\"position\") == 0) {\n\t\tmDrawRef2 = true;\n\t\tthis->mRef2 = new DPhy::Character(skel_path); \n\n\t\tDPhy::SetSkeletonColor(this->mRef2->GetSkeleton(), Eigen::Vector4d(235./255., 87./255., 87./255., 1.0));\n\t}\n\n\tint dof = this->mRef->GetSkeleton()->getPositions().rows();\n\n\tDPhy::ReferenceManager* referenceManager = new DPhy::ReferenceManager(this->mRef);\n\treferenceManager->LoadMotionFromBVH(std::string(\"/motion/\") + motion);\n\treferenceManager->InitOptimization(1, \"\");\n\n\tstd::vector<double> knots = referenceManager->GetKnots();\n\n\tstd::vector<int> nc;\n\tnc.push_back(3);\n\tnc.push_back(5);\n\n\tDPhy::MultilevelSpline* s = new DPhy::MultilevelSpline(1, referenceManager->GetPhaseLength(), nc);\n\ts->SetKnots(0, knots);\n\t\n\tstd::ifstream is(record);\n\t\t\n\tchar buffer[256];\n\n\tint length = 0;\n\tdouble reward = 0;\n\n\tstd::vector<Eigen::VectorXd> pos;\n\tstd::vector<double> step;\n\n\tint n = 0;\n\tstd::vector<Eigen::VectorXd> cps_mean;\n\tstd::vector<Eigen::VectorXd> cps;\n\n\tfor(int i = 0; i < knots.size() + 3 ; i++) {\n\t\tcps_mean.push_back(Eigen::VectorXd::Zero(dof));\n\t}\n\n\tEigen::VectorXd targetBase = referenceManager->GetTargetBase();\n\tEigen::VectorXd targetUnit = referenceManager->GetTargetUnit();\n\tEigen::VectorXd targetIdx(targetBase.size());\n\ttargetIdx(0) = 0;\n\twhile(!is.eof()) {\n\t\tif(record_type.compare(\"spline\") == 0) {\n\t\t\t// cps number\n\t\t\tis >> buffer;\n\t\t\tEigen::VectorXd tp(targetBase.rows());\n\t\t\tEigen::VectorXd idx(targetBase.rows());\n\t\t\tfor(int j = 0; j < targetBase.rows(); j++) \n\t\t\t{\n\t\t\t\tis >> buffer;\n\t\t\t\ttp[j] = atof(buffer);\n\t\t\t\tidx[j] = std::floor((tp[j] - targetBase[j]) / targetUnit[j]);\n\t\t\t}\n\t\t\t// comma\n\t\t\tis >> buffer;\n\n\t\t\tEigen::VectorXd cp(dof);\n\t\t\tfor(int j = 0; j < dof; j++) \n\t\t\t{\n\t\t\t\tis >> buffer;\n\t\t\t\tcp[j] = atof(buffer);\n\t\t\t}\n\t\t\t// comma\n\t\t\tis >> buffer;\n\t\t\t// reward\n\t\t\tis >> buffer;\n\t\t\n\t\t\tcps.push_back(cp);\n\n\t\t\tif(cps.size() == knots.size() + 3) {\n\t\t\t\ts->SetControlPoints(0, cps);\n\t\t\t\tstd::vector<Eigen::VectorXd> displacement = s->ConvertSplineToMotion();\t\n\t\t\t\tstd::vector<Eigen::VectorXd> new_pos;\n\t\t\t\treferenceManager->AddDisplacementToBVH(displacement, new_pos);\n\n\t\t\t\tfor(int i = 0; i < new_pos.size(); i++) {\n\t\t\t\t\tlength += 1;\n\t\t\t\t\tmMemoryRef.push_back(new_pos[i]);\n\t\t\t\t}\t\n\t\t\t\tfor(int i = 0; i < cps.size(); i++) {\n\t\t\t\t\tcps_mean[i] += cps[i];\n\t\t\t\t}\n\n\t\t\t\tn += 1;\n\t\t\t\tcps.clear();\n\t\t\t}\n\t\t} else if(record_type.compare(\"position\") == 0) {\n\t\t\tEigen::VectorXd p(dof);\n\t\t\tfor(int j = 0; j < dof; j++) \n\t\t\t{\n\t\t\t\tis >> buffer;\n\t\t\t\tp[j] = atof(buffer);\n\t\t\t}\n\n\t\t\tis >> buffer;\n\t\t\tdouble cur_step = atof(buffer);\t\t\t\n\t\t\tis >> buffer;\n\t\t\tdouble cur_reward = atof(buffer);\n\t\t\tis >> buffer;\n\t\t\tdouble cur_reward2 = atof(buffer);\n\t\t\tif(reward == 0)\n\t\t\t\treward = cur_reward;\n\t\t\tis >> buffer;\n\n\t\t\t// next phase\n\t\t\tif(cur_reward != reward) {\n\t\t\t\tstd::cout << cur_reward << \" \" << cur_reward2 << std::endl;\n\t\t\t\treward = cur_reward;\n\t\t\t\n\t\t\t\tstd::vector<std::pair<Eigen::VectorXd,double>> displacement;\n\t\t\t\tpos = DPhy::Align(pos, referenceManager->GetPosition(std::fmod(step[0], referenceManager->GetPhaseLength())).segment<6>(0));\n\t\t\t\tstd::vector<std::pair<Eigen::VectorXd,double>> trajectory;\n\t\t\t\tfor(int i = 0; i < pos.size(); i++) {\n\t\t\t\t\ttrajectory.push_back(std::pair<Eigen::VectorXd,double>(pos[i], step[i]));\n\t\t\t\t}\n\t\t\t\treferenceManager->GetDisplacementWithBVH(trajectory, displacement);\n\t\t\t\tif(mMemoryRef.size() == 0) {\n\t\t\t\t\tfor(int i = 0; i < trajectory.size(); i++) {\n\t\t\t\t\t\tstd::cout << trajectory[i].second << \" \"<< trajectory[i].first.segment<3>(3).transpose() << \" \"<< displacement[i].first.segment<3>(3).transpose() << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ts->ConvertMotionToSpline(displacement);\n\n\t\t\t\tstd::vector<Eigen::VectorXd> new_displacement = s->ConvertSplineToMotion();\n\t\t\t\tstd::vector<Eigen::VectorXd> new_pos;\n\t\t\t\treferenceManager->AddDisplacementToBVH(new_displacement, new_pos);\n\t\t\t\tif(mMemoryRef.size() == 0) {\n\t\t\t\t\tfor(int i = 0; i < new_displacement.size(); i++) {\n\t\t\t\t\t\tstd::cout << i  << \" \"<< new_pos[i].segment<3>(3).transpose() << \" \"<< new_displacement[i].segment<3>(3).transpose() << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcps = s->GetControlPoints(0);\n\t\t\t\tfor(int i = 0; i < cps.size(); i++) {\n\t\t\t\t\tcps_mean[i] += cps[i];\n\t\t\t\t}\n\t\t\t\tn += 1;\n\n\t\t\t\tint l = std::min(pos.size(), new_pos.size());\n\t\t\t\tfor(int i = 0; i < l; i++) {\n\t\t\t\t\tlength += 1;\n\t\t\t\t\tmMemoryRef.push_back(pos[i]);\n\t\t\t\t\tnew_pos[i][3] += 1.5;\n\t\t\t\t\tmMemoryRef2.push_back(new_pos[i]);\n\t\t\t\t}\n\t\t\t\tpos.clear();\n\t\t\t\tstep.clear();\n\t\t\t}\n\n\t\t\tpos.push_back(p);\n\t\t\tstep.push_back(cur_step);\n\t\t}\n\t}\n\tis.close();\n\n\tfor(int i = 0; i < cps_mean.size(); i++) {\n\t\tcps_mean[i] /= n;\n\t}\n\ts->SetControlPoints(0, cps_mean);\n\tstd::vector<Eigen::VectorXd> displacement = s->ConvertSplineToMotion();\n\tstd::vector<Eigen::VectorXd> new_pos;\n\treferenceManager->AddDisplacementToBVH(displacement, new_pos);\n\tfor(int i = 0; i < referenceManager->GetPhaseLength(); i++) {\n\t\tnew_pos[i][3] += 3;\n\t}\n\tfor(int i = 0; i < n; i++) {\n\t\tfor(int j = 0; j < referenceManager->GetPhaseLength(); j++) {\n\t\t\tmMemoryRef3.push_back(new_pos[j]);\n\t\t}\n\t}\n\t\n\tif(this->mTotalFrame == 0 || length < mTotalFrame) {\n\t\tmTotalFrame = length;\n\t}\n\n\tthis->mCurFrame = 0;\n\tthis->mDisplayTimeout = 33;\n\n\tthis->SetFrame(this->mCurFrame);\n\n}\nvoid\nSplineWindow::\nSetFrame(int n)\n{\n\tif( n < 0 || n >= this->mTotalFrame )\n\t{\n\t \tstd::cout << \"Frame exceeds limits\" << std::endl;\n\t \treturn;\n\t}\n\n    mRef->GetSkeleton()->setPositions(mMemoryRef[n]);\n    if(mDrawRef2)  {\n    \tmRef2->GetSkeleton()->setPositions(mMemoryRef2[n]);\n    }\n    mRef3->GetSkeleton()->setPositions(mMemoryRef3[n]);\n\n}\n\nvoid\nSplineWindow::\nNextFrame()\n{ \n\tthis->mCurFrame+=1;\n\tif (this->mCurFrame >= this->mTotalFrame) {\n        this->mCurFrame = 0;\n    }\n\tthis->SetFrame(this->mCurFrame);\n}\nvoid\nSplineWindow::\nPrevFrame()\n{\n\tthis->mCurFrame-=1;\n\tif( this->mCurFrame < 0 ) {\n        this->mCurFrame = this->mTotalFrame - 1;\n    }\n\tthis->SetFrame(this->mCurFrame);\n}\nvoid\nSplineWindow::\nDrawSkeletons()\n{\n\tGUI::DrawSkeleton(this->mRef->GetSkeleton(), 0);\n\tif(mDrawRef2) {\n\t\tGUI::DrawSkeleton(this->mRef2->GetSkeleton(), 0);\n\t}\n\tGUI::DrawSkeleton(this->mRef3->GetSkeleton(), 0);\n\n}\nvoid\nSplineWindow::\nDrawGround()\n{\n\tEigen::Vector3d com_root;\n\tcom_root = this->mRef->GetSkeleton()->getRootBodyNode()->getCOM();\n\tGUI::DrawGround((int)com_root[0], (int)com_root[2], 0);\n}\nvoid\nSplineWindow::\nDisplay() \n{\n\n\tglClearColor(1.0, 1.0, 1.0, 1);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tglEnable(GL_DEPTH_TEST);\n\n\tdart::dynamics::SkeletonPtr skel = this->mRef->GetSkeleton();\n\tEigen::Vector3d com_root = skel->getRootBodyNode()->getCOM();\n\tEigen::Vector3d com_front = skel->getRootBodyNode()->getTransform()*Eigen::Vector3d(0.0, 0.0, 2.0);\n\n\tif(this->mTrackCamera){\n\t\tEigen::Vector3d com = skel->getRootBodyNode()->getCOM();\n\t\tEigen::Isometry3d transform = skel->getRootBodyNode()->getTransform();\n\t\tcom[1] = 0.8;\n\n\t\tEigen::Vector3d camera_pos;\n\t\tcamera_pos << -3, 1, 1.5;\n\t\tcamera_pos = camera_pos + com;\n\t\tcamera_pos[1] = 2;\n\n\t\tmCamera->SetCenter(com);\n\t}\n\tmCamera->Apply();\n\n\tglUseProgram(program);\n\tglPushMatrix();\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n    glScalef(1.0, -1.0, 1.0);\n\tinitLights(com_root[0], com_root[2], com_front[0], com_front[2]);\n\t// DrawSkeletons();\n\tglPopMatrix();\n\tinitLights(com_root[0], com_root[2], com_front[0], com_front[2]);\n\t// glColor4f(0.7, 0.0, 0.0, 0.40);  /* 40% dark red floor color */\n\tDrawGround();\n\tDrawSkeletons();\n\tglDisable(GL_BLEND);\n\n\tglUseProgram(0);\n\tglutSwapBuffers();\n\n}\nvoid\nSplineWindow::\nReset()\n{\n\tthis->mCurFrame = 0;\n\tthis->SetFrame(this->mCurFrame);\n\n}\nvoid\nSplineWindow::\nKeyboard(unsigned char key,int x,int y) \n{\n\tswitch(key)\n\t{\n\t\tcase '`' :mIsRotate= !mIsRotate;break;\n\t\tcase '[': mIsAuto=false;this->PrevFrame();break;\n\t\tcase ']': mIsAuto=false;this->NextFrame();break;\n\t\tcase 'o': this->mCurFrame-=99; this->PrevFrame();break;\n\t\tcase 'p': this->mCurFrame+=99; this->NextFrame();break;\n\t\tcase 's': std::cout << this->mCurFrame << std::endl;break;\n\t\tcase 'r': Reset();break;\n\t\tcase 't': mTrackCamera = !mTrackCamera; this->SetFrame(this->mCurFrame); break;\n\t\tcase ' ':\n\t\t\tmIsAuto = !mIsAuto;\n\t\t\tbreak;\n\t\tcase 27: exit(0);break;\n\t\tdefault : break;\n\t}\n\t// this->SetFrame(this->mCurFrame);\n\n\t// glutPostRedisplay();\n}\nvoid\nSplineWindow::\nMouse(int button, int state, int x, int y) \n{\n\tif(button == 3 || button == 4){\n\t\tif (button == 3)\n\t\t{\n\t\t\tmCamera->Pan(0,-5,0,0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmCamera->Pan(0,5,0,0);\n\t\t}\n\t}\n\telse{\n\t\tif (state == GLUT_DOWN)\n\t\t{\n\t\t\tmIsDrag = true;\n\t\t\tmMouseType = button;\n\t\t\tmPrevX = x;\n\t\t\tmPrevY = y;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmIsDrag = false;\n\t\t\tmMouseType = 0;\n\t\t}\n\t}\n\n\t// glutPostRedisplay();\n}\nvoid\nSplineWindow::\nMotion(int x, int y) \n{\n\tif (!mIsDrag)\n\t\treturn;\n\n\tint mod = glutGetModifiers();\n\tif (mMouseType == GLUT_LEFT_BUTTON)\n\t{\n\t\tmCamera->Translate(x,y,mPrevX,mPrevY);\n\t}\n\telse if (mMouseType == GLUT_RIGHT_BUTTON)\n\t{\n\t\tmCamera->Rotate(x,y,mPrevX,mPrevY);\n\t\n\n\t}\n\tmPrevX = x;\n\tmPrevY = y;\n}\nvoid\nSplineWindow::\nReshape(int w, int h) \n{\n\tglViewport(0, 0, w, h);\n\tmCamera->Apply();\n}\n\nvoid \nSplineWindow::\nStep()\n{\t\n\tthis->mCurFrame++;\n\tthis->SetFrame(this->mCurFrame);\n}\nvoid\nSplineWindow::\nTimer(int value) \n{\n\tstd::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n\n\tif( mIsAuto && this->mCurFrame == this->mTotalFrame - 1){\n         Step();\n\t} else if( mIsAuto && this->mCurFrame < this->mTotalFrame - 1){\n        this->mCurFrame++;\n        SetFrame(this->mCurFrame);\n        \t\n    }\n\n\tstd::chrono::steady_clock::time_point end= std::chrono::steady_clock::now();\n\tdouble elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()/1000.;\n\t\n\tglutTimerFunc(std::max(0.0,mDisplayTimeout-elapsed), TimerEvent,1);\n\tglutPostRedisplay();\n\n}", "meta": {"hexsha": "458bc17ccc7976ef5a3eb5ea921bf0bd9b550373", "size": 10676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "render/SplineWindow.cpp", "max_stars_repo_name": "snumrl/CAR", "max_stars_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T08:47:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:56:21.000Z", "max_issues_repo_path": "render/SplineWindow.cpp", "max_issues_repo_name": "snumrl/CAR", "max_issues_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "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": "render/SplineWindow.cpp", "max_forks_repo_name": "snumrl/CAR", "max_forks_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "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.6558891455, "max_line_length": 165, "alphanum_fraction": 0.6398463844, "num_tokens": 3383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702254064929194, "lm_q1q2_score": 0.19810703325200965}}
{"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_IEEE_FUNCTIONS_SIMD_COMMON_NEGATE_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_IEEE_FUNCTIONS_SIMD_COMMON_NEGATE_HPP_INCLUDED\n#include <boost/simd/toolbox/ieee/functions/negate.hpp>\n#include <boost/simd/include/functions/simd/is_ltz.hpp>\n#include <boost/simd/include/functions/simd/is_nez.hpp>\n#include <boost/simd/include/functions/simd/is_nan.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/seladd.hpp>\n#include <boost/simd/include/functions/simd/unary_minus.hpp>\n#include <boost/simd/include/functions/simd/if_else_zero.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::negate_, tag::cpu_,\n                         (A0)(X),\n                         ((simd_<arithmetic_<A0>,X>))\n                         ((simd_<arithmetic_<A0>,X>))\n                        )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return  if_else(is_ltz(a1),-a0,if_else_zero(is_nez(a1), a0));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::negate_, tag::cpu_,\n                         (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)\n    {\n      return if_else_zero(is_nez(a1), a0);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::negate_, tag::cpu_,\n                         (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)\n    {\n      A0 tmp = if_else_zero(is_nez(a1), a0);\n      tmp = if_else(is_ltz(a1), -a0, tmp);\n      return select(is_nan(a1), a1, tmp); //TODO signed Nan ?\n    }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "b4d526ed42554714975e8de1165747e442ad3308", "size": 2465, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/negate.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/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/negate.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/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/negate.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": 37.9230769231, "max_line_length": 80, "alphanum_fraction": 0.5707910751, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.19810702953378914}}
{"text": "#include <ros/ros.h>\n#include \"imu_spatial/imu_spatial.h\"\n\n#include \"std_msgs/String.h\"\n\n#include \"sensor_msgs/Imu.h\"\n#include \"sensor_msgs/MagneticField.h\"\n#include \"sensor_msgs/Temperature.h\"\n#include \"diagnostic_updater/diagnostic_updater.h\"\n#include \"diagnostic_updater/DiagnosticStatusWrapper.h\"\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n#include <tf/LinearMath/Vector3.h>\n#include <tf/LinearMath/Quaternion.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_listener.h>\n/*#include <tf2/LinearMath/Quaternion.h>\n#include <tf2/LinearMath/Transform.h>\n#include <tf2_ros/transform_broadcaster.h>\n#include <tf2_ros/transform_listener.h>*/\n#include <geometry_msgs/TransformStamped.h>\n#include <geometry_msgs/Quaternion.h>\n#include <geometry_msgs/Twist.h>\n#include <nav_msgs/Odometry.h>\n\n#include <fstream>\n#include <boost/filesystem.hpp>\n\n#include <jetsoncar_utils/jetsoncar_utils.h>\n\n\nclass IMUNode {\nprivate:\n    IMU imu;\n\n    bool publish_tf_;\n    bool include_standard_deviations_;\n    bool enable_position_fusion_;\n    bool enable_heading_fusion_;\n    int odom_downsample_rate_;\n    int odom_sample_count_{0};\n    float odom_position_stddev_m_;\n    float odom_heading_stddev_deg_;\n\n    ros::Time imu_t0;\n    IMU::Orientation est_orientation_;\n    IMU::QuaternionStdDev est_quaternion_stddev_;\n    IMU::StateEstimate est_acceleration_;\n    IMU::StateEstimate est_angular_velocity_;\n    IMU::StateEstimate est_body_velocity_;\n    IMU::StateEstimate est_position_NED_;\n    IMU::CombinedSensorsMeasurement raw_;\n\n    ros::NodeHandle nh_;\n    ros::NodeHandle nParam_;\n    std::string world_frame_;\n    std::string imu_frame_;\n    std::string position_imu_frame_; // mainly for visualization\n\n    // Publishers\n    ros::Publisher pub_imu_;\n    ros::Publisher pub_imu_pose_;\n    ros::Publisher pub_imu_raw_;\n    ros::Publisher pub_magnetic_field_;\n\n    // Subscribers\n    ros::Subscriber sub_odom_in_;\n\n    tf::TransformBroadcaster tf_broadcaster_;\n    tf::TransformListener tf_listener_;\n\n    // Logging\n    bool loggingEnabled{false};\n    std::ofstream log_raw;\n    std::ofstream log_estimate;\n    std::ofstream log_angular_velocity;\n    std::ofstream log_odom_pose;\n\nprivate:\n#if 0\n    void publish_imu_msg() {\n        sensor_msgs::Imu imu_msg;\n        geometry_msgs::Quaternion quaternion_msg;\n        float orientation_covariance[9] = {pow((quaternion_std_packet_.standard_deviation[0]), 2.0), 0, 0,\n                                           0, pow((quaternion_std_packet_.standard_deviation[1]), 2.0), 0,\n                                           0, 0, pow((quaternion_std_packet_.standard_deviation[2]), 2.0)};\n        geometry_msgs::Vector3 angular_velocity;\n\n        geometry_msgs::Vector3 linear_acceleration;\n\n        imu_msg.header.stamp = ros::Time::now();\n        imu_msg.header.frame_id = frame_id_;\n\n        imu_msg.orientation.w = quaternion_packet_.orientation[0];\n        imu_msg.orientation.x = quaternion_packet_.orientation[1];\n        imu_msg.orientation.y = quaternion_packet_.orientation[2];\n        imu_msg.orientation.z = quaternion_packet_.orientation[3];\n        imu_msg.orientation_covariance[0] = orientation_covariance[0];\n        imu_msg.orientation_covariance[4] = orientation_covariance[4];\n        imu_msg.orientation_covariance[8] = orientation_covariance[8];\n\n        imu_msg.angular_velocity.x = angular_velocity_packet_.angular_velocity[0];\n        imu_msg.angular_velocity.y = angular_velocity_packet_.angular_velocity[1];\n        imu_msg.angular_velocity.z = angular_velocity_packet_.angular_velocity[2];\n        imu_msg.angular_velocity_covariance[0] = -1;\n\n        imu_msg.linear_acceleration.x = acceleration_packet_.acceleration[0];\n        imu_msg.linear_acceleration.y = acceleration_packet_.acceleration[1];\n        imu_msg.linear_acceleration.z = acceleration_packet_.acceleration[2];\n        imu_msg.linear_acceleration_covariance[0] = -1;\n\n        imu_pub_.publish(imu_msg);\n    }\n    void publish_imu_orienation_tf() {\n        tf::Quaternion q_attitude;\n        q_attitude.setW(quaternion_packet_.orientation[0]);\n        q_attitude.setX(quaternion_packet_.orientation[2]);\n        q_attitude.setY(quaternion_packet_.orientation[1]);\n        q_attitude.setZ(-quaternion_packet_.orientation[3]);\n\n        tf::Transform attitudeTf;\n        attitudeTf.setIdentity();\n        attitudeTf.setRotation(q_attitude);\n\n        /* Send transfrom from \"heading\" frame to \"base_link\" frame */\n        geometry_msgs::TransformStamped tf_tilt_msg;\n        tf_tilt_msg.header.frame_id = \"heading\";\n        tf_tilt_msg.child_frame_id = \"base_link\";\n        tf_tilt_msg.header.stamp = ros::Time::now();\n        tf_tilt_msg.transform.translation.x = 0;\n        tf_tilt_msg.transform.translation.y = 0;\n        tf_tilt_msg.transform.translation.z = 0.0;\n        tf_tilt_msg.transform.rotation.w = q_attitude.w();\n        tf_tilt_msg.transform.rotation.x = q_attitude.x();\n        tf_tilt_msg.transform.rotation.y = q_attitude.y();\n        tf_tilt_msg.transform.rotation.z = q_attitude.z();\n        tf_broadcaster_.sendTransform(tf_tilt_msg);\n\n        /* Send odometry message */\n        //   This represents an estimate of a position and velocity in free space.\n        //   The pose in this message should be specified in the coordinate frame given by header.frame_id\n        //   The twist in this message should be specified in the coordinate frame given by the child_frame_id\n        nav_msgs::Odometry odom_msg;\n        odom_msg.header.stamp = ros::Time::now();\n        odom_msg.header.frame_id = \"odom\";\n        odom_msg.child_frame_id = \"imu\";\n        odom_msg.pose.pose.position.x = 0; // inertial frame position\n        odom_msg.pose.pose.position.y = 0;\n        odom_msg.pose.pose.position.z = 0;\n        odom_msg.pose.pose.orientation.w = q_attitude.w();\n        odom_msg.pose.pose.orientation.x = q_attitude.x();\n        odom_msg.pose.pose.orientation.y = q_attitude.y();\n        odom_msg.pose.pose.orientation.z = q_attitude.z();\n        odom_msg.twist.twist.linear.x = 0; // body frame velocity\n        odom_msg.twist.twist.linear.y = 0;\n        odom_msg.twist.twist.linear.z = 0;\n        odom_msg.twist.twist.angular.x = angular_velocity_packet_.angular_velocity[0];\n        odom_msg.twist.twist.angular.y = angular_velocity_packet_.angular_velocity[1];\n        odom_msg.twist.twist.angular.z = angular_velocity_packet_.angular_velocity[2];\n        pub_odom_.publish(odom_msg);\n    }\n    void publish_imu_raw_msg() {\n        sensor_msgs::Imu imu_msg;\n        geometry_msgs::Vector3 angular_velocity;\n        geometry_msgs::Vector3 linear_acceleration;\n\n        imu_msg.header.stamp = ros::Time::now();\n        imu_msg.header.frame_id = frame_id_;\n\n        imu_msg.orientation_covariance[0] = -1;\n\n        imu_msg.angular_velocity.x = raw_sensors_packet_.gyroscopes[0];\n        imu_msg.angular_velocity.y = raw_sensors_packet_.gyroscopes[1];\n        imu_msg.angular_velocity.z = raw_sensors_packet_.gyroscopes[2];\n        imu_msg.angular_velocity_covariance[0] = -1;\n\n        imu_msg.linear_acceleration.x = raw_sensors_packet_.accelerometers[0];\n        imu_msg.linear_acceleration.y = raw_sensors_packet_.accelerometers[1];\n        imu_msg.linear_acceleration.z = raw_sensors_packet_.accelerometers[2];\n        imu_msg.linear_acceleration_covariance[0] = -1;\n\n        imu_raw_pub_.publish(imu_msg);\n    }\n    void publish_magnetics_msg() {\n        sensor_msgs::MagneticField magnetic_field_msg;\n\n        magnetic_field_msg.header.stamp = ros::Time::now();\n        magnetic_field_msg.header.frame_id = frame_id_;\n\n        magnetic_field_msg.magnetic_field.x = raw_sensors_packet_.magnetometers[0] * (1.0e-7);\n        magnetic_field_msg.magnetic_field.y = raw_sensors_packet_.magnetometers[1] * (1.0e-7);\n        magnetic_field_msg.magnetic_field.z = raw_sensors_packet_.magnetometers[2] * (1.0e-7);\n\n        magnetic_field_pub_.publish(magnetic_field_msg);\n    }\n#endif\n\n    void RawSensorsUpdate(IMU::CombinedSensorsMeasurement meas)\n    {\n        auto time = imu_t0 + ros::Duration(meas.timestamp);\n\n        if (log_raw.is_open()) {\n            log_raw << time.toNSec() << \"\\t\";\n            log_raw << std::setprecision(10) << meas.timestamp << \"\\t\";\n            log_raw << std::setprecision(10) << meas.accelerometer[0] << \"\\t\";\n            log_raw << std::setprecision(10) << meas.accelerometer[1] << \"\\t\";\n            log_raw << std::setprecision(10) << meas.accelerometer[2] << \"\\t\";\n            log_raw << std::setprecision(10) << meas.gyroscope[0] << \"\\t\";\n            log_raw << std::setprecision(10) << meas.gyroscope[1] << \"\\t\";\n            log_raw << std::setprecision(10) << meas.gyroscope[2] << \"\\t\";\n            log_raw << std::setprecision(10) << meas.magnetometer[0] << \"\\t\";\n            log_raw << std::setprecision(10) << meas.magnetometer[1] << \"\\t\";\n            log_raw << std::setprecision(10) << meas.magnetometer[2];\n            log_raw << std::endl;\n        }\n\n        raw_ = meas;\n\n        // Publish IMU message\n        sensor_msgs::Imu imu_msg;\n        imu_msg.header.stamp = imu_t0 + ros::Duration(meas.timestamp);\n        imu_msg.header.frame_id = imu_frame_;\n\n        imu_msg.orientation_covariance[0] = -1;\n\n        imu_msg.angular_velocity.x = meas.gyroscope[0];\n        imu_msg.angular_velocity.y = meas.gyroscope[1];\n        imu_msg.angular_velocity.z = meas.gyroscope[2];\n        imu_msg.angular_velocity_covariance[0] = -1;\n\n        imu_msg.linear_acceleration.x = meas.accelerometer[0];\n        imu_msg.linear_acceleration.y = meas.accelerometer[1];\n        imu_msg.linear_acceleration.z = meas.accelerometer[2];\n        imu_msg.linear_acceleration_covariance[0] = -1;\n\n        pub_imu_raw_.publish(imu_msg);\n\n        // Publish magnetometer message\n        sensor_msgs::MagneticField magnetic_field_msg;\n\n        magnetic_field_msg.header.stamp = ros::Time::now();\n        magnetic_field_msg.header.frame_id = imu_frame_;\n\n        magnetic_field_msg.magnetic_field.x = meas.magnetometer[0] * (1.0e-7); // milliGauss to Tesla\n        magnetic_field_msg.magnetic_field.y = meas.magnetometer[1] * (1.0e-7);\n        magnetic_field_msg.magnetic_field.z = meas.magnetometer[2] * (1.0e-7);\n\n        pub_magnetic_field_.publish(magnetic_field_msg);\n    }\n\n    void PublishEstimateIfReady()\n    {\n        if (est_orientation_.timestamp > 0 &&\n           (est_orientation_.timestamp == est_quaternion_stddev_.timestamp || !include_standard_deviations_) &&\n            est_orientation_.timestamp == est_angular_velocity_.timestamp &&\n           (est_orientation_.timestamp == est_body_velocity_.timestamp || !enable_position_fusion_) &&\n           (est_orientation_.timestamp == est_position_NED_.timestamp || !enable_position_fusion_))\n        {\n            auto time = imu_t0 + ros::Duration(est_orientation_.timestamp);\n\n            tf::Quaternion q_imu;\n            q_imu.setX(est_orientation_.quaternion[0]);\n            q_imu.setY(est_orientation_.quaternion[1]);\n            q_imu.setZ(est_orientation_.quaternion[2]);\n            q_imu.setW(est_orientation_.quaternion[3]);\n\n            if (fabs(q_imu.length() - 1.0) > 0.01) {\n                ROS_WARN_STREAM(\"[IMU] Internal estimator not ready yet\");\n                return; // error\n            }\n\n            tf::Quaternion q_flip({1,0,0}, deg2rad(180));\n            tf::Quaternion q_orientation = q_flip * q_imu; // apply this flip to convert the quaternion estimate from a NED frame into the world NWU frame\n\n            auto rpy = IMU::GetPoseEulerRPY(est_orientation_.quaternion, true);\n            ROS_DEBUG_STREAM(\"RPY = \" << rpy[0] << \", \" << rpy[1] << \", \" << rpy[2]);\n\n            /* Send transfrom from \"world\" frame to \"imu\" frame */\n            if (publish_tf_) {\n                geometry_msgs::TransformStamped tf_imu_msg;\n                tf_imu_msg.header.frame_id = world_frame_;\n                tf_imu_msg.child_frame_id = imu_frame_;\n                tf_imu_msg.header.stamp = time;\n                tf_imu_msg.transform.translation.x = 0;\n                tf_imu_msg.transform.translation.y = 0;\n                tf_imu_msg.transform.translation.z = 0;\n                tf_imu_msg.transform.rotation.x = q_orientation.x();\n                tf_imu_msg.transform.rotation.y = q_orientation.y();\n                tf_imu_msg.transform.rotation.z = q_orientation.z();\n                tf_imu_msg.transform.rotation.w = q_orientation.w();\n                tf_broadcaster_.sendTransform(tf_imu_msg);\n            }\n\n            // Publish IMU estimates\n            sensor_msgs::Imu imu_msg;\n            geometry_msgs::Quaternion quaternion_msg;\n            // Factor of 2 since the quaternion elements are = sin(1/2*angle)\n            imu_msg.header.stamp = time;\n            imu_msg.header.frame_id = imu_frame_;\n\n            imu_msg.orientation.x = q_orientation.x();\n            imu_msg.orientation.y = q_orientation.y();\n            imu_msg.orientation.z = q_orientation.z();\n            imu_msg.orientation.w = q_orientation.w();\n            imu_msg.orientation_covariance[0] = -1;\n\n            if (include_standard_deviations_) {\n                double orientation_covariance[9] = {pow((2.0 * est_quaternion_stddev_.stddev[0]), 2.0), 0, 0,\n                                                    0, pow((2.0 * est_quaternion_stddev_.stddev[1]), 2.0), 0,\n                                                    0, 0, pow((2.0 * est_quaternion_stddev_.stddev[2]), 2.0)};\n                imu_msg.orientation_covariance[0] = orientation_covariance[0];\n                imu_msg.orientation_covariance[4] = orientation_covariance[4];\n                imu_msg.orientation_covariance[8] = orientation_covariance[8];\n            }\n\n            imu_msg.angular_velocity.x = est_angular_velocity_.estimate[0];\n            imu_msg.angular_velocity.y = est_angular_velocity_.estimate[1];\n            imu_msg.angular_velocity.z = est_angular_velocity_.estimate[2];\n            imu_msg.angular_velocity_covariance[0] = -1;\n\n            // est_acceleration_.estimate doesn't contain any acceleration if the internal position estimator within the IMU isn't running\n            /*\n            imu_msg.linear_acceleration.x = est_acceleration_.estimate[0];\n            imu_msg.linear_acceleration.y = est_acceleration_.estimate[1];\n            imu_msg.linear_acceleration.z = est_acceleration_.estimate[2];\n            */\n            // Instead we correct the accelerometer measurement with the orientation quaternion and report that as the linear acceleration\n            /*auto accelerometer = tf::Vector3(raw_.accelerometer[0], raw_.accelerometer[1], raw_.accelerometer[2]);\n            auto acceleration = accelerometer - tf::quatRotate(q_imu.inverse(), {0,0,-gravity_});\n            imu_msg.linear_acceleration.x = acceleration.x();\n            imu_msg.linear_acceleration.y = acceleration.y();\n            imu_msg.linear_acceleration.z = acceleration.z();*/\n            imu_msg.linear_acceleration_covariance[0] = -1;\n\n            pub_imu_.publish(imu_msg);\n\n            // Send position and velocity estimates\n            if (enable_position_fusion_) {\n                geometry_msgs::TransformStamped tf_imu_msg;\n                tf_imu_msg.header.frame_id = world_frame_;\n                tf_imu_msg.child_frame_id = position_imu_frame_;\n                tf_imu_msg.header.stamp = ros::Time::now();\n                tf_imu_msg.transform.translation.x = est_position_NED_.estimate[0]; // From NED to ENU\n                tf_imu_msg.transform.translation.y = -est_position_NED_.estimate[1];\n                tf_imu_msg.transform.translation.z = -est_position_NED_.estimate[2];\n                tf_imu_msg.transform.rotation.x = q_orientation.x();\n                tf_imu_msg.transform.rotation.y = q_orientation.y();\n                tf_imu_msg.transform.rotation.z = q_orientation.z();\n                tf_imu_msg.transform.rotation.w = q_orientation.w();\n                tf_broadcaster_.sendTransform(tf_imu_msg);\n\n                /* Send IMU Pose odometry message */\n                //   This represents an estimate of a position and velocity in free space.\n                //   The pose in this message should be specified in the coordinate frame given by header.frame_id\n                //   The twist in this message should be specified in the coordinate frame given by the child_frame_id\n                nav_msgs::Odometry odom_msg;\n                odom_msg.header.stamp = ros::Time::now();\n                odom_msg.header.frame_id = world_frame_;\n                odom_msg.child_frame_id = position_imu_frame_;\n                odom_msg.pose.pose.position.x = est_position_NED_.estimate[0]; // From NED to ENU\n                odom_msg.pose.pose.position.y = -est_position_NED_.estimate[1];\n                odom_msg.pose.pose.position.z = -est_position_NED_.estimate[2];\n                odom_msg.pose.pose.orientation.w = q_orientation.w();\n                odom_msg.pose.pose.orientation.x = q_orientation.x();\n                odom_msg.pose.pose.orientation.y = q_orientation.y();\n                odom_msg.pose.pose.orientation.z = q_orientation.z();\n                odom_msg.twist.twist.linear.x = est_body_velocity_.estimate[0]; // body frame velocity\n                odom_msg.twist.twist.linear.y = est_body_velocity_.estimate[1]; // OBS! Needs to be converted\n                odom_msg.twist.twist.linear.z = est_body_velocity_.estimate[2];\n                odom_msg.twist.twist.angular.x = est_angular_velocity_.estimate[0]; // these are already body angular velocities\n                odom_msg.twist.twist.angular.y = est_angular_velocity_.estimate[1];\n                odom_msg.twist.twist.angular.z = est_angular_velocity_.estimate[2];\n                pub_imu_pose_.publish(odom_msg);\n            }\n\n            // Invalidate stored estimates\n            est_orientation_.timestamp = 0;\n            est_quaternion_stddev_.timestamp = 0;\n            est_angular_velocity_.timestamp = 0;\n            est_body_velocity_.timestamp = 0;\n            est_position_NED_.timestamp = 0;\n        }\n    }\n\n    void OrientationUpdate(IMU::Orientation orientation)\n    {\n        auto time = imu_t0 + ros::Duration(orientation.timestamp);\n\n        if (log_estimate.is_open()) {\n            log_estimate << time.toNSec() << \"\\t\";\n            log_estimate << std::setprecision(10) << orientation.timestamp << \"\\t\";\n            log_estimate << std::setprecision(10) << orientation.quaternion[3] << \"\\t\"; // w\n            log_estimate << std::setprecision(10) << orientation.quaternion[0] << \"\\t\"; // x\n            log_estimate << std::setprecision(10) << orientation.quaternion[1] << \"\\t\"; // y\n            log_estimate << std::setprecision(10) << orientation.quaternion[2];         // z\n            log_estimate << std::endl;\n        }\n\n        est_orientation_ = orientation;\n        PublishEstimateIfReady();\n    }\n\n    void QuaternionStdDevUpdate(IMU::QuaternionStdDev stddev)\n    {\n        est_quaternion_stddev_ = stddev;\n        PublishEstimateIfReady();\n    }\n\n    void AccelerationUpdate(IMU::StateEstimate estimate)\n    {\n        est_acceleration_ = estimate;\n        PublishEstimateIfReady();\n    }\n\n    void AngularVelocityUpdate(IMU::StateEstimate estimate)\n    {\n        auto time = imu_t0 + ros::Duration(estimate.timestamp);\n\n        if (log_angular_velocity.is_open()) {\n            log_angular_velocity << time.toNSec() << \"\\t\";\n            log_angular_velocity << std::setprecision(10) << estimate.timestamp << \"\\t\";\n            log_angular_velocity << std::setprecision(10) << estimate.estimate[0] << \"\\t\";\n            log_angular_velocity << std::setprecision(10) << estimate.estimate[1] << \"\\t\";\n            log_angular_velocity << std::setprecision(10) << estimate.estimate[2];\n            log_angular_velocity << std::endl;\n        }\n\n        est_angular_velocity_ = estimate;\n        PublishEstimateIfReady();\n    }\n\n    void BodyVelocityUpdate(IMU::StateEstimate estimate)\n    {\n        est_body_velocity_ = estimate;\n        PublishEstimateIfReady();\n    }\n\n    void PositionNEDUpdate(IMU::StateEstimate estimate)\n    {\n        est_position_NED_ = estimate;\n        PublishEstimateIfReady();\n    }\n\n    void odom_in_callback(const nav_msgs::Odometry::ConstPtr& msg)\n    {\n        if (log_odom_pose.is_open()) {\n            log_odom_pose << msg->header.stamp.toNSec() << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->pose.pose.orientation.w << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->pose.pose.orientation.x << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->pose.pose.orientation.y << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->pose.pose.orientation.z << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->pose.pose.position.x << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->pose.pose.position.y << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->pose.pose.position.z << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->twist.twist.linear.x << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->twist.twist.linear.y << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->twist.twist.linear.z << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->twist.twist.angular.x << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->twist.twist.angular.y << \"\\t\";\n            log_odom_pose << std::setprecision(10) << msg->twist.twist.angular.z;\n            log_odom_pose << std::endl;\n        }\n\n        odom_sample_count_++;\n        if (odom_sample_count_ % odom_downsample_rate_ != 0) return;\n\n        tf::Pose W_T_realsense;\n        tf::poseMsgToTF(msg->pose.pose, W_T_realsense);\n\n        tf::StampedTransform imu_T_realsense;\n        try {\n            tf_listener_.lookupTransform(imu_frame_, msg->child_frame_id, msg->header.stamp, imu_T_realsense);\n\n            // Note: The part below could also have been made smarter simply by looking up the imu_frame position in the world frame and reporting that\n            auto imu_orientation = imu_T_realsense.getRotation() * W_T_realsense.getRotation();\n\n            auto realsense_position_NED = tf::Vector3(W_T_realsense.getOrigin().x(),\n                                                      -W_T_realsense.getOrigin().y(),\n                                                      -W_T_realsense.getOrigin().z());\n\n            auto W_T_imu = W_T_realsense * imu_T_realsense.inverse();\n\n            auto imu_position_NED = tf::Vector3(W_T_imu.getOrigin().x(),\n                                               -W_T_imu.getOrigin().y(),\n                                               -W_T_imu.getOrigin().z());\n\n            // Compute heading from received Realsense orientation quaternion\n            tf::Vector3 xVector = tf::quatRotate(imu_orientation, tf::Vector3(1,0,0));\n            float heading = atan2(xVector.y(), xVector.x());\n\n            imu.SetHeading(heading, deg2rad(odom_heading_stddev_deg_));\n            imu.SetPositionNED(imu_position_NED.x(), imu_position_NED.y(), imu_position_NED.z(), odom_position_stddev_m_);\n\n            ROS_DEBUG(\"X,Y,Z - Heading = %f, %f, %f - %f\", imu_position_NED.x(), imu_position_NED.y(), imu_position_NED.z(), rad2deg(heading));\n        }\n        catch (tf::TransformException ex){\n            ROS_ERROR(\"%s\", ex.what());\n        }\n    }\n\n    void OpenLogFiles()\n    {\n        // Prepare logs folder\n        if (!boost::filesystem::is_directory(boost::filesystem::path(std::string(getenv(\"HOME\")) + \"/logs\"))) {\n            if (boost::filesystem::exists(boost::filesystem::path(std::string(getenv(\"HOME\")) + \"/logs\"))) {\n                printf(\"Log path (~/logs) already exists but without write permissions\\n\");\n                return;\n            } else {\n                if (!boost::filesystem::create_directory(boost::filesystem::path(std::string(getenv(\"HOME\")) + \"/logs\"))) {\n                    printf(\"Could not create Log folder (~/logs)\\n\");\n                    return;\n                }\n                else\n                    printf(\"Successfully created log folder (~/logs)\\n\");\n            }\n        }\n\n\n        std::string logTimestamp = utils::GetLogFormattedTimestamp(utils::utime());\n        log_raw.open(std::string(getenv(\"HOME\")) + \"/logs/\" + logTimestamp + \"_imu_raw.txt\", std::ofstream::trunc);\n        if (!log_raw.is_open()) {\n            std::cout << \"Could not create \" << logTimestamp + \"_imu_accel.txt\" << std::endl;\n        }\n\n        log_estimate.open(std::string(getenv(\"HOME\")) + \"/logs/\" + logTimestamp + \"_imu_estimate.txt\", std::ofstream::trunc);\n        if (!log_estimate.is_open()) {\n            std::cout << \"Could not create \" << logTimestamp + \"_imu_estimate.txt\" << std::endl;\n        }\n\n        log_angular_velocity.open(std::string(getenv(\"HOME\")) + \"/logs/\" + logTimestamp + \"_imu_angular_velocity.txt\", std::ofstream::trunc);\n        if (!log_angular_velocity.is_open()) {\n            std::cout << \"Could not create \" << logTimestamp + \"_imu_angular_velocity.txt\" << std::endl;\n        }\n\n        log_odom_pose.open(std::string(getenv(\"HOME\")) + \"/logs/\" + logTimestamp + \"_odom_pose.txt\", std::ofstream::trunc);\n        if (!log_odom_pose.is_open()) {\n            std::cout << \"Could not create \" << logTimestamp + \"_odom_pose.txt\" << std::endl;\n        }\n\n        loggingEnabled = true;\n    }\n\n    void CloseLogFiles()\n    {\n        log_raw.close();\n        log_estimate.close();\n        log_odom_pose.close();\n\n        loggingEnabled = false;\n    }\n\npublic:\n    IMUNode(ros::NodeHandle nh, ros::NodeHandle nParam, std::string world_frame, std::string imu_frame, std::string position_imu_frame,  bool enable_position_fusion, bool enable_heading_fusion, float odom_position_stddev_m, float odom_heading_stddev_deg, bool publish_tf, std::string log_path, int odom_downsample_rate = 1)\n            : include_standard_deviations_{false}\n            , enable_position_fusion_{enable_position_fusion}\n            , enable_heading_fusion_{enable_heading_fusion}\n            , odom_downsample_rate_{odom_downsample_rate}\n            , odom_position_stddev_m_{odom_position_stddev_m}\n            , odom_heading_stddev_deg_{odom_heading_stddev_deg}\n            , nh_(nh)\n            , nParam_(nParam)\n            , world_frame_{world_frame}\n            , imu_frame_{imu_frame}\n            , position_imu_frame_{position_imu_frame}\n            , publish_tf_{publish_tf}\n            , pub_imu_{nh.advertise<sensor_msgs::Imu>(\"imu/est\", 10)}\n            , pub_imu_pose_{nh.advertise<nav_msgs::Odometry>(\"imu/pose\", 10)}\n            , pub_imu_raw_{nh.advertise<sensor_msgs::Imu>(\"imu/raw\", 10)}\n            , pub_magnetic_field_{nh.advertise<sensor_msgs::MagneticField>(\"imu/mag\", 10)}\n            , sub_odom_in_{nh.subscribe(\"odom_in\", 50, &IMUNode::odom_in_callback, this)}\n    {\n        imu.RegisterCallback_RawSensors(std::bind(&IMUNode::RawSensorsUpdate, this, std::placeholders::_1));\n        imu.RegisterCallback_Orientation(std::bind(&IMUNode::OrientationUpdate, this, std::placeholders::_1));\n        imu.RegisterCallback_AngularVelocity(std::bind(&IMUNode::AngularVelocityUpdate, this, std::placeholders::_1));\n\n        if (enable_position_fusion_)\n            imu.RegisterCallback_Acceleration(std::bind(&IMUNode::AccelerationUpdate, this, std::placeholders::_1));\n\n        imu.LoadLog(log_path);\n    }\n    IMUNode(ros::NodeHandle nh, ros::NodeHandle nParam, std::string world_frame, std::string imu_frame, std::string position_imu_frame, bool enable_position_fusion, bool enable_heading_fusion, float odom_position_stddev_m, float odom_heading_stddev_deg, bool publish_tf, int raw_data_rate = 200, int estimate_data_rate = 100, int odom_downsample_rate = 1, bool include_standard_deviations = false, std::string port_name = \"/dev/ttyUSB0\", uint32_t baud_rate = 460800)\n            : imu(port_name, baud_rate)\n            , include_standard_deviations_{include_standard_deviations}\n            , enable_position_fusion_{enable_position_fusion}\n            , enable_heading_fusion_{enable_heading_fusion}\n            , odom_downsample_rate_{odom_downsample_rate}\n            , odom_position_stddev_m_{odom_position_stddev_m}\n            , odom_heading_stddev_deg_{odom_heading_stddev_deg}\n            , nh_(nh)\n            , nParam_(nParam)\n            , world_frame_{world_frame}\n            , imu_frame_{imu_frame}\n            , position_imu_frame_{position_imu_frame}\n            , publish_tf_{publish_tf}\n            , pub_imu_{nh.advertise<sensor_msgs::Imu>(\"imu/est\", 10)}\n            , pub_imu_pose_{nh.advertise<nav_msgs::Odometry>(\"imu/pose\", 10)}\n            , pub_imu_raw_{nh.advertise<sensor_msgs::Imu>(\"imu/raw\", 10)}\n            , pub_magnetic_field_{nh.advertise<sensor_msgs::MagneticField>(\"imu/mag\", 10)}\n            , sub_odom_in_{nh.subscribe(\"imu/odom_in\", 50, &IMUNode::odom_in_callback, this)} // odom_in\n    {\n        if (raw_data_rate < 0) raw_data_rate = 200;\n        if (estimate_data_rate < 0) estimate_data_rate = 200;\n\n        imu.Connect();\n        imu.Configure(IMU::OutputType::RawAndIndividualEstimates, raw_data_rate, estimate_data_rate, enable_heading_fusion_, enable_position_fusion_, include_standard_deviations_);\n        imu.SynchronizeTime(); // synchronize time again manually\n        imu_t0 = ros::Time().now();\n\n        imu.RegisterCallback_RawSensors(std::bind(&IMUNode::RawSensorsUpdate, this, std::placeholders::_1));\n        imu.RegisterCallback_Orientation(std::bind(&IMUNode::OrientationUpdate, this, std::placeholders::_1));\n        imu.RegisterCallback_AngularVelocity(std::bind(&IMUNode::AngularVelocityUpdate, this, std::placeholders::_1));\n\n        if (include_standard_deviations_)\n            imu.RegisterCallback_QuaternionStdDev(std::bind(&IMUNode::QuaternionStdDevUpdate, this, std::placeholders::_1));\n\n        if (enable_position_fusion_) {\n            imu.RegisterCallback_Acceleration(std::bind(&IMUNode::AccelerationUpdate, this, std::placeholders::_1));\n            imu.RegisterCallback_Velocity(std::bind(&IMUNode::BodyVelocityUpdate, this, std::placeholders::_1));\n            imu.RegisterCallback_PositionNED(std::bind(&IMUNode::PositionNEDUpdate, this, std::placeholders::_1));\n        }\n    }\n\n    ~IMUNode()\n    {\n        CloseLogFiles();\n    }\n\n    void StartLogging()\n    {\n        if (loggingEnabled) return;\n        OpenLogFiles();\n        imu.RecordANPPLog();\n    }\n\n    void StopLogging()\n    {\n        if (!loggingEnabled) return;\n        CloseLogFiles();\n        imu.StopANPPLog();\n    }\n\n};\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"imu_node\");\n    ros::NodeHandle nh;\n    ros::NodeHandle nParam(\"~\"); // default/current namespace node handle\n\n    int raw_data_rate = 100; // Hz\n    if (!nParam.getParam(\"raw_data_rate\", raw_data_rate)) {\n        ROS_WARN_STREAM(\"IMU Raw data rate not set (Parameter: raw_data_rate). Defaults to: \" << raw_data_rate);\n    }\n\n    int estimate_data_rate = 100; // Hz\n    if (!nParam.getParam(\"estimate_data_rate\", estimate_data_rate)) {\n        ROS_WARN_STREAM(\"IMU Estimate data rate not set (Parameter: estimate_data_rate). Defaults to: \" << estimate_data_rate);\n    }\n\n    bool publish_tf = true;\n    if (!nParam.getParam(\"publish_tf\", publish_tf)) {\n        ROS_WARN_STREAM(\"Publish Transform not set (Parameter: publish_tf). Defaults to: \" << publish_tf);\n    }\n\n    std::string world_frame = \"world\";\n    if (!nParam.getParam(\"world_frame\", world_frame)) {\n        ROS_WARN_STREAM(\"World frame not set (Parameter: world_frame). Defaults to: \" << world_frame);\n    }\n\n    std::string imu_frame = \"imu_link\";\n    if (!nParam.getParam(\"imu_frame\", imu_frame)) {\n        ROS_WARN_STREAM(\"IMU frame not set (Parameter: imu_frame). Defaults to: \" << imu_frame);\n    }\n\n    std::string position_imu_frame = \"imu\";\n    if (!nParam.getParam(\"position_imu_frame\", position_imu_frame)) {\n        ROS_WARN_STREAM(\"IMU publish frame not set (Parameter: position_imu_frame). Defaults to: \" << position_imu_frame);\n    }\n\n    bool enable_position_fusion = false;\n    if (!nParam.getParam(\"enable_position_fusion\", enable_position_fusion)) {\n        ROS_WARN_STREAM(\"IMU Position fusion flag not set (Parameter: enable_position_fusion). Defaults to: \" << enable_position_fusion);\n    }\n\n    bool enable_heading_fusion = false;\n    if (!nParam.getParam(\"enable_heading_fusion\", enable_heading_fusion)) {\n        ROS_WARN_STREAM(\"IMU Heading fusion flag not set (Parameter: enable_heading_fusion). Defaults to: \" << enable_heading_fusion);\n    }\n\n    int odom_downsample_rate = 10; // number of samples to skip + 1\n    if (!nParam.getParam(\"odom_downsample_rate\", odom_downsample_rate)) {\n        ROS_WARN_STREAM(\"IMU Odometry downsample rate not set (Parameter: odom_downsample_rate). Defaults to: \" << odom_downsample_rate);\n    }\n\n    float odom_position_stddev_m = 0.1; // m\n    if (!nParam.getParam(\"odom_position_stddev_m\", odom_position_stddev_m)) {\n        ROS_WARN_STREAM(\"IMU Odometry position standard deviation not set (Parameter: odom_position_stddev_m). Defaults to: \" << odom_position_stddev_m);\n    }\n\n    float odom_heading_stddev_deg = 1; // deg\n    if (!nParam.getParam(\"odom_heading_stddev_deg\", odom_heading_stddev_deg)) {\n        ROS_WARN_STREAM(\"IMU Odometry heading standard deviation not set (Parameter: odom_heading_stddev_deg). Defaults to: \" << odom_heading_stddev_deg);\n    }\n\n    try {\n        IMUNode node(nh, nParam, world_frame, imu_frame, position_imu_frame, enable_position_fusion, enable_heading_fusion, odom_position_stddev_m, odom_heading_stddev_deg, publish_tf, raw_data_rate, estimate_data_rate, odom_downsample_rate);\n        //IMUNode node(nh, nParam, world_frame, imu_frame, position_imu_frame, enable_position_fusion, enable_heading_fusion, odom_position_stddev_m, odom_heading_stddev_deg, publish_tf, \"SpatialLog_20-06-17_15-56-07.anpp\");\n        node.StartLogging();\n        ros::spin();\n    } catch(std::exception& e){\n        ROS_FATAL_STREAM(\"Exception thrown: \" << e.what());\n    }\n}\n", "meta": {"hexsha": "8266a761afcf51570b9f4b5c011586a46771720a", "size": 34046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros/jetsoncar_sensors/src/imu_spatial_node.cpp", "max_stars_repo_name": "mindThomas/JetsonCar", "max_stars_repo_head_hexsha": "74636d4da1f7f71ca9f2315a1b2347393b081eda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-09T08:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T15:18:36.000Z", "max_issues_repo_path": "ros/jetsoncar_sensors/src/imu_spatial_node.cpp", "max_issues_repo_name": "mindThomas/JetsonCar", "max_issues_repo_head_hexsha": "74636d4da1f7f71ca9f2315a1b2347393b081eda", "max_issues_repo_licenses": ["MIT"], "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/jetsoncar_sensors/src/imu_spatial_node.cpp", "max_forks_repo_name": "mindThomas/JetsonCar", "max_forks_repo_head_hexsha": "74636d4da1f7f71ca9f2315a1b2347393b081eda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-06T15:18:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T15:18:41.000Z", "avg_line_length": 47.7503506311, "max_line_length": 466, "alphanum_fraction": 0.6515009105, "num_tokens": 8080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19810702581556877}}
{"text": "#include <stan/math/rev.hpp>\n#include <boost/mp11.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/functor/test_fixture_ode.hpp>\n#include <test/unit/math/rev/functor/test_fixture_dae_index_3.hpp>\n#include <test/unit/math/rev/functor/dae_test_functors.hpp>\n\n/**\n *\n * Use same solver functor type for both w & w/o tolerance control\n */\ntemplate <typename solve_type, typename... Ts>\nusing ode_test_tuple = std::tuple<solve_type, solve_type, Ts...>;\n\n/**\n * Outer product of test types\n */\nusing dae_test_types = boost::mp11::mp_product<\n    ode_test_tuple, ::testing::Types<dae_functor>,\n    ::testing::Types<double>,                                  // t\n    ::testing::Types<double, stan::math::var_value<double> >,  // yy0\n    ::testing::Types<double, stan::math::var_value<double> >,  // yp0\n    ::testing::Types<double, stan::math::var_value<double> >   // theta\n    >;\n\nTYPED_TEST_SUITE_P(index_3_dae_test);\nTYPED_TEST_P(index_3_dae_test, solver_failure) {\n  EXPECT_THROW_MSG(this->apply_solver(), std::runtime_error,\n                   \"Error test failures occurred too many times\");\n  this->ts = {0.0001};\n  EXPECT_THROW_MSG(this->apply_solver_tol(), std::runtime_error,\n                   \"Error test failures occurred too many times\");\n}\n\nREGISTER_TYPED_TEST_SUITE_P(index_3_dae_test, solver_failure);\nINSTANTIATE_TYPED_TEST_SUITE_P(StanDAE, index_3_dae_test, dae_test_types);\n", "meta": {"hexsha": "25538c5408f55a43d4be21df4f407f3b75a914c8", "size": 1396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/functor/index_3_dae_typed_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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": "test/unit/math/rev/functor/index_3_dae_typed_test.cpp", "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": "test/unit/math/rev/functor/index_3_dae_typed_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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.7297297297, "max_line_length": 74, "alphanum_fraction": 0.7034383954, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19810702581556874}}
{"text": "// -*- lsst-c++ -*-\n\n/*\n * LSST Data Management System\n * Copyright 2008, 2009, 2010 LSST Corporation.\n *\n * This product includes software developed by the\n * LSST Project (http://www.lsst.org/).\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 LSST License Statement and\n * the GNU General Public License along with this program.  If not,\n * see <http://www.lsstcorp.org/LegalNotices/>.\n */\n#include \"lsst/afw/geom/ellipses/BaseCore.h\"\n#include \"lsst/afw/geom/ellipses/Quadrupole.h\"\n#include \"lsst/afw/geom/ellipses/Axes.h\"\n#include \"lsst/geom/Angle.h\"\n#include <boost/format.hpp>\n#include <map>\n\nnamespace lsst {\nnamespace afw {\nnamespace geom {\nnamespace ellipses {\n\nnamespace {\n\ntypedef std::map<std::string, std::shared_ptr<BaseCore> > RegistryMap;\n\nRegistryMap& getRegistry() {\n    static RegistryMap instance;\n    return instance;\n}\n\nstd::shared_ptr<BaseCore> getRegistryCopy(std::string const& name) {\n    RegistryMap::iterator i = getRegistry().find(name);\n    if (i == getRegistry().end()) {\n        throw LSST_EXCEPT(lsst::pex::exceptions::InvalidParameterError,\n                          (boost::format(\"Ellipse core with name '%s' not found in registry.\") % name).str());\n    }\n    return i->second->clone();\n}\n\n}  // namespace\n\nstd::shared_ptr<BaseCore> BaseCore::make(std::string const& name) {\n    std::shared_ptr<BaseCore> result = getRegistryCopy(name);\n    *result = Quadrupole();\n    return result;\n}\n\nstd::shared_ptr<BaseCore> BaseCore::make(std::string const& name, ParameterVector const& parameters) {\n    std::shared_ptr<BaseCore> result = getRegistryCopy(name);\n    result->setParameterVector(parameters);\n    return result;\n}\n\nstd::shared_ptr<BaseCore> BaseCore::make(std::string const& name, double v1, double v2, double v3) {\n    std::shared_ptr<BaseCore> result = getRegistryCopy(name);\n    result->setParameterVector(ParameterVector(v1, v2, v3));\n    return result;\n}\n\nstd::shared_ptr<BaseCore> BaseCore::make(std::string const& name, BaseCore const& other) {\n    std::shared_ptr<BaseCore> result = getRegistryCopy(name);\n    *result = other;\n    return result;\n}\n\nstd::shared_ptr<BaseCore> BaseCore::make(std::string const& name, Transformer const& other) {\n    std::shared_ptr<BaseCore> result = getRegistryCopy(name);\n    other.apply(*result);\n    return result;\n}\n\nstd::shared_ptr<BaseCore> BaseCore::make(std::string const& name, Convolution const& other) {\n    std::shared_ptr<BaseCore> result = getRegistryCopy(name);\n    other.apply(*result);\n    return result;\n}\n\nvoid BaseCore::registerSubclass(std::shared_ptr<BaseCore> const& example) {\n    getRegistry()[example->getName()] = example;\n}\n\nvoid BaseCore::grow(double buffer) {\n    double a, b, theta;\n    _assignToAxes(a, b, theta);\n    a += buffer;\n    b += buffer;\n    _assignFromAxes(a, b, theta);\n}\n\nvoid BaseCore::scale(double factor) {\n    double a, b, theta;\n    _assignToAxes(a, b, theta);\n    a *= factor;\n    b *= factor;\n    _assignFromAxes(a, b, theta);\n}\n\ndouble BaseCore::getArea() const {\n    double a, b, theta;\n    _assignToAxes(a, b, theta);\n    return a * b * lsst::geom::PI;\n}\n\ndouble BaseCore::getDeterminantRadius() const {\n    double a, b, theta;\n    _assignToAxes(a, b, theta);\n    return std::sqrt(a * b);\n}\n\ndouble BaseCore::getTraceRadius() const {\n    double ixx, iyy, ixy;\n    _assignToQuadrupole(ixx, iyy, ixy);\n    return std::sqrt(0.5 * (ixx + iyy));\n}\n\nlsst::geom::Extent2D BaseCore::computeDimensions() const {\n    double a, b, theta;\n    _assignToAxes(a, b, theta);\n    double c = std::cos(theta);\n    double s = std::sin(theta);\n    c *= c;\n    s *= s;\n    b *= b;\n    a *= a;\n    lsst::geom::Extent2D dimensions(std::sqrt(b * s + a * c), std::sqrt(a * s + b * c));\n    dimensions *= 2;\n    return dimensions;\n}\n\nBaseCore::ParameterVector const BaseCore::getParameterVector() const {\n    ParameterVector r;\n    writeParameters(r.data());\n    return r;\n}\n\nvoid BaseCore::setParameterVector(ParameterVector const& p) { readParameters(p.data()); }\n\nbool BaseCore::operator==(BaseCore const& other) const {\n    return getParameterVector() == other.getParameterVector() && getName() == other.getName();\n}\n\nBaseCore& BaseCore::operator=(BaseCore const& other) {\n    if (&other != this) {\n        // We use Axes instead of Quadrupole here because it allows us to copy Axes without\n        // implicitly normalizing them.\n        double a, b, theta;\n        other._assignToAxes(a, b, theta);\n        _assignFromAxes(a, b, theta);\n    }\n    return *this;\n}\n// Delegate to copy-constructor for backward-compatibility\nBaseCore& BaseCore::operator=(BaseCore&& other) { return *this = other; }\n\nBaseCore::Jacobian BaseCore::dAssign(BaseCore const& other) {\n    if (getName() == other.getName()) {\n        this->operator=(other);\n        return Jacobian::Identity();\n    }\n    // We use Quadrupole instead of Axes here because the ambiguity of the position angle\n    // in the circular case causes some of the Jacobians to/from Axes to be undefined for\n    // exact circles.  Quadrupoles don't have that problem, and the Axes-to-Axes case is\n    // handled by the above if block.\n    double ixx, iyy, ixy;\n    Jacobian rhs = other._dAssignToQuadrupole(ixx, iyy, ixy);\n    Jacobian lhs = _dAssignFromQuadrupole(ixx, iyy, ixy);\n    return lhs * rhs;\n}\n\nvoid BaseCore::_assignQuadrupoleToAxes(double ixx, double iyy, double ixy, double& a, double& b,\n                                       double& theta) {\n    double xx_p_yy = ixx + iyy;\n    double xx_m_yy = ixx - iyy;\n    double t = std::sqrt(xx_m_yy * xx_m_yy + 4 * ixy * ixy);\n    a = std::sqrt(0.5 * (xx_p_yy + t));\n    b = std::sqrt(0.5 * (xx_p_yy - t));\n    theta = 0.5 * std::atan2(2.0 * ixy, xx_m_yy);\n}\n\nBaseCore::Jacobian BaseCore::_dAssignQuadrupoleToAxes(double ixx, double iyy, double ixy, double& a,\n                                                      double& b, double& theta) {\n    double xx_p_yy = ixx + iyy;\n    double xx_m_yy = ixx - iyy;\n    double t2 = xx_m_yy * xx_m_yy + 4.0 * ixy * ixy;\n    Eigen::Vector3d dt2(2.0 * xx_m_yy, -2.0 * xx_m_yy, 8.0 * ixy);\n    double t = std::sqrt(t2);\n    a = std::sqrt(0.5 * (xx_p_yy + t));\n    b = std::sqrt(0.5 * (xx_p_yy - t));\n    theta = 0.5 * std::atan2(2.0 * ixy, xx_m_yy);\n    Jacobian m = Jacobian::Zero();\n    m(0, 0) = 0.25 * (1.0 + 0.5 * dt2[0] / t) / a;\n    m(0, 1) = 0.25 * (1.0 + 0.5 * dt2[1] / t) / a;\n    m(0, 2) = 0.25 * (0.5 * dt2[2] / t) / a;\n    m(1, 0) = 0.25 * (1.0 - 0.5 * dt2[0] / t) / b;\n    m(1, 1) = 0.25 * (1.0 - 0.5 * dt2[1] / t) / b;\n    m(1, 2) = 0.25 * (-0.5 * dt2[2] / t) / b;\n\n    m.row(2).setConstant(1.0 / (t * t));\n    m(2, 0) *= -ixy;\n    m(2, 1) *= ixy;\n    m(2, 2) *= xx_m_yy;\n    return m;\n}\n\nvoid BaseCore::_assignAxesToQuadrupole(double a, double b, double theta, double& ixx, double& iyy,\n                                       double& ixy) {\n    a *= a;\n    b *= b;\n    double c = std::cos(theta);\n    double s = std::sin(theta);\n    ixy = (a - b) * c * s;\n    c *= c;\n    s *= s;\n    ixx = c * a + s * b;\n    iyy = s * a + c * b;\n}\n\nBaseCore::Jacobian BaseCore::_dAssignAxesToQuadrupole(double a, double b, double theta, double& ixx,\n                                                      double& iyy, double& ixy) {\n    Jacobian m;\n    m.col(0).setConstant(2 * a);\n    m.col(1).setConstant(2 * b);\n    a *= a;\n    b *= b;\n    m.col(2).setConstant(a - b);\n    double c = std::cos(theta);\n    double s = std::sin(theta);\n    double cs = c * s;\n    ixy = (a - b) * c * s;\n    c *= c;\n    s *= s;\n    ixx = c * a + s * b;\n    iyy = s * a + c * b;\n    m(0, 0) *= c;\n    m(0, 1) *= s;\n    m(0, 2) *= -2.0 * cs;\n    m(1, 0) *= s;\n    m(1, 1) *= c;\n    m(1, 2) *= 2.0 * cs;\n    m(2, 0) *= cs;\n    m(2, 1) *= -cs;\n    m(2, 2) *= (c - s);\n    return m;\n}\n}  // namespace ellipses\n}  // namespace geom\n}  // namespace afw\n}  // namespace lsst\n", "meta": {"hexsha": "dc9898c0c5d998b23773c9917f8d78e3c4293a29", "size": 8301, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/afw/geom/ellipses/BaseCore.cc", "max_stars_repo_name": "DarkEnergySurvey/cosmicRays", "max_stars_repo_head_hexsha": "5c29bd9fc4a9f37e298e897623ec98fff4a8d539", "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/afw/geom/ellipses/BaseCore.cc", "max_issues_repo_name": "DarkEnergySurvey/cosmicRays", "max_issues_repo_head_hexsha": "5c29bd9fc4a9f37e298e897623ec98fff4a8d539", "max_issues_repo_licenses": ["NCSA"], "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/afw/geom/ellipses/BaseCore.cc", "max_forks_repo_name": "DarkEnergySurvey/cosmicRays", "max_forks_repo_head_hexsha": "5c29bd9fc4a9f37e298e897623ec98fff4a8d539", "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": 31.5627376426, "max_line_length": 110, "alphanum_fraction": 0.6140224069, "num_tokens": 2578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19810702581556874}}
{"text": "/*\n * Copyright 2020 Robert Bosch GmbH\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 * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * \\file osi_omni_sensor.hpp\n * \\see  osi_omni_sensor.cpp\n */\n\n#pragma once\n\n#include <map>      // for map<>\n#include <memory>   // for shared_ptr<>, unique_ptr<>\n#include <string>   // for string\n#include <utility>  // for move\n\n#include <Eigen/Geometry>  // for Isometry3d, Vector3d\n\n#include <cloe/component/lane_boundary.hpp>  // for LaneBoundary\n#include <cloe/component/object.hpp>         // for Object\n#include <cloe/core.hpp>                     // for Json, Duration\n#include <cloe/simulator.hpp>                // for ModelError\n#include <cloe/sync.hpp>                     // for Sync\n\n#include \"osi_common.pb.h\"           // for Timestamp, Identifier, BaseMoving, ..\n#include \"osi_detectedobject.pb.h\"   // for DetectedMovingObject\n#include \"osi_hostvehicledata.pb.h\"  // for HostVehicleData\n#include \"osi_object.pb.h\"           // for MovingObject\n#include \"osi_sensordata.pb.h\"       // for SensorData, DetectedEntityHeader\n\n#include \"osi_ground_truth.hpp\"  // for OsiGroundTruth\n#include \"osi_transceiver.hpp\"   // for OsiTransceiver\n#include \"osi_utils.hpp\"\n\nnamespace osii {\n\n/**\n * Convert OSI timestamp to Cloe time format.\n */\ncloe::Duration osi_timestamp_to_time(const osi3::Timestamp& timestamp);\n\nvoid from_osi_identifier(const osi3::Identifier& osi_id, int& id);\n\n/**\n * OSI host vehicle coordinates/orientations are relative to the global ground\n * truth coordinate system. Here, this data is stored in a Cloe object.\n */\nvoid from_osi_host_vehicle_data(const osi3::HostVehicleData& osi_hv, cloe::Object& obj);\n\n/**\n * Map the OSI data fields without taking care of transformations to the Cloe\n * reference frame convention.\n * Note that the OSI reference frame may differ for different object data types.\n */\nvoid from_osi_base_moving(const osi3::BaseMoving& osi_bm, cloe::Object& obj);\n\n/**\n * As from_osi_base_moving, but use ground truth information if required data is\n * not provided by sensor (model).\n */\nvoid from_osi_base_moving_alt(const osi3::BaseMoving& osi_bm,\n                              const osi3::BaseMoving& osi_bm_gt,\n                              cloe::Object& obj);\n\ntemplate <typename T>\nvoid from_osi_mov_obj_type_classification(const T& osi_mo, cloe::Object::Class& oc);\nvoid from_osi_mov_obj_type_classification(\n    const osi3::MovingObject::Type& osi_ot,\n    const osi3::MovingObject::VehicleClassification::Type& osi_vt,\n    cloe::Object::Class& oc);\n\nvoid from_osi_detected_moving_object_alt(const osi3::DetectedMovingObject& osi_mo,\n                                         const OsiGroundTruth& ground_truth, cloe::Object& obj);\n\nvoid from_osi_boundary_points(const osi3::LaneBoundary& osi_lb, cloe::LaneBoundary& lb);\n\nvoid transform_ego_coord_from_osi_data(const Eigen::Vector3d& dimensions_gt, cloe::Object& obj);\n\n/**\n * \\param sensor_pose: Relation between the sensor frame and the ego vehicle\n *                     frame, expressed in the ego vehicle frame.\n * \\param obj When enter: Geometric information in ego vehicle frame.\n *            When return: Geometric information in sensor frame.\n */\nvoid transform_obj_coord_from_osi_data(const Eigen::Isometry3d& sensor_pose,\n                                       const Eigen::Vector3d& dimensions_gt,\n                                       cloe::Object& obj);\n\nEigen::Isometry3d osi_position_orientation_to_pose_alt(const osi3::BaseMoving& base,\n                                                       const osi3::BaseMoving& base_gt);\n\nEigen::Vector3d osi_vehicle_attrib_rear_offset_to_vector3d(\n    const osi3::MovingObject::VehicleAttributes& osi_va);\n\n/**\n * OSI messages of the listed data types may be overwritten by ground truth\n * information, if requested by the user.\n */\nenum class SensorMockTarget { MountingPosition, DetectedMovingObject, DetectedLaneBoundary };\n\n/**\n * SensorMockLevel determines to which degree an OSI message of a certain data type\n * should be overwritten by ground truth information:\n *  - `Zero` means that the message is not altered (default behavior).\n *  - `MissingData` means that unavailable data fields are filled.\n *  - `All` means that the entire message is overwritten.\n */\nenum class SensorMockLevel { OverwriteNone, InterpolateMissing, OverwriteAll };\n\n// clang-format off\nENUM_SERIALIZATION(SensorMockLevel, ({\n  {SensorMockLevel::OverwriteNone, \"overwrite_none\"},\n  {SensorMockLevel::InterpolateMissing, \"interpolate_missing\"},\n  {SensorMockLevel::OverwriteAll, \"overwrite_all\"},\n}))\n// clang-format on\n\n/**\n * Configure sensor mock level.\n */\nstruct SensorMockConf : public cloe::Confable {\n  using Target = SensorMockTarget;\n  using Level = SensorMockLevel;\n\n  SensorMockConf() = default;\n\n  virtual ~SensorMockConf() noexcept = default;\n\n  std::map<Target, Level> level = {{Target::MountingPosition, Level::OverwriteNone},\n                                   {Target::DetectedMovingObject, Level::OverwriteNone},\n                                   {Target::DetectedLaneBoundary, Level::OverwriteNone}};\n\n  CONFABLE_SCHEMA(SensorMockConf) {\n    return fable::Schema{\n        // clang-format off\n        {\"mounting_position\", cloe::Schema(&level[Target::MountingPosition], \"mock level for sensor mounting position\")},\n        {\"detected_moving_objects\", cloe::Schema(&level[Target::DetectedMovingObject], \"mock level for detected moving objects\")},\n        {\"detected_lane_boundaries\", cloe::Schema(&level[Target::DetectedLaneBoundary], \"mock level for detected lane boundaries\")},\n        // clang-format on\n    };\n  }\n\n  void to_json(cloe::Json& j) const override {\n    j[\"mounting_position\"] = level.at(SensorMockTarget::MountingPosition);\n    j[\"detected_moving_objects\"] = level.at(SensorMockTarget::DetectedMovingObject);\n    j[\"detected_lane_boundaries\"] = level.at(SensorMockTarget::DetectedLaneBoundary);\n  }\n};\n\n/**\n * Base class for an OSI sensor which is connected via TCP.\n */\nclass OsiOmniSensor {\n public:\n  virtual ~OsiOmniSensor() = default;\n  OsiOmniSensor() = delete;\n\n  /**\n   * Create a new instance of OsiOmniSensor with the given OsiTransceiver.\n   */\n  OsiOmniSensor(std::unique_ptr<OsiTransceiver>&& osi_transceiver, uint64_t owner_id)\n      : osi_comm_(std::move(osi_transceiver)), owner_id_(owner_id) {\n    ground_truth_ = std::make_unique<OsiGroundTruth>();\n  }\n\n  /**\n   * Create a new instance of OsiOmniSensor with the given new OsiTransceiver.\n   *\n   * WARNING: If you use this constructor, please realize that OsiOmniSensor\n   *          takes ownership of the pointer you pass in.\n   */\n  OsiOmniSensor(OsiTransceiver* osi_transceiver, uint64_t owner_id)\n      : osi_comm_(osi_transceiver), owner_id_(owner_id) {\n    ground_truth_ = std::make_unique<OsiGroundTruth>();\n  }\n\n  /**\n   * Receive and process the incoming messages.\n   */\n  virtual void step(const cloe::Sync& s, const bool& restart, cloe::Duration& sim_time);\n\n  /**\n   * Store the initial timestamp.\n   * Note that the osi time does not necessarily start at zero.\n   */\n  virtual void process(const osi3::Timestamp& timestamp);\n\n  /**\n   * Translate OSI SensorData to Cloe data objects.\n   *\n   * \\param osi_sd SensorData message to be processed.\n   * \\param sim_time Simulation time to be set.\n   */\n  virtual void process(osi3::SensorData* osi_sd, cloe::Duration& sim_time);\n\n  /**\n   * Translate OSI SensorView to Cloe data objects.\n   *\n   * \\param osi_sv SensorView message to be processed, including ground truth.\n   */\n  virtual void process(const osi3::SensorView& osi_sv);\n\n  /**\n   * Translate OSI ego base information made available to the sensor model\n   * from other components, or use ground truth.\n   * \\param osi_hv HostVehicleData message to be processed (if available).\n   * \\param osi_mo MovingObject (ground truth) used as fallback.\n   */\n  virtual void process(const bool has_veh_data,\n                       const osi3::HostVehicleData& osi_hv,\n                       const osi3::MovingObject& osi_ego);\n\n  /**\n   * Translate OSI detected moving object information to Cloe data objects.\n   *\n   * \\param osi_eh DetectedEntityHeader message to be processed (if available).\n   * \\param osi_mo DetectedMovingObject message to be processed.\n   */\n  virtual void process(const bool has_eh,\n                       const osi3::DetectedEntityHeader& osi_eh,\n                       const osi3::DetectedMovingObject& osi_mo);\n\n  void mock_detected_lane_boundaries();\n\n  void from_osi_boundary_points(const osi3::LaneBoundary& osi_lb, cloe::LaneBoundary& lb);\n\n  /**\n   * Store the ego object that should be passed to Cloe.\n   *\n   * \\param ego_obj Ego object to be stored.\n   */\n  virtual void store_ego_object(std::shared_ptr<cloe::Object> ego_obj) = 0;\n\n  /**\n   * Store a detected object in a list of Cloe data objects.\n   *\n   * \\param obj Object to be stored.\n   */\n  virtual void store_object(std::shared_ptr<cloe::Object> obj) = 0;\n\n  /**\n   * Store a detected lane boundary in a map of Cloe data objects.\n   *\n   * \\param lb Lane boundary to be stored.\n   */\n  virtual void store_lane_boundary(const cloe::LaneBoundary& lb) = 0;\n\n  /**\n   * Store the sensor pose etc. in the corresponding Cloe sensor component.\n   */\n  virtual void store_sensor_meta_data(const Eigen::Vector3d& bbcenter_to_veh_origin,\n                                      const Eigen::Vector3d& ego_dimensions) = 0;\n\n  /**\n  * Get the current simulation time (t-t0).\n  */\n  cloe::Duration osi_timestamp_to_simtime(const osi3::Timestamp& timestamp) const;\n\n  /**\n  * Get sensor pose in OSI vehicle reference frame, e.g. from simulator configuration.\n  */\n  virtual Eigen::Isometry3d get_static_mounting_position(\n      const Eigen::Vector3d& bbcenter_to_veh_origin, const Eigen::Vector3d& ego_dimensions) = 0;\n\n  virtual void set_mock_conf(std::shared_ptr<const SensorMockConf> mock) = 0;\n\n  SensorMockLevel get_mock_level(SensorMockTarget trg_type) const {\n    return mock_->level.at(trg_type);\n  }\n\n  friend void to_json(cloe::Json& j, const OsiOmniSensor& c) {\n    j = cloe::Json{\n        {\"osi_connection\", *c.osi_comm_},\n    };\n  }\n\n protected:\n  /// Connection via TCP to simulator.\n  /// Should always be valid.\n  std::unique_ptr<OsiTransceiver> osi_comm_;\n\n  /// Access to osi ground truth, e.g. for mock-ups.\n  std::unique_ptr<OsiGroundTruth> ground_truth_;\n\n  /// Id of the sensor's owner (ego).\n  uint64_t owner_id_;\n\n  /// Store ego pose (reference point is rear axle center, not ground level).\n  Eigen::Isometry3d osi_ego_pose_;\n\n  /// Store sensor pose relative to the ego frame (rear axle center, not ground level).\n  Eigen::Isometry3d osi_sensor_pose_;\n\n  /// Initial simulation time.\n  cloe::Duration init_time_ = cloe::Duration(-1);\n\n  /// Use alternative source for required data or overwrite incoming data, if requested.\n  std::shared_ptr<const SensorMockConf> mock_{nullptr};\n};\n}  // namespace osii\n", "meta": {"hexsha": "5d481c8e8a19f0c0d884515b23210c0bb827e4d7", "size": 11422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "plugins/vtd/src/osi_omni_sensor.hpp", "max_stars_repo_name": "Sidharth-S-S/cloe", "max_stars_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T18:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:35:28.000Z", "max_issues_repo_path": "plugins/vtd/src/osi_omni_sensor.hpp", "max_issues_repo_name": "Sidharth-S-S/cloe", "max_issues_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-20T10:13:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:27:19.000Z", "max_forks_repo_path": "plugins/vtd/src/osi_omni_sensor.hpp", "max_forks_repo_name": "Sidharth-S-S/cloe", "max_forks_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T08:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T10:09:53.000Z", "avg_line_length": 36.3757961783, "max_line_length": 132, "alphanum_fraction": 0.6995272282, "num_tokens": 2807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19810702581556874}}
{"text": "#ifndef STAN_MCMC_HMC_HAMILTONIANS_AUTO_E_METRIC_HPP\n#define STAN_MCMC_HMC_HAMILTONIANS_AUTO_E_METRIC_HPP\n\n#include <stan/callbacks/logger.hpp>\n#include <stan/math/prim.hpp>\n#include <stan/mcmc/hmc/hamiltonians/base_hamiltonian.hpp>\n#include <stan/mcmc/hmc/hamiltonians/auto_e_point.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n\nnamespace stan {\nnamespace mcmc {\n\n// Euclidean manifold with dense metric\ntemplate <class Model, class BaseRNG>\nclass auto_e_metric : public base_hamiltonian<Model, auto_e_point, BaseRNG> {\n public:\n  explicit auto_e_metric(const Model& model)\n      : base_hamiltonian<Model, auto_e_point, BaseRNG>(model) {}\n\n  double T(auto_e_point& z) {\n    return 0.5 * z.p.transpose() * z.inv_e_metric_ * z.p;\n  }\n\n  double tau(auto_e_point& z) { return T(z); }\n\n  double phi(auto_e_point& z) { return this->V(z); }\n\n  double dG_dt(auto_e_point& z, callbacks::logger& logger) {\n    return 2 * T(z) - z.q.dot(z.g);\n  }\n\n  Eigen::VectorXd dtau_dq(auto_e_point& z, callbacks::logger& logger) {\n    return Eigen::VectorXd::Zero(this->model_.num_params_r());\n  }\n\n  Eigen::VectorXd dtau_dp(auto_e_point& z) {\n    if (z.is_diagonal_) {\n      return z.inv_e_metric_.diagonal().cwiseProduct(z.p);\n    } else {\n      return z.inv_e_metric_ * z.p;\n    }\n  }\n\n  Eigen::VectorXd dphi_dq(auto_e_point& z, callbacks::logger& logger) {\n    return z.g;\n  }\n\n  void sample_p(auto_e_point& z, BaseRNG& rng) {\n    typedef typename stan::math::index_type<Eigen::VectorXd>::type idx_t;\n    boost::variate_generator<BaseRNG&, boost::normal_distribution<> > rand_gaus(\n        rng, boost::normal_distribution<>());\n\n    if (z.is_diagonal_) {\n      for (int i = 0; i < z.p.size(); ++i)\n        z.p(i) = rand_gaus() / sqrt(z.inv_e_metric_(i, i));\n    } else {\n      Eigen::VectorXd u(z.p.size());\n\n      for (idx_t i = 0; i < u.size(); ++i)\n        u(i) = rand_gaus();\n\n      z.p = z.inv_e_metric_.llt().matrixU().solve(u);\n    }\n  }\n};\n\n}  // namespace mcmc\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "3041252a6513337e755a246c9493ac628e450ce4", "size": 2034, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/mcmc/hmc/hamiltonians/auto_e_metric.hpp", "max_stars_repo_name": "hsbadr/stan", "max_stars_repo_head_hexsha": "663a5d30334c37961e323ef8cee9d42b091cb9e7", "max_stars_repo_licenses": ["CC-BY-3.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": "src/stan/mcmc/hmc/hamiltonians/auto_e_metric.hpp", "max_issues_repo_name": "hsbadr/stan", "max_issues_repo_head_hexsha": "663a5d30334c37961e323ef8cee9d42b091cb9e7", "max_issues_repo_licenses": ["CC-BY-3.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/stan/mcmc/hmc/hamiltonians/auto_e_metric.hpp", "max_forks_repo_name": "hsbadr/stan", "max_forks_repo_head_hexsha": "663a5d30334c37961e323ef8cee9d42b091cb9e7", "max_forks_repo_licenses": ["CC-BY-3.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": 28.6478873239, "max_line_length": 80, "alphanum_fraction": 0.6764995084, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1981070258155687}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2017-2018, Oracle and/or its affiliates.\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_TEST_SRS_PROJ4_HPP\r\n#define BOOST_GEOMETRY_TEST_SRS_PROJ4_HPP\r\n\r\n#ifdef TEST_WITH_PROJ4\r\n\r\n#include <string>\r\n\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n\r\n#include <proj_api.h>\r\n\r\nstruct pj_ptr\r\n{\r\n    explicit pj_ptr(projPJ ptr)\r\n        : m_ptr(ptr)\r\n    {\r\n        if (ptr == NULL)\r\n            throw std::runtime_error(\"bleh\");\r\n    }\r\n\r\n    projPJ get() const\r\n    {\r\n        return m_ptr;\r\n    }\r\n\r\n    ~pj_ptr()\r\n    {\r\n        if (m_ptr)\r\n            pj_free(m_ptr);\r\n    }\r\n\r\nprivate:\r\n    projPJ m_ptr;\r\n};\r\n\r\nstruct pj_projection\r\n{\r\n    pj_projection(std::string const& prj)\r\n        : m_ptr(pj_init_plus(prj.c_str()))\r\n    {}\r\n\r\n    template <typename In, typename Out>\r\n    void forward(In const& in, Out & out) const\r\n    {\r\n        double x = bg::get_as_radian<0>(in);\r\n        double y = bg::get_as_radian<1>(in);\r\n    \r\n        projUV p1;\r\n        projUV p2;\r\n\r\n        p1.u = x;\r\n        p1.v = y;\r\n\r\n        p2 = pj_fwd(p1, m_ptr.get());\r\n\r\n        bg::set_from_radian<0>(out, p2.u);\r\n        bg::set_from_radian<1>(out, p2.v);\r\n    }\r\n\r\n    template <typename In, typename Out>\r\n    void inverse(In const& in, Out & out) const\r\n    {\r\n        double lon = bg::get_as_radian<0>(in);\r\n        double lat = bg::get_as_radian<1>(in);\r\n    \r\n        projUV p1;\r\n        projUV p2;\r\n\r\n        p1.u = lon;\r\n        p1.v = lat;\r\n\r\n        p2 = pj_inv(p1, pj_prj.get());\r\n\r\n        bg::set_from_radian<0>(out, p2.u);\r\n        bg::set_from_radian<1>(out, p2.v);\r\n    }\r\n\r\nprivate:\r\n    pj_ptr m_ptr;\r\n};\r\n\r\nstruct pj_transformation\r\n{\r\n    pj_transformation(std::string const& from, std::string const& to)\r\n        : m_from(pj_init_plus(from.c_str()))\r\n        , m_to(pj_init_plus(to.c_str()))\r\n    {}\r\n\r\n    template <typename In, typename Out>\r\n    void forward(In const& in, Out & out) const\r\n    {\r\n        double x = bg::get_as_radian<0>(in);\r\n        double y = bg::get_as_radian<1>(in);\r\n    \r\n        pj_transform(m_from.get(), m_to.get(), 1, 0, &x, &y, NULL);\r\n\r\n        bg::set_from_radian<0>(out, x);\r\n        bg::set_from_radian<1>(out, y);\r\n    }\r\n\r\n    void forward(std::vector<double> in_x,\r\n                 std::vector<double> in_y,\r\n                 std::vector<double> & out_x,\r\n                 std::vector<double> & out_y) const\r\n    {\r\n        assert(in_x.size() == in_y.size());\r\n        pj_transform(m_from.get(), m_to.get(), in_x.size(), 1, &in_x[0], &in_y[0], NULL);\r\n        out_x = in_x;\r\n        out_y = in_y;\r\n    }\r\n\r\nprivate:\r\n    pj_ptr m_from;\r\n    pj_ptr m_to;\r\n};\r\n\r\n#endif // TEST_WITH_PROJ4\r\n\r\n#endif // BOOST_GEOMETRY_TEST_SRS_PROJ4_HPP\r\n", "meta": {"hexsha": "f69f087e0bfa465493ae2b49c9e1d1c37af963e9", "size": 3009, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/geometry/test/srs/proj4.hpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "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/geometry/test/srs/proj4.hpp", "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/geometry/test/srs/proj4.hpp", "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": 23.1461538462, "max_line_length": 90, "alphanum_fraction": 0.5603190429, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1981070258155687}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp\n//! \\author Alex Robinson, Eli Moll\n//! \\brief  Tet mesh flux estimator class declaration.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_TET_MESH_TRACK_LENGTH_FLUX_ESTIMATOR_HPP\n#define MONTE_CARLO_TET_MESH_TRACK_LENGTH_FLUX_ESTIMATOR_HPP\n\n// Std Lib Includes\n#include <string>\n\n// Boost Includes\n#include <boost/mpl/vector.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/unordered_set.hpp>\n\n// Moab Includes\n#include <moab/Interface.hpp>\n#include <moab/AdaptiveKDTree.hpp>\n#include <moab/Matrix3.hpp>\n\n// Trilinos Includes\n#include <Teuchos_RCP.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_StandardEntityEstimator.hpp\"\n#include \"MonteCarlo_ParticleSubtrackEndingGlobalEventObserver.hpp\"\n#include \"MonteCarlo_EstimatorContributionMultiplierPolicy.hpp\"\n#include \"Geometry_ModuleTraits.hpp\"\n#include \"MonteCarlo_ParticleState.hpp\"\n\nnamespace MonteCarlo{\n\n/*! The tet-mesh track length flux estimator class\n * \\details This class is based off of the TrackLengthMeshTally written by\n * Kerry Dunn (UW-Madison CNERG group). The DAGMC repo that contains her\n * class can be found at https://github.com/svalinn/DAGMC.\n */\ntemplate<typename ContributionMutliplierPolicy = WeightMultiplier>\nclass TetMeshTrackLengthFluxEstimator : public StandardEntityEstimator<moab::EntityHandle>,\n  public ParticleSubtrackEndingGlobalEventObserver\n{\n\npublic:\n\n  //! Typedef for the cell id type\n  typedef Geometry::ModuleTraits::InternalCellHandle cellIdType;\n\n  //! Typedef for event tags used for quick dispatcher registering\n  typedef boost::mpl::vector<ParticleSubtrackEndingGlobalEventObserver::EventTag>\n  EventTags;\n\n  //! Constructor\n  TetMeshTrackLengthFluxEstimator(\n\t\t     const Estimator::idType id,\n\t\t     const double multiplier,\n\t\t     const std::string input_mesh_file_name,\n\t\t     const std::string output_mesh_file_name = \"tetmesh.h5m\" );\n\n  //! Destructor\n  ~TetMeshTrackLengthFluxEstimator()\n  { /* ... */ }\n\n  //! Set the response functions\n  void setResponseFunctions(\n  const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_functions );\n\n  //! Set the particle types that can contribute to the estimator\n  void setParticleTypes( const Teuchos::Array<ParticleType>& particle_types );\n\n  //! Add current history estimator contribution\n  void updateFromGlobalParticleSubtrackEndingEvent(\n\t\t\t\t\t\t const ParticleState& particle,\n\t\t\t\t\t\t const double start_point[3],\n\t\t\t\t\t\t const double end_point[3] );\n\n  //! Export the estimator data\n  void exportData( EstimatorHDF5FileHandler& hdf5_file,\n\t\t   const bool process_data ) const;\n\n  //! Print the estimator data\n  void print( std::ostream& os ) const;\n\n  //! Get all tet elements\n  const moab::Range getAllTetElements() const;\n\n  //! Test if a point is in the mesh\n  bool isPointInMesh( const double point[3] );\n\n  //! Determine which tet the point is in\n  moab::EntityHandle whichTetIsPointIn( const double point[3] );\n\nprivate:\n\n  // Assign bin boundaries to an estimator dimension\n  void assignBinBoundaries(\n\tconst Teuchos::RCP<EstimatorDimensionDiscretization>& bin_boundaries );\n\n  // The tolerance used for geometric tests\n  static const double s_tol;\n\n  // The moab instance that stores all mesh data\n  Teuchos::RCP<moab::Interface> d_moab_interface;\n\n  // The tet meshset\n  moab::EntityHandle d_tet_meshset;\n\n  // The kd-tree for finding point in tet\n  Teuchos::RCP<moab::AdaptiveKDTree> d_kd_tree;\n  \n  // The root of the kd-tree\n  moab::EntityHandle d_kd_tree_root;\n\n  // The map of tet ids and barycentric coordinate transform matrices\n  boost::unordered_map<moab::EntityHandle,moab::Matrix3> \n  d_tet_barycentric_transform_matrices;\n  \n  // The map of tet ids and reference vertices\n  boost::unordered_map<moab::EntityHandle, moab::CartVect>\n  d_tet_reference_vertices;\n  \n  // The output mesh file name\n  std::string d_output_mesh_name;\n};\n  \n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"MonteCarlo_TetMeshTrackLengthFluxEstimator_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end MONTE_CARLO_TET_MESH_TRACK_LENGTH_FLUX_ESTIMATOR_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "294b61772bf05017a1711d9de37f7680a1d53644", "size": 4660, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator.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/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator.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/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator.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": 32.3611111111, "max_line_length": 91, "alphanum_fraction": 0.6770386266, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.19805170031997832}}
{"text": "#include \"ag_CumDistributionFunctionView.h\"\n\n// Library headers.\n#include <boost/smart_ptr.hpp>\n#include <QApplication>\n#include <QPen>\n#include <qwt_plot_canvas.h>\n#include <qwt_scale_div.h>\n\n// PCRaster library headers.\n#include \"dal_DataSpace.h\"\n#include \"dal_Table.h\"\n#include \"dal_MathUtils.h\"\n#include \"com_userdefinedclassifier.h\"\n\n// Module headers.\n#include \"ag_DataObject.h\"\n#include \"ag_DataProperties.h\"\n#include \"ag_Raster.h\"\n#include \"ag_RasterDataSources.h\"\n#include \"ag_VisEngine.h\"\n\n\n\n/*!\n  \\file\n  This file contains the implementation of the CumDistributionFunctionView class.\n*/\n\n\n\nnamespace ag {\n\n//------------------------------------------------------------------------------\n// DEFINITION OF STATIC CUMDISTRIBUTIONFUNCTIONVIEW MEMBERS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF CUMDISTRIBUTIONFUNCTIONVIEW MEMBERS\n//------------------------------------------------------------------------------\n\nCumDistributionFunctionView::CumDistributionFunctionView(\n         DataObject* object, QWidget* parent, const char* name)\n\n  : PlotVisualisation(object, \"Cumulative Distribution Function View\",\n         parent, name)\n\n{\n  // Supported data types.\n  std::vector<geo::DataType> dataTypes;\n  dataTypes.push_back(geo::STACK);\n  dataTypes.push_back(geo::FEATURE);\n  setSupportedDataTypes(dataTypes);\n\n  std::vector<CSF_VS> valueScales;\n  valueScales.push_back(VS_SCALAR);\n  setSupportedValueScales(valueScales);\n\n  trackDragPoint();\n\n  canvas()->setCursor(Qt::PointingHandCursor);\n}\n\n\n\nCumDistributionFunctionView::~CumDistributionFunctionView()\n{\n}\n\n\n\nvoid CumDistributionFunctionView::rescan()\n{\n  visualisationEngine().rescan(dataObject());\n}\n\n\n\nvoid CumDistributionFunctionView::process()\n{\n  if(visualisationEngine().change() & VisEngine::OTHERATTRIB ||\n         visualisationEngine().change() & VisEngine::DRAWPROPS ||\n         visualisationEngine().change() & VisEngine::SELECTION ||\n         visualisationEngine().change() & VisEngine::TIME ||\n         visualisationEngine().change() & VisEngine::RASTER_CELL) {\n    clearPlot();\n    createPlot();\n  }\n  else {\n    if(visualisationEngine().change() & VisEngine::QUANTILE) {\n      assert(!(visualisationEngine().change() & VisEngine::VALUE_SELECTION));\n\n      dal::DataSpace const& space(dataObject().dataSpace());\n\n      if(space.hasCumProbabilities()) {\n        dal::DataSpaceAddress const& address(dataObject().dataSpaceAddress());\n        size_t index = space.indexOf(dal::CumulativeProbabilities);\n        double quantile = address.coordinate<float>(index);\n\n        setYMarker(quantile);\n      }\n    }\n    else if(visualisationEngine().change() & VisEngine::VALUE_SELECTION) {\n      assert(!(visualisationEngine().change() & VisEngine::QUANTILE));\n      assert(dataObject().hasSelectedValue());\n\n      setXMarker(dataObject().selectedValue());\n    }\n  }\n\n  if(visualisationEngine().change() & VisEngine::BACKGROUND_COLOUR) {\n    if(!dataObject().backgroundColour().isValid()) {\n      setPalette(QPalette());\n    }\n    else {\n      QPalette palette;\n      palette.setColor(backgroundRole(), dataObject().backgroundColour());\n      setPalette(palette);\n    }\n  }\n}\n\n\n\nvoid CumDistributionFunctionView::visualise()\n{\n  if(visualisationEngine().change() & VisEngine::OTHERATTRIB ||\n         visualisationEngine().change() & VisEngine::DRAWPROPS ||\n         visualisationEngine().change() & VisEngine::VALUE_SELECTION ||\n         visualisationEngine().change() & VisEngine::SELECTION ||\n         visualisationEngine().change() & VisEngine::RASTER_CELL ||\n         visualisationEngine().change() & VisEngine::TIME ||\n         visualisationEngine().change() & VisEngine::QUANTILE ||\n         visualisationEngine().change() & VisEngine::BACKGROUND_COLOUR) {\n    replot();\n  }\n\n  visualisationEngine().finishedScanning(dataObject());\n}\n\n\n\nvoid CumDistributionFunctionView::addAttribute(\n         DataGuide const& dataGuide) {\n  testDataGuide(dataGuide);\n  visualisationEngine().addAttribute(dataObject(), dataGuide);\n}\n\n\n\nvoid CumDistributionFunctionView::setXAxisTitle()\n{\n  QwtText title;\n\n  title.setFont(QApplication::font());\n  title.setText(QString(\"Value\"));\n  setAxisTitle(xBottom, title);\n}\n\n\n\nvoid CumDistributionFunctionView::setYAxisTitle()\n{\n  QwtText title;\n\n  title.setFont(QApplication::font());\n\n  if(onlyCumulativeProbabilitiesShown()) {\n    title.setText(QString(\"Cumulative probability\"));\n  }\n  else if(onlyExceedanceProbabilitiesShown()) {\n    title.setText(QString(\"Exceedance probability\"));\n  }\n  else {\n    title.setText(QString(\"Probability\"));\n  }\n\n  setAxisTitle(yLeft, title);\n}\n\n\n\nvoid CumDistributionFunctionView::setXAxisScale()\n{\n  double min, max;\n  pcr::setMV(min);\n  pcr::setMV(max);\n  bool extremesInitialised = false;\n\n  if(!dataObject().hasSelectedValue()) {\n    BOOST_FOREACH(DataGuide const& guide, visualisationEngine().dataGuides()) {\n      assert(guide.valueScale() == VS_SCALAR);\n\n      RangeDrawProps const& properties(\n         dataObject().properties().rangeDrawProperties(guide));\n\n      if(properties.cutoffsAreValid()) {\n        if(!extremesInitialised) {\n          min = properties.minCutoff();\n          max = properties.maxCutoff();\n          extremesInitialised = true;\n        }\n        else {\n          min = std::min(min, properties.minCutoff());\n          max = std::max(max, properties.maxCutoff());\n        }\n      }\n    }\n  }\n  else {\n    SpatialDataset* dataset;\n\n    BOOST_FOREACH(DataGuide const& guide, visualisationEngine().dataGuides()) {\n      assert(guide.type() == geo::STACK || guide.type() == geo::FEATURE);\n      assert(guide.valueScale() == VS_SCALAR);\n      dataset = 0;\n\n      switch(guide.type()) {\n        case geo::STACK: {\n          dataset = &dataObject().rasterDataSources().data(guide);\n          break;\n        }\n        case geo::FEATURE: {\n          dataset = &dataObject().featureDataSources().data(guide);\n          break;\n        }\n        default: {\n          assert(false);\n          break;\n        }\n      }\n\n      assert(dataset);\n      assert(dataset->dataSpace().hasCumProbabilities());\n\n      if(!dataset->allMV()) {\n        if(!extremesInitialised) {\n          min = dataset->min<REAL4>();\n          max = dataset->max<REAL4>();\n          extremesInitialised = true;\n        }\n        else {\n          min = std::min(min, double(dataset->min<REAL4>()));\n          max = std::max(max, double(dataset->max<REAL4>()));\n        }\n      }\n    }\n  }\n\n  if(!pcr::isMV(min) && !pcr::isMV(max)) {\n    assert(min <= max);\n    setAxisScale(xBottom, min, max);\n  }\n}\n\n\n\nvoid CumDistributionFunctionView::setYAxisScale()\n{\n  double min = 0.0;\n  double max = 1.0;\n\n  if(dataObject().hasSelectedValue()) {\n    bool extremesInitialised = false;\n\n    BOOST_FOREACH(DataGuide const& guide, visualisationEngine().dataGuides()) {\n      assert(guide.valueScale() == VS_SCALAR);\n\n      RangeDrawProps const& properties(\n         dataObject().properties().rangeDrawProperties(guide));\n\n      if(properties.cutoffsAreValid()) {\n        if(!extremesInitialised) {\n          min = properties.minCutoff();\n          max = properties.maxCutoff();\n          extremesInitialised = true;\n        }\n        else {\n          min = std::min(min, properties.minCutoff());\n          max = std::max(max, properties.maxCutoff());\n        }\n      }\n    }\n  }\n\n  setAxisScale(yLeft, min, max);\n}\n\n\n\nvoid CumDistributionFunctionView::configureXAxis()\n{\n  setXAxisTitle();\n  setXAxisScale();\n}\n\n\n\nvoid CumDistributionFunctionView::configureYAxis()\n{\n  setYAxisTitle();\n  setYAxisScale();\n}\n\n\n\nvoid CumDistributionFunctionView::drawPlots()\n{\n  DataObject& object(dataObject());\n  dal::DataSpace const& space(object.dataSpace());\n  dal::DataSpaceAddress const& address(dataObject().dataSpaceAddress());\n\n  SpatialDataset* dataset;\n\n  BOOST_FOREACH(DataGuide const& guide, visualisationEngine().dataGuides()) {\n    assert(guide.type() == geo::STACK || guide.type() == geo::FEATURE);\n    assert(guide.valueScale() == VS_SCALAR);\n\n    dataset = 0;\n\n    switch(guide.type()) {\n      case geo::STACK: {\n        dataset = &object.rasterDataSources().data(guide);\n        break;\n      }\n      case geo::FEATURE: {\n        dataset = &object.featureDataSources().data(guide);\n        break;\n      }\n      default: {\n        assert(false);\n        break;\n      }\n    }\n\n    assert(dataset);\n    assert(dataset->dataSpace().hasCumProbabilities());\n\n    if(!dataset->allMV()) {\n      // Create table for data values at the quantile levels.\n      dal::Table table;\n      dataset->readCumulativeProbabilities(space, address, table);\n\n      dal::Array<REAL4> const& quantileCol(table.col<REAL4>(0));\n      dal::Array<REAL4> const& attrCol(table.col<REAL4>(1));\n      boost::scoped_array<double> x(new double[table.nrRecs()]);\n      boost::scoped_array<double> y(new double[table.nrRecs()]);\n\n      RangeDrawProps const& properties(\n        object.properties().rangeDrawProperties(guide));\n\n      for(size_t i = 0; i < table.nrRecs(); ++i) {\n        y[i] = quantileCol[i];\n\n        if(properties.probabilityScale() ==\n               RangeDrawProps::ExceedanceProbabilities) {\n          y[i] = 1.0 - y[i];\n        }\n\n        if(pcr::isMV(attrCol[i])) {\n          pcr::setMV(x[i]);\n        }\n        else {\n          x[i] = attrCol[i];\n        }\n      }\n\n      QPen pen;\n\n      if(object.isSelected(guide)) {\n        pen = QPen(object.properties().colour(guide), 2, Qt::SolidLine);\n      }\n      else {\n        pen = QPen(object.properties().colour(guide), 1, Qt::SolidLine);\n      }\n\n      drawCurve(guide, x.get(), y.get(), table.nrRecs(), pen);\n    }\n  }\n\n  if(object.hasSelectedValue(/* guide */)) {\n    // A value is selected. Use the first guide for the properties of\n    // the marker. Mark data values.\n    setXMarker(object.selectedValue(/* guide */));\n    enableMarker(xMarker());\n    disableMarker(yMarker());\n  }\n  else {\n    size_t indexOfCumProbabilities = space.indexOf(\n         dal::CumulativeProbabilities);\n    assert(address.isValid(indexOfCumProbabilities));\n    float quantile = address.coordinate<float>(indexOfCumProbabilities);\n\n    setYMarker(quantile);\n    disableMarker(xMarker());\n    enableMarker(yMarker());\n  }\n}\n\n\n\nvoid CumDistributionFunctionView::createPlot()\n{\n  if(visualisationEngine().isEmpty()) {\n    return;\n  }\n\n  if(!dataObject().dataSpace().hasCumProbabilities()) {\n    return;\n  }\n\n  configureXAxis();\n  configureYAxis();\n  drawPlots();\n  attachMarkers();\n}\n\n\n\nvoid CumDistributionFunctionView::appended(\n         QPointF const& point)\n{\n  moved(point);\n}\n\n\n\nvoid CumDistributionFunctionView::moved(\n         QPointF const& point)\n{\n  if(markerEnabled(xMarker())) {\n    /// for(size_t i = 0; i < visualisationEngine().size(); ++i) {\n    ///   DataGuide const& guide = visualisationEngine().guide(i);\n    ///   // assert(guide.type() == geo::STACK);\n    ///   assert(guide.valueScale() == VS_SCALAR);\n    ///   dataObject().setSelectedValue<REAL4>(guide, static_cast<float>(point.x()), false);\n    /// }\n\n    dataObject().setSelectedValue(static_cast<REAL4>(point.x()), false);\n    /// dataObject().notify();\n  }\n  else if(markerEnabled(yMarker())) {\n    // Snap to closest quantile.\n    dal::DataSpace const& space = dataObject().dataSpace();\n    if(space.hasCumProbabilities()) {\n      size_t index = space.indexOf(dal::CumulativeProbabilities);\n      dal::Dimension const& dimension = space.dimension(index);\n      dataObject().setQuantile(dimension.clamp<float>(static_cast<float>(point.y())), false);\n    }\n  }\n\n  dataObject().notify();\n}\n\n\n\nQSize CumDistributionFunctionView::minimumSizeHint() const\n{\n  // Override QwtPlot one with the default.\n  return QWidget::minimumSizeHint();\n}\n\n\n\nvoid CumDistributionFunctionView::toggleMarker()\n{\n  // Determine which marker is on: the one which iterates over the quantiles\n  // or the one which iterates over the data values.\n  // Then switch from the one marker to the other and adjust relevant settings.\n\n  // The initial position of the new marker is the intersection of the current\n  // marker with the plot of the first data guide.\n\n  assert(!visualisationEngine().isEmpty());\n\n  double x, y;\n\n  assert(markerEnabled(xMarker()) || markerEnabled(yMarker()));\n  assert(!(markerEnabled(xMarker()) && markerEnabled(yMarker())));\n\n  // Take the first guide.\n  DataGuide const& guide = visualisationEngine().guide(0);\n\n  if(markerEnabled(xMarker())) {\n    // xMarker iterates over the y-axis. Attribute values will be shown in\n    // the map.\n    if(!intersectMarker(&x, &y, xMarker(), guide)) {\n      y = 0.5;\n    }\n\n    // Snap to closest quantile.\n    dal::DataSpace const& space = dataObject().dataSpace();\n    assert(space.hasCumProbabilities());\n    size_t index = space.indexOf(dal::CumulativeProbabilities);\n    dal::Dimension const& dimension = space.dimension(index);\n    dataObject().setQuantile(dimension.clamp<float>(y), false);\n\n    dataObject().unsetSelectedValue(false);\n\n    for(size_t i = 0; i < visualisationEngine().size(); ++i) {\n      DataGuide const& guide = visualisationEngine().guide(i);\n      dataObject().popClassifiers(guide, false);\n    }\n  }\n  else if(markerEnabled(yMarker())) {\n    // double min, max;\n\n    // extremes(&min, &max);\n\n    // yMarker iterates over the x-axis. Probabilities will be shown in the\n    // map.\n    if(!intersectMarker(&x, &y, yMarker(), guide)) {\n      // Marker does not intersect the curve of the first guide.\n#if QWT_VERSION >= 0x060100\n      // QwtPlot::axisScaleDiv returns a reference.\n      QwtScaleDiv const& scaleDiv = axisScaleDiv(xMarker());\n#else\n      // QwtPlot::axisScaleDiv returns a pointer.\n      QwtScaleDiv const& scaleDiv = *axisScaleDiv(xMarker());\n#endif\n\n      x = scaleDiv.lowerBound();\n\n      if(scaleDiv.range() > 0.0) {\n        // Use the middle value.\n        x += scaleDiv.range() / 2.0;\n      }\n    }\n\n    dataObject().setSelectedValue(x, false);\n\n    for(size_t i = 0; i < visualisationEngine().size(); ++i) {\n      DataGuide const& guide = visualisationEngine().guide(i);\n      assert(guide.valueScale() == VS_SCALAR);\n\n      com::Classifier classifier(0.0, 1.0);\n      classifier.setNrClasses(100);\n      classifier.installAlgorithm(com::Classifier::LIN);\n      dataObject().pushClassifier(guide, classifier, false);\n    }\n  }\n\n  dataObject().notify();\n}\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF FREE OPERATORS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF FREE FUNCTIONS\n//------------------------------------------------------------------------------\n\n} // namespace ag\n", "meta": {"hexsha": "1d2c07d186cb2640f51e10663d9086bcd9e31b59", "size": 14798, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_CumDistributionFunctionView.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "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": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_CumDistributionFunctionView.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_CumDistributionFunctionView.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.3778966132, "max_line_length": 93, "alphanum_fraction": 0.6216380592, "num_tokens": 3425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19805169301539852}}
{"text": "#ifndef __GYRO_ROCKET6G_HH__\n#define __GYRO_ROCKET6G_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Non-Ideal Gyro Implementation from Rocket6G)\nLIBRARY DEPENDENCY:\n      ((../../src/gyro/gyro_rocket6g.cpp))\n*******************************************************************************/\n\n#include <armadillo>\n#include \"aux.hh\"\n#include \"gyro.hh\"\n\nclass GyroRocket6G : public Gyro\n{\n    TRICK_INTERFACE(GyroRocket6G);\n\npublic:\n    GyroRocket6G();\n\n    virtual ~GyroRocket6G() {}\n    virtual void init(LaunchVehicle *VehicleIn){};\n    virtual void algorithm(LaunchVehicle *VehicleIn);\n\n    std::default_random_engine generator;\n};\n\n#endif  // __GYRO_ROCKET6G__", "meta": {"hexsha": "e6c1798796475028d8d97291210a9bc56090e753", "size": 714, "ext": "hh", "lang": "C++", "max_stars_repo_path": "modules/sensor_dm/gyro/gyro_rocket6g.hh", "max_stars_repo_name": "mlouielu/mazu-sim", "max_stars_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T07:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T07:09:54.000Z", "max_issues_repo_path": "modules/sensor_dm/gyro/gyro_rocket6g.hh", "max_issues_repo_name": "mlouielu/mazu-sim", "max_issues_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "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/sensor_dm/gyro/gyro_rocket6g.hh", "max_forks_repo_name": "mlouielu/mazu-sim", "max_forks_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "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.5, "max_line_length": 80, "alphanum_fraction": 0.5798319328, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.19805169301539852}}
{"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_BITFLOATING_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_BITFLOATING_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing bitfloating capabilities\n\n    Transform a pattern of bits stored in an integer value\n    in a floating point with different formulas according to\n    the integer @ref bitofsign value.\n\n    This function is the converse of @ref bitinteger\n\n    @par Semantic:\n\n    for any parameter @c x of integral type @c T\n\n    @code\n    as_floating_t<T> r = bitfloating(x);\n    @endcode\n\n    @par Note:\n    This is an internal used utility function related to the computation of\n    floating successors or predecessors.\n\n    @see next, prev, successor,  predecessor,  nextafter, bitinteger\n\n  **/\n  as_floating_t<T> bitfloating(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/bitfloating.hpp>\n#include <boost/simd/function/simd/bitfloating.hpp>\n\n#endif\n", "meta": {"hexsha": "0b674e45fefc41e37e800dd7a581bdec4544e2e8", "size": 1383, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/bitfloating.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/bitfloating.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/bitfloating.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": 26.5961538462, "max_line_length": 100, "alphanum_fraction": 0.6326825741, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.1980516930153985}}
{"text": "#include <GAGPL/GAGLIBRARY/LibraryTree.h>\n#include <GAGPL/MATH/combination.h>\n//#include <GAGPL/GLYCAN/MonosaccharideUnitTable.h>\n#include <GAGPL/CHEMISTRY/FunctionalGroupTable.h>\n#include <GAGPL/FRAGMENTATION/FragmentationTable.h>\n//#include <boost/assign/ptr_map_inserter.hpp>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <boost/make_shared.hpp>\n#include <GAGPL/MATH/MassConversion.h>\n\nnamespace gag\n{\n\t\n\tNodeItem::NodeItem(const NodeItem& node)\n\t{\n\t\tsate = node.sate;\n\t\tfg = node.fg;\n\t\tcompo = node.compo;\n\t}\n\tNodeItem& NodeItem::operator=(const NodeItem& node)\n\t{\n\t\tif(this != &node)\n\t\t{\n\t\t\tsate = node.sate;\n\t\t\tfg = boost::make_shared<Fragment>(*(node.fg));\n\t\t\tcompo = node.compo;\n\t\t}\n\t\treturn *this;\n\t}\n\n\tbool NodeItem::appendMassShift(const std::string& loss_type, int num)\n\t{\t\n\t\t// Update the composition information.\n\t\tComposition append_compo;\n\t\tfor(int i = 1; i <= abs(num); i++)\n\t\t{\n\t\t\tappend_compo.add(loss_type);\n\t\t}\n\n\t\t//Composition append_compo(loss_type);\n\t\tif(num > 0) {\n\t\t\tif(append_compo < compo)\n\t\t\t\tcompo.deduct(append_compo);\n\t\t\telse\n\t\t\t\treturn false;\n\t\t} else {\n\t\t\tcompo.add(append_compo);\n\t\t}\n\t\t// Store the mass shift information.\n\t\tsate.insert(std::make_pair(loss_type, num));\n\t\treturn true;\n\t}\n\n\tstd::string NodeItem::getCompositionShift() const\n\t{\n\t\tstd::string shift_string;\n\t\t\n\t\tfor(Satellite::const_iterator iter = sate.begin(); iter != sate.end(); iter++)\n\t\t{\t\n\t\t\t// The inforamtion of so3 and ac is recorded separately.\n\t\t\tif(iter->first == \"O3S\" || iter->first == \"CH2CO\")\n\t\t\t\tcontinue;\n\n\t\t\tif(iter->second == 0) \n\t\t\t\tcontinue;\n\t\t\telse if(iter->second >= 1) {\n\t\t\t\tshift_string.append(\"-\");\n\t\t\t\tif(iter->second == 1)\n\t\t\t\t\tshift_string.append(iter->first);\n\t\t\t\telse {\n\t\t\t\t\tstd::ostringstream ostr;\n\t\t\t\t\tostr << iter->second << iter->first;\n\t\t\t\t\tshift_string.append(ostr.str());\n\t\t\t\t}\n\t\t\t}\telse if(iter->second <= -1) {\n\t\t\t\tshift_string.append(\"+\");\n\t\t\t\tif(iter->second == -1)\n\t\t\t\t\tshift_string.append(iter->first);\n\t\t\t\telse {\n\t\t\t\t\tstd::ostringstream ostr;\n\t\t\t\t\tostr << abs(iter->second) << iter->first;\n\t\t\t\t\tshift_string.append(ostr.str());\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\treturn shift_string;\n\t}\n\n\tvoid NodeItem::printNodeItem(const std::string format, const size_t clv_num) const\n\t{\n\t\t// The function is used to control cleavage numbers.\n\t\tif(this->getCleavageNum() > clv_num)\n\t\t\treturn;\n\t\t\n\t\tif(format == \"regular\") {\n\t\t\tstd::cout << \"Cleavage type: \" << this->getCleavageType() << std::endl;;\n\t\t\tstd::cout << \"Shift: \" << this->getCompositionShift() << std::endl;\n\t\t\tstd::cout << \"Composition: \" << this->getCompositionString() << std::endl;\n\t\t\tstd::cout << \"Ac: \" << this->getModificationNum(\"Ac\") << std::endl;\n\t\t\tstd::cout << \"SO3: \" << this->getModificationNum(\"SO3\") << std::endl;\n\t\t\tstd::cout << \"Mass: \" << this->getMass() << std::endl;\n\t\t} else if(format == \"compact\") {\n\t\t\tstd::cout << this->getCleavageType() << \"\\t\" << this->getCompositionShift() << \"\\t\" << this->getCompositionString() << \"\\t\" << this->getModificationNum(\"Ac\") << \"\\t\" << this->getModificationNum(\"SO3\") << \"\\t\" << this->getMass() << std::endl;\n\t\t}\n\n\t}\n\n\tint NodeItem::getModificationNum( const std::string& compo_string ) const\n\t{\n\t\tstd::string internal_string;\n\t\tif(compo_string == \"Ac\")\n\t\t\tinternal_string = \"C2H2O\";\n\t\telse if(compo_string == \"SO3\")\n\t\t\tinternal_string = \"O3S\";\n\t\tSatellite::const_iterator iter = sate.find(internal_string);\n\t\treturn iter != sate.end() ? abs(iter->second) : 0;\n\t}\n\n\tvoid FragmentTree::build()\n\t{\n\t\tthis->addCleavage();\n\t}\n\n\tvoid FragmentTree::addCleavage()\n\t{\n\t\t// Get the number of mono units.\n\t\tsize_t mono_num = glycan_seq->getBranchByID(0).getUnitNum();\n\n\t\tfor(int re_clv = RE_INTACT; re_clv <RE_N; re_clv++)\n\t\t{\n\t\t\t\n\t\t\tif(re_clv == RE_INTACT) {\n\t\t\t\t//FragmentPtr fg(new Fragment(glycan_seq));\n\t\t\t\t//std::cout << \"INTACT\" << std::endl;\n\t\t\t\tCleavageCollection cc;\n\t\t\t\tthis->addRestCleavage(cc, mono_num);\n\t\t\t} else {\n\t\t\t\tfor(size_t i = 0; i<mono_num; i++) {\n\t\t\t\t\tif(re_clv == A) {\n\t\t\t\t\t\tfor(size_t x = 0; x<=3; x++)\n\t\t\t\t\t\t\tfor(size_t y = x+2; y <= 5; y++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif((y - x == 3) || (x == 0 && (y == 4 || y == 5)) || (x == 1 && y == 3))\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t//std::cout << \"A\" << i << \":\" << x << \"-\" << y << std::endl;\n\t\t\t\t\t\t\t\t//FragmentPtr fg(new Fragment(glycan_seq));\n\t\t\t\t\t\t\t\t//fg->setFragmentation(\"A\", i, \"\", x, y);\n\t\t\t\t\t\t\t\tCleavageCollection cc;\n\t\t\t\t\t\t\t\tcc.insert(std::make_pair(\"A\", FragmentPosition(0, i, x, y)));\n\t\t\t\t\t\t\t\tthis->addRestCleavage(cc, i);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//FragmentPtr fg(new Fragment(glycan_seq));\n\n            // B and C type of cleavage at the RE is a problem.\n            // Ignore it at this moment.\n            if(i == mono_num-1) continue;\n\n\t\t\t\t\t\tstd::string type;\n\t\t\t\t\t\tif(re_clv == B) \n\t\t\t\t\t\t\ttype = \"B\";\n\t\t\t\t\t\telse if(re_clv == C) \n\t\t\t\t\t\t\ttype = \"C\";\n\t\t\t\t\t\telse \n\t\t\t\t\t\t\tthrow std::runtime_error(\"Uncharacterized cleavage type\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tCleavageCollection cc;\n\t\t\t\t\t\tcc.insert(std::make_pair(type, FragmentPosition(0, i, 0, 0)));\n\t\t\t\t\t\t//std::cout << type << i << std::endl;\n\t\t\t\t\t\t//fg->setFragmentation(type, i, \"\", 0, 0);\n\t\t\t\t\t\tthis->addRestCleavage(cc, i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\n\t\t}\n\t}\n\n\tvoid FragmentTree::addRestCleavage(const CleavageCollection& cc, const size_t& cur )\n\t{\n\t\t// Get the number of mono units.\n\t\tsize_t mono_num = glycan_seq->getBranchByID(0).getUnitNum();\n\t\tMassLossWindow mlw = frag_table.getMassLoss();\n\t\tfor(int nre_clv = NRE_INTACT; nre_clv < NRE_N; nre_clv++)\n\t\t{\n\t\t\t// Intact sequence.\n\t\t\tif(nre_clv == NRE_INTACT) {\n\t\t\t\t// Do nothing.\n\t\t\t\t//std::cout << \"INTACT\" << std::endl;\n\t\t\t\tthis->processFragment(cc, mlw);\n\t\t\t} else {\n\t\t\t\tfor(size_t i = 0; i < cur; i++)\n\t\t\t\t{\n\t\t\t\t\tif(nre_clv == X) {\n\t\t\t\t\t\tfor(size_t x=0; x<=3; x++)\n\t\t\t\t\t\t\tfor(size_t y = x+2; y <=5; y++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif((y - x == 3) || (x == 0 && (y == 4 || y == 5)) || (x == 1 && y == 3))\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t//std::cout << \"X\" << i << \":\" << x << \"-\" << y << std::endl;\n\t\t\t\t\t\t\t\t//FragmentPtr fg1(new Fragment(*fg));\n\t\t\t\t\t\t\t\t//fg1->setFragmentation(\"X\", i, \"\", x,y);\n\t\t\t\t\t\t\t\tCleavageCollection cc1(cc);\n\t\t\t\t\t\t\t\tcc1.insert(std::make_pair(\"X\", FragmentPosition(0, i, x, y)));\n\t\t\t\t\t\t\t\tthis->processFragment(cc1, mlw);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//FragmentPtr fg1(new Fragment(*fg));\n\n\t\t\t\t\t\tstd::string type;\n\t\t\t\t\t\tif(nre_clv == Y) \n\t\t\t\t\t\t\ttype = \"Y\";\n\t\t\t\t\t\telse if(nre_clv == Z) \n\t\t\t\t\t\t\ttype = \"Z\";\n\t\t\t\t\t\telse \n\t\t\t\t\t\t\tthrow std::runtime_error(\"Uncharacterized cleavage type\");\n\t\t\t\t\t\t\n\t\t\t\t\t\t//std::cout << type << i << std::endl;\n\t\t\t\t\t\t//fg1->setFragmentation(type, i, \"\", 0, 0);\n\t\t\t\t\t\tCleavageCollection cc1(cc);\n\t\t\t\t\t\tcc1.insert(std::make_pair(type, FragmentPosition(0, i, 0, 0)));\n\t\t\t\t\t\tthis->processFragment(cc1, mlw);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid FragmentTree::processFragment(const CleavageCollection& cc, MassLossWindow mlw)\n\t{\t\n\t\tFragmentPtr fg(new Fragment(glycan_seq));\n\t\tfg->updateCleavage(cc);\n\n\t\t//std::string final_type = fg->getCleavageType();\n\t\t\n\t\t// Modify the MassLossWindow based on the possibility of modification sites.\n\t\tstd::set<std::string> mod_types = glycan_seq->getModificationTypes();\n\n\t\tfor(std::set<std::string>::iterator iter = mod_types.begin(); iter != mod_types.end(); iter++)\n\t\t{\n\t\t\tint num = (int)fg->getModificationSiteNum(*iter, 1);\n\t\t\tComposition temp_compo;\n\t\t\tif(*iter == \"SO3\") {\n\t\t\t\ttemp_compo.add(\"SO3\");\n\t\t\t\tint upper_num = glycan_seq->getModificationConstraint(\"SO3\");\n\t\t\t\tif(num > upper_num)\n\t\t\t\t\tnum = upper_num;\n\t\t\t} else if(*iter == \"Ac\") {\n\t\t\t\ttemp_compo.add(\"CH2CO\");\n\t\t\t\tint upper_num = glycan_seq->getModificationConstraint(\"Ac\");\n\t\t\t\tif(num > upper_num)\n\t\t\t\t\tnum = upper_num;\n\t\t\t}\n\t\t\tif(num != 0) mlw.push_back(MassLoss(temp_compo, 0, -1 * num));\n\n\t\t}\n\t\t\n\t\tthis->processFragment(fg, mlw, 0, Satellite());\n\t}\n\n\tvoid FragmentTree::processFragment( FragmentPtr fg, MassLossWindow& mlw, size_t degree, Satellite sate )\n\t{\n\t\tif(degree == mlw.size()) {  // Out of boundary.\n\t\t\tNodeItem node(fg);\n\n\t\t\tint max_num = (int)fg->getModificationSiteNum(\"SO3\", 1);\n\t\t\tSatellite::iterator ac_iter = sate.find(\"CH2CO\");\n\t\t\tint ac_num = ac_iter == sate.end() ? 0 : -1 * ac_iter->second;\n\t\t\tSatellite::iterator s_iter = sate.find(\"SO3\");\n\t\t\tint s_num = s_iter == sate.end() ? 0 : -1 * s_iter->second;\n\t\t\tif(s_num + ac_num > max_num)\n\t\t\t\ts_iter->second = max_num - ac_num;\n\n\t\t\t// Update the composition.\n\t\t\tfor(Satellite::iterator iter = sate.begin(); iter != sate.end(); iter++) {\n\t\t\t\t//std::cout << iter->first << \" \" << iter->second << \" \";\n\t\t\t\tif(!node.appendMassShift(iter->first, iter->second)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//std::cout << std::endl;\n\n\t\t\tnode_pool.insert(node);\n\t\t\treturn;\n\t\t}\n\n\t\tMassLoss& ml = mlw.at(degree);\n\n\t\tfor(int i = ml.lower; i<=ml.upper; i++)\n\t\t{\n\t\t\t// Copy the composition.\n\t\t\tSatellite temp_sate(sate);\n\n\t\t\tif(i != 0) {\n\t\t\t\ttemp_sate.insert(std::make_pair(ml.loss_compo.getCompositionString(), i));\n\t\t\t\tthis->processFragment(fg, mlw, degree+1, temp_sate);\n\t\t\t} else {\n\t\t\t\tthis->processFragment(fg, mlw, degree+1, temp_sate);\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid FragmentTree::getNodeItemsByMass(MonoPeakPtr pk, std::multimap<MonoPeakPtr, NodeItem>& node_map)\n\t{\n\t\tTreeByMass& tree_mass_index = node_pool.get<theo_mass>();\n\t\tdouble matching_error = param.getParameter<double>(\"matching_error\").first;\n\n\t\tdouble mass = msmath::calculateMass(pk->mz, -1 * pk->z);\n\t\tTreeByMass::iterator mass_iter = tree_mass_index.lower_bound(mass);\n    TreeByMass::iterator up_bound = tree_mass_index.upper_bound(mass);\n\t\t// Shift the iterator upstream and downstream.\n\t\t\n\t\tif(mass_iter == tree_mass_index.end() && up_bound == tree_mass_index.end()) // Not found.\n\t\t\treturn;\n\n\t\t//std::cout << \"Current mass: \" << mass << std::endl;\n\t\tTreeByMass::iterator up_iter = mass_iter;\n\n\t\t// Upstream.\n\t\twhile(1)\n\t\t{\t\n\t\t\t//std::cout << \"Try to match \" << up_iter->getMass() << std::endl;\n\t\t\tif((up_iter->getMass() - mass)/mass >= 1e-6 * matching_error)\n\t\t\t\tbreak;\n\n\t\t\tif(abs(up_iter->getMass()-mass)/mass < 1e-6 * matching_error){\n\t\t\t\t//std::cout << \"A hit for \" << mass << std::endl;\n\t\t\t\tnode_map.insert(std::make_pair(pk, *up_iter));\t\n\t\t\t\t//if(status == false) status = true;\n\t\t\t} \n\t\t\tup_iter++;\n\t\t\tif(up_iter == tree_mass_index.end())\n\t\t\t\tbreak;\n\t\t}\n\t\tTreeByMass::iterator down_iter = mass_iter;\n\t\twhile(1)\n\t\t{\n\t\t\t//std::cout << \"Try to match \" << down_iter->getMass() << std::endl;\n\t\t\tif((mass - down_iter->getMass())/down_iter->getMass() >= 1e-6 * matching_error) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(abs(down_iter->getMass()-mass)/down_iter->getMass() < 1e-6 * matching_error){\n\t\t\t\t//std::cout << \"A hit for \" << mass << std::endl;\n\t\t\t\tnode_map.insert(std::make_pair(pk, *down_iter));\n\t\t\t\t//if(status == false) status = true;\n\t\t\t} \n\t\t\tif(down_iter == tree_mass_index.begin())\n\t\t\t\tbreak;\n\t\t\tdown_iter--;\n\t\t}\n\n\t\treturn;\n\t\t\n\t}\n\n\tvoid FragmentTree::printLibrary()\n\t{\n\t\tTreeByMass& tree_mass_index = node_pool.get<theo_mass>();\n\t\tfor(TreeByMass::const_iterator iter = tree_mass_index.begin(); iter!= tree_mass_index.end(); iter++)\n\t\t{\n\t\t\t(*iter).printNodeItem(\"compact\");\n\t\t}\n\t}\n\n\tstd::multimap<MonoPeakPtr, NodeItem> FragmentTree::searchLibrary( const std::set<MonoPeakPtr>& pk_list )\n\t{\n\t\tstd::multimap<MonoPeakPtr, NodeItem> node_list;\n\t\t// Slow version.\n\t\tfor(std::set<MonoPeakPtr>::const_iterator const_iter = pk_list.begin(); const_iter != pk_list.end(); const_iter++)\n\t\t{\n      double mz = (*const_iter)->mz;\n\t\t\tthis->getNodeItemsByMass(*const_iter, node_list);\n\t\t}\n\t\treturn node_list;\n\t}\n\n\tvoid FragmentTree::exportLibrary( const std::string& filename )\n\t{\n\t\tstd::ofstream outfile(filename.c_str());\n\n\t\tif(outfile.is_open()) {\n\t\t\tTreeByMass& tree_mass_index = node_pool.get<theo_mass>();\n\t\t\toutfile.precision(5);\n\t\t\tfor(TreeByMass::const_iterator iter = tree_mass_index.begin(); iter!= tree_mass_index.end(); iter++)\n\t\t\t{\n\t\t\t\toutfile << std::fixed << iter->getMass() << \"\\t\" << iter->getCleavageType() << \"\\t\" << iter->getCompositionShift() << \"\\t\" << iter->getCompositionString() << \"\\t\" << \"\\n\";\n\t\t\t}\n\t\t\toutfile.close();\n\t\t} else {\n\t\t\tstd::cout << \"Unable to open file!\\n\" << std::endl;\n\t\t}\n\t}\n\n\tvoid loadMonoPeakList( const std::string& filename, std::set<MonoPeakPtr>& peak_list)\n\t{\n\t\tstd::cout << \"Load peak list...\" << std::endl;\n\t\tstd::ifstream infile(filename.c_str());\n\n\t\tstd::string line;\n\n\t\t//RichList spec;\n\t\tif(infile.is_open())\n\t\t{\n\t\t\t// Deal with title.\n\t\t\tstd::getline(infile, line);\n/*\t\t\tstd::istringstream title;\n\t\t\ttitle.str(line);\n\t\t\tdouble t1, t2;\n\t\t\ttitle >> t1 >> t2;\t\t*/\t\n\n\t\t\twhile(std::getline(infile, line))\n\t\t\t{\n\t\t\t\tstd::istringstream is;\n\t\t\t\tis.str(line);\n\t\t\t\t// mz, intensity and charge state.\n\t\t\t\tdouble k1; double k2; int k3; \n\t\t\t\tis >> k1 >> k2 >> k3;\n\t\t\t\tgag::MonoPeakPtr pk = boost::make_shared<MonoPeak>(k1, k2, k3);\n\t\t\t\t//double mass = msmath::calculateMass(k1, -1 * k2);\n\t\t\t\t//std::cout.precision(5);\n\t\t\t\t//std::cout << std::fixed << mass << std::endl;\n\t\t\t\tpeak_list.insert(pk);\n\t\t\t}\n\t\t}\n\t\tinfile.close();\n\t\tinfile.clear();\n\n\t}\n\n}", "meta": {"hexsha": "5f9d4745b1da98b7282473f1242de5c1ada0c66a", "size": 12819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GAG/src/GAGPL/GAGLIBRARY/LibraryTree.cpp", "max_stars_repo_name": "hh1985/multi_hs_seq", "max_stars_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-03T14:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-15T13:38:39.000Z", "max_issues_repo_path": "GAG/src/GAGPL/GAGLIBRARY/LibraryTree.cpp", "max_issues_repo_name": "hh1985/multi_hs_seq", "max_issues_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "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": "GAG/src/GAGPL/GAGLIBRARY/LibraryTree.cpp", "max_forks_repo_name": "hh1985/multi_hs_seq", "max_forks_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "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.4013761468, "max_line_length": 244, "alphanum_fraction": 0.6107340666, "num_tokens": 3980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1980516930153985}}
{"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#include \"graph_filtering.hh\"\n#include \"graph_python_interface.hh\"\n\n#include <boost/python.hpp>\n#include <boost/graph/astar_search.hpp>\n\n#include \"graph.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_util.hh\"\n\n#include \"graph_astar.hh\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\ntemplate <class T>\npython::object operator |(const python::object& a, const T& b)\n{\n    return a / b;\n}\n\nstruct do_astar_search\n{\n    template <class Graph, class DistanceMap>\n    void operator()(const Graph& g, size_t s, DistanceMap dist,\n                    boost::any pred_map, boost::any aweight,\n                    AStarVisitorWrapper vis, pair<AStarCmp, AStarCmb> cmp,\n                    pair<python::object, python::object> range,\n                    pair<python::object, python::object> h) const\n    {\n        typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n        typedef typename property_traits<DistanceMap>::value_type dtype_t;\n        dtype_t z = python::extract<dtype_t>(range.first);\n        dtype_t i = python::extract<dtype_t>(range.second);\n        typedef typename property_map_type::\n            apply<int32_t, typeof(get(vertex_index, g))>::type pred_t;\n        pred_t pred = any_cast<pred_t>(pred_map);\n        checked_vector_property_map<default_color_type,\n                                    typeof(get(vertex_index, g))>\n            color(get(vertex_index, g));\n        checked_vector_property_map<dtype_t,\n                                    typeof(get(vertex_index, g))>\n            cost(get(vertex_index, g));\n        DynamicPropertyMapWrap<dtype_t, edge_t> weight(aweight,\n                                                       edge_properties());\n        astar_search(g, vertex(s, g), AStarH<dtype_t>(h.first, h.second),\n                     vis, pred, cost, dist, weight, get(vertex_index, g), color,\n                     cmp.first, cmp.second, i, z);\n   }\n};\n\n\nvoid a_star_search(GraphInterface& g, python::object gi, size_t source,\n                   boost::any dist_map, boost::any pred_map, boost::any weight,\n                   python::object vis, python::object cmp, python::object cmb,\n                   python::object zero, python::object inf, python::object h)\n{\n    run_action<graph_tool::detail::all_graph_views,mpl::true_>()\n        (g, std::bind(do_astar_search(),  placeholders::_1, source,\n                      placeholders::_2, pred_map, weight,\n                      AStarVisitorWrapper(gi, vis), make_pair(AStarCmp(cmp),\n                                                              AStarCmb(cmb)),\n                      make_pair(zero, inf), make_pair(gi, h)),\n         writable_vertex_properties())(dist_map);\n}\n\nvoid export_astar()\n{\n    using namespace boost::python;\n    def(\"astar_search\", &a_star_search);\n}\n", "meta": {"hexsha": "de47042cefc41188f700317a0195f04df38ac6f6", "size": 3587, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/search/graph_astar.cc", "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/search/graph_astar.cc", "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/search/graph_astar.cc", "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": 39.8555555556, "max_line_length": 80, "alphanum_fraction": 0.634513521, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19805168734344344}}
{"text": "/* Copyright (c) 2019, NVIDIA CORPORATION. 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 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#pragma once\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"mapping/mapping.hpp\"\n#include \"model/engine.hpp\"\n#include \"workload/problem-shape.hpp\"\n\nusing namespace boost::multiprecision;\n\nnamespace mapspace\n{\n\n//--------------------------------------------//\n//             Mapspace Dimensions            //\n//--------------------------------------------//\n\nenum class Dimension\n{\n  IndexFactorization,  // Factorization of loop bounds across storage levels\n  LoopPermutation,     // Permutation of loop nests in each storage level\n  Spatial,             // Position of the transition point between horizontal and vertical\n                       //   spatial tilings \n  DatatypeBypass,      // Optionally bypass a storage level for a datatype\n  Num\n};\n\nstd::ostream& operator << (std::ostream& out, Dimension d);\n\n//--------------------------------------------//\n//                MapSpace ID                 //\n//--------------------------------------------//\n\ntypedef CartesianCounter<int(Dimension::Num)> ID;\n\n//--------------------------------------------//\n//                   Status                   //\n//--------------------------------------------//\n\nstruct Status\n{\n  bool success;\n  std::string fail_reason;\n};\n\n//--------------------------------------------//\n//                  MapSpace                  //\n//--------------------------------------------//\n\nclass MapSpace\n{\n protected:\n  model::Engine::Specs arch_specs_;\n  const problem::Workload& workload_;\n  std::array<uint128_t, int(Dimension::Num)> size_;\n\n public:\n  MapSpace(model::Engine::Specs arch_specs,\n           const problem::Workload& workload) :\n      arch_specs_(arch_specs),\n      workload_(workload),\n      size_({})\n  {}\n\n  virtual ~MapSpace() {}\n\n  virtual std::vector<MapSpace*> Split(std::uint64_t num_splits) = 0;\n\n  virtual void InitPruned(uint128_t local_index_factorization_id) = 0;\n\n  virtual std::vector<Status> ConstructMapping(ID mapping_id, Mapping* mapping, bool break_on_failure = true) = 0;\n\n  std::vector<Status> ConstructMapping(const uint128_t mapping_id, Mapping* mapping, bool break_on_failure = true)\n  {\n    ID cmapping_id(size_);\n    cmapping_id.Set(mapping_id);\n    return ConstructMapping(cmapping_id, mapping, break_on_failure); \n  }\n\n  uint128_t Size(Dimension dim)\n  {\n    return size_[int(dim)];\n  }\n  \n  uint128_t Size()\n  {\n    uint128_t size = 1;\n    for (int i = 0; i < int(Dimension::Num); i++)\n    {\n      size *= size_[i];\n    }\n    return size;\n  }\n\n  std::array<uint128_t, int(Dimension::Num)> AllSizes()\n  {\n    return size_;\n  }\n};\n\n} // namespace mapspace\n", "meta": {"hexsha": "100bebc5a9157f678155b7106971e7a5d41237cc", "size": 4158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mapspaces/mapspace-base.hpp", "max_stars_repo_name": "tanvisharma/timeloop", "max_stars_repo_head_hexsha": "bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-28T09:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T19:33:18.000Z", "max_issues_repo_path": "src/mapspaces/mapspace-base.hpp", "max_issues_repo_name": "tanvisharma/timeloop", "max_issues_repo_head_hexsha": "bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2", "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/mapspaces/mapspace-base.hpp", "max_forks_repo_name": "tanvisharma/timeloop", "max_forks_repo_head_hexsha": "bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-22T19:33:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T19:33:19.000Z", "avg_line_length": 32.2325581395, "max_line_length": 114, "alphanum_fraction": 0.6296296296, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.38121955219593834, "lm_q1q2_score": 0.1980516857108188}}
{"text": "#include <string.h>\n#include <iostream>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\nusing namespace std;\nusing namespace boost::property_tree;\n\n#include <map>\n#include <string>\n#include <iostream>\n#include <string.h>\n\n#include <fc/crypto/elliptic.hpp>\n#include <fc/crypto/ripemd160.hpp>\n#include <fc/crypto/base58.hpp>\n#include <fc/crypto/sha512.hpp>\n#include <fc/io/json.hpp>\n#include <fc/reflect/reflect.hpp>\n#include <fc/io/raw.hpp>\n#include <fc/variant_object.hpp>\n#include <fc/exception/exception.hpp>\n#include <graphene/chain/pts_address.hpp>\n#include <graphene/chain/protocol/address.hpp>\n#include <fc/variant.hpp>\n#include \"wallet_lib.hpp\"\n\nusing namespace std;\n\nstruct binary_key\n{\n  binary_key(){}\n  uint32_t check = 0;\n  fc::ecc::public_key_data data;\n};\n\nFC_REFLECT( binary_key, (data)(check) )\n\nstd::string key_to_wif(const fc::sha256& secret )\n{\n  const size_t size_of_data_to_hash = sizeof(secret) + 1;\n  const size_t size_of_hash_bytes = 4;\n  char data[size_of_data_to_hash + size_of_hash_bytes];\n  data[0] = (char)0x80;\n  memcpy(&data[1], (char*)&secret, sizeof(secret));\n  fc::sha256 digest = fc::sha256::hash(data, size_of_data_to_hash);\n  digest = fc::sha256::hash(digest);\n  memcpy(data + size_of_data_to_hash, (char*)&digest, size_of_hash_bytes);\n  return fc::to_base58(data, sizeof(data));\n}\n\nstd::string key_to_wif(const fc::ecc::private_key& key)\n{\n    return key_to_wif( key.get_secret() );\n}\n\nfc::optional<fc::ecc::private_key> wif_to_key( const std::string& wif_key )\n{\n    std::vector<char> wif_bytes;\n    try\n    {\n        wif_bytes = fc::from_base58(wif_key);\n    }\n    catch (const fc::parse_error_exception&)\n    {\n        return fc::optional<fc::ecc::private_key>();\n    }\n    if (wif_bytes.size() < 5) {\n        return fc::optional<fc::ecc::private_key>();\n    }\n    std::vector<char> key_bytes(wif_bytes.begin() + 1, wif_bytes.end() - 4);\n\n    fc::variant var = fc::variant( key_bytes);\n    fc::ecc::private_key key;\n    from_variant(var, key);\n\n    fc::sha256 check = fc::sha256::hash(wif_bytes.data(), wif_bytes.size() - 4);\n    fc::sha256 check2 = fc::sha256::hash(check);\n//\n    if( memcmp( (char*)&check, wif_bytes.data() + wif_bytes.size() - 4, 4 ) == 0 ||\n       memcmp( (char*)&check2, wif_bytes.data() + wif_bytes.size() - 4, 4 ) == 0 ) {\n        return key;\n    }\n\n    return fc::optional<fc::ecc::private_key>();\n}\n\n/*\n * global parameters to hold the keys\n */\n\n//cybex_priv_key_type active_priv_key, owner_priv_key, memo_priv_key;\n\nstatic map<string, fc::ecc::private_key> stored_keys;\nstatic map<string, vector<string>> stored_addresses;\n\nstatic string default_public_key = \"\";\nstatic string default_private_key = \"\";\n\n\nvoid set_default_public_key(string pub_key_base58_str)\n{\n  default_public_key = pub_key_base58_str;\n}\n\nvoid set_default_private_key(string pri_key_base58_str)\n{\n    default_private_key = pri_key_base58_str;\n}\n\nvoid clear_user_key()\n{\n    stored_keys.clear();\n    stored_addresses.clear();\n}\n\nvoid add_user_key(string public_key, fc::ecc::private_key key)\n{\n    stored_keys.insert(map<string, fc::ecc::private_key>::value_type(public_key, key));\n}\n\nvoid add_address(string public_key, vector<string> addresses)\n{\n    stored_addresses.insert(map<string, vector<string>>::value_type(public_key, addresses));\n}\n\nfc::ecc::private_key get_private_key(string public_key)\n{\n    if(default_private_key.size())\n    {\n        fc::ecc::private_key pk = *wif_to_key(default_private_key);\n        return pk;\n    }\n    map<string, fc::ecc::private_key>::iterator iter;\n\n    if(public_key == \"\")\n        iter = stored_keys.find(default_public_key);\n    else\n        iter = stored_keys.find(public_key);\n    if(iter != stored_keys.end())\n        return iter->second;\n\n    FC_THROW_EXCEPTION(fc::exception, \"private key not found\");\n}\n\nstring get_private_key_with_message(string message)\n{\n    fc::ecc::private_key priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(message)));\n    return key_to_wif(priv_key);\n}\n\nfc::ecc::private_key get_private_key_with_random(string public_key)\n{\n    fc::ecc::private_key priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(public_key)));\n    return priv_key;\n}\n\nstring get_pubkey_from_address(string address)\n{\n    if(address == \"\")\n        FC_THROW_EXCEPTION(fc::exception, \"private key not found\");\n    else\n        for (auto &i : stored_addresses) {\n            if ( std::find(i.second.begin(), i.second.end(), address) != i.second.end() ) {\n                return string(i.first.c_str());\n            }\n        }\n\n    FC_THROW_EXCEPTION(fc::exception, \"private key not found\");\n}\n\n\nfc::mutable_variant_object get_dev_key(string type, string secret)\n{\n  fc::ecc::private_key priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(secret)));\n  string private_key = key_to_wif( priv_key );\n  fc::ecc::public_key pub_key = priv_key.get_public_key();\n  struct binary_key bkey;\n  bkey.data = pub_key.serialize();\n  bkey.check = fc::ripemd160::hash( bkey.data.data, bkey.data.size() )._hash[0];\n  \n  auto data = fc::raw::pack( bkey );\n  string public_key = \"CYB\" + fc::to_base58( data.data(), data.size() );\n  \n  auto dat = pub_key.serialize();\n  fc::ripemd160 addr = fc::ripemd160::hash( fc::sha512::hash( dat.data, sizeof( dat ) ) );\n  fc::array<char,24> bin_addr;\n  \n  memcpy( (char*)&bin_addr, (char*)&addr, sizeof( addr ) );\n  auto checksum = fc::ripemd160::hash( (char*)&addr, sizeof( addr ) );\n  memcpy( ((char*)&bin_addr)+20, (char*)&checksum._hash[0], 4 );\n  string address = \"CYB\" + fc::to_base58( bin_addr.data, sizeof( bin_addr ) );\n  \n  graphene::chain::pts_address compress_pts_addr(pub_key, true, 56);\n  graphene::chain::pts_address uncompress_pts_addr(pub_key, false, 56);\n  \n  fc::mutable_variant_object mvo;\n  mvo( \"private_key\", private_key)\n  ( \"public_key\", public_key)\n  ( \"address\", address)\n  ( \"compressed\", string(graphene::chain::address(compress_pts_addr)))\n  ( \"uncompressed\", string(graphene::chain::address(uncompress_pts_addr)))\n  ;\n\n    vector<string> addresses;\n    addresses.push_back(address);\n    addresses.push_back(string(graphene::chain::address(compress_pts_addr)));\n    addresses.push_back(string(graphene::chain::address(uncompress_pts_addr)));\n\n  add_user_key(public_key, priv_key);\n    add_address(public_key, addresses);\n  if(type == \"active\")\n    default_public_key = public_key;\n\n  return mvo;\n  //return fc::json::to_string(mvo);\n}\n\nstring get_user_key(string user_name, string password)\n{\n  clear_user_key();\n  fc::mutable_variant_object mvo;\n  mvo(\"active-key\", get_dev_key(\"active\", user_name + \"active\" + password))\n     (\"owner-key\", get_dev_key(\"owner\", user_name + \"owner\" + password))\n     (\"memo-key\", get_dev_key(\"memo\", user_name + \"memo\" + password))\n  ;\n  return fc::json::to_string(mvo);\n}\n\nstring get_active_user_key(string pubkey)\n{\n    fc::mutable_variant_object mvo;\n    graphene::chain::public_key_type to_pub_key = graphene::chain::public_key_type(pubkey);\n\n\n    fc::ecc::public_key pub_key = to_pub_key;\n\n    auto dat = pub_key.serialize();\n    fc::ripemd160 addr = fc::ripemd160::hash( fc::sha512::hash( dat.data, sizeof( dat ) ) );\n    fc::array<char,24> bin_addr;\n\n    memcpy( (char*)&bin_addr, (char*)&addr, sizeof( addr ) );\n    auto checksum = fc::ripemd160::hash( (char*)&addr, sizeof( addr ) );\n    memcpy( ((char*)&bin_addr)+20, (char*)&checksum._hash[0], 4 );\n    string address = \"CYB\" + fc::to_base58( bin_addr.data, sizeof( bin_addr ) );\n\n    graphene::chain::pts_address compress_pts_addr(pub_key, true, 56);\n    graphene::chain::pts_address uncompress_pts_addr(pub_key, false, 56);\n\n    fc::mutable_variant_object activemvo;\n    activemvo( \"private_key\", \"\")\n    ( \"public_key\", pubkey)\n    ( \"address\", address)\n    ( \"compressed\", string(graphene::chain::address(compress_pts_addr)))\n    ( \"uncompressed\", string(graphene::chain::address(uncompress_pts_addr)));\n\n    mvo(\"active-key\", activemvo)\n    (\"owner-key\", activemvo);\n    return fc::json::to_string(mvo);\n}\n\nconst char *get_user_key(const char *user_name, const char *password) {\n    string asss = get_user_key(string(user_name), string(password));\n    const char *cstr = asss.c_str();\n\n    return cstr;\n}\n", "meta": {"hexsha": "f469e9e4a9a1aee0830c30de401df156c27472d9", "size": 8228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cybex_ios_core_cpp/source/get_dev_key.cpp", "max_stars_repo_name": "CybexDex/cybex-ios-core-cpp", "max_stars_repo_head_hexsha": "6d6e446180dba9f302bd5296942a2b17289ed949", "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": "cybex_ios_core_cpp/source/get_dev_key.cpp", "max_issues_repo_name": "CybexDex/cybex-ios-core-cpp", "max_issues_repo_head_hexsha": "6d6e446180dba9f302bd5296942a2b17289ed949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cybex_ios_core_cpp/source/get_dev_key.cpp", "max_forks_repo_name": "CybexDex/cybex-ios-core-cpp", "max_forks_repo_head_hexsha": "6d6e446180dba9f302bd5296942a2b17289ed949", "max_forks_repo_licenses": ["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.7014925373, "max_line_length": 107, "alphanum_fraction": 0.6893534273, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.19801615239146855}}
{"text": "#include <boost/foreach.hpp>\n\n#include \"joint_tracker/MultiJointTracker.h\"\n\n#include <geometry_msgs/Vector3.h>\n\n#include <cmath>\n\n#include <wrappers/matrix/matrix_wrapper.h>\n\n#include \"omip_msgs/RigidBodyTwistWithCovMsg.h\"\n#include \"omip_common/OMIPUtils.h\"\n\nusing namespace omip;\nusing namespace MatrixWrapper;\nusing namespace BFL;\n\nMultiJointTracker::MultiJointTracker(double loop_period_ns, ks_analysis_t ks_analysis_type, double dj_ne) :\n    RecursiveEstimatorFilterInterface(loop_period_ns),\n    _ks_analysis_type(ks_analysis_type),\n    _disconnected_j_ne(dj_ne),\n    _likelihood_sample_num(0),\n    _sigma_delta_meas_uncertainty_linear(0),\n    _sigma_delta_meas_uncertainty_angular(0)\n{\n    this->_filter_name = \"KSFilter\";\n}\n\nMultiJointTracker::~MultiJointTracker()\n{\n\n}\n\nvoid MultiJointTracker::predictState(double time_interval_ns)\n{\n    BOOST_FOREACH(joint_combined_filters_map::value_type joint_combined_filter_it, this->_joint_combined_filters)\n    {\n        joint_combined_filter_it.second->predictState(time_interval_ns);\n    }\n}\n\nvoid MultiJointTracker::predictMeasurement()\n{\n    // We query the predictions from each joint\n    // In order to propagate a prediction to the lower level, it must fulfill:\n    //  1) It is not a prediction from a disconnected joint (we could remove this condition, it would be ignored at the lower level)\n    //  2) There should be only one prediction for a rigid body. The prediction with highest likelihood gets propagated\n    this->_predicted_measurement.rb_poses_and_vels.clear();\n    omip_msgs::RigidBodyPoseAndVelMsg pose_and_vel_one_rb;\n    RB_id_t rbid_predicted;\n\n    std::map<int, double> rbid_predicted_and_likelihood;\n    std::map<int, omip_msgs::RigidBodyPoseAndVelMsg> rbid_predicted_and_predictions;\n    BOOST_FOREACH(joint_combined_filters_map::value_type joint_combined_filter_it, this->_joint_combined_filters)\n    {\n        joint_combined_filter_it.second->predictMeasurement();\n        rbid_predicted = joint_combined_filter_it.first.second;\n        JointFilterPtr most_probable_joint_hypothesis = joint_combined_filter_it.second->getMostProbableJointFilter();\n\n        // The prediction is useful only if the bodies are not disconnected\n        // Only one prediction per RB\n        if(most_probable_joint_hypothesis->getJointFilterType() != DISCONNECTED_JOINT)\n        {\n            std::map<int, double>::iterator previous_prediction_it = rbid_predicted_and_likelihood.find(rbid_predicted);\n            // If we already have a prediction for this (second) rigid body, we check which of the two generating models has higher probability\n            if(previous_prediction_it != rbid_predicted_and_likelihood.end())\n            {\n                // If the new prediction comes from a model that is more likely, we take this prediction\n                if(previous_prediction_it->second < most_probable_joint_hypothesis->getProbabilityOfJointFilter())\n                {\n                    ROS_INFO_STREAM_NAMED(\"MultiJointTracker.predictMeasurement\", \"Replacing previous prediction with prediction from \"\n                                          << most_probable_joint_hypothesis->getJointFilterTypeStr());\n                    pose_and_vel_one_rb.rb_id = rbid_predicted;\n                    pose_and_vel_one_rb.pose_wc = most_probable_joint_hypothesis->getPredictedSRBDeltaPoseWithCovInSensorFrame();\n                    pose_and_vel_one_rb.velocity_wc = most_probable_joint_hypothesis->getPredictedSRBVelocityWithCovInSensorFrame();\n                    rbid_predicted_and_predictions[rbid_predicted] = pose_and_vel_one_rb;\n                    rbid_predicted_and_likelihood[rbid_predicted] = most_probable_joint_hypothesis->getProbabilityOfJointFilter();\n                }\n            }\n            // If we don't have any prediction for this (second) rigid body, we use this prediction\n            else{\n                ROS_INFO_STREAM_NAMED(\"MultiJointTracker.predictMeasurement\", \"Use prediction from \"\n                                      << most_probable_joint_hypothesis->getJointFilterTypeStr());\n                pose_and_vel_one_rb.rb_id = rbid_predicted;\n                pose_and_vel_one_rb.pose_wc = most_probable_joint_hypothesis->getPredictedSRBDeltaPoseWithCovInSensorFrame();\n                pose_and_vel_one_rb.velocity_wc = most_probable_joint_hypothesis->getPredictedSRBVelocityWithCovInSensorFrame();\n                rbid_predicted_and_predictions[rbid_predicted] = pose_and_vel_one_rb;\n                rbid_predicted_and_likelihood[rbid_predicted] = most_probable_joint_hypothesis->getProbabilityOfJointFilter();\n            }\n        }\n    }\n\n    // We collect all the best predictions into the vector of predicted measurements\n    std::map<int, omip_msgs::RigidBodyPoseAndVelMsg>::iterator best_predictions_it = rbid_predicted_and_predictions.begin();\n    std::map<int, omip_msgs::RigidBodyPoseAndVelMsg>::iterator best_predictions_it_end = rbid_predicted_and_predictions.end();\n    for(; best_predictions_it != best_predictions_it_end; best_predictions_it++)\n    {\n        this->_predicted_measurement.rb_poses_and_vels.push_back(best_predictions_it->second);\n    }\n}\n\nvoid MultiJointTracker::setMeasurement(const ks_measurement_t &poses_and_vels, const double &measurement_timestamp_ns)\n{\n    this->_previous_measurement_timestamp_ns = this->_measurement_timestamp_ns;\n    this->_measurement_timestamp_ns = measurement_timestamp_ns;\n\n    this->_previous_rcvd_poses_and_vels.swap(this->_last_rcvd_poses_and_vels);\n    this->_last_rcvd_poses_and_vels = boost::shared_ptr<ks_measurement_t>(new ks_measurement_t(poses_and_vels));\n\n    _n_previous_rcvd_poses_and_vels.push_back(boost::shared_ptr<ks_measurement_t>(new ks_measurement_t(poses_and_vels)));\n    if(_n_previous_rcvd_poses_and_vels.size() > _min_num_frames_for_new_rb)\n    {\n        _n_previous_rcvd_poses_and_vels.pop_front();\n    }\n\n    size_t rrb_idx_begin = 0;\n    size_t rrb_idx_end = 0;\n\n    switch(this->_ks_analysis_type)\n    {\n    case MOVING_BODIES_TO_STATIC_ENV:\n        rrb_idx_begin = 0;\n        rrb_idx_end = 1;\n        break;\n    case BETWEEN_MOVING_BODIES:\n        rrb_idx_begin = 1;\n        rrb_idx_end = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.size();\n        break;\n    case FULL_ANALYSIS:\n        rrb_idx_begin = 0;\n        rrb_idx_end = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.size();\n        break;\n    }\n\n    for (size_t rrb_idx = rrb_idx_begin; rrb_idx < rrb_idx_end; rrb_idx++)\n    {\n        for (size_t srb_idx = rrb_idx + 1; srb_idx < this->_last_rcvd_poses_and_vels->rb_poses_and_vels.size(); srb_idx++)\n        {\n            // Extract RB ids\n            int rrb_id = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(rrb_idx).rb_id;\n            int srb_id = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(srb_idx).rb_id;\n\n            std::pair<int, int> rrb_srb_ids = std::pair<int, int>(rrb_id, srb_id);\n\n            // Check if this pair of rbs were observed before -> joint was estimated before\n            std::map<std::pair<int, int>, JointCombinedFilterPtr>::iterator prev_joint_combined_filter_it =this->_joint_combined_filters.find(rrb_srb_ids);\n\n            // If this is a new pair of RB not analyzed before\n            if (prev_joint_combined_filter_it != this->_joint_combined_filters.end())\n            { // It was previously stored -> Use it and pass the new measurements\n                prev_joint_combined_filter_it->second->setMeasurement(joint_measurement_t(\n                                                                          this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(rrb_idx),\n                                                                          this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(srb_idx)), measurement_timestamp_ns);\n            }\n        }\n    }\n}\n\nJointCombinedFilterPtr MultiJointTracker::getCombinedFilter(int n)\n{\n    joint_combined_filters_map::iterator it = this->_joint_combined_filters.begin();\n\n    for(int k=0; k<n; k++)\n    {\n        it++;\n    }\n    return it->second;\n}\n\nvoid MultiJointTracker::correctState()\n{\n    // I create a new one so that the joints are either created, corrected, or deleted if there is no more information about them\n    joint_combined_filters_map corrected_joint_combined_filters;\n\n    size_t rrb_idx_begin = 0;\n    size_t rrb_idx_end = 0;\n\n    switch(this->_ks_analysis_type)\n    {\n    case MOVING_BODIES_TO_STATIC_ENV:\n        rrb_idx_begin = 0;\n        rrb_idx_end = 1;\n        break;\n    case BETWEEN_MOVING_BODIES:\n        rrb_idx_begin = 1;\n        rrb_idx_end = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.size();\n        break;\n    case FULL_ANALYSIS:\n        rrb_idx_begin = 0;\n        rrb_idx_end = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.size();\n        break;\n    }\n\n    for (size_t rrb_idx = rrb_idx_begin; rrb_idx < rrb_idx_end; rrb_idx++)\n    {\n        for (size_t srb_idx = rrb_idx + 1; srb_idx < this->_last_rcvd_poses_and_vels->rb_poses_and_vels.size(); srb_idx++)\n        {\n            // Extract RB ids\n            int rrb_id = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(rrb_idx).rb_id;\n            int srb_id = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(srb_idx).rb_id;\n\n            std::pair<int, int> rrb_srb_ids = std::pair<int, int>(rrb_id, srb_id);\n\n            // Check if this pair of rbs were observed before and we already have a joint filter for it\n            std::map<std::pair<int, int>, JointCombinedFilterPtr>::iterator prev_joint_combined_filter_it =this->_joint_combined_filters.find(rrb_srb_ids);\n\n            // If we don't have a joint filter for it\n            if (prev_joint_combined_filter_it == this->_joint_combined_filters.end())\n            {\n                // If we it is the very first time we see this pair rrb-srb (probably because it is the first frame we track the srb)\n                if (this->_precomputing_counter.find(rrb_srb_ids) == this->_precomputing_counter.end())\n                {\n                    // 1)\n                    // We create an entry for this pair rrb-srb into our counter and set the counter to zero\n                    this->_precomputing_counter[rrb_srb_ids] = 0;\n\n                    // 2)\n                    // We store the pose of the reference rigid body at the frame/time step when the new (second) rb was detected\n                    // Since we estimate an initial trajectory of length _min_num_frames_for_new_rb we query the pose of the\n                    // reference rigid body _min_num_frames_for_new_rb frames before\n                    // Actually, we are not sure that the reference rb existed _min_num_frames_for_new_rb before\n                    // so we query the oldest in our accumulator\n                    Eigen::Twistd rrb_pose_at_srb_birthday_in_sf_twist = Eigen::Twistd(0.,0.,0.,0.,0.,0.);\n                    std::list<omip_msgs::RigidBodyPosesAndVelsMsgPtr>::iterator acc_frames_it = this->_n_previous_rcvd_poses_and_vels.begin();\n                    std::list<omip_msgs::RigidBodyPosesAndVelsMsgPtr>::iterator acc_frames_end = this->_n_previous_rcvd_poses_and_vels.end();\n\n                    for(; acc_frames_it !=  acc_frames_end; acc_frames_it++)\n                    {\n                        for(int rb_prev_idx = 0; rb_prev_idx < (*acc_frames_it)->rb_poses_and_vels.size(); rb_prev_idx++)\n                        {\n                            // The RRB was existing in the previous frame\n                            if((*acc_frames_it)->rb_poses_and_vels.at(rb_prev_idx).rb_id == rrb_id)\n                            {\n                                ROSTwist2EigenTwist((*acc_frames_it)->rb_poses_and_vels.at(rb_prev_idx).pose_wc.twist, rrb_pose_at_srb_birthday_in_sf_twist);\n                            }\n                        }\n                    }\n                    this->_rrb_pose_at_srb_birthday_in_sf[rrb_srb_ids] = rrb_pose_at_srb_birthday_in_sf_twist;\n\n                    // 3)\n                    // We store the first pose of the second rigid body\n                    // Due to the initial trajectory estimation, the first pose received is actually not really the first pose.\n                    // Before, with the OMIP version that does NOT place the body frames at the centroid of the body we could assume that the first pose\n                    // of the body wrt the sensor was the identity\n                    // Now, with the OMIP version that places the body frames at the centroid of the body that assumption does not hold any longer\n                    // SOLUTION: at the first frame/time step we get from the RBTracker in the field centroid of the rigid body the centroid we used for the trajectory estimation\n                    // We can use this centroid as initial translation\n                    Eigen::Twistd srb_pose_at_srb_birthday_in_sf_twist = Eigen::Twistd(0.,0.,0.,0.,0.,0.);\n                    for(int rb_prev_idx = 0; rb_prev_idx < this->_last_rcvd_poses_and_vels->rb_poses_and_vels.size(); rb_prev_idx++)\n                    {\n                        // The SRB was existing in the previous frame\n                        if(this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(rb_prev_idx).rb_id == srb_id)\n                        {\n                            srb_pose_at_srb_birthday_in_sf_twist.vx() = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(rb_prev_idx).centroid.x;\n                            srb_pose_at_srb_birthday_in_sf_twist.vy() = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(rb_prev_idx).centroid.y;\n                            srb_pose_at_srb_birthday_in_sf_twist.vz() = this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(rb_prev_idx).centroid.z;\n                        }\n                    }\n\n                    this->_srb_pose_at_srb_birthday_in_sf[rrb_srb_ids] = srb_pose_at_srb_birthday_in_sf_twist;\n                }\n                else\n                {\n                    Eigen::Twistd new_twist;\n                    ROSTwist2EigenTwist(this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(srb_idx).pose_wc.twist, new_twist);\n\n                    // We accumulate _min_joint_age_for_ee iterations (pairs of poses) to initialize the filters with a better estimation\n                    if (this->_precomputing_counter[rrb_srb_ids] >= this->_min_joint_age_for_ee)\n                    {\n                        corrected_joint_combined_filters[rrb_srb_ids] = JointCombinedFilterPtr(new JointCombinedFilter());\n                        corrected_joint_combined_filters[rrb_srb_ids]->setLoopPeriodNS(this->_loop_period_ns);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setNumSamplesForLikelihoodEstimation(this->_likelihood_sample_num);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceDeltaMeasurementLinear(this->_sigma_delta_meas_uncertainty_linear);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceDeltaMeasurementAngular(this->_sigma_delta_meas_uncertainty_angular);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setMaxTranslationRigid(this->_rig_max_translation);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setMaxRotationRigid(this->_rig_max_rotation);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setJointLikelihoodDisconnected(this->_disconnected_j_ne);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovariancePrior(PRISMATIC_JOINT, this->_prism_prior_cov_vel);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoisePhi(PRISMATIC_JOINT, this->_prism_sigma_sys_noise_phi);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoiseTheta(PRISMATIC_JOINT, this->_prism_sigma_sys_noise_theta);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoiseJointState(PRISMATIC_JOINT, this->_prism_sigma_sys_noise_pv);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoiseJointVelocity(PRISMATIC_JOINT, this->_prism_sigma_sys_noise_pvd);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceMeasurementNoise(PRISMATIC_JOINT, this->_prism_sigma_meas_noise);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovariancePrior(REVOLUTE_JOINT, this->_rev_prior_cov_vel);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoisePhi(REVOLUTE_JOINT, this->_rev_sigma_sys_noise_phi);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoiseTheta(REVOLUTE_JOINT, this->_rev_sigma_sys_noise_theta);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoiseJointState(REVOLUTE_JOINT, this->_rev_sigma_sys_noise_rv);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoiseJointVelocity(REVOLUTE_JOINT, this->_rev_sigma_sys_noise_rvd);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoisePx(REVOLUTE_JOINT, this->_rev_sigma_sys_noise_px);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoisePy(REVOLUTE_JOINT, this->_rev_sigma_sys_noise_py);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceAdditiveSystemNoisePz(REVOLUTE_JOINT, this->_rev_sigma_sys_noise_pz);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setCovarianceMeasurementNoise(REVOLUTE_JOINT, this->_rev_sigma_meas_noise);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setMinRotationRevolute(this->_rev_min_rot_for_ee);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setMaxRadiusDistanceRevolute(this->_rev_max_joint_distance_for_ee);\n                        corrected_joint_combined_filters[rrb_srb_ids]->setInitialMeasurement(joint_measurement_t(this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(rrb_idx),\n                                                                                                                 this->_last_rcvd_poses_and_vels->rb_poses_and_vels.at(srb_idx)),\n                                                                                             this->_rrb_pose_at_srb_birthday_in_sf[rrb_srb_ids],\n                                                                                             this->_srb_pose_at_srb_birthday_in_sf[rrb_srb_ids]);\n                        corrected_joint_combined_filters[rrb_srb_ids]->initialize();\n                    }\n                    else\n                    {\n                        this->_precomputing_counter[rrb_srb_ids] += 1;\n                    }\n                }\n            }else{\n                prev_joint_combined_filter_it->second->correctState();\n                corrected_joint_combined_filters[rrb_srb_ids] = prev_joint_combined_filter_it->second;\n            }\n\n        }\n    }\n\n    this->_joint_combined_filters = corrected_joint_combined_filters;\n    this->_reflectState();\n}\n\nvoid MultiJointTracker::_reflectState()\n{\n    this->_state.clear();\n    this->_state = this->_joint_combined_filters;\n}\n\nvoid MultiJointTracker::estimateJointFiltersProbabilities()\n{\n    BOOST_FOREACH(joint_combined_filters_map::value_type joint_combined_filter_it, this->_joint_combined_filters)\n    {\n        joint_combined_filter_it.second->estimateJointFilterProbabilities();\n    }\n}\n\n", "meta": {"hexsha": "ee9933522273370e206b114d7b8fcbe86e8ad12d", "size": 19614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "joint_tracker/src/MultiJointTracker.cpp", "max_stars_repo_name": "tu-rbo/omip", "max_stars_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-11-10T16:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T20:11:39.000Z", "max_issues_repo_path": "joint_tracker/src/MultiJointTracker.cpp", "max_issues_repo_name": "tu-rbo/omip", "max_issues_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-28T13:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T22:01:58.000Z", "max_forks_repo_path": "joint_tracker/src/MultiJointTracker.cpp", "max_forks_repo_name": "tu-rbo/omip", "max_forks_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-11-25T18:24:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T03:20:33.000Z", "avg_line_length": 59.078313253, "max_line_length": 178, "alphanum_fraction": 0.6769654329, "num_tokens": 4388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.19800775103288723}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@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_BLAKE2B_FUNCTIONS_HPP\n#define CRYPTO3_BLAKE2B_FUNCTIONS_HPP\n\n#include <array>\n\n#include <nil/crypto3/hash/detail/blake2b/blake2b_policy.hpp>\n\n#include <boost/static_assert.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<std::size_t DigestBits>\n                struct blake2b_functions : public blake2b_policy<DigestBits> {\n                    typedef blake2b_policy<DigestBits> policy_type;\n\n                    typedef typename policy_type::word_type word_type;\n\n                    constexpr static const std::size_t state_words = policy_type::state_words;\n\n                    inline static void g(word_type &a, word_type &b, word_type &c, word_type &d, word_type M0,\n                                         word_type M1) {\n                        a = a + b + M0;\n                        d = policy_type::template rotr<32>(d ^ a);\n                        c = c + d;\n                        b = policy_type::template rotr<24>(b ^ c);\n                        a = a + b + M1;\n                        d = policy_type::template rotr<16>(d ^ a);\n                        c = c + d;\n                        b = policy_type::template rotr<63>(b ^ c);\n                    }\n\n                    template<size_t i0, size_t i1, size_t i2, size_t i3, size_t i4, size_t i5, size_t i6, size_t i7,\n                             size_t i8, size_t i9, size_t iA, size_t iB, size_t iC, size_t iD, size_t iE, size_t iF>\n                    inline static void round(std::array<word_type, state_words * 2> &v,\n                                             const std::array<word_type, state_words * 2> &M) {\n                        g(v[0], v[4], v[8], v[12], M[i0], M[i1]);\n                        g(v[1], v[5], v[9], v[13], M[i2], M[i3]);\n                        g(v[2], v[6], v[10], v[14], M[i4], M[i5]);\n                        g(v[3], v[7], v[11], v[15], M[i6], M[i7]);\n                        g(v[0], v[5], v[10], v[15], M[i8], M[i9]);\n                        g(v[1], v[6], v[11], v[12], M[iA], M[iB]);\n                        g(v[2], v[7], v[8], v[13], M[iC], M[iD]);\n                        g(v[3], v[4], v[9], v[14], M[iE], M[iF]);\n                    }\n                };\n            }    // namespace detail\n        }        // namespace hashes\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_BLAKE2B_FUNCTIONS_HPP\n", "meta": {"hexsha": "c0468527d9eea70e81279a4bfd25f3eda09402fa", "size": 3815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/hash/detail/blake2b/blake2b_functions.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/blake2b/blake2b_functions.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/blake2b/blake2b_functions.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": 48.2911392405, "max_line_length": 116, "alphanum_fraction": 0.5323722149, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.1979995782496004}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SCALAR_FMASUBADD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SCALAR_FMASUBADD_HPP_INCLUDED\n\n#include <boost/simd/function/definition/fmasubadd.hpp>\n#include <boost/simd/arch/common/scalar/function/fmasubadd.hpp>\n\n#endif\n", "meta": {"hexsha": "a2c0b6451b0c2845b4101c047315296bfaba5051", "size": 629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/scalar/fmasubadd.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/scalar/fmasubadd.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/scalar/fmasubadd.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.0, "max_line_length": 100, "alphanum_fraction": 0.5516693164, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.19799955779230896}}
{"text": "#include <iostream>\n\n#include \"gflags/gflags.h\"\n#include \"sndfile.h\"\n#include \"tbb/tbb.h\"\n#include \"tbb/pipeline.h\"\n#include \"tbb/scalable_allocator.h\"\n#include \"tbb/cache_aligned_allocator.h\"\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include \"bakuage/sndfile_wrapper.h\"\n#include \"bakuage/dft.h\"\n#include \"bakuage/memory.h\"\n#include \"bakuage/utils.h\"\n#include \"bakuage/window_func.h\"\n#include \"bakuage/transient_filter.h\"\n#include \"bakuage/transient_filter2.h\"\n\nDEFINE_string(input, \"\", \"comma separated input wav file paths\");\nDEFINE_string(output, \"\", \"output wav file path\");\nDEFINE_double(window_sec, 0.02, \"dft window size in sec\");\nDEFINE_double(mean_sec, 0.02, \"energy lowpass mean time in sec\");\nDEFINE_double(ratio, 2, \"ratio\");\nDEFINE_double(noise_reduction_threshold, -20, \"noise reduction threshold in dB\");\nDEFINE_bool(normalize, false, \"whether if normalize is done before output\");\nDEFINE_string(mode, \"transient\", \"mode (transient)\");\n\nnamespace {\ntypedef float Float;\n    \ntemplate <class Effect>\nvoid CalculateEffect(Effect *effect, const std::vector<std::vector<Float>> &input, int channels, int samples, int sample_freq, Float *output) {\n\n    std::cerr << \"calculate start\" << std::endl;\n    bakuage::StopWatch stop_watch;\n    stop_watch.Start();\n    Float temp[2] = { 0 };\n    Float zero[2] = { 0 };\n    for (int i = 0; i < samples + effect->delay_samples(); i++) {\n        if (i < samples) {\n            for (int j = 0; j < channels; j++) {\n                temp[j] = input[0][channels * i + j];\n            }\n            effect->Clock(temp, temp);\n        } else {\n            effect->Clock(zero, temp);\n        }\n        \n        int output_i = i - effect->delay_samples();\n        if (0 <= output_i) {\n            for (int j = 0; j < channels; j++) {\n                output[channels * output_i + j] = temp[j];\n            }\n        }\n    }\n    \n    std::cerr << \"calculate finish \" << stop_watch.time() << std::endl;\n}\n\ntemplate <class Float>\nvoid SaveFloatWave(const std::vector<Float> &wave, const std::string &filename) {\n    bakuage::SndfileWrapper snd_file;\n    SF_INFO sfinfo = { 0 };\n    std::memset(&sfinfo, 0, sizeof(sfinfo));\n    \n    sfinfo.channels = 2;\n    sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;\n    int frames = wave.size() / sfinfo.channels;\n    sfinfo.frames = frames;\n    sfinfo.samplerate = 44100;\n    \n    if ((snd_file.set(sf_open(filename.c_str(), SFM_WRITE, &sfinfo))) == NULL) {\n        std::stringstream message;\n        message << \"Not able to open output file \" << filename << \", \"\n        << sf_strerror(NULL);\n        throw std::logic_error(message.str());\n    }\n    \n    sf_count_t size;\n    if (sizeof(Float) == 4) {\n        size = sf_writef_float(snd_file.get(), (float *)wave.data(), frames);\n    } else {\n        size = sf_writef_double(snd_file.get(), (double *)wave.data(), frames);\n    }\n    if (size != frames) {\n        std::stringstream message;\n        message << \"sf_writef_float error: \" << size;\n        throw std::logic_error(message.str());\n    }\n}\n}\n\n// wav\u3092\u53d7\u3051\u53d6\u3063\u3066\u3001\u6a19\u6e96\u51fa\u529b\u306brawvideo\u3092\u51fa\u529b\nint main(int argc, char* argv[]) {\n    gflags::SetVersionString(\"1.0.0\");\n    gflags::ParseCommandLineFlags(&argc, &argv, true);\n    \n    bakuage::SndfileWrapper infile;\n    SF_INFO sfinfo = { 0 };\n    int frames = 1 << 30;\n    \n    // \u30ab\u30f3\u30de\u533a\u5207\u308a\u3092\u5206\u89e3\u3057\u3066\u3001load wave (\u5168\u3066\u304c\u540c\u3058\u30d5\u30a9\u30fc\u30de\u30c3\u30c8\u3067\u3042\u308b\u5fc5\u8981\u304c\u3042\u308b)\n    std::vector<std::vector<float>> buffers;\n    std::vector<std::string> input_paths;\n    boost::algorithm::split(input_paths, FLAGS_input, boost::is_any_of(\",\"));\n    for (const auto &input_file_path: input_paths) {\n        if ((infile.set(sf_open (input_file_path.c_str(), SFM_READ, &sfinfo))) == NULL) {\n            fprintf(stderr, \"Not able to open input file %s.\\n\", input_file_path.c_str());\n            fprintf(stderr, \"%s\\n\", sf_strerror(NULL));\n            return 1;\n        }\n        \n        // check format\n        fprintf(stderr, \"sfinfo.format 0x%08x.\\n\", sfinfo.format);\n        switch (sfinfo.format & SF_FORMAT_TYPEMASK) {\n            case SF_FORMAT_WAV:\n            case SF_FORMAT_WAVEX:\n                break;\n            default:\n                fprintf(stderr, \"Not supported sfinfo.format 0x%08x.\\n\", sfinfo.format);\n                return 2;\n        }\n        \n        std::vector<float> buffer(sfinfo.channels * sfinfo.frames);\n        int read_size = sf_readf_float(infile.get(), buffer.data(), sfinfo.frames);\n        fprintf(stderr, \"%d samples read.\\n\", read_size);\n        if (read_size != sfinfo.frames) {\n            fprintf(stderr, \"sf_readf_float error: %d %d\\n\", read_size, (int)sfinfo.frames);\n            return 3;\n        }\n        buffers.emplace_back(buffer);\n        \n        frames = std::min<int>(frames, sfinfo.frames);\n    }\n    \n    // calculate spectrogram (energy)\n    std::vector<float> output(frames * sfinfo.channels);\n    \n    if (FLAGS_mode == \"transient\") {\n        bakuage::TransientFilter<Float, std::function<Float (Float, Float)>>::Config config;\n        config.num_channels = sfinfo.channels;\n        config.sample_rate = sfinfo.samplerate;\n        config.long_mean_sec = 0.2;\n        config.short_mean_sec = 0.02;\n        config.gain_func = [](Float long_loundess, Float short_loudness) {\n            return (short_loudness - long_loundess) * (FLAGS_ratio - 1);\n        };\n        bakuage::TransientFilter<Float, std::function<Float (Float, Float)>> transient_filter(config);\n        CalculateEffect(&transient_filter, buffers, sfinfo.channels, frames, sfinfo.samplerate, output.data());\n    } else if (FLAGS_mode == \"transient2\") {\n        bakuage::TransientFilter2<Float, std::function<Float (Float, Float)>>::Config config;\n        config.num_channels = sfinfo.channels;\n        config.sample_rate = sfinfo.samplerate;\n        config.long_mean_sec = 0.2;\n        config.short_mean_sec = 0.02;\n        config.gain_func = [](Float long_loundess, Float short_loudness) {\n            return (short_loudness - long_loundess) * (FLAGS_ratio - 1);\n        };\n        bakuage::TransientFilter2<Float, std::function<Float (Float, Float)>> transient_filter(config);\n        CalculateEffect(&transient_filter, buffers, sfinfo.channels, frames, sfinfo.samplerate, output.data());\n    }\n    \n    // normalize\n    if (FLAGS_normalize) {\n        double peak = 1e-37;\n        for (int i = 0; i < output.size(); i++) {\n            peak = std::max<double>(peak, std::abs(output[i]));\n        }\n        for (int i = 0; i < output.size(); i++) {\n            output[i] /= peak;\n        }\n    }\n    \n    // save output\n    SaveFloatWave(output, FLAGS_output);\n}\n\n", "meta": {"hexsha": "51ade6db1a504cc615d5f8eb82eebf87ef78ac6d", "size": 6601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/effect_test/main.cpp", "max_stars_repo_name": "nankasuisui/phaselimiter", "max_stars_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-07-07T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:43:47.000Z", "max_issues_repo_path": "src/effect_test/main.cpp", "max_issues_repo_name": "nankasuisui/phaselimiter", "max_issues_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_issues_repo_licenses": ["MIT"], "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/effect_test/main.cpp", "max_forks_repo_name": "nankasuisui/phaselimiter", "max_forks_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-03T13:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T20:21:10.000Z", "avg_line_length": 37.0842696629, "max_line_length": 143, "alphanum_fraction": 0.6156642933, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.34510525748676857, "lm_q1q2_score": 0.19797943451849767}}
{"text": "//#include <exe/inputParser.h>\n\n//#include <base/cgal_typedefs.h>\n//#include <IO/fileIO.h>\n//#include <IO/ttIO.h>\n//#include <IO/ethIO.h>\n//#ifdef OpenMVS\n//#include <IO/mvIO.h>\n//#endif\n//#ifdef COLMAP\n//#include <IO/colmapIO.h>\n//#endif\n//#include <util/helper.h>\n//#include <util/vectorArithmetic.h>\n\n//#include <processing/meshProcessing.h>\n//#include <processing/edgeManifoldness.h>\n//#include <processing/graphCut.h>\n\n//#include <processing/pointSetProcessing.h>\n//#include <processing/normalAndSensorProcessing.h>\n//#include <processing/evaluation.h>\n//#include <processing/rayTracingFacet.h>\n\n//#include <learning/learning.h>\n//#include <learning/learningMath.h>\n//#include <learning/learningRayTracing.h>\n//#include <learning/learningRayTracingGroundTruth.h>\n//#include <learning/learningIO.h>\n\n//#include <CGAL/refine_mesh_3.h>\n\n//#ifdef Open3D\n//#include \"open3d/Open3D.h\"\n//#include \"open3d/geometry/TetraMesh.h\"\n//#endif\n\n//#include <CGAL/optimal_bounding_box.h>\n//#include <boost/filesystem.hpp>\n//using namespace boost::filesystem;\n\n////#include <CGAL/Polygon_mesh_processing/clip.h>\n////#include <CGAL/Surface_mesh_default_triangulation_3.h>\n////#include <CGAL/Complex_2_in_triangulation_3.h>\n////#include <CGAL/make_surface_mesh.h>\n////#include <CGAL/Implicit_surface_3.h>\n////#include <CGAL/IO/facets_in_complex_2_to_triangle_mesh.h>\n////#include <CGAL/IO/Complex_2_in_triangulation_3_file_writer.h>\n\n////Delaunay gDt;\n\n////typedef Delaunay::Geom_traits GT;\n////typedef GT::FT FT;\n\n////// default triangulation for Surface_mesher\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::FT FT;\n////typedef FT (*Function)(Point);\n////typedef CGAL::Implicit_surface_3<GT, Function> Surface_3;\n\n////double smoothedOccupancy(Cell_handle& ch, Point& p, bool gc){\n\n////    EPICK k;\n\n////    // query point to triangle distances\n////    double dp0 = sqrt(CGAL::internal::squared_distance_to_triangle(p,ch->vertex(0)->point(),ch->vertex(1)->point(),ch->vertex(2)->point(),k));\n////    double dp1 = sqrt(CGAL::internal::squared_distance_to_triangle(p,ch->vertex(0)->point(),ch->vertex(1)->point(),ch->vertex(3)->point(),k));\n////    double dp2 = sqrt(CGAL::internal::squared_distance_to_triangle(p,ch->vertex(1)->point(),ch->vertex(2)->point(),ch->vertex(3)->point(),k));\n////    double dp3 = sqrt(CGAL::internal::squared_distance_to_triangle(p,ch->vertex(0)->point(),ch->vertex(2)->point(),ch->vertex(3)->point(),k));\n\n////    Point bc = barycenter(ch);\n////    // barycenter to triangle distances\n////    double dc0 = sqrt(CGAL::internal::squared_distance_to_triangle(bc,ch->vertex(0)->point(),ch->vertex(1)->point(),ch->vertex(2)->point(),k));\n////    double dc1 = sqrt(CGAL::internal::squared_distance_to_triangle(bc,ch->vertex(0)->point(),ch->vertex(1)->point(),ch->vertex(3)->point(),k));\n////    double dc2 = sqrt(CGAL::internal::squared_distance_to_triangle(bc,ch->vertex(1)->point(),ch->vertex(2)->point(),ch->vertex(3)->point(),k));\n////    double dc3 = sqrt(CGAL::internal::squared_distance_to_triangle(bc,ch->vertex(0)->point(),ch->vertex(2)->point(),ch->vertex(3)->point(),k));\n\n////    // d(P,f_i)/d(c,f_i)\n////    double d0 = dp0/dc0;\n////    double d1 = dp1/dc1;\n////    double d2 = dp2/dc2;\n////    double d3 = dp3/dc3;\n\n////    // min_i d(P,f_i)/d(c,f_i)\n////    double mind = min(min(min(d0,d1),d2),d3);\n\n////    // x\n////    double x = (1.0+mind)/2.0;\n\n////    if(0.5 > x || x > 1.0){\n////        cout << x << endl;\n////        cout << ch->vertex(0)->point() << endl;\n////        cout << ch->vertex(1)->point() << endl;\n////        cout << ch->vertex(2)->point() << endl;\n////        cout << ch->vertex(3)->point() << endl;\n////    }\n////    assert(0.5<=x && x<=1.0);\n\n\n////    // z_i\n////    double z0 = max(0.0,1-d0)/2.0;\n////    double z1 = max(0.0,1-d1)/2.0;\n////    double z2 = max(0.0,1-d2)/2.0;\n////    double z3 = max(0.0,1-d3)/2.0;\n////    assert(0.0<=z0 && z0<=0.5);\n////    assert(0.0<=z1 && z1<=0.5);\n////    assert(0.0<=z2 && z2<=0.5);\n////    assert(0.0<=z3 && z3<=0.5);\n\n////    if(!gc){ // without graph cut\n////        double occ0 = ch->neighbor(3)->info().outside_score - 0.5; // triangle 0,1,2\n////        double occ1 = ch->neighbor(2)->info().outside_score - 0.5; // triangle 0,1,3\n////        double occ2 = ch->neighbor(0)->info().outside_score - 0.5; // triangle 1,2,3\n////        double occ3 = ch->neighbor(1)->info().outside_score - 0.5; // triangle 0,2,3\n////        double occ = ch->info().outside_score - 0.5;\n////        return (x*occ + z0*occ0 + z1*occ1 + z2*occ2 + z3*occ3) / (x+z0+z1+z2+z3);\n////    }\n////    else{ // with graph cut\n////        bool stet = false;\n////        // check if tet is surface tet\n////        for(int i = 0; i < 4; i++){\n////            if(ch->neighbor(i)->info().gc_label != ch->info().gc_label){\n////                stet = true;\n////                break;\n////            }\n////        }\n////        if(stet){ // use continuous (smoothed) occupancy\n////            double occ0 = ch->neighbor(3)->info().outside_score - 0.5; // triangle 0,1,2\n////            double occ1 = ch->neighbor(2)->info().outside_score - 0.5; // triangle 0,1,3\n////            double occ2 = ch->neighbor(0)->info().outside_score - 0.5; // triangle 1,2,3\n////            double occ3 = ch->neighbor(1)->info().outside_score - 0.5; // triangle 0,2,3\n////            double occ = ch->info().outside_score - 0.5;\n\n//////            double occ0 = ch->neighbor(3)->info().gc_label - 0.5; // triangle 0,1,2\n//////            double occ1 = ch->neighbor(2)->info().gc_label - 0.5; // triangle 0,1,3\n//////            double occ2 = ch->neighbor(0)->info().gc_label - 0.5; // triangle 1,2,3\n//////            double occ3 = ch->neighbor(1)->info().gc_label - 0.5; // triangle 0,2,3\n//////            double occ = ch->info().gc_label - 0.5;\n////            return (x*occ + z0*occ0 + z1*occ1 + z2*occ2 + z3*occ3) / (x+z0+z1+z2+z3);\n////        }\n////        else{ // use discrete occupancy (smoothing shouldn't change anything??)\n////            return ch->info().gc_label - 0.5;\n////        }\n////    }\n////}\n\n\n////FT gc_occ_function (Point p){\n\n\n////    // get the cell of the test point\n////    Delaunay::Locate_type lt;\n////    int li, lj;\n////    auto ch = gDt.locate(p,lt,li,lj);\n////    if(lt == Delaunay::OUTSIDE_CONVEX_HULL || lt == Delaunay::OUTSIDE_AFFINE_HULL){\n////        const FT occ = 0.5;\n////        return occ;\n////    }\n////    // check for neighboring labels\n////    for(int i = 0; i < 4; i++){\n////        if(ch->neighbor(i)->info().gc_label != ch->info().gc_label){\n////            const FT occ = ch->info().outside_score - 0.5;\n////            return occ;\n////        }\n////    }\n////    const FT occ = ch->info().gc_label - 0.5;\n////    return occ;\n\n\n////}\n////FT occ_function (Point p){\n\n////    // get the cell of the test point and return its \"signed occupancy\"\n////    Delaunay::Locate_type lt;\n////    int li, lj;\n////    auto ch = gDt.locate(p,lt,li,lj);\n////    if(lt == Delaunay::OUTSIDE_CONVEX_HULL || lt == Delaunay::OUTSIDE_AFFINE_HULL){\n////        const FT occ = 0.5;\n////        return occ;\n////    }\n////    const FT occ = ch->info().outside_score - 0.5;\n////    return occ;\n////}\n////FT gc_smoothed_occ_function (Point p){\n\n////    // get the cell of the test point\n////    Delaunay::Locate_type lt;\n////    int li, lj;\n////    auto ch = gDt.locate(p,lt,li,lj);\n////    if(lt == Delaunay::OUTSIDE_CONVEX_HULL || lt == Delaunay::OUTSIDE_AFFINE_HULL){\n////        const FT occ = 0.5;\n////        return occ;\n////    }\n////    const FT occ = smoothedOccupancy(ch,p,1);\n////    return occ;\n\n\n////}\n////FT smoothed_occ_function (Point p){\n////    // get the cell of the test point and return its \"signed occupancy\"\n////    Delaunay::Locate_type lt;\n////    int li, lj;\n////    auto ch = gDt.locate(p,lt,li,lj);\n////    if(lt == Delaunay::OUTSIDE_CONVEX_HULL || lt == Delaunay::OUTSIDE_AFFINE_HULL){\n////        const FT occ = 0.5;\n////        return occ;\n////    }\n////    const FT occ = smoothedOccupancy(ch,p,0);\n////    return occ;\n////}\n\n\n\n////int isoExtraction(dirHolder dir, dataHolder& data, runningOptions options){\n\n////    auto start = std::chrono::high_resolution_clock::now();\n\n////    std::cout << \"\\nExtract isosurface...\" << endl;\n////    cout << \"\\t-lower bound facet angle: \" << options.iso_options[0] << endl;\n////    cout << \"\\t-upper bound radius surface Delaunay balls: \" << options.iso_options[1] << endl;\n////    cout << \"\\t-upper bound for facet center-center distances: \" << options.iso_options[2] << endl;\n\n\n\n////    Tr tr;            // 3D-Delaunay triangulation\n////    C2t3 c2t3(tr);   // 2D-complex in 3D-Delaunay triangulation\n\n////    gDt = data.Dt;\n\n////    int init = 20;\n\n////    // defining the surface\n////    if(options.optimization){\n////        cout << \"\\t-use graph cut labels\" << endl;\n////        if(options.smooth_field){\n////            cout << \"\\t-use smoothed field\" << endl;\n////            Surface_3 surface(gc_smoothed_occ_function,             // pointer to function\n////                            Sphere_3(CGAL::ORIGIN, 100.0*100.0)); // bounding sphere with squared radius\n////            CGAL::Surface_mesh_default_criteria_3<Tr> criteria(options.iso_options[0],  // angular bound\n////                                                           options.iso_options[1],  // radius bound\n////                                                           options.iso_options[2]); // distance bound\n\n////            cout << \"\\t-defined field\" << endl;\n\n////            // meshing surface\n////            CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Manifold_tag(),init);\n////        }\n////        else{\n////            cout << \"\\t-use unsmoothed field\" << endl;\n////            Surface_3 surface(gc_occ_function,             // pointer to function\n////                            Sphere_3(CGAL::ORIGIN, 100.0*100.0)); // bounding sphere with squared radius\n////            CGAL::Surface_mesh_default_criteria_3<Tr> criteria(options.iso_options[0],  // angular bound\n////                                                           options.iso_options[1],  // radius bound\n////                                                           options.iso_options[2]); // distance bound\n\n////            cout << \"\\t-defined field\" << endl;\n\n////            // meshing surface\n////            CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Manifold_tag(),init);\n////        }\n\n\n////    }\n////    else{\n////        cout << \"\\t-use continuous labels\" << endl;\n////        if(options.smooth_field){\n////            cout << \"\\t-use smoothed field\" << endl;\n////            Surface_3 surface(smoothed_occ_function,             // pointer to function\n////                            Sphere_3(CGAL::ORIGIN, 100.0*100.0)); // bounding sphere with squared radius\n////            CGAL::Surface_mesh_default_criteria_3<Tr> criteria(options.iso_options[0],  // angular bound\n////                                                           options.iso_options[1],  // radius bound\n////                                                           options.iso_options[2]); // distance bound\n////            cout << \"\\t-defined field\" << endl;\n\n////            // meshing surface\n////            CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Manifold_tag(),init);\n////        }\n////        else{\n////            cout << \"\\t-use unsmoothed field\" << endl;\n////            Surface_3 surface(occ_function,             // pointer to function\n////                            Sphere_3(CGAL::ORIGIN, 100.0*100.0)); // bounding sphere with squared radius\n////            CGAL::Surface_mesh_default_criteria_3<Tr> criteria(options.iso_options[0],  // angular bound\n////                                                           options.iso_options[1],  // radius bound\n////                                                           options.iso_options[2]); // distance bound\n////            cout << \"\\t-defined field\" << endl;\n////            // meshing surface\n////            CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Manifold_tag(),init);\n////        }\n////    }\n\n////    // criteria see here: https://doc.cgal.org/latest/Surface_mesher/classCGAL_1_1Surface__mesh__default__criteria__3.html\n\n//////    a lower bound on the minimum angle in degrees of the surface mesh facets.\n//////    an upper bound on the radius of surface Delaunay balls. A surface Delaunay ball is a ball circumscribing a facet, centered on the surface and empty of vertices. Such a ball exists for each facet of the current surface mesh. Indeed the current surface mesh is the Delaunay triangulation of the current sampling restricted to the surface which is just the set of facets in the three dimensional Delaunay triangulation of the sampling that have a Delaunay surface ball.\n//////    an upper bound on the center-center distances of the surface mesh facets. The center-center distance of a surface mesh facet is the distance between the facet circumcenter and the center of its surface Delaunay ball.\n\n////    //  topology\tis the set of topological constraints which have to be verified by each surface facet. See section Delaunay Refinement for further details. Note that if one parameter is set to 0, then its corresponding criteria is ignored.\n\n\n////    SurfaceMesh sm;\n////    std::ofstream out(dir.path+dir.write_file+\"_isosurface.off\");\n\n\n////    CGAL::output_surface_facets_to_off(out,c2t3);\n\n////    cout << \"\\t-make surface mesh\" << endl;\n//////    CGAL::facets_in_complex_2_to_triangle_mesh(c2t3, sm);\n//////    out << sm << std::endl;\n\n//////    std::cout << \"\\t-number of points: \" << tr.number_of_vertices() << \"\\n\";\n////    auto stop = chrono::high_resolution_clock::now();\n////    auto duration = chrono::duration_cast<chrono::seconds>(stop - start);\n////    cout << \"\\t-done after \" << duration.count() << \"s\" << endl;\n////}\n\n\n///////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////\n/////////////////////////// CONTROL FUNCTIONS /////////////////////////\n///////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////\n//int surfaceReconstruction(dirHolder& dir, dataHolder& data, runningOptions& options, exportOptions& exportO){\n\n//    // TOOD: add an assert for checking that there are no duplicate points in the input for the 3DT, because the ray tracing crashes\n//    // if there are. Maybe it would however be best to change my data.points+data.infos vector to a CLGA::Point_set_3\n//    // with property maps for each info.\n\n\n\n//    ///////////////////////////////\n//    ///////// FILE NAMING /////////\n//    ///////////////////////////////\n//    options.scoring=\"_\"+options.scoring;\n//    dir.rw_string = double2string(options.area_reg_weight+options.angle_reg_weight+options.cc_reg_weight+options.sv_reg_weight);\n//    if(options.percentage_of_outliers > 0.0)\n//        dir.ol_string = double2string(options.percentage_of_outliers*100);\n//    if(dir.read_file.empty())\n//        dir.read_file = dir.write_file;\n//    if(dir.write_file.empty())\n//        dir.write_file = dir.read_file+dir.ol_string+options.scoring+dir.rw_string;\n//    else\n//        dir.write_file+=options.scoring+dir.rw_string;\n\n//    ///////////////////////////////\n//    ///////// IMPORT DATA /////////\n//    ///////////////////////////////\n//    // ground truth\n//    if(!dir.gt_poly_file.empty()){\n//        if(dir.gt_poly_file.substr(dir.gt_poly_file.length() - 3 ) == \"off\"){\n//            if(importOFFMesh(dir.path+dir.gt_poly_file, data.gt_poly))\n//                return 1;\n////            CGAL::Polygon_mesh_processing::keep_largest_connected_components(data.gt_poly, 1);\n//        }\n//        #ifdef RECONBENCH\n//        else if(dir.gt_poly_file.substr(dir.gt_poly_file.length() - 3 ) == \"mpu\"){\n//            if(importImplicit(dir, data))\n//                return 1;\n//        }\n//        #endif\n//        else{\n//            cerr << \"\\nnot a valid ending for a ground truth file. choose either .mpu or .off\" << endl;\n//            return 1;\n//        }\n//        options.ground_truth = 1;\n//    }\n//    // tt input\n////    if(options.data_source == \"tt\"){\n////        // bounding box\n////        cout << \"\\nRead bounding box from \" << dir.path+dir.read_file+\"_obb.ply\" << endl;\n////        std::ifstream in(dir.path+dir.read_file+\"_obb.ply\");\n////        CGAL::read_ply(in,data.sm_obb);\n////        if(data.sm_obb.is_empty()){\n////            cout << \"\\nERROR: empty bounding box\" << endl;\n////            return 1;\n////        }\n//////        SurfaceMesh gt_mesh;\n//////        CGAL::copy_face_graph(data.gt_poly, gt_mesh);\n//////        CGAL::Polygon_mesh_processing::triangulate_faces(data.sm_obb);\n//////        assert(CGAL::Polygon_mesh_processing::does_bound_a_volume(data.sm_obb));\n//////        CGAL::Polygon_mesh_processing::clip(gt_mesh,data.sm_obb);\n//////        data.gt_poly.clear();\n//////        CGAL::copy_face_graph(gt_mesh,data.gt_poly);\n////        // sensor locations\n////        if(importTanksAndTemplesScannerLocations(dir, data, options))\n////            return 1;\n////    }\n////    if(!options.gt_scan_source.empty()){\n////        if(options.gt_scan_source == \"eth\"){\n////            #ifdef PCL\n////            if(importETH3D(dir,data)){\n////                cout << \"\\nERROR: in importETH3D()\" << endl;\n////                return 1;\n////            }\n////            #endif\n////            data.gt_points=data.points, data.points.clear();\n////            data.gt_infos=data.infos, data.infos.clear();\n////        }\n////        else if(options.gt_scan_source == \"lidar\"){\n////            dir.gt_scan_file;\n////            // load the file from there;\n////            data.gt_points=data.points, data.points.clear();\n////            data.gt_infos=data.infos, data.infos.clear();\n////        }\n//////        else if(options.gt_scan_source == \"tt\"){\n//////            if(importTanksAndTemples(dir,data,options)){\n//////                cout << \"\\nERROR: in importTanksAndTemples()\" << endl;\n//////                return 1;\n//////            }\n//////            if(options.subsample_grid_spacing > 0)\n//////                gridSimplify(data, options.subsample_grid_spacing);\n//////            data.gt_points=data.points, data.points.clear();\n//////            data.gt_infos=data.infos, data.infos.clear();\n//////        }\n////        else{\n////            cout << \"ERROR: not a valid ground truth scan source [--gts]\" << endl;\n////            return 1;\n////        }\n////    }\n//    // reconstruction input\n//    if(options.data_source == \"scan\" || options.data_source == \"tt\"){\n//        if(!data.gt_poly.size_of_vertices() > 0){\n//            cout << \"\\nERROR: you need to load a ground truth polygon (with -g) for scanning it\" << endl;\n//            return 1;\n//        };\n//        if(scanObjectClosed(data, options))\n//            return 1;\n//    }\n//    else if(options.data_source == \"lidar\"){\n//        importPLYPoints(dir, data);\n//    }\n//    else if(options.data_source == \"npz\"){\n//        importNPZ(dir, data);\n//    }\n//    #ifdef COLMAP\n//    else if(options.data_source == \"colmap\"){\n//        readColmapFiles(dir, data);\n//    }\n//    #endif\n//    #ifdef OpenMVS\n//    else if(options.data_source == \"omvs\"){\n//        if(loadOMVSScene(dir, data))\n//            return 1;\n//    }\n//    #endif\n////    else if(options.data_source == \"tt\"){\n////        if(importTanksAndTemples(dir,data,options))\n////            return 1;\n////        options.ground_truth = 0;\n////    }\n////    #ifdef PCL\n////    else if(options.data_source == \"eth\"){\n////        if(importETH3D(dir,data)){\n////            cout << \"\\nERROR: in importETH3D()\" << endl;\n////            return 1;\n////        }\n////    }\n////    #endif\n//    else{\n//        cout << \"ERROR: not a valid reconstruction input\" << endl;\n//        return 1;\n//    }\n\n\n//    ///////////////////////////////////\n//    ///////// PREPROCESS DATA /////////\n//    ///////////////////////////////////\n//    if(!dir.transformation_file.empty()){\n//        // import translation matrix\n////        if(importTransformationMatrix(dir,data))\n////            return 1;\n//        if(applyTransformationMatrix(data))\n//            return 1;\n//    }\n//    // calc gt obb\n////    if(!options.gt_isclosed){\n////        cout << \"\\nMake bounding box of open GT for cropping input...\" << endl;\n////        assert(options.ground_truth);\n////        // get centroid of ground truth\n////        std::array<Point, 8> obb_points;\n////        CGAL::oriented_bounding_box(data.gt_poly,obb_points);\n////        double mx = 0, my = 0, mz = 0;\n////        for(const auto p : obb_points){\n////            mx+=p.x();\n////            my+=p.y();\n////            mz+=p.z();\n////        }\n////        data.gt_centroid = Point(mx/8,my/8,mz/8+1000);\n////        cout << \"\\t-ground truth centroid for ray tracing: \" << data.gt_centroid << \"-1000\" << endl;\n////        CGAL::make_hexahedron(obb_points[0], obb_points[1], obb_points[2], obb_points[3],\n////                              obb_points[4], obb_points[5], obb_points[6], obb_points[7], data.sm_obb);\n////        CGAL::Polygon_mesh_processing::triangulate_faces(data.sm_obb);\n\n////        clipWithBoundingBox(data.points,data.infos,data.sm_obb);\n\n////    }\n\n////    if(options.scale > 0.0)\n////        scalePointSet(dir, data, options.scale);\n\n//    if(options.scale > 0.0)\n//        standardizePointSet(dir, data, options.scale);\n\n////    if(options.scoring == \"_rt\")\n////        orderSensors(data);\n////    else\n////        cout << \"\\nSensors not ordered for ray-tracing\" << endl;\n\n//    if(exportO.cameras){\n//        dir.suffix = \"_cameras\";\n//        exportCameraCenter(dir, data);\n//    }\n//    // export the scanned points\n//    if(exportO.scan){\n//        dir.suffix = \"_scan\";\n//        exportPLY(dir, data.points, data.infos, exportO);\n//    }\n\n\n//    //////////////////////////////////////\n//    /////// DELAUNAY TRIANGULATION ///////\n//    //////////////////////////////////////\n//    if(options.Dt_epsilon > 0.0)\n//        makeAdaptiveDelaunayWithInfo(data, options.Dt_epsilon);\n//    else\n//        makeDelaunayWithInfo(data);\n\n//    if(options.labatut_sigma == -1.0 && (options.scoring == \"_rt\" || options.scoring == \"_clrt\"))\n//        options.labatut_sigma = pcaKNN(data.Dt);\n//    else{\n//        cout << \"\\nd parameter of Labatu set to \" << options.labatut_sigma << endl;\n//    }\n\n////    cout << \"Mean edge length after scaling: \" << calcMeanEdgeLength(data) << endl;\n\n\n\n\n\n////    // add camera points to delaunay\n////    typedef CGAL::Labeled_mesh_domain_3<EPICK> Mesh_domain;\n////    // Triangulation\n////    typedef CGAL::Mesh_triangulation_3<Mesh_domain,CGAL::Default,Concurrency_tag>::type Tr;\n////    typedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;\n////    // Criteria\n////    typedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;\n\n////    Mesh_domain domain(data.Dt);\n////    Mesh_criteria criteria();\n////    CGAL::refine_mesh_3(data.Dt, domain, criteria);\n\n\n\n\n//    ///////////////////////////////////\n//    /////// TETRAHEDRON SCORING ///////\n//    ///////////////////////////////////\n//    // make an index, necessary for graphExport e.g.\n//    options.make_global_cell_idx=1;\n//    indexDelaunay(data, options);\n//    // put score on cells\n//    if(options.scoring == \"_cs\"){\n//        if(options.gt_isclosed){\n//            if(labelObjectWithClosedGroundTruth(dir,data,options.number_of_points_per_cell))\n//                return 1;\n//        }\n//        else{\n//            if(labelObjectWithOpenGroundTruth(dir,data, options.number_of_points_per_cell))\n//                return 1;\n//        }\n//        #ifdef RECONBENCH\n//        else\n//            labelObjectWithImplicit(data, options.number_of_points_per_cell);\n//        #endif\n//    }\n//    else if(options.scoring == \"_csrt\"){\n//        auto rc = processing::RayCaster(data, options);\n//        if(options.gt_isclosed){\n//            if(labelObjectWithClosedGroundTruth(dir,data, options.number_of_points_per_cell))\n//                return 1;\n//        }\n//        else{\n//            if(labelObjectWithOpenGroundTruth(dir,data, options.number_of_points_per_cell))\n//                return 1;\n//        }\n//        rc.run(1);\n//    }\n//    else if(options.scoring == \"_rt\"){\n//        // NOTE: careful! the processing rayTracing does not have the cell_distance_pairs function\n//        // resulting in the fact that the ray cell edges will not be exported at all\n//        if(options.score_type == \"\")\n//            processing::rayTracing(data.Dt, options);\n//        else{\n//            auto rc = processing::RayCaster(data, options);\n//            rc.run(1);\n//        }\n//    }\n//    else if(options.scoring == \"_lrt\"){\n//        // this constructs the features which are exported to the cell ray graph,\n//        // important to note the difference between score, and features, where score is not used in any way in the learning.\n//        if(options.scale == 0.0)\n//            cout << \"\\nConsider turning on scaling with --sn, if your learning data is not yet scaled to a unit cube!\" << endl;\n//        learning::rayTracing(data.Dt, options);\n//        // this is only for making a reconstruction of a lrt, but has no influence on the features or the learning\n////        learning::aggregateScoreAndLabel(data.Dt);\n//    }\n//    else if(options.scoring == \"_lrtcs\"){\n//        learning::rayTracing(data.Dt, options);\n//        if(dir.gt_poly_file.substr(dir.gt_poly_file.length() - 3 ) == \"off\"){\n//            if(options.gt_isclosed){\n//                if(labelObjectWithClosedGroundTruth(dir,data, options.number_of_points_per_cell))\n//                    return 1;\n//            }\n//            else{\n//                if(labelObjectWithOpenGroundTruth(dir,data, options.number_of_points_per_cell))\n//                    return 1;\n//            }\n//        }\n//        #ifdef RECONBENCH\n//        if(dir.gt_poly_file.substr(dir.gt_poly_file.length() - 3 ) == \"mpu\"){\n//            labelObjectWithImplicit(data, options.number_of_points_per_cell);\n//        }\n//        #endif\n\n//    }\n//    else if(options.scoring == \"_cl\"){\n//        if(loadPrediction(dir, data, options))\n//            return 1;\n//    }\n//    else if(options.scoring == \"_clrt\"){\n//        auto rc = processing::RayCaster(data, options);\n//        if(loadPrediction(dir, data, options))\n//            return 1;\n//        rc.run(1);\n//    }\n//    else if(options.scoring == \"_clcs\"){\n//        if(options.gt_isclosed){\n//            if(labelObjectWithClosedGroundTruth(dir,data, options.number_of_points_per_cell))\n//                return 1;\n//        }\n//        else{\n//            if(labelObjectWithOpenGroundTruth(dir,data, options.number_of_points_per_cell))\n//                return 1;\n//        }\n//        if(loadPrediction(dir, data, options))\n//            return 1;\n//        // TODO: tweak the graphCut function to use unaries from cell.prediction_inside/outside but sv - binaries from cell.inside/outside_score\n\n//    }\n\n\n\n//    ////////////////////////////\n//    /////// OPTIMIZATION ///////\n//    ////////////////////////////\n//    if(options.optimization == 1){\n//        options.gco_iterations = -1;\n//        if(options.score_type == \"mine\" || options.scoring == \"_cl\" || options.scoring == \"_cs\" || options.scoring == \"_clcs\" || options.scoring == \"_lrtcs\")\n//            graphCutTet(data, options);\n//        else\n//            graphCutFacet(data,options);\n//    }\n//    else{\n//        cout << \"\\nLabel cells without optimization by taking max score\" << endl;\n//        cout << \"\\t-infinite cells will be labelled outside\" << endl;\n//        for(auto cit = data.Dt.all_cells_begin(); cit != data.Dt.all_cells_end(); cit++){\n//            if(data.Dt.is_infinite(cit)){\n//                cit->info().gc_label = 1;\n//                continue;\n//            }\n//            // this means untraversed cells and 50/50 cells will be labelled as inside\n//            cit->info().gc_label = cit->info().outside_score > cit->info().inside_score ? 1 : 0;\n//        }\n//    }\n\n//    ////////////////////////////\n//    ////////// EXPORT //////////\n//    ////////////////////////////\n\n\n//    //// export features and labels\n////    if(options.scoring == \"_lrtcs\" || options.scoring == \"_lrt\"){\n////        // check if labels directory exists, if not create it\n////        path lpath(dir.path);\n////        // this shitty problem here is not present on the laptop\n////        lpath /= string(\"gt\");\n////        if(!is_directory(lpath))\n////            create_directory(lpath);\n////        // export the features and labels\n////        exportGraph(dir, options, data.Dt);\n////    }\n\n\n\n//    // make new 3DT with old 3DT cell centers, attribute cell score to vertices\n\n\n////    #ifdef Open3D\n//////    Delaunay Dt;\n//////    Vertex_handle vh;\n//////    vertex_info vi;\n//////    Point p1,p2,p3,p4,centroid;\n//////    for(auto cit = data.Dt.finite_cells_begin(); cit != data.Dt.finite_cells_end(); cit++){\n//////        p1 = cit->vertex(0)->point();\n//////        p2 = cit->vertex(1)->point();\n//////        p3 = cit->vertex(2)->point();\n//////        p4 = cit->vertex(3)->point();\n//////        centroid = CGAL::centroid(p1,p2,p3,p4);\n//////        vh = Dt.insert(centroid);\n//////        vi.occupancy = cit->info().outside_score;\n//////        vh->info() = vi;\n//////    }\n//////    exportIsoSurface(dir, Dt, 0);\n//////    exportConvexHull(dir, Dt);\n\n////    if(exportO.isosurface)\n////        exportMITSurface(dir, data.Dt, 1, 0.5);\n\n////    #endif\n\n\n\n//    //// export interface\n//    if(exportO.interface)\n//        exportInterface(dir, data, options, exportO);\n\n//    #ifdef OpenMVS\n//    if(options.clean_mesh)\n//        omvsCleanMesh(dir,data);\n//    #endif\n\n////    if(exportO.coloredFacets)\n////        exportColoredFacets(dir, data.Dt, options.optimization);\n//    if(exportO.cellScore){\n//        exportCellCenter(dir, data.Dt);\n//        exportCellScore(dir, data.Dt);\n//    }\n//    if(exportO.convexHull){\n//        exportConvexHull(dir, data.Dt);\n//    }\n//    ////////// create surface mesh ////////////\n//    // set export options\n//    meshProcessingOptions mpOptions;\n//    mpOptions.try_to_close = options.try_to_close;\n//    mpOptions.try_to_make_manifold = options.try_to_make_manifold;\n//    mpOptions.number_of_components_to_keep = options.number_of_components_to_keep;\n//    mpOptions.factor_for_removing_large_faces = options.factor_for_removing_large_faces;\n//    if(exportO.mesh){\n//        dir.suffix = \"_mesh\";\n//        createSurfaceMesh(data, mpOptions);\n//        exportPLY(dir, data.smesh);\n//    }\n\n\n//    ////////// sample surface mesh //////////\n//    if(exportO.sampling){\n//        data.points.clear();\n//        data.infos.clear();\n//        if(data.smesh.is_empty()){\n//            createSurfaceMesh(data, mpOptions);\n//        }\n//        sampleMesh(data, exportO);\n//        dir.suffix = \"_sampled\";\n//        // turn of color and sensor_vec export, because mesh sampling obviously does not have that\n//        exportO.sensor_vec = false;\n//        exportO.sensor_position = false;\n//        exportO.color = false;\n//        exportO.normals = false;\n//        exportPLY(dir, data.points, data.infos, exportO);\n//    }\n\n//    if(options.evaluate_mesh){\n//        if(data.smesh.is_empty()){\n//            createSurfaceMesh(data, mpOptions);\n//        }\n//        if(options.ground_truth){\n//            double iou;\n//            if(calcIOU(data, exportO.sampling_method_option, iou))\n//                return 1;\n//            printMeshEvaluation(dir,data,iou);\n//        }\n//        else\n//            printMeshEvaluation(dir,data,-1.0);\n\n//    }\n\n//    return 0;\n//}\n\n\n\n//int main(int argc, char const *argv[]){\n\n\n//    cliParser ip(\"clf\");\n//    if(ip.parse(argc, argv))\n//        return 1;\n//    if(ip.getInput())\n//        return 1;\n//    if(ip.getOutput())\n//        return 1;\n//    if(ip.getLabatut())\n//        return 1;\n\n//    auto start = std::chrono::high_resolution_clock::now();\n//    cout << \"\\n-----DELAUNAY-GRAPH-CUT-BASED SURFACE RECONSTRUCTION-----\" << endl;\n//    cout << \"\\nWorking dir set to:\\n\\t-\" << ip.dh.path << endl;\n\n//    dataHolder data;\n//    if(surfaceReconstruction(ip.dh, data, ip.ro, ip.eo))\n//        return 1;\n\n//    auto stop = std::chrono::high_resolution_clock::now();\n//    auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);\n//    cout << \"\\n-----DELAUNAY-GRAPH-CUT-BASED SURFACE RECONSTRUCTION FINISHED in \"<< duration.count() << \"s -----\\n\" << endl;\n\n//    return 0;\n\n//}\n\n\n\n", "meta": {"hexsha": "1cc17ca4cf1e95cd71f90c6b62229450f58318ac", "size": 32805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/exe/sure.cpp", "max_stars_repo_name": "raphaelsulzer/mesh-tools", "max_stars_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-24T03:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T03:39:05.000Z", "max_issues_repo_path": "src/exe/sure.cpp", "max_issues_repo_name": "raphaelsulzer/mesh-tools", "max_issues_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-24T06:59:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T01:25:09.000Z", "max_forks_repo_path": "src/exe/sure.cpp", "max_forks_repo_name": "raphaelsulzer/mesh-tools", "max_forks_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_forks_repo_licenses": ["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.715496368, "max_line_length": 476, "alphanum_fraction": 0.5477823503, "num_tokens": 8506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.1978685505345122}}
{"text": "#include \"./manual_dice.h\"\n\n#include \"./dice_roller.h\"\n#include \"../cqsdk/utils/base64.h\"\n\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n\nnamespace dicebot::manual{\n\n    std::regex regex_filter_manual_dice_part(\"^(?:\\\\+)?(\\\\d+)?[dD](\\\\d+)\");\n\n    manual_dice::manual_dice(){\n        i_sum_result = 0; \n    }\n\n    manual_dice::operator bool() const noexcept{\n        return this->status == roll::roll_status::FINISHED;\n    }\n\n    manual_dice::manual_dice(const std::string & source){\n        i_sum_result = 0;\n        this->add(source);\n    }\n\n    void manual_dice::roll(const std::string & source){\n        try{\n            this->status = roll::roll_status::UNINITIALIZED;\n            unsigned int target = std::stoi(source) - 1;\n            if(target >= this->size()){ \n                this->status = roll::roll_status::FINISHED;\n                return; \n            }\n            else if(target < 0) return;\n            vec_mdice::iterator iter_list = this->begin() + target;\n            int i_face_of_die = (*iter_list).first;\n            roll::dice_roll dr;\n            roll::roll_base(dr, 1, i_face_of_die);\n            if(dr){\n                this->i_sum_result -= (*iter_list).second;\n                (*iter_list).second = dr.summary;\n                this->i_sum_result += dr.summary;\n            }\n            else{\n                this->status = dr.status;\n                return;\n            }\n            this->status = roll::roll_status::FINISHED;\n        }\n        catch (const std::invalid_argument& ia){\n            #ifdef _DEBUG\n                logger::log(\"manual_dice\", ia.what());\n            #endif\n            this->status = roll::roll_status::DICE_NOT_AVAILABLE;\n        }\n    }\n\n    void manual_dice::kill(const std::string & source){\n        this->status = roll::roll_status::UNINITIALIZED;\n        try{\n            unsigned int target = std::stoi(source) -1;\n            if(target >= this->size()){\n                this->status = roll::roll_status::FINISHED;\n                return;\n            }\n            else if(target < 0) return;\n            vec_mdice::iterator iter_list = (this->begin()) + target;\n            i_sum_result -= (*iter_list).second;\n            this->erase((iter_list));\n            if(this->status == roll::roll_status::UNINITIALIZED) this->status = roll::roll_status::FINISHED;\n        }\n        catch (const std::invalid_argument& ia){\n            #ifdef _DEBUG\n                logger::log(\"manual_dice\", ia.what());\n            #endif\n            this->status = roll::roll_status::DICE_NOT_AVAILABLE;\n        }\n    }\n\n    void manual_dice::add(const std::string & source){\n        std::regex regex_manual_part(\"^(?:\\\\+)?(\\\\d+)?[dD](\\\\d+)\");\n        try{\n            this->status = roll::roll_status::DICE_NOT_AVAILABLE;\n            std::string str_source_copy(source);\n            std::smatch smatch_single;\n            while(str_source_copy.size() > 0){\n\n                std::regex_search(str_source_copy, smatch_single, regex_manual_part);\n                if(smatch_single.begin() == smatch_single.end()) return;\n                int i_dice = 1;\n                if(smatch_single[1].matched) i_dice = std::stoi(smatch_single[1].str());\n                int i_face = std::stoi(smatch_single[2].str());\n\n                if(!CHECK_LIMITS((this->size() + i_dice),i_face)){\n                    this->status = roll::roll_status::TOO_MANY_DICE;\n                    return;\n                }\n\n                for(int i_iter = 0; i_iter < i_dice; i_iter++){\n                    roll::dice_roll dr;\n                    roll::roll_base(dr, 1, i_face);\n                    if(dr){\n                        this->push_back(pair_mdice(i_face, dr.summary));\n                        this->i_sum_result += dr.summary;\n                    }\n                    else{\n                        this->status = dr.status;\n                        return;\n                    }\n                }\n                str_source_copy.assign(smatch_single.suffix().str());\n            }\n            this->status = roll::roll_status::FINISHED;\n        }\n        catch (const std::invalid_argument& ia){\n            #ifdef _DEBUG\n                logger::log(\"manual_dice\", ia.what());\n            #endif\n            this->status = roll::roll_status::DICE_NOT_AVAILABLE;\n        }\n    }\n\n    void manual_dice::killall(){\n        this->status = roll::roll_status::UNINITIALIZED;\n        try{\n            this->clear();\n            this->i_sum_result = 0;\n            if(this->status == roll::roll_status::UNINITIALIZED) this->status = roll::roll_status::FINISHED;\n        }\n        catch(const std::invalid_argument& ia){\n            #ifdef _DEBUG\n                logger::log(\"manual_dice\", ia.what());\n            #endif\n            this->status = roll::roll_status::DICE_NOT_AVAILABLE;\n        }\n    }\n\n    std::string manual_dice::encode() const{\n        ostrs strs(ostrs::ate);\n        boost::archive::binary_oarchive oa(strs);\n        oa << this->size();\n        auto iter_list = this->cbegin();\n        for(; iter_list != this->cend(); iter_list++){\n            oa << ((*iter_list).first);\n            oa << ((*iter_list).second);\n        }\n        return cq::utils::base64::encode((const unsigned char *)(strs.str().c_str()),strs.str().size());\n    }\n\n    void manual_dice::decode(std::string & source){\n        this->clear();\n        std::string source_copy(source);\n        source_copy = cq::utils::base64::decode(source_copy);\n        std::istringstream iss(source_copy);\n        boost::archive::binary_iarchive ia(iss);\n\n        this->i_sum_result = 0;\n        int len = 0;\n        ia >> len;\n        for(int i_iter = 0; i_iter < len; i_iter++){\n            int first = 0;\n            ia >> first;\n            int second = 0;\n            ia >> second;\n            this->i_sum_result += second;\n            this->push_back(pair_mdice(first, second));\n        }\n    }\n\n    std::string manual_dice::str(){\n        ostrs ostrs_result(ostrs::ate);\n        int i_sum_result = 0;\n        vec_mdice::iterator iter_list = this->begin();\n\n        bool hasDice = iter_list != this->end();\n        for(; iter_list != this->end(); iter_list++){\n            if(iter_list != this->begin()){\n                ostrs_result << \" + \";\n            }\n            ostrs_result << (*iter_list).second << \"(\" << (*iter_list).first << \")\";\n            i_sum_result += (*iter_list).second;\n        }\n        if(!hasDice) ostrs_result << u8\"\u6ca1\u6709\u9ab0\u5b50\u4e86\";\n        else ostrs_result << \" = \" << i_sum_result;\n        return ostrs_result.str();\n    }\n}", "meta": {"hexsha": "d9986c20115d9ea38310af0452b12562a173b1ff", "size": 6584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dicebot/manual_dice.cpp", "max_stars_repo_name": "Rainy12138/coolq-dicebot", "max_stars_repo_head_hexsha": "225d1031f55a3db50d8df9a76a08d29bde8591a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T01:27:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T01:27:30.000Z", "max_issues_repo_path": "src/dicebot/manual_dice.cpp", "max_issues_repo_name": "Rainy12138/coolq-dicebot", "max_issues_repo_head_hexsha": "225d1031f55a3db50d8df9a76a08d29bde8591a8", "max_issues_repo_licenses": ["MIT"], "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/dicebot/manual_dice.cpp", "max_forks_repo_name": "Rainy12138/coolq-dicebot", "max_forks_repo_head_hexsha": "225d1031f55a3db50d8df9a76a08d29bde8591a8", "max_forks_repo_licenses": ["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.2085561497, "max_line_length": 108, "alphanum_fraction": 0.5148845687, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.19780932335418258}}
{"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#ifndef QCTOOL_INTENSITY_DISTRIBUTION_COMPUTATION_HPP\n#define QCTOOL_INTENSITY_DISTRIBUTION_COMPUTATION_HPP\n\n#include <Eigen/Core>\n#include \"metro/mean_and_variance.hpp\"\n#include \"components/SampleSummaryComponent/SampleSummaryComputation.hpp\"\n\nnamespace sample_stats {\n\tstruct IntensityDistributionComputation: public SampleSummaryComputation\n\t{\n\t\tIntensityDistributionComputation() ;\n\t\tvoid accumulate( genfile::VariantIdentifyingData const&, Genotypes const&, genfile::VariantDataReader& ) ;\n\t\tvoid compute( int sample, ResultCallback ) ;\n\t\tstd::string get_summary( std::string const& prefix = \"\", std::size_t column_width = 20 ) const ;\n\tprivate:\n\t\tdouble const m_call_threshhold ;\n\t\ttypedef Eigen::MatrixXd IntensityMatrix ;\n\t\tIntensityMatrix m_intensities ;\n\t\tIntensityMatrix m_nonmissingness ;\n\t\tIntensityMatrix m_intensities_by_genotype ;\n\t\tIntensityMatrix m_nonmissingness_by_genotype ;\n\n\t\tstd::size_t m_number_of_samples ;\n\t\tstd::size_t m_snp_index ;\n\t\tmetro::OnlineElementwiseMeanAndVariance m_accumulator ;\n\t\tstd::vector< metro::OnlineElementwiseMeanAndVariance > m_accumulator_by_genotype ;\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "b65dab44b60d65d7ef22af2760cdae1aa3534107", "size": 1335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/SampleSummaryComponent/include/components/SampleSummaryComponent/IntensityDistributionComputation.hpp", "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/SampleSummaryComponent/include/components/SampleSummaryComponent/IntensityDistributionComputation.hpp", "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/SampleSummaryComponent/include/components/SampleSummaryComponent/IntensityDistributionComputation.hpp", "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": 36.0810810811, "max_line_length": 108, "alphanum_fraction": 0.7902621723, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1977810586773576}}
{"text": "#include <disposer/core/generate_module.hpp>\n#include <disposer/core/directory.hpp>\n\n#define BOOST_TEST_MODULE disposer module_register\n#include <boost/test/included/unit_test.hpp>\n\n\nusing namespace disposer;\n\nusing namespace disposer::literals;\nusing namespace std::literals::string_view_literals;\n\n\nusing type_index = boost::typeindex::type_index;\n\ntemplate < std::size_t D >\nusing ic = index_component< D >;\n\ntemplate < typename ... T > struct morph{};\n\n\nBOOST_AUTO_TEST_CASE(register_0){\n\tdirectory dir;\n\n\tstruct exec{\n\t\tconstexpr void operator()()const{}\n\t};\n\n\tconstexpr module_init_fn state_dummy{};\n\tconstexpr exec_fn exec_dummy{exec{}};\n\n\t{\n\t\tauto fn = generate_module(\"description\",\n\t\t\tmodule_configure{}, state_dummy, exec_dummy);\n\t\tfn(\"register_0\", dir.declarant());\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(register_1){\n\tdirectory dir;\n\n\tconstexpr auto list = dimension_list{\n\t\t\tdimension_c< double, char, float >\n\t\t};\n\n\tstruct exec{\n\t\tconstexpr void operator()()const{}\n\t};\n\n\tconstexpr module_init_fn state_dummy{};\n\tconstexpr exec_fn exec_dummy{exec{}};\n\n\tauto const generate_fn = [=](std::size_t i){\n\t\t\treturn generate_module(\"description\", list,\n\t\t\t\tmodule_configure{\n\t\t\t\t\tset_dimension_fn([i](auto const&){\n\t\t\t\t\t\treturn solved_dimensions{index_component< 0 >{i}};\n\t\t\t\t\t})\n\t\t\t\t}, state_dummy, exec_dummy);\n\t\t};\n\n\t{\n\t\tauto fn = generate_fn(0);\n\t\tfn(\"register_1_1\", dir.declarant());\n\t}\n\t{\n\t\tauto fn = generate_fn(1);\n\t\tfn(\"register_1_2\", dir.declarant());\n\t}\n\t{\n\t\tauto fn = generate_fn(2);\n\t\tfn(\"register_1_3\", dir.declarant());\n\t}\n}\n", "meta": {"hexsha": "9010538ad463ae2d8a44ab5b083a1010df1be065", "size": 1535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/module_register.cpp", "max_stars_repo_name": "bebuch/disposer", "max_stars_repo_head_hexsha": "8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105", "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/module_register.cpp", "max_issues_repo_name": "bebuch/disposer", "max_issues_repo_head_hexsha": "8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2017-03-10T10:45:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-05T19:38:58.000Z", "max_forks_repo_path": "test/module_register.cpp", "max_forks_repo_name": "bebuch/disposer", "max_forks_repo_head_hexsha": "8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-02-21T06:45:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-18T11:22:33.000Z", "avg_line_length": 20.4666666667, "max_line_length": 56, "alphanum_fraction": 0.7100977199, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702584}}
{"text": "//=======================================================================\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#ifndef BOOST_GRAPH_DIJKSTRA_HPP\n#define BOOST_GRAPH_DIJKSTRA_HPP\n\n#include <functional>\n#include <boost/limits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/relax.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/graph/exception.hpp>\n#include <boost/pending/relaxed_heap.hpp>\n\n#ifdef BOOST_GRAPH_DIJKSTRA_TESTING\n#  include <boost/pending/mutable_queue.hpp>\n#endif // BOOST_GRAPH_DIJKSTRA_TESTING\n\nnamespace boost {\n\n#ifdef BOOST_GRAPH_DIJKSTRA_TESTING\n  static bool dijkstra_relaxed_heap = true;\n#endif\n\n  template <class Visitor, class Graph>\n  struct DijkstraVisitorConcept {\n    void constraints() {\n      function_requires< CopyConstructibleConcept<Visitor> >();\n      vis.initialize_vertex(u, g);\n      vis.discover_vertex(u, g);\n      vis.examine_vertex(u, g);\n      vis.examine_edge(e, g);\n      vis.edge_relaxed(e, g);\n      vis.edge_not_relaxed(e, g);\n      vis.finish_vertex(u, g);\n    }\n    Visitor vis;\n    Graph g;\n    typename graph_traits<Graph>::vertex_descriptor u;\n    typename graph_traits<Graph>::edge_descriptor e;\n  };\n\n  template <class Visitors = null_visitor>\n  class dijkstra_visitor : public bfs_visitor<Visitors> {\n  public:\n    dijkstra_visitor() { }\n    dijkstra_visitor(Visitors vis)\n      : bfs_visitor<Visitors>(vis) { }\n\n    template <class Edge, class Graph>\n    void edge_relaxed(Edge e, Graph& g) {\n      invoke_visitors(this->m_vis, e, g, on_edge_relaxed());\n    }\n    template <class Edge, class Graph>\n    void edge_not_relaxed(Edge e, Graph& g) {\n      invoke_visitors(this->m_vis, e, g, on_edge_not_relaxed());\n    }\n  private:\n    template <class Edge, class Graph>\n    void tree_edge(Edge u, Graph& g) { }\n  };\n  template <class Visitors>\n  dijkstra_visitor<Visitors>\n  make_dijkstra_visitor(Visitors vis) {\n    return dijkstra_visitor<Visitors>(vis);\n  }\n  typedef dijkstra_visitor<> default_dijkstra_visitor;\n\n  namespace detail {\n\n    template <class UniformCostVisitor, class UpdatableQueue,\n      class WeightMap, class PredecessorMap, class DistanceMap,\n      class BinaryFunction, class BinaryPredicate>\n    struct dijkstra_bfs_visitor\n    {\n      typedef typename property_traits<DistanceMap>::value_type D;\n\n      dijkstra_bfs_visitor(UniformCostVisitor vis, UpdatableQueue& Q,\n                           WeightMap w, PredecessorMap p, DistanceMap d,\n                           BinaryFunction combine, BinaryPredicate compare,\n                           D zero)\n        : m_vis(vis), m_Q(Q), m_weight(w), m_predecessor(p), m_distance(d),\n          m_combine(combine), m_compare(compare), m_zero(zero)  { }\n\n      template <class Edge, class Graph>\n      void tree_edge(Edge e, Graph& g) {\n        m_decreased = relax(e, g, m_weight, m_predecessor, m_distance,\n                            m_combine, m_compare);\n        if (m_decreased)\n          m_vis.edge_relaxed(e, g);\n        else\n          m_vis.edge_not_relaxed(e, g);\n      }\n      template <class Edge, class Graph>\n      void gray_target(Edge e, Graph& g) {\n        m_decreased = relax(e, g, m_weight, m_predecessor, m_distance,\n                            m_combine, m_compare);\n        if (m_decreased) {\n          m_Q.update(target(e, g));\n          m_vis.edge_relaxed(e, g);\n        } else\n          m_vis.edge_not_relaxed(e, g);\n      }\n\n      template <class Vertex, class Graph>\n      void initialize_vertex(Vertex /*u*/, Graph& /*g*/) { }\n      template <class Edge, class Graph>\n      void non_tree_edge(Edge, Graph&) { }\n      template <class Vertex, class Graph>\n      void discover_vertex(Vertex u, Graph& g) { m_vis.discover_vertex(u, g); }\n      template <class Vertex, class Graph>\n      void examine_vertex(Vertex u, Graph& g) { m_vis.examine_vertex(u, g); }\n      template <class Edge, class Graph>\n      void examine_edge(Edge e, Graph& g) {\n        if (m_compare(get(m_weight, e), m_zero))\n          throw negative_edge();\n        m_vis.examine_edge(e, g);\n      }\n      template <class Edge, class Graph>\n      void black_target(Edge, Graph&) { }\n      template <class Vertex, class Graph>\n      void finish_vertex(Vertex u, Graph& g) { m_vis.finish_vertex(u, g); }\n\n      UniformCostVisitor m_vis;\n      UpdatableQueue& m_Q;\n      WeightMap m_weight;\n      PredecessorMap m_predecessor;\n      DistanceMap m_distance;\n      BinaryFunction m_combine;\n      BinaryPredicate m_compare;\n      bool m_decreased;\n      D m_zero;\n    };\n\n  } // namespace detail\n\n  // Call breadth first search with default color map.\n  template <class VertexListGraph, class DijkstraVisitor,\n            class PredecessorMap, class DistanceMap,\n            class WeightMap, class IndexMap, class Compare, class Combine,\n            class DistZero>\n  inline void\n  dijkstra_shortest_paths_no_init\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n     IndexMap index_map,\n     Compare compare, Combine combine, DistZero zero,\n     DijkstraVisitor vis)\n  {\n    std::vector<default_color_type> color(num_vertices(g));\n    default_color_type c = white_color;\n    dijkstra_shortest_paths_no_init( g, s, predecessor, distance, weight,\n      index_map, compare, combine, zero, vis,\n        make_iterator_property_map(&color[0], index_map, c));\n  }\n\n  // Call breadth first search\n  template <class VertexListGraph, class DijkstraVisitor,\n            class PredecessorMap, class DistanceMap,\n            class WeightMap, class IndexMap, class Compare, class Combine,\n            class DistZero, class ColorMap>\n  inline void\n  dijkstra_shortest_paths_no_init\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n     IndexMap index_map,\n     Compare compare, Combine combine, DistZero zero,\n     DijkstraVisitor vis, ColorMap color)\n  {\n    typedef indirect_cmp<DistanceMap, Compare> IndirectCmp;\n    IndirectCmp icmp(distance, compare);\n\n    typedef typename graph_traits<VertexListGraph>::vertex_descriptor Vertex;\n\n#ifdef BOOST_GRAPH_DIJKSTRA_TESTING\n    if (!dijkstra_relaxed_heap) {\n      typedef mutable_queue<Vertex, std::vector<Vertex>, IndirectCmp, IndexMap>\n        MutableQueue;\n\n      MutableQueue Q(num_vertices(g), icmp, index_map);\n\n      detail::dijkstra_bfs_visitor<DijkstraVisitor, MutableQueue, WeightMap,\n        PredecessorMap, DistanceMap, Combine, Compare>\n      bfs_vis(vis, Q, weight, predecessor, distance, combine, compare, zero);\n\n      breadth_first_visit(g, s, Q, bfs_vis, color);\n      return;\n    }\n#endif // BOOST_GRAPH_DIJKSTRA_TESTING\n\n    typedef relaxed_heap<Vertex, IndirectCmp, IndexMap> MutableQueue;\n\n    MutableQueue Q(num_vertices(g), icmp, index_map);\n\n    detail::dijkstra_bfs_visitor<DijkstraVisitor, MutableQueue, WeightMap,\n      PredecessorMap, DistanceMap, Combine, Compare>\n        bfs_vis(vis, Q, weight, predecessor, distance, combine, compare, zero);\n\n    breadth_first_visit(g, s, Q, bfs_vis, color);\n  }\n\n  // Initialize distances and call breadth first search with default color map\n  template <class VertexListGraph, class DijkstraVisitor,\n            class PredecessorMap, class DistanceMap,\n            class WeightMap, class IndexMap, class Compare, class Combine,\n            class DistInf, class DistZero>\n  inline void\n  dijkstra_shortest_paths\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n     IndexMap index_map,\n     Compare compare, Combine combine, DistInf inf, DistZero zero,\n     DijkstraVisitor vis)\n  {\n    std::vector<default_color_type> color(num_vertices(g));\n    default_color_type c = white_color;\n    dijkstra_shortest_paths(g, s, predecessor, distance, weight, index_map,\n                            compare, combine, inf, zero, vis,\n                            make_iterator_property_map(&color[0], index_map,\n                                                       c));\n  }\n\n  // Initialize distances and call breadth first search\n  template <class VertexListGraph, class DijkstraVisitor,\n            class PredecessorMap, class DistanceMap,\n            class WeightMap, class IndexMap, class Compare, class Combine,\n            class DistInf, class DistZero, class ColorMap>\n  inline void\n  dijkstra_shortest_paths\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n     IndexMap index_map,\n     Compare compare, Combine combine, DistInf inf, DistZero zero,\n     DijkstraVisitor vis, ColorMap color)\n  {\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n    typename graph_traits<VertexListGraph>::vertex_iterator ui, ui_end;\n    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n      vis.initialize_vertex(*ui, g);\n      put(distance, *ui, inf);\n      put(predecessor, *ui, *ui);\n      put(color, *ui, Color::white());\n    }\n    put(distance, s, zero);\n\n    dijkstra_shortest_paths_no_init(g, s, predecessor, distance, weight,\n                            index_map, compare, combine, zero, vis, color);\n  }\n\n  namespace detail {\n\n    // Handle defaults for PredecessorMap and\n    // Distance Compare, Combine, Inf and Zero\n    template <class VertexListGraph, class DistanceMap, class WeightMap,\n              class IndexMap, class Params, class ColorMap>\n    inline void\n    dijkstra_dispatch2\n      (const VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s,\n       DistanceMap distance, WeightMap weight, IndexMap index_map,\n       const Params& params, ColorMap color)\n    {\n      // Default for predecessor map\n      dummy_property_map p_map;\n\n      typedef typename property_traits<DistanceMap>::value_type D;\n      dijkstra_shortest_paths\n        (g, s,\n         choose_param(get_param(params, vertex_predecessor), p_map),\n         distance, weight, index_map,\n         choose_param(get_param(params, distance_compare_t()),\n                      std::less<D>()),\n         choose_param(get_param(params, distance_combine_t()),\n                      closed_plus<D>()),\n         choose_param(get_param(params, distance_inf_t()),\n                      (std::numeric_limits<D>::max)()),\n         choose_param(get_param(params, distance_zero_t()),\n                      D()),\n         choose_param(get_param(params, graph_visitor),\n                      make_dijkstra_visitor(null_visitor())),\n         color);\n    }\n\n    template <class VertexListGraph, class DistanceMap, class WeightMap,\n              class IndexMap, class Params, class ColorMap>\n    inline void\n    dijkstra_dispatch1\n      (const VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s,\n       DistanceMap distance, WeightMap weight, IndexMap index_map,\n       const Params& params, ColorMap color)\n    {\n      // Default for distance map\n      typedef typename property_traits<WeightMap>::value_type D;\n      typename std::vector<D>::size_type\n        n = is_default_param(distance) ? num_vertices(g) : 1;\n      std::vector<D> distance_map(n);\n\n      // Default for color map\n      typename std::vector<default_color_type>::size_type\n        m = is_default_param(color) ? num_vertices(g) : 1;\n      std::vector<default_color_type> color_map(m);\n\n      detail::dijkstra_dispatch2\n        (g, s, choose_param(distance, make_iterator_property_map\n                            (distance_map.begin(), index_map,\n                             distance_map[0])),\n         weight, index_map, params,\n         choose_param(color, make_iterator_property_map\n                      (color_map.begin(), index_map,\n                       color_map[0])));\n    }\n  } // namespace detail\n\n  // Named Parameter Variant\n  template <class VertexListGraph, class Param, class Tag, class Rest>\n  inline void\n  dijkstra_shortest_paths\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     const bgl_named_params<Param,Tag,Rest>& params)\n  {\n    // Default for edge weight and vertex index map is to ask for them\n    // from the graph.  Default for the visitor is null_visitor.\n    detail::dijkstra_dispatch1\n      (g, s,\n       get_param(params, vertex_distance),\n       choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n       choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\n       params,\n       get_param(params, vertex_color));\n  }\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_DIJKSTRA_HPP\n", "meta": {"hexsha": "243b17f752bca872f08e5b23fe67c799698a5f98", "size": 13156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/dijkstra_shortest_paths.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": 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/dijkstra_shortest_paths.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": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/miniBoost/boost/graph/dijkstra_shortest_paths.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": 37.8045977011, "max_line_length": 79, "alphanum_fraction": 0.6692763758, "num_tokens": 3046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.1977009496470258}}
{"text": "//****************************************************************************\n// (c) 2008, 2009 by the openOR Team\n//****************************************************************************\n// The contents of this file are available under the GPL v2.0 license\n// or under the openOR comercial license. see\n//   /Doc/openOR_free_license.txt or\n//   /Doc/openOR_comercial_license.txt\n// for Details.\n//****************************************************************************\n//! OPENOR_INTERFACE_FILE(openOR_core)\n//****************************************************************************\n/**\n * @file\n * @author Christian Winne\n * @ingroup openOR_core\n */\n\n#ifndef openOR_core_Math_matrixconcept_hpp\n#define openOR_core_Math_matrixconcept_hpp\n\n#include <boost/type_traits/add_const.hpp>\n#include <boost/type_traits/is_const.hpp>\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/concept/usage.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/math/quaternion.hpp>\n\n#include <openOR/Math/utilities.hpp>\n#include <openOR/Math/traits.hpp>\n#include <openOR/Math/vector.hpp>\n#include <openOR/Math/ublasmatrix.hpp>\n#include <openOR/Math/ublasvector.hpp>\n\n\nnamespace openOR {\n   namespace Math {\n\n      template <int I, int J, typename P>\n         typename if_const < P,\n                     typename MatrixTraits<typename boost::remove_const<P>::type>::Access::ConstAccessType,\n                     typename MatrixTraits<typename boost::remove_const<P>::type>::Access::AccessType > \n      ::type get(P& p) {\n         return MatrixTraits<typename boost::remove_const<P>::type>::Access::template get<I, J>(p);\n      }\n\n\n      namespace Impl {\n\n\n         template < class Mat,\n         int BeginRow = 0,\n         int EndRow = MatrixTraits<Mat>::RowDimension::value,\n         int BeginCol = 0,\n         int EndCol = MatrixTraits<Mat>::ColDimension::value >\n         class MatrixCompileTimeIterator {\n               static const int SizeRow = EndRow - BeginRow;\n               static const int SizeCol = EndCol - BeginCol;\n\n            public:\n\n               template<template<class, int, int> class Op>\n               inline void apply() const {\n                  BOOST_MPL_ASSERT((boost::mpl::less_equal<boost::mpl::int_<BeginRow>, boost::mpl::int_<EndRow> >));\n                  BOOST_MPL_ASSERT((boost::mpl::less_equal<boost::mpl::int_<BeginCol>, boost::mpl::int_<EndCol> >));\n                  Apply0<0, SizeRow * SizeCol, Op>()();\n               }\n\n               template<template<class, class, int, int> class Op, class Mat2>\n               inline void apply(Mat& mat, const Mat2& mat2) {\n                  BOOST_MPL_ASSERT((boost::mpl::less_equal<boost::mpl::int_<BeginRow>, boost::mpl::int_<EndRow> >));\n                  BOOST_MPL_ASSERT((boost::mpl::less_equal<boost::mpl::int_<BeginCol>, boost::mpl::int_<EndCol> >));\n                  Apply2<0, SizeRow * SizeCol, Op, Mat2>()(mat, mat2);\n               }\n\n               template<template <class, int, int> class Op, typename Result, template<class> class Reducer>\n               inline Result reduce(const Mat& mat) const {\n                  BOOST_MPL_ASSERT((boost::mpl::less<boost::mpl::int_<BeginRow>, boost::mpl::int_<EndRow> >));\n                  BOOST_MPL_ASSERT((boost::mpl::less<boost::mpl::int_<BeginCol>, boost::mpl::int_<EndCol> >));\n                  return Reduce1 < 0, SizeRow * SizeCol - 1, Op, Result, Reducer > ()(mat);\n               }\n\n               template<template <class, class, int, int> class Op, class Mat2, typename Result, template<class> class Reducer>\n               inline Result reduce(const Mat& mat, const Mat2& mat2) const {\n                  BOOST_MPL_ASSERT((boost::mpl::less<boost::mpl::int_<BeginRow>, boost::mpl::int_<EndRow> >));\n                  BOOST_MPL_ASSERT((boost::mpl::less<boost::mpl::int_<BeginCol>, boost::mpl::int_<EndCol> >));\n                  return Reduce2 < 0, SizeRow * SizeCol - 1, Op, Mat2, Result, Reducer > ()(mat, mat2);\n               }\n\n            private:\n\n               template<int I, int Count, template<class, int, int> class Op>\n               struct Apply0 {\n                  inline void operator()() const {\n                     Op < Mat, BeginRow + (I % SizeRow), BeginCol + (I / SizeRow) > ()();\n                     Apply0 < I + 1, Count, Op > ()();\n                  }\n               };\n\n\n               template<int Count, template<class, int, int> class Op>\n               struct Apply0<Count, Count, Op> {\n                  inline void operator()() const {}\n               };\n\n\n               template<int I, int Count, template<class, class, int, int> class Op, class Mat2>\n               struct Apply2 {\n                  inline void operator()(Mat& mat, const Mat2& mat2) const {\n                     Op < Mat, Mat2, BeginRow + (I % SizeRow), BeginCol + (I / SizeRow) > ()(mat, mat2);\n                     Apply2 < I + 1, Count, Op, Mat2 > ()(mat, mat2);\n                  }\n               };\n\n\n               template<int Count, template<class, class, int, int> class Op, class Mat2>\n               struct Apply2<Count, Count, Op, Mat2> {\n                  inline void operator()(Mat& mat, const Mat2& mat2) const {}\n               };\n\n\n               template<int I, int Count, template <class, int, int> class Op, typename Result, template<class> class Reducer>\n               struct Reduce1 {\n                  inline Result operator()(const Mat& mat) const {\n                     return Reducer<Result>()(Op < Mat, BeginRow + (I % SizeRow), BeginCol + (I / SizeRow) > ()(mat),\n                                              Reduce1 < I + 1, Count, Op, Result, Reducer > ()(mat));\n                  }\n               };\n\n\n               template<int Count, template <class, int, int> class Op, typename Result, template<class> class Reducer>\n               struct Reduce1<Count, Count, Op, Result, Reducer> {\n                  inline Result operator()(const Mat& mat) {\n                     return Op < Mat, BeginRow + (Count % SizeRow), BeginCol + (Count / SizeRow) > ()(mat);\n                  }\n               };\n\n\n               template<int I, int Count, template <class, class, int, int> class Op, class Mat2, typename Result, template<class> class Reducer>\n               struct Reduce2 {\n                  inline Result operator()(const Mat& mat, const Mat2& mat2) {\n                     return Reducer<Result>()(Op < Mat, Mat2, BeginRow + (I % SizeRow), BeginCol + (I / SizeRow) > ()(mat, mat2),\n                                              Reduce2 < I + 1, Count, Op, Mat2, Result, Reducer > ()(mat, mat2));\n                  }\n               };\n\n               template<int Count, template <class, class, int, int> class Op, class Mat2, typename Result, template<class> class Reducer>\n               struct Reduce2<Count, Count, Op, Mat2, Result, Reducer> {\n                  inline Result operator()(const Mat& mat, const Mat2& mat2) {\n                     return Op < Mat, Mat2, BeginRow + (Count % SizeRow), BeginCol + (Count / SizeRow) > ()(mat, mat2);\n                  }\n               };\n\n         };\n\n      }\n\n\n      namespace Concept {\n\n         template <typename Type>\n         class ConstMatrix {\n            private:\n\n               BOOST_MPL_ASSERT((typename MatrixTraits<Type>::IsMatrix));\n\n               typedef typename MatrixTraits<Type>::ValueType ValueType;\n               typedef typename MatrixTraits<Type>::RowVectorType RowVectorType;\n               typedef typename MatrixTraits<Type>::ColVectorType ColVectorType;\n               enum { ROW_DIMENSION = MatrixTraits<Type>::RowDimension::value,\n                      COL_DIMENSION = MatrixTraits<Type>::ColDimension::value\n                 };\n\n\n               template <class M, int I, int J>\n               struct AccessCheck {\n                  inline void operator()() const {\n                     const M* p = 0;\n                     typename MatrixTraits<M>::ValueType val(Math::get<I, J>(*p));\n                     (void)sizeof(val); // To avoid \"unused variable\" warnings\n                  }\n               };\n\n            public :\n               /// BCCL macro to check the ConstPoint concept\n               BOOST_CONCEPT_USAGE(ConstMatrix) {\n                  Impl::MatrixCompileTimeIterator<Type, 0, ROW_DIMENSION, 0, COL_DIMENSION>().template apply<AccessCheck>();\n                  Type* pMat = NULL;\n                  const RowVectorType* pRowVector = NULL;\n                  ColVectorType colvec(Math::prod(*pMat, *pRowVector));\n               }\n         };\n\n\n         template<class Type>\n         class Matrix : public boost::DefaultConstructible<Type>, public boost::CopyConstructible<Type>, public boost::Assignable<Type> {\n            private:\n\n               BOOST_CONCEPT_ASSERT((Concept::ConstMatrix<Type>));\n               BOOST_MPL_ASSERT((typename MatrixTraits<Type>::IsMatrix));\n\n               typedef typename MatrixTraits<Type>::ValueType ValueType;\n               enum { ROW_DIMENSION = MatrixTraits<Type>::RowDimension::value,\n                      COL_DIMENSION = MatrixTraits<Type>::ColDimension::value\n                 };\n\n\n               template <class M, int I, int J>\n               struct AccessCheck {\n                  void operator()() const {\n                     M* p = NULL;\n                     get<I, J>(*p) = typename MatrixTraits<M>::ValueType();\n                  }\n               };\n\n\n               template<typename P, int RowCount, int ColCount>\n               struct MatrixProductChecker {\n                  static void check() {}\n               };\n\n               template<typename P, int Count>\n               struct MatrixProductChecker<P, Count, Count> {\n                  static void check() {\n                     P* p = 0;\n                     *p = Math::prod(*p, *p);\n                  }\n               };\n\n            public:\n               /// BCCL macro to check the Point concept\n               BOOST_CONCEPT_USAGE(Matrix) {\n                  Impl::MatrixCompileTimeIterator<Type, 0, ROW_DIMENSION, 0, COL_DIMENSION>().template apply<AccessCheck>();\n                  MatrixProductChecker<Type, ROW_DIMENSION, COL_DIMENSION>::check();\n                  ValueType v;\n                  Type t;\n                  t *= v;\n                  t = v * t;\n                  t = t * v;\n                  t = t + t;\n                  t = t - t;\n                  t += t;\n                  t -= t;\n               }\n         };\n\n      }\n\n   }\n}\n\n\n#endif\n", "meta": {"hexsha": "ba6d2ec4f78beb55b214a16f7a11698629044c78", "size": 10529, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/matrixconcept.hpp", "max_stars_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_stars_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "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/include/openOR/Math/matrixconcept.hpp", "max_issues_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_issues_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_issues_repo_licenses": ["MIT"], "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/include/openOR/Math/matrixconcept.hpp", "max_forks_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_forks_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_forks_repo_licenses": ["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.2901960784, "max_line_length": 145, "alphanum_fraction": 0.5160983949, "num_tokens": 2278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702578}}
{"text": "// Copyright 2022 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#ifndef IMAGE_PROJECTION_BASED_FUSION__UTILS__GEOMETRY_HPP_\n#define IMAGE_PROJECTION_BASED_FUSION__UTILS__GEOMETRY_HPP_\n\n#define EIGEN_MPL2_ONLY\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <autoware_auto_perception_msgs/msg/shape.hpp>\n#include <geometry_msgs/msg/pose.hpp>\n#include <sensor_msgs/msg/region_of_interest.hpp>\n\n#include <vector>\n\nnamespace image_projection_based_fusion\n{\n\nusing autoware_auto_perception_msgs::msg::Shape;\nusing geometry_msgs::msg::Pose;\n\ndouble calcIoU(\n  const sensor_msgs::msg::RegionOfInterest & roi_1,\n  const sensor_msgs::msg::RegionOfInterest & roi_2);\n\ndouble calcIoUX(\n  const sensor_msgs::msg::RegionOfInterest & roi_1,\n  const sensor_msgs::msg::RegionOfInterest & roi_2);\n\ndouble calcIoUY(\n  const sensor_msgs::msg::RegionOfInterest & roi_1,\n  const sensor_msgs::msg::RegionOfInterest & roi_2);\n\nvoid objectToVertices(\n  const Pose & pose, const Shape & shape, std::vector<Eigen::Vector3d> & vertices);\n\nvoid boundingBoxToVertices(\n  const Pose & pose, const Shape & shape, std::vector<Eigen::Vector3d> & vertices);\n\nvoid cylinderToVertices(\n  const Pose & pose, const Shape & shape, std::vector<Eigen::Vector3d> & vertices);\n\nvoid polygonToVertices(\n  const Pose & pose, const Shape & shape, std::vector<Eigen::Vector3d> & vertices);\n\nvoid transformPoints(\n  const std::vector<Eigen::Vector3d> & input_points, const Eigen::Affine3d & affine_transform,\n  std::vector<Eigen::Vector3d> & output_points);\n\n}  // namespace image_projection_based_fusion\n\n#endif  // IMAGE_PROJECTION_BASED_FUSION__UTILS__GEOMETRY_HPP_\n", "meta": {"hexsha": "9d69410c699009c7380ca706206a3b5fc3dc323b", "size": 2159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perception/image_projection_based_fusion/include/image_projection_based_fusion/utils/geometry.hpp", "max_stars_repo_name": "meliketanrikulu/autoware.universe", "max_stars_repo_head_hexsha": "04f2b53ae1d7b41846478641ad6ff478c3d5a247", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2021-11-30T09:03:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:25:17.000Z", "max_issues_repo_path": "perception/image_projection_based_fusion/include/image_projection_based_fusion/utils/geometry.hpp", "max_issues_repo_name": "meliketanrikulu/autoware.universe", "max_issues_repo_head_hexsha": "04f2b53ae1d7b41846478641ad6ff478c3d5a247", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 425.0, "max_issues_repo_issues_event_min_datetime": "2021-11-30T02:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:26:37.000Z", "max_forks_repo_path": "perception/image_projection_based_fusion/include/image_projection_based_fusion/utils/geometry.hpp", "max_forks_repo_name": "meliketanrikulu/autoware.universe", "max_forks_repo_head_hexsha": "04f2b53ae1d7b41846478641ad6ff478c3d5a247", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2021-11-30T02:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:38:29.000Z", "avg_line_length": 32.7121212121, "max_line_length": 94, "alphanum_fraction": 0.7725798981, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702578}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <scorum/chain/dba/db_accessor.hpp>\n#include <scorum/chain/evaluators/post_bet_evalulator.hpp>\n#include <scorum/chain/evaluators/cancel_pending_bets_evaluator.hpp>\n\n#include \"betting_common.hpp\"\n#include \"object_wrapper.hpp\"\n\n#include \"detail.hpp\"\n\nnamespace {\n\nusing namespace scorum;\nusing namespace scorum::chain;\nusing namespace scorum::protocol;\n\nSCORUM_TEST_CASE(post_bet_operation_validate_odds)\n{\n    post_bet_operation op;\n    op.better = \"aclice\";\n    op.uuid = gen_uuid(\"game\");\n    op.wincase = correct_score_home::yes();\n    op.stake = ASSET_SCR(100'000'000);\n\n    BOOST_CHECK_EQUAL(1001u, SCORUM_MIN_ODDS.inverted().numerator);\n    BOOST_CHECK_EQUAL(1u, SCORUM_MIN_ODDS.inverted().denominator);\n\n    BOOST_CHECK_EQUAL(1001u, SCORUM_MIN_ODDS.base().numerator);\n    BOOST_CHECK_EQUAL(1000u, SCORUM_MIN_ODDS.base().denominator);\n\n    op.odds = { SCORUM_MIN_ODDS.inverted().numerator, SCORUM_MIN_ODDS.inverted().denominator }; // max odds\n    BOOST_CHECK_NO_THROW(op.validate());\n\n    op.odds = { SCORUM_MIN_ODDS.base().numerator, SCORUM_MIN_ODDS.base().denominator };\n    BOOST_CHECK_NO_THROW(op.validate());\n\n    op.odds = { SCORUM_MIN_ODDS.inverted().numerator + 1, SCORUM_MIN_ODDS.inverted().denominator };\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n\n    op.odds = { SCORUM_MIN_ODDS.base().numerator - 1, SCORUM_MIN_ODDS.base().denominator };\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n\n    op.odds = { 1, 1 };\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n}\n\nSCORUM_TEST_CASE(post_bet_evaluator_operation_validate_check)\n{\n    post_bet_operation test_op;\n    test_op.better = \"aclice\";\n    test_op.uuid = gen_uuid(\"game\");\n    test_op.wincase = correct_score_home::yes();\n    test_op.odds = { 3, 1 };\n    test_op.stake = ASSET_SCR(100'000'000);\n\n    post_bet_operation op = test_op;\n\n    BOOST_CHECK_NO_THROW(op.validate());\n\n    op.better = \"\";\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n    op = test_op;\n\n    op.odds = { 1, 10 };\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n    op = test_op;\n\n    op.stake.amount = 0;\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n    op = test_op;\n\n    op.stake = ASSET_SP(1e+9);\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n    op = test_op;\n}\n\nstruct cancel_pending_bets_evaluator_fixture : public shared_memory_fixture\n{\n    using check_account_existence_ptr\n        = void (account_service_i::*)(const account_name_type&, const fc::optional<const char*>&) const;\n    using is_exists_ptr = bool (pending_bet_service_i::*)(const uuid_type&) const;\n    using get_ptr = const pending_bet_object& (pending_bet_service_i::*)(const uuid_type&)const;\n\n    MockRepository mocks;\n\n    data_service_factory_i* dbs_factory = mocks.Mock<data_service_factory_i>();\n    betting_service_i* betting_svc = mocks.Mock<betting_service_i>();\n    account_service_i* acc_svc = mocks.Mock<account_service_i>();\n    pending_bet_service_i* pending_bet_svc = mocks.Mock<pending_bet_service_i>();\n\n    cancel_pending_bets_evaluator_fixture()\n    {\n        mocks.OnCall(dbs_factory, data_service_factory_i::account_service).ReturnByRef(*acc_svc);\n        mocks.OnCall(dbs_factory, data_service_factory_i::pending_bet_service).ReturnByRef(*pending_bet_svc);\n    }\n};\n\nBOOST_FIXTURE_TEST_SUITE(cancel_pending_bets_evaluator_tests, cancel_pending_bets_evaluator_fixture)\n\nSCORUM_TEST_CASE(bet_id_existance_check_should_throw)\n{\n    cancel_pending_bets_operation op;\n    op.better = \"better\";\n    op.bet_uuids = { gen_uuid(\"0\") };\n\n    cancel_pending_bets_evaluator ev(*dbs_factory, *betting_svc);\n\n    mocks.ExpectCallOverload(acc_svc, (check_account_existence_ptr)&account_service_i::check_account_existence);\n    mocks.ExpectCallOverload(pending_bet_svc, (is_exists_ptr)&pending_bet_service_i::is_exists)\n        .With(gen_uuid(\"0\"))\n        .Return(false);\n\n    BOOST_CHECK_THROW(ev.do_apply(op), fc::assert_exception);\n}\n\nSCORUM_TEST_CASE(better_mismatch_should_throw)\n{\n    cancel_pending_bets_operation op;\n    op.better = \"better\";\n    op.bet_uuids = { gen_uuid(\"0\") };\n\n    auto obj = create_object<pending_bet_object>(shm, [](pending_bet_object& o) { o.data.better = \"cartman\"; });\n\n    mocks.OnCallOverload(acc_svc, (check_account_existence_ptr)&account_service_i::check_account_existence);\n    mocks.OnCallOverload(pending_bet_svc, (is_exists_ptr)&pending_bet_service_i::is_exists)\n        .With(gen_uuid(\"0\"))\n        .Return(true);\n    mocks.ExpectCallOverload(pending_bet_svc, (get_ptr)&pending_bet_service_i::get_pending_bet)\n        .With(gen_uuid(\"0\"))\n        .ReturnByRef(obj);\n\n    cancel_pending_bets_evaluator ev(*dbs_factory, *betting_svc);\n    BOOST_CHECK_THROW(ev.do_apply(op), fc::assert_exception);\n}\n\nSCORUM_TEST_CASE(should_cancel_bets)\n{\n    cancel_pending_bets_operation op;\n    op.better = \"better\";\n    op.bet_uuids = { gen_uuid(\"0\"), gen_uuid(\"1\") };\n\n    // clang-format off\n    auto obj1 = create_object<pending_bet_object>(shm, [&](pending_bet_object& o){ o.data.better = \"better\"; o.id = 0; o.data.uuid = gen_uuid(\"0\"); });\n    auto obj2 = create_object<pending_bet_object>(shm, [&](pending_bet_object& o){ o.data.better = \"better\"; o.id = 1; o.data.uuid = gen_uuid(\"1\"); });\n\n    mocks.OnCallOverload(acc_svc, (check_account_existence_ptr)&account_service_i::check_account_existence);\n    mocks.OnCallOverload(pending_bet_svc, (is_exists_ptr)&pending_bet_service_i::is_exists).With(gen_uuid(\"0\")).Return(true);\n    mocks.OnCallOverload(pending_bet_svc, (is_exists_ptr)&pending_bet_service_i::is_exists).With(gen_uuid(\"1\")).Return(true);\n    mocks.OnCallOverload(pending_bet_svc, (get_ptr)&pending_bet_service_i::get_pending_bet).With(gen_uuid(\"0\")).ReturnByRef(obj1);\n    mocks.OnCallOverload(pending_bet_svc, (get_ptr)&pending_bet_service_i::get_pending_bet).With(gen_uuid(\"1\")).ReturnByRef(obj2);\n    mocks.ExpectCall(betting_svc, betting_service_i::cancel_pending_bet).With(0);\n    mocks.ExpectCall(betting_svc, betting_service_i::cancel_pending_bet).With(1);\n    // clang-format on\n\n    cancel_pending_bets_evaluator ev(*dbs_factory, *betting_svc);\n    BOOST_CHECK_NO_THROW(ev.do_apply(op));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(cancel_pending_bets_operation_validate_tests)\n\nSCORUM_TEST_CASE(throw_exception_when_bet_uuids_is_empty)\n{\n    cancel_pending_bets_operation op;\n    op.better = \"better\";\n    op.bet_uuids = {};\n\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n}\n\nSCORUM_TEST_CASE(dont_throw_exception_when_bet_uuids_set)\n{\n    cancel_pending_bets_operation op;\n    op.better = \"better\";\n    op.bet_uuids = { gen_uuid(\"1\") };\n\n    BOOST_CHECK_NO_THROW(op.validate());\n}\n\nSCORUM_TEST_CASE(throw_exception_when_better_is_empty)\n{\n    cancel_pending_bets_operation op;\n    op.better = \"\";\n    op.bet_uuids = { gen_uuid(\"1\") };\n\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n}\n\nSCORUM_TEST_CASE(throw_exception_when_bets_not_unique)\n{\n    cancel_pending_bets_operation op;\n    op.better = \"better\";\n    op.bet_uuids = { gen_uuid(\"1\"), gen_uuid(\"1\") };\n\n    BOOST_CHECK_THROW(op.validate(), fc::assert_exception);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n}\n", "meta": {"hexsha": "ac9ca9591f6488649c4ef4d1791d2bdac6953d27", "size": 7218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utests/betting/bet_evaluators_tests.cpp", "max_stars_repo_name": "scorum/scorum", "max_stars_repo_head_hexsha": "1da00651f2fa14bcf8292da34e1cbee06250ae78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:20:48.000Z", "max_issues_repo_path": "tests/utests/betting/bet_evaluators_tests.cpp", "max_issues_repo_name": "Scorum/Scorum", "max_issues_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2017-11-25T09:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T09:17:22.000Z", "max_forks_repo_path": "tests/utests/betting/bet_evaluators_tests.cpp", "max_forks_repo_name": "Scorum/Scorum", "max_forks_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T19:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:50:42.000Z", "avg_line_length": 35.7326732673, "max_line_length": 151, "alphanum_fraction": 0.7432806872, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702578}}
{"text": "#include \"atomistic.hpp\"\n#include \"formats.hpp\"\n#include \"types.hpp\"\n#include \"io.hpp\"\n\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <string>\n\n#include <boost/program_options.hpp>\n\n\n#include <ctime>\ntime_t t = clock();\n//#include <gsl/gsl_const_mksa.h>\n\nnamespace po = boost::program_options;\nnamespace at = atomistic;\nnamespace cp2k = formats::cp2k;\nnamespace stm = formats::stm;\n\n// Returns true, if parsing went ok\nbool parse(int ac, char* av[], po::variables_map& vm);\n\n// Prepares extrapolation\nbool prepare(types::String levelFileName,\n             std::vector<types::String> wfnCubes,\n             types::String hartreeFileName,\n             types::String mode,\n             double start,\n             double width,\n             double isoValue,\n             double approachFrom,\n             double kPlaneMax,\n             types::Uint nLayers,\n             double ballRadius\n             );\n\nint main(int ac, char* av[]) {\n\n    po::variables_map args;\n    if (parse(ac, av, args)) {\n        prepare(args[\"levels\"].as< types::String >(),\n                args[\"wfncubes\"].as< std::vector<types::String> >(),\n                args[\"hartree\"].as< types::String >(),\n                args[\"mode\"].as< types::String >(),\n                args[\"start\"].as< double >(),\n                args[\"width\"].as< double >(),\n                args[\"isovalue\"].as< double >(),\n                args[\"approach-from\"].as< double >(),\n                args[\"k-cutoff\"].as< double >(),\n                args[\"nlayers\"].as< types::Uint >(),\n                args[\"ball-radius\"].as< double >()\n               );\n\n    }\n\n    return 0;\n}\n\nbool prepare(types::String levelFileName,\n             std::vector<types::String> wfnCubes,\n             types::String hartreeFileName,\n             types::String mode,\n             double start,\n             double width,\n             double isoValue,\n             double approachFrom,\n             double kPlaneMax,\n             types::Uint nLayers,\n             double ballRadius\n            ){\n\n    // Read energy levels\n    cp2k::Spectrum spectrum = cp2k::Spectrum();\n    spectrum.readFromCp2k(levelFileName.c_str());\n\n    // Read hartree cube file\n    formats::Cube hartree = formats::Cube();\n    hartree.readCubeFile(hartreeFileName.c_str());\n\n    // Write Zprofile of hartree potential\n    std::string hartreeZProfile = io::getFileName(hartreeFileName);\n    hartreeZProfile += \".zprofile\";\n    std::cout << \"Writing Z profile of Hartree potential to \" \n        << hartreeZProfile << std::endl;\n    hartree.writeZProfile(hartreeZProfile);\n    \n    std::cout << \"Time to prepare : \" << (clock() -t)/1000.0 << \" ms\\n\";\n    t = clock();\n    \n    // Iterate over cubes\n    stm::WfnExtrapolation::Mode m ;\n    types::Real var1;\n    if( mode == \"plane\" ){\n        m = stm::WfnExtrapolation::plane;\n        var1 = start;\n    }\n    else if ( mode == \"isosurface\" ){\n        m = stm::WfnExtrapolation::isoSurface;\n        var1 = isoValue;\n    }\n    else if ( mode == \"rolling-ball\" ){\n        m = stm::WfnExtrapolation::rollingBall;\n        var1 = ballRadius;\n    }\n    stm::WfnExtrapolation extrapolation = stm::WfnExtrapolation(\n            wfnCubes,\n            spectrum,\n            hartree,\n            m,\n            var1,\n            width,\n            approachFrom,\n            kPlaneMax,\n            nLayers\n            );\n    extrapolation.execute();\n\n    return true;\n}\n\n\n\n\nbool parse(int ac, char* av[], po::variables_map& vm) {\n    types::String input_file;\n    // Declare regular options\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"version,v\", \"print version information\")\n    (\"input-file,i\", po::value<types::String>(&input_file), \"Input file specifying all or several of the following options\")\n    (\"levels\", po::value<types::String>(), \"CP2K output file containing energy levels\")\n    (\"wfncubes\", po::value< std::vector<types::String> >(), \"List of wavefunction cubes you wish to extrapolate\")\n    (\"hartree\", po::value<types::String>(), \"cube file of hartree potential from CP2K\")\n    (\"mode\", po::value<types::String>()->default_value(\"plane\"), \"may be 'plane', 'isosurface', 'rolling-ball'\")\n    (\"start\", po::value<double>()->default_value(5), \"mode 'plane': distance between extrapolation plane and outermost atom in a.u.\")\n    (\"width\", po::value<double>()->default_value(15), \"length of extrapolation in a.u.\")\n    (\"isovalue\", po::value<double>()->default_value(0.0), \"mode 'isosurface': isovalue of the Hartree potential [a.u.] \")\n    (\"approach-from\", po::value<double>()->default_value(-1.0), \"mode 'isosurface': z [a.u.] from where you want to go down to find the isosurface (default: top z of cube file).\")\n//  (\"decay-cutoff\", po::value<double>()->default_value(2.0), \"Maximum decay constant k [1/a.u.] to be retained for z decay  10^(-k*z).\")\n    (\"k-cutoff\", po::value<double>()->default_value(3.0), \"Restrict basis functions to maximum wave number k = 1/lambda [1/a.u.] in xy-plane.\")\n    (\"nlayers\", po::value<types::Uint>()->default_value(1), \"Number of layers to fit the wave function values.\")\n    (\"ball-radius\", po::value<double>()->default_value(5.0), \"mode 'rolling-ball': Radius of ball rolling on top of the atoms [a.u.] \")\n    ;\n\n    // Register positional options\n    po::positional_options_description p;\n    p\t.add(\"input-file\", 1) .add(\"wfncubes\", -1);\n\n    // Parse\n    po::store(po::command_line_parser(ac,av).\n              options(desc).positional(p).run(), vm);\n    po::notify(vm);\n\n    // If specified, try to parse conig file\n    if (vm.count(\"input-file\")){\n        std::ifstream ifs(input_file.c_str());\n        if(!ifs) throw types::fileAccessError() << boost::errinfo_file_name(input_file);\n        store(parse_config_file(ifs, desc), vm);\n        notify(vm);\n    }\n\n    // Display help message\n    if (\tvm.count(\"help\") ||\n            !vm.count(\"levels\") ||\n            !vm.count(\"hartree\") ||\n            !vm.count(\"wfncubes\") ||\n            !vm.count(\"width\")\t) {\n        std::cout << \"Usage: extrapolate [options]\\n\";\n        std::cout << desc << \"\\n\";\n    } else if (vm.count(\"version\")) {\n        std::cout << \"October 9th 2012\\n\";\n    } else if ( vm.count(\"mode\")  && \n                vm[\"mode\"].as< types::String >() != \"plane\" && \n                vm[\"mode\"].as< types::String >() != \"rolling-ball\" && \n                vm[\"mode\"].as< types::String >() != \"isosurface\") {\n                std::cout << \"Error: invalid mode specified.\\n\";\n    } else if ( (!vm.count(\"mode\")  || vm[\"mode\"].as< types::String >() == \"plane\") &&\n               !(vm.count(\"start\") && vm.count(\"width\"))) {\n                std::cout << \"Error: Need to specify 'start' and 'width' for mode='plane'.\\n\";\n    } else if ( vm[\"mode\"].as< types::String >() == \"isosurface\" &&\n               !(vm.count(\"isovalue\") && vm.count(\"width\"))) {\n                std::cout << \"Error: Need to specify 'isovalue' and 'width' for mode='isosurface'.\\n\";\n    } else if ( vm[\"mode\"].as< types::String >() == \"rolling-ball\" &&\n               !(vm.count(\"ball-radius\") && vm.count(\"width\"))) {\n                std::cout << \"Error: Need to specify 'ball-radius' and 'width' for mode='rolling-ball'.\\n\";\n    } else if ( vm[\"k-cutoff\"].as< types::Real >() < 0 ){\n                std::cout << \"Error: K-cutoff must be non-negative.\\n\";\n    } else {\n        return true;\n    }\n\n    return false;\n}\n\n", "meta": {"hexsha": "9cf2d8df45baa7852d8a4cd7599db3dcae40dd1d", "size": 7447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stm/extrapolate2.cpp", "max_stars_repo_name": "ltalirz/util-programs", "max_stars_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "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": "stm/extrapolate2.cpp", "max_issues_repo_name": "ltalirz/util-programs", "max_issues_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stm/extrapolate2.cpp", "max_forks_repo_name": "ltalirz/util-programs", "max_forks_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_forks_repo_licenses": ["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.235, "max_line_length": 179, "alphanum_fraction": 0.5692225057, "num_tokens": 1917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.19761247593169104}}
{"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\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/EagerMath/DotProduct.hpp\"\n#include \"DataStructures/Tensor/EagerMath/Magnitude.hpp\"  // For Tags::Normalized\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/InterfaceHelpers.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Domain/TagsTimeDependent.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace domain {\nnamespace Tags {\n/// Compute the characteristic speeds on the moving mesh given the\n/// characteristic speeds if the mesh were stationary.\n///\n/// \\note Assumes that `typename CharSpeedsComputeTag::return_type` is a\n/// `std::array<DataVector, NumberOfCharSpeeds>`\ntemplate <typename CharSpeedsComputeTag, size_t Dim>\nstruct CharSpeedCompute : CharSpeedsComputeTag::base, db::ComputeTag {\n  using base = typename CharSpeedsComputeTag::base;\n  using return_type = typename CharSpeedsComputeTag::return_type;\n\n  template <typename... Ts, typename T, size_t NumberOfCharSpeeds>\n  static void function(\n      const gsl::not_null<std::array<T, NumberOfCharSpeeds>*> result,\n      const boost::optional<tnsr::I<DataVector, Dim, Frame::Inertial>>&\n          grid_velocity,\n      const tnsr::i<DataVector, Dim, Frame::Inertial>& unit_normal_covector,\n      const Ts&... ts) noexcept {\n    // Note that while the CharSpeedsComputeTag almost certainly also needs the\n    // unit normal covector for computing the original characteristic speeds, we\n    // don't know which of the `ts` it is, and thus we need the unit normal\n    // covector to be passed explicitly.\n    CharSpeedsComputeTag::function(result, ts...);\n    if (static_cast<bool>(grid_velocity)) {\n      const Scalar<DataVector> normal_dot_velocity =\n          dot_product(*grid_velocity, unit_normal_covector);\n      for (size_t i = 0; i < result->size(); ++i) {\n        gsl::at(*result, i) -= get(normal_dot_velocity);\n      }\n    }\n  }\n\n  using argument_tags =\n      tmpl::push_front<typename CharSpeedsComputeTag::argument_tags,\n                       MeshVelocity<Dim, Frame::Inertial>,\n                       ::Tags::Normalized<UnnormalizedFaceNormal<Dim>>>;\n  using volume_tags = get_volume_tags<CharSpeedsComputeTag>;\n};\n}  // namespace Tags\n}  // namespace domain\n", "meta": {"hexsha": "fa7e6711f60061dcb576c0d93e8025f4d8692deb", "size": 2387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/TagsCharacteresticSpeeds.hpp", "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/TagsCharacteresticSpeeds.hpp", "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/TagsCharacteresticSpeeds.hpp", "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": 39.131147541, "max_line_length": 81, "alphanum_fraction": 0.7222454964, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.19761247593169104}}
{"text": "#include \"generate_data/shadowed.h\"\n\n#include \"generate_data/clip_by_plane.h\"\n#include \"generate_data/get_points_from_subset.h\"\n#include \"generate_data/triangle.h\"\n#include \"generate_data/triangle_subset.h\"\n#include \"generate_data/triangle_subset_intersection.h\"\n#include \"intersect/triangle.h\"\n#include \"intersect/triangle_impl.h\"\n#include \"lib/array_vec.h\"\n#include \"lib/span.h\"\n\n#include <boost/geometry.hpp>\n#include <unordered_set>\n\n#include \"dbg.h\"\n#include \"generate_data/print_region.h\"\n#include \"lib/info/print_triangle.h\"\n\nnamespace std {\n// from\n// https://codereview.stackexchange.com/questions/171999/specializing-stdhash-for-stdarray\ntemplate <class T, size_t N> struct hash<array<T, N>> {\n  auto operator()(const array<T, N> &key) const {\n    size_t result = 0;\n    for (size_t i = 0; i < N; ++i) {\n      result = result * 31 + hasher(key[i]);\n    }\n    return result;\n  }\n\n  std::hash<T> hasher;\n};\n} // namespace std\n\nnamespace generate_data {\n\n// TODO: fix epsilons\n// TODO: could be sooooo much faster probably\nATTR_PURE_NDEBUG PartiallyShadowedInfo partially_shadowed(\n    const Triangle &from, const TriangleSubset &from_clipped_region,\n    const Triangle &blocker, const TriangleSubset &blocker_clipped_region,\n    const Triangle &onto, const TriangleSubset &onto_clipped_region,\n    bool flip_onto_normal) {\n  auto from_pb = get_points_from_subset_with_baryo(from, from_clipped_region);\n  const auto blocker_pb =\n      get_points_from_subset_with_baryo(blocker, blocker_clipped_region);\n  const auto &from_vertices = from_pb.points;\n  const auto &from_baryo = from_pb.baryo;\n  const auto &blocker_vertices = blocker_pb.points;\n  const auto &blocker_baryo = blocker_pb.baryo;\n  debug_assert(from_vertices.size() == from_baryo.size());\n  debug_assert(blocker_vertices.size() == blocker_baryo.size());\n  debug_assert(!from_vertices.empty());\n  debug_assert(!blocker_vertices.empty());\n\n  auto normal = *onto.normal();\n  if (flip_onto_normal) {\n    normal = -normal;\n  }\n  auto plane_vertex = onto.vertices[0];\n\n  double plane_offset = normal.dot(plane_vertex);\n  auto plane_pos = [&](const Eigen::Vector3d &point) {\n    return point.dot(normal) - plane_offset;\n  };\n\n#ifndef NDEBUG\n  // double from_max_plane_pos = std::numeric_limits<double>::lowest();\n  for (const auto &p : from_vertices) {\n    double pos = plane_pos(p);\n    // should already be clipped by plane!\n    debug_assert(pos > -1e-6);\n    // from_max_plane_pos = std::max(pos, from_max_plane_pos);\n  }\n\n  // shouldn't be coplaner\n  // debug_assert(from_max_plane_pos > 1e-13);\n\n  for (const auto &p : blocker_vertices) {\n    // should already be clipped by plane!\n    [[maybe_unused]] double pos = plane_pos(p);\n    debug_assert(pos > -1e-6);\n  }\n#endif\n\n  VectorT<Eigen::Vector2d> points_for_hull;\n  // TODO: could be handled just using an angle range\n  VectorT<Eigen::Vector2d> directions;\n  points_for_hull.reserve(from_vertices.size() * blocker_vertices.size() * 6);\n  directions.reserve(from_vertices.size() * blocker_vertices.size());\n\n  VectorT<PartiallyShadowedInfo::RayItem> ray_items;\n  ray_items.reserve(from_vertices.size() * blocker_vertices.size() * 6);\n\n  std::unordered_set<std::array<double, 4>> added_items;\n\n  // NOTE: this has_all approach only really makes sense with clipping!\n  bool has_all = false;\n  auto run_for_points =\n      [&](const BaryoPoint &baryo_origin, const BaryoPoint &baryo_endpoint,\n          const Eigen::Vector3d &origin, const Eigen::Vector3d &endpoint) {\n        std::array key{baryo_origin.x(), baryo_origin.y(), baryo_endpoint.x(),\n                       baryo_endpoint.y()};\n        if (!added_items.insert(key).second) {\n          // already added\n          return;\n        }\n\n        auto add_point = [&](const Eigen::Vector3d &point) -> Eigen::Vector2d {\n          auto baryo = onto.baryo_values(point);\n          Eigen::Vector2d baryo_eigen{baryo[0], baryo[1]};\n          points_for_hull.push_back(baryo_eigen);\n\n          return baryo_eigen;\n        };\n\n        double origin_plane_position = plane_pos(origin);\n        double endpoint_plane_position = plane_pos(endpoint);\n\n        // TODO: https://github.com/boostorg/geometry/issues/861\n        if (origin_plane_position - endpoint_plane_position <= -1e-5) {\n          return;\n        }\n        // debug_assert(origin_plane_position - endpoint_plane_position >\n        // -1e-5);\n\n        Eigen::Vector3d direction = endpoint - origin;\n\n        auto result = [&]() -> PartiallyShadowedInfo::RayItem::Result {\n          if (direction.squaredNorm() < 1e-16) {\n            has_all = true;\n            // intersecting/overlapping point case\n            return {tag_v<RayItemResultType::ClosePoint>, {}};\n          }\n\n          if (origin_plane_position - endpoint_plane_position < 1e-5) {\n            // coplanar case\n            if (std::abs(endpoint_plane_position) < 1e-6) {\n              // TODO: is this case important?\n              // endpoint is also on onto\n              add_point(endpoint);\n            }\n\n            auto origin_on_plane_baryo =\n                onto.baryo_values(origin - normal * origin_plane_position);\n            auto endpoint_on_plane =\n                onto.baryo_values(endpoint - normal * endpoint_plane_position);\n            Eigen::Vector2d direction{\n                endpoint_on_plane[0] - origin_on_plane_baryo[0],\n                endpoint_on_plane[1] - origin_on_plane_baryo[1]};\n            direction.normalize();\n            directions.push_back(direction);\n            return {tag_v<RayItemResultType::Ray>, direction};\n          } else {\n            double denom = normal.dot(direction);\n            debug_assert(std::abs(denom) > 1e-15);\n            double t = -origin_plane_position / denom;\n            debug_assert(t > 1. - 1e-3); // should hit plane AFTER endpoint\n            return {tag_v<RayItemResultType::Intersection>,\n                    add_point(t * direction + origin)};\n          }\n        }();\n\n        ray_items.push_back({\n            .baryo_origin = baryo_origin,\n            .baryo_endpoint = baryo_endpoint,\n            .origin = origin,\n            .endpoint = endpoint,\n            .result = result,\n        });\n      };\n\n  // TODO: could make this much more efficient in many different ways...\n  // Also, this has pretty terrible numerical properties...\n  for (unsigned i = 0; i < from_vertices.size(); ++i) {\n    auto clipped =\n        clip_by_plane(-normal, from_vertices[i].dot(-normal), blocker);\n    auto new_blocker_region =\n        triangle_subset_intersection(blocker_clipped_region, clipped);\n\n    const auto new_blocker_bp =\n        get_points_from_subset_with_baryo(blocker, new_blocker_region);\n    const auto &new_blocker_vertices = new_blocker_bp.points;\n    const auto &new_blocker_baryo = new_blocker_bp.baryo;\n    debug_assert(new_blocker_vertices.size() == new_blocker_baryo.size());\n\n    for (unsigned j = 0; j < new_blocker_vertices.size(); ++j) {\n      run_for_points(from_baryo[i], new_blocker_baryo[j], from_vertices[i],\n                     new_blocker_vertices[j]);\n    }\n  }\n  for (unsigned j = 0; j < blocker_vertices.size(); ++j) {\n    auto new_from_region = triangle_subset_intersection(\n        from_clipped_region,\n        clip_by_plane(normal, blocker_vertices[j].dot(normal), from));\n\n    const auto new_from_bp =\n        get_points_from_subset_with_baryo(from, new_from_region);\n    const auto &new_from_vertices = new_from_bp.points;\n    const auto &new_from_baryo = new_from_bp.baryo;\n    debug_assert(new_from_vertices.size() == new_from_baryo.size());\n\n    for (unsigned i = 0; i < new_from_vertices.size(); ++i) {\n      run_for_points(new_from_baryo[i], blocker_baryo[j], new_from_vertices[i],\n                     blocker_vertices[j]);\n    }\n  }\n\n  if (has_all) {\n    return {.partially_shadowed = {tag_v<TriangleSubsetType::All>, {}},\n            .ray_items = ray_items};\n  }\n  if (points_for_hull.empty()) {\n    // hmm, does this mishandle only direction case? (should be very very edge\n    // case...)\n    return {.partially_shadowed = {tag_v<TriangleSubsetType::None>, {}},\n            .ray_items = ray_items};\n  }\n\n  boost::geometry::model::multi_point<BaryoPoint> multi_point_for_hull;\n  auto add_final_point = [&](const Eigen::Vector2d &p) {\n    boost::geometry::append(multi_point_for_hull, BaryoPoint{p.x(), p.y()});\n  };\n  for (const auto &point : points_for_hull) {\n    add_final_point(point);\n  }\n\n  // this is jank and slow - probably could do this better...\n  // Also has numerical issues...\n  double edge_total = 0.;\n  for (unsigned i = 0; i < onto.vertices.size(); ++i) {\n    unsigned next_i = (i + 1) % onto.vertices.size();\n    edge_total += (onto.vertices[next_i] - onto.vertices[i]).norm();\n  }\n  double base_multiplier = edge_total + 2.;\n  for (const auto &dir : directions) {\n    for (const auto &point : points_for_hull) {\n      auto dist_from_0 = point.norm();\n      // multiplier just needs to be sufficiently large\n      double multiplier = 2. * (dist_from_0 + base_multiplier);\n      add_final_point(point + dir * multiplier);\n    }\n  }\n\n  TriPolygon poly;\n  boost::geometry::convex_hull(multi_point_for_hull, poly);\n\n  TriPolygon triangle{{{0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {0.0, 0.0}}};\n  debug_assert(boost::geometry::is_valid(triangle));\n\n  auto partially_shadowed = triangle_subset_intersection(\n      triangle_subset_intersection({tag_v<TriangleSubsetType::Some>, poly},\n                                   {tag_v<TriangleSubsetType::Some>, triangle}),\n      onto_clipped_region);\n\n  if (partially_shadowed.type() == TriangleSubsetType::Some) {\n    auto poly = partially_shadowed.get(tag_v<TriangleSubsetType::Some>);\n    if (boost::geometry::area(poly) > 0.5 - 1e-12) {\n      partially_shadowed = {tag_v<TriangleSubsetType::All>, {}};\n    }\n  }\n\n  return {.partially_shadowed = partially_shadowed, .ray_items = ray_items};\n}\n\nATTR_PURE_NDEBUG TriangleSubset shadowed_from_point(\n    const Eigen::Vector3d &point,\n    SpanSized<const Eigen::Vector3d> blocker_points, const Triangle &onto,\n    const TriangleSubset &onto_clipped_region) {\n  TriangleSubset full_intersection = onto_clipped_region;\n  debug_assert(blocker_points.size() >= 3);\n\n  for (unsigned j = 0; j < blocker_points.size(); ++j) {\n    unsigned next_j = (j + 1) % blocker_points.size();\n    unsigned next_next_j = (j + 2) % blocker_points.size();\n\n    auto vec_0 = blocker_points[j] - point;\n    auto vec_1 = blocker_points[next_j] - point;\n    Eigen::Vector3d normal = vec_0.cross(vec_1).normalized();\n    auto point_on_plane = blocker_points[next_j];\n    // other vertex should be on positive side of plane (blocker_points is\n    // assumed to be convex, planar polygon)\n    if (normal.dot(blocker_points[next_next_j] - point_on_plane) < 0.) {\n      normal *= -1.;\n    }\n\n    auto clipped = clip_by_plane_point(normal, point_on_plane, onto);\n\n    full_intersection =\n        triangle_subset_intersection(full_intersection, clipped);\n  }\n\n  return full_intersection;\n}\n\nATTR_PURE_NDEBUG TotallyShadowedInfo totally_shadowed(\n    const Triangle &from, const TriangleSubset &from_clipped_region,\n    const Triangle &blocker, const TriangleSubset &blocker_clipped_region,\n    const Triangle &onto, const TriangleSubset &onto_clipped_region) {\n  // no need for the func to be called in these cases\n  always_assert(from_clipped_region.type() != TriangleSubsetType::None);\n  always_assert(blocker_clipped_region.type() != TriangleSubsetType::None);\n\n  auto from_points = get_points_from_subset(from, from_clipped_region);\n  auto blocker_points = get_points_from_subset(blocker, blocker_clipped_region);\n  VectorT<TriangleSubset> from_each_point(from_points.size());\n  TriangleSubset totally_shadowed = {tag_v<TriangleSubsetType::All>, {}};\n  for (unsigned i = 0; i < from_points.size(); ++i) {\n    const auto &origin = from_points[i];\n    from_each_point[i] =\n        shadowed_from_point(origin, blocker_points, onto, onto_clipped_region);\n    totally_shadowed =\n        triangle_subset_intersection(totally_shadowed, from_each_point[i]);\n  }\n\n  return {\n      .totally_shadowed = totally_shadowed,\n      .from_each_point = from_each_point,\n  };\n}\n} // namespace generate_data\n", "meta": {"hexsha": "8eecd0803918bf1847729a94169377ecb01086c1", "size": 12167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/generate_data/shadowed.cpp", "max_stars_repo_name": "rgreenblatt/path", "max_stars_repo_head_hexsha": "2057618ee3a6067c230c1c1c40856d2c9f5006b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-15T19:26:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T19:26:37.000Z", "max_issues_repo_path": "src/generate_data/shadowed.cpp", "max_issues_repo_name": "rgreenblatt/path", "max_issues_repo_head_hexsha": "2057618ee3a6067c230c1c1c40856d2c9f5006b0", "max_issues_repo_licenses": ["MIT"], "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_data/shadowed.cpp", "max_forks_repo_name": "rgreenblatt/path", "max_forks_repo_head_hexsha": "2057618ee3a6067c230c1c1c40856d2c9f5006b0", "max_forks_repo_licenses": ["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.6687306502, "max_line_length": 90, "alphanum_fraction": 0.6770773403, "num_tokens": 3026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37754068280545827, "lm_q1q2_score": 0.197612475931691}}
{"text": "/*\n * Copyright 2020 Robert Bosch GmbH\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 * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * \\file osi_omni_sensor.cpp\n * \\see  osi_omni_sensor.hpp\n */\n\n#include \"osi_omni_sensor.hpp\"\n\n#include <math.h>     // for atan\n#include <algorithm>  // for max\n#include <cassert>    // for assert\n#include <map>        // for map<>\n\n#include <Eigen/Geometry>  // for Isometry3d, Vector3d\n\n#include <cloe/component/lane_boundary.hpp>  // for LaneBoundary\n#include <cloe/component/object.hpp>         // for Object\n#include <cloe/core.hpp>                     // for Duration\n#include <cloe/simulator.hpp>                // for ModelError\n#include <cloe/utility/geometry.hpp>         // for quaternion_from_rpy\n\n#include \"osi_common.pb.h\"           // for Timestamp, Identifier, BaseMoving, ..\n#include \"osi_detectedobject.pb.h\"   // for DetectedMovingObject\n#include \"osi_hostvehicledata.pb.h\"  // for HostVehicleData\n#include \"osi_object.pb.h\"           // for MovingObject\n#include \"osi_sensordata.pb.h\"       // for SensorData, DetectedEntityHeader\n#include \"osi_sensorview.pb.h\"       // for SensorView\n\n#include \"osi_ground_truth.hpp\"  // for OsiGroundTruth\n#include \"osi_utils.hpp\"         // for osi_require, ..\n\nnamespace osii {\n\nEigen::Isometry3d osi_position_orientation_to_pose_alt(const osi3::BaseMoving& base,\n                                                       const osi3::BaseMoving& base_gt) {\n  const osi3::BaseMoving* base_p;\n  if (base.has_orientation()) {\n    base_p = &base;\n  } else {\n    osi_require(\"GroundTruth-BaseMoving::orientation\", base_gt.has_orientation());\n    base_p = &base_gt;\n  }\n  Eigen::Quaterniond quaternion = cloe::utility::quaternion_from_rpy(\n      base_p->orientation().roll(), base_p->orientation().pitch(), base_p->orientation().yaw());\n\n  osi_require(\"base::position\", base.has_position());\n  Eigen::Vector3d translation = osi_vector3d_xyz_to_vector3d(base.position());\n  return cloe::utility::pose_from_rotation_translation(quaternion, translation);\n}\n\n/**\n * Convert from OSI moving object type to Cloe object classification. Note that\n * vehicles are treated explicitly in osi_mov_veh_class_map.\n */\nconst std::map<osi3::MovingObject::Type, cloe::Object::Class> osi_mov_obj_type_map = {\n    {osi3::MovingObject_Type_TYPE_UNKNOWN, cloe::Object::Class::Unknown},\n    {osi3::MovingObject_Type_TYPE_OTHER, cloe::Object::Class::Unknown},\n    {osi3::MovingObject_Type_TYPE_ANIMAL, cloe::Object::Class::Unknown},\n    {osi3::MovingObject_Type_TYPE_PEDESTRIAN, cloe::Object::Class::Pedestrian},\n};\n\n/**\n * Convert from OSI moving vehicle type to Cloe object classification. Note that\n * objects other than vehicles are treated explicitly in osi_mov_obj_type_map.\n */\nconst std::map<osi3::MovingObject::VehicleClassification::Type, cloe::Object::Class>\n    osi_mov_veh_class_map = {\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_UNKNOWN, cloe::Object::Class::Unknown},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_OTHER, cloe::Object::Class::Unknown},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_SMALL_CAR, cloe::Object::Class::Car},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_COMPACT_CAR, cloe::Object::Class::Car},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_MEDIUM_CAR, cloe::Object::Class::Car},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_LUXURY_CAR, cloe::Object::Class::Car},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_DELIVERY_VAN,\n         cloe::Object::Class::Truck},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_HEAVY_TRUCK,\n         cloe::Object::Class::Truck},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_SEMITRAILER,\n         cloe::Object::Class::Truck},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_TRAILER, cloe::Object::Class::Unknown},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_MOTORBIKE,\n         cloe::Object::Class::Motorbike},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_BICYCLE, cloe::Object::Class::Bike},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_BUS, cloe::Object::Class::Truck},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_TRAM, cloe::Object::Class::Unknown},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_TRAIN, cloe::Object::Class::Unknown},\n        {osi3::MovingObject_VehicleClassification_Type_TYPE_WHEELCHAIR,\n         cloe::Object::Class::Unknown},\n};\n\n/**\n * Convert from OSI lane boundary types to Cloe types.\n */\nconst std::map<osi3::LaneBoundary_Classification_Type, cloe::LaneBoundary::Type>\n    osi_lane_bdry_type_map = {\n        // clang-format off\n        {osi3::LaneBoundary_Classification_Type_TYPE_UNKNOWN, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_OTHER, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_NO_LINE, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_SOLID_LINE, cloe::LaneBoundary::Type::Solid},\n        {osi3::LaneBoundary_Classification_Type_TYPE_DASHED_LINE, cloe::LaneBoundary::Type::Dashed},\n        {osi3::LaneBoundary_Classification_Type_TYPE_BOTTS_DOTS, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_ROAD_EDGE, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_SNOW_EDGE, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_GRASS_EDGE, cloe::LaneBoundary::Type::Grass},\n        {osi3::LaneBoundary_Classification_Type_TYPE_GRAVEL_EDGE, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_SOIL_EDGE, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_GUARD_RAIL, cloe::LaneBoundary::Type::Unknown},\n        {osi3::LaneBoundary_Classification_Type_TYPE_CURB, cloe::LaneBoundary::Type::Curb},\n        {osi3::LaneBoundary_Classification_Type_TYPE_STRUCTURE, cloe::LaneBoundary::Type::Unknown},\n        // clang-format on\n};\n\n/**\n * Convert from OSI lane boundary colors to Cloe colors.\n */\nconst std::map<int, cloe::LaneBoundary::Color> osi_lane_bdry_color_map = {\n    {osi3::LaneBoundary_Classification_Color_COLOR_UNKNOWN, cloe::LaneBoundary::Color::Unknown},\n    {osi3::LaneBoundary_Classification_Color_COLOR_OTHER, cloe::LaneBoundary::Color::Unknown},\n    {osi3::LaneBoundary_Classification_Color_COLOR_NONE, cloe::LaneBoundary::Color::Unknown},\n    {osi3::LaneBoundary_Classification_Color_COLOR_WHITE, cloe::LaneBoundary::Color::White},\n    {osi3::LaneBoundary_Classification_Color_COLOR_YELLOW, cloe::LaneBoundary::Color::Yellow},\n    {osi3::LaneBoundary_Classification_Color_COLOR_RED, cloe::LaneBoundary::Color::Red},\n    {osi3::LaneBoundary_Classification_Color_COLOR_BLUE, cloe::LaneBoundary::Color::Blue},\n    {osi3::LaneBoundary_Classification_Color_COLOR_GREEN, cloe::LaneBoundary::Color::Green},\n    {osi3::LaneBoundary_Classification_Color_COLOR_VIOLET, cloe::LaneBoundary::Color::Unknown},\n};\n\ncloe::Duration osi_timestamp_to_time(const osi3::Timestamp& timestamp) {\n  return std::chrono::duration_cast<cloe::Duration>(std::chrono::seconds(timestamp.seconds()) +\n                                                    std::chrono::nanoseconds(timestamp.nanos()));\n}\n\ncloe::Duration OsiOmniSensor::osi_timestamp_to_simtime(const osi3::Timestamp& timestamp) const {\n  return osi_timestamp_to_time(timestamp) - this->init_time_;\n}\n\nvoid from_osi_identifier(const osi3::Identifier& osi_id, int& id) {\n  id = static_cast<int>(osi_id.value());\n}\n\nvoid from_osi_host_vehicle_data(const osi3::HostVehicleData& osi_hv, cloe::Object& obj) {\n  from_osi_base_moving(osi_hv.location(), obj);\n}\n\nvoid from_osi_detected_item_header(const osi3::DetectedItemHeader& osi_hdr, cloe::Object& obj) {\n  osi_require(\"ground_truth_id_size == 1\", osi_hdr.ground_truth_id_size() == 1);\n  // Multiple ground truth objects melt into one detected item are currently not\n  // supported.\n  auto osi_obj_gt_id = osi_hdr.ground_truth_id(0);\n  from_osi_identifier(osi_obj_gt_id, obj.id);\n  // Existence probability\n  if (osi_hdr.has_existence_probability()) {\n    obj.exist_prob = osi_hdr.existence_probability();\n  } else {\n    obj.exist_prob = 1.0;\n  }\n}\n\nvoid from_osi_detected_moving_object(const osi3::DetectedMovingObject& osi_mo, cloe::Object& obj) {\n  // object id = ground truth id\n  osi_require(\"DetectedMovingObject::header\", osi_mo.has_header());\n  from_osi_detected_item_header(osi_mo.header(), obj);\n\n  // Object classification\n  if (osi_mo.candidate_size() > 0) {\n    osi_require(\"candidate_size == 1\", osi_mo.candidate_size() == 1);\n    from_osi_mov_obj_type_classification(osi_mo.candidate(0), obj.classification);\n    // TODO(tobias): Need to additionally handle classification probability.\n  } else {\n    obj.classification = cloe::Object::Class::Unknown;\n  }\n\n  // DetectedMovingObject::base: \"The bounding box does NOT include mirrors for\n  // vehicles. The parent frame of base is the sensor's [vehicle frame].\"\n  from_osi_base_moving(osi_mo.base(), obj);\n  // TODO(tobias): handle sensor-specific data: if (osi_mo.has_radar_specifics())\n}\n\nvoid from_osi_detected_moving_object_alt(const osi3::DetectedMovingObject& osi_mo,\n                                         const OsiGroundTruth& ground_truth,\n                                         cloe::Object& obj) {\n  // Object id = ground truth id\n  osi_require(\"DetectedMovingObject::header\", osi_mo.has_header());\n  from_osi_detected_item_header(osi_mo.header(), obj);\n\n  // Get ground truth info for this object as fallback for missing data.\n  osi3::MovingObject osi_mo_gt(*(ground_truth.get_moving_object(obj.id)));\n  osi3::MovingObject osi_ego_gt(*(ground_truth.get_moving_object(ground_truth.get_ego_id())));\n  // Transform coordinates to osi detected object convention, i.e. into ego\n  // vehicle frame.\n  osi_transform_base_moving(osi_ego_gt.base(), *(osi_mo_gt.mutable_base()));\n\n  // Object classification\n  if (osi_mo.candidate_size() > 0) {\n    osi_require(\"candidate_size == 1\", osi_mo.candidate_size() == 1);\n    from_osi_mov_obj_type_classification(osi_mo.candidate(0), obj.classification);\n    // TODO(tobias): Need to additionally handle classification probability.\n  } else {\n    from_osi_mov_obj_type_classification(osi_mo_gt, obj.classification);\n  }\n\n  assert(obj.id != static_cast<int>(ground_truth.get_ego_id()));\n  // DetectedMovingObject::base: \"The bounding box does NOT include mirrors for\n  // vehicles. The parent frame of base is the sensor's [vehicle frame].\"\n  from_osi_base_moving_alt(osi_mo.base(), osi_mo_gt.base(), obj);\n  // TODO(tobias): handle sensor-specific data: if (osi_mo.has_radar_specifics())\n}\n\nvoid from_osi_base_moving(const osi3::BaseMoving& osi_bm, cloe::Object& obj) {\n  obj.type = cloe::Object::Type::Dynamic;\n\n  obj.pose = osi_position_orientation_to_pose(osi_bm);\n\n  osi_require(\"BaseMoving::dimension\", osi_bm.has_dimension());\n  obj.dimensions = osi_dimension3d_lwh_to_vector3d(osi_bm.dimension());\n\n  osi_require(\"BaseMoving::acceleration\", osi_bm.has_acceleration());\n  obj.acceleration = osi_vector3d_xyz_to_vector3d(osi_bm.acceleration());\n\n  osi_require(\"BaseMoving::velocity\", osi_bm.has_velocity());\n  obj.velocity = osi_vector3d_xyz_to_vector3d(osi_bm.velocity());\n\n  osi_require(\"BaseMoving::orientation_rate\", osi_bm.has_orientation_rate());\n  obj.angular_velocity = osi_orientation3d_rpy_to_vector3d(osi_bm.orientation_rate());\n}\n\nvoid from_osi_base_moving_alt(const osi3::BaseMoving& osi_bm, const osi3::BaseMoving& osi_bm_gt,\n                              cloe::Object& obj) {\n  obj.type = cloe::Object::Type::Dynamic;\n\n  obj.pose = osi_position_orientation_to_pose_alt(osi_bm, osi_bm_gt);\n\n  assert(osi_bm.has_dimension());\n  obj.dimensions = osi_dimension3d_lwh_to_vector3d(osi_bm.dimension());\n\n  assert(osi_bm.has_acceleration());\n  obj.acceleration = osi_vector3d_xyz_to_vector3d(osi_bm.acceleration());\n\n  assert(osi_bm.has_velocity());\n  obj.velocity = osi_vector3d_xyz_to_vector3d(osi_bm.velocity());\n\n  if (osi_bm.has_orientation_rate()) {\n    obj.angular_velocity = osi_orientation3d_rpy_to_vector3d(osi_bm.orientation_rate());\n  } else {\n    assert(osi_bm_gt.has_orientation_rate());\n    obj.angular_velocity = osi_orientation3d_rpy_to_vector3d(osi_bm_gt.orientation_rate());\n  }\n}\n\ntemplate <typename T>\nvoid from_osi_mov_obj_type_classification(const T& osi_mo, cloe::Object::Class& oc) {\n  if (!osi_mo.has_type()) {\n    throw cloe::ModelError(\"OSI missing moving object type\");\n  }\n\n  if (osi_mo.type() == osi3::MovingObject_Type_TYPE_VEHICLE) {\n    if (!osi_mo.has_vehicle_classification()) {\n      throw cloe::ModelError(\"OSI missing moving vehicle classification\");\n    }\n    if (!osi_mo.vehicle_classification().has_type()) {\n      throw cloe::ModelError(\"OSI missing moving vehicle classification type\");\n    }\n  }\n\n  from_osi_mov_obj_type_classification(osi_mo.type(), osi_mo.vehicle_classification().type(), oc);\n}\n\ntemplate void from_osi_mov_obj_type_classification<osi3::MovingObject>(\n    const osi3::MovingObject& osi_mo, cloe::Object::Class& oc);\ntemplate void\nfrom_osi_mov_obj_type_classification<osi3::DetectedMovingObject::CandidateMovingObject>(\n    const osi3::DetectedMovingObject::CandidateMovingObject& osi_mo, cloe::Object::Class& oc);\n\nvoid from_osi_mov_obj_type_classification(\n    const osi3::MovingObject::Type& osi_ot,\n    const osi3::MovingObject::VehicleClassification::Type& osi_vt,\n    cloe::Object::Class& oc) {\n  if (osi_ot == osi3::MovingObject_Type_TYPE_VEHICLE) {\n    oc = osi_mov_veh_class_map.at(osi_vt);\n  } else {\n    oc = osi_mov_obj_type_map.at(osi_ot);\n  }\n}\n\nvoid transform_ego_coord_from_osi_data(const Eigen::Vector3d& dimensions_gt, cloe::Object& obj) {\n  // obj->pose: Change object position from bbox-center to vehicle reference\n  // point (rear axle/street level):\n  //  - Shift (x,y) to rear axis center using given osi bbcenter_to_rear vector.\n  //  - Shift (z) to street level using bbox half-height.\n  Eigen::Vector3d bbcenter_to_rear_street{obj.cog_offset(0), obj.cog_offset(1),\n                                          -0.5 * dimensions_gt(2)};\n\n  // Transform translation vector from vehicle frame into world frame.\n  Eigen::Vector3d pos_veh_origin =\n      obj.pose.translation() + obj.pose.rotation() * bbcenter_to_rear_street;\n\n  obj.pose.translation() = pos_veh_origin;\n\n  // cog is on street level, i.e. only x-offset is non-zero. Here, the direction\n  // is opposite as defined in the OSI standard.\n  obj.cog_offset = Eigen::Vector3d(-1.0 * obj.cog_offset(0), 0.0, 0.0);\n\n  // Convert ego velocity and acceleration into ego vehicle frame coordinates.\n  obj.velocity = obj.pose.rotation().inverse() * obj.velocity;\n  obj.acceleration = obj.pose.rotation().inverse() * obj.acceleration;\n}\n\nvoid transform_obj_coord_from_osi_data(const Eigen::Isometry3d& sensor_pose,\n                                       const Eigen::Vector3d& dimensions_gt, cloe::Object& obj) {\n  // obj->pose/velocity/acceleration/angular_velocity:\n  // Transform the location and orientation of the detected object from the ego\n  // vehicle frame into the sensor reference frame.\n  Eigen::Vector3d obj_pos_sensor_frame =\n      sensor_pose.rotation().inverse() * (obj.pose.translation() - sensor_pose.translation());\n  obj.pose.translation() = obj_pos_sensor_frame;\n  obj.pose.rotate(sensor_pose.rotation().inverse());\n\n  obj.velocity = sensor_pose.rotation().inverse() * obj.velocity;\n  obj.acceleration = sensor_pose.rotation().inverse() * obj.acceleration;\n  obj.angular_velocity = sensor_pose.rotation().inverse() * obj.angular_velocity;\n\n  // obj->pose: Change the object position reference point from the bounding box\n  // center to the vehicle reference point (rear axle/street level).\n  Eigen::Vector3d bbcenter_to_rear_street{obj.cog_offset(0), obj.cog_offset(1),\n                                          -0.5 * dimensions_gt(2)};\n\n  // Transform translation vector from the object reference frame into the\n  // sensor frame.\n  obj_pos_sensor_frame = obj.pose.translation() + obj.pose.rotation() * bbcenter_to_rear_street;\n\n  obj.pose.translation() = obj_pos_sensor_frame;\n\n  // cog is on street level, i.e. only x-offset is non-zero. Here, the direction\n  // is opposite as defined in the OSI standard.\n  obj.cog_offset = Eigen::Vector3d(-1.0 * obj.cog_offset(0), 0.0, 0.0);\n}\n\nvoid OsiOmniSensor::step(const cloe::Sync& s, const bool& restart, cloe::Duration& sim_time) {\n  // Cycle until sensor data has been received.\n  int n_msg{0};\n  while (n_msg == 0 || restart) {\n    auto osi_msg = osi_comm_->receive_sensor_data();\n    if (osi_msg.size() > 0) {\n      osi_logger()->trace(\"OsiOmniSensor: processing {} messages at Cloe frame no {}\",\n                          osi_msg.size(), s.step());\n      // 1st. timestep: Store the simulation reference (e.g. start) time.\n      this->process(osi_msg[0]->timestamp());\n    }\n    for (auto m : osi_msg) {\n      this->process(m.get(), sim_time);\n      ++n_msg;\n    }\n  }\n\n  if (abs(sim_time.count() - s.time().count()) >= s.step_width().count() / 100) {\n    // Sensor data time deviates from cloe time by more than 1% of the time step.\n    osi_logger()->warn(\"OsiOmniSensor: inconsistent timestamps [t_sensor={}ns, t_cloe={}ns]\",\n                       sim_time.count(), s.time().count());\n  }\n\n  osi_logger()->trace(\"OsiOmniSensor: completed processing messages [frame={}, time={}ns]\",\n                      s.step(), s.time().count());\n}\n\nvoid OsiOmniSensor::process(const osi3::Timestamp& timestamp) {\n  // TODO(tobias): probably needs to be changed for restarts\n  if (init_time_.count() >= 0.0) {\n    return;\n  }\n  init_time_ = osi_timestamp_to_time(timestamp);\n}\n\nvoid OsiOmniSensor::process(osi3::SensorData* osi_sd, cloe::Duration& sim_time) {\n  if (osi_sd == nullptr) {\n    return;\n  }\n\n  if (osi_sd->ByteSize() == 0) {\n    return;\n  }\n\n  osi_require(\"v3.x.x\", !osi_sd->has_version() || osi_sd->version().version_major() > 2);\n\n  // TODO(tobias): handle restart\n\n  // Read the time when the message was sent, which is after capturing and\n  // processing the sensor raw signal.\n  if (osi_sd->has_timestamp()) {\n    sim_time = osi_timestamp_to_simtime(osi_sd->timestamp());\n    osi_logger()->trace(\"OsiOmniSensor: message @ {} ns\", sim_time.count());\n  } else {\n    throw cloe::ModelError(\"OsiOmniSensor: No timestamp in SensorData. FMU properly loaded?\");\n  }\n\n  // Read the time of the ground truth scene that was processed.\n  if (osi_sd->has_last_measurement_time()) {\n    cloe::Duration meas_time = osi_timestamp_to_simtime(osi_sd->last_measurement_time());\n    osi_logger()->trace(\"OsiOmniSensor: measurement @ {} ns\", meas_time.count());\n  } else {\n    osi_logger()->info(\"OsiOmniSensor: last_measurement_time not available in SensorData.\");\n  }\n\n  // Obtain ego data from sensor views (sensor model input), i.e. ground truth.\n  osi_require(\"SensorData::SensorView\", osi_sd->sensor_view_size() > 0);\n  const osi3::MountingPosition* mnt_pos{nullptr};\n  for (int i_sv = 0; i_sv < osi_sd->sensor_view_size(); ++i_sv) {\n    this->process(osi_sd->sensor_view(i_sv));\n    if (osi_sd->sensor_view(i_sv).has_mounting_position()) {\n      mnt_pos = &(osi_sd->sensor_view(i_sv).mounting_position());\n    }\n  }\n\n  if (osi_sd->has_mounting_position()) {\n    // Give higher priority to the sensor model output (SensorData) than to SensorView.\n    mnt_pos = &(osi_sd->mounting_position());\n  }\n\n  // Store sensor mounting position and orientation for reference frame transformations.\n  if (mnt_pos) {\n    osi_sensor_pose_ = osi_position_orientation_to_pose(*mnt_pos);\n  } else {\n    if (this->get_mock_level(SensorMockTarget::MountingPosition) !=\n        SensorMockLevel::OverwriteNone) {\n      osi_sensor_pose_ =\n          get_static_mounting_position(ground_truth_->get_veh_coord_sys_info(owner_id_),\n                                       ground_truth_->get_mov_obj_dimensions(owner_id_));\n    } else {\n      throw cloe::ModelError(\"OSI sensor mounting position is not available\");\n    }\n  }\n\n  if (osi_sd->has_host_vehicle_location()) {\n    // Sensor has its own estimate of the vehicle location, which we could use\n    // to overwrite the ego pose that was taken from ground truth.\n    throw cloe::ModelError(\"OSI host_vehicle_location handling is not yet available\");\n  }\n\n  // Process detected moving objects.\n  for (int i_mo = 0; i_mo < osi_sd->moving_object_size(); ++i_mo) {\n    this->process(osi_sd->has_moving_object_header(), osi_sd->moving_object_header(),\n                  osi_sd->moving_object(i_mo));\n  }\n\n  // TODO(tobias): Process detected stationary objects.\n\n  // Process lane boundaries.\n  switch (this->get_mock_level(SensorMockTarget::DetectedLaneBoundary)) {\n    case SensorMockLevel::OverwriteAll: {\n      mock_detected_lane_boundaries();\n      break;\n    }\n    default: {\n      //  TODO(tobias): Detected road marking handling is not yet available.\n      break;\n    }\n  }\n\n  // TODO(tobias): Process detected lanes once supported by Cloe data model.\n\n  // TODO(tobias): Process detected traffic signs.\n\n  // TODO(tobias): Process detected traffic lights once supported by Cloe data model.\n\n  store_sensor_meta_data(ground_truth_->get_veh_coord_sys_info(owner_id_),\n                         ground_truth_->get_mov_obj_dimensions(owner_id_));\n\n  // Cleanup\n  ground_truth_->reset();\n}\n\nvoid OsiOmniSensor::process(const osi3::SensorView& osi_sv) {\n  if (osi_sv.ByteSize() == 0) {\n    return;\n  }\n\n  // Fill the coordinate system info from ground truth.\n  osi_require(\"SensorView::GroundTruth\", osi_sv.has_global_ground_truth());\n  const osi3::GroundTruth* osi_gt = &(osi_sv.global_ground_truth());\n  ground_truth_->set(*osi_gt);\n\n  for (int i_mo = 0; i_mo < osi_gt->moving_object_size(); ++i_mo) {\n    osi3::MovingObject osi_mo = osi_gt->moving_object(i_mo);\n    int obj_id;\n    from_osi_identifier(osi_mo.id(), obj_id);\n\n    // Store geometric information of different object reference frames.\n    if (osi_mo.has_vehicle_attributes()) {\n      ground_truth_->store_veh_coord_sys_info(obj_id, osi_mo.vehicle_attributes());\n    }\n\n    // Store object bounding box dimensions for cooordinate transformations.\n    osi_require(\"GroundTruth::MovingObject::base\", osi_mo.has_base());\n    if (osi_mo.has_base()) {\n      osi_require(\"GroundTruth-BaseMoving::dimension\", osi_mo.base().has_dimension());\n      ground_truth_->store_mov_obj_dimensions(obj_id, osi_mo.base().dimension());\n    }\n  }\n\n  // Process ego vehicle info. For the ego, we may use ground truth information.\n  // Note: osi.sv.host_vehicle_id() may not be populated.\n  auto osi_ego = ground_truth_->get_moving_object(ground_truth_->get_ego_id());\n  process(osi_sv.has_host_vehicle_data(), osi_sv.host_vehicle_data(), *osi_ego);\n}\n\nvoid OsiOmniSensor::process(const bool has_veh_data, const osi3::HostVehicleData& osi_hv,\n                            const osi3::MovingObject& osi_ego) {\n  auto obj = std::make_shared<cloe::Object>();\n  obj->exist_prob = 1.0;\n  // Object id\n  from_osi_identifier(osi_ego.id(), obj->id);\n  assert(obj->id == static_cast<int>(owner_id_));\n\n  // Ego pose\n  if (has_veh_data) {\n    // Ego data that was explicitly made available to the sensor (e.g. gps\n    // location & rmse).\n    from_osi_host_vehicle_data(osi_hv, *obj);\n  } else {\n    // Use ground truth object information\n    from_osi_base_moving(osi_ego.base(), *obj);\n  }\n\n  // Data extracted from ground truth:\n  //  - Vehicle type\n  from_osi_mov_obj_type_classification(osi_ego, obj->classification);\n  //  - Offset to vehicle frame origin\n  obj->cog_offset = ground_truth_->get_veh_coord_sys_info(obj->id);\n\n  // Store ego pose.\n  osi_ego_pose_ = obj->pose;\n  osi_ego_pose_.translation() = obj->pose.translation() + obj->pose.rotation() * obj->cog_offset;\n\n  // Object attributes are all set:\n  //  - 1a) osi3::HostVehicleData: \"All coordinates and orientations are relative\n  //        to the global ground truth coordinate system.\"\n  //  - 1b) \"All position coordinates refer to the center of the bounding box of\n  //         the object (vehicle or otherwise).\"\n  //  - 2 ) osi3::MovingObject::VehicleAttributes::bbcenter_to_rear: \"The vector\n  //        pointing from the bounding box center point to the middle of the rear\n  //        axle under neutral load conditions. In object coordinates.\"\n  // Now transform the data into the Cloe reference frame convention:\n  //  - 1a) obj->velocity/acceleration: Convert from world frame into vehicle\n  //        frame coordinates.\n  //  - 1b) obj->pose: Change object position from bbox-center to vehicle\n  //        reference point (rear axle/street level).\n  //  - 2 ) obj->cog_offset: cog should be on street level, i.e. only x-offset is\n  //        non-zero. Here, the direction is opposite as defined by OSI.\n  transform_ego_coord_from_osi_data(ground_truth_->get_mov_obj_dimensions(obj->id), *obj);\n  store_ego_object(obj);  // XXX is this fine for multiple sensor views?\n}\n\nvoid OsiOmniSensor::process(const bool has_eh, const osi3::DetectedEntityHeader& osi_eh,\n                            const osi3::DetectedMovingObject& osi_mo) {\n  auto obj = std::make_shared<cloe::Object>();\n\n  // Get object information. The sensor (model) may not provide all required data.\n  if (has_eh) {\n    // TODO(tobias): handle entity header, if needed\n    osi_logger()->warn(\n        \"VtdOsiSensor: DetectedEntityHeader not yet handled. measurement_time = {}ns\",\n        osi_timestamp_to_simtime(osi_eh.measurement_time()).count());\n  }\n  switch (this->get_mock_level(SensorMockTarget::DetectedMovingObject)) {\n    case SensorMockLevel::OverwriteNone: {\n      from_osi_detected_moving_object(osi_mo, *obj);\n      break;\n    }\n    case SensorMockLevel::InterpolateMissing: {\n      from_osi_detected_moving_object_alt(osi_mo, *ground_truth_, *obj);\n      break;\n    }\n    case SensorMockLevel::OverwriteAll: {\n      throw cloe::ModelError(\n          \"OSI SensorMockLevel::OverwriteAll not available for DetectedMovingObject\");\n      break;\n    }\n  }\n\n  assert(obj->id != static_cast<int>(owner_id_));\n\n  // Offset to the vehicle frame origin\n  obj->cog_offset = ground_truth_->get_veh_coord_sys_info(obj->id);\n\n  // Object attributes are all set:\n  //  - 1a) DetectedMovingObject::base: \"The parent frame of base is the sensor's\n  //        [vehicle frame].\"\n  //  - 1b) \"All position coordinates refer to the center of the bounding box of\n  //         the object (vehicle or otherwise).\"\n  //  - 2 ) osi3::MovingObject::VehicleAttributes::bbcenter_to_rear: \"The vector\n  //        pointing from the bounding box center point to the middle of the rear\n  //        axle under neutral load conditions. In object coordinates.\"\n  // Now transform the data to the Cloe reference frame:\n  //  - 1a) obj->pose/velocity/acceleration/angular_velocity: Transform detected\n  //        object location from the ego vehicle frame into the sensor frame.\n  //  - 1b) obj->pose: Change object position from bbox-center to vehicle\n  //        reference point (rear axle/street level).\n  //  - 2 ) obj->cog_offset: cog should be on street level, i.e. only x-offset is\n  //        non-zero. Here, the direction is opposite as defined by OSI.\n  transform_obj_coord_from_osi_data(osi_sensor_pose_,\n                                    ground_truth_->get_mov_obj_dimensions(obj->id), *obj);\n\n  // Fill the object list\n  store_object(obj);\n}\n\nvoid OsiOmniSensor::from_osi_boundary_points(const osi3::LaneBoundary& osi_lb,\n                                             cloe::LaneBoundary& lb) {\n  assert(osi_lb.boundary_line_size() > 0);\n  for (int i = 0; i < osi_lb.boundary_line_size(); ++i) {\n    const auto& osi_pt = osi_lb.boundary_line(i);\n    Eigen::Vector3d position = osi_vector3d_xyz_to_vector3d(osi_pt.position());\n    // Transform points from the inertial into the sensor reference frame.\n    cloe::utility::transform_to_child_frame(osi_ego_pose_, &position);\n    cloe::utility::transform_to_child_frame(osi_sensor_pose_, &position);\n    lb.points.push_back(position);\n  }\n  // Compute clothoid segment. TODO(tobias): implement curved segments.\n  lb.dx_start = lb.points.front()(0);\n  lb.dy_start = lb.points.front()(1);\n  lb.heading_start = std::atan((lb.points.back()(1) - lb.points.front()(1)) /\n                               (lb.points.back()(0) - lb.points.front()(0)));\n  lb.curv_hor_start = 0.0;\n  lb.curv_hor_change = 0.0;\n  lb.dx_end = lb.points.back()(0);\n}\n\nvoid OsiOmniSensor::mock_detected_lane_boundaries() {\n  const auto& osi_gt = ground_truth_->get_gt();\n  int lb_id = 0;\n  // If some of the OSI data does not have an id, avoid id clashes.\n  for (const auto& osi_lb : osi_gt.lane_boundary()) {\n    if (osi_lb.has_classification() && osi_lb.has_id()) {\n      int id;\n      from_osi_identifier(osi_lb.id(), id);\n      lb_id = std::max(lb_id, id + 1);\n    }\n  }\n  // Set lane boundary data.\n  for (const auto& osi_lb : osi_gt.lane_boundary()) {\n    if (osi_lb.has_classification()) {\n      cloe::LaneBoundary lb;\n      if (osi_lb.has_id()) {\n        from_osi_identifier(osi_lb.id(), lb.id);\n      } else {\n        lb.id = lb_id;\n      }\n      lb.exist_prob = 1.0;\n      lb.prev_id = -1;  // no concatenated line segments for now\n      lb.next_id = -1;\n      ++lb_id;\n      from_osi_boundary_points(osi_lb, lb);\n      lb.type = osi_lane_bdry_type_map.at(osi_lb.classification().type());\n      lb.color = osi_lane_bdry_color_map.at(osi_lb.classification().color());\n      store_lane_boundary(lb);\n    }\n  }\n}\n\n}  // namespace osii\n", "meta": {"hexsha": "ad2086f330c7f9037e9ce27ebc6f8eff9b354c5e", "size": 30067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugins/vtd/src/osi_omni_sensor.cpp", "max_stars_repo_name": "Sidharth-S-S/cloe", "max_stars_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T18:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:35:28.000Z", "max_issues_repo_path": "plugins/vtd/src/osi_omni_sensor.cpp", "max_issues_repo_name": "Sidharth-S-S/cloe", "max_issues_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-20T10:13:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:27:19.000Z", "max_forks_repo_path": "plugins/vtd/src/osi_omni_sensor.cpp", "max_forks_repo_name": "Sidharth-S-S/cloe", "max_forks_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T08:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T10:09:53.000Z", "avg_line_length": 44.41211226, "max_line_length": 101, "alphanum_fraction": 0.7101473376, "num_tokens": 7760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.19761247031823972}}
{"text": "#ifndef __WALD_SEPARATE_METHOD_H__\n#define __WALD_SEPARATE_METHOD_H__\n\n#include <string>\n#include <vector>\n\n#include <armadillo>\n\n#include <besiq/method/method.hpp>\n#include <besiq/stats/log_scale.hpp>\n\n/**\n * This class is responsible for executing the closed form\n * wald test for a logistic regression model.\n */\nclass wald_separate_method\n: public method_type\n{\npublic:\n    /**\n     * Constructor.\n     *\n     * @param data Additional data required by all methods, such as\n     *             covariates.\n     */\n    wald_separate_method(method_data_ptr data, bool is_lm);\n    \n    /**\n     * @see method_type::init.\n     */\n    virtual std::vector<std::string> init();\n    \n    /**\n     * @see method_type::run.\n     */\n    virtual double run(const snp_row &row1, const snp_row &row2, float *output);\nprivate:\n    void compute_lm(const snp_row &row1, const snp_row &row2, float *output);\n    void compute_binomial(const snp_row &row1, const snp_row &row2, float *output);\n    /**\n     * Weight for each sample.\n     */\n    arma::vec m_weight;\n\n    /**\n     * Indicates whether this is a linear model or not.\n     */\n    bool m_is_lm;\n};\n\n#endif /* End of __WALD_SEPARATE_METHOD_H__ */\n", "meta": {"hexsha": "f5cfbbd62930883645ae32fa9471b04e7b2a5724", "size": 1189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/besiq/method/wald_separate_method.hpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/besiq/method/wald_separate_method.hpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/besiq/method/wald_separate_method.hpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 22.8653846154, "max_line_length": 83, "alphanum_fraction": 0.6560134567, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1976124685999784}}
{"text": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"main.hpp\"\n#include \"imagereconstruct.hpp\"\n#include \"image.hpp\"\n#include \"segments.hpp\"\n#include \"descriptors.hpp\"\n#include \"classify.hpp\"\n#include \"misc.hpp\"\n\nusing namespace std;\nusing namespace cv;\nnamespace fs = boost::filesystem;\n\nint main(int argc, char ** argv) {\n    const int RESIZE_FACTOR = 2;\n    const string DATA_PATH = \"/workspace/steam/opencv-steam-captcha/data\";\n    const string OUTPUT_PATH = \"/workspace/steam/opencv-steam-captcha/output/\";\nint notX=1;\n    // 0, 1, 5, 6, I, O and S are never used\n    const string ALLOWED_CHARS = \"234789ABCDEFGHJKLMNPQRTUVWXYZ@&%\";\n\n    // Images\n    Mat sourceImage, finalImage, histogramImage;\n    Mat histogram;\n\n    // Initialize character counters\n    map < string, int > counter;\n    for (int i = 0; i < ALLOWED_CHARS.length(); i++) {\n      string letter(1, ALLOWED_CHARS[i]);\n      counter[letter] = 0;\n    }\n\n    // Check if data folder exists\n    fs::path folder(DATA_PATH);\n    if (!exists(folder))\n      return -1;\n\n    // Create output folder structure\n    if (!createFolderStructure(OUTPUT_PATH, ALLOWED_CHARS))\n      return -1;\n\n    fs::directory_iterator endItr;\n    for (fs::directory_iterator itr(folder); itr != endItr; itr++) {\n      string fullPath = itr -> path().string();\n      string fileName = itr -> path().filename().string();\n\n      // Skip all dot files\n      if (fileName[0] == '.')\n        continue;\n\n      // Retrieve captcha string\n      string captchaCode = boost::replace_all_copy(fileName, \".png\", \"\");\n      captchaCode = aliasToSpecialChar(captchaCode);\n\n      // Load our base image\n      sourceImage = imread(fullPath, CV_LOAD_IMAGE_GRAYSCALE);\n\n      // Is it loaded?\n      if (!sourceImage.data)\n        return -1;\n\n      // Resize the image by resize factor\n      resize(sourceImage, sourceImage, Size(sourceImage.cols * RESIZE_FACTOR, sourceImage.rows * RESIZE_FACTOR));\n\n      // Define our final image\n      finalImage = sourceImage.clone();\n\n      // Apply adaptive threshold\n      //adaptiveThreshold(finalImage, finalImage, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, 1);\n\n      // Use the thresholded image as a mask\n      Mat tmp;\n      sourceImage.copyTo(tmp, finalImage);\n      tmp.copyTo(finalImage);\n      tmp.release();\n\n      // Let's calculate histogram for our image\n      histogram = createHistogram(finalImage);\n\n      // Calculate final threshold value\n      int thresholdValue = getIdealThreshold(histogram);\n\n      // Draw histogram image\n      histogramImage = drawHistogram(histogram, thresholdValue);\n\n      // Apply binary threshold\n      //threshold(finalImage, finalImage, thresholdValue, 255, THRESH_BINARY);\n\n      // Morphological closing\n      Mat element = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));\n      dilate(finalImage, finalImage, element);\n      erode(finalImage, finalImage, element);\n\n\t  \n      // Segments\n      int * segH = horizontalSegments(finalImage);\n      int * segV = verticalSegments(finalImage);\n\n      Mat segHImage = drawHorizontalSegments(segH, finalImage.rows, finalImage.cols);\n      Mat segVImage = drawVerticalSegments(segV, finalImage.rows, finalImage.cols);\n\n      // Create pairs\n      vector < pair < int, int > > verticalPairs = filterVerticalPairs(createSegmentPairs(segV, finalImage.rows));\n      vector < pair < int, int > > horizontalPairs = splitLarge(filterHorizontalPairs(createSegmentPairs(segH, finalImage.cols), finalImage.cols));\n\n      // Get segment squares\n      vector < Rectangle > squares = takeRectangles(shrinkRectangles(finalImage, getRectangles(verticalPairs, horizontalPairs)), 6);\n\n      // Save the squares\n      saveRectangles(sourceImage, squares, OUTPUT_PATH, captchaCode, counter);\n      // Let's draw the rectangles\n      drawRectangles(finalImage, squares);\n      drawRectangles(sourceImage, squares);\n\n      // Display the images if necessary\n\n\t  if(notX ==12){\n       imshow(\"Final image\", finalImage);\n       imshow(\"Source image\", sourceImage);\n       imshow(\"HSeg\", segHImage);\n       imshow(\"VSeg\", segVImage);\n       imshow(\"Histogram\", histogramImage);\n       waitKey();\n\t   notX=2;\n\t}\n      sourceImage.release();\n      finalImage.release();\n    }\n\n    Mat trainingData, classLabels;\n\n    // Create training data\n    getSimpleTrainingData(trainingData, classLabels, OUTPUT_PATH, \"G\", \"Y\", 10);\n\n    // This part is highly simplified and was mostly done just to test\n    // classification based on two characters with the highest frequency\n    CvSVMParams params;\n    params.svm_type = CvSVM::C_SVC;\n    params.kernel_type = CvSVM::LINEAR;\n    params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);\n\n    CvSVM SVM;\n    SVM.train(trainingData, classLabels, Mat(), Mat(), params);\n\n    int success = 0;\n\tint fail=0;\n    for (int i = 0; i < 10; i++) {\n\n      Mat letterImage = imread(OUTPUT_PATH + \"2/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      float result = classify(SVM, letterImage);\n      if (result == 1) {\n        cout << \"2 classified as: 2\" << endl;\n        success++;\n      } else {\n\t\tcout << \"!!! 2 misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n fail++;\n      }\n\t  letterImage.release();\n\n\t  letterImage = imread(OUTPUT_PATH + \"3/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      result = classify(SVM, letterImage);\n      if (result == 2) {\n        cout << \"3 classified as: 3\" << endl;\n        success++;\n      } else {\n\t\t  \t\tcout << \"!!! 3 misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n fail++;\n      }\n      letterImage.release();\n\tletterImage = imread(OUTPUT_PATH + \"4/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      result = classify(SVM, letterImage);\n      if (result == 3) {\n        cout << \"4 classified as: 4\" << endl;\n        success++;\n      } else {\n\t\t  \t\tcout << \"!!! 4 misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n\t\t\n fail++;\n      }\n      letterImage.release();\n\t  \n\t  \n\t  letterImage = imread(OUTPUT_PATH + \"7/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      result = classify(SVM, letterImage);\n      if (result == 4) {\n        cout << \"7 classified as: 7\" << endl;\n        success++;\n      } else {\n\t\t  \t\tcout << \"!!! 7 misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n fail++;\n      }\n      letterImage.release();\n\t  \n\t  letterImage = imread(OUTPUT_PATH + \"8/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      result = classify(SVM, letterImage);\n      if (result == 5) {\n        cout << \"8 classified as: 8\" << endl;\n        success++;\n      } else {\n\t\t  \t\tcout << \"!!! 8 misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n fail++;\n      }\n      letterImage.release();\n\t  \n\t  letterImage = imread(OUTPUT_PATH + \"9/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      result = classify(SVM, letterImage);\n      if (result == 6) {\n        cout << \"9 classified as: 9\" << endl;\n        success++;\n      } else {\n\t\t  \t\tcout << \"!!! 9 misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n fail++;\n      }\n      letterImage.release();\n\t  \n\t  letterImage = imread(OUTPUT_PATH + \"and/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      result = classify(SVM, letterImage);\n      if (result == 33) {\n        cout << \"& classified as: &\" << endl;\n        success++;\n      } else {\n\t\t  \t\tcout << \"!!! & misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n fail++;\n      }\n      letterImage.release();\n\t  \n\t  letterImage = imread(OUTPUT_PATH + \"at/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      result = classify(SVM, letterImage);\n      if (result == 34) {\n        cout << \"@ classified as: @\" << endl;\n        success++;\n      } else {\n\t\t  \t\tcout << \"!!! @ misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n fail++;\n      }\n      letterImage.release();\n  \n\n  \t  letterImage = imread(OUTPUT_PATH + \"pct/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n      result = classify(SVM, letterImage);\n      if (result == 35) {\n        cout << \"% classified as: %\" << endl;\n        success++;\n      } else {\n\t\t  \t\tcout << \"!!! % misrecognised\" << endl;\n\n        // cout << \"FAIL G\" << endl; \n fail++;\n      }\n      letterImage.release();\n  \n\n     \n\t  for (int tmp = 66; tmp <= 90; tmp++) {\n        if (tmp == 73 || tmp == 79 || tmp == 83)\n          continue;\n        else {\n\n          letterImage = imread(OUTPUT_PATH + char(tmp)+\"/\" + to_string(i) + \".png\", CV_LOAD_IMAGE_GRAYSCALE);\n          result = classify(SVM, letterImage);\n          //cout<<\"R: \"<<result<<endl;\n\n          if (result == tmp-66+8) {\n            cout << \"Letter \"<<char(tmp)<<\" classified as: \"<<char(result-7+65) << endl;\n            success++;\n          } else {\n            // cout << \"FAIL Y\" << endl;\n\t\t\t            cout << \"!!!Letter \"<<char(tmp)<<\" classified as: \"<<char(result-7+65) <<\"[R:\"<<result<<\"]\"<<endl;\n\t\t\t\t\t\tfail++;\n          }\n          letterImage.release();\n\n        }\n\n      }\n\t\n\t \n\t \n      trainingData.release();\n      classLabels.release();\n}\nfloat rate = ((success*100/(success+fail)));\n      cout << \"Success rate: \" << success << \"/\" << (success+fail) <<\" = \"<< rate<<\"%\"<< endl;\n\n      return 0;\n    }", "meta": {"hexsha": "fc7d51eb6b7a41bf74a9d7b6a57e1a5d756b2a40", "size": 9296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Ashesh3/steamCapRecog", "max_stars_repo_head_hexsha": "390113668db373dcb20cb20ca7d275992365c973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-01T20:35:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-01T20:35:01.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "Ashesh3/steamCapRecog", "max_issues_repo_head_hexsha": "390113668db373dcb20cb20ca7d275992365c973", "max_issues_repo_licenses": ["MIT"], "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": "Ashesh3/steamCapRecog", "max_forks_repo_head_hexsha": "390113668db373dcb20cb20ca7d275992365c973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-22T02:06:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T21:59:29.000Z", "avg_line_length": 30.1818181818, "max_line_length": 147, "alphanum_fraction": 0.5913296041, "num_tokens": 2367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1976124685999784}}
{"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\n#include <cmath>\n#include <Eigen/Eigen>\n#include <comma/base/exception.h>\n#include \"../rotation_matrix.h\"\n#include \"polytope.h\"\n\nnamespace snark { namespace geometry {\n\nconvex_polytope::convex_polytope( const std::vector< Eigen::VectorXd >& normals, const std::vector< double >& distances )\n    : normals_( normals.size(), normals[0].size() )\n    , distances_( distances.size() )\n{\n    if( !normals.size() || !normals[0].size() ) { COMMA_THROW( comma::exception, \"normals cannot be empty or have zero dimensions\" ); }\n    if( normals.size() != distances.size() ) { COMMA_THROW( comma::exception, \"normals and distances should be of same size, got \"<< normals.size()<<\" normals and \" << distances.size() << \" distances\" ); }\n    for( unsigned int i = 0; i < normals.size(); ++i )\n    {\n        normals_.row( i ) = normals[i].transpose().normalized();\n        distances_( i ) = distances[i];\n    }\n}\n\nconvex_polytope::convex_polytope( const Eigen::MatrixXd& normals, const Eigen::VectorXd& distances )\n    : normals_( normals )\n    , distances_( distances )\n{\n    if( !normals.size() ) { COMMA_THROW( comma::exception, \"normals cannot be empty\" ); }\n    if( normals.rows() != distances.size() ) { COMMA_THROW( comma::exception, \"normals and distances should be of same size, got \"<< normals.rows() << \" normals and \" << distances.size() << \" distances\" ); }\n    for( unsigned int i = 0; i < normals.rows(); ++i ) { normals_.row( i ).normalize(); }\n}\n\nconvex_polytope convex_polytope::transformed( const Eigen::Vector3d& translation, const snark::roll_pitch_yaw& orientation ) const\n{\n    convex_polytope p( *this );\n    const Eigen::MatrixXd& rotation_matrix = snark::rotation_matrix::rotation( orientation );\n    for( unsigned int i = 0; i < normals_.rows(); ++i ) // todo: quick and dirty; can it be done in a single operation?\n    {\n        p.normals_.row( i ) = rotation_matrix * normals_.row( i ).transpose();\n        const Eigen::VectorXd& n = p.normals_.row( i );\n        p.distances_[i] = n.dot( n * distances_[i] + translation );\n    }\n    return p;\n}\n\nbool convex_polytope::has( const Eigen::VectorXd &rhs, double epsilon ) const\n{\n    if( rhs.size() != normals_.cols() ) { COMMA_THROW( comma::exception, \"expected same dimension as polytope: \"<< normals_.cols()<<\"; got dimension: \" << rhs.size() ); }\n    return ( ( normals_ * rhs - distances_ ).array() <= epsilon ).all();\n}\n\n} } // namespace snark{ { namespace geometry {\n", "meta": {"hexsha": "643dd008de3104c8b9674c0d86e8f7b8b0d4289f", "size": 4200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/geometry/polytope.cpp", "max_stars_repo_name": "mission-systems-pty-ltd/snark", "max_stars_repo_head_hexsha": "2bc8a20292ee3684d3a9897ba6fee43fed8d89ae", "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/polytope.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "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/polytope.cpp", "max_forks_repo_name": "NEU-LC/snark", "max_forks_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "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": 51.8518518519, "max_line_length": 207, "alphanum_fraction": 0.7028571429, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1976124685999784}}
{"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_DEFINITION_SHR_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DEFINITION_SHR_HPP_INCLUDED\n\n#include <boost/simd/config.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.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    BOOST_DISPATCH_MAKE_TAG(ext, shr_, boost::dispatch::elementwise_<shr_>);\n  }\n\n  namespace ext\n  {\n    BOOST_DISPATCH_FUNCTION_DECLARATION(tag, shr_);\n  }\n\n  BOOST_DISPATCH_CALLABLE_DEFINITION(tag::shr_,shr);\n\n\n} }\n\n#endif\n", "meta": {"hexsha": "eda61a6065d92ff0d13d0ca7655a7a661d3d727e", "size": 989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/definition/shr.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/function/definition/shr.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/definition/shr.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": 26.7297297297, "max_line_length": 100, "alphanum_fraction": 0.6147623862, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.19761246126826595}}
{"text": "//\n// Copyright (c) 2017 CNRS\n//\n// This file is part of tsid\n// tsid is free software: you can redistribute it\n// and/or modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation, either version\n// 3 of the License, or (at your option) any later version.\n// tsid 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 GNU\n// General Lesser Public License for more details. You should have\n// received a copy of the GNU Lesser General Public License along with\n// tsid If not, see\n// <http://www.gnu.org/licenses/>.\n//\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\n#include <tsid/math/utils.hpp>\n#include \"tsid/robots/robot-wrapper.hpp\"\n\n\nusing namespace tsid;\nusing namespace tsid::robots;\nusing namespace std;\nusing namespace pinocchio;\n\ntypedef pinocchio::Motion Motion;\n\n\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_set_gravity )\n{\n\t\n  const string romeo_model_path = TSID_SOURCE_DIR\"/models/romeo\";\n\t\n  vector<string> package_dirs;\n  package_dirs.push_back(romeo_model_path);\n  string urdfFileName = package_dirs[0] + \"/urdf/romeo.urdf\";\n  RobotWrapper robot(urdfFileName,\n                     package_dirs,\n                     pinocchio::JointModelFreeFlyer(),\n                     false);\n\n\n  Motion g = pinocchio::Motion::Zero();\n  Motion init_gravity = robot.model().gravity;\n \n  robot.setGravity(g);\n  \n  Motion no_gravity = robot.model().gravity;\n  \n  \n  BOOST_CHECK(no_gravity != init_gravity);\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "23024c2dfc149c9a1f608f328e1370698f6f89bc", "size": 1704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/set_gravity.cpp", "max_stars_repo_name": "hucebot/tsid", "max_stars_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 74.0, "max_stars_repo_stars_event_min_datetime": "2017-10-19T08:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T16:31:17.000Z", "max_issues_repo_path": "tests/set_gravity.cpp", "max_issues_repo_name": "hucebot/tsid", "max_issues_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 123.0, "max_issues_repo_issues_event_min_datetime": "2017-06-16T14:10:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:04:32.000Z", "max_forks_repo_path": "tests/set_gravity.cpp", "max_forks_repo_name": "hucebot/tsid", "max_forks_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2017-11-24T15:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T11:10:34.000Z", "avg_line_length": 25.8181818182, "max_line_length": 71, "alphanum_fraction": 0.7224178404, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.19758572421365608}}
{"text": "#include <iostream>\n\n#include <vector>\nusing namespace std;\n\n#include <boost/timer.hpp>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"DM_NRG.hpp\"\n\n\nvoid DM_NRG_CalcRhoN(vector<double> ParamsTemp,\n\t\t     bool UseFDM,CNRGbasisarray* pAcutN,\n\t\t     CNRGbasisarray* pAcutNp1,\n\t\t     CNRGbasisarray* pAbasisNp1,\n\t\t     CNRGmatrix* pRhoN,\n\t\t     CNRGmatrix* pRhoNp1){\n\n  // New routine, which rotates the matrix first with uBLAS (!)\n  // FASTER... like a Ferrari compared to an old Volkswagen beetle.\n\n  vector< vector<int> > ChildSt_SameType;\n  vector< vector<int> >::iterator arrayit;\n  vector<int>::iterator iit;\n\n  //Trace...\n  double trace=0.0;\n  double traceKK=0.0;\n  double traceDD=0.0;\n\n  // Check time\n  boost::timer MyTime;\n  double time_elapsed;\n\n  bool debug=false;\n\n  CNRGmatrix RhoNp1basis;\n\n  double TempBar=ParamsTemp[0];\n  double ZNdisc=ParamsTemp[1];\n  double betabar=1/TempBar;\n\n\n  cout << \" DM-NRG: Calculating Rho N ...\" << endl;\n\n  cout << \" Rotating Rho N... \" << endl;\n\n  MyTime.restart();\n  RotateMatrix(pRhoNp1,pAcutNp1,(&RhoNp1basis));\n  time_elapsed=MyTime.elapsed();\n\n  cout << \" ... done in \" << time_elapsed << \" secs. \" << endl;\n\n  int ThisBl=0;\n//   if (pAcutN->Nshell==4){\n//     cout << \" Rho_N=5: \" << endl;\n//     pRhoNp1->PrintAllBlocks();\n// //     pRhoNp1->PrintMatBlock(11,11);\n// //     RhoNp1basis.PrintMatBlock(11,11);\n//     ThisBl=11;\n//     cout << \" ibl = \" << ThisBl << endl;\n//     cout << \" pAcutNp1 block structure: \" << endl;\n//     pAcutNp1->PrintBlockQNumbers(ThisBl);\n//     cout << \" Block \" << ThisBl << \" goes from ist = \" \n// \t << pAcutNp1->GetBlockLimit(ThisBl,0) \n// \t << \" to \"\n// \t << pAcutNp1->GetBlockLimit(ThisBl,1)\n// \t << endl;\n//     cout << \" RhoNp1basis block structure: \" << endl;\n//     RhoNp1basis.PrintBlockQNumbers(ThisBl);\n//     cout << \" Block \" << ThisBl << \" goes from ist = \" \n// \t << RhoNp1basis.GetBlockLimit(ThisBl,0) \n// \t << \" to \"\n// \t << RhoNp1basis.GetBlockLimit(ThisBl,1)\n// \t << endl;\n//     ThisBl=18;\n//     cout << \" pAbasisNp1 block structure: \" << endl;\n// //     pAbasisNp1->PrintBlockQNumbers(ThisBl);\n// //     cout << \" Block \" << ThisBl << \" goes from ist = \" \n// // \t << pAbasisNp1->GetBlockLimit(ThisBl,0) \n// // \t << \" to \"\n// // \t << pAbasisNp1->GetBlockLimit(ThisBl,1)\n// // \t << endl;\n// //     pAbasisNp1->PrintBlockBasis(ThisBl);\n//   }\n  \n  // Initial set up\n  pRhoN->ClearAll();\n  pRhoN->SyncNRGarray(*pAcutN);\n  pRhoN->UpperTriangular=true;\n  pRhoN->IsComplex=pRhoNp1->IsComplex;\n\n  // Calculate matrix elements\n  int i1=0;\n  for (int ibl=0;ibl<pAcutN->NumBlocks();ibl++){\n\n\n    // Rho is block diagonal\n    pRhoN->MatBlockMap.push_back(ibl);\n    pRhoN->MatBlockMap.push_back(ibl);\n    pRhoN->MatBlockBegEnd.push_back(i1);\n    \n    int ist0=pAcutN->GetBlockLimit(ibl,0);\n    int ist1=pAcutN->GetBlockLimit(ibl,1);\n\n    // testing...\n\n    // Get Sold from ibl\n\n\n\n    int BlSize=pAcutN->GetBlockSize(ibl);\n    if (debug)\n      cout << \" Setting Block \" << ibl << \" of \" << pAcutN->NumBlocks()-1\n\t   << \"  Size : \" << BlSize << \" ... \"; \n\n    MyTime.restart();\n    // Loop in block states (and calculate rhoN(ist,jst))\n    for (int ist=ist0;ist<=ist1;ist++){\n      for (int jst=ist;jst<=ist1;jst++){\n\n\n\t// Ok, watch out for the \" type\" thing for SU(2) symmetry\n\n\tDM_NRG_SetChildSameType(ist,jst,pAcutN,pAbasisNp1,ChildSt_SameType);\n\n\tdouble auxMatEl=0.0;\n\tcomplex<double> cMatEl=ZeroC;\n\t// Loop over blocks in ChildSt_SameType (N+1)\n\tfor (arrayit=ChildSt_SameType.begin();\n\t     arrayit<ChildSt_SameType.end();arrayit++){\n\t  iit=(*arrayit).begin();\n\t  int iblbasis_Np1=(*iit);\n\t  int istbasis_Np1=(*(iit+1));\n\t  int jstbasis_Np1=(*(iit+2));\n\n\t  // Get S_Np1 from iblbasis_Np1\n\t  // Get S_type= from istbasis_Np1\n\t  // Calculate Clebsh-Gordan coefs.\n\n\n\t  //\n\t  // No need to find corresponding block in AcutNp1:\n\t  //\n\t  // if block is not there, then \n\t  // RhoNp1basis.GetMatEl(istbasis_Np1,jstbasis_Np1)\n\t  // will return 0.0 (in principle!)\n\t  // \n\n\t  if (!(RhoNp1basis.IsComplex))\n\t    auxMatEl+=RhoNp1basis.GetMatEl(istbasis_Np1,jstbasis_Np1);\n\t  else\n\t    cMatEl+=RhoNp1basis.cGetMatEl(istbasis_Np1,jstbasis_Np1);\n\t    \n\n//  \t  if ( (debug)&&(iblbasis_Np1==18)&&(ist==jst) ){\n// \t    cout << \" ibl = \" << ibl  \n// \t\t << \" ist = \" << ist\n// \t\t << \" jst = \" << jst\n// \t\t << \" iblbasis_Np1 = \" << iblbasis_Np1\n// \t\t << \" istbasis_Np1 = \" << istbasis_Np1\n// \t\t << \" jstbasis_Np1 = \" << jstbasis_Np1\n// \t\t << \" mat el = \" << RhoNp1basis.GetMatEl(istbasis_Np1,jstbasis_Np1)\n// \t\t << \" auxMatEl = \" << auxMatEl\n// \t\t << endl; \n// \t  }\n\n\n\t}\n\t// end loop in Child states\n\t// What if states are NOT kept\n\t// // Diagonal only\n\tif ( (UseFDM)&&(jst==ist)&&(pAcutN->CheckKept(ist,false)) ){\n// \t  cout << \" Disc-disc : ist=\" << ist <<  endl;\n// \t  cout << \" size ChildSt[ist]= \" << pAcutN->ChildStates[ist].size();\n\t  if ( dNEqual(ZNdisc,0.0) )\n\t    auxMatEl=exp(-betabar*(pAcutN->dEn[ist]))/ZNdisc;\n// \t  cout << \" auxMatEl= \" << auxMatEl;\n//\t  cout << endl;\n\t}\n\t// end if discarded, discarded\n\n\t\n\tif (ist==jst){\n\t  trace+=auxMatEl;\n\t  if (pAcutN->Kept[ist]) traceKK+=auxMatEl;\n\t  else traceDD+=auxMatEl;\n\n\n\t}\n\t// diagonal terms\n\tif (!(pRhoN->IsComplex))\t  \n\t  pRhoN->MatEl.push_back(auxMatEl);\n\telse\n\t  pRhoN->MatElCplx.push_back(cMatEl);\n\t  \n\ti1++;\n      }\n      // end loop in jst\n    }\n    // end loop in ist\n    pRhoN->MatBlockBegEnd.push_back(i1-1);\n\n\n    time_elapsed=MyTime.elapsed();\n    if (debug)\n     cout << \" ... done in \" << time_elapsed << \" secs.\" << endl;\n\n  }\n  // end loop in pAcutN blocks\n\n  cout << \" ... Rho N  done. \" << endl;\n  cout << \" Trace = \" << trace \n       << \" TraceKK = \" << traceKK \n       << \" TraceDD = \" << traceDD << endl;\n\n\n//   if (pAcutN->Nshell==4){\n//     cout << \" Rho_N=4: \" << endl;\n//     //pRhoN->PrintMatBlock(10,10);\n//     ThisBl=10;\n//     cout << \" ibl = \" << ThisBl << endl;\n//     cout << \" pRhoN block structure: \" << endl;\n//     pRhoN->PrintBlockQNumbers(ThisBl);\n//     cout << \" Block \" << ThisBl << \" goes from ist = \" \n// \t << pRhoN->GetBlockLimit(ThisBl,0) \n// \t << \" to \"\n// \t << pRhoN->GetBlockLimit(ThisBl,1) \n// \t << endl;\n//     //pRhoN->PrintMatBlock(13,13);\n//     ThisBl=13;\n//     cout << \" ibl = \" << ThisBl << endl;\n//     cout << \" pRhoN block structure: \" << endl;\n//     pRhoN->PrintBlockQNumbers(ThisBl);\n//     cout << \" Block \" << ThisBl << \" goes from ist = \" \n// \t << pRhoN->GetBlockLimit(ThisBl,0) \n// \t << \" to \"\n// \t << pRhoN->GetBlockLimit(ThisBl,1) \n// \t << endl;\n//   }\n\n}\n// end set RhoN new\n\n\n/////////////////////////////////////////\n/////   Version with SU(2) symmetry /////\n/////////////////////////////////////////\n\n\nvoid DM_NRG_CalcRhoN_withSU2(vector<double> ParamsTemp,\n\t\t\t     bool UseFDM,\n\t\t\t     CNRGbasisarray* pAcutN,\n\t\t\t     CNRGbasisarray* pAcutNp1,\n\t\t\t     CNRGbasisarray* pAbasisNp1,\n\t\t\t     CNRGbasisarray* pSingleSite,\n\t\t\t     CNRGmatrix* pRhoN,\n\t\t\t     CNRGmatrix* pRhoNp1){\n\n  // New routine, which rotates the matrix first with uBLAS (!)\n  // FASTER... like a Ferrari compared to an old Volkswagen beetle.\n\n  vector< vector<int> > ChildSt_SameType;\n  vector< vector<int> >::iterator arrayit;\n  vector<int>::iterator iit;\n\n  // Check time\n  boost::timer MyTime;\n  double time_elapsed;\n\n  //Trace...\n  double trace=0.0;\n\n  bool debug=false;\n\n  CNRGmatrix RhoNp1basis;\n\n  double TempBar=ParamsTemp[0];\n  double ZNdisc=ParamsTemp[1];\n  double betabar=1/TempBar;\n\n\n\n  cout << \" DM-NRG: Calculating Rho N (w SU(2))...\" << endl;\n\n  cout << \" Rotating Rho N... \" << endl;\n\n  MyTime.restart();\n  RotateMatrix(pRhoNp1,pAcutNp1,(&RhoNp1basis));\n  time_elapsed=MyTime.elapsed();\n\n  cout << \" ... done in \" << time_elapsed << \" secs. \" << endl;\n\n  int ThisBl=0;\n  \n  // Initial set up\n  pRhoN->ClearAll();\n  pRhoN->SyncNRGarray(*pAcutN);\n  pRhoN->UpperTriangular=true;\n\n  // Calculate matrix elements\n  int i1=0;\n  for (int ibl=0;ibl<pAcutN->NumBlocks();ibl++){\n\n\n    // Rho is block diagonal\n    pRhoN->MatBlockMap.push_back(ibl);\n    pRhoN->MatBlockMap.push_back(ibl);\n    pRhoN->MatBlockBegEnd.push_back(i1);\n    \n    int ist0=pAcutN->GetBlockLimit(ibl,0);\n    int ist1=pAcutN->GetBlockLimit(ibl,1);\n\n    // testing...\n\n    // Get Sold from ibl\n    double Sold=0.0;\n    if (pAcutN->totalS){\n      Sold=pAcutN->GetQNumber(ibl,pAcutN->Sqnumbers[0]); \n      // only a single SU(2) for now\n    }\n\n\n    int BlSize=pAcutN->GetBlockSize(ibl);\n    if (debug)\n      cout << \" Setting Block \" << ibl << \" of \" << pAcutN->NumBlocks()-1\n\t   << \"  Size : \" << BlSize << \" ... \"; \n\n    MyTime.restart();\n    // Loop in block states (and calculate rhoN(ist,jst))\n    for (int ist=ist0;ist<=ist1;ist++){\n      for (int jst=ist;jst<=ist1;jst++){\n\n\t// Ok, watch out for the \" type\" thing for SU(2) symmetry\n\tDM_NRG_SetChildSameType(ist,jst,pAcutN,pAbasisNp1,ChildSt_SameType);\n\n\tdouble auxMatEl=0.0;\n\tcomplex<double> cMatEl=ZeroC;\n\t// Loop over blocks in ChildSt_SameType (N+1)\n\tfor (arrayit=ChildSt_SameType.begin();\n\t     arrayit<ChildSt_SameType.end();arrayit++){\n\t  iit=(*arrayit).begin();\n\t  int iblbasis_Np1=(*iit);\n\t  int istbasis_Np1=(*(iit+1));\n\t  int jstbasis_Np1=(*(iit+2));\n\n\t  // Get S_Np1 from iblbasis_Np1\n\t  double Si=0.0;\n\t  if (pAbasisNp1->totalS){\n\t    Si=pAbasisNp1->GetQNumber(iblbasis_Np1,pAbasisNp1->Sqnumbers[0]); \n\t    // only a single SU(2) for now\n\t  }\n\t  // Get S_type= from istbasis_Np1\n\t  int itype_Np1=pAbasisNp1->iType[istbasis_Np1];\n\t  double Stilde=0.0;\n\t  if (pSingleSite->totalS){\n\t    //Stilde=pSingleSite->GetQNumber(ibls,pSingleSite->Sqnumbers[0]);\n\t    Stilde=pSingleSite->GetQNumberFromSt(itype_Np1,pSingleSite->Sqnumbers[0]);\n\t    // only a single SU(2) for now\n\t  }\n\n\t  // Calculate Clebsh-Gordan coefs.\n\n\t  double CGfactor=0.0;\n\t  for (double Sz=-Si;Sz<=Si;Sz+=1.0){\n\t    double auxCG=CGordan(Sold,Sold,Stilde,Sz-Sold,Si,Sz);\n\t    CGfactor+=auxCG*auxCG; // Square it!! (oct 2010)\n\t  }\n\t  // end calcCG\n\n\t  //\n\t  // No need to find corresponding block in AcutNp1:\n\t  //\n\t  // if block is not there, then \n\t  // RhoNp1basis.GetMatEl(istbasis_Np1,jstbasis_Np1)\n\t  // will return 0.0 (in principle!)\n\t  // \n\t  //auxMatEl+=CGfactor*RhoNp1basis.GetMatEl(istbasis_Np1,jstbasis_Np1);\n\t  if (!(RhoNp1basis.IsComplex))\n\t    auxMatEl+=CGfactor*RhoNp1basis.GetMatEl(istbasis_Np1,jstbasis_Np1);\n\t  else\n\t    cMatEl+=CGfactor*RhoNp1basis.cGetMatEl(istbasis_Np1,jstbasis_Np1);\n\n\t}\n\t// end loop in Child states\n\t// What if states are NOT kept\n\t// // Diagonal only\n\t// What about the CB coefficient? Should we do (???)\n\t//auxExp=(2.0*Sold+1.0)*exp(-betabar*pAcutNp1->dEn[ist]);\n\t// NO! IT GIVES WRONG RESULTS...\n\t\n\tif ( (UseFDM)&&(jst==ist)&&(pAcutN->CheckKept(ist,false)) ){\n\t  //cout << \" Disc-disc : ist=\" << ist <<  endl;\n\t  //cout << \" size ChildSt[ist]= \" << pAcutN->ChildStates[ist].size();\n\t  if ( dNEqual(ZNdisc,0.0) )\n\t    auxMatEl=exp(-betabar*(pAcutN->dEn[ist]))/ZNdisc;\n\t}\n\t// end if discarded, discarded\n\t\n\tif (ist==jst) trace+=(2.0*Sold+1.0)*auxMatEl;\n\n\tif (pRhoN->IsComplex)\n\t  pRhoN->MatElCplx.push_back(cMatEl);\n\telse\n\t  pRhoN->MatEl.push_back(auxMatEl);\n\n\ti1++;\n      }\n      // end loop in jst\n    }\n    // end loop in ist\n    pRhoN->MatBlockBegEnd.push_back(i1-1);\n\n\n    time_elapsed=MyTime.elapsed();\n    if (debug)\n     cout << \" ... done in \" << time_elapsed << \" secs.\" << endl;\n\n  }\n  // end loop in pAcutN blocks\n\n  cout << \" ... Rho N  done. Trace(2Si+1) = \" << trace << endl;\n\n//   if (pAcutN->Nshell==4){\n//     cout << \" Rho_N=4: \" << endl;\n//     //pRhoN->PrintMatBlock(10,10);\n//     ThisBl=10;\n//     cout << \" ibl = \" << ThisBl << endl;\n//     cout << \" pRhoN block structure: \" << endl;\n//     pRhoN->PrintBlockQNumbers(ThisBl);\n//     cout << \" Block \" << ThisBl << \" goes from ist = \" \n// \t << pRhoN->GetBlockLimit(ThisBl,0) \n// \t << \" to \"\n// \t << pRhoN->GetBlockLimit(ThisBl,1) \n// \t << endl;\n//     //pRhoN->PrintMatBlock(13,13);\n//     ThisBl=13;\n//     cout << \" ibl = \" << ThisBl << endl;\n//     cout << \" pRhoN block structure: \" << endl;\n//     pRhoN->PrintBlockQNumbers(ThisBl);\n//     cout << \" Block \" << ThisBl << \" goes from ist = \" \n// \t << pRhoN->GetBlockLimit(ThisBl,0) \n// \t << \" to \"\n// \t << pRhoN->GetBlockLimit(ThisBl,1) \n// \t << endl;\n//   }\n\n}\n// end set RhoN new\n\n/////////////////////////////////////////\n/////////////////////////////////////////\n/////////////////////////////////////////\n\nvoid DM_NRG_CalcRhoN_old(CNRGbasisarray* pAcutN,\n\t\t     CNRGbasisarray* pAcutNp1,\n\t\t     CNRGbasisarray* pAbasisNp1,\n\t\t     CNRGmatrix* pRhoN,\n\t\t     CNRGmatrix* pRhoNp1){\n\n  // Poor old routine, which does not use uBLAS... (slow old man)\n\n  vector< vector<int> > ChildSt_SameType;\n  vector< vector<int> >::iterator arrayit;\n  vector<int>::iterator iit;\n\n  // Check time\n  boost::timer MyTime;\n  double time_elapsed;\n\n\n  cout << \" DM-NRG: Calculating Rho N ...\" << endl;\n\n  // Initial set up\n  pRhoN->ClearAll();\n  pRhoN->SyncNRGarray(*pAcutN);\n  pRhoN->UpperTriangular=true;\n\n  // Calculate matrix elements\n  int i1=0;\n  for (int ibl=0;ibl<pAcutN->NumBlocks();ibl++){\n  // Testing in a few blocks\n  //for (int ibl=0;ibl<=8;ibl+=8){\n    // Rho is block diagonal\n    pRhoN->MatBlockMap.push_back(ibl);\n    pRhoN->MatBlockMap.push_back(ibl);\n    pRhoN->MatBlockBegEnd.push_back(i1);\n    \n    int ist0=pAcutN->GetBlockLimit(ibl,0);\n    int ist1=pAcutN->GetBlockLimit(ibl,1);\n\n    // testing...\n\n\n    int BlSize=pAcutN->GetBlockSize(ibl);\n    cout << \" Setting Block \" << ibl << \" of \" << pAcutN->NumBlocks()-1\n\t << \"  Size : \" << BlSize << \" ... \"; \n\n    MyTime.restart();\n    // Loop in block states (and calculate rhoN(ist,jst))\n    for (int ist=ist0;ist<=ist1;ist++){\n      for (int jst=ist;jst<=ist1;jst++){\n\n\tdouble auxMatEl=0.0;\n\t// Debugging\n// \tif ( (ist==61)&&(jst==61) ){\n// \t  cout << \" ist = \" << ist << \" jst = \" << jst << endl;\n// \t}\n\n\tDM_NRG_SetChildSameType(ist,jst,pAcutN,pAbasisNp1,ChildSt_SameType);\n\n// \tif ( (ist==61)&&(jst==61) ){\n// \t  cout << \"bl  ist_Np1  jst_Np1 \" << endl;\n// \t  for (arrayit=ChildSt_SameType.begin();\n// \t       arrayit<ChildSt_SameType.end();arrayit++){\n// \t    for(iit=(*arrayit).begin();iit<(*arrayit).end();iit++){\n// \t      cout << (*iit) << \" \";\n// \t    }\n// \t    cout << endl;\n// \t  }\n// \t}\n\t// debug\n\n\t// Loop over blocks in ChildSt_SameType (N+1)\n\n\tfor (arrayit=ChildSt_SameType.begin();\n\t     arrayit<ChildSt_SameType.end();arrayit++){\n\t  iit=(*arrayit).begin();\n\t  int iblbasis_Np1=(*iit);\n\t  int istbasis_Np1=(*(iit+1));\n\t  int jstbasis_Np1=(*(iit+2));\n\n// \t  if ( (ist==61)&&(jst==61) ){\n// \t    cout << \" iblbasis_Np1 = \" << iblbasis_Np1\n// \t\t << \" istbasis_Np1 = \"<< istbasis_Np1 \n// \t\t << \" jstbasis_Np1 = \"<< jstbasis_Np1 \n// \t\t << endl;\n// \t  }\n\t  //\n\t  // Find corresponding block in AcutNp1 (compare QNumbers)\n\t  //\n\t  double* qnums=new double [pAbasisNp1->NQNumbers];\n\t  for (int iqn=0;iqn<pAbasisNp1->NQNumbers;iqn++){\n\t    qnums[iqn]=pAbasisNp1->GetQNumber(iblbasis_Np1,iqn);\n\t  }\n\t  int ibl_Np1=pAcutNp1->GetBlockFromQNumbers(qnums);\n// \t  if (ibl_Np1==-1){\n// \t    cout << \" Block  not found in Acut N+1: \";\n// \t    cout << \" QNs = \" ;\n// \t    for (int iqn=0;iqn<pAbasisNp1->NQNumbers;iqn++){\n// \t      cout << qnums[iqn] << \" \";\n// \t    } \n// \t    cout << endl;\n// \t  }\n\t  // if block not found\n\t  delete [] qnums;\n\n// \t  if ( (ist==61)&&(jst==61) ){\n// \t    cout << \" ibl_Np1 = \" << ibl_Np1 << endl;\n// \t    if (ibl_Np1>0)\n// \t      cout << \" states: from \" << pAcutNp1->GetBlockLimit(ibl_Np1,0)\n// \t\t   << \" to \" << pAcutNp1->GetBlockLimit(ibl_Np1,1) << endl;\n// \t  }\n\t  // debug\n\t  // Loop over states in the block\n\t  if (ibl_Np1>0){ // Block exists in cut basis (kept)\n\t    for(int ist_Np1=pAcutNp1->GetBlockLimit(ibl_Np1,0);\n\t\tist_Np1<=pAcutNp1->GetBlockLimit(ibl_Np1,1);\n\t\tist_Np1++){\n\t      for(int jst_Np1=pAcutNp1->GetBlockLimit(ibl_Np1,0);\n\t\t  jst_Np1<=pAcutNp1->GetBlockLimit(ibl_Np1,1);\n\t\t  jst_Np1++){\n\t       double U_wi=pAcutNp1->GetEigVecComponent(ist_Np1,istbasis_Np1);\n\t       double U_wpj=pAcutNp1->GetEigVecComponent(jst_Np1,jstbasis_Np1);\n\t       double rho_wwp=pRhoNp1->GetMatEl(ist_Np1,jst_Np1);\n\n\t       auxMatEl+=rho_wwp*U_wi*U_wpj;\n\n// \t      if ( (ist==61)&&(jst==61) ){\n// \t\tcout << \" ist_Np1 = \" << ist_Np1 \n// \t\t     << \" jst_Np1 = \" << jst_Np1 \n// \t\t     << endl; \n// \t\tcout << \" U_wi= \" << U_wi\n// \t\t     << \" U_wpj= \" << U_wpj \n// \t\t     << \" rho_wwp= \" << rho_wwp\n// \t\t     << endl; \n// \t\tcout << \" auxMatEl = \" << auxMatEl << endl;\n// \t      }\n\t      // debug\n\t      }\n\t      // end loop in j_states in ibl_Np1\n\t    }\n\t    // end loop in i_states in ibl_Np1\n\t  } \n\t  // end if block exists in Acut\n\n// \t  if ( (ist==61)&&(jst==61) ){\n// \t    cout << \" auxMatEl = \" << auxMatEl << endl;\n// \t  }\n\n\t}\n\t// end loop in ChildSt_SameType\n\n\n\t\n\tpRhoN->MatEl.push_back(auxMatEl);\n\ti1++;\n      }\n      // loop over jst    \n    }\n    // loop over ist\n    pRhoN->MatBlockBegEnd.push_back(i1-1);\n\n    time_elapsed=MyTime.elapsed();\n    cout << \" ... done in \" << time_elapsed << \" secs.\" << endl;\n\n  }\n  // end loop in blocks\n\n  cout << \" ... Rho N done.\" << endl;\n\n\n\n}\n// end subroutine\n\n/////////////////////////////////////////\n/////////////////////////////////////////\n/////////////////////////////////////////\n", "meta": {"hexsha": "a839ed480931fa1c05a2420073f98f413dc25ff0", "size": 17084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DM_NRG/DM_NRG_CalcRhoN.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/DM_NRG/DM_NRG_CalcRhoN.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/DM_NRG/DM_NRG_CalcRhoN.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.0744849445, "max_line_length": 79, "alphanum_fraction": 0.5814797471, "num_tokens": 6066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.19758572048381132}}
{"text": "/**\nBSD 3-Clause License\n\nThis file is part of the code accompanying the paper\nGradient-SDF: A Semi-Implicit Surface Representation for 3D Reconstruction\nby Christiane Sommer*, Lu Sang*, David Schubert, and Daniel Cremers (* denotes equal contribution).\n\nCopyright (c) 2021, Christiane Sommer and Lu Sang.\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 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\n// standard includes\n#include <iostream>\n#include <fstream>\n#include <vector>\n// library includes\n#include <cstdlib>\n#include <Eigen/Dense>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <CLI/CLI.hpp>\n// class includes\n#include \"Timer.h\"\n#include \"normals/NormalEstimator.h\"\n#include \"sdf_tracker/MapGradPixelSdf.h\"\n#include \"sdf_tracker/RigidPointOptimizer.h\"\n#include \"img_loader/img_loader.h\"\n#include \"ps_optimizer/PhotometricOptimizer.h\"\n#include \"ps_optimizer/ColorUpsampler.h\"\n#include \"ps_optimizer/SharpDetector.h\"\n// own includes\n#include \"mat.h\"\n\nvoid sampleKeyFrame(std::vector<int>& key_frames, std::vector<std::string>& key_stamps, std::vector<std::shared_ptr<cv::Mat>>& key_images, std::vector<Mat4f, Eigen::aligned_allocator<Mat4f>>& key_poses, int max_num);\n/**\n * main function\n */\nint main(int argc, char *argv[]) {\n\n    Timer T;\n    // Default input sequence in folder\n    std::string input = \"\";\n    std::string output = \"../results/\";\n    std::string stype = \"map-gp\";\n    std::string dtype = \"\";\n    size_t first = 0;\n    size_t last = 300;\n    float voxel_size = 0.01; // Voxel size in m\n    float z_max = 3.5; // maximal depth to take into account in m\n    float truncation_factor = 5; // truncation in voxels\n    float sharp_threshold = 0.0001;\n    int num_frame = 30;\n\n    CLI::App app{\"Hash Table-Based 3D Scanning and Texture Optimization\"};\n    app.add_option(\"--input\", input, \"folder of input sequence\");\n    app.add_option(\"--results\", output, \"folder to store results in\");\n    app.add_option(\"--first\", first, \"number of first frame to be processed (default: 0)\");\n    app.add_option(\"--last\", last, \"number of last frame (default: all)\");\n    app.add_option(\"--data-type\", dtype, \"type of dataset\");\n    app.add_option(\"--voxel-size\", voxel_size, \"voxel size in meters (default: 0.01)\");\n    app.add_option(\"--trunc\", truncation_factor, \"truncation in multiples of voxels (default: 5)\");\n    app.add_option(\"--key-frame\", num_frame, \"number of the key frames to be sampled (default: 20)\");\n   \n\n    // parse input arguments\n    try {\n        app.parse(argc, argv);\n    } catch (const CLI::ParseError& e) {\n        return app.exit(e);\n    }\n\n    // parse dataset type\n    enum class DataType {\n        TUM_RGBD,\n        SYNTH,\n        PRINTED_3D,\n        REDWOOD,\n    };\n    DataType DT;\n    if (dtype == \"tum\" || dtype == \"tumrgbd\") {\n        DT = DataType::TUM_RGBD;\n        sharp_threshold = 0.026;\n    }\n    else if (dtype == \"synth\") {\n        DT = DataType::SYNTH;\n    }\n    else if (dtype == \"printed\") {\n        DT = DataType::PRINTED_3D;\n        sharp_threshold = 0.026;\n    }\n    else if (dtype == \"rw\" || dtype == \"redwood\") {\n        DT = DataType::REDWOOD;\n        sharp_threshold = 0.033;\n    }\n    else {\n        std::cerr << \"Your specified dataset type is not supported (yet).\" << std::endl;\n        return 1;\n    }\n    \n    // create image loader\n    ImageLoader* loader;\n    switch (DT) {\n    case DataType::TUM_RGBD :\n        loader = new TumrgbdLoader(input);\n        break;\n    case DataType::SYNTH :\n        loader = new SynthLoader(input);\n        break;\n    case DataType::PRINTED_3D :\n        loader = new Printed3dLoader(input);\n        break;\n    case DataType::REDWOOD :\n        loader = new RedwoodLoader(input);\n        break;\n    default:\n        std::cerr << \"Specified dataset type not recognized, return\" << std::endl;\n        return 1;\n    }\n\n    // Load camera intrinsics\n    if (!loader->load_intrinsics(\"intrinsics.txt\")) {\n        std::cerr << \"No intrinsics file found in \" << input << \"!\" << std::endl;\n        return 1;\n    }\n    const Mat3f K = loader->K();\n    std::cout << \"K: \" << std::endl << K << std::endl;\n    \n    // create normal estimator\n    T.tic();\n    cv::NormalEstimator<float>* NEst;\n    NEst = new cv::NormalEstimator<float>(640, 480, K, cv::Size(2*5+1, 2*5+1));\n    T.toc(\"Init normal estimation\");\n\n    std::stringstream stream;\n    stream << std::fixed << std::setprecision(3) << voxel_size;\n    std::string voxel_size_str = stream.str();\n\n    // Trunction distance for the tSDF\n    const float truncation = truncation_factor * voxel_size;\n\n    Sdf* tSDF;\n    RigidPointOptimizer* pOpt;\n    PhotometricOptimizer* cOpt;\n    \n    std::ofstream pose_file(output + stype + \"_\" + voxel_size_str + \"m_T\" + std::to_string(int(truncation_factor)) + \"_poses.txt\");\n\n    std::vector<Mat4f, Eigen::aligned_allocator<Mat4f>> poses;\n    // poses.push_back(Mat4f::Identity());\n    std::vector<int> valid_frames;\n    std::vector<int> invalid_frames;\n    std::vector<int> keyframes;\n    valid_frames.push_back(0);\n    keyframes.push_back(0);\n    // vector of sampled poses and frames\n    std::vector<std::string> key_stamps;\n    std::vector<std::shared_ptr<cv::Mat>> key_images;\n    std::vector<Mat4f, Eigen::aligned_allocator<Mat4f>> key_poses;\n    key_poses.push_back(Mat4f::Identity());\n\n\n    // Frames to be processed\n    cv::Mat color, depth;\n    int dist_to_last_keyframe = 0;\n\n    // Proceed until first frame\n    for (size_t i = 0; i < first; ++i) {\n        loader->load_next(color, depth);\n    }\n    \n    // Actual scanning loop\n    for (size_t i = first; i <= last; ++i) {\n        std::cout << \"Working on frame: \" << i << std::endl;\n        \n        // Load data\n        T.tic();\n        if (!loader->load_next(color, depth)) {\n            std::cerr << \" -> Frame \" << i << \" could not be loaded!\" << std::endl;\n            T.toc(\"Load data\");\n            break;\n        }\n        T.toc(\"Load data\");\n\n        // Get initial volume pose from centroid of first depth map\n        if (i == first) {\n            // create SDF data\n            T.tic();\n            tSDF = new MapGradPixelSdf(voxel_size, truncation);\n            T.toc(\"Create Sdf\");\n            // Initialize tSDF\n            T.tic();\n            tSDF->setup(color, depth, K, NEst);\n            T.toc(\"Integrate depth data into Sdf\");\n\n\t\t\t// Initialize optimizers\n\t\t\tT.tic();\n\t\t\tpOpt = new RigidPointOptimizer(tSDF);\n\t\t\tT.toc(\"Create RigidOptimizer\");\n            T.tic();\n            cOpt = new PhotometricOptimizer(static_cast<MapGradPixelSdf*>(tSDF), voxel_size, K, output);\n            T.toc(\"Create PhotometricOptimizer\");\n            key_stamps.push_back(loader->rgb_timestamp());\n            cv::Mat new_color;\n            color.copyTo(new_color);\n            key_images.push_back(std::make_shared<cv::Mat>(new_color));\n            \n        }\n\t\telse {\n            // Perform optimization\n            T.tic();\n            bool conv = pOpt->optimize(depth, K);\n            T.toc(\"Point optimization\");\n            // Integrate data into model\n            if (conv) {\n                valid_frames.push_back(i-first);\n                T.tic();\n                tSDF->update(color, depth, K, pOpt->pose(), NEst);\n                T.toc(\"Integrate depth data into Sdf\");\n\n                if (sharpDetector(color, sharp_threshold) || dist_to_last_keyframe > 5)\n                {\n                    dist_to_last_keyframe = 0;\n                    keyframes.push_back(i-first);\n                    key_stamps.push_back(loader->rgb_timestamp());\n                    key_poses.push_back(pOpt->pose().matrix());\n                    cv::Mat new_color;\n                    color.copyTo(new_color);\n                    key_images.push_back(std::make_shared<cv::Mat>(new_color));\n                }\n                else{\n\n                    dist_to_last_keyframe++;\n                }\n            }\n            else {\n                invalid_frames.push_back(i-first);\n            }\n\t\t}\n\t\t// write timestamp + pose in tx ty tz qx qy qz qw format\n\t\tstd::cout << \"Current pose:\" << std::endl\n\t\t          << pOpt->pose().matrix() << std::endl;\n        poses.push_back(pOpt->pose().matrix());\n\t\tVec3f t(pOpt->pose().translation());\n\t\tEigen::Quaternion<float> q(pOpt->pose().rotationMatrix());\n\t\tpose_file << loader->depth_timestamp() << \" \"\n\t\t          << t[0] << \" \" << t[1] << \" \" << t[2] << \" \"\n\t\t          << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() << \"\\n\";\n    }\n    pose_file.close();\n    \n    // extract mesh and write to file\n    T.tic();\n    if (!tSDF->extract_mesh(output + \"mesh_lr.ply\")) { \n        std::cerr << \"Could not save mesh!\" << std::endl;\n    }\n    T.toc(\"Save mesh to disk\");\n    \n    // extract point cloud and write to file\n    T.tic();\n    if (!tSDF->extract_pc(output + \"cloud_lr.ply\")) { \n        std::cerr << \"Could not save point cloud!\" << std::endl;\n    }\n    T.toc(\"Save point cloud to disk\");\n\n    sampleKeyFrame(keyframes, key_stamps, key_images, key_poses, num_frame);\n\n    cOpt->setImages(key_images);\n    cOpt->setKeyframes(keyframes);\n    cOpt->setPoses(key_poses);\n    cOpt->setKeytimestamps(key_stamps);\n    cOpt->optimize();\n\n    // up sampling\n    ColorUpsampler tOpt((static_cast<MapGradPixelSdf*>(tSDF))->get_tsdf(),\n                    (static_cast<MapGradPixelSdf*>(tSDF))->get_vis(),\n                    key_images,\n                    key_poses,\n                    keyframes,\n                    voxel_size,\n                    K);\n    \n    std::cout << \"Color optimizer constructed\" << std::endl;\n    tOpt.computeColor(); // just to be able to compare better\n    tOpt.extractMesh(output + \"coarse_BA_mesh_after_upsample\");\n    tOpt.extractCloud(output + \"coarse_BA_cloud_after_upsample\");\n    \n\n    return 0;\n}\n\n\n//! To selected limited number of frames if there are too many input as key frames.\nvoid sampleKeyFrame(std::vector<int>& key_frames, std::vector<std::string>& key_stamps, std::vector<std::shared_ptr<cv::Mat>>& key_images, std::vector<Mat4f, Eigen::aligned_allocator<Mat4f>>& key_poses, int max_num){\n    if (key_frames.size() < max_num ){\n        return;\n    }\n    max_num -= 1;\n    float step = static_cast<float>(key_frames.size()) / static_cast<float>(max_num);\n    std::vector<int> frames;\n    std::vector<std::string> stamps;\n    std::vector<std::shared_ptr<cv::Mat>> images;\n    std::vector<Mat4f, Eigen::aligned_allocator<Mat4f>> poses;\n    float idx = 0;\n    for(int count = 0; count < max_num; count++){\n        int i = static_cast<int>(idx);\n        frames.push_back(key_frames[i]);\n        stamps.push_back(key_stamps[i]);\n        images.push_back(key_images[i]);\n        poses.push_back(key_poses[i]);\n        idx+=step;\n    }\n    frames.push_back(key_frames.back()); //we need the last frame for resize the visibility vector\n    stamps.push_back(key_stamps.back());\n    images.push_back(key_images.back());\n    poses.push_back(key_poses.back());\n    \n    key_frames = frames;\n    key_stamps = stamps;\n    key_poses = poses;\n    key_images = images;\n}", "meta": {"hexsha": "098d93fb96174ae84a074455d9bed061f2943a0e", "size": 12422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/photometric_opt/src/main_photo_ba.cpp", "max_stars_repo_name": "c-sommer/gradient-sdf", "max_stars_repo_head_hexsha": "8e777231e04ca138fc3118bd5851caa0280e503b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-27T11:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T11:06:45.000Z", "max_issues_repo_path": "cpp/photometric_opt/src/main_photo_ba.cpp", "max_issues_repo_name": "c-sommer/gradient-sdf", "max_issues_repo_head_hexsha": "8e777231e04ca138fc3118bd5851caa0280e503b", "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": "cpp/photometric_opt/src/main_photo_ba.cpp", "max_forks_repo_name": "c-sommer/gradient-sdf", "max_forks_repo_head_hexsha": "8e777231e04ca138fc3118bd5851caa0280e503b", "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.7982708934, "max_line_length": 216, "alphanum_fraction": 0.6200289808, "num_tokens": 3118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.19758571675396663}}
{"text": "//***************************************************************************\n//* Copyright (c) 2015 Saint Petersburg State University\n//* Copyright (c) 2011-2014 Saint Petersburg Academic University\n//* All Rights Reserved\n//* See file LICENSE for details.\n//***************************************************************************\n\n#pragma once\n\n#include \"adt/iterator_range.hpp\"\n#include \"assembly_graph/core/action_handlers.hpp\"\n#include \"utils/parallel/openmp_wrapper.h\"\n#include \"paired_info_buffer.hpp\"\n#include <type_traits>\n#include <boost/iterator/iterator_facade.hpp>\n#include <btree/safe_btree_map.h>\n#include <set>\n\nnamespace omnigraph {\n\nnamespace de {\n\ntemplate<typename G, typename Traits, template<typename, typename> class Container>\nclass PairedIndex : public PairedBuffer<G, Traits, Container> {\n    typedef PairedIndex<G, Traits, Container> self;\n    typedef PairedBuffer<G, Traits, Container> base;\n\n    typedef typename base::InnerHistogram InnerHistogram;\n    typedef typename base::InnerHistPtr InnerHistPtr;\n    typedef typename base::InnerPoint InnerPoint;\n\n    using typename base::EdgePair;\n\npublic:\n    using typename base::Graph;\n    using typename base::EdgeId;\n    typedef typename base::InnerMap InnerMap;\n    typedef typename base::StorageMap StorageMap;\n    using typename base::Point;\n\n    typedef omnigraph::de::Histogram<Point> Histogram;\n\n    //--Data access types--\n\n    typedef typename StorageMap::const_iterator ImplIterator;\n\n    //---------------- Data accessing methods ----------------\n\n    /**\n     * @brief Underlying raw implementation data (for custom iterator helpers).\n     */\n    ImplIterator data_begin() const {\n        return this->storage_.begin();\n    }\n\n    /**\n     * @brief Underlying raw implementation data (for custom iterator helpers).\n     */\n    ImplIterator data_end() const {\n        return this->storage_.end();\n    }\n\n    /**\n     * @brief Smart proxy set representing a composite histogram of points between two edges.\n     * @detail You can work with the proxy just like any constant set.\n     *         The only major difference is that it returns all consisting points by value,\n     *         because some of them don't exist in the underlying sets and are\n     *         restored from the conjugate info on-the-fly.\n     */\n    class HistProxy {\n\n    public:\n        /**\n         * @brief Iterator over a proxy set of points.\n         */\n        class Iterator: public boost::iterator_facade<Iterator, Point, boost::bidirectional_traversal_tag, Point> {\n\n            typedef typename InnerHistogram::const_iterator InnerIterator;\n\n        public:\n            Iterator(InnerIterator iter, DEDistance offset, bool back = false)\n                    : iter_(iter), offset_(offset), back_(back)\n            {}\n\n        private:\n            friend class boost::iterator_core_access;\n\n            Point dereference() const {\n                auto i = iter_;\n                if (back_) --i;\n                Point result = Traits::Expand(*i, offset_);\n                if (back_)\n                    result.d = -result.d;\n                return result;\n            }\n\n            void increment() {\n                back_ ? --iter_ : ++iter_;\n            }\n\n            void decrement() {\n                back_ ? ++iter_ : --iter_;\n            }\n\n            inline bool equal(const Iterator &other) const {\n                return iter_ == other.iter_ && back_ == other.back_;\n            }\n\n            InnerIterator iter_; //current position\n            DEDistance offset_; //edge length\n            bool back_;\n        };\n\n        /**\n         * @brief Returns a wrapper for a histogram.\n         */\n        HistProxy(const InnerHistogram& hist, DEDistance offset = 0, bool back = false)\n            : hist_(hist), offset_(offset), back_(back)\n        {}\n\n        /**\n         * @brief Returns an empty proxy (effectively a Null object pattern).\n         */\n        static const InnerHistogram& empty_hist() {\n            static InnerHistogram res;\n            return res;\n        }\n\n        Iterator begin() const {\n            return Iterator(back_ ? hist_.end() : hist_.begin(), offset_, back_);\n        }\n\n        Iterator end() const {\n            return Iterator(back_ ? hist_.begin() : hist_.end(), offset_, back_);\n        }\n\n        /**\n         * @brief Finds the point with the minimal distance.\n         */\n        Point min() const {\n            VERIFY(!empty());\n            return *begin();\n        }\n\n        /**\n         * @brief Finds the point with the maximal distance.\n         */\n        Point max() const {\n            VERIFY(!empty());\n            return *--end();\n        }\n\n        /**\n         * @brief Returns the copy of all points in a simple flat histogram.\n         */\n        Histogram Unwrap() const {\n            return Histogram(begin(), end());\n        }\n\n        size_t size() const {\n            return hist_.size();\n        }\n\n        bool empty() const {\n            return hist_.empty();\n        }\n\n    private:\n        const InnerHistogram& hist_;\n        DEDistance offset_;\n        bool back_;\n    };\n\n    typedef typename HistProxy::Iterator HistIterator;\n\n    //---- Traversing edge neighbours ----\n\n    using EdgeHist = std::pair<EdgeId, HistProxy>;\n\n    /**\n     * @brief A proxy map representing neighbourhood of an edge,\n     *        where `Key` is the graph edge ID and `Value` is the proxy histogram.\n     * @detail You can work with the proxy just like with any constant map.\n     *         The only major difference is that it returns all consisting pairs by value,\n     *         because proxies are constructed on-the-fly.\n     */\n    class EdgeProxy {\n    public:\n\n        /**\n         * @brief Iterator over a proxy map.\n         * @detail For a full proxy, traverses both straight and conjugate pairs.\n         *         For a half proxy, traverses only lesser pairs (i.e., (a,b) where (a,b)<=(b',a')) of edges.\n         */\n        class Iterator: public boost::iterator_facade<Iterator, EdgeHist, boost::forward_traversal_tag, EdgeHist> {\n\n            typedef typename InnerMap::const_iterator InnerIterator;\n\n            void Skip() { //For a half iterator, skip conjugate pairs\n                while (half_ && iter_ != stop_ && !index_.IsCanonical(edge_, iter_->first))\n                    ++iter_;\n            }\n\n        public:\n            Iterator(const PairedIndex &index, InnerIterator iter, InnerIterator stop, EdgeId edge, bool half)\n                    : index_ (index)\n                    , iter_(iter)\n                    , stop_(stop)\n                    , edge_(edge)\n                    , half_(half)\n            {\n                Skip();\n            }\n\n            void increment() {\n                ++iter_;\n                Skip();\n            }\n\n        private:\n            friend class boost::iterator_core_access;\n\n            bool equal(const Iterator &other) const {\n                return iter_ == other.iter_;\n            }\n\n            EdgeHist dereference() const {\n                const auto& hist = *iter_->second;\n                return std::make_pair(iter_->first, HistProxy(hist, index_.CalcOffset(edge_)));\n            }\n\n        private:\n            const PairedIndex &index_; //TODO: get rid of this somehow\n            InnerIterator iter_, stop_;\n            EdgeId edge_;\n            bool half_;\n        };\n\n        EdgeProxy(const PairedIndex &index, const InnerMap& map, EdgeId edge, bool half = false)\n            : index_(index), map_(map), edge_(edge), half_(half)\n        {}\n\n        Iterator begin() const {\n            return Iterator(index_, map_.begin(), map_.end(), edge_, half_);\n        }\n\n        Iterator end() const {\n            return Iterator(index_, map_.end(), map_.end(), edge_, half_);\n        }\n\n        HistProxy operator[](EdgeId e2) const {\n            if (half_ && !index_.IsCanonical(edge_, e2))\n                return HistProxy::empty_hist();\n            return index_.Get(edge_, e2);\n        }\n\n        bool empty() const {\n            return map_.empty();\n        }\n\n    private:\n        const PairedIndex& index_;\n        const InnerMap& map_;\n        EdgeId edge_;\n        //When false, represents all neighbours (consisting both of directly added data and \"restored\" conjugates).\n        //When true, proxifies only half of the added edges.\n        bool half_;\n    };\n\n    typedef typename EdgeProxy::Iterator EdgeIterator;\n\n    //---------------- Constructor ----------------\n\n    PairedIndex(const Graph &graph)\n        : base(graph) {}\n\n    /**\n     * @brief Adds a lot of info from another index, using fast merging strategy.\n     *        Should be used instead of point-by-point index merge.\n     */\n    template<class Buffer>\n    void Merge(Buffer& index_to_add) {\n        if (index_to_add.size() == 0)\n            return;\n\n        auto locked_table = index_to_add.lock_table();\n        for (auto& kvpair : locked_table) {\n            EdgeId e1_to_add = kvpair.first; auto& map_to_add = kvpair.second;\n\n            for (auto& to_add : map_to_add) {\n                EdgePair ep(e1_to_add, to_add.first), conj = this->ConjugatePair(e1_to_add, to_add.first);\n                if (ep > conj)\n                    continue;\n\n                base::Merge(ep.first, ep.second, *to_add.second);\n            }\n        }\n        VERIFY(this->size() >= index_to_add.size());\n    }\n\n    template<class Buffer>\n    typename std::enable_if<std::is_convertible<typename Buffer::InnerMap, InnerMap>::value,\n        void>::type MoveAssign(Buffer& from) {\n        auto& base_index = this->storage_;\n        base_index.clear();\n        auto locked_table = from.lock_table();\n        for (auto& kvpair : locked_table) {\n            base_index[kvpair.first] = std::move(kvpair.second);\n        }\n        this->size_ = from.size();\n    }\n\npublic:\n    //---------------- Data deleting methods ----------------\n\n    /**\n     * @brief Removes the specific entry from the index, and its conjugate.\n     * @warning Don't use it on unclustered index, because hashmaps require set_deleted_item\n     * @return The number of deleted entries (0 if there wasn't such entry)\n     */\n    size_t Remove(EdgeId e1, EdgeId e2, Point p) {\n        InnerPoint point = Traits::Shrink(p, this->graph_.length(e1));\n\n        // We remove first \"non-owning part\"\n        EdgePair minep, maxep;\n        std::tie(minep, maxep) = this->MinMaxConjugatePair({ e1, e2 });\n\n        size_t res = RemoveSingle(minep.first, minep.second, point);\n        size_t removed = (this->IsSelfConj(e1, e2) ? res : 2 * res);\n        this->size_ -= removed;\n\n        Prune(maxep.first, maxep.second);\n        Prune(minep.first, minep.second);\n\n        return removed;\n    }\n\n    /**\n     * @brief Removes the whole histogram from the index, and its conjugate.\n     * @warning Don't use it on unclustered index, because hashmaps require set_deleted_item\n     * @return The number of deleted entries\n     */\n    size_t Remove(EdgeId e1, EdgeId e2) {\n        EdgePair minep, maxep;\n        std::tie(minep, maxep) = this->MinMaxConjugatePair({ e1, e2 });\n\n        size_t removed = RemoveAll(maxep.first, maxep.second);\n        removed += RemoveAll(minep.first, minep.second);\n        this->size_ -= removed;\n\n        return removed;\n    }\n\n  private:\n    void Prune(EdgeId e1, EdgeId e2) {\n        auto i1 = this->storage_.find(e1);\n        if (i1 == this->storage_.end())\n            return;\n\n        auto& map = i1->second;\n        auto i2 = map.find(e2);\n        if (i2 == map.end())\n            return;\n\n        if (!i2->second->empty())\n            return;\n\n        map.erase(e2);\n        if (map.empty())\n            this->storage_.erase(e1);\n    }\n\n    size_t RemoveSingle(EdgeId e1, EdgeId e2, InnerPoint point) {\n        auto i1 = this->storage_.find(e1);\n        if (i1 == this->storage_.end())\n            return 0;\n\n        auto& map = i1->second;\n        auto i2 = map.find(e2);\n        if (i2 == map.end())\n            return 0;\n\n        if (!i2->second->erase(point))\n           return 0;\n\n        return 1;\n    }\n\n    size_t RemoveAll(EdgeId e1, EdgeId e2) {\n        auto i1 = this->storage_.find(e1);\n        if (i1 == this->storage_.end())\n            return 0;\n        auto& map = i1->second;\n        auto i2 = map.find(e2);\n        if (i2 == map.end())\n            return 0;\n\n        size_t size_decrease = i2->second->size();\n        map.erase(i2);\n        if (map.empty()) //Prune empty maps\n            this->storage_.erase(i1);\n        return size_decrease;\n    }\n\npublic:\n\n    /**\n     * @brief Removes all neighbourhood of an edge (all edges referring to it, and their histograms)\n     * @warning To keep the symmetricity, it also deletes all conjugates, so the actual complexity is O(size).\n     * NB: size - not all index but size of conjugates!!!\n     * @return The number of deleted entries\n     */\n    size_t Remove(EdgeId edge) {\n        auto i = this->storage_.find(edge);\n        if (i == this->storage_.end())\n            return 0;\n        InnerMap &inner_map = i->second;\n        std::vector<EdgeId> to_remove;\n        to_remove.reserve(inner_map.size());\n        size_t old_size = this->size();\n        for (const auto& ep : inner_map)\n            to_remove.push_back(ep.first);\n        for (auto e2 : to_remove)\n            this->Remove(edge, e2);\n        return old_size - this->size();\n    }\n\nprivate:\n    //When there is no such edge, returns a fake empty map for safety\n    const InnerMap& GetImpl(EdgeId e) const {\n        auto i = this->storage_.find(e);\n        if (i != this->storage_.end())\n            return i->second;\n        return empty_map_;\n    }\n\n    //When there is no such histogram, returns a fake empty histogram for safety\n    const InnerHistogram& GetImpl(EdgeId e1, EdgeId e2) const {\n        auto i = this->storage_.find(e1);\n        if (i != this->storage_.end()) {\n            auto j = i->second.find(e2);\n            if (j != i->second.end())\n                return *j->second;\n        }\n        return HistProxy::empty_hist();\n    }\n\npublic:\n\n    /**\n     * @brief Returns a whole proxy map to the neighbourhood of some edge.\n     * @param e ID of starting edge\n     */\n    EdgeProxy Get(EdgeId e) const {\n        return EdgeProxy(*this, GetImpl(e), e);\n    }\n\n    /**\n     * @brief Returns a half proxy map to the neighbourhood of some edge.\n     * @param e ID of starting edge\n     */\n    EdgeProxy GetHalf(EdgeId e) const {\n        return EdgeProxy(*this, GetImpl(e), e, true);\n    }\n\n    /**\n     * @brief Operator alias of Get(id).\n     */\n    EdgeProxy operator[](EdgeId e) const {\n        return Get(e);\n    }\n\n    /**\n     * @brief Returns a histogram proxy for all points between two edges.\n     */\n    HistProxy Get(EdgeId e1, EdgeId e2) const {\n        return HistProxy(GetImpl(e1, e2), this->CalcOffset(e1));\n    }\n\n    /**\n     * @brief Operator alias of Get(e1, e2).\n     */\n    HistProxy operator[](EdgePair p) const {\n        return Get(p.first, p.second);\n    }\n\n    /**\n     * @brief Checks if an edge (or its conjugated twin) is consisted in the index.\n     */\n    bool contains(EdgeId edge) const {\n        return this->storage_.count(edge) + this->storage_.count(this->graph_.conjugate(edge)) > 0;\n    }\n\n    /**\n     * @brief Checks if there is a histogram for two points (or their conjugated pair).\n     */\n    bool contains(EdgeId e1, EdgeId e2) const {\n        auto i1 = this->storage_.find(e1);\n        if (i1 != this->storage_.end() && i1->second.count(e2))\n            return true;\n        return false;\n    }\n\n    /**\n     * @brief Inits the index with graph data. For each edge, adds a loop with zero weight.\n     * @warning Do not call this on non-empty indexes.\n     */\n    void Init() {\n        //VERIFY(size() == 0);\n        for (auto it = this->graph_.ConstEdgeBegin(); !it.IsEnd(); ++it)\n            this->Add(*it, *it, Point());\n    }\n\n    void VerifyIndex() {\n        std::set<EdgeId> edges_in_index;\n        size_t sz = 0;\n        for( auto iter = data_begin(); iter != data_end(); iter ++ ) {\n            VERIFY_MSG(iter->second.size() > 0, \" empty map! \");\n            VERIFY_MSG(this->graph_.edges().find(iter->first) != this->graph_.edges().end(), \" left edge wrong  \" << iter->first);\n            for (const auto &e_iter: iter->second) {\n                VERIFY_MSG(this->graph_.edges().find(e_iter.first) != this->graph_.edges().end(), \" right edge wrong  \" << e_iter.first);\n                sz += e_iter.second->size();\n\n            }\n        }\n        DEBUG(sz << \" \" << this->size_);\n        VERIFY_MSG(sz == this ->size_, \"Different sizes\");\n    }\nprivate:\n    InnerMap empty_map_; //null object\n};\n\ntemplate<class T>\nclass NoLockingAdapter : public T {\n  public:\n    class locked_table {\n      public:\n        using iterator = typename T::iterator;\n        using const_iterator = typename T::const_iterator;\n\n        locked_table(T& table)\n                : table_(table) {}\n\n        iterator begin() { return table_.begin();  }\n        const_iterator begin() const { return table_.begin(); }\n        const_iterator cbegin() const { return table_.begin(); }\n\n        iterator end() { return table_.end(); }\n        const_iterator end() const { return table_.end(); }\n        const_iterator cend() const { return table_.end(); }\n\n        size_t size() const { return table_.size(); }\n\n      private:\n        T& table_;\n    };\n\n    // Nothing to lock here\n    locked_table lock_table() {\n        return locked_table(*this);\n    }\n};\n\n//Aliases for common graphs\ntemplate<typename K, typename V>\nusing safe_btree_map = NoLockingAdapter<btree::safe_btree_map<K, V>>; //Two-parameters wrapper\ntemplate<typename Graph>\nusing PairedInfoIndexT = PairedIndex<Graph, PointTraits, safe_btree_map>;\n\ntemplate<typename K, typename V>\nusing btree_map = NoLockingAdapter<btree::btree_map<K, V>>; //Two-parameters wrapper\n\ntemplate<typename Graph>\nusing UnclusteredPairedInfoIndexT = PairedIndex<Graph, RawPointTraits, btree_map>;\n\n\ntemplate<typename G, typename Traits, template<typename, typename> class Container>\nclass PairedIndexHandler : public omnigraph::GraphActionHandler<G> {\n\npublic:\n    using BaseIndex = PairedIndex<G, Traits, Container>;\n\n    typedef typename G::EdgeId EdgeId;\n\n    BaseIndex &paired_index_;\n\n    PairedIndexHandler(PairedIndex<G, Traits, Container>& p): GraphActionHandler<G>(p.graph(), \"PairedIndexHandler\"), paired_index_(p) {}\n\n    virtual void HandleDelete(EdgeId e) override {\n        if (e == paired_index_.graph().conjugate(e)) {\n            DEBUG(\"removing self-conj\");\n        }\n        DEBUG(\"Deleted:\" << e << \" \" << omp_get_thread_num());\n        paired_index_.Remove(e);\n    }\n\n    virtual void HandleMerge(const std::vector<EdgeId> &old_edges, EdgeId new_edge) override {\n//        VerifyIndex();\n//        return;\n        size_t shift = 0;\n        DEBUG(\"created: \" << new_edge);\n        if (new_edge == paired_index_.graph().conjugate(new_edge))\n            DEBUG(\"merging self-conj\");\n        std::set<EdgeId> forbidden;\n        std::map<EdgeId, size_t> shifts;\n        for (EdgeId e : old_edges)  {\n            shifts[e] = shift;\n            shift += paired_index_.graph().length(e);\n            forbidden.insert(paired_index_.graph().conjugate(e));\n        }\n\n        DEBUG_EXPR({\n            for (EdgeId e : old_edges)\n                DEBUG(e << \" \" << paired_index_.graph().length(e));\n        });\n        \n        for (EdgeId e : old_edges) {\n            DEBUG(\"trying \" << e);\n            typename BaseIndex::EdgeProxy old_e = paired_index_.Get(e);\n            std::vector<std::pair<EdgeId, Point>> to_add;\n            for (auto it : old_e) {\n                EdgeId next = it.first;\n                if (forbidden.find(next) != forbidden.end()) {\n                    DEBUG(\"skpping self-conjugate merge\");\n                    continue;\n                }\n                size_t neg_shift = 0;\n                if (shifts.find(next) != shifts.end()) {\n                    DEBUG(\"old edge was: \" << next );\n                    neg_shift = shifts[next];\n                    next = new_edge;\n                }\n                DEBUG(e <<\" \" << next << \" \"<< it.second.size());\n                for (auto pp : it.second) {\n                    Point point (pp);\n                    point.d += (double) shifts[e] - double (neg_shift);\n                    DEBUG(\"from \"  <<new_edge << \" to \" << next  <<\" old \" << e << \" old_dist \" << pp.d << \"new_dist \" << point.d << \" \"  << point.weight);\n                    if (paired_index_.graph().length(new_edge) > point.d && new_edge != next) {\n                        DEBUG(\"not adding, assert failed\");\n                    } else {\n                        to_add.push_back(std::make_pair(next, point));\n                        DEBUG(\"added\");\n                    }\n                }\n            }\n            for (const auto &p : to_add)  {\n                paired_index_.Add(new_edge, p.first, p.second);\n            }\n\n        }\n    }\n};\n\n/**\n * @brief A collection of paired indexes which can be manipulated as one.\n *        Used as a convenient wrapper in parallel index processing.\n */\ntemplate<class Index>\nclass PairedIndices {\n    typedef std::vector<Index> Storage;\n    Storage data_;\n\npublic:\n    typedef Index value_type;\n\n    PairedIndices() {}\n\n    PairedIndices(const typename Index::Graph& graph, size_t lib_num) {\n        for (size_t i = 0; i < lib_num; ++i)\n            data_.emplace_back(graph);\n    }\n\n    /**\n     * @brief Initializes all indexes with zero points.\n     */\n    void Init() { for (auto& it : data_) it.Init(); }\n\n    /**\n     * @brief Clears all indexes.\n     */\n    void Clear() { for (auto& it : data_) it.clear(); }\n\n    Index& operator[](size_t i) { return data_[i]; }\n\n    const Index& operator[](size_t i) const { return data_[i]; }\n\n    size_t size() const { return data_.size(); }\n\n    typename Storage::iterator begin() { return data_.begin(); }\n    typename Storage::iterator end() { return data_.end(); }\n\n    typename Storage::const_iterator begin() const { return data_.begin(); }\n    typename Storage::const_iterator end() const { return data_.end(); }\n};\n\ntemplate<class Graph>\nusing PairedInfoIndicesT = PairedIndices<PairedInfoIndexT<Graph>>;\n\n\ntemplate<typename Graph>\nusing PairedInfoIndexHandlerT = PairedIndexHandler<Graph, PointTraits, safe_btree_map>;\n\ntemplate<class Graph>\nusing PairedInfoIndicesHandlerT = std::vector<PairedInfoIndexHandlerT<Graph>>;\n\ntemplate<class Graph>\nusing UnclusteredPairedInfoIndicesT = PairedIndices<UnclusteredPairedInfoIndexT<Graph>>;\n\ntemplate<typename K, typename V>\nusing unordered_map = NoLockingAdapter<std::unordered_map<K, V>>; //Two-parameters wrapper\ntemplate<class Graph>\nusing PairedInfoBuffer = PairedBuffer<Graph, RawPointTraits, unordered_map>;\n\ntemplate<class Graph>\nusing PairedInfoBuffersT = PairedIndices<PairedInfoBuffer<Graph>>;\n\n}\n\n}\n", "meta": {"hexsha": "15aaf34ad200a7d47a72b8059ec54e5e391d1675", "size": 22871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/metaspades/src/common/paired_info/paired_info.hpp", "max_stars_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_stars_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "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/metaspades/src/common/paired_info/paired_info.hpp", "max_issues_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_issues_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_issues_repo_licenses": ["MIT"], "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/metaspades/src/common/paired_info/paired_info.hpp", "max_forks_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_forks_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T07:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T08:02:58.000Z", "avg_line_length": 31.7652777778, "max_line_length": 155, "alphanum_fraction": 0.5702417909, "num_tokens": 5258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.1975857147236838}}
{"text": "//\n// Copyright (c) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\n//\n#include \"stdafx.h\"\n#include <algorithm>\n#include <array>\n#include <random>\n#include <numeric>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include \"../../../Source/Math/Matrix.h\"\n#include \"../../../Source/Math/CPUMatrix.h\"\n#include \"../../../Source/Math/GPUMatrix.h\"\n#include \"../../../Source/Math/ConvolutionEngine.h\"\n#include \"../../../Source/Math/CuDnnFactories.h\"\n#include \"common.h\"\n\nnamespace Microsoft { namespace MSR { namespace CNTK { namespace Test {\n\nusing vec = std::vector<float>;\n\nusing ConvEng = ConvolutionEngine<float>;\n\nbool AreEqual(float a, float b, float maxRelError, float maxAbsError)\n{\n    float diff = std::abs(a - b);\n    if (diff <= maxAbsError)\n        return true;\n    float largest = std::max(std::abs(a), std::abs(b));\n    return diff < largest * maxRelError;\n}\nbool AreEqual(double a, double b, double maxRelError, double maxAbsError)\n{\n    double diff = std::abs(a - b);\n    if (diff <= maxAbsError)\n        return true;\n    double largest = std::max(std::abs(a), std::abs(b));\n    return diff < largest * maxRelError;\n}\n\nsize_t CountNans(const SingleMatrix& src)\n{\n    size_t n = 0;\n    foreach_coord (i, j, src)\n    {\n        n += std::isnan(src(i, j)) ? 1 : 0;\n    }\n    return n;\n}\n\n// Returns vector of engine config parameters: <kind, device, maxTempMemSizeInSamples>\nstd::vector<std::tuple<ConvolutionEngineKind, DEVICEID_TYPE, size_t>> GetTestEngineConfigs()\n{\n    std::vector<std::tuple<ConvolutionEngineKind, DEVICEID_TYPE, size_t>> res;\n    // Reference engine. The engine does not use temp memory so safe to set it to 0.\n    res.push_back(std::make_tuple(ConvolutionEngineKind::Reference, -1, 0));\n    res.push_back(std::make_tuple(ConvolutionEngineKind::Reference, 0, 0));\n\n    // Gemm engine. Implemented only for CPU for now. Uses temp memory.\n    res.push_back(std::make_tuple(ConvolutionEngineKind::Gemm, -1, 0));\n    res.push_back(std::make_tuple(ConvolutionEngineKind::Gemm, -1, 1));\n    res.push_back(std::make_tuple(ConvolutionEngineKind::Gemm, -1, 3));\n    return res;\n}\n\nstd::vector<ConvolveGeometryPtr> GenerateConvTestConfigs()\n{\n    std::vector<ConvolveGeometryPtr> res;\n    // REVIEW alexeyk: add test cases with even dimensions of a kernel. There are some corner cases which cuDNN does not support (which essentially require negative padding).\n    for (size_t kW : {1, 3})\n    {\n        for (size_t kH : {1, 3})\n        {\n            for (size_t inW : {kW, 2 * kW, 2 * kW - 1})\n            {\n                for (size_t inC : {1, 3})\n                {\n                    for (size_t mapCount : {1, 5})\n                    {\n                        for (size_t stride : {1, min((int)kW, min((int)kH, 2))})\n                        {\n                            // Note: must use sharing=false in channel dimension otherwise geometry will not be cuDNN compatible but cuDNN won't fail.\n                            res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(inW, max(kH, inW) + 1, inC),\n                                TensorShape(kW, kH, inC), TensorShape(mapCount), TensorShape(stride, stride, inC),\n                                ConvolveGeometry::BoolVec{true},\n                                ConvolveGeometry::BoolVec{(kW & 1) != 0, (kH & 1) != 0, false},\n                                TensorShape(0), TensorShape(0)));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    // For debugging.\n    res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(3, 3, 1),\n        TensorShape(3, 3, 1), TensorShape(2), TensorShape(1, 1, 1),\n        ConvolveGeometry::BoolVec{true}, ConvolveGeometry::BoolVec{true, true, false},\n        TensorShape(0), TensorShape(0)));\n\n    // Simple 3D convolution.\n    res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(5, 5, 5, 2),\n        TensorShape(3, 3, 3, 2), TensorShape(2), TensorShape(1),\n        ConvolveGeometry::BoolVec{true}, ConvolveGeometry::BoolVec{false},\n        TensorShape(0), TensorShape(0)));\n    // Example of 3D convolution that can be represented with 3D tensors in reference engine\n    // but requires 4D tensors in other engines.\n    res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(5, 5, 3, 1),\n        TensorShape(3, 3, 2, 1), TensorShape(2), TensorShape(1),\n        ConvolveGeometry::BoolVec{true}, ConvolveGeometry::BoolVec{false},\n        TensorShape(0), TensorShape(0)));\n\n    res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(16, 16, 1),\n        TensorShape(3, 3, 1), TensorShape(8), TensorShape(1, 2, 1),\n        ConvolveGeometry::BoolVec{true}, ConvolveGeometry::BoolVec{true, true, false},\n        TensorShape(0), TensorShape(0)));\n\n    // 1x1 convolution (shortcuts in ResNet).\n    res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(16, 16, 2),\n        TensorShape(1, 1, 2), TensorShape(1), TensorShape(2, 2, 1),\n        ConvolveGeometry::BoolVec{true}, ConvolveGeometry::BoolVec{false},\n        TensorShape(0, 0, 0), TensorShape(0)));\n    return res;\n}\n\nstd::vector<ConvolveGeometryPtr> GeneratePoolTestConfigs()\n{\n    std::vector<ConvolveGeometryPtr> res;\n    for (size_t kW : {1, 2, 3})\n    {\n        for (size_t kH : {1, 2, 3})\n        {\n            for (size_t inW : {kW, 2 * kW, 2 * kW - 1})\n            {\n                for (size_t inC : {1, 3})\n                {\n                    for (size_t stride : {1, min((int)kW, min((int)kH, 2))})\n                    {\n                        // Note: must always use autopadding otherwise there might be configurations that \n                        // require negative padding that cuDNN does not support.\n                        res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(inW, max(kH, inW) + 1, inC),\n                            TensorShape(kW, kH, 1), TensorShape(1), TensorShape(stride, stride, 1),\n                            ConvolveGeometry::BoolVec{true},\n                            ConvolveGeometry::BoolVec{true, true, false},\n                            TensorShape(0), TensorShape(0)));\n                    }\n                }\n            }\n        }\n    }\n    // For debugging.\n    // Ordinary pooling.\n    res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(4, 4, 1),\n        TensorShape(2, 2, 1), TensorShape(1), TensorShape(2, 2, 1),\n        ConvolveGeometry::BoolVec{true}, ConvolveGeometry::BoolVec{true, true, false},\n        TensorShape(0), TensorShape(0)));\n    // Overlapped with padding.\n    res.push_back(std::make_shared<ConvolveGeometry>(TensorShape(4, 4, 1),\n        TensorShape(3, 3, 1), TensorShape(1), TensorShape(2, 2, 1),\n        ConvolveGeometry::BoolVec{true}, ConvolveGeometry::BoolVec{true, true, false},\n        TensorShape(0), TensorShape(0)));\n    return res;\n}\n\nBOOST_AUTO_TEST_SUITE(ConvolutionSuite)\n\nBOOST_AUTO_TEST_CASE(ConvolutionForward)\n{\n    std::mt19937 rng(0);\n    boost::random::uniform_int_distribution<> batchSizeG(1, 8);\n    boost::random::normal_distribution<float> nd;\n\n    auto initMat = [&](SingleMatrix& buf, size_t r, size_t c, vec& data) -> SingleMatrix\n    {\n        data.resize(r * 3 * c);\n        std::fill(begin(data), end(data), std::numeric_limits<float>::quiet_NaN());\n        std::generate(begin(data) + r * c, begin(data) + 2 * r * c, [&] { return nd(rng); });\n        buf.SetValue(r, 3 * c, buf.GetDeviceId(), data.data());\n        // Get center slice.\n        return buf.ColumnSlice(c, c);\n    };\n\n    int baseDeviceId = 0;\n    for (const auto& engCfg : GetTestEngineConfigs())\n    {\n        auto engKind = std::get<0>(engCfg);\n        auto deviceId = std::get<1>(engCfg);\n        auto maxTempMem = std::get<2>(engCfg);\n        for (const auto& g : GenerateConvTestConfigs())\n        {\n            auto baseEng = ConvEng::Create(g, baseDeviceId, ImageLayoutKind::CHW, 0, PoolKind::None, ConvolutionEngineKind::CuDnn);\n            auto testEng = ConvEng::Create(g, deviceId, ImageLayoutKind::CHW, maxTempMem, PoolKind::None, engKind);\n\n            size_t n = batchSizeG(rng);\n            vec buf;\n            buf.resize(g->InputShape().GetNumElements() * n);\n            std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n            SingleMatrix in(g->InputShape().GetNumElements(), n, buf.data(), deviceId, matrixFlagNormal);\n            SingleMatrix inB(g->InputShape().GetNumElements(), n, buf.data(), baseDeviceId, matrixFlagNormal);\n\n            size_t mapCount = g->GetMapCount(g->InputShape().GetRank() - 1);\n            buf.resize(g->KernelShape().GetNumElements() * mapCount);\n            std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n            SingleMatrix kernel(mapCount, g->KernelShape().GetNumElements(), buf.data(), deviceId, matrixFlagNormal);\n            SingleMatrix kernelB(mapCount, g->KernelShape().GetNumElements(), buf.data(), baseDeviceId, matrixFlagNormal);\n\n            size_t crowOut = g->OutputShape().GetNumElements();\n            SingleMatrix outBuf(deviceId);\n            SingleMatrix out = initMat(outBuf, crowOut, n, buf);\n            SingleMatrix outB(out.DeepClone(), baseDeviceId);\n\n            SingleMatrix workspace(deviceId);\n            SingleMatrix workspaceB(baseDeviceId);\n\n            testEng->Forward(in, kernel, out, workspace);\n            baseEng->Forward(inB, kernelB, outB, workspaceB);\n\n            std::stringstream tmsg;\n            tmsg << \"Geometry: \" << (std::string)(*g) << \", Batch: \" << n << \", Device: \" << deviceId << \", MaxTempMem: \" << maxTempMem;\n            std::string msg = \" are not equal, \" + tmsg.str();\n            std::string msgNan = \" has NaNs, \" + tmsg.str();\n            std::string msgNotNan = \" has buffer overflow/underflow, \" + tmsg.str();\n\n            float relErr = Err<float>::Rel;\n            float absErr = Err<float>::Abs;\n            std::string emsg;\n\n            BOOST_REQUIRE_MESSAGE(!out.HasNan(\"out\"), \"out\" << msgNan);\n            BOOST_REQUIRE_MESSAGE(CheckEqual(out, outB, emsg, relErr * 4, absErr * 14), \"out\" << msg << \". \" << emsg);\n            BOOST_REQUIRE_MESSAGE(CountNans(outBuf) == crowOut * 2 * n, \"out\" << msgNotNan);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(ConvolutionBackwardData)\n{\n    std::mt19937 rng(0);\n    boost::random::uniform_int_distribution<> batchSizeG(1, 8);\n    boost::random::normal_distribution<float> nd;\n\n    auto initMat = [&](SingleMatrix& buf, size_t r, size_t c, vec& data) -> SingleMatrix\n    {\n        data.resize(r * 3 * c);\n        std::fill(begin(data), end(data), std::numeric_limits<float>::quiet_NaN());\n        std::generate(begin(data) + r * c, begin(data) + 2 * r * c, [&] { return nd(rng); });\n        buf.SetValue(r, 3 * c, buf.GetDeviceId(), data.data());\n        // Get center slice.\n        return buf.ColumnSlice(c, c);\n    };\n\n    int baseDeviceId = 0;\n    for (const auto& engCfg : GetTestEngineConfigs())\n    {\n        auto engKind = std::get<0>(engCfg);\n        auto deviceId = std::get<1>(engCfg);\n        auto maxTempMem = std::get<2>(engCfg);\n        for (const auto& g : GenerateConvTestConfigs())\n        {\n            auto baseEng = ConvEng::Create(g, baseDeviceId, ImageLayoutKind::CHW, 0, PoolKind::None, ConvolutionEngineKind::CuDnn);\n            auto testEng = ConvEng::Create(g, deviceId, ImageLayoutKind::CHW, maxTempMem, PoolKind::None, engKind);\n\n            size_t n = batchSizeG(rng);\n            vec buf;\n            buf.resize(g->OutputShape().GetNumElements() * n);\n            std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n            SingleMatrix srcGrad(g->OutputShape().GetNumElements(), n, buf.data(), deviceId, matrixFlagNormal);\n            SingleMatrix srcGradB(g->OutputShape().GetNumElements(), n, buf.data(), baseDeviceId, matrixFlagNormal);\n\n            size_t mapCount = g->GetMapCount(g->InputShape().GetRank() - 1);\n            buf.resize(g->KernelShape().GetNumElements() * mapCount);\n            std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n            SingleMatrix kernel(mapCount, g->KernelShape().GetNumElements(), buf.data(), deviceId, matrixFlagNormal);\n            SingleMatrix kernelB(mapCount, g->KernelShape().GetNumElements(), buf.data(), baseDeviceId, matrixFlagNormal);\n\n            size_t crowGrad = g->InputShape().GetNumElements();\n            SingleMatrix gradBuf(deviceId);\n            SingleMatrix grad = initMat(gradBuf, crowGrad, n, buf);\n            SingleMatrix gradB(grad.DeepClone(), baseDeviceId);\n\n            SingleMatrix workspace(deviceId);\n            SingleMatrix workspaceB(baseDeviceId);\n\n            testEng->BackwardData(srcGrad, kernel, grad, true, workspace);\n            baseEng->BackwardData(srcGradB, kernelB, gradB, true, workspaceB);\n\n            std::stringstream tmsg;\n            tmsg << \"Geometry: \" << (std::string)(*g) << \", Batch: \" << n << \", Device: \" << deviceId;\n            std::string msg = \" are not equal, \" + tmsg.str();\n            std::string msgNan = \" has NaNs, \" + tmsg.str();\n            std::string msgNotNan = \" has buffer overflow/underflow, \" + tmsg.str();\n\n            float relErr = Err<float>::Rel;\n            float absErr = Err<float>::Abs;\n            std::string emsg;\n\n            BOOST_REQUIRE_MESSAGE(!grad.HasNan(\"grad\"), \"grad\" << msgNan);\n            BOOST_REQUIRE_MESSAGE(CheckEqual(grad, gradB, emsg, relErr * 16, absErr * 16), \"grad\" << msg << \". \" << emsg);\n            BOOST_REQUIRE_MESSAGE(CountNans(gradBuf) == crowGrad * 2 * n, \"grad\" << msgNotNan);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(ConvolutionBackwardKernel)\n{\n    std::mt19937 rng(0);\n    boost::random::uniform_int_distribution<> batchSizeG(1, 8);\n    boost::random::normal_distribution<float> nd;\n\n    auto initMat = [&](SingleMatrix& buf, size_t r, size_t c, vec& data) -> SingleMatrix\n    {\n        data.resize(r * 3 * c);\n        std::fill(begin(data), end(data), std::numeric_limits<float>::quiet_NaN());\n        std::generate(begin(data) + r * c, begin(data) + 2 * r * c, [&] { return nd(rng); });\n        buf.SetValue(r, 3 * c, buf.GetDeviceId(), data.data());\n        // Get center slice.\n        return buf.ColumnSlice(c, c);\n    };\n\n    int baseDeviceId = 0;\n    for (const auto& engCfg : GetTestEngineConfigs())\n    {\n        auto engKind = std::get<0>(engCfg);\n        auto deviceId = std::get<1>(engCfg);\n        auto maxTempMem = std::get<2>(engCfg);\n        for (const auto& g : GenerateConvTestConfigs())\n        {\n            auto baseEng = ConvEng::Create(g, baseDeviceId, ImageLayoutKind::CHW, 0, PoolKind::None, ConvolutionEngineKind::CuDnn);\n            auto testEng = ConvEng::Create(g, deviceId, ImageLayoutKind::CHW, maxTempMem, PoolKind::None, engKind);\n\n            size_t n = batchSizeG(rng);\n            vec buf;\n            buf.resize(g->InputShape().GetNumElements() * n);\n            std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n            SingleMatrix in(g->InputShape().GetNumElements(), n, buf.data(), deviceId, matrixFlagNormal);\n            SingleMatrix inB(g->InputShape().GetNumElements(), n, buf.data(), baseDeviceId, matrixFlagNormal);\n\n            buf.resize(g->OutputShape().GetNumElements() * n);\n            std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n            SingleMatrix grad(g->OutputShape().GetNumElements(), n, buf.data(), deviceId, matrixFlagNormal);\n            SingleMatrix gradB(g->OutputShape().GetNumElements(), n, buf.data(), baseDeviceId, matrixFlagNormal);\n\n            size_t mapCount = g->GetMapCount(g->InputShape().GetRank() - 1);\n            buf.resize(g->KernelShape().GetNumElements() * mapCount);\n            std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n            SingleMatrix kernelBuf(deviceId);\n            SingleMatrix kernel = initMat(kernelBuf, mapCount, g->KernelShape().GetNumElements(), buf);\n            SingleMatrix kernelB(kernel.DeepClone(), baseDeviceId);\n\n            SingleMatrix workspace(deviceId);\n            SingleMatrix workspaceB(baseDeviceId);\n            \n            testEng->BackwardKernel(grad, in, kernel, true, false, workspace);\n            baseEng->BackwardKernel(gradB, inB, kernelB, true, false, workspaceB);\n            \n            std::stringstream tmsg;\n            tmsg << \"Geometry: \" << (std::string)(*g) << \", Batch: \" << n << \", Device: \" << deviceId;\n            std::string msg = \" are not equal, \" + tmsg.str();\n            std::string msgNan = \" has NaNs, \" + tmsg.str();\n            std::string msgNotNan = \" has buffer overflow/underflow, \" + tmsg.str();\n\n            float relErr = Err<float>::Rel;\n            float absErr = Err<float>::Abs;\n            std::string emsg;\n\n            BOOST_REQUIRE_MESSAGE(!kernel.HasNan(\"kernel\"), \"kernel\" << msgNan);\n            // Todo: check the threashold value after we have setttings regard determinstics in place.\n            BOOST_REQUIRE_MESSAGE(CheckEqual(kernel, kernelB, emsg, relErr * 192, absErr * 32), \"kernel\" << msg << \". \" << emsg);\n            BOOST_REQUIRE_MESSAGE(CountNans(kernelBuf) == kernel.GetNumElements() * 2, \"kernel\" << msgNotNan);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PoolingForward)\n{\n    std::mt19937 rng(0);\n    boost::random::uniform_int_distribution<> batchSizeG(1, 8);\n    boost::random::normal_distribution<float> nd;\n\n    auto initMat = [&](SingleMatrix& buf, size_t r, size_t c, vec& data) -> SingleMatrix\n    {\n        data.resize(r * 3 * c);\n        std::fill(begin(data), end(data), std::numeric_limits<float>::quiet_NaN());\n        std::generate(begin(data) + r * c, begin(data) + 2 * r * c, [&] { return nd(rng); });\n        buf.SetValue(r, 3 * c, buf.GetDeviceId(), data.data());\n        // Get center slice.\n        return buf.ColumnSlice(c, c);\n    };\n\n    int baseDeviceId = 0;\n    auto engKind = ConvolutionEngineKind::Reference;\n    for (auto kind : {PoolKind::Max, PoolKind::Average})\n    {\n        for (int deviceId : {-1, 0})\n        {\n            for (const auto& g : GeneratePoolTestConfigs())\n            {\n                auto baseEng = ConvEng::Create(g, baseDeviceId, ImageLayoutKind::CHW, 0, kind, ConvolutionEngineKind::CuDnn);\n                auto testEng = ConvEng::Create(g, deviceId, ImageLayoutKind::CHW, 0, kind, engKind);\n\n                size_t n = batchSizeG(rng);\n                vec buf;\n                buf.resize(g->InputShape().GetNumElements() * n);\n                std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n                SingleMatrix in(g->InputShape().GetNumElements(), n, buf.data(), deviceId, matrixFlagNormal);\n                SingleMatrix inB(g->InputShape().GetNumElements(), n, buf.data(), baseDeviceId, matrixFlagNormal);\n\n                size_t crowOut = g->OutputShape().GetNumElements();\n                SingleMatrix outBuf(deviceId);\n                SingleMatrix out = initMat(outBuf, crowOut, n, buf);\n                SingleMatrix outB(out.DeepClone(), baseDeviceId);\n\n                testEng->ForwardPooling(in, out);\n                baseEng->ForwardPooling(inB, outB);\n\n                std::stringstream tmsg;\n                tmsg << \"Geometry: \" << (std::string)(*g) << \", Pool: \" << (int)kind << \", Batch: \" << n << \", Device: \" << deviceId;\n                std::string msg = \" are not equal, \" + tmsg.str();\n                std::string msgNan = \" has NaNs, \" + tmsg.str();\n                std::string msgNotNan = \" has buffer overflow/underflow, \" + tmsg.str();\n\n                float relErr = Err<float>::Rel;\n                float absErr = Err<float>::Abs;\n                std::string emsg;\n\n                BOOST_REQUIRE_MESSAGE(!out.HasNan(\"out\"), \"out\" << msgNan);\n                BOOST_REQUIRE_MESSAGE(CheckEqual(out, outB, emsg, relErr, absErr * 8), \"out\" << msg << \". \" << emsg);\n                BOOST_REQUIRE_MESSAGE(CountNans(outBuf) == crowOut * 2 * n, \"out\" << msgNotNan);\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PoolingBackward)\n{\n    std::mt19937 rng(0);\n    boost::random::uniform_int_distribution<> batchSizeG(1, 8);\n    boost::random::normal_distribution<float> nd;\n\n    auto initMat = [&](SingleMatrix& buf, size_t r, size_t c, vec& data) -> SingleMatrix\n    {\n        data.resize(r * 3 * c);\n        std::fill(begin(data), end(data), std::numeric_limits<float>::quiet_NaN());\n        std::generate(begin(data) + r * c, begin(data) + 2 * r * c, [&] { return nd(rng); });\n        buf.SetValue(r, 3 * c, buf.GetDeviceId(), data.data());\n        // Get center slice.\n        return buf.ColumnSlice(c, c);\n    };\n\n    int baseDeviceId = 0;\n    auto engKind = ConvolutionEngineKind::Reference;\n    for (auto kind : {PoolKind::Max, PoolKind::Average})\n    {\n        for (int deviceId : {-1, 0})\n        {\n            for (const auto& g : GeneratePoolTestConfigs())\n            {\n                auto baseEng = ConvEng::Create(g, baseDeviceId, ImageLayoutKind::CHW, 0, kind, ConvolutionEngineKind::CuDnn);\n                auto testEng = ConvEng::Create(g, deviceId, ImageLayoutKind::CHW, 0, kind, engKind);\n\n                size_t n = batchSizeG(rng);\n                vec buf;\n                size_t crowIn = g->InputShape().GetNumElements();\n                buf.resize(crowIn * n);\n                std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n                SingleMatrix inB(crowIn, n, buf.data(), baseDeviceId, matrixFlagNormal);\n                SingleMatrix in(crowIn, n, buf.data(), deviceId, matrixFlagNormal);\n\n                size_t crowOut = g->OutputShape().GetNumElements();\n                buf.resize(crowOut * n);\n                std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n                SingleMatrix srcGradB(crowOut, n, buf.data(), baseDeviceId, matrixFlagNormal);\n                SingleMatrix srcGrad(crowOut, n, buf.data(), deviceId, matrixFlagNormal);\n                // Do not generate for out as it will be replaced anyway.\n                SingleMatrix outB(crowOut, n, buf.data(), baseDeviceId, matrixFlagNormal);\n                SingleMatrix out(crowOut, n, buf.data(), deviceId, matrixFlagNormal);\n\n                testEng->ForwardPooling(in, out);\n                baseEng->ForwardPooling(inB, outB);\n\n                SingleMatrix gradBuf(deviceId);\n                SingleMatrix grad = initMat(gradBuf, crowIn, n, buf);\n                SingleMatrix gradB(grad.DeepClone(), baseDeviceId);\n\n                testEng->BackwardPooling(out, srcGrad, in, grad);\n                baseEng->BackwardPooling(outB, srcGradB, inB, gradB);\n\n                std::stringstream tmsg;\n                tmsg << \"Geometry: \" << (std::string)(*g) << \", Pool: \" << (int)kind << \", Batch: \" << n << \", Device: \" << deviceId;\n                std::string msg = \" are not equal, \" + tmsg.str();\n                std::string msgNan = \" has NaNs, \" + tmsg.str();\n                std::string msgNotNan = \" has buffer overflow/underflow, \" + tmsg.str();\n\n                float relErr = Err<float>::Rel;\n                float absErr = Err<float>::Abs;\n                std::string emsg;\n\n                BOOST_REQUIRE_MESSAGE(!grad.HasNan(\"grad\"), \"grad\" << msgNan);\n                BOOST_REQUIRE_MESSAGE(CheckEqual(grad, gradB, emsg, relErr, absErr * 8), \"grad\" << msg << \". \" << emsg);\n                BOOST_REQUIRE_MESSAGE(CountNans(gradBuf) == crowIn * 2 * n, \"grad\" << msgNotNan);\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(MaxUnpooling)\n{\n    using IntMatrix = Matrix<int>;\n\n    std::mt19937 rng(0);\n    boost::random::uniform_int_distribution<> batchSizeG(1, 8);\n    // Using uniform distribution with positive values to avoid issues with\n    // unpooling negative values.\n    boost::random::uniform_real_distribution<float> nd(0, 1);\n\n    auto initMat = [&](SingleMatrix& buf, size_t r, size_t c, vec& data) -> SingleMatrix\n    {\n        data.resize(r * 3 * c);\n        std::fill(begin(data), end(data), std::numeric_limits<float>::quiet_NaN());\n        std::generate(begin(data) + r * c, begin(data) + 2 * r * c, [&] { return nd(rng); });\n        buf.SetValue(r, 3 * c, buf.GetDeviceId(), data.data());\n        // Get center slice.\n        return buf.ColumnSlice(c, c);\n    };\n\n    int cpuDeviceId = -1;\n    int gpuDeviceId = 0;\n\n    for (const auto& g : GeneratePoolTestConfigs())\n    {\n        // cpuEng and gpuEng are used to compare results against each other.\n        auto cpuEng = ConvEng::Create(g, cpuDeviceId, ImageLayoutKind::CHW, 0, PoolKind::Max, ConvolutionEngineKind::Reference);\n        auto gpuEng = ConvEng::Create(g, gpuDeviceId, ImageLayoutKind::CHW, 0, PoolKind::Max, ConvolutionEngineKind::Reference);\n\n        size_t n = batchSizeG(rng);\n        vec buf;\n        buf.resize(g->InputShape().GetNumElements() * n);\n        std::generate(begin(buf), end(buf), [&] { return nd(rng); });\n        SingleMatrix inC(g->InputShape().GetNumElements(), n, buf.data(), cpuDeviceId, matrixFlagNormal);\n        SingleMatrix inG(g->InputShape().GetNumElements(), n, buf.data(), gpuDeviceId, matrixFlagNormal);\n\n        // First, compute max pooling output and corresponding mask.\n        SingleMatrix outC(g->OutputShape().GetNumElements(), n, cpuDeviceId);\n        SingleMatrix outG(g->OutputShape().GetNumElements(), n, gpuDeviceId);\n\n        cpuEng->ForwardPooling(inC, outC);\n        gpuEng->ForwardPooling(inG, outG);\n        \n        // Second, do the unpooling.\n        size_t crowIn = g->InputShape().GetNumElements();\n        SingleMatrix inUBufC(cpuDeviceId);\n        SingleMatrix inUC = initMat(inUBufC, crowIn, n, buf);\n        SingleMatrix inUBufG(inUBufC.DeepClone(), gpuDeviceId);\n        SingleMatrix inUG = initMat(inUBufG, crowIn, n, buf);\n\n        cpuEng->MaxUnpooling(outC, inC, inUC);\n        gpuEng->MaxUnpooling(outG, inG, inUG);\n\n        // Check that CPU/GPU results are the same.\n        std::stringstream tmsg;\n        tmsg << \"Geometry: \" << (std::string)(*g) << \", Batch: \" << n;\n        std::string msg = \" are not equal, \" + tmsg.str();\n        std::string msgNan = \" has NaNs, \" + tmsg.str();\n        std::string msgNotNan = \" has buffer overflow/underflow, \" + tmsg.str();\n\n        float relErr = 0;\n        float absErr = 0;\n        std::string emsg;\n\n        BOOST_REQUIRE_MESSAGE(!inUC.HasNan(\"inUC\"), \"inUC\" << msgNan);\n        BOOST_REQUIRE_MESSAGE(!inUG.HasNan(\"inUG\"), \"inUG\" << msgNan);\n        BOOST_REQUIRE_MESSAGE(CheckEqual(inUC, inUG, emsg, relErr, absErr), \"inU\" << msg << \". \" << emsg);\n        BOOST_REQUIRE_MESSAGE(CountNans(inUBufC) == crowIn * 2 * n, \"inUBufC\" << msgNotNan);\n        BOOST_REQUIRE_MESSAGE(CountNans(inUBufG) == crowIn * 2 * n, \"inUBufG\" << msgNotNan);\n\n        // Now do the pooling from unpooled source and compare with original pooling.\n        SingleMatrix outC_2(g->OutputShape().GetNumElements(), n, cpuDeviceId);\n        SingleMatrix outG_2(g->OutputShape().GetNumElements(), n, gpuDeviceId);\n        cpuEng->ForwardPooling(inUC, outC_2);\n        gpuEng->ForwardPooling(inUG, outG_2);\n\n        BOOST_REQUIRE_MESSAGE(CheckEqual(outC_2, outC, emsg, relErr, absErr), \"outC_2\" << msg << \". \" << emsg);\n        BOOST_REQUIRE_MESSAGE(CheckEqual(outG_2, outG, emsg, relErr, absErr), \"outG_2\" << msg << \". \" << emsg);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n} } } }\n", "meta": {"hexsha": "db265932e5a471d1ffe100e2bf2e06fa6b065ab9", "size": 27304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/UnitTests/MathTests/ConvolutionEngineTests.cpp", "max_stars_repo_name": "Wootai/CNTK", "max_stars_repo_head_hexsha": "5eca042341c8152594e67652a44c3b733a2acaa0", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-08-28T08:27:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T21:12:52.000Z", "max_issues_repo_path": "Tests/UnitTests/MathTests/ConvolutionEngineTests.cpp", "max_issues_repo_name": "zhuyawen/CNTK", "max_issues_repo_head_hexsha": "0ee09cf771bda9d4912790e0fed7322e89d86d87", "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": "Tests/UnitTests/MathTests/ConvolutionEngineTests.cpp", "max_forks_repo_name": "zhuyawen/CNTK", "max_forks_repo_head_hexsha": "0ee09cf771bda9d4912790e0fed7322e89d86d87", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-23T11:42:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T08:41:32.000Z", "avg_line_length": 46.2779661017, "max_line_length": 174, "alphanum_fraction": 0.5940155289, "num_tokens": 7173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.19758571132455974}}
{"text": "#ifndef FAST_GICP_FAST_VGICP_CUDA_HPP\n#define FAST_GICP_FAST_VGICP_CUDA_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/registration/registration.h>\n\n#include <fast_gicp/gicp/gicp_settings.hpp>\n#include <fast_gicp/gicp/lsq_registration.hpp>\n\nnamespace fast_gicp {\n\nnamespace cuda {\nclass FastVGICPCudaCore;\n}\n\nenum class NearestNeighborMethod { CPU_PARALLEL_KDTREE, GPU_BRUTEFORCE, GPU_RBF_KERNEL };\n\n/**\n * @brief Fast Voxelized GICP algorithm boosted with CUDA\n */\ntemplate<typename PointSource, typename PointTarget>\nclass FastVGICPCuda : public LsqRegistration<PointSource, PointTarget> {\npublic:\n  using Scalar = float;\n  using Matrix4 = typename pcl::Registration<PointSource, PointTarget, Scalar>::Matrix4;\n\n  using PointCloudSource = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudSource;\n  using PointCloudSourcePtr = typename PointCloudSource::Ptr;\n  using PointCloudSourceConstPtr = typename PointCloudSource::ConstPtr;\n\n  using PointCloudTarget = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudTarget;\n  using PointCloudTargetPtr = typename PointCloudTarget::Ptr;\n  using PointCloudTargetConstPtr = typename PointCloudTarget::ConstPtr;\n\n#if PCL_VERSION >= PCL_VERSION_CALC(1, 10, 0)\n  using Ptr = pcl::shared_ptr<FastVGICPCuda<PointSource, PointTarget>>;\n  using ConstPtr = pcl::shared_ptr<const FastVGICPCuda<PointSource, PointTarget>>;\n#else\n  using Ptr = boost::shared_ptr<FastVGICPCuda<PointSource, PointTarget>>;\n  using ConstPtr = boost::shared_ptr<const FastVGICPCuda<PointSource, PointTarget>>;\n#endif\n\nprotected:\n  using pcl::Registration<PointSource, PointTarget, Scalar>::input_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::target_;\n\npublic:\n  FastVGICPCuda();\n  virtual ~FastVGICPCuda() override;\n\n  void setCorrespondenceRandomness(int k);\n  void setResolution(double resolution);\n  void setKernelWidth(double kernel_width, double max_dist = -1.0);\n  void setRegularizationMethod(RegularizationMethod method);\n  void setNeighborSearchMethod(NeighborSearchMethod method, double radius = -1.0);\n  void setNearestNeighborSearchMethod(NearestNeighborMethod method);\n\n  virtual void swapSourceAndTarget() override;\n  virtual void clearSource() override;\n  virtual void clearTarget() override;\n\n  virtual void setInputSource(const PointCloudSourceConstPtr& cloud) override;\n  virtual void setInputTarget(const PointCloudTargetConstPtr& cloud) override;\n\nprotected:\n  virtual void computeTransformation(PointCloudSource& output, const Matrix4& guess) override;\n  virtual double linearize(const Eigen::Isometry3d& trans, Eigen::Matrix<double, 6, 6>* H = nullptr, Eigen::Matrix<double, 6, 1>* b = nullptr) override;\n  virtual double compute_error(const Eigen::Isometry3d& trans) override;\n\n  template<typename PointT>\n  std::vector<int> find_neighbors_parallel_kdtree(int k, typename pcl::PointCloud<PointT>::ConstPtr cloud) const;\n\nprivate:\n  int k_correspondences_;\n  double voxel_resolution_;\n  RegularizationMethod regularization_method_;\n  NearestNeighborMethod neighbor_search_method_;\n\n  std::unique_ptr<cuda::FastVGICPCudaCore> vgicp_cuda_;\n};\n\n}  // namespace fast_gicp\n\n#endif\n", "meta": {"hexsha": "2eb21d74dc6e6e10aefc21959bc794b2b8c7bce6", "size": 3279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fast_gicp/gicp/fast_vgicp_cuda.hpp", "max_stars_repo_name": "Gatsby23/fast_gicp", "max_stars_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "include/fast_gicp/gicp/fast_vgicp_cuda.hpp", "max_issues_repo_name": "Gatsby23/fast_gicp", "max_issues_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "include/fast_gicp/gicp/fast_vgicp_cuda.hpp", "max_forks_repo_name": "Gatsby23/fast_gicp", "max_forks_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 36.4333333333, "max_line_length": 152, "alphanum_fraction": 0.7990240927, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1975849450029357}}
{"text": "#pragma once\n#include <algorithm>\n#include <type_traits>\n#include <functional>\n#include <autoppl/util/var_traits.hpp>\n#include <autoppl/util/model_expr_traits.hpp>\n#include <autoppl/util/dist_expr_traits.hpp>\n#include <type_traits>\n#include <typeinfo>       // operator typeid\n#include <boost/uuid/uuid.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <autoppl/program_analysis/dependencies_intervals.hpp>\n#include <autoppl/program_analysis/UncertainIntervals/IntervalAnalysis.hpp>\n\nnamespace ppl {\nnamespace expr {\n\nstruct EqNodeParent {};\nstruct EqNodeCont {};\nstruct EqNodeDisc {};\n\n/**\n * This class represents a \"node\" in the model expression\n * that relates a var with a distribution.\n */\n#if __cplusplus <= 201703L\ntemplate <class VarType, class DistType>\n#else\ntemplate <util::var VarType, util::dist_expr DistType>\n#endif\nstruct EqNode : util::ModelExpr<EqNode<VarType, DistType>>, EqNodeParent, std::conditional_t<std::is_base_of_v<util::continuous_dist_base, DistType>, EqNodeCont, EqNodeDisc>\n{\n\n#if __cplusplus <= 201703L\n    static_assert(util::assert_is_var_v<VarType>);\n    static_assert(util::assert_is_dist_expr_v<DistType>);\n#endif\n\n    using var_t = VarType;\n    using dist_t = DistType;\n    using dist_value_t = typename util::dist_expr_traits<dist_t>::dist_value_t;\n\n    EqNode(var_t& var, \n           const dist_t& dist) noexcept\n        : orig_var_ref_{var}\n        , dist_{dist}\n    {}\n\n\n    template <class EqNodeFunc>\n    void traverse(EqNodeFunc&& eq_f)\n    {\n        using this_t = EqNode<VarType, DistType>;\n        eq_f(static_cast<this_t&>(*this));\n    }\n\n    template <class EqNodeFunc>\n    void traverse(EqNodeFunc&& eq_f) const\n    {\n        using this_t = EqNode<VarType, DistType>;\n        eq_f(static_cast<const this_t&>(*this));\n    }\n\n\n    dist_value_t pdf() const {\n        return dist_.pdf(get_variable());\n    }\n\n    dist_value_t log_pdf() const {\n        return dist_.log_pdf(get_variable());\n    }\n\n\n    auto& get_variable() { return orig_var_ref_.get(); }\n    const auto& get_variable() const { return orig_var_ref_.get(); }\n    const auto& get_distribution() const { return dist_; }\n\n\n    std::set<boost::uuids::uuid> getDeps(){\n\treturn dist_.getDeps();\n    }\n\n    std::set<boost::uuids::uuid> getVarID(){\n\treturn orig_var_ref_.get().getDeps();\n    }\n\n\n    void getInterval(){\n\t//get  distribution's interval\n\tDeterministicInterval dist_range = dist_.getInterval();\n\t//get  var's id\n\tboost::uuids::uuid var_id = orig_var_ref_.get().getUUID();\n\tstd::cout << dist_range.upper << std::endl;\n\t//map them together\n\tglobals::intervals.insert({var_id,dist_range});\n    }\n\n    void getLikelihoodInterval(){\n\n\t//check if my variable is a data or param\n\tif constexpr (util::is_data_v<var_t>){\n\t\tboost::uuids::uuid var_id = orig_var_ref_.get().getUUID();\n\t\tint NumDataPoints = orig_var_ref_.get().size();\n\t\tDeterministicInterval DataInterval = orig_var_ref_.get().getDataInterval();\n\t\t\n\t\tDeterministicInterval BiggestInterval(0.,0.);\n\t\tDeterministicInterval LikelihoodInterval = dist_.log_pdf_interval(DataInterval,BiggestInterval);\n\n\t\tglobals::single_likelihood_intervals.insert({var_id,LikelihoodInterval});\n\n\t\t//account for the likelihood sum over all data points\n\t\tif (NumDataPoints > 0){\n\t\t\tLikelihoodInterval = scale(double(NumDataPoints)/double(4),LikelihoodInterval);\n\t\t}\n\t\tBiggestInterval = union_(BiggestInterval,LikelihoodInterval);\n\n\t\tglobals::likelihood_intervals.insert({var_id,LikelihoodInterval});\n\t\tglobals::biggest_intervals.insert({var_id,BiggestInterval});\n\t}\n\n    }\n\n\nprivate:\n    using var_ref_t = std::reference_wrapper<var_t>;    \n    var_ref_t orig_var_ref_;                           \n    dist_t dist_;                 \n\n\n};\n\n} // namespace expr\n} // namespace ppl\n", "meta": {"hexsha": "fd46187551f15fe5472553cd952c8f2fd7ea3cdf", "size": 3768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autoppl/expression/model/eq_node.hpp", "max_stars_repo_name": "uiuc-arc/Statheros", "max_stars_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "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": "autoppl/expression/model/eq_node.hpp", "max_issues_repo_name": "uiuc-arc/Statheros", "max_issues_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "autoppl/expression/model/eq_node.hpp", "max_forks_repo_name": "uiuc-arc/Statheros", "max_forks_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "max_forks_repo_licenses": ["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.9111111111, "max_line_length": 173, "alphanum_fraction": 0.7078025478, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"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 \"read_into_bdd.hpp\"\n\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/range/algorithm.hpp>\n\n#include <core/utils/range_utils.hpp>\n#include <core/utils/timer.hpp>\n#include <classical/aig.hpp>\n#include <classical/dd/aig_to_cirkit_bdd.hpp>\n#include <classical/io/read_aiger.hpp>\n#include <classical/io/read_pla_to_cirkit_bdd.hpp>\n#include <classical/utils/aig_utils.hpp>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nstd::pair<bdd_manager_ptr, std::vector<bdd>> read_into_bdd( const std::string& filename,\n                                                            const properties::ptr& settings,\n                                                            const properties::ptr& statistics )\n{\n  /* settings */\n  auto log_max_objs = get( settings, \"log_max_objs\", 24u );\n\n  /* timing */\n  properties_timer t( statistics );\n\n  if ( boost::ends_with( filename, \".pla\" ) )\n  {\n    auto function = read_pla_into_cirkit_bdd( filename, settings );\n    std::vector<bdd> fs( function->num_outputs() );\n    for ( auto i = 0u; i < function->num_outputs(); ++i )\n    {\n      fs[i] = function->lookupOutput( i );\n    }\n\n    set( statistics, \"input_labels\", function->input_labels() );\n    set( statistics, \"output_labels\", function->output_labels() );\n\n    return std::make_pair( function->manager(), fs );\n  }\n  else if ( boost::ends_with( filename, \".aag\" ) )\n  {\n    aig_graph aig;\n    read_aiger( aig, filename );\n\n    std::vector<bdd> fs;\n    cirkit_bdd_simulator sim( aig, log_max_objs );\n    auto map = simulate_aig( aig, sim );\n\n    for ( const auto& m : map )\n    {\n      fs.push_back( m.second );\n    }\n\n    if ( statistics )\n    {\n      const auto info = aig_info( aig );\n      std::vector<std::string> input_labels( info.inputs.size() );\n      boost::transform( info.inputs, input_labels.begin(), [&]( const aig_node& n ) { return info.node_names.at( n ); } );\n      auto output_labels = get_map_values( info.outputs );\n      set( statistics, \"input_labels\", input_labels );\n      set( statistics, \"output_labels\", output_labels );\n    }\n\n    return std::make_pair( sim.mgr, fs );\n  }\n\n  std::cerr << \"[e] unknown suffix\" << std::endl;\n  assert( false );\n\n  return std::make_pair( bdd_manager_ptr(), std::vector<bdd>() );\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": "e7bd349457152202733fffdae4968b323fa28eec", "size": 4286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/io/read_into_bdd.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/io/read_into_bdd.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/io/read_into_bdd.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": 36.0168067227, "max_line_length": 122, "alphanum_fraction": 0.5636957536, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "#include \"blockrelay/graphene_set.h\"\n#include \"bloom.h\"\n#include \"hash.h\"\n#include \"serialize.h\"\n#include \"streams.h\"\n#include \"test/test_bitcoin.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n\n// Create a deterministic hash by providing an index\nuint256 GetHash(unsigned int nIndex)\n{\n    std::stringstream ss;\n    ss << std::setfill('0') << std::setw(32) << nIndex;\n    return uint256S(ss.str());\n}\n\nBOOST_FIXTURE_TEST_SUITE(graphene_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(graphene_set_encodes_and_decodes)\n{\n    uint256 senderArr[] = {\n        SerializeHash(3), SerializeHash(1), SerializeHash(2), SerializeHash(7), SerializeHash(11), SerializeHash(4)};\n    std::vector<uint256> senderItems(senderArr, senderArr + sizeof(senderArr) / sizeof(uint256));\n    uint256 receiverArr[] = {\n        SerializeHash(7), SerializeHash(2), SerializeHash(4), SerializeHash(-1), SerializeHash(1), SerializeHash(11)};\n    std::vector<uint256> receiverItems(receiverArr, receiverArr + sizeof(receiverArr) / sizeof(uint256));\n\n    // unordered graphene sets\n    {\n        CGrapheneSet senderGrapheneSet(6, senderItems, false, true);\n        std::vector<uint64_t> reconciledCheapHashes = senderGrapheneSet.Reconcile(receiverItems);\n\n        std::vector<uint64_t> senderCheapHashes;\n        for (uint256 item : senderItems)\n            senderCheapHashes.push_back(item.GetCheapHash());\n\n        std::sort(senderCheapHashes.begin(), senderCheapHashes.end(), [](uint64_t i1, uint64_t i2) { return i1 < i2; });\n        std::sort(reconciledCheapHashes.begin(), reconciledCheapHashes.end(),\n            [](uint64_t i1, uint64_t i2) { return i1 < i2; });\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(reconciledCheapHashes.begin(), reconciledCheapHashes.end(),\n            senderCheapHashes.begin(), senderCheapHashes.end());\n    }\n\n    // ordered graphene sets\n    {\n        CGrapheneSet senderGrapheneSet(6, senderItems, true, true);\n        std::vector<uint64_t> reconciledCheapHashes = senderGrapheneSet.Reconcile(receiverItems);\n\n        std::vector<uint64_t> senderCheapHashes;\n        for (uint256 item : senderItems)\n            senderCheapHashes.push_back(item.GetCheapHash());\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(reconciledCheapHashes.begin(), reconciledCheapHashes.end(),\n            senderCheapHashes.begin(), senderCheapHashes.end());\n    }\n}\n\nBOOST_AUTO_TEST_CASE(graphene_set_decodes_multiple_sizes)\n{\n    size_t nItemList[] = {1, 10, 50, 500, 5000, 10000};\n    int nNumHashes = 0;\n    for (size_t nItems : nItemList)\n    {\n        std::vector<uint256> senderItems;\n        std::vector<uint64_t> senderCheapHashes;\n        std::vector<uint256> baseReceiverItems;\n        for (size_t i = 1; i <= nItems; i++)\n        {\n            nNumHashes++;\n            const uint256 &hash = GetHash(nNumHashes);\n            senderItems.push_back(hash);\n            senderCheapHashes.push_back(hash.GetCheapHash());\n            baseReceiverItems.push_back(hash);\n        }\n\n        // Add 10 more items to receiver mempool\n        {\n            std::vector<uint256> receiverItems = baseReceiverItems;\n            for (size_t j = 1; j < 11; j++)\n            {\n                nNumHashes++;\n                receiverItems.push_back(SerializeHash(GetHash(nNumHashes)));\n            }\n\n            CGrapheneSet senderGrapheneSet(receiverItems.size(), senderItems, true, true);\n            std::vector<uint64_t> reconciledCheapHashes = senderGrapheneSet.Reconcile(receiverItems);\n\n            BOOST_CHECK_EQUAL_COLLECTIONS(reconciledCheapHashes.begin(), reconciledCheapHashes.end(),\n                senderCheapHashes.begin(), senderCheapHashes.end());\n        }\n\n        // Add 100 more items to receiver mempool\n        {\n            std::vector<uint256> receiverItems = baseReceiverItems;\n            for (size_t j = 1; j < 101; j++)\n            {\n                nNumHashes++;\n                receiverItems.push_back(SerializeHash(GetHash(nNumHashes)));\n            }\n\n            CGrapheneSet senderGrapheneSet(receiverItems.size(), senderItems, true, true);\n            std::vector<uint64_t> reconciledCheapHashes = senderGrapheneSet.Reconcile(receiverItems);\n\n            BOOST_CHECK_EQUAL_COLLECTIONS(reconciledCheapHashes.begin(), reconciledCheapHashes.end(),\n                senderCheapHashes.begin(), senderCheapHashes.end());\n        }\n\n    }\n}\n\nBOOST_AUTO_TEST_CASE(graphene_set_finds_optimal_settings)\n{\n    const int SERIALIZATION_OVERHEAD = 11;\n    FastRandomContext insecure_rand(true);\n    CGrapheneSet grapheneSet;\n\n    int m = 5000;\n    int mu = 2999;\n    int n = 3000;\n\n    auto fpr = [m, mu](int a) { return a / float(m - mu); };\n\n    int best_a = 1;\n    size_t best_size = std::numeric_limits<size_t>::max();\n    int a = 1;\n    for (a = 1; a < m - mu; a++)\n    {\n        CBloomFilter filter(n, fpr(a), insecure_rand.rand32(), BLOOM_UPDATE_ALL, true, std::numeric_limits<uint32_t>::max());\n        CIblt iblt(a);\n\n        size_t filterBytes = ::GetSerializeSize(filter, SER_NETWORK, PROTOCOL_VERSION) - SERIALIZATION_OVERHEAD;\n        size_t ibltBytes = ::GetSerializeSize(iblt, SER_NETWORK, PROTOCOL_VERSION) - SERIALIZATION_OVERHEAD;\n        size_t total = filterBytes + ibltBytes;\n\n        if (total < best_size)\n        {\n            best_size = total;\n            best_a = a;\n        }\n    }\n\n    BOOST_CHECK_EQUAL(grapheneSet.OptimalSymDiff(n, m), best_a);\n}\n\nBOOST_AUTO_TEST_CASE(graphene_set_can_serde)\n{\n    std::vector<uint256> senderItems;\n    CDataStream ss(SER_DISK, 0);\n\n    senderItems.push_back(SerializeHash(3));\n    CGrapheneSet sentGrapheneSet(1, senderItems, true);\n    CGrapheneSet receivedGrapheneSet;\n\n    ss << sentGrapheneSet;\n    ss >> receivedGrapheneSet;\n\n    BOOST_CHECK_EQUAL(receivedGrapheneSet.Reconcile(senderItems)[0], senderItems[0].GetCheapHash());\n}\n\nBOOST_AUTO_TEST_CASE(item_rank_encodes_and_decodes)\n{\n    uint64_t itemArr[4] = {1, 20, 500, 7000};\n    std::vector<uint64_t> inputItems(itemArr, itemArr + sizeof(itemArr) / sizeof(uint64_t));\n    uint16_t nBits = 13;\n\n    std::vector<unsigned char> encoded = CGrapheneSet::EncodeRank(inputItems, nBits);\n    std::vector<uint64_t> outputItems = CGrapheneSet::DecodeRank(encoded, inputItems.size(), nBits);\n\n    BOOST_CHECK_EQUAL_COLLECTIONS(outputItems.begin(), outputItems.end(), inputItems.begin(), inputItems.end());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c4dad2ba7837ec12de66843688bbba69870a3a41", "size": 6385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/graphene_tests.cpp", "max_stars_repo_name": "jtoomim/BitcoinUnlimited", "max_stars_repo_head_hexsha": "b7b9b59a8440f720c5e0c3d5aeb1bcc4e48f1b9c", "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/test/graphene_tests.cpp", "max_issues_repo_name": "jtoomim/BitcoinUnlimited", "max_issues_repo_head_hexsha": "b7b9b59a8440f720c5e0c3d5aeb1bcc4e48f1b9c", "max_issues_repo_licenses": ["MIT"], "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/graphene_tests.cpp", "max_forks_repo_name": "jtoomim/BitcoinUnlimited", "max_forks_repo_head_hexsha": "b7b9b59a8440f720c5e0c3d5aeb1bcc4e48f1b9c", "max_forks_repo_licenses": ["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.8707865169, "max_line_length": 125, "alphanum_fraction": 0.6704776821, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "/**\n * Copyright (c) 2017 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 \"../coordsManip.hpp\"\n\n#include \"../include/vts-browser/mapCallbacks.hpp\" // ensure that projFinderCallback is visible\n\n#include <boost/utility/in_place_factory.hpp>\n#include <GeographicLib/Geodesic.hpp>\n#include \"geo/detail/projapi.hpp\"\n\n#include <vts-libs/vts/csconvertor.hpp>\n#include <vts-libs/vts/mapconfig.hpp>\n\n#include <unordered_map>\n#include <memory>\n#include <functional>\n\nnamespace vts\n{\n\nstd::function<const char *(const char *)> &projFinderCallback()\n{\n    static std::function<const char *(const char *)> fnc;\n    return fnc;\n}\n\nnamespace\n{\n\nconst char *pjFind(const char *p)\n{\n    if (!p)\n        return nullptr; // nothing to look for? nothing to return.\n    if (projFinderCallback())\n        return projFinderCallback()(p);\n    return nullptr;\n}\n\n// disable PROJ's file access on some systems\nPAFile pjFOpen(projCtx ctx, const char *filename, const char *access)\n{\n    return nullptr;\n}\nsize_t pjFRead(void *buffer, size_t size, size_t nmemb, PAFile file)\n{\n    return 0;\n}\nint pjFSeek(PAFile file, long offset, int whence)\n{\n    return 0;\n}\nlong pjFTell(PAFile file)\n{\n    return 0;\n}\nvoid pjFClose(PAFile file)\n{}\n\nstruct projInitClass\n{\n    projFileAPI_t pjFileApi;\n\n    projInitClass()\n    {\n        pjFileApi.FOpen = &pjFOpen;\n        pjFileApi.FRead = &pjFRead;\n        pjFileApi.FSeek = &pjFSeek;\n        pjFileApi.FTell = &pjFTell;\n        pjFileApi.FClose = &pjFClose;\n        pj_set_finder(&pjFind);\n    }\n} projInitInstance;\n\nclass CoordManipImpl : public CoordManip\n{\npublic:\n    vtslibs::vts::MapConfig &mapconfig;\n    std::unordered_map<std::string, std::unique_ptr<vtslibs::vts::CsConvertor>> convertors;\n    boost::optional<GeographicLib::Geodesic> geodesic_;\n    projCtx ctx = nullptr;\n\n    CoordManipImpl(\n            vtslibs::vts::MapConfig &mapconfig,\n            const std::string &searchSrs,\n            const std::string &customSrs1,\n            const std::string &customSrs2) :\n        mapconfig(mapconfig),\n        ctx(pj_ctx_alloc())\n    {\n        LOG(info1) << \"Creating coordinate systems manipulator\";\n\n#ifdef __EMSCRIPTEN__\n        pj_ctx_set_fileapi(ctx, &projInitInstance.pjFileApi);\n#endif\n\n        // create geodesic\n        {\n            auto r = geo::ellipsoid(mapconfig.srs(mapconfig.referenceFrame.model.navigationSrs).srsDef);\n            auto a = r[0];\n            auto b = r[2];\n            LOG(info1) << \"Creating geodesic manipulator: a=<\" << a << \">, b=<\" << b << \">\";\n            geodesic_ = boost::in_place(a, (a - b) / a);\n        }\n\n        addSrsDef(\"$search$\", searchSrs);\n        addSrsDef(\"$custom1$\", customSrs1);\n        addSrsDef(\"$custom2$\", customSrs2);\n    }\n\n    ~CoordManipImpl()\n    {\n        pj_ctx_free(ctx);\n    }\n\n    void addSrsDef(const std::string &name, const std::string &def)\n    {\n        vtslibs::registry::Srs s;\n        s.comment = name;\n        s.srsDef = geo::SrsDefinition::fromString(def);\n        mapconfig.srs.replace(name, s);\n    }\n\n    const std::string &srsToProj(Srs srs)\n    {\n        static const std::string search = \"$search$\";\n        static const std::string custom1 = \"$custom1$\";\n        static const std::string custom2 = \"$custom2$\";\n        switch(srs)\n        {\n        case Srs::Physical:\n            return mapconfig.referenceFrame.model.physicalSrs;\n        case Srs::Navigation:\n            return mapconfig.referenceFrame.model.navigationSrs;\n        case Srs::Public:\n            return mapconfig.referenceFrame.model.publicSrs;\n        case Srs::Search:\n            return search;\n        case Srs::Custom1:\n            return custom1;\n        case Srs::Custom2:\n            return custom2;\n        default:\n            LOGTHROW(fatal, std::invalid_argument) << \"Invalid srs enum\";\n            throw;\n        }\n    }\n\n    vtslibs::vts::CsConvertor &convertor(const std::string &a, const std::string &b)\n    {\n        const std::string key = a + \" >>> \" + b;\n        auto it = convertors.find(key);\n        if (it == convertors.end())\n        {\n            convertors[key] = std::make_unique<vtslibs::vts::CsConvertor>(a, b, mapconfig, ctx);\n            it = convertors.find(key);\n        }\n        return *it->second;\n    }\n\n    vec3 convert(const vec3 &value, const std::string &f, const std::string &t)\n    {\n        const auto &cs = convertor(f, t);\n        vec3 res = vecFromUblas<vec3>(cs(vecFromUblas<math::Point3>(value)));\n        //LOG(debug) << \"Converted <\" << value.transpose() << \"><\" << f << \"> to <\" << res.transpose() << \"><\" << t << \">\";\n        return res;\n    }\n};\n\n} // namespace\n\nstd::shared_ptr<CoordManip> CoordManip::create(\n    vtslibs::vts::MapConfig &mapconfig,\n    const std::string &searchSrs,\n    const std::string &customSrs1,\n    const std::string &customSrs2)\n{\n    return std::make_shared<CoordManipImpl>(mapconfig, searchSrs, customSrs1, customSrs2);\n}\n\nvec3 CoordManip::navToPhys(const vec3 &value)\n{\n    return convert(value, Srs::Navigation, Srs::Physical);\n}\n\nvec3 CoordManip::physToNav(const vec3 &value)\n{\n    return convert(value, Srs::Physical, Srs::Navigation);\n}\n\nvec3 CoordManip::searchToNav(const vec3 &value)\n{\n    return convert(value, Srs::Search, Srs::Navigation);\n}\n\nvec3 CoordManip::convert(const vec3 &value, Srs from, Srs to)\n{\n    CoordManipImpl *impl = (CoordManipImpl *)this;\n    return impl->convert(value, impl->srsToProj(from), impl->srsToProj(to));\n}\n\nvec3 CoordManip::convert(const vec3 &value, const std::string &from, Srs to)\n{\n    CoordManipImpl *impl = (CoordManipImpl *)this;\n    return impl->convert(value, from, impl->srsToProj(to));\n}\n\nvec3 CoordManip::convert(const vec3 &value, Srs from, const std::string &to)\n{\n    CoordManipImpl *impl = (CoordManipImpl *)this;\n    return impl->convert(value, impl->srsToProj(from), to);\n}\n\nvec3 CoordManip::geoDirect(const vec3 &position, double distance, double azimuthIn, double &azimuthOut)\n{\n    CoordManipImpl *impl = (CoordManipImpl *)this;\n    vec3 res;\n    impl->geodesic_->Direct(position(1), position(0), azimuthIn, distance, res(1), res(0), azimuthOut);\n    res(2) = position(2);\n    return res;\n}\n\nvec3 CoordManip::geoDirect(const vec3 &position, double distance, double azimuthIn)\n{\n    double a;\n    return geoDirect(position, distance, azimuthIn, a);\n}\n\nvoid CoordManip::geoInverse(const vec3 &a, const vec3 &b, double &distance, double &azimuthA, double &azimuthB)\n{\n    CoordManipImpl *impl = (CoordManipImpl *)this;\n    impl->geodesic_->Inverse(a(1), a(0), b(1), b(0), distance, azimuthA, azimuthB);\n}\n\ndouble CoordManip::geoAzimuth(const vec3 &a, const vec3 &b)\n{\n    double d, a1, a2;\n    geoInverse(a, b, d, a1, a2);\n    return a1;\n}\n\ndouble CoordManip::geoDistance(const vec3 &a, const vec3 &b)\n{\n    double d, a1, a2;\n    geoInverse(a, b, d, a1, a2);\n    return d;\n}\n\ndouble CoordManip::geoArcDist(const vec3 &a, const vec3 &b)\n{\n    CoordManipImpl *impl = (CoordManipImpl *)this;\n    double dummy;\n    return impl->geodesic_->Inverse(a(1), a(0), b(1), b(0), dummy);\n}\n\n} // namespace vts\n", "meta": {"hexsha": "370bec6aa59f40a8f695f1ad751830202f43161d", "size": 8316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "browser/src/vts-libbrowser/map/coordsManip.cpp", "max_stars_repo_name": "ExploreWilder/vts-browser-cpp", "max_stars_repo_head_hexsha": "2a2be1124551d4fdd71b812b7e71dd7b33414a94", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2019-08-20T17:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T01:52:24.000Z", "max_issues_repo_path": "browser/src/vts-libbrowser/map/coordsManip.cpp", "max_issues_repo_name": "ExploreWilder/vts-browser-cpp", "max_issues_repo_head_hexsha": "2a2be1124551d4fdd71b812b7e71dd7b33414a94", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-09-14T20:27:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:43:55.000Z", "max_forks_repo_path": "browser/src/vts-libbrowser/map/coordsManip.cpp", "max_forks_repo_name": "ExploreWilder/vts-browser-cpp", "max_forks_repo_head_hexsha": "2a2be1124551d4fdd71b812b7e71dd7b33414a94", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T07:10:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T05:06:00.000Z", "avg_line_length": 29.7, "max_line_length": 123, "alphanum_fraction": 0.655964406, "num_tokens": 2228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "//  bpp.cpp\n//  PhyloAcc\n//\n//  Created by hzr on 3/8/16.\n//  Copyright \u00a9 2016 hzr. All rights reserved.\n//\n\n#include \"bpp.hpp\"\n#include <armadillo>\n#include <sys/types.h>\n#include <dirent.h>\n#include<queue>\n\n#include <cmath>\n#include <cassert>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_cdf.h>\n\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <ctype.h>\n\n\n#include \"newick.h\"\n#include \"utils.h\"\n#include \"bpp_c.hpp\"\n\n\nusing namespace std;\nusing namespace arma;\n\n\n// load the phylogenetic tree\nvoid BPP::InitPhyloTree(PhyloTree & tree) //, double indel_pi), double indel, double indel2\n{\n\n    submat = tree.subs_rate;\n    children    = new int[N][2];\n    parent      = new int[N];\n    distances   = new double[N];\n    thetas   = new double[N];\n    heights = vector<double>(N);\n    move_br = vector<int>(N);\n\n\n    for(int s=0; s<N; s++)\n    {\n        distances[s] = tree.distances[s];\n        thetas[s] = tree.thetas[s];\n        heights[s] = 0; // root\n    }\n    \n\n    for(int i=0; i<N; i++)\n    {\n        children[i][0] = -1;\n        children[i][1] = -1;\n        parent[i] = N;\n    }\n\n    for(int i=0; i<N; i++)\n    {\n        int p = -1;\n        for(int j=0; j<N; j++)\n        {\n            if (tree.dag[i][j])\n            {\n                p++;\n                children[i][p] = j;\n                parent[j] = i;\n            }\n        }\n    }\n    \n    for(int i = N-2; i >= 0; i--)\n    {\n        heights[i] = heights[parent[i]] - distances[i]; //heights<=0. root=0. Distance: br length. +ve.\n    }\n}\n\n// try to match the phylogenetic profile and tree\nvoid BPP::MatchProfAndTree(PhyloProf & _prof, PhyloTree & _tree)\n{\n    // try to match the species\n    bool success_match = true;\n    int S = _tree.S;\n    int S2 = _prof.S;\n    vector<int> reorder(S);  //each species in the tree where is in prof\n    for(int s1=0; s1<S; s1++)\n    {\n        bool has_same_species = false;\n        string sname1 = _tree.species_names[s1];\n        for(int s2=0; s2<S2; s2++)\n        {\n            string sname2 = _prof.species_names[s2];\n            if (sname1 == sname2)\n            {\n                has_same_species = true;\n                reorder[s1] = s2;\n                break;\n            }\n        }\n        if (!has_same_species)\n        {\n            cout << \"No matrix species \" << _prof.species_names[s1] << \" found in tree.\" << endl;\n            success_match = false;\n            break;\n        }\n    }\n\n    if (!success_match) // if cannot match literally\n    {\n        cout << endl << \"The species in phylogenetic profile and tree cannot be matched literally:\" << endl;\n        cout << \"The program will use the default mapping in data:\" << endl;\n        for(int s=0; s<S; s++)\n            cout << \"(\" << _prof.species_names[s] << \"\\t=  \" << _tree.species_names[s] << \")\" << endl;\n        cout << endl;\n    }\n    else                // if successully matched\n    {\n        cout << \"The species in profile and tree match perfectly. Reorder the species in profile matrix by the tree.\" << endl << endl;\n        vector<string> old_X = _prof.X;\n        for(int s=0; s<S; s++)\n        {\n            int reorder_s = reorder[s];\n            _prof.X[s] = old_X[reorder_s];\n        }\n        _prof.species_names = _tree.species_names;\n    }\n\n}\n\nvoid BPP::InitMCMC(int _num_burn, int _num_mcmc, int _num_thin)\n{\n    // init parameters\n    num_burn = _num_burn;\n\n    num_mcmc = _num_mcmc;\n    num_thin = _num_thin;\n\n    last_time = time(NULL);\n\n    // init MCMC sampling storage\n    Max_Z = vector<vector < vector <int > >> (3,vector < vector <int >>  (C,vector <int > (N,0)));\n    cur_Z = vector<vector < vector <int > >> (3,vector < vector <int >>  (C,vector <int > (N,0)));\n    \n    genetrees = vector<vector<string>>(3, vector<string>(C)); // for max gene tree\n\n    log_liks_null = vector <double>(C,0);\n    log_liks_null_L = vector <double>(C,0);\n    log_liks_Z = vector<vector <double>>(3,vector <double>(C,0));\n    log_liks_sgl = vector <double>(C,0);\n    log_liks_resZ = vector <double>(C,0);\n    log_liks_sgl_L = vector <double>(C,0);\n    log_liks_resZ_L = vector <double>(C,0);\n    log_liks_WL = vector< vector <double> > (3, vector <double>(C, 0));\n    log_mle = vector<vector<double> > (3, vector<double> (C,0));\n\n    log_liks_curZ = vector <double>(C,0);\n    log_liks_propZ = vector <double>(C,0);\n    MH_ratio_gain = vector <double>(C,0);\n    MH_ratio_loss = vector <double>(C,0);\n\n\n    cur_crate = vector <double>(C,ratio0);\n    cur_nrate = vector <double>(C,ratio1);\n\n    cur_lrate = vector <double>(C,ind_lrate);\n    cur_lrate2 = vector <double>(C,ind_lrate2);\n    cur_grate = vector <double>(C, ind_grate);\n\n   //Han*: used to save mode of MCMC output, so one element one vector.\n    cur_pi = vector<vector<vector<double>>>(3,vector<vector<double>> (C, vector<double>(4,0.25)));      \n\n}\n\nvoid BPP::sample_proposal(int iter, double & lrate_prop, double & grate_prop, ofstream & output)\n{\n    lrate_prop =gsl_ran_beta(RNG, ind_lrate * vlr, (1 - ind_lrate) *vlr); // let vlr == vgr!!\n    grate_prop =gsl_ran_beta(RNG, ind_grate * vgr, (1 - ind_grate - ind_lrate) *vgr); //gsl_ran_gamma(RNG, vgr, ind_grate/vgr);\n    grate_prop = grate_prop * (1 - lrate_prop);\n\n    output << iter << \"\\t\"<< nprior_a<< \"\\t\"<< nprior_b <<\"\\t\"<< cprior_a << \"\\t\"<< cprior_b << \"\\t\"<< indel << \"\\t\"<< indel2 << \"\\t\"<<ind_grate<< \"\\t\"<< ind_lrate <<endl;\n}\n\nvec BPP::getlogTM(double dist, double rate, mat & lam )\n{\n    mat tmp_diag  = exp(eigenval* dist * rate);\n    mat x = eigenvec;\n    x.each_col()%=tmp_diag;\n    \n    mat log_cache_TM = log(eigeninv * x) ; //transpose Q\n    return(log_multi(log_cache_TM, lam.col(lam.n_cols -1)));\n}\n\nmat BPP::getlogTM(double dist, double rate) //Han: get log transition matrix.\n{\n    if(dist < 1e-8)\n    {\n        mat x(num_base, num_base);\n        x.fill(-INFINITY);\n        x.diag().zeros();\n        return(x);\n    }\n    mat tmp_diag  = exp(eigenval* dist * rate);\n    mat x = eigenvec;\n    x.each_col()%=tmp_diag;\n    \n    return(log(eigeninv * x)) ; //transpose Q\n    \n}\n\n//Han*: new function. to account for updated Q\n//For each element, since eigen value/vec changed\nmat BPP::getlogTMc(double dist, double rate, mat& c_eigenvec, mat& c_eigenval, mat& c_eigeninv)\n{\n    if(dist < 1e-8)\n    {\n        mat x(num_base, num_base);\n        x.fill(-INFINITY);\n        x.diag().zeros();\n        return(x);\n    }\n    mat tmp_diag  = exp(c_eigenval* dist * rate);\n    mat x = c_eigenvec;\n    x.each_col()%=tmp_diag;\n    \n    return(log(c_eigeninv * x)) ; //transpose Q //element-wise log\n}\n\nmat BPP::getlogTM_len(double dist, mat& c_eigenvec, mat& c_eigenval, mat& c_eigeninv){\n    if(dist < 1e-8){\n        mat x(num_base, num_base);\n        x.fill(-INFINITY);\n        x.diag().zeros();\n        return(x);\n    }\n    mat tmp_diag  = exp(c_eigenval* dist);\n    mat x = c_eigenvec;\n    x.each_col()%=tmp_diag;\n    \n    return(log(c_eigeninv * x)) ; //transpose Q\n}\n\ndouble BPP::log_lik(vector< vector<vec> > & lambda, double _indel, double _indel2, int start1, int end1, vector<unsigned int> & v, double p)\n{\n    // compute loglik\n    double result =0;\n    mat x(2,2);\n\n    int rr = *subtree.rbegin();\n    // 1. sending the lambda msg from leaves bottom up through the network\n    for(vector<int>::iterator it = subtree.begin(); it!=subtree.end(); it++) //int s=S; s<N; s++)\n    {\n        int s = *it;\n        if(s<S) continue;\n        int* p = children[s];\n        for(int it = start1; it < end1; it++)  lambda[v[it]][s].fill(0);\n\n\n        for(int cc=0;cc<2;cc++)\n        {\n            int chi = p[cc];\n            assert(chi != -1);\n            if(distances[chi]>0 )\n            {\n                double tt = (1 - exp(-(_indel + _indel2) * distances[chi]))/(_indel + _indel2);\n                x.at(1,0) = _indel * tt;\n                x.at(0,0) = 1 - x.at(1,0);\n\n                x.at(0,1) = _indel2 * tt;\n                x.at(1,1) = 1 - x.at(0,1);\n\n                //cout << x;\n                x = log(x);\n\n\n            }\n            else{\n                x.fill(-INFINITY); //83, root\n                x.diag().fill(0);\n            }\n\n            #pragma omp parallel for schedule (guided)\n            for(int it = start1; it < end1; it++)  lambda[v[it]][s] +=  BPP::log_multi(x,lambda[v[it]][chi]);\n        }\n\n    }\n\n    // 2. processing the distribution of root species\n    for(int it = start1; it < end1; it++)\n    {\n\n        lambda[v[it]][rr][0] += log(1-p); //N-1\n        lambda[v[it]][rr][1] += log(p) ;\n        result += BPP::log_exp_sum(lambda[v[it]][rr]);\n    }\n\n    return(result);\n}\n\nvoid BPP::sample_hyperparam(int iter, vector<int> & ids, ofstream & output) // recompute log_TM, double indel_prop, double indel2_prop,\n{\n    //indepent MH to sample hyperparam of rates\n    double p=1,r = 1; //hyperparam for shape\n    double q=0.1,s = 0.1; // hyperparam for scale\n\n    double vna = 100, vnb = 100, vca = 100, vcb = 100;\n    double nprior_a_prop =gsl_ran_gamma(RNG, vna, nprior_a/vna);\n    double cprior_a_prop =gsl_ran_gamma(RNG, vca, cprior_a/vca);\n\n    double nprior_b_prop =gsl_ran_gamma(RNG, vnb, nprior_b/vnb);\n    double cprior_b_prop =gsl_ran_gamma(RNG, vcb, cprior_b/vcb);\n\n    //MH proposal\n    double sum_r = 0;\n    double log_prod_r = 0;\n    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702\n    {\n        int c = ids[i];\n        sum_r += cur_nrate[c];\n        //var_r += pow(*it, 2);\n        log_prod_r += log(cur_nrate[c]);\n    }\n\n\n    double M_ratio = (nprior_a_prop - 1) * (log(p) + log_prod_r) - (q + sum_r)/nprior_b_prop - (ids.size() + r)*lgamma(nprior_a_prop) - log(nprior_b_prop) * nprior_a_prop * (s + ids.size());\n    M_ratio -= (nprior_a - 1) * (log(p) + log_prod_r) - (q + sum_r)/nprior_b - (ids.size() + r)*lgamma(nprior_a) - log(nprior_b) * nprior_a * (s + ids.size());\n\n    double H_ratio = log(gsl_ran_gamma_pdf(nprior_a,vna,nprior_a_prop/vna)) - log(gsl_ran_gamma_pdf(nprior_a_prop,vna,nprior_a/vna)) + log(gsl_ran_gamma_pdf(nprior_b,vnb,nprior_b_prop/vnb)) - log(gsl_ran_gamma_pdf(nprior_b_prop,vnb,nprior_b/vnb));\n\n    cout << \"nrate_MH_ratio: \" << M_ratio <<\", \" << H_ratio << \", \" << nprior_a << \", \" << nprior_a_prop << \", \" << nprior_b << \", \" << nprior_b_prop << endl;\n\n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        nprior_a = nprior_a_prop;\n        nprior_b = nprior_b_prop;\n    }\n\n    sum_r = 0;\n    log_prod_r = 0;\n    //for(vector<double>::iterator it = cur_crate.begin(); it< cur_crate.end(); it++)\n    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702\n    {\n        int c = ids[i];\n        sum_r += cur_crate[c];\n        //var_r += pow(*it, 2);\n        log_prod_r += log(cur_crate[c]);\n    }\n\n    M_ratio = (cprior_a_prop - 1) * (log(p) + log_prod_r) - (q + sum_r)/cprior_b_prop - (ids.size() + r)*lgamma(cprior_a_prop) - log(cprior_b_prop) * cprior_a_prop * (s + ids.size()) - ((cprior_a - 1) * (log(p) + log_prod_r) - (q + sum_r)/cprior_b - (ids.size() + r)*lgamma(cprior_a) - log(cprior_b) * cprior_a * (s + ids.size()));\n\n    H_ratio = log(gsl_ran_gamma_pdf(cprior_a,vca,cprior_a_prop/vca)) - log(gsl_ran_gamma_pdf(cprior_a_prop,vca,cprior_a/vca)) + log(gsl_ran_gamma_pdf(cprior_b,vcb,cprior_b_prop/vcb)) - log(gsl_ran_gamma_pdf(cprior_b_prop,vcb,cprior_b/vcb));\n\n    cout << \"crate_MH_ratio: \" << M_ratio + H_ratio << \", \" << cprior_a << \", \" << cprior_a_prop <<\", \" << cprior_b << \", \" << cprior_b_prop << endl;\n\n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        cprior_a = cprior_a_prop;\n        cprior_b = cprior_b_prop;\n    }\n\n\n  // sample hyperparameters of lrate and grate, exponential prior for prior_l_a and prior_l_b, prior_g_a and prior_g_b\n    double u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);\n    double prior_l_a_prop = prior_l_a *  u;\n\n    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);\n    double prior_l_b_prop = prior_l_b *  u;\n    double log_p = 0, log_pc = 0;\n    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702\n    {\n        int c = ids[i];\n        log_p += log(cur_lrate[c]);\n        log_pc += log(1 - cur_lrate[c]);\n    }\n\n\n    M_ratio = (prior_l_a_prop - prior_l_a) * (log_p - 1) + (prior_l_b_prop - prior_l_b) * (log_pc - 1);\n    M_ratio += ids.size() * (gsl_sf_lnbeta(prior_l_a, prior_l_b) - gsl_sf_lnbeta(prior_l_a_prop, prior_l_b_prop));\n\n    H_ratio = log(prior_l_a) - log(prior_l_a_prop) + log(prior_l_b) - log(prior_l_b_prop);\n\n    cout << \"lrate_MH_ratio: \" << M_ratio + H_ratio << \", \" << prior_l_a << \", \" << prior_l_a_prop <<\", \" << prior_l_b << \", \" << prior_l_b_prop  << endl;\n\n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        prior_l_a = prior_l_a_prop;\n        prior_l_b = prior_l_b_prop;\n    }\n\n    // sample grate\n    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);\n    double prior_g_a_prop = prior_g_a *  u;\n\n    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);\n    double prior_g_b_prop = prior_g_b *  u;\n    log_p = 0; log_pc = 0;\n    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702\n    {\n        int c = ids[i];\n        log_p += log(cur_grate[c]);\n        log_pc += log(1 - cur_grate[c]);\n    }\n\n\n    M_ratio = (prior_g_a_prop - prior_g_a) * (log_p - 1) + (prior_g_b_prop - prior_g_b) * (log_pc - 1);\n    M_ratio += ids.size() * (gsl_sf_lnbeta(prior_g_a, prior_g_b) - gsl_sf_lnbeta(prior_g_a_prop, prior_g_b_prop));\n\n    H_ratio = log(prior_g_a) - log(prior_g_a_prop) + log(prior_g_b) - log(prior_g_b_prop);\n\n    cout << \"grate_MH_ratio: \" << M_ratio + H_ratio << \", \" << prior_g_a << \", \" << prior_g_a_prop <<\", \" << prior_g_b << \", \" << prior_g_b_prop  << endl;\n\n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        prior_g_a = prior_g_a_prop;\n        prior_g_b = prior_g_b_prop;\n    }\n\n    output << iter << \"\\t\"<< nprior_a<< \"\\t\"<< nprior_b <<\"\\t\"<< cprior_a << \"\\t\"<< cprior_b << \"\\t\"<< prior_l_a << \"\\t\"<< prior_l_b << \"\\t\"<< prior_g_a << \"\\t\"<< prior_g_b <<endl;\n}\n\n\nvoid BPP::getUppertree(int root, vector<int>& child, set<int> & visited_init)  // go to the root, include root!\n{\n    for(vector<int>::iterator it = child.begin(); it!=child.end(); it++)\n    {\n       int p = *it;\n       while(p!=root)\n       {\n           visited_init.insert(p);\n           p = parent[p];\n       }\n    }\n    visited_init.insert(root);\n}\n\nvoid BPP::getSubtree(int root, vector<int> & visited_init)  // traverse from root to children, include root\n{\n\n\n    int j = root;\n\n    //cout << nodes_names[j]<<\"\\t\";\n\n    if(children[j][0]!=-1)\n    {\n        for(int chi=0;chi<2;chi++)\n        {\n            getSubtree(children[j][chi], visited_init);\n        }\n    }\n    visited_init.push_back(j);\n}\n\nvoid BPP::getSubtree(int root, set<int>& child, vector<int> & visited_init)  // traverse from root, stop at children, 74 & 64; do include 1-S!\n{\n    int j = root;\n\n    //cout << nodes_names[j]<<\"\\t\";\n    if(child.find(j) != child.end())\n    {\n        visited_init.push_back(j);\n        return;\n    }\n\n    if(children[j][0]!=-1)\n    {\n        for(int chi=0;chi<2;chi++)\n        {\n            getSubtree(children[j][chi], child, visited_init);\n        }\n    }\n     visited_init.push_back(j);\n}\n\nvoid BPP::Output_init(PhyloProf & prof, string output_path, vector<int> & ids){\n\n        string outpath_elem = output_path+ \"_elem_lik.txt\";\n        ofstream out_lik(outpath_elem.c_str());\n        out_lik.precision(8);\n\n        //out_lik<<\"No.\\tID\\tloglik_Null_W\\tloglik_Acc_W\\tloglik_Full_W\\tlogBF1\\tlogBF2\\tlogPost_Max_M0\\tlogPost_Max_M1\\tlogPost_Max_M2\\n\";\n        out_lik<<\"No.\\tID\\tloglik_Null_W\\tloglik_Acc_W\\tloglik_Full_W\\tlogBF1\\tlogBF2\"<<endl;\n        for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)\n        {\n            int cc = *it;\n            out_lik <<cc << \"\\t\" << prof.element_names[cc] << \"\\t\" << log_liks_WL[0][cc] <<\"\\t\"<< log_liks_WL[2][cc] <<\"\\t\"<< log_liks_WL[1][cc] <<\"\\t\";\n            out_lik<<log_liks_WL[2][cc]-log_liks_WL[0][cc]<<\"\\t\"<<log_liks_WL[2][cc]-log_liks_WL[1][cc]<<endl;\n            //out_lik <<log_liks_Z[0][cc] << \"\\t\" <<log_liks_Z[2][cc]<<\"\\t\" <<log_liks_Z[1][cc]<<\"\\t\";\n            //out_lik<<log_mle[0][cc]<<\"\\t\"<<log_mle[2][cc]<<\"\\t\"<<log_mle[1][cc]<<\"\\t\"<<log_mle[2][cc]-log_mle[0][cc]<<\"\\t\"<<log_mle[2][cc]-log_mle[1][cc];\n            //out_lik << endl;\n        }\n\n        out_lik.close();\n\n    ofstream out_z;\n    for(int r =0;r<3;r++)\n    {\n      if(r == 2)\n      {\n          outpath_elem = output_path+\"_M\" +to_string(1) + \"_elem_Z.txt\";\n      }else if(r == 1)\n      {\n          outpath_elem = output_path+\"_M\" +to_string(2) + \"_elem_Z.txt\";\n      }else{\n          outpath_elem = output_path+\"_M\" +to_string(0) + \"_elem_Z.txt\";\n      }\n\n            out_z.open(outpath_elem.c_str());\n            out_z<<\"No.\";\n                for(int s =0 ;s<N;s++){  // header: species name\n                    out_z<< \"\\t\" << nodes_names[s];\n                }\n            out_z << \"\\tgenetree\" <<endl;\n\n            for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)\n            {\n                int c = *it;\n                out_z<<c;\n                for(int s=0; s<N;s++)\n                    out_z<<\"\\t\" << Max_Z[r][c][s];\n                out_z << \"\\t\" << genetrees[r][c];\n                out_z <<endl;\n            }\n        out_z.close();\n    }\n\n    ofstream out_pi;    \n    for(int r=0; r<3;r++){\n        if(r==0){\n            outpath_elem=output_path+\"_M\"+to_string(0)+\"_Beta_Post_pi_mode.txt\";\n        }else if(r==2){\n            outpath_elem=output_path+\"_M\"+to_string(1)+\"_Beta_Post_pi_mode.txt\";\n        }else{\n            outpath_elem=output_path+\"_M\"+to_string(2)+\"_Beta_Post_pi_mode.txt\";\n        }\n        out_pi.open(outpath_elem.c_str());\n\n        for(vector<int>:: iterator it = ids.begin(); it !=ids.end(); it++)\n        {\n            int c=*it;\n            out_pi << c;\n            for(int b=0; b<4; b++) {//4 or num_base\n                out_pi<<\"\\t\"<<cur_pi[r][c][b];\n            }\n            out_pi <<endl;\n        }\n        out_pi.close();\n    }\n\n}\n\n\nvoid BPP::Output_init0(PhyloProf & prof, ofstream& out_lik, vector<int> & ids){\n\n    //for(int cc=0; cc<C;cc++)\n    for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)\n    {\n        int cc = *it;\n        out_lik <<cc << \"\\t\" << prof.element_names[cc] << \"\\t\"  <<log_liks_sgl[cc]<< \"\\t\"<<log_liks_Z[1][cc];\n        out_lik << endl;\n    }\n}\n\n/*** output simulated sequence ***/\nvoid BPP::Output_simu(PhyloProf & prof, string outpath, int c){\n    ofstream output;\n    string outpath1 = outpath + \".fasta\";\n    string outpath2 = outpath + \".bed\";\n    string outpath3 = outpath +\"_Z.txt\";\n    string outpath4 = outpath +\"_pi.txt\";\n    output.open(outpath1.c_str());\n    for(int s = 0; s< S; s++)\n    {\n        output << \">\" << prof.species_names[s] << endl;\n        output << prof.X[s].substr(0, element_start[c] + element_size[c])<< endl; //strutils::ToUpperCase(\n    }\n    output.close();\n    \n    output.open(outpath2.c_str());\n    for(int i = 0; i < c; i++)\n    {\n        output << i << \"\\t\" << element_start[i] << \"\\t\" << element_start[i] + element_size[i]<< \"\\t\";\n        //Han*: add in output for pi\n        output << i << \"\\t\" << 1 << \"\\t\" << cur_crate[i] << \"\\t\" << cur_nrate[i] << \"\\t\" << genetrees[0][i] << endl;\n    }\n    output.close();\n\n    //Han*: output for Z\n    output.open(outpath3.c_str());\n    for(int s=0; s<N; s++){\n        output<<\"\\t\"<<nodes_names[s];\n    }\n    output<<endl;\n    for(int s=0; s<N; s++){\n        output<<\"\\t\"<<cur_Z[0][0][s];\n    }\n    output<<endl;\n    output.close();\n\n    //Han*: output pi\n    output.open(outpath4.c_str());\n    for(int i=0; i<c; i++){\n        output<<i<<\"\\t\"<<cur_pi[0][i][0]<<endl; //only need to output pi_A (double-stranded)\n    }\n    output.close();\n}\n\n    void BPP::getTreeString(int rootN, std::stringstream & buffer)\n    {\n        if (children[rootN][0] == -1)\n        {\n            buffer << species_names[rootN] << \":\"<< distances[rootN];\n        }\n        else\n        {\n            buffer << \"(\";\n            for(int i =0;i <2; i++)\n            {\n                int child = children[rootN][i];\n                \n                getTreeString(child, buffer);\n                if(i==0) buffer << \",\";\n            }\n            \n            if(parent[rootN] < N)\n            {\n                buffer << \"):\" << distances[rootN];\n            }else{\n                buffer << \");\" ;\n            }\n        }\n    }\n", "meta": {"hexsha": "5dda6779c8d1a27f55605f02199c9d6eec9eebc7", "size": 20497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PhyloAcc-GT/bpp.cpp", "max_stars_repo_name": "gwct/PhyloAcc", "max_stars_repo_head_hexsha": "089162e2bce5a17b95d71add074bf51bccc8a266", "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/PhyloAcc-GT/bpp.cpp", "max_issues_repo_name": "gwct/PhyloAcc", "max_issues_repo_head_hexsha": "089162e2bce5a17b95d71add074bf51bccc8a266", "max_issues_repo_licenses": ["MIT"], "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/PhyloAcc-GT/bpp.cpp", "max_forks_repo_name": "gwct/PhyloAcc", "max_forks_repo_head_hexsha": "089162e2bce5a17b95d71add074bf51bccc8a266", "max_forks_repo_licenses": ["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.976599064, "max_line_length": 331, "alphanum_fraction": 0.550812314, "num_tokens": 6363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "/*\n * RecoTauDiscriminantCutMultiplexer\n *\n * Author: Evan K. Friis, UW\n *\n * Takes two PFTauDiscriminators.\n *\n * The \"key\" discriminantor is rounded to the nearest integer.\n *\n * A set of cuts for different keys on the \"toMultiplex\" discriminantor is\n * provided in the config file.\n *\n * Both the key and toMultiplex discriminators should map to the same PFTau\n * collection.\n *\n */\n#include <boost/foreach.hpp>\n#include \"RecoTauTag/RecoTau/interface/TauDiscriminationProducerBase.h\"\n#include \"FWCore/Utilities/interface/InputTag.h\"\n#include \"CommonTools/Utils/interface/StringObjectFunction.h\"\n#include \"DataFormats/TauReco/interface/PFTau.h\"\n#include \"FWCore/ParameterSet/interface/FileInPath.h\"\n\n#include <FWCore/ParameterSet/interface/ConfigurationDescriptions.h>\n#include <FWCore/ParameterSet/interface/ParameterSetDescription.h>\n\n#include \"CondFormats/PhysicsToolsObjects/interface/PhysicsTGraphPayload.h\"\n#include \"CondFormats/DataRecord/interface/PhysicsTGraphPayloadRcd.h\"\n#include \"CondFormats/PhysicsToolsObjects/interface/PhysicsTFormulaPayload.h\"\n#include \"CondFormats/DataRecord/interface/PhysicsTFormulaPayloadRcd.h\"\n\n#include \"TMath.h\"\n#include \"TGraph.h\"\n#include \"TFormula.h\"\n#include \"TFile.h\"\n\nclass RecoTauDiscriminantCutMultiplexer : public PFTauDiscriminationProducerBase \n{\n public:\n  explicit RecoTauDiscriminantCutMultiplexer(const edm::ParameterSet& pset);\n\n  ~RecoTauDiscriminantCutMultiplexer() override;\n  double discriminate(const reco::PFTauRef&) const override;\n  void beginEvent(const edm::Event& event, const edm::EventSetup& eventSetup) override;\n\n  static void fillDescriptions(edm::ConfigurationDescriptions & descriptions);\n\n private:\n  std::string moduleLabel_;\n\n  bool loadMVAfromDB_;\n  edm::FileInPath inputFileName_;\n\n  struct DiscriminantCutEntry\n  {\n    DiscriminantCutEntry()\n      : cutVariable_(),\n\tcutFunction_(),\n\tmode_(kUndefined)\n    {}\n    ~DiscriminantCutEntry()\n    {\n    }\n    double cutValue_;\n    std::string cutName_;\n    std::unique_ptr<StringObjectFunction<reco::PFTau>> cutVariable_;\n    std::unique_ptr<const TGraph> cutFunction_;\n    enum { kUndefined, kFixedCut, kVariableCut };\n    int mode_;\n  };\n  typedef std::map<int, std::unique_ptr<DiscriminantCutEntry>> DiscriminantCutMap;\n  DiscriminantCutMap cuts_;\n\n  std::string mvaOutputNormalizationName_;\n  std::unique_ptr<const TFormula> mvaOutput_normalization_;\n\n  bool isInitialized_;\n\n  edm::InputTag toMultiplex_;\n  edm::InputTag key_;\n  edm::Handle<reco::PFTauDiscriminator> toMultiplexHandle_;\n  edm::Handle<reco::PFTauDiscriminator> keyHandle_;\n  edm::EDGetTokenT<reco::PFTauDiscriminator> toMultiplex_token;\n  edm::EDGetTokenT<reco::PFTauDiscriminator> key_token;\n\n  int verbosity_;\n};\n\nnamespace\n{\n  std::unique_ptr<TFile> openInputFile(const edm::FileInPath& inputFileName) {\n    if ( inputFileName.location() == edm::FileInPath::Unknown){  throw cms::Exception(\"RecoTauDiscriminantCutMultiplexer::loadObjectFromFile\") \n      << \" Failed to find File = \" << inputFileName << \" !!\\n\";\n    }\n    return std::unique_ptr<TFile>{ new TFile(inputFileName.fullPath().data()) };\n  }\n\n  template <typename T>\n  std::unique_ptr<const T> loadObjectFromFile(TFile& inputFile, const std::string& objectName)\n  {\n    const T* object = dynamic_cast<T*>(inputFile.Get(objectName.data()));\n    if ( !object )\n      throw cms::Exception(\"RecoTauDiscriminantCutMultiplexer::loadObjectFromFile\") \n        << \" Failed to load Object = \" << objectName.data() << \" from file = \" << inputFile.GetName() << \" !!\\n\";\n    //Need to use TObject::Clone since the type T might be a base class\n    return std::unique_ptr<const T>{ static_cast<T*>(object->Clone()) };\n  }\n\n  std::unique_ptr<const TGraph> loadTGraphFromDB(const edm::EventSetup& es, const std::string& graphName, const int& verbosity_ = 0)\n  {\n    if(verbosity_){\n      std::cout << \"<loadTGraphFromDB>:\" << std::endl;\n      std::cout << \" graphName = \" << graphName << std::endl;\n    }\n    edm::ESHandle<PhysicsTGraphPayload> graphPayload;\n    es.get<PhysicsTGraphPayloadRcd>().get(graphName, graphPayload);\n    return std::unique_ptr<const TGraph>{ new TGraph(*graphPayload.product()) };\n  }  \n\n  std::unique_ptr<TFormula> loadTFormulaFromDB(const edm::EventSetup& es, const std::string& formulaName, const TString& newName, const int& verbosity_ = 0)\n  {\n    if(verbosity_){\n      std::cout << \"<loadTFormulaFromDB>:\" << std::endl;\n      std::cout << \" formulaName = \" << formulaName << std::endl;\n    }\n    edm::ESHandle<PhysicsTFormulaPayload> formulaPayload;\n    es.get<PhysicsTFormulaPayloadRcd>().get(formulaName, formulaPayload);\n\n    if ( formulaPayload->formulas().size() == 1 && formulaPayload->limits().size() == 1 ) {\n      return std::unique_ptr<TFormula> {new TFormula(newName, formulaPayload->formulas().at(0).data()) };\n    } else {\n      throw cms::Exception(\"RecoTauDiscriminantCutMultiplexer::loadTFormulaFromDB\") \n\t<< \"Failed to load TFormula = \" << formulaName << \" from Database !!\\n\";\n    }\n    return std::unique_ptr<TFormula>{};\n  }  \n}\n\nRecoTauDiscriminantCutMultiplexer::RecoTauDiscriminantCutMultiplexer(const edm::ParameterSet& cfg)\n  : PFTauDiscriminationProducerBase(cfg),\n    moduleLabel_(cfg.getParameter<std::string>(\"@module_label\")),\n    mvaOutput_normalization_(),\n    isInitialized_(false)\n{\n  \n  toMultiplex_ = cfg.getParameter<edm::InputTag>(\"toMultiplex\");\n  toMultiplex_token = consumes<reco::PFTauDiscriminator>(toMultiplex_);\n  key_ = cfg.getParameter<edm::InputTag>(\"key\");\n  key_token = consumes<reco::PFTauDiscriminator>(key_);\n\n  verbosity_ = cfg.getParameter<int>(\"verbosity\");\n\n  loadMVAfromDB_ = cfg.getParameter<bool>(\"loadMVAfromDB\");\n  if ( !loadMVAfromDB_ ) {\n      inputFileName_ = cfg.getParameter<edm::FileInPath>(\"inputFileName\");\n  }\n  if(verbosity_)  std::cout << moduleLabel_ << \" loadMVA = \" << loadMVAfromDB_ << std::endl;\n  mvaOutputNormalizationName_ = cfg.getParameter<std::string>(\"mvaOutput_normalization\"); \n\n  // Setup our cut map\n  typedef std::vector<edm::ParameterSet> VPSet;\n  VPSet mapping = cfg.getParameter<VPSet>(\"mapping\");\n  for ( VPSet::const_iterator mappingEntry = mapping.begin();\n\tmappingEntry != mapping.end(); ++mappingEntry ) {\n    unsigned category = mappingEntry->getParameter<uint32_t>(\"category\");\n    std::unique_ptr<DiscriminantCutEntry> cut{new DiscriminantCutEntry()};\n    if ( mappingEntry->existsAs<double>(\"cut\") ) {\n      cut->cutValue_ = mappingEntry->getParameter<double>(\"cut\");\n      cut->mode_ = DiscriminantCutEntry::kFixedCut;\n    } else if ( mappingEntry->existsAs<std::string>(\"cut\") ) {\n      cut->cutName_ = mappingEntry->getParameter<std::string>(\"cut\");\n      std::string cutVariable_string = mappingEntry->getParameter<std::string>(\"variable\");\n      cut->cutVariable_.reset( new StringObjectFunction<reco::PFTau>(cutVariable_string) );\n      cut->mode_ = DiscriminantCutEntry::kVariableCut;\n    } else {\n      throw cms::Exception(\"RecoTauDiscriminantCutMultiplexer\") \n        << \" Undefined Configuration Parameter 'cut' !!\\n\";\n    }\n    cuts_[category] = std::move(cut);\n  }\n\n  verbosity_ = cfg.getParameter<int>(\"verbosity\");\n  if(verbosity_) std::cout << \"constructed \" << moduleLabel_ << std::endl;\n}\n\nRecoTauDiscriminantCutMultiplexer::~RecoTauDiscriminantCutMultiplexer()\n{\n}\n\nvoid RecoTauDiscriminantCutMultiplexer::beginEvent(const edm::Event& evt, const edm::EventSetup& es) \n{\n  if(verbosity_) std::cout << \" begin! \" << moduleLabel_ << \" \" << isInitialized_ << std::endl;\n  if ( !isInitialized_ ) {\n    //Only open the file once and we can close it when this routine is done\n    // since all objects gotten from the file will have been copied\n    std::unique_ptr<TFile> inputFile;\n    if ( !mvaOutputNormalizationName_.empty() ) {\n      if ( !loadMVAfromDB_ ) {\n\tinputFile = openInputFile(inputFileName_);\n\tmvaOutput_normalization_ = loadObjectFromFile<TFormula>(*inputFile, mvaOutputNormalizationName_);\n      } else {\n\tauto temp = loadTFormulaFromDB(es, mvaOutputNormalizationName_, Form(\"%s_mvaOutput_normalization\", moduleLabel_.data()), verbosity_);\n\tmvaOutput_normalization_ = std::move(temp);\n      }\n    }\n    for ( DiscriminantCutMap::iterator cut = cuts_.begin();\n\t  cut != cuts_.end(); ++cut ) {\n      if ( cut->second->mode_ == DiscriminantCutEntry::kVariableCut ) {\n\tif ( !loadMVAfromDB_ ) {\n\t  if(not inputFile) {\n\t    inputFile = openInputFile(inputFileName_);\n\t  }\n\t  if(verbosity_) std::cout << \"Loading from file\" << inputFileName_ << std::endl;\n\t  cut->second->cutFunction_ = loadObjectFromFile<TGraph>(*inputFile, cut->second->cutName_);\n\t} else {\n\t  if(verbosity_) std::cout << \"Loading from DB\" << std::endl;\n\t  cut->second->cutFunction_ = loadTGraphFromDB(es, cut->second->cutName_, verbosity_);\n\t}\n      }\n    }\n    isInitialized_ = true;\n  }\n\n  evt.getByToken(toMultiplex_token, toMultiplexHandle_);\n  evt.getByToken(key_token, keyHandle_);\n}\n\ndouble\nRecoTauDiscriminantCutMultiplexer::discriminate(const reco::PFTauRef& tau) const\n{\n  if ( verbosity_ ) {\n    std::cout << \"<RecoTauDiscriminantCutMultiplexer::discriminate>:\" << std::endl;\n    std::cout << \" moduleLabel = \" << moduleLabel_ << std::endl;\n  }\n\n  double disc_result = (*toMultiplexHandle_)[tau];\n  if ( verbosity_ ) {\n    std::cout << \"disc_result = \" <<  disc_result << std::endl;\n  }\n  if ( mvaOutput_normalization_ ) {\n    disc_result = mvaOutput_normalization_->Eval(disc_result);\n    //if ( disc_result > 1. ) disc_result = 1.;\n    //if ( disc_result < 0. ) disc_result = 0.;\n    if ( verbosity_ ) {\n      std::cout << \"disc_result (normalized) = \" <<  disc_result << std::endl;\n    }\n  }\n  double key_result = (*keyHandle_)[tau];\n  DiscriminantCutMap::const_iterator cutIter = cuts_.find(TMath::Nint(key_result));\n\n  \n  // Return null if it doesn't exist\n  if ( cutIter == cuts_.end() ) {\n    return prediscriminantFailValue_;\n  }\n  // See if the discriminator passes our cuts\n  bool passesCuts = false;\n  if ( cutIter->second->mode_ == DiscriminantCutEntry::kFixedCut ) {\n    passesCuts = (disc_result > cutIter->second->cutValue_);\n    if ( verbosity_ ) {\n      std::cout << \"cutValue (fixed) = \" << cutIter->second->cutValue_ << \" --> passesCuts = \" << passesCuts << std::endl;\n    }\n  } else if ( cutIter->second->mode_ == DiscriminantCutEntry::kVariableCut ) {\n    double cutVariable = (*cutIter->second->cutVariable_)(*tau);\n    double xMin, xMax, dummy;\n    cutIter->second->cutFunction_->GetPoint(0, xMin, dummy);\n    cutIter->second->cutFunction_->GetPoint(cutIter->second->cutFunction_->GetN() - 1, xMax, dummy);\n    const double epsilon = 1.e-3;\n    if      ( cutVariable < (xMin + epsilon) ) cutVariable = xMin + epsilon;\n    else if ( cutVariable > (xMax - epsilon) ) cutVariable = xMax - epsilon;\n    double cutValue = cutIter->second->cutFunction_->Eval(cutVariable);\n    passesCuts = (disc_result > cutValue);\n    if ( verbosity_ ) {\n      std::cout << \"cutValue (@\" << cutVariable << \") = \" << cutValue << \" --> passesCuts = \" << passesCuts << std::endl;\n    }\n  } else assert(0);\n\n  return passesCuts;\n}\n\nvoid\nRecoTauDiscriminantCutMultiplexer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {\n  // recoTauDiscriminantCutMultiplexer\n  edm::ParameterSetDescription desc;\n  desc.add<edm::InputTag>(\"toMultiplex\", edm::InputTag(\"fixme\"));\n  desc.add<int>(\"verbosity\", 0);\n\n  {\n    edm::ParameterSet pset_mapping;\n    pset_mapping.addParameter<unsigned int>(\"category\",0);\n    pset_mapping.addParameter<double>(\"cut\",0.);\n    edm::ParameterSetDescription desc_mapping;\n    desc_mapping.add<unsigned int>(\"category\",0);\n    desc_mapping.addNode(edm::ParameterDescription<std::string>(\"cut\", true) xor\n                         edm::ParameterDescription<double>(\"cut\", true));\n    // it seems the parameter string \"variable\" exists only when \"cut\" is string\n    // see hpsPFTauDiscriminationByVLooseIsolationMVArun2v1DBdR03oldDMwLT in RecoTauTag/Configuration/python/HPSPFTaus_cff.py\n    desc_mapping.addOptional<std::string>(\"variable\")->setComment(\"the parameter is required when \\\"cut\\\" is string\");\n    //  desc_mapping.add<double>(\"cut\",0.);\n    std::vector<edm::ParameterSet> vpsd_mapping;\n    vpsd_mapping.push_back(pset_mapping);\n    desc.addVPSet(\"mapping\",desc_mapping,vpsd_mapping);\n  }\n \n  desc.add<edm::FileInPath>(\"inputFileName\", edm::FileInPath(\"RecoTauTag/RecoTau/data/emptyMVAinputFile\"));\n  desc.add<bool>(\"loadMVAfromDB\", true);\n  fillProducerDescriptions(desc); // inherited from the base\n  desc.add<std::string>(\"mvaOutput_normalization\", \"\");\n  desc.add<edm::InputTag>(\"key\", edm::InputTag(\"fixme\"));\n  descriptions.add(\"recoTauDiscriminantCutMultiplexerDefault\", desc);\n}\n\n\nDEFINE_FWK_MODULE(RecoTauDiscriminantCutMultiplexer);\n", "meta": {"hexsha": "73377b6339bd060c50eede64546e87ab368ffec6", "size": 12668, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RecoTauTag/RecoTau/plugins/RecoTauDiscriminantCutMultiplexer.cc", "max_stars_repo_name": "Nik-Menendez/L1Trigger", "max_stars_repo_head_hexsha": "5336631cc0a517495869279ed7d3a4cac8d4e5e5", "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": "RecoTauTag/RecoTau/plugins/RecoTauDiscriminantCutMultiplexer.cc", "max_issues_repo_name": "Nik-Menendez/L1Trigger", "max_issues_repo_head_hexsha": "5336631cc0a517495869279ed7d3a4cac8d4e5e5", "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": "RecoTauTag/RecoTau/plugins/RecoTauDiscriminantCutMultiplexer.cc", "max_forks_repo_name": "Nik-Menendez/L1Trigger", "max_forks_repo_head_hexsha": "5336631cc0a517495869279ed7d3a4cac8d4e5e5", "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": 40.2158730159, "max_line_length": 156, "alphanum_fraction": 0.7113988001, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "/**\n * @file budgeted_maximum_coverage.hpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-03-18\n */\n#ifndef PAAL_BUDGETED_MAXIMUM_COVERAGE_HPP\n#define PAAL_BUDGETED_MAXIMUM_COVERAGE_HPP\n\n#include \"paal/data_structures/fraction.hpp\"\n#include \"paal/utils/accumulate_functors.hpp\"\n#include \"paal/utils/algorithms/subset_backtrack.hpp\"\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n\n#include <boost/heap/d_ary_heap.hpp>\n#include <boost/range/adaptor/indexed.hpp>\n#include <boost/range/algorithm/copy.hpp>\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/range/algorithm/fill.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n#include <boost/range/algorithm/sort.hpp>\n#include <boost/range/combine.hpp>\n\n#include <algorithm>\n#include <vector>\n\nnamespace paal {\nnamespace greedy {\nnamespace detail {\n\ntemplate <typename ElementWeight, typename SetCost> struct set_data_type {\n    set_data_type()\n        : m_weight_of_uncovered_elements{}, m_cost{}, m_is_processed{ true } {}\n    ElementWeight m_weight_of_uncovered_elements; // sum of weight of uncovered\n                                                  // elements in backtrack and\n                                                  // greedy\n    SetCost m_cost;\n    bool m_is_processed;\n    // set is processed if is selected or is not selected and at least one of\n    // the following situations occurs\n    // -we have not enough budget to select set\n    // -sum of weight of uncovered elements belong to set equal 0\n};\n\ntemplate <typename SetReference, typename GetElementsOfSet,\n          typename GetWeightOfElement>\nusing element_weight_t = pure_result_of_t<GetWeightOfElement(\n    range_to_elem_t<pure_result_of_t<GetElementsOfSet(SetReference)>>)>;\n\nconst int UNCOVERED = -1;\ntemplate <class Budget, class SetCost, class SetIdToData, class ElementWeight,\n          class SetIdToElements, class ElementIndex, class GetWeightOfElement,\n          typename DecreseWeight>\nclass selector {\n    const Budget m_budget;\n    SetCost &m_cost_of_solution;\n    std::vector<int> m_selected_sets;\n    SetIdToData &m_sets_data;\n    const ElementWeight &m_weight_of_bests_solution;\n    ElementWeight &m_weight_of_covered_elements;\n    SetIdToElements m_set_id_to_elements;\n    std::vector<int> &m_covered_by;\n    std::vector<std::vector<int>> &m_sets_covering_element;\n    ElementIndex &m_get_el_index;\n    GetWeightOfElement &m_element_to_weight;\n    DecreseWeight m_decrese_weight;\n\n    using SetData = range_to_elem_t<SetIdToData>;\n\n  public:\n    selector(const Budget budget, SetCost &cost_of_solution,\n             SetIdToData &sets_data,\n             const ElementWeight &weight_of_bests_solution,\n             ElementWeight &weight_of_covered_elements,\n             SetIdToElements set_id_to_elements, std::vector<int> &covered_by,\n             std::vector<std::vector<int>> &sets_covering_element,\n             ElementIndex &get_el_index, GetWeightOfElement &element_to_weight,\n             DecreseWeight decrese_weight)\n        : m_budget(budget), m_cost_of_solution(cost_of_solution),\n          m_sets_data(sets_data),\n          m_weight_of_bests_solution(weight_of_bests_solution),\n          m_weight_of_covered_elements(weight_of_covered_elements),\n          m_set_id_to_elements(set_id_to_elements), m_covered_by(covered_by),\n          m_sets_covering_element(sets_covering_element),\n          m_get_el_index(get_el_index), m_element_to_weight(element_to_weight),\n          m_decrese_weight(decrese_weight) {}\n\n    // we return true if (we select set) or (set is already in solution)\n    bool select_set_backtrack(int selected_set_id, bool in_reset = false) {\n        if(!can_select(m_sets_data[selected_set_id])) return false;\n\n        select_set(selected_set_id, true);\n        if(!in_reset) m_selected_sets.push_back(selected_set_id);\n        return true;\n    }\n\n    // we return true if we violated budget\n    bool select_set_greedy(int selected_set_id) {\n        auto &select_set_data = m_sets_data[selected_set_id];\n\n        if(!can_select(select_set_data)) return false;\n        m_selected_sets.push_back(selected_set_id);\n\n        if(greedy_prune(select_set_data))  return true;\n        select_set(selected_set_id, false);\n        return false;\n    }\n\n\n    void deselect_set(int selected_set_id, bool backtrack = true) {\n        // we deselect set\n\n        m_cost_of_solution -= m_sets_data[selected_set_id].m_cost;\n        for (auto element : m_set_id_to_elements(selected_set_id)) {\n            if (covered_by(element) == selected_set_id) {\n                m_covered_by[m_get_el_index(element)] = UNCOVERED;\n                auto weight_of_element = m_element_to_weight(element);\n                cover_element(element, -weight_of_element, backtrack, false);\n            }\n        }\n        m_selected_sets.pop_back();\n    }\n\n    void set_unprocessed(\n            boost::iterator_range<std::vector<int>::const_iterator> const & set_ids) {\n        for (auto set_id : set_ids) {\n            m_sets_data[set_id].m_is_processed = false;\n        }\n    };\n\n    void reset() {\n        set_unprocessed(m_selected_sets);\n        if (m_selected_sets.size() > 0) {\n            boost::for_each(m_selected_sets, [&](int selected_set_id) {\n                select_set_backtrack(selected_set_id, true);\n            });\n        }\n    }\n\n    std::size_t size() {\n        return m_selected_sets.size();\n    }\n\n    void resize(std::size_t size) {\n        return m_selected_sets.resize(size);\n    }\n\n    template <typename OutputIterator>\n    void copy_to(OutputIterator out){\n        boost::copy(m_selected_sets, out);\n    }\nprivate:\n\n    void select_set(int selected_set_id, bool backtrack) {\n        auto &select_set_data = m_sets_data[selected_set_id];\n\n        m_cost_of_solution += select_set_data.m_cost;\n        for (auto element : m_set_id_to_elements(selected_set_id)) {\n            if (covered_by(element) == UNCOVERED) { /* we do not cover the\n                                                        elements being covered*/\n\n                m_covered_by[m_get_el_index(element)] = selected_set_id;\n                auto weight_of_element = m_element_to_weight(element);\n                cover_element(element, weight_of_element, backtrack);\n            }\n        }\n    }\n\n    /// optimization:\n    /// in greedy phase we get sets in decreasing density order, so we can cut\n    /// when spend rest of budget with current density product solution, worse\n    /// then best found solution.\n    bool greedy_prune(const SetData & set_data) {\n        return (m_budget - m_cost_of_solution) * set_data.m_weight_of_uncovered_elements <=\n                static_cast<Budget>(set_data.m_cost * (m_weight_of_bests_solution - m_weight_of_covered_elements));\n    }\n\n    ///this function is ALWAYS called from select_set, thats why we set set_data.m_is_processed!\n    bool can_select(SetData & set_data) {\n        if (set_data.m_is_processed) return false;\n        set_data.m_is_processed = true;\n        return static_cast<Budget>(m_cost_of_solution + set_data.m_cost) <= m_budget &&\n            set_data.m_weight_of_uncovered_elements!= ElementWeight{};\n    }\n\n    template <typename Element>\n    void cover_element(Element && el, ElementWeight weight_diff, bool backtrack, bool select = true) {\n        m_weight_of_covered_elements += weight_diff;\n        for (auto set_id :\n                m_sets_covering_element[m_get_el_index(el)]) {\n            if (m_sets_data[set_id].m_weight_of_uncovered_elements >\n                    weight_diff || backtrack) {\n                m_sets_data[set_id].m_weight_of_uncovered_elements -= weight_diff;\n                if (!backtrack && !m_sets_data[set_id].m_is_processed) {\n                    m_decrese_weight(set_id);\n                }\n            } else {\n                if (select) {\n                    m_sets_data[set_id].m_is_processed = true;\n                }\n            }\n        }\n    }\n\n    template <typename Element>\n    auto covered_by(Element && el) const\n        -> decltype(m_covered_by[m_get_el_index(el)]) {\n\n        return m_covered_by[m_get_el_index(el)];\n    }\n};\n\ntemplate <class Budget, class SetCost, class SetIdToData, class ElementWeight,\n         class SetIdToElements, class ElementIndex, class GetWeightOfElement,\n         typename DecreseWeight>\nauto make_selector(const Budget budget, SetCost &cost_of_solution,\n                   SetIdToData &sets_data,\n                   const ElementWeight &weight_of_bests_solution,\n                   ElementWeight &weight_of_covered_elements,\n                   SetIdToElements set_id_to_elements,\n                   std::vector<int> &covered_by,\n                   std::vector<std::vector<int>> &sets_covering_element,\n                   ElementIndex &get_el_index,\n                   GetWeightOfElement &element_to_weight,\n                   DecreseWeight decrese_weight) {\n    return selector<Budget, SetCost, SetIdToData, ElementWeight,\n                    SetIdToElements, ElementIndex, GetWeightOfElement,\n                    DecreseWeight>(\n        budget, cost_of_solution, sets_data,\n        weight_of_bests_solution, weight_of_covered_elements,\n        set_id_to_elements, covered_by, sets_covering_element, get_el_index,\n        element_to_weight, decrese_weight);\n}\n} //!detail\n\n/**\n * @brief this is solve Set Cover problem\n * and return set cover cost\n * example:\n *  \\snippet set_cover_example.cpp Set Cover Example\n *\n * complete example is set_cover_example.cpp\n * @param sets\n * @param set_to_cost\n * @param set_to_elements\n * @param result set iterators of chosen sets\n * @param get_el_index\n * @param budget\n * @param element_to_weight\n * @param initial_set_size\n * @tparam SetRange\n * @tparam GetCostOfSet\n * @tparam GetElementsOfSet\n * @tparam OutputIterator\n * @tparam ElementIndex\n * @tparam Budget\n * @tparam GetWeightOfElement\n */\ntemplate <typename SetRange, class GetCostOfSet, class GetElementsOfSet,\n          class OutputIterator, class ElementIndex, class Budget,\n          class GetWeightOfElement = utils::return_one_functor>\nauto budgeted_maximum_coverage(\n    SetRange && sets, GetCostOfSet set_to_cost,\n    GetElementsOfSet set_to_elements, OutputIterator result,\n    ElementIndex get_el_index, Budget budget,\n    GetWeightOfElement element_to_weight = GetWeightOfElement(),\n    const unsigned int initial_set_size = 3) {\n\n    using set_reference = typename boost::range_reference<SetRange>::type;\n    using element_weight = typename detail::element_weight_t<\n        set_reference, GetElementsOfSet, GetWeightOfElement>;\n    using set_cost = pure_result_of_t<GetCostOfSet(set_reference)>;\n    using set_id_to_data = std::vector<detail::set_data_type<element_weight, set_cost>>;\n\n    auto nu_sets = boost::distance(sets);\n    set_id_to_data initial_sets_data(nu_sets), sets_data(nu_sets);\n    set_cost cost_of_solution{}, cost_of_best_solution{};\n    int number_of_elements = 0;\n\n    // we find max index of elements in all sets\n    for (auto set_and_data : boost::combine(sets, initial_sets_data)) {\n        auto const & set = boost::get<0>(set_and_data);\n        auto &cost = boost::get<1>(set_and_data).m_cost;\n        cost = set_to_cost(set);\n        assert(cost != set_cost{});\n        auto const & elements = set_to_elements(set);\n        if (!boost::empty(elements)) {\n            number_of_elements = std::max(number_of_elements,\n                    *max_element_functor(elements, get_el_index) + 1);\n        }\n    }\n    element_weight weight_of_covered_elements{}, weight_of_bests_solution{};\n    std::vector<int> best_solution(1);\n    std::vector<int> covered_by(\n        number_of_elements, detail::UNCOVERED); // index of the first set that covers\n                                        // element or -1 if element is uncovered\n    std::vector<int> sets_id(nu_sets);\n    boost::iota(sets_id, 0);\n    std::vector<std::vector<int>> sets_covering_element(number_of_elements);\n    auto decreasing_density_order =\n        utils::make_functor_to_comparator([&](int x) {\n            return data_structures::make_fraction(\n                sets_data[x].m_weight_of_uncovered_elements, sets_data[x].m_cost);\n        });\n    using queue = boost::heap::d_ary_heap<\n        int, boost::heap::arity<3>, boost::heap::mutable_<true>,\n        boost::heap::compare<decltype(decreasing_density_order)>>;\n\n    queue uncovered_set_queue{ decreasing_density_order };\n    std::vector<typename queue::handle_type> set_id_to_handle(nu_sets);\n\n    // we fill sets_covering_element and setToWeightOfElements\n    for (auto set : sets | boost::adaptors::indexed()) {\n        auto set_id = set.index();\n        auto &set_data = initial_sets_data[set_id];\n\n        for (auto &&element : set_to_elements(set.value())) {\n            sets_covering_element[get_el_index(element)].push_back(set_id);\n            set_data.m_weight_of_uncovered_elements += element_to_weight(element);\n        }\n        if (initial_set_size ==\n            0) { /* we check all one element set. if initial_set_size!= 0 then\n                    we will do it anyway */\n            set_cost cost_of_set = set_data.m_cost;\n            if (set_data.m_weight_of_uncovered_elements >= weight_of_bests_solution &&\n                static_cast<Budget>(cost_of_set) <= budget) {\n                weight_of_bests_solution = set_data.m_weight_of_uncovered_elements;\n                best_solution[0] = set_id;\n                cost_of_best_solution = cost_of_set;\n            }\n        }\n    };\n\n    auto sort_sets = [&](std::vector<int>& sets_range) {\n        boost::sort(sets_range, utils::make_functor_to_comparator([&](int x) {\n                                    return sets_data[x].m_weight_of_uncovered_elements;\n                                }));\n        return sets_range.end();\n    };\n    auto selector = detail::make_selector\n                (budget, cost_of_solution,sets_data,\n                 weight_of_bests_solution,weight_of_covered_elements,\n                 [&](int selected_set_id){return set_to_elements(sets[selected_set_id]);},\n                 covered_by,sets_covering_element,get_el_index,\n                 element_to_weight,\n                 [&](int set_id){uncovered_set_queue.decrease(set_id_to_handle[set_id]);});\n\n    boost::copy(initial_sets_data, sets_data.begin());\n    sort_sets(sets_id);\n    auto solver = make_subset_backtrack(sets_id);\n\n    auto reset = [&]() {\n        boost::copy(initial_sets_data, sets_data.begin());\n        cost_of_solution = set_cost{};\n        selector.set_unprocessed(solver.get_moves());\n        boost::fill(covered_by, detail::UNCOVERED);\n        weight_of_covered_elements = element_weight{};\n        selector.reset();\n    };\n\n    auto on_pop = [&](int deselected_set_id) {\n        selector.deselect_set(deselected_set_id);\n        selector.set_unprocessed(solver.get_moves());\n    };\n\n    auto save_best_solution = [&]() {\n        // we check that new solution is better than any previous\n        // if is we remember them\n        // tricky: either better weight, or equal weight and lower cost\n        if (std::make_pair(weight_of_covered_elements, cost_of_best_solution) >\n            std::make_pair(weight_of_bests_solution, cost_of_solution)) {\n            weight_of_bests_solution = weight_of_covered_elements;\n            cost_of_best_solution = cost_of_solution;\n            best_solution.resize(selector.size());\n            selector.copy_to(best_solution.begin());\n        }\n    };\n    auto greedy_phase = [&]() {\n        uncovered_set_queue.clear();\n        auto moves = solver.get_moves();\n        if(boost::empty(moves)) return;\n\n        for (auto set_id : moves) {\n            set_id_to_handle[set_id] = uncovered_set_queue.push(set_id);\n        }\n        /* we select set with best elements to cost ratio, and add it to the\n         * result until all elements are covered*/\n        int uncovered_set_id;\n        do {\n            uncovered_set_id = uncovered_set_queue.top();\n            uncovered_set_queue.pop();\n        } while (!selector.select_set_greedy(uncovered_set_id) &&\n                !uncovered_set_queue.empty());\n    };\n\n    auto can_push = [&](int candidate) {\n        if (!selector.select_set_backtrack(candidate)) {\n            return false;\n        }\n        if (selector.size() == initial_set_size) {\n            greedy_phase();\n            save_best_solution();\n            selector.resize(initial_set_size-1);\n            reset();\n            return false;\n        } else {\n            save_best_solution();\n            return true;\n        }\n    };\n\n    reset();\n    if (initial_set_size != 0) { /* if initial_set_size == 0 then we do greedy\n    algorithm once starts from empty initial Set.\n    Otherwise we starts greedy algorithm from all initial set of size equal\n    initial_set_size those for which we have enough budget*/\n        solver.solve(can_push, on_pop, sort_sets);\n    } else {\n        greedy_phase();\n        save_best_solution();\n    }\n\n    for (auto set_id : best_solution) {\n        *result = *(sets.begin() + set_id);\n        ++result;\n    }\n    return weight_of_bests_solution;\n};\n} //!greedy\n} //!paal\n\n#endif /* PAAL_BUDGETED_MAXIMUM_COVERAGE_HPP */\n", "meta": {"hexsha": "609827abc5adeb2cc1202ee2aae0ce59dbaacc54", "size": 17169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/greedy/set_cover/budgeted_maximum_coverage.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/set_cover/budgeted_maximum_coverage.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/set_cover/budgeted_maximum_coverage.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": 39.4689655172, "max_line_length": 115, "alphanum_fraction": 0.660434504, "num_tokens": 3816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "#ifndef OSRM_UTIL_RECTANGLE_HPP\n#define OSRM_UTIL_RECTANGLE_HPP\n\n#include \"util/coordinate.hpp\"\n#include \"util/coordinate_calculation.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <limits>\n#include <utility>\n\n#include <cstdint>\n\nnamespace osrm\n{\nnamespace util\n{\n\nstruct RectangleInt2D\n{\n    RectangleInt2D()\n        : min_lon{std::numeric_limits<std::int32_t>::max()},\n          max_lon{std::numeric_limits<std::int32_t>::min()},\n          min_lat{std::numeric_limits<std::int32_t>::max()},\n          max_lat{std::numeric_limits<std::int32_t>::min()}\n    {\n    }\n\n    RectangleInt2D(FixedLongitude min_lon_,\n                   FixedLongitude max_lon_,\n                   FixedLatitude min_lat_,\n                   FixedLatitude max_lat_)\n        : min_lon(min_lon_), max_lon(max_lon_), min_lat(min_lat_), max_lat(max_lat_)\n    {\n    }\n\n    RectangleInt2D(FloatLongitude min_lon_,\n                   FloatLongitude max_lon_,\n                   FloatLatitude min_lat_,\n                   FloatLatitude max_lat_)\n        : min_lon(toFixed(min_lon_)), max_lon(toFixed(max_lon_)), min_lat(toFixed(min_lat_)),\n          max_lat(toFixed(max_lat_))\n    {\n    }\n\n    FixedLongitude min_lon, max_lon;\n    FixedLatitude min_lat, max_lat;\n\n    void MergeBoundingBoxes(const RectangleInt2D &other)\n    {\n        min_lon = std::min(min_lon, other.min_lon);\n        max_lon = std::max(max_lon, other.max_lon);\n        min_lat = std::min(min_lat, other.min_lat);\n        max_lat = std::max(max_lat, other.max_lat);\n        BOOST_ASSERT(min_lon != FixedLongitude{std::numeric_limits<std::int32_t>::min()});\n        BOOST_ASSERT(min_lat != FixedLatitude{std::numeric_limits<std::int32_t>::min()});\n        BOOST_ASSERT(max_lon != FixedLongitude{std::numeric_limits<std::int32_t>::min()});\n        BOOST_ASSERT(max_lat != FixedLatitude{std::numeric_limits<std::int32_t>::min()});\n    }\n\n    Coordinate Centroid() const\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 = (min_lon + max_lon) / FixedLongitude{2};\n        centroid.lat = (min_lat + max_lat) / FixedLatitude{2};\n        return centroid;\n    }\n\n    bool Intersects(const RectangleInt2D &other) const\n    {\n        // Standard box intersection test - check if boxes *don't* overlap,\n        // and return the negative of that\n        return !(max_lon < other.min_lon || min_lon > other.max_lon || max_lat < other.min_lat ||\n                 min_lat > other.max_lat);\n    }\n\n    // This code assumes that we are operating in euclidean space!\n    // That means if you just put unprojected lat/lon in here you will\n    // get invalid results.\n    std::uint64_t GetMinSquaredDist(const Coordinate location) const\n    {\n        const bool is_contained = Contains(location);\n        if (is_contained)\n        {\n            return 0.0f;\n        }\n\n        enum Direction\n        {\n            INVALID = 0,\n            NORTH = 1,\n            SOUTH = 2,\n            EAST = 4,\n            NORTH_EAST = 5,\n            SOUTH_EAST = 6,\n            WEST = 8,\n            NORTH_WEST = 9,\n            SOUTH_WEST = 10\n        };\n\n        Direction d = INVALID;\n        if (location.lat > max_lat)\n            d = (Direction)(d | NORTH);\n        else if (location.lat < min_lat)\n            d = (Direction)(d | SOUTH);\n        if (location.lon > max_lon)\n            d = (Direction)(d | EAST);\n        else if (location.lon < min_lon)\n            d = (Direction)(d | WEST);\n\n        BOOST_ASSERT(d != INVALID);\n\n        std::uint64_t min_dist = std::numeric_limits<std::uint64_t>::max();\n        switch (d)\n        {\n        case NORTH:\n            min_dist = coordinate_calculation::squaredEuclideanDistance(\n                location, Coordinate(location.lon, max_lat));\n            break;\n        case SOUTH:\n            min_dist = coordinate_calculation::squaredEuclideanDistance(\n                location, Coordinate(location.lon, min_lat));\n            break;\n        case WEST:\n            min_dist = coordinate_calculation::squaredEuclideanDistance(\n                location, Coordinate(min_lon, location.lat));\n            break;\n        case EAST:\n            min_dist = coordinate_calculation::squaredEuclideanDistance(\n                location, Coordinate(max_lon, location.lat));\n            break;\n        case NORTH_EAST:\n            min_dist = coordinate_calculation::squaredEuclideanDistance(\n                location, Coordinate(max_lon, max_lat));\n            break;\n        case NORTH_WEST:\n            min_dist = coordinate_calculation::squaredEuclideanDistance(\n                location, Coordinate(min_lon, max_lat));\n            break;\n        case SOUTH_EAST:\n            min_dist = coordinate_calculation::squaredEuclideanDistance(\n                location, Coordinate(max_lon, min_lat));\n            break;\n        case SOUTH_WEST:\n            min_dist = coordinate_calculation::squaredEuclideanDistance(\n                location, Coordinate(min_lon, min_lat));\n            break;\n        default:\n            break;\n        }\n\n        BOOST_ASSERT(min_dist < std::numeric_limits<std::uint64_t>::max());\n\n        return min_dist;\n    }\n\n    bool Contains(const Coordinate location) const\n    {\n        const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);\n        const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);\n        return lons_contained && lats_contained;\n    }\n\n    bool IsValid() const\n    {\n        return min_lon != FixedLongitude{std::numeric_limits<std::int32_t>::max()} &&\n               max_lon != FixedLongitude{std::numeric_limits<std::int32_t>::min()} &&\n               min_lat != FixedLatitude{std::numeric_limits<std::int32_t>::max()} &&\n               max_lat != FixedLatitude{std::numeric_limits<std::int32_t>::min()};\n    }\n};\n} // namespace util\n} // namespace osrm\n\n#endif\n", "meta": {"hexsha": "eb53396d1a00aced82020f18f2707bd7fee3f329", "size": 5925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/rectangle.hpp", "max_stars_repo_name": "EricWang1hitsz/osrm-backend", "max_stars_repo_head_hexsha": "ff1af413d6c78f8e454584fe978d5468d984d74a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4526.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T15:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:33:49.000Z", "max_issues_repo_path": "include/util/rectangle.hpp", "max_issues_repo_name": "wsx9527/osrm-backend", "max_issues_repo_head_hexsha": "1e70b645e480946dad313b67f6a7d331baecfe3c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4497.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T15:29:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:19:35.000Z", "max_forks_repo_path": "include/util/rectangle.hpp", "max_forks_repo_name": "wsx9527/osrm-backend", "max_forks_repo_head_hexsha": "1e70b645e480946dad313b67f6a7d331baecfe3c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3023.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T18:40:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T13:30:46.000Z", "avg_line_length": 33.2865168539, "max_line_length": 97, "alphanum_fraction": 0.5951054852, "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "/*\n    Copyright 2013 Adobe\n    Distributed under the Boost Software License, Version 1.0.\n    (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n/**************************************************************************************************/\n\n#ifndef ADOBE_dancing_links_t_HPP\n#define ADOBE_dancing_links_t_HPP\n\n/**************************************************************************************************/\n\n#include <adobe/config.hpp>\n\n#include <vector>\n\n#if ADOBE_STD_SERIALIZATION\n#include <iostream>\n#endif\n\n#include <boost/function.hpp>\n#include <boost/noncopyable.hpp>\n\n#include <adobe/implementation/toroid.hpp>\n\n#define ADOBE_DLX_VERBOSE 0\n\n#if ADOBE_STD_SERIALIZATION && ADOBE_DLX_VERBOSE\n#include <adobe/iomanip.hpp>\n#endif\n\n/**************************************************************************************************/\n\nnamespace adobe {\n\n/**************************************************************************************************/\n\n#ifndef ADOBE_NO_DOCUMENTATION\n\n/**************************************************************************************************/\n\nnamespace implementation {\n\n/**************************************************************************************************/\n\nstruct do_nothing_callback_t {\n    inline void operator()(std::size_t, bool) const {}\n};\n\n/**************************************************************************************************/\n\nstruct select_right_heuristic_t {\n    inline toroid_header_t* operator()(byte_toroid_t& toroid) const {\n        return toroid.right_of(&toroid.header_m);\n    }\n};\n\n/**************************************************************************************************/\n\nstruct select_most_constrained_heuristic_t {\n    inline toroid_header_t* operator()(byte_toroid_t& toroid) const {\n        toroid_header_t* c(toroid.right_of(&toroid.header_m));\n        std::size_t sz(c->size_m);\n\n        for (toroid_header_t* p(toroid.right_of(c)); p != &toroid.header_m;\n             p = toroid.right_of(p)) {\n            if (p->size_m < sz) {\n                c = p;\n                sz = p->size_m;\n            }\n\n            if (sz == 1)\n                break;\n        }\n\n        return c;\n    }\n};\n\n/**************************************************************************************************/\n\n} // namespace implementation\n\n/**************************************************************************************************/\n\n#endif\n\n/**************************************************************************************************/\n\nclass dancing_links_t : boost::noncopyable {\npublic:\n#ifndef ADOBE_NO_DOCUMENTATION\n    dancing_links_t(std::size_t row_count, std::size_t column_count)\n        : toroid_m(row_count, column_count), output_m(column_count, 0), solutions_m(0)\n#if ADOBE_DLX_VERBOSE\n          ,\n          tab_count_m(0)\n#endif\n    {\n    }\n#endif\n\n    inline void set(std::size_t row, std::size_t col, char color = 0) {\n        toroid_m.set(row, col, color);\n    }\n\n    inline void set_secondary_column(std::size_t col) { toroid_m.set_secondary_column(col); }\n\n    template <typename ResultCallback, typename SearchHeuristic>\n    inline std::size_t search(std::size_t max_solutions, ResultCallback callback,\n                              SearchHeuristic heuristic) {\n        max_solutions_m = max_solutions;\n\n        toroid_m.finalize();\n\n        do_search(0, callback, heuristic);\n\n        return solutions_m;\n    }\n\n    inline std::size_t search(std::size_t max_solutions) {\n        return search(max_solutions, implementation::do_nothing_callback_t(),\n                      implementation::select_most_constrained_heuristic_t());\n    }\n\n#if ADOBE_STD_SERIALIZATION\n    friend std::ostream& operator<<(std::ostream& s, const dancing_links_t& dancing_links_t) {\n        return s << dancing_links_t.toroid_m;\n    }\n#endif\n\nprivate:\n    template <typename ResultCallback, typename SearchHeuristic>\n    void do_search(std::size_t k, ResultCallback callback, SearchHeuristic heuristic) {\n        if (toroid_m.right_of(&toroid_m.header_m) == &toroid_m.header_m) {\n            ++solutions_m;\n\n#if ADOBE_DLX_VERBOSE\n            std::cout << adobe::indents(tab_count_m) << \"<solved/>\" << std::endl;\n#endif\n\n            for (std::size_t i(0); i < k; ++i)\n                callback(toroid_m.row_index_of(output_m[i]), i + 1 == k);\n\n            return;\n        }\n\n        std::size_t next_k(k + 1);\n\n        toroid_header_t* c(heuristic(toroid_m));\n\n#if ADOBE_DLX_VERBOSE\n        ++tab_count_m;\n        std::cout << adobe::indents(tab_count_m) << \"<c\"\n                  << toroid_m.column_index_of(toroid_m.down_of(c)) << \">\" << std::endl;\n#endif\n\n        toroid_m.cover_column(c);\n\n        // branch on each node in this column\n        for (toroid_node_t* r(toroid_m.down_of(c)); r != c; r = toroid_m.down_of(r)) {\n#if ADOBE_DLX_VERBOSE\n            std::cout << adobe::indents(tab_count_m) << \"<r\" << toroid_m.row_index_of(r) << \">\"\n                      << std::endl;\n#endif\n\n            output_m[k] = r;\n\n            // cover or purify each node on the same row as the node we're branching on\n            for (toroid_node_t* j(toroid_m.right_of(r)); j != r; j = toroid_m.right_of(j)) {\n                if (j->color_m == 0) {\n#if ADOBE_DLX_VERBOSE\n                    std::cout << adobe::indents(tab_count_m) << \"<c\" << toroid_m.column_index_of(j)\n                              << \">\" << std::endl;\n#endif\n                    toroid_m.cover_column(toroid_m.column_of(j));\n                } else if (j->color_m > 0) {\n#if ADOBE_DLX_VERBOSE\n                    std::cout << adobe::indents(tab_count_m) << \"<p\" << toroid_m.column_index_of(j)\n                              << \">\" << std::endl;\n#endif\n                    toroid_m.purify(j);\n                }\n            }\n\n#if ADOBE_DLX_VERBOSE\n// std::cout << *this << std::endl;\n#endif\n\n            do_search(next_k, callback, heuristic);\n\n            if (solutions_m >= max_solutions_m)\n                return;\n\n            r = output_m[k];\n\n            c = toroid_m.column_of(r);\n\n            // undo the cover/purify\n            for (toroid_node_t* j(toroid_m.left_of(r)); j != r; j = toroid_m.left_of(j)) {\n                if (j->color_m == 0) {\n#if ADOBE_DLX_VERBOSE\n                    std::cout << adobe::indents(tab_count_m) << \"</c\" << toroid_m.column_index_of(j)\n                              << \">\" << std::endl;\n#endif\n                    toroid_m.uncover_column(toroid_m.column_of(j));\n                } else if (j->color_m > 0) {\n#if ADOBE_DLX_VERBOSE\n                    std::cout << adobe::indents(tab_count_m) << \"</p\" << toroid_m.column_index_of(j)\n                              << \">\" << std::endl;\n#endif\n                    toroid_m.unpurify(j);\n                }\n            }\n\n#if ADOBE_DLX_VERBOSE\n            std::cout << adobe::indents(tab_count_m) << \"</r\" << toroid_m.row_index_of(r) << \">\"\n                      << std::endl;\n#endif\n        }\n\n        toroid_m.uncover_column(c);\n\n#if ADOBE_DLX_VERBOSE\n        std::cout << adobe::indents(tab_count_m) << \"</c\"\n                  << toroid_m.column_index_of(toroid_m.down_of(c)) << \">\" << std::endl;\n        --tab_count_m;\n#endif\n    };\n\n    byte_toroid_t toroid_m;\n    std::vector<toroid_node_t*> output_m;\n    std::size_t solutions_m;\n    std::size_t max_solutions_m;\n#if ADOBE_DLX_VERBOSE\n    std::size_t tab_count_m;\n#endif\n};\n\n/**************************************************************************************************/\n\n} // namespace adobe\n\n/**************************************************************************************************/\n\n#endif\n\n/**************************************************************************************************/\n", "meta": {"hexsha": "5e538d6b5d85cc15a16ec2888bf24410b8e6a3f2", "size": 7759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adobe/dancing_links.hpp", "max_stars_repo_name": "jaredwy/adobe_source_libraries", "max_stars_repo_head_hexsha": "b71f5d08ab10396e9d2ba5e73861ca018f899a2d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 252.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T13:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:02:01.000Z", "max_issues_repo_path": "adobe/dancing_links.hpp", "max_issues_repo_name": "etiennemlb/adobe_source_libraries", "max_issues_repo_head_hexsha": "5ced8bf61fbb487e9a2c6fa3ea7abc2687448c3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-05-04T23:49:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T18:31:51.000Z", "max_forks_repo_path": "adobe/dancing_links.hpp", "max_forks_repo_name": "etiennemlb/adobe_source_libraries", "max_forks_repo_head_hexsha": "5ced8bf61fbb487e9a2c6fa3ea7abc2687448c3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-06-09T07:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:35:05.000Z", "avg_line_length": 31.1606425703, "max_line_length": 100, "alphanum_fraction": 0.4825364093, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "/*\n * Luca Anzalone\n */\n\n#include <jni.h>\n\n#include <string>\n#include <vector>\n#include <mutex>\n\n#include <android/log.h>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/features2d.hpp>  // FAST\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/video/tracking.hpp>\n\n#include <dlib/image_io.h>\n#include <dlib/image_processing.h>\n#include <dlib/image_processing/generic_image.h>\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <dlib/opencv/cv_image.h>\n\n#define LOG_TAG \"native-lib\"\n#define LOGD(...) \\\n  ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))\n\n#define JNI_METHOD(NAME) \\\n    Java_com_dev_anzalone_luca_facelandmarks_Native_##NAME\n\n#define KERNEL_SIZE 5 // 3, 5, 7, 9\n\n#define NV21 17\n#define YV12 842094169\n#define YUV_420_888 35\n#define PYRAMIDS 3\n#define MAX_FRAME_COUNT 5\n\nusing namespace std;\n\n// global variables:\ndlib::shape_predictor shape_predictor;\nstd::mutex _mutex;\nint imageFormat = NV21;\n\n// -------------------------------------------------------------------------------------------------\n// -- Lucas-Kanade Optical Flow Tracker\n// -------------------------------------------------------------------------------------------------\nnamespace LK {\n    // variables\n    int frameCount = 0;\n    bool isTracking = false;\n    cv::Mat prev_img;\n    vector<cv::Point2f> prev_pts;\n    vector<cv::Point2f> next_pts;\n    cv::TermCriteria criteria(cv::TermCriteria::COUNT | cv::TermCriteria::EPS, 25, 0.01);\n    cv::Size ROI(20, 20);\n\n    /** Initialize tracking with the current frame and detected landmarks */\n    void start(cv::Mat &mat, dlib::full_object_detection &pts) {\n        // release stuff..\n        prev_img.release();\n        prev_img = mat;\n        prev_pts.clear();\n        next_pts.clear();\n\n        // consider the new points\n        for (unsigned long i = 0; i < pts.num_parts(); i++) {\n            auto pt = pts.part(i);\n            prev_pts.push_back(cv::Point2f(pt.x(), pt.y()));\n        }\n\n        // reset count\n        frameCount = 0;\n        isTracking = true;\n    }\n\n    /** tracking points in the next captured frame */\n    vector<cv::Point2f> track(cv::Mat &frame) {\n        vector<uchar> status;\n        vector<float> err;\n        vector<cv::Point2f> tracked;\n\n        // get the new points from the old one\n        calcOpticalFlowPyrLK(prev_img, frame, prev_pts, next_pts, status, err,\n                             ROI, PYRAMIDS, criteria);\n\n        for (int i = 0; i < status.size(); ++i) {\n            if (status[i] == 0) {\n                // flow not found: take the old point\n                tracked.push_back(prev_pts[i]);\n            } else {\n                // flow found: take the new point\n                tracked.push_back(next_pts[i]);\n            }\n        }\n\n        // switch the previous points and image with the current\n        swap(prev_img, frame);\n        swap(prev_pts, tracked);\n        next_pts.clear();\n\n        // increase tracking frame count\n        if (frameCount++ > MAX_FRAME_COUNT) {\n            isTracking = false;\n        }\n\n        return prev_pts;\n    }\n}\n// -------------------------------------------------------------------------------------------------\n\nextern \"C\"\nJNIEXPORT void JNICALL\nJNI_METHOD(loadModel)(JNIEnv* env, jclass, jstring detectorPath) {\n    try {\n        const char *path = env->GetStringUTFChars(detectorPath, JNI_FALSE);\n\n        _mutex.lock();\n            // cause the later initialization of the tracking\n            LK::isTracking = false;\n\n            // load the shape predictor\n            dlib::deserialize(path) >> shape_predictor;\n        _mutex.unlock();\n\n        env->ReleaseStringUTFChars(detectorPath, path); //free mem\n        LOGD(\"JNI: model loaded\");\n\n    } catch (dlib::serialization_error &e) {\n        LOGD(\"JNI: failed to model -> %s\", e.what());\n    }\n}\n//--------------------------------------------------------------------------------------------------\n\nvoid rotateMat(cv::Mat &mat, int rotation) {\n    if (rotation == 90) { // portrait\n//        LOGD(\"JNI: rotation 90\");\n        cv::transpose(mat, mat);\n        cv::flip(mat, mat, -1);\n    } else if (rotation == 0) { // landscape-left\n//        LOGD(\"JNI: rotation 0\");\n        cv::flip(mat, mat, 1);\n    } else if (rotation == 180) { // landscape-right\n//        LOGD(\"JNI: rotation 180\");\n        cv::flip(mat, mat, 0);\n    }\n}\n\nextern \"C\"\nJNIEXPORT void JNICALL\nJNI_METHOD(setImageFormat)(JNIEnv* env, jclass, jint format) {\n    imageFormat = format;\n}\n\n\n//--------------------------------------------------------------------------------------------------\n//-- LANDMARK DETECTION\n//--------------------------------------------------------------------------------------------------\nextern \"C\"\nJNIEXPORT jlongArray JNICALL\nJNI_METHOD(detectLandmarks)(JNIEnv* env, jclass, jbyteArray yuvFrame, jint rotation, jint width, jint height, jint left, jint top, jint right, jint bottom) {\n//    LOGD(\"JNI: detectLandmarks\");\n\n    // copy content of frame into image\n    jbyte *data = env->GetByteArrayElements(yuvFrame, 0);\n\n    // convert yuv-frame to cv::Mat\n    cv::Mat yuvMat(height + height / 2, width, CV_8UC1, (unsigned char *) data);\n    cv::Mat grayMat(height, width, CV_8UC1);\n\n    // to grayscale\n    if (imageFormat == NV21)\n        cv::cvtColor(yuvMat, grayMat, cv::COLOR_YUV2GRAY_NV21);  // was CV_YUV2GRAY_NV21\n    else if (imageFormat == YV12)\n        cv::cvtColor(yuvMat, grayMat, cv::COLOR_YUV2GRAY_YV12);  // was CV_YUV2GRAY_YV12\n\n    // adjust rotation according to phone orientation\n    rotateMat(grayMat, rotation);\n\n //   __android_log_print(ANDROID_LOG_VERBOSE, \"D/native-lib\",\n //                       \"left %d right %d width %d, height %d\", left, right, width, grayMat.cols);\n\n    // keeping the face inside of the grayMat\n    if (left < 0) {\n        left = 0;\n        LOGD(\"Face out of left\");\n    }\n    if (right > grayMat.cols) {\n        right = grayMat.cols-1;\n        LOGD(\"Face out of right\");\n    }\n    if (top < 0) {\n        top = 0;\n        LOGD(\"Face out of top\");\n    }\n    if (bottom > grayMat.rows) {\n        bottom = grayMat.rows-1;\n        LOGD(\"Face out of bottom\");\n    }\n    // crop face for enhancements\n    cv::Rect faceROI(left, top, right - left, bottom - top);\n    cv::Mat face = grayMat(faceROI);\n\n    // apply filters\n    cv::medianBlur(face, face, KERNEL_SIZE);  // remove noise\n    cv::equalizeHist(face, face);  // improve contrast\n\n    if (!LK::isTracking) {\n        // -- DETECT LANDMARKS -- //\n\n        // cv::mat to dlib::image\n        dlib::cv_image<unsigned char> image(grayMat);\n\n        // detect landmark points\n        _mutex.lock();\n        dlib::rectangle region(left, top, right, bottom);\n        dlib::full_object_detection points = shape_predictor(image, region);\n        _mutex.unlock();\n\n        // result\n        auto num_points = points.num_parts();\n        jsize len = (jsize) (num_points * sizeof(short)); // num_points * 2\n\n        jlong buffer[len];\n        jlongArray result = env->NewLongArray(len);\n\n        // copy points in the buffer\n        auto k = 0;\n        for (unsigned long i = 0l; i < num_points; ++i) {\n            dlib::point p = points.part(i);\n            buffer[k++] = p.x();\n            buffer[k++] = p.y();\n        }\n\n        // set the content of buffer into result array\n        env->SetLongArrayRegion(result, 0, len, buffer);\n\n        // free mem\n        env->ReleaseByteArrayElements(yuvFrame, data, 0);\n\n        // uncomment to enable tracking for the next frames\n//        LK::start(grayMat, points);\n\n        return result;\n\n    } else {\n        // -- COMPUTE LK-OPTICAL FLOW --\n        auto trackedPts = LK::track(grayMat);\n\n        // result\n        auto num_points = trackedPts.size();\n        jsize len = (jsize) (num_points * sizeof(short)); // num_points * 2\n\n        jlong buffer[len];\n        jlongArray result = env->NewLongArray(len);\n\n        // copy tracked points in the buffer\n        auto k = 0;\n        for (unsigned long i = 0l; i < num_points; ++i) {\n            auto p = trackedPts[i];\n            buffer[k++] = static_cast<jlong>(p.x);\n            buffer[k++] = static_cast<jlong>(p.y);\n        }\n\n        // set the content of buffer into result array\n        env->SetLongArrayRegion(result, 0, len, buffer);\n\n        // free mem\n        env->ReleaseByteArrayElements(yuvFrame, data, 0);\n\n        return result;\n    }\n}\n\n//--------------------------------------------------------------------------------------------------", "meta": {"hexsha": "62989ea1e50fa8d3d1153f46a187d6217fac6583", "size": 8497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/src/main/cpp/native-lib.cpp", "max_stars_repo_name": "muratcancicek/android-face-landmarks-mc", "max_stars_repo_head_hexsha": "f31a144d08e171f7d3aa224b02db61c1db65cfdb", "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/src/main/cpp/native-lib.cpp", "max_issues_repo_name": "muratcancicek/android-face-landmarks-mc", "max_issues_repo_head_hexsha": "f31a144d08e171f7d3aa224b02db61c1db65cfdb", "max_issues_repo_licenses": ["MIT"], "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/src/main/cpp/native-lib.cpp", "max_forks_repo_name": "muratcancicek/android-face-landmarks-mc", "max_forks_repo_head_hexsha": "f31a144d08e171f7d3aa224b02db61c1db65cfdb", "max_forks_repo_licenses": ["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.6750902527, "max_line_length": 157, "alphanum_fraction": 0.5477227257, "num_tokens": 2049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400276}}
{"text": "// Copyright 2018 Google 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#include <jni.h>\n#include <stdint.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"cpp/jni/macros.h\"\n#include \"cpp/sensor_fusion/online_sensor_fusion.h\"\n\n#undef JNI_PACKAGE_NAME\n#define JNI_PACKAGE_NAME com_google_vr180_capture_motion\n\n#undef JNI_CLASS_NAME\n#define JNI_CLASS_NAME SensorFusion\n\nusing vr180::OnlineSensorFusion;\n\nextern \"C\" {\n\nnamespace {\nstatic const double kNanoSecondToSecond = 1e-9;\n\nstatic Eigen::Vector3d JNIFloatArrayToVector3d(JNIEnv* env, jfloatArray array) {\n  float tmp[3];\n  env->GetFloatArrayRegion(array, 0, 3, tmp);\n  const Eigen::Vector3d vec3(tmp[0], tmp[1], tmp[2]);\n  return vec3;\n}\n\nstatic Eigen::Matrix3d JNIFloatArrayToMatrix3d(JNIEnv* env, jfloatArray array) {\n  float tmp[9];\n  env->GetFloatArrayRegion(array, 0, 9, tmp);\n  return Eigen::Map<Eigen::Matrix3f>(tmp, 3, 3).cast<double>();\n}\n\ninline jlong jptr(OnlineSensorFusion* native_object) {\n  return reinterpret_cast<intptr_t>(native_object);\n}\n\ninline OnlineSensorFusion* native(jlong ptr) {\n  return reinterpret_cast<OnlineSensorFusion*>(ptr);\n}\n\n}  // namespace\n\nJNIEXPORT jlong JNICALL JNI_METHOD(nativeInit)(\n    JNIEnv* env, jobject obj, jfloatArray device_to_imu_transform) {\n  OnlineSensorFusion::Options options;\n  options.device_to_imu_transform =\n      JNIFloatArrayToMatrix3d(env, device_to_imu_transform);\n  return jptr(new OnlineSensorFusion(options));\n}\n\nJNIEXPORT void JNICALL JNI_METHOD(nativeRelease)(JNIEnv* env, jobject obj,\n                                                 jlong native_object) {\n  delete native(native_object);\n}\n\nJNIEXPORT void JNICALL JNI_METHOD(nativeAddGyroMeasurement)(\n    JNIEnv* env, jobject obj, jlong native_object, jfloatArray gyro,\n    jlong timestamp_ns) {\n  OnlineSensorFusion* filter = native(native_object);\n  if (filter == nullptr) {\n    return;\n  }\n  const auto gyro_vec3 = JNIFloatArrayToVector3d(env, gyro);\n  const double timestamp_s = timestamp_ns * kNanoSecondToSecond;\n  filter->AddGyroMeasurement(gyro_vec3, timestamp_s);\n}\n\nJNIEXPORT void JNICALL JNI_METHOD(nativeAddAccelMeasurement)(\n    JNIEnv* env, jobject obj, jlong native_object, jfloatArray accel,\n    jlong timestamp_ns) {\n  OnlineSensorFusion* filter = native(native_object);\n  if (filter == nullptr) {\n    return;\n  }\n  const auto accel_vec3 = JNIFloatArrayToVector3d(env, accel);\n  const double timestamp_s = timestamp_ns * kNanoSecondToSecond;\n  filter->AddAccelMeasurement(accel_vec3, timestamp_s);\n}\n\nJNIEXPORT jfloatArray JNICALL JNI_METHOD(nativeGetOrientation)(\n    JNIEnv* env, jobject obj, jlong native_object) {\n  OnlineSensorFusion* filter = native(native_object);\n  jfloatArray out = env->NewFloatArray(3);\n  if (filter == nullptr) {\n    return out;\n  }\n  Eigen::Vector3f v = filter->GetOrientation();\n  float carray[3] = {v[0], v[1], v[2]};\n  env->SetFloatArrayRegion(out, 0, 3, carray);\n  return out;\n}\n\nJNIEXPORT void JNICALL JNI_METHOD(nativeRecenter)(JNIEnv* env, jobject obj,\n                                                  jlong native_object) {\n  OnlineSensorFusion* filter = native(native_object);\n  if (filter == nullptr) {\n    return;\n  }\n  filter->Recenter();\n}\n\nJNIEXPORT void JNICALL JNI_METHOD(nativeSetGyroBias)(JNIEnv* env, jobject obj,\n                                                     jlong native_object,\n                                                     jfloatArray bias) {\n  OnlineSensorFusion* filter = native(native_object);\n  if (filter == nullptr) {\n    return;\n  }\n  const auto gyro_bias = JNIFloatArrayToVector3d(env, bias);\n  filter->SetGyroBias(gyro_bias);\n}\n}\n", "meta": {"hexsha": "50308e0c005c8f3886bc2fd3c6332c2ac412f9d9", "size": 4131, "ext": "cc", "lang": "C++", "max_stars_repo_path": "java/com/google/vr180/capture/motion/jni/sensor_fusion.cc", "max_stars_repo_name": "google/vr180", "max_stars_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-12-09T17:58:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T11:43:24.000Z", "max_issues_repo_path": "java/com/google/vr180/capture/motion/jni/sensor_fusion.cc", "max_issues_repo_name": "google/vr180", "max_issues_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T06:01:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T09:49:29.000Z", "max_forks_repo_path": "java/com/google/vr180/capture/motion/jni/sensor_fusion.cc", "max_forks_repo_name": "google/vr180", "max_forks_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-05-25T02:18:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:35:03.000Z", "avg_line_length": 32.023255814, "max_line_length": 80, "alphanum_fraction": 0.7145969499, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.19733961136178998}}
{"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#include <Eigen/Core>\n#include \"gtest/gtest.h\"\n\n#include \"bark/commons/params/setter_params.hpp\"\n#include \"bark/geometry/commons.hpp\"\n#include \"bark/geometry/line.hpp\"\n#include \"bark/geometry/polygon.hpp\"\n#include \"bark/models/dynamic/single_track.hpp\"\n#include \"bark/models/behavior/dynamic_model/dynamic_model.hpp\"\n#include \"bark/models/dynamic/single_track.hpp\"\n#include \"bark/models/dynamic/single_track_steering_rate.hpp\"\n#include \"bark/world/observed_world.hpp\"\n#include \"bark/world/tests/make_test_world.hpp\"\n\nusing namespace bark::models::dynamic;\nusing namespace bark::models::execution;\nusing namespace bark::commons;\nusing namespace bark::models::behavior;\nusing namespace bark::models::dynamic;\nusing namespace bark::world;\nusing namespace bark::geometry;\nusing namespace bark::world::tests;\nusing bark::geometry::standard_shapes::GenerateGoalRectangle;\n\nclass DummyObservedWorld : public ObservedWorld {\n public:\n  DummyObservedWorld(const State& init_state, const ParamsPtr& params, DynamicModelPtr dyn)\n      : ObservedWorld(std::make_shared<World>(params), AgentId(0)),\n        init_state_(init_state) {\n\n    auto agent = std::make_shared<Agent>(init_state, nullptr, dyn, nullptr,\n                                         Polygon(), params);\n    agent->SetAgentId(0);\n    AddAgent(agent);\n  }\n\n  virtual State CurrentEgoState() const { return init_state_; }\n\n  virtual double GetWorldTime() const { return 0.0; }\n\n private:\n  State init_state_;\n};\n\n\nTEST(behavior_motion_primitives_add, behavior_test) {\n  auto params = std::make_shared<SetterParams>();\n  BehaviorDynamicModel behavior(params);\n  Input u(2);\n  u << 0, 0;\n  behavior.ActionToBehavior(u);\n\n  // single track model\n  DynamicModelPtr dyn(new SingleTrackModel(params));\n  State init_state0(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state0 << 0.0, 0.0, 0.0, 0.0, 1.0;\n  DummyObservedWorld world0(init_state0, params, dyn);\n  behavior.ActionToBehavior(u);\n  Trajectory traj0 = behavior.Plan(0.5, world0);\n  EXPECT_NEAR(traj0(traj0.rows() - 1, StateDefinition::X_POSITION), 0.5, 0.1);\n  EXPECT_NEAR(traj0(traj0.rows() - 1, StateDefinition::Y_POSITION), 0.0, 0.1);\n\n\n  // test single track steering rate model\n  DynamicModelPtr dyn_steering_rate(new SingleTrackSteeringRateModel(params));\n  State init_state1(static_cast<int>(StateDefinition::MIN_STATE_SIZE) + 1);\n  init_state1 << 0.0, 0.0, 0.0, 0.0, 1.0, 0.0;\n  DummyObservedWorld world1(init_state1, params, dyn_steering_rate);\n  u << 0.5, 3.; // acceleration and steering-rate\n  behavior.ActionToBehavior(u);\n  Trajectory traj1 = behavior.Plan(0.5, world1);\n  EXPECT_NEAR(traj1(traj1.rows() - 1, StateDefinition::X_POSITION), 0.55, 0.1);\n  EXPECT_NEAR(traj1(traj1.rows() - 1, StateDefinition::X_POSITION), 0.52, 0.1);\n\n  // real BARK world\n  double ego_velocity = 5.0, rel_distance = 5.0,\n        velocity_difference = 4;\n  double time_step = 0.02f;\n  int num_steps = 1000;\n  Polygon polygon = GenerateGoalRectangle(6, 3);\n  std::shared_ptr<Polygon> goal_polygon(\n    std::dynamic_pointer_cast<Polygon>(polygon.Translate(Point2d(50, -2))));\n\n  auto goal_definition_ptr = std::make_shared<GoalDefinitionPolygon>(\n    *goal_polygon);\n\n  WorldPtr test_world = make_test_world(\n    1, rel_distance, ego_velocity, velocity_difference, goal_definition_ptr);\n\n  // set steering rate behavior model\n  // test_world->GetAgents()[0]->GetBehaviorModel() = behavior;\n\n}\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "90006507bf9f3e48993c2ae0c03398297ac62841", "size": 3750, "ext": "cc", "lang": "C++", "max_stars_repo_path": "bark/models/tests/behavior_dynamic_model_test.cc", "max_stars_repo_name": "xmyqsh/bark", "max_stars_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174.0, "max_stars_repo_stars_event_min_datetime": "2019-04-03T11:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T09:14:38.000Z", "max_issues_repo_path": "bark/models/tests/behavior_dynamic_model_test.cc", "max_issues_repo_name": "xmyqsh/bark", "max_issues_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 192.0, "max_issues_repo_issues_event_min_datetime": "2019-04-05T09:41:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T14:14:28.000Z", "max_forks_repo_path": "bark/models/tests/behavior_dynamic_model_test.cc", "max_forks_repo_name": "xmyqsh/bark", "max_forks_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2019-04-05T13:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T07:03:41.000Z", "avg_line_length": 35.046728972, "max_line_length": 91, "alphanum_fraction": 0.7341333333, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19733960880496657}}
{"text": "#include \"shape_reconstruction/ShapeReconstruction.h\"\n\n#include <pcl/conversions.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/filter_indices.h>\n#include <sensor_msgs/Image.h>\n\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/video/tracking.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/video/tracking.hpp>\n\n#include <pcl_conversions/pcl_conversions.h>\n\n#include <ros/package.h>\n\n#include <cmath>\n\n#include <ros/console.h>\n\n#include \"shape_reconstruction/RangeImagePlanar.hpp\"\n\n#include \"shape_reconstruction/Passthrough.hpp\"\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/filters/passthrough.h>\n\n#include <boost/lexical_cast.hpp>\n#include <sensor_msgs/image_encodings.h>\n\n#include <pcl/point_types_conversion.h>\n\n#include <pcl/registration/icp.h>\n\n#include <pcl/common/centroid.h>\n\n#include <pcl/surface/poisson.h>\n#include <pcl/surface/mls.h>\n\n#include <math.h>\n\nusing namespace omip;\n\nShapeReconstruction::ShapeReconstruction()\n    :\n      _accumulate_change_candidates(true),\n      _min_depth_change(0.08),\n      _remove_inconsistent_points(true),\n      _t(0),\n      _extend_to_neighbor_sv(false),\n      _acc_candidates_of_current(IMG_HEIGHT, IMG_WIDTH, CV_8UC1),\n      _similarity_in_normal(0),\n      _similarity_in_h(0)\n{\n    // Create auxiliary depth map image\n    this->_acc_candidates_of_current.setTo(0);\n\n    // Create range image planar object\n    this->_rip_temp = pcl::RangeImagePlanar::Ptr(new pcl::RangeImagePlanar());\n\n    // Create indices\n    this->_moving_pts_of_current_idx_depth = pcl::PointIndices::Ptr(new pcl::PointIndices ());\n    this->_moving_pts_of_previous_idx_depth = pcl::PointIndices::Ptr(new pcl::PointIndices ());\n    this->_out_of_view_pts_of_current_idx= pcl::PointIndices::Ptr(new pcl::PointIndices ());\n    this->_occluded_pts_of_current_idx= pcl::PointIndices::Ptr(new pcl::PointIndices ());\n\n    this->_moving_pts_of_current_idx_color = pcl::PointIndices::Ptr(new pcl::PointIndices ());\n    this->_moving_pts_of_previous_idx_color = pcl::PointIndices::Ptr(new pcl::PointIndices ());\n\n    this->_knn = pcl::search::Search<omip::SRPoint>::Ptr(new pcl::search::KdTree<omip::SRPoint>);\n\n    this->_rb_shape  =  omip::SRPointCloud::Ptr(new omip::SRPointCloud);\n    this->_rb_shape->height=1;\n\n    this->_supporting_features = pcl::PointCloud<pcl::PointXYZL>::Ptr(new pcl::PointCloud<pcl::PointXYZL>());\n\n    this->_candidates = SRPointCloud::Ptr(new SRPointCloud);\n    this->_candidates->height=1;\n\n    this->_candidates_in_current = SRPointCloud::Ptr(new SRPointCloud);\n\n    this->_rb_segment.reset(new SRPointCloud);\n\n    /// Mesh generation and storage as STL file\n    ///\n    /// For RB shape\n    this->_rb_polygon_data_ptr = vtkSmartPointer<vtkPolyData>::New ();\n    this->_rb_normal_estimator_ptr.reset(new pcl::NormalEstimationOMP<omip::SRPoint, pcl::Normal>());\n    this->_rb_normal_estimator_ptr->setKSearch (50);\n    this->_rb_estimated_normals_pc_ptr.reset(new pcl::PointCloud<pcl::Normal>());\n    this->_rb_tree_for_normal_estimation_ptr.reset(new pcl::search::KdTree<omip::SRPoint>());\n    this->_rb_position_color_and_normals_pc_ptr.reset(new pcl::PointCloud<pcl::PointXYZRGBNormal>());\n    this->_rb_tree_for_triangulation_ptr.reset(new pcl::search::KdTree<pcl::PointXYZRGBNormal>());\n    this->_rb_greedy_projection_triangulator_ptr.reset(new pcl::GreedyProjectionTriangulation<pcl::PointXYZRGBNormal>());\n    // Set typical values for the parameters\n    this->_rb_greedy_projection_triangulator_ptr->setMu (2.5);\n    this->_rb_greedy_projection_triangulator_ptr->setMaximumNearestNeighbors (100);\n    this->_rb_greedy_projection_triangulator_ptr->setMaximumSurfaceAngle(M_PI); // 180 degrees\n    this->_rb_greedy_projection_triangulator_ptr->setMinimumAngle(0.0); // 5 degrees\n    this->_rb_greedy_projection_triangulator_ptr->setMaximumAngle(M_PI); // 180 degrees\n    this->_rb_greedy_projection_triangulator_ptr->setNormalConsistency(true);\n    this->_rb_greedy_projection_triangulator_ptr->setConsistentVertexOrdering(true);\n    // Set the maximum distance between connected points (maximum edge length)\n    this->_rb_greedy_projection_triangulator_ptr->setSearchRadius (0.1);\n    this->_rb_polygon_writer_ptr = vtkSmartPointer<vtkSTLWriter>::New ();\n    this->_rb_polygon_writer_ptr->SetFileTypeToBinary();\n    this->_rb_triangulated_mesh_ptr.reset(new pcl::PolygonMesh());\n}\n\nvoid ShapeReconstruction::setInitialFullRGBDPCAndRBT(const SRPointCloud::Ptr &initial_pc_msg,\n                                                     const geometry_msgs::TwistWithCovariance &rb_transformation_initial)\n{\n    // Copy the initial point cloud\n    pcl::copyPointCloud(*initial_pc_msg, *this->_initial_ffs._pc);\n\n    // Get time stamp of the initial point cloud\n    this->_initial_ffs._time.fromNSec(initial_pc_msg->header.stamp);\n\n    // Clean the point cloud of nans\n    pcl::removeNaNFromPointCloud<SRPoint>(*this->_initial_ffs._pc,*this->_initial_ffs._pc_without_nans, this->_initial_ffs._not_nan_indices);\n\n    // Get the RGB image from the point cloud\n    pcl::toROSMsg (*initial_pc_msg, this->_initial_ffs._rgb); //convert the cloud\n\n    // Get the initial transformation\n    this->_initial_ffs._transformation = geometry_msgs::TwistWithCovariance(rb_transformation_initial);\n\n    // Get the depth map from the point cloud\n    OrganizedPC2DepthMap(this->_initial_ffs._pc, this->_initial_ffs._dm->image);\n\n    if(this->_depth_filling)\n    {\n        fillNaNsCBF(this->_initial_ffs._rgb, this->_initial_ffs._dm->image, this->_initial_ffs._dm_filled, this->_initial_ffs._time);\n    }\n}\n\nvoid ShapeReconstruction::initialize()\n{\n    std::stringstream pub_topic_name_ext_d_and_c;\n    pub_topic_name_ext_d_and_c << \"/shape_recons/shape_rb\" << this->_rb_id;\n    this->_rb_shape_pub = this->_node_handle.advertise<sensor_msgs::PointCloud2>(pub_topic_name_ext_d_and_c.str(), 1);\n\n    std::stringstream pub_segment_topic_name;\n    pub_segment_topic_name << \"/shape_recons/segment_rb\" << this->_rb_id;\n    this->_rb_segment_pub = this->_node_handle.advertise<sensor_msgs::PointCloud2>(pub_segment_topic_name.str(), 1);\n\n    std::stringstream pub_occlusion_topic_name;\n    pub_occlusion_topic_name << \"/shape_recons/pc_occlusions_rb\" << this->_rb_id;\n    this->_occlusions_pub = this->_node_handle.advertise<sensor_msgs::PointCloud2>(pub_occlusion_topic_name.str(), 1);\n\n    std::stringstream pub_occlusion_t_topic_name;\n    pub_occlusion_t_topic_name << \"/shape_recons/pc_occlusions_transf_rb\" << this->_rb_id;\n    this->_occlusions_transformed_pub = this->_node_handle.advertise<sensor_msgs::PointCloud2>(pub_occlusion_t_topic_name.str(), 1);\n\n    this->_approximate_voxel_grid_filter.setLeafSize(this->_leaf_size,\n                                                     this->_leaf_size,\n                                                     this->_leaf_size);\n\n    // This filter should delete single super voxels. If the properties of the super voxels\n    // change, or the leaf size of the voxel grid filter change, the radius and/or the min neighbors of\n    // the outlier removal should change\n    // set radius for neighbor search\n    this->_radius_outlier_removal.setRadiusSearch (this->_ror_radius_search);\n    // set threshold for minimum required neighbors neighbors\n    this->_radius_outlier_removal.setMinNeighborsInRadius (this->_ror_min_neighbors);\n\n    if(this->_record_videos)\n    {\n        std::string videos_path = ros::package::getPath(\"shape_reconstruction\") + std::string(\"/videos/\");\n\n        // create folder if does not exist\n        boost::filesystem::path videos_folder(videos_path);\n        if (!boost::filesystem::exists(videos_folder)) {\n            if (!boost::filesystem::create_directories(videos_folder)) {\n                ROS_ERROR_NAMED(\"ShapeReconstruction.ShapeReconstruction\", \"Output directory for video bag does not exist and cannot be created!\");\n                return;\n            }\n        }\n\n        this->_videos.open(videos_path + std::string(\"videos_rb\") + boost::lexical_cast<std::string>(this->_rb_id)+std::string(\".bag\"),rosbag::bagmode::Write);\n\n        sensor_msgs::ImagePtr initial_dm_msg;\n        DepthImage2CvImage(this->_initial_ffs._dm->image, initial_dm_msg);\n        this->_videos.write(\"original_dm\", this->_initial_ffs._time, initial_dm_msg);\n\n        if(this->_depth_filling)\n        {\n            sensor_msgs::ImagePtr initial_dm_filled_msg;\n            DepthImage2CvImage(this->_initial_ffs._dm_filled, initial_dm_filled_msg);\n            this->_videos.write(\"filled_dm\", this->_initial_ffs._time, initial_dm_filled_msg);\n        }\n    }\n}\n\nShapeReconstruction::ShapeReconstruction(const ShapeReconstruction &sr)\n{\n    ROS_ERROR_STREAM_NAMED(\"ShapeReconstruction.ShapeReconstruction\", \"Do not use this copy constructor! It is not complete!\");\n\n    this->_rb_id = sr._rb_id;\n\n    this->_to_initial = sr._to_initial;\n    this->_depth_filling = sr._depth_filling;\n\n    this->_initial_ffs = sr._initial_ffs.clone();\n    this->_previous_ffs = sr._previous_ffs.clone();\n    this->_current_ffs = sr._current_ffs.clone();\n\n    this->_rip_temp = pcl::RangeImagePlanar::Ptr(new pcl::RangeImagePlanar(*sr._rip_temp));\n\n    this->_moving_pts_of_current_idx_depth = pcl::PointIndices::Ptr(new pcl::PointIndices(*sr._moving_pts_of_current_idx_depth));\n    this->_moving_pts_of_previous_idx_depth = pcl::PointIndices::Ptr(new pcl::PointIndices(*sr._moving_pts_of_previous_idx_depth));\n    this->_out_of_view_pts_of_current_idx = pcl::PointIndices::Ptr(new pcl::PointIndices(*sr._out_of_view_pts_of_current_idx));\n    this->_occluded_pts_of_current_idx = pcl::PointIndices::Ptr(new pcl::PointIndices(*sr._occluded_pts_of_current_idx));\n\n}\n\nShapeReconstruction::~ShapeReconstruction()\n{\n    if(this->_record_videos)\n    {\n        _videos.close();\n    }\n}\n\nvoid ShapeReconstruction::setCameraInfo(const sensor_msgs::CameraInfo& camera_info)\n{\n    this->_ci = sensor_msgs::CameraInfo(camera_info);\n}\n\nvoid ShapeReconstruction::setFullRGBDPCandRBT(const SRPointCloud::Ptr &pc_msg,\n                                              const geometry_msgs::TwistWithCovariance &rb_transformation)\n{\n    ros::Time t1 = ros::Time::now();\n\n    _previous_k_indices.clear();\n    _current_k_indices.clear();\n    // t=0 means first point cloud AFTER initial received\n    ROS_WARN_STREAM_NAMED(\"ShapeReconstruction.setFullRGBDPCandRBT\", \"[RB\" << this->_rb_id << \"]: t = \" << _t);\n\n\n    if(this->_current_ffs._pc->points.size() > 0 )\n    {\n        this->_previous_ffs = this->_current_ffs;\n    }else{\n        this->_previous_ffs = this->_initial_ffs;\n    }\n    this->_current_ffs.reset();\n\n    ros::Time t2 = ros::Time::now();\n\n    pcl::copyPointCloud(*pc_msg, *this->_current_ffs._pc);\n\n    ros::Time t3 = ros::Time::now();\n\n    // Clean the point cloud of nans\n    this->_current_ffs._not_nan_indices.clear();\n    pcl::removeNaNFromPointCloud<SRPoint>(*this->_current_ffs._pc,*this->_current_ffs._pc_without_nans, this->_current_ffs._not_nan_indices);\n\n    ros::Time t4 = ros::Time::now();\n\n    ROS_WARN_STREAM_NAMED(\"ShapeReconstruction.setFullRGBDPCandRBT\", \"[RB\" << this->_rb_id << \"]: \" << \"Point cloud time stamp: \"\n                          <<this->_current_ffs._pc->header.stamp <<  \", not nan points \"\n                          << this->_current_ffs._not_nan_indices.size() << \"/\" << this->_current_ffs._pc_without_nans->size());\n\n\n    this->_current_ffs._time = pcl_conversions::fromPCL(pc_msg->header.stamp);\n    pcl::toROSMsg (*pc_msg, this->_current_ffs._rgb); //convert the cloud\n    this->_current_ffs._transformation = geometry_msgs::TwistWithCovariance(rb_transformation);\n\n    ros::Time t5 = ros::Time::now();\n\n    // Create a depth map from the current organized depth map\n    OrganizedPC2DepthMap(this->_current_ffs._pc, this->_current_ffs._dm->image);\n\n    ros::Time t6 = ros::Time::now();\n\n    // -----------------------------------------------------------\n    // main algorithm\n\n    if(this->_depth_filling)\n    {\n        fillNaNsCBF(this->_current_ffs._rgb, this->_current_ffs._dm->image, this->_current_ffs._dm_filled, this->_current_ffs._time);\n        this->_current_ffs._dm->image.copyTo(this->_current_ffs._dm_filled, this->_current_ffs._dm->image == this->_current_ffs._dm->image);\n    }\n\n    ros::Time t7 = ros::Time::now();\n\n    if(this->_record_videos)\n    {\n        sensor_msgs::ImagePtr current_dm_msg;\n        DepthImage2CvImage(this->_current_ffs._dm->image, current_dm_msg);\n        this->_videos.write(\"original_dm\", this->_current_ffs._time, current_dm_msg);\n\n        if(this->_depth_filling)\n        {\n            sensor_msgs::ImagePtr current_dm_filled_msg;\n            DepthImage2CvImage(this->_current_ffs._dm_filled, current_dm_filled_msg);\n            this->_videos.write(\"filled_dm\", this->_current_ffs._time, current_dm_filled_msg);\n        }\n    }\n\n    // Segmentation method 1: motion segmentation based on DEPTH (memoryless)\n    this->_DetectImageLocationsWhereDepthChanges();\n    ros::Time t8 = ros::Time::now();\n    this->_TestMotionCoherencyOfPointsInImageLocationsWhereDepthChanged();\n    ros::Time t9 = ros::Time::now();\n\n    // Segmentation method 2: motion segmentation based on COLOR (memoryless)\n    this->_DetectImageLocationsWhereColorChanges();\n    ros::Time t10 = ros::Time::now();\n    this->_TestMotionCoherencyOfPointsInImageLocationsWhereColorChanged();\n    ros::Time t11 = ros::Time::now();\n\n    // Merge the segmentation results into the model(s)\n    this->_MergeValidPointsIntoModels();\n\n    ros::Time t12 = ros::Time::now();\n\n    this->_RemoveInconsistentPointsFromModelsAndExtendToRegions();\n\n    ros::Time t12b = ros::Time::now();\n\n    this->_FilterModel();\n\n    ros::Time t13 = ros::Time::now();\n\n    _t++;\n\n//    std::cout << \"Preprocessing: \" << (t7-t1).toSec() << std::endl;\n//    std::cout << \"Depth-based segmentation: \" << (t9-t7).toSec() << std::endl;\n//    std::cout << \"Color-based segmentation: \" << (t11-t9).toSec() << std::endl;\n//    std::cout << \"Remove inconsistent points and extend to regions: \" << (t12b-t12).toSec() << std::endl;\n//    std::cout << \"Filter model: \" << (t13-t12b).toSec() << std::endl;\n//    std::cout << \"Total processing RGBD frame (one RB): \" << (t13-t1).toSec() << std::endl;\n}\n\nvoid ShapeReconstruction::_DetectImageLocationsWhereDepthChanges()\n{\n    // Find the difference\n    if(this->_depth_filling)\n    {\n        this->_difference_in_depth = this->_current_ffs._dm_filled - this->_previous_ffs._dm_filled;\n    }else{\n        this->_difference_in_depth = this->_current_ffs._dm->image - this->_previous_ffs._dm->image;\n    }\n\n    if(this->_record_videos)\n    {\n        sensor_msgs::ImagePtr dm_msg;\n        DepthImage2CvImage(_difference_in_depth, dm_msg);\n        this->_videos.write(\"changes_in_depth\", this->_current_ffs._time, dm_msg);\n    }\n\n\n    // If the difference is negative (under some threshold) that means that the object occludes now what was behind and visible before\n    // This part of the CURRENT depth map (of the CURRENT point cloud) should be added to the candidates of the RB\n    cv::threshold(this->_difference_in_depth, this->_candidates_of_current, -_min_depth_change, 255, cv::THRESH_BINARY_INV);\n\n    if(this->_record_videos)\n    {\n        sensor_msgs::ImagePtr dm_msg;\n        DepthImage2CvImage(_candidates_of_current, dm_msg);\n        this->_videos.write(\"candidates_of_current\", this->_current_ffs._time, dm_msg);\n    }\n\n    // If the difference is positive (over some threshold) that means that the object is now not occluding what it was occluding before\n    // This part of the PREVIOUS depth map (of the PREVIOUS point cloud) should be added to the candidates of the RB\n    cv::threshold(this->_difference_in_depth, this->_candidates_of_previous, _min_depth_change, 255, cv::THRESH_BINARY);\n\n    if(this->_record_videos)\n    {\n        sensor_msgs::ImagePtr dm_msg;\n        DepthImage2CvImage(_candidates_of_previous, dm_msg);\n        this->_videos.write(\"candidates_of_previous\", this->_current_ffs._time, dm_msg);\n    }\n\n    this->_previous_depth_mask = this->_previous_ffs._dm->image > 1.5 | this->_previous_ffs._dm->image < 0.3 | this->_previous_ffs._dm->image != this->_previous_ffs._dm->image;\n    this->_current_depth_mask = this->_current_ffs._dm->image > 1.5 | this->_current_ffs._dm->image < 0.3 | this->_current_ffs._dm->image != this->_current_ffs._dm->image;\n\n    this->_candidates_of_current.convertTo(this->_candidates_of_current_8u, CV_8U);\n    this->_candidates_of_previous.convertTo(this->_candidates_of_previous_8u, CV_8U);\n\n    // accumulate candidates\n    this->_acc_candidates_of_current = _acc_candidates_of_current | this->_candidates_of_current_8u;\n    this->_acc_candidates_of_current.setTo(0,this->_candidates_of_previous_8u);\n\n    if(this->_record_videos)\n    {\n        sensor_msgs::ImagePtr dm_msg;\n        DepthImage2CvImage(_acc_candidates_of_current, dm_msg);\n        this->_videos.write(\"acc_candidates_of_current\", this->_current_ffs._time, dm_msg);\n    }\n\n    if (!this->_depth_filling)\n    {\n        ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._DetectImageLocationsWhereDepthChanges\",  \"[RB\" << this->_rb_id << \"]: Removing nan points from accumulator\");\n        this->_acc_candidates_of_current.setTo(0, this->_current_ffs._dm->image != this->_current_ffs._dm->image);\n    }\n\n    if(this->_accumulate_change_candidates)\n    {\n        this->_acc_candidates_of_current.copyTo(this->_candidates_of_current_8u);\n    }\n\n    this->_candidates_of_current_8u.setTo(0, this->_current_depth_mask);\n    this->_candidates_of_previous_8u.setTo(0, this->_previous_depth_mask);\n\n    this->_moving_pts_of_current_idx_depth->indices.clear();\n    this->_moving_pts_of_previous_idx_depth->indices.clear();\n\n    Image8u2Indices(this->_candidates_of_current_8u, this->_moving_pts_of_current_idx_depth);\n    Image8u2Indices(this->_candidates_of_previous_8u, this->_moving_pts_of_previous_idx_depth);\n}\n\nvoid ShapeReconstruction::_TestMotionCoherencyOfPointsInImageLocationsWhereDepthChanged()\n{\n    // Estimate the transformations from the twists\n    this->_EstimateTransformations();\n\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._TestMotionCoherencyOfPointsInImageLocationsWhereDepthChanged\",\n                          \"[RB\" << this->_rb_id << \"]: Estimating which of the points that changed DEPTH moved coherently with the RB motion.\");\n\n    // Filter the previous point cloud, transform only the filtered points and find the nearest neighbors in the current point cloud\n    this->_sqrt_dist.clear();\n    this->_FindCandidatesInPreviousPC(this->_previous_ffs,\n                                      this->_current_ffs,\n                                      this->_moving_pts_of_previous_idx_depth,\n                                      this->_current_to_previous_HTransform,\n                                      this->_current_k_indices,\n                                      this->_sqrt_dist);\n\n    // Filter the current point cloud, transform only the filtered points and find the nearest neighbors in the previous point cloud\n    this->_sqrt_dist.clear();\n    this->_FindCandidatesInCurrentPC(this->_previous_ffs,\n                                     this->_current_ffs,\n                                     this->_moving_pts_of_current_idx_depth,\n                                     this->_previous_to_current_HTransform,\n                                     this->_previous_k_indices,\n                                     this->_sqrt_dist);\n\n    std::vector<int > invalid_indices;\n    // Add the valid points of the current point cloud to the model\n    for (unsigned int i = 0; i < _previous_k_indices.size(); i++)\n    {\n        if (_previous_k_indices[i].size() == 0)\n        {\n            invalid_indices.push_back(_moving_pts_of_current_idx_depth->indices.at(i));\n        }\n    }\n\n    cv::Mat not_coherent_points = cv::Mat(IMG_HEIGHT, IMG_WIDTH, CV_8UC1);\n    Indices2Image8u(invalid_indices, not_coherent_points);\n\n    this->_acc_candidates_of_current.setTo(0, not_coherent_points);\n}\n\n//#define DISPLAY_IMAGES_DILWCC\nvoid ShapeReconstruction::_DetectImageLocationsWhereColorChanges()\n{\n    // Create matrices\n    cv::Mat current_hsv_image, current_h_channel, current_s_channel, current_v_channel;\n    cv::Mat previous_hsv_image, previous_h_channel, previous_s_channel, previous_v_channel;\n    cv::Mat difference_h_channel, circular_difference_h_channel, thresholded_difference_h_channel, difference_h_channel_wo_black, thresholded_difference_h_channel_wo_black;\n\n    // Convert ROS msg to opencv\n    cv_bridge::CvImagePtr previous_rgb_cv;\n    previous_rgb_cv = cv_bridge::toCvCopy(this->_previous_ffs._rgb);\n\n    cv_bridge::CvImagePtr current_rgb_cv;\n    current_rgb_cv = cv_bridge::toCvCopy(this->_current_ffs._rgb);\n\n#ifdef DISPLAY_IMAGES_DILWCC\n    // Display original color images\n    cv::imshow(\"color current\", current_rgb_cv->image);\n    cv::imshow(\"color previous\", previous_rgb_cv->image);\n#endif\n\n    // Convert color to HSV images\n    cv::cvtColor(previous_rgb_cv->image, previous_hsv_image, CV_BGR2HSV);\n    cv::cvtColor(current_rgb_cv->image, current_hsv_image, CV_BGR2HSV);\n\n    // Smooth images\n    //cv::GaussianBlur(previous_hsv_image, previous_hsv_image,cv::Size(5,5), 0,0);\n    //cv::GaussianBlur(current_hsv_image, current_hsv_image,cv::Size(5,5), 0,0);\n\n    // Extract channels\n    cv::extractChannel(current_hsv_image,current_h_channel,0);\n    cv::extractChannel(current_hsv_image,current_s_channel,1);\n    cv::extractChannel(current_hsv_image,current_v_channel,2);\n\n    cv::extractChannel(previous_hsv_image,previous_h_channel,0);\n    cv::extractChannel(previous_hsv_image,previous_s_channel,1);\n    cv::extractChannel(previous_hsv_image,previous_v_channel,2);\n\n    // Difference of hue -> HUE values are between 0 and 179 and represent the angle\n    // of a cylindrical coordinates system. That implies that 180=0.\n    cv::absdiff(current_h_channel,  previous_h_channel, difference_h_channel );\n    circular_difference_h_channel = 180.0 - difference_h_channel;\n    circular_difference_h_channel.copyTo(difference_h_channel, difference_h_channel >89);\n\n#ifdef DISPLAY_IMAGES_DILWCC\n    // Show difference of HUE\n    cv::imshow(\"Circular difference of HUE\", difference_h_channel);\n#endif\n\n    // We do not consider pixels that change between different black hue colors, because black identification if really bad\n    difference_h_channel.copyTo(difference_h_channel_wo_black);\n    //difference_h_channel_wo_black.setTo(cv::Scalar(0), current_s_channel < 90 & current_v_channel < 50 & previous_s_channel < 90 & previous_v_channel < 50);\n    difference_h_channel_wo_black.setTo(cv::Scalar(0), current_s_channel < 90 | previous_s_channel < 90 );\n\n#ifdef DISPLAY_IMAGES_DILWCC\n    // Show pixels with low saturation or value\n    cv::imshow(\"Low current_s_channel\", current_s_channel < 90);\n    //cv::imshow(\"Low current_v_channel\", current_v_channel < 10);\n    cv::imshow(\"Low previous_s_channel\", previous_s_channel < 90);\n    //cv::imshow(\"Low previous_v_channel\", previous_v_channel < 10);\n#endif\n\n    // Threshold the circular hue difference to find points that change enough\n    cv::threshold(difference_h_channel, thresholded_difference_h_channel, 20, 255, cv::THRESH_BINARY);\n\n#ifdef DISPLAY_IMAGES_DILWCC\n    cv::imshow(\"Thresholded circular difference of HUE\", thresholded_difference_h_channel);\n#endif\n\n    // Threshold the circular hue difference without black pixels to find points that change enough\n    cv::threshold(difference_h_channel_wo_black, thresholded_difference_h_channel_wo_black, 15, 255, cv::THRESH_BINARY);\n\n#ifdef DISPLAY_IMAGES_DILWCC\n    cv::imshow(\"Thresholded circular difference of HUE without black pixels\", thresholded_difference_h_channel_wo_black);\n#endif\n\n    cv::Mat thresholded_difference_h_channel_wo_black_wo_noisy_pixels;\n    int openning_size = 1;\n    // Element: 0: Rect - 1: Cross - 2: Ellipse\n    int openning_element_type = 2;\n    cv::Mat openning_element = cv::getStructuringElement( openning_element_type, cv::Size( 2*openning_size + 1, 2*openning_size+1 ), cv::Point( openning_size, openning_size ) );\n    cv::morphologyEx(thresholded_difference_h_channel_wo_black, thresholded_difference_h_channel_wo_black_wo_noisy_pixels, cv::MORPH_OPEN, openning_element);\n\n#ifdef DISPLAY_IMAGES_DILWCC\n    cv::imshow(\"Thresholded circular difference of HUE without black pixels nor NOISY pixels\", thresholded_difference_h_channel_wo_black_wo_noisy_pixels);\n#endif\n\n    // We use color to detect things that move and do not change depth. Therefore, we set to zero\n    // points that changed their color AND their depth\n    cv::Mat changing_depth_points;\n    if(this->_depth_filling)\n    {\n        cv::absdiff(this->_current_ffs._dm_filled, this->_previous_ffs._dm_filled, changing_depth_points);\n    }else{\n        cv::absdiff(this->_current_ffs._dm->image, this->_previous_ffs._dm->image, changing_depth_points);\n    }\n\n    // The mask of moving points in current frame are the points that changed color and that are valid\n    cv::Mat motion_mask_current= thresholded_difference_h_channel_wo_black_wo_noisy_pixels.clone();\n    motion_mask_current.setTo(cv::Scalar(0), this->_current_depth_mask);\n\n    // The mask of moving points in previous frame are the points that changed color and that are valid\n    cv::Mat motion_mask_previous = thresholded_difference_h_channel_wo_black_wo_noisy_pixels.clone();\n    motion_mask_previous.setTo(cv::Scalar(0), this->_previous_depth_mask);\n\n#ifdef DISPLAY_IMAGES_DILWCC\n    cv::imshow(\"Current color candidates\", motion_mask_current);\n    cv::imshow(\"Previous color candidates\", motion_mask_previous);\n#endif\n\n#ifdef DISPLAY_IMAGES_DILWCC\n    cv::waitKey(-1);\n#endif\n\n    Image8u2Indices(motion_mask_current, this->_moving_pts_of_current_idx_color);\n    Image8u2Indices(motion_mask_previous, this->_moving_pts_of_previous_idx_color);\n\n    if(this->_record_videos)\n    {\n        _videos.write(\"original_color\",ros::Time::now(), current_rgb_cv->toImageMsg());\n        sensor_msgs::ImagePtr dm_msg;\n        DepthImage2CvImage(thresholded_difference_h_channel, dm_msg);\n        this->_videos.write(\"changes_in_color\", this->_current_ffs._time, dm_msg);\n    }\n}\n\nvoid ShapeReconstruction::_TestMotionCoherencyOfPointsInImageLocationsWhereColorChanged()\n{\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._TestMotionCoherencyOfPointsInImageLocationsWhereColorChanged\",\n                          \"[RB\" << this->_rb_id << \"]: Estimating which of the points that changed COLOR moved coherently with the RB motion.\");\n\n    // Filter the previous point cloud, transform only the filtered points and find the nearest neighbors in the current point cloud\n    this->_FindCandidatesInPreviousPC(this->_previous_ffs,\n                                      this->_current_ffs,\n                                      this->_moving_pts_of_previous_idx_color,\n                                      this->_current_to_previous_HTransform,\n                                      this->_current_k_indices,\n                                      this->_sqrt_dist);\n\n    // Filter the current point cloud, transform only the filtered points and find the nearest neighbors in the previous point cloud\n    this->_FindCandidatesInCurrentPC(this->_previous_ffs,\n                                     this->_current_ffs,\n                                     this->_moving_pts_of_current_idx_color,\n                                     this->_previous_to_current_HTransform,\n                                     this->_previous_k_indices,\n                                     this->_sqrt_dist);\n}\n\nvoid ShapeReconstruction::_FindCandidatesInPreviousPC(FrameForSegmentation& _previous_ffs,\n                                                      const FrameForSegmentation& _current_ffs,\n                                                      pcl::PointIndices::Ptr& _moving_pts_of_previous_idx,\n                                                      Eigen::Matrix4d& _current_to_previous_HTransform,\n                                                      std::vector<std::vector<int > >& _previous_k_indices,\n                                                      std::vector<std::vector<float > >& _previous_sqrt_dist)\n{\n    _previous_ffs._pc_moving_pts =  omip::SRPointCloud::Ptr(new omip::SRPointCloud);\n    this->_extractor.setInputCloud(_previous_ffs._pc);\n    this->_extractor.setIndices(_moving_pts_of_previous_idx);\n    this->_extractor.setNegative(false);\n    this->_extractor.filter(*_previous_ffs._pc_moving_pts);\n\n    std::vector<std::vector<int > > previous_k_indices;\n    if(_previous_ffs._pc_moving_pts->points.size())\n    {\n        pcl::transformPointCloud<SRPoint>(*_previous_ffs._pc_moving_pts, *_previous_ffs._pc_moving_pts_transf, _current_to_previous_HTransform.cast<float>());\n\n        this->_knn->setInputCloud(_current_ffs._pc_without_nans);\n        std::vector<int> empty;\n\n        this->_knn->radiusSearch(*_previous_ffs._pc_moving_pts_transf, empty, this->_knn_min_radius, previous_k_indices, _previous_sqrt_dist);\n\n        ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._FindCandidatesInPreviousPC\", \"[RB\" << this->_rb_id << \"]: After radius search for finding candidates in previous PC. Queries: \"\n                              << _previous_ffs._pc_moving_pts_transf->points.size() );\n\n    }\n\n    _previous_k_indices.insert(_previous_k_indices.end(), previous_k_indices.begin(), previous_k_indices.end());\n}\n\nvoid ShapeReconstruction::_FindCandidatesInCurrentPC(const FrameForSegmentation& _previous_ffs,\n                                                     FrameForSegmentation& _current_ffs,\n                                                     pcl::PointIndices::Ptr& _moving_pts_of_current_idx,\n                                                     Eigen::Matrix4d& _previous_to_current_HTransform,\n                                                     std::vector<std::vector<int > >& _current_k_indices,\n                                                     std::vector<std::vector<float > >& _current_sqrt_dist)\n{\n    _current_ffs._pc_moving_pts =  omip::SRPointCloud::Ptr(new omip::SRPointCloud);\n    this->_extractor.setInputCloud(_current_ffs._pc);\n    this->_extractor.setIndices(_moving_pts_of_current_idx);\n    this->_extractor.setNegative(false);\n    this->_extractor.filter(*_current_ffs._pc_moving_pts);\n\n    std::vector<std::vector<int > > current_k_indices;\n    if(_current_ffs._pc_moving_pts->points.size())\n    {\n        pcl::transformPointCloud<SRPoint>(*_current_ffs._pc_moving_pts, *_current_ffs._pc_moving_pts_transf, _previous_to_current_HTransform.cast<float>());\n\n        this->_knn->setInputCloud(_previous_ffs._pc_without_nans);\n\n        std::vector<int> empty;\n        this->_knn->radiusSearch(*_current_ffs._pc_moving_pts_transf, empty, this->_knn_min_radius, current_k_indices, _current_sqrt_dist);\n\n        ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._FindCandidatesInPreviousPC\", \"[RB\" << this->_rb_id << \"]: After radius search for finding candidates in current PC. Queries: \"\n                              << _current_ffs._pc_moving_pts_transf->points.size() );\n    }\n\n    _current_k_indices.insert(_current_k_indices.end(), current_k_indices.begin(), current_k_indices.end());\n}\n\n\nvoid ShapeReconstruction::_MergeValidPointsIntoModels()\n{\n    // We create these transformed point clouds in the general function to avoid repeating it in the subfunctions\n\n    // Transform the points of the current point cloud that belong to the model to the object frame (corresponds to the frame of the first point cloud)\n    omip::SRPointCloud::Ptr points_of_current_in_origin(new omip::SRPointCloud);\n    pcl::transformPointCloud<SRPoint>(*this->_current_ffs._pc_without_nans, *points_of_current_in_origin, this->_current_HTransform_inv.cast<float>());\n\n    // Transform the points of the previous point cloud that belong to the model into the object frame (corresponds to the frame of the first point cloud)\n    omip::SRPointCloud::Ptr points_of_previous_in_origin(new omip::SRPointCloud);\n    pcl::transformPointCloud<SRPoint>(*this->_previous_ffs._pc_without_nans, *points_of_previous_in_origin, this->_previous_HTransform_inv.cast<float>());\n\n    //Now we have all the indices together\n    _MergeValidPointsIntoModels(\"DEPTHANDCOLOR\",\n                                    points_of_current_in_origin,\n                                    points_of_previous_in_origin,\n                                    this->_rb_shape,\n                                    this->_current_k_indices,\n                                    this->_previous_k_indices);\n\n    this->_candidates->points.clear();\n    this->_candidates->width = 0;\n}\n\nvoid ShapeReconstruction::_MergeValidPointsIntoModels(const std::string& logger_name,\n                                                      omip::SRPointCloud::Ptr& points_of_current_in_origin,\n                                                      omip::SRPointCloud::Ptr& points_of_previous_in_origin,\n                                                      omip::SRPointCloud::Ptr& rb_model,\n                                                      const std::vector<std::vector<int > >& current_k_indices,\n                                                      const std::vector<std::vector<int > >& previous_k_indices)\n{\n    int model_size_before_adding = rb_model->width;\n\n    // Add the valid points of the current point cloud to the model\n    for (unsigned int i = 0; i < current_k_indices.size(); i++) {\n        if (current_k_indices[i].size() > 0){\n            rb_model->points.push_back(points_of_current_in_origin->points[current_k_indices[i].at(0)]);\n            rb_model->width++;\n        }\n    }\n\n    // Add the valid points of the previous point cloud to the model\n    for (unsigned int i = 0; i < previous_k_indices.size(); i++) {\n        if (previous_k_indices[i].size() > 0){\n            rb_model->points.push_back(points_of_previous_in_origin->points[previous_k_indices[i].at(0)]);\n            rb_model->width++;\n        }\n    }\n\n    int number_of_points_added = rb_model->width - model_size_before_adding;\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._MergeValidPointsIntoModels\", \"[RB\" << this->_rb_id << \"] \"\n                          << \": Added \" << number_of_points_added << \" points to the model based on changes in \" << logger_name);\n}\n\nvoid ShapeReconstruction::_RemoveInconsistentPointsFromModelsAndExtendToRegions()\n{\n    // clean up models by removing points inconsistent with the current view\n    this->_RemoveInconsistentPointsFromRBModel(\"BeforeExtendingToRegions\", this->_current_HTransform,\n                                               this->_rb_shape,this->_current_ffs._dm->image,this->_current_ffs._pc,this->_rb_segment);\n\n    if(_estimate_supervoxels)\n    {\n        // After cleaning up the models we extend to regions\n        this->_ExtendPointsToRegions();\n\n        this->_RemoveInconsistentPointsFromRBModel(\"AfterExtendingToRegions\", this->_current_HTransform,\n                                                   this->_rb_shape,this->_current_ffs._dm->image,this->_current_ffs._pc,this->_rb_segment);\n    }\n}\n\nvoid ShapeReconstruction::_FilterModel()\n{\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._FilterModel\", \"[RB\" << this->_rb_id << \"]: Before approximate voxel grid filter. Num of points: \"\n                           << this->_rb_shape->points.size() );\n    this->_approximate_voxel_grid_filter.setInputCloud (this->_rb_shape);\n    this->_approximate_voxel_grid_filter.filter (*this->_rb_shape);\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._FilterModel\", \"[RB\" << this->_rb_id << \"]: After approximate voxel grid filter. Num of points: \"\n                           << this->_rb_shape->points.size() );\n\n    // Apply the outlier removal filter to keep the model clean of small noisy clusters\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._FilterModel\", \"[RB\" << this->_rb_id << \"] \" << \": Before outlier removal. Num of points: \"\n                          << this->_rb_shape->points.size() );\n    this->_radius_outlier_removal.setInputCloud(this->_rb_shape);\n    this->_radius_outlier_removal.filter (*this->_rb_shape);\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._FilterModel\", \"[RB\" << this->_rb_id << \"] \" << \": After outlier removal. Num of points: \"\n                          << this->_rb_shape->points.size() );\n\n}\n\nvoid ShapeReconstruction::_RemoveInconsistentPointsFromRBModel(const std::string logger_name,\n                                                               const Eigen::Matrix4d& HTransform,\n                                                               SRPointCloud::Ptr& rb_shape,\n                                                               cv::Mat& current_dm,\n                                                               SRPointCloud::Ptr current_pc,\n                                                               SRPointCloud::Ptr& rb_segment)\n{\n    // are self-occlusions handled?\n    // yes they should be accounted for implicitly because if the \"front\" & the \"back\" are in the model, only\n    // the front (which should be visible in current) will be projected to rb_rip.\n\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._RemoveInconsistentPointsFromRBModel\", \"[RB\" << this->_rb_id << \"] \" << logger_name <<\n                          \": Removing inconsistent points\");\n\n    // move the rb_shape into the current frame\n    omip::SRPointCloud::Ptr rb_shape_current(new omip::SRPointCloud);\n    pcl::transformPointCloud<SRPoint>(*rb_shape, *rb_shape_current, HTransform.cast<float>());\n\n    // move the rb_shape into the current frame (new variant)\n    omip::SRPointCloud::Ptr rb_shape_current_new(new omip::SRPointCloud);\n    *rb_shape_current_new = *rb_shape_current;\n\n    std::stringstream rb_id_str;\n    rb_id_str << _rb_id;\n\n    pcl::PointIndicesPtr indices_to_remove(new pcl::PointIndices);\n\n    // these are the points in the current image that are consistent\n    // with the model -> the actual segment in the image\n    pcl::PointIndicesPtr indices_matching_in_model(new pcl::PointIndices);\n    pcl::PointIndicesPtr indices_matching_in_current(new pcl::PointIndices);\n\n    // find points that are inconsistent between moved rb_shape\n    // and current depth image\n    _FindInconsistentPoints(rb_shape_current_new, current_dm, // input\n                               indices_to_remove, // output\n                               indices_matching_in_model, // output\n                               indices_matching_in_current // output\n                               );\n\n    // remove indices\n    SRPointCloud::Ptr rb_new_clean(new SRPointCloud);\n    if (_remove_inconsistent_points)\n    {\n        // move the rb_shape into the current frame\n        this->_extractor.setNegative(true);\n        this->_extractor.setInputCloud(rb_shape);\n        this->_extractor.setIndices(indices_to_remove);\n        this->_extractor.setKeepOrganized(false);\n        this->_extractor.filter(*rb_new_clean);\n    } else {\n        indices_to_remove->indices.clear();\n    }\n\n    // create segment (always in current frame)\n    SRPointCloud::Ptr rb_segment_new(new SRPointCloud);\n    this->_extractor.setNegative(false);\n    this->_extractor.setInputCloud(current_pc);\n    this->_extractor.setIndices(indices_matching_in_current);\n    this->_extractor.setKeepOrganized(true);\n    this->_extractor.filter(*rb_segment_new);\n    this->_extractor.setKeepOrganized(false);\n\n    cv::Mat rb_segment_new_dm(IMG_HEIGHT, IMG_WIDTH, CV_32FC1);\n    OrganizedPC2DepthMap(rb_segment_new, rb_segment_new_dm);\n\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._RemoveInconsistentPointsAndComputeSegment\", \"[RB\" << this->_rb_id << \"] \" << logger_name << \":\" << std::endl\n                          << \"\\tPoints of the original model: \" << rb_shape->points.size() << \",\" << std::endl\n                          << \"\\tPoints matching in model: \" << indices_matching_in_model->indices.size() << \",\" << std::endl\n                          << \"\\tPoints matching in model: \" << rb_new_clean->points.size()  << \",\" << std::endl\n                          << \"\\tPoints matching in current point cloud: \" << indices_matching_in_current->indices.size() << std::endl\n                          << \"\\tPoints removed: \" << indices_to_remove->indices.size() << (indices_to_remove->indices.empty() ? \" (NO POINTS REMOVED) \" : \"\")\n                          );\n\n    if (_remove_inconsistent_points)\n    {\n        rb_shape = rb_new_clean;\n    }\n    rb_segment = rb_segment_new;\n}\n\nvoid ShapeReconstruction::_FindInconsistentPoints(const omip::SRPointCloud::Ptr& pc_source,\n                                                     const cv::Mat & dm_true,\n                                                     pcl::PointIndicesPtr& indices_to_remove,\n                                                     pcl::PointIndicesPtr& indices_matching_in_true,\n                                                     pcl::PointIndicesPtr& indices_matching_in_dm,\n                                                     const double min_depth_error) {\n\n    indices_to_remove->indices.clear();\n\n    using ::shape_reconstruction::RangeImagePlanar;\n    RangeImagePlanar::Ptr dm_source_rip(new RangeImagePlanar);\n\n    Eigen::Affine3f sensor_pose;\n    sensor_pose.matrix() = Eigen::Matrix4f::Identity(); // this->_current_HTransform_inv.cast<float>();\n    pcl::RangeImagePlanar::CoordinateFrame coordinate_frame = pcl::RangeImagePlanar::CAMERA_FRAME;\n\n    int width = dm_true.cols, height = dm_true.rows;\n    dm_source_rip->matchPointCloudAndImage (\n                *pc_source,\n                width,\n                height,\n                this->_ci.P[2], //width/2 -0.5, //319.5, // 329.245223575443,\n            this->_ci.P[6], //height/2 - 0.5, // 239.5, //  239.458\n            this->_ci.P[0], // fx\n            this->_ci.P[5], // fy\n            sensor_pose,\n            coordinate_frame,\n            dm_true,\n            min_depth_error,\n            indices_matching_in_true,\n            indices_matching_in_dm,\n            indices_to_remove\n            );\n\n}\n\nvoid ShapeReconstruction::growSVRecursively(uint32_t label_sv_seed,\n                                            std::vector<uint32_t>& labels_extension,\n                                            std::multimap<uint32_t, uint32_t>& supervoxel_adjacency,\n                                            std::vector<uint32_t>& sv_containing_supporting_features,\n                                            int& distance_to_feature_sv,\n                                            std::map<uint32_t, std::unordered_set<int> >& labels_of_segments_to_extend)\n{\n    std::pair< std::multimap<uint32_t, uint32_t>::iterator, std::multimap<uint32_t, uint32_t>::iterator > neighbors;\n\n    // Get the adjacency map of the sv\n    neighbors =supervoxel_adjacency.equal_range(label_sv_seed);\n\n    // Iterate over the pairs of sv-neighbor\n    for(std::multimap<uint32_t, uint32_t>::iterator neighbor_it = neighbors.first; neighbor_it!= neighbors.second; ++neighbor_it)\n    {\n        bool add_neighbor = false;\n        // Check if the neighbor sv was already added\n        if(std::find(labels_extension.begin(), labels_extension.end(), neighbor_it->second)  != labels_extension.end())\n        {\n            add_neighbor = false;\n        }else{\n            // Check if the neighbor sv should be added\n            // if it contains a feature OR if (it contains enough points that changed (color OR depth) AND the distance to a feature-containing SV is small)\n            if(std::find(sv_containing_supporting_features.begin(), sv_containing_supporting_features.end(), neighbor_it->second)  != sv_containing_supporting_features.end())\n            {\n                add_neighbor = true;\n                distance_to_feature_sv = 0;\n            }else{\n                std::map<uint32_t, std::unordered_set<int> >::iterator set_it = labels_of_segments_to_extend.find(neighbor_it->second);\n                if(set_it != labels_of_segments_to_extend.end())\n                {\n                    if(set_it->second.size() > this->_min_number_model_pixels_in_sv)\n                    {\n                        if(distance_to_feature_sv <= 2)\n                        {\n                            add_neighbor = true;\n                            distance_to_feature_sv++;\n                        }\n                    }\n                }\n\n            }\n        }\n\n        if(add_neighbor)\n        {\n            labels_extension.push_back(neighbor_it->second);\n            growSVRecursively(neighbor_it->second,\n                              labels_extension,\n                              supervoxel_adjacency,\n                              sv_containing_supporting_features,\n                              distance_to_feature_sv,\n                              labels_of_segments_to_extend);\n        }\n    }\n}\n\nvoid ShapeReconstruction::_ExtendPointsToRegions()\n{\n    std::vector<uint32_t> labels_to_extend;\n\n    //Retrieve the labeled point cloud. Labels == Supervoxel ids\n    pcl::PointCloud<pcl::PointXYZL>::Ptr labeled_cloud = (*_supervoxelizer_ptr_ptr)->getLabeledCloud();\n\n    //Remove NaNs from the labeled point cloud\n    pcl::PointCloud<pcl::PointXYZL>::Ptr labeled_cloud_not_nans(new pcl::PointCloud<pcl::PointXYZL>());\n    std::vector<int> unused;\n    pcl::removeNaNFromPointCloud< pcl::PointXYZL >(*labeled_cloud, *labeled_cloud_not_nans, unused);\n\n    //Copy labeled point cloud without NaNs to a point cloud of XYZRGB points\n    omip::SRPointCloud::Ptr labeled_cloud_not_nans_xyzrgb(new omip::SRPointCloud);\n    pcl::copyPointCloud(*labeled_cloud_not_nans, *labeled_cloud_not_nans_xyzrgb);\n\n    //Pass the new point cloud as input to a KNN. We will use it to find neighbors of the features and the points of the model\n    this->_knn->setInputCloud(labeled_cloud_not_nans_xyzrgb);\n\n    //Copy the supporting features of this RB into a point cloud without labels (only xyz)\n    pcl::PointCloud<pcl::PointXYZ>::Ptr supporting_feats_no_labels(new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::copyPointCloud(*this->_supporting_features, *supporting_feats_no_labels);\n\n    //Find the neighbor of each supporting feature in the point cloud of supervoxels -> find the supervoxel that contains each supporting feature\n    //and add the supervoxels to the candidates\n    for(int idx_sf =0; idx_sf<supporting_feats_no_labels->points.size(); idx_sf++)\n    {\n        std::vector<int> neighbors;\n        std::vector<float> distances;\n        this->_knn->nearestKSearchT<pcl::PointXYZ>(supporting_feats_no_labels->points[idx_sf], 1, neighbors, distances);\n        if(std::find(labels_to_extend.begin(), labels_to_extend.end(), labeled_cloud_not_nans->points[neighbors[0]].label) == labels_to_extend.end())\n        {\n            if(labeled_cloud_not_nans->points[neighbors[0]].label != 0 )\n            {\n                labels_to_extend.push_back(labeled_cloud_not_nans->points[neighbors[0]].label);\n            }\n        }\n    }\n\n    // THIS PART COULD BE IMPROVED TO ACCELERATE THE PROCESS!\n    // Move the model to the current location\n    // and find neighbors in the labeled point cloud (supervoxels)\n    omip::SRPointCloud::Ptr model_in_current_frame(new omip::SRPointCloud);\n    std::vector<std::vector<int > > indices_model;\n    std::vector<std::vector<float > > unused2;\n    unused.clear();\n    if(this->_rb_shape->points.size())\n    {\n        pcl::transformPointCloud<SRPoint>(*this->_rb_shape, *model_in_current_frame, this->_current_HTransform.cast<float>());\n        this->_knn->radiusSearch(*model_in_current_frame, unused, this->_knn_min_radius, indices_model, unused2);\n    }\n\n    // Build a set that contains all the labels of the supervoxels containing points of the depth-based\n    // and the indices of the points of the supervoxels that are neighbors of the models (this avoids counting the same point several times)\n    std::map<uint32_t, std::unordered_set<int> > labels_of_segments_to_extend;\n    for (unsigned int i = 0; i < indices_model.size(); i++)\n    {\n        for(unsigned int k=0; k < indices_model[i].size(); k++)\n        {\n            if(indices_model[i].at(k))\n            {\n                // For the first point we need to create the entry of the map\n                if(labels_of_segments_to_extend.find(labeled_cloud_not_nans->points.at(indices_model[i].at(k)).label) ==  labels_of_segments_to_extend.end())\n                {\n                    std::unordered_set<int> initial_set_of_indices = {indices_model[i].at(k)};\n                    labels_of_segments_to_extend[labeled_cloud_not_nans->points.at(indices_model[i].at(k)).label] = initial_set_of_indices;\n                }\n                else{\n                    // If this point was not counted before as neighbor of another point we add its label\n                    if(labels_of_segments_to_extend.at(labeled_cloud_not_nans->points.at(indices_model[i].at(k)).label).find(indices_model[i].at(k))\n                            == labels_of_segments_to_extend.at(labeled_cloud_not_nans->points.at(indices_model[i].at(k)).label).end())\n                    {\n                        labels_of_segments_to_extend.at(labeled_cloud_not_nans->points.at(indices_model[i].at(k)).label).insert(indices_model[i].at(k));\n                    }\n                }\n            }\n        }\n    }\n\n    std::map<uint32_t, std::unordered_set<int> >::iterator it = labels_of_segments_to_extend.begin();\n    std::map<uint32_t, std::unordered_set<int> >::iterator itend = labels_of_segments_to_extend.end();\n    // Iterate over the map-counter and add the supervoxels that contain enough points\n    for(; it != itend; it++)\n    {\n        if(it->second.size() > _min_number_model_pixels_in_sv && std::find(labels_to_extend.begin(), labels_to_extend.end(), it->first) == labels_to_extend.end())\n        {\n            if(it->first != 0)\n            {\n                labels_to_extend.push_back(it->first);\n            }\n        }\n    }\n    // END OF (THIS PART COULD BE IMPROVED TO ACCELERATE THE PROCESS!)\n\n    std::multimap<uint32_t, uint32_t> supervoxel_adjacency;\n    (*_supervoxelizer_ptr_ptr)->getSupervoxelAdjacency (supervoxel_adjacency);\n\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._ExtendPointsToRegions\",\n                          \"[RB\" << this->_rb_id << \"]: Superpixels to extend the results: \" << labels_to_extend.size());\n\n    if(this->_extend_to_neighbor_sv)\n    {\n        this->_ExtendToNeighborSV(supervoxel_adjacency, labels_to_extend);\n\n        ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._ExtendPointsToRegions\",\n                              \"[RB\" << this->_rb_id << \"]: Superpixels to extend the results (after extending to SV of similar properties): \" << labels_to_extend.size());\n    }\n\n    // Add the points of the supervoxels to extend\n    shape_reconstruction::PassThrough<pcl::PointXYZL>::Ptr pt_filter(new shape_reconstruction::PassThrough<pcl::PointXYZL>());\n    pt_filter->setInputCloud(boost::shared_ptr<pcl::PointCloud<pcl::PointXYZL> >(labeled_cloud_not_nans));\n    pt_filter->setFilterFieldName(\"label\");\n    omip::SRPointCloud::Ptr points_of_current_in_origin(new omip::SRPointCloud);\n    pcl::transformPointCloud<SRPoint>(*this->_current_ffs._pc_without_nans, *points_of_current_in_origin, this->_current_HTransform_inv.cast<float>());\n\n    pt_filter->setLabels(labels_to_extend);\n\n    boost::shared_ptr<std::vector<int> > passing_indices_ptr = boost::shared_ptr<std::vector<int> >(new std::vector<int>());\n    pt_filter->filter(*passing_indices_ptr);\n\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._ExtendPointsToRegions\",\n                           \"[RB\" << this->_rb_id << \"]: Adding \" << (*passing_indices_ptr).size() << \" points to the extended model (currently \" <<this->_rb_shape->width << \" points)\");\n    for (unsigned int i = 0; i < (*passing_indices_ptr).size(); i++)\n    {\n        this->_rb_shape->points.push_back(points_of_current_in_origin->points[(*passing_indices_ptr)[i]]);\n        this->_rb_shape->width++;\n    }\n}\n\nvoid ShapeReconstruction::_ExtendToNeighborSV(std::multimap<uint32_t, uint32_t>& supervoxel_adjacency,\n                                              std::vector<uint32_t>& labels_extension)\n{\n    //EXPERIMENTAL: Naive extension of the SV to neighboring SV with similar properties\n\n    int number_of_sv = _supervoxel_clusters_ptr->size();\n    std::vector<uint32_t> labels_extension_safety_copy = labels_extension;\n\n    //We retrieve the range of elements with each of the added SV\n    std::pair< std::multimap<uint32_t, uint32_t>::iterator, std::multimap<uint32_t, uint32_t>::iterator > neighbors;\n\n    int num_extended_labels = labels_extension.size();\n    int num_extended_labels_with_neigbors = 0;\n\n    // This repeats until we do not add any other label\n    while(num_extended_labels != num_extended_labels_with_neigbors)\n    {\n        num_extended_labels = labels_extension.size();\n        std::vector<uint32_t> labels_extension_copy = labels_extension;\n        for(std::vector<uint32_t>::iterator labels_it = labels_extension.begin(); labels_it!=labels_extension.end(); labels_it++)\n        {\n            // Find the neighbors of the sv\n            neighbors =supervoxel_adjacency.equal_range(*labels_it);\n\n            // Query the supervoxel to be extended\n            if(_supervoxel_clusters_ptr->find(*labels_it) != _supervoxel_clusters_ptr->end())\n            {\n                pcl::Supervoxel<pcl::PointXYZRGB>::Ptr sv = _supervoxel_clusters_ptr->at(*labels_it);\n\n                // Normal of the supervoxel to be extended\n                Eigen::Vector3d sv_normal(sv->normal_.data_n[0], sv->normal_.data_n[1], sv->normal_.data_n[2]);\n\n                // Position and color (RGB) of the supervoxel to be extended\n                pcl::PointXYZRGB sv_centroid_xyzrgb( sv->centroid_.r, sv->centroid_.g, sv->centroid_.b);\n                sv_centroid_xyzrgb.x = sv->centroid_.x;\n                sv_centroid_xyzrgb.y = sv->centroid_.y;\n                sv_centroid_xyzrgb.z = sv->centroid_.z;\n\n                // Position and color (HSV) of the supervoxel to be extended\n                pcl::PointXYZHSV sv_centroid_xyzhsv;\n                pcl::PointXYZRGBtoXYZHSV(sv_centroid_xyzrgb, sv_centroid_xyzhsv);\n\n                // Iterate over the pairs of sv-neighbor\n                for(std::multimap<uint32_t, uint32_t>::iterator neighbor_it = neighbors.first; neighbor_it!= neighbors.second; ++neighbor_it)\n                {\n                    // Check if the neighbor was already added\n                    if(std::find(labels_extension_copy.begin(), labels_extension_copy.end(), neighbor_it->second)  == labels_extension_copy.end() )\n                    {\n                        // Query the neighbor supervoxel to extend to\n                        pcl::Supervoxel<pcl::PointXYZRGB>::Ptr nsv = _supervoxel_clusters_ptr->at(neighbor_it->second);\n\n                        // Normal of the neighbor supervoxel to extend to\n                        Eigen::Vector3d nsv_normal(nsv->normal_.data_n[0], nsv->normal_.data_n[1], nsv->normal_.data_n[2]);\n\n                        // Position and color (RGB) of the neighbor supervoxel to extend to\n                        pcl::PointXYZRGB nsv_centroid_xyzrgb( nsv->centroid_.r, nsv->centroid_.g, nsv->centroid_.b);\n                        nsv_centroid_xyzrgb.x = nsv->centroid_.x;\n                        nsv_centroid_xyzrgb.y = nsv->centroid_.y;\n                        nsv_centroid_xyzrgb.z = nsv->centroid_.z;\n\n                        // Position and color (HSV) of the neighbor supervoxel to extend to\n                        pcl::PointXYZHSV nsv_centroid_xyzhsv;\n                        pcl::PointXYZRGBtoXYZHSV(nsv_centroid_xyzrgb, nsv_centroid_xyzhsv);\n\n                        // We compare the mean normal and the color of the centroid point\n                        // CAREFUL: h values in pcl are between 0 and 360\n                        double h_diff = std::fabs(sv_centroid_xyzhsv.h - nsv_centroid_xyzhsv.h);\n                        h_diff = std::fmod(h_diff, 360.0);\n                        h_diff = h_diff > 180.0 ? 360.0 - h_diff : h_diff;\n                        // TODO: Handle black and white regions (use s and v)\n\n                        if(std::fabs(sv_normal.dot(nsv_normal) - 1.0) < _similarity_in_normal*(M_PI/180.0) && h_diff < _similarity_in_h)\n                        {\n                            labels_extension_copy.push_back(neighbor_it->second);\n                        }\n                    }\n                }\n            }\n        }\n        num_extended_labels_with_neigbors = labels_extension_copy.size();\n        labels_extension = labels_extension_copy;\n    }\n\n    // Emergency brake! -> We are adding too many svs\n    int added_supervoxels = labels_extension.size() - labels_extension_safety_copy.size();\n    // Options: max number of sv to add (absolute) or max fraction of the total amount of sv to add (relative to the total amount of sv)\n    if((double)added_supervoxels/(double)number_of_sv > 0.2 )\n    {\n        ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._ExtendPointsToRegions\",\"We are adding too many supervoxels! Undo!\");\n        labels_extension = labels_extension_safety_copy;\n    }\n}\n\nvoid ShapeReconstruction::_EstimateTransformations()\n{\n    ROSTwist2EigenTwist(this->_previous_ffs._transformation.twist, this->_previous_twist);\n    Twist2TransformMatrix(this->_previous_twist, this->_previous_HTransform);\n    this->_previous_HTransform_inv = this->_previous_HTransform.inverse();\n\n    ROSTwist2EigenTwist(this->_current_ffs._transformation.twist, this->_current_twist);\n    Twist2TransformMatrix(this->_current_twist, this->_current_HTransform);\n    this->_current_HTransform_inv = this->_current_HTransform.inverse();\n\n    ROS_DEBUG_STREAM_NAMED(\"ShapeReconstruction._EstimateTransformations\",  \"[RB\" << this->_rb_id << \"]: _current_HTransform \" << std::endl <<\n                           _current_HTransform);\n\n    this->_current_to_previous_HTransform = this->_current_HTransform*this->_previous_HTransform_inv;\n\n    this->_previous_to_current_HTransform = this->_current_to_previous_HTransform.inverse();\n\n    ROS_DEBUG_STREAM_NAMED(\"ShapeReconstruction._EstimateTransformations\",  \"[RB\" << this->_rb_id << \"]: current to previous \" << std::endl <<\n                           _current_to_previous_HTransform);\n}\n\nvoid ShapeReconstruction::_GenerateMesh(const omip::SRPointCloud::Ptr& pc_source,\n                                        std::string shape_file_prefix)\n{\n    if(pc_source->points.size())\n    {\n        // Normal estimation*\n        this->_rb_tree_for_normal_estimation_ptr->setInputCloud(pc_source);\n        this->_rb_normal_estimator_ptr->setInputCloud(pc_source);\n        this->_rb_normal_estimator_ptr->setSearchMethod (this->_rb_tree_for_normal_estimation_ptr);\n        this->_rb_normal_estimator_ptr->compute(*this->_rb_estimated_normals_pc_ptr);\n\n        // Concatenate the XYZ and normal fields*\n        pcl::concatenateFields (*pc_source, *this->_rb_estimated_normals_pc_ptr, *this->_rb_position_color_and_normals_pc_ptr);\n        this->_rb_tree_for_triangulation_ptr->setInputCloud (this->_rb_position_color_and_normals_pc_ptr);\n\n        // Get result\n        this->_rb_greedy_projection_triangulator_ptr->setInputCloud(this->_rb_position_color_and_normals_pc_ptr);\n        this->_rb_greedy_projection_triangulator_ptr->setSearchMethod(this->_rb_tree_for_triangulation_ptr);\n        this->_rb_greedy_projection_triangulator_ptr->reconstruct(*this->_rb_triangulated_mesh_ptr);\n\n        // Additional vertex information\n        //std::vector<int> parts = gp3.getPartIDs();\n        //std::vector<int> states = gp3.getPointStates();\n\n        std::string mesh_path = ros::package::getPath(\"shape_reconstruction\") + std::string(\"/meshes/\");\n        std::stringstream rb_name_ss;\n        rb_name_ss << shape_file_prefix << this->_rb_id << \".stl\";\n\n        std::string rb_mesh_full_file_name = mesh_path + rb_name_ss.str();\n\n        pcl::io::mesh2vtk(*this->_rb_triangulated_mesh_ptr, this->_rb_polygon_data_ptr);\n\n        this->_rb_polygon_writer_ptr->SetInputData (this->_rb_polygon_data_ptr);\n        this->_rb_polygon_writer_ptr->SetFileName (rb_mesh_full_file_name.c_str ());\n        this->_rb_polygon_writer_ptr->Write ();\n\n        ROS_INFO_STREAM_NAMED(\"ShapeReconstruction.generateMesh\",  \"[RB\" << this->_rb_id << \"]: Resulting triangular mesh written to \" << rb_mesh_full_file_name);\n    }else{\n        ROS_WARN_STREAM_NAMED(\"ShapeReconstruction.generateMesh\",  \"[RB\" << this->_rb_id << \"]: Impossible to generate a triangular mesh for this model, it doesn't contain any points!\");\n    }\n}\n\nvoid ShapeReconstruction::generateMesh()\n{\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction.generateMesh\",  \"[RB\" << this->_rb_id << \"]: Called the generation of 3D triangular mesh from the model of RB\" << this->_rb_id <<\n                          \" based on extending other models with supervoxels.\");\n    std::string shape_ext_d_and_c_file_prefix(\"shape_ext_d_and_c_rb\");\n    this->_GenerateMesh(this->_rb_shape, shape_ext_d_and_c_file_prefix);\n\n\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction.generateMesh\",  \"[RB\" << this->_rb_id << \"]: Finished the generation of 3D triangular mesh from the point cloud of RB \" << this->_rb_id);\n}\n\nvoid ShapeReconstruction::getShapeModel(omip_msgs::ShapeModelsPtr shapes)\n{\n    omip_msgs::ShapeModel shape;\n    shape.rb_id = this->_rb_id;\n    sensor_msgs::PointCloud2 rb_shape_ros;\n    rb_shape_ros.header.frame_id = \"/camera_rgb_optical_frame\";\n\n    this->_rb_shape->header = this->_current_ffs._pc->header;\n    pcl::toROSMsg(*this->_rb_shape, rb_shape_ros);\n\n    shape.rb_shape_model = rb_shape_ros;\n    shapes->rb_shape_models.push_back(shape);\n}\n\nvoid ShapeReconstruction::PublishMovedModelAndSegment(const ros::Time current_time,\n                                                      const geometry_msgs::TwistWithCovariance &rb_transformation,\n                                                      rosbag::Bag& bag,\n                                                      bool bagOpen)\n{\n    Eigen::Twistd current_twist;\n    ROSTwist2EigenTwist(rb_transformation.twist, current_twist);\n\n    Eigen::Matrix4d current_HTransform;\n    Twist2TransformMatrix(current_twist, current_HTransform);\n\n    ROS_INFO_STREAM_NAMED(\"ShapeReconstruction._PublishMovedModel\",  \"[RB\" << this->_rb_id << \"]: Publishing \" << this->_rb_shape->points.size() << \" points reconstructed from RB\" << this->_rb_id\n                          << \" based on extending both depth and color model with supervoxels.\");\n    this->_rb_shape->header = this->_current_ffs._pc->header;\n    this->_rb_shape->header.frame_id = \"/camera_rgb_optical_frame\";\n    this->_rb_shape_in_current_frame.reset(new omip::SRPointCloud);\n    pcl::transformPointCloud<SRPoint>(*this->_rb_shape, *this->_rb_shape_in_current_frame, current_HTransform.cast<float>());\n    sensor_msgs::PointCloud2 rb_shape_ext_d_and_c_in_current_frame_ros;\n    pcl::toROSMsg(*this->_rb_shape_in_current_frame, rb_shape_ext_d_and_c_in_current_frame_ros);\n    rb_shape_ext_d_and_c_in_current_frame_ros.header.frame_id = \"/camera_rgb_optical_frame\";\n    this->_rb_shape_pub.publish(rb_shape_ext_d_and_c_in_current_frame_ros);\n\n    if (bagOpen){\n        bag.write(_rb_shape_pub.getTopic(), current_time, rb_shape_ext_d_and_c_in_current_frame_ros);\n    }\n\n    // segment\n    {\n        this->_rb_segment->header = this->_current_ffs._pc->header;\n        this->_rb_segment->header.frame_id = \"/camera_rgb_optical_frame\";\n        sensor_msgs::PointCloud2 rb_segment_in_current_frame_ros;\n        pcl::toROSMsg(*this->_rb_segment, rb_segment_in_current_frame_ros);\n        rb_segment_in_current_frame_ros.header.frame_id = \"/camera_rgb_optical_frame\";\n        this->_rb_segment_pub.publish(rb_segment_in_current_frame_ros);\n        if (bagOpen){\n            bag.write(_rb_segment_pub.getTopic(), current_time, rb_segment_in_current_frame_ros);\n        }\n    }\n}\n\nvoid ShapeReconstruction::RemoveInconsistentPoints(const SRPointCloud::Ptr &pc_msg,\n                                                   const geometry_msgs::TwistWithCovariance &rb_transformation)\n{\n    Eigen::Twistd current_twist;\n    ROSTwist2EigenTwist(rb_transformation.twist, current_twist);\n    Eigen::Matrix4d current_HTransform;\n    Twist2TransformMatrix(current_twist, current_HTransform);\n\n    SRPointCloud::Ptr current_pc(new SRPointCloud());\n    pcl::copyPointCloud(*pc_msg, *current_pc);\n\n    // Create a depth map from the current organized depth map\n    cv::Mat current_dm;\n    this->_current_ffs._dm->image.copyTo(current_dm);   // Just to initialize current_dm correctly\n    OrganizedPC2DepthMap(current_pc, current_dm);\n\n    this->_RemoveInconsistentPointsFromRBModel(\"\", current_HTransform, this->_rb_shape, current_dm,current_pc, this->_rb_segment);\n\n}\n", "meta": {"hexsha": "ee72d62431e5922badf0e8c900dbda9819c4b3da", "size": 64776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shape_reconstruction/src/ShapeReconstruction.cpp", "max_stars_repo_name": "tu-rbo/omip", "max_stars_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-11-10T16:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T20:11:39.000Z", "max_issues_repo_path": "shape_reconstruction/src/ShapeReconstruction.cpp", "max_issues_repo_name": "tu-rbo/omip", "max_issues_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-28T13:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T22:01:58.000Z", "max_forks_repo_path": "shape_reconstruction/src/ShapeReconstruction.cpp", "max_forks_repo_name": "tu-rbo/omip", "max_forks_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-11-25T18:24:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T03:20:33.000Z", "avg_line_length": 49.7511520737, "max_line_length": 195, "alphanum_fraction": 0.6765314314, "num_tokens": 14751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.19733960114349794}}
{"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#include <nt2/toolbox/libc/include/functions/fabs.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/bench/benchmark.hpp>\n#include <cmath>\n\n//////////////////////////////////////////////////////////////////////////////\n// Scalar Runtime benchmark for functor<fabs_> from libc\n//////////////////////////////////////////////////////////////////////////////\nusing nt2::libc::tag::fabs_;\n\n//////////////////////////////////////////////////////////////////////////////\n// range macro\n//////////////////////////////////////////////////////////////////////////////\n#define RS(T,V1,V2) (T, T(V1) , T(V2))\n\n// TO DO Check ranges\nNT2_TIMING(nt2::libc::tag::fabs_,(RS(float,-1.0f,1.0f)))\nNT2_TIMING(nt2::libc::tag::fabs_,(RS(double,-1.0f,1.0f)))\nNT2_TIMING(nt2::libc::tag::fabs_,(RS(int32_t,-1,1)))\n\n#undef RS\n", "meta": {"hexsha": "89f62c48000e11277adb661978d192837c44b925", "size": 1321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/extern/libc/bench/simd/fabs.cpp", "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/extern/libc/bench/simd/fabs.cpp", "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/extern/libc/bench/simd/fabs.cpp", "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": 44.0333333333, "max_line_length": 80, "alphanum_fraction": 0.4201362604, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.19726667441515172}}
{"text": "// Autogenerated from KST: please remove this line if doing any edits by hand!\n\n#include <boost/test/unit_test.hpp>\n#include \"expr_int_div.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n\nBOOST_AUTO_TEST_CASE(test_expr_int_div) {\n    std::ifstream ifs(\"src/fixed_struct.bin\", std::ifstream::binary);\n    kaitai::kstream ks(&ifs);\n    expr_int_div_t* r = new expr_int_div_t(&ks);\n\n    BOOST_CHECK_EQUAL(r->int_u(), 1262698832);\n    BOOST_CHECK_EQUAL(r->int_s(), -52947);\n    BOOST_CHECK_EQUAL(r->div_pos_const(), 756);\n    BOOST_CHECK_EQUAL(r->div_neg_const(), -757);\n    BOOST_CHECK_EQUAL(r->div_pos_seq(), 97130679);\n    BOOST_CHECK_EQUAL(r->div_neg_seq(), -4073);\n\n    delete r;\n}\n", "meta": {"hexsha": "abff2f2ae46f3bdcec380b18972b607ff2b18a26", "size": 695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spec/cpp_stl_98/test_expr_int_div.cpp", "max_stars_repo_name": "DarkShadow44/kaitai_struct_tests", "max_stars_repo_head_hexsha": "4bb13cef82965cca66dda2eb2b77cd64e9f70a12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-04-01T03:58:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T09:04:55.000Z", "max_issues_repo_path": "spec/cpp_stl_98/test_expr_int_div.cpp", "max_issues_repo_name": "DarkShadow44/kaitai_struct_tests", "max_issues_repo_head_hexsha": "4bb13cef82965cca66dda2eb2b77cd64e9f70a12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 73.0, "max_issues_repo_issues_event_min_datetime": "2016-07-20T10:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T18:56:46.000Z", "max_forks_repo_path": "spec/cpp_stl_98/test_expr_int_div.cpp", "max_forks_repo_name": "DarkShadow44/kaitai_struct_tests", "max_forks_repo_head_hexsha": "4bb13cef82965cca66dda2eb2b77cd64e9f70a12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-08-15T08:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T14:48:46.000Z", "avg_line_length": 30.2173913043, "max_line_length": 78, "alphanum_fraction": 0.7122302158, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.19726666684034658}}
{"text": "#include \"STBA/baproblem.h\"\n\n#include <fstream>\n#include <numeric>\n#include <Eigen/IterativeLinearSolvers>\n\nBAProblem::BAProblem() :\n    pose_block_(), point_block_(), intrinsic_block_(), projection_block_(),\n    residual_(NULL),\n    pose_jacobian_(NULL),\n    point_jacobian_(NULL),\n    pose_jacobian_square_(NULL),\n    point_jacobian_square_(NULL),\n    pose_point_jacobian_product_(NULL),\n    pose_gradient_(NULL),\n    point_gradient_(NULL),\n    Ec_Cinv_w_(NULL),\n    loss_function_(NULL),\n    thread_num_(1),\n    max_degree_(1000),\n    linear_solver_type_(ADAPTIVE)\n{\n    loss_function_ = new HuberLoss();\n}\n\nBAProblem::BAProblem(LossType loss_type) :\n    pose_block_(), point_block_(), projection_block_(),\n    residual_(NULL),\n    pose_jacobian_(NULL),\n    point_jacobian_(NULL),\n    pose_jacobian_square_(NULL),\n    point_jacobian_square_(NULL),\n    pose_point_jacobian_product_(NULL),\n    pose_gradient_(NULL),\n    point_gradient_(NULL),\n    Ec_Cinv_w_(NULL),\n    loss_function_(NULL),\n    thread_num_(1),\n    max_degree_(1000),\n    linear_solver_type_(ADAPTIVE)\n{\n    switch(loss_type)\n    {\n    case NULLLossType:\n        loss_function_ = new NULLLoss();\n        break;\n    case CauchyLossType:\n        loss_function_ = new CauchyLoss();\n        break;\n    default:\n        loss_function_ = new HuberLoss();\n    }\n}\n\nBAProblem::BAProblem(size_t pose_num, size_t group_num, size_t point_num, size_t proj_num) :\n    pose_block_(pose_num), point_block_(point_num), projection_block_(proj_num),\n    loss_function_(NULL), max_degree_(1000), linear_solver_type_(ADAPTIVE)\n{\n    Create(pose_num, group_num, point_num, proj_num);\n    loss_function_ = new HuberLoss();\n}\n\nBAProblem::~BAProblem()\n{\n    Delete();\n    if (loss_function_ != NULL)                 delete loss_function_;\n}\n\nbool BAProblem::Create(size_t pose_num, size_t group_num, size_t point_num, size_t proj_num)\n{\n    DT memory = pose_num * 12 + group_num * 12 + point_num * 6 + proj_num * 2 +\n            proj_num * 2 + proj_num * 12 + proj_num * 6 + pose_num * 36 + point_num * 9 +\n            proj_num * 18 + pose_num * 6 + point_num * 3 + pose_num * 6;\n    memory = memory * 4 / (1024 * 1024 * 1024);  // kB\n    std::cout << \"[BAProblem::Create] A memory of \" << memory << \" GB is going to be allocated.\\n\";\n\n    if (!pose_block_.Create(pose_num))          return false;\n    if (!intrinsic_block_.Create(group_num))    return false;\n    if (!point_block_.Create(point_num))         return false;\n    if (!projection_block_.Create(proj_num))   return false;\n\n    Delete();\n    try\n    {\n        residual_ = new DT[2 * proj_num];\n        pose_jacobian_ = new DT[2 * proj_num * 6];   // The i-th item stores the jacobian of i-th projection w.r.t corresponding camera\n        point_jacobian_ = new DT[2 * proj_num * 3];  // The i-th item stores the jacobian of i-th projection w.r.t corresponding point\n        pose_jacobian_square_ = new DT[pose_num * 6 * 6];\n        point_jacobian_square_ = new DT[point_num * 3 * 3];\n        pose_point_jacobian_product_ = new DT[proj_num * 6 * 3];\n        pose_gradient_ = new DT[pose_num * 6];\n        point_gradient_ = new DT[point_num * 3];\n        Ec_Cinv_w_ = new DT[pose_num * 6];\n    }\n    catch (std::bad_alloc & e)\n    {\n        std::cout << \"[BAProblem::Create] Catching bad_alloc: \" << e.what() << std::endl;\n        return false;\n    }\n    return true;\n}\n\nbool BAProblem::Initialize(BundleBlock const & bundle_block)\n{\n    std::vector<size_t> group_indexes = bundle_block.GroupIndexes();\n    std::vector<size_t> camera_indexes = bundle_block.CameraIndexes();\n    std::vector<size_t> point_indexes = bundle_block.TrackIndexes();\n    std::vector<size_t> projection_indexes = bundle_block.ProjectionIndexes();\n    std::sort(group_indexes.begin(), group_indexes.end());\n    std::sort(camera_indexes.begin(), camera_indexes.end());\n    std::sort(point_indexes.begin(), point_indexes.end());\n    std::sort(projection_indexes.begin(), projection_indexes.end());\n\n    size_t group_num = group_indexes.size();\n    size_t pose_num = camera_indexes.size();\n    size_t point_num = point_indexes.size();\n    size_t projection_num = projection_indexes.size();\n\n    if (!Create(pose_num, group_num, point_num, projection_num))    return false;\n\n    std::unordered_map<size_t, size_t> group_map;\n    for (size_t i = 0; i < group_indexes.size(); i++)\n    {\n        size_t index = group_indexes[i];\n        group_map[index] = i;\n        group_index_map_[i] = index;\n    }\n\n    max_degree_ = 0;\n    std::unordered_map<size_t, size_t> pose_map;\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        size_t index = camera_indexes[i];\n        pose_map[index] = i;\n        pose_index_map_[i] = index;\n\n        BundleBlock::DCamera const & camera = bundle_block.GetCamera(index);\n        BundleBlock::DGroup const & group = bundle_block.GetGroup(camera.group_id);\n        SetPose(i, camera.axis_angle, camera.translation);\n        assert(group_map.find(group.id) != group_map.end() && \"Camera has no group\");\n        size_t group_index = group_map[group.id];\n        SetIntrinsic(group_index, i, group.intrinsic);\n        pose_projection_map_[i] = std::unordered_map<size_t, size_t>();\n\n        max_degree_ = std::max(max_degree_, camera.linked_cameras.size());\n    }\n\n    std::unordered_map<size_t, size_t> point_map;\n    for (size_t i = 0; i < point_num; i++)\n    {\n        size_t index = point_indexes[i];\n        point_map[index] = i;\n        point_index_map_[i] = index;\n        BundleBlock::DTrack const & track = bundle_block.GetTrack(index);\n        SetPoint(i, track.position);\n        SetColor(i, track.color);\n        point_projection_map_[i] = std::unordered_map<size_t, size_t>();\n    }\n\n    for (size_t i = 0; i < projection_indexes.size(); i++)\n    {\n        size_t index = projection_indexes[i];\n        BundleBlock::DProjection const & projection = bundle_block.GetProjection(index);\n        size_t camera_index = projection.camera_id;\n        size_t track_index = projection.track_id;\n        assert(pose_map.find(camera_index) != pose_map.end() && \"Pose index not found\");\n        assert(point_map.find(track_index) != point_map.end() && \"Point index not found\");\n        size_t pose_index = pose_map[camera_index];\n        size_t point_index = point_map[track_index];\n        SetProjection(i, pose_index, point_index, projection.projection);\n    }\n\n    std::unordered_map<size_t, std::unordered_map<size_t, std::vector<size_t> > > common_track_map;\n    bundle_block.GetCommonPoints(common_track_map);\n    std::unordered_map<size_t, std::unordered_map<size_t, std::vector<size_t> > >::const_iterator it1;\n    for (it1 = common_track_map.begin(); it1 != common_track_map.end(); it1++)\n    {\n        size_t camera_index1 = it1->first;\n        assert(pose_map.find(camera_index1) != pose_map.end());\n        size_t pose_index1 = pose_map[camera_index1];\n        std::unordered_map<size_t, std::vector<size_t> > const & local_map = it1->second;\n        std::unordered_map<size_t, std::vector<size_t> >::const_iterator it2;\n        for (it2 = local_map.begin(); it2 != local_map.end(); it2++)\n        {\n            size_t camera_index2 = it2->first;\n            assert(pose_map.find(camera_index2) != pose_map.end());\n            size_t pose_index2 = pose_map[camera_index2];\n            if (pose_index1 > pose_index2)  continue;\n            std::vector<size_t> const & track_indexes = it2->second;\n            std::unordered_set<size_t> point_index_set;\n            for (size_t i = 0; i < track_indexes.size(); i++)\n            {\n                size_t track_index = track_indexes[i];\n                assert(point_map.find(track_index) != point_map.end());\n                size_t point_index = point_map[track_index];\n                point_index_set.insert(point_index);\n            }\n            std::vector<size_t> common_point_indexes(point_index_set.begin(), point_index_set.end());\n            SetCommonPoints(pose_index1, pose_index2, common_point_indexes);\n        }\n    }\n\n    std::stringstream local_stream;\n    local_stream << \"[Initialize] \\n\"\n                 << \"# poses: \" << PoseNum() << \"\\n\"\n                 << \"# groups: \" << GroupNum() << \"\\n\"\n                 << \"# points: \" << PointNum() << \"\\n\"\n                 << \"# projections: \" << ProjectionNum() << \"\\n\"\n                 << \"max degree: \" << max_degree_ << \"\\n\";\n    std::cout << local_stream.str();\n    stream_ << local_stream.str();\n\n    return true;\n}\n\nvoid BAProblem::Update(BundleBlock & bundle_block) const\n{\n    size_t pose_num = PoseNum();\n    size_t point_num = PointNum();\n\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        size_t pose_index = pose_index_map_.find(i)->second;\n        BundleBlock::DCamera & camera = bundle_block.GetCamera(pose_index);\n        GetPose(i, camera.axis_angle, camera.translation);\n    }\n\n    for (size_t i = 0; i < point_num; i++)\n    {\n        size_t point_index = point_index_map_.find(i)->second;\n        BundleBlock::DTrack & track = bundle_block.GetTrack(point_index);\n        GetPoint(i, track.position);\n    }\n}\n\nvoid BAProblem::SaveReport(std::string const & report_path) const\n{\n    std::ofstream fout(report_path);\n    fout << stream_.str();\n    fout.close();\n}\n\nvoid BAProblem::SetIntrinsic(size_t idx, size_t camera_index, Vec6 const & intrinsic)\n{\n    assert(camera_index < PoseNum() && \"Pose index of projection out of range\");\n    intrinsic_block_.SetIntrinsic(idx, intrinsic);\n    pose_group_map_[camera_index] = idx;\n    std::unordered_map<size_t, std::vector<size_t> >::iterator it = group_pose_map_.find(idx);\n    if (it == group_pose_map_.end())\n    {\n        std::vector<size_t> pose_indexes = {camera_index};\n        group_pose_map_[idx] = pose_indexes;\n    }\n    else\n    {\n        std::vector<size_t> & pose_indexes = it->second;\n        pose_indexes.push_back(camera_index);\n    }\n}\n\nvoid BAProblem::SetProjection(size_t idx,size_t camera_index, size_t point_index, Vec2 const & proj)\n{\n    assert(camera_index < pose_block_.PoseNum() && \"Pose index of projection out of range\");\n    assert(point_index < point_block_.PointNum() && \"Point index of projection out of range\");\n    projection_block_.SetProjection(idx, camera_index, point_index, proj);\n    std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::iterator it = pose_projection_map_.find(camera_index);\n    if (it != pose_projection_map_.end())\n    {\n        std::unordered_map<size_t, size_t> & map = it->second;\n        map[point_index] = idx;\n    }\n    else\n    {\n        std::unordered_map<size_t, size_t> map;\n        map[point_index] = idx;\n        pose_projection_map_[camera_index] = map;\n    }\n\n    it = point_projection_map_.find(point_index);\n    if (it != point_projection_map_.end())\n    {\n        std::unordered_map<size_t, size_t> & map = it->second;\n        map[camera_index] = idx;\n    }\n    else\n    {\n        std::unordered_map<size_t, size_t> map;\n        map[camera_index] = idx;\n        point_projection_map_[point_index] = map;\n    }\n}\n\nvoid BAProblem::SetCommonPoints(size_t pose_index1, size_t pose_index2, std::vector<size_t> const & points)\n{\n    assert(pose_index1 < pose_block_.PoseNum() && \"[SetCommonPoints] Pose index out of range\");\n    assert(pose_index2 < pose_block_.PoseNum() && \"[SetCommonPoints] Pose index out of range\");\n    size_t index1 = std::min(pose_index1, pose_index2);\n    size_t index2 = std::max(pose_index1, pose_index2);\n    std::unordered_map<size_t, std::unordered_map<size_t, std::vector<size_t> > >::iterator it1 = common_point_map_.find(index1);\n    if (it1 != common_point_map_.end())\n    {\n        std::unordered_map<size_t, std::vector<size_t> > & map = it1->second;\n        map[index2] = points;\n    }\n    else\n    {\n        std::unordered_map<size_t, std::vector<size_t> > map;\n        map[index2] = points;\n        common_point_map_[index1] = map;\n    }\n}\n\nsize_t BAProblem::GetProjectionIndex(size_t pose_index, size_t point_index) const\n{\n    std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::const_iterator it1 = pose_projection_map_.find(pose_index);\n    assert(it1 != pose_projection_map_.end() && \"[GetProjectionIndex] Pose index not found\");\n    std::unordered_map<size_t, size_t> const & map = it1->second;\n    std::unordered_map<size_t, size_t>::const_iterator it2 = map.find(point_index);\n    assert(it2 != map.end() && \"[GetProjectionIndex] Point index not found\");\n    return it2->second;\n}\n\nvoid BAProblem::GetCommonPoints(size_t pose_index1, size_t pose_index2, std::vector<size_t> & points) const\n{\n    points.clear();\n    size_t index1 = std::min(pose_index1, pose_index2);\n    size_t index2 = std::max(pose_index1, pose_index2);\n    std::unordered_map<size_t, std::unordered_map<size_t, std::vector<size_t> > >::const_iterator it1 = common_point_map_.find(index1);\n    if (it1 == common_point_map_.end()) return;\n    std::unordered_map<size_t, std::vector<size_t> > const & map = it1->second;\n    std::unordered_map<size_t, std::vector<size_t> >::const_iterator it2 = map.find(index2);\n    if (it2 == map.end()) return;\n    points = it2->second;\n}\n\nvoid BAProblem::GetResidual(size_t proj_index, Vec2 & residual) const\n{\n    assert(proj_index < projection_block_.ProjectionNum() && \"[GetResidual] Projection index out of range\");\n    DT * ptr = residual_ + proj_index * 2;\n    residual = Vec2(ptr);\n}\n\nvoid BAProblem::SetResidual(size_t proj_index, Vec2 const & residual)\n{\n    assert(proj_index < projection_block_.ProjectionNum() && \"[SetResidual] Projection index out of range\");\n    residual_[proj_index * 2] = residual(0);\n    residual_[proj_index * 2 + 1] = residual(1);\n}\n\nvoid BAProblem::GetPoseJacobian(size_t proj_index, Mat26 & jacobian) const\n{\n    assert(proj_index < projection_block_.ProjectionNum() && \"[GetPoseJacobian] Projection index out of range\");\n    DT * ptr = pose_jacobian_ + proj_index * 12;\n    jacobian = Mat26(ptr);\n}\n\nvoid BAProblem::SetPoseJacobian(size_t proj_index, Mat23 const & jacobian_rotation, Mat23 const & jacobian_translation)\n{\n    assert(proj_index < projection_block_.ProjectionNum() && \"[SetPoseJacobian] Projection index out of range\");\n    pose_jacobian_[proj_index * 12] = jacobian_rotation(0, 0);           // store in row major\n    pose_jacobian_[proj_index * 12 + 1] = jacobian_rotation(0, 1);\n    pose_jacobian_[proj_index * 12 + 2] = jacobian_rotation(0, 2);\n    pose_jacobian_[proj_index * 12 + 3] = jacobian_translation(0, 0);\n    pose_jacobian_[proj_index * 12 + 4] = jacobian_translation(0, 1);\n    pose_jacobian_[proj_index * 12 + 5] = jacobian_translation(0, 2);\n    pose_jacobian_[proj_index * 12 + 6] = jacobian_rotation(1, 0);\n    pose_jacobian_[proj_index * 12 + 7] = jacobian_rotation(1, 1);\n    pose_jacobian_[proj_index * 12 + 8] = jacobian_rotation(1, 2);\n    pose_jacobian_[proj_index * 12 + 9] = jacobian_translation(1, 0);\n    pose_jacobian_[proj_index * 12 + 10] = jacobian_translation(1, 1);\n    pose_jacobian_[proj_index * 12 + 11] = jacobian_translation(1, 2);\n}\n\nvoid BAProblem::GetPointJacobian(size_t proj_index, Mat23 & jacobian) const\n{\n    assert(proj_index < projection_block_.ProjectionNum() && \"[GetPointJacobian] Projection index out of range\");\n    DT * ptr = point_jacobian_ + proj_index * 6;\n    jacobian = Mat23(ptr);\n}\n\nvoid BAProblem::SetPointJacobian(size_t proj_index, Mat23 const & jacobian_point)\n{\n    assert(proj_index < projection_block_.ProjectionNum() && \"[SetPointJacobian] Projection index out of range\");\n    point_jacobian_[proj_index * 6] = jacobian_point(0, 0);\n    point_jacobian_[proj_index * 6 + 1] = jacobian_point(0, 1);\n    point_jacobian_[proj_index * 6 + 2] = jacobian_point(0, 2);\n    point_jacobian_[proj_index * 6 + 3] = jacobian_point(1, 0);\n    point_jacobian_[proj_index * 6 + 4] = jacobian_point(1, 1);\n    point_jacobian_[proj_index * 6 + 5] = jacobian_point(1, 2);\n}\n\nvoid BAProblem::GetJcJc(size_t pose_index, Mat6 & JcJc) const\n{\n    assert(pose_index < pose_block_.PoseNum() && \"[GetJcJc] Pose index out of range\");\n    DT * ptr = pose_jacobian_square_ + pose_index * 6 * 6;\n    JcJc = Mat6(ptr);\n}\n\nvoid BAProblem::GetJcJc(std::vector<size_t> const & pose_indexes, MatX & JcJc) const\n{\n    size_t pose_num = pose_indexes.size();\n    JcJc = MatX::Zero(pose_num * 6, pose_num * 6);\n\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        size_t pose_index = pose_indexes[i];\n        Mat6 local_JcJc;\n        GetJcJc(pose_index, local_JcJc);\n        JcJc.block(6 * i, 6 * i, 6, 6) = local_JcJc;\n    }\n}\n\nvoid BAProblem::GetJcJc(std::vector<size_t> const & pose_indexes, SMat & JcJc) const\n{\n    size_t pose_num = pose_indexes.size();\n    JcJc.resize(pose_num * 6, pose_num * 6);\n    JcJc.reserve(Eigen::VectorXi::Constant(pose_num * 6, 6));\n\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        size_t pose_index = pose_indexes[i];\n        Mat6 local_JcJc;\n        GetJcJc(pose_index, local_JcJc);\n        for (size_t j = 0; j < 6; j++)\n            for (size_t k = 0; k < 6; k++)\n                JcJc.insert(6 * i + j, 6 * i + k) = local_JcJc(j, k);\n    }\n}\n\nvoid BAProblem::GetJcJc(MatX & JcJc) const\n{\n    size_t pose_num = PoseNum();\n    JcJc = MatX::Zero(pose_num * 6, pose_num * 6);\n\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        Mat6 local_JcJc;\n        GetJcJc(i, local_JcJc);\n        JcJc.block(6 * i, 6 * i, 6, 6) = local_JcJc;\n    }\n}\n\nvoid BAProblem::SetJcJc(size_t pose_index, Mat6 const & JcJc)\n{\n    assert(pose_index < pose_block_.PoseNum() && \"[SetJcJc] Pose index out of range\");\n    for (size_t i = 0; i < 6; i++)\n        for (size_t j = 0; j < 6; j++)\n            pose_jacobian_square_[pose_index * 6 * 6 + i * 6 + j] = JcJc(i, j);\n}\n\nvoid BAProblem::IncreJcJc(size_t pose_index, Mat6 const & JcJc)\n{\n    assert(pose_index < pose_block_.PoseNum() && \"[IncreJcJc] Pose index out of range\");\n    for (size_t i = 0; i < 6; i++)\n        for (size_t j = 0; j < 6; j++)\n            pose_jacobian_square_[pose_index * 6 * 6 + i * 6 + j] += JcJc(i, j);\n}\n\nvoid BAProblem::GetJpJp(size_t point_index, Mat3 & JpJp) const\n{\n    assert(point_index < point_block_.PointNum() && \"[GetJpJp] Point index out of range\");\n    DT * ptr = point_jacobian_square_ + point_index * 3 * 3;\n    JpJp = Mat3(ptr);\n}\n\nvoid BAProblem::SetJpJp(size_t point_index, Mat3 const & JpJp)\n{\n    assert(point_index < point_block_.PointNum() && \"[SetJpJp] Point index out of range\");\n    for (size_t i = 0; i < 3; i++)\n        for (size_t j = 0; j < 3; j++)\n            point_jacobian_square_[point_index * 3 * 3 + i * 3 + j] = JpJp(i, j);\n}\n\nvoid BAProblem::IncreJpJp(size_t point_index, Mat3 const & JpJp)\n{\n    assert(point_index < point_block_.PointNum() && \"[IncreJpJp] Point index out of range\");\n    for (size_t i = 0; i < 3; i++)\n        for (size_t j = 0; j < 3; j++)\n            point_jacobian_square_[point_index * 3 * 3 + i * 3 + j] += JpJp(i, j);\n}\n\nvoid BAProblem::GetJcJp(size_t proj_index, Mat63 & JcJp) const\n{\n    assert(proj_index < projection_block_.ProjectionNum() && \"[GetJcJp] Projection index out of range\");\n    DT * ptr = pose_point_jacobian_product_ + proj_index * 6 * 3;\n    JcJp = Mat63(ptr);\n}\n\nvoid BAProblem::GetJcJp(size_t pose_index, size_t point_index, Mat63 & JcJp) const\n{\n    size_t proj_index = GetProjectionIndex(pose_index, point_index);\n    GetJcJp(proj_index, JcJp);\n}\n\nvoid BAProblem::SetJcJp(size_t proj_index, Mat63 const & JcJp)\n{\n    assert(proj_index < projection_block_.ProjectionNum() && \"[SetJcJp] Projection index out of range\");\n    for (size_t i = 0; i < 6; i++)\n        for (size_t j = 0; j < 3; j++)\n            pose_point_jacobian_product_[proj_index * 6 * 3 + i * 3 + j] = JcJp(i, j);\n}\n\nvoid BAProblem::SetJcJp(size_t pose_index, size_t point_index, Mat63 const & JcJp)\n{\n    size_t proj_index = GetProjectionIndex(pose_index, point_index);\n    SetJcJp(proj_index, JcJp);\n}\n\nvoid BAProblem::GetJce(size_t pose_index, Vec6 & Jce) const\n{\n    assert(pose_index < pose_block_.PoseNum() && \"[GetJce] Pose index out of range\");\n    DT * ptr = pose_gradient_ + pose_index * 6;\n    Jce = Vec6(ptr);\n}\n\nvoid BAProblem::GetJce(std::vector<size_t> const & pose_indexes, VecX & Jce) const\n{\n    size_t pose_num = pose_indexes.size();\n    Jce.resize(pose_num * 6);\n    for (size_t i = 0; i < pose_indexes.size(); i++)\n    {\n        size_t pose_index = pose_indexes[i];\n        Vec6 local_Jce;\n        GetJce(pose_index, local_Jce);\n        Jce.segment(i * 6, 6) = local_Jce;\n    }\n}\n\nvoid BAProblem::GetJce(VecX & Jce) const\n{\n    size_t pose_num = pose_block_.PoseNum();\n    Jce.resize(pose_num * 6);\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        Vec6 local_Jce;\n        GetJce(i, local_Jce);\n        Jce.segment(i * 6, 6) = local_Jce;\n    }\n}\n\nvoid BAProblem::SetJce(size_t pose_index, Vec6 const & Jce)\n{\n    assert(pose_index < pose_block_.PoseNum() && \"[GetJce] Pose index out of range\");\n    for (size_t i = 0; i < 6; i++)\n        pose_gradient_[pose_index * 6 + i] = Jce(i);\n}\n\nvoid BAProblem::IncreJce(size_t pose_index, Vec6 const & Jce)\n{\n    assert(pose_index < pose_block_.PoseNum() && \"[IncreJce] Pose index out of range\");\n    for (size_t i = 0; i < 6; i++)\n        pose_gradient_[pose_index * 6 + i] += Jce(i);\n}\n\nvoid BAProblem::GetJpe(size_t point_index, Vec3 & Jpe) const\n{\n    assert(point_index < point_block_.PointNum() && \"[GetJpe] Point index out of range\");\n    DT * ptr = point_gradient_ + point_index * 3;\n    Jpe = Vec3(ptr);\n}\n\nvoid BAProblem::GetJpe(VecX & Jpe) const\n{\n    size_t point_num = point_block_.PointNum();\n    Jpe.resize(point_num * 3);\n    for (size_t i = 0; i < point_num; i++)\n    {\n        Vec3 local_Jpe;\n        GetJpe(i, local_Jpe);\n        Jpe.segment(3 * i, 3) = local_Jpe;\n    }\n}\n\nvoid BAProblem::SetJpe(size_t point_index, Vec3 const & Jpe)\n{\n    assert(point_index < point_block_.PointNum() && \"[SetJpe] Point index out of range\");\n    for (size_t i = 0; i < 3; i++)\n        point_gradient_[point_index * 3 + i] = Jpe(i);\n}\n\nvoid BAProblem::IncreJpe(size_t point_index, Vec3 const & Jpe)\n{\n    assert(point_index < point_block_.PointNum() && \"[SetJpe] Point index out of range\");\n    for (size_t i = 0; i < 3; i++)\n        point_gradient_[point_index * 3 + i] += Jpe(i);\n}\n\nvoid BAProblem::GetEcw(size_t pose_index, Vec6 & ECw) const\n{\n    assert(pose_index < pose_block_.PoseNum() && \"[GetECw] Pose index out of range\");\n    DT * ptr = Ec_Cinv_w_ + pose_index * 6;\n    ECw = Vec6(ptr);\n}\n\nvoid BAProblem::GetEcw(std::vector<size_t> const & pose_indexes, VecX & ECw) const\n{\n    size_t pose_num = pose_indexes.size();\n    ECw = VecX::Zero(6 * pose_num);\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        size_t pose_index = pose_indexes[i];\n        Vec6 local_ECw;\n        GetEcw(pose_index, local_ECw);\n        ECw.segment(6 * i, 6) = local_ECw;\n    }\n}\n\nvoid BAProblem::GetEcw(VecX & Ecw) const\n{\n    size_t pose_num = PoseNum();\n    Ecw = VecX::Zero(6 * pose_num);\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        Vec6 local_ECw;\n        GetEcw(i, local_ECw);\n        Ecw.segment(6 * i, 6) = local_ECw;\n    }\n}\n\nvoid BAProblem::SetECw(size_t pose_index, Vec6 const & ECw)\n{\n    assert(pose_index < pose_block_.PoseNum() && \"[SetECw] Pose index out of range\");\n    for (size_t i = 0; i < 6; i++)\n        Ec_Cinv_w_[pose_index * 6 + i] = ECw(i);\n}\n\nvoid BAProblem::GetPose(VecX & poses) const\n{\n    size_t pose_num = PoseNum();\n    poses.resize(pose_num * 6);\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        Vec6 local_pose;\n        pose_block_.GetPose(i, local_pose);\n        poses.segment(6 * i, 6) = local_pose;\n    }\n}\n\nvoid BAProblem::GetPoint(VecX & points) const\n{\n    size_t point_num = PointNum();\n    points.resize(point_num * 3);\n    for (size_t i = 0; i < point_num; i++)\n    {\n        Vec3 local_point;\n        point_block_.GetPoint(i, local_point);\n        points.segment(3 * i, 3) = local_point;\n    }\n}\n\nvoid BAProblem::GetPoseUpdate(VecX & update) const\n{\n    size_t pose_num = PoseNum();\n    update.resize(pose_num * 6);\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        Vec6 local_update;\n        pose_block_.GetDeltaPose(i, local_update);\n        update.segment(6 * i, 6) = local_update;\n    }\n}\n\nvoid BAProblem::GetPointUpdate(VecX & update) const\n{\n    size_t point_num = PointNum();\n    update.resize(point_num * 3);\n    for (size_t i = 0; i < point_num; i++)\n    {\n        Vec3 local_update;\n        point_block_.GetDeltaPoint(i, local_update);\n        update.segment(3 * i, 3) = local_update;\n    }\n}\n\nsize_t BAProblem::GetPoseGroup(size_t pose_index) const\n{\n    std::unordered_map<size_t, size_t>::const_iterator it = pose_group_map_.find(pose_index);\n    assert(it != pose_group_map_.end() && \"[GetPoseGroup] Pose index not found\");\n    return it->second;\n}\n\nvoid BAProblem::EvaluateResidual()\n{\n    ClearResidual();\n    size_t proj_num = projection_block_.ProjectionNum();\n\n#pragma omp parallel for\n    for (size_t i = 0; i < proj_num; i++)\n    {\n        size_t pose_index = projection_block_.PoseIndex(i);\n        size_t point_index = projection_block_.PointIndex(i);\n        Vec3 angle_axis, translation, point;\n        Vec6 intrinsic;\n        pose_block_.GetPose(pose_index, angle_axis, translation);\n        point_block_.GetPoint(point_index, point);\n        GetPoseIntrinsic(pose_index, intrinsic);\n        Vec2 reprojection_error, reprojection;\n        if (!Project(intrinsic(0), intrinsic(1), intrinsic(2), angle_axis, translation, point, intrinsic.tail<3>(), reprojection))\n            continue;\n        Vec2 projection;\n        projection_block_.GetProjection(i, projection);\n        reprojection_error = reprojection - projection;\n        loss_function_->CorrectResiduals(reprojection_error);\n        SetResidual(i, reprojection_error);\n    }\n}\n\ndouble BAProblem::EvaluateSquareResidual(bool const update) const\n{\n    double error = 0.0;\n    size_t proj_num = projection_block_.ProjectionNum();\n    for (size_t i = 0; i < proj_num; i++)\n    {\n        size_t pose_index = projection_block_.PoseIndex(i);\n        size_t group_index = GetPoseGroup(pose_index);\n        size_t point_index = projection_block_.PointIndex(i);\n        Vec3 angle_axis, translation, point;\n        Vec6 intrinsic;\n        pose_block_.GetPose(pose_index, angle_axis, translation);\n        point_block_.GetPoint(point_index, point);\n        GetPoseIntrinsic(pose_index, intrinsic);\n        if (update)\n        {\n            Vec3 delta_angle_axis, delta_translation, delta_point;\n            pose_block_.GetDeltaPose(pose_index, delta_angle_axis, delta_translation);\n            point_block_.GetDeltaPoint(point_index, delta_point);\n            angle_axis += delta_angle_axis;\n            translation += delta_translation;\n            point += delta_point;\n        }\n        Vec2 reprojection;\n        if (!Project(intrinsic(0), intrinsic(1), intrinsic(2), angle_axis, translation, point, intrinsic.tail<3>(), reprojection))\n            continue;\n        Vec2 projection;\n        projection_block_.GetProjection(i, projection);\n        Vec2 reprojection_error = reprojection - projection;\n        loss_function_->CorrectResiduals(reprojection_error);\n        double residual_square = reprojection_error.squaredNorm();\n        error += residual_square;\n    }\n    return error;\n}\n\nvoid BAProblem::ReprojectionError(double & mean, double & median, double & max, bool const update) const\n{\n    size_t proj_num = projection_block_.ProjectionNum();\n    assert(proj_num > 0 && \"[ReprojectionError] Empty projection\");\n    std::vector<double> errors(proj_num, 0.0);\n\n    #pragma omp parallel for\n    for (size_t i = 0; i < proj_num; i++)\n    {\n        Vec2 projection;\n        projection_block_.GetProjection(i, projection);\n        size_t pose_index = projection_block_.PoseIndex(i);\n        size_t group_index = GetPoseGroup(pose_index);\n        size_t point_index = projection_block_.PointIndex(i);\n        Vec3 angle_axis, translation, point;\n        Vec6 intrinsic;\n        pose_block_.GetPose(pose_index, angle_axis, translation);\n        GetPoseIntrinsic(pose_index, intrinsic);\n        point_block_.GetPoint(point_index, point);\n        if (update)\n        {\n            Vec3 delta_angle_axis, delta_translation, delta_point;\n            pose_block_.GetDeltaPose(pose_index, delta_angle_axis, delta_translation);\n            point_block_.GetDeltaPoint(point_index, delta_point);\n            angle_axis += delta_angle_axis;\n            translation += delta_translation;\n            point += delta_point;\n        }\n        Vec2 reprojection;\n        if (!Project(intrinsic(0), intrinsic(1), intrinsic(2), angle_axis, translation, point, intrinsic.tail<3>(), reprojection))\n            continue;\n        double reprojection_error = (reprojection - projection).norm();\n        if (reprojection_error > MAX_REPROJ_ERROR) continue;\n        errors[i] = reprojection_error;\n    }\n    double sum_error = 0.0, max_error = 0.0;\n    for (size_t i = 0; i < proj_num; i++)\n    {\n        sum_error += errors[i];\n        max_error = std::max(max_error, errors[i]);\n    }\n    std::nth_element(errors.begin(), errors.begin() + errors.size() / 2, errors.end());\n    mean = sum_error / double(errors.size());\n    median = errors[errors.size() / 2];\n    max = max_error;\n}\n\n/*!\n * @Depend EvaluateResidual\n */\ndouble BAProblem::EvaluateSquareError(bool const update) const\n{\n    size_t proj_num = projection_block_.ProjectionNum();\n    assert(proj_num > 0 && \"[EvaluateSquareError] Empty projection\");\n    double error = 0;\n\n#pragma omp parallel for reduction(+:error)\n    for (size_t i = 0; i < proj_num; i++)\n    {\n        Vec2 projection;\n        projection_block_.GetProjection(i, projection);\n        size_t pose_index = projection_block_.PoseIndex(i);\n        size_t group_index = GetPoseGroup(pose_index);\n        size_t point_index = projection_block_.PointIndex(i);\n        Vec3 angle_axis, translation, point;\n        Vec6 intrinsic;\n        pose_block_.GetPose(pose_index, angle_axis, translation);\n        GetPoseIntrinsic(pose_index, intrinsic);\n        point_block_.GetPoint(point_index, point);\n        if (update)\n        {\n            Vec3 delta_angle_axis, delta_translation, delta_point;\n            pose_block_.GetDeltaPose(pose_index, delta_angle_axis, delta_translation);\n            point_block_.GetDeltaPoint(point_index, delta_point);\n            angle_axis += delta_angle_axis;\n            translation += delta_translation;\n            point += delta_point;\n        }\n        Vec2 reprojection;\n        if (!Project(intrinsic(0), intrinsic(1), intrinsic(2), angle_axis, translation, point, intrinsic.tail<3>(), reprojection))\n            continue;\n        Vec2 reprojection_error = reprojection - projection;\n        double robust_error = loss_function_->Loss(reprojection_error.squaredNorm());\n        error += robust_error;\n    }\n    return error * 0.5;\n}\n\nvoid BAProblem::EvaluateJacobian()\n{\n    ClearPoseJacobian();\n    ClearPointJacobian();\n    size_t proj_num = projection_block_.ProjectionNum();\n\n#pragma omp parallel for\n    for (size_t j = 0; j < proj_num; j++)\n    {\n        // Multiply a factor for robustfication\n        size_t pose_index = projection_block_.PoseIndex(j);\n        size_t point_index = projection_block_.PointIndex(j);\n        Vec3 angle_axis, translation, point;\n        Vec6 intrinsic;\n        pose_block_.GetPose(pose_index, angle_axis, translation);\n        GetPoseIntrinsic(pose_index, intrinsic);\n        point_block_.GetPoint(point_index, point);\n        Vec2 reprojection;\n        if (!Project(intrinsic(0), intrinsic(1), intrinsic(2), angle_axis, translation, point, intrinsic.tail<3>(), reprojection))\n            continue;\n        Vec2 projection;\n        projection_block_.GetProjection(j, projection);\n        Vec2 reprojection_error = reprojection - projection;\n\n        Mat23 jacobian_rotation;\n        Mat23 jacobian_translation;\n        Mat23 jacobian_point;\n        Mat26 jacobian_intrinsic;\n\n        ProjectAndGradient(angle_axis, translation, point, intrinsic(0), intrinsic(1), intrinsic(2), intrinsic.tail<3>(),\n                           projection, jacobian_rotation, jacobian_translation, jacobian_point, jacobian_intrinsic);\n\n        // Correct Jacobian due to robust function\n        loss_function_->CorrectJacobian<2, 3>(reprojection_error, jacobian_rotation);\n        loss_function_->CorrectJacobian<2, 3>(reprojection_error, jacobian_translation);\n        loss_function_->CorrectJacobian<2, 3>(reprojection_error, jacobian_point);\n        loss_function_->CorrectJacobian<2, 6>(reprojection_error, jacobian_intrinsic);\n\n        SetPoseJacobian(j, jacobian_rotation, jacobian_translation);\n        SetPointJacobian(j, jacobian_point);\n    }\n}\n\n/*!\n * @brief Evaluate the Jacobian square of a single camera, which is the sum of\n * Jacobian square of all the projections in this camera.\n */\nvoid BAProblem::EvaluateJcJc(size_t pose_index, Mat6 & JcJc) const\n{\n    JcJc = Mat6::Zero();\n    std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::const_iterator it1 = pose_projection_map_.find(pose_index);\n    assert(it1 != pose_projection_map_.end() && \"[EvaluateJcJc] Pose index not found\");\n    std::unordered_map<size_t, size_t> const & map = it1->second;\n    std::unordered_map<size_t, size_t>::const_iterator it2 = map.begin();\n    for (; it2 != map.end(); it2++)\n    {\n        size_t proj_index = it2->second;\n        Mat26 jacobian;\n        GetPoseJacobian(proj_index, jacobian);\n        JcJc += jacobian.transpose() * jacobian;\n    }\n}\n\n/*!\n * @brief Jc^TJc is a block diagonal matrix, with each block of size 6x6,\n * since each projection (residual term) only corresponds to a unique camera.\n */\nvoid BAProblem::EvaluateJcJc()\n{\n    ClearJcJc();\n    size_t pose_num = pose_block_.PoseNum();\n#pragma omp parallel for\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        Mat6 jcjc;\n        EvaluateJcJc(i, jcjc);\n        SetJcJc(i, jcjc);\n    }\n}\n\n/*!\n * @brief Evaluate the Jacobian square of a single point, which is the sum of\n * Jacobian square of all the projections of this point.\n */\nvoid BAProblem::EvaluateJpJp(size_t point_index, Mat3 & JpJp) const\n{\n    JpJp = Mat3::Zero();\n    std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::const_iterator it1 = point_projection_map_.find(point_index);\n    assert(it1 != point_projection_map_.end() && \"[EvaluateJpJp] Point index not found\");\n    std::unordered_map<size_t, size_t> const & map = it1->second;\n    std::unordered_map<size_t, size_t>::const_iterator it2 = map.begin();\n    for (; it2 != map.end(); it2++)\n    {\n        size_t proj_index = it2->second;\n        Mat23 jacobian;\n        GetPointJacobian(proj_index, jacobian);\n        JpJp += jacobian.transpose() * jacobian;\n    }\n    if (!IsNumericalValid(JpJp))\n        JpJp = Mat3::Zero();\n}\n\n/*!\n * @brief Jp^TJp is a block diagonal matrix, with each block of size 3x3,\n * since each projection (residual term) only corresponds to a unique point.\n */\nvoid BAProblem::EvaluateJpJp()\n{\n    ClearJpJp();\n    size_t point_num = point_block_.PointNum();\n#pragma omp parallel for\n    for (size_t i = 0; i < point_num; i++)\n    {\n        Mat3 jpjp;\n        EvaluateJpJp(i, jpjp);\n        SetJpJp(i, jpjp);\n    }\n}\n\nvoid BAProblem::EvaluateJcJp(size_t proj_index, Mat63 & JcJp) const\n{\n    Mat26 pose_jacobian;\n    GetPoseJacobian(proj_index, pose_jacobian);\n    Mat23 point_jacobian;\n    GetPointJacobian(proj_index, point_jacobian);\n    JcJp = pose_jacobian.transpose() * point_jacobian;\n}\n\nvoid BAProblem::EvaluateJcJp(size_t pose_index, size_t point_index, Mat63 & JcJp) const\n{\n    size_t proj_index = GetProjectionIndex(pose_index, point_index);\n    EvaluateJcJp(proj_index, JcJp);\n}\n\n/*!\n * @brief Jc^TJp is a sparse matrix, whose nonzero element number is equal\n * to the number of projections.\n */\nvoid BAProblem::EvaluateJcJp()\n{\n    ClearJcJp();\n    size_t proj_num = projection_block_.ProjectionNum();\n\n#pragma omp parallel for\n    for (size_t i = 0; i < proj_num; i++)\n    {\n        Mat63 JcJp;\n        EvaluateJcJp(i, JcJp);\n        SetJcJp(i, JcJp);\n    }\n}\n\n/*!\n * @brief Jc^Te - It denotes the gradient of the sum-of-square cost w.r.t the pose\n */\nvoid BAProblem::EvaluateJce(size_t pose_index, Vec6 & Je) const\n{\n    Je = Vec6::Zero();\n    std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::const_iterator it1 = pose_projection_map_.find(pose_index);\n    assert(it1 != pose_projection_map_.end() && \"[EvaluateJce] Pose index not found\");\n    std::unordered_map<size_t, size_t> const & map = it1->second;\n    std::unordered_map<size_t, size_t>::const_iterator it2 = map.begin();\n    for (; it2 != map.end(); it2++)\n    {\n        size_t proj_index = it2->second;\n        Mat26 pose_jacobian;\n        GetPoseJacobian(proj_index, pose_jacobian);\n\n        Vec2 residual;\n        GetResidual(proj_index, residual);\n        Je += pose_jacobian.transpose() * residual;\n    }\n}\n\nvoid BAProblem::EvaluateJce(std::vector<size_t> const & pose_indexes, VecX & Je) const\n{\n    size_t pose_num = pose_indexes.size();\n    Je.resize(pose_num * 6);\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        size_t pose_index = pose_indexes[i];\n        Vec6 local_Je;\n        EvaluateJce(pose_index, local_Je);\n        Je.segment(i * 6, 6) = local_Je;\n    }\n}\n\nvoid BAProblem::EvaluateJce()\n{\n    ClearJce();\n    size_t pose_num = pose_block_.PoseNum();\n\n#pragma omp parallel for\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        Vec6 local_Jce;\n        EvaluateJce(i, local_Jce);\n        SetJce(i, local_Jce);\n    }\n}\n\n/*!\n * @brief Jp^Te - It denotes the gradient of the sum-of-square cost w.r.t the point\n */\nvoid BAProblem::EvaluateJpe(size_t point_index, Vec3 & Je) const\n{\n    Je = Vec3::Zero();\n    std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::const_iterator it1 = point_projection_map_.find(point_index);\n    assert(it1 != point_projection_map_.end() && \"[EvaluateJpe] Point index not found\");\n    std::unordered_map<size_t, size_t> const & map = it1->second;\n    std::unordered_map<size_t, size_t>::const_iterator it2 = map.begin();\n    for (; it2 != map.end(); it2++)\n    {\n        size_t proj_index = it2->second;\n        Mat23 point_jacobian;\n        GetPointJacobian(proj_index, point_jacobian);\n\n        Vec2 residual;\n        GetResidual(proj_index, residual);\n        Je += point_jacobian.transpose() * residual;\n    }\n}\n\nvoid BAProblem::EvaluateJpe(std::vector<size_t> const & point_indexes, VecX & Jpe) const\n{\n    size_t point_num = point_indexes.size();\n    Jpe.resize(point_num * 3);\n    for (size_t i = 0; i < point_num; i++)\n    {\n        size_t point_index = point_indexes[i];\n        Vec3 local_Jpe;\n        EvaluateJpe(point_index, local_Jpe);\n        Jpe.segment(i * 3, 3) = local_Jpe;\n    }\n}\n\nvoid BAProblem::EvaluateJpe()\n{\n    ClearJpe();\n    size_t point_num = point_block_.PointNum();\n#pragma omp parallel for\n    for (size_t i = 0; i < point_num; i++)\n    {\n        Vec3 local_Jpe;\n        EvaluateJpe(i, local_Jpe);\n        SetJpe(i, local_Jpe);\n    }\n}\n\nbool BAProblem::EvaluateEcEc(size_t pose_index1, size_t pose_index2, Mat6 & EcEc) const\n{\n    EcEc.setZero();\n    std::vector<size_t> points;\n    GetCommonPoints(pose_index1, pose_index2, points);\n    if (points.empty()) return false;\n\n    for (size_t i = 0; i < points.size(); i++)\n    {\n        size_t point_index = points[i];\n        Mat63 Jc1Jp, Jc2Jp;\n        Mat3 JpJp;\n        GetJcJp(pose_index1, point_index, Jc1Jp);\n        GetJcJp(pose_index2, point_index, Jc2Jp);\n        GetJpJp(point_index, JpJp);\n        if (std::abs(Determinant(JpJp)) > EPSILON)\n        {\n            Mat3 JpJp_inv = JpJp.inverse();\n            EcEc += Jc1Jp * JpJp_inv * Jc2Jp.transpose();\n            assert(IsNumericalValid(EcEc));\n        }\n    }\n    return true;\n}\n\n/*!\n * @brief A 6x6 EC_-1E^T block w.r.t cameras is occupied iff two cameras share common points.\n */\nvoid BAProblem::EvaluateEcEc(std::vector<size_t> const & pose_indexes, MatX & EcEc) const\n{\n    size_t pose_num = pose_indexes.size();\n    EcEc = MatX::Zero(pose_num * 6, pose_num * 6);\n\n    std::vector<std::pair<size_t, size_t> > pose_pairs;\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        for (size_t j = i; j < pose_num; j++)\n        {\n            pose_pairs.push_back(std::make_pair(i, j));\n        }\n    }\n\n    for (size_t i = 0; i < pose_pairs.size(); i++)\n    {\n        size_t index1 = pose_pairs[i].first;\n        size_t index2 = pose_pairs[i].second;\n        size_t pose_index1 = pose_indexes[index1];\n        size_t pose_index2 = pose_indexes[index2];\n        Mat6 local_EcEc;\n        bool ret = EvaluateEcEc(pose_index1, pose_index2, local_EcEc);\n        if (ret)\n        {\n            EcEc.block(6 * index1, 6 * index2, 6, 6) = local_EcEc;\n            if (pose_index1 != pose_index2)\n                EcEc.block(6 * index2, 6 * index1, 6, 6) = local_EcEc.transpose();\n        }\n    }\n}\n\nvoid BAProblem::EvaluateEcEc(std::vector<size_t> const & pose_indexes, SMat & EcEc) const\n{\n    size_t pose_num = pose_indexes.size();\n    EcEc.resize(pose_num * 6, pose_num * 6);\n    EcEc.reserve(Eigen::VectorXi::Constant(pose_num * 6, max_degree_ * 6));\n\n    std::vector<std::pair<size_t, size_t> > pose_pairs;\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        for (size_t j = i; j < pose_num; j++)\n        {\n            pose_pairs.push_back(std::make_pair(i, j));\n        }\n    }\n\n    for (size_t i = 0; i < pose_pairs.size(); i++)\n    {\n        size_t index1 = pose_pairs[i].first;\n        size_t index2 = pose_pairs[i].second;\n        size_t pose_index1 = pose_indexes[index1];\n        size_t pose_index2 = pose_indexes[index2];\n        Mat6 local_EcEc;\n        bool ret = EvaluateEcEc(pose_index1, pose_index2, local_EcEc);\n        if (ret)\n        {\n            for (size_t j = 0; j < 6; j++)\n                for (size_t k = 0; k < 6; k++)\n                {\n                    EcEc.insert(6 * index1 + j, 6 * index2 + k) = local_EcEc(j, k);\n                    if (pose_index1 != pose_index2)\n                        EcEc.insert(6 * index2 + j, 6 * index1 + k) = local_EcEc(k, j);\n                }\n        }\n    }\n}\n\nvoid BAProblem::EvaluateEcEc(MatX & EcEc) const\n{\n    size_t pose_num = PoseNum();\n    EcEc = MatX::Zero(pose_num * 6, pose_num * 6);\n\n    size_t point_num = PointNum();\n\n    #pragma omp parallel for\n    for (size_t i = 0; i < point_num; i++)\n    {\n        std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::const_iterator it1 = point_projection_map_.find(i);\n        assert(it1 != point_projection_map_.end() && \"[EvaluateEcEc] Point index not found\");\n        std::unordered_map<size_t, size_t> const & map = it1->second;\n        std::unordered_map<size_t, size_t>::const_iterator it2 = map.begin();\n        std::vector<size_t> pose_indexes, proj_indexes;\n        for (; it2 != map.end(); it2++)\n        {\n            size_t pose_index = it2->first;\n            size_t proj_index = it2->second;\n            pose_indexes.push_back(pose_index);\n            proj_indexes.push_back(proj_index);\n        }\n        Mat3 JpJp;\n        GetJpJp(i, JpJp);\n        if (std::abs(Determinant(JpJp)) > EPSILON)\n        {\n            Mat3 JpJp_inv = JpJp.inverse();\n            for (size_t j = 0; j < pose_indexes.size(); j++)\n            {\n                size_t pose_index1 = pose_indexes[j];\n                size_t proj_index1 = proj_indexes[j];\n                Mat63 Jc1Jp;\n                GetJcJp(proj_index1, Jc1Jp);\n                for (size_t k = j; k < pose_indexes.size(); k++)\n                {\n                    size_t pose_index2 = pose_indexes[k];\n                    size_t proj_index2 = proj_indexes[k];\n                    Mat63 Jc2Jp;\n                    GetJcJp(proj_index2, Jc2Jp);\n                    Mat6 ece = Jc1Jp * JpJp_inv * Jc2Jp.transpose();\n                    EcEc.block(pose_index1 * 6, pose_index2 * 6, 6, 6) += ece;\n                    if (pose_index1 != pose_index2)\n                    {\n                        EcEc.block(pose_index2 * 6, pose_index1 * 6, 6, 6) += ece.transpose();\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid BAProblem::EvaluateEcEc(SMat & EcEc) const\n{\n    size_t pose_num = PoseNum();\n    EcEc.resize(pose_num * 6, pose_num * 6);\n    EcEc.reserve(Eigen::VectorXi::Constant(pose_num * 6, max_degree_ * 6));\n\n    std::vector<std::pair<size_t, size_t> > pose_pairs;\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        for (size_t j = i; j < pose_num; j++)\n        {\n            pose_pairs.push_back(std::make_pair(i, j));\n        }\n    }\n\n    for (size_t i = 0; i < pose_pairs.size(); i++)\n    {\n        size_t index1 = pose_pairs[i].first;\n        size_t index2 = pose_pairs[i].second;\n        size_t pose_index1 = index1;\n        size_t pose_index2 = index2;\n        Mat6 local_EcEc;\n        bool ret = BAProblem::EvaluateEcEc(pose_index1, pose_index2, local_EcEc);\n        if (ret)\n        {\n            for (size_t j = 0; j < 6; j++)\n                for (size_t k = 0; k < 6; k++)\n                {\n                    EcEc.insert(6 * index1 + j, 6 * index2 + k) = local_EcEc(j, k);\n                    if (pose_index1 != pose_index2)\n                        EcEc.insert(6 * index2 + j, 6 * index1 + k) = local_EcEc(k, j);\n                }\n        }\n    }\n}\n\n/*!\n * @brief EcC^-1w, w = -Jp^Te\n */\nvoid BAProblem::EvaluateEcw(size_t pose_index, Vec6 & Ecw) const\n{\n    Ecw = Vec6::Zero();\n    std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::const_iterator it1 = pose_projection_map_.find(pose_index);\n    assert(it1 != pose_projection_map_.end() && \"[EvaluateECw] Pose index not found\");\n    std::unordered_map<size_t, size_t> const & map = it1->second;\n    std::unordered_map<size_t, size_t>::const_iterator it2 = map.begin();\n    for (; it2 != map.end(); it2++)\n    {\n        size_t point_index = it2->first;\n        size_t proj_index = it2->second;\n        Mat63 JcJp;\n        Mat3 JpJp;\n        Vec3 Jpe;\n        GetJcJp(proj_index, JcJp);\n        GetJpJp(point_index, JpJp);\n        GetJpe(point_index, Jpe);\n\n        if (std::abs(Determinant(JpJp)) > EPSILON)\n        {\n            Mat3 JpJp_inv = JpJp.inverse();\n            Ecw += JcJp * JpJp_inv * (-Jpe);\n        }\n    }\n}\n\nvoid BAProblem::EvaluateEcw()\n{\n    ClearECw();\n\n    size_t pose_num = PoseNum();\n#pragma omp parallel for\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        Vec6 local_Ecw;\n        EvaluateEcw(i, local_Ecw);\n        SetECw(i, local_Ecw);\n    }\n}\n\n\n/*!\n * @brief Read Schur Complement Trick in https://zlthinker.github.io/optimization-for-least-square-problem#schur-complement-trick\n */\nvoid BAProblem::EvaluateB(MatX & B) const\n{\n    GetJcJc(B);\n    return;\n}\n\n/*!\n * @brief S = B - EC^-1E^T, B = Jc^TJc, C = Jp^TJp, E = Jc^TJp, omitting intrinsic blocks here\n */\nvoid BAProblem::EvaluateSchurComplement(std::vector<size_t> const & pose_indexes, MatX & S) const\n{\n    MatX JcJc, ECE;\n    GetJcJc(pose_indexes, JcJc);\n    EvaluateEcEc(pose_indexes, ECE);\n    S = JcJc - ECE;\n}\n\nvoid BAProblem::EvaluateSchurComplement(std::vector<size_t> const & pose_indexes, SMat & S) const\n{\n    SMat JcJc, ECE;\n    size_t pose_num = PoseNum();\n    S.resize(pose_num * 6, pose_num * 6);\n    S.reserve(Eigen::VectorXi::Constant(pose_num * 6, max_degree_ * 6));\n\n    GetJcJc(pose_indexes, JcJc);\n    EvaluateEcEc(pose_indexes, ECE);\n    S = JcJc - ECE;\n}\n\n/*!\n * @brief Schur complement including pose blocks and intrinsic blocks\n */\nvoid BAProblem::EvaluateSchurComplement(MatX & S) const\n{\n    MatX B, EE;\n    EvaluateB(B);\n    EvaluateEcEc(EE);\n    S = B - EE;\n}\n\nvoid BAProblem::EvaluateSchurComplement(SMat & S) const\n{\n    SMat B, EE;\n\n    size_t pose_num = PoseNum();\n    std::vector<size_t> pose_indexes(pose_num);\n    std::iota(pose_indexes.begin(), pose_indexes.end(), 0);\n    GetJcJc(pose_indexes, B);\n    EvaluateEcEc(EE);\n    S = B - EE;\n}\n\n/*!\n * @brief S dy = b = -Jc^Te - EC^-1w, omitting intrinsic blocks here\n */\nbool BAProblem::EvaluateDeltaPose(std::vector<size_t> const & pose_indexes, VecX & dy) const\n{\n    bool ret;\n    if (pose_indexes.size() < 5000)\n    {\n        MatX S;\n        VecX Jce, ECw, b;\n        EvaluateSchurComplement(pose_indexes, S);\n        GetJce(pose_indexes, Jce);\n        GetEcw(pose_indexes, ECw);\n        b = -Jce - ECw;\n        ret = SolveLinearSystem(S, b, dy);\n    }\n    else\n    {\n        SMat S;\n        VecX Jce, ECw, b;\n        EvaluateSchurComplement(pose_indexes, S);\n        GetJce(pose_indexes, Jce);\n        GetEcw(pose_indexes, ECw);\n        b = -Jce - ECw;\n        ret = SolveLinearSystem(S, b, dy);\n    }\n\n    return ret;\n}\n\nbool BAProblem::EvaluateDeltaPose(std::vector<size_t> const & pose_indexes)\n{\n    VecX dy;\n    if (!EvaluateDeltaPose(pose_indexes, dy))\n    {\n        std::cout << \"[EvaluateDeltaPose] Fail in solver linear system.\\n\";\n        return false;\n    }\n    for (size_t i = 0; i < pose_indexes.size(); i++)\n    {\n        size_t pose_index = pose_indexes[i];\n        Vec3 delta_angle_axis = dy.segment(i * 6, 3);\n        Vec3 delta_translation = dy.segment(i * 6 + 3, 3);\n        pose_block_.SetDeltaPose(pose_index, delta_angle_axis, delta_translation);\n    }\n    return true;\n}\n\nbool BAProblem::EvaluateDeltaPose()\n{\n    std::vector<size_t> pose_indexes(PoseNum());\n    std::iota(pose_indexes.begin(), pose_indexes.end(), 0);\n    return EvaluateDeltaPose(pose_indexes);\n}\n\n/*!\n * @brief E^T dy\n */\nvoid BAProblem::EvaluateEDeltaPose(size_t point_index, Vec3 & Edy) const\n{\n    Edy = Vec3::Zero();\n    std::unordered_map<size_t, std::unordered_map<size_t, size_t> >::const_iterator it1 = point_projection_map_.find(point_index);\n    assert(it1 != point_projection_map_.end() && \"[EvaluateEDeltaPose] Point index not found\");\n    std::unordered_map<size_t, size_t> const & map = it1->second;\n    std::unordered_map<size_t, size_t>::const_iterator it2 = map.begin();\n    for (; it2 != map.end(); it2++)\n    {\n        size_t pose_index = it2->first;\n        size_t proj_index = it2->second;\n        Mat63 JcJp;\n        Vec6 dy;\n        GetJcJp(proj_index, JcJp);\n        pose_block_.GetDeltaPose(pose_index, dy);\n        Edy += JcJp.transpose() * dy;\n    }\n}\n\nvoid BAProblem::EvaluateEDelta(size_t point_index, Vec3 & Edy) const\n{\n    Edy = Vec3::Zero();\n\n    EvaluateEDeltaPose(point_index, Edy);\n}\n\n/*!\n * @brief dz = C^-1 (-Jp^Te -E^T dy), C = Jp^TJp\n */\nvoid BAProblem::EvaluateDeltaPoint(size_t point_index, Vec3 & dz)\n{\n    Mat3 JpJp;\n    Vec3 Jpe, Edy;\n    GetJpJp(point_index, JpJp);\n    GetJpe(point_index, Jpe);\n    EvaluateEDelta(point_index, Edy);\n    if (std::abs(Determinant(JpJp)) > EPSILON)\n    {\n        Mat3 JpJp_inv = JpJp.inverse();\n        dz = JpJp_inv * (-Jpe - Edy);\n        assert(IsNumericalValid(dz));\n    }\n    else\n    {\n        dz = Vec3::Zero();\n    }\n}\n\nvoid BAProblem::EvaluateDeltaPoint()\n{\n    size_t point_num = PointNum();\n    for (size_t i = 0; i < point_num; i++)\n    {\n        Vec3 dz;\n        EvaluateDeltaPoint(i, dz);\n        point_block_.SetDeltaPoint(i, dz);\n    }\n}\n\nvoid BAProblem::UpdateParam()\n{\n    pose_block_.UpdatePose();\n    point_block_.UpdatePoint();\n}\n\nvoid BAProblem::ClearUpdate()\n{\n    pose_block_.ClearUpdate();\n    point_block_.ClearUpdate();\n}\n\nvoid BAProblem::ClearResidual()\n{\n    std::fill(residual_, residual_ + 2 * ProjectionNum(), 0.0);\n}\n\nvoid BAProblem::ClearPoseJacobian()\n{\n    std::fill(pose_jacobian_, pose_jacobian_ + 2 * ProjectionNum() * 6, 0.0);\n}\n\nvoid BAProblem::ClearPointJacobian()\n{\n    std::fill(point_jacobian_, point_jacobian_ + 2 * ProjectionNum() * 3, 0.0);\n}\n\nvoid BAProblem::ClearJcJc()\n{\n    std::fill(pose_jacobian_square_, pose_jacobian_square_ + PoseNum() * 6 * 6, 0.0);\n}\n\nvoid BAProblem::ClearJpJp()\n{\n    std::fill(point_jacobian_square_, point_jacobian_square_ + PointNum() * 3 * 3, 0.0);\n}\n\nvoid BAProblem::ClearJcJp()\n{\n    std::fill(pose_point_jacobian_product_, pose_point_jacobian_product_ + ProjectionNum() * 6 * 3, 0.0);\n}\n\nvoid BAProblem::ClearJce()\n{\n    std::fill(pose_gradient_, pose_gradient_ + PoseNum() * 6, 0.0);\n}\n\nvoid BAProblem::ClearJpe()\n{\n    std::fill(point_gradient_, point_gradient_ + PointNum() * 3, 0.0);\n}\n\nvoid BAProblem::ClearECw()\n{\n    std::fill(Ec_Cinv_w_, Ec_Cinv_w_ + PoseNum() * 6, 0.0);\n}\n\n/*!\n * @brief In LM algorithm, the \"Hessian\" matrix's diagonal is augmented as (H + lambda I)x = b\n */\nvoid BAProblem::GetDiagonal(VecX & diagonal) const\n{\n    size_t pose_num = PoseNum();\n    size_t point_num = PointNum();\n    diagonal.resize(6 * pose_num + 3 * point_num);\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        diagonal(6 * i) = pose_jacobian_square_[6 * 6 * i];\n        diagonal(6 * i + 1) = pose_jacobian_square_[6 * 6 * i + 7];\n        diagonal(6 * i + 2) = pose_jacobian_square_[6 * 6 * i + 14];\n        diagonal(6 * i + 3) = pose_jacobian_square_[6 * 6 * i + 21];\n        diagonal(6 * i + 4) = pose_jacobian_square_[6 * 6 * i + 28];\n        diagonal(6 * i + 5) = pose_jacobian_square_[6 * 6 * i + 35];\n    }\n    for (size_t i = 0; i < point_num; i++)\n    {\n        diagonal(6 * pose_num + 3 * i) = point_jacobian_square_[3 * 3 * i];\n        diagonal(6 * pose_num + 3 * i + 1) = point_jacobian_square_[3 * 3 * i + 4];\n        diagonal(6 * pose_num + 3 * i + 2) = point_jacobian_square_[3 * 3 * i + 8];\n    }\n}\n\nvoid BAProblem::SetDiagonal(VecX const & diagonal)\n{\n    size_t pose_num = PoseNum();\n    size_t point_num = PointNum();\n    assert(pose_num * 6 + point_num * 3 == diagonal.size() && \"[SetDiagonal] Size disagrees\");\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        pose_jacobian_square_[6 * 6 * i] = diagonal(6 * i);\n        pose_jacobian_square_[6 * 6 * i + 7] = diagonal(6 * i + 1);\n        pose_jacobian_square_[6 * 6 * i + 14] = diagonal(6 * i + 2);\n        pose_jacobian_square_[6 * 6 * i + 21] = diagonal(6 * i + 3);\n        pose_jacobian_square_[6 * 6 * i + 28] = diagonal(6 * i + 4);\n        pose_jacobian_square_[6 * 6 * i + 35] = diagonal(6 * i + 5);\n    }\n    for (size_t i = 0; i < point_num; i++)\n    {\n        point_jacobian_square_[3 * 3 * i] = diagonal(6 * pose_num + 3 * i);\n        point_jacobian_square_[3 * 3 * i + 4] = diagonal(6 * pose_num + 3 * i + 1);\n        point_jacobian_square_[3 * 3 * i + 8] = diagonal(6 * pose_num + 3 * i + 2);\n    }\n}\n\nvoid BAProblem::GetPoseDiagonal(VecX & diagonal) const\n{\n    size_t pose_num = PoseNum();\n    diagonal.resize(6 * pose_num);\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        diagonal(6 * i) = pose_jacobian_square_[6 * 6 * i];\n        diagonal(6 * i + 1) = pose_jacobian_square_[6 * 6 * i + 7];\n        diagonal(6 * i + 2) = pose_jacobian_square_[6 * 6 * i + 14];\n        diagonal(6 * i + 3) = pose_jacobian_square_[6 * 6 * i + 21];\n        diagonal(6 * i + 4) = pose_jacobian_square_[6 * 6 * i + 28];\n        diagonal(6 * i + 5) = pose_jacobian_square_[6 * 6 * i + 35];\n    }\n}\n\nvoid BAProblem::SetPoseDiagonal(VecX const & diagonal)\n{\n    size_t pose_num = PoseNum();\n    assert(pose_num * 6 == diagonal.size() && \"[SetPoseDiagonal] Size disagrees\");\n    for (size_t i = 0; i < pose_num; i++)\n    {\n        pose_jacobian_square_[6 * 6 * i] = diagonal(6 * i);\n        pose_jacobian_square_[6 * 6 * i + 7] = diagonal(6 * i + 1);\n        pose_jacobian_square_[6 * 6 * i + 14] = diagonal(6 * i + 2);\n        pose_jacobian_square_[6 * 6 * i + 21] = diagonal(6 * i + 3);\n        pose_jacobian_square_[6 * 6 * i + 28] = diagonal(6 * i + 4);\n        pose_jacobian_square_[6 * 6 * i + 35] = diagonal(6 * i + 5);\n    }\n}\n\nvoid BAProblem::GetPointDiagonal(VecX & diagonal) const\n{\n    size_t point_num = PointNum();\n    diagonal.resize(3 * point_num);\n    for (size_t i = 0; i < point_num; i++)\n    {\n        diagonal(3 * i) = point_jacobian_square_[3 * 3 * i];\n        diagonal(3 * i + 1) = point_jacobian_square_[3 * 3 * i + 4];\n        diagonal(3 * i + 2) = point_jacobian_square_[3 * 3 * i + 8];\n    }\n}\n\nvoid BAProblem::SetPointDiagonal(VecX const & diagonal)\n{\n    size_t point_num = PointNum();\n    assert(point_num * 3 == diagonal.size() && \"[SetPointDiagonal] Size disagrees\");\n    for (size_t i = 0; i < point_num; i++)\n    {\n        point_jacobian_square_[3 * 3 * i] = diagonal(3 * i);\n        point_jacobian_square_[3 * 3 * i + 4] = diagonal(3 * i + 1);\n        point_jacobian_square_[3 * 3 * i + 8] = diagonal(3 * i + 2);\n    }\n}\n\nvoid BAProblem::Delete()\n{\n    if (residual_ != NULL)                              delete [] residual_;\n    if (pose_jacobian_ != NULL)                         delete [] pose_jacobian_;\n    if (point_jacobian_ != NULL)                        delete [] point_jacobian_;\n    if (pose_jacobian_square_ != NULL)                  delete [] pose_jacobian_square_;\n    if (point_jacobian_square_ != NULL)                 delete [] point_jacobian_square_;\n    if (pose_point_jacobian_product_ != NULL)           delete [] pose_point_jacobian_product_;\n    if (pose_gradient_ != NULL)                         delete [] pose_gradient_;\n    if (point_gradient_ != NULL)                        delete [] point_gradient_;\n    if (Ec_Cinv_w_ != NULL)                              delete [] Ec_Cinv_w_;\n}\n\n/*!\n * @brief Ax = b\n * @return If the solution contains NaN values, e.g. due to singular A, return false.\n */\nbool BAProblem::SolveLinearSystem(MatX const & A, VecX const & b, VecX & x) const\n{\n    bool ret = false;\n\n    switch (linear_solver_type_)\n    {\n    case SPARSE:\n        ret = SolveLinearSystemSparse(A.sparseView(), b, x);\n        break;\n    case DENSE:\n        ret = SolveLinearSystemDense(A, b, x);\n        break;\n    case ITERATIVE:\n        ret = SolveLinearSystemIterative(A.sparseView(), b, x);\n        break;\n    case ADAPTIVE:\n    {\n        size_t dimension = b.rows() / 6;\n        if (dimension < 300)\n        {\n            ret = SolveLinearSystemDense(A, b, x);\n        }\n        else\n        {\n            ret = SolveLinearSystemIterative(A.sparseView(), b, x);\n        }\n        break;\n    }\n    default:\n    {\n        std::cout << \"No linear solver stype specified.\\n\";\n        exit(0);\n    }\n    }\n    return ret;\n}\n\nbool BAProblem::SolveLinearSystem(SMat const & A, VecX const & b, VecX & x) const\n{\n    bool ret = false;\n\n    switch (linear_solver_type_)\n    {\n    case SPARSE:\n    {\n        ret = SolveLinearSystemSparse(A, b, x);\n        break;\n    }\n    case DENSE:\n    {\n        MatX A_dense = MatX(A);\n        ret = SolveLinearSystemDense(A_dense, b, x);\n        break;\n    }\n    case ITERATIVE:\n    {\n        ret = SolveLinearSystemIterative(A, b, x);\n        break;\n    }\n    case ADAPTIVE:\n    {\n        size_t dimension = b.rows() / 6;\n        if (dimension < 300)\n        {\n            MatX A_dense = MatX(A);\n            ret = SolveLinearSystemDense(A_dense, b, x);\n        }\n        else\n        {\n            ret = SolveLinearSystemIterative(A, b, x);\n        }\n        break;\n    }\n    default:\n    {\n        std::cout << \"No linear solver stype specified.\\n\";\n        exit(0);\n    }\n    }\n\n    return ret;\n}\n\n/*!\n * @brief Ax = b\n */\nbool BAProblem::SolveLinearSystemDense(MatX const & A, VecX const & b, VecX & x) const\n{\n    // QR is more accurate than LDLT, but slower in efficiency.\n    x = A.ldlt().solve(b);\n    //    x = A.colPivHouseholderQr().solve(b);\n    return IsNumericalValid(x);\n}\n\nbool BAProblem::SolveLinearSystemSparse(SMat const & A, VecX const & b, VecX & x) const\n{\n    SimplicialLLT<SparseMatrix<DT> > solver;\n    x = solver.compute(A).solve(b);\n    return IsNumericalValid(x);\n}\n\nbool BAProblem::SolveLinearSystemIterative(SMat const & A, VecX const & b, VecX & x) const\n{\n    ConjugateGradient<SparseMatrix<DT>, Lower|Upper> cg;\n    cg.setMaxIterations(500);\n    cg.setTolerance(1e-6);\n    x = cg.compute(A).solve(b);\n    return IsNumericalValid(x);\n}\n\n\n", "meta": {"hexsha": "c8cfc642aa9c6119bb49198ac7793dbf3b16b0a6", "size": 59572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/baproblem.cpp", "max_stars_repo_name": "zlthinker/STBA", "max_stars_repo_head_hexsha": "c0034d67018c9b7a72459821e9e9ad46870b6292", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 175.0, "max_stars_repo_stars_event_min_datetime": "2020-08-02T11:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T04:54:36.000Z", "max_issues_repo_path": "src/baproblem.cpp", "max_issues_repo_name": "zlthinker/STBA", "max_issues_repo_head_hexsha": "c0034d67018c9b7a72459821e9e9ad46870b6292", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-02T08:42:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T08:42:11.000Z", "max_forks_repo_path": "src/baproblem.cpp", "max_forks_repo_name": "zlthinker/STBA", "max_forks_repo_head_hexsha": "c0034d67018c9b7a72459821e9e9ad46870b6292", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2020-08-02T13:04:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T04:54:28.000Z", "avg_line_length": 33.7518413598, "max_line_length": 135, "alphanum_fraction": 0.627459209, "num_tokens": 17018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19726666305294407}}
{"text": "// Copyright (c) 2015-2018 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 \"filtered_read_fraction.hpp\"\n\n#include <iterator>\n#include <algorithm>\n\n#include <boost/variant.hpp>\n\nnamespace octopus { namespace csr {\n\nconst std::string FilteredReadFraction::name_ = \"FRF\";\n\nFilteredReadFraction::FilteredReadFraction(bool aggregate_samples)\n: calling_depth_ {false, aggregate_samples}\n, filtering_depth_ {true, aggregate_samples}\n{}\n\nstd::unique_ptr<Measure> FilteredReadFraction::do_clone() const\n{\n    return std::make_unique<FilteredReadFraction>(*this);\n}\n\nMeasure::ResultType FilteredReadFraction::do_evaluate(const VcfRecord& call, const FacetMap& facets) const\n{\n    if (filtering_depth_.cardinality() == Measure::ResultCardinality::num_samples) {\n        const auto calling_depth   = boost::get<std::vector<std::size_t>>(calling_depth_.evaluate(call, facets));\n        const auto filtering_depth = boost::get<std::vector<std::size_t>>(filtering_depth_.evaluate(call, facets));\n        assert(calling_depth.size() == filtering_depth.size());\n        std::vector<double> result(calling_depth.size());\n        std::transform(std::cbegin(calling_depth), std::cend(calling_depth), std::cbegin(filtering_depth), std::begin(result),\n                       [] (auto cd, auto fd) { return fd > 0 ? 1.0 - (static_cast<double>(cd) / fd) : 0; });\n        return result;\n    } else {\n        const auto filtering_depth = boost::get<std::size_t>(filtering_depth_.evaluate(call, facets));\n        double result {0};\n        if (filtering_depth > 0) {\n            auto calling_depth = boost::get<std::size_t>(calling_depth_.evaluate(call, facets));\n            result = 1.0 - (static_cast<double>(calling_depth) / filtering_depth);\n        }\n        return result;\n    }\n}\n\nMeasure::ResultCardinality FilteredReadFraction::do_cardinality() const noexcept\n{\n    return filtering_depth_.cardinality();\n}\n\nconst std::string& FilteredReadFraction::do_name() const\n{\n    return name_;\n}\n\nstd::string FilteredReadFraction::do_describe() const\n{\n    return \"Fraction of reads filtered for calling\";\n}\n\nstd::vector<std::string> FilteredReadFraction::do_requirements() const\n{\n    return filtering_depth_.requirements();\n}\n\nbool FilteredReadFraction::is_equal(const Measure& other) const noexcept\n{\n    return calling_depth_ == static_cast<const FilteredReadFraction&>(other).calling_depth_;\n}\n\n} // namespace csr\n} // namespace octopus\n", "meta": {"hexsha": "6ab4b8eee361f0ed39b1d6bf68b3200aed738ce5", "size": 2488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/csr/measures/filtered_read_fraction.cpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-21T23:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T23:34:28.000Z", "max_issues_repo_path": "src/core/csr/measures/filtered_read_fraction.cpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/csr/measures/filtered_read_fraction.cpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.0821917808, "max_line_length": 126, "alphanum_fraction": 0.7150321543, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1972623190926713}}
{"text": "#include <Eigen/Dense>\n\n#include <fstream>\n#include <vector>\n#include <thread>\n\n#include \"LevRuntimeInterface.h\"\n#include \"GridRemover.h\"\n#include \"LevSceneNode.h\"\n#include \"LevSceneObject.h\"\n#include \"LevRAttrObjectColor.h\"\n#include \"LevScheduler.h\"\n#include \"ViewScheduler.h\"\n#include \"SceneGraph.h\"\n#include \"AABB.h\"\n#include \"LevMeshObject.h\"\n#include \"MeshImpl.h\"\n\nusing namespace Leviathan;\n\nbool LoadFrameData(const char * dataFilePath, std::vector<Point3D>& result)\n{\n\tstd::fstream frameFile(dataFilePath, std::ios::in);\n\tif (!frameFile.is_open()) return false;\n\n\tchar line[300];\n\tunsigned vertexCount = 0;\n\twhile (true)\n\t{\n\t\tframeFile.getline(line, 300);\n\t\tstd::string _line = line;\n\t\tif (_line.find(\"element vertex\") != std::string::npos)\n\t\t{\n\t\t\tstd::string vertexCountStr = _line.substr(15, _line.length() - 15);\n\t\t\tvertexCount = std::atoi(vertexCountStr.c_str());\n\t\t}\n\n\t\tif (_line == \"end_header\") break;\n\t}\n\n\t// Skip first two line\n\tframeFile.getline(line, sizeof(line));\n\tframeFile.getline(line, sizeof(line));\n\n\t//Leviathan::DynamicArray<float> databuffer(vertexCount * 6 * sizeof(float));\n\tfloat* _data = new float[vertexCount * 6];\n\n\tauto pCoord = _data;\n\tauto pNormal = _data + vertexCount * 3;\n\n\tfor (unsigned i = 0; i < vertexCount; i++)\n\t{\n\t\tfloat vertexData[7];\n\t\tfor (unsigned i = 0; i < 7; i++)\n\t\t{\n\t\t\tframeFile >> vertexData[i];\n\t\t}\n\n\t\tmemcpy(pCoord + 3 * i, vertexData + 1, 3 * sizeof(float));\n\t\tmemcpy(pNormal + 3 * i, vertexData + 4, 3 * sizeof(float));\n\n\t\tresult.push_back(std::move(Point3D(vertexData + 1)));\n\t}\n\n\treturn true;\n}\n\nint main(int argc, char** argv)\n{\n\tif (argc < 2 || !argv[1])\n\t{\n\t\treturn -1;\n\t}\n\n\tstd::thread renderer([]\n\t\t{\n\t\t\tLevRuntimeInterface::Init(1080, 720, 0);\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tLevRuntimeInterface::Update();\n\t\t\t}\n\t\t});\n\n\trenderer.detach();\n\n\tint nCount = 100;\n\tint nCurrent = 0;\n\n\tstd::string path = argv[1];\n\tpath += \"\\\\frame_%04d.ply\";\n\tchar buf[300];\n\n\tstd::vector<Point3D> points;\n\tstd::vector<Point3D> tsdfFrame;\n\tGridRemover remover;\n\tauto& viewScheduler = LevRuntimeInterface::GetViewScheduler();\n\n\tstd::vector<LPtr<Scene::LevSceneNode>> meshes;\n\n\twhile (true)\n\t{\n\t\t// Load\n\t\tif(nCount > nCurrent)\n\t\t{\n\t\t\tmemset(buf, 0, 300);\n\t\t\tsnprintf(buf, 300, path.c_str(), nCurrent++);\n\t\t\tLPtr<Scene::LevSceneNode> pMeshNode;\n\t\t\tLevRuntimeInterface::LoadPointCloud(buf, pMeshNode);\n\t\t\tmeshes.push_back(pMeshNode);\n\t\t\tstd::vector<Point3D> frame;\n\t\t\tLoadFrameData(buf, frame);\n\t\t\tpoints.insert(points.end(), frame.begin(), frame.end());\n\n\t\t\tif (nCurrent == 50)\n\t\t\t{\n\t\t\t\ttsdfFrame = frame;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tremover.SetTSDFCloud(tsdfFrame);\n\t\tstd::vector<bool> testResult;\n\t\tremover.TestOverlap(Eigen::Matrix4f::Identity(), points, testResult);\n\n\t\t// Update original data\n\t\tunsigned currentPointIndex = 0;\n\t\tfor (auto& mesh : meshes)\n\t\t{\n\t\t\tauto& objDesc = mesh->GetNodeData()->GetObjDesc();\n\t\t\tif (objDesc.GetType() & LevSceneObjectDescType::ELSOD_MESH == 0)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tScene::LevMeshObject* pMesh = dynamic_cast<Scene::LevMeshObject*>(&objDesc);\n\t\t\tif (!pMesh)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tScene::LevObjectColorData colorData;\n\t\t\tcolorData.pure_color[0] = 0.1f;\n\t\t\tcolorData.pure_color[1] = 0.5f;\n\t\t\tcolorData.pure_color[2] = 0.1f;\n\n\t\t\tauto _updateColor = [pMesh, &colorData](Leviathan::CoPullType<int>&)\n\t\t\t{\n\t\t\t\tpMesh->SetColorData(Scene::ELOCT_PURE_COLOR, colorData);\n\t\t\t};\n\n\t\t\tviewScheduler.DoSyncTask(_updateColor);\n\n// \t\t\tauto& attributes = mesh->GetNodeData()->GetObjAttributes();\n// \n// \t\t\tfor (auto& attr : attributes)\n// \t\t\t{\n// \t\t\t\tif (attr->GetType() != Scene::ELSOAT_RENDER)\n// \t\t\t\t{\n// \t\t\t\t\tcontinue;\n// \t\t\t\t}\n// \n// \t\t\t\tScene::LevRAttrObjectColor* pColorAttr = dynamic_cast<Scene::LevRAttrObjectColor*>(attr.Get());\n// \t\t\t\tif (pColorAttr)\n// \t\t\t\t{\n// \t\t\t\t\t// Reset color data array.\n// \t\t\t\t\tLEV_ASSERT(pColorAttr->GetColorType() == Scene::ELOCT_COLOR_ARRAY);\n// \t\t\t\t\tauto* pColorArrayData = pColorAttr->GetColorData().color_array;\n// \n// \t\t\t\t\tauto _updateColorArray = [&testResult, &currentPointIndex, pColorAttr, pColorArrayData](Leviathan::CoPullType<int>&)\n// \t\t\t\t\t{\n// \t\t\t\t\t\tauto vertexCount = pColorAttr->GetColorData().color_array_byte_size / (3 * sizeof(float));\n// \n// \t\t\t\t\t\tfor (unsigned i = 0; i < vertexCount; i++)\n// \t\t\t\t\t\t{\n// \t\t\t\t\t\t\tfloat* pcolor = pColorArrayData + 3 * i;\n// \t\t\t\t\t\t\tif (testResult[currentPointIndex + i])\n// \t\t\t\t\t\t\t{\n// \t\t\t\t\t\t\t\tpcolor[0] = 0.0f;\n// \t\t\t\t\t\t\t\tpcolor[1] = 0.0f;\n// \t\t\t\t\t\t\t\tpcolor[2] = 0.0f;\n// \t\t\t\t\t\t\t}\n// \t\t\t\t\t\t}\n// \n// \t\t\t\t\t\tcurrentPointIndex += vertexCount;\n// \t\t\t\t\t};\n// \n// \t\t\t\t\tviewScheduler.DoSyncTask(_updateColorArray);\n//\t\t\t\t}\n//\t\t\t}\n\n\t\t\tviewScheduler.DoTask([&mesh](Leviathan::CoPullType<int>&)\n\t\t\t{\n\t\t\t\tmesh->GetNodeData()->SetState(Leviathan::Scene::ELSOS_UPDATE);\n\t\t\t});\n\t\t}\n\n\t\t// Add Grid geometry\n\t\tauto& grids = remover.GetGridBars();\n\t\tfor (auto& grid : grids)\n\t\t{\n\t\t\tfloat min[3], max[3];\n\t\t\tgrid.GetBoxRange(min, max);\n\n\t\t\tmin[2] = grid.tsdf;\n\t\t\t//min[2] = -2.0f;\n\t\t\tmax[2] = 0.0f;\n\n\t\t\tAABB aabb(min, max);\n\n\t\t\tfloat _vertexCoord[] =\n\t\t\t{\n\t\t\t\tmin[0], min[1], min[2],\n\t\t\t\tmin[0], min[1], max[2],\n\t\t\t\tmin[0], max[1], min[2],\n\t\t\t\tmin[0], max[1], max[2],\n\t\t\t\tmax[0], min[1], min[2],\n\t\t\t\tmax[0], min[1], max[2],\n\t\t\t\tmax[0], max[1], min[2],\n\t\t\t\tmax[0], max[1], max[2],\n\t\t\t};\n\n\t\t\tunsigned _index[] =\n\t\t\t{\n\t\t\t\t0,2,3,\n\t\t\t\t0,3,1,\n\t\t\t\t0,1,5,\n\t\t\t\t0,5,4,\n\t\t\t\t0,2,6,\n\t\t\t\t0,6,4,\n\t\t\t\t7,4,2,\n\t\t\t\t7,2,3,\n\t\t\t\t7,5,4,\n\t\t\t\t7,4,6,\n\t\t\t\t7,5,1,\n\t\t\t\t7,1,3\n\t\t\t};\n\n\t\t\tLPtr<MeshImpl> pMesh = new MeshImpl(8, 12);\n\t\t\tpMesh->SetVertexCoordData(_vertexCoord);\n\t\t\tpMesh->SetPrimitiveIndexData(_index);\n\n\t\t\tviewScheduler.LoadCustomMesh(TryCast<MeshImpl, IMesh>(pMesh));\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tstd::chrono::milliseconds timespan(100000);\n\tstd::this_thread::sleep_for(timespan);\n\n\treturn 0;\n}", "meta": {"hexsha": "e641bd874a63805f47b62d1b6548b9ea574d700c", "size": 5712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LeviathanGirdRemoverTest/main.cpp", "max_stars_repo_name": "wakare/Leviathan", "max_stars_repo_head_hexsha": "8a488f014d6235c5c6e6422c9f53c82635b7ebf7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T13:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-16T05:56:21.000Z", "max_issues_repo_path": "src/LeviathanGirdRemoverTest/main.cpp", "max_issues_repo_name": "wakare/Leviathan", "max_issues_repo_head_hexsha": "8a488f014d6235c5c6e6422c9f53c82635b7ebf7", "max_issues_repo_licenses": ["MIT"], "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/LeviathanGirdRemoverTest/main.cpp", "max_forks_repo_name": "wakare/Leviathan", "max_forks_repo_head_hexsha": "8a488f014d6235c5c6e6422c9f53c82635b7ebf7", "max_forks_repo_licenses": ["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.5770750988, "max_line_length": 124, "alphanum_fraction": 0.6242997199, "num_tokens": 1872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1972623141249674}}
{"text": "#include \"engine/plugins/tile.hpp\"\n#include \"engine/plugins/plugin_base.hpp\"\n\n#include \"util/coordinate_calculation.hpp\"\n#include \"util/string_view.hpp\"\n#include \"util/vector_tile.hpp\"\n#include \"util/web_mercator.hpp\"\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/multi/geometries/multi_linestring.hpp>\n\n#include <protozero/pbf_writer.hpp>\n#include <protozero/varint.hpp>\n\n#include <algorithm>\n#include <numeric>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include <cmath>\n#include <cstdint>\n\nnamespace osrm\n{\nnamespace engine\n{\nnamespace plugins\n{\n\nconstexpr const static int MIN_ZOOM_FOR_TURNS = 15;\n\nnamespace\n{\n\nusing RTreeLeaf = datafacade::BaseDataFacade::RTreeLeaf;\n// TODO: Port all this encoding logic to https://github.com/mapbox/vector-tile, which wasn't\n// available when this code was originally written.\n\n// Simple container class for WGS84 coordinates\ntemplate <typename T> struct Point final\n{\n    Point(T _x, T _y) : x(_x), y(_y) {}\n\n    const T x;\n    const T y;\n};\n\n// Simple container to hold a bounding box\nstruct BBox final\n{\n    BBox(const double _minx, const double _miny, const double _maxx, const double _maxy)\n        : minx(_minx), miny(_miny), maxx(_maxx), maxy(_maxy)\n    {\n    }\n\n    double width() const { return maxx - minx; }\n    double height() const { return maxy - miny; }\n\n    const double minx;\n    const double miny;\n    const double maxx;\n    const double maxy;\n};\n\n// Simple container for integer coordinates (i.e. pixel coords)\nstruct point_type_i final\n{\n    point_type_i(std::int64_t _x, std::int64_t _y) : x(_x), y(_y) {}\n\n    const std::int64_t x;\n    const std::int64_t y;\n};\n\nusing FixedPoint = Point<std::int32_t>;\nusing FloatPoint = Point<double>;\n\nusing FixedLine = std::vector<FixedPoint>;\nusing FloatLine = std::vector<FloatPoint>;\n\n// We use boost::geometry to clip lines/points that are outside or cross the boundary\n// of the tile we're rendering.  We need these types defined to use boosts clipping\n// logic\ntypedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> point_t;\ntypedef boost::geometry::model::linestring<point_t> linestring_t;\ntypedef boost::geometry::model::box<point_t> box_t;\ntypedef boost::geometry::model::multi_linestring<linestring_t> multi_linestring_t;\nconst static box_t clip_box(point_t(-util::vector_tile::BUFFER, -util::vector_tile::BUFFER),\n                            point_t(util::vector_tile::EXTENT + util::vector_tile::BUFFER,\n                                    util::vector_tile::EXTENT + util::vector_tile::BUFFER));\n\n// from mapnik-vector-tile\n// Encodes a linestring using protobuf zigzag encoding\ninline bool encodeLinestring(const FixedLine &line,\n                             protozero::packed_field_uint32 &geometry,\n                             std::int32_t &start_x,\n                             std::int32_t &start_y)\n{\n    const std::size_t line_size = line.size();\n    if (line_size < 2)\n    {\n        return false;\n    }\n\n    const unsigned lineto_count = static_cast<const unsigned>(line_size) - 1;\n\n    auto pt = line.begin();\n    const constexpr int MOVETO_COMMAND = 9;\n    geometry.add_element(MOVETO_COMMAND); // move_to | (1 << 3)\n    geometry.add_element(protozero::encode_zigzag32(pt->x - start_x));\n    geometry.add_element(protozero::encode_zigzag32(pt->y - start_y));\n    start_x = pt->x;\n    start_y = pt->y;\n    // This means LINETO repeated N times\n    // See: https://github.com/mapbox/vector-tile-spec/tree/master/2.1#example-command-integers\n    geometry.add_element((lineto_count << 3u) | 2u);\n    // Now that we've issued the LINETO REPEAT N command, we append\n    // N coordinate pairs immediately after the command.\n    for (++pt; pt != line.end(); ++pt)\n    {\n        const std::int32_t dx = pt->x - start_x;\n        const std::int32_t dy = pt->y - start_y;\n        geometry.add_element(protozero::encode_zigzag32(dx));\n        geometry.add_element(protozero::encode_zigzag32(dy));\n        start_x = pt->x;\n        start_y = pt->y;\n    }\n    return true;\n}\n\n// from mapnik-vctor-tile\n// Encodes a point\ninline void encodePoint(const FixedPoint &pt, protozero::packed_field_uint32 &geometry)\n{\n    const constexpr int MOVETO_COMMAND = 9;\n    geometry.add_element(MOVETO_COMMAND);\n    const std::int32_t dx = pt.x;\n    const std::int32_t dy = pt.y;\n    // Manual zigzag encoding.\n    geometry.add_element(protozero::encode_zigzag32(dx));\n    geometry.add_element(protozero::encode_zigzag32(dy));\n}\n\n/**\n * Returnx the x1,y1,x2,y2 pixel coordinates of a line in a given\n * tile.\n *\n * @param start the first coordinate of the line\n * @param target the last coordinate of the line\n * @param tile_bbox the boundaries of the tile, in mercator coordinates\n * @return a FixedLine with coordinates relative to the tile_bbox.\n */\nFixedLine coordinatesToTileLine(const util::Coordinate start,\n                                const util::Coordinate target,\n                                const BBox &tile_bbox)\n{\n    FloatLine geo_line;\n    geo_line.emplace_back(static_cast<double>(util::toFloating(start.lon)),\n                          static_cast<double>(util::toFloating(start.lat)));\n    geo_line.emplace_back(static_cast<double>(util::toFloating(target.lon)),\n                          static_cast<double>(util::toFloating(target.lat)));\n\n    linestring_t unclipped_line;\n\n    for (auto const &pt : geo_line)\n    {\n        double px_merc = pt.x * util::web_mercator::DEGREE_TO_PX;\n        double py_merc = util::web_mercator::latToY(util::FloatLatitude{pt.y}) *\n                         util::web_mercator::DEGREE_TO_PX;\n        // convert lon/lat to tile coordinates\n        const auto px = std::round(\n            ((px_merc - tile_bbox.minx) * util::web_mercator::TILE_SIZE / tile_bbox.width()) *\n            util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE);\n        const auto py = std::round(\n            ((tile_bbox.maxy - py_merc) * util::web_mercator::TILE_SIZE / tile_bbox.height()) *\n            util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE);\n\n        boost::geometry::append(unclipped_line, point_t(px, py));\n    }\n\n    multi_linestring_t clipped_line;\n\n    boost::geometry::intersection(clip_box, unclipped_line, clipped_line);\n\n    FixedLine tile_line;\n\n    // b::g::intersection might return a line with one point if the\n    // original line was very short and coords were dupes\n    if (!clipped_line.empty() && clipped_line[0].size() == 2)\n    {\n        if (clipped_line[0].size() == 2)\n        {\n            for (const auto &p : clipped_line[0])\n            {\n                tile_line.emplace_back(p.get<0>(), p.get<1>());\n            }\n        }\n    }\n\n    return tile_line;\n}\n\n/**\n * Converts lon/lat into coordinates inside a Mercator projection tile (x/y pixel values)\n *\n * @param point the lon/lat you want the tile coords for\n * @param tile_bbox the mercator boundaries of the tile\n * @return a point (x,y) on the tile defined by tile_bbox\n */\nFixedPoint coordinatesToTilePoint(const util::Coordinate point, const BBox &tile_bbox)\n{\n    const FloatPoint geo_point{static_cast<double>(util::toFloating(point.lon)),\n                               static_cast<double>(util::toFloating(point.lat))};\n\n    const double px_merc = geo_point.x * util::web_mercator::DEGREE_TO_PX;\n    const double py_merc = util::web_mercator::latToY(util::FloatLatitude{geo_point.y}) *\n                           util::web_mercator::DEGREE_TO_PX;\n\n    const auto px = static_cast<std::int32_t>(std::round(\n        ((px_merc - tile_bbox.minx) * util::web_mercator::TILE_SIZE / tile_bbox.width()) *\n        util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE));\n    const auto py = static_cast<std::int32_t>(std::round(\n        ((tile_bbox.maxy - py_merc) * util::web_mercator::TILE_SIZE / tile_bbox.height()) *\n        util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE));\n\n    return FixedPoint{px, py};\n}\n\nstd::vector<RTreeLeaf> getEdges(const datafacade::ContiguousInternalMemoryDataFacadeBase &facade,\n                                unsigned x,\n                                unsigned y,\n                                unsigned z)\n{\n    double min_lon, min_lat, max_lon, max_lat;\n\n    // Convert the z,x,y mercator tile coordinates into WGS84 lon/lat values\n    //\n    util::web_mercator::xyzToWGS84(\n        x, y, z, min_lon, min_lat, max_lon, max_lat, util::web_mercator::TILE_SIZE * 0.10);\n\n    util::Coordinate southwest{util::FloatLongitude{min_lon}, util::FloatLatitude{min_lat}};\n    util::Coordinate northeast{util::FloatLongitude{max_lon}, util::FloatLatitude{max_lat}};\n\n    // Fetch all the segments that are in our bounding box.\n    // This hits the OSRM StaticRTree\n    return facade.GetEdgesInBox(southwest, northeast);\n}\n\nstd::vector<std::size_t> getEdgeIndex(const std::vector<RTreeLeaf> &edges)\n{\n    // In order to ensure consistent tile encoding, we need to process\n    // all edges in the same order.  Differences in OSX/Linux/Windows\n    // sorting methods mean that GetEdgesInBox doesn't return the same\n    // ordered array on all platforms.\n    // GetEdgesInBox is marked `const`, so we can't sort the array itself,\n    // instead we create an array of indexes and sort that instead.\n    std::vector<std::size_t> sorted_edge_indexes(edges.size(), 0);\n    std::iota(\n        sorted_edge_indexes.begin(), sorted_edge_indexes.end(), 0); // fill with 0,1,2,3,...N-1\n\n    // Now, sort that array based on the edges list, using the u/v node IDs\n    // as the sort condition\n    std::sort(sorted_edge_indexes.begin(),\n              sorted_edge_indexes.end(),\n              [&edges](const std::size_t &left, const std::size_t &right) -> bool {\n                  return (edges[left].u != edges[right].u) ? edges[left].u < edges[right].u\n                                                           : edges[left].v < edges[right].v;\n              });\n\n    return sorted_edge_indexes;\n}\n\nvoid encodeVectorTile(const datafacade::ContiguousInternalMemoryDataFacadeBase &facade,\n                      unsigned x,\n                      unsigned y,\n                      unsigned z,\n                      const std::vector<RTreeLeaf> &edges,\n                      const std::vector<std::size_t> &sorted_edge_indexes,\n                      const std::vector<routing_algorithms::TurnData> &all_turn_data,\n                      std::string &pbf_buffer)\n{\n\n    // Vector tiles encode properties as references to a common lookup table.\n    // When we add a property to a \"feature\", we actually attach the index of the value\n    // rather than the value itself.  Thus, we need to keep a list of the unique\n    // values we need, and we add this list to the tile as a lookup table.  This\n    // vector holds all the actual used values, the feature refernce offsets in\n    // this vector.\n    // for integer values\n    std::vector<int> used_line_ints;\n    // While constructing the tile, we keep track of which integers we have in our table\n    // and their offsets, so multiple features can re-use the same values\n    std::unordered_map<int, std::size_t> line_int_offsets;\n\n    // Same idea for street names - one lookup table for names for all features\n    std::vector<util::StringView> names;\n    std::unordered_map<util::StringView, std::size_t> name_offsets;\n\n    // And again for integer values used by points.\n    std::vector<int> used_point_ints;\n    std::unordered_map<int, std::size_t> point_int_offsets;\n\n    // And again for float values used by points\n    std::vector<float> used_point_floats;\n    std::unordered_map<float, std::size_t> point_float_offsets;\n\n    std::uint8_t max_datasource_id = 0;\n\n    // This is where we accumulate information on turns\n\n    // Helper function for adding a new value to the line_ints lookup table.  Returns\n    // the index of the value in the table, adding the value if it doesn't already\n    // exist\n    const auto use_line_value = [&used_line_ints, &line_int_offsets](const int value) {\n        const auto found = line_int_offsets.find(value);\n\n        if (found == line_int_offsets.end())\n        {\n            used_line_ints.push_back(value);\n            line_int_offsets[value] = used_line_ints.size() - 1;\n        }\n\n        return;\n    };\n\n    // Same again\n    const auto use_point_int_value = [&used_point_ints, &point_int_offsets](const int value) {\n        const auto found = point_int_offsets.find(value);\n        std::size_t offset;\n\n        if (found == point_int_offsets.end())\n        {\n            used_point_ints.push_back(value);\n            offset = used_point_ints.size() - 1;\n            point_int_offsets[value] = offset;\n        }\n        else\n        {\n            offset = found->second;\n        }\n\n        return offset;\n    };\n\n    // And a third time, should probably template this....\n    const auto use_point_float_value = [&used_point_floats,\n                                        &point_float_offsets](const float value) {\n        const auto found = point_float_offsets.find(value);\n        std::size_t offset;\n\n        if (found == point_float_offsets.end())\n        {\n            used_point_floats.push_back(value);\n            offset = used_point_floats.size() - 1;\n            point_float_offsets[value] = offset;\n        }\n        else\n        {\n            offset = found->second;\n        }\n\n        return offset;\n    };\n\n    // Vector tiles encode feature properties as indexes into a lookup table.  So, we need\n    // to \"pre-loop\" over all the edges to create the lookup tables.  Once we have those, we\n    // can then encode the features, and we'll know the indexes that feature properties\n    // need to refer to.\n    for (const auto &edge_index : sorted_edge_indexes)\n    {\n        const auto &edge = edges[edge_index];\n\n        const auto forward_datasource_vector =\n            facade.GetUncompressedForwardDatasources(edge.packed_geometry_id);\n        const auto reverse_datasource_vector =\n            facade.GetUncompressedReverseDatasources(edge.packed_geometry_id);\n\n        BOOST_ASSERT(edge.fwd_segment_position < forward_datasource_vector.size());\n        const auto forward_datasource = forward_datasource_vector[edge.fwd_segment_position];\n        BOOST_ASSERT(edge.fwd_segment_position < reverse_datasource_vector.size());\n        const auto reverse_datasource = reverse_datasource_vector[reverse_datasource_vector.size() -\n                                                                  edge.fwd_segment_position - 1];\n\n        // Keep track of the highest datasource seen so that we don't write unnecessary\n        // data to the layer attribute values\n        max_datasource_id = std::max(max_datasource_id, forward_datasource);\n        max_datasource_id = std::max(max_datasource_id, reverse_datasource);\n    }\n\n    // Convert tile coordinates into mercator coordinates\n    double min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat;\n    util::web_mercator::xyzToMercator(\n        x, y, z, min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat);\n    const BBox tile_bbox{min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat};\n\n    // Protobuf serializes blocks when objects go out of scope, hence\n    // the extra scoping below.\n    protozero::pbf_writer tile_writer{pbf_buffer};\n    {\n        {\n            // Add a layer object to the PBF stream.  3=='layer' from the vector tile spec\n            // (2.1)\n            protozero::pbf_writer line_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);\n            // TODO: don't write a layer if there are no features\n\n            line_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2); // version\n            // Field 1 is the \"layer name\" field, it's a string\n            line_layer_writer.add_string(util::vector_tile::NAME_TAG, \"speeds\"); // name\n            // Field 5 is the tile extent.  It's a uint32 and should be set to 4096\n            // for normal vector tiles.\n            line_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,\n                                         util::vector_tile::EXTENT); // extent\n\n            // Because we need to know the indexes into the vector tile lookup table,\n            // we need to do an initial pass over the data and create the complete\n            // index of used values.\n            for (const auto &edge_index : sorted_edge_indexes)\n            {\n                const auto &edge = edges[edge_index];\n\n                // Weight values\n                const auto forward_weight_vector =\n                    facade.GetUncompressedForwardWeights(edge.packed_geometry_id);\n                const auto reverse_weight_vector =\n                    facade.GetUncompressedReverseWeights(edge.packed_geometry_id);\n                const auto forward_weight = forward_weight_vector[edge.fwd_segment_position];\n                const auto reverse_weight = reverse_weight_vector[reverse_weight_vector.size() -\n                                                                  edge.fwd_segment_position - 1];\n                use_line_value(forward_weight);\n                use_line_value(reverse_weight);\n\n                // Duration values\n                const auto forward_duration_vector =\n                    facade.GetUncompressedForwardDurations(edge.packed_geometry_id);\n                const auto reverse_duration_vector =\n                    facade.GetUncompressedReverseDurations(edge.packed_geometry_id);\n                const auto forward_duration = forward_duration_vector[edge.fwd_segment_position];\n                const auto reverse_duration =\n                    reverse_duration_vector[reverse_duration_vector.size() -\n                                            edge.fwd_segment_position - 1];\n                use_line_value(forward_duration);\n                use_line_value(reverse_duration);\n            }\n\n            // Begin the layer features block\n            {\n                // Each feature gets a unique id, starting at 1\n                unsigned id = 1;\n                for (const auto &edge_index : sorted_edge_indexes)\n                {\n                    const auto &edge = edges[edge_index];\n                    // Get coordinates for start/end nodes of segment (NodeIDs u and v)\n                    const auto a = facade.GetCoordinateOfNode(edge.u);\n                    const auto b = facade.GetCoordinateOfNode(edge.v);\n                    // Calculate the length in meters\n                    const double length =\n                        osrm::util::coordinate_calculation::haversineDistance(a, b);\n\n                    const auto forward_weight_vector =\n                        facade.GetUncompressedForwardWeights(edge.packed_geometry_id);\n                    const auto reverse_weight_vector =\n                        facade.GetUncompressedReverseWeights(edge.packed_geometry_id);\n                    const auto forward_duration_vector =\n                        facade.GetUncompressedForwardDurations(edge.packed_geometry_id);\n                    const auto reverse_duration_vector =\n                        facade.GetUncompressedReverseDurations(edge.packed_geometry_id);\n                    const auto forward_datasource_vector =\n                        facade.GetUncompressedForwardDatasources(edge.packed_geometry_id);\n                    const auto reverse_datasource_vector =\n                        facade.GetUncompressedReverseDatasources(edge.packed_geometry_id);\n                    const auto forward_weight = forward_weight_vector[edge.fwd_segment_position];\n                    const auto reverse_weight =\n                        reverse_weight_vector[reverse_weight_vector.size() -\n                                              edge.fwd_segment_position - 1];\n                    const auto forward_duration =\n                        forward_duration_vector[edge.fwd_segment_position];\n                    const auto reverse_duration =\n                        reverse_duration_vector[reverse_duration_vector.size() -\n                                                edge.fwd_segment_position - 1];\n                    const auto forward_datasource =\n                        forward_datasource_vector[edge.fwd_segment_position];\n                    const auto reverse_datasource =\n                        reverse_datasource_vector[reverse_datasource_vector.size() -\n                                                  edge.fwd_segment_position - 1];\n\n                    auto name = facade.GetNameForID(edge.name_id);\n\n                    const auto name_offset = [&name, &names, &name_offsets]() {\n                        auto iter = name_offsets.find(name);\n                        if (iter == name_offsets.end())\n                        {\n                            auto offset = names.size();\n                            name_offsets[name] = offset;\n                            names.push_back(name);\n                            return offset;\n                        }\n                        return iter->second;\n                    }();\n\n                    const auto encode_tile_line = [&line_layer_writer,\n                                                   &edge,\n                                                   &id,\n                                                   &max_datasource_id,\n                                                   &used_line_ints](const FixedLine &tile_line,\n                                                                    const std::uint32_t speed_kmh,\n                                                                    const std::size_t weight,\n                                                                    const std::size_t duration,\n                                                                    const DatasourceID datasource,\n                                                                    const std::size_t name_idx,\n                                                                    std::int32_t &start_x,\n                                                                    std::int32_t &start_y) {\n                        // Here, we save the two attributes for our feature: the speed and\n                        // the is_small boolean.  We only serve up speeds from 0-139, so all we\n                        // do is save the first\n                        protozero::pbf_writer feature_writer(line_layer_writer,\n                                                             util::vector_tile::FEATURE_TAG);\n                        // Field 3 is the \"geometry type\" field.  Value 2 is \"line\"\n                        feature_writer.add_enum(\n                            util::vector_tile::GEOMETRY_TAG,\n                            util::vector_tile::GEOMETRY_TYPE_LINE); // geometry type\n                        // Field 1 for the feature is the \"id\" field.\n                        feature_writer.add_uint64(util::vector_tile::ID_TAG, id++); // id\n                        {\n                            // When adding attributes to a feature, we have to write\n                            // pairs of numbers.  The first value is the index in the\n                            // keys array (written later), and the second value is the\n                            // index into the \"values\" array (also written later).  We're\n                            // not writing the actual speed or bool value here, we're saving\n                            // an index into the \"values\" array.  This means many features\n                            // can share the same value data, leading to smaller tiles.\n                            protozero::packed_field_uint32 field(\n                                feature_writer, util::vector_tile::FEATURE_ATTRIBUTES_TAG);\n\n                            field.add_element(0); // \"speed\" tag key offset\n                            field.add_element(\n                                std::min(speed_kmh, 127u)); // save the speed value, capped at 127\n                            field.add_element(1);           // \"is_small\" tag key offset\n                            field.add_element(128 +\n                                              (edge.component.is_tiny ? 0 : 1)); // is_small feature\n                            field.add_element(2);                // \"datasource\" tag key offset\n                            field.add_element(130 + datasource); // datasource value offset\n                            field.add_element(3);                // \"weight\" tag key offset\n                            field.add_element(130 + max_datasource_id + 1 +\n                                              weight); // weight value offset\n                            field.add_element(4);      // \"duration\" tag key offset\n                            field.add_element(130 + max_datasource_id + 1 +\n                                              duration); // duration value offset\n                            field.add_element(5);        // \"name\" tag key offset\n\n                            field.add_element(130 + max_datasource_id + 1 + used_line_ints.size() +\n                                              name_idx); // name value offset\n                        }\n                        {\n\n                            // Encode the geometry for the feature\n                            protozero::packed_field_uint32 geometry(\n                                feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);\n                            encodeLinestring(tile_line, geometry, start_x, start_y);\n                        }\n                    };\n\n                    // If this is a valid forward edge, go ahead and add it to the tile\n                    if (forward_duration != 0 && edge.forward_segment_id.enabled)\n                    {\n                        std::int32_t start_x = 0;\n                        std::int32_t start_y = 0;\n\n                        // Calculate the speed for this line\n                        std::uint32_t speed_kmh =\n                            static_cast<std::uint32_t>(round(length / forward_duration * 10 * 3.6));\n\n                        auto tile_line = coordinatesToTileLine(a, b, tile_bbox);\n                        if (!tile_line.empty())\n                        {\n                            encode_tile_line(tile_line,\n                                             speed_kmh,\n                                             line_int_offsets[forward_weight],\n                                             line_int_offsets[forward_duration],\n                                             forward_datasource,\n                                             name_offset,\n                                             start_x,\n                                             start_y);\n                        }\n                    }\n\n                    // Repeat the above for the coordinates reversed and using the `reverse`\n                    // properties\n                    if (reverse_duration != 0 && edge.reverse_segment_id.enabled)\n                    {\n                        std::int32_t start_x = 0;\n                        std::int32_t start_y = 0;\n\n                        // Calculate the speed for this line\n                        std::uint32_t speed_kmh =\n                            static_cast<std::uint32_t>(round(length / reverse_duration * 10 * 3.6));\n\n                        auto tile_line = coordinatesToTileLine(b, a, tile_bbox);\n                        if (!tile_line.empty())\n                        {\n                            encode_tile_line(tile_line,\n                                             speed_kmh,\n                                             line_int_offsets[reverse_weight],\n                                             line_int_offsets[reverse_duration],\n                                             reverse_datasource,\n                                             name_offset,\n                                             start_x,\n                                             start_y);\n                        }\n                    }\n                }\n            }\n\n            // Field id 3 is the \"keys\" attribute\n            // We need two \"key\" fields, these are referred to with 0 and 1 (their array\n            // indexes) earlier\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"speed\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"is_small\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"datasource\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"weight\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"duration\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"name\");\n\n            // Now, we write out the possible speed value arrays and possible is_tiny\n            // values.  Field type 4 is the \"values\" field.  It's a variable type field,\n            // so requires a two-step write (create the field, then write its value)\n            for (std::size_t i = 0; i < 128; i++)\n            {\n                // Writing field type 4 == variant type\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 5 == uint64 type\n                values_writer.add_uint64(util::vector_tile::VARIANT_TYPE_UINT64, i);\n            }\n            {\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 7 == bool type\n                values_writer.add_bool(util::vector_tile::VARIANT_TYPE_BOOL, true);\n            }\n            {\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 7 == bool type\n                values_writer.add_bool(util::vector_tile::VARIANT_TYPE_BOOL, false);\n            }\n            for (std::size_t i = 0; i <= max_datasource_id; i++)\n            {\n                // Writing field type 4 == variant type\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 1 == string type\n                values_writer.add_string(util::vector_tile::VARIANT_TYPE_STRING,\n                                         facade.GetDatasourceName(i).to_string());\n            }\n            for (auto value : used_line_ints)\n            {\n                // Writing field type 4 == variant type\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 2 == float type\n                // Durations come out of OSRM in integer deciseconds, so we convert them\n                // to seconds with a simple /10 for display\n                values_writer.add_double(util::vector_tile::VARIANT_TYPE_DOUBLE, value / 10.);\n            }\n\n            for (const auto &name : names)\n            {\n                // Writing field type 4 == variant type\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 1 == string type\n                values_writer.add_string(\n                    util::vector_tile::VARIANT_TYPE_STRING, name.data(), name.size());\n            }\n        }\n\n        // Only add the turn layer to the tile if it has some features (we sometimes won't\n        // for tiles of z<16, and tiles that don't show any intersections)\n        if (!all_turn_data.empty())\n        {\n            // we need to pre-encode all values here because we need the full offsets later\n            // for encoding the actual features.\n            std::vector<std::tuple<util::Coordinate, unsigned, unsigned, unsigned>>\n                encoded_turn_data(all_turn_data.size());\n            std::transform(\n                all_turn_data.begin(),\n                all_turn_data.end(),\n                encoded_turn_data.begin(),\n                [&](const routing_algorithms::TurnData &t) {\n                    auto angle_idx = use_point_int_value(t.in_angle);\n                    auto turn_idx = use_point_int_value(t.turn_angle);\n                    auto duration_idx =\n                        use_point_float_value(t.duration / 10.0); // Note conversion to float here\n                    return std::make_tuple(t.coordinate, angle_idx, turn_idx, duration_idx);\n                });\n\n            // Now write the points layer for turn penalty data:\n            // Add a layer object to the PBF stream.  3=='layer' from the vector tile spec\n            // (2.1)\n            protozero::pbf_writer point_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);\n            point_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2);    // version\n            point_layer_writer.add_string(util::vector_tile::NAME_TAG, \"turns\"); // name\n            point_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,\n                                          util::vector_tile::EXTENT); // extent\n\n            // Begin writing the set of point features\n            {\n                // Start each features with an ID starting at 1\n                int id = 1;\n\n                // Helper function to encode a new point feature on a vector tile.\n                const auto encode_tile_point = [&](const FixedPoint &tile_point,\n                                                   const auto &point_turn_data) {\n                    protozero::pbf_writer feature_writer(point_layer_writer,\n                                                         util::vector_tile::FEATURE_TAG);\n                    // Field 3 is the \"geometry type\" field.  Value 1 is \"point\"\n                    feature_writer.add_enum(\n                        util::vector_tile::GEOMETRY_TAG,\n                        util::vector_tile::GEOMETRY_TYPE_POINT);                // geometry type\n                    feature_writer.add_uint64(util::vector_tile::ID_TAG, id++); // id\n                    {\n                        // Write out the 3 properties we want on the feature.  These\n                        // refer to indexes in the properties lookup table, which we\n                        // add to the tile after we add all features.\n                        protozero::packed_field_uint32 field(\n                            feature_writer, util::vector_tile::FEATURE_ATTRIBUTES_TAG);\n                        field.add_element(0); // \"bearing_in\" tag key offset\n                        field.add_element(std::get<1>(point_turn_data));\n                        field.add_element(1); // \"turn_angle\" tag key offset\n                        field.add_element(std::get<2>(point_turn_data));\n                        field.add_element(2); // \"cost\" tag key offset\n                        field.add_element(used_point_ints.size() + std::get<3>(point_turn_data));\n                    }\n                    {\n                        // Add the geometry as the last field in this feature\n                        protozero::packed_field_uint32 geometry(\n                            feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);\n                        encodePoint(tile_point, geometry);\n                    }\n                };\n\n                // Loop over all the turns we found and add them as features to the layer\n                for (const auto &turndata : encoded_turn_data)\n                {\n                    const auto tile_point =\n                        coordinatesToTilePoint(std::get<0>(turndata), tile_bbox);\n                    if (!boost::geometry::within(point_t(tile_point.x, tile_point.y), clip_box))\n                    {\n                        continue;\n                    }\n                    encode_tile_point(tile_point, turndata);\n                }\n            }\n\n            // Add the names of the three attributes we added to all the turn penalty\n            // features previously.  The indexes used there refer to these keys.\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"bearing_in\");\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"turn_angle\");\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"cost\");\n\n            // Now, save the lists of integers and floats that our features refer to.\n            for (const auto &value : used_point_ints)\n            {\n                protozero::pbf_writer values_writer(point_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                values_writer.add_sint64(util::vector_tile::VARIANT_TYPE_SINT64, value);\n            }\n            for (const auto &value : used_point_floats)\n            {\n                protozero::pbf_writer values_writer(point_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                values_writer.add_float(util::vector_tile::VARIANT_TYPE_FLOAT, value);\n            }\n        }\n    }\n    // protozero serializes data during object destructors, so once the scope closes,\n    // our result buffer will have all the tile data encoded into it.\n}\n}\n\nStatus TilePlugin::HandleRequest(const datafacade::ContiguousInternalMemoryDataFacadeBase &facade,\n                                 const RoutingAlgorithmsInterface &algorithms,\n                                 const api::TileParameters &parameters,\n                                 std::string &pbf_buffer) const\n{\n    BOOST_ASSERT(parameters.IsValid());\n\n    auto edges = getEdges(facade, parameters.x, parameters.y, parameters.z);\n\n    auto edge_index = getEdgeIndex(edges);\n\n    std::vector<routing_algorithms::TurnData> turns;\n\n    // If we're zooming into 16 or higher, include turn data.  Why?  Because turns make the map\n    // really cramped, so we don't bother including the data for tiles that span a large area.\n    if (parameters.z >= MIN_ZOOM_FOR_TURNS && algorithms.HasGetTileTurns())\n    {\n        turns = algorithms.GetTileTurns(edges, edge_index);\n    }\n\n    encodeVectorTile(\n        facade, parameters.x, parameters.y, parameters.z, edges, edge_index, turns, pbf_buffer);\n\n    return Status::Ok;\n}\n}\n}\n}\n", "meta": {"hexsha": "4f9a99d0ef3909acfef17d97d22d58f18eced598", "size": 38517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/deps/osrm/src/engine/plugins/tile.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/deps/osrm/src/engine/plugins/tile.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/deps/osrm/src/engine/plugins/tile.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": 47.3763837638, "max_line_length": 100, "alphanum_fraction": 0.5636731833, "num_tokens": 7714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.197262302512705}}
{"text": "#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cassert>\n#include <cmath>\n\n#include \"config.h\"\n#ifdef HAVE_MPI\n#include <boost/mpi.hpp>\n#endif\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"verbose.h\"\n#include \"hg.h\"\n#include \"prob.h\"\n#include \"inside_outside.h\"\n#include \"ff_register.h\"\n#include \"decoder.h\"\n#include \"filelib.h\"\n#include \"weights.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nbool InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"weights,w\",po::value<string>(),\"Input feature weights file\")\n        (\"training_data,t\",po::value<string>(),\"Training data corpus\")\n        (\"decoder_config,c\",po::value<string>(),\"Decoder configuration file\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config\", po::value<string>(), \"Configuration file\")\n        (\"help,h\", \"Print this help message and exit\");\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(opts).add(clo);\n  \n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"config\")) {\n    ifstream config((*conf)[\"config\"].as<string>().c_str());\n    po::store(po::parse_config_file(config, dconfig_options), *conf);\n  }\n  po::notify(*conf);\n\n  if (conf->count(\"help\") || !conf->count(\"training_data\") || !conf->count(\"decoder_config\")) {\n    cerr << dcmdline_options << endl;\n    return false;\n  }\n  return true;\n}\n\nvoid ReadTrainingCorpus(const string& fname, int rank, int size, vector<string>* c, vector<int>* ids) {\n  ReadFile rf(fname);\n  istream& in = *rf.stream();\n  string line;\n  int lc = 0;\n  while(in) {\n    getline(in, line);\n    if (!in) break;\n    if (lc % size == rank) {\n      c->push_back(line);\n      ids->push_back(lc);\n    }\n    ++lc;\n  }\n}\n\nstatic const double kMINUS_EPSILON = -1e-6;\n\nstruct TrainingObserver : public DecoderObserver {\n  void Reset() {\n    acc_obj = 0;\n  } \n\n  virtual void NotifyDecodingStart(const SentenceMetadata&) {\n    cur_obj = 0;\n    state = 1;\n  }\n\n  // compute model expectations, denominator of objective\n  virtual void NotifyTranslationForest(const SentenceMetadata&, Hypergraph* hg) {\n    assert(state == 1);\n    state = 2;\n    SparseVector<prob_t> cur_model_exp;\n    const prob_t z = InsideOutside<prob_t,\n                                   EdgeProb,\n                                   SparseVector<prob_t>,\n                                   EdgeFeaturesAndProbWeightFunction>(*hg, &cur_model_exp);\n    cur_obj = log(z);\n  }\n\n  // compute \"empirical\" expectations, numerator of objective\n  virtual void NotifyAlignmentForest(const SentenceMetadata& smeta, Hypergraph* hg) {\n    assert(state == 2);\n    state = 3;\n    SparseVector<prob_t> ref_exp;\n    const prob_t ref_z = InsideOutside<prob_t,\n                                       EdgeProb,\n                                       SparseVector<prob_t>,\n                                       EdgeFeaturesAndProbWeightFunction>(*hg, &ref_exp);\n\n    double log_ref_z;\n#if 0\n    if (crf_uniform_empirical) {\n      log_ref_z = ref_exp.dot(feature_weights);\n    } else {\n      log_ref_z = log(ref_z);\n    }\n#else\n    log_ref_z = log(ref_z);\n#endif\n\n    // rounding errors means that <0 is too strict\n    if ((cur_obj - log_ref_z) < kMINUS_EPSILON) {\n      cerr << \"DIFF. ERR! log_model_z < log_ref_z: \" << cur_obj << \" \" << log_ref_z << endl;\n      exit(1);\n    }\n    assert(!isnan(log_ref_z));\n    acc_obj += (cur_obj - log_ref_z);\n  }\n\n  double acc_obj;\n  double cur_obj;\n  int state;\n};\n\n#ifdef HAVE_MPI\nnamespace mpi = boost::mpi;\n#endif\n\nint main(int argc, char** argv) {\n#ifdef HAVE_MPI\n  mpi::environment env(argc, argv);\n  mpi::communicator world;\n  const int size = world.size(); \n  const int rank = world.rank();\n#else\n  const int size = 1;\n  const int rank = 0;\n#endif\n  if (size > 1) SetSilent(true);  // turn off verbose decoder output\n  register_feature_functions();\n\n  po::variables_map conf;\n  if (!InitCommandLine(argc, argv, &conf))\n    return false;\n\n  // load initial weights\n  Weights weights;\n  if (conf.count(\"weights\"))\n    weights.InitFromFile(conf[\"weights\"].as<string>());\n\n  // freeze feature set\n  //const bool freeze_feature_set = conf.count(\"freeze_feature_set\");\n  //if (freeze_feature_set) FD::Freeze();\n\n  // load cdec.ini and set up decoder\n  ReadFile ini_rf(conf[\"decoder_config\"].as<string>());\n  Decoder decoder(ini_rf.stream());\n  if (decoder.GetConf()[\"input\"].as<string>() != \"-\") {\n    cerr << \"cdec.ini must not set an input file\\n\";\n    abort();\n  }\n\n  vector<string> corpus; vector<int> ids;\n  ReadTrainingCorpus(conf[\"training_data\"].as<string>(), rank, size, &corpus, &ids);\n  assert(corpus.size() > 0);\n  assert(corpus.size() == ids.size());\n\n  vector<double> wv;\n  weights.InitVector(&wv);\n  decoder.SetWeights(wv);\n  TrainingObserver observer;\n  double objective = 0;\n  bool converged = false;\n\n  observer.Reset();\n  if (rank == 0)\n    cerr << \"Each processor is decoding \" << corpus.size() << \" training examples...\\n\";\n\n  for (int i = 0; i < corpus.size(); ++i) {\n    decoder.SetId(ids[i]);\n    decoder.Decode(corpus[i], &observer);\n  }\n\n#ifdef HAVE_MPI\n  reduce(world, observer.acc_obj, objective, std::plus<double>(), 0);\n#else\n  objective = observer.acc_obj;\n#endif\n\n  if (rank == 0)\n    cout << \"OBJECTIVE: \" << objective << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "332f6d0c17a0c2eaab36dd1fd89bd6837048dba9", "size": 5516, "ext": "cc", "lang": "C++", "max_stars_repo_path": "training/compute_cllh.cc", "max_stars_repo_name": "agesmundo/FasterCubePruning", "max_stars_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T00:44:01.000Z", "max_issues_repo_path": "training/compute_cllh.cc", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "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": "training/compute_cllh.cc", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T12:44:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:44:54.000Z", "avg_line_length": 27.58, "max_line_length": 103, "alphanum_fraction": 0.641044235, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.19726230251270496}}
{"text": "// Copyright (C) 2013  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include <dlib/python.h>\n#include <dlib/matrix.h>\n#include <dlib/svm.h>\n#include \"testing_results.h\"\n#include <pybind11/stl_bind.h>\n\nusing namespace dlib;\nusing namespace std;\nnamespace py = pybind11;\n\ntypedef matrix<double,0,1> sample_type; \ntypedef std::vector<std::pair<unsigned long,double> > sparse_vect;\ntypedef std::vector<ranking_pair<sample_type> > ranking_pairs;\ntypedef std::vector<ranking_pair<sparse_vect> > sparse_ranking_pairs;\n\nPYBIND11_MAKE_OPAQUE(ranking_pairs);\nPYBIND11_MAKE_OPAQUE(sparse_ranking_pairs);\n\n// ----------------------------------------------------------------------------------------\n\nnamespace dlib\n{\n    template <typename T>\n    bool operator== (\n        const ranking_pair<T>&, \n        const ranking_pair<T>& \n    )\n    {\n        pyassert(false, \"It is illegal to compare ranking pair objects for equality.\");\n        return false;\n    }\n}\n\ntemplate <typename T>\nvoid resize(T& v, unsigned long n) { v.resize(n); }\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename trainer_type>\ntypename trainer_type::trained_function_type train1 (\n    const trainer_type& trainer,\n    const ranking_pair<typename trainer_type::sample_type>& sample\n)\n{\n    typedef ranking_pair<typename trainer_type::sample_type> st;\n    pyassert(is_ranking_problem(std::vector<st>(1, sample)), \"Invalid inputs\");\n    return trainer.train(sample);\n}\n\ntemplate <typename trainer_type>\ntypename trainer_type::trained_function_type train2 (\n    const trainer_type& trainer,\n    const std::vector<ranking_pair<typename trainer_type::sample_type> >& samples\n)\n{\n    pyassert(is_ranking_problem(samples), \"Invalid inputs\");\n    return trainer.train(samples);\n}\n\ntemplate <typename trainer_type>\nvoid set_epsilon ( trainer_type& trainer, double eps)\n{\n    pyassert(eps > 0, \"epsilon must be > 0\");\n    trainer.set_epsilon(eps);\n}\n\ntemplate <typename trainer_type>\ndouble get_epsilon ( const trainer_type& trainer) { return trainer.get_epsilon(); }\n\ntemplate <typename trainer_type>\nvoid set_c ( trainer_type& trainer, double C)\n{\n    pyassert(C > 0, \"C must be > 0\");\n    trainer.set_c(C);\n}\n\ntemplate <typename trainer_type>\ndouble get_c (const trainer_type& trainer)\n{\n    return trainer.get_c();\n}\n\n\ntemplate <typename trainer>\nvoid add_ranker (\n    py::module& m,\n    const char* name\n)\n{\n    py::class_<trainer>(m, name)\n        .def(py::init())\n        .def_property(\"epsilon\", get_epsilon<trainer>, set_epsilon<trainer>)\n        .def_property(\"c\", get_c<trainer>, set_c<trainer>)\n        .def_property(\"max_iterations\", &trainer::get_max_iterations, &trainer::set_max_iterations)\n        .def_property(\"force_last_weight_to_1\", &trainer::forces_last_weight_to_1, &trainer::force_last_weight_to_1)\n        .def_property(\"learns_nonnegative_weights\", &trainer::learns_nonnegative_weights, &trainer::set_learns_nonnegative_weights)\n        .def_property_readonly(\"has_prior\", &trainer::has_prior)\n        .def(\"train\", train1<trainer>)\n        .def(\"train\", train2<trainer>)\n        .def(\"set_prior\", &trainer::set_prior)\n        .def(\"be_verbose\", &trainer::be_verbose)\n        .def(\"be_quiet\", &trainer::be_quiet);\n}\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <\n    typename trainer_type,\n    typename T\n    >\nconst ranking_test _cross_ranking_validate_trainer (\n    const trainer_type& trainer,\n    const std::vector<ranking_pair<T> >& samples,\n    const unsigned long folds\n)\n{\n    pyassert(is_ranking_problem(samples), \"Training data does not make a valid training set.\");\n    pyassert(1 < folds && folds <= samples.size(), \"Invalid number of folds given.\");\n    return cross_validate_ranking_trainer(trainer, samples, folds);\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid bind_svm_rank_trainer(py::module& m)\n{\n    py::class_<ranking_pair<sample_type> >(m, \"ranking_pair\")\n        .def(py::init())\n        .def_readwrite(\"relevant\", &ranking_pair<sample_type>::relevant)\n        .def_readwrite(\"nonrelevant\", &ranking_pair<sample_type>::nonrelevant)\n        .def(py::pickle(&getstate<ranking_pair<sample_type>>, &setstate<ranking_pair<sample_type>>));\n\n    py::class_<ranking_pair<sparse_vect> >(m, \"sparse_ranking_pair\")\n        .def(py::init())\n        .def_readwrite(\"relevant\", &ranking_pair<sparse_vect>::relevant)\n        .def_readwrite(\"nonrelevant\", &ranking_pair<sparse_vect>::nonrelevant)\n        .def(py::pickle(&getstate<ranking_pair<sparse_vect>>, &setstate<ranking_pair<sparse_vect>>));\n\n    py::bind_vector<ranking_pairs>(m, \"ranking_pairs\")\n        .def(\"clear\", &ranking_pairs::clear)\n        .def(\"resize\", resize<ranking_pairs>)\n        .def(\"extend\", extend_vector_with_python_list<ranking_pair<sample_type>>)\n        .def(py::pickle(&getstate<ranking_pairs>, &setstate<ranking_pairs>));\n\n    py::bind_vector<sparse_ranking_pairs>(m, \"sparse_ranking_pairs\")\n        .def(\"clear\", &sparse_ranking_pairs::clear)\n        .def(\"resize\", resize<sparse_ranking_pairs>)\n        .def(\"extend\", extend_vector_with_python_list<ranking_pair<sparse_vect>>)\n        .def(py::pickle(&getstate<sparse_ranking_pairs>, &setstate<sparse_ranking_pairs>));\n\n    add_ranker<svm_rank_trainer<linear_kernel<sample_type> > >(m, \"svm_rank_trainer\");\n    add_ranker<svm_rank_trainer<sparse_linear_kernel<sparse_vect> > >(m, \"svm_rank_trainer_sparse\");\n\n    m.def(\"cross_validate_ranking_trainer\", &_cross_ranking_validate_trainer<\n                svm_rank_trainer<linear_kernel<sample_type> >,sample_type>,\n                py::arg(\"trainer\"), py::arg(\"samples\"), py::arg(\"folds\") );\n    m.def(\"cross_validate_ranking_trainer\", &_cross_ranking_validate_trainer<\n                svm_rank_trainer<sparse_linear_kernel<sparse_vect> > ,sparse_vect>,\n                py::arg(\"trainer\"), py::arg(\"samples\"), py::arg(\"folds\") );\n}\n\n\n\n", "meta": {"hexsha": "43979b2635eb3ecca5ac775793d4f07dab319255", "size": 6038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib-19.9/tools/python/src/svm_rank_trainer.cpp", "max_stars_repo_name": "BasileAmeeuw/IA-project-orientation-and-mood-detection", "max_stars_repo_head_hexsha": "02b674ca0a347642f460916880a73b374446b40b", "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": "dlib-19.9/tools/python/src/svm_rank_trainer.cpp", "max_issues_repo_name": "BasileAmeeuw/IA-project-orientation-and-mood-detection", "max_issues_repo_head_hexsha": "02b674ca0a347642f460916880a73b374446b40b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dlib-19.9/tools/python/src/svm_rank_trainer.cpp", "max_forks_repo_name": "BasileAmeeuw/IA-project-orientation-and-mood-detection", "max_forks_repo_head_hexsha": "02b674ca0a347642f460916880a73b374446b40b", "max_forks_repo_licenses": ["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.3734939759, "max_line_length": 131, "alphanum_fraction": 0.6666114607, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.19715090639729996}}
{"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_TRAITS_SYMM_HERM_TRAITS_HPP\n#define BOOST_NUMERIC_BINDINGS_TRAITS_SYMM_HERM_TRAITS_HPP\n\n#include <boost/numeric/bindings/traits/type.hpp> \n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/static_assert.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n\nnamespace boost { namespace numeric { namespace bindings { namespace traits {\n\n  namespace detail {\n\n    // select symmetric or hermitian matrix structure \n\n    template <typename T> \n    struct symm_herm_t {}; \n    template<>\n    struct symm_herm_t<float> {\n      typedef symmetric_t type;\n    }; \n    template<>\n    struct symm_herm_t<double> {\n      typedef symmetric_t type;\n    }; \n    template<>\n    struct symm_herm_t<complex_f> {\n      typedef hermitian_t type;\n    }; \n    template<>\n    struct symm_herm_t<complex_d> {\n      typedef hermitian_t type;\n    }; \n\n    template <typename T> \n    struct symm_herm_pack_t {}; \n    template<>\n    struct symm_herm_pack_t<float> {\n      typedef symmetric_packed_t type;\n    }; \n    template<>\n    struct symm_herm_pack_t<double> {\n      typedef symmetric_packed_t type;\n    }; \n    template<>\n    struct symm_herm_pack_t<complex_f> {\n      typedef hermitian_packed_t type;\n    }; \n    template<>\n    struct symm_herm_pack_t<complex_d> {\n      typedef hermitian_packed_t type;\n    }; \n\n\n    template <class T, class S>\n    struct symm_herm_compatible {\n      BOOST_STATIC_CONSTANT( bool, value=false ) ;\n    };\n\n    template <class T>\n    struct symm_herm_compatible< T, hermitian_t > {\n      BOOST_STATIC_CONSTANT( bool, value=true ) ;\n    };\n\n    template <class T>\n    struct symm_herm_compatible< T, symmetric_t > {\n      BOOST_STATIC_CONSTANT( bool, value=true ) ;\n    };\n\n    template <class T>\n    struct symm_herm_compatible< std::complex<T>, symmetric_t > {\n      BOOST_STATIC_CONSTANT( bool, value=false ) ;\n    };\n\n  }\n\n}}}}\n\n#endif // BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n\n#endif // BOOST_NUMERIC_BINDINGS_TRAITS_SYMM_HERM_TRAITS_HPP \n", "meta": {"hexsha": "8200f9fc6cedd6efe93f811dc991f9be80e93c38", "size": 2329, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/traits/detail/symm_herm_traits.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/traits/detail/symm_herm_traits.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/traits/detail/symm_herm_traits.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-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 24.5157894737, "max_line_length": 77, "alphanum_fraction": 0.6942893946, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.19715090271847308}}
{"text": "/**\n * Implementation of KVH 1750 types.\n * \\author Jason Ziglar <jpz@vt.edu>\n * \\date 02/16/2015\n */\n#include \"kvh1750/types.h\"\n\n#include <byteswap.h>\n#include <boost/crc.hpp>\n\nnamespace\n{\n  //! Offset between Celsius and Farenheit\n  const double CF_Offset = 32.0;\n  //! Scaling factor from Farenheit to Celsius\n  const double FC_Scale = 5.0 / 9.0;\n  //! Scaling factor from Celsius to Farenheit\n  const double CF_Scale = 9.0 / 5.0;\n}\n\nnamespace kvh\n{\n\n/**\n * Default Constructor, initializes to invalid memory\n */\nMessage::Message() :\n  _ang_vel{0.0, 0.0, 0.0},\n  _lin_accel{0.0, 0.0, 0.0},\n  _secs(0),\n  _nsecs(0),\n  _temp(0),\n  _status(0),\n  _seq(0),\n  _is_da(false),\n  _is_c(false)\n{\n}\n\n/**\n * Constructor which converts a raw message to a valid message\n */\nMessage::Message(const RawMessage& raw, uint32_t secs, uint32_t nsecs, bool is_c,\n  bool is_da) :\n  _ang_vel(),\n  _lin_accel(),\n  _secs(),\n  _nsecs(),\n  _temp(),\n  _status(),\n  _seq(),\n  _is_da(),\n  _is_c()\n{\n  from_raw(raw, secs, nsecs, is_c, is_da);\n}\n\n/**\n * Default destructor\n */\nMessage::~Message()\n{\n}\n\n/**\n * Conversion function from raw message to a more meaningful representation.\n * \\param[out] Flag indicating if the CRC came up valid.\n */\nbool Message::from_raw(const RawMessage& raw, uint32_t secs, uint32_t nsecs,\n  bool is_c, bool is_da)\n{\n  bool valid_msg = valid_checksum(raw);\n\n  if(valid_msg)\n  {\n    const size_t Num_Values_Per_Array = 3;\n\n    for(size_t ii = 0; ii < Num_Values_Per_Array; ++ii)\n    {\n\n      union swap_float\n      {\n        int32_t raw;\n        float val;\n      } ang, lin;\n\n      ang.raw = bswap_32(raw.rots[ii]);\n      lin.raw = bswap_32(raw.accels[ii]);\n      _ang_vel[ii] = ang.val;\n      _lin_accel[ii] = Gravity * lin.val;\n    }\n\n    _status = raw.status;\n    _seq = raw.seq;\n    _temp = bswap_16(raw.temp);\n    _secs = secs;\n    _nsecs = nsecs;\n    _is_c = is_c;\n    _is_da = is_da;\n  }\n  else\n  {\n    *this = Message(); //zero all data\n  }\n\n  return valid_msg;\n}\n\n/**\n * Accessing angular velocity along IMU's X.\n */\nfloat Message::gyro_x() const\n{\n  return _ang_vel[X];\n}\n\n/**\n * Accessing angular velocity with IMU's Y.\n */\nfloat Message::gyro_y() const\n{\n  return _ang_vel[Y];\n}\n\n/**\n * Accessing angular velocity with IMU's Z.\n */\nfloat Message::gyro_z() const\n{\n  return _ang_vel[Z];\n}\n\n/**\n * Accessing linear acceleration with IMU's X.\n */\nfloat Message::accel_x() const\n{\n  return _lin_accel[X];\n}\n\n/**\n * Accessing linear acceleration with IMU's Y.\n */\nfloat Message::accel_y() const\n{\n  return _lin_accel[Y];\n}\n\n/**\n * Accessing linear acceleration with IMU's Z.\n */\nfloat Message::accel_z() const\n{\n  return _lin_accel[Z];\n}\n\n/**\n * Accessing temperature rounded to the nearest degree. See\n * is_celsius() to determine units.\n */\nint16_t Message::temp() const\n{\n  return _temp;\n}\n\n/**\n * Accesses temperature, and returns flag indicating units.\n * \\param[in,out] Flag indicating if temperature is in Celsius\n * \\param[out] Temperature, rounded to nearest degree\n */\nint16_t Message::temp(bool& is_c) const\n{\n  is_c = _is_c;\n  return _temp;\n}\n\n/**\n * Returns the time this message was recorded.\n */\nvoid Message::time(uint32_t& secs, uint32_t& nsecs) const\n{\n  secs = _secs;\n  nsecs = _nsecs;\n}\n\n/**\n * Sequential Number from IMU.\n * \\param[out] Number\n */\nuint8_t Message::sequence_number() const\n{\n  return _seq;\n}\n\n/**\n * Tests if this message contains valid data.\n */\nbool Message::valid() const\n{\n  return _status != 0;\n}\n\n/**\n * Flag indicating if the X gyro was valid.\n */\nbool Message::valid_gyro_x() const\n{\n  return _status & GYRO_X;\n}\n\n/**\n * Flag indicating if the Y gyro was valid.\n */\nbool Message::valid_gyro_y() const\n{\n  return _status & GYRO_Y;\n}\n\n/**\n * Flag indicating if the Z gyro was valid.\n */\nbool Message::valid_gyro_z() const\n{\n  return _status & GYRO_Z;\n}\n\n/**\n * Flag indicating if the X accelerometer was valid.\n */\nbool Message::valid_accel_x() const\n{\n  return _status & ACCEL_X;\n}\n\n/**\n * Flag indicating if the Y accelerometer was valid.\n */\nbool Message::valid_accel_y() const\n{\n  return _status & ACCEL_Y;\n}\n\n/**\n * Flag indicating if the Z accelerometer was valid.\n */\nbool Message::valid_accel_z() const\n{\n  return _status & ACCEL_Z;\n}\n\n/**\n * Flag indicating if temperature is in Celsius.\n */\nbool Message::is_celsius() const\n{\n  return _is_c;\n}\n\n/**\n * Flag indicating if angular velocities are delta-angles, as\n * opposed to some filtered angular velocity.\n */\nbool Message::is_delta_angle() const\n{\n  return _is_da;\n}\n\n/**\n * Converts temperature to Celsius, if in Farenheit.\n */\nvoid Message::to_celsius()\n{\n  if(_is_c)\n  {\n    return;\n  }\n\n  _temp = to_c(_temp);\n  _is_c = true;\n}\n\n/**\n * Converts temperature to Farenheight, if in Celsius.\n */\nvoid Message::to_farenheit()\n{\n  if(!_is_c)\n  {\n    return;\n  }\n\n  _temp = to_f(_temp);\n  _is_c = false;\n}\n\n/**\n * Free function converting to Celsius.\n */\nint16_t to_c(int16_t temp)\n{\n  return static_cast<int16_t>((static_cast<double>(temp) - CF_Offset) * FC_Scale);\n}\n\n/**\n * Free function converting to Farenheit.\n */\nint16_t to_f(int16_t temp)\n{\n  return static_cast<int16_t>((static_cast<double>(temp) * CF_Scale) + CF_Offset);\n}\n\n/**\n * Function to test the CRC of a RawMessage using the parameters\n * defined by KVH.\n * \\param[in] Message to test\n * \\param[out] Flag indicating if CRC matches.\n */\nbool valid_checksum(const kvh::RawMessage& msg)\n{\n  const size_t CRCSize = sizeof(kvh::RawMessage) - sizeof(msg.crc);\n  const char* ptr = reinterpret_cast<const char*>(&msg);\n  uint32_t check = compute_checksum(ptr, CRCSize);\n\n  return (check == bswap_32(msg.crc));\n}\n\n/**\n * Computes checksum of an arbitrary buffer of a given length,\n * using the KVH CRC parameters\n * \\param[in] buff Pointer to buffer\n * \\param[in] len Length of buffer in bytes\n * \\param[out] CRC checksum value\n */\nuint32_t compute_checksum(const char* buff, size_t len)\n{\n  return boost::crc<crc::Width, crc::Poly, crc::XOr_In, crc::XOr_Out,\n    crc::Reflect_In, crc::Reflect_Out>(buff, len);\n}\n\n}", "meta": {"hexsha": "3ead62df023ddb01e6ea17cb0246af2247b45277", "size": 5984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/types.cpp", "max_stars_repo_name": "SergiGarcia/ros_kvh1750", "max_stars_repo_head_hexsha": "5db4ed7be8de2933f96d14eddb585dfa14af1ba1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-24T22:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T05:54:41.000Z", "max_issues_repo_path": "src/types.cpp", "max_issues_repo_name": "SergiGarcia/ros_kvh1750", "max_issues_repo_head_hexsha": "5db4ed7be8de2933f96d14eddb585dfa14af1ba1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-10-30T02:48:53.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T02:48:53.000Z", "max_forks_repo_path": "src/types.cpp", "max_forks_repo_name": "TRECVT/ros_kvh1750", "max_forks_repo_head_hexsha": "5db4ed7be8de2933f96d14eddb585dfa14af1ba1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-03-15T13:51:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T18:14:42.000Z", "avg_line_length": 17.6, "max_line_length": 82, "alphanum_fraction": 0.6626002674, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19715089903964625}}
{"text": "// -*- mode: c++; indent-tabs-mode: nil; -*-\n//\n// Copyright (c) 2009-2013 Illumina, Inc.\n//\n// This software is provided under the terms and conditions of the\n// Illumina Open Source Software License 1.\n//\n// You should have received a copy of the Illumina Open Source\n// Software License 1 along with this program. If not, see\n// <https://github.com/sequencing/licenses/>\n//\n\n/// \\file\n\n/// variation on the original strowman snv caller -- implements a\n/// compile-time specified grid in allele frequency space and requires\n/// similar frequency as definition of non-somatic.\n///\n\n/// \\author Chris Saunders\n///\n#ifndef __POSITION_SOMATIC_SNV_STRAND_GRID_HH\n#define __POSITION_SOMATIC_SNV_STRAND_GRID_HH\n\n#include \"extended_pos_data.hh\"\n#include \"position_somatic_snv_grid_shared.hh\"\n\n#include \"blt_common/snp_pos_info.hh\"\n#include \"blt_common/position_snp_call_pprob_digt.hh\"\n#include \"blt_util/qscore.hh\"\n#include \"strelka/strelka_shared.hh\"\n\n#include <boost/utility.hpp>\n\n#include <iosfwd>\n\n\n//#define SOMATIC_DEBUG\n\n\nnamespace DIGT_SGRID {\n\n// HET_RES is the number of points sampled between 0 and 0.5 on\n// the continuous frequency scale. Thus a fully sampled axis will\n// be sampled HET_RES*2+3 times.\n//\n// Note that the single-strand tests are only implemented on the\n// half axis containing the reference allele as a major\n// allele. The \"STRAND_STATE_SIZE\" appended to the PRESTAND_SIZE\n// represents these additional strand-specific error states.\n//\nenum constants { HET_RES = 4,\n                 HET_COUNT = HET_RES*2+1,\n                 HET_SIZE = DIGT::SIZE-N_BASE,\n                 STRAND_COUNT = HET_RES,\n                 STRAND_SIZE = HET_SIZE/2,\n                 HET_STATE_SIZE = HET_SIZE*HET_COUNT,\n                 PRESTRAND_SIZE = N_BASE+HET_STATE_SIZE,\n                 STRAND_STATE_SIZE = STRAND_COUNT*STRAND_SIZE\n               };\n\nenum index_t { SIZE = PRESTRAND_SIZE+STRAND_STATE_SIZE };\n\n// generates fast lookup-table to translate between stranded ref-only\n// het states and DIGT het states:\n//\nstruct strand_state_tables {\n    strand_state_tables();\n\n    unsigned digt_state[N_BASE][STRAND_SIZE];\n};\n\nextern const strand_state_tables stables;\n\ninline\nunsigned\nget_het_count(const unsigned state) {\n    if (state<N_BASE)         return 0;\n    if (state<PRESTRAND_SIZE) return (state-N_BASE)/HET_SIZE;\n    return (state-PRESTRAND_SIZE)/STRAND_SIZE;\n}\n\ninline\nbool\nis_strand_state(const unsigned state) {\n    return (state>=PRESTRAND_SIZE);\n}\n\ninline\nunsigned\nget_strand_state(const unsigned state) {\n    return (state-PRESTRAND_SIZE)%STRAND_SIZE;\n}\n\ninline\nunsigned\nget_digt_state(const unsigned state,\n               const unsigned ref_base) {\n    if (state<N_BASE)         return state;\n    if (state<PRESTRAND_SIZE) return N_BASE+((state-N_BASE)%HET_SIZE);\n    return stables.digt_state[ref_base][get_strand_state(state)];\n}\n\n\n// write only most representative genotype, ie \"GT\", for each state\nvoid\nwrite_state(const DIGT_SGRID::index_t gt,\n            const unsigned ref_gt,\n            std::ostream& os);\n\n// write genotype, heterozygous id, and whether this is a single-strand state\nvoid\nwrite_full_state(const DIGT_SGRID::index_t gt,\n                 const unsigned ref_gt,\n                 std::ostream& os);\n}\n\n\nnamespace DDIGT_SGRID {\n\nenum constants { PRESTRAND_SIZE = DIGT_SGRID::PRESTRAND_SIZE*DIGT_SGRID::PRESTRAND_SIZE };\nenum index_t { SIZE = PRESTRAND_SIZE+DIGT_SGRID::STRAND_STATE_SIZE };\n\ninline\nunsigned\nget_state(const unsigned normal_gt,\n          const unsigned tumor_gt) {\n    if (normal_gt<DIGT_SGRID::PRESTRAND_SIZE) return normal_gt+DIGT_SGRID::PRESTRAND_SIZE*tumor_gt;\n    return PRESTRAND_SIZE+normal_gt-DIGT_SGRID::PRESTRAND_SIZE;\n}\n\ninline\nvoid\nget_digt_grid_states(const unsigned dgt,\n                     unsigned& normal_gt,\n                     unsigned& tumor_gt) {\n    if (dgt<PRESTRAND_SIZE) {\n        normal_gt = (dgt%DIGT_SGRID::PRESTRAND_SIZE);\n        tumor_gt = (dgt/DIGT_SGRID::PRESTRAND_SIZE);\n    } else {\n        normal_gt= dgt+DIGT_SGRID::PRESTRAND_SIZE-PRESTRAND_SIZE;\n        tumor_gt=normal_gt;\n    }\n}\n\n// writes state to pattern: \"AA->AG\"\nvoid\nwrite_state(const DDIGT_SGRID::index_t dgt,\n            const unsigned ref_gt,\n            std::ostream& os);\n\n// writes state to pattern: \"AA_0->AG_5_strand\", using a unique id for\n// each heterozygous state. Writing actual allele frequencies instead of just\n// ids TBD\nvoid\nwrite_full_state(const DDIGT_SGRID::index_t dgt,\n                 const unsigned ref_gt,\n                 std::ostream& os);\n\nvoid\nwrite_alt_alleles(const DDIGT_SGRID::index_t dgt,\n                  const unsigned ref_gt,\n                  std::ostream& os);\n\nstruct is_nonsom_maker_t {\n    is_nonsom_maker_t();\n\n    std::vector<bool> val;\n};\n}\n\n\nstd::ostream& operator<<(std::ostream& os,const DDIGT_SGRID::index_t dgt);\n\n\n// object used to pre-compute priors:\nstruct somatic_snv_caller_strand_grid {\n\n    somatic_snv_caller_strand_grid(const strelka_options& opt,\n                                   const pprob_digt_caller& pd_caller);\n\n    //\n    void\n    position_somatic_snv_call(const extended_pos_info& normal_epi,\n                              const extended_pos_info& tumor_epi,\n                              const extended_pos_info* normal_epi_t2_ptr,\n                              const extended_pos_info* tumor_epi_t2_ptr,\n                              somatic_snv_genotype_grid& sgt) const;\n\n    // compute a lot of prior information for various alternate\n    // versions of the method -- we don't actually need all of this for any one computation:\n    //\n    struct prior_set {\n        prior_set()\n            : normal(DIGT_SGRID::SIZE)\n            , somatic_marginal(DIGT_SGRID::SIZE)\n            , normal_poly(DIGT_SGRID::SIZE)\n            , somatic_marginal_poly(DIGT_SGRID::SIZE)\n        {}\n\n        typedef std::vector<blt_float_t> prior_t;\n\n        prior_t normal;\n        prior_t somatic_marginal;\n        prior_t normal_poly;\n        prior_t somatic_marginal_poly;\n    };\n\nprivate:\n\n    const prior_set&\n    get_prior_set(const unsigned ref_id) const {\n        return _lnprior[ref_id];\n    }\n\n    const std::vector<blt_float_t>&\n    lnprior_genomic(const unsigned ref_id) const {\n        return _lnprior[ref_id].normal;\n    }\n\n    const std::vector<blt_float_t>&\n    lnprior_polymorphic(const unsigned ref_id) const {\n        return _lnprior[ref_id].normal_poly;\n    }\n\n    const strelka_options& _opt;\n    prior_set _lnprior[N_BASE+1];\n    blt_float_t _ln_som_match;\n    blt_float_t _ln_som_mismatch;\n};\n\n\n\n// vcf output:\n//\nvoid\nwrite_vcf_somatic_snv_genotype_strand_grid(const strelka_options& opt,\n                                           const somatic_snv_genotype_grid& sgt,\n                                           const extended_pos_data& n1_epd,\n                                           const extended_pos_data& t1_epd,\n                                           const extended_pos_data& n2_epd,\n                                           const extended_pos_data& t2_epd,\n                                           std::ostream& os);\n#endif\n", "meta": {"hexsha": "206818f87920e56210c8f09e8d0062a6ebac1676", "size": 7081, "ext": "hh", "lang": "C++", "max_stars_repo_path": "isaac_variant_caller/src/lib/strelka/position_somatic_snv_strand_grid.hh", "max_stars_repo_name": "sequencing/isaac_variant_caller", "max_stars_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T01:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-04T03:48:21.000Z", "max_issues_repo_path": "isaac_variant_caller/src/lib/strelka/position_somatic_snv_strand_grid.hh", "max_issues_repo_name": "sequencing/isaac_variant_caller", "max_issues_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-07-23T09:38:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-01T05:37:26.000Z", "max_forks_repo_path": "isaac_variant_caller/src/lib/strelka/position_somatic_snv_strand_grid.hh", "max_forks_repo_name": "sequencing/isaac_variant_caller", "max_forks_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:41:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:42:32.000Z", "avg_line_length": 28.9020408163, "max_line_length": 99, "alphanum_fraction": 0.6647366191, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.19715089903964622}}
{"text": "// boost\\math\\distributions\\bernoulli.hpp\n\n// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007.\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// http://en.wikipedia.org/wiki/bernoulli_distribution\n// http://mathworld.wolfram.com/BernoulliDistribution.html\n\n// bernoulli distribution is the discrete probability distribution of\n// the number (k) of successes, in a single Bernoulli trials.\n// It is a version of the binomial distribution when n = 1.\n\n// But note that the bernoulli distribution\n// (like others including the poisson, binomial & negative binomial)\n// is strictly defined as a discrete function: only integral values of k are envisaged.\n// However because of the method of calculation using a continuous gamma function,\n// it is convenient to treat it as if a continuous function,\n// and permit non-integral values of k.\n// To enforce the strict mathematical model, users should use floor or ceil functions\n// on k outside this function to ensure that k is integral.\n\n#ifndef BOOST_MATH_SPECIAL_BERNOULLI_HPP\n#define BOOST_MATH_SPECIAL_BERNOULLI_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/distributions/complement.hpp> // complements\n#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks\n#include <boost/math/special_functions/fpclassify.hpp> // isnan.\n\n#include <utility>\n\nnamespace boost\n{\n  namespace math\n  {\n    namespace bernoulli_detail\n    {\n      // Common error checking routines for bernoulli distribution functions:\n      template <class RealType, class Policy>\n      inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& /* pol */)\n      {\n        if(!(boost::math::isfinite)(p) || (p < 0) || (p > 1))\n        {\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"Success fraction argument is %1%, but must be >= 0 and <= 1 !\", p, Policy());\n          return false;\n        }\n        return true;\n      }\n      template <class RealType, class Policy>\n      inline bool check_dist(const char* function, const RealType& p, RealType* result, const Policy& /* pol */, const std::true_type&)\n      {\n        return check_success_fraction(function, p, result, Policy());\n      }\n      template <class RealType, class Policy>\n      inline bool check_dist(const char* , const RealType& , RealType* , const Policy& /* pol */, const std::false_type&)\n      {\n         return true;\n      }\n      template <class RealType, class Policy>\n      inline bool check_dist(const char* function, const RealType& p, RealType* result, const Policy& /* pol */)\n      {\n         return check_dist(function, p, result, Policy(), typename policies::constructor_error_check<Policy>::type());\n      }\n\n      template <class RealType, class Policy>\n      inline bool check_dist_and_k(const char* function, const RealType& p, RealType k, RealType* result, const Policy& pol)\n      {\n        if(check_dist(function, p, result, Policy(), typename policies::method_error_check<Policy>::type()) == false)\n        {\n          return false;\n        }\n        if(!(boost::math::isfinite)(k) || !((k == 0) || (k == 1)))\n        {\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"Number of successes argument is %1%, but must be 0 or 1 !\", k, pol);\n          return false;\n        }\n       return true;\n      }\n      template <class RealType, class Policy>\n      inline bool check_dist_and_prob(const char* function, RealType p, RealType prob, RealType* result, const Policy& /* pol */)\n      {\n        if((check_dist(function, p, result, Policy(), typename policies::method_error_check<Policy>::type()) && detail::check_probability(function, prob, result, Policy())) == false)\n        {\n          return false;\n        }\n        return true;\n      }\n    } // namespace bernoulli_detail\n\n\n    template <class RealType = double, class Policy = policies::policy<> >\n    class bernoulli_distribution\n    {\n    public:\n      typedef RealType value_type;\n      typedef Policy policy_type;\n\n      bernoulli_distribution(RealType p = 0.5) : m_p(p)\n      { // Default probability = half suits 'fair' coin tossing\n        // where probability of heads == probability of tails.\n        RealType result; // of checks.\n        bernoulli_detail::check_dist(\n           \"boost::math::bernoulli_distribution<%1%>::bernoulli_distribution\",\n          m_p,\n          &result, Policy());\n      } // bernoulli_distribution constructor.\n\n      RealType success_fraction() const\n      { // Probability.\n        return m_p;\n      }\n\n    private:\n      RealType m_p; // success_fraction\n    }; // template <class RealType> class bernoulli_distribution\n\n    typedef bernoulli_distribution<double> bernoulli;\n\n    #ifdef __cpp_deduction_guides\n    template <class RealType>\n    bernoulli_distribution(RealType)->bernoulli_distribution<typename boost::math::tools::promote_args<RealType>::type>;\n    #endif\n\n    template <class RealType, class Policy>\n    inline const std::pair<RealType, RealType> range(const bernoulli_distribution<RealType, Policy>& /* dist */)\n    { // Range of permissible values for random variable k = {0, 1}.\n      using boost::math::tools::max_value;\n      return std::pair<RealType, RealType>(static_cast<RealType>(0), static_cast<RealType>(1));\n    }\n\n    template <class RealType, class Policy>\n    inline const std::pair<RealType, RealType> support(const bernoulli_distribution<RealType, Policy>& /* dist */)\n    { // Range of supported values for random variable k = {0, 1}.\n      // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n      return std::pair<RealType, RealType>(static_cast<RealType>(0), static_cast<RealType>(1));\n    }\n\n    template <class RealType, class Policy>\n    inline RealType mean(const bernoulli_distribution<RealType, Policy>& dist)\n    { // Mean of bernoulli distribution = p (n = 1).\n      return dist.success_fraction();\n    } // mean\n\n    // Rely on dereived_accessors quantile(half)\n    //template <class RealType>\n    //inline RealType median(const bernoulli_distribution<RealType, Policy>& dist)\n    //{ // Median of bernoulli distribution is not defined.\n    //  return tools::domain_error<RealType>(BOOST_CURRENT_FUNCTION, \"Median is not implemented, result is %1%!\", std::numeric_limits<RealType>::quiet_NaN());\n    //} // median\n\n    template <class RealType, class Policy>\n    inline RealType variance(const bernoulli_distribution<RealType, Policy>& dist)\n    { // Variance of bernoulli distribution =p * q.\n      return  dist.success_fraction() * (1 - dist.success_fraction());\n    } // variance\n\n    template <class RealType, class Policy>\n    RealType pdf(const bernoulli_distribution<RealType, Policy>& dist, const RealType& k)\n    { // Probability Density/Mass Function.\n      BOOST_FPU_EXCEPTION_GUARD\n      // Error check:\n      RealType result = 0; // of checks.\n      if(false == bernoulli_detail::check_dist_and_k(\n        \"boost::math::pdf(bernoulli_distribution<%1%>, %1%)\",\n        dist.success_fraction(), // 0 to 1\n        k, // 0 or 1\n        &result, Policy()))\n      {\n        return result;\n      }\n      // Assume k is integral.\n      if (k == 0)\n      {\n        return 1 - dist.success_fraction(); // 1 - p\n      }\n      else  // k == 1\n      {\n        return dist.success_fraction(); // p\n      }\n    } // pdf\n\n    template <class RealType, class Policy>\n    inline RealType cdf(const bernoulli_distribution<RealType, Policy>& dist, const RealType& k)\n    { // Cumulative Distribution Function Bernoulli.\n      RealType p = dist.success_fraction();\n      // Error check:\n      RealType result = 0;\n      if(false == bernoulli_detail::check_dist_and_k(\n        \"boost::math::cdf(bernoulli_distribution<%1%>, %1%)\",\n        p,\n        k,\n        &result, Policy()))\n      {\n        return result;\n      }\n      if (k == 0)\n      {\n        return 1 - p;\n      }\n      else\n      { // k == 1\n        return 1;\n      }\n    } // bernoulli cdf\n\n    template <class RealType, class Policy>\n    inline RealType cdf(const complemented2_type<bernoulli_distribution<RealType, Policy>, RealType>& c)\n    { // Complemented Cumulative Distribution Function bernoulli.\n      RealType const& k = c.param;\n      bernoulli_distribution<RealType, Policy> const& dist = c.dist;\n      RealType p = dist.success_fraction();\n      // Error checks:\n      RealType result = 0;\n      if(false == bernoulli_detail::check_dist_and_k(\n        \"boost::math::cdf(bernoulli_distribution<%1%>, %1%)\",\n        p,\n        k,\n        &result, Policy()))\n      {\n        return result;\n      }\n      if (k == 0)\n      {\n        return p;\n      }\n      else\n      { // k == 1\n        return 0;\n      }\n    } // bernoulli cdf complement\n\n    template <class RealType, class Policy>\n    inline RealType quantile(const bernoulli_distribution<RealType, Policy>& dist, const RealType& p)\n    { // Quantile or Percent Point Bernoulli function.\n      // Return the number of expected successes k either 0 or 1.\n      // for a given probability p.\n\n      RealType result = 0; // of error checks:\n      if(false == bernoulli_detail::check_dist_and_prob(\n        \"boost::math::quantile(bernoulli_distribution<%1%>, %1%)\",\n        dist.success_fraction(),\n        p,\n        &result, Policy()))\n      {\n        return result;\n      }\n      if (p <= (1 - dist.success_fraction()))\n      { // p <= pdf(dist, 0) == cdf(dist, 0)\n        return 0;\n      }\n      else\n      {\n        return 1;\n      }\n    } // quantile\n\n    template <class RealType, class Policy>\n    inline RealType quantile(const complemented2_type<bernoulli_distribution<RealType, Policy>, RealType>& c)\n    { // Quantile or Percent Point bernoulli function.\n      // Return the number of expected successes k for a given\n      // complement of the probability q.\n      //\n      // Error checks:\n      RealType q = c.param;\n      const bernoulli_distribution<RealType, Policy>& dist = c.dist;\n      RealType result = 0;\n      if(false == bernoulli_detail::check_dist_and_prob(\n        \"boost::math::quantile(bernoulli_distribution<%1%>, %1%)\",\n        dist.success_fraction(),\n        q,\n        &result, Policy()))\n      {\n        return result;\n      }\n\n      if (q <= 1 - dist.success_fraction())\n      { // // q <= cdf(complement(dist, 0)) == pdf(dist, 0)\n        return 1;\n      }\n      else\n      {\n        return 0;\n      }\n    } // quantile complemented.\n\n    template <class RealType, class Policy>\n    inline RealType mode(const bernoulli_distribution<RealType, Policy>& dist)\n    {\n      return static_cast<RealType>((dist.success_fraction() <= 0.5) ? 0 : 1); // p = 0.5 can be 0 or 1\n    }\n\n    template <class RealType, class Policy>\n    inline RealType skewness(const bernoulli_distribution<RealType, Policy>& dist)\n    {\n      BOOST_MATH_STD_USING; // Aid ADL for sqrt.\n      RealType p = dist.success_fraction();\n      return (1 - 2 * p) / sqrt(p * (1 - p));\n    }\n\n    template <class RealType, class Policy>\n    inline RealType kurtosis_excess(const bernoulli_distribution<RealType, Policy>& dist)\n    {\n      RealType p = dist.success_fraction();\n      // Note Wolfram says this is kurtosis in text, but gamma2 is the kurtosis excess,\n      // and Wikipedia also says this is the kurtosis excess formula.\n      // return (6 * p * p - 6 * p + 1) / (p * (1 - p));\n      // But Wolfram kurtosis article gives this simpler formula for kurtosis excess:\n      return 1 / (1 - p) + 1/p -6;\n    }\n\n    template <class RealType, class Policy>\n    inline RealType kurtosis(const bernoulli_distribution<RealType, Policy>& dist)\n    {\n      RealType p = dist.success_fraction();\n      return 1 / (1 - p) + 1/p -6 + 3;\n      // Simpler than:\n      // return (6 * p * p - 6 * p + 1) / (p * (1 - p)) + 3;\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_MATH_SPECIAL_BERNOULLI_HPP\n\n\n\n", "meta": {"hexsha": "78b6d4f1266b4c4e93bd93353ca1b624e464a902", "size": 12336, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/distributions/bernoulli.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/distributions/bernoulli.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/distributions/bernoulli.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": 36.0701754386, "max_line_length": 182, "alphanum_fraction": 0.6398346304, "num_tokens": 3068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19715089348509107}}
{"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_COMPARE_LE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COMPARE_LE_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-reduction\n    Function object implementing compare_le capabilities\n\n    Returns a logical scalar that is the result of the lexicographic\n    test for <= on all elements of the entries\n\n    It is probably not what you wish. Have a look to @ref is_less_equal\n\n    This is a convenient alias of @ref compare_less_equal\n  **/\n  const boost::dispatch::functor<tag::compare_le_> compare_le = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/compare_less_equal.hpp>\n#include <boost/simd/function/simd/compare_le.hpp>\n\n#endif\n", "meta": {"hexsha": "29992823093e00b62ca5d9211d69b4b27a3114c1", "size": 1138, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/compare_le.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/compare_le.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/compare_le.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.1794871795, "max_line_length": 100, "alphanum_fraction": 0.6247803163, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19715089168199268}}
{"text": "#include <boost/regex/icu.hpp>\n#include <iostream>\n\nint main(int argc, const char * const argv[])\n{\n    return boost::u32regex_match( \"Is icu \u56f3\u66f8\u9928 there ?\", boost::make_u32regex( \"\u66f8\" ) );       \n}", "meta": {"hexsha": "677d399d569a437fd800d2b0863bb6ab33f30a5d", "size": 195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_package/regex_use_icu.cpp", "max_stars_repo_name": "Zinnion/conan-boost", "max_stars_repo_head_hexsha": "4a488cbda8b8b9676e8a1a34173838f99d32603d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2018-02-02T16:08:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-19T13:46:57.000Z", "max_issues_repo_path": "test_package/regex_use_icu.cpp", "max_issues_repo_name": "Zinnion/conan-boost", "max_issues_repo_head_hexsha": "4a488cbda8b8b9676e8a1a34173838f99d32603d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 93.0, "max_issues_repo_issues_event_min_datetime": "2018-02-12T11:42:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-10T09:53:42.000Z", "max_forks_repo_path": "test_package/regex_use_icu.cpp", "max_forks_repo_name": "Zinnion/conan-boost", "max_forks_repo_head_hexsha": "4a488cbda8b8b9676e8a1a34173838f99d32603d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2018-02-04T02:41:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-15T00:25:31.000Z", "avg_line_length": 27.8571428571, "max_line_length": 93, "alphanum_fraction": 0.6512820513, "num_tokens": 62, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.197042654598895}}
{"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// Copyright (c) 2014-2015 Samuel Debionne, Grenoble, France.\n\n// This file was modified by Oracle on 2015, 2016, 2017, 2018, 2019.\n// Modifications copyright (c) 2015-2019, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\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_GEOMETRY_STRATEGIES_SPHERICAL_EXPAND_BOX_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_EXPAND_BOX_HPP\n\n#include <algorithm>\n#include <cstddef>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_system.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/algorithms/convert.hpp>\n#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>\n#include <boost/geometry/algorithms/detail/normalize.hpp>\n#include <boost/geometry/algorithms/detail/envelope/transform_units.hpp>\n#include <boost/geometry/algorithms/detail/envelope/range_of_boxes.hpp>\n#include <boost/geometry/algorithms/dispatch/envelope.hpp>\n\n#include <boost/geometry/geometries/helper_geometry.hpp>\n\n#include <boost/geometry/strategies/expand.hpp>\n\n#include <boost/geometry/views/detail/indexed_point_view.hpp>\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace envelope\n{\n\ntemplate\n<\n    std::size_t Index,\n    std::size_t DimensionCount\n>\nstruct envelope_indexed_box_on_spheroid\n{\n    template <typename BoxIn, typename BoxOut>\n    static inline void apply(BoxIn const& box_in, BoxOut& mbr)\n    {\n        // transform() does not work with boxes of dimension higher\n        // than 2; to account for such boxes we transform the min/max\n        // points of the boxes using the indexed_point_view\n        detail::indexed_point_view<BoxIn const, Index> box_in_corner(box_in);\n        detail::indexed_point_view<BoxOut, Index> mbr_corner(mbr);\n\n        // first transform the units\n        transform_units(box_in_corner, mbr_corner);\n\n        // now transform the remaining coordinates\n        detail::conversion::point_to_point\n            <\n                detail::indexed_point_view<BoxIn const, Index>,\n                detail::indexed_point_view<BoxOut, Index>,\n                2,\n                DimensionCount\n            >::apply(box_in_corner, mbr_corner);\n    }\n};\n\nstruct envelope_box_on_spheroid\n{\n    template <typename BoxIn, typename BoxOut>\n    static inline void apply(BoxIn const& box_in, BoxOut& mbr)\n    {\n        // BoxIn can be non-mutable\n        typename helper_geometry<BoxIn>::type box_in_normalized;\n        geometry::convert(box_in, box_in_normalized);\n        \n        if (! is_inverse_spheroidal_coordinates(box_in))\n        {\n            strategy::normalize::spherical_box::apply(box_in, box_in_normalized);\n        }\n\n        geometry::detail::envelope::envelope_indexed_box_on_spheroid\n            <\n                min_corner, dimension<BoxIn>::value\n            >::apply(box_in_normalized, mbr);\n\n        geometry::detail::envelope::envelope_indexed_box_on_spheroid\n            <\n                max_corner, dimension<BoxIn>::value\n            >::apply(box_in_normalized, mbr);\n    }\n};\n\n}} // namespace detail::envelope\n#endif // DOXYGEN_NO_DETAIL\n\n\nnamespace strategy { namespace expand\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\nstruct box_on_spheroid\n{\n    template <typename BoxOut, typename BoxIn>\n    static inline void apply(BoxOut& box_out, BoxIn const& box_in)\n    {\n        // normalize both boxes and convert box-in to be of type of box-out\n        BoxOut mbrs[2];\n        geometry::detail::envelope::envelope_box_on_spheroid::apply(box_in, mbrs[0]);\n        geometry::detail::envelope::envelope_box_on_spheroid::apply(box_out, mbrs[1]);\n\n        // compute the envelope of the two boxes\n        geometry::detail::envelope::envelope_range_of_boxes::apply(mbrs, box_out);\n    }\n};\n\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\nstruct spherical_box\n    : detail::box_on_spheroid\n{};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n\ntemplate <typename CalculationType>\nstruct default_strategy<box_tag, spherical_equatorial_tag, CalculationType>\n{\n    typedef spherical_box type;\n};\n\ntemplate <typename CalculationType>\nstruct default_strategy<box_tag, spherical_polar_tag, CalculationType>\n{\n    typedef spherical_box type;\n};\n\ntemplate <typename CalculationType>\nstruct default_strategy<box_tag, geographic_tag, CalculationType>\n{\n    typedef spherical_box type;\n};\n\n} // namespace services\n\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::expand\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_EXPAND_BOX_HPP\n", "meta": {"hexsha": "e4bfafadd5588603f0b7c98ac317506ad16bf1b7", "size": 5203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/spherical/expand_box.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/geometry/strategies/spherical/expand_box.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/geometry/strategies/spherical/expand_box.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.5625, "max_line_length": 86, "alphanum_fraction": 0.7274649241, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.19704265085804076}}
{"text": "#include <thread>\n#include <string>\n#include <fstream>\n#include <unistd.h>\n#include <Eigen/Core>\n//#include <tbb/concurrent_unordered_map.h>\n#include <unordered_map>\n#include <gflags/gflags.h>\n#include <comlog/comlog.h>\n#include <baidu/rpc/server.h>\n#include \"document.pb.h\"\n#include \"rank_service.pb.h\"\n#include <pthread.h>\n\npthread_rwlock_t l;\n\ntypedef ::Eigen::Matrix<float, 32, 1> Vector;\ntypedef ::Eigen::Map<Vector> MVector;\nusing ::baidu::lijiang01::proto::Document;\n\nDEFINE_int32(log_level, 4, \"\");\nDEFINE_uint64(limit, 10000, \"\");\nDEFINE_int32(port, 8899, \"\");\nDEFINE_int32(sleep, 1000, \"\");\n\nstatic ::std::atomic<uint64_t> all;\nstatic int64_t latency_us;\n\nclass Node {\npublic:\n    Node(const Node& other) {\n        char* x = NULL;\n        CFATAL_LOG(\" copy\");\n        x[10000] = 10;\n    }\n\n    Node(Node&& other) : _brife(other._brife.exchange(nullptr, ::std::memory_order_relaxed)) {}\n\n    Node(const Document& brife) : _brife(new Document(brife)) {}\n\n    const Document* brife() const {\n        return _brife.load(::std::memory_order_relaxed);\n    }\n\n    void brife(Document* new_brife) {\n        auto old_brife = _brife.exchange(new_brife, ::std::memory_order_relaxed);\n        if (old_brife != nullptr) {\n            usleep(1000);\n            delete old_brife;\n        }\n    }\n\n    void brife(Document&& new_brife) {\n        auto created_brife = new Document();\n        created_brife->Swap(&new_brife);\n        brife(created_brife);\n    }\n\n    ~Node() {\n        brife(nullptr);\n    }\n\nprivate:\n    ::std::atomic<const Document*> _brife;\n};\n\nclass RankServiceImpl : public ::baidu::lijiang01::proto::RankService {\npublic:\n    RankServiceImpl(\n        //::tbb::concurrent_unordered_map<uint64_t, Node>& store\n        ::std::unordered_map<uint64_t, Node>& store\n        ) : _store(store) {};\n    virtual ~RankServiceImpl() {};\n    virtual void rank(google::protobuf::RpcController* cntl_base,\n                      const ::baidu::lijiang01::proto::RankRequest* request,\n                      ::baidu::lijiang01::proto::RankResponse* response,\n                      google::protobuf::Closure* done) {\n        auto begin = ::base::cpuwide_time_ns();\n        Vector v;\n        for (size_t i = 0; i < 32; i++) {\n            v(i, 0) = 0.0;\n        }\n        response->mutable_nid()->Reserve(request->nid_size());\n        response->mutable_score()->Reserve(request->nid_size());\n            pthread_rwlock_rdlock(&l);\n        for (auto nid : request->nid()) { \n            auto it = _store.find(nid);\n            auto& node = it->second;\n            const Document* x = node.brife();\n            MVector mv((float*)(x->ann_vector().data()));\n            float score = v.dot(mv);\n            response->add_nid(nid);\n            response->add_score(score);\n\n        }\n            pthread_rwlock_unlock(&l);\n        all.fetch_add(1, ::std::memory_order_relaxed);\n        auto end = ::base::cpuwide_time_ns();\n        latency_us = end - begin;\n        done->Run();\n    }\n\nprivate:\n    //::tbb::concurrent_unordered_map<uint64_t, Node>& _store;\n    ::std::unordered_map<uint64_t, Node>& _store;\n};\n\n//::tbb::concurrent_unordered_map<uint64_t, Node> store;\n::std::unordered_map<uint64_t, Node> store;\nstatic void status() {\n    uint64_t last_all = all.load(::std::memory_order_relaxed);\n    ::std::ifstream doc(\"d\");\n    ::std::string line;\n    Document document;\n    for (size_t i = 0; i < 32; i++) {\n        document.add_ann_vector(0.0);\n    }\n\n    while (true) {\n        usleep(FLAGS_sleep);\n        uint64_t current_all = all.load(::std::memory_order_relaxed);\n        last_all = current_all;\n        ::std::getline(doc, line);\n        char* brife_start = nullptr;\n        uint64_t nid = strtoull(line.c_str(), &brife_start, 10);\n        ++brife_start;\n        document.set_data(brife_start);\n\n        pthread_rwlock_wrlock(&l);\n        store.emplace(nid, Node(document));\n        pthread_rwlock_unlock(&l);\n    }\n}\n\nint32_t main(int32_t argc, char** argv) {\n    ::google::ParseCommandLineFlags(&argc, &argv, true);\n    pthread_rwlock_init(&l, NULL);\n\n    com_logstat_t logstat;\n    logstat.sysevents = FLAGS_log_level;\n    com_device_t dev[1];\n    strcpy(dev[0].type, \"TTY\");\n    COMLOG_SETSYSLOG(dev[0]);\n    com_openlog(\"main\", dev, 1, &logstat);\n\n    {\n        ::std::ifstream doc(\"doc\");\n        ::std::string line;\n        uint64_t num = 0;\n        Document document;\n        for (size_t i = 0; i < 32; i++) {\n            document.add_ann_vector(0.0);\n        }\n        while (::std::getline(doc, line)) {\n            if (++num > FLAGS_limit) {\n                break;\n            }\n            char* brife_start = nullptr;\n            uint64_t nid = strtoull(line.c_str(), &brife_start, 10);\n            ++brife_start;\n            document.set_data(brife_start);\n            store.emplace(nid, Node(document));\n        }\n    }\n\n    CNOTICE_LOG(\" doc = %llu\", store.size());\n\n    ::baidu::rpc::Server server;\n    ::RankServiceImpl rank_service(store);\n    server.AddService(&rank_service, ::baidu::rpc::SERVER_DOESNT_OWN_SERVICE);\n\n    baidu::rpc::ServerOptions options;\n    server.Start(FLAGS_port, &options);\n\n    ::std::thread status_thread(status);\n    status_thread.detach();\n    \n    server.RunUntilAskedToQuit();\n\n    return 0;\n}\n", "meta": {"hexsha": "bf583e3abebb3af615f09ae674729bfe9473fd52", "size": 5245, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rank_server.cpp", "max_stars_repo_name": "derek-zhang/linux", "max_stars_repo_head_hexsha": "1cc4b9f869378e12dc088ca928ef9769d4dae277", "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": "rank_server.cpp", "max_issues_repo_name": "derek-zhang/linux", "max_issues_repo_head_hexsha": "1cc4b9f869378e12dc088ca928ef9769d4dae277", "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": "rank_server.cpp", "max_forks_repo_name": "derek-zhang/linux", "max_forks_repo_head_hexsha": "1cc4b9f869378e12dc088ca928ef9769d4dae277", "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.8186813187, "max_line_length": 95, "alphanum_fraction": 0.597521449, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.19703609786663737}}
{"text": "/**\n ** Copyright (c) 2014 Illumina, Inc.\n **\n ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE),\n ** covered by the \"BSD 2-Clause License\" (see accompanying LICENSE file)\n **\n ** \\author Lilian Janin\n **/\n\n#ifndef EAGLE_GENOME_QUALITY_MODEL_HH\n#define EAGLE_GENOME_QUALITY_MODEL_HH\n\n#include <fstream>\n#include <boost/assign.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\n#include \"model/Nucleotides.hh\"\n#include \"genome/ErrorModelPlugin.hh\"\n\n\nnamespace eagle\n{\nnamespace genome\n{\n\nclass MotifRepeatQualityDropInfo;\n\n// ClusterErrorModelContext contains all the data that needs to be remembered to process consequent cycles of a read cluster\n// It contains a substructure for each error plugin\nstruct ClusterErrorModelContext\n{\n    struct\n    {\n        unsigned int profileNumber;\n    } qualityModelContext;\n\n    struct\n    {\n        int qualityDrop;\n    } phasingContext;\n\n    struct\n    {\n        char lastBase;\n        signed char errorDirection; // insertion=+1, deletion=-1\n        unsigned int homopolymerLength;\n    } homopolymerModelContext;\n\n    struct\n    {\n        uint64_t kmer;\n        unsigned int kmerLength;\n        double qualityDropLevel;\n        MotifRepeatQualityDropInfo *shortTermEffect;\n        float shortTermQualityDrop;\n    } motifQualityDropModelContext;\n\n    ClusterErrorModelContext()\n    {\n        initialiseForNewRead();\n    }\n\n    void initialiseForNewRead()\n    {\n        qualityModelContext.profileNumber = 0;\n        homopolymerModelContext.lastBase = 0;\n        homopolymerModelContext.errorDirection = 0;\n        homopolymerModelContext.homopolymerLength = 0;\n        motifQualityDropModelContext.kmer = 0;\n        motifQualityDropModelContext.kmerLength = 0;\n        motifQualityDropModelContext.shortTermQualityDrop = 0;\n        motifQualityDropModelContext.shortTermEffect = NULL;\n        motifQualityDropModelContext.qualityDropLevel = 0;\n        phasingContext.qualityDrop = 0;\n    }\n};\n\n// QualityModel provides a way to generate the phred quality values\nclass QualityModel\n{\npublic:\n    QualityModel( const std::vector<boost::filesystem::path>& qualityTableFiles );\n\n    unsigned int getQuality( boost::mt19937& randomGen, const unsigned int cycle, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext );\n    unsigned int getQuality( boost::mt19937& randomGen, const unsigned int cycle, ClusterErrorModelContext& clusterErrorModelContext );\n    double qualToProbError(unsigned int qual);\n\nprivate:\n    unsigned int parseQualityTableFile( const boost::filesystem::path& filename, const int cycleOffset = 0 );\n    void createDiscreteDistributionPerCycle();\n\n    std::vector< std::vector< boost::random::discrete_distribution<> > > qualityDistPerCyclePerLastQuality;\n\n    // New stuff\n    unsigned int parseBigQualityTableFile( const boost::filesystem::path& filename );\n    bool useNewStuff_;\n    std::vector< unsigned int > bigTable_;\n};\n\n\nclass SequencingMismatchModel\n{\npublic:\n    SequencingMismatchModel( const boost::filesystem::path& mismatchTableFilename );\n    void apply( boost::mt19937& randomGen, const double errorRate, unsigned int& randomErrorType, char& bclBase, ClusterErrorModelContext& clusterErrorModelContext );\n\nprivate:\n    std::vector< boost::random::discrete_distribution<> > errorDistPerBase;\n};\n\n\nclass HomopolymerIndelModel\n{\npublic:\n    HomopolymerIndelModel( const boost::filesystem::path& homopolymerIndelTableFilename );\n    void apply( boost::mt19937& randomGen, const double errorRate, unsigned int& randomErrorType, char& bclBase, ClusterErrorModelContext& clusterErrorModelContext );\n\nprivate:\n    std::vector< double > homoDeletionTable_;\n    std::vector< double > homoInsertionTable_;\n};\n\n\nclass MotifQualityDropModel\n{\npublic:\n    MotifQualityDropModel( const boost::filesystem::path& tableFilename );\n    void applyQualityDrop( unsigned int& quality, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext, const unsigned int cycle, boost::mt19937& randomGen );\n\nprivate:\n    MotifRepeatQualityDropInfo* getMotifRepeatQualityDrop( const uint64_t kmer1, const unsigned int repeatKmerLength, const unsigned int repeatCount );\n    bool active_;\n    std::vector< std::map< uint64_t, boost::shared_ptr< std::vector< MotifRepeatQualityDropInfo > > > > tableData_;\n    eagle::model::IUPAC baseConverter_;\n};\n\n\nclass RandomQualityDropModel\n{\npublic:\n    RandomQualityDropModel( /*const boost::filesystem::path& tableFilename*/ );\n    void applyQualityDrop( unsigned int& quality, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext );\n\nprivate:\n};\n\n\nclass QualityGlitchModel\n{\npublic:\n    QualityGlitchModel( /*const boost::filesystem::path& tableFilename*/ );\n    void applyQualityDrop( unsigned int& quality, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext );\n\nprivate:\n};\n\n\nclass HappyPhasingModel\n{\npublic:\n    HappyPhasingModel( /*const boost::filesystem::path& tableFilename*/ );\n    void applyQualityDrop( unsigned int& quality, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext );\n\nprivate:\n};\n\n\nclass QQTable\n{\npublic:\n    QQTable( const boost::filesystem::path& qqTableFilename );\n    double qualToErrorRate( const unsigned int quality );\n\nprivate:\n    std::vector< double > qualityToProbability_;\n};\n\n\nclass ErrorModel\n{\npublic:\n    enum ErrorType { NoError, BaseSubstitution, BaseDeletion, BaseInsertion } ;\n\n    ErrorModel( const std::vector<boost::filesystem::path>& qualityTableFiles, const boost::filesystem::path& mismatchTableFile, const boost::filesystem::path& homopolymerIndelTableFilename, const boost::filesystem::path& motifQualityDropTableFilename, const boost::filesystem::path& qqTableFilename, const std::vector< std::string >& errorModelOptions );\n    void getQualityAndRandomError( boost::mt19937& randomGen, const unsigned int cycle, const char base, unsigned int& quality, unsigned int& randomErrorType, char& bclBase, ClusterErrorModelContext& clusterErrorModelContext );\n\nprivate:\n    QualityModel qualityModel_;\n    SequencingMismatchModel sequencingMismatchModel_;\n    HomopolymerIndelModel homopolymerIndelModel_;\n    MotifQualityDropModel motifQualityDropModel_;\n    RandomQualityDropModel randomQualityDropModel_;\n    QualityGlitchModel qualityGlitchModel_;\n    HappyPhasingModel happyPhasingModel_;\n    LongreadBaseDuplicationModel longreadBaseDuplicationModel_;\n    LongreadDeletionModel longreadDeletionModel_;\n    QQTable qqTable_;\n    eagle::model::IUPAC baseConverter_;\n};\n\n\n} // namespace genome\n} // namespace eagle\n\n#endif // EAGLE_GENOME_QUALITY_MODEL_HH\n", "meta": {"hexsha": "00af3c00fa8f1eaf8151324f912ef9f388bf223e", "size": 6761, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/c++/include/genome/QualityModel.hh", "max_stars_repo_name": "sequencing/EAGLE", "max_stars_repo_head_hexsha": "6da0438c1f7620ea74dec1f34baf20bb0b14b110", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-05-22T16:03:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T12:12:46.000Z", "max_issues_repo_path": "src/c++/include/genome/QualityModel.hh", "max_issues_repo_name": "sequencing/EAGLE", "max_issues_repo_head_hexsha": "6da0438c1f7620ea74dec1f34baf20bb0b14b110", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-10-21T11:19:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T05:01:12.000Z", "max_forks_repo_path": "src/c++/include/genome/QualityModel.hh", "max_forks_repo_name": "sequencing/EAGLE", "max_forks_repo_head_hexsha": "6da0438c1f7620ea74dec1f34baf20bb0b14b110", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-01-21T00:31:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-12T13:28:57.000Z", "avg_line_length": 32.1952380952, "max_line_length": 355, "alphanum_fraction": 0.7614258246, "num_tokens": 1579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.19702590570932774}}
{"text": "#include <I3Test.h>\n\n#include <PROPOSAL-icetray/I3PropagatorServicePROPOSAL.h>\n#include <PROPOSAL-icetray/SimplePropagator.h>\n#include <dataclasses/physics/I3Particle.h>\n#include <phys-services/I3SPRNGRandomService.h>\n\n#include <boost/make_shared.hpp>\n\nTEST_GROUP(Repeatablility);\n\nstatic I3Particle make_particle()\n{\n    I3Particle p;\n    p.SetPos(0, 0, 2e3);\n    p.SetDir(0, 0);\n    p.SetTime(0);\n    p.SetType(I3Particle::MuMinus);\n    p.SetLocationType(I3Particle::InIce);\n    p.SetEnergy(1e6);\n\n    return p;\n}\n\nTEST(SimplePropagator)\n{\n    I3RandomServicePtr rng(new I3SPRNGRandomService(1, 10000, 2));\n\n    boost::shared_ptr<PROPOSAL::SimplePropagator> prop(\n        new PROPOSAL::SimplePropagator(I3Particle::MuMinus, \"ice\", 5e2, -1));\n    prop->SetRandomNumberGenerator(rng);\n    double distance = 1e2;\n\n    std::vector<std::vector<I3Particle> > daughters;\n    std::vector<I3Particle> primaries;\n    std::vector<I3FrameObjectPtr> states;\n    for (int i = 0; i < 100; i++)\n    {\n        I3Particle p = make_particle();\n        p.SetEnergy(std::pow(10, rng->Uniform(3, 6)));\n        primaries.push_back(p);\n        states.push_back(rng->GetState());\n        boost::shared_ptr<std::vector<I3Particle> > d(new std::vector<I3Particle>);\n        prop->propagate(p, distance, d);\n        daughters.push_back(*d);\n    }\n\n    // Now, replay the simulation and ensure we get the same thing\n\n    for (size_t i = 0; i < daughters.size(); i++)\n    {\n        // Throw out a random subset of events. The remainder should\n        // be reproducible given the same sequence of random numbers,\n        // unless of course the propagator keeps secret state.\n        if (rng->Uniform() < 0.5)\n            continue;\n        rng->RestoreState(states[i]);\n        boost::shared_ptr<std::vector<I3Particle> > d(new std::vector<I3Particle>);\n        prop->propagate(primaries[i], distance, d);\n        ENSURE_EQUAL(daughters[i].size(), d->size(), \"Same number of particles must be produced\");\n        for (size_t j = 0; j < daughters[i].size(); j++)\n        {\n            I3Particle& p1 = daughters[i][j];\n            I3Particle& p2 = (*d)[j];\n            ENSURE_EQUAL(p1.GetType(), p2.GetType(), \"Secondaries must have the same type\");\n            ENSURE_EQUAL(p1.GetTime(), p2.GetTime(), \"Times must be completely identical\");\n            ENSURE_EQUAL(p1.GetEnergy(), p2.GetEnergy(), \"Energies must completely identical\");\n        }\n    }\n}\n\nTEST(PropagatorService)\n{\n    I3RandomServicePtr rng(new I3SPRNGRandomService(1, 10000, 1));\n    I3FrameObjectPtr state = rng->GetState();\n\n    PROPOSAL::I3PropagatorServicePROPOSALPtr prop(new PROPOSAL::I3PropagatorServicePROPOSAL);\n    prop->SetRandomNumberGenerator(rng);\n\n    I3PropagatorService::DiagnosticMapPtr frame(new I3PropagatorService::DiagnosticMap);\n    // the dummy I3Frame makes compiler happy, but won't be used\n    I3FramePtr dummy(new I3Frame()); \n\n    std::vector<std::vector<I3Particle> > daughters;\n    for (int i = 0; i < 2; i++)\n    {\n        I3Particle p              = make_particle();\n        std::vector<I3Particle> d = prop->Propagate(p, frame, dummy);\n        daughters.push_back(d);\n    }\n\n    rng->RestoreState(state);\n\n    for (size_t i = 0; i < daughters.size(); i++)\n    {\n        I3Particle p              = make_particle();\n        std::vector<I3Particle> d = prop->Propagate(p, frame, dummy);\n        ENSURE_EQUAL(daughters[i].size(), d.size());\n        for (size_t j = 0; j < daughters[i].size(); j++)\n        {\n            I3Particle& p1 = daughters[i][j];\n            I3Particle& p2 = d[j];\n            ENSURE_EQUAL(p1.GetType(), p2.GetType());\n            ENSURE_EQUAL(p1.GetTime(), p2.GetTime());\n            ENSURE_EQUAL(p1.GetEnergy(), p2.GetEnergy());\n        }\n    }\n}\n", "meta": {"hexsha": "2d32d8d7be4ef19a51fd6a9ab41e8342299e09c9", "size": 3745, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "PROPOSAL/private/PROPOSAL-icetray/test/Repeatability.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-icetray/test/Repeatability.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-icetray/test/Repeatability.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": 34.3577981651, "max_line_length": 98, "alphanum_fraction": 0.6288384513, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "// AbilitySpend.cpp\n//\n#include \"StdAfx.h\"\n#include \"AbilitySpend.h\"\n#include \"XmlLib\\SaxWriter.h\"\n#include <boost/static_assert.hpp>\n\n#define DL_ELEMENT AbilitySpend\n\nnamespace\n{\n    const wchar_t f_saxElementName[] = L\"AbilitySpend\";\n    DL_DEFINE_NAMES(AbilitySpend_PROPERTIES)\n\n    const unsigned f_verCurrent = 1;\n\n    size_t c_maxSpend = 10;\n    int c_statIncreaseCosts[] = {1, 1, 1, 1, 1, 1, 2, 2, 3, 3};\n    const unsigned arraySize = sizeof(c_statIncreaseCosts) / sizeof(*c_statIncreaseCosts);\n    BOOST_STATIC_ASSERT(arraySize == 10);\n}\n\nAbilitySpend::AbilitySpend() :\n    XmlLib::SaxContentElement(f_saxElementName, f_verCurrent)\n{\n    DL_INIT(AbilitySpend_PROPERTIES)\n}\n\nDL_DEFINE_ACCESS(AbilitySpend_PROPERTIES)\n\nXmlLib::SaxContentElementInterface * AbilitySpend::StartElement(\n        const XmlLib::SaxString & name,\n        const XmlLib::SaxAttributes & attributes)\n{\n    XmlLib::SaxContentElementInterface * subHandler =\n            SaxContentElement::StartElement(name, attributes);\n\n    DL_START(AbilitySpend_PROPERTIES)\n\n    return subHandler;\n}\n\nvoid AbilitySpend::EndElement()\n{\n    SaxContentElement::EndElement();\n    DL_END(AbilitySpend_PROPERTIES)\n    if (m_StrSpend > c_maxSpend)\n    {\n        SAXASSERT(false, DL_STRINGIZE(DL_ELEMENT) \"::m_StrSpend had invalid value\");\n    }\n    if (m_DexSpend > c_maxSpend)\n    {\n        SAXASSERT(false, DL_STRINGIZE(DL_ELEMENT) \"::m_DexSpend had invalid value\");\n    }\n    if (m_ConSpend > c_maxSpend)\n    {\n        SAXASSERT(false, DL_STRINGIZE(DL_ELEMENT) \"::m_ConSpend had invalid value\");\n    }\n    if (m_IntSpend > c_maxSpend)\n    {\n        SAXASSERT(false, DL_STRINGIZE(DL_ELEMENT) \"::m_IntSpend had invalid value\");\n    }\n    if (m_WisSpend > c_maxSpend)\n    {\n        SAXASSERT(false, DL_STRINGIZE(DL_ELEMENT) \"::m_WisSpend had invalid value\");\n    }\n    if (m_ChaSpend > c_maxSpend)\n    {\n        SAXASSERT(false, DL_STRINGIZE(DL_ELEMENT) \"::m_ChaSpend had invalid value\");\n    }\n    if (!m_hasUserSelectedSpend)\n    {\n        m_hasUserSelectedSpend = true;\n    }\n}\n\nvoid AbilitySpend::Write(XmlLib::SaxWriter * writer) const\n{\n    writer->StartElement(ElementName());//, VersionAttributes());\n    DL_WRITE(AbilitySpend_PROPERTIES)\n    writer->EndElement();\n}\n\nsize_t AbilitySpend::PointsSpent() const\n{\n    // sum how many build points have been spent on each ability\n    size_t totalSpent = 0;\n    totalSpent += GetAbilitySpendPoints(Ability_Strength);\n    totalSpent += GetAbilitySpendPoints(Ability_Dexterity);\n    totalSpent += GetAbilitySpendPoints(Ability_Constitution);\n    totalSpent += GetAbilitySpendPoints(Ability_Intelligence);\n    totalSpent += GetAbilitySpendPoints(Ability_Wisdom);\n    totalSpent += GetAbilitySpendPoints(Ability_Charisma);\n    return totalSpent;\n}\n\nbool AbilitySpend::CanSpendOnAbility(\n        AbilityType ability) const\n{\n    bool canSpend = false;\n    size_t currentSpend = GetAbilitySpend(ability);\n    if (currentSpend < c_maxSpend)\n    {\n        // its not at max, but are there enough points left to\n        // spend to the next level?\n        int availablePoints = ((int)m_AvailableSpend - (int)PointsSpent());\n        int nextCost = c_statIncreaseCosts[currentSpend];\n        canSpend = (availablePoints >= nextCost); // true if enough points available\n    }\n    return canSpend;\n}\n\nbool AbilitySpend::CanRevokeSpend(\n        AbilityType ability) const\n{\n    bool canRevokeSpend = false;\n    size_t currentSpend = GetAbilitySpend(ability);\n    // can always undo if any points spent\n    canRevokeSpend = (currentSpend > 0);\n    return canRevokeSpend;\n}\n\nsize_t AbilitySpend::NextPointsSpentCost(\n        AbilityType ability) const\n{\n    size_t nextCost = 0;\n    size_t currentSpend = GetAbilitySpend(ability);\n    if (currentSpend < c_maxSpend)\n    {\n        // its not at max, but are there enough points left to\n        // spend to the next level?\n        nextCost = c_statIncreaseCosts[currentSpend];\n    }\n    return nextCost;\n}\n\nvoid AbilitySpend::SpendOnAbility(\n        AbilityType ability)\n{\n    switch (ability)\n    {\n    case Ability_Strength:\n        ++m_StrSpend;\n        break;\n    case Ability_Dexterity:\n        ++m_DexSpend;\n        break;\n    case Ability_Constitution:\n        ++m_ConSpend;\n        break;\n    case Ability_Intelligence:\n        ++m_IntSpend;\n        break;\n    case Ability_Wisdom:\n        ++m_WisSpend;\n        break;\n    case Ability_Charisma:\n        ++m_ChaSpend;\n        break;\n    default:\n        ASSERT(FALSE);\n        break;\n    }\n}\n\nvoid AbilitySpend::RevokeSpendOnAbility(\n        AbilityType ability)\n{\n    switch (ability)\n    {\n    case Ability_Strength:\n        --m_StrSpend;\n        break;\n    case Ability_Dexterity:\n        --m_DexSpend;\n        break;\n    case Ability_Constitution:\n        --m_ConSpend;\n        break;\n    case Ability_Intelligence:\n        --m_IntSpend;\n        break;\n    case Ability_Wisdom:\n        --m_WisSpend;\n        break;\n    case Ability_Charisma:\n        --m_ChaSpend;\n        break;\n    default:\n        ASSERT(FALSE);\n        break;\n    }\n}\n\nsize_t AbilitySpend::GetAbilitySpend(\n        AbilityType ability) const\n{\n    size_t spent = c_maxSpend;  // assume\n    switch (ability)\n    {\n    case Ability_Strength:\n        spent = m_StrSpend;\n        break;\n    case Ability_Dexterity:\n        spent = m_DexSpend;\n        break;\n    case Ability_Constitution:\n        spent = m_ConSpend;\n        break;\n    case Ability_Intelligence:\n        spent = m_IntSpend;\n        break;\n    case Ability_Wisdom:\n        spent = m_WisSpend;\n        break;\n    case Ability_Charisma:\n        spent = m_ChaSpend;\n        break;\n    default:\n        ASSERT(FALSE);\n        break;\n    }\n    return spent;\n}\n\nsize_t AbilitySpend::GetAbilitySpendPoints(\n        AbilityType ability) const\n{\n    size_t spentPoints = 0;\n    size_t abilitySpend = GetAbilitySpend(ability);\n    for (size_t i = 0; i < abilitySpend; ++i)\n    {\n        spentPoints += c_statIncreaseCosts[i];\n    }\n    return spentPoints;\n}\n", "meta": {"hexsha": "d32d542d828710b978aad3b0a28b88d1bb686983", "size": 5985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DDOCP/AbilitySpend.cpp", "max_stars_repo_name": "shortydude/DDOBuilder-learning", "max_stars_repo_head_hexsha": "e71162c10b81bb4afd0365e61088437353cc4607", "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": "DDOCP/AbilitySpend.cpp", "max_issues_repo_name": "shortydude/DDOBuilder-learning", "max_issues_repo_head_hexsha": "e71162c10b81bb4afd0365e61088437353cc4607", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DDOCP/AbilitySpend.cpp", "max_forks_repo_name": "shortydude/DDOBuilder-learning", "max_forks_repo_head_hexsha": "e71162c10b81bb4afd0365e61088437353cc4607", "max_forks_repo_licenses": ["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.253164557, "max_line_length": 90, "alphanum_fraction": 0.6581453634, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "/*\n * \trobot_server_dvrk.hpp\n *\n *\tAuthor(s): Tamas D. Nagy\n *\tCreated on: 2016-11-07\n *\n *  Base class for dVRK robot arms, itself usable for\n *  MTMs and ECM.\n *\n */\n\n#ifndef ROBOT_SERVER_DVRK_HPP_\n#define ROBOT_SERVER_DVRK_HPP_\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <std_msgs/String.h>\n#include <sensor_msgs/JointState.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <std_msgs/Float32.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry> \n#include <cmath>\n#include <irob_dvrk/arm_types.hpp>\n#include <irob_general_robot/robot_server.hpp>\n\nnamespace saf {\n\nclass RobotServerDVRK: public RobotServer {\n\npublic:\n\n  // Constants\n  static const std::string READY;\n\n\nprotected:\n  const ArmTypes arm_typ;\n\n\n  // States\n  std_msgs::String status;\n  sensor_msgs::JointState measured_js;\n  geometry_msgs::TransformStamped measured_cp;\n  std_msgs::String error;\n  std_msgs::String warning;\n\n  // Subscribers\n  ros::Subscriber status_sub;\n  ros::Subscriber smeasured_js_sub;\n  ros::Subscriber measured_cp_sub;\n  ros::Subscriber error_sub;\n  ros::Subscriber warning_sub;\n\n\n  // Publishers\n  ros::Publisher position_joint_pub;\n  ros::Publisher position_cartesian_pub;\n\n  void subscribeLowLevelTopics();\n  void advertiseLowLevelTopics();\n\npublic:\n  RobotServerDVRK(ros::NodeHandle, ros::NodeHandle, ArmTypes, std::string, bool);\n  ~RobotServerDVRK();\n\n  // Callbacks\n  void resetPose(bool);\n  void stop();\n  void followTrajectory(Trajectory<ToolPose>);\n  void moveJointAbsolute(sensor_msgs::JointState , double );\n\n  void status_cb(const std_msgs::String);\n  void error_cb(const std_msgs::String);\n  void warning_cb(const std_msgs::String);\n  void measured_js_cb(const sensor_msgs::JointStateConstPtr&);\n  virtual void measured_cp_cb(\n      const geometry_msgs::TransformStampedConstPtr&);\n\n\n  void loadRegistration(std::string);\n\n  double getJointStateCurrent(int);\n  std::vector<double> getJointStateCurrent();\n  Eigen::Vector3d getPositionCartesianCurrent();\n  Eigen::Quaternion<double> getOrientationCartesianCurrent();\n  ToolPose getPoseCurrent();\n\n  //DVRK actions\n  std::string getCurrentState();\n  void moveCartesianRelative(Eigen::Translation3d, double = 0.01);\n  virtual void moveCartesianAbsolute(ToolPose, double = 0.01);\n\n\n  void recordTrajectory(Trajectory<Eigen::Vector3d>&);\n  void recordTrajectory(Trajectory<ToolPose>&);\n  void saveTrajectory(std::string);\n\n\n  void checkErrors();\n  void checkVelCartesian(const ToolPose&, const ToolPose&, double);\n  void checkNaNCartesian(const ToolPose&);\n  void checkVelJoint(const sensor_msgs::JointState&,\n                     const std::vector<double>&, double);\n  sensor_msgs::JointState maximizeVelJoint(const sensor_msgs::JointState&,\n                     const std::vector<double>&, double);\n  void checkNaNJoint(const sensor_msgs::JointState&);\n\n};\n\n}\n#endif /* ROBOT_SERVER_DVRK_HPP_ */\n", "meta": {"hexsha": "2458a46331ce78c15a251dec8b8c606cf6cfcac9", "size": 2957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "irob_robot/include/irob_dvrk/robot_server_dvrk.hpp", "max_stars_repo_name": "ABC-iRobotics/irob-saf", "max_stars_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-06-07T22:56:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:56:36.000Z", "max_issues_repo_path": "irob_robot/include/irob_dvrk/robot_server_dvrk.hpp", "max_issues_repo_name": "ABC-iRobotics/irob-saf", "max_issues_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T10:04:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T13:45:25.000Z", "max_forks_repo_path": "irob_robot/include/irob_dvrk/robot_server_dvrk.hpp", "max_forks_repo_name": "ABC-iRobotics/irob-saf", "max_forks_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T23:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T23:33:43.000Z", "avg_line_length": 25.0593220339, "max_line_length": 81, "alphanum_fraction": 0.7463645587, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "//\n// Copyright (c) 2019-2020 Kris Jusiak (kris at jusiak dot 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#include <algorithm>\n#include <boost/ut.hpp>\n#include <string_view>\n#include <tuple>\n#include <type_traits>\n\nclass matcher : boost::ut::detail::op {\n public:\n  matcher(bool result, const std::string& str) : result_{result}, str_{str} {}\n  constexpr explicit operator bool() const { return result_; }\n  friend auto operator<<(std::ostream& os, const matcher& self)\n      -> std::ostream& {\n    return (os << self.str_);\n  }\n\n private:\n  const bool result_{};\n  const std::string str_{};\n};\n\ntemplate <class... Ts>\nclass any_of {\n public:\n  constexpr explicit any_of(Ts... ts) : ts_{ts...} {}\n\n  constexpr auto operator==(std::common_type_t<Ts...> t) const {\n    return std::apply([t](auto... args) { return eq(t, args...); }, ts_);\n  }\n\n private:\n  template <class T, class U, class... TArgs>\n  static constexpr auto eq(const T& t, const U& u, const TArgs&... args) {\n    using namespace boost::ut;\n    if constexpr (sizeof...(args) > 0) {\n      return (that % detail::value{u} == t) or eq(t, args...);\n    } else {\n      return (that % detail::value{u} == t);\n    }\n  }\n\n  std::tuple<Ts...> ts_;\n};\n\nint main() {\n  using namespace boost::ut;\n  using namespace std::literals::string_view_literals;\n\n  \"matcher\"_test = [] {\n    constexpr auto is_between = [](auto lhs, auto rhs) {\n      return [=](auto value) {\n        return that % value >= lhs and that % value <= rhs;\n      };\n    };\n\n    constexpr auto ends_with = [](const auto& arg, const auto& ext) {\n      std::stringstream str{};\n      str << '(' << arg << \" ends with \" << ext << ')';\n      if (ext.size() > arg.size()) {\n        return matcher{{}, str.str()};\n      }\n      return matcher{std::equal(ext.rbegin(), ext.rend(), arg.rbegin()),\n                     str.str()};\n    };\n\n    auto value = 42;\n    auto str = \"example.test\"sv;\n\n    expect(is_between(1, 100)(value) and not is_between(1, 100)(0));\n    expect(ends_with(str, \".test\"sv));\n    expect(any_of{1, 2, 3} == 2 or any_of{42, 43} == 44);\n  };\n}\n", "meta": {"hexsha": "1bf06043659114bd7a2b0d6444ab866ef220f91b", "size": 2199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/matcher.cpp", "max_stars_repo_name": "ambushed/ut", "max_stars_repo_head_hexsha": "248df4dd091781b45b2cde7332774226d6a459b3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 567.0, "max_stars_repo_stars_event_min_datetime": "2020-06-30T20:16:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:22:41.000Z", "max_issues_repo_path": "example/matcher.cpp", "max_issues_repo_name": "ambushed/ut", "max_issues_repo_head_hexsha": "248df4dd091781b45b2cde7332774226d6a459b3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 85.0, "max_issues_repo_issues_event_min_datetime": "2020-07-01T02:21:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T22:12:35.000Z", "max_forks_repo_path": "example/matcher.cpp", "max_forks_repo_name": "ambushed/ut", "max_forks_repo_head_hexsha": "248df4dd091781b45b2cde7332774226d6a459b3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-07-08T06:47:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T15:08:34.000Z", "avg_line_length": 27.4875, "max_line_length": 78, "alphanum_fraction": 0.5957253297, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"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_CONSTANT_CONSTANT_VALUE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_CONSTANT_CONSTANT_VALUE_HPP_INCLUDED\n\n#if defined(BOOST_SIMD_DETECTED)\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/detail/constant_traits.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/as.hpp>\n#include <boost/config.hpp>\n#include <boost/simd/detail/nsm.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD_FALLBACK( (typename Constant, typename T, typename X)\n                                  , boost::dispatch::constant_value_<Constant>\n                                  , bs::simd_\n                                  , bd::target_< bs::pack_<bd::unspecified_<T>,X> >\n                                  )\n  {\n    using value_t   = typename T::type::value_type;\n    using scalar_t  = decltype(bd::functor<Constant>{}(bd::as_<value_t>()));\n    using result_t  = typename T::type::template rebind<scalar_t>;\n\n    BOOST_FORCEINLINE result_t operator()(T const&) const\n    {\n      return result_t{ bd::functor<Constant>{}(bd::as_<value_t>()) };\n    }\n  };\n} } }\n\n#endif\n\n#endif\n", "meta": {"hexsha": "6da7e50d3c3f1f726823feba218873b1b4d968f7", "size": 1647, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/constant/constant_value.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/simd/constant/constant_value.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/simd/constant/constant_value.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": 35.0425531915, "max_line_length": 100, "alphanum_fraction": 0.5883424408, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19696593568471757}}
{"text": "/*\n * OpusHandler.cpp\n *\n *  Created on: 5 oct. 2018\n *      Author: max\n */\n\n#include <boost/asio.hpp>\n#include <opus/opus_defines.h>\n#include <OpusHandler.hpp>\n#include <StreamHandler.hpp>\n#include <cstdio>\n\nnamespace Babel {\n\n\tOpusHandler::OpusHandler() :\n\t\t\t_decodeSize(0), _encodeSize(0) {\n\t\t_encoder = opus_encoder_create(SoundDevice::sampleRate, SoundDevice::channelCount, OPUS_APPLICATION_VOIP, NULL);\n\t\t_decoder = opus_decoder_create(SoundDevice::sampleRate, SoundDevice::channelCount, NULL);\n\n\t\tthis->_decodedData = new std::vector<float>(SoundDevice::channelCount * SoundDevice::sampleRate * SoundDevice::secTimeOfEachPacket);\n\t\tthis->_encodedData = new std::vector<unsigned char>(SoundDevice::channelCount * SoundDevice::sampleRate * SoundDevice::secTimeOfEachPacket);\n\t}\n\n\tOpusHandler::~OpusHandler() {\n\t        opus_encoder_destroy(_encoder);\n\t        opus_decoder_destroy(_decoder);\n\t}\n\n\tstd::vector<float> *OpusHandler::decode(std::vector<unsigned char> sound) {\n\t\t/*\n\t\tfor (int i = 0; i < sound.size(); i++) {\n\t\t\tif (sound.at(i) != 0) {\n\t\t\t\tprintf(\"BBBAAA%d\\n\", sound.at(i));\n\t\t\t}\n\t\t}*/\n\n\t\t//_decodedData->resize(sound.size());\n\t\t_decodeSize = opus_decode_float(_decoder, sound.data(), _encodeSize, _decodedData->data(), 480, 0); //* SoundDevice::channelCount;\n\t\tif (_decodeSize < 0) {\n\t\t\tthrow(\"opus_decode_float : Couldn''t decode data.\");\n\t\t}\n\t\t//printf(\"RET = %d\\nSIZE = %lu\\n\", _decodeSize, _decodedData->size() );\n\n\t\t/*\n\t\tfor (int i = 0; i < _decodedData->size(); i++) {\n\t\t\tif (_decodedData->at(i) != 0) {\n\t\t\t\tprintf(\"DECODED = %f.\\n\", _decodedData->at(i));\n\t\t\t}\n\t\t}*/\n\n\n\t\treturn _decodedData;\n\t}\n\n\tstd::vector<unsigned char> *OpusHandler::encode(std::vector<float> sound) {\n\n\t\tprintf(\"SIZE = %lu\\n\", sound.size());\n\n\t\t/*\n\t\tfor (int i = 0; i < sound.size(); i++) {\n\t\t\tif (sound.at(i)) {\n\t\t\t\tprintf(\"%f\\n\", sound.at(i));\n\t\t\t}\n\t\t}*/\n\n\t\t//_encodedData->resize(sound.size());\n\t\t_encodeSize = opus_encode_float(_encoder, sound.data(), 480, _encodedData->data(), sound.size());\n\t\tif (_encodeSize < 0) {\n\t\t\tthrow(\"opus_encode_float : Couldn''t encode data.\");\n\t\t}\n\t\t//printf(\"ret = %d\\n\", _encodeSize);\n\t\t/*\n\n\t\tfor (int i = 0; i < _encodedData->size(); i++) {\n\t\t\tif (_encodedData->at(i) != 0) {\n\t\t\t\tprintf(\"AAABBB = %d.\\n\", _encodedData->at(i));\n\t\t\t}\n\t\t}*/\n\n\t\treturn _encodedData;\n\t}\n\n} /* namespace Babel */\n\n\n\n\n\n\n\n", "meta": {"hexsha": "310bf2d28fc87cc772fdb125f99a05626dbd8ff8", "size": 2332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tek3/CPP/Babel/Client/OpusHandler.cpp", "max_stars_repo_name": "PhilippeDeSousa/EpitechBundle", "max_stars_repo_head_hexsha": "5981d424c7dd25a5fbae79172e6a14db27ba985d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T19:05:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-14T19:05:58.000Z", "max_issues_repo_path": "Tek3/CPP/Babel/Client/OpusHandler.cpp", "max_issues_repo_name": "PhilippeDeSousa/EpitechBundle", "max_issues_repo_head_hexsha": "5981d424c7dd25a5fbae79172e6a14db27ba985d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tek3/CPP/Babel/Client/OpusHandler.cpp", "max_forks_repo_name": "PhilippeDeSousa/EpitechBundle", "max_forks_repo_head_hexsha": "5981d424c7dd25a5fbae79172e6a14db27ba985d", "max_forks_repo_licenses": ["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.347826087, "max_line_length": 142, "alphanum_fraction": 0.6427958834, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19696593568471757}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and\n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 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_UNITS_CODATA_ELECTROMAGNETIC_CONSTANTS_HPP\n#define BOOST_UNITS_CODATA_ELECTROMAGNETIC_CONSTANTS_HPP\n\n///\n/// \\file\n/// \\brief CODATA recommended values of fundamental electromagnetic constants.\n/// \\details CODATA recommended values of the fundamental physical constants: NIST SP 961\n///   CODATA 2006 values as of 2007/03/30\n///\n\n#include <boost/units/quantity.hpp>\n#include <boost/units/static_constant.hpp>\n\n#include <boost/units/systems/detail/constants.hpp>\n#include <boost/units/systems/si/conductance.hpp>\n#include <boost/units/systems/si/current.hpp>\n#include <boost/units/systems/si/electric_charge.hpp>\n#include <boost/units/systems/si/electric_potential.hpp>\n#include <boost/units/systems/si/energy.hpp>\n#include <boost/units/systems/si/frequency.hpp>\n#include <boost/units/systems/si/magnetic_flux.hpp>\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\n#include <boost/units/systems/si/resistance.hpp>\n\n#include <boost/units/systems/si/codata/typedefs.hpp>\n\nnamespace boost {\n\nnamespace units {\n\nnamespace si {\n\nnamespace constants {\n\nnamespace codata {\n\n// ELECTROMAGNETIC\n/// elementary charge\nBOOST_UNITS_PHYSICAL_CONSTANT(e,quantity<electric_charge>,1.602176487e-19*coulombs,4.0e-27*coulombs);\n/// elementary charge to Planck constant ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(e_over_h,quantity<current_over_energy>,2.417989454e14*amperes/joule,6.0e6*amperes/joule);\n/// magnetic flux quantum\nBOOST_UNITS_PHYSICAL_CONSTANT(Phi_0,quantity<magnetic_flux>,2.067833667e-15*webers,5.2e-23*webers);\n/// conductance quantum\nBOOST_UNITS_PHYSICAL_CONSTANT(G_0,quantity<conductance>,7.7480917004e-5*siemens,5.3e-14*siemens);\n/// Josephson constant\nBOOST_UNITS_PHYSICAL_CONSTANT(K_J,quantity<frequency_over_electric_potential>,483597.891e9*hertz/volt,1.2e7*hertz/volt);\n/// von Klitzing constant\nBOOST_UNITS_PHYSICAL_CONSTANT(R_K,quantity<resistance>,25812.807557*ohms,1.77e-5*ohms);\n/// Bohr magneton\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_B,quantity<energy_over_magnetic_flux_density>,927.400915e-26*joules/tesla,2.3e-31*joules/tesla);\n/// nuclear magneton\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_N,quantity<energy_over_magnetic_flux_density>,5.05078324e-27*joules/tesla,1.3e-34*joules/tesla);\n\n} // namespace codata\n\n} // namespace constants\n\n} // namespace si\n\n} // namespace units\n\n} // namespace boost\n\n#endif // BOOST_UNITS_CODATA_ELECTROMAGNETIC_CONSTANTS_HPP\n", "meta": {"hexsha": "d53870173a83b9a9a42d09dd5eab78b9e28e0e2c", "size": 2752, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/units/systems/si/codata/electromagnetic_constants.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/units/systems/si/codata/electromagnetic_constants.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/units/systems/si/codata/electromagnetic_constants.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.2105263158, "max_line_length": 129, "alphanum_fraction": 0.8023255814, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19696593568471757}}
{"text": "// CZI.\n#include \"CellGraph.hpp\"\n#include \"color.hpp\"\n#include \"CZI_ASSERT.hpp\"\n#include \"deduplicate.hpp\"\n#include \"iostream.hpp\"\n#include \"iterator.hpp\"\n#include \"SimilarPairs.hpp\"\n#include \"timestamp.hpp\"\nusing namespace ChanZuckerberg::ExpressionMatrix2;\n\n// Boost libraries.\n#include \"boost_lexical_cast.hpp\"\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/algorithm/string.hpp>\nusing boost::algorithm::split;\nusing boost::algorithm::is_any_of;\n\n// Standard libraries.\n#include \"algorithm.hpp\"\n#include <chrono>\n#include \"fstream.hpp\"\n#include \"set.hpp\"\n#include \"stdexcept.hpp\"\n#include \"utility.hpp\"\n#include \"vector.hpp\"\n#include <limits>\n#include <random>\n\n\n\nCellGraph::CellGraph(\n    const MemoryMapped::Vector<CellId>& cellSet, // The cell set to be used.\n    const string& similarPairsName,              // The name of the SimilarPairs object to be used to create the graph.\n    double similarityThreshold,                  // The minimum similarity to create an edge.\n    size_t maxConnectivity                      // The maximum number of neighbors (k of the k-NN graph).\n )\n{\n    typedef SimilarPairs::Pair Pair;\n\n    // Create the SimilarPairs object.\n    const SimilarPairs similarPairs(similarPairsName, true);\n\n    // Create a vertex for each cell in the cell set.\n    for(const CellId cellId: cellSet) {\n        const vertex_descriptor v = boost::add_vertex(CellGraphVertex(cellId), graph());\n        vertexTable.insert(make_pair(cellId, v));\n    }\n\n\n\n    // Create the edges.\n    // The similar pairs are sorted by decreasing similarity.\n    vector< pair<vertex_descriptor, float > > pairs;\n    for(const CellId cellId0: cellSet) {\n\n        // Find the local cell id (in the cell set of the SimilarPairs object)\n        // corresponding to this global cell id.\n        // If the cell set of the SimilarPairs object does not contain this cell,\n        // this is an invalid cell id and in that case we skip this cell.\n        const CellId localCellId0 = similarPairs.getLocalCellId(cellId0);\n        if(localCellId0 == invalidCellId) {\n            continue;\n        }\n\n        // Locate the corresponding vertex.\n        const vertex_descriptor v0 = vertexTable[cellId0];\n\n        // Find the best up to k pairs such that the other vertex\n        // is also in the cell set.\n        pairs.clear();\n        const Pair* begin = similarPairs.begin(localCellId0);\n        const Pair* end = similarPairs.end(localCellId0);\n        for(const Pair* p=begin; p!=end; ++p) {\n            const float similarity = p->second;\n            if(similarity < similarityThreshold) {\n                break;\n            }\n            const CellId cellId1 = similarPairs.getGlobalCellId(p->first);\n            const auto it1 = vertexTable.find(cellId1);\n            if(it1 == vertexTable.end()) {\n                continue;\n            }\n            pairs.push_back(make_pair(it1->second, similarity));\n            if(pairs.size() == maxConnectivity) {\n                break;\n            }\n        }\n\n        // Add an edge for each pair we found.\n        // Some of the edges may already exist (we added them when\n        // processing cellId1).\n        for(const pair<vertex_descriptor, float >& p: pairs) {\n            const vertex_descriptor v1 = p.first;\n            edge_descriptor e;\n            bool edgeExists = false;\n            tie(e, edgeExists) = boost::edge(v0, v1, graph());\n            if(edgeExists) {\n                continue;\n            }\n            boost::add_edge(v0, v1, CellGraphEdge(p.second), graph());\n        }\n    }\n\n    // cout << \"The cell similarity graph has \" << boost::num_vertices(graph());\n    // cout << \" vertices and \" << num_edges(graph()) << \" edges.\" << endl;\n\n}\n\n\n\n// Write the graph in Graphviz format.\nvoid CellGraph::write(const string& fileName) const\n    {\n    ofstream outputFileStream(fileName);\n    if(!outputFileStream) {\n        throw runtime_error(\"Error opening \" + fileName);\n    }\n    write(outputFileStream);\n}\nvoid CellGraph::write(ostream& s) const\n    {\n    Writer writer(*this);\n    boost::write_graphviz(s, graph(), writer, writer, writer,\n        boost::get(&CellGraphVertex::cellId, graph()));\n}\n\nCellGraph::Writer::Writer(const Graph& graph) :\n    graph(graph)\n{\n}\n\n\n\nvoid CellGraph::Writer::operator()(std::ostream& s) const\n{\n    s << \"tooltip=\\\"\\\";\";\n    s << \"node [shape=point];\";\n}\n\n\n// Write out a vertex of the cell graph.\nvoid CellGraph::Writer::operator()(std::ostream& s, vertex_descriptor v) const\n{\n    // Get the vertex.\n    const CellGraphVertex& vertex = graph[v];\n\n    // Begin vertex attributes.\n    s << \"[\";\n\n    // Add a tooltip that shows the cell id.\n    s << \"tooltip=\" << vertex.cellId;\n\n    // End vertex attributes.\n    s << \"]\";\n}\n\n\n\nvoid CellGraph::Writer::operator()(std::ostream& s, edge_descriptor e) const\n{\n    // Get the edge.\n    const CellGraphEdge& edge = graph[e];\n\n    // Begin edge attributes.\n    s << \"[\";\n\n    // Add a tooltip that shows the similarity.\n    s.precision(2);\n    s.setf(std::ios::fixed);\n    s << \"tooltip=\\\"\" << edge.similarity << \"\\\"\";\n\n    // End edge attributes.\n    s << \"]\";\n}\n\n\n\n// Remove isolated vertices and returns\\ the number of vertices that were removed\nsize_t CellGraph::removeIsolatedVertices()\n{\n    vector<vertex_descriptor> verticesToBeRemoved;\n    BGL_FORALL_VERTICES(v, graph(), Graph) {\n        if(out_degree(v, graph()) == 0) {\n            verticesToBeRemoved.push_back(v);\n        }\n    }\n\n    for(const vertex_descriptor v: verticesToBeRemoved) {\n        const CellGraphVertex& vertex = graph()[v];\n        vertexTable[vertex.cellId] = null_vertex();\n        boost::remove_vertex(v, graph());\n    }\n\n    return verticesToBeRemoved.size();\n}\n\n\n\n// Use Graphviz to compute the graph layout and store it in the vertex positions.\nvoid CellGraph::computeLayout()\n{\n    // Write the graph in Graphviz format.\n    write(\"Graph.dot\");\n\n    // Run sfdp with output in Graphviz plain format.\n    // See https://www.graphviz.org/doc/info/output.html#d:plain\n    const int systemReturnCode = ::system(\"sfdp -O -Tplain -Goverlap=true -Gsmoothing=triangle Graph.dot\");\n    const int sfdpReturnCode = WEXITSTATUS(systemReturnCode);   // Man page for system is not super clear on this.\n    if(sfdpReturnCode!=0 && sfdpReturnCode!=1) {    // Sfdp returns 1 if build without triangulation library.\n        throw runtime_error(\"Error \" +\n            lexical_cast<string>(systemReturnCode) + \" \" +\n            lexical_cast<string>(sfdpReturnCode) +\n            \" running sfdp.\");\n    }\n\n\n\n    // Extract vertex positions from the output.\n    ifstream file(\"Graph.dot.plain\");\n    string line;\n    vector<string> tokens;\n    while(true) {\n\n        // Get a line.\n        getline(file, line);\n        if(!file) {\n            break;\n        }\n\n        // Parse it.\n        split(tokens, line, is_any_of(\" \"));\n\n        // Only parse lines that describe vertices.\n        CZI_ASSERT(tokens.size() >= 1);\n        if(tokens[0] != \"node\") {\n            continue;\n        }\n        CZI_ASSERT(tokens.size() >= 4);\n\n        // Extract the positions for this vertex.\n        try {\n            const CellId cellId = lexical_cast<CellId>(tokens[1]);\n            const vertex_descriptor v = vertexTable[cellId];\n            CZI_ASSERT(v != null_vertex());\n            CellGraphVertex& vertex = graph()[v];\n            vertex.position[0] = lexical_cast<double>(tokens[2]);\n            vertex.position[1] = lexical_cast<double>(tokens[3]);\n        } catch(std::exception& e) {\n            cout << \"Error processing the following line of Graph.dot.plain:\" << endl;\n            cout << line << endl;\n            throw;\n        }\n    }\n}\n\n\n\n\n// Compute minimum and maximum coordinates of all the vertices.\nvoid CellGraph::computeCoordinateRange(\n    double& xMin,\n    double& xMax,\n    double& yMin,\n    double& yMax) const\n{\n    xMin = std::numeric_limits<double>::max();\n    xMax = std::numeric_limits<double>::min();\n    yMin = std::numeric_limits<double>::max();\n    yMax = std::numeric_limits<double>::min();\n    BGL_FORALL_VERTICES(v, graph(), Graph) {\n        const CellGraphVertex& vertex = graph()[v];\n        const double x = vertex.position[0];\n        const double y = vertex.position[1];\n        xMin = min(xMin, x);\n        xMax = max(xMax, x);\n        yMin = min(yMin, y);\n        yMax = max(yMax, y);\n    }\n\n}\n\n\n\n// Write the graph in svg format.\n// This does not use Graphviz. It uses the graph layout stored in the vertices,\n// and previously computed using Graphviz.\n// The vertex coordinates are used without any transformation.\n// The last argument specifies the color assigned to each vertex group.\n// If empty, vertex groups are not used, and each vertex is drawn\n// with its own color.\nvoid CellGraph::writeSvg(\n    ostream& s,\n    bool hideEdges,\n    double svgSizePixels,\n    double xViewBoxCenter,\n    double yViewBoxCenter,\n    double viewBoxHalfSize,\n    double vertexRadius,\n    double edgeThickness,\n    const map<int, string>& groupColors,\n    const string& geneSetName   // Used for the cell URL\n    ) const\n{\n\n\n\n\n    // Start the svg object.\n    s <<\n        \"<p><svg id=graphSvg width='\" << svgSizePixels << \"' height='\" << svgSizePixels <<\n        \"' viewBox='\" <<\n        xViewBoxCenter-viewBoxHalfSize << \" \" << yViewBoxCenter-viewBoxHalfSize << \" \" <<\n        2.*viewBoxHalfSize << \" \" << 2.*viewBoxHalfSize <<\n        \"'>\";\n\n\n\n    // Draw the edges first.\n    // This makes it easier to see the vertices and their tooltips.\n    if(!hideEdges) {\n        s << \"<g id=edges>\";\n        BGL_FORALL_EDGES(e, graph(), Graph){\n            const vertex_descriptor v1 = source(e, graph());\n            const vertex_descriptor v2 = target(e, graph());\n\n            const CellGraphVertex& vertex1 = graph()[v1];\n            const CellGraphVertex& vertex2 = graph()[v2];\n\n            const double x1 = vertex1.position[0];\n            const double y1 = vertex1.position[1];\n            const double x2 = vertex2.position[0];\n            const double y2 = vertex2.position[1];\n\n            s << \"<line x1='\" << x1 << \"' y1='\" << y1 << \"'\";\n            s << \" x2='\" << x2 << \"' y2='\" << y2 << \"'\";\n\n            s << \" style='stroke:\";\n            const string& color = graph()[e].color;\n            if(color.empty()) {\n                s << \"black\";\n            } else {\n                s << color;\n            }\n            s << \";stroke-width:\" << edgeThickness << \"' />\";\n        }\n        s << \"</g>\";\n    }\n\n\n\n    // If the groupColors map is empty, vertex groups are not used,\n    // and each vertex is drawn in its own color.\n    // We still write two levels of groups, because the javascript code\n    // to change vertex size expects that structure.\n    if(groupColors.empty()) {\n        s << \"<g id=vertices><g>\";\n        BGL_FORALL_VERTICES(v, graph(), Graph) {\n            const CellGraphVertex& vertex = graph()[v];\n            const double x = vertex.position[0];\n            const double y = vertex.position[1];\n            s <<\n                \"<a xlink:href='cell?cellId=\" << vertex.cellId << \"&geneSetName=\" << geneSetName << \"'>\"\n                \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << vertexRadius << \"' stroke=none\";\n            if(!vertex.color.empty()) {\n                s << \" fill='\" << vertex.color << \"'\";\n            }\n            s <<\n                \">\"\n                \"<title>Cell \" << vertex.cellId << \"</title></circle>\"\n                \"</a>\"\n                ;\n        }\n        s << \"</g></g>\";\n    }\n\n\n\n    // Otherwise, colors are specified for each group, not for each vertex.\n    else {\n\n\n        // Find the vertices in each group.\n        vector< vector<vertex_descriptor> > groups;\n        BGL_FORALL_VERTICES(v, graph(), Graph) {\n            const CellGraphVertex& vertex = graph()[v];\n            const size_t group = vertex.group;\n            if(groups.size() <= group) {\n                groups.resize(group+1);\n            }\n            groups[group].push_back(v);\n        }\n\n        // A circle at the center.\n        // s << \"<circle cx='\" << svgSizePixels/2 << \"' cy='\" << svgSizePixels/2 << \"' r='\" << 10 << \"' stroke='black' stroke-width='3' fill='red' />\";\n\n        // Draw the vertices, one group at a time.\n        s << \"<g id=vertices>\";\n\n        // Loop over all groups.\n        for(int iGroup=0; iGroup<int(groups.size()); iGroup++) {\n            string groupColor;\n            const auto it = groupColors.find(iGroup);\n            if(it == groupColors.end()) {\n                groupColor = \"black\";\n            } else {\n                groupColor = it->second;\n            }\n            auto& group= groups[iGroup];\n            s << \"<g id=vertexGroup\" << iGroup << \" style='fill:\" << groupColor << \"'>\";\n\n            // Loop over all vertices of this group.\n            for(const vertex_descriptor v: group) {\n                const CellGraphVertex& vertex = graph()[v];\n\n                const double x = vertex.position[0];\n                const double y = vertex.position[1];\n                s <<\n                    \"<a xlink:href='cell?cellId=\" << vertex.cellId << \"&geneSetName=\" << geneSetName << \"'>\"\n                    \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << vertexRadius << \"' stroke=none>\"\n                    \"<title>Cell \" << vertex.cellId << \"</title></circle>\"\n                    \"</a>\"\n                    ;\n            }\n            s << \"</g>\";\n        }\n        s << \"</g>\";\n    }\n\n}\n\n\n#if 1\n// Clustering using the label propagation algorithm.\n// The cluster each vertex is assigned to is stored in the clusterId data member of the vertex.\nvoid CellGraph::labelPropagationClustering(\n    ostream& out,\n    size_t seed,                            // Seed for random number generator.\n    size_t stableIterationCountThreshold,   // Stop after this many iterations without changes.\n    size_t maxIterationCount                // Stop after this many iterations no matter what.\n    )\n{\n    out << timestamp << \"Clustering by label propagation begins.\" << endl;\n    out << \"Seed for random number generator is \" << seed << \".\" << endl;\n    out << \"Will stop after \" << stableIterationCountThreshold << \" iterations without changes.\" << endl;\n    out << \"Maximum number of iterations is \" << maxIterationCount << \".\" << endl;\n    const auto t0 = std::chrono::steady_clock::now();\n\n    // Set the cluster of each vertex equal to its cell id.\n    BGL_FORALL_VERTICES(v, graph(), CellGraph) {\n        CellGraphVertex& vertex = graph()[v];\n        vertex.clusterId = vertex.cellId;\n    }\n\n    // Initialize the ClusterTable of each vertex.\n    BGL_FORALL_VERTICES(v0, graph(), CellGraph) {\n        CellGraphVertex& vertex0 = graph()[v0];\n        ClusterTable& clusterTable0 = vertex0.clusterTable;\n        clusterTable0.clear();\n        BGL_FORALL_OUTEDGES(v0, e, graph(), CellGraph) {\n            const vertex_descriptor v1 = target(e, graph());\n            const CellGraphVertex& vertex1 = graph()[v1];\n            const CellGraphEdge& edge = graph()[e];\n            clusterTable0.addWeightQuick(vertex1.clusterId, edge.similarity);\n        }\n        clusterTable0.findBestCluster();\n    }\n\n\n    // Create the random number generator using the specified seed.\n    std::mt19937 randomGenerator(seed);\n\n    // Vector with all the vertices in the graph, in the same order as in the vertex table.\n    vector<vertex_descriptor> allVertices;\n    for(const auto& p : vertexTable) {\n        const vertex_descriptor v = p.second;\n        if(v != null_vertex()) {\n            allVertices.push_back(p.second);\n        }\n    }\n\n\n    // Vector to contain the vertices in the random order to be used at each iteration.\n    vector<vertex_descriptor> shuffledVertices;\n\n    // Counter of the number of stable iterations\n    // (iterations without changes).\n    size_t stableIterationCount = 0;\n\n\n\n    // Iterate.\n    out << timestamp << \"Label propagation iteration begins.\" << endl;\n    for(size_t iteration=0; iteration<maxIterationCount; iteration++) {\n        // cout << \"Begin iteration \" << iteration << endl;\n        const auto t0 = std::chrono::steady_clock::now();\n        size_t changeCount = 0;\n\n        // Create a random shuffle of the vertices, to be used for this iteration.\n        shuffledVertices = allVertices;\n        std::shuffle(shuffledVertices.begin(), shuffledVertices.end(), randomGenerator);\n\n        // Process the vertices in the order determined by the random shuffle.\n        for(const vertex_descriptor v0: shuffledVertices) {\n            CZI_ASSERT(v0 != CellGraph::null_vertex());\n            CellGraphVertex& vertex0 = graph()[v0];\n            if(vertex0.clusterTable.isEmpty()) {\n                continue;\n            }\n\n            // If the cluster is already consistent with the cluster table,\n            // we don't need to do anything.\n            const uint32_t bestClusterId = vertex0.clusterTable.bestCluster();\n            if(vertex0.clusterId == bestClusterId) {\n                continue;\n            }\n\n\n            // Change the cluster id of vertex0.\n            const uint32_t oldClusterId = vertex0.clusterId;\n            vertex0.clusterId = bestClusterId;\n            ++changeCount;\n\n            // Update the cluster table of its neighbors.\n            BGL_FORALL_OUTEDGES(v0, e, graph(), CellGraph) {\n                const vertex_descriptor v1 = target(e, graph());\n                CellGraphVertex& vertex1 = graph()[v1];\n                ClusterTable& clusterTable1 = vertex1.clusterTable;\n                const CellGraphEdge& edge = graph()[e];\n                clusterTable1.addWeight(bestClusterId, edge.similarity);\n                clusterTable1.addWeight(oldClusterId, -edge.similarity);\n            }\n        }\n        const auto t1 = std::chrono::steady_clock::now();\n        const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count());\n        out << \"Iteration \" << iteration << \" took \" << t01 << \" s, made \" << changeCount << \" changes.\" << endl;\n\n        // Update the number of stable iterations (iterations without changes).\n        if(changeCount) {\n            stableIterationCount = 0;\n        } else {\n            ++stableIterationCount;\n        }\n\n        // If we have done enough stable iterations, stop.\n        if(stableIterationCount == stableIterationCountThreshold) {\n            break;\n        }\n    }\n\n\n    if(stableIterationCount == stableIterationCountThreshold) {\n        out << \"Terminating because the specified number of stable iterations was achieved.\" << endl;\n    } else {\n        out << \"Terminating because the maximum number of iterations was reached.\" << endl;\n    }\n\n\n\n    // Compute the size of each cluster.\n    map<uint32_t, size_t> clusterSize;    // Key=clusterId, Value=cluster size\n    BGL_FORALL_VERTICES(v, graph(), CellGraph) {\n        const uint32_t clusterId = graph()[v].clusterId;\n        const auto it = clusterSize.find(clusterId);\n        if(it == clusterSize.end()) {\n            clusterSize.insert(make_pair(clusterId, 1));\n        } else {\n            ++(it->second);\n        }\n    }\n\n\n\n    // Renumber the clusters beginning at 0 and in order of decreasing cluster size.\n    vector< pair<size_t, uint32_t> > clusterSizeVector;   // first:cluster size, second: clusterId\n    for(const auto& p: clusterSize) {\n        clusterSizeVector.push_back(make_pair(p.second, p.first));\n    }\n    sort(clusterSizeVector.begin(), clusterSizeVector.end(), std::greater< pair<size_t, size_t> >());\n    out << \"Cluster sizes:\";\n    for(size_t newClusterId=0; newClusterId<clusterSizeVector.size(); newClusterId++) {\n        const auto& p = clusterSizeVector[newClusterId];\n        out << \" \" << p.first;\n    }\n    out << endl;\n    map<uint32_t, uint32_t> clusterMap; // Key: old clusterId. Value: new clustyerId.\n    for(uint32_t newClusterId=0; newClusterId<clusterSizeVector.size(); newClusterId++) {\n        const uint32_t oldClusterId = clusterSizeVector[newClusterId].second;\n        clusterMap.insert(make_pair(oldClusterId, newClusterId));\n    }\n\n    // Update the vertices to reflect the new cluster numbering.\n    BGL_FORALL_VERTICES(v, graph(), CellGraph) {\n        CellGraphVertex& vertex = graph()[v];\n        vertex.clusterId = clusterMap[vertex.clusterId];\n    }\n\n\n    const auto t1 = std::chrono::steady_clock::now();\n    const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count());\n    out << timestamp << \"Clustering by label propagation completed in \" << t01 << \" s.\" << endl;\n}\n\n\n\n#else\n// Clustering using the label propagation algorithm.\n// The cluster each vertex is assigned to is stored in the clusterId data member of the vertex.\nvoid CellGraph::labelPropagationClustering(\n    ostream& out,\n    size_t seed,                            // Seed for random number generator.\n    size_t stableIterationCountThreshold,   // Stop after this many iterations without changes.\n    size_t maxIterationCount                // Stop after this many iterations no matter what.\n    )\n{\n    out << timestamp << \"Clustering by label propagation begins.\" << endl;\n    out << \"Seed for random number generator is \" << seed << \".\" << endl;\n    out << \"Will stop after \" << stableIterationCountThreshold << \" iterations without changes.\" << endl;\n    out << \"Maximum number of iterations is \" << maxIterationCount << \".\" << endl;\n\n    // Set the cluster of each vertex equal to its cell id.\n    BGL_FORALL_VERTICES(v, graph(), CellGraph) {\n        CellGraphVertex& vertex = graph()[v];\n        vertex.clusterId = vertex.cellId;\n    }\n\n    // Create the random number generator using the specified seed.\n    std::mt19937 randomGenerator(seed);\n\n    // Vector with all the vertices in the graph, in the same order as in the vertex table.\n    vector<vertex_descriptor> allVertices;\n    for(const auto& p : vertexTable) {\n        const vertex_descriptor v = p.second;\n        if(v != null_vertex()) {\n            allVertices.push_back(p.second);\n        }\n    }\n\n\n    // Vector to contain the vertices in the random order to be used at each iteration.\n    vector<vertex_descriptor> shuffledVertices;\n\n    // Counter of the number of stable iterations\n    // (iterations without changes).\n    size_t stableIterationCount = 0;\n\n\n\n    // Iterate.\n    for(size_t iteration=0; iteration<maxIterationCount; iteration++) {\n        size_t changeCount = 0;\n\n        // Create a random shuffle of the vertices, to be used for this iteration.\n        shuffledVertices = allVertices;\n        std::shuffle(shuffledVertices.begin(), shuffledVertices.end(), randomGenerator);\n\n        // Process the vertices in the order determined by the random shuffle.\n        for(const vertex_descriptor v0: shuffledVertices) {\n            CZI_ASSERT(v0 != CellGraph::null_vertex());\n            CellGraphVertex& vertex0 = graph()[v0];\n            const size_t clusterId0 = vertex0.clusterId;\n\n            // Map to contain the clusters of the neighbors of this vertex, each with its total weight.\n            // This could be written for better performance.\n            map<uint32_t, double> clusterMap;\n\n            // Loop over the edges of this vertex.\n            BGL_FORALL_OUTEDGES(v0, e, graph(), CellGraph) {\n                const vertex_descriptor v1 = target(e, graph());\n                const double weight = graph()[e].similarity;\n                const uint32_t clusterId1 = graph()[v1].clusterId;\n\n                const auto it = clusterMap.find(clusterId1);\n                if(it == clusterMap.end()) {\n                    clusterMap.insert(make_pair(clusterId1, weight));\n                } else {\n                    it->second += weight;\n                }\n            }\n            if(clusterMap.empty()) {\n                continue;   // There were no neighbors. Nothing to do.\n            }\n\n            // Find the cluster with the most weight.\n            // Note that we don't bother to deal with ties explicitly.\n            uint32_t bestClusterId = std::numeric_limits<uint32_t>::max();\n            double bestWeight = -1;\n            for(const auto& p: clusterMap) {\n                const uint32_t clusterId = p.first;\n                const double weight = p.second;\n                if(weight > bestWeight) {\n                    bestClusterId = clusterId;\n                    bestWeight = weight;\n                }\n            }\n            CZI_ASSERT(bestClusterId != std::numeric_limits<uint32_t>::max());\n\n            // The best cluster id becomes the cluster id of vertex v0.\n            if(bestClusterId != clusterId0) {\n                vertex0.clusterId = bestClusterId;\n                ++changeCount;\n            }\n\n        }\n        out << \"Iteration \" << iteration << \": \" << changeCount << \" changes.\" << endl;\n\n        // Scroll to the bottom of the page to show the line we just wrote.\n        // But for some reason it does not work.\n        // out << \"<script>window.scrollTo(0, document.body.scrollHeight);</scr\u200c\u200bipt>\" << endl;\n\n        // Update the number of stable iterations (iterations without changes).\n        if(changeCount) {\n            stableIterationCount = 0;\n        } else {\n            ++stableIterationCount;\n        }\n\n        // If we have done enough stable iterations, stop.\n        if(stableIterationCount == stableIterationCountThreshold) {\n            break;\n        }\n    }\n\n\n    if(stableIterationCount == stableIterationCountThreshold) {\n        out << \"Terminating because the specified number of stable iterations was achieved.\" << endl;\n    } else {\n        out << \"Terminating because the maximum number of iterations was reached.\" << endl;\n    }\n\n\n\n    // Compute the size of each cluster.\n    map<uint32_t, size_t> clusterSize;    // Key=clusterId, Value=cluster size\n    BGL_FORALL_VERTICES(v, graph(), CellGraph) {\n        const uint32_t clusterId = graph()[v].clusterId;\n        const auto it = clusterSize.find(clusterId);\n        if(it == clusterSize.end()) {\n            clusterSize.insert(make_pair(clusterId, 1));\n        } else {\n            ++(it->second);\n        }\n    }\n\n\n\n    // Renumber the clusters beginning at 0 and in order of decreasing cluster size.\n    vector< pair<size_t, uint32_t> > clusterSizeVector;   // first:cluster size, second: clusterId\n    for(const auto& p: clusterSize) {\n        clusterSizeVector.push_back(make_pair(p.second, p.first));\n    }\n    sort(clusterSizeVector.begin(), clusterSizeVector.end(), std::greater< pair<size_t, size_t> >());\n    out << \"Cluster sizes:\";\n    for(size_t newClusterId=0; newClusterId<clusterSizeVector.size(); newClusterId++) {\n        const auto& p = clusterSizeVector[newClusterId];\n        out << \" \" << p.first;\n    }\n    out << endl;\n    map<uint32_t, uint32_t> clusterMap; // Key: old clusterId. Value: new clustyerId.\n    for(uint32_t newClusterId=0; newClusterId<clusterSizeVector.size(); newClusterId++) {\n        const uint32_t oldClusterId = clusterSizeVector[newClusterId].second;\n        clusterMap.insert(make_pair(oldClusterId, newClusterId));\n    }\n\n    // Update the vertices to reflect the new cluster numbering.\n    BGL_FORALL_VERTICES(v, graph(), CellGraph) {\n        CellGraphVertex& vertex = graph()[v];\n        vertex.clusterId = clusterMap[vertex.clusterId];\n    }\n\n\n\n    out << timestamp << \"Clustering by label propagation ends.\" << endl;\n}\n#endif\n\n\n// Assign integer colors to groups.\n// The same color can be used for multiple groups, but if two\n// groups are joined by one or more edges they must have distinct colors.\n// On return, colorTable[group] contains the integer color assigned to each group.\n// This processes the groups in increasing order beginning at group 0,\n// so it is best if the group numbers are all contiguous, starting at zero,\n// and in decreasing size of group.\nvoid CellGraph::assignColorsToGroups(vector<uint32_t>& colorTable)\n{\n    // Start with no colors assigned.\n    colorTable.clear();\n\n    // Find the vertices of each group.\n    vector< vector<vertex_descriptor> > groupVertices;\n    BGL_FORALL_VERTICES(v, graph(), CellGraph) {\n        const uint32_t groupId = graph()[v].group;\n        if(groupVertices.size() <= groupId) {\n            groupVertices.resize(groupId + 1);\n        }\n        groupVertices[groupId].push_back(v);\n    }\n    const size_t groupCount = groupVertices.size();\n\n\n    // Create the group graph.\n    // Each vertex corresponds ot a group.\n    typedef boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS> GroupGraph;\n    GroupGraph groupGraph(groupCount);\n    BGL_FORALL_EDGES(e, graph(), CellGraph) {\n        const vertex_descriptor v0 = source(e, graph());\n        const vertex_descriptor v1 = target(e, graph());\n        const CellGraphVertex& vertex0 = graph()[v0];\n        const CellGraphVertex& vertex1 = graph()[v1];\n        const uint32_t group0 = vertex0.group;\n        const uint32_t group1 = vertex1.group;\n        if(group0 != group1) {\n            boost::add_edge(group0, group1, groupGraph);\n        }\n    }\n\n    // ofstream graphOut(\"GroupGraph.dot\");\n    // boost::write_graphviz(graphOut, groupGraph);\n\n    // For each group, we have to look at edges to lowered numbered groups\n    vector<uint32_t> adjacentColors;\n    for(uint32_t group0=0; group0<groupCount; group0++) {\n        adjacentColors.clear();\n        // cout << \"Already colored groups adjacent to group \" << group0 << \":\";\n        BGL_FORALL_OUTEDGES(group0, e, groupGraph, GroupGraph) {\n            const uint32_t group1 = uint32_t(target(e, groupGraph));\n            if(group1 < group0) {\n                // cout << \" \" << group1;\n                adjacentColors.push_back(colorTable[group1]);\n            }\n        }\n        // cout << endl;\n        deduplicate(adjacentColors);\n        // cout << \"Already assigned colors adjacent to group \" << group0 << \": \";\n        // copy(adjacentColors.begin(), adjacentColors.end(), ostream_iterator<uint32_t>(cout, \" \"));\n        // cout << endl;\n\n        // Assign to this group the smallest integer color that does not appear\n        // in the adjacent groups.\n        for(uint32_t color=0; color<adjacentColors.size(); color++) {\n            if(adjacentColors[color] != color) {\n                colorTable.push_back(color);\n                break;\n            }\n        }\n        if(colorTable.size() == group0) {\n            colorTable.push_back(uint32_t(adjacentColors.size()));\n        }\n\n        // cout << \"Group \" << group0 << \" assigned color \" << colorTable[group0] << endl;\n    }\n}\n", "meta": {"hexsha": "02491d5ef543d5c9dd78b40c7c2dfb160dabf9b6", "size": 30492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CellGraph.cpp", "max_stars_repo_name": "iosonofabio/ExpressionMatrix2", "max_stars_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "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/CellGraph.cpp", "max_issues_repo_name": "iosonofabio/ExpressionMatrix2", "max_issues_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "max_issues_repo_licenses": ["MIT"], "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/CellGraph.cpp", "max_forks_repo_name": "iosonofabio/ExpressionMatrix2", "max_forks_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "max_forks_repo_licenses": ["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.6631578947, "max_line_length": 151, "alphanum_fraction": 0.6015676243, "num_tokens": 6953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19696593568471757}}
{"text": "/*\n * Costmap2DConverterTest.cpp\n *\n *  Created on: Nov 23, 2016\n *      Authors: Peter Fankhauser, Gabriel Hottiger\n *      Institute: ETH Zurich, ANYbotics\n */\n\n// Grid map\n#include <grid_map_core/grid_map_core.hpp>\n#include <grid_map_costmap_2d/grid_map_costmap_2d.hpp>\n\n// Gtest\n#include <gtest/gtest.h>\n\n// Eigen\n#include <Eigen/Core>\n\nusing namespace grid_map;\n\ntemplate <typename ConversionTable>\nclass TestCostmap2DConversion : public testing::Test {\n public:\n  using TestValue = std::tuple<Position, unsigned char, double, bool>;\n\n  //! Constructor\n  TestCostmap2DConversion() : costmap2d_(8, 5, 1.0, 2.0, 3.0) { gridMap_.setGeometry(Length(8.0, 5.0), 1.0, Position(6.0, 5.5)); }\n\n  //! Getter of test data\n  std::vector<TestValue> getTestValues();\n\n  //! Check that maps have same geometry\n  void assertMapGeometry(const GridMap& gridMap, const costmap_2d::Costmap2D& costMap) {\n    // Check map info.\n    // Different conventions: Costmap2d returns the *centerpoint* of the last cell in the map.\n    Length length = gridMap.getLength() - Length::Constant(0.5 * gridMap.getResolution());\n    Length position = gridMap.getPosition() - 0.5 * gridMap.getLength().matrix();\n    EXPECT_EQ(costMap.getSizeInMetersX(), length.x());\n    EXPECT_EQ(costMap.getSizeInMetersY(), length.y());\n    EXPECT_EQ(costMap.getSizeInCellsX(), gridMap.getSize()[0]);\n    EXPECT_EQ(costMap.getSizeInCellsY(), gridMap.getSize()[1]);\n    EXPECT_EQ(costMap.getResolution(), gridMap.getResolution());\n    EXPECT_EQ(costMap.getOriginX(), position.x());\n    EXPECT_EQ(costMap.getOriginY(), position.y());\n  }\n\n protected:\n  Costmap2DConverter<GridMap, ConversionTable> costmap2dConverter_;\n  costmap_2d::Costmap2D costmap2d_;\n  GridMap gridMap_;\n};\n\n//! Map type that has only mappings for cost map special values.\nusing Costmap2DSpecialTranslationTable = Costmap2DTranslationTable<3, 2, 1, 0>;\n//! Map type that has larger intervals between special values.\nusing Costmap2DLargeIntervalsTranslationTable = Costmap2DTranslationTable<5, 500, 400, 100>;\n\n// Test data for special translation\ntemplate <>\nstd::vector<TestCostmap2DConversion<Costmap2DSpecialTranslationTable>::TestValue>\nTestCostmap2DConversion<Costmap2DSpecialTranslationTable>::getTestValues() {\n  std::vector<TestValue> testValues;\n  testValues.emplace_back(TestValue(Position(3.2, 5.1), costmap_2d::FREE_SPACE, 0.f, true));\n  testValues.emplace_back(TestValue(Position(4.2, 4.1), costmap_2d::INSCRIBED_INFLATED_OBSTACLE, 1.f, true));\n  testValues.emplace_back(TestValue(Position(6.2, 3.1), costmap_2d::LETHAL_OBSTACLE, 2.f, true));\n  testValues.emplace_back(TestValue(Position(5.2, 7.8), costmap_2d::NO_INFORMATION, 3.f, true));\n  // Check for grid map to costmap only.\n  testValues.emplace_back(TestValue(Position(5.4, 6.8), costmap_2d::FREE_SPACE, -1.f, false));\n  testValues.emplace_back(TestValue(Position(8.5, 4.5), costmap_2d::LETHAL_OBSTACLE, 4.f, false));\n  return testValues;\n}\n\n// Test data for special translation\ntemplate <>\nstd::vector<TestCostmap2DConversion<Costmap2DLargeIntervalsTranslationTable>::TestValue>\nTestCostmap2DConversion<Costmap2DLargeIntervalsTranslationTable>::getTestValues() {\n  std::vector<TestValue> testValues;\n  testValues.emplace_back(TestValue(Position(3.2, 5.1), costmap_2d::FREE_SPACE, 100.f, true));\n  testValues.emplace_back(TestValue(Position(4.2, 4.1), costmap_2d::INSCRIBED_INFLATED_OBSTACLE, 400.f, true));\n  testValues.emplace_back(TestValue(Position(6.2, 3.1), costmap_2d::LETHAL_OBSTACLE, 500.f, true));\n  testValues.emplace_back(TestValue(Position(5.2, 7.8), costmap_2d::NO_INFORMATION, 5.f, true));\n  testValues.emplace_back(TestValue(Position(3.4, 3.8), 253/11, 100.f + 300.f/11.f, true));\n  // Check for grid map to costmap only.\n  testValues.emplace_back(TestValue(Position(5.4, 6.8), costmap_2d::FREE_SPACE, 83.f, false));\n  testValues.emplace_back(TestValue(Position(8.5, 4.5), costmap_2d::LETHAL_OBSTACLE, 504.f, false));\n  testValues.emplace_back(TestValue(Position(4.7, 5.8), costmap_2d::INSCRIBED_INFLATED_OBSTACLE, 444.f, false));\n\n  return testValues;\n}\n\n// Test data for direct translation\ntemplate <>\nstd::vector<TestCostmap2DConversion<Costmap2DDirectTranslationTable>::TestValue>\nTestCostmap2DConversion<Costmap2DDirectTranslationTable>::getTestValues() {\n  std::vector<TestValue> testValues;\n  testValues.emplace_back(TestValue(Position(3.2, 5.1), costmap_2d::FREE_SPACE, costmap_2d::FREE_SPACE, true));\n  testValues.emplace_back(\n      TestValue(Position(4.2, 4.1), costmap_2d::INSCRIBED_INFLATED_OBSTACLE, costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true));\n  testValues.emplace_back(TestValue(Position(6.2, 3.1), costmap_2d::LETHAL_OBSTACLE, costmap_2d::LETHAL_OBSTACLE, true));\n  testValues.emplace_back(TestValue(Position(5.2, 7.8), costmap_2d::NO_INFORMATION, costmap_2d::NO_INFORMATION, true));\n  testValues.emplace_back(TestValue(Position(5.4, 6.8), 1, 1.0, true));\n  testValues.emplace_back(TestValue(Position(8.5, 4.5), 97, 97.0, true));\n  // Check for grid map to costmap only.\n  testValues.emplace_back(TestValue(Position(4.7, 5.8), costmap_2d::FREE_SPACE, -30.f, false));\n  testValues.emplace_back(TestValue(Position(3.4, 3.8), costmap_2d::LETHAL_OBSTACLE, 270.f, false));\n  return testValues;\n}\n\n// Test data for century translation\ntemplate <>\nstd::vector<TestCostmap2DConversion<Costmap2DCenturyTranslationTable>::TestValue>\nTestCostmap2DConversion<Costmap2DCenturyTranslationTable>::getTestValues() {\n  std::vector<TestValue> testValues;\n  testValues.emplace_back(TestValue(Position(3.2, 5.1), costmap_2d::FREE_SPACE, 0.f, true));\n  testValues.emplace_back(TestValue(Position(4.2, 4.1), costmap_2d::INSCRIBED_INFLATED_OBSTACLE, 99.f, true));\n  testValues.emplace_back(TestValue(Position(6.2, 3.1), costmap_2d::LETHAL_OBSTACLE, 100.f, true));\n  testValues.emplace_back(TestValue(Position(5.2, 7.8), costmap_2d::NO_INFORMATION, -1.f, true));\n  testValues.emplace_back(TestValue(Position(5.4, 6.8), 253/11, 99.f/11.f, true));\n  // Check for grid map to costmap only.\n  testValues.emplace_back(TestValue(Position(4.7, 5.8), costmap_2d::FREE_SPACE, -30.f, false));\n  testValues.emplace_back(TestValue(Position(3.4, 3.8), costmap_2d::LETHAL_OBSTACLE, 270.f, false));\n  return testValues;\n}\n\nusing TranslationTableTestTypes = ::testing::Types<Costmap2DSpecialTranslationTable, Costmap2DLargeIntervalsTranslationTable,\n                                                   Costmap2DDirectTranslationTable, Costmap2DCenturyTranslationTable>;\n\nTYPED_TEST_CASE(TestCostmap2DConversion, TranslationTableTestTypes);\n\nTYPED_TEST(TestCostmap2DConversion, initializeFromCostmap2d) {\n  // Convert to grid map.\n  GridMap gridMap;\n  this->costmap2dConverter_.initializeFromCostmap2D(this->costmap2d_, gridMap);\n  this->assertMapGeometry(gridMap, this->costmap2d_);\n}\n\nTYPED_TEST(TestCostmap2DConversion, initializeFromGridMap) {\n  // Convert to Costmap2D.\n  costmap_2d::Costmap2D costmap2d;\n  this->costmap2dConverter_.initializeFromGridMap(this->gridMap_, costmap2d);\n  this->assertMapGeometry(this->gridMap_, costmap2d);\n}\n\nTYPED_TEST(TestCostmap2DConversion, addLayerFromCostmap2d) {\n  // Create grid map.\n  const std::string layer(\"layer\");\n  GridMap gridMap;\n  this->costmap2dConverter_.initializeFromCostmap2D(this->costmap2d_, gridMap);\n\n  // Fill in test data to Costmap2D.\n  for (const auto& testValue : this->getTestValues()) {\n    if (std::get<3>(testValue)) {\n      unsigned int xIndex, yIndex;\n      ASSERT_TRUE(this->costmap2d_.worldToMap(std::get<0>(testValue).x(), std::get<0>(testValue).y(), xIndex, yIndex));\n      this->costmap2d_.getCharMap()[this->costmap2d_.getIndex(xIndex, yIndex)] = std::get<1>(testValue);\n    }\n  }\n\n  // Copy data.\n  this->costmap2dConverter_.addLayerFromCostmap2D(this->costmap2d_, layer, gridMap);\n\n  // Check data.\n  for (const auto& testValue : this->getTestValues()) {\n    if (std::get<3>(testValue)) {\n      EXPECT_EQ(std::get<2>(testValue), gridMap.atPosition(layer, std::get<0>(testValue)));\n    }\n  }\n}\n\nTYPED_TEST(TestCostmap2DConversion, setCostmap2DFromGridMap) {\n  // Create costmap2d.\n  costmap_2d::Costmap2D costmap;\n  this->costmap2dConverter_.initializeFromGridMap(this->gridMap_, costmap);\n\n  // Fill in test data to grid map.\n  const std::string layer(\"layer\");\n  this->gridMap_.add(layer);\n  for (const auto& testValue : this->getTestValues()) {\n    Index index;\n    this->gridMap_.getIndex(std::get<0>(testValue), index);\n    this->gridMap_.get(layer)(index(0), index(1)) = std::get<2>(testValue);\n  }\n\n  // Copy data.\n  this->costmap2dConverter_.setCostmap2DFromGridMap(this->gridMap_, layer, costmap);\n\n  // Check data.\n  for (const auto& testValue : this->getTestValues()) {\n    unsigned int xIndex, yIndex;\n    ASSERT_TRUE(costmap.worldToMap(std::get<0>(testValue).x(), std::get<0>(testValue).y(), xIndex, yIndex));\n    costmap.getCharMap()[costmap.getIndex(xIndex, yIndex)] = std::get<1>(testValue);\n  }\n}", "meta": {"hexsha": "7ee1a07885256c17e3789980d647b38cd0afb6b1", "size": 8881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_costmap_2d/test/Costmap2DConverterTest.cpp", "max_stars_repo_name": "jacobhuesman/grid_map", "max_stars_repo_head_hexsha": "16673339229f9669aab407d60324515e2459281b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1305.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T14:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:44:18.000Z", "max_issues_repo_path": "grid_map_costmap_2d/test/Costmap2DConverterTest.cpp", "max_issues_repo_name": "jacobhuesman/grid_map", "max_issues_repo_head_hexsha": "16673339229f9669aab407d60324515e2459281b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 174.0, "max_issues_repo_issues_event_min_datetime": "2018-08-06T21:41:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T04:45:09.000Z", "max_forks_repo_path": "grid_map_costmap_2d/test/Costmap2DConverterTest.cpp", "max_forks_repo_name": "jacobhuesman/grid_map", "max_forks_repo_head_hexsha": "16673339229f9669aab407d60324515e2459281b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 423.0, "max_forks_repo_forks_event_min_datetime": "2018-08-07T13:37:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:07:26.000Z", "avg_line_length": 46.0155440415, "max_line_length": 130, "alphanum_fraction": 0.7474383515, "num_tokens": 2738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.1969659356847175}}
{"text": "#include <boost/numpy.hpp>\n#include <cmath>\n#include \"mjc/core/slcp.h\"\n#include \"macros.h\"\n#include <iostream>\n#include \"mjc/core/mj_render.h\"\n#include <boost/python/slice.hpp>\n\nnamespace bp = boost::python;\nnamespace bn = boost::numpy;\n\ntemplate<typename T>\nbn::ndarray toNdarray1(const T* data, long dim0) {\n  long dims[1] = {dim0};\n  bn::ndarray out = bn::empty(1, dims, bn::dtype::get_builtin<T>());\n  memcpy(out.get_data(), data, dim0*sizeof(T));\n  return out;\n}\ntemplate<typename T>\nbn::ndarray toNdarray2(const T* data, long dim0, long dim1) {\n  long dims[2] = {dim0,dim1};\n  bn::ndarray out = bn::empty(2, dims, bn::dtype::get_builtin<T>());\n  memcpy(out.get_data(), data, dim0*dim1*sizeof(T));\n  return out;\n}\ntemplate<typename T>\nbn::ndarray toNdarray3(const T* data, long dim0, long dim1, long dim2) {\n  long dims[3] = {dim0,dim1,dim2};\n  bn::ndarray out = bn::empty(3, dims, bn::dtype::get_builtin<T>());\n  memcpy(out.get_data(), data, dim0*dim1*dim2*sizeof(T));\n  return out;\n}\n\nenum ContactType {\n  ContactType_SPRING=0,\n  ContactType_SLCP=1,\n  ContactType_SPRINGTAU=2,\n  ContactType_CONVEX=3\n};\n\n\n#define  NV (m_model->ndof)\n#define  NQ (m_model->nqpos)\n#define  NBODY (m_model->nbody)\n#define  NL (m_model->nlmax)\n#define  NC (m_model->ncmax)\n\nconst int Integrator_FWD=1;\n\nclass PyMJCWorld {\n\n\npublic:\n\n    PyMJCWorld(const std::string& binfile);\n    bn::ndarray Step(const bn::ndarray& x, const bn::ndarray& u);\n    bn::ndarray StepMulti(const bn::ndarray& x, const bn::ndarray& u);\n    bp::tuple StepMulti2(const bn::ndarray& x, const bn::ndarray& u, const bn::ndarray& done);\n    bp::tuple StepJacobian(const bn::ndarray& x, const bn::ndarray& u);\n    void Plot(const bn::ndarray& x);    \n    void SetActuatedDims(const bp::object& dims);\n    void SetContactType(ContactType contactType) {\n      m_contactType = contactType;\n    }\n    void SetTimestep(mjtNum dt) {\n      m_model->timestep = dt;\n    }\n    bn::ndarray ComputeContacts(const bn::ndarray& x);\n    bp::dict GetModel();\n    void SetModel(bp::dict);\n    bp::dict GetData(const bn::ndarray& x);\n\n    bn::ndarray GetImage(const bn::ndarray& x);\n\n    ~PyMJCWorld();\nprivate:\n    // PyMJCWorld(const PyMJCWorld&) {}\n\n    void _PlotInit();\n    mjtByte _StepLowLevel(const mjtByte flgDiff, const mjtNum* tu,\n          mjtNum* contact_scratch, mjtNum *f_ctr,\n          mjtNum *plam, mjtNum *pdist, mjtNum *pdebug, mjtNum *s, \n          mjtNum *jac, mjtNum *f_j);\n\n    void _PreProcess();\n    mjtNum _ContactImpulse(mjtNum* contact_scratch, mjtNum *f_ctr, const mjtNum *qvel_next_user);\n\n    void _SetState(const mjtNum* xdata) {mju_copy(m_data->qpos, (xdata), NQ); mju_copy(m_data->qvel, (xdata)+NQ, NV); }\n    void _SetControl(const mjtNum* udata) {for (int i=0; i < m_actuatedDims.size(); ++i) m_u[m_actuatedDims[i]] = (udata)[i];}\n    void _ComputeCOM(mjtNum* out);\n\n\n    mjModel* m_model;\n    mjData* m_data;\n    mjRender* m_mjr;\n    std::vector<mjtNum> m_u;\n    std::vector<int> m_actuatedDims;\n    ContactType m_contactType;\n    int m_integrator;\n\n    mjtByte m_flagPrehoc;\n\n    mjtNum m_spring_kspring, m_spring_kdamp;\n    mjtByte m_spring_scale;\n\n    mjtNum m_st_tau, m_st_beta; // recovery time, softness\n\n    mjtNum m_slcp_tau, m_slcp_beta, m_slcp_tau2;   // ? ? ?\n    int m_slcp_iterCloud;\n    int m_slcp_maxIter;\n    mjtNum* m_slcp_betaVec; // XXX i'm not sure what this is.\n\n\n    mjtByte m_flagPlanar;\n    double *pDBG, *pXIN, *pUIN, *pXOUT, *pLAM, *pDIST, *pS, *pJAC, *pF_J;\n    double *pPUSH_BODY, *pPUSH_POINT, *pPUSH_FORCE;\n    int NS, NDS;\n    int m_SZ_F, m_SZ_DIST, m_SZ_DISTX;\n    // int FLG_CONTACT, FLG_FWD;\n    double* FEAT;\n    mjtNum* cscratch[1];\n\n};\n\nPyMJCWorld::PyMJCWorld(const std::string& binfile) :\n  m_model(mj_loadModel(binfile.c_str())),\n  m_data(mj_makeData(m_model)),\n  m_mjr(NULL),\n  m_u(NV, 0),\n  m_actuatedDims(),\n  \n  m_contactType(ContactType_SPRING),\n  m_integrator(Integrator_FWD),\n  m_flagPrehoc(true),\n\n  m_spring_kspring(0),\n  m_spring_kdamp(0),\n  m_spring_scale(false),\n\n  m_st_tau(0.04), // depth of penetration\n  m_st_beta(0.1),\n\n  m_slcp_tau(0.04), // depth of penetration\n  m_slcp_beta(0.001),\n  m_slcp_tau2(0.04), \n  m_slcp_iterCloud(2), // ??\n  m_slcp_maxIter(10),\n  m_slcp_betaVec(new mjtNum[(m_flagPlanar?2:4)*NC+NL]),\n\n  m_flagPlanar(((m_model->jnt_type[0]==mjSLIDE)&&(m_model->jnt_type[1]==mjSLIDE)&&(m_model->jnt_type[2]==mjHINGE))),\n\n  pDBG(NULL), \n  pXIN(NULL), \n  pUIN(NULL), \n  pXOUT(NULL), \n  pLAM(NULL), \n  pDIST(NULL), \n  pS(NULL), \n  pJAC(NULL), \n  pF_J(NULL),\n  pPUSH_BODY(NULL), \n  pPUSH_POINT(NULL), \n  pPUSH_FORCE(NULL),\n\n  NS(0),\n  NDS(0),\n\n  m_SZ_F(mjConDim*NC+NL),\n  m_SZ_DIST(NC+NL),\n  m_SZ_DISTX(4*NC+NL),\n\n  FEAT(NULL)\n{\n\n\n\n\n    _PreProcess();\n\n    printf(\"Damping[0]: %f\\n\", m_model->jnt_vel_damping[0]);\n    printf(\"Gravity: %f %f %f\\n\", m_model->gravity[0], m_model->gravity[1], m_model->gravity[2]);\n    printf(\"Viscosity: %f\\n\", m_model->viscosity);\n    printf(\"Timestep: %f\\n\", m_model->timestep);\n    \n\n\n}\n\nPyMJCWorld::~PyMJCWorld() {\n  if (m_mjr) {\n    m_mjr->Close();\n    delete m_mjr;\n  }\n  mj_delete(m_model, m_data);\n  delete[] m_slcp_betaVec;\n}\n\n#define MJTNUM_DTYPE bn::dtype::get_builtin<mjtNum>()\n#define CHECK_MJTNUM_ARRAY(x,ndim) FAIL_IF_FALSE((x).get_dtype() == MJTNUM_DTYPE && (x).get_nd() == (ndim) && (x).get_flags() & bn::ndarray::C_CONTIGUOUS)\n// #define ENSURE_MJTNUM_ARRAY(x) FAIL_IF_FALSE( x.get_dtype() ==  )\n\n#define DO_STEP() do {_StepLowLevel(flgDiff, m_u.data(), cscratch[0], f_ctr, pLAM, pDIST, pDBG, s, jac, f_j);} while(0)\n\n#define COPY_STATE(dest) do {mju_copy((dest), m_data->qpos, NQ); mju_copy((dest)+NQ, m_data->qvel, NV); } while(0)\n#define INC_BY_STATE(dest) do {mju_add((dest), (dest), m_data->qpos, NQ); mju_add((dest)+NQ, (dest)+NQ, m_data->qvel, NV); } while(0)\n#define DEC_BY_STATE(dest) do {mju_sub((dest), (dest), m_data->qpos, NQ); mju_sub((dest)+NQ, (dest)+NQ, m_data->qvel, NV); } while(0)\n#define SCALE_INPLACE(p, scl, n) mju_scl((p), (p), (scl), (n))\n\n#define PYPRINT(obj) do{std::string s1 = bp::extract<std::string>((obj).attr(\"__repr__\")()); std::cout << s1 << std::endl;} while(0)\n\n\nbn::ndarray PyMJCWorld::Step(const bn::ndarray& x, const bn::ndarray& u) {\n  CHECK_MJTNUM_ARRAY(x, 1);\n  CHECK_MJTNUM_ARRAY(u, 1);\n  FAIL_IF_FALSE(u.shape(0) == m_actuatedDims.size());\n\n  mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());\n  mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());\n\n  _SetState(xdata);\n  _SetControl(udata);\n\n\n  mjtByte flgDiff=1;\n  mjtNum *s=0, *jac=0, *f_j=0, *f_ctr=0;\n  DO_STEP();\n\n  bn::ndarray out = bn::empty(bp::make_tuple(NQ+NV), bn::dtype::get_builtin<mjtNum>());    \n  mjtNum* outdata = reinterpret_cast<mjtNum*>(out.get_data());\n  COPY_STATE(outdata);\n  return out;\n}\n\nbn::ndarray PyMJCWorld::StepMulti(const bn::ndarray& x, const bn::ndarray& u) {\n  CHECK_MJTNUM_ARRAY(x, 2);\n  CHECK_MJTNUM_ARRAY(u, 2);\n\n  int n_steps = x.shape(0);\n  FAIL_IF_FALSE (u.shape(0) == x.shape(0));\n\n  mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());\n  mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());\n\n  const int NX = NQ + NV, NU = m_actuatedDims.size();\n\n  bn::ndarray out = bn::empty(bp::make_tuple(n_steps,NX), bn::dtype::get_builtin<mjtNum>());    \n  mjtNum* outdata = reinterpret_cast<mjtNum*>(out.get_data());\n\n\n  for (int i=0; i < n_steps; ++i) {\n    _SetState(xdata + NX*i);\n    _SetControl(udata + NU*i);\n\n    mjtByte flgDiff=1;\n    mjtNum *s=0, *jac=0, *f_j=0, *f_ctr=0;\n    DO_STEP();\n    COPY_STATE(outdata + NX*i);\n  }\n\n  return out;\n}\n\nbp::tuple PyMJCWorld::StepMulti2(const bn::ndarray& x, const bn::ndarray& u, const bn::ndarray& done) {\n  CHECK_MJTNUM_ARRAY(x, 2);\n  CHECK_MJTNUM_ARRAY(u, 2);\n  \n  const int xcols = NQ+NV,\n               ucols = m_actuatedDims.size(),\n               ycols = NQ+NV,\n               fcols=m_model->ndof,\n               dcomcols = 3,\n               distcols = m_model->nbody,\n               kincols = m_model->ndof*7 + m_model->nbody*28;\n  int n_steps = x.shape(0);\n\n  // kincols is cdof thru qfrc_bias inclusive\n\n  FAIL_IF_FALSE (u.shape(0) == x.shape(0));\n  FAIL_IF_FALSE(u.shape(1) == ucols);\n  FAIL_IF_FALSE(x.shape(1) == xcols);\n\n\n  mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());\n  mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());\n\n  uint8_t* donedata = reinterpret_cast<uint8_t*>(done.get_data());\n\n  bn::ndarray yarray = bn::zeros(bp::make_tuple(n_steps,ycols), bn::dtype::get_builtin<mjtNum>());\n  bn::ndarray farray = bn::zeros(bp::make_tuple(n_steps,fcols), bn::dtype::get_builtin<mjtNum>());\n  bn::ndarray dcomarray = bn::zeros(bp::make_tuple(n_steps,dcomcols), bn::dtype::get_builtin<mjtNum>());\n  bn::ndarray distarray = bn::zeros(bp::make_tuple(n_steps,distcols), bn::dtype::get_builtin<mjtNum>());\n  bn::ndarray kinarray = bn::zeros(bp::make_tuple(n_steps,kincols), bn::dtype::get_builtin<mjtNum>());\n\n  mjtNum* ydata = reinterpret_cast<mjtNum*>(yarray.get_data());\n  mjtNum* fdata = reinterpret_cast<mjtNum*>(farray.get_data());\n  mjtNum* dcomdata = reinterpret_cast<mjtNum*>(dcomarray.get_data());\n  mjtNum* distdata = reinterpret_cast<mjtNum*>(distarray.get_data());\n  mjtNum* kindata =  reinterpret_cast<mjtNum*>(kinarray.get_data());\n\n  for (int i=0; i < n_steps; ++i) {\n\n    if (donedata[i]) continue;\n\n    _SetState(xdata + xcols*i);\n    _SetControl(udata + ucols*i);\n\n    mjtByte flgDiff=1;\n    mjtNum *s=0, *jac=0, *f_j=0, *f_ctr=0;\n\n    mjtNum *plam = fdata + fcols*i; // note mju_copy(plam, d->lc_f, m->ndof);\n    mjtNum *pdist = distdata + distcols*i;\n\n    mjtNum comBefore[3];\n    mj_kinematics(m_model, m_data);\n    _ComputeCOM(comBefore); // XXX extra calculation\n\n    _StepLowLevel(flgDiff, m_u.data(), cscratch[0], f_ctr, plam, pdist, pDBG, s, jac, f_j);\n    \n    COPY_STATE(ydata + ycols*i); // y \n    mju_copy(kindata + kincols*i, m_data->cdof, kincols);\n    // f is handled by steplowlevel\n    mjtNum comAfter[3]; // dcom\n    mj_kinematics(m_model, m_data);\n    _ComputeCOM(comAfter); // XXX extra calculation\n    mju_sub(dcomdata + dcomcols*i, comAfter, comBefore, 3); \n    // dist is handled by steplowlevel\n\n  }\n\n  return bp::make_tuple(yarray, farray, dcomarray, distarray, kinarray);\n}\n\nvoid PyMJCWorld::_ComputeCOM(mjtNum* com) {\n\t // XXX is idx 0 always the ground?\n  mjtNum tot=0;\n  com[0] = com[1] = com[2] = tot = 0;\n  for(int i=1; i<m_model->nbody; i++ )\n  {\n    if( m_model->geom_type[i]==mjPLANE ) continue;\n    com[0] += m_data->xpos[3*i+0]*m_model->body_mass[i];\n    com[1] += m_data->xpos[3*i+1]*m_model->body_mass[i];\n    com[2] += m_data->xpos[3*i+2]*m_model->body_mass[i];\n    tot += m_model->body_mass[i];\n  }\n  com[0] /= tot;\n  com[1] /= tot;\n  com[2] /= tot; \n}\n\nbp::tuple PyMJCWorld::StepJacobian(const bn::ndarray& x, const bn::ndarray& u) {\n    CHECK_MJTNUM_ARRAY(x, 1);\n    CHECK_MJTNUM_ARRAY(u, 1);\n    FAIL_IF_FALSE(u.shape(0) == m_actuatedDims.size());\n\n    mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());\n    mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());\n\n\n    for (int i=0; i < m_actuatedDims.size(); ++i) {\n      m_u[m_actuatedDims[i]] = udata[i];\n    }\n\n    mjtByte flgDiff=1;\n    mjtNum *s=0, *jac=0, *f_j=0, *f_ctr=0;\n\n\n    const int NX = NQ+NV, NU = m_actuatedDims.size();\n    bn::ndarray y =    bn::zeros(bp::make_tuple(NX), bn::dtype::get_builtin<mjtNum>());\n    bn::ndarray dydx = bn::zeros(bp::make_tuple(NX, NX), bn::dtype::get_builtin<mjtNum>());\n    bn::ndarray dydu = bn::zeros(bp::make_tuple(NU, NX), bn::dtype::get_builtin<mjtNum>());\n\n\n    mjtNum* py = reinterpret_cast<mjtNum*>(y.get_data());\n    mjtNum* pdydx = reinterpret_cast<mjtNum*>(dydx.get_data());\n    mjtNum* pdydu = reinterpret_cast<mjtNum*>(dydu.get_data());\n\n\n    mjtNum eps=1e-6;\n\n    _SetState(xdata);\n    _SetControl(udata);\n    DO_STEP();\n    COPY_STATE(py);\n    for (int i=0; i < NX; ++i) { // XXX LOL using the fact that qpos and qvel are stored next to each other continguously\n\n      _SetState(xdata);\n      m_data->qpos[i] += eps;\n      DO_STEP();\n      INC_BY_STATE(pdydx+i*NX);\n\n      _SetState(xdata);\n      m_data->qpos[i] -= eps;\n      DO_STEP();\n      DEC_BY_STATE(pdydx+i*NX);\n\n      SCALE_INPLACE(pdydx + i*NX, 1./(2.*eps), NX);      \n\n    }\n\n    for (int i=0; i < NU; ++i) {\n\n      _SetState(xdata);\n      m_u[m_actuatedDims[i]] = udata[i] + eps;\n      DO_STEP();\n      INC_BY_STATE(pdydu + i*NX);\n\n      _SetState(xdata);\n      m_u[m_actuatedDims[i]] = udata[i] - eps;\n      DO_STEP();\n      DEC_BY_STATE(pdydu + i*NX);\n\n      m_u[m_actuatedDims[i]] = udata[i];\n\n      SCALE_INPLACE(pdydu + i*NX, 1./(2.*eps), NX);      \n\n    }\n\n  return bp::make_tuple(y, dydx.transpose(), dydu.transpose());\n}\n\nvoid PyMJCWorld::Plot(const bn::ndarray& x) {\n    CHECK_MJTNUM_ARRAY(x, 1);\n    if (!m_mjr) _PlotInit();\n\n    mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());\n    // mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());\n\n    _SetState(xdata);\n    mj_kinematics(m_model, m_data);\n    mj_global(m_model, m_data);\n\n    m_mjr->Update(m_model, m_data);\n\n}\n\nbn::ndarray PyMJCWorld::GetImage(const bn::ndarray& x) {\n  long dims[3]={480,640,4};\n  bn::ndarray out = bn::empty(3, dims, bn::dtype::get_builtin<uint8_t>());\n  Plot(x);\n  m_mjr->SaveImage(out.get_data());\n  using bp::_;\n  using bp::slice;\n  // using bp::slice;\n  // return out;\n  out = bp::extract<bn::ndarray>(out[bp::make_tuple(slice(_,_,-1),slice(),bp::make_tuple(2,1,0))].attr(\"copy\")());\n  return out;\n}\n\n\nvoid PyMJCWorld::SetActuatedDims(const bp::object& dims) {\n  m_u.assign(NV, 0);\n  int ndims = bp::len(dims);\n  m_actuatedDims.clear();\n  for (int i=0; i < ndims; ++i) {\n    m_actuatedDims.push_back(bp::extract<int>(dims[i]));\n  }\n}\n\n\nvoid PyMJCWorld::_PlotInit() {\n  m_mjr = new mjRender();\n  int x        = 0;\n  int y        = 0;\n  int width    = 640;\n  int height   = 480;  \n  m_mjr->Open(m_model->name, x, y, width, height);\n  m_mjr->Set(m_model, m_data);\n}\n\n\nvoid PyMJCWorld::_PreProcess() { \n\n  // Original code:\n  mj_solve1(m_model, m_data);\n  mj_contactPrepare(m_model, m_data, 0);\n  mj_solve2(m_model, m_data);\n  m_data->nlim=m_model->nlmax;\n  m_data->ncon=m_model->ncmax;\n\n\n\n\n  // for (int i=0; i < sz_pyramid; ++i) m_slcp_betaVec[i] = 0; // siminit.m line 72\n}\n\n\nmjtNum PyMJCWorld::_ContactImpulse(mjtNum* contact_scratch, mjtNum *f_ctr, const mjtNum * /*qvel_next_user*/) {\n  mjModel* m=m_model;\n  mjData* d = m_data;\n\n  mjtNum dbg, mu;\n  int j, stepDbg;\n\n  #if 0\n  mjtNum *alpha, *kappaN, *kappaT, *kappaV, *contact_buffer, *P\n  int sz_dist = nl+nc;\n  #endif\n\n  mjtNum *J, *A, *f, *v, *scratch;\n  mjtByte inCloud;\n  int nl    = d->nlim;\n  int nc    = d->ncon;\n  int sz = nl+mjConDim*nc;\n  int sz_pyramid = (m_flagPlanar?2:4)*nc+nl;\n\n   //no need to zero - contactPrepare did that already\n   //mju_zero(d->lc_f, SZ_F);\n   \n   switch( m_contactType ) {\n      case ContactType_SPRING:\n         mju_mulMatVec(d->lc_v0, d->lc_J, d->qvel_next, sz, NV);\n         mj_impulseSpring(m, d, m_spring_kspring, m_spring_kdamp, 1, 1, m_spring_scale);\n         return 0;\n      case ContactType_SPRINGTAU:\n      case ContactType_SLCP:\n         mju_mulMatVec(d->lc_v0, d->lc_J, d->qvel_next, sz, NV);\n     if (m_contactType == ContactType_SPRINGTAU)\n      mj_impulseTau(m, d, m_st_tau, m_st_beta);\n     else\n      mj_impulseTau2(m, d, m_slcp_tau, m_slcp_tau2, m_slcp_beta, m_slcp_maxIter);\n     return 0; // This is a little hack - in this formulation, SLCP no longer exists, there is only springtau\n         //if( FLG_CONTACT==CF_SPRINGTAU && !ITER_CLOUD ) return 0; //otherwise, continue with slcp\n         f       = contact_scratch;\n         v       = contact_scratch + sz_pyramid;\n         J       = contact_scratch + sz_pyramid*2;\n         A       = contact_scratch + sz_pyramid*2 + sz_pyramid*NV;\n         scratch = contact_scratch + sz_pyramid*2 + sz_pyramid*NV + sz_pyramid*sz_pyramid;\n         mju_mulMatVec(v, J, d->qvel_next, sz_pyramid, NV);\n         sz_pyramid = convexify(m, d, m_flagPlanar, f, v, J, A);\n\n         if( m_contactType==ContactType_SLCP ) { //if we came here from springTau, lc_f is already initialized\n#ifdef _WIN32\n            inCloud= (f_ctr && !_isnan(f_ctr[0]));\n#else\n            inCloud= (f_ctr && !std::isnan(f_ctr[0]));\n#endif\n            if (!inCloud) {\n               // tol = 1e-15\n               dbg=slcp_solve(sz_pyramid, A, v, f, m_slcp_betaVec, 1E-15, m_slcp_maxIter, scratch);\n               if( dbg<0 )\n                  return dbg;\n               if (f_ctr) mju_copy(f_ctr, f, sz_pyramid);\n            } else {\n               mju_copy(f, f_ctr, sz_pyramid);\n            }\n         }\n         for (j=0;j<m_slcp_iterCloud;j++) {\n            mu=-1; //a small regularizing term to deal with rank-deficient A\n            stepDbg = slcp_step(sz_pyramid, A, v, f, m_slcp_betaVec, scratch, scratch+sz_pyramid, &mu);\n            if( stepDbg<0 ) return stepDbg-0.1234567;\n         }\n         deconvexify(m, d, m_flagPlanar, f); // assigns into d->lc_f\n         \n         //test: J*f should be equal to lc_J*lc_f:\n         //mju_mulMatTVec(ds,J,f,LOCAL_sz_cl,NV);\n         //mju_mulMatTVec(ds+SZ_F,d->lc_J,d->lc_f,SZ_F,NV);\n         return dbg;\n         \n      case ContactType_CONVEX:\n        NOTIMPLEMENTED;\n        #if 0\n         kappaN = contact_scratch;\n         kappaT = contact_scratch + sz_dist;\n         kappaV = contact_scratch + sz_dist*2;\n         alpha  = contact_scratch + sz_dist*3;\n         makeKappa(pkappal[0],pkappac[0], kappaN, d->lc_A, nl, nc);\n         makeKappa(0         ,pkappac[1], kappaT, d->lc_A, nl, nc);\n         makeKappa(pkappal[1],pkappac[2], kappaV, d->lc_A, nl, nc);\n#ifdef _WIN32\n         inCloud= (f_ctr && !_isnan(f_ctr[0]));\n#else\n         inCloud= (f_ctr && !std::isnan(f_ctr[0]));\n#endif\n         \n         //initialize:\n         mju_mulMatVec(d->lc_v0, d->lc_J, d->qvel_next, sz, NV);\n         mj_impulseTau(m, d, TAU_SPRING, BETA_SPRING);\n         \n         if (FLG_FWD>0) {\n            contact_buffer = contact_scratch + sz_dist*3 + sz;\n            if (!inCloud) {\n               dbg=mj_impulseConvex(d->lc_f, m, d, kappaN, kappaT, kappaV,\n                       dmax, amin, amaxl, amaxc, marginF, marginV, 1e-15, MAX_ITER, contact_buffer);\n               if( dbg<0 )\n                  return dbg;\n               if (f_ctr) mju_copy(f_ctr, d->lc_f, sz);\n            } else {\n               mju_copy(d->lc_f, f_ctr, sz);\n            }\n            makeAlpha(alpha, d->lc_dist, amin, amaxl, amaxc, dmax, d->lc_A, nl, nc);\n            for (j=0;j<ITER_CLOUD;j++) {\n               contact_buffer[sz]=0;\n               stepDbg = convex_fwdIter(d->lc_f, m, nl, nc,\n                       alpha, kappaN, kappaT, kappaV,\n                       d->con_friction, d->lc_A, d->lc_v0, d->lc_vmin,\n                       marginF, marginV, contact_buffer, contact_buffer+sz);\n               if( stepDbg ) return stepDbg+0.7654321;\n            }\n         } else { //inv dyn\n            P              = contact_scratch + sz_dist*3 + sz;\n            contact_buffer = contact_scratch + sz_dist*3 + sz*2;\n            mju_copy(d->qvel_next, qvel_next_user, NV);\n            mju_mulMatVec(d->lc_v0, d->lc_J, d->qvel_next, sz, NV);\n            if (!inCloud) {\n               dbg=mj_impulseConvexInv(d->lc_f, m, d, kappaN, kappaT, kappaV,\n                       dmax, amin, amaxl, amaxc, marginF, marginV, 1e-15, MAX_ITER, contact_buffer);\n               if( dbg<0 )\n                  return dbg;\n               if (f_ctr) mju_copy(f_ctr, d->lc_f, sz);\n            } else {\n               mju_copy(d->lc_f, f_ctr, sz);\n            }\n            mju_zero(alpha, sz);\n            makeP(P, d->lc_A, alpha, d->lc_v0, d->lc_vmin, nl, nc, kappaV, marginV);\n            makeAlpha(alpha, d->lc_dist, amin, amaxl, amaxc, dmax, d->lc_A, nl, nc);\n            for (j=0;j<ITER_CLOUD;j++) {\n               contact_buffer[sz]=0;\n               stepDbg=convex_invIter(d->lc_f, m, nl, nc,\n                       alpha, kappaN, kappaT,\n                       d->con_friction, d->lc_A, P,\n                       marginF, contact_buffer, contact_buffer+sz);\n               if( stepDbg ) return stepDbg+0.7654321;\n            }\n         }\n         return dbg;\n         #endif\n   }\n\n   PRINT_AND_THROW(\"UNREACHABLE\");\n   return 0;\n}\n\nmjtByte PyMJCWorld::_StepLowLevel(const mjtByte flgDiff, const mjtNum* tu,\n        mjtNum* contact_scratch, mjtNum *f_ctr,\n        mjtNum *plam, mjtNum *pdist, mjtNum *pdebug, mjtNum *s, \n        mjtNum *jac, mjtNum *f_j) {\n\n  mjModel* m=m_model;\n  mjData* d=m_data;\n   int i, j, k, n;\n   mjtNum *ds = d->scratch;\n   mjtNum dbg, total_mass;\n   mjtByte needCoM;\n\n   if (flgDiff) {\n      // run kinematic computations\n      mj_kinematics(m, d);\n      mj_global(m, d);\n      mj_crb(m, d);\n      mj_factorM(m, d);\n      if (m_SZ_F) {\n         mj_contactPrepare(m, d, (tu?0:2));//(FLG_CONTACT==CF_SPRINGTAU && !ITER_CLOUD));\n      }\n   } else {\n      // global does this, so if we're not running global, we should manually zero it out\n      mju_zero(d->qfrc_ext, NV);\n      // contactPrepare does this\n      mju_zero(d->lc_f, m_SZ_F);\n   }\n   mj_rne(m, d, 0);\n   mj_passive(m, d);\n   \n\n   if( s ) {\n      needCoM = 0;\n      i=0;\n      // start with CoM:\n      \n      // CoM quat space:\n      if( FEAT[0] ) i+=4;\n      // CoM position:\n      for( k=0; k<3; k++ ) {\n         if( FEAT[1+k] != 0.0 ) {\n            s[i]=d->com[k];\n            i++;\n            needCoM++;\n         }\n      }\n      // CoM velocities:\n      for( k=0; k<6; k++ ) {\n         if( FEAT[4+k] != 0.0 ) {\n            s[i]=d->cvel[k];\n            i++;\n         }\n      }\n\n      for (j=1;j<NBODY;j++) {\n         // quaternion\n         if( FEAT[10*j] != 0.0 ) {\n            for( k=0; k<4; k++ ) {\n               s[i]=d->xquat[4*j+k];\n               i++;\n            }\n         }\n         // position\n         for( k=0; k<3; k++ ) {\n            if( FEAT[10*j+1+k] != 0.0 ) {\n         if ( FEAT[10*j+1+k] == 2.0 ) // Use xanchor\n                  s[i]=d->xanchor[3*m->body_jnt_adr[j]+k];\n         else // Use regular position\n          s[i]=d->xpos[3*j+k];\n               i++;\n            }\n         }\n         // velocities\n         for( k=0; k<6; k++ ) {\n            if( FEAT[10*j+4+k] != 0.0 ) {\n               s[i]=d->cvel[6*j+k];\n               i++;\n            }\n         }\n      }\n    //test:\n      //if( i!=NS ) s[0]=sqrt((double)-1.0);\n      if( jac ) { //need to compute jacs as well\n         total_mass=0;\n         i=needCoM; //save room for the CoM's jac, which will be created last\n         if( FEAT[0] != 0.0 ) i+=3; //save useless room for the CoM's nonexistent quat's jac\n         for( j=1; j<NBODY; j++ ) {\n            if( FEAT[10*j] != 0.0 ) {\n               mj_jac(m, d, 0, ds, 0, j, 1);\n               for( k=0; k<3; k++ ) {\n                  mju_copy(jac+i*NV, ds+k*NV, NV);\n                  i++;\n               }\n            }\n            if( needCoM || FEAT[10*j+1] != 0.0 || FEAT[10*j+2] != 0.0 || FEAT[10*j+3] != 0.0 ) {\n               mj_jac(m, d, ds, 0, 0, j, 1);\n               for( k=0; k<3; k++ ) {\n                  if( FEAT[10*j+1+k] != 0.0 ) {// keep this body's jac:\n                     mju_copy(jac+i*NV, ds+k*NV, NV);\n                     i++;\n                  }\n               }\n               if( needCoM ) { // building the CoM's jac:\n                  n=0;\n                  total_mass+=m->body_mass[j];\n                  mju_scl(ds, ds, m->body_mass[j], 3*NV);  //scale by body mass\n                  for( k=0; k<3; k++ ){\n                     if( FEAT[1+k] != 0.0 ) {\n                        mju_addTo(jac+n*NV, ds+k*NV, NV);\n                        n++;\n                     }\n                  }\n               }\n            }\n         }\n         if( needCoM ) mju_scl(jac, jac, 1/total_mass, needCoM*NV);\n      }\n   }\n   \n   if( f_j ) mju_copy(f_j, d->lc_J, (d->nlim+mjConDim*d->ncon)*NV);\n\n   if( pdist )  {\n    // store the smallest contact distance for each body.\n      // first, set all contact distances to the maximum value.\n      for (i = 0; i < NBODY; i++)\n      pdist[i] = 1000.0;\n    for (j = 0; j < d->ncon; j++)\n    {\n      // Address of bodies.\n      if (d->con_pair[j] >= m->ncpair) continue;\n      int b1 = m->geom_body_id[m->pair_geom1[d->con_pair[j]]];\n      int b2 = m->geom_body_id[m->pair_geom2[d->con_pair[j]]];\n      double pen = d->lc_dist[d->nlim+j];\n      if (pdist[b1] > pen)\n        pdist[b1] = pen;\n      if (pdist[b2] > pen)\n        pdist[b2] = pen;\n      // Make sure the ground is one of the bodies -- otherwise we need some special handling.\n      //if (b1 != 0 && b2 != 0)\n      //  mexErrMsgTxt(\"Returning X distance and detected collision not with the ground -- consider adding some code to handle this!\");\n    }\n      //min2full_dist(d, d->lc_dist, pdist);\n      //min2full_xpos(d, d->con_xpos, pdist+SZ_DIST);\n   }\n   \n   if( !tu ) return 0;\n   \n   if (m_SZ_F && m_flagPrehoc==0) {\n      mj_solve2(m, d);\n   } \n   else {\n      if (m_integrator>0) {\n        mju_addTo(d->qfrc_ext, tu, NV);\n      }\n      mj_solve2(m, d);\n   }\n   if (m_SZ_F) {\n      dbg = _ContactImpulse(contact_scratch, f_ctr, tu); //we give tu to contact because \n   }\n   \n   if (m_integrator>0) {\n      if (m_flagPrehoc==0) {\n         mj_backsubM(m, d, d->qacc, tu);\n         mju_scl(d->qacc, d->qacc, m->timestep, NV);\n         mju_addTo(d->qvel_next, d->qacc, NV);\n      }\n      mj_solve3(m, d);\n      mj_integrate(m, d);\n   } else {\n      mju_mulMatTVec(d->scratch, d->lc_JP, d->lc_f, m_SZ_F, NV);\n      mju_sub(d->qvel_next, tu, d->scratch, NV);\n      mju_sub(d->qvel_next, d->qvel_next, d->qvel, NV);\n      mju_scl(d->qacc, d->qvel_next, 1/m->timestep, NV);\n      mj_fullM(m, d, d->scratch, d->qM);\n      mju_mulMatVec(d->qvel_next, d->scratch, d->qacc, NV, NV);\n      //first i multiplied by JP, then mult by fullM;\n      //alternatively, maybe mult by J and not mult that piece by M?\n      mju_sub(d->qvel_next, d->qvel_next, d->qfrc_bias, NV);\n      mju_sub(d->qvel_next, d->qvel_next, d->qfrc_ext, NV);\n   }\n   \n   if( plam ) { // return contact forces.\n    int sz = d->nlim + mjConDim*d->ncon;\n    //mju_mulMatTVec(d->scratch, d->lc_JP, d->lc_f, sz, m->ndof); // This version computes accelerations.\n    mju_mulMatTVec(d->scratch, d->lc_J, d->lc_f, sz, m->ndof); // This version computes forces.\n    mju_copy(plam, d->scratch, m->ndof);\n    //min2full_lam(d, d->lc_f, plam);\n   }\n   if( pdebug ) pdebug[0]=dbg;\n   return 0;\n}\n\nbn::ndarray PyMJCWorld::ComputeContacts(const bn::ndarray& x) {\n\n\n  CHECK_MJTNUM_ARRAY(x, 1);\n  mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());\n  _SetState(xdata);\n  mj_kinematics(m_model, m_data);\n  mj_global(m_model, m_data);\n\n\n\n  bn::ndarray dists = bn::empty(bp::make_tuple(m_model->nbody), bn::dtype::get_builtin<mjtNum>());    \n  mjtNum* distsdata = reinterpret_cast<mjtNum*>(dists.get_data());\n  for (int i=0; i < m_model->nbody; ++i) {\n    // printf(\"body %i parent id %i\\n\", i, m_model->body_parent_id[i]);\n    distsdata[i] = 1000;\n  }\n\n\n  // Code copied from mj_contactPrepare\n  mjContact con[mjMaxConPair]; \n  mjModel* m=m_model;\n\n  for(int i=0; i<m->ncpair; i++ )\n    if( m->pair_enable[i] )\n    {\n      // get geom ids\n      int gid1 = m->pair_geom1[i];\n      int gid2 = m->pair_geom2[i];\n\n\n      int num = conFunction[m->pair_type[i]](con, m->mindist[0],\n        m_data->geom_xpos+3*gid1, m_data->geom_xmat+9*gid1, m->geom_size+mjNumSize*gid1,\n        m_data->geom_xpos+3*gid2, m_data->geom_xmat+9*gid2, m->geom_size+mjNumSize*gid2);\n\n      if( num > conInfo[m->pair_type[i]][0] )\n        mju_error(\"too many contacts in geom pair\");\n         \n      // process all returned contacts\n      for(int j=0; j<num; j++ )\n      {\n        mjtNum dist = -con[j].depth;\n        int bid1 = m_model->geom_body_id[gid1];\n        int bid2 = m_model->geom_body_id[gid2];\n        distsdata[bid1] = fmin(dist, distsdata[bid1]);\n        distsdata[bid2] = fmin(dist, distsdata[bid2]);\n      }\n    }\n  return dists;\n\n}\n\nint _ndarraysize(const bn::ndarray& arr) {\n  int prod = 1;\n  for (int i=0; i < arr.get_nd(); ++i) {\n    prod *= arr.shape(i);\n  }\n  return prod;\n}\ntemplate<class T>\nvoid _copyscalardata(const bp::object& from, T& to) {\n  to = bp::extract<T>(from);\n}\ntemplate <short ndim,typename T>\nvoid _copyarraydata(const bn::ndarray& from, T* to) {\n  FAIL_IF_FALSE(from.get_dtype() == bn::dtype::get_builtin<T>() && from.get_nd() == ndim && from.get_flags() & bn::ndarray::C_CONTIGUOUS);\n  memcpy(to, from.get_data(), _ndarraysize(from)*sizeof(T));\n}\n\ntemplate<typename T>\nvoid _csdihk(bp::dict d, const char* key, T& to) {\n  // copy scalar data if has_key\n  if (d.has_key(key)) _copyscalardata(d[key], to);\n}\ntemplate<short ndim, typename T>\nvoid _cadihk(bp::dict d, const char* key, T* to) {\n  // copy array data if has_key\n  if (d.has_key(key)) {\n    bn::ndarray arr = bp::extract<bn::ndarray>(d[key]);\n    _copyarraydata<ndim,T>(arr, to);\n  }\n}\n\nvoid PyMJCWorld::SetModel(bp::dict d) {\n  _cadihk<1>(d, \"dof_armature\", m_model->dof_armature);\n  _cadihk<2>(d, \"jnt_limit\", m_model->jnt_limit);\n}\n\nbp::dict PyMJCWorld::GetModel() {\n  bp::dict out;\n  out[\"nqpos\"] = m_model->nqpos;\n  out[\"ndof\"] = m_model->ndof;\n  out[\"njnt\"] = m_model->njnt;\n  out[\"nbody\"] = m_model->nbody;\n  out[\"ngeom\"] = m_model->ngeom;\n  out[\"neqmax\"] = m_model->neqmax;\n  out[\"nlmax\"] = m_model->nlmax;\n  out[\"ncpair\"] = m_model->ncpair;\n  out[\"ncmax\"] = m_model->ncmax;\n  out[\"name\"] = bp::str(m_model->name);\n  out[\"timestep\"] = m_model->timestep;\n  out[\"gravity\"] = toNdarray1<mjtNum>(m_model->gravity,3);\n  out[\"viscosity\"] = m_model->viscosity;\n  out[\"mindist\"] = toNdarray1<mjtNum>(m_model->mindist,2);\n  out[\"erreduce\"] = toNdarray1<mjtNum>(m_model->errreduce, 3);\n\n  out[\"body_mass\"] = toNdarray1<mjtNum>(m_model->body_mass, m_model->nbody);\n  out[\"body_inertia\"] = toNdarray2<mjtNum>(m_model->body_inertia, m_model->nbody,3);\n  out[\"body_pos\"] = toNdarray2<mjtNum>(m_model->body_pos, m_model->nbody,3);\n  out[\"body_quat\"] = toNdarray2<mjtNum>(m_model->body_quat, m_model->nbody,4);\n  out[\"body_viscoef\"] = toNdarray1<mjtNum>(m_model->body_viscoef, m_model->nbody);\n  out[\"body_parent_id\"] = toNdarray1<int>(m_model->body_parent_id, m_model->nbody);\n  out[\"body_jnt_num\"] = toNdarray1<int>(m_model->body_jnt_num, m_model->nbody);\n  out[\"body_dof_num\"] = toNdarray1<int>(m_model->body_dof_num, m_model->nbody);\n  out[\"body_root_id\"] = toNdarray1<int>(m_model->body_root_id, m_model->nbody);\n\n  out[\"jnt_type\"] = toNdarray1<int>((int*)m_model->jnt_type, m_model->njnt);\n  out[\"jnt_pos\"] = toNdarray2<mjtNum>(m_model->jnt_pos, m_model->njnt,3);\n  out[\"jnt_axis\"] = toNdarray2<mjtNum>(m_model->jnt_axis, m_model->njnt,3);\n  out[\"jnt_spring\"] = toNdarray1<mjtNum>(m_model->jnt_spring, m_model->njnt);\n  out[\"jnt_damping\"] = toNdarray1<mjtNum>(m_model->jnt_damping, m_model->njnt);\n  out[\"jnt_vel_damping\"] = toNdarray1<mjtNum>(m_model->jnt_vel_damping, m_model->njnt);\n  out[\"jnt_body_id\"] = toNdarray1<int>(m_model->jnt_body_id, m_model->njnt);\n  out[\"jnt_limit\"] = toNdarray2<mjtNum>(m_model->jnt_limit, m_model->njnt,2);\n  out[\"jnt_islimited\"] = toNdarray1<mjtByte>(m_model->jnt_islimited, m_model->njnt);\n\n  out[\"dof_armature\"] = toNdarray1<mjtNum>(m_model->dof_armature, m_model->ndof);\n  out[\"dof_body_id\"] = toNdarray1<int>(m_model->dof_body_id, m_model->ndof);\n  out[\"dof_jnt_id\"] = toNdarray1<int>(m_model->dof_jnt_id, m_model->ndof);\n  out[\"dof_parent_id\"] = toNdarray1<int>(m_model->dof_parent_id, m_model->ndof);\n\n  out[\"geom_type\"] = toNdarray1<int>((int*)m_model->geom_type, m_model->ngeom);\n  out[\"geom_size\"] = toNdarray2<mjtNum>(m_model->geom_size, m_model->ngeom, mjNumSize);\n  out[\"geom_pos\"] = toNdarray2<mjtNum>(m_model->geom_pos, m_model->ngeom,3);\n  out[\"geom_quat\"] = toNdarray2<mjtNum>(m_model->geom_quat, m_model->ngeom,4);\n  out[\"geom_color\"] = toNdarray2<mjtNum>(m_model->geom_color, m_model->ngeom,3);\n  out[\"geom_body_id\"] = toNdarray1<int>(m_model->geom_body_id, m_model->ngeom);\n  out[\"geom_isoffset\"] = toNdarray1<mjtByte>(m_model->geom_isoffset, m_model->ngeom);\n\n  out[\"eq_body1\"] = toNdarray1<int>(m_model->eq_body1, m_model->neqmax);\n  out[\"eq_body2\"] = toNdarray1<int>(m_model->eq_body2, m_model->neqmax);\n  out[\"eq_pos1\"] = toNdarray2<mjtNum>(m_model->eq_pos1, m_model->neqmax, 3);\n  out[\"eq_pos2\"] = toNdarray2<mjtNum>(m_model->eq_pos2, m_model->neqmax, 3);\n  out[\"eq_enable\"] = toNdarray1<mjtByte>(m_model->eq_enable, m_model->neqmax);\n\n  out[\"pair_type\"] = toNdarray1<int>((int*)m_model->pair_type, m_model->ncpair);\n  out[\"pair_friction\"] = toNdarray1<mjtNum>(m_model->pair_friction, m_model->ncpair);\n  out[\"pair_geom1\"] = toNdarray1<int>(m_model->pair_geom1, m_model->ncpair);\n  out[\"pair_geom2\"] = toNdarray1<int>(m_model->pair_geom2, m_model->ncpair);\n  out[\"pair_enable\"] = toNdarray1<mjtByte>(m_model->pair_enable, m_model->ncpair);\n\n  return out;\n}\n\nbp::dict PyMJCWorld::GetData(const bn::ndarray& x) {\n  NOTIMPLEMENTED;\n}\n\nBOOST_PYTHON_MODULE(mjcpy) {\n    bn::initialize();\n\n    bp::enum_<ContactType>(\"ContactType\")\n      .value(\"NONE\",ContactType_SPRING)\n      .value(\"SLCP\",ContactType_SLCP)\n      .value(\"SPRING\",ContactType_SPRINGTAU)\n      .value(\"CONVEX\",ContactType_CONVEX)\n      ;\n\n    bp::class_<PyMJCWorld,boost::noncopyable>(\"MJCWorld\",\"docstring here\", bp::init<const std::string&>())\n\n        .def(\"Step\",&PyMJCWorld::Step)\n        .def(\"StepMulti\",&PyMJCWorld::StepMulti)\n        .def(\"StepMulti2\",&PyMJCWorld::StepMulti2)\n        .def(\"StepJacobian\", &PyMJCWorld::StepJacobian)\n        .def(\"Plot\",&PyMJCWorld::Plot)\n        .def(\"SetActuatedDims\",&PyMJCWorld::SetActuatedDims)\n        .def(\"ComputeContacts\", &PyMJCWorld::ComputeContacts)\n        .def(\"SetTimestep\",&PyMJCWorld::SetTimestep)\n        .def(\"SetContactType\",&PyMJCWorld::SetContactType)\n        .def(\"GetModel\",&PyMJCWorld::GetModel)\n        .def(\"SetModel\",&PyMJCWorld::SetModel)\n        .def(\"GetData\",&PyMJCWorld::GetData)\n        .def(\"GetImage\",&PyMJCWorld::GetImage)\n        ;\n}\n", "meta": {"hexsha": "7c499057ed52ecff39ea90134b018ff4b5d51c36", "size": 33776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/mjcpy/mjcpy.cpp", "max_stars_repo_name": "sfpd/rlreloaded", "max_stars_repo_head_hexsha": "650c64ec22ad45996c8c577d85b1a4f20aa1c692", "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/mjcpy/mjcpy.cpp", "max_issues_repo_name": "sfpd/rlreloaded", "max_issues_repo_head_hexsha": "650c64ec22ad45996c8c577d85b1a4f20aa1c692", "max_issues_repo_licenses": ["MIT"], "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/mjcpy/mjcpy.cpp", "max_forks_repo_name": "sfpd/rlreloaded", "max_forks_repo_head_hexsha": "650c64ec22ad45996c8c577d85b1a4f20aa1c692", "max_forks_repo_licenses": ["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.4415841584, "max_line_length": 154, "alphanum_fraction": 0.6039199432, "num_tokens": 11448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38491213037224875, "lm_q1q2_score": 0.19696592846353417}}
{"text": "#ifndef STAN_MCMC_HMC_HAMILTONIANS_BASE_HAMILTONIAN_HPP\n#define STAN_MCMC_HMC_HAMILTONIANS_BASE_HAMILTONIAN_HPP\n\n#include <stan/callbacks/logger.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/model/gradient.hpp>\n#include <stan/model/log_prob_propto.hpp>\n#include <Eigen/Dense>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n#include <vector>\n\nnamespace stan {\nnamespace mcmc {\n\ntemplate <class Model, class Point, class BaseRNG>\nclass base_hamiltonian {\n public:\n  explicit base_hamiltonian(const Model& model) : model_(model) {}\n\n  ~base_hamiltonian() {}\n\n  typedef Point PointType;\n\n  virtual double T(Point& z) = 0;\n\n  double V(Point& z) { return z.V; }\n\n  virtual double tau(Point& z) = 0;\n\n  virtual double phi(Point& z) = 0;\n\n  double H(Point& z) { return T(z) + V(z); }\n\n  // The time derivative of the virial, G = \\sum_{d = 1}^{D} q^{d} p_{d}.\n  virtual double dG_dt(Point& z, callbacks::logger& logger) = 0;\n\n  // tau = 0.5 p_{i} p_{j} Lambda^{ij} (q)\n  virtual Eigen::VectorXd dtau_dq(Point& z, callbacks::logger& logger) = 0;\n\n  virtual Eigen::VectorXd dtau_dp(Point& z) = 0;\n\n  // phi = 0.5 * log | Lambda (q) | + V(q)\n  virtual Eigen::VectorXd dphi_dq(Point& z, callbacks::logger& logger) = 0;\n\n  virtual void sample_p(Point& z, BaseRNG& rng) = 0;\n\n  void init(Point& z, callbacks::logger& logger) {\n    this->update_potential_gradient(z, logger);\n  }\n\n  void update_potential(Point& z, callbacks::logger& logger) {\n    try {\n      z.V = -stan::model::log_prob_propto<true>(model_, z.q);\n    } catch (const std::exception& e) {\n      this->write_error_msg_(e, logger);\n      z.V = std::numeric_limits<double>::infinity();\n    }\n  }\n\n  void update_potential_gradient(Point& z, callbacks::logger& logger) {\n    try {\n      stan::model::gradient(model_, z.q, z.V, z.g, logger);\n      z.V = -z.V;\n    } catch (const std::exception& e) {\n      this->write_error_msg_(e, logger);\n      z.V = std::numeric_limits<double>::infinity();\n    }\n    z.g = -z.g;\n  }\n\n  void update_metric(Point& z, callbacks::logger& logger) {}\n\n  void update_metric_gradient(Point& z, callbacks::logger& logger) {}\n\n  void update_gradients(Point& z, callbacks::logger& logger) {\n    update_potential_gradient(z, logger);\n  }\n\n protected:\n  const Model& model_;\n\n  void write_error_msg_(const std::exception& e, callbacks::logger& logger) {\n    logger.error(\n        \"Informational Message: The current Metropolis proposal \"\n        \"is about to be rejected because of the following issue:\");\n    logger.error(e.what());\n    logger.error(\n        \"If this warning occurs sporadically, such as for highly \"\n        \"constrained variable types like covariance matrices, \"\n        \"then the sampler is fine,\");\n    logger.error(\n        \"but if this warning occurs often then your model may be \"\n        \"either severely ill-conditioned or misspecified.\");\n    logger.error(\"\");\n  }\n};\n\n}  // namespace mcmc\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "a0405d539cc5ee5c239225d586b14ba82d5eb2cc", "size": 2946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/mcmc/hmc/hamiltonians/base_hamiltonian.hpp", "max_stars_repo_name": "Dr-G/stan", "max_stars_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "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/mcmc/hmc/hamiltonians/base_hamiltonian.hpp", "max_issues_repo_name": "Dr-G/stan", "max_issues_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "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/mcmc/hmc/hamiltonians/base_hamiltonian.hpp", "max_forks_repo_name": "Dr-G/stan", "max_forks_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "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.3269230769, "max_line_length": 77, "alphanum_fraction": 0.6680244399, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.19666720619014783}}
{"text": "\ufeff// MS WARNINGS MACRO\n#define _SCL_SECURE_NO_WARNINGS\n\n// Macro: Program Settings\n#define ENABLE_NETWORK_IO 1\n#define ENABLE_SAVE_IMAGE 0\n\n#include <iostream>\n#include <deque>\n#include <utility>\n#include <boost/noncopyable.hpp>\n#include <boost/optional.hpp>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/range/algorithm.hpp>\n#include \"data_type.hpp\"\n#include \"image_comparator.hpp\"\n#include \"ppm_reader.hpp\"\n#include \"splitter.hpp\"\n#include \"slide_algorithm/algorithm.hpp\"\n#include \"slide_algorithm/algorithm_2.hpp\"\n#include \"slide_algorithm/truncater.hpp\"\n#include \"slide_algorithm/charles.hpp\"\n#include \"gui.hpp\"\n#include \"network.hpp\"\n#include \"test_tool.hpp\"\n\n#include <image_algorithm/yrange2.hpp>\n#include <image_algorithm/yrange5.hpp>\n#include <image_algorithm/genetic.hpp>\n#include <image_algorithm/Murakami.hpp>\n\nclass position_manager : boost::noncopyable\n{\npublic:\n    typedef question_data position_type;\n\n    position_manager() = default;\n    virtual ~position_manager() = default;\n\n    template<class T>\n    void add(T && pos, bool const auto__ = false)\n    {\n        std::lock_guard<std::mutex> lock(mutex_);\n        items_.push_back(std::forward<T>(pos));\n        auto_.push_back(auto__);\n    }\n\n    std::pair<position_type,bool> get()\n    {\n        std::lock_guard<std::mutex> lock(mutex_);\n        auto res = items_.front(); auto res_b = auto_.front();\n        items_.pop_front();\n        auto_.pop_front();\n        return std::make_pair(res, res_b);\n    }\n\n    bool empty()\n    {\n        return items_.empty();\n    }\n\nprivate:\n    std::mutex mutex_;\n    std::deque<position_type> items_;\n    std::deque<bool>          auto_;\n};\n\nclass analyzer : boost::noncopyable\n{\npublic:\n    explicit analyzer(\n        boost::shared_ptr<network::client> const& network_client,\n        int const problem_id, std::string const& player_id,\n        bool const is_auto, bool const is_blur\n#if ENABLE_SAVE_IMAGE\n        ,std::string const& dir_path = \"./saved_image\"\n#endif\n        )\n        : client_(network_client), problem_id_(problem_id), player_id_(player_id)\n        , is_auto_(is_auto), is_blur_(is_blur)\n#if ENABLE_SAVE_IMAGE\n        , dir_path_(dir_path)\n#endif\n    {\n    }\n    virtual ~analyzer() = default;\n\n    void operator() (position_manager& manager)\n    {\n        splitter sp;\n\n        // \u554f\u984c\u6587\u306e\u5165\u624b\n        raw_data_ = get_raw_question();\n        data_     = get_skelton_question(raw_data_);\n\n        // 2\u6b21\u5143\u753b\u50cf\u306b\u5206\u5272\n        split_image_ = sp.split_image(raw_data_);\n\n        // compare\u7528\u306e\u753b\u50cf\u3092\u4f5c\u6210\n        auto const arranged_split = is_blur_ ? sp.split_image_gaussianblur(split_image_) : split_image_;\n        auto const image_comp    = comparator_   .image_comp(raw_data_, arranged_split);\n\t\tauto const image_comp_dx = comparator_dx_.image_comp(raw_data_, arranged_split);\n\n        // \u539f\u753b\u50cf\u63a8\u6e2c\u90e8\n        yrange2 yrange2_(raw_data_, image_comp);\n        Murakami murakami_(raw_data_, image_comp,true);\n\n        // GUI Thread\u306e\u8d77\u52d5\n        gui::manager gui_thread(\n            [this, &manager](std::vector<std::vector<point_type>> const& data)\n            {\n                // \u56de\u7b54\u3068\u3057\u3066\u30de\u30fc\u30af -> \u56de\u7b54\u30b8\u30e7\u30d6\u306b\u8ffd\u52a0\n                auto clone = data_.clone();\n                clone.block = data;\n                manager.add(convert_block(clone));\n            });\n\n        // YRange2 -> YRange5 Thread\n        boost::thread y_thread(\n            [&, this]()\n            {\n                // YRange2\n                auto yrange2_resolve = yrange2_();\n                if (!yrange2_resolve.empty())\n\t\t        {\n                    // Shoot\n                    if(is_auto_)\n                    {\n                        is_auto_ = false;\n\n                        std::cout << \"Yrange2 Auto\" << std::endl;\n                        auto clone = data_.clone();\n                        clone.block = yrange2_resolve[0].points;\n                        manager.add(convert_block(clone), true);\n                    }\n\n                    // GUI\n\t\t\t        for (int y2 = yrange2_resolve.size() - 1; y2 >= 0; --y2)\n\t\t\t        {\n                        gui_thread.push_back(\n                            boost::bind(gui::make_mansort_window, split_image_, yrange2_resolve.at(y2).points, \"yrange2\")\n                            );\n\t\t\t        }\n\t\t        }\n                \n                // YRange5\n\t\t\t\tif (raw_data_.split_num.first > 3 || raw_data_.split_num.second > 3){\n\t\t\t\t\tauto yrange5_resolve = yrange5(raw_data_, image_comp)(yrange2_.sorted_matrix());\n\t\t\t\t\tif (!yrange5_resolve.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\t// Shoot\n\t\t\t\t\t\tif(is_auto_)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tis_auto_ = false;\n\n                            std::cout << \"Yrange5 Auto\" << std::endl;\n\t\t\t\t\t\t\tauto clone = data_.clone();\n\t\t\t\t\t\t\tclone.block = yrange5_resolve[0].points;\n\t\t\t\t\t\t\tmanager.add(convert_block(clone), true);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// GUI\n\t\t\t\t\t\tfor (int y5 = yrange5_resolve.size() - 1; y5 >= 0; --y5)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tgui_thread.push_back(\n\t\t\t\t\t\t\t\tboost::bind(gui::make_mansort_window, split_image_, yrange5_resolve.at(y5).points, \"yrange5\")\n\t\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            });\n\n        // Murakami Thread\n        boost::thread m_thread(\n            [&]()\n            {\n                // Murakami\n\t\t    \tstd::cout << \"\u6751\u4e0a\u30e2\u30fc\u30c9\" << std::endl;\n                auto murakami_resolve = murakami_()[0].points;\n\t\t\t\tstd::vector<std::vector<point_type>> murakami_dx_resolve, murakami_w_resolve, murakami_dx_w_resolve;\n\t\t\t\tif (!murakami_resolve.empty())\n\t\t\t\t{\n\t\t\t\t\tif(is_auto_)\n\t\t\t\t\t{\n\t\t\t\t\t\tis_auto_ = false;\n\n                        std::cout << \"Murakami Auto\" << std::endl;\n\t\t\t\t\t\tauto clone = data_.clone();\n\t\t\t\t\t\tclone.block = murakami_resolve;\n\t\t\t\t\t\tmanager.add(convert_block(clone), true);\n\t\t\t\t\t}\n\t\t\t\t\tgui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_resolve, \"Murakami\"));\n                }\n\t\t\t\tif (murakami_resolve.empty()){\n\t\t\t\t\tstd::cout << \"\u30c7\u30e9\u30c3\u30af\u30b9\u6751\u4e0a\u30e2\u30fc\u30c9\" << std::endl;\n\t\t\t\t\tMurakami murakami_dx(raw_data_, image_comp_dx, true);\n\t\t\t\t\tmurakami_dx_resolve = murakami_dx()[0].points;\n\t\t\t\t\tif (!murakami_dx_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_dx_resolve, \"Murakami_dx\"));\n\t\t\t\t\tif (murakami_dx_resolve.empty()){\n\t\t\t\t\t\tstd::cout << \"W\u6751\u4e0a\u30e2\u30fc\u30c9\" << std::endl;\n\t\t\t\t\t\tMurakami murakami_w(raw_data_, image_comp, false);\n\t\t\t\t\t\tmurakami_w_resolve = murakami_w()[0].points;\n\t\t\t\t\t\tif (!murakami_w_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_w_resolve, \"Murakami_w\"));\n\t\t\t\t\t\tif (murakami_w_resolve.empty()){\n\t\t\t\t\t\t\tstd::cout << \"\u30c7\u30e9\u30c3\u30af\u30b9W\u6751\u4e0a\u30e2\u30fc\u30c9\" << std::endl;\n\t\t\t\t\t\t\tMurakami murakami_dx_w(raw_data_, image_comp_dx, false);\n\t\t\t\t\t\t\tmurakami_dx_w_resolve = murakami_w()[0].points;\n\t\t\t\t\t\t\tif (!murakami_dx_w_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_dx_w_resolve, \"Murakami_dx_w\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n            });\n\n        gui_thread.push_back(\n            boost::bind(gui::make_mansort_window, split_image_, \"Yor are the sorter!!! Sort this!\")\n            );\n\n        // \u5404Thread\u306e\u5f85\u6a5f\n        y_thread.join();\n        m_thread.join();\n        gui_thread.wait_all_window();\n    }\n\n    int calc_cost(answer_type const& ans) const\n    {\n        int cost = (timer_.elapsed().wall / 1000000000) * 100;\n        cost += ans.list.size() * data_.cost_select;\n        boost::for_each(\n            ans.list,\n            [&,this](answer_atom const& move)\n            {\n                cost += move.actions.size() * data_.cost_change;\n            });\n \n        return cost;\n    }\n\n    std::string submit(answer_type const& ans, bool is_auto = false) const\n    {\n        std::lock_guard<std::mutex> lock(submit_mutex_);\n        int const cost = calc_cost(ans);\n\n\tif(is_auto)\n\t{\n            auto submit_result = client_->submit(problem_id_, player_id_, ans);\n            return submit_result.get();\n\t}\n\t\n        char input;\n        std::cout << \"\u2605Submit: Cost = \" << cost << \" [Y/n]\u2605\";\n        std::cin.get(input);\n\n        if(input == '\\n' || input == 'y' || input == 'Y')\n        {\n            auto submit_result = client_->submit(problem_id_, player_id_, ans);\n            return submit_result.get();\n        }\n\n        return std::string();\n    }\n\nprivate:\n    question_raw_data get_raw_question() const\n    {\n#if ENABLE_NETWORK_IO\n        // \u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u901a\u4fe1\u304b\u3089\n        std::string const data = client_->get_problem(problem_id_).get();\n        timer_.start();\n#if ENABLE_SAVE_IMAGE\n        std::ofstream ofs((boost::format(\"%s/prob%02d.ppm\") % dir_path_ % problem_id_).str(), std::ios::binary);\n        ofs << data;\n        ofs.close();\n#endif\n        return ppm_reader().from_data(data);\n#else\n        // \u30d5\u30a1\u30a4\u30eb\u304b\u3089\n        std::string const path(\"prob01.ppm\");\n        timer_.start();\n        return ppm_reader().from_file(path);\n#endif\n    }\n\n    question_data get_skelton_question(question_raw_data const& raw) const\n    {\n        question_data formed = {\n            problem_id_,\n            player_id_,\n            raw.split_num,\n            raw.selectable_num,\n            raw.cost.first,\n            raw.cost.second,\n            std::vector<std::vector<point_type>>()\n        };\n\n        return formed;\n    }\n\n    question_data convert_block(question_data const& data) const\n    {\n        auto res = data.clone();\n\n        for(int i = 0; i < data.size.second; ++i)\n        {\n            for(int j = 0; j < data.size.first; ++j)\n            {\n                auto const& target = data.block[i][j];\n                res.block[target.y][target.x] = point_type{j, i};\n\t\t}\n        }\n\n        return res;\n    }\n\n    int const problem_id_;\n    std::string const player_id_;\n    bool is_auto_;\n    bool const is_blur_;\n\n    question_raw_data raw_data_;\n    question_data         data_;\n    split_image_type  split_image_;\n\tsplit_image_type  split_image_gaussianblur;\n\n    mutable boost::shared_ptr<network::client> client_;\n    image_comparator    comparator_;\n\timage_comparator_dx comparator_dx_;\n\n    // \u9001\u4fe1\u7528mutex\n    mutable boost::timer::cpu_timer timer_;\n    mutable std::mutex submit_mutex_;\n\n#if ENABLE_SAVE_IMAGE\n    mutable std::string dir_path_;\n#endif\n};\n\nvoid submit_func(question_data question, analyzer const& analyze, bool is_auto)\n{\n    algorithm algo;\n    truncater talgo;\n\n    algorithm_2 algo2;\n\tcharles algo3;\n\n    boost::optional<answer_type> algo_answer;\n    boost::optional<answer_type> talgo_answer;\n    boost::optional<answer_type> answer;\n\n    auto algo_thread = boost::thread(\n        [&algo, &algo_answer, &question]() {\n            algo.reset(question);\n            algo_answer = algo.get();\n        }\n    );\n\n    auto talgo_thread = boost::thread(\n        [&talgo, &talgo_answer, &question]() {\n            talgo.reset(question);\n            talgo_answer = talgo.get();\n        }\n    );\n\n    algo_thread.join();\n    talgo_thread.join();\n\n    int algo_score = algo_answer->get_score(question.cost_select, question.cost_change);\n    int talgo_score = talgo_answer->get_score(question.cost_select, question.cost_change);\n    if (algo_score < talgo_score) {\n        answer = algo_answer;\n    } else {\n        answer = talgo_answer;\n    }\n\n    if(answer) // \u89e3\u304c\u898b\u3064\u304b\u3063\u305f\n    {\n#if ENABLE_NETWORK_IO\n        // TODO: \u524d\u3088\u308a\u826f\u304f\u306a\u3063\u305f\u3089\u63d0\u51fa\u306a\u3069(\u666e\u901a\u306b\u3044\u3089\u306a\u3044\u304b\u3082\uff0e\u63d0\u51fa\u524d\u306b\u76eegrep\u3057\u3066\u308b\u308f\u3051\u3060\u3057)\n\t\tstd::cout << \"Submit! Wait 5 sec\" << std::endl;\n\n        std::string result;\n\n        result = analyze.submit(answer.get(), is_auto);\n        std::cout << \"Submit Result: \" << result << std::endl;\n\n        if(result.find(\"ACCEPTED\") == std::string::npos)\n        {\n            std::cout << \"Submit Result is not \\\"ACCEPTED\\\"\" << std::endl;\n            return;\n        }\n\n\t// FIXME: \u6c5a\u3044\u3057\u30bb\u30b0\u30d5\u30a9\u3059\u308b//\u30bb\u30b0\u30d5\u30a9\u306f\u3057\u306a\u304f\u306a\u3063\u305f\u3089\u3057\u3044\n\tint wrong_number = std::stoi(result.substr(result.find(\" \")));\n\tif (wrong_number == 0)\n\t{\n\t\talgo2.reset(question);\n\t\tauto const answer = algo2.get();\n\t\tif (algo2.overlimitcheck()){\n\t\t\tif (answer)\n\t\t\t{\n\t\t\t\tresult = analyze.submit(answer.get());\n\t\t\t\tstd::cout << \"Submit Result: \" << result << std::endl;\n\t\t\t\tstd::cout << \"\u52dd\u3063\u305f\uff01\" << std::endl;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tstd::cout << \"algo2\u306f\u7b54\u3048\u3092\u8fd4\u3057\u307e\u305b\u3093\u3067\u3057\u305f\" << std::endl;\n\t\t}\n\n\t\talgo3.reset(question);\n\t\tauto const answer2 = algo3.get();\n\t\tif (algo3.overlimitcheck()){\n\t\t\tif (answer2)\n\t\t\t{\n\t\t\t\tresult = analyze.submit(answer2.get());\n\t\t\t\tstd::cout << \"Submit Result 2 : \" << result << std::endl;\n\t\t\t\tstd::cout << \"\u3055\u3089\u306b\u52dd\u3063\u305f\uff01\" << std::endl;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tstd::cout << \"algo3\u306f\u7b54\u3048\u3092\u8fd4\u3057\u307e\u305b\u3093\u3067\u3057\u305f\" << std::endl;\n\t\t}\n\t}\n#else\n        test_tool::emulator emu(question);\n        auto result = emu.start(answer.get());\n        std::cout << \"Wrong: \" << result.wrong << std::endl;\n        std::cout << \"Cost : \" << result.cost  << std::endl;\n        std::cout << \"---\" << std::endl;\n#endif\n    }\n}\n\nint main(int const argc, char const* argv[])\n{\n    std::string server_addr;\n\tint         problemid = 0;\n    auto const  token = \"1\";//\"3935105806\";\n    bool        is_auto;\n    bool        is_blur;\n    std::string url_format;\n#if ENABLE_SAVE_IMAGE\n    std::string save_dir;\n#endif\n\n    try\n    {\n        namespace po = boost::program_options;\n        po::options_description opt(\"option\");\n        opt.add_options()\n            (\"help,h\"    , \"produce help message\")\n            (\"auto,a\"    , \"auto submit flag\")\n            (\"blur,b\"    , \"gaussian blur to image\")\n#if ENABLE_SAVE_IMAGE\n            (\"save_dir\"  , po::value<std::string>(&save_dir)   , \"(require)set image dir to save\")\n#endif\n#if ENABLE_NETWORK_IO\n            (\"prob_format,f\", po::value<std::string>(&url_format)->default_value(\"/problem/prob%02d.ppm\"), \"set problem format(ex. /problem/prob%02d.ppm)\")\n            (\"server,s\"  , po::value<std::string>(&server_addr), \"(require)set server ip address\")\n            (\"problem,p\" , po::value<int>(&problemid)          , \"(require)set problem_id\")\n#endif\n            ;\n\n        po::variables_map argmap;\n        po::store(po::parse_command_line(argc, argv, opt), argmap);\n        po::notify(argmap);\n\n#if ENABLE_NETWORK_IO\n        if(argmap.count(\"help\") || !argmap.count(\"server\") || !argmap.count(\"problem\"))\n#else\n        if(argmap.count(\"help\"))\n#endif\n        {\n            std::cout << opt << std::endl;\n            return 0;\n        }\n\n        is_auto = argmap.count(\"auto\");\n        is_blur = argmap.count(\"blur\");\n    }\n    catch(boost::program_options::error_with_option_name const& e)\n    {\n        std::cout << e.what() << std::endl;\n        std::exit(-1);\n    }\n\n    auto             network_client = boost::make_shared<network::client>(server_addr, url_format/*, submit_path*/);\n\n#if ENABLE_SAVE_IMAGE\n    if(save_dir.empty()) save_dir = \"./saved_image\";\n    analyzer         analyze(network_client, problemid, token, is_auto, is_blur, save_dir);\n#else\n    analyzer         analyze(network_client, problemid, token, is_auto, is_blur);\n#endif\n    position_manager manager;\n\n    boost::thread thread(boost::bind(&analyzer::operator(), &analyze, std::ref(manager)));\n    boost::thread_group submit_threads;\n\n    while(thread.joinable())\n    {\n        if(!manager.empty())\n        {\n            auto question = manager.get();\n\n            // \u624b\u9806\u63a2\u7d22\u90e8\n            submit_threads.create_thread(\n                boost::bind(submit_func, question.first, boost::ref(analyze), question.second)\n                );\n        }\n    }\n\n    thread.join();\n    submit_threads.join_all();\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "11e5a0fca6af24918a7e7c221667c8ee6944ab1c", "size": 15253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "resolver/src/main.cpp", "max_stars_repo_name": "tnct-spc/procon2014", "max_stars_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-02T08:42:05.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-02T08:42:05.000Z", "max_issues_repo_path": "resolver/src/main.cpp", "max_issues_repo_name": "tnct-spc/procon2014", "max_issues_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resolver/src/main.cpp", "max_forks_repo_name": "tnct-spc/procon2014", "max_forks_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_forks_repo_licenses": ["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.3892100193, "max_line_length": 156, "alphanum_fraction": 0.587687668, "num_tokens": 3922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19666720430304876}}
{"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#include <nt2/combinatorial/include/functions/factorial.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/bench/benchmark.hpp>\n#include <nt2/sdk/bench/timing.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <cmath>\n\nusing nt2::tag::factorial_;\n\n#define RS(T,V1,V2) (T, (V1) ,(V2))\n\n\n#undef RS\n", "meta": {"hexsha": "4eb6dd5fc0efe4ce6a975c4f179c8b1800c915cd", "size": 827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/combinatorial/bench/simd/factorial.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": "modules/core/combinatorial/bench/simd/factorial.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": "modules/core/combinatorial/bench/simd/factorial.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": 37.5909090909, "max_line_length": 80, "alphanum_fraction": 0.5344619105, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1966671988077544}}
{"text": "#include \"fixtures.h\"\n#include \"geometric/coordinate.hpp\"\n#include \"id/line.hpp\"\n#include \"id/stop.hpp\"\n#include \"service/master.hpp\"\n\n#include \"test/toolkit.hpp\"\n\n#include <vector>\n\nusing namespace nepomuk;\n\n// make sure we get a new main function here\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(annotate_stops)\n{\n    service::Master data_service(TRANSIT_THREE_LINES_EXAMPLE_FIXTURE);\n\n    auto const &geometry_annotation = data_service.geometry_annotation();\n\n    // construct once\n    BOOST_CHECK(&geometry_annotation == &data_service.geometry_annotation());\n\n    BOOST_CHECK_EQUAL(geometry_annotation.get(StopID{0}), make_coordinate(0.005, 0.0051));\n    BOOST_CHECK_EQUAL(geometry_annotation.get(StopID{1}), make_coordinate(0.005, 0.0049));\n    BOOST_CHECK_EQUAL(geometry_annotation.get(StopID{2}), make_coordinate(0.0152, 0.005));\n    BOOST_CHECK_EQUAL(geometry_annotation.get(StopID{3}), make_coordinate(0.0253, 0.005));\n    BOOST_CHECK_EQUAL(geometry_annotation.get(StopID{4}), make_coordinate(0.0354, 0.005));\n    BOOST_CHECK_EQUAL(geometry_annotation.get(StopID{5}), make_coordinate(0.0455, 0.005));\n    BOOST_CHECK_EQUAL(geometry_annotation.get(StopID{6}), make_coordinate(0.0253, -0.104));\n}\n\nBOOST_AUTO_TEST_CASE(annotate_lines)\n{\n    service::Master data_service(TRANSIT_THREE_LINES_EXAMPLE_FIXTURE);\n\n    auto const &geometry_annotation = data_service.geometry_annotation();\n\n    std::vector<geometric::WGS84Coordinate> expected_coordinates;\n    expected_coordinates.push_back(make_coordinate(0.005, 0.005));\n    expected_coordinates.push_back(make_coordinate(0.0051, 0.005));\n    expected_coordinates.push_back(make_coordinate(0.0052, 0.005));\n    expected_coordinates.push_back(make_coordinate(0.00525, 0.005));\n    expected_coordinates.push_back(make_coordinate(0.0053, 0.005));\n    expected_coordinates.push_back(make_coordinate(0.00535, 0.005));\n    expected_coordinates.push_back(make_coordinate(0.0054, 0.005));\n    expected_coordinates.push_back(make_coordinate(0.00545, 0.005));\n    expected_coordinates.push_back(make_coordinate(0.0055, 0.005));\n\n    auto const range = geometry_annotation.get(LineID{0}, StopID{0}, StopID{5});\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        range.begin(), range.end(), expected_coordinates.begin(), expected_coordinates.end());\n}\n", "meta": {"hexsha": "2a388485bd1f817c000578ff3ec4b6652c764f5d", "size": 2323, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/annotation/geometry.cc", "max_stars_repo_name": "mapbox/nepomuk", "max_stars_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-12T11:52:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T06:05:08.000Z", "max_issues_repo_path": "test/annotation/geometry.cc", "max_issues_repo_name": "mapbox/nepomuk", "max_issues_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2017-05-11T16:13:58.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-13T11:19:17.000Z", "max_forks_repo_path": "test/annotation/geometry.cc", "max_forks_repo_name": "mapbox/nepomuk", "max_forks_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T12:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:14:25.000Z", "avg_line_length": 41.4821428571, "max_line_length": 94, "alphanum_fraction": 0.7709857942, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.37022538564692026, "lm_q1q2_score": 0.19666719511655778}}
{"text": "//\n// Created by nvidia on 6/22/18.\n//\n\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <opencv2/ximgproc.hpp>\n#include <algorithm> // for copy\n#include <iterator> // for ostream_iterator\n#include <boost/graph/graph_utility.hpp>\n#include \"../lib/SpVec.hpp\"\n#include \"../lib/superpixel_seg.hpp\"\n#include \"../lib/distance.hpp\"\n#include \"../lib/FloodFillSsdSuperpixelAlgorithm.hpp\"\n#include \"../lib/RTreesClassifier.hpp\"\n#include \"../lib/util.hpp\"\n\nusing namespace cv;\nusing namespace std;\nusing namespace cv::ximgproc;\nusing namespace cove;\n\nint main(int argc, char** argv) {\n    bool fastFinish = false;\n#ifdef DEBUG\n    namedWindow(\"params\", 1);\n#endif\n    ALGORITHM_PARAM(blurKernel, 3, 10)\n    ALGORITHM_PARAM(iterations, 10, 20)\n    ALGORITHM_PARAM(blurDev, 0, 100)\n    ALGORITHM_PARAM(regionSize, 7, 50)\n    ALGORITHM_PARAM(ratio, 70, 200)\n    ALGORITHM_PARAM(cannyLow, 70, 150)\n    ALGORITHM_PARAM(ssdEpsilonSlider, 10, 250)\n\n    int frameno = 0;\n    Mat frame;\n    Mat label;\n\n    RTreesClassifier classifier;\n//    Ptr<ml::RTrees> model;\n//    model = ml::StatModel::load<ml::RTrees>(\"RTREES\");\n    if( classifier.loadModelFromPath(\"RTREES\") ) {\n        cout << \"The classifier \" << \"RTREES\" << \" is loaded.\\n\";\n    } else {\n        cout << \"Could not read the classifier \" << \"RTREES\" << endl;\n        return 1;\n    }\n\n    FloodFillSsdSuperpixelAlgorithm algorithm(80, 60, regionSize, static_cast<float>(ssdEpsilonSlider) / 10, blurKernel, blurDev, iterations,\n                                              static_cast<float>(ratio) / 1000, cannyLow, cannyLow*2.5);\n\n    vector<double> ius;\n    for (int idx = static_cast<int>(argc*0.8); idx < argc; idx++) {\n        clock_t start=CLOCK();\n\n#ifdef DEBUG\n        if (blurKernel % 2 == 0) {\n            blurKernel++;\n        }\n#endif\n\n        string path(argv[idx]);\n        string filename = util::getFileName(path, true);\n        string labelPath = \"img/labels/\" + filename;\n        frame = imread(path);\n        label = imread(labelPath);\n        SHOW_ALWAYS(\"frame\", frame)\n        SHOW_ALWAYS(\"label\", label)\n        if (frame.empty() || label.empty()) {\n            cout << \"frame empty\" << endl;\n            break;\n        }\n\n        Mat floorMask;\n        Mat resizedLabel;\n        Mat sizedFrame;\n\n\n\n\n        Mat coloredSizedFrame;\n        auto super = algorithm.getSuperPixels(frame, floorMask, sizedFrame);\n        cvtColor(sizedFrame, coloredSizedFrame, COLOR_BGR2Lab);\n        super->iterate(iterations);\n        super->enforceLabelConnectivity(15);\n        Mat spxLabels;\n        // floor inference\n        super->getLabels(spxLabels);\n        cout << \"t\" << endl;\n        classifier.getFloorMask(spxLabels, coloredSizedFrame, super->getNumberOfSuperpixels(), floorMask);\n        cout << \"t\" << endl;\n\n//\n//\n//        Mat pxSamples = Mat::zeros(0, 10, CV_32F);\n//        for (int i = 0; i < super->getNumberOfSuperpixels(); i++) {\n//            Mat mask;\n//            inRange(spxLabels, Scalar(i), Scalar(i), mask);\n//            pxSamples.push_back(RTreesClassifier::getData(mask, coloredSizedFrame));\n//            // inference\n//        }\n//        Mat labels;\n//        model->predict(pxSamples, labels);\n//        cout << labels.size() << endl;\n//        cout << labels.depth() << endl;\n//        // compute floorMask\n//        Mat temp;\n//        floorMask = Mat::zeros(sizedFrame.size(), CV_8U);\n//        for (int i = 0; i < super->getNumberOfSuperpixels(); i++) {\n//            if (labels.at<float>(0, i) > 2.5) {\n//                continue;\n//            }\n//            inRange(spxLabels, Scalar(i), Scalar(i), temp);\n//            bitwise_or(floorMask, temp, floorMask);\n//        }\n\n        dilate(floorMask, floorMask, Mat(), Point(-1, -1), 2);\n        erode(floorMask, floorMask, Mat(), Point(-1, -1), 2);\n        resize(label, resizedLabel, floorMask.size(), 0, 0, INTER_NEAREST);\n        SHOW_ALWAYS(\"resize\", resizedLabel)\n        SHOW_ALWAYS(\"calced floor\", floorMask)\n        util::overlayMask(sizedFrame, floorMask, Scalar(0, 0, 255), sizedFrame);\n        SHOW_ALWAYS(\"display\", sizedFrame);\n\n        // get labeled floor mask\n        Mat tmp;\n        inRange(resizedLabel, Scalar(0,0,255), Scalar(0,0,255), tmp);\n        inRange(resizedLabel, Scalar(0,255,0), Scalar(0,255,0), resizedLabel);\n        bitwise_or(tmp, resizedLabel, resizedLabel);\n\n        // iu calculation\n        bitwise_and(resizedLabel, floorMask, tmp);\n        SHOW_ALWAYS(\"TRUE POS\", tmp);\n        int truePositive = countNonZero(tmp);\n        bitwise_xor(resizedLabel, floorMask, tmp);\n        SHOW_ALWAYS(\"FALSE *\", tmp);\n        int falsePosandNeg = countNonZero(tmp);\n        double iu = truePositive / static_cast<double>(falsePosandNeg + truePositive);\n        ius.push_back(iu);\n        cout << \"IU: \" << iu << endl;\n\n\n//        true positive / (true positive + false positive + false negative)\n\n\n\n        // mask the floor and etc\n\n//        Mat zeros(floorMask.size(), CV_8UC3, Scalar(0));\n//        Mat red(floorMask.size(), CV_8UC3, Scalar(0, 0, 255));\n//        red.copyTo(zeros, floorMask);\n//        addWeighted(resized, 0.7, zeros, 0.3, 0.0, resized);\n\n//        SHOW_ALWAYS(\"output\", resized);\n        // =========== time fps and exit ===========\n        double dur = CLOCK()-start;\n        printf(\"avg time per frame %f ms. fps %f. frameno = %d\\n\",avgdur(dur),avgfps(),frameno++ );\n        cout << argv[idx] << endl;\n        if (fastFinish) {\n            continue;\n        }\n        int key = waitKey(1000);\n        if (key == 27) {\n            break;\n        } else if (key == 99) {\n            fastFinish = true;\n        }\n\n    }\n    double sum = std::accumulate(ius.begin(), ius.end(), 0.0);\n    double mean = sum / ius.size();\n    std::vector<double> diff(ius.size());\n    std::transform(ius.begin(), ius.end(), diff.begin(), [mean](double x) { return x - mean; });\n    double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);\n    double stdev = std::sqrt(sq_sum / ius.size());\n\n    cout << \"MEAN: \" << mean << endl;\n    cout << \"STDV: \" << stdev << endl;\n\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "353df0475878acb04d0d2dac7d6de296c0899133", "size": 6096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "superpixel-seg/exe/superpixel_evaluate.cpp", "max_stars_repo_name": "NVIDIA-Jetson/Foursee-Navigation", "max_stars_repo_head_hexsha": "673b4a8bcf5774cf23d2564bada68709d28c850e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T06:05:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T02:48:03.000Z", "max_issues_repo_path": "superpixel-seg/exe/superpixel_evaluate.cpp", "max_issues_repo_name": "NVIDIA-Jetson/Foursee-Navigation", "max_issues_repo_head_hexsha": "673b4a8bcf5774cf23d2564bada68709d28c850e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-03T18:54:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-03T18:55:37.000Z", "max_forks_repo_path": "superpixel-seg/exe/superpixel_evaluate.cpp", "max_forks_repo_name": "NVIDIA-Jetson/Foursee-Navigation", "max_forks_repo_head_hexsha": "673b4a8bcf5774cf23d2564bada68709d28c850e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-12-17T10:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T06:45:28.000Z", "avg_line_length": 32.7741935484, "max_line_length": 141, "alphanum_fraction": 0.5825131234, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.3276683139517237, "lm_q1q2_score": 0.19666270773224281}}
{"text": "#include <iostream>\n#include <string>\n\n#include <Eigen/Eigen>\n\n#include <ros/ros.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <tms_msg_ss/SkeletonArray.h>\n#include <tms_msg_ss/CameraPosture.h>\n#include <tms_msg_ss/SkeletonStreamWrapper.h>\n\n<<<<<<< HEAD\nstatic const float marker_color[][3] = {  // BGR\n    {1.0f, 0, 0},\n    {0, 1.0f, 0},\n    {0, 0, 1.0f},\n    {1.0f, 1.0f, 0},\n    {1.0f, 0, 1.0f},\n    {0, 1.0f, 1.0f}};\n\nclass SkeletonViewer\n{\npublic:\n  SkeletonViewer();\n  ~SkeletonViewer();\n  void callback_skeleton(const tms_msg_ss::SkeletonArray::ConstPtr &msg);\n  void run();\n\nprivate:\n  ros::NodeHandle _nh;\n  ros::Publisher *_pmarker_array_pub;\n  bool gotCameraPosture;\n  Eigen::Vector3f translation;\n  Eigen::Quaternionf rotation;\n\n  inline void toWorldPoint(Eigen::Vector3f &vec);\n};\n\nSkeletonViewer::SkeletonViewer() : gotCameraPosture(false)\n=======\nstatic const float marker_color[][3] = { // BGR\n  {1.0f, 0, 0},\n  {0, 1.0f, 0},\n  {0, 0, 1.0f},\n  {1.0f, 1.0f, 0},\n  {1.0f, 0, 1.0f},\n  {0, 1.0f, 1.0f}\n};\n\nclass SkeletonViewer\n{\n  public:\n    SkeletonViewer();\n    ~SkeletonViewer();\n    void callback_skeleton(const tms_msg_ss::SkeletonArray::ConstPtr& msg);\n    void run();\n  private:\n    ros::NodeHandle _nh;\n    ros::Publisher *_pmarker_array_pub;\n    bool gotCameraPosture;\n    Eigen::Vector3f translation;\n    Eigen::Quaternionf rotation;\n\n    inline void toWorldPoint(Eigen::Vector3f &vec);\n};\n\nSkeletonViewer::SkeletonViewer() :\n  gotCameraPosture(false)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n{\n}\n\nSkeletonViewer::~SkeletonViewer()\n{\n}\n\ninline void SkeletonViewer::toWorldPoint(Eigen::Vector3f &vec)\n{\n  vec = this->rotation.matrix() * vec + this->translation;\n  return;\n}\n\n<<<<<<< HEAD\ntemplate < class T >\nstd::string to_str(const T &t)\n=======\ntemplate <class T>\nstd::string to_str(const T& t)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n{\n  std::stringstream ss;\n  ss << t;\n  return ss.str();\n}\n\n<<<<<<< HEAD\nvoid SkeletonViewer::callback_skeleton(const tms_msg_ss::SkeletonArray::ConstPtr &msg)\n=======\nvoid SkeletonViewer::callback_skeleton(const tms_msg_ss::SkeletonArray::ConstPtr& msg)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n{\n  visualization_msgs::MarkerArray marker_array;\n  for (int j = 0; j < msg->data.size(); j++)\n  {\n    tms_msg_ss::Skeleton skeleton = msg->data[j];\n    ROS_INFO(\"Received skeleton %d\", skeleton.user_id);\n\n    uint32_t shape = visualization_msgs::Marker::SPHERE;\n    for (int i = 0; i < 25; i++)\n    {\n      visualization_msgs::Marker marker;\n      marker.header.frame_id = \"/world_link\";\n      marker.header.stamp = ros::Time::now();\n      std::string name(\"skeleton\");\n<<<<<<< HEAD\n      marker.ns = name.append(to_str< int >(j + 1));\n=======\n      marker.ns = name.append(to_str<int>(j+1));\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      marker.id = i;\n      marker.type = shape;\n      marker.action = visualization_msgs::Marker::ADD;\n      Eigen::Vector3f pos(skeleton.position[i].x, skeleton.position[i].y, skeleton.position[i].z);\n      if (gotCameraPosture)\n      {\n        this->toWorldPoint(pos);\n      }\n      marker.pose.position.x = pos.x();\n      marker.pose.position.y = pos.y();\n      marker.pose.position.z = pos.z();\n      marker.pose.orientation.x = skeleton.orientation[i].x;\n      marker.pose.orientation.y = skeleton.orientation[i].y;\n      marker.pose.orientation.z = skeleton.orientation[i].z;\n      marker.pose.orientation.w = skeleton.orientation[i].w;\n      marker.scale.x = 0.05;\n      marker.scale.y = 0.05;\n      marker.scale.z = 0.05;\n<<<<<<< HEAD\n      marker.color.r = marker_color[j / 6][2];\n      marker.color.g = marker_color[j / 6][1];\n      marker.color.b = marker_color[j / 6][0];\n      marker.color.a = 1.0f * (float)skeleton.confidence[i] / 2.0f;\n=======\n      marker.color.r = marker_color[j/6][2];\n      marker.color.g = marker_color[j/6][1];\n      marker.color.b = marker_color[j/6][0];\n      marker.color.a = 1.0f*(float)skeleton.confidence[i]/2.0f;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      marker.lifetime = ros::Duration();\n      marker_array.markers.push_back(marker);\n    }\n  }\n  _pmarker_array_pub->publish(marker_array);\n\n  return;\n}\n\nvoid SkeletonViewer::run()\n{\n  ros::Subscriber sub_skeleton =\n<<<<<<< HEAD\n      this->_nh.subscribe(\"integrated_skeleton_stream\", 1, &SkeletonViewer::callback_skeleton, this);\n  ros::Publisher marker_pub = _nh.advertise< visualization_msgs::MarkerArray >(\"skeleton_visualization\", 1);\n=======\n    this->_nh.subscribe(\"integrated_skeleton_stream\", 1, &SkeletonViewer::callback_skeleton, this);\n  ros::Publisher marker_pub = _nh.advertise<visualization_msgs::MarkerArray>(\n      \"skeleton_visualization\", 1);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  _pmarker_array_pub = &marker_pub;\n  ros::spin();\n  return;\n}\n\n<<<<<<< HEAD\nint main(int argc, char **argv)\n=======\nint main (int argc, char **argv)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n{\n  ros::init(argc, argv, \"skeleton_viewer\");\n\n  SkeletonViewer viewer;\n\n  viewer.run();\n\n  return 0;\n}\n", "meta": {"hexsha": "c5b0104293382441f683bf7d5c408f1df753e8b1", "size": 5057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tms_ss/tms_ss_kinect_v2/skeleton_viewer/main.cpp", "max_stars_repo_name": "SigmaHayashi/ros_tms_for_smart_previewed_reality", "max_stars_repo_head_hexsha": "4ace908bd3da0519246b3c45d0230cbd02e49da0", "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": "tms_ss/tms_ss_kinect_v2/skeleton_viewer/main.cpp", "max_issues_repo_name": "SigmaHayashi/ros_tms_for_smart_previewed_reality", "max_issues_repo_head_hexsha": "4ace908bd3da0519246b3c45d0230cbd02e49da0", "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": "tms_ss/tms_ss_kinect_v2/skeleton_viewer/main.cpp", "max_forks_repo_name": "SigmaHayashi/ros_tms_for_smart_previewed_reality", "max_forks_repo_head_hexsha": "4ace908bd3da0519246b3c45d0230cbd02e49da0", "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.8989361702, "max_line_length": 108, "alphanum_fraction": 0.664227803, "num_tokens": 1517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.1966591613488892}}
{"text": "//----------------------------------------------------------------------------\n// Copyright (C) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the Server Side Public License, version 1,\n// as published by the author.\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// Server Side Public License for more details.\n//\n// You should have received a copy of the Server Side Public License\n// along with this program. If not, see\n// <https://github.com/NilFoundation/plugin/blob/master/LICENSE_1_0.txt>.\n//----------------------------------------------------------------------------\n\n#define BOOST_TEST_MODULE por_test\n\n#include <boost/test/data/monomorphic.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <nil/filecoin/storage/proofs/core/por.hpp>\n#include <nil/filecoin/storage/proofs/core/drgraph.hpp>\n\nBOOST_AUTO_TEST_SUITE(por_test_suite)\n\ntemplate<typename MerkleTreeType>\nvoid test_merklepor() {\n    const auto rng = XorShiftRng::from_seed(crate::TEST_SEED);\n\n    const std::size_t leaves = 16;\n    const auto pub_params = PublicParams {\n        leaves,\n        private : false,\n    };\n\n    std::vector<std::uint8_t> data = (0..leaves).flat_map(| _ | fr_into_bytes(&Fr::random(rng))).collect();\n    const auto porep_id = [3; 32];\n    const auto graph = BucketGraph<typename MerkleTreeType::hash_type> (leaves, BASE_DEGREE, 0, porep_id);\n    const auto tree = create_base_merkle_tree::<Tree>(None, graph.size(), data.as_slice());\n\n    const auto pub_inputs = PublicInputs {\n        challenge : 3,\n        commitment : Some(tree.root()),\n    };\n\n    const auto leaf =\n        typename MerkleTreeType::hash_type::digest_type::try_from_bytes(data_at_node(data.as_slice(), pub_inputs.challenge), )\n            ;\n\n    const auto priv_inputs = PrivateInputs(leaf, &tree);\n\n    const auto proof = PoR::<Tree>::prove(&pub_params, &pub_inputs, &priv_inputs).expect(\"proving failed\");\n\n    const auto is_valid = PoR::<Tree>::verify(&pub_params, &pub_inputs, &proof).expect(\"verification failed\");\n\n    BOOST_ASSERT(is_valid);\n}\n\ntype TestTree<H, U> = MerkleTreeWrapper<H, DiskStore <H::digest_type>, U, 0, 0> ;\n\nBOOST_AUTO_TEST_CASE(merklepor_pedersen_binary) {\n    test_merklepor<TestTree<PedersenHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_poseidon_binary) {\n    test_merklepor<TestTree<PoseidonHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_sha256_binary) {\n    test_merklepor<TestTree<Sha256Hasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_blake2s_binary) {\n    test_merklepor<TestTree<Blake2sHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_pedersen_quad) {\n    test_merklepor<TestTree<PedersenHasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_poseidon_quad) {\n    test_merklepor<TestTree<PoseidonHasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_sha256_quad) {\n    test_merklepor<TestTree<Sha256Hasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_blake2s_quad) {\n    test_merklepor<TestTree<Blake2sHasher, 4>>();\n}\n\n// Takes a valid proof and breaks it.\nDataProof<Proof> make_bogus_proof<Proof : BasicMerkleProof>(rng\n                                              : XorShiftRng, proof\n                                              : DataProof<Proof>) {\n    const auto bogus_leaf = Proof::Hasher::digest_type::random(rng);\n    proof.proof.break_me(bogus_leaf);\n    return proof;\n}\n\nvoid test_merklepor_validates<Tree : MerkleTreeTrait>() {\n    const auto rng = XorShiftRng::from_seed(crate::TEST_SEED);\n\n    const std::size_t leaves = 64;\n    const auto pub_params = PublicParams {\n        leaves,\n        private : false,\n    };\n\n    std::vector<std::uint8_t> data = (0..leaves).flat_map(| _ | fr_into_bytes(&Fr::random(rng))).collect();\n\n    const auto porep_id = [99; 32];\n\n    const auto graph = BucketGraph<typename MerkleTreeType::hash_type> (leaves, BASE_DEGREE, 0, porep_id);\n    const auto tree = create_base_merkle_tree::<Tree>(None, graph.size(), data.as_slice());\n\n    const auto pub_inputs = PublicInputs {\n        challenge : 3,\n        commitment : Some(tree.root()),\n    };\n\n    const auto leaf =\n        typename MerkleTreeType::hash_type::digest_type::try_from_bytes(data_at_node(data.as_slice(), pub_inputs.challenge), )\n            ;\n\n    const auto priv_inputs = PrivateInputs::<Tree> (leaf, &tree);\n\n    const auto good_proof = PoR::<Tree>::prove(&pub_params, &pub_inputs, &priv_inputs).expect(\"proving failed\");\n\n    const auto verified = PoR::<Tree>::verify(&pub_params, &pub_inputs, &good_proof).expect(\"verification failed\");\n    BOOST_ASSERT(verified);\n\n    const auto bad_proof = make_bogus_proof::<MerkleTreeType::Proof>(rng, good_proof);\n\n    const auto verified = PoR::<Tree>::verify(&pub_params, &pub_inputs, &bad_proof).expect(\"verification failed\");\n\n    // A bad proof should not be verified!\n    BOOST_ASSERT(!verified);\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_sha256_binary) {\n    test_merklepor_validates<TestTree<Sha256Hasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_blake2s_binary) {\n    test_merklepor_validates<TestTree<Blake2sHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_pedersen_binary) {\n    test_merklepor_validates<TestTree<PedersenHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_poseidon_binary) {\n    test_merklepor_validates<TestTree<PoseidonHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_sha256_quad) {\n    test_merklepor_validates<TestTree<Sha256Hasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_blake2s_quad) {\n    test_merklepor_validates<TestTree<Blake2sHasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_pedersen_quad) {\n    test_merklepor_validates<TestTree<PedersenHasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_poseidon_quad) {\n    test_merklepor_validates<TestTree<PoseidonHasher, 4>>();\n}\n\ntemplate<typename MerkleTreeType>\nvoid test_merklepor_validates_challenge_identity() {\n    const auto rng = XorShiftRng::from_seed(crate::TEST_SEED);\n\n    const std::size_t leaves = 64;\n\n    const auto pub_params = PublicParams {\n        leaves,\n        private : false,\n    };\n\n    std::vector<std::uint8_t> data = (0..leaves).flat_map(| _ | fr_into_bytes(&Fr::random(rng))).collect();\n\n    const auto porep_id = [32; 32];\n    const auto graph = BucketGraph<typename MerkleTreeType::hash_type> (leaves, BASE_DEGREE, 0, porep_id);\n    const auto tree = create_base_merkle_tree::<Tree>(None, graph.size(), data.as_slice());\n\n    const auto pub_inputs = PublicInputs {\n        challenge : 3,\n        commitment : Some(tree.root()),\n    };\n\n    const auto leaf =\n        typename MerkleTreeType::hash_type::digest_type::try_from_bytes(data_at_node(data.as_slice(), pub_inputs.challenge), )\n            ;\n\n    const auto priv_inputs = PrivateInputs::<Tree> (leaf, &tree);\n\n    const auto proof = PoR::<Tree>::prove(&pub_params, &pub_inputs, &priv_inputs).expect(\"proving failed\");\n\n    const auto different_pub_inputs = PublicInputs {\n        challenge : 999,\n        commitment : Some(tree.root()),\n    };\n\n    const auto verified = PoR::<Tree>::verify(&pub_params, &different_pub_inputs, &proof).expect(\"verification failed\");\n\n    // A proof created with a the wrong challenge not be verified!\n    BOOST_ASSERT(!verified);\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_challenge_identity_sha256_binary) {\n    test_merklepor_validates_challenge_identity<TestTree<Sha256Hasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_challenge_identity_blake2s_binary) {\n    test_merklepor_validates_challenge_identity<TestTree<Blake2sHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_challenge_identity_pedersen_binary) {\n    test_merklepor_validates_challenge_identity<TestTree<PedersenHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_challenge_identity_poseidon_binary) {\n    test_merklepor_validates_challenge_identity<TestTree<PoseidonHasher, 2>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_challenge_identity_sha256_quad) {\n    test_merklepor_validates_challenge_identity<TestTree<Sha256Hasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_challenge_identity_blake2s_quad) {\n    test_merklepor_validates_challenge_identity<TestTree<Blake2sHasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_challenge_identity_pedersen_quad) {\n    test_merklepor_validates_challenge_identity<TestTree<PedersenHasher, 4>>();\n}\n\nBOOST_AUTO_TEST_CASE(merklepor_actually_validates_challenge_identity_poseidon_quad) {\n    test_merklepor_validates_challenge_identity<TestTree<PoseidonHasher, 4>>();\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "5a699498d0a54b340b16b2e6b47ac0b7b0f629d2", "size": 8900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/storage/test/core/por.cpp", "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/test/core/por.cpp", "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/test/core/por.cpp", "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": 35.6, "max_line_length": 126, "alphanum_fraction": 0.726741573, "num_tokens": 2267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.1966591613488892}}
{"text": "/*!\n * @file    swp_bintree_primary.cpp\n * @author  William J Menz\n * @brief   Implementation of generic binary tree particle model\n *\n *   Author(s):      William J Menz\n *   Project:        sweepc (population balance solver)\n *   Copyright (C) 2012 William J Menz\n *\n *   File purpose:\n *      Implementation of the BinTreePrimary class.\n *\n *   Licence:\n *      This file is part of \"sweepc\".\n *\n *      sweepc 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 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 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 program; if not, write to the Free Software\n *      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\n *      02111-1307, USA.\n *\n *   Contact:\n *      Prof Markus Kraft\n *      Dept of Chemical Engineering\n *      University of Cambridge\n *      New Museums Site\n *      Pembroke Street\n *      Cambridge\n *      CB2 3RA, UK\n *\n *      Email:       mk306@cam.ac.uk\n *      Website:     http://como.cheng.cam.ac.uk\n*/\n\n#define _USE_MATH_DEFINES //!< First define.\n#include <math.h>         //!< Then include so that the pi constant (M_PI) can be used.\n\n#include \"swp_bintree_primary.h\"\n#include \"swp_bintree_serializer.h\"\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <stack>\n\nusing namespace Sweep;\nusing namespace Sweep::AggModels;\nusing namespace std;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n/*!\n * @brief       Initialising constructor with no arguments\n *\n * Initialises a particle from no arguments.\n *\n */\nBinTreePrimary::BinTreePrimary() : Primary(),\n    m_numprimary(0),\n    m_primarydiam(0.0),\n    m_children_radius(0.0),\n    m_children_vol(0.0),\n    m_children_surf(0.0),\n\tm_free_surf(0.0),\n\tm_sum_necks(0.0),\n\tm_primaryvol(0.0),\n    m_distance_centreToCentre(0.0),\n    m_children_sintering(0.0),\n    m_avg_sinter(0.0),\n    m_sint_rate(0.0),\n    m_sint_time(0.0),\n    m_leftchild(NULL),\n    m_rightchild(NULL),\n    m_parent(NULL),\n    m_leftparticle(NULL),\n    m_rightparticle(NULL),\n    m_r(0.0),\n    m_r2(0.0),\n    m_r3(0.0),\n\tm_Rg(0.0),\n\tm_tracked(false)\n{\n    m_cen_bsph[0] = 0.0;\n    m_cen_bsph[1] = 0.0;\n    m_cen_bsph[2] = 0.0;\n\n    m_cen_mass[0] = 0.0;\n    m_cen_mass[1] = 0.0;\n    m_cen_mass[2] = 0.0;\n\n\tm_frame_orient_z[0] = 0.0;\n\tm_frame_orient_z[1] = 0.0;\n\tm_frame_orient_z[2] = 1.0e-9;\n\n\tm_frame_orient_x[0] = 1.0e-9;\n\tm_frame_orient_x[1] = 0.0;\n\tm_frame_orient_x[2] = 0.0;\n}\n\n/*!\n * @brief       Initialising constructor using time and model\n *\n * Initialises a particle with the default chemical properties. Calls\n * UpdateCache() to calculate the derived properties after creation.\n *\n * @param[in]   time        Time at which particle is being created\n * @param[in]   model       Model which defines the meaning of the primary\n *\n */\nBinTreePrimary::BinTreePrimary(const double time,\n        const Sweep::ParticleModel &model)\n: Primary(time, model),\n    m_numprimary(0),\n    m_primarydiam(0.0),\n    m_children_radius(0.0),\n    m_children_vol(0.0),\n    m_children_surf(0.0),\n\tm_free_surf(0.0),\n\tm_sum_necks(0.0),\n\tm_primaryvol(0.0),\n    m_distance_centreToCentre(0.0),\n    m_children_sintering(0.0),\n    m_avg_sinter(0.0),\n    m_sint_rate(0.0),\n    m_sint_time(0.0),\n    m_leftchild(NULL),\n    m_rightchild(NULL),\n    m_parent(NULL),\n    m_leftparticle(NULL),\n    m_rightparticle(NULL),\n    m_r(0.0),\n    m_r2(0.0),\n    m_r3(0.0),\n\tm_Rg(0.0),\n\tm_tracked(false)\n{\n    m_cen_bsph[0] = 0.0;\n    m_cen_bsph[1] = 0.0;\n    m_cen_bsph[2] = 0.0;\n\n    m_cen_mass[0] = 0.0;\n    m_cen_mass[1] = 0.0;\n    m_cen_mass[2] = 0.0;\n\n\tm_frame_orient_z[0] = 0.0;\n\tm_frame_orient_z[1] = 0.0;\n\tm_frame_orient_z[2] = 1.0e-9;\n\n\tm_frame_orient_x[0] = 1.0e-9;\n\tm_frame_orient_x[1] = 0.0;\n\tm_frame_orient_x[2] = 0.0;\n}\n\n//! Copy constructor.\nBinTreePrimary::BinTreePrimary(const BinTreePrimary &copy)\n{\n    *this = copy;\n    if (copy.m_leftchild!=NULL)\n    {\n        CopyTree(&copy);\n    }\n}\n\n//! Stream-reading constructor.\nBinTreePrimary::BinTreePrimary(std::istream &in,\n        const Sweep::ParticleModel &model) :\nm_numprimary(0),\nm_primarydiam(0.0),\nm_children_radius(0.0),\nm_children_vol(0.0),\nm_children_surf(0.0),\nm_free_surf(0.0),\nm_sum_necks(0.0),\nm_primaryvol(0.0),\nm_distance_centreToCentre(0.0),\nm_children_sintering(0.0),\nm_avg_sinter(0.0),\nm_sint_rate(0.0),\nm_sint_time(0.0),\nm_leftchild(NULL),\nm_rightchild(NULL),\nm_parent(NULL),\nm_leftparticle(NULL),\nm_rightparticle(NULL),\nm_tracked(false)\n{\n    Deserialize(in, model);\n}\n\n//! Default destructor.\nBinTreePrimary::~BinTreePrimary()\n{\n    delete m_leftchild;\n    delete m_rightchild;\n\n    releaseMem();\n}\n\n\n// Primary operator\nBinTreePrimary &BinTreePrimary::operator=(const Primary &rhs)\n{\n    operator=(dynamic_cast<const BinTreePrimary&>(rhs));\n\n    return *this;\n}\n\n//! Return a copy of the model data\nBinTreePrimary *const BinTreePrimary::Clone(void) const\n{\n   return new BinTreePrimary(*this);\n}\n\n\n/*!\n * @brief       Recursively copy the tree for non-leaf nodes.\n *\n * @param[in] source Pointer to the primary to be copied\n*/\nvoid BinTreePrimary::CopyTree(const BinTreePrimary *source)\n{\n    // Create the new left and right children with nothing in them\n    m_leftchild     = new BinTreePrimary(source->CreateTime(),*m_pmodel);\n    m_rightchild    = new BinTreePrimary(source->CreateTime(),*m_pmodel);\n\n    // Copy the properties such as the volume,\n    // surface area and list of constituent chemical units\n    m_leftchild->CopyParts(source->m_leftchild);\n    m_rightchild->CopyParts(source->m_rightchild);\n\n    // Set the pointers to the parent\n    m_leftchild->m_parent=this;\n    m_rightchild->m_parent=this;\n\n    // The left and right particle are set further down in UpdateAllPointers\n    // These are the pointers that specify which primary particles touch each\n    // other in the aggregate structure.\n    m_leftparticle=NULL;\n    m_rightparticle=NULL;\n\n    // Recursively copy the subtrees\n    if (source->m_leftchild->m_leftchild!=NULL)\n        m_leftchild->CopyTree(source->m_leftchild);\n\n    if (source->m_rightchild->m_leftchild!=NULL)\n        m_rightchild->CopyTree(source->m_rightchild);\n\n    // Set the leftparticle and rightparticle\n    UpdateAllPointers(source);\n\n}\n\n/*!\n * @brief       Updates all pointers, ensuring the connectivity of the tree\n *                 is preserved during copying.\n *\n * Each node contains two pointers (m_leftparticle and m_rightparticle)\n * to primary particles that are connected by this node\n * This function is used when the entire particle tree is duplicated.\n * It sets the pointers in the copied node (this), such that the connectivity\n * of the primary particles in this node is the same as in the original node.\n *\n * @param[in] original Pointer to the primary to be copied\n*/\nvoid BinTreePrimary::UpdateAllPointers(const BinTreePrimary *original)\n{\n    // The primary has no children => there are no left and right particles\n    if (original->m_leftchild == NULL) {\n        m_leftparticle=NULL;\n        m_rightparticle=NULL;\n     }\n    else {\n        // Find the route to m_leftparticle in the original tree\n        std::stack<bool> route =recordPath(original->m_leftparticle, original);\n\n        // Now follow the same route down the new tree to find\n        // the new left particle\n        m_leftparticle = descendPath(this, route);\n\n         // Find the route to m_rightparticle in the original tree\n        route = recordPath(original->m_rightparticle, original);\n\n        // Now follow the same route down the new tree to find\n        // the new right particle\n        m_rightparticle = descendPath(this, route);\n    }\n}\n\n\n/*!\n *\n * It climbs up the tree from bottom to top recording a route\n * suitable for use in call to @see descendPath.\n *\n *@param[in]    bottom      Tree node from which to start climbing\n *@param[in]    top         Tree node at which to stop climbing\n *\n *@pre      top must be above bottom in a tree\n *\n *@return   Stack that can be used to descend the same path by moving to the\n *          left child each time the top of the stack is true.\n */\nstd::stack<bool> BinTreePrimary::recordPath(const BinTreePrimary* bottom,\n                                        const BinTreePrimary* const top)\n{\n    std::stack<bool> wasLeftChild;\n\n    while(bottom != top) {\n        // check whether bottom was a left child of its parent\n        wasLeftChild.push(bottom == bottom->m_parent->m_leftchild);\n\n        // Climb one level up the tree\n        bottom = bottom->m_parent;\n    }\n    return wasLeftChild;\n}\n\n/*!\n *@param[in]        here            Point in tree from which to start descent\n *@param[in,out]    takeLeftBranch  Instructions for which child to move to\n *                                   at each level\n *\n *@return   The node at the bottom of the path\n *\n *@pre  here must be a node of tree in which takeLeftBranch is a valid path\n *@post takeLeftBranch.empty() == true\n */\nBinTreePrimary* BinTreePrimary::descendPath(BinTreePrimary *here,\n                                    std::stack<bool> &takeLeftBranch) {\n    while(!takeLeftBranch.empty()) {\n        // Move one step down the tree in the instructed direction\n        if(takeLeftBranch.top())\n            here = here->m_leftchild;\n        else\n            here = here->m_rightchild;\n\n        // This instuction has now been processed\n        takeLeftBranch.pop();\n    }\n\n    return here;\n}\n\n/*!\n * @brief       Coagulates *this* and rhs particle\n *\n * Called by coagulate, this function joins sp1 (this) and sp2 (rhs).\n * Basic properties are first calculated, followed by derived.\n *\n * @param[in] rhs   Pointer to the particle to be coagulated with this\n * @param[in] rng   Random number generator\n*/\nBinTreePrimary &BinTreePrimary::Coagulate(const Primary &rhs, rng_type &rng)\n{\n    const BinTreePrimary *rhsparticle = NULL;\n    rhsparticle = dynamic_cast<const AggModels::BinTreePrimary*>(&rhs);\n\n\t// Don't sum-up components now. Wait for UpdateCache so as to not\n    // double-count the values.\n\n    // Create the new particles\n    BinTreePrimary *newleft = new BinTreePrimary(m_time, *m_pmodel);\n    BinTreePrimary *newright = new BinTreePrimary(m_time, *m_pmodel);\n    BinTreePrimary copy_rhs(*rhsparticle);\n\n    //Randomly select where to add the second particle\n    boost::bernoulli_distribution<> bernoulliDistrib;\n    if (bernoulliDistrib(rng)) {\n        newleft->CopyParts(this);\n        newright->CopyParts(&copy_rhs);\n\t\t//if both particles are being tracked remove tracking from the one that will be deleted\n\t\tif (newleft->m_tracked == true && newright->m_tracked == true) newright->removeTracking();\n    }\n    else {\n        newright->CopyParts(this);\n        newleft->CopyParts(&copy_rhs);\n\t\t//if both particles are being tracked remove tracking from the one that will be deleted\n\t\tif (newright->m_tracked == true && newleft->m_tracked == true) newleft->removeTracking();\n    }\n\n    // Set the pointers\n    m_leftchild     = newleft;\n    m_rightchild    = newright;\n    newright->m_parent = this;\n    newleft->m_parent  = this;\n\n    // Set the pointers to the parent node\n    if (newleft->m_leftchild!=NULL) {\n\t\tnewleft->m_leftchild->m_parent      = newleft;\n\t\tnewleft->m_rightchild->m_parent     = newleft;\n    }\n    if (newright->m_leftchild!=NULL) {\n\t\tnewright->m_leftchild->m_parent     = newright;\n\t\tnewright->m_rightchild->m_parent    = newright;\n    }\n    m_children_sintering=0.0;\n\n    UpdateCache();\n\n    //! It is assumed that primary pi from particle Pq and primary pj from\n    //! particle Pq are in point contact and by default pi and pj are\n    //! uniformly selected. If we track the coordinates of the primaries in\n    //! a particle, we can do a smarter selection where pi and pj are\n    //! determined by ballistic cluster-cluster aggregation (BCCA):\n    //! R. Jullien, Transparency effects in cluster-cluster aggregation with\n    //! linear trajectories, J. Phys. A 17 (1984) L771-L776.\n    if (m_pmodel->getTrackPrimaryCoordinates()) {\n        boost::uniform_01<rng_type&, double> uniformGenerator(rng);\n        \n\t\t//! Calculate centre of mass and bounding sphere\n\t\tm_leftchild->calcBoundSph();\n\t\tm_leftchild->calcCOM();\n\t\tm_rightchild->calcBoundSph();\n\t\tm_rightchild->calcCOM();\n\n        //! Implementation of Arvo's algorithm, Fast Random Rotation Matrices,\n        //! Chapter III.4 in Graphic Gems III edited by David Kirk to generate\n        //! a transformation matrix for randomly rotating a particle.\n        double theta1 = 2 * PI * uniformGenerator(); //!< Pick a rotation about the pole.\n        double phi1 = 2 * PI * uniformGenerator();   //!< Pick a direction to deflect the pole.\n        double z1 = uniformGenerator();              //!< Pick the amount of pole deflection.\n\n        //! Construct a vector for performing the reflection.\n        fvector V1; \n        V1.push_back(cos(phi1) * sqrt(z1));\n        V1.push_back(sin(phi1) * sqrt(z1));\n        V1.push_back(sqrt(1 - z1));\t\n\n        //! Rotate centre-of-mass.\n        m_leftchild->rotateCOM(theta1, V1);\n\n        //! Implementation of Arvo's algorithm, Fast Random Rotation Matrices,\n        //! Chapter III.4 in Graphic Gems III edited by David Kirk to generate\n        //! a transformation matrix for randomly rotating a particle.\n        double theta2 = 2 * PI * uniformGenerator(); //!< Pick a rotation about the pole.\n        double phi2 = 2 * PI * uniformGenerator();   //!< Pick a direction to deflect the pole.\n        double z2 = uniformGenerator();              //!< Pick the amount of pole deflection.\n\n        //! Construct a vector for performing the reflection.\n        fvector V2; \n        V2.push_back(cos(phi2) * sqrt(z2));\n        V2.push_back(sin(phi2) * sqrt(z2));\n        V2.push_back(sqrt(1 - z2));\n\n        //! Rotate centre-of-mass.\n        m_rightchild->rotateCOM(theta2, V2);\n\n        m_leftchild->centreBoundSph();\n        m_rightchild->centreBoundSph();\n\n        bool Overlap = false;\n\n\t\tif (true){\t//Select between BCCA and DLCA (currently only using BCCA)\n\t\t\t///////////////////////////////////////////////////////////////////////////////\n\t\t\t//\tBallistic Cluster Cluster Aggregation (BCCA)\n\t\t\t//\tGives D_f ~ 1.91 and k_f ~ 1.333\n\t\t\t//\tLindberg et al., J. Comp. Phys. 397, 108799, (2019)\n\t\t\t///////////////////////////////////////////////////////////////////////////////\n        \n\t\t\t//! Incremental translation.\n\t\t\twhile (!Overlap) {\n\t\t\t\t//! Sphere point picking. This is the random direction step of\n\t\t\t\t//! Jullien's BCCA algorithm. It is incorrect to select spherical\n\t\t\t\t//! coordinates theta (azimuthal angle) and phi (polar angle) from\n\t\t\t\t//! uniform distributions theta E [0, 2 * pi) and phi E [0, pi] as\n\t\t\t\t//! points picked in this way will be 'bunched' near the poles:\n\t\t\t\t//! http://mathworld.wolfram.com/SpherePointPicking.html\n\t\t\t\tdouble theta = 2.0 * PI * uniformGenerator();\n\t\t\t\tdouble phi = acos(2.0 * uniformGenerator() - 1.0);\n\n\t\t\t\t//! In terms of Cartesian coordinates.\n\t\t\t\tdouble x = cos(theta) * sin(phi);\n\t\t\t\tdouble y = sin(theta) * sin(phi);\n\t\t\t\tdouble z = cos(phi);\n\n\t\t\t\t//! We want to find the rotation matrix which rotates an\n\t\t\t\t//! arbitrarily chosen unit vector to the randomly chosen unit\n\t\t\t\t//! vector selected above. Not sure where the formula is from but I\n\t\t\t\t//! have checked that it works:\n\t\t\t\t//! https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d\n\t\t\t\tdouble bx = 0.0;\n\t\t\t\tdouble by = 0.0;\n\t\t\t\tdouble bz = -1.0;\n\n\t\t\t\t//! Cross product of the two vectors.\n\t\t\t\tdouble vx = by * z - bz * y;\n\t\t\t\tdouble vy = bz * x - bx * z;\n\t\t\t\tdouble vz = bx * y - by * x;\n\n\t\t\t\t//! Skew-symmetric cross-product matrix of vector v.\n\t\t\t\tdouble v[3][3] = {0};\n\n\t\t\t\tv[0][0] = 0.0;\n\t\t\t\tv[0][1] = -vz;\n\t\t\t\tv[0][2] = vy;\n\t\t\t\tv[1][0] = vz;\n\t\t\t\tv[1][1] = 0.0;\n\t\t\t\tv[1][2] = -vx;\n\t\t\t\tv[2][0] = -vy;\n\t\t\t\tv[2][1] = vx;\n\t\t\t\tv[2][2] = 0.0;\n\n\t\t\t\t//! Identity.\n\t\t\t\tdouble I[3][3] = {0};\n\n\t\t\t\tI[0][0] = 1.0;\n\t\t\t\tI[0][1] = 0.0;\n\t\t\t\tI[0][2] = 0.0;\n\t\t\t\tI[1][0] = 0.0;\n\t\t\t\tI[1][1] = 1.0;\n\t\t\t\tI[1][2] = 0.0;\n\t\t\t\tI[2][0] = 0.0;\n\t\t\t\tI[2][1] = 0.0;\n\t\t\t\tI[2][2] = 1.0;\n\n\t\t\t\t//! Rotation matrix.\n\t\t\t\tdouble R[3][3] = {0};\n\t\t\t\tdouble Mult = 1.0 / (1.0 + bx * x + by * y + bz * z); //!< Dot product of the two unit vectors.\n\n\t\t\t\t//! Square of the matrix v.\n\t\t\t\tR[0][0] = Mult * (-vy * vy - vz * vz);\n\t\t\t\tR[0][1] = Mult * (vx * vy);\n\t\t\t\tR[0][2] = Mult * (vx * vz);\n\t\t\t\tR[1][0] = Mult * (vx * vy);\n\t\t\t\tR[1][1] = Mult * (-vx * vx - vz * vz);\n\t\t\t\tR[1][2] = Mult * (vy * vz);\n\t\t\t\tR[2][0] = Mult * (vx * vz);\n\t\t\t\tR[2][1] = Mult * (vy * vz);\n\t\t\t\tR[2][2] = Mult * (-vx * vx - vy * vy);\n\n\t\t\t\tR[0][0] = 1.0 + R[0][0];\n\t\t\t\tR[0][1] = -vz + R[0][1];\n\t\t\t\tR[0][2] = vy + R[0][2];\n\t\t\t\tR[1][0] = vz + R[1][0];\n\t\t\t\tR[1][1] = 1.0 + R[1][1];\n\t\t\t\tR[1][2] = -vx + R[1][2];\n\t\t\t\tR[2][0] = -vy + R[2][0];\n\t\t\t\tR[2][1] = vx + R[2][1];\n\t\t\t\tR[2][2] = 1.0 + R[2][2];\n\n\t\t\t\t//! Disk point picking. This is the random impact step of Jullien's\n\t\t\t\t//! BCCA algorithm. We first randomly select a point in the x-y\n\t\t\t\t//! plane over a disk of diameter and at a distance equal to the\n\t\t\t\t//! sum of the primary particle radii as this is the maximum\n\t\t\t\t//! distance they can be apart. Then we apply the rotation matrix\n\t\t\t\t//! obtained above to the point:\n\t\t\t\t// http://mathworld.wolfram.com/DiskPointPicking.html\n\t\t\t\tdouble r = uniformGenerator();\n\t\t\t\ttheta  = 2.0 * PI * uniformGenerator();\n\n\t\t\t\tdouble sumr = m_leftchild->Radius() + m_rightchild->Radius();\n\n\t\t\t\tdouble x3 = sumr * sqrt(r) * cos(theta);\n\t\t\t\tdouble y3 = sumr * sqrt(r) * sin(theta);\n\t\t\t\tdouble z3 = -sumr;\n\n\t\t\t\tdouble x4 = R[0][0] * x3 + R[0][1] * y3 + R[0][2] * z3;\n\t\t\t\tdouble y4 = R[1][0] * x3 + R[1][1] * y3 + R[1][2] * z3;\n\t\t\t\tdouble z4 = R[2][0] * x3 + R[2][1] * y3 + R[2][2] * z3;\n\n\t\t\t\tthis->m_leftchild->Translate(x4, y4, z4);\n            \n\t\t\t\t//! The two particles are initially at the origin. Keep doubling\n\t\t\t\t//! the distance between them so that they do not overlap. This is\n\t\t\t\t//! more efficient than picking an arbitrarily large distance.\n\t\t\t\tint numberOfOverlaps = 0;\n\t\t\t\tint factorApart = 1;\n\t\t\t\tdouble Separation = 0.0;\n\n\t\t\t\twhile (this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation)) {\n\t\t\t\t\tthis->m_leftchild->Translate(-factorApart * R[0][2] * sumr, -factorApart * R[1][2] * sumr, -factorApart * R[2][2] * sumr);\n\t\t\t\t\tfactorApart *= 2;\n\t\t\t\t}    \n\n\t\t\t\tnumberOfOverlaps = 0;\n\n\t\t\t\twhile (!Overlap) {\n\n\t\t\t\t\tdouble dx = this->m_leftchild->m_cen_bsph[0];\n\t\t\t\t\tdouble dy = this->m_leftchild->m_cen_bsph[1];\n\t\t\t\t\tdouble dz = this->m_leftchild->m_cen_bsph[2];\n\n\t\t\t\t\tdouble oldDistance = dx * dx + dy * dy + dz * dz;\n\n\t\t\t\t\t//! Translate particle in 1% increments.\n\t\t\t\t\tthis->m_leftchild->Translate(-0.01 * x * sumr, -0.01 * y * sumr, -0.01 * z * sumr);\n\n\t\t\t\t\tOverlap = this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation);\n                \n\t\t\t\t\tdx = this->m_leftchild->m_cen_bsph[0];\n\t\t\t\t\tdy = this->m_leftchild->m_cen_bsph[1];\n\t\t\t\t\tdz = this->m_leftchild->m_cen_bsph[2];\n\n\t\t\t\t\tdouble newDistance = dx * dx + dy * dy + dz * dz;\n\n\t\t\t\t\t//! If the left particle has failed to collide with the\n\t\t\t\t\t//! particle at the origin (first condition) or if there are\n\t\t\t\t\t//! multiple points of overlap (second condition), the trial is\n\t\t\t\t\t//! abandoned and another trajectory is chosen.\n\t\t\t\t\tif ((newDistance > oldDistance && newDistance > sumr * sumr) || (numberOfOverlaps > 1)) {\n\t\t\t\t\t\tthis->m_leftchild->centreBoundSph();\n\t\t\t\t\t\t//this->m_leftchild->centreCOM();\n\t\t\t\t\t\tnumberOfOverlaps = 0;\n\t\t\t\t\t\tOverlap = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//! Newton bisection method to speed up translation.\n\t\t\t\t//! Needs to be tested.\n\t\t\t\t//double a = 0.0;\n\t\t\t\t//double b = 0.0;\n\t\t\t\t//double c = 0.0;\n\n\t\t\t\t//b = this->m_leftchild->m_cen_bsph[2];\n\t\t\t\t//double Translation = - (b - (a + b) / 2.0);\n\n\t\t\t\t//numberOfOverlaps = 0;\n\n\t\t\t\t//while (!(abs(Separation - 1) < 0.01 && numberOfOverlaps == 1)) {\n\t\t\t\t//    this->m_leftchild->Translate(0, 0, Translation);\n\n\t\t\t\t//    numberOfOverlaps = 0;\n\n\t\t\t\t//    if (this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation)) {\n\t\t\t\t//        a = this->m_leftchild->m_cen_bsph[2];\n\t\t\t\t//        Translation = (a + b) / 2.0 - a;\n\t\t\t\t//    } else {\n\t\t\t\t//        b = this->m_leftchild->m_cen_bsph[2];\n\t\t\t\t//        Translation = - (b - (a + b) / 2.0);\n\t\t\t\t//    }\n\t\t\t\t//}\n\t\t\t}\n\t\t\t///////////////////////////////////////////////////////////////////////////////\n\t\t}\n\t\telse{\t//DLCA disabled\n\t\t\t///////////////////////////////////////////////////////////////////////////////\n\t\t\t//\tDiffusion Limited Cluster Aggregation (DLCA)\n\t\t\t//\tGives D_f ~ 1.8 and k_f ~ 1.36\n\t\t\t//\tInstead of ballistic trajectories as with BCCA, DLCA models Brownian motion. \n\t\t\t//\tThe \"bullet\" particle takes steps in random directions with step size \n\t\t\t//\tequal to the average primary diameter.\n\t\t\t///////////////////////////////////////////////////////////////////////////////\n\t\t\twhile (!Overlap) {\n\t\t\t\t//! Generate random point on sphere\n\t\t\t\tdouble theta = 2.0 * PI * uniformGenerator();\n\t\t\t\tdouble phi = acos(2.0 * uniformGenerator() - 1.0);\n\n\t\t\t\t//! In terms of Cartesian coordinates.\n\t\t\t\tdouble x = cos(theta) * sin(phi);\n\t\t\t\tdouble y = sin(theta) * sin(phi);\n\t\t\t\tdouble z = cos(phi);\n\n\t\t\t\tdouble sumr = m_leftchild->Radius() + m_rightchild->Radius();\n\n\t\t\t\t// translate the left child\n\t\t\t\tthis->m_leftchild->Translate(sumr*x, sumr*y, sumr*z);\n\n\t\t\t\t//! The two particles are initially at the origin. Keep doubling\n\t\t\t\t//! the distance between them so that they do not overlap. This is\n\t\t\t\t//! more efficient than picking an arbitrarily large distance.\n\t\t\t\tint numberOfOverlaps = 0;\n\t\t\t\tint factorApart = 1;\n\t\t\t\tdouble Separation = 0.0;\n\n\t\t\t\twhile (this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation)) {\n\t\t\t\t\tthis->m_leftchild->Translate(factorApart * x * sumr, factorApart * y * sumr, factorApart * z * sumr);\n\t\t\t\t\tfactorApart *= 2;\n\t\t\t\t}\n\n\t\t\t\tdouble dx = this->m_leftchild->m_cen_bsph[0];\n\t\t\t\tdouble dy = this->m_leftchild->m_cen_bsph[1];\n\t\t\t\tdouble dz = this->m_leftchild->m_cen_bsph[2];\n\n\t\t\t\tdouble initialDistance = dx * dx + dy * dy + dz * dz;\n\n\t\t\t\tnumberOfOverlaps = 0;\n\n\t\t\t\t//Loop over Brownian steps \n\t\t\t\twhile (!Overlap) {\n\n\t\t\t\t\t//Generate a random direction\n\t\t\t\t\tdouble theta2 = 2.0 * PI * uniformGenerator();\n\t\t\t\t\tdouble phi2 = acos(2.0 * uniformGenerator() - 1.0);\n\n\t\t\t\t\t//! In terms of Cartesian coordinates.\n\t\t\t\t\tdouble x2 = cos(theta2) * sin(phi2);\n\t\t\t\t\tdouble y2 = sin(theta2) * sin(phi2);\n\t\t\t\t\tdouble z2 = cos(phi2);\n\n\t\t\t\t\t//Brownian step size: this is the average primary size\n\t\t\t\t\tdouble step_size = m_leftchild->m_primarydiam / m_leftchild->m_numprimary;\n\n\t\t\t\t\t//First take an entire Brownian step\n\t\t\t\t\tthis->m_leftchild->Translate(step_size * x2, step_size * y2, step_size * z2);\n\t\t\t\t\tOverlap = this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation);\n\n\t\t\t\t\t//If particles overlap then reverse the step and retake it in smaller increments \n\t\t\t\t\t//until the particles are approximately in point contact\n\t\t\t\t\tif (Overlap == true){\n\n\t\t\t\t\t\t//Reverse the step\n\t\t\t\t\t\tthis->m_leftchild->Translate(-step_size * x2, -step_size * y2, -step_size * z2);\n\t\t\t\t\t\tOverlap = false;\n\t\t\t\t\t\tnumberOfOverlaps = 0;\n\n\t\t\t\t\t\t//Take the Brownian step in small increments\n\t\t\t\t\t\tunsigned int increment = 0;\n\t\t\t\t\t\tunsigned int tot_increments = 10;\n\t\t\t\t\t\n\t\t\t\t\t\twhile (Overlap == false && increment < tot_increments){\n\n\t\t\t\t\t\t\t//! Translate particle in 10% increments of Brownian step\n\t\t\t\t\t\t\tthis->m_leftchild->Translate(step_size * x2 / tot_increments, step_size * y2 / tot_increments, step_size * z2 / tot_increments);\n\n\t\t\t\t\t\t\tOverlap = this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation);\n\n\t\t\t\t\t\t\tincrement++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Get the boundins sphere separation\n\t\t\t\t\tdx = this->m_leftchild->m_cen_bsph[0];\n\t\t\t\t\tdy = this->m_leftchild->m_cen_bsph[1];\n\t\t\t\t\tdz = this->m_leftchild->m_cen_bsph[2];\n\n\t\t\t\t\tdouble newDistance = dx * dx + dy * dy + dz * dz;\n\n\t\t\t\t\t//! If the left particle has failed to collide with the particle at the\n\t\t\t\t\t//! origin (first condition) i.e. travelled too far in the wrong direction\n\t\t\t\t\t//! or if there are multiple points of overlap (second condition), \n\t\t\t\t\t//! the trial is abandoned and another trajectory is chosen.\n\t\t\t\t\tif ((newDistance > initialDistance*2) || (numberOfOverlaps > 1)) {\n\t\t\t\t\t\tthis->m_leftchild->centreBoundSph();\n\t\t\t\t\t\tnumberOfOverlaps = 0;\n\t\t\t\t\t\tOverlap = false;\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///////////////////////////////////////////////////////////////////////////////\n\n        double deltax = m_rightparticle->m_cen_bsph[0] - m_leftparticle->m_cen_bsph[0];\n        double deltay = m_rightparticle->m_cen_bsph[1] - m_leftparticle->m_cen_bsph[1];\n        double deltaz = m_rightparticle->m_cen_bsph[2] - m_leftparticle->m_cen_bsph[2];\n\n        m_distance_centreToCentre = sqrt(deltax * deltax + deltay * deltay + deltaz * deltaz);\n\n        //! Calculate properties of this particle.\n        this->calcBoundSph();\n        this->calcCOM();\n\n        //! If particle contains PAH to be traced write POV-Ray translation\n        //! of particle\n        this->centreBoundSph();\n\n        //! Particle is centred about its bounding sphere for the purpose\n        //! generating its structure. Now that it is complete centre it\n        //! about its centre-of-mass.\n        this->centreCOM();\n\n\t\t//! Rotate back to original orientation of one particle \n\t\tthis->rotateCOM(-theta1, V1);\n\n    } else {\n        //! Randomly select the primaries that are touching.\n        this->m_leftparticle = m_leftchild->SelectRandomSubparticle(rng);\n        this->m_rightparticle = m_rightchild->SelectRandomSubparticle(rng);\n    }\n\n    // Set the sintering times\n    SetSinteringTime(std::max(m_sint_time, rhsparticle->m_sint_time));\n    m_createt = max(m_createt, rhsparticle->m_createt);\n\n    // Initialise the variables used to calculate the sintering level\n    m_children_vol      = m_leftparticle->m_vol + m_rightparticle->m_vol;\n    m_children_surf     = m_leftparticle->m_surf + m_rightparticle->m_surf;\n    m_children_radius   = pow(3.0/(4.0*PI)*(m_children_vol),(ONE_THIRD));\n    m_children_sintering= SinteringLevel();\n\n    //! If the coordinates of the primary particles are tracked we can directly\n    //! calculate the centre-to-centre primary particle distance which is not\n    //! exactly equal to the sum of the primary particle radii. Primaries are\n    //! not considered to be in point contact unless there is a small overlap.\n    if (m_pmodel->getTrackPrimaryCoordinates()) {\n        double x1 = m_leftparticle->m_cen_bsph[0];\n        double y1 = m_leftparticle->m_cen_bsph[1];\n        double z1 = m_leftparticle->m_cen_bsph[2];\n\n        double x2 = m_rightparticle->m_cen_bsph[0];\n        double y2 = m_rightparticle->m_cen_bsph[1];\n        double z2 = m_rightparticle->m_cen_bsph[2];\n\n        m_distance_centreToCentre = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1));    \n    } else if (m_pmodel->getTrackPrimarySeparation()) {\n        m_distance_centreToCentre = m_leftparticle->m_primarydiam / 2.0 + m_rightparticle->m_primarydiam / 2.0;\n    }\n\n\tassert(m_distance_centreToCentre >= 0.0);\n\n\tCheckSintering();\n\n    // Must set all the pointer to NULL otherwise the delete function\n    // will also delete the children\n    copy_rhs.m_leftchild    = NULL;\n    copy_rhs.m_rightchild   = NULL;\n    copy_rhs.m_parent       = NULL;\n    copy_rhs.m_leftparticle = NULL;\n    copy_rhs.m_rightparticle= NULL;\n\n    return *this;\n}\n\n/*!\n * @brief       Coagulates *this* and rhs particle\n *\n * Called by coagulate, this function joins sp1 (this) and sp2 (rhs).\n * Basic properties are first calculated, followed by derived.\n *\n * @param[in] rhs   Pointer to the particle to be coagulated with this\n * @param[in] rng   Random number generator\n*/\nBinTreePrimary &BinTreePrimary::Fragment(const Primary &rhs, rng_type &rng)\n{\n    const BinTreePrimary *rhsparticle = NULL;\n    rhsparticle = dynamic_cast<const AggModels::BinTreePrimary*>(&rhs);\n\n    // Don't sum-up components now. Wait for UpdateCache so as to not\n    // double-count the values.\n\n    // Create the new particles\n    BinTreePrimary *newleft = new BinTreePrimary(m_time, *m_pmodel);\n    BinTreePrimary *newright = new BinTreePrimary(m_time, *m_pmodel);\n    BinTreePrimary copy_rhs(*rhsparticle);\n\n\n    //Randomly select where to add the second particle\n    boost::bernoulli_distribution<> bernoulliDistrib;\n    if (bernoulliDistrib(rng)) {\n        newleft->CopyParts(this);\n        newright->CopyParts(&copy_rhs);\n    }\n    else {\n        newright->CopyParts(this);\n        newleft->CopyParts(&copy_rhs);\n    }\n\n    // Set the pointers\n    m_leftchild     = newleft;\n    m_rightchild    = newright;\n    newright->m_parent = this;\n    newleft->m_parent  = this;\n\n    // Set the pointers to the parent node\n    if (newleft->m_leftchild!=NULL) {\n\t\tnewleft->m_leftchild->m_parent      = newleft;\n\t\tnewleft->m_rightchild->m_parent     = newleft;\n    }\n    if (newright->m_leftchild!=NULL) {\n\t\tnewright->m_leftchild->m_parent     = newright;\n\t\tnewright->m_rightchild->m_parent    = newright;\n    }\n    m_children_sintering=0.0;\n    UpdateCache();\n\n    // Select the primaries that are touching\n    m_leftparticle      = m_leftchild->SelectRandomSubparticle(rng);\n    m_rightparticle     = m_rightchild->SelectRandomSubparticle(rng);\n\n    // Set the sintering times\n    SetSinteringTime(std::max(m_sint_time, rhsparticle->m_sint_time));\n    m_createt = max(m_createt, rhsparticle->m_createt);\n\n    // Initialise the variables used to calculate the sintering level\n    m_children_vol      = m_leftparticle->m_vol + m_rightparticle->m_vol;\n    m_children_surf     = m_leftparticle->m_surf + m_rightparticle->m_surf;\n    m_children_radius   = pow(3.0/(4.0*PI)*(m_children_vol),(ONE_THIRD));\n    m_children_sintering= SinteringLevel();\n    CheckSintering();\n\n    // Must set all the pointer to NULL otherwise the delete function\n    // will also delete the children\n    copy_rhs.m_leftchild    = NULL;\n    copy_rhs.m_rightchild   = NULL;\n    copy_rhs.m_parent       = NULL;\n    copy_rhs.m_leftparticle = NULL;\n    copy_rhs.m_rightparticle= NULL;\n\n    return *this;\n}\n\n//! Check for the overlap of primary particles.\n/*!\n * @brief       Copy state-space and derived properties from source *\n *  @return Whether there is the overlap of primary particles.\n */\nbool BinTreePrimary::checkForOverlap(BinTreePrimary &target, BinTreePrimary &bullet, int &numberOfOverlaps, double &Separation)\n{\n    bool Overlap = false;\n\n    if (target.isLeaf()) {\n        //! Target is a leaf.\n        if (bullet.isLeaf()) {\n            Overlap = particlesOverlap(target.boundSphCentre(), target.Radius(), bullet.boundSphCentre(), bullet.Radius(), Separation);\n\n            //! Keep a running total of the number of overlaps, and the left\n            //! and right particles should not be assigned unless there is\n            //! overlap.\n            if (Overlap) {\n                numberOfOverlaps += 1;\n\n                //! Bullet is a leaf (both leaves).\n                this->m_leftparticle = &target;\n                this->m_rightparticle = &bullet;    \n            }\n\n            return Overlap;\n        } else {\n            //! Bullet is not a leaf, call sub-nodes.\n            Overlap = checkForOverlap(target, *bullet.m_leftchild, numberOfOverlaps, Separation);\n            Overlap = checkForOverlap(target, *bullet.m_rightchild, numberOfOverlaps, Separation) || Overlap;\n\n            return Overlap;\n        }\n    } else {\n        //! Target is not a leaf.\n        if (bullet.isLeaf()) {\n            //! Bullet is a leaf, call target sub-nodes.\n            Overlap = checkForOverlap(*target.m_leftchild, bullet, numberOfOverlaps, Separation);\n            Overlap = checkForOverlap(*target.m_rightchild, bullet, numberOfOverlaps, Separation) || Overlap;\n\n            return Overlap;\n        } else {\n            //! Bullet is not a leaf (neither is a leaf), check all left/right\n            //! collision combinations.\n            //! Target left and bullet left.\n            Overlap = checkForOverlap(*target.m_leftchild, *bullet.m_leftchild, numberOfOverlaps, Separation);\n\n            //! Target left and bullet right.\n            Overlap = checkForOverlap(*target.m_leftchild, *bullet.m_rightchild, numberOfOverlaps, Separation) || Overlap;\n            \n            //! Target right and bullet left.\n            Overlap = checkForOverlap(*target.m_rightchild, *bullet.m_leftchild, numberOfOverlaps, Separation) || Overlap;\n\n            //! Target right and bullet right.\n            Overlap = checkForOverlap(*target.m_rightchild, *bullet.m_rightchild, numberOfOverlaps, Separation) || Overlap;\n\n            return Overlap;\n        }\n    }\n}\n\n//! Determine whether the particles overlap.\n/*!\n *  @param[in]  p1         Coordinates of sphere 1.\n *  @param[in]  r1         Radius of sphere 1.\n *  @param[in]  p2         Coordinates of sphere 2.\n *  @param[in]  r2         Radius of sphere 2.\n *  @param[out] Separation Separation between the centres of the primary\n *                         particles for use with the Newton bisection\n *                         method.\n *\n *  @return Do the particles overlap?\n */\nbool BinTreePrimary::particlesOverlap(const Coords::Vector &p1, double r1,\n                           const Coords::Vector &p2, double r2, double &Separation)\n{\n    double sumrsqr;\n\n    sumrsqr = r1 + r2;\n\n    //! Calculate the square of the sum of the radii.\n    sumrsqr *= sumrsqr;\n\n    //! Calculate dx, dy and dz.\n    double xdev = p2[0] - p1[0];\n    double ydev = p2[1] - p1[1];\n    double zdev = p2[2] - p1[2];\n\n    //! Calculate dx, dy and dz squared.\n    double dxsqr = xdev * xdev;\n    double dysqr = ydev * ydev;\n    double dzsqr = zdev * zdev;\n\n    //! The particles overlap if the centre-to-centre distance is less than the\n    //! sum of the primary radii.\n    if (sumrsqr < dxsqr + dysqr + dzsqr) {\n        Separation = 0.0;\n        return false;\n    } else {\n        Separation = sqrt(dxsqr + dysqr + dzsqr);\n        return true;\n    }\n}\n\n//! Calculates the radius of gyration of a particle\n//! assuming primaries are point masses.\ndouble BinTreePrimary::RadiusOfGyration() const\n{\n    double sum=0;\n    double mass;\n    double totalmass=0;\n    double r2;\n    double Rg;\n    double rix, riy, riz, rjx, rjy, rjz;\n    vector<fvector> coords;\n\n\t//! If single primary then return Rg = 0 because primaries are treated as point particles\n\tif(m_numprimary == 1) {\n\t\tRg = 0.0;\n\n\t}else{\n\n\t\tthis->GetPriCoords(coords);\n    \n\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t//! Calculation is based on Eq. (1) in R. Jullien, Transparency effects\n\t\t\t//! in cluster-cluster aggregation with linear trajectories, J. Phys. A\n\t\t\t//! 17 (1984) L771-L776. \n\t\t\tfor (int i = 0; i!=coords.size(); ++i) {\n\t\t\t\tfor (int j = 0; j!=coords.size(); ++j) {\n\t\t\t\t\trix = coords[i][0];\n\t\t\t\t\triy = coords[i][1];\n\t\t\t\t\triz = coords[i][2];\n\n\t\t\t\t\trjx = coords[j][0];\n\t\t\t\t\trjy = coords[j][1];\n\t\t\t\t\trjz = coords[j][2];\n\n\t\t\t\t\t//! Expansion of (r_i - r_j)^2 term. Dot product of r vectors.\n\t\t\t\t\tsum += rix * rix + riy * riy + riz * riz +\n\t\t\t\t\t\t   rjx * rjx + rjy * rjy + rjz * rjz -\n\t\t\t\t\t\t   2 * (rix * rjx + riy * rjy + riz * rjz);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRg = sqrt(sum / 2 / coords.size() / coords.size());\n\t\t} else {\n\t\t\tfor (unsigned int i=0; i!=coords.size(); ++i) {\n\t\t\t\t//! Mass is proportional to the cube of the radius.\n\t\t\t\tmass = coords[i][3] * coords[i][3] * coords[i][3];\n\t\t\t\tr2 = coords[i][0] * coords[i][0] + coords[i][1] * coords[i][1] + coords[i][2] * coords[i][2];\n\t\t\t\tsum += mass * r2;\n\t\t\t\ttotalmass += mass;\n\t\t\t}\n\n\t\t\tRg = sqrt(sum / totalmass);\n\t\t}\n\t}\n\t    \n\treturn Rg;\n}\n\n//! Returns a vector of primary coordinates, radius, and mass (5D).\n/*!\n *  @param[in] coords The first three returned values are the cartesian x, y, z\n *                    coordinates, the final value is the radius.\n */\nvoid BinTreePrimary::GetPriCoords(std::vector<fvector> &coords) const\n{\n    if (isLeaf()) {\n        fvector c(5);\n        c[0] = m_cen_mass[0];\n        c[1] = m_cen_mass[1];\n        c[2] = m_cen_mass[2];\n        c[3] = m_r;\n\t\tc[4] = m_mass;\n        coords.push_back(c);\n    } else {\n        m_leftchild->GetPriCoords(coords);\n        m_rightchild->GetPriCoords(coords);\n    }\n}\n\n/*!\n *  @brief Copy state-space and derived properties from source.\n *\n *  This function is like a limited assignment operator, except that the\n *  children are not copied and the pointers to the particles may need\n *  adjusting after this method has finished.\n *\n *  @param[in] source Pointer to the primary to be copied.\n */\nvoid BinTreePrimary::CopyParts(const BinTreePrimary *source)\n{\n    //! Set primary characteristics.\n    SetComposition(source->Composition());\n    SetValues(source->Values());\n    SetTime(source->LastUpdateTime());\n    SetCollDiameter(source->CollDiameter());\n    SetMobDiameter(source->MobDiameter());\n    SetSphDiameter(source->SphDiameter());\n    SetSurfaceArea(source->SurfaceArea());\n    SetVolume(source->Volume());\n    SetMass(source->Mass());\n    SetNumCarbon(source->NumCarbon());\n    SetFrag(source->Frag());\n\n    //! Set BinTreePrimary model characteristics.\n    m_numprimary              = source->m_numprimary;\n    m_primarydiam             = source->m_primarydiam;\n    m_children_radius         = source->m_children_radius;\n    m_children_vol            = source->m_children_vol;\n    m_children_surf           = source->m_children_surf;\n\tm_free_surf\t\t\t\t  = source->m_free_surf;\n\tm_sum_necks\t\t\t\t  = source->m_sum_necks;\n\tm_primaryvol\t\t\t  = source->m_primaryvol;\n    m_distance_centreToCentre = source->m_distance_centreToCentre;\n    m_cen_bsph                = source->m_cen_bsph;\n    m_cen_mass                = source->m_cen_mass;\n    m_r                       = source->m_r;\n    m_r2                      = source->m_r2;\n    m_r3                      = source->m_r3;\n    m_children_sintering      = source->m_children_sintering;\n    m_avg_sinter              = source->m_avg_sinter;\n    m_sint_rate               = source->m_sint_rate;\n    m_sint_time               = source->m_sint_time;\n\tm_frame_orient_z\t\t  = source->m_frame_orient_z;\n\tm_frame_orient_x\t\t  = source->m_frame_orient_x;\n\tm_Rg\t\t\t\t      = source->m_Rg;\n\tm_tracked\t\t\t\t  = source->m_tracked;\n\n    //! Set particles.\n    m_leftchild     = source->m_leftchild;\n    m_rightchild    = source->m_rightchild;\n    m_parent        = source->m_parent;\n    m_leftparticle  = source->m_leftparticle;\n    m_rightparticle = source->m_rightparticle;\n}\n\n/*!\n * @brief           Recursively set the sintering time\n *\n * Needed to ensure that every node has an up-to-date value of the\n * sintering time; otherwise coagulation and merge events can lose\n * this information.\n *\n * @param time      Total time for which particles have been sintered\n */\nvoid BinTreePrimary::SetSinteringTime(double time) {\n    m_sint_time = time;\n\n    // Update children\n    if (m_leftchild != NULL) {\n        m_leftchild->SetSinteringTime(time);\n        m_rightchild->SetSinteringTime(time);\n    }\n\n    // Update particles\n    if (m_leftparticle != NULL) {\n        m_leftparticle->SetSinteringTime(time);\n        m_rightparticle->SetSinteringTime(time);\n    }\n}\n\n/*!\n * @brief       Overload of the SetTime function for BinTreePrimary\n *\n * Sets the LDPA update time throughout the binary tree. This is important\n * as Merge can sometimes delete the originial root node, losing m_time\n * stored in m_primary. This potentially leads to longer dt LDPA action\n * times when UpdateParticle is called.\n *\n * @param t     LDPA update time\n */\nvoid BinTreePrimary::SetTime(double t) {\n    m_time = t;\n\n    // Set LDPA time of children\n    if (m_leftchild != NULL) {\n        m_leftchild->SetTime(t);\n        m_rightchild->SetTime(t);\n    }\n\n    // Set LDPA time of particles\n    if (m_leftparticle != NULL) {\n        m_leftparticle->SetTime(t);\n        m_rightparticle->SetTime(t);\n    }\n}\n\n/*!\n * @brief       Randomly selects a primary in the binary tree\n *\n * Select a primary uniformly at random from this particle\n * and descend the aggregate tree to find the primary.\n * Note that most BinTreePrimaries are nodes in a tree representing\n * connectivity within an aggregate, so it is necessary to\n * descend the tree to find a primary that really is a\n * primary.\n *\n * @param[in]   rng     Random number generator\n *\n * @return      Pointer to an object representing a physical primary\n */\nBinTreePrimary *BinTreePrimary::SelectRandomSubparticle(rng_type &rng)\n{\n    // We want to choose an integer uniformly on the range [0, m_numprimary - 1]\n    boost::random::uniform_smallint<int> uniformDistrib(0, m_numprimary - 1);\n\n    return SelectRandomSubparticleLoop(uniformDistrib(rng));\n\n}\n/*!\n * @brief       Helper function for SelectRandomSubparticle\n *\n * @param[in] target The primary to be selected\n *\n * @return      Pointer to the next node down the tree on the path\n*/\nBinTreePrimary *BinTreePrimary::SelectRandomSubparticleLoop(int target)\n{\n    if (m_leftchild==NULL) return this;\n    if (target < m_leftchild->m_numprimary)\n    {\n        return m_leftchild->SelectRandomSubparticleLoop(target);\n    }\n    else\n    {\n        return m_rightchild->SelectRandomSubparticleLoop(\n                target-(m_leftchild->m_numprimary));\n    }\n}\n\n/*!\n * @brief    Calculates the sintering level for particles connected by node.\n *\n * Unlike the original SilicaPrimary model; this model assumes that a single\n * primary particle (no tree structure) has a sintering level of 1.0. In the\n * case where it is part of a tree, 0.0 is returned so as to not cause\n * erroneous calculation of m_children_sintering.\n *\n * @return   Sintering level\n */\ndouble BinTreePrimary::SinteringLevel()\n{\n\tif (m_leftchild != NULL && m_rightchild != NULL) {\n\n\t\tdouble slevel(0.0);\n\n\t\t//! If the centre-centre separation is not tracked the sintering level is calculated \n\t\t//! as per Shekar et al. (2012)\n\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t// Calculate the spherical surface\n\t\t\tconst double spherical_surface =\n\t\t\t\t4 * PI * m_children_radius * m_children_radius;\n\n\t\t\tif (m_children_surf == 0.0) {\n\t\t\t\tslevel = 0.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tslevel = ((spherical_surface / m_children_surf) - TWO_ONE_THIRD)\n\t\t\t\t\t/ (1 - TWO_ONE_THIRD);\n\t\t\t}\n\n\t\t//! If the centre-centre separation is tracked, the sintering level is calculated\n\t\t//! as per Lindberg et al. (J. Comp. Phys. 397, 108799, (2019)):\n\t\t//! s = R_ij / min(r_i,r_j)\n\t\t}else{\n\t\t\tif (m_leftparticle != NULL && m_rightparticle != NULL) {\n\t\t\t\t\n\t\t\t\tdouble r_i = m_leftparticle->m_primarydiam/2.0;\n\t\t\t\tdouble r_j = m_rightparticle->m_primarydiam/2.0;\n\t\t\t\tdouble d_ij =  m_distance_centreToCentre;\n\t\t\t\tdouble x_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i)/(2.0*d_ij);\n\t\t\t\tdouble R_ij = sqrt(r_i*r_i - x_ij*x_ij);\n\n\t\t\t\tslevel = R_ij / min(r_i,r_j);\n\t\t\t}\n\t\t}\n\n\t\tif (slevel < 0.0) {\n\t\t\treturn 0.0;\n\t\t}\n\t\telse if (slevel > 1.0) {\n\t\t\treturn 1.0;\n\t\t}\n\t\telse return slevel;\n\n\t}\n\telse {\n\t\t// Particle is a primary\n\t\tm_children_surf = 0.0;\n\t\tm_children_radius = 0.0;\n\t\tm_children_vol = 0.0;\n\t\tif (m_parent == NULL) return 1.0;        // Single primary case\n\t\telse return 0.0;                         // Part of a tree\n\t}\n}\n\n/*!\n * @brief       Checks the sintering level of the particle\n *\n * If the sintering level is above 95%, Merge is called and the cache\n * is updated.\n *\n * @return      Boolean telling if the particle has sintered\n */\nbool BinTreePrimary::CheckSintering()\n{\n    bool hassintered=false;\n\n\n\tif(m_leftparticle != NULL) {\n\n\t\t// check whether condition for merger is met\n\t\tif (MergeCondition()) {\n\t\t\t Merge();\n\t\t//\t UpdateCache();\t//this is already done at the end of merge\n\t\t\t hassintered=true;\n\n\t\t\t // Check again because this node has changed\n\t\t\t CheckSintering();\n\t\t}\n\t}\n    if (m_leftchild!=NULL) {\n        hassintered = m_leftchild->CheckSintering();\n        hassintered = m_rightchild->CheckSintering();\n    }\n\n    return hassintered;\n}\n\n/*!\n * @brief       Checks if condition for merger is met\n *\n * @return      Boolean telling if the merger condition is met\n */\nbool BinTreePrimary::MergeCondition()\n{\n\tbool condition=false;\n\n\tif(m_leftparticle != NULL) {\n\t\t//! The condition for whether a particle has coalesced depends on whether\n\t\t//! the distance between the centres of primary particles is tracked. \n\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t//! If coordinates are not tracked, the condition depends on whether the rounding \n\t\t\t//! level exceeds an arbitrarily high threshold s > 0.95.\n\t\t\tcondition = (m_children_sintering > 0.95);\n\t\t} else {\n\n\t\t\tdouble r_i = m_leftparticle->m_primarydiam/2.0;\n\t\t\tdouble r_j = m_rightparticle->m_primarydiam/2.0;\n\t\t\tdouble d_ij =  m_distance_centreToCentre;\n\t\t\t\n\t\t\tif(d_ij <= 0.0){\n\t\t\t\t//ensures that particles are merged if the sintering step overshoots\n\t\t\t\tcondition = true;\n\t\t\t}else{\n\t\t\t\t//! If primary coordinates are tracked,\n\t\t\t\t//! primaries are merged when the neck radius is 95% of the smaller primary radius.\n\t\t\t\t//! The second condition ensures that primaries are merged even if sintering overshoots\n\t\t\t\t//! i.e. the neck crosses the centre of smaller primary\n\t\t\t\tdouble x_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i)/(2.0*d_ij);\n\t\t\t\tdouble R_ij = sqrt(r_i*r_i - x_ij*x_ij);\t//!neck radius\n\t\t\t\tcondition = R_ij/min(r_i,r_j) >= 0.95 || ( (pow(d_ij,2.0) - pow(max(r_i,r_j),2.0) + pow(min(r_i,r_j),2.0) )/(2.0*d_ij) ) <= 0.0;\n\t\t\t}\n\t\t}\n\t}\n\treturn condition;\n}\n\n/*!\n * @brief       Merges the left and right particles\n *\n * Considers two cases of particle structure. If the node only has two\n * primaries in its subtree, they are simply deleted and *this* becomes\n * the new primary. Otherwise, the subtrees are moved in the manner\n * explained in Markus Sander's thesis.\n *\n * @return      Pointer to new merged particle\n */\nBinTreePrimary &BinTreePrimary::Merge()\n{\n\t//! Declare pointers for coordinate/separation tracking model\n\tBinTreePrimary *small_prim; //!< smaller of the merging primaries\n\tBinTreePrimary *big_prim;\t//!< larger of the merging primaries\n\tBinTreePrimary *new_prim;\t//!< new (merged) primary\n\n\t//initialise parameters\n\tdouble r_big,r_small; //, d_ij, x_ij;\n\tdouble r_new = 0.0;\n\n\t//! If a merging primary is tracked save the frame orientation vectors\n\tCoords::Vector frame_x;\n\tCoords::Vector frame_z;\n\tbool update_tracking = false;\n\tif (m_rightparticle->m_tracked == true){\n\t\tupdate_tracking = true;\n\t\tm_rightparticle->m_tracked = false;\n\t\tframe_x = m_rightparticle->m_frame_orient_x;\n\t\tframe_z = m_rightparticle->m_frame_orient_z;\n\t}\n\telse if (m_leftparticle->m_tracked == true){\n\t\tupdate_tracking = true;\n\t\tm_leftparticle->m_tracked = false;\n\t\tframe_x = m_leftparticle->m_frame_orient_x;\n\t\tframe_z = m_leftparticle->m_frame_orient_z;\n\t}\n\n    // Make sure this primary has children to merge\n    if( m_leftchild!=NULL) {\n\n\t\t//! Update primaries\n\t\tm_leftparticle->UpdatePrimary();\n\t\tm_rightparticle->UpdatePrimary();\n\n\t\t//! If the centre to centre distance is tracked we need to know which is the smaller primary of the merging pair\n\t\tif(m_leftparticle->m_primarydiam > m_rightparticle->m_primarydiam){\n\t\t\tsmall_prim = m_rightparticle;\n\t\t\tbig_prim = m_leftparticle;\n\t\t}else{\n\t\t\tsmall_prim = m_leftparticle;\n\t\t\tbig_prim = m_rightparticle;\n\t\t}\n\n\t\tr_big = big_prim->m_primarydiam/2.0;\n\t\tr_small = small_prim->m_primarydiam/2.0;\n\n\t\t//! If primary coordinates (or separation) are tracked then we need to estimate the radius\n\t\t//! of the new merged primary, given the new merged volume and a list of necks with neighbours.\n\t\t//  Lindberg et al., J. Comp. Phys. 397, 108799, (2019):\n\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates()){\n\n\t\t\t//! Merge primary volumes and calculate new primary radius\n\t\t\tdouble V_new = small_prim->m_primaryvol + big_prim->m_primaryvol; //! Use the volume derived from the geometric properties \n\t\t\t// An alternative would be to use the composition derived volume. \n\t\t\t// This corrects the geometric volume to match the composition volume (see lower bound note below)\n\t\t//\tdouble V_new = small_prim->m_vol + big_prim->m_vol; \t\t\t\n\t\t\t\n\t\t\t//! Get list of neck areas\n\t\t\tfvector necks;\n\t\t\tsmall_prim->GetNecks(small_prim, this, necks);\n\t\t\tbig_prim->GetNecks(big_prim, this, necks);\n\t\t\t\n\t\t\t//! Estimate new primary diameter\n\t\t\t//! Use the Newton Raphson method to find new radius using the old radius as the initial guess\n\t\t\tdouble r_guess = r_big;\t// Initial guess\n\t\t\tdouble r_min = 0.0;\t\t// Lower bound\n\t\t\tdouble r_max = 10.0*r_big; // Assumed upper bound. Could also use std::numeric_limits<double>::max();\n\t\t\tint r_digits = static_cast<int>(0.6*std::numeric_limits<double>::digits);  // Just over half the number of digits suggested as precision in Boost manual for Newton Raphson\n\t\t\tconst boost::uintmax_t r_maxit = 20; // Maximum number of iterations to perform\n\t\t\tboost::uintmax_t r_it = r_maxit;\n\n\t\t\tr_new = boost::math::tools::newton_raphson_iterate(merge_radius_functor(V_new,necks),r_guess,r_min,r_max,r_digits,r_it);\n\n\t\t\t//sanity checks\n\t\t\tif (r_new < r_big*0.99){ // the radius should be larger than the radius of the larger of the merging primaries\n\t\t\t\tstd::cout << \"BinTreePrimary::Merge: r_new < r_big \\n\";\n\t\t\t\tassert(r_new >= r_big*0.99);\n\t\t\t}\n\t\t\tif (r_new > r_big*2.0){ // the new radius should not too much larger than old radius\n\t\t\t\tstd::cout << \"BinTreePrimary::Merge: large jump in primary radius \\n\";\n\t\t\t\tassert(r_new <= 2.0*r_guess);\n\t\t\t}\n\t\t\tif (!std::isnormal(r_new)){\n\t\t\t\tstd::cout << \"BinTreePrimary::Merge: Could not calculate new radius! \\n\";\n\t\t\t}\n\t\t\t\n\t\t\t//! Get the largest neck (area)\n\t\t\tdouble max_neck = 0.0;\n\t\t\tif (!necks.empty())\tmax_neck = *std::max_element(necks.begin(), necks.end());\n\t\t\t//! The lower bounds on the new radius are the old radius since new volume is merged\n\t\t\t//! and the largest neck radius\n\t\t\t//  Note: if the composition dervied volume is used in estimating the new radius then\n\t\t\t//\tthe old radius should be removed as a lower bound to allow for some adjustment\n\t\t\tr_min = std::max(pow(max_neck / M_PI, 0.5), r_big);\n\n\t\t\t//! Impose lower bound in case the Newton method fails to find a solution\n\t\t\tif (r_new < r_min){\n\t\t\t\tif ((abs(r_new - r_min) / r_min) > 1e-10)\n\t\t\t\t\tstd::cout << \"BinTreePrimary::Merge: Imposing lower bound on new radius! \\n\";\n\t\t\t\tr_new = r_min;\t\n\t\t\t}\n\n\t\t\t//! set diameter of larger primary to calculated diameter\n\t\t\tbig_prim->m_primarydiam = 2.0*r_new;\n\n\t\t}\n\n        if (m_leftchild==m_leftparticle && m_rightchild==m_rightparticle)\n        {\n            //! This node has only two primaries in its subtree, it is possible\n            //! that this node is not the root node and belongs to a bigger\n            //! particle.\n\n            // Sum up the components first\n            for (size_t i=0; i != m_comp.size(); i++) {\n                m_comp[i] = m_leftparticle->Composition(i) +\n                        m_rightparticle->Composition(i);\n            }\n\n\t\t\tnew_prim = this; //!< new primary\n\n\t\t\t//! Update quantities for coordinate/separation tracking model\n\t\t\t//! m_primarydiam of the new particle is the larger of the diameters of the merging particles\n\t\t\t//! If the centre to centre separation isn't tracked this will be changed to the spherical equivalent in the call to UpdatePrimary\n\t\t\tnew_prim->m_primarydiam = big_prim->m_primarydiam;\n\n\t\t\tif(m_pmodel->getTrackPrimaryCoordinates()){\n\t\t\t\tnew_prim->m_cen_bsph = big_prim->m_cen_bsph;\n\t\t\t\tnew_prim->m_cen_mass = big_prim->m_cen_mass;\n\t\t\t}\n\n            //! Update the pointers that pointed to the two former children\n\t\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t        ChangePointer(m_leftchild,this);\n\t\t\t    ChangePointer(m_rightchild,this);\n\t\t\t}else{\n\t\t\t\t//! If coordinates/separation are tracked the pointer to the larger primary is changed first\n\t\t\t\t//! so that primary properties are correctly calculated when adding neighbours\n\t\t\t\tChangePointer(big_prim, this, this, small_prim, r_new, r_big);\n\t\t\t\tChangePointer(small_prim, this, this, small_prim, r_new, r_small);\n\t\t\t}\n\n            // Delete the children (destructor is recursive for this class)\n            delete m_leftchild;\n            delete m_rightchild;\n            m_leftchild=NULL;\n            m_rightchild=NULL;\n            m_leftparticle=NULL;\n            m_rightparticle=NULL;\n\n            // Set the children properties to zero, this node has no\n            // more children\n            ResetChildrenProperties();\n            UpdatePrimary();\n\n            // Only update the cache on m_parent if the sintering level of\n            // m_parent if the sintering level won't call a merge on the\n            // parent node. Otherwise, the *this* memory address could be\n            // removed from the tree and segmentation faults will result!\n            if(m_parent!=NULL) {\n\t\t\t\tif (!m_parent->MergeCondition()) {\n                    m_parent->UpdateCache();\n                }\n            }\n        }else{\n\n\t\t\t//! If primary coordinates or primary separations are not tracked then\n\t\t\t//! select subtree to keep the tree balanced\n\t\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\n\t\t\t\tif (m_leftchild->m_numprimary<m_rightchild->m_numprimary)\n\t\t\t\t{\n\t\t\t\t\t// Append to left subtree because there are fewer primaries\n\t\t\t\t\t// (this is only to keep the tree balanced)\n\t\t\t\t\tBinTreePrimary *oldleftparticle = m_leftparticle;\n\t\t\t\t\tfor (size_t i=0; i != m_comp.size(); i++) {\n\t\t\t\t\t\tm_rightparticle->m_comp[i] =\n\t\t\t\t\t\t\t\tm_leftparticle->Composition(i) +\n\t\t\t\t\t\t\t\tm_rightparticle->Composition(i);\n\t\t\t\t\t}\n\n\t\t\t\t\tm_rightparticle->UpdatePrimary();\n\n\t\t\t\t\t// Set the pointers from the leftprimary to the rightprimary\n\t\t\t\t\toldleftparticle->ChangePointer(oldleftparticle,m_rightparticle);\n\t\t\t\t\tm_rightparticle->ChangePointer(m_rightparticle,m_rightparticle);\n\n\t\t\t\t\t// Set the pointer to the parent node\n\t\t\t\t\tif (oldleftparticle->m_parent->m_leftchild==oldleftparticle) {\n\t\t\t\t\t\toldleftparticle->m_parent->m_leftchild=m_rightchild;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toldleftparticle->m_parent->m_rightchild=m_rightchild;\n\t\t\t\t\t}\n\t\t\t\t\tm_rightchild->m_parent=oldleftparticle->m_parent;\n\n\t\t\t\t\tBinTreePrimary *oldleftchild    = m_leftchild;\n\t\t\t\t\tBinTreePrimary *oldparent       = m_parent;\n\n\t\t\t\t\t// Copy the properties of the former leftchild to this node\n\t\t\t\t\t// so that it can be removed from the aggregate tree structure\n\t\t\t\t\tCopyParts(oldleftchild);\n\n\t\t\t\t\t// Now break the links to the tree structure in oldleftchild\n\t\t\t\t\t// in order to free it\n\t\t\t\t\toldleftchild->m_leftchild   = NULL;\n\t\t\t\t\toldleftchild->m_rightchild  = NULL;\n\t\t\t\t\tdelete oldleftchild;\n\n\t\t\t\t\tm_parent = oldparent;\n\n\t\t\t\t\tif (m_leftchild!=NULL) {\n\t\t\t\t\t\tm_rightchild->m_parent=this;\n\t\t\t\t\t\tm_leftchild->m_parent=this;\n\t\t\t\t\t}\n\n\t\t\t\t\tdelete oldleftparticle;\n\n\t\t\t\t}else{\n\t\t\t\t\t// Append to right subtree\n\t\t\t\t\tBinTreePrimary *oldrightparticle = m_rightparticle;\n\t\t\t\t\tfor (size_t i=0; i != m_comp.size(); i++) {\n\t\t\t\t\t\tm_leftparticle->m_comp[i] =\n\t\t\t\t\t\t\t\tm_leftparticle->Composition(i) +\n\t\t\t\t\t\t\t\tm_rightparticle->Composition(i);\n\t\t\t\t\t}\n\n\t\t\t\t\tm_leftparticle->UpdatePrimary();\n\n\t\t\t\t\t// All pointers to m_leftparticle now point to oldright particle\n\t\t\t\t\toldrightparticle->ChangePointer(oldrightparticle,m_leftparticle);\n\t\t\t\t\tm_leftparticle->ChangePointer(m_leftparticle,m_leftparticle);\n\n\t\t\t\t\t// Set the pointer to the parent node\n\t\t\t\t\tif (oldrightparticle->m_parent->m_leftchild==oldrightparticle) {\n\t\t\t\t\t\toldrightparticle->m_parent->m_leftchild=m_leftchild;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toldrightparticle->m_parent->m_rightchild=m_leftchild;\n\t\t\t\t\t}\n\t\t\t\t\tm_leftchild->m_parent=oldrightparticle->m_parent;\n\n\t\t\t\t\tBinTreePrimary *oldrightchild=m_rightchild;\n\t\t\t\t\tBinTreePrimary *oldparent=m_parent;\n\n\t\t\t\t\t// Copy the properties of the former leftchild to this node\n\t\t\t\t\t// so that it can be removed from the aggregate tree structure\n\t\t\t\t\tCopyParts(oldrightchild);\n\n\t\t\t\t\t// Now break the links to the tree structure in oldrightchild\n\t\t\t\t\t// in order to free it\n\t\t\t\t\toldrightchild->m_leftchild = NULL;\n\t\t\t\t\toldrightchild->m_rightchild = NULL;\n\t\t\t\t\tdelete oldrightchild;\n\n\t\t\t\t\tm_parent=oldparent;\n\n\t\t\t\t\tif (m_leftchild!=NULL) {\n\t\t\t\t\t\tm_rightchild->m_parent=this;\n\t\t\t\t\t\tm_leftchild->m_parent=this;\n\t\t\t\t\t}\n\n\t\t\t\t\tdelete oldrightparticle;\n\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t//! If the coordinates/separations are tracked then the larger primary becomes the new primary\n\n\t\t\t\t//! the new (merged) primary\n\t\t\t\tnew_prim = big_prim;\n\n\t\t\t\t//! left/right flag\n\t\t\t\tbool newleft;\n\t\t\t\tif(new_prim == m_leftparticle){\n\t\t\t\t\tnewleft = true;\n\t\t\t\t}else{\n\t\t\t\t\tnewleft = false;\n\t\t\t\t}\n\n\t\t\t\t//! update composition\n\t\t\t\tBinTreePrimary *oldparticle = small_prim;\n\t\t\t\tfor (size_t i=0; i != m_comp.size(); i++) {\n\t\t\t\t\tnew_prim->m_comp[i] =\n\t\t\t\t\t\t\tm_leftparticle->Composition(i) +\n\t\t\t\t\t\t\tm_rightparticle->Composition(i);\n\t\t\t\t}\n\n\t\t\t\t//! update pointers to neighbours\n\t\t\t\tnew_prim->ChangePointer(new_prim,new_prim,this,small_prim,r_new,r_big);\n\t\t\t\toldparticle->ChangePointer(oldparticle,new_prim,this,small_prim,r_new,r_small);\n\n\t\t\t\t// Set the pointer to the parent node\n\t\t\t\tBinTreePrimary *oldchild = NULL;\n\t\t\t\tif(newleft){\n\t\t\t\t\tif (oldparticle->m_parent->m_leftchild==oldparticle) {\n\t\t\t\t\t\toldparticle->m_parent->m_leftchild=m_leftchild;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toldparticle->m_parent->m_rightchild=m_leftchild;\n\t\t\t\t\t}\n\t\t\t\t\tm_leftchild->m_parent=oldparticle->m_parent;\n\n\t\t\t\t\toldchild    = m_rightchild;\n\t\t\t\t}else{\n\t\t\t\t\tif (oldparticle->m_parent->m_leftchild==oldparticle) {\n\t\t\t\t\t\toldparticle->m_parent->m_leftchild=m_rightchild;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toldparticle->m_parent->m_rightchild=m_rightchild;\n\t\t\t\t\t}\n\t\t\t\t\tm_rightchild->m_parent=oldparticle->m_parent;\n\n\t\t\t\t\toldchild    = m_leftchild;\n\t\t\t\t}\n\t\t\t\tBinTreePrimary *oldparent = m_parent;\n\n\t\t\t\t// Copy the properties of the former leftchild to this node\n\t\t\t\t// so that it can be removed from the aggregate tree structure\n\t\t\t\tCopyParts(oldchild);\n\n\t\t\t\t// Now break the links to the tree structure in oldleftchild\n\t\t\t\t// in order to free it\n\t\t\t\toldchild->m_leftchild   = NULL;\n\t\t\t\toldchild->m_rightchild  = NULL;\n\t\t\t\tdelete oldchild;\n\n\t\t\t\tm_parent = oldparent;\n\n\t\t\t\tif (m_leftchild!=NULL) {\n\t\t\t\t\tm_rightchild->m_parent=this;\n\t\t\t\t\tm_leftchild->m_parent=this;\n\t\t\t\t}\n\n\t\t\t\tdelete oldparticle;\n\t\t\t}\n\n        }\n\n\t\t//if coordinates are tracked then update the tracked radii\n\t\tif(m_pmodel->getTrackPrimaryCoordinates()){\n\t\t\tnew_prim->setRadius(new_prim->m_primarydiam / 2.0);\n\t\t}\n\n\t\t//! Update tracking\n\t\tif(update_tracking == true){\n\t\t\tnew_prim->m_tracked = true;\n\t\t\tnew_prim->m_frame_orient_x = frame_x;\n\t\t\tnew_prim->m_frame_orient_z = frame_z;\n\t\t}\n\n\t\tUpdateCache();\n\n    }\n\n    return *this;\n}\n\n//! Returns f(r) and f'(r) for solving the new primary radius given a new volume using the Newton method\nstd::pair<double, double> BinTreePrimary::merge_radius_functor::operator()(double const& r)\n{\n\tdouble neck_vol(0.0);\n\tdouble neck_area(0.0);\n\tdouble fr(0.0), dr(0.0); // f(r) and f'(r)\n\n\tfvector::const_iterator ineck;\n\tfor(ineck = a_necks.begin(); ineck!=a_necks.end(); ineck++){\n\t\t// Lower bound on primary radius is imposed by largest neck radius\n\t\tdouble r_min = pow(*ineck/M_PI, 0.5);\n\n\t\tneck_vol += 2.0*r*r*r+pow(r*r-*ineck/M_PI , 1.5)-3.0*r*r*pow(r*r-*ineck/M_PI , 0.5);\n\t\tneck_area += 2.0*r*r - r*pow(r*r-*ineck/M_PI , 0.5) - r*r*r*pow(r*r-*ineck/M_PI, -0.5);\n\t}\n\n\t// Calculate sums of neck volumes and areas\n\tfr = a_vol - 4.0*M_PI*r*r*r/3.0 + M_PI*neck_vol/3.0;\n\tdr = -4.0*M_PI*r*r + M_PI*neck_area;\n\t\n\treturn std::make_pair(fr,dr);\n}\n\n/*!\n//function to return fvector of neck radii for merged primary\n//work up from primary and determine\n * @param[in] prim Pointer to merging primary\n * @param[in] node Pointer to merging node\n * @param[in] necks vector of neck areas\n */\nvoid BinTreePrimary::GetNecks(BinTreePrimary *prim, BinTreePrimary *node, fvector &necks){\n\n\tdouble d_ij = m_parent->m_distance_centreToCentre;\n\tdouble r_i = prim->m_primarydiam / 2.0;\n\tdouble r_j = 0.0;\n\tdouble x_ij = 0.0;\n\tdouble A_nij = 0.0;\n\n\t//! Check parent node is a neck joining prim but is not the merging neck\n\tif (m_parent->m_leftparticle == prim && m_parent != node) {\n\t\t//! right particle is a neighbour of prim\n\t\tr_j = m_parent->m_rightparticle->m_primarydiam/2.0;\t\t//! neighbour radius\n\t\tx_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i) / d_ij / 2.0;    //! distance from prim to neck\n\t\tA_nij = M_PI*(r_i*r_i - x_ij*x_ij);\t\t\t\t\t\t//! neck area\n\n\t\tnecks.push_back(A_nij);\t\t//! Add neck area to vector\n\n\t} else if(m_parent->m_rightparticle == prim && m_parent != node) {\n\t\t//! Left primary is a neighbour of prim\n\t\tr_j = m_parent->m_leftparticle->m_primarydiam/2.0;\t\t//! neighbour radius\n\t\tx_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i) / d_ij / 2.0;    //! distance from prim to neck\n\t\tA_nij = M_PI*(r_i*r_i - x_ij*x_ij);\t\t\t\t\t\t//! neck area\n\n\t\tnecks.push_back(A_nij);\t\t//! Add neck area to vector\n\n\t}\n\n\t//! Continue working up the binary tree\n\tif(m_parent->m_parent != NULL){\n\t\tm_parent->GetNecks(prim, node, necks);\n\t}\n}\n\n/*!\n * @brief       Changes pointer from source to target when centre-centre separation is tracked\n *\n * If a primary neighbours the smaller of the merging pair the centre to centre separation is\n * re-estmated as the smaller of the sum of the separation or the sum of primary radii.\n *\n * @param[in] source\t\tPointer to the original particle\n * @param[in] target\t\tPointer to the new particle\n * @param[in] node\t\t\tPointer to merging neck (non-leaf node)\n * @param[in] small_prim\tPointer to the smaller of the merging primaries\n * @param[in] r_new\t\t\tNew primary diameter\n * @param[in] r_old\t\t\tOld primary diameter\n*/\nvoid BinTreePrimary::ChangePointer(BinTreePrimary *source, BinTreePrimary *target, BinTreePrimary *node, \n\t\t\t\t\t\t\t\t\tBinTreePrimary *small_prim, double const r_new, double const r_old)\n{\n\n\tif(m_rightparticle == source) {\n\t\t//! left particle is a neighbour\n\t\tif (this != node){\n\t\t\t//! Not the merging node\n\n\t\t\tdouble d_ij_old = m_distance_centreToCentre;\t\t//!< Old centre to centre separation\n\t\t\tdouble r_j = m_leftparticle->m_primarydiam/2.0;\t\t//!< Radius of neighbour\n\t\t\tdouble x_ji = (d_ij_old*d_ij_old - r_old*r_old + r_j*r_j)/d_ij_old/2.0;\t\t//!< Neighbour centre to neck distance\n\n\t\t\t//! Calculate new centre to centre separation\n\t\t\tdouble d_ij_new = std::max(x_ji+ sqrt(x_ji*x_ji - r_j*r_j + r_new*r_new), x_ji - sqrt(x_ji*x_ji - r_j*r_j + r_new*r_new));\n\n\t\t\t//! Update centre to centre separation ensuring primaries are at least in point contact\n\t\t\tm_distance_centreToCentre = std::min(r_j + r_new, d_ij_new);\n\t\t\tassert(m_distance_centreToCentre >= 0.0);\n\n\t\t\t//! adjust coordinates of new neighbour and all its neighbour\n\t\t\t//! this translates the branch along old separation vector d_ik to new separation\n\t\t\tif(m_pmodel->getTrackPrimaryCoordinates()){\n\n\t\t\t\tCoords::Vector u_ik = UnitVector(m_leftparticle->boundSphCentre(), target->boundSphCentre());\t//!< old separation unit vector\n\t\t\t\tdouble d_ik = Separation(m_leftparticle->boundSphCentre(), target->boundSphCentre());\t\t\t//!< old separation distance\n\t\t\t\t//! Translate the neighbour\n\t\t\t\tm_leftparticle->TranslatePrimary(u_ik, d_ik - m_distance_centreToCentre);\n\t\t\t\t//! Translate all neighbours of the neighbour except the old small_prim\n\t\t\t\tm_leftparticle->TranslateNeighbours(m_leftparticle, u_ik, d_ik - m_distance_centreToCentre, small_prim);\n\t\t\t}\n\n\t\t\tm_rightparticle = target;\n\n\t\t}else{\n\t\t\tm_rightparticle = NULL;\n\t\t}\n\n    }\n\n    if(m_leftparticle == source){\n\t\t//! right particle is a neighbour\n\t\tif (this != node){\n\t\t\t//! Not the merging node\n\n\t\t\tdouble d_ij_old = m_distance_centreToCentre;\t\t\t//!< Old centre to centre separation\n\t\t\tdouble r_j = m_rightparticle->m_primarydiam/2.0;\t\t//!< Radius of neighbour\n\t\t\tdouble x_ji = (d_ij_old*d_ij_old - r_old*r_old + r_j*r_j)/d_ij_old/2.0;\t\t//!< Neighbour centre to neck distance\n\n\t\t\t//! Calculate new centre to centre separation\n\t\t\tdouble d_ij_new = std::max(x_ji+ sqrt(x_ji*x_ji - r_j*r_j + r_new*r_new), x_ji - sqrt(x_ji*x_ji - r_j*r_j + r_new*r_new));\n\n\t\t\t//! Update centre to centre separation ensuring primaries are at least in point contact\n\t\t\tm_distance_centreToCentre = std::min(r_j + r_new, d_ij_new);\n\t\t\t\n\t\t\tassert(m_distance_centreToCentre >= 0.0);\n\n\t\t\t//! adjust coordinates of new neighbour and all its neighbour\n\t\t\t//! this translates the branch along old separation vector d_ik to new separation\n\t\t\tif(m_pmodel->getTrackPrimaryCoordinates()){\n\n\t\t\t\tCoords::Vector u_ik = UnitVector(m_rightparticle->boundSphCentre(), target->boundSphCentre());\t//!< old separation unit vector\n\t\t\t\tdouble d_ik = Separation(m_rightparticle->boundSphCentre(), target->boundSphCentre());\t\t\t//!< old separation distance\n\t\t\t\t//! Translate the neighbour\n\t\t\t\tm_rightparticle->TranslatePrimary(u_ik, d_ik - m_distance_centreToCentre);\n\t\t\t\t//! Translate all neighbours of the neighbour except the old small_prim\n\t\t\t\tm_rightparticle->TranslateNeighbours(m_rightparticle, u_ik, d_ik - m_distance_centreToCentre, small_prim);\n\t\t\t}\n\n\t\t\tm_leftparticle = target;\n\n\t\t}else{\n\t\t\tm_leftparticle = NULL;\n\t\t}\n    }\n\n    // Update the tree above this sub-particle.\n    if (m_parent != NULL) {\n        m_parent->ChangePointer(source, target, node, small_prim, r_new, r_old);\n    }\n\n}\n\n/*!\n * @brief       Changes pointer from source to target\n *\n * The children surface is re-estimated using the spherical surface\n * and re-arranging the sintering level formula:\n * Cij = Ssph / (s * (1-2^{1/3}) + 2^{1/3})\n *\n * @param[in] source Pointer to the original particle\n * @param[in] target Pointer to the new particle\n*/\nvoid BinTreePrimary::ChangePointer(BinTreePrimary *source, BinTreePrimary *target)\n{\n\n\tif(m_rightparticle == source) {\n        m_rightparticle = target;\n        double sphericalsurface =\n            4 * PI * pow(3 * (m_leftparticle->Volume() +\n                    m_rightparticle->Volume()) /(4 * PI), TWO_THIRDS);\n        m_children_surf = sphericalsurface / (m_children_sintering *\n                (1.0 - TWO_ONE_THIRD) + TWO_ONE_THIRD);\n\t\t// Impose upper bound on the common surface area \n\t\t// equal to the sum of spherical primary surfaces.\n\t\tif((m_leftparticle->m_surf + m_rightparticle->m_surf) < m_children_surf){\n\t\t\t\tm_children_surf = m_leftparticle->m_surf + m_rightparticle->m_surf;\n\t\t}\n    }\n    if(m_leftparticle == source){\n        m_leftparticle = target;\n        double sphericalsurface =\n            4 * PI * pow(3 * (m_leftparticle->Volume() +\n                    m_rightparticle->Volume()) /(4 * PI), TWO_THIRDS);\n        m_children_surf = sphericalsurface / (m_children_sintering *\n                (1.0 - TWO_ONE_THIRD) + TWO_ONE_THIRD);\n\t\t// Impose upper bound on the common surface area\n\t\t// equal to the sum of spherical primary surfaces.\n\t\tif((m_leftparticle->m_surf + m_rightparticle->m_surf) < m_children_surf){\n\t\t\t\tm_children_surf = m_leftparticle->m_surf + m_rightparticle->m_surf;\n\t\t}\n    }\n    // Update the tree above this sub-particle.\n    if (m_parent != NULL) {\n        m_parent->ChangePointer(source, target);\n    }\n\n}\n\n/*!\n * @brief       Sets all of the properties of the children to zero\n *\n * Used after the children are coalesced\n */\nvoid BinTreePrimary::ResetChildrenProperties()\n{\n    m_children_radius   = 0.0;\n    m_children_vol      = 0.0;\n    m_children_surf     = 0.0;\n    m_children_sintering= 0.0;\n    m_avg_sinter        = 0.0;\n    m_sint_rate         = 0.0;\n\tm_distance_centreToCentre = 0.0;\n}\n\n/*!\n *  @brief Updates the properties of a primary.\n */\nvoid BinTreePrimary::UpdatePrimary(void)\n{\n    //! Call parent class UpdateCache.\n    Primary::UpdateCache();\n\n    //! Set specific features of this node.\n    //! If the primary centre-centre separation isn't tracked, the primary\n    //! coordinates or this is a single primary m_primarydiam and m_diam are\n    //! both the spherical equivalent diameter and the free surface area is the\n    //! sperhical surface area.\n    if(!(m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates()) || m_parent == NULL){\n\t\t//To Do (csl37): should not reset properties if this is a single primary due to a merge event\n\t\tm_primarydiam = m_diam;\n\t\tm_free_surf = m_surf;\n\t\tm_primaryvol = m_vol;\n\t\tm_sum_necks = 0.0;\n\t}else{\n\t\t//! Update overlapping primary model\n\t\tUpdateOverlappingPrimary();\n\t}\n\n    m_numprimary  = 1;\n\n    //! Initialisation of the radius of bounding sphere which is only relevant\n    //! if the primary coordinates are tracked.\n    if (m_pmodel->getTrackPrimaryCoordinates()) {\n        setRadius(m_primarydiam / 2.0);\n    }\n}\n\n/*!\n * @brief       Updates the BinTreePrimary cache from the root node\n *\n * Works up the tree to the root node and then calls UpdateCache\n *\n*/\nvoid BinTreePrimary::UpdateCacheRoot(void){\n\tif(m_parent != NULL){\n\t\tm_parent->UpdateCacheRoot();\n\t}else{\n\t\tUpdateCache(this);\n\t}\n}\n\n//! UpdateCache helper function\nvoid BinTreePrimary::UpdateCache(void)\n{\n    UpdateCache(this);\n}\n\n/*!\n * @brief       Updates the BinTreePrimary cache\n *\n * Updates the whole particle, from root to the lowest leaf-node.\n * Calculates the sintering level and merges particles (through Check\n * Sintering) if necessary. Only accurately calculates collision\n * diameter and other properties used outside of BinTreePrimary for\n * the root node.\n *\n * @param[in] root The root node of this particle\n*/\nvoid BinTreePrimary::UpdateCache(BinTreePrimary *root)\n{\n    // Update the children\n    if (m_leftchild!=NULL) {\n        m_leftchild->UpdateCache(root);\n        m_rightchild->UpdateCache(root);\n    }\n    // This is a primary\n    else {\n        // If it's a single particle, give it a sintering level of 1.0.\n        if (m_parent == NULL) m_avg_sinter = 1.0;\n        else m_avg_sinter = 0.0;\n        m_numprimary    = 1;\n\t\tm_Rg = 0.0;\n        UpdatePrimary();\n    }\n\n    // This is not a primary, sum up the properties\n    if (m_leftchild!=NULL)\n    {\n        // Sum up the components first\n        for (size_t i=0; i != m_comp.size(); i++) {\n            m_comp[i] = m_leftchild->m_comp[i] + m_rightchild->m_comp[i];\n        }\n\n        // Now recalculate derived properties\n        m_numprimary    = m_leftchild->m_numprimary +\n                m_rightchild->m_numprimary;\n        m_surf          = m_leftchild->m_surf + m_rightchild->m_surf;\n        m_primarydiam   = m_leftchild->m_primarydiam\n                + m_rightchild->m_primarydiam;\n        m_vol           = m_leftchild->m_vol + m_rightchild->m_vol;\n        m_mass          = m_leftchild->m_mass + m_rightchild->m_mass;\n\t\tm_free_surf\t\t= m_leftchild->m_free_surf + m_rightchild->m_free_surf;\n\t\tm_primaryvol\t= m_leftchild->m_primaryvol + m_rightchild->m_primaryvol;\n\t\t//titania phase transformation term\n\t\tm_phaseterm\t\t= m_leftchild->m_phaseterm + m_rightchild->m_phaseterm;\n\n\t\t//calculate bounding sphere\n\t\tcalcBoundSph();\n\n\t\t// updates m_children_radius\n\t\tif ((m_leftparticle!=NULL) && (m_rightparticle!=NULL)){\n\t\t\tm_children_radius = pow((3.0/(4.0*PI))*(m_leftparticle->Volume() + m_rightparticle->Volume()),(ONE_THIRD));\t\n\t\t}\n\n\t\t//! Particle tracking\n\t\tif (m_leftchild->m_tracked == true || m_rightchild->m_tracked == true) m_tracked = true;\n\n        // Calculate the sintering level of the two primaries connected by this node\n        m_children_sintering = SinteringLevel();\n        if (MergeCondition()) CheckSintering();\n\n        // Sum up the avg sintering level (now that sintering is done)\n        if((m_leftchild != NULL) && (m_rightchild != NULL)) {\n            m_avg_sinter = m_children_sintering +\n                    m_leftchild->m_avg_sinter + m_rightchild->m_avg_sinter;\n        }\n        else {\n            // This should only occur if CheckSintering has merged\n            m_avg_sinter = m_children_sintering;\n        }\n\n        // Calculate the different diameters only for the root node because\n        // this is the only part of the tree seen by the other code, for\n        // example, the coagulation kernel\n\t\tif (this->m_parent == NULL){\t//if this does not have a parent this is the root node \n             // Get spherical equivalent radius and diameter\n            double spherical_radius = pow(3 * m_vol / (4*PI), ONE_THIRD);\n            m_diam = 2 * spherical_radius;\n\n            // There are m_numprimary-1 connections between the primary\n            // particles\n            if (m_numprimary > 1)\n                m_avg_sinter = m_avg_sinter / (m_numprimary - 1);\n\n\t\t\t//! if the centre to centre distance is tracked then\n\t\t\t//! the surface area is the particle free surface area\n\t\t\t//! and the collision diameter is calculated using the\n\t\t\t//! primary coordinates\n\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\tm_surf = m_free_surf;\n\t\t\t\tm_dcol = CollisionDiameter();\n\t\t\t}else{\n\t\t\t\t\n\t\t\t\t//! If primary separations are tracked then\n\t\t\t\t//! the surface area is the particle free surface area\n\t\t\t\tif (m_pmodel->getTrackPrimarySeparation()){\n\t\t\t\t\tm_surf = m_free_surf;\n\t\t\t\t}else{\n\t\t\t\t\t//! Approxmiate the surface of the particle\n\t\t\t\t\t// (same as in ChangePointer)\n\t\t\t\t\tconst double numprim_1_3 = pow(m_numprimary, -1.0 * ONE_THIRD);\n\t\t\t\t\tm_surf = 4 * PI * spherical_radius * spherical_radius /\n\t\t\t\t\t\t(m_avg_sinter * (1 - numprim_1_3) + numprim_1_3);\n\t\t\t\t}\n\n\t\t\t\t//! Calculate dcol based-on formula given in Lavvas et al. (2011)\n\t\t\t\tconst double aggcolldiam = (6 * m_vol / m_surf) *\n\t\t\t\t\tpow(pow(m_surf, 3) / (36 * PI * m_vol * m_vol),\n\t\t\t\t\t(1.0 / m_pmodel->GetFractDim()));\n\t\t\t\tm_dcol = aggcolldiam;\n\n\t\t\t}\n\n\t\t\t//! Radius of gyration\n\t\t\tm_Rg = RadiusOfGyration();\n\n\t\t\t//! Mobility diameter\n            m_dmob = MobDiameter();\n\n        } else {\n            m_diam=0;\n            m_dmob=0;\n\t\t\tm_Rg = 0.0;\n        }\t\n\n    }\n\n}\n\n/*!\n *@brief        Overload of MobDiameter to return correct dmob\n *\n * This calculation is based on the work of Rogak et al., 1993 Aer. Sci.\n * Tech. 18:25-47, who give the calculation of dmob in the FM, SF and\n * transition regime.\n *\n * Currently, only the FM calculation is used, as the majority of experimental\n * systems which measure dmob run at continuum conditions.\n *\n * dmob,SF = 0.9 * dpri * sqrt(Df/(Df+2)) * npri^(1/Df)\n * dmob,FM = dpri * sqrt(0.802 * (npri - 1) + 1)\n *\n *@return   Mobility diameter of particle\n */\ndouble BinTreePrimary::MobDiameter() const\n{\n    double dmob(1.0);\n\n    // Is this a single particle?\n    if (m_leftchild == NULL && m_parent == NULL) {\n        dmob = m_diam;\n    } else {\n        // Presently hard-coded as T, P are abstracted from this\n        // function's view\n        // @TODO: somehow give this function access to Kn(T, P, d)\n\n        if (false) {\n            // SF regime mobility diameter\n            dmob *= 0.9 * m_primarydiam / (double)m_numprimary;\n            dmob *= sqrt(m_pmodel->GetFractDim() / (m_pmodel->GetFractDim() + 2));\n            dmob *= pow(m_numprimary, (1.0/m_pmodel->GetFractDim()));\n        } else {\n            // FM regime mobility diameter\n            dmob *= m_primarydiam / (double)m_numprimary;\n            dmob *= sqrt(0.802*(m_numprimary-1) + 1);\n        }\n\n        if (dmob < m_diam) dmob = m_diam;\n\n    }\n    return dmob;\n}\n\n\n//! Calculates the collision diameter based on the radius of gyration\n//! if primary coordinates are tracked\n//\tLindberg et al., J. Comp. Phys. 397, 108799, (2019)\ndouble BinTreePrimary::CollisionDiameter()\n{\n    double sum=0.0;\n    double dcol=0.0;\n    vector<fvector> coords;\n\t\t\n\t//! Calculate centre of mass\n\tthis->calcCOM();\n\t//! Save centre of mass coordinates\n\tdouble COM_x = m_cen_mass[0];\n\tdouble COM_y = m_cen_mass[1];\n\tdouble COM_z = m_cen_mass[2];\n\t\n\t//! Get a list of primary coordinates\n\tthis->GetPriCoords(coords);\n\n\t//! Calculate Rg (mass weighted)\n\t//! This is based on Eq. (2) in Lapuerta et al., A method to determine \n\t//! the fractal dimension of diesel soot agglomerates.\n\t//! Journal of Colloid Interface Science, 303:149-158. 2006.\n\t//! A modification is made to the radius of gyration of a single primary\n\t//! replacing r_gp = sqrt(3/5)*r_p with r_gp = r_p, as per Eq. (4) in \n\t//! Filippov et al., Fractal-like aggregates: Relation between morphology\n\t//! and physical properties. Journal of Colloid Interface Science, \n\t//! 229:261-273, 2000.\n\tfor (int i = 0; i!=coords.size(); ++i) {\n\t\t\n\t\t//! Add square of distance from the CoM weighted by mass\n\t\tsum += coords[i][4] * (pow((coords[i][0] - COM_x),2.0) + pow((coords[i][1] - COM_y),2.0) + pow((coords[i][2] - COM_z),2.0));\n\t\t\n\t\t//! Add square of primary radius weighted by mass\n\t\tsum += coords[i][4] * coords[i][3] * coords[i][3];\n\n\t}\n\n\tdcol = 2*sqrt(sum/m_mass);\n\n\treturn dcol;\n}\n\n/*!\n * @brief       Prints a graphical output of the binary tree structure\n *\n * Graph outputted in GraphViz format. Use command 'dot' to convert.\n * e.g. dot -Tpng -o name.png name.dat\n * for PNG terminal, plotting output file name.dat\n *\n * @param[in] filename Output filename\n*/\nvoid BinTreePrimary::PrintTree(string filename) const\n{\n    std::ofstream out;\n    out.open(filename.c_str());\n    out << \"digraph unix {\"<<endl;\n    out <<\"graph [rankdir = \\\"LR\\\"];\"<<endl;\n    PrintTreeLoop(out);\n    out << \"}\"<<endl;\n    out.close();\n}\n\n/*!\n * @brief       Helper function for printing tree.\n *\n * @param[in] out Output stream\n*/\nvoid BinTreePrimary::PrintTreeLoop(std::ostream &out)const\n{\n    // Non leaf-node case\n    if (m_leftchild!=NULL)\n    {\n        out << \"\\\" \" << this << \"\\\" \" << \" [shape = \\\"record\\\" label = \\\"\";\n        this->PrintTreeNode(out);\n        out <<\"\\\"];\"<<endl;\n\n        out << \"\\\" \" << this->m_leftchild << \"\\\" \" <<\n                \" [shape = \\\"record\\\" label = \\\"\";\n        this->PrintTreeNode(out);\n        out << \"|\" << this << \"\\\"];\"<<endl;\n\n        out << \"\\\" \" << this->m_rightchild << \"\\\" \" <<\n                \" [shape = \\\"record\\\" label = \\\"\";\n        this->PrintTreeNode(out);\n        out << \"|\" << this << \"\\\"];\"<<endl;\n\n        out<<\"\\\" \"<<this<<\"\\\" \"<<\"->\"<<\"\\\" \"<<this->m_leftchild<<\"\\\"; \"<<endl;\n        out<<\"\\\" \"<<this<<\"\\\" \"<<\"->\"<<\"\\\" \"<<this->m_rightchild<<\"\\\"; \"<<endl;\n        out<<\"\\\" \"<<this<<\"\\\" \"<<\"->\"<<\"\\\" \"<<this->m_leftparticle<<\n                \"\\\"[label=\\\"\"<<this<<\"\\\",color=\\\"blue\\\"]; \"<<endl;\n        out<<\"\\\" \"<<this<<\"\\\" \"<<\"->\"<<\"\\\" \"<<this->m_rightparticle<<\n                \"\\\"[label=\\\"\"<<this<<\"\\\",color=\\\"blue\\\"]; \"<<endl;\n        m_leftchild->PrintTreeLoop(out);\n        m_rightchild->PrintTreeLoop(out);\n    }\n\n    // Case when the node is a primary\n    else\n    {\n        out << \"\\\" \" << this << \"\\\" \" <<\n                \" [shape = \\\"record\\\" color=\\\"blue\\\" label = \\\"\";\n        this->PrintTreeNode(out);\n        out <<\"\\\"];\"<<endl;\n    }\n}\n\n/*!\n * @brief       Prints out each node of the tree\n *\n * @param[in] out Output stream\n*/\nvoid BinTreePrimary::PrintTreeNode(std::ostream &out) const\n{\n    out\n        << \"|m_surf=\"             << this->m_surf\n        << \"|m_vol=\"             << this->m_vol\n        << \"|m_numprimary=\"      << this->m_numprimary\n        << \"|m_child_sint=\"      << this->m_children_sintering\n        << \"|m_child_rad=\"       << this->m_children_radius\n        << \"|m_child_surf=\"      << this->m_children_surf;\n        for (size_t i=0; i != m_comp.size(); i++) {\n            out << \"|\" + string(m_pmodel->Components(i)->Name()) + \"=\" <<\n                    m_comp[i];\n        }\n    out\n        << \"|m_parent=\"          << this->m_parent\n        << \"|this=\" << this;\n}\n\nvoid BinTreePrimary::PrintComponents() const\n{\n    for (size_t i=0; i != m_comp.size(); i++) {\n        cout << m_pmodel->Components(i)->Name() << \" \" << m_comp[i] << \" \";\n    }\n    cout << endl;\n}\n\n/*!\n * @brief       Adjusts the particle after a surface rxn event\n *\n * Analogous to the implementation in Primary. The function will\n * however descend the tree to find a primary adjust. The surface area\n * and volume added to the particle is also rippled through the binary\n * tree.\n *\n * @param[in]   dcomp   Vector storing changes in particle composition\n * @param[in]   dvalues Vector storing changes in gas-phase comp\n * @param[in]   rng     Random number generator\n * @param[in]   n       Number of times for adjustment\n */\nunsigned int BinTreePrimary::Adjust(const fvector &dcomp,\n        const fvector &dvalues, rng_type &rng, unsigned int n)\n\n{\n\n    if (m_leftchild == NULL && m_rightchild == NULL) {\n        \t\t\n\t\tdouble dV(0.0);\n        double volOld = m_vol;\n\t\tdouble m_diam_old = m_diam;\n\t\tdouble r_old = m_primarydiam / 2.0;\n\n        // Call to Primary to adjust the state space\n        n = Primary::Adjust(dcomp, dvalues, rng, n);\n\n        // Stop doing the adjustment if n is 0.\n        if (n > 0) {\n            // Update only the primary\n            UpdatePrimary();\n\n\t\t\t//! If the distance between the centres of primary particles or the\n            //! primary coordinates are tracked, the rate of change in the\n            //! primary diameter is affected by its neighbours.\n\t\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\t\n\t\t\t\t//! Particle with more than one primary.\n\t\t\t\tif (m_parent != NULL) {\t\n\t\t\t\t\t\n\t\t\t\t\twhile (volOld <= m_vol){\n\n\t\t\t\t\t\t//! Initialisation of variables to adjust the primary diameter if the\n\t\t\t\t\t\t//! distance between the centres of primary particles is tracked.\n\t\t\t\t\t\tdouble r_i = m_primarydiam / 2.0;\t//!< Radius of primary particle i.\n\t\t\t\t\t\tdouble dr_max = 0.01*r_i;\t\t\t//!< Maximum change in primary radius during internal step (1% of primary radius)\n\t\t\t\t\t\tdouble dr = 0.0;\t\t\t\t\t//!< Change in radius of i\n\t\t\t\t\t\n\t\t\t\t\t\t//Calculate change in volume\n\t\t\t\t\t\tdV = dr_max * m_free_surf;\n\n\t\t\t\t\t\t//Calculate change in radius\n\t\t\t\t\t\tif (volOld + dV > m_vol){\n\t\t\t\t\t\t\tdr = (m_vol - volOld)*dr_max / dV;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tdr = dr_max;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//Update primary diameter\n\t\t\t\t\t\tm_primarydiam = 2.0* (r_i + dr);\n\n\t\t\t\t\t\t//! Update free surface area\n\t\t\t\t\t\tthis->UpdateOverlappingPrimary();\n\t\t\t\t\t\t\n\t\t\t\t\t\tvolOld += dV;\n\t\t\t\t\t}\n\n\t\t\t\t\t//if coordinates are tracked then update coordinate tracking properties\n\t\t\t\t\tif(m_pmodel->getTrackPrimaryCoordinates()){\n\t\t\t\t\t\tsetRadius(m_primarydiam / 2.0);\n\t\t\t\t\t\tthis->calcBoundSph();\t\t\t//(csl37) are these necessary here?\n\t\t\t\t\t\tthis->calcCOM();\n\t\t\t\t\t}\n\n\t\t\t\t\t//adjust composition of neighbours due to change in neck position\n\t\t\t\t\tthis->AdjustNeighbours(this, m_primarydiam / 2.0 - r_old, dcomp, dvalues, rng);\n\n\t\t\t\t} \n\t\t\t\t//! Single primary case: the primary diameter equals the\n                //! spherical diameter                \n                else {\n\t\t\t\t    m_primarydiam = m_diam;\n\n                    if (m_pmodel->getTrackPrimaryCoordinates()) {\n                        setRadius(m_primarydiam / 2.0);\n                    }\n\t\t\t\t}\n\t\t\t}\n            \n            //! If the distance between the centres of primary particles or the\n            //! primary coordinates is not tracked, just update the surface\n            //! area and work up the tree.\n            else {\n\t\t\t\tdV = m_vol - volOld;\n\t\t\t\tdouble dS(0.0);\n\n\t\t\t\tif (dV > 0.0) {\n\t\t\t\t\t//! Surface change due to volume addition.\n\t\t\t\t\tdS = dV * 2.0 * m_pmodel->GetBinTreeCoalThresh() / m_diam;\n\t\t\t\t}\n\t\t\t\t//! TODO: Implement surface area reduction?\n\n\t\t\t\t//! Climb back-up the tree and update the surface area and\n\t\t\t\t//! sintering of a particle.\n\t\t\t\tUpdateParents(dS);\n\t\t\t}\n\n\t\t\t//! Update the cache from the root node\n\t\t\tUpdateCacheRoot();\n        }\n    }\n    // Else this a non-leaf node (not a primary)\n    else\n    {\n\t\t\n\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\n\t\t\t//  Note (csl37): Adjust could be improved for deferred growth processes by distributing the new mass\n\t\t\t//\tover all or multiple primaries rather than applying all of the deferred growth to a single primary.\n\t\t\t//\n\t\t\t//! Primary selection based on the relative free surface area\n\t\t\t//! Work down tree selecting left/right child based on sum of primary free surface areas under node\n\t\t\t//! generate random number, use bernoulli with p=free_surf(leftchild)/free_surf(this)\n\t\t\tboost::bernoulli_distribution<> leftRightChooser(m_leftchild->m_free_surf/m_free_surf);\n\t\t\tif(leftRightChooser(rng)){\n\t\t\t\treturn m_leftchild->Adjust(dcomp, dvalues, rng, n);\n\t\t\t}else{\n\t\t\t\treturn m_rightchild->Adjust(dcomp, dvalues, rng, n);\n\t\t\t}\n\t\t\t\n\t\t}else{\n\n\t\t\treturn SelectRandomSubparticle(rng)->Adjust(dcomp, dvalues, rng, n);\n\t\t\n\t\t\t//Note (csl37): this only picks the left or right particle of the root node \n\t\t\t//and ignores the rest of the tree\n\t\t\t/*\n\t\t\t// Generate random numbers\n\t\t\tboost::bernoulli_distribution<> leftRightChooser;\n\t\t\t// Select particle\n\t\t\tif(leftRightChooser(rng))\n\t\t\t\treturn m_leftparticle->Adjust(dcomp, dvalues, rng, n);\n\t\t\telse\n\t\t\t\treturn m_rightparticle->Adjust(dcomp, dvalues, rng, n);\n\t\t\t*/\n\n\t\t}\n    }\n\n    // Update property cache.\n    // UpdateCache(this); // (csl37) No need to do this here: UpdateCache will be called again in Particle::Adjust\n\n    return n;\n\n}\n\n\n/*!\n * @brief       Adjusts the particle after a phase transformation event\n *\n * Analogous to the implementation in Primary. The function will\n * however descend the tree to find a primary adjust. \n *\n * @param[in]   dcomp   Vector storing changes in particle composition\n * @param[in]   dvalues Vector storing changes in gas-phase comp\n * @param[in]   rng     Random number generator\n * @param[in]   n       Number of times for adjustment\n */\nunsigned int BinTreePrimary::AdjustPhase(const fvector &dcomp,\n        const fvector &dvalues, rng_type &rng, unsigned int n)\n{\n\n\tif (m_leftchild == NULL && m_rightchild == NULL) {\n\n        // Call to Primary to adjust the state space\n        n = Primary::Adjust(dcomp, dvalues, rng, n);\n\t\t\n        // Stop doing the adjustment if n is 0.\n        if (n > 0) {\n            // Update only the primary\n            UpdatePrimary();\n        }\n    }\n    // Else this a non-leaf node (not a primary)\n\t// Select primary to adjust\n    else\n    {\t\n        return SelectRandomSubparticle(rng)->AdjustPhase(dcomp, dvalues, rng, n);\n    }\n\n    // Update property cache.\n    UpdateCache(this);\n\n    return n;\n}\n\n//Melting point dependent phase change\nvoid BinTreePrimary::Melt(rng_type &rng, Cell &sys){\n\n\t// Update the children\n\tif (m_leftchild != NULL) {\n\t\tm_leftchild->Melt(rng, sys);\n\t\tm_rightchild->Melt(rng, sys);\n\t}\n\telse{ // this is a primary\n\n\t\tPrimary::Melt(rng, sys);\n\t}\n}\n\n/*! \n* @brief\t\tAdjust composition of neighbours\n*\n* Called by Adjust() during a growth event to rebalance the \n* composition of a primary and its neighbours. Rebalancing is necessary\n* if the position of the neck has moved due to a change in radius.\n*\n* @param[in]   prim\t\tPointer to primary adjusted\n* @param[in]   delta_r  Change in radius\n* @param[in]   dcomp\tVector storing changes in particle composition\n* @param[in]   dvalues\tVector storing changes in gas-phase comp\n* @param[in]   rng\t\tRandom number generator\n*/\nvoid BinTreePrimary::AdjustNeighbours(BinTreePrimary *prim, const double delta_r, const fvector &dcomp,const fvector &dvalues, rng_type &rng){\n\t\n\tBinTreePrimary *neighbour = NULL;\n\n\t//! Check if parent node contains a neighbour of prim\n\tif (m_parent->m_leftparticle == prim) {\n\t\t//! right particle is a neighbour\n\t\tneighbour = m_parent->m_rightparticle;\n\t} else if (m_parent->m_rightparticle == prim) {\n\t\t//! left particle is a neighbour\n\t\tneighbour = m_parent->m_leftparticle;\n\t} \n\n\t//! Adjust neighbour's composition\n\tif (neighbour != NULL){\n\n\t\tdouble r_i = prim->m_primarydiam / 2.0;\t\t\t\t\t\t//!< primary radius\n\t\tdouble r_j = neighbour->m_primarydiam / 2.0;\t\t\t\t//!< neighbouring primary radius\n\t\tdouble d_ij = m_parent->m_distance_centreToCentre;\t\t\t//!< centre to centre separation\n\t\tdouble x_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i) / d_ij / 2.0;\t//!< distance neck to centre of primary p_i\n\t\tdouble A_nij = M_PI*(r_i*r_i - x_ij*x_ij);\t\t\t\t\t//!< neck area\n\n\t\tunsigned int max_n = 0;\n\n\t\t//! unit change in volume\n\t\t// this is the volume given by dcomp\n\t\tdouble uvol = 0.0; //!< unit change in volume\n\t\tdouble m = 0.0;\n\t\tfor (int i = 0; i != dcomp.size(); ++i) {\n\t\t\tm = m_pmodel->Components(i)->MolWt() * dcomp[i] / NA;\n\t\t\t//! max possible change to the composition leaving 1 component\n\t\t\tif (i > 0) {\n\t\t\t\tmax_n = min(max_n, static_cast<unsigned int>((neighbour->Composition(i) - 1.0) / dcomp[i]));\n\t\t\t}else{\n\t\t\t\tmax_n = static_cast<unsigned int>((neighbour->Composition(i) - 1.0) / dcomp[i]);\t//initial value for max_n\n\t\t\t}\n\t\t\tif (m_pmodel->Components(i)->Density() > 0.0)\n\t\t\t\tuvol += m / m_pmodel->Components(i)->Density();\n\t\t}\n\n\t\t//! change in volume of prim\n\t\tdouble dvol = A_nij * (r_i - delta_r) * delta_r / d_ij; //use the old radius (r_i - delta_r) here\n\t\t//! change in composition\n\t\tunsigned int dn = min(max_n, static_cast<unsigned int>(dvol / uvol));\n\n\t\t//! adjust primary compositions if change is large enough\n\t\tif (dvol > 0.0 && dn > 0){\n\t\t\t//! composition change vectors for the neighbour\n\t\t\tfvector dcomp_neighbour(dcomp.size());\n\t\t\tfvector dvalues_neighbour(dvalues.size());\n\t\t\tfor (int i = 0; i != dcomp.size(); ++i) {\n\t\t\t\tdcomp_neighbour[i] = -dcomp[i];\n\t\t\t}\n\t\t\tfor (int i = 0; i != dvalues.size(); ++i) {\n\t\t\t\tdvalues_neighbour[i] = -dvalues[i];\n\t\t\t}\n\t\t\t//! Adjust neighbour's composition (decrease)\n\t\t\tunsigned int n = Primary::Adjust(dcomp_neighbour, dvalues_neighbour, rng, dn);\n\t\t\t//! Adjust primary's composition (increase)\n\t\t\tunsigned int m = Primary::Adjust(dcomp, dvalues, rng, n);\n\t\t\tassert(m == n); //decrease in neighbour's composition must be equal to increase in primary's composition\n\t\t}\n\t}\n\n\t//! Continue working up the binary tree\n\tif (m_parent->m_parent != NULL){\n\t\tm_parent->AdjustNeighbours(prim,delta_r,dcomp,dvalues,rng);\n\t}\n}\n\n\n/*! Updates primary free surface area and volume\n*\n* @param[in]   this\t\tPrimary to update\n*/\nvoid BinTreePrimary::UpdateOverlappingPrimary(){\n\n\t//! Get sum of cap areas and volumes\n\tdouble CapAreas = 0.0;\t\t\t//!< Contribution from neighbours to free surface area\n\tdouble CapVolumes = 0.0;\t\t//!< Contribution from neighbours to volume\n\tdouble SumNecks = 0.0;\t\t\t//!< Sum of necks * r_i / x_ij\n\tSumCaps(this, CapAreas, CapVolumes, SumNecks);\n\t\n\t//! Update free surface area\n\t//if the calculated area is negative (too many overlaps) then set m_free_surf = 0.0\n\tm_free_surf = max(M_PI*m_primarydiam*m_primarydiam - CapAreas, 0.0);\n\n\t//! Update primary volume\n\t//if calculated volume is negative (too many overlaps) then set m_primaryvol = 0.0\n\tm_primaryvol = max( M_PI*pow(m_primarydiam,3.0)/6.0 - CapVolumes , 0.0);\n\n\t//! Update sum of necks \n\tm_sum_necks = SumNecks;\n\n\t//sanity checks for debugging\n\tassert(m_sum_necks >= 0.0);\n\tassert(m_free_surf >= 0.0);\n\n}\n\n/*!\n * @brief       Identify neighbours and sum their cap areas and volumes\n *\n * Works up the binary tree identifying the neighbours of the adjusted primary \n * and sums the contribution from neighbours to the free surface area.\n * All neighbours of the primary being adjusted are left/rightparticles of nodes directly \n * above it.\n * \n * @param[in]   prim\t\tPointer to the primary being adjusted\n * @param[in]   CapAreas\tSum of cap areas\n * @param[in]   CapVolumes\tSum of cap volumes\n */\nvoid BinTreePrimary::SumCaps(BinTreePrimary *prim, double &CapAreas, double &CapVolumes, double &SumNecks){\n\t\n\tdouble d_ij = m_parent->m_distance_centreToCentre;\n\tdouble r_i = prim->m_primarydiam / 2.0;\n\tdouble r_j = 0.0;\n\tdouble x_ij = 0.0;\n\n\t//! Check if a neighbour of prim\n\tif (m_parent->m_leftparticle == prim) {\n\t\t\n\t\t//! Right primary is a neighbour\n\t\tr_j = m_parent->m_rightparticle->m_primarydiam / 2.0;\n\t\tx_ij = min( ( pow(d_ij,2.0) - pow(r_j,2.0) + pow(r_i,2.0) ) / ( 2.0*d_ij ), r_i); //ensure -r_i <= x_ij <= r_i\n\t\tx_ij = max( x_ij, -r_i );\n\n\t\t//! Calculate cap area and add to sum\n\t\tCapAreas += 2*M_PI*(r_i*r_i - r_i*x_ij);\n\n\t\t//! Calculate cap volume and add to sum\n\t\tCapVolumes += M_PI * (2*pow(r_i,3.0) + pow(x_ij,3.0) - 3.0*pow(r_i,2.0)*x_ij ) /3.0;\n\n\t\t//! Neck area * r_i / x_ij\n\t\tSumNecks +=  abs(M_PI*(r_i*r_i - x_ij*x_ij) * r_i / x_ij);\n\n\t} else if(m_parent->m_rightparticle == prim) {\n\t\t\n\t\t//! Left primary is a neighbour\n\t\tr_j = m_parent->m_leftparticle->m_primarydiam / 2.0;\n\t\tx_ij = min( ( pow(d_ij,2.0) - pow(r_j,2.0) + pow(r_i,2.0) ) / ( 2.0*d_ij ), r_i);\t//ensure -r_i <= x_ij <= r_i\n\t\tx_ij = max( x_ij, -r_i );\n\n\t\t//! Calculate cap area and add to sum\n\t\tCapAreas += 2*M_PI*(r_i*r_i - r_i*x_ij);\n\n\t\t//! Calculate cap volume and add to sum\n\t\tCapVolumes += M_PI * (2*pow(r_i,3.0) + pow(x_ij,3.0) - 3.0*pow(r_i,2.0)*x_ij ) /3.0;\n\t\n\t\t//! Neck area * r_i / x_ij\n\t\tSumNecks += abs(M_PI*(r_i*r_i - x_ij*x_ij) * r_i / x_ij);\n\n\t}\n\n\t//sanity checks for debugging\n\tassert(r_i >= 0.0);\n\tassert(r_j >= 0.0);\n\tassert(SumNecks >= 0.0);\n\tassert(2*M_PI*(r_i*r_i - r_i*x_ij) >= 0.0); //cap area\n\n\t//! Continue working up the binary tree\n\tif(m_parent->m_parent != NULL){\n\t\tm_parent->SumCaps(prim, CapAreas, CapVolumes, SumNecks);\n\t}\n}\n\n/*!\n * @brief       Identify neighbours and update centre to centre separation and \n *\t\t\t\tcoordinates except for specified neighbour.\n *\n * Works up the binary tree identifying the neighbours of the adjusted primary \n * and updates the centre to centre separation. Also sums the contribution from\n * neighbours to the free surface area.\n *\n * @param[in]   prim\t\t\tPointer to the primary being adjusted\n * @param[in]   delta_r\t\t\tChange in radius of prim\n * @param[in]   prim_ignore\t\tPointer to the primary to be ignored\n */\nvoid BinTreePrimary::UpdateConnectivity(BinTreePrimary *prim, double delta_r, BinTreePrimary *prim_ignore){\n\t\n\tdouble d_ij = m_parent->m_distance_centreToCentre;\n\tdouble r_i = prim->m_primarydiam / 2.0;\n\tdouble r_j = 0.0;\n\tdouble x_ij = 0.0;\n\tBinTreePrimary *neighbour = NULL;\n\n\t//! check if a neighbour of prim\n\tif (m_parent->m_leftparticle == prim && m_parent->m_rightparticle != prim_ignore ) {\n\t\t//! right particle is a neighbour\n\t\tneighbour = m_parent->m_rightparticle;\n\t\tr_j = neighbour->m_primarydiam / 2.0;\n\t} else if(m_parent->m_rightparticle == prim &&  m_parent->m_leftparticle != prim_ignore ) {\n\t\t//! left particle is a neighbour\n\t\tneighbour = m_parent->m_leftparticle;\n\t\tr_j = neighbour->m_primarydiam / 2.0;\n\t} else {\n\t\t//! not a neighbour\n\t\tr_j = 0.0;\n\t}\n\n\tif(r_j > 0.0){\n\n\t\tdouble d_ij_old = d_ij;\n\t\tx_ij = ( pow(d_ij,2.0) - pow(r_j,2.0) + pow(r_i,2.0) ) / ( 2.0*d_ij );\n\t\t//! update centre to centre separation\n\t\t//making sure centre to centre separation remains smaller than the sum of the radii\n\t\td_ij = min(d_ij + r_i * delta_r / x_ij, r_i+r_j+delta_r);\n\t\tdouble d_ij_min = max(r_i - r_j, r_j - r_i); //!< minimum separation \n\t\t//and larger than the minimum possible separation (where one primary enevelopes the other)\n\t\td_ij = max(d_ij, d_ij_min);\n\n\t\tm_parent->m_distance_centreToCentre = d_ij;\n\t\t\n\t\t//! if primary coordinates are tracked then we need to update the coordinates of the neighbour \n\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t//! get (unit) vector separating prim and neighbour\n\t\t\tCoords::Vector u = UnitVector(prim->boundSphCentre(), neighbour->boundSphCentre()); \n\t\t\tdouble delta_d = d_ij-d_ij_old; //!< change in separation (magnitude)\n\t\t\t//! translate the neighbour \n\t\t\tneighbour->TranslatePrimary(u, delta_d);\n\t\t\t//! translate all neighbours of the neighbour except prim\n\t\t\tneighbour->TranslateNeighbours(neighbour,u, delta_d, prim);\n\t\t}\n\t}\n\n\t//continue working up the binary tree\n\tif(m_parent->m_parent != NULL){\n\t\tm_parent->UpdateConnectivity(prim, delta_r, prim_ignore);\n\t}\n}\n\n\n/*!\n * @brief       Updates the surface area and sintering level of all parents\n *\n * @param[in]   dS      Surface area increment to adjust area by\n */\nvoid BinTreePrimary::UpdateParents(double dS) {\n    if (m_parent != NULL) {\n        m_parent->m_children_surf += dS;\n        m_parent->m_children_sintering = m_parent->SinteringLevel();\n        //m_parent->UpdateCache();\t//updating here may cause a seg fault if a merger event occurs\n    }\n}\n\n/*!\n * @brief       Adjusts the particle after an IntP event\n *\n * @param[in]   dcomp   Vector storing changes in particle composition\n * @param[in]   dvalues Vector storing changes in gas-phase comp\n * @param[in]   rng     Random number generator\n * @param[in]   n       Number of times for adjustment\n */\nunsigned int BinTreePrimary::AdjustIntPar(const fvector &dcomp,\n        const fvector &dvalues, rng_type &rng, unsigned int n)\n\n{\n    if(m_numprimary == 1) {\n        // Call to Primary to adjust the state space\n        n = Primary::AdjustIntPar(dcomp, dvalues, rng, n);\n    } else {\n        return SelectRandomSubparticle(rng)->Adjust(dcomp, dvalues, rng, n);\n        // Generate random numbers\n        //boost::bernoulli_distribution<> leftRightChooser;\n\n        // Select particle\n        //if(leftRightChooser(rng))\n      //return m_leftparticle->AdjustIntPar(dcomp, dvalues, rng, n);\n      //else\n      //return m_rightparticle->AdjustIntPar(dcomp, dvalues, rng, n);\n    }\n    // Update property cache.\n    UpdateCache();\n    return n;\n\n}\n\n/*!\n * @brief       Sinters particles for time dt\n *\n * This function only operates on non-leaf nodes. It begins at the root\n * node, which sinters for time dt. It then descends the tree to sinter\n * nodes below the root. If the sintering level rises above 95%, Merge\n * is called and the particles are combined.\n *\n * @param[in]   dt      Time for which to sinter\n * @param[in]   sys     Environment for particles\n * @param[in]   model   Sintering model to apply\n * @param[in]   rng     Random number generator\n * @param[in]   wt      Statistical weight\n */\nvoid BinTreePrimary::Sinter(double dt, Cell &sys,\n                            const Processes::SinteringModel &model,\n                            rng_type &rng,\n                            double wt)\n{\n    // Only update the time on the root node\n    if (m_parent == NULL) {\n        m_sint_time += dt;\n        SetSinteringTime(m_sint_time);\n    }\n\n    // Do only if there is a particle to sinter\n    if (m_leftparticle!=NULL && m_rightparticle!=NULL) {\n\n\t\tSinterNode(dt, sys, model, rng, wt);\n\n\t\t// Check if the sintering level is above the threshold, and merge\n\t\tif (MergeCondition()) {\n            CheckSintering();\n\t\t}\n\n\t\tif (m_leftchild != NULL && m_rightchild != NULL) {\n            m_leftchild->Sinter(dt, sys, model, rng, wt);\n            m_rightchild->Sinter(dt, sys, model, rng, wt);\n        }\n\n\t\tUpdateCache();\n\n\t\tm_children_sintering = SinteringLevel();\n    }\n\n}\n\n//! Returns the sintering rate\ndouble BinTreePrimary::GetSintRate() const\n{\n    double sint_rate = m_sint_rate;\n    if(m_leftchild!=NULL)\n    {\n        sint_rate += (m_leftchild->GetSintRate() +\n                m_rightchild->GetSintRate());\n    }\n\n    return sint_rate;\n}\n\n/*!\n *\n * Sinters the node in the binary tree for time dt\n *\n * @param[in]   dt      Time for which to sinter\n * @param[in]   sys     Environment for particles\n * @param[in]   model   Sintering model to apply\n * @param[in]   rng     Random number generator\n * @param[in]   wt      Statistical weight\n */\nvoid BinTreePrimary::SinterNode(\n        double dt,\n        Cell &sys,\n        const Processes::SinteringModel &model,\n        rng_type &rng,\n        double wt\n        ) {\n\n\t// Declare time step variables.\n\tdouble t1=0.0, delt=0.0, tstop=dt;\n\tdouble r=0.0;\n\n\t// The scale parameter discretises the delta-S when using\n\t// the Poisson distribution.  This allows a smoother change\n\t// (smaller scale = higher precision).\n\tdouble scale = 0.01;\n\n    //! The sintering model depends on whether the distance between the centres\n    //! of primary particles or the coordinates of the primary particles are\n    //! tracked. If tracked, sintering results in a decrease in the distance\n    //! between the primaries and an increase in their diameters. If not,\n    //! sintering results in a decrease in the common surface between the\n    //! primaries.\n    if (!(m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())) {\n\n\t\t// Calculate the spherical surface\n\t\tconst double spherical_surface=4*PI*m_children_radius*m_children_radius;\t\n\n\t\t// Define the maximum allowed change in surface\n\t\t// area in one internal time step (10% spherical surface).\n\t\tdouble dAmax = 0.1 * spherical_surface;\n\n\t\t// Perform integration loop.\n\t\twhile (t1 < tstop)\n\t\t{\n\t\t\t// Calculate sintering rate.\n\t\t\tr = model.Rate(m_time+t1, sys, *this);\n\n\t\t\tif (r > 0) {\n\t\t\t\t// Calculate next time-step end point so that the\n\t\t\t\t// surface area changes by no more than dAmax.\n\t\t\t\tdelt = dAmax / max(r, 1.0e-300);\n\n\t\t\t\t// Approximate sintering by a poisson process.  Calculate\n\t\t\t\t// number of poisson events.\n\t\t\t\tdouble mean;\n\n\t\t\t\tif (tstop > (t1+delt)) {\n\t\t\t\t\t// A sub-step, we have changed surface by dAmax, on average\n\t\t\t\t\tmean = 1.0 / scale;\n\t\t\t\t} else {\n\t\t\t\t\t// Step until end.  Calculate degree of sintering explicitly.\n\t\t\t\t\tmean = r * (tstop - t1) / (scale*dAmax);\n\t\t\t\t}\n\t\t\t\tboost::random::poisson_distribution<unsigned, double> repeatDistribution(mean);\n\t\t\t\tconst unsigned n = repeatDistribution(rng);\n\n\t\t\t\t// Adjust the surface area.\n\t\t\t\tif (n > 0) {\n\t\t\t\t\tm_children_surf -= (double)n * scale * dAmax;\n\n\t\t\t\t\t// Check that primary is not completely sintered.\n\t\t\t\t\tif (m_children_surf <= spherical_surface) {\n\t\t\t\t\t\tm_children_surf = spherical_surface;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Set t1 for next time step.\n\t\t\t\tt1 += delt;\n\t\t\t}\n\n\t\t}\n\n\t} else {\n        //! Define the maximum allowed change (1%) in the distance between the\n        //! centres of primary particles in one internal time step. In the case\n        //! of pure sintering it was found that if the allowed change is too\n        //! large (~10%) a significant error is incurred in the final spherical\n        //! volume determined through comparisons with the mass-derived volume.\n        //! Note that the smaller the distance is, the smaller the changes are.\n\n\t\t///////////////////////////////////////////////////////\n\t\t/// References to equations in Langmuir 27:6358 (2011).\n\t\t///////////////////////////////////////////////////////\n\n\t\t//make sure particles are up to date\n\t\tm_leftparticle->UpdatePrimary();\n\t\tm_rightparticle->UpdatePrimary();\n\t\t\n\t\tdouble dd_ij_Max = m_distance_centreToCentre / 100.0;\n\n        while (t1 < tstop) {\n\t\t\t//! Definition of variables\n\t\t\tdouble r_i = this->m_leftparticle->m_primarydiam / 2.0;\n            double r_j = this->m_rightparticle->m_primarydiam / 2.0;\n\t\t\tdouble d_ij = m_distance_centreToCentre;\n\t\t\n            double d_ij2 = pow(d_ij, 2.0); \n            double r_i2 = pow(r_i, 2.0);\n            double r_j2 = pow(r_j, 2.0);\n            double r_i4 = pow(r_i, 4.0);\n            double r_j4 = pow(r_j, 4.0);\n\t\t\t\n\t\t\t//! Continue if primaries have not coalesced\n            if (!MergeCondition()) {\n\n\t\t\t\t//! Due to rounding, x_i and x_j are sometimes calculated to be larger \n\t\t\t\t//! than the respective primary radii resulting in a negative neck area.\n\t\t\t\t//! Therefore we take the smaller of x_i and r_i.\n\t\t\t\tdouble x_i = min((d_ij2 - r_j2 + r_i2) / (2.0 * d_ij),r_i); //!< Eq. (3b).\n\t\t\t\tdouble x_j = min((d_ij2 - r_i2 + r_j2) / (2.0 * d_ij),r_j); //!< Eq. (3b).\n\t\t\t\tdouble A_n = M_PI * (r_i2 - pow(x_i, 2.0));        //!< Eq. (4).\n\t\t\t\n\t\t\t\t//declare more variables\n\t\t\t\tdouble dd_ij_dt=0.0;\n\t\t\t\tdouble R_n = 0.0;\n\t\t\t\tdouble r4_tau = 0.0;\n\t\t\t\tdouble tau = 0.0;\n\t\t\t\tdouble gamma_eta = 0.0;\n\n\t\t\t\t//! Sintering model dependent part\n\t\t\t\t//! Viscous flow model\n\t\t\t\tif(model.Type() == Processes::SinteringModel::ViscousFlow){\n\t\t\t\t\t\t\n\t\t\t\t\t//! In Section 3.1.2 of Langmuir 27:6358 (2011), it is argued that\n\t\t\t\t\t//! the smaller particle dominates the sintering process.\n\t\t\t\t\tif (r_i <= r_j) {\n\t\t\t\t\t\ttau = model.SintTime(sys, *this->m_leftparticle); //!< The left particle is smaller than the right. \n\t\t\t\t\t} else {\n\t\t\t\t\t\ttau = model.SintTime(sys, *this->m_rightparticle); //!< The right particle is smaller than the left.\n\t\t\t\t\t}\n\n\t\t\t\t\t//! Gamma is the surface tension and eta is the viscosity, and the\n\t\t\t\t\t//! ratio (gamma/eta) can be related to tau.\n\t\t\t\t\t//! J. Colloid Interface Sci. 140:419 (1990).\n\t\t\t\t\tgamma_eta = min(r_i, r_j) / tau;\n\n\t\t\t\t\t//! Eq. (14a).\n\t\t\t\t\tdd_ij_dt = 4.0 * r_i * r_j * d_ij2 * (r_i + r_j) * gamma_eta /\n\t\t\t\t\t\t\t\t((r_i + r_j + d_ij) * (r_i4  + r_j4 - 2.0 * r_i2 * r_j2 + 4.0 * d_ij * r_i * r_j *(r_i + r_j) - d_ij2 * (r_i2 + r_j2)));\n\n\t\t\t\t//! Grain boundary diffusion model \n\t\t\t\t}else if(model.Type() == Processes::SinteringModel::GBD){ \n\n\t\t\t\t\t//! If the particles are in point contact set an initial neck radius of 1% \n\t\t\t\t\t//! of the smaller primary radius, otherwise dd_ij_dt would be undefined\n\t\t\t\t\tif(A_n <= 0.0){\n\t\t\t\t\t\tR_n = 0.01*min(r_i,r_j);\n\t\t\t\t\t\tA_n = M_PI * R_n * R_n;\n\t\t\t\t\t\tx_i = sqrt(r_i2 - R_n * R_n);\n\t\t\t\t\t\tx_j = sqrt(r_j2 - R_n * R_n);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tR_n = sqrt(A_n / M_PI);\n\t\t\t\t\t}\n\n\t\t\t\t\t//! The primary radius in the numerator cancels with the diameter dependence of tau\n\t\t\t\t\t//! so we can calculate this for only one of the primaries.\n\t\t\t\t\t//! Use smaller primary in case a minimum diameter is imposed for sintering\n\t\t\t\t\t//  In SintTime the diameter is calculated as 6.0 * m_vol / m_surf\n\t\t\t\t\t//  so r = 3.0 * m_vol / m_surf\n\t\t\t\t\tBinTreePrimary * small_prim;\n\t\t\t\t\tif (r_i <= r_j){\n\t\t\t\t\t\tsmall_prim = m_leftparticle;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tsmall_prim = m_rightparticle;\n\t\t\t\t\t}\n\t\t\t\t\tdouble r4 = pow(3.0 * small_prim->m_vol / small_prim->m_surf, 4.0);\n\t\t\t\t\tr4_tau = r4 / model.SintTime(sys, *small_prim);\n\n\t\t\t\t\t//! J Aerosol Sci 46:7-19 (2012) Eq. (A6)\n\t\t\t\t\t//! dx_i_dt + dx_j_dt\n\t\t\t\t\t//! (this is missing a minus sign, which is accounted for below)\n\t\t\t\t\tdd_ij_dt = r4_tau * ( 1/(r_i - x_i) + 1/(r_j - x_j) - 2/R_n ) / A_n;\n\n\t\t\t\t//Other model are not coded\n\t\t\t\t}else{\n\t\t\t\t\tstd::cout<<\"Sintering model not coded\"<<endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t//! Get surface area and subtract mutual contribution\n\t\t\t\tdouble A_i = std::max(0.0,m_leftparticle->m_free_surf + m_leftparticle->m_sum_necks - M_PI*(r_i*r_i - x_i*x_i)*r_i/x_i);\n\t\t\t\tdouble A_j = std::max(0.0,m_rightparticle->m_free_surf + m_rightparticle->m_sum_necks - M_PI*(r_j*r_j - x_j*x_j)*r_j / x_j);\n\n\t\t\t\t//! @todo Remove derivation and replace with reference to preprint\n\t\t\t\t//!       or paper if results do get published.\n\t\t\t\tdouble B_i = (-r_j*A_n*A_n - x_j*A_j*A_n)/(A_i*A_j*d_ij + r_i*A_j*A_n + r_j*A_i*A_n);\n\t\t\t\tdouble B_j = (-r_i*A_n*A_n - x_i*A_i*A_n)/(A_j*A_i*d_ij + r_j*A_i*A_n + r_i*A_j*A_n);\n\t\t\t\t\n\t\t\t\tdelt = dd_ij_Max / max(dd_ij_dt, 1.0e-300);\n\t\t\t\tdouble mean;\n\n\t\t\t\tif (tstop > (t1 + delt)) {\n\t\t\t\t\tmean = 1.0 / scale;\n\t\t\t\t} else {\n\t\t\t\t\tmean = dd_ij_dt * (tstop - t1) / (scale * dd_ij_Max);\n\t\t\t\t}\n\n\t\t\t\t//! Sinter primaries\n                boost::random::poisson_distribution<unsigned, double> repeatDistribution(mean);\n                const unsigned n = repeatDistribution(rng);\n\n\t\t\t\tdouble d_ij_min = max(r_i - r_j, r_j - r_i); //!< minimum possible separation (where one primary enevelopes the other)\n\t\t\t\tdouble delta_dij = -(double)n * scale * dd_ij_Max; //!< Change in separation (sintering decreases d_ij hence the negative sign)\n\t\t\t\t//! Make sure that sintering doesn't overshoot\n\t\t\t\tif (d_ij + delta_dij < d_ij_min){\n\t\t\t\t\tdelta_dij = d_ij_min - d_ij;\n\t\t\t\t}\n\n\t\t\t\t//! adjust separation\n\t\t\t\tm_distance_centreToCentre += delta_dij; \n\n\t\t\t\t//! if coordinates are tracked then we will translate one side of the particle by the change in separation\n\t\t\t\t//! this is faster than translating both sides by half the change\n\t\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\t\t//! get direction of translation (left particle to right particle)\n\t\t\t\t\tCoords::Vector vector_change = UnitVector(m_leftparticle->boundSphCentre(), m_rightparticle->boundSphCentre());\n\t\t\t\t\t//! translate the leftparticle\n\t\t\t\t\t// -delta_dij because delta_dij is negative (the direction of translation is determined by the vector) \n\t\t\t\t\tm_leftparticle->TranslatePrimary(vector_change, -delta_dij);\n\t\t\t\t\t//! translate all neighbours of the left particle except the right particle\n\t\t\t\t\tm_leftparticle->TranslateNeighbours(m_leftparticle,vector_change,-delta_dij,m_rightparticle);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//! Change in primary radii\n\t\t\t\tdouble delta_r_i = delta_dij * B_i;  //!< Eq. (8).\n\t\t\t\tdouble delta_r_j = delta_dij * B_j;  //!< Eq. (8).\n\n\t\t\t\t//! Adjust separation of neighbours that are not currently sintering\n\t\t\t\tm_leftparticle->UpdateConnectivity(m_leftparticle, delta_r_i, m_rightparticle);\n\t\t\t\tm_rightparticle->UpdateConnectivity(m_rightparticle, delta_r_j, m_leftparticle);\t\t\t\t\t\n\n\t\t\t\t//! Adjust primary radii\n\t\t\t\tthis->m_leftparticle->m_primarydiam += 2.0 * delta_r_i;\t\t\t\t\n\t\t\t\tthis->m_rightparticle->m_primarydiam += 2.0 * delta_r_j;\n\n\t\t\t\t//! update primaries\n\t\t\t\tm_leftparticle->UpdateOverlappingPrimary();\n\t\t\t\tm_rightparticle->UpdateOverlappingPrimary();\n\n\t\t\t\tt1 += delt;\n\n\t\t\t\t// Should return some sintering rate (units of m2/s expected)\n\t\t\t\t// r = dd_ij_dt;\n\n            } else {\n                break; //!do not continue to sinter.\n            }\n        }\n\n\t\t//! If coordinates are tracked update tracking radius \n\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\t\t\n\t\t\tm_leftparticle->setRadius(m_leftparticle->m_primarydiam / 2.0);\n\t\t\tm_rightparticle->setRadius(m_rightparticle->m_primarydiam / 2.0);\n        }\n\t}\n\n    m_children_sintering = SinteringLevel();\n\n    m_sint_rate = r;\n\n}\n\n\n/*!\n * Get the number of units of a component\n *\n * @param name  Name of component\n * @return      Number of units of a component\n */\ndouble BinTreePrimary::GetComponent(std::string name) const\n{\n\treturn m_comp[m_pmodel->ComponentIndex(name)];\n}\n\n/*!\n * Set the number of units of a component\n *\n * @param name  Name of component\n * @param val   Value to set\n */\nvoid BinTreePrimary::SetComponent(std::string name, double val)\n{\n    try {\n        m_comp[m_pmodel->ComponentIndex(name)] = val;\n    } catch(std::exception& e) {\n        throw e.what();\n    }\n}\n\n/*!\n * @return  Arithmetic standard dev. of primary diameter\n */\ndouble BinTreePrimary::GetPrimaryAStdDev() const\n{\n    // Get a list of all primary diameters first\n    fvector diams;\n    GetAllPrimaryDiameters(diams);\n    double dpri = GetPrimaryDiam() / ((double) GetNumPrimary());\n\n    // If binary tree writing hasn't been enabled, an erroneous\n    // value will be returned. So just give zero.\n    if (!m_pmodel->WriteBinaryTrees())\n        return 0.0;\n\n    // Loop over diameters to get stdev\n    double stdev(0.0), dev(0.0);\n    for (size_t i = 0; i != diams.size(); i++) {\n        dev = (diams[i] - dpri);\n        stdev += dev * dev;\n    }\n\n    stdev = sqrt(stdev / diams.size());\n    return stdev;\n}\n\n/*!\n * @return  Geometric mean primary diameter\n */\ndouble BinTreePrimary::GetPrimaryGMean() const\n{\n    // Get a list of all primary diameters first\n    fvector diams;\n    GetAllPrimaryDiameters(diams);\n\n    // If binary tree writing hasn't been enabled, an erroneous\n    // value will be returned. So just give zero.\n    if (!m_pmodel->WriteBinaryTrees())\n        return 0.0;\n\n    // Calculate the geometric mean diameter\n    double dpri(1.0);\n    double inv_n = 1.0 / (double) diams.size();\n    for (size_t i = 0; i != diams.size(); i++) {\n        dpri *= pow(diams[i], inv_n);\n    }\n\n    return dpri;\n}\n\n/*!\n *\n * @return  Geometric stdev of primary diameter\n */\ndouble BinTreePrimary::GetPrimaryGStdDev() const\n{\n    // Get a list of all primary diameters first\n    fvector diams;\n    GetAllPrimaryDiameters(diams);\n    double dpri = GetPrimaryGMean();\n\n    // If binary tree writing hasn't been enabled, an erroneous\n    // value will be returned. So just give zero.\n    if (!m_pmodel->WriteBinaryTrees())\n        return 0.0;\n\n    // Loop over diameters to get stdev\n    double stdev(0.0), dev(0.0);\n    for (size_t i = 0; i != diams.size(); i++) {\n        dev = log(diams[i] / dpri); // (natural log)\n        stdev += dev * dev;\n    }\n\n    stdev = exp(sqrt(stdev / diams.size()));\n    return stdev;\n}\n\n/*!\n * Loop through the particles and collect a list of primary\n * particle diameters.\n *\n * @param diams     Vector of diameters\n */\nvoid BinTreePrimary::GetAllPrimaryDiameters(fvector &diams) const\n{\n    // Only add diameter to list if it's a primary\n    if (m_leftchild == NULL && m_rightchild == NULL)\n        //diams.push_back(m_diam);\n\t\tdiams.push_back(m_primarydiam);\t\t//use m_primarydiam for consistency\n\n    if (m_leftchild != NULL && m_rightchild != NULL) {\n        m_leftchild->GetAllPrimaryDiameters(diams);\n        m_rightchild->GetAllPrimaryDiameters(diams);\n    }\n}\n\n/*!\n * @brief Writes a particle to a binary stream\n *\n * @param[in,out]    out                 Output binary stream\n *\n * @exception        invalid_argument    Stream not ready\n */\nvoid BinTreePrimary::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        if (m_pmodel->WriteBinaryTrees()) {\n            // Call the binary tree serialiser...\n            BinTreeSerializer <BinTreePrimary> tree;\n            tree.Serialize(out, this, NULL);\n        } else {\n            // Just serialise the root node.\n            SerializePrimary(out, NULL);\n        }\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, BinTreePrimary::Serialize).\");\n    }\n}\n\n/*!\n *  @brief Writes an individual primary to a binary stream.\n *\n *  @param[in,out] out  Output binary stream.\n *  @param         void It is a pointer, but the type that it points to is not known.\n *\n *  @exception invalid_argument Stream not ready.\n */\nvoid BinTreePrimary::SerializePrimary(std::ostream &out, void*) const\n{\n    if (out.good()) {\n\n\t\tconst unsigned int trueval  = 1;\n\t\tconst unsigned int falseval = 0;\n\n        int  val_int(0);\n        double val(0.0);\n\n        val_int = m_numprimary;\n        out.write((char*)&val_int, sizeof(val_int));\n\n        val = m_primarydiam;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_children_radius;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_children_vol;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_children_surf;\n        out.write((char*)&val, sizeof(val));\n\n\t\tval = m_free_surf;\n        out.write((char*)&val, sizeof(val));\n\n\t\tval = m_sum_necks;\n        out.write((char*)&val, sizeof(val));\n\n\t\tval = m_primaryvol;\n        out.write((char*)&val, sizeof(val));\n\t\t\n        val = m_distance_centreToCentre;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_cen_bsph[0];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_cen_bsph[1];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_cen_bsph[2];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_cen_mass[0];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_cen_mass[1];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_cen_mass[2];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_r;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_r2;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_r3;\n        out.write((char*)&val, sizeof(val));\n\n\t\tval = m_Rg;\n\t\tout.write((char*)&val, sizeof(val));\n\n        val = m_children_sintering;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_avg_sinter;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_sint_rate;\n        out.write((char*)&val, sizeof(val));\n\n        val = m_sint_time;\n        out.write((char*)&val, sizeof(val));\n\n\t\t// frame orientation vectors\n\t\t// Note: serialization is not actually needed because the output\n\t\t// files are not currently produced in the postpocessing step\n\t\tval = m_frame_orient_z[0];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_frame_orient_z[1];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_frame_orient_z[2];\n        out.write((char*)&val, sizeof(val));\n\n\t\tval = m_frame_orient_x[0];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_frame_orient_x[1];\n        out.write((char*)&val, sizeof(val));\n\n        val = m_frame_orient_x[2];\n        out.write((char*)&val, sizeof(val));\n\n\t\t// Output if primary is tracked\n\t\tif (m_tracked) {\n\t\t\tout.write((char*)&trueval, sizeof(trueval));\n\t\t}\n\t\telse {\n\t\t\tout.write((char*)&falseval, sizeof(falseval));\n\t\t}\n\n        // Output base class.\n        Primary::Serialize(out);\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, BinTreePrimary::SerializePrimary).\");\n    }\n}\n\n\n\n/*!\n * @brief Deserialise the binary tree\n *\n * Will only deserialise the full binary tree if the particle model has\n * writing/reading of trees activated. Otherwise, it will just load the\n * root node data.\n *\n * @param[in,out]    in                  Input binary stream\n * @param[in]        model               Particle model defining interpretation of particle data\n *\n * @exception        invalid_argument    Stream not ready\n */\nvoid BinTreePrimary::Deserialize(std::istream &in, const Sweep::ParticleModel &model)\n{\n    //UpdateCache();\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        if (model.WriteBinaryTrees()) {\n            // Call the binary tree serialiser...\n            BinTreeSerializer <BinTreePrimary> tree;\n            tree.Deserialize(in, this, model, NULL);\n        } else {\n            // Just deserialise the root node.\n            DeserializePrimary(in, model, NULL);\n        }\n\n\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, BinTreePrimary::Deserialize).\");\n    }\n}\n\n/*!\n *  @brief Deserialise attributes of a single particle node.\n *\n *  @param[in,out] in    Input binary stream.\n *  @param[in]     model Particle model defining interpretation of particle data.\n *  @param         void  It is a pointer, but the type that it points to is not known.\n *\n *  @exception invalid_argument Stream not ready.\n */\nvoid BinTreePrimary::DeserializePrimary(std::istream &in,\n        const Sweep::ParticleModel &model,\n        void*)\n{\n    if (in.good()) {\n\n        int  val_int(0);\n        double val(0.0);\n\t\tunsigned int val_unsigned(0);\n\n        in.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n        m_numprimary = val_int;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_primarydiam = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_children_radius = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_children_vol = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_children_surf = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_free_surf = val;\n\t\t\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_sum_necks = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_primaryvol = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_distance_centreToCentre = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_cen_bsph[0] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_cen_bsph[1] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_cen_bsph[2] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_cen_mass[0] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_cen_mass[1] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_cen_mass[2] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_r = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_r2 = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_r3 = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_Rg = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_children_sintering = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_avg_sinter = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_sint_rate = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_sint_time = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_frame_orient_z[0] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_frame_orient_z[1] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_frame_orient_z[2] = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_frame_orient_x[0] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_frame_orient_x[1] = val;\n\n        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n        m_frame_orient_x[2] = val;\n\n\t\t // Read if primary is tracked.\n        in.read(reinterpret_cast<char*>(&val_unsigned), sizeof(val_unsigned));\n        if (val_int==1) {\n            m_tracked = true;\n        } else {\n            m_tracked = false;\n        }\n\n        // Input base class.\n        Primary::Deserialize(in, model);\n\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, BinTreePrimary::DeserializePrimary).\");\n    }\n}\n\n//! Returns true if this node is a leaf (has no children).\nbool BinTreePrimary::isLeaf(void) const\n{\n    return (m_leftchild == NULL) && (m_rightchild == NULL);\n}\n\n//! Returns the bounding-sphere centre.\nconst Coords::Vector &BinTreePrimary::boundSphCentre(void) const\n{\n    return m_cen_bsph;\n}\n\n//! Estimates the bounding sphere position and radius using\n//! Ritter's method. ~5% larger than minimum bounding sphere\n//! Ritter, J. (1990). An efficient bounding sphere, Graphics Gems \n//! (Andrew S. Glassner ed.), pp. 301-303. Academic Press, Boston\nvoid BinTreePrimary::calcBoundSph(void)\n{\n\tif ((m_leftchild != NULL) && (m_rightchild != NULL)) {\n\n\t\t//! Get list of primary coordinates\n\t\tvector<fvector> coords;\n\t\tthis->GetPriCoords(coords);\n\n\t\t//! Find 3 pairs of points with the min and max x,y,z values\n\t\tfvector min_x = coords[1];\t//! initialise with first point\n\t\tfvector max_x = min_x;\n\t\tfvector min_y = min_x;\n\t\tfvector max_y = min_x;\n\t\tfvector min_z = min_x;\n\t\tfvector max_z = min_x;\n\t\tfor (int i = 1; i != coords.size(); ++i) {\n\t\t\tif (coords[i][0] < min_x[0]) min_x = coords[i];\n\t\t\tif (coords[i][0] > max_x[0]) max_x = coords[i];\n\t\t\tif (coords[i][1] < min_y[1]) min_y = coords[i];\n\t\t\tif (coords[i][1] > max_y[1]) max_y = coords[i];\n\t\t\tif (coords[i][2] < min_z[2]) min_z = coords[i];\n\t\t\tif (coords[i][2] > max_z[2]) max_z = coords[i];\n\t\t}\n\n\t\t//! Calculate separation (squared) between min and max \n\t\tdouble dx = (max_x[0] - min_x[0]);\n\t\tdouble dy = (max_x[1] - min_x[1]);\n\t\tdouble dz = (max_x[2] - min_x[2]);\n\t\tdouble x_sep = dx*dx + dy*dy + dz*dz;\n\t\tdx = (max_y[0] - min_y[0]);\n\t\tdy = (max_y[1] - min_y[1]);\n\t\tdz = (max_y[2] - min_y[2]);\n\t\tdouble y_sep = dx*dx + dy*dy + dz*dz;\n\t\tdx = (max_z[0] - min_z[0]);\n\t\tdy = (max_z[1] - min_z[1]);\n\t\tdz = (max_z[2] - min_z[2]);\n\t\tdouble z_sep = dx*dx + dy*dy + dz*dz;\n\n\t\t//! find maximum separation\n\t\t//! points p_1 and p_2 are the points with maximum separation\n\t\tdouble max_sep = x_sep;\n\t\tfvector p_1 = min_x;\n\t\tfvector p_2 = max_x;\n\t\tif (y_sep > max_sep){\n\t\t\tmax_sep = y_sep;\n\t\t\tp_1 = min_y;\n\t\t\tp_2 = max_y;\n\t\t}\n\t\tif (z_sep > max_sep){\n\t\t\tmax_sep = z_sep;\n\t\t\tp_1 = min_z;\n\t\t\tp_2 = max_z;\n\t\t}\n\n\t\t//! Use p_1 and p_2 for initial guess at bounding sphere\n\t\t//! bounding sphere centre\n\t\tm_cen_bsph[0] = (p_1[0] + p_2[0]) / 2.0;\n\t\tm_cen_bsph[1] = (p_1[1] + p_2[1]) / 2.0;\n\t\tm_cen_bsph[2] = (p_1[2] + p_2[2]) / 2.0;\n\t\t//! radius of bounding sphere \n\t\t//! including the primary radii\n\t\tsetRadius((sqrt(max_sep)/2.0)+p_1[3]+p_2[3]);\n\n\t\t//! Make a second pass through list of primaries updating the sphere\n\t\tfor (int i = 1; i != coords.size(); ++i) {\n\t\t\t\n\t\t\t//! calculate distance from bounding sphere centre and add primary radius\n\t\t\tdx = coords[i][0] - m_cen_bsph[0];\n\t\t\tdy = coords[i][1] - m_cen_bsph[1];\n\t\t\tdz = coords[i][2] - m_cen_bsph[2];\n\t\t\tdouble r_cen = sqrt(dx*dx + dy*dy + dz*dz); //!< Distance to primary centre\n\t\t\tdouble r_out = r_cen + coords[i][3]; //!< Distance to outer edge of primary\n\n\t\t\t//! If distance from the bounding sphere centre exceeds the \n\t\t\t//! bounding sphere radius then update the bounding sphere:\n\t\t\t//! move centre by half the difference and increase the radius by half the difference\n\t\t\tif (r_out > m_r){\n\t\t\t\t\n\t\t\t\t//! half the distance from current bounding sphere centre to outer edge of primary\n\t\t\t\tdouble delta_r = (r_out - m_r) / 2.0; \n\n\t\t\t\t//! Update the bounding sphere centre:\n\t\t\t\t//! the centre is translated along the vector joining \n\t\t\t\t//! the old centre to the primary centre by half the difference\n\t\t\t\tm_cen_bsph[0] += delta_r * dx / r_cen;\n\t\t\t\tm_cen_bsph[1] += delta_r * dy / r_cen;\n\t\t\t\tm_cen_bsph[2] += delta_r * dz / r_cen;\n\n\t\t\t\t//! Set new radius\n\t\t\t\tsetRadius(m_r + delta_r);\n\t\t\t}\n\t\t}\n\t}\n}\n\n//! Calculates the centre-of-mass using the left and right child node values.\nvoid BinTreePrimary::calcCOM(void)\n{\n    if ((m_leftchild != NULL) && (m_rightchild != NULL)) {\n        //! Calculate centres-of-mass of left and right children.\n        m_leftchild->calcCOM();\n        m_rightchild->calcCOM();\n\n        //! Calculate inverse total mass of left and right children.\n        m_mass = m_leftchild->m_mass + m_rightchild->m_mass;\n        double invtotmass = 1.0 / m_mass;\n\n        //! Now calculate centre-of-mass.\n        for (unsigned int i=0; i!=3; ++i) {\n            m_cen_mass[i]  = m_leftchild->m_cen_mass[i] * m_leftchild->m_mass;\n            m_cen_mass[i] += m_rightchild->m_cen_mass[i] * m_rightchild->m_mass;\n            m_cen_mass[i] *= invtotmass;\n        }\n    } else {\n        //! If there are no children, then the centre-of-mass and bounding-\n        //! sphere centre are the same.\n        m_cen_mass[0] = m_cen_bsph[0];\n        m_cen_mass[1] = m_cen_bsph[1];\n        m_cen_mass[2] = m_cen_bsph[2];\n    }\n}\n\n//! Put the bounding-sphere at the origin.\nvoid BinTreePrimary::centreBoundSph(void)\n{\n    Translate(-m_cen_bsph[0], -m_cen_bsph[1], -m_cen_bsph[2]);\n}\n\n//! Put the centre-of-mass at the origin.\nvoid BinTreePrimary::centreCOM(void)\n{\n    Translate(-m_cen_mass[0], -m_cen_mass[1], -m_cen_mass[2]);\n}\n\n/*!\n *  Randomly rotates the aggregate node and child structure about its centre of\n *  mass.\n *\n *  @param[in]    theta    Rotation about the pole. \n *  @param[in]    V        Vector for performing the reflection.\n */\nvoid BinTreePrimary::rotateCOM(double theta, fvector V)\n{\n    //! Move the aggregate so that its centre-of-mass is at the origin. Store\n    //! the coordinates, so that they can be restored afterwards.\n    Coords::Vector D(m_cen_mass);\n    Translate(-D.X(), -D.Y(), -D.Z());\n\n    //! Create transformation matrix.\n    Coords::Matrix M;\n    //M.SetIdentity();\n    M.rotateArvo(theta, V);\n\n    //! Rotate child nodes.\n    if (m_leftchild != NULL) m_leftchild->transform(M);\n    if (m_rightchild != NULL) m_rightchild->transform(M);\n\n    //! Rotate bounding-sphere coordinates.\n    m_cen_bsph = M.Mult(m_cen_bsph);\n\n    //! Restore centre-of-mass coordinates.\n    Translate(D.X(), D.Y(), D.Z());\n}\n\n/*!\n *  @brief Sets the radius of the bounding sphere.\n *\n *  @param[in]    r    Radius of bounding sphere.\n */\nvoid BinTreePrimary::setRadius(double r)\n{\n    m_r  = r;\n    m_r2 = r * r;\n    m_r3 = m_r2 * m_r;\n}\n\n//! Returns the bounding sphere radius.\ndouble BinTreePrimary::Radius(void) const\n{\n    return m_r;\n}\n\n/*!\n *  Transform the primary particle coordinates using the transformation matrix\n *  so as to rotate it.\n *:\n *  @param[in]    mat               Transformation matrix.\n *  @param[in]    PAHTracerMatch    Flag used to indicate whether the particle\n *                                  contains the PAH to be traced.\n */\nvoid BinTreePrimary::transform(const Coords::Matrix &mat)\n{\n\t//! Descend binary tree to the leaf nodes, i.e. single primary particles.\n\tif (m_leftchild != NULL)\n\t\tm_leftchild->transform(mat);\n\tif (m_rightchild != NULL)\n\t\tm_rightchild->transform(mat);\n\n\t//! Rotate centre-of-mass and bounding sphere coordinates.\n\tm_cen_mass = mat.Mult(m_cen_mass);\n\tm_cen_bsph = mat.Mult(m_cen_bsph);\n\n\t//! If the primary is tracked then rotate the frame orientation\n\tif (m_tracked == true) {\n\t\tm_frame_orient_z = mat.Mult(m_frame_orient_z);\n\t\tm_frame_orient_x = mat.Mult(m_frame_orient_x);\n\t}\n}\n\n/*!\n *  Translates (moves) the aggregate node and child structure by the given\n *  amounts along the cartesian axes.\n *\n *  @param[in]    dx    Distance to translate in the x-axis.\n *  @param[in]    dy    Distance to translate in the y-axis.\n *  @param[in]    dz    Distance to translate in the z-axis.\n */\nvoid BinTreePrimary::Translate(double dx, double dy, double dz)\n{\n    //! Translate child branches.\n    if (m_leftchild != NULL) m_leftchild->Translate(dx, dy, dz);\n    if (m_rightchild != NULL) m_rightchild->Translate(dx, dy, dz);\n\n    //! Translate bounding sphere centre.\n    m_cen_bsph.Translate(dx, dy, dz);\n\n    //! Translate centre-of-mass.\n    m_cen_mass.Translate(dx, dy, dz);\n}\n\n//! Write the coordinates of the primaries in the particle pointed to by the\n//! this pointer. Units of nm.\nvoid BinTreePrimary::writePrimaryCoordinatesRadius(void)\n{\n    if (m_leftchild!=NULL)\n        m_leftchild->writePrimaryCoordinatesRadius();\n\n    if (m_rightchild!=NULL)\n        m_rightchild->writePrimaryCoordinatesRadius();\n\n    std::ofstream outfile;\n\n    double r = Radius() * 1.0e9;\n    double a = m_cen_mass[0] * 1.0e9;\n    double b = m_cen_mass[1] * 1.0e9;\n    double c = m_cen_mass[2] * 1.0e9;\n\n    //! There is a need for these two conditions as upon exit of the function\n    //! the aggregate node will pass through this part of the code but are only\n    //! we are only interested in the coordinates of the primaries.\n\tif (isLeaf()) {\n\t\toutfile.open(\"Spheres.m\", std::ios_base::app);\n\t\toutfile << \"surf(x*\" << r << \"+\" << a << \",y*\" << r << \"+\" << b << \",z*\" << r << \"+\" << c << \");\\n\";\n\t\toutfile.close();\n\t}\n}\n\n/*!\n *  Calculates unit vector between two set coordinates\n *\n *  @param[in]    x_i\tCoordinates\n *  @param[in]    x_j\tCoordinates\n *  @param[out]   unit vector\n */\nCoords::Vector BinTreePrimary::UnitVector(Coords::Vector x_i, Coords::Vector x_j)\n{\n\tCoords::Vector delta_x;\n\tdouble len_delta_x;\n\n\t//! Calculate difference x_j - x_i\n\tdelta_x[0] = x_j[0] - x_i[0];\n\tdelta_x[1] = x_j[1] - x_i[1];\n\tdelta_x[2] = x_j[2] - x_i[2];\n\n\t//! Calculate the length of the vector\n\tlen_delta_x = sqrt(delta_x[0]*delta_x[0]+delta_x[1]*delta_x[1]+delta_x[2]*delta_x[2]);\n\n\t//! Create unit vector\n\tdelta_x[0] /=  len_delta_x;\n\tdelta_x[1] /=  len_delta_x;\n\tdelta_x[2] /=  len_delta_x;\n\n\treturn delta_x;\n}\n\n/*!\n *  Calculates distance between two points\n *\n *  @param[in]    x_i\tCoordinates\n *  @param[in]    x_j\tCoordinates\n *  @param[out]   Separation\n */\ndouble BinTreePrimary::Separation(Coords::Vector x_i, Coords::Vector x_j)\n{\n\tCoords::Vector delta_x;\n\tdouble len_delta_x;\n\n\t//calculate difference x_j - x_i\n\tdelta_x[0] = x_j[0] - x_i[0];\n\tdelta_x[1] = x_j[1] - x_i[1];\n\tdelta_x[2] = x_j[2] - x_i[2];\n\n\t//calculate the length of the vector\n\tlen_delta_x = sqrt(delta_x[0]*delta_x[0]+delta_x[1]*delta_x[1]+delta_x[2]*delta_x[2]);\n\n\treturn len_delta_x;\n}\n\n\n/*!\n *  Translates a primary particle along a unit vector\n *\n *  @param[in]    u\t\t\tUnit vector (direction)\n *  @param[in]    delta_d\tDistance to translate\n */\nvoid BinTreePrimary::TranslatePrimary(Coords::Vector u, double delta_d)\n{\n\t//! Bounding sphere coordinates\n\tm_cen_bsph[0] += delta_d * u[0];\n\tm_cen_bsph[1] += delta_d * u[1];\n\tm_cen_bsph[2] += delta_d * u[2];\n\t//! Centre of mass coordinates\n\tm_cen_mass[0] += delta_d * u[0];\n\tm_cen_mass[1] += delta_d * u[1];\n\tm_cen_mass[2] += delta_d * u[2];\n}\n\n/*!\n *  Translates neighbours of a primary particle along a unit vector\n *\n *  @param[in]    prim\t\t\tPrimary\n *  @param[in]    u\t\t\t\tUnit vector direction of translation\n *  @param[in]    delta_d\t\tMagnitude of translation\n *  @param[in]    prim_ignore\tPrimary to ignore\n */\nvoid BinTreePrimary::TranslateNeighbours(BinTreePrimary *prim, Coords::Vector u, double delta_d, BinTreePrimary *prim_ignore)\n{\n\tBinTreePrimary *neighbour = NULL;\n\t//! Check if a neighbour of prim but not prim_ignore\n\tif (m_parent->m_leftparticle == prim && m_parent->m_rightparticle != prim_ignore ) {\n\t\t//! right particle is a neighbour\n\t\tneighbour = m_parent->m_rightparticle;\n\t\t//! adjust its coordinates\n\t\tneighbour->TranslatePrimary(u,delta_d);\n\t\t//! adjust its neighbours except for prim\n\t\tneighbour->TranslateNeighbours(neighbour, u, delta_d, prim);\n\t} else if(m_parent->m_rightparticle == prim &&  m_parent->m_leftparticle != prim_ignore ) {\n\t\t//! left particle is a neighbour\n\t\tneighbour = m_parent->m_leftparticle;\n\t\t//! adjust its coordinates\n\t\tneighbour->TranslatePrimary(u,delta_d);\n\t\t//! adjust its neighbours except for prim\n\t\tneighbour->TranslateNeighbours(neighbour, u, delta_d, prim);\n\t}\n\n\t//! continue working up the binary tree\n\tif(m_parent->m_parent != NULL){\n\t\tm_parent->TranslateNeighbours(prim, u, delta_d, prim_ignore);\n\t}\n}\n\n// PARTICLE TRACKING FOR VIDEOS\n\n//! Remove primary tracking flag\nvoid BinTreePrimary::removeTracking()\n{\n\t//set tracking flag to false\n\tm_tracked = false;\n\n\t//work down bintree structure\n\tif (m_leftchild != NULL) m_leftchild->removeTracking();\n\tif (m_rightchild != NULL) m_rightchild->removeTracking();\n}\n\n//! Set tracking flag\n//  A single primary in the aggregate is tracked to centre the image frame\nvoid BinTreePrimary::setTracking()\n { \n\t m_tracked = true;\n\n\t// work done binary tree to a primary\n\tif (m_leftchild != NULL) m_leftchild->setTracking();\n}\n\n//! Returns the frame position and orientation, and primary coordinates\n//! Used by particle tracking for videos\nvoid BinTreePrimary::GetFrameCoords(std::vector<fvector> &coords) const\n{\n\tif (isLeaf()) { //this is a primary\n\t\tfvector c(10);\n\t\tc[0] = m_cen_mass[0];\t//primary coordinates\n\t\tc[1] = m_cen_mass[1];\n\t\tc[2] = m_cen_mass[2];\n\t\tc[3] = m_r;\t\t\t\t//primary radius\n\t\tif (m_tracked == true){\t\n\t\t\t//the frame orientation vectors are output\n\t\t\t//for the single tracked primary\n\t\t\t//the primary coordinates define the centre of the frame\n\t\t\tc[4] = m_frame_orient_x[0];\t\n\t\t\tc[5] = m_frame_orient_x[1];\n\t\t\tc[6] = m_frame_orient_x[2];\n\t\t\tc[7] = m_frame_orient_z[0];\n\t\t\tc[8] = m_frame_orient_z[1];\n\t\t\tc[9] = m_frame_orient_z[2];\n\t\t}\n\t\telse{\n\t\t\tc[4] = 0.0;\n\t\t\tc[5] = 0.0;\n\t\t\tc[6] = 0.0;\n\t\t\tc[7] = 0.0;\n\t\t\tc[8] = 0.0;\n\t\t\tc[9] = 0.0;\n\t\t}\n\t\t//get primary composition\n\t\tfvector comp = this->Composition();\n\t\tc.insert(c.end(), comp.begin(), comp.end());\n\n\t\t//add to coords vector\n\t\tcoords.push_back(c);\n\t}\n\telse {\t//this is a non-leaf node\n\t\tm_leftchild->GetFrameCoords(coords);\n\t\tm_rightchild->GetFrameCoords(coords);\n\t}\n}\n\n/*!\n *  Print primary particle details and connectivity\n *\n *  @param[in]    surface\t\t\tPrimary connectivity\n *  @param[in]    primary_diameter\tPrimary details\n *  @param[in]    k\t\t\t\t\tParticle counter\n */\nvoid BinTreePrimary::PrintPrimary(vector<fvector> &surface, vector<fvector> &primary_diameter, int k) const\n{\n\tfvector node(10);\t\n\tfvector primary;\n\tfvector comp;\n\n\tif ((m_leftchild==NULL) && (m_rightchild==NULL)){\n\t\t//if leaf then print diameter\n\t\tprimary.push_back((double)k+1);\n\t\tprimary.push_back(m_primarydiam);\n\t\tprimary.push_back(m_diam);\n\t\tprimary.push_back(m_primaryvol);\n\t\tprimary.push_back(m_vol);\n\t\tprimary.push_back(m_free_surf);\n\n\t\t//primary coordinates\n\t\tvector<fvector> coords;\n\t\tthis->GetPriCoords(coords); //get primary coodinates\n\t\tprimary.push_back(coords[0][0]);\n\t\tprimary.push_back(coords[0][1]);\n\t\tprimary.push_back(coords[0][2]);\n\t\tprimary.push_back(coords[0][3]);\n\n\t\t//primary composition\n\t\tfvector comp = Primary::Composition();\n\t\tprimary.insert(primary.end(),comp.begin(),comp.end());\n\n\t\tprimary_diameter.push_back(primary);\n\t\t\n\t\tif (m_parent == NULL){\t//connectivity information for single primary case\n\t\t\tnode[0] = k+1;\n\t\t\tnode[1] = m_numprimary;\n\t\t\tnode[2] = 0.0;\n\t\t\tnode[3] = 1.0;\n\t\t\tnode[4] = 0.0;\n\t\t\tnode[5] = 0.0;\n\t\t\tnode[6] = m_primarydiam/2.0;\n\t\t\tnode[7] = 0.0;\n\t\t\t//print pointer to this primary as integer (assume this a unique id to the primary)\n\t\t\tnode[8] = reinterpret_cast<uintptr_t>(this);\t\n\t\t\tnode[9] = 0.0;\n\n\t\t\tsurface.push_back(node);\n\t\t}\n\t} else {\n\t\t\n\t\tdouble r_i = m_leftparticle->m_primarydiam/2.0;\n\t\tdouble r_j = m_rightparticle->m_primarydiam/2.0;\t\n\t\tdouble d_ij = m_distance_centreToCentre;\n\n\t\tdouble x_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i)/(2.0*d_ij);\n\t\tdouble R_ij = sqrt(r_i*r_i - x_ij*x_ij);\t//!neck radius\n\n\t\t//if non-leaf node then print node and continue down the tree\n\t\tnode[0] = k+1;\n\t\tnode[1] = m_numprimary;\n\t\tnode[2] = m_children_surf;\n\t\tnode[3] = m_children_sintering;\n\t\tnode[4] = d_ij;\n\t\tnode[5] = R_ij;\n\t\tnode[6] = r_i;\n\t\tnode[7] = r_j;\n\t\t//print pointer to left primary as integer (assume this a unique id to the primary)\n\t\tnode[8] = reinterpret_cast<uintptr_t>(m_leftparticle);\t\n\t\t//print pointer to right primary as integer (assume this a unique id to the primary)\n\t\tnode[9] = reinterpret_cast<uintptr_t>(m_rightparticle);\t\n\t\t\n\t\tsurface.push_back(node);\n\t\t\n\t\t//continue down binary tree\n\t\tm_leftchild->PrintPrimary(surface, primary_diameter, k);\n\t\tm_rightchild->PrintPrimary(surface, primary_diameter, k);\n\t}\n}\n", "meta": {"hexsha": "81e1dd27c81100bed49b03a27408236705234109", "size": 137434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_bintree_primary.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_bintree_primary.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "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/sweepc/source/swp_bintree_primary.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 33.2689421448, "max_line_length": 174, "alphanum_fraction": 0.6437417233, "num_tokens": 38216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.19665915751061697}}
{"text": "\n#include <boost/foreach.hpp>\n\n#include \"constants.hpp\"\n#include \"gc.hpp\"\n\n\nboost::mutex GCCorrection::mut;\n\n\nGCCorrection::GCCorrection(TranscriptSet& ts, const double* transcript_gc)\n    : ts(ts)\n    , transcript_gc(transcript_gc)\n{\n    n = 0;\n    for (TranscriptSet::iterator t = ts.begin(); t != ts.end(); ++t) {\n        n = std::max<size_t>(n, t->tgroup + 1);\n    }\n\n    gene_expr.resize(n);\n    gene_gc.resize(n);\n    xs.resize(n);\n    ys.resize(n);\n    fit.resize(ts.size());\n    se_fit.resize(ts.size());\n    tgc.resize(ts.size());\n\n    lo.model.span = constants::gc_loess_smoothing;\n    lo.model.family = \"symmetric\";\n    lo.model.degree = 1;\n}\n\n\nGCCorrection::~GCCorrection()\n{\n}\n\n// I really hat this code. It's so goofy.\n// If I really want to correct for gc-content I also have to try take into account\n// 5'-3' effects. Also, I should really be correcting for GC content at the fragment\n// level.\nvoid GCCorrection::correct(double* expr)\n{\n    boost::lock_guard<boost::mutex> lock(mut);\n\n    std::fill(gene_gc.begin(), gene_gc.end(), 0.0);\n    std::fill(gene_expr.begin(), gene_expr.end(), 0.0);\n    for (TranscriptSet::iterator t = ts.begin(); t != ts.end(); ++t) {\n        if (expr[t->id] == 0.0 ||\n            t->exonic_length() < 500 ||\n            transcript_gc[t->id] < 0.10 ||\n            transcript_gc[t->id] > 0.90) {\n            continue;\n        }\n\n        gene_gc[t->tgroup] += expr[t->id] * transcript_gc[t->id];\n        gene_expr[t->tgroup] += expr[t->id];\n    }\n\n    double max_gc = 0.0, min_gc = 1.0;\n    size_t j = 0;\n    for (size_t i = 0; i < n; ++i) {\n        if (gene_expr[i] > 0.0) {\n            xs[j] = gene_gc[i] / gene_expr[i];\n            ys[j] = log(gene_expr[i]);\n            max_gc = std::max<double>(max_gc, xs[j]);\n            min_gc = std::min<double>(min_gc, xs[j]);\n            ++j;\n        }\n    }\n\n    loess_setup(&xs.at(0), &ys.at(0), j, 1, &lo);\n    lo.model.span = constants::gc_loess_smoothing;\n    lo.model.family = \"symmetric\";\n    lo.model.degree = 1;\n    loess(&lo);\n\n    // normalize to a arbitary point in the loess curve\n    double ref_gc = 0.5;\n    double ref, ref_se;\n    predict2(&lo, &ref_gc, &ref, &ref_se, 1, FALSE);\n\n    // normalize samples\n    std::copy(transcript_gc, transcript_gc + ts.size(), tgc.begin());\n    for (size_t i = 0; i < ts.size(); ++i) {\n        tgc[i] = std::min(max_gc, std::max(min_gc, tgc[i]));\n    }\n\n    predict2(&lo, &tgc.at(0), &fit.at(0), &se_fit.at(0), ts.size(), FALSE);\n\n    double z = 0.0;\n    for (size_t i = 0; i < ts.size(); ++i) {\n        expr[i]  = pow(expr[i], ref / fit[i]);\n        z += expr[i];\n    }\n\n    for (size_t i = 0; i < ts.size(); ++i) {\n        expr[i] /= z;\n    }\n\n    loess_free_mem(&lo);\n}\n\n\nvoid GCCorrection::adjustments(const double* expr, double* weights)\n{\n    boost::lock_guard<boost::mutex> lock(mut);\n\n    std::fill(gene_gc.begin(), gene_gc.end(), 0.0);\n    std::fill(gene_expr.begin(), gene_expr.end(), 0.0);\n    for (TranscriptSet::iterator t = ts.begin(); t != ts.end(); ++t) {\n        if (expr[t->id] == 0.0 ||\n            t->exonic_length() < 500 ||\n            transcript_gc[t->id] < 0.10 ||\n            transcript_gc[t->id] > 0.90) {\n            continue;\n        }\n\n        gene_gc[t->tgroup] += expr[t->id] * transcript_gc[t->id];\n        gene_expr[t->tgroup] += expr[t->id];\n    }\n\n    double max_gc = 0.0, min_gc = 1.0;\n    size_t j = 0;\n    for (size_t i = 0; i < n; ++i) {\n        if (gene_expr[i] > 0.0) {\n            xs[j] = gene_gc[i] / gene_expr[i];\n            ys[j] = log(gene_expr[i]);\n            max_gc = std::max<double>(max_gc, xs[j]);\n            min_gc = std::min<double>(min_gc, xs[j]);\n            ++j;\n        }\n    }\n\n    loess_setup(&xs.at(0), &ys.at(0), j, 1, &lo);\n    lo.model.span = constants::gc_loess_smoothing;\n    lo.model.family = \"symmetric\";\n    lo.model.degree = 1;\n    loess(&lo);\n\n    // normalize to a arbitary point in the loess curve\n    double ref_gc = 0.5;\n    double ref, ref_se;\n    predict2(&lo, &ref_gc, &ref, &ref_se, 1, FALSE);\n\n    // normalize samples\n    std::copy(transcript_gc, transcript_gc + ts.size(), tgc.begin());\n    for (size_t i = 0; i < ts.size(); ++i) {\n        tgc[i] = std::min(max_gc, std::max(min_gc, tgc[i]));\n    }\n\n    predict2(&lo, &tgc.at(0), &fit.at(0), &se_fit.at(0), ts.size(), FALSE);\n\n    for (size_t i = 0; i < n; ++i) {\n        weights[i] = ref / fit[i];\n    }\n}\n\n\n", "meta": {"hexsha": "71bc3b23861483efe0a224f1fa230ca683f31086", "size": 4382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gc.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/gc.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/gc.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": 27.3875, "max_line_length": 84, "alphanum_fraction": 0.5397078959, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.1966591563067882}}
{"text": "#ifndef MPLLIBS_METAMONAD_TEST_SAME_MAP_HPP\n#define MPLLIBS_METAMONAD_TEST_SAME_MAP_HPP\n\n// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.\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 <mpllibs/metamonad/metafunction.hpp>\n#include <mpllibs/metamonad/lambda_c.hpp>\n#include <mpllibs/metamonad/lazy.hpp>\n#include <mpllibs/metamonad/already_lazy.hpp>\n#include <mpllibs/metamonad/lazy_protect_args.hpp>\n#include <mpllibs/metamonad/name.hpp>\n#include <mpllibs/metamonad/first.hpp>\n#include <mpllibs/metamonad/second.hpp>\n\n#include <boost/type_traits.hpp>\n\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/not.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/size.hpp>\n\n// equal depends on the order of elements in the map\nMPLLIBS_METAFUNCTION(same_map, (A)(B))\n((\n  boost::mpl::and_<\n    typename\n      boost::mpl::fold<\n        A,\n        boost::mpl::true_,\n        mpllibs::metamonad::lambda_c<\n          mpllibs::metamonad::s,\n          mpllibs::metamonad::p,\n          mpllibs::metamonad::lazy<\n            boost::mpl::and_<\n              mpllibs::metamonad::already_lazy<mpllibs::metamonad::s>,\n              boost::is_same<\n                boost::mpl::at<\n                  mpllibs::metamonad::already_lazy<B>,\n                  mpllibs::metamonad::lazy_protect_args<\n                    mpllibs::metamonad::first<mpllibs::metamonad::p>\n                  >\n                >,\n                mpllibs::metamonad::lazy_protect_args<\n                  mpllibs::metamonad::second<mpllibs::metamonad::p>\n                >\n              >\n            >\n          >\n        >\n      >::type,\n    typename boost::mpl::equal_to<\n      typename boost::mpl::size<A>::type,\n      typename boost::mpl::size<B>::type\n    >::type\n  >\n));\n\nMPLLIBS_METAFUNCTION(not_same_map, (A)(B))\n((boost::mpl::not_<typename same_map<A, B>::type>));\n\n#endif\n\n", "meta": {"hexsha": "9cf36b4ba2084de0e2bd3734a2567194c133c92e", "size": 2063, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/metamonad/test/same_map.hpp", "max_stars_repo_name": "sabel83/mpllibs", "max_stars_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T09:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:49:31.000Z", "max_issues_repo_path": "libs/metamonad/test/same_map.hpp", "max_issues_repo_name": "sabel83/mpllibs", "max_issues_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T19:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T19:49:51.000Z", "max_forks_repo_path": "libs/metamonad/test/same_map.hpp", "max_forks_repo_name": "sabel83/mpllibs", "max_forks_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T08:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:17:57.000Z", "avg_line_length": 29.8985507246, "max_line_length": 70, "alphanum_fraction": 0.6286960737, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19665915367234474}}
{"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) 2014-2017 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2017-2021.\n// Modifications copyright (c) 2017-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_ALGORITHMS_CORRECT_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP\n\n\n#include <algorithm>\n#include <cstddef>\n#include <functional>\n\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n#include <boost/range/value_type.hpp>\n\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/correct_closure.hpp>\n#include <boost/geometry/algorithms/detail/interior_iterator.hpp>\n#include <boost/geometry/algorithms/detail/multi_modify.hpp>\n#include <boost/geometry/algorithms/detail/visit.hpp>\n\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n#include <boost/geometry/core/mutable_range.hpp>\n#include <boost/geometry/core/ring_type.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/core/visit.hpp>\n\n#include <boost/geometry/geometries/adapted/boost_variant.hpp> // For backward compatibility\n#include <boost/geometry/geometries/concepts/check.hpp>\n\n#include <boost/geometry/strategies/area/cartesian.hpp>\n#include <boost/geometry/strategies/area/geographic.hpp>\n#include <boost/geometry/strategies/area/spherical.hpp>\n#include <boost/geometry/strategies/detail.hpp>\n\n#include <boost/geometry/util/algorithm.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n// Silence warning C4127: conditional expression is constant\n#if defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable : 4127)\n#endif\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace correct\n{\n\nstruct correct_nop\n{\n    template <typename Geometry, typename Strategy>\n    static inline void apply(Geometry& , Strategy const& )\n    {}\n};\n\n\n// Correct a box: make min/max correct\nstruct correct_box\n{\n    template <typename Box, typename Strategy>\n    static inline void apply(Box& box, Strategy const& )\n    {\n        using coordinate_type = typename geometry::coordinate_type<Box>::type;\n\n        // Currently only for Cartesian coordinates\n        // (or spherical without crossing dateline)\n        // Future version: adapt using strategies\n        detail::for_each_dimension<Box>([&](auto dimension)\n        {\n            if (get<min_corner, dimension>(box) > get<max_corner, dimension>(box))\n            {\n                // Swap the coordinates\n                coordinate_type max_value = get<min_corner, dimension>(box);\n                coordinate_type min_value = get<max_corner, dimension>(box);\n                set<min_corner, dimension>(box, min_value);\n                set<max_corner, dimension>(box, max_value);\n            }\n        });\n    }\n};\n\n\n// Close a ring, if not closed\ntemplate <typename Predicate = std::less<>>\nstruct correct_ring\n{\n    template <typename Ring, typename Strategy>\n    static inline void apply(Ring& r, Strategy const& strategy)\n    {\n        // Correct closure if necessary\n        detail::correct_closure::close_or_open_ring::apply(r);\n\n        // NOTE: calculate_point_order should probably be used here instead.\n\n        // Check area\n        using area_t = typename area_result<Ring, Strategy>::type;\n        area_t const zero = 0;\n        if (Predicate()(detail::area::ring_area::apply(r, strategy), zero))\n        {\n            std::reverse(boost::begin(r), boost::end(r));\n        }\n    }\n};\n\n// Correct a polygon: normalizes all rings, sets outer ring clockwise, sets all\n// inner rings counter clockwise (or vice versa depending on orientation)\nstruct correct_polygon\n{\n    template <typename Polygon, typename Strategy>\n    static inline void apply(Polygon& poly, Strategy const& strategy)\n    {\n        correct_ring<std::less<>>::apply(exterior_ring(poly), strategy);\n\n        auto&& rings = interior_rings(poly);\n        auto const end = boost::end(rings);\n        for (auto it = boost::begin(rings); it != end; ++it)\n        {\n            correct_ring<std::greater<>>::apply(*it, strategy);\n        }\n    }\n};\n\n\n}} // namespace detail::correct\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate <typename Geometry, typename Tag = typename tag<Geometry>::type>\nstruct correct: not_implemented<Tag>\n{};\n\ntemplate <typename Point>\nstruct correct<Point, point_tag>\n    : detail::correct::correct_nop\n{};\n\ntemplate <typename LineString>\nstruct correct<LineString, linestring_tag>\n    : detail::correct::correct_nop\n{};\n\ntemplate <typename Segment>\nstruct correct<Segment, segment_tag>\n    : detail::correct::correct_nop\n{};\n\n\ntemplate <typename Box>\nstruct correct<Box, box_tag>\n    : detail::correct::correct_box\n{};\n\ntemplate <typename Ring>\nstruct correct<Ring, ring_tag>\n    : detail::correct::correct_ring<>\n{};\n\ntemplate <typename Polygon>\nstruct correct<Polygon, polygon_tag>\n    : detail::correct::correct_polygon\n{};\n\n\ntemplate <typename MultiPoint>\nstruct correct<MultiPoint, multi_point_tag>\n    : detail::correct::correct_nop\n{};\n\n\ntemplate <typename MultiLineString>\nstruct correct<MultiLineString, multi_linestring_tag>\n    : detail::correct::correct_nop\n{};\n\n\ntemplate <typename Geometry>\nstruct correct<Geometry, multi_polygon_tag>\n    : detail::multi_modify<detail::correct::correct_polygon>\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy\n{\n\ntemplate\n<\n    typename Strategy,\n    bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategy>::value\n>\nstruct correct\n{\n    template <typename Geometry>\n    static inline void apply(Geometry& geometry, Strategy const& strategy)\n    {\n        dispatch::correct<Geometry>::apply(geometry, strategy);\n    }\n};\n\ntemplate <typename Strategy>\nstruct correct<Strategy, false>\n{\n    template <typename Geometry>\n    static inline void apply(Geometry& geometry, Strategy const& strategy)\n    {\n        // NOTE: calculate_point_order strategy should probably be used here instead.\n        using geometry::strategies::area::services::strategy_converter;\n        dispatch::correct<Geometry>::apply(geometry, strategy_converter<Strategy>::get(strategy));\n    }\n};\n\ntemplate <>\nstruct correct<default_strategy, false>\n{\n    template <typename Geometry>\n    static inline void apply(Geometry& geometry, default_strategy const& )\n    {\n        // NOTE: calculate_point_order strategy should probably be used here instead.\n        using strategy_type = typename strategies::area::services::default_strategy\n            <\n                Geometry\n            >::type;\n        dispatch::correct<Geometry>::apply(geometry, strategy_type());\n    }\n};\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_dynamic\n{\n\ntemplate <typename Geometry, typename Tag = typename tag<Geometry>::type>\nstruct correct\n{\n    template <typename Strategy>\n    static inline void apply(Geometry& geometry, Strategy const& strategy)\n    {\n        concepts::check<Geometry>();\n        resolve_strategy::correct<Strategy>::apply(geometry, strategy);\n    }\n};\n\ntemplate <typename Geometry>\nstruct correct<Geometry, dynamic_geometry_tag>\n{\n    template <typename Strategy>\n    static inline void apply(Geometry& geometry, Strategy const& strategy)\n    {\n        traits::visit<Geometry>::apply([&](auto & g)\n        {\n            correct<util::remove_cref_t<decltype(g)>>::apply(g, strategy);\n        }, geometry);\n    }\n};\n\ntemplate <typename Geometry>\nstruct correct<Geometry, geometry_collection_tag>\n{\n    template <typename Strategy>\n    static inline void apply(Geometry& geometry, Strategy const& strategy)\n    {\n        detail::visit_breadth_first([&](auto & g)\n        {\n            correct<util::remove_cref_t<decltype(g)>>::apply(g, strategy);\n            return true;\n        }, geometry);\n    }\n};\n\n\n} // namespace resolve_dynamic\n\n\n/*!\n\\brief Corrects a geometry\n\\details Corrects a geometry: all rings which are wrongly oriented with respect\n    to their expected orientation are reversed. To all rings which do not have a\n    closing point and are typed as they should have one, the first point is\n    appended. Also boxes can be corrected.\n\\ingroup correct\n\\tparam Geometry \\tparam_geometry\n\\param geometry \\param_geometry which will be corrected if necessary\n\n\\qbk{[include reference/algorithms/correct.qbk]}\n*/\ntemplate <typename Geometry>\ninline void correct(Geometry& geometry)\n{\n    resolve_dynamic::correct<Geometry>::apply(geometry, default_strategy());\n}\n\n/*!\n\\brief Corrects a geometry\n\\details Corrects a geometry: all rings which are wrongly oriented with respect\n    to their expected orientation are reversed. To all rings which do not have a\n    closing point and are typed as they should have one, the first point is\n    appended. Also boxes can be corrected.\n\\ingroup correct\n\\tparam Geometry \\tparam_geometry\n\\tparam Strategy \\tparam_strategy{Area}\n\\param geometry \\param_geometry which will be corrected if necessary\n\\param strategy \\param_strategy{area}\n\n\\qbk{distinguish,with strategy}\n\n\\qbk{[include reference/algorithms/correct.qbk]}\n*/\ntemplate <typename Geometry, typename Strategy>\ninline void correct(Geometry& geometry, Strategy const& strategy)\n{\n    resolve_dynamic::correct<Geometry>::apply(geometry, strategy);\n}\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP\n", "meta": {"hexsha": "9d1f246a6ac83fda6ccc1989d661140f6711cca3", "size": 10055, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/algorithms/correct.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/algorithms/correct.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/algorithms/correct.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": 28.6467236467, "max_line_length": 98, "alphanum_fraction": 0.717851815, "num_tokens": 2243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.19665914095369982}}
{"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_X86_AVX_SIMD_FUNCTION_GROUP_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_AVX_SIMD_FUNCTION_GROUP_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/function/combine.hpp>\n#include <boost/simd/function/slice.hpp>\n#include <boost/simd/function/saturated.hpp>\n#include <boost/simd/detail/dispatch/meta/downgrade.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n\n   BOOST_DISPATCH_OVERLOAD( group_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::double_<A0>, avx_>\n                          , bs::pack_<bd::double_<A0>, avx_>\n                          )\n   {\n      using result = bd::downgrade_t<A0>;\n\n      BOOST_FORCEINLINE result operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n      {\n        using slice_t = typename A0::template rebind<typename result::value_type>;\n        return combine(slice_t(_mm256_cvtpd_ps(a0)),slice_t(_mm256_cvtpd_ps(a1)));\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD( group_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::integer_<A0>, avx_>\n                          , bs::pack_<bd::integer_<A0>, avx_>\n                          )\n   {\n      using result = bd::downgrade_t<A0>;\n\n      BOOST_FORCEINLINE result operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n      {\n        auto a0x = slice(a0), a1x = slice(a1);\n        auto v0  = group(a0x[0], a0x[1]);\n        auto v1  = group(a1x[0], a1x[1]);\n\n        return _mm256_insertf128_si256(_mm256_castsi128_si256(v0), v1, 1);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD( group_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::saturated_tag\n                          , bs::pack_<bd::integer_<A0>, avx_>\n                          , bs::pack_<bd::integer_<A0>, avx_>\n                          )\n   {\n      using result = bd::downgrade_t<A0>;\n\n      BOOST_FORCEINLINE\n      result operator()(bs::saturated_tag const&, const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n      {\n        auto a0x = slice(a0), a1x = slice(a1);\n        auto v0  = saturated_(group)(a0x[0], a0x[1]);\n        auto v1  = saturated_(group)(a1x[0], a1x[1]);\n\n        return _mm256_insertf128_si256(_mm256_castsi128_si256(v0), v1, 1);\n      }\n   };\n} } }\n\n#endif\n", "meta": {"hexsha": "0a4f4094c3a93eab172fa9fa9e58fb0c97427b22", "size": 2838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/avx/simd/function/group.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/x86/avx/simd/function/group.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/x86/avx/simd/function/group.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.037037037, "max_line_length": 100, "alphanum_fraction": 0.5257223397, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.196643766166744}}
{"text": "#include \"rdb_protocol/profile.hpp\"\n\n#include <inttypes.h>\n\n#include <limits>\n\n#include \"errors.hpp\"\n#include <boost/variant/static_visitor.hpp>\n\n#include \"containers/archive/stl_types.hpp\"\n#include \"logger.hpp\"\n#include \"rdb_protocol/math_utils.hpp\"\n#include \"rdb_protocol/datum.hpp\"\n#include \"rdb_protocol/env.hpp\"\n\nnamespace profile {\n\nstart_t::start_t() { }\n\nstart_t::start_t(const std::string &description)\n    : description_(description), when_(get_ticks()) { }\n\nRDB_IMPL_SERIALIZABLE_2_SINCE_v1_13(start_t, description_, when_);\n\nsplit_t::split_t() { }\n\nsplit_t::split_t(size_t n_parallel_jobs)\n    : n_parallel_jobs_(n_parallel_jobs) { }\n\nRDB_IMPL_SERIALIZABLE_1_SINCE_v1_13(split_t, n_parallel_jobs_);\n\nsample_t::sample_t() { }\n\nsample_t::sample_t(const std::string &description,\n        ticks_t mean_duration, size_t n_samples)\n    : description_(description), mean_duration_(mean_duration),\n      n_samples_(n_samples)\n{ }\n\nRDB_IMPL_SERIALIZABLE_3_SINCE_v1_13(sample_t, description_, mean_duration_, n_samples_);\n\nstop_t::stop_t()\n    : when_(get_ticks()) { }\n\nRDB_IMPL_SERIALIZABLE_1_SINCE_v1_13(stop_t, when_);\n\nql::datum_t construct_start(\n        ticks_t duration, std::string description,\n        ql::datum_t sub_tasks) {\n        std::map<datum_string_t, ql::datum_t> res;\n    res[datum_string_t(\"duration(ms)\")] =\n        ql::datum_t(safe_to_double(duration) / MILLION);\n    res[datum_string_t(\"description\")] =\n        ql::datum_t(datum_string_t(description));\n    res[datum_string_t(\"sub_tasks\")] = sub_tasks;\n    return ql::datum_t(std::move(res));\n}\n\nql::datum_t construct_split(\n        ql::datum_t par_tasks) {\n    std::map<datum_string_t, ql::datum_t> res;\n    res[datum_string_t(\"parallel_tasks\")] = par_tasks;\n    return ql::datum_t(std::move(res));\n}\n\nql::datum_t construct_sample(\n        const sample_t *sample) {\n    std::map<datum_string_t, ql::datum_t> res;\n    double mean_duration = safe_to_double(sample->mean_duration_) / MILLION;\n    double n_samples = safe_to_double(sample->n_samples_);\n    res[datum_string_t(\"mean_duration(ms)\")] = ql::datum_t(mean_duration);\n    res[datum_string_t(\"n_samples\")] = ql::datum_t(n_samples);\n    res[datum_string_t(\"description\")] =\n        ql::datum_t(datum_string_t(sample->description_));\n        return ql::datum_t(std::move(res));\n    return ql::datum_t();\n}\n\nql::datum_t construct_datum(\n        event_log_t::const_iterator *begin,\n        event_log_t::const_iterator end,\n        const ql::configured_limits_t &limits);\n\nclass construct_datum_visitor_t : public boost::static_visitor<void> {\npublic:\n    // N.B.: it is important that the lifetime of this visitor not\n    // exceed the lifetime of the limits reference: for example\n    // writing construct_datum_visitor_t v(begin, end,\n    // ql::configured_limits_t(), &res) is a terrible idea.  When in\n    // doubt, use construct_datum, which ensures that its lifetime is\n    // a subset of the limits lifetime.\n    construct_datum_visitor_t(\n        event_log_t::const_iterator *begin, event_log_t::const_iterator end,\n        const ql::configured_limits_t *limits,\n        std::vector<ql::datum_t> *res)\n        : begin_(begin), end_(end), limits_(limits), res_(res) { }\n\n    void operator()(const start_t &start) const {\n        (*begin_)++;\n        ql::datum_t sub_tasks = construct_datum(begin_, end_, *limits_);\n        auto stop = boost::get<stop_t>(&**begin_);\n        guarantee(stop);\n        res_->push_back(construct_start(\n            stop->when_ - start.when_, start.description_, sub_tasks));\n            (*begin_)++;\n    }\n    void operator()(const split_t &split) const {\n        (*begin_)++;\n        std::vector<ql::datum_t> parallel_tasks;\n        for (size_t i = 0; i < split.n_parallel_jobs_; ++i) {\n            parallel_tasks.push_back(construct_datum(begin_, end_, *limits_));\n            guarantee(boost::get<stop_t>(&**begin_));\n            (*begin_)++;\n        }\n        res_->push_back(construct_split(\n        ql::datum_t(std::move(parallel_tasks), *limits_)));\n    }\n    void operator()(const sample_t &sample) const {\n        (*begin_)++;\n        res_->push_back(construct_sample(&sample));\n    }\n    void operator()(const stop_t &) const {\n        //Nothing to do here\n    }\n\nprivate:\n    event_log_t::const_iterator *begin_;\n    event_log_t::const_iterator end_;\n    const ql::configured_limits_t *limits_;\n    std::vector<ql::datum_t> *res_;\n};\n\nql::datum_t construct_datum(\n        event_log_t::const_iterator *begin,\n        event_log_t::const_iterator end,\n        const ql::configured_limits_t &limits) {\n    std::vector<ql::datum_t> res;\n\n    construct_datum_visitor_t visitor(begin, end, &limits, &res);\n    while (*begin != end && !boost::get<stop_t>(&**begin)) {\n        boost::apply_visitor(visitor, **begin);\n    }\n\n    return ql::datum_t(std::move(res), limits);\n}\n\nclass print_event_log_visitor_t : public boost::static_visitor<void> {\npublic:\n    void operator()(const start_t &start) const {\n        logINF(\"Start: %s.\\n\", start.description_.c_str());\n    }\n    void operator()(const split_t &split) const {\n        logINF(\"Split: %zu.\\n\", split.n_parallel_jobs_);\n    }\n    void operator()(const sample_t &) const {\n        logINF(\"Sample.\");\n    }\n    void operator()(const stop_t &) const {\n        logINF(\"Stop.\\n\");\n    }\n};\n\nvoid print_event_log(const event_log_t &event_log) {\n    print_event_log_visitor_t visitor;\n    for (auto it = event_log.begin(); it != event_log.end(); ++it) {\n        boost::apply_visitor(visitor, *it);\n    }\n}\n\nstarter_t::starter_t(const std::string &description, trace_t *parent) {\n    init(description, parent);\n}\n\nstarter_t::starter_t(const std::string &description, const scoped_ptr_t<trace_t> &parent) {\n    init(description, parent.get_or_null());\n}\n\nstarter_t::~starter_t() {\n    if (parent_) {\n        parent_->stop();\n    }\n}\n\nvoid starter_t::init(const std::string &description, trace_t *parent) {\n    parent_ = parent;\n    if (parent_) {\n        parent_->start(description);\n    }\n}\n\nsplitter_t::splitter_t(trace_t *parent) {\n    init(parent);\n}\n\nsplitter_t::splitter_t(const scoped_ptr_t<trace_t> &parent) {\n    init(parent.get_or_null());\n}\n\nvoid splitter_t::give_splits(\n    size_t n_parallel_jobs, const event_log_t &event_log) {\n    n_parallel_jobs_ = n_parallel_jobs;\n    event_log_ = event_log;\n}\n\nsplitter_t::~splitter_t() {\n    if (parent_) {\n        parent_->stop_split(n_parallel_jobs_, event_log_);\n    }\n}\n\nvoid splitter_t::init(trace_t *parent) {\n    parent_ = parent;\n    n_parallel_jobs_ = 0;\n\n    if (parent_) {\n        parent_->start_split();\n    }\n}\n\nsampler_t::sampler_t(const std::string &description, trace_t *parent) {\n    init(description, parent);\n}\n\nsampler_t::sampler_t(const std::string &description, const scoped_ptr_t<trace_t> &parent) {\n    init(description, parent.get_or_null());\n}\n\nvoid sampler_t::init(const std::string &description, trace_t *parent) {\n    parent_ = parent;\n    description_ = description;\n    total_time_ = 0;\n    n_samples_ = 0;\n    if (parent_) {\n        parent_->start_sample(&event_log_);\n    }\n}\n\nticks_t duration(const event_log_t &event_log) {\n    guarantee(!event_log.empty());\n    if (auto start = boost::get<start_t>(&event_log.at(0))) {\n        auto stop = boost::get<stop_t>(&event_log.back());\n        guarantee(stop);\n        return stop->when_ - start->when_;\n    } else {\n        //This is a code path that is currently never hit and that will go a\n        //way when we implement more meaningful sampling functions.\n        return 0;\n    }\n}\n\nvoid sampler_t::new_sample() {\n    if (!event_log_.empty()) {\n        n_samples_++;\n        total_time_ += duration(event_log_);\n    }\n\n    event_log_.clear();\n}\n\nsampler_t::~sampler_t() {\n    new_sample();\n    if (parent_) {\n        if (n_samples_ > 0) {\n            parent_->stop_sample(description_, total_time_ / n_samples_, n_samples_, &event_log_);\n        } else {\n            parent_->stop_sample(&event_log_);\n        }\n    }\n}\n\ndisabler_t::disabler_t(trace_t *parent) {\n    init(parent);\n}\n\ndisabler_t::disabler_t(const scoped_ptr_t<trace_t> &parent) {\n    init(parent.get_or_null());\n}\n\ndisabler_t::~disabler_t() {\n    if (parent_) {\n        parent_->enable();\n    }\n}\n\nvoid disabler_t::init(trace_t *parent) {\n    parent_ = parent;\n    if (parent_) {\n        parent_->disable();\n    }\n}\n\ntrace_t::trace_t()\n    : redirected_event_log_(NULL), disabled_ref_count_(0) { }\n\nql::datum_t trace_t::as_datum() const {\n    guarantee(!redirected_event_log_);\n    event_log_t::const_iterator begin = event_log_.begin();\n    // Again, use defaults, as there's no predicting where this could\n    // come in response to user requests.\n    return construct_datum(&begin, event_log_.end(),\n                           ql::configured_limits_t());\n}\n\nevent_log_t trace_t::extract_event_log() RVALUE_THIS {\n    // These guarantees imply that this trace_t gets left in a default-constructed\n    // state (which is valid, thereby acceptable for an RVALUE_THIS function).\n    guarantee(redirected_event_log_ == NULL);\n    guarantee(disabled_ref_count_ == 0);\n    return std::move(event_log_);\n}\n\nvoid trace_t::start(const std::string &description) {\n    if (disabled()) { return; }\n    //debugf(\"Start %s %p.\\n\", description.c_str(), this);\n    event_log_target()->push_back(start_t(description));\n}\n\nvoid trace_t::stop() {\n    if (disabled()) { return; }\n    //debugf(\"Stop %p.\\n\", this);\n    event_log_target()->push_back(stop_t());\n}\n\nvoid trace_t::start_split() {\n    if (disabled()) { return; }\n    //debugf(\"Start split %p.\\n\", this);\n    event_log_target()->push_back(split_t());\n}\n\nvoid trace_t::stop_split(size_t n_parallel_jobs_, const event_log_t &par_event_log) {\n    if (disabled()) { return; }\n    //debugf(\"Stop split %zu, %p.\\n\", n_parallel_jobs_, this);\n    auto split = boost::get<split_t>(&event_log_target()->back());\n    guarantee(split);\n    split->n_parallel_jobs_ = n_parallel_jobs_;\n    event_log_target()->insert(event_log_target()->end(), par_event_log.begin(), par_event_log.end());\n}\n\nvoid trace_t::start_sample(event_log_t *event_log) {\n    if (disabled()) { return; }\n    //debugf(\"Start sample %p.\\n\", this);\n    /* This is a tad hacky. We currently don't  allow samples within samples.\n     * And if someone tries to do it the inner sample winds up just being a\n     * no-op. We should see if in practice this is something we actually want\n     * to support. */\n    if (!redirected_event_log_) {\n        redirected_event_log_ = event_log;\n    }\n}\n\nvoid trace_t::stop_sample(const std::string &description,\n        ticks_t mean_duration, size_t n_samples, event_log_t *event_log) {\n    if (disabled()) { return; }\n    //debugf(\"Stop sample %s, %p.\\n\", description.c_str(), this);\n    /* Don't reset the redirected_event_log_ if the sampler_t wasn't\n     * actually being redirected to. The predicate fails when the\n     * innter samplers in nested sampler_ts are destructed. */\n    if (event_log == redirected_event_log_) {\n        redirected_event_log_ = NULL;\n    }\n    event_log_target()->push_back(sample_t(description, mean_duration, n_samples));\n}\n\nvoid trace_t::stop_sample(event_log_t *event_log) {\n    if (disabled()) { return; }\n    //debugf(\"Stop sample %p.\\n\", this);\n    /* Don't reset the redirected_event_log_ if the sampler_t wasn't\n     * actually being redirected to. The predicate fails when the\n     * innter samplers in nested sampler_ts are destructed. */\n    if (event_log == redirected_event_log_) {\n        redirected_event_log_ = NULL;\n    }\n}\n\nvoid trace_t::disable() {\n    disabled_ref_count_++;\n}\nvoid trace_t::enable() {\n    disabled_ref_count_--;\n}\n\nbool trace_t::disabled() {\n    return disabled_ref_count_ > 0;\n}\n\nevent_log_t *trace_t::event_log_target() {\n    if (redirected_event_log_) {\n        return redirected_event_log_;\n    } else {\n        return &event_log_;\n    }\n}\n\n} //namespace profile\n", "meta": {"hexsha": "cda9f57d6297ddd448b0cf7ea4f473ba04322dd5", "size": 11890, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/rdb_protocol/profile.cc", "max_stars_repo_name": "NicoHood/rethinkdb", "max_stars_repo_head_hexsha": "8d7e97b7838b844902d222e7c9790fadbaf70441", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2018-09-27T04:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-03T12:53:01.000Z", "max_issues_repo_path": "src/rdb_protocol/profile.cc", "max_issues_repo_name": "NicoHood/rethinkdb", "max_issues_repo_head_hexsha": "8d7e97b7838b844902d222e7c9790fadbaf70441", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-09-27T14:36:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T12:59:39.000Z", "max_forks_repo_path": "src/rdb_protocol/profile.cc", "max_forks_repo_name": "NicoHood/rethinkdb", "max_forks_repo_head_hexsha": "8d7e97b7838b844902d222e7c9790fadbaf70441", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-10-05T11:42:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-04T02:35:31.000Z", "avg_line_length": 30.1012658228, "max_line_length": 102, "alphanum_fraction": 0.6666947014, "num_tokens": 3004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.19664376375077466}}
{"text": "#include \"NeuralNetworkPixelClassifiers.h\"\n#include \"image_loader.h\"\n\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n\n#include \"log4cxx/logger.h\"\n\n#include <boost/filesystem.hpp>\n#include <boost/regex.hpp>\n\n#include <string>\n#include <stdexcept>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <algorithm>\n#include <utility>\n\nstruct _StringComparator {\n\t  bool operator() (const std::string a, const std::string b) { return a < b;}\n} StringComparator;\n\nvoid NeuralNetworkPixelClassifiers::create_neural_networks( const unsigned int inputSize, const unsigned int numberOfClassifiers, const std::vector< unsigned int > hiddenLayers, const float learning_rate )\n{\n\tlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\n\tm_InputSize = inputSize;\n\tm_NumberOfClassifiers = numberOfClassifiers;\n\tm_NumberOfClasses = 1 == m_NumberOfClassifiers ? 2 : m_NumberOfClassifiers;\n\n\tstd::vector< unsigned int > layers = hiddenLayers;\n\tlayers.insert(layers.begin(), m_InputSize);\n\tlayers.push_back(1);\n\n\tfor(int i = 0; i < m_NumberOfClassifiers; ++i)\n\t{\n\t\tNeuralNetwork* ann = fann_create_standard_array(layers.size(), layers.data());\n\t\tfann_set_activation_function_hidden(ann, FANN_SIGMOID);\n\t\tfann_set_activation_function_output(ann, FANN_SIGMOID);\n\t\tfann_set_train_stop_function(ann, FANN_STOPFUNC_MSE);\n\t\tfann_set_learning_rate(ann, learning_rate);\n\n\t\tm_NeuralNetworks.push_back( boost::shared_ptr< NeuralNetwork >( ann, fann_destroy ) );\n\t}\n}\n\nbool score_comparator(std::pair< float, float> & a, std::pair< float, float> & b)\n{\n\treturn a.second < b.second;\n}\n\nvoid NeuralNetworkPixelClassifiers::train_neural_networks(\n\tFannClassificationDataset const *training_sets,\n\tconst unsigned int max_epoch,\n\tconst float mse_target,\n\tFannClassificationDataset const *validation_sets )\n{\n\tlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\n\tm_TrainingScoresHistory.clear();\n\n\tif(validation_sets != NULL) {\n\t\tm_TrainingScoresHistory.reserve(m_NumberOfClassifiers);\n\t\tfor(int i = 0; i < m_NumberOfClassifiers; ++i)\n\t\t\tm_TrainingScoresHistory.push_back(std::vector< std::pair< float, float > >());\n\t}\n\n\t#pragma omp parallel for\n\tfor(int i = 0; i < m_NumberOfClassifiers; ++i)\n\t{\n\t\tLOG4CXX_INFO(logger, \"Training ann #\" << i);\n\n\t\tboost::shared_ptr< NeuralNetwork > current_neural_network = m_NeuralNetworks[i];\n\t\tFannClassificationDataset::FannDataset *current_training_set = training_sets->getSet(i);\n\n\t\tif(validation_sets == NULL)\n\t\t{\n\t\t\tfann_train_on_data(current_neural_network.get(), current_training_set, max_epoch, 0, mse_target);\n\t\t} else {\n\t\t\tFannClassificationDataset::FannDataset *current_validation_set = validation_sets->getSet(i);\n\n\t\t\tstd::vector< boost::shared_ptr< NeuralNetwork > > trainingHistory;\n\t\t\ttrainingHistory.reserve(max_epoch);\n\n\t\t\tfor(int j = 0; j < max_epoch; ++j) {\n\t\t\t\tfloat train_mse      = fann_train_epoch( current_neural_network.get(), current_training_set  ),\n\t\t\t\t      validation_mse = fann_test_data(   current_neural_network.get(), current_validation_set );\n\n\t\t\t\ttrainingHistory.push_back( boost::shared_ptr< NeuralNetwork >( fann_copy(current_neural_network.get()), fann_destroy ) );\n\n\t\t\t\tm_TrainingScoresHistory[i].push_back(std::make_pair(train_mse, validation_mse));\n\n\t\t\t\tLOG4CXX_INFO(logger, \"MSE for ann #\" << i << \"; \" << j << \"; \" << train_mse << \"; \" << validation_mse);\n\t\t\t}\n\n\t\t\tconst int best_neural_network_index = std::distance(\n\t\t\t\t\tm_TrainingScoresHistory[i].begin(),\n\t\t\t\t\tstd::min_element(m_TrainingScoresHistory[i].begin(), m_TrainingScoresHistory[i].end(), score_comparator)\n\t\t\t\t);\n\n\t\t\tLOG4CXX_INFO(logger, \"Best neural network for dataset #\" << i << \" obtained at training-iteration #\" << best_neural_network_index << \": MSE=\" << m_TrainingScoresHistory[i][best_neural_network_index].second);\n\n\t\t\tm_NeuralNetworks[i] = boost::shared_ptr< NeuralNetwork >(trainingHistory[best_neural_network_index]);\n\n\t\t\tfann_test_data(m_NeuralNetworks[i].get(), current_validation_set);\n\t\t}\n\n\t\tLOG4CXX_INFO(logger, \"MSE for ann #\" << i << \": \" << fann_get_MSE(m_NeuralNetworks[i].get()));\n\t}\n}\n\nvoid NeuralNetworkPixelClassifiers::save(const std::string dir)\n{\n\tlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\tLOG4CXX_INFO(logger, \"Saving neural networks in \" << dir);\n\n\tfor(int i = 0; i < m_NumberOfClassifiers; ++i) {\n\t\tstd::ostringstream filename;\n\t\tfilename << std::setfill('0') << std::setw(6) << (i+1) << \".ann\";\n\n\t\tboost::filesystem::path path = boost::filesystem::path(dir) / filename.str();\n\n\t\tif(0 != fann_save(m_NeuralNetworks[i].get(), path.native().c_str())) {\n\t\t\tthrow std::runtime_error(\"Cannot save the neural-network in \" + path.native());\n\t\t}\n\n\t\tif(!m_TrainingScoresHistory.empty()) {\n\t\t\tstd::ostringstream filename;\n\t\t\tfilename << std::setfill('0') << std::setw(6) << (i+1) << \"-training-scores.dat\";\n\n\t\t\tboost::filesystem::path path = boost::filesystem::path(dir) / filename.str();\n\n\t\t\tstd::ofstream score_file;\n\t\t\tscore_file.exceptions(std::ofstream::failbit | std::ofstream::badbit);\n\t\t\tscore_file.open(path.native().c_str(), std::ios::out | std::ios::trunc); // This will erase the content of the file\n\n\t\t\ttry {\n\t\t\t\tfor(std::vector< std::pair< float, float > >::const_iterator it = m_TrainingScoresHistory[i].begin(); it != m_TrainingScoresHistory[i].end(); ++it) {\n\t\t\t\t\tscore_file << it->first << \"\\t\" << it->second << std::endl;\n\t\t\t\t}\n\n\t\t\t\tscore_file.close();\n\t\t\t} catch(std::ifstream::failure &e) {\n\t\t\t\tthrow std::runtime_error(\"Cannot save the neural-network training-scores file in \" + path.native() + \" (\" + e.what() + \")\");\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NeuralNetworkPixelClassifiers::load(const std::string dir)\n{\n\tlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\tLOG4CXX_INFO(logger, \"Loading neural networks from \" << dir);\n\n\tm_TrainingScoresHistory.clear();\n\n\tconst boost::regex config_file_filter( \"\\\\d{6,6}.ann\" );\n\tstd::vector< std::string > config_files;\n\n\tboost::filesystem::directory_iterator end_itr; // Default ctor yields past-the-end\n\tfor( boost::filesystem::directory_iterator i( dir ); i != end_itr; ++i ) {\n\t\t// Skip if not a file\n\t\tif( !boost::filesystem::is_regular_file( i->status() ) ) continue;\n\n\t\tboost::smatch what;\n\n\t\t// Skip if no match\n\t\tif( !boost::regex_match( i->path().filename().native(), what, config_file_filter ) ) continue;\n\n\t\t// File matches, store it\n\t\tconfig_files.push_back( i->path().native() );\n\t}\n\n\tstd::sort(config_files.begin(), config_files.end(), StringComparator);\n\n\tm_NumberOfClassifiers = config_files.size();\n\tm_NumberOfClasses = 1 == m_NumberOfClassifiers ? 2 : m_NumberOfClassifiers;\n\n\tfor(std::vector<std::string>::const_iterator it = config_files.begin(); it != config_files.end(); ++it) {\n\t\tLOG4CXX_INFO(logger, \"Loading neural network from \" << *it);\n\n\t\tNeuralNetwork* ann = fann_create_from_file(it->c_str());\n\n\t\tif(ann == NULL)\n\t\t\tthrow std::runtime_error(\"Cannot load neural network from \" + *it);\n\n\t\tm_NeuralNetworks.push_back( boost::shared_ptr< NeuralNetwork >( ann, fann_destroy ) );\n\t}\n\n\tm_InputSize = fann_get_num_input(m_NeuralNetworks.front().get());\n\n\tLOG4CXX_INFO(logger, \"Number of components per pixel: \" << m_InputSize);\n}\n\nstd::vector<float> NeuralNetworkPixelClassifiers::classify(const std::vector< fann_type > &input) const\n{\n\tstd::vector<float> result(m_NumberOfClassifiers);\n\n\tfor(int i = 0; i < m_NumberOfClassifiers; ++i)\n\t{\n\t\tdouble* r = fann_run( m_NeuralNetworks[i].get(), const_cast<fann_type *>( input.data() ) );\n\t\tresult[i] = r[0];\n\t}\n\n\treturn result;\n}\n", "meta": {"hexsha": "cdd65cc268920fb7471cc2ecc82612c98068dc63", "size": 7453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NeuralNetworkPixelClassifiers.cpp", "max_stars_repo_name": "Sigill/isgcr", "max_stars_repo_head_hexsha": "3fbca4aeef25be2195885d69dcd89f3669c2602f", "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": "NeuralNetworkPixelClassifiers.cpp", "max_issues_repo_name": "Sigill/isgcr", "max_issues_repo_head_hexsha": "3fbca4aeef25be2195885d69dcd89f3669c2602f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NeuralNetworkPixelClassifiers.cpp", "max_forks_repo_name": "Sigill/isgcr", "max_forks_repo_head_hexsha": "3fbca4aeef25be2195885d69dcd89f3669c2602f", "max_forks_repo_licenses": ["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.0048309179, "max_line_length": 210, "alphanum_fraction": 0.7191734872, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19664376237036085}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2012-2020 Barend Gehrels, Amsterdam, the Netherlands.\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_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\r\n\r\n#include <boost/geometry/core/assert.hpp>\r\n#include <boost/geometry/arithmetic/infinite_line_functions.hpp>\r\n#include <boost/geometry/algorithms/detail/make/make.hpp>\r\n\r\n#include <boost/core/ignore_unused.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail { namespace buffer\r\n{\r\n\r\n// TODO: it might once be changed this to proper strategy\r\nstruct line_line_intersection\r\n{\r\n    template <typename Point>\r\n    static inline Point\r\n    apply(Point const& pi, Point const& pj, Point const& qi, Point const& qj)\r\n    {\r\n        typedef typename coordinate_type<Point>::type ct;\r\n        typedef model::infinite_line<ct> line_type;\r\n\r\n        line_type const p = detail::make::make_infinite_line<ct>(pi, pj);\r\n        line_type const q = detail::make::make_infinite_line<ct>(qi, qj);\r\n\r\n        // The input lines are not parallel, they intersect, because\r\n        // their join type is checked before.\r\n        Point ip;\r\n        bool const intersecting = arithmetic::intersection_point(p, q, ip);\r\n        BOOST_GEOMETRY_ASSERT(intersecting);\r\n        boost::ignore_unused(intersecting);\r\n\r\n        return ip;\r\n    }\r\n};\r\n\r\n\r\n}} // namespace detail::buffer\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\r\n", "meta": {"hexsha": "1516f242aa73098fccb274ba5d1af96e76143c91", "size": 1828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/algorithms/detail/buffer/line_line_intersection.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/geometry/algorithms/detail/buffer/line_line_intersection.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/geometry/algorithms/detail/buffer/line_line_intersection.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": 30.4666666667, "max_line_length": 80, "alphanum_fraction": 0.7188183807, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.19664375857397778}}
{"text": "#pragma once\n\n#include <array>\n#include <condition_variable>\n#include <type_traits>\n\n#include <blake2/blake2.h>\n\n#include <boost/iostreams/device/back_inserter.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <cryptopp/osrng.h>\n\n#include <liblmdb/lmdb.h>\n\n#include <paper/config.hpp>\n\nnamespace paper\n{\nextern CryptoPP::AutoSeededRandomPool random_pool;\n// We operate on streams of uint8_t by convention\nusing stream = std::basic_streambuf <uint8_t>;\nusing bufferstream = boost::iostreams::stream_buffer <boost::iostreams::basic_array_source <uint8_t>>;\nusing vectorstream = boost::iostreams::stream_buffer <boost::iostreams::back_insert_device <std::vector <uint8_t>>>;\n// OS-specific way of finding a path to a home directory.\nboost::filesystem::path working_path ();\n// Get a unique path within the home directory, used for testing\nboost::filesystem::path unique_path ();\n// Read a raw byte stream the size of `T' and fill value.\ntemplate <typename T>\nbool read (paper::stream & stream_a, T & value)\n{\n\tstatic_assert (std::is_pod <T>::value, \"Can't stream read non-standard layout types\");\n\tauto amount_read (stream_a.sgetn (reinterpret_cast <uint8_t *> (&value), sizeof (value)));\n\treturn amount_read != sizeof (value);\n}\ntemplate <typename T>\nvoid write (paper::stream & stream_a, T const & value)\n{\n\tstatic_assert (std::is_pod <T>::value, \"Can't stream write non-standard layout types\");\n\tauto amount_written (stream_a.sputn (reinterpret_cast <uint8_t const *> (&value), sizeof (value)));\n\tassert (amount_written == sizeof (value));\n}\nstd::string to_string_hex (uint64_t);\nbool from_string_hex (std::string const &, uint64_t &);\n\nusing uint128_t = boost::multiprecision::uint128_t;\nusing uint256_t = boost::multiprecision::uint256_t;\nusing uint512_t = boost::multiprecision::uint512_t;\n// SI dividers\npaper::uint128_t const Gpaper_ratio = paper::uint128_t (\"1000000000000000000000000000000000\"); // 10^33\npaper::uint128_t const Mpaper_ratio = paper::uint128_t (\"1000000000000000000000000000000\"); // 10^30\npaper::uint128_t const kpaper_ratio = paper::uint128_t (\"1000000000000000000000000000\"); // 10^27\npaper::uint128_t const  paper_ratio = paper::uint128_t (\"1000000000000000000000000\"); // 10^24\npaper::uint128_t const mpaper_ratio = paper::uint128_t (\"1000000000000000000000\"); // 10^21\npaper::uint128_t const upaper_ratio = paper::uint128_t (\"1000000000000000000\"); // 10^18\nclass mdb_env\n{\npublic:\n\tmdb_env (bool &, boost::filesystem::path const &);\n\t~mdb_env ();\n\toperator MDB_env * () const;\n\tvoid add_transaction ();\n\tvoid remove_transaction ();\n\tMDB_env * environment;\n\tstd::mutex lock;\n\tstd::condition_variable open_notify;\n\tunsigned open_transactions;\n\tunsigned transaction_iteration;\n\tstd::condition_variable resize_notify;\n\tbool resizing;\n};\nclass mdb_val\n{\npublic:\n\tmdb_val (size_t, void *);\n\toperator MDB_val * () const;\n\toperator MDB_val const & () const;\n\tMDB_val value;\n};\nclass transaction\n{\npublic:\n\ttransaction (paper::mdb_env &, MDB_txn *, bool);\n\t~transaction ();\n\toperator MDB_txn * () const;\n\tMDB_txn * handle;\n\tpaper::mdb_env & environment;\n};\nunion uint128_union\n{\npublic:\n\tuint128_union () = default;\n\tuint128_union (std::string const &);\n\tuint128_union (uint64_t);\n\tuint128_union (paper::uint128_union const &) = default;\n\tuint128_union (paper::uint128_t const &);\n\tbool operator == (paper::uint128_union const &) const;\n\tvoid encode_hex (std::string &) const;\n\tbool decode_hex (std::string const &);\n\tvoid encode_dec (std::string &) const;\n\tbool decode_dec (std::string const &);\n\tpaper::uint128_t number () const;\n\tvoid clear ();\n\tbool is_zero () const;\n\tpaper::mdb_val val () const;\n\tstd::string to_string () const;\n\tstd::array <uint8_t, 16> bytes;\n\tstd::array <char, 16> chars;\n\tstd::array <uint32_t, 4> dwords;\n\tstd::array <uint64_t, 2> qwords;\n};\n// Balances are 128 bit.\nusing amount = uint128_union;\nunion uint256_union\n{\n\tuint256_union () = default;\n\tuint256_union (std::string const &);\n\tuint256_union (uint64_t, uint64_t = 0, uint64_t = 0, uint64_t = 0);\n\tuint256_union (paper::uint256_t const &);\n\tuint256_union (paper::uint256_union const &, paper::uint256_union const &, uint128_union const &);\n\tuint256_union (MDB_val const &);\n\tuint256_union prv (uint256_union const &, uint128_union const &) const;\n\tuint256_union & operator ^= (paper::uint256_union const &);\n\tuint256_union operator ^ (paper::uint256_union const &) const;\n\tbool operator == (paper::uint256_union const &) const;\n\tbool operator != (paper::uint256_union const &) const;\n\tbool operator < (paper::uint256_union const &) const;\n\tpaper::mdb_val val () const;\n\tvoid encode_hex (std::string &) const;\n\tbool decode_hex (std::string const &);\n\tvoid encode_dec (std::string &) const;\n\tbool decode_dec (std::string const &);\n\tvoid encode_base58check (std::string &) const;\n\tstd::string to_base58check () const;\n\tbool decode_base58check (std::string const &);\n\tstd::array <uint8_t, 32> bytes;\n\tstd::array <char, 32> chars;\n\tstd::array <uint64_t, 4> qwords;\n\tstd::array <uint128_union, 2> owords;\n\tvoid clear ();\n\tbool is_zero () const;\n\tstd::string to_string () const;\n\tpaper::uint256_t number () const;\n};\n// All keys and hashes are 256 bit.\nusing block_hash = uint256_union;\nusing account = uint256_union;\nusing public_key = uint256_union;\nusing private_key = uint256_union;\nusing secret_key = uint256_union;\nusing checksum = uint256_union;\nunion uint512_union\n{\n\tuint512_union () = default;\n\tuint512_union (paper::uint512_t const &);\n\tbool operator == (paper::uint512_union const &) const;\n\tbool operator != (paper::uint512_union const &) const;\n\tpaper::uint512_union & operator ^= (paper::uint512_union const &);\n\tvoid encode_hex (std::string &) const;\n\tbool decode_hex (std::string const &);\n\tstd::array <uint8_t, 64> bytes;\n\tstd::array <uint32_t, 16> dwords;\n\tstd::array <uint64_t, 8> qwords;\n\tstd::array <uint256_union, 2> uint256s;\n\tvoid clear ();\n\tboost::multiprecision::uint512_t number () const;\n};\n// Only signatures are 512 bit.\nusing signature = uint512_union;\npaper::uint512_union sign_message (paper::private_key const &, paper::public_key const &, paper::uint256_union const &);\nbool validate_message (paper::public_key const &, paper::uint256_union const &, paper::uint512_union const &);\n}", "meta": {"hexsha": "b22e1f238228bd7ca2a665edbfe45dd739ab4508", "size": 6296, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "paper/utility.hpp", "max_stars_repo_name": "paper-project/paper", "max_stars_repo_head_hexsha": "d558d26c1df95a13ba8957790e511ced8a62ec73", "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": "paper/utility.hpp", "max_issues_repo_name": "paper-project/paper", "max_issues_repo_head_hexsha": "d558d26c1df95a13ba8957790e511ced8a62ec73", "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": "paper/utility.hpp", "max_forks_repo_name": "paper-project/paper", "max_forks_repo_head_hexsha": "d558d26c1df95a13ba8957790e511ced8a62ec73", "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.9771428571, "max_line_length": 120, "alphanum_fraction": 0.7387229987, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.19656440787468585}}
{"text": "#include <mtpio/chain/platform_timer_accuracy.hpp>\n#include <mtpio/chain/platform_timer.hpp>\n\n#include <fc/time.hpp>\n#include <fc/log/logger.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/weighted_mean.hpp>\n#include <boost/accumulators/statistics/weighted_variance.hpp>\n\n#include <chrono>\n#include <mutex>\n\nnamespace mtpio { namespace chain {\n\nnamespace bacc = boost::accumulators;\n\nvoid compute_and_print_timer_accuracy(platform_timer& timer) {\n   static std::mutex m;\n   static bool once_is_enough;\n\n   std::lock_guard guard(m);\n\n   if(once_is_enough)\n      return;\n\n   bacc::accumulator_set<int, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::variance>, float> samples;\n\n   //keep longest first in list. You're effectively going to take test_intervals[0]*sizeof(test_intervals[0])\n   //time to do the the test\n   int test_intervals[] = {50000, 10000, 5000, 1000, 500, 100, 50, 10};\n\n   for(int& interval : test_intervals) {\n      unsigned int loops = test_intervals[0]/interval;\n\n      for(unsigned int i = 0; i < loops; ++i) {\n         auto start = std::chrono::high_resolution_clock::now();\n         timer.start(fc::time_point(fc::time_point::now().time_since_epoch() + fc::microseconds(interval)));\n         while(!timer.expired) {}\n         auto end = std::chrono::high_resolution_clock::now();\n         int timer_slop = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() - interval;\n\n         //since more samples are run for the shorter expirations, weigh the longer expirations accordingly. This\n         //helps to make a few results more fair. Two such examples: AWS c4&i5 xen instances being rather stable\n         //down to 100us but then struggling with 50us and 10us. MacOS having performance that seems to correlate\n         //with expiry length; that is, long expirations have high error, short expirations have low error.\n         //That said, for these platforms, a tighter tolerance may possibly be achieved by taking performance\n         //metrics in mulitple bins and appliying the slop based on which bin a deadline resides in. Not clear\n         //if that's worth the extra complexity at this point.\n         samples(timer_slop, bacc::weight = interval/(float)test_intervals[0]);\n      }\n   }\n\n   #define TIMER_STATS_FORMAT \"min:${min}us max:${max}us mean:${mean}us stddev:${stddev}us\"\n   #define TIMER_STATS \\\n      (\"min\", bacc::min(samples))(\"max\", bacc::max(samples)) \\\n      (\"mean\", (int)bacc::mean(samples))(\"stddev\", (int)sqrt(bacc::variance(samples)))\n\n   ilog(\"Checktime timer accuracy: \" TIMER_STATS_FORMAT, TIMER_STATS);\n   if(bacc::mean(samples) + sqrt(bacc::variance(samples))*2 > 250)\n      wlog(\"Checktime timer accuracy on this platform and hardware combination is poor; accuracy of subjective transaction deadline enforcement will suffer\");\n\n   once_is_enough = true;\n}\n\n}}\n", "meta": {"hexsha": "b4bb58a8d1ec83f4326ee894a1e8c6904dacdd91", "size": 3059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/platform_timer_accuracy.cpp", "max_stars_repo_name": "mtpbuilder/mtp", "max_stars_repo_head_hexsha": "9dbc99e91b7d0900b75ad4a461a1da9da2c80450", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T08:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-07T07:51:52.000Z", "max_issues_repo_path": "libraries/chain/platform_timer_accuracy.cpp", "max_issues_repo_name": "zhllljm/mtp", "max_issues_repo_head_hexsha": "9dbc99e91b7d0900b75ad4a461a1da9da2c80450", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/platform_timer_accuracy.cpp", "max_forks_repo_name": "zhllljm/mtp", "max_forks_repo_head_hexsha": "9dbc99e91b7d0900b75ad4a461a1da9da2c80450", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2020-08-04T08:59:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-07T07:51:54.000Z", "avg_line_length": 43.7, "max_line_length": 158, "alphanum_fraction": 0.7119973848, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1965644063000309}}
{"text": "#define BOOST_TEST_MODULE Test\n\n#include \"keyboard_optimizer/concepts.hpp\"\n#include \"keyboard_optimizer/layout.hpp\"\n#include \"keyboard_optimizer/standart_constraints.hpp\"\n#include \"keyboard_optimizer/standart_effort_model.hpp\"\n#include \"keyboard_optimizer/standart_optimizer.hpp\"\n#include \"keyboard_optimizer/utils.hpp\"\n#include \"utility/type_traits.hpp\"\n#include \"tbb/concurrent_unordered_set.h\"\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/cycle_canceling.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/graph/read_dimacs.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/property_map/function_property_map.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <iostream>\n\nusing namespace KeyboardOptimizer;\nBOOST_AUTO_TEST_CASE(compile_test) {\n  using AllowedKeys = StandartConstraints::AllowedKeys;\n  using SymBonds = StandartConstraints::SymBonds;\n  using SymConstraints = StandartConstraints::SymConstraints;\n  using SymLayers = StandartConstraints::SymLayers;\n  auto key = Key(1, 1.0);\n  auto layer = Layer{0};\n  auto press = Press{key, layer};\n  auto modifier = Modifier{};\n  auto keyboard = Keyboard{key};\n  auto mods = LayersMap<Modifier>{modifier};\n  auto finger = Finger{FingerType::Index, Hand::Left};\n  auto pfmap = PressFingerMap{{press, finger}};\n  auto pemap = PressEffortMap{{press, 1.0}};\n  auto sym = Sym{0};\n  auto symLayers = SymLayers{layer};\n  auto symBonds = SymBonds{sym};\n  auto symConsts = SymConstraints{AllowedKeys{key}};\n  auto layout = Layout{press};\n  auto constParams = StandartConstraintsParameters{};\n  auto constsPtr = std::unique_ptr<StandartConstraints>{};\n  {\n    auto consts2 = StandartConstraints{\n        std::move(symLayers), std::move(symBonds), std::move(symConsts),\n        Keyboard(keyboard), std::move(constParams)};\n    constsPtr = std::make_unique<StandartConstraints>(consts2);\n  }\n  auto consts = std::move(*constsPtr);\n\n  auto emparams = StandartEffortModelParameters{};\n  auto emodelPtr = std::unique_ptr<StandartEffortModel>{};\n  {\n    auto fp = FingerPositions(NFingers, key);\n    auto emodel2 =\n        StandartEffortModel{std::move(mods), std::move(pfmap), std::move(pemap),\n                            std::move(fp), std::move(emparams)};\n    emodelPtr = std::make_unique<StandartEffortModel>(emodel2);\n  }\n  auto emodel = std::move(*emodelPtr);\n\n  auto text = SymString(1000, sym);\n  auto bench = StandartOptimizerBenchmarkParameters{};\n  bench.genOverheadTextSize = 20;\n  bench.genOverheadRuns = 1;\n  bench.DNAOverheadPopulationSize = 10;\n  bench.DNAOverheadRuns = 1;\n  bench.errorFactorRuns = 5;\n\n  auto opt = StandartOptimizer(SymString(text), StandartEffortModel{emodel},\n                               StandartConstraints(consts), bench);\n  auto modelParams = opt.GetModelParameters();\n  auto opt1 =\n      StandartOptimizer(SymString(text), StandartEffortModel{emodel},\n                        StandartConstraints(consts), std::move(modelParams));\n  opt.Optimize();\n  opt1.Optimize();\n}\n\nBOOST_AUTO_TEST_CASE(copy_move_test) {\n  using AllowedKeys = StandartConstraints::AllowedKeys;\n  using SymBonds = StandartConstraints::SymBonds;\n  using SymConstraints = StandartConstraints::SymConstraints;\n  using SymLayers = StandartConstraints::SymLayers;\n  static_assert(std::copyable<StandartConstraints>);\n  static_assert(std::copyable<StandartEffortModel>);\n  static_assert(std::copyable<\n                StandartOptimizer<StandartEffortModel, StandartConstraints>>);\n\n  auto modifier = Modifier{};\n  auto mods = LayersMap<Modifier>{modifier};\n\n  auto N = size_t{100};\n  auto layer = Layer{0};\n  auto syms = Utility::GetIndices(N);\n  auto keyboard = Keyboard{};\n  auto symLayers = SymLayers{};\n  auto symBonds = SymBonds{};\n  auto symConsts = SymConstraints{};\n  symConsts.reserve(N);\n  keyboard.reserve(N);\n  symLayers.reserve(N);\n  symBonds.reserve(N);\n  for (auto i = size_t{0}; i != N; ++i) {\n    keyboard.emplace_back(static_cast<int>(i), 1.0);\n    symLayers.push_back(layer);\n    symBonds.push_back(i);\n  }\n  for (auto i = size_t{0}; i != N; ++i)\n    symConsts.emplace_back(keyboard.begin(), keyboard.end());\n  auto antiDCE = size_t{0};\n  auto consts = StandartConstraints{std::move(symLayers), std::move(symBonds),\n                                    std::move(symConsts), Keyboard(keyboard)};\n  auto copyTime = Utility::Benchmark([&]() { auto c2 = consts; }, 100);\n  auto moveTime = Utility::Benchmark(\n      [&]() {\n        auto c2 = std::move(consts);\n        consts = std::move(c2);\n      },\n      100);\n\n  BOOST_TEST((copyTime > moveTime * 10));\n\n  std::cout << std::endl;\n  std::cout << \"Benchmark of move and copy StandartConstraints:\" << std::endl;\n  std::cout << \"With \" << N << \" syms and \" << keyboard.size() << \" keys\"\n            << std::endl;\n  std::cout << \"Copy time: \" << copyTime.count() << \" nanoseconds\" << std::endl;\n  std::cout << \"Move time: \" << moveTime.count() << \" nanoseconds\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(concepts_test) {\n  static_assert(ConstraintsConcept<StandartConstraints>);\n  static_assert(EffortModelConcept<StandartEffortModel>);\n  static_assert(OptimizerConcept<\n                StandartOptimizer<StandartEffortModel, StandartConstraints>>);\n}\n\nBOOST_AUTO_TEST_CASE(layout_hash_benchmark) {\n  auto N = 1000;\n  auto NSyms = 100;\n  auto hashT = std::chrono::nanoseconds{0};\n\n  for (auto i = 0; i != N; ++i) {\n    auto layout = Layout{};\n    for (auto j = 0; j != NSyms; ++j)\n      layout.emplace_back(Key{i, static_cast<double>(j)}, 0);\n    hashT += Utility::Benchmark([&]() { std::hash<Layout>{}(layout); });\n  }\n  auto time = hashT.count() / static_cast<double>(N);\n  std::cout << std::endl;\n  std::cout << \"Layout hashing time \" + std::to_string(time) + \" nanoseconds\"\n            << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(random_benchmark) {\n  auto N = 1000;\n  auto timen = std::chrono::nanoseconds{0};\n  auto d = 0.0;\n  auto gen = std::mt19937();\n  auto rand = std::uniform_real_distribution<>{};\n\n  auto gentime = Utility::Benchmark([&]() { gen = std::mt19937(); }, N);\n  auto randtime = Utility::Benchmark(\n      [&]() { rand = std::uniform_real_distribution<>{}; }, N);\n  auto time = Utility::Benchmark([&]() { d += rand(gen); }, N);\n  std::cout << \"Generator create time:   \" + std::to_string(gentime.count()) +\n                   \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Distribution create time \" + std::to_string(randtime.count()) +\n                   \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Random time              \" + std::to_string(time.count()) +\n                   \" nanoseconds\"\n            << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(mst_benchmarks) {\n  struct VertexProperty final {\n    VertexProperty(){};\n  };\n  auto static lastind = size_t{0};\n  struct EdgeProperty {\n    size_t ind;\n    EdgeProperty() { ind = lastind++; };\n  };\n  using Graph =\n      boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n                            VertexProperty, EdgeProperty>;\n  using Edge = boost::graph_traits<Graph>::edge_descriptor;\n  using Vertex = boost::graph_traits<Graph>::vertex_descriptor;\n\n  auto nSyms = size_t{33};\n  auto nVertices = nSyms * 4;\n  auto nEdges = 3 * nSyms * nSyms;\n  auto g = Graph{};\n  auto gdynptr = std::make_unique<Graph>();\n  auto &&gdyn = *gdynptr;\n  auto gen = std::mt19937{};\n#pragma warning(disable : 4267)\n  boost::generate_random_graph(g, nVertices, nEdges, gen);\n  lastind = 0;\n  boost::generate_random_graph(gdyn, nVertices, nEdges, gen);\n#pragma warning(default : 4267)\n\n  auto rand = std::uniform_real_distribution<double>{};\n  auto antidce = size_t{0};\n  auto wmtime = Utility::Benchmark(\n      [&]() {\n        auto weightmap = std::vector<double>(nEdges);\n        for (auto i = 0; i < nEdges; ++i)\n          weightmap[i] = rand(gen);\n      },\n      2);\n  auto weightmap = std::vector<double>(nEdges);\n\n  auto fmtime = Utility::Benchmark(\n      [&]() {\n        auto fmap = boost::make_function_property_map<Edge>(\n            [&](auto e) { return weightmap[g[e].ind]; });\n      },\n      2);\n  auto fmap = boost::make_function_property_map<Edge>(\n      [&](auto e) { return weightmap[g[e].ind]; });\n  auto ptime =\n      Utility::Benchmark([&]() { auto props = boost::weight_map(fmap); }, 100);\n  auto props = boost::weight_map(fmap);\n  auto fmapdyn = boost::make_function_property_map<Edge>(\n      [&](auto e) { return weightmap[gdyn[e].ind]; });\n  auto propsdyn = boost::weight_map(fmapdyn);\n\n  auto predMap = std::vector<Vertex>(nVertices);\n  auto tprim = Utility::Benchmark(\n      [&]() { boost::prim_minimum_spanning_tree(g, &predMap[0], props); }, 30);\n  auto tprimdyn = Utility::Benchmark(\n      [&]() { boost::prim_minimum_spanning_tree(gdyn, &predMap[0], propsdyn); },\n      30);\n\n  auto spanning_tree = std::vector<Edge>{};\n  spanning_tree.reserve(nEdges);\n  auto tkruskal = Utility::Benchmark(\n      [&]() {\n        spanning_tree.clear();\n        boost::kruskal_minimum_spanning_tree(\n            g, std::back_inserter(spanning_tree), props);\n        antidce += spanning_tree.size();\n      },\n      10);\n  auto tkruskaldyn = Utility::Benchmark(\n      [&]() {\n        spanning_tree.clear();\n        boost::kruskal_minimum_spanning_tree(\n            gdyn, std::back_inserter(spanning_tree), propsdyn);\n        antidce += spanning_tree.size();\n      },\n      10);\n\n  auto g2 = g;\n  auto g3 = g;\n  auto tmove = Utility::Benchmark(\n                   [&]() {\n                     g3 = std::move(g2);\n                     g2 = std::move(g3);\n                     antidce += boost::num_edges(g2);\n                   },\n                   10) /\n               2;\n  auto tcopy = Utility::Benchmark(\n                   [&]() {\n                     g3 = g2;\n                     g2 = g3;\n                     antidce += boost::num_edges(g2);\n                   },\n                   10) /\n               2;\n\n  BOOST_TEST(antidce);\n  std::cout << std::endl;\n  std::cout << \"Benchmark of move and copy graphs:\" << std::endl;\n  std::cout << \"With \" << nVertices << \" vertices and \" << nEdges << \" edges\"\n            << std::endl;\n  std::cout << \"Move time: \" << tmove.count() << \" nanoseconds\" << std::endl;\n  std::cout << \"Copy time: \" << tcopy.count() << \" nanoseconds\" << std::endl;\n\n  std::cout << std::endl;\n  std::cout << \"Benchmark of prim and kruskal minimum spanning tree algorithms:\"\n            << std::endl;\n  std::cout << \"With \" << nVertices << \" vertices and \" << nEdges << \" edges\"\n            << std::endl;\n  std::cout << \"Weigth map creation time:            \" << wmtime.count()\n            << \" nanoseconds\" << std::endl;\n  std::cout << \"function_property_map creation time: \" << fmtime.count()\n            << \" nanoseconds\" << std::endl;\n  std::cout << \"Properties creation time:            \" << ptime.count()\n            << \" nanoseconds\" << std::endl;\n  std::cout << \"Prim                                 \" << tprim.count()\n            << \" nanoseconds\" << std::endl;\n  std::cout << \"Prim (dyn allocated graph)           \" << tprimdyn.count()\n            << \" nanoseconds\" << std::endl;\n  std::cout << \"Kruskal                              \" << tkruskal.count()\n            << \" nanoseconds\" << std::endl;\n  std::cout << \"Kruskal (dyn allocated graph)        \" << tkruskaldyn.count()\n            << \" nanoseconds\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(maxflow_benchmarks) {\n  auto static vertlastind = size_t{0};\n  struct VertexProperty final {\n    size_t ind;\n    VertexProperty() : ind(-1){};\n    VertexProperty(size_t ind) : ind(ind){};\n  };\n  auto static edgelastind = size_t{0};\n  using Edge = boost::graph_traits<boost::adjacency_list<\n      boost::vecS, boost::vecS, boost::directedS>>::edge_descriptor;\n  using Vertex = boost::graph_traits<boost::adjacency_list<\n      boost::vecS, boost::vecS, boost::directedS>>::vertex_descriptor;\n\n  using EdgeProperty = boost::property<\n      boost::edge_capacity_t, size_t,\n      boost::property<boost::edge_index_t, size_t,\n                      boost::property<boost::edge_reverse_t, Edge>>>;\n  using Graph =\n      boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n                            VertexProperty, EdgeProperty>;\n\n  auto nSyms = size_t{40};\n  auto nTryEdges = static_cast<size_t>(nSyms * nSyms * 0.8);\n  auto g = Graph{};\n  auto &&edge_index_map = boost::get(boost::edge_index, g);\n  auto &&capacity_map = boost::get(boost::edge_capacity, g);\n  auto &&reverse_edge_map = boost::get(boost::edge_reverse, g);\n  auto gen = std::mt19937{};\n  auto A = std::vector<Vertex>{};\n  auto B = std::vector<Vertex>{};\n  auto RevEdges = std::unordered_set<size_t>(nTryEdges * 3);\n  A.reserve(nSyms);\n  B.reserve(nSyms);\n  auto s = boost::add_vertex({vertlastind++}, g);\n  auto t = boost::add_vertex({vertlastind++}, g);\n  auto symRand = std::uniform_int_distribution<size_t>(0, nSyms - 1);\n  for (auto i = size_t{0}; i != nSyms; ++i) {\n    A.push_back(boost::add_vertex({vertlastind++}, g));\n    B.push_back(boost::add_vertex({vertlastind++}, g));\n  }\n  for (auto i = size_t{0}; i != nTryEdges; ++i) {\n    auto a = symRand(gen);\n    auto b = symRand(gen);\n    auto const &[tmp, isExist] = boost::edge(A[a], B[b], g);\n    if (isExist)\n      continue;\n    auto const &[dir, tmp2] = boost::add_edge(A[a], B[b], g);\n    auto const &[rev, success] = boost::add_edge(B[b], A[a], g);\n    edge_index_map[dir] = edgelastind++;\n    edge_index_map[rev] = edgelastind++;\n    RevEdges.insert(edge_index_map[rev]);\n  }\n  for (auto i = size_t{0}; i != nSyms; ++i) {\n    auto const &[dir1, tmp1] = boost::add_edge(s, A[i], g);\n    auto const &[rev1, success1] = boost::add_edge(A[i], s, g);\n    auto const &[dir2, tmp2] = boost::add_edge(B[i], t, g);\n    auto const &[rev2, success2] = boost::add_edge(t, B[i], g);\n    edge_index_map[dir1] = edgelastind++;\n    edge_index_map[dir2] = edgelastind++;\n    edge_index_map[rev1] = edgelastind++;\n    edge_index_map[rev2] = edgelastind++;\n    RevEdges.insert(edge_index_map[rev1]);\n    RevEdges.insert(edge_index_map[rev2]);\n  }\n  auto nVertices = boost::num_vertices(g);\n  auto nEdges = boost::num_edges(g);\n\n  auto residualCapacityMap = std::vector<size_t>(nEdges);\n  auto colorMap = std::vector<boost::default_color_type>(nVertices);\n  auto predcessorMap = std::vector<Edge>(nVertices);\n  auto distanceMap = std::vector<int>(nVertices);\n  auto distanceMap2 = std::vector<int>(nVertices);\n  auto weigthMap = std::vector<int>(nEdges);\n\n  auto weightRand = std::uniform_int_distribution<>(0, 10);\n  std::generate(weigthMap.begin(), weigthMap.end(),\n                [&]() { return weightRand(gen); });\n  for (auto const &e : boost::make_iterator_range(boost::edges(g))) {\n    auto source = boost::source(e, g);\n    auto target = boost::target(e, g);\n    auto const &[revEdge, isExist] = boost::edge(target, source, g);\n    assert(isExist);\n    assert(revEdge != e);\n    auto ind = edge_index_map[e];\n    auto revind = edge_index_map[revEdge];\n    reverse_edge_map[e] = revEdge;\n    if (RevEdges.contains(ind)) {\n      weigthMap[ind] = -weigthMap[revind];\n      capacity_map[e] = 0;\n    } else\n      capacity_map[e] = 1;\n  }\n  auto vertex_index_map = boost::make_function_property_map<Vertex>(\n      [&](auto const &v) { return g[v].ind; });\n  auto residual_capacity = boost::make_iterator_property_map(\n      residualCapacityMap.begin(), edge_index_map);\n  auto color_map =\n      boost::make_iterator_property_map(colorMap.begin(), vertex_index_map);\n  auto predcessor_map = boost::make_iterator_property_map(predcessorMap.begin(),\n                                                          vertex_index_map);\n  auto distance_map =\n      boost::make_iterator_property_map(distanceMap.begin(), vertex_index_map);\n  auto distance_map2 =\n      boost::make_iterator_property_map(distanceMap2.begin(), vertex_index_map);\n  auto weight_map =\n      boost::make_iterator_property_map(weigthMap.begin(), edge_index_map);\n  auto props = boost::weight_map(weight_map)\n                   .residual_capacity_map(residual_capacity)\n                   .distance_map(distance_map)\n                   .distance_map2(distance_map2)\n                   .vertex_index_map(vertex_index_map)\n                   .predecessor_map(predcessor_map)\n                   .color_map(color_map);\n\n  struct Filter final {\n    bool x;\n    Filter() {}\n    Filter(bool x) : x(x) {}\n    bool operator()(Edge const &e) const { return x; }\n    bool operator()(Vertex const &v) const { return x; }\n  };\n\n  struct VertexFilter final {\n    bool x;\n    VertexFilter() {}\n    VertexFilter(bool x) : x(x) {}\n    bool operator()(Vertex const &v) const { return x; }\n  };\n  using FilteredGraph = boost::filtered_graph<Graph, Filter, Filter>;\n  auto static volatile x = true; // anti-optimization\n  auto copyTime = std::chrono::nanoseconds{};\n  auto filtTime = std::chrono::nanoseconds{};\n  {\n    auto gv = std::vector<Graph>{};\n    auto gv2 = std::vector<FilteredGraph>{};\n    copyTime = Utility::Benchmark([&]() { gv.push_back(g); }, 1000);\n    filtTime = Utility::Benchmark(\n        [&]() { gv2.push_back(FilteredGraph(g, Filter(x), Filter(x))); }, 1000);\n  }\n\n  auto g2 = FilteredGraph(g, Filter(x), Filter(x));\n\n  auto antiDCECounter = size_t{0};\n  auto randedgetime = Utility::Benchmark(\n      [&]() {\n#pragma warning(disable : 4267)\n        auto &&e = boost::random_edge(g, gen);\n#pragma warning(default : 4267)\n        antiDCECounter += weight_map[e];\n      },\n      1000);\n  auto gettime = Utility::Benchmark(\n                     [&]() {\n#pragma warning(disable : 4267)\n                       auto &&e = boost::random_edge(g, gen);\n#pragma warning(default : 4267)\n                       auto &&a = boost::get(boost::edge_index, g);\n                       auto &&b = boost::get(boost::edge_capacity, g);\n                       auto &&c = boost::get(boost::edge_reverse, g);\n                       antiDCECounter += a[e];\n                       antiDCECounter += b[e];\n                       antiDCECounter += b[c[e]];\n                     },\n                     1000) -\n                 randedgetime;\n\n  auto rev1time = Utility::Benchmark(\n      [&]() {\n        auto e = boost::random_edge(g, gen);\n        auto ind = edge_index_map[e];\n        antiDCECounter += RevEdges.contains(ind);\n      },\n      1000);\n\n  auto bktime = Utility::Benchmark(\n      [&]() { boost::boykov_kolmogorov_max_flow(g, s, t, props); }, 10);\n  auto bktime2 = Utility::Benchmark(\n      [&]() { boost::boykov_kolmogorov_max_flow(g2, s, t, props); }, 10);\n\n  auto ektime = Utility::Benchmark(\n      [&]() { boost::edmonds_karp_max_flow(g, s, t, props); }, 10);\n  auto ektime2 = Utility::Benchmark(\n      [&]() { boost::edmonds_karp_max_flow(g2, s, t, props); }, 10);\n\n  auto prtime = Utility::Benchmark(\n      [&]() { boost::push_relabel_max_flow(g, s, t, props); }, 10);\n  auto prtime2 = Utility::Benchmark(\n      [&]() { boost::push_relabel_max_flow(g2, s, t, props); }, 10);\n\n  auto cctime = Utility::Benchmark(\n      [&]() {\n        std::generate(weigthMap.begin(), weigthMap.end(),\n                      [&]() { return weightRand(gen); });\n        boost::cycle_canceling(g, props);\n      },\n      10);\n  auto sstime = Utility::Benchmark(\n      [&]() {\n        std::generate(weigthMap.begin(), weigthMap.end(),\n                      [&]() { return weightRand(gen); });\n        boost::successive_shortest_path_nonnegative_weights(g, s, t, props);\n      },\n      10);\n  auto sstime2 = Utility::Benchmark(\n      [&]() {\n        std::generate(weigthMap.begin(), weigthMap.end(),\n                      [&]() { return weightRand(gen); });\n        boost::successive_shortest_path_nonnegative_weights(g2, s, t, props);\n      },\n      10);\n\n  std::cout << std::endl;\n  std::cout << \"Benchmark of max flow algorithms:\" << std::endl;\n  std::cout << \"With \" << nVertices << \" vertices and \" << nEdges << \" edges\"\n            << std::endl;\n  std::cout << \"Graph copy time:   \" << copyTime.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Graph filter time: \" << filtTime.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << std::endl;\n  std::cout << \"Boykov-Kolmogorov        \" << bktime.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Boykov-Kolmogorov (filt) \" << bktime2.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Edmonds-Karp             \" << ektime.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Edmonds-Karp (filt)      \" << ektime2.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Push-relabel             \" << prtime.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Push-relabel (filt)      \" << prtime2.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << std::endl;\n  std::cout << \"Benchmark of min const algorithms:\" << std::endl;\n  std::cout << \"Cycle canceling      \" << cctime.count()\n            << \" nanoseconds (does not work actually)\" << std::endl;\n  std::cout << \"Shortest path        \" << sstime.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << \"Shortest path (filt) \" << sstime2.count() << \" nanoseconds\"\n            << std::endl;\n  std::cout << std::endl;\n  std::cout << \"Benchmark of support functions:\" << std::endl;\n  std::cout << \"boost::random_edge  \" << randedgetime.count() << std::endl;\n  std::cout << \"boost::get  \" << gettime.count() << std::endl;\n\n  auto bridges = 0;\n  for (auto const &e : boost::make_iterator_range(boost::edges(g))) {\n    if (RevEdges.contains(edge_index_map[e]))\n      continue;\n    bridges += static_cast<int>(capacity_map[e]) -\n               static_cast<int>(residual_capacity[e]);\n  }\n\n  BOOST_TEST(bridges == nSyms * 3);\n  BOOST_TEST(antiDCECounter);\n}\n\nBOOST_AUTO_TEST_CASE(cont_benchmark) {\n  auto N = size_t{100};\n  auto syms = Utility::GetIndices(N);\n  auto gen = std::mt19937{};\n  auto rand = std::uniform_int_distribution<size_t>(0, N - 1);\n  auto layerRand = std::uniform_int_distribution<size_t>(0, 3);\n  auto symmap = std::unordered_map<Sym, size_t>{};\n  auto cnt = size_t{0};\n\n  auto presses = std::vector<Press>{};\n  auto pressmap = std::unordered_map<Press, size_t>{};\n  for (auto i = size_t{0}; i != N; ++i) {\n    auto press =\n        Press{Key{static_cast<int>(i), static_cast<double>(layerRand(gen))},\n              layerRand(gen)};\n    presses.push_back(press);\n    pressmap.emplace(press, i);\n  }\n  auto trand = Utility::Benchmark([&]() { cnt += rand(gen); }, 100000);\n  auto tvec =\n      Utility::Benchmark([&]() { cnt += syms[rand(gen)]; }, 10000) - trand;\n  auto tmap =\n      Utility::Benchmark([&]() { cnt += symmap[rand(gen)]; }, 10000) - trand;\n\n  auto tpvec =\n      Utility::Benchmark([&]() { cnt += presses[rand(gen)].key.row; }, 10000) -\n      trand;\n  auto tpmap = Utility::Benchmark(\n                   [&]() {\n                     auto &&press = presses[rand(gen)];\n                     cnt += pressmap[press];\n                   },\n                   10000) -\n               trand;\n  BOOST_TEST(cnt);\n\n  std::cout << std::endl;\n  std::cout << \"Benchmark of map and vector access where key is Sym:\"\n            << std::endl;\n  std::cout << \"With \" << syms.size() << \" Syms \" << std::endl;\n  std::cout << \"Vector \" << tvec.count() << \" nanoseconds\" << std::endl;\n  std::cout << \"Map    \" << tmap.count() << \" nanoseconds\" << std::endl;\n  std::cout << std::endl;\n  std::cout << \"Benchmark of map and vector access where key is Press:\"\n            << std::endl;\n  std::cout << \"With \" << presses.size() << \" Presses \" << std::endl;\n  std::cout << \"Vector \" << tpvec.count() << \" nanoseconds\" << std::endl;\n  std::cout << \"Map    \" << tpmap.count() << \" nanoseconds\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(exprtk_example) {\n  using SymbolTable = exprtk::symbol_table<Effort>;\n  using Expression = exprtk::expression<Effort>;\n  using Parser = exprtk::parser<Effort>;\n  auto expr = std::string(\"sin(x)^8+cos(y)\");\n  auto x = 1.0;\n  auto y = 2.0;\n\n  auto symbolTable = SymbolTable{};\n  auto expression = Expression{};\n  symbolTable.add_constants();\n  symbolTable.add_variable(\"x\", x);\n  symbolTable.add_variable(\"y\", y);\n  expression.register_symbol_table(symbolTable);\n  auto parser = Parser{};\n\n  auto cnt = 0.0;\n  auto n = size_t{0};\n  auto compileTime = Utility::Benchmark(\n      [&]() {\n        parser.compile(expr + std::to_string(n++), expression);\n        cnt += expression.value();\n      },\n      5);\n\n  std::cout << std::endl;\n  std::cout << \"ExprTk compile time benchmark\" << std::endl;\n  std::cout << \"Time: \" << compileTime.count() << \" nanoseconds\" << std::endl;\n}\n", "meta": {"hexsha": "6ace34a554d214363e729e5462958e6c3840d2ab", "size": 24868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "keyboard_optimizer_test/test.cpp", "max_stars_repo_name": "RudenkoRNK/keyboard_optimizer", "max_stars_repo_head_hexsha": "016d228a448001493e2b27ca8ad342d9e2ff0e21", "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": "keyboard_optimizer_test/test.cpp", "max_issues_repo_name": "RudenkoRNK/keyboard_optimizer", "max_issues_repo_head_hexsha": "016d228a448001493e2b27ca8ad342d9e2ff0e21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "keyboard_optimizer_test/test.cpp", "max_forks_repo_name": "RudenkoRNK/keyboard_optimizer", "max_forks_repo_head_hexsha": "016d228a448001493e2b27ca8ad342d9e2ff0e21", "max_forks_repo_licenses": ["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.3765432099, "max_line_length": 80, "alphanum_fraction": 0.6088949654, "num_tokens": 6653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496064}}
{"text": "// Copyright \u00a9 2017-2019 Trust.\n//\n// This file is part of Trust. The full Trust copyright notice, including\n// terms governing use, modification, and redistribution, is contained in the\n// file LICENSE at the root of the source code distribution tree.\n\n#include <TrustWalletCore/TWUInt256.h>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint256_t;\nusing boost::multiprecision::cpp_int;\n\nstruct TWUInt256 TWUInt256Zero() {\n    return TWUInt256{0};\n}\n\nstruct TWUInt256 TWUInt256One(void) {\n    TWUInt256 result{0};\n\n    uint256_t i = 1;\n    export_bits(i, std::make_reverse_iterator(result.bytes + 32), 8, false);\n\n    return result;\n}\n\nbool TWUInt256InitWithData(struct TWUInt256 *_Nonnull instance, TWData *_Nonnull data) {\n    const auto size = TWDataSize(data);\n    if (size < 32) {\n        memset(instance->bytes, 0, 32);\n        TWDataCopyBytes(data, 0, TWDataSize(data), instance->bytes + 32 - TWDataSize(data));\n    } else if (size == 32) {\n        TWDataCopyBytes(data, 0, 32, instance->bytes);\n    } else {\n        return false;\n    }\n    return true;\n}\n\nbool TWUInt256InitWithString(struct TWUInt256 *_Nonnull instance, TWString *_Nonnull string) {\n    try {\n        uint256_t i(TWStringUTF8Bytes(string));\n        export_bits(i, std::make_reverse_iterator(instance->bytes + 32), 8, false);\n    } catch (std::runtime_error e) {\n        return false;\n    }\n    return true;\n}\n\nvoid TWUInt256InitWithUInt32(struct TWUInt256 *_Nonnull instance, uint32_t value) {\n    uint256_t i = value;\n    std::fill(instance->bytes, instance->bytes + 32, 0);\n    export_bits(i, std::make_reverse_iterator(instance->bytes + 32), 8, false);\n}\n\nvoid TWUInt256InitWithUInt64(struct TWUInt256 *_Nonnull instance, uint64_t value) {\n    uint256_t i = value;\n    std::fill(instance->bytes, instance->bytes + 32, 0);\n    export_bits(i, std::make_reverse_iterator(instance->bytes + 32), 8, false);\n}\n\nbool TWUInt256IsZero(struct TWUInt256 value){\n    uint256_t i;\n    import_bits(i, value.bytes, value.bytes + 32);\n    return i == 0;\n}\n\nuint32_t TWUInt256UInt32Value(struct TWUInt256 value) {\n    uint256_t i;\n    import_bits(i, value.bytes, value.bytes + 32);\n    return static_cast<uint32_t>(i);\n}\n\nuint64_t TWUInt256UInt64Value(struct TWUInt256 value) {\n    uint256_t i;\n    import_bits(i, value.bytes, value.bytes + 32);\n    return static_cast<uint32_t>(i);\n}\n\nTWData *_Nonnull TWUInt256Data(struct TWUInt256 value) {\n    return TWDataCreateWithBytes(value.bytes, 32);\n}\n\nTWString *_Nonnull TWUInt256Description(struct TWUInt256 value) {\n    uint256_t i;\n    import_bits(i, value.bytes, value.bytes + 32);\n    auto string = boost::lexical_cast<std::string>(i);\n    return TWStringCreateWithUTF8Bytes(string.c_str());\n}\n\nbool TWUInt256Equal(struct TWUInt256 lhs, struct TWUInt256 rhs) {\n    uint256_t i;\n    uint256_t j;\n    import_bits(i, lhs.bytes, lhs.bytes + 32);\n    import_bits(j, rhs.bytes, rhs.bytes + 32);\n    return i == j;\n}\n\nbool TWUInt256Less(struct TWUInt256 lhs, struct TWUInt256 rhs) {\n    uint256_t i;\n    uint256_t j;\n    import_bits(i, lhs.bytes, lhs.bytes + 32);\n    import_bits(j, rhs.bytes, rhs.bytes + 32);\n    return i < j;\n}\n\ninline void formatPush(int n, std::string& s, int& decimals) {\n    if (n > 0 || decimals <= 1) {\n        s.push_back('0' + n);\n    }\n    if (decimals > 0 && decimals-- == 1) {\n        s.push_back('.');\n    }\n}\n\nTWString *_Nonnull TWUInt256Format(struct TWUInt256 value, int decimals) {\n    uint256_t i;\n    import_bits(i, value.bytes, value.bytes + 32);\n    auto string = boost::lexical_cast<std::string>(i);\n    if (decimals == 0) {\n        return TWStringCreateWithUTF8Bytes(string.c_str());\n    }\n\n    if (string.size() <= decimals) {\n        auto prefix = std::string(\"0.\");\n        auto padding = std::string(decimals - string.size(), '0');\n        string.insert(string.begin(), padding.begin(), padding.end());\n        string.insert(string.begin(), prefix.begin(), prefix.end());\n    } else {\n        string.insert(string.end() - decimals, '.');\n    }\n\n    auto zerosBegin = std::find_if(string.rbegin(), string.rbegin() + decimals - 1, [](auto& c){ return c != '0' && c != '.'; }).base();\n    string.erase(zerosBegin, string.end());\n\n    return TWStringCreateWithUTF8Bytes(string.c_str());\n}\n", "meta": {"hexsha": "979c6727ad44a3627e33c5b6f097bf1711e13f9e", "size": 4300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interface/TWUInt256.cpp", "max_stars_repo_name": "johnnynanjiang/trust-wallet-core", "max_stars_repo_head_hexsha": "e4af642084b856e206adfc8c681fe3605bde91d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T15:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T22:08:32.000Z", "max_issues_repo_path": "src/interface/TWUInt256.cpp", "max_issues_repo_name": "oregonisaac/wallet-core", "max_issues_repo_head_hexsha": "26db31f716e0ba48306a010d075e4545142ea6f3", "max_issues_repo_licenses": ["MIT"], "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/interface/TWUInt256.cpp", "max_forks_repo_name": "oregonisaac/wallet-core", "max_forks_repo_head_hexsha": "26db31f716e0ba48306a010d075e4545142ea6f3", "max_forks_repo_licenses": ["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.9352517986, "max_line_length": 136, "alphanum_fraction": 0.6706976744, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "// Copyright Daniel Wallin 2006. Use, modification and distribution is\n// subject to 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_TIME_SERIES_NUMERIC_FINE_GRAIN_060614_HPP\n# define BOOST_TIME_SERIES_NUMERIC_FINE_GRAIN_060614_HPP\n\n#include <boost/concept/requires.hpp>\n#include <boost/detail/pod_singleton.hpp>\n#include <boost/range_run_storage/algorithm/for_each.hpp>\n#include <boost/time_series/concepts.hpp>\n#include <boost/time_series/sparse_series.hpp>\n#include <boost/time_series/piecewise_constant_series.hpp>\n#include <boost/time_series/ordered_inserter.hpp>\n\nnamespace boost { namespace time_series\n{\n\n    namespace samplers\n    {\n\n        template <typename Derived>\n        struct sampler_base\n        {\n            Derived const &cast() const\n            {\n                return static_cast<Derived const&>(*this);\n            }\n        };\n\n        /// A fine_grain upsampler that makes a piecewise constant function\n        /// with jumps at the coarse-grained points.\n        ///\n        struct piecewise_upsample\n          : sampler_base<piecewise_upsample>\n        {\n            template <typename ValueType, typename Discretization>\n            struct apply\n            {\n                typedef piecewise_constant_series<ValueType, Discretization> type;\n            };\n\n            template <typename Value, typename Offset, typename Out>\n            void operator()(Out &out, Value value, Offset offset, Offset endoff, Offset factor) const\n            {\n                out(value, offset * factor, endoff * factor);\n            }\n        };\n\n        /// A fine_grain upsampler that sets non-zero values at the coarse-grained\n        /// points.\n        ///\n        struct sparse_upsample\n          : sampler_base<sparse_upsample>\n        {\n            template <typename ValueType, typename Discretization>\n            struct apply\n            {\n                typedef sparse_series<ValueType, Discretization> type;\n            };\n\n            template <typename Value, typename Offset, typename Out>\n            void operator()(Out &out, Value value, Offset offset, Offset endoff, Offset factor) const\n            {\n                std::size_t length = endoff - offset;\n                offset *= factor;\n\n                while(length-- > 0)\n                {\n                    out(value, offset);\n                    offset += factor;\n                }\n            }\n        };\n\n        /// INTERNAL ONLY\n        template<typename UpSampler, typename Out, typename Offset>\n        struct upsampler_functor\n        {\n            upsampler_functor(UpSampler upsampler, Out &out, Offset factor)\n              : upsampler_(upsampler)\n              , out_(out)\n              , factor_(factor)\n            {}\n\n            template<typename Value>\n            void operator ()(Value const &value, Offset start, Offset stop) const\n            {\n                this->upsampler_(this->out_, value, start, stop, this->factor_);\n            }\n        private:\n            UpSampler upsampler_;\n            Out &out_;\n            Offset factor_;\n        };\n\n    } // namespace samplers\n\n    namespace \n    {\n        samplers::piecewise_upsample const &piecewise_upsample\n            = boost::detail::pod_singleton<samplers::piecewise_upsample>::instance;\n\n        samplers::sparse_upsample const &sparse_upsample\n            = boost::detail::pod_singleton<samplers::sparse_upsample>::instance;\n    }\n\n    /// \\brief Generate a series of finer discretization from a series of coarser\n    /// discretization according to a sampling policy.\n    ///\n    /// Generate a series of finer discretization from a series of coarser\n    /// discretization according to a sampling policy.\n    ///\n    /// \\param series The input series.\n    /// \\param discretization The finer discretization.\n    /// \\param upsampler The sampling policy. Could be \\c piecewise_upsample or \\c sparse_upsample.\n    /// \\param out An \\c OrderedInserter into which to write the finer series.\n    /// \\return If you specify an \\c OrderedInserter, the return value is a copy of the\n    ///     \\c OrderedInserter. Otherwise, if you specify the \\c sparse_upsample, the return\n    ///     value is a <tt>sparse_series\\<\\></tt> containing the finer-grained series. Otherwise,\n    ///     if you specify the \\c piecewise_upsample, the return value is a\n    ///     <tt>piecewise_constant_series\\<\\></tt> containing the finer-grained series.\n    /// \\attention If using the version that takes an \\c OrderedInserter, you must call\n    ///     <tt>.commit()</tt> on the returned \\c OrderedInserter when you are done with it.\n    /// \\pre The coarser discretization is a multiple of the finer discretization.\n    template<typename Series, typename Discretization, typename UpSampler, typename Out>\n    BOOST_CONCEPT_REQUIRES(\n        ((concepts::TimeSeries<Series const>)),\n    (ordered_inserter<Out>))\n    fine_grain(\n        Series const &series\n      , Discretization discretization\n      , samplers::sampler_base<UpSampler> const &upsampler\n      , ordered_inserter<Out> out\n    )\n    {\n        typedef typename concepts::TimeSeries<Series const>::offset_type offset_type;\n\n        BOOST_ASSERT(series.discretization() > discretization);\n        BOOST_ASSERT(series.discretization() % discretization == 0);\n\n        offset_type factor = series.discretization() / discretization;\n        samplers::upsampler_functor<UpSampler, ordered_inserter<Out>, offset_type>\n            fun(upsampler.cast(), out, factor);\n\n        range_run_storage::for_each(series, fun);\n        return out;\n    }\n\n    /// \\overload\n    ///\n    template <typename Series, typename Discretization, typename Out>\n    BOOST_CONCEPT_REQUIRES(\n        ((concepts::TimeSeries<Series const>)),\n    (ordered_inserter<Out>))\n    fine_grain(\n        Series const &series\n      , Discretization discretization\n      , ordered_inserter<Out> out\n    )\n    {\n        return time_series::fine_grain(\n            series\n          , discretization\n          , piecewise_upsample\n          , out\n        );\n    }\n\n    /// \\overload\n    ///\n    template<typename Series, typename Discretization, typename UpSampler>\n    BOOST_CONCEPT_REQUIRES(\n        ((concepts::TimeSeries<Series const>)),\n    (typename mpl::apply_wrap2<\n        UpSampler\n      , typename concepts::TimeSeries<Series const>::value_type\n      , Discretization\n    >::type))\n    fine_grain(\n        Series const &series\n      , Discretization discretization\n      , samplers::sampler_base<UpSampler> const &upsampler\n    )\n    {\n        typedef typename concepts::TimeSeries<Series const>::value_type value_type;\n\n        BOOST_ASSERT(series.discretization() > discretization);\n        BOOST_ASSERT(series.discretization() % discretization == 0);\n\n        typedef typename mpl::apply_wrap2<\n            UpSampler\n          , value_type\n          , Discretization\n        >::type result_type;\n\n        result_type result(time_series::discretization = discretization);\n\n        time_series::fine_grain(\n            series\n          , discretization\n          , upsampler.cast()\n          , time_series::make_ordered_inserter(result)\n        ).commit();\n\n        return result;\n    }\n\n    /// \\overload\n    ///\n    template <typename Series, typename Discretization>\n    BOOST_CONCEPT_REQUIRES(\n        ((concepts::TimeSeries<Series const>)),\n    (typename mpl::apply_wrap2<\n        samplers::piecewise_upsample\n      , typename concepts::TimeSeries<Series const>::value_type\n      , Discretization\n    >::type))\n    fine_grain(Series const &series, Discretization discretization)\n    {\n        return time_series::fine_grain(\n            series\n          , discretization\n          , piecewise_upsample\n        );\n    }\n\n}} // namespace boost::time_series\n\n#endif // BOOST_TIME_SERIES_NUMERIC_FINE_GRAIN_060614_HPP\n", "meta": {"hexsha": "6189941560e3e4a32f1abbaa96f70a89d953c15f", "size": 7909, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/time_series/numeric/fine_grain.hpp", "max_stars_repo_name": "ericniebler/time_series", "max_stars_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T11:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T03:39:29.000Z", "max_issues_repo_path": "boost/time_series/numeric/fine_grain.hpp", "max_issues_repo_name": "ericniebler/time_series", "max_issues_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "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/time_series/numeric/fine_grain.hpp", "max_forks_repo_name": "ericniebler/time_series", "max_forks_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-05-09T02:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-02T13:39:29.000Z", "avg_line_length": 34.2380952381, "max_line_length": 101, "alphanum_fraction": 0.6297888481, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19656440062496056}}
{"text": "\n//          Copyright Oliver Kowalke 2009.\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 <cstdlib>\n#include <stdexcept>\n\n#include <boost/bind.hpp>\n\n#include \"boost/task.hpp\"\n\nnamespace tsk = boost::tasks;\n\ninline\nint fibonacci_fn( int n)\n{\n\tif ( n == 0) return 0;\n\tif ( n == 1) return 1;\n\tint k1( 1), k2( 0);\n\tfor ( int i( 2); i <= n; ++i)\n\t{\n\t\tboost::this_thread::interruption_point();\n\t\tint tmp( k1);\n\t\tk1 = k1 + k2;\n\t\tk2 = tmp;\n\t}\n\tboost::this_thread::interruption_point();\n\treturn k1;\n}\n\nint main( int argc, char *argv[])\n{\n\ttry\n\t{\n\t\ttsk::static_pool< tsk::unbounded_prio_queue< int > > pool( tsk::poolsize( 3) ); \n\n\t\ttsk::task< int > t1( fibonacci_fn, 10);\n\t\ttsk::task< int > t2( fibonacci_fn, 10);\n\t\ttsk::task< int > t3( fibonacci_fn, 10);\n\t\ttsk::task< int > t4( fibonacci_fn, 10);\n\n\t\ttsk::handle< int > h1(\n\t\t\ttsk::async( boost::move( t1) ) );\n\t\ttsk::handle< int > h2(\n\t\t\ttsk::async(\n\t\t\t\tboost::move( t2),\n\t\t\t\ttsk::new_thread() ) );\n\t\ttsk::handle< int > h3(\n\t\t\ttsk::async(\n\t\t\t\tboost::move( t3),\n\t\t\t\t2,\n\t\t\t\tpool) );\n\t\ttsk::handle< int > h4(\n\t\t\ttsk::async(\n\t\t\t\tboost::move( t4),\n\t\t\t\t2,\n\t\t\t\tpool) );\n\n\t\tstd::cout << h1.get() << std::endl;\n\t\tstd::cout << h2.get() << std::endl;\n\t\tstd::cout << h3.get() << std::endl;\n\t\tstd::cout << h4.get() << std::endl;\n\n\t\treturn EXIT_SUCCESS;\n\t}\n\tcatch ( std::exception const& e)\n\t{ std::cerr << \"exception: \" << e.what() << std::endl; }\n\tcatch ( ... )\n\t{ std::cerr << \"unhandled\" << std::endl; }\n\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "989b924a58a6b7db38f017422f06fd1825408b8c", "size": 1613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/boost.task/libs/task/examples/submit.cpp", "max_stars_repo_name": "ghisguth/tasks", "max_stars_repo_head_hexsha": "ce04926dbee2ab1204ed34e50dbce53f0303bde1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-18T02:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-18T02:34:18.000Z", "max_issues_repo_path": "libs/boost.task/libs/task/examples/submit.cpp", "max_issues_repo_name": "ghisguth/tasks", "max_issues_repo_head_hexsha": "ce04926dbee2ab1204ed34e50dbce53f0303bde1", "max_issues_repo_licenses": ["MIT"], "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.task/libs/task/examples/submit.cpp", "max_forks_repo_name": "ghisguth/tasks", "max_forks_repo_head_hexsha": "ce04926dbee2ab1204ed34e50dbce53f0303bde1", "max_forks_repo_licenses": ["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.2236842105, "max_line_length": 82, "alphanum_fraction": 0.5840049597, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1964780961168555}}
{"text": "#include <boost/test/unit_test.hpp>\r\n\r\n#include \"moja/datarepository/tileblockcellindexer.h\"\r\n#include \"moja/datarepository/datarepositoryexceptions.h\"\r\n#include \"moja/datarepository/providerspatialrastertiled.h\"\r\n#include \"moja/dynamicstruct.h\"\r\n\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <vector>\r\n\r\nusing moja::datarepository::ProviderSpatialRasterTiled;\r\nusing moja::datarepository::FileNotFoundException;\r\nusing moja::datarepository::QueryException;\r\nusing namespace moja::datarepository;\r\n\r\nstruct ProviderSpatialRasterTiledTestsFixture {\r\n\tmoja::DynamicObject settings;\r\n\r\n\tProviderSpatialRasterTiledTestsFixture() {\r\n\t}\r\n\r\n\t~ProviderSpatialRasterTiledTestsFixture() {\r\n\t}\r\n};\r\n\r\n\r\nBOOST_FIXTURE_TEST_SUITE(TileBlockCellIteratorTests, ProviderSpatialRasterTiledTestsFixture);\r\n\r\nBOOST_AUTO_TEST_CASE(DataRepository_Sanity_On_Creation) {\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(DataRepository_New_Iterator) {\r\n\tProviderSpatialRasterTiled provider(settings);\r\n\r\n\tTileBlockCellIndexer indexer = { 1.0, 1.0, 0.1, 0.1, 0.00025, 0.00025 };\t// 1.0 Degree Tiles\r\n\tmoja::datarepository::Rectangle areaOfInterest{ Point{ 0.5, 34.5 }, { 1.0, 1.0 } };\r\n\tstd::vector<std::vector<int>> tileBlockCellCount;\r\n\ttileBlockCellCount.resize(indexer.tileDesc.indexLimit);\r\n\tfor (auto& tile : tileBlockCellCount)\r\n\t{\r\n\t\ttile.resize(indexer.blockDesc.indexLimit);\r\n\t\tfor (auto& blockCount : tile) {\r\n\t\t\tblockCount = 0;\r\n\t\t}\r\n\t}\r\n\r\n\t//std::cout << \"Tile\\tblock\\tcell\\t\" << std::endl;\r\n\tfor (auto& cell : provider.cells(areaOfInterest))\r\n\t{\r\n\t\tauto& count = tileBlockCellCount[cell.tileIdx][cell.blockIdx];\r\n\t\tcount++;\r\n\t\t////if (cell.cellIdx % 160000 == 0)\r\n\t\t//\tstd::cout << cell.tileIdx << \"\\t\" << cell.blockIdx << \"\\t\" << cell.cellIdx << std::endl;\r\n\t}\r\n\r\n\tstd::cout << \"Tile\\tblock\\tcell count\\t\" << std::endl;\r\n\tint tileIdx = 0;\r\n\tfor (auto& tile : tileBlockCellCount)\r\n\t{\r\n\t\tint blockIdx = 0;\r\n\t\tfor (auto& blockCount : tile) {\r\n\t\t\tif (blockCount > 0)\r\n\t\t\t\tstd::cout << tileIdx << \"\\t\" << blockIdx << \"\\t\" << blockCount << std::endl;\r\n\t\t\tblockIdx++;\r\n\t\t}\r\n\t\ttileIdx++;\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "33253434f57772aaa4f4b2fe3d56a9dafaf837fd", "size": 2093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/moja.datarepository/tests/src/tileblockcelliteratortests.cpp", "max_stars_repo_name": "moja-global/flint", "max_stars_repo_head_hexsha": "2c65c5808d908247ce8ee4d9f87f11c7dd57794e", "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": "Source/moja.datarepository/tests/src/tileblockcelliteratortests.cpp", "max_issues_repo_name": "moja-global/flint", "max_issues_repo_head_hexsha": "2c65c5808d908247ce8ee4d9f87f11c7dd57794e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T11:30:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-18T14:50:16.000Z", "max_forks_repo_path": "Source/moja.datarepository/tests/src/tileblockcelliteratortests.cpp", "max_forks_repo_name": "moja-global/flint", "max_forks_repo_head_hexsha": "2c65c5808d908247ce8ee4d9f87f11c7dd57794e", "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.0694444444, "max_line_length": 94, "alphanum_fraction": 0.7047300526, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1964780961168555}}
{"text": "/*\n * This module contains the implementation of several\n * kind of integrals used for non-adiabatic molecular dynamics,\n * including the overlaps integrals between different geometries\n * And the dipoles and quadrupoles to compute absorption spectra.\n * This module is based on libint, Eigen and pybind11.\n * Copyright (C) 2018-2020 the Netherlands eScience Center.\n */\n\n#ifndef NAMD_H_\n#define NAMD_H_\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <thread>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n// integrals library\n#include <libint2.hpp>\n\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n\n// Eigen matrix algebra library\n#include <Eigen/Dense>\n\n// HDF5 funcionality\n#include <highfive/H5DataSet.hpp>\n#include <highfive/H5DataSpace.hpp>\n#include <highfive/H5File.hpp>\n\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\nnamespace namd {\n\nusing real_t = libint2::scalar_type;\n// import dense, dynamically sized Matrix type from Eigen;\n// this is a matrix with row-major storage\n// (http://en.wikipedia.org/wiki/Row-major_order) to meet the layout of the\n// integrals returned by the Libint integral library\nusing Matrix =\n    Eigen::Matrix<real_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nstruct CP2K_Basis_Atom {\n  // Contains the basis specificationf for a given atom\n  std::string symbol;\n  libint2::svector<libint2::svector<double>> coefficients;\n  libint2::svector<double> exponents;\n  libint2::svector<int> basis_format;\n};\n\n// Map from atomic_number to symbol\nstd::unordered_map<int, std::string> map_elements = {\n    {1, \"h\"},   {2, \"he\"},  {3, \"li\"},  {4, \"be\"},  {5, \"b\"},   {6, \"c\"},\n    {7, \"n\"},   {8, \"o\"},   {9, \"f\"},   {10, \"ne\"}, {11, \"na\"}, {12, \"mg\"},\n    {13, \"al\"}, {14, \"si\"}, {15, \"p\"},  {16, \"s\"},  {17, \"cl\"}, {18, \"ar\"},\n    {19, \"k\"},  {20, \"ca\"}, {21, \"sc\"}, {22, \"ti\"}, {23, \"v\"},  {24, \"cr\"},\n    {25, \"mn\"}, {26, \"fe\"}, {27, \"co\"}, {28, \"ni\"}, {29, \"cu\"}, {30, \"zn\"},\n    {31, \"ga\"}, {32, \"ge\"}, {33, \"as\"}, {34, \"se\"}, {35, \"br\"}, {36, \"kr\"},\n    {37, \"rb\"}, {38, \"sr\"}, {39, \"y\"},  {40, \"zr\"}, {41, \"nb\"}, {42, \"mo\"},\n    {43, \"tc\"}, {44, \"ru\"}, {45, \"rh\"}, {46, \"pd\"}, {47, \"ag\"}, {48, \"cd\"},\n    {49, \"in\"}, {50, \"sn\"}, {51, \"sb\"}, {52, \"te\"}, {53, \"i\"},  {54, \"xe\"},\n    {55, \"cs\"}, {56, \"ba\"}, {57, \"la\"}, {58, \"ce\"}, {59, \"pr\"}, {60, \"nd\"},\n    {61, \"pm\"}, {62, \"sm\"}, {63, \"eu\"}, {64, \"gd\"}, {65, \"tb\"}, {66, \"dy\"},\n    {67, \"ho\"}, {68, \"er\"}, {69, \"tm\"}, {70, \"yb\"}, {71, \"lu\"}, {72, \"hf\"},\n    {73, \"ta\"}, {74, \"w\"},  {75, \"re\"}, {76, \"os\"}, {77, \"ir\"}, {78, \"pt\"},\n    {79, \"au\"}, {80, \"hg\"}, {81, \"tl\"}, {82, \"pb\"}, {83, \"bi\"}, {84, \"po\"},\n    {85, \"at\"}, {86, \"rn\"}, {87, \"fr\"}, {88, \"ra\"}, {89, \"ac\"}, {90, \"th\"},\n    {91, \"pa\"}, {92, \"u\"},  {93, \"np\"}, {94, \"pu\"}, {95, \"am\"}, {96, \"cm\"}};\n\n} // namespace namd\n#endif // NAMD_H_\n", "meta": {"hexsha": "58659a8fdca3c591e9b1acf4861f301309f8d506", "size": 2881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libint/include/namd.hpp", "max_stars_repo_name": "SCM-NV/nano-qmflows", "max_stars_repo_head_hexsha": "106bb48f5de9a5f89e57b9d165af8202bcfb84eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T08:01:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T16:27:41.000Z", "max_issues_repo_path": "libint/include/namd.hpp", "max_issues_repo_name": "SCM-NV/nano-qmflows", "max_issues_repo_head_hexsha": "106bb48f5de9a5f89e57b9d165af8202bcfb84eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 96.0, "max_issues_repo_issues_event_min_datetime": "2020-04-01T13:05:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T18:34:42.000Z", "max_forks_repo_path": "libint/include/namd.hpp", "max_forks_repo_name": "SCM-NV/nano-qmflows", "max_forks_repo_head_hexsha": "106bb48f5de9a5f89e57b9d165af8202bcfb84eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-08T11:08:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T02:05:13.000Z", "avg_line_length": 36.0125, "max_line_length": 76, "alphanum_fraction": 0.562651857, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.1964780939225172}}
{"text": "\n\n#include <ripple/basics/strHex.h>\n#include <ripple/crypto/KeyType.h>\n#include <ripple/net/RPCErr.h>\n#include <ripple/protocol/ErrorCodes.h>\n#include <ripple/protocol/jss.h>\n#include <ripple/protocol/PublicKey.h>\n#include <ripple/protocol/SecretKey.h>\n#include <ripple/protocol/Seed.h>\n#include <ripple/rpc/Context.h>\n#include <ripple/rpc/impl/RPCHelpers.h>\n#include <ripple/rpc/handlers/WalletPropose.h>\n#include <ed25519-donna/ed25519.h>\n#include <boost/optional.hpp>\n#include <cmath>\n#include <map>\n\nnamespace ripple {\n\ndouble\nestimate_entropy (std::string const& input)\n{\n    std::map<int, double> freq;\n\n    for (auto const& c : input)\n        freq[c]++;\n\n    double se = 0.0;\n\n    for (auto const& f : freq)\n    {\n        auto x = f.second / input.length();\n        se += (x) * log2(x);\n    }\n\n    return std::floor (-se * input.length());\n}\n\nJson::Value doWalletPropose (RPC::Context& context)\n{\n    return walletPropose (context.params);\n}\n\nJson::Value walletPropose (Json::Value const& params)\n{\n    boost::optional<KeyType> keyType;\n    boost::optional<Seed> seed;\n    bool rippleLibSeed = false;\n\n    if (params.isMember (jss::key_type))\n    {\n        if (! params[jss::key_type].isString())\n        {\n            return RPC::expected_field_error (\n                jss::key_type, \"string\");\n        }\n\n        keyType = keyTypeFromString (\n            params[jss::key_type].asString());\n\n        if (!keyType)\n            return rpcError(rpcINVALID_PARAMS);\n    }\n\n    {\n        if (params.isMember(jss::passphrase))\n            seed = RPC::parseRippleLibSeed(params[jss::passphrase]);\n        else if (params.isMember(jss::seed))\n            seed = RPC::parseRippleLibSeed(params[jss::seed]);\n\n        if(seed)\n        {\n            rippleLibSeed = true;\n\n            if (keyType.value_or(KeyType::ed25519) != KeyType::ed25519)\n                return rpcError(rpcBAD_SEED);\n\n            keyType = KeyType::ed25519;\n        }\n    }\n\n    if (!seed)\n    {\n        if (params.isMember(jss::passphrase) ||\n            params.isMember(jss::seed) ||\n            params.isMember(jss::seed_hex))\n        {\n            Json::Value err;\n\n            seed = RPC::getSeedFromRPC(params, err);\n\n            if (!seed)\n                return err;\n        }\n        else\n        {\n            seed = randomSeed();\n        }\n    }\n\n    if (!keyType)\n        keyType = KeyType::secp256k1;\n\n    auto const publicKey = generateKeyPair (*keyType, *seed).first;\n\n    Json::Value obj (Json::objectValue);\n\n    auto const seed1751 = seedAs1751 (*seed);\n    auto const seedHex = strHex (*seed);\n    auto const seedBase58 = toBase58 (*seed);\n\n    obj[jss::master_seed] = seedBase58;\n    obj[jss::master_seed_hex] = seedHex;\n    obj[jss::master_key] = seed1751;\n    obj[jss::account_id] = toBase58(calcAccountID(publicKey));\n    obj[jss::public_key] = toBase58(TokenType::AccountPublic, publicKey);\n    obj[jss::key_type] = to_string (*keyType);\n    obj[jss::public_key_hex] = strHex (publicKey);\n\n    if (!rippleLibSeed && params.isMember (jss::passphrase))\n    {\n        auto const passphrase = params[jss::passphrase].asString();\n\n        if (passphrase != seed1751 &&\n            passphrase != seedBase58 &&\n            passphrase != seedHex)\n        {\n            if (estimate_entropy (passphrase) < 80.0)\n                obj[jss::warning] =\n                    \"This wallet was generated using a user-supplied \"\n                    \"passphrase that has low entropy and is vulnerable \"\n                    \"to brute-force attacks.\";\n            else\n                obj[jss::warning] =\n                    \"This wallet was generated using a user-supplied \"\n                    \"passphrase. It may be vulnerable to brute-force \"\n                    \"attacks.\";\n        }\n    }\n\n    return obj;\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": "36d447dd3262aa1a74078c135306a7b5f1bb904a", "size": 3814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ripple/rpc/handlers/WalletPropose.cpp", "max_stars_repo_name": "DEEPSPACE007/DsDeFi-Exchange", "max_stars_repo_head_hexsha": "777486b799bae42a4297f9524f3ff30e0b149ef7", "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/ripple/rpc/handlers/WalletPropose.cpp", "max_issues_repo_name": "DEEPSPACE007/DsDeFi-Exchange", "max_issues_repo_head_hexsha": "777486b799bae42a4297f9524f3ff30e0b149ef7", "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/ripple/rpc/handlers/WalletPropose.cpp", "max_forks_repo_name": "DEEPSPACE007/DsDeFi-Exchange", "max_forks_repo_head_hexsha": "777486b799bae42a4297f9524f3ff30e0b149ef7", "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.4352941176, "max_line_length": 73, "alphanum_fraction": 0.5752490823, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.1964780848631193}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2007 Joel de Guzman\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 PHOENIX_OPERATOR_ARITHMETIC_HPP\n#define PHOENIX_OPERATOR_ARITHMETIC_HPP\n\n#include <boost/spirit/home/phoenix/core/composite.hpp>\n#include <boost/spirit/home/phoenix/core/compose.hpp>\n#include <boost/spirit/home/phoenix/detail/type_deduction.hpp>\n#include <boost/spirit/home/phoenix/operator/detail/unary_eval.hpp>\n#include <boost/spirit/home/phoenix/operator/detail/unary_compose.hpp>\n#include <boost/spirit/home/phoenix/operator/detail/binary_eval.hpp>\n#include <boost/spirit/home/phoenix/operator/detail/binary_compose.hpp>\n\nnamespace boost { namespace phoenix\n{\n    struct negate_eval;\n    struct posit_eval;\n    struct pre_increment_eval;\n    struct pre_decrement_eval;\n    struct post_increment_eval;\n    struct post_decrement_eval;\n\n    struct plus_assign_eval;\n    struct minus_assign_eval;\n    struct multiplies_assign_eval;\n    struct divides_assign_eval;\n    struct modulus_assign_eval;\n\n    struct plus_eval;\n    struct minus_eval;\n    struct multiplies_eval;\n    struct divides_eval;\n    struct modulus_eval;\n\n    BOOST_UNARY_RESULT_OF(-x, result_of_negate)\n    BOOST_UNARY_RESULT_OF(+x, result_of_posit)\n    BOOST_UNARY_RESULT_OF(++x, result_of_pre_increment)\n    BOOST_UNARY_RESULT_OF(--x, result_of_pre_decrement)\n    BOOST_UNARY_RESULT_OF(x++, result_of_post_increment)\n    BOOST_UNARY_RESULT_OF(x--, result_of_post_decrement)\n\n    BOOST_BINARY_RESULT_OF(x += y, result_of_plus_assign)\n    BOOST_BINARY_RESULT_OF(x -= y, result_of_minus_assign)\n    BOOST_BINARY_RESULT_OF(x *= y, result_of_multiplies_assign)\n    BOOST_BINARY_RESULT_OF(x /= y, result_of_divides_assign)\n    BOOST_BINARY_RESULT_OF(x %= y, result_of_modulus_assign)\n\n    BOOST_BINARY_RESULT_OF(x + y, result_of_plus)\n    BOOST_BINARY_RESULT_OF(x - y, result_of_minus)\n    BOOST_BINARY_RESULT_OF(x * y, result_of_multiplies)\n    BOOST_BINARY_RESULT_OF(x / y, result_of_divides)\n    BOOST_BINARY_RESULT_OF(x % y, result_of_modulus)\n\n#define x a0.eval(env)\n#define y a1.eval(env)\n\n    PHOENIX_UNARY_EVAL(negate_eval, result_of_negate, -x)\n    PHOENIX_UNARY_EVAL(posit_eval, result_of_posit, +x)\n    PHOENIX_UNARY_EVAL(pre_increment_eval, result_of_pre_increment, ++x)\n    PHOENIX_UNARY_EVAL(pre_decrement_eval, result_of_pre_decrement, --x)\n    PHOENIX_UNARY_EVAL(post_increment_eval, result_of_post_increment, x++)\n    PHOENIX_UNARY_EVAL(post_decrement_eval, result_of_post_decrement, x--)\n\n    PHOENIX_BINARY_EVAL(plus_assign_eval, result_of_plus_assign, x += y)\n    PHOENIX_BINARY_EVAL(minus_assign_eval, result_of_minus_assign, x -= y)\n    PHOENIX_BINARY_EVAL(multiplies_assign_eval, result_of_multiplies_assign, x *= y)\n    PHOENIX_BINARY_EVAL(divides_assign_eval, result_of_divides_assign, x /= y)\n    PHOENIX_BINARY_EVAL(modulus_assign_eval, result_of_modulus_assign, x %= y)\n\n    PHOENIX_BINARY_EVAL(plus_eval, result_of_plus, x + y)\n    PHOENIX_BINARY_EVAL(minus_eval, result_of_minus, x - y)\n    PHOENIX_BINARY_EVAL(multiplies_eval, result_of_multiplies, x * y)\n    PHOENIX_BINARY_EVAL(divides_eval, result_of_divides, x / y)\n    PHOENIX_BINARY_EVAL(modulus_eval, result_of_modulus, x % y)\n\n    PHOENIX_UNARY_COMPOSE(negate_eval, -)\n    PHOENIX_UNARY_COMPOSE(posit_eval, +)\n    PHOENIX_UNARY_COMPOSE(pre_increment_eval, ++)\n    PHOENIX_UNARY_COMPOSE(pre_decrement_eval, --)\n\n    template <typename T0>\n    inline actor<typename as_composite<post_increment_eval, actor<T0> >::type>\n    operator++(actor<T0> const& a0, int) // special case\n    {\n        return compose<post_increment_eval>(a0);\n    }\n\n    template <typename T0>\n    inline actor<typename as_composite<post_decrement_eval, actor<T0> >::type>\n    operator--(actor<T0> const& a0, int) // special case\n    {\n        return compose<post_decrement_eval>(a0);\n    }\n\n    PHOENIX_BINARY_COMPOSE(plus_assign_eval, +=)\n    PHOENIX_BINARY_COMPOSE(minus_assign_eval, -=)\n    PHOENIX_BINARY_COMPOSE(multiplies_assign_eval, *=)\n    PHOENIX_BINARY_COMPOSE(divides_assign_eval, /=)\n    PHOENIX_BINARY_COMPOSE(modulus_assign_eval, %=)\n\n    PHOENIX_BINARY_COMPOSE(plus_eval, +)\n    PHOENIX_BINARY_COMPOSE(minus_eval, -)\n    PHOENIX_BINARY_COMPOSE(multiplies_eval, *)\n    PHOENIX_BINARY_COMPOSE(divides_eval, /)\n    PHOENIX_BINARY_COMPOSE(modulus_eval, %)\n\n#undef x\n#undef y\n}}\n\n#endif\n", "meta": {"hexsha": "e51b23e14a5e642f93c785d8cd5d493b17883f30", "size": 4589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/spirit/home/phoenix/operator/arithmetic.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 113.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T07:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T12:41:53.000Z", "max_issues_repo_path": "boost/boost/spirit/home/phoenix/operator/arithmetic.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 81.0, "max_issues_repo_issues_event_min_datetime": "2018-03-01T18:05:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-15T18:47:31.000Z", "max_forks_repo_path": "boost/boost/spirit/home/phoenix/operator/arithmetic.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2018-07-16T06:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-01T13:18:36.000Z", "avg_line_length": 39.5603448276, "max_line_length": 84, "alphanum_fraction": 0.7450424929, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19647808111187393}}
{"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_SIMD_SSE_SSE2_MULS_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_SSE2_MULS_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n\n#include <boost/simd/arithmetic/functions/muls.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/include/functions/simd/bitwise_xor.hpp>\n#include <boost/simd/include/functions/simd/bitwise_or.hpp>\n#include <boost/simd/include/functions/simd/shift_right.hpp>\n#include <boost/simd/include/functions/simd/is_not_equal.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/split_multiplies.hpp>\n#include <boost/simd/include/functions/simd/group.hpp>\n#include <boost/simd/include/functions/simd/genmask.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n#include <boost/simd/sdk/meta/scalar_of.hpp>\n#include <boost/dispatch/meta/upgrade.hpp>\n#include <boost/dispatch/meta/as_unsigned.hpp>\n\n/* No native groups for 64-bit SSE;\n * we use bit tricks instead of calling saturate. */\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( muls_, boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_<uint32_<A0>, boost::simd::tag::sse_>))\n                                      ((simd_<uint32_<A0>, boost::simd::tag::sse_>))\n                                    )\n  {\n\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::scalar_of<A0>::type stype;\n      typedef typename dispatch::meta::upgrade<A0>::type utype;\n\n      utype res0, res1;\n      split_multiplies(a0, a1, res0, res1);\n\n      return group(res0, res1)\n           | genmask( group( shrai(res0, sizeof(stype)*CHAR_BIT)\n                           , shrai(res1, sizeof(stype)*CHAR_BIT)\n                           )\n                    );\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( muls_, boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_<int32_<A0>, boost::simd::tag::sse_>))\n                                      ((simd_<int32_<A0>, boost::simd::tag::sse_>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::scalar_of<A0>::type stype;\n      typedef typename dispatch::meta::as_unsigned<A0>::type untype;\n      typedef typename dispatch::meta::upgrade<A0>::type utype;\n\n      utype res0, res1;\n      split_multiplies(a0, a1, res0, res1);\n\n      untype res2 = shrai(bitwise_cast<untype>(a0 ^ a1), sizeof(stype)*CHAR_BIT-1)\n                  + static_cast<typename meta::scalar_of<untype>::type>(Valmax<stype>());\n\n      A0 hi = group( shrai(res0, sizeof(stype)*CHAR_BIT)\n                   , shrai(res1, sizeof(stype)*CHAR_BIT)\n                   );\n      A0 lo = group(res0, res1);\n\n      return if_else( hi != shrai(lo, sizeof(stype)*CHAR_BIT-1)\n                    , bitwise_cast<A0>(res2)\n                    , lo\n                    );\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "f344f51ab3bc9cc193c0803e872b9cc467620c07", "size": 3657, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/sse/sse2/muls.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/sse/sse2/muls.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/sse/sse2/muls.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.75, "max_line_length": 89, "alphanum_fraction": 0.5799835931, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1964171618345254}}
{"text": "//\n// Copyright (c) 2017 CNRS\n//\n// This file is part of tsid\n// tsid is free software: you can redistribute it\n// and/or modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation, either version\n// 3 of the License, or (at your option) any later version.\n// tsid 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 GNU\n// General Lesser Public License for more details. You should have\n// received a copy of the GNU Lesser General Public License along with\n// tsid If not, see\n// <http://www.gnu.org/licenses/>.\n//\n\n#include <Eigen/Dense>\n#include <pinocchio/multibody/model.hpp>\n#include \"tsid/tasks/task-contact-force-equality.hpp\"\n\nnamespace tsid {\nnamespace tasks {\n\nusing namespace tsid::math;\nusing namespace std;\n\nTaskContactForceEquality::TaskContactForceEquality(const std::string & name, RobotWrapper & robot,\n                                                   const double dt, contacts::ContactBase & contact):\n  TaskContactForce(name, robot),\n  m_contact(&contact),\n  m_constraint(name, 6, 12),  \n  m_ref(6,6),\n  m_fext(6,6) {\n  m_forceIntegralError = Vector::Zero(6);\n  m_dt = dt;\n  m_leak_rate = 0.05;\n  m_contact_name = m_contact->name();\n}\n\nint TaskContactForceEquality::dim() const {\n  return 6;\n}\n\nconst Vector & TaskContactForceEquality::Kp() const { return m_Kp; }\nconst Vector & TaskContactForceEquality::Kd() const { return m_Kd; }\nconst Vector & TaskContactForceEquality::Ki() const { return m_Ki; }\nconst double & TaskContactForceEquality::getLeakRate() const { return m_leak_rate; }\n\nvoid TaskContactForceEquality::Kp(ConstRefVector Kp)\n{\n  assert(Kp.size()==6);\n  m_Kp = Kp;\n}\n\nvoid TaskContactForceEquality::Kd(ConstRefVector Kd)\n{\n  assert(Kd.size()==6);\n  m_Kd = Kd;\n}\n\nvoid TaskContactForceEquality::Ki(ConstRefVector Ki)\n{\n  assert(Ki.size()==6);\n  m_Ki = Ki;\n}\n\nvoid TaskContactForceEquality::setLeakRate(double leak)\n{\n  m_leak_rate = leak;\n}\n\nconst std::string& TaskContactForceEquality::getAssociatedContactName() {\n  return m_contact_name;\n}\n\nconst contacts::ContactBase& TaskContactForceEquality::getAssociatedContact() {\n  return *m_contact;\n}\n\nvoid TaskContactForceEquality::setAssociatedContact(contacts::ContactBase & contact) {\n  m_contact = &contact;\n  m_contact_name = m_contact->name();\n}\n\nvoid TaskContactForceEquality::setReference(TrajectorySample & ref) {\n  m_ref = ref;\n}\n\nconst TaskContactForceEquality::TrajectorySample & TaskContactForceEquality::getReference() const {\n  return m_ref;\n}\n\nvoid TaskContactForceEquality::setExternalForce(TrajectorySample & f_ext) {\n  m_fext = f_ext;\n}\n\nconst TaskContactForceEquality::TrajectorySample & TaskContactForceEquality::getExternalForce() const {\n  return m_fext;\n}\n\n\nconst ConstraintBase & TaskContactForceEquality::compute(const double t,\n                                                         ConstRefVector q,\n                                                         ConstRefVector v,\n                                                         Data & data,\n                                                         const std::vector<std::shared_ptr<ContactLevel> >  *contacts) {\n  bool contactFound = false;\n  if (m_contact_name != \"\") {\n    // look if the associated contact is in the list of contact\n    for(auto cl : *contacts) {\n      if (m_contact_name == cl->contact.name()) {\n        contactFound = true;\n        break;\n      }\n    }\n  } else {\n    std::cout << \"[TaskContactForceEquality] ERROR: Contact name empty\" << std::endl;\n    return m_constraint;\n  }\n  if (!contactFound) {\n    std::cout << \"[TaskContactForceEquality] ERROR: Contact name not in the list of contact in the formulation pb\" << std::endl;\n    return m_constraint;\n  }\n  return compute(t, q, v, data);\n}\n\nconst ConstraintBase & TaskContactForceEquality::compute(const double,\n                                                         ConstRefVector,\n                                                         ConstRefVector,\n                                                         Data & data) {\n\n  auto& M = m_constraint.matrix();\n  M = m_contact->getForceGeneratorMatrix(); // 6x12 for a 6d contact\n\n  Vector forceError = m_ref.getValue() - m_fext.getValue();\n  Vector f_ref = m_ref.getValue() + m_Kp.cwiseProduct(forceError) + m_Kd.cwiseProduct(m_ref.getDerivative() - m_fext.getDerivative()) \n                 + m_Ki.cwiseProduct(m_forceIntegralError);\n  m_constraint.vector() = f_ref;\n\n  m_forceIntegralError += (forceError - m_leak_rate * m_forceIntegralError) * m_dt;\n\n  return m_constraint;\n}\n\nconst ConstraintBase & TaskContactForceEquality::getConstraint() const {\n  return m_constraint;\n}\n\n}\n}\n", "meta": {"hexsha": "67a2f6ff787811ef3a1c0a9f4202eec8bf91dddc", "size": 4768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tasks/task-contact-force-equality.cpp", "max_stars_repo_name": "hucebot/tsid", "max_stars_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 74.0, "max_stars_repo_stars_event_min_datetime": "2017-10-19T08:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T16:31:17.000Z", "max_issues_repo_path": "src/tasks/task-contact-force-equality.cpp", "max_issues_repo_name": "hucebot/tsid", "max_issues_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 123.0, "max_issues_repo_issues_event_min_datetime": "2017-06-16T14:10:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:04:32.000Z", "max_forks_repo_path": "src/tasks/task-contact-force-equality.cpp", "max_forks_repo_name": "hucebot/tsid", "max_forks_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2017-11-24T15:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T11:10:34.000Z", "avg_line_length": 31.3684210526, "max_line_length": 134, "alphanum_fraction": 0.663590604, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.19641715431088594}}
{"text": "//\n// Created by Hamza El-Kebir on 2/20/22.\n//\n\n#ifndef LSEXAMPLE_PANDAARMBLOCK_HPP\n#define LSEXAMPLE_PANDAARMBLOCK_HPP\n\n\n#include <Lodestar/blocks/Block.hpp>\n#include <Eigen/Dense>\n#include <string>\n#include <array>\n\n#include \"arm/Panda.hpp\"\n#include <thread>\n\nnamespace ls {\n    namespace blocks {\n        class PandaArmBlock\n                : public Block<\n                        ::std::tuple<Eigen::Matrix<double, 7, 1>>,\n                        ::std::tuple<PandaState>,\n                        ::std::tuple<::std::string>\n                > {\n        public:\n            using Base =\n            Block<\n                    ::std::tuple<Eigen::Matrix<double, 7, 1>>,\n                    ::std::tuple<PandaState>,\n                    ::std::tuple<::std::string>\n            >;\n\n            using Matrix = Eigen::Matrix<double, 7, 1>;\n\n            PandaArmBlock()\n            {\n                this->template i<0>().object.setZero();\n                bindFunction();\n            }\n\n            ~PandaArmBlock()\n            {\n                panda_.stop();\n            }\n\n            typename ::std::tuple_element<0, typename Base::Params>::type &\n            ipAddress()\n            {\n                return this->template p<0>();\n            }\n\n            const typename ::std::tuple_element<0, typename Base::Params>::type &\n            ipAddress() const\n            {\n                return this->template p<0>();\n            }\n\n        protected:\n            Panda panda_;\n            \n            void bindFunction()\n            {\n                this->equation = ::std::bind(\n                        &PandaArmBlock::triggerFunction, this,\n                        ::std::placeholders::_1);\n            }\n\n            void triggerFunction(Base &b)\n            {\n                static bool init = false;\n                static bool ready = false;\n\n                if (!init) {\n                    panda_ = Panda{ipAddress(), false};\n                    \n                    init = panda_.initConnection().ok();\n                    \n                    if (!init)\n                        return;\n\n                    Eigen::AngleAxisd aa{M_PI / 2, Eigen::Vector3d{0, -1, 0}};\n                    Eigen::AngleAxisd aa2{M_PI, Eigen::Vector3d{1, 0, 0}};\n                    aa = aa * aa2;\n                    Eigen::Vector3d translation = {200e-3, 0, 0};\n\n                    panda_.setNominalToEndEffectorTransformation(aa, translation);\n                    \n                    panda_.setGuidingMode();\n\n                    ready = true;\n\n                    ::std::thread([&] () {\n                        panda_.robot_->control([&] (const franka::RobotState &rs, franka::Duration duration) -> franka::Torques\n                                               {\n                                                   // TODO: Add mutex for thread safety\n\n                                                   this->template o<0>().object.robot.parse(rs);\n                                                   this->template o<0>().propagate();\n\n                                                   while (!ready) {}\n\n                                                   ::std::array<double, 7> tau_d_array{this->template i<0>().object[0],\n                                                                                       this->template i<0>().object[1],\n                                                                                       this->template i<0>().object[2],\n                                                                                       this->template i<0>().object[3],\n                                                                                       this->template i<0>().object[4],\n                                                                                       this->template i<0>().object[5],\n                                                                                       this->template i<0>().object[6]};\n                                                   ready = false;\n                                                   return {tau_d_array};\n                                               });\n//                        panda_.control(f);\n                    }).detach();\n                }\n\n                ready = true;\n                \n//                b.template o<0>() = panda_.getState().value();\n            }\n        };\n\n        template<>\n        class BlockTraits<PandaArmBlock> {\n        public:\n            static constexpr const BlockType blockType = BlockType::CustomBlock;\n            enum {\n                directFeedthrough = false\n            };\n\n            using type = PandaArmBlock;\n            using Base = typename type::Base;\n\n            enum {\n                kIns = Base::kIns,\n                kOuts = Base::kOuts,\n                kPars = Base::kPars\n            };\n\n            static const ::std::array<::std::string, kIns> inTypes;\n            static const ::std::array<::std::string, kOuts> outTypes;\n            static const ::std::array<::std::string, kPars> parTypes;\n\n            static const ::std::array<::std::string, 0> templateTypes;\n        };\n    }\n}\n\n\n#endif //LSEXAMPLE_PANDAARMBLOCK_HPP\n", "meta": {"hexsha": "e76e47cce653ac5958923a6257575438baeb824e", "size": 5177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobotPID/PandaArmBlock.hpp", "max_stars_repo_name": "helkebir/Lodestar-Examples", "max_stars_repo_head_hexsha": "7d8ed5715980703665fc1bfe7f0327cb4cb9b487", "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": "RobotPID/PandaArmBlock.hpp", "max_issues_repo_name": "helkebir/Lodestar-Examples", "max_issues_repo_head_hexsha": "7d8ed5715980703665fc1bfe7f0327cb4cb9b487", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobotPID/PandaArmBlock.hpp", "max_forks_repo_name": "helkebir/Lodestar-Examples", "max_forks_repo_head_hexsha": "7d8ed5715980703665fc1bfe7f0327cb4cb9b487", "max_forks_repo_licenses": ["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.5133333333, "max_line_length": 127, "alphanum_fraction": 0.3760865366, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19624361026359122}}
{"text": "// Copyright 2019-present MongoDB 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 HEADER_EBA231D0_AA7A_4008_A9E8_BD1C98D9023E_INCLUDED\n#define HEADER_EBA231D0_AA7A_4008_A9E8_BD1C98D9023E_INCLUDED\n\n#include <cstdint>\n#include <memory>\n\n#include <boost/random.hpp>\n\nnamespace genny {\nnamespace v1 {\n\n/**\n * Genny random number generator.\n *\n * @tparam RNGImpl Random number generator implementation to use.\n * @private\n */\ntemplate <class RNGImpl>\nclass Random {\n\npublic:\n    using result_type = typename RNGImpl::result_type;\n\n    /** @private */\n    using Handle = Random&;\n\n    /**\n     * Construct a Random object.\n     * @param seed the seed. The default seed is used if seed is omitted.\n     */\n    explicit Random(result_type seed = 6514393) : _rng(seed) {}\n\n    // Moves are okay\n    Random(Random&&) noexcept = default;\n    Random& operator=(Random&&) noexcept = default;\n\n    // But no copies\n    Random(const Random&) = delete;\n    Random& operator=(const Random&) = delete;\n\n    ~Random() = default;\n\n    /**\n     * Construct new Random using the next number from the current one as the seed.\n     * @return\n     */\n    Random child() {\n        return Random(this->nextValue());\n    }\n\n    /**\n     * Seed engine.\n     */\n    void seed(result_type newSeed) {\n        _rng.seed(newSeed);\n    }\n\n    /**\n     * Generate random number.\n     */\n    result_type nextValue() {\n        return _rng();\n    }\n\n    /**\n     * Generate random number, shorthand for Random::nextValue()\n     */\n    result_type operator()() {\n        return this->nextValue();\n    }\n\n    /**\n     * Minimum value.\n     */\n    static constexpr auto min() {\n        return RNGImpl::min();\n    }\n\n    /**\n     * Maximum value.\n     */\n    static constexpr auto max() {\n        return RNGImpl::max();\n    }\n\nprivate:\n    // RNGImpl is a plain class member instead of a unique pointer to avoid performance penalty.\n    // For more detail, see https://github.com/10gen/genny/pull/88#issuecomment-451014165\n    RNGImpl _rng;\n};\n}  // namespace v1\n\n/**\n * DefaultRandom should be used if you need a random number generator.\n */\n// Note we use boost::random because its distributions are\n// cross-platform.\nusing DefaultRandom = v1::Random<boost::random::mt19937_64>;\n\n}  // namespace genny\n#endif  // HEADER_EBA231D0_AA7A_4008_A9E8_BD1C98D9023E_INCLUDED\n", "meta": {"hexsha": "78099d99aadc553f40e8bf2cf99365ed56f23e86", "size": 2846, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/value_generators/include/value_generators/DefaultRandom.hpp", "max_stars_repo_name": "MikhailShchatko/genny", "max_stars_repo_head_hexsha": "00938dc557ef1ad9b6b2d950447bc0e372e951ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2019-01-30T17:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T00:05:33.000Z", "max_issues_repo_path": "src/value_generators/include/value_generators/DefaultRandom.hpp", "max_issues_repo_name": "MikhailShchatko/genny", "max_issues_repo_head_hexsha": "00938dc557ef1ad9b6b2d950447bc0e372e951ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 358.0, "max_issues_repo_issues_event_min_datetime": "2019-01-15T21:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:10:42.000Z", "max_forks_repo_path": "src/value_generators/include/value_generators/DefaultRandom.hpp", "max_forks_repo_name": "MikhailShchatko/genny", "max_forks_repo_head_hexsha": "00938dc557ef1ad9b6b2d950447bc0e372e951ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2019-01-15T20:01:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:19:52.000Z", "avg_line_length": 24.5344827586, "max_line_length": 96, "alphanum_fraction": 0.6626844694, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.1962436102635912}}
{"text": "// Copyright 2021 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#ifndef UTILIZATION__ARC_LANE_UTIL_HPP_\n#define UTILIZATION__ARC_LANE_UTIL_HPP_\n\n#include <rclcpp/rclcpp.hpp>\n#include <tier4_autoware_utils/geometry/geometry.hpp>\n#include <utilization/boost_geometry_helper.hpp>\n\n#include <autoware_auto_planning_msgs/msg/path_with_lane_id.hpp>\n\n#include <boost/optional.hpp>\n\n#ifdef ROS_DISTRO_GALACTIC\n#include <tf2_eigen/tf2_eigen.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#else\n#include <tf2_eigen/tf2_eigen.hpp>\n\n#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>\n#endif\n\n#include <algorithm>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#define EIGEN_MPL2_ONLY\n#include <Eigen/Core>\n\nnamespace behavior_velocity_planner\n{\nnamespace bg = boost::geometry;\nnamespace arc_lane_utils\n{\nusing PathIndexWithPose = std::pair<size_t, geometry_msgs::msg::Pose>;  // front index, pose\nusing PathIndexWithPoint2d = std::pair<size_t, Point2d>;                // front index, point2d\nusing PathIndexWithOffset = std::pair<size_t, double>;                  // front index, offset\n\ninline double calcSignedDistance(\n  const geometry_msgs::msg::Pose & p1, const geometry_msgs::msg::Point & p2)\n{\n  Eigen::Affine3d map2p1;\n  tf2::fromMsg(p1, map2p1);\n  const auto basecoords_p2 = map2p1.inverse() * Eigen::Vector3d(p2.x, p2.y, p2.z);\n  return basecoords_p2.x() >= 0 ? basecoords_p2.norm() : -basecoords_p2.norm();\n}\n\ninline boost::optional<Point2d> getNearestCollisionPoint(\n  const LineString2d & stop_line, const LineString2d & path_segment)\n{\n  // Find all collision points\n  std::vector<Point2d> collision_points;\n  bg::intersection(stop_line, path_segment, collision_points);\n  if (collision_points.empty()) {\n    return {};\n  }\n\n  // To dist list\n  std::vector<double> dist_list;\n  dist_list.reserve(collision_points.size());\n  std::transform(\n    collision_points.cbegin(), collision_points.cend(), std::back_inserter(dist_list),\n    [&path_segment](const Point2d & collision_point) {\n      return bg::distance(path_segment.front(), collision_point);\n    });\n\n  // Find nearest collision point\n  const auto min_itr = std::min_element(dist_list.cbegin(), dist_list.cend());\n  const auto min_idx = std::distance(dist_list.cbegin(), min_itr);\n\n  return collision_points.at(min_idx);\n}\n\ntemplate <class T>\nboost::optional<PathIndexWithPoint2d> findCollisionSegment(\n  const T & path, const LineString2d & stop_line)\n{\n  for (size_t i = 0; i < path.points.size() - 1; ++i) {\n    const auto & p1 = path.points.at(i).point.pose.position;      // Point before collision point\n    const auto & p2 = path.points.at(i + 1).point.pose.position;  // Point after collision point\n\n    const LineString2d path_segment = {{p1.x, p1.y}, {p2.x, p2.y}};\n\n    const auto nearest_collision_point = getNearestCollisionPoint(stop_line, path_segment);\n    if (nearest_collision_point) {\n      return std::make_pair(i, *nearest_collision_point);\n    }\n  }\n\n  return {};\n}\n\ntemplate <class T>\nboost::optional<PathIndexWithOffset> findForwardOffsetSegment(\n  const T & path, const size_t base_idx, const double offset_length)\n{\n  double sum_length = 0.0;\n  for (size_t i = base_idx; i < path.points.size() - 1; ++i) {\n    sum_length += tier4_autoware_utils::calcDistance2d(path.points.at(i), path.points.at(i + 1));\n\n    // If it's over offset point, return front index and remain offset length\n    if (sum_length >= offset_length) {\n      return std::make_pair(i, sum_length - offset_length);\n    }\n  }\n\n  // No enough path length\n  return {};\n}\n\ntemplate <class T>\nboost::optional<PathIndexWithOffset> findBackwardOffsetSegment(\n  const T & path, const size_t base_idx, const double offset_length)\n{\n  double sum_length = 0.0;\n  const auto start = static_cast<std::int32_t>(base_idx) - 1;\n  for (std::int32_t i = start; i >= 0; --i) {\n    sum_length += tier4_autoware_utils::calcDistance2d(path.points.at(i), path.points.at(i + 1));\n\n    // If it's over offset point, return front index and remain offset length\n    if (sum_length >= offset_length) {\n      const auto k = static_cast<std::size_t>(i);\n      return std::make_pair(k, sum_length - offset_length);\n    }\n  }\n\n  // No enough path length\n  return {};\n}\n\ntemplate <class T>\nboost::optional<PathIndexWithOffset> findOffsetSegment(\n  const T & path, const PathIndexWithPoint2d & collision_segment, const double offset_length)\n{\n  const size_t collision_idx = collision_segment.first;\n  const Point2d & collision_point = collision_segment.second;\n  const auto p_front = to_bg2d(path.points.at(collision_idx).point.pose.position);\n  const auto p_back = to_bg2d(path.points.at(collision_idx + 1).point.pose.position);\n\n  if (offset_length >= 0) {\n    return findForwardOffsetSegment(\n      path, collision_idx, offset_length + bg::distance(p_front, collision_point));\n  } else {\n    return findBackwardOffsetSegment(\n      path, collision_idx + 1, -offset_length + bg::distance(p_back, collision_point));\n  }\n}\n\ntemplate <class T>\ngeometry_msgs::msg::Pose calcTargetPose(const T & path, const PathIndexWithOffset & offset_segment)\n{\n  const size_t offset_idx = offset_segment.first;\n  const double remain_offset_length = offset_segment.second;\n  const auto & p_front = path.points.at(offset_idx).point.pose.position;\n  const auto & p_back = path.points.at(offset_idx + 1).point.pose.position;\n\n  // To Eigen point\n  const auto p_eigen_front = Eigen::Vector2d(p_front.x, p_front.y);\n  const auto p_eigen_back = Eigen::Vector2d(p_back.x, p_back.y);\n\n  // Calculate interpolation ratio\n  const auto interpolate_ratio = remain_offset_length / (p_eigen_back - p_eigen_front).norm();\n\n  // Add offset to front point\n  const auto target_point_2d = p_eigen_front + interpolate_ratio * (p_eigen_back - p_eigen_front);\n  const double interpolated_z = p_front.z + interpolate_ratio * (p_back.z - p_front.z);\n\n  // Calculate orientation so that X-axis would be along the trajectory\n  geometry_msgs::msg::Pose target_pose;\n  target_pose.position.x = target_point_2d.x();\n  target_pose.position.y = target_point_2d.y();\n  target_pose.position.z = interpolated_z;\n  const double yaw = tier4_autoware_utils::calcAzimuthAngle(p_front, p_back);\n  target_pose.orientation = tier4_autoware_utils::createQuaternionFromYaw(yaw);\n  return target_pose;\n}\n\n}  // namespace arc_lane_utils\n}  // namespace behavior_velocity_planner\n\n#endif  // UTILIZATION__ARC_LANE_UTIL_HPP_\n", "meta": {"hexsha": "9c4b3e47f995dcd2d6b411f04904ddb9f4067bc7", "size": 6919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "planning/behavior_velocity_planner/include/utilization/arc_lane_util.hpp", "max_stars_repo_name": "meliketanrikulu/autoware.universe", "max_stars_repo_head_hexsha": "04f2b53ae1d7b41846478641ad6ff478c3d5a247", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2021-11-30T09:03:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:25:17.000Z", "max_issues_repo_path": "planning/behavior_velocity_planner/include/utilization/arc_lane_util.hpp", "max_issues_repo_name": "meliketanrikulu/autoware.universe", "max_issues_repo_head_hexsha": "04f2b53ae1d7b41846478641ad6ff478c3d5a247", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 425.0, "max_issues_repo_issues_event_min_datetime": "2021-11-30T02:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:26:37.000Z", "max_forks_repo_path": "planning/behavior_velocity_planner/include/utilization/arc_lane_util.hpp", "max_forks_repo_name": "meliketanrikulu/autoware.universe", "max_forks_repo_head_hexsha": "04f2b53ae1d7b41846478641ad6ff478c3d5a247", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2021-11-30T02:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:38:29.000Z", "avg_line_length": 35.4820512821, "max_line_length": 99, "alphanum_fraction": 0.7366671484, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.19616159926255441}}
{"text": "//---------------------------------------------------------------------------//\n//  MIT License\n//\n//  Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\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#define BOOST_TEST_MODULE filecoin_pieces_test\n\n#include <boost/test/data/monomorphic.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <nil/filecoin/proofs/pieces.hpp>\n\nBOOST_AUTO_TEST_SUITE(filecoin_pieces_test_suite)\n\ntemplate<typename PieceSizesIterator>\nstd::tuple<std::array<std::uint8_t, 32>, piece_info>\n    build_sector(PieceSizesIterator piece_sizes_first, PieceSizesIterator pieces_sizes_last, sector_size ss) {\n    let rng = &mut XorShiftRng::from_seed(crate::TEST_SEED);\n    let porep_id = [32; 32];\n    let graph = StackedBucketGraph<DefaultPieceHasher>::new_stacked(\n        sector_size / NODE_SIZE, DRG_DEGREE, EXP_DEGREE, porep_id);\n\n    let mut staged_sector = Vec::with_capacity(u64::from(sector_size) as usize);\n    let mut staged_sector_io = std::io::Cursor::new (&mut staged_sector);\n    let mut piece_infos = Vec::with_capacity(piece_sizes.len());\n\n    for (i, piece_size)\n        in piece_sizes.iter().enumerate() {\n            let piece_size_u = u64::from(*piece_size) as usize;\n            let mut piece_bytes = vec ![255u8; piece_size_u];\n            rng.fill_bytes(&mut piece_bytes);\n\n            let mut piece_file = std::io::Cursor::new (&mut piece_bytes);\n\n            let(piece_info, _) =\n                crate::api::add_piece(&mut piece_file, &mut staged_sector_io, *piece_size, &piece_sizes[..i], ) ?\n                ;\n\n            piece_infos.push(piece_info);\n        }\n    BOOST_CHECK_EQUAL(staged_sector.len(), u64::from(sector_size) as usize);\n\n    let data_tree : DataTree = create_base_merkle_tree::<DataTree>(None, graph.size(), &staged_sector);\n    let comm_d_root : Fr = data_tree.root().into();\n    let comm_d = commitment_from_fr(comm_d_root);\n\n    return std::make_tuple(comm_d, piece_infos);\n}\n\nstd::uint32_t prev_power_of_two(std::uint32_t x) {\n    x |= x >> 1;\n    x |= x >> 2;\n    x |= x >> 4;\n    x |= x >> 8;\n    x |= x >> 16;\n    return x - (x >> 1);\n}\n\nBOOST_AUTO_TEST_CASE(test_empty_source) {\n    let mut source = EmptySource::new (12);\n    let mut target = Vec::new ();\n    source.read_to_end(&mut target);\n    BOOST_CHECK_EQUAL(target, vec ![0u8; 12]);\n}\n\nBOOST_AUTO_TEST_CASE(test_compute_comm_d_empty) {\n    let comm_d = compute_comm_d(SectorSize(2048), &[]);\n    BOOST_CHECK_EQUAL(comm_d, [\n        252, 126, 146, 130, 150, 229, 22, 250, 173, 233, 134, 178, 143, 146, 212, 74,\n        79,  36,  185, 53,  72,  82,  35, 55,  106, 121, 144, 39,  188, 24,  248, 51\n    ]);\n\n    let comm_d = compute_comm_d(SectorSize(128), &[]);\n    BOOST_CHECK_EQUAL(hex::encode(&comm_d), \"3731bb99ac689f66eef5973e4a94da188f4ddcae580724fc6f3fd60dfd488333\", );\n}\n\nBOOST_AUTO_TEST_CASE(test_get_piece_alignment) {\n    let table = vec ![\n        (0, 0, (0, 127)),\n        (0, 127, (0, 0)),\n        (0, 254, (0, 0)),\n        (0, 508, (0, 0)),\n        (0, 1016, (0, 0)),\n        (127, 127, (0, 0)),\n        (127, 254, (127, 0)),\n        (127, 508, (381, 0)),\n        (100, 100, (27, 27)),\n        (200, 200, (54, 54)),\n        (300, 300, (208, 208)),\n    ];\n\n    for (bytes_in_sector, bytes_in_piece, (expected_left_align, expected_right_align))\n        in table.clone() {\n            let PieceAlignment {\n                left_bytes : UnpaddedBytesAmount(actual_left_align),\n                right_bytes : UnpaddedBytesAmount(actual_right_align),\n            } = get_piece_alignment(UnpaddedBytesAmount(bytes_in_sector), UnpaddedBytesAmount(bytes_in_piece), );\n            BOOST_CHECK_EQUAL((expected_left_align, expected_right_align), (actual_left_align, actual_right_align));\n        }\n}\n\nBOOST_AUTO_TEST_CASE(test_get_piece_start_byte) {\n    let pieces = [\n        UnpaddedBytesAmount(31),\n        UnpaddedBytesAmount(32),\n        UnpaddedBytesAmount(33),\n    ];\n\n    BOOST_CHECK_EQUAL(get_piece_start_byte(&pieces[..0], pieces[0]), UnpaddedByteIndex(0));\n    BOOST_CHECK_EQUAL(get_piece_start_byte(&pieces[..1], pieces[1]), UnpaddedByteIndex(127));\n    BOOST_CHECK_EQUAL(get_piece_start_byte(&pieces[..2], pieces[2]), UnpaddedByteIndex(254));\n}\n\nBOOST_AUTO_TEST_CASE(test_verify_simple_pieces) {\n    let rng = &mut XorShiftRng::from_seed(crate::TEST_SEED);\n\n    //     g\n    //   /  \\\n        //  e    f\n    // / \\  / \\\n        // a  b c  d\n\n    let(a, b, c, d) : ([u8; 32], [u8; 32], [u8; 32], [u8; 32]) = rng.gen();\n\n    let mut e = [0u8; 32];\n    let h = piece_hash(&a, &b);\n    e.copy_from_slice(h.as_ref());\n\n    let mut f = [0u8; 32];\n    let h = piece_hash(&c, &d);\n    f.copy_from_slice(h.as_ref());\n\n    let mut g = [0u8; 32];\n    let h = piece_hash(&e, &f);\n    g.copy_from_slice(h.as_ref());\n    let a = PieceInfo::new (a, UnpaddedBytesAmount(127));\n    let b = PieceInfo::new (b, UnpaddedBytesAmount(127));\n    let c = PieceInfo::new (c, UnpaddedBytesAmount(127));\n    let d = PieceInfo::new (d, UnpaddedBytesAmount(127));\n\n    let e = PieceInfo::new (e, UnpaddedBytesAmount(254));\n    let f = PieceInfo::new (f, UnpaddedBytesAmount(254));\n    let g = PieceInfo::new (g, UnpaddedBytesAmount(508));\n\n    let sector_size = SectorSize(4 * 128);\n    let comm_d = g.commitment;\n\n    // println!(\"e: {:?}\", e);\n    // println!(\"f: {:?}\", f);\n    // println!(\"g: {:?}\", g);\n\n    BOOST_CHECK(\n        verify_pieces(&comm_d, &[ a.clone(), b.clone(), c.clone(), d.clone() ], sector_size).expect(\"failed to verify\"),\n        \"[a, b, c, d]\");\n\n    BOOST_CHECK(verify_pieces(&comm_d, &[ e.clone(), c, d ], sector_size).expect(\"failed to verify\"), \"[e, c, d]\");\n\n    BOOST_CHECK(verify_pieces(&comm_d, &[ e, f.clone() ], sector_size).expect(\"failed to verify\"), \"[e, f]\");\n\n    BOOST_CHECK(verify_pieces(&comm_d, &[ a, b, f ], sector_size).expect(\"failed to verify\"), \"[a, b, f]\");\n\n    BOOST_CHECK(verify_pieces(&comm_d, &[g], sector_size).expect(\"failed to verify\"), \"[g]\");\n}\n\nBOOST_AUTO_TEST_CASE(test_verify_padded_pieces) {\n    // [\n    //   {(A0 00) (BB BB)} -> A(1) P(1) P(1) P(1) B(4)\n    //   {(CC 00) (00 00)} -> C(2)      P(1) P(1) P(1) P(1) P(1) P(1)\n    // ]\n    // [\n    //   {(DD DD) (DD DD)} -> D(8)\n    //   {(00 00) (00 00)} -> P(1) P(1) P(1) P(1) P(1) P(1) P(1) P(1)\n    // ]\n\n    let sector_size = SectorSize(32 * 128);\n    let pad = zero_padding(UnpaddedBytesAmount(127));\n\n    let pieces = vec ![\n        PieceInfo::new ([1u8; 32], UnpaddedBytesAmount(1 * 127)),\n        PieceInfo::new ([2u8; 32], UnpaddedBytesAmount(4 * 127)),\n        PieceInfo::new ([3u8; 32], UnpaddedBytesAmount(2 * 127)),\n        PieceInfo::new ([4u8; 32], UnpaddedBytesAmount(8 * 127)),\n    ];\n\n    let padded_pieces = vec ![\n        PieceInfo::new ([1u8; 32], UnpaddedBytesAmount(1 * 127)),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        PieceInfo::new ([2u8; 32], UnpaddedBytesAmount(4 * 127)),\n        PieceInfo::new ([3u8; 32], UnpaddedBytesAmount(2 * 127)),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        PieceInfo::new ([4u8; 32], UnpaddedBytesAmount(8 * 127)),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        pad.clone(),\n        pad,\n    ];\n\n    let hash = | a, b | {\n        let hash = piece_hash(a, b);\n        let mut res = [0u8; 32];\n        res.copy_from_slice(hash.as_ref());\n        res\n    };\n\n    std::array<std::uint8_t, 32> layer1 = {\n        hash(&padded_pieces[0].commitment, &padded_pieces[1].commitment),      // 2: H(A(1) | P(1))\n        hash(&padded_pieces[2].commitment, &padded_pieces[3].commitment),      // 2: H(P(1) | P(1))\n        padded_pieces[4].commitment,                                           // 4: B(4)\n        padded_pieces[5].commitment,                                           // 2: C(2)\n        hash(&padded_pieces[6].commitment, &padded_pieces[7].commitment),      // 2: H(P(1) | P(1))\n        hash(&padded_pieces[8].commitment, &padded_pieces[9].commitment),      // 2: H(P(1) | P(1))\n        hash(&padded_pieces[10].commitment, &padded_pieces[11].commitment),    // 2: H(P(1) | P(1))\n        padded_pieces[12].commitment,                                          // 8: D(8)\n        hash(&padded_pieces[13].commitment, &padded_pieces[14].commitment),    // 2: H(P(1) | P(1))\n        hash(&padded_pieces[15].commitment, &padded_pieces[16].commitment),    // 2: H(P(1) | P(1))\n        hash(&padded_pieces[17].commitment, &padded_pieces[18].commitment),    // 2: H(P(1) | P(1))\n        hash(&padded_pieces[19].commitment, &padded_pieces[20].commitment),    // 2: H(P(1) | P(1))\n    };\n\n    std::array<std::uint8_t, 32> layer2 = {\n        hash(&layer1[0], &layer1[1]),      // 4\n        layer1[2],                         // 4\n        hash(&layer1[3], &layer1[4]),      // 4\n        hash(&layer1[5], &layer1[6]),      // 4\n        layer1[7],                         // 8\n        hash(&layer1[8], &layer1[9]),      // 4\n        hash(&layer1[10], &layer1[11]),    // 4\n    };\n\n    let layer3 = vec ![\n        hash(&layer2[0], &layer2[1]),    // 8\n        hash(&layer2[2], &layer2[3]),    // 8\n        layer2[4],                       // 8\n        hash(&layer2[5], &layer2[6]),    // 8\n    ];\n\n    let layer4 = vec ![\n        hash(&layer3[0], &layer3[1]),    // 16\n        hash(&layer3[2], &layer3[3]),    // 16\n    ];\n\n    let comm_d = hash(&layer4[0], &layer4[1]);    // 32\n\n    BOOST_CHECK(verify_pieces(&comm_d, &pieces, sector_size));\n}\n\nBOOST_AUTO_TEST_CASE(test_verify_random_pieces) {\n    let rng = &mut XorShiftRng::from_seed(crate::TEST_SEED);\n\n    for\n        sector_size in\n            &[SectorSize(4 * 128), SectorSize(32 * 128), SectorSize(1024 * 128), SectorSize(1024 * 8 * 128), ] {\n                println !(\"--- {:?} ---\", sector_size);\n    for (int i = 0; i < 100; i++) {\n            println !(\" - {} -\", i);\n            let unpadded_sector_size : UnpaddedBytesAmount = sector_size.clone().into();\n            let sector_size = *sector_size;\n            let padded_sector_size : PaddedBytesAmount = sector_size.into();\n\n            let mut piece_sizes = Vec::new ();\n            while(true) {\n                std::size_t  sum_piece_sizes = sum_piece_bytes_with_alignment(piece_sizes);\n\n                if (sum_piece_sizes\n                    > padded_sector_size) {\n                        piece_sizes.pop();\n                        break;\n                    }\n                if (sum_piece_sizes\n                    == padded_sector_size) {\n                        break;\n                    }\n\n                while (true) {\n                    // pieces must be power of two\n                    let left = u64::from(padded_sector_size) - u64::from(sum_piece_sizes);\n                let left_power_of_two = prev_power_of_two(left as u32);\n                let max_exp = (left_power_of_two as f64).log2() as u32;\n\n                std::size_t padded_exp;\n                if (max_exp > 7) {\n                    padded_exp = rng.gen_range(7,    // 2**7 == 128,\n                                  max_exp);\n                }\n                else {padded_exp = 7;};\n                let padded_piece_size = 2u64.pow(padded_exp);\n                let piece_size : UnpaddedBytesAmount = PaddedBytesAmount(padded_piece_size).into();\n                piece_sizes.push(piece_size);\n                let sum : PaddedBytesAmount = sum_piece_bytes_with_alignment(&piece_sizes).into();\n\n                if (sum\n                    > padded_sector_size) {\n                        // pieces might be too large after padding, so remove them and try again.\n                        piece_sizes.pop();\n                    }\n                else {\n                    break;\n                }\n            }\n        }\n\n    // println!(\n    //     \"  {:?}\",\n    //     piece_sizes\n    //         .iter()\n    //         .map(|s| u64::from(*s) / 127)\n    //         .collect::<Vec<_>>()\n    // );\n    BOOST_CHECK(sum_piece_bytes_with_alignment(&piece_sizes) <= unpadded_sector_size);\n    BOOST_CHECK(!piece_sizes.is_empty());\n\n    let(comm_d, piece_infos) = build_sector(&piece_sizes, sector_size) ? ;\n\nBOOST_CHECK(\nverify_pieces(comm_d, piece_infos, sector_size));\n            }\n}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2f4330bcf79cc473aff88591601f9d06e88add5a", "size": 13456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/filecoin/test/pieces.cpp", "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/filecoin/test/pieces.cpp", "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/filecoin/test/pieces.cpp", "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": 38.2272727273, "max_line_length": 120, "alphanum_fraction": 0.5636147444, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.19616159555959295}}
{"text": "#pragma once\n\n#include <iostream>\n#include <boost/format.hpp>\n#include <boost/program_options.hpp>\n#include <Eigen/Dense>\n#include \"grape.hpp\"\n#include \"grapedb.hpp\"\n#include \"lot.hpp\"\n\nnamespace arbor\n{\n\nclass Arbor\n    {\n    public:\n                            Arbor();\n                            ~Arbor();\n\n        void                processCommandLineOptions(int argc, const char * argv[]);\n        void                run();\n\n    private:\n        typedef std::pair<unsigned, unsigned>   size_topol_pair_t;\n        typedef std::vector<double>             dlb_vect_t;\n        typedef std::vector<double>             param_vect_t;\n        typedef std::vector<param_vect_t>       sample_vect_t;\n        typedef std::pair<unsigned, double>     pair_uint_dbl_t;\n        typedef pair_uint_dbl_t &               pair_uint_dbl_ref_t;\n\n        enum ParamType {ptype_edge_length, ptype_gamma_shape, ptype_pinvar, ptype_exchangeability, ptype_frequency};\n\n        // member functions\n        void                initRandom();\n        void                showUserSpecifiedOptions() const;\n        void                calcParamTypesFromColumnHeaders();\n        void                readData();\n        void                showParamTable() const;\n        void                calcIndivTopolMargLikes();\n        void                showTopoFreq();\n        void                showTopoTable();\n        double              summationWithFloatingControl(const std::vector<double> & v) const;\n        void                margLikeOneTopology(sample_vect_t & parameters, dlb_vect_t & log_likelihoods, dlb_vect_t & log_priors);\n        void                chooseGrapeSeeds(sample_vect_t & parameters);\n        void                calcMeansAndStdevs(sample_vect_t & parameters);\n        void                standardizeSampleAllowingCorrelation(sample_vect_t & parameters);\n        void                standardizeSampleAssumingIndependence(sample_vect_t & parameters);\n        double              calcDistance(std::vector<double> & a, std::vector<double> & b) const;\n        double              calcPutativeRadius(unsigned index, sample_vect_t & parameters, unsigned num_to_keep, std::vector<pair_uint_dbl_t> & neighbors);\n        void                createGrapes(sample_vect_t & parameters, dlb_vect_t & log_likelihoods, dlb_vect_t & log_priors, dlb_vect_t & log_jacobians);\n        void                calcDeltaTerms(sample_vect_t & parameters, dlb_vect_t & log_likelihoods, dlb_vect_t & log_priors, dlb_vect_t & log_jacobians);\n        void                calcRatioTerms(sample_vect_t & parameters, dlb_vect_t & log_likelihoods, dlb_vect_t & log_priors, dlb_vect_t & log_jacobians);\n        void                calcOverallMargLike();\n\n\n        // data members representing user-configurable options\n        std::string                             _data_file_name;            // the name of the sample file to be processed\n        unsigned                                _min_sample_size;           // minimum number of samples for tree topology inclusion\n        unsigned                                _rnseed;                    // pseudorandom number seed\n        double                                  _grape_fraction;            // fraction of sample used to define grapes\n\n        // data members that could become user-configurable options in the future\n        unsigned                                _skip;                      // number of samples to skip (as burn-in)\n        bool                                    _correlation;               // if true, uses full covariance matrix to standardize parameters\n\n        // other data members\n        Lot::SharedPtr                          _lot;                       // Pseudorandom number generator\n        GrapeDatabase                           _db;                        // object that stores results for each tree topology and used for outputting summaries of results\n        std::vector<std::string>                _column_headers;            // labels in first row of parameter file\n        std::map<unsigned, dlb_vect_t>          _log_likelihoods;           // map with key=topology and value=vector of log-likelihood (3rd column of parameter file)\n        std::map<unsigned, dlb_vect_t>          _log_priors;                // map with key=topology and value=vector of log-prior (4th column of parameter file)\n        std::map<unsigned, sample_vect_t>       _parameters;                // map with key=topology and value=vector of parameter vectors\n        unsigned                                _nsubsets;                  // number of data subsets (determined from prefixes in column headers)\n        unsigned                                _nparams;                   // length of each vector stored in _parameters\n        std::vector<ParamType>                  _param_types;               // parameter types in order of appearance in sample vectors\n        std::vector<unsigned>                   _param_subsets;             // data subset of each parameter in order of appearance in sample vectors\n        std::vector<size_topol_pair_t>          _tree_topologies;           // vector storing topology number and frequency pairs\n        unsigned                                _N;                         // total number of estimation sample points used over all tree topologies\n        unsigned                                _total_sample_size;         // total number of samples used (does not count samples from tree topologies not used)\n        double                                  _min_radius;                // minimum radius of all grapes for one particular tree topology\n        std::vector<double>                     _log_ratio_terms;           // terms composing numerator of estimator of 1/c\n        std::vector<double>                     _delta_terms;               // terms composing denominator of estimator of 1/c\n\n        // - used if assuming independence among parameters\n        std::vector<double>                     _means;                     // means of parameters from reference sample\n        std::vector<double>                     _stdevs;                    // standard deviations of parameters from reference sample\n\n        // - used if allowing correlations among parameters\n        Eigen::VectorXd                         _Means;                     // 1 x p vector of column means\n        Eigen::VectorXd                         _primary_eigenvector;       // eigenvector with largest eigenvalue from variance-covariance matrix\n        Eigen::MatrixXd                         _Y;                         // n x p matrix of sampled parameter vectors\n        Eigen::MatrixXd                         _M;                         // n x p matrix in which each row is vector of column means\n        Eigen::MatrixXd                         _S;                         // p x p covariance matrix raised to power 0.5\n        Eigen::MatrixXd                         _Sinv;                      // p x p covariance matrix raised to power -0.5\n        double                                  _logdetS;                   // log |determinant of _S|\n\n        // data members that are emptied and reused for each topology\n        unsigned                                _in_multiple_grapes;        // number of estimation sample points placed in more than one grape\n        std::vector<double>                     _placed;                    // vector of absolute differences between log-kernel of placed sample point and the log-kernel of the center of the grape in which it was placed\n        std::vector<Grape>                      _grapes;                    // vector of Grape objects\n        std::vector<double>                     _log_jacobians;             // log of the jacobian for log-transformation plus standardization\n        std::vector<unsigned>                   _reference_indices;         // Indices into _parameters of reference sample points\n        std::vector<unsigned>                   _estimation_indices;        // Indices into _parameters of estimation sample points\n\n        // static data members\n        static std::string                      _program_name;              // name of the program\n        static std::string                      _author;                    // author of program\n        static unsigned                         _major_version;             // major version number (e.g. \"1\" in \"version 1.2\")\n        static unsigned                         _minor_version;             // minor version number (e.g. \"2\" in \"version 1.2\")\n        static unsigned                         _def_rnseed;                // default value for _rnseed\n        static unsigned                         _def_minsamplesize;         // default value for _min_sample_size\n        static double                           _def_grapefraction;         // default value for _grape_fraction\n\n    };\n\ninline Arbor::Arbor()\n  : _min_sample_size(_def_minsamplesize)\n  , _rnseed(_def_rnseed)\n  , _grape_fraction(_def_grapefraction)\n  , _skip(1)\n  , _correlation(true)\n    {\n    std::cout << boost::str(boost::format(\"%s %d.%d (written by %s)\") % _program_name % _major_version % _minor_version % _author) << std::endl;\n    }\n\ninline Arbor::~Arbor()\n    {\n    }\n\n}\n", "meta": {"hexsha": "6a42a8fa60f4b9b55f54cd77af4b73f7fbe11b3a", "size": 9265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "arbor/arbor/arbor.hpp", "max_stars_repo_name": "plewis/arbor", "max_stars_repo_head_hexsha": "f76c801f54874ba41dff63cc95cce42925ec8a7d", "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": "arbor/arbor/arbor.hpp", "max_issues_repo_name": "plewis/arbor", "max_issues_repo_head_hexsha": "f76c801f54874ba41dff63cc95cce42925ec8a7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arbor/arbor/arbor.hpp", "max_forks_repo_name": "plewis/arbor", "max_forks_repo_head_hexsha": "f76c801f54874ba41dff63cc95cce42925ec8a7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.7251908397, "max_line_length": 220, "alphanum_fraction": 0.5519697787, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1961615918566316}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/timing.h\"\n#include \"dynet/rnn.h\"\n#include \"dynet/gru.h\"\n#include \"dynet/lstm.h\"\n#include \"dynet/fast-lstm.h\"\n#include \"dynet/expr.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <type_traits>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/program_options.hpp>\n\n#include \"s2s/dynet/dict.h\"\n#include \"s2s/corpus/options.hpp\"\n#include \"s2s/corpus/corpora.hpp\"\n#include \"s2s/corpus/dicts.hpp\"\n#include \"s2s/corpus/batch.hpp\"\n#include \"s2s/nn/encdec.hpp\"\n\n#ifndef INCLUDE_GUARD_ENCODER_DECODER_BASE_HPP\n#define INCLUDE_GUARD_ENCODER_DECODER_BASE_HPP\n\nnamespace s2s {\n\nclass encoder_decoder_base : public encoder_decoder {\n\npublic:\n\n    std::vector<dynet::Expression> h_bi;\n    dynet::Expression i_feed;\n\n    explicit encoder_decoder_base(dynet::ParameterCollection& model, const s2s_options& opts, dicts& d) : encoder_decoder(model,opts,d) {\n\n        flag_drop_out = true;\n        unsigned int dec_feeding_size = 0;\n\n        assert(opts.dec_feature_vocab_size.size() == opts.dec_feature_vec_size.size());\n        unsigned int cell_ratio = 2; // In GRU, cell_ratio = 1;\n\n        p_dec_init_w.resize(opts.num_layers * cell_ratio);\n        for(unsigned int i = 0; i < opts.num_layers * cell_ratio; i++){\n            p_dec_init_w[i] = model.add_parameters({opts.rnn_size, opts.rnn_size});\n        }\n        p_dec_init_bias.resize(opts.num_layers * cell_ratio);\n        for(unsigned int i = 0; i < opts.num_layers * cell_ratio; i++){\n            p_dec_init_bias[i] = model.add_parameters({opts.rnn_size});\n        }\n        if(opts.additional_output_layer == true){\n            dec_feeding_size = opts.rnn_size;\n        }else{\n            dec_feeding_size = opts.rnn_size * 3;\n        }\n        if(opts.additional_output_layer == true){\n            p_add_W = model.add_parameters({dec_feeding_size, opts.rnn_size * 3});\n            p_add_bias = model.add_parameters({dec_feeding_size});\n            p_out_R = model.add_parameters({d.dict_set_trg.d_word.size(), opts.rnn_size});\n            p_out_bias = model.add_parameters({d.dict_set_trg.d_word.size()});\n        }else{\n            p_out_R = model.add_parameters({d.dict_set_trg.d_word.size(), dec_feeding_size});\n            p_out_bias = model.add_parameters({d.dict_set_trg.d_word.size()});\n        }\n\n        dec_builder = dynet::VanillaLSTMBuilder(\n            opts.num_layers,\n            (rev_enc_builder.input_dim + dec_feeding_size + 3),\n            opts.rnn_size,\n            model\n        );\n    \n    }\n\n    encoder_decoder_base(const encoder_decoder_base&) = delete;\n    encoder_decoder_base& operator=(const encoder_decoder_base&) = delete;\n    ~encoder_decoder_base() = default;\n\n    void encoder(const batch &batch_local, dynet::ComputationGraph& cg) {\n        // initialize\n        init(batch_local, cg);\n        // embedding\n        embedding(batch_local, cg);\n\n        std::vector<dynet::Expression> h_fwd(slen);\n        std::vector<dynet::Expression> h_bwd(slen);\n        h_bi.resize(slen);\n\n        // forward encoder\n        fwd_enc_builder.new_graph(cg);\n        fwd_enc_builder.start_new_sequence();\n        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){\n            fwd_enc_builder.set_dropout_masks(batch_size);\n        }\n        for (unsigned int t_i = 0; t_i < slen; ++t_i) {\n            fwd_enc_builder.add_input(h_lookup[t_i]);\n            h_fwd[t_i] = fwd_enc_builder.back();\n        }\n        // backward encoder\n        rev_enc_builder.new_graph(cg);\n        rev_enc_builder.start_new_sequence();\n        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){\n            rev_enc_builder.set_dropout_masks(batch_size);\n        }\n        for (unsigned int ind = 0; ind < slen; ++ind) {\n            unsigned int t_i = (slen - 1) - ind;\n            rev_enc_builder.add_input(h_lookup[t_i]);\n            h_bwd[t_i] = rev_enc_builder.back();\n        }\n        // bidirectional encoding\n        for (unsigned int t_i = 0; t_i < slen; ++t_i) {\n            h_bi[t_i] = concatenate(std::vector<dynet::Expression>({h_fwd[t_i], h_bwd[t_i]}));\n        }\n        // Initialize decoder\n        std::vector<dynet::Expression> vec_enc_final_state;\n        vec_enc_final_state = rev_enc_builder.final_s();\n        dec_builder.new_graph(cg);\n        if(opts.additional_connect_layer){\n            std::vector<dynet::Expression> vec_dec_init_state;\n            for (unsigned int i = 0; i < vec_enc_final_state.size(); i++){\n                dynet::Expression i_dec_init_w = parameter(cg, p_dec_init_w[i]);\n                dynet::Expression i_dec_init_bias = parameter(cg, p_dec_init_bias[i]);\n                vec_dec_init_state.push_back(tanh(i_dec_init_w * vec_enc_final_state[i] + i_dec_init_bias));\n            }\n            dec_builder.start_new_sequence(vec_dec_init_state);\n        }else{\n            dec_builder.start_new_sequence(vec_enc_final_state);\n        }\n        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){\n            dec_builder.set_dropout_masks(batch_size);\n        }\n        init_feed(batch_local, cg);\n    }\n    \n    void init_feed(const batch &batch_local, dynet::ComputationGraph& cg){\n        i_feed = dynet::zeroes(cg, dynet::Dim({p_out_R.dim().d[1]}, batch_local.batch_size()));\n    }\n\n    dynet::Expression decoder_output(dynet::ComputationGraph& cg,  const std::vector<unsigned int> prev, const unsigned int t){\n        return decoder_output(cg, prev, t, dec_builder.state());\n    }\n\n    dynet::Expression decoder_output(dynet::ComputationGraph& cg,  const std::vector<unsigned int> prev, const unsigned int t, const dynet::RNNPointer pointer_prev){\n        // t should be always larger than 0.\n        assert(t > 0);\n        // convert previous label to the bit features.\n        std::vector<dynet::real> bit_features;\n        const unsigned int start_id = d.dict_set_trg.start_id_word;\n        const unsigned int kep_id = d.dict_set_trg.keep_id_word;\n        const unsigned int del_id = d.dict_set_trg.delete_id_word;\n        for(unsigned int batch_id = 0; batch_id < prev.size(); batch_id++){\n            // start\n            if(prev[batch_id] == start_id){\n                bit_features.push_back(opts.bit_size_flt);\n            }else{\n                bit_features.push_back(0.0f);\n            }\n            // keep\n            if(prev[batch_id] == kep_id){\n                bit_features.push_back(opts.bit_size_flt);\n            }else{\n                bit_features.push_back(0.0f);\n            }\n            // delete\n            if(prev[batch_id] == del_id){\n                bit_features.push_back(opts.bit_size_flt);\n            }else{\n                bit_features.push_back(0.0f);\n            }\n        }\n        dynet::Expression i_x_t = dynet::input(cg, dynet::Dim({3}, batch_size), bit_features);\n        dynet::Expression i_dec_input = concatenate(std::vector<dynet::Expression>({i_x_t, i_feed}));\n        i_dec_input = concatenate(std::vector<dynet::Expression>({i_dec_input, h_lookup[t]}));\n        dec_builder.add_input(pointer_prev, i_dec_input);\n        dynet::Expression i_h_dec = dec_builder.h.back().back();\n        if(opts.additional_output_layer){\n            dynet::Expression i_add_W = parameter(cg, p_add_W);\n            dynet::Expression i_add_bias = parameter(cg, p_add_bias);\n            i_feed = tanh(i_add_W * concatenate(std::vector<dynet::Expression>({i_h_dec, h_bi[t]})) + i_add_bias);\n        }else{\n            i_feed = concatenate(std::vector<dynet::Expression>({i_h_dec, h_bi[t]}));\n        }\n        dynet::Expression i_out_R = parameter(cg, p_out_R);\n        dynet::Expression i_out_bias = parameter(cg, p_out_bias);\n        dynet::Expression i_out_pred_t = i_out_R * i_feed + i_out_bias;\n        return i_out_pred_t;\n    }\n\n    void disable_dropout(){\n        fwd_char_enc_builder.disable_dropout();\n        rev_char_enc_builder.disable_dropout();\n        fwd_enc_builder.disable_dropout();\n        rev_enc_builder.disable_dropout();\n        dec_builder.disable_dropout();\n        flag_drop_out = false;\n    }\n\n    void enable_dropout(){\n        fwd_char_enc_builder.set_dropout(opts.dropout_rate_lstm_char, 0.f);\n        rev_char_enc_builder.set_dropout(opts.dropout_rate_lstm_char, 0.f);\n        fwd_enc_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);\n        rev_enc_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);\n        dec_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);\n        flag_drop_out = true;\n    }\n\nprivate:\n    friend class boost::serialization::access;\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version) {\n        ar & p_word_enc;\n        ar & p_char_enc;\n        ar & p_feat_enc;\n        ar & p_dec_init_bias;\n        ar & p_dec_init_w;\n        ar & p_layer_w;\n        ar & p_add_W;\n        ar & p_add_bias;\n        ar & p_out_R;\n        ar & p_out_bias;\n        ar & dec_builder;\n        ar & rev_char_enc_builder;\n        ar & fwd_char_enc_builder;\n        ar & rev_enc_builder;\n        ar & fwd_enc_builder;\n    }\n\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "1d510881f0664661ca09b31c8087decc4b2d7cff", "size": 9193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "compressor/include/s2s/nn/base.hpp", "max_stars_repo_name": "kamigaito/SLAHAN", "max_stars_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-05-24T16:03:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T21:52:32.000Z", "max_issues_repo_path": "compressor/include/s2s/nn/base.hpp", "max_issues_repo_name": "kamigaito/SLAHAN", "max_issues_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-31T18:41:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T16:16:22.000Z", "max_forks_repo_path": "compressor/include/s2s/nn/base.hpp", "max_forks_repo_name": "kamigaito/SLAHAN", "max_forks_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-05-26T01:53:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T07:13:31.000Z", "avg_line_length": 38.4644351464, "max_line_length": 165, "alphanum_fraction": 0.6364625258, "num_tokens": 2208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.19616158815367027}}
{"text": "/* Copyright 2015 Google Inc. All Rights Reserved.\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// Computing label Op\n\n#include <stdio.h>\n#include <cfloat>\n#include <math.h>\n#include <time.h>\n\n#include \"types.h\"\n#include \"sampler2D.h\"\n#include \"ransac.h\"\n#include \"Hypothesis.h\"\n#include \"detection.h\"\n#include <Eigen/Geometry> \n\n#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n\nusing namespace tensorflow;\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n\nREGISTER_OP(\"Houghvoting\")\n    .Attr(\"T: {float, double}\")\n    .Attr(\"is_train: int\")\n    .Input(\"bottom_label: int32\")\n    .Input(\"bottom_vertex: T\")\n    .Input(\"bottom_extents: T\")\n    .Input(\"bottom_meta_data: T\")\n    .Input(\"bottom_gt: T\")\n    .Output(\"top_box: T\")\n    .Output(\"top_pose: T\")\n    .Output(\"top_target: T\")\n    .Output(\"top_weight: T\");\n\nREGISTER_OP(\"HoughvotingGrad\")\n    .Attr(\"T: {float, double}\")\n    .Input(\"bottom_label: int32\")\n    .Input(\"bottom_vertex: T\")\n    .Input(\"grad: T\")\n    .Output(\"output_label: T\")\n    .Output(\"output_vertex: T\");\n\n/**\n * @brief Data used in NLOpt callback loop.\n */\nstruct DataForOpt\n{\n  int imageWidth;\n  int imageHeight;\n  float rx, ry;\n  cv::Rect bb2D;\n  std::vector<cv::Point3f> bb3D;\n  cv::Mat_<float> camMat;\n};\n\nvoid getLabels(const int* label_map, std::vector<std::vector<int>>& labels, std::vector<int>& object_ids, int width, int height, int num_classes, int minArea);\nvoid getBb3Ds(const float* extents, std::vector<std::vector<cv::Point3f>>& bb3Ds, int num_classes);\ninline bool samplePoint2D(jp::id_t objID, std::vector<cv::Point2f>& eyePts, std::vector<cv::Point2f>& objPts, std::vector<float>& distances, const cv::Point2f& pt2D, const float* vertmap, int width, int num_classes);\nstd::vector<TransHyp*> getWorkingQueue(std::map<jp::id_t, std::vector<TransHyp>>& hypMap, int maxIt);\ninline float point2line(cv::Point2d x, cv::Point2f n, cv::Point2f p);\ninline void countInliers2D(TransHyp& hyp, const float * vertmap, const std::vector<std::vector<int>>& labels, float inlierThreshold, int width, int num_classes, int pixelBatch);\ninline void updateHyp2D(TransHyp& hyp, int maxPixels);\ninline void filterInliers2D(TransHyp& hyp, int maxInliers);\ninline cv::Point2f getMode2D(jp::id_t objID, const cv::Point2f& pt, const float* vertmap, float & distance, int width, int num_classes);\nstatic double optEnergy(const std::vector<double> &pose, std::vector<double> &grad, void *data);\ndouble poseWithOpt(std::vector<double> & vec, DataForOpt data, int iterations);\nvoid estimateCenter(const int* labelmap, const float* vertmap, std::vector<std::vector<cv::Point3f>> bb3Ds, int batch, int height, int width, int num_classes, int is_train,\n  float fx, float fy, float px, float py, std::vector<cv::Vec<float, 13> >& outputs);\nvoid compute_target_weight(int height, int width, float* target, float* weight, std::vector<std::vector<cv::Point3f>> bb3Ds, const float* poses_gt, int num_gt, int num_classes, float fx, float fy, float px, float py, std::vector<cv::Vec<float, 13> > outputs);\ninline void compute_width_height(TransHyp& hyp, const float* vertmap, const std::vector<std::vector<int>>& labels, float inlierThreshold, int width, int num_classes);\n\ntemplate <typename Device, typename T>\nclass HoughvotingOp : public OpKernel {\n public:\n  explicit HoughvotingOp(OpKernelConstruction* context) : OpKernel(context) {\n    // Get the pool height\n    OP_REQUIRES_OK(context,\n                   context->GetAttr(\"is_train\", &is_train_));\n    // Check that pooled_height is positive\n    OP_REQUIRES(context, is_train_ >= 0,\n                errors::InvalidArgument(\"Need is_train >= 0, got \",\n                                        is_train_));\n  }\n\n  // bottom_label: (batch_size, height, width)\n  // bottom_vertex: (batch_size, height, width, 3 * num_classes)\n  // top_box: (num, 6) i.e., batch_index, cls, x1, y1, x2, y2\n  void Compute(OpKernelContext* context) override \n  {\n    // Grab the input tensor\n    const Tensor& bottom_label = context->input(0);\n    const Tensor& bottom_vertex = context->input(1);\n    const Tensor& bottom_extents = context->input(2);\n\n    // format of the meta_data\n    // intrinsic matrix: meta_data[0 ~ 8]\n    // inverse intrinsic matrix: meta_data[9 ~ 17]\n    // pose_world2live: meta_data[18 ~ 29]\n    // pose_live2world: meta_data[30 ~ 41]\n    // voxel step size: meta_data[42, 43, 44]\n    // voxel min value: meta_data[45, 46, 47]\n    const Tensor& bottom_meta_data = context->input(3);\n    auto meta_data = bottom_meta_data.flat<T>();\n\n    const Tensor& bottom_gt = context->input(4);\n    const float* gt = bottom_gt.flat<float>().data();\n\n    // data should have 5 dimensions.\n    OP_REQUIRES(context, bottom_label.dims() == 3,\n                errors::InvalidArgument(\"label must be 3-dimensional\"));\n\n    OP_REQUIRES(context, bottom_vertex.dims() == 4,\n                errors::InvalidArgument(\"vertex must be 4-dimensional\"));\n\n    // batch size\n    int batch_size = bottom_label.dim_size(0);\n    // height\n    int height = bottom_label.dim_size(1);\n    // width\n    int width = bottom_label.dim_size(2);\n    // num of classes\n    int num_classes = bottom_vertex.dim_size(3) / VERTEX_CHANNELS;\n    int num_meta_data = bottom_meta_data.dim_size(3);\n    int num_gt = bottom_gt.dim_size(0);\n\n    // for each image, run hough voting\n    std::vector<cv::Vec<float, 13> > outputs;\n    const float* extents = bottom_extents.flat<float>().data();\n\n    // bb3Ds\n    std::vector<std::vector<cv::Point3f>> bb3Ds;\n    getBb3Ds(extents, bb3Ds, num_classes);\n\n    int index_meta_data = 0;\n    float fx, fy, px, py;\n    for (int n = 0; n < batch_size; n++)\n    {\n      const int* labelmap = bottom_label.flat<int>().data() + n * height * width;\n      const float* vertmap = bottom_vertex.flat<float>().data() + n * height * width * VERTEX_CHANNELS * num_classes;\n      fx = meta_data(index_meta_data + 0);\n      fy = meta_data(index_meta_data + 4);\n      px = meta_data(index_meta_data + 2);\n      py = meta_data(index_meta_data + 5);\n\n      estimateCenter(labelmap, vertmap, bb3Ds, n, height, width, num_classes, is_train_, fx, fy, px, py, outputs);\n\n      index_meta_data += num_meta_data;\n    }\n\n    if (outputs.size() == 0)\n    {\n      std::cout << \"no detection\" << std::endl;\n      // add a dummy detection to the output\n      cv::Vec<float, 13> roi;\n      roi(0) = 0;\n      roi(1) = -1;\n      roi(2) = 0;\n      roi(3) = 0;\n      roi(4) = 1;\n      roi(5) = 1;\n      roi(6) = 1;\n      outputs.push_back(roi);\n    }\n\n    // Create output tensors\n    // top_box\n    int dims[2];\n    dims[0] = outputs.size();\n    dims[1] = 6;\n    TensorShape output_shape;\n    TensorShapeUtils::MakeShape(dims, 2, &output_shape);\n\n    Tensor* top_box_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &top_box_tensor));\n    float* top_box = top_box_tensor->template flat<float>().data();\n\n    // top_pose\n    dims[1] = 7;\n    TensorShape output_shape_pose;\n    TensorShapeUtils::MakeShape(dims, 2, &output_shape_pose);\n\n    Tensor* top_pose_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(1, output_shape_pose, &top_pose_tensor));\n    float* top_pose = top_pose_tensor->template flat<float>().data();\n\n    // top target\n    dims[1] = 4 * num_classes;\n    TensorShape output_shape_target;\n    TensorShapeUtils::MakeShape(dims, 2, &output_shape_target);\n\n    Tensor* top_target_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(2, output_shape_target, &top_target_tensor));\n    float* top_target = top_target_tensor->template flat<float>().data();\n    memset(top_target, 0, outputs.size() * 4 * num_classes *sizeof(T));\n\n    // top weight\n    Tensor* top_weight_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(3, output_shape_target, &top_weight_tensor));\n    float* top_weight = top_weight_tensor->template flat<float>().data();\n    memset(top_weight, 0, outputs.size() * 4 * num_classes *sizeof(T));\n    \n    for(int n = 0; n < outputs.size(); n++)\n    {\n      cv::Vec<float, 13> roi = outputs[n];\n\n      for (int i = 0; i < 6; i++)\n        top_box[n * 6 + i] = roi(i);\n\n      for (int i = 0; i < 7; i++)\n        top_pose[n * 7 + i] = roi(6 + i);\n    }\n\n    if (is_train_)\n      compute_target_weight(height, width, top_target, top_weight, bb3Ds, gt, num_gt, num_classes, fx, fy, px, py, outputs);\n  }\n private:\n  int is_train_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"Houghvoting\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), HoughvotingOp<CPUDevice, float>);\n\n\n// compute gradient\ntemplate <class Device, class T>\nclass HoughvotingGradOp : public OpKernel {\n public:\n  explicit HoughvotingGradOp(OpKernelConstruction* context) : OpKernel(context) {\n  }\n\n  void Compute(OpKernelContext* context) override \n  {\n    // Grab the input tensor\n    const Tensor& bottom_label = context->input(0);\n    const Tensor& bottom_vertex = context->input(1);\n\n    // data should have 5 dimensions.\n    OP_REQUIRES(context, bottom_label.dims() == 3,\n                errors::InvalidArgument(\"label must be 3-dimensional\"));\n\n    OP_REQUIRES(context, bottom_vertex.dims() == 4,\n                errors::InvalidArgument(\"vertex must be 4-dimensional\"));\n\n    // batch size\n    int batch_size = bottom_label.dim_size(0);\n    // height\n    int height = bottom_label.dim_size(1);\n    // width\n    int width = bottom_label.dim_size(2);\n    // num of classes\n    int num_classes = bottom_vertex.dim_size(3) / VERTEX_CHANNELS;\n\n    // construct the output shape\n    TensorShape output_shape = bottom_label.shape();\n    Tensor* top_label_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &top_label_tensor));\n    T* top_label = top_label_tensor->template flat<T>().data();\n    memset(top_label, 0, batch_size * height * width * sizeof(T));\n\n    TensorShape output_shape_1 = bottom_vertex.shape();\n    Tensor* top_vertex_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(1, output_shape_1, &top_vertex_tensor));\n    T* top_vertex = top_vertex_tensor->template flat<T>().data();\n    memset(top_vertex, 0, batch_size * height * width * 2 * num_classes *sizeof(T));\n  }\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"HoughvotingGrad\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), HoughvotingGradOp<CPUDevice, float>);\n\n\n// get label lists\nvoid getLabels(const int* label_map, std::vector<std::vector<int>>& labels, std::vector<int>& object_ids, int width, int height, int num_classes, int minArea)\n{\n  for(int i = 0; i < num_classes; i++)\n    labels.push_back( std::vector<int>() );\n\n  // for each pixel\n  #pragma omp parallel for\n  for(int x = 0; x < width; x++)\n  for(int y = 0; y < height; y++)\n  {\n    int label = label_map[y * width + x];\n    labels[label].push_back(y * width + x);\n  }\n\n  for(int i = 1; i < num_classes; i++)\n  {\n    if (labels[i].size() > minArea)\n    {\n      object_ids.push_back(i);\n    }\n  }\n}\n\n\n// get 3D bounding boxes\nvoid getBb3Ds(const float* extents, std::vector<std::vector<cv::Point3f>>& bb3Ds, int num_classes)\n{\n  // for each object\n  for (int i = 1; i < num_classes; i++)\n  {\n    cv::Vec<float, 3> extent;\n    extent(0) = extents[i * 3];\n    extent(1) = extents[i * 3 + 1];\n    extent(2) = extents[i * 3 + 2];\n\n    bb3Ds.push_back(getBB3D(extent));\n  }\n}\n\n\ninline cv::Point2f getMode2D(jp::id_t objID, const cv::Point2f& pt, const float* vertmap, float & distance, int width, int num_classes)\n{\n  int channel = VERTEX_CHANNELS * objID;\n  int offset = channel + VERTEX_CHANNELS * num_classes * (pt.y * width + pt.x);\n\n  jp::coord2_t mode;\n  mode(0) = vertmap[offset];\n  mode(1) = vertmap[offset + 1];\n  distance = vertmap[offset + 2];\n\n  return cv::Point2f(mode(0), mode(1));\n}\n\n\ninline bool samplePoint2D(jp::id_t objID, std::vector<cv::Point2f>& eyePts, std::vector<cv::Point2f>& objPts, std::vector<float>& distances, const cv::Point2f& pt2D, const float* vertmap, int width, int num_classes)\n{\n  float distance;\n  cv::Point2f obj = getMode2D(objID, pt2D, vertmap, distance, width, num_classes); // read out object coordinate\n\n  eyePts.push_back(pt2D);\n  objPts.push_back(obj);\n  distances.push_back(distance);\n\n  if (distance < 0)\n    return false;\n  else\n    return true;\n}\n\n\n/**\n * @brief Creates a list of pose hypothesis (potentially belonging to multiple objects) which still have to be processed (e.g. refined).\n * \n * The method includes all remaining hypotheses of an object if there is still more than one, or if there is only one remaining but it still needs to be refined.\n * \n * @param hypMap Map of object ID to a list of hypotheses for that object.\n * @param maxIt Each hypotheses should be at least this often refined.\n * @return std::vector< Ransac3D::TransHyp*, std::allocator< void > > List of hypotheses to be processed further.\n*/\nstd::vector<TransHyp*> getWorkingQueue(std::map<jp::id_t, std::vector<TransHyp>>& hypMap, int maxIt, int is_train)\n{\n  std::vector<TransHyp*> workingQueue;\n\n  if (is_train)\n  {      \n    for(auto it = hypMap.begin(); it != hypMap.end(); it++)\n    for(int h = 0; h < it->second.size(); h++)\n      if(it->second[h].refSteps < maxIt)\n        workingQueue.push_back(&(it->second[h]));\n  }\n  else\n  {\n    for(auto it = hypMap.begin(); it != hypMap.end(); it++)\n    for(int h = 0; h < it->second.size(); h++)\n      if(it->second.size() > 1 || it->second[h].refSteps < maxIt) //exclude a hypothesis if it is the only one remaining for an object and it has been refined enough already\n        workingQueue.push_back(&(it->second[h]));\n  }\n\n  return workingQueue;\n}\n\n\ninline float point2line(cv::Point2d x, cv::Point2f n, cv::Point2f p)\n{\n  float n1 = -n.y;\n  float n2 = n.x;\n  float p1 = p.x;\n  float p2 = p.y;\n  float x1 = x.x;\n  float x2 = x.y;\n\n  return fabs(n1 * (x1 - p1) + n2 * (x2 - p2)) / sqrt(n1 * n1 + n2 * n2);\n}\n\n\ninline float angle_distance(cv::Point2f x, cv::Point2f n, cv::Point2f p)\n{\n  return n.dot(x - p);\n}\n\n\ninline void countInliers2D(TransHyp& hyp, const float * vertmap, const std::vector<std::vector<int>>& labels, float inlierThreshold, int width, int num_classes, int pixelBatch)\n{\n  // reset data of last RANSAC iteration\n  hyp.inlierPts2D.clear();\n  hyp.inliers = 0;\n\n  hyp.effPixels = 0; // num of pixels drawn\n  hyp.maxPixels += pixelBatch; // max num of pixels to be drawn\t\n\n  int maxPt = labels[hyp.objID].size(); // num of pixels of this class\n  float successRate = hyp.maxPixels / (float) maxPt; // probability to accept a pixel\n\n  std::mt19937 generator;\n  std::negative_binomial_distribution<int> distribution(1, successRate); // lets you skip a number of pixels until you encounter the next pixel to accept\n\n  for(unsigned ptIdx = 0; ptIdx < maxPt;)\n  {\n    int index = labels[hyp.objID][ptIdx];\n    cv::Point2d pt2D(index % width, index / width);\n  \n    hyp.effPixels++;\n  \n    // read out object coordinate\n    float distance;\n    cv::Point2d obj = getMode2D(hyp.objID, pt2D, vertmap, distance, width, num_classes);\n\n    // inlier check\n    float d = cv::norm(hyp.center - pt2D);\n    if(point2line(hyp.center, obj, pt2D) < inlierThreshold && angle_distance(hyp.center, obj, pt2D) > 0 && d < std::max(hyp.bb.width, hyp.bb.height))\n    {\n      hyp.inlierPts2D.push_back(std::pair<cv::Point2d, cv::Point2d>(obj, pt2D)); // store object coordinate - camera coordinate correspondence\n      hyp.inliers++; // keep track of the number of inliers (correspondences might be thinned out for speed later)\n    }\n\n    // advance to the next accepted pixel\n    if(successRate < 1)\n      ptIdx += std::max(1, distribution(generator));\n    else\n      ptIdx++;\n  }\n}\n\n\ninline void compute_width_height(TransHyp& hyp, const float* vertmap, const std::vector<std::vector<int>>& labels, float inlierThreshold, int width, int num_classes)\n{\n  float w = -1;\n  float h = -1;\n  int maxPt = labels[hyp.objID].size(); // num of pixels of this class\n\n  for(unsigned ptIdx = 0; ptIdx < maxPt; ptIdx++)\n  {\n    int index = labels[hyp.objID][ptIdx];\n    cv::Point2d pt2D(index % width, index / width);\n  \n    // read out object coordinate\n    float distance;\n    cv::Point2d obj = getMode2D(hyp.objID, pt2D, vertmap, distance, width, num_classes);\n\n    // inlier check\n    float d = cv::norm(hyp.center - pt2D);\n    if(point2line(hyp.center, obj, pt2D) < inlierThreshold && angle_distance(hyp.center, obj, pt2D) > 0 && d < std::max(hyp.bb.width, hyp.bb.height))\n    {\n      float x = fabs(pt2D.x - hyp.center.x);\n      float y = fabs(pt2D.y - hyp.center.y);\n      if (x > w)\n        w = x;\n      if (y > h)\n        h = y;\n    }\n  }\n  hyp.width_ = 2 * w;\n  hyp.height_ = 2 * h;\n}\n\n\ninline void updateHyp2D(TransHyp& hyp, int maxPixels)\n{\n  if(hyp.inlierPts2D.size() < 4) return;\n  filterInliers2D(hyp, maxPixels); // limit the number of correspondences\n      \n  // data conversion\n  cv::Point2d center = hyp.center;\n  Hypothesis trans(center);\t\n\t\n  // recalculate pose\n  trans.calcCenter(hyp.inlierPts2D);\n  hyp.center = trans.getCenter();\n}\n\n\ninline void filterInliers2D(TransHyp& hyp, int maxInliers)\n{\n  if(hyp.inlierPts2D.size() < maxInliers) return; // maximum number not reached, do nothing\n      \t\t\n  std::vector<std::pair<cv::Point2d, cv::Point2d>> inlierPts; // filtered list of inlier correspondences\n\t\n  // select random correspondences to keep\n  for(unsigned i = 0; i < maxInliers; i++)\n  {\n    int idx = irand(0, hyp.inlierPts2D.size());\n\t    \n    inlierPts.push_back(hyp.inlierPts2D[idx]);\n  }\n\t\n  hyp.inlierPts2D = inlierPts;\n}\n\n\nvoid estimateCenter(const int* labelmap, const float* vertmap, std::vector<std::vector<cv::Point3f>> bb3Ds, int batch, int height, int width, int num_classes, int is_train,\n  float fx, float fy, float px, float py, std::vector<cv::Vec<float, 13> >& outputs)\n{     \n  //set parameters, see documentation of GlobalProperties\n  int maxIterations = 10000000;\n  float minArea = 400; // a hypothesis covering less projected area (2D bounding box) can be discarded (too small to estimate anything reasonable)\n  float minDist2D = 10;\n  float inlierThreshold3D = 0.5;\n  int ransacIterations;  // 256\n  int poseIterations = 100;\n  int preemptiveBatch;  // 1000\n  int maxPixels;  // 1000\n  int refIt;  // 8\n\n  if (is_train)\n  {\n    ransacIterations = 256;\n    preemptiveBatch = 100;\n    maxPixels = 1000;\n    refIt = 4;\n  }\n  else\n  {\n    ransacIterations = 256 * 1;\n    preemptiveBatch = 100 * 1;\n    maxPixels = 1000 * 1;\n    refIt = 8;\n  }\n\n  // labels\n  std::vector<std::vector<int>> labels;\n  std::vector<int> object_ids;\n  getLabels(labelmap, labels, object_ids, width, height, num_classes, minArea);\n\n  // camera matrix\n  cv::Mat_<float> camMat = cv::Mat_<float>::zeros(3, 3);\n  camMat(0, 0) = fx;\n  camMat(1, 1) = fy;\n  camMat(2, 2) = 1.f;\n  camMat(0, 2) = px;\n  camMat(1, 2) = py;\n\n  if (object_ids.size() == 0)\n    return;\n\t\n  int imageWidth = width;\n  int imageHeight = height;\n\t\t\n  // hold for each object a list of pose hypothesis, these are optimized until only one remains per object\n  std::map<jp::id_t, std::vector<TransHyp>> hypMap;\n\t\n  // sample initial pose hypotheses\n  #pragma omp parallel for\n  for(unsigned h = 0; h < ransacIterations; h++)\n  for(unsigned i = 0; i < maxIterations; i++)\n  {\n    // camera coordinate - object coordinate correspondences\n    std::vector<cv::Point2f> eyePts;\n    std::vector<cv::Point2f> objPts;\n    std::vector<float> distances;\n\t    \n    // sample first point and choose object ID\n    jp::id_t objID = object_ids[irand(0, object_ids.size())];\n\n    if(objID == 0) continue;\n\n    int pindex = irand(0, labels[objID].size());\n    int index = labels[objID][pindex];\n    cv::Point2f pt1(index % width, index / width);\n    \n    // sample first correspondence\n    if(!samplePoint2D(objID, eyePts, objPts, distances, pt1, vertmap, width, num_classes))\n      continue;\n\n    // sample other points in search radius, discard hypothesis if minimum distance constrains are violated\n    pindex = irand(0, labels[objID].size());\n    index = labels[objID][pindex];\n    cv::Point2f pt2(index % width, index / width);\n\n    if (cv::norm(pt1 - pt2) < minDist2D)\n      continue;\n\n    if(!samplePoint2D(objID, eyePts, objPts, distances, pt2, vertmap, width, num_classes))\n      continue;\n\n    // reconstruct\n    std::vector<std::pair<cv::Point2d, cv::Point2d>> pts2D;\n    float distance = 0;\n    for(unsigned j = 0; j < eyePts.size(); j++)\n    {\n      pts2D.push_back(std::pair<cv::Point2d, cv::Point2d>(\n      cv::Point2d(objPts[j].x, objPts[j].y),\n      cv::Point2d(eyePts[j].x, eyePts[j].y)\n      ));\n      distance += distances[j];\n    }\n    distance /= distances.size();\n\n    Hypothesis trans(pts2D);\n\n    // center\n    cv::Point2d center = trans.getCenter();\n    int x = int(center.x);\n    int y = int(center.y);\n    if (num_classes > 2 && x >= 0 && x < width && y >= 0 && y < height)\n    {\n      if (labelmap[y * width + x] == 0)\n        continue;\n    }\n    \n    // create a hypothesis object to store meta data\n    TransHyp hyp(objID, center);\n\n    // estimate a projection\n    cv::Mat tvec(3, 1, CV_64F);\n    cv::Mat rvec(3, 1, CV_64F);\n    for(int j = 0; j < 3; j++)\n    {\n      tvec.at<double>(j, 0) = 0;\n      rvec.at<double>(j, 0) = 0;\n    }\n    tvec.at<double>(2, 0) = distance;\n    jp::cv_trans_t pose(rvec, tvec);\n\n    std::vector<cv::Point2f> bb2D;\n    cv::projectPoints(bb3Ds[objID-1], pose.first, pose.second, camMat, cv::Mat(), bb2D);\n    \n    // get min-max of projected vertices\n    int minX = 10000000;\n    int maxX = -10000000;\n    int minY = 10000000;\n    int maxY = -10000000;\n    \n    for(unsigned j = 0; j < bb2D.size(); j++)\n    {\n\tminX = std::min((float) minX, bb2D[j].x);\n\tminY = std::min((float) minY, bb2D[j].y);\n\tmaxX = std::max((float) maxX, bb2D[j].x);\n\tmaxY = std::max((float) maxY, bb2D[j].y);\n    }\n    hyp.bb = cv::Rect(0, 0, (maxX - minX + 1), (maxY - minY + 1));\n\n    cv::Point2f c;\n    c.x = center.x;\n    c.y = center.y;\n    if (cv::norm(pt1 - c) > std::max(hyp.bb.width, hyp.bb.height) || cv::norm(pt2 - c) > std::max(hyp.bb.width, hyp.bb.height))\n      continue;\n    \n    #pragma omp critical\n    {\n      hypMap[objID].push_back(hyp);\n    }\n\n    break;\n  }\n\n  // create a list of all objects where hyptheses have been found\n  std::vector<jp::id_t> objList;\n  for(std::pair<jp::id_t, std::vector<TransHyp>> hypPair : hypMap)\n  {\n    objList.push_back(hypPair.first);\n  }\n\n  // create a working queue of all hypotheses to process\n  std::vector<TransHyp*> workingQueue = getWorkingQueue(hypMap, refIt, is_train);\n\t\n  // main preemptive RANSAC loop, it will stop if there is max one hypothesis per object remaining which has been refined a minimal number of times\n  while(!workingQueue.empty())\n  {\n    // draw a batch of pixels and check for inliers, the number of pixels looked at is increased in each iteration\n    #pragma omp parallel for\n    for(int h = 0; h < workingQueue.size(); h++)\n      countInliers2D(*(workingQueue[h]), vertmap, labels, inlierThreshold3D, width, num_classes, preemptiveBatch);\n\t    \t    \n    // sort hypothesis according to inlier count and discard bad half\n    #pragma omp parallel for \n    for(unsigned o = 0; o < objList.size(); o++)\n    {\n      jp::id_t objID = objList[o];\n      if(hypMap[objID].size() > 1)\n      {\n\tstd::sort(hypMap[objID].begin(), hypMap[objID].end());\n\thypMap[objID].erase(hypMap[objID].begin() + hypMap[objID].size() / 2, hypMap[objID].end());\n      }\n    }\n    workingQueue = getWorkingQueue(hypMap, refIt, is_train);\n\t    \n    // refine\n    #pragma omp parallel for\n    for(int h = 0; h < workingQueue.size(); h++)\n    {\n      updateHyp2D(*(workingQueue[h]), maxPixels);\n      workingQueue[h]->refSteps++;\n    }\n    \n    workingQueue = getWorkingQueue(hypMap, refIt, is_train);\n  }\n\n  #pragma omp parallel for\n  for(auto it = hypMap.begin(); it != hypMap.end(); it++)\n  for(int h = 0; h < it->second.size(); h++)\n  {\n    cv::Vec<float, 13> roi;\n    roi(0) = batch;\n    roi(1) = it->second[h].objID;\n\n    // backproject the center\n    cv::Point2d center = it->second[h].center;\n    float rx = (center.x - px) / fx;\n    float ry = (center.y - py) / fy;\n    float distance = it->second[h].compute_distance(vertmap, num_classes, width);\n\n    // initial pose\n    std::vector<double> vec(6);\n    vec[0] = 0.0;\n    vec[1] = 0.0;\n    vec[2] = 0.0;\n    vec[3] = rx * distance;\n    vec[4] = ry * distance;\n    vec[5] = distance;\n\n    // convert pose to our format\n    cv::Mat tvec(3, 1, CV_64F);\n    cv::Mat rvec(3, 1, CV_64F);\n      \n    for(int i = 0; i < 6; i++)\n    {\n      if(i > 2) \n        tvec.at<double>(i-3, 0) = vec[i];\n      else \n        rvec.at<double>(i, 0) = vec[i];\n    }\n\t\n    jp::cv_trans_t trans(rvec, tvec);\n    jp::jp_trans_t pose = jp::cv2our(trans);\n\n    // convert to quarternion\n    cv::Mat pose_t;\n    cv::transpose(pose.first, pose_t);\n    Eigen::Map<Eigen::Matrix3d> eigenT( (double*)pose_t.data );\n    Eigen::Quaterniond quaternion(eigenT);\n\n    compute_width_height(it->second[h], vertmap, labels, inlierThreshold3D, width, num_classes);\n    float scale = 0.05;\n    roi(2) = center.x - it->second[h].width_ * (0.5 + scale);\n    roi(3) = center.y - it->second[h].height_ * (0.5 + scale);\n    roi(4) = center.x + it->second[h].width_ * (0.5 + scale);\n    roi(5) = center.y + it->second[h].height_ * (0.5 + scale);\n\n    roi(6) = quaternion.w();\n    roi(7) = quaternion.x();\n    roi(8) = quaternion.y();\n    roi(9) = quaternion.z();\n    roi(10) = pose.second.x;\n    roi(11) = pose.second.y;\n    roi(12) = pose.second.z;\n\n    /*\n    std::cout << pose.first << std::endl;\n    std::cout << eigenT << std::endl;\n    std::cout << quaternion.w() << \" \" << quaternion.x() << \" \" << quaternion.y() << \" \" << quaternion.z() << std::endl;\n    std::cout << pose.second << std::endl;\n    \n    std::cout << \"Inliers: \" << it->second[h].inliers;\n    std::printf(\" (Rate: %.1f\\%)\\n\", it->second[h].getInlierRate() * 100);\n    std::cout << \"Refined \" << it->second[h].refSteps << \" times. \" << std::endl;\n    std::cout << \"Center \" << center << std::endl;\n    std::cout << \"Width: \" << it->second[h].width_ << \" Height: \" << it->second[h].height_ << std::endl;\n    std::cout << \"---------------------------------------------------\" << std::endl;\n    std::cout << roi << std::endl;\n    */\n\n    outputs.push_back(roi);\n\n    if (is_train)\n    {\n      // add jittering rois\n      float x1 = roi(2);\n      float y1 = roi(3);\n      float x2 = roi(4);\n      float y2 = roi(5);\n      float ww = x2 - x1;\n      float hh = y2 - y1;\n\n      // (-1, -1)\n      roi(2) = x1 - 0.05 * ww;\n      roi(3) = y1 - 0.05 * hh;\n      roi(4) = roi(2) + ww;\n      roi(5) = roi(3) + hh;\n      outputs.push_back(roi);\n\n      // (+1, -1)\n      roi(2) = x1 + 0.05 * ww;\n      roi(3) = y1 - 0.05 * hh;\n      roi(4) = roi(2) + ww;\n      roi(5) = roi(3) + hh;\n      outputs.push_back(roi);\n\n      // (-1, +1)\n      roi(2) = x1 - 0.05 * ww;\n      roi(3) = y1 + 0.05 * hh;\n      roi(4) = roi(2) + ww;\n      roi(5) = roi(3) + hh;\n      outputs.push_back(roi);\n\n      // (+1, +1)\n      roi(2) = x1 + 0.05 * ww;\n      roi(3) = y1 + 0.05 * hh;\n      roi(4) = roi(2) + ww;\n      roi(5) = roi(3) + hh;\n      outputs.push_back(roi);\n\n      // (0, -1)\n      roi(2) = x1;\n      roi(3) = y1 - 0.05 * hh;\n      roi(4) = roi(2) + ww;\n      roi(5) = roi(3) + hh;\n      outputs.push_back(roi);\n\n      // (-1, 0)\n      roi(2) = x1 - 0.05 * ww;\n      roi(3) = y1;\n      roi(4) = roi(2) + ww;\n      roi(5) = roi(3) + hh;\n      outputs.push_back(roi);\n\n      // (0, +1)\n      roi(2) = x1;\n      roi(3) = y1 + 0.05 * hh;\n      roi(4) = roi(2) + ww;\n      roi(5) = roi(3) + hh;\n      outputs.push_back(roi);\n\n      // (+1, 0)\n      roi(2) = x1 + 0.05 * ww;\n      roi(3) = y1;\n      roi(4) = roi(2) + ww;\n      roi(5) = roi(3) + hh;\n      outputs.push_back(roi);\n    }\n  }\n}\n\n\nstatic double optEnergy(const std::vector<double> &pose, std::vector<double> &grad, void *data)\n{\n  DataForOpt* dataForOpt = (DataForOpt*) data;\n\n  cv::Mat tvec(3, 1, CV_64F);\n  cv::Mat rvec(3, 1, CV_64F);\n      \n  for(int i = 0; i < 6; i++)\n  {\n    if(i > 2) \n      tvec.at<double>(i-3, 0) = pose[i];\n    else \n      rvec.at<double>(i, 0) = pose[i];\n  }\n\t\n  jp::cv_trans_t trans(rvec, tvec);\n\n  // project the 3D bounding box according to the current pose\n  cv::Rect bb2D = getBB2D(dataForOpt->imageWidth, dataForOpt->imageHeight, dataForOpt->bb3D, dataForOpt->camMat, trans);\n\n  // compute IoU between boxes\n  float energy = -1 * getIoU(bb2D, dataForOpt->bb2D);\n\n  return energy;\n}\n\n\ndouble poseWithOpt(std::vector<double> & vec, DataForOpt data, int iterations) \n{\n  // set up optimization algorithm (gradient free)\n  nlopt::opt opt(nlopt::LN_NELDERMEAD, 6); \n\n  // set optimization bounds \n  double rotRange = 180;\n  rotRange *= PI / 180;\n  double tRangeXY = 0.01;\n  double tRangeZ = 0.01; // pose uncertainty is larger in Z direction\n\t\n  std::vector<double> lb(6);\n  lb[0] = vec[0]-rotRange; lb[1] = vec[1]-rotRange; lb[2] = vec[2]-rotRange;\n  lb[3] = vec[3]-tRangeXY; lb[4] = vec[4]-tRangeXY; lb[5] = vec[5]-tRangeZ;\n  opt.set_lower_bounds(lb);\n      \n  std::vector<double> ub(6);\n  ub[0] = vec[0]+rotRange; ub[1] = vec[1]+rotRange; ub[2] = vec[2]+rotRange;\n  ub[3] = vec[3]+tRangeXY; ub[4] = vec[4]+tRangeXY; ub[5] = vec[5]+tRangeZ;\n  opt.set_upper_bounds(ub);\n      \n  // configure NLopt\n  opt.set_min_objective(optEnergy, &data);\n  opt.set_maxeval(iterations);\n\n  // run optimization\n  double energy;\n  nlopt::result result = opt.optimize(vec, energy);\n\n  // std::cout << \"IoU after optimization: \" << -energy << std::endl;\n   \n  return energy;\n}\n\n\n// compute the pose target and weight\nvoid compute_target_weight(int height, int width, float* target, float* weight, std::vector<std::vector<cv::Point3f>> bb3Ds, \n  const float* poses_gt, int num_gt, int num_classes, float fx, float fy, float px, float py, std::vector<cv::Vec<float, 13> > outputs)\n{\n  int num = outputs.size();\n  float threshold = 0.2;\n\n  // camera matrix\n  cv::Mat_<float> camMat = cv::Mat_<float>::zeros(3, 3);\n  camMat(0, 0) = fx;\n  camMat(1, 1) = fy;\n  camMat(2, 2) = 1.f;\n  camMat(0, 2) = px;\n  camMat(1, 2) = py;\n\n  // compute the gt boxes\n  std::vector<cv::Rect> bb2Ds_gt(num_gt);\n  for (int i = 0; i < num_gt; i++)\n  {\n    Eigen::Quaternionf quaternion(poses_gt[i * 13 + 6], poses_gt[i * 13 + 7], poses_gt[i * 13 + 8], poses_gt[i * 13 + 9]);\n    Eigen::Matrix3f rmatrix = quaternion.toRotationMatrix();\n    cv::Mat rmat_trans = cv::Mat(3, 3, CV_32F, rmatrix.data());\n    cv::Mat rmat;\n    cv::transpose(rmat_trans, rmat);\n    cv::Point3d tvec(poses_gt[i * 13 + 10], poses_gt[i * 13 + 11], poses_gt[i * 13 + 12]);\n    jp::jp_trans_t pose(rmat, tvec);\n    jp::cv_trans_t trans = jp::our2cv(pose);\n\n    int objID = int(poses_gt[i * 13 + 1]);\n    std::vector<cv::Point3f> bb3D = bb3Ds[objID-1];\n    bb2Ds_gt[i] = getBB2D(width, height, bb3D, camMat, trans);\n  }\n\n  for (int i = 0; i < num; i++)\n  {\n    cv::Vec<float, 13> roi = outputs[i];\n    int batch_id = int(roi(0));\n    int class_id = int(roi(1));\n\n    // find the gt index\n    int gt_ind = -1;\n    for (int j = 0; j < num_gt; j++)\n    {\n      int gt_batch = int(poses_gt[j * 13 + 0]);\n      int gt_id = int(poses_gt[j * 13 + 1]);\n      if(class_id == gt_id && batch_id == gt_batch)\n      {\n        gt_ind = j;\n        break;\n      }\n    }\n\n    if (gt_ind == -1)\n      continue;\n\n    // compute bounding box overlap\n    float x1 = roi(2);\n    float y1 = roi(3);\n    float x2 = roi(4);\n    float y2 = roi(5);\n    cv::Rect bb2D(x1, y1, x2-x1, y2-y1);\n\n    float overlap = getIoU(bb2D, bb2Ds_gt[gt_ind]);\n    if (overlap < threshold)\n      continue;\n\n    target[i * 4 * num_classes + 4 * class_id + 0] = poses_gt[gt_ind * 13 + 6];\n    target[i * 4 * num_classes + 4 * class_id + 1] = poses_gt[gt_ind * 13 + 7];\n    target[i * 4 * num_classes + 4 * class_id + 2] = poses_gt[gt_ind * 13 + 8];\n    target[i * 4 * num_classes + 4 * class_id + 3] = poses_gt[gt_ind * 13 + 9];\n\n    weight[i * 4 * num_classes + 4 * class_id + 0] = 1;\n    weight[i * 4 * num_classes + 4 * class_id + 1] = 1;\n    weight[i * 4 * num_classes + 4 * class_id + 2] = 1;\n    weight[i * 4 * num_classes + 4 * class_id + 3] = 1;\n\n  }\n}\n", "meta": {"hexsha": "3fbf87b5040bf67f2a6acdb1848a5cf7f9035ec5", "size": 32665, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/hough_voting_layer/hough_voting_op.cc", "max_stars_repo_name": "aditya2592/PoseCNN", "max_stars_repo_head_hexsha": "a763120ce0ceb55cf3432980287ef463728f8052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 655.0, "max_stars_repo_stars_event_min_datetime": "2018-03-21T19:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:41:21.000Z", "max_issues_repo_path": "lib/hough_voting_layer/hough_voting_op.cc", "max_issues_repo_name": "SergioRAgostinho/PoseCNN", "max_issues_repo_head_hexsha": "da9eaae850eed7521a2a48a4d27474d655caab42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122.0, "max_issues_repo_issues_event_min_datetime": "2018-04-04T13:57:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T09:28:44.000Z", "max_forks_repo_path": "lib/hough_voting_layer/hough_voting_op.cc", "max_forks_repo_name": "SergioRAgostinho/PoseCNN", "max_forks_repo_head_hexsha": "da9eaae850eed7521a2a48a4d27474d655caab42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 226.0, "max_forks_repo_forks_event_min_datetime": "2018-03-22T01:40:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T11:56:14.000Z", "avg_line_length": 32.665, "max_line_length": 259, "alphanum_fraction": 0.6283177713, "num_tokens": 10122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.1961615844507089}}
{"text": "//\n// Created by Murtuza Husain on 26/03/2018.\n//\n\n#include <iostream>\n#include <goicpzSurfaceUtils.h>\n#include <GlobalRegister.h>\n#include <pcl/io/ply_io.h>\n#include <pcl/point_types.h>\n#include <pcl/registration/icp.h>\n//#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/console/time.h>   // TicToc\n#include <pcl/point_types.h>\n#include <pcl/common/projection_matrix.h>\n#include <SurfaceRegister.h>\n#include <boost/timer.hpp>\n\nusing namespace goicpz;\n\n\n\nint main (int argc, char** argv) {\n    boost::timer timer;\n    int sampleSize = 600;\n\n    GlobalRegister rigid(1, 0.0001);\n    rigid.loadMoving(\"/Users/murtuza/dev/Matlab/data/IPCAI2018Data/reform/InitialCT_top.ply\",\n                     \"/Users/murtuza/dev/Matlab/data/IPCAI2018Data/reform/InitialCT_top.ply\",\n                     \"/Users/murtuza/dev/Matlab/data/IPCAI2018Data/reform/InitialCT_boundary.ply\");\n    rigid.preProcessMoving(sampleSize);\n    std::cout << timer.elapsed() << std::endl;\n    timer.restart();\n\n    rigid.loadTarget(\"/Users/murtuza/dev/Matlab/data/IPCAI2018Data/reform/PartialDeformed4.ply\",\n                     \"/Users/murtuza/dev/Matlab/data/IPCAI2018Data/reform/PartialDeformed4_boundary.ply\");\n    rigid.processTarget(sampleSize);\n    std::cout <<  timer.elapsed() << std::endl;\n    timer.restart();\n\n    rigid.buildCorrespondeces();\n    std::cout <<  timer.elapsed() << std::endl;\n    timer.restart();\n\n    Eigen::MatrixXf W = rigid.buildAffinityMatrix(0.3);\n    std::cout <<  timer.elapsed() << std::endl;\n    timer.restart();\n\n    pcl::IndicesPtr moving_correspondence(new std::vector<int>);\n    pcl::IndicesPtr target_correspondence(new std::vector<int>);\n\n    rigid.prune_correspondence(W, 0.4, moving_correspondence, target_correspondence);\n    std::cout << \"Prune \" <<  timer.elapsed() << std::endl;\n    timer.restart();\n\n    std::cout << rigid.moving_features_idx->size() << std::endl;\n\n    int x = 9;\n\n    /*PointCloudT::Ptr res = rigid.transform(moving_correspondence, target_correspondence);\n    std::cout << \"Transform \" <<  timer.elapsed() << std::endl;\n    timer.restart();*/\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "1f9db8019202de8a57e4306511c6a3fafc8a3d32", "size": 2105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/CommandLineApps/goicpzGlobalRigidRegTest.cpp", "max_stars_repo_name": "clicky/go-icpz", "max_stars_repo_head_hexsha": "11b595778210cbfde3135f98c7ddfeb8808f9a1c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T08:35:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T07:37:08.000Z", "max_issues_repo_path": "Code/CommandLineApps/goicpzGlobalRigidRegTest.cpp", "max_issues_repo_name": "clicky/go-icpz", "max_issues_repo_head_hexsha": "11b595778210cbfde3135f98c7ddfeb8808f9a1c", "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/goicpzGlobalRigidRegTest.cpp", "max_forks_repo_name": "clicky/go-icpz", "max_forks_repo_head_hexsha": "11b595778210cbfde3135f98c7ddfeb8808f9a1c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-03T16:21:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T16:21:06.000Z", "avg_line_length": 31.4179104478, "max_line_length": 106, "alphanum_fraction": 0.6817102138, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.32082130082460697, "lm_q1q2_score": 0.1961443599729447}}
{"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_SWAR_FUNCTIONS_GENERIC_SPLIT_MULTIPLIES_HPP_INCLUDED\n#define BOOST_SIMD_SWAR_FUNCTIONS_GENERIC_SPLIT_MULTIPLIES_HPP_INCLUDED\n\n#include <boost/simd/swar/functions/split_multiplies.hpp>\n#include <boost/simd/sdk/meta/is_upgradable.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <boost/mpl/not.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT_IF         ( split_multiplies_\n                                      , tag::cpu_\n                                      , (A0)(A1)\n                                      , (simd::meta::is_upgradable_to<A0,A1>)\n                                      , ((generic_< arithmetic_<A0> >))\n                                        ((generic_< arithmetic_<A0> >))\n                                        ((generic_< arithmetic_<A1> >))\n                                      )\n  {\n    typedef A1 result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A0 const& a1, A1 & a3) const\n    {\n      result_type a2;\n      boost::simd::split_multiplies(a0, a1, a2, a3);\n      return a2;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT_IF         ( split_multiplies_, tag::cpu_\n                                      , (A0)\n                                      , ( simd::meta::is_upgradable<A0> )\n                                      , (generic_< arithmetic_<A0> >)\n                                        (generic_< arithmetic_<A0> >)\n                                      )\n  {\n    typedef typename dispatch::meta::upgrade<A0>::type part;\n    typedef std::pair<part,part>                       result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A0 const& a1) const\n    {\n      part first, second;\n      boost::simd::split_multiplies( a0, a1, first, second );\n      return result_type(first, second);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "1fd04488d77d19d041bc0b154a6228295531cdfb", "size": 2344, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/swar/functions/generic/split_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/boost/simd/base/include/boost/simd/swar/functions/generic/split_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/boost/simd/base/include/boost/simd/swar/functions/generic/split_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": 41.1228070175, "max_line_length": 87, "alphanum_fraction": 0.491894198, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1961404329619086}}
{"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// Copyright (c) 2014-2015 Samuel Debionne, Grenoble, France.\n\n// This file was modified by Oracle on 2015-2020.\n// Modifications copyright (c) 2015-2020, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\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_GEOMETRY_ALGORITHMS_DETAIL_EXPAND_SEGMENT_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_EXPAND_SEGMENT_HPP\n\n\n#include <boost/core/ignore_unused.hpp>\n\n#include <boost/geometry/algorithms/dispatch/expand.hpp>\n\n#include <boost/geometry/core/tags.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate\n<\n    typename Box, typename Segment\n>\nstruct expand\n    <\n        Box, Segment,\n        box_tag, segment_tag\n    >\n{\n    template <typename Strategy>\n    static inline void apply(Box& box,\n                             Segment const& segment,\n                             Strategy const& strategy)\n    {\n        strategy.expand(box, segment).apply(box, segment);\n    }\n};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_EXPAND_SEGMENT_HPP\n", "meta": {"hexsha": "c09c664e229e33dd151e2d5d40ab680d239d6ddb", "size": 1692, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/expand/segment.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/expand/segment.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/expand/segment.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": 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": 26.4375, "max_line_length": 77, "alphanum_fraction": 0.7263593381, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.19614043098323866}}
{"text": "/*\n==============================================================================\nKratosIncompressibleFluidApplication \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\npooyan@cimne.upc.edu \nrrossi@cimne.upc.edu\n- CIMNE (International Center for Numerical Methods in Engineering),\nGran Capita' s/n, 08034 Barcelona, Spain\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//   Project Name:        Kratos       \n//   Last modified by:    $Author: kazem $\n//   Date:                $Date: 2008-12-15 10:10:27 $\n//   Revision:            $Revision: 1.8 $\n//\n//\n\n\n// System includes \n\n\n// External includes \n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <boost/timer.hpp> \n\n\n// Project includes\n#include \"includes/define.h\"\n#include \"custom_python/add_custom_strategies_to_python.h\"\n\n#include \"spaces/ublas_space.h\"\n\n//strategies\n#include \"solving_strategies/strategies/solving_strategy.h\"\n#include \"solving_strategies/strategies/residualbased_linear_strategy.h\"\n\n\n\n//convergence criterias\n#include \"custom_strategies/strategies/residualbased_fluid_strategy.h\"\n#include \"custom_strategies/strategies/residualbased_ND_fluid_strategy.h\"\n#include \"custom_strategies/strategies/residualbased_fluid_strategy_coupled.h\"\n#include \"custom_strategies/strategies/residualbased_lagrangian_monolithic_scheme.h\"\n#include \"custom_strategies/strategies/newton_raphson_oss_strategy.h\"\n#include \"custom_strategies/convergencecriterias/UP_criteria.h\"\n//linear solvers\n#include \"linear_solvers/linear_solver.h\"\n\n\n\nnamespace Kratos\n{\n\n\tnamespace Python\n\t{\t\t\n\t\tusing namespace boost::python;\n\n\t\tvoid  AddCustomStrategiesToPython()\n\t\t{\n\t\t\ttypedef UblasSpace<double, CompressedMatrix, Vector> SparseSpaceType;\n\t\t\ttypedef UblasSpace<double, Matrix, Vector> LocalSpaceType;\n\n\t\t\ttypedef LinearSolver<SparseSpaceType, LocalSpaceType > LinearSolverType;\n\t\t\ttypedef SolvingStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType > BaseSolvingStrategyType;\n\t\t\ttypedef Scheme< SparseSpaceType, LocalSpaceType > BaseSchemeType;\n\t\t\ttypedef ConvergenceCriteria< SparseSpaceType, LocalSpaceType > TConvergenceCriteriaType;\n\t\t\t//********************************************************************\n\t\t\t//********************************************************************\n\t\t\t//\n\n\t\t\tclass_< ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >,\t\n\t\t\t\t\tbases< BaseSolvingStrategyType >,  boost::noncopyable >\n\t\t\t\t(\"ResidualBasedFluidStrategy\", \n\t\t\t\tinit<ModelPart&, LinearSolverType::Pointer, LinearSolverType::Pointer,\n\t\t\t\tbool, bool, bool,\n\t\t\t\tdouble, double,\n\t\t\t\tint, int,\n\t\t\t\tunsigned int, unsigned int, unsigned int,\n\t\t\t\tbool\n\t\t\t\t>() )\n\t\t\t\t  .def(\"SolveStep1\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep1)\n\t\t\t\t  .def(\"SolveStep2\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep2)\n\t\t\t\t  .def(\"SolveStep2_Mp\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep2_Mp)\n\t\t\t\t  .def(\"SolveStep3\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep3)\n\t\t\t\t  .def(\"SolveStep4\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep4)\n\t\t\t\t  .def(\"ActOnLonelyNodes\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::ActOnLonelyNodes)\n\t\t\t\t  .def(\"Clear\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::Clear)\n\t\t\t\t  .def(\"FractionalVelocityIteration\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::FractionalVelocityIteration)\n\t\t\t\t  .def(\"ConvergenceCheck\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::ConvergenceCheck)\n\t\t\t\t  .def(\"InitializeFractionalStep\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::InitializeFractionalStep)\n\t\t\t\t  .def(\"PredictVelocity\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::PredictVelocity)\n\t\t\t\t  .def(\"InitializeProjections\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::InitializeProjections)\n\t\t\t\t  .def(\"AssignInitialStepValues\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::AssignInitialStepValues)\n\t\t\t\t  .def(\"IterativeSolve\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::IterativeSolve)\n\t\t\t\t  .def(\"SavePressureIteration\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SavePressureIteration)\n\t\t\t\t  .def(\"ApplyFractionalVelocityFixity\",&ResidualBasedFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::ApplyFractionalVelocityFixity)\t\t\t\t;\n\n\t\t\tclass_< ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >,\t\n\t\t\t\t\tbases< BaseSolvingStrategyType >,  boost::noncopyable >\n\t\t\t\t(\"ResidualBasedNDFluidStrategy\", \n\t\t\t\tinit<ModelPart&, LinearSolverType::Pointer, LinearSolverType::Pointer,\n\t\t\t\tbool, bool, bool,\n\t\t\t\tdouble, double,\n\t\t\t\tint, int,\n\t\t\t\tunsigned int, unsigned int, unsigned int,\n\t\t\t\tbool\n\t\t\t\t>() )\n\t\t\t\t  .def(\"SolveStep1\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep1)\n\t\t\t\t  .def(\"SolveStep2\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep2)\n\t\t\t\t  .def(\"SolveStep3\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep3)\n\t\t\t\t  .def(\"SolveStep4\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep4)\n\t\t\t\t  .def(\"ActOnLonelyNodes\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::ActOnLonelyNodes)\n\t\t\t\t  .def(\"Clear\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::Clear)\n\t\t\t\t  .def(\"FractionalVelocityIteration\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::FractionalVelocityIteration)\n\t\t\t\t  .def(\"ConvergenceCheck\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::ConvergenceCheck)\n\t\t\t\t  .def(\"InitializeFractionalStep\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::InitializeFractionalStep)\n\t\t\t\t  .def(\"PredictVelocity\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::PredictVelocity)\n\t\t\t\t  .def(\"InitializeProjections\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::InitializeProjections)\n\t\t\t\t  .def(\"AssignInitialStepValues\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::AssignInitialStepValues)\n\t\t\t\t  .def(\"IterativeSolve\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::IterativeSolve)\n\t\t\t\t  .def(\"SavePressureIteration\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::SavePressureIteration)\n\t\t\t\t  .def(\"ApplyFractionalVelocityFixity\",&ResidualBasedNDFluidStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::ApplyFractionalVelocityFixity)\t\t\t\t;\t\n\n\n\t\t\tclass_< ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >,\t\n\t\t\t\t\tbases< BaseSolvingStrategyType >,  boost::noncopyable >\n\t\t\t\t(\"ResidualBasedFluidStrategyCoupled\", \n\t\t\t\tinit<ModelPart&, LinearSolverType::Pointer, LinearSolverType::Pointer,\n\t\t\t\tbool, bool, bool,\n\t\t\t\tdouble, double,\n\t\t\t\tint, int,\n\t\t\t\tunsigned int, unsigned int, unsigned int,\n\t\t\t\tbool\n\t\t\t\t>() )\n\t\t\t\t  .def(\"SolveStep1\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep1)\n\t\t\t\t  .def(\"SolveStep2\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep2)\n\t\t\t\t  .def(\"SolveStep2_Mp\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep2_Mp)\n\t\t\t\t  .def(\"SolveStep3\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep3)\n\t\t\t\t  .def(\"SolveStep4\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::SolveStep4)\n\t\t\t\t  .def(\"ActOnLonelyNodes\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::ActOnLonelyNodes)\n\t\t\t\t  .def(\"Clear\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::Clear)\n\t\t\t\t  .def(\"FractionalVelocityIteration\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::FractionalVelocityIteration)\n\t\t\t\t  .def(\"ConvergenceCheck\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::ConvergenceCheck)\n\t\t\t\t  .def(\"InitializeFractionalStep\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::InitializeFractionalStep)\n\t\t\t\t  .def(\"PredictVelocity\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::PredictVelocity)\n\t\t\t\t  .def(\"InitializeProjections\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::InitializeProjections)\n\t\t\t\t  .def(\"AssignInitialStepValues\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::AssignInitialStepValues)\n\t\t\t\t  .def(\"IterativeSolve\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::IterativeSolve)\n\t\t\t\t  .def(\"SavePressureIteration\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::SavePressureIteration)\n\t\t\t\t  .def(\"ApplyFractionalVelocityFixity\",&ResidualBasedFluidStrategyCoupled< SparseSpaceType, LocalSpaceType, LinearSolverType >::ApplyFractionalVelocityFixity)\t\t\t\t;\t\n\n\n\t\t\t\tclass_< ConvergenceCriteria< SparseSpaceType, LocalSpaceType >, boost::noncopyable >(\"ConvergenceCriteria\", init<>() )\n\t\t\t\t.def(\"SetActualizeRHSFlag\", &ConvergenceCriteria<SparseSpaceType, LocalSpaceType >::SetActualizeRHSFlag )\n\t\t\t .def(\"GetActualizeRHSflag\", &ConvergenceCriteria<SparseSpaceType, LocalSpaceType >::GetActualizeRHSflag )\n\t\t\t .def(\"PreCriteria\", &ConvergenceCriteria<SparseSpaceType, LocalSpaceType >::PreCriteria )\n\t\t\t .def(\"PostCriteria\", &ConvergenceCriteria<SparseSpaceType, LocalSpaceType >::PostCriteria )\n\t\t\t .def(\"Initialize\", &ConvergenceCriteria<SparseSpaceType, LocalSpaceType >::Initialize )\n\t\t\t .def(\"InitializeSolutionStep\", &ConvergenceCriteria<SparseSpaceType, LocalSpaceType >::InitializeSolutionStep )\n\t\t\t .def(\"FinalizeSolutionStep\", &ConvergenceCriteria<SparseSpaceType, LocalSpaceType >::FinalizeSolutionStep )\n\t\t\t ;                  \n\t\t\t\n\t\t\tclass_< UPCriteria<SparseSpaceType, LocalSpaceType >,\n\t\t\t         bases<ConvergenceCriteria< SparseSpaceType, LocalSpaceType > >,  \n\t\t\t         boost::noncopyable >\n\t\t\t        (\"UPCriteria\", init< double, double, double, double>() );\n\n\n        \t\t   class_< ResidualBasedLagrangianMonolithicScheme<SparseSpaceType,LocalSpaceType>,\n        \t\t\t   bases< ResidualBasedIncrementalUpdateStaticScheme<SparseSpaceType,LocalSpaceType> >,  boost::noncopyable >\n             \t\t\t      (\n               \t\t\t\t     \"ResidualBasedLagrangianMonolithicScheme\", init< int >()\n                \t\t       );\n\n\t\t\tclass_< NewtonRaphsonOssStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >,bases< BaseSolvingStrategyType >,  boost::noncopyable >\n\t\t\t\t(\"NewtonRaphsonOssStrategy\", \n\t\t\t\tinit<ModelPart&, BaseSchemeType::Pointer, LinearSolverType::Pointer, TConvergenceCriteriaType::Pointer, int, bool, bool, bool\n\t\t\t\t>() )\n\t\t\t\t;\n\n\n\n\n\n\t\t}\n\n\t}  // namespace Python.\n\n} // Namespace Kratos\n\n", "meta": {"hexsha": "c6b9e261c6962a0e2800a7de1b1563fc7c11523d", "size": 13031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/incompressible_fluid_application/custom_python/add_custom_strategies_to_python.cpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": "applications/incompressible_fluid_application/custom_python/add_custom_strategies_to_python.cpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": "applications/incompressible_fluid_application/custom_python/add_custom_strategies_to_python.cpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": 58.1741071429, "max_line_length": 168, "alphanum_fraction": 0.7644079503, "num_tokens": 3143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1961404273446898}}
{"text": "/* Copyright (C) 2014 InfiniDB, Inc.\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; version 2 of\n   the License.\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., 51 Franklin Street, Fifth Floor, Boston,\n   MA 02110-1301, USA. */\n\n/*****************************************************************************\n * $Id$\n *\n ****************************************************************************/\n\n#define BRMAUTOINCMGR_DLLEXPORT\n#include \"autoincrementmanager.h\"\n#undef BRMAUTOINCMGR_DLLEXPORT\n\n#include <math.h>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::posix_time;\n\nnamespace BRM\n{\n\nAutoincrementManager::AutoincrementManager()\n{\n}\n\nAutoincrementManager::~AutoincrementManager()\n{\n}\n\nvoid AutoincrementManager::startSequence(uint32_t oid, uint64_t firstNum, uint32_t colWidth,\n        execplan::CalpontSystemCatalog::ColDataType colDataType)\n{\n    boost::mutex::scoped_lock lk(lock);\n    map<uint64_t, sequence>::iterator it;\n    sequence s;\n\n    it = sequences.find(oid);\n\n    if (it != sequences.end())\n        return;\n\n    s.value = firstNum;\n\n    if (isUnsigned(colDataType))\n    {\n        s.overflow = (0xFFFFFFFFFFFFFFFFULL >> (64 - colWidth * 8)) - 1;\n    }\n    else\n    {\n        s.overflow = (1ULL << (colWidth * 8 - 1));\n    }\n\n    sequences[oid] = s;\n}\n\nbool AutoincrementManager::getAIRange(uint32_t oid, uint64_t count, uint64_t* firstNum)\n{\n    boost::mutex::scoped_lock lk(lock);\n    map<uint64_t, sequence>::iterator it;\n\n    it = sequences.find(oid);\n\n    if (it == sequences.end())\n        throw runtime_error(\"There is no sequence with that lock\");\n\n    if ((count >= it->second.overflow ||\n            count + it->second.value > it->second.overflow ||\n            count + it->second.value <= it->second.value)\n            && count != 0)\n        return false;\n\n    *firstNum = it->second.value;\n    it->second.value += count;\n    return true;\n}\n\nvoid AutoincrementManager::resetSequence(uint32_t oid, uint64_t value)\n{\n    boost::mutex::scoped_lock lk(lock);\n    map<uint64_t, sequence>::iterator it;\n\n    it = sequences.find(oid);\n\n    if (it == sequences.end())\n        return;\n\n    it->second.value = value;\n}\n\nconst uint32_t AutoincrementManager::lockTime = 30;\n\nvoid AutoincrementManager::getLock(uint32_t oid)\n{\n    boost::mutex::scoped_lock lk(lock);\n    map<uint64_t, sequence>::iterator it;\n    ptime stealTime = microsec_clock::local_time() + seconds(lockTime);\n\n    bool gotIt = false;\n\n    it = sequences.find(oid);\n\n    if (it == sequences.end())\n        throw runtime_error(\"There is no sequence with that lock\");\n\n    lk.unlock();\n\n    while (!gotIt && microsec_clock::local_time() < stealTime)\n    {\n        gotIt = it->second.lock.try_lock();\n\n        if (!gotIt)\n            usleep(100000);\n    }\n\n    // If !gotIt, take possession\n}\n\nvoid AutoincrementManager::releaseLock(uint32_t oid)\n{\n    boost::mutex::scoped_lock lk(lock);\n    map<uint64_t, sequence>::iterator it;\n\n    it = sequences.find(oid);\n\n    if (it == sequences.end())\n        return;   // it's unlocked if the lock doesn't exist...\n\n    lk.unlock();\n\n    it->second.lock.unlock();\n}\n\nvoid AutoincrementManager::deleteSequence(uint32_t oid)\n{\n    boost::mutex::scoped_lock lk(lock);\n    map<uint64_t, sequence>::iterator it;\n\n    it = sequences.find(oid);\n\n    if (it != sequences.end())\n        sequences.erase(it);\n}\n\n\n} /* namespace BRM */\n", "meta": {"hexsha": "9decda641a5d1f246308bc84b41cbcb880a26e9c", "size": 3913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/versioning/BRM/autoincrementmanager.cpp", "max_stars_repo_name": "zettadb/zettalib", "max_stars_repo_head_hexsha": "3d5f96dc9e3e4aa255f4e6105489758944d37cc4", "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/vendor/mariadb-10.6.7/storage/columnstore/columnstore/versioning/BRM/autoincrementmanager.cpp", "max_issues_repo_name": "zettadb/zettalib", "max_issues_repo_head_hexsha": "3d5f96dc9e3e4aa255f4e6105489758944d37cc4", "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/vendor/mariadb-10.6.7/storage/columnstore/columnstore/versioning/BRM/autoincrementmanager.cpp", "max_forks_repo_name": "zettadb/zettalib", "max_forks_repo_head_hexsha": "3d5f96dc9e3e4aa255f4e6105489758944d37cc4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-27T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:24:22.000Z", "avg_line_length": 24.3043478261, "max_line_length": 92, "alphanum_fraction": 0.6383848709, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1961404273446898}}
{"text": "/*\n\nCopyright (c) 2005-2017, 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 CRYPTPROJECTIONFORCE_HPP_\n#define CRYPTPROJECTIONFORCE_HPP_\n\n#include \"GeneralisedLinearSpringForce.hpp\"\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n/**\n * A force law for use in crypt projection simulations.\n */\nclass CryptProjectionForce : public GeneralisedLinearSpringForce<2>\n{\n    friend class TestCryptProjectionForce;\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<GeneralisedLinearSpringForce<2> >(*this);\n        archive & mA;\n        archive & mB;\n        archive & mIncludeWntChemotaxis;\n        archive & mWntChemotaxisStrength;\n    }\n\n    /**\n     * The value of the constant a in the definition of the crypt surface\n     *      z = f(r) = a*r^b.\n     */\n    double mA;\n\n    /**\n     * The value of the constant b in the definition of the crypt surface\n     *      z = f(r) = a*r^b.\n     */\n    double mB;\n\n    /**\n     * Whether to include Wnt-dependent chemotaxis for stem cells.\n     */\n    bool mIncludeWntChemotaxis;\n\n    /**\n     * Strength of Wnt-based chemotactic force.\n     */\n    double mWntChemotaxisStrength;\n\n    /**\n     * Map node indices to 3D locations on the crypt surface.\n     */\n    std::map<unsigned, c_vector<double, 3> > mNode3dLocationMap;\n\n    /**\n     * Fix up the mappings between node indices and 3D locations.\n     *\n     * @param rCellPopulation the cell population\n     */\n    void UpdateNode3dLocationMap(AbstractCellPopulation<2>& rCellPopulation);\n\n    /**\n     * Calculates the force between two nodes.\n     *\n     * Note that this assumes they are connected and is called by rCalculateVelocitiesOfEachNode()\n     *\n     * @param nodeAGlobalIndex the index of the first node\n     * @param nodeBGlobalIndex the index of the second node\n     * @param rCellPopulation the cell population\n     *\n     * @return The force exerted on Node A by Node B.\n     */\n    c_vector<double,2> CalculateForceBetweenNodes(unsigned nodeAGlobalIndex, unsigned nodeBGlobalIndex, AbstractCellPopulation<2>& rCellPopulation);\n\npublic:\n\n    /**\n     * Constructor.\n     */\n    CryptProjectionForce();\n\n    /**\n     * Destructor.\n     */\n    ~CryptProjectionForce();\n\n    /**\n     * @return mA.\n     */\n    double GetA() const;\n\n    /**\n     * @return mB.\n     */\n    double GetB() const;\n\n    /**\n     * @return mWntChemotaxisStrength\n     */\n    double GetWntChemotaxisStrength();\n\n    /**\n     * Set mWntChemotaxisStrength.\n     *\n     * @param wntChemotaxisStrength the new value of mWntChemotaxisStrength\n     */\n    void SetWntChemotaxisStrength(double wntChemotaxisStrength);\n\n    /**\n     * Set mIncludeWntChemotaxis.\n     *\n     * @param includeWntChemotaxis whether to include Wnt-dependent chemotaxis\n     */\n    void SetWntChemotaxis(bool includeWntChemotaxis);\n\n    /**\n     * Calculates the height of the crypt surface given by\n     *     z = f(r) = a*r^b\n     * at a point whose 2D position is a distance r from the centre of the cell population.\n     * This assumes that the cell population is centred at the origin.\n     *\n     * @param rNodeLocation\n     * @return the z component corresponding to rNodeLocation\n     */\n    double CalculateCryptSurfaceHeightAtPoint(const c_vector<double,2>& rNodeLocation);\n\n    /**\n     * Calculates the derivative df/dr of the crypt surface function z=f(r) at a point\n     * whose 2D position is a distance r from the centre of the cell_population, which we assume\n     * to be at (0,0).\n     *\n     * @param rNodeLocation the 2D location of a node\n     * @return the gradient\n     */\n    double CalculateCryptSurfaceDerivativeAtPoint(const c_vector<double,2>& rNodeLocation);\n\n    /**\n     * Overridden AddForceContribution method.\n     *\n     * @param rCellPopulation reference to the cell population\n     */\n    void AddForceContribution(AbstractCellPopulation<2>& rCellPopulation);\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// Declare identifier for the serializer\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(CryptProjectionForce)\n\n#endif /*CRYPTPROJECTIONFORCE_HPP_*/\n", "meta": {"hexsha": "8b2d0681af51d3b9c7b8ea6a14426a9e51a92997", "size": 6311, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "crypt/src/forces/CryptProjectionForce.hpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": "crypt/src/forces/CryptProjectionForce.hpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": "crypt/src/forces/CryptProjectionForce.hpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": 31.555, "max_line_length": 148, "alphanum_fraction": 0.7065441293, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19614042172747104}}
{"text": "/**\n * @file\n *\n *   Unless noted otherwise, the portions of Isis written by the USGS are public\n *   domain. See individual third-party library and package descriptions for \n *   intellectual property information,user agreements, and related information.\n *\n *   Although Isis has been used by the USGS, no warranty, expressed or implied,\n *   is made by the USGS as to the accuracy and functioning of such software \n *   and related material nor shall the fact of distribution constitute any such \n *   warranty, and no responsibility is assumed by the USGS in connection \n *   therewith.\n *\n *   For additional information, launch\n *   $ISISROOT/doc//documents/Disclaimers/Disclaimers.html in a browser or see \n *   the Privacy &amp; Disclaimers page on the Isis website,\n *   http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on\n *   http://www.usgs.gov/privacy.html.\n */\n#include <cmath>\n#include <iostream>\n\n#include <boost/math/special_functions/legendre.hpp>\n\n#include \"Camera.h\"\n#include \"Constants.h\"\n#include \"FunctionTools.h\"\n#include \"IString.h\"\n#include \"NewHorizonsMvicFrameCameraDistortionMap.h\"\n\n#include \"CameraFocalPlaneMap.h\"\n\n\n#include <QDebug>\n\n\nusing namespace boost::math;\nusing namespace std;\nusing namespace Isis;\n\nnamespace Isis {\n  /** Camera distortion map constructor\n   *\n   * This class maps between distorted and undistorted focal plane x/y's. The default mapping is the\n   * identity, that is, the focal plane x/y and undistorted focal plane x/y will be identical.\n   *\n   * @param parent              the parent camera that will use this distortion map\n   * @param zDirection          the direction of the focal plane Z-axis\n   *                            (either 1 or -1)\n   *\n   * @param xDistortionCoeffs   distortion coefficients in x\n   * @param yDistortionCoeffs   distortion coefficients in y\n   */\n  NewHorizonsMvicFrameCameraDistortionMap::NewHorizonsMvicFrameCameraDistortionMap(Camera *parent,\n                                                             vector<double> xDistortionCoeffs,\n                                                             vector<double> yDistortionCoeffs) :\n    CameraDistortionMap(parent, 1.0) {\n\n    m_xDistortionCoeffs = xDistortionCoeffs;\n    m_yDistortionCoeffs = yDistortionCoeffs;\n\n    double pixelPitch = p_camera->PixelPitch();\n\n    m_focalPlaneHalf_x = 0.5 * p_camera->Samples() * pixelPitch; // 32.5 mm\n    m_focalPlaneHalf_y = 0.5 * p_camera->Lines() * pixelPitch;   // 0.832 mm\n  }\n\n\n  /** Destructor\n   */\n  NewHorizonsMvicFrameCameraDistortionMap::~NewHorizonsMvicFrameCameraDistortionMap() {\n  }\n\n\n//  /**\n//   * Testing method to output corrections in x and y at pixel centers for entire focal plane.\n//   * Output in csv format for viewing/plotting in Excel.\n//   */\n//bool NewHorizonsMvicFrameCameraDistortionMap::outputDeltas() {\n//\n//  QString ofname(\"mvic_frame_deltas.csv\");\n//  std::ofstream fp_out(ofname.toLatin1().data(), std::ios::out);\n//  if (!fp_out)\n//    return false;\n//\n//  char buf[1056];\n//\n//  double deltax, deltay;\n//\n//  for (double line = 0.5; line <= 128.5; line += 1.0) {    // loop in y direction\n//    for (double sample=0.5; sample <= 5000.5; sample += 1.0) {      // loop in x direction\n//\n//      p_camera->FocalPlaneMap()->SetDetector(sample,line);\n//\n//      double fplanex = p_camera->FocalPlaneMap()->FocalPlaneX();\n//      double fplaney = p_camera->FocalPlaneMap()->FocalPlaneY();\n//\n//      SetFocalPlane(fplanex,fplaney);\n//\n//      deltax = fplanex - p_undistortedFocalPlaneX;\n//      deltay = fplaney - p_undistortedFocalPlaneY;\n//\n//      sprintf(buf, \"%lf,%lf,%lf,%lf\\n\", sample, deltax/0.013, line, deltay/0.013);\n//\n//      fp_out << buf;\n//    }\n//  }\n//\n//  fp_out.close();\n//\n//  return true;\n//}\n\n\n  /** Compute undistorted focal plane x/y\n   *\n   * Compute undistorted focal plane x/y given a distorted focal plane x/y.\n   *\n   * @param dx distorted focal plane x in millimeters\n   * @param dy distorted focal plane y in millimeters\n   *\n   * @return if the conversion was successful\n   * @see SetDistortion\n   */\n  bool NewHorizonsMvicFrameCameraDistortionMap::SetFocalPlane(const double dx, const double dy) {\n\n    p_focalPlaneX = dx;\n    p_focalPlaneY = dy;\n\n    // in case of failures, initialize undistorted focal plane coordinates to the distorted\n    // coordinate values\n    p_undistortedFocalPlaneX = dx;\n    p_undistortedFocalPlaneY = dy;\n\n    // if x and/or y lie outside of the detector, do NOT apply distortion\n    // set undistorted focal plane values to be identical to raw values\n    if ((fabs(dx) > m_focalPlaneHalf_x) || (fabs(dy) > m_focalPlaneHalf_y)) {\n      return true;\n    }\n\n    // shift from ISIS MVIC FT image coordinate system with +x to the left and +y down to\n    // the desired system of +x to the right and +y up\n    // e.g. negate x and y\n\n    // scale x and y to lie in the range -1.0 to +1.0\n    // this is requirement for Legendre Polynomials, man\n    double xscaled = -dx/m_focalPlaneHalf_x;\n    double yscaled = -dy/m_focalPlaneHalf_y;\n\n    // compute distortion corrections in x and y using Legendre Polynomials\n    // these corrections are also in the -1.0 to +1.0 range\n    // if Legendre computations fail, we set undistorted focal plane x and y\n    // to be identical to distorted x and y and return true\n    double deltax, deltay;\n    if (!computeDistortionCorrections(xscaled, yscaled, deltax, deltay)) {\n      return true;\n    }\n\n    // apply the corrections to original x,y\n    xscaled += deltax;\n    yscaled += deltay;\n\n    // scale back from range of '-1.0 to +1.0' to the detector, '-32.5 to 32.5 mm'\n    p_undistortedFocalPlaneX = -xscaled * m_focalPlaneHalf_x;\n    p_undistortedFocalPlaneY = -yscaled * m_focalPlaneHalf_y;\n\n    return true;\n  }\n\n\n//  bool NewHorizonsMvicFrameCameraDistortionMap::SetFocalPlane(const double dx, const double dy) {\n\n//    p_focalPlaneX = dx;\n//    p_focalPlaneY = dy;\n\n//    // if x and/or y lie outside of the detector, do NOT apply distortion\n//    // set undistorted focal plane values to be identical to raw values\n//    if ((fabs(dx) > m_focalPlaneHalf_x) || (fabs(dy) > m_focalPlaneHalf_y)) {\n//      p_undistortedFocalPlaneX = dx;\n//      p_undistortedFocalPlaneY = dy;\n\n//      return true;\n//    }\n\n//    // scale x and y to lie in the range -1.0 to +1.0\n//    // this is requirement for Legendre Polynomials, man\n//    double xscaled = dx/m_focalPlaneHalf_x;\n//    double yscaled = dy/m_focalPlaneHalf_y;\n\n//    // compute distortion corrections in x and y using Legendre Polynomials\n//    // these corrections are also in the -1.0 to +1.0 range\n//    double deltax, deltay;\n//    computeDistortionCorrections(xscaled, yscaled, deltax, deltay);\n\n//    // apply the corrections\n//    xscaled += deltax;\n//    yscaled += deltay;\n\n//    // scale back from range of '-1.0 to +1.0' to the detector, '-32.656 to 32.656 mm'\n//    p_undistortedFocalPlaneX = xscaled * m_focalPlaneHalf_x;\n//    p_undistortedFocalPlaneY = yscaled * m_focalPlaneHalf_y;\n\n//    return true;\n//  }\n\n\n  /** Compute distorted focal plane x/y\n   *\n   * Compute distorted focal plane x/y given an undistorted focal plane x/y.\n   *\n   * This is an iterative procedure.\n   *\n   * @param ux undistorted focal plane x in millimeters\n   * @param uy undistorted focal plane y in millimeters\n   *\n   * @return if the conversion was successful\n   * @see SetDistortion\n   */\n  bool NewHorizonsMvicFrameCameraDistortionMap::SetUndistortedFocalPlane(const double ux, const double uy) {\n\n    // image coordinates prior to introducing distortion\n    p_undistortedFocalPlaneX = ux;\n    p_undistortedFocalPlaneY = uy;\n\n    double xScaledDistortion, yScaledDistortion;\n\n    // scale undistorted coordinates to range of -1.0 to +1.0\n    double xtScaled = -ux/m_focalPlaneHalf_x;\n    double ytScaled = -uy/m_focalPlaneHalf_y;\n\n    double uxScaled = xtScaled;\n    double uyScaled = ytScaled;\n\n    double xScaledPrevious = 1000000.0;\n    double yScaledPrevious = 1000000.0;\n\n    double tolerance = 0.000001;\n\n    bool bConverged = false;\n\n    // iterating to introduce distortion...\n    // we stop when the difference between distorted coordinates\n    // in successive iterations is at or below the given tolerance\n    for( int i = 0; i < 50; i++ ) {\n\n      // compute distortion in x and y (scaled to -1.0 - +1.0) using Legendre Polynomials\n      computeDistortionCorrections(xtScaled, ytScaled, xScaledDistortion, yScaledDistortion);\n\n      // update scaled image coordinates\n      xtScaled = uxScaled - xScaledDistortion;\n      ytScaled = uyScaled - yScaledDistortion;\n\n      // check for convergence\n      if((fabs(xtScaled - xScaledPrevious) <= tolerance) && (fabs(ytScaled - yScaledPrevious) <= tolerance)) {\n        bConverged = true;\n        break;\n      }\n\n      xScaledPrevious = xtScaled;\n      yScaledPrevious = ytScaled;\n    }\n\n    if (bConverged) {\n      // scale coordinates back to detector (-32.5 to +32.5)\n      xtScaled *= -m_focalPlaneHalf_x;\n      ytScaled *= -m_focalPlaneHalf_y;\n\n      // set distorted coordinates\n      p_focalPlaneX = xtScaled;\n      p_focalPlaneY = ytScaled;\n    }\n\n    return bConverged;\n  }\n//  bool NewHorizonsMvicFrameCameraDistortionMap::SetUndistortedFocalPlane(const double ux, const double uy) {\n\n//    // image coordinates prior to introducing distortion\n//    p_undistortedFocalPlaneX = ux;\n//    p_undistortedFocalPlaneY = uy;\n\n//    double xScaledDistortion, yScaledDistortion;\n\n//    // scale undistorted coordinates to range of -1.0 to +1.0\n//    double xtScaled = ux/m_focalPlaneHalf_x;\n//    double ytScaled = uy/m_focalPlaneHalf_y;\n\n//    double uxScaled = xtScaled;\n//    double uyScaled = ytScaled;\n\n//    double xScaledPrevious = 1000000.0;\n//    double yScaledPrevious = 1000000.0;\n\n//    double tolerance = 0.000001;\n\n//    bool bConverged = false;\n\n//    // iterating to introduce distortion...\n//    // we stop when the difference between distorted coordinates\n//    // in successive iterations is at or below the given tolerance\n//    for( int i = 0; i < 50; i++ ) {\n\n//      // compute distortion in x and y (scaled to -1.0 - +1.0) using Legendre Polynomials\n//      computeDistortionCorrections(xtScaled, ytScaled, xScaledDistortion, yScaledDistortion);\n\n//      // update scaled image coordinates\n//      xtScaled = uxScaled - xScaledDistortion;\n//      ytScaled = uyScaled - yScaledDistortion;\n\n//      // check for convergence\n//      if((fabs(xtScaled - xScaledPrevious) <= tolerance) && (fabs(ytScaled - yScaledPrevious) <= tolerance)) {\n//        bConverged = true;\n//        break;\n//      }\n\n//      xScaledPrevious = xtScaled;\n//      yScaledPrevious = ytScaled;\n//    }\n\n//    if (bConverged) {\n//      // scale coordinates back to detector (-32.656 to +32.656)\n//      xtScaled *= m_focalPlaneHalf_x;\n//      ytScaled *= m_focalPlaneHalf_y;\n\n//      // set distorted coordinates\n//      p_focalPlaneX = xtScaled;\n//      p_focalPlaneY = ytScaled;\n//    }\n\n//    return bConverged;\n//  }\n\n\n  /** Compute distortion corrections in x and y direction\n   *\n   * For Legendre Polynomials, see ...\n   *\n   * http://mathworld.wolfram.com/LegendrePolynomial.html\n   * http://www.boost.org/doc/libs/1_36_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/sf_poly/legendre.html\n   *\n   * @param xscaled focal plane x scaled to range of 1- to 1 for Legendre Polynomials\n   * @param yscaled focal plane y scaled to range of 1- to 1 for Legendre Polynomials\n   * @param deltax focal plane distortion correction to x in millimeters\n   * @param deltay focal plane distortion correction to y in millimeters\n   *\n   * @return if successful\n   */\n  bool NewHorizonsMvicFrameCameraDistortionMap::computeDistortionCorrections(const double xscaled,\n                                                                  const double yscaled, \n                                                                  double &deltax, double &deltay) {\n\n    double lpx0, lpx1, lpx2, lpx3, lpx4, lpx5;\n    double lpy0, lpy1, lpy2, lpy3, lpy4, lpy5;\n\n    // Legendre polynomials\n    // boost library method legendre_p will generate an exception if xscaled or yscaled do not lie\n    // between -1 to 1 (inclusive). In this event we return false.\n    try {\n      lpx0 = legendre_p(0,xscaled);\n      lpx1 = legendre_p(1,xscaled);\n      lpx2 = legendre_p(2,xscaled);\n      lpx3 = legendre_p(3,xscaled);\n      lpx4 = legendre_p(4,xscaled);\n      lpx5 = legendre_p(5,xscaled);\n      lpy0 = legendre_p(0,yscaled);\n      lpy1 = legendre_p(1,yscaled);\n      lpy2 = legendre_p(2,yscaled);\n      lpy3 = legendre_p(3,yscaled);\n      lpy4 = legendre_p(4,yscaled);\n      lpy5 = legendre_p(5,yscaled);\n    }\n    // TESTING NOTE: Could not find a way to cause this error. If one is found a test should be added\n    catch (const std::exception& e) {\n      return false;\n    }\n\n    deltax =\n       m_xDistortionCoeffs[0] * lpx0 * lpy1 +\n       m_xDistortionCoeffs[1] * lpx1 * lpy0 +\n       m_xDistortionCoeffs[2] * lpx0 * lpy2 +\n       m_xDistortionCoeffs[3] * lpx1 * lpy1 +\n       m_xDistortionCoeffs[4] * lpx2 * lpy0 +\n       m_xDistortionCoeffs[5] * lpx0 * lpy3 +\n       m_xDistortionCoeffs[6] * lpx1 * lpy2 +\n       m_xDistortionCoeffs[7] * lpx2 * lpy1 +\n       m_xDistortionCoeffs[8] * lpx3 * lpy0 +\n       m_xDistortionCoeffs[9] * lpx0 * lpy4 +\n      m_xDistortionCoeffs[10] * lpx1 * lpy3 +\n      m_xDistortionCoeffs[11] * lpx2 * lpy2 +\n      m_xDistortionCoeffs[12] * lpx3 * lpy1 +\n      m_xDistortionCoeffs[13] * lpx4 * lpy0 +\n      m_xDistortionCoeffs[14] * lpx0 * lpy5 +\n      m_xDistortionCoeffs[15] * lpx1 * lpy4 +\n      m_xDistortionCoeffs[16] * lpx2 * lpy3 +\n      m_xDistortionCoeffs[17] * lpx3 * lpy2 +\n      m_xDistortionCoeffs[18] * lpx4 * lpy1 +\n      m_xDistortionCoeffs[19] * lpx5 * lpy0;\n\n    deltay =\n      m_yDistortionCoeffs[0] * lpx0 * lpy1 +\n      m_yDistortionCoeffs[1] * lpx1 * lpy0 +\n      m_yDistortionCoeffs[2] * lpx0 * lpy2 +\n      m_yDistortionCoeffs[3] * lpx1 * lpy1 +\n      m_yDistortionCoeffs[4] * lpx2 * lpy0 +\n      m_yDistortionCoeffs[5] * lpx0 * lpy3 +\n      m_yDistortionCoeffs[6] * lpx1 * lpy2 +\n      m_yDistortionCoeffs[7] * lpx2 * lpy1 +\n      m_yDistortionCoeffs[8] * lpx3 * lpy0 +\n      m_yDistortionCoeffs[9] * lpx0 * lpy4 +\n     m_yDistortionCoeffs[10] * lpx1 * lpy3 +\n     m_yDistortionCoeffs[11] * lpx2 * lpy2 +\n     m_yDistortionCoeffs[12] * lpx3 * lpy1 +\n     m_yDistortionCoeffs[13] * lpx4 * lpy0 +\n     m_yDistortionCoeffs[14] * lpx0 * lpy5 +\n     m_yDistortionCoeffs[15] * lpx1 * lpy4 +\n     m_yDistortionCoeffs[16] * lpx2 * lpy3 +\n     m_yDistortionCoeffs[17] * lpx3 * lpy2 +\n     m_yDistortionCoeffs[18] * lpx4 * lpy1 +\n     m_yDistortionCoeffs[19] * lpx5 * lpy0;\n\n    return true;\n  }\n}\n", "meta": {"hexsha": "a6425148f65f4fd933eec08b3df589f3276da37d", "size": 14680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCameraDistortionMap.cpp", "max_stars_repo_name": "ihumphrey-usgs/ISIS3_old", "max_stars_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T15:31:33.000Z", "max_issues_repo_path": "isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCameraDistortionMap.cpp", "max_issues_repo_name": "ihumphrey-usgs/ISIS3_old", "max_issues_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "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": "isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCameraDistortionMap.cpp", "max_forks_repo_name": "ihumphrey-usgs/ISIS3_old", "max_forks_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T06:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T06:05:03.000Z", "avg_line_length": 34.7044917258, "max_line_length": 115, "alphanum_fraction": 0.6617166213, "num_tokens": 4302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19600010223289313}}
{"text": "#ifndef STAN_MATH_TORSTEN_SOLVE_GROUP_ODE_HPP\n#define STAN_MATH_TORSTEN_SOLVE_GROUP_ODE_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/torsten/to_array_2d.hpp>\n#include <stan/math/torsten/ev_manager.hpp>\n#include <stan/math/torsten/pmx_population_check.hpp>\n#include <stan/math/torsten/pmx_ode_model.hpp>\n#include <stan/math/torsten/pmx_check.hpp>\n#include <stan/math/torsten/pmx_solve_ode.hpp>\n#include <vector>\n\nnamespace torsten {\n\n  template<typename integrator_type>\n  struct PMXSolveGroupODE {\n    static constexpr double RTOL_DE = 1.e-6;\n    static constexpr double ATOL_DE = 1.e-6;\n    static constexpr int MAXSTEP_DE = 1e6;\n    static constexpr double RTOL_AS = 1.e-6;\n    static constexpr double ATOL_AS = 1.e-6;\n    static constexpr int MAXSTEP_AS = 1e2;\n    /*\n     * For population models, more often we use ragged arrays\n     * to describe the entire population, so in addition we need the arrays of\n     * the length of each individual's data. The size of that\n     * vector is the size of the population.\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          double as_rel_tol,\n          double as_abs_tol,\n          long int as_max_num_steps,\n          std::ostream* msgs) {\n      static const char* caller(\"PMX SOLVE GROUP ODE\");\n      torsten::pmx_population_check(len, time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, caller);\n      torsten::pmx_population_check(len, time, biovar, tlag, caller);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> >>;\n      ER events_rec(nCmt, len, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      Eigen::Matrix<typename EM::T_scalar, -1, -1> pred(nCmt, events_rec.total_num_event_times);\n\n      pr.pred(events_rec, pred, integrator, pMatrix, biovar, tlag, nCmt, f);\n\n      return pred;\n    }\n\n    /*\n     * overload with default ode & algebra solver controls\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * overload with default algebra solver controls\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * overload for omitting <code>tlag</code>, with all the solver controls\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          double as_rel_tol,\n          double as_abs_tol,\n          long int as_max_num_steps,\n          std::ostream* msgs) {\n      static const char* caller(\"PMX SOLVE GROUP ODE\");\n      torsten::pmx_population_check(len, time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, caller);\n      torsten::pmx_population_check(len, time, biovar, caller);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5> >>;\n      ER events_rec(nCmt, len, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      Eigen::Matrix<typename EM::T_scalar, -1, -1> pred(nCmt, events_rec.total_num_event_times);\n\n      pr.pred(events_rec, pred, integrator, pMatrix, biovar, nCmt, f);\n\n      return pred;\n    }\n\n    /*\n     * overload for omitting <code>tlag</code>, with default solver controls\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix, biovar,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * overload for omitting <code>tlag</code>, with default algebra\n     * solver controls and user-defined ode solver controls\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix, biovar,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * overload for omitting <code>biuovar/tlag</code>, with all the solver controls\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          double as_rel_tol,\n          double as_abs_tol,\n          long int as_max_num_steps,\n          std::ostream* msgs) {\n      static const char* caller(\"PMX SOLVE GROUP ODE\");\n      torsten::pmx_population_check(len, time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, caller);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<> >>;\n      ER events_rec(nCmt, len, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      Eigen::Matrix<typename EM::T_scalar, -1, -1> pred(nCmt, events_rec.total_num_event_times);\n\n      pr.pred(events_rec, pred, integrator, pMatrix, nCmt, f);\n\n      return pred;\n    }\n\n    /*\n     * overload for omitting <code>biovar/tlag</code>, with default solver controls\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * overload for omitting <code>tlag</code>, with default algebra\n     * solver controls and user-defined ode solver controls\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * For population models, more often we use ragged arrays\n     * to describe the entire population, so in addition we need the arrays of\n     * the length of each individual's data. The size of that\n     * vector is the size of the population. \n     * Overload with support of real data.\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          const std::vector<std::vector<double> >& x_r,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          double as_rel_tol,\n          double as_abs_tol,\n          long int as_max_num_steps,\n          std::ostream* msgs) {\n      static const char* caller(\"PMX SOLVE GROUP ODE\");\n      torsten::pmx_population_check(len, time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, caller);\n      torsten::pmx_population_check(len, time, biovar, tlag, caller);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6>, double>>;\n      ER events_rec(nCmt, len, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      Eigen::Matrix<typename EM::T_scalar, -1, -1> pred(nCmt, events_rec.total_num_event_times);\n\n      pr.pred(events_rec, pred, integrator, pMatrix, biovar, tlag, x_r, nCmt, f);\n\n      return pred;\n    }\n\n    /*\n     * overload with default ode & algebra solver controls, with support of real data\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          const std::vector<std::vector<double> >& x_r,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag, x_r,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * overload with default algebra solver controls, with support of real data\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          const std::vector<std::vector<double> >& x_r,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag, x_r,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * For population models, more often we use ragged arrays\n     * to describe the entire population, so in addition we need the arrays of\n     * the length of each individual's data. The size of that\n     * vector is the size of the population. \n     * Overload with support of real & integer data.\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          const std::vector<std::vector<double> >& x_r,\n          const std::vector<std::vector<int> >& x_i,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          double as_rel_tol,\n          double as_abs_tol,\n          long int as_max_num_steps,\n          std::ostream* msgs) {\n      static const char* caller(\"PMX SOLVE GROUP ODE\");\n      torsten::pmx_population_check(len, time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, caller);\n      torsten::pmx_population_check(len, time, biovar, tlag, caller);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6>, double, int>>;\n      ER events_rec(nCmt, len, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      Eigen::Matrix<typename EM::T_scalar, -1, -1> pred(nCmt, events_rec.total_num_event_times);\n\n      pr.pred(events_rec, pred, integrator, pMatrix, biovar, tlag, x_r, x_i, nCmt, f);\n\n      return pred;\n    }\n\n    /*\n     * overload with default ode & algebra solver controls, with support of real & integer data\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          const std::vector<std::vector<double> >& x_r,\n          const std::vector<std::vector<int> >& x_i,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag, x_r, x_i,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * overload with default algebra solver controls, with support of real & integer data\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static Eigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n                         Eigen::Dynamic, Eigen::Dynamic>\n    solve(const F& f,\n          const int nCmt,\n          const std::vector<int>& len,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          const std::vector<std::vector<T6> >& tlag,\n          const std::vector<std::vector<double> >& x_r,\n          const std::vector<std::vector<int> >& x_i,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          std::ostream* msgs) {\n      return solve(f, nCmt, len, time, amt, rate,\n                   ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag, x_r, x_i,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n  };\n\n}\n#endif\n", "meta": {"hexsha": "3604b3cd5dd31844f61e525886611d591daf9dd9", "size": 21249, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pmx_solve_group_ode.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_group_ode.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_group_ode.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": 44.26875, "max_line_length": 168, "alphanum_fraction": 0.6037460586, "num_tokens": 5766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1960000997383093}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_COMPUTE_RANDOM_MERSENNE_TWISTER_ENGINE_HPP\n#define BOOST_COMPUTE_RANDOM_MERSENNE_TWISTER_ENGINE_HPP\n\n#include <algorithm>\n\n#include <boost/compute/types.hpp>\n#include <boost/compute/buffer.hpp>\n#include <boost/compute/kernel.hpp>\n#include <boost/compute/context.hpp>\n#include <boost/compute/program.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/detail/iterator_range_size.hpp>\n#include <boost/compute/iterator/discard_iterator.hpp>\n#include <boost/compute/utility/program_cache.hpp>\n\nnamespace boost {\nnamespace compute {\n\n/// \\class mersenne_twister_engine\n/// \\brief Mersenne twister pseudorandom number generator.\ntemplate<class T>\nclass mersenne_twister_engine\n{\npublic:\n    typedef T result_type;\n    static const T default_seed = 5489U;\n    static const T n = 624;\n    static const T m = 397;\n\n    /// Creates a new mersenne_twister_engine and seeds it with \\p value.\n    explicit mersenne_twister_engine(command_queue &queue,\n                                     result_type value = default_seed)\n        : m_context(queue.get_context()),\n          m_state_buffer(m_context, n * sizeof(result_type))\n    {\n        // setup program\n        load_program();\n\n        // seed state\n        seed(value, queue);\n    }\n\n    /// Creates a new mersenne_twister_engine object as a copy of \\p other.\n    mersenne_twister_engine(const mersenne_twister_engine<T> &other)\n        : m_context(other.m_context),\n          m_state_index(other.m_state_index),\n          m_program(other.m_program),\n          m_state_buffer(other.m_state_buffer)\n    {\n    }\n\n    /// Copies \\p other to \\c *this.\n    mersenne_twister_engine<T>& operator=(const mersenne_twister_engine<T> &other)\n    {\n        if(this != &other){\n            m_context = other.m_context;\n            m_state_index = other.m_state_index;\n            m_program = other.m_program;\n            m_state_buffer = other.m_state_buffer;\n        }\n\n        return *this;\n    }\n\n    /// Destroys the mersenne_twister_engine object.\n    ~mersenne_twister_engine()\n    {\n    }\n\n    /// Seeds the random number generator with \\p value.\n    ///\n    /// \\param value seed value for the random-number generator\n    /// \\param queue command queue to perform the operation\n    ///\n    /// If no seed value is provided, \\c default_seed is used.\n    void seed(result_type value, command_queue &queue)\n    {\n        kernel seed_kernel = m_program.create_kernel(\"seed\");\n        seed_kernel.set_arg(0, value);\n        seed_kernel.set_arg(1, m_state_buffer);\n\n        queue.enqueue_task(seed_kernel);\n\n        m_state_index = 0;\n    }\n\n    /// \\overload\n    void seed(command_queue &queue)\n    {\n        seed(default_seed, queue);\n    }\n\n    /// Generates random numbers and stores them to the range [\\p first, \\p last).\n    template<class OutputIterator>\n    void generate(OutputIterator first, OutputIterator last, command_queue &queue)\n    {\n        const size_t size = detail::iterator_range_size(first, last);\n\n        kernel fill_kernel(m_program, \"fill\");\n        fill_kernel.set_arg(0, m_state_buffer);\n        fill_kernel.set_arg(2, first.get_buffer());\n\n        size_t offset = 0;\n        size_t &p = m_state_index;\n\n        for(;;){\n            size_t count = 0;\n            if(size > n){\n                count = (std::min)(static_cast<size_t>(n), size - offset);\n            }\n            else {\n                count = size;\n            }\n            fill_kernel.set_arg(1, static_cast<const uint_>(p));\n            fill_kernel.set_arg(3, static_cast<const uint_>(offset));\n            queue.enqueue_1d_range_kernel(fill_kernel, 0, count, 0);\n\n            p += count;\n            offset += count;\n\n            if(offset >= size){\n                break;\n            }\n\n            generate_state(queue);\n            p = 0;\n        }\n    }\n\n    /// \\internal_\n    void generate(discard_iterator first, discard_iterator last, command_queue &queue)\n    {\n        (void) queue;\n\n        m_state_index += std::distance(first, last);\n    }\n\n    /// Generates random numbers, transforms them with \\p op, and then stores\n    /// them to the range [\\p first, \\p last).\n    template<class OutputIterator, class Function>\n    void generate(OutputIterator first, OutputIterator last, Function op, command_queue &queue)\n    {\n        vector<T> tmp(std::distance(first, last), queue.get_context());\n        generate(tmp.begin(), tmp.end(), queue);\n        transform(tmp.begin(), tmp.end(), first, op, queue);\n    }\n\n    /// Generates \\p z random numbers and discards them.\n    void discard(size_t z, command_queue &queue)\n    {\n        generate(discard_iterator(0), discard_iterator(z), queue);\n    }\n\n    /// \\internal_ (deprecated)\n    template<class OutputIterator>\n    void fill(OutputIterator first, OutputIterator last, command_queue &queue)\n    {\n        generate(first, last, queue);\n    }\n\nprivate:\n    /// \\internal_\n    void generate_state(command_queue &queue)\n    {\n        kernel generate_state_kernel =\n            m_program.create_kernel(\"generate_state\");\n        generate_state_kernel.set_arg(0, m_state_buffer);\n        queue.enqueue_task(generate_state_kernel);\n    }\n\n    /// \\internal_\n    void load_program()\n    {\n        boost::shared_ptr<program_cache> cache =\n            program_cache::get_global_cache(m_context);\n\n        std::string cache_key =\n            std::string(\"__boost_mersenne_twister_engine_\") + type_name<T>();\n\n        const char source[] =\n            \"static uint twiddle(uint u, uint v)\\n\"\n            \"{\\n\"\n            \"    return (((u & 0x80000000U) | (v & 0x7FFFFFFFU)) >> 1) ^\\n\"\n            \"           ((v & 1U) ? 0x9908B0DFU : 0x0U);\\n\"\n            \"}\\n\"\n\n            \"__kernel void generate_state(__global uint *state)\\n\"\n            \"{\\n\"\n            \"    const uint n = 624;\\n\"\n            \"    const uint m = 397;\\n\"\n            \"    for(uint i = 0; i < (n - m); i++)\\n\"\n            \"        state[i] = state[i+m] ^ twiddle(state[i], state[i+1]);\\n\"\n            \"    for(uint i = n - m; i < (n - 1); i++)\\n\"\n            \"        state[i] = state[i+m-n] ^ twiddle(state[i], state[i+1]);\\n\"\n            \"    state[n-1] = state[m-1] ^ twiddle(state[n-1], state[0]);\\n\"\n            \"}\\n\"\n\n            \"__kernel void seed(const uint s, __global uint *state)\\n\"\n            \"{\\n\"\n            \"    const uint n = 624;\\n\"\n            \"    state[0] = s & 0xFFFFFFFFU;\\n\"\n            \"    for(uint i = 1; i < n; i++){\\n\"\n            \"        state[i] = 1812433253U * (state[i-1] ^ (state[i-1] >> 30)) + i;\\n\"\n            \"        state[i] &= 0xFFFFFFFFU;\\n\"\n            \"    }\\n\"\n            \"    generate_state(state);\\n\"\n            \"}\\n\"\n\n            \"static uint random_number(__global uint *state, const uint p)\\n\"\n            \"{\\n\"\n            \"    uint x = state[p];\\n\"\n            \"    x ^= (x >> 11);\\n\"\n            \"    x ^= (x << 7) & 0x9D2C5680U;\\n\"\n            \"    x ^= (x << 15) & 0xEFC60000U;\\n\"\n            \"    return x ^ (x >> 18);\\n\"\n            \"}\\n\"\n\n            \"__kernel void fill(__global uint *state,\\n\"\n            \"                   const uint state_index,\\n\"\n            \"                   __global uint *vector,\\n\"\n            \"                   const uint offset)\\n\"\n            \"{\\n\"\n            \"    const uint i = get_global_id(0);\\n\"\n            \"    vector[offset+i] = random_number(state, state_index + i);\\n\"\n            \"}\\n\";\n\n        m_program = cache->get_or_build(cache_key, std::string(), source, m_context);\n    }\n\nprivate:\n    context m_context;\n    size_t m_state_index;\n    program m_program;\n    buffer m_state_buffer;\n};\n\ntypedef mersenne_twister_engine<uint_> mt19937;\n\n} // end compute namespace\n} // end boost namespace\n\n#endif // BOOST_COMPUTE_RANDOM_MERSENNE_TWISTER_ENGINE_HPP\n", "meta": {"hexsha": "db8560e53d1dc9a16bba59958e73211fcb40647c", "size": 8288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/compute/random/mersenne_twister_engine.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": "ios/Pods/boost-for-react-native/boost/compute/random/mersenne_twister_engine.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "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": "ios/Pods/boost-for-react-native/boost/compute/random/mersenne_twister_engine.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "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": 32.5019607843, "max_line_length": 95, "alphanum_fraction": 0.5728764479, "num_tokens": 2011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.19600009462342927}}
{"text": "#ifndef OSRM_OPENING_HOURS_HPP\n#define OSRM_OPENING_HOURS_HPP\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n\n#include <string>\n#include <vector>\n\nnamespace osrm\n{\nnamespace util\n{\n\n// Helper classes for \"opening hours\" format http://wiki.openstreetmap.org/wiki/Key:opening_hours\n// Grammar https://wiki.openstreetmap.org/wiki/Key:opening_hours/specification\n// Supported simplified features in CheckOpeningHours:\n// - Year/Month/Day ranges\n// - Weekday ranges\n// - Time ranges\n// Not supported:\n// - Week numbers\n// - Holidays, events, variables dates\n// - Day offsets and periodic ranges\nstruct OpeningHours\n{\n    enum Modifier\n    {\n        unknown,\n        open,\n        closed,\n        off,\n        is24_7\n    };\n\n    struct Time\n    {\n        enum Event : unsigned char\n        {\n            invalid,\n            none,\n            dawn,\n            sunrise,\n            sunset,\n            dusk\n        };\n\n        Event event;\n        std::int32_t minutes;\n\n        Time() : event(invalid), minutes(0) {}\n        Time(Event event) : event(event), minutes(0) {}\n        Time(char hour, char min) : event(none), minutes(hour * 60 + min) {}\n        Time(Event event, bool positive, const Time &offset)\n            : event(event), minutes(positive ? offset.minutes : -offset.minutes)\n        {\n        }\n    };\n\n    struct TimeSpan\n    {\n        Time from, to;\n        TimeSpan() = default;\n        TimeSpan(const Time &from_, const Time &to_) : from(from_), to(to_)\n        {\n            if (to.minutes < from.minutes)\n                to.minutes += 24 * 60;\n        }\n\n        bool IsInRange(const struct tm &time, bool &use_curr_day, bool &use_next_day) const\n        {\n            // TODO: events are not handled\n            if (from.event != OpeningHours::Time::none || to.event != OpeningHours::Time::none)\n                return false;\n\n            const auto minutes = time.tm_hour * 60 + time.tm_min;\n            if (to.minutes > 24 * 60)\n            {\n                use_curr_day = (from.minutes <= minutes); // in range [from, 24:00) current day\n                use_next_day = (minutes < to.minutes - 24 * 60); // in range [00:00, to) next day\n            }\n            else\n            {\n                use_curr_day =\n                    (from.minutes <= minutes && minutes < to.minutes); // in range [from, to)\n                use_next_day = false;                                  // do not use the next day\n            }\n\n            return use_curr_day || use_next_day;\n        }\n    };\n\n    struct WeekdayRange\n    {\n        int weekdays, overnight_weekdays;\n        WeekdayRange() = default;\n        WeekdayRange(unsigned char from, unsigned char to)\n        {\n            // weekdays mask for [from, to], e.g [2, 5] -> 0111100, [5, 2] -> 1100111,\n            //  [3, 3] -> 0001000, [0,6] -> 1111111, [6,0] -> 1000001, [4, 3] -> 1111111\n            weekdays = (from <= to) ? ((1 << (to - from + 1)) - 1) << from\n                                    : ~(((1 << (from - to - 1)) - 1) << (to + 1));\n            weekdays &= 0x7f;\n            overnight_weekdays = (weekdays << 1) | (weekdays & 0x40 ? 1 : 0);\n        }\n\n        bool IsInRange(const struct tm &time, bool use_curr_day, bool use_next_day) const\n        {\n            return (use_curr_day && weekdays & (1 << time.tm_wday)) ||\n                   (use_next_day && overnight_weekdays & (1 << time.tm_wday));\n        }\n    };\n\n    struct Monthday\n    {\n        int year;\n        char month;\n        char day;\n        Monthday() = default;\n        Monthday(int year) : year(year), month(0), day(0) {}\n        Monthday(int year, char month, char day) : year(year), month(month), day(day) {}\n\n        bool IsValid() const { return year > 0 || month != 0 || day != 0; }\n        bool operator==(const Monthday &rhs) const\n        {\n            return std::tie(year, month, day) == std::tie(rhs.year, rhs.month, rhs.day);\n        }\n    };\n\n    struct MonthdayRange\n    {\n        Monthday from, to;\n        MonthdayRange() : from(0, 0, 0), to(0, 0, 0) {}\n        MonthdayRange(const Monthday &from, const Monthday &to) : from(from), to(to) {}\n\n        bool IsInRange(const struct tm &time, bool use_curr_day, bool use_next_day) const\n        {\n            using boost::gregorian::date;\n            using boost::gregorian::date_duration;\n\n            const auto year = time.tm_year + 1900;\n            const auto month = time.tm_mon + 1;\n\n            date date_current(year, month, time.tm_mday);\n            date date_from(boost::gregorian::min_date_time);\n            date date_to(boost::gregorian::max_date_time);\n\n            if (from.IsValid())\n            {\n                date_from = (from.day == 0) ? date(from.year == 0 ? year : from.year,\n                                                   from.month == 0 ? month : from.month,\n                                                   1)\n                                            : date(from.year == 0 ? year : from.year,\n                                                   from.month == 0 ? month : from.month,\n                                                   from.day);\n            }\n            if (to.IsValid())\n            {\n                date_to = date(to.year == 0 ? (from.year == 0 ? year : from.year) : to.year,\n                               to.month == 0 ? (from.month == 0 ? month : from.month) : to.month,\n                               1);\n                date_to = (to.day == 0) ? date_to.end_of_month()\n                                        : date(date_to.year(), date_to.month(), to.day);\n            }\n            else if (to == Monthday())\n            {\n                date_to = date_from;\n            }\n\n            const bool inverse = (from.year == 0) && (to.year == 0) && (date_from > date_to);\n            if (inverse)\n            {\n                std::swap(date_from, date_to);\n            }\n\n            if (!use_curr_day)\n                date_from += date_duration(1);\n            if (use_next_day && date_to != date(boost::gregorian::max_date_time))\n                date_to += date_duration(1);\n\n            return (date_from <= date_current && date_current <= date_to) ^ inverse;\n        }\n    };\n\n    OpeningHours() : modifier(open) {}\n\n    bool IsInRange(const struct tm &time) const\n    {\n        bool use_curr_day = true;  // the first matching time uses the current day\n        bool use_next_day = false; // the first matching time uses the next day\n        return (!times.empty() || !weekdays.empty() || !monthdays.empty())\n               // the value is in range if time is not specified or is in any time range\n               // (also modifies use_curr_day and use_next_day flags to handle overnight day ranges,\n               // e.g. for 22:00-03:00 and 2am -> use_curr_day = false and use_next_day = true)\n               && (times.empty() ||\n                   std::any_of(times.begin(),\n                               times.end(),\n                               [&time, &use_curr_day, &use_next_day](const auto &x) {\n                                   return x.IsInRange(time, use_curr_day, use_next_day);\n                               }))\n               // .. and if weekdays are not specified or matches weekdays range\n               && (weekdays.empty() ||\n                   std::any_of(weekdays.begin(),\n                               weekdays.end(),\n                               [&time, use_curr_day, use_next_day](const auto &x) {\n                                   return x.IsInRange(time, use_curr_day, use_next_day);\n                               }))\n               // .. and if month-day ranges are not specified or is in any month-day range\n               && (monthdays.empty() ||\n                   std::any_of(monthdays.begin(),\n                               monthdays.end(),\n                               [&time, use_curr_day, use_next_day](const auto &x) {\n                                   return x.IsInRange(time, use_curr_day, use_next_day);\n                               }));\n    }\n\n    std::vector<TimeSpan> times;\n    std::vector<WeekdayRange> weekdays;\n    std::vector<MonthdayRange> monthdays;\n    Modifier modifier;\n};\n\nstd::vector<OpeningHours> ParseOpeningHours(const std::string &str);\n\nbool CheckOpeningHours(const std::vector<OpeningHours> &input, const struct tm &time);\n\n} // namespace util\n} // namespace osrm\n\n#endif // OSRM_OPENING_HOURS_HPP\n", "meta": {"hexsha": "e506bd0fa722232c0a779948e1ce5dfecddbd751", "size": 8363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/opening_hours.hpp", "max_stars_repo_name": "EricWang1hitsz/osrm-backend", "max_stars_repo_head_hexsha": "ff1af413d6c78f8e454584fe978d5468d984d74a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4526.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T15:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:33:49.000Z", "max_issues_repo_path": "include/util/opening_hours.hpp", "max_issues_repo_name": "wsx9527/osrm-backend", "max_issues_repo_head_hexsha": "1e70b645e480946dad313b67f6a7d331baecfe3c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4497.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T15:29:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:19:35.000Z", "max_forks_repo_path": "include/util/opening_hours.hpp", "max_forks_repo_name": "wsx9527/osrm-backend", "max_forks_repo_head_hexsha": "1e70b645e480946dad313b67f6a7d331baecfe3c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3023.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T18:40:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T13:30:46.000Z", "avg_line_length": 36.3608695652, "max_line_length": 100, "alphanum_fraction": 0.4997010642, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19600008950854927}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n/// This application is for use of discovering which cameras contain\n/// most of the error after a bundle adjustment. The information\n/// produced by this application can help narrow down where better\n/// measurements are required.\n\n#include <vw/Core/ProgressCallback.h>\n#include <vw/BundleAdjustment/ControlNetwork.h>\n#include <asp/Core/Macros.h>\n#include <asp/Core/Common.h>\n#include <asp/IsisIO/IsisAdjustCameraModel.h>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/foreach.hpp>\n\nusing namespace vw;\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nstruct Options : public asp::BaseOptions {\n  std::string cnet_file;\n  std::vector<std::string> input_names;\n  bool find_median;\n};\n\nvoid handle_arguments( int argc, char *argv[], Options& opt ) {\n  po::options_description general_options(\"\");\n  general_options.add_options()\n    (\"find-median\", po::bool_switch(&opt.find_median)->default_value(false),\n     \"Find median when reporting high error cameras.\");\n  general_options.add( asp::BaseOptionsDescription(opt) );\n\n  po::options_description positional(\"\");\n  positional.add_options()\n    (\"cnet-file\", po::value(&opt.cnet_file))\n    (\"input-files\", po::value(&opt.input_names));\n\n  po::positional_options_description positional_desc;\n  positional_desc.add(\"cnet-file\", 1);\n  positional_desc.add(\"input-files\", -1);\n\n  std::string usage(\"<cnet_file> <isis cube files> ...\");\n  po::variables_map vm =\n    asp::check_command_line( argc, argv, opt, general_options,\n                             positional, positional_desc, usage );\n\n  if ( opt.input_names.empty() )\n    vw_throw( ArgumentErr() << \"Missing input cube files!\\n\"\n              << usage << general_options );\n  if ( opt.cnet_file.empty() )\n    vw_throw( ArgumentErr() << \"Missing input control network!\\n\"\n              << usage << general_options );\n}\n\nint main( int argc, char* argv[]) {\n\n  Options opt;\n  try {\n    handle_arguments( argc, argv, opt );\n\n    // Loading the image data into the camera models. Also applying\n    // blank equations to define the cameras\n    std::vector< camera::IsisAdjustCameraModel > camera_models;\n    std::map<std::string,size_t> serial_to_camera_model;\n    std::map<size_t,std::string> id_to_filename;\n    {\n      vw_out() << \"Loading Camera Models:\\n\";\n      vw_out() << \"----------------------\\n\";\n      TerminalProgressCallback progress(\"asp\",\"Camera Models:\");\n      progress.report_progress(0);\n      double tpc_inc = 1/double(opt.input_names.size());\n      BOOST_FOREACH( std::string const& input, opt.input_names ) {\n        progress.report_incremental_progress( tpc_inc );\n        vw_out(DebugMessage,\"asp\") << \"Loading: \" << input << \"\\n\";\n\n        std::string adjust_file =\n          fs::path( input ).replace_extension(\"isis_adjust\").string();\n\n        typedef boost::shared_ptr<asp::BaseEquation> shared_eq;\n        shared_eq posF, poseF;\n        if ( fs::exists( adjust_file ) ) {\n          std::ifstream input( adjust_file.c_str() );\n          posF = asp::read_equation(input);\n          poseF = asp::read_equation(input);\n          input.close();\n        } else {\n          posF = shared_eq( new asp::PolyEquation( 0 ) );\n          poseF = shared_eq( new asp::PolyEquation( 0 ) );\n        }\n        camera::IsisAdjustCameraModel camera( input, posF, poseF );\n        camera_models.push_back( camera );\n\n        serial_to_camera_model[ camera_models.back().serial_number() ] =\n          camera_models.size() - 1;\n        id_to_filename[ camera_models.size() - 1 ] = input;\n      }\n      progress.report_finished();\n    }\n\n    ba::ControlNetwork cnet(\"\");\n    std::vector<std::string> tokens;\n    boost::split( tokens, opt.cnet_file, boost::is_any_of(\".\") );\n    if ( tokens[tokens.size()-1] == \"net\" ) {\n      cnet.read_isis( opt.cnet_file );\n    } else if ( tokens[tokens.size()-1] == \"cnet\" ) {\n      cnet.read_binary( opt.cnet_file );\n    } else {\n      vw_throw( IOErr() << \"Unknown Control Network file extension, \\\"\"\n                << tokens[tokens.size()-1] << \"\\\".\" );\n    }\n\n    vw_out() << \"Assigning Indexing:\\n\";\n    BOOST_FOREACH( ba::ControlPoint& cp, cnet ) {\n      BOOST_FOREACH( ba::ControlMeasure& cm, cp ) {\n        std::map<std::string,size_t>::const_iterator id =\n          serial_to_camera_model.find( cm.serial() );\n        if ( id != serial_to_camera_model.end() )\n          cm.set_image_id( id->second );\n        else\n          vw_throw( IOErr() << \"Control Network has serial not associated with input cameras, \\\"\" << cm.serial() << \"\\\".\" );\n      }\n    }\n\n    vw_out() << \"Iterating through cameras.\\n\";\n    std::vector<double> average_error( camera_models.size() );\n    std::vector<size_t> average_count( camera_models.size() );\n    std::fill( average_error.begin(), average_error.end(), 0 );\n    std::fill( average_count.begin(), average_count.end(), 0 );\n    math::CDFAccumulator<double> cdf_accu;\n    BOOST_FOREACH( ba::ControlPoint & cp, cnet ) {\n      BOOST_FOREACH( ba::ControlMeasure & cm, cp ) {\n        Vector2 reprojection =\n          camera_models[cm.image_id()].point_to_pixel( cp.position() );\n        average_count[cm.image_id()]++;\n        double error = norm_2(reprojection-cm.position());\n        average_error[cm.image_id()] += error;\n        cdf_accu(error);\n      }\n    }\n    cdf_accu.update();\n    vw_out() << \"CDF [\" << cdf_accu.quantile(0.0) << \" \"\n             << cdf_accu.quantile(0.25) << \" \" << cdf_accu.quantile(0.5)\n             << \" \" << cdf_accu.quantile(0.75) << \" \"\n             << cdf_accu.quantile(1.0) << \"]\\n\";\n\n    // Calculate average and accumulators\n    MeanAccumulator<double> mean_acc;\n    StdDevAccumulator<double> stddev_acc;\n    double max_error = -1;\n    size_t index_max_error = 0;\n    std::list<size_t> cameras_not_connected;\n    for ( size_t i = 0; i < average_error.size(); i++ ) {\n      if ( average_count[i] == 0 ) {\n        average_error[i] = 0;\n        cameras_not_connected.push_back(i);\n        continue;\n      }\n      average_error[i] /= double(average_count[i]);\n      mean_acc( average_error[i] );\n      stddev_acc( average_error[i] );\n      if ( average_error[i] > max_error ) {\n        max_error = average_error[i];\n        index_max_error = i;\n      }\n    }\n\n    double mean = mean_acc.value();\n    double stddev = stddev_acc.value();\n    std::cout << \"Mean error  : \" << mean << \" px\\n\";\n    std::cout << \"StdDev error: \" << stddev << \" px\\n\";\n\n\n    // Printing stats\n    vw_out() << \"\\nCameras not connected:\\n\";\n    vw_out() << \"-------------------------------------\\n\";\n    BOOST_FOREACH( size_t i, cameras_not_connected ) {\n      vw_out() << id_to_filename[i] << \"\\n\";\n    }\n    vw_out() << \"\\nCamera of largest error is:\\n\";\n    vw_out() << \"-------------------------------------\\n\";\n    vw_out() << id_to_filename[index_max_error] << \" [\"\n             << max_error << \" px]\\n\";\n    vw_out() << \"\\nCameras that are 1 std dev off:\\n\";\n    vw_out() << \"-------------------------------------\\n\";\n    for ( size_t i = 0; i < average_error.size(); i++ ) {\n      if ( average_error[i] - mean > stddev ) {\n        if ( opt.find_median ) {\n          MedianAccumulator<double> cmedian_acc;\n          StdDevAccumulator<double> cstddev_acc;\n          BOOST_FOREACH( ba::ControlPoint const& cp, cnet ) {\n            BOOST_FOREACH( ba::ControlMeasure const& cm, cp ) {\n              if ( cm.image_id() == i ) {\n                Vector2 reprojection =\n                  camera_models[cm.image_id()].point_to_pixel( cp.position() );\n                double error = norm_2(reprojection-cm.position());\n                cmedian_acc(error);\n                cstddev_acc(error);\n              }\n            }\n          }\n          vw_out() << id_to_filename[i] << \"[ m: \" << average_error[i]\n                   << \" std: \" << cstddev_acc.value()\n                   << \" md: \" <<  cmedian_acc.value() << \" px ]\\n\";\n        } else {\n          vw_out() << id_to_filename[i] << \" [\"\n                   << average_error[i] << \" px]\\n\";\n        }\n      }\n    }\n\n  } ASP_STANDARD_CATCHES;\n\n  return 0;\n}\n", "meta": {"hexsha": "795222daabe7a9a58c5689ee02a6c876771ff03b", "size": 8313, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/Tools/isis_adjust_camera_err.cc", "max_stars_repo_name": "nasa/StereoPipeline", "max_stars_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-05-06T01:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:55:29.000Z", "max_issues_repo_path": "src/asp/Tools/isis_adjust_camera_err.cc", "max_issues_repo_name": "imagineagents/StereoPipeline", "max_issues_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_issues_repo_licenses": ["NASA-1.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": "src/asp/Tools/isis_adjust_camera_err.cc", "max_forks_repo_name": "imagineagents/StereoPipeline", "max_forks_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T01:31:17.000Z", "avg_line_length": 37.2780269058, "max_line_length": 124, "alphanum_fraction": 0.5985805365, "num_tokens": 2071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.1959585169612145}}
{"text": "// Copyright (c) 2017-2020, The Monero Project\n// \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// \n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n// \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\n//    materials provided with the distribution.\n// \n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    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\n// EXPRESS 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\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// 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\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Implements the Bulletproofs+ prover and verifier algorithms\n//\n// Preprint: https://eprint.iacr.org/2020/735, version 17 Jun 2020\n//\n// NOTE ON NOTATION:\n//  In the signature constructions used in Monero, commitments to zero are treated as\n//      public keys against the curve group generator `G`. This means that amount\n//      commitments must use another generator `H` for values in order to show balance.\n//  The result is that the roles of `g` and `h` in the preprint are effectively swapped\n//      in this code, taking on the roles of `H` and `G`, respectively. Read carefully!\n\n#include <stdlib.h>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/lock_guard.hpp>\n#include \"misc_log_ex.h\"\n#include \"span.h\"\n#include \"cryptonote_config.h\"\nextern \"C\"\n{\n#include \"crypto/crypto-ops.h\"\n}\n#include \"rctOps.h\"\n#include \"multiexp.h\"\n#include \"bulletproofs_plus.h\"\n\n#undef MONERO_DEFAULT_LOG_CATEGORY\n#define MONERO_DEFAULT_LOG_CATEGORY \"bulletproof_plus\"\n\n#define STRAUS_SIZE_LIMIT 232\n#define PIPPENGER_SIZE_LIMIT 0\n\nnamespace rct\n{\n    // Vector functions\n    static rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b);\n    static rct::keyV vector_of_scalar_powers(const rct::key &x, size_t n);\n\n    // Proof bounds\n    static constexpr size_t maxN = 64; // maximum number of bits in range\n    static constexpr size_t maxM = BULLETPROOF_PLUS_MAX_OUTPUTS; // maximum number of outputs to aggregate into a single proof\n\n    // Cached public generators\n    static ge_p3 Hi_p3[maxN*maxM], Gi_p3[maxN*maxM];\n    static std::shared_ptr<straus_cached_data> straus_HiGi_cache;\n    static std::shared_ptr<pippenger_cached_data> pippenger_HiGi_cache;\n\n    // Useful scalar constants\n    static const constexpr rct::key ZERO = { {0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00  } }; // 0\n    static const constexpr rct::key ONE = { {0x01, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00  } }; // 1\n    static const constexpr rct::key TWO = { {0x02, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00  } }; // 2\n    static const constexpr rct::key MINUS_ONE = { { 0xec, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 } }; // -1\n    static const constexpr rct::key MINUS_INV_EIGHT = { { 0x74, 0xa4, 0x19, 0x7a, 0xf0, 0x7d, 0x0b, 0xf7, 0x05, 0xc2, 0xda, 0x25, 0x2b, 0x5c, 0x0b, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a } }; // -(8**(-1))\n    static rct::key TWO_SIXTY_FOUR_MINUS_ONE; // 2**64 - 1\n\n    // Initial transcript hash\n    static rct::key initial_transcript;\n\n    static boost::mutex init_mutex;\n\n    // Use the generator caches to compute a multiscalar multiplication\n    static inline rct::key multiexp(const std::vector<MultiexpData> &data, size_t HiGi_size)\n    {\n        if (HiGi_size > 0)\n        {\n            static_assert(232 <= STRAUS_SIZE_LIMIT, \"Straus in precalc mode can only be calculated till STRAUS_SIZE_LIMIT\");\n            return HiGi_size <= 232 && data.size() == HiGi_size ? straus(data, straus_HiGi_cache, 0) : pippenger(data, pippenger_HiGi_cache, HiGi_size, get_pippenger_c(data.size()));\n        }\n        else\n        {\n            return data.size() <= 95 ? straus(data, NULL, 0) : pippenger(data, NULL, 0, get_pippenger_c(data.size()));\n        }\n    }\n\n    // Confirm that a scalar is properly reduced\n    static inline bool is_reduced(const rct::key &scalar)\n    {\n        return sc_check(scalar.bytes) == 0;\n    }\n\n    // Use hashed values to produce indexed public generators\n    static ge_p3 get_exponent(const rct::key &base, size_t idx)\n    {\n        std::string hashed = std::string((const char*)base.bytes, sizeof(base)) + config::HASH_KEY_BULLETPROOF_PLUS_EXPONENT + tools::get_varint_data(idx);\n        rct::key generator;\n        ge_p3 generator_p3;\n        rct::hash_to_p3(generator_p3, rct::hash2rct(crypto::cn_fast_hash(hashed.data(), hashed.size())));\n        ge_p3_tobytes(generator.bytes, &generator_p3);\n        CHECK_AND_ASSERT_THROW_MES(!(generator == rct::identity()), \"Exponent is point at infinity\");\n        return generator_p3;\n    }\n\n    // Construct public generators\n    static void init_exponents()\n    {\n        boost::lock_guard<boost::mutex> lock(init_mutex);\n\n        // Only needs to be done once\n        static bool init_done = false;\n        if (init_done)\n            return;\n\n        std::vector<MultiexpData> data;\n        data.reserve(maxN*maxM*2);\n        for (size_t i = 0; i < maxN*maxM; ++i)\n        {\n            Hi_p3[i] = get_exponent(rct::H, i * 2);\n            Gi_p3[i] = get_exponent(rct::H, i * 2 + 1);\n\n            data.push_back({rct::zero(), Gi_p3[i]});\n            data.push_back({rct::zero(), Hi_p3[i]});\n        }\n\n        straus_HiGi_cache = straus_init_cache(data, STRAUS_SIZE_LIMIT);\n        pippenger_HiGi_cache = pippenger_init_cache(data, 0, PIPPENGER_SIZE_LIMIT);\n\n        // Compute 2**64 - 1 for later use in simplifying verification\n        TWO_SIXTY_FOUR_MINUS_ONE = TWO;\n        for (size_t i = 0; i < 6; i++)\n        {\n            sc_mul(TWO_SIXTY_FOUR_MINUS_ONE.bytes, TWO_SIXTY_FOUR_MINUS_ONE.bytes, TWO_SIXTY_FOUR_MINUS_ONE.bytes);\n        }\n        sc_sub(TWO_SIXTY_FOUR_MINUS_ONE.bytes, TWO_SIXTY_FOUR_MINUS_ONE.bytes, ONE.bytes);\n\n        // Generate the initial Fiat-Shamir transcript hash, which is constant across all proofs\n        const std::string domain_separator(config::HASH_KEY_BULLETPROOF_PLUS_TRANSCRIPT);\n        ge_p3 initial_transcript_p3;\n        rct::hash_to_p3(initial_transcript_p3, rct::hash2rct(crypto::cn_fast_hash(domain_separator.data(), domain_separator.size())));\n        ge_p3_tobytes(initial_transcript.bytes, &initial_transcript_p3);\n\n        init_done = true;\n    }\n\n    // Given two scalar arrays, construct a vector pre-commitment:\n    //\n    // a = (a_0, ..., a_{n-1})\n    // b = (b_0, ..., b_{n-1})\n    //\n    // Outputs a_0*Gi_0 + ... + a_{n-1}*Gi_{n-1} +\n    //         b_0*Hi_0 + ... + b_{n-1}*Hi_{n-1}\n    static rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b)\n    {\n        CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n        CHECK_AND_ASSERT_THROW_MES(a.size() <= maxN*maxM, \"Incompatible sizes of a and maxN\");\n\n        std::vector<MultiexpData> multiexp_data;\n        multiexp_data.reserve(a.size()*2);\n        for (size_t i = 0; i < a.size(); ++i)\n        {\n            multiexp_data.emplace_back(a[i], Gi_p3[i]);\n            multiexp_data.emplace_back(b[i], Hi_p3[i]);\n        }\n        return multiexp(multiexp_data, 2 * a.size());\n    }\n\n    // Helper function used to compute the L and R terms used in the inner-product round function\n    static rct::key compute_LR(size_t size, const rct::key &y, const std::vector<ge_p3> &G, size_t G0, const std::vector<ge_p3> &H, size_t H0, const rct::keyV &a, size_t a0, const rct::keyV &b, size_t b0, const rct::key &c, const rct::key &d)\n    {\n        CHECK_AND_ASSERT_THROW_MES(size + G0 <= G.size(), \"Incompatible size for G\");\n        CHECK_AND_ASSERT_THROW_MES(size + H0 <= H.size(), \"Incompatible size for H\");\n        CHECK_AND_ASSERT_THROW_MES(size + a0 <= a.size(), \"Incompatible size for a\");\n        CHECK_AND_ASSERT_THROW_MES(size + b0 <= b.size(), \"Incompatible size for b\");\n        CHECK_AND_ASSERT_THROW_MES(size <= maxN*maxM, \"size is too large\");\n\n        std::vector<MultiexpData> multiexp_data;\n        multiexp_data.resize(size*2 + 2);\n        rct::key temp;\n        for (size_t i = 0; i < size; ++i)\n        {\n            sc_mul(temp.bytes, a[a0+i].bytes, y.bytes);\n            sc_mul(multiexp_data[i*2].scalar.bytes, temp.bytes, INV_EIGHT.bytes);\n            multiexp_data[i*2].point = G[G0+i];\n\n            sc_mul(multiexp_data[i*2+1].scalar.bytes, b[b0+i].bytes, INV_EIGHT.bytes);\n            multiexp_data[i*2+1].point = H[H0+i];\n        }\n\n        sc_mul(multiexp_data[2*size].scalar.bytes, c.bytes, INV_EIGHT.bytes);\n        ge_p3 H_p3;\n        ge_frombytes_vartime(&H_p3, rct::H.bytes);\n        multiexp_data[2*size].point = H_p3;\n\n        sc_mul(multiexp_data[2*size+1].scalar.bytes, d.bytes, INV_EIGHT.bytes);\n        ge_p3 G_p3;\n        ge_frombytes_vartime(&G_p3, rct::G.bytes);\n        multiexp_data[2*size+1].point = G_p3;\n\n        return multiexp(multiexp_data, 0);\n    }\n\n    // Given a scalar, construct a vector of its powers:\n    //\n    // Output (1,x,x**2,...,x**{n-1})\n    static rct::keyV vector_of_scalar_powers(const rct::key &x, size_t n)\n    {\n        CHECK_AND_ASSERT_THROW_MES(n != 0, \"Need n > 0\");\n\n        rct::keyV res(n);\n        res[0] = rct::identity();\n        if (n == 1)\n            return res;\n        res[1] = x;\n        for (size_t i = 2; i < n; ++i)\n        {\n            sc_mul(res[i].bytes, res[i-1].bytes, x.bytes);\n        }\n        return res;\n    }\n\n    // Given a scalar, construct the sum of its powers from 2 to n (where n is a power of 2):\n    //\n    // Output x**2 + x**4 + x**6 + ... + x**n\n    static rct::key sum_of_even_powers(const rct::key &x, size_t n)\n    {\n        CHECK_AND_ASSERT_THROW_MES((n & (n - 1)) == 0, \"Need n to be a power of 2\");\n        CHECK_AND_ASSERT_THROW_MES(n != 0, \"Need n > 0\");\n\n        rct::key x1 = copy(x);\n        sc_mul(x1.bytes, x1.bytes, x1.bytes);\n\n        rct::key res = copy(x1);\n        while (n > 2)\n        {\n            sc_muladd(res.bytes, x1.bytes, res.bytes, res.bytes);\n            sc_mul(x1.bytes, x1.bytes, x1.bytes);\n            n /= 2;\n        }\n\n        return res;\n    }\n\n    // Given a scalar, return the sum of its powers from 1 to n\n    //\n    // Output x**1 + x**2 + x**3 + ... + x**n\n    static rct::key sum_of_scalar_powers(const rct::key &x, size_t n)\n    {\n        CHECK_AND_ASSERT_THROW_MES(n != 0, \"Need n > 0\");\n\n        rct::key res = ONE;\n        if (n == 1)\n            return res;\n\n        n += 1;\n        rct::key x1 = copy(x);\n\n        const bool is_power_of_2 = (n & (n - 1)) == 0;\n        if (is_power_of_2)\n        {\n            sc_add(res.bytes, res.bytes, x1.bytes);\n            while (n > 2)\n            {\n                sc_mul(x1.bytes, x1.bytes, x1.bytes);\n                sc_muladd(res.bytes, x1.bytes, res.bytes, res.bytes);\n                n /= 2;\n            }\n        }\n        else\n        {\n            rct::key prev = x1;\n            for (size_t i = 1; i < n; ++i)\n            {\n                if (i > 1)\n                    sc_mul(prev.bytes, prev.bytes, x1.bytes);\n                sc_add(res.bytes, res.bytes, prev.bytes);\n            }\n        }\n        sc_sub(res.bytes, res.bytes, ONE.bytes);\n\n        return res;\n    }\n\n    // Given two scalar arrays, construct the weighted inner product against another scalar\n    //\n    // Output a_0*b_0*y**1 + a_1*b_1*y**2 + ... + a_{n-1}*b_{n-1}*y**n\n    static rct::key weighted_inner_product(const epee::span<const rct::key> &a, const epee::span<const rct::key> &b, const rct::key &y)\n    {\n        CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n        rct::key res = rct::zero();\n        rct::key y_power = ONE;\n        rct::key temp;\n        for (size_t i = 0; i < a.size(); ++i)\n        {\n            sc_mul(temp.bytes, a[i].bytes, b[i].bytes);\n            sc_mul(y_power.bytes, y_power.bytes, y.bytes);\n            sc_muladd(res.bytes, temp.bytes, y_power.bytes, res.bytes);\n        }\n        return res;\n    }\n\n    static rct::key weighted_inner_product(const rct::keyV &a, const epee::span<const rct::key> &b, const rct::key &y)\n    {\n        CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n        rct::key res = rct::zero();\n        rct::key y_power = ONE;\n        rct::key temp;\n        for (size_t i = 0; i < a.size(); ++i)\n        {\n            sc_mul(temp.bytes, a[i].bytes, b[i].bytes);\n            sc_mul(y_power.bytes, y_power.bytes, y.bytes);\n            sc_muladd(res.bytes, temp.bytes, y_power.bytes, res.bytes);\n        }\n        return res;\n    }\n\n    // Fold inner-product point vectors\n    static void hadamard_fold(std::vector<ge_p3> &v, const rct::key &a, const rct::key &b)\n    {\n        CHECK_AND_ASSERT_THROW_MES((v.size() & 1) == 0, \"Vector size should be even\");\n        const size_t sz = v.size() / 2;\n        for (size_t n = 0; n < sz; ++n)\n        {\n            ge_dsmp c[2];\n            ge_dsm_precomp(c[0], &v[n]);\n            ge_dsm_precomp(c[1], &v[sz + n]);\n            ge_double_scalarmult_precomp_vartime2_p3(&v[n], a.bytes, c[0], b.bytes, c[1]);\n        }\n        v.resize(sz);\n    }\n\n    // Add vectors componentwise\n    static rct::keyV vector_add(const rct::keyV &a, const rct::keyV &b)\n    {\n        CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n        rct::keyV res(a.size());\n        for (size_t i = 0; i < a.size(); ++i)\n        {\n            sc_add(res[i].bytes, a[i].bytes, b[i].bytes);\n        }\n        return res;\n    }\n\n    // Add a scalar to all elements of a vector\n    static rct::keyV vector_add(const rct::keyV &a, const rct::key &b)\n    {\n        rct::keyV res(a.size());\n        for (size_t i = 0; i < a.size(); ++i)\n        {\n            sc_add(res[i].bytes, a[i].bytes, b.bytes);\n        }\n        return res;\n    }\n\n    // Subtract a scalar from all elements of a vector\n    static rct::keyV vector_subtract(const rct::keyV &a, const rct::key &b)\n    {\n        rct::keyV res(a.size());\n        for (size_t i = 0; i < a.size(); ++i)\n        {\n            sc_sub(res[i].bytes, a[i].bytes, b.bytes);\n        }\n        return res;\n    }\n\n    // Multiply a scalar by all elements of a vector\n    static rct::keyV vector_scalar(const epee::span<const rct::key> &a, const rct::key &x)\n    {\n        rct::keyV res(a.size());\n        for (size_t i = 0; i < a.size(); ++i)\n        {\n            sc_mul(res[i].bytes, a[i].bytes, x.bytes);\n        }\n        return res;\n    }\n\n    // Inversion helper function\n    static rct::key sm(rct::key y, int n, const rct::key &x)\n    {\n        while (n--)\n            sc_mul(y.bytes, y.bytes, y.bytes);\n        sc_mul(y.bytes, y.bytes, x.bytes);\n        return y;\n    }\n\n    // Compute the inverse of a nonzero\n    static rct::key invert(const rct::key &x)\n    {\n        CHECK_AND_ASSERT_THROW_MES(!(x == ZERO), \"Cannot invert zero!\");\n        rct::key _1, _10, _100, _11, _101, _111, _1001, _1011, _1111;\n\n        _1 = x;\n        sc_mul(_10.bytes, _1.bytes, _1.bytes);\n        sc_mul(_100.bytes, _10.bytes, _10.bytes);\n        sc_mul(_11.bytes, _10.bytes, _1.bytes);\n        sc_mul(_101.bytes, _10.bytes, _11.bytes);\n        sc_mul(_111.bytes, _10.bytes, _101.bytes);\n        sc_mul(_1001.bytes, _10.bytes, _111.bytes);\n        sc_mul(_1011.bytes, _10.bytes, _1001.bytes);\n        sc_mul(_1111.bytes, _100.bytes, _1011.bytes);\n\n        rct::key inv;\n        sc_mul(inv.bytes, _1111.bytes, _1.bytes);\n\n        inv = sm(inv, 123 + 3, _101);\n        inv = sm(inv, 2 + 2, _11);\n        inv = sm(inv, 1 + 4, _1111);\n        inv = sm(inv, 1 + 4, _1111);\n        inv = sm(inv, 4, _1001);\n        inv = sm(inv, 2, _11);\n        inv = sm(inv, 1 + 4, _1111);\n        inv = sm(inv, 1 + 3, _101);\n        inv = sm(inv, 3 + 3, _101);\n        inv = sm(inv, 3, _111);\n        inv = sm(inv, 1 + 4, _1111);\n        inv = sm(inv, 2 + 3, _111);\n        inv = sm(inv, 2 + 2, _11);\n        inv = sm(inv, 1 + 4, _1011);\n        inv = sm(inv, 2 + 4, _1011);\n        inv = sm(inv, 6 + 4, _1001);\n        inv = sm(inv, 2 + 2, _11);\n        inv = sm(inv, 3 + 2, _11);\n        inv = sm(inv, 3 + 2, _11);\n        inv = sm(inv, 1 + 4, _1001);\n        inv = sm(inv, 1 + 3, _111);\n        inv = sm(inv, 2 + 4, _1111);\n        inv = sm(inv, 1 + 4, _1011);\n        inv = sm(inv, 3, _101);\n        inv = sm(inv, 2 + 4, _1111);\n        inv = sm(inv, 3, _101);\n        inv = sm(inv, 1 + 2, _11);\n\n        return inv;\n    }\n\n    // Invert a batch of scalars, all of which _must_ be nonzero\n    static rct::keyV invert(rct::keyV x)\n    {\n        rct::keyV scratch;\n        scratch.reserve(x.size());\n\n        rct::key acc = rct::identity();\n        for (size_t n = 0; n < x.size(); ++n)\n        {\n            CHECK_AND_ASSERT_THROW_MES(!(x[n] == ZERO), \"Cannot invert zero!\");\n            scratch.push_back(acc);\n            if (n == 0)\n                acc = x[0];\n            else\n                sc_mul(acc.bytes, acc.bytes, x[n].bytes);\n        }\n\n        acc = invert(acc);\n\n        rct::key tmp;\n        for (int i = x.size(); i-- > 0; )\n        {\n            sc_mul(tmp.bytes, acc.bytes, x[i].bytes);\n            sc_mul(x[i].bytes, acc.bytes, scratch[i].bytes);\n            acc = tmp;\n        }\n\n        return x;\n    }\n\n    // Compute the slice of a vector\n    static epee::span<const rct::key> slice(const rct::keyV &a, size_t start, size_t stop)\n    {\n        CHECK_AND_ASSERT_THROW_MES(start < a.size(), \"Invalid start index\");\n        CHECK_AND_ASSERT_THROW_MES(stop <= a.size(), \"Invalid stop index\");\n        CHECK_AND_ASSERT_THROW_MES(start < stop, \"Invalid start/stop indices\");\n        return epee::span<const rct::key>(&a[start], stop - start);\n    }\n\n    // Update the transcript\n    static rct::key transcript_update(rct::key &transcript, const rct::key &update_0)\n    {\n        rct::key data[2];\n        data[0] = transcript;\n        data[1] = update_0;\n        rct::hash_to_scalar(transcript, data, sizeof(data));\n        return transcript;\n    }\n\n    static rct::key transcript_update(rct::key &transcript, const rct::key &update_0, const rct::key &update_1)\n    {\n        rct::key data[3];\n        data[0] = transcript;\n        data[1] = update_0;\n        data[2] = update_1;\n        rct::hash_to_scalar(transcript, data, sizeof(data));\n        return transcript;\n    }\n\n    // Given a value v [0..2**N) and a mask gamma, construct a range proof\n    BulletproofPlus bulletproof_plus_PROVE(const rct::key &sv, const rct::key &gamma)\n    {\n        return bulletproof_plus_PROVE(rct::keyV(1, sv), rct::keyV(1, gamma));\n    }\n\n    BulletproofPlus bulletproof_plus_PROVE(uint64_t v, const rct::key &gamma)\n    {\n        return bulletproof_plus_PROVE(std::vector<uint64_t>(1, v), rct::keyV(1, gamma));\n    }\n\n    // Given a set of values v [0..2**N) and masks gamma, construct a range proof\n    BulletproofPlus bulletproof_plus_PROVE(const rct::keyV &sv, const rct::keyV &gamma)\n    {\n        // Sanity check on inputs\n        CHECK_AND_ASSERT_THROW_MES(sv.size() == gamma.size(), \"Incompatible sizes of sv and gamma\");\n        CHECK_AND_ASSERT_THROW_MES(!sv.empty(), \"sv is empty\");\n        for (const rct::key &sve: sv)\n            CHECK_AND_ASSERT_THROW_MES(is_reduced(sve), \"Invalid sv input\");\n        for (const rct::key &g: gamma)\n            CHECK_AND_ASSERT_THROW_MES(is_reduced(g), \"Invalid gamma input\");\n\n        init_exponents();\n\n        // Useful proof bounds\n        //\n        // N: number of bits in each range (here, 64)\n        // logN: base-2 logarithm\n        // M: first power of 2 greater than or equal to the number of range proofs to aggregate\n        // logM: base-2 logarithm\n        constexpr size_t logN = 6; // log2(64)\n        constexpr size_t N = 1<<logN;\n        size_t M, logM;\n        for (logM = 0; (M = 1<<logM) <= maxM && M < sv.size(); ++logM);\n        CHECK_AND_ASSERT_THROW_MES(M <= maxM, \"sv/gamma are too large\");\n        const size_t logMN = logM + logN;\n        const size_t MN = M * N;\n\n        rct::keyV V(sv.size());\n        rct::keyV aL(MN), aR(MN);\n        rct::keyV aL8(MN), aR8(MN);\n        rct::key temp;\n        rct::key temp2;\n\n        // Prepare output commitments and offset by a factor of 8**(-1)\n        //\n        // This offset is applied to other group elements as well;\n        //  it allows us to apply a multiply-by-8 operation in the verifier efficiently\n        //  to ensure that the resulting group elements are in the prime-order point subgroup\n        //  and avoid much more constly multiply-by-group-order operations.\n        for (size_t i = 0; i < sv.size(); ++i)\n        {\n            rct::key gamma8, sv8;\n            sc_mul(gamma8.bytes, gamma[i].bytes, INV_EIGHT.bytes);\n            sc_mul(sv8.bytes, sv[i].bytes, INV_EIGHT.bytes);\n            rct::addKeys2(V[i], gamma8, sv8, rct::H);\n        }\n\n        // Decompose values\n        //\n        // Note that this effectively pads the set to a power of 2, which is required for the inner-product argument later.\n        for (size_t j = 0; j < M; ++j)\n        {\n            for (size_t i = N; i-- > 0; )\n            {\n                if (j < sv.size() && (sv[j][i/8] & (((uint64_t)1)<<(i%8))))\n                {\n                    aL[j*N+i] = rct::identity();\n                    aL8[j*N+i] = INV_EIGHT;\n                    aR[j*N+i] = aR8[j*N+i] = rct::zero();\n                }\n                else\n                {\n                    aL[j*N+i] = aL8[j*N+i] = rct::zero();\n                    aR[j*N+i] = MINUS_ONE;\n                    aR8[j*N+i] = MINUS_INV_EIGHT;\n                }\n            }\n        }\n\ntry_again:\n        // This is a Fiat-Shamir transcript\n        rct::key transcript = copy(initial_transcript);\n        transcript = transcript_update(transcript, rct::hash_to_scalar(V));\n\n        // A\n        rct::key alpha = rct::skGen();\n        rct::key pre_A = vector_exponent(aL8, aR8);\n        rct::key A;\n        sc_mul(temp.bytes, alpha.bytes, INV_EIGHT.bytes);\n        rct::addKeys(A, pre_A, rct::scalarmultBase(temp));\n\n        // Challenges\n        rct::key y = transcript_update(transcript, A);\n        if (y == rct::zero())\n        {\n            MINFO(\"y is 0, trying again\");\n            goto try_again;\n        }\n        rct::key z = transcript = rct::hash_to_scalar(y);\n        if (z == rct::zero())\n        {\n            MINFO(\"z is 0, trying again\");\n            goto try_again;\n        }\n        rct::key z_squared;\n        sc_mul(z_squared.bytes, z.bytes, z.bytes);\n\n        // Windowed vector\n        // d[j*N+i] = z**(2*(j+1)) * 2**i\n        //\n        // We compute this iteratively in order to reduce scalar operations.\n        rct::keyV d(MN, rct::zero());\n        d[0] = z_squared;\n        for (size_t i = 1; i < N; i++)\n        {\n            sc_mul(d[i].bytes, d[i-1].bytes, TWO.bytes);\n        }\n\n        for (size_t j = 1; j < M; j++)\n        {\n            for (size_t i = 0; i < N; i++)\n            {\n                sc_mul(d[j*N+i].bytes, d[(j-1)*N+i].bytes, z_squared.bytes);\n            }\n        }\n\n        rct::keyV y_powers = vector_of_scalar_powers(y, MN+2);\n\n        // Prepare inner product terms\n        rct::keyV aL1 = vector_subtract(aL, z);\n\n        rct::keyV aR1 = vector_add(aR, z);\n        rct::keyV d_y(MN);\n        for (size_t i = 0; i < MN; i++)\n        {\n            sc_mul(d_y[i].bytes, d[i].bytes, y_powers[MN-i].bytes);\n        }\n        aR1 = vector_add(aR1, d_y);\n\n        rct::key alpha1 = alpha;\n        temp = ONE;\n        for (size_t j = 0; j < sv.size(); j++)\n        {\n            sc_mul(temp.bytes, temp.bytes, z_squared.bytes);\n            sc_mul(temp2.bytes, y_powers[MN+1].bytes, temp.bytes);\n            sc_mul(temp2.bytes, temp2.bytes, gamma[j].bytes);\n            sc_add(alpha1.bytes, alpha1.bytes, temp2.bytes);\n        }\n\n        // These are used in the inner product rounds\n        size_t nprime = MN;\n        std::vector<ge_p3> Gprime(MN);\n        std::vector<ge_p3> Hprime(MN);\n        rct::keyV aprime(MN);\n        rct::keyV bprime(MN);\n\n        const rct::key yinv = invert(y);\n        rct::keyV yinvpow(MN);\n        yinvpow[0] = ONE;\n        for (size_t i = 0; i < MN; ++i)\n        {\n            Gprime[i] = Gi_p3[i];\n            Hprime[i] = Hi_p3[i];\n            if (i > 0)\n            {\n                sc_mul(yinvpow[i].bytes, yinvpow[i-1].bytes, yinv.bytes);\n            }\n            aprime[i] = aL1[i];\n            bprime[i] = aR1[i];\n        }\n        rct::keyV L(logMN);\n        rct::keyV R(logMN);\n        int round = 0;\n\n        // Inner-product rounds\n        while (nprime > 1)\n        {\n            nprime /= 2;\n\n            rct::key cL = weighted_inner_product(slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size()), y);\n            rct::key cR = weighted_inner_product(vector_scalar(slice(aprime, nprime, aprime.size()), y_powers[nprime]), slice(bprime, 0, nprime), y);\n\n            rct::key dL = rct::skGen();\n            rct::key dR = rct::skGen();\n\n            L[round] = compute_LR(nprime, yinvpow[nprime], Gprime, nprime, Hprime, 0, aprime, 0, bprime, nprime, cL, dL);\n            R[round] = compute_LR(nprime, y_powers[nprime], Gprime, 0, Hprime, nprime, aprime, nprime, bprime, 0, cR, dR);\n\n            const rct::key challenge = transcript_update(transcript, L[round], R[round]);\n            if (challenge == rct::zero())\n            {\n                MINFO(\"challenge is 0, trying again\");\n                goto try_again;\n            }\n\n            const rct::key challenge_inv = invert(challenge);\n\n            sc_mul(temp.bytes, yinvpow[nprime].bytes, challenge.bytes);\n            hadamard_fold(Gprime, challenge_inv, temp);\n            hadamard_fold(Hprime, challenge, challenge_inv);\n\n            sc_mul(temp.bytes, challenge_inv.bytes, y_powers[nprime].bytes);\n            aprime = vector_add(vector_scalar(slice(aprime, 0, nprime), challenge), vector_scalar(slice(aprime, nprime, aprime.size()), temp));\n            bprime = vector_add(vector_scalar(slice(bprime, 0, nprime), challenge_inv), vector_scalar(slice(bprime, nprime, bprime.size()), challenge));\n\n            rct::key challenge_squared;\n            sc_mul(challenge_squared.bytes, challenge.bytes, challenge.bytes);\n            rct::key challenge_squared_inv = invert(challenge_squared);\n            sc_muladd(alpha1.bytes, dL.bytes, challenge_squared.bytes, alpha1.bytes);\n            sc_muladd(alpha1.bytes, dR.bytes, challenge_squared_inv.bytes, alpha1.bytes);\n\n            ++round;\n        }\n\n        // Final round computations\n        rct::key r = rct::skGen();\n        rct::key s = rct::skGen();\n        rct::key d_ = rct::skGen();\n        rct::key eta = rct::skGen();\n\n        std::vector<MultiexpData> A1_data;\n        A1_data.reserve(4);\n        A1_data.resize(4);\n\n        sc_mul(A1_data[0].scalar.bytes, r.bytes, INV_EIGHT.bytes);\n        A1_data[0].point = Gprime[0];\n\n        sc_mul(A1_data[1].scalar.bytes, s.bytes, INV_EIGHT.bytes);\n        A1_data[1].point = Hprime[0];\n\n        sc_mul(A1_data[2].scalar.bytes, d_.bytes, INV_EIGHT.bytes);\n        ge_p3 G_p3;\n        ge_frombytes_vartime(&G_p3, rct::G.bytes);\n        A1_data[2].point = G_p3;\n\n        sc_mul(temp.bytes, r.bytes, y.bytes);\n        sc_mul(temp.bytes, temp.bytes, bprime[0].bytes);\n        sc_mul(temp2.bytes, s.bytes, y.bytes);\n        sc_mul(temp2.bytes, temp2.bytes, aprime[0].bytes);\n        sc_add(temp.bytes, temp.bytes, temp2.bytes);\n        sc_mul(A1_data[3].scalar.bytes, temp.bytes, INV_EIGHT.bytes);\n        ge_p3 H_p3;\n        ge_frombytes_vartime(&H_p3, rct::H.bytes);\n        A1_data[3].point = H_p3;\n\n        rct::key A1 = multiexp(A1_data, 0);\n\n        sc_mul(temp.bytes, r.bytes, y.bytes);\n        sc_mul(temp.bytes, temp.bytes, s.bytes);\n        sc_mul(temp.bytes, temp.bytes, INV_EIGHT.bytes);\n        sc_mul(temp2.bytes, eta.bytes, INV_EIGHT.bytes);\n        rct::key B;\n        rct::addKeys2(B, temp2, temp, rct::H);\n\n        rct::key e = transcript_update(transcript, A1, B);\n        if (e == rct::zero())\n        {\n            MINFO(\"e is 0, trying again\");\n            goto try_again;\n        }\n        rct::key e_squared;\n        sc_mul(e_squared.bytes, e.bytes, e.bytes);\n\n        rct::key r1;\n        sc_muladd(r1.bytes, aprime[0].bytes, e.bytes, r.bytes);\n\n        rct::key s1;\n        sc_muladd(s1.bytes, bprime[0].bytes, e.bytes, s.bytes);\n\n        rct::key d1;\n        sc_muladd(d1.bytes, d_.bytes, e.bytes, eta.bytes);\n        sc_muladd(d1.bytes, alpha1.bytes, e_squared.bytes, d1.bytes);\n\n        return BulletproofPlus(std::move(V), A, A1, B, r1, s1, d1, std::move(L), std::move(R));\n    }\n\n    BulletproofPlus bulletproof_plus_PROVE(const std::vector<uint64_t> &v, const rct::keyV &gamma)\n    {\n        CHECK_AND_ASSERT_THROW_MES(v.size() == gamma.size(), \"Incompatible sizes of v and gamma\");\n\n        // vG + gammaH\n        rct::keyV sv(v.size());\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            sv[i] = rct::zero();\n            sv[i].bytes[0] = v[i] & 255;\n            sv[i].bytes[1] = (v[i] >> 8) & 255;\n            sv[i].bytes[2] = (v[i] >> 16) & 255;\n            sv[i].bytes[3] = (v[i] >> 24) & 255;\n            sv[i].bytes[4] = (v[i] >> 32) & 255;\n            sv[i].bytes[5] = (v[i] >> 40) & 255;\n            sv[i].bytes[6] = (v[i] >> 48) & 255;\n            sv[i].bytes[7] = (v[i] >> 56) & 255;\n        }\n        return bulletproof_plus_PROVE(sv, gamma);\n    }\n\n    struct bp_plus_proof_data_t\n    {\n        rct::key y, z, e;\n        std::vector<rct::key> challenges;\n        size_t logM, inv_offset;\n    };\n\n    // Given a batch of range proofs, determine if they are all valid\n    bool bulletproof_plus_VERIFY(const std::vector<const BulletproofPlus*> &proofs)\n    {\n        init_exponents();\n\n        const size_t logN = 6;\n        const size_t N = 1 << logN;\n\n        // Set up\n        size_t max_length = 0; // size of each of the longest proof's inner-product vectors\n        size_t nV = 0; // number of output commitments across all proofs\n        size_t inv_offset = 0;\n        size_t max_logM = 0; \n\n        std::vector<bp_plus_proof_data_t> proof_data;\n        proof_data.reserve(proofs.size());\n\n        // We'll perform only a single batch inversion across all proofs in the batch,\n        //  since batch inversion requires only one scalar inversion operation.\n        std::vector<rct::key> to_invert;\n        to_invert.reserve(11 * proofs.size()); // maximal size, given the aggregation limit\n\n        for (const BulletproofPlus *p: proofs)\n        {\n            const BulletproofPlus &proof = *p;\n\n            // Sanity checks\n            CHECK_AND_ASSERT_MES(is_reduced(proof.r1), false, \"Input scalar not in range\");\n            CHECK_AND_ASSERT_MES(is_reduced(proof.s1), false, \"Input scalar not in range\");\n            CHECK_AND_ASSERT_MES(is_reduced(proof.d1), false, \"Input scalar not in range\");\n\n            CHECK_AND_ASSERT_MES(proof.V.size() >= 1, false, \"V does not have at least one element\");\n            CHECK_AND_ASSERT_MES(proof.L.size() == proof.R.size(), false, \"Mismatched L and R sizes\");\n            CHECK_AND_ASSERT_MES(proof.L.size() > 0, false, \"Empty proof\");\n\n            max_length = std::max(max_length, proof.L.size());\n            nV += proof.V.size();\n\n            proof_data.push_back({});\n            bp_plus_proof_data_t &pd = proof_data.back();\n\n            // Reconstruct the challenges\n            rct::key transcript = copy(initial_transcript);\n            transcript = transcript_update(transcript, rct::hash_to_scalar(proof.V));\n            pd.y = transcript_update(transcript, proof.A);\n            CHECK_AND_ASSERT_MES(!(pd.y == rct::zero()), false, \"y == 0\");\n            pd.z = transcript = rct::hash_to_scalar(pd.y);\n            CHECK_AND_ASSERT_MES(!(pd.z == rct::zero()), false, \"z == 0\");\n\n            // Determine the number of inner-product rounds based on proof size\n            size_t M;\n            for (pd.logM = 0; (M = 1<<pd.logM) <= maxM && M < proof.V.size(); ++pd.logM);\n            CHECK_AND_ASSERT_MES(proof.L.size() == 6+pd.logM, false, \"Proof is not the expected size\");\n            max_logM = std::max(pd.logM, max_logM);\n\n            const size_t rounds = pd.logM+logN;\n            CHECK_AND_ASSERT_MES(rounds > 0, false, \"Zero rounds\");\n\n            // The inner-product challenges are computed per round\n            pd.challenges.resize(rounds);\n            for (size_t j = 0; j < rounds; ++j)\n            {\n                pd.challenges[j] = transcript_update(transcript, proof.L[j], proof.R[j]);\n                CHECK_AND_ASSERT_MES(!(pd.challenges[j] == rct::zero()), false, \"challenges[j] == 0\");\n            }\n\n            // Final challenge\n            pd.e = transcript_update(transcript,proof.A1,proof.B);\n            CHECK_AND_ASSERT_MES(!(pd.e == rct::zero()), false, \"e == 0\");\n\n            // Batch scalar inversions\n            pd.inv_offset = inv_offset;\n            for (size_t j = 0; j < rounds; ++j)\n                to_invert.push_back(pd.challenges[j]);\n            to_invert.push_back(pd.y);\n            inv_offset += rounds + 1;\n        }\n        CHECK_AND_ASSERT_MES(max_length < 32, false, \"At least one proof is too large\");\n        size_t maxMN = 1u << max_length;\n\n        rct::key temp;\n        rct::key temp2;\n\n        // Final batch proof data\n        std::vector<MultiexpData> multiexp_data;\n        multiexp_data.reserve(nV + (2 * (max_logM + logN) + 3) * proofs.size() + 2 * maxMN);\n        multiexp_data.resize(2 * maxMN);\n\n        const std::vector<rct::key> inverses = invert(std::move(to_invert));\n        to_invert.clear();\n\n        // Weights and aggregates\n        //\n        // The idea is to take the single multiscalar multiplication used in the verification\n        //  of each proof in the batch and weight it using a random weighting factor, resulting\n        //  in just one multiscalar multiplication check to zero for the entire batch.\n        // We can further simplify the verifier complexity by including common group elements\n        //  only once in this single multiscalar multiplication.\n        // Common group elements' weighted scalar sums are tracked across proofs for this reason.\n        //\n        // To build a multiscalar multiplication for each proof, we use the method described in\n        //  Section 6.1 of the preprint. Note that the result given there does not account for\n        //  the construction of the inner-product inputs that are produced in the range proof\n        //  verifier algorithm; we have done so here.\n        rct::key G_scalar = rct::zero();\n        rct::key H_scalar = rct::zero();\n        rct::keyV Gi_scalars(maxMN, rct::zero());\n        rct::keyV Hi_scalars(maxMN, rct::zero());\n\n        int proof_data_index = 0;\n        rct::keyV challenges_cache;\n        std::vector<ge_p3> proof8_V, proof8_L, proof8_R;\n\n        // Process each proof and add to the weighted batch\n        for (const BulletproofPlus *p: proofs)\n        {\n            const BulletproofPlus &proof = *p;\n            const bp_plus_proof_data_t &pd = proof_data[proof_data_index++];\n\n            CHECK_AND_ASSERT_MES(proof.L.size() == 6+pd.logM, false, \"Proof is not the expected size\");\n            const size_t M = 1 << pd.logM;\n            const size_t MN = M*N;\n\n            // Random weighting factor must be nonzero, which is exceptionally unlikely!\n            rct::key weight = ZERO;\n            while (weight == ZERO)\n            {\n                weight = rct::skGen();\n            }\n\n            // Rescale previously offset proof elements\n            //\n            // This ensures that all such group elements are in the prime-order subgroup.\n            proof8_V.resize(proof.V.size()); for (size_t i = 0; i < proof.V.size(); ++i) rct::scalarmult8(proof8_V[i], proof.V[i]);\n            proof8_L.resize(proof.L.size()); for (size_t i = 0; i < proof.L.size(); ++i) rct::scalarmult8(proof8_L[i], proof.L[i]);\n            proof8_R.resize(proof.R.size()); for (size_t i = 0; i < proof.R.size(); ++i) rct::scalarmult8(proof8_R[i], proof.R[i]);\n            ge_p3 proof8_A1;\n            ge_p3 proof8_B;\n            ge_p3 proof8_A;\n            rct::scalarmult8(proof8_A1, proof.A1);\n            rct::scalarmult8(proof8_B, proof.B);\n            rct::scalarmult8(proof8_A, proof.A);\n\n            // Compute necessary powers of the y-challenge\n            rct::key y_MN = copy(pd.y);\n            rct::key y_MN_1;\n            size_t temp_MN = MN;\n            while (temp_MN > 1)\n            {\n                sc_mul(y_MN.bytes, y_MN.bytes, y_MN.bytes);\n                temp_MN /= 2;\n            }\n            sc_mul(y_MN_1.bytes, y_MN.bytes, pd.y.bytes);\n\n            // V_j: -e**2 * z**(2*j+1) * y**(MN+1) * weight\n            rct::key e_squared;\n            sc_mul(e_squared.bytes, pd.e.bytes, pd.e.bytes);\n\n            rct::key z_squared;\n            sc_mul(z_squared.bytes, pd.z.bytes, pd.z.bytes);\n\n            sc_sub(temp.bytes, ZERO.bytes, e_squared.bytes);\n            sc_mul(temp.bytes, temp.bytes, y_MN_1.bytes);\n            sc_mul(temp.bytes, temp.bytes, weight.bytes);\n            for (size_t j = 0; j < proof8_V.size(); j++)\n            {\n                sc_mul(temp.bytes, temp.bytes, z_squared.bytes);\n                multiexp_data.emplace_back(temp, proof8_V[j]);\n            }\n\n            // B: -weight\n            sc_mul(temp.bytes, MINUS_ONE.bytes, weight.bytes);\n            multiexp_data.emplace_back(temp, proof8_B);\n\n            // A1: -weight*e\n            sc_mul(temp.bytes, temp.bytes, pd.e.bytes);\n            multiexp_data.emplace_back(temp, proof8_A1);\n\n            // A: -weight*e*e\n            rct::key minus_weight_e_squared;\n            sc_mul(minus_weight_e_squared.bytes, temp.bytes, pd.e.bytes);\n            multiexp_data.emplace_back(minus_weight_e_squared, proof8_A);\n\n            // G: weight*d1\n            sc_muladd(G_scalar.bytes, weight.bytes, proof.d1.bytes, G_scalar.bytes);\n\n            // Windowed vector\n            // d[j*N+i] = z**(2*(j+1)) * 2**i\n            rct::keyV d(MN, rct::zero());\n            d[0] = z_squared;\n            for (size_t i = 1; i < N; i++)\n            {\n                sc_add(d[i].bytes, d[i-1].bytes, d[i-1].bytes);\n            }\n\n            for (size_t j = 1; j < M; j++)\n            {\n                for (size_t i = 0; i < N; i++)\n                {\n                    sc_mul(d[j*N+i].bytes, d[(j-1)*N+i].bytes, z_squared.bytes);\n                }\n            }\n\n            // More efficient computation of sum(d)\n            rct::key sum_d;\n            sc_mul(sum_d.bytes, TWO_SIXTY_FOUR_MINUS_ONE.bytes, sum_of_even_powers(pd.z, 2*M).bytes);\n\n            // H: weight*( r1*y*s1 + e**2*( y**(MN+1)*z*sum(d) + (z**2-z)*sum(y) ) )\n            rct::key sum_y = sum_of_scalar_powers(pd.y, MN);\n            sc_sub(temp.bytes, z_squared.bytes, pd.z.bytes);\n            sc_mul(temp.bytes, temp.bytes, sum_y.bytes);\n\n            sc_mul(temp2.bytes, y_MN_1.bytes, pd.z.bytes);\n            sc_mul(temp2.bytes, temp2.bytes, sum_d.bytes);\n            sc_add(temp.bytes, temp.bytes, temp2.bytes);\n            sc_mul(temp.bytes, temp.bytes, e_squared.bytes);\n            sc_mul(temp2.bytes, proof.r1.bytes, pd.y.bytes);\n            sc_mul(temp2.bytes, temp2.bytes, proof.s1.bytes);\n            sc_add(temp.bytes, temp.bytes, temp2.bytes);\n            sc_muladd(H_scalar.bytes, temp.bytes, weight.bytes, H_scalar.bytes);\n\n            // Compute the number of rounds for the inner-product argument\n            const size_t rounds = pd.logM+logN;\n            CHECK_AND_ASSERT_MES(rounds > 0, false, \"Zero rounds\");\n\n            const rct::key *challenges_inv = &inverses[pd.inv_offset];\n            const rct::key yinv = inverses[pd.inv_offset + rounds];\n\n            // Compute challenge products\n            challenges_cache.resize(1<<rounds);\n            challenges_cache[0] = challenges_inv[0];\n            challenges_cache[1] = pd.challenges[0];\n            for (size_t j = 1; j < rounds; ++j)\n            {\n                const size_t slots = 1<<(j+1);\n                for (size_t s = slots; s-- > 0; --s)\n                {\n                    sc_mul(challenges_cache[s].bytes, challenges_cache[s/2].bytes, pd.challenges[j].bytes);\n                    sc_mul(challenges_cache[s-1].bytes, challenges_cache[s/2].bytes, challenges_inv[j].bytes);\n                }\n            }\n\n            // Gi and Hi\n            rct::key e_r1_w_y;\n            sc_mul(e_r1_w_y.bytes, pd.e.bytes, proof.r1.bytes);\n            sc_mul(e_r1_w_y.bytes, e_r1_w_y.bytes, weight.bytes);\n            rct::key e_s1_w;\n            sc_mul(e_s1_w.bytes, pd.e.bytes, proof.s1.bytes);\n            sc_mul(e_s1_w.bytes, e_s1_w.bytes, weight.bytes);\n            rct::key e_squared_z_w;\n            sc_mul(e_squared_z_w.bytes, e_squared.bytes, pd.z.bytes);\n            sc_mul(e_squared_z_w.bytes, e_squared_z_w.bytes, weight.bytes);\n            rct::key minus_e_squared_z_w;\n            sc_sub(minus_e_squared_z_w.bytes, ZERO.bytes, e_squared_z_w.bytes);\n            rct::key minus_e_squared_w_y;\n            sc_sub(minus_e_squared_w_y.bytes, ZERO.bytes, e_squared.bytes);\n            sc_mul(minus_e_squared_w_y.bytes, minus_e_squared_w_y.bytes, weight.bytes);\n            sc_mul(minus_e_squared_w_y.bytes, minus_e_squared_w_y.bytes, y_MN.bytes);\n            for (size_t i = 0; i < MN; ++i)\n            {\n                rct::key g_scalar = copy(e_r1_w_y);\n                rct::key h_scalar;\n\n                // Use the binary decomposition of the index\n                sc_muladd(g_scalar.bytes, g_scalar.bytes, challenges_cache[i].bytes, e_squared_z_w.bytes);\n                sc_muladd(h_scalar.bytes, e_s1_w.bytes, challenges_cache[(~i) & (MN-1)].bytes, minus_e_squared_z_w.bytes);\n\n                // Complete the scalar derivation\n                sc_add(Gi_scalars[i].bytes, Gi_scalars[i].bytes, g_scalar.bytes);\n                sc_muladd(h_scalar.bytes, minus_e_squared_w_y.bytes, d[i].bytes, h_scalar.bytes);\n                sc_add(Hi_scalars[i].bytes, Hi_scalars[i].bytes, h_scalar.bytes);\n\n                // Update iterated values\n                sc_mul(e_r1_w_y.bytes, e_r1_w_y.bytes, yinv.bytes);\n                sc_mul(minus_e_squared_w_y.bytes, minus_e_squared_w_y.bytes, yinv.bytes);\n            }\n\n            // L_j: -weight*e*e*challenges[j]**2\n            // R_j: -weight*e*e*challenges[j]**(-2)\n            for (size_t j = 0; j < rounds; ++j)\n            {\n                sc_mul(temp.bytes, pd.challenges[j].bytes, pd.challenges[j].bytes);\n                sc_mul(temp.bytes, temp.bytes, minus_weight_e_squared.bytes);\n                multiexp_data.emplace_back(temp, proof8_L[j]);\n\n                sc_mul(temp.bytes, challenges_inv[j].bytes, challenges_inv[j].bytes);\n                sc_mul(temp.bytes, temp.bytes, minus_weight_e_squared.bytes);\n                multiexp_data.emplace_back(temp, proof8_R[j]);\n            }\n        }\n\n        // Verify all proofs in the weighted batch\n        multiexp_data.emplace_back(G_scalar, rct::G);\n        multiexp_data.emplace_back(H_scalar, rct::H);\n        for (size_t i = 0; i < maxMN; ++i)\n        {\n            multiexp_data[i * 2] = {Gi_scalars[i], Gi_p3[i]};\n            multiexp_data[i * 2 + 1] = {Hi_scalars[i], Hi_p3[i]};\n        }\n        if (!(multiexp(multiexp_data, 2 * maxMN) == rct::identity()))\n        {\n            MERROR(\"Verification failure\");\n            return false;\n        }\n\n        return true;\n    }\n\n    bool bulletproof_plus_VERIFY(const std::vector<BulletproofPlus> &proofs)\n    {\n        std::vector<const BulletproofPlus*> proof_pointers;\n        proof_pointers.reserve(proofs.size());\n        for (const BulletproofPlus &proof: proofs)\n            proof_pointers.push_back(&proof);\n        return bulletproof_plus_VERIFY(proof_pointers);\n    }\n\n    bool bulletproof_plus_VERIFY(const BulletproofPlus &proof)\n    {\n        std::vector<const BulletproofPlus*> proofs;\n        proofs.push_back(&proof);\n        return bulletproof_plus_VERIFY(proofs);\n    }\n}\n", "meta": {"hexsha": "f538201735ff36f71e48e4687d5e775ebd655f6b", "size": 45357, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ringct/bulletproofs_plus.cc", "max_stars_repo_name": "wownero-project/wownero", "max_stars_repo_head_hexsha": "51e7a4178ecaefebbf6c936d67eb108f52865230", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-05-01T21:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:24:36.000Z", "max_issues_repo_path": "src/ringct/bulletproofs_plus.cc", "max_issues_repo_name": "wownero-project/wownero", "max_issues_repo_head_hexsha": "51e7a4178ecaefebbf6c936d67eb108f52865230", "max_issues_repo_licenses": ["MIT"], "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/ringct/bulletproofs_plus.cc", "max_forks_repo_name": "wownero-project/wownero", "max_forks_repo_head_hexsha": "51e7a4178ecaefebbf6c936d67eb108f52865230", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-13T19:06:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T19:06:46.000Z", "avg_line_length": 39.8217734855, "max_line_length": 267, "alphanum_fraction": 0.5741781864, "num_tokens": 13144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.19595851311604393}}
{"text": "#include \"Controller_Cooperative.h\"\n// #include <Eigen/Dense>\n// #include <iostream>\n\nusing namespace Eigen;\n\n\n\n\nnamespace DQ_robotics\n{\n\n\n//----------------------------------------------------------------------------------------------------------\n//##########################################################################################################\n//#################################====================================#########################################\n//#################################                                    #########################################\n//#################################  CLASS : Controller_Cooperative    #########################################\n//#################################                                    #########################################\n//#################################====================================#########################################\n//##########################################################################################################\n//----------------------------------------------------------------------------------------------------------  \n/// * CALL init_default_parameters with robot input (DQ_kinematics)\n//*********************************************************************************************************\n// Controller_Cooperative::Controller_Cooperative(DQ_kinematics robot) : DQ_controller()\n// {    \n//     init_default_parameters(robot);\n//     print_parameters();\n// }\nController_Cooperative::Controller_Cooperative(int num_of_joints) : DQ_controller()\n{    \n    //** NUMBER OF JOINTS (COOPERATIVE)\n    cooperative_number_of_joints = num_of_joints;\n    //** DEBUG MODE:\n    var_FLAG_DEBUG__MODE_JOINTLIMIT_VERIF = true;\n    //** Init Flags   ****[ DEFAULT VALUES ]\n    var_FLAG_CTRL__at_least_one_error     = false;    \n    var_FLAG_CTRL__at_least_one_reference = false;\n    var_FLAG_TRACK_enable_tracking_term   = false;\n    var_FLAG_ROBOT__joint_limits          = false;    \n\n    //** Control Param ****[ DEFAULT VALUES ]\n    var_ctrlgain_kp = 0.05;\n    var_ctrlgain_ki = 0.0; \n    var_ctrlgain_kd = 0.0;\n    var_ctrl_Ki_memorySize = 100.0;\n    var_ctrl_sri_lambda       = 0.01;\n    var_ctrl_srivar_lambda_max = 0.0; //0.05;\n    var_ctrl_srivar_ballsize  = 0.001;\n\n    //** INIT VARIABLES WITHOUT RIGHT SIZE\n    jacobian = MatrixXd::Zero(1,num_of_joints);\n    jacobian_INV = MatrixXd::Zero(num_of_joints,1);\n    error = VectorXd::Zero(1,1);\n    error_integral   = VectorXd::Zero(1,1);\n    error_last_error = VectorXd::Zero(1,1);\n    output_joint_speed  = VectorXd::Zero(num_of_joints,1);\n    output_joints       = VectorXd::Zero(num_of_joints,1);\n    \n    task_abs_pose        = dq_indiv_task(8,num_of_joints);\n    task_abs_translation = dq_indiv_task(4,num_of_joints);\n    task_abs_orientation = dq_indiv_task(4,num_of_joints);\n    task_abs_distance    = dq_indiv_task(1,num_of_joints);\n    task_rel_pose          = dq_indiv_task(4,num_of_joints);\n    task_rel_translation   = dq_indiv_task(4,num_of_joints);\n    task_rel_orientation   = dq_indiv_task(4,num_of_joints);\n    task_rel_distance      = dq_indiv_task(1,num_of_joints);\n\n\n    // INIT JOINT VECTORS\n    var_task_thetas         = VectorXd::Zero(num_of_joints,1);\n    var_task_thetas_Delta   = VectorXd::Zero(num_of_joints,1);        \n\n    // //** Tracking Terms\n    // var_tracking_updateTerm      = MatrixXd::Zero(8,1);    \n    // var_tracking_lastReference   = DQ(0,0,0,0,0,0,0,0);    \n    // var_tracking4_updateTerm      = MatrixXd::Zero(4,1);    \n    // var_tracking4_lastReference   = DQ(0,0,0,0);   \n\n}\n\n\n\n\n\n\n\n                  \n//------------------------------------------------------------------------------------------------------------\n//#############################################################################################################\n//#################################===================================#########################################\n//#################################                                   #########################################\n//#################################  CLASS : Controller_Cooperative   #########################################\n//#################################        SET TASKS : ABSOLUTE       #########################################\n//#################################                                   #########################################\n//#################################===================================#########################################\n//#############################################################################################################\n//-------------------------------------------------------------------------------------------------------------\nvoid Controller_Cooperative::set_task_abs_pose(bool  enable) {\n    if (enable==false)\n        task_abs_pose.enable = false;\n}\nvoid Controller_Cooperative::set_task_abs_dist(bool  enable){\n    if (enable==false)\n        task_abs_distance.enable = false;\n}\nvoid Controller_Cooperative::set_task_abs_trans(bool  enable){\n    if (enable==false)\n        task_abs_translation.enable = false;\n}\nvoid Controller_Cooperative::set_task_abs_orien(bool  enable){\n    if (enable==false)\n        task_abs_orientation.enable = false;    \n}\n//######################################################################################################\n//######################################################################################################\n//######################################################################################################\nvoid Controller_Cooperative::set_task_abs_pose(bool  enable,   DQ task_xm,  DQ task_xd,  MatrixXd  Jacob_abs){\n    if (enable==false) {\n        task_abs_pose.enable = false;\n        return;\n    }\n    task_abs_pose.enable = true;\n    task_abs_pose.jacob = Hminus8(task_xd)*C8()*Jacob_abs;\n    task_abs_pose.error = vec8(DQ(1)-task_xm.conj()*task_xd); \n    // std::cout << \"test err abs: \" << task_abs_pose.error << std::endl; \n    // std::cout << \"test pose xm: \" << task_xm << std::endl;\n    // std::cout << \"test pose xd: \" << task_xd << std::endl;\n\n}\n\nvoid Controller_Cooperative::set_task_abs_dist(bool  enable,   DQ task_xm,  double task_xd,  MatrixXd  Jacob_abs){\n    if (enable==false) {\n        task_abs_distance.enable = false;\n        return;\n    }\n    // task_abs_distance.enable = true;\n    // task_abs_distance.jacob = jacobd(Jacob_abs, task_xm.vec8());    \n    // task_abs_distance.error = - ( task_xd - pow(task_xm.translation().norm(),2)) ;     \n}\nvoid Controller_Cooperative::set_task_abs_trans(bool  enable,  DQ task_xm,  DQ task_xd,  MatrixXd  Jacob_abs){  // TASK_XD in this case must be a translation already!\n    if (enable==false) {\n        task_abs_translation.enable = false;\n        return;\n    }\n    task_abs_translation.enable = true;\n    task_abs_translation.jacob = jacobp(Jacob_abs, task_xm.vec8());    \n    task_abs_translation.error = vec4(task_xd - task_xm.translation());  \n}\nvoid Controller_Cooperative::set_task_abs_orien(bool  enable,  DQ task_xm,  DQ task_xd,  MatrixXd  Jacob_abs){\n    if (enable==false) {\n        task_abs_orientation.enable = false;\n        return;\n    }\n    task_abs_orientation.enable = true;\n    task_abs_orientation.jacob = Hminus4(task_xd)*C4()*Jacob_abs.block(0,0,4,task_abs_orientation.size_num_joints);\n    task_abs_orientation.error = vec4(DQ(1)-task_xm.P().conj()*task_xd.P());      \n}\n\n\n                  \n//------------------------------------------------------------------------------------------------------------\n//#############################################################################################################\n//#################################===================================#########################################\n//#################################                                   #########################################\n//#################################  CLASS : Controller_Cooperative   #########################################\n//#################################        SET TASKS : ABSOLUTE       #########################################\n//#################################                                   #########################################\n//#################################===================================#########################################\n//#############################################################################################################\n//-------------------------------------------------------------------------------------------------------------  \n    void Controller_Cooperative::set_task_rel_pose(bool  enable) {\n    if (enable==false)\n        task_rel_pose.enable = false;\n}\nvoid Controller_Cooperative::set_task_rel_dist(bool  enable){\n    if (enable==false)\n        task_rel_distance.enable = false;\n}\nvoid Controller_Cooperative::set_task_rel_trans(bool  enable){\n    if (enable==false)\n        task_rel_translation.enable = false;\n}\nvoid Controller_Cooperative::set_task_rel_orien(bool  enable){\n    if (enable==false)\n        task_rel_orientation.enable = false;    \n}\n//######################################################################################################\n//######################################################################################################\n//######################################################################################################\nvoid Controller_Cooperative::set_task_rel_pose(bool  enable,   DQ task_xm,  DQ task_xd,  MatrixXd  Jacob_rel){\n    if (enable==false) {\n        task_rel_pose.enable = false;\n        return;\n    }\n    task_rel_pose.enable = true;\n    task_rel_pose.jacob = Hminus8(task_xd)*C8()*Jacob_rel;\n    task_rel_pose.error = 3*vec8(DQ(1)-task_xm.conj()*task_xd);  \n}\n\nvoid Controller_Cooperative::set_task_rel_dist(bool  enable,   DQ task_xm,  double task_xd,  MatrixXd  Jacob_rel){\n    if (enable==false) {\n        task_rel_distance.enable = false;\n        return;\n    }\n    // task_rel_distance.enable = true;\n    // task_rel_distance.jacob = jacobd(Jacob_rel, task_xm.vec8());    \n    // task_rel_distance.error = - ( task_xd - pow(task_xm.translation().norm(),2)) ;     \n}\nvoid Controller_Cooperative::set_task_rel_trans(bool  enable,  DQ task_xm,  DQ task_xd,  MatrixXd  Jacob_rel){  // TASK_XD in this case must be a translation already!\n    if (enable==false) {\n        task_rel_translation.enable = false;\n        return;\n    }\n    task_rel_translation.enable = true;\n    task_rel_translation.jacob = jacobp(Jacob_rel, task_xm.vec8());    \n    task_rel_translation.error = vec4(task_xd - task_xm.translation());  \n}\nvoid Controller_Cooperative::set_task_rel_orien(bool  enable,  DQ task_xm,  DQ task_xd,  MatrixXd  Jacob_rel)\n{\n    if (enable==false) {\n        task_rel_orientation.enable = false;\n        return;\n    }\n    task_rel_orientation.enable = true;\n    task_rel_orientation.jacob = Hminus4(task_xd)*C4()*Jacob_rel.block(0,0,4,task_rel_orientation.size_num_joints);\n    task_rel_orientation.error = vec4(DQ(1)-task_xm.P().conj()*task_xd.P());    \n}\n\n\n\n\n\n\n\n//------------------------------------------------------------------------------------------------------------\n//#############################################################################################################\n//#################################===================================#########################################\n//#################################                                   #########################################\n//#################################  CLASS : Controller_Cooperative   #########################################\n//#################################      GET ERROS                    #########################################\n//#################################                                   #########################################\n//#################################===================================#########################################\n//#############################################################################################################\n//-------------------------------------------------------------------------------------------------------------  \nVectorXd Controller_Cooperative::get_task_abs_error()\n{\n    VectorXd abs_error;\n    int size_dualtask_abs;\n    size_dualtask_abs = 0;    \n    // Check task size\n    if (task_abs_pose.enable)\n        size_dualtask_abs = size_dualtask_abs + 8;\n    else {\n        if (task_abs_translation.enable)\n            size_dualtask_abs = size_dualtask_abs + 4;\n        else {\n            if (task_abs_distance.enable)\n                size_dualtask_abs = size_dualtask_abs + 1;\n        }\n        if (task_abs_orientation.enable)\n            size_dualtask_abs = size_dualtask_abs + 4;\n    }    \n    abs_error = VectorXd::Zero(size_dualtask_abs, 1);\n    int cur_pos=0;\n    // *** GET ABSOLUTE ERROR\n    if (task_abs_pose.enable)     {\n        abs_error.block(cur_pos,0,8,1)   = task_abs_pose.error;\n        cur_pos = cur_pos + 8;\n    }\n    else   {\n        if (task_abs_translation.enable)  {\n            abs_error.block(cur_pos,0,4,1)   = task_abs_translation.error;\n            cur_pos = cur_pos + 4;\n        }\n        else {\n            if (task_abs_distance.enable)  \n                std::cout << \"Not yet implemented\" << std::endl;\n        }\n        if (task_abs_orientation.enable)  \n            abs_error.block(cur_pos,0,4,1)   = task_abs_orientation.error;\n    }    \n    return abs_error;\n}\n\n\nVectorXd Controller_Cooperative::get_task_rel_error()\n{\n    VectorXd rel_error;\n    int size_dualtask_rel;\n    size_dualtask_rel = 0;\n    // Check task size\n    if (task_rel_pose.enable)\n        size_dualtask_rel = size_dualtask_rel + 8;\n    else {\n        if (task_rel_translation.enable)\n            size_dualtask_rel = size_dualtask_rel + 4;\n        else {\n            if (task_rel_distance.enable)\n                size_dualtask_rel = size_dualtask_rel + 1;\n        }\n        if (task_rel_orientation.enable)\n            size_dualtask_rel = size_dualtask_rel + 4;\n    }    \n    rel_error = VectorXd::Zero(size_dualtask_rel, 1);\n    int cur_pos=0;    \n    // *** RELATIVE    \n    if (task_rel_pose.enable)     {\n        rel_error.block(cur_pos,0,8,1)  = task_rel_pose.error;\n        cur_pos = cur_pos + 8;\n    }\n    else   {\n        if (task_rel_translation.enable)  {\n            rel_error.block(cur_pos,0,4,1) = task_rel_translation.error;\n            cur_pos = cur_pos + 4;\n        }\n        else {\n            if (task_rel_distance.enable)  \n                std::cout << \"Not yet implemented\" << std::endl;\n        }\n        if (task_rel_orientation.enable)  \n            rel_error.block(cur_pos,0,4,1)  = task_rel_orientation.error;\n    }    \n    return rel_error;\n}\n\n\n\n\n                  \n//------------------------------------------------------------------------------------------------------------\n//#############################################################################################################\n//#################################===================================#########################################\n//#################################                                   #########################################\n//#################################  CLASS : Controller_Cooperative   #########################################\n//#################################      CONSTRUCTOR JACOB-ERROR      #########################################\n//#################################                                   #########################################\n//#################################===================================#########################################\n//#############################################################################################################\n//-------------------------------------------------------------------------------------------------------------  \nvoid Controller_Cooperative::constructor_jacob_error()\n{\n    int size_dualtask;\n    size_dualtask = 0;\n\n    // Check task size\n    if (task_abs_pose.enable)\n        size_dualtask = size_dualtask + 8;\n    else {\n        if (task_abs_translation.enable)\n            size_dualtask = size_dualtask + 4;\n        else {\n            if (task_abs_distance.enable)\n                size_dualtask = size_dualtask + 1;\n        }\n        if (task_abs_orientation.enable)\n            size_dualtask = size_dualtask + 4;\n    }\n    if (task_rel_pose.enable)\n        size_dualtask = size_dualtask + 8;\n    else {\n        if (task_rel_translation.enable)\n            size_dualtask = size_dualtask + 4;\n        else {\n            if (task_rel_distance.enable)\n                size_dualtask = size_dualtask + 1;\n        }\n        if (task_rel_orientation.enable)\n            size_dualtask = size_dualtask + 4;\n    }\n\n    // RESIZE JACOBIAN AND ERROR\n    if (error_integral.rows() !=  size_dualtask)\n    {\n        error_integral.resize(size_dualtask, NoChange);\n        error_integral = VectorXd::Zero(size_dualtask,1);\n    }\n    \n\n    error.resize(size_dualtask, NoChange);\n    jacobian.resize(size_dualtask, NoChange);\n    jacobian_INV.resize(NoChange, size_dualtask);\n    \n    int cur_pos=0;\n    // CREATE DUAL TASK JACOB AND ERROR\n    // *** ABSOLUTE\n    if (task_abs_pose.enable)     {\n        error.block(cur_pos,0,8,1)                               = task_abs_pose.error;\n        jacobian.block(cur_pos,0,8,cooperative_number_of_joints) = task_abs_pose.jacob;\n        cur_pos = cur_pos + 8;\n    }\n    else   {\n        if (task_abs_translation.enable)  {\n            error.block(cur_pos,0,4,1)                               = task_abs_translation.error;\n            jacobian.block(cur_pos,0,4,cooperative_number_of_joints) = task_abs_translation.jacob;\n            cur_pos = cur_pos + 4;\n        }\n        else {\n            if (task_abs_distance.enable)  {\n                std::cout << \"Not yet implemented\" << std::endl;\n            }\n        }\n        if (task_abs_orientation.enable)  {\n            error.block(cur_pos,0,4,1)                               = task_abs_orientation.error;\n            jacobian.block(cur_pos,0,4,cooperative_number_of_joints) = task_abs_orientation.jacob;\n            cur_pos = cur_pos + 4;            \n        }\n    }    \n    // *** RELATIVE    \n    if (task_rel_pose.enable)     {\n        error.block(cur_pos,0,8,1)                               = task_rel_pose.error;\n        jacobian.block(cur_pos,0,8,cooperative_number_of_joints) = task_rel_pose.jacob;\n        cur_pos = cur_pos + 8;\n    }\n    else   {\n        if (task_rel_translation.enable)  {\n            error.block(cur_pos,0,4,1)                               = task_rel_translation.error;\n            jacobian.block(cur_pos,0,4,cooperative_number_of_joints) = task_rel_translation.jacob;\n            cur_pos = cur_pos + 4;\n        }\n        else {\n            if (task_rel_distance.enable)  {\n                std::cout << \"Not yet implemented\" << std::endl;\n            }\n        }\n        if (task_rel_orientation.enable)  {\n            error.block(cur_pos,0,4,1)                               = task_rel_orientation.error;\n            jacobian.block(cur_pos,0,4,cooperative_number_of_joints) = task_rel_orientation.jacob;\n            cur_pos = cur_pos + 4;            \n        }\n    }    \n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// /**********************************************************************************\n// ####################################################################################\n// ####  CLASS:   Controller_Cooperative                 \n// ####  FUNCTION:   init_default_parameters(DQ_kinematics robot) \n// ####_______________________________________________________________________________  \n//     * SET DEFAULT VALUES FOR THE PARAMETERS OF THE CLASS\n// ####################################################################################    \n// ***********************************************************************************/\n// void Controller_Cooperative::init_default_parameters(DQ_kinematics robot) \n// {    \n//     //** DEBUG MODE:\n//     var_FLAG_DEBUG__MODE_JOINTLIMIT_VERIF = true;\n\n//     var_TASK_SIZE = 8;\n\n//     //** Init Flags   ****[ DEFAULT VALUES ]\n//     var_FLAG_CTRL__at_least_one_error     = false;    \n//     var_FLAG_CTRL__at_least_one_reference = false;\n//     var_FLAG_TRACK_enable_tracking_term   = false;\n//     var_FLAG_ROBOT__joint_limits          = false;\n\n\n//     //** Init Robotic Arm Param\n//     var_ROBOT_DOFs     = (robot.links() - robot.n_dummy());\n//     var_ROBOT_KINE     = robot;\n//     var_ROBOT_JOINTS_LIM__UPPER    = VectorXd::Zero(var_ROBOT_DOFs); // upper_joint_limits;\n//     var_ROBOT_JOINTS_LIM__LOWER    = VectorXd::Zero(var_ROBOT_DOFs); // lower_joint_limits;\n//     var_ROBOT_DUMMY_JOINTS         = var_ROBOT_KINE.dummy(); \n\n//     //** Control Param ****[ DEFAULT VALUES ]\n//     var_ctrl_Kp     = MatrixXd::Identity(8,8);\n//     var_ctrl_Kp     = 0.1*var_ctrl_Kp;\n//     var_ctrl_Ki     = MatrixXd::Zero(8,8);\n//     var_ctrl_Kd     = MatrixXd::Zero(8,8);\n//     var_ctrl_Ki_memorySize = 100.0;\n//     var_ctrl_sri_lambda       = 0.01;\n//     var_ctrl_srivar_lambda_max = 0.0; //0.05;\n//     var_ctrl_srivar_ballsize  = 0.001;\n\n//     //** Init evolution Task variables\n//     var_task_thetas         = MatrixXd(var_ROBOT_DOFs,1);\n//     var_task_thetas_Delta   = MatrixXd::Zero(var_ROBOT_DOFs,1);        \n//     var_task_ERROR          = MatrixXd(8,1);\n//     var_task_ki_error       = MatrixXd::Zero(8,1);\n//     var_task_kd_last_error  = MatrixXd::Zero(8,1);\n\n//     // // TASK JACOB \n//     varJACOB  = dqjacob(var_ROBOT_DOFs, 8);\n//     varJACOB4 = dqjacob(var_ROBOT_DOFs, 4);\n\n\n//     //** Tracking Terms\n//     var_tracking_updateTerm      = MatrixXd::Zero(8,1);    \n//     var_tracking_lastReference   = DQ(0,0,0,0,0,0,0,0);    \n//     var_tracking4_updateTerm      = MatrixXd::Zero(4,1);    \n//     var_tracking4_lastReference   = DQ(0,0,0,0);   \n// }\n\n\n\n\n\n\n\n                  \n//----------------------------------------------------------------------------------------------------------\n//##########################################################################################################\n//#################################================================#########################################\n//#################################                                #########################################\n//#################################  CLASS : Controller_Cooperative    #########################################\n//#################################         CONFIGURATION          #########################################\n//#################################                                #########################################\n//#################################================================#########################################\n//##########################################################################################################\n//----------------------------------------------------------------------------------------------------------  \n\n\n/**********************************************************************************\n####################################################################################\n####  CLASS:   Controller_Cooperative                 \n####  FUNCTION:   set_joint_limits (VectorXd:  upper_limits and lower_limits )\n####_______________________________________________________________________________  \n    * SET the arm joint limits and enable joint limits exclusion\n***********************************************************************************/\nvoid Controller_Cooperative::set_joint_limits(VectorXd upper_joint_limits, VectorXd lower_joint_limits)\n{\n    var_FLAG_ROBOT__joint_limits  = true;\n    var_ROBOT_JOINTS_LIM__UPPER   = upper_joint_limits;\n    var_ROBOT_JOINTS_LIM__LOWER   = lower_joint_limits;\n}\n\n\n\n/**********************************************************************************\n####################################################################################\n####  CLASS:   Controller_Cooperative                 \n####  FUNCTION:   set_control_gains (different options)\n####_______________________________________________________________________________  \n    * Adjust control gains of the PID (just P matrix)\n***********************************************************************************/\n/// * Adjust control gains of the PID (just P gain-scalar)\nvoid Controller_Cooperative::set_control_gains(double kp){\n    var_ctrlgain_kp             = kp;\n}\n/// * Adjust control gains of the PID (just Kp and Ki gain-scalars)\nvoid Controller_Cooperative::set_control_gains(double kp, double ki){\n    var_ctrlgain_kp             = kp;\n    var_ctrlgain_ki             = ki;\n}\n/// * Adjust control gains of the PID (Kp and Ki and Kd gain-scalars)\nvoid Controller_Cooperative::set_control_gains(double kp, double ki, double kd){\n    var_ctrlgain_kp             = kp;\n    var_ctrlgain_ki             = ki;\n    var_ctrlgain_kd             = kd;\n}\n/// * Adjust control gains of the PID (Kp and Ki and Kd gain-scalars | and  integral memory it)\nvoid Controller_Cooperative::set_control_gains(double kp, double ki, const double ki_memory, double kd){\n    set_control_gains(kp, ki, kd);\n    var_ctrl_Ki_memorySize  = ki_memory;   \n}\n\n\n\n\n\n\n/**********************************************************************************\n####################################################################################\n####  CLASS:   Controller_Cooperative                 \n####  FUNCTION:   set_jacob_srivar_paramconst (double:  sri_lambda, srivar_lambda_max, sri_var_lambda_region)\n####_______________________________________________________________________________  \n    * Adjust damping parameters for the SRI variable inverse  \n####################################################################################    \n***********************************************************************************/\nvoid Controller_Cooperative::set_jacob_srivar_paramconst(const double& sri_lambda, const double& sriVar_lambda_max, const double& sriVar_ball_size)\n{\n    var_ctrl_sri_lambda          = sri_lambda;\n    var_ctrl_srivar_lambda_max   = sriVar_lambda_max;\n    var_ctrl_srivar_ballsize     = sriVar_ball_size;\n}\n/// * Adjust damping parameter for the SRI  inverse  \nvoid Controller_Cooperative::set_jacob_srivar_paramconst(const double& sri_lambda)\n{\n    var_ctrl_sri_lambda          = sri_lambda;\n}\n//***************************************************************************************************************\n\n\n\n\n\n\n\n\n//----------------------------------------------------------------------------------------------------------\n//##########################################################################################################\n//#################################================================#########################################\n//#################################                                #########################################\n//#################################  CLASS : Controller_Cooperative    #########################################\n//#################################         CONTROLLERS            #########################################\n//#################################                                #########################################\n//#################################================================#########################################\n//##########################################################################################################\n//----------------------------------------------------------------------------------------------------------\nVectorXd Controller_Cooperative::getNewJointPositions(const DQ reference, const VectorXd thetas)\n{\n    var_task_thetas_Delta = getNewJointVelocities(reference, thetas, 1.0);\n    // Send updated thetas to simulation\n    return (var_task_thetas + var_task_thetas_Delta);\n}\n\nVectorXd Controller_Cooperative::getNewJointPositions(const DQ reference, const VectorXd thetas, double POS_GAIN)\n{\n    var_task_thetas_Delta = getNewJointVelocities(reference, thetas, POS_GAIN);\n    // Send updated thetas to simulation\n    return (var_task_thetas + var_task_thetas_Delta);\n}\nVectorXd Controller_Cooperative::getNewJointVelocities(const DQ reference, const VectorXd thetas)\n{\n    return getNewJointVelocities( reference, thetas, 1.0);     \n}\n\n\nVectorXd Controller_Cooperative::getNewJointVelocities(const DQ reference, const VectorXd thetas, double POS_GAIN)\n{\n    var_task_thetas = thetas; \n    return var_task_thetas;\n}\n\n\n\n\nVectorXd Controller_Cooperative::get_output_pos(const VectorXd theta1, const VectorXd theta2, double POS_GAIN)\n{\n    var_task_thetas_Delta = get_output_vel(theta1, theta2, POS_GAIN);\n    // Send updated thetas to simulation\n    return (var_task_thetas + var_task_thetas_Delta);\n}\nVectorXd Controller_Cooperative::get_output_vel(const VectorXd theta1, const VectorXd theta2, double POS_GAIN)\n{\n    // Init control step:\n    // var_task_thetas = thetas; //This is necessary for the getNewJointPositions to work\n    var_task_thetas.block(0,            0,theta1.rows(),1) = theta1;\n    var_task_thetas.block(theta1.rows(),0,theta2.rows(),1) = theta2;\n    var_task_thetas_Delta = VectorXd::Zero(14,1);\n    constructor_jacob_error();\n\n    // std::cout << \"teste:  size of jacob: \" << jacobian.rows() << \"x\" << jacobian.cols() << std::endl;\n    // std::cout << \"teste:  error: \" << error(0,0) << std::endl;\n\n    // NULL SPACE VARIABLES \n    //*************************************************\n    // MatrixXd NS_Z2;     //  7 x 1\n    // MatrixXd NS_OPT_FCT; // n x 1\n    // MatrixXd NS_JACOB;  //  n x 7\n    // VectorXd        NS_THETA_MEDIO;\n    // VectorXd        NS_MARGIN;\n    // \n    // NS_Z2 = MatrixXd::Zero(7,1);    \n    // NS_OPT_FCT = MatrixXd::Zero(1,1);    \n    // NS_JACOB   = MatrixXd::Zero(1,7);    \n    // NS_THETA_MEDIO    = VectorXd::Zero(var_ROBOT_DOFs); \n    // NS_MARGIN    = VectorXd::Zero(var_ROBOT_DOFs); \n\n    //  \n    // for(int i=0,j=0; i < var_ROBOT_DOFs; i++)   {    \n    //     NS_THETA_MEDIO(i) = 0.5*( var_ROBOT_JOINTS_LIM__UPPER(i) + var_ROBOT_JOINTS_LIM__LOWER(i) );\n    //     NS_MARGIN(i) = 0.03*( var_ROBOT_JOINTS_LIM__UPPER(i) - var_ROBOT_JOINTS_LIM__LOWER(i) );\n    // }        \n    //*************************************************\n\n\n    // bool should_break_loop = false;\n    // while(not should_break_loop){\n\n        // ******  Calculate JACOB (N = Hminus8(x_d) * C8 * J  )  ******\n\n        //****** UPDATE ERROR  ********\n        // var_task_kd_last_error   = var_task_ERROR;\n        // var_task_ki_error = var_task_ERROR + var_ctrl_Ki_memorySize*var_task_ki_error;      \n\n        // if (error.norm() < 0.1)\n            error_integral = error + 0.99*error_integral;\n        // else\n        //     error_integral = 0.001*error;\n\n\n        // //******  INVERSE MATRIX [init] *******  \n        // // varJACOB.get_SVD(current_step_relevant_dof);\n        // // varJACOB.get_INV(var_ctrl_sri_lambda, var_ctrl_srivar_lambda_max, var_ctrl_srivar_ballsize);\n        // varJACOB.get_INV_left( var_ctrl_sri_lambda );       \n\n        MatrixXd tIDENTIDADE;\n        // jacobian_INV = get_jacobinv_left(jacobian, var_ctrl_sri_lambda);\n        tIDENTIDADE = MatrixXd::Identity(14,14);     \n        jacobian_INV =  ((  jacobian.transpose()*jacobian + (var_ctrl_sri_lambda)*(tIDENTIDADE)   ).inverse() )*jacobian.transpose();\n\n        // tIDENTIDADE = MatrixXd::Identity(error.rows(),error.rows());     \n        // jacobian_INV =  jacobian.transpose()*((  jacobian*jacobian.transpose() + (var_ctrl_sri_lambda)*(tIDENTIDADE)   ).inverse() );\n \n        \n\n        // //******  TRACKING ******\n        // var_tracking_updateTerm  = MatrixXd::Zero(8,1);    \n        // if (var_FLAG_TRACK_enable_tracking_term)  {\n        //     if( var_FLAG_CTRL__at_least_one_reference )\n        //       var_tracking_updateTerm = Hminus8( pose_Xd - var_tracking_lastReference )*C8()*vec8( pose_Xm );\n        //     else\n        //       var_FLAG_CTRL__at_least_one_reference = true;        \n        //     var_tracking_lastReference = pose_Xd;            \n        // }\n    \n\n        //******  OUTPUT CONTROL   ******\n        // var_task_thetas_Delta = jacobian_INV*( 0.0105*error + 0.0001*error_integral );\n        var_task_thetas_Delta = jacobian_INV*( 0.006*error + 0.00001*error_integral );\n        // var_task_thetas_Delta = jacobian_INV*( 0.0075*error + 0*error_integral );\n        return var_task_thetas_Delta;\n\n\n        // if( var_FLAG_CTRL__at_least_one_error )\n        //     varPSEUDO_ROBOT.thetas_delta = jacobian_INV*( var_ctrl_Kp*var_task_ERROR + var_ctrl_Ki*var_task_ki_error + var_ctrl_Kd*(var_task_ERROR - var_task_kd_last_error)  - var_tracking_updateTerm );            \n        // else  {\n        //   var_FLAG_CTRL__at_least_one_error = true;\n        //   varPSEUDO_ROBOT.thetas_delta = jacobian_INV*( var_ctrl_Kp*var_task_ERROR + var_ctrl_Ki*var_task_ki_error  - var_tracking_updateTerm );\n        // }\n\n\n        // //**************************************************************************************************************[ TESTE SECTION ]\n        // //**************************************************************************************************************[ TESTE SECTION ]\n        // //**************************************************************************************************************[ TESTE SECTION ]\n        // int NS_OPTIONS = 1;\n        // //******  Null space optimization for joint limits   ******\n        // varJACOB.get_NullSpaceProjector();\n        // NS_OPT_FCT(0,0) = 0;\n        // double nsGAIN= 0.5;\n        \n        // double xgain[7];\n        // xgain[0]=8;\n        // xgain[1]=6;\n        // xgain[2]=4;\n        // xgain[3]=4;\n        // xgain[4]=2;\n        // xgain[5]=1;\n        // xgain[6]=1;\n\n        // //*********************************===>   OPTION 1\n        // if (NS_OPTIONS==1)\n        // {\n        //     for(int i=0,j=0; i < var_ROBOT_DOFs; i++)   {            \n        //         NS_OPT_FCT(0,0) = NS_OPT_FCT(0,0) + 0.5*xgain[i]*( varPSEUDO_ROBOT.thetas(i)-NS_THETA_MEDIO(i) )*( varPSEUDO_ROBOT.thetas(i)-NS_THETA_MEDIO(i) );\n        //         NS_JACOB(0,i) =  xgain[i]*(varPSEUDO_ROBOT.thetas(i)-NS_THETA_MEDIO(i) );\n        //     }\n\n        //     jacobtemp.jacob = NS_JACOB*( varJACOB.jacobNSproject );    \n        //     // NS_Z2 =  dqjacob::get_INV( NS_JACOB*( varJACOB.jacobNSproject ), var_ctrl_sri_lambda )*(  var_ctrl_Kp*NS_OPT_FCT - 1*NS_JACOB*varPSEUDO_ROBOT.thetas_delta );\n        //     NS_Z2 = dqjacob::get_INV( jacobtemp.jacob, var_ctrl_sri_lambda )*(  0.025*NS_OPT_FCT - 0.5*NS_JACOB*varPSEUDO_ROBOT.thetas_delta );\n\n        //     // extra info\n        //     // jacobtemp.get_SVD(jacobtemp.jacob.rows());\n        //     // std::cout << \"MIN SING VALUES: \" << jacobtemp.singValues(0) << jacobtemp.singValues(1) << jacobtemp.singValues(2) << jacobtemp.singValues(3) << jacobtemp.singValues(4) << jacobtemp.singValues(5) << jacobtemp.singValues(6) << std::endl;\n        //     // std::cout << \"MIN SING VALUES: \" << jacobtemp.singValues  << std::endl;\n        //     // std::cout << \"MIN SING VALUES: \" << jacobtemp.singValues.size() << std::endl;\n            \n        //     // // NEW OUTPUT WITH NULL SPACE\n        //     varPSEUDO_ROBOT.thetas_delta  =  varPSEUDO_ROBOT.thetas_delta + 0.0008*( varJACOB.jacobNSproject )*NS_Z2;\n        // }\n\n\n        // //*********************************===>   OPTION 2\n        // if ( (NS_OPTIONS==2) || (NS_OPTIONS==3) )\n        // {\n        //     double jointslimdiv = 0;\n        \n        //     for(int i=0,j=0; i < var_ROBOT_DOFs; i++)   {  \n        //         NS_JACOB(0,i)  = 0;   \n        //         jointslimdiv  = varPSEUDO_ROBOT.thetas(i)-var_ROBOT_JOINTS_LIM__LOWER(i);\n        //         if ( jointslimdiv  < NS_MARGIN(i) ) {\n        //             NS_OPT_FCT(0,0) = NS_OPT_FCT(0,0) + nsGAIN*0.5*pow(  (1/NS_MARGIN(i))*( NS_MARGIN(i)-jointslimdiv)  ,2); \n        //             NS_JACOB(0,i) =  -nsGAIN*(   (1/NS_MARGIN(i))*std::abs(  NS_MARGIN(i) - jointslimdiv )    ); \n        //             std::cout << \"bottom: \" << i << \"=> (\" << varPSEUDO_ROBOT.thetas(i) << \" x \" << var_ROBOT_JOINTS_LIM__LOWER(i)  << \")= \"<< jointslimdiv <<\" ==>  \" <<  NS_JACOB(0,i) << std::endl;\n        //         }\n        //         else {\n        //             jointslimdiv  = var_ROBOT_JOINTS_LIM__UPPER(i)-varPSEUDO_ROBOT.thetas(i);\n        //             if ( jointslimdiv  < NS_MARGIN(i) ) {\n        //                 NS_OPT_FCT(0,0) = NS_OPT_FCT(0,0) + nsGAIN*0.5*pow(   (1/NS_MARGIN(i))*( NS_MARGIN(i)-jointslimdiv )    ,2); \n        //                 NS_JACOB(0,i) =  +nsGAIN*(  (1/NS_MARGIN(i))*std::abs( NS_MARGIN(i)-jointslimdiv )   ); \n        //                 std::cout << \"top: \" << i << \"=> (\" << varPSEUDO_ROBOT.thetas(i) << \" x \" << var_ROBOT_JOINTS_LIM__UPPER(i)  << \")= \"<< jointslimdiv <<\" ==>  \" <<  NS_JACOB(0,i) << std::endl;\n        //             }\n        //             else\n        //             {\n        //                 NS_OPT_FCT(0,0) = NS_OPT_FCT(0,0); \n        //                 NS_JACOB(0,i) =  0.00; \n        //             }\n        //         }   \n        //     }\n\n        //     if (NS_OPTIONS==2) \n        //     {\n        //         jacobtemp.jacob = NS_JACOB*( varJACOB.jacobNSproject );    \n        //         NS_Z2 = dqjacob::get_INV( jacobtemp.jacob, var_ctrl_sri_lambda )*(  0.5*NS_OPT_FCT - 0.1*NS_JACOB*varPSEUDO_ROBOT.thetas_delta );        \n\n        //         // // NEW OUTPUT WITH NULL SPACE\n        //         varPSEUDO_ROBOT.thetas_delta  =  varPSEUDO_ROBOT.thetas_delta + 0.5*( varJACOB.jacobNSproject )*NS_Z2;\n        //         // varPSEUDO_ROBOT.thetas_delta  =  varPSEUDO_ROBOT.thetas_delta ; // + 1*( varJACOB.jacobNSproject )*NS_Z2;\n        //         // varPSEUDO_ROBOT.thetas_delta  =  varPSEUDO_ROBOT.thetas_delta + 0.5*( varJACOB.jacobNSproject )*dqjacob::get_INV( NS_JACOB, 0 )*NS_OPT_FCT ;\n        //     }\n        //     else\n        //     {\n        //         // std::cout << \"FCT: \" << std::endl << NS_JACOB.transpose() << std::endl ;   \n        //         // varPSEUDO_ROBOT.thetas_delta  =  varPSEUDO_ROBOT.thetas_delta - (0.2)*NS_JACOB.transpose();     \n        //         varPSEUDO_ROBOT.thetas_delta  =  varPSEUDO_ROBOT.thetas_delta - (2)*NS_JACOB.transpose();     \n        //     }\n        //     // extra info\n        //     // jacobtemp.get_SVD(jacobtemp.jacob.rows());\n        //     // std::cout << \"jacob :   \" << NS_OPT_FCT  << std::endl << jacobtemp.jacob << std::endl;\n        //     // std::cout << \"jacob inv:   \"  <<  std::endl << varJACOB.jacob*dqjacob::get_INV( jacobtemp.jacob, 0 ) << std::endl;\n        // }\n        // if ( (NS_OPTIONS<0) || (NS_OPTIONS>3) )\n        //     varPSEUDO_ROBOT.thetas_delta  =  varPSEUDO_ROBOT.thetas_delta;\n        // // \n        // //**************************************************************************************************************[ TESTE SECTION ]\n        // //**************************************************************************************************************[ TESTE SECTION ]\n        //**************************************************************************************************************[ TESTE SECTION ]\n\n        // //Update delta_thetas for FUTURE THETA calculation\n        // for(int i=0,j=0; i < var_ROBOT_DOFs; i++)   {\n        //     if(varPSEUDO_ROBOT.dummy_joints_marker(i) == 0) {\n        //         var_task_thetas_Delta(i) = varPSEUDO_ROBOT.thetas_delta(j);\n        //         ++j;\n        //     }\n        // }\n        // ******  OUTPUT THETAS (POSSIBLE)   ******\n        // varPSEUDO_ROBOT.thetas_output = var_task_thetas + var_task_thetas_Delta;\n\n    // }//While not should_break_loop\n\n\n\n}\n\n\n\n\n\n\n\n\n//  bool Controller_Cooperative::joint_limit_verification_step() \n//  {\n//     bool returnBreakLoop = true;\n//     int j=0;\n//     //For all joints\n//     for(int i = 0; i < var_ROBOT_DOFs; i++){\n\n//         //If joint is not yet marked for not being considered in the minimization\n//         if(varPSEUDO_ROBOT.dummy_joints_marker(i) == 0){\n\n//             //If the controller is trying to put a joint further than any of its limits\n//             if(    varPSEUDO_ROBOT.thetas_output(i) > var_ROBOT_JOINTS_LIM__UPPER(i)\n//                 || varPSEUDO_ROBOT.thetas_output(i) < var_ROBOT_JOINTS_LIM__LOWER(i) )\n//             {\n\n//                 //If the joint was already saturated sometime ago\n//                 double ep = 1.e-05;\n//                 if (    var_task_thetas(i) > var_ROBOT_JOINTS_LIM__UPPER(i) - ep \n//                      || var_task_thetas(i) < var_ROBOT_JOINTS_LIM__LOWER(i) + ep){\n\n//                     varPSEUDO_ROBOT.dummy_joints_marker(i) = 1; //Mark it to be ignored in the minization\n//                     //std::cout << std::endl << \"Joint \" << i << \" will be ignored in the next controller step.\";\n//                     varPSEUDO_ROBOT.dh_matrix(4,i) = 1;          //Set matrix as dummy.\n//                     varPSEUDO_ROBOT.dh_matrix(0,i) = var_task_thetas(i); //Set matrix theta as a fixed value.\n//                     returnBreakLoop = false;\n//                     if (var_FLAG_DEBUG__MODE_JOINTLIMIT_VERIF)\n//                         std::cout << \"[WARN]:[Eliminate Joint \" << i <<\"]: It has saturated its limits sometime ago. Value:\" << var_task_thetas(i) << std::endl;\n//                 }\n//                 //If the joint was not yet saturated and the controller wants to saturate it\n//                 else{\n//                     // Saturate the joint in this step.\n//                     if   ( varPSEUDO_ROBOT.thetas_output(i) > var_ROBOT_JOINTS_LIM__UPPER(i) ){\n//                         var_task_thetas_Delta(i) = var_ROBOT_JOINTS_LIM__UPPER(i) - var_task_thetas(i);\n//                         if (var_FLAG_DEBUG__MODE_JOINTLIMIT_VERIF)\n//                             std::cout << \"[WARN]: Joint (\" << i <<\") is going to saturate its limits. Value:\" <<  varPSEUDO_ROBOT.thetas_output(i) << std::endl;\n//                     }\n//                     else if ( varPSEUDO_ROBOT.thetas_output(i) < var_ROBOT_JOINTS_LIM__LOWER(i) ){\n//                         var_task_thetas_Delta(i) = var_ROBOT_JOINTS_LIM__LOWER(i) - var_task_thetas(i);\n//                         if (var_FLAG_DEBUG__MODE_JOINTLIMIT_VERIF)\n//                             std::cout << \"[WARN]: Joint (\" << i <<\") is going to saturate its limits. Value:\" <<  varPSEUDO_ROBOT.thetas_output(i) << std::endl;\n//                     }\n//                     else{\n//                         std::cout << std::endl << \"Something is really wrong\";\n//                     }\n//                     //The joint should still be considered in the minimizations.\n//                     varPSEUDO_ROBOT.thetas(j) = var_task_thetas(i);\n//                     ++j;    \n//                 }\n\n  \n//             }\n//             //If the controller is not trying to put this joint further than any of its limits, we consider the velocity given normally\n//             else{\n//                 var_task_thetas_Delta(i) = varPSEUDO_ROBOT.thetas_delta(j);\n//                 varPSEUDO_ROBOT.thetas(j) = var_task_thetas(i);\n//                 ++j;      \n//             }\n//         }\n//         //If joint was marked to be ignored, it shall be ignored.\n//         else{\n//             var_task_thetas_Delta(i) = 0;\n//             if (var_FLAG_DEBUG__MODE_JOINTLIMIT_VERIF)\n//                 std::cout << \"[WARN]: Ignore move in Joint (\" << i <<\") due to joint limits\" << std::endl;\n//         }\n\n//     }\n//     if( j == 0 ){\n//         std::cout << std::endl << \"Robot will be unable to get out of this configuration using this controller.\";\n//         var_task_thetas_Delta = VectorXd::Zero(var_ROBOT_DOFs);\n//         returnBreakLoop = true;\n//         return returnBreakLoop;       \n//     }\n//     if(not returnBreakLoop){\n//         varPSEUDO_ROBOT.KINE =  DQ_kinematics(varPSEUDO_ROBOT.dh_matrix);  //Change DH\n//         varPSEUDO_ROBOT.KINE.set_base(var_ROBOT_KINE.base()); \n//         varPSEUDO_ROBOT.KINE.set_effector(var_ROBOT_KINE.effector());            \n//         varPSEUDO_ROBOT.thetas.conservativeResize(j);           //Resize pseudothetas\n//         if (var_FLAG_DEBUG__MODE_JOINTLIMIT_VERIF)\n//             std::cout << \"=========================================================\" << std::endl;        \n//     } \n//     return returnBreakLoop;     \n\n//     std::cout << std::endl;           \n     \n// }\n\n\n\n\nvoid Controller_Cooperative::enableTrackingTerm(const bool bool_falseortrue)\n{\n    var_FLAG_TRACK_enable_tracking_term = bool_falseortrue;\n}\n\n\n\n\n\n\n\n\n//----------------------------------------------------------------------------------------------------------\n//##########################################################################################################\n//#################################================================#########################################\n//#################################                                #########################################\n//#################################  SUBCLASS:    dqjacob          #########################################\n//#################################                                #########################################\n//#################################================================#########################################\n//##########################################################################################################\n//----------------------------------------------------------------------------------------------------------\n\n\n\n\n// /*********************************************************\n// ##########################################################\n// ####  SUBCLASS:   dqjacob                 \n// ####  FUNCTION:   get_SVD : (int DOFs) -> void \n// ####______________________________________________________  \n//     * Update the svd, singValues, min_singValue, min_U_svd using the jacobian from the subclass, and the input arg.\n// ##########################################################\n// **********************************************************/\n// void Controller_Cooperative::dqjacob::get_SVD(int relevant_DOFs)\n// {\n//     svd.compute(jacob, ComputeFullU);\n//     singValues    = svd.singularValues();  \n//     min_singValue = singValues( relevant_DOFs - 1);\n//     min_U_svd     = svd.matrixU().col( relevant_DOFs - 1);               \n// }\n\n\n\n// /*********************************************************\n// ##########################################################\n// ####  SUBCLASS:   dqjacob                 \n// ####  FUNCTION:   get_INV : (double lambda) -> void \n// ####______________________________________________________  \n//     * Calculate the Jacobian Inverse using SRI (sing robust inverse) with lamda\n// ##########################################################\n// **********************************************************/\n// void Controller_Cooperative::dqjacob::get_INV( double lambda )\n// {      \n//     MatrixXd IDENTIDADE;\n//     IDENTIDADE = Controller_Cooperative::getIDENTMATRIX_WITH_PROPER_SIZE(task_size); \n//     jacobInv =  (jacob.transpose())*((  jacob*jacob.transpose() \n//                     + (lambda)*(IDENTIDADE)   ).inverse() );\n// }\n\n// void Controller_Cooperative::dqjacob::get_INV_left( double lambda )\n// {      \n//     MatrixXd IDENTIDADE;\n//     IDENTIDADE = Controller_Cooperative::getIDENTMATRIX_WITH_PROPER_SIZE(jacob.cols()); \n\n//     // Matrix<double,8,1> kp_diagonal(8,1);\n//     // // kp_diagonal << 0.3,0.3,0.3,0.3,1,1,1,1;\n//     // kp_diagonal << 1000,1000,1000,1000,1000,1000,1000,1;\n//     // IDENTIDADE.diagonal() = kp_diagonal; \n\n//     jacobInv =  ((  jacob.transpose()*jacob + (lambda)*(IDENTIDADE)   ).inverse() )*jacob.transpose();\n// }\n\n// /// * Returns the inverse of a jacob_data using SRI (sing robust inverse) with lamda\n// MatrixXd Controller_Cooperative::dqjacob::get_INV( MatrixXd jacob_data, double lambda )\n// {      \n//     MatrixXd IDENTIDADE;\n//     MatrixXd outpumatrix;\n//     IDENTIDADE = Controller_Cooperative::getIDENTMATRIX_WITH_PROPER_SIZE( jacob_data.rows()  ); \n//     // outpumatrix = jacob_data.transpose();    \n//     outpumatrix = (jacob_data.transpose())*((  jacob_data*jacob_data.transpose() + (lambda)*(IDENTIDADE)   ).inverse() );\n//     return  outpumatrix; \n// }\n\n\n\n\n// /*********************************************************\n// ##########################################################\n// ####  SUBCLASS:   dqjacob                 \n// ####  FUNCTION:   get_INV : (double lambda, srivar_lambda_max, srivar_lambda_region) -> void \n// ####______________________________________________________  \n//     * Calculate the Jacobian Inverse using SRI-VAR (sing robust inverse) with lamda, lambda_var, lambda_var_region\n// ##########################################################\n// **********************************************************/\n// void Controller_Cooperative::dqjacob::get_INV(double lambda, double srivar_lamda_max, double srivar_lamda_region )\n// {\n//     double      SRI_VAR_LAMBDA;\n//     MatrixXd    IDENTIDADE;             \n//     SRI_VAR_LAMBDA  = srivar_lamda_max;  \n//     if (task_size==8)\n//         IDENTIDADE = Matrix<double,8,8>::Identity();\n//     else\n//         IDENTIDADE = Matrix<double,4,4>::Identity();   \n\n//     if (min_singValue < srivar_lamda_region)\n//         SRI_VAR_LAMBDA = (  1-(min_singValue/srivar_lamda_region)*(min_singValue/srivar_lamda_region)  )*srivar_lamda_max;\n//     // Get JACOBIAN INVERSE:\n//     jacobInv =  (jacob.transpose())*((  jacob*jacob.transpose() \n//                     + (lambda)*(IDENTIDADE) \n//                     + (SRI_VAR_LAMBDA)*(min_U_svd*min_U_svd.transpose())  ).inverse() );\n// }  \n// ////// * Returns the inverse of a jacob_data using SRI-VAR with lamda, lambda_var, lambda_var_region\n\n\n\n\n\n\n} // END OF NAMESPACE\n\n\n\n     \n\n\n\n", "meta": {"hexsha": "e130db587610ed95ce105d09f76fb5ba7a41cbcc", "size": 49907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/Controller_Cooperative.cpp", "max_stars_repo_name": "birlrobotics/birlBaxter_demos", "max_stars_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-12-29T11:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T00:49:10.000Z", "max_issues_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/Controller_Cooperative.cpp", "max_issues_repo_name": "birlrobotics/birlBaxter_demos", "max_issues_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-20T05:52:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-30T09:07:56.000Z", "max_forks_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/Controller_Cooperative.cpp", "max_forks_repo_name": "birlrobotics/birlBaxter_demos", "max_forks_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-02-10T06:12:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T11:56:07.000Z", "avg_line_length": 46.5550373134, "max_line_length": 253, "alphanum_fraction": 0.463281704, "num_tokens": 11035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.1958922843631508}}
{"text": "#include <NTL/config.h>\n\n#if (defined(NTL_GF2X_LIB) && defined(NTL_THREADS))\n// we require v1.2 or later\n\n#include <gf2x.h>\n\n#ifndef GF2X_VERSION_MAJOR\n// versions after v1.2 should define GF2X_VERSION_MAJOR\n\nextern \"C\" {\n\nstruct gf2x_ternary_fft_info_s;\n\ntypedef const struct gf2x_ternary_fft_info_s * gf2x_ternary_fft_info_srcptr;\n\nint gf2x_ternary_fft_compatible(gf2x_ternary_fft_info_srcptr o1, gf2x_ternary_fft_info_srcptr o2);\n\n}\n\n// This will fail to link for versions prior to v1.2.\nvoid fun()\n{\n   gf2x_ternary_fft_compatible(0, 0);\n}\n\n#endif\n\n#endif\n\nint main()\n{\n   return 0;\n}\n", "meta": {"hexsha": "08773da1d8c2b7d72af67ec384504494e3623d16", "size": 589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libNTL/unix.d/src/gf2x_version_1_2_or_later_required.cpp", "max_stars_repo_name": "textbrowser/spot-on", "max_stars_repo_head_hexsha": "4cf5628bc588cf2de6bd070abfdc78401a965cc0", "max_stars_repo_licenses": ["PostgreSQL"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T06:14:16.000Z", "max_issues_repo_path": "libNTL/unix.d/src/gf2x_version_1_2_or_later_required.cpp", "max_issues_repo_name": "kalilearner/spot-on", "max_issues_repo_head_hexsha": "6f2d802c87a88e3001cb8238f65b5d7253bc6f49", "max_issues_repo_licenses": ["PostgreSQL"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-10-18T18:26:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:50:04.000Z", "max_forks_repo_path": "libNTL/unix.d/src/gf2x_version_1_2_or_later_required.cpp", "max_forks_repo_name": "kalilearner/spot-on", "max_forks_repo_head_hexsha": "6f2d802c87a88e3001cb8238f65b5d7253bc6f49", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T07:59:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T10:27:23.000Z", "avg_line_length": 16.8285714286, "max_line_length": 98, "alphanum_fraction": 0.765704584, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19589227684112068}}
{"text": "/*\nThis code is based on the original code by Quentin \"Leph\" Rouxel and Team Rhoban.\nThe original files can be found at:\nhttps://github.com/Rhoban/model/\n*/\n#ifndef QUINTICWALKNODE_HPP\n#define QUINTICWALKNODE_HPP\n\n#include <iostream>\n#include <string>\n#include <Eigen/Dense>\n#include <chrono>\n\n#include <ros/ros.h>\n\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PointStamped.h>\n#include <visualization_msgs/Marker.h>\n#include <std_msgs/String.h>\n#include <std_msgs/Float64.h>\n#include <std_msgs/Char.h>\n#include <sensor_msgs/JointState.h>\n#include <sensor_msgs/Imu.h>\n#include <nav_msgs/Odometry.h>\n#include <std_srvs/SetBool.h>\n#include <std_srvs/Trigger.h>\n#include <moveit_msgs/RobotState.h>\n#include <humanoid_league_msgs/RobotControlState.h>\n#include <bitbots_quintic_walk/WalkingDebug.h>\n#include <bitbots_msgs/JointCommand.h>\n#include <bitbots_msgs/FootPressure.h>\n\n#include <dynamic_reconfigure/server.h>\n#include <eigen_conversions/eigen_msg.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_broadcaster.h>\n#include <moveit/robot_model_loader/robot_model_loader.h>\n#include <moveit/kinematics_base/kinematics_base.h>\n#include <moveit/move_group_interface/move_group_interface.h>\n\n#include <bitbots_quintic_walk/bitbots_quintic_walk_paramsConfig.h>\n#include \"bitbots_ik/AnalyticIKSolver.hpp\"\n#include \"bitbots_ik/BioIKSolver.hpp\"\n#include \"bitbots_quintic_walk/WalkEngine.hpp\"\n#include \"DspSDK/DspHandler.h\"\n#include <std_msgs/Bool.h>\n#include <unistd.h>\n\n\nclass QuinticWalkingNode {\npublic:\n    QuinticWalkingNode();\n\n    /**\n     * This is the main loop which takes care of stopping and starting of the walking.\n     * A small state machine is tracking in which state the walking is and builds the trajectories accordingly.\n     */\n    void run();\n\n    /**\n     * Dynamic reconfigure callback. Takes in new parameters and applies them to the needed software parts\n     */\n    void reconf_callback(bitbots_quintic_walk::bitbots_quintic_walk_paramsConfig &config, uint32_t level);\n\n    /**\n     * Initialize internal WalkEngine to correctly zeroed, usable state\n     */\n    void initializeEngine();\n\n    bool SetHeadMoveValid(std_srvs::SetBool::Request& req,\n                          std_srvs::SetBool::Response& res);\n\n    bool SetSensorEnableValid(std_srvs::SetBool::Request& req,\n                              std_srvs::SetBool::Response& res);\n\n    bool ResetOdometry(std_srvs::SetBool::Request& req,\n                       std_srvs::SetBool::Response& res);\n\n    bool SetSpecialGaitValid(std_srvs::SetBool::Request& req,\n                             std_srvs::SetBool::Response& res);\n\n    bool DoLeftKick(std_srvs::Trigger::Request& req,\n                    std_srvs::Trigger::Response& res);\n\n    bool DoRightKick(std_srvs::Trigger::Request& req,\n                     std_srvs::Trigger::Response& res);\n\n    bool DoStandFront(std_srvs::Trigger::Request& req,\n                      std_srvs::Trigger::Response& res);\n\n    bool DoStandBack(std_srvs::Trigger::Request& req,\n                     std_srvs::Trigger::Response& res);\n\n    bool DoWalkKickLeft(std_srvs::Trigger::Request& req,\n                        std_srvs::Trigger::Response& res);\n\n    bool DoWalkKickRight(std_srvs::Trigger::Request& req,\n                         std_srvs::Trigger::Response& res);\n\n    bool SetTorqueEnable(std_srvs::SetBool::Request& req,\n                         std_srvs::SetBool::Response& res);\n\n    bool SetGaitValid(std_srvs::SetBool::Request& req,\n                      std_srvs::SetBool::Response& res);\n\n    bool ResetGait(std_srvs::SetBool::Request& req,\n                   std_srvs::SetBool::Response& res);\n\n    bool GetSpecialGaitPending(std_srvs::Trigger::Request& req,\n                               std_srvs::Trigger::Response& res);\n\n    bool GetOdometryResetPending(std_srvs::Trigger::Request& req,\n                                 std_srvs::Trigger::Response& res);\n\n    bool GaitResetPending(std_srvs::Trigger::Request& req,\n                          std_srvs::Trigger::Response& res);\n\n    bool GetWalkKickPending(std_srvs::Trigger::Request& req,\n                            std_srvs::Trigger::Response& res);\n\n   private:\n    void publishControllerCommands(std::vector<std::string> joint_names, std::vector<double> positions);\n\n    void publishDebug(tf::Transform &trunk_to_support_foot, tf::Transform &trunk_to_flying_foot);\n\n    void publishMarker(std::string name_space, std::string frame, geometry_msgs::Pose pose, float r, float g, float b,\n                       float a);\n\n    void publishMarkers();\n\n    void publishOdometry();\n\n    void cmdVelCb(geometry_msgs::Twist msg);\n\n    void headPosCb(sensor_msgs::JointState msg);\n\n    void imuCb(sensor_msgs::Imu msg);\n\n    void pressureCb(bitbots_msgs::FootPressure msg);\n\n    void robStateCb(humanoid_league_msgs::RobotControlState msg);\n\n    void jointStateCb(sensor_msgs::JointState msg);\n\n    void kickCb(std_msgs::BoolConstPtr msg);\n\n    void cop_l_cb(const geometry_msgs::PointStamped msg);\n\n    void cop_r_cb(const geometry_msgs::PointStamped msg);\n\n    void calculateJointGoals();\n\n    double getTimeDelta();\n\n    void SetDspCommand();\n    void ClearDspValidState();\n    void GetDataFromDsp();\n\n    bool _fake_mode;\n    bool _debugActive;\n    bool _simulation_active;\n\n    bool _first_run;\n\n    double _engineFrequency;\n\n    bool _phaseResetActive;\n    double _phaseResetPhase;\n    double _groundMinPressure;\n    bool _copStopActive;\n    double _copXThreshold;\n    double _copYThreshold;\n    bool _pressureStopActive;\n    double _ioPressureThreshold;\n    double _fbPressureThreshold;\n\n    bool _imuActive;\n    double _imu_pitch_threshold;\n    double _imu_roll_threshold;\n    double _imu_pitch_vel_threshold;\n    double _imu_roll_vel_threshold;\n\n\n    bool _publishOdomTF;\n    int _odomPubFactor;\n    std::chrono::time_point<std::chrono::steady_clock> _last_update_time;\n    double _last_ros_update_time;\n\n    int _robotState;\n    int _marker_id;\n\n    bitbots_quintic_walk::WalkingParameter _params;\n\n    Eigen::Vector3d _trunkPos;\n    Eigen::Vector3d _trunkAxis;\n    Eigen::Vector3d _footPos;\n    Eigen::Vector3d _footAxis;\n    bool _isLeftSupport;\n\n    bool _special_gait_pending;\n    bool _odometry_reset_pending;\n    bool _gait_reset_pending;\n    bool _walk_kick_pending;\n\n    Eigen::Vector3d _real_velocities;\n    Eigen::Vector3d _real_odometry;\n    Eigen::Vector3d _imu_angle;\n    Eigen::Vector2d _real_head_pos;\n    Eigen::Matrix<double, 7, 1> _real_body_pos;\n\n    /**\n     * Saves current orders as [x-direction, y-direction, z-rotation]\n     */\n    Eigen::Vector3d _currentOrders;\n    Eigen::Vector2d _headPos;\n    Eigen::Vector2i _gaitId;\n\n    /**\n     * Saves max values we can move in a single step as [x-direction, y-direction, z-rotation].\n     * Is used to limit _currentOrders to sane values\n     */\n    Eigen::Vector3d _max_step;\n\n    /**\n     * Measures how much distance we can traverse in X and Y direction combined\n     */\n    double _max_step_xy;\n    bitbots_quintic_walk::QuinticWalk _walkEngine;\n\n    bitbots_msgs::JointCommand _command_msg;\n    nav_msgs::Odometry _odom_msg;\n    geometry_msgs::TransformStamped _odom_trans;\n\n    ros::NodeHandle _nh;\n\n    ros::Publisher _pubControllerCommand;\n    ros::Publisher _pubOdometry;\n    ros::Publisher _pubSupport;\n    tf::TransformBroadcaster _odom_broadcaster;\n    ros::Publisher _pubDebug;\n    ros::Publisher _pubDebugMarker;\n\n    ros::Subscriber _subCmdVel;\n    ros::Subscriber _subHeadPos;\n    ros::Subscriber _subRobState;\n    ros::Subscriber _subJointStates;\n    ros::Subscriber _subKick;\n    ros::Subscriber _subImu;\n    ros::Subscriber _subPressure;\n    ros::Subscriber _subCopL;\n    ros::Subscriber _subCopR;\n\n    // dsp command service\n    ros::ServiceServer _set_head_move_valid_service;\n    ros::ServiceServer _set_sensor_enable_valid_service;\n    ros::ServiceServer _set_special_gait_valid_service;\n    ros::ServiceServer _do_left_kick_service;\n    ros::ServiceServer _do_right_kick_service;\n    ros::ServiceServer _do_stand_front_service;\n    ros::ServiceServer _do_stand_back_service;\n    ros::ServiceServer _do_walk_kick_left_service;\n    ros::ServiceServer _do_walk_kick_right_service;\n    ros::ServiceServer _set_torque_enable_service;\n    ros::ServiceServer _set_gait_valid_service;\n    ros::ServiceServer _reset_odometry_service;\n    ros::ServiceServer _reset_gait_service;\n\n    ros::ServiceServer _get_special_gait_pending_service;\n    ros::ServiceServer _get_odometry_reset_pending_service;\n    ros::ServiceServer _gait_reset_pending_service;\n    ros::ServiceServer _get_walk_kick_pending_service;\n\n    geometry_msgs::PointStamped _cop_l;\n    geometry_msgs::PointStamped _cop_r;\n\n    // MoveIt!\n    robot_model_loader::RobotModelLoader _robot_model_loader;\n    robot_model::RobotModelPtr _kinematic_model;\n    robot_state::RobotStatePtr _goal_state;\n    robot_state::RobotStatePtr _current_state;\n    const robot_state::JointModelGroup *_all_joints_group;\n    const robot_state::JointModelGroup *_legs_joints_group;\n    const robot_state::JointModelGroup *_lleg_joints_group;\n    const robot_state::JointModelGroup *_rleg_joints_group;\n\n    // IK solver\n    bitbots_ik::BioIKSolver _bioIK_solver;\n    std::shared_ptr<DspSDK::DspHandler> _dsp_handler;\n};\n\n#endif\n", "meta": {"hexsha": "6d1a394e3ae79ecb93e0bfbd9d7a320168d5ed0a", "size": 9288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bitbots_quintic_walk/include/bitbots_quintic_walk/QuinticWalkingNode.hpp", "max_stars_repo_name": "b51/bitbots_motion", "max_stars_repo_head_hexsha": "82f2ea2d257334346907a68878324f1ee073a472", "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": "bitbots_quintic_walk/include/bitbots_quintic_walk/QuinticWalkingNode.hpp", "max_issues_repo_name": "b51/bitbots_motion", "max_issues_repo_head_hexsha": "82f2ea2d257334346907a68878324f1ee073a472", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bitbots_quintic_walk/include/bitbots_quintic_walk/QuinticWalkingNode.hpp", "max_forks_repo_name": "b51/bitbots_motion", "max_forks_repo_head_hexsha": "82f2ea2d257334346907a68878324f1ee073a472", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-18T06:01:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T05:12:13.000Z", "avg_line_length": 31.6996587031, "max_line_length": 118, "alphanum_fraction": 0.7183462532, "num_tokens": 2289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.3557748866829643, "lm_q1q2_score": 0.19589227308010562}}
{"text": "// Copyright (c) 2015 The Dogecoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"arith_uint256.h\"\n#include \"chainparams.h\"\n#include \"lemoncoin.h\"\n#include \"main.h\"\n#include \"test/test_bitcoin.h\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(lemoncoin_tests, TestingSetup)\n\nBOOST_AUTO_TEST_CASE(get_next_work_difficulty_limit)\n{\n    SelectParams(CBaseChainParams::MAIN);\n    const Consensus::Params& params = Params().GetConsensus(0);\n\n    CBlockIndex pindexLast;\n    int64_t nLastRetargetTime = 1455393600; // Block # 1\n    \n    /*\n    pindexLast.nHeight = 239;\n    pindexLast.nTime = 1386475638; // Block #239\n    pindexLast.nBits = 0x1e0ffff0;\n    BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1e00ffff);*/\n}\n\nBOOST_AUTO_TEST_CASE(get_next_work_digishield)\n{\n    /*SelectParams(CBaseChainParams::MAIN);\n    const Consensus::Params& params = Params().GetConsensus(145000);\n    \n    CBlockIndex pindexLast;\n    int64_t nLastRetargetTime = 1395094427;\n\n    // First hard-fork at 145,000, which applies to block 145,001 onwards\n    pindexLast.nHeight = 145000;\n    pindexLast.nTime = 1395094679;\n    pindexLast.nBits = 0x1b499dfd;\n    BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1b671062);*/\n}\n\nBOOST_AUTO_TEST_CASE(get_next_work_digishield_modulated_upper)\n{\n    /*SelectParams(CBaseChainParams::MAIN);\n    const Consensus::Params& params = Params().GetConsensus(145000);\n    \n    CBlockIndex pindexLast;\n    int64_t nLastRetargetTime = 1395100835;\n\n    // Test the upper bound on modulated time using mainnet block #145,107\n    pindexLast.nHeight = 145107;\n    pindexLast.nTime = 1395101360;\n    pindexLast.nBits = 0x1b3439cd;\n    BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1b4e56b3);*/\n}\n\nBOOST_AUTO_TEST_CASE(get_next_work_digishield_modulated_lower)\n{\n    /*SelectParams(CBaseChainParams::MAIN);\n    const Consensus::Params& params = Params().GetConsensus(145000);\n    \n    CBlockIndex pindexLast;\n    int64_t nLastRetargetTime = 1395380517;\n\n    // Test the lower bound on modulated time using mainnet block #149,423\n    pindexLast.nHeight = 149423;\n    pindexLast.nTime = 1395380447;\n    pindexLast.nBits = 0x1b446f21;\n    BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1b335358);*/\n}\n\nBOOST_AUTO_TEST_CASE(get_next_work_digishield_rounding)\n{\n    /*SelectParams(CBaseChainParams::MAIN);\n    const Consensus::Params& params = Params().GetConsensus(145000);\n    \n    CBlockIndex pindexLast;\n    int64_t nLastRetargetTime = 1395094679;\n\n    // Test case for correct rounding of modulated time - this depends on\n    // handling of integer division, and is not obvious from the code\n    pindexLast.nHeight = 145001;\n    pindexLast.nTime = 1395094727;\n    pindexLast.nBits = 0x1b671062;\n    BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1b6558a4);*/\n}\n\nBOOST_AUTO_TEST_CASE(hardfork_parameters)\n{\n    SelectParams(CBaseChainParams::MAIN);\n    const Consensus::Params& initialParams = Params().GetConsensus(0);\n\n    BOOST_CHECK_EQUAL(initialParams.nPowTargetTimespan, 60);\n    BOOST_CHECK_EQUAL(initialParams.fAllowLegacyBlocks, true);\n    BOOST_CHECK_EQUAL(initialParams.fDigishieldDifficultyCalculation, true);\n\n    /*\n    const Consensus::Params& initialParamsEnd = Params().GetConsensus(144999);\n    BOOST_CHECK_EQUAL(initialParamsEnd.nPowTargetTimespan, 14400);\n    BOOST_CHECK_EQUAL(initialParamsEnd.fAllowLegacyBlocks, true);\n    BOOST_CHECK_EQUAL(initialParamsEnd.fDigishieldDifficultyCalculation, false);\n\n    const Consensus::Params& digishieldParams = Params().GetConsensus(145000);\n    BOOST_CHECK_EQUAL(digishieldParams.nPowTargetTimespan, 60);\n    BOOST_CHECK_EQUAL(digishieldParams.fAllowLegacyBlocks, true);\n    BOOST_CHECK_EQUAL(digishieldParams.fDigishieldDifficultyCalculation, true);\n\n    const Consensus::Params& digishieldParamsEnd = Params().GetConsensus(371336);\n    BOOST_CHECK_EQUAL(digishieldParamsEnd.nPowTargetTimespan, 60);\n    BOOST_CHECK_EQUAL(digishieldParamsEnd.fAllowLegacyBlocks, true);\n    BOOST_CHECK_EQUAL(digishieldParamsEnd.fDigishieldDifficultyCalculation, true);\n\n    const Consensus::Params& auxpowParams = Params().GetConsensus(371337);\n    BOOST_CHECK_EQUAL(auxpowParams.nHeightEffective, 371337);\n    BOOST_CHECK_EQUAL(auxpowParams.nPowTargetTimespan, 60);\n    BOOST_CHECK_EQUAL(auxpowParams.fAllowLegacyBlocks, false);\n    BOOST_CHECK_EQUAL(auxpowParams.fDigishieldDifficultyCalculation, true);\n\n    const Consensus::Params& auxpowHighParams = Params().GetConsensus(700000); // Arbitrary point after last hard-fork\n    BOOST_CHECK_EQUAL(auxpowHighParams.nPowTargetTimespan, 60);\n    BOOST_CHECK_EQUAL(auxpowHighParams.fAllowLegacyBlocks, false);\n    BOOST_CHECK_EQUAL(auxpowHighParams.fDigishieldDifficultyCalculation, true);\n    */\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fa1fddb081239efffa3294942da958b06f2e49de", "size": 5102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/lemoncoin_tests.cpp", "max_stars_repo_name": "fflo/lemoncoin", "max_stars_repo_head_hexsha": "1d45a3821afacf24d07827b64712d31f28b75730", "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/test/lemoncoin_tests.cpp", "max_issues_repo_name": "fflo/lemoncoin", "max_issues_repo_head_hexsha": "1d45a3821afacf24d07827b64712d31f28b75730", "max_issues_repo_licenses": ["MIT"], "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/lemoncoin_tests.cpp", "max_forks_repo_name": "fflo/lemoncoin", "max_forks_repo_head_hexsha": "1d45a3821afacf24d07827b64712d31f28b75730", "max_forks_repo_licenses": ["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.2461538462, "max_line_length": 118, "alphanum_fraction": 0.7773422187, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.1958270216359123}}
{"text": "//==============================================================================\n//         Copyright 2009 - 2013 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2013 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 NT2_SDK_BENCH_DETAILS_MEASURE_HPP_INCLUDED\n#define NT2_SDK_BENCH_DETAILS_MEASURE_HPP_INCLUDED\n\n#include <nt2/sdk/timing/now.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <sstream>\n#include <string>\n\nnamespace nt2 { namespace details\n{\n  // Type of accumulator used by all benchmarks\n  typedef boost::accumulators::stats< boost::accumulators::tag::mean\n                                      , boost::accumulators::tag::median\n                                      , boost::accumulators::tag::min\n                                      , boost::accumulators::tag::max\n                                      , boost::accumulators::tag::count\n                                      > stats_t;\n\n  // accumulator for microseconds\n  typedef boost::accumulators::accumulator_set<microseconds_t,stats_t>  times_set;\n\n  // accumulator for CPU cycles\n  typedef boost::accumulators::accumulator_set<cycles_t,stats_t>        cycles_set;\n\n\n  // Compute an unique string referring to a proper Experiment result\n  template<typename Experiment, typename Stat>\n  inline std::string identify_result( std::string const& name\n                                    , Experiment const& e\n                                    , Stat const& s\n                                    )\n  {\n    std::ostringstream str;\n    str << name << e.size() << s.unit();\n    return str.str();\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "efc53b7bb5804e3473a302f577f52659476b8511", "size": 2165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/test/benchmark/include/nt2/sdk/bench/details/measure.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/test/benchmark/include/nt2/sdk/bench/details/measure.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/test/benchmark/include/nt2/sdk/bench/details/measure.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": 40.0925925926, "max_line_length": 83, "alphanum_fraction": 0.5755196305, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "//============================================================================\n// Name        : AltitudeMatrix.cpp\n// Author      : mm\n// Copyright   : This tool and Javascript code are licensed under the MIT license.\n// Description :\n//============================================================================\n#include \"AltitudeMatrix.h\"\n#include \"GeoTiffReader.h\"\n#include \"Dct.h\"\n#include <boost/format.hpp>\n#include <cctype>\n#include <fstream>\n\nAltitudeMatrix::AltitudeMatrix() {\n\tmasterMatrix.init(MATRIX_SIZE+4, MATRIX_SIZE+4);\n\tmemset(matrix, 0, sizeof(matrix));\n\tsmoothingCount = 0;\n    dctRadius = -1;\n\tbaseFileName = \"\";\n}\n\n\nAltitudeMatrix::~AltitudeMatrix() {\n}\n\nvoid AltitudeMatrix::clear()\n{\n\tmasterMatrix.init(MATRIX_SIZE+4, MATRIX_SIZE+4);\n\tmemset(matrix, 0, sizeof(matrix));\n\tsmoothingCount = 0;\n}\n\nbool AltitudeMatrix::setDEMMatrix(\n\tMatrix<short>* pMatrix11, Matrix<short>* pMatrix12, Matrix<short>* pMatrix13,\n\tMatrix<short>* pMatrix21, Matrix<short>* pMatrix22, Matrix<short>* pMatrix23,\n\tMatrix<short>* pMatrix31, Matrix<short>* pMatrix32, Matrix<short>* pMatrix33)\n{\n\tif(!pMatrix22){\n\t\treturn false;\n\t}\n\n\tmasterMatrix.copy(pMatrix31, MATRIX_SIZE-2, MATRIX_SIZE-2, 2,           2,           0,             0);\n\tmasterMatrix.copy(pMatrix32, 0,             MATRIX_SIZE-2, MATRIX_SIZE, 2,           2,             0);\n\tmasterMatrix.copy(pMatrix33, 0,             MATRIX_SIZE-2, 2,           2,           MATRIX_SIZE+2, 0);\n\tmasterMatrix.copy(pMatrix21, MATRIX_SIZE-2, 0,             2,           MATRIX_SIZE, 0,             2);\n\tmasterMatrix.copy(pMatrix22, 0,             0,             MATRIX_SIZE, MATRIX_SIZE, 2,             2);\n\tmasterMatrix.copy(pMatrix23, MATRIX_SIZE-2, 0,             2,           MATRIX_SIZE, MATRIX_SIZE+2, 2);\n\tmasterMatrix.copy(pMatrix11, MATRIX_SIZE-2, 0,             2,           2,           0,             MATRIX_SIZE+2);\n\tmasterMatrix.copy(pMatrix12, 0,             0,             MATRIX_SIZE, 2,           2,             MATRIX_SIZE+2);\n\tmasterMatrix.copy(pMatrix13, 0,             0,             2,           2,           MATRIX_SIZE+2, MATRIX_SIZE+2);\n\n\tif(!pMatrix12){\n\t\tmasterMatrix.copy(&masterMatrix, 2, 2, MATRIX_SIZE, 1, 2, 0);\n\t\tmasterMatrix.copy(&masterMatrix, 2, 2, MATRIX_SIZE, 1, 2, 1);\n\t}\n\tif(!pMatrix21){\n\t\tmasterMatrix.copy(&masterMatrix, 2, 2, 1, MATRIX_SIZE, 0, 2);\n\t\tmasterMatrix.copy(&masterMatrix, 2, 2, 1, MATRIX_SIZE, 1, 2);\n\t}\n\tif(!pMatrix23){\n\t\tmasterMatrix.copy(&masterMatrix, MATRIX_SIZE+1, 2, 1, MATRIX_SIZE, MATRIX_SIZE+2, 2);\n\t\tmasterMatrix.copy(&masterMatrix, MATRIX_SIZE+1, 2, 1, MATRIX_SIZE, MATRIX_SIZE+3, 2);\n\t}\n\tif(!pMatrix32){\n\t\tmasterMatrix.copy(&masterMatrix, 2, MATRIX_SIZE+1, MATRIX_SIZE, 1, 2, MATRIX_SIZE+2);\n\t\tmasterMatrix.copy(&masterMatrix, 2, MATRIX_SIZE+1, MATRIX_SIZE, 1, 2, MATRIX_SIZE+3);\n\t}\n\n\tif(!pMatrix11){\n\t\tmasterMatrix.setMatrixValue(0, 1, masterMatrix.getMatrixValue(0, 2));\n\t\tmasterMatrix.setMatrixValue(1, 1, masterMatrix.getMatrixValue(2, 2));\n\t\tmasterMatrix.setMatrixValue(1, 0, masterMatrix.getMatrixValue(2, 0));\n\t\tmasterMatrix.setMatrixValue(0, 0, (masterMatrix.getMatrixValue(0, 1) + masterMatrix.getMatrixValue(1, 1) + masterMatrix.getMatrixValue(1, 0))/3);\n\t}\n\tif(!pMatrix13){\n\t\tmasterMatrix.setMatrixValue(0, MATRIX_SIZE+2, masterMatrix.getMatrixValue(0, MATRIX_SIZE+1));\n\t\tmasterMatrix.setMatrixValue(1, MATRIX_SIZE+2, masterMatrix.getMatrixValue(2, MATRIX_SIZE+1));\n\t\tmasterMatrix.setMatrixValue(1, MATRIX_SIZE+3, masterMatrix.getMatrixValue(2, MATRIX_SIZE+3));\n\t\tmasterMatrix.setMatrixValue(0, MATRIX_SIZE+3, (masterMatrix.getMatrixValue(0, MATRIX_SIZE+2) + masterMatrix.getMatrixValue(1, MATRIX_SIZE+2) + masterMatrix.getMatrixValue(1, MATRIX_SIZE+3))/3);\n\t}\n\tif(!pMatrix31){\n\t\tmasterMatrix.setMatrixValue(MATRIX_SIZE+2, 0, masterMatrix.getMatrixValue(MATRIX_SIZE+1, 0));\n\t\tmasterMatrix.setMatrixValue(MATRIX_SIZE+2, 1, masterMatrix.getMatrixValue(MATRIX_SIZE+1, 2));\n\t\tmasterMatrix.setMatrixValue(MATRIX_SIZE+3, 1, masterMatrix.getMatrixValue(MATRIX_SIZE+3, 2));\n\t\tmasterMatrix.setMatrixValue(MATRIX_SIZE+3, 0, (masterMatrix.getMatrixValue(MATRIX_SIZE+2, 0) + masterMatrix.getMatrixValue(MATRIX_SIZE+2, 1) + masterMatrix.getMatrixValue(MATRIX_SIZE+3, 1))/3);\n\t}\n\tif(!pMatrix33){\n\t\tmasterMatrix.setMatrixValue(MATRIX_SIZE+2, MATRIX_SIZE+3, masterMatrix.getMatrixValue(MATRIX_SIZE+1, MATRIX_SIZE+3));\n\t\tmasterMatrix.setMatrixValue(MATRIX_SIZE+2, MATRIX_SIZE+2, masterMatrix.getMatrixValue(MATRIX_SIZE+1, MATRIX_SIZE+1));\n\t\tmasterMatrix.setMatrixValue(MATRIX_SIZE+3, MATRIX_SIZE+2, masterMatrix.getMatrixValue(MATRIX_SIZE+3, MATRIX_SIZE+1));\n\t\tmasterMatrix.setMatrixValue(MATRIX_SIZE+3, MATRIX_SIZE+3, (masterMatrix.getMatrixValue(MATRIX_SIZE+2, MATRIX_SIZE+3) + masterMatrix.getMatrixValue(MATRIX_SIZE+2, MATRIX_SIZE+2) + masterMatrix.getMatrixValue(MATRIX_SIZE+3, MATRIX_SIZE+2))/3);\n\t}\n\n\treturn true;\n}\n\nbool AltitudeMatrix::setDEMMatrix(Matrix<short>* pDemMatrix)\n{\n\tif(!pDemMatrix){\n\t\treturn false;\n\t}\n\n\tmasterMatrix.copy(pDemMatrix, 0, 0, MATRIX_SIZE, MATRIX_SIZE, 2, 2);\n\n\treturn true;\n}\n\nvoid AltitudeMatrix::doSmoothing(unsigned long smoothingCount,\n                                 bool afterDct)\n{\n\tlong i;\n\tlong j;\n\n    for(long repeat=0; repeat<smoothingCount; repeat++){\n        std::cout << \"Smoothing ...\" << (repeat+1) << std::endl;\n\n        for(i=0; i<MATRIX_SIZE+4; i++){\n            for(j=0; j<MATRIX_SIZE+4; j++){\n                if(afterDct == false){\n                    if(repeat == 0){\n                        matrix[eFactor1][i][j] = (long)masterMatrix.getMatrixValue(j, i);\n                        matrix[eFactor4][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 4;\n                        matrix[eFactor6][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 6;\n                        matrix[eFactor16][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 16;\n                        matrix[eFactor24][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 24;\n                        matrix[eFactor36][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 36;\n                    }\n                    else{\n                        if(i>=2 && i<=MATRIX_SIZE+2 && j>=2 && j<=MATRIX_SIZE+2){\n                            matrix[eFactor1][i][j] = matrix[eResult][i][j];\n                            matrix[eFactor4][i][j] = matrix[eResult][i][j] * 4;\n                            matrix[eFactor6][i][j] = matrix[eResult][i][j] * 6;\n                            matrix[eFactor16][i][j] = matrix[eResult][i][j] * 16;\n                            matrix[eFactor24][i][j] = matrix[eResult][i][j] * 24;\n                            matrix[eFactor36][i][j] = matrix[eResult][i][j] * 36;\n                        }\n                        else{\n                            matrix[eFactor1][i][j] = (long)masterMatrix.getMatrixValue(j, i);\n                            matrix[eFactor4][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 4;\n                            matrix[eFactor6][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 6;\n                            matrix[eFactor16][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 16;\n                            matrix[eFactor24][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 24;\n                            matrix[eFactor36][i][j] = (long)masterMatrix.getMatrixValue(j, i) * 36;\n                        }\n                    }\n                }\n                else{\n                    matrix[eFactor1][i][j] = matrix[eResult][i][j];\n                    matrix[eFactor4][i][j] = matrix[eResult][i][j] * 4;\n                    matrix[eFactor6][i][j] = matrix[eResult][i][j] * 6;\n                    matrix[eFactor16][i][j] = matrix[eResult][i][j] * 16;\n                    matrix[eFactor24][i][j] = matrix[eResult][i][j] * 24;\n                    matrix[eFactor36][i][j] = matrix[eResult][i][j] * 36;\n                }\n            }\n        }\n\n        for(i=2; i<MATRIX_SIZE+2; i++){\n            for(j=2; j<MATRIX_SIZE+2; j++){\n                matrix[eResult][i][j] =\n                    ((matrix[eFactor1][i-2][j-2] + matrix[eFactor4][i-1][j-2]  + matrix[eFactor6][i][j-2]  + matrix[eFactor4][i+1][j-2]  + matrix[eFactor1][i+2][j-2] +\n                      matrix[eFactor4][i-2][j-1] + matrix[eFactor16][i-1][j-1] + matrix[eFactor24][i][j-1] + matrix[eFactor16][i+1][j-1] + matrix[eFactor4][i+2][j-1] +\n                      matrix[eFactor6][i-2][j]   + matrix[eFactor24][i-1][j]   + matrix[eFactor36][i][j]   + matrix[eFactor24][i+1][j]   + matrix[eFactor6][i+2][j] +\n                      matrix[eFactor4][i-2][j+1] + matrix[eFactor16][i-1][j+1] + matrix[eFactor24][i][j+1] + matrix[eFactor16][i+1][j+1] + matrix[eFactor4][i+2][j+1] +\n                      matrix[eFactor1][i-2][j+2] + matrix[eFactor4][i-1][j+2]  + matrix[eFactor6][i][j+2]  + matrix[eFactor4][i+1][j+2]  + matrix[eFactor1][i+2][j+1])\n                     / 256);\n            }\n        }\n    }\n\n\tthis->smoothingCount = smoothingCount;\n}\n\nvoid AltitudeMatrix::doDCT(long dctRadius)\n{\n    Dct dct;\n    \n    dct.doDCT(&masterMatrix, matrix[eResult], dctRadius);\n    \n    this->dctRadius = dctRadius;\n}\n\nbool AltitudeMatrix::setBaseFile(std::string & demFileName)\n{\n\tbaseFileName = boost::filesystem::path(demFileName).stem().generic_string();\n\n\tlong latPos = baseFileName.find(\"_\");\n\tbaseFileName = baseFileName.substr(latPos+1, 7);\n\treturn true;\n}\n\nvoid AltitudeMatrix::verify(Matrix<short > *pOrgMatrix)\n{\n\tfor(long i=2; i<MATRIX_SIZE+2; i++){\n\t\tfor(long j=2; j<MATRIX_SIZE+2; j++){\n\t\t\tshort orgAltitude = pOrgMatrix->getMatrixValue((j-2)*3, (i-2)*3);\n\t\t\tshort resultAltitude = smoothingCount>0 ? matrix[eResult][i][j] : masterMatrix.getMatrixValue(j, i);\n\n\t\t\tif(abs(orgAltitude - resultAltitude) > HEIGHT_THRESHOLD && resultAltitude==0 && orgAltitude>0){\n\t\t\t\tstd::cout << baseFileName << \" x=\" << (j-2) << \" y=\" << (i-2) << \" org=\" << orgAltitude << \" smooth=\" << resultAltitude << std::endl;\n\t\t\t\tif(smoothingCount > 0){\n\t\t\t\t\tmatrix[eResult][i][j] = orgAltitude;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tmasterMatrix.setMatrixValue(j, i, orgAltitude);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid AltitudeMatrix::compare()\n{\n    long totalChange = 0;\n\t\n    for(long i=2; i<MATRIX_SIZE+2; i++){\n\t\tfor(long j=2; j<MATRIX_SIZE+2; j++){\n\t\t\tlong orgAltitude = (long)masterMatrix.getMatrixValue(j, i);\n\t\t\tlong resultAltitude = matrix[eResult][i][j];\n            totalChange += abs((int)orgAltitude - (int)resultAltitude);\n        }\n    }\n    double ratio = totalChange / (MATRIX_SIZE * MATRIX_SIZE);\n\n    std::cout << \"change ratio=\" << ratio << std::endl;\n}\n\nbool AltitudeMatrix::writeJSON(std::string& outputFolder)\n{\n\tstd::cout << \"Writing \" << baseFileName << \" ...\" <<std::endl;\n\n    boost::filesystem::create_directories(boost::filesystem::path(outputFolder));\n    \n\tfor(long k=0; k<3; k++){\n\t\tfor(long l=0; l<3; l++){\n\t\t\tstd::string outputFileName = outputFolder + baseFileName + (boost::format(\"M%1%%2%.json\") % k % l).str();\n\n\t\t\tstd::ofstream outStream(outputFileName.c_str(), std::ios::out |  std::ios::binary );\n\t\t\tif(!outStream){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\toutStream << \"{\\\"h\\\" : [\" << std::endl;\n\n\t\t\tfor(long i=0; i<MATRIX_SIZE/3; i++){\n\t\t\t\tshort previous = 0;\n\t\t\t\tshort diff = 0;\n\t\t\t\tshort count = 0;\n\n\t\t\t\tstd::string lineString = \"\\\"\";\n\n\t\t\t\tfor(long j=0; j<MATRIX_SIZE/3; j++){\n\t\t\t\t\tshort current;\n\t\t\t\t\tif(smoothingCount > 0 || dctRadius >= 0){\n\t\t\t\t\t\tcurrent = matrix[eResult][(3-k)*(MATRIX_SIZE/3)-i+1][l*MATRIX_SIZE/3+j+2];\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcurrent = masterMatrix.getMatrixValue(l*MATRIX_SIZE/3+j+2, (3-k)*(MATRIX_SIZE/3)-i+1);\n\t\t\t\t\t}\n\n\t\t\t\t\tdiff = current - previous;\n\t\t\t\t\tif(diff == 0){\n\t\t\t\t\t\tif(count == 0){\n\t\t\t\t\t\t\tlineString += \":\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tif(count>0){\n\t\t\t\t\t\t\tlineString += heightEncode(count);\n\t\t\t\t\t\t\tcount = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdiff = diff << 1;\n\t\t\t\t\t\tif(diff & 0x8000){\n\t\t\t\t\t\t\tdiff = ~diff;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlineString += heightEncode(diff);\n\t\t\t\t\t}\n\t\t\t\t\tprevious = current;\n\t\t\t\t}\n\t\t\t\tif(count>0){\n\t\t\t\t\tlineString += heightEncode(count);\n\t\t\t\t}\n\t\t\t\tif(i == MATRIX_SIZE/3-1){\n\t\t\t\t\tlineString += \"\\\"\";\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tlineString += \"\\\",\";\n\t\t\t\t}\n\t\t\t\toutStream << lineString << std::endl;\n\t\t\t}\n\t\t\toutStream << \"]}\" << std::endl;\n\t\t\toutStream.close();\n\t\t}\n\t}\n\treturn true;\n}\n\nchar* AltitudeMatrix::heightEncode(short height)\n{\n\tstatic char caEncodeString[10];\n\tmemset(caEncodeString, 0, sizeof(caEncodeString));\n\n\tlong i=0;\n\twhile(height >= 0x20){\n\t\tcaEncodeString[i] = (char)((0x20 | (height & 0x1f)) + 0x3f);\n\t\theight >>= 5;\n\t\ti++;\n\t}\n\tif(height + 0x3f == 0x5c){\n\t\tcaEncodeString[i] = 0x5c;\n\t\tcaEncodeString[i+1] = 0x5c;\n\t}\n\telse{\n\t\tcaEncodeString[i] = (char)(height + 0x3f);\n\t}\n\n\treturn caEncodeString;\n}\n", "meta": {"hexsha": "44f5f3e8a672a79d9519ebc6e4a2f690822d76b9", "size": 12578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hgt2json-osx/AltitudeMatrix.cpp", "max_stars_repo_name": "mm-git/hgt2json-osx", "max_stars_repo_head_hexsha": "13d0e43914c269a08413997e09cebfa95a0adb11", "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": "hgt2json-osx/AltitudeMatrix.cpp", "max_issues_repo_name": "mm-git/hgt2json-osx", "max_issues_repo_head_hexsha": "13d0e43914c269a08413997e09cebfa95a0adb11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hgt2json-osx/AltitudeMatrix.cpp", "max_forks_repo_name": "mm-git/hgt2json-osx", "max_forks_repo_head_hexsha": "13d0e43914c269a08413997e09cebfa95a0adb11", "max_forks_repo_licenses": ["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.30625, "max_line_length": 243, "alphanum_fraction": 0.5881698203, "num_tokens": 3802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"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     graph.cpp\n* \\author   Collin Johnson\n*\n* Definition of convert_map_to_graph.\n*/\n\n#include <hssh/global_topological/graph.h>\n#include <hssh/global_topological/topological_map.h>\n#include <boost/range/adaptor/map.hpp>\n#include <cassert>\n\nnamespace vulcan\n{\nnamespace hssh\n{\n\nTopologicalVertex convert_path_segment_to_vertex(const GlobalPathSegment&  segment,\n                                                 const Point<float>& plusPosition,\n                                                 const Point<float>& minusPosition);\nTopologicalVertex convert_frontier_path_segment_to_vertex(const GlobalPathSegment&  segment,\n                                                          const Point<float>& position);\n\nvoid add_explored_segment(const GlobalPathSegment& segment, \n                          const TopologicalMap& map, \n                          TopologicalGraph& graph);\nvoid add_frontier_segment(const GlobalPathSegment& segment, \n                          const TopologicalMap& map, \n                          TopologicalGraph& graph);\nGlobalPlace transition_place(const GlobalTransition& transition, \n                             const GlobalPathSegment& segment, \n                             const TopologicalMap& map);\n\n\nTopologicalGraph convert_map_to_graph(const TopologicalMap& map)\n{\n    auto& segments = map.segments();\n\n    TopologicalGraph graph;\n\n    for(auto& s : boost::adaptors::values(segments))\n    {\n        if(s->isFrontier())\n        {\n            add_frontier_segment(*s, map, graph);\n        }\n        else\n        {\n            add_explored_segment(*s, map, graph);\n        }\n    }\n\n    return graph;\n}\n\n\nTopologicalVertex convert_location_to_vertex(const GlobalLocation& location, const TopologicalMap& map)\n{\n    if(location.areaType == AreaType::path_segment)\n    {\n        assert(map.getPathSegment(location.areaId));\n        \n        GlobalPathSegment segment = *map.getPathSegment(location.areaId);\n\n        if(!segment.isFrontier())\n        {\n            const GlobalPlace plus  = transition_place(segment.plusTransition(), segment, map);\n            const GlobalPlace minus = transition_place(segment.minusTransition(), segment, map);\n\n            return TopologicalVertex(convert_path_segment_to_vertex(segment,\n                                                                    map.referenceFrame(plus.id()).toPoint(),\n                                                                    map.referenceFrame(minus.id()).toPoint()));\n        }\n        else\n        {\n            auto transition = segment.plusTransition().isFrontier() ? segment.plusTransition() : segment.minusTransition();\n            GlobalPlace place = transition_place(transition, segment, map);\n\n            return TopologicalVertex(convert_frontier_path_segment_to_vertex(segment,\n                                                                             map.referenceFrame(place.id()).toPoint()));\n        }\n    }\n    else // at a place\n    {\n        return convert_place_to_vertex(*map.getPlace(location.areaId), map);\n    }\n}\n\n\nTopologicalVertex convert_place_to_vertex(const GlobalPlace& place, const TopologicalMap& map)\n{\n    Point<float> location = map.referenceFrame(place.id()).toPoint();\n    return TopologicalVertex(place.id(), location, NodeData(place.id()));\n}\n\n\nTopologicalVertex convert_path_segment_to_vertex(const GlobalPathSegment&  segment,\n                                                 const Point<float>& plusPosition,\n                                                 const Point<float>& minusPosition)\n{\n    Point<float> segmentLocation((plusPosition.x + minusPosition.x) / 2.0f,\n                                       (plusPosition.y + minusPosition.y) / 2.0f);\n\n    return TopologicalVertex(segment.id(), \n                             segmentLocation, \n                             NodeData(segment.id(), true), \n                             segment.lambda().magnitude());\n}\n\n\nTopologicalVertex convert_frontier_path_segment_to_vertex(const GlobalPathSegment&  segment,\n                                                          const Point<float>& position)\n{\n    // For frontier segments, put the location halfway down the explored section of the segment.\n    Point<float> segmentLocation((position.x + segment.lambda().x) / 2.0f,\n                                       (position.y + segment.lambda().y) / 2.0f);\n\n    return TopologicalVertex(segment.id(), \n                             segmentLocation, \n                             NodeData(segment.id(), true), \n                             segment.lambda().magnitude());\n}\n\n\nvoid add_explored_segment(const GlobalPathSegment& segment, \n                          const TopologicalMap& map, \n                          TopologicalGraph& graph)\n{\n    // Ids for the edges in the graph are monotonically increasing. Can just use the current number of edges\n    // as the benchmark for determining the next id\n\n    auto plus  = segment.plusTransition();\n    auto minus = segment.minusTransition();\n\n    TopologicalVertex plusVertex    = convert_place_to_vertex(transition_place(plus, segment, map), map);\n    TopologicalVertex minusVertex   = convert_place_to_vertex(transition_place(minus, segment, map), map);\n    TopologicalVertex segmentVertex = convert_path_segment_to_vertex(segment, \n                                                                     plusVertex.getPosition(), \n                                                                     minusVertex.getPosition());\n\n    TopologicalEdge   plusEdge (graph.numEdges() + 1, plusVertex,  segmentVertex, 0.0);\n    TopologicalEdge   minusEdge(graph.numEdges() + 2, minusVertex, segmentVertex, 0.0);\n\n    graph.addVertex(plusVertex);\n    graph.addVertex(minusVertex);\n    graph.addVertex(segmentVertex);\n    graph.addEdge(plusEdge);\n    graph.addEdge(minusEdge);\n}\n\n\nvoid add_frontier_segment(const GlobalPathSegment& segment, \n                          const TopologicalMap& map, \n                          TopologicalGraph& graph)\n{\n    auto transition = segment.plusTransition().isFrontier() ? segment.plusTransition() : segment.minusTransition();\n\n    TopologicalVertex placeVertex   = convert_place_to_vertex(transition_place(transition, segment, map), map);\n    TopologicalVertex segmentVertex = convert_frontier_path_segment_to_vertex(segment, placeVertex.getPosition());\n\n    TopologicalEdge edge(graph.numEdges() + 1, placeVertex,  segmentVertex, 0.0);\n\n    graph.addVertex(placeVertex);\n    graph.addVertex(segmentVertex);\n    graph.addEdge(edge);\n}\n\n\nGlobalPlace transition_place(const GlobalTransition& transition, \n                             const GlobalPathSegment& segment, \n                             const TopologicalMap& map)\n{\n    return *map.getPlace(transition.otherArea(segment.toArea()).id());\n}\n\n} // namespace hssh\n} // namespace vulcan\n", "meta": {"hexsha": "b799c1ee976390431876cf1e3d57d4b2066ecc41", "size": 7197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hssh/global_topological/graph.cpp", "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_issues_repo_path": "src/hssh/global_topological/graph.cpp", "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_forks_repo_path": "src/hssh/global_topological/graph.cpp", "max_forks_repo_name": "h2ssh/Vulcan", "max_forks_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T00:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:56:38.000Z", "avg_line_length": 38.486631016, "max_line_length": 123, "alphanum_fraction": 0.6103932194, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "/*\n * ChiSquaredThreeJetsTopPairReconstruction.cpp\n *\n *  Created on: 2 Sep 2011\n *      Author: kreczko\n */\n\n#include \"../../interface/ReconstructionModules/ChiSquaredThreeJetsTopPairReconstruction.h\"\n#include <boost/lexical_cast.hpp>\n#include \"../../interface/ReconstructionModules/ReconstructionException.h\"\n\nnamespace BAT {\n\nbool ChiSquaredThreeJetsTopPairReconstruction::meetsJetFromWRequirement(unsigned short jet1Index,\n\t\tunsigned short jet2Index) {\n\treturn jet1Index == jet2Index; // two jets from W merged, therefore only 3 jets are needed\n}\n\nbool ChiSquaredThreeJetsTopPairReconstruction::meetsGlobalRequirement(const TtbarHypothesisPointer solution) {\n\treturn solution->isPhysical() && solution->hadronicW->mass() > 40;\n}\n\nbool ChiSquaredThreeJetsTopPairReconstruction::meetsInitialCriteria() const {\n\treturn met != 0 && leptonFromW != 0 && jets.size() == 3; // needs exactly 3 jets\n}\n\nstd::string ChiSquaredThreeJetsTopPairReconstruction::getDetailsOnFailure() const {\n\tstd::string msg = \"Initial Criteria not met: \\n\";\n\tif (leptonFromW == 0)\n\t\tmsg += \"Electron from W: not filled \\n\";\n\telse\n\t\tmsg += \"Electron from W: filled \\n\";\n\n\tif (met == 0)\n\t\tmsg += \"Missing transverse energy: not filled \\n\";\n\telse\n\t\tmsg += \"Missing transverse energy: filled \\n\";\n\tstd::string nJets(boost::lexical_cast<std::string>(jets.size()));\n\tif (jets.size() != 3) {\n\t\tif (jets.size() > 3)\n\t\t\tmsg += \"Number of jets is too large:\" + nJets + \", should be == 3 \\n\";\n\t\telse\n\t\t\tmsg += \"Number of jets is too small:\" + nJets + \", should be == 3 \\n\";\n\t}\n\n\telse\n\t\tmsg += \"Number of jets is OK:\" + nJets + \"\\n\";\n\n\treturn msg;\n}\n\nChiSquaredThreeJetsTopPairReconstruction::ChiSquaredThreeJetsTopPairReconstruction(const LeptonPointer lepton,\n\t\tconst METPointer met, const JetCollection jets) :\n\t\tBasicTopPairReconstruction(lepton, met, jets), ChiSquaredBasedTopPairReconstruction(lepton, met, jets) {\n\n}\n\nChiSquaredThreeJetsTopPairReconstruction::~ChiSquaredThreeJetsTopPairReconstruction() {\n}\n\n} /* namespace BAT */\n", "meta": {"hexsha": "a381b24c7d078322b698c6ed4b6490331233154a", "size": 2000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ReconstructionModules/ChiSquaredThreeJetsTopPairReconstruction.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/ReconstructionModules/ChiSquaredThreeJetsTopPairReconstruction.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/ReconstructionModules/ChiSquaredThreeJetsTopPairReconstruction.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": 32.2580645161, "max_line_length": 110, "alphanum_fraction": 0.733, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "// Copyright Oleg Maximenko 2014.\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://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <svgpp/parser/detail/common.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n\nnamespace svgpp \n{\n\nnamespace qi = boost::spirit::qi;\n\nnamespace detail\n{\n  typedef boost::tuple<unsigned char, unsigned char, unsigned char> rgb_t;\n\n  namespace\n  {\n    struct color_keywords\n    {\n      typedef qi::symbols<char, rgb_t> symbols;\n      static bool initialized_;\n      static symbols symbols_;\n    };\n\n    bool color_keywords::initialized_ = false;\n    color_keywords::symbols color_keywords::symbols_;\n  }\n}\n\ntemplate <class PropertySource, class Iterator, class ColorFactory>\nclass color_grammar: public qi::grammar<Iterator, typename ColorFactory::color_type()>\n{\n  typedef color_grammar<PropertySource, Iterator, ColorFactory> this_type;\npublic:\n  typedef typename ColorFactory::color_type color_type;\n\n  color_grammar()\n    : this_type::grammar(color)\n  {\n    namespace phx = boost::phoenix;\n    using qi::_1;\n    using qi::_2;\n    using qi::_3;\n    using qi::_a;\n    using qi::_b;\n    using qi::_c;\n    using qi::_val;\n    using qi::lit;\n    using detail::character_encoding_namespace::space;\n\n    comma \n        =   *space \n            >> ',' \n            >> *space;\n    color \n        =   hex_rule [_val = _1]\n        |   (\n                 detail::no_case_if_css(PropertySource())[ lit(\"rgb(\") ]\n              >> *space \n              >> (  components_rule [_val = _1]\n                 |  percentage_rule [_val = _1]\n                 )\n              >> *space \n              >> ')' \n            )\n        |   detail::color_keywords::symbols_ [_val = phx::bind(&color_grammar::color_keyword, _1)];\n\n    hex_rule \n        =   lit('#') \n            >> hex3 [_a = _1] \n            >> ( hex3 [_val = phx::bind(&color_grammar::six_hex_digits, _a, _1)] \n               | qi::eps [_val = phx::bind(&color_grammar::three_hex_digits, _a)] \n               );\n\n    components_rule \n        =   (  integer\n            >> comma \n            >> integer\n            >> comma \n            >> integer\n            ) [_val = phx::bind(&color_grammar::absolute_components, _1, _2, _3)];\n\n    percentage_rule \n        =   (  number \n            >> '%'\n            >> comma \n            >> number \n            >> '%' \n            >> comma \n            >> number \n            >> '%'\n            ) [_val = phx::bind(&color_grammar::percent_components, _1, _2, _3)];\n  }\n\nprivate:\n  typedef typename ColorFactory::percentage_type number_type;\n\n  typename this_type::start_type color;\n  qi::rule<Iterator> comma;\n  qi::rule<Iterator, color_type (), qi::locals<unsigned int> > hex_rule;\n  qi::rule<Iterator, color_type ()> components_rule;\n  qi::rule<Iterator, color_type ()> percentage_rule;\n  qi::uint_parser<unsigned char, 10, 1, 3> integer;\n  // There was mistake in SVG 1.1 that limits percentage to integer values, while CSS permits floating point numbers.\n  // Till fixed version is not released, we will use CSS version of percentage definition.\n  qi::real_parser<number_type, detail::number_policies<number_type, tag::source::css> > number;\n  qi::uint_parser<unsigned int, 16, 3, 3> hex3;\n\n  static color_type three_hex_digits(unsigned int h)\n  {\n    return ColorFactory::create( \n      static_cast<unsigned char>( ( (h & 0xf00) >> 8 ) | ( (h & 0xf00) >> 4 ) ),\n      static_cast<unsigned char>( ( (h & 0x0f0) >> 4 ) |   (h & 0x0f0) ),\n      static_cast<unsigned char>( ( (h & 0x00f) << 4 ) |   (h & 0x00f) ) );\n  }\n\n  static color_type six_hex_digits(unsigned int h1, unsigned int h2)\n  {\n    return ColorFactory::create( \n      static_cast<unsigned char>( h1 >> 4 ), \n      static_cast<unsigned char>( ( ( h1 & 0x0f ) << 4 ) | ( h2 >> 8 ) ),\n      static_cast<unsigned char>( h2 & 0xff ) );\n  }\n\n  static color_type absolute_components(unsigned char r, unsigned char g, unsigned char b)\n  {\n    return ColorFactory::create(r, g, b);\n  }\n\n  static color_type percent_components(number_type r, number_type g, number_type b)\n  {\n    return ColorFactory::create_from_percent(r, g, b);\n  }\n\n  static color_type color_keyword(detail::rgb_t const & rgb)\n  {\n    return ColorFactory::create(rgb.get<0>(), rgb.get<1>(), rgb.get<2>());\n  }\n};\n\nnamespace detail\n{\n  namespace\n  {\n    struct color_keywords_initializer\n    {\n      color_keywords_initializer()\n      {\n        if (!color_keywords::initialized_)\n        {\n          color_keywords::symbols_.add\n#define SVGPP_ON(name, r, g, b) (#name, rgb_t(r, g, b))\n#include <svgpp/detail/dict/enumerate_colors.inc>\n#undef SVGPP_ON\n            ;\n          color_keywords::initialized_ = true;\n        }\n      }\n    };\n\n    color_keywords_initializer color_keywords_initializer_instance;\n  }\n}\n\n}", "meta": {"hexsha": "4153ccf878bd2385eeea51e82cb3a14c04560480", "size": 4967, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/svgpp/parser/grammar/color.hpp", "max_stars_repo_name": "phonxvzf/svg2scad", "max_stars_repo_head_hexsha": "eb458df6cee6a65fbabbe5a5600f50551532adb4", "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/svgpp/parser/grammar/color.hpp", "max_issues_repo_name": "phonxvzf/svg2scad", "max_issues_repo_head_hexsha": "eb458df6cee6a65fbabbe5a5600f50551532adb4", "max_issues_repo_licenses": ["MIT"], "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/svgpp/parser/grammar/color.hpp", "max_forks_repo_name": "phonxvzf/svg2scad", "max_forks_repo_head_hexsha": "eb458df6cee6a65fbabbe5a5600f50551532adb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-25T13:34:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T13:34:53.000Z", "avg_line_length": 28.710982659, "max_line_length": 117, "alphanum_fraction": 0.6104288303, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "#define BOOST_TEST_MODULE test_magnusson\n\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n#include \"graph.h\"\n#include \"magnusson.h\"\n\nusing namespace dpct;\n\nBOOST_AUTO_TEST_CASE(minimal_test_magnusson)\n{\n    Graph::Configuration config(false, false, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 3,-10}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(1, {0, 3,-10}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n\n    g.addMoveArc(n1, n2, {1.0});\n\n    Magnusson tracker(&g, false);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    BOOST_CHECK_EQUAL(score, 7.0);\n    BOOST_CHECK_EQUAL(paths.size(), 1);\n}\n\nBOOST_AUTO_TEST_CASE(two_cell_test_magnusson)\n{\n    Graph::Configuration config(false, false, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 3, 5, -10}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(1, {0, 3, 4, -10}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n\n    g.addMoveArc(n1, n2, {1.0, 1.0});\n\n    Magnusson tracker(&g, false);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    BOOST_CHECK_EQUAL(score, 11.0); // arc score is applied only once!\n    BOOST_CHECK_EQUAL(paths.size(), 2);\n}\n\nBOOST_AUTO_TEST_CASE(magnusson_no_swap_failure_case)\n{\n    Graph::Configuration config(false, false, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 2\"));\n\n    Graph::NodePtr n3 = g.addNode(1, {0, 5}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n    Graph::NodePtr n4 = g.addNode(1, {0, 15}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 2\"));\n\n    Graph::NodePtr n5 = g.addNode(2, {0, 2}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 1\"));\n    Graph::NodePtr n6 = g.addNode(2, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 2\"));\n\n    g.addMoveArc(n1, n3, {0.0});\n    g.addMoveArc(n2, n4, {0.0});\n    g.addMoveArc(n3, n5, {4.0});\n    g.addMoveArc(n4, n5, {0.0});\n    g.addMoveArc(n4, n6, {0.0});\n\n    Magnusson tracker(&g, false);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    BOOST_CHECK_EQUAL(score, 18.0);\n    BOOST_CHECK_EQUAL(paths.size(), 1);\n}\n\nBOOST_AUTO_TEST_CASE(magnusson_simple_swap_test)\n{\n    Graph::Configuration config(false, false, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 2\"));\n\n    Graph::NodePtr n3 = g.addNode(1, {0, 5}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n    Graph::NodePtr n4 = g.addNode(1, {0, 15}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 2\"));\n\n    Graph::NodePtr n5 = g.addNode(2, {0, 2}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 1\"));\n    Graph::NodePtr n6 = g.addNode(2, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 2\"));\n\n    g.addMoveArc(n1, n3, {0.0});\n    g.addMoveArc(n2, n4, {0.0});\n    g.addMoveArc(n3, n5, {4.0});\n    g.addMoveArc(n4, n5, {0.0});\n    g.addMoveArc(n4, n6, {0.0});\n\n    Magnusson tracker(&g, true, true);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    BOOST_CHECK_EQUAL(score, 29.0);\n    BOOST_CHECK_EQUAL(paths.size(), 2);\n\n    // check the paths\n    for(TrackingAlgorithm::Path& p : paths)\n    {\n        for(Arc* a : p)\n        {\n            BOOST_CHECK_NE(a->getType(), Arc::Swap);\n            BOOST_CHECK(a->getSourceNode() != n4.get() || a->getTargetNode() != n5.get());\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(magnusson_simple_swap_test_with_app_dis)\n{\n    Graph::Configuration config(true, true, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 2\"));\n\n    Graph::NodePtr n3 = g.addNode(1, {0, 10}, {10.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n    Graph::NodePtr n4 = g.addNode(1, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 2: Node 2\"));\n\n    g.addMoveArc(n1, n3, {0.0});\n    g.addMoveArc(n1, n4, {2.0});\n    g.addMoveArc(n2, n4, {2.0});\n\n    Magnusson tracker(&g, true, true);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    // BOOST_CHECK_EQUAL(score, 29.0);\n    // BOOST_CHECK_EQUAL(paths.size(), 2);\n}\n\nBOOST_AUTO_TEST_CASE(magnusson_two_possible_swaps)\n{\n    Graph::Configuration config(false, false, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 2\"));\n    Graph::NodePtr n10 = g.addNode(0, {0, 2}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 3\"));\n\n    Graph::NodePtr n3 = g.addNode(1, {0, 5}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n    Graph::NodePtr n4 = g.addNode(1, {0, 15}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 2\"));\n    Graph::NodePtr n11 = g.addNode(0, {0, 2}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 3\"));\n\n    Graph::NodePtr n5 = g.addNode(2, {0, 2}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 1\"));\n    Graph::NodePtr n6 = g.addNode(2, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 2\"));\n    Graph::NodePtr n12 = g.addNode(2, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 3\"));\n\n    g.addMoveArc(n1, n3, {0.0});\n    g.addMoveArc(n2, n4, {0.0});\n    g.addMoveArc(n3, n5, {4.0});\n    g.addMoveArc(n4, n5, {0.0});\n    g.addMoveArc(n4, n6, {0.0});\n    g.addMoveArc(n10, n11, {0.0});\n    g.addMoveArc(n11, n12, {0.0});\n    g.addMoveArc(n11, n5, {0.0});\n    g.addMoveArc(n4, n12, {0.0});\n\n    Magnusson tracker(&g, true, true);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    BOOST_CHECK_EQUAL(score, 34.0);\n    BOOST_CHECK_EQUAL(paths.size(), 3);\n}\n\nvoid buildGraph(Graph& g)\n{\n    std::vector<double> appearanceScore(2, -200);\n    std::vector<double> disappearanceScore(2, -200);\n    std::vector<double> divisionScore(2, -200);\n\n    // -----------------------------------------------------\n    // Timestep 1\n    Graph::NodePtr n_1_1 = g.addNode(0, {0, 3, 2}, appearanceScore, disappearanceScore,\n                                        true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n\n    Graph::NodePtr n_1_2 = g.addNode(0, {0, 2, 7}, appearanceScore, disappearanceScore,\n                                        true, false, std::make_shared<NameData>(\"Timestep 1: Node 2\"));\n\n    Graph::NodePtr n_1_3 = g.addNode(0, {0, 3, -2}, appearanceScore, disappearanceScore,\n                                        true, false, std::make_shared<NameData>(\"Timestep 1: Node 3\"));\n\n    // -----------------------------------------------------\n    // Timestep 2\n    Graph::NodePtr n_2_1 = g.addNode(1, {0, 4, 2}, appearanceScore, disappearanceScore,\n                                        false, false, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n\n    Graph::NodePtr n_2_2 = g.addNode(1, {0, 2, 0}, appearanceScore, disappearanceScore,\n                                        false, false, std::make_shared<NameData>(\"Timestep 2: Node 2\"));\n\n    Graph::NodePtr n_2_3 = g.addNode(1, {0, 2, -2}, appearanceScore, disappearanceScore,\n                                        false, false, std::make_shared<NameData>(\"Timestep 2: Node 3\"));\n\n    Graph::NodePtr n_2_4 = g.addNode(1, {0, 2, 0}, appearanceScore, {-1.0, -1.0},\n                                        false, false, std::make_shared<NameData>(\"Timestep 2: Node 4\"));\n\n    g.addMoveArc(n_1_1, n_2_1, {0.0});\n    g.addMoveArc(n_1_2, n_2_2, {0.0});\n    g.addMoveArc(n_1_2, n_2_3, {0.0});\n    g.addMoveArc(n_1_3, n_2_4, {0.0});\n\n    // -----------------------------------------------------\n    // Timestep 3\n    Graph::NodePtr n_3_1 = g.addNode(2, {0, 3, 5}, appearanceScore, disappearanceScore,\n                                        false, false, std::make_shared<NameData>(\"Timestep 3: Node 1\"));\n\n    Graph::NodePtr n_3_2 = g.addNode(2, {0, 2, 2}, appearanceScore, disappearanceScore,\n                                        false, false, std::make_shared<NameData>(\"Timestep 3: Node 2\"));\n\n    Graph::NodePtr n_3_3 = g.addNode(2, {0, 3, 0}, appearanceScore, disappearanceScore,\n                                        false, false, std::make_shared<NameData>(\"Timestep 3: Node 3\"));\n\n\n    g.addMoveArc(n_2_1, n_3_1, {0.0});\n    g.addMoveArc(n_2_2, n_3_2, {0.0});\n    g.addMoveArc(n_2_3, n_3_3, {0.0});\n\n    // -----------------------------------------------------\n    // Timestep 4\n    Graph::NodePtr n_4_1 = g.addNode(3, {0, 4, 3}, appearanceScore, disappearanceScore,\n                                        false, true, std::make_shared<NameData>(\"Timestep 4: Node 1\"));\n\n    Graph::NodePtr n_4_2 = g.addNode(3, {0, 2, 1}, appearanceScore, disappearanceScore,\n                                        false, true, std::make_shared<NameData>(\"Timestep 4: Node 2\"));\n\n    Graph::NodePtr n_4_3 = g.addNode(3, {0, 2, -4}, appearanceScore, disappearanceScore,\n                                        false, true, std::make_shared<NameData>(\"Timestep 4: Node 3\"));\n\n    Graph::NodePtr n_4_4 = g.addNode(3, {0, 4, 2}, appearanceScore, disappearanceScore,\n                                        false, true, std::make_shared<NameData>(\"Timestep 4: Node 4\"));\n\n    g.addMoveArc(n_3_1, n_4_1, {0.0});\n    g.addMoveArc(n_3_1, n_4_2, {0.0});\n    g.addMoveArc(n_3_2, n_4_2, {0.0});\n    g.addMoveArc(n_3_2, n_4_3, {0.0});\n    g.addMoveArc(n_3_3, n_4_3, {0.0});\n    g.addMoveArc(n_3_3, n_4_4, {0.0});\n\n    g.allowMitosis(n_3_2, n_4_3, -1);\n    g.allowMitosis(n_3_3, n_4_3, 2);\n\n    std::cout << \"Done setting up graph\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_full_magnusson_no_swap)\n{\n    Graph::Configuration config(true, true, true);\n    Graph g(config);\n\n    buildGraph(g);\n\t\n    // -----------------------------------------------------\n    // Tracking\n    Magnusson tracker(&g, false, true);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    BOOST_CHECK_EQUAL(paths.size(), 5);\n    BOOST_CHECK_EQUAL(score, 44.0);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n}\n\n\nBOOST_AUTO_TEST_CASE(test_full_magnusson_with_swap)\n{\n    Graph::Configuration config(true, true, true);\n    Graph g(config);\n\n    buildGraph(g);\n\n    // -----------------------------------------------------\n    // Tracking\n    Magnusson tracker(&g, true, true);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    BOOST_CHECK_EQUAL(paths.size(), 5);\n    BOOST_CHECK_EQUAL(score, 44.0);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_full_magnusson_graph_constness)\n{\n    Graph::Configuration config(true, true, true);\n    Graph g(config);\n\n    buildGraph(g);\n\n    size_t num_arcs = g.getNumArcs();\n    size_t num_timesteps = g.getNumTimesteps();\n    size_t num_nodes = g.getNumNodes();\n\n    // -----------------------------------------------------\n    // Tracking\n    Magnusson tracker(&g, true, true);\n    std::vector<TrackingAlgorithm::Path> paths;\n    tracker.track(paths);\n\n    BOOST_CHECK_EQUAL(g.getNumArcs(), num_arcs);\n    BOOST_CHECK_EQUAL(g.getNumNodes(), num_nodes);\n    BOOST_CHECK_EQUAL(g.getNumTimesteps(), num_timesteps);\n}\n\nvoid updateNode(Node* n)\n{\n    n->updateBestInArcAndScore();\n    \n    for(Node::ArcIt outArc = n->getOutArcsBegin(); outArc != n->getOutArcsEnd(); ++outArc)\n    {\n        (*outArc)->update();\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_backward_path)\n{\n    using std::placeholders::_1;\n    Graph::Configuration config(true, true, true);\n    Graph g(config);\n\n    buildGraph(g);\n\n    // -----------------------------------------------------\n    // Tracking\n    Magnusson tracker(&g, true, true);\n    // init best in arcs\n    for(size_t t = 0; t < g.getNumTimesteps(); ++t)\n    {\n        g.visitNodesInTimestep(t, std::bind(&updateNode, _1));\n    }\n    g.visitSpecialNodes(std::bind(&updateNode, _1));\n\n    TrackingAlgorithm::Solution paths;\n    tracker.findNonintersectingBackwardPaths(&g.getSourceNode(), &g.getSinkNode(), paths);\n\n    BOOST_CHECK(paths.size() > 0);\n    BOOST_CHECK(paths.size() <= g.getSinkNode().getNumInArcs());\n\n    // test that none of the paths overlap\n    std::map<const Arc*, size_t> arcUseCount;\n    for(TrackingAlgorithm::Path& p : paths)\n    {\n        for(const Arc* a : p)\n        {\n            BOOST_CHECK(arcUseCount.find(a) == arcUseCount.end());\n            arcUseCount[a] = 1;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_full_magnusson_fast_1st_iter)\n{\n    Graph::Configuration config(true, true, true);\n    Graph g(config);\n\n    buildGraph(g);\n    \n    // -----------------------------------------------------\n    // Tracking\n    Magnusson tracker(&g, false, true, true);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    BOOST_CHECK(paths.size() <= 5);\n    BOOST_CHECK(score <= 44.0);\n    BOOST_CHECK(score >= 0);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n\n    // Magnusson tracker2(&g, false, false, false);\n    // std::vector<TrackingAlgorithm::Path> paths2;\n    // score = tracker2.track(paths2);\n    // BOOST_CHECK(tracker.getElapsedSeconds() < tracker2.getElapsedSeconds());\n}\n\nBOOST_AUTO_TEST_CASE(test_magnusson_maxNumPaths)\n{\n    Graph::Configuration config(true, true, true);\n    Graph g(config);\n\n    buildGraph(g);\n    \n    // -----------------------------------------------------\n    // Tracking\n    Magnusson tracker(&g, false, true, true);\n    std::vector<TrackingAlgorithm::Path> paths;\n    tracker.setMaxNumberOfPaths(2);\n    double score = tracker.track(paths);\n\n    BOOST_CHECK(paths.size() == 2);\n    BOOST_CHECK(score <= 44.0);\n    BOOST_CHECK(score >= 0);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n\n    // Magnusson tracker2(&g, false, false, false);\n    // std::vector<TrackingAlgorithm::Path> paths2;\n    // score = tracker2.track(paths2);\n    // BOOST_CHECK(tracker.getElapsedSeconds() < tracker2.getElapsedSeconds());\n}\n\nBOOST_AUTO_TEST_CASE(magnusson_selector_func)\n{\n    Graph::Configuration config(false, false, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 2\"));\n\n    Graph::NodePtr n3 = g.addNode(1, {0, 5}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n    Graph::NodePtr n4 = g.addNode(1, {0, 15}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 2\"));\n\n    Graph::NodePtr n5 = g.addNode(2, {0, 2}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 1\"));\n    Graph::NodePtr n6 = g.addNode(2, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 2\"));\n\n    g.addMoveArc(n1, n3, {0.0});\n    g.addMoveArc(n2, n4, {0.0});\n    g.addMoveArc(n3, n5, {4.0});\n    g.addMoveArc(n4, n5, {0.0});\n    g.addMoveArc(n4, n6, {0.0});\n\n    Magnusson tracker(&g, false);\n    tracker.setPathStartSelectorFunction([](Node* n) -> Arc* {\n        Node::ArcIt it = n->getInArcsBegin() + (n->getNumInArcs() - 1);\n        return *it;\n    });\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    BOOST_CHECK_EQUAL(score, 17.0);\n    BOOST_CHECK_EQUAL(paths.size(), 1);\n}\n\nBOOST_AUTO_TEST_CASE(magnusson_selector_func_2nd_best)\n{\n    Graph::Configuration config(false, false, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 2\"));\n\n    Graph::NodePtr n3 = g.addNode(1, {0, 5}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n    Graph::NodePtr n4 = g.addNode(1, {0, 15}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 2\"));\n\n    Graph::NodePtr n5 = g.addNode(2, {0, 2}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 1\"));\n    Graph::NodePtr n6 = g.addNode(2, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 2\"));\n\n    g.addMoveArc(n1, n3, {0.0});\n    g.addMoveArc(n2, n4, {0.0});\n    g.addMoveArc(n3, n5, {4.0});\n    g.addMoveArc(n4, n5, {0.0});\n    g.addMoveArc(n4, n6, {0.0});\n\n    Magnusson tracker(&g, false);\n    tracker.setPathStartSelectorFunction(selectSecondBestInArc);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    BOOST_CHECK_EQUAL(score, 29.0);\n    BOOST_CHECK_EQUAL(paths.size(), 2);\n}\n\nBOOST_AUTO_TEST_CASE(magnusson_selector_func_random)\n{\n    Graph::Configuration config(false, false, false);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 1\"));\n    Graph::NodePtr n2 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<NameData>(\"Timestep 1: Node 2\"));\n\n    Graph::NodePtr n3 = g.addNode(1, {0, 5}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 1\"));\n    Graph::NodePtr n4 = g.addNode(1, {0, 15}, {0.0}, {0.0}, false, false, std::make_shared<NameData>(\"Timestep 2: Node 2\"));\n\n    Graph::NodePtr n5 = g.addNode(2, {0, 2}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 1\"));\n    Graph::NodePtr n6 = g.addNode(2, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<NameData>(\"Timestep 3: Node 2\"));\n\n    g.addMoveArc(n1, n3, {0.0});\n    g.addMoveArc(n2, n4, {0.0});\n    g.addMoveArc(n3, n5, {4.0});\n    g.addMoveArc(n4, n5, {0.0});\n    g.addMoveArc(n4, n6, {0.0});\n\n    Magnusson tracker(&g, false);\n    tracker.setPathStartSelectorFunction(selectAtRandom);\n    std::vector<TrackingAlgorithm::Path> paths;\n    double score = tracker.track(paths);\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n    BOOST_CHECK(score >= 17.0);\n    BOOST_CHECK(paths.size() >= 1);\n}\n\n\nclass PositionData2D : public UserData\n{\npublic:\n    PositionData2D(double x, double y):\n        x_(x),\n        y_(y)\n    {}\n\n    virtual std::string toString() const \n    { \n        std::stringstream s;\n        s << \"Pos(\" << x_ << \", \" << y_ << \")\"; \n        return s.str();\n    }\n\n    double X() const { return x_; }\n    double Y() const { return y_; }\nprivate:\n    double x_, y_;\n};\n\n/*\n// TODO: fix swap arc handling when motion model is present!\nBOOST_AUTO_TEST_CASE(test_full_magnusson_motion_model)\n{\n    Graph::Configuration config(true, true, true);\n    Graph g(config);\n\n    Graph::NodePtr n1 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<PositionData2D>(0,0));\n    Graph::NodePtr n2 = g.addNode(0, {0, 1}, {0.0}, {0.0}, true, false, std::make_shared<PositionData2D>(1,0));\n\n    Graph::NodePtr n3 = g.addNode(1, {0, 5}, {0.0}, {0.0}, false, false, std::make_shared<PositionData2D>(0,1));\n    Graph::NodePtr n4 = g.addNode(1, {0, 15}, {0.0}, {0.0}, false, false, std::make_shared<PositionData2D>(1,1));\n\n    Graph::NodePtr n5 = g.addNode(2, {0, 2}, {0.0}, {0.0}, false, true, std::make_shared<PositionData2D>(0,2));\n    Graph::NodePtr n6 = g.addNode(2, {0, 1}, {0.0}, {0.0}, false, true, std::make_shared<PositionData2D>(1,2));\n\n    g.addMoveArc(n1, n3, {0.0});\n    g.addMoveArc(n2, n4, {0.0});\n    g.addMoveArc(n3, n5, {4.0});\n    g.addMoveArc(n4, n5, {0.0});\n    g.addMoveArc(n4, n6, {0.0});\n\n    // set up motion model\n    Magnusson::MotionModelScoreFunction momoscofu = [&](Node* a, Node* b, Node* c)\n    {\n        typedef std::shared_ptr<PositionData2D> Pos2DPtr;\n\n        // only evaluate if we're looking at 3 proper nodes, otherwise return default value\n        if(a == nullptr || b == nullptr || c == nullptr || g.isSpecialNode(a) || g.isSpecialNode(b) || g.isSpecialNode(c))\n        {\n            return -10.0;\n        }\n\n        Pos2DPtr posA = std::static_pointer_cast<PositionData2D>(a->getUserData());\n        Pos2DPtr posB = std::static_pointer_cast<PositionData2D>(b->getUserData());\n        Pos2DPtr posC = std::static_pointer_cast<PositionData2D>(c->getUserData());\n        double dist1 = sqrt( pow(posA->X() - posB->X(), 2.0) + pow(posA->Y() - posB->Y(), 2.0) );\n        double dist2 = sqrt( pow(posC->X() - posB->X(), 2.0) + pow(posC->Y() - posB->Y(), 2.0) );\n\n        double velocityMagnitude = fabsf(dist1 - dist2);\n        std::cout << \"Points: {\" << posA->toString() << \", \" << posB->toString() << \", \" << posC->toString()\n                  << \"} have distances \" << dist1 << \", \" << dist2 << \" and vel \" << velocityMagnitude << std::endl;\n        return -velocityMagnitude;\n    };\n    \n    // -----------------------------------------------------\n    // Tracking\n    Magnusson tracker(&g, false, false);\n    std::vector<TrackingAlgorithm::Path> paths;\n    tracker.setMotionModelScoreFunction(momoscofu);\n    double score = tracker.track(paths);\n\n    BOOST_CHECK_EQUAL(paths.size(), 3);\n    BOOST_CHECK(score < 24.6 && score > 24.5); // should be 25 - (sqrt(2)-1)\n\n    std::cout << \"Tracker returned score \" << score << std::endl;\n}\n*/\n", "meta": {"hexsha": "947f176cd05ef2a58b5c42a5919a7900378b89de", "size": 22843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_magnusson.cpp", "max_stars_repo_name": "ilastik/dpct", "max_stars_repo_head_hexsha": "59f553d917ef257c3e4c230752979263db7a57e1", "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_magnusson.cpp", "max_issues_repo_name": "ilastik/dpct", "max_issues_repo_head_hexsha": "59f553d917ef257c3e4c230752979263db7a57e1", "max_issues_repo_licenses": ["MIT"], "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_magnusson.cpp", "max_forks_repo_name": "ilastik/dpct", "max_forks_repo_head_hexsha": "59f553d917ef257c3e4c230752979263db7a57e1", "max_forks_repo_licenses": ["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.9812286689, "max_line_length": 130, "alphanum_fraction": 0.5948430591, "num_tokens": 7307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "/*\n * Copyright 2017 Maeve Automation\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 \"ar_isp_field/node_handler.h\"\n\n#include <cv_bridge/cv_bridge.h>\n#include <tf2_eigen/tf2_eigen.h>\n#include <boost/optional.hpp>\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"ar_isp_field/geometry.h\"\n#include \"open_maeve/isp_field/isp_field.h\"\n#include \"open_maeve/isp_field/visualize.h\"\n#include \"open_maeve/maeve_geometry/tau.h\"\n\nnamespace open_maeve {\nnamespace {\nconst auto EPS = 1e-4;\nconst auto NaN = std::numeric_limits<double>::quiet_NaN();\nconst auto INF = std::numeric_limits<double>::infinity();\n}  // namespace\n\n//------------------------------------------------------------------------------\n\nstd::vector<std::string> AR_ISPFieldNodeHandler::initializeTimeQueues(\n    const std::vector<int>& id_list) {\n  std::vector<std::string> frame_names;\n  frame_names.reserve(id_list.size());\n\n  std::for_each(std::begin(id_list), std::end(id_list), [&](const int id) {\n    const auto ar_frame_name = params_.ar_frame_prefix + std::to_string(id);\n    frame_names.push_back(ar_frame_name);\n    ar_max_extent_time_queue_[ar_frame_name] = MaeveTimeQueue<double>(\n        params_.ar_time_queue_size, params_.ar_time_queue_max_gap);\n  });\n\n  return frame_names;\n}\n\n//------------------------------------------------------------------------------\n\nAR_ISPFieldNodeHandler::AR_ISPFieldNodeHandler(const std::string& node_name)\n    : nh_(node_name), it_(nh_), tf2_listener_(tf2_buffer_) {\n  if (!params_.load(nh_)) {\n    ROS_FATAL_STREAM(\"Failed to load parameters. Fatal error.\");\n    return;\n  }\n\n  // Set up frame list and time queues.\n  ar_obstacle_tag_frames_ = initializeTimeQueues(params_.ar_tag_obstacle_ids);\n  ar_target_tag_frames_ = initializeTimeQueues(params_.ar_tag_target_ids);\n\n  // Compute raw tag corner points (CW ordering).\n  const auto half_extent = params_.ar_tag_size / 2.0;\n  ar_corner_points_[0] = Eigen::Vector3d(half_extent, -half_extent, 0.0);\n  ar_corner_points_[1] = Eigen::Vector3d(half_extent, half_extent, 0.0);\n  ar_corner_points_[2] = Eigen::Vector3d(-half_extent, half_extent, 0.0);\n  ar_corner_points_[3] = Eigen::Vector3d(-half_extent, -half_extent, 0.0);\n\n  // Instantiate transforms.\n  hc_ = PotentialTransform<ConstraintType::HARD>(\n      params_.hard_constraint_transform);\n  sc_ = PotentialTransform<ConstraintType::SOFT>(\n      params_.soft_constraint_transform);\n\n  // Register callback.\n  camera_sub_ = it_.subscribeCamera(\n      params_.camera_topic, 1, &AR_ISPFieldNodeHandler::cameraCallback, this);\n\n  // Set up command handler.\n  command2d_mgr_.initialize(nh_, params_.control_command_input_topic);\n\n  // Control command output publisher.\n  control_command_output_pub_ =\n      nh_.advertise<controller_interface_msgs::Command2D>(\n          params_.control_command_output_topic, 1);\n\n  // Visualize?\n  viz_isp_field_pub_ = it_.advertise(params_.viz_isp_field_topic, 1);\n  horizon_visualizer_.initialize(\n      HorizonVisualizer::Params(params_.horizon_viz_height,\n                                sc_.shapeParameters().range_min,\n                                sc_.shapeParameters().range_max),\n      params_.visualize_horizons, it_);\n}\n\n//------------------------------------------------------------------------------\n\nstd::vector<cv::Point2d> AR_ISPFieldNodeHandler::projectPoints(\n    const Eigen::Affine3d& camera_T_artag) const {\n  // Compute the corner points under the given transform.\n  const auto corner_points =\n      arTagCornerPoints(camera_T_artag, ar_corner_points_);\n\n  // Allocate return structure.\n  std::vector<cv::Point2d> image_points;\n  image_points.reserve(corner_points.size());\n\n  // Convert Eigen -> OpenCV.\n  const auto camera_points = arEigenPoints2OpenCV(corner_points);\n\n  // Project camera_points into image_points.\n  for (auto i = 0; i < 4; ++i) {\n    image_points.push_back(camera_model_.project3dToPixel(camera_points[i]));\n  }\n\n  // Done.\n  return image_points;\n}\n\n//------------------------------------------------------------------------------\n\nboost::optional<std::tuple<Eigen::Affine3d, double>>\nAR_ISPFieldNodeHandler::getTransformAndStamp(const std::string& ar_tag_frame,\n                                             const ros::Time& timestamp) const {\n  Eigen::Affine3d T;\n  ros::Time T_timestamp;\n  try {\n    const auto T_msg = tf2_buffer_.lookupTransform(params_.camera_frame_name,\n                                                   ar_tag_frame, ros::Time(0));\n    T = tf2::transformToEigen(T_msg);\n    T_timestamp = T_msg.header.stamp;\n    const auto age = (timestamp - T_timestamp).toSec();\n\n    // If the transform is too old, the detection is stale.\n    if (age > params_.ar_tag_max_age) {\n      return boost::none;\n    }\n  } catch (const tf2::TransformException& ex) {\n    return boost::none;\n  }\n\n  return std::make_tuple(T, T_timestamp.toSec());\n}\n\n//------------------------------------------------------------------------------\n\nbool AR_ISPFieldNodeHandler::computePotentialFields(\n    const ros::Time& timestamp, const ConstraintType& constraint_type,\n    FieldMap& field_map) {\n  auto updated = false;\n\n  // Compute max extents for each AR tag and add to time queues.\n  std::for_each(\n      std::begin(field_map), std::end(field_map),\n      [&](FieldMap::value_type& pair) {\n        // Get references and initialize field.\n        const auto& frame_name = pair.first;\n        auto& field = pair.second;\n        field.setTo(0.0);\n\n        // Only use valid transforms.\n        auto t = NaN;\n        Eigen::Affine3d camera_T_artag = Eigen::Affine3d::Identity();\n        if (const auto vals = getTransformAndStamp(frame_name, timestamp)) {\n          std::tie(camera_T_artag, t) = *vals;\n        } else {\n          return;\n        }\n\n        // Project AR tag onto image plane.\n        const auto image_corner_points = projectPoints(camera_T_artag);\n\n        // Get max extent and add to time queue.\n        const auto s = arComputeMaxXY_Extent(image_corner_points);\n        ar_max_extent_time_queue_[frame_name].insert(t, s);\n\n        // Compute measurement values.\n        // TODO(me): should put a filter on these dt values.\n        auto s_dot = NaN;\n        auto t_delta = NaN;\n        if (const auto dt = ar_max_extent_time_queue_[frame_name].bfd_dt(t)) {\n          std::tie(t_delta, s_dot) = *dt;\n        } else {\n          // If the backward differencing operation fails probably the queue has\n          // recently become empty. It's expected and probably not an error.\n          return;\n        }\n        const auto tau = tauFromDiscreteScaleDt(s, s_dot, t_delta, EPS);\n        const auto tau_dot = 0.0;\n\n        // Compute potential values.\n        const auto p_value = (constraint_type == ConstraintType::HARD)\n                                 ? hc_(cv::Point2d(tau, tau_dot))\n                                 : sc_(cv::Point2d(params_.target_reward, 0.0));\n\n        // Print output?\n        if (params_.verbose && std::isfinite(tau)) {\n          ROS_INFO_STREAM(constraint_type << \" :\" << frame_name << \" - tau: \"\n                                          << tau << \", tau_dot: \" << tau_dot);\n          ROS_INFO_STREAM(constraint_type << \" :\" << frame_name\n                                          << \" - k0: \" << p_value.x\n                                          << \", k1: \" << p_value.y);\n        }\n\n        // Fill ISP.\n        arFillISP(p_value, image_corner_points, field);\n\n        // Mark that at least one potential field has been computed.\n        updated = true;\n      });\n\n  // Done.\n  return updated;\n}\n\n//------------------------------------------------------------------------------\n\nvoid AR_ISPFieldNodeHandler::initFieldStorage(\n    const cv::Size& size, const std::vector<std::string>& frame_list,\n    FieldMap& field_map) {\n  std::for_each(std::begin(frame_list), std::end(frame_list),\n                [&](const std::string& frame_name) {\n                  field_map[frame_name] = zeroISP_Field(size);\n                });\n}\n\n//------------------------------------------------------------------------------\n\nvoid AR_ISPFieldNodeHandler::cameraCallback(\n    const sensor_msgs::Image::ConstPtr& msg,\n    const sensor_msgs::CameraInfoConstPtr& info_msg) {\n  // Make sure field maps have storage allocated, but do it only once.\n  static auto init = true;\n  if (init) {\n    // Initialize camera model.\n    camera_model_.fromCameraInfo(info_msg);\n\n    // Initialize ISP controller.\n    params_.isp_controller_params.principal_point_x = camera_model_.cx();\n    params_.isp_controller_params.focal_length_x = camera_model_.fx();\n    isp_controller_ = ISP_Controller2D(params_.isp_controller_params);\n\n    // Initialize storage.\n    initFieldStorage(camera_model_.fullResolution(), ar_obstacle_tag_frames_,\n                     obstacle_field_map_);\n    initFieldStorage(camera_model_.fullResolution(), ar_target_tag_frames_,\n                     target_field_map_);\n    init = false;\n  }\n\n  // Compute a potential field for each tag.\n  const auto obstacles_updated = computePotentialFields(\n      msg->header.stamp, ConstraintType::HARD, obstacle_field_map_);\n  const auto targets_updated = computePotentialFields(\n      msg->header.stamp, ConstraintType::SOFT, target_field_map_);\n\n  // Compose fields into an ISP.\n  cv::Mat ISP = computeISP();\n\n  // Do any requested visualization.\n  visualize(ISP, msg->header);\n\n  // Get most recent desired control.\n  ControlCommand u_d;\n  if (const auto cmd_msg_ptr_opt = command2d_mgr_.most_recent_msg_ptr()) {\n    const auto& cmd_msg = *(*cmd_msg_ptr_opt);\n    u_d = command2D_Msg2ControlCommand(cmd_msg);\n    if (!u_d.valid()) {\n      u_d = params_.default_guidance_control;\n      ROS_ERROR_STREAM(\"u_d not valid: \"\n                       << u_d << \", sending default guidance control: \" << u_d);\n    }\n  } else {\n    u_d = params_.default_guidance_control;\n  }\n\n  // Don't try to use uninitialized controller.\n  if (!isp_controller_.isInitialized()) {\n    ROS_ERROR_STREAM(\"ISP controller is not initialized.\");\n    return;\n  }\n\n  // Compute control with desired method.\n  const auto& p = ISP_Controller2D::get_params(isp_controller_);\n  const cv::Rect ROI =\n      ISP_ROI(ISP, p.erosion_kernel.height, p.erosion_kernel.horizon);\n  const auto u_star = params_.potential_only_guidance\n                          ? isp_controller_.potentialControl(ISP, ROI)\n                          : isp_controller_.SD_Control(ISP, ROI, u_d);\n\n  // Visualize controller horizons; do this after computing control.\n  horizon_visualizer_.visualize(msg->header, isp_controller_);\n\n  // Publish control.\n  control_command_output_pub_.publish(\n      controlCommand2Command2D_Msg(u_star, msg->header));\n}\n\n//------------------------------------------------------------------------------\n\ncv::Mat AR_ISPFieldNodeHandler::computeISP() const {\n  // Initialize to zeroed field.\n  cv::Mat ISP = zeroISP_Field(camera_model_.fullResolution());\n\n  // Compose hard constraint field.\n  std::for_each(\n      std::begin(obstacle_field_map_), std::end(obstacle_field_map_),\n      [&](const FieldMap::value_type& pair) { ISP = ISP + pair.second; });\n\n  // Compose soft constraint field.\n  std::for_each(\n      std::begin(target_field_map_), std::end(target_field_map_),\n      [&](const FieldMap::value_type& pair) { ISP = ISP + pair.second; });\n\n  // Done.\n  return ISP;\n}\n\n//------------------------------------------------------------------------------\n\nvoid AR_ISPFieldNodeHandler::visualize(const cv::Mat& ISP,\n                                       const std_msgs::Header& header) const {\n  // If no topic, nothing to do.\n  if (params_.viz_isp_field_topic.empty()) {\n    return;\n  }\n\n  // Compute visualization of ISP.\n  const auto visual =\n      computeISPFieldVisualization(ISP, params_.viz_potential_bounds);\n\n  // Convert visualization to ROS message.\n  const auto viz_msg = cv_bridge::CvImage(header, \"bgr8\", visual).toImageMsg();\n\n  // Publish.\n  viz_isp_field_pub_.publish(viz_msg);\n}\n\n//------------------------------------------------------------------------------\n\n}  // namespace open_maeve\n", "meta": {"hexsha": "523c46653ce2f724e63c420fd3119bf83ef2aa6d", "size": 13112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visual_servoing/ar_isp_field/src/ar_isp_field/node_handler.cpp", "max_stars_repo_name": "togaen/open_maeve", "max_stars_repo_head_hexsha": "5a5916a8519f4184f5b73c74e5a229df45a02af5", "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": "visual_servoing/ar_isp_field/src/ar_isp_field/node_handler.cpp", "max_issues_repo_name": "togaen/open_maeve", "max_issues_repo_head_hexsha": "5a5916a8519f4184f5b73c74e5a229df45a02af5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "visual_servoing/ar_isp_field/src/ar_isp_field/node_handler.cpp", "max_forks_repo_name": "togaen/open_maeve", "max_forks_repo_head_hexsha": "5a5916a8519f4184f5b73c74e5a229df45a02af5", "max_forks_repo_licenses": ["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.8314606742, "max_line_length": 80, "alphanum_fraction": 0.6375076266, "num_tokens": 2955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "//   \n//   Project Name:        Kratos       \n//   Last modified by:    $Author: antonia $\n//   Date:                $Date: 2009-01-14 12:09:16 $\n//   Revision:            $Revision: 1.6 $\n//\n//\n\n\n// System includes \n\n// External includes \n#include <boost/python.hpp>\n\n\n// Project includes\n#include \"includes/define.h\"\n#include \"python/add_equation_systems_to_python.h\" \n#include \"spaces/ublas_space.h\"\n//#include \"spaces/parallel_ublas_space.h\"\n\n#include \"linear_solvers/direct_solver.h\"\n#include \"linear_solvers/iterative_solver.h\"\n#include \"linear_solvers/skyline_lu_factorization_solver.h\"\n#include \"external_includes/superlu_solver.h\"\n#include \"external_includes/gmres_solver.h\"\n\n\nnamespace Kratos\n{\n    \nnamespace Python\n{\n    void  AddLinearSolversToPython()\n    {\n        typedef UblasSpace<double, CompressedMatrix, Vector> SpaceType;\n\t//      typedef ParallelUblasSpace<double, CompressedMatrix, Vector> ParallelSpaceType;\n        typedef UblasSpace<double, Matrix, Vector> LocalSpaceType;\n\t// typedef UblasSpace<double, Matrix, Vector> ParallelLocalSpaceType;\n        typedef LinearSolver<SpaceType,  LocalSpaceType> LinearSolverType;\n        //typedef LinearSolver<ParallelSpaceType,  ParallelLocalSpaceType> ParallelLinearSolverType;\n        typedef DirectSolver<SpaceType,  LocalSpaceType> DirectSolverType;\n        //typedef Reorderer<ParallelSpaceType,  ParallelLocalSpaceType > ParallelReordererType;\n        //typedef DirectSolver<ParallelSpaceType,  ParallelLocalSpaceType, ParallelReordererType > ParallelDirectSolverType;\n        typedef SuperLUSolver<SpaceType,  LocalSpaceType> SuperLUSolverType;\n        typedef IterativeSolver<SpaceType, LocalSpaceType> IterativeSolverType;\n        typedef GMRESSolver<SpaceType, LocalSpaceType> GMRESSolverType;\n        typedef Preconditioner<SpaceType,  LocalSpaceType> PreconditionerType;\n        \n        using namespace boost::python;\n        \n        //***************************************************************************\n        //linear solvers\n        //***************************************************************************\n        class_<SuperLUSolverType, bases<DirectSolverType>, boost::noncopyable >\n                ( \"SuperLUSolver\",\n                  init<>() );\n        \n        class_<GMRESSolverType, bases<IterativeSolverType>, boost::noncopyable >\n                ( \"GMRESSolver\")\n                .def(init<double>())\n                .def(init<double, unsigned int>())\n                .def(init<double, unsigned int,  PreconditionerType::Pointer>())\n                .def(self_ns::str(self))\n                ;\n\n  }\n\t\n}  // namespace Python.\n\n} // Namespace Kratos\n\n", "meta": {"hexsha": "232cd424fcf14d18ee5ceaaa4559cbd24e995512", "size": 2656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/ExternalSolversApplication/custom_python/add_linear_solvers_to_python.cpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": "applications/ExternalSolversApplication/custom_python/add_linear_solvers_to_python.cpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": "applications/ExternalSolversApplication/custom_python/add_linear_solvers_to_python.cpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": 36.3835616438, "max_line_length": 124, "alphanum_fraction": 0.6415662651, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19582702163591223}}
{"text": "// Copyright (c) 2010 Satoshi Nakamoto\n// Copyright (c) 2009-2015 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"chainparams.h\"\n#include \"consensus/merkle.h\"\n#include \"consensus/consensus.h\"\n#include \"zerocoin_params.h\"\n\n#include \"tinyformat.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include \"libzerocoin/bitcoin_bignum/bignum.h\"\n\n#include <assert.h>\n\n#include <boost/assign/list_of.hpp>\n\n#include \"chainparamsseeds.h\"\n#include \"arith_uint256.h\"\n\n\nstatic CBlock CreateGenesisBlock(const char *pszTimestamp, const CScript &genesisOutputScript, uint32_t nTime, uint32_t nNonce,\n        uint32_t nBits, int32_t nVersion, const CAmount &genesisReward,\n        std::vector<unsigned char> extraNonce) {\n    CMutableTransaction txNew;\n    txNew.nVersion = 1;\n    txNew.vin.resize(1);\n    txNew.vout.resize(1);\n    txNew.vin[0].scriptSig = CScript() << 504365040 << CBigNum(4).getvch() << std::vector < unsigned char >\n    ((const unsigned char *) pszTimestamp, (const unsigned char *) pszTimestamp + strlen(pszTimestamp)) << extraNonce;\n    txNew.vout[0].nValue = genesisReward;\n    txNew.vout[0].scriptPubKey = genesisOutputScript;\n\n    CBlock genesis;\n    genesis.nTime = nTime;\n    genesis.nBits = nBits;\n    genesis.nNonce = nNonce;\n    genesis.nVersion = nVersion;\n    genesis.vtx.push_back(txNew);\n    genesis.hashPrevBlock.SetNull();\n    genesis.hashMerkleRoot = BlockMerkleRoot(genesis);\n    return genesis;\n}\n\nstatic CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount &genesisReward,\n        std::vector<unsigned char> extraNonce) {\n    const char *pszTimestamp = \"Severe acute respiratory syndrome coronavirus 2 - SARS-CoV-2\";\n    const CScript genesisOutputScript = CScript();\n    return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward,\n                              extraNonce);\n}\n\n\nclass CMainParams : public CChainParams {\npublic:\n    CMainParams() {\n        strNetworkID = \"main\";\n\n        consensus.chainType = Consensus::chainMain;\n\n        consensus.nSubsidyHalvingFirst = 302438;\n        consensus.nSubsidyHalvingInterval = 420000;\n        consensus.nSubsidyHalvingStopBlock = 3646849;\n\n        consensus.nMajorityEnforceBlockUpgrade = 8100;\n        consensus.nMajorityRejectBlockOutdated = 10260;\n        consensus.nMajorityWindow = 10800;\n        consensus.powLimit = uint256S(\"00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n        //static const int64 nInterval = nTargetTimespan / nTargetSpacing;\n        consensus.nPowTargetTimespan = 40 * 60; // 40 minutes between retargets \n        consensus.nPowTargetSpacing = 120; // alternate PoW/PoS every one minute\n        consensus.nDgwPastBlocks = 30; // number of blocks to average in Dark Gravity Wave\n        consensus.fPowAllowMinDifficultyBlocks = false;\n        consensus.fPowNoRetargeting = false;\n        consensus.nRuleChangeActivationThreshold = 10260; // 95% of 10800\n        consensus.nMinerConfirmationWindow = 10800; // nPowTargetTimespan / nPowTargetSpacing\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1580217929; // January 1, 2008\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1611840329; // December 31, 2008\n\n        // Deployment of BIP68, BIP112, and BIP113.\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1580217929; // May 1st, 2016\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1611840329; // May 1st, 2017\n\n        // Deployment of SegWit (BIP141, BIP143, and BIP147)\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1580217929; // November 15th, 2016.\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1611840329; // November 15th, 2017.\n\n        // The best chain should have at least this much work\n        //consensus.nMinimumChainWork = uint256S(\"0000000000000000000000000000000000000000000000002ee3ae8b33a68f5f\");\n        consensus.nMinimumChainWork = uint256S(\"0x0\");\n\n        consensus.nCheckBugFixedAtBlock = ZC_CHECK_BUG_FIXED_AT_BLOCK;\n        consensus.nXFSnodePaymentsBugFixedAtBlock = ZC_XFSNODE_PAYMENT_BUG_FIXED_AT_BLOCK;\n\t    consensus.nSpendV15StartBlock = ZC_V1_5_STARTING_BLOCK;\n\t    consensus.nSpendV2ID_1 = ZC_V2_SWITCH_ID_1;\n\t    consensus.nSpendV2ID_10 = ZC_V2_SWITCH_ID_10;\n\t    consensus.nSpendV2ID_25 = ZC_V2_SWITCH_ID_25;\n\t    consensus.nSpendV2ID_50 = ZC_V2_SWITCH_ID_50;\n\t    consensus.nSpendV2ID_100 = ZC_V2_SWITCH_ID_100;\n\t    consensus.nModulusV2StartBlock = ZC_MODULUS_V2_START_BLOCK;\n        consensus.nModulusV1MempoolStopBlock = ZC_MODULUS_V1_MEMPOOL_STOP_BLOCK;\n\t    consensus.nModulusV1StopBlock = ZC_MODULUS_V1_STOP_BLOCK;\n        consensus.nMultipleSpendInputsInOneTxStartBlock = ZC_MULTIPLE_SPEND_INPUT_STARTING_BLOCK;\n        consensus.nDontAllowDupTxsStartBlock = 1;\n\n        // xfsnode params\n        consensus.nXFSnodePaymentsStartBlock = HF_XFSNODE_PAYMENT_START; // not true, but it's ok as long as it's less then nXFSnodePaymentsIncreaseBlock\n\n\n        consensus.nDisableZerocoinStartBlock = 1;\n\n        nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin\n\n        nPoolMaxTransactions = 3;\n        nFulfilledRequestExpireTime = 60*60; // fulfilled requests expire in 1 hour\n        strSporkPubKey = \"04290423a6ef6be3367257ea7f1b78d3e252103f6cf5659c26b187ed7b4e6380ace84a453c3a9b65aebb4cd1b039cf8dc1caff815f8cdfa3fd3278da007913ec04\";\n        //Stake stuff\n        consensus.nFirstPOSBlock = 52;\n        consensus.nStakeTimestampMask = 0xf; // 15\n        consensus.posLimit = uint256S(\"00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n\n        consensus.nDisableZCoinClientCheckTime = 1593515602; //Date and time (GMT): Tuesday, June 2, 2020 11:07:41 PM\n        consensus.nBlacklistEnableHeight = 1;\n\n        pchMessageStart[0] = 0xc1;\n        pchMessageStart[1] = 0x1a;\n        pchMessageStart[2] = 0xf1;\n        pchMessageStart[3] = 0xff;\n        nDefaultPort = 8668;\n        nPruneAfterHeight = 100000;\n\n        std::vector<unsigned char> extraNonce(4);\n\t    extraNonce[0] = 0xaa;\n        extraNonce[1] = 0xc1;\n        extraNonce[2] = 0xf1;\n        extraNonce[3] = 0xcb;\n        genesis = CreateGenesisBlock(ZC_GENESIS_BLOCK_TIME, 7382559, 0x1e00ffff, 2, 0 * COIN, extraNonce);\n\n        consensus.hashGenesisBlock = genesis.GetHash();    \n\n        assert(consensus.hashGenesisBlock == uint256S(\"0x0000002483dee2a97df95f61d810f2115bc83134d3c399168d682ea1da6d0fd8\"));\n        assert(genesis.hashMerkleRoot     == uint256S(\"ed2efdba33e9bc206cba44a213440e29a0902740f4f4209bdea833c48673606f\"));\n        //Initial seeders for use\n        vSeeds.push_back(CDNSSeedData(\"peer5.xfscore.org\", \"peer5.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer1.xfscore.org\", \"peer1.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer2.xfscore.org\", \"peer2.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer3.xfscore.org\", \"peer3.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer4.xfscore.org\", \"peer4.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer6.xfscore.org\", \"peer6.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer7.xfscore.org\", \"peer7.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer8.xfscore.org\", \"peer8.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer9.xfscore.org\", \"peer9.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer10.xfscore.org\", \"peer10.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer11.xfscore.org\", \"peer11.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer12.xfscore.org\", \"peer12.xfscore.org\", false));\n        vSeeds.push_back(CDNSSeedData(\"peer13.xfscore.org\", \"peer13.xfscore.org\", false));\n\n        // Note that of those with the service bits flag, most only support a subset of possible options\n        base58Prefixes[PUBKEY_ADDRESS] = std::vector < unsigned char > (1, 75); //XFS address starts with 'X'\n        base58Prefixes[SCRIPT_ADDRESS] = std::vector < unsigned char > (1, 5);\n        base58Prefixes[SECRET_KEY] = std::vector < unsigned char > (1, 210);\n        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container < std::vector < unsigned char > > ();\n        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container < std::vector < unsigned char > > ();\n\n        vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));\n\n        fMiningRequiresPeers = false;\n        fDefaultConsistencyChecks = false;\n        fRequireStandard = true;\n        fMineBlocksOnDemand = false;\n        fTestnetToBeDeprecatedFieldRPC = false;\n        nConsecutivePoWHeight = 40000;\n        nMaxPoWBlocks = 1000;\n        checkpointData = (CCheckpointData) {\n                boost::assign::map_list_of\n                    (0, genesis.GetHash())\n                    //(200,uint256S(\"0x2eac965dcd0e10574dc05f44ee14756e5224bf521358e5455f33da1ad8a9536c\"))\n                    ,\n\n                1593268902, // * UNIX timestamp of last checkpoint block\n                148510,    // * total number of transactions between genesis and last checkpoint\n                //   (the tx=... number in the SetBestChain debug.log lines)\n                1440     // * estimated number of transactions per day after checkpoint\n        };\n        consensus.nSpendV15StartBlock = ZC_V1_5_STARTING_BLOCK;\n        consensus.nSpendV2ID_1 = ZC_V2_SWITCH_ID_1;\n        consensus.nSpendV2ID_10 = ZC_V2_SWITCH_ID_10;\n        consensus.nSpendV2ID_25 = ZC_V2_SWITCH_ID_25;\n        consensus.nSpendV2ID_50 = ZC_V2_SWITCH_ID_50;\n        consensus.nSpendV2ID_100 = ZC_V2_SWITCH_ID_100;\n        consensus.nModulusV2StartBlock = ZC_MODULUS_V2_START_BLOCK;\n        consensus.nModulusV1MempoolStopBlock = ZC_MODULUS_V1_MEMPOOL_STOP_BLOCK;\n        consensus.nModulusV1StopBlock = ZC_MODULUS_V1_STOP_BLOCK;\n\n        // Sigma related values.\n        consensus.nSigmaStartBlock = ZC_SIGMA_STARTING_BLOCK;\n        consensus.nSigmaPaddingBlock = ZC_SIGMA_PADDING_BLOCK;\n        consensus.nDisableUnpaddedSigmaBlock = ZC_SIGMA_DISABLE_UNPADDED_BLOCK;\n        consensus.nOldSigmaBanBlock = ZC_OLD_SIGMA_BAN_BLOCK;\n        consensus.nZerocoinV2MintMempoolGracefulPeriod = ZC_V2_MINT_GRACEFUL_MEMPOOL_PERIOD;\n        consensus.nZerocoinV2MintGracefulPeriod = ZC_V2_MINT_GRACEFUL_PERIOD;\n        consensus.nZerocoinV2SpendMempoolGracefulPeriod = ZC_V2_SPEND_GRACEFUL_MEMPOOL_PERIOD;\n        consensus.nZerocoinV2SpendGracefulPeriod = ZC_V2_SPEND_GRACEFUL_PERIOD;\n        consensus.nMaxSigmaInputPerBlock = ZC_SIGMA_INPUT_LIMIT_PER_BLOCK;\n        consensus.nMaxValueSigmaSpendPerBlock = ZC_SIGMA_VALUE_SPEND_LIMIT_PER_BLOCK;\n        consensus.nMaxSigmaInputPerTransaction = ZC_SIGMA_INPUT_LIMIT_PER_TRANSACTION;\n        consensus.nMaxValueSigmaSpendPerTransaction = ZC_SIGMA_VALUE_SPEND_LIMIT_PER_TRANSACTION;\n        consensus.nZerocoinToSigmaRemintWindowSize = 0;\n\n        // Dandelion related values.\n        consensus.nDandelionEmbargoMinimum = DANDELION_EMBARGO_MINIMUM;\n        consensus.nDandelionEmbargoAvgAdd = DANDELION_EMBARGO_AVG_ADD;\n        consensus.nDandelionMaxDestinations = DANDELION_MAX_DESTINATIONS;\n        consensus.nDandelionShuffleInterval = DANDELION_SHUFFLE_INTERVAL;\n        consensus.nDandelionFluff = DANDELION_FLUFF;\n    }\n};\n\nstatic CMainParams mainParams;\n\n/**\n * Testnet (v3)\n */\nclass CTestNetParams : public CChainParams {\npublic:\n    CTestNetParams() {\n        strNetworkID = \"test\";\n\n        consensus.chainType = Consensus::chainTestnet;\n\n        consensus.nSubsidyHalvingFirst = 302438;\n        consensus.nSubsidyHalvingInterval = 420000;\n        consensus.nSubsidyHalvingStopBlock = 3646849;\n\n        consensus.nMajorityEnforceBlockUpgrade = 51;\n        consensus.nMajorityRejectBlockOutdated = 75;\n        consensus.nMajorityWindow = 100;\n        consensus.BIP34Hash = uint256S(\"0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8\");\n        consensus.powLimit = uint256S(\"00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n        consensus.posLimit = uint256S(\"00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n        //Proof-of-Stake related values\n        consensus.nFirstPOSBlock = 135;//TODO akshaynexus :This needs to be decided\n        consensus.nStakeTimestampMask = 0xf; // 15\n        consensus.nPowTargetTimespan = 5 * 60; // 5 minutes between retargets\n        consensus.nPowTargetSpacing = 1 * 60; // 1 minute blocks\n        consensus.fPowAllowMinDifficultyBlocks = true;\n        consensus.fPowNoRetargeting = false;\n        consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains\n        consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008\n\n        // Deployment of BIP68, BIP112, and BIP113.\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017\n\n        // Deployment of SegWit (BIP141, BIP143, and BIP147)\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1462060800; // May 1st 2016\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1493596800; // May 1st 2017\n\n        // The best chain should have at least this much work.\n        consensus.nMinimumChainWork = uint256S(\"0x0\");\n\n        consensus.nSpendV15StartBlock = 5000;\n        consensus.nCheckBugFixedAtBlock = 1;\n        consensus.nXFSnodePaymentsBugFixedAtBlock = 1;\n\n        consensus.nSpendV2ID_1 = ZC_V2_TESTNET_SWITCH_ID_1;\n        consensus.nSpendV2ID_10 = ZC_V2_TESTNET_SWITCH_ID_10;\n        consensus.nSpendV2ID_25 = ZC_V2_TESTNET_SWITCH_ID_25;\n        consensus.nSpendV2ID_50 = ZC_V2_TESTNET_SWITCH_ID_50;\n        consensus.nSpendV2ID_100 = ZC_V2_TESTNET_SWITCH_ID_100;\n        consensus.nModulusV2StartBlock = ZC_MODULUS_V2_TESTNET_START_BLOCK;\n        consensus.nModulusV1MempoolStopBlock = ZC_MODULUS_V1_TESTNET_MEMPOOL_STOP_BLOCK;\n        consensus.nModulusV1StopBlock = ZC_MODULUS_V1_TESTNET_STOP_BLOCK;\n        consensus.nMultipleSpendInputsInOneTxStartBlock = 1;\n        consensus.nDontAllowDupTxsStartBlock = 18825;\n\n        // XFSnode params testnet\n        consensus.nXFSnodePaymentsStartBlock = 2200;\n        nMaxTipAge = 0x7fffffff; // allow mining on top of old blocks for testnet\n\n\n        consensus.nDisableZerocoinStartBlock = 50500;\n\n        nPoolMaxTransactions = 3;\n        nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes\n        strSporkPubKey = \"04ff38adc0c2fab7544d1123d664c2458d50c12b46988ef2214a6288883e19e56fb739ee3382f72a77cd9116169011cd739f84a3870781f856ae5d54f47e16cee8\";\n        strXFSnodePaymentsPubKey = \"04ff38adc0c2fab7544d1123d664c2458d50c12b46988ef2214a6288883e19e56fb739ee3382f72a77cd9116169011cd739f84a3870781f856ae5d54f47e16cee8\";\n\n        pchMessageStart[0] = 0xc1;\n        pchMessageStart[1] = 0x1a;\n        pchMessageStart[2] = 0xf1;\n        pchMessageStart[3] = 0xff;\n        nDefaultPort = 18168;\n        nPruneAfterHeight = 1000;\n\n        std::vector<unsigned char> extraNonce(4);\n\t    extraNonce[0] = 0xaa;\n        extraNonce[1] = 0xc1;\n        extraNonce[2] = 0xf1;\n        extraNonce[3] = 0xcb;\n        genesis = CreateGenesisBlock(ZC_GENESIS_BLOCK_TIME, 7382559, 0x1e00ffff, 2, 0 * COIN, extraNonce);\n        consensus.hashGenesisBlock = genesis.GetHash();\n        \n        assert(consensus.hashGenesisBlock ==\n                uint256S(\"0x0000002483dee2a97df95f61d810f2115bc83134d3c399168d682ea1da6d0fd8\"));\n        assert(genesis.hashMerkleRoot ==\n                uint256S(\"ed2efdba33e9bc206cba44a213440e29a0902740f4f4209bdea833c48673606f\"));\n        vFixedSeeds.clear();\n        vSeeds.clear();\n        // nodes with support for servicebits filtering should be at the top\n        // index test seeds\n        //vSeeds.push_back(CDNSSeedData(\"beta1.web.org\", \"beta1.web.org\", false));\n\n        base58Prefixes[PUBKEY_ADDRESS] = std::vector < unsigned char > (1, 65);\n        base58Prefixes[SCRIPT_ADDRESS] = std::vector < unsigned char > (1, 178);\n        base58Prefixes[SECRET_KEY] = std::vector < unsigned char > (1, 185);\n        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container < std::vector < unsigned char > > ();\n        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container < std::vector < unsigned char > > ();\n        vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));\n\n        fMiningRequiresPeers = true;\n        fDefaultConsistencyChecks = false;\n        fRequireStandard = false;\n        fMineBlocksOnDemand = false;\n        fTestnetToBeDeprecatedFieldRPC = true;\n\n        checkpointData = (CCheckpointData) {\n                boost::assign::map_list_of\n                    (0, uint256S(\"0x0000002483dee2a97df95f61d810f2115bc83134d3c399168d682ea1da6d0fd8\")),\n                    ZC_GENESIS_BLOCK_TIME,\n                    0,\n                    100.0\n        };\n\n        consensus.nSpendV15StartBlock = ZC_V1_5_TESTNET_STARTING_BLOCK;\n        consensus.nSpendV2ID_1 = ZC_V2_TESTNET_SWITCH_ID_1;\n        consensus.nSpendV2ID_10 = ZC_V2_TESTNET_SWITCH_ID_10;\n        consensus.nSpendV2ID_25 = ZC_V2_TESTNET_SWITCH_ID_25;\n        consensus.nSpendV2ID_50 = ZC_V2_TESTNET_SWITCH_ID_50;\n        consensus.nSpendV2ID_100 = ZC_V2_TESTNET_SWITCH_ID_100;\n        consensus.nModulusV2StartBlock = ZC_MODULUS_V2_TESTNET_START_BLOCK;\n        consensus.nModulusV1MempoolStopBlock = ZC_MODULUS_V1_TESTNET_MEMPOOL_STOP_BLOCK;\n        consensus.nModulusV1StopBlock = ZC_MODULUS_V1_TESTNET_STOP_BLOCK;\n        // Sigma related values.\n        consensus.nSigmaStartBlock = ZC_SIGMA_TESTNET_STARTING_BLOCK;\n        consensus.nSigmaPaddingBlock = ZC_SIGMA_TESTNET_PADDING_BLOCK;\n        consensus.nDisableUnpaddedSigmaBlock = ZC_SIGMA_TESTNET_DISABLE_UNPADDED_BLOCK;\n        consensus.nOldSigmaBanBlock = 70416;\n        consensus.nZerocoinV2MintMempoolGracefulPeriod = ZC_V2_MINT_TESTNET_GRACEFUL_MEMPOOL_PERIOD;\n        consensus.nZerocoinV2MintGracefulPeriod = ZC_V2_MINT_TESTNET_GRACEFUL_PERIOD;\n        consensus.nZerocoinV2SpendMempoolGracefulPeriod = ZC_V2_SPEND_TESTNET_GRACEFUL_MEMPOOL_PERIOD;\n        consensus.nZerocoinV2SpendGracefulPeriod = ZC_V2_SPEND_TESTNET_GRACEFUL_PERIOD;\n            consensus.nMaxSigmaInputPerBlock = ZC_SIGMA_INPUT_LIMIT_PER_BLOCK;\n            consensus.nMaxValueSigmaSpendPerBlock = ZC_SIGMA_VALUE_SPEND_LIMIT_PER_BLOCK;\n            consensus.nMaxSigmaInputPerTransaction = ZC_SIGMA_INPUT_LIMIT_PER_TRANSACTION;\n            consensus.nMaxValueSigmaSpendPerTransaction = ZC_SIGMA_VALUE_SPEND_LIMIT_PER_TRANSACTION;\n            consensus.nZerocoinToSigmaRemintWindowSize = 50000;\n\n            // Dandelion related values.\n            consensus.nDandelionEmbargoMinimum = DANDELION_TESTNET_EMBARGO_MINIMUM;\n            consensus.nDandelionEmbargoAvgAdd = DANDELION_TESTNET_EMBARGO_AVG_ADD;\n            consensus.nDandelionMaxDestinations = DANDELION_MAX_DESTINATIONS;\n            consensus.nDandelionShuffleInterval = DANDELION_SHUFFLE_INTERVAL;\n            consensus.nDandelionFluff = DANDELION_FLUFF;\n    }\n};\n\nstatic CTestNetParams testNetParams;\n\n/**\n * Regression test\n */\nclass CRegTestParams : public CChainParams {\npublic:\n    CRegTestParams() {\n        strNetworkID = \"regtest\";\n\n        consensus.chainType = Consensus::chainRegtest;\n\n        consensus.nSubsidyHalvingFirst = 302438;\n        consensus.nSubsidyHalvingInterval = 420000;\n        consensus.nSubsidyHalvingStopBlock = 3646849;\n\n        consensus.nMajorityEnforceBlockUpgrade = 750;\n        consensus.nMajorityRejectBlockOutdated = 950;\n        consensus.nMajorityWindow = 1000;\n        consensus.powLimit = uint256S(\"7fffff0000000000000000000000000000000000000000000000000000000000\");\n        consensus.nPowTargetTimespan = 60 * 60 * 1000; // 60 minutes between retargets\n        consensus.nPowTargetSpacing = 1; // 10 minute blocks\n        consensus.fPowAllowMinDifficultyBlocks = true;\n        consensus.fPowNoRetargeting = true;\n        consensus.nXFSnodePaymentsStartBlock = 120;\n        consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains\n        consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;\n        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;\n        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 0;\n        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 999999999999ULL;\n\n        // The best chain should have at least this much work.\n        consensus.nMinimumChainWork = uint256S(\"0x0\");\n        // XFSnode code\n        nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes\n        nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin\n\n        consensus.nCheckBugFixedAtBlock = 120;\n        consensus.nXFSnodePaymentsBugFixedAtBlock = 1;\n        consensus.nSpendV15StartBlock = 1;\n        consensus.nSpendV2ID_1 = 2;\n        consensus.nSpendV2ID_10 = 3;\n        consensus.nSpendV2ID_25 = 3;\n        consensus.nSpendV2ID_50 = 3;\n        consensus.nSpendV2ID_100 = 3;\n        consensus.nModulusV2StartBlock = 130;\n        consensus.nModulusV1MempoolStopBlock = 135;\n        consensus.nModulusV1StopBlock = 140;\n        consensus.nMultipleSpendInputsInOneTxStartBlock = 1;\n        consensus.nDontAllowDupTxsStartBlock = 1;\n\n        consensus.nDisableZerocoinStartBlock = INT_MAX;\n\n        pchMessageStart[0] = 0xc1;\n        pchMessageStart[1] = 0x1a;\n        pchMessageStart[2] = 0xf1;\n        pchMessageStart[3] = 0xff;\n        nDefaultPort = 18444;\n        nPruneAfterHeight = 1000;\n\n        std::vector<unsigned char> extraNonce(4);\n\t    extraNonce[0] = 0xaa;\n        extraNonce[1] = 0xc1;\n        extraNonce[2] = 0xf1;\n        extraNonce[3] = 0xcb;\n        genesis = CreateGenesisBlock(ZC_GENESIS_BLOCK_TIME, 7382559, 0x1e00ffff, 2, 0 * COIN, extraNonce);\n        consensus.hashGenesisBlock = genesis.GetHash();\n\n        assert(consensus.hashGenesisBlock ==\n              uint256S(\"0x0000002483dee2a97df95f61d810f2115bc83134d3c399168d682ea1da6d0fd8\"));\n        assert(genesis.hashMerkleRoot ==\n              uint256S(\"ed2efdba33e9bc206cba44a213440e29a0902740f4f4209bdea833c48673606f\"));\n        //Disable consecutive checks\n        nConsecutivePoWHeight = INT_MAX;\n        nMaxPoWBlocks = 101;\n        consensus.nFirstPOSBlock = nConsecutivePoWHeight;//TODO akshaynexus :This needs to be decided\n\n        vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds.\n        vSeeds.clear();      //!< Regtest mode doesn't have any DNS seeds.\n\n        fMiningRequiresPeers = false;\n        fDefaultConsistencyChecks = true;\n        fRequireStandard = false;\n        fMineBlocksOnDemand = true;\n        fTestnetToBeDeprecatedFieldRPC = false;\n\n        checkpointData = (CCheckpointData) {\n            boost::assign::map_list_of\n                (0, uint256S(\"0x0000002483dee2a97df95f61d810f2115bc83134d3c399168d682ea1da6d0fd8\")),\n                0,\n                0,\n                0\n        };\n        base58Prefixes[PUBKEY_ADDRESS] = std::vector < unsigned char > (1, 65);\n        base58Prefixes[SCRIPT_ADDRESS] = std::vector < unsigned char > (1, 178);\n        base58Prefixes[SECRET_KEY] = std::vector < unsigned char > (1, 239);\n        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container < std::vector < unsigned char > > ();\n        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container < std::vector < unsigned char > > ();\n\n        nSpendV15StartBlock = ZC_V1_5_TESTNET_STARTING_BLOCK;\n        nSpendV2ID_1 = ZC_V2_TESTNET_SWITCH_ID_1;\n        nSpendV2ID_10 = ZC_V2_TESTNET_SWITCH_ID_10;\n        nSpendV2ID_25 = ZC_V2_TESTNET_SWITCH_ID_25;\n        nSpendV2ID_50 = ZC_V2_TESTNET_SWITCH_ID_50;\n        nSpendV2ID_100 = ZC_V2_TESTNET_SWITCH_ID_100;\n        nModulusV2StartBlock = ZC_MODULUS_V2_TESTNET_START_BLOCK;\n        nModulusV1MempoolStopBlock = ZC_MODULUS_V1_TESTNET_MEMPOOL_STOP_BLOCK;\n        nModulusV1StopBlock = ZC_MODULUS_V1_TESTNET_STOP_BLOCK;\n\n        // Sigma related values.\n        consensus.nSigmaStartBlock = 400;\n        consensus.nSigmaPaddingBlock = 550;\n        consensus.nDisableUnpaddedSigmaBlock = 510;\n        consensus.nOldSigmaBanBlock = 450;\n        consensus.nZerocoinV2MintMempoolGracefulPeriod = 2;\n        consensus.nZerocoinV2MintGracefulPeriod = 5;\n        consensus.nZerocoinV2SpendMempoolGracefulPeriod = 10;\n        consensus.nZerocoinV2SpendGracefulPeriod = 20;\n            consensus.nMaxSigmaInputPerBlock = ZC_SIGMA_INPUT_LIMIT_PER_BLOCK;\n            consensus.nMaxValueSigmaSpendPerBlock = ZC_SIGMA_VALUE_SPEND_LIMIT_PER_BLOCK;\n            consensus.nMaxSigmaInputPerTransaction = ZC_SIGMA_INPUT_LIMIT_PER_TRANSACTION;\n            consensus.nMaxValueSigmaSpendPerTransaction = ZC_SIGMA_VALUE_SPEND_LIMIT_PER_TRANSACTION;\n            consensus.nZerocoinToSigmaRemintWindowSize = 1000;\n\n            // Dandelion related values.\n            consensus.nDandelionEmbargoMinimum = 0;\n            consensus.nDandelionEmbargoAvgAdd = 1;\n            consensus.nDandelionMaxDestinations = DANDELION_MAX_DESTINATIONS;\n            consensus.nDandelionShuffleInterval = DANDELION_SHUFFLE_INTERVAL;\n            consensus.nDandelionFluff = DANDELION_FLUFF;\n    }\n\n    void UpdateBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) {\n        consensus.vDeployments[d].nStartTime = nStartTime;\n        consensus.vDeployments[d].nTimeout = nTimeout;\n    }\n};\n\nstatic CRegTestParams regTestParams;\n\nstatic CChainParams *pCurrentParams = 0;\n\nconst CChainParams &Params() {\n    assert(pCurrentParams);\n    return *pCurrentParams;\n}\n\nCChainParams &Params(const std::string &chain) {\n    if (chain == CBaseChainParams::MAIN)\n        return mainParams;\n    else if (chain == CBaseChainParams::TESTNET)\n        return testNetParams;\n    else if (chain == CBaseChainParams::REGTEST)\n        return regTestParams;\n    else\n        throw std::runtime_error(strprintf(\"%s: Unknown chain %s.\", __func__, chain));\n}\n\nvoid SelectParams(const std::string &network) {\n    SelectBaseParams(network);\n    pCurrentParams = &Params(network);\n}\n\nvoid UpdateRegtestBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) {\n    regTestParams.UpdateBIP9Parameters(d, nStartTime, nTimeout);\n}\n", "meta": {"hexsha": "a3ba2ed46e889eee942d03bc68e462703d5bd40f", "size": 28011, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/chainparams.cpp", "max_stars_repo_name": "Black-NET/xfscore", "max_stars_repo_head_hexsha": "a4191203db2fff88c4f64cd5417a0edc47f3a607", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T19:44:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T19:44:43.000Z", "max_issues_repo_path": "src/chainparams.cpp", "max_issues_repo_name": "Black-NET/xfscore", "max_issues_repo_head_hexsha": "a4191203db2fff88c4f64cd5417a0edc47f3a607", "max_issues_repo_licenses": ["MIT"], "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/chainparams.cpp", "max_forks_repo_name": "Black-NET/xfscore", "max_forks_repo_head_hexsha": "a4191203db2fff88c4f64cd5417a0edc47f3a607", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.9290909091, "max_line_length": 168, "alphanum_fraction": 0.7205740602, "num_tokens": 8180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19582702163591223}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2014-2021 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, 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_ALGORITHMS_DETAIL_DISTANCE_SEGMENT_TO_BOX_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_SEGMENT_TO_BOX_HPP\n\n#include <cstddef>\n#include <functional>\n#include <type_traits>\n#include <vector>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/algorithms/detail/assign_box_corners.hpp>\n#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>\n#include <boost/geometry/algorithms/detail/closest_feature/point_to_range.hpp>\n#include <boost/geometry/algorithms/detail/disjoint/segment_box.hpp>\n#include <boost/geometry/algorithms/detail/distance/default_strategies.hpp>\n#include <boost/geometry/algorithms/detail/distance/is_comparable.hpp>\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\n#include <boost/geometry/algorithms/dispatch/distance.hpp>\n#include <boost/geometry/algorithms/not_implemented.hpp>\n\n#include <boost/geometry/policies/compare.hpp>\n\n#include <boost/geometry/util/calculation_type.hpp>\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/has_nan_coordinate.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/strategies/disjoint.hpp>\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/tags.hpp>\n\n// TEMP - remove when distance umbrella strategies are implemented\n#include <boost/geometry/strategies/relate/services.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace distance\n{\n\n\ntemplate <typename Segment, typename Box, typename Strategy>\ninline bool intersects_segment_box(Segment const& segment, Box const& box,\n                                   Strategy const& strategy)\n{\n    // TODO: pass strategy\n    auto const s = strategies::relate::services::strategy_converter\n        <\n            // This is the only strategy defined in distance segment/box\n            // strategies that carries the information about the spheroid\n            // so use it for now.\n            decltype(strategy.get_side_strategy())\n        >::get(strategy.get_side_strategy());\n\n    return ! detail::disjoint::disjoint_segment_box::apply(segment, box, s);\n}\n\n\ntemplate\n<\n    typename Segment,\n    typename Box,\n    typename Strategy,\n    bool UsePointBoxStrategy = false\n>\nclass segment_to_box_2D_generic\n{\nprivate:\n    typedef typename point_type<Segment>::type segment_point;\n    typedef typename point_type<Box>::type box_point;\n\n    typedef typename strategy::distance::services::comparable_type\n        <\n            typename Strategy::distance_ps_strategy::type\n        >::type comparable_strategy;\n\n    typedef detail::closest_feature::point_to_point_range\n        <\n            segment_point,\n            std::vector<box_point>,\n            open,\n            comparable_strategy\n        > point_to_point_range;\n\n    typedef typename strategy::distance::services::return_type\n        <\n            comparable_strategy, segment_point, box_point\n        >::type comparable_return_type;\n    \npublic:\n    typedef typename strategy::distance::services::return_type\n        <\n            Strategy, segment_point, box_point\n        >::type return_type;\n\n    static inline return_type apply(Segment const& segment,\n                                    Box const& box,\n                                    Strategy const& strategy,\n                                    bool check_intersection = true)\n    {\n        if (check_intersection && intersects_segment_box(segment, box, strategy))\n        {\n            return 0;\n        }\n\n        comparable_strategy cstrategy =\n            strategy::distance::services::get_comparable\n                <\n                    typename Strategy::distance_ps_strategy::type\n                >::apply(strategy.get_distance_ps_strategy());\n\n        // get segment points\n        segment_point p[2];\n        detail::assign_point_from_index<0>(segment, p[0]);\n        detail::assign_point_from_index<1>(segment, p[1]);\n\n        // get box points\n        std::vector<box_point> box_points(4);\n        detail::assign_box_corners_oriented<true>(box, box_points);\n \n        comparable_return_type cd[6];\n        for (unsigned int i = 0; i < 4; ++i)\n        {\n            cd[i] = cstrategy.apply(box_points[i], p[0], p[1]);\n        }\n\n        std::pair\n            <\n                typename std::vector<box_point>::const_iterator,\n                typename std::vector<box_point>::const_iterator\n            > bit_min[2];\n\n        bit_min[0] = point_to_point_range::apply(p[0],\n                                                 box_points.begin(),\n                                                 box_points.end(),\n                                                 cstrategy,\n                                                 cd[4]);\n        bit_min[1] = point_to_point_range::apply(p[1],\n                                                 box_points.begin(),\n                                                 box_points.end(),\n                                                 cstrategy,\n                                                 cd[5]);\n\n        unsigned int imin = 0;\n        for (unsigned int i = 1; i < 6; ++i)\n        {\n            if (cd[i] < cd[imin])\n            {\n                imin = i;\n            }\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(is_comparable<Strategy>::value))\n        {\n            return cd[imin];\n        }\n\n        if (imin < 4)\n        {\n            return strategy.get_distance_ps_strategy().apply(box_points[imin], p[0], p[1]);\n        }\n        else\n        {\n            unsigned int bimin = imin - 4;\n            return strategy.get_distance_ps_strategy().apply(p[bimin],\n                                  *bit_min[bimin].first,\n                                  *bit_min[bimin].second);\n        }\n    }\n};\n\n\ntemplate\n<\n    typename Segment,\n    typename Box,\n    typename Strategy\n>\nclass segment_to_box_2D_generic<Segment, Box, Strategy, true>\n{\nprivate:\n    typedef typename point_type<Segment>::type segment_point;\n    typedef typename point_type<Box>::type box_point;\n\n    typedef typename strategy::distance::services::comparable_type\n        <\n            Strategy\n        >::type comparable_strategy;\n\n    typedef typename strategy::distance::services::return_type\n        <\n            comparable_strategy, segment_point, box_point\n        >::type comparable_return_type;\n\n    typedef typename detail::distance::default_strategy\n        <\n            segment_point, Box\n        >::type point_box_strategy;\n\n    typedef typename strategy::distance::services::comparable_type\n        <\n            point_box_strategy\n        >::type point_box_comparable_strategy;\n\npublic:\n    typedef typename strategy::distance::services::return_type\n        <\n            Strategy, segment_point, box_point\n        >::type return_type;\n\n    static inline return_type apply(Segment const& segment,\n                                    Box const& box,\n                                    Strategy const& strategy,\n                                    bool check_intersection = true)\n    {\n        if (check_intersection && intersects_segment_box(segment, box, strategy))\n        {\n            return 0;\n        }\n\n        comparable_strategy cstrategy =\n            strategy::distance::services::get_comparable\n                <\n                    Strategy\n                >::apply(strategy);\n        boost::ignore_unused(cstrategy);\n\n        // get segment points\n        segment_point p[2];\n        detail::assign_point_from_index<0>(segment, p[0]);\n        detail::assign_point_from_index<1>(segment, p[1]);\n\n        // get box points\n        std::vector<box_point> box_points(4);\n        detail::assign_box_corners_oriented<true>(box, box_points);\n \n        comparable_return_type cd[6];\n        for (unsigned int i = 0; i < 4; ++i)\n        {\n            cd[i] = cstrategy.apply(box_points[i], p[0], p[1]);\n        }\n\n        point_box_comparable_strategy pb_cstrategy;\n        boost::ignore_unused(pb_cstrategy);\n        cd[4] = pb_cstrategy.apply(p[0], box);\n        cd[5] = pb_cstrategy.apply(p[1], box);\n\n        unsigned int imin = 0;\n        for (unsigned int i = 1; i < 6; ++i)\n        {\n            if (cd[i] < cd[imin])\n            {\n                imin = i;\n            }\n        }\n\n        if (is_comparable<Strategy>::value)\n        {\n            return cd[imin];\n        }\n\n        if (imin < 4)\n        {\n            strategy.apply(box_points[imin], p[0], p[1]);\n        }\n        else\n        {\n            return point_box_strategy().apply(p[imin - 4], box);\n        }\n    }\n};\n\n\n\n\ntemplate\n<\n    typename ReturnType,\n    typename SegmentPoint,\n    typename BoxPoint,\n    typename SBStrategy\n>\nclass segment_to_box_2D\n{\nprivate:\n    template <typename Result>\n    struct cast_to_result\n    {\n        template <typename T>\n        static inline Result apply(T const& t)\n        {\n            return boost::numeric_cast<Result>(t);\n        }\n    };\n\n\n    template <typename T, bool IsLess /* true */>\n    struct compare_less_equal\n    {\n        typedef compare_less_equal<T, !IsLess> other;\n\n        template <typename T1, typename T2>\n        inline bool operator()(T1 const& t1, T2 const& t2) const\n        {\n            return std::less_equal<T>()(cast_to_result<T>::apply(t1),\n                                        cast_to_result<T>::apply(t2));\n        }\n    };\n\n    template <typename T>\n    struct compare_less_equal<T, false>\n    {\n        typedef compare_less_equal<T, true> other;\n\n        template <typename T1, typename T2>\n        inline bool operator()(T1 const& t1, T2 const& t2) const\n        {\n            return std::greater_equal<T>()(cast_to_result<T>::apply(t1),\n                                           cast_to_result<T>::apply(t2));\n        }\n    };\n\n\n    template <typename LessEqual>\n    struct other_compare\n    {\n        typedef typename LessEqual::other type;\n    };\n\n\n    // it is assumed here that p0 lies to the right of the box (so the\n    // entire segment lies to the right of the box)\n    template <typename LessEqual>\n    struct right_of_box\n    {\n        static inline ReturnType apply(SegmentPoint const& p0,\n                                       SegmentPoint const& p1,\n                                       BoxPoint const& bottom_right,\n                                       BoxPoint const& top_right,\n                                       SBStrategy const& sb_strategy)\n        {\n            boost::ignore_unused(sb_strategy);\n\n            // the implementation below is written for non-negative slope\n            // segments\n            //\n            // for negative slope segments swap the roles of bottom_right\n            // and top_right and use greater_equal instead of less_equal.\n\n            typedef cast_to_result<ReturnType> cast;\n\n            LessEqual less_equal;\n\n            typename SBStrategy::distance_ps_strategy::type ps_strategy =\n                                sb_strategy.get_distance_ps_strategy();\n\n            if (less_equal(geometry::get<1>(bottom_right), geometry::get<1>(p0)))\n            {\n                //if p0 is in box's band\n                if (less_equal(geometry::get<1>(p0), geometry::get<1>(top_right)))\n                {\n                    // segment & crosses band (TODO:merge with box-box dist)\n                    if (math::equals(geometry::get<0>(p0), geometry::get<0>(p1)))\n                    {\n                        SegmentPoint high = geometry::get<1>(p1) > geometry::get<1>(p0) ? p1 : p0;\n                        if (less_equal(geometry::get<1>(high), geometry::get<1>(top_right)))\n                        {\n                            return cast::apply(ps_strategy.apply(high, bottom_right, top_right));\n                        }\n                        return cast::apply(ps_strategy.apply(top_right, p0, p1));\n                    }\n                    return cast::apply(ps_strategy.apply(p0, bottom_right, top_right));\n                }\n                // distance is realized between the top-right\n                // corner of the box and the segment\n                return cast::apply(ps_strategy.apply(top_right, p0, p1));\n            }\n            else\n            {\n                // distance is realized between the bottom-right\n                // corner of the box and the segment\n                return cast::apply(ps_strategy.apply(bottom_right, p0, p1));\n            }\n        }\n    };\n\n    // it is assumed here that p0 lies above the box (so the\n    // entire segment lies above the box)\n\n    template <typename LessEqual>\n    struct above_of_box\n    {\n\n        static inline ReturnType apply(SegmentPoint const& p0,\n                                       SegmentPoint const& p1,\n                                       BoxPoint const& top_left,\n                                       SBStrategy const& sb_strategy)\n        {\n            boost::ignore_unused(sb_strategy);\n            return apply(p0, p1, p0, top_left, sb_strategy);\n        }\n\n        static inline ReturnType apply(SegmentPoint const& p0,\n                                       SegmentPoint const& p1,\n                                       SegmentPoint const& p_max,\n                                       BoxPoint const& top_left,\n                                       SBStrategy const& sb_strategy)\n        {\n            boost::ignore_unused(sb_strategy);\n            typedef cast_to_result<ReturnType> cast;\n            LessEqual less_equal;\n\n            // p0 is above the upper segment of the box (and inside its band)\n            // then compute the vertical (i.e. meridian for spherical) distance\n            if (less_equal(geometry::get<0>(top_left), geometry::get<0>(p_max)))\n            {\n                ReturnType diff =\n                sb_strategy.get_distance_ps_strategy().vertical_or_meridian(\n                                    geometry::get_as_radian<1>(p_max),\n                                    geometry::get_as_radian<1>(top_left));\n\n                return strategy::distance::services::result_from_distance\n                    <\n                        SBStrategy, SegmentPoint, BoxPoint\n                    >::apply(sb_strategy, math::abs(diff));\n            }\n\n            // p0 is to the left of the box, but p1 is above the box\n            // in this case the distance is realized between the\n            // top-left corner of the box and the segment\n            return cast::apply(sb_strategy.get_distance_ps_strategy().\n                                                      apply(top_left, p0, p1));\n        }\n    };\n\n    template <typename LessEqual>\n    struct check_right_left_of_box\n    {\n        static inline bool apply(SegmentPoint const& p0,\n                                 SegmentPoint const& p1,\n                                 BoxPoint const& top_left,\n                                 BoxPoint const& top_right,\n                                 BoxPoint const& bottom_left,\n                                 BoxPoint const& bottom_right,\n                                 SBStrategy const& sb_strategy,\n                                 ReturnType& result)\n        {\n            // p0 lies to the right of the box\n            if (geometry::get<0>(p0) >= geometry::get<0>(top_right))\n            {\n                result = right_of_box\n                    <\n                        LessEqual\n                    >::apply(p0, p1, bottom_right, top_right,\n                             sb_strategy);\n                return true;\n            }\n\n            // p1 lies to the left of the box\n            if (geometry::get<0>(p1) <= geometry::get<0>(bottom_left))\n            {\n                result = right_of_box\n                    <\n                        typename other_compare<LessEqual>::type\n                    >::apply(p1, p0, top_left, bottom_left,\n                             sb_strategy);\n                return true;\n            }\n\n            return false;\n        }\n    };\n\n    template <typename LessEqual>\n    struct check_above_below_of_box\n    {\n        static inline bool apply(SegmentPoint const& p0,\n                                 SegmentPoint const& p1,\n                                 BoxPoint const& top_left,\n                                 BoxPoint const& top_right,\n                                 BoxPoint const& bottom_left,\n                                 BoxPoint const& bottom_right,\n                                 SBStrategy const& sb_strategy,\n                                 ReturnType& result)\n        {\n            typedef compare_less_equal<ReturnType, false> GreaterEqual;\n\n            // the segment lies below the box\n            if (geometry::get<1>(p1) < geometry::get<1>(bottom_left))\n            {\n                result = sb_strategy.template segment_below_of_box\n                        <\n                            LessEqual,\n                            ReturnType\n                        >(p0, p1,\n                          top_left, top_right,\n                          bottom_left, bottom_right);\n                return true;\n            }\n\n            // the segment lies above the box\n            if (geometry::get<1>(p0) > geometry::get<1>(top_right))\n            {\n                result = (std::min)(above_of_box\n                                    <\n                                        LessEqual\n                                    >::apply(p0, p1, top_left, sb_strategy),\n                                    above_of_box\n                                    <\n                                        GreaterEqual\n                                    >::apply(p1, p0, top_right, sb_strategy));\n                return true;\n            }\n            return false;\n        }\n    };\n\n    struct check_generic_position\n    {\n        static inline bool apply(SegmentPoint const& p0,\n                                 SegmentPoint const& p1,\n                                 BoxPoint const& corner1,\n                                 BoxPoint const& corner2,\n                                 SBStrategy const& sb_strategy,\n                                 ReturnType& result)\n        {\n            typename SBStrategy::side_strategy_type\n                side_strategy = sb_strategy.get_side_strategy();\n\n            typedef cast_to_result<ReturnType> cast;\n            ReturnType diff1 = cast::apply(geometry::get<1>(p1))\n                               - cast::apply(geometry::get<1>(p0));\n\n            typename SBStrategy::distance_ps_strategy::type ps_strategy =\n                                sb_strategy.get_distance_ps_strategy();\n\n            int sign = diff1 < 0 ? -1 : 1;\n            if (side_strategy.apply(p0, p1, corner1) * sign < 0)\n            {\n                result = cast::apply(ps_strategy.apply(corner1, p0, p1));\n                return true;\n            }\n            if (side_strategy.apply(p0, p1, corner2) * sign > 0)\n            {\n                result = cast::apply(ps_strategy.apply(corner2, p0, p1));\n                return true;\n            }\n            return false;\n        }\n    };\n\n    static inline ReturnType\n    non_negative_slope_segment(SegmentPoint const& p0,\n                               SegmentPoint const& p1,\n                               BoxPoint const& top_left,\n                               BoxPoint const& top_right,\n                               BoxPoint const& bottom_left,\n                               BoxPoint const& bottom_right,\n                               SBStrategy const& sb_strategy)\n    {\n        typedef compare_less_equal<ReturnType, true> less_equal;\n\n        // assert that the segment has non-negative slope\n        BOOST_GEOMETRY_ASSERT( ( math::equals(geometry::get<0>(p0), geometry::get<0>(p1))\n                              && geometry::get<1>(p0) < geometry::get<1>(p1))\n                            ||\n                               ( geometry::get<0>(p0) < geometry::get<0>(p1)\n                              && geometry::get<1>(p0) <= geometry::get<1>(p1) )\n                            || geometry::has_nan_coordinate(p0)\n                            || geometry::has_nan_coordinate(p1));\n\n        ReturnType result(0);\n\n        if (check_right_left_of_box\n                <\n                    less_equal\n                >::apply(p0, p1,\n                         top_left, top_right, bottom_left, bottom_right,\n                         sb_strategy, result))\n        {\n            return result;\n        }\n\n        if (check_above_below_of_box\n                <\n                    less_equal\n                >::apply(p0, p1,\n                         top_left, top_right, bottom_left, bottom_right,\n                         sb_strategy, result))\n        {\n            return result;\n        }\n\n        if (check_generic_position::apply(p0, p1,\n                                          top_left, bottom_right,\n                                          sb_strategy, result))\n        {\n            return result;\n        }\n\n        // in all other cases the box and segment intersect, so return 0\n        return result;\n    }\n\n\n    static inline ReturnType\n    negative_slope_segment(SegmentPoint const& p0,\n                           SegmentPoint const& p1,\n                           BoxPoint const& top_left,\n                           BoxPoint const& top_right,\n                           BoxPoint const& bottom_left,\n                           BoxPoint const& bottom_right,\n                           SBStrategy const& sb_strategy)\n    {\n        typedef compare_less_equal<ReturnType, false> greater_equal;\n\n        // assert that the segment has negative slope\n        BOOST_GEOMETRY_ASSERT( ( geometry::get<0>(p0) < geometry::get<0>(p1)\n                              && geometry::get<1>(p0) > geometry::get<1>(p1) )\n                            || geometry::has_nan_coordinate(p0)\n                            || geometry::has_nan_coordinate(p1) );\n\n        ReturnType result(0);\n\n        if (check_right_left_of_box\n                <\n                    greater_equal\n                >::apply(p0, p1,\n                         bottom_left, bottom_right, top_left, top_right,\n                         sb_strategy, result))\n        {\n            return result;\n        }\n\n        if (check_above_below_of_box\n                <\n                    greater_equal\n                >::apply(p1, p0,\n                         top_right, top_left, bottom_right, bottom_left,\n                         sb_strategy, result))\n        {\n            return result;\n        }\n\n        if (check_generic_position::apply(p0, p1,\n                                          bottom_left, top_right,\n                                          sb_strategy, result))\n        {\n            return result;\n        }\n\n        // in all other cases the box and segment intersect, so return 0\n        return result;\n    }\n\npublic:\n    static inline ReturnType apply(SegmentPoint const& p0,\n                                   SegmentPoint const& p1,\n                                   BoxPoint const& top_left,\n                                   BoxPoint const& top_right,\n                                   BoxPoint const& bottom_left,\n                                   BoxPoint const& bottom_right,\n                                   SBStrategy const& sb_strategy)\n    {\n        BOOST_GEOMETRY_ASSERT( (geometry::less<SegmentPoint, -1, typename SBStrategy::cs_tag>()(p0, p1))\n                            || geometry::has_nan_coordinate(p0)\n                            || geometry::has_nan_coordinate(p1) );\n\n        if (geometry::get<0>(p0) < geometry::get<0>(p1)\n            && geometry::get<1>(p0) > geometry::get<1>(p1))\n        {\n            return negative_slope_segment(p0, p1,\n                                          top_left, top_right,\n                                          bottom_left, bottom_right,\n                                          sb_strategy);\n        }\n\n        return non_negative_slope_segment(p0, p1,\n                                          top_left, top_right,\n                                          bottom_left, bottom_right,\n                                          sb_strategy);\n    }\n\n    template <typename LessEqual>\n    static inline ReturnType call_above_of_box(SegmentPoint const& p0,\n                                               SegmentPoint const& p1,\n                                               SegmentPoint const& p_max,\n                                               BoxPoint const& top_left,\n                                               SBStrategy const& sb_strategy)\n    {\n        return above_of_box<LessEqual>::apply(p0, p1, p_max, top_left, sb_strategy);\n    }\n\n    template <typename LessEqual>\n    static inline ReturnType call_above_of_box(SegmentPoint const& p0,\n                                               SegmentPoint const& p1,\n                                               BoxPoint const& top_left,\n                                               SBStrategy const& sb_strategy)\n    {\n        return above_of_box<LessEqual>::apply(p0, p1, top_left, sb_strategy);\n    }\n};\n\n//=========================================================================\n\ntemplate\n<\n    typename Segment,\n    typename Box,\n    typename std::size_t Dimension,\n    typename SBStrategy\n>\nclass segment_to_box\n    : not_implemented<Segment, Box>\n{};\n\n\ntemplate\n<\n    typename Segment,\n    typename Box,\n    typename SBStrategy\n>\nclass segment_to_box<Segment, Box, 2, SBStrategy>\n{\nprivate:\n    typedef typename point_type<Segment>::type segment_point;\n    typedef typename point_type<Box>::type box_point;\n\n    typedef typename strategy::distance::services::comparable_type\n        <\n            SBStrategy\n        >::type ps_comparable_strategy;\n\n    typedef typename strategy::distance::services::return_type\n        <\n            ps_comparable_strategy, segment_point, box_point\n        >::type comparable_return_type;\npublic:\n    typedef typename strategy::distance::services::return_type\n        <\n            SBStrategy, segment_point, box_point\n        >::type return_type;\n\n    static inline return_type apply(Segment const& segment,\n                                    Box const& box,\n                                    SBStrategy const& sb_strategy)\n    {\n        segment_point p[2];\n        detail::assign_point_from_index<0>(segment, p[0]);\n        detail::assign_point_from_index<1>(segment, p[1]);\n\n        if (detail::equals::equals_point_point(p[0], p[1],\n                sb_strategy.get_equals_point_point_strategy()))\n        {\n            typedef std::conditional_t\n                <\n                    std::is_same\n                        <\n                            ps_comparable_strategy,\n                            SBStrategy\n                        >::value,\n                    typename strategy::distance::services::comparable_type\n                        <\n                            typename SBStrategy::distance_pb_strategy::type\n                        >::type,\n                    typename SBStrategy::distance_pb_strategy::type\n                > point_box_strategy_type;\n\n            return dispatch::distance\n                <\n                    segment_point,\n                    Box,\n                    point_box_strategy_type\n                >::apply(p[0], box, point_box_strategy_type());\n        }\n\n        box_point top_left, top_right, bottom_left, bottom_right;\n        detail::assign_box_corners(box, bottom_left, bottom_right,\n                                   top_left, top_right);\n\n        SBStrategy::mirror(p[0], p[1],\n                           bottom_left, bottom_right,\n                           top_left, top_right);\n\n        typedef geometry::less<segment_point, -1, typename SBStrategy::cs_tag> less_type;\n        if (less_type()(p[0], p[1]))\n        {\n            return segment_to_box_2D\n                <\n                    return_type,\n                    segment_point,\n                    box_point,\n                    SBStrategy\n                >::apply(p[0], p[1],\n                         top_left, top_right, bottom_left, bottom_right,\n                         sb_strategy);\n        }\n        else\n        {\n            return segment_to_box_2D\n                <\n                    return_type,\n                    segment_point,\n                    box_point,\n                    SBStrategy\n                >::apply(p[1], p[0],\n                         top_left, top_right, bottom_left, bottom_right,\n                         sb_strategy);\n        }\n    }\n};\n\n\n}} // namespace detail::distance\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\ntemplate <typename Segment, typename Box, typename Strategy>\nstruct distance\n    <\n        Segment, Box, Strategy, segment_tag, box_tag,\n        strategy_tag_distance_segment_box, false\n    >\n{\n    typedef typename strategy::distance::services::return_type\n        <\n            Strategy,\n            typename point_type<Segment>::type,\n            typename point_type<Box>::type\n        >::type return_type;\n\n\n    static inline return_type apply(Segment const& segment,\n                                    Box const& box,\n                                    Strategy const& strategy)\n    {\n        assert_dimension_equal<Segment, Box>();\n\n        return detail::distance::segment_to_box\n            <\n                Segment,\n                Box,\n                dimension<Segment>::value,\n                Strategy\n            >::apply(segment, box, strategy);\n    }\n};\n\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_SEGMENT_TO_BOX_HPP\n", "meta": {"hexsha": "296df7ef624a78050147aed184e1e458d09b16db", "size": 30317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/distance/segment_to_box.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/geometry/algorithms/detail/distance/segment_to_box.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/geometry/algorithms/detail/distance/segment_to_box.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": 34.1792559188, "max_line_length": 104, "alphanum_fraction": 0.5153214368, "num_tokens": 5818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.19581608368816286}}
{"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 <iostream>\n#include <iomanip>\n#include <string>\n#include <cstdio>\n#include <boost/spirit/include/karma.hpp>\n#include <Eigen/Core>\n#include \"genfile/snp_data_utils.hpp\"\n#include \"genfile/gen.hpp\"\n#include \"genfile/GenLikeSNPDataSink.hpp\"\n#include \"genfile/ImputeHapProbsSNPDataSink.hpp\"\n//#include \"genfile/vcf/get_set.hpp\"\n//#include \"genfile/vcf/get_set_eigen.hpp\"\n#include \"genfile/ToGP.hpp\"\n#include \"genfile/format_float.hpp\"\n\nnamespace genfile {\n\t\n\tImputeHapProbsSNPDataSink::ImputeHapProbsSNPDataSink( std::string const& filename ):\n\t\tGenLikeSNPDataSink( filename, get_compression_type_indicated_by_filename( filename ) ),\n\t\tm_precision( 5 )\n\t{}\n\n\tImputeHapProbsSNPDataSink::ImputeHapProbsSNPDataSink( std::string const& filename, CompressionType compression_type ):\n\t\tGenLikeSNPDataSink( filename, compression_type ),\n\t\tm_precision( 5 )\n\t{}\n\n\tvoid ImputeHapProbsSNPDataSink::set_sample_names_impl( std::size_t number_of_samples, SampleNameGetter ) {\n\t\tm_data.resize( number_of_samples * 4 ) ;\n\t\tm_data.setConstant( -1 ) ;\n\t}\n\n\tvoid ImputeHapProbsSNPDataSink::set_precision( std::size_t precision ) {\n        m_precision = precision ;\n\t}\n\n\tnamespace {\n\t\tstruct HapProbWriter: public VariantDataReader::PerSampleSetter {\n\t\t\tHapProbWriter( Eigen::VectorXd& data, std::size_t const precision = 5 ):\n\t\t\t\tm_data( data ),\n\t\t\t\tm_precision( precision ),\n\t\t\t\tm_number_of_samples( m_data.size() / 4 ),\n\t\t\t\tm_sample_i(0),\n\t\t\t\tm_entry_i(0)\n\t\t\t{\n\t\t\t\tm_data.setConstant( -1 ) ;\n\t\t\t}\n\n\t\t\t~HapProbWriter() throw() {}\n\t\t\t\n\t\t\tvoid initialise( std::size_t nSamples, std::size_t nAlleles ) {\n\t\t\t\tif( nSamples != m_number_of_samples ) {\n\t\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\t\"genfile::HapProbWriter::initialise()\",\n\t\t\t\t\t\t\"n=\" + string_utils::to_string( nSamples ),\n\t\t\t\t\t\t\"Number of samples does not match expected number (\" + string_utils::to_string( m_number_of_samples ) + \")\"\n\t\t\t\t\t) ;\n\t\t\t\t}\n\t\t\t\tif( nAlleles != 2 ) {\n\t\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\t\"genfile::HapProbWriter::initialise()\",\n\t\t\t\t\t\t( boost::format( \"n=%d\" ) % nAlleles ).str(),\n\t\t\t\t\t\t\"Expected two alleles.\"\n\t\t\t\t\t) ;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool set_sample( std::size_t i ) {\n\t\t\t\tassert( i < m_number_of_samples ) ;\n\t\t\t\tm_sample_i = i ;\n\t\t\t\treturn true ;\n\t\t\t}\n\n\t\t\tvoid set_number_of_entries( uint32_t, std::size_t n, OrderType const order_type, ValueType const value_type ) {\n\t\t\t\tif( n != 4 || order_type != ePerPhasedHaplotypePerAllele || value_type != eProbability ) {\n\t\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\t\"genfile::IntensityWriter::set_number_of_entries()\",\n\t\t\t\t\t\t\"n=\" + string_utils::to_string(n),\n\t\t\t\t\t\t\"Expected 4 genotype probabilities per sample.\"\n\t\t\t\t\t) ;\n\t\t\t\t}\n\t\t\t\tm_entry_i = 0 ;\n\t\t\t}\n\t\t\tvoid set_value( std::size_t j, MissingValue const value ) {\n\t\t\t\t// Value of -1 means missing data for this sample\n\t\t\t\tm_data[ 4 * m_sample_i + 0 ] = -1 ;\n\t\t\t}\n\t\t\tvoid set_value( std::size_t, std::string& value ) {\n\t\t\t\tassert(0) ;\n\t\t\t}\n\t\t\tvoid set_value( std::size_t, Integer const value ) {\n\t\t\t\tm_data( m_sample_i * 4 + m_entry_i++ ) = value ;\n\t\t\t}\n\t\t\tvoid set_value( std::size_t, double const value ) {\n\t\t\t\tm_data( m_sample_i * 4 + m_entry_i++ ) = value ;\n\t\t\t}\n\t\t\tvoid finalise() {} ;\n\n\t\t\tvoid write_to_stream( std::ostream& stream ) {\n\t\t\t\tfor( std::size_t i = 0; i < m_number_of_samples; ++i ) {\n\t\t\t\t\tif( m_data[2*i+0] < 0 ) {\n\t\t\t\t\t\tstream << \" 0 0\" ;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif( m_precision == 5 ) {\n\t\t\t\t\t\t\t// Fast formatting at 5dps.\n\t\t\t\t\t\t\timpl::FormatFloat5dp formatter ;\n\t\t\t\t\t\t\tboost::spirit::karma::generate(\n\t\t\t\t\t\t\t\t&m_buffer[0],\n\t\t\t\t\t\t\t\t( \" \" << formatter << \" \" << formatter << \"\\0\" ),\n\t\t\t\t\t\t\t\tm_data[4*i+1],\n\t\t\t\t\t\t\t\tm_data[4*i+3]\n\t\t\t\t\t\t\t) ;\n\t\t\t\t\t\t\tstream << m_buffer ;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Slow but flexible formatting at any precision.\n\t\t\t\t\t\t\tstream \n\t\t\t\t\t\t\t\t<< std::setprecision( m_precision )\n\t\t\t\t\t\t\t\t<< \" \" << m_data[4*i+1] \n\t\t\t\t\t\t\t\t<< \" \" << m_data[4*i+3] \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\n\t\tprivate:\n\t\t\tEigen::VectorXd& m_data ;\n\t\t\tstd::size_t const m_precision ;\n\t\t\tstd::size_t m_number_of_samples ;\n\t\t\tstd::size_t m_sample_i ;\n\t\t\tstd::size_t m_entry_i ;\n\t\t\tchar m_buffer[100];\n\t\t} ;\n\t}\n\n\tvoid ImputeHapProbsSNPDataSink::write_variant_data_impl(\n\t\tVariantIdentifyingData const& id_data,\n\t\tVariantDataReader& data_reader,\n\t\tInfo const& info\n\t) {\n\t\twrite_variant( stream(), id_data ) ;\n\t\tHapProbWriter writer( m_data, m_precision ) ;\n\t\tif( data_reader.supports( \":genotypes:\" )) {\n\t\t\tdata_reader.get( \":genotypes:\", to_GP_phased( writer ) ) ;\n\t\t} else {\n\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\"genfile::ImputeHapProbsSNPDataSink::write_variant_data_impl()\",\n\t\t\t\t\"data_reader\",\n\t\t\t\t\"Data source must support :genotypes: field.\"\n\t\t\t) ;\n\t\t}\n\t\twriter.write_to_stream( stream() ) ;\n\t\tstream() << \"\\n\" ;\n\t}\n}\n\n", "meta": {"hexsha": "d8e815e93c28b1644e7f18db364e282370802627", "size": 4916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "genfile/src/ImputeHapProbsSNPDataSink.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": "genfile/src/ImputeHapProbsSNPDataSink.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": "genfile/src/ImputeHapProbsSNPDataSink.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": 30.1595092025, "max_line_length": 119, "alphanum_fraction": 0.6482912937, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.37387583672470853, "lm_q1q2_score": 0.1956942264762677}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2014, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, 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_ALGORITHMS_DETAIL_CLOSEST_FEATURE_GEOMETRY_TO_RANGE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_CLOSEST_FEATURE_GEOMETRY_TO_RANGE_HPP\n\n#include <iterator>\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/algorithms/dispatch/distance.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace closest_feature\n{\n\n\n\n// returns the range iterator the realizes the closest\n// distance between the geometry and the element of the range\nclass geometry_to_range\n{\nprivate:\n    template\n    <\n        typename Geometry,\n        typename RangeIterator,\n        typename Strategy,\n        typename Distance\n    >\n    static inline void apply(Geometry const& geometry,\n                             RangeIterator first,\n                             RangeIterator last,\n                             Strategy const& strategy,\n                             RangeIterator& it_min,\n                             Distance& dist_min)\n    {\n        BOOST_GEOMETRY_ASSERT( first != last );\n\n        Distance const zero = Distance(0);\n\n        // start with first distance\n        it_min = first;\n        dist_min = dispatch::distance\n            <\n                Geometry,\n                typename std::iterator_traits<RangeIterator>::value_type,\n                Strategy\n            >::apply(geometry, *it_min, strategy);\n\n        // check if other elements in the range are closer\n        for (RangeIterator it = ++first; it != last; ++it)\n        {\n            Distance dist = dispatch::distance\n                <\n                    Geometry,\n                    typename std::iterator_traits<RangeIterator>::value_type,\n                    Strategy\n                >::apply(geometry, *it, strategy);\n\n            if (geometry::math::equals(dist, zero))\n            {\n                dist_min = dist;\n                it_min = it;\n                return;\n            }\n            else if (dist < dist_min)\n            {\n                dist_min = dist;\n                it_min = it;\n            }\n        }\n    }\n\npublic:\n    template\n    <\n        typename Geometry,\n        typename RangeIterator,\n        typename Strategy,\n        typename Distance\n    >    \n    static inline RangeIterator apply(Geometry const& geometry,\n                                      RangeIterator first,\n                                      RangeIterator last,\n                                      Strategy const& strategy,\n                                      Distance& dist_min)\n    {\n        RangeIterator it_min;\n        apply(geometry, first, last, strategy, it_min, dist_min);\n\n        return it_min;\n    }\n\n\n    template\n    <\n        typename Geometry,\n        typename RangeIterator,\n        typename Strategy\n    >    \n    static inline RangeIterator apply(Geometry const& geometry,\n                                      RangeIterator first,\n                                      RangeIterator last,\n                                      Strategy const& strategy)\n    {\n        typename strategy::distance::services::return_type\n            <\n                Strategy,\n                typename point_type<Geometry>::type,\n                typename point_type\n                    <\n                        typename std::iterator_traits\n                            <\n                                RangeIterator\n                            >::value_type\n                    >::type\n            >::type dist_min;\n\n        return apply(geometry, first, last, strategy, dist_min);\n    }\n};\n\n\n\n}} // namespace detail::closest_feature\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace geofeatures_boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_CLOSEST_FEATURE_GEOMETRY_TO_RANGE_HPP\n", "meta": {"hexsha": "edd73af69c75caa165c2ae1fa2dc7d4e23572c9a", "size": 4248, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/closest_feature/geometry_to_range.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/closest_feature/geometry_to_range.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/closest_feature/geometry_to_range.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 29.095890411, "max_line_length": 116, "alphanum_fraction": 0.5572033898, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1956942136140167}}
{"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_SIMD_COMMON_ELLIPKE_HPP_INCLUDED\n#define NT2_TOOLBOX_ELLIPTIC_FUNCTION_SIMD_COMMON_ELLIPKE_HPP_INCLUDED\n#include <nt2/sdk/meta/as_real.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/ldexp.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/average.hpp>\n#include <nt2/include/functions/oneminus.hpp>\n#include <nt2/include/functions/any.hpp>\n#include <nt2/include/functions/maximum.hpp>\n#include <nt2/sdk/constant/real.hpp>\n#include <nt2/sdk/constant/infinites.hpp>\n#include <nt2/sdk/constant/eps_related.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ellipke_, tag::cpu_,\n                       (A0)(X),\n                       ((simd_<arithmetic_<A0>,X>))\n                      );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::ellipke_(tag::simd_<tag::arithmetic_, X >),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0)>\n      {\n\ttypedef typename meta::as_real<A0>::type      etype;\n\ttypedef boost::fusion::tuple<etype, etype>     type;\n      };\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::as_real<A0>::type       etype;\n      typedef typename meta::scalar_of<etype>::type setype; \n      return ellipke(tofloat(a0), Eps<setype>()); \n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n//Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ellipke_, tag::cpu_,\n\t\t      (A0)(A1)(X),\n                       ((simd_<arithmetic_<A0>,X>))\n                       ((real_<A1>))\n                      );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::ellipke_(tag::simd_ < tag::arithmetic_, X >,\n\t\t\t    tag::real_),\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      {\n\ttypedef typename meta::as_real<A0>::type      etype;\n\ttypedef boost::fusion::tuple<etype, etype>     type;\n      };\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return ellipke(tofloat(a0), a1); \n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ellipke_, tag::cpu_,\n\t\t      (A0)(A1)(X),\n                       ((simd_<real_<A0>,X>))\n                       ((real_<A1>))\n                      );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::ellipke_(tag::simd_<tag::real_, X>,\n\t\t\t    tag::real_),\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      {\n\ttypedef typename meta::strip<A0>::type       etype;\n\ttypedef boost::fusion::tuple<etype, etype>    type;\n      };\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename NT2_RETURN_TYPE(2)::type type; \n      typedef typename meta::as_integer<A0>::type iA0;\n      typedef typename meta::scalar_of<A0>::type sA0;\n      A0 nan =  b_or(is_ltz(a0), gt(a0, One<A0>()));\n      A0 m = b_andnot(a0, nan); \n      A0 aa0 = One<A0>();\n      A0 bb0 = sqrt(oneminus(m));\n      A0 s0 = m;\n      int32_t i1 = 0;\n      sA0 mm = One<sA0>();\n      A0 aa1; \n      while (gt(mm, a1))\n\t{\n\t  aa1 = average(aa0, bb0);\n\t  A0 bb1 = sqrt(aa0*bb0);\n\t  A0 cc1 = average(aa0, -bb0);\n\t  ++i1; \n\t  A0 w1 = ldexp(sqr(cc1), splat<iA0>(i1));\n\t  mm =  maximum(w1); \n\t  s0 += w1;\n\t  aa0 = aa1;\n\t  bb0 = bb1;\n\t};\n      type res;\n      A0 isneqm1 = eq(m, One<A0>());\n      boost::fusion::at_c<0>(res) = b_or(nan, sel(isneqm1,One<A0>(), nt2::Pio_2<A0>()/aa1));\n      boost::fusion::at_c<1>(res) = b_or(nan, sel(isneqm1,Inf<A0>(),\n\t\t\t\t    boost::fusion::at_c<0>(res)*(One<A0>()-s0*Half<A0>()))); \n      return res; \n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "04e24f408c57028740fdbe38013f8af48b047488", "size": 4861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/elliptic/include/nt2/toolbox/elliptic/function/simd/common/ellipke.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/simd/common/ellipke.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/simd/common/ellipke.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.0680272109, "max_line_length": 92, "alphanum_fraction": 0.526229171, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19569421361401665}}
{"text": "#ifndef _CHUNK_HPP_\n#define _CHUNK_HPP_\n\n#include <unordered_map>\n#include <queue>\n#include <cstdint>\n#include <boost/timer.hpp>\n#include <boost/array.hpp>\n#include <boost/multi_array.hpp>\n#include <zlib/zlib.h>\n\n#include \"protocol/messages.hpp\"\n\n\ntypedef std::vector<uint8_t>::const_iterator ByteVecConstItr;\n\nvoid Inflate(const std::vector<uint8_t>& _src, std::vector<uint8_t>& _dst);\n\n// Exceptions\nclass ColumnDoesNotExistException {};\n\nint WorldToColumnRel(int _worldCoord);\nint WorldToColumnCoord(int _worldCoord);\nint RoundWorldCoord(double _worldCoord);\n\n/*int ColumnRelToWorld(int _relCoord, int _colCoord)\n{\n\treturn \n}*/\n\n\nstruct ChunkColumnID\n{\n\tint32_t m_columnX;\n\tint32_t m_columnZ;\n\n\tChunkColumnID(int32_t _columnX, int32_t _columnZ)\n\t\t:\tm_columnX(_columnX)\n\t\t,\tm_columnZ(_columnZ)\n\t{}\n\n\tbool operator==(const ChunkColumnID& _other) const\n\t{\n\t\treturn _other.m_columnX == m_columnX && _other.m_columnZ == m_columnZ;\n\t}\n\n};\n\nnamespace std {\n\ntemplate <>\nstruct hash<ChunkColumnID>\n{\n\tsize_t operator()(const ChunkColumnID& _subject) const\n\t{\n\t\tunion {int32_t x; uint32_t ux;};\n\t\tx = _subject.m_columnX;\n\t\tunion {int32_t z; uint32_t uz;};\n\t\tz = _subject.m_columnZ;\n\n\t\tsize_t retr = 23;\n\t\tretr *= 31;\n\t\tretr += ux;\n\t\tretr *= 31;\n\t\tretr += uz;\n\n\t\treturn retr;\n\t}\n};\n\n} // namespace std\n\n\n\nstruct BlockData\n{\n\tuint16_t m_type;\n\tuint8_t m_metadata;\t\t// 4 bits when arrives\n\tuint8_t m_blockLight;\t// 4 bits when arrives\n\tuint8_t m_skyLight;\t\t// only if 'skylight' is true; 4 bits when arrives\n};\n\n\n// 16x256x16 block, 16 chunks\nclass ChunkColumn\n{\npublic:\n\tChunkColumn()\n\t//\t:\tm_columnDataRef(m_columnData.c_array(), boost::extents[256][16][16]) // YZX\n\t{}\n\tChunkColumn(const ChunkColumn& _other);\n\t~ChunkColumn(){}\n\n\n\tsize_t load(std::vector<uint8_t>& _src, size_t _offset, int _nNonAirChunks);\n\n\tsize_t load(std::vector<uint8_t>& _src, size_t _offset, uint16_t _PrimBitmask, uint16_t _addBitmask);\n\tByteVecConstItr load(ByteVecConstItr _begin, uint16_t _PrimBitmask, uint16_t _addBitmask);\n\n\tinline BlockData& getBlock(int _relX, int _relY, int _relZ);\n\tinline const BlockData& getBlock(int _relX, int _relY, int _relZ) const;\n\t\n\nprivate:\n\tboost::array<BlockData, 256 * 16 * 16> m_columnData; // flat representation of 3d array\n\t\n\n};\n\n\nBlockData& ChunkColumn::getBlock(int _relX, int _relY, int _relZ)\n{\n\treturn m_columnData[_relY * 256 + _relZ * 16 + _relX];\n\t//return m_columnDataRef[_relY][_relZ][_relX];\n\t// boost multi array ref is too slow\n}\n\nconst BlockData& ChunkColumn::getBlock(int _relX, int _relY, int _relZ) const\n{\n\treturn m_columnData[_relY * 256 + _relZ * 16 + _relX];\n\t//return m_columnDataRef[_relY][_relZ][_relX];\n}\n\n\n\n//------------------------------------------------------------------------------\n\nstruct ScheduledBlock\n{\n\tint m_x, m_y, m_z;\n\tBlockData m_block;\n};\n\n\nclass World\n{\npublic:\n\tWorld(){}\n\n\t~World()\n\t{\n\t\tfor(auto itr = m_columnsMap.begin(); itr != m_columnsMap.end(); ++itr)\n\t\t\tdelete itr->second;\n\t}\n\n\tvoid loadColumns(protocol::msg::MapChunkBulk& _columnsMsg);\n\n\tinline BlockData& getBlock(int _blockX, int _blockY, int _blockZ);\n\tinline const BlockData& getBlock(int _blockX, int _blockY, int _blockZ) const;\n\n\t// If column that block belongs to does not exist when change block message arrived,\n\t// this can be used to change block when column appears.\n\t// Will be called automatically when anyone tries to change block in non-existent column.\n\t// Move to private?\n\tvoid scheduleBlockChange(int _blockX, int _blockY, int _blockZ, BlockData _newBlock);\n\nprivate:\n\tstd::unordered_map<ChunkColumnID, ChunkColumn*> m_columnsMap;\n\t// Merge with columns?\n\tstd::unordered_map<ChunkColumnID, std::queue<ScheduledBlock>> m_scheduledBlocks;\n\n};\n\n//------------------------------------------------------------------------------\n\nBlockData& World::getBlock(int _blockX, int _blockY, int _blockZ)\n{\n\tauto colItr = m_columnsMap.find(ChunkColumnID(WorldToColumnCoord(_blockX), WorldToColumnCoord(_blockZ)));\n\tif(colItr == m_columnsMap.end())\n\t\tthrow ColumnDoesNotExistException();\n\n\treturn colItr->second->getBlock(WorldToColumnRel(_blockX), _blockY, WorldToColumnRel(_blockZ));\n}\n\n\nconst BlockData& World::getBlock(int _blockX, int _blockY, int _blockZ) const\n{\n\treturn const_cast<World*>(this)->getBlock(WorldToColumnRel(_blockX), _blockY, WorldToColumnRel(_blockZ));\t\n}\n\n\n\n#endif // _CHUNK_HPP_", "meta": {"hexsha": "9b16d53e2a8b89a5c96219fec7af6ef48c40eae6", "size": 4328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/client/chunk.hpp", "max_stars_repo_name": "tehme/outlaw162", "max_stars_repo_head_hexsha": "8a1eb62f91ba9a53cae871c396fbffe94b871aeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T20:51:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T20:51:32.000Z", "max_issues_repo_path": "include/client/chunk.hpp", "max_issues_repo_name": "tehme/outlaw162", "max_issues_repo_head_hexsha": "8a1eb62f91ba9a53cae871c396fbffe94b871aeb", "max_issues_repo_licenses": ["MIT"], "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/client/chunk.hpp", "max_forks_repo_name": "tehme/outlaw162", "max_forks_repo_head_hexsha": "8a1eb62f91ba9a53cae871c396fbffe94b871aeb", "max_forks_repo_licenses": ["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.650273224, "max_line_length": 107, "alphanum_fraction": 0.7121072089, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19569421361401665}}
{"text": "/*    Copyright (c) 2010-2018, 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#define BOOST_TEST_MAIN\n\n#include <string>\n#include <thread>\n#include <limits>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/tabulatedEphemeris.h\"\n\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/External/SpiceInterface/spiceInterface.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/accelerationModel.h\"\n\n#include \"Tudat/SimulationSetup/EnvironmentSetup/defaultBodies.h\"\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createBodies.h\"\n#include \"Tudat/SimulationSetup/EstimationSetup/createNumericalSimulator.h\"\n#include \"Tudat/SimulationSetup/EstimationSetup/createEstimatableParameters.h\"\n#include \"Tudat/SimulationSetup/EstimationSetup/variationalEquationsSolver.h\"\n\nnamespace tudat\n{\n\nnamespace unit_tests\n{\n\n//Using declarations.\nusing namespace tudat::interpolators;\nusing namespace tudat::numerical_integrators;\nusing namespace tudat::spice_interface;\nusing namespace tudat::simulation_setup;\nusing namespace tudat::basic_astrodynamics;\nusing namespace tudat::estimatable_parameters;\nusing namespace tudat::orbital_element_conversions;\nusing namespace tudat::ephemerides;\nusing namespace tudat::propagators;\n\n\nBOOST_AUTO_TEST_SUITE( test_sequential_variational_equation_integration )\n\n\nstd::pair< std::shared_ptr< CombinedStateTransitionAndSensitivityMatrixInterface >, std::shared_ptr< Ephemeris > >\nintegrateEquations( const bool performIntegrationsSequentially )\n{\n    //Load spice kernels.\n    spice_interface::loadStandardSpiceKernels( );\n\n    std::vector< std::string > bodyNames;\n    bodyNames.push_back( \"Earth\" );\n    bodyNames.push_back( \"Sun\" );\n    bodyNames.push_back( \"Moon\" );\n\n    // Specify initial time\n    double initialEphemerisTime = 1.0E7;\n    double finalEphemerisTime = initialEphemerisTime + 14.0 * 86400.0;\n    double maximumTimeStep = 600.0;\n\n    double numberOfTimeStepBuffer = 6.0;\n    double buffer = numberOfTimeStepBuffer * maximumTimeStep;\n\n    // Create bodies needed in simulation\n    std::map< std::string, std::shared_ptr< BodySettings > > bodySettings =\n            getDefaultBodySettings( bodyNames, initialEphemerisTime - buffer, finalEphemerisTime + buffer );\n    NamedBodyMap bodyMap =\n            createBodies( bodySettings );\n    std::shared_ptr< Body > lageos = std::make_shared< Body >( );\n    bodyMap[ \"LAGEOS\" ] = lageos;\n\n    // Create  body initial state\n    Eigen::Vector6d lageosKeplerianElements;\n    lageosKeplerianElements[ semiMajorAxisIndex ] = 8000.0E3;\n    lageosKeplerianElements[ eccentricityIndex ] = 0.0044;\n    lageosKeplerianElements[ inclinationIndex ] = 109.89 * mathematical_constants::PI / 180.0;\n    lageosKeplerianElements[ argumentOfPeriapsisIndex ] = 259.35 * mathematical_constants::PI / 180.0;\n    lageosKeplerianElements[ longitudeOfAscendingNodeIndex ] = 31.56 * mathematical_constants::PI / 180.0;\n    lageosKeplerianElements[ trueAnomalyIndex ] = 1.0;\n    Eigen::Vector6d lageosState = convertKeplerianToCartesianElements(\n                lageosKeplerianElements, getBodyGravitationalParameter(\"Earth\" ) );\n\n    lageos->setEphemeris( std::make_shared< TabulatedCartesianEphemeris< double, double > >(\n                              std::shared_ptr< interpolators::OneDimensionalInterpolator<\n                              double, Eigen::Vector6d > >( ), \"Earth\" ) );\n    setGlobalFrameBodyEphemerides( bodyMap, \"SSB\", \"ECLIPJ2000\" );\n\n    // Set accelerations between bodies that are to be taken into account.\n    SelectedAccelerationMap accelerationMap;\n\n    std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfLageos;\n    //accelerationsOfLageos[ \"Sun\" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );\n    //accelerationsOfLageos[ \"Earth\" ].push_back( std::make_shared< RelativisticCorrectionSettings >( ) );\n    //accelerationsOfLageos[ \"Earth\" ].push_back( std::make_shared< SphericalHarmonicAccelerationSettings >( 8, 8 ) );\n    accelerationsOfLageos[ \"Earth\" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );\n    accelerationMap[ \"LAGEOS\" ] = accelerationsOfLageos;\n\n    // Set bodies for which initial state is to be estimated and integrated.\n    std::vector< std::string > bodiesToIntegrate;\n    bodiesToIntegrate.push_back( \"LAGEOS\" );\n    unsigned int numberOfNumericalBodies = bodiesToIntegrate.size( );\n\n    std::vector< std::string > centralBodies;\n    std::map< std::string, std::string > centralBodyMap;\n\n    centralBodies.resize( numberOfNumericalBodies );\n    for( unsigned int i = 0; i < numberOfNumericalBodies; i++ )\n    {\n        centralBodies[ i ] = \"Earth\";\n        centralBodyMap[ bodiesToIntegrate[ i ] ] = centralBodies[ i ];\n    }\n    AccelerationMap accelerationModelMap = createAccelerationModelsMap(\n                bodyMap, accelerationMap, centralBodyMap );\n\n    // Set parameters that are to be included.\n    std::vector< std::shared_ptr< EstimatableParameterSettings > > parameterNames;\n    parameterNames.push_back( std::make_shared< InitialTranslationalStateEstimatableParameterSettings< double > >(\n                                  \"LAGEOS\", lageosState, \"Earth\" ) );\n    parameterNames.push_back( std::make_shared< EstimatableParameterSettings >\n                              ( \"Earth\", gravitational_parameter ) );\n    parameterNames.push_back( std::make_shared< EstimatableParameterSettings >\n                              ( \"Moon\", gravitational_parameter ) );\n    std::shared_ptr< estimatable_parameters::EstimatableParameterSet< double > > parametersToEstimate =\n            createParametersToEstimate( parameterNames, bodyMap, accelerationModelMap );\n\n    // Define integrator settings.\n    std::shared_ptr< IntegratorSettings< > > matrixTypeIntegratorSettings =\n            std::make_shared< RungeKuttaVariableStepSizeSettings< > >\n            ( initialEphemerisTime, 10.0,\n              RungeKuttaCoefficients::rungeKuttaFehlberg45, 0.01, 10.0, 1.0E-6, 1.0E-6 );\n\n    // Define propagator settings.\n    std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings =\n            std::make_shared< TranslationalStatePropagatorSettings< double > >\n            ( centralBodies, accelerationModelMap, bodiesToIntegrate, lageosState, finalEphemerisTime );\n\n    // Perform requested propagation\n    std::shared_ptr< SingleArcVariationalEquationsSolver< double, double> > variationalEquationSolver;\n    if( !performIntegrationsSequentially )\n    {\n        // Propagate\n        variationalEquationSolver = std::make_shared< SingleArcVariationalEquationsSolver< double, double> >(\n                    bodyMap, matrixTypeIntegratorSettings,\n                    propagatorSettings, parametersToEstimate );\n    }\n    else\n    {\n\n        // Define integrator settings for vector type.\n        std::shared_ptr< IntegratorSettings< > > vectorTypeIntegratorSettings =\n                std::make_shared< RungeKuttaVariableStepSizeSettings< > >\n                ( initialEphemerisTime, 10.0, RungeKuttaCoefficients::rungeKuttaFehlberg45, 0.01, 10.0, 1.0E-6, 1.0E-6 );\n\n        // Propagate\n        variationalEquationSolver = std::make_shared< SingleArcVariationalEquationsSolver< double, double > >(\n                    bodyMap, vectorTypeIntegratorSettings,\n                    propagatorSettings, parametersToEstimate, 0,\n                    matrixTypeIntegratorSettings );\n    }\n\n    return std::make_pair( variationalEquationSolver->getStateTransitionMatrixInterface( ),\n                           bodyMap[ \"LAGEOS\" ]->getEphemeris( ) );\n}\n\n//! Test whether concurrent and sequential propagation of variational equations gives same results.\nBOOST_AUTO_TEST_CASE( testSequentialVariationalEquationIntegration )\n{\n    // Propagate concurrently.\n    std::pair< std::shared_ptr< CombinedStateTransitionAndSensitivityMatrixInterface >, std::shared_ptr< Ephemeris > >\n            concurrentResult = integrateEquations( 0 );\n\n    // Propagate sequentially.\n    std::pair< std::shared_ptr< CombinedStateTransitionAndSensitivityMatrixInterface >, std::shared_ptr< Ephemeris > >\n            sequentialResult = integrateEquations( 1 );\n\n    // Test variational equations solution.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                concurrentResult.first->getCombinedStateTransitionAndSensitivityMatrix( 1.0E7 + 14.0 * 80000.0 ),\n                sequentialResult.first->getCombinedStateTransitionAndSensitivityMatrix( 1.0E7 + 14.0 * 80000.0 ), 2.0E-6 );\n\n    // Test dynamics solution.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                concurrentResult.second->getCartesianState( 1.0E7 + 14.0 * 80000.0 ),\n                sequentialResult.second->getCartesianState( 1.0E7 + 14.0 * 80000.0 ),\n                std::numeric_limits< double >::epsilon( ) );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n}\n\n}\n", "meta": {"hexsha": "ee5e71d151f5723210dbc7a877e7b38c5b27e0aa", "size": 9490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Propagators/UnitTests/unitTestSequentialVariationalEquationIntegration.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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/Propagators/UnitTests/unitTestSequentialVariationalEquationIntegration.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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/Propagators/UnitTests/unitTestSequentialVariationalEquationIntegration.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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": 46.2926829268, "max_line_length": 123, "alphanum_fraction": 0.7239199157, "num_tokens": 2412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19569420631072648}}
{"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_X86_AVX_SIMD_FUNCTION_HMSB_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_AVX_SIMD_FUNCTION_HMSB_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/function/slice.hpp>\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/detail/dispatch/meta/as_floating.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n\n   BOOST_DISPATCH_OVERLOAD( hmsb_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::type32_<A0>, bs::avx_>\n                          )\n   {\n     BOOST_FORCEINLINE std::size_t operator()(A0 const& a0) const\n      {\n        return _mm256_movemask_ps(bitwise_cast<bd::as_floating_t<A0>>(a0));\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD( hmsb_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::type64_<A0>, bs::avx_>\n                          )\n   {\n     BOOST_FORCEINLINE std::size_t operator()(A0 const& a0) const\n      {\n        return _mm256_movemask_pd(bitwise_cast<bd::as_floating_t<A0>>(a0));\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD( hmsb_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::ints8_<A0>, bs::avx_>\n                          )\n   {\n     BOOST_FORCEINLINE std::size_t operator()(A0 const& a0) const\n      {\n        auto const s = slice(a0);\n        return std::uint32_t(_mm_movemask_epi8(s[0]) | (_mm_movemask_epi8(s[1]) << 16));\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD( hmsb_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::ints16_<A0>, bs::avx_>\n                          )\n   {\n     BOOST_FORCEINLINE std::size_t operator()(A0 const& a0) const\n      {\n        auto const s = slice(a0);\n        return hmsb(s[0]) | (hmsb(s[1]) << 8);\n      }\n   };\n} } }\n\n#endif\n", "meta": {"hexsha": "8ee3c8cf718b32515df29546cddd8bd93baac46a", "size": 2389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/avx/simd/function/hmsb.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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": "third_party/boost/simd/arch/x86/avx/simd/function/hmsb.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/x86/avx/simd/function/hmsb.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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.2837837838, "max_line_length": 100, "alphanum_fraction": 0.4935119297, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19569420631072648}}
{"text": "// Copyright (c) 2009-2010 Satoshi Nakamoto\n// Copyright (c) 2009-2017 The Bitcoin developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"maxblocksize.h\"\n\n#include \"chain.h\"\n#include \"util.h\"\n#include \"options.h\"\n#include \"utilfork.h\"\n\n#include <string>\n#include <algorithm>\n\n#include <boost/lexical_cast.hpp>\n\nuint64_t GetNextMaxBlockSize(const CBlockIndex* pindexLast, const Consensus::Params& params)\n{\n    if (pindexLast == NULL)\n        return MAX_BLOCK_SIZE;\n\n    uint64_t nMaxBlockSize = pindexLast->nMaxBlockSize;\n\n    // Only change once per difficulty adjustment interval\n    if ((pindexLast->nHeight+1) % params.nMaxBlockSizeAdjustmentInterval != 0) {\n        return nMaxBlockSize;\n    }\n\n    std::vector<uint64_t> votes;\n    const CBlockIndex *pindexWalk = pindexLast;\n    for (int64_t i = 0; i < params.nMaxBlockSizeAdjustmentInterval; i++) {\n        assert(pindexWalk);\n        votes.push_back(pindexWalk->nMaxBlockSizeVote ? pindexWalk->nMaxBlockSizeVote : nMaxBlockSize);\n        pindexWalk = pindexWalk->pprev;\n    }\n\n    std::sort(votes.begin(),votes.end());\n    uint64_t lowerValue = votes.at(params.nMaxBlockSizeChangePosition - 1);\n    uint64_t raiseValue = votes.at(params.nMaxBlockSizeAdjustmentInterval - params.nMaxBlockSizeChangePosition);\n\n    assert(lowerValue >= 1000000); // minimal vote supported is 1MB\n    assert(lowerValue >= raiseValue); // lowerValue comes from a higher sorted position\n\n    uint64_t raiseCap = nMaxBlockSize * 105 / 100;\n    raiseValue = (raiseValue > raiseCap ? raiseCap : raiseValue);\n    if (raiseValue > nMaxBlockSize) {\n        nMaxBlockSize = raiseValue;\n    } else {\n        uint64_t lowerFloor = nMaxBlockSize * 100 / 105;\n        lowerValue = (lowerValue < lowerFloor ? lowerFloor : lowerValue);\n        if (lowerValue < nMaxBlockSize)\n            nMaxBlockSize = lowerValue;\n    }\n\n    if (nMaxBlockSize != pindexLast->nMaxBlockSize) {\n        LogPrintf(\"GetNextMaxBlockSize RETARGET\\n\");\n        LogPrintf(\"Before: %d\\n\", pindexLast->nMaxBlockSize);\n        LogPrintf(\"After:  %d\\n\", nMaxBlockSize);\n    }\n\n    return nMaxBlockSize;\n}\n\nstatic uint32_t FindVote(const std::string& coinbase) {\n\n    bool eb_vote = false;\n    uint32_t ebVoteMB = 0;\n    std::vector<char> curr;\n    bool bip100vote = false;\n    bool started = false;\n\n    for (char s : coinbase) {\n        if (s == '/') {\n            started = true;\n            // End (or beginning) of a potential vote string.\n\n            if (curr.size() < 2) // Minimum vote string length is 2\n            {\n                bip100vote = false;\n                curr.clear();\n                continue;\n            }\n\n            if (std::string(begin(curr), end(curr)) == \"BIP100\") {\n                bip100vote = true;\n                curr.clear();\n                continue;\n            }\n\n            // Look for a B vote.\n            if (bip100vote && curr[0] == 'B') {\n                try {\n                    return boost::lexical_cast<uint32_t>(std::string(\n                                begin(curr) + 1, end(curr)));\n                }\n                catch (const std::exception& e) {\n                    LogPrintf(\"Invalid coinbase B-vote: %s\\n\", e.what());\n                }\n            }\n\n            // Look for a EB vote. Keep it, but continue to look for a BIP100/B vote.\n            if (!eb_vote && curr[0] == 'E' && curr[1] == 'B') {\n                try {\n                    ebVoteMB = boost::lexical_cast<uint32_t>(std::string(\n                                begin(curr) + 2, end(curr)));\n                    eb_vote = true;\n                }\n                catch (const std::exception& e) {\n                    LogPrintf(\"Invalid coinbase EB-vote: %s\\n\", e.what());\n                }\n            }\n\n            bip100vote = false;\n            curr.clear();\n            continue;\n        }\n        else if (!started)\n            continue;\n        else\n            curr.push_back(s);\n    }\n    return ebVoteMB;\n}\n\nuint64_t GetMaxBlockSizeVote(const CScript &coinbase, int32_t nHeight)\n{\n    // Skip encoded height if found at start of coinbase\n    CScript expect = CScript() << nHeight;\n    int searchStart = coinbase.size() >= expect.size() &&\n                      std::equal(expect.begin(), expect.end(), coinbase.begin())\n                      ? expect.size()\n                      :0;\n\n    std::string s(coinbase.begin() + searchStart, coinbase.end());\n\n    if (s.length() < 5) // shortest vote is /EB1/\n        return 0;\n\n\n    return static_cast<uint64_t>(FindVote(s)) * 1000000;\n}\n\nuint64_t NextBlockRaiseCap(uint64_t maxCurrBlock) {\n    if (maxCurrBlock < MAX_BLOCK_SIZE)\n        throw std::invalid_argument(\"Current block max can't be less than MAX_BLOCK_SIZE\");\n\n    // BIP100 allows block size limit to be increased 5%.\n    return maxCurrBlock * 105 / 100;\n}\n", "meta": {"hexsha": "41f7be3ca065956c1042dc007783bf404ea9c5d8", "size": 4908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/maxblocksize.cpp", "max_stars_repo_name": "coindroid42/chain2", "max_stars_repo_head_hexsha": "ce7c8012da1792ddb0b9760a7bfc0673f2ca5816", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T15:55:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-11T04:21:11.000Z", "max_issues_repo_path": "src/maxblocksize.cpp", "max_issues_repo_name": "coindroid42/chain2", "max_issues_repo_head_hexsha": "ce7c8012da1792ddb0b9760a7bfc0673f2ca5816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T23:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T18:38:55.000Z", "max_forks_repo_path": "src/maxblocksize.cpp", "max_forks_repo_name": "coindroid42/chain2", "max_forks_repo_head_hexsha": "ce7c8012da1792ddb0b9760a7bfc0673f2ca5816", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T15:04:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-13T09:44:41.000Z", "avg_line_length": 32.5033112583, "max_line_length": 112, "alphanum_fraction": 0.5823145884, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.19563431511552987}}
{"text": "#include <boost/circular_buffer.hpp>\n#include <iostream>\n#include <mutex>\n\n#include <pcl_ros/point_cloud.h>\n#include <pcl_ros/transforms.h>\n#include <ros/ros.h>\n#include <tf/transform_broadcaster.h>\n#include <tf_conversions/tf_eigen.h>\n\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <std_msgs/Float64.h>\n\n#include <nodelet/nodelet.h>\n#include <pluginlib/class_list_macros.h>\n\n#include <pcl/filters/voxel_grid.h>\n\n#include <pclomp/ndt_omp.h>\n\n#include <hdl_localization/pose_estimator.hpp>\n\nnamespace hdl_localization {\n\nclass HdlLocalizationNodelet : public nodelet::Nodelet {\npublic:\n  using PointT = pcl::PointXYZI;\n\n  HdlLocalizationNodelet() {}\n  virtual ~HdlLocalizationNodelet() {}\n\n  void onInit() override {\n    nh = getNodeHandle();\n    mt_nh = getMTNodeHandle();\n    private_nh = getPrivateNodeHandle();\n\n    processing_time.resize(16);\n    initialize_params();\n\n    map_frame_id = private_nh.param<std::string>(\"map_frame_id\", \"world\");\n    odom_child_frame_id =\n        private_nh.param<std::string>(\"odom_child_frame_id\", \"base_link\");\n\n    use_guesses = private_nh.param<bool>(\"use_guesses\", true);\n    if (use_guesses) {\n      NODELET_INFO(\"enable guess-based prediction\");\n      guess_sub = mt_nh.subscribe(\n          \"/guess\", 256, &HdlLocalizationNodelet::guess_callback, this);\n    }\n    points_sub = mt_nh.subscribe(\n        \"/velodyne_points\", 5, &HdlLocalizationNodelet::points_callback, this);\n    globalmap_sub = nh.subscribe(\n        \"/globalmap\", 1, &HdlLocalizationNodelet::globalmap_callback, this);\n    initialpose_sub = nh.subscribe(\n        \"/initialpose\", 8, &HdlLocalizationNodelet::initialpose_callback, this);\n\n    pose_pub = nh.advertise<nav_msgs::Odometry>(\"/odom\", 5, false);\n    aligned_pub =\n        nh.advertise<sensor_msgs::PointCloud2>(\"/aligned_points\", 5, false);\n    score_pub = nh.advertise<std_msgs::Float64>(\"/score\", 5, false);\n  }\n\nprivate:\n  void initialize_params() {\n    // intialize scan matching method\n    double downsample_resolution =\n        private_nh.param<double>(\"downsample_resolution\", 0.1);\n    std::string ndt_neighbor_search_method =\n        private_nh.param<std::string>(\"ndt_neighbor_search_method\", \"DIRECT7\");\n\n    double ndt_resolution = private_nh.param<double>(\"ndt_resolution\", 1.0);\n    boost::shared_ptr<pcl::VoxelGrid<PointT>> voxelgrid(\n        new pcl::VoxelGrid<PointT>());\n    voxelgrid->setLeafSize(downsample_resolution, downsample_resolution,\n                           downsample_resolution);\n    downsample_filter = voxelgrid;\n\n    pclomp::NormalDistributionsTransform<PointT, PointT>::Ptr ndt(\n        new pclomp::NormalDistributionsTransform<PointT, PointT>());\n    ndt->setTransformationEpsilon(0.01);\n    ndt->setResolution(ndt_resolution);\n    if (ndt_neighbor_search_method == \"DIRECT1\") {\n      NODELET_INFO(\"search_method DIRECT1 is selected\");\n      ndt->setNeighborhoodSearchMethod(pclomp::DIRECT1);\n    } else if (ndt_neighbor_search_method == \"DIRECT7\") {\n      NODELET_INFO(\"search_method DIRECT7 is selected\");\n      ndt->setNeighborhoodSearchMethod(pclomp::DIRECT7);\n    } else {\n      if (ndt_neighbor_search_method == \"KDTREE\") {\n        NODELET_INFO(\"search_method KDTREE is selected\");\n      } else {\n        NODELET_WARN(\"invalid search method was given\");\n        NODELET_WARN(\"default method is selected (KDTREE)\");\n      }\n      ndt->setNeighborhoodSearchMethod(pclomp::KDTREE);\n    }\n    registration = ndt;\n\n    // initialize pose estimator\n    if (private_nh.param<bool>(\"specify_init_pose\", true)) {\n      NODELET_INFO(\"initialize pose estimator with specified parameters!!\");\n      pose_estimator.reset(new hdl_localization::PoseEstimator(\n          registration, ros::Time::now(),\n          Eigen::Vector3f(private_nh.param<double>(\"init_pos_x\", 0.0),\n                          private_nh.param<double>(\"init_pos_y\", 0.0),\n                          private_nh.param<double>(\"init_pos_z\", 0.0)),\n          Eigen::Quaternionf(private_nh.param<double>(\"init_ori_w\", 1.0),\n                             private_nh.param<double>(\"init_ori_x\", 0.0),\n                             private_nh.param<double>(\"init_ori_y\", 0.0),\n                             private_nh.param<double>(\"init_ori_z\", 0.0)),\n          private_nh.param<double>(\"cool_time_duration\", 0.5)));\n    }\n  }\n\nprivate:\n  /**\n   * @brief callback for guesses\n   * @param pose\n   */\n  void\n  guess_callback(const geometry_msgs::PoseWithCovarianceStampedConstPtr pose) {\n    std::lock_guard<std::mutex> lock(pose_estimator_mutex);\n    auto p = pose->pose.pose.position;\n    auto o = pose->pose.pose.orientation;\n    auto stamp = pose->header.stamp;\n    Eigen::Vector3f pos(p.x, p.y, p.z);\n    Eigen::Vector4f ori(o.w, o.x, o.y, o.z);\n    pose_estimator->predict(stamp, pos, ori);\n  }\n\n  /**\n   * @brief callback for point cloud data\n   * @param points_msg\n   */\n  void points_callback(const sensor_msgs::PointCloud2ConstPtr &points_msg) {\n    std::lock_guard<std::mutex> estimator_lock(pose_estimator_mutex);\n    if (!pose_estimator) {\n      NODELET_ERROR(\"waiting for initial pose input!!\");\n      return;\n    }\n\n    if (!globalmap) {\n      NODELET_ERROR(\"globalmap has not been received!!\");\n      return;\n    }\n\n    const auto &stamp = points_msg->header.stamp;\n    pcl::PointCloud<PointT>::Ptr pcl_cloud(new pcl::PointCloud<PointT>());\n    pcl::fromROSMsg(*points_msg, *pcl_cloud);\n\n    if (pcl_cloud->empty()) {\n      NODELET_ERROR(\"cloud is empty!!\");\n      return;\n    }\n\n    // transform pointcloud into odom_child_frame_id\n    pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>());\n    if (!tf_listener.waitForTransform(odom_child_frame_id, \"velodyne\", stamp,\n                                      ros::Duration(0.5))) {\n      NODELET_WARN(\"timeout at waiting for transformer update!!\");\n      return;\n    }\n\n    if (!pcl_ros::transformPointCloud(odom_child_frame_id, *pcl_cloud, *cloud,\n                                      tf_listener)) {\n      NODELET_WARN(\"point cloud cannot be transformed into target frame!!\");\n      return;\n    }\n\n    // predict\n    auto q = pose_estimator->quat();\n    Eigen::Vector4f ori(q.w(), q.x(), q.y(), q.z());\n    pose_estimator->predict(stamp,\n                            pose_estimator->pos() + pose_estimator->vel(), ori);\n\n    // correct\n    auto filtered = downsample(cloud);\n    auto t1 = ros::WallTime::now();\n    auto aligned = pose_estimator->correct(filtered);\n    auto t2 = ros::WallTime::now();\n    score_pub.publish(pose_estimator->score);\n\n    processing_time.push_back((t2 - t1).toSec());\n    double avg_processing_time =\n        std::accumulate(processing_time.begin(), processing_time.end(), 0.0) /\n        processing_time.size();\n\n    if (aligned_pub.getNumSubscribers()) {\n      aligned->header.frame_id = map_frame_id;\n      aligned->header.stamp = cloud->header.stamp;\n      aligned_pub.publish(aligned);\n    }\n\n    publish_odometry(points_msg->header.stamp, pose_estimator->matrix());\n  }\n\n  /**\n   * @brief callback for globalmap input\n   * @param points_msg\n   */\n  void globalmap_callback(const sensor_msgs::PointCloud2ConstPtr &points_msg) {\n    NODELET_INFO(\"globalmap received!\");\n    pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>());\n    pcl::fromROSMsg(*points_msg, *cloud);\n    globalmap = cloud;\n\n    registration->setInputTarget(globalmap);\n  }\n\n  /**\n   * @brief callback for initial pose input (\"2D Pose Estimate\" on rviz)\n   * @param pose_msg\n   */\n  void initialpose_callback(\n      const geometry_msgs::PoseWithCovarianceStampedConstPtr &pose_msg) {\n    NODELET_INFO(\"initial pose received!!\");\n    std::lock_guard<std::mutex> lock(pose_estimator_mutex);\n    const auto &p = pose_msg->pose.pose.position;\n    const auto &q = pose_msg->pose.pose.orientation;\n    pose_estimator.reset(new hdl_localization::PoseEstimator(\n        registration, ros::Time::now(), Eigen::Vector3f(p.x, p.y, p.z),\n        Eigen::Quaternionf(q.w, q.x, q.y, q.z),\n        private_nh.param<double>(\"cool_time_duration\", 0.5)));\n  }\n\n  /**\n   * @brief downsampling\n   * @param cloud   input cloud\n   * @return downsampled cloud\n   */\n  pcl::PointCloud<PointT>::ConstPtr\n  downsample(const pcl::PointCloud<PointT>::ConstPtr &cloud) const {\n    if (!downsample_filter) {\n      return cloud;\n    }\n\n    pcl::PointCloud<PointT>::Ptr filtered(new pcl::PointCloud<PointT>());\n    downsample_filter->setInputCloud(cloud);\n    downsample_filter->filter(*filtered);\n    filtered->header = cloud->header;\n\n    return filtered;\n  }\n\n  /**\n   * @brief publish odometry\n   * @param stamp  timestamp\n   * @param pose   odometry pose to be published\n   */\n  void publish_odometry(const ros::Time &stamp, const Eigen::Matrix4f &pose) {\n    // broadcast the transform over tf\n    geometry_msgs::TransformStamped odom_trans =\n        matrix2transform(stamp, pose, map_frame_id, odom_child_frame_id);\n    pose_broadcaster.sendTransform(odom_trans);\n\n    // publish the transform\n    nav_msgs::Odometry odom;\n    odom.header.stamp = stamp;\n    odom.header.frame_id = map_frame_id;\n\n    odom.pose.pose.position.x = pose(0, 3);\n    odom.pose.pose.position.y = pose(1, 3);\n    odom.pose.pose.position.z = pose(2, 3);\n    odom.pose.pose.orientation = odom_trans.transform.rotation;\n\n    odom.child_frame_id = odom_child_frame_id;\n    odom.twist.twist.linear.x = 0.0;\n    odom.twist.twist.linear.y = 0.0;\n    odom.twist.twist.angular.z = 0.0;\n\n    pose_pub.publish(odom);\n  }\n\n  /**\n   * @brief convert a Eigen::Matrix to TransformedStamped\n   * @param stamp           timestamp\n   * @param pose            pose matrix\n   * @param frame_id        frame_id\n   * @param child_frame_id  child_frame_id\n   * @return transform\n   */\n  geometry_msgs::TransformStamped\n  matrix2transform(const ros::Time &stamp, const Eigen::Matrix4f &pose,\n                   const std::string &frame_id,\n                   const std::string &child_frame_id) {\n    Eigen::Quaternionf quat(pose.block<3, 3>(0, 0));\n    quat.normalize();\n    geometry_msgs::Quaternion odom_quat;\n    odom_quat.w = quat.w();\n    odom_quat.x = quat.x();\n    odom_quat.y = quat.y();\n    odom_quat.z = quat.z();\n\n    geometry_msgs::TransformStamped odom_trans;\n    odom_trans.header.stamp = stamp;\n    odom_trans.header.frame_id = frame_id;\n    odom_trans.child_frame_id = child_frame_id;\n\n    odom_trans.transform.translation.x = pose(0, 3);\n    odom_trans.transform.translation.y = pose(1, 3);\n    odom_trans.transform.translation.z = pose(2, 3);\n    odom_trans.transform.rotation = odom_quat;\n\n    return odom_trans;\n  }\n\nprivate:\n  // ROS\n  ros::NodeHandle nh;\n  ros::NodeHandle mt_nh;\n  ros::NodeHandle private_nh;\n\n  std::string map_frame_id;\n  std::string odom_child_frame_id;\n\n  bool use_guesses;\n  ros::Subscriber guess_sub;\n  ros::Subscriber points_sub;\n  ros::Subscriber globalmap_sub;\n  ros::Subscriber initialpose_sub;\n\n  ros::Publisher pose_pub;\n  ros::Publisher aligned_pub;\n  ros::Publisher score_pub;\n  tf::TransformBroadcaster pose_broadcaster;\n  tf::TransformListener tf_listener;\n\n  // globalmap and registration method\n  pcl::PointCloud<PointT>::Ptr globalmap;\n  pcl::Filter<PointT>::Ptr downsample_filter;\n  pcl::Registration<PointT, PointT>::Ptr registration;\n\n  // pose estimator\n  std::mutex pose_estimator_mutex;\n  std::unique_ptr<hdl_localization::PoseEstimator> pose_estimator;\n\n  // processing time buffer\n  boost::circular_buffer<double> processing_time;\n};\n\n} // namespace hdl_localization\n\nPLUGINLIB_EXPORT_CLASS(hdl_localization::HdlLocalizationNodelet,\n                       nodelet::Nodelet)\n", "meta": {"hexsha": "84515d3c2aa58c915534f42d15f12e2e229d35ab", "size": 11628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/hdl_localization_nodelet.cpp", "max_stars_repo_name": "bugerry87/hdl_localization", "max_stars_repo_head_hexsha": "53b4a159412b8d570071f0dab8610c5c1fdbf7c4", "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": "apps/hdl_localization_nodelet.cpp", "max_issues_repo_name": "bugerry87/hdl_localization", "max_issues_repo_head_hexsha": "53b4a159412b8d570071f0dab8610c5c1fdbf7c4", "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": "apps/hdl_localization_nodelet.cpp", "max_forks_repo_name": "bugerry87/hdl_localization", "max_forks_repo_head_hexsha": "53b4a159412b8d570071f0dab8610c5c1fdbf7c4", "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.4137931034, "max_line_length": 80, "alphanum_fraction": 0.6755245958, "num_tokens": 2862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.195634311401413}}
{"text": "// This file is part of slideio project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://slideio.com/license.html.\n#include \"slideio/imagetools/imagetools.hpp\"\n\n#include <numeric>\n\n#include \"slideio/slideio.hpp\"\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <opencv2/imgproc.hpp>\n\n\nint slideio::ImageTools::dataTypeSize(slideio::DataType dt)\n{\n    switch(dt)\n    {\n    case DataType::DT_Byte:\n    case DataType::DT_Int8:\n        return 1;\n    case DataType::DT_UInt16:\n    case DataType::DT_Int16:\n    case DataType::DT_Float16:\n        return 2;\n    case DataType::DT_Int32:\n    case DataType::DT_Float32:\n        return 4;\n    case DataType::DT_Float64:\n        return 8;\n    case DataType::DT_Unknown:\n    case DataType::DT_None:\n        break;\n    }\n    throw std::runtime_error(\n        (boost::format(\"Unknown data type: %1%\") % (int)dt).str());\n}\n\nvoid slideio::ImageTools::scaleRect(const cv::Rect& srcRect, const cv::Size& newSize, cv::Rect& trgRect)\n{\n    double scaleX = static_cast<double>(newSize.width) / static_cast<double>(srcRect.width);\n    double scaleY = static_cast<double>(newSize.height) / static_cast<double>(srcRect.height);\n    trgRect.x = static_cast<int>(std::floor(static_cast<double>(srcRect.x)*scaleX));\n    trgRect.y = static_cast<int>(std::floor(static_cast<double>(srcRect.y)*scaleY));\n    trgRect.width = newSize.width;\n    trgRect.height = newSize.height;\n}\n\nvoid slideio::ImageTools::scaleRect(const cv::Rect& srcRect, double scaleX, double scaleY, cv::Rect& trgRect)\n{\n    trgRect.x = static_cast<int>(std::floor(static_cast<double>(srcRect.x)*scaleX));\n    trgRect.y = static_cast<int>(std::floor(static_cast<double>(srcRect.y)*scaleY));\n    int xn = srcRect.x + srcRect.width;\n    int yn = srcRect.y + srcRect.height;\n    int dxn = static_cast<int>(std::ceil(static_cast<double>(xn)* scaleX));\n    int dyn = static_cast<int>(std::ceil(static_cast<double>(yn)* scaleY));\n    trgRect.width = dxn - trgRect.x;\n    trgRect.height = dyn - trgRect.y;\n}\n\ndouble slideio::ImageTools::computeSimilarity(const cv::Mat& leftM, const cv::Mat& rightM)\n{\n    double similarity = 0;\n\n    // convert to 8bit images\n    cv::Mat oneChannelLeftM = leftM.reshape(1);\n    cv::Mat oneChannelRightM = rightM.reshape(1);\n    double minLeft(0), maxLeft(0), minRight(0), maxRight(0);\n    cv::minMaxLoc(oneChannelLeftM, &minLeft, &maxLeft);\n    cv::minMaxLoc(oneChannelRightM, &minRight, &maxRight);\n    double minVal = std::min(minLeft, minRight);\n    double maxVal = std::max(maxLeft, maxRight);\n    double absVal = maxVal;\n    absVal -= minVal;\n    double alpha = 255. / absVal;\n    double beta = -minVal * alpha;\n\n    cv::Mat left, right;\n    leftM.convertTo(left, CV_MAKE_TYPE(CV_8U, left.channels()), alpha, beta);\n    rightM.convertTo(right, CV_MAKE_TYPE(CV_8U, right.channels()), alpha, beta);\n\n    cv::Rect rectWindow(0, 0, 30, 30);\n    const int width = left.size[1];\n    const int height = left.size[0];\n    std::vector<double> scores;\n    cv::Rect image(0, 0, width, height);\n    const int binCount = 10;\n\n    for (int y = 0; y < height; y += rectWindow.height)\n    {\n        for (int x = 0; x < width; x += rectWindow.width)\n        {\n            cv::Rect rectWnd2(rectWindow);\n            rectWnd2.x = x;\n            rectWnd2.y = y;\n            cv::Rect rectRoi = rectWnd2 & image;\n            cv::Mat leftRoi = left(rectRoi);\n            cv::Mat rightRoi = right(rectRoi);\n            double score = compareHistograms(leftRoi, rightRoi, binCount);\n            scores.push_back(score);\n        }\n    }\n    similarity = std::accumulate(scores.begin(), scores.end(), 0.0) / scores.size();\n    return similarity;\n}\n\ndouble slideio::ImageTools::compareHistograms(const cv::Mat& left, const cv::Mat& right, int binCount)\n{\n    double similarity = 0;\n\n    const int channelCount = left.channels();\n    std::vector<int> channels(channelCount);\n\n    std::vector<float*> ranges(channelCount);\n    std::vector<int> histSizes(channelCount);\n    std::vector<float> rangeVals(channelCount * 2);\n    float minVal = 0;\n    float maxVal = 256;\n\n    for (int channel = 0; channel < channelCount; ++channel) {\n        channels[channel] = channel;\n        histSizes[channel] = binCount;\n        const int channel2 = channel * 2;\n        rangeVals[channel2] = (float)minVal;\n        rangeVals[channel2 + 1] = (float)maxVal;\n        ranges[channel] = &rangeVals[channel2];\n    }\n\n    cv::Mat histLeft, histRight;\n    cv::Mat mask;\n\n    cv::calcHist(&left, 1, channels.data(), mask, histLeft,\n        channelCount, histSizes.data(), (const float**)ranges.data());\n\n    cv::calcHist(&right, 1, channels.data(), mask, histRight,\n        channelCount, histSizes.data(), (const float**)ranges.data());\n\n    similarity = cv::compareHist(histLeft, histRight, cv::HISTCMP_CORREL);\n\n    return similarity;\n}\n", "meta": {"hexsha": "0c6c18b28e3ed4c310b1157e396276f41f88b062", "size": 4909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/slideio/imagetools/imagetools.cpp", "max_stars_repo_name": "Booritas/slideio", "max_stars_repo_head_hexsha": "fdee97747cc73f087a5538aef6a0315ec75becca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-01-25T15:21:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T09:23:37.000Z", "max_issues_repo_path": "src/slideio/imagetools/imagetools.cpp", "max_issues_repo_name": "Booritas/slideio", "max_issues_repo_head_hexsha": "fdee97747cc73f087a5538aef6a0315ec75becca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-12-30T16:21:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T09:23:18.000Z", "max_forks_repo_path": "src/slideio/imagetools/imagetools.cpp", "max_forks_repo_name": "Booritas/slideio", "max_forks_repo_head_hexsha": "fdee97747cc73f087a5538aef6a0315ec75becca", "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.8156028369, "max_line_length": 109, "alphanum_fraction": 0.6563454879, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.1954629536740928}}
{"text": "#include <iostream>\n#include <exception>\n\n#include <boost/filesystem.hpp>\n\n#include \"SUEPTree/Utils/interface/JECCorrector.h\"\n\n\nusing namespace suep;\n\n\nnamespace {\n\n  // Used to initialize the JetCorrectionParameters\n  std::vector<JetCorrectorParameters> load_params (const std::string& files_base, const std::string& jet_type) {\n\n    std::vector<JetCorrectorParameters> output {};\n\n    const std::vector<std::string> levels = {\n      \"L1FastJet\",\n      \"L2Relative\",\n      \"L3Absolute\",\n      \"L2L3Residual\"\n    };\n\n    for (const auto& level : levels) {\n\n      const std::string correction_file = files_base + \"_\" + level + \"_\" + jet_type + \".txt\";\n\n      if (not boost::filesystem::exists(correction_file)) {\n        std::cerr << \"Cannot find correction file: \" << correction_file << std::endl;\n        throw std::runtime_error {\"No file\"};\n      }\n\n      output.emplace_back(correction_file);\n    }\n\n    return output;\n\n  }\n\n}\n\n\nJECCorrector::JECCorrector (const std::string& files_base, const std::string& jet_type) :\n  m_corrector_params {load_params(files_base, jet_type)},\n  m_corrector {m_corrector_params} {}\n\n\nvoid JECCorrector::update_event (const suep::Event& event, const suep::JetCollection& jets, const RecoMet& met) {\n\n  // Copy jets over\n  m_corrected_jets = jets;\n  m_corrected_met = met;\n\n  TVector2 new_met {met.v()};\n  TVector2 met_correction {};\n\n  for (auto& jet : m_corrected_jets) {\n\n    // FactorizedJetCorrectorCalculator is stupid and resets these every time\n    m_corrector.setNPV(event.npv);\n    m_corrector.setRho(event.rho);\n\n    m_corrector.setJetEta(jet.eta());\n    m_corrector.setJetPt(jet.rawPt);\n    m_corrector.setJetE(jet.e());\n    m_corrector.setJetPhi(jet.phi());\n    m_corrector.setJetEMF(jet.cef + jet.nef); // Check that this is right\n    m_corrector.setJetA(jet.area);\n\n    auto scale = m_corrector.getCorrection();\n\n    auto new_pt = scale * jet.rawPt;\n\n    // Use minus new so that we don't have to flip phi.\n    // This takes out the old correction and adds the new correction back in\n    met_correction.SetMagPhi(jet.pt() - new_pt, jet.phi());\n\n    new_met += met_correction;\n\n    jet.setPtEtaPhiM(new_pt, jet.eta(), jet.phi(), jet.m());\n  }\n\n  m_corrected_jets.sort(suep::Particle::PtGreater);\n\n  // Change stored MET\n  m_corrected_met.setXY(new_met.X(), new_met.Y());\n\n}\n\n\nconst JetCollection& JECCorrector::get_jets () const {\n\n  return m_corrected_jets;\n\n}\n\n\nconst RecoMet& JECCorrector::get_met () const {\n\n  return m_corrected_met;\n\n}\n", "meta": {"hexsha": "130ca23cf3556c6493bd797a9d5430eaec09d6e9", "size": 2491, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Utils/src/JECCorrector.cc", "max_stars_repo_name": "dr-stringfellow/SUEPTree", "max_stars_repo_head_hexsha": "ed19f065e73eabfe659ae651efc7239849fac75b", "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/src/JECCorrector.cc", "max_issues_repo_name": "dr-stringfellow/SUEPTree", "max_issues_repo_head_hexsha": "ed19f065e73eabfe659ae651efc7239849fac75b", "max_issues_repo_licenses": ["MIT"], "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/src/JECCorrector.cc", "max_forks_repo_name": "dr-stringfellow/SUEPTree", "max_forks_repo_head_hexsha": "ed19f065e73eabfe659ae651efc7239849fac75b", "max_forks_repo_licenses": ["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.7238095238, "max_line_length": 113, "alphanum_fraction": 0.6868727419, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.1954629536740928}}
{"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_MAKE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_MAKE_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/function/genmask.hpp>\n#include <boost/simd/function/load.hpp>\n#include <boost/simd/meta/hierarchy/logical.hpp>\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/meta/as_arithmetic.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <initializer_list>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = ::boost::dispatch;\n  namespace bs = ::boost::simd;\n\n  //------------------------------------------------------------------------------------------------\n  // Some shared code between two specialisation\n  template<typename Target, typename... Values>\n  struct make_helper\n  {\n    using storage_t = typename Target::storage_type;\n\n    static inline storage_t do_ ( Values const&... vs\n                                , ::boost::simd::scalar_storage const&\n                                ) BOOST_NOEXCEPT\n    {\n      storage_t that{{ static_cast<typename Target::substorage_type>(vs)... }};\n      return that;\n    }\n\n    static inline Target do_( Values const&... vs\n                            , ::boost::simd::aggregate_storage const&\n                            ) BOOST_NOEXCEPT\n    {\n      using value_type = typename Target::value_type;\n      std::initializer_list<value_type> lst{ static_cast<value_type>(vs)... };\n      return load<Target>(lst.begin());\n    }\n  };\n\n  template<typename Target, typename... Values>\n  struct make_logical_helper\n  {\n    using storage_t = typename Target::storage_type;\n\n    static inline Target do_( Values const&... vs\n                            , ::boost::simd::aggregate_storage const&\n                            ) BOOST_NOEXCEPT\n    {\n      using value_type = typename Target::value_type;\n      std::initializer_list<value_type> lst{ static_cast<value_type>(vs)... };\n      return load<Target>(lst.begin());\n    }\n\n    template<typename K>\n    static inline Target do_( Values const&... vs\n                            , K const&\n                            ) BOOST_NOEXCEPT\n    {\n      using   value_t = typename as_arithmetic_t<Target>::value_type;\n      return  bitwise_cast<Target>( make<as_arithmetic_t<Target>>( genmask<value_t>(vs)...));\n    }\n  };\n\n  //------------------------------------------------------------------------------------------------\n  // make from unspecified value\n  BOOST_DISPATCH_OVERLOAD ( make_\n                          , (typename Target, typename... Values)\n                          , bd::cpu_\n                          , bd::target_<bs::pack_<bd::unspecified_<Target>,bs::simd_emulation_>>\n                          , bd::scalar_<bd::unspecified_<Values>>...\n                          )\n  {\n    using target_t  = typename Target::type;\n    using storage_t = typename target_t::storage_type;\n\n    static_assert ( sizeof...(Values) == target_t::static_size\n                  , \"boost::simd::make - Invalid number of parameters\"\n                  );\n\n    BOOST_FORCEINLINE target_t operator()(Target const&, Values const&... vs) const BOOST_NOEXCEPT\n    {\n      return make_helper<target_t,Values...>::do_( vs..., typename target_t::storage_kind{});\n    }\n  };\n\n  //------------------------------------------------------------------------------------------------\n  // make from logical value in emulation mode - This is not duplicated code\n  BOOST_DISPATCH_OVERLOAD ( make_\n                          , (typename Target, typename... Values, typename Ext)\n                          , bd::cpu_\n                          , bd::target_<bs::pack_<bs::logical_<Target>,Ext>>\n                          , bd::scalar_<bd::unspecified_<Values>>...\n                          )\n  {\n    using target_t  = typename Target::type;\n    using storage_t = typename target_t::storage_type;\n\n    static_assert ( sizeof...(Values) == target_t::static_size\n                  , \"boost::simd::make - Invalid number of parameters\"\n                  );\n\n    BOOST_FORCEINLINE target_t operator()(Target const&, Values const&... vs) const BOOST_NOEXCEPT\n    {\n      return make_logical_helper<target_t,Values...>::do_(vs..., typename target_t::storage_kind{});\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "020e6da7d0ac403accf75cb52d092b6910916dc0", "size": 4747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/make.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/simd/function/make.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/make.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": 37.976, "max_line_length": 100, "alphanum_fraction": 0.5487676427, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "\n#include <algorithm>\n#include <cassert>\n\n#include <ros/package.h>\n#include <cv_bridge/cv_bridge.h>\n#include <sensor_msgs/image_encodings.h>\n\n#include <boost/assign/list_of.hpp>\n#include <boost/filesystem.hpp>\n\n#include <anchoring/attribute.hpp>\n\nnamespace anchoring {\n\n  // Set a global threashold for max spikes in distributions\n  const double CONST_MAX_TH = 0.65;\n\n  // Used namespace(s)\n  using namespace std;\n\n  // --[ Namspace functions ]--  \n  void sortAttribute( vector<string>  &symbols,\n\t\t      vector<float> &predictions,\n\t\t      int n ) {\n    for( uint i = 0; i < predictions.size() - 1; i++ ) {\n      for( uint j = i + 1; j < predictions.size(); j++ ) {\n\tif( predictions[i] < predictions[j] ) {\n\t  swapValues<float>( predictions[i], predictions[j]);\n\t  swapValues<std::string>( symbols[i], symbols[j]);\n\t}\n      }\n    }\n    if( n >= 0 && n < (int)symbols.size() ) {\n      symbols.erase( symbols.begin() + n, symbols.end());\n      predictions.erase( predictions.begin() + n, predictions.end());\n    }\n  }\n\n  // Mapping between attribute type and string\n  AttributeType mapAttributeType(const string &type) {\n    if( type == \"category\" ) return CATEGORY;\n    if( type == \"color\" ) return COLOR;\n    if( type == \"descriptor\" ) return DESCRIPTOR;\n    if( type == \"position\" ) return POSITION;\n    return SIZE;\n  }\n\n  // Create an attribute (pointer) based on the attribute type  \n  AttributePtr createAttribute(AttributeType type) {\n    switch(type) {\n    case CATEGORY:   return AttributePtr( new CategoryAttribute(type) );\n    case COLOR:      return AttributePtr( new ColorAttribute(type) );\n    case DESCRIPTOR: return AttributePtr( new DescriptorAttribute(type) );\n    case POSITION:   return AttributePtr( new PositionAttribute(type) );\n    default:         return AttributePtr( new SizeAttribute(type) );\n    };\n  }\n\n  \n  // ---------------------------------------\n  // 0. Common attribute base struct methods\n  // ------------------------------------------\n  mongo::Database::Document AttributeCommon::serialize() {\n    mongo::Database::Document doc;\n\n    // Save the symbols\n    try {\n      doc.add<string>( \"symbols\", this->_symbols);\n    }\n    catch( const std::exception &e) {\n      cout << \"[AttributeCommon::serialize]\" << e.what() << endl;\n    }\n    return doc;\n  }\n\n  void AttributeCommon::deserialize(const mongo::Database::Document &doc) {\n\n    // Load the symbols\n    try {\n      doc.get<string>( \"symbols\", this->_symbols);\n    }\n    catch( const std::exception &e) {\n      cout << \"[AttributeCommon::deserialize]\" << e.what() << endl;\n    }\n  }\n\n  // Symbol mapping of the attribute type\n  string AttributeCommon::getTypeStr() {\n    string result;\n    switch(this->_type) {\n    case CATEGORY:   result = \"category\"; break;\n    case COLOR:      result = \"color\"; break;\n    case DESCRIPTOR: result = \"descriptor\"; break;\n    case POSITION:   result = \"position\"; break;\n    case SIZE :      result = \"size\"; break;\n    default:         result = \"none\"; break;\n    }\n    return result;\n  }\n\n\n  // -------------------------------\n  // 1. Category attribute class methods\n  // --------------_--------------------\n  CategoryAttribute::CategoryAttribute( const anchor_msgs::CategoryAttribute &msg,\n\t\t\t\t\tAttributeType type ) : AttributeCommon( msg.symbols, type) {\n    this->_predictions = vector<double>( msg.predictions.begin(), msg.predictions.end() );\n    this->_n = 1.0;   // ...counter\n  }\n\n  mongo::Database::Document CategoryAttribute::serialize() {\n\n    // Save the symbol(s)\n    mongo::Database::Document doc = AttributeCommon::serialize();\n\n    // Save (category) predictions\n    try {\n      doc.add<double>( \"predictions\", this->_predictions);\n      doc.add<double>( \"n\", this->_n);  // ..including the frequency \n    }\n    catch( const std::exception &e) {\n      cout << \"[CategoryAttribute::serialize]\" << e.what() << endl;\n    }\n    return doc;\n  }\n\n  void CategoryAttribute::deserialize(const mongo::Database::Document &doc) {\n  \n    // Load (category) predictions\n    try {\n      doc.get<double>( \"predictions\", this->_predictions);\n      this->_n = (float)doc.get<double>(\"n\");  // ...including the frequency \n    }\n    catch( const std::exception &e) {\n      cout << \"[CategoryAttribute::deserialize]\" << e.what() << endl;\n    }\n\n    // Load the symbol(s) \n    AttributeCommon::deserialize(doc);\n  }\n\n  void CategoryAttribute::populate(anchor_msgs::Anchor &msg) {\n    anchor_msgs::CategoryAttribute category_msg;\n    //double max = *std::max_element( this->_predictions.begin(), this->_predictions.end());\n    for( uint i = 0; i < this->_predictions.size(); i++ ) {\n      //if( (this->_predictions[i] / max) > 0.25 ) {  // ...looking for spikes above max theshold value\n      category_msg.symbols.push_back(this->_symbols[i]);\n      category_msg.predictions.push_back((float)this->_predictions[i] / this->_n);\n      //}\n    }\n    double max = *std::max_element( this->_predictions.begin(), this->_predictions.end()) / this->_n;\n    sortAttribute( category_msg.symbols, category_msg.predictions, (max > 0.95 ? 1 : max > 0.65 ? 2 : 3 ));\n\n    /*\n    category_msg.symbols = this->_symbols;\n    auto n = this->_N.begin();\n    for( auto ite = this->_predictions.begin(); ite != this->_predictions.end(); ++ite, ++n) {\n      categoryu_msg.predictions.push_back((float)*ite / *n);\n    }\n    */\n    msg.category = category_msg;\n  }\n\n  void CategoryAttribute::populate(anchor_msgs::Display &msg) {\n    float best = 0.0;\n    int index = -1;\n    for( uint i = 0; i < this->_symbols.size(); i++ ) {\n      float prob = this->_predictions[i] / this->_n; \n      if( prob > best ) {\n\tbest = prob;\n\tindex = i;\n      }\n    }\n    if( index >= 0 ) {\n      msg.category = this->_symbols[index];\n      msg.prediction = this->_predictions[index] / this->_n;\n    }\n    \n  }\n\n  float CategoryAttribute::match(const AttributePtr &query_ptr) { \n\n    // Typecast the query attribute pointer\n    CategoryAttribute *raw_ptr = dynamic_cast<CategoryAttribute*>(query_ptr.get());\n    assert( raw_ptr != nullptr );\n\n    float result = 0.0;\n    for( uint i = 0; i < this->_symbols.size(); i++ ) {\n      for( uint j = 0; j < raw_ptr->_symbols.size(); j++ ) {\n\tif( this->_symbols[i] == raw_ptr->_symbols[j] && (this->_predictions[i] / this->_n) > 0.05 && raw_ptr->_predictions[j] > 0.05  ) {\n\t  float diff = 1.0 / \n\t    exp( abs( (this->_predictions[i] / this->_n) - raw_ptr->_predictions[j] ) /\n\t\t ( (this->_predictions[i] / this->_n) + raw_ptr->_predictions[j] ) );\n\t  if (diff > result ) {\n\t    result = diff;\n\t  }\n\t}\n      }\n    }\n    return result;\n  }\n\n  bool CategoryAttribute::update(const unique_ptr<AttributeCommon> &new_ptr) {\n    \n    // Typecast the new attribute pointer\n    CategoryAttribute *raw_ptr = dynamic_cast<CategoryAttribute*>(new_ptr.get());\n    assert( raw_ptr != nullptr );\n\n    // Increment the counter\n    this->_n = this->_n + raw_ptr->_n;\n    \n    // Summarize the predictions\n    for( uint i = 0; i < this->_symbols.size(); i++ ) {\n      for( uint j = 0; j < raw_ptr->_symbols.size(); j++ ) {\n\tif( this->_symbols[i] == raw_ptr->_symbols[j] ) {\n\t  this->_predictions[i] += raw_ptr->_predictions[j];\n\t}\n      }\n    }\n    return true;\n  }\n\n  string CategoryAttribute::toString() {\n    float best = 0.0;\n    int index = -1;\n    std::stringstream ss;\n    for( uint i = 0; i < this->_symbols.size(); i++ ) {\n      float prob = this->_predictions[i] / this->_n;\n      if( prob > best ) {\n\tbest = prob;\n\tindex = i;\n      }\n    }\n    if( index >= 0 ) {\n      ss << this->_symbols[index];\n    }\n    return ss.str();\n  }\n\n\n  // --------------------------------\n  // 2. Color attribute methods\n  // ------------------------------------  \n  ColorAttribute::ColorAttribute( const anchor_msgs::ColorAttribute &msg, \n\t\t\t\t  AttributeType type ) : AttributeCommon( msg.symbols, type) {\n    // Initilize counter\n    this->_n = 1.0;  \n    \n    // Read the data from ROS msg\n    cv_bridge::CvImagePtr cv_ptr;\n    try {\n      cv_ptr = cv_bridge::toCvCopy( msg.data,\n\t\t\t\t    sensor_msgs::image_encodings::TYPE_32FC1 );\n      cv_ptr->image.copyTo(this->_data);\n    } catch (cv_bridge::Exception& e) {\n      throw std::logic_error(\"[ColorAttribute::ColorAttribute]:\" + std::string(e.what()) );\n    }\n    this->_predictions = vector<double>( msg.predictions.begin(), msg.predictions.end() );\n  }\n\n  mongo::Database::Document ColorAttribute::serialize() {\n  \n    // Save the symbol(s)\n    mongo::Database::Document doc = AttributeCommon::serialize();\n\n    // Save the color\n    try {      \n      vector<double> array;      \n      for( int i = 0; i < this->_data.cols; i++) {\n\tarray.push_back(this->_data.at<float>( 0, i));\n      }\n      doc.add<double>( \"data\", array);\n\n      // Save the counter\n      doc.add<double>( \"n\", this->_n);\n      \n      // Save (color) predictions\n      doc.add<double>( \"predictions\", this->_predictions);\n    }\n    catch( const std::exception &e) {\n      cout << \"[ColorAttribute::serialize]\" << e.what() << endl;\n    }\n    return doc;\n  }\n\n  void ColorAttribute::deserialize(const mongo::Database::Document &doc) {\n\n    // Load the color \n    try {\n      \n      vector<double> array;\n      doc.get<double>( \"data\", array);\n      this->_data = cv::Mat( 1, array.size(), CV_32FC1);\n      for( int i = 0; i < array.size(); i++) {\n\tthis->_data.at<float>( 0, i) = (float)array[i];\n      } \n      \n      // Load the counter\n      this->_n = (float)doc.get<double>(\"n\");\n      \n      // Load (color) predictions\n      doc.get<double>( \"predictions\", this->_predictions);\n    }\n    catch( const std::exception &e) {\n      cout << \"[ColorAttribute::deserialize]\" << e.what() << endl;\n    }\n\n    // Load the symbol(s) \n    AttributeCommon::deserialize(doc);\n  }\n\n  void ColorAttribute::populate(anchor_msgs::Anchor &msg) {\n    anchor_msgs::ColorAttribute color_msg;\n    double max = *std::max_element( this->_predictions.begin(), this->_predictions.end());\n    for( uint i = 0; i < this->_predictions.size(); i++ ) {\n      if( (this->_predictions[i] / max) > CONST_MAX_TH ) {  // ...looking for spikes above max theshold value \n\tcolor_msg.symbols.push_back(this->_symbols[i]);\n\tcolor_msg.predictions.push_back((float)this->_predictions[i] / this->_n);\t\n      }\n    }\n    sortAttribute( color_msg.symbols, color_msg.predictions, 5);\n    msg.color = color_msg;\n  }\n  void ColorAttribute::populate(anchor_msgs::Display &msg) {\n    double max = *std::max_element( this->_predictions.begin(), this->_predictions.end());\n    for( uint i = 0; i < this->_predictions.size(); i++ ) {\n      if( (this->_predictions[i] / max) > CONST_MAX_TH ) {  // ...looking for spikes above max theshold value \n\tmsg.colors.push_back(this->_symbols[i]);\n      }\n    }\n    // msg.colors = this->_symbols;\n  }\n  \n  float ColorAttribute::match(const AttributePtr &query_ptr) {\n    \n    // Typecast the query attribute pointer\n    ColorAttribute *raw_ptr = dynamic_cast<ColorAttribute*>(query_ptr.get());\n    assert( raw_ptr != nullptr );\n\n    float dist = (1.0 + cv::compareHist( raw_ptr->_data, (this->_data / this->_n), CV_COMP_CORREL)) / 2.0; // CV_COMP_CORREL | CV_COMP_INTERSECT | CV_COMP_BHATTACHARYYA\n    //std::cout << \"Color dist: \" << dist << std::endl;\n    return dist;\n  }\n\n  bool ColorAttribute::update(const AttributePtr &new_ptr) {\n\n    // Typecast the new attribute pointer\n    ColorAttribute *raw_ptr = dynamic_cast<ColorAttribute*>(new_ptr.get());\n    assert( raw_ptr != nullptr );\n\n    // Summarize histograms\n    this->_data = this->_data + raw_ptr->_data;\n    \n    // Increment the counter\n    this->_n = this->_n + raw_ptr->_n;\n\n    // Summarize the predictions\n    for( uint i = 0; i < this->_predictions.size(); i++ ) {\n      this->_predictions[i] += raw_ptr->_predictions[i];\n    }\n\n    return true;\n  }\n\n  string ColorAttribute::toString() {\n    std::stringstream ss;\n    ss << \"[ \";\n    for( size_t i = 0; i < _symbols.size(); i++ ) {\n      ss << _symbols[i];\n      if( i + 1 < _symbols.size() ) {\n\tss << \", \";\n      }\n    }\n    ss << \"]\";\n    return ss.str();\n  }\n\n\n  // ------------------------------------\n  // 3. Descriptor attribute methods\n  // --------------------------------------------\n  DescriptorAttribute::DescriptorAttribute( const anchor_msgs::DescriptorAttribute &msg, \n\t\t\t\t\t    AttributeType type ) : AttributeCommon( msg.symbols, type) {\n    // Read the data from ROS msg\n    cv_bridge::CvImagePtr cv_ptr;\n    try {\n      cv_ptr = cv_bridge::toCvCopy( msg.data, \n\t\t\t\t    sensor_msgs::image_encodings::MONO8 );\n      // (Deep) copy of the data\n      cv_ptr->image.copyTo(this->_data);\n    } catch (cv_bridge::Exception& e) {\n      throw std::logic_error(\"[DescriptorAttribute::DescriptorAttribute]:\" + std::string(e.what()) );\n    }\n  }\n\n  mongo::Database::Document DescriptorAttribute::serialize() {\n\n    // Save the symbol(s)\n    mongo::Database::Document doc = AttributeCommon::serialize();\n  \n    // Save the descriptor\n    try {\n      doc.add<int>( \"rows\", (int)this->_data.rows);\n      doc.add<int>( \"cols\", (int)this->_data.cols);\n\n      std::size_t length = this->_data.rows * this->_data.cols;\n      if( length > 0 ) {\n\tdoc.add<unsigned char*>( \"data\", this->_data.data, length);\n      }\n    }\n    catch( const std::exception &e) {\n      cout << \"[DescriptorAttribute::serialize]\" << e.what() << endl;\n    }\n    return doc;\n  }\n\n  void DescriptorAttribute::deserialize(const mongo::Database::Document &doc) {\n\n    // Load the descriptor\n    try {\n      int rows = doc.get<int>( \"rows\");\n      int cols = doc.get<int>( \"cols\");\n      if( rows > 0 ) {\n\tunsigned char* array = doc.get<unsigned char*>( \"data\");\n\tthis->_data = cv::Mat( rows, cols, CV_8U, array);\n      }\n    }\n    catch( const std::exception &e) {\n      cout << \"[DescriptorAttribute::deserialize]\" << e.what() << endl;\n    }\n\n    // Load the symbol(s) \n    AttributeCommon::deserialize(doc);\n  }\n\n\n  // ----------------------------------\n  // 4. Position attribute methods\n  // ---------------------------------------\n  PositionAttribute::PositionAttribute( const anchor_msgs::PositionAttribute &msg,\n\t\t\t\t\tAttributeType type ) : AttributeCommon( msg.symbols, type) {\n    // Add the data (including a timestamp)\n    this->_array.push_back(msg.data);\n  }\n\n\n  PositionAttribute::PositionAttribute( const vector<geometry_msgs::PoseStamped> &array, \n\t\t\t\t\tconst vector<string> &symbols,\n\t\t\t\t\tAttributeType type ) : AttributeCommon( symbols, type) {\n      // Add the data (including a timestamp)\n    for( auto &pos : array ) {\n      this->_array.push_back(pos);\n    }\n  }\n\n  \n  PositionAttribute::PositionAttribute( const AttributePtr &ptr,\n\t\t\t\t\tAttributeType type) : AttributeCommon(type) {\n\n    // Typecast the query pointer\n    PositionAttribute *raw_ptr = dynamic_cast<PositionAttribute*>(ptr.get());\n    assert( raw_ptr != nullptr );\n\n    // Add the data (including a timestamp)\n    for( auto &pos : raw_ptr->_array ) {\n      this->_array.push_back(pos);\n    }\n  }\n\n  mongo::Database::Document PositionAttribute::serialize() {\n\n    // Save the symbol(s)\n    mongo::Database::Document doc = AttributeCommon::serialize();\n    \n    // Save the location\n    try {\n      \n      vector<geometry_msgs::PoseStamped>::iterator ite_d = this->_array.begin();\n      for( ; ite_d != this->_array.end(); ++ite_d ) {  \n\n\tmongo::Database::Document subdoc;\n\n\t// Add time\n\tsubdoc.add<double>( \"t\", ite_d->header.stamp.toSec());\n\n\t// Add position\n\tmongo::Database::Document position;\n\tposition.add<double>( \"x\", ite_d->pose.position.x);\n\tposition.add<double>( \"y\", ite_d->pose.position.y);\n\tposition.add<double>( \"z\", ite_d->pose.position.z);\n\tsubdoc.add( \"position\", position);\n\n\t// Add orientation\n\tmongo::Database::Document orientation;\n\torientation.add<double>( \"x\", ite_d->pose.orientation.x);\n\torientation.add<double>( \"y\", ite_d->pose.orientation.y);\n\torientation.add<double>( \"z\", ite_d->pose.orientation.z);\n\torientation.add<double>( \"w\", ite_d->pose.orientation.w);\n\tsubdoc.add( \"orientation\", orientation);\n\n\tdoc.append( \"array\", subdoc);\n      }\n    }\n    catch( const std::exception &e) {\n      cout << \"[PositionAttribute::serialize]\" << e.what() << endl;\n    }\n    return doc;\n  }\n\n  void PositionAttribute::deserialize(const mongo::Database::Document &doc) {\n    \n    // Load the positions\n    try {\n      \n      // Read a series of position data\n      for( mongo::document_iterator ite = doc.begin(\"array\"); ite != doc.end(\"array\"); ++ite) {\n\tgeometry_msgs::PoseStamped data;\n\n\t// Read the time\n\tdata.header.stamp = ros::Time(ite->get<double>(\"t\"));\t\n\t\n\t// Read position\n\tmongo::Database::Document position = ite->get(\"position\");\n\tdata.pose.position.x = position.get<double>(\"x\");\n\tdata.pose.position.y = position.get<double>(\"y\");\n\tdata.pose.position.z = position.get<double>(\"z\");\n\n\t// Read orientation\n\tmongo::Database::Document orientation = ite->get(\"orientation\");\n\tdata.pose.orientation.x = orientation.get<double>(\"x\");\n\tdata.pose.orientation.y = orientation.get<double>(\"y\");\n\tdata.pose.orientation.z = orientation.get<double>(\"z\");\n\tdata.pose.orientation.w = orientation.get<double>(\"w\");\n\t\n\tthis->_array.push_back(data);\n      }\n    }\n    catch( const std::exception &e) {\n      cout << \"[PositionAttribute::deserialize]\" << e.what() << endl;\n    }\n\n    // Load the symbol(s) \n    AttributeCommon::deserialize(doc);\n  }\n\n  // Overleaded functions for populating ROS messages\n  void PositionAttribute::populate(anchor_msgs::Anchor &msg) {\n    //anchor_msgs::PositionAttribute poistion;\n    if( !this->_array.empty() ) {\n      for( const auto &pos : this->_array ) {\n        msg.position.data.pose.position.x += pos.pose.position.x;\n        msg.position.data.pose.position.y += pos.pose.position.y;\n        msg.position.data.pose.position.z += pos.pose.position.z;\n        msg.position.data.pose.orientation.x += pos.pose.orientation.x;\n        msg.position.data.pose.orientation.y += pos.pose.orientation.y;\n        msg.position.data.pose.orientation.z += pos.pose.orientation.z;\n        msg.position.data.pose.orientation.w += pos.pose.orientation.w;\n      }\n      msg.position.data.pose.position.x /= (int)this->_array.size();\n      msg.position.data.pose.position.y /= (int)this->_array.size();\n      msg.position.data.pose.position.z /= (int)this->_array.size();\n      msg.position.data.pose.orientation.x /= (int)this->_array.size();\n      msg.position.data.pose.orientation.y /= (int)this->_array.size();\n      msg.position.data.pose.orientation.z /= (int)this->_array.size();\n      msg.position.data.pose.orientation.w /= (int)this->_array.size();\n    }\n    //msg.position = poistion;\n  }\n  void PositionAttribute::populate(anchor_msgs::Display &msg) {\n    if( !this->_array.empty() ) {\n      for( const auto &pos : this->_array ) {\n\tmsg.pos.pose.position.x += pos.pose.position.x;\n\tmsg.pos.pose.position.y += pos.pose.position.y;\n\tmsg.pos.pose.position.z += pos.pose.position.z;\n      }\n      msg.pos.pose.position.x /= (int)this->_array.size();\n      msg.pos.pose.position.y /= (int)this->_array.size();\n      msg.pos.pose.position.z /= (int)this->_array.size();\n    }\n  }\n  \n  float PositionAttribute::match(const AttributePtr &query_ptr) {\n\n    // Typecast the query attribute pointer\n    PositionAttribute *raw_ptr = dynamic_cast<PositionAttribute*>(query_ptr.get());\n    assert( raw_ptr != nullptr );\n\n    // The normalized L2 distance\n    double _x, _y, _z, _d, _dist = -1.0;\n    for( uint i = 0; i < this->_array.size(); i++ ) {\n      geometry_msgs::PoseStamped train = this->_array[i];\n      for( uint j = 0; j < raw_ptr->_array.size(); j++ ) {      \n\tgeometry_msgs::PoseStamped query = raw_ptr->_array[j];\n\t_x = query.pose.position.x - train.pose.position.x;\n\t_y = query.pose.position.y - train.pose.position.y;\n\t_z = query.pose.position.z - train.pose.position.z;\n\t_d  = sqrt( _x*_x + _y*_y + _z*_z );\n\tif( _dist < 0.0 || _d < _dist ) {\n\t  _dist = _d;\n\t}\n      }\n    }\n    if( _dist >= 0.0 ) {\n      return 1.0 / exp(_dist);\n    }\n    return 0.0;\n  }\n\n  bool PositionAttribute::update(const unique_ptr<AttributeCommon> &new_ptr) {\n    \n    // Typecast the new attribute pointer\n    PositionAttribute *raw_ptr = dynamic_cast<PositionAttribute*>(new_ptr.get());\n    assert( raw_ptr != nullptr );\n\n    // Update the location\n    this->_array.clear();\n    for( auto &pos : raw_ptr->_array ) {\n      this->_array.push_back(pos);\n    }\n\n    /*\n    // Update the location\n    if( this->match(new_ptr) < 0.01 ) { // ...not moved more than 1cm\n      this->_array.back().header.stamp = raw_ptr->_array.back().header.stamp;\n      // this->_array.back() = raw_ptr->_array.front();\n      }\n    else {\n      // Append the location (including a timestamp)\n      this->_array.push_back(raw_ptr->_array.back());\n    }\n    */\n    \n    /*\n    // Append the symbol (if there exists an symbol)\n    if( !raw_ptr->_symbols.empty() ) {\n      this->_symbols.back() = raw_ptr->_symbols.front();\n      this->_symbols.push_back(raw_ptr->_symbols.front());\n    }  \n    */\n\n    return true;\n  }\n\n  string PositionAttribute::toString() {\n    std::stringstream ss;\n    ss << \"@ {\";\n    ss << \" x = \" << this->_array.back().pose.position.x;\n    ss << \", y = \" << this->_array.back().pose.position.y;\n    ss << \", z = \" << this->_array.back().pose.position.z;\n    ss << \"}\";\n    return ss.str();\n  }\n\n  \n  // --------------------------------\n  // 5. Size attribute class methods\n  // -------------------------------------\n  SizeAttribute::SizeAttribute( const anchor_msgs::SizeAttribute &msg,\n\t\t\t\tAttributeType type ) : AttributeCommon( msg.symbols, type) {\n    this->_data = msg.data;\n  }\n\n  mongo::Database::Document SizeAttribute::serialize() {\n  \n    // Save the symbol(s)\n    mongo::Database::Document doc = AttributeCommon::serialize();\n\n    // Save the shape\n    try {\n      std::vector<double> size;\n      size.push_back(this->_data.x);\n      size.push_back(this->_data.y);\n      size.push_back(this->_data.z);\n      doc.add<double>( \"data\", size);\n    }\n    catch( const std::exception &e) {\n      cout << \"[SizeAttribute::serialize]\" << e.what() << endl;\n    }\n    return doc;\n  }\n\n  void SizeAttribute::deserialize(const mongo::Database::Document &doc) {\n\n    // Load the shape\n    try {\n      vector<double> size;\n      doc.get<double>( \"data\", size);\n      this->_data.x = size[0];\n      this->_data.y = size[1];\n      this->_data.z = size[2];\n    }\n    catch( const std::exception &e) {\n      cout << \"[SizeAttribute::deserialize]\" << e.what() << endl;\n    }\n\n    // Load the symbol(s) \n    AttributeCommon::deserialize(doc);\n  }\n\n  void SizeAttribute::populate(anchor_msgs::Anchor &msg) {\n    anchor_msgs::SizeAttribute size_msg;\n    size_msg.data = this->_data;\n    size_msg.symbols = this->_symbols;\n    msg.size = size_msg;\n  }\n  void SizeAttribute::populate(anchor_msgs::Display &msg) {\n    msg.size = _symbols[0];\n  }\n\n  float SizeAttribute::match(const AttributePtr &query_ptr) {\n\n    // Typecast the query attribute pointer\n    SizeAttribute *raw_ptr = dynamic_cast<SizeAttribute*>(query_ptr.get());\n    assert( raw_ptr != nullptr );\n\n    // Jaccard similarity coefficient\n    float min = 0.0, max = 0.0;\n    min += raw_ptr->_data.x < _data.x ? raw_ptr->_data.x : _data.x;\n    min += raw_ptr->_data.y < _data.y ? raw_ptr->_data.y : _data.y;\n    min += raw_ptr->_data.z < _data.z ? raw_ptr->_data.z : _data.z;\n    max += raw_ptr->_data.x > _data.x ? raw_ptr->_data.x : _data.x;\n    max += raw_ptr->_data.y > _data.y ? raw_ptr->_data.y : _data.y;\n    max += raw_ptr->_data.z > _data.z ? raw_ptr->_data.z : _data.z;\n    if( max > 0.0 ) {\n      return min / max;\n    }\n    return 0.0;\n  }\n  \n  bool SizeAttribute::update(const unique_ptr<AttributeCommon> &new_ptr) {\n\n    // Typecast the new atribute pointer\n    SizeAttribute* raw_ptr = dynamic_cast<SizeAttribute*>(new_ptr.get());\n    assert( raw_ptr != nullptr );\n\n    this->_data = raw_ptr->_data;\n  }\n  \n  string SizeAttribute::toString() {\n    return _symbols[0];\n  }\n  \n  \n} // namespace anchoring\n", "meta": {"hexsha": "8168ba89202fe8e4db529024d786f2051217f4e3", "size": 23884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anchoring/src/attribute.cpp", "max_stars_repo_name": "probabilistic-anchoring/probanch", "max_stars_repo_head_hexsha": "cfba24fd431ed7e7109b715018e344d7989f565d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-27T14:00:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-27T14:00:27.000Z", "max_issues_repo_path": "anchoring/src/attribute.cpp", "max_issues_repo_name": "probabilistic-anchoring/probanch", "max_issues_repo_head_hexsha": "cfba24fd431ed7e7109b715018e344d7989f565d", "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": "anchoring/src/attribute.cpp", "max_forks_repo_name": "probabilistic-anchoring/probanch", "max_forks_repo_head_hexsha": "cfba24fd431ed7e7109b715018e344d7989f565d", "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.0160857909, "max_line_length": 168, "alphanum_fraction": 0.6097806063, "num_tokens": 6070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "/*\n\tCopyright (C) 2003-2013 by David White <davewx7@gmail.com>\n\t\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, see <http://www.gnu.org/licenses/>.\n*/\n#include <iostream>\n#include <deque>\n#include <boost/cstdint.hpp>\n#include <math.h>\n#include <algorithm>\n\n#include \"graphics.hpp\"\n#include \"asserts.hpp\"\n#include \"color_utils.hpp\"\n#include \"entity.hpp\"\n#include \"foreach.hpp\"\n#include \"formula.hpp\"\n#include \"frame.hpp\"\n#include \"particle_system.hpp\"\n#include \"preferences.hpp\"\n#include \"string_utils.hpp\"\n#include \"texture.hpp\"\n#include \"variant_utils.hpp\"\n#include \"weather_particle_system.hpp\"\n#include \"water_particle_system.hpp\"\n#include \"raster.hpp\"\n\nnamespace {\n\nclass particle_animation {\npublic:\n\texplicit particle_animation(variant node) :\n\t  id_(node[\"id\"].as_string()),\n\t  texture_(graphics::texture::get(node[\"image\"].as_string())),\n\t  duration_(node[\"duration\"].as_int()),\n\t  reverse_frame_(node[\"reverse\"].as_bool()),\n\t  loops_(node[\"loops\"].as_bool(false))\n\t{\n\t\trect base_area(node.has_key(\"rect\") ? rect(node[\"rect\"]) :\n\t           rect(node[\"x\"].as_int(),\n\t                node[\"y\"].as_int(),\n\t                node[\"w\"].as_int(),\n\t                node[\"h\"].as_int()));\n\t\twidth_  = base_area.w()*node[\"scale\"].as_int(2);\n\t\theight_ = base_area.h()*node[\"scale\"].as_int(2);\n\t\tint nframes = node[\"frames\"].as_int(1);\n\t\tif(nframes < 1) {\n\t\t\tnframes = 1;\n\t\t}\n\n\t\tconst int nframes_per_row = node[\"frames_per_row\"].as_int(-1);\n\t\tconst int pad = node[\"pad\"].as_int();\n\n\t\tframe frame_obj(node);\n\n\t\tint row = 0, col = 0;\n\t\tfor(int n = 0; n != nframes; ++n) {\n\t\t\tconst frame::frame_info& info = frame_obj.frame_layout()[n];\n\t\t\tconst rect& area = info.area;\n\n\t\t\tframe_area a;\n\t\t\ta.u1 = GLfloat(area.x())/GLfloat(texture_.width());\n\t\t\ta.u2 = GLfloat(area.x2())/GLfloat(texture_.width());\n\t\t\ta.v1 = GLfloat(area.y())/GLfloat(texture_.height());\n\t\t\ta.v2 = GLfloat(area.y2())/GLfloat(texture_.height());\n\n\t\t\ta.x_adjust = info.x_adjust*2;\n\t\t\ta.y_adjust = info.y_adjust*2;\n\t\t\ta.x2_adjust = info.x2_adjust*2;\n\t\t\ta.y2_adjust = info.y2_adjust*2;\n\n\t\t\tframes_.push_back(a);\n\n\t\t\t++col;\n\t\t\tif(col == nframes_per_row) {\n\t\t\t\tcol = 0;\n\t\t\t\t++row;\n\t\t\t}\n\t\t}\n\t}\n\n\tstruct frame_area {\n\t\tGLfloat u1, v1, u2, v2;\n\t\tint x_adjust, y_adjust, x2_adjust, y2_adjust;\n\t};\n\n\tconst frame_area& get_frame(int t) const {\n\t\tint index = t/duration_;\n\t\tif(index < 0) {\n\t\t\tindex = 0;\n\t\t} else if(index >= frames_.size()) {\n\t\t\tif(loops_ && !reverse_frame_) {\n\t\t\t\tindex = index%frames_.size();\n\t\t\t} else if (loops_ && reverse_frame_){\n\t\t\t\tindex = (running_in_reverse(index)? frames_.size()- 1 - index%frames_.size(): index%frames_.size());\n\t\t\t} else {\n\t\t\t\tindex = frames_.size() - 1;\n\t\t\t}\n\t\t}\n\n\t\treturn frames_[index];\n\t}\n\tbool running_in_reverse(int current_frame) const\n\t{\n\t\treturn current_frame % (2* frames_.size()) >= frames_.size();\n\t}\n\t\n\t\n\tvoid set_texture() const {\n\t\ttexture_.set_as_current_texture();\n\t}\n\n\tint width() const { return width_; }\n\tint height() const { return height_; }\nprivate:\n\tstd::string id_;\n\tgraphics::texture texture_;\n\n\tstd::vector<frame_area> frames_;\n\tint duration_;\n\tint reverse_frame_;\n\tint width_, height_;\n\tbool loops_;\n};\n\nstruct simple_particle_system_info {\n\tsimple_particle_system_info(variant node)\n\t  : spawn_rate_(node[\"spawn_rate\"].as_int(1)),\n\t    spawn_rate_random_(node[\"spawn_rate_random\"].as_int()),\n\t    system_time_to_live_(node[\"system_time_to_live\"].as_int(-1)),\n\t    time_to_live_(node[\"time_to_live\"].as_int(50)),\n\t    min_x_(node[\"min_x\"].as_int(0)),\n\t    max_x_(node[\"max_x\"].as_int(0)),\n\t    min_y_(node[\"min_y\"].as_int(0)),\n\t    max_y_(node[\"max_y\"].as_int(0)),\n\t\tvelocity_x_(node[\"velocity_x\"].as_int(0)),\n\t\tvelocity_y_(node[\"velocity_y\"].as_int(0)),\n\t\tvelocity_x_rand_(node[\"velocity_x_random\"].as_int(0)),\n\t\tvelocity_y_rand_(node[\"velocity_y_random\"].as_int(0)),\n\t\tvelocity_magnitude_(node[\"velocity_magnitude\"].as_int(0)),\n\t\tvelocity_magnitude_rand_(node[\"velocity_magnitude_random\"].as_int(0)),\n\t\tvelocity_rotate_(node[\"velocity_rotate\"].as_int(0)),\n\t\tvelocity_rotate_rand_(node[\"velocity_rotate_random\"].as_int(0)),\n\t\taccel_x_(node[\"accel_x\"].as_int(0)),\n\t\taccel_y_(node[\"accel_y\"].as_int(0)),\n\t\tpre_pump_cycles_(node[\"pre_pump_cycles\"].as_int(0)),\n\t\tdelta_r_(node[\"delta_r\"].as_int(0)),\n\t\tdelta_g_(node[\"delta_g\"].as_int(0)),\n\t\tdelta_b_(node[\"delta_b\"].as_int(0)),\n\t\tdelta_a_(node[\"delta_a\"].as_int(0)),\n\t\trandom_schedule_(false)\n\n\t{\n\t\tif(node.has_key(\"velocity_x_schedule\")) {\n\t\t\tvelocity_x_schedule_ = node[\"velocity_x_schedule\"].as_list_int();\n\t\t}\n\n\t\tif(node.has_key(\"velocity_y_schedule\")) {\n\t\t\tvelocity_y_schedule_ = node[\"velocity_y_schedule\"].as_list_int();\n\t\t}\n\n\t\trandom_schedule_ = node[\"random_schedule\"].as_bool(velocity_x_schedule_.empty() == false || velocity_y_schedule_.empty() == false);\n\t}\n\tint spawn_rate_, spawn_rate_random_;\n\tint system_time_to_live_;\n\tint time_to_live_;\n\tint min_x_, max_x_, min_y_, max_y_;\n\tint velocity_x_, velocity_y_;\n\tint velocity_x_rand_, velocity_y_rand_;\n\tint velocity_magnitude_, velocity_magnitude_rand_;\n\tint velocity_rotate_, velocity_rotate_rand_;\n\tint accel_x_, accel_y_;\n\t\n\tint pre_pump_cycles_;  //# of cycles to pre-emptively simulate so the particle system appears to have been running for a while, rather than visibly starting to emit particles just when the player walks onscreen\n\n\tint delta_r_, delta_g_, delta_b_, delta_a_;\n\n\tstd::vector<int> velocity_x_schedule_, velocity_y_schedule_;\n\n\tbool random_schedule_;\n};\n\nclass simple_particle_system_factory : public particle_system_factory {\npublic:\n\texplicit simple_particle_system_factory(variant node);\n\t~simple_particle_system_factory() {}\n\n\tparticle_system_ptr create(const entity& e) const;\n\n\tstd::vector<particle_animation> frames_;\n\n\tsimple_particle_system_info info_;\n};\n\nsimple_particle_system_factory::simple_particle_system_factory(variant node)\n  : info_(node)\n{\n\tforeach(variant frame_node, node[\"animation\"].as_list()) {\n\t\tframes_.push_back(particle_animation(frame_node));\n\t}\n}\n\nclass simple_particle_system : public particle_system\n{\npublic:\n\tsimple_particle_system(const entity& e, const simple_particle_system_factory& factory);\n\t~simple_particle_system() {}\n\n\tbool is_destroyed() const { return info_.system_time_to_live_ == 0 || info_.spawn_rate_ < 0 && particles_.empty(); }\n\tbool should_save() const { return info_.spawn_rate_ >= 0; }\n\tvoid process(const entity& e);\n\tvoid draw(const rect& area, const entity& e) const;\n\nprivate:\n\tvoid prepump(const entity& e);\n\n\tvariant get_value(const std::string& key) const {\n\t\tif(key == \"spawn_rate\") {\n\t\t\treturn variant(info_.spawn_rate_);\n\t\t} else if(key == \"spawn_rate_random\") {\n\t\t\treturn variant(info_.spawn_rate_random_);\n\t\t} else if(key == \"system_time_to_live\") {\n\t\t\treturn variant(info_.system_time_to_live_);\n\t\t} else if(key == \"time_to_live\") {\n\t\t\treturn variant(info_.time_to_live_);\n\t\t} else if(key == \"min_x\") {\n\t\t\treturn variant(info_.min_x_);\n\t\t} else if(key == \"max_x\") {\n\t\t\treturn variant(info_.max_x_);\n\t\t} else if(key == \"min_y\") {\n\t\t\treturn variant(info_.min_y_);\n\t\t} else if(key == \"max_y\") {\n\t\t\treturn variant(info_.max_y_);\n\t\t} else if(key == \"velocity_x\") {\n\t\t\treturn variant(info_.velocity_x_);\n\t\t} else if(key == \"velocity_y\") {\n\t\t\treturn variant(info_.velocity_y_);\n\t\t} else if(key == \"velocity_x_random\") {\n\t\t\treturn variant(info_.velocity_x_rand_);\n\t\t} else if(key == \"velocity_y_random\") {\n\t\t\treturn variant(info_.velocity_y_rand_);\n\t\t} else if(key == \"velocity_magnitude\") {\n\t\t\treturn variant(info_.velocity_magnitude_);\n\t\t} else if(key == \"velocity_magnitude_random\") {\n\t\t\treturn variant(info_.velocity_magnitude_rand_);\n\t\t} else if(key == \"velocity_rotate\") {\n\t\t\treturn variant(info_.velocity_rotate_);\n\t\t} else if(key == \"velocity_rotate_random\") {\n\t\t\treturn variant(info_.velocity_rotate_rand_);\n\t\t} else if(key == \"velocity_rotate\") {\n\t\t\treturn variant(info_.velocity_rotate_);\n\t\t} else if(key == \"velocity_rotate_random\") {\n\t\t\treturn variant(info_.velocity_rotate_rand_);\n\t\t} else if(key == \"accel_x\") {\n\t\t\treturn variant(info_.accel_x_);\n\t\t} else if(key == \"accel_y\") {\n\t\t\treturn variant(info_.accel_y_);\n\t\t} else if(key == \"pre_pump_cycles\") {\n\t\t\treturn variant(info_.pre_pump_cycles_);\n\t\t} else if(key == \"delta_r\") {\n\t\t\treturn variant(info_.delta_r_);\n\t\t} else if(key == \"delta_g\") {\n\t\t\treturn variant(info_.delta_g_);\n\t\t} else if(key == \"delta_b\") {\n\t\t\treturn variant(info_.delta_b_);\n\t\t} else if(key == \"delta_a\") {\n\t\t\treturn variant(info_.delta_a_);\n\t\t} else {\n\t\t\treturn variant();\n\t\t}\n\t}\n\n\tvoid set_value(const std::string& key, const variant& value) {\n\t\tif(key == \"spawn_rate\") {\n\t\t\tinfo_.spawn_rate_ = value.as_int();\n\t\t} else if(key == \"spawn_rate_random\") {\n\t\t\tinfo_.spawn_rate_random_ = value.as_int();\n\t\t} else if(key == \"system_time_to_live\") {\n\t\t\tinfo_.system_time_to_live_ = value.as_int();\n\t\t} else if(key == \"time_to_live\") {\n\t\t\tinfo_.time_to_live_ = value.as_int();\n\t\t} else if(key == \"min_x\") {\n\t\t\tinfo_.min_x_ = value.as_int();\n\t\t} else if(key == \"max_x\") {\n\t\t\tinfo_.max_x_ = value.as_int();\n\t\t} else if(key == \"min_y\") {\n\t\t\tinfo_.min_y_ = value.as_int();\n\t\t} else if(key == \"max_y\") {\n\t\t\tinfo_.max_y_ = value.as_int();\n\t\t} else if(key == \"velocity_x\") {\n\t\t\tinfo_.velocity_x_ = value.as_int();\n\t\t} else if(key == \"velocity_y\") {\n\t\t\tinfo_.velocity_y_ = value.as_int();\n\t\t} else if(key == \"velocity_x_random\") {\n\t\t\tinfo_.velocity_x_rand_ = value.as_int();\n\t\t} else if(key == \"velocity_y_random\") {\n\t\t\tinfo_.velocity_y_rand_ = value.as_int();\n\t\t} else if(key == \"velocity_magnitude\") {\n\t\t\tinfo_.velocity_magnitude_ = value.as_int();\n\t\t} else if(key == \"velocity_magnitude_random\") {\n\t\t\tinfo_.velocity_magnitude_rand_ = value.as_int();\n\t\t} else if(key == \"velocity_rotate\") {\n\t\t\tinfo_.velocity_rotate_ = value.as_int();\n\t\t} else if(key == \"velocity_rotate_random\") {\n\t\t\tinfo_.velocity_rotate_rand_ = value.as_int();\n\t\t} else if(key == \"velocity_rotate\") {\n\t\t\tinfo_.velocity_rotate_ = value.as_int();\n\t\t} else if(key == \"velocity_rotate_random\") {\n\t\t\tinfo_.velocity_rotate_rand_ = value.as_int();\n\t\t} else if(key == \"accel_x\") {\n\t\t\tinfo_.accel_x_ = value.as_int();\n\t\t} else if(key == \"accel_y\") {\n\t\t\tinfo_.accel_y_ = value.as_int();\n\t\t} else if(key == \"pre_pump_cycles\") {\n\t\t\tinfo_.pre_pump_cycles_ = value.as_int();\n\t\t} else if(key == \"delta_r\") {\n\t\t\tinfo_.delta_r_ = value.as_int();\n\t\t} else if(key == \"delta_g\") {\n\t\t\tinfo_.delta_g_ = value.as_int();\n\t\t} else if(key == \"delta_b\") {\n\t\t\tinfo_.delta_b_ = value.as_int();\n\t\t} else if(key == \"delta_a\") {\n\t\t\tinfo_.delta_a_ = value.as_int();\n\t\t}\n\t\t\n\t}\n\n\tconst simple_particle_system_factory& factory_;\n\tsimple_particle_system_info info_;\n\n\tint cycle_;\n\n\tstruct particle {\n\t\tGLfloat pos[2];\n\t\tGLfloat velocity[2];\n\t\tconst particle_animation* anim;\n\t\tint random;\n\t};\n\n\tstruct generation {\n\t\tint members;\n\t\tint created_at;\n\t};\n\n\tstd::deque<particle> particles_;\n\tstd::deque<generation> generations_;\n\n\tint spawn_buildup_;\n};\n\nsimple_particle_system::simple_particle_system(const entity& e, const simple_particle_system_factory& factory)\n  : factory_(factory), info_(factory.info_), cycle_(0), spawn_buildup_(0)\n{\n}\n\nvoid simple_particle_system::prepump(const entity& e)\n{\n\t//cosmetic thing for very slow-moving particles:\n\t//it looks weird when you walk into a scene, with, say, a column of smoke that's presumably been rising for quite some time,\n\t//but it only begins rising the moment you arrive.  To overcome this, we can optionally have particle systems pre-simulate their particles\n\t//for the short period of time (often as low as 4 seconds) needed to eliminate that implementation artifact\n\tfor( int i = 0; i < info_.pre_pump_cycles_; ++i)\n\t{\n\t\tprocess(e);\n\t}\n\t\n}\n\nvoid simple_particle_system::process(const entity& e)\n{\n\t--info_.system_time_to_live_;\n\t++cycle_;\n\n\tif(cycle_ == 1) {\n\t\tprepump(e);\n\t}\n\n\twhile(!generations_.empty() && cycle_ - generations_.front().created_at == info_.time_to_live_) {\n\t\tparticles_.erase(particles_.begin(), particles_.begin() + generations_.front().members);\n\t\tgenerations_.pop_front();\n\t}\n\n\tstd::deque<particle>::iterator p = particles_.begin();\n\tforeach(generation& gen, generations_) {\n\t\tfor(int n = 0; n != gen.members; ++n) {\n\t\t\tp->pos[0] += p->velocity[0];\n\t\t\tp->pos[1] += p->velocity[1];\n\t\t\tif(e.face_right()) {\n\t\t\t\tp->velocity[0] += info_.accel_x_/1000.0;\n\t\t\t} else {\n\t\t\t\tp->velocity[0] -= info_.accel_x_/1000.0;\n\t\t\t}\n\t\t\tp->velocity[1] += info_.accel_y_/1000.0;\n\t\t\t++p;\n\t\t}\n\t}\n\n\tif(info_.velocity_x_schedule_.empty() == false) {\n\t\tstd::deque<particle>::iterator p = particles_.begin();\n\t\tforeach(generation& gen, generations_) {\n\n\t\t\tfor(int n = 0; n != gen.members; ++n) {\n\t\t\t\tconst int ncycle = p->random + cycle_ - gen.created_at - 1;\n\t\t\t\tp->velocity[0] += info_.velocity_x_schedule_[ncycle%info_.velocity_x_schedule_.size()];\n\t\t\t\tif(cycle_ - gen.created_at > 1) {\n\t\t\t\t\tp->velocity[0] -= info_.velocity_x_schedule_[(ncycle-1)%info_.velocity_x_schedule_.size()];\n\t\t\t\t}\n\n\t\t\t\t++p;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(info_.velocity_y_schedule_.empty() == false) {\n\t\tstd::deque<particle>::iterator p = particles_.begin();\n\t\tforeach(generation& gen, generations_) {\n\t\t\tfor(int n = 0; n != gen.members; ++n) {\n\t\t\t\tconst int ncycle = p->random + cycle_ - gen.created_at - 1;\n\t\t\t\tp->velocity[1] += info_.velocity_y_schedule_[ncycle%info_.velocity_y_schedule_.size()];\n\t\t\t\tif(cycle_ - gen.created_at > 1) {\n\t\t\t\t\tp->velocity[1] -= info_.velocity_y_schedule_[(ncycle-1)%info_.velocity_y_schedule_.size()];\n\t\t\t\t}\n\n\t\t\t\t++p;\n\t\t\t}\n\t\t}\n\t}\n\n\tint nspawn = info_.spawn_rate_;\n\tif(info_.spawn_rate_random_ > 0) {\n\t\tnspawn += rand()%info_.spawn_rate_random_;\n\t}\n\n\tif(nspawn > 0) {\n\t\tnspawn += spawn_buildup_;\n\t}\n\n\tspawn_buildup_ = nspawn%1000;\n\tnspawn /= 1000;\n\n\tif(nspawn == 0) {\n\t\treturn;\n\t}\n\n\tgeneration new_gen;\n\tnew_gen.members = nspawn;\n\tnew_gen.created_at = cycle_;\n\n\tgenerations_.push_back(new_gen);\n\n\twhile(nspawn-- > 0) {\n\t\tparticle p;\n\t\tp.pos[0] = e.face_right() ? (e.x() + info_.min_x_) : (e.x() + e.current_frame().width() - info_.max_x_);\n\t\tp.pos[1] = e.y() + info_.min_y_;\n\t\tp.velocity[0] = info_.velocity_x_/1000.0;\n\t\tp.velocity[1] = info_.velocity_y_/1000.0;\n\n\t\tif(info_.velocity_x_rand_ > 0) {\n\t\t\tp.velocity[0] += (rand()%info_.velocity_x_rand_)/1000.0;\n\t\t}\n\n\t\tif(info_.velocity_y_rand_ > 0) {\n\t\t\tp.velocity[1] += (rand()%info_.velocity_y_rand_)/1000.0;\n\t\t}\n\n\t\tint velocity_magnitude = info_.velocity_magnitude_;\n\t\tif(info_.velocity_magnitude_rand_ > 0) {\n\t\t\tvelocity_magnitude += rand()%info_.velocity_magnitude_rand_;\n\t\t}\n\n\t\tif(velocity_magnitude) {\n\t\t\tint rotate_velocity = info_.velocity_rotate_;\n\t\t\tif(info_.velocity_rotate_rand_) {\n\t\t\t\trotate_velocity += rand()%info_.velocity_rotate_rand_;\n\t\t\t}\n\n\t\t\tconst GLfloat rotate_radians = (GLfloat(rotate_velocity)/360.0)*3.14*2.0;\n\t\t\tconst GLfloat magnitude = velocity_magnitude/1000.0;\n\t\t\tp.velocity[0] += sin(rotate_radians)*magnitude;\n\t\t\tp.velocity[1] += cos(rotate_radians)*magnitude;\n\t\t}\n\n\t\tASSERT_GT(factory_.frames_.size(), 0);\n\t\tp.anim = &factory_.frames_[rand()%factory_.frames_.size()];\n\n\t\tconst int diff_x = info_.max_x_ - info_.min_x_;\n\t\tif(diff_x > 0) {\n\t\t\tp.pos[0] += (rand()%(diff_x*1000))/1000.0;\n\t\t}\n\n\t\tconst int diff_y = info_.max_y_ - info_.min_y_;\n\t\tif(diff_y > 0) {\n\t\t\tp.pos[1] += (rand()%(diff_y*1000))/1000.0;\n\t\t}\n\n\t\tif(!e.face_right()) {\n\t\t\tp.velocity[0] = -p.velocity[0];\n\t\t}\n\n\t\tif(info_.random_schedule_) {\n\t\t\tp.random = rand();\n\t\t} else {\n\t\t\tp.random = 0;\n\t\t}\n\n\t\tparticles_.push_back(p);\n\t}\n}\n\nvoid simple_particle_system::draw(const rect& area, const entity& e) const\n{\n\tif(particles_.empty()) {\n\t\treturn;\n\t}\n\n\tstd::deque<particle>::const_iterator p = particles_.begin();\n\n\t//all particles must have the same texture, so just set it once.\n\tp->anim->set_texture();\n\tstd::vector<GLfloat>& varray = graphics::global_vertex_array();\n\tstd::vector<GLfloat>& tcarray = graphics::global_texcoords_array();\n\tstd::vector<GLbyte>& carray = graphics::global_vertex_color_array();\n\n\tconst int facing = e.face_right() ? 1 : -1;\n\t\t\t\n\n\tcarray.clear();\n\tvarray.clear();\n\ttcarray.clear();\n\tforeach(const generation& gen, generations_) {\n\t\tfor(int n = 0; n != gen.members; ++n) {\n\t\t\tconst particle_animation* anim = p->anim;\n\t\t\tconst particle_animation::frame_area& f = anim->get_frame(cycle_ - gen.created_at);\n\n\t\t\tif(info_.delta_a_){\n\t\t\t\t//Spare the bandwidth if we're opaque\n\t\t\t\tconst int alpha_level = std::max(256 - info_.delta_a_*(cycle_ - gen.created_at), 0);\n\t\t\t\tconst int red = 255;\n\t\t\t\tconst int green = 255;\n\t\t\t\tconst int blue = 255;\n\t\t\t\tfor( int i = 0; i < 6; ++i){\n\t\t\t\t\tcarray.push_back(red); carray.push_back(green); carray.push_back(blue); carray.push_back(alpha_level);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t//draw the first point twice, to allow drawing all particles\n\t\t\t//in one drawing operation.\n\n\t\t\ttcarray.push_back(graphics::texture::get_coord_x(f.u1));\n\t\t\ttcarray.push_back(graphics::texture::get_coord_y(f.v1));\n\t\t\tvarray.push_back(p->pos[0] + f.x_adjust*facing);\n\t\t\tvarray.push_back(p->pos[1] + f.y_adjust);\n\t\t\ttcarray.push_back(graphics::texture::get_coord_x(f.u1));\n\t\t\ttcarray.push_back(graphics::texture::get_coord_y(f.v1));\n\t\t\tvarray.push_back(p->pos[0] + f.x_adjust*facing);\n\t\t\tvarray.push_back(p->pos[1] + f.y_adjust);\n\n\t\t\ttcarray.push_back(graphics::texture::get_coord_x(f.u2));\n\t\t\ttcarray.push_back(graphics::texture::get_coord_y(f.v1));\n\t\t\tvarray.push_back(p->pos[0] + (anim->width() - f.x2_adjust)*facing);\n\t\t\tvarray.push_back(p->pos[1] + f.y_adjust);\n\t\t\ttcarray.push_back(graphics::texture::get_coord_x(f.u1));\n\t\t\ttcarray.push_back(graphics::texture::get_coord_y(f.v2));\n\t\t\tvarray.push_back(p->pos[0] + f.x_adjust*facing);\n\t\t\tvarray.push_back(p->pos[1] + anim->height() - f.y2_adjust);\n\n\t\t\t//draw the last point twice.\n\t\t\ttcarray.push_back(graphics::texture::get_coord_x(f.u2));\n\t\t\ttcarray.push_back(graphics::texture::get_coord_y(f.v2));\n\t\t\tvarray.push_back(p->pos[0] + (anim->width() - f.x2_adjust)*facing);\n\t\t\tvarray.push_back(p->pos[1] + anim->height() - f.y2_adjust);\n\t\t\ttcarray.push_back(graphics::texture::get_coord_x(f.u2));\n\t\t\ttcarray.push_back(graphics::texture::get_coord_y(f.v2));\n\t\t\tvarray.push_back(p->pos[0] + (anim->width() - f.x2_adjust)*facing);\n\t\t\tvarray.push_back(p->pos[1] + anim->height() - f.y2_adjust);\n\t\t\t++p;\n\t\t}\n\t}\n\t\n#if defined(USE_SHADERS)\n\tif(info_.delta_a_) {\n\t\tgles2::manager gles2_manager(gles2::get_texcol_shader());\n\t\tgles2::active_shader()->shader()->color_array(4, GL_UNSIGNED_BYTE, GL_TRUE, 0, &carray.front());\n\t\tgles2::active_shader()->shader()->vertex_array(2, GL_FLOAT, GL_FALSE, 0, &varray.front());\n\t\tgles2::active_shader()->shader()->texture_array(2, GL_FLOAT, GL_FALSE, 0, &tcarray.front());\n\t\tglDrawArrays(GL_TRIANGLE_STRIP, 0, varray.size()/2);\n\t} else {\n\t\tgles2::active_shader()->prepare_draw();\n\t\tgles2::active_shader()->shader()->vertex_array(2, GL_FLOAT, GL_FALSE, 0, &varray.front());\n\t\tgles2::active_shader()->shader()->texture_array(2, GL_FLOAT, GL_FALSE, 0, &tcarray.front());\n\t\tglDrawArrays(GL_TRIANGLE_STRIP, 0, varray.size()/2);\n\t}\n#else\n\tif(info_.delta_a_){\n\t\tglEnableClientState(GL_COLOR_ARRAY);\n\t\tglColorPointer(4, GL_UNSIGNED_BYTE, 0, &carray.front());\n\t}\n\t\n\tglVertexPointer(2, GL_FLOAT, 0, &varray.front());\n\tglTexCoordPointer(2, GL_FLOAT, 0, &tcarray.front());\n\tglDrawArrays(GL_TRIANGLE_STRIP, 0, varray.size()/2);\n\n\tif(info_.delta_a_){\n\t\tglDisableClientState(GL_COLOR_ARRAY);\n\t}\n#endif\n\tglColor4f(1.0, 1.0, 1.0, 1.0);\n}\n\nparticle_system_ptr simple_particle_system_factory::create(const entity& e) const\n{\n\treturn particle_system_ptr(new simple_particle_system(e, *this));\n}\n\nstruct point_particle_info\n{\n\texplicit point_particle_info(variant node)\n\t  : generation_rate_millis(node[\"generation_rate_millis\"].as_int()),\n\t    pos_x(node[\"pos_x\"].as_int()*1024),\n\t    pos_y(node[\"pos_y\"].as_int()*1024),\n\t    pos_x_rand(node[\"pos_x_rand\"].as_int()*1024),\n\t    pos_y_rand(node[\"pos_y_rand\"].as_int()*1024),\n\t    velocity_x(node[\"velocity_x\"].as_int()),\n\t    velocity_y(node[\"velocity_y\"].as_int()),\n\t\taccel_x(node[\"accel_x\"].as_int()),\n\t\taccel_y(node[\"accel_y\"].as_int()),\n\t    velocity_x_rand(node[\"velocity_x_rand\"].as_int()),\n\t    velocity_y_rand(node[\"velocity_y_rand\"].as_int()),\n\t\tdot_size(node[\"dot_size\"].as_int(1)*(preferences::double_scale() ? 2 : 1)),\n\t\tdot_rounded(node[\"dot_rounded\"].as_bool(false)),\n\t    time_to_live(node[\"time_to_live\"].as_int()),\n\t    time_to_live_max(node[\"time_to_live_rand\"].as_int() + time_to_live) {\n\n\t\tif(node.has_key(\"colors\")) {\n\t\t\tconst std::vector<variant> colors_vec = node[\"colors\"].as_list();\n\t\t\tforeach(const variant& col, colors_vec) {\n\t\t\t\tunsigned int val = strtoul(col.as_string().c_str(), NULL, 16);\n\t\t\t\tunsigned char* c = reinterpret_cast<unsigned char*>(&val);\n#if SDL_BYTEORDER == SDL_LIL_ENDIAN\n\t\t\t\tstd::reverse(c, c+4);\n#endif\n\t\t\t\tcolors.push_back(val);\n\t\t\t}\n\t\t}\n\n\t\tif(node.has_key(\"colors_expression\")) {\n\t\t\tconst variant v = game_logic::formula(node[\"colors_expression\"]).execute();\n\t\t\tfor(int n = 0; n != v.num_elements(); ++n) {\n\t\t\t\tconst variant u = v[n];\n\t\t\t\tASSERT_LOG(u.num_elements() == 4, \"UNEXPECTED colors_expression: \" << u.to_debug_string());\n\t\t\t\tconst unsigned int r = u[0].as_int();\n\t\t\t\tconst unsigned int g = u[1].as_int();\n\t\t\t\tconst unsigned int b = u[2].as_int();\n\t\t\t\tconst unsigned int a = u[3].as_int();\n\t\t\t\tunsigned int val = (r << 24) + (g << 16) + (b << 8) + a;\n\n#if SDL_BYTEORDER == SDL_LIL_ENDIAN\n\t\t\t\tunsigned char* c = reinterpret_cast<unsigned char*>(&val);\n\t\t\t\tstd::reverse(c, c+4);\n#endif\n\t\t\t\tcolors.push_back(val);\n\t\t\t}\n\t\t}\n\n\t\tstd::reverse(colors.begin(), colors.end());\n\n\t\tttl_divisor = time_to_live_max/(colors.size()-1);\n\n\t\trgba[0] = node[\"red\"].as_int();\n\t\trgba[1] = node[\"green\"].as_int();\n\t\trgba[2] = node[\"blue\"].as_int();\n\t\trgba[3] = node[\"alpha\"].as_int(255);\n\t\trgba_rand[0] = node[\"red_rand\"].as_int();\n\t\trgba_rand[1] = node[\"green_rand\"].as_int();\n\t\trgba_rand[2] = node[\"blue_rand\"].as_int();\n\t\trgba_rand[3] = node[\"alpha_rand\"].as_int();\n\t\trgba_delta[0] = node[\"red_delta\"].as_int();\n\t\trgba_delta[1] = node[\"green_delta\"].as_int();\n\t\trgba_delta[2] = node[\"blue_delta\"].as_int();\n\t\trgba_delta[3] = node[\"alpha_delta\"].as_int();\n\t}\n\n\tint generation_rate_millis;\n\tint pos_x, pos_y, pos_x_rand, pos_y_rand;\n\tint velocity_x, velocity_y, velocity_x_rand, velocity_y_rand;\n\tint accel_x, accel_y;\n\tint time_to_live, time_to_live_max;\n\tunsigned char rgba[4];\n\tunsigned char rgba_rand[4];\n\tchar rgba_delta[4];\n\tint dot_size;\n\tbool dot_rounded;\n\n\tstd::vector<unsigned int> colors;\n\tint ttl_divisor;\n};\n\nclass point_particle_system : public particle_system\n{\npublic:\n\tpoint_particle_system(const entity& obj, const point_particle_info& info) : obj_(obj), info_(info), particle_generation_(0), generation_rate_millis_(info.generation_rate_millis), pos_x_(info.pos_x), pos_x_rand_(info.pos_x_rand), pos_y_(info.pos_y), pos_y_rand_(info.pos_y_rand) {\n\t}\n\n\tvoid process(const entity& e) {\n\t\tparticle_generation_ += generation_rate_millis_;\n\n\t\tparticles_.erase(std::remove_if(particles_.begin(), particles_.end(), particle_destroyed), particles_.end());\n\n\t\tfor(std::vector<particle>::iterator p = particles_.begin();\n\t\t    p != particles_.end(); ++p) {\n\t\t\tp->pos_x += p->velocity_x;\n\t\t\tp->pos_y += p->velocity_y;\n\t\t\tif(e.face_right()) {\n\t\t\t\tp->velocity_x += info_.accel_x/1000.0;\n\t\t\t} else {\n\t\t\t\tp->velocity_x -= info_.accel_x/1000.0;\n\t\t\t}\n\t\t\tp->velocity_y += info_.accel_y/1000.0;\n\t\t\tp->rgba[0] = std::min(std::max(0, p->rgba[0] + info_.rgba_delta[0]), 255);\n\t\t\tp->rgba[1] = std::min(std::max(0, p->rgba[1] + info_.rgba_delta[1]), 255);\n\t\t\tp->rgba[2] = std::min(std::max(0, p->rgba[2] + info_.rgba_delta[2]), 255);\n\t\t\tp->rgba[3] = std::min(std::max(0, p->rgba[3] + info_.rgba_delta[3]), 255);\n\t\t\tp->ttl--;\n\t\t}\n\n\t\twhile(particle_generation_ >= 1000) {\n\t\t\t//std::cerr << \"PARTICLE X ORIGIN: \" << pos_x_;\n\t\t\tparticles_.push_back(particle());\n\t\t\tparticle& p = particles_.back();\n\t\t\tp.ttl = info_.time_to_live;\n\t\t\tif(info_.time_to_live_max != info_.time_to_live) {\n\t\t\t\tp.ttl += rand()%(info_.time_to_live_max - info_.time_to_live);\n\t\t\t}\n\n\t\t\tp.velocity_x = info_.velocity_x;\n\t\t\tp.velocity_y = info_.velocity_y;\n\n\t\t\tif(info_.velocity_x_rand) {\n\t\t\t\tp.velocity_x += rand()%info_.velocity_x_rand;\n\t\t\t}\n\n\t\t\tif(info_.velocity_y_rand) {\n\t\t\t\tp.velocity_y += rand()%info_.velocity_y_rand;\n\t\t\t}\n\n\t\t\tp.pos_x = e.x()*1024 + pos_x_;\n\t\t\tp.pos_y = e.y()*1024 + pos_y_;\n\n\t\t\tif(pos_x_rand_) {\n\t\t\t\tp.pos_x += rand()%pos_x_rand_;\n\t\t\t}\n\t\t\t\n\t\t\tif(pos_y_rand_) {\n\t\t\t\tp.pos_y += rand()%pos_y_rand_;\n\t\t\t}\n\n\t\t\tp.rgba[0] = info_.rgba[0];\n\t\t\tp.rgba[1] = info_.rgba[1];\n\t\t\tp.rgba[2] = info_.rgba[2];\n\t\t\tp.rgba[3] = info_.rgba[3];\n\n\t\t\tif(info_.rgba_rand[0]) {\n\t\t\t\tp.rgba[0] = std::min(std::max(0, p.rgba[0] + rand()%info_.rgba_rand[0]), 255);\n\t\t\t}\n\n\t\t\tif(info_.rgba_rand[1]) {\n\t\t\t\tp.rgba[1] = std::min(std::max(0, p.rgba[1] + rand()%info_.rgba_rand[1]), 255);\n\t\t\t}\n\n\t\t\tif(info_.rgba_rand[2]) {\n\t\t\t\tp.rgba[2] = std::min(std::max(0, p.rgba[2] + rand()%info_.rgba_rand[2]), 255);\n\t\t\t}\n\n\t\t\tif(info_.rgba_rand[3]) {\n\t\t\t\tp.rgba[3] = std::min(std::max(0, p.rgba[3] + rand()%info_.rgba_rand[3]), 255);\n\t\t\t}\n\n\t\t\tparticle_generation_ -= 1000;\n\t\t}\n\t}\n\n\tvoid draw(const rect& area, const entity& e) const {\n\t\tif(particles_.empty()) {\n\t\t\treturn;\n\t\t}\n\n\t\tstatic std::vector<GLshort> vertex;\n\t\tstatic std::vector<unsigned int> colors;\n\t\tvertex.resize(particles_.size()*2);\n\t\tcolors.resize(particles_.size());\n\n\t\tunsigned int* c = &colors[0];\n\t\tGLshort* v = &vertex[0];\n\t\tfor(std::vector<particle>::const_iterator p = particles_.begin();\n\t\t    p != particles_.end(); ++p) {\n\t\t\t*v++ = p->pos_x/1024;\n\t\t\t*v++ = p->pos_y/1024;\n\t\t\tif(info_.colors.size() >= 2) {\n\t\t\t\t*c++ = info_.colors[p->ttl/info_.ttl_divisor];\n\t\t\t} else {\n\t\t\t\t*c++ = p->color;\n\t\t\t}\n\t\t}\n\n\t\tglColor4f(1.0, 1.0, 1.0, 1.0);\n\n#if defined(USE_SHADERS)\n\t\t// Not dealing with GL_POINT_SMOOTH right now -- this would probably be better as a frgament shader.\n\t\tglPointSize(info_.dot_size);\n\t\tgles2::manager gles2_manager(gles2::get_simple_col_shader());\n\t\tgles2::active_shader()->shader()->vertex_array(2, GL_SHORT, GL_FALSE, 0, &vertex[0]);\n\t\tgles2::active_shader()->shader()->color_array(4, GL_UNSIGNED_BYTE, GL_TRUE, 0, &colors[0]);\n\t\tglDrawArrays(GL_POINTS, 0, particles_.size());\n#else\n\t\tglDisable(GL_TEXTURE_2D);\n\t\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\tglEnableClientState(GL_COLOR_ARRAY);\n\t\tif(info_.dot_rounded){\n\t\t\tglEnable( GL_POINT_SMOOTH );\n\t\t}\n\t\tglPointSize(info_.dot_size);\n\n\t\tglVertexPointer(2, GL_SHORT, 0, &vertex[0]);\n\t\tglColorPointer(4, GL_UNSIGNED_BYTE, 0, &colors[0]);\n\t\tglDrawArrays(GL_POINTS, 0, particles_.size());\n\n\t\tglDisableClientState(GL_COLOR_ARRAY);\n\t\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tif(info_.dot_rounded){\n\t\t\tglDisable( GL_POINT_SMOOTH );\n\t\t}\n#endif\n\t\tglColor4f(1.0, 1.0, 1.0, 1.0);\n\t}\nprivate:\n\tconst entity& obj_;\n\tconst point_particle_info& info_;\n\n\tstruct particle {\n\t\tGLshort velocity_x, velocity_y;\n\t\tint pos_x, pos_y;\n\t\tunion { unsigned int color; unsigned char rgba[4]; };\n\t\tint ttl;\n\t};\n\n\tstatic bool particle_destroyed(const particle& p) { return p.ttl <= 0; }\n\n\tint particle_generation_;\n\tint generation_rate_millis_;\n\tint pos_x_, pos_x_rand_, pos_y_, pos_y_rand_;\n\tstd::vector<particle> particles_;\n\n\tvariant get_value(const std::string& key) const {\n\t\treturn variant();\n\t}\n\n\tvoid set_value(const std::string& key, const variant& value) {\n\t\tif(key == \"generation_rate\" || key == \"generation_rate_millis\") {\n\t\t\tgeneration_rate_millis_ = value.as_int();\n\t\t} else if (key == \"pos_x\") {\n\t\t\tpos_x_ = value.as_int()*1024;\n\t\t} else if (key == \"pos_x_rand\") {\n\t\t\tpos_x_rand_ = value.as_int()*1024;\n\t\t} else if (key == \"pos_y\") {\n\t\t\tpos_y_ = value.as_int()*1024;\n\t\t} else if (key == \"pos_y_rand\") {\n\t\t\tpos_y_rand_ = value.as_int()*1024;\n\t\t}\n\t}\n};\n\nclass point_particle_system_factory : public particle_system_factory\n{\npublic:\n\texplicit point_particle_system_factory(variant node)\n\t  : info_(node)\n\t{}\n\n\tparticle_system_ptr create(const entity& e) const {\n\t\treturn particle_system_ptr(new point_particle_system(e, info_));\n\t}\n\nprivate:\n\tpoint_particle_info info_;\n};\n\n}\n\nconst_particle_system_factory_ptr particle_system_factory::create_factory(variant node)\n{\n\tconst std::string& type = node[\"type\"].as_string();\n\tif(type == \"simple\") {\n\t\treturn const_particle_system_factory_ptr(new simple_particle_system_factory(node));\n\t} else if (type == \"weather\") {\n\t\treturn const_particle_system_factory_ptr(new weather_particle_system_factory(node));\n\t} else if (type == \"water\") {\n\t\treturn const_particle_system_factory_ptr(new water_particle_system_factory(node));\n\t} else if(type == \"point\") {\n\t\treturn const_particle_system_factory_ptr(new point_particle_system_factory(node));\n\t}\n\n\tASSERT_LOG(false, \"Unrecognized particle system type: \" << node[\"type\"].as_string());\n}\n\nparticle_system_factory::~particle_system_factory()\n{\n}\n\nparticle_system::~particle_system()\n{\n}\n", "meta": {"hexsha": "923620409fb1cf9f8b6eeedd0192690bfb51cd24", "size": 29167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/particle_system.cpp", "max_stars_repo_name": "sweetkristas/anura", "max_stars_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "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": "src/particle_system.cpp", "max_issues_repo_name": "sweetkristas/anura", "max_issues_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "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": "src/particle_system.cpp", "max_forks_repo_name": "sweetkristas/anura", "max_forks_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "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": 31.566017316, "max_line_length": 280, "alphanum_fraction": 0.6846093188, "num_tokens": 8481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "/** $Id: histogram.cxx 172050 2019-03-15 12:47:22Z flauber $\n * @file\n * @author Jakob van Santen <vansanten@wisc.edu>\n *\n * $Revision: 172050 $\n * $Date: 2019-03-15 06:47:22 -0600 (Fri, 15 Mar 2019) $\n */\n\n#include <MuonGun/histogram.h>\n#include <boost/foreach.hpp>\n#include <boost/python/slice.hpp>\n\nnamespace bp = boost::python;\n\n#if PY_MAJOR_VERSION >= 3\nstatic PyObject *\nPyBuffer_FromMemory(void *memory, size_t size)\n{\n\tPy_buffer buf;\n\tmemset(&buf, 0, sizeof(buf));\n\tbuf.buf = memory;\n\tbuf.len = size;\n\tbuf.readonly = true;\n\tbuf.ndim = 1;\n\tbuf.itemsize = sizeof(double);\n        size_t s= size/sizeof(double);\n        assert(s<= INT_MAX);\n\tPy_ssize_t shape[] = { static_cast<Py_ssize_t>(s) };\n\tbuf.shape = shape;\n\treturn PyMemoryView_FromBuffer(&buf);\n}\n#endif\n\nstatic bp::object\nto_dashi(boost::shared_ptr<I3MuonGun::histogram::histogram_base> h)\n{\n\tbp::object histmodule = bp::import(\"dashi.histogram\");\n\tbp::object numpy = bp::import(\"numpy\");\n\tbp::list edges;\n\tBOOST_FOREACH(const std::vector<double> &dim, h->binedges())\n\t\tedges.append(bp::list(dim));\n\t\n\tbp::object dhist = histmodule.attr(\"histogram\")(h->ndim(), edges);\n\t\n\tbp::list shape;\n\tsize_t ndim = h->ndim(); (void) ndim;\n\tsize_t tsize = 1;\n\tBOOST_FOREACH(size_t i, h->shape()) {\n\t\ttsize *= i;\n\t\tshape.append(i);\n\t}\n\tbp::tuple shapet(shape);\n\tbp::object dtype = numpy.attr(\"float64\");\n\t\n\tbp::object buffer = bp::object(bp::handle<>(PyBuffer_FromMemory(\n\t    (void*)h->raw_bincontent(), sizeof(double)*tsize)));\n\tdhist.attr(\"_h_bincontent\").attr(\"__setitem__\")(bp::slice(),\n\t    numpy.attr(\"ndarray\")(shapet, dtype, buffer));\n\t\n\tbuffer =  bp::object(bp::handle<>(PyBuffer_FromMemory(\n\t    (void*)h->raw_squaredweights(), sizeof(double)*tsize)));\n\tdhist.attr(\"_h_squaredweights\").attr(\"__setitem__\")(bp::slice(),\n\t    numpy.attr(\"ndarray\")(shapet, dtype, buffer));\n\t\n\treturn dhist;\n}\n\nstatic boost::shared_ptr<I3MuonGun::histogram::histogram_base> test_histogram()\n{\n\tusing namespace I3MuonGun::histogram;\n\t\n\thistogram<3>::bin_specification edges;\n\t{\n\t\tusing namespace binning;\n\t\t// edges[0] = uniform<>::create(0, 1, 11);\n\t\tedges[0] = uniform<cosine>::create(0, M_PI/2., 11);\n\t\t// edges[0] = boost::get<boost::shared_ptr<binning::scheme> >(edges[0])->edges();\n\t\tedges[1] = uniform<binning::log10>::create(1e3, 1e5, 11);\n\t\tedges[2] = uniform<power<2> >::create(1, 10, 11);\n\t}\n\t\n\tboost::shared_ptr<histogram<3> > h(new histogram<3>(edges));\n\t\n\tboost::array<double, 3> values = {{0.5, 1e4, 8}};\n\t\n\tfor (int i=0; i < 25; i++) {\n\t\tvalues[0] = 1e-1*i;\n\t\th->fill(values);\n\t}\n\t\n\treturn h;\n}\n\n\nvoid register_histogram()\n{\n\tusing namespace I3MuonGun::histogram;\n\tnamespace bp = boost::python;\n\t\n\tbp::def(\"test_histogram\", &test_histogram);\n\t\n\tbp::class_<histogram_base, boost::shared_ptr<histogram_base>, boost::noncopyable>(\"histogram\", bp::no_init)\n\t\t.def(\"to_dashi\", &to_dashi)\n\t\t\t;\n\ttry {\n\t\tbp::import(\"dashi.histogram\");\n\t\tbp::import(\"numpy\");\n\t} catch (const bp::error_already_set&) {\n\t\t\n\t\tPyErr_Clear();\n\t}\n\t\n}\n", "meta": {"hexsha": "de2f2ca6353ebfb6878248aab81822f136b45201", "size": 2977, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "MuonGun/private/pybindings/histogram.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": "MuonGun/private/pybindings/histogram.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": "MuonGun/private/pybindings/histogram.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": 26.1140350877, "max_line_length": 108, "alphanum_fraction": 0.6664427276, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <stdexcept>\n#include <cmath>\n#include <locale.h>\n\n#include <QApplication>\n\n#include \"common.h\"\n#include \"time_utils.h\"\n#include \"cli_parser.h\"\n#include \"image_loader.h\"\n#include \"Classifier.h\"\n#include \"ClassificationDataset.h\"\n#include \"FannClassificationDataset.h\"\n#include \"NeuralNetworkPixelClassifiers.h\"\n#include \"LibSVMClassificationDataset.h\"\n#include \"SVMPixelClassifier.h\"\n\n#include \"doublefann.h\"\n\n#include <tulip/TlpQtTools.h>\n#include <tulip/PluginLoaderTxt.h>\n#include <tulip/Graph.h>\n#include <tulip/TlpTools.h>\n#include <tulip/PluginLibraryLoader.h>\n#include <tulip/StringCollection.h>\n#include <tulip/DoubleProperty.h>\n#include <tulip/BooleanProperty.h>\n\n#include <boost/filesystem.hpp>\n\n#include <itkImageSeriesWriter.h>\n#include <itkNumericSeriesFileNames.h>\n\n#include <itkBinaryThresholdImageFilter.h>\n\n#include \"LoggerPluginProgress.h\"\n\n#include \"log4cxx/logger.h\"\n#include \"log4cxx/consoleappender.h\"\n#include \"log4cxx/patternlayout.h\"\n#include \"log4cxx/basicconfigurator.h\"\n\n#include \"callgrind.h\"\n\nusing namespace tlp;\nusing namespace std;\n\nnamespace bfs = boost::filesystem;\n\n//bool desc_comparator(const T a, const T b) { return a > b; }\ntemplate <typename T>\nclass desc_comparator {\npublic:\n\tdesc_comparator(std::vector<T> const & values) :m_values(values) {}\n\tinline bool operator() (size_t a, size_t b) { return m_values[a] > m_values[b]; }\nprivate:\n\tstd::vector<T> const& m_values;\n};\n\ntemplate <typename T>\nstd::vector<size_t> ordered(std::vector<T> const& values, desc_comparator<T> comparator) {\n\tstd::vector<size_t> indices(values.size());\n\t//std::iota(begin(indices), end(indices), static_cast<size_t>(0)); // cxx11\n\tfor (size_t i = 0; i != indices.size(); ++i) indices[i] = i;\n\n\tstd::sort( indices.begin(), indices.end(), comparator );\n\n\treturn indices;\n}\n\nclass DirException : public std::runtime_error\n{\nprivate:\n\tDirException ( const std::string &err ) : std::runtime_error (err) {}\npublic:\n\tstatic DirException NotEmpty(const bfs::path &path) {     return DirException(path.native() + \" is not empty.\"); }\n\tstatic DirException File(const bfs::path &path) {         return DirException(path.native() + \" is a file.\"); }\n\tstatic DirException CannotCreate(const bfs::path &path) { return DirException(path.native() + \" cannot be created.\"); }\n};\n\nvoid get_directory(const bfs::path &path, const bool mustBeEmpty = false) {\n\tif(bfs::exists(path)) {\n\t\tif(bfs::is_directory(path)) {\n\t\t\tif(mustBeEmpty && !bfs::is_empty(path))\n\t\t\t\tthrow DirException::NotEmpty(path);\n\t\t} else\n\t\t\tthrow DirException::File(path);\n\t} else {\n\t\tif(!bfs::create_directories(path))\n\t\t\tthrow DirException::CannotCreate(path);\n\t}\n}\n\nstd::string pad(const unsigned int i, const char c = '0', const unsigned int l = 6) {\n\tstd::ostringstream os;\n\tos << std::setfill(c) << std::setw(l) << i;\n\treturn os.str();\n}\n\nint main(int argc, char **argv)\n{\n\tQApplication app(argc,argv);\n\tsetlocale(LC_NUMERIC,\"C\");\n\n\tlog4cxx::BasicConfigurator::configure(\n\t\t\tlog4cxx::AppenderPtr(new log4cxx::ConsoleAppender(\n\t\t\t\t\tlog4cxx::LayoutPtr(new log4cxx::PatternLayout(\"\\%-5p - [%c] - \\%m\\%n\")),\n\t\t\t\t\tlog4cxx::ConsoleAppender::getSystemErr()\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t);\n\n\tlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\n\tCliParser cli_parser;\n\ttry {\n\t\tif(cli_parser.parse_argv(argc, argv) != CliParser::CONTINUE)\n\t\t\texit(0);\n\t} catch (CliException &err) {\n\t\tLOG4CXX_FATAL(logger, err.what());\n\t\treturn -1;\n\t}\n\n\ttimestamp_t last_timestamp;\n\n\tFeaturesImage::Pointer input_image;\n\n\t/*\n\t * Loading the input image (if it exists).\n\t */\n\tif(!cli_parser.get_input_image().empty()) {\n\t\tlast_timestamp = get_timestamp();\n\t\tLOG4CXX_INFO(logger, \"Loading features image\");\n\n\t\ttypename itk::ImageFileReader< FeaturesImage >::Pointer input_image_reader = itk::ImageFileReader< FeaturesImage >::New();\n\t\tinput_image_reader->SetFileName(cli_parser.get_input_image());\n\n\t\ttry {\n\t\t\tinput_image_reader->Update();\n\t\t} catch( itk::ExceptionObject &ex ) {\n\t\t\tLOG4CXX_FATAL(logger, \"ITK is unable to load the image \\\"\" << cli_parser.get_input_image() << \"\\\" (\" << ex.what() << \")\");\n\t\t\texit(-1);\n\t\t}\n\n\t\tinput_image = input_image_reader->GetOutput();\n\n\t\tLOG4CXX_INFO(logger, \"Features image loaded in \" << elapsed_time(last_timestamp, get_timestamp()) << \"s\");\n\t}\n\n\tboost::shared_ptr< Classifier<fann_type> > pixelClassifier;\n\n\tif(cli_parser.get_classifier_training_images_classes().empty()) {\n\t\t/*\n\t\t * Loading the classifier from a stored configuration.\n\t\t */\n\t\ttry {\n\t\t\tif(cli_parser.get_classifier_type() == CliParser::ANN) {\n\t\t\t\tpixelClassifier = boost::shared_ptr< Classifier<fann_type> >(new NeuralNetworkPixelClassifiers);\n\t\t\t} else if(cli_parser.get_classifier_type() == CliParser::SVM) {\n\t\t\t\tpixelClassifier = boost::shared_ptr< Classifier<fann_type> >(new SVMPixelClassifier);\n\t\t\t}\n\n\t\t\tpixelClassifier->load(cli_parser.get_classifier_config_dir());\n\t\t} catch (std::runtime_error &err) {\n\t\t\tLOG4CXX_FATAL(logger, err.what());\n\t\t\texit(-1);\n\t\t}\n\t} else {\n\t\t/*\n\t\t * Loading the training classes.\n\t\t */\n\t\tlast_timestamp = get_timestamp();\n\t\tLOG4CXX_INFO(logger, \"Loading training classes\");\n\n\t\tboost::shared_ptr< ClassificationDataset<double> > trainingDataset;\n\n\t\ttry {\n\t\t\tif(cli_parser.get_classifier_training_images().empty()) {\n\t\t\t\t/*\n\t\t\t\t * No image provided for training the classifier, so we\n\t\t\t\t * wil use the one that will be segmented.\n\t\t\t\t */\n\t\t\t\tLOG4CXX_INFO(logger, \"Loading training classes from input image\");\n\n\t\t\t\ttrainingDataset = boost::shared_ptr< ClassificationDataset<double> >(new ClassificationDataset<double>(input_image, cli_parser.get_classifier_training_images_classes()));\n\t\t\t} else {\n\t\t\t\t/*\n\t\t\t\t * A list of image is available to train the classifier.\n\t\t\t\t */\n\t\t\t\tLOG4CXX_INFO(logger, \"Loading training classes from a list of images\");\n\n\t\t\t\ttrainingDataset = boost::shared_ptr< ClassificationDataset<double> >(\n\t\t\t\t\t\tnew ClassificationDataset<double>(cli_parser.get_classifier_training_images(), cli_parser.get_classifier_training_images_classes())\n\t\t\t\t);\n\t\t\t}\n\n\t\t\ttrainingDataset->checkValid();\n\n\t\t\tLOG4CXX_INFO(logger, \"Training classes loaded in \" << elapsed_time(last_timestamp, get_timestamp()) << \"s\");\n\t\t} catch (ClassificationDatasetException & ex) {\n\t\t\tLOG4CXX_FATAL(logger, \"Unable to load the training classes: \" << ex.what());\n\t\t\texit(-1);\n\t\t}\n\n\t\tif(cli_parser.get_classifier_type() == CliParser::ANN)\n\t\t{\n\t\t\t/*\n\t\t\t * Loading the validation classes.\n\t\t\t */\n\t\t\tlast_timestamp = get_timestamp();\n\t\t\tLOG4CXX_INFO(logger, \"Loading training classes\");\n\n\t\t\tboost::shared_ptr< ClassificationDataset<double> > validationDataset;\n\n\t\t\tif(cli_parser.get_ann_validation_images().size() > 0) {\n\t\t\t\ttry {\n\t\t\t\t\t/*\n\t\t\t\t\t * A list of image is available to build the validation-set.\n\t\t\t\t\t */\n\t\t\t\t\tLOG4CXX_INFO(logger, \"Loading validation-classes from a list of images\");\n\n\t\t\t\t\tvalidationDataset = boost::shared_ptr< ClassificationDataset<fann_type> >(\n\t\t\t\t\t\t\tnew ClassificationDataset<double>(cli_parser.get_ann_validation_images(), cli_parser.get_ann_validation_images_classes())\n\t\t\t\t\t);\n\n\t\t\t\t\tif(validationDataset->getInputSize() != trainingDataset->getInputSize()) {\n\t\t\t\t\t\tLOG4CXX_FATAL(logger, \"The validation set do not have the same number of components per pixel than the training set.\");\n\t\t\t\t\t\texit(-1);\n\t\t\t\t\t}\n\n\t\t\t\t\tvalidationDataset->checkValid();\n\t\t\t\t} catch (ClassificationDatasetException & ex) {\n\t\t\t\t\tLOG4CXX_FATAL(logger, \"Unable to load the validation classes: \" << ex.what());\n\t\t\t\t\texit(-1);\n\t\t\t\t}\n\t\t\t} else if(cli_parser.get_ann_validation_training_ratio() > 0) {\n\t\t\t\t/*\n\t\t\t\t * From the training set.\n\t\t\t\t */\n\t\t\t\tLOG4CXX_INFO(logger, \"Generating the validation-set from the training-set with a ratio of \" << cli_parser.get_ann_validation_training_ratio());\n\n\t\t\t\ttry {\n\t\t\t\t\ttrainingDataset->shuffle();\n\n\t\t\t\t\tstd::pair< boost::shared_ptr< ClassificationDataset<fann_type> >, boost::shared_ptr< ClassificationDataset<fann_type> > > new_sets =\n\t\t\t\t\t\ttrainingDataset->split(cli_parser.get_ann_validation_training_ratio());\n\n\t\t\t\t\ttrainingDataset = new_sets.second;\n\t\t\t\t\tvalidationDataset = new_sets.first;\n\n\t\t\t\t} catch (FannClassificationDatasetException &ex) {\n\t\t\t\t\tLOG4CXX_FATAL(logger, \"Cannot generate validation-set from training-set: \" << ex.what());\n\t\t\t\t\texit(-1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG4CXX_INFO(logger, \"Validation classes loaded in \" << elapsed_time(last_timestamp, get_timestamp()) << \"s\");\n\n\t\t\tboost::shared_ptr< FannClassificationDataset > fannTrainingDatasets(new FannClassificationDataset(*trainingDataset)),\n\t\t\t                                               fannValidationDatasets(new FannClassificationDataset(*validationDataset));\n\n\t\t\t// TODO Supprimer le training set et le validation-set\n\t\t\t// They are not needed now that we have the FannClassificationDatasets\n\t\t\ttrainingDataset.reset();\n\t\t\tvalidationDataset.reset();\n\n\t\t\tfannTrainingDatasets->shuffle();\n\n\t\t\tNeuralNetworkPixelClassifiers *ann = new NeuralNetworkPixelClassifiers();\n\t\t\tpixelClassifier = boost::shared_ptr< Classifier<fann_type> >(ann);\n\n\t\t\t/*\n\t\t\t * Training of neural networks\n\t\t\t */\n\t\t\tlast_timestamp = get_timestamp();\n\t\t\tLOG4CXX_INFO(logger, \"Training neural networks\");\n\n\t\t\tann->create_neural_networks(fannTrainingDatasets->getInputSize(), fannTrainingDatasets->getNumberOfDatasets(), cli_parser.get_ann_hidden_layers(), cli_parser.get_ann_learning_rate());\n\t\t\tann->train_neural_networks(fannTrainingDatasets.get(), cli_parser.get_ann_max_epoch(), cli_parser.get_ann_mse_target(), fannValidationDatasets.get());\n\n\t\t\tLOG4CXX_INFO(logger, \"Neural networks trained in \" << elapsed_time(last_timestamp, get_timestamp()) << \"s\");\n\t\t} else if(cli_parser.get_classifier_type() == CliParser::SVM) {\n\t\t\tboost::shared_ptr< LibSVMClassificationDataset > svmTrainingDataset(new LibSVMClassificationDataset(*trainingDataset));\n\t\t\ttrainingDataset.reset();\n\n\t\t\tSVMPixelClassifier *svm = new SVMPixelClassifier();\n\t\t\tpixelClassifier = boost::shared_ptr< Classifier<fann_type> >(svm);\n\n\t\t\tlast_timestamp = get_timestamp();\n\t\t\tLOG4CXX_INFO(logger, \"Training the SVM\");\n\t\t\tif(!svm->train(svmTrainingDataset.get())) {\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t\tLOG4CXX_INFO(logger, \"SVM trained in \" << elapsed_time(last_timestamp, get_timestamp()) << \"s\");\n\t\t}\n\n\t\t/*\n\t\t * Saving the classifier (if required).\n\t\t */\n\t\tif(!cli_parser.get_classifier_config_dir().empty()) {\n\t\t\tbfs::path classifier_config_dir(cli_parser.get_classifier_config_dir());\n\n\t\t\ttry {\n\t\t\t\tget_directory(classifier_config_dir);\n\t\t\t\tpixelClassifier->save(cli_parser.get_classifier_config_dir());\n\t\t\t} catch (std::runtime_error &err) {\n\t\t\t\tLOG4CXX_FATAL(logger, err.what());\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t *\n\t *\n\t *\n\t * The classifier is ready!\n\t *\n\t *\n\t *\n\t */\n\n\tif(cli_parser.get_input_image().empty())\n\t\texit(0);\n\n\tif((cli_parser.get_classifier_type() == CliParser::ANN) && (pixelClassifier->getInputSize() != input_image->GetNumberOfComponentsPerPixel())) {\n\t\tLOG4CXX_FATAL(logger, \"The classifier is configured to work on pixels with \" << pixelClassifier->getInputSize() << \" components per pixel, \"\n\t\t                   << \"but the input image has \" << input_image->GetNumberOfComponentsPerPixel() << \" components per pixel.\");\n\t\texit(-1);\n\t}\n\n\tbfs::path export_dir_path(cli_parser.get_export_dir());\n\ttry {\n\t\tget_directory(export_dir_path);\n\t} catch (DirException &err) {\n\t\tLOG4CXX_FATAL(logger, err.what());\n\t\texit(-1);\n\t}\n\n\tconst unsigned int number_of_classifiers = pixelClassifier->getNumberOfClasses() == 2 ? 1 : pixelClassifier->getNumberOfClasses();\n\n\t/*\n\t * Creation of the export folders for each class\n\t */\n\tif(cli_parser.get_export_interval() > 0) {\n\t\ttry {\n\t\t\tfor(int i = 0; i < number_of_classifiers; ++i)\n\t\t\t\tget_directory(export_dir_path / pad(i));\n\t\t} catch (DirException &err) {\n\t\t\tLOG4CXX_FATAL(logger, err.what());\n\t\t\texit(-1);\n\t\t}\n\t}\n\n\tif(cli_parser.get_debug()) {\n\t\tPluginLoaderTxt txtLoader;\n\t\ttlp::initTulipSoftware(&txtLoader);\n\t} else {\n\t\ttlp::initTulipSoftware(NULL);\n\t}\n\n\t/*\n\t * Creation of the graph structure\n\t */\n\tlast_timestamp = get_timestamp();\n\tLOG4CXX_INFO(logger, \"Generating graph structure\");\n\n\ttlp::DataSet data;\n\tdata.set(\"Width\",               input_image->GetLargestPossibleRegion().GetSize()[0]);\n\tdata.set(\"Height\",              input_image->GetLargestPossibleRegion().GetSize()[1]);\n\tdata.set(\"Depth\",               input_image->GetLargestPossibleRegion().GetSize()[2]);\n\tdata.set(\"Neighborhood radius\", 1.0);\n\tdata.set(\"Neighborhood type\",   tlp::StringCollection(\"Circular\"));\n\tdata.set(\"Positionning\",        true);\n\tdata.set(\"Spacing\",             1.0);\n\n\ttlp::Graph *graph = tlp::importGraph(\"Grid 3D\", data);\n\n\ttlp::BooleanProperty *everything = graph->getLocalProperty<tlp::BooleanProperty>(\"everything\");\n\teverything->setAllNodeValue(true);\n\teverything->setAllEdgeValue(true);\n\n\ttlp::BooleanProperty *roi = graph->getLocalProperty<tlp::BooleanProperty>(\"ROI\");\n\n\tLOG4CXX_INFO(logger, \"Importing region of interest\");\n\tif(cli_parser.get_region_of_interest().empty()) {\n\t\tLOG4CXX_INFO(logger, \"No region of interest specified\");\n\t\troi->setAllNodeValue(true);\n\t} else {\n\t\ttlp::DataSet data;\n\t\tstd::string error;\n\t\tdata.set(\"file::Image\",          cli_parser.get_region_of_interest());\n\t\tdata.set(\"Property\",             roi);\n\t\tdata.set(\"Convert to grayscale\", false);\n\n\t\tif(!graph->applyAlgorithm(\"Load image data\", error, &data)) {\n\t\t\tLOG4CXX_FATAL(logger, \"Unable to import region of interest: \" << error);\n\t\t\treturn -1;\n\t\t}\n\t\tLOG4CXX_INFO(logger, \"Region of interest successfully imported\");\n\t}\n\n\n\ttlp::DoubleProperty *weight = graph->getLocalProperty<tlp::DoubleProperty>(\"Weight\");\n\tweight->setAllEdgeValue(1);\n\n\ttlp::DoubleVectorProperty *features_property = graph->getLocalProperty<tlp::DoubleVectorProperty>(\"features\");\n\n\t{ // Copy of the texture features into the graph\n\t\ttlp::Iterator<tlp::node> *itNodes = graph->getNodes();\n\t\ttlp::node u;\n\n\t\tconst FeaturesImage::PixelType::ValueType *features_tmp;\n\t\tstd::vector<double> features(input_image->GetNumberOfComponentsPerPixel());\n\n\t\twhile(itNodes->hasNext())\n\t\t{\n\t\t\tu = itNodes->next();\n\t\t\tFeaturesImage::PixelType texture = input_image->GetPixel(input_image->ComputeIndex(u.id));\n\n\t\t\tfeatures_tmp = texture.GetDataPointer();\n\t\t\tfeatures.assign(features_tmp, features_tmp + input_image->GetNumberOfComponentsPerPixel());\n\t\t\tfeatures_property->setNodeValue(u, features);\n\t\t}\n\t\tdelete itNodes;\n\t}\n\n\tLOG4CXX_INFO(logger, \"Graph structure generated in \" << elapsed_time(last_timestamp, get_timestamp()) << \"s\");\n\n\n\tlast_timestamp = get_timestamp();\n\tLOG4CXX_INFO(logger, \"Classifying the pixels\");\n\n\tstd::vector< tlp::DoubleProperty* > regularized_segmentations(number_of_classifiers); \n\n\tstd::vector< tlp::Graph* > subgraphs;\n\tstd::vector< tlp::DoubleProperty* > f0_properties;\n\tstd::vector< tlp::DoubleProperty* > seed_properties;\n\n\t/*\n\t * Classification of the pixels\n\t */\n\tfor(unsigned int i = 0; i < number_of_classifiers; ++i)\n\t{\n\t\ttlp::Graph *subgraph = graph->addSubGraph(everything, pad(i));\n\n\t\tsubgraphs.push_back(subgraph);\n\t\tseed_properties.push_back(subgraph->getLocalProperty<tlp::DoubleProperty>(\"Seed\"));\n\t\tf0_properties.push_back(subgraph->getLocalProperty<tlp::DoubleProperty>(\"f0\"));\n\t}\n\n\t{\n\t\ttlp::Iterator<tlp::node> *itNodes = graph->getNodes();\n\t\ttlp::node u;\n\t\twhile(itNodes->hasNext())\n\t\t{\n\t\t\tu = itNodes->next();\n\t\t\tif(roi->getNodeValue(u))\n\t\t\t{\n\t\t\t\tstd::vector<float> probabilities = pixelClassifier->classify(features_property->getNodeValue(u));\n\n\t\t\t\tfor(unsigned int i = 0; i < number_of_classifiers; ++i)\n\t\t\t\t{\n\t\t\t\t\tf0_properties[i]->setNodeValue(u, probabilities[i]);\n\t\t\t\t\tseed_properties[i]->setNodeValue(u, probabilities[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelete itNodes;\n\t}\n\n\tLOG4CXX_INFO(logger, \"Pixels classified in \" << elapsed_time(last_timestamp, get_timestamp()) << \"s\");\n\n\tfor(unsigned int i = 0; i < number_of_classifiers; ++i)\n\t{\n\t\tLOG4CXX_INFO(logger, \"Data classification done for image #\" << i);\n\n\t\t/*****************************************************/\n\t\t/* Application of the graph regularisation algorithm */\n\t\t/*****************************************************/\n\t\t//LOG4CXX_INFO(logger, \"Applying CV Regularization algorithm on image #\" << i);\n\t\tLOG4CXX_INFO(logger, \"Applying ROF Regularization algorithm on image #\" << i);\n\n\t\tbfs::path export_dir = export_dir_path / pad(i);\n\n\t\tDoubleProperty* fn = subgraphs[i]->getLocalProperty< DoubleProperty >(\"fn\");\n\t\tBooleanProperty* segmentation = subgraphs[i]->getLocalProperty< BooleanProperty >(\"viewSelection\");\n\n\t\tDataSet data4;\n\t\tdata4.set(\"seed\",                  seed_properties[i]);\n\t\tdata4.set(\"result\",                fn);\n\t\tdata4.set(\"segmentation result\",   segmentation);\n\t\tdata4.set(\"data\",                  f0_properties[i]);\n\t\tdata4.set(\"similarity measure\",    weight);\n\t\tdata4.set(\"number of iterations\",  cli_parser.get_num_iter());\n\t\tdata4.set(\"lambda\",               cli_parser.get_lambda());\n\t\tdata4.set(\"export interval\",       cli_parser.get_export_interval());\n\t\tdata4.set(\"dir::export directory\", export_dir.native());\n\n\t\tLoggerPluginProgress pp(\"main.cv_ta\");\n\n\t\tstring error4;\n\t\t//bool reg_applied = subgraph->applyAlgorithm(\"ChanVese Regularization\", error4, &data4, &pp);\n\t\tbool reg_applied = subgraphs[i]->applyAlgorithm(\"Rudin-Osher-Fatemi Regularization\", error4, &data4, &pp);\n\t\tif(!reg_applied) {\n\t\t\tLOG4CXX_FATAL(logger, \"Unable to apply the ROF Regularization algorithm: \" << error4);\n\t\t\treturn -1;\n\t\t}\n\n\t\tregularized_segmentations[i] = fn;\n\n\t\tLOG4CXX_INFO(logger, \"Regularization done for image #\" << i);\n\t}\n\n\tif(cli_parser.get_debug()) {\n\t\tbfs::path output_graph = export_dir_path / \"graph.tlp\";\n\t}\n\n\tImageType::Pointer classification_image = ImageType::New();\n\tclassification_image->SetRegions(input_image->GetLargestPossibleRegion());\n\tclassification_image->Allocate();\n\tImageType::IndexType index;\n\n\tint width, height, depth;\n\tunsigned int id;\n\n\tgraph->getAttribute<int>(\"width\", width);\n\tgraph->getAttribute<int>(\"height\", height);\n\tgraph->getAttribute<int>(\"depth\", depth);\n\n\ttlp::Iterator<tlp::node> *itNodes = graph->getNodes();\n\ttlp::node u;\n\tstd::vector< double > values(number_of_classifiers);\n\n\tstd::vector< double >::iterator max_it;\n\tunsigned int max_pos;\n\n\twhile(itNodes->hasNext())\n\t{\n\t\tu = itNodes->next();\n\t\tid = u.id;\n\t\tindex[0] =  id % width;\n\t\tid /= width;\n\t\tindex[1] = id % height;\n\t\tid /= height;\n\t\tindex[2] = id;\n\n\t\tif(roi->getNodeValue(u))\n\t\t{\n\t\t\tif(number_of_classifiers > 1)\n\t\t\t{\n\t\t\t\tfor(unsigned int i = 0; i < number_of_classifiers; ++i)\n\t\t\t\t{\n\t\t\t\t\tvalues[i] = regularized_segmentations[i]->getNodeValue(u);\n\t\t\t\t}\n\n\t\t\t\tstd::vector< size_t > ordered_indices = ordered(values, desc_comparator<double>(values));\n\n\t\t\t\t//if( (values[ordered_indices[0]] > 0.5) && ( (0.9 * values[ordered_indices[0]]) > values[ordered_indices[1]]) ) {\n\t\t\t\t/*\n\t\t\t\tif( values[ordered_indices[0]] > 0.5 ) {\n\t\t\t\t\tmax_pos = ordered_indices[0] + 1;\n\t\t\t\t} else {\n\t\t\t\t\tmax_pos = 0;\n\t\t\t\t}\n\t\t\t\t*/\n\t\t\t\tmax_pos = ordered_indices[0] + 1;\n\t\t\t} else {\n\t\t\t\tmax_pos = (regularized_segmentations[0]->getNodeValue(u) > 0.5 ? 1 : 2); // No rejected class\n\t\t\t}\n\t\t} else {\n\t\t\tmax_pos = 0; // XXX Do we set it to 0 when we are supposed to ignore the pixel?\n\t\t}\n\n\t\tclassification_image->SetPixel(index, max_pos);\n\n\t\t//copy( &values[0], &values[networks->size()], std::ostream_iterator< double >(std::cout, \", \"));\n\t\t//std::cout << std::endl;\n\t}\n\tdelete itNodes;\n\n\tbfs::path final_export_dir_path = export_dir_path / \"final_export\";\n\n\ttry {\n\t\tget_directory(final_export_dir_path);\n\t} catch (DirException &err) {\n\t\tLOG4CXX_FATAL(logger, err.what());\n\t\texit(-1);\n\t}\n\n\t{\n\t\tbfs::path classmap_export_dir_path = final_export_dir_path / \"classmap\";\n\t\ttry {\n\t\t\tget_directory(classmap_export_dir_path);\n\t\t} catch (DirException &err) {\n\t\t\tLOG4CXX_FATAL(logger, err.what());\n\t\t\texit(-1);\n\t\t}\n\n\t\tbfs::path export_dir_pattern = classmap_export_dir_path / \"%06d.bmp\";\n\t\titk::NumericSeriesFileNames::Pointer outputNames = itk::NumericSeriesFileNames::New();\n\t\toutputNames->SetSeriesFormat(export_dir_pattern.native());\n\t\toutputNames->SetStartIndex(0);\n\t\toutputNames->SetEndIndex(depth - 1);\n\n\t\ttypedef itk::ImageSeriesWriter< ImageType, itk::Image< unsigned char, 2 > > WriterType;\n\t\tWriterType::Pointer writer = WriterType::New();\n\t\twriter->SetInput(classification_image);\n\t\twriter->SetFileNames(outputNames->GetFileNames());\n\t\twriter->Update();\n\t}\n\n\tfor(int i = 0; i <= number_of_classifiers; ++i)\n\t{\n\t\tbfs::path final_class_export_dir_path = final_export_dir_path / (i == 0 ? \"rejected\" : pad(i));\n\n\t\ttry {\n\t\t\tget_directory(final_class_export_dir_path);\n\t\t} catch (DirException &err) {\n\t\t\tLOG4CXX_FATAL(logger, err.what());\n\t\t\texit(-1);\n\t\t}\n\n\t\tbfs::path final_class_export_dir_pattern = final_class_export_dir_path / \"%06d.bmp\";\n\t\titk::NumericSeriesFileNames::Pointer outputNames = itk::NumericSeriesFileNames::New();\n\t\toutputNames->SetSeriesFormat(final_class_export_dir_pattern.native());\n\t\toutputNames->SetStartIndex(0);\n\t\toutputNames->SetEndIndex(depth - 1);\n\n\t\ttypedef itk::BinaryThresholdImageFilter< ImageType, ImageType > Thresholder;\n\t\tThresholder::Pointer thresholder = Thresholder::New();\n\t\tthresholder->SetLowerThreshold(i);\n\t\tthresholder->SetUpperThreshold(i);\n\t\tthresholder->SetInput(classification_image);\n\n\t\ttypedef itk::ImageSeriesWriter< ImageType, itk::Image< unsigned char, 2 > > WriterType;\n\t\tWriterType::Pointer writer = WriterType::New();\n\t\twriter->SetInput(thresholder->GetOutput());\n\t\twriter->SetFileNames(outputNames->GetFileNames());\n\t\twriter->Update();\n\t}\n\n\tdelete graph;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "2210bef194d35ab98549a6f5ec84d6dbe633afcf", "size": 21458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Sigill/isgcr", "max_stars_repo_head_hexsha": "3fbca4aeef25be2195885d69dcd89f3669c2602f", "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": "Sigill/isgcr", "max_issues_repo_head_hexsha": "3fbca4aeef25be2195885d69dcd89f3669c2602f", "max_issues_repo_licenses": ["MIT"], "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": "Sigill/isgcr", "max_forks_repo_head_hexsha": "3fbca4aeef25be2195885d69dcd89f3669c2602f", "max_forks_repo_licenses": ["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.9110429448, "max_line_length": 186, "alphanum_fraction": 0.7010438997, "num_tokens": 5511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.19533597995602864}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_LKJ_CORR_LOG_HPP\n#define STAN_MATH_PRIM_MAT_PROB_LKJ_CORR_LOG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/prob/lkj_corr_lpdf.hpp>\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * @deprecated use <code>lkj_corr_lpdf</code>\n */\ntemplate <bool propto, typename T_y, typename T_shape>\nreturn_type_t<T_y, T_shape> lkj_corr_log(\n    const Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic>& y,\n    const T_shape& eta) {\n  return lkj_corr_lpdf<propto, T_y, T_shape>(y, eta);\n}\n\n/**\n * @deprecated use <code>lkj_corr_lpdf</code>\n */\ntemplate <typename T_y, typename T_shape>\ninline return_type_t<T_y, T_shape> lkj_corr_log(\n    const Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic>& y,\n    const T_shape& eta) {\n  return lkj_corr_lpdf<T_y, T_shape>(y, eta);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "c503026c02b4ae6f71fd3067ec3e84da17d27590", "size": 942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/prob/lkj_corr_log.hpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "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/mat/prob/lkj_corr_log.hpp", "max_issues_repo_name": "PhilClemson/math", "max_issues_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "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/mat/prob/lkj_corr_log.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": 26.9142857143, "max_line_length": 64, "alphanum_fraction": 0.7377919321, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.1952854783116638}}
{"text": "#include \"exodus/mdex.h\"\n\n#include \"exodus/errors.h\"\n#include \"exodus/fees.h\"\n#include \"exodus/log.h\"\n#include \"exodus/exodus.h\"\n#include \"exodus/rules.h\"\n#include \"exodus/sp.h\"\n#include \"exodus/tx.h\"\n#include \"exodus/uint256_extensions.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"main.h\"\n#include \"tinyformat.h\"\n#include \"uint256.h\"\n\n#include <univalue.h>\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/rational.hpp>\n\n#include <openssl/sha.h>\n\n#include <assert.h>\n#include <stdint.h>\n\n#include <fstream>\n#include <limits>\n#include <map>\n#include <set>\n#include <string>\n\ntypedef boost::multiprecision::cpp_dec_float_100 dec_float;\ntypedef boost::multiprecision::checked_int128_t int128_t;\n\nusing namespace exodus;\n\n//! Number of digits of unit price\n#define DISPLAY_PRECISION_LEN  50\n\n//! Global map for price and order data\nmd_PropertiesMap exodus::metadex;\n\nmd_PricesMap* exodus::get_Prices(uint32_t prop)\n{\n    md_PropertiesMap::iterator it = metadex.find(prop);\n\n    if (it != metadex.end()) return &(it->second);\n\n    return (md_PricesMap*) NULL;\n}\n\nmd_Set* exodus::get_Indexes(md_PricesMap* p, rational_t price)\n{\n    md_PricesMap::iterator it = p->find(price);\n\n    if (it != p->end()) return &(it->second);\n\n    return (md_Set*) NULL;\n}\n\nenum MatchReturnType\n{\n    NOTHING = 0,\n    TRADED = 1,\n    TRADED_MOREINSELLER,\n    TRADED_MOREINBUYER,\n    ADDED,\n    CANCELLED,\n};\n\nstatic const std::string getTradeReturnType(MatchReturnType ret)\n{\n    switch (ret) {\n        case NOTHING: return \"NOTHING\";\n        case TRADED: return \"TRADED\";\n        case TRADED_MOREINSELLER: return \"TRADED_MOREINSELLER\";\n        case TRADED_MOREINBUYER: return \"TRADED_MOREINBUYER\";\n        case ADDED: return \"ADDED\";\n        case CANCELLED: return \"CANCELLED\";\n        default: return \"* unknown *\";\n    }\n}\n\n// Used by rangeInt64, xToInt64\nstatic bool rangeInt64(const int128_t& value)\n{\n    return (std::numeric_limits<int64_t>::min() <= value && value <= std::numeric_limits<int64_t>::max());\n}\n\n// Used by xToString\nstatic bool rangeInt64(const rational_t& value)\n{\n    return (rangeInt64(value.numerator()) && rangeInt64(value.denominator()));\n}\n\n// Used by CMPMetaDEx::displayUnitPrice\nstatic int64_t xToRoundUpInt64(const rational_t& value)\n{\n    // for integer rounding up: ceil(num / denom) => 1 + (num - 1) / denom\n    int128_t result = int128_t(1) + (value.numerator() - int128_t(1)) / value.denominator();\n\n    assert(rangeInt64(result));\n\n    return result.convert_to<int64_t>();\n}\n\nstd::string xToString(const dec_float& value)\n{\n    return value.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed);\n}\n\nstd::string xToString(const int128_t& value)\n{\n    return strprintf(\"%s\", boost::lexical_cast<std::string>(value));\n}\n\nstd::string xToString(const rational_t& value)\n{\n    if (rangeInt64(value)) {\n        int64_t num = value.numerator().convert_to<int64_t>();\n        int64_t denom = value.denominator().convert_to<int64_t>();\n        dec_float x = dec_float(num) / dec_float(denom);\n        return xToString(x);\n    } else {\n        return strprintf(\"%s / %s\", xToString(value.numerator()), xToString(value.denominator()));\n    }\n}\n\n// find the best match on the market\n// NOTE: sometimes I refer to the older order as seller & the newer order as buyer, in this trade\n// INPUT: property, desprop, desprice = of the new order being inserted; the new object being processed\n// RETURN: \nstatic MatchReturnType x_Trade(CMPMetaDEx* const pnew)\n{\n    const uint32_t propertyForSale = pnew->getProperty();\n    const uint32_t propertyDesired = pnew->getDesProperty();\n    MatchReturnType NewReturn = NOTHING;\n    bool bBuyerSatisfied = false;\n\n    if (exodus_debug_metadex1) PrintToLog(\"%s(%s: prop=%d, desprop=%d, desprice= %s);newo: %s\\n\",\n        __FUNCTION__, pnew->getAddr(), propertyForSale, propertyDesired, xToString(pnew->inversePrice()), pnew->ToString());\n\n    md_PricesMap* const ppriceMap = get_Prices(propertyDesired);\n\n    // nothing for the desired property exists in the market, sorry!\n    if (!ppriceMap) {\n        PrintToLog(\"%s()=%d:%s NOT FOUND ON THE MARKET\\n\", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn));\n        return NewReturn;\n    }\n\n    // within the desired property map (given one property) iterate over the items looking at prices\n    for (md_PricesMap::iterator priceIt = ppriceMap->begin(); priceIt != ppriceMap->end(); ++priceIt) { // check all prices\n        const rational_t sellersPrice = priceIt->first;\n\n        if (exodus_debug_metadex2) PrintToLog(\"comparing prices: desprice %s needs to be GREATER THAN OR EQUAL TO %s\\n\",\n            xToString(pnew->inversePrice()), xToString(sellersPrice));\n\n        // Is the desired price check satisfied? The buyer's inverse price must be larger than that of the seller.\n        if (pnew->inversePrice() < sellersPrice) {\n            continue;\n        }\n\n        md_Set* const pofferSet = &(priceIt->second);\n\n        // at good (single) price level and property iterate over offers looking at all parameters to find the match\n        md_Set::iterator offerIt = pofferSet->begin();\n        while (offerIt != pofferSet->end()) { // specific price, check all properties\n            const CMPMetaDEx* const pold = &(*offerIt);\n            assert(pold->unitPrice() == sellersPrice);\n\n            if (exodus_debug_metadex1) PrintToLog(\"Looking at existing: %s (its prop= %d, its des prop= %d) = %s\\n\",\n                xToString(sellersPrice), pold->getProperty(), pold->getDesProperty(), pold->ToString());\n\n            // does the desired property match?\n            if (pold->getDesProperty() != propertyForSale) {\n                ++offerIt;\n                continue;\n            }\n\n            if (exodus_debug_metadex1) PrintToLog(\"MATCH FOUND, Trade: %s = %s\\n\", xToString(sellersPrice), pold->ToString());\n\n            // match found, execute trade now!\n            const int64_t seller_amountForSale = pold->getAmountRemaining();\n            const int64_t buyer_amountOffered = pnew->getAmountRemaining();\n\n            if (exodus_debug_metadex1) PrintToLog(\"$$ trading using price: %s; seller: forsale=%d, desired=%d, remaining=%d, buyer amount offered=%d\\n\",\n                xToString(sellersPrice), pold->getAmountForSale(), pold->getAmountDesired(), pold->getAmountRemaining(), pnew->getAmountRemaining());\n            if (exodus_debug_metadex1) PrintToLog(\"$$ old: %s\\n\", pold->ToString());\n            if (exodus_debug_metadex1) PrintToLog(\"$$ new: %s\\n\", pnew->ToString());\n\n            ///////////////////////////\n\n            // preconditions\n            assert(0 < pold->getAmountRemaining());\n            assert(0 < pnew->getAmountRemaining());\n            assert(pnew->getProperty() != pnew->getDesProperty());\n            assert(pnew->getProperty() == pold->getDesProperty());\n            assert(pold->getProperty() == pnew->getDesProperty());\n            assert(pold->unitPrice() <= pnew->inversePrice());\n            assert(pnew->unitPrice() <= pold->inversePrice());\n\n            ///////////////////////////\n\n            // First determine how many representable (indivisible) tokens Alice can\n            // purchase from Bob, using Bob's unit price\n            // This implies rounding down, since rounding up is impossible, and would\n            // require more tokens than Alice has\n            arith_uint256 iCouldBuy = (ConvertTo256(pnew->getAmountRemaining()) * ConvertTo256(pold->getAmountForSale())) / ConvertTo256(pold->getAmountDesired());\n\n            int64_t nCouldBuy = 0;\n            if (iCouldBuy < ConvertTo256(pold->getAmountRemaining())) {\n                nCouldBuy = ConvertTo64(iCouldBuy);\n            } else {\n                nCouldBuy = pold->getAmountRemaining();\n            }\n\n            if (nCouldBuy == 0) {\n                if (exodus_debug_metadex1) PrintToLog(\n                        \"-- buyer has not enough tokens for sale to purchase one unit!\\n\");\n                ++offerIt;\n                continue;\n            }\n\n            // If the amount Alice would have to pay to buy Bob's tokens at his price\n            // is fractional, always round UP the amount Alice has to pay\n            // This will always be better for Bob. Rounding in the other direction\n            // will always be impossible, because ot would violate Bob's accepted price\n            arith_uint256 iWouldPay = DivideAndRoundUp((ConvertTo256(nCouldBuy) * ConvertTo256(pold->getAmountDesired())), ConvertTo256(pold->getAmountForSale()));\n            int64_t nWouldPay = ConvertTo64(iWouldPay);\n\n            // If the resulting adjusted unit price is higher than Alice' price, the\n            // orders shall not execute, and no representable fill is made\n            const rational_t xEffectivePrice(nWouldPay, nCouldBuy);\n\n            if (xEffectivePrice > pnew->inversePrice()) {\n                if (exodus_debug_metadex1) PrintToLog(\n                        \"-- effective price is too expensive: %s\\n\", xToString(xEffectivePrice));\n                ++offerIt;\n                continue;\n            }\n\n            const int64_t buyer_amountGot = nCouldBuy;\n            const int64_t seller_amountGot = nWouldPay;\n            const int64_t buyer_amountLeft = pnew->getAmountRemaining() - seller_amountGot;\n            const int64_t seller_amountLeft = pold->getAmountRemaining() - buyer_amountGot;\n\n            if (exodus_debug_metadex1) PrintToLog(\"$$ buyer_got= %d, seller_got= %d, seller_left_for_sale= %d, buyer_still_for_sale= %d\\n\",\n                buyer_amountGot, seller_amountGot, seller_amountLeft, buyer_amountLeft);\n\n            ///////////////////////////\n\n            // postconditions\n            assert(xEffectivePrice >= pold->unitPrice());\n            assert(xEffectivePrice <= pnew->inversePrice());\n            assert(0 <= seller_amountLeft);\n            assert(0 <= buyer_amountLeft);\n            assert(seller_amountForSale == seller_amountLeft + buyer_amountGot);\n            assert(buyer_amountOffered == buyer_amountLeft + seller_amountGot);\n\n            ///////////////////////////\n\n            int64_t buyer_amountGotAfterFee = buyer_amountGot;\n            int64_t tradingFee = 0;\n\n            // strip a 0.05% fee from non-EXODUS pairs if fees are activated\n            if (IsFeatureActivated(FEATURE_FEES, pnew->getBlock())) {\n                if (pold->getProperty() > EXODUS_PROPERTY_TEXODUS && pold->getDesProperty() > EXODUS_PROPERTY_TEXODUS) {\n                    int64_t feeDivider = 2000; // 0.05%\n                    tradingFee = buyer_amountGot / feeDivider;\n\n                    // subtract the fee from the amount the seller will receive\n                    buyer_amountGotAfterFee = buyer_amountGot - tradingFee;\n\n                    // add the fee to the fee cache\n                    p_feecache->AddFee(pnew->getDesProperty(), pnew->getBlock(), tradingFee);\n                } else {\n                    if (exodus_debug_fees) PrintToLog(\"Skipping fee reduction for trade match %s:%s as one of the properties is Omni\\n\", pold->getHash().GetHex(), pnew->getHash().GetHex());\n                }\n            }\n\n            // transfer the payment property from buyer to seller\n            assert(update_tally_map(pnew->getAddr(), pnew->getProperty(), -seller_amountGot, BALANCE));\n            assert(update_tally_map(pold->getAddr(), pold->getDesProperty(), seller_amountGot, BALANCE));\n\n            // transfer the market (the one being sold) property from seller to buyer\n            assert(update_tally_map(pold->getAddr(), pold->getProperty(), -buyer_amountGot, METADEX_RESERVE));\n            assert(update_tally_map(pnew->getAddr(), pnew->getDesProperty(), buyer_amountGotAfterFee, BALANCE));\n\n            NewReturn = TRADED;\n\n            CMPMetaDEx seller_replacement = *pold; // < can be moved into last if block\n            seller_replacement.setAmountRemaining(seller_amountLeft, \"seller_replacement\");\n\n            pnew->setAmountRemaining(buyer_amountLeft, \"buyer\");\n\n            if (0 < buyer_amountLeft) {\n                NewReturn = TRADED_MOREINBUYER;\n            }\n\n            if (0 == buyer_amountLeft) {\n                bBuyerSatisfied = true;\n            }\n\n            if (0 < seller_amountLeft) {\n                NewReturn = TRADED_MOREINSELLER;\n            }\n\n            if (exodus_debug_metadex1) PrintToLog(\"==== TRADED !!! %u=%s\\n\", NewReturn, getTradeReturnType(NewReturn));\n\n            // record the trade in MPTradeList\n            t_tradelistdb->recordMatchedTrade(pold->getHash(), pnew->getHash(), // < might just pass pold, pnew\n                pold->getAddr(), pnew->getAddr(), pold->getDesProperty(), pnew->getDesProperty(), seller_amountGot, buyer_amountGotAfterFee, pnew->getBlock(), tradingFee);\n\n            if (exodus_debug_metadex1) PrintToLog(\"++ erased old: %s\\n\", offerIt->ToString());\n            // erase the old seller element\n            pofferSet->erase(offerIt++);\n\n            // insert the updated one in place of the old\n            if (0 < seller_replacement.getAmountRemaining()) {\n                PrintToLog(\"++ inserting seller_replacement: %s\\n\", seller_replacement.ToString());\n                pofferSet->insert(seller_replacement);\n            }\n\n            if (bBuyerSatisfied) {\n                assert(buyer_amountLeft == 0);\n                break;\n            }\n        } // specific price, check all properties\n\n        if (bBuyerSatisfied) break;\n    } // check all prices\n\n    PrintToLog(\"%s()=%d:%s\\n\", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn));\n\n    return NewReturn;\n}\n\n/**\n * Used for display of unit prices to 8 decimal places at UI layer.\n *\n * Automatically returns unit or inverse price as needed.\n */\nstd::string CMPMetaDEx::displayUnitPrice() const\n{\n     rational_t tmpDisplayPrice;\n     if (getDesProperty() == EXODUS_PROPERTY_EXODUS || getDesProperty() == EXODUS_PROPERTY_TEXODUS) {\n         tmpDisplayPrice = unitPrice();\n         if (isPropertyDivisible(getProperty())) tmpDisplayPrice = tmpDisplayPrice * COIN;\n     } else {\n         tmpDisplayPrice = inversePrice();\n         if (isPropertyDivisible(getDesProperty())) tmpDisplayPrice = tmpDisplayPrice * COIN;\n     }\n\n     // offers with unit prices under 0.00000001 will be excluded from UI layer - TODO: find a better way to identify sub 0.00000001 prices\n     std::string tmpDisplayPriceStr = xToString(tmpDisplayPrice);\n     if (!tmpDisplayPriceStr.empty()) { if (tmpDisplayPriceStr.substr(0,1) == \"0\") return \"0.00000000\"; }\n\n     // we must always round up here - for example if the actual price required is 0.3333333344444\n     // round: 0.33333333 - price is insufficient and thus won't result in a trade\n     // round: 0.33333334 - price will be sufficient to result in a trade\n     std::string displayValue = FormatDivisibleMP(xToRoundUpInt64(tmpDisplayPrice));\n     return displayValue;\n}\n\n/**\n * Used for display of unit prices with 50 decimal places at RPC layer.\n *\n * Note: unit price is no longer always shown in EXODUS and/or inverted\n */\nstd::string CMPMetaDEx::displayFullUnitPrice() const\n{\n    rational_t tempUnitPrice = unitPrice();\n\n    /* Matching types require no action (divisible/divisible or indivisible/indivisible)\n       Non-matching types require adjustment for display purposes\n           divisible/indivisible   : *COIN\n           indivisible/divisible   : /COIN\n    */\n    if ( isPropertyDivisible(getProperty()) && !isPropertyDivisible(getDesProperty()) ) tempUnitPrice = tempUnitPrice*COIN;\n    if ( !isPropertyDivisible(getProperty()) && isPropertyDivisible(getDesProperty()) ) tempUnitPrice = tempUnitPrice/COIN;\n\n    std::string unitPriceStr = xToString(tempUnitPrice);\n    return unitPriceStr;\n}\n\nrational_t CMPMetaDEx::unitPrice() const\n{\n    rational_t effectivePrice;\n    if (amount_forsale) effectivePrice = rational_t(amount_desired, amount_forsale);\n    return effectivePrice;\n}\n\nrational_t CMPMetaDEx::inversePrice() const\n{\n    rational_t inversePrice;\n    if (amount_desired) inversePrice = rational_t(amount_forsale, amount_desired);\n    return inversePrice;\n}\n\nint64_t CMPMetaDEx::getAmountToFill() const\n{\n    // round up to ensure that the amount we present will actually result in buying all available tokens\n    arith_uint256 iAmountNeededToFill = DivideAndRoundUp((ConvertTo256(amount_remaining) * ConvertTo256(amount_desired)), ConvertTo256(amount_forsale));\n    int64_t nAmountNeededToFill = ConvertTo64(iAmountNeededToFill);\n    return nAmountNeededToFill;\n}\n\nint64_t CMPMetaDEx::getBlockTime() const\n{\n    CBlockIndex* pblockindex = chainActive[block];\n    return pblockindex->GetBlockTime();\n}\n\nvoid CMPMetaDEx::setAmountRemaining(int64_t amount, const std::string& label)\n{\n    amount_remaining = amount;\n    PrintToLog(\"update remaining amount still up for sale (%ld %s):%s\\n\", amount, label, ToString());\n}\n\nstd::string CMPMetaDEx::ToString() const\n{\n    return strprintf(\"%s:%34s in %d/%03u, txid: %s , trade #%u %s for #%u %s\",\n        xToString(unitPrice()), addr, block, idx, txid.ToString().substr(0, 10),\n        property, FormatMP(property, amount_forsale), desired_property, FormatMP(desired_property, amount_desired));\n}\n\nvoid CMPMetaDEx::saveOffer(std::ofstream& file, SHA256_CTX* shaCtx) const\n{\n    std::string lineOut = strprintf(\"%s,%d,%d,%d,%d,%d,%d,%d,%s,%d\",\n        addr,\n        block,\n        amount_forsale,\n        property,\n        amount_desired,\n        desired_property,\n        subaction,\n        idx,\n        txid.ToString(),\n        amount_remaining\n    );\n\n    // add the line to the hash\n    SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length());\n\n    // write the line\n    file << lineOut << std::endl;\n}\n\nbool MetaDEx_compare::operator()(const CMPMetaDEx &lhs, const CMPMetaDEx &rhs) const\n{\n    if (lhs.getBlock() == rhs.getBlock()) return lhs.getIdx() < rhs.getIdx();\n    else return lhs.getBlock() < rhs.getBlock();\n}\n\nbool exodus::MetaDEx_INSERT(const CMPMetaDEx& objMetaDEx)\n{\n    // Create an empty price map (to use in case price map for this property does not already exist)\n    md_PricesMap temp_prices;\n    // Attempt to obtain the price map for the property\n    md_PricesMap *p_prices = get_Prices(objMetaDEx.getProperty());\n\n    // Create an empty set of metadex objects (to use in case no set currently exists at this price)\n    md_Set temp_indexes;\n    md_Set *p_indexes = NULL;\n\n    // Prepare for return code\n    std::pair <md_Set::iterator, bool> ret;\n\n    // Attempt to obtain a set of metadex objects for this price from the price map\n    if (p_prices) p_indexes = get_Indexes(p_prices, objMetaDEx.unitPrice());\n    // See if the set was populated, if not no set exists at this price level, use the empty set that we created earlier\n    if (!p_indexes) p_indexes = &temp_indexes;\n\n    // Attempt to insert the metadex object into the set\n    ret = p_indexes->insert(objMetaDEx);\n    if (false == ret.second) return false;\n\n    // If a prices map did not exist for this property, set p_prices to the temp empty price map\n    if (!p_prices) p_prices = &temp_prices;\n\n    // Update the prices map with the new set at this price\n    (*p_prices)[objMetaDEx.unitPrice()] = *p_indexes;\n\n    // Set the metadex map for the property to the updated (or new if it didn't exist) price map\n    metadex[objMetaDEx.getProperty()] = *p_prices;\n\n    return true;\n}\n\n// pretty much directly linked to the ADD TX21 command off the wire\nint exodus::MetaDEx_ADD(const std::string& sender_addr, uint32_t prop, int64_t amount, int block, uint32_t property_desired, int64_t amount_desired, const uint256& txid, unsigned int idx)\n{\n    int rc = METADEX_ERROR -1;\n\n    // Create a MetaDEx object from paremeters\n    CMPMetaDEx new_mdex(sender_addr, block, prop, amount, property_desired, amount_desired, txid, idx, CMPTransaction::ADD);\n    if (exodus_debug_metadex1) PrintToLog(\"%s(); buyer obj: %s\\n\", __FUNCTION__, new_mdex.ToString());\n\n    // Ensure this is not a badly priced trade (for example due to zero amounts)\n    if (0 >= new_mdex.unitPrice()) return METADEX_ERROR -66;\n\n    // Match against existing trades, remainder of the order will be put into the order book\n    if (exodus_debug_metadex3) MetaDEx_debug_print();\n    x_Trade(&new_mdex);\n    if (exodus_debug_metadex3) MetaDEx_debug_print();\n\n    // Insert the remaining order into the MetaDEx maps\n    if (0 < new_mdex.getAmountRemaining()) { //switch to getAmountRemaining() when ready\n        if (!MetaDEx_INSERT(new_mdex)) {\n            PrintToLog(\"%s() ERROR: ALREADY EXISTS, line %d, file: %s\\n\", __FUNCTION__, __LINE__, __FILE__);\n            return METADEX_ERROR -70;\n        } else {\n            // move tokens into reserve\n            assert(update_tally_map(sender_addr, prop, -new_mdex.getAmountRemaining(), BALANCE));\n            assert(update_tally_map(sender_addr, prop, new_mdex.getAmountRemaining(), METADEX_RESERVE));\n\n            if (exodus_debug_metadex1) PrintToLog(\"==== INSERTED: %s= %s\\n\", xToString(new_mdex.unitPrice()), new_mdex.ToString());\n            if (exodus_debug_metadex3) MetaDEx_debug_print();\n        }\n    }\n\n    rc = 0;\n    return rc;\n}\n\nint exodus::MetaDEx_CANCEL_AT_PRICE(const uint256& txid, unsigned int block, const std::string& sender_addr, uint32_t prop, int64_t amount, uint32_t property_desired, int64_t amount_desired)\n{\n    int rc = METADEX_ERROR -20;\n    CMPMetaDEx mdex(sender_addr, 0, prop, amount, property_desired, amount_desired, uint256(), 0, CMPTransaction::CANCEL_AT_PRICE);\n    md_PricesMap* prices = get_Prices(prop);\n    const CMPMetaDEx* p_mdex = NULL;\n\n    if (exodus_debug_metadex1) PrintToLog(\"%s():%s\\n\", __FUNCTION__, mdex.ToString());\n\n    if (exodus_debug_metadex2) MetaDEx_debug_print();\n\n    if (!prices) {\n        PrintToLog(\"%s() NOTHING FOUND for %s\\n\", __FUNCTION__, mdex.ToString());\n        return rc -1;\n    }\n\n    // within the desired property map (given one property) iterate over the items\n    for (md_PricesMap::iterator my_it = prices->begin(); my_it != prices->end(); ++my_it) {\n        rational_t sellers_price = my_it->first;\n\n        if (mdex.unitPrice() != sellers_price) continue;\n\n        md_Set* indexes = &(my_it->second);\n\n        for (md_Set::iterator iitt = indexes->begin(); iitt != indexes->end();) {\n            p_mdex = &(*iitt);\n\n            if (exodus_debug_metadex3) PrintToLog(\"%s(): %s\\n\", __FUNCTION__, p_mdex->ToString());\n\n            if ((p_mdex->getDesProperty() != property_desired) || (p_mdex->getAddr() != sender_addr)) {\n                ++iitt;\n                continue;\n            }\n\n            rc = 0;\n            PrintToLog(\"%s(): REMOVING %s\\n\", __FUNCTION__, p_mdex->ToString());\n\n            // move from reserve to main\n            assert(update_tally_map(p_mdex->getAddr(), p_mdex->getProperty(), -p_mdex->getAmountRemaining(), METADEX_RESERVE));\n            assert(update_tally_map(p_mdex->getAddr(), p_mdex->getProperty(), p_mdex->getAmountRemaining(), BALANCE));\n\n            // record the cancellation\n            bool bValid = true;\n            p_txlistdb->recordMetaDExCancelTX(txid, p_mdex->getHash(), bValid, block, p_mdex->getProperty(), p_mdex->getAmountRemaining());\n\n            indexes->erase(iitt++);\n        }\n    }\n\n    if (exodus_debug_metadex2) MetaDEx_debug_print();\n\n    return rc;\n}\n\nint exodus::MetaDEx_CANCEL_ALL_FOR_PAIR(const uint256& txid, unsigned int block, const std::string& sender_addr, uint32_t prop, uint32_t property_desired)\n{\n    int rc = METADEX_ERROR -30;\n    md_PricesMap* prices = get_Prices(prop);\n    const CMPMetaDEx* p_mdex = NULL;\n\n    PrintToLog(\"%s(%d,%d)\\n\", __FUNCTION__, prop, property_desired);\n\n    if (exodus_debug_metadex3) MetaDEx_debug_print();\n\n    if (!prices) {\n        PrintToLog(\"%s() NOTHING FOUND\\n\", __FUNCTION__);\n        return rc -1;\n    }\n\n    // within the desired property map (given one property) iterate over the items\n    for (md_PricesMap::iterator my_it = prices->begin(); my_it != prices->end(); ++my_it) {\n        md_Set* indexes = &(my_it->second);\n\n        for (md_Set::iterator iitt = indexes->begin(); iitt != indexes->end();) {\n            p_mdex = &(*iitt);\n\n            if (exodus_debug_metadex3) PrintToLog(\"%s(): %s\\n\", __FUNCTION__, p_mdex->ToString());\n\n            if ((p_mdex->getDesProperty() != property_desired) || (p_mdex->getAddr() != sender_addr)) {\n                ++iitt;\n                continue;\n            }\n\n            rc = 0;\n            PrintToLog(\"%s(): REMOVING %s\\n\", __FUNCTION__, p_mdex->ToString());\n\n            // move from reserve to main\n            assert(update_tally_map(p_mdex->getAddr(), p_mdex->getProperty(), -p_mdex->getAmountRemaining(), METADEX_RESERVE));\n            assert(update_tally_map(p_mdex->getAddr(), p_mdex->getProperty(), p_mdex->getAmountRemaining(), BALANCE));\n\n            // record the cancellation\n            bool bValid = true;\n            p_txlistdb->recordMetaDExCancelTX(txid, p_mdex->getHash(), bValid, block, p_mdex->getProperty(), p_mdex->getAmountRemaining());\n\n            indexes->erase(iitt++);\n        }\n    }\n\n    if (exodus_debug_metadex3) MetaDEx_debug_print();\n\n    return rc;\n}\n\n/**\n * Scans the orderbook and remove everything for an address.\n */\nint exodus::MetaDEx_CANCEL_EVERYTHING(const uint256& txid, unsigned int block, const std::string& sender_addr, unsigned char ecosystem)\n{\n    int rc = METADEX_ERROR -40;\n\n    PrintToLog(\"%s()\\n\", __FUNCTION__);\n\n    if (exodus_debug_metadex2) MetaDEx_debug_print();\n\n    PrintToLog(\"<<<<<<\\n\");\n\n    for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {\n        unsigned int prop = my_it->first;\n\n        // skip property, if it is not in the expected ecosystem\n        if (isMainEcosystemProperty(ecosystem) && !isMainEcosystemProperty(prop)) continue;\n        if (isTestEcosystemProperty(ecosystem) && !isTestEcosystemProperty(prop)) continue;\n\n        PrintToLog(\" ## property: %u\\n\", prop);\n        md_PricesMap& prices = my_it->second;\n\n        for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {\n            rational_t price = it->first;\n            md_Set& indexes = it->second;\n\n            PrintToLog(\"  # Price Level: %s\\n\", xToString(price));\n\n            for (md_Set::iterator it = indexes.begin(); it != indexes.end();) {\n                PrintToLog(\"%s= %s\\n\", xToString(price), it->ToString());\n\n                if (it->getAddr() != sender_addr) {\n                    ++it;\n                    continue;\n                }\n\n                rc = 0;\n                PrintToLog(\"%s(): REMOVING %s\\n\", __FUNCTION__, it->ToString());\n\n                // move from reserve to balance\n                assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE));\n                assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE));\n\n                // record the cancellation\n                bool bValid = true;\n                p_txlistdb->recordMetaDExCancelTX(txid, it->getHash(), bValid, block, it->getProperty(), it->getAmountRemaining());\n\n                indexes.erase(it++);\n            }\n        }\n    }\n    PrintToLog(\">>>>>>\\n\");\n\n    if (exodus_debug_metadex2) MetaDEx_debug_print();\n\n    return rc;\n}\n\n/**\n * Scans the orderbook and removes every all-pair order\n */\nint exodus::MetaDEx_SHUTDOWN_ALLPAIR()\n{\n    int rc = 0;\n    PrintToLog(\"%s()\\n\", __FUNCTION__);\n    for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {\n        md_PricesMap& prices = my_it->second;\n        for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {\n            md_Set& indexes = it->second;\n            for (md_Set::iterator it = indexes.begin(); it != indexes.end();) {\n                if (it->getDesProperty() > EXODUS_PROPERTY_TEXODUS && it->getProperty() > EXODUS_PROPERTY_TEXODUS) { // no EXODUS/TEXODUS side to the trade\n                    PrintToLog(\"%s(): REMOVING %s\\n\", __FUNCTION__, it->ToString());\n                    // move from reserve to balance\n                    assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE));\n                    assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE));\n                    indexes.erase(it++);\n                }\n            }\n        }\n    }\n    return rc;\n}\n\n/**\n * Scans the orderbook and removes every order\n */\nint exodus::MetaDEx_SHUTDOWN()\n{\n    int rc = 0;\n    PrintToLog(\"%s()\\n\", __FUNCTION__);\n    for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {\n        md_PricesMap& prices = my_it->second;\n        for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {\n            md_Set& indexes = it->second;\n            for (md_Set::iterator it = indexes.begin(); it != indexes.end();) {\n                PrintToLog(\"%s(): REMOVING %s\\n\", __FUNCTION__, it->ToString());\n                // move from reserve to balance\n                assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE));\n                assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE));\n                indexes.erase(it++);\n            }\n        }\n    }\n    return rc;\n}\n\n// searches the metadex maps to see if a trade is still open\n// allows search to be optimized if propertyIdForSale is specified\nbool exodus::MetaDEx_isOpen(const uint256& txid, uint32_t propertyIdForSale)\n{\n    for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {\n        if (propertyIdForSale != 0 && propertyIdForSale != my_it->first) continue;\n        md_PricesMap & prices = my_it->second;\n        for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {\n            md_Set & indexes = (it->second);\n            for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) {\n                CMPMetaDEx obj = *it;\n                if( obj.getHash().GetHex() == txid.GetHex() ) return true;\n            }\n        }\n    }\n    return false;\n}\n\n/**\n * Returns a string describing the status of a trade\n *\n */\nstd::string exodus::MetaDEx_getStatusText(int tradeStatus)\n{\n    switch (tradeStatus) {\n        case TRADE_OPEN: return \"open\";\n        case TRADE_OPEN_PART_FILLED: return \"open part filled\";\n        case TRADE_FILLED: return \"filled\";\n        case TRADE_CANCELLED: return \"cancelled\";\n        case TRADE_CANCELLED_PART_FILLED: return \"cancelled part filled\";\n        case TRADE_INVALID: return \"trade invalid\";\n        default: return \"unknown\";\n    }\n}\n\n/**\n * Returns the status of a MetaDEx trade\n *\n */\nint exodus::MetaDEx_getStatus(const uint256& txid, uint32_t propertyIdForSale, int64_t amountForSale, int64_t totalSold)\n{\n    // NOTE: If the calling code is already aware of the total amount sold, pass the value in to this function to avoid duplication of\n    //       work.  If the calling code doesn't know the amount, leave default (-1) and we will calculate it from levelDB lookups.\n    if (totalSold == -1) {\n        UniValue tradeArray(UniValue::VARR);\n        int64_t totalReceived;\n        t_tradelistdb->getMatchingTrades(txid, propertyIdForSale, tradeArray, totalSold, totalReceived);\n    }\n\n    // Return a \"trade invalid\" status if the trade was invalidated at parsing/interpretation (eg insufficient funds)\n    if (!getValidMPTX(txid)) return TRADE_INVALID;\n\n    // Calculate and return the status of the trade via the amount sold and open/closed attributes.\n    if (MetaDEx_isOpen(txid, propertyIdForSale)) {\n        if (totalSold == 0) {\n            return TRADE_OPEN;\n        } else {\n            return TRADE_OPEN_PART_FILLED;\n        }\n    } else {\n        if (totalSold == 0) {\n            return TRADE_CANCELLED;\n        } else if (totalSold < amountForSale) {\n            return TRADE_CANCELLED_PART_FILLED;\n        } else {\n            return TRADE_FILLED;\n        }\n    }\n}\n\nvoid exodus::MetaDEx_debug_print(bool bShowPriceLevel, bool bDisplay)\n{\n    PrintToLog(\"<<<\\n\");\n    for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {\n        uint32_t prop = my_it->first;\n\n        PrintToLog(\" ## property: %u\\n\", prop);\n        md_PricesMap& prices = my_it->second;\n\n        for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {\n            rational_t price = it->first;\n            md_Set& indexes = it->second;\n\n            if (bShowPriceLevel) PrintToLog(\"  # Price Level: %s\\n\", xToString(price));\n\n            for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) {\n                const CMPMetaDEx& obj = *it;\n\n                if (bDisplay) PrintToConsole(\"%s= %s\\n\", xToString(price), obj.ToString());\n                else PrintToLog(\"%s= %s\\n\", xToString(price), obj.ToString());\n            }\n        }\n    }\n    PrintToLog(\">>>\\n\");\n}\n\n/**\n * Locates a trade in the MetaDEx maps via txid and returns the trade object\n *\n */\nconst CMPMetaDEx* exodus::MetaDEx_RetrieveTrade(const uint256& txid)\n{\n    for (md_PropertiesMap::iterator propIter = metadex.begin(); propIter != metadex.end(); ++propIter) {\n        md_PricesMap & prices = propIter->second;\n        for (md_PricesMap::iterator pricesIter = prices.begin(); pricesIter != prices.end(); ++pricesIter) {\n            md_Set & indexes = pricesIter->second;\n            for (md_Set::iterator tradesIter = indexes.begin(); tradesIter != indexes.end(); ++tradesIter) {\n                if (txid == (*tradesIter).getHash()) return &(*tradesIter);\n            }\n        }\n    }\n    return (CMPMetaDEx*) NULL;\n}\n", "meta": {"hexsha": "f50f640bc6ef33f94e4b88d8c9828d9f0d7454ba", "size": 33636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/exodus/mdex.cpp", "max_stars_repo_name": "zcoindev/zcoin", "max_stars_repo_head_hexsha": "7dca1ee7fa3d14c174f8406d65785920207b38d6", "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/exodus/mdex.cpp", "max_issues_repo_name": "zcoindev/zcoin", "max_issues_repo_head_hexsha": "7dca1ee7fa3d14c174f8406d65785920207b38d6", "max_issues_repo_licenses": ["MIT"], "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/exodus/mdex.cpp", "max_forks_repo_name": "zcoindev/zcoin", "max_forks_repo_head_hexsha": "7dca1ee7fa3d14c174f8406d65785920207b38d6", "max_forks_repo_licenses": ["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.5252643948, "max_line_length": 190, "alphanum_fraction": 0.6387501487, "num_tokens": 8484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1952450449565267}}
{"text": "#include <iostream>\n#include <string>\n#include <math.h>\n#include <cstdlib>\n#include <stdbool.h>\n#include <vector>\n//#include <boost/thread/thread.hpp>\n#include <unistd.h>\n#include <thread>\n#include <time.h>\n#include <fstream>\n//#include <boost/system/error_code.hpp>\n////////////////////////////////////////////////////////////////////////////////\n// MAC: Comment in srandomdev(); comment out rand() (one occurrence)\n// LINUX: Comment out srandomdev(); comment in ran() \n///////////////////////////////////////\n// TO RUN WITH C++11\n// -Comment out all boost:: lines, commenting in the std:: version next to them.\n// -Comment out boost in #include statements, and comment in #include <thread>\n\n// TO RUN WITHOUT C++11\n// -Install boost thread and system libraries\n// -Comment in all places using boost::, while commenting out the adjacent std:: versions.\n// -Comment in the two boost #include lines, and comment out the #include <thread> line.\n///////////////////////////////////////////////////////////////////////////////\n\n\n#define DIVISION 600 //number of clock pulses per quarter note; for header\n\n//#include <unistd.h>\n//#define SLEEP( milliseconds ) usleep( (unsigned long) (milliseconds * 1000.0) )\n\n\nstd::vector<int> factors;\nstd::vector<int> sorted_factors;\nstd::vector<int> dupes_out;\nstd::vector<int> to_run (13, 0);\n\nint low;\nint med;\nint high;\n\nint chords[3][7];\n\nint this_key = 21;\nint this_chord = 0;\n\n\n\nvoid randomize(){\n    //srandomdev();\n    //srand (time(NULL));\n    int number = random() % 100;\n    //std::cout<<\"Random number: \"<<number<<\"\\n\";\n    int tenth = number/10;\n    if(tenth<2){\n        this_chord = 0;\n    }\n    else if(tenth==2 || tenth==3){\n        this_chord = 1;\n    }\n    else if(tenth==4){\n        this_chord = 2;\n    }\n    else if(tenth==5){\n        this_chord = 3;\n    }\n    else if(tenth==6){\n        //this_chord = 4;\n        this_chord = 6;\n    }\n    else if(tenth==7 || tenth==8){\n        this_chord = 5;\n    }\n    else{\n        this_chord = 6;\n    }\n    //std::cout<<\"This chord: \"<<this_chord<<\"\\n\";\n    low = this_key+chords[0][this_chord];\n    med = this_key+chords[1][this_chord];\n    high = this_key+chords[2][this_chord];\n\n}\nvoid one(){//channel 11 in 0-index, 12 in 1-index\n    std::fstream channel_12 (\"ch12.csv\", std::fstream::out | std::fstream::trunc);//These are one-indexed!\n\n    //for A: use 33 or 45\n    if(to_run[1]==1){\n\n        int iterations = 0;\n        int elapsed = 0;\n        channel_12<<\"11, 0, Start_track\\n11, 0, Program_c, 11, \"<<35<<\"\\n\";\n        //std::cout<<\"in one\\n\";\n\n        while(iterations<23){\n            //std::cout<<\"bass iterations: \"<<iterations<<\"\\n\";\n            randomize();\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n            elapsed += 400;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n            elapsed += 200;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n            elapsed += 200;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 80\\n\";\n            elapsed += 400;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 0\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<med<<\", 80\\n\";\n            elapsed += 400;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<med<<\", 0\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 80\\n\";\n            elapsed += 200;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 0\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<med<<\", 80\\n\";\n            elapsed += 200;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<med<<\", 0\\n\";\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 80\\n\";\n            elapsed += 400;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 0\\n\";\n\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 80\\n\";\n            elapsed += 400;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 0\\n\";\n\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 80\\n\";\n            elapsed += 200;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 0\\n\";\n\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<med<<\", 80\\n\";\n            elapsed += 200;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<med<<\", 0\\n\";\n\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n            elapsed += 200;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n            elapsed += 200;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n            \n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 80\\n\";\n            elapsed += 400;\n            channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<high<<\", 0\\n\";\n\n            iterations++;\n        }\n        low = this_key+12;\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n        elapsed += 400;\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n        elapsed += 400;\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n        elapsed += 400;\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n        elapsed += 400;\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 80\\n\";\n        elapsed += 1600;\n        channel_12<<\"11, \"<<elapsed<<\", Note_on_c, 11, \"<<low<<\", 0\\n\";\n\n        channel_12<<\"11, \"<<elapsed<<\", End_track\\n\";\n    }\n    channel_12.close();\n\n}\nvoid two(){//channel 1 in 0-index, 2 in 1-index\n    std::fstream channel_3 (\"ch3.csv\", std::fstream::out | std::fstream::trunc);\n    if(to_run[2]==1){\n        //std::cout<<\"two should go...\";\n        int iterations = 0;\n        int elapsed = 0;\n        //elapsed_1.push_back(elapsed);\n        channel_3<<\"2, 0, Start_track\\n2, 0, Program_c, 2, \"<<11<<\"\\n\";\n\n        //channel_3<<\"3, 0, Control_c, 2, 7, 89\\n3, 0, Control_c, 2, 10, 64\\n3, 0, Control_c, 2, 91, 70\\n\";\n\n\n        //std::cout<<\"in one\\n\";\n        elapsed += 4800*2;\n        int key = this_key;\n        while(iterations<6){\n            key = this_key;\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<36+key<<\", 60\\n\";\n            elapsed += 2000;\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<36+key<<\", 0\\n\";\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<43+key<<\", 60\\n\";\n            elapsed += 400;\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<43+key<<\", 0\\n\";\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<34+key<<\", 60\\n\";\n            elapsed += 50;\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<41+key<<\", 60\\n\";\n            elapsed += 50;\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<38+key<<\", 60\\n\";\n            elapsed += 7100;//2300+4800\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<34+key<<\", 0\\n\";\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<41+key<<\", 0\\n\";\n            channel_3<<\"2, \"<<elapsed<<\", Note_on_c, 2, \"<<38+key<<\", 0\\n\";\n        \n            iterations++;\n        }\n        channel_3<<\"2, \"<<elapsed<<\", End_track\\n\";\n    }\n    channel_3.close();\n}\nvoid three(){\n    std::fstream channel_4 (\"ch4.csv\", std::fstream::out | std::fstream::trunc);\n    if(to_run[3]==1){\n        int iterations = 0;\n        int elapsed = 0;\n        channel_4<<\"3, 0, Start_track\\n3, 0, Program_c, 3, \"<<50<<\"\\n\";\n        elapsed += 4800*3;\n        int key = this_key;\n        int chord = this_chord;\n        while(iterations<8){\n            key = this_key;\n            chord = this_chord;\n            channel_4<<\"3, \"<<elapsed<<\", Note_on_c, 3, \"<<24+key<<\", 80\\n\";\n            elapsed += 2400;\n            channel_4<<\"3, \"<<elapsed<<\", Note_on_c, 3, \"<<24+key<<\", 0\\n\";\n            \n            channel_4<<\"3, \"<<elapsed<<\", Note_on_c, 3, \"<<12+chords[2][chord]+key<<\", 80\\n\";\n            elapsed +=7200;\n            channel_4<<\"3, \"<<elapsed<<\", Note_on_c, 3, \"<<12+chords[2][chord]+key<<\", 0\\n\";\n\n            iterations++;\n        }\n        channel_4<<\"3, \"<<elapsed<<\", End_track\\n\";\n    }\n    channel_4.close();\n}\nvoid nine(){\n    std::fstream channel_5 (\"ch5.csv\", std::fstream::out | std::fstream::trunc);\n    if(to_run[9]==1){\n        int iterations = 0;\n        int elapsed = 0;\n        channel_5<<\"4, 0, Start_track\\n4, 0, Program_c, 4, \"<<26<<\"\\n\";\n        elapsed += 4800*4;\n        while(iterations<8){\n            for(int a=0; a<4; a++){\n                channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<59<<\", 60\\n\";\n                elapsed += 300;\n                channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<59<<\", 0\\n\";\n            }\n            channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<55<<\", 60\\n\";\n            elapsed += 300;\n            channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<59<<\", 60\\n\";\n            elapsed += 300;\n            channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<55<<\", 0\\n\";\n            channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<59<<\", 0\\n\";\n\n            channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<62<<\", 60\\n\";\n            elapsed += 600;\n            channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<62<<\", 0\\n\";\n\n            \n            for(int b=0; b<8; b++){\n                channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<55<<\", 60\\n\";\n                elapsed += 300;\n                channel_5<<\"4, \"<<elapsed<<\", Note_on_c, 4, \"<<55<<\", 0\\n\";\n            }\n            elapsed += 300;\n\n            iterations++;\n        }\n        channel_5<<\"4, \"<<elapsed<<\", End_track\\n\";\n    }\n    channel_5.close();\n}\nvoid five(){\n    std::fstream channel_6 (\"ch6.csv\", std::fstream::out | std::fstream::trunc);\n    if(to_run[5]==1){\n        int elapsed = 0;\n        int iterations = 0;\n        channel_6<<\"5, 0, Start_track\\n5, 0, Program_c, 5, \"<<77<<\"\\n\";\n        elapsed += 4800*5;\n        int key = this_key;\n        int chord = this_chord;\n        int value, new_value;\n        while(iterations<8){\n            value = random() % 3;\n            new_value = value+1;\n            if(new_value>3){\n                new_value=0;\n            }\n            key = this_key;\n            chord = this_chord;\n            channel_6<<\"5, \"<<elapsed<<\", Note_on_c, 5, \"<<key+chords[value][chord]+12<<\", 80\\n\";\n            channel_6<<\"5, \"<<elapsed<<\", Note_on_c, 5, \"<<key+chords[new_value][chord]+12<<\", 80\\n\";\n            int interval = random () % 3;\n            interval = (interval+1)*400;\n            elapsed += interval;\n\n            channel_6<<\"5, \"<<elapsed<<\", Note_on_c, 5, \"<<key+chords[value][chord]+12<<\", 0\\n\";\n            channel_6<<\"5, \"<<elapsed<<\", Note_on_c, 5, \"<<key+chords[new_value][chord]+12<<\", 0\\n\";\n            elapsed += 3600;\n\n            iterations++;\n        }\n        channel_6<<\"5, \"<<elapsed<<\", End_track\\n\";\n    }\n    channel_6.close();\n}\nvoid twelve(){\n    std::fstream channel_7 (\"ch7.csv\", std::fstream::out | std::fstream::trunc);\n    //a lot like 5; just vary the values longer. (gives a distribution determined by the chord)\n    if(to_run[12]==1){\n        int iterations = 0;\n        int elapsed = 0;\n        channel_7<<\"6, 0, Start_track\\n6, 0, Program_c, 6, \"<<61<<\"\\n\";\n        elapsed += 4800*3;\n        int key = this_key;\n        int chord = this_chord;\n        while(iterations<8){\n            int value = random() % 3;\n            int new_value = (value+1)%3;\n            //if(new_value==4){new_value=0;} \n            key = this_key;\n            chord = this_chord;\n            channel_7<<\"6, \"<<elapsed<<\", Note_on_c, 6, \"<<key+chords[value][chord]+12<<\", 80\\n\";\n            elapsed += 300;\n            channel_7<<\"6, \"<<elapsed<<\", Note_on_c, 6, \"<<key+chords[new_value][chord]+12<<\", 80\\n\";\n            int interval = random () % 3;\n            interval = (interval+1)*200;\n            elapsed += interval;\n\n            channel_7<<\"6, \"<<elapsed<<\", Note_on_c, 6, \"<<key+chords[value][chord]+12<<\", 0\\n\";\n            elapsed += (interval*3);\n            channel_7<<\"6, \"<<elapsed<<\", Note_on_c, 6, \"<<key+chords[new_value][chord]+12<<\", 0\\n\";\n            elapsed += 3600;\n\n            iterations++;\n        }\n        channel_7<<\"6, \"<<elapsed<<\", End_track\\n\";\n    }\n    channel_7.close();\n}\nvoid ten(){\n    std::fstream channel_8 (\"ch8.csv\", std::fstream::out | std::fstream::trunc);\n    if(to_run[10]==1){\n        int iterations = 0;\n        int elapsed = 0;\n        channel_8<<\"7, 0, Start_track\\n7, 0, Program_c, 7, \"<<26<<\"\\n\";\n        elapsed += 4800*6;\n        int key = this_key;\n        while(iterations<3){\n            key = this_key;\n            for(int a=0; a<5; a++){\n                channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 100\\n\";\n                elapsed += 200;\n                channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 0\\n\";\n            }\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 100\\n\";\n\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<36+key<<\", 100\\n\";\n            elapsed += 200;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<36+key<<\", 0\\n\";\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 0\\n\";\n\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 100\\n\";\n            elapsed += 200;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<43+key<<\", 100\\n\";\n            elapsed += 200;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 0\\n\";\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<43+key<<\", 0\\n\";\n\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<43+key<<\", 100\\n\";\n            elapsed += 200;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<43+key<<\", 0\\n\";\n\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 100\\n\";\n            elapsed += 200;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 0\\n\";\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 100\\n\";\n            elapsed += 200;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 0\\n\";\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 100\\n\";\n            elapsed += 200;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 0\\n\";\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 100\\n\";\n            elapsed += 200;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 0\\n\";\n\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<43+key<<\", 100\\n\";\n            elapsed += 400;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<43+key<<\", 0\\n\";\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<36+key<<\", 100\\n\";\n            elapsed += 400;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<36+key<<\", 0\\n\";\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 100\\n\";\n            elapsed += 400;\n            channel_8<<\"7, \"<<elapsed<<\", Note_on_c, 7, \"<<40+key<<\", 0\\n\";\n            elapsed += 14400;\n\n            iterations++;\n        }\n        channel_8<<\"7, \"<<elapsed<<\", End_track\\n\";\n    }\n    channel_8.close();\n}\nvoid eight(){\n    std::fstream channel_11 (\"ch11.csv\", std::fstream::out | std::fstream::trunc);\n    if(to_run[8]==1){\n        int iterations = 0;\n        int elapsed = 0;\n        channel_11<<\"10, 0, Start_track\\n10, 0, Program_c, 10, \"<<116<<\"\\n\";\n        elapsed += 2400*5;\n        int key = this_key;\n        int chord = this_chord;\n        while(iterations<18){\n            int value = random() % 3;\n            int new_value = (value+1)%3;\n            //if(new_value==4){new_value=0;} \n            key = this_key;\n            chord = this_chord;\n            channel_11<<\"10, \"<<elapsed<<\", Note_on_c, 10, \"<<key+chords[value][chord]+12<<\", 80\\n\";\n            channel_11<<\"10, \"<<elapsed<<\", Note_on_c, 10, \"<<key+chords[new_value][chord]+12<<\", 80\\n\";\n            elapsed += 400;\n\n            iterations++;\n        }\n        channel_11<<\"10, \"<<elapsed<<\", End_track\\n\";\n    }\n    channel_11.close();\n}\n\nvoid mandatory(){\n    std::fstream channel_9 (\"ch9.csv\", std::fstream::out | std::fstream::trunc);\n    //std::cout<<\"in mandatory thread\\n\";\n    //shifts the key\n    int elapsed = 0;\n    elapsed += 2400*26;\n    //std::cout<<\"key changed\\n\";\n    //this_key += 7;\n    elapsed += 2400*8;\n    //this_key -= 7;\n    //std::cout<<\"key changed again\\n\";\n    elapsed += 2400;\n\n    channel_9<<\"8, 0, Start_track\\n8, 0, Program_c, 8, \"<<119<<\"\\n\";\n\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<59<<\", 30\\n\";\n    elapsed += 200;\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<59<<\", 40\\n\";\n    elapsed += 150;\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<59<<\", 50\\n\";\n    elapsed += 120;\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<59<<\", 60\\n\";\n    elapsed += 90;\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<59<<\", 70\\n\";\n    elapsed += 90;\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<59<<\", 80\\n\";\n    elapsed += 90;\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<59<<\", 90\\n\";\n    elapsed += 90;\n    for(int b=100; b>19; b-=20){\n        for(int a=0; a<4; a++){\n            channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<59<<\", \"<<b<<\"\\n\";\n            elapsed += 100;\n        }\n    }\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<46<<\", 80\\n\";\n    elapsed += 100;\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<46<<\", 0\\n\";\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<51<<\", 80\\n\";\n    elapsed += 100;\n    channel_9<<\"8, \"<<elapsed<<\", Note_on_c, 8, \"<<51<<\", 0\\n\";\n\n    channel_9<<\"8, \"<<elapsed<<\", End_track\\n\";\n    channel_9.close();\n}\nvoid percussion(){\n    std::fstream channel_10 (\"ch10.csv\", std::fstream::out | std::fstream::trunc);\n    int elapsed = 0;\n    elapsed += 2400;\n    channel_10<<\"9, 0, Start_track\\n\";\n    int iterations = 0;\n    while(iterations < 30){\n        channel_10<<\"9, \"<<elapsed<<\", Note_on_c, 9, \"<<36<<\", 60\\n\";\n        elapsed += 400;\n        channel_10<<\"9, \"<<elapsed<<\", Note_on_c, 9, \"<<36<<\", 60\\n\";\n        elapsed += 400;\n        channel_10<<\"9, \"<<elapsed<<\", Note_on_c, 9, \"<<38<<\", 60\\n\";\n        elapsed += 400;\n        channel_10<<\"9, \"<<elapsed<<\", Note_on_c, 9, \"<<36<<\", 60\\n\";\n        elapsed += 400;\n        channel_10<<\"9, \"<<elapsed<<\", Note_on_c, 9, \"<<36<<\", 60\\n\";\n        elapsed += 400;\n        channel_10<<\"9, \"<<elapsed<<\", Note_on_c, 9, \"<<38<<\", 60\\n\";\n        elapsed += 200;\n        channel_10<<\"9, \"<<elapsed<<\", Note_on_c, 9, \"<<38<<\", 60\\n\";\n        elapsed += 200;\n        channel_10<<\"9, \"<<elapsed<<\", Note_on_c, 9, \"<<38<<\", 60\\n\";\n        elapsed += 400;\n\n        iterations ++;\n    }\n    channel_10<<\"9, \"<<elapsed<<\", End_track\\n\";\n    channel_10.close();\n}\nvoid chord_init(){//based from the octave below the desired one, for the -1s.\n    //chords[3][7]\n    chords[0][0] =12;\n    chords[1][0] =16;\n    chords[2][0] =19;\n    \n    chords[0][1] =12;\n    chords[1][1] =17;\n    chords[2][1] =21;\n    \n    chords[0][2] =11;\n    chords[1][2] =17;\n    chords[2][2] =19;\n    \n    chords[0][3] =11;\n    chords[1][3] =14;\n    chords[2][3] =19;\n    \n    chords[0][4] =12;\n    chords[1][4] =15;\n    chords[2][4] =19;\n    \n    chords[0][5] =12;\n    chords[1][5] =16;\n    chords[2][5] =22;\n    \n    chords[0][6] =14;\n    chords[1][6] =17;\n    chords[2][6] =21;\n    \n    low = 45;\n    med = low;\n    high = low;\n    \n}\nvoid sort(){\n    for(int y = 0; y<100; y++){\n        for(unsigned int x=0; x<factors.size(); x++){\n            if(factors[x] == y){\n                sorted_factors.push_back(y);\n            }\n        }\n    }\n}\nvoid remove_dupes(){\n    dupes_out.push_back(sorted_factors[0]);\n    for(unsigned int x=1; x<sorted_factors.size(); x++){\n        if(sorted_factors[x]!=sorted_factors[x-1]){\n            dupes_out.push_back(sorted_factors[x]);\n        }\n    }\n}\nint main(){\n    chord_init();\n    srand (time(NULL));\n\n    bool input_done = false;\n    int input;\n    while(!input_done){\n        std::cout<<\"Input a number of 6 digits or less\\n\";\n        std::string in;\n        std::getline(std::cin, in);\n        //int input = stoi(in, NULL, 10);\n        input = atoi(in.c_str());\n        if(input/1000000 == 0){\n            input_done = true;\n        }\n    }\n    std::cout<<input<<\"\\nFactors:\\n\";\n    bool factoring_done = false;\n    int divisor = 1;\n    int count_factors = 0;\n    while(!factoring_done){\n        if (input % divisor == 0) {\n            std::cout<<divisor<<\"\\n\";\n            factors.push_back(divisor);\n            divisor ++;\n            count_factors++;\n        }\n        else{\n            std::cout<<\"\\t\"<<divisor<<\" is not a factor.\\n\";\n            divisor++;\n        }\n        if (divisor > sqrt(input)) {\n        //if(divisor>input/2){\n            factoring_done = true;\n        }\n    }\n    std::cout<<\"Number of factors for \"<<input<<\": \"<<count_factors<<\"\\n\";\n    std::cout<<\"Factors: \";\n    for (unsigned int i = 0; i < factors.size(); i++){\n        //std::cout<<factors[i]<<\", \";\n        //factors[i] = factors[i] % 100;\n        std::cout<<factors[i]<<\", \";\n    }\n    std::cout<<\"\\n\";\n    sort();\n    std::cout<<\"Sorted: \";\n\n    for (unsigned int j = 0; j < sorted_factors.size(); j++){\n        std::cout<<sorted_factors[j]<<\", \";\n    }\n    std::cout<<\"\\n\";\n    remove_dupes();\n    std::cout<<\"Duplicates removed.\\n \";\n    fflush(stdout);\n\n\n    //boost::thread t_mandatory(mandatory);\n    std::thread t_mandatory(mandatory);\n    //std::cout<<\"thread initiated\\n\";\n    \n    for (unsigned int k = 0; k < dupes_out.size(); k++){\n        std::cout<<dupes_out[k]<<\", \";\n        to_run[dupes_out[k]] = 1;\n    }\n    std::cout<<\"\\n\";\n    for(unsigned int n = 0; n<to_run.size(); n++){\n        //std::cout<<to_run[n]<<\",\";\n    }\n    //std::cout<<\"\\n\";\n\n\n\n\n    //boost::thread t_one(one);\n    std::thread t_one(one);\n\n    //boost::thread t_two(two);\n    std::thread t_two(two);\n\n    //boost::thread t_three(three);\n    std::thread t_three(three);\n\n    //boost::thread t_five(five);\n    std::thread t_five(five);\n\n    //boost::thread t_eight(eight);\n    std::thread t_eight(eight);\n\n    //boost::thread t_nine(nine);\n    std::thread t_nine(nine);\n\n    //boost::thread t_ten(ten);\n    std::thread t_ten(ten);\n\n    //boost::thread t_twelve(twelve);\n    std::thread t_twelve(twelve);\n\n    //boost::thread t_else(percussion, dupes_out[k]);\n    std::thread t_else(percussion);\n            \n\n    t_mandatory.join();//9\n    t_one.join();//12 CHANNEL (1-index)\n    t_two.join();//3\n    t_three.join();//4\n    t_five.join();//6\n    t_eight.join();//11\n    t_nine.join();//5\n    t_ten.join();//8\n    t_twelve.join();//7\n    t_else.join();//10\n\n    int count_threads = 2;\n    for(int a=0; a<13; a++){\n        if(to_run[a]==1){\n            if(a==1 || a==2 || a==3 || a==5 || a==8 || a==9 || a==10 || a==12){\n                count_threads++;\n                //std::cout<<\"count_threads: \"<<count_threads<<\"\\n\";\n            }\n        }\n    }\n\n    std::cout<<\"\\n\";\n    std::cout<<\"Number of unique factors after mod 100: \"<<dupes_out.size()<<\"\\n\";\n    \n    //std::cout<<\"back to file ops\\n\";\n    std::fstream main_file (\"final_test.csv\", std::fstream::in | std::fstream::out | std::fstream::trunc);\n\n    main_file << \"0, 0, Header, 1, \"<< 1+count_threads <<\", \" << DIVISION << std::endl;\n\n    main_file<<\"1, 0, Start_track\\n\";\n    main_file<<\"1, 0, Title_t, \\\"Test program\\\"\\n\";\n    main_file<<\"1, 0, Time_signature, 4, 2, 24, 8\\n\";\n    main_file<<\"1, 0, Tempo, 600000\\n\";\n    main_file<<\"1, 0, End_track\\n\";\n\n    \n\n    std::ifstream ch_3 (\"ch3.csv\", std::fstream::in);\n    if(to_run[2]==1){\n        main_file << ch_3.rdbuf();\n    }\n    ch_3.close();\n\n    std::fstream ch_4 (\"ch4.csv\", std::fstream::in);\n    if(to_run[3]==1){\n        main_file << ch_4.rdbuf();\n    }\n    ch_4.close();\n\n    std::fstream ch_5 (\"ch5.csv\", std::fstream::in);\n    if(to_run[9]==1){\n        main_file << ch_5.rdbuf();\n    }\n    ch_5.close();\n\n    std::fstream ch_6 (\"ch6.csv\", std::fstream::in);\n    if(to_run[5]==1){\n        main_file << ch_6.rdbuf();\n    }\n    ch_6.close();\n\n    std::fstream ch_7 (\"ch7.csv\", std::fstream::in);\n    if(to_run[12]==1){\n        main_file << ch_7.rdbuf();\n    }\n    ch_7.close();\n\n    std::fstream ch_8 (\"ch8.csv\", std::fstream::in);\n    if(to_run[10]==1){\n        main_file << ch_8.rdbuf();\n    }\n    ch_8.close();\n\n    std::fstream ch_9 (\"ch9.csv\", std::fstream::in);\n    main_file << ch_9.rdbuf();\n    ch_9.close();\n\n    std::fstream ch_10 (\"ch10.csv\", std::fstream::in);\n    main_file << ch_10.rdbuf();\n    ch_10.close();\n\n    std::fstream ch_11 (\"ch11.csv\", std::fstream::in);\n    if(to_run[8]==1){\n        main_file << ch_11.rdbuf();\n    }\n    ch_11.close();\n\n    std::fstream ch_12 (\"ch12.csv\", std::fstream::in);\n    if(to_run[1]==1){\n        main_file << ch_12.rdbuf();\n    }\n    ch_12.close();\n\n    main_file << \"0, 0, End_of_file\\n\";\n    main_file.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "4a2145636b54c2de8dd71999826749a90ffc0abe", "size": 25685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/version6.cpp", "max_stars_repo_name": "valerie-sd/mumt306project", "max_stars_repo_head_hexsha": "21e441da94ef9c4bde5d329f35534622b90e6afb", "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/version6.cpp", "max_issues_repo_name": "valerie-sd/mumt306project", "max_issues_repo_head_hexsha": "21e441da94ef9c4bde5d329f35534622b90e6afb", "max_issues_repo_licenses": ["MIT"], "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/version6.cpp", "max_forks_repo_name": "valerie-sd/mumt306project", "max_forks_repo_head_hexsha": "21e441da94ef9c4bde5d329f35534622b90e6afb", "max_forks_repo_licenses": ["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.8852242744, "max_line_length": 107, "alphanum_fraction": 0.4905197586, "num_tokens": 8030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.19524503701306717}}
{"text": "/*\n\nCopyright (c) 2005-2022, 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 _CML_noble_varghese_kohl_noble_1998_basic_with_sac_\n#define _CML_noble_varghese_kohl_noble_1998_basic_with_sac_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include <cmath>\n#include <cassert>\n#include \"AbstractCardiacCell.hpp\"\n#include \"Exception.hpp\"\n#include \"AbstractStimulusFunction.hpp\"\n#include \"OdeSystemInformation.hpp\"\n\n\n/**\n *  The Noble98 'Basic' model, but hand-altered to add a stretch activation channel ionic\n *  current, which is dependent on the stretch the cell is under (an additional member variable\n *  which can be set be the user/mechanics solver\n */\nclass CML_noble_varghese_kohl_noble_1998_basic_with_sac : public AbstractCardiacCell\n{\n    friend class boost::serialization::access;\n    /**\n     * Checkpointing.\n     * @param archive\n     * @param version\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & mStretch;\n        archive & boost::serialization::base_object<AbstractCardiacCell>(*this);\n    }\nprivate:\n\n    /** The stretch the cell is under - affects the stretch-activated-channel ionic current */\n    double mStretch;\n\npublic:\n    /**\n     * Constructor.\n     * @param pSolver  ODE solver to use\n     * @param pIntracellularStimulus  intracellular stimulus to apply\n     */\n    CML_noble_varghese_kohl_noble_1998_basic_with_sac(boost::shared_ptr<AbstractIvpOdeSolver> pSolver,\n                                                      boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus);\n\n    /** Destructor. */\n    ~CML_noble_varghese_kohl_noble_1998_basic_with_sac();\n\n    /** @return the total ionic current\n     * @param pStateVariables  state variable vector; if not given, use cell's internal state\n     */\n    double GetIIonic(const std::vector<double>* pStateVariables=NULL);\n\n    /**\n     * Evaluate the RHS of this cell's ODE system.\n     * @param var_environment__time  current simulation time\n     * @param rY  state variable vector\n     * @param rDY  will be filled in with the derivatives\n     */\n    void EvaluateYDerivatives(double var_environment__time,\n                              const std::vector<double> &rY,\n                              std::vector<double> &rDY);\n\n    /**\n     *  Set the stretch (overloaded)\n     *  @param stretch stretch\n     */\n    void SetStretch(double stretch)\n    {\n        assert(stretch > 0.0);\n        mStretch = stretch;\n    }\n\n    /**\n     *  @return the stretch\n     */\n    double GetStretch()\n    {\n        return mStretch;\n    }\n\n    /**\n     * Get the intracellular calcium concentration\n     *\n     * @return the intracellular calcium concentration\n     */\n    double GetIntracellularCalciumConcentration()\n    {\n        return mStateVariables[16];\n    }\n};\n\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(CML_noble_varghese_kohl_noble_1998_basic_with_sac)\n\nnamespace boost\n{\n    namespace serialization\n    {\n        /**\n         * Avoid the need for a default constructor.\n         * @param ar\n         * @param t\n         * @param fileVersion\n         */\n        template<class Archive>\n        inline void save_construct_data(\n            Archive & ar, const CML_noble_varghese_kohl_noble_1998_basic_with_sac * t, const unsigned int fileVersion)\n        {\n            const boost::shared_ptr<AbstractIvpOdeSolver> p_solver = t->GetSolver();\n            const boost::shared_ptr<AbstractStimulusFunction> p_stimulus = t->GetStimulusFunction();\n            ar << p_solver;\n            ar << p_stimulus;\n        }\n\n        /**\n         * Avoid the need for a default constructor.\n         * @param ar\n         * @param t\n         * @param fileVersion\n         */\n        template<class Archive>\n        inline void load_construct_data(\n            Archive & ar, CML_noble_varghese_kohl_noble_1998_basic_with_sac * t, const unsigned int fileVersion)\n        {\n            boost::shared_ptr<AbstractIvpOdeSolver> p_solver;\n            boost::shared_ptr<AbstractStimulusFunction> p_stimulus;\n            ar >> p_solver;\n            ar >> p_stimulus;\n            ::new(t)CML_noble_varghese_kohl_noble_1998_basic_with_sac(p_solver, p_stimulus);\n        }\n    }\n}\n\n#endif\n", "meta": {"hexsha": "f53cf4a37d9e0a1707b2e414a36ccc077671dc7f", "size": 5934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/odes/ionicmodels/NobleVargheseKohlNoble1998WithSac.hpp", "max_stars_repo_name": "stu-l/Chaste", "max_stars_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "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": "heart/src/odes/ionicmodels/NobleVargheseKohlNoble1998WithSac.hpp", "max_issues_repo_name": "stu-l/Chaste", "max_issues_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "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": "heart/src/odes/ionicmodels/NobleVargheseKohlNoble1998WithSac.hpp", "max_forks_repo_name": "stu-l/Chaste", "max_forks_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "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.3005780347, "max_line_length": 122, "alphanum_fraction": 0.697842939, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.19522597421863327}}
{"text": "#pragma once\n\n#include \"FaceClassificationResult.hpp\"\n#include \"Persistence/FlsDatabase.hpp\"\n#include \"Resource/UserResource.hpp\"\n\n#include <memory>\n#include <opencv2/core/hal/interface.h>\n#include <dlib/svm/kernel.h>\n#include <dlib/svm/function.h>\n\nnamespace Fls\n{\n    struct UserResource;\n\n    class FaceClassifier\n    {\n    public:\n        void init(const std::shared_ptr<FlsDatabase>& database);\n\n        std::vector<FaceClassificationResult> classify(const UserResource* userResource, \n            const std::vector<std::vector<float>>& embeddedFaces);\n        int classify(const std::vector<float>& faceEmbeddings) const;\n    private:\n        typedef dlib::matrix<double, 0, 1> Sample;\n        typedef dlib::linear_kernel<Sample> LinearKernel;\n        typedef dlib::vector_normalizer<Sample> Normalizer;\n        typedef dlib::multiclass_linear_decision_function<LinearKernel, int> DecisionFunction;\n        typedef dlib::normalized_function<DecisionFunction> Classifier;\n\n        void train();\n        std::vector<FaceClassificationResult> namePredictions(const std::vector<int>& predictions) const;\n\n        std::atomic_bool mInitialized{ false };\n        std::future<void> mInitializedFuture;\n\n        std::shared_ptr<FlsDatabase> mDatabase;\n        Classifier mClassifier;\n        float mConfidenceThreshold{ 0.4f };\n\n        int64 mLastFrameId{ 0 };\n        std::vector<FaceClassificationResult> mLastFrameClassificationResult;\n    };\n}\n", "meta": {"hexsha": "7b2baad32f7bd76d3ceb2eea4b34738fe3d56a1c", "size": 1447, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Detectors/FaceClassifier.hpp", "max_stars_repo_name": "maciejjaskiewicz/FacelinkStudio", "max_stars_repo_head_hexsha": "4bcb4ed06932546e58af4a01ee2b17e3dc45f366", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-11T02:40:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T02:40:32.000Z", "max_issues_repo_path": "src/Detectors/FaceClassifier.hpp", "max_issues_repo_name": "maciejjaskiewicz/FacelinkStudio", "max_issues_repo_head_hexsha": "4bcb4ed06932546e58af4a01ee2b17e3dc45f366", "max_issues_repo_licenses": ["MIT"], "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/Detectors/FaceClassifier.hpp", "max_forks_repo_name": "maciejjaskiewicz/FacelinkStudio", "max_forks_repo_head_hexsha": "4bcb4ed06932546e58af4a01ee2b17e3dc45f366", "max_forks_repo_licenses": ["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.1555555556, "max_line_length": 105, "alphanum_fraction": 0.7090532135, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19522597421863325}}
{"text": "#ifndef HOPS_LINEARPROGRAMCLPIMPL_HPP\n#define HOPS_LINEARPROGRAMCLPIMPL_HPP\n\n#include <Eigen/Core>\n#include \"LinearProgram.hpp\"\n\n#ifdef HOPS_CLP_FOUND\n\n#include <coin/ClpSimplex.hpp>\n\nnamespace hops {\n    class LinearProgramClpImpl : public LinearProgram {\n    public:\n        LinearProgramClpImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b);\n\n        LinearProgramClpImpl(const LinearProgramClpImpl &other);\n\n        LinearProgramClpImpl &operator=(const LinearProgramClpImpl &other);\n\n        LinearProgramSolution solve(const Eigen::VectorXd &objective) const override;\n\n        std::tuple<Eigen::MatrixXd, Eigen::VectorXd> removeRedundantConstraints(double tolerance) override;\n\n        LinearProgramSolution computeChebyshevCenter() const override;\n\n        std::vector<long> computeUnconstrainedDimensions() const override;\n\n        std::tuple<Eigen::MatrixXd, Eigen::VectorXd>\n        addBoxConstraintsToUnconstrainedDimensions(double lb, double ub) override;\n\n    private:\n        mutable ClpSimplex model;\n    };\n}\n\n#else //HOPS_CLP_FOUND\n\nnamespace hops {\n    class LinearProgramClpImpl : public LinearProgram {\n    public:\n        LinearProgramClpImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b) : LinearProgram(A, b) {\n            throw std::runtime_error(\"HOPS did not find CLP during compilation.\");\n        }\n\n        [[nodiscard]] LinearProgramSolution solve(const Eigen::VectorXd &) const override {\n            throw std::runtime_error(\"HOPS did not find CLP during compilation.\");\n        }\n\n        std::tuple<Eigen::MatrixXd, Eigen::VectorXd> removeRedundantConstraints(double) override {\n            throw std::runtime_error(\"HOPS did not find CLP during compilation.\");\n        }\n\n        [[nodiscard]] LinearProgramSolution computeChebyshevCenter() const override {\n            throw std::runtime_error(\"HOPS did not find CLP during compilation.\");\n        }\n\n        [[nodiscard]] std::vector<long> computeUnconstrainedDimensions() const override {\n            throw std::runtime_error(\"HOPS did not find CLP during compilation.\");\n        }\n\n        std::tuple<Eigen::MatrixXd, Eigen::VectorXd>\n        addBoxConstraintsToUnconstrainedDimensions(double, double) override {\n            throw std::runtime_error(\"HOPS did not find CLP during compilation.\");\n        }\n    };\n}\n\n#endif //HOPS_CLP_FOUND\n#endif //HOPS_LINEARPROGRAMCLPIMPL_HPP\n", "meta": {"hexsha": "15e74510614561a1f800ed74ae8796b69f84959e", "size": 2381, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/LinearProgram/LinearProgramClpImpl.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/LinearProgram/LinearProgramClpImpl.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/LinearProgram/LinearProgramClpImpl.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": 34.0142857143, "max_line_length": 107, "alphanum_fraction": 0.7030659387, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19522596689034008}}
{"text": "#include \"graph_map/ndt/ndt_map_type.h\"\n#include <boost/serialization/export.hpp>\nBOOST_CLASS_EXPORT(perception_oru::libgraphMap::NDTMapType)\nnamespace perception_oru{\nnamespace libgraphMap{\n  using namespace std;\n\n  using namespace perception_oru;\n\n  NDTMapType::NDTMapType( MapParamPtr paramptr) : MapType(paramptr){\n    NDTMapParamPtr param = boost::dynamic_pointer_cast< NDTMapParam >(paramptr);//Should not be NULL\n    if(param!=NULL){\n      resolution_=param ->resolution_;\n      map_ = new perception_oru::NDTMap(new perception_oru::LazyGrid(resolution_));\n      map_->initialize(0.0,0.0,0.0,param->sizex_,param->sizey_,param->sizez_);\n    }\n    else\n      cerr<<\"Cannot create instance of NDTmapHMT\"<<std::endl;\n  }\n  NDTMapType::~NDTMapType(){}\n\n  void NDTMapType::update(const Eigen::Affine3d &Tsensor,pcl::PointCloud<pcl::PointXYZ> &cloud, bool simple){//update map, cloud is the scan, Tsensor is the pose where the scan was aquired.\n\n    if(initialized_ && enable_mapping_){\n      Eigen::Vector3d localMapSize(2*max_range_,2*max_range_,sizez_);\n      if (!simple) {\n        map_->addPointCloudMeanUpdate(Tsensor.translation(),cloud,localMapSize, 1e5, 25, sizez_, 0.06);\n      }\n      else {\n        map_->addPointCloudSimple(cloud, sizez_);\n        map_->computeNDTCells();\n      }\n    }\n    else if(!initialized_){\n      InitializeMap(Tsensor,cloud, simple);\n      initialized_ = true;\n    }\n  }\n\n  void NDTMapType::update(const Eigen::Affine3d &Tsensor,pcl::PointCloud<velodyne_pointcloud::PointXYZIR> &cloud, bool simple){//update map, cloud is the scan, Tsensor is the pose where the scan was aquired.\n\n    cerr << \"TODO: implement update for point type PointXYZIR - will convert to PointXYZ for now\" << endl;\n    pcl::PointCloud<pcl::PointXYZ> cloud_xyz;\n    pcl::copyPointCloud(cloud, cloud_xyz);\n    update(Tsensor, cloud_xyz, simple);\n  }\n\n  void NDTMapType::InitializeMap(const Eigen::Affine3d &Tsensor,pcl::PointCloud<pcl::PointXYZ> &cloud, bool simple){\n    cout<<\"initialize map\"<<endl;\n    if (!simple) {\n      map_->addPointCloud(Tsensor.translation(),cloud, 0.1, 100.0, 0.1);\n      map_->computeNDTCells(CELL_UPDATE_MODE_SAMPLE_VARIANCE, 1e5, 255, Tsensor.translation(), 0.1);\n    }\n    else {\n      map_->addPointCloudSimple(cloud, sizez_);\n      map_->computeNDTCells();\n    }\n  }\n  bool NDTMapType::CompoundMapsByRadius(MapTypePtr target,const Affine3d &T_source,const Affine3d &T_target, double radius){\n\n    Affine3d Tdiff=Affine3d::Identity();\n    Tdiff=T_source.inverse()*T_target;\n    pcl::PointXYZ center_pcl(Tdiff.translation()(0),Tdiff.translation()(1),Tdiff.translation()(2));\n    if( NDTMapPtr targetPtr=boost::dynamic_pointer_cast<NDTMapType>(target) ){\n      cout<<\"dynamic casted pointer\"<<endl;\n      if(resolution_!=targetPtr->resolution_)//checking if source and target have same resolution, they shoould have.\n        return false;\n\n      if(radius==-1)//if radius is not defined, match rcenter_pcladius to size of new map\n        radius=targetPtr->sizex_<targetPtr->sizey_? targetPtr->sizex_/2:targetPtr->sizey_/2;\n\n      int neighboors=radius/resolution_;\n      cout<<\"neighboors cells to search through=\"<<neighboors<<endl;\n      std::vector<NDTCell*>cells= map_->getCellsForPoint(center_pcl,neighboors,true);\n      cout<<\"cells to transfer:\"<<cells.size()<<endl;\n      Tdiff=T_source.inverse()*T_target;\n      cout<<\"centerpoint in prev map frame=\\n\"<<Tdiff.translation()<<endl;\n\n      for(int i=0;i<cells.size();i++){\n        Eigen::Matrix3d cov=Tdiff.inverse().linear()*cells[i]->getCov()*Tdiff.linear();\n        Eigen::Vector3d mean=Tdiff.inverse()*cells[i]->getMean();\n        targetPtr->GetNDTMap()->addDistributionToCell(cov,mean,cells[i]->getN());\n      }\n\n    }\n\n  }\n  std::string NDTMapType::ToString(){\n    stringstream ss;\n    ss<<MapType::ToString()<<\"NDT Map Type:\"<<endl;\n    ss<<\"resolution:\"<<resolution_<<endl;\n    ss<<\"resolution local factor:\"<<resolution_local_factor_<<endl;\n  // TODO sensor_range_ is not used at the moment.\n    ss<<\"maximum sensor range (not used):\"<<sensor_range_<<endl;\n    ss<<\"nb active cells:\"<<map_->numberOfActiveCells() << endl;\n    //ss<<\"NDTMap:\"<<map_->ToString()<<endl;\n    return ss.str();\n  }\n\n}\n}\n", "meta": {"hexsha": "a6e808faa94d9242f69fce4ff4fe35c4b6373cca", "size": 4203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/graph_map/src/ndt/ndt_map_type.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/graph_map/src/ndt/ndt_map_type.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/graph_map/src/ndt/ndt_map_type.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": 41.2058823529, "max_line_length": 207, "alphanum_fraction": 0.6937901499, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19522596689034005}}
{"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#include <boost/algorithm/string.hpp>\n#include <vw/Cartography/Datum.h>\n#include <vw/Math/Functions.h>\n\n\nvw::cartography::Datum::Datum(std::string const& name,\n                              std::string const& spheroid_name,\n                              std::string const& meridian_name,\n                              double semi_major_axis,\n                              double semi_minor_axis,\n                              double meridian_offset)\n  : m_name(name),\n    m_spheroid_name(spheroid_name),\n    m_meridian_name(meridian_name),\n    m_semi_major_axis(semi_major_axis),\n    m_semi_minor_axis(semi_minor_axis),\n    m_meridian_offset(meridian_offset),\n    m_geocentric(false)\n{\n  std::ostringstream strm;\n  strm << \"+a=\" << semi_major_axis << \" +b=\" << semi_minor_axis;\n  m_proj_str = strm.str();\n}\n\nvoid vw::cartography::Datum::set_well_known_datum( std::string const& name ) {\n  m_meridian_name = \"Greenwich\";\n  m_geocentric = false;\n\n  std::string up_name = boost::to_upper_copy(name);\n\n  m_meridian_offset = 0;\n  if (up_name == \"WGS84\" || up_name == \"WGS_1984\") {\n    m_name            = \"WGS_1984\";\n    m_spheroid_name   = \"WGS 84\";\n    m_semi_major_axis = 6378137.0;\n    m_semi_minor_axis = 6356752.31424518;\n    m_proj_str        = \"+ellps=WGS84 +datum=WGS84\";\n    return;\n  }\n\n  if (up_name == \"WGS72\" || up_name == \"WGS_1972\") {\n    m_name            = \"WGS_1972\";\n    m_spheroid_name   = \"WGS 72\";\n    m_semi_major_axis = 6378135.0;\n    m_semi_minor_axis = 6356750.5;\n    m_proj_str        = \"+ellps=WGS72 +towgs84=0,0,4.5,0,0,0.554,0.2263\";\n    return;\n  }\n\n  if (up_name == \"NAD83\" ||\n      up_name == boost::to_upper_copy(std::string(\"North_American_Datum_1983\"))) {\n    m_name            = \"North_American_Datum_1983\";\n    m_spheroid_name   = \"GRS 1980\";\n    m_semi_major_axis = 6378137;\n    m_semi_minor_axis = 6356752.31414036;\n    m_proj_str        = \"+ellps=GRS80 +datum=NAD83\";\n    return;\n  }\n\n  if (up_name == \"NAD27\" ||\n      up_name == boost::to_upper_copy(std::string(\"North_American_Datum_1927\"))) {\n    m_name            = \"North_American_Datum_1927\";\n    m_spheroid_name   = \"Clarke 1866\";\n    m_semi_major_axis = 6378206.4;\n    m_semi_minor_axis = 6356583.8;\n    m_proj_str        = \"+ellps=clrk66 +datum=NAD27\";\n    return;\n  }\n\n  if (up_name == \"D_MOON\") {\n    m_name            = \"D_MOON\";\n    m_spheroid_name   = \"MOON\";\n    m_meridian_name   = \"Reference Meridian\";\n    m_semi_major_axis = m_semi_minor_axis = 1737400;\n    m_meridian_offset = 0.0;\n    m_proj_str        = \"+a=1737400 +b=1737400\";\n    return;\n  }\n\n  if (up_name == \"D_MARS\") {\n    m_name            = \"D_MARS\";\n    m_spheroid_name   = \"MARS\";\n    m_meridian_name   = \"Reference Meridian\";\n    m_semi_major_axis = m_semi_minor_axis = 3396190;\n    m_meridian_offset = 0.0;\n    m_proj_str        = \"+a=3396190 +b=3396190\";\n    return;\n  }\n\n  vw::vw_throw( vw::InputErr() << \"Unknown datum string \\\"\" << name << \"\\\"!\");\n}\n\nvoid vw::cartography::Datum::set_semi_major_axis(double val) {\n  m_semi_major_axis = val;\n  std::ostringstream strm;\n  strm << \"+a=\" << m_semi_major_axis << \" +b=\" << m_semi_minor_axis;\n  if (m_geocentric)\n    strm << \" +geoc\";\n  m_proj_str = strm.str();\n}\n\nvoid vw::cartography::Datum::set_semi_minor_axis(double val) {\n  m_semi_minor_axis = val;\n  std::ostringstream strm;\n  strm << \"+a=\" << m_semi_major_axis << \" +b=\" << m_semi_minor_axis;\n  if (m_geocentric)\n    strm << \" +geoc\";\n  m_proj_str = strm.str();\n}\n\n// return meridian radius of curvature.  NOT geocentric radius\ndouble vw::cartography::Datum::radius(double /*lon*/, double lat) const {\n  // Optimize in the case of spherical datum\n  if (m_semi_major_axis == m_semi_minor_axis) {\n    return m_semi_major_axis;\n  }\n\n  // Bi-axial Ellpisoid datum\n  double a = m_semi_major_axis;\n  double b = m_semi_minor_axis;\n  double t = atan((a/b) * tan(lat * M_PI / 180.0));\n  double x = a * cos(t);\n  double y = b * sin(t);\n  return sqrt(x*x + y*y);\n}\n\ndouble vw::cartography::Datum::geocentric_latitude(double lat) const {\n   // Optimize in the case of spherical datum\n  if (m_semi_major_axis == m_semi_minor_axis) {\n    return m_semi_major_axis;\n  }\n\n  // Bi-axial Ellpisoid datum\n  // http://mathworld.wolfram.com/GeocentricLatitude.html\n  double a  = m_semi_major_axis;\n  double b  = m_semi_minor_axis;\n  double a2 = a * a;\n  double b2 = b * b;\n  double e2 = (a2 - b2) / a2;\n  return atan((1-e2)*tan(lat * M_PI / 180.0));\n\n}\n\ndouble vw::cartography::Datum::radius_of_curvature(double /*lon*/, double lat) const {\n  // Optimize in the case of spherical datum\n  if (m_semi_major_axis == m_semi_minor_axis) {\n    return m_semi_major_axis;\n  }\n\n  // Bi-axial Ellpisoid datum\n  double a    = m_semi_major_axis;\n  double b    = m_semi_minor_axis;\n  double a2   = a * a;\n  double b2   = b * b;\n  double e2   = (a2 - b2) / a2;\n  double slat = sin(M_PI/180*lat);\n  return a / sqrt(1.0 - e2*slat*slat);\n}\n\n// return meridian radius of curvature.  NOT geocentric radius\ndouble vw::cartography::Datum::geocentric_radius(double /*lon*/, double lat, double alt) const {\n  // Optimize in the case of spherical datum\n  if (m_semi_major_axis == m_semi_minor_axis) {\n    return m_semi_major_axis + alt;\n  }\n  double a    = m_semi_major_axis;\n  double b    = m_semi_minor_axis;\n  double a2   = a * a;\n  double b2   = b * b;\n  double e2   = (a2 - b2) / a2;\n  double rlat = lat * (M_PI/180);\n  double slat = sin( rlat );\n  double clat = cos( rlat );\n  double Rn   = a / sqrt(1.0-e2*slat*slat) + alt;\n\n  return sqrt(Rn*Rn*(clat*clat + (1-e2)*(1-e2)*slat*slat));\n}\n\ndouble vw::cartography::Datum::inverse_flattening() const {\n  return 1.0 / (1.0 - m_semi_minor_axis / m_semi_major_axis);\n}\n\nvw::Matrix3x3 vw::cartography::Datum::lonlat_to_ned_matrix( vw::Vector2 const& lonlat) const {\n  double lon = lonlat.x();\n  double lat = lonlat.y();\n  if ( lat < -90 ) lat = -90;\n  if ( lat >  90 ) lat =  90;\n\n  double rlon = (lon + m_meridian_offset) * (M_PI/180);\n  double rlat = lat * (M_PI/180);\n  double slat = sin( rlat );\n  double clat = cos( rlat );\n  double slon = sin( rlon );\n  double clon = cos( rlon );\n\n  Matrix3x3 R;\n\n  R(0,0) = -slat*clon;\n  R(0,1) = -slat*slon;\n  R(0,2) = clat;\n  R(1,0) = -slon;\n  R(1,1) = clon;\n  R(1,2) = 0.0;\n  R(2,0) = -clon*clat;\n  R(2,1) = -slon*clat;\n  R(2,2) = -slat;\n\n  return R;\n}\n\nvw::Vector3 vw::cartography::Datum::geodetic_to_cartesian( vw::Vector3 const& llh ) const {\n  double a  = m_semi_major_axis;\n  double b  = m_semi_minor_axis;\n  double a2 = a * a;\n  double b2 = b * b;\n  double e2 = (a2 - b2) / a2;\n\n  double lat = llh.y();\n  if ( lat < -90 ) lat = -90;\n  if ( lat >  90 ) lat = 90;\n\n  double rlon = (llh.x() + m_meridian_offset) * (M_PI/180);\n  double rlat = lat * (M_PI/180);\n  double slat = sin( rlat );\n  double clat = cos( rlat );\n  double slon = sin( rlon );\n  double clon = cos( rlon );\n  double radius = a / sqrt(1.0-e2*slat*slat);\n\n  return Vector3( (radius+llh.z()) * clat * clon,\n                  (radius+llh.z()) * clat * slon,\n                  (radius*(1-e2)+llh.z()) * slat );\n}\n\n// This algorithm is a non-iterative algorithm from \"An analytical\n// method to transform geocentric into geodetic coordinates\" by Hugues\n// Vermeille, Journal of Geodesy 2011.\n//\n// This is an improvement over the 1988/Proj4's implementation as it's\n// a smidgen faster and it still works near the center of the datum.\nvw::Vector3 vw::cartography::Datum::cartesian_to_geodetic( vw::Vector3 const& xyz ) const {\n  const double a2 = m_semi_major_axis * m_semi_major_axis;\n  const double b2 = m_semi_minor_axis * m_semi_minor_axis;\n  const double e2 = 1 - b2 / a2;\n  const double e4 = e2 * e2;\n\n  double xy_dist = sqrt( xyz[0] * xyz[0] + xyz[1] * xyz[1] );\n  double p = ( xyz[0] * xyz[0] + xyz[1] * xyz[1] ) / a2;\n  double q = ( 1 - e2 ) * xyz[2] * xyz[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(xyz[2]) < std::numeric_limits<double>::epsilon() ) {\n    // On the equator plane\n    llh[1] = 0;\n    llh[2] = norm_2( xyz ) - m_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] = -m_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 + xyz[2] * xyz[2];\n    llh[2] = ( k + e2 - 1 ) * sqrt( dist_2 ) / k;\n    llh[1] = 2 * atan2( xyz[2], sqrt( dist_2 ) + D );\n  }\n\n  if ( xy_dist + xyz[0] > ( sqrt(2) - 1 ) * xyz[1] ) {\n    // Longitude is between -135 and 135\n    llh[0] = 360.0 * atan2( xyz[1], xy_dist + xyz[0] ) / M_PI;\n  } else if ( xy_dist + xyz[1] < ( sqrt(2) + 1 ) * xyz[0] ) {\n    // Longitude is between -225 and 45\n    llh[0] = - 90.0 + 360.0 * atan2( xyz[0], xy_dist - xyz[1] ) / M_PI;\n  } else {\n    // Longitude is between -45 and 225\n    llh[0] = 90.0 - 360.0 * atan2( xyz[0], xy_dist + xyz[1] ) / M_PI;\n  }\n  llh[0] -= m_meridian_offset;\n  llh[1] *= 180.0 / M_PI;\n\n  return llh;\n}\n\nstd::ostream& vw::cartography::operator<<( std::ostream& os, vw::cartography::Datum const& datum ) {\n  os << \"Geodetic Datum --> Name: \" << datum.name() << \"  Spheroid: \" << datum.spheroid_name()\n     << \"  Semi-major: \" << datum.semi_major_axis()\n     << \"  Semi-minor: \" << datum.semi_minor_axis()\n     << \"  Meridian: \"   << datum.meridian_name()\n     << \"  at \"          << datum.meridian_offset();\n  return os;\n}\n\n// Free associated functions\n\nvw::Vector3\nvw::cartography::datum_intersection(double semi_major_axis, double semi_minor_axis,\n                                    vw::Vector3 camera_ctr, vw::Vector3 camera_vec) {\n\n  // The datum is a spheroid. To simplify the calculations, scale\n  // everything in such a way that the spheroid becomes a\n  // sphere. Scale back at the end of computation.\n\n  double z_scale = semi_major_axis / semi_minor_axis;\n  camera_ctr.z() *= z_scale;\n  camera_vec.z() *= z_scale;\n  camera_vec = normalize(camera_vec);\n  double radius_2 = semi_major_axis * semi_major_axis;\n  double alpha = -dot_prod(camera_ctr, camera_vec );\n  vw::Vector3 projection = camera_ctr + alpha*camera_vec;\n  if ( norm_2_sqr(projection) > radius_2 ) {\n    // did not intersect\n    return vw::Vector3();\n  }\n\n  alpha -= sqrt( radius_2 -\n                 norm_2_sqr(projection) );\n  vw::Vector3 intersection = camera_ctr + alpha * camera_vec;\n  intersection.z() /= z_scale;\n  return intersection;\n}\n\n// Intersect the ray back-projected from the camera with the datum.\nvw::Vector3\nvw::cartography::datum_intersection( vw::cartography::Datum const& datum,\n                                     vw::Vector3 camera_ctr, vw::Vector3 camera_vec) {\n  return vw::cartography::datum_intersection(datum.semi_major_axis(), datum.semi_minor_axis(),\n                                             camera_ctr, camera_vec);\n}\n", "meta": {"hexsha": "4e2d86bb10788d24ad1bbe866356e279198e3efe", "size": 12677, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Cartography/Datum.cc", "max_stars_repo_name": "mdhancher/visionworkbench", "max_stars_repo_head_hexsha": "d2074e1186a81777e64000a62c4f6cd9a47d3c36", "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/vw/Cartography/Datum.cc", "max_issues_repo_name": "mdhancher/visionworkbench", "max_issues_repo_head_hexsha": "d2074e1186a81777e64000a62c4f6cd9a47d3c36", "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/Datum.cc", "max_forks_repo_name": "mdhancher/visionworkbench", "max_forks_repo_head_hexsha": "d2074e1186a81777e64000a62c4f6cd9a47d3c36", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-26T00:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T00:44:27.000Z", "avg_line_length": 33.9865951743, "max_line_length": 100, "alphanum_fraction": 0.6195472115, "num_tokens": 4192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37022538564692026, "lm_q1q2_score": 0.19522596322619348}}
{"text": "#include \"solver.h\"\n\n#include <algorithm>\n#include <boost/functional/hash.hpp>\n#include <boost/mpi.hpp>\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/environment.hpp>\n#include <boost/serialization/utility.hpp>\n#include <chrono>\n#include <clocale>\n#include <cmath>\n#include <cstdio>\n#include <fstream>\n#include <iostream>\n#include <list>\n#include <mutex>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include \"big_unordered_map.h\"\n#include \"constants.h\"\n#include \"det.h\"\n#include \"timer.h\"\n#include \"types.h\"\n#include \"wavefunction.h\"\n\nnamespace hci {\n\nSolver::Solver() {\n  mpi.id = mpi.world.rank();\n  mpi.n = mpi.world.size();\n  setlocale(LC_NUMERIC, \"\");\n}\n\n// Main solve procedure.\nvoid Solver::solve() {\n  std::string proc_name = boost::mpi::environment::processor_name();\n  printf(\"Proc %d running on %s\\n\", mpi.id, proc_name.c_str());\n  mpi.world.barrier();\n\n  if (mpi.id == 0) printf(\"%s Begin solving.\\n\", Timer::str());\n  std::ifstream config_file(\"CONFIG\");\n  if (!config_file) {\n    if (mpi.id == 0) printf(\"CONFIG file not found.\\n\");\n    return;\n  }\n  read_config(config_file);\n  setup();\n  load_wavefunction(wave_filename);\n  pt(eps_pt);\n  const double cor_energy = var_energy + pt_energy - hf_energy;\n  if (mpi.id == 0) {\n    printf(\"\\n[Summary]\\n\");\n    printf(\"HF Energy: %.10f eV\\n\", hf_energy);\n    printf(\"Variational Energy: %.10f eV\\n\", var_energy);\n    printf(\"PT Correction: %.10f eV\\n\", pt_energy);\n    printf(\"Correlation energy: %.10f eV\\n\", cor_energy);\n  }\n}\n\nvoid Solver::load_wavefunction(const std::string& filename) {\n  int n_in;\n  double coef;\n  const Det zero_det(n_orbs);\n  int orb;\n\n  // Read header line.\n  std::ifstream wave_file(filename.c_str());\n  if (!wave_file) {\n    if (mpi.id == 0) printf(\"Wave file %s not found.\\n\", filename.c_str());\n    exit(0);\n  }\n  wave_file >> n_in >> hf_energy >> var_energy;\n\n  // Read each coef and det.\n  for (int i = 0; i < n_in; i++) {\n    wave_file >> coef;\n    Det& det = wf.append_det(zero_det, coef);\n    for (int j = 0; j < n_up; j++) {\n      wave_file >> orb;\n      det.up.set_orb(orb - 1, true);\n    }\n    for (int j = 0; j < n_dn; j++) {\n      wave_file >> orb;\n      det.dn.set_orb(orb - 1, true);\n    }\n  }\n\n  mpi.world.barrier();\n  if (mpi.id == 0) {\n    printf(\"%s Loaded var dets (%'d)\\n\", Timer::str(), wf.size());\n  }\n}\n\nunsigned long long Solver::estimate_n_pt_dets() {\n  const int n = wf.size();\n  unsigned long long estimation_local = 0, estimation = 0;\n  auto it_det = wf.get_dets().begin();\n  auto it_coef = wf.get_coefs().begin();\n  const int sample_interval = std::max(n / 500, 100);\n  for (int i = 0; i < n; i++) {\n    const auto& det_i = *it_det++;\n    const double coef_i = *it_coef++;\n    if ((i % (sample_interval * mpi.n)) != sample_interval * mpi.id) continue;\n    const auto& connected_dets =\n        find_connected_dets(det_i, eps_pt / fabs(coef_i));\n    estimation_local += connected_dets.size();\n  }\n  estimation_local *= sample_interval;\n  all_reduce(\n      mpi.world, estimation_local, estimation, std::plus<unsigned long long>());\n  return estimation;\n}\n\ntemplate <class T>\nstd::vector<T> Solver::get_local_portion(const std::list<T>& all) {\n  std::vector<T> local;\n  auto it = all.begin();\n  local.reserve(all.size() / mpi.n + 1);\n  for (int i = 0; i < static_cast<int>(all.size()); i++) {\n    const auto& item = *it++;\n    if (i % mpi.n != mpi.id) continue;\n    local.push_back(item);\n  }\n  return local;\n}\n\n// Deterministic 2nd-order purterbation.\nvoid Solver::pt(const double eps_pt) {\n  mpi.world.barrier();\n  auto begin = std::chrono::high_resolution_clock::now();\n  if (mpi.id == 0) printf(\"%s Start PT w/ %d procs.\\n\", Timer::str(), mpi.n);\n\n  // Save variational dets into hash set.\n  std::unordered_set<Det, boost::hash<Det>> var_dets_set;\n  for (const auto& det : wf.get_dets()) var_dets_set.insert(det);\n  var_dets_set.rehash(var_dets_set.size() * 10);\n\n  // Determine number of hash buckets.\n  unsigned long long n_pt_dets_estimate = estimate_n_pt_dets();\n  if (mpi.id == 0) printf(\"Estimated PT dets: %'llu\\n\", n_pt_dets_estimate);\n\n  // Setup hash table.\n  std::pair<std::pair<EncodeType, EncodeType>, double> skeleton;\n  skeleton.first = wf.get_dets().front().encode();\n  BigUnorderedMap<\n      std::pair<EncodeType, EncodeType>,\n      double,\n      boost::hash<std::pair<EncodeType, EncodeType>>>\n      pt_sums(mpi.world, skeleton);\n  pt_sums.reserve(n_pt_dets_estimate * 2);\n  unsigned long long hash_buckets = pt_sums.bucket_count();\n  if (mpi.id == 0) {\n    printf(\"%s \", Timer::str());\n    printf(\"Reserved %'llu total hash buckets.\\n\", hash_buckets);\n  }\n\n  // Shrink variational dets.\n  const auto& var_dets_shrinked = get_local_portion(wf.get_dets());\n  const auto& var_coefs_shrinked = get_local_portion(wf.get_coefs());\n  wf.clear();\n\n  // Accumulate sums.\n  int progress = 10;\n  std::size_t local_n = var_dets_shrinked.size();\n  for (std::size_t i = 0; i < local_n; i++) {\n    const auto& det_i = var_dets_shrinked[i];\n    const double coef_i = var_coefs_shrinked[i];\n    const auto& connected_dets =\n        find_connected_dets(det_i, eps_pt / fabs(coef_i));\n    for (const auto& det_a : connected_dets) {\n      if (var_dets_set.count(det_a) == 1) continue;\n      const double H_ai = get_hamiltonian_elem(det_i, det_a, n_up, n_dn);\n      if (fabs(H_ai) < Constants::EPSILON) continue;\n      const double term = H_ai * coef_i;\n      pt_sums.async_inc(det_a.encode(), term);\n    }\n    if ((i + 1) * 100 >= local_n * progress && mpi.id == 0) {\n      const auto& local_map = pt_sums.get_local_map();\n      const std::size_t local_size = local_map.size();\n      const double load_factor = local_map.load_factor();\n      printf(\"%s \", Timer::str());\n      printf(\"MASTER: Progress: %d%% (%lu/%lu) \", progress, i, local_n);\n      printf(\"Local PT dets: %'lu, hash load: %.2f\\n\", local_size, load_factor);\n      progress += 10;\n    }\n  }\n  pt_sums.complete_async_incs();\n\n  unsigned long long n_pt_dets = pt_sums.size();\n  if (mpi.id == 0) printf(\"%s Total PT dets: %'llu\\n\", Timer::str(), n_pt_dets);\n\n  // Accumulate contribution from each det_a to the pt_energy.\n  pt_energy = 0.0;\n  Det det_a;\n  double pt_energy_local = 0.0;\n  for (const auto& kv : pt_sums.get_local_map()) {\n    det_a.decode(kv.first, n_orbs);\n    const double sum_a = kv.second;\n    const double H_aa = get_hamiltonian_elem(det_a, det_a, n_up, n_dn);\n    pt_energy_local += pow(sum_a, 2) / (var_energy - H_aa);\n  }\n  reduce(mpi.world, pt_energy_local, pt_energy, std::plus<double>(), 0);\n\n  if (mpi.id == 0) {\n    using namespace std::chrono;\n    printf(\"%s PT correction: %.10f eV\\n\", Timer::str(), pt_energy);\n    auto end = high_resolution_clock::now();\n    auto pt_time = duration_cast<duration<double>>(end - begin).count();\n    printf(\"%s Total PT time: %.3f s\\n\", Timer::str(), pt_time);\n  }\n}\n}\n", "meta": {"hexsha": "8662c9ab8b868df678e7a1ffefff5a32eca1826e", "size": 6846, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/solver.cc", "max_stars_repo_name": "jl2922/hci-cc", "max_stars_repo_head_hexsha": "e024758d8051249e7f861ba113f6bc5fbb382d89", "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.cc", "max_issues_repo_name": "jl2922/hci-cc", "max_issues_repo_head_hexsha": "e024758d8051249e7f861ba113f6bc5fbb382d89", "max_issues_repo_licenses": ["MIT"], "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.cc", "max_forks_repo_name": "jl2922/hci-cc", "max_forks_repo_head_hexsha": "e024758d8051249e7f861ba113f6bc5fbb382d89", "max_forks_repo_licenses": ["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.9906542056, "max_line_length": 80, "alphanum_fraction": 0.6498685364, "num_tokens": 1987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19522596139001816}}
{"text": "/*\nDeterministic Bayesian Sparse Linear Mixed Model (DBSLMM)\nCopyright (C) 2019  Sheng Yang and Xiang Zhou\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 3 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#include <vector>\n#include <string>\n#include <iostream>\n#include <ctime>\n#include <math.h>\n\n\n\n#include <armadillo>\n\n#include \"../include/dtpr.hpp\"\n#include \"../include/dbslmm.hpp\"\n#include \"../include/tobool.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\nDBSLMM::DBSLMM(void) :\n\tversion(\"0.3\"), date(\"05/01/2021\"), year(\"2021\")\n{}\n\nvoid DBSLMM::printHeader(void)\n{\n\tcout << endl;\n\tcout << \"*************************************************************\"<< endl;\n\tcout << \"  Deterministic Bayesian Sparse Linear Mixed Model (DBSLMM)  \" << endl;\n\tcout << \"  Version \" << version << \", \" << date << \"                  \" << endl;\n\tcout << \"  Visit http://www.xzlab.org/software.html For Update        \" << endl;\n\tcout << \"  (C) \" << year << \" Sheng Yang, Xiang Zhou                  \" << endl;\n\tcout << \"  GNU General Public License                                 \" << endl;\n\tcout << \"  For Help, Type ./dbslmm -h                                 \" << endl;\n\tcout << \"*************************************************************\" << endl;\n\tcout << endl;\n\n\treturn;\n}\n\nvoid DBSLMM::printHelp(void) {\n\tcout << \" FILE I/O RELATED OPTIONS\" << endl;\n\tcout << \" -s        [filename]  \" << \" specify input the summary data for the small effect SNPs.\" << endl;\n\tcout << \" -l        [filename]  \" << \" specify input the summary data for the large effect SNPs.\" << endl;\n\tcout << \" -r        [filename]  \" << \" specify input the bfile of reference data.\" << endl;\n\tcout << \" -n        [num]       \" << \" specify input the sample size of the summary data.\" << endl;\n\tcout << \" -mafMax   [num]       \" << \" specify input the maximium of the difference between reference panel and summary data.\" << endl;\n\tcout << \" -nsnp     [num]  \" << \" specify input the number of snp.\" << endl;\n\tcout << \" -b        [num]       \" << \" specify input the block information.\" << endl;\n\tcout << \" -h        [num]       \" << \" specify input the heritability.\" << endl;\n\tcout << \" -t        [filename]  \" << \" specify input thread.\" << endl;\n\tcout << \" -eff      [filename]  \" << \" specify output the estimate effect SNPs.\" << endl;\n\treturn;\n}\n\nvoid DBSLMM::Assign(int argc, char ** argv, PARAM &cPar) {\n\t\n\tstring str;\n\tfor (int i = 0; i < argc; i++) {\n\n\t\tif (strcmp(argv[i], \"--smallEff\") == 0 || strcmp(argv[i], \"-s\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.s = str;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--largeEff\") == 0 || strcmp(argv[i], \"-l\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.l = str;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--reference\") == 0 || strcmp(argv[i], \"-r\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.r = str;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--N\") == 0 || strcmp(argv[i], \"-n\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.n = atoi(str.c_str());\n\t\t}\n\t\telse if (strcmp(argv[i], \"--mafMax\") == 0 || strcmp(argv[i], \"-mafMax\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.mafMax = atof(str.c_str());\n\t\t}\n\t\telse if (strcmp(argv[i], \"--numSNP\") == 0 || strcmp(argv[i], \"-nsnp\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.nsnp = atoi(str.c_str());\n\t\t}\n\t\telse if (strcmp(argv[i], \"--block\") == 0 || strcmp(argv[i], \"-b\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.b = str;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--Heritability\") == 0 || strcmp(argv[i], \"-h\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.h = atof(str.c_str());\n\t\t}\n\t\telse if (strcmp(argv[i], \"--Thread\") == 0 || strcmp(argv[i], \"-t\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.t = atoi(str.c_str());\n\t\t}\n\t\telse if (strcmp(argv[i], \"--EFF\") == 0 || strcmp(argv[i], \"-eff\") == 0) {\n\n\t\t\tif (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t\t++i;\n\t\t\tstr.clear();\n\t\t\tstr.assign(argv[i]);\n\t\t\tcPar.eff = str;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--training\") == 0 || strcmp(argv[i], \"-training\") == 0) {\n\t\t  \n\t\t  if (argv[i + 1] == NULL || argv[i + 1][0] == '-') { continue; }\n\t\t  ++i;\n\t\t  str.clear();\n\t\t  str.assign(argv[i]);\n\t\t  cPar.training = to_bool(str);\n\t\t}\n\t\t\n\t}\n\treturn;\n}\n\n", "meta": {"hexsha": "7970bda211365c30350f98a219e7e51454d408c8", "size": 5440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dbslmm.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/dbslmm.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/dbslmm.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": 32.1893491124, "max_line_length": 136, "alphanum_fraction": 0.5283088235, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.19508560342075304}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// This file is manually converted from PROJ4 (projects.h)\n\n// Copyright (c) 2008-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// 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 Geometry Library by Barend Gehrels (Geodan, Amsterdam)\n\n// Original copyright notice:\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_PROJECTIONS_IMPL_PROJECTS_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PROJECTS_HPP\n\n#include <cstring>\n#include <string>\n#include <vector>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n/* some useful constants */\nstatic const double FORTPI = boost::math::constants::pi<double>() / 4.0;\n\nstatic const int PJD_UNKNOWN =0;\nstatic const int PJD_3PARAM = 1;\nstatic const int PJD_7PARAM = 2;\nstatic const int PJD_GRIDSHIFT = 3;\nstatic const int PJD_WGS84 = 4;   /* WGS84 (or anything considered equivelent) */\n\n\nstruct pvalue\n{\n    std::string param;\n    int used;\n\n    int i;\n    double f;\n    std::string s;\n};\n\nstruct pj_const_pod\n{\n    int over;   /* over-range flag */\n    int geoc;   /* geocentric latitude flag */\n    int is_latlong; /* proj=latlong ... not really a projection at all */\n    int is_geocent; /* proj=geocent ... not really a projection at all */\n    double\n        a,  /* major axis or radius if es==0 */\n        a_orig, /* major axis before any +proj related adjustment */\n        es, /* e ^ 2 */\n        es_orig, /* es before any +proj related adjustment */\n        e,  /* eccentricity */\n        ra, /* 1/A */\n        one_es, /* 1 - e^2 */\n        rone_es, /* 1/one_es */\n        lam0, phi0, /* central longitude, latitude */\n        x0, y0, /* easting and northing */\n        k0,    /* general scaling factor */\n        to_meter, fr_meter; /* cartesian scaling */\n\n    int datum_type; /* PJD_UNKNOWN/3PARAM/7PARAM/GRIDSHIFT/WGS84 */\n    double  datum_params[7];\n    double  from_greenwich; /* prime meridian offset (in radians) */\n    double  long_wrap_center; /* 0.0 for -180 to 180, actually in radians*/\n\n    // Initialize all variables to zero\n    pj_const_pod()\n    {\n        std::memset(this, 0, sizeof(pj_const_pod));\n    }\n};\n\n// PROJ4 complex. Might be replaced with std::complex\nstruct COMPLEX { double r, i; };\n\nstruct PJ_ELLPS\n{\n    std::string id;    /* ellipse keyword name */\n    std::string major;    /* a= value */\n    std::string ell;    /* elliptical parameter */\n    std::string name;    /* comments */\n};\n\nstruct PJ_DATUMS\n{\n    std::string id;     /* datum keyword */\n    std::string defn;   /* ie. \"to_wgs84=...\" */\n    std::string ellipse_id; /* ie from ellipse table */\n    std::string comments; /* EPSG code, etc */\n};\n\nstruct PJ_PRIME_MERIDIANS\n{\n    std::string id;     /* prime meridian keyword */\n    std::string defn;   /* offset from greenwich in DMS format. */\n};\n\nstruct PJ_UNITS\n{\n    std::string id;    /* units keyword */\n    std::string to_meter;    /* multiply by value to get meters */\n    std::string name;    /* comments */\n};\n\nstruct DERIVS\n{\n    double x_l, x_p; /* derivatives of x for lambda-phi */\n    double y_l, y_p; /* derivatives of y for lambda-phi */\n};\n\nstruct FACTORS\n{\n    struct DERIVS der;\n    double h, k;    /* meridinal, parallel scales */\n    double omega, thetap;    /* angular distortion, theta prime */\n    double conv;    /* convergence */\n    double s;        /* areal scale factor */\n    double a, b;    /* max-min scale error */\n    int code;        /* info as to analytics, see following */\n};\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n/*!\n    \\brief parameters, projection parameters\n    \\details This structure initializes all projections\n    \\ingroup projection\n*/\nstruct parameters : public detail::pj_const_pod\n{\n    std::string name;\n    std::vector<detail::pvalue> params;\n};\n\n// TODO: derived from boost::exception / make more for forward/inverse/init/setup\nclass proj_exception\n{\npublic:\n\n    proj_exception(int code = 0)\n        : m_code(code)\n    {\n    }\n    int code() const { return m_code; }\nprivate :\n    int m_code;\n};\n\n}}} // namespace boost::geometry::projections\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PROJECTS_HPP\n", "meta": {"hexsha": "7fbd5d8761afb2e722692c9eb0e3abcfd5014dd1", "size": 5603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/impl/projects.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/impl/projects.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/impl/projects.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": 30.7857142857, "max_line_length": 81, "alphanum_fraction": 0.6791004819, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.359364145160102, "lm_q1q2_score": 0.19508559969609374}}
{"text": "//  Copyright John Maddock 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\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/math/tools/real_cast.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include <ostream>\n#include <istream>\n#include <cmath>\n#include <NTL/RR.h>\n\n#ifndef BOOST_MATH_NTL_RR_HPP\n#define BOOST_MATH_NTL_RR_HPP\n\nnamespace boost{ namespace math{\n\nnamespace ntl\n{\n\nclass RR;\n\nRR ldexp(RR r, int exp);\nRR frexp(RR r, int* exp);\n\nclass RR\n{\npublic:\n   // Constructors:\n   RR() {}\n   RR(const ::NTL::RR& c) : m_value(c){}\n   RR(char c)\n   {\n      m_value = c;\n   }\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\n   RR(wchar_t c)\n   {\n      m_value = c;\n   }\n#endif\n   RR(unsigned char c)\n   {\n      m_value = c;\n   }\n   RR(signed char c)\n   {\n      m_value = c;\n   }\n   RR(unsigned short c)\n   {\n      m_value = c;\n   }\n   RR(short c)\n   {\n      m_value = c;\n   }\n   RR(unsigned int c)\n   {\n      assign_large_int(c);\n   }\n   RR(int c)\n   {\n      assign_large_int(c);\n   }\n   RR(unsigned long c)\n   {\n      assign_large_int(c);\n   }\n   RR(long c)\n   {\n      assign_large_int(c);\n   }\n#ifdef BOOST_HAS_LONG_LONG\n   RR(unsigned long long c)\n   {\n      assign_large_int(c);\n   }\n   RR(long long c)\n   {\n      assign_large_int(c);\n   }\n#endif\n   RR(float c)\n   {\n      m_value = c;\n   }\n   RR(double c)\n   {\n      m_value = c;\n   }\n   RR(long double c)\n   {\n      assign_large_real(c);\n   }\n\n   // Assignment:\n   RR& operator=(char c) { m_value = c; return *this; }\n   RR& operator=(unsigned char c) { m_value = c; return *this; }\n   RR& operator=(signed char c) { m_value = c; return *this; }\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\n   RR& operator=(wchar_t c) { m_value = c; return *this; }\n#endif\n   RR& operator=(short c) { m_value = c; return *this; }\n   RR& operator=(unsigned short c) { m_value = c; return *this; }\n   RR& operator=(int c) { assign_large_int(c); return *this; }\n   RR& operator=(unsigned int c) { assign_large_int(c); return *this; }\n   RR& operator=(long c) { assign_large_int(c); return *this; }\n   RR& operator=(unsigned long c) { assign_large_int(c); return *this; }\n#ifdef BOOST_HAS_LONG_LONG\n   RR& operator=(long long c) { assign_large_int(c); return *this; }\n   RR& operator=(unsigned long long c) { assign_large_int(c); return *this; }\n#endif\n   RR& operator=(float c) { m_value = c; return *this; }\n   RR& operator=(double c) { m_value = c; return *this; }\n   RR& operator=(long double c) { assign_large_real(c); return *this; }\n\n   // Access:\n   NTL::RR& value(){ return m_value; }\n   NTL::RR const& value()const{ return m_value; }\n\n   // Member arithmetic:\n   RR& operator+=(const RR& other)\n   { m_value += other.value(); return *this; }\n   RR& operator-=(const RR& other)\n   { m_value -= other.value(); return *this; }\n   RR& operator*=(const RR& other)\n   { m_value *= other.value(); return *this; }\n   RR& operator/=(const RR& other)\n   { m_value /= other.value(); return *this; }\n   RR operator-()const\n   { return -m_value; }\n   RR const& operator+()const\n   { return *this; }\n\n   // RR compatibity:\n   const ::NTL::ZZ& mantissa() const\n   { return m_value.mantissa(); }\n   long exponent() const\n   { return m_value.exponent(); }\n\n   static void SetPrecision(long p)\n   { ::NTL::RR::SetPrecision(p); }\n\n   static long precision()\n   { return ::NTL::RR::precision(); }\n\n   static void SetOutputPrecision(long p)\n   { ::NTL::RR::SetOutputPrecision(p); }\n   static long OutputPrecision()\n   { return ::NTL::RR::OutputPrecision(); }\n\n\nprivate:\n   ::NTL::RR m_value;\n\n   template <class V>\n   void assign_large_real(const V& a)\n   {\n      using std::frexp;\n      using std::ldexp;\n      using std::floor;\n      if (a == 0) {\n         clear(m_value);\n         return;\n      }\n\n      if (a == 1) {\n         NTL::set(m_value);\n         return;\n      }\n\n      if (!(boost::math::isfinite)(a))\n      {\n         throw std::overflow_error(\"Cannot construct an instance of NTL::RR with an infinite value.\");\n      }\n\n      int e;\n      long double f, term;\n      ::NTL::RR t;\n      clear(m_value);\n\n      f = frexp(a, &e);\n\n      while(f)\n      {\n         // extract 30 bits from f:\n         f = ldexp(f, 30);\n         term = floor(f);\n         e -= 30;\n         conv(t.x, (int)term);\n         t.e = e;\n         m_value += t;\n         f -= term;\n      }\n   }\n\n   template <class V>\n   void assign_large_int(V a)\n   {\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4146)\n#endif\n      clear(m_value);\n      int exp = 0;\n      NTL::RR t;\n      bool neg = a < V(0) ? true : false;\n      if(neg) \n         a = -a;\n      while(a)\n      {\n         t = static_cast<double>(a & 0xffff);\n         m_value += ldexp(RR(t), exp).value();\n         a >>= 16;\n         exp += 16;\n      }\n      if(neg)\n         m_value = -m_value;\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n   }\n};\n\n// Non-member arithmetic:\ninline RR operator+(const RR& a, const RR& b)\n{\n   RR result(a);\n   result += b;\n   return result;\n}\ninline RR operator-(const RR& a, const RR& b)\n{\n   RR result(a);\n   result -= b;\n   return result;\n}\ninline RR operator*(const RR& a, const RR& b)\n{\n   RR result(a);\n   result *= b;\n   return result;\n}\ninline RR operator/(const RR& a, const RR& b)\n{\n   RR result(a);\n   result /= b;\n   return result;\n}\n\n// Comparison:\ninline bool operator == (const RR& a, const RR& b)\n{ return a.value() == b.value() ? true : false; }\ninline bool operator != (const RR& a, const RR& b)\n{ return a.value() != b.value() ? true : false;}\ninline bool operator < (const RR& a, const RR& b)\n{ return a.value() < b.value() ? true : false; }\ninline bool operator <= (const RR& a, const RR& b)\n{ return a.value() <= b.value() ? true : false; }\ninline bool operator > (const RR& a, const RR& b)\n{ return a.value() > b.value() ? true : false; }\ninline bool operator >= (const RR& a, const RR& b)\n{ return a.value() >= b.value() ? true : false; }\n\n#if 0\n// Non-member mixed compare:\ntemplate <class T>\ninline bool operator == (const T& a, const RR& b)\n{\n   return a == b.value();\n}\ntemplate <class T>\ninline bool operator != (const T& a, const RR& b)\n{\n   return a != b.value();\n}\ntemplate <class T>\ninline bool operator < (const T& a, const RR& b)\n{\n   return a < b.value();\n}\ntemplate <class T>\ninline bool operator > (const T& a, const RR& b)\n{\n   return a > b.value();\n}\ntemplate <class T>\ninline bool operator <= (const T& a, const RR& b)\n{\n   return a <= b.value();\n}\ntemplate <class T>\ninline bool operator >= (const T& a, const RR& b)\n{\n   return a >= b.value();\n}\n#endif  // Non-member mixed compare:\n\n// Non-member functions:\n/*\ninline RR acos(RR a)\n{ return ::NTL::acos(a.value()); }\n*/\ninline RR cos(RR a)\n{ return ::NTL::cos(a.value()); }\n/*\ninline RR asin(RR a)\n{ return ::NTL::asin(a.value()); }\ninline RR atan(RR a)\n{ return ::NTL::atan(a.value()); }\ninline RR atan2(RR a, RR b)\n{ return ::NTL::atan2(a.value(), b.value()); }\n*/\ninline RR ceil(RR a)\n{ return ::NTL::ceil(a.value()); }\n/*\ninline RR fmod(RR a, RR b)\n{ return ::NTL::fmod(a.value(), b.value()); }\ninline RR cosh(RR a)\n{ return ::NTL::cosh(a.value()); }\n*/\ninline RR exp(RR a)\n{ return ::NTL::exp(a.value()); }\ninline RR fabs(RR a)\n{ return ::NTL::fabs(a.value()); }\ninline RR abs(RR a)\n{ return ::NTL::abs(a.value()); }\ninline RR floor(RR a)\n{ return ::NTL::floor(a.value()); }\n/*\ninline RR modf(RR a, RR* ipart)\n{\n   ::NTL::RR ip;\n   RR result = modf(a.value(), &ip);\n   *ipart = ip;\n   return result;\n}\ninline RR frexp(RR a, int* expon)\n{ return ::NTL::frexp(a.value(), expon); }\ninline RR ldexp(RR a, int expon)\n{ return ::NTL::ldexp(a.value(), expon); }\n*/\ninline RR log(RR a)\n{ return ::NTL::log(a.value()); }\ninline RR log10(RR a)\n{ return ::NTL::log10(a.value()); }\n/*\ninline RR tan(RR a)\n{ return ::NTL::tan(a.value()); }\n*/\ninline RR pow(RR a, RR b)\n{ return ::NTL::pow(a.value(), b.value()); }\ninline RR pow(RR a, int b)\n{ return ::NTL::power(a.value(), b); }\ninline RR sin(RR a)\n{ return ::NTL::sin(a.value()); }\n/*\ninline RR sinh(RR a)\n{ return ::NTL::sinh(a.value()); }\n*/\ninline RR sqrt(RR a)\n{ return ::NTL::sqrt(a.value()); }\n/*\ninline RR tanh(RR a)\n{ return ::NTL::tanh(a.value()); }\n*/\n   inline RR pow(const RR& r, long l)\n   {\n      return ::NTL::power(r.value(), l);\n   }\n   inline RR tan(const RR& a)\n   {\n      return sin(a)/cos(a);\n   }\n   inline RR frexp(RR r, int* exp)\n   {\n      *exp = r.value().e;\n      r.value().e = 0;\n      while(r >= 1)\n      {\n         *exp += 1;\n         r.value().e -= 1;\n      }\n      while(r < 0.5)\n      {\n         *exp -= 1;\n         r.value().e += 1;\n      }\n      BOOST_ASSERT(r < 1);\n      BOOST_ASSERT(r >= 0.5);\n      return r;\n   }\n   inline RR ldexp(RR r, int exp)\n   {\n      r.value().e += exp;\n      return r;\n   }\n\n// Streaming:\ntemplate <class charT, class traits>\ninline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const RR& a)\n{\n   return os << a.value();\n}\ntemplate <class charT, class traits>\ninline std::basic_istream<charT, traits>& operator>>(std::basic_istream<charT, traits>& is, RR& a)\n{\n   ::NTL::RR v;\n   is >> v;\n   a = v;\n   return is;\n}\n\n} // namespace ntl\n\nnamespace tools\n{\n\ntemplate<>\ninline int digits<boost::math::ntl::RR>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(boost::math::ntl::RR))\n{\n   return ::NTL::RR::precision();\n}\n\ntemplate <>\ninline float real_cast<float, boost::math::ntl::RR>(boost::math::ntl::RR t)\n{\n   double r;\n   conv(r, t.value());\n   return static_cast<float>(r);\n}\ntemplate <>\ninline double real_cast<double, boost::math::ntl::RR>(boost::math::ntl::RR t)\n{\n   double r;\n   conv(r, t.value());\n   return r;\n}\n\nnamespace detail{\n\ntemplate<class I>\nvoid convert_to_long_result(NTL::RR const& r, I& result)\n{\n   result = 0;\n   I last_result(0);\n   NTL::RR t(r);\n   double term;\n   do\n   {\n      conv(term, t);\n      last_result = result;\n      result += static_cast<I>(term);\n      t -= term;\n   }while(result != last_result);\n}\n\n}\n\ntemplate <>\ninline long double real_cast<long double, boost::math::ntl::RR>(boost::math::ntl::RR t)\n{\n   long double result(0);\n   detail::convert_to_long_result(t.value(), result);\n   return result;\n}\ntemplate <>\ninline boost::math::ntl::RR real_cast<boost::math::ntl::RR, boost::math::ntl::RR>(boost::math::ntl::RR t)\n{\n   return t;\n}\ntemplate <>\ninline unsigned real_cast<unsigned, boost::math::ntl::RR>(boost::math::ntl::RR t)\n{\n   unsigned result;\n   detail::convert_to_long_result(t.value(), result);\n   return result;\n}\ntemplate <>\ninline int real_cast<int, boost::math::ntl::RR>(boost::math::ntl::RR t)\n{\n   unsigned result;\n   detail::convert_to_long_result(t.value(), result);\n   return result;\n}\n\ntemplate <>\ninline boost::math::ntl::RR max_value<boost::math::ntl::RR>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(boost::math::ntl::RR))\n{\n   static bool has_init = false;\n   static NTL::RR val;\n   if(!has_init)\n   {\n      val = 1;\n      val.e = NTL_OVFBND-20;\n      has_init = true;\n   }\n   return val;\n}\n\ntemplate <>\ninline boost::math::ntl::RR min_value<boost::math::ntl::RR>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(boost::math::ntl::RR))\n{\n   static bool has_init = false;\n   static NTL::RR val;\n   if(!has_init)\n   {\n      val = 1;\n      val.e = -NTL_OVFBND+20;\n      has_init = true;\n   }\n   return val;\n}\n\ntemplate <>\ninline boost::math::ntl::RR log_max_value<boost::math::ntl::RR>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(boost::math::ntl::RR))\n{\n   static bool has_init = false;\n   static NTL::RR val;\n   if(!has_init)\n   {\n      val = 1;\n      val.e = NTL_OVFBND-20;\n      val = log(val);\n      has_init = true;\n   }\n   return val;\n}\n\ntemplate <>\ninline boost::math::ntl::RR log_min_value<boost::math::ntl::RR>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(boost::math::ntl::RR))\n{\n   static bool has_init = false;\n   static NTL::RR val;\n   if(!has_init)\n   {\n      val = 1;\n      val.e = -NTL_OVFBND+20;\n      val = log(val);\n      has_init = true;\n   }\n   return val;\n}\n\ntemplate <>\ninline boost::math::ntl::RR epsilon<boost::math::ntl::RR>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(boost::math::ntl::RR))\n{\n   return ldexp(boost::math::ntl::RR(1), 1-boost::math::policies::digits<boost::math::ntl::RR, boost::math::policies::policy<> >());\n}\n\n} // namespace tools\n\n//\n// The number of digits precision in RR can vary with each call\n// so we need to recalculate these with each call:\n//\nnamespace constants{\n\ntemplate<> inline boost::math::ntl::RR pi<boost::math::ntl::RR>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(boost::math::ntl::RR))\n{\n    NTL::RR result;\n    ComputePi(result);\n    return result;\n}\ntemplate<> inline boost::math::ntl::RR e<boost::math::ntl::RR>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(boost::math::ntl::RR))\n{\n    NTL::RR result;\n    result = 1;\n    return exp(result);\n}\n\n} // namespace constants\n\nnamespace ntl{\n   //\n   // These are some fairly brain-dead versions of the math\n   // functions that NTL fails to provide.\n   //\n\n\n   //\n   // Inverse trig functions:\n   //\n   struct asin_root\n   {\n      asin_root(RR const& target) : t(target){}\n\n      std::tr1::tuple<RR, RR, RR> operator()(RR const& p)\n      {\n         RR f0 = sin(p);\n         RR f1 = cos(p);\n         RR f2 = -f0;\n         f0 -= t;\n         return std::tr1::make_tuple(f0, f1, f2);\n      }\n   private:\n      RR t;\n   };\n\n   inline RR asin(RR z)\n   {\n      double r;\n      conv(r, z.value());\n      return boost::math::tools::halley_iterate(\n         asin_root(z), \n         RR(std::asin(r)), \n         RR(-boost::math::constants::pi<RR>()/2),\n         RR(boost::math::constants::pi<RR>()/2),\n         NTL::RR::precision());\n   }\n\n   struct acos_root\n   {\n      acos_root(RR const& target) : t(target){}\n\n      std::tr1::tuple<RR, RR, RR> operator()(RR const& p)\n      {\n         RR f0 = cos(p);\n         RR f1 = -sin(p);\n         RR f2 = -f0;\n         f0 -= t;\n         return std::tr1::make_tuple(f0, f1, f2);\n      }\n   private:\n      RR t;\n   };\n\n   inline RR acos(RR z)\n   {\n      double r;\n      conv(r, z.value());\n      return boost::math::tools::halley_iterate(\n         acos_root(z), \n         RR(std::acos(r)), \n         RR(-boost::math::constants::pi<RR>()/2),\n         RR(boost::math::constants::pi<RR>()/2),\n         NTL::RR::precision());\n   }\n\n   struct atan_root\n   {\n      atan_root(RR const& target) : t(target){}\n\n      std::tr1::tuple<RR, RR, RR> operator()(RR const& p)\n      {\n         RR c = cos(p);\n         RR ta = tan(p);\n         RR f0 = ta - t;\n         RR f1 = 1 / (c * c);\n         RR f2 = 2 * ta / (c * c);\n         return std::tr1::make_tuple(f0, f1, f2);\n      }\n   private:\n      RR t;\n   };\n\n   inline RR atan(RR z)\n   {\n      double r;\n      conv(r, z.value());\n      return boost::math::tools::halley_iterate(\n         atan_root(z), \n         RR(std::atan(r)), \n         -boost::math::constants::pi<RR>()/2,\n         boost::math::constants::pi<RR>()/2,\n         NTL::RR::precision());\n   }\n\n   inline RR sinh(RR z)\n   {\n      return (expm1(z.value()) - expm1(-z.value())) / 2;\n   }\n\n   inline RR cosh(RR z)\n   {\n      return (exp(z) + exp(-z)) / 2;\n   }\n\n   inline RR tanh(RR z)\n   {\n      return sinh(z) / cosh(z);\n   }\n\n   inline RR fmod(RR x, RR y)\n   {\n      // This is a really crummy version of fmod, we rely on lots\n      // of digits to get us out of trouble...\n      RR factor = floor(x/y);\n      return x - factor * y;\n   }\n\n} // namespace ntl\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_REAL_CONCEPT_HPP\n\n\n", "meta": {"hexsha": "3708b068f70ed424b7c7b30b9aebe6e4ac2eb9fa", "size": 15646, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_35/boost/math/bindings/rr.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/bindings/rr.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/bindings/rr.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": 22.0988700565, "max_line_length": 132, "alphanum_fraction": 0.5812348204, "num_tokens": 4656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.195085592246775}}
{"text": "/**\n * \\ file VolumeFilter.cpp\n */\n\n#include <cmath>\n\n#include <ATK/Tools/VolumeFilter.h>\n\n#include <ATK/Mock/TriangleCheckerFilter.h>\n#include <ATK/Mock/TriangleGeneratorFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\nconstexpr gsl::index PROCESSSIZE = 1024;\n\nBOOST_AUTO_TEST_CASE( VolumeFilter_volume_test )\n{\n  ATK::VolumeFilter<double> volumefilter;\n  volumefilter.set_volume(10);\n  BOOST_CHECK_EQUAL(volumefilter.get_volume(), 10);\n}\n\nBOOST_AUTO_TEST_CASE( VolumeFilter_1_test )\n{\n  ATK::TriangleGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(48000);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::VolumeFilter<double> volumefilter;\n  volumefilter.set_input_sampling_rate(48000);\n  volumefilter.set_output_sampling_rate(48000);\n  \n  ATK::TriangleCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(48000);\n  checker.set_amplitude(1);\n  checker.set_frequency(1000);\n  \n  volumefilter.set_input_port(0, &generator, 0);\n  checker.set_input_port(0, &volumefilter, 0);\n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( VolumeFilter_0dB_test )\n{\n  ATK::TriangleGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(48000);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::VolumeFilter<double> volumefilter;\n  volumefilter.set_input_sampling_rate(48000);\n  volumefilter.set_output_sampling_rate(48000);\n  volumefilter.set_volume_db(0);\n  \n  ATK::TriangleCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(48000);\n  checker.set_amplitude(1);\n  checker.set_frequency(1000);\n  \n  volumefilter.set_input_port(0, &generator, 0);\n  checker.set_input_port(0, &volumefilter, 0);\n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( VolumeFilter_2_test )\n{\n  ATK::TriangleGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(48000);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::VolumeFilter<double> volumefilter;\n  volumefilter.set_input_sampling_rate(48000);\n  volumefilter.set_output_sampling_rate(48000);\n  volumefilter.set_volume(2);\n  \n  ATK::TriangleCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(48000);\n  checker.set_amplitude(2);\n  checker.set_frequency(1000);\n  \n  volumefilter.set_input_port(0, &generator, 0);\n  checker.set_input_port(0, &volumefilter, 0);\n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( VolumeFilter_6dB_test )\n{\n  ATK::TriangleGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(48000);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::VolumeFilter<double> volumefilter;\n  volumefilter.set_input_sampling_rate(48000);\n  volumefilter.set_output_sampling_rate(48000);\n  volumefilter.set_volume_db(6);\n  \n  ATK::TriangleCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(48000);\n  checker.set_amplitude(1.995262);\n  checker.set_frequency(1000);\n  \n  volumefilter.set_input_port(0, &generator, 0);\n  checker.set_input_port(0, &volumefilter, 0);\n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( VolumeFilter_0_5_test )\n{\n  ATK::TriangleGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(48000);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::VolumeFilter<double> volumefilter;\n  volumefilter.set_input_sampling_rate(48000);\n  volumefilter.set_output_sampling_rate(48000);\n  volumefilter.set_volume(.5);\n  \n  ATK::TriangleCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(48000);\n  checker.set_amplitude(.5);\n  checker.set_frequency(1000);\n  \n  volumefilter.set_input_port(0, &generator, 0);\n  checker.set_input_port(0, &volumefilter, 0);\n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( VolumeFilter__6dB_test )\n{\n  ATK::TriangleGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(48000);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::VolumeFilter<double> volumefilter;\n  volumefilter.set_input_sampling_rate(48000);\n  volumefilter.set_output_sampling_rate(48000);\n  volumefilter.set_volume_db(-6);\n  \n  ATK::TriangleCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(48000);\n  checker.set_amplitude(1/1.995262);\n  checker.set_frequency(1000);\n  \n  volumefilter.set_input_port(0, &generator, 0);\n  checker.set_input_port(0, &volumefilter, 0);\n  checker.process(PROCESSSIZE);\n}\n", "meta": {"hexsha": "4f5c7cffd26831b9ccf8f1de5b2ab6a897ba1a39", "size": 4449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Tools/VolumeFilter.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": "tests/Tools/VolumeFilter.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": "tests/Tools/VolumeFilter.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": 28.7032258065, "max_line_length": 51, "alphanum_fraction": 0.786693639, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19507638209139166}}
{"text": "#define BOOST_TEST_MODULE ChipmunkppTest\n#include <boost/test/unit_test.hpp>\n#include <chipmunk.hpp>\n\nusing namespace cp;\n\nBOOST_AUTO_TEST_CASE(PolyShapeTest) {\n\tSpace space;\n\n\tstd::vector<std::shared_ptr<PolyShape>> shapes;\n\n\tauto add = [&](std::vector<Vect> vects) {\n\t\tauto shape = std::make_shared<PolyShape>(space.staticBody, vects);\n\t\tspace.add(shape);\n\t\tshapes.push_back(shape);\n\t\tBOOST_CHECK_EQUAL(shape->getNumVerts(), vects.size());\n\t\tfor (size_t i = 0; i < vects.size(); ++i) {\n\t\t\tBOOST_CHECK(shape->getVert(i) == vects[i]);\n\t\t}\n\t\tBOOST_CHECK(!shape->pointQuery(Vect(253, 17)));\n\t};\n\n\tadd({Vect(0, 40), Vect(-479, 264), Vect(480, 264)});\n\tadd({Vect(-140, 0), Vect(-479, -320), Vect(-479, 264)});\n\tadd({Vect(-10, -100), Vect(-479, -320), Vect(-140, 0)});\n\tadd({Vect(-61, 37), Vect(55, 50), Vect(5, -58)});\n\tBOOST_CHECK(shapes.back()->pointQuery(Vect(0, 0)));\n}\n", "meta": {"hexsha": "6efe33b32ce17f25f5625b061b7a4fc3f0be2b7b", "size": 870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_test/polyshape.cpp", "max_stars_repo_name": "amiani/chipmunkpp", "max_stars_repo_head_hexsha": "4ffd0c9ae269dcdec2e693c439f28bf1bd63bff8", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-06T21:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T10:06:39.000Z", "max_issues_repo_path": "unit_test/polyshape.cpp", "max_issues_repo_name": "amiani/chipmunkpp", "max_issues_repo_head_hexsha": "4ffd0c9ae269dcdec2e693c439f28bf1bd63bff8", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-04-22T08:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T20:22:03.000Z", "max_forks_repo_path": "unit_test/polyshape.cpp", "max_forks_repo_name": "amiani/chipmunkpp", "max_forks_repo_head_hexsha": "4ffd0c9ae269dcdec2e693c439f28bf1bd63bff8", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-25T19:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T19:15:17.000Z", "avg_line_length": 30.0, "max_line_length": 68, "alphanum_fraction": 0.6574712644, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19507638209139166}}
{"text": "#include \"add.h\"\n\n#include <cmath>\n\n#include <boost/random.hpp>\n\nnamespace math\n{\n    int add(const int a, const int b)\n    {\n        constexpr size_t RV_SIZE = 100;\n        std::vector<double> random_values(RV_SIZE);\n        boost::random::mt19937 gen;\n        boost::random::uniform_real_distribution<double> dist(0.0, 1.0);\n\n#       pragma omp parallel for\n        for (auto i = 0; i< RV_SIZE; i++)\n        {\n            random_values[i] = std::sqrt(dist(gen));\n            std::cout<< i;\n        }\n\n        int result = a + b;\n\n#       pragma omp parallel for reduction(+: result)\n        for (auto i = 0; i< RV_SIZE; i++)\n        {\n            result += static_cast<int>(random_values[i]);\n        }\n        return result;\n    }\n}\n\n", "meta": {"hexsha": "85bca6b09c76e87dfd6e4571664460ef92a2b35a", "size": 737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "add.cpp", "max_stars_repo_name": "mkviatkovskii/mingw-clang-test", "max_stars_repo_head_hexsha": "bc6ae69a4a979699653fcfdf13064e6783a89a36", "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": "add.cpp", "max_issues_repo_name": "mkviatkovskii/mingw-clang-test", "max_issues_repo_head_hexsha": "bc6ae69a4a979699653fcfdf13064e6783a89a36", "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": "add.cpp", "max_forks_repo_name": "mkviatkovskii/mingw-clang-test", "max_forks_repo_head_hexsha": "bc6ae69a4a979699653fcfdf13064e6783a89a36", "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.6764705882, "max_line_length": 72, "alphanum_fraction": 0.5373134328, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.19499281176316474}}
{"text": "// Copyright (c) 2015-2021 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 \"strand_bias.hpp\"\n\n#include <algorithm>\n#include <iterator>\n#include <random>\n#include <functional>\n#include <cmath>\n#include <cassert>\n\n#include <boost/variant.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"io/variant/vcf_record.hpp\"\n#include \"io/variant/vcf_spec.hpp\"\n#include \"basics/aligned_read.hpp\"\n#include \"utils/maths.hpp\"\n#include \"utils/beta_distribution.hpp\"\n#include \"utils/string_utils.hpp\"\n#include \"../facets/samples.hpp\"\n#include \"../facets/alleles.hpp\"\n#include \"../facets/read_assignments.hpp\"\n\nnamespace octopus { namespace csr {\n\nconst std::string StrandBias::name_ = \"SB\";\n\nStrandBias::StrandBias(const double critical_value)\n: min_medium_trigger_ {critical_value / 2}\n, min_big_trigger_ {critical_value / 8}\n, critical_resample_lb_ {0.995 * critical_value}\n, critical_resample_ub_ {1.005 * critical_value}\n, use_resampling_ {true}\n{}\n\nstd::unique_ptr<Measure> StrandBias::do_clone() const\n{\n    return std::make_unique<StrandBias>(*this);\n}\n\nMeasure::ValueType StrandBias::get_value_type() const\n{\n    return double {};\n}\n\nvoid StrandBias::do_set_parameters(std::vector<std::string> params)\n{\n    if (params.size() != 1) {\n        throw BadMeasureParameters {this->name(), \"only has one parameter (min proportion difference)\"};\n    }\n    try {\n        min_difference_ = boost::lexical_cast<decltype(min_difference_)>(params.front());\n    } catch (const boost::bad_lexical_cast&) {\n        throw BadMeasureParameters {this->name(), \"given parameter \\\"\" + params.front() + \"\\\" cannot be parsed\"};\n    }\n    if (min_difference_ < 0 || min_difference_ > 1) {\n        throw BadMeasureParameters {this->name(), \"min proportion difference must be between 0 and 1\"};\n    }\n}\n\nstd::vector<std::string> StrandBias::do_parameters() const\n{\n    return {utils::to_string(min_difference_, 2)};\n}\n\nnamespace {\n\nbool is_canonical(const VcfRecord::NucleotideSequence& allele) noexcept\n{\n    return !(allele == vcfspec::missingValue || allele == vcfspec::deleteMaskAllele);\n}\n\nbool has_called_alt_allele(const VcfRecord& call, const VcfRecord::SampleName& sample)\n{\n    if (!call.has_genotypes()) return true;\n    const auto& genotype = get_genotype(call, sample);\n    return std::any_of(std::cbegin(genotype), std::cend(genotype),\n                       [&] (const auto& allele) { return allele != call.ref() && is_canonical(allele); });\n}\n\nbool is_evaluable(const VcfRecord& call, const VcfRecord::SampleName& sample)\n{\n    return has_called_alt_allele(call, sample) && call.is_heterozygous(sample);\n}\n\nstruct DirectionCounts\n{\n    unsigned forward, reverse;\n};\n\ntemplate <typename Container>\nDirectionCounts count_directions(const Container& reads, const GenomicRegion& call_region)\n{\n    unsigned n_forward {0}, n_reverse {0};\n    for (const auto& read : reads) {\n        if (overlaps(read.get(), call_region)) {\n            if (is_forward_strand(read)) {\n                ++n_forward;\n            } else {\n                ++n_reverse;\n            }\n        }\n    }\n    return {n_forward, n_reverse};\n}\n\nusing DirectionCountVector = std::vector<DirectionCounts>;\n\nauto get_direction_counts(const std::vector<Allele>& alleles, const AlleleSupportMap& support, const GenomicRegion& call_region, const unsigned prior = 1)\n{\n    DirectionCountVector result {};\n    result.reserve(alleles.size());\n    for (const auto& allele : alleles) {\n        result.push_back(count_directions(support.at(allele), call_region));\n        result.back().forward += prior;\n        result.back().reverse += prior;\n    }\n    return result;\n}\n\ntemplate <typename URNG>\nauto sample_beta(const DirectionCounts& counts, const std::size_t n, URNG& generator)\n{\n    std::beta_distribution<> beta {static_cast<double>(counts.forward), static_cast<double>(counts.reverse)};\n    std::vector<double> result(n);\n    std::generate_n(std::begin(result), n, [&] () { return beta(generator); });\n    return result;\n}\n\ntemplate <typename URNG>\ntypename URNG::result_type\ngenerate_urng_seed(const DirectionCountVector& direction_counts, const std::size_t num_samples) noexcept\n{\n    const static auto add_counts = [] (auto curr, const auto& counts) noexcept { return counts.forward + counts.reverse; };\n    const auto tot_count = std::accumulate(std::cbegin(direction_counts), std::cend(direction_counts), 0u, add_counts);\n    return tot_count + num_samples % tot_count;\n}\n\nauto generate_beta_samples(const DirectionCountVector& direction_counts, const std::size_t num_samples)\n{\n    std::mt19937 generator {generate_urng_seed<std::mt19937>(direction_counts, num_samples)};\n    std::vector<std::vector<double>> result {};\n    result.reserve(direction_counts.size());\n    for (const auto& counts : direction_counts) {\n        result.push_back(sample_beta(counts, num_samples, generator));\n    }\n    return result;\n}\n\ndouble estimate_prob_different(const std::vector<double>& lhs, const std::vector<double>& rhs,\n                               const double min_diff)\n{\n    assert(lhs.size() == rhs.size());\n    std::vector<double> diffs(lhs.size());\n    std::transform(std::cbegin(lhs), std::cend(lhs), std::cbegin(rhs), std::begin(diffs), std::minus<> {});\n    auto n_diffs = std::count_if(std::cbegin(diffs), std::cend(diffs), [=] (auto diff) { return std::abs(diff) > min_diff; });\n    return static_cast<double>(n_diffs) / diffs.size();\n}\n\ndouble calculate_max_prob_different(const DirectionCountVector& direction_counts, const std::size_t num_samples,\n                                    const double min_diff)\n{\n    const auto num_counts = direction_counts.size();\n    if (num_counts < 2) return 0;\n    const auto samples = generate_beta_samples(direction_counts, num_samples);\n    double result {0};\n    for (std::size_t i {0}; i < num_counts - 1; ++i) {\n        for (auto j = i + 1; j < num_counts; ++j) {\n            result = std::max(result, estimate_prob_different(samples[i], samples[j], min_diff));\n        }\n    }\n    return result;\n}\n\n} // namespace\n\nMeasure::ResultType StrandBias::do_evaluate(const VcfRecord& call, const FacetMap& facets) const\n{\n    const auto& samples = get_value<Samples>(facets.at(\"Samples\"));\n    const auto& alleles = get_value<Alleles>(facets.at(\"Alleles\"));\n    const auto& assignments = get_value<ReadAssignments>(facets.at(\"ReadAssignments\")).alleles;\n    Array<Optional<ValueType>> result(samples.size());\n    for (std::size_t s {0}; s < samples.size(); ++s) {\n        const auto& sample = samples[s];\n        if (is_evaluable(call, sample)) {\n            const auto direction_counts = get_direction_counts(get_called(alleles, call, sample), assignments.at(sample), mapped_region(call));\n            double prob;\n            if (use_resampling_) {\n                prob = calculate_max_prob_different(direction_counts, small_sample_size_, min_difference_);\n                if (prob >= min_big_trigger_) {\n                    prob = calculate_max_prob_different(direction_counts, big_sample_size_, min_difference_);\n                } else if (prob >= min_medium_trigger_) {\n                    prob = calculate_max_prob_different(direction_counts, medium_sample_size_, min_difference_);\n                    if (prob >= min_big_trigger_) {\n                        prob = calculate_max_prob_different(direction_counts, big_sample_size_, min_difference_);\n                    }\n                }\n                if (prob > critical_resample_lb_ && prob < critical_resample_ub_) {\n                    prob = calculate_max_prob_different(direction_counts, very_big_sample_size, min_difference_);\n                }\n            } else {\n                prob = calculate_max_prob_different(direction_counts, big_sample_size_, min_difference_);\n            }\n            result[s] = ValueType {prob};\n        }\n    }\n    return result;\n}\n\nMeasure::ResultCardinality StrandBias::do_cardinality() const noexcept\n{\n    return ResultCardinality::samples;\n}\n\nconst std::string& StrandBias::do_name() const\n{\n    return name_;\n}\n\nstd::string StrandBias::do_describe() const\n{\n    return \"Strand bias of reads based on haplotype support\";\n}\n\nstd::vector<std::string> StrandBias::do_requirements() const\n{\n    return {\"Samples\", \"Alleles\", \"ReadAssignments\"};\n}\n\nbool StrandBias::is_equal(const Measure& other) const noexcept\n{\n    return min_medium_trigger_ == static_cast<const StrandBias&>(other).min_medium_trigger_;\n}\n\n} // namespace csr\n} // namespace octopus\n", "meta": {"hexsha": "149aed22069c9f1488c227012a9d61adf29f3f35", "size": 8576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/csr/measures/strand_bias.cpp", "max_stars_repo_name": "Schaudge/octopus", "max_stars_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "src/core/csr/measures/strand_bias.cpp", "max_issues_repo_name": "Schaudge/octopus", "max_issues_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "src/core/csr/measures/strand_bias.cpp", "max_forks_repo_name": "Schaudge/octopus", "max_forks_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 35.7333333333, "max_line_length": 154, "alphanum_fraction": 0.6833022388, "num_tokens": 1987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.19495128466296338}}
{"text": "#include \"extractor/guidance/turn_instruction.hpp\"\n\n#include \"engine/plugins/plugin_base.hpp\"\n#include \"engine/plugins/tile.hpp\"\n\n#include \"util/coordinate_calculation.hpp\"\n#include \"util/string_view.hpp\"\n#include \"util/vector_tile.hpp\"\n#include \"util/web_mercator.hpp\"\n\n#include \"engine/api/json_factory.hpp\"\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/multi/geometries/multi_linestring.hpp>\n\n#include <protozero/pbf_writer.hpp>\n#include <protozero/varint.hpp>\n\n#include <algorithm>\n#include <numeric>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include <cmath>\n#include <cstdint>\n\nnamespace osrm\n{\nnamespace engine\n{\nnamespace plugins\n{\n\nconstexpr const static int MIN_ZOOM_FOR_TURNS = 15;\n\nnamespace\n{\n\n// Creates an indexed lookup table for values - used to encoded the vector tile\n// which uses a lookup table and index pointers for encoding\ntemplate <typename T> struct ValueIndexer\n{\n  private:\n    std::vector<T> used_values;\n    std::unordered_map<T, std::size_t> value_offsets;\n\n  public:\n    std::size_t add(const T &value)\n    {\n        const auto found = value_offsets.find(value);\n        std::size_t offset;\n\n        if (found == value_offsets.end())\n        {\n            used_values.push_back(value);\n            offset = used_values.size() - 1;\n            value_offsets[value] = offset;\n        }\n        else\n        {\n            offset = found->second;\n        }\n\n        return offset;\n    }\n\n    std::size_t indexOf(const T &value) { return value_offsets[value]; };\n\n    const std::vector<T> &values() { return used_values; }\n\n    std::size_t size() const { return used_values.size(); }\n};\n\nusing RTreeLeaf = datafacade::BaseDataFacade::RTreeLeaf;\n// TODO: Port all this encoding logic to https://github.com/mapbox/vector-tile, which wasn't\n// available when this code was originally written.\n\n// Simple container class for WGS84 coordinates\ntemplate <typename T> struct Point final\n{\n    Point(T _x, T _y) : x(_x), y(_y) {}\n\n    const T x;\n    const T y;\n};\n\n// Simple container to hold a bounding box\nstruct BBox final\n{\n    BBox(const double _minx, const double _miny, const double _maxx, const double _maxy)\n        : minx(_minx), miny(_miny), maxx(_maxx), maxy(_maxy)\n    {\n    }\n\n    double width() const { return maxx - minx; }\n    double height() const { return maxy - miny; }\n\n    const double minx;\n    const double miny;\n    const double maxx;\n    const double maxy;\n};\n\n// Simple container for integer coordinates (i.e. pixel coords)\nstruct point_type_i final\n{\n    point_type_i(std::int64_t _x, std::int64_t _y) : x(_x), y(_y) {}\n\n    const std::int64_t x;\n    const std::int64_t y;\n};\n\nusing FixedPoint = Point<std::int32_t>;\nusing FloatPoint = Point<double>;\n\nusing FixedLine = std::vector<FixedPoint>;\nusing FloatLine = std::vector<FloatPoint>;\n\n// We use boost::geometry to clip lines/points that are outside or cross the boundary\n// of the tile we're rendering.  We need these types defined to use boosts clipping\n// logic\ntypedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> point_t;\ntypedef boost::geometry::model::linestring<point_t> linestring_t;\ntypedef boost::geometry::model::box<point_t> box_t;\ntypedef boost::geometry::model::multi_linestring<linestring_t> multi_linestring_t;\nconst static box_t clip_box(point_t(-util::vector_tile::BUFFER, -util::vector_tile::BUFFER),\n                            point_t(util::vector_tile::EXTENT + util::vector_tile::BUFFER,\n                                    util::vector_tile::EXTENT + util::vector_tile::BUFFER));\n\n// from mapnik-vector-tile\n// Encodes a linestring using protobuf zigzag encoding\ninline bool encodeLinestring(const FixedLine &line,\n                             protozero::packed_field_uint32 &geometry,\n                             std::int32_t &start_x,\n                             std::int32_t &start_y)\n{\n    const std::size_t line_size = line.size();\n    if (line_size < 2)\n    {\n        return false;\n    }\n\n    const unsigned lineto_count = static_cast<const unsigned>(line_size) - 1;\n\n    auto pt = line.begin();\n    const constexpr int MOVETO_COMMAND = 9;\n    geometry.add_element(MOVETO_COMMAND); // move_to | (1 << 3)\n    geometry.add_element(protozero::encode_zigzag32(pt->x - start_x));\n    geometry.add_element(protozero::encode_zigzag32(pt->y - start_y));\n    start_x = pt->x;\n    start_y = pt->y;\n    // This means LINETO repeated N times\n    // See: https://github.com/mapbox/vector-tile-spec/tree/master/2.1#example-command-integers\n    geometry.add_element((lineto_count << 3u) | 2u);\n    // Now that we've issued the LINETO REPEAT N command, we append\n    // N coordinate pairs immediately after the command.\n    for (++pt; pt != line.end(); ++pt)\n    {\n        const std::int32_t dx = pt->x - start_x;\n        const std::int32_t dy = pt->y - start_y;\n        geometry.add_element(protozero::encode_zigzag32(dx));\n        geometry.add_element(protozero::encode_zigzag32(dy));\n        start_x = pt->x;\n        start_y = pt->y;\n    }\n    return true;\n}\n\n// from mapnik-vctor-tile\n// Encodes a point\ninline void encodePoint(const FixedPoint &pt, protozero::packed_field_uint32 &geometry)\n{\n    const constexpr int MOVETO_COMMAND = 9;\n    geometry.add_element(MOVETO_COMMAND);\n    const std::int32_t dx = pt.x;\n    const std::int32_t dy = pt.y;\n    // Manual zigzag encoding.\n    geometry.add_element(protozero::encode_zigzag32(dx));\n    geometry.add_element(protozero::encode_zigzag32(dy));\n}\n\n/**\n * Returnx the x1,y1,x2,y2 pixel coordinates of a line in a given\n * tile.\n *\n * @param start the first coordinate of the line\n * @param target the last coordinate of the line\n * @param tile_bbox the boundaries of the tile, in mercator coordinates\n * @return a FixedLine with coordinates relative to the tile_bbox.\n */\nFixedLine coordinatesToTileLine(const util::Coordinate start,\n                                const util::Coordinate target,\n                                const BBox &tile_bbox)\n{\n    FloatLine geo_line;\n    geo_line.emplace_back(static_cast<double>(util::toFloating(start.lon)),\n                          static_cast<double>(util::toFloating(start.lat)));\n    geo_line.emplace_back(static_cast<double>(util::toFloating(target.lon)),\n                          static_cast<double>(util::toFloating(target.lat)));\n\n    linestring_t unclipped_line;\n\n    for (auto const &pt : geo_line)\n    {\n        double px_merc = pt.x * util::web_mercator::DEGREE_TO_PX;\n        double py_merc = util::web_mercator::latToY(util::FloatLatitude{pt.y}) *\n                         util::web_mercator::DEGREE_TO_PX;\n        // convert lon/lat to tile coordinates\n        const auto px = std::round(\n            ((px_merc - tile_bbox.minx) * util::web_mercator::TILE_SIZE / tile_bbox.width()) *\n            util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE);\n        const auto py = std::round(\n            ((tile_bbox.maxy - py_merc) * util::web_mercator::TILE_SIZE / tile_bbox.height()) *\n            util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE);\n\n        boost::geometry::append(unclipped_line, point_t(px, py));\n    }\n\n    multi_linestring_t clipped_line;\n\n    boost::geometry::intersection(clip_box, unclipped_line, clipped_line);\n\n    FixedLine tile_line;\n\n    // b::g::intersection might return a line with one point if the\n    // original line was very short and coords were dupes\n    if (!clipped_line.empty() && clipped_line[0].size() == 2)\n    {\n        if (clipped_line[0].size() == 2)\n        {\n            for (const auto &p : clipped_line[0])\n            {\n                tile_line.emplace_back(p.get<0>(), p.get<1>());\n            }\n        }\n    }\n\n    return tile_line;\n}\n\n/**\n * Converts lon/lat into coordinates inside a Mercator projection tile (x/y pixel values)\n *\n * @param point the lon/lat you want the tile coords for\n * @param tile_bbox the mercator boundaries of the tile\n * @return a point (x,y) on the tile defined by tile_bbox\n */\nFixedPoint coordinatesToTilePoint(const util::Coordinate point, const BBox &tile_bbox)\n{\n    const FloatPoint geo_point{static_cast<double>(util::toFloating(point.lon)),\n                               static_cast<double>(util::toFloating(point.lat))};\n\n    const double px_merc = geo_point.x * util::web_mercator::DEGREE_TO_PX;\n    const double py_merc = util::web_mercator::latToY(util::FloatLatitude{geo_point.y}) *\n                           util::web_mercator::DEGREE_TO_PX;\n\n    const auto px = static_cast<std::int32_t>(std::round(\n        ((px_merc - tile_bbox.minx) * util::web_mercator::TILE_SIZE / tile_bbox.width()) *\n        util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE));\n    const auto py = static_cast<std::int32_t>(std::round(\n        ((tile_bbox.maxy - py_merc) * util::web_mercator::TILE_SIZE / tile_bbox.height()) *\n        util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE));\n\n    return FixedPoint{px, py};\n}\n\nstd::vector<RTreeLeaf> getEdges(const DataFacadeBase &facade, unsigned x, unsigned y, unsigned z)\n{\n    double min_lon, min_lat, max_lon, max_lat;\n\n    // Convert the z,x,y mercator tile coordinates into WGS84 lon/lat values\n    //\n    util::web_mercator::xyzToWGS84(\n        x, y, z, min_lon, min_lat, max_lon, max_lat, util::web_mercator::TILE_SIZE * 0.10);\n\n    util::Coordinate southwest{util::FloatLongitude{min_lon}, util::FloatLatitude{min_lat}};\n    util::Coordinate northeast{util::FloatLongitude{max_lon}, util::FloatLatitude{max_lat}};\n\n    // Fetch all the segments that are in our bounding box.\n    // This hits the OSRM StaticRTree\n    return facade.GetEdgesInBox(southwest, northeast);\n}\n\nstd::vector<std::size_t> getEdgeIndex(const std::vector<RTreeLeaf> &edges)\n{\n    // In order to ensure consistent tile encoding, we need to process\n    // all edges in the same order.  Differences in OSX/Linux/Windows\n    // sorting methods mean that GetEdgesInBox doesn't return the same\n    // ordered array on all platforms.\n    // GetEdgesInBox is marked `const`, so we can't sort the array itself,\n    // instead we create an array of indexes and sort that instead.\n    std::vector<std::size_t> sorted_edge_indexes(edges.size(), 0);\n    std::iota(\n        sorted_edge_indexes.begin(), sorted_edge_indexes.end(), 0); // fill with 0,1,2,3,...N-1\n\n    // Now, sort that array based on the edges list, using the u/v node IDs\n    // as the sort condition\n    std::sort(sorted_edge_indexes.begin(),\n              sorted_edge_indexes.end(),\n              [&edges](const std::size_t &left, const std::size_t &right) -> bool {\n                  return (edges[left].u != edges[right].u) ? edges[left].u < edges[right].u\n                                                           : edges[left].v < edges[right].v;\n              });\n\n    return sorted_edge_indexes;\n}\n\nvoid encodeVectorTile(const DataFacadeBase &facade,\n                      unsigned x,\n                      unsigned y,\n                      unsigned z,\n                      const std::vector<RTreeLeaf> &edges,\n                      const std::vector<std::size_t> &sorted_edge_indexes,\n                      const std::vector<routing_algorithms::TurnData> &all_turn_data,\n                      std::string &pbf_buffer)\n{\n\n    std::uint8_t max_datasource_id = 0;\n\n    // Vector tiles encode properties on features as indexes into a layer-specific\n    // lookup table.  These ValueIndexer's act as memoizers for values as we discover\n    // them during edge explioration, and are then used to generate the lookup\n    // tables for each tile layer.\n    ValueIndexer<int> line_int_index;\n    ValueIndexer<util::StringView> line_string_index;\n    ValueIndexer<int> point_int_index;\n    ValueIndexer<float> point_float_index;\n    ValueIndexer<std::string> point_string_index;\n\n    const auto get_geometry_id = [&facade](auto edge) {\n        return facade.GetGeometryIndex(edge.forward_segment_id.id).id;\n    };\n\n    // Vector tiles encode feature properties as indexes into a lookup table.  So, we need\n    // to \"pre-loop\" over all the edges to create the lookup tables.  Once we have those, we\n    // can then encode the features, and we'll know the indexes that feature properties\n    // need to refer to.\n    for (const auto &edge_index : sorted_edge_indexes)\n    {\n        const auto &edge = edges[edge_index];\n\n        const auto geometry_id = get_geometry_id(edge);\n        const auto forward_datasource_vector =\n            facade.GetUncompressedForwardDatasources(geometry_id);\n        const auto reverse_datasource_vector =\n            facade.GetUncompressedReverseDatasources(geometry_id);\n\n        BOOST_ASSERT(edge.fwd_segment_position < forward_datasource_vector.size());\n        const auto forward_datasource = forward_datasource_vector[edge.fwd_segment_position];\n        BOOST_ASSERT(edge.fwd_segment_position < reverse_datasource_vector.size());\n        const auto reverse_datasource = reverse_datasource_vector[reverse_datasource_vector.size() -\n                                                                  edge.fwd_segment_position - 1];\n\n        // Keep track of the highest datasource seen so that we don't write unnecessary\n        // data to the layer attribute values\n        max_datasource_id = std::max(max_datasource_id, forward_datasource);\n        max_datasource_id = std::max(max_datasource_id, reverse_datasource);\n    }\n\n    // Convert tile coordinates into mercator coordinates\n    double min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat;\n    util::web_mercator::xyzToMercator(\n        x, y, z, min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat);\n    const BBox tile_bbox{min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat};\n\n    // Protobuf serializes blocks when objects go out of scope, hence\n    // the extra scoping below.\n    protozero::pbf_writer tile_writer{pbf_buffer};\n    {\n        {\n            // Add a layer object to the PBF stream.  3=='layer' from the vector tile spec\n            // (2.1)\n            protozero::pbf_writer line_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);\n            // TODO: don't write a layer if there are no features\n\n            line_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2); // version\n            // Field 1 is the \"layer name\" field, it's a string\n            line_layer_writer.add_string(util::vector_tile::NAME_TAG, \"speeds\"); // name\n            // Field 5 is the tile extent.  It's a uint32 and should be set to 4096\n            // for normal vector tiles.\n            line_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,\n                                         util::vector_tile::EXTENT); // extent\n\n            // Because we need to know the indexes into the vector tile lookup table,\n            // we need to do an initial pass over the data and create the complete\n            // index of used values.\n            for (const auto &edge_index : sorted_edge_indexes)\n            {\n                const auto &edge = edges[edge_index];\n                const auto geometry_id = get_geometry_id(edge);\n\n                // Get coordinates for start/end nodes of segment (NodeIDs u and v)\n                const auto a = facade.GetCoordinateOfNode(edge.u);\n                const auto b = facade.GetCoordinateOfNode(edge.v);\n                // Calculate the length in meters\n                const double length = osrm::util::coordinate_calculation::haversineDistance(a, b);\n\n                // Weight values\n                const auto forward_weight_vector =\n                    facade.GetUncompressedForwardWeights(geometry_id);\n                const auto reverse_weight_vector =\n                    facade.GetUncompressedReverseWeights(geometry_id);\n                const auto forward_weight = forward_weight_vector[edge.fwd_segment_position];\n                const auto reverse_weight = reverse_weight_vector[reverse_weight_vector.size() -\n                                                                  edge.fwd_segment_position - 1];\n                line_int_index.add(forward_weight);\n                line_int_index.add(reverse_weight);\n\n                std::uint32_t forward_rate =\n                    static_cast<std::uint32_t>(round(length / forward_weight * 10.));\n                std::uint32_t reverse_rate =\n                    static_cast<std::uint32_t>(round(length / reverse_weight * 10.));\n\n                line_int_index.add(forward_rate);\n                line_int_index.add(reverse_rate);\n\n                // Duration values\n                const auto forward_duration_vector =\n                    facade.GetUncompressedForwardDurations(geometry_id);\n                const auto reverse_duration_vector =\n                    facade.GetUncompressedReverseDurations(geometry_id);\n                const auto forward_duration = forward_duration_vector[edge.fwd_segment_position];\n                const auto reverse_duration =\n                    reverse_duration_vector[reverse_duration_vector.size() -\n                                            edge.fwd_segment_position - 1];\n                line_int_index.add(forward_duration);\n                line_int_index.add(reverse_duration);\n            }\n\n            // Begin the layer features block\n            {\n                // Each feature gets a unique id, starting at 1\n                unsigned id = 1;\n                for (const auto &edge_index : sorted_edge_indexes)\n                {\n                    const auto &edge = edges[edge_index];\n                    const auto geometry_id = get_geometry_id(edge);\n\n                    // Get coordinates for start/end nodes of segment (NodeIDs u and v)\n                    const auto a = facade.GetCoordinateOfNode(edge.u);\n                    const auto b = facade.GetCoordinateOfNode(edge.v);\n                    // Calculate the length in meters\n                    const double length =\n                        osrm::util::coordinate_calculation::haversineDistance(a, b);\n\n                    const auto forward_weight_vector =\n                        facade.GetUncompressedForwardWeights(geometry_id);\n                    const auto reverse_weight_vector =\n                        facade.GetUncompressedReverseWeights(geometry_id);\n                    const auto forward_duration_vector =\n                        facade.GetUncompressedForwardDurations(geometry_id);\n                    const auto reverse_duration_vector =\n                        facade.GetUncompressedReverseDurations(geometry_id);\n                    const auto forward_datasource_vector =\n                        facade.GetUncompressedForwardDatasources(geometry_id);\n                    const auto reverse_datasource_vector =\n                        facade.GetUncompressedReverseDatasources(geometry_id);\n                    const auto forward_weight = forward_weight_vector[edge.fwd_segment_position];\n                    const auto reverse_weight =\n                        reverse_weight_vector[reverse_weight_vector.size() -\n                                              edge.fwd_segment_position - 1];\n                    const auto forward_duration =\n                        forward_duration_vector[edge.fwd_segment_position];\n                    const auto reverse_duration =\n                        reverse_duration_vector[reverse_duration_vector.size() -\n                                                edge.fwd_segment_position - 1];\n                    const auto forward_datasource_idx =\n                        forward_datasource_vector[edge.fwd_segment_position];\n                    const auto reverse_datasource_idx =\n                        reverse_datasource_vector[reverse_datasource_vector.size() -\n                                                  edge.fwd_segment_position - 1];\n\n                    const auto component_id = facade.GetComponentID(edge.forward_segment_id.id);\n                    const auto name_id = facade.GetNameIndex(edge.forward_segment_id.id);\n                    auto name = facade.GetNameForID(name_id);\n\n                    line_string_index.add(name);\n\n                    const auto encode_tile_line = [&line_layer_writer,\n                                                   &edge,\n                                                   &component_id,\n                                                   &id,\n                                                   &max_datasource_id,\n                                                   &line_int_index](\n                        const FixedLine &tile_line,\n                        const std::uint32_t speed_kmh_idx,\n                        const std::uint32_t rate_idx,\n                        const std::size_t weight_idx,\n                        const std::size_t duration_idx,\n                        const DatasourceID datasource_idx,\n                        const std::size_t name_idx,\n                        std::int32_t &start_x,\n                        std::int32_t &start_y) {\n                        // Here, we save the two attributes for our feature: the speed and\n                        // the is_small boolean.  We only serve up speeds from 0-139, so all we\n                        // do is save the first\n                        protozero::pbf_writer feature_writer(line_layer_writer,\n                                                             util::vector_tile::FEATURE_TAG);\n                        // Field 3 is the \"geometry type\" field.  Value 2 is \"line\"\n                        feature_writer.add_enum(\n                            util::vector_tile::GEOMETRY_TAG,\n                            util::vector_tile::GEOMETRY_TYPE_LINE); // geometry type\n                        // Field 1 for the feature is the \"id\" field.\n                        feature_writer.add_uint64(util::vector_tile::ID_TAG, id++); // id\n                        {\n                            // When adding attributes to a feature, we have to write\n                            // pairs of numbers.  The first value is the index in the\n                            // keys array (written later), and the second value is the\n                            // index into the \"values\" array (also written later).  We're\n                            // not writing the actual speed or bool value here, we're saving\n                            // an index into the \"values\" array.  This means many features\n                            // can share the same value data, leading to smaller tiles.\n                            protozero::packed_field_uint32 field(\n                                feature_writer, util::vector_tile::FEATURE_ATTRIBUTES_TAG);\n\n                            field.add_element(0); // \"speed\" tag key offset\n                            field.add_element(std::min(\n                                speed_kmh_idx, 127u)); // save the speed value, capped at 127\n                            field.add_element(1);      // \"is_small\" tag key offset\n                            field.add_element(\n                                128 + (component_id.is_tiny ? 0 : 1)); // is_small feature offset\n                            field.add_element(2);                    // \"datasource\" tag key offset\n                            field.add_element(130 + datasource_idx); // datasource value offset\n                            field.add_element(3);                    // \"weight\" tag key offset\n                            field.add_element(130 + max_datasource_id + 1 +\n                                              weight_idx); // weight value offset\n                            field.add_element(4);          // \"duration\" tag key offset\n                            field.add_element(130 + max_datasource_id + 1 +\n                                              duration_idx); // duration value offset\n                            field.add_element(5);            // \"name\" tag key offset\n\n                            field.add_element(130 + max_datasource_id + 1 +\n                                              line_int_index.values().size() + name_idx);\n\n                            field.add_element(6); // rate tag key offset\n                            field.add_element(130 + max_datasource_id + 1 + rate_idx);\n                        }\n                        {\n\n                            // Encode the geometry for the feature\n                            protozero::packed_field_uint32 geometry(\n                                feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);\n                            encodeLinestring(tile_line, geometry, start_x, start_y);\n                        }\n                    };\n\n                    // If this is a valid forward edge, go ahead and add it to the tile\n                    if (forward_duration != 0 && edge.forward_segment_id.enabled)\n                    {\n                        std::int32_t start_x = 0;\n                        std::int32_t start_y = 0;\n\n                        // Calculate the speed for this line\n                        // Speeds are looked up in a simple 1:1 table, so the speed value == lookup\n                        // table index\n                        std::uint32_t speed_kmh_idx =\n                            static_cast<std::uint32_t>(round(length / forward_duration * 10 * 3.6));\n\n                        // Rate values are in meters per weight-unit - and similar to speeds, we\n                        // present 1 decimal place of precision (these values are added as\n                        // double/10) lower down\n                        std::uint32_t forward_rate =\n                            static_cast<std::uint32_t>(round(length / forward_weight * 10.));\n\n                        auto tile_line = coordinatesToTileLine(a, b, tile_bbox);\n                        if (!tile_line.empty())\n                        {\n                            encode_tile_line(tile_line,\n                                             speed_kmh_idx,\n                                             line_int_index.indexOf(forward_rate),\n                                             line_int_index.indexOf(forward_weight),\n                                             line_int_index.indexOf(forward_duration),\n                                             forward_datasource_idx,\n                                             line_string_index.indexOf(name),\n                                             start_x,\n                                             start_y);\n                        }\n                    }\n\n                    // Repeat the above for the coordinates reversed and using the `reverse`\n                    // properties\n                    if (reverse_duration != 0 && edge.reverse_segment_id.enabled)\n                    {\n                        std::int32_t start_x = 0;\n                        std::int32_t start_y = 0;\n\n                        // Calculate the speed for this line\n                        // Speeds are looked up in a simple 1:1 table, so the speed value == lookup\n                        // table index\n                        std::uint32_t speed_kmh_idx =\n                            static_cast<std::uint32_t>(round(length / reverse_duration * 10 * 3.6));\n\n                        // Rate values are in meters per weight-unit - and similar to speeds, we\n                        // present 1 decimal place of precision (these values are added as\n                        // double/10) lower down\n                        std::uint32_t reverse_rate =\n                            static_cast<std::uint32_t>(round(length / reverse_weight * 10.));\n\n                        auto tile_line = coordinatesToTileLine(b, a, tile_bbox);\n                        if (!tile_line.empty())\n                        {\n                            encode_tile_line(tile_line,\n                                             speed_kmh_idx,\n                                             line_int_index.indexOf(reverse_rate),\n                                             line_int_index.indexOf(reverse_weight),\n                                             line_int_index.indexOf(reverse_duration),\n                                             reverse_datasource_idx,\n                                             line_string_index.indexOf(name),\n                                             start_x,\n                                             start_y);\n                        }\n                    }\n                }\n            }\n\n            // Field id 3 is the \"keys\" attribute\n            // We need two \"key\" fields, these are referred to with 0 and 1 (their array\n            // indexes) earlier\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"speed\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"is_small\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"datasource\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"weight\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"duration\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"name\");\n            line_layer_writer.add_string(util::vector_tile::KEY_TAG, \"rate\");\n\n            // Now, we write out the possible speed value arrays and possible is_tiny\n            // values.  Field type 4 is the \"values\" field.  It's a variable type field,\n            // so requires a two-step write (create the field, then write its value)\n            for (std::size_t i = 0; i < 128; i++)\n            {\n                // Writing field type 4 == variant type\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 5 == uint64 type\n                values_writer.add_uint64(util::vector_tile::VARIANT_TYPE_UINT64, i);\n            }\n            {\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 7 == bool type\n                values_writer.add_bool(util::vector_tile::VARIANT_TYPE_BOOL, true);\n            }\n            {\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 7 == bool type\n                values_writer.add_bool(util::vector_tile::VARIANT_TYPE_BOOL, false);\n            }\n            for (std::size_t i = 0; i <= max_datasource_id; i++)\n            {\n                // Writing field type 4 == variant type\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 1 == string type\n                values_writer.add_string(util::vector_tile::VARIANT_TYPE_STRING,\n                                         facade.GetDatasourceName(i).to_string());\n            }\n            for (auto value : line_int_index.values())\n            {\n                // Writing field type 4 == variant type\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 2 == float type\n                // Durations come out of OSRM in integer deciseconds, so we convert them\n                // to seconds with a simple /10 for display\n                values_writer.add_double(util::vector_tile::VARIANT_TYPE_DOUBLE, value / 10.);\n            }\n\n            for (const auto &name : line_string_index.values())\n            {\n                // Writing field type 4 == variant type\n                protozero::pbf_writer values_writer(line_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                // Attribute value 1 == string type\n                values_writer.add_string(\n                    util::vector_tile::VARIANT_TYPE_STRING, name.data(), name.size());\n            }\n        }\n\n        // Only add the turn layer to the tile if it has some features (we sometimes won't\n        // for tiles of z<16, and tiles that don't show any intersections)\n        if (!all_turn_data.empty())\n        {\n\n            struct EncodedTurnData\n            {\n                util::Coordinate coordinate;\n                std::size_t angle_index;\n                std::size_t turn_index;\n                std::size_t duration_index;\n                std::size_t weight_index;\n                std::size_t turntype_index;\n                std::size_t turnmodifier_index;\n            };\n            // we need to pre-encode all values here because we need the full offsets later\n            // for encoding the actual features.\n            std::vector<EncodedTurnData> encoded_turn_data(all_turn_data.size());\n            std::transform(\n                all_turn_data.begin(),\n                all_turn_data.end(),\n                encoded_turn_data.begin(),\n                [&](const routing_algorithms::TurnData &t) {\n                    auto angle_idx = point_int_index.add(t.in_angle);\n                    auto turn_idx = point_int_index.add(t.turn_angle);\n                    auto duration_idx =\n                        point_float_index.add(t.duration / 10.0); // Note conversion to float here\n                    auto weight_idx =\n                        point_float_index.add(t.weight / 10.0); // Note conversion to float here\n\n                    auto turntype_idx =\n                        point_string_index.add(extractor::guidance::internalInstructionTypeToString(\n                            t.turn_instruction.type));\n                    auto turnmodifier_idx =\n                        point_string_index.add(extractor::guidance::instructionModifierToString(\n                            t.turn_instruction.direction_modifier));\n                    return EncodedTurnData{t.coordinate,\n                                           angle_idx,\n                                           turn_idx,\n                                           duration_idx,\n                                           weight_idx,\n                                           turntype_idx,\n                                           turnmodifier_idx};\n                });\n\n            // Now write the points layer for turn penalty data:\n            // Add a layer object to the PBF stream.  3=='layer' from the vector tile spec\n            // (2.1)\n            protozero::pbf_writer point_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);\n            point_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2);    // version\n            point_layer_writer.add_string(util::vector_tile::NAME_TAG, \"turns\"); // name\n            point_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,\n                                          util::vector_tile::EXTENT); // extent\n\n            // Begin writing the set of point features\n            {\n                // Start each features with an ID starting at 1\n                int id = 1;\n\n                // Helper function to encode a new point feature on a vector tile.\n                const auto encode_tile_point = [&](const FixedPoint &tile_point,\n                                                   const auto &point_turn_data) {\n                    protozero::pbf_writer feature_writer(point_layer_writer,\n                                                         util::vector_tile::FEATURE_TAG);\n                    // Field 3 is the \"geometry type\" field.  Value 1 is \"point\"\n                    feature_writer.add_enum(\n                        util::vector_tile::GEOMETRY_TAG,\n                        util::vector_tile::GEOMETRY_TYPE_POINT);                // geometry type\n                    feature_writer.add_uint64(util::vector_tile::ID_TAG, id++); // id\n                    {\n                        // Write out the 4 properties we want on the feature.  These\n                        // refer to indexes in the properties lookup table, which we\n                        // add to the tile after we add all features.\n                        protozero::packed_field_uint32 field(\n                            feature_writer, util::vector_tile::FEATURE_ATTRIBUTES_TAG);\n                        field.add_element(0); // \"bearing_in\" tag key offset\n                        field.add_element(point_turn_data.angle_index);\n                        field.add_element(1); // \"turn_angle\" tag key offset\n                        field.add_element(point_turn_data.turn_index);\n                        field.add_element(2); // \"cost\" tag key offset\n                        field.add_element(point_int_index.size() + point_turn_data.duration_index);\n                        field.add_element(3); // \"weight\" tag key offset\n                        field.add_element(point_int_index.size() + point_turn_data.weight_index);\n                        field.add_element(4); // \"type\" tag key offset\n                        field.add_element(point_int_index.size() + point_float_index.size() +\n                                          point_turn_data.turntype_index);\n                        field.add_element(5); // \"modifier\" tag key offset\n                        field.add_element(point_int_index.size() + point_float_index.size() +\n                                          point_turn_data.turnmodifier_index);\n                    }\n                    {\n                        // Add the geometry as the last field in this feature\n                        protozero::packed_field_uint32 geometry(\n                            feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);\n                        encodePoint(tile_point, geometry);\n                    }\n                };\n\n                // Loop over all the turns we found and add them as features to the layer\n                for (const auto &turndata : encoded_turn_data)\n                {\n                    const auto tile_point = coordinatesToTilePoint(turndata.coordinate, tile_bbox);\n                    if (!boost::geometry::within(point_t(tile_point.x, tile_point.y), clip_box))\n                    {\n                        continue;\n                    }\n                    encode_tile_point(tile_point, turndata);\n                }\n            }\n\n            // Add the names of the three attributes we added to all the turn penalty\n            // features previously.  The indexes used there refer to these keys.\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"bearing_in\");\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"turn_angle\");\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"cost\");\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"weight\");\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"type\");\n            point_layer_writer.add_string(util::vector_tile::KEY_TAG, \"modifier\");\n\n            // Now, save the lists of integers and floats that our features refer to.\n            for (const auto &value : point_int_index.values())\n            {\n                protozero::pbf_writer values_writer(point_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                values_writer.add_sint64(util::vector_tile::VARIANT_TYPE_SINT64, value);\n            }\n            for (const auto &value : point_float_index.values())\n            {\n                protozero::pbf_writer values_writer(point_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                values_writer.add_float(util::vector_tile::VARIANT_TYPE_FLOAT, value);\n            }\n            for (const auto &value : point_string_index.values())\n            {\n                protozero::pbf_writer values_writer(point_layer_writer,\n                                                    util::vector_tile::VARIANT_TAG);\n                values_writer.add_string(util::vector_tile::VARIANT_TYPE_STRING, value);\n            }\n        }\n\n        // OSM Node tile layer\n        {\n            protozero::pbf_writer point_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);\n            point_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2);       // version\n            point_layer_writer.add_string(util::vector_tile::NAME_TAG, \"osmnodes\"); // name\n            point_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,\n                                          util::vector_tile::EXTENT); // extent\n\n            std::vector<NodeID> internal_nodes;\n            internal_nodes.reserve(edges.size() * 2);\n            for (const auto &edge : edges)\n            {\n                internal_nodes.push_back(edge.u);\n                internal_nodes.push_back(edge.v);\n            }\n            std::sort(internal_nodes.begin(), internal_nodes.end());\n            auto new_end = std::unique(internal_nodes.begin(), internal_nodes.end());\n            internal_nodes.resize(new_end - internal_nodes.begin());\n\n            for (const auto &internal_node : internal_nodes)\n            {\n                const auto coord = facade.GetCoordinateOfNode(internal_node);\n                const auto tile_point = coordinatesToTilePoint(coord, tile_bbox);\n                if (!boost::geometry::within(point_t(tile_point.x, tile_point.y), clip_box))\n                {\n                    continue;\n                }\n                protozero::pbf_writer feature_writer(point_layer_writer,\n                                                     util::vector_tile::FEATURE_TAG);\n                // Field 3 is the \"geometry type\" field.  Value 1 is \"point\"\n                feature_writer.add_enum(util::vector_tile::GEOMETRY_TAG,\n                                        util::vector_tile::GEOMETRY_TYPE_POINT); // geometry type\n                const auto osmid =\n                    static_cast<OSMNodeID::value_type>(facade.GetOSMNodeIDOfNode(internal_node));\n                feature_writer.add_uint64(util::vector_tile::ID_TAG, osmid); // id\n                // There are no additional properties, just the ID and the geometry\n                {\n                    // Add the geometry as the last field in this feature\n                    protozero::packed_field_uint32 geometry(\n                        feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);\n                    encodePoint(tile_point, geometry);\n                }\n            }\n        }\n    }\n    // protozero serializes data during object destructors, so once the scope closes,\n    // our result buffer will have all the tile data encoded into it.\n}\n}\n\nStatus TilePlugin::HandleRequest(const RoutingAlgorithmsInterface &algorithms,\n                                 const api::TileParameters &parameters,\n                                 std::string &pbf_buffer) const\n{\n    BOOST_ASSERT(parameters.IsValid());\n\n    const auto &facade = algorithms.GetFacade();\n    auto edges = getEdges(facade, parameters.x, parameters.y, parameters.z);\n\n    auto edge_index = getEdgeIndex(edges);\n\n    std::vector<routing_algorithms::TurnData> turns;\n\n    // If we're zooming into 16 or higher, include turn data.  Why?  Because turns make the map\n    // really cramped, so we don't bother including the data for tiles that span a large area.\n    if (parameters.z >= MIN_ZOOM_FOR_TURNS && algorithms.HasGetTileTurns())\n    {\n        turns = algorithms.GetTileTurns(edges, edge_index);\n    }\n\n    encodeVectorTile(\n        facade, parameters.x, parameters.y, parameters.z, edges, edge_index, turns, pbf_buffer);\n\n    return Status::Ok;\n}\n}\n}\n}\n", "meta": {"hexsha": "41a850e6e9307d3b346112bab8409627b019060d", "size": 43767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/engine/plugins/tile.cpp", "max_stars_repo_name": "neilbu/osrm-backend", "max_stars_repo_head_hexsha": "2a8e1f77459fef33ca34c9fe01ec62e88e255452", "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/engine/plugins/tile.cpp", "max_issues_repo_name": "neilbu/osrm-backend", "max_issues_repo_head_hexsha": "2a8e1f77459fef33ca34c9fe01ec62e88e255452", "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/engine/plugins/tile.cpp", "max_forks_repo_name": "neilbu/osrm-backend", "max_forks_repo_head_hexsha": "2a8e1f77459fef33ca34c9fe01ec62e88e255452", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-24T14:24:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T14:24:44.000Z", "avg_line_length": 48.4148230088, "max_line_length": 100, "alphanum_fraction": 0.5639408687, "num_tokens": 8630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1949512801040086}}
{"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// File generated at Sat 27 Aug 2016 12:51:19\n\n#ifndef MSSM_PHYSICAL_H\n#define MSSM_PHYSICAL_H\n\n#include \"linalg2.hpp\"\n#include <Eigen/Core>\n\n#include <iosfwd>\n#include <string>\n\nnamespace flexiblesusy {\n\nstruct MSSM_physical {\n   MSSM_physical();\n   void clear();\n   void convert_to_hk();   ///< converts pole masses to HK convention\n   void convert_to_slha(); ///< converts pole masses to SLHA convention\n   Eigen::ArrayXd get() const; ///< returns array with all masses and mixings\n   void set(const Eigen::ArrayXd&); ///< set all masses and mixings\n   Eigen::ArrayXd get_masses() const; ///< returns array with all masses\n   void set_masses(const Eigen::ArrayXd&); ///< set all masses\n   void print(std::ostream&) const;\n\n   double MVG;\n   double MGlu;\n   Eigen::Array<double,3,1> MFv;\n   Eigen::Array<double,6,1> MSd;\n   Eigen::Array<double,3,1> MSv;\n   Eigen::Array<double,6,1> MSu;\n   Eigen::Array<double,6,1> MSe;\n   Eigen::Array<double,2,1> Mhh;\n   Eigen::Array<double,2,1> MAh;\n   Eigen::Array<double,2,1> MHpm;\n   Eigen::Array<double,4,1> MChi;\n   Eigen::Array<double,2,1> MCha;\n   Eigen::Array<double,3,1> MFe;\n   Eigen::Array<double,3,1> MFd;\n   Eigen::Array<double,3,1> MFu;\n   double MVWm;\n   double MVP;\n   double MVZ;\n\n   Eigen::Matrix<double,6,6> ZD;\n   Eigen::Matrix<double,3,3> ZV;\n   Eigen::Matrix<double,6,6> ZU;\n   Eigen::Matrix<double,6,6> ZE;\n   Eigen::Matrix<double,2,2> ZH;\n   Eigen::Matrix<double,2,2> ZA;\n   Eigen::Matrix<double,2,2> ZP;\n   Eigen::Matrix<std::complex<double>,4,4> ZN;\n   Eigen::Matrix<std::complex<double>,2,2> UM;\n   Eigen::Matrix<std::complex<double>,2,2> UP;\n   Eigen::Matrix<std::complex<double>,3,3> ZEL;\n   Eigen::Matrix<std::complex<double>,3,3> ZER;\n   Eigen::Matrix<std::complex<double>,3,3> ZDL;\n   Eigen::Matrix<std::complex<double>,3,3> ZDR;\n   Eigen::Matrix<std::complex<double>,3,3> ZUL;\n   Eigen::Matrix<std::complex<double>,3,3> ZUR;\n   Eigen::Matrix<double,2,2> ZZ;\n\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSM_physical&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "682cdf88f3eea4802539036f7598b498c277cd2f", "size": 2869, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSM/MSSM_physical.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/models/MSSM/MSSM_physical.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/models/MSSM/MSSM_physical.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": 32.9770114943, "max_line_length": 77, "alphanum_fraction": 0.6563262461, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.19477999026921686}}
{"text": "#include <FeePolicyEstimator.h>\n\n#include <boost/foreach.hpp>\n#include <streams.h>\n#include <Logging.h>\n#include <MemPoolEntry.h>\n\ntemplate <typename T>\nstd::vector<T> buf2vec(boost::circular_buffer<T> buf)\n{\n    std::vector<T> vec(buf.begin(), buf.end());\n    return vec;\n}\n\nCBlockAverage::CBlockAverage() : feeSamples(100), prioritySamples(100) {}\n\nvoid CBlockAverage::RecordFee(const CFeeRate& feeRate)\n{\n    feeSamples.push_back(feeRate);\n}\n\nvoid CBlockAverage::RecordPriority(double priority)\n{\n    prioritySamples.push_back(priority);\n}\n\nsize_t CBlockAverage::FeeSamples() const { return feeSamples.size(); }\nsize_t CBlockAverage::GetFeeSamples(std::vector<CFeeRate>& insertInto) const\n{\n    BOOST_FOREACH (const CFeeRate& f, feeSamples)\n        insertInto.push_back(f);\n    return feeSamples.size();\n}\nsize_t CBlockAverage::PrioritySamples() const { return prioritySamples.size(); }\nsize_t CBlockAverage::GetPrioritySamples(std::vector<double>& insertInto) const\n{\n    BOOST_FOREACH (double d, prioritySamples)\n        insertInto.push_back(d);\n    return prioritySamples.size();\n}\n\n/**\n * Used as belt-and-suspenders check when reading to detect\n * file corruption\n */\nbool CBlockAverage::AreSane(const CFeeRate fee, const CFeeRate& minRelayFee)\n{\n    if (fee < CFeeRate(0))\n        return false;\n    if (fee.GetFeePerK() > minRelayFee.GetFeePerK() * 10000)\n        return false;\n    return true;\n}\nbool CBlockAverage::AreSane(const std::vector<CFeeRate>& vecFee, const CFeeRate& minRelayFee)\n{\n    BOOST_FOREACH (CFeeRate fee, vecFee) {\n        if (!AreSane(fee, minRelayFee))\n            return false;\n    }\n    return true;\n}\nbool CBlockAverage::AreSane(const double priority)\n{\n    return priority >= 0;\n}\nbool CBlockAverage::AreSane(const std::vector<double> vecPriority)\n{\n    BOOST_FOREACH (double priority, vecPriority) {\n        if (!AreSane(priority))\n            return false;\n    }\n    return true;\n}\n\nvoid CBlockAverage::Write(CAutoFile& fileout) const\n{\n    std::vector<CFeeRate> vecFee = buf2vec(feeSamples);\n    fileout << vecFee;\n    std::vector<double> vecPriority = buf2vec(prioritySamples);\n    fileout << vecPriority;\n}\n\nvoid CBlockAverage::Read(CAutoFile& filein, const CFeeRate& minRelayFee)\n{\n    std::vector<CFeeRate> vecFee;\n    filein >> vecFee;\n    if (AreSane(vecFee, minRelayFee))\n        feeSamples.insert(feeSamples.end(), vecFee.begin(), vecFee.end());\n    else\n        throw std::runtime_error(\"Corrupt fee value in estimates file.\");\n    std::vector<double> vecPriority;\n    filein >> vecPriority;\n    if (AreSane(vecPriority))\n        prioritySamples.insert(prioritySamples.end(), vecPriority.begin(), vecPriority.end());\n    else\n        throw std::runtime_error(\"Corrupt priority value in estimates file.\");\n    if (feeSamples.size() + prioritySamples.size() > 0)\n        LogPrint(\"estimatefee\", \"Read %d fee samples and %d priority samples\\n\",\n            feeSamples.size(), prioritySamples.size());\n}\n\n\n\nFeePolicyEstimator::FeePolicyEstimator(\n    int nEntries\n    ): history()\n    , sortedFeeSamples()\n    , sortedPrioritySamples()\n    , nBestSeenHeight(0)\n{\n    history.resize(nEntries);\n}\n\nvoid FeePolicyEstimator::seenTxConfirm(const CFeeRate& feeRate, const CFeeRate& minRelayFee, double coinAgeOfInputsPerByte, int nBlocksAgo)\n{\n    // Last entry records \"everything else\".\n    int nBlocksTruncated = std::min(nBlocksAgo, (int)history.size() - 1);\n    assert(nBlocksTruncated >= 0);\n\n    // We need to guess why the transaction was included in a block-- either\n    // because it is high-priority or because it has sufficient fees.\n    bool sufficientFee = (feeRate > minRelayFee);\n    bool sufficientPriority = CTxMemPoolEntry::AllowFree(coinAgeOfInputsPerByte);\n    const char* assignedTo = \"unassigned\";\n    if (sufficientFee && !sufficientPriority && CBlockAverage::AreSane(feeRate, minRelayFee)) {\n        history[nBlocksTruncated].RecordFee(feeRate);\n        assignedTo = \"fee\";\n    } else if (sufficientPriority && !sufficientFee && CBlockAverage::AreSane(coinAgeOfInputsPerByte)) {\n        history[nBlocksTruncated].RecordPriority(coinAgeOfInputsPerByte);\n        assignedTo = \"priority\";\n    } else {\n        // Neither or both fee and priority sufficient to get confirmed:\n        // don't know why they got confirmed.\n    }\n    LogPrint(\"estimatefee\", \"Seen TX confirm: %s : %s fee/%g priority, took %d blocks\\n\",\n        assignedTo, feeRate, coinAgeOfInputsPerByte, nBlocksAgo);\n}\n\nvoid FeePolicyEstimator::seenBlock(const std::vector<const CTxMemPoolEntry*>& entries, int nBlockHeight, const CFeeRate minRelayFee)\n{\n    if (nBlockHeight <= nBestSeenHeight) {\n        // Ignore side chains and re-orgs; assuming they are random\n        // they don't affect the estimate.\n        // And if an attacker can re-org the chain at will, then\n        // you've got much bigger problems than \"attacker can influence\n        // transaction fees.\"\n        return;\n    }\n    nBestSeenHeight = nBlockHeight;\n\n    // Fill up the history buckets based on how long transactions took\n    // to confirm.\n    std::vector<std::vector<const CTxMemPoolEntry*> > entriesByConfirmations;\n    entriesByConfirmations.resize(history.size());\n    BOOST_FOREACH (const CTxMemPoolEntry* entryReference, entries) {\n        // How many blocks did it take for miners to include this transaction?\n        if (!entryReference) continue;\n        const CTxMemPoolEntry& entry = *entryReference;\n        int delta = nBlockHeight - entry.GetHeight();\n        if (delta <= 0) {\n            // Re-org made us lose height, this should only happen if we happen\n            // to re-org on a difficulty transition point: very rare!\n            continue;\n        }\n        if ((delta - 1) >= (int)history.size())\n            delta = history.size(); // Last bucket is catch-all\n        entriesByConfirmations.at(delta - 1).push_back(&entry);\n    }\n    for (size_t i = 0; i < entriesByConfirmations.size(); i++) {\n        std::vector<const CTxMemPoolEntry*>& e = entriesByConfirmations.at(i);\n        // Insert at most 10 random entries per bucket, otherwise a single block\n        // can dominate an estimate:\n        if (e.size() > 10) {\n            std::random_shuffle(e.begin(), e.end());\n            e.resize(10);\n        }\n        BOOST_FOREACH (const CTxMemPoolEntry* entry, e) {\n            // Fees are stored and reported as DIVI-per-kb:\n            CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());\n            double coinAgeOfInputsPerByte = entry->ComputeInputCoinAgePerByte(entry->GetHeight()); // Want priority when it went IN\n            seenTxConfirm(feeRate, minRelayFee, coinAgeOfInputsPerByte, i);\n        }\n    }\n\n    //After new samples are added, we have to clear the sorted lists,\n    //so they'll be resorted the next time someone asks for an estimate\n    sortedFeeSamples.clear();\n    sortedPrioritySamples.clear();\n\n    for (size_t i = 0; i < history.size(); i++) {\n        if (history[i].FeeSamples() + history[i].PrioritySamples() > 0)\n            LogPrint(\"estimatefee\", \"estimates: for confirming within %d blocks based on %d/%d samples, fee=%s, prio=%g\\n\",\n                i,\n                history[i].FeeSamples(), history[i].PrioritySamples(),\n                estimateFee(i + 1), estimatePriority(i + 1));\n    }\n}\n\n/**\n * Can return CFeeRate(0) if we don't have any data for that many blocks back. nBlocksToConfirm is 1 based.\n */\nCFeeRate FeePolicyEstimator::estimateFee(int nBlocksToConfirm)\n{\n    nBlocksToConfirm--;\n\n    if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())\n        return CFeeRate(0);\n\n    if (sortedFeeSamples.size() == 0) {\n        for (size_t i = 0; i < history.size(); i++)\n            history.at(i).GetFeeSamples(sortedFeeSamples);\n        std::sort(sortedFeeSamples.begin(), sortedFeeSamples.end(),\n            std::greater<CFeeRate>());\n    }\n    if (sortedFeeSamples.size() < 11) {\n        // Eleven is Gavin's Favorite Number\n        // ... but we also take a maximum of 10 samples per block so eleven means\n        // we're getting samples from at least two different blocks\n        return CFeeRate(0);\n    }\n\n    int nBucketSize = history.at(nBlocksToConfirm).FeeSamples();\n\n    // Estimates should not increase as number of confirmations goes up,\n    // but the estimates are noisy because confirmations happen discretely\n    // in blocks. To smooth out the estimates, use all samples in the history\n    // and use the nth highest where n is (number of samples in previous bucket +\n    // half the samples in nBlocksToConfirm bucket):\n    size_t nPrevSize = 0;\n    for (int i = 0; i < nBlocksToConfirm; i++)\n        nPrevSize += history.at(i).FeeSamples();\n    size_t index = std::min(nPrevSize + nBucketSize / 2, sortedFeeSamples.size() - 1);\n    return sortedFeeSamples[index];\n}\ndouble FeePolicyEstimator::estimatePriority(int nBlocksToConfirm)\n{\n    nBlocksToConfirm--;\n\n    if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())\n        return -1;\n\n    if (sortedPrioritySamples.size() == 0) {\n        for (size_t i = 0; i < history.size(); i++)\n            history.at(i).GetPrioritySamples(sortedPrioritySamples);\n        std::sort(sortedPrioritySamples.begin(), sortedPrioritySamples.end(),\n            std::greater<double>());\n    }\n    if (sortedPrioritySamples.size() < 11)\n        return -1.0;\n\n    int nBucketSize = history.at(nBlocksToConfirm).PrioritySamples();\n\n    // Estimates should not increase as number of confirmations needed goes up,\n    // but the estimates are noisy because confirmations happen discretely\n    // in blocks. To smooth out the estimates, use all samples in the history\n    // and use the nth highest where n is (number of samples in previous buckets +\n    // half the samples in nBlocksToConfirm bucket).\n    size_t nPrevSize = 0;\n    for (int i = 0; i < nBlocksToConfirm; i++)\n        nPrevSize += history.at(i).PrioritySamples();\n    size_t index = std::min(nPrevSize + nBucketSize / 2, sortedPrioritySamples.size() - 1);\n    return sortedPrioritySamples[index];\n}\n\nvoid FeePolicyEstimator::Write(CAutoFile& fileout) const\n{\n    fileout << nBestSeenHeight;\n    fileout << history.size();\n    BOOST_FOREACH (const CBlockAverage& entry, history) {\n        entry.Write(fileout);\n    }\n}\n\nvoid FeePolicyEstimator::Read(CAutoFile& filein, const CFeeRate& minRelayFee)\n{\n    int nFileBestSeenHeight;\n    filein >> nFileBestSeenHeight;\n    size_t numEntries;\n    filein >> numEntries;\n    if (numEntries <= 0 || numEntries > 10000)\n        throw std::runtime_error(\"Corrupt estimates file. Must have between 1 and 10k entries.\");\n\n    std::vector<CBlockAverage> fileHistory;\n\n    for (size_t i = 0; i < numEntries; i++) {\n        CBlockAverage entry;\n        entry.Read(filein, minRelayFee);\n        fileHistory.push_back(entry);\n    }\n\n    // Now that we've processed the entire fee estimate data file and not\n    // thrown any errors, we can copy it to our history\n    nBestSeenHeight = nFileBestSeenHeight;\n    history = fileHistory;\n    assert(history.size() > 0);\n}", "meta": {"hexsha": "0ce255c875885bd2298881f1d1b7b827b01c159e", "size": 11026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "divi/src/FeePolicyEstimator.cpp", "max_stars_repo_name": "DiviProject/Divi", "max_stars_repo_head_hexsha": "4d4e34a134c2497a3f272f48beacaf292f4b6d14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2019-05-16T21:31:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T16:13:02.000Z", "max_issues_repo_path": "divi/src/FeePolicyEstimator.cpp", "max_issues_repo_name": "Divicoin/Divi", "max_issues_repo_head_hexsha": "4d4e34a134c2497a3f272f48beacaf292f4b6d14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 98.0, "max_issues_repo_issues_event_min_datetime": "2018-03-07T19:30:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-29T14:17:12.000Z", "max_forks_repo_path": "divi/src/FeePolicyEstimator.cpp", "max_forks_repo_name": "DiviProject/Divi", "max_forks_repo_head_hexsha": "4d4e34a134c2497a3f272f48beacaf292f4b6d14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2019-05-07T11:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:06:12.000Z", "avg_line_length": 37.25, "max_line_length": 139, "alphanum_fraction": 0.6731362235, "num_tokens": 2779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.1947359095582749}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <limits.h>\n#include <cmath>\n#include <immintrin.h>\n#include <omp.h>\n#include \"bayes.hpp\"\n#include \"utilities.hpp\"\n#include \"dotp_lut.hpp\"\n#include \"na_lut.hpp\"\n#include \"xfiles.hpp\"\n#include <boost/math/special_functions/gamma.hpp>\n\n\nvoid Bayes::predict() {\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    double ts = MPI_Wtime();\n\n    check_openmp();\n\n    MPI_Status status;\n    MPI_Offset file_size = 0;\n    MPI_File*  fh;\n\n    cross_bim_files();\n\n    int pidx = 0;\n    for (auto& phen : pmgr.get_phens()) {\n        pidx += 1;\n\n        phen.delete_output_prediction_files();\n        phen.open_prediction_files();\n\n        const std::vector<unsigned char> mask4 = phen.get_mask4();\n        const int im4 = phen.get_im4();\n\n        fh = phen.get_inbet_fh();\n        check_mpi(MPI_File_get_size(*fh, &file_size), __LINE__, __FILE__);\n        //printf(\"file_size = %u B\\n\", file_size);\n\n        // First element of the .bet is the total number of processed markers\n        // Then: iteration (uint) beta (double) for all markers\n        uint Mtot_ = 0;\n        MPI_Offset betoff = size_t(0);\n        check_mpi(MPI_File_read_at_all(*fh, betoff, &Mtot_, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n        if (Mtot_ != m_refrsid.size()) {\n            printf(\"Mismatch between expected and Mtot read from .bet file: %lu vs %d\\n\", rsid.size(), Mtot_);\n            MPI_Abort(MPI_COMM_WORLD, 1);\n        }\n\n        assert((file_size - sizeof(uint)) % (Mtot_ * sizeof(double) + sizeof(uint)) == 0);\n        uint niter = (file_size - sizeof(uint)) / (Mtot_ * sizeof(double) + sizeof(uint));\n        if (rank == 0)\n            printf(\"INFO   : Number of recorded iterations in .bet file %d: %u\\n\", pidx-1, niter);\n\n        double* beta_sum = (double*) _mm_malloc(size_t(Mtot_) * sizeof(double), 32);\n        check_malloc(beta_sum, __LINE__, __FILE__);\n        for (int i=0; i<Mtot_; i++) beta_sum[i] = 0.0;\n\n        double* beta_it = (double*) _mm_malloc(size_t(Mtot_) * sizeof(double), 32);\n        check_malloc(beta_it, __LINE__, __FILE__);\n\n        uint start_iter = 0;\n        //EO: use this one to speed up testing (avoids to read the entire bet history)\n        //if (niter > 3) start_iter = niter - 3;\n\n        for (uint i=start_iter; i<niter; i++) {\n            betoff\n                = sizeof(uint) // Mtot\n                + (sizeof(uint) + size_t(Mtot_) * sizeof(double)) * size_t(i)\n                + sizeof(uint);\n            check_mpi(MPI_File_read_at_all(*fh, betoff, beta_it, Mtot_, MPI_DOUBLE, &status), __LINE__, __FILE__);\n            for (int j=0; j<Mtot_;j++)\n                beta_sum[j] += beta_it[j];\n        }\n\n        for (int j=0; j<Mtot_;j++)\n            beta_sum[j] /= double(niter);\n\n        fflush(stdout);\n        double t_1 = MPI_Wtime();\n        MPI_Barrier(MPI_COMM_WORLD);\n        //if (rank >= 0)\n        //    printf(\"INFO   : intermediate time 1 = %.2f seconds.\\n\", t_1 - ts);\n\n\n        double* g_k = (double*) _mm_malloc(size_t(im4*4) * sizeof(double), 32);\n        check_malloc(g_k, __LINE__, __FILE__);\n        for (int i=0; i<im4*4; i++) g_k[i] = 0.0;\n\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n        for (int mrki=0; mrki<M; mrki++) {\n\n            // Get rsid from current\n            int mglo = S + mrki;\n            std::string id = rsid.at(mglo);\n\n            // Skip markers with no corresponding rsid in reference bim file\n            if (m_refrsid.find(id) == m_refrsid.end()) {\n                //printf(\"%d -> %d = %s not found in reference bim\\n\", mrki, mglo, id.c_str());\n                continue;\n            }\n\n            int rmglo = m_refrsid.find(id)->second; // global marker index in reference bed\n\n            size_t bedix = size_t(mrki) * size_t(mbytes);\n            const unsigned char* bedm = &bed_data[bedix];\n\n            double mave = phen.get_marker_ave(mrki);\n            double msig = phen.get_marker_sig(mrki);\n\n            for (int j=0; j<im4; j++) {\n                for (int k=0; k<4; k++) {\n                    double val = (dotp_lut_a[bedm[j] * 4 + k] - mave) * dotp_lut_b[bedm[j] * 4 + k] * na_lut[mask4[j] * 4 + k] * msig;\n#ifdef _OPENMP\n#pragma omp atomic update\n#endif\n                    g_k[j*4+k] += val * beta_sum[mglo];\n                }\n            }\n        }\n\n        fflush(stdout);\n        double t_2 = MPI_Wtime();\n        MPI_Barrier(MPI_COMM_WORLD);\n        //if (rank >= 0)\n        //    printf(\"INFO   : intermediate time 2 = %.2f seconds.\\n\", t_2 - t_1);\n\n        double* g = (double*) _mm_malloc(size_t(im4*4) * sizeof(double), 32);\n        check_malloc(g, __LINE__, __FILE__);\n\n        check_mpi(MPI_Allreduce(g_k, g, im4*4, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD), __LINE__, __FILE__);\n\n        double* y_k = (double*) _mm_malloc(size_t(im4*4) * sizeof(double), 32);\n        check_malloc(y_k, __LINE__, __FILE__);\n\n        phen.get_centered_and_scaled_y(y_k);\n\n        //EO: already done when computing original epsilon when reading .phen\n\t//phen.set_nas_to_zero(y_k, im4*4);\n        // NAs are 0.0 in all, so should be safe\n        for (int i=0; i<im4*4; i++)\n            y_k[i] -= (g[i] - g_k[i]);\n\n        double sigma = 0.0;\n        for (int i=0; i<N; i++)\n            sigma += y_k[i] * y_k[i];\n        sigma /= phen.get_nonas();\n        //printf(\"### r: %d sigma = %20.15f\\n\", rank, sigma);\n\n        MPI_File* mlma_fh = phen.get_outmlma_fh();\n\n        double* Beta  = (double*) _mm_malloc(size_t(M) * sizeof(double), 32);\n        check_malloc(Beta, __LINE__, __FILE__);\n        double* Tdist = (double*) _mm_malloc(size_t(M) * sizeof(double), 32);\n        check_malloc(Tdist, __LINE__, __FILE__);\n        double* Se    = (double*) _mm_malloc(size_t(M) * sizeof(double), 32);\n        check_malloc(Se, __LINE__, __FILE__);\n        double* Pval  = (double*) _mm_malloc(size_t(M) * sizeof(double), 32);\n        check_malloc(Pval, __LINE__, __FILE__);\n\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n        for (int mrki=0; mrki<M; mrki++) {\n\n            // Global index in current .bim\n            int mglo = S + mrki;\n            std::string id = rsid.at(mglo);\n\n            // Skip markers with no corresponding rsid in reference bim file\n            if (m_refrsid.find(id) == m_refrsid.end()) {\n                //printf(\"%d -> %d = %s not found in reference bim\\n\", mrki, mglo, id.c_str());\n                continue;\n            }\n\n            // Global marker index in reference bed\n            int rmglo = m_refrsid.find(id)->second;\n\n            size_t bedix = size_t(mrki) * size_t(mbytes);\n            const unsigned char* bedm = &bed_data[bedix];\n\n            double mave = phen.get_marker_ave(mrki);\n            double msig = phen.get_marker_sig(mrki);\n\n            double xtx = 0.0;\n            double xty = 0.0;\n            double chk = 0.0;\n            for (int j=0; j<im4; j++) {\n                for (int k=0; k<4; k++) {\n                    double val = dotp_lut_a[bedm[j] * 4 + k] * dotp_lut_b[bedm[j] * 4 + k] * na_lut[mask4[j] * 4 + k];\n                    xtx += val * val;\n                    xty += val * y_k[j*4 + k];\n                }\n            }\n\n            double beta  = xty / xtx;\n            double tdist = xty / sqrt(sigma * xtx);\n            double se    = beta / tdist;\n            double pval  = 1.0 - boost::math::gamma_p(0.5, tdist * tdist * 0.5);\n\n            Beta[mrki]  = beta;\n            Tdist[mrki] = tdist;\n            Se[mrki]    = se;\n            Pval[mrki]  = pval;\n\n            //if (mrki < 5) {\n            //    printf(\"r: %3d  m: %8d %8d (%5s) %8d  beta=%20.15f  se=%20.15f  tdist=%20.15f pval=%20.15f   xtx=%10.1f xty=%15.6f\\n\", rank, mrki, mglo, id.c_str(), rmglo, beta, se, tdist, pval, xtx, xty);\n            //}\n        }\n\n        fflush(stdout);\n        double t_3 = MPI_Wtime();\n        MPI_Barrier(MPI_COMM_WORLD);\n        //if (rank >= 0)\n        //    printf(\"INFO   : intermediate time 3 = %.2f seconds.\\n\", t_3 - t_2);\n\n        const int LLEN = 123 + 1;\n        char* todump  = (char*) _mm_malloc(size_t(LLEN) * size_t(M) * sizeof(char), 32);\n        check_malloc(todump, __LINE__, __FILE__);\n\n        int n_rem = 0;\n        for (int mrki=0; mrki<M; mrki++) {\n            int mglo = S + mrki;\n            std::string id = rsid.at(mglo);\n            if (m_refrsid.find(id) == m_refrsid.end()) {\n                //|| id.compare(\"rs12562034\") == 0m|| id.compare(\"rs188466450\") == 0)\n                printf(\"WARNING: marker id %s excluded -- no match\\n\", id.c_str());\n                n_rem++;\n                continue;\n            }\n            int rmglo = m_refrsid.find(id)->second;\n            int cx = snprintf(&todump[(mrki - n_rem) * (LLEN - 1)], LLEN, \"%20s %8d %8d %20.15f %20.15f %20.15f %20.15f\\n\",\n                              id.c_str(), mglo, rmglo, Beta[mrki], Tdist[mrki], Se[mrki], Pval[mrki]);\n            assert(cx >= 0 && cx < LLEN);\n        }\n\n        // Collect numbers of markers to print in each task\n        int mp = M - n_rem;\n        int* mps = (int*) malloc(nranks * sizeof(int));\n        check_mpi(MPI_Allgather(&mp, 1, MPI_INTEGER, mps, 1, MPI_INTEGER, MPI_COMM_WORLD), __LINE__, __FILE__);\n\n        int ps = 0;\n        for (int i=0; i<rank; i++) { ps += mps[i]; }\n\n        MPI_Offset offset = size_t(ps) * size_t(LLEN-1);\n        check_mpi(MPI_File_write_at(*mlma_fh,\n                                    offset, todump, size_t(LLEN-1) * size_t(mp), MPI_CHAR, &status),\n                  __LINE__, __FILE__);\n\n        _mm_free(todump);\n\n        fflush(stdout);\n        double t_4 = MPI_Wtime();\n        MPI_Barrier(MPI_COMM_WORLD);\n        //if (rank >= 0)\n        //    printf(\"INFO   : intermediate time 4 = %.2f seconds.\\n\", t_4 - t_3);\n\n        MPI_Barrier(MPI_COMM_WORLD);\n\n        phen.close_prediction_files();\n\n        _mm_free(Beta);\n        _mm_free(Tdist);\n        _mm_free(Se);\n        _mm_free(Pval);\n        _mm_free(beta_sum);\n        _mm_free(beta_it);\n        _mm_free(g_k);\n        _mm_free(g);\n        _mm_free(y_k);\n    }\n\n    fflush(stdout);\n    double te = MPI_Wtime();\n    MPI_Barrier(MPI_COMM_WORLD);\n    if (rank == 0)\n        printf(\"INFO   : Time to compute the predictions: %.2f seconds.\\n\", te - ts);\n}\n\n// EO: bim_file - I assume that the row number is the index\n//\nvoid Bayes::cross_bim_files() {\n\n    if (rank == 0) {\n        printf(\"INFO   : bim file:     %s\\n\", opt.get_bim_file().c_str());\n        printf(\"INFO   : ref bim file: %s\\n\", opt.get_ref_bim_file().c_str());\n    }\n    std::ifstream in(opt.get_bim_file().c_str());\n    if (!in) throw (\"Error: can not open the file [\" + opt.get_bim_file() + \"] to read.\");\n    std::string   id, allele1, allele2;\n    unsigned chr, physPos, idx = 0;\n    float    genPos;\n    while (in >> chr >> id >> genPos >> physPos >> allele1 >> allele2) {\n        rsid.push_back(id);\n    }\n    in.close();\n    int nrsid = rsid.size();\n    if (rank == 0)\n        printf(\"INFO   : found %d ids in bim file\\n\", nrsid);\n\n    std::ifstream refin(opt.get_ref_bim_file().c_str());\n    if (!refin) throw (\"Error: can not open the file [\" + opt.get_ref_bim_file() + \"] to read.\");\n    idx = 0;\n    while (refin >> chr >> id >> genPos >> physPos >> allele1 >> allele2) {\n        m_refrsid[id] = idx++;\n    }\n    refin.close();\n    if (rank == 0)\n        printf(\"INFO   : found %d ids in reference bim file\\n\", idx);\n}\n\nvoid Bayes::process() {\n\n    check_openmp();\n\n    for (auto& phen : pmgr.get_phens()) {\n        phen.delete_output_files();\n        phen.open_output_files();\n        phen.set_midx();\n        for (int i=0; i<opt.get_ngroups(); i++) {\n            phen.set_sigmag_for_group(i, phen.sample_beta_rng(1.0, 1.0));\n            if (mtotgrp.at(i) == 0)\n                phen.set_sigmag_for_group(i, 0.0);\n            //printf(\"sample sigmag[%d] = %20.15f\\n\", i, phen.get_sigmag_for_group(i));\n        }\n        check_mpi(MPI_Bcast(phen.get_sigmag()->data(), phen.get_sigmag()->size(), MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n        phen.set_pi_est(pi_prior);\n        //printf(\"sample sigmag[0] = %20.15f\\n\", phen.get_sigmag()->at(0));\n    }\n\n    const int NPHEN =  pmgr.get_phens().size();\n    bool recv_update[nranks];\n\n    for (unsigned int it = 1; it <= opt.get_iterations(); it++) {\n\n        double ts_it = MPI_Wtime();\n\n        if (rank == 0)\n            printf(\"\\n\\n@@@ ITERATION %5d\\n\", it);\n\n        int pidx = 0;\n        for (auto& phen : pmgr.get_phens()) {\n            pidx += 1;\n            //printf(\"phen %d has mu = %20.15f\\n\", pidx, phen.get_mu());\n            phen.offset_epsilon(phen.get_mu());\n            //phen.update_epsilon_sum();\n            if (it == 1) {\n                phen.update_epsilon_sigma();\n                //printf(\"epssum = %20.15f, sigmae = %20.15f\\n\", phen.get_epsilon_sum(), phen.get_sigmae());\n            }\n            phen.set_mu(phen.sample_norm_rng());\n            //printf(\"new mu = %20.15f\\n\", phen.get_mu());\n            phen.offset_epsilon(-phen.get_mu());\n            //**BUG in original phen.epsilon_stats();\n\n            // Shuffling of the markers on its own PRNG (see README/wiki)\n            if (opt.shuffle_markers())\n                phen.shuffle_midx(opt.mimic_hydra());\n\n            phen.reset_m0();\n            phen.reset_cass();\n        }\n        fflush(stdout);\n\n        double dbetas[NPHEN * 3]; // [ dbeta:mave:msig | ... | ]\n\n        double t_it_sync = 0.0;\n\n        for (int mrki=0; mrki<Mm; mrki++) {\n\n            bool share_mrk = false;\n            for (int i=0; i<NPHEN*3; i++)\n                dbetas[i] = 0.0;\n            int mloc = 0;\n\n            if (mrki < M) {\n\n                mloc = pmgr.get_phens()[0].get_marker_local_index(mrki);\n                const int mglo = S + mloc;\n                const int mgrp = get_marker_group(mglo);\n                //std::cout << \"mloc = \" << mloc << \", mglo = \" << mglo << \", mgrp = \" << mgrp << std::endl;\n\n                int pheni = -1;\n\n                for (auto& phen : pmgr.get_phens()) {\n\n                    pheni += 1;\n\n                    // Adav\n                    if (phen.get_sigmag_for_group(mgrp) == 0.0) {\n                        phen.set_marker_acum(mloc, 1.0);\n                        phen.set_marker_beta(mloc, 0.0);\n                        continue;\n                    }\n\n                    double beta   = phen.get_marker_beta(mloc);\n                    double sige_g = phen.get_sigmae() / phen.get_sigmag_for_group(get_marker_group(mglo));\n                    double sigg_e = 1.0 / sige_g;\n                    double inv2sige = 1.0 / (2.0 * phen.get_sigmae());\n                    //if (mrki < 3)\n                    //    printf(\"mrk = %3d has beta = %20.15f; sige_g = %20.15f = %20.15f / %20.15f\\n\", mloc, phen.get_marker_beta(mloc), sige_g, phen.get_sigmae(), phen.get_sigmag());\n\n                    std::vector<double> denom = phen.get_denom();\n                    std::vector<double> muk   = phen.get_muk();\n                    std::vector<double> logl  = phen.get_logl();\n\n                    for (int i=1; i<=K-1; ++i) {\n                        denom.at(i-1) = (double)(N - 1) + sige_g * cvai[mgrp][i];\n                        //printf(\"it %d, rank %d, m %d: denom[%d] = %20.15f, cvai = %20.15f\\n\", it, rank, mloc, i-1, denom.at(i-1), cvai[mgrp][i]);\n                    }\n\n                    double num = dot_product(mloc, phen.get_epsilon(), phen.get_marker_ave(mloc), phen.get_marker_sig(mloc));\n\n                    //printf(\"num = %20.15f\\n\", num);\n                    num += beta * double(phen.get_nonas() - 1);\n\n                    //printf(\"i:%d r:%d m:%d: num = %.17g, %20.15f, %20.15f\\n\", it, rank, mloc, num, phen.get_marker_ave(mloc), phen.get_marker_sig(mloc));\n\n                    for (int i=1; i<=K-1; ++i)\n                        muk.at(i) = num / denom.at(i - 1);\n\n                    for (int i=0; i<K; i++) {\n                        logl[i] = log(phen.get_pi_est(mgrp, i));\n                        if (i>0)\n                            logl[i] += -0.5 * log(sigg_e * double(phen.get_nonas() - 1) * cva[mgrp][i] + 1.0) + muk[i] * num * inv2sige;\n                        //printf(\"logl[%d] = %20.15f\\n\", i, logl[i]);\n                    }\n\n                    double prob = phen.sample_unif_rng();\n\n                    bool zero_acum = false;\n                    double tmp1 = 0.0;\n                    for (int i=0; i<K; i++) {\n                        if (abs(logl[i] - logl[0]) > 700.0)\n                            zero_acum = true;\n                        tmp1 += exp(logl[i] - logl[0]);\n                    }\n                    zero_acum ? tmp1 = 0.0 : tmp1 = 1.0 / tmp1;\n                    phen.set_marker_acum(mloc, tmp1);\n                    //printf(\"i:%d r:%d m:%d p:%d  num = %20.15f, acum = %20.15f, prob = %20.15f\\n\", it, rank, mloc, pheni, num, phen.get_marker_acum(mloc), prob);\n\n                    double dbeta = phen.get_marker_beta(mloc);\n\n                    for (int i=0; i<K; i++) {\n                        if (prob <= phen.get_marker_acum(mloc) || i == K - 1) {\n                            if (i == 0) {\n                                phen.set_marker_beta(mloc, 0.0);\n                                //printf(\"@0@ i:%4d r:%4d m:%4d: beta reset to 0.0\\n\", it, rank, mloc);\n                            } else {\n                                phen.set_marker_beta(mloc, phen.sample_norm_rng(muk[i], phen.get_sigmae() / denom[i-1]));\n                                //printf(\"@B@ i:%4d r:%4d m:%4d:  dbetat = %20.15f, muk[%4d] = %15.10f with prob=%15.10f <= acum = %15.10f, denom = %15.10f, sigmaE = %15.10f: beta = %15.10f\\n\", it, rank, mloc, phen.get_marker_beta(mloc) - dbeta, i, muk[i], prob, phen.get_marker_acum(mloc), denom[i-1], phen.get_sigmae(), phen.get_marker_beta(mloc));\n                                //fflush(stdout);\n                            }\n                            phen.increment_cass(mgrp, i, 1);\n                            //std::cout << \"cass \" << mgrp << \" \" << i << \" = \" << phen.get_cass_for_group(mgrp,i) << std::endl;\n                            phen.set_comp(mloc, i);\n                            break;\n                        } else {\n                            bool zero_inc = false;\n                            for (int j=i+1; j<K; j++) {\n                                if (abs(logl[j] - logl[i+1]) > 700.0)\n                                    zero_inc = true;\n                            }\n                            if (!zero_inc) {\n                                double esum = 0.0;\n                                for (int k=0; k<logl.size(); k++)\n                                    esum += exp(logl[k] - logl[i+1]);\n                                phen.set_marker_acum(mloc, phen.get_marker_acum(mloc) + 1.0 / esum);\n                            }\n                        }\n                    }\n\n                    dbeta -= phen.get_marker_beta(mloc);\n\n                    //printf(\"iteration %3d, rank %3d, marker %5d: dbeta = %20.15f, pheni = %d, %20.15f %20.15f\\n\", it, rank, mloc, dbeta, pheni, dbetas[pheni + 1], dbetas[pheni + 2]);\n\n                    if (abs(dbeta) > 0.0) {\n                        share_mrk = true;\n                        dbetas[pheni * 3 + 0] = dbeta;\n                        dbetas[pheni * 3 + 1] = phen.get_marker_ave(mloc);\n                        dbetas[pheni * 3 + 2] = phen.get_marker_sig(mloc);\n                        //printf(\"@\u00a2@ i:%3d r:%3d m:%5d: dbeta = %20.15f, pheni = %d, %20.15f %20.15f\\n\", it, rank, mloc, dbeta, pheni, dbetas[pheni * 3 + 1], dbetas[pheni * 3 + 2]);\n                    } else {\n                        //printf(\"-\u00a2- i:%3d r:%3d m:%5d: dbeta = %20.15f, pheni = %d, %20.15f %20.15f\\n\", it, rank, mloc, dbeta, pheni, dbetas[pheni * 3 + 1], dbetas[pheni * 3 + 2]);\n                    }\n                }\n            }\n\n            MPI_Barrier(MPI_COMM_WORLD);\n            double ts_sync = MPI_Wtime();\n\n            // Collect information on which tasks need to share its just processed marker;\n            // Tasks with M < Mm, share_mrk is false by default.\n            MPI_Allgather(&share_mrk,  1, MPI_C_BOOL,\n                          recv_update, 1, MPI_C_BOOL,\n                          MPI_COMM_WORLD);\n\n            /*\n            if (rank == 0) {\n                printf(\"rank:share mrk %d?: \", mrki);\n                for (int i=0; i<nranks; i++) {\n                    printf(\"%d:%d \", i, recv_update[i] == true ? 1:0);\n                }\n                printf(\"\\n\");\n            }\n            fflush(stdout);\n            */\n\n            int totbytes = 0;\n\n            int dis_bet[nranks], cnt_bet[nranks];\n            int dis_bed[nranks], cnt_bed[nranks];\n            int disp_bet = 0, disp_bed = 0;\n            for (int i=0; i<nranks; i++) {\n                if (recv_update[i]) {\n                    cnt_bet[i] = NPHEN * 3;\n                    cnt_bed[i] = mbytes;\n                    totbytes += mbytes;\n                } else {\n                    cnt_bet[i] = 0;\n                    cnt_bed[i] = 0;\n                }\n                dis_bet[i] = disp_bet;\n                dis_bed[i] = disp_bed;\n                //printf(\"mrki = %d, recv_update[%d] = %s %d:%d\\n\", mrki, i, recv_update[i] ? \"T\" : \"F\", dis_bet[i], cnt_bet[i]);\n                disp_bet += cnt_bet[i];\n                disp_bed += cnt_bed[i];\n            }\n\n            //printf(\"rank %d bytes vs %d\\n\", totbytes, disp_bed);\n\n            double recv_dbetas[disp_bet];\n            MPI_Allgatherv(&dbetas, share_mrk ? NPHEN * 3 : 0, MPI_DOUBLE,\n                           recv_dbetas, cnt_bet, dis_bet, MPI_DOUBLE, MPI_COMM_WORLD);\n\n            unsigned char* recv_bed = (unsigned char*) _mm_malloc(disp_bed, 32);\n            check_malloc(recv_bed, __LINE__, __FILE__);\n            MPI_Allgatherv(&bed_data[mloc * mbytes], share_mrk ? mbytes : 0, MPI_UNSIGNED_CHAR,\n                           recv_bed, cnt_bed, dis_bed, MPI_UNSIGNED_CHAR, MPI_COMM_WORLD);\n\n            update_epsilon(cnt_bet, recv_dbetas, recv_bed);\n\n            MPI_Barrier(MPI_COMM_WORLD);\n            double te_sync = MPI_Wtime();\n            t_it_sync += te_sync - ts_sync;\n\n            _mm_free(recv_bed);\n\n        } // End marker loop\n\n        //exit(0);\n        //continue;\n\n        //MPI_Barrier(MPI_COMM_WORLD);\n\n        int pheni = -1;\n        for (auto& phen : pmgr.get_phens()) {\n            pheni++;\n\n            phen.reset_beta_sqn_to_zero();\n            for (int i=0; i<M; i++) {\n                phen.increment_beta_sqn(get_marker_group(S + i), phen.get_marker_beta(i) * phen.get_marker_beta(i));\n            }\n\n            //for (int i=0; i<G; i++)\n            //    printf(\"i:%d r:%d p:%d g:%d: beta_sqn[%d] = %20.15f\\n\", it, rank, pheni, i, i, phen.get_beta_sqn_for_group(i));\n\n            double* beta_sqn_sum = (double*) malloc(G * sizeof(double));\n            check_mpi(MPI_Allreduce(phen.get_beta_sqn()->data(),\n                                    beta_sqn_sum,\n                                    G,\n                                    MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD), __LINE__, __FILE__);\n            phen.set_beta_sqn(beta_sqn_sum);\n            free(beta_sqn_sum);\n\n            int* cass_sum = (int*) malloc(G * K * sizeof(int));\n            check_mpi(MPI_Allreduce(phen.get_cass(),\n                                    cass_sum,\n                                    G * K,\n                                    MPI_INT,\n                                    MPI_SUM,\n                                    MPI_COMM_WORLD), __LINE__, __FILE__);\n            phen.set_cass(cass_sum);\n            free(cass_sum);\n\n            // Update global parameters\n            //\n            for (int i=0; i<G; i++) {\n\n                // Skip empty groups\n                if (mtotgrp.at(i) == 0)\n                    continue;\n\n                //printf(\" !!! i:%d r:%d p:%d g:%d:  OLD sigmag = %20.15f\\n\", it, rank, pheni, i, phen.get_sigmag_for_group(i));\n\n                //if (rank == 0)\n                //    printf(\"i:%d r:%d p:%d g:%d:  m0 = %d - %d = %d\\n\", it, rank, pheni, i, mtotgrp.at(i), phen.get_cass_for_group(i, 0), mtotgrp.at(i) - phen.get_cass_for_group(i, 0));\n\n                phen.set_m0_for_group(i, mtotgrp.at(i) - phen.get_cass_for_group(i, 0));\n\n                // Skip groups with m0 being null or empty cass (adaV in action)\n                if (phen.get_m0_for_group(i) == 0 || phen.get_cass_sum_for_group(i) == 0) {\n                    phen.set_sigmag_for_group(i, 0.0);\n                    continue;\n                }\n\n                phen.set_sigmag_for_group(i, phen.sample_inv_scaled_chisq_rng(V0G + (double) phen.get_m0_for_group(i), (phen.get_beta_sqn_for_group(i) * (double) phen.get_m0_for_group(i) + V0G * S02G) / (V0G + (double) phen.get_m0_for_group(i))));\n                //printf(\" !!! i:%d r:%d p:%d g:%d:  NEW sigmag = %20.15f %20.15f\\n\", it, rank, pheni, i, phen.get_sigmag_for_group(i), phen.get_beta_sqn_for_group(i));\n\n                phen.update_pi_est_dirichlet(i);\n            }\n\n            //continue;\n\n            //if (rank == 0)\n            //    phen.print_cass(mtotgrp);\n\n\n            // Broadcast sigmaG of rank 0\n            check_mpi(MPI_Bcast(phen.get_sigmag()->data(), phen.get_sigmag()->size(), MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n            for (int i=0; i<opt.get_ngroups(); i++) {\n                //printf(\"i:%d r:%d p:%d g:%d:  sigmag = %20.15f\\n\", it, rank, pheni, i, phen.get_sigmag_for_group(i));\n            }\n\n            double e_sqn = phen.epsilon_sumsqr();\n            //printf(\"i:%d r:%d p:%d  e_sqn = %20.15f\\n\", it, rank, pheni, e_sqn);\n\n            //EO: sample sigmaE and broadcast the one from rank 0 to all the others\n            phen.set_sigmae(phen.sample_inv_scaled_chisq_rng(V0E + (double)N, (e_sqn + V0E * S02E) / (V0E + (double)N)));\n\n            double sigmae_r0 = phen.get_sigmae();\n            check_mpi(MPI_Bcast(&sigmae_r0, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n            phen.set_sigmae(sigmae_r0);\n            if (rank % 10 == 0) {\n                printf(\"RESULT : i:%d r:%d p:%d  sum sigmaG = %20.15f  sigmaE = %20.15f\\n\", it, rank, pheni, phen.get_sigmag_sum(), phen.get_sigmae());\n                //for (int i=0; i<opt.get_ngroups(); i++) {\n                //    printf(\"i:%d r:%d p:%d  sigmaG = %20.15f  sigmaE = %20.15f\\n\", it, rank, pheni, phen.get_sigmag_for_group(i), phen.get_sigmae());\n                //}\n            }\n\n            // Broadcast pi_est from rank 0\n            for (int i=0; i<G; i++) {\n                check_mpi(MPI_Bcast(phen.get_pi_est()->at(i).data(), phen.get_pi_est()->at(i).size(), MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n            }\n        }\n\n        double te_it = MPI_Wtime();\n        if (rank == 0)\n            printf(\"RESULT : It %d  total proc time = %7.3f sec, with sync time = %7.3f\\n\", it, te_it - ts_it, t_it_sync);\n\n\n        // Write output files\n        if (it % opt.get_output_thin_rate() == 0) {\n            const unsigned nthinned = it / opt.get_output_thin_rate() - 1;\n            for (auto& phen : pmgr.get_phens()) {\n                if (rank == 0) {\n                    //phen.print_pi_est();\n                    write_ofile_csv(*(phen.get_outcsv_fh()), it,  phen.get_sigmag(), phen.get_sigmae(), phen.get_m0_sum(), nthinned, phen.get_pi_est());\n                }\n                write_ofile_h1(*(phen.get_outbet_fh()), rank, Mt, it, nthinned, S, M, phen.get_betas().data(), MPI_DOUBLE);\n                write_ofile_h1(*(phen.get_outcpn_fh()), rank, Mt, it, nthinned, S, M, phen.get_comp().data(),  MPI_INTEGER);\n            }\n        }\n\n    } // End iteration loop\n\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    for (auto& phen : pmgr.get_phens())\n        phen.close_output_files();\n}\n\n// counts[rank]: holds either NPHEN * 3 or 0\n\nvoid Bayes::update_epsilon(const int* counts, const double* dbetas, const unsigned char* bed) {\n\n    const int NPHEN =  pmgr.get_phens().size();\n\n    int cnt_tot = 0;\n    int bedi = 0;\n    for (int i=0; i<nranks; i++) {\n        int cnt = counts[i];\n        //printf(\"r:%d  cnt = %d\\n\", i, cnt);\n        if (cnt == 0) continue;\n        assert(cnt == NPHEN * 3);\n        //printf(\" cnt > 0: task %d, get for rank %d cnt = %d dbetas:\\n\", rank, i, cnt);\n        int pheni = 0;\n        for (auto& phen : pmgr.get_phens()) {\n            //printf(\"r:%d p:%d - dbeta = %20.15f\\n\", rank, pheni, dbetas[cnt_tot + pheni * 3]);\n            if (dbetas[cnt_tot + pheni * 3] != 0.0)\n                phen.update_epsilon(&dbetas[cnt_tot + pheni * 3], &bed[bedi * mbytes]);\n            //phen.update_epsilon_sum();\n            //printf(\" - r:%d p:%d   epssum = %.17g, cnt_tot = %d\\n\", i, pheni, phen.get_epsilon_sum(), cnt_tot);\n            pheni += 1;\n        }\n        cnt_tot += cnt;\n        bedi    += 1;\n    }\n    fflush(stdout);\n}\n\n// EO, review!!\ndouble Bayes::dot_product(const int mloc, double* __restrict__ phen, const double mu, const double sigma_inv) {\n\n    unsigned char* bed = &bed_data[mloc * mbytes];\n\n#ifdef MANVEC\n    __m256d luta, lutb; //, lutna;\n    __m512d lutab, p42;\n    __m256d p4   = _mm256_set1_pd(0.0);\n    __m256d suma = _mm256_set1_pd(0.0);\n    __m256d sumb = _mm256_set1_pd(0.0);\n    __m512d sum42 = _mm512_set1_pd(0.0);\n\n#ifdef _OPENMP\n    //#pragma omp parallel for schedule(static) reduction(addpd4:suma,sumb)\n#pragma omp parallel for schedule(static) reduction(addpd8:sum42)\n#endif\n    for (int j=0; j<mbytes; j++) {\n        //luta  = _mm256_load_pd(&dotp_lut_a[bed[j] * 4]);\n        //lutb  = _mm256_load_pd(&dotp_lut_b[bed[j] * 4]);\n        //luta  = _mm256_load_pd(&dotp_lut_ab[bed[j] * 8]);\n        //lutb  = _mm256_load_pd(&dotp_lut_ab[bed[j] * 8 + 4]);\n        lutab = _mm512_load_pd(&dotp_lut_ab[bed[j] * 8]);\n        //p4    = _mm256_load_pd(&phen[j * 4]);\n        p42 = _mm512_broadcast_f64x4(_mm256_load_pd(&phen[j * 4]));\n        ////lutna = _mm256_load_pd(&na_lut[mask4[j] * 4]); // phen = 0.0 on NAs!\n        //luta  = _mm256_mul_pd(luta, p4);\n        //lutb  = _mm256_mul_pd(lutb, p4);\n        p42 = _mm512_mul_pd(p42, lutab);\n        //suma  = _mm256_add_pd(suma, luta);\n        //sumb  = _mm256_add_pd(sumb, lutb);\n        sum42 = _mm512_add_pd(sum42, p42);\n    }\n\n    //return sigma_inv *\n    //    (suma[0] + suma[1] + suma[2] + suma[3] - mu * (sumb[0] + sumb[1] + sumb[2] + sumb[3]));\n    return sigma_inv *\n        (sum42[0] + sum42[1] + sum42[2] + sum42[3] - mu * (sum42[4] + sum42[5] + sum42[6] + sum42[7]));\n\n#else\n\n    double dpa = 0.0;\n    double dpb = 0.0;\n\n#ifdef _OPENMP\n    //#pragma omp parallel for schedule(static) reduction(addpd4:suma,sumb)\n#pragma omp parallel for schedule(static) reduction(+:dpa,dpb)\n#endif\n    for (int i=0; i<mbytes; i++) {\n#ifdef _OPENMP\n#pragma omp simd aligned(dotp_lut_a,dotp_lut_b,phen:32)\n#endif\n        for (int j=0; j<4; j++) {\n            dpa += dotp_lut_a[bed[i] * 4 + j] * phen[i * 4 + j];\n            dpb += dotp_lut_b[bed[i] * 4 + j] * phen[i * 4 + j];\n        }\n    }\n\n    return sigma_inv * (dpa - mu * dpb);\n\n#endif\n\n}\n\n\n// Setup processing: load input files and define MPI task workload\nvoid Bayes::setup_processing() {\n\n    mbytes = (N %  4) ? (size_t) N /  4 + 1 : (size_t) N /  4;\n    load_genotype();\n\n    pmgr.read_phen_files(opt, get_N(), get_M());\n\n    check_processing_setup();\n\n    if (rank == 0)\n        printf(\"INFO   : output directory: %s\\n\", opt.get_out_dir().c_str());\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    double ts = MPI_Wtime();\n    pmgr.compute_markers_statistics(bed_data, get_N(), get_M(), mbytes);\n    MPI_Barrier(MPI_COMM_WORLD);\n    double te = MPI_Wtime();\n    if (rank == 0)\n        printf(\"INFO   : Time to compute the markers' statistics: %.2f seconds.\\n\", te - ts);\n\n    if (opt.predict()) return;\n\n    for (auto& phen : pmgr.get_phens()) {\n        phen.set_prng_m((unsigned int)(opt.get_seed() + (rank + 0)));\n        if (opt.mimic_hydra()) {\n            phen.set_prng_d((unsigned int)(opt.get_seed() + (rank + 0) * 1000));\n        } else {\n            phen.set_prng_d((unsigned int)(opt.get_seed() + (rank + 1) * 1000));\n        }\n    }\n\n    read_group_index_file(opt.get_group_index_file());\n\n    for (int i=0; i<Mt; i++) {\n        mtotgrp.at(get_marker_group(i)) += 1;\n    }\n    //for (int i=0; i<G; i++)\n    //    printf(\"mtotgrp at %d = %d\\n\", i, mtotgrp.at(i));\n}\n\n\nvoid Bayes::check_openmp() {\n#ifdef _OPENMP\n#pragma omp parallel\n    {\n        if (rank == 0) {\n            int nt = omp_get_num_threads();\n            if (omp_get_thread_num() == 0)\n                printf(\"INFO   : OMP parallel regions will use %d thread(s)\\n\", nt);\n        }\n    }\n#else\n    printf(\"WARNING: no OpenMP support!\\n\");\n#endif\n}\n\nvoid Bayes::read_group_index_file(const std::string& file) {\n\n    std::ifstream infile(file.c_str());\n    if (! infile)\n        throw (\"Error: can not open the group file [\" + file + \"] to read. Use the --group-index-file option!\");\n\n    if (rank == 0)\n        std::cout << \"INFO   : Reading groups from \" + file + \".\" << std::endl;\n\n    std::string label;\n    int group;\n\n    group_index.clear();\n\n    while (infile >> label >> group) {\n        //std::cout << label << \" - \" << group << std::endl;\n        if (group > G) {\n            printf(\"FATAL  : group index file contains a value that exceeds the number of groups given in group mixture file.\\n\");\n            printf(\"       : check the consistency between your group index and mixture input files.\\n\");\n            exit(1);\n        }\n        group_index.push_back(group);\n    }\n}\n\n\nvoid Bayes::check_processing_setup() {\n    for (const auto& phen : pmgr.get_phens()) {\n        const int Np = phen.get_nas() + phen.get_nonas();\n        if (Np != N) {\n            std::cout << \"Fatal: N = \" << N << \" while phen file \" << phen.get_filepath() << \" has \" << Np << \" individuals!\" << std::endl;\n            exit(1);\n        }\n    }\n}\n\n\nvoid Bayes::load_genotype() {\n\n    double ts = MPI_Wtime();\n\n    MPI_File bedfh;\n    const std::string bedfp = opt.get_bed_file();\n    check_mpi(MPI_File_open(MPI_COMM_WORLD, bedfp.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &bedfh),  __LINE__, __FILE__);\n\n    const size_t size_bytes = size_t(M) * size_t(mbytes) * sizeof(unsigned char);\n\n    bed_data = (unsigned char*)_mm_malloc(size_bytes, 64);\n    check_malloc(bed_data, __LINE__, __FILE__);\n    printf(\"INFO   : rank %4d has allocated %zu bytes (%.3f GB) for raw data.\\n\", rank, size_bytes, double(size_bytes) / 1.0E9);\n\n    // Offset to section of bed file to be processed by task\n    MPI_Offset offset = size_t(3) + size_t(S) * size_t(mbytes) * sizeof(unsigned char);\n\n    // Gather the sizes to determine common number of reads\n    size_t max_size_bytes = 0;\n    check_mpi(MPI_Allreduce(&size_bytes, &max_size_bytes, 1, MPI_UNSIGNED_LONG_LONG, MPI_MAX, MPI_COMM_WORLD), __LINE__, __FILE__);\n\n    const int NREADS = check_int_overflow(size_t(ceil(double(max_size_bytes)/double(INT_MAX/2))), __LINE__, __FILE__);\n    size_t bytes = 0;\n    mpi_file_read_at_all <unsigned char*> (size_bytes, offset, bedfh, MPI_UNSIGNED_CHAR, NREADS, bed_data, bytes);\n    //@@@MPI_Barrier(MPI_COMM_WORLD);\n\n    check_mpi(MPI_File_close(&bedfh), __LINE__, __FILE__);\n\n    double te = MPI_Wtime();\n    MPI_Barrier(MPI_COMM_WORLD);\n    if (rank >= 0)\n        printf(\"INFO   : time to load genotype data = %.2f seconds.\\n\", te - ts);\n\n}\n\n\nvoid Bayes::set_block_of_markers() {\n\n    const int modu = Mt % nranks;\n    const int size = Mt / nranks;\n\n    Mm = Mt % nranks != 0 ? size + 1 : size;\n\n    int len[nranks], start[nranks];\n    int cum = 0;\n    for (int i=0; i<nranks; i++) {\n        len[i]  = i < modu ? size + 1 : size;\n        start[i] = cum;\n        cum += len[i];\n    }\n    //printf(\"cum %d vs %d  Mm = %d\\n\", cum, Mt, Mm);\n    assert(cum == Mt);\n\n    M = len[rank];\n    S = start[rank];\n\n    printf(\"INFO   : rank %4d has %d markers over tot Mt = %d, max Mm = %d, starting at S = %d\\n\", rank, M, Mt, Mm, S);\n    //@todo: mpi check sum over tasks == Mt\n}\n\nvoid Bayes::print_cva() {\n    printf(\"INFO   : mixtures for all groups:\\n\");\n    for (int i=0; i<G; i++) {\n        printf(\"         grp %2d: \", i);\n        for (int j=0; j<K; j++) {\n            printf(\"%7.5f \", cva[i][j]);\n        }\n        printf(\"\\n\");\n    }\n}\n\nvoid Bayes::print_cvai() {\n    printf(\"INFO   : inverse mixtures for all groups:\\n\");\n    for (int i=0; i<G; i++) {\n        printf(\"         grp %2d: \", i);\n        for (int j=0; j<K; j++) {\n            printf(\"%10.3f \", cvai[i][j]);\n        }\n        printf(\"\\n\");\n    }\n}\n", "meta": {"hexsha": "a3f039fb8705a783f53e7e4f369465ba971538b3", "size": 36363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bayes.cpp", "max_stars_repo_name": "medical-genomics-group/gmrm", "max_stars_repo_head_hexsha": "4bd759c8b80de90c2510de0ed13fd2aa250f6ff3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T12:30:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T15:01:38.000Z", "max_issues_repo_path": "src/bayes.cpp", "max_issues_repo_name": "medical-genomics-group/gmrm", "max_issues_repo_head_hexsha": "4bd759c8b80de90c2510de0ed13fd2aa250f6ff3", "max_issues_repo_licenses": ["MIT"], "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/bayes.cpp", "max_forks_repo_name": "medical-genomics-group/gmrm", "max_forks_repo_head_hexsha": "4bd759c8b80de90c2510de0ed13fd2aa250f6ff3", "max_forks_repo_licenses": ["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.3575949367, "max_line_length": 350, "alphanum_fraction": 0.5140114952, "num_tokens": 10591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.1947359041169451}}
{"text": "/**\n * 3D NDT-UKF Node. \n */\n\n#include <ros/ros.h>\n#include <angles/angles.h>\n#include <tf/transform_listener.h>\n#include <boost/foreach.hpp>\n#include <sensor_msgs/LaserScan.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <nav_msgs/Odometry.h>\n#include <nav_msgs/OccupancyGrid.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <tf/transform_broadcaster.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <geometry_msgs/Pose.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/filters/voxel_grid.h>\n#include <velodyne_pointcloud/rawdata.h>\n#include <velodyne_pointcloud/point_types.h>\n#include <pcl_ros/impl/transforms.hpp>\n\n#include \"tf/message_filter.h\"\n#include <tf/transform_broadcaster.h>\n#include <tf_conversions/tf_eigen.h>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/PoseStamped.h>\n\n#include <sensor_msgs/PointCloud2.h>\n\n#include <ndt_generic/utils.h>\n#include <ndt_generic/eigen_utils.h>\n#include <ndt_mcl/3d_ndt_ukf.h>\n#include <ndt_map/ndt_map.h>\n\n#include <ndt_rviz/ndt_rviz.h>\n#include <ndt_generic/pcl_utils.h>\n\n\ninline void normalizeEulerAngles(Eigen::Vector3d &euler) {\n    if (fabs(euler[0]) > M_PI/2) {\n        euler[0] += M_PI;\n        euler[1] += M_PI;\n        euler[2] += M_PI;\n    \n        euler[0] = angles::normalize_angle(euler[0]);\n        euler[1] = angles::normalize_angle(euler[1]);\n        euler[2] = angles::normalize_angle(euler[2]);\n    }\n}\n\nstd::string affine3dToString(const Eigen::Affine3d &T) {\n    std::ostringstream stream;\n    stream << std::setprecision(std::numeric_limits<double>::digits10);\n    Eigen::Vector3d rot = T.rotation().eulerAngles(0,1,2);\n    normalizeEulerAngles(rot);\n  \n    stream << T.translation().transpose() << \" \" << rot.transpose();\n    return stream.str();\n}\n\nclass NDTUKF3DNode {\n\nprivate:\n    ros::NodeHandle nh_;\n    NDTUKF3D *ndtukf;\n    boost::mutex ukf_m,message_m;\n\n    message_filters::Subscriber<sensor_msgs::PointCloud2> *points2_sub_;\n    message_filters::Subscriber<nav_msgs::Odometry> *odom_sub_;\n    ros::Subscriber scan_sub_;\n    ros::Subscriber scan2_sub_;\n    ros::Subscriber gt_sub;\n\n    ///Laser sensor offset\n    Eigen::Affine3d sensorPoseT; //<<Sensor offset with respect to odometry frame\n    ros::Duration sensorTimeOffset_;\n    Eigen::Affine3d sensorPoseT2; //<<Sensor offset with respect to odometry frame\n    ros::Duration sensorTimeOffset2_;\n    Eigen::Affine3d Told,Todo,Todo_old,Tcum; //<<old and current odometry transformations\n    Eigen::Affine3d initPoseT; //<<Sensor offset with respect to odometry frame\n\n    pcl::PointCloud<pcl::PointXYZ> scan2_cloud_;\n    ros::Time scan2_t0_;\n            \n\n    bool use_dual_scan;\n    bool hasSensorPose, hasInitialPose;\n    bool isFirstLoad;\n    bool forceSIR, do_visualize;\n    bool saveMap;\t\t\t\t\t\t///< indicates if we want to save the map in a regular intervals\n    std::string mapName; ///<name and the path to the map\n    std::string output_map_name;\n    double resolution;\n    double subsample_level;\n    int pcounter;\n\n    ros::Publisher ukf_pub; ///< The output of UKF is published with this!\n    ros::Publisher marker_pub_;\n    ros::Publisher markerarray_pub_;\n    ros::Publisher pointcloud_pub_;\n    ros::Publisher pointcloud2_pub_;\n\n    std::string tf_base_link, tf_sensor_link, tf_gt_link, points_topic, odometry_topic, odometry_frame, scan_topic, scan2_topic;\n\n    ros::Timer heartbeat_slow_visualization_;\n    ros::Timer heartbeat_fast_visualization_;\n    bool do_pub_ndt_markers_;\n    bool do_pub_sigmapoints_markers_;\n\n    std::ofstream gt_file_;\n    std::ofstream gt2d_file_;\n    \n    std::ofstream est_file_;\n    std::ofstream est2d_file_;\n    std::string gt_topic;\n\n    bool use_initial_pose_from_gt;\n\n    boost::shared_ptr<velodyne_rawdata::RawData> data_; \n    boost::shared_ptr<velodyne_rawdata::RawData> data2_;\n    tf::TransformListener tf_listener;\n    \n    int skip_nb_rings_;\n    int skip_start_;\n    double voxel_filter_size_;\n    int cloud_min_size_;\n\n    bool draw_ml_lines;\n    \npublic:\n    NDTUKF3DNode(ros::NodeHandle param_nh) : data_(new velodyne_rawdata::RawData()), data2_(new velodyne_rawdata::RawData()) {\n\t    \n        //////////////////////////////////////////////////////////\n        // Setup the data parser for the raw packets\n        //////////////////////////////////////////////////////////\n        {\n            data_->setup(param_nh); // To get the calibration file\n            double max_range, min_range, view_direction, view_width;\n            param_nh.param<double>(\"max_range\", max_range, 130.);\n            param_nh.param<double>(\"min_range\", min_range, 2.);\n            param_nh.param<double>(\"view_direction\", view_direction, 0.);\n            param_nh.param<double>(\"view_width\", view_width, 6.3);\n            data_->setParameters(min_range, max_range, view_direction, view_width);\n\n            param_nh.param<int>(\"skip_nb_rings\", skip_nb_rings_, 0);\n            param_nh.param<int>(\"skip_start\", skip_start_, 0);\n            param_nh.param<double>(\"voxel_filter_size\", voxel_filter_size_, -1.);\n            param_nh.param<int>(\"cloud_min_size\", cloud_min_size_, 2000); // minimum amount of points (to avoid some problems with lost packages...).\n        }\n        // Need to have a separate configuration file for the second scanner...\n        std::string calibration2;\n        param_nh.param<std::string>(\"calibration2\", calibration2, std::string(\"\"));\n        {\n            if (calibration2 != std::string(\"\")) {\n                ros::NodeHandle nh_tmp(\"scan2\");\n                nh_tmp.setParam(\"calibration\", calibration2);\n                data2_->setup(nh_tmp);\n                double max_range, min_range, view_direction, view_width;\n                param_nh.param<double>(\"max_range2\", max_range, 130.);\n                param_nh.param<double>(\"min_range2\", min_range, 2.);\n                param_nh.param<double>(\"view_direction2\", view_direction, 0.);\n                param_nh.param<double>(\"view_width2\", view_width, 6.3);\n                data2_->setParameters(min_range, max_range, view_direction, view_width);        }\n        } \n            \n        //////////////////////////////////////////////////////////\n        /// Prepare Pose offsets\n        //////////////////////////////////////////////////////////\n        bool use_sensor_pose, use_initial_pose;\n        double pose_init_x,pose_init_y,pose_init_z,\n            pose_init_r,pose_init_p,pose_init_t;\n        double sensor_pose_x,sensor_pose_y,sensor_pose_z,\n            sensor_pose_r,sensor_pose_p,sensor_pose_t;\n\n        param_nh.param<bool>(\"set_sensor_pose\", use_sensor_pose, true);\n        param_nh.param<bool>(\"set_initial_pose\", use_initial_pose, false);\n        param_nh.param<bool>(\"set_initial_pose_from_gt\", use_initial_pose_from_gt, false);\n\n        if(use_initial_pose) {\n            ///initial pose of the vehicle with respect to the map\n            param_nh.param(\"pose_init_x\",pose_init_x,0.);\n            param_nh.param(\"pose_init_y\",pose_init_y,0.);\n            param_nh.param(\"pose_init_z\",pose_init_z,0.);\n            param_nh.param(\"pose_init_r\",pose_init_r,0.);\n            param_nh.param(\"pose_init_p\",pose_init_p,0.);\n            param_nh.param(\"pose_init_t\",pose_init_t,0.);\n            initPoseT =  Eigen::Translation<double,3>(pose_init_x,pose_init_y,pose_init_z)*\n                Eigen::AngleAxis<double>(pose_init_r,Eigen::Vector3d::UnitX()) *\n                Eigen::AngleAxis<double>(pose_init_p,Eigen::Vector3d::UnitY()) *\n                Eigen::AngleAxis<double>(pose_init_t,Eigen::Vector3d::UnitZ()) ;\n\n            hasInitialPose=true;\n        } else {\n            hasInitialPose=false;\n        }\n\n        if(use_sensor_pose) {\n            ///pose of the sensor with respect to the vehicle odometry frame\n            param_nh.param(\"sensor_pose_x\",sensor_pose_x,0.);\n            param_nh.param(\"sensor_pose_y\",sensor_pose_y,0.);\n            param_nh.param(\"sensor_pose_z\",sensor_pose_z,0.);\n            param_nh.param(\"sensor_pose_r\",sensor_pose_r,0.);\n            param_nh.param(\"sensor_pose_p\",sensor_pose_p,0.);\n            param_nh.param(\"sensor_pose_t\",sensor_pose_t,0.);\n            hasSensorPose = true;\n            sensorPoseT =  Eigen::Translation<double,3>(sensor_pose_x,sensor_pose_y,sensor_pose_z)*\n                Eigen::AngleAxis<double>(sensor_pose_r,Eigen::Vector3d::UnitX()) *\n                Eigen::AngleAxis<double>(sensor_pose_p,Eigen::Vector3d::UnitY()) *\n                Eigen::AngleAxis<double>(sensor_pose_t,Eigen::Vector3d::UnitZ()) ;\n\t    \n            param_nh.param(\"sensor_pose2_x\",sensor_pose_x,0.);\n            param_nh.param(\"sensor_pose2_y\",sensor_pose_y,0.);\n            param_nh.param(\"sensor_pose2_z\",sensor_pose_z,0.);\n            param_nh.param(\"sensor_pose2_r\",sensor_pose_r,0.);\n            param_nh.param(\"sensor_pose2_p\",sensor_pose_p,0.);\n            param_nh.param(\"sensor_pose2_t\",sensor_pose_t,0.);\n\t\t\n            sensorPoseT2 =  Eigen::Translation<double,3>(sensor_pose_x,sensor_pose_y,sensor_pose_z)*\n                Eigen::AngleAxis<double>(sensor_pose_r,Eigen::Vector3d::UnitX()) *\n                Eigen::AngleAxis<double>(sensor_pose_p,Eigen::Vector3d::UnitY()) *\n                Eigen::AngleAxis<double>(sensor_pose_t,Eigen::Vector3d::UnitZ()) ;\n                \n        } else {\n            hasSensorPose = false;\n        }\n\n        double sensor_time_offset;\n        param_nh.param(\"sensor_time_offset\", sensor_time_offset, 0.);\n        sensorTimeOffset_ = ros::Duration(sensor_time_offset);\n        param_nh.param(\"sensor_time_offset2\", sensor_time_offset, 0.);\n        sensorTimeOffset2_ = ros::Duration(sensor_time_offset);\n            \n        //////////////////////////////////////////////////////////\n        /// Prepare the map\n        //////////////////////////////////////////////////////////\n        param_nh.param<std::string>(\"map_file_name\", mapName, std::string(\"basement.ndmap\"));\n        param_nh.param<bool>(\"save_output_map\", saveMap, true);\n        param_nh.param<std::string>(\"output_map_file_name\", output_map_name, std::string(\"ndt_mapper_output.ndmap\"));\n        param_nh.param<double>(\"map_resolution\", resolution , 0.2);\n        param_nh.param<double>(\"subsample_level\", subsample_level , 1);\n\n        fprintf(stderr,\"USING RESOLUTION %lf\\n\",resolution);\n\t    \n        perception_oru::NDTMap ndmap(new perception_oru::LazyGrid(resolution));\n        ndmap.loadFromJFF(mapName.c_str());\n        ROS_INFO_STREAM(\"Loaded map: \" << mapName << \" containing \" << ndmap.getAllCells().size() << \" cells\");\n            \n\n        //////////////////////////////////////////////////////////\n        /// Prepare UKF object \n        //////////////////////////////////////////////////////////\n\n        ndtukf = new NDTUKF3D(resolution,ndmap);\n        UKF3D::Params ukf_params;\n        param_nh.getParam(\"motion_model\", ndtukf->motion_model);\n        param_nh.getParam(\"motion_model_offset\", ndtukf->motion_model_offset);\n        param_nh.param<double>(\"resolution_sensor\", ndtukf->resolution_sensor, resolution);\n        param_nh.param<double>(\"ukf_range_var\", ukf_params.range_var, 1.);\n        param_nh.param<double>(\"ukf_alpha\", ukf_params.alpha, 0.1);\n        param_nh.param<double>(\"ukf_beta\", ukf_params.beta, 2.);\n        param_nh.param<double>(\"ukf_kappa\", ukf_params.kappa, 3.);\n        param_nh.param<double>(\"ukf_min_pos_var\", ukf_params.min_pos_var, 0.01);\n        param_nh.param<double>(\"ukf_min_rot_var\", ukf_params.min_rot_var, 0.01);\n        param_nh.param<double>(\"ukf_range_filter_max_dist\", ukf_params.range_filter_max_dist, 1.);\n        param_nh.param<int>(\"ukf_nb_ranges_in_update\", ukf_params.nb_ranges_in_update, 100);\n\n        ndtukf->setParamsUKF(ukf_params);\n        \n        ukf_pub = nh_.advertise<nav_msgs::Odometry>(\"ndt_ukf\",10);\n        \n        //////////////////////////////////////////////////////////\n        /// Prepare the callbacks and message filters\n        //////////////////////////////////////////////////////////\n        //the name of the TF link associated to the base frame / odometry frame    \n        param_nh.param<std::string>(\"tf_base_link\", tf_base_link, std::string(\"/base_link\"));\n        //the name of the tf link associated to the 3d laser scanner\n        param_nh.param<std::string>(\"tf_laser_link\", tf_sensor_link, std::string(\"/velodyne_link\"));\n        param_nh.param<std::string>(\"tf_gt_link\", tf_gt_link, std::string(\"\"));\n\n\n        ///topic to wait for packet data \n        param_nh.param<std::string>(\"scan_topic\", scan_topic, \"\");\n        param_nh.param<std::string>(\"scan2_topic\", scan2_topic, \"\");\n        use_dual_scan = false;\n        if (scan2_topic != std::string(\"\")) {\n            use_dual_scan = true;\n            if (calibration2 == std::string(\"\")) {\n                ROS_ERROR(\"no calibration2 parameter given for the scan2 scanner!!!\");\n            }\n        }\n\n        ///topic to wait for point clouds\n        param_nh.param<std::string>(\"points_topic\",points_topic,\"points\");\n        ///topic to wait for odometry messages\n        param_nh.param<std::string>(\"odometry_topic\",odometry_topic,\"odometry\");\n        param_nh.param<std::string>(\"odometry_frame\", odometry_frame, \"/world\");\n\n            \n        // If a scan_topic is provided, force to use it\n        if (scan_topic != std::string(\"\")) {\n            ROS_INFO_STREAM(\"A scan topic is specified [will use that along with tf] : \" << scan_topic);\n            scan_sub_ = nh_.subscribe<velodyne_msgs::VelodyneScan>(scan_topic,10,&NDTUKF3DNode::scan_callback, this);\n            if (scan2_topic != std::string(\"\")) {\n                scan2_sub_ = nh_.subscribe<velodyne_msgs::VelodyneScan>(scan2_topic,10,&NDTUKF3DNode::scan2_callback, this);\n                ROS_INFO_STREAM(\"A scan2 topic is specified [will use that along with tf] : \" << scan_topic);\n            }\n        }\n        else {\n            ROS_ERROR_STREAM(\"No scan_topic specified... quitting.\");\n            exit(-1);\n        }\n\n        isFirstLoad=true;\n        pcounter =0;\n\n        //////////////////////////////////////////////////////////\n        /// Visualization\n        //////////////////////////////////////////////////////////\n        param_nh.param<bool>(\"do_visualize\", do_visualize, true);\n        param_nh.param<bool>(\"do_pub_ndt_markers\", do_pub_ndt_markers_, true);\n        param_nh.param<bool>(\"do_pub_sigmapoints_markers\", do_pub_sigmapoints_markers_, true);\n        param_nh.param<bool>(\"draw_ml_lines\", draw_ml_lines, true);\n        \n        marker_pub_ = nh_.advertise<visualization_msgs::Marker>(\"visualization_marker\", 3);\n        markerarray_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(\"visualization_marker_array\", 10);\n\n        pointcloud_pub_ = nh_.advertise<sensor_msgs::PointCloud2>(\"interppoints\", 15);\n        pointcloud2_pub_ = nh_.advertise<sensor_msgs::PointCloud2>(\"ml_points\", 15);\n\n        heartbeat_slow_visualization_   = nh_.createTimer(ros::Duration(1.0),&NDTUKF3DNode::publish_visualization_slow,this);\n        heartbeat_fast_visualization_   = nh_.createTimer(ros::Duration(0.1),&NDTUKF3DNode::publish_visualization_fast,this);\n    \n        //////////////////////////////////////////////////////////\n        /// Evaluation\n        //////////////////////////////////////////////////////////\n        std::string gt_filename, gt2d_filename, est_filename, est2d_filename;\n        param_nh.param<std::string>(\"gt_topic\",gt_topic,\"\");\n        param_nh.param<std::string>(\"output_gt_file\",  gt_filename, \"loc_gt_pose.txt\");\n        param_nh.param<std::string>(\"output_gt2d_file\",  gt2d_filename, \"loc_gt2d_pose.txt\");\n        param_nh.param<std::string>(\"output_est_file\", est_filename, \"loc_est_pose.txt\"); \n        param_nh.param<std::string>(\"output_est2d_file\", est2d_filename, \"loc_est2d_pose.txt\");\n        if (gt_filename != std::string(\"\")) {\n            gt_file_.open(gt_filename.c_str());\n            if (tf_gt_link == std::string(\"\")) {\n                ROS_WARN(\"tf_gt_link not set - will not log any gt data\");\n            }\n        }\n        if (gt2d_filename != std::string(\"\")) {\n            gt2d_file_.open(gt2d_filename.c_str());\n            if (tf_gt_link == std::string(\"\")) {\n                ROS_WARN(\"tf_gt_link not set - will not log any gt data\");\n            }\n        }\n\n        if (est_filename != std::string(\"\")) {\n            est_file_.open(est_filename.c_str());\n        }\n        if (est2d_filename != std::string(\"\")) {\n            est2d_file_.open(est2d_filename.c_str());\n        }\n            \n        if (!gt_file_.is_open() || !gt2d_file_.is_open() || !est_file_.is_open() || !est2d_file_.is_open())\n        {\n\n            ROS_ERROR_STREAM(\"Failed to open : \" << est_file_.rdbuf() << \" | \" << est2d_file_.rdbuf() << \" | \" << gt_file_.rdbuf() << \" | \" << gt2d_file_.rdbuf()); \n        }\n                        \n        if (gt_topic != std::string(\"\")) \n        {\n            ROS_INFO_STREAM(\"Subscribing to : \" << gt_topic);\n            gt_sub = nh_.subscribe<nav_msgs::Odometry>(gt_topic,10,&NDTUKF3DNode::gt_callback, this);\t\n        }\n        \n\n    }\n    ~NDTUKF3DNode() {\n        if (gt_file_.is_open())\n            gt_file_.close();\n        if (gt2d_file_.is_open())\n            gt2d_file_.close();\n        if (est_file_.is_open())\n            est_file_.close();\n        if (est2d_file_.is_open())\n            est2d_file_.close();\n          \n        delete points2_sub_;\n        delete odom_sub_;\n        delete ndtukf;\n    }\n\n    void publish_visualization_fast(const ros::TimerEvent &event) {\n\n        if (do_pub_sigmapoints_markers_) \n        {\n            ukf_m.lock();\n            std::vector<Eigen::Affine3d> sigmas = ndtukf->getSigmasAsAffine3d();\n            for (int i = 0; i < sigmas.size(); i++) {\n                markerarray_pub_.publish(ndt_visualisation::getMarkerFrameAffine3d(sigmas[i], \"sigmapoints\" + ndt_generic::toString(i), 1., 0.1));\n                std::cout << \"sigmas[i] : \" << ndt_generic::affine3dToStringRPY(sigmas[i]) << std::endl;\n            }\n            ukf_m.unlock();\n        }\n    }\n\n    void publish_visualization_slow(const ros::TimerEvent &event) {\n        if (do_pub_ndt_markers_)\n        {\n            // visualization_msgs::Marker markers_ndt;\n            // ndt_visualisation::markerNDTCells2(*(graph->getLastFeatureFuser()->map),\n            //                                    graph->getT(), 1, \"nd_global_map_last\", markers_ndt);\n            // marker_pub_.publish(markers_ndt);\n            ukf_m.lock();\n            marker_pub_.publish(ndt_visualisation::markerNDTCells(ndtukf->map, 1, \"nd_map\"));\n            ukf_m.unlock();\n        }\n    }\n    \n    void initialize() {\n        //if not, check if initial robot pose has been set\n        if(!hasInitialPose) {\n            //can't do anything, wait for pose message...\n            ROS_INFO(\"waiting for initial pose\");\n            return;\n        }\n        //initialize filter\n        Eigen::Vector3d tr = initPoseT.translation();\n        Eigen::Vector3d rot = initPoseT.rotation().eulerAngles(0,1,2);\n\t\n        Todo_old=Todo;\n        Tcum = initPoseT;\n\n        //ndtukf->initializeFilter(initPoseT, 50, 50, 10, 100.0*M_PI/180.0, 100.0*M_PI/180.0 ,100.0*M_PI/180.0);\n        // ndtukf->initializeFilter(initPoseT, 0.5, 0.5, 0.5, 2.0*M_PI/180.0, 2.0*M_PI/180.0 ,2.0*M_PI/180.0);\n        //        ndtukf->initializeFilter(initPoseT, 2, 2, 2, 5.0*M_PI/180.0, 5.0*M_PI/180.0 ,5.0*M_PI/180.0);\n        ndtukf->initializeFilter(initPoseT, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01);\n        isFirstLoad = false;\n    }\n    \n\n    // Simply to get an easier interface to tf.\n    bool getTransformationForTime(const ros::Time &t0, const std::string &frame_id, tf::Transform &T) {\n        bool success = false;\n        try {\n            success = tf_listener.waitForTransform(odometry_frame, frame_id, t0, ros::Duration(2.0));\n        }\n        catch (tf::TransformException &ex) {\n            ROS_WARN_THROTTLE(100, \"%s\", ex.what());\n            return false;\n        }\n        if (!success) {\n            return false;\n        }\n        tf::StampedTransform Ts;\n        tf_listener.lookupTransform (odometry_frame, frame_id, t0, Ts);\n        T = Ts;\n        return true;\n    }\n\n    // Simply to get an easier interface to tf.\n    bool getRelativeTransformationForTime(const ros::Time &t0,const ros::Time &t1, const std::string &frame_id,tf::Transform &T)  {\n        bool success = false;\n        try { \n            success = tf_listener.waitForTransform(frame_id, t0, frame_id, t1, odometry_frame, ros::Duration(2.0));\n        }\n        catch (tf::TransformException &ex) {\n            ROS_WARN_THROTTLE(100, \"%s\", ex.what());\n            return false;\n        }\n        if (!success) {\n            return false;\n        }\n        tf::StampedTransform Ts;\n        tf_listener.lookupTransform (frame_id, t0, frame_id, t1, odometry_frame, Ts);\n        T = Ts;\n        return true;\n    }\n\n    bool getTransformationAffine3d(const ros::Time &t0, const std::string &frame_id, Eigen::Affine3d &T) {\n        tf::Transform tf_T;\n        if (!getTransformationForTime(t0, frame_id, tf_T)) {\n            ROS_ERROR_STREAM(\"Failed to get from /tf : \" << frame_id);\n            return false;\n        }\n        tf::transformTFToEigen(tf_T, T);\n        return true;\n    }\n\n        \n    // Access the scans directly. This to better handle the time offsets / perform interpolation. Anyway it is useful to have better access to the points.\n    void scan_callback(const velodyne_msgs::VelodyneScan::ConstPtr &scanMsg) {\n        ukf_m.lock();\n\n        // Get the time stamp from the header, the pose at this time will be seen as the origin.\n        ros::Time t0; // Corresponding time stamp which relates the scan to the odometry tf frame.\n        t0 = scanMsg->header.stamp + sensorTimeOffset_;\n\n        // If we are using the dual scan setup then we need to have the timestamp of the previous one in order to get syncronized pointclouds\n        if (use_dual_scan) {\n            if (scan2_cloud_.empty()) {\n                ukf_m.unlock();\n                return;\n            }\n            t0 = scan2_t0_ - sensorTimeOffset2_ + sensorTimeOffset_;  \n        }\n\n        // Get the current odometry position (need to check the incremental odometry meassure since last call).\n        {\n            tf::Transform T;\n            if (!getTransformationForTime(t0, tf_base_link, T)) {\n                ROS_INFO_STREAM(\"Waiting for : \" << tf_base_link);\n                ukf_m.unlock();\n                return;\n            }\n            tf::transformTFToEigen(T, Todo);\n        }\n \n        //check if we have done iterations \n        if(isFirstLoad) {\n            initialize();\n            ukf_m.unlock();\n            return;\n        }\n\n        Eigen::Affine3d Tm;\n        Tm = Todo_old.inverse()*Todo;\n\n        if(Tm.translation().norm()<0.01 && fabs(Tm.rotation().eulerAngles(0,1,2)[2])<(0.5*M_PI/180.0)) {\n            ROS_INFO_STREAM(\"Not enough distance / rot traversed : \" << Tm.translation().norm() << \" / \" << fabs(Tm.rotation().eulerAngles(0,1,2)[2]));\n            ukf_m.unlock();\n            return;\n        }\n\n        // We're interessted in getting the pointcloud in the vehicle frame (that is to transform it using the sensor pose offset).\n        pcl::PointCloud<pcl::PointXYZ> cloud, cloud2;\n        \n        velodyne_rawdata::VPointCloud pnts,conv_points;\n        tf::Transform T_sensorpose;\n        tf::transformEigenToTF(sensorPoseT, T_sensorpose);\n\n        for (size_t next = 0; next < scanMsg->packets.size(); ++next) {\n            data_->unpack(scanMsg->packets[next], pnts);\n            // Get the transformation of this scan packet (the vehicle pose)\n            \n            ros::Time t1 = scanMsg->packets[next].stamp + sensorTimeOffset_;\n            // Get the relative pose...\n            tf::Transform T;\n            if (!getRelativeTransformationForTime(t0, t1, tf_base_link, T)) {\n                continue;\n            }\n            \n            tf::Transform Tcloud =  T * T_sensorpose;\n            pcl_ros::transformPointCloud(pnts,conv_points,Tcloud);\n            for (size_t i = 0; i < conv_points.size(); i++) {\n                if (skip_nb_rings_ == 0) {\n                    cloud.push_back(pcl::PointXYZ(conv_points.points[i].x,\n                                                  conv_points.points[i].y,\n                                                  conv_points.points[i].z));\n                }\n                else if (conv_points.points[i].ring % (skip_nb_rings_+1) == skip_start_ % (skip_nb_rings_+1)) {\n                    cloud.push_back(pcl::PointXYZ(conv_points.points[i].x,\n                                                  conv_points.points[i].y,\n                                                  conv_points.points[i].z));\n                }\n                else {\n                    \n                }\n            }\n            pnts.clear();\n            conv_points.clear();\n        }\n        \n        if (voxel_filter_size_ > 0) {\n            // Create the filtering object\n            pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2(new pcl::PointCloud<pcl::PointXYZ>());\n            *cloud2 = cloud;\n            pcl::VoxelGrid<pcl::PointXYZ> sor;\n            sor.setInputCloud (cloud2);\n            sor.setLeafSize (voxel_filter_size_, voxel_filter_size_, voxel_filter_size_);\n            pcl::PointCloud<pcl::PointXYZ> cloud_filtered;\n            sor.filter (cloud);\n            \n            // pcl::PointCloud<PointType>::Ptr laserCloudCornerStack(new pcl::PointCloud<PointType>());\n            // pcl::VoxelGrid<PointType> downSizeFilterCorner;\n            // downSizeFilterCorner.setLeafSize(0.2, 0.2, 0.2);\n\n            // downSizeFilterCorner.setInputCloud(laserCloudCornerStack2);\n            // downSizeFilterCorner.filter(*laserCloudCornerStack);\n        \n\n\n        }\n\n        // Check size of the cloud\n        if (cloud.size() < cloud_min_size_) {\n            ukf_m.unlock();\n            return;\n        }\n        \n        if (use_dual_scan) {\n            cloud += scan2_cloud_;\n            scan2_cloud_.clear();\n        }\n\n        // \n        Tcum = Tcum*Tm;\n        Todo_old=Todo;\n\n  \n\n        //update filter -> + add parameter to subsample ndt map in filter step\n        ndtukf->updateAndPredict/*Eff*/(Tm, cloud/*, subsample_level*/, sensorPoseT);\n        //ndtukf->predict(Tm);\n\n        {\n            sensor_msgs::PointCloud2 pcloud;\n            pcl::toROSMsg(ndtukf->getFilterRaw(), pcloud);\n            pcloud.header.stamp = t0;\n            pcloud.header.frame_id = \"interppoints\";\n            pointcloud_pub_.publish(pcloud);\n        }\n\n        {\n            sensor_msgs::PointCloud2 pcloud;\n            pcl::toROSMsg(ndtukf->getFilterPred(),pcloud);\n            pcloud.header.stamp = t0;\n            pcloud.header.frame_id = \"interppoints\";\n            pointcloud2_pub_.publish(pcloud);\n\n            if (draw_ml_lines) {\n                \n                marker_pub_.publish(ndt_visualisation::getMarkerLineListFromTwoPointClouds(ndtukf->getFilterRaw(), ndtukf->getFilterPred(), 0, \"ml_lines\", \"interppoints\", 0.05));\n            }\n        }\n       \n        //publish pose\n        sendROSOdoMessage(ndtukf->getMean(),t0);\n        ukf_m.unlock();\n    }\n\n    // Simply store the point cloud, all the updates are from the scan_callback()\n    void scan2_callback(const velodyne_msgs::VelodyneScan::ConstPtr &scanMsg) {\n        ukf_m.lock();\n\n        // Get the time stamp from the header, the pose at this time will be seen as the origin.\n        ros::Time t0;\n        t0 = scanMsg->header.stamp + sensorTimeOffset2_;\n        scan2_t0_ = t0;\n        // Get the current odometry position (need to check the incremental odometry meassure since last call).\n        {\n            tf::Transform T;\n            if (!getTransformationForTime(t0, tf_base_link, T)) {\n                ROS_INFO_STREAM(\"Waiting for : \" << tf_base_link);\n                ukf_m.unlock();\n                return;\n            }\n            tf::transformTFToEigen(T, Todo);\n        }\n \n        //check if we have done iterations \n        if(isFirstLoad) {\n            initialize();\n            ukf_m.unlock();\n            return;\n        }\n\n        Eigen::Affine3d Tm;\n        Tm = Todo_old.inverse()*Todo;\n\n        if(Tm.translation().norm()<0.01 && fabs(Tm.rotation().eulerAngles(0,1,2)[2])<(0.5*M_PI/180.0)) {\n            ukf_m.unlock();\n            return;\n        }\n\n        // We're interessted in getting the pointcloud in the vehicle frame (that is to transform it using the sensor pose offset).\n        pcl::PointCloud<pcl::PointXYZ> cloud;\n        \n        velodyne_rawdata::VPointCloud pnts,conv_points;\n        tf::Transform T_sensorpose;\n        tf::transformEigenToTF(sensorPoseT2, T_sensorpose);\n\n        for (size_t next = 0; next < scanMsg->packets.size(); ++next) {\n            data2_->unpack(scanMsg->packets[next], pnts);\n            // Get the transformation of this scan packet (the vehicle pose)\n            \n            ros::Time t1 = scanMsg->packets[next].stamp + sensorTimeOffset_;\n            // Get the relative pose...\n            tf::Transform T;\n            if (!getRelativeTransformationForTime(t0, t1, tf_base_link, T)) {\n                continue;\n            }\n            \n            tf::Transform Tcloud =  T * T_sensorpose;\n            pcl_ros::transformPointCloud(pnts,conv_points,Tcloud);\n            for (size_t i = 0; i < conv_points.size(); i++) {\n                cloud.push_back(pcl::PointXYZ(conv_points.points[i].x,\n                                              conv_points.points[i].y,\n                                              conv_points.points[i].z));\n            }\n            pnts.clear();\n            conv_points.clear();\n        }\n\n        // Check size of the cloud\n        if (cloud.size() < 3000) {\n            ukf_m.unlock();\n            return;\n        }\n\n        scan2_cloud_ = cloud;\n\n        ukf_m.unlock();\n    }\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //\n    bool sendROSOdoMessage(Eigen::Affine3d mean,ros::Time ts){\n        nav_msgs::Odometry O;\n        static int seq = 0;\n        O.header.stamp = ts;\n        O.header.seq = seq;\n        O.header.frame_id = odometry_frame;\n        O.child_frame_id = \"/ukf_pose\";\n\n        O.pose.pose.position.x = mean.translation()[0];\n        O.pose.pose.position.y = mean.translation()[1];\n        O.pose.pose.position.z = mean.translation()[2];\n        Eigen::Quaterniond q (mean.rotation());\n        tf::Quaternion qtf;\n        tf::quaternionEigenToTF (q, qtf);\n        O.pose.pose.orientation.x = q.x();\n        O.pose.pose.orientation.y = q.y();\n        O.pose.pose.orientation.z = q.z();\n        O.pose.pose.orientation.w = q.w();\n\n        seq++;\n        ukf_pub.publish(O);\n\n        static tf::TransformBroadcaster br;\n        tf::Transform transform;\n        transform.setOrigin( tf::Vector3(mean.translation()[0],mean.translation()[1], mean.translation()[2]) );\n\n        transform.setRotation( qtf );\n        br.sendTransform(tf::StampedTransform(transform, ts, \"world\", \"ukf_pose\"));\n\n        if (est_file_.is_open()) {\n            est_file_ << ts << \" \" << perception_oru::transformToEvalString(mean);\n        }\n        if (est2d_file_.is_open()) {\n            est2d_file_ << ts << \" \" << perception_oru::transformToEval2dString(mean);\n        }\n        if (gt_file_.is_open() && tf_gt_link != std::string(\"\")) {\n            Eigen::Affine3d T_gt;\n            if (getTransformationAffine3d(ts, tf_gt_link, T_gt)) {\n                gt_file_ << ts << \" \" << perception_oru::transformToEvalString(T_gt);\n            }\n            if (gt2d_file_.is_open()) {\n                gt2d_file_ << ts << \" \" << perception_oru::transformToEval2dString(T_gt);\n            }\n        }\n\n        return true;\n    }\n\n    // Callback\n    void gt_callback(const nav_msgs::Odometry::ConstPtr& msg_in)\n    {\n        Eigen::Quaterniond qd;\n        Eigen::Affine3d gt_pose;\n\n        qd.x() = msg_in->pose.pose.orientation.x;\n        qd.y() = msg_in->pose.pose.orientation.y;\n        qd.z() = msg_in->pose.pose.orientation.z;\n        qd.w() = msg_in->pose.pose.orientation.w;\n\t    \n        gt_pose = Eigen::Translation3d (msg_in->pose.pose.position.x,\n                                        msg_in->pose.pose.position.y,msg_in->pose.pose.position.z) * qd;\n\t     \n\n        // Query the pose from the /tf instead (see abouve in sendOdoMessage).\n        // if (gt_file_.is_open()) {\n        //   gt_file_ << msg_in->header.stamp << \" \" << lslgeneric::transformToEvalString(gt_pose);\n        // }\n\n        // m.lock();\n        if(use_initial_pose_from_gt && !hasInitialPose) {\n            hasInitialPose = true;\n            ROS_INFO(\"Set initial pose from GT track\");\n            initPoseT = gt_pose;\n        }\n        // m.unlock();\n    }\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n};\n\n\nint main(int argc, char **argv){\n    ros::init(argc, argv, \"NDT-UKF\");\n    ros::NodeHandle paramHandle (\"~\");\n    NDTUKF3DNode ukfnode(paramHandle);   \t\n    ros::spin();\n    return 0;\n}\n", "meta": {"hexsha": "b17d2396779a8e5f9e23cf5616469b9ed52faf9d", "size": 33139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_mcl/src/3d_ndt_ukf_node2.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_mcl/src/3d_ndt_ukf_node2.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_mcl/src/3d_ndt_ukf_node2.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": 41.0644361834, "max_line_length": 178, "alphanum_fraction": 0.5809770965, "num_tokens": 7979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19473590411694508}}
{"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_DEFINITION_NEARBYINT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DEFINITION_NEARBYINT_HPP_INCLUDED\n\n#include <boost/simd/config.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.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    BOOST_DISPATCH_MAKE_TAG(ext, nearbyint_, boost::dispatch::elementwise_<nearbyint_>);\n  }\n\n  namespace ext\n  {\n    BOOST_DISPATCH_FUNCTION_DECLARATION(tag, nearbyint_)\n  }\n\n  BOOST_DISPATCH_CALLABLE_DEFINITION(tag::nearbyint_,nearbyint);\n\n\n} }\n\n#endif\n", "meta": {"hexsha": "4f7bfb3a6cf31fb2671f20484cda137ecc554632", "size": 1030, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/definition/nearbyint.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/definition/nearbyint.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/definition/nearbyint.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": 27.8378378378, "max_line_length": 100, "alphanum_fraction": 0.6310679612, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19473590411694508}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_POISSON_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_POISSON_RNG_HPP\n\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_less.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.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/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/gamma_q.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\ntemplate <class RNG>\ninline int poisson_rng(double lambda, RNG& rng) {\n  using boost::random::poisson_distribution;\n  using boost::variate_generator;\n\n  static const char* function = \"poisson_rng\";\n\n  check_not_nan(function, \"Rate parameter\", lambda);\n  check_nonnegative(function, \"Rate parameter\", lambda);\n  check_less(function, \"Rate parameter\", lambda, POISSON_MAX_RATE);\n\n  variate_generator<RNG&, poisson_distribution<> > poisson_rng(\n      rng, poisson_distribution<>(lambda));\n  return poisson_rng();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "a81dc4833045a8fbb5500f29c18aff98df2c34a2", "size": 1245, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/prob/poisson_rng.hpp", "max_stars_repo_name": "sakrejda/math", "max_stars_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "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/poisson_rng.hpp", "max_issues_repo_name": "sakrejda/math", "max_issues_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "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/poisson_rng.hpp", "max_forks_repo_name": "sakrejda/math", "max_forks_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "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.9230769231, "max_line_length": 67, "alphanum_fraction": 0.7775100402, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19473590411694505}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <vw/Core/Log.h>\n#include <vw/Camera/PinholeModel.h>\n#include <vw/Math/EulerAngles.h>\n\n#if defined(VW_HAVE_PKG_LAPACK) && VW_HAVE_PKG_LAPACK==1\n#include <vw/Math/LinearAlgebra.h>\n#endif\n\n// For std::setprecision\n#include <iomanip>\n\n#if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1\n#include <vw/Camera/TsaiFile.pb.h>\nusing google::protobuf::RepeatedFieldBackInserter;\n#endif\n\n#include <boost/filesystem/convenience.hpp>\nnamespace fs = boost::filesystem;\n\nusing namespace vw;\n\n// Old deprecated format of Pinhole I/O. Didn't support all distortion options.\n// Reads in a file containing parameters of a pinhole model with\n// a tsai lens distortion model. An example is provided at the end of this file.\nvoid camera::PinholeModel::read_old_file(std::string const& filename) {\n\n  char line[2048];\n  double fu, fv, cu, cv;\n  Vector3 u_direction, v_direction, w_direction;\n  Vector3 C;\n  Matrix3x3 R;\n  Vector4 distortion_params(0,0,0,0);\n\n\n  FILE *cam_file = fopen(filename.c_str(), \"r\");\n  if (cam_file == 0) vw_throw( IOErr() << \"PinholeModel::read_file: Could not open file\\n\" );\n\n  // Read intrinsic parameters\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"fu = %lf\", &fu) != 1) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read x focal length\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"fv = %lf\", &fv) != 1) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read y focal length\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"cu = %lf\", &cu) != 1) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read x principal point\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"cv = %lf\", &cv) != 1) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read y principal point\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"u_direction = %lf %lf %lf\", &u_direction(0), &u_direction(1), &u_direction(2)) != 3) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read u direction vector\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"v_direction = %lf %lf %lf\", &v_direction(0), &v_direction(1), &v_direction(2)) != 3) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read v direction vector\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"w_direction = %lf %lf %lf\", &w_direction(0), &w_direction(1), &w_direction(2)) != 3) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read w direction vector\\n\" );\n  }\n\n  // Read extrinsic parameters\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"C = %lf %lf %lf\", &C(0), &C(1), &C(2)) != 3) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file: Could not read C (camera center) vector\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if ( sscanf(line, \"R = %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\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)) != 9 ) {\n      fclose(cam_file);\n      vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read rotation matrix\\n\" );\n  }\n\n  // Read distortion parameters.\n   fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"k1 = %lf\", &distortion_params[0] ) != 1) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read tsai distortion parameter k1\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"k2 = %lf\", &distortion_params[1] ) != 1) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read tsai distortion parameter k2\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"p1 = %lf\", &distortion_params[2] ) != 1) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read tsai distortion parameter p1\\n\" );\n  }\n\n  fgets(line, sizeof(line), cam_file);\n  if (sscanf(line,\"p2 = %lf\", &distortion_params[3] ) != 1) {\n    fclose(cam_file);\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read tsai distortion parameter p2\\n\" );\n  }\n\n  fclose(cam_file);\n\n  m_u_direction = u_direction;\n  m_v_direction = v_direction;\n  m_w_direction = w_direction;\n  m_pixel_pitch = 1;\n\n  m_fu = fu;\n  m_fv = fv;\n  m_cu = cu;\n  m_cv = cv;\n  m_camera_center = C;\n\n  m_rotation = R;\n  this->rebuild_camera_matrix();\n\n  if( distortion_params == Vector4(0,0,0,0))\n    m_distortion.reset(new NullLensDistortion());\n  else\n    m_distortion.reset(new TsaiLensDistortion(distortion_params));\n}\n\n\n// Reads in a file containing parameters of a pinhole model with\n// a tsai lens distortion model.\nvoid camera::PinholeModel::read_file(std::string const& filename) {\n  this->read(filename);\n}\n\nvoid camera::PinholeModel::read(std::string const& filename) {\n\n  fs::path filename_path( filename );\n  if ( filename_path.extension() == \".pinhole\" ) {\n#if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1\n    std::fstream input( filename.c_str(), std::ios::in | std::ios::binary );\n    if ( !input )\n      vw_throw( IOErr() << \"Pinhole::read_file: Could not open \" << filename << \"\\n\" );\n    TsaiFile file;\n    if ( !file.ParseFromIstream( &input ) )\n      vw_throw( IOErr() << \"Pinhole::read_file: Protocol buffer failed to parse \\\"\" << filename << \"\\\"\\n\" );\n    input.close();\n\n    // Making sure protobuf seems correct\n    VW_ASSERT( file.focal_length_size() == 2,\n               IOErr() << \"Pinhole::read_file: Unexpected amount of focal lengths.\" );\n    VW_ASSERT( file.center_point_size() == 2,\n               IOErr() << \"Pinhole::read_file: Unexpected amount of center points.\" );\n    VW_ASSERT( file.u_direction_size() == 3,\n               IOErr() << \"Pinhole::read_file: Unexpected size of u vector.\" );\n    VW_ASSERT( file.v_direction_size() == 3,\n               IOErr() << \"Pinhole::read_file: Unexpected size of v vector.\" );\n    VW_ASSERT( file.w_direction_size() == 3,\n               IOErr() << \"Pinhole::read_file: Unexpected size of w vector.\" );\n    VW_ASSERT( file.camera_center_size() == 3,\n               IOErr() << \"Pinhole::read_file: Unexpected size of camera vector.\" );\n    VW_ASSERT( file.camera_rotation_size() == 9,\n               IOErr() << \"Pinhole::read_file: Unexpected size of rotation matrix.\" );\n\n    typedef VectorProxy<double,3> Vector3P;\n    m_u_direction = Vector3P(file.mutable_u_direction()->mutable_data());\n    m_v_direction = Vector3P(file.mutable_v_direction()->mutable_data());\n    m_w_direction = Vector3P(file.mutable_w_direction()->mutable_data());\n    m_camera_center = Vector3P(file.mutable_camera_center()->mutable_data());\n    m_fu = file.focal_length(0);\n    m_fv = file.focal_length(1);\n    m_cu = file.center_point(0);\n    m_cv = file.center_point(1);\n    m_rotation = MatrixProxy<double,3,3>(file.mutable_camera_rotation()->mutable_data());\n    m_pixel_pitch = file.pixel_pitch();\n\n    this->rebuild_camera_matrix();\n\n    if ( file.distortion_name() == \"NULL\" ) {\n      VW_ASSERT( file.distortion_vector_size() == 0,\n                 IOErr() << \"Pinhole::read_file: Unexpected distortion vector.\" );\n      m_distortion.reset( new NullLensDistortion());\n    } else if ( file.distortion_name() == \"TSAI\" ) {\n      VW_ASSERT( file.distortion_vector_size() == 4,\n                 IOErr() << \"Pinhole::read_file: Unexpected distortion vector.\" );\n      m_distortion.reset( new TsaiLensDistortion(VectorProxy<double,4>(file.mutable_distortion_vector()->mutable_data())));\n    } else if ( file.distortion_name() == \"BROWNCONRADY\" ) {\n      VW_ASSERT( file.distortion_vector_size() == 8,\n                 IOErr() << \"Pinhole::read_file: Unexpected distortion vector.\" );\n      m_distortion.reset( new BrownConradyDistortion(VectorProxy<double,8>(file.mutable_distortion_vector()->mutable_data())));\n    } else if ( file.distortion_name() == \"AdjustableTSAI\" ) {\n      VW_ASSERT( file.distortion_vector_size() > 3,\n                 IOErr() << \"Pinhole::read_file: Unexpected distortion vector.\" );\n      m_distortion.reset( new AdjustableTsaiLensDistortion(VectorProxy<double>(file.distortion_vector_size(),file.mutable_distortion_vector()->mutable_data())));\n    }\n#else\n    // If you hit this point, you need to install Google Protobuffers to\n    // be in order to write.\n    vw_throw( IOErr() << \"Pinhole::write_file: Camera IO not supported without Google Protobuffers\" );\n#endif\n  } else if ( filename_path.extension() == \".tsai\" ) {\n    this->read_old_file( filename );\n  } else {\n    vw_throw( IOErr() << \"Unknown PinholeModel filename extension \\\"\"\n              << filename_path.extension() << \"\\\"\" );\n  }\n}\n\n\n// Write parameters of an exiting PinholeModel into a .tsai file for later use.\nvoid camera::PinholeModel::write_file(std::string const& filename) const {\n  write(filename);\n}\nvoid camera::PinholeModel::write(std::string const& filename) const {\n#if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1\n  std::string output_file =\n    fs::path(filename).replace_extension(\".pinhole\").string();\n\n  TsaiFile file;\n  file.add_focal_length( m_fu );\n  file.add_focal_length( m_fv );\n  file.add_center_point( m_cu );\n  file.add_center_point( m_cv );\n  file.set_pixel_pitch( m_pixel_pitch );\n\n  std::copy(m_u_direction.begin(), m_u_direction.end(),\n            RepeatedFieldBackInserter(file.mutable_u_direction()));\n  std::copy(m_v_direction.begin(), m_v_direction.end(),\n            RepeatedFieldBackInserter(file.mutable_v_direction()));\n  std::copy(m_w_direction.begin(), m_w_direction.end(),\n            RepeatedFieldBackInserter(file.mutable_w_direction()));\n  std::copy(m_camera_center.begin(), m_camera_center.end(),\n            RepeatedFieldBackInserter(file.mutable_camera_center()));\n\n  std::copy(m_rotation.begin(), m_rotation.end(),\n            RepeatedFieldBackInserter(file.mutable_camera_rotation()));\n\n  file.set_distortion_name( m_distortion->name() );\n  Vector<double> distort_vec = m_distortion->distortion_parameters();\n  std::copy(distort_vec.begin(),distort_vec.end(),\n            RepeatedFieldBackInserter(file.mutable_distortion_vector()));\n\n  std::ofstream output(output_file.c_str());\n  if( !output.is_open() )\n    vw_throw( IOErr() << \"PinholeModel::write_file: Could not open file\\n\" );\n  file.SerializeToOstream( &output );\n  output.close();\n#else\n  // If you hit this point, you need to install Google Protobuffers to\n  // be in order to write.\n  vw_throw( IOErr() << \"Pinhole::write_file: Camera IO not supported without Google Protobuffers\" );\n#endif\n}\n\nVector2 camera::PinholeModel::point_to_pixel(Vector3 const& point) const {\n\n  //  Multiply the pixel location by the camera matrix.\n  double denominator = m_camera_matrix(2,0)*point(0) + m_camera_matrix(2,1)*point(1) +\n    m_camera_matrix(2,2)*point(2) + m_camera_matrix(2,3);\n  Vector2 pixel = Vector2( (m_camera_matrix(0,0)*point(0) + m_camera_matrix(0,1)*point(1) +\n                            m_camera_matrix(0,2)*point(2) + m_camera_matrix(0,3)) / denominator,\n                           (m_camera_matrix(1,0)*point(0) + m_camera_matrix(1,1)*point(1) +\n                            m_camera_matrix(1,2)*point(2) + m_camera_matrix(1,3)) / denominator);\n\n  //  Apply the lens distortion model\n  return m_distortion->distorted_coordinates(*this, pixel)/m_pixel_pitch;\n}\n\nbool camera::PinholeModel::projection_valid(Vector3 const& point) const {\n  // z coordinate after extrinsic transformation\n  double z = m_extrinsics(2, 0)*point(0) + m_extrinsics(2, 1)*point(1) +\n    m_extrinsics(2, 2)*point(2) + m_extrinsics(2,3);\n  return z > 0;\n}\n\nVector3 camera::PinholeModel::pixel_to_vector (Vector2 const& pix) const {\n  // Apply the inverse lens distortion model\n  Vector2 undistorted_pix = m_distortion->undistorted_coordinates(*this, pix*m_pixel_pitch);\n\n  // Compute the direction of the ray emanating from the camera center.\n  Vector3 p(0,0,1);\n  subvector(p,0,2) = undistorted_pix;\n  return normalize( m_inv_camera_transform * p);\n}\n\nvoid camera::PinholeModel::intrinsic_parameters(double& f_u, double& f_v,\n                                                double& c_u, double& c_v) const {\n  f_u = m_fu;  f_v = m_fv;  c_u = m_cu;  c_v = m_cv;\n}\n\nvoid camera::PinholeModel::set_intrinsic_parameters(double f_u, double f_v,\n                                                    double c_u, double c_v) {\n  m_fu = f_u;  m_fv = f_v;  m_cu = c_u;  m_cv = c_v;\n  rebuild_camera_matrix();\n}\n\n\nvoid camera::PinholeModel::set_camera_matrix( Matrix<double,3,4> const& p ) {\n#if defined(VW_HAVE_PKG_LAPACK) && VW_HAVE_PKG_LAPACK==1\n  // Solving for camera center\n  Matrix<double> cam_nullsp = nullspace(p);\n  Vector<double> cam_center = select_col(cam_nullsp,0);\n  cam_center /= cam_center[3];\n  m_camera_center = subvector(cam_center,0,3);\n\n  // Solving for intrinsics with RQ decomposition\n  Matrix<double> M = submatrix(p,0,0,3,3);\n  Matrix<double> R,Q;\n  rqd( M, R, Q );\n  Matrix<double> sign_fix(3,3);\n  sign_fix.set_identity();\n  if ( R(0,0) < 0 )\n    sign_fix(0,0) = -1;\n  if ( R(1,1) < 0 )\n    sign_fix(1,1) = -1;\n  if ( R(2,2) < 0 )\n    sign_fix(2,2) = -1;\n  R = R*sign_fix;\n  Q = sign_fix*Q;\n  R /= R(2,2);\n\n  // Pulling out intrinsic and last extrinsic\n  Matrix<double,3,3> uvwRotation;\n  select_row(uvwRotation,0) = m_u_direction;\n  select_row(uvwRotation,1) = m_v_direction;\n  select_row(uvwRotation,2) = m_w_direction;\n  m_rotation = inverse(uvwRotation*Q);\n  m_fu = R(0,0);\n  m_fv = R(1,1);\n  m_cu = R(0,2);\n  m_cv = R(1,2);\n\n  if ( fabs(R(0,1)) >= 1.2 )\n    vw_out(WarningMessage,\"camera\") << \"Significant skew not modelled by pinhole camera\\n\";\n\n  // Rebuild\n  rebuild_camera_matrix();\n#else\n  vw_throw( NoImplErr() << \"PinholeModel::set_Camera_Matrix is unavailable without LAPACK\" );\n#endif\n}\n\nvoid camera::PinholeModel::rebuild_camera_matrix() {\n\n  /// The intrinsic portion of the camera matrix is stored as\n  ///\n  ///    [  fx   0   cx  ]\n  /// K= [  0    fy  cy  ]\n  ///    [  0    0   1   ]\n  ///\n  /// with fx, fy the focal length of the system (in horizontal and\n  /// vertical pixels), and (cx, cy) the pixel coordinates of the\n  /// central pixel (the principal point on the image plane).\n\n  m_intrinsics(0,0) = m_fu;\n  m_intrinsics(0,1) = 0;\n  m_intrinsics(0,2) = m_cu;\n  m_intrinsics(1,0) = 0;\n  m_intrinsics(1,1) = m_fv;\n  m_intrinsics(1,2) = m_cv;\n  m_intrinsics(2,0) = 0;\n  m_intrinsics(2,1) = 0;\n  m_intrinsics(2,2) = 1;\n\n  // The extrinsics are normally built as the matrix:  [ R | -R*C ].\n  // To allow for user-specified coordinate frames, the\n  // extrinsics are now build to include the u,v,w rotation\n  //\n  //               | u_0  u_1  u_2  |\n  //     Extr. =   | v_0  v_1  v_2  | * [ R | -R*C]\n  //               | w_0  w_1  w_2  |\n  //\n  // The vectors u,v, and w must be orthonormal.\n\n  /*   check for orthonormality of u,v,w              */\n  VW_LINE_ASSERT( dot_prod(m_u_direction, m_v_direction) == 0 );\n  VW_LINE_ASSERT( dot_prod(m_u_direction, m_w_direction) == 0 );\n  VW_LINE_ASSERT( dot_prod(m_v_direction, m_w_direction) == 0 );\n  VW_LINE_ASSERT( fabs( norm_2(m_u_direction) - 1 ) < 0.001 );\n  VW_LINE_ASSERT( fabs( norm_2(m_v_direction) - 1 ) < 0.001 );\n  VW_LINE_ASSERT( fabs( norm_2(m_w_direction) - 1 ) < 0.001 );\n\n  Matrix<double,3,3> uvwRotation;\n\n  select_row(uvwRotation,0) = m_u_direction;\n  select_row(uvwRotation,1) = m_v_direction;\n  select_row(uvwRotation,2) = m_w_direction;\n\n  Matrix<double,3,3> m_rotation_inverse = transpose(m_rotation);\n  submatrix(m_extrinsics,0,0,3,3) = uvwRotation * m_rotation_inverse;\n  select_col(m_extrinsics,3) = uvwRotation * -m_rotation_inverse * m_camera_center;\n\n  m_camera_matrix = m_intrinsics * m_extrinsics;\n  m_inv_camera_transform = inverse(uvwRotation*m_rotation_inverse) * inverse(m_intrinsics);\n}\n\n// scale_camera\n//  Used to modify camera in the event to user resizes the image\ncamera::PinholeModel\ncamera::scale_camera(camera::PinholeModel const& camera_model,\n                     float const& scale) {\n  Vector2 focal = camera_model.focal_length();\n  Vector2 offset = camera_model.point_offset();\n  focal *= scale;\n  offset *= scale;\n  boost::shared_ptr<LensDistortion> lens = camera_model.lens_distortion()->copy();\n  lens->scale( scale );\n  return camera::PinholeModel( camera_model.camera_center(),\n                               camera_model.camera_pose().rotation_matrix(),\n                               focal[0], focal[1], offset[0], offset[1],\n                               camera_model.coordinate_frame_u_direction(),\n                               camera_model.coordinate_frame_v_direction(),\n                               camera_model.coordinate_frame_w_direction(),\n                               *lens );\n}\n\n//   /// Given two pinhole camera models, this method returns two new camera\n//   /// models that have been epipolar rectified.\n//   template <>\n//   void epipolar(PinholeModel<NoLensDistortion> const& src_camera0,\n//                 PinholeModel<NoLensDistortion> const& src_camera1,\n//                 PinholeModel<NoLensDistortion> &dst_camera0,\n//                 PinholeModel<NoLensDistortion> &dst_camera1);\ncamera::PinholeModel\ncamera::linearize_camera(camera::PinholeModel const& camera_model) {\n  Vector2 focal = camera_model.focal_length();\n  Vector2 offset = camera_model.point_offset();\n  camera::NullLensDistortion distortion;\n  return camera::PinholeModel(camera_model.camera_center(),\n      camera_model.camera_pose().rotation_matrix(),\n      focal[0], focal[1], offset[0], offset[1],\n      camera_model.coordinate_frame_u_direction(),\n      camera_model.coordinate_frame_v_direction(),\n      camera_model.coordinate_frame_w_direction(),\n      distortion);\n}\n\nstd::ostream& camera::operator<<(std::ostream& str,\n                                 camera::PinholeModel const& model) {\n  str << \"Pinhole camera: \\n\";\n  str << \"\\tCamera Center: \" << model.camera_center() << \"\\n\";\n  str << \"\\tRotation Matrix: \" << model.camera_pose() << \"\\n\";\n  str << \"\\tIntrinsics:\\n\";\n  str << \"\\t  focal: \" << model.focal_length() << \"\\n\";\n  str << \"\\t  offset: \" << model.point_offset() << \"\\n\";\n  str << \"\\tDistortion Model: \" << model.lens_distortion()->name() << \"\\n\";\n  str << \"\\t  \" << *model.lens_distortion() << \"\\n\";\n\n  return str;\n}\n", "meta": {"hexsha": "edb5124d77e13f33f6de747e6cc9bb9b05b1861c", "size": 18563, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Camera/PinholeModel.cc", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/Camera/PinholeModel.cc", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.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": "src/vw/Camera/PinholeModel.cc", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 39.245243129, "max_line_length": 161, "alphanum_fraction": 0.6602381081, "num_tokens": 5198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19473589676484807}}
{"text": "//\n// Tracker time cluster finder\n//\n//\n// Original author D. Brown and G. Tassielli\n//\n// framework\n#include \"art/Framework/Principal/Event.h\"\n#include \"fhiclcpp/ParameterSet.h\"\n#include \"art/Framework/Principal/Handle.h\"\n#include \"art/Framework/Core/EDProducer.h\"\n#include \"art/Framework/Core/ModuleMacros.h\"\n#include \"art_root_io/TFileService.h\"\n// Mu2e\n#include \"GeneralUtilities/inc/Angles.hh\"\n#include \"Mu2eUtilities/inc/MVATools.hh\"\n#include \"Mu2eUtilities/inc/polyAtan2.hh\"\n// data\n#include \"RecoDataProducts/inc/ComboHit.hh\"\n#include \"RecoDataProducts/inc/StrawHitFlag.hh\"\n#include \"RecoDataProducts/inc/TimeCluster.hh\"\n#include \"RecoDataProducts/inc/CaloCluster.hh\"\n// tracking\n#include \"TrkReco/inc/TrkUtilities.hh\"\n#include \"TrkReco/inc/TrkTimeCalculator.hh\"\n// root\n#include \"TH1F.h\"\n// boost\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/weighted_median.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/weighted_mean.hpp>\n#include <boost/accumulators/statistics/weighted_variance.hpp>\n// C++\n#include <memory>\n#include <algorithm>\n#include <utility>\nusing namespace std;\nusing namespace boost::accumulators;\n\nnamespace {\n\n  struct TimeCluMVA\n  {\n    vector<Float_t> _pars;\n    Float_t& _dt;\n    Float_t& _dphi;\n    Float_t& _rho;\n    Float_t& _nsh;\n    Float_t& _plane;\n    Float_t& _werr;\n    Float_t& _wdist;\n    \n    TimeCluMVA() : _pars(7,0.0), _dt(_pars[0]), _dphi(_pars[1]), _rho(_pars[2]), _nsh(_pars[3]),\n     _plane(_pars[4]), _werr(_pars[5]), _wdist(_pars[6]){}\n//    TimeCluMVA() : _pars(5,0.0), _dt(_pars[0]), _nsh(_pars[1]),\n//      _plane(_pars[2]), _werr(_pars[3]), _wdist(_pars[4]){}\n  };\n}\n\nnamespace mu2e {\n   \n  class TimeClusterFinder : public art::EDProducer\n  {  \n    public:\n       \n\n        struct Config\n        {\n            using Name    = fhicl::Name;\n            using Comment = fhicl::Comment;\n            fhicl::Atom<art::InputTag>              comboHitCollection     {Name(\"ComboHitCollection\"),     Comment(\"ComboHit collection {Name\") };\n            fhicl::Atom<art::InputTag>              strawHitFlagCollection {Name(\"StrawHitFlagCollection\"), Comment(\"StrawHitFlag collection {Name\") };\n            fhicl::Atom<art::InputTag>              caloClusterCollection  {Name(\"CaloClusterCollection\"),  Comment(\"Calo cluster collection {Name\") };\n            fhicl::Table<MVATools::Config>          tcMVA                  {Name(\"ClusterMVA\"),             Comment(\"MVA for time cluster cleaning\") }; \n            fhicl::Table<MVATools::Config>          tcCaloMVA              {Name(\"ClusterCaloMVA\"),         Comment(\"MVA for time clsuter cleaning with calo\") }; \n            fhicl::Sequence<std::string>            hsel                   {Name(\"HitSelectionBits\"),       Comment(\"HitSelectionBits\") }; \n            fhicl::Sequence<std::string>            hbkg                   {Name(\"HitBackgroundBits\"),      Comment(\"HitBackgroundBits\") }; \n            fhicl::Atom<bool>                       usecc                  {Name(\"UseCaloCluster\"),         Comment(\"Use calorimeter cluster\") }; \n            fhicl::Atom<bool>                       useccpos               {Name(\"UseCaloClusterPosition\"), Comment(\"Use calorimeter cluster position\") }; \n            fhicl::Atom<float>                      ccmine                 {Name(\"CaloClusterMinE\"),        Comment(\"Minimum energy for calorimeter cluster\") }; \n            fhicl::Atom<float>                      ccweight               {Name(\"CaloClusterWeight\"),      Comment(\"Weight of cluster in tracker hits\") }; \n            fhicl::Table<TrkTimeCalculator::Config> ttcalc                 {Name(\"T0Calculator\"),           Comment(\"TimeTracker calculator config\") };  \n            fhicl::Atom<bool>                       testflag               {Name(\"TestFlag\"),               Comment(\"Test hit flags\") }; \n            fhicl::Atom<float>                      maxdt                  {Name(\"DtMax\"),                  Comment(\"Maximum delta time for hit in cluster\") }; \n            fhicl::Atom<unsigned>                   minnhits               {Name(\"MinNHits\"),               Comment(\"Minimum number of hits for cluster\") }; \n            fhicl::Atom<float>                      minkeepmva             {Name(\"MinKeepHitMVA\"),          Comment(\"Minimum MVA score to keep in cluster\") }; \n            fhicl::Atom<float>                      minaddmva              {Name(\"MinAddHitMVA\"),           Comment(\"Minimum MVA score to add in cluster\") }; \n            fhicl::Atom<float>                      maxdPhi                {Name(\"MaxdPhi\"),                Comment(\"Maximum delta Phi for hit to be in cluster\") }; \n            fhicl::Atom<float>                      tmin                   {Name(\"Tmin\"),                   Comment(\"Time histogram start\") }; \n            fhicl::Atom<float>                      tmax                   {Name(\"Tmax\"),                   Comment(\"Time histogram end\") }; \n            fhicl::Atom<float>                      tbin                   {Name(\"Tbin\"),                   Comment(\"Time histogram bin width\") }; \n            fhicl::Atom<float>                      pitch                  {Name(\"AveragePitch\"),           Comment(\"Average helix pitch (= dz/dflight, =sin(lambda)\") }; \n            fhicl::Atom<float>                      ymin                   {Name(\"Ymin\"),                   Comment(\"Minimum hit in time histo bin for peak\") }; \n            fhicl::Atom<bool>                       recover                {Name(\"RefineClusters\"),         Comment(\"Apply hit refining algorithm\") }; \n            fhicl::Atom<bool>                       refine                 {Name(\"PrefilterCluster\"),       Comment(\"Apply hit pre-filtering algorithm\") }; \n            fhicl::Atom<bool>                       preFilter              {Name(\"RecoverHits\"),            Comment(\"Apply hit recovery algorithm\") }; \n            fhicl::Atom<int>                        npeak                  {Name(\"PeakWidth\"),              Comment(\"Time Peak Width\") }; \n            fhicl::Atom<int>                        printfreq              {Name(\"printFrequency\"),         Comment(\"Print frequency\"), 100 }; \n            fhicl::Atom<int>                        debugLevel             {Name(\"debugLevel\"),             Comment(\"Debut Level\"), 0 }; \n        };\n\n        explicit TimeClusterFinder(const art::EDProducer::Table<Config>& config);\n\n        void beginJob() override;\n        void produce(art::Event& e) override;\n\n    \n    private:\n       typedef std::pair<Float_t,int> BinContent;\n       typedef std::vector<StrawHitIndex>::iterator ISH;\n       \n       int                                             _iev; \n       const art::ProductToken<ComboHitCollection>     _chToken;\n       const art::ProductToken<StrawHitFlagCollection> _shfToken;\n       const art::ProductToken<CaloClusterCollection>  _ccToken;      \n       const StrawHitFlagCollection* _shfcol;\n       const ComboHitCollection*     _chcol;\n       const CaloClusterCollection*  _cccol;\n       StrawHitFlag                  _hsel;\n       StrawHitFlag                  _hbkg;\n       MVATools                      _tcMVA;     \n       MVATools                      _tcCaloMVA; \n       bool                          _usecc, _useccpos;\n       float                         _ccmine, _ccwt;\n       TrkTimeCalculator             _ttcalc;\n       bool                          _testflag;\n       float                         _maxdt;\n       unsigned                      _minnhits;\n       float                         _minkeepmva, _minaddmva; \n       float                         _maxdPhi;\n       float                         _tmin, _tmax, _tbin;\n       float\t\t             _pitch; \n       float                         _ymin;\n       bool                          _refine;\n       bool                          _preFilter;\n       bool                          _recover;\n       int                           _npeak;\n       int                           _printfreq;\n       int                           _debug;    \n       TH1F                          _timespec;\n       TimeCluMVA                    _pmva; // input variables to TMVA for cluster cleaning\n\n\n      void findClusters(TimeClusterCollection& tccol);\n      void findCaloSeeds(TimeClusterCollection& tccol, art::Handle<CaloClusterCollection> const& ccH);\n      void fillTimeSpectrum();\n      void initCluster(TimeCluster& tc);\n      void prefilterCluster(TimeCluster& tc);\n      void recoverHits(TimeCluster& tc);\n      ISH  removeHit(TimeCluster& tc, ISH);\n      void addHit(TimeCluster& tc,size_t iadd);\n      void clusterMean(TimeCluster& tc);\n      void refineCluster(TimeCluster& tc);\n      void findPeaks(TimeClusterCollection& seeds);\n      void assignHits(TimeClusterCollection& tccol );\n      bool goodHit(const StrawHitFlag& flag) const;\n  };\n\n  \n  TimeClusterFinder::TimeClusterFinder(const art::EDProducer::Table<Config>& config) :\n     art::EDProducer{config},\n     _chToken      { consumes<ComboHitCollection>(      config().comboHitCollection()) },\n     _shfToken     { mayConsume<StrawHitFlagCollection>(config().strawHitFlagCollection()) },\n     _ccToken      { mayConsume<CaloClusterCollection>( config().caloClusterCollection()) },\n     _hsel         ( config().hsel()),\n     _hbkg         ( config().hbkg()),\n     _tcMVA        ( config().tcMVA()),\n     _tcCaloMVA    ( config().tcCaloMVA()),\n     _usecc        ( config().usecc()),\n     _useccpos     ( config().useccpos()),\n     _ccmine       ( config().ccmine()),\n     _ccwt         ( config().ccweight()),\n     _ttcalc       ( config().ttcalc()),\n     _testflag     ( config().testflag()),\n     _maxdt        ( config().maxdt()),\n     _minnhits     ( config().minnhits()),\n     _minkeepmva   ( config().minkeepmva()),\n     _minaddmva    ( config().minaddmva()),\n     _maxdPhi      ( config().maxdPhi()),\n     _tmin         ( config().tmin()),\n     _tmax         ( config().tmax()),\n     _tbin         ( config().tbin()),\n     _pitch        ( config().pitch()), \n     _ymin         ( config().ymin()),\n     _refine       ( config().refine()),          \n     _preFilter    ( config().preFilter()),        \n     _recover      ( config().recover()),      \n     _npeak        ( config().npeak()), \n     _printfreq    ( config().printfreq()),\n     _debug        ( config().debugLevel())\n    {\n        unsigned nbins = (unsigned)rint((_tmax-_tmin)/_tbin);\n        _timespec = TH1F(\"timespec\",\"time spectrum\",nbins,_tmin,_tmax);\n        produces<TimeClusterCollection>();\n    }\n\n  void TimeClusterFinder::beginJob() {\n    _tcMVA.initMVA();\n    _tcCaloMVA.initMVA();\n    if (_debug > 0)\n    {\n      std::cout << \"TimeClusterFinder MVA : \" << std::endl;\n      _tcMVA.showMVA();\n      std::cout << \"TimeClusterFinder Calo MVA : \" << std::endl;\n      _tcCaloMVA.showMVA();\n    }\n  }\n\n\n  //--------------------------------------------------------------------------------------------------------------\n  void TimeClusterFinder::produce(art::Event & event ){\n    _iev = event.id().event();\n\n    if (_debug > 0 && (_iev%_printfreq)==0) std::cout<<\"TimeClusterFinder: event=\"<<_iev<<std::endl;\n\n    auto const& chH = event.getValidHandle(_chToken);\n    _chcol = chH.product();\n\n    art::Handle<CaloClusterCollection> ccH{}; // need to cache for later Ptr creation \n    if(_usecc){\n      ccH = event.getHandle<CaloClusterCollection>(_ccToken);\n      _cccol = ccH.product();\n    }\n\n    if(_testflag){\n      auto shfH = event.getValidHandle(_shfToken);\n      _shfcol = shfH.product();\n      if(_shfcol->size() != _chcol->size())\n\tthrow cet::exception(\"RECO\")<<\"TimeClusterFinder: inconsistent flag collection length \" << endl;\n    }\n\n    std::unique_ptr<TimeClusterCollection> tccol(new TimeClusterCollection);\n    // If requested, use calo clusters to for time cluster seeds\n    if (_usecc) findCaloSeeds(*tccol,ccH);\n    // find all the hit clusters\n    findClusters(*tccol);\n\n    if (_debug > 0) std::cout << \"Found \" << tccol->size() << \" Time Clusters \" << std::endl;\n\n    if (_debug > 1){\n      for(auto const& tc : *tccol) {\n\tstd::cout << \"Time Cluster time = \" << tc.t0().t0() << \" +- \" << tc.t0().t0Err()\n\t  << \" position = \" << tc._pos << std::endl;\n\tif(_debug > 3){\n\t  for (auto shi : tc._strawHitIdxs ) {\n\t    std::cout << \"Time Cluster hit at index \" << shi << std::endl;\n\t  }\n\t}\n      }\n    }\n    event.put(std::move(tccol));\n  }\n\n\n  //--------------------------------------------------------------------------------------------------------------\n  void TimeClusterFinder::findClusters(TimeClusterCollection& tccol) {\n    // find seed from hits\n    fillTimeSpectrum();\n    findPeaks(tccol);\n    // associate hits to seeds\n    assignHits(tccol);\n    // loop over seeds and fill/refine information\n    auto itc = tccol.begin();\n    while(itc != tccol.end()){\n      TimeCluster& tc = *itc;\n      initCluster(tc);\n      if (_preFilter) prefilterCluster(tc);\n      if( tc.nStrawHits() >= _minnhits) {\n\tclusterMean(tc);\n\tif (_refine) refineCluster(tc);\n\tif (_recover) recoverHits(tc);\n      }\n      if (tc.nStrawHits() < _minnhits) {\n\titc = tccol.erase(itc);\n      } else\n\t++itc;\n      //std::cout<<\"Collection size final\"<<tc._strawHitIdxs.size()<<std::endl;\n    }\n    // debug test of histogram\n    if (_debug > 2) {\n      art::ServiceHandle<art::TFileService> tfs;\n      TH1F* tspec = tfs->make<TH1F>(_timespec);\n      char name[40];\n      char title[100];\n      snprintf(name,40,\"tspec_%i\",_iev);\n      snprintf(title,100,\"time spectrum event %i;nsec\",_iev);\n      tspec->SetNameTitle(name,title);\n    }\n  }\n\n  void TimeClusterFinder::findCaloSeeds(TimeClusterCollection& tccol, art::Handle<CaloClusterCollection>const& ccH) {\n    for(size_t icalo=0; icalo < _cccol->size(); ++icalo){\n      auto const& calo = (*_cccol)[icalo];\n      if (calo.energyDep() > _ccmine){\n\tTimeCluster tc;\n\ttc._t0 = TrkT0(_ttcalc.caloClusterTime(calo,_pitch), _ttcalc.caloClusterTimeErr());\n\ttc._caloCluster = art::Ptr<CaloCluster>(ccH,icalo);\n\ttccol.push_back(tc);\n      }\n    }\n  }\n\n  //--------------------------------------------------------------------------------------------------------------\n  void TimeClusterFinder::fillTimeSpectrum() {\n    _timespec.Reset();\n    for (unsigned istr=0; istr<_chcol->size();++istr) {\n      if (_testflag && !goodHit((*_shfcol)[istr])) continue;\n      ComboHit const& ch = (*_chcol)[istr];\n      float time = _ttcalc.comboHitTime((*_chcol)[istr],_pitch);\n      _timespec.Fill(time,ch.nStrawHits());\n    }\n  }\n\n  void TimeClusterFinder::assignHits(TimeClusterCollection& tccol ) {\n  // assign hits to the closest time peak\n    for(size_t istr=0; istr<_chcol->size(); ++istr) {\n      if ((!_testflag) || goodHit((*_shfcol)[istr])) {\n\tComboHit const& ch =(*_chcol)[istr];\n\tfloat time = _ttcalc.comboHitTime(ch,_pitch);\n\tfloat mindt(1e5);\n\tauto besttc = tccol.end();\n\t// find the closest seed (if any)\n\tfor (auto itc = tccol.begin(); itc != tccol.end(); ++itc) {\n\t  float dt = fabs(time - itc->_t0._t0);\n\t  // make an absolute cut, including error on the cluster t0\n\t  if (dt < _maxdt+itc->_t0._t0err && dt < mindt){\n\t    mindt = dt;\n\t    besttc = itc;\n\t  }\n\t}\n\tif(besttc != tccol.end())\n\t  besttc->_strawHitIdxs.push_back(istr);\n      }\n    }\n  }\n\n  //--------------------------------------------------------------------------------------------------------------\n  void TimeClusterFinder::findPeaks(TimeClusterCollection& tccol) {\n    int nbins = _timespec.GetNbinsX()+1;\n    std::vector<bool> alreadyUsed(nbins,false);\n    // blank out bins around input times (from calo clusters)\n    for(auto const& tc : tccol ){ \n      int ibin = _timespec.FindBin(tc._t0._t0);\n      for(int jbin = std::max(1,ibin-_npeak);jbin < std::min(nbins,ibin+_npeak+1); ++jbin)\n\talreadyUsed[jbin] = true;\n    }\n    // loop over spectrum to find peaks \n    std::vector<BinContent> bcv;\n    for (int ibin=1;ibin < nbins; ++ibin)\n      if (_timespec.GetBinContent(ibin) >= _ymin) bcv.push_back(make_pair(_timespec.GetBinContent(ibin),ibin));\n    std::sort(bcv.begin(),bcv.end(),[](const BinContent& x, const BinContent& y){return x.first > y.first;});\n\n    for (const auto& bc : bcv) {\n      if (alreadyUsed[bc.second]) continue;\n      float nsh(0.0);\n      float t0(0.0);\n      for (int ibin = std::max(1,bc.second-_npeak);ibin < std::min(nbins,bc.second+_npeak+1); ++ibin) {\n\tnsh += _timespec.GetBinContent(ibin);\n\tt0 += _timespec.GetBinCenter(ibin)*_timespec.GetBinContent(ibin);\n\talreadyUsed[ibin] = true;\n      }\n      t0 /= nsh;\n      // if the count is enough, create a cluster\n      if (nsh > _minnhits){\n\tTimeCluster tc;\n\ttc._t0 = TrkT0(t0,_tbin*0.5); // bin width\n\ttc._nsh = nsh;\n\ttccol.push_back(tc);\n      }    \n    }\n  }\n\n  //--------------------------------------------------------------------------------------------------------------\n  void TimeClusterFinder::initCluster(TimeCluster& tc) {\n    // use medians to initialize robustly\n    accumulator_set<float, stats<tag::min > > tmin;\n    accumulator_set<float, stats<tag::max > > tmax;\n    accumulator_set<float, stats<tag::weighted_median(with_p_square_quantile) >, float > tacc, xacc, yacc, zacc;\n\n    unsigned nstrs = tc._strawHitIdxs.size();\n    tc._nsh = 0;\n    for(auto ish :tc._strawHitIdxs) {\n      if (_testflag && !goodHit((*_shfcol)[ish])) continue;\n      ComboHit const& ch = (*_chcol)[ish];\n      unsigned nsh = ch.nStrawHits();\n      tc._nsh += nsh;\n      const XYZVec& pos = ch.pos();\n      float htime = _ttcalc.comboHitTime(ch,_pitch);\n      float hwt = ch.nStrawHits();\n      tmin(htime);\n      tmax(htime);\n      tacc(htime,weight=hwt);\n      xacc(pos.x(),weight=hwt);\n      yacc(pos.y(),weight=hwt);\n      zacc(pos.z(),weight=hwt);\n    }\n\n    if (tc.hasCaloCluster()) {\n    // don't update t0 if there's an assigned calo cluster\n      if(_useccpos){\n\txacc(tc._caloCluster->cog3Vector().x(),weight=_ccwt);\n\tyacc(tc._caloCluster->cog3Vector().y(),weight=_ccwt);\n      }\n    } else {\n      static float invsqrt12(1.0/sqrt(12.0));\n      tc._t0._t0 = extract_result<tag::weighted_median>(tacc);\n      tc._t0._t0err = ( boost::accumulators::extract::max(tmax)-boost::accumulators::extract::min(tmin))*invsqrt12/sqrt(nstrs);\n    }\n    //\n    tc._pos = XYZVec(extract_result<tag::weighted_median>(xacc),\n        extract_result<tag::weighted_median>(yacc),\n        extract_result<tag::weighted_median>(zacc));\n\n    if (_debug > 0) std::cout<<\"Init time peak \"<<tc._t0._t0<<std::endl;\n  }\n\n  // prefilter based on a rough hemisphere cut and the initial robust position\n  void TimeClusterFinder::prefilterCluster(TimeCluster& tc){\n    bool changed(true);\n    while (changed) {\n      changed = false;\n      float pphi = polyAtan2( tc._pos.y(), tc._pos.x());\n      auto iworst = tc._strawHitIdxs.end();\n      float maxadPhi(_maxdPhi);\n      for( auto ips = tc._strawHitIdxs.begin(); ips != tc._strawHitIdxs.end(); ++ips){\n\tComboHit const& ch = (*_chcol)[*ips];\n\tfloat phi   = polyAtan2(ch.pos().y(), ch.pos().x()); \n\tfloat dphi  = Angles::deltaPhi(phi,pphi);\n\tfloat adphi = std::abs(dphi);\n\tif(adphi > maxadPhi ){\n\t  iworst = ips;\n\t  maxadPhi = adphi;\n\t}\n      }\n      if( iworst != tc._strawHitIdxs.end()){\n\tchanged = true;\n\tremoveHit(tc,iworst);\n      }\n    }\n  }\n\n  void TimeClusterFinder::recoverHits(TimeCluster& tc){\n    bool changed(true);\n    while (changed) {\n      changed = false;\n      float pphi = polyAtan2(tc._pos.y(), tc._pos.x());\n      for(size_t ich=0;ich < _chcol->size(); ++ich){\n\tif ((!_testflag) || goodHit((*_shfcol)[ich])) {\n\t  if(std::find(tc._strawHitIdxs.begin(),tc._strawHitIdxs.end(),ich) == tc._strawHitIdxs.end()){\n\t    ComboHit const& ch = (*_chcol)[ich];\n\t    float cht = _ttcalc.comboHitTime(ch,_pitch);\n\t    _pmva._dt = fabs(cht - tc._t0._t0);\n\t    if(_pmva._dt < _maxdt+tc._t0._t0err){\n\t      float phi = polyAtan2(ch.pos().y(), ch.pos().x());//ch.phi();\n\t      float dphi = fabs(Angles::deltaPhi(phi,pphi));\n\t      if(dphi < _maxdPhi){ \n\t\t_pmva._dphi = dphi;\n\t\t_pmva._rho = ch.pos().Perp2();\n\t\t_pmva._nsh = ch.nStrawHits();\n\t\t_pmva._plane = ch.strawId().plane();\n\t\t_pmva._werr = ch.wireRes();\n\t\t_pmva._wdist = fabs(ch.wireDist());\n\n\t\tfloat mvaout(-1.0);\n\t\tif (tc.hasCaloCluster())\n\t\t  mvaout = _tcCaloMVA.evalMVA(_pmva._pars);\n\t\telse\n\t\t  mvaout = _tcMVA.evalMVA(_pmva._pars);\n\t\tif (mvaout > _minaddmva) {\n\t\t  addHit(tc,ich);\n\t\t  changed = true;\n\t\t}\n\t      }\n\t    }\n\t  }\n\t}\n      }\n    }\n  }\n\n  std::vector<StrawHitIndex>::iterator TimeClusterFinder::removeHit(TimeCluster& tc, ISH iworst) {\n    ComboHit const& ch = (*_chcol)[*iworst];\n    unsigned nsh = ch.nStrawHits();\n    float denom = float(tc._nsh - nsh);\n    // update time cluster properties \n    if(!tc.hasCaloCluster()){\n      float cht = _ttcalc.comboHitTime(ch,_pitch);\n      float newt0  = (tc._t0._t0*tc._nsh - cht*nsh)/denom;\n      tc._t0._t0err = sqrt((tc._t0._t0err*tc._t0._t0err*tc._nsh - (cht-newt0)*(cht-tc._t0._t0)*nsh )/denom);\n      tc._t0._t0 = newt0;\n    }\n    tc._pos.SetX((tc._pos.x()*tc._nsh - ch.pos().x()*nsh)/denom);\n    tc._pos.SetY((tc._pos.y()*tc._nsh - ch.pos().x()*nsh)/denom);\n    tc._pos.SetZ((tc._pos.z()*tc._nsh - ch.pos().x()*nsh)/denom);\n    tc._nsh -= nsh;\n    return tc._strawHitIdxs.erase(iworst);\n  }\n\n  void TimeClusterFinder::addHit(TimeCluster& tc,size_t iadd) {\n    ComboHit const& ch = (*_chcol)[iadd];\n    unsigned nsh = ch.nStrawHits();\n    float denom = float(tc._nsh + nsh);\n    // update time cluster properties \n    if(!tc.hasCaloCluster()){\n      float cht = _ttcalc.comboHitTime(ch,_pitch);\n      float newt0  = (tc._t0._t0*tc._nsh + cht*nsh)/denom;\n      tc._t0._t0err = sqrt((tc._t0._t0err*tc._t0._t0err*tc._nsh + (cht-newt0)*(cht-tc._t0._t0)*nsh )/denom);\n      tc._t0._t0 = newt0;\n    }\n    tc._pos.SetX((tc._pos.x()*tc._nsh + ch.pos().x()*nsh)/denom);\n    tc._pos.SetY((tc._pos.y()*tc._nsh + ch.pos().x()*nsh)/denom);\n    tc._pos.SetZ((tc._pos.z()*tc._nsh + ch.pos().x()*nsh)/denom);\n    tc._nsh += nsh;\n    tc._strawHitIdxs.push_back(iadd);\n  }\n\n  void TimeClusterFinder::clusterMean(TimeCluster& tc) {\n    // compute properties using weighted mean\n    accumulator_set<float, stats<tag::weighted_variance(lazy)>, float > terr;\n    accumulator_set<float, stats<tag::weighted_mean >,float > xacc, yacc, zacc;\n    for(StrawHitIndex ish : tc._strawHitIdxs) {\n      ComboHit const& ch = (*_chcol)[ish];\n      float hwt = ch.nStrawHits();\n      float cht = _ttcalc.comboHitTime(ch,_pitch);\n      terr(cht,weight=hwt);\n      xacc(ch.pos().x(),weight=hwt);\n      yacc(ch.pos().y(),weight=hwt);\n      zacc(ch.pos().z(),weight=hwt);\n    }\n    if (tc.hasCaloCluster()) {\n      if(_useccpos){\n\txacc(tc._caloCluster->cog3Vector().x(),weight=_ccwt);\n\tyacc(tc._caloCluster->cog3Vector().y(),weight=_ccwt);\n      }\n    } else {\n      tc._t0._t0 = extract_result<tag::weighted_mean>(terr);\n      tc._t0._t0err = sqrtf(std::max(double(1.0),2.0*extract_result<tag::weighted_variance(lazy)>(terr))/extract_result<tag::count>(terr));\n    }\n    \n    tc._pos = XYZVec(extract_result<tag::weighted_mean>(xacc),\n\textract_result<tag::weighted_mean>(yacc),\n\textract_result<tag::weighted_mean>(zacc));\n  } \n\n  void TimeClusterFinder::refineCluster(TimeCluster& tc) {\n    // mva filtering; remove worst hit iteratively\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      auto iworst = tc._strawHitIdxs.end();\n      float worstmva(100.0);\n      float pphi = polyAtan2(tc._pos.y(), tc._pos.x());\n      for (auto ips=tc._strawHitIdxs.begin();ips != tc._strawHitIdxs.end();++ips) {\n        ComboHit const& ch = (*_chcol)[*ips];\n        float cht = _ttcalc.comboHitTime(ch,_pitch);\n\n        _pmva._dt = fabs(cht - tc._t0._t0);\n        float phi = polyAtan2(ch.pos().y(), ch.pos().x());//ch.phi();\n        float dphi = Angles::deltaPhi(phi,pphi);\n        _pmva._dphi = fabs(dphi);\n\t_pmva._rho = ch.pos().Perp2();\n\t_pmva._nsh = ch.nStrawHits();\n\t_pmva._plane = ch.strawId().plane();\n\t_pmva._werr = ch.wireRes();\n\t_pmva._wdist = fabs(ch.wireDist());\n\n\tfloat mvaout(-1.0);\n\tif (tc.hasCaloCluster())\n\t   mvaout = _tcCaloMVA.evalMVA(_pmva._pars);\n\telse\n\t  mvaout = _tcMVA.evalMVA(_pmva._pars);\n\tif (mvaout < worstmva) {\n\t  worstmva = mvaout;\n\t  iworst = ips;\n        }\n      }\n\n      if (worstmva < _minkeepmva) {\n        changed = true;\n\tremoveHit(tc,iworst);\n      }\n    }\n  }\n\n  bool TimeClusterFinder::goodHit(const StrawHitFlag& flag) const\n  {\n    return flag.hasAllProperties(_hsel) && !flag.hasAnyProperty(_hbkg);\n  }\n\n}\n\nusing mu2e::TimeClusterFinder;\nDEFINE_ART_MODULE(TimeClusterFinder);\n", "meta": {"hexsha": "13e89d4a49bf319ec1c1bc6f74d04bc1184af623", "size": 24732, "ext": "cc", "lang": "C++", "max_stars_repo_path": "TrkPatRec/src/TimeClusterFinder_module.cc", "max_stars_repo_name": "lborrel/Offline", "max_stars_repo_head_hexsha": "db9f647bad3c702171ab5ffa5ccc04c82b3f8984", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-23T22:09:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T22:09:28.000Z", "max_issues_repo_path": "TrkPatRec/src/TimeClusterFinder_module.cc", "max_issues_repo_name": "lborrel/Offline", "max_issues_repo_head_hexsha": "db9f647bad3c702171ab5ffa5ccc04c82b3f8984", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 125.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T13:44:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-15T21:29:57.000Z", "max_forks_repo_path": "TrkPatRec/src/TimeClusterFinder_module.cc", "max_forks_repo_name": "lborrel/Offline", "max_forks_repo_head_hexsha": "db9f647bad3c702171ab5ffa5ccc04c82b3f8984", "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.22, "max_line_length": 170, "alphanum_fraction": 0.5740740741, "num_tokens": 6931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.19468373054357999}}
{"text": "#include <trajopt_utils/macros.h>\nTRAJOPT_IGNORE_WARNINGS_PUSH\n#include <boost/format.hpp>\n#include <cmath>\n#include <cstdio>\nTRAJOPT_IGNORE_WARNINGS_POP\n\n#include <trajopt_sco/expr_ops.hpp>\n#include <trajopt_sco/modeling.hpp>\n#include <trajopt_sco/optimizers.hpp>\n#include <trajopt_sco/sco_common.hpp>\n#include <trajopt_sco/solver_interface.hpp>\n#include <trajopt_utils/logging.hpp>\n#include <trajopt_utils/macros.h>\n#include <trajopt_utils/stl_to_string.hpp>\n\nnamespace sco\n{\nstd::ostream& operator<<(std::ostream& o, const OptResults& r)\n{\n  o << \"Optimization results:\" << std::endl\n    << \"status: \" << statusToString(r.status) << std::endl\n    << \"cost values: \" << util::Str(r.cost_vals) << std::endl\n    << \"constraint violations: \" << util::Str(r.cnt_viols) << std::endl\n    << \"n func evals: \" << r.n_func_evals << std::endl\n    << \"n qp solves: \" << r.n_qp_solves << std::endl;\n  return o;\n}\n\n//////////////////////////////////////////////////\n////////// private utility functions for  sqp /////////\n//////////////////////////////////////////////////\n\nstatic DblVec evaluateCosts(const std::vector<CostPtr>& costs, const DblVec& x)\n{\n  DblVec out(costs.size());\n  for (size_t i = 0; i < costs.size(); ++i)\n  {\n    out[i] = costs[i]->value(x);\n  }\n  return out;\n}\nstatic DblVec evaluateConstraintViols(const std::vector<ConstraintPtr>& constraints, const DblVec& x)\n{\n  DblVec out(constraints.size());\n  for (size_t i = 0; i < constraints.size(); ++i)\n  {\n    out[i] = constraints[i]->violation(x);\n  }\n  return out;\n}\nstatic std::vector<ConvexObjectivePtr> convexifyCosts(const std::vector<CostPtr>& costs, const DblVec& x, Model* model)\n{\n  std::vector<ConvexObjectivePtr> out(costs.size());\n  for (size_t i = 0; i < costs.size(); ++i)\n  {\n    out[i] = costs[i]->convex(x, model);\n  }\n  return out;\n}\nstatic std::vector<ConvexConstraintsPtr> convexifyConstraints(const std::vector<ConstraintPtr>& cnts, const DblVec& x,\n                                                              Model* model)\n{\n  std::vector<ConvexConstraintsPtr> out(cnts.size());\n  for (size_t i = 0; i < cnts.size(); ++i)\n  {\n    out[i] = cnts[i]->convex(x, model);\n  }\n  return out;\n}\n\nDblVec evaluateModelCosts(const std::vector<ConvexObjectivePtr>& costs, const DblVec& x)\n{\n  DblVec out(costs.size());\n  for (size_t i = 0; i < costs.size(); ++i)\n  {\n    out[i] = costs[i]->value(x);\n  }\n  return out;\n}\nDblVec evaluateModelCntViols(const std::vector<ConvexConstraintsPtr>& cnts, const DblVec& x)\n{\n  DblVec out(cnts.size());\n  for (size_t i = 0; i < cnts.size(); ++i)\n  {\n    out[i] = cnts[i]->violation(x);\n  }\n  return out;\n}\n\nstatic std::vector<std::string> getCostNames(const std::vector<CostPtr>& costs)\n{\n  std::vector<std::string> out(costs.size());\n  for (size_t i = 0; i < costs.size(); ++i)\n    out[i] = costs[i]->name();\n  return out;\n}\nstatic std::vector<std::string> getCntNames(const std::vector<ConstraintPtr>& cnts)\n{\n  std::vector<std::string> out(cnts.size());\n  for (size_t i = 0; i < cnts.size(); ++i)\n    out[i] = cnts[i]->name();\n  return out;\n}\n\nvoid printCostInfo(const DblVec& old_cost_vals, const DblVec& model_cost_vals, const DblVec& new_cost_vals,\n                   const DblVec& old_cnt_vals, const DblVec& model_cnt_vals, const DblVec& new_cnt_vals,\n                   const std::vector<std::string>& cost_names, const std::vector<std::string>& cnt_names,\n                   double merit_coeff)\n{\n  std::printf(\"%15s | %10s | %10s | %10s | %10s\\n\", \"\", \"oldexact\", \"dapprox\", \"dexact\", \"ratio\");\n  std::printf(\"%15s | %10s---%10s---%10s---%10s\\n\", \"COSTS\", \"----------\", \"----------\", \"----------\", \"----------\");\n  for (size_t i = 0; i < old_cost_vals.size(); ++i)\n  {\n    double approx_improve = old_cost_vals[i] - model_cost_vals[i];\n    double exact_improve = old_cost_vals[i] - new_cost_vals[i];\n    if (fabs(approx_improve) > 1e-8)\n      std::printf(\"%15s | %10.3e | %10.3e | %10.3e | %10.3e\\n\", cost_names[i].c_str(), old_cost_vals[i], approx_improve,\n                  exact_improve, exact_improve / approx_improve);\n    else\n      std::printf(\"%15s | %10.3e | %10.3e | %10.3e | %10s\\n\", cost_names[i].c_str(), old_cost_vals[i], approx_improve,\n                  exact_improve, \"  ------  \");\n  }\n  if (cnt_names.size() == 0)\n    return;\n  std::printf(\"%15s | %10s---%10s---%10s---%10s\\n\", \"CONSTRAINTS\", \"----------\", \"----------\", \"----------\", \"---------\"\n                                                                                                             \"-\");\n  for (size_t i = 0; i < old_cnt_vals.size(); ++i)\n  {\n    double approx_improve = old_cnt_vals[i] - model_cnt_vals[i];\n    double exact_improve = old_cnt_vals[i] - new_cnt_vals[i];\n    if (fabs(approx_improve) > 1e-8)\n      std::printf(\"%15s | %10.3e | %10.3e | %10.3e | %10.3e\\n\", cnt_names[i].c_str(), merit_coeff * old_cnt_vals[i],\n                  merit_coeff * approx_improve, merit_coeff * exact_improve, exact_improve / approx_improve);\n    else\n      std::printf(\"%15s | %10.3e | %10.3e | %10.3e | %10s\\n\", cnt_names[i].c_str(), merit_coeff * old_cnt_vals[i],\n                  merit_coeff * approx_improve, merit_coeff * exact_improve, \"  ------  \");\n  }\n}\n\n// todo: use different coeffs for each constraint\nstd::vector<ConvexObjectivePtr> cntsToCosts(const std::vector<ConvexConstraintsPtr>& cnts, double err_coeff,\n                                            Model* model)\n{\n  std::vector<ConvexObjectivePtr> out;\n  for (const ConvexConstraintsPtr& cnt : cnts)\n  {\n    ConvexObjectivePtr obj(new ConvexObjective(model));\n    for (const AffExpr& aff : cnt->eqs_)\n    {\n      obj->addAbs(aff, err_coeff);\n    }\n    for (const AffExpr& aff : cnt->ineqs_)\n    {\n      obj->addHinge(aff, err_coeff);\n    }\n    out.push_back(obj);\n  }\n  return out;\n}\n\nvoid Optimizer::addCallback(const Callback& cb)\n{\n  callbacks_.push_back(cb);\n}\nvoid Optimizer::callCallbacks()\n{\n  for (unsigned i = 0; i < callbacks_.size(); ++i)\n  {\n    callbacks_[i](prob_.get(), results_);\n  }\n}\n\nvoid Optimizer::initialize(const DblVec& x)\n{\n  if (!prob_)\n    PRINT_AND_THROW(\"need to set the problem before initializing\");\n  if (prob_->getVars().size() != x.size())\n    PRINT_AND_THROW(boost::format(\"initialization vector has wrong length. expected %i got %i\") %\n                    prob_->getVars().size() % x.size());\n  results_.clear();\n  results_.x = x;\n}\n\nBasicTrustRegionSQPParameters::BasicTrustRegionSQPParameters()\n{\n  improve_ratio_threshold = 0.25;\n  min_trust_box_size = 1e-4;\n  min_approx_improve = 1e-4;\n  min_approx_improve_frac = -INFINITY;\n  max_iter = 50;\n  trust_shrink_ratio = 0.1;\n  trust_expand_ratio = 1.5;\n  cnt_tolerance = 1e-4;\n  max_merit_coeff_increases = 5;\n  merit_coeff_increase_ratio = 10;\n  max_time = INFINITY;\n  merit_error_coeff = 10;\n  trust_box_size = 1e-1;\n}\n\nBasicTrustRegionSQP::BasicTrustRegionSQP()\n{\n}\nBasicTrustRegionSQP::BasicTrustRegionSQP(OptProbPtr prob)\n{\n  setProblem(prob);\n}\nvoid BasicTrustRegionSQP::setProblem(OptProbPtr prob)\n{\n  Optimizer::setProblem(prob);\n  model_ = prob->getModel();\n}\n\nvoid BasicTrustRegionSQP::adjustTrustRegion(double ratio)\n{\n  param_.trust_box_size *= ratio;\n}\nvoid BasicTrustRegionSQP::setTrustBoxConstraints(const DblVec& x)\n{\n  const VarVector& vars = prob_->getVars();\n  assert(vars.size() == x.size());\n  const DblVec &lb = prob_->getLowerBounds(), ub = prob_->getUpperBounds();\n  DblVec lbtrust(x.size()), ubtrust(x.size());\n  for (size_t i = 0; i < x.size(); ++i)\n  {\n    lbtrust[i] = fmax(x[i] - param_.trust_box_size, lb[i]);\n    ubtrust[i] = fmin(x[i] + param_.trust_box_size, ub[i]);\n  }\n  model_->setVarBounds(vars, lbtrust, ubtrust);\n}\n\n#if 0\nstruct MultiCritFilter {\n  /**\n   * Checks if you're making an improvement on a multidimensional objective\n   * Given a set of past error vectors, the improvement is defined as\n   * min_{olderrvec in past_err_vecs} | olderrvec - errvec |^+\n   */\n  vector<DblVec> errvecs;\n  double improvement(const DblVec& errvec) {\n    double leastImprovement=INFINITY;\n    for (const DblVec& olderrvec : errvecs) {\n      double improvement=0;\n      for (int i=0; i < errvec.size(); ++i) improvement += pospart(olderrvec[i] - errvec[i]);\n      leastImprovement = fmin(leastImprovement, improvement);\n    }\n    return leastImprovement;\n  }\n  void insert(const DblVec& x) {errvecs.push_back(x);}\n  bool empty() {return errvecs.size() > 0;}\n};\n#endif\n\nOptStatus BasicTrustRegionSQP::optimize()\n{\n  std::vector<std::string> cost_names = getCostNames(prob_->getCosts());\n  std::vector<ConstraintPtr> constraints = prob_->getConstraints();\n  std::vector<std::string> cnt_names = getCntNames(constraints);\n\n  if (results_.x.size() == 0)\n    PRINT_AND_THROW(\"you forgot to initialize!\");\n  if (!prob_)\n    PRINT_AND_THROW(\"you forgot to set the optimization problem\");\n\n  results_.x = prob_->getClosestFeasiblePoint(results_.x);\n\n  assert(results_.x.size() == prob_->getVars().size());\n  assert(prob_->getCosts().size() > 0 || constraints.size() > 0);\n\n  OptStatus retval = INVALID;\n\n  for (int merit_increases = 0; merit_increases < param_.max_merit_coeff_increases; ++merit_increases)\n  { /* merit adjustment loop */\n    for (int iter = 1;; ++iter)\n    { /* sqp loop */\n      callCallbacks();\n\n      LOG_DEBUG(\"current iterate: %s\", CSTR(results_.x));\n      LOG_INFO(\"iteration %i\", iter);\n\n      // speedup: if you just evaluated the cost when doing the line search, use\n      // that\n      if (results_.cost_vals.empty() && results_.cnt_viols.empty())\n      {  // only happens on the first iteration\n        results_.cnt_viols = evaluateConstraintViols(constraints, results_.x);\n        results_.cost_vals = evaluateCosts(prob_->getCosts(), results_.x);\n        assert(results_.n_func_evals == 0);\n        ++results_.n_func_evals;\n      }\n\n      // DblVec new_cnt_viols = evaluateConstraintViols(constraints, results_.x);\n      // DblVec new_cost_vals = evaluateCosts(prob_->getCosts(), results_.x);\n      // cout << \"costs\" << endl;\n      // for (int i=0; i < new_cnt_viols.size(); ++i) {\n      //   cout << cnt_names[i] << \" \" << new_cnt_viols[i] -\n      //   results_.cnt_viols[i] << endl;\n      // }\n      // for (int i=0; i < new_cost_vals.size(); ++i) {\n      //   cout << cost_names[i] << \" \" << new_cost_vals[i] -\n      //   results_.cost_vals[i] << endl;\n      // }\n\n      std::vector<ConvexObjectivePtr> cost_models = convexifyCosts(prob_->getCosts(), results_.x, model_.get());\n      std::vector<ConvexConstraintsPtr> cnt_models = convexifyConstraints(constraints, results_.x, model_.get());\n      std::vector<ConvexObjectivePtr> cnt_cost_models = cntsToCosts(cnt_models, param_.merit_error_coeff, model_.get());\n      model_->update();\n      for (ConvexObjectivePtr& cost : cost_models)\n        cost->addConstraintsToModel();\n      for (ConvexObjectivePtr& cost : cnt_cost_models)\n        cost->addConstraintsToModel();\n      model_->update();\n      QuadExpr objective;\n      for (ConvexObjectivePtr& co : cost_models)\n        exprInc(objective, co->quad_);\n      for (ConvexObjectivePtr& co : cnt_cost_models)\n        exprInc(objective, co->quad_);\n\n      //    objective = cleanupExpr(objective);\n      model_->setObjective(objective);\n\n      //    if (logging::filter() >= IPI_LEVEL_DEBUG) {\n      //      DblVec model_cost_vals;\n      //      for (ConvexObjectivePtr& cost : cost_models) {\n      //        model_cost_vals.push_back(cost->value(x));\n      //      }\n      //      LOG_DEBUG(\"model costs %s should equalcosts  %s\",\n      //      printer(model_cost_vals), printer(cost_vals));\n      //    }\n\n      while (param_.trust_box_size >= param_.min_trust_box_size)\n      {\n        setTrustBoxConstraints(results_.x);\n        CvxOptStatus status = model_->optimize();\n        ++results_.n_qp_solves;\n        if (status != CVX_SOLVED)\n        {\n          LOG_ERROR(\"convex solver failed! set TRAJOPT_LOG_THRESH=DEBUG to see \"\n                    \"solver output. saving model to /tmp/fail.lp and IIS to \"\n                    \"/tmp/fail.ilp\");\n          model_->writeToFile(\"/tmp/fail.lp\");\n          model_->writeToFile(\"/tmp/fail.ilp\");\n          retval = OPT_FAILED;\n          goto cleanup;\n        }\n        DblVec model_var_vals = model_->getVarValues(model_->getVars());\n\n        DblVec model_cost_vals = evaluateModelCosts(cost_models, model_var_vals);\n        DblVec model_cnt_viols = evaluateModelCntViols(cnt_models, model_var_vals);\n\n        // the n variables of the OptProb happen to be the first n variables in\n        // the Model\n        DblVec new_x(model_var_vals.begin(), model_var_vals.begin() + static_cast<long int>(results_.x.size()));\n\n        if (util::GetLogLevel() >= util::LevelDebug)\n        {\n          DblVec cnt_costs1 = evaluateModelCosts(cnt_cost_models, model_var_vals);\n          DblVec cnt_costs2 = model_cnt_viols;\n          for (unsigned i = 0; i < cnt_costs2.size(); ++i)\n            cnt_costs2[i] *= param_.merit_error_coeff;\n          LOG_DEBUG(\"SHOULD BE ALMOST THE SAME: %s ?= %s\", CSTR(cnt_costs1), CSTR(cnt_costs2));\n          // not exactly the same because cnt_costs1 is based on aux variables,\n          // but they might not be at EXACTLY the right value\n        }\n\n        DblVec new_cost_vals = evaluateCosts(prob_->getCosts(), new_x);\n        DblVec new_cnt_viols = evaluateConstraintViols(constraints, new_x);\n        ++results_.n_func_evals;\n\n        double old_merit = vecSum(results_.cost_vals) + param_.merit_error_coeff * vecSum(results_.cnt_viols);\n        double model_merit = vecSum(model_cost_vals) + param_.merit_error_coeff * vecSum(model_cnt_viols);\n        double new_merit = vecSum(new_cost_vals) + param_.merit_error_coeff * vecSum(new_cnt_viols);\n        double approx_merit_improve = old_merit - model_merit;\n        double exact_merit_improve = old_merit - new_merit;\n        double merit_improve_ratio = exact_merit_improve / approx_merit_improve;\n\n        if (util::GetLogLevel() >= util::LevelInfo)\n        {\n          LOG_INFO(\" \");\n          printCostInfo(results_.cost_vals, model_cost_vals, new_cost_vals, results_.cnt_viols, model_cnt_viols,\n                        new_cnt_viols, cost_names, cnt_names, param_.merit_error_coeff);\n          std::printf(\"%15s | %10.3e | %10.3e | %10.3e | %10.3e\\n\", \"TOTAL\", old_merit, approx_merit_improve,\n                      exact_merit_improve, merit_improve_ratio);\n        }\n\n        if (approx_merit_improve < -1e-5)\n        {\n          LOG_ERROR(\"approximate merit function got worse (%.3e). \"\n                    \"(convexification is probably wrong to zeroth order)\",\n                    approx_merit_improve);\n        }\n        if (approx_merit_improve < param_.min_approx_improve)\n        {\n          LOG_INFO(\"converged because improvement was small (%.3e < %.3e)\", approx_merit_improve,\n                   param_.min_approx_improve);\n          retval = OPT_CONVERGED;\n          goto penaltyadjustment;\n        }\n        if (approx_merit_improve / old_merit < param_.min_approx_improve_frac)\n        {\n          LOG_INFO(\"converged because improvement ratio was small (%.3e < %.3e)\", approx_merit_improve / old_merit,\n                   param_.min_approx_improve_frac);\n          retval = OPT_CONVERGED;\n          goto penaltyadjustment;\n        }\n        else if (exact_merit_improve < 0 || merit_improve_ratio < param_.improve_ratio_threshold)\n        {\n          adjustTrustRegion(param_.trust_shrink_ratio);\n          LOG_INFO(\"shrunk trust region. new box size: %.4f\", param_.trust_box_size);\n        }\n        else\n        {\n          results_.x = new_x;\n          results_.cost_vals = new_cost_vals;\n          results_.cnt_viols = new_cnt_viols;\n          adjustTrustRegion(param_.trust_expand_ratio);\n          LOG_INFO(\"expanded trust region. new box size: %.4f\", param_.trust_box_size);\n          break;\n        }\n      }\n\n      if (param_.trust_box_size < param_.min_trust_box_size)\n      {\n        LOG_INFO(\"converged because trust region is tiny\");\n        retval = OPT_CONVERGED;\n        goto penaltyadjustment;\n      }\n      else if (iter >= param_.max_iter)\n      {\n        LOG_INFO(\"iteration limit\");\n        retval = OPT_SCO_ITERATION_LIMIT;\n        goto cleanup;\n      }\n    }\n\n  penaltyadjustment:\n    if (results_.cnt_viols.empty() || vecMax(results_.cnt_viols) < param_.cnt_tolerance)\n    {\n      if (results_.cnt_viols.size() > 0)\n        LOG_INFO(\"woo-hoo! constraints are satisfied (to tolerance %.2e)\", param_.cnt_tolerance);\n      goto cleanup;\n    }\n    else\n    {\n      LOG_INFO(\"not all constraints are satisfied. increasing penalties\");\n      param_.merit_error_coeff *= param_.merit_coeff_increase_ratio;\n      param_.trust_box_size = fmax(param_.trust_box_size, param_.min_trust_box_size / param_.trust_shrink_ratio * 1.5);\n    }\n  }\n  retval = OPT_PENALTY_ITERATION_LIMIT;\n  LOG_INFO(\"optimization couldn't satisfy all constraints\");\n\ncleanup:\n  assert(retval != INVALID && \"should never happen\");\n  results_.status = retval;\n  results_.total_cost = vecSum(results_.cost_vals);\n  LOG_INFO(\"\\n==================\\n%s==================\", CSTR(results_));\n  callCallbacks();\n\n  return retval;\n}\n}  // namespace sco\n", "meta": {"hexsha": "d541106c20f005319741a2cf441e10f674227d20", "size": 17095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moveit_planners/trajopt/trajopt_sco/src/optimizers.cpp", "max_stars_repo_name": "adam-vonderviszt/moveit", "max_stars_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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": "moveit_planners/trajopt/trajopt_sco/src/optimizers.cpp", "max_issues_repo_name": "adam-vonderviszt/moveit", "max_issues_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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": "moveit_planners/trajopt/trajopt_sco/src/optimizers.cpp", "max_forks_repo_name": "adam-vonderviszt/moveit", "max_forks_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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.9222462203, "max_line_length": 120, "alphanum_fraction": 0.6305352442, "num_tokens": 4697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.37754068280545827, "lm_q1q2_score": 0.1946674950501602}}
{"text": "/*\n@copyright Louis Dionne 2014\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/constant/mcd.hpp>\n\n#include <boost/hana/comparable/laws.hpp>\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/minimal/constant.hpp>\n#include <boost/hana/list/instance.hpp>\nusing namespace boost::hana;\n\n\nstruct UDT {\n    struct Type { };\n    Type member;\n};\n\ntemplate <typename mcd, typename T, typename U>\nvoid test() {\n    BOOST_HANA_CONSTANT_ASSERT(\n        Comparable::laws::check(\n            list(\n                detail::minimal::constant<T, 0, mcd>,\n                detail::minimal::constant<T, 1, mcd>,\n\n                detail::minimal::constant<U, 1, mcd>,\n                detail::minimal::constant<U, 2, mcd>,\n\n                detail::minimal::constant<decltype(&UDT::member), &UDT::member, mcd>\n            )\n        )\n    );\n}\n\nint main() {\n    test<Constant::mcd, int, int>();\n    test<Constant::mcd, int, unsigned long long>();\n}\n", "meta": {"hexsha": "d79c065a8999b1707883887495d40e7bf2a558a3", "size": 1059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/comparable/laws.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/constant/comparable/laws.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/constant/comparable/laws.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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": 25.2142857143, "max_line_length": 84, "alphanum_fraction": 0.6241737488, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1946674878277107}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2019 Nil Foundation AG\n// Copyright (c) 2018-2019 Mikhail Komarov <nemo@nilfoundation.org>\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// 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#define BOOST_TEST_MODULE wesolowski_test\n\n#include <nil/crypto3/vdf/wesolowski.hpp>\n\n#include <nil/crypto3/vdf/algorithm/compute.hpp>\n#include <nil/crypto3/vdf/algorithm/verify.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include <boost/static_assert.hpp>\n\n#include <iostream>\n#include <string>\n#include <unordered_map>\n\nusing namespace nil::crypto3::vdf;\n\nBOOST_AUTO_TEST_SUITE(wesolowski_test_suite)\n\n    BOOST_AUTO_TEST_CASE(wesolowski_vdf) {\n\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "0b1d706a0d63e67f385d55be8e71fe70721e9a2f", "size": 1551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vdf/test/wesolowski.cpp", "max_stars_repo_name": "nemothenoone/chia_network.nemo1369-vdf-track2", "max_stars_repo_head_hexsha": "9ffd2b907b0e859441c799af343db96f42ee2787", "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": "libs/vdf/test/wesolowski.cpp", "max_issues_repo_name": "nemothenoone/chia_network.nemo1369-vdf-track2", "max_issues_repo_head_hexsha": "9ffd2b907b0e859441c799af343db96f42ee2787", "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": "libs/vdf/test/wesolowski.cpp", "max_forks_repo_name": "nemothenoone/chia_network.nemo1369-vdf-track2", "max_forks_repo_head_hexsha": "9ffd2b907b0e859441c799af343db96f42ee2787", "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.0, "max_line_length": 79, "alphanum_fraction": 0.6866537718, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19466748782771068}}
{"text": "// Copyright (c) 2012-2013 The PPCoin developers\n// Copyright (c) 2014 The BlackCoin 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 <boost/assign/list_of.hpp>\n\n#include <pos.h>\n#include <txdb.h>\n#include <validation.h>\n#include <arith_uint256.h>\n#include <hash.h>\n#include <timedata.h>\n#include <chainparams.h>\n#include <script/sign.h>\n#include <consensus/consensus.h>\n#include <util/signstr.h>\n#include <qtum/qtumdelegation.h>\n\nusing namespace std;\n\n// Delegation contract function\nQtumDelegation& GetQtumDelegation()\n{\n    static QtumDelegation qtumDelegation;\n    return qtumDelegation;\n}\n\n// Stake Modifier (hash modifier of proof-of-stake):\n// The purpose of stake modifier is to prevent a txout (coin) owner from\n// computing future proof-of-stake generated by this txout at the time\n// of transaction confirmation. To meet kernel protocol, the txout\n// must hash with a future stake modifier to generate the proof.\nuint256 ComputeStakeModifier(const CBlockIndex* pindexPrev, const uint256& kernel)\n{\n    if (!pindexPrev)\n        return uint256();  // genesis block's modifier is 0\n\n    CDataStream ss(SER_GETHASH, 0);\n    ss << kernel << pindexPrev->nStakeModifier;\n    return Hash(ss.begin(), ss.end());\n}\n\n// BlackCoin kernel protocol\n// coinstake must meet hash target according to the protocol:\n// kernel (input 0) must meet the formula\n//     hash(nStakeModifier + blockFrom.nTime + txPrev.vout.hash + txPrev.vout.n + nTime) < bnTarget * nWeight\n// this ensures that the chance of getting a coinstake is proportional to the\n// amount of coins one owns.\n// The reason this hash is chosen is the following:\n//   nStakeModifier: scrambles computation to make it very difficult to precompute\n//                   future proof-of-stake\n//   blockFrom.nTime: slightly scrambles computation\n//   txPrev.vout.hash: hash of txPrev, to reduce the chance of nodes\n//                     generating coinstake at the same time\n//   txPrev.vout.n: output number of txPrev, to reduce the chance of nodes\n//                  generating coinstake at the same time\n//   nTime: current timestamp\n//   block/tx hash should not be used here as they can be generated in vast\n//   quantities so as to generate blocks faster, degrading the system back into\n//   a proof-of-work situation.\n//\nbool CheckStakeKernelHash(CBlockIndex* pindexPrev, unsigned int nBits, uint32_t blockFromTime, CAmount prevoutValue, const COutPoint& prevout, unsigned int nTimeBlock, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake)\n{\n    if (nTimeBlock < blockFromTime)  // Transaction timestamp violation\n        return error(\"CheckStakeKernelHash() : nTime violation\");\n\n    // Base target\n    arith_uint256 bnTarget;\n    bnTarget.SetCompact(nBits);\n\n    // Weighted target\n    int64_t nValueIn = prevoutValue;\n    arith_uint256 bnWeight = arith_uint256(nValueIn);\n    bnTarget *= bnWeight;\n\n    targetProofOfStake = ArithToUint256(bnTarget);\n\n    uint256 nStakeModifier = pindexPrev->nStakeModifier;\n\n    // Calculate hash\n    CDataStream ss(SER_GETHASH, 0);\n    ss << nStakeModifier;\n    ss << blockFromTime << prevout.hash << prevout.n << nTimeBlock;\n    hashProofOfStake = Hash(ss.begin(), ss.end());\n\n    if (fPrintProofOfStake)\n    {\n        LogPrintf(\"CheckStakeKernelHash() : check modifier=%s nTimeBlockFrom=%u nPrevout=%u nTimeBlock=%u hashProof=%s\\n\",\n            nStakeModifier.GetHex().c_str(),\n            blockFromTime, prevout.n, nTimeBlock,\n            hashProofOfStake.ToString());\n    }\n\n    // Now check if proof-of-stake hash meets target protocol\n    if (UintToArith256(hashProofOfStake) > bnTarget)\n        return false;\n\n    if (LogInstance().WillLogCategory(BCLog::COINSTAKE) && !fPrintProofOfStake)\n    {\n        LogPrintf(\"CheckStakeKernelHash() : check modifier=%s nTimeBlockFrom=%u nPrevout=%u nTimeBlock=%u hashProof=%s\\n\",\n            nStakeModifier.GetHex().c_str(),\n            blockFromTime, prevout.n, nTimeBlock,\n            hashProofOfStake.ToString());\n    }\n\n    return true;\n}\n\nbool GetStakeCoin(const COutPoint& prevout, Coin& coinPrev, CBlockIndex*& blockFrom, CBlockIndex* pindexPrev, BlockValidationState& state, CCoinsViewCache& view)\n{\n    // Get the coin\n    if(!view.GetCoin(prevout, coinPrev)){\n        return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-prevout-not-exist\", strprintf(\"CheckProofOfStake() : Stake prevout does not exist %s\", prevout.hash.ToString()));\n    }\n\n    // Check that the coin is mature\n    int nHeight = pindexPrev->nHeight + 1;\n    if(nHeight - coinPrev.nHeight < COINBASE_MATURITY){\n        return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-prevout-not-mature\", strprintf(\"CheckProofOfStake() : Stake prevout is not mature, expecting %i and only matured to %i\", COINBASE_MATURITY, nHeight - coinPrev.nHeight));\n    }\n\n    // Get the block header from the coin\n    blockFrom = pindexPrev->GetAncestor(coinPrev.nHeight);\n    if(!blockFrom) {\n        return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-prevout-not-loaded\", strprintf(\"CheckProofOfStake() : Block at height %i for prevout can not be loaded\", coinPrev.nHeight));\n    }\n\n    // Check that the coin is not used in the last COINBASE_MATURITY headers\n    // Delegated utxo is not spent when block is created using that coin, so additional check to the last headers needed\n    int coinHeight = -1;\n    CBlockIndex* prev = pindexPrev;\n    for(int i = 0; i < COINBASE_MATURITY; i++) {\n        if(prev->prevoutStake == prevout) {\n            coinHeight = prev->nHeight;\n            break;\n        }\n        prev = prev->pprev;\n\n        if(!prev) break;\n    }\n    if(coinHeight != -1) {\n        if(nHeight - coinHeight < COINBASE_MATURITY){\n            return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-prevout-not-mature\", strprintf(\"CheckProofOfStake() : Stake prevout is not mature, expecting %i and only matured to %i\", COINBASE_MATURITY, nHeight - coinHeight));\n        }\n    }\n\n    return true;\n}\n\n// Check kernel hash target and coinstake signature\nbool CheckProofOfStake(CBlockIndex* pindexPrev, BlockValidationState& state, const CTransaction& tx, unsigned int nBits, uint32_t nTimeBlock, const std::vector<unsigned char>& vchPoD,  const COutPoint& headerPrevout, uint256& hashProofOfStake, uint256& targetProofOfStake, CCoinsViewCache& view)\n{\n    if (!tx.IsCoinStake())\n        return error(\"CheckProofOfStake() : called on non-coinstake %s\", tx.GetHash().ToString());\n\n    // Kernel (input 0) must match the stake hash target (nBits)\n    const CTxIn& txin = tx.vin[0];\n\n    // Get the PoS transaction coin from the first input\n    Coin coinTxPrev;\n    CBlockIndex* blockTxFrom = 0;\n    if(!GetStakeCoin(txin.prevout, coinTxPrev, blockTxFrom, pindexPrev, state, view))\n        return error(\"CheckProofOfStake() : fail to get prevout %s\", txin.prevout.hash.ToString());\n\n    // Get the PoS header coin from prevoutStake\n    Coin coinHeaderPrev;\n    CBlockIndex* blockHeaderFrom = 0;\n    if(txin.prevout == headerPrevout)\n    {\n        coinHeaderPrev = coinTxPrev;\n        blockHeaderFrom = blockTxFrom;\n    }\n    else\n    {\n        // The PoS transaction and PoS header coins are different when proof of delegation exist\n        if(!GetStakeCoin(headerPrevout, coinHeaderPrev, blockHeaderFrom, pindexPrev, state, view))\n            return error(\"CheckProofOfStake() : fail to get prevout %s\", headerPrevout.hash.ToString());\n    }\n\n    int nHeight = pindexPrev->nHeight + 1;\n    bool checkDelegation = false;\n    int nOfflineStakeHeight = Params().GetConsensus().nOfflineStakeHeight;\n    if (nHeight >= nOfflineStakeHeight && !Params().GetConsensus().delegationsAddress.IsNull())\n    {\n        ////////////////////////////////////////////////// deploy offline staking contract\n        if(nHeight == nOfflineStakeHeight){\n            globalState->deployDelegationsContract();\n        }\n        /////////////////////////////////////////////////\n\n        // Check if the delegation contract exist\n        QtumDelegation& qtumDelegation = GetQtumDelegation();\n        if(!qtumDelegation.ExistDelegationContract())\n            return state.Invalid(BlockValidationResult::BLOCK_HEADER_REJECT, \"stake-delegation-contract-not-exist\", strprintf(\"CheckProofOfStake() : The delegation contract doesn't exist, block height %i\", nOfflineStakeHeight)); // Internal error, delegation contract not exist\n\n        // Get the delegation from the contract\n        uint160 address = uint160(ExtractPublicKeyHash(coinHeaderPrev.out.scriptPubKey));\n        Delegation delegation;\n        if(!qtumDelegation.GetDelegation(address, delegation)) {\n            return state.Invalid(BlockValidationResult::BLOCK_HEADER_REJECT, \"stake-get-delegation-failed\", strprintf(\"CheckProofOfStake() : Failed to get delegation from the delegation contract\")); // Internal error, get delegation from the delegation contract\n        }\n\n        // Verify delegation received from the contract\n        bool verifiedDelegation = qtumDelegation.VerifyDelegation(address, delegation);\n        bool hasDelegationProof = vchPoD.size() > 0;\n\n        // Check that if PoD is present then the delegation received from the contract can be verified\n        if(hasDelegationProof && hasDelegationProof != verifiedDelegation) {\n            return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-delegation-not-verified\", strprintf(\"CheckProofOfStake() : Delegation for block at height %i cannot be verified\", nHeight));\n        }\n\n        // Check that if PoD is not present then the delegation received from the contract is null\n        if(!hasDelegationProof && !delegation.IsNull()) {\n            return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-delegation-not-used\", strprintf(\"CheckProofOfStake() : Delegation for block at height %i is present but not used to create the block\", nHeight));\n        }\n\n        checkDelegation = hasDelegationProof;\n        if(checkDelegation)\n        {\n            // Check that the staker have the permission to use that coin to create the coinstake transaction\n            CScript stakerPubKey = tx.vout[1].scriptPubKey;\n            uint160 staker = uint160(ExtractPublicKeyHash(stakerPubKey));\n            if(!SignStr::VerifyMessage(CKeyID(address), staker.GetReverseHex(), vchPoD))\n                return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-verify-delegation-failed\", strprintf(\"CheckProofOfStake() : VerifyDelegation failed on coinstake %s\", tx.GetHash().ToString()));\n\n            // Check the super staker min utxo value\n            if(coinTxPrev.out.nValue < DEFAULT_STAKING_MIN_UTXO_VALUE)\n                return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-delegation-not-min-utxo\", strprintf(\"CheckProofOfStake() : Stake for block at height %i do not have the minimum amount required for super staker\", nHeight));\n\n            // Check that the block delegation data is the same as the data received from the contract, this is to avoid using old/removed delegation\n            bool delegateOutputExist = IsDelegateOutputExist(delegation.fee);\n            int fee = GetDelegationFeeTx(tx, coinTxPrev, delegateOutputExist);\n            if(delegation.staker != staker ||\n                    (int)delegation.fee != fee ||\n                    (int)delegation.blockHeight > nHeight ||\n                    delegation.PoD != vchPoD) {\n                return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-delegation-not-match\", strprintf(\"CheckProofOfStake() : Delegation for block at height %i is not the same with the delegation received from the delegation contract\", nHeight));\n            }\n        }\n    }\n\n    // Check stake and block prevout\n    if(!checkDelegation && txin.prevout != headerPrevout)\n        return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-prevout-diff-block-prevout\", strprintf(\"CheckProofOfStake() : Stake prevout %s is different then block prevout %s\", txin.prevout.hash.ToString(), headerPrevout.hash.ToString()));\n\n    // Verify signature\n    if (!VerifySignature(coinTxPrev, txin.prevout.hash, tx, 0, SCRIPT_VERIFY_NONE))\n        return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, \"stake-verify-signature-failed\", strprintf(\"CheckProofOfStake() : VerifySignature failed on coinstake %s\", tx.GetHash().ToString()));\n\n    if (!CheckStakeKernelHash(pindexPrev, nBits, blockHeaderFrom->nTime, coinHeaderPrev.out.nValue, headerPrevout, nTimeBlock, hashProofOfStake, targetProofOfStake, LogInstance().WillLogCategory(BCLog::COINSTAKE)))\n        return state.Invalid(BlockValidationResult::BLOCK_HEADER_SYNC, \"stake-check-kernel-failed\", strprintf(\"CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s\", tx.GetHash().ToString(), hashProofOfStake.ToString())); // may occur during initial download or if behind on block chain sync\n\n    return true;\n}\n\n// Check whether the coinstake timestamp meets protocol\nbool CheckCoinStakeTimestamp(uint32_t nTimeBlock)\n{\n    return (nTimeBlock & STAKE_TIMESTAMP_MASK) == 0;\n}\n\nbool CheckBlockInputPubKeyMatchesOutputPubKey(const CBlock& block, CCoinsViewCache& view, bool delegateOutputExist) {\n\n    Coin coinIn;\n    if(!view.GetCoin(block.prevoutStake, coinIn)) {\n        return error(\"%s: Could not fetch prevoutStake from UTXO set\", __func__);\n    }\n\n    uint32_t hasDelegation = block.HasProofOfDelegation() ? 1 : 0;\n    if(hasDelegation && !delegateOutputExist)\n        return true; // Delegate output doesn't exist in case of 100% fee, so the check cannot be performed\n\n    CTransactionRef coinstakeTx = block.vtx[1];\n    if(coinstakeTx->vout.size() < 2 + hasDelegation) {\n        return error(\"%s: coinstake transaction does not have the minimum number of outputs\", __func__);\n    }\n\n    const CTxOut& txout = coinstakeTx->vout[1 + hasDelegation];\n\n    if(coinIn.out.scriptPubKey == txout.scriptPubKey) {\n        return true;\n    }\n\n    // If the input does not exactly match the output, it MUST be on P2PKH spent and P2PK out.\n    CTxDestination inputAddress;\n    txnouttype inputTxType=TX_NONSTANDARD;\n    if(!ExtractDestination(coinIn.out.scriptPubKey, inputAddress, &inputTxType)) {\n        return error(\"%s: Could not extract address from input\", __func__);\n    }\n\n    if(inputTxType != TX_PUBKEYHASH || inputAddress.type() != typeid(PKHash)) {\n        return error(\"%s: non-exact match input must be P2PKH\", __func__);\n    }\n\n    CTxDestination outputAddress;\n    txnouttype outputTxType=TX_NONSTANDARD;\n    if(!ExtractDestination(txout.scriptPubKey, outputAddress, &outputTxType)) {\n        return error(\"%s: Could not extract address from output\", __func__);\n    }\n\n    if(outputTxType != TX_PUBKEY || outputAddress.type() != typeid(PKHash)) {\n        return error(\"%s: non-exact match output must be P2PK\", __func__);\n    }\n\n    if(boost::get<PKHash>(inputAddress) != boost::get<PKHash>(outputAddress)) {\n        return error(\"%s: input P2PKH pubkey does not match output P2PK pubkey\", __func__);\n    }\n\n    return true;\n}\n\nbool CheckRecoveredPubKeyFromBlockSignature(CBlockIndex* pindexPrev, const CBlockHeader& block, CCoinsViewCache& view) {\n    Coin coinPrev;\n    if(!view.GetCoin(block.prevoutStake, coinPrev)){\n        if(!GetSpentCoinFromMainChain(pindexPrev, block.prevoutStake, &coinPrev)) {\n            return error(\"CheckRecoveredPubKeyFromBlockSignature(): Could not find %s and it was not at the tip\", block.prevoutStake.hash.GetHex());\n        }\n    }\n\n    uint256 hash = block.GetHashWithoutSign();\n    CPubKey pubkey;\n    std::vector<unsigned char> vchBlockSig = block.GetBlockSignature();\n    std::vector<unsigned char> vchPoD = block.GetProofOfDelegation();\n    bool hasDelegation = block.HasProofOfDelegation();\n\n    if(vchBlockSig.empty()) {\n        return error(\"CheckRecoveredPubKeyFromBlockSignature(): Signature is empty\\n\");\n    }\n\n    // Recover the public key\n    if (pindexPrev->nHeight + 1 >= Params().GetConsensus().nOfflineStakeHeight)\n    {\n        // Recover the public key from compact signature\n        if(hasDelegation)\n        {\n            // Has delegation\n            CTxDestination address;\n            txnouttype txType=TX_NONSTANDARD;\n            if(pubkey.RecoverCompact(hash, vchBlockSig) &&\n                    ExtractDestination(coinPrev.out.scriptPubKey, address, &txType)){\n                if ((txType == TX_PUBKEY || txType == TX_PUBKEYHASH) && address.type() == typeid(PKHash)) {\n                    if(SignStr::VerifyMessage(CKeyID(boost::get<PKHash>(address)), pubkey.GetID().GetReverseHex(), vchPoD)) {\n                        return true;\n                    }\n                }\n            }\n        }\n        else\n        {\n            // No delegation\n            CTxDestination address;\n            txnouttype txType=TX_NONSTANDARD;\n            if(pubkey.RecoverCompact(hash, vchBlockSig) &&\n                    ExtractDestination(coinPrev.out.scriptPubKey, address, &txType)){\n                if ((txType == TX_PUBKEY || txType == TX_PUBKEYHASH) && address.type() == typeid(PKHash)) {\n                    if(pubkey.GetID() == boost::get<PKHash>(address)) {\n                        return true;\n                    }\n                }\n            }\n        }\n    }\n    else\n    {\n        // Recover the public key from LowS signature\n        for(uint8_t recid = 0; recid <= 3; ++recid) {\n            for(uint8_t compressed = 0; compressed < 2; ++compressed) {\n                if(!pubkey.RecoverLaxDER(hash, vchBlockSig, recid, compressed)) {\n                    continue;\n                }\n\n                CTxDestination address;\n                txnouttype txType=TX_NONSTANDARD;\n                if(ExtractDestination(coinPrev.out.scriptPubKey, address, &txType)){\n                    if ((txType == TX_PUBKEY || txType == TX_PUBKEYHASH) && address.type() == typeid(PKHash)) {\n                        if(pubkey.GetID() == boost::get<PKHash>(address)) {\n                            return true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    return false;\n}\n\nbool CheckKernel(CBlockIndex* pindexPrev, unsigned int nBits, uint32_t nTimeBlock, const COutPoint& prevout, CCoinsViewCache& view)\n{\n    std::map<COutPoint, CStakeCache> tmp;\n    return CheckKernel(pindexPrev, nBits, nTimeBlock, prevout, view, tmp);\n}\n\nbool CheckKernel(CBlockIndex* pindexPrev, unsigned int nBits, uint32_t nTimeBlock, const COutPoint& prevout, CCoinsViewCache& view, const std::map<COutPoint, CStakeCache>& cache)\n{\n    uint256 hashProofOfStake, targetProofOfStake;\n    auto it=cache.find(prevout);\n    if(it == cache.end()) {\n        //not found in cache (shouldn't happen during staking, only during verification which does not use cache)\n        Coin coinPrev;\n        if(!view.GetCoin(prevout, coinPrev)){\n            if(!GetSpentCoinFromMainChain(pindexPrev, prevout, &coinPrev)) {\n                return error(\"CheckKernel(): Could not find coin and it was not at the tip\");\n            }\n        }\n\n        if(pindexPrev->nHeight + 1 - coinPrev.nHeight < COINBASE_MATURITY){\n            return error(\"CheckKernel(): Coin not matured\");\n        }\n        CBlockIndex* blockFrom = pindexPrev->GetAncestor(coinPrev.nHeight);\n        if(!blockFrom) {\n            return error(\"CheckKernel(): Could not find block\");\n        }\n        if(coinPrev.IsSpent()){\n            return error(\"CheckKernel(): Coin is spent\");\n        }\n\n        return CheckStakeKernelHash(pindexPrev, nBits, blockFrom->nTime, coinPrev.out.nValue, prevout,\n                                    nTimeBlock, hashProofOfStake, targetProofOfStake);\n    }else{\n        //found in cache\n        const CStakeCache& stake = it->second;\n        if(CheckStakeKernelHash(pindexPrev, nBits, stake.blockFromTime, stake.amount, prevout,\n                                    nTimeBlock, hashProofOfStake, targetProofOfStake)){\n            //Cache could potentially cause false positive stakes in the event of deep reorgs, so check without cache also\n            return CheckKernel(pindexPrev, nBits, nTimeBlock, prevout, view);\n        }\n    }\n    return false;\n}\n\nvoid CacheKernel(std::map<COutPoint, CStakeCache>& cache, const COutPoint& prevout, CBlockIndex* pindexPrev, CCoinsViewCache& view){\n    if(cache.find(prevout) != cache.end()){\n        //already in cache\n        return;\n    }\n\n    Coin coinPrev;\n    if(!view.GetCoin(prevout, coinPrev)){\n        return;\n    }\n\n    if(pindexPrev->nHeight + 1 - coinPrev.nHeight < COINBASE_MATURITY){\n        return;\n    }\n    CBlockIndex* blockFrom = pindexPrev->GetAncestor(coinPrev.nHeight);\n    if(!blockFrom) {\n        return;\n    }\n\n    CStakeCache c(blockFrom->nTime, coinPrev.out.nValue);\n    cache.insert({prevout, c});\n}\n\n/**\n * Proof-of-stake functions needed in the wallet but wallet independent\n */\nstruct BlockScript{\n    CScript stakerScript;\n    CScript delegateScript;\n    uint8_t fee;\n    bool hasDelegate;\n\n    BlockScript(const CScript& _stakerScript = CScript()):\n        stakerScript(_stakerScript),\n        fee(0),\n        hasDelegate(false)\n    {}\n};\n\nstruct ScriptsElement{\n    BlockScript script;\n    uint256 hash;\n};\n\n/**\n * Cache of the recent mpos scripts for the block reward recipients\n * The max size of the map is 2 * nCacheScripts - nMPoSRewardRecipients, so in this case it is 20\n */\nstd::map<int, ScriptsElement> scriptsMap;\n\nunsigned int GetStakeMaxCombineInputs() { return 100; }\n\nint64_t GetStakeCombineThreshold() { return 100 * COIN; }\n\nunsigned int GetStakeSplitOutputs() { return 2; }\n\nint64_t GetStakeSplitThreshold() { return GetStakeSplitOutputs() * GetStakeCombineThreshold(); }\n\nbool SplitOfflineStakeReward(const int64_t& nReward, const uint8_t& fee, int64_t& nRewardOffline, int64_t& nRewardStaker)\n{\n    if(fee > 100) return false;\n    nRewardStaker = nReward * fee / 100;\n    nRewardOffline = nReward - nRewardStaker;\n    return true;\n}\n\nbool IsDelegateOutputExist(int inFee)\n{\n    return inFee >= 0 && inFee < 100;\n}\n\nint GetDelegationFeeTx(const CTransaction& tx, const Coin& coin, bool delegateOutputExist)\n{\n    CAmount nValueCoin = coin.out.nValue;\n    size_t minVoutSize = delegateOutputExist ? 3 : 2;\n    if(!tx.IsCoinStake() || tx.vout.size() < minVoutSize || nValueCoin <= 0)\n        return -1;\n\n    CAmount nValueStaker = tx.vout[1].nValue - nValueCoin;\n    CAmount nValueDelegate = delegateOutputExist ? tx.vout[2].nValue : 0;\n    CAmount nReward = nValueStaker + nValueDelegate;\n    if(nReward <= 0)\n        return -1;\n\n    return (nValueStaker * 100 + nReward - 1) / nReward;\n}\n\nbool GetDelegationFeeFromContract(const uint160& address, uint8_t& fee)\n{\n    Delegation delegation;\n    QtumDelegation& qtumDelegation = GetQtumDelegation();\n    bool ret = qtumDelegation.GetDelegation(address, delegation);\n    if(ret) ret &= qtumDelegation.VerifyDelegation(address, delegation);\n    if(ret)\n    {\n        fee = delegation.fee;\n    }\n    return ret;\n}\n\nbool NeedToEraseScriptFromCache(int nBlockHeight, int nCacheScripts, int nScriptHeight, const ScriptsElement& scriptElement)\n{\n    // Erase element from cache if not in range [nBlockHeight - nCacheScripts, nBlockHeight + nCacheScripts]\n    if(nScriptHeight < (nBlockHeight - nCacheScripts) ||\n            nScriptHeight > (nBlockHeight + nCacheScripts))\n        return true;\n\n    // Erase element from cache if hash different\n    CBlockIndex* pblockindex = ChainActive()[nScriptHeight];\n    if(pblockindex && pblockindex->GetBlockHash() != scriptElement.hash)\n        return true;\n\n    return false;\n}\n\nvoid CleanScriptCache(int nHeight, const Consensus::Params& consensusParams)\n{\n    int nCacheScripts = consensusParams.nMPoSRewardRecipients * 1.5;\n\n    // Remove the scripts from cache that are not used\n    for (std::map<int, ScriptsElement>::iterator it=scriptsMap.begin(); it!=scriptsMap.end();){\n        if(NeedToEraseScriptFromCache(nHeight, nCacheScripts, it->first, it->second))\n        {\n            it = scriptsMap.erase(it);\n        }\n        else{\n            it++;\n        }\n    }\n}\n\nbool ReadFromScriptCache(BlockScript &script, CBlockIndex* pblockindex, int nHeight, const Consensus::Params& consensusParams)\n{\n    CleanScriptCache(nHeight, consensusParams);\n\n    // Find the script in the cache\n    std::map<int, ScriptsElement>::iterator it = scriptsMap.find(nHeight);\n    if(it != scriptsMap.end())\n    {\n        if(it->second.hash == pblockindex->GetBlockHash())\n        {\n            script = it->second.script;\n            return true;\n        }\n    }\n\n    return false;\n}\n\nvoid AddToScriptCache(BlockScript script, CBlockIndex* pblockindex, int nHeight, const Consensus::Params& consensusParams)\n{\n    CleanScriptCache(nHeight, consensusParams);\n\n    // Add the script into the cache\n    ScriptsElement listElement;\n    listElement.script = script;\n    listElement.hash = pblockindex->GetBlockHash();\n    scriptsMap.insert(std::pair<int, ScriptsElement>(nHeight, listElement));\n}\n\nbool AddMPoSScript(std::vector<BlockScript> &mposScriptList, int nHeight, const Consensus::Params& consensusParams)\n{\n    // Check if the block index exist into the active chain\n    CBlockIndex* pblockindex = ChainActive()[nHeight];\n    if(!pblockindex)\n    {\n        LogPrint(BCLog::COINSTAKE, \"Block index not found\\n\");\n        return false;\n    }\n\n    // Try find the script from the cache\n    BlockScript blockScript;\n    if(ReadFromScriptCache(blockScript, pblockindex, nHeight, consensusParams))\n    {\n        mposScriptList.push_back(blockScript);\n        return true;\n    }\n\n    // Read the block\n    uint160 stakeAddress;\n    if(!pblocktree->ReadStakeIndex(nHeight, stakeAddress)){\n        return false;\n    }\n\n    // The block reward for PoS is in the second transaction (coinstake) and the second or third output\n    if(pblockindex->IsProofOfStake())\n    {\n        if(stakeAddress == uint160())\n        {\n            LogPrint(BCLog::COINSTAKE, \"Fail to solve script for mpos reward recipient\\n\");\n            //This should never fail, but in case it somehow did we don't want it to bring the network to a halt\n            //So, use an OP_RETURN script to burn the coins for the unknown staker\n            blockScript = CScript() << OP_RETURN;\n        }else{\n            // Make public key hash script\n            blockScript = CScript() << OP_DUP << OP_HASH160 << ToByteVector(stakeAddress) << OP_EQUALVERIFY << OP_CHECKSIG;\n        }\n\n        if(pblockindex->HasProofOfDelegation())\n        {\n            uint160 delegateAddress;\n            uint8_t fee;\n            if(!pblocktree->ReadDelegateIndex(nHeight, delegateAddress, fee)){\n                return false;\n            }\n\n            if(delegateAddress == uint160())\n            {\n                LogPrint(BCLog::COINSTAKE, \"Fail to solve script for mpos delegate reward recipient\\n\");\n                blockScript.delegateScript = CScript() << OP_RETURN;\n            }else{\n                // Make public key hash script\n                blockScript.delegateScript = CScript() << OP_DUP << OP_HASH160 << ToByteVector(delegateAddress) << OP_EQUALVERIFY << OP_CHECKSIG;\n            }\n\n            blockScript.fee = fee;\n            blockScript.hasDelegate = true;\n        }\n\n        // Add the script into the list\n        mposScriptList.push_back(blockScript);\n\n        // Update script cache\n        AddToScriptCache(blockScript, pblockindex, nHeight, consensusParams);\n    }\n    else\n    {\n        if(Params().MineBlocksOnDemand()){\n            //this could happen in regtest. Just ignore and add an empty script\n            blockScript = CScript() << OP_RETURN;\n            mposScriptList.push_back(blockScript);\n            return true;\n\n        }\n        LogPrint(BCLog::COINSTAKE, \"The block is not proof-of-stake\\n\");\n        return false;\n    }\n\n    return true;\n}\n\nbool GetMPoSOutputScripts(std::vector<BlockScript>& mposScriptList, int nHeight, const Consensus::Params& consensusParams)\n{\n    bool ret = true;\n    nHeight -= COINBASE_MATURITY;\n\n    // Populate the list of scripts for the reward recipients\n    for(int i = 0; (i < consensusParams.nMPoSRewardRecipients - 1) && ret; i++)\n    {\n        ret &= AddMPoSScript(mposScriptList, nHeight - i, consensusParams);\n    }\n\n    return ret;\n}\n\nbool GetMPoSOutputs(std::vector<CTxOut>& mposOutputList, int64_t nRewardPiece, int nHeight, const Consensus::Params& consensusParams)\n{\n    std::vector<BlockScript> mposScriptList;\n    if(!GetMPoSOutputScripts(mposScriptList, nHeight, consensusParams))\n    {\n        LogPrint(BCLog::COINSTAKE, \"Fail to get the list of recipients\\n\");\n        return false;\n    }\n\n    // Create the outputs for the recipients\n    for(unsigned int i = 0; i < mposScriptList.size(); i++)\n    {\n        BlockScript blockScript = mposScriptList[i];\n        if(blockScript.hasDelegate)\n        {\n            int64_t nRewardDelegate, nRewardStaker;\n            if(!SplitOfflineStakeReward(nRewardPiece, blockScript.fee, nRewardDelegate, nRewardStaker))\n            {\n                LogPrint(BCLog::COINSTAKE, \"Fail to to split the offline staking reward\\n\");\n                return false;\n            }\n\n            mposOutputList.push_back(CTxOut(nRewardStaker, blockScript.stakerScript));\n            if(IsDelegateOutputExist(blockScript.fee))\n            {\n                mposOutputList.push_back(CTxOut(nRewardDelegate, blockScript.delegateScript));\n            }\n        }\n        else\n        {\n            mposOutputList.push_back(CTxOut(nRewardPiece, blockScript.stakerScript));\n        }\n    }\n\n    return true;\n}\n\nbool CreateMPoSOutputs(CMutableTransaction& txNew, int64_t nRewardPiece, int nHeight, const Consensus::Params& consensusParams)\n{\n    std::vector<CTxOut> mposOutputList;\n    if(!GetMPoSOutputs(mposOutputList, nRewardPiece, nHeight, consensusParams))\n    {\n        return false;\n    }\n\n    // Split the block reward with the recipients\n    for(unsigned int i = 0; i < mposOutputList.size(); i++)\n    {\n        txNew.vout.push_back(mposOutputList[i]);\n    }\n\n    return true;\n}\n\n", "meta": {"hexsha": "6129e4b1df250af1d482c433cad5ae0418a3e431", "size": 30154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pos.cpp", "max_stars_repo_name": "100milliondollars/NeuQ", "max_stars_repo_head_hexsha": "8670b9e50d4e2edfd2f35dc3058b3112ffb46986", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-13T01:44:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-13T01:44:54.000Z", "max_issues_repo_path": "src/pos.cpp", "max_issues_repo_name": "100milliondollars/NeuQ", "max_issues_repo_head_hexsha": "8670b9e50d4e2edfd2f35dc3058b3112ffb46986", "max_issues_repo_licenses": ["MIT"], "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/pos.cpp", "max_forks_repo_name": "100milliondollars/NeuQ", "max_forks_repo_head_hexsha": "8670b9e50d4e2edfd2f35dc3058b3112ffb46986", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T22:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-13T15:15:12.000Z", "avg_line_length": 40.6388140162, "max_line_length": 316, "alphanum_fraction": 0.6705909664, "num_tokens": 7492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1946674822074067}}
{"text": "/**\n * @file envelope_collection.cc\n * Computes the reverberation envelope time series for all combinations of\n * receiver azimuth, source beam number, receiver beam number.\n */\n#include <usml/eigenverb/envelope_collection.h>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/foreach.hpp>\n#include <netcdfcpp.h>\n\nusing namespace usml::eigenverb;\n\n/**\n * Reserve memory in which to store results as a series of\n * nested dynamic arrays.\n */\nenvelope_collection::envelope_collection(\n\tconst seq_vector* envelope_freq,\n\tsize_t src_freq_first,\n\tconst seq_vector* travel_time,\n\tdouble reverb_duration,\n\tdouble pulse_length,\n\tdouble threshold,\n\tsize_t num_azimuths,\n\tsize_t num_src_beams,\n\tsize_t num_rcv_beams,\n\tdouble initial_time,\n\tsensor_model::id_type source_id,\n    sensor_model::id_type receiver_id,\n    wposition1 src_position,\n    wposition1 rcv_position\n) :\n\t_envelope_freq(envelope_freq->clone()),\n\t_travel_time( travel_time->clip(0.0,reverb_duration) ),\n\t_reverb_duration(reverb_duration),\n\t_pulse_length(pulse_length),\n\t_threshold( threshold ),\n\t_num_azimuths(num_azimuths),\n\t_num_src_beams(num_src_beams),\n\t_num_rcv_beams(num_rcv_beams),\n\t_initial_time(initial_time),\n\t_source_id(source_id),\n\t_receiver_id(receiver_id),\n\t_source_position(src_position),\n\t_receiver_position(rcv_position),\n\t_envelope_model( _envelope_freq, src_freq_first, _travel_time,\n\t                        _initial_time, _pulse_length, _threshold)\n{\n    // Store range from source to receiver when eigenverbs were obtained.\n    _slant_range = _receiver_position.distance(_source_position);\n\n\t_envelopes = new matrix<double>***[_num_azimuths];\n\tmatrix<double>**** pa = _envelopes;\n\tfor (size_t a = 0; a < _num_azimuths; ++a, ++pa) {\n\t\t*pa = new matrix<double>**[_num_src_beams];\n\t\tmatrix<double>*** ps = *pa;\n\t\tfor (size_t s = 0; s < _num_src_beams; ++s, ++ps) {\n\t\t\t*ps = new matrix<double>*[_num_rcv_beams];\n\t\t\tmatrix<double>** pr = *ps;\n\t\t\tfor (size_t r = 0; r < _num_rcv_beams; ++r, ++pr) {\n\t\t\t\t*pr = new matrix< double >(\n\t\t\t\t\t\t_envelope_freq->size(), _travel_time->size() ) ;\n\t\t\t\t(*pr)->clear();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Delete dynamic memory in each of the nested dynamic arrays.\n */\nenvelope_collection::~envelope_collection() {\n\tmatrix<double>**** pa = _envelopes;\n\tfor (size_t a = 0; a < _num_azimuths; ++a, ++pa) {\n\t\tmatrix<double>*** ps = *pa;\n\t\tfor (size_t s = 0; s < _num_src_beams; ++s, ++ps) {\n\t\t\tmatrix<double>** pr = *ps;\n\t\t\tfor (size_t r = 0; r < _num_rcv_beams; ++r, ++pr) {\n\t\t\t\tdelete *pr ;\n\t\t\t}\n\t\t\tdelete[] *ps ;\n\t\t}\n\t\tdelete[] *pa ;\n\t}\n\tdelete[] _envelopes ;\n\tdelete _envelope_freq ;\n\tdelete _travel_time ;\n}\n\n/**\n * Adds the intensity contribution for a single combination of source\n * and receiver eigenverbs.\n */\nvoid envelope_collection::add_contribution(\n\tconst eigenverb& src_verb, const eigenverb& rcv_verb,\n\tconst matrix<double>& src_beam, const matrix<double>& rcv_beam,\n\tconst vector<double>& scatter, double xs2, double ys2 )\n{\n\tsize_t azimuth = rcv_verb.az_index ;\n\tbool ok = _envelope_model.compute_intensity(src_verb,rcv_verb,scatter,xs2,ys2) ;\n\tif ( ok ) {\n\t\tfor ( size_t s=0 ; s < src_beam.size2() ; ++s ) {\n\t\t\tfor ( size_t r=0 ; r < rcv_beam.size2() ; ++r ) {\n\t\t\t\tfor ( size_t f=0 ; f < _envelope_freq->size() ; ++f ) {\n\t\t\t\t\tmatrix_row< matrix<double> > intensity(_envelope_model.intensity(), f);\n\t\t\t\t\tmatrix_row< matrix<double> > envelope(*_envelopes[azimuth][s][r], f);\n\t\t\t\t\tenvelope += src_beam(f, s) * rcv_beam(f, r) * intensity;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Updates the envelope_collection data with the parameters provided.\n */\nvoid envelope_collection::dead_reckon(double delta_time,\n                                    double slant_range, double prev_range) {\n    // Set new slant_range\n    _slant_range = slant_range;\n\n    // Shift the time series\n    delete _travel_time;\n    boost::numeric::ublas::vector<double> temp_data = (*_travel_time);\n    temp_data = temp_data + delta_time;\n    _travel_time = new seq_data( temp_data );\n\n    { // Scope for lock\n\n        // Perform copy and intensity update\n        double gain = slant_range/prev_range;\n        gain *= gain ;\n\n        write_lock_guard guard(this->_envelopes_mutex);\n        // Copy \"this\" envelopes to new_collection\n        matrix<double>**** pa = _envelopes;\n        for (size_t a = 0; a < _num_azimuths; ++a, ++pa)\n        {\n            matrix<double>*** ps = *pa;\n            for (size_t s = 0; s < _num_src_beams; ++s, ++ps)\n            {\n                matrix<double>** pr = *ps;\n                for (size_t r = 0; r < _num_rcv_beams; ++r, ++pr)\n                {\n                    (**pr) = this->envelope(a, s, r);\n                    (**pr) *= gain;\n                }\n            }\n        }\n    }\n}\n\n/**\n * Writes the envelope data to disk\n */\nvoid envelope_collection::write_netcdf(const char* filename) const {\n\tNcFile* nc_file = new NcFile(filename, NcFile::Replace);\n\n\t// dimensions\n\n\tNcDim* azimuth_dim = nc_file->add_dim(\"azimuth\", (long) _num_azimuths ) ;\n\tNcDim* src_beam_dim = nc_file->add_dim(\"src_beam\", (long) _num_src_beams ) ;\n\tNcDim* rcv_beam_dim = nc_file->add_dim(\"rcv_beam\", (long) _num_rcv_beams ) ;\n\tNcDim* freq_dim = nc_file->add_dim(\"frequency\", (long) _envelope_freq->size()) ;\n\tNcDim* time_dim = nc_file->add_dim(\"travel_time\", (long) _travel_time->size()) ;\n\n\t// variables\n\n\tNcVar* pulse_length_var = nc_file->add_var(\"pulse_length\", ncDouble );\n\tNcVar* threshold_var = nc_file->add_var(\"threshold\", ncDouble );\n\tNcVar* initial_time_var = nc_file->add_var(\"initial_time\", ncDouble );\n\tNcVar* freq_var = nc_file->add_var(\"frequency\", ncDouble, freq_dim);\n\tNcVar* time_var = nc_file->add_var(\"travel_time\", ncDouble, time_dim);\n\tNcVar* envelopes_var = nc_file->add_var(\"intensity\", ncDouble,\n\t\tazimuth_dim, src_beam_dim, rcv_beam_dim, freq_dim, time_dim ) ;\n\n\t// units\n\n\tpulse_length_var->add_att(\"units\", \"seconds\");\n\tthreshold_var->add_att(\"units\", \"dB\");\n\tinitial_time_var->add_att(\"units\", \"seconds\");\n\ttime_var->add_att(\"units\", \"seconds\");\n\tfreq_var->add_att(\"units\", \"hertz\");\n\tenvelopes_var->add_att(\"units\", \"dB\");\n\n\t// data\n\n\tpulse_length_var->put( &_pulse_length ) ;\n\tthreshold_var->put( &_threshold ) ;\n\tinitial_time_var->put( &_initial_time ) ;\n\tfreq_var->put( _envelope_freq->data().begin(), (long) _envelope_freq->size());\n\ttime_var->put( _travel_time->data().begin(), (long) _travel_time->size());\n\n\tfor (size_t a = 0; a < _num_azimuths; ++a) {\n\t\tfor (size_t s = 0; s < _num_src_beams; ++s) {\n\t\t\tfor (size_t r = 0; r < _num_rcv_beams; ++r) {\n\t\t\t\tfor (size_t f = 0; f < _envelope_freq->size(); ++f) {\n\t\t\t\t\tmatrix_row< matrix<double> > row(*_envelopes[a][s][r], f);\n\t\t\t\t\tvector<double> envelope = 10.0*log10(max(row, 1e-30));\n\t\t\t\t\tenvelopes_var->set_cur((long)a, (long)s, (long)r, (long) f, 0L );\n\t\t\t\t\tenvelopes_var->put(envelope.data().begin(), 1L, 1L, 1L, 1L,\n\t\t\t\t\t\t(long) _travel_time->size() );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n    // close file\n\n    delete nc_file; // destructor frees all netCDF temp variables\n}\n", "meta": {"hexsha": "a2d414c1093eabe1f70176627d5227e7219b335c", "size": 6951, "ext": "cc", "lang": "C++", "max_stars_repo_path": "eigenverb/envelope_collection.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "eigenverb/envelope_collection.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "eigenverb/envelope_collection.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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.7877358491, "max_line_length": 81, "alphanum_fraction": 0.6622068767, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19465799562517183}}
{"text": "#include <thread>\n#include <unordered_map>\n#include \"kvmsg.hpp\"\n#include <random>\n#include <format>\n#include <chrono>\n#include <boost/algorithm/string.hpp>\n#include <fmt/core.h>\n\nint gen_num(int a, int b)\n{\n\tstd::random_device rd;  //Will be used to obtain a seed for the random number engine\n\tstd::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()\n\tstd::uniform_int_distribution<> distrib(a, b);\n\treturn distrib(gen);\n}\n\nint main()\n{\n\tusing namespace std::string_literals;\n\tconst std::string SUBTREE = \"/client/\";\n\tstd::unordered_map<std::string, kvmsg> mp;\n\n\tzmqpp::context_t ctx;\n\tzmqpp::socket_t snapshot(ctx, zmqpp::socket_type::dealer);\n\tsnapshot.connect(\"tcp://localhost:5556\");\n\n\tzmqpp::socket_t subscriber(ctx, zmqpp::socket_type::subscribe);\n\tsubscriber.connect(\"tcp://localhost:5557\");\n\tsubscriber.subscribe(SUBTREE);\n\n\tzmqpp::socket_t push(ctx, zmqpp::socket_type::push);\n\tpush.connect(\"tcp://localhost:5558\");\n\n\t// get state snapshot\n\tzmqpp::message_t snmsg;\n\tsnmsg << \"ICANHAZ?\";\n\tsnmsg << SUBTREE;\n\tsnapshot.send(snmsg);\n\n\tint seq{};\n\n\twhile (1) {\n\t\tkvmsg reply(1);\n\t\treply.recv(snapshot);\n\t\tseq = reply.getSequence();\n\n\t\tif (boost::iequals(reply.getKey(), \"KTHXBAI\"s)) {\n\t\t\tfmt::print(\"Received snaphot {}\\n\", seq);\n\t\t\tbreak;\n\t\t}\n\t\tfmt::print(\"Receiving {}\\n\", seq);\n\t\tmp.insert_or_assign(reply.getKey(), reply);\n\t}\n\n\tzmqpp::poller_t poller;\n\tpoller.add(subscriber);\n\n\tconstexpr int INTERVAL = 2000;\n\tauto alarm = std::chrono::steady_clock::now();\n\twhile (true) {\n\t\tpoller.poll(1000);\n\t\tif (poller.events(subscriber) == zmqpp::poller_t::poll_in) {\n\t\t\tkvmsg reply2(0);\n\t\t\treply2.recv(subscriber);\n\n\t\t\tif (reply2.getSequence() > seq) {\n\t\t\t\tfmt::print(\"Received snaphot {}\\n\", reply2.getSequence());\n\t\t\t\tmp.insert_or_assign(reply2.getKey(), reply2);\n\t\t\t}\n\t\t}\n\n\t\tauto diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - alarm).count();\n\t\tif (diff > INTERVAL) {\n\t\t\tauto key = std::format(\"{}{}\", SUBTREE, gen_num(0, 10000));\n\t\t\tauto body = std::format(\"{}\", gen_num(0, 1000000));\n\n\t\t\tkvmsg msg(0);\n\t\t\tmsg.setKey(key);\n\t\t\tmsg.setBody(body);\n\t\t\tmsg.setProp(\"ttl\", std::to_string(gen_num(1, 3)));\n\t\t\tmsg.send(push);\n\t\t\talarm = std::chrono::steady_clock::now();\n\t\t}\n\t}\n\treturn 0;\n}", "meta": {"hexsha": "44b44d8307b2f5da5c7524ea72486bb904bd79df", "size": 2253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "zeromq/5-Advanced Pub-Sub Patterns/5.4-Reliable Pub-Sub (Clone Pattern)/clonecli5.cpp", "max_stars_repo_name": "pvthuyet/books", "max_stars_repo_head_hexsha": "bac5f754a68243e463ec7b0d93610be8807b31ac", "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": "zeromq/5-Advanced Pub-Sub Patterns/5.4-Reliable Pub-Sub (Clone Pattern)/clonecli5.cpp", "max_issues_repo_name": "pvthuyet/books", "max_issues_repo_head_hexsha": "bac5f754a68243e463ec7b0d93610be8807b31ac", "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": "zeromq/5-Advanced Pub-Sub Patterns/5.4-Reliable Pub-Sub (Clone Pattern)/clonecli5.cpp", "max_forks_repo_name": "pvthuyet/books", "max_forks_repo_head_hexsha": "bac5f754a68243e463ec7b0d93610be8807b31ac", "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": 25.8965517241, "max_line_length": 118, "alphanum_fraction": 0.6768752774, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19465799050065175}}
{"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#ifndef PS_CMD_BETTER_SOLVER_H\n#define PS_CMD_BETTER_SOLVER_H\n\n#include <thread>\n#include <numeric>\n#include <atomic>\n#include <bitset>\n#include <fstream>\n#include <unordered_map>\n\n#include <boost/format.hpp>\n#include <boost/assert.hpp>\n\n#include \"app/pretty_printer.h\"\n#include \"ps/base/algorithm.h\"\n#include \"ps/base/board_combination_iterator.h\"\n#include \"ps/base/cards.h\"\n#include \"ps/base/frontend.h\"\n#include \"ps/base/holdem_board_decl.h\"\n#include \"ps/base/rank_hasher.h\"\n#include \"ps/base/suit_hasher.h\"\n#include \"ps/base/tree.h\"\n\n#include \"ps/detail/tree_printer.h\"\n\n#include \"ps/eval/class_cache.h\"\n#include \"ps/eval/pass_mask_eval.h\"\n#include \"ps/eval/instruction.h\"\n\n#include \"ps/support/config.h\"\n#include \"ps/support/index_sequence.h\"\n\n#include <boost/timer/timer.hpp>\n\n#include <boost/log/trivial.hpp>\n\n#include <Eigen/Dense>\n\n#include \"ps/support/command.h\"\n\n#include <boost/iterator/indirect_iterator.hpp>\n#include \"ps/eval/holdem_class_vector_cache.h\"\n#include \"ps/eval/binary_strategy_description.h\"\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <boost/serialization/utility.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/assume_abstract.hpp>\n\n#include \"ps/support/persistent_impl.h\"\n\nnamespace VARR{\nnamespace ExpressionTreeV1{\n        using namespace ps;\n\n\n\n        struct Pair{\n                friend std::ostream& operator<<(std::ostream& ostr, Pair const& self){\n                        ostr << \"a = \" << self.a;\n                        ostr << \", b = \" << self.b;\n                        return ostr;\n                }\n                size_t a;\n                size_t b;\n        };\n        struct VectorComputation{\n                struct Item{\n                        holdem_class_vector cv;\n                        double constant;\n                        std::vector<Pair> index;\n                        Eigen::VectorXd value;\n                };\n                void Add(holdem_class_vector cv, double constant, std::vector<Pair> index, Eigen::VectorXd value){\n                        v_.emplace_back();\n                        v_.back().cv = std::move(cv);\n                        v_.back().constant = constant;\n                        v_.back().index = std::move(index);\n                        v_.back().value = std::move(value);\n                }\n                template<class Filter>\n                Eigen::VectorXd EvalConditional(std::vector<Eigen::VectorXd> const& F, Filter const& filter)const noexcept{\n                        Eigen::VectorXd R(2);\n                        R.fill(0);\n                        double sigma = 0.0;\n                        for(auto const& _ : v_){\n                                if( ! filter(_.index) )\n                                        continue;\n                                double c = _.constant;\n                                for(auto const& p : _.index ){\n                                        c *= F[p.a][p.b];\n                                }\n                                R += c * _.value; \n                                sigma += c;\n                        }\n                        R /= sigma;\n                        return R;\n                }\n                Eigen::VectorXd Eval(std::vector<Eigen::VectorXd> const& F)const noexcept{\n                        return EvalConditional(F, [](auto&& _)noexcept{ return true; });\n                }\n                void Display()const{\n                        using namespace Pretty;\n                        std::vector<Pretty::LineItem> lines;\n                        std::cout << \"v_.size() => \" << v_.size() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,v_.size())\n                        double sigma = 0.0;\n                        Eigen::VectorXd v_sigma = v_.back().value;\n                        v_sigma.fill(0);\n                        for(auto const& _ : v_){\n                                std::vector<std::string> line;\n                                line.push_back( _.cv.to_string() );\n                                line.push_back( boost::lexical_cast<std::string>(_.constant));\n                                line.push_back( detail::to_string(_.index) );\n                                line.push_back( vector_to_string(_.value) );\n                                lines.push_back(std::move(line));\n\n                                sigma += _.constant;\n                                v_sigma += _.value;\n                        }\n                        RenderTablePretty(std::cout, lines);\n                        std::cout << \"sigma => \" << sigma << \"\\n\"; // __CandyPrint__(cxx-print-scalar,sigma)\n                        std::cout << \"vector_to_string(v_sigma) => \" << vector_to_string(v_sigma) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,vector_to_string(v_sigma))\n                }\n        private:\n                std::vector<Item> v_;\n        };\n\n\n        struct HeadsUpComputation{\n                HeadsUpComputation(double sb, double bb, double eff){\n                        std::string cache_name{\".cc.bin\"};\n                        class_cache C;\n                        C.load(cache_name);\n\n                        size_t Index_P  = 0*169;\n                        size_t Index_F  = 1*169;\n                        size_t Index_PP = 2*169;\n                        size_t Index_PF = 3*169;\n\n                        Eigen::VectorXd v_pf(2);\n                        v_pf[0] = +bb;\n                        v_pf[1] = -bb;\n                        \n                        Eigen::VectorXd v_f(2);\n                        v_f[0] = -sb;\n                        v_f[1] = +sb;\n                                        \n                        Eigen::VectorXd eff_v(2);\n                        eff_v.fill(eff);\n\n                        auto vc = std::make_shared<VectorComputation>();\n\n                        for(auto const& group : *Memory_TwoPlayerClassVector){\n                                for(auto const& _ : group.vec){\n                                        auto const& cv = _.cv;\n                        \n\n                                        Eigen::VectorXd ev = C.LookupVector(cv);\n                                        \n\n                                        \n                                        vc->Add(cv, _.prob, std::vector<Pair>{ Pair{0, cv[0] } , Pair{2, cv[1] } }, 2 * eff * ev - eff_v); // pp\n                                        vc->Add(cv, _.prob, std::vector<Pair>{ Pair{0, cv[0] } , Pair{3, cv[1] } }, v_pf); // pf\n                                        vc->Add(cv, _.prob, std::vector<Pair>{ Pair{1, cv[0] }                   }, v_f); // pf\n\n\n                                }\n                        }\n                        vc_ = vc;\n                        vc_->Display();\n                }\n                Eigen::VectorXd Eval(std::vector<Eigen::VectorXd> const& S){\n\n                        #if 0\n                        Eigen::VectorXd F(169 * 4);\n                        F.fill(0);\n                        for(size_t i=0;i!=2;++i){\n                                for(size_t j=0;j!=169;++j){\n                                        F[i  * 169*2 + j       ] = S[i][j];\n                                        F[i  * 169*2 + j + 169 ] = 1.0 - S[i][j];\n                                }\n                        }\n                        #endif\n                        \n                        Eigen::VectorXd R(2);\n                        R.fill(0);\n\n\n                        R = vc_->Eval(S);\n\n                        return R;\n                }\n                void Display(){\n                        vc_->Display();\n                }\n        private:\n                std::shared_ptr<VectorComputation> vc_;\n        };\n\n\n} // end namespace ExpressionTreeV1\n\n\n\n\n\nstruct event_tree{\n\n\n        struct visitor{\n                virtual ~visitor()=default;\n                virtual void path_decl(size_t n, double eff){}\n                virtual void player_fold(event_tree const*, size_t player_idx){}\n                virtual void player_raise(event_tree const*, size_t player_idx, double amt, bool allin){}\n                virtual void post_sb(size_t player_idx, double amt, bool allin){}\n                virtual void post_bb(size_t player_idx, double amt, bool allin){}\n        };\n        struct to_string_visitor : visitor{\n                virtual void path_decl(size_t n, double eff)override{\n                        sstr_ << \"path_decl(\" << n << \",\" << eff << \");\";\n                }\n                virtual void player_fold(event_tree const* EV, size_t player_idx)override{\n                        sstr_ << \"player_fold(\" << map_(EV) << \",\" << player_idx << \");\";\n                }\n                virtual void player_raise(event_tree const* EV, size_t player_idx, double amt, bool allin)override{\n                        sstr_ << \"player_raise(\" << map_(EV)  << \",\"<< player_idx << \",\" << amt << \",\" << allin << \");\";\n                }\n                virtual void post_sb(size_t player_idx, double amt, bool allin)override{\n                        sstr_ << \"post_sb(\" << player_idx << \",\" << amt << \",\" << allin << \");\";\n                }\n                virtual void post_bb(size_t player_idx, double amt, bool allin)override{\n                        sstr_ << \"post_bb(\" << player_idx << \",\" << amt << \",\" << allin << \");\";\n                }\n                std::string to_string()const{ return sstr_.str(); }\n                void clear(){ sstr_.str(\"\"); }\n        private:\n                std::string map_(event_tree const* ev)const{\n                        if( m_.count(ev) == 0 ){\n                                m_[ev] = std::string(1,'A' + m_.size());\n                        }\n                        return m_[ev];\n                }\n                std::stringstream sstr_;\n                mutable std::map<event_tree const*, std::string> m_;\n        };\n\n        using strategy_impl_t = std::vector<Eigen::VectorXd>;\n        using terminals_vector_type = std::vector<std::shared_ptr<event_tree > >;\n\n        virtual std::string to_string()const noexcept{ return \"<>\"; }\n\n        void display(){\n                std::vector<std::vector<event_tree const*> > stack;\n                stack.emplace_back();\n                stack.back().push_back(this);\n                \n                for(;stack.size();){\n                        if( stack.back().empty()){\n                                // A'\n                                stack.pop_back();\n                                continue;\n                        }\n                        auto head = stack.back().back();\n                        stack.back().pop_back();\n                        \n                        std::cout << std::string(stack.size()*2, ' ') << head->to_string() << \"\\n\";\n                        if( ! head->is_terminal()){\n                                stack.emplace_back();\n                                for(size_t i=head->next_.size();i!=0;){\n                                        --i;\n                                        stack.back().push_back(head->next_[i].get());\n                                }\n                        }\n                }\n                using namespace ps;\n                using namespace ps::Pretty;\n                std::vector<Pretty::LineItem> lines;\n                lines.push_back(LineBreak);\n                lines.push_back(std::vector<std::string>{\"non-terminals\"});\n                lines.push_back(LineBreak);\n                for(auto const& _ : non_terminals_){\n                        std::vector<std::string> line{ _->pretty() };\n                        lines.push_back(std::move(line));\n                }\n                lines.push_back(LineBreak);\n                lines.push_back(std::vector<std::string>{\"terminals\"});\n                lines.push_back(LineBreak);\n                for(auto const& _ : terminals_){\n                        std::vector<std::string> line{ _->pretty() };\n                        lines.push_back(std::move(line));\n                }\n                lines.push_back(LineBreak);\n                RenderTablePretty(std::cout, lines);\n        }\n\n        \n        virtual std::string event()const noexcept{ return \"\"; }\n        \n        static std::shared_ptr<event_tree> build(size_t n, double sb, double bb, double eff);\n        static std::shared_ptr<event_tree> build_raise_fold(size_t n, double sb, double bb, double eff);\n        bool is_terminal()const{\n                return next_.empty();\n        }\n        using terminal_iterator = boost::indirect_iterator<terminals_vector_type::const_iterator>;\n        terminal_iterator terminal_begin()const{ return terminals_.begin(); }\n        terminal_iterator terminal_end()const{ return terminals_.end(); }\n\n        terminal_iterator non_terminal_begin()const{ return non_terminals_.begin(); }\n        terminal_iterator non_terminal_end()const{ return non_terminals_.end(); }\n        \n        terminal_iterator children_begin()const{ return next_.begin(); }\n        terminal_iterator children_end()const{ return next_.end(); }\n        \n        terminal_iterator decendent_begin()const{ return decendents_.begin(); }\n        terminal_iterator decendent_end()const{ return decendents_.end(); }\n\n\n        virtual void apply(visitor& v)const{\n                auto p = path();\n                for(auto ptr : p){\n                        ptr->apply_impl(v);\n                }\n        }\n\n        virtual void apply_impl(visitor& v)const{}\n\n        size_t player_idx()const { return player_idx_; }\n        size_t prev_player_idx()const { return parent_->player_idx_; }\n\n        explicit event_tree(size_t player_idx = 0)\n                : player_idx_{player_idx}\n        {}\n\n        std::string pretty()const{\n                to_string_visitor v;\n                apply(v);\n                return v.to_string();\n        }\n        std::vector<event_tree const*> path()const noexcept{\n                std::vector<event_tree const*> path{this};\n                for(;;){\n                        if( path.back()->parent_ == nullptr)\n                                break;\n                        path.push_back(path.back()->parent_);\n                }\n                return std::vector<event_tree const*>{ path.rbegin(), path.rend() };\n        }\nprivate:\n\n        void add_child(std::shared_ptr<event_tree > child){\n                next_.push_back(child);\n                child->parent_ = this;\n        }\n        void finish(){\n                //std::vector<std::shared_ptr<event_tree>> stack{std::shared_ptr<event_tree>(this, [](auto&&_){})};\n                std::vector<std::shared_ptr<event_tree>> stack = next_;\n                for(;stack.size();){\n                        auto head = stack.back();\n                        stack.pop_back();\n                        decendents_.push_back(head);\n                        if( head->is_terminal() ){\n                                terminals_.push_back(head);\n                        } else {\n                                non_terminals_.push_back(head);\n                                std::copy( head->next_.begin(), head->next_.end(), std::back_inserter(stack));\n                        }\n                }\n        }\n        void make_parent(){\n                finish();\n                for(auto ptr : non_terminals_ ){\n                        if( ptr.get() != this ){\n                                ptr->finish();\n                        }\n                }\n        }\n\nprotected:\n        event_tree* parent_{nullptr};\n        std::vector< std::shared_ptr<event_tree> > next_;\n\n        terminals_vector_type terminals_;\n        terminals_vector_type non_terminals_;\n        terminals_vector_type decendents_;\n\n        size_t player_idx_{static_cast<size_t>(-1)};\n\n};\n\nstruct event_tree_hu_sb_bb : event_tree{\n        event_tree_hu_sb_bb(size_t n, double sb, double bb, double eff)\n                : event_tree{0}, n_{n}, sb_{sb}, bb_{bb}, eff_{eff}\n        {}\nprivate:\n        virtual void apply_impl(visitor& v)const override{\n                // sb acts first, so...\n                v.path_decl(n_, eff_);\n                v.post_bb(1, bb_, false);\n                v.post_sb(0, sb_, false);\n        }\n        size_t n_;\n        double sb_;\n        double bb_;\n        double eff_;\n};\nstruct event_tree_sb_bb : event_tree{\n        event_tree_sb_bb(size_t n, double sb, double bb, double eff)\n                : event_tree{0},  n_{n}, sb_{sb}, bb_{bb}, eff_{eff}\n        {}\nprivate:\n        virtual void apply_impl(visitor& v)const override{\n                // this will work for three players\n                v.path_decl(n_, eff_);\n                v.post_sb(1, sb_, false);\n                v.post_bb(2, bb_, false);\n        }\n        size_t n_;\n        double sb_;\n        double bb_;\n        double eff_;\n};\n\nstruct event_tree_push : event_tree{\n        explicit event_tree_push(size_t player_idx, double amt):event_tree{player_idx}, amt_{amt}{}\n        virtual std::string event()const noexcept override{ return \"p\"; }\n        virtual std::string to_string()const noexcept override{ return \"push\"; }\nprivate:\n        virtual void apply_impl(visitor& v)const override{\n                v.player_raise(this, player_idx(), amt_, true);\n        }\n        double amt_;\n};\nstruct event_tree_raise : event_tree{\n        explicit event_tree_raise(size_t player_idx, double amt):event_tree{player_idx}, amt_{amt} {}\n        virtual std::string event()const noexcept override{ return \"r\"; }\n        virtual std::string to_string()const noexcept override{ return \"raise\"; }\nprivate:\n        virtual void apply_impl(visitor& v)const override{\n                v.player_raise(this, player_idx(), amt_, false);\n        }\n        double amt_;\n};\nstruct event_tree_fold : event_tree{\n        explicit event_tree_fold(size_t player_idx):event_tree{player_idx}{}\n        virtual std::string event()const noexcept override{ return \"f\"; }\n        virtual std::string to_string()const noexcept override{ return \"fold\"; }\nprivate:\n        virtual void apply_impl(visitor& v)const override{\n                v.player_fold(this, player_idx());\n        }\n};\n\n\nstd::shared_ptr<event_tree> event_tree::build_raise_fold(size_t n, double sb, double bb, double eff){\n        std::shared_ptr<event_tree> root;\n\n        root = std::make_shared<event_tree_hu_sb_bb>(2, sb, bb, eff);\n        auto p = std::make_shared<event_tree_push>(1, eff - sb);\n        auto r = std::make_shared<event_tree_raise>(1, 2);\n        auto f = std::make_shared<event_tree_fold>(1);\n        root->add_child(p);\n        root->add_child(r);\n        root->add_child(f);\n\n\n        auto pp = std::make_shared<event_tree_push>(0, eff - bb);\n        auto pf = std::make_shared<event_tree_fold>(0);\n        p->add_child(pp);\n        p->add_child(pf);\n\n        auto rp = std::make_shared<event_tree_push>(0, eff - bb);\n        auto rf = std::make_shared<event_tree_fold>(0);\n        \n        r->add_child(rp);\n        r->add_child(rf);\n        \n        auto rpp = std::make_shared<event_tree_push>(1, eff - sb - 2.0);\n        auto rpf = std::make_shared<event_tree_fold>(1);\n        rp->add_child(rpp);\n        rp->add_child(rpf);\n\n        root->make_parent();\n        return root;\n}\nstd::shared_ptr<event_tree> event_tree::build(size_t n, double sb, double bb, double eff){\n        std::shared_ptr<event_tree> root;\n\n        switch(n){\n                case 2:\n                {\n\n                        root = std::make_shared<event_tree_hu_sb_bb>(2, sb, bb, eff);\n                        auto p = std::make_shared<event_tree_push>(0, eff - sb);\n                        auto f = std::make_shared<event_tree_fold>(0);\n                        root->add_child(p);\n                        root->add_child(f);\n\n\n\n                        auto pp = std::make_shared<event_tree_push>(1, eff - bb);\n                        auto pf = std::make_shared<event_tree_fold>(1);\n                        p->add_child(pp);\n                        p->add_child(pf);\n                        \n\n\n                        break;\n\n                }\n                #if 0\n                case 3:\n                {\n                        /*\n                                             <0>\n                                           /     \\\n                                         P         F\n                                         |         |\n                                        <1>       <2>\n                                       /   \\      /  \\\n                                      P    F     P    F\n                                      |    |     |\n                                     <3>  <4>   <5>\n                                     / \\  / \\   / \\\n                                     P F  P F   P F  \n\n                         */\n                        root = std::make_shared<event_tree_sb_bb>(3, sb, bb, eff);\n\n                        auto p = std::make_shared<event_tree_push>(2, 0, eff);\n                        auto f = std::make_shared<event_tree_fold>(2, 0);\n                        root->add_child(p);\n                        root->add_child(f);\n\n                        auto pp = std::make_shared<event_tree_push>(0, 1, eff);\n                        auto pf = std::make_shared<event_tree_fold>(0, 1);\n                        p->add_child(pp);\n                        p->add_child(pf);\n\n                        auto fp = std::make_shared<event_tree_push>(0, 2, eff);\n                        auto ff = std::make_shared<event_tree_fold>(0, 2);\n                        f->add_child(fp);\n                        f->add_child(ff);\n                        \n                        auto ppp = std::make_shared<event_tree_push>(1, 3, eff);\n                        auto ppf = std::make_shared<event_tree_fold>(1, 3);\n                        pp->add_child(ppp);\n                        pp->add_child(ppf);\n                        \n                        auto pfp = std::make_shared<event_tree_push>(1, 4, eff);\n                        auto pff = std::make_shared<event_tree_fold>(1, 4);\n                        pf->add_child(pfp);\n                        pf->add_child(pff);\n\n                        auto fpp = std::make_shared<event_tree_push>(1, 5, eff);\n                        auto fpf = std::make_shared<event_tree_fold>(1, 5);\n                        fp->add_child(fpp);\n                        fp->add_child(fpf);\n\n                        break;\n\n                }\n                #endif\n\n        }\n        root->make_parent();\n        return root;\n\n}\n\n#ifdef NOT_DEFINED\nstruct strategy_decl{\n        \n\n        struct strategy_choice_decl{\n                strategy_choice_decl(event_tree const* ev, size_t idx, size_t player_idx, std::vector<size_t> const& alloc)\n                        :ev_{ev}\n                        ,idx_(idx)\n                        ,player_idx_(player_idx),\n                        alloc_(alloc)\n                {}\n                size_t index()const{ return idx_; }\n                size_t num_choices()const{ return alloc_.size(); }\n                size_t player_index()const{ return player_idx_; }\n                size_t at(size_t idx)const{ return alloc_[idx]; }\n                auto const& alloc()const{ return alloc_; }\n                friend std::ostream& operator<<(std::ostream& ostr, strategy_choice_decl const& self){\n                        ostr << \"idx_ = \" << self.idx_ << \",\";\n                        ostr << \"pretty_ = \" << self.ev_->pretty() << \",\";\n                        ostr << \"player_idx_ = \" << self.player_idx_ << \",\";\n                        typedef std::vector<size_t>::const_iterator CI0;\n                        const char* comma = \"\";\n                        ostr << \"alloc_\" << \" = {\";\n                        for(CI0 iter= self.alloc_.begin(), end=self.alloc_.end();iter!=end;++iter){\n                                ostr << comma << *iter;\n                                comma = \", \";\n                        }\n                        ostr << \"}\\n\";\n                        return ostr;\n                }\n        private:\n                event_tree const* ev_;\n                size_t idx_;\n                size_t player_idx_;\n                std::vector<size_t> alloc_;\n        };\n        \n        size_t dimensions()const{ return s_alloc_.size(); }\n        auto begin()const{ return choies_.begin(); }\n        auto end()const{ return choies_.end(); }\n        size_t s_alloc(event_tree const* ev, size_t cid)const{\n                auto offset = s_alloc_.find(ev)->second;\n                return offset * 169 + cid;\n        }\n\n        auto* root()const{ return root_; }\n\n        friend std::ostream& operator<<(std::ostream& ostr, strategy_decl const& self){\n                ostr << \"dims_ = \" << self.dims_;\n                typedef std::vector<strategy_choice_decl>::const_iterator CI0;\n                const char* comma = \"\";\n                ostr << \"choies_\" << \" = {\";\n                for(CI0 iter= self.choies_.begin(), end=self.choies_.end();iter!=end;++iter){\n                        ostr << comma << *iter;\n                        comma = \", \";\n                }\n                ostr << \"}\\n\";\n                return ostr;\n        }\n        void Display()const{\n                using namespace Pretty;\n                std::vector<Pretty::LineItem> lines;\n                lines.push_back(std::vector<std::string>{\"index\", \"num_choies\", \"player_index\", \"alloc\"});\n                lines.push_back(LineBreak);\n                for(auto const& _ : choies_){\n                        std::vector<std::string> line;\n                        line.push_back( boost::lexical_cast<std::string>(_.index()));\n                        line.push_back( boost::lexical_cast<std::string>(_.num_choices()));\n                        line.push_back( boost::lexical_cast<std::string>(_.player_index()));\n                        line.push_back( detail::to_string(_.alloc()) );\n                        lines.push_back(std::move(line));\n                }\n                RenderTablePretty(std::cout, lines);\n                lines.clear();\n                lines.push_back(std::vector<std::string>{\"idx\", \"pretty\"});\n                lines.push_back(LineBreak);\n                for(auto const& _ : s_alloc_ ){\n                        lines.push_back(std::vector<std::string>{boost::lexical_cast<std::string>(_.second),\n                                                                 _.first->pretty() } );\n                }\n                RenderTablePretty(std::cout, lines);\n        }\nprivate:\n        size_t dims_;\n        event_tree const* root_;\n        std::vector<strategy_choice_decl> choies_;\n        std::map< event_tree const*, size_t> s_alloc_;\n\npublic:\n\n        static strategy_decl generate(event_tree const* root){\n\n                strategy_decl result;\n\n                std::vector< event_tree const*> stack;\n                stack.push_back(root);\n                std::map<event_tree const*, std::vector<event_tree const*> > G;\n                for(;stack.size();){\n                        auto head = stack.back();\n                        stack.pop_back();\n                        if( head->is_terminal()){\n                                continue;\n                        }\n                        for(auto iter=head->children_begin(), end=head->children_end();iter!=end;++iter){\n                                G[head].push_back(&*iter);\n                                stack.push_back(&*iter);\n                        }\n                }\n\n                // I probably want some pretty ordering for strategy\n                std::vector<event_tree const*> alloc_aux;\n                for(auto iter=root->non_terminal_begin(), end=root->non_terminal_end();iter!=end;++iter){\n                        alloc_aux.push_back(&*iter);\n                }\n                #if 0\n                for(auto const& p : G){\n                        for(auto ptr : p.second ){\n                                alloc_aux.push_back(ptr);\n                        }\n                }\n                #endif\n                std::sort(alloc_aux.begin(), alloc_aux.end(), [](auto&& l, auto&& r){ return l->path().size() < r->path().size(); });\n                for(auto ptr : alloc_aux){\n                        result.s_alloc_[ptr] = result.s_alloc_.size();\n                }\n\n\n                typedef std::map<event_tree const*, std::vector<event_tree const*> >::const_iterator VI;\n                for(VI iter(G.begin()), end(G.end());iter!=end;++iter){\n\n                        std::stringstream sstr;\n                        sstr << iter->first << \"->\" << \"{\";\n                        for(size_t j=0;j!=iter->second.size();++j){\n                                if( j != 0 )\n                                        sstr << \", \";\n                                sstr << iter->second[j];\n                        }\n                        sstr << \"}\";\n                        std::cout << sstr.str() << \"\\n\";\n                }\n                \n                size_t choice_idx = 0;\n                for(VI iter(G.begin()), end(G.end());iter!=end;++iter){\n                        std::vector<size_t> alloc;\n                        for(auto ptr : iter->second){\n                                alloc.push_back( result.s_alloc_[ptr] );\n                        }\n                        result.choies_.emplace_back(iter->first, choice_idx, iter->first->player_idx(), std::move(alloc));\n                        ++choice_idx;\n                }\n                result.root_ = root;\n                return result;\n        }\n};\n#endif\n\n\nusing namespace ExpressionTreeV1;\n\nnamespace computation_builder_detail{\n        struct computation_builder_alloc_concept{\n                virtual ~computation_builder_alloc_concept()=default;\n                //virtual size_t alloc(event_tree const* ptr, holdem_class_id cid)const=0;\n                virtual std::vector<Pair> make_index(std::vector<event_tree const*> const& path, holdem_class_vector const& cv)const=0;\n        };\n\n        struct computation_builder_sub{\n                virtual ~computation_builder_sub()=default;\n                virtual void emit(VectorComputation* vc, class_cache const* cache, holdem_class_vector const& cv, double P_cb)const noexcept=0;\n        };\n        struct computation_builder_static : computation_builder_sub{\n                computation_builder_static(std::shared_ptr<computation_builder_alloc_concept> S, event_tree const* term, Eigen::VectorXd V)\n                        : S_{S}, path_{term->path()}, V_{std::move(V)}\n                {}\n                virtual void emit(VectorComputation* vc, class_cache const* cache, holdem_class_vector const& cv, double P_cb)const noexcept override\n                {\n                        #if 0\n                        std::vector<size_t> index;\n                        for(size_t j=0;j +1 < path_.size();++j){\n                                auto ptr = path_[j];\n                                //std::cout << \"ptr->pretty() => \" << ptr->pretty() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,ptr->pretty())\n                                index.push_back( S_->alloc(ptr, cv.at(ptr->player_idx()) ) );\n                        }\n                        #endif\n                        auto index = S_->make_index(path_, cv);\n                        vc->Add(cv, P_cb, std::move(index), V_ );\n                }\n        private:\n                std::shared_ptr<computation_builder_alloc_concept> S_;\n                std::vector<event_tree const*> path_;\n                Eigen::VectorXd V_;\n        };\n        struct computation_builder_eval : computation_builder_sub{\n                computation_builder_eval(std::shared_ptr<computation_builder_alloc_concept> S, event_tree const* term, Eigen::VectorXd A, std::vector<size_t> perm)\n                        : S_{S}, path_{term->path()}, A_{std::move(A)}, perm_{std::move(perm)}\n                {\n                        pot_ = -A_.sum();\n                }\n                virtual void emit(VectorComputation* vc, class_cache const* cache, holdem_class_vector const& cv, double P_cb)const noexcept override\n                {\n                        #if 0\n                        std::vector<size_t> index;\n                        for(size_t j=1;j < path_.size();++j){\n                                auto ptr = path_[j];\n                                index.push_back( S_->alloc(ptr, cv[ptr->player_idx()] ) );\n                        }\n                        std::cout << \"detail::to_string(path_) => \" << detail::to_string(path_) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,detail::to_string(path_))\n                        std::cout << \"detail::to_string(index) => \" << detail::to_string(index) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,detail::to_string(index))\n                        #endif\n                        auto index = S_->make_index(path_, cv);\n\n                        holdem_class_vector aux;\n                        for(auto _ : perm_ ){\n                                aux.push_back(cv[_]);\n                        }\n                        auto ev = cache->LookupVector(aux);\n                        ev *= pot_;\n                        Eigen::VectorXd ev_v(cv.size());\n                        ev_v.fill(0);\n                        size_t out_iter = 0;\n                        for(auto _ : perm_ ){\n                                ev_v[_] = ev[out_iter];\n                                ++out_iter;\n                        }\n\n                        ev_v += A_;\n\n                        vc->Add(cv, P_cb, std::move(index), std::move(ev_v) );\n                }\n        private:\n                std::shared_ptr<computation_builder_alloc_concept> S_;\n                std::vector<event_tree const*> path_;\n                Eigen::VectorXd A_;\n                std::vector<size_t> perm_;\n                double pot_;\n        };\n        struct visitor_impl : event_tree::visitor{\n                virtual void path_decl(size_t n, double eff)override{\n                        for(size_t idx=0;idx!=n;++idx){\n                                Active.insert(idx);\n                        }\n                        Eff = eff;\n                        Delta.resize(n);\n                        Delta.fill(0);\n                }\n                virtual void player_fold(event_tree const*, size_t player_idx)override{\n                        Active.erase(player_idx);\n                }\n                virtual void player_raise(event_tree const*, size_t player_idx, double amt, bool allin)override{\n                        Delta[player_idx] -= amt;\n                }\n                virtual void post_sb(size_t player_idx, double amt, bool allin)override{\n                        Delta[player_idx] -= amt;\n                }\n                virtual void post_bb(size_t player_idx, double amt, bool allin)override{\n                        Delta[player_idx] -= amt;\n                }\n                friend std::ostream& operator<<(std::ostream& ostr, visitor_impl const& self){\n                        ostr << \"Delta = \" << vector_to_string(self.Delta);\n                        ostr << \", Active = \" << detail::to_string(self.Active);\n                        return ostr;\n                }\n                double Eff;\n                Eigen::VectorXd Delta;\n                std::set<size_t> Active;\n        };\n} // end namespace computation_builder_detail\n\nstd::shared_ptr<VectorComputation> build_vc(event_tree const* root){\n        using namespace computation_builder_detail;\n        std::vector<std::shared_ptr<computation_builder_detail::computation_builder_sub> > builders_;\n        struct alloc_type : computation_builder_detail::computation_builder_alloc_concept{\n                explicit alloc_type(event_tree const* root){\n                        for(auto iter = root->decendent_begin(), end = root->decendent_end();iter!=end;++iter){\n                                size_t next = M.size();\n                                M[&*iter] = next;\n                        }\n                }\n                virtual std::vector<Pair> make_index(std::vector<event_tree const*> const& path, holdem_class_vector const& cv)const override{\n                        std::vector<Pair> index;\n                        for(size_t j=1;j < path.size(); ++j){\n                                auto* ptr = path[j];\n                                index.push_back( Pair{ M.find(ptr)->second, cv[ptr->prev_player_idx()] });\n                        }\n                        return index;\n                }\n        private:\n                std::unordered_map<void const*, size_t> M;\n        };\n        auto alloc = std::make_shared<alloc_type>(root);\n        for(auto iter = root->terminal_begin(), end = root->terminal_end();iter!=end;++iter){\n                visitor_impl V;\n                iter->apply(V);\n                std::cout << \"V => \" << V << \"\\n\"; // __CandyPrint__(cxx-print-scalar,V)\n                if( V.Active.size() == 1 ){\n                        auto vec = V.Delta;\n                        auto sum = vec.sum();\n                        auto winner_idx = *V.Active.begin();\n                        vec[winner_idx] -= sum;\n                        std::cout << \"vector_to_string(vec) => \" << vector_to_string(vec) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,vector_to_string(vec))\n                        builders_.push_back( std::make_shared<computation_builder_static>( alloc, &*iter, std::move(vec)) );\n                } else {\n                        std::vector<size_t> perm( V.Active.begin(), V.Active.end() );\n                        builders_.push_back( std::make_shared<computation_builder_eval>(alloc, &*iter, V.Delta, std::move(perm)) );\n                }\n        }\n        auto vc = std::make_shared<VectorComputation>();\n        std::string cache_name{\".cc.bin\"};\n        class_cache C;\n        C.load(cache_name);\n        for(auto const& group : *Memory_TwoPlayerClassVector){\n                for(auto const& _ : group.vec){\n                        auto const& cv = _.cv;\n                        for( auto b : builders_ ){\n                                b->emit( vc.get(), &C, cv, _.prob );\n                        }\n                }\n        }\n        return vc;\n}\n\n} // end namespace VARR\n\nnamespace ps{\n        struct cc_eval_view : binary_strategy_description::eval_view{\n                cc_eval_view(){\n                        std::string cache_name{\".cc.bin\"};\n                        class_cache C;\n                        C.load(cache_name);\n                        cvmem_.reserve(C.size());\n                        for(auto const& p : C){\n                                //S.emplace(p.first, p.second);\n                                cvmem_.push_back(p.first);\n                                support::array_view<holdem_class_id> view(cvmem_.back());\n                                M[view] = p.second;\n                        }\n                }\n                virtual std::vector<double> const* eval_no_perm(support::array_view<holdem_class_id> const& view)const noexcept override{\n                        auto iter = M.find(view);\n                        if( iter == M.end())\n                                return nullptr;\n                        return &iter->second;\n                }\n        private:\n                std::vector<holdem_class_vector> cvmem_;\n                std::unordered_map<\n                        support::array_view<holdem_class_id>, \n                        std::vector<double>,\n                        boost::hash<support::array_view<holdem_class_id> >\n                > M;\n        };\n        #if 0\n        struct cc_eval_view : binary_strategy_description::eval_view{\n                virtual std::vector<double> const* eval_no_perm(holdem_class_vector const& vec)const noexcept override{\n                        return impl_.fast_lookup_no_perm(vec);\n                }\n        private:\n                hash_class_cache impl_;\n        };\n        #endif\n\n        #if 0\n        struct dev_class_cache_item{\n                holdem_class_vector cv;\n                std::vector<double> ev;\n        };\n        inline\n        size_t hash_value(dev_class_cache_item const& item){\n                return boost::hash_range(item.cv.begin(), item.cv.end());\n        }\n        #endif\n\n\n        inline Eigen::VectorXd choose_push_fold(Eigen::VectorXd const& push, Eigen::VectorXd const& fold){\n                Eigen::VectorXd result(169);\n                result.fill(.0);\n                for(holdem_class_id id=0;id!=169;++id){\n                        if( push(id) >= fold(id) ){\n                                result(id) = 1.0;\n                        }\n                }\n                return result;\n        }\n        inline Eigen::VectorXd clamp(Eigen::VectorXd s){\n                for(holdem_class_id idx=0;idx!=169;++idx){\n                        s(idx) = ( s(idx) < .5 ? .0 : 1. );\n                }\n                return s;\n        }\n\n        struct counter_strategy_concept{\n                virtual ~counter_strategy_concept()=default;\n                /*\n                        This is represents the abstract function of figurting out that, given everyone\n                        eles's strategy is constant, should we push or fold each class.\n                                Now to allow optmizations, we take as an argument the last result,\n                        where the state should only be slightly permuated. However this is optional,\n                        and a bad hint don't effect performance.\n                        \n                 */\n                virtual Eigen::VectorXd produce_counter(binary_strategy_description const& strategy_desc,\n                                                        binary_strategy_description::strategy_decl const& decl,\n                                                        binary_strategy_description::strategy_impl_t const& state,\n                                                        boost::optional<Eigen::VectorXd> hint)const=0;\n        };\n        struct counter_strategy_elementwise_batch : counter_strategy_concept{\n                enum{ Debug = false };\n                virtual Eigen::VectorXd produce_counter(binary_strategy_description const& strategy_desc,\n                                                binary_strategy_description::strategy_decl const& decl,\n                                                binary_strategy_description::strategy_impl_t const& state,\n                                                        boost::optional<Eigen::VectorXd> hint)const override\n                {\n                        auto fold_s = decl.make_all_fold(state);\n                        auto push_s = decl.make_all_push(state);\n                                        \n\n                        auto fold_ev = strategy_desc.expected_value_by_class_id(decl.player_index(), fold_s);\n                        auto push_ev = strategy_desc.expected_value_by_class_id(decl.player_index(), push_s);\n                        \n\n                        Eigen::VectorXd counter(169);\n                        counter.fill(0);\n                        for(holdem_class_id cid=0;cid!=169;++cid){\n                                double val = ( fold_ev[cid] <= push_ev[cid] ? 1.0 : 0.0 );\n                                counter[cid] = val;\n                        }\n\n                        if( Debug ){\n                                static std::mutex mtx;\n                                std::lock_guard<std::mutex> lock(mtx);\n                                enum{ Dp = 8 };\n                                std::cout << \"-------------- \" << strategy_desc.string_representation() << \" \" << decl.description() << \"\\n\";\n                                std::cout << \"fold_s\\n\";\n                                pretty_print_strat(fold_s[decl.vector_index()], Dp);\n                                std::cout << \"push_s\\n\";\n                                pretty_print_strat(push_s[decl.vector_index()], Dp);\n                                std::cout << \"fold_ev\\n\";\n                                pretty_print_strat(fold_ev, Dp);\n                                std::cout << \"push_ev\\n\";\n                                pretty_print_strat(push_ev, Dp);\n                                auto delta = push_ev - fold_ev;\n                                std::cout << \"<delta>\\n\";\n                                pretty_print_strat(delta, Dp);\n                                std::cout << \"counter\\n\";\n                                pretty_print_strat(counter, Dp);\n                        }\n                        \n                        return counter;\n                }\n        };\n        struct counter_strategy_elementwise : counter_strategy_concept{\n                virtual Eigen::VectorXd produce_counter(binary_strategy_description const& strategy_desc,\n                                                binary_strategy_description::strategy_decl const& decl,\n                                                binary_strategy_description::strategy_impl_t const& state,\n                                                        boost::optional<Eigen::VectorXd> hint)const override\n                {\n                        auto fold_s = decl.make_all_fold(state);\n                        auto push_s = decl.make_all_push(state);\n\n                        Eigen::VectorXd counter(169);\n                        counter.fill(0);\n                        for(holdem_class_id class_idx=0;class_idx!=169;++class_idx){\n                                auto fold_ev = strategy_desc.expected_value_for_class_id(decl.player_index(),\n                                                                                 class_idx,\n                                                                                 fold_s);\n                                auto push_ev = strategy_desc.expected_value_for_class_id(decl.player_index(),\n                                                                                 class_idx,\n                                                                                 push_s);\n                                double val = ( fold_ev <= push_ev ? 1.0 : 0.0 );\n                                counter[class_idx] = val;\n                        }\n                        return counter;\n                }\n        };\n        struct counter_strategy_aggresive : counter_strategy_concept{\n                enum{ Debug = false };\n                // I think this gives a small increase, ~10%\n                enum{ DisableHint = false };\n                enum MaybeBool{\n                        MB_False,\n                        MB_True,\n                        MB_Unknown,\n                };\n                struct Context{\n                        binary_strategy_description const& strategy_desc;\n                        binary_strategy_description::strategy_decl const& decl;\n                        binary_strategy_description::strategy_impl_t const& state;\n                        boost::optional<Eigen::VectorXd> hint;\n                        binary_strategy_description::strategy_impl_t fold_s;\n                        binary_strategy_description::strategy_impl_t push_s;\n                        size_t derived_counter{0};\n                        std::array<MaybeBool, 169> result;\n\n                        Context( binary_strategy_description const& strategy_desc_,\n                                 binary_strategy_description::strategy_decl const& decl_,\n                                 binary_strategy_description::strategy_impl_t const& state_,\n                                 boost::optional<Eigen::VectorXd> const& hint_)\n                                : strategy_desc(strategy_desc_)\n                                , decl(decl_)\n                                , state(state_)\n                                , fold_s( decl.make_all_fold(state) )\n                                , push_s( decl.make_all_push(state) )\n                        {\n                                result.fill(MB_Unknown);\n\n                                if( ! DisableHint ){\n                                        hint = hint_;\n                                }\n                        }\n                        static std::string mb_to_string(MaybeBool mb){\n                                return ( mb == MB_True  ? \"True\"   :\n                                         mb == MB_False ? \"False\"  :\n                                                          \"Unknown\" );\n                        }\n\n                        void CheckAll()const{\n                                holdem_class_vector false_push;\n                                holdem_class_vector false_fold;\n                                for(size_t idx=0;idx!=169;++idx){\n                                        auto mb = result[idx];\n                                        if(mb == MB_Unknown )\n                                                continue;\n                                        auto check = UnderlyingComputation(idx);\n                                        if( check == mb )\n                                                continue;\n                                        if( mb == MB_True )\n                                                false_push.push_back(idx);\n                                        else\n                                                false_fold.push_back(idx);\n                                }\n                                if( false_push.size() + false_fold.size()){\n                                        std::stringstream sstr;\n                                        sstr << \"fold_push=\" << false_push << \", false_fold=\" << false_fold;\n                                        throw std::domain_error(sstr.str());\n                                }\n                        }\n                        void Check(std::string const& from, size_t idx, MaybeBool mb)const{\n                                auto check = UnderlyingComputation(idx);\n                                #if 0\n                                for(size_t idx=0;idx!=13;++idx){\n                                        std::cout << \"idx => \" << idx << \"\\n\"; // __CandyPrint__(cxx-print-scalar,idx)\n                                        std::cout << \"holdem_class_decl::get(idx) => \" << holdem_class_decl::get(idx) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,holdem_class_decl::get(idx))\n                                }\n                                #endif\n                                if( mb != check ){\n                                        std::stringstream sstr;\n                                        sstr << \"bad check [\" << from << \"]at \" <<  holdem_class_decl::get(idx) \n                                             << \" real=\" << mb_to_string(check)\n                                             << \" vs \" << mb_to_string(mb);\n                                        //std::cout << \"sstr.str() => \" << sstr.str() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,sstr.str())\n                                        throw std::domain_error(sstr.str());\n                                }\n                        }\n                        Eigen::VectorXd Counter()const{\n                                Eigen::VectorXd counter{169};\n                                for(size_t idx=0;idx!=169;++idx){\n                                        switch(result[idx]){\n                                                case MB_True:\n                                                        if( Debug )\n                                                                Check(\"Counter()\", idx, result[idx]);\n                                                        counter[idx] = 1.0;\n                                                        break;\n                                                case MB_False:\n                                                        if( Debug )\n                                                                Check(\"Counter()\", idx, result[idx]);\n                                                        counter[idx] = 0.0;\n                                                        break;\n                                                case MB_Unknown:\n                                                {\n                                                        std::stringstream sstr;\n                                                        sstr << \"not defined \" << holdem_class_decl::get(idx);\n                                                        throw std::domain_error(sstr.str());\n                                                }\n                                        }\n                                }\n                                return counter;\n                        }\n                        MaybeBool GetMaybeValue(holdem_class_id cid)const{\n                                return result[cid];\n                        }\n                        double GetRealValue(holdem_class_id cid)const{\n                                switch(result[cid]){\n                                case MB_True:\n                                        return 1.0;\n                                case MB_False:\n                                        return 0.0;\n                                default:\n                                        throw std::domain_error(\"cid not set\");\n                                }\n                        }\n                        MaybeBool GetMaybeValueOrCompute(holdem_class_id cid){\n                                switch(result[cid]){\n                                        case MB_True:\n                                                return MB_True;\n                                        case MB_False:\n                                                return MB_False;\n                                        case MB_Unknown:\n                                        {\n                                                auto ret = UnderlyingComputation(cid);\n                                                SetValue(cid, ret);\n                                                return ret;\n                                        }\n                                }\n                                PS_UNREACHABLE();\n                        }\n                        void SetValue(holdem_class_id cid, MaybeBool val){\n                                if( result[cid] != MB_Unknown){\n                                        std::cout << \"holdem_class_decl::get(cid) => \" << holdem_class_decl::get(cid) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,holdem_class_decl::get(cid))\n                                        throw std::domain_error(\"cid already sett\");\n                                }\n                                assert( val != MB_Unknown && \"precondition failed\");\n                                result[cid] = val;\n                        }\n                        void TakeDerived(holdem_class_id cid, MaybeBool val){\n                                if( Debug ){\n                                        if( result[cid] != MB_Unknown )\n                                                throw std::domain_error(\"cid already set\");\n                                        Check(\"TakeDerived()\", cid, val);\n                                }\n                                SetValue(cid, val);\n                                ++derived_counter;\n                        }\n                        MaybeBool UnderlyingComputation(holdem_class_id cid)const\n                        {\n                                #if 0\n                                auto fold_ev = strategy_desc.expected_value_for_class_id(decl.player_index(),\n                                                                                         cid,\n                                                                                         fold_s);\n                                auto push_ev = strategy_desc.expected_value_for_class_id(decl.player_index(),\n                                                                                         cid,\n                                                                                         push_s);\n                                #else\n                                \n                                auto fold_ev = decl.expected_value_for_class_id(cid, fold_s);\n                                auto push_ev = decl.expected_value_for_class_id(cid, push_s);\n                                #endif\n                                #if 0\n                                std::cout << \"[\" << holdem_class_decl::get(cid) << \"] \";\n                                std::cout << \"fold_ev => \" << fold_ev << \"\\n\"; // __CandyPrint__(cxx-print-scalar,fold_ev)\n                                #endif\n                                return ( fold_ev <= push_ev ? MB_True : MB_False );\n                        }\n\n                };\n                struct Op{\n                        virtual void push_or_fold(Context& ctx)const=0;\n                        virtual std::string to_string()const=0;\n                };\n                struct Row : Op, holdem_class_vector{\n                        virtual MaybeBool Compute(Context& ctx, holdem_class_id cid)const{\n                                return ctx.GetMaybeValueOrCompute(cid);\n                        }\n                        virtual void push_or_fold(Context& ctx)const override{\n                                // we just start at the front untill we find one that is zero\n                                auto start = find_bounary(ctx);\n\n                                if( Debug ){\n                                        if( start != 0 ){\n                                                ctx.Check(\"Row<T>()\", at(start-1), MB_True);\n                                        }\n                                        if( start != size() ){\n                                                ctx.Check(\"Row<F>()\", at(start), MB_False);\n                                        }\n                                }\n\n\n                                for(size_t idx=start;idx!=size();++idx){\n                                        auto cid = at(idx);\n                                        if(ctx.GetMaybeValue(cid) == MB_Unknown ){\n                                                ctx.TakeDerived(cid, MB_False);\n                                        }\n                                }\n                                for(size_t idx=0;idx!=start;++idx){\n                                        auto cid = at(idx);\n                                        if(ctx.GetMaybeValue(cid) == MB_Unknown ){\n                                                ctx.TakeDerived(cid, MB_True);\n                                        }\n                                }\n                        }\n                        virtual std::string to_string()const{\n                                std::stringstream sstr;\n                                sstr << \"Row{\" << *this << \"}\";\n                                return sstr.str();\n                        }\n                        // returns the index one after the first item in the row\n                        // for which is false, or the end of the sequence otherwise\n                        //\n                        //\n                        // \\return \\in [1,size()]\n                        //  0 => 0\n                        //  1 => 10\n                        //  2 => 110\n                        //  ...\n                        //  size()-1 =>  11..10\n                        //  size()   => 11...1\n                        size_t find_bounary(Context& ctx)const{\n                                double epsilon = 1e-5;\n                                size_t idx = 0;\n\n                                if( ctx.hint ){\n                                        auto const& hint = *ctx.hint;\n                                        for(; idx+1<size();++idx){\n                                                auto cid = at(idx);\n                                                if( std::fabs(hint[cid]) < epsilon ){\n                                                        // we have found the boundry\n                                                        break;\n                                                }\n                                        }\n                                }\n\n                                if( Compute(ctx, at(idx)) == MB_True ){\n                                        // if we have one that is true, we want to find the first false one\n                                        ++idx;\n                                        for(; idx!= size(); ++idx){\n                                                if( Compute(ctx, at(idx)) == MB_False ){\n                                                        return idx;\n                                                }\n                                        }\n                                        return size();\n                                } else {\n                                        // else we have found a fold, we want to find the first true one\n                                        for(;idx!=0;){\n                                                --idx;\n                                                if( Compute(ctx, at(idx)) == MB_True){\n                                                        return idx+1;\n                                                }\n                                        }\n                                        // if we get here, they are all false\n                                        return 0;\n                                }\n                                PS_UNREACHABLE();\n                        }\n                };\n                struct SuitedRow : Row{\n                        virtual MaybeBool Compute(Context& ctx, holdem_class_id cid)const override{\n                                auto const& decl = holdem_class_decl::get(cid);\n                                auto offsuit_cid = holdem_class_decl::make_id(holdem_class_type::offsuit, decl.first(), decl.second());\n                                switch(ctx.GetMaybeValue(offsuit_cid)){\n                                        case MB_True:\n                                        {\n                                                // if the offsuit card is true, then flush must be true\n                                                ctx.TakeDerived(cid, MB_True);\n                                                return MB_True;\n                                        }\n                                        // if the offsuit card is false, then maybe\n                                        case MB_False:\n                                        case MB_Unknown:\n                                        {\n                                                auto ret = ctx.UnderlyingComputation(cid);\n                                                ctx.SetValue(cid, ret);\n                                                return ret;\n                                        }\n                                }\n                                PS_UNREACHABLE();\n                        }\n                };\n                counter_strategy_aggresive(){\n\n                        /*\n                                The idea is that for any strategy, we ALWAYS have the constaruct that \n                                the top-left to bottom-right diagonal is monotonic. \n\n                                                   A K Q J T 9 8 7 6 5 4 3 2 \n                                                  +--------------------------\n                                                A |1 1 1 1 1 1 1 1 1 1 1 1 1\n                                                K |1 1 1 1 1 1 1 1 1 1 1 1 1\n                                                Q |1 1 1 1 1 1 1 1 0 0 0 0 0\n                                                J |1 1 1 1 1 1 1 0 0 0 0 0 0\n                                                T |1 1 1 1 1 1 0 0 0 0 0 0 0\n                                                9 |1 1 1 0 0 1 0 0 0 0 0 0 0\n                                                8 |1 1 0 0 0 0 1 0 0 0 0 0 0\n                                                7 |1 1 0 0 0 0 0 1 0 0 0 0 0\n                                                6 |1 1 0 0 0 0 0 0 1 0 0 0 0\n                                                5 |1 1 0 0 0 0 0 0 0 1 0 0 0\n                                                4 |1 0 0 0 0 0 0 0 0 0 1 0 0\n                                                3 |1 0 0 0 0 0 0 0 0 0 0 1 0\n                                                2 |1 0 0 0 0 0 0 0 0 0 0 0 1\n\n                                This strategy is that we want, for each diagonal on the offsuit side, \n                                we want to choose which is the point where either \n                                                The right end is One => all One\n                                                The left end is Zero => all zero\n                                                X is One and  X+1 is Zero \n\n                                        ( A2 )\n                                        ( A3, K2 )\n                                        ( A4, K3, Q2 )\n                                        ( A5, K4, Q3, J2 )\n                                        ( A6, K5, Q4, J3, T2 )\n                                        ( A7, K6, Q5, J4, T3, 92 )\n                                        ( A8, K7, Q6, J5, T4, 93, 82 )\n                                        ( A9, K8, Q7, J6, T5, 94, 83, 72 )\n                                        ( AT, K9, Q8, J7, T6, 95, 84, 73, 62 )\n                                        ( AJ, KT, Q9, J8, T7, 96, 85, 74, 63, 52 )\n                                        ( AQ, KJ, QT, J9, T8, 97, 86, 75, 64, 53, 42)\n                                        ( AK, KQ, QJ, JT, T9, 98, 87, 76, 65, 54, 43, 32)\n\n                                With this parametrization, we don't have to worry that A5 is better than A6 sometimes, because \n                                they are in different rows\n\n\n\n                         */\n                        auto pp = std::make_shared<Row>();\n                        for(size_t A=13;A!=0;){\n                                --A;\n                                pp->push_back( holdem_class_decl::make_id(holdem_class_type::pocket_pair, A, A));\n                        }\n                        ops_.push_back(pp);\n\n                        for(size_t d = 1; d != 13; ++d){\n                                auto ptr = std::make_shared<Row>();\n                                for(size_t A=13;A!=0;){\n                                        --A;\n                                        if( A >= d ){\n                                                ptr->push_back( holdem_class_decl::make_id(holdem_class_type::offsuit, A, A-d));\n                                        }\n                                }\n                                ops_.push_back(ptr);\n                        }\n\n                        for(size_t d = 1; d != 13; ++d){\n                                auto ptr = std::make_shared<SuitedRow>();\n                                for(size_t A=13;A!=0;){\n                                        --A;\n                                        if( A >= d ){\n                                                ptr->push_back( holdem_class_decl::make_id(holdem_class_type::suited, A, A-d));\n                                        }\n                                }\n                                ops_.push_back(ptr);\n                        }\n\n\n                        if( Debug ){\n                                for(auto const& _ : ops_){\n                                        std::cout << _->to_string() << \"\\n\";\n                                }\n                        }\n                }\n                virtual Eigen::VectorXd produce_counter(binary_strategy_description const& strategy_desc,\n                                                binary_strategy_description::strategy_decl const& decl,\n                                                binary_strategy_description::strategy_impl_t const& state,\n                                                boost::optional<Eigen::VectorXd> hint)const override\n                {\n                        Eigen::VectorXd counter(169);\n                        counter.fill(0);\n                        Context ctx(strategy_desc, decl, state, hint);\n                        for(auto const& _ : ops_){\n                                _->push_or_fold(ctx);\n                        }\n                        if( Debug ){\n                                std::cout << \"ctx.derived_counter => \" << ctx.derived_counter << \"\\n\"; // __CandyPrint__(cxx-print-scalar,ctx.derived_counter)\n                        }\n                        return ctx.Counter();\n                }\n        private:\n                std::vector<std::shared_ptr<Op> > ops_;\n        };\n\n        // basically a wrapper class\n        struct holdem_binary_strategy{\n                holdem_binary_strategy()=default;\n                /* implicit */ holdem_binary_strategy(std::vector<Eigen::VectorXd> const& state){\n                        for(auto const& vec : state){\n                                state_.emplace_back();\n                                state_.back().resize(vec.size());\n                                for(size_t idx=0;idx!=vec.size();++idx){\n                                        state_.back()[idx] = vec[idx];\n                                }\n                        }\n                }\n                std::vector<Eigen::VectorXd> to_eigen()const{\n                        std::vector<Eigen::VectorXd> tmp;\n                        for(auto const& v : state_){\n                                Eigen::VectorXd ev(v.size());\n                                for(size_t idx=0;idx!=v.size();++idx){\n                                        ev[idx] = v[idx];\n                                }\n                                tmp.push_back(std::move(ev));\n                        }\n                        return tmp;\n                }\n        private:\n                friend class boost::serialization::access;\n                template<class Archive>\n                void serialize(Archive & ar, const unsigned int version){\n                        ar & state_;\n                }\n        private:\n                std::vector< std::vector<double> > state_;\n        };\n\n        template<class ImplType>\n        struct serialization_base{\n                void load(std::string const& path){\n                        std::lock_guard<std::mutex> lock(mtx_);\n                        using archive_type = boost::archive::text_iarchive;\n                        std::ifstream ofs(path);\n                        archive_type oa(ofs);\n                        oa >> *reinterpret_cast<ImplType*>(this);\n                        path_ = path;\n                }\n                // returns true indicte that load from disk\n                // returns false to indicate that an empty object represention\n                //         was created and loaded from disk\n                bool try_load_or_default(std::string const& path){\n                        try{\n                                load(path);\n                                return true;\n                        }catch(...){\n                                // clear it\n                                auto typed = reinterpret_cast<ImplType*>(this);\n                                typed->~ImplType();\n                                new(typed)ImplType;\n                                // now write to disk\n                                save_as(path);\n                                // no load it again so any error is apprent now\n                                load(path);\n                                return false;\n                        }\n                }\n                void save_as(std::string const& path)const {\n                        std::lock_guard<std::mutex> lock(mtx_);\n                        using archive_type = boost::archive::text_oarchive;\n                        std::ofstream ofs(path);\n                        archive_type oa(ofs);\n                        oa << *reinterpret_cast<ImplType const*>(this);\n                }\n                void save_()const{\n                        if( path_.size() ){\n                                save_as(path_);\n                        }\n                }\n        private:\n                mutable std::mutex mtx_;\n                std::string path_;\n        };\n\n        struct holdem_binary_strategy_ledger : serialization_base<holdem_binary_strategy_ledger>{\n                void push(holdem_binary_strategy s){\n                        ledger_.emplace_back(std::move(s));\n                }\n                size_t size()const{ return ledger_.size(); }\n                auto const& back()const{ return ledger_.back(); }\n        private:\n                friend class boost::serialization::access;\n                template<class Archive>\n                void serialize(Archive & ar, const unsigned int version){\n                        ar & ledger_;\n                }\n        private:\n                std::vector<holdem_binary_strategy> ledger_;\n        };\n\n        struct holdem_binary_solution_set : serialization_base<holdem_binary_solution_set>{\n                void add_solution(std::string const& key, holdem_binary_strategy solution){\n                        std::lock_guard<std::mutex> lock(mtx_);\n                        solutions_.emplace(key, std::move(solution));\n                }\n                // there are no thread safe\n                auto begin()const{ return solutions_.begin(); }\n                auto end()const{ return solutions_.end(); }\n                auto find(std::string const& key)const{ return solutions_.find(key); }\n        private:\n                friend class boost::serialization::access;\n                template<class Archive>\n                void serialize(Archive & ar, const unsigned int version){\n                        ar & solutions_;\n                }\n        private:\n                std::mutex mtx_;\n                // in our scope we can represent everyting in a string, ie\n                // we might want to encode the sb:bb:eff:stragery etc here\n                std::map<std::string, holdem_binary_strategy> solutions_;\n        };\n\n\n        struct Continue{};\n        struct Break{ std::string msg; };\n        struct Error{ std::string msg; };\n        struct SmallerFactor{};\n\n        using  holdem_binary_solver_ctrl = boost::variant<Continue, Break, Error, SmallerFactor>;\n\n        struct holdem_binary_solver;\n\n        struct holdem_binary_solver_any_observer{\n                using state_type = binary_strategy_description::strategy_impl_t;\n                explicit holdem_binary_solver_any_observer(std::string const& name):name_{name}{}\n                virtual ~holdem_binary_solver_any_observer()=default;\n                virtual holdem_binary_solver_ctrl start(holdem_binary_solver const*, state_type const& state){ return Continue{}; }\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const*, state_type const& from, state_type const& to){ return Continue{}; }\n                virtual holdem_binary_solver_ctrl finish(holdem_binary_solver const*, state_type const& state){ return Continue{}; }\n                virtual void imbue(holdem_binary_solver* solver){}\n\n                std::string const& get_name()const{ return name_; }\n\n                virtual size_t precedence()const{ return 10; }\n        private:\n                std::string name_;\n        };\n\n        struct holdem_binary_solver_result{\n                using state_type = binary_strategy_description::strategy_impl_t;\n                state_type state;\n                size_t n{0};\n                holdem_binary_solver_ctrl stop_condition;\n                \n                bool success()const{\n                        return ( boost::get<Break>(&stop_condition) != nullptr );\n                }\n        };\n        struct holdem_binary_solver{\n                using state_type = binary_strategy_description::strategy_impl_t;\n                void use_description(std::shared_ptr<binary_strategy_description> desc){\n                        desc_ = desc;\n                }\n                void use_strategy(std::shared_ptr<counter_strategy_concept> counter_strat){\n                        counter_strategy_ = counter_strat;\n                }\n                void add_observer(std::shared_ptr<holdem_binary_solver_any_observer> obs){\n                        obs->imbue(this);\n                        obs_.push_back(obs);\n                }\n                template<class T>\n                T const* get_observer()const{\n                        for(auto const& _ : obs_){\n                                if( _->get_name() == T::static_get_name()){\n                                        return reinterpret_cast<T const*>(_.get());\n                                }\n                        }\n                        return nullptr;\n                }\n                // this is intended to be used for the Imbue section\n                template<class T>\n                void use_observer(){\n                        auto ptr = this->get_observer<T>();\n                        if( ptr == nullptr){\n                                add_observer( std::make_shared<T>() );\n                        }\n                }\n                void use_inital_state(state_type state){\n                        initial_state_ = std::move(state);\n                }\n                holdem_binary_solver_result compute(){\n\n                        std::stable_sort(obs_.begin(), obs_.end(), [](auto const& r, auto const& l){\n                                return r->precedence() < l->precedence();\n                        });\n\n                        std::vector<boost::optional<Eigen::VectorXd> > hint_vector(desc_->strat_vector_size());\n\n                        auto step = [&](auto const& state)->state_type\n                        {\n                                struct Task{\n                                        binary_strategy_description::strategy_decl const* sd;\n                                        Eigen::VectorXd solution;\n                                };\n                                using result_t = std::future<Task>;\n                                std::vector<result_t> tmp;\n                                for(auto si=desc_->begin_strategy(),se=desc_->end_strategy();si!=se;++si){\n                                        auto fut = std::async(std::launch::async, [&,sd=*si](){\n                                                auto sol = counter_strategy_->produce_counter(*desc_,\n                                                                                              sd,\n                                                                                              state,\n                                                                                              hint_vector[sd.vector_index()]);\n                                                hint_vector[sd.vector_index()] = sol;\n                                                return Task{&sd, std::move(sol)};\n                                        });\n                                        tmp.emplace_back(std::move(fut));\n                                }\n                                auto result = state;\n                                for(auto& _ : tmp){\n                                        auto ret = _.get();\n                                        auto idx            = ret.sd->vector_index();\n                                        auto const& counter = ret.solution;\n                                        result[idx] = state[idx] * ( 1.0 - factor_ ) + counter * factor_;\n                                }\n                                return result;\n                        };\n                        \n                        state_type state;\n\n                        if( initial_state_ ){\n                                state = *initial_state_;\n                        } else {\n                                state = desc_->make_inital_state();\n                        }\n                        \n\n\n                        for(auto& _ : obs_ ){\n                                _->start(this, state);\n                        }\n\n                        auto finish = [&](auto const& result){\n                                for(auto& _ : obs_ ){\n                                        _->finish(this, result);\n                                }\n                        };\n\n                        size_t n = 0;\n                        for(;;++n){\n                                auto next = step(state);\n\n                                for(auto& _ : obs_ ){\n                                        auto result = _->step(this, state, next);\n                                        if( auto ptr = boost::get<Continue>(&result)){\n                                                continue;\n                                        }\n                                        if( auto ptr = boost::get<Break>(&result)){\n                                                finish(state);\n                                                return { state, n, result };\n                                        }\n                                        if( auto ptr = boost::get<Error>(&result)){\n                                                finish(state);\n                                                return { state, n, result };\n                                        }\n                                        if( auto ptr = boost::get<SmallerFactor>(&result)){\n                                                std::cerr << \"changing factor\\n\";\n                                                factor_ /= 2.0;\n                                                continue;\n                                        }\n                                        PS_UNREACHABLE();\n                                }\n\n                                state = next;\n                        }\n                        PS_UNREACHABLE();\n                }\n                std::shared_ptr<binary_strategy_description> get_description()const{\n                        return desc_;\n                }\n        private:\n                boost::optional<state_type> initial_state_;\n                // desripbes the game\n                std::shared_ptr<binary_strategy_description> desc_;\n                // computes the coutner strategy\n                std::shared_ptr<counter_strategy_concept> counter_strategy_;\n\n                // all the observers\n                std::vector<std::shared_ptr<holdem_binary_solver_any_observer> > obs_;\n\n                double factor_{0.10};\n        };\n\n        struct table_observer : holdem_binary_solver_any_observer{\n                table_observer(binary_strategy_description* desc, bool print_step = false)\n                        : holdem_binary_solver_any_observer{\"table_observer\"}, desc_{desc}, print_step_{print_step}\n                {\n                        using namespace Pretty;\n                        std::vector<std::string> header;\n                        header.push_back(\"n\");\n                        for(auto si=desc->begin_strategy(),se=desc->end_strategy();si!=se;++si){\n                                header.push_back(si->action());\n                        }\n                        header.push_back(\"max\");\n                        for(size_t idx=0;idx!=desc->num_players();++idx){\n                                std::stringstream sstr;\n                                sstr << \"ev[\" << idx << \"]\";\n                                header.push_back(sstr.str());\n                        }\n                        header.push_back(\"time\");\n                        lines.push_back(std::move(header));\n                        lines.push_back(LineBreak);\n\n                        timer.start();\n                }\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const*, state_type const& from, state_type const& to)override{\n\n                        std::vector<std::string> norm_vec_s;\n                        std::vector<double> norm_vec;\n\n                        for(size_t idx=0;idx!=from.size();++idx){\n                                auto delta = from[idx] - to[idx];\n                                auto norm = delta.lpNorm<1>();\n                                norm_vec.push_back(norm);\n                        }\n                        auto norm = *std::max_element(norm_vec.begin(),norm_vec.end());\n\n                        for(auto val : norm_vec){\n                                norm_vec_s.push_back(boost::lexical_cast<std::string>(val));\n                        }\n                        norm_vec_s.push_back(boost::lexical_cast<std::string>(norm));\n                        using namespace Pretty;\n                        std::vector<std::string> line;\n                        line.push_back(boost::lexical_cast<std::string>(n_));\n                        for(size_t idx=0;idx!=norm_vec_s.size();++idx){\n                                line.push_back(boost::lexical_cast<std::string>(norm_vec_s[idx]));\n                        }\n\n                        auto ev = desc_->expected_value(to);\n                        for(size_t idx=0;idx!=desc_->num_players();++idx){\n                                line.push_back(boost::lexical_cast<std::string>(ev[idx]));\n                        }\n                        line.push_back(format(timer.elapsed(), 2, \"%w(%t cpu)\"));\n                        timer.start();\n                        lines.push_back(std::move(line));\n                        ++n_;\n                        last_ = to;\n\n                        // don't want this for hu\n                        if( print_step_ ){\n                                RenderTablePretty(std::cout, lines);\n                        }\n\n                        return Continue{};\n                }\n                virtual holdem_binary_solver_ctrl finish(holdem_binary_solver const*, state_type const& state)override{\n\n                        RenderTablePretty(std::cout, lines);\n                        return Continue{};\n                }\n        private:\n                binary_strategy_description* desc_;\n                bool print_step_;\n                size_t n_{0};\n                std::vector<Pretty::LineItem> lines;\n                boost::timer::cpu_timer timer;\n                boost::optional<state_type> last_;\n        };\n        \n        struct lp_inf_stoppage_condition : holdem_binary_solver_any_observer{\n                explicit lp_inf_stoppage_condition(double epsilon = 0.005)\n                        : holdem_binary_solver_any_observer{\"lp_inf_stoppage_condition\"}\n                        , epsilon_{epsilon}\n                {}\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const*, state_type const& from, state_type const& to)override{\n                        std::vector<double> norm_vec;\n                        for(size_t idx=0;idx!=from.size();++idx){\n                                auto delta = from[idx] - to[idx];\n                                auto norm = delta.lpNorm<1>();\n                                norm_vec.push_back(norm);\n                        }\n                        auto norm = *std::max_element(norm_vec.begin(),norm_vec.end());\n\n                        bool cond = norm < epsilon_;\n                        if( cond )\n                                return Break{\"lp_inf_stoppage_condition\"};\n                        return Continue{};\n                }\n        private:\n                double epsilon_;\n        };\n        // for this stoppage condtiion, we want that the ev is less than norm\n        struct ev_diff_stoppage_condition : holdem_binary_solver_any_observer{\n                explicit ev_diff_stoppage_condition(double epsilon = 0.000001, size_t stride = 1)\n                        : holdem_binary_solver_any_observer{\"ev_diff_stoppage_condition\"}\n                        , epsilon_{epsilon}, stride_{stride}\n                {\n                        assert( stride != 0 );\n                }\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const* solver, state_type const& from, state_type const& to)override{\n                        if( ++count_ % stride_ != 0 )\n                                return Continue{};\n                        auto desc = solver->get_description();\n                        auto from_ev = desc->expected_value(from);\n                        auto to_ev = desc->expected_value(to);\n\n                        auto delta = from_ev - to_ev;\n                        auto norm = delta.lpNorm<1>();\n                        auto cond = ( norm < epsilon_ );\n                        if( cond ){\n                                std::stringstream sstr;\n                                sstr << std::fixed;\n                                sstr << \"ev_diff_stoppage_condition: norm=\" << norm << \", epsilon=\" << epsilon_;\n                                return Break{sstr.str()};\n                        }\n                        return Continue{};\n                }\n        private:\n                double epsilon_;\n                size_t stride_;\n                size_t count_{0};\n        };\n        struct ev_seq : holdem_binary_solver_any_observer{\n                static std::string static_get_name(){ return \"ev_seq\"; }\n                ev_seq() : holdem_binary_solver_any_observer{static_get_name()}{}\n                struct min_max_type{\n                        double min_;\n                        double max_;\n\n                        double delta()const{ return max_ - min_; }\n                };\n\n                virtual void imbue(holdem_binary_solver* solver)override{\n                        n_ = solver->get_description()->num_players();\n                }\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const* solver, state_type const& from, state_type const& to)override{\n                        auto desc = solver->get_description();\n                        auto to_ev = desc->expected_value(to);\n                        seq_.push_back(to_ev);\n                        return Continue{};\n                }\n                boost::optional<std::vector<min_max_type> > make_min_max(size_t lookback)const{\n                        Eigen::VectorXd min_(n_), max_(n_);\n                        min_.fill(+DBL_MAX);;\n                        max_.fill(-DBL_MAX);\n                        if(seq_.size() < lookback )\n                                return boost::none;\n                        for(size_t idx=lookback; idx!=0;){\n                                --idx;\n                                auto const& v = seq_[seq_.size()-1-idx];\n                                for(size_t j=0;j!=v.size();++j){\n                                        if( v[j] < min_[j]){\n                                                min_[j] = v[j];\n                                        }\n                                        if( v[j] > max_[j]){\n                                                max_[j] = v[j];\n                                        }\n                                }\n                        }\n                        std::vector<min_max_type> result;\n                        for(size_t idx=0;idx!=n_;++idx){\n                                result.emplace_back( min_max_type{ min_[idx], max_[idx] } );\n                        }\n                        return result;\n                }\n                virtual size_t precedence()const override{ return 0; }\n        private:\n                size_t n_{0};\n                std::vector< Eigen::VectorXd > seq_;\n        };\n\n        struct ev_seq_printer : holdem_binary_solver_any_observer{\n                ev_seq_printer(): holdem_binary_solver_any_observer{\"ev_seq_printer\"}{}\n                virtual void imbue(holdem_binary_solver* solver)override{\n                        solver->use_observer<ev_seq>();\n                }\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const* solver, state_type const& from, state_type const& to)override{\n                        enum{ Lookback = 100 };\n\n                        auto ptr = solver->get_observer<ev_seq>();\n                        if( ! ptr )\n                                return Continue{};\n\n                        auto opt = ptr->make_min_max(Lookback);\n                        if( ! opt )\n                                return Continue{};\n                        table_.push_back(std::move(*opt));\n\n                        using namespace Pretty;\n                        std::vector<LineItem> lines;\n                        lines.push_back(std::vector<std::string>{\"range[0]\", \"delta[0]\", \"range[1]\", \"delta[1]\"});\n                        lines.push_back(LineBreak);\n                        for(auto const& row : table_){\n                                std::vector<std::string> line;\n                                for(auto const& col : row ){\n                                        std::stringstream sstr;\n                                        sstr << std::fixed << std::setprecision(10);\n                                        sstr << \"(\" << col.min_ << \",\" << col.max_ << \")\";\n                                        line.emplace_back(sstr.str());\n                                        sstr.str(\"\");\n                                        sstr << col.max_ - col.min_;\n                                        line.emplace_back(sstr.str());\n                                }\n                                lines.push_back(std::move(line));\n                        }\n                        RenderTablePretty(std::cout, lines);\n                        return Continue{};\n\n                }\n                std::vector< std::vector< ev_seq::min_max_type > > table_;\n        };\n\n        struct ev_seq_break : holdem_binary_solver_any_observer{\n                explicit ev_seq_break(double epsilon): holdem_binary_solver_any_observer{\"ev_seq_break\"}, epsilon_{epsilon}{}\n                virtual void imbue(holdem_binary_solver* solver)override{\n                        solver->use_observer<ev_seq>();\n                }\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const* solver, state_type const& from, state_type const& to)override{\n                        enum{ Lookback = 100 };\n\n                        auto ptr = solver->get_observer<ev_seq>();\n                        if( ! ptr )\n                                return Continue{};\n\n                        auto opt = ptr->make_min_max(Lookback);\n                        if( ! opt )\n                                return Continue{};\n\n                        auto delta =  opt->at(0).delta();\n                        auto cond = ( delta < epsilon_ );\n                        if( cond ){\n                                std::stringstream sstr;\n                                sstr << std::fixed << std::setprecision(10);\n                                sstr << \"ev_seq_break: delta=\" << delta << \", epsilon=\" << epsilon_;\n                                return Break{sstr.str()};\n                        }\n                        return Continue{};\n                }\n        private:\n                double epsilon_;\n        };\n\n\n\n        /*\n                This is to detect cyclic solutions\n\n                We have this situation where a partition S = A \\union B of the solution set,\n                where every sequence of id's in A is constant, and every id in B is non-monotonic\n\n                This excludes the sitation when we have one id which is monotonic, \n         */\n        struct state_seq : holdem_binary_solver_any_observer{\n                enum{ Lookback = 30 };\n                enum{ Debug = true };\n                static std::string static_get_name(){ return \"state_seq\"; }\n                state_seq() : holdem_binary_solver_any_observer{static_get_name()}{}\n\n                virtual void imbue(holdem_binary_solver* solver)override{\n                        n_ = solver->get_description()->num_players();\n                }\n                virtual size_t precedence()const override{ return 0; }\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const* solver, state_type const& from, state_type const& to)override{\n\n                        state_seq_.push_back(to);\n\n                        if( state_seq_.size() < Lookback )\n                                return Continue{};\n\n\n                        auto is_non_increasing = [](auto const& seq){\n                                double epsilon =1e-5;\n                                bool result = true;\n                                for(size_t idx=0;idx+1<seq.size();++idx){\n                                        bool cond = ( seq[idx] - epsilon < seq[idx+1]);\n                                        if( ! cond )\n                                                return false;\n                                }\n                                return true;\n                        };\n                        auto is_non_decreasing = [](auto const& seq){\n                                double epsilon =1e-5;\n                                bool result = true;\n                                for(size_t idx=0;idx+1<seq.size();++idx){\n                                        bool cond = ( seq[idx] + epsilon > seq[idx+1]);\n                                        if( ! cond )\n                                                return false;\n                                }\n                                return true;\n                        };\n                        auto is_monotonic = [&](auto const& seq){\n                                return is_non_increasing(seq) || is_non_decreasing(seq);\n                        };\n                        auto is_constant = [](auto C, auto const& seq){\n                                double epsilon =1e-5;\n                                for(auto s : seq){\n                                        bool cond = ( std::fabs(s - C ) < epsilon );\n                                        if( ! cond )\n                                                return false;\n                                }\n                                return true;\n                        };\n                        \n                        bool result = true;\n\n\n                        struct Item{\n                                size_t idx;\n                                size_t cid;\n                        };\n                        std::vector<Item> constant;\n                        std::vector<Item> monotonic;\n                        std::vector<Item> non_monoonic;\n\n                        size_t start_idx = state_seq_.size() - Lookback;\n                        std::vector<double > seq;\n\n                        // for each degree of state (2 for hu, 6 for three players )\n                        for(size_t j=0;j!=n_;++j){\n                                // for each class id\n                                for(size_t k=0;k!=169;++k){\n                                        // for each lag\n                                        for(size_t idx=start_idx;idx!=state_seq_.size();++idx){\n                                                // want to consider each sequence\n                                                auto const& S = state_seq_[idx][j];\n                                                seq.push_back(S[k] );\n                                        }\n\n                                        if( is_monotonic(seq) ){\n                                                if( is_constant(0.0, seq) || is_constant(1.0, seq)){\n                                                        constant.push_back(Item{j,k});\n                                                } else {\n                                                        monotonic.push_back(Item{j,k});\n                                                }\n                                        } else {\n                                                non_monoonic.push_back(Item{j,k});\n                                        }\n                                        seq.clear();\n                                }\n                        }\n\n                        bool cyclic_solution = ( monotonic.empty() && non_monoonic.size() );\n\n\n                        if( cyclic_solution ){\n                                std::stringstream sstr;\n                                sstr << \"state_seq: \";\n                                std::vector<holdem_class_vector> aux;\n                                aux.resize(n_);\n                                for(auto const& p : non_monoonic ){\n                                        aux[p.idx].push_back(p.cid);\n                                }\n                                std::string sep;\n                                for(auto const& cv : aux){\n                                        sstr << sep << cv;\n                                        sep = \",\";\n                                }\n\n                                if( Debug ){\n                                        std::cout << sstr.str() << \"\\n\";\n                                }\n                                #if 0\n                                return Break{sstr.str()};\n                                #endif\n                                state_seq_.clear();\n                                return SmallerFactor{};\n                        }\n                        return Continue{};\n                }\n        private:\n                size_t n_{0};\n                std::vector< state_type > state_seq_;\n        };\n\n\n\n\n        struct max_steps_condition : holdem_binary_solver_any_observer{\n                explicit max_steps_condition(size_t n):holdem_binary_solver_any_observer{\"max_steps_condition\"}, n_{n}{}\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const* solver, state_type const& from, state_type const& to)override{\n                        if( ++count_ > n_){\n                                std::stringstream sstr;\n                                sstr << \"Done \" << n_ << \" steps for \" << solver->get_description()->string_representation();\n                                return Break{sstr.str()};\n                        }\n                        return Continue{};\n                }\n        private:\n                size_t n_;\n                size_t count_{0};\n        };\n        struct max_steps_error_condition : holdem_binary_solver_any_observer{\n                explicit max_steps_error_condition(size_t n):holdem_binary_solver_any_observer{\"max_steps_error_condition\"}, n_{n}{}\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const* solver, state_type const& from, state_type const& to)override{\n                        if( ++count_ > n_){\n                                std::stringstream sstr;\n                                sstr << \"Too many steps (\" << n_ << \") for \" << solver->get_description()->string_representation();\n                                return Error{sstr.str()};\n                        }\n                        return Continue{};\n                }\n        private:\n                size_t n_;\n                size_t count_{0};\n        };\n        struct strategy_printer : holdem_binary_solver_any_observer{\n                enum{ Dp = 2 };\n                strategy_printer():holdem_binary_solver_any_observer{\"strategy_printer\"}{}\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const* solver, state_type const& from, state_type const& to)override{\n                        auto desc = solver->get_description();\n                        for(auto si=desc->begin_strategy(),se=desc->end_strategy();si!=se;++si){\n                                std::cout << si->description() << \"\\n\";\n                                pretty_print_strat(to[si->vector_index()], Dp);\n                        }\n                        return Continue{};\n                }\n        private:\n                binary_strategy_description* desc_;\n        };\n\n        struct solver_ledger : holdem_binary_solver_any_observer{\n                explicit solver_ledger(std::shared_ptr<holdem_binary_strategy_ledger> ledger)\n                        : holdem_binary_solver_any_observer{\"solver_ledger\"}\n                        , ledger_{ledger}\n                {}\n                virtual holdem_binary_solver_ctrl step(holdem_binary_solver const*, state_type const& from, state_type const& to)override{\n                        ledger_->push(to);\n                        ledger_->save_();\n                        return Continue{};\n                }\n                virtual void imbue(holdem_binary_solver* solver)override{\n                        if( ledger_->size() ){\n                                auto state0 = ledger_->back().to_eigen();\n                                solver->use_inital_state(std::move(state0));\n                        }\n                }\n        private:\n                std::shared_ptr<holdem_binary_strategy_ledger> ledger_;\n        };\n\n        /*\n                Computing the push/fold table for three players is computation intensive,\n                and takes hours to solve for each effective stack, so we need code that\n                can handle the restarting, saving of jobs\n         */\n        struct computation_decl{\n                double SB{0.5};\n                double BB{1.0};\n                size_t N{2};\n                std::string Directory;\n                std::vector<double> EffectiveStacks;\n        };\n        struct computation_manager{\n                struct work_item{\n                        enum{ Debug = true };\n                        // args\n                        work_item(binary_strategy_description::eval_view* eval,\n                                  std::string const& key,\n                                  std::string const& ledger_name,\n                                  double sb, double bb, size_t n, double eff)\n                                :key_{key}\n                                ,ledger_name_(ledger_name),\n                                sb_(sb),\n                                bb_(bb),\n                                n_(n),\n                                eff_(eff)\n                        {\n                                switch(n_){\n                                        case 2:\n                                        {\n                                                desc_ = binary_strategy_description::make_hu_description(eval, sb_, bb_, eff_);\n                                                break;\n                                        }\n                                        case 3:\n                                        {\n                                                desc_ = binary_strategy_description::make_three_player_description(eval, sb_, bb_, eff_);\n                                                break;\n                                        }\n                                        default:\n                                        {\n                                                throw std::domain_error(\"unsupported\");\n                                        }\n                                }\n                        }\n                        double sb()const{ return sb_; }\n                        double bb()const{ return bb_; }\n                        double eff()const{ return eff_; }\n                        binary_strategy_description::strategy_impl_t solution()const{\n                                return solution_;\n                        }\n                        binary_strategy_description const* description()const{ return desc_.get(); }\n                        void display()const{\n                                std::cout << \"sb_ => \" << sb_ << \"\\n\"; // __CandyPrint__(cxx-print-scalar,sb_)\n                                std::cout << \"bb_ => \" << bb_ << \"\\n\"; // __CandyPrint__(cxx-print-scalar,bb_)\n                                std::cout << \"eff_ => \" << eff_ << \"\\n\"; // __CandyPrint__(cxx-print-scalar,eff_)\n\n                                for(auto const& s : solution_){\n                                        pretty_print_strat(s, 0);\n                                        std::cout << \"\\n\";\n                                }\n                        }\n\n                        void solution_hint(binary_strategy_description::strategy_impl_t const& hint){\n                                hint_ = hint;\n                        }\n                private:\n                        friend struct computation_manager;\n                        void load(holdem_binary_solution_set* mgr){\n                                auto iter = mgr->find(key_);\n                                if( iter == mgr->end()){\n                                        compute_single();\n                                        mgr->add_solution(key_, solution_);\n                                        mgr->save_();\n                                } else{\n                                        solution_ = iter->second.to_eigen();\n                                }\n                        }\n                        void compute_single(){\n                                auto ledger = std::make_shared<holdem_binary_strategy_ledger>();\n                                if( ledger->try_load_or_default(ledger_name_ ) == false ){\n                                        if( hint_ ){\n                                                ledger->push(*hint_);\n                                        }\n                                } else {\n                                        std::cout << \"loaded ledger of side \" << ledger->size() << \" (\" << ledger_name_ << \")\\n\";\n                                }\n                                std::cout << \"doing \" << desc_->string_representation() << \"\\n\";\n                                holdem_binary_solver solver;\n                                solver.use_description(desc_);\n                                solver.use_strategy(std::make_shared<counter_strategy_aggresive>());\n                                //solver.use_strategy(std::make_shared<counter_strategy_elementwise_batch>());\n                                if( n_ == 2 ){\n                                        solver.add_observer(std::make_shared<table_observer>(desc_.get(), false));\n                                } else {\n                                        solver.add_observer(std::make_shared<table_observer>(desc_.get(), true));\n                                        solver.add_observer(std::make_shared<strategy_printer>());\n                                }\n                                //solver.add_observer(std::make_shared<solver_ledger>(ledger));\n                                solver.add_observer(std::make_shared<lp_inf_stoppage_condition>(lp_epsilon_));\n                                solver.add_observer(std::make_shared<max_steps_condition>(max_steps_));\n                                solver.add_observer(std::make_shared<state_seq>());\n\n                                auto result = solver.compute();\n                                if( result.success()){\n                                        for(auto& _ : result.state){\n                                                _ = clamp(_);\n                                        }\n                                }\n                                solution_ = result.state;\n                        }\n                private:\n                        // inputs\n                        std::string key_;\n                        std::string ledger_name_;\n                        double sb_;\n                        double bb_;\n                        size_t n_;\n                        double eff_;\n\n                        double lp_epsilon_{0.05};\n                        size_t max_steps_{200};\n\n\n                        // data\n                        std::shared_ptr<binary_strategy_description> desc_;\n                        //holdem_binary_strategy_ledger ledger;\n\n                        binary_strategy_description::strategy_impl_t solution_;\n\n                        boost::optional<binary_strategy_description::strategy_impl_t> hint_;\n                };\n                computation_manager(computation_decl const& decl){\n                        #if 0\n                        if( decl.Directory.size() ){\n                                mkdir(decl.Directory.c_str());\n                        }\n                        #endif\n                        for(auto eff : decl.EffectiveStacks ){\n                                std::stringstream ledger_name;\n                                if( decl.Directory.size() ){\n                                        ledger_name << decl.Directory << \"/\";\n                                }\n                                ledger_name << decl.N << \":\" << decl.SB << \":\" << decl.BB << \":\" << eff;\n                                std::string name = ledger_name.str();\n                                std::string key = name; // for now\n                                auto item =std::make_shared<work_item>(&eval_,\n                                                                       name,\n                                                                       key,\n                                                                       decl.SB,\n                                                                       decl.BB,\n                                                                       decl.N,\n                                                                       eff);\n                                items_.push_back(item);\n                        }\n                        mgr_.try_load_or_default(\".computation_mgr_other\");\n                }\n                void compute(){\n                        std::vector<std::future<void> > v;\n                        for(auto const& ptr : items_){\n                                v.push_back(std::async([this,p=ptr](){ p->load(&mgr_); }));\n                        }\n                }\n                void compute_serial(){\n                        for(size_t idx=0;idx!=items_.size();++idx){\n                                items_[idx]->load(&mgr_);\n                                if( idx+1 < items_.size()){\n                                        items_[idx+1]->solution_hint( items_[idx]->solution() );\n                                }\n                        }\n                }\n                using items_vector_type = std::vector<std::shared_ptr<work_item> >;\n                using iterator = boost::indirect_iterator<items_vector_type::const_iterator>;\n                iterator begin()const{ return items_.begin(); }\n                iterator end()const{ return items_.end(); }\n        private:\n                items_vector_type items_;\n                holdem_binary_solution_set mgr_;\n                cc_eval_view eval_;\n        };\n\n        \n        struct SolverCmd : Command{\n                struct PrintStrat{\n                        void operator()(computation_manager const& mgr)const{\n                                using state_type = binary_strategy_description::strategy_impl_t;\n                                state_type state;\n                                for(auto const& sol : mgr){\n                                        auto desc = sol.description();\n                                        auto eff        = desc->eff();\n                                        auto const& vec = sol.solution();\n                                        for(; state.size() < vec.size();){\n                                                state.emplace_back(169);\n                                                state.back().fill(0.0);\n                                        }\n                                        for(size_t i=0;i!=vec.size();++i){\n                                                for(size_t cid=0;cid!=169;++cid){\n                                                        if( state[i][cid] < eff*vec[i][cid] ){\n                                                                state[i][cid] = eff*vec[i][cid];\n                                                        }\n                                                }\n                                        }\n                                }\n                                for(auto const& s : state){\n                                        pretty_print_strat(s, 1);\n                                        std::cout << \"\\n\";\n                                }\n                        }\n                };\n                struct PrintEv{\n                        void operator()(computation_manager const& mgr)const{\n                                using namespace Pretty;\n                                std::vector<LineItem> lines;\n                                lines.push_back(std::vector<std::string>{\"Eff\", \"SB\", \"BB\"});\n                                lines.push_back(LineBreak);\n                                for(auto const& sol : mgr){\n                                        auto desc = sol.description();\n                                        auto ev = desc->expected_value(sol.solution());\n                                        std::vector<std::string> line;\n                                        char buf[18];\n                                        std::sprintf(buf, \"%.1f\", desc->eff());\n                                        line.push_back(buf);\n                                        for(size_t idx=0;idx!=ev.size();++idx){\n                                                line.push_back(boost::lexical_cast<std::string>(ev[idx]));\n                                        }\n\n                                        using namespace VARR;\n\n                                        do{\n                                                auto et = event_tree::build(2, 0.5, 1.0, desc->eff());\n                                                auto ev = build_vc(et.get());\n                                                static bool first = true;\n                                                if( first ){\n                                                        first = false;\n                                                        et->display();\n                                                        ev->Display();\n                                                }\n\n                                                std::vector<Eigen::VectorXd> S(4);\n                                                auto const& s = sol.solution();\n                                                for(size_t idx=0;idx!=4;++idx){\n                                                        S[idx].resize(169);\n                                                }\n                                                for(size_t idx=0;idx!=169;++idx){\n                                                        S[0][idx] = s[0][idx];\n                                                        S[1][idx] = 1.0 - s[0][idx];\n                                                        S[2][idx] = 1.0 - s[1][idx];\n                                                        S[3][idx] = s[1][idx];\n                                                }\n\n                                                auto ret = ev->Eval(S);\n                                                \n                                                for(size_t idx=0;idx!=ret.size();++idx){\n                                                        line.push_back(boost::lexical_cast<std::string>(ret[idx]));\n                                                }\n                                        }while(0);\n                                        lines.push_back(std::move(line));\n                                        RenderTablePretty(std::cout, lines);\n\n                                }\n                                RenderTablePretty(std::cout, lines);\n                        }\n                };\n                enum{ Debug = 1};\n                explicit\n                SolverCmd(std::vector<std::string> const& args):args_{args}{}\n                virtual int Execute()override{\n\n                        computation_decl cd;\n                        std::string dir = \".SolverCacheOther\";\n                        cd.Directory = dir;\n                        double start_eff = 2.0;\n\n                        double d = 0.1;\n                        if( args_.size() && args_[0] == \"three\"){\n                                cd.N = 3;\n                                d = 1.0;\n                                start_eff = 10.0;\n                        }\n\n                        for(double eff=start_eff;eff-1e-5 < 20.0;eff += d ){\n                                cd.EffectiveStacks.push_back(eff);\n                        }\n\n                        computation_manager mgr(cd);\n                        mgr.compute();\n                        //mgr.compute_serial();\n\n                        std::vector<std::function<void(computation_manager const&)> > views {\n                                PrintStrat{}, PrintEv{} \n                        };\n                        for(auto const& view : views){\n                                view(mgr);\n                        }\n\n\n\n                        #if 0\n                        std::shared_ptr<binary_strategy_description> desc;\n                        std::string ledger_path;\n                        if( args_.size() && args_[0] == \"three\"){\n                                desc = binary_strategy_description::make_three_player_description(0.5, 1, 10);\n                                ledger_path = \".3_player_ledger.bin\";\n                        } else{\n                                desc = binary_strategy_description::make_hu_description(0.5, 1, 6);\n                                ledger_path = \".2_player_ledger.bin\";\n                        }\n\n                        holdem_binary_solver solver;\n                        solver.use_description(desc);\n                        solver.use_strategy(std::make_shared<counter_strategy_aggresive>());\n\n                        solver.add_observer(std::make_shared<ev_seq_printer>());\n                        //solver.add_observer(std::make_shared<ev_seq_break>(5e-5));\n                        solver.add_observer(std::make_shared<table_observer>(desc.get()));\n                        //solver.add_observer(std::make_shared<solver_ledger>(ledger_path));\n                        solver.add_observer(std::make_shared<strategy_printer>());\n                        solver.add_observer(std::make_shared<lp_inf_stoppage_condition>());\n                        //solver.add_observer(std::make_shared<ev_diff_stoppage_condition>());\n\n                        auto result = solver.compute();\n                        if( auto ptr = boost::get<Break>(&result.stop_condition)){\n                                std::cerr << \"Break: \" << ptr->msg << \"\\n\";\n                                for(auto& _ : result.state){\n                                        _ = clamp(_);\n                                }\n                        } else if( auto ptr = boost::get<Error>(&result.stop_condition)){\n                                std::cerr << \"Error: \" << ptr->msg << \"\\n\";\n                        } else{\n                                std::cerr << \"unknown093\\n\";\n                        }\n                        #endif\n\n                        return EXIT_SUCCESS;\n                }\n        private:\n                std::vector<std::string> const& args_;\n        };\n        static TrivialCommandDecl<SolverCmd> SolverCmdDecl{\"solver\"};\n        \n} // end namespace ps\n\n#endif // PS_CMD_BETTER_SOLVER_H\n", "meta": {"hexsha": "8af62fc76f7db24f38f3596ca0e832184a4bc980", "size": 124304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Trash/cmd_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/cmd_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/cmd_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": 48.9771473601, "max_line_length": 190, "alphanum_fraction": 0.3976782726, "num_tokens": 20990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.34864512856608554, "lm_q1q2_score": 0.19465798159745273}}
{"text": "//\n//  helper.cpp\n//  Project: humid\n//\n//\tAll rights reserved. Use of this source code is governed by the\n//\t3-clause BSD License in LICENSE.txt.\n\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n#include <iomanip>\n#include <sstream>\n#include \"colourhelper.h\"\n#include \"valuehelper.h\"\n#include \"structure.h\"\n\n\nstatic int val(char hex) {\n\tint res = 0;\n\tif (hex >= 'a') hex -= 32;\n\tif (hex >= 'A') {\n\t\tres = 10 + hex - 'A';\n\t\tif (res >= 16) res = 0;\n\t}\n\telse if (hex >= '0') {\n\t\tres = hex - '0';\n\t\tif (res >= 10) res = 0;\n\t}\n\treturn res;\n}\n\nnanogui::Color colourFromString(const std::string &colour) {\n\tstruct Colour { int r, g, b, a; };\n\tColour c{0, 0, 0, 0};\n\tauto len = colour.length();\n\tauto dbl = [](int val) -> int { return val * 16 + val; };\n\tauto parse = [](const char * &p) -> int { int res = val(*p++); return res * 16 + val(*p++); };\n\tconst char *p = colour.c_str() + 1;\n\tif (colour[0] == '#') {\n\t\tif (len == 4 || len ==5) {\n\t\t\t// #rgb format, with or without alpha\n\t\t\tauto dbl = [](int val) -> int { return val * 16 + val; };\n\t\t\tc = {\n\t\t\t\t.r = dbl(val(*p++)),\n\t\t\t\t.g = dbl(val(*p++)),\n\t\t\t\t.b = dbl(val(*p++)),\n\t\t\t\t.a = (len == 5) ? dbl(val(*p)) : 255\n\t\t\t};\n\t\t}\n\t\telse if (len == 7 || len == 9) {\n\t\t\t// #rrggbb format with or without alpha\n\t\t\tc = {\n\t\t\t\t.r = parse(p),\n\t\t\t\t.g = parse(p),\n\t\t\t\t.b = parse(p),\n\t\t\t\t.a = len == 9 ? parse(p) : 255\n\t\t\t};\n\t\t}\n\t}\n\telse if (colour[0] == '&') {\n\t\tauto len = colour.length();\n\t\tif (len == 3) {\n\t\t\t// #ga where c is a grey intensity level and a is an alpha level\n\t\t\tauto grey = dbl(val(*p++));\n\t\t\tc = {\n\t\t\t\t.r = grey,\n\t\t\t\t.g = grey,\n\t\t\t\t.b = grey,\n\t\t\t\t.a = dbl(val(*p))\n\t\t\t};\n\t\t}\n\t\telse if (len == 5) {\n\t\t\tauto grey = parse(p);\n\t\t\tc = {\n\t\t\t\t.r = grey,\n\t\t\t\t.g = grey,\n\t\t\t\t.b = grey,\n\t\t\t\t.a = parse(p)\n\t\t\t};\n\t\t}\n\t}\n\treturn nanogui::Color(nanogui::Vector4i{c.r, c.g, c.b, c.a});\n}\n\nstd::string stringFromColour(const nanogui::Color &colour) {\n\n\tstd::stringstream ss;\n\tss << '#' << std::hex << std::setfill('0') \n\t\t<< std::setw(2) << static_cast<int>(colour.r()*255) \n\t\t<< std::setw(2) << static_cast<int>(colour.g()*255)  \n\t\t<< std::setw(2) << static_cast<int>(colour.b()*255);\n\tif (colour.w() != 1.0)\n\t\tss << std::setw(2) <<static_cast<int>(colour.w()*255);\n\treturn ss.str();\n}\n\nnanogui::Color colourFromProperty(Structure *element, const std::string &prop) {\n\treturn colourFromProperty(element, prop.c_str());\n}\n\nnanogui::Color colourFromProperty(Structure *element, const char *prop) {\n\tValue colour(element->getValue(prop));\n\tif (colour == SymbolTable::Null) {\n\t\tcolour = defaultForProperty(prop);\n\t}\n\tif (colour != SymbolTable::Null) {\n\t\tstd::string colour_str = colour.asString();\n\t\tif (colour_str[0] == '#' || colour_str[0] == '&') {\n\t\t\treturn colourFromString(colour_str);\n\t\t}\n\t\tstd::vector<std::string> tokens;\n\t\tboost::algorithm::split(tokens, colour_str, boost::is_any_of(\",\"));\n\t\tif (tokens.size() == 4) {\n\t\t\tstd::vector<float>fields(4);\n\t\t\tfor (int i=0; i<4; ++i) fields[i] = std::atof(tokens[i].c_str());\n\t\t\treturn nanogui::Color(fields[0], fields[1], fields[2], fields[3]);\n\t\t}\n\t\telse if (tokens.size() == 3) {\n\t\t\tstd::vector<float>fields(3);\n\t\t\tfor (int i=0; i<4; ++i) fields[i] = std::atof(tokens[i].c_str());\n\t\t\treturn nanogui::Color(fields[0], fields[1], fields[2], 1.0f);\n\t\t}\n\t\telse {\n\t\t\tstd::cerr << \"unrecognised colour: \" << colour << \"\\n\";\n\t\t}\n\t}\n\treturn nanogui::Color(0.0f, 0.0f, 0.0f, 1.0f);\n}\n\n", "meta": {"hexsha": "b8fc9fdb401df1845ecee8e6e2f159d3c3091011", "size": 3375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/colourhelper.cpp", "max_stars_repo_name": "latproc/humid", "max_stars_repo_head_hexsha": "dfd111c74e6cedddff82e078faa1c507080d2529", "max_stars_repo_licenses": ["curl", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-28T10:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T10:34:42.000Z", "max_issues_repo_path": "src/colourhelper.cpp", "max_issues_repo_name": "latproc/humid", "max_issues_repo_head_hexsha": "dfd111c74e6cedddff82e078faa1c507080d2529", "max_issues_repo_licenses": ["curl", "BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2019-07-04T23:18:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-31T13:16:34.000Z", "max_forks_repo_path": "src/colourhelper.cpp", "max_forks_repo_name": "latproc/humid", "max_forks_repo_head_hexsha": "dfd111c74e6cedddff82e078faa1c507080d2529", "max_forks_repo_licenses": ["curl", "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.1627906977, "max_line_length": 95, "alphanum_fraction": 0.5626666667, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.19465169680112743}}
{"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// File generated at Thu 10 May 2018 14:40:04\n\n#ifndef MSSMEFTHiggs_mAmu_INPUT_PARAMETERS_H\n#define MSSMEFTHiggs_mAmu_INPUT_PARAMETERS_H\n\n#include <complex>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nstruct MSSMEFTHiggs_mAmu_input_parameters {\n   double MSUSY{};\n   double M1Input{};\n   double M2Input{};\n   double M3Input{};\n   double MuInput{};\n   double mAInput{};\n   double TanBeta{};\n   Eigen::Matrix<double,3,3> mq2Input{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> mu2Input{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> md2Input{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> ml2Input{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> me2Input{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> AuInput{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> AdInput{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> AeInput{Eigen::Matrix<double,3,3>::Zero()};\n\n\n   Eigen::ArrayXd get() const;\n   void set(const Eigen::ArrayXd&);\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMEFTHiggs_mAmu_input_parameters&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "6034f4d49e725b1e4a55d6e1a71cca9df7031106", "size": 2013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs_mAmu/MSSMEFTHiggs_mAmu_input_parameters.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs_mAmu/MSSMEFTHiggs_mAmu_input_parameters.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs_mAmu/MSSMEFTHiggs_mAmu_input_parameters.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 35.9464285714, "max_line_length": 83, "alphanum_fraction": 0.6696472926, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.19465168916207215}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <limits>\n#include <cmath>\n#include <opencv2/opencv.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include <thread>\n#include <chrono>\n#include <mutex>\n#include <math.h>\n#include <glob.h>\n\nextern \"C\" {\n  #include <vl/generic.h>\n  #include <vl/slic.h>\n}\n\nconst int ANN_TRAINING_SET_LIMIT = 500000;\nconst int ANN_EPOC_INCREMENT = 5;\nconst int DSEG_GRID_SIZE = 16;\nconst int DSEG_POINTS_THRESHOLD = 8;\nconst int DSEG_MAX_IMG_SIZE = 800;\nconst int DSEG_POSITIVE_SCALE_START = 1;\nconst int DSEG_POSITIVE_SCALE_END = 60;\nconst int DSEG_NEGATIVE_SCALE_START = 5;\nconst int DSEG_NEGATIVE_SCALE_END = 45;\nconst int DSEG_MAX_OPAQUE_IMAGES = 2000;\nconst int DSEG_DATA_SIZE = DSEG_GRID_SIZE * DSEG_GRID_SIZE + 4;\nconst float DSEG_REGION_RATIO = 0.25;\nconst float DSEG_REGULARIZATION = 4000.0;\nstd::random_device rd;\nstd::mt19937 g(rd());\n\n// vector addition\ntemplate <typename T>\nstd::vector<T>& operator+=(std::vector<T>& a, const std::vector<T>& b)\n{\n    a.insert(a.end(), b.begin(), b.end());\n    return a;\n}\n\ninline float sq(float n) {\n  return n * n;\n}\n\ninline int sq(int n) {\n  return n * n;\n}\n\nfloat dist3d(float x1, float y1, float z1, float x2, float y2, float z2) {\n  return sqrt(sq(x1 - x2) + sq(y1 - y2) + sq(z1 - z2));\n}\n\ninline int max(int a, int b) {\n  if (a >= b)\n    return a;\n  return b;\n}\n\ninline int min(int a, int b) {\n  if (a <= b)\n    return a;\n  return b;\n}\n\nvoid fill_magic_pink(cv::Mat &mat) {\n  for(int x = 0; x < mat.cols; x++) {\n    for(int y = 0; y < mat.rows; y++) {\n      if(mat.at<cv::Vec3b>(x, y)[0] == 0 &&\n         mat.at<cv::Vec3b>(x, y)[1] == 0 &&\n         mat.at<cv::Vec3b>(x, y)[2] == 0)\n      {\n        mat.at<cv::Vec3b>(x, y)[0] = 255;\n        mat.at<cv::Vec3b>(x, y)[1] = 0;\n        mat.at<cv::Vec3b>(x, y)[2] = 255;\n      }\n    }\n  }\n}\n\nclass DColor {\n  public:\n    unsigned char r;\n    unsigned char g;\n    unsigned char b;\n};\n\ninline bool is_magic_pink(DColor color) {\n  return color.r == 255 && color.g == 0 && color.b == 255;\n}\n\nclass DPos {\n  public:\n    unsigned int x;\n    unsigned int y;\n};\n\nDPos make_pos(int x, int y) {\n  DPos pos;\n  pos.x = x;\n  pos.y = y;\n  return pos;\n}\n\nclass BSegment {\n  public:\n    int id;\n    int r_sum = 0;\n    int g_sum = 0;\n    int b_sum = 0;\n    int x_sum = 0;\n    int y_sum = 0;\n    DPos center_pos;\n    DColor main_color;\n    DColor avg_color;\n    std::vector<DPos> positions;\n    std::vector<DColor> colors;\n\n    void add_pixel(int x, int y, unsigned char r, unsigned char g, unsigned char b) {\n      DColor color;\n      color.r = r;\n      color.g = g;\n      color.b = b;\n      if (is_magic_pink(color))\n        return;\n      DPos pos;\n      pos.x = x;\n      pos.y = y;\n      positions.push_back(pos);\n      r_sum += (int)r;\n      g_sum += (int)g;\n      b_sum += (int)b;\n      x_sum += x;\n      y_sum += y;\n      colors.push_back(color);\n    }\n\n    void compute_averages() {\n      if (positions.size() == 0)\n        return;\n      // calculate center_pos\n      center_pos.x = x_sum / positions.size();\n      center_pos.y = y_sum / positions.size();\n      // find color closest to average color\n      avg_color.r = (unsigned char)(r_sum / positions.size());\n      avg_color.g = (unsigned char)(g_sum / positions.size());\n      avg_color.b = (unsigned char)(b_sum / positions.size());\n      float closest_dist = std::numeric_limits<float>::max();\n      for(DColor color : colors) {\n        float dist = dist3d(color.r, color.g, color.b, avg_color.r, avg_color.g, avg_color.b);\n        if (dist < closest_dist) {\n          closest_dist = dist;\n          main_color = color;\n        }\n      }\n    }\n};\n\nclass DSegment {\n  public:\n    DColor cta_color; // closest color to average\n    cv::Mat patch_orig;\n    cv::Mat patch_resized;\n};\n\nclass DFeatVect {\n  public:\n    char data[DSEG_GRID_SIZE * DSEG_GRID_SIZE + 4];\n\n    void set_color(DColor color) {\n      data[DSEG_GRID_SIZE * DSEG_GRID_SIZE + 1] = (char)color.r;\n      data[DSEG_GRID_SIZE * DSEG_GRID_SIZE + 2] = (char)color.g;\n      data[DSEG_GRID_SIZE * DSEG_GRID_SIZE + 3] = (char)color.b;\n    }\n\n    void set_grid(cv::Mat &mat) {\n      for(int x = 0; x < DSEG_GRID_SIZE; x++)\n        for(int y = 0; y < DSEG_GRID_SIZE; y++)\n          data[y * DSEG_GRID_SIZE + x] = 255 - mat.at<unsigned char>(x, y);\n    }\n};\n\nDFeatVect make_feature_vector(DSegment dseg) {\n  DFeatVect feat;\n  feat.set_grid(dseg.patch_resized);\n  feat.set_color(dseg.cta_color);\n  return feat;\n}\n\nclass DFeatFile {\n  public:\n    std::vector<char> buffer;\n    long num_features;\n    long file_size;\n    bool positive; // whether these are positive or negative examples\n\n    void load(std::string file_path, bool ispositive) {\n      positive = ispositive;\n      std::cout << \"loading \" << file_path << \"...\" << std::endl;\n      std::ifstream file(file_path, std::ios::binary | std::ios::ate);\n      std::streamsize size = file.tellg();\n      file_size = size;\n      num_features = size / DSEG_DATA_SIZE;\n      std::cout << \"loading \" << size << \" bytes into memory...\" << std::endl;\n      file.seekg(0, std::ios::beg);\n      buffer.reserve(size);\n      if (!file.read(buffer.data(), size)) {\n        std::cout << \"could not read file \" << file_path << std::endl;\n        exit(1);\n      }\n      std::cout << \"done loading\" << std::endl;\n    }\n\n    unsigned char *block(int index) {\n      return (unsigned char *)(buffer.data() + DSEG_DATA_SIZE * index);\n    }\n\n    cv::Mat get_ANN_training_blob(int cutoff, int offset=0) {\n      if (cutoff > num_features) {\n        std::cout << \"error: cutoff cannot exceed num_features!\" << std::endl;\n      }\n      std::cout << \"converting to cv::Mat blob for ANN...\" << std::endl;\n      cv::Mat inputs(cutoff - offset, DSEG_DATA_SIZE, CV_32F);\n      for(int i = offset; i < cutoff; i++) {\n        for(int j = 0; j < DSEG_DATA_SIZE; j++) {\n          inputs.at<float>(i, j) = (float)(block(i)[j]);\n        }\n      }\n      std::cout << \"done converting.\" << std::endl;\n      return inputs;\n    }\n};\n\nclass DSegmentationResult {\n  public:\n    std::unordered_map<int, BSegment> bmap;\n    cv::Mat segmented_image;\n};\n\nclass DPair {\n  public:\n    unsigned char *block;\n    bool positive;\n};\n\nclass ANNDataset {\n  public:\n    cv::Mat training_inputs;\n    cv::Mat training_outputs;\n    cv::Mat validation_inputs;\n    cv::Mat validation_outputs;\n\n    void load(DFeatFile &positives, DFeatFile &negatives, DFeatFile &validation_positives) {\n      std::vector<DPair> positive_pairs;\n      std::vector<DPair> negative_pairs;\n      std::vector<DPair> validation_positive_pairs;\n      std::vector<DPair> training_negative_pairs;\n      std::vector<DPair> validation_negative_pairs;\n      // add positive examples\n      for(int i = 0; i < positives.num_features; i++) {\n        DPair pair;\n        pair.positive = true;\n        pair.block = positives.block(i);\n        positive_pairs.push_back(pair);\n      }\n      // add validation positive examples\n      for(int i = 0; i < validation_positives.num_features; i++) {\n        DPair pair;\n        pair.positive = true;\n        pair.block = positives.block(i);\n        validation_positive_pairs.push_back(pair);\n      }\n      // add negative examples\n      for(int i = 0; i < negatives.num_features; i++) {\n        DPair pair;\n        pair.positive = false;\n        pair.block = negatives.block(i);\n        negative_pairs.push_back(pair);\n      }\n      // shuffle pairs\n      std::shuffle(std::begin(positive_pairs), std::end(positive_pairs), rd);\n      std::shuffle(std::begin(negative_pairs), std::end(negative_pairs), rd);\n      std::shuffle(std::begin(validation_positive_pairs), std::end(validation_positive_pairs), rd);\n      // divide training and validation\n      for(DPair pair : negative_pairs) {\n        if (validation_negative_pairs.size() < validation_positive_pairs.size()) {\n          validation_negative_pairs.push_back(pair);\n        } else {\n          if (training_negative_pairs.size() < ANN_TRAINING_SET_LIMIT) {\n            training_negative_pairs.push_back(pair);\n          } else {\n            break;\n          }\n        }\n      }\n      std::cout << negative_pairs.size() << \" negative features available\" << std::endl;\n      std::cout << validation_negative_pairs.size() << \" negative features allocated to validation set\" << std::endl;\n      std::cout << training_negative_pairs.size() << \" negative features available for training set\" << std::endl;\n      negative_pairs.clear();\n      std::cout << positive_pairs.size() << \" positive features available for training set\" << std::endl;\n      std::vector<DPair> training_pairs;\n      for(DPair pair : positive_pairs) {\n        if (training_pairs.size() < training_negative_pairs.size()) {\n          training_pairs.push_back(pair);\n        } else {\n          break;\n        }\n      }\n      training_pairs += training_negative_pairs;\n      std::cout << \"final size of training set:  \" << training_pairs.size() << std::endl;\n      std::vector<DPair> validation_pairs;\n      validation_pairs += validation_positive_pairs;\n      validation_pairs += validation_negative_pairs;\n      std::cout << \"final size of validation set: \" << validation_pairs.size() << std::endl;\n      // final shuffle\n      std::shuffle(std::begin(validation_pairs), std::end(validation_pairs), rd);\n      std::shuffle(std::begin(training_pairs), std::end(training_pairs), rd);\n      positive_pairs.clear();\n      negative_pairs.clear();\n      validation_positive_pairs.clear();\n      validation_negative_pairs.clear();\n      training_negative_pairs.clear();\n      std::cout << \"done shuffling\" << std::endl;\n\n      // create images\n      std::cout << \"generating training inputs image...\" << std::endl;\n      training_inputs = cv::Mat(training_pairs.size(), DSEG_DATA_SIZE, CV_32F);\n      for(int i = 0; i < training_pairs.size(); i++)\n        for(int j = 0; j < DSEG_DATA_SIZE; j++)\n          training_inputs.at<float>(i, j) = ((float)(training_pairs[i].block[j])) / 255.0;\n      positives.buffer.clear();\n\n      std::cout << \"generating validation inputs image...\" << std::endl;\n      validation_inputs = cv::Mat(validation_pairs.size(), DSEG_DATA_SIZE, CV_32F);\n      for(int i = 0; i < validation_pairs.size(); i++)\n        for(int j = 0; j < DSEG_DATA_SIZE; j++)\n          validation_inputs.at<float>(i, j) = ((float)(validation_pairs[i].block[j])) / 255.0;\n      validation_positives.buffer.clear();\n      negatives.buffer.clear();\n\n      std::cout << \"generating training outputs image...\" << std::endl;\n      training_outputs = cv::Mat(training_pairs.size(), 1, CV_32F);\n      for(int i = 0; i < training_pairs.size(); i++) {\n        float val;\n        if (training_pairs[i].positive) {\n          val = 1.0;\n        } else {\n          val = 0.0;\n        }\n        training_outputs.at<float>(i, 0) = val;\n      }\n\n      std::cout << \"generating validation outputs image...\" << std::endl;\n      validation_outputs = cv::Mat(validation_pairs.size(), 1, CV_32F);\n      for(int i = 0; i < validation_pairs.size(); i++) {\n        float val;\n        if (validation_pairs[i].positive) {\n          val = 1.0;\n        } else {\n          val = 0.0;\n        }\n        validation_outputs.at<float>(i, 0) = val;\n      }\n\n      std::cout << \"done.\" << std::endl;\n    }\n};\n\nint seg_at(vl_uint32 *segmentation, int i, int j, int cols) {\n  return (int)segmentation[j + cols * i];\n}\n\ninline DPos project_point(int dest_width, int dest_height, int x, int y, float xmod, float ymod) {\n  DPos pos;\n  pos.x = min(max(round((float)x * xmod), 0), dest_width - 1);\n  pos.y = min(max(round((float)y * ymod), 0), dest_height - 1);\n  return pos;\n}\n\ninline bool in_bounds(int w, int h, int x, int y) {\n  return x >= 0 && y >= 0 && x < w && y < h;\n}\n\n// novel algorithm for vectorizing and resizing solid-color images\n// preserves softness of edges\ncv::Mat resize_contour(cv::Mat &src, int dest_width, int dest_height) {\n  cv::Mat dest = cv::Mat(dest_width, dest_height, cv::DataType<unsigned char>::type);\n  float xmod = ((float)dest_width) / (float)src.cols;\n  float ymod = ((float)dest_height) / (float)src.rows;\n  for(int x = 0; x < dest_width; x++)\n    for(int y = 0; y < dest_height; y++)\n      dest.at<unsigned char>(x, y) = 255;\n  for(int x = 0; x < src.cols; x++) {\n    for(int y = 0; y < src.rows; y++) {\n      if (src.at<unsigned char>(x, y) != 0)\n        continue;\n      DPos dest_pos = project_point(dest_width, dest_height, x, y, xmod, ymod);\n      DPos border_cands[8] = {make_pos(x    , y - 1),  // TOP\n                              make_pos(x + 1, y - 1),  // TOP RIGHT\n                              make_pos(x + 1, y    ),  // RIGHT\n                              make_pos(x + 1, y + 1),  // BOTTOM RIGHT\n                              make_pos(x    , y + 1),  // BOTTOM\n                              make_pos(x - 1, y + 1),  // BOTTOM LEFT\n                              make_pos(x - 1, y    ),  // LEFT\n                              make_pos(x - 1, y - 1)}; // TOP LEFT\n      std::vector<DPos> border;\n      for(int i = 0; i < 8; i++) {\n        DPos pos = border_cands[i];\n        if (in_bounds(src.cols, src.rows, pos.x, pos.y) && src.at<unsigned char>(pos.x, pos.y) == 0)\n          border.push_back(project_point(dest_width, dest_height, pos.x, pos.y, xmod, ymod));\n      }\n      if (border.size() > 0)\n        border.push_back(border[0]); // enclose\n      std::vector<cv::Point> pts;\n      for(DPos pos : border) {\n        pts.push_back(cv::Point(pos.x, pos.y));\n      }\n      if (border.size() > 1) {\n        std::vector<std::vector<cv::Point>> polys;\n        polys.push_back(pts);\n        cv::fillPoly(dest, polys, 0);\n      }\n    }\n  }\n  /* commented out code for drawing markers\n  for(int x = 0; x < src.cols; x++) {\n    for(int y = 0; y < src.rows; y++) {\n      if (src.at<unsigned char>(x, y) == 0) {\n        DPos proj = project_point(dest_width, dest_height, x, y, xmod, ymod);\n        //dest.at<unsigned char>(proj.x, proj.y) = 0;\n        cv::drawMarker(dest, cv::Point(proj.x, proj.y), 0);\n      }\n    }\n  }*/\n  return dest;\n}\n\nDSegmentationResult perform_segmentation(cv::Mat mat, int region, int min_region, float regularization=800.0, bool return_image=false) {\n  cv::Mat matc;\n  if (return_image)\n    matc = mat.clone();\n  vl_uint32* segmentation = new vl_uint32[mat.rows * mat.cols];\n  vl_size height = mat.rows;\n  vl_size width = mat.cols;\n  vl_size channels = mat.channels();\n  // convert to 1 dimensional array of floats\n  float* image = new float[mat.rows * mat.cols * mat.channels()];\n  for(int i = 0; i < mat.rows; ++i) {\n    for(int j = 0; j < mat.cols; ++j) {\n      // Assuming three channels ...\n      image[j + mat.cols * i + mat.cols * mat.rows * 0] = mat.at<cv::Vec3b>(i, j)[0];\n      image[j + mat.cols * i + mat.cols * mat.rows * 1] = mat.at<cv::Vec3b>(i, j)[1];\n      image[j + mat.cols * i + mat.cols * mat.rows * 2] = mat.at<cv::Vec3b>(i, j)[2];\n    }\n  }\n  std::unordered_map<int, BSegment> bmap;\n  // do segmentation with VLFeat SLIC\n  vl_slic_segment(segmentation, image, width, height, channels, region, regularization, min_region);\n  int label = 0;\n  int label_top = -1;\n  int label_bottom = -1;\n  int label_left = -1;\n  int label_right = -1;\n  // record segmentation result\n  for(int i = 0; i < mat.rows; i++) {\n    for(int j = 0; j < mat.cols; j++) {\n      label = seg_at(segmentation, i, j, mat.cols);\n\n      if (return_image) {\n        label_top = label;\n        if (i > 0)\n          label_top = seg_at(segmentation, i - 1, j, matc.cols);\n        label_bottom = label;\n        if (i < matc.rows - 1)\n          label_bottom = seg_at(segmentation, i + 1, j, matc.cols);\n        label_left = label;\n        if (j > 0)\n          label_left = seg_at(segmentation, i, j - 1, matc.cols);\n        label_right = label;\n        if (j < matc.cols - 1)\n          label_right = seg_at(segmentation, i, j + 1, matc.cols);\n        if (label != label_top || label != label_bottom || label != label_left || label != label_right) {\n          matc.at<cv::Vec3b>(i, j)[0] = 0;\n          matc.at<cv::Vec3b>(i, j)[1] = 0;\n          matc.at<cv::Vec3b>(i, j)[2] = 255;\n        }\n      }\n      // create bsegs\n      unsigned char b = (unsigned char)mat.at<cv::Vec3b>(i, j)[0];\n      unsigned char g = (unsigned char)mat.at<cv::Vec3b>(i, j)[1];\n      unsigned char r = (unsigned char)mat.at<cv::Vec3b>(i, j)[2];\n      std::unordered_map<int, BSegment>::iterator iter = bmap.find(label);\n      if (iter == bmap.end()) {\n        BSegment bseg;\n        bseg.add_pixel(i, j, r, g, b);\n        bseg.id = label;\n        bmap[label] = bseg;\n      } else {\n        BSegment *bseg = &bmap[label];\n        bseg->add_pixel(i, j, r, g, b);\n      }\n    }\n  }\n  DSegmentationResult res;\n  res.bmap = bmap;\n  if (return_image)\n    res.segmented_image = matc;\n  delete[] image;\n  delete[] segmentation;\n  return res;\n}\n\nDSegment generate_dseg(BSegment bseg, int num=0) {\n  DSegment dseg;\n  if (bseg.positions.size() == 0)\n    return dseg;\n  dseg.cta_color = bseg.main_color;\n  int min_x = std::numeric_limits<int>::max();\n  int min_y = min_x;\n  int max_x = std::numeric_limits<int>::min();\n  int max_y = max_x;\n  for(DPos pos : bseg.positions) {\n    min_x = min(min_x, pos.x);\n    min_y = min(min_y, pos.y);\n    max_x = max(max_x, pos.x);\n    max_y = max(max_y, pos.y);\n  }\n  int w = max_x - min_x + 1;\n  int h = max_y - min_y + 1;\n  cv::Mat patch = cv::Mat(w, h, cv::DataType<unsigned char>::type);\n  for(int x = 0; x < w; x++)\n    for(int y = 0; y < h; y++)\n      patch.at<unsigned char>(x, y) = 255;\n  for(DPos pos : bseg.positions) {\n    int x = pos.x - min_x;\n    int y = pos.y - min_y;\n    patch.at<unsigned char>(x, y) = 0;\n  }\n  //std::stringstream ss;\n  //ss << \"patch_\" << num << \"_\" << bseg.id << \".png\";\n  //cv::imwrite(ss.str(), patch);\n  //dseg.patch_orig = patch;\n  dseg.patch_resized = resize_contour(patch, DSEG_GRID_SIZE, DSEG_GRID_SIZE);\n  //dseg.patch_resized = cv::Mat(DSEG_GRID_SIZE, DSEG_GRID_SIZE, cv::DataType<unsigned char>::type);\n  //cv::resize(patch, dseg.patch_resized, dseg.patch_resized.size(), cv::INTER_AREA);\n  //cv::imwrite(ss.str(), dseg.patch_resized);\n  return dseg;\n}\n\nstd::vector<DSegment> generate_dsegs(std::unordered_map<int, BSegment> bmap, int num=0) {\n  std::vector<DSegment> dsegs;\n  for(auto pair : bmap) {\n    pair.second.compute_averages();\n    DColor main_color = pair.second.main_color;\n    if (!is_magic_pink(main_color) && pair.second.positions.size() > DSEG_POINTS_THRESHOLD) {\n      dsegs.push_back(generate_dseg(pair.second, num));\n    }\n  }\n  return dsegs;\n}\n\nstd::vector<DFeatVect> frame_to_feature_vectors(cv::Mat &mat, bool translucent=true, bool output_images=false) {\n  if (translucent)\n    fill_magic_pink(mat);\n  if (mat.rows > DSEG_MAX_IMG_SIZE || mat.cols > DSEG_MAX_IMG_SIZE) {\n    int new_rows, new_cols;\n    if (mat.rows > mat.cols) {\n      new_rows = DSEG_MAX_IMG_SIZE;\n      new_cols = min(round(((float)DSEG_MAX_IMG_SIZE / (float)mat.rows) * mat.cols), DSEG_MAX_IMG_SIZE);\n    } else {\n      new_cols = DSEG_MAX_IMG_SIZE;\n      new_rows = min(round(((float)DSEG_MAX_IMG_SIZE / (float)mat.cols) * mat.rows), DSEG_MAX_IMG_SIZE);\n    }\n    cv::Mat tmp;\n    //std::cout << \"old: \" << mat.cols << \", \" << mat.rows << \" => \" << new_cols << \", \" << new_rows << std::endl;\n    cv::resize(mat, tmp, cv::Size(new_cols, new_rows));\n    mat = tmp.clone();\n  }\n  std::vector<DSegment> all_dsegs;\n  int scale_start, scale_end;\n  if (translucent) {\n    scale_start = DSEG_POSITIVE_SCALE_START;\n    scale_end = DSEG_POSITIVE_SCALE_END;\n  } else {\n    scale_start = DSEG_NEGATIVE_SCALE_START;\n    scale_end = DSEG_NEGATIVE_SCALE_END;\n  }\n  for(int scale = scale_start; scale <= scale_end;) {\n    DSegmentationResult res = perform_segmentation(mat, 4 + scale, (4 + scale) * DSEG_REGION_RATIO, DSEG_REGULARIZATION, output_images);\n    if (output_images) {\n      std::stringstream ss;\n      ss << \"contours_\" << scale << \".png\";\n      std::cout << ss.str() << std::endl;\n      cv::imwrite(ss.str(), res.segmented_image);\n    }\n    std::vector<DSegment> dsegs = generate_dsegs(res.bmap, scale);\n    all_dsegs.insert(all_dsegs.end(), dsegs.begin(), dsegs.end());\n    if (translucent) {\n      if (scale < 10)\n        scale += 1;\n      else if (scale < 20)\n        scale += 2;\n      else if (scale < 30)\n        scale += 4;\n      else if (scale < 40)\n        scale += 8;\n      else if (scale < 50)\n        scale += 10;\n      else\n        scale += 15;\n    } else {\n      scale += 10;\n    }\n  }\n  std::vector<DFeatVect> feats;\n  for(DSegment dseg : all_dsegs)\n    feats.push_back(make_feature_vector(dseg));\n  return feats;\n}\n\n// adapted from http://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c\nstd::vector<std::string> match_files(const std::string &pattern) {\n  glob_t glob_result;\n  glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);\n  std::vector<std::string> files;\n  for(unsigned int i = 0; i < glob_result.gl_pathc; ++i) {\n    files.push_back(std::string(glob_result.gl_pathv[i]));\n  }\n  globfree(&glob_result);\n  return files;\n}\n\nint num_done = 0;\nstd::mutex print_mutex;\nvoid thread_print(int thread_num, std::string msg) {\n  print_mutex.lock();\n  num_done++;\n  std::cout << \"#\" << thread_num << \"(\" << num_done << \"): \" << msg << std::endl;\n  print_mutex.unlock();\n}\n\nstd::mutex file_mutex;\nstd::ofstream out_file;\n\nvoid genfeats_multithreaded(int thread_num, std::vector<std::string> img_paths, std::string outfile, bool translucent) {\n  for(std::string path : img_paths) {\n    cv::Mat mat = cv::imread(path, CV_LOAD_IMAGE_COLOR);\n    std::vector<DFeatVect> feats = frame_to_feature_vectors(mat, translucent, false);\n    std::stringstream ss;\n    ss << \"found \" << feats.size() << \" features in \" << path;\n    thread_print(thread_num, ss.str());\n    file_mutex.lock();\n    for(DFeatVect feat : feats) {\n      out_file.write(feat.data, sizeof(feat.data));\n    }\n    file_mutex.unlock();\n  }\n}\n\nvoid train_ANN(cv::Ptr<cv::ml::ANN_MLP> &net, ANNDataset &dataset, double target_error=0.2) {\n  std::cout << \"training...\" << std::endl;\n  double err = 1.0;\n  int epoch = 0;\n  do {\n    net->train(dataset.training_inputs, cv::ml::ROW_SAMPLE, dataset.training_outputs);\n    epoch += ANN_EPOC_INCREMENT;\n    std::cout << \"epoch: \" << epoch << std::endl;\n    int num_right = 0;\n    int num_wrong = 0;\n    int num_negative_right = 0;\n    int num_negative_wrong = 0;\n    int num_positive_right = 0;\n    int num_positive_wrong = 0;\n    cv::Mat output;\n    net->predict(dataset.validation_inputs, output);\n    for(int i = 0; i < output.rows; i++) {\n      float actual = output.at<float>(0, i);\n      if (std::isnan(actual))\n        actual = 0.0;\n      float expected = dataset.validation_outputs.at<float>(0, i);\n      bool right = round(max(0, actual)) == round(expected);\n      if (right) {\n        num_right += 1;\n        if (round(expected) == 1) {\n          num_positive_right += 1;\n        } else {\n          num_negative_right += 1;\n        }\n      } else {\n        num_wrong += 1;\n        if (round(expected) == 1) {\n          num_positive_wrong += 1;\n        } else {\n          num_negative_wrong += 1;\n        }\n      }\n    }\n    float accuracy = (float)num_right / (float)(num_wrong + num_right);\n    err = 1.0 - accuracy;\n    std::cout << \"num_right: \" << num_right << std::endl;\n    std::cout << \"num_wrong: \" << num_wrong << std::endl;\n    std::cout << \"  p_right: \" << num_positive_right << std::endl;\n    std::cout << \"  p_wrong: \" << num_positive_wrong << std::endl;\n    std::cout << \"  n_right: \" << num_negative_right << std::endl;\n    std::cout << \"  n_wrong: \" << num_negative_wrong << std::endl;\n    std::cout << \"accuracy: \" << accuracy << std::endl;\n  } while(err > target_error);\n  std::cout << \"training stopped (target error threshold reached)\" << std::endl;\n\n}\n\nint main(int argc, char** argv) {\n  std::cout << \"===========================================================\" << std::endl;\n  std::cout << \" Delvr 1.0 - copyright (c) Sam Kelly - all rights reserved \" << std::endl;\n  std::cout << \"===========================================================\" << std::endl;\n  std::cout << std::endl;\n  if (argc == 1) {\n    std::cout << \"usage: delvr genfeats [translucent|opaque] [path/to/images] [path/to/outfile]\" << std::endl;\n    std::cout << \"       delvr traindetector [path/to/positive/features] [path/to/negative/features] [output/path]\" << std::endl;\n    return 0;\n  }\n  unsigned num_threads = std::thread::hardware_concurrency();\n\n  // BEGIN GENFEATS\n  if (std::string(argv[1]) == \"genfeats\") {\n    if (argc != 5) {\n      std::cout << \"wrong number of arguments!\" << std::endl;\n      return 1;\n    }\n    bool translucent = false;\n    if (std::string(argv[2]) == \"opaque\") {\n      translucent = false;\n    } else if (std::string(argv[2]) == \"translucent\") {\n      translucent = true;\n    } else {\n      std::cout << \"error: translucent / opaque not specified!\" << std::endl;\n      return 1;\n    }\n    std::string images_path = std::string(argv[3]);\n    if (!boost::algorithm::ends_with(images_path, \"/\"))\n      images_path = images_path + \"/\";\n    std::string outpath = std::string(argv[4]);\n    std::cout << \"Feature generation routine started.\" << std::endl;\n    std::cout << std::endl;\n\n    std::vector<std::string> imgs;\n    if (translucent) {\n      imgs = match_files(images_path + \"*.png\");\n      std::cout << \"found \" << imgs.size() << \" PNG files in \" << images_path << std::endl;\n    } else {\n      // hack for SUN since glob does not work recursively\n      imgs = match_files(images_path + \"*.jpg\");\n      imgs += match_files(images_path + \"**/*.jpg\");\n      imgs += match_files(images_path + \"**/**/*.jpg\");\n      imgs += match_files(images_path + \"**/**/**/*.jpg\");\n      imgs += match_files(images_path + \"**/**/**/**/*.jpg\");\n      imgs += match_files(images_path + \"**/**/**/**/**/*.jpg\");\n      std::cout << \"found \" << imgs.size() << \" JPG files in \" << images_path << std::endl;\n    }\n    std::cout << \"randomly shuffling images...\" << std::endl;\n    std::shuffle(std::begin(imgs), std::end(imgs), rd);\n    std::cout << \"done shuffling.\" << std::endl;\n\n    std::cout << \"will use \" << num_threads << \" threads\" << std::endl;\n    std::cout << \"creating threads...\" << std::endl;\n    std::vector<std::thread> threads;\n    // divy up workload among available threads\n    int num_added = 0;\n    std::vector<std::vector<std::string>> workload;\n    for(int i = 0; i < num_threads; i++)\n      workload.push_back(std::vector<std::string>());\n    for(int i = 0, j = 0; i < imgs.size(); i++, j++) {\n      num_added++;\n      if (!translucent && num_added >= DSEG_MAX_OPAQUE_IMAGES)\n        break;\n      workload[j].push_back(imgs[i]);\n      if (j == num_threads - 1)\n        j = -1;\n    }\n    std::cout << \"will use \" << num_added << \" images\" << std::endl;\n    // set up io\n    out_file.open(outpath, std::ios::out | std::ios::app | std::ios::binary);\n    // start threads\n    for(int i = 0; i < num_threads; i++) {\n      threads.push_back(std::thread(genfeats_multithreaded, i, workload[i], outpath, translucent));\n    }\n    for(int i = 0; i < num_threads; i++) {\n      threads[i].join();\n    }\n    std::cout << \"all threads finished\" << std::endl;\n    std::cout << \"finalizing output file...\" << std::endl;\n    out_file.close();\n    std::cout << \"done.\" << std::endl;\n    return 0;\n\n  // BEGIN TRAIN DETECTOR\n  } else if(std::string(argv[1]) == \"traindetector\") {\n    if (argc != 6) {\n      std::cout << \"error: wrong number of arguments!\" << std::endl;\n      exit(1);\n    }\n    std::string positive_features_path = std::string(argv[2]);\n    std::string negative_features_path = std::string(argv[3]);\n    std::string positive_features_test_path = std::string(argv[4]);\n    std::string output_path = std::string(argv[5]);\n    DFeatFile positive_features;\n    positive_features.load(positive_features_path, true);\n    DFeatFile positive_features_test;\n    positive_features_test.load(positive_features_test_path, true);\n    DFeatFile negative_features;\n    negative_features.load(negative_features_path, false);\n    ANNDataset dataset;\n    dataset.load(positive_features, negative_features, positive_features_test);\n\n    std::vector<int> layer_sizes = {DSEG_DATA_SIZE, 48, 1};\n    cv::Ptr<cv::ml::ANN_MLP> net = cv::ml::ANN_MLP::create();\n    net->setLayerSizes(layer_sizes);\n    net->setActivationFunction(cv::ml::ANN_MLP::SIGMOID_SYM);\n    net->setTrainMethod(cv::ml::ANN_MLP::RPROP);\n    net->setTermCriteria(cv::TermCriteria(cv::TermCriteria::Type::MAX_ITER, ANN_EPOC_INCREMENT, 0.0));\n\n    train_ANN(net, dataset, 0.2);\n  }\n  return 0;\n}\n", "meta": {"hexsha": "a8356a3d48de51e4387a410af178fad02141fc69", "size": 28665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/delvr.cpp", "max_stars_repo_name": "samkelly/delvr", "max_stars_repo_head_hexsha": "b79ca5d53135b3add197b03907851b8f1c4d0506", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T08:07:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T13:05:05.000Z", "max_issues_repo_path": "src/delvr.cpp", "max_issues_repo_name": "samkelly/delvr", "max_issues_repo_head_hexsha": "b79ca5d53135b3add197b03907851b8f1c4d0506", "max_issues_repo_licenses": ["MIT"], "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/delvr.cpp", "max_forks_repo_name": "samkelly/delvr", "max_forks_repo_head_hexsha": "b79ca5d53135b3add197b03907851b8f1c4d0506", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T14:09:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-25T16:55:07.000Z", "avg_line_length": 34.453125, "max_line_length": 136, "alphanum_fraction": 0.5986394558, "num_tokens": 8090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.19460231996678576}}
{"text": "#include \"TTree.h\"\n#include \"TStyle.h\"\n#include \"TMath.h\"\n#include \"TFile.h\"\n#include \"TH1F.h\"\n#include \"TH2F.h\"\n#include \"TF1.h\"\n#include \"TCut.h\"\n#include \"TLegend.h\"\n#include \"TCanvas.h\"\n#include \"TProfile.h\"\n#include \"TMath.h\"\n#include \"TPaveText.h\"\n#include \"TLeaf.h\"\n#include \"TLine.h\"\n#include \"TArrow.h\"\n#include \"TRandom2.h\"\n#include \"TRandom3.h\"\n#include \"TRolke.h\"\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <cmath>\n#include <algorithm>\n#include \"TRandom3.h\"\n#include \"TFrame.h\"\n//#include <boost/lexical_cast.hpp>\n//#include <boost/timer.hpp>\n//#include <boost/functional/hash.hpp>\n#include <TChain.h>\n#include <string>\n#include <fstream>\n\n#include <TLimit.h>\n#include <TConfidenceLevel.h>\n#include <TLimitDataSource.h>\n#include \"Riostream.h\"\n#include \"TMath.h\"\n#include \"TNtuple.h\"\n#include \"TObject.h\"\n#include \"TString.h\"\n#include \"TGraph.h\"\n\n#include \"TFile.h\"\n#include <cstdio>\n#include \"TAxis.h\"\n\n\n#include <iostream>\n#include <iomanip>\n#include \"TSystem.h\"\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TH2.h\"\n#include \"TTree.h\"\n#include \"TF1.h\"\n#include \"TMath.h\"\n#include \"TFitResult.h\"\n#include \"TChain.h\"\n#include \"TLegend.h\"\n#include \"TCanvas.h\"\n#include \"TLine.h\"\n#include \"TLatex.h\"\n#include \"TVector.h\"\n#include \"TLorentzVector.h\"\n\n#include \"TGraphErrors.h\"\n#include \"TFitResultPtr.h\"\n#include \"TBox.h\"\n#include \"TAxis.h\"\nusing namespace std;\n\n\n\nvoid annotated_v5_LIWC_analysisForPaper()\n\n{\n\n  std::ofstream analysisOut;\n  analysisOut.open(\"analysisLIWC.txt\");\n  //  std::ifstream inputFiles(\"TestOneSpreadsheet.txt\");\n  std::ifstream inputFiles(\"annotated_v5_ALL_drivesFixed.txt\");\n  std::ofstream hashOut(\"hashOut.txt\");\n  std::vector<std::string> letterFileList;\n  std::string letterLine;\n\n  std::ofstream candIdMalePhysicsOut(\"candIdMalePhysics.txt\");\n  std::ofstream candIdFemalePhysicsOut(\"candIdFemalePhysics.txt\");\n\n\n  std::ofstream candIdMaleSocSciOut(\"candIdMaleSocSci.txt\");\n  std::ofstream candIdFemaleSocSciOut(\"candIdFemaleSocSci.txt\");\n\n  while(std::getline(inputFiles,letterLine))\n    {\n      letterFileList.push_back(letterLine);\n      //     std::cout << physicscMrMLine << std::endl;\n    }\n\n  analysisOut << \" past initial while loop\" << std::endl;\n  Int_t letterLength = letterFileList.size();\n  analysisOut << \"length of letter list = \" << letterLength << std::endl;\n \n  \n  /*********analyze**************/\n  Int_t cat;\n  Bool_t useBoth;\n  useBoth = false;\n  \n  Int_t wc; Int_t disp;\n\n  string rowHash;\n  string rowNo,bobHash;\n  Float_t Analytic,Clout,Authentic,Tone,WPS, Dic, function, pronoun, ppron, i, we, you , shehe, they, ipron, article, prep, auxverb, adverb, conj, negate, verb, adj, compare, interrog, number, quant,\n    affect, posemo, negemo, anx, anger, sad ,\n    social , family, friends, female, male, cogproc, insight, cause, discrep, tentat, certain, differ, percept, see, hear, feel, bio, body, health, sexual, ingest, drives, affiliation,\n    achiev,power,familyRelated,reward,risk,focuspast,focuspresent,focusfuture ,\n    relativ,motion,space,time,work,leisure,home,money,relig,death,informal,swear,netspeak,assent,nonflu,filler,AllPunc,Period,Comma,Colon,SemiC,QMark,Exclam,Dash,Quote,\n    Apostro,Parent,OtherP;\n\n  Int_t canGender, writerGender,both,candId,writerId,discipline;\n  string candidateName;\n  Int_t wcCut;\n\n  Int_t Ref_is_advisor, Ref_nonresearch,both_gender_non_advisor_refs;\n\n  Float_t standout, ability, grindstone , teaching , research , agentic, communal, internal1 , internal2, internal3, internal4 , internal5, internal6;\n  Int_t nlines = 0;\n    \n  TFile* f = new TFile(\"lexicalAnalysisLIWC.root\", \"RECREATE\");\n\n  Float_t nt[93];\n  TNtuple* physics = new TNtuple(\"physics\",\"Physics Ntuple\",\n\t\t\t\t \"cat:WC:Analytic:Clout:Authentic:Tone:WPS:Dic:function:pronoun:ppron:i:we:you:shehe:they:ipron:article:prep:auxverb:adverb:conj:negate:verb:adj:compare:interrog:number:quant:affect:posemo:negemo:anx:anger:sad:social:family:friends:female:male:cogproc:insight:cause:discrep:tentat:certain:differ:percept:see:hear:feel:bio:body:health:sexual:ingest:drives:affiliation:achiev:power:familyRelated:reward:risk:focuspast:focuspresent:focusfuture:relativ:motion:space:time:work:leisure:home:money:relig:death:informal:swear:netspeak:assent:nonflu:filler:AllPunc:Period:Comma:Colon:SemiC:QMark:Exclam:Dash:Quote:Apostro:Parent:OtherP\");\n\n  TNtuple*socsci = new TNtuple(\"socsci\",\"SocSci Ntuple\",\n\t\t\t       \"cat:WC:Analytic:Clout:Authentic:Tone:WPS:Dic:function:pronoun:ppron:i:we:you:shehe:they:ipron:article:prep:auxverb:adverb:conj:negate:verb:adj:compare:interrog:number:quant:affect:posemo:negemo:anx:anger:sad:social:family:friends:female:male:cogproc:insight:cause:discrep:tentat:certain:differ:percept:see:hear:feel:bio:body:health:sexual:ingest:drives:affiliation:achiev:power:familyRelated:reward:risk:focuspast:focuspresent:focusfuture:relativ:motion:space:time:work:leisure:home:money:relig:death:informal:swear:netspeak:assent:nonflu:filler:AllPunc:Period:Comma:Colon:SemiC:QMark:Exclam:Dash:Quote:Apostro:Parent:OtherP\");\n\n\n  TH1F* wordsPhysicscMrM = new TH1F(\"wordsPhysicscMrM\", \" number of words in Physics letter, male candidate/male writer\",100,0.,5000.);\n  TH1F* wordsPhysicscFrM = new TH1F(\"wordsPhysicscFrM\", \" number of words in Physics letter, female candidate/male writer\",100,0.,5000.);\n  TH1F* wordsPhysicscFrF = new TH1F(\"wordsPhysicscFrF\", \" number of words in Physics letter, female candidate/female writer\",100,0.,5000.);\n  TH1F* wordsPhysicscMrF = new TH1F(\"wordsPhysicscMrF\", \" number of words in Physics letter, male candidate/female writer\",100,0.,5000.);\n\n  TH1F* wordsSocScicMrM = new TH1F(\"wordsSocScicMrM\", \" number of words in SocSci letter, male candidate/male writer\",100,0.,5000.);\n  TH1F* wordsSocScicFrM = new TH1F(\"wordsSocScicFrM\", \" number of words in SocSci letter, female candidate/male writer\",100,0.,5000.);\n  TH1F* wordsSocScicFrF = new TH1F(\"wordsSocScicFrF\", \" number of words in SocSci letter, female candidate/female writer\",100,0.,5000.);\n  TH1F* wordsSocScicMrF = new TH1F(\"wordsSocScicMrF\", \" number of words in SocSci letter, male candidate/female writer\",100,0.,5000.);\n\n \n  TH1F* drivescMrMphysics = new TH1F(\"drivesphysicscMrM\",\"LIWC Drive words in Wilson Letters, cMrM (cat 80)\", 20,0.,50.);\n  TH1F* drivescMrFphysics = new TH1F(\"drivesphysicscMrF\",\"LIWC Drive words in Wilson Letters, cMrM (cat 80)\", 20,0.,50.);\n  TH1F* drivescFrFphysics = new TH1F(\"drivesphysicscFrF\",\"LIWC Drive words in Wilson Letters, cFrF (cat 80)\", 20,0.,50.);\n  TH1F* drivescFrMphysics = new TH1F(\"drivesphysicscFrM\",\"LIWC Drive words in Wilson Letters, cFrM (cat 80)\", 20,0.,50.);\n\n  TH1F* drivescMrMsocsci = new TH1F(\"drivessocscicMrM\",\"LIWC Drive words in Cornell Letters, cMrM (cat 80)\", 20,0.,50.);\n  TH1F* drivescMrFsocsci = new TH1F(\"drivessocscicMrF\",\"LIWC Drive words in Cornell Letters, cMrF (cat 80)\", 20,0.,50.);\n  TH1F* drivescFrFsocsci = new TH1F(\"drivessocscicFrF\",\"LIWC Drive words in Cornell Letters, cFrF (cat 80)\", 20,0.,50.);\n  TH1F* drivescFrMsocsci = new TH1F(\"drivessocscicFrM\",\"LIWC Drive words in Cornell Letters, cFrM (cat 80)\", 20,0.,50.);\n\n\n  TH1F* workcMrMphysics = new TH1F(\"workphysicscMrM\",\"LIWC Work words in Wilson Letters, cMrM\", 20,0.,50.);\n  TH1F* workcMrFphysics = new TH1F(\"workphysicscMrF\",\"LIWC Work words in Wilson Letters, cMrM\", 20,0.,50.);\n  TH1F* workcFrFphysics = new TH1F(\"workphysicscFrF\",\"LIWC Work words in Wilson Letters, cFrF\", 20,0.,50.);\n  TH1F* workcFrMphysics = new TH1F(\"workphysicscFrM\",\"LIWC Work words in Wilson Letters, cFrM\", 20,0.,50.);\n\n  TH1F* workcMrMsocsci = new TH1F(\"worksocscicMrM\",\"LIWC Work words in Cornell Letters, cMrM\", 20,0.,50.);\n  TH1F* workcMrFsocsci = new TH1F(\"worksocscicMrF\",\"LIWC Work words in Cornell Letters, cMrF\", 20,0.,50.);\n  TH1F* workcFrFsocsci = new TH1F(\"worksocscicFrF\",\"LIWC Work words in Cornell Letters, cFrF\", 20,0.,50.);\n  TH1F* workcFrMsocsci = new TH1F(\"worksocscicFrM\",\"LIWC Work words in Cornell Letters, cFrM\", 20,0.,50.);\n\n\n  TH1F* affectcMrMphysics = new TH1F(\"affectphysicscMrM\",\"LIWC Affect words in Wilson Letters, (cat 30)\", 20,0.,20.);\n  TH1F* affectcMrFphysics = new TH1F(\"affectphysicscMrF\",\"LIWC Affect words in Wilson Letters, (cat 30)\", 20,0.,20.);\n  TH1F* affectcFrFphysics = new TH1F(\"affectphysicscFrF\",\"LIWC Affect words in Wilson Letters, (cat 30)\", 20,0.,20.);\n  TH1F* affectcFrMphysics = new TH1F(\"affectphysicscFrM\",\"LIWC Affect words in Wilson Letters, (cat 30)\", 20,0.,20.);\n\n  TH1F* affectcMrMsocsci = new TH1F(\"affectsocscicMrM\",\"LIWC Affect words in Cornell Letters, (cat 30)\", 20,0.,20.);\n  TH1F* affectcMrFsocsci = new TH1F(\"affectsocscicMrF\",\"LIWC Affect words in Cornell Letters, (cat 30)\", 20,0.,20.);\n  TH1F* affectcFrFsocsci = new TH1F(\"affectsocscicFrF\",\"LIWC Affect words in Cornell Letters, (cat 30)\", 20,0.,20.);\n  TH1F* affectcFrMsocsci = new TH1F(\"affectsocscicFrM\",\"LIWC Affect words in Cornell Letters, (cat 30)\", 20,0.,20.);\n\n  TH1F* socialcMrMphysics = new TH1F(\"socialphysicscMrM\",\"LIWC Social words in Wilson Letters, (cat 40)\", 20,0.,20.);\n  TH1F* socialcMrFphysics = new TH1F(\"socialphysicscMrF\",\"LIWC Social words in Wilson Letters, (cat 40)\", 20,0.,20.);\n  TH1F* socialcFrFphysics = new TH1F(\"socialphysicscFrF\",\"LIWC Social words in Wilson Letters, (cat 40)\", 20,0.,20.);\n  TH1F* socialcFrMphysics = new TH1F(\"socialphysicscFrM\",\"LIWC Social words in Wilson Letters, (cat 40)\", 20,0.,20.);\n\n  TH1F* socialcMrMsocsci = new TH1F(\"socialsocscicMrM\",\"LIWC Social words in Cornell Letters, (cat 40)\", 20,0.,20.);\n  TH1F* socialcMrFsocsci = new TH1F(\"socialsocscicMrF\",\"LIWC Social words in Cornell Letters, (cat 40)\", 20,0.,20.);\n  TH1F* socialcFrFsocsci = new TH1F(\"socialsocscicFrF\",\"LIWC Social words in Cornell Letters, (cat 40)\", 20,0.,20.);\n  TH1F* socialcFrMsocsci = new TH1F(\"socialsocscicFrM\",\"LIWC Social words in Cornell Letters, (cat 40)\", 20,0.,20.);\n\n  TH1F* cogProccMrMphysics = new TH1F(\"cogProcphysicscMrM\",\"LIWC CogProc words in Wilson Letters, (cat 50)\", 20,0.,20.);\n  TH1F* cogProccMrFphysics = new TH1F(\"cogProcphysicscMrF\",\"LIWC CogProc words in Wilson Letters, (cat 50)\", 20,0.,20.);\n  TH1F* cogProccFrFphysics = new TH1F(\"cogProcphysicscFrF\",\"LIWC CogProc words in Wilson Letters, (cat 50)\", 20,0.,20.);\n  TH1F* cogProccFrMphysics = new TH1F(\"cogProcphysicscFrM\",\"LIWC CogProc words in Wilson Letters, (cat 50)\", 20,0.,20.);\n\n  TH1F* cogProccMrMsocsci = new TH1F(\"cogProcsocscicMrM\",\"LIWC CogProc words in Cornell Letters, (cat 50)\", 20,0.,20.);\n  TH1F* cogProccMrFsocsci = new TH1F(\"cogProcsocscicMrF\",\"LIWC CogProc words in Cornell Letters, (cat 50)\", 20,0.,20.);\n  TH1F* cogProccFrFsocsci = new TH1F(\"cogProcsocscicFrF\",\"LIWC CogProc words in Cornell Letters, (cat 50)\", 20,0.,20.);\n  TH1F* cogProccFrMsocsci = new TH1F(\"cogProcsocscicFrM\",\"LIWC CogProc words in Cornell Letters, (cat 50)\", 20,0.,20.);\n\n  \n  TH1F* timeOrientPastcMrMphysics = new TH1F(\"timeOrientPastphysicscMrM\",\"LIWC TimeOrientPast+Present words in Wilson Letters\", 20,0.,20.);\n  TH1F* timeOrientPastcMrFphysics = new TH1F(\"timeOrientPastphysicscMrF\",\"LIWC TimeOrientPast+Present words in Wilson Letters\", 20,0.,20.);\n  TH1F* timeOrientPastcFrFphysics = new TH1F(\"timeOrientPastphysicscFrF\",\"LIWC TimeOrientPast+Present words in Wilson Letters\", 20,0.,20.);\n  TH1F* timeOrientPastcFrMphysics = new TH1F(\"timeOrientPastphysicscFrM\",\"LIWC TimeOrientPast+Present words in Wilson Letters\", 20,0.,20.);\n\n  TH1F* timeOrientPastcMrMsocsci = new TH1F(\"timeOrientPastsocscicMrM\",\"LIWC TimeOrientPast+Present words in Cornell Letters\", 20,0.,20.);\n  TH1F* timeOrientPastcMrFsocsci = new TH1F(\"timeOrientPastsocscicMrF\",\"LIWC TimeOrientPast+Present words in Cornell Letters\", 20,0.,20.);\n  TH1F* timeOrientPastcFrFsocsci = new TH1F(\"timeOrientPastsocscicFrF\",\"LIWC TimeOrientPast+Present words in Cornell Letters\", 20,0.,20.);\n  TH1F* timeOrientPastcFrMsocsci = new TH1F(\"timeOrientPastsocscicFrM\",\"LIWC TimeOrientPast+Present words in Cornell Letters\", 20,0.,20.);\n\n  TH1F* timeOrientFuturecMrMphysics = new TH1F(\"timeOrientFuturephysicscMrM\",\"LIWC TimeOrientFuture words in Wilson Letters\", 20,0.,5.);\n  TH1F* timeOrientFuturecMrFphysics = new TH1F(\"timeOrientFuturephysicscMrF\",\"LIWC TimeOrientFuture words in Wilson Letters\", 20,0.,5.);\n  TH1F* timeOrientFuturecFrFphysics = new TH1F(\"timeOrientFuturephysicscFrF\",\"LIWC TimeOrientFuture words in Wilson Letters\", 20,0.,5.);\n  TH1F* timeOrientFuturecFrMphysics = new TH1F(\"timeOrientFuturephysicscFrM\",\"LIWC TimeOrientFuture words in Wilson Letters\", 20,0.,5.);\n\n  TH1F* timeOrientFuturecMrMsocsci = new TH1F(\"timeOrientFuturesocscicMrM\",\"LIWC TimeOrientFuture words in Wilson Letters\", 20,0.,5.);\n  TH1F* timeOrientFuturecMrFsocsci = new TH1F(\"timeOrientFuturesocscicMrF\",\"LIWC TimeOrientFuture words in Wilson Letters\", 20,0.,5.);\n  TH1F* timeOrientFuturecFrFsocsci = new TH1F(\"timeOrientFuturesocscicFrF\",\"LIWC TimeOrientFuture words in Wilson Letters\", 20,0.,5.);\n  TH1F* timeOrientFuturecFrMsocsci = new TH1F(\"timeOrientFuturesocscicFrM\",\"LIWC TimeOrientFuture words in Wilson Letters\", 20,0.,5.);\n\n\n  TH1F* PersConccMrMphysics = new TH1F(\"PersConcphysicscMrM\",\"LIWC PersConc words in Wilson Letters\", 40,0.,40.);\n  TH1F* PersConccMrFphysics = new TH1F(\"PersConcphysicscMrF\",\"LIWC PersConc words in Wilson Letters\", 40,0.,40.);\n  TH1F* PersConccFrFphysics = new TH1F(\"PersConcphysicscFrF\",\"LIWC PersConc words in Wilson Letters\", 40,0.,40.);\n  TH1F* PersConccFrMphysics = new TH1F(\"PersConcphysicscFrM\",\"LIWC PersConc words in Wilson Letters\", 40,0.,40.);\n\n  TH1F* PersConccMrMsocsci = new TH1F(\"PersConcsocscicMrM\",\"LIWC PersConc words in Cornell Letters\", 40,0.,40.);\n  TH1F* PersConccMrFsocsci = new TH1F(\"PersConcsocscicMrF\",\"LIWC PersConc words in Cornell Letters\", 40,0.,40.);\n  TH1F* PersConccFrFsocsci = new TH1F(\"PersConcsocscicFrF\",\"LIWC PersConc words in Cornell Letters\", 40,0.,40.);\n  TH1F* PersConccFrMsocsci = new TH1F(\"PersConcsocscicFrM\",\"LIWC PersConc words in Cornell Letters\", 40,0.,40.);\n\n  TH1F* PosemocMrMphysics = new TH1F(\"PosemophysicscMrM\",\"LIWC Posemo words in Wilson Letters\", 40,0.,40.);\n  TH1F* PosemocMrFphysics = new TH1F(\"PosemophysicscMrF\",\"LIWC Posemo words in Wilson Letters\", 40,0.,40.);\n  TH1F* PosemocFrFphysics = new TH1F(\"PosemophysicscFrF\",\"LIWC Posemo words in Wilson Letters\", 40,0.,40.);\n  TH1F* PosemocFrMphysics = new TH1F(\"PosemophysicscFrM\",\"LIWC Posemo words in Wilson Letters\", 40,0.,40.);\n\n    TH1F* NegemocMrMphysics = new TH1F(\"NegemophysicscMrM\",\"LIWC Negemo words in Wilson Letters\", 40,0.,40.);\n  TH1F* NegemocMrFphysics = new TH1F(\"NegemophysicscMrF\",\"LIWC Negemo words in Wilson Letters\", 40,0.,40.);\n  TH1F* NegemocFrFphysics = new TH1F(\"NegemophysicscFrF\",\"LIWC Negemo words in Wilson Letters\", 40,0.,40.);\n  TH1F* NegemocFrMphysics = new TH1F(\"NegemophysicscFrM\",\"LIWC Negemo words in Wilson Letters\", 40,0.,40.);\n\n  TH1F* analyticcMrMsocsci = new TH1F(\"analyticsocscicMrM\",\"LIWC analytic words in Cornell Letters\", 50,0.,100.);\n  TH1F* analyticcMrFsocsci = new TH1F(\"analyticsocscicMrF\",\"LIWC analytic words in Cornell Letters\", 50,0.,100.);\n  TH1F* analyticcFrFsocsci = new TH1F(\"analyticsocscicFrF\",\"LIWC analytic words in Cornell Letters\", 50,0.,100.);\n  TH1F* analyticcFrMsocsci = new TH1F(\"analyticsocscicFrM\",\"LIWC analytic words in Cornell Letters\", 50,0.,100.);\n\n  TH1F* analyticcMrMphysics = new TH1F(\"analyticphysicscMrM\",\"LIWC analytic words in Wilson Letters\", 50,0.,100.);\n  TH1F* analyticcMrFphysics = new TH1F(\"analyticphysicscMrF\",\"LIWC analytic words in Wilson Letters\", 50,0.,100.);\n  TH1F* analyticcFrFphysics = new TH1F(\"analyticphysicscFrF\",\"LIWC analytic words in Wilson Letters\", 50,0.,100.);\n  TH1F* analyticcFrMphysics = new TH1F(\"analyticphysicscFrM\",\"LIWC analytic words in Wilson Letters\", 50,0.,100.);\n\n  TH1F* analyticPhysicsHist = new TH1F(\"analyticPhysicsHist\",\"LIWC analytic distribution in Physics\", 100,0.,100.);\n  TH1F* analyticSocSciHist = new TH1F(\"analyticSocSciHist\",\"LIWC analytic distribution in SocSci\", 100,0.,100.);\n\n  TH1F* homecMrMsocsci = new TH1F(\"homesocscicMrM\",\"LIWC home words in Cornell Letters\", 50,0.,100.);\n  TH1F* homecMrFsocsci = new TH1F(\"homesocscicMrF\",\"LIWC home words in Cornell Letters\", 50,0.,100.);\n  TH1F* homecFrFsocsci = new TH1F(\"homesocscicFrF\",\"LIWC home words in Cornell Letters\", 50,0.,100.);\n  TH1F* homecFrMsocsci = new TH1F(\"homesocscicFrM\",\"LIWC home words in Cornell Letters\", 50,0.,100.);\n\n  TH1F* homecMrMphysics = new TH1F(\"homephysicscMrM\",\"LIWC home words in Wilson Letters\", 50,0.,100.);\n  TH1F* homecMrFphysics = new TH1F(\"homephysicscMrF\",\"LIWC home words in Wilson Letters\", 50,0.,100.);\n  TH1F* homecFrFphysics = new TH1F(\"homephysicscFrF\",\"LIWC home words in Wilson Letters\", 50,0.,100.);\n  TH1F* homecFrMphysics = new TH1F(\"homephysicscFrM\",\"LIWC home words in Wilson Letters\", 50,0.,100.);\n\n\n  TH1F* cloutcMrMsocsci = new TH1F(\"cloutsocscicMrM\",\"LIWC clout words in Cornell Letters\", 50,0.,100.);\n  TH1F* cloutcMrFsocsci = new TH1F(\"cloutsocscicMrF\",\"LIWC clout words in Cornell Letters\", 50,0.,100.);\n  TH1F* cloutcFrFsocsci = new TH1F(\"cloutsocscicFrF\",\"LIWC clout words in Cornell Letters\", 50,0.,100.);\n  TH1F* cloutcFrMsocsci = new TH1F(\"cloutsocscicFrM\",\"LIWC clout words in Cornell Letters\", 50,0.,100.);\n\n  TH1F* cloutcMrMphysics = new TH1F(\"cloutphysicscMrM\",\"LIWC clout words in Wilson Letters\", 50,0.,100.);\n  TH1F* cloutcMrFphysics = new TH1F(\"cloutphysicscMrF\",\"LIWC clout words in Wilson Letters\", 50,0.,100.);\n  TH1F* cloutcFrFphysics = new TH1F(\"cloutphysicscFrF\",\"LIWC clout words in Wilson Letters\", 50,0.,100.);\n  TH1F* cloutcFrMphysics = new TH1F(\"cloutphysicscFrM\",\"LIWC clout words in Wilson Letters\", 50,0.,100.);\n\n  TH1F* authenticcMrMsocsci = new TH1F(\"authenticsocscicMrM\",\"LIWC authentic words in Cornell Letters\", 50,0.,100.);\n  TH1F* authenticcMrFsocsci = new TH1F(\"authenticsocscicMrF\",\"LIWC authentic words in Cornell Letters\", 50,0.,100.);\n  TH1F* authenticcFrFsocsci = new TH1F(\"authenticsocscicFrF\",\"LIWC authentic words in Cornell Letters\", 50,0.,100.);\n  TH1F* authenticcFrMsocsci = new TH1F(\"authenticsocscicFrM\",\"LIWC authentic words in Cornell Letters\", 50,0.,100.);\n\n  TH1F* authenticcMrMphysics = new TH1F(\"authenticphysicscMrM\",\"LIWC authentic words in Wilson Letters\", 50,0.,100.);\n  TH1F* authenticcMrFphysics = new TH1F(\"authenticphysicscMrF\",\"LIWC authentic words in Wilson Letters\", 50,0.,100.);\n  TH1F* authenticcFrFphysics = new TH1F(\"authenticphysicscFrF\",\"LIWC authentic words in Wilson Letters\", 50,0.,100.);\n  TH1F* authenticcFrMphysics = new TH1F(\"authenticphysicscFrM\",\"LIWC authentic words in Wilson Letters\", 50,0.,100.);\n\n\n  TH1F* tonecMrMsocsci = new TH1F(\"tonesocscicMrM\",\"LIWC tone words in Cornell Letters\", 50,0.,100.);\n  TH1F* tonecMrFsocsci = new TH1F(\"tonesocscicMrF\",\"LIWC tone words in Cornell Letters\", 50,0.,100.);\n  TH1F* tonecFrFsocsci = new TH1F(\"tonesocscicFrF\",\"LIWC tone words in Cornell Letters\", 50,0.,100.);\n  TH1F* tonecFrMsocsci = new TH1F(\"tonesocscicFrM\",\"LIWC tone words in Cornell Letters\", 50,0.,100.);\n\n  TH1F* tonecMrMphysics = new TH1F(\"tonephysicscMrM\",\"LIWC tone words in Wilson Letters\", 50,0.,100.);\n  TH1F* tonecMrFphysics = new TH1F(\"tonephysicscMrF\",\"LIWC tone words in Wilson Letters\", 50,0.,100.);\n  TH1F* tonecFrFphysics = new TH1F(\"tonephysicscFrF\",\"LIWC tone words in Wilson Letters\", 50,0.,100.);\n  TH1F* tonecFrMphysics = new TH1F(\"tonephysicscFrM\",\"LIWC tone words in Wilson Letters\", 50,0.,100.);\n\n\n  \n  TH1F* PosemocMrMsocsci = new TH1F(\"PosemosocscicMrM\",\"LIWC Posemo words in Cornell Letters\", 40,0.,40.);\n  TH1F* PosemocMrFsocsci = new TH1F(\"PosemosocscicMrF\",\"LIWC Posemo words in Cornell Letters\", 40,0.,40.);\n  TH1F* PosemocFrFsocsci = new TH1F(\"PosemosocscicFrF\",\"LIWC Posemo words in Cornell Letters\", 40,0.,40.);\n  TH1F* PosemocFrMsocsci = new TH1F(\"PosemosocscicFrM\",\"LIWC Posemo words in Cornell Letters\", 40,0.,40.);\n\n  TH1F* NegemocMrMsocsci = new TH1F(\"NegemosocscicMrM\",\"LIWC Negemo words in Cornell Letters\", 40,0.,40.);\n  TH1F* NegemocMrFsocsci = new TH1F(\"NegemosocscicMrF\",\"LIWC Negemo words in Cornell Letters\", 40,0.,40.);\n  TH1F* NegemocFrFsocsci = new TH1F(\"NegemosocscicFrF\",\"LIWC Negemo words in Cornell Letters\", 40,0.,40.);\n  TH1F* NegemocFrMsocsci = new TH1F(\"NegemosocscicFrM\",\"LIWC Negemo words in Cornell Letters\", 40,0.,40.);\n\n\n  TH2F* workVsSocialcFrMsocsci = new TH2F(\"workVsSocialcFrM\",\"Work Vs Social socsci cFrM\",40,0.,40,40,0.,40.);\n  TH2F* workVsSocialcFrFsocsci = new TH2F(\"workVsSocialcFrF\",\"Work Vs Social socsci cFrF\",40,0.,40,40,0.,40.);\n  TH2F* workVsSocialcMrMsocsci = new TH2F(\"workVsSocialcMrM\",\"Work Vs Social socsci cMrM\",40,0.,40,40,0.,40.);\n  TH2F* workVsSocialcMrFsocsci = new TH2F(\"workVsSocialcMrF\",\"Work Vs Social socsci cMrF\",40,0.,40,40,0.,40.);\n\n  TH2F* workVsSocialcFrMphysics = new TH2F(\"workVsSocialcFrM\",\"Work Vs Social physics cFrM\",40,0.,40,40,0.,40.);\n  TH2F* workVsSocialcFrFphysics = new TH2F(\"workVsSocialcFrF\",\"Work Vs Social physics cFrF\",40,0.,40,40,0.,40.);\n  TH2F* workVsSocialcMrMphysics = new TH2F(\"workVsSocialcMrM\",\"Work Vs Social physics cMrM\",40,0.,40,40,0.,40.);\n  TH2F* workVsSocialcMrFphysics = new TH2F(\"workVsSocialcMrF\",\"Work Vs Social physics cMrF\",40,0.,40,40,0.,40.);\n\n  const char* labels[4] = {\"cMwM\", \"cMwF\", \"cFwF\",\"cFwM\"};\n  std::cout << \"made ntuples\" << std::endl;\n  inputFiles.clear();\n  inputFiles.seekg(0);\n \n  string headerInfo;\n  std::getline(inputFiles,headerInfo);\n\n\n  // this code assumes list sorted by candidate ID\n  Int_t uniqueMaleCandidatesPhysics, uniqueFemaleCandidatesPhysics, uniqueMaleCandidatesSocSci, uniqueFemaleCandidatesSocSci;\n  uniqueMaleCandidatesPhysics = uniqueFemaleCandidatesPhysics = uniqueMaleCandidatesSocSci = uniqueFemaleCandidatesSocSci = 0;\n  Int_t currentMaleCandidatePhysics, currentFemaleCandidatePhysics, currentMaleCandidateSocSci, currentFemaleCandidateSocSci;\n  currentMaleCandidatePhysics = currentFemaleCandidatePhysics = currentMaleCandidateSocSci = currentFemaleCandidateSocSci = 0;\n  Int_t currentCandidateIdMalePhysics = 0;\n  Int_t currentCandidateIdFeMalePhysics = 0;\n  Int_t currentCandidateIdMaleSocSci= 0;\n  Int_t currentCandidateIdFeMaleSocSci = 0;\n  Int_t currentCandidateId = 0;\n  // cMrM analysis\n  // letterLength = 10;\n  \n  for (Int_t ithLetter = 0 ; ithLetter< letterLength; ++ithLetter){\n    inputFiles >> rowNo >> rowHash >> bobHash >> candId >> writerId >> canGender >> writerGender >> both >> discipline\n\t       >> Ref_is_advisor >> Ref_nonresearch >> both_gender_non_advisor_refs >>  wc >> Analytic >> Clout >> Authentic >> Tone >>  WPS>> Dic>> function>> pronoun>> ppron>> i>> we>> you >> shehe>> they>> ipron>> article>> prep>> auxverb>> adverb>> conj>> negate>> verb>> adj>> compare>> interrog>> number>> quant>>\n      affect>> posemo>> negemo>> anx>> anger>> sad >>      social >> family>> friends>> female>> male>> cogproc>> insight>> cause>> discrep>> tentat>> certain>> differ>> percept>> see>> hear>> feel>> bio>> body>> health>> sexual>> ingest>> drives>> affiliation>>\n      achiev>>power>>familyRelated>>reward>>risk>>focuspast>>focuspresent>>focusfuture >>\n      relativ>>motion>>space>>time>>work>>leisure>>home>>money>>relig>>death>>informal>>swear>>netspeak>>assent>>nonflu>>filler>>AllPunc>>Period>>Comma>>Colon>>SemiC>>QMark>>Exclam>>Dash>>Quote>>\n      Apostro>>Parent>>OtherP >> standout >> ability >> grindstone >> teaching >> research >> agentic >> communal >> internal1 >> internal2 >> internal3 >> internal4 >> internal5 >> internal6;\n    std::cout << \"wc = \" << wc << std::endl;\n    std::cout << \"read a row\" << std::endl;\n    wcCut = 0.;\n    if (ithLetter > -10000){\n      analysisOut   << rowNo << \" \" << rowHash << \" \" << bobHash << \" \" << candId << \" \" << writerId << \" \" << canGender << \" \" << writerGender << \" \" << \" \"\n\t\t    << both << \" \" << discipline << \" \" << Ref_is_advisor << \" \" << Ref_nonresearch << \" \" << both_gender_non_advisor_refs << \" \" <<   wc <<  \" \"  <<  WPS <<  \" \"  <<  Dic <<  \" \"  <<  function <<  \" \"  <<  pronoun <<  \" \"  <<  ppron <<  \" \"  <<  i <<  \" \"  <<  we <<  \" \"  <<  you  <<  \" \"  <<  shehe <<  \" \"  <<  they <<  \" \"  <<  ipron  <<  \" \"  <<  article <<  \" \"\n\t\t    <<  prep  <<  \" \"  <<  auxverb <<  \" \"  <<  adverb <<  \" \"  <<  conj <<  \" \"  <<  negate <<  \" \"  <<  verb <<  \" \"  <<  adj <<  \" \"  <<  compare <<  \" \"  <<  interrog <<  \" \"  <<  number <<  \" \"  <<  quant <<  \"\\n \"\n\t\t    <<  affect <<  \" \"  <<  posemo <<  \" \"  <<  negemo <<  \" \"  <<  anx <<  \" \"  <<  anger <<  \" \"  <<  sad  <<  \" \"\n\t\t    <<  social  <<  \" \"  <<  family <<  \" \"  <<  friends <<  \" \"  <<  female <<  \" \"  <<  male <<  \"\\n \"  <<  cogproc <<  \" \"  <<  insight <<  \" \"  <<  cause <<  \" \"  <<  discrep <<  \" \"  <<  tentat <<  \" \"  <<  certain <<  \" \"  <<  differ <<  \" \"\n\t\t    <<  percept <<  \" \"  <<  see <<  \" \"  <<  hear  <<  \" \"  <<  feel  <<  \" \"  <<  bio  <<  \" \"  <<  body  <<  \" \"  <<  health <<  \" \"  <<  sexual <<  \" \"  <<  ingest  <<  \" \"  <<  drives  <<  \" \"  <<  affiliation  <<  \" \" \n\t\t    <<  achiev <<  \" \"  << power <<  \" \"  << reward <<  \" \"  << risk <<  \" \"  <<  focuspast <<  \" \"  <<  focuspresent <<  \" \"  <<  focusfuture  <<  \"\\n \"  << \n\trelativ <<  \" \"  << motion <<  \" \"  << space <<  \" \"  << time <<  \" \"  << work <<  \" \"  << leisure <<  \" \"  << home <<  \" \"  << money <<  \" \"  << relig <<  \" \"\n\t\t    << death <<  \"\\n \"  << informal <<  \" \"  << swear <<  \" \"  << netspeak <<  \" \"  << assent <<  \" \"  << nonflu <<  \" \"  << filler <<  \" \"  << AllPunc <<  \" \"  << Period <<  \" \"  << Comma <<  \" \"\n\t\t    << Colon <<  \" \"  << SemiC <<  \" \"  << QMark <<  \" \"  << Exclam <<  \" \"  << Dash <<  \" \"  << Quote <<  \" \"  << \n\tApostro <<  \" \"  << Parent <<  \" \"  << OtherP  << \" \" << internal5 << \" \" << internal6 << \"\\n \\n \" <<  std::endl;\n    }\n\n    if (candId != currentCandidateId) {\n      if (discipline == 1){\n\tif (canGender == 1){\n\t  ++uniqueFemaleCandidatesPhysics;\n\t  candIdFemalePhysicsOut << candidateName << \" \" << candId << std::endl;\n\t}\n\tif (canGender == 0){\n\t  ++uniqueMaleCandidatesPhysics;\n\t  candIdMalePhysicsOut << candidateName << \" \" << candId << std::endl;\n\t}\n      }\n      if (discipline == 0){\n\tif (canGender == 1){\n\t  candIdFemaleSocSciOut << candidateName << \" \" << candId << std::endl;\n\t  ++uniqueFemaleCandidatesSocSci;\n\t}\n\tif (canGender == 0){\n\t  candIdMaleSocSciOut << candidateName << \" \" << candId << std::endl;\n\t  ++uniqueMaleCandidatesSocSci;\n\t}\n      }\n      currentCandidateId = candId;\n    }\n    useBoth = false;\n    std::cout << \"finished\" << std::endl;\n    if  (useBoth && both < 0.5) continue;\n    std::cout << \" candidate and writer \" << canGender << \" \" << writerGender << \" \" << candId << std::endl;\n    if (writerGender < 0.5){std::cout << \"male writer \" << std::endl;}\n    if (wc < wcCut ) continue;\n\n    if (discipline > 0.5){\n      if (canGender < 0.5 && writerGender < 0.5){\n\tcat = 1;\n\tstd::cout << \"in cat 1\" << std::endl;\n\tnt[0] = cat;\n\tnt[1] = wc;\n\tnt[2] = Analytic;\n\tnt[3] = Clout;\n\tnt[4] = Authentic;\n\tnt[5] = Tone;\n\tnt[6] = WPS;\n\tnt[7] = Dic;\n\tnt[8] = function;\n\tnt[9] = pronoun;\n\tnt[10] = ppron;\n\tnt[11] = i;\n\tnt[12] = we;\n\tnt[13] = you ;\n\tnt[14] = shehe;\n\tnt[15] = they;\n\tnt[16] = ipron;\n\tnt[17] = article;\n\tnt[18] = prep;\n\tnt[19] = auxverb;\n\tnt[20] = adverb;\n\tnt[21] = conj;\n\tnt[22] = negate;\n\tnt[23] = verb;\n\tnt[24] = adj;\n\tnt[25] = compare;\n\tnt[26] = interrog;\n\tnt[27] = number;\n\tnt[28] = quant;\n\tnt[29] = affect;\n\tnt[30] = posemo;\n\tnt[31] = negemo;\n\tnt[32] = anx;\n\tnt[33] = anger;\n\tnt[34] = sad ;\n\tnt[35] = social ;\n\tnt[36] = family;\n\tnt[37] = friends;\n\tnt[38] = female;\n\tnt[39] = male;\n\tnt[40] = cogproc;\n\tnt[41] = insight;\n\tnt[42] = cause;\n\tnt[43] = discrep;\n\tnt[44] = tentat;\n\tnt[45] = certain;\n\tnt[46] = differ;\n\tnt[47] = percept;\n\tnt[48] = see;\n\tnt[49] = hear;\n\tnt[50] = feel;\n\tnt[51] = bio;\n\tnt[52] = body;\n\tnt[53] = health;\n\tnt[54] = sexual;\n\tnt[55] = ingest;\n\tnt[56] = drives;\n\tnt[57] = affiliation;\n\tnt[58] = achiev;\n\tnt[59] = power;\n\tnt[60] = reward;\n\tnt[61] = risk;\n\tnt[62] = focuspast;\n\tnt[63] = focuspresent;\n\tnt[64] = focusfuture ;\n\tnt[65] = relativ;\n\tnt[66] = motion;\n\tnt[67] = space;\n\tnt[68] = time;\n\tnt[69] = work;\n\tnt[70] = leisure;\n\tnt[71] = home;\n\tnt[72] = money;\n\tnt[73] = relig;\n\tnt[74] = death;\n\tnt[75] = informal;\n\tnt[76] = swear;\n\tnt[77] = netspeak;\n\tnt[78] = assent;\n\tnt[79] = nonflu;\n\tnt[80] = filler;\n\tnt[81] = AllPunc;\n\tnt[82] = Period;\n\tnt[83] = Comma;\n\tnt[84] = Colon;\n\tnt[85] = SemiC;\n\tnt[86] = QMark;\n\tnt[87] = Exclam;\n\tnt[88] = Dash;\n\tnt[89] = Quote;\n\tnt[90] = Apostro;\n\tnt[91] = Parent;\n\tnt[92] = OtherP;\n\n\twordsPhysicscMrM->Fill(wc);\n\tPosemocMrMphysics->Fill(posemo);\n\tNegemocMrMphysics->Fill(negemo);\n\tFloat_t  drivesT = achiev + power - familyRelated;\n\t//drivesT = achiev;\n\tdrivescMrMphysics->Fill(drivesT);\n\taffectcMrMphysics->Fill(affect);\n\tsocialcMrMphysics->Fill(social);\n\tcogProccMrMphysics->Fill(cogproc);\n\ttimeOrientPastcMrMphysics->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecMrMphysics->Fill(focusfuture);\n\tPersConccMrMphysics->Fill(work+leisure+home+money+relig+death);\n\tworkcMrMphysics->Fill(work);\n\thomecMrMphysics->Fill(home);\n\tanalyticcMrMphysics->Fill(Analytic);\n\tcloutcMrMphysics->Fill(Clout);\n\tauthenticcMrMphysics->Fill(Authentic);\n\ttonecMrMphysics->Fill(Tone);\n\tanalyticPhysicsHist->Fill(Analytic);\n\tphysics->Fill(nt);\n\t++nlines;\n      }\n      // cFrM analysis\n    \n      if (canGender > 0.5 && writerGender < 0.5){\n\tcat = 2;\n\tnt[0] = cat;\n\tnt[1] = wc;\n\tnt[2] = Analytic;\n\tnt[3] = Clout;\n\tnt[4] = Authentic;\n\tnt[5] = Tone;\n\tnt[6] = WPS;\n\tnt[7] = Dic;\n\tnt[8] = function;\n\tnt[9] = pronoun;\n\tnt[10] = ppron;\n\tnt[11] = i;\n\tnt[12] = we;\n\tnt[13] = you ;\n\tnt[14] = shehe;\n\tnt[15] = they;\n\tnt[16] = ipron;\n\tnt[17] = article;\n\tnt[18] = prep;\n\tnt[19] = auxverb;\n\tnt[20] = adverb;\n\tnt[21] = conj;\n\tnt[22] = negate;\n\tnt[23] = verb;\n\tnt[24] = adj;\n\tnt[25] = compare;\n\tnt[26] = interrog;\n\tnt[27] = number;\n\tnt[28] = quant;\n\tnt[29] = affect;\n\tnt[30] = posemo;\n\tnt[31] = negemo;\n\tnt[32] = anx;\n\tnt[33] = anger;\n\tnt[34] = sad ;\n\tnt[35] = social ;\n\tnt[36] = family;\n\tnt[37] = friends;\n\tnt[38] = female;\n\tnt[39] = male;\n\tnt[40] = cogproc;\n\tnt[41] = insight;\n\tnt[42] = cause;\n\tnt[43] = discrep;\n\tnt[44] = tentat;\n\tnt[45] = certain;\n\tnt[46] = differ;\n\tnt[47] = percept;\n\tnt[48] = see;\n\tnt[49] = hear;\n\tnt[50] = feel;\n\tnt[51] = bio;\n\tnt[52] = body;\n\tnt[53] = health;\n\tnt[54] = sexual;\n\tnt[55] = ingest;\n\tnt[56] = drives;\n\tnt[57] = affiliation;\n\tnt[58] = achiev;\n\tnt[59] = power;\n\tnt[60] = reward;\n\tnt[61] = risk;\n\tnt[62] = focuspast;\n\tnt[63] = focuspresent;\n\tnt[64] = focusfuture ;\n\tnt[65] = relativ;\n\tnt[66] = motion;\n\tnt[67] = space;\n\tnt[68] = time;\n\tnt[69] = work;\n\tnt[70] = leisure;\n\tnt[71] = home;\n\tnt[72] = money;\n\tnt[73] = relig;\n\tnt[74] = death;\n\tnt[75] = informal;\n\tnt[76] = swear;\n\tnt[77] = netspeak;\n\tnt[78] = assent;\n\tnt[79] = nonflu;\n\tnt[80] = filler;\n\tnt[81] = AllPunc;\n\tnt[82] = Period;\n\tnt[83] = Comma;\n\tnt[84] = Colon;\n\tnt[85] = SemiC;\n\tnt[86] = QMark;\n\tnt[87] = Exclam;\n\tnt[88] = Dash;\n\tnt[89] = Quote;\n\tnt[90] = Apostro;\n\tnt[91] = Parent;\n\tnt[92] = OtherP;\n\ttimeOrientPastcFrMphysics->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecFrMphysics->Fill(focusfuture);\n\tPosemocFrMphysics->Fill(posemo);\n\tNegemocFrMphysics->Fill(negemo);\n\twordsPhysicscFrM->Fill(wc);\n\tFloat_t  drivesT = achiev + power - familyRelated;\n\t//\tdrivesT = achiev;\n\tdrivescFrMphysics->Fill(drivesT);\n\taffectcFrMphysics->Fill(affect);\n\tsocialcFrMphysics->Fill(social);\n\tcogProccFrMphysics->Fill(cogproc);\n\ttimeOrientPastcFrMphysics->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecFrMphysics->Fill(focusfuture);\n\tPersConccFrMphysics->Fill(work+leisure+home+money+relig+death);\n\tworkcFrMphysics->Fill(work);\n\tanalyticcFrMphysics->Fill(Analytic);\n\tcloutcFrMphysics->Fill(Clout);\n\tauthenticcFrMphysics->Fill(Authentic);\n\ttonecFrMphysics->Fill(Tone);\n\thomecFrMphysics->Fill(home);\n\tanalyticPhysicsHist->Fill(Analytic);\n\n\tphysics->Fill(nt);\n\t++nlines;\n      }\n\n      // cFrF analysis\n      if (canGender > 0.5 && (writerGender > 0.5)){\n\tcat = 3;\n\tstd::cout << \"in cat 3\" << std::endl;\n\tstd::cout   << candidateName << \" \"  <<   wc <<  \" \"  <<  WPS <<  \" \"  <<  Dic <<  \" \"  <<  function <<  \" \"  <<  pronoun <<  \" \"  <<  ppron <<  \" \"  <<  i <<  \" \"  <<  we <<  \" \"  <<  you  <<  \" \"  <<  shehe <<  \" \"  <<  they <<  \" \"  <<  ipron  <<  \" \"  <<  article <<  \" \"\n\t\t    <<  prep  <<  \" \"  <<  auxverb <<  \" \"  <<  adverb <<  \" \"  <<  conj <<  \" \"  <<  negate <<  \" \"  <<  verb <<  \" \"  <<  adj <<  \" \"  <<  compare <<  \" \"  <<  interrog <<  \" \"  <<  number <<  \" \"  <<  quant <<  \"\\n \"\n\t\t    <<  affect <<  \" \"  <<  posemo <<  \" \"  <<  negemo <<  \" \"  <<  anx <<  \" \"  <<  anger <<  \" \"  <<  sad  <<  \" \"\n\t\t    <<  social  <<  \" \"  <<  family <<  \" \"  <<  friends <<  \" \"  <<  female <<  \" \"  <<  male <<  \"\\n \"  <<  cogproc <<  \" \"  <<  insight <<  \" \"  <<  cause <<  \" \"  <<  discrep <<  \" \"  <<  tentat <<  \" \"  <<  certain <<  \" \"  <<  differ <<  \" \"\n\t\t    <<  percept <<  \" \"  <<  see <<  \" \"  <<  hear  <<  \" \"  <<  feel  <<  \" \"  <<  bio  <<  \" \"  <<  body  <<  \" \"  <<  health <<  \" \"  <<  sexual <<  \" \"  <<  ingest  <<  \" \"  <<  drives  <<  \" \"  <<  affiliation  <<  \" \" \n\t\t    <<  achiev <<  \" \"  << power <<  \" \"  << reward <<  \" \"  << risk <<  \" \"  <<  focuspast <<  \" \"  <<  focuspresent <<  \" \"  <<  focusfuture  <<  \"\\n \"  << \n\t  relativ <<  \" \"  << motion <<  \" \"  << space <<  \" \"  << time <<  \" \"  << work <<  \" \"  << leisure <<  \" \"  << home <<  \" \"  << money <<  \" \"  << relig <<  \" \"\n\t\t    << death <<  \"\\n \"  << informal <<  \" \"  << swear <<  \" \"  << netspeak <<  \" \"  << assent <<  \" \"  << nonflu <<  \" \"  << filler <<  \" \"  << AllPunc <<  \" \"  << Period <<  \" \"  << Comma <<  \" \"\n\t\t    << Colon <<  \" \"  << SemiC <<  \" \"  << QMark <<  \" \"  << Exclam <<  \" \"  << Dash <<  \" \"  << Quote <<  \" \"  << \n\t  Apostro <<  \" \"  << Parent <<  \" \"  << OtherP  <<  \"\\n \\n \" <<  std::endl;\n\n\tnt[0] = cat;\n\tnt[1] = wc;\n\tnt[2] = Analytic;\n\tnt[3] = Clout;\n\tnt[4] = Authentic;\n\tnt[5] = Tone;\n\tnt[6] = WPS;\n\tnt[7] = Dic;\n\tnt[8] = function;\n\tnt[9] = pronoun;\n\tnt[10] = ppron;\n\tnt[11] = i;\n\tnt[12] = we;\n\tnt[13] = you ;\n\tnt[14] = shehe;\n\tnt[15] = they;\n\tnt[16] = ipron;\n\tnt[17] = article;\n\tnt[18] = prep;\n\tnt[19] = auxverb;\n\tnt[20] = adverb;\n\tnt[21] = conj;\n\tnt[22] = negate;\n\tnt[23] = verb;\n\tnt[24] = adj;\n\tnt[25] = compare;\n\tnt[26] = interrog;\n\tnt[27] = number;\n\tnt[28] = quant;\n\tnt[29] = affect;\n\tnt[30] = posemo;\n\tnt[31] = negemo;\n\tnt[32] = anx;\n\tnt[33] = anger;\n\tnt[34] = sad ;\n\tnt[35] = social ;\n\tnt[36] = family;\n\tnt[37] = friends;\n\tnt[38] = female;\n\tnt[39] = male;\n\tnt[40] = cogproc;\n\tnt[41] = insight;\n\tnt[42] = cause;\n\tnt[43] = discrep;\n\tnt[44] = tentat;\n\tnt[45] = certain;\n\tnt[46] = differ;\n\tnt[47] = percept;\n\tnt[48] = see;\n\tnt[49] = hear;\n\tnt[50] = feel;\n\tnt[51] = bio;\n\tnt[52] = body;\n\tnt[53] = health;\n\tnt[54] = sexual;\n\tnt[55] = ingest;\n\tnt[56] = drives;\n\tnt[57] = affiliation;\n\tnt[58] = achiev;\n\tnt[59] = power;\n\tnt[60] = reward;\n\tnt[61] = risk;\n\tnt[62] = focuspast;\n\tnt[63] = focuspresent;\n\tnt[64] = focusfuture ;\n\tnt[65] = relativ;\n\tnt[66] = motion;\n\tnt[67] = space;\n\tnt[68] = time;\n\tnt[69] = work;\n\tnt[70] = leisure;\n\tnt[71] = home;\n\tnt[72] = money;\n\tnt[73] = relig;\n\tnt[74] = death;\n\tnt[75] = informal;\n\tnt[76] = swear;\n\tnt[77] = netspeak;\n\tnt[78] = assent;\n\tnt[79] = nonflu;\n\tnt[80] = filler;\n\tnt[81] = AllPunc;\n\tnt[82] = Period;\n\tnt[83] = Comma;\n\tnt[84] = Colon;\n\tnt[85] = SemiC;\n\tnt[86] = QMark;\n\tnt[87] = Exclam;\n\tnt[88] = Dash;\n\tnt[89] = Quote;\n\tnt[90] = Apostro;\n\tnt[91] = Parent;\n\tnt[92] = OtherP;\n\tPosemocFrFphysics->Fill(posemo);\n\tNegemocFrFphysics->Fill(negemo);\n\twordsPhysicscFrF->Fill(wc);\n\tFloat_t  drivesT = achiev + power - familyRelated;\n\t//drivesT\tdrivesT = achiev;\n\tdrivescFrFphysics->Fill(drivesT);\n\taffectcFrFphysics->Fill(affect);\n\tsocialcFrFphysics->Fill(social);\n\tcogProccFrFphysics->Fill(cogproc);\n\ttimeOrientPastcFrFphysics->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecFrFphysics->Fill(focusfuture);\n\tPersConccFrFphysics->Fill(work+leisure+home+money+relig+death);\n\tworkcFrFphysics->Fill(work);\n\n\tanalyticcFrFphysics->Fill(Analytic);\n\tcloutcFrFphysics->Fill(Clout);\n\tauthenticcFrFphysics->Fill(Authentic);\n\ttonecFrFphysics->Fill(Tone);\n\thomecFrFphysics->Fill(home);\n \tanalyticPhysicsHist->Fill(Analytic);\n\n\tphysics->Fill(nt);\n\t++nlines;\n      }\n\n\n      // cMrF analysis\n      if (canGender < 0.5 && writerGender > 0.5){\n\tcat = 4;\n\tstd::cout << \"in cat 4\" << std::endl;\n\n\tnt[0] = cat;\n\tnt[1] = wc;\n\tnt[2] = Analytic;\n\tnt[3] = Clout;\n\tnt[4] = Authentic;\n\tnt[5] = Tone;\n\tnt[6] = WPS;\n\tnt[7] = Dic;\n\tnt[8] = function;\n\tnt[9] = pronoun;\n\tnt[10] = ppron;\n\tnt[11] = i;\n\tnt[12] = we;\n\tnt[13] = you ;\n\tnt[14] = shehe;\n\tnt[15] = they;\n\tnt[16] = ipron;\n\tnt[17] = article;\n\tnt[18] = prep;\n\tnt[19] = auxverb;\n\tnt[20] = adverb;\n\tnt[21] = conj;\n\tnt[22] = negate;\n\tnt[23] = verb;\n\tnt[24] = adj;\n\tnt[25] = compare;\n\tnt[26] = interrog;\n\tnt[27] = number;\n\tnt[28] = quant;\n\tnt[29] = affect;\n\tnt[30] = posemo;\n\tnt[31] = negemo;\n\tnt[32] = anx;\n\tnt[33] = anger;\n\tnt[34] = sad ;\n\tnt[35] = social ;\n\tnt[36] = family;\n\tnt[37] = friends;\n\tnt[38] = female;\n\tnt[39] = male;\n\tnt[40] = cogproc;\n\tnt[41] = insight;\n\tnt[42] = cause;\n\tnt[43] = discrep;\n\tnt[44] = tentat;\n\tnt[45] = certain;\n\tnt[46] = differ;\n\tnt[47] = percept;\n\tnt[48] = see;\n\tnt[49] = hear;\n\tnt[50] = feel;\n\tnt[51] = bio;\n\tnt[52] = body;\n\tnt[53] = health;\n\tnt[54] = sexual;\n\tnt[55] = ingest;\n\tnt[56] = drives;\n\tnt[57] = affiliation;\n\tnt[58] = achiev;\n\tnt[59] = power;\n\tnt[60] = reward;\n\tnt[61] = risk;\n\tnt[62] = focuspast;\n\tnt[63] = focuspresent;\n\tnt[64] = focusfuture ;\n\tnt[65] = relativ;\n\tnt[66] = motion;\n\tnt[67] = space;\n\tnt[68] = time;\n\tnt[69] = work;\n\tnt[70] = leisure;\n\tnt[71] = home;\n\tnt[72] = money;\n\tnt[73] = relig;\n\tnt[74] = death;\n\tnt[75] = informal;\n\tnt[76] = swear;\n\tnt[77] = netspeak;\n\tnt[78] = assent;\n\tnt[79] = nonflu;\n\tnt[80] = filler;\n\tnt[81] = AllPunc;\n\tnt[82] = Period;\n\tnt[83] = Comma;\n\tnt[84] = Colon;\n\tnt[85] = SemiC;\n\tnt[86] = QMark;\n\tnt[87] = Exclam;\n\tnt[88] = Dash;\n\tnt[89] = Quote;\n\tnt[90] = Apostro;\n\tnt[91] = Parent;\n\tnt[92] = OtherP;\n\tPosemocMrFphysics->Fill(posemo);\n\tNegemocMrFphysics->Fill(negemo);\n\tFloat_t  drivesT = achiev + power - familyRelated;\n\t//\tdrivesT= achiev;\n        wordsPhysicscMrF->Fill(wc);\n\tdrivescMrFphysics->Fill(drivesT);\n\taffectcMrFphysics->Fill(affect);\n\tsocialcMrFphysics->Fill(social);\n\tcogProccMrFphysics->Fill(cogproc);\n\ttimeOrientPastcMrFphysics->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecMrFphysics->Fill(focusfuture);\n\tPersConccMrFphysics->Fill(work+leisure+home+money+relig+death);\n\tworkcMrFphysics->Fill(work);\n\thomecMrFphysics->Fill(home);\n \tanalyticPhysicsHist->Fill(Analytic);\n\n\tanalyticcMrFphysics->Fill(Analytic);\n\tcloutcMrFphysics->Fill(Clout);\n\tauthenticcMrFphysics->Fill(Authentic);\n\ttonecMrFphysics->Fill(Tone);\n\n    \n\tphysics->Fill(nt);\n\t++nlines;\n      }\n    }\n\n\n\n    if (discipline < 0.5){\n      std::cout << \"in soscsi clause\" << std::endl;\t\n      if (canGender < 0.5 && writerGender < 0.5){\n\n\tcat = 5; \n\tnt[0] = cat;\n\tnt[1] = wc;\n\tnt[2] = Analytic;\n\tnt[3] = Clout;\n\tnt[4] = Authentic;\n\tnt[5] = Tone;\n\tnt[6] = WPS;\n\tnt[7] = Dic;\n\tnt[8] = function;\n\tnt[9] = pronoun;\n\tnt[10] = ppron;\n\tnt[11] = i;\n\tnt[12] = we;\n\tnt[13] = you ;\n\tnt[14] = shehe;\n\tnt[15] = they;\n\tnt[16] = ipron;\n\tnt[17] = article;\n\tnt[18] = prep;\n\tnt[19] = auxverb;\n\tnt[20] = adverb;\n\tnt[21] = conj;\n\tnt[22] = negate;\n\tnt[23] = verb;\n\tnt[24] = adj;\n\tnt[25] = compare;\n\tnt[26] = interrog;\n\tnt[27] = number;\n\tnt[28] = quant;\n\tnt[29] = affect;\n\tnt[30] = posemo;\n\tnt[31] = negemo;\n\tnt[32] = anx;\n\tnt[33] = anger;\n\tnt[34] = sad ;\n\tnt[35] = social ;\n\tnt[36] = family;\n\tnt[37] = friends;\n\tnt[38] = female;\n\tnt[39] = male;\n\tnt[40] = cogproc;\n\tnt[41] = insight;\n\tnt[42] = cause;\n\tnt[43] = discrep;\n\tnt[44] = tentat;\n\tnt[45] = certain;\n\tnt[46] = differ;\n\tnt[47] = percept;\n\tnt[48] = see;\n\tnt[49] = hear;\n\tnt[50] = feel;\n\tnt[51] = bio;\n\tnt[52] = body;\n\tnt[53] = health;\n\tnt[54] = sexual;\n\tnt[55] = ingest;\n\tnt[56] = drives;\n\tnt[57] = affiliation;\n\tnt[58] = achiev;\n\tnt[59] = power;\n\tnt[60] = reward;\n\tnt[61] = risk;\n\tnt[62] = focuspast;\n\tnt[63] = focuspresent;\n\tnt[64] = focusfuture ;\n\tnt[65] = relativ;\n\tnt[66] = motion;\n\tnt[67] = space;\n\tnt[68] = time;\n\tnt[69] = work;\n\tnt[70] = leisure;\n\tnt[71] = home;\n\tnt[72] = money;\n\tnt[73] = relig;\n\tnt[74] = death;\n\tnt[75] = informal;\n\tnt[76] = swear;\n\tnt[77] = netspeak;\n\tnt[78] = assent;\n\tnt[79] = nonflu;\n\tnt[80] = filler;\n\tnt[81] = AllPunc;\n\tnt[82] = Period;\n\tnt[83] = Comma;\n\tnt[84] = Colon;\n\tnt[85] = SemiC;\n\tnt[86] = QMark;\n\tnt[87] = Exclam;\n\tnt[88] = Dash;\n\tnt[89] = Quote;\n\tnt[90] = Apostro;\n\tnt[91] = Parent;\n\tnt[92] = OtherP;\n\tPosemocMrMsocsci->Fill(posemo);\n\tNegemocMrMsocsci->Fill(negemo);\n\tFloat_t  drivesT = achiev + power - familyRelated;\n\t//\tdrivesT = achiev;\n\twordsSocScicMrM->Fill(wc);\n\tdrivescMrMsocsci->Fill(drivesT);\n\taffectcMrMsocsci->Fill(affect);\n\tsocialcMrMsocsci->Fill(social);\n\tcogProccMrMsocsci->Fill(cogproc);\n\ttimeOrientPastcMrMsocsci->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecMrMsocsci->Fill(focusfuture);\n\tPersConccMrMsocsci->Fill(work+leisure+home+money+relig+death);\n\tworkVsSocialcMrMsocsci->Fill(work,social);\n\tworkcMrMsocsci->Fill(work);\n\tanalyticcMrMsocsci->Fill(Analytic);\n\tcloutcMrMsocsci->Fill(Clout);\n\tauthenticcMrMsocsci->Fill(Authentic);\n\ttonecMrMsocsci->Fill(Tone);\n\thomecMrMsocsci->Fill(home);\n \tanalyticSocSciHist->Fill(Analytic);\n\n\tsocsci->Fill(nt);\n\t++nlines;\n      }\n      // cFrm analysis\n      if ( canGender > 0.5 && writerGender < 0.5){\n\n\tcat = 6;\n \n\tnt[0] = cat;\n\tnt[1] = wc;\n\tnt[2] = Analytic;\n\tnt[3] = Clout;\n\tnt[4] = Authentic;\n\tnt[5] = Tone;\n\tnt[6] = WPS;\n\tnt[7] = Dic;\n\tnt[8] = function;\n\tnt[9] = pronoun;\n\tnt[10] = ppron;\n\tnt[11] = i;\n\tnt[12] = we;\n\tnt[13] = you ;\n\tnt[14] = shehe;\n\tnt[15] = they;\n\tnt[16] = ipron;\n\tnt[17] = article;\n\tnt[18] = prep;\n\tnt[19] = auxverb;\n\tnt[20] = adverb;\n\tnt[21] = conj;\n\tnt[22] = negate;\n\tnt[23] = verb;\n\tnt[24] = adj;\n\tnt[25] = compare;\n\tnt[26] = interrog;\n\tnt[27] = number;\n\tnt[28] = quant;\n\tnt[29] = affect;\n\tnt[30] = posemo;\n\tnt[31] = negemo;\n\tnt[32] = anx;\n\tnt[33] = anger;\n\tnt[34] = sad ;\n\tnt[35] = social ;\n\tnt[36] = family;\n\tnt[37] = friends;\n\tnt[38] = female;\n\tnt[39] = male;\n\tnt[40] = cogproc;\n\tnt[41] = insight;\n\tnt[42] = cause;\n\tnt[43] = discrep;\n\tnt[44] = tentat;\n\tnt[45] = certain;\n\tnt[46] = differ;\n\tnt[47] = percept;\n\tnt[48] = see;\n\tnt[49] = hear;\n\tnt[50] = feel;\n\tnt[51] = bio;\n\tnt[52] = body;\n\tnt[53] = health;\n\tnt[54] = sexual;\n\tnt[55] = ingest;\n\tnt[56] = drives;\n\tnt[57] = affiliation;\n\tnt[58] = achiev;\n\tnt[59] = power;\n\tnt[60] = reward;\n\tnt[61] = risk;\n\tnt[62] = focuspast;\n\tnt[63] = focuspresent;\n\tnt[64] = focusfuture ;\n\tnt[65] = relativ;\n\tnt[66] = motion;\n\tnt[67] = space;\n\tnt[68] = time;\n\tnt[69] = work;\n\tnt[70] = leisure;\n\tnt[71] = home;\n\tnt[72] = money;\n\tnt[73] = relig;\n\tnt[74] = death;\n\tnt[75] = informal;\n\tnt[76] = swear;\n\tnt[77] = netspeak;\n\tnt[78] = assent;\n\tnt[79] = nonflu;\n\tnt[80] = filler;\n\tnt[81] = AllPunc;\n\tnt[82] = Period;\n\tnt[83] = Comma;\n\tnt[84] = Colon;\n\tnt[85] = SemiC;\n\tnt[86] = QMark;\n\tnt[87] = Exclam;\n\tnt[88] = Dash;\n\tnt[89] = Quote;\n\tnt[90] = Apostro;\n\tnt[91] = Parent;\n\tnt[92] = OtherP;\n\n\tPosemocFrMsocsci->Fill(posemo);\n\tNegemocFrMsocsci->Fill(negemo);\n\tFloat_t  drivesT = achiev + power - familyRelated;\n\t//\tdrivesT = achiev;\n\twordsSocScicFrM->Fill(wc);\n\tdrivescFrMsocsci->Fill(drivesT);\n\taffectcFrMsocsci->Fill(affect);\n\tsocialcFrMsocsci->Fill(social);\n\tcogProccFrMsocsci->Fill(cogproc);\n\ttimeOrientPastcFrMsocsci->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecFrMsocsci->Fill(focusfuture);\n\tPersConccFrMsocsci->Fill(work+leisure+home+money+relig+death);\n\tworkVsSocialcFrMsocsci->Fill(work,social);\n\tworkcFrMsocsci->Fill(work);\n\thomecFrMsocsci->Fill(home);\n \n\tanalyticcFrMsocsci->Fill(Analytic);\n\tcloutcFrMsocsci->Fill(Clout);\n\tauthenticcFrMsocsci->Fill(Authentic);\n\ttonecFrMsocsci->Fill(Tone);\n\tanalyticSocSciHist->Fill(Analytic);\n\n\tsocsci->Fill(nt);\n\t++nlines;\n      }\n\n      // cFrF analysis\n\n      if (canGender > 0.5 && (writerGender > 0.5)){\n\tcat = 7;\n \n\n\n\tnt[0] = cat;\n\tnt[1] = wc;\n\tnt[2] = Analytic;\n\tnt[3] = Clout;\n\tnt[4] = Authentic;\n\tnt[5] = Tone;\n\tnt[6] = WPS;\n\tnt[7] = Dic;\n\tnt[8] = function;\n\tnt[9] = pronoun;\n\tnt[10] = ppron;\n\tnt[11] = i;\n\tnt[12] = we;\n\tnt[13] = you ;\n\tnt[14] = shehe;\n\tnt[15] = they;\n\tnt[16] = ipron;\n\tnt[17] = article;\n\tnt[18] = prep;\n\tnt[19] = auxverb;\n\tnt[20] = adverb;\n\tnt[21] = conj;\n\tnt[22] = negate;\n\tnt[23] = verb;\n\tnt[24] = adj;\n\tnt[25] = compare;\n\tnt[26] = interrog;\n\tnt[27] = number;\n\tnt[28] = quant;\n\tnt[29] = affect;\n\tnt[30] = posemo;\n\tnt[31] = negemo;\n\tnt[32] = anx;\n\tnt[33] = anger;\n\tnt[34] = sad ;\n\tnt[35] = social ;\n\tnt[36] = family;\n\tnt[37] = friends;\n\tnt[38] = female;\n\tnt[39] = male;\n\tnt[40] = cogproc;\n\tnt[41] = insight;\n\tnt[42] = cause;\n\tnt[43] = discrep;\n\tnt[44] = tentat;\n\tnt[45] = certain;\n\tnt[46] = differ;\n\tnt[47] = percept;\n\tnt[48] = see;\n\tnt[49] = hear;\n\tnt[50] = feel;\n\tnt[51] = bio;\n\tnt[52] = body;\n\tnt[53] = health;\n\tnt[54] = sexual;\n\tnt[55] = ingest;\n\tnt[56] = drives;\n\tnt[57] = affiliation;\n\tnt[58] = achiev;\n\tnt[59] = power;\n\tnt[60] = reward;\n\tnt[61] = risk;\n\tnt[62] = focuspast;\n\tnt[63] = focuspresent;\n\tnt[64] = focusfuture ;\n\tnt[65] = relativ;\n\tnt[66] = motion;\n\tnt[67] = space;\n\tnt[68] = time;\n\tnt[69] = work;\n\tnt[70] = leisure;\n\tnt[71] = home;\n\tnt[72] = money;\n\tnt[73] = relig;\n\tnt[74] = death;\n\tnt[75] = informal;\n\tnt[76] = swear;\n\tnt[77] = netspeak;\n\tnt[78] = assent;\n\tnt[79] = nonflu;\n\tnt[80] = filler;\n\tnt[81] = AllPunc;\n\tnt[82] = Period;\n\tnt[83] = Comma;\n\tnt[84] = Colon;\n\tnt[85] = SemiC;\n\tnt[86] = QMark;\n\tnt[87] = Exclam;\n\tnt[88] = Dash;\n\tnt[89] = Quote;\n\tnt[90] = Apostro;\n\tnt[91] = Parent;\n\tnt[92] = OtherP;\n\tPosemocFrFsocsci->Fill(posemo);\n\tNegemocFrFsocsci->Fill(negemo);\n\tFloat_t  drivesT = achiev + power - familyRelated;\n\t//\tdrivesT = achiev;\n\twordsSocScicFrF->Fill(wc);\n\tdrivescFrFsocsci->Fill(drivesT);\n\taffectcFrFsocsci->Fill(affect);\n\tsocialcFrFsocsci->Fill(social);\n\tcogProccFrFsocsci->Fill(cogproc);\n\ttimeOrientPastcFrFsocsci->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecFrFsocsci->Fill(focusfuture);\n\tPersConccFrFsocsci->Fill(work+leisure+home+money+relig+death);\n\tworkVsSocialcFrFsocsci->Fill(work,social);\n\tworkcFrFsocsci->Fill(work);\n\n\tanalyticcFrFsocsci->Fill(Analytic);\n\tcloutcFrFsocsci->Fill(Clout);\n\tauthenticcFrFsocsci->Fill(Authentic);\n\ttonecFrFsocsci->Fill(Tone);\n\thomecFrFsocsci->Fill(home);\n \tanalyticSocSciHist->Fill(Analytic);\n\n\tsocsci->Fill(nt);\n\t++nlines;\n      }\n\n\n      // cMrF analysis\n      if (canGender < 0.5 && writerGender > 0.5){\n\tcat = 8;\n\tnt[0] = cat;\n\tnt[1] = wc;\n\tnt[2] = Analytic;\n\tnt[3] = Clout;\n\tnt[4] = Authentic;\n\tnt[5] = Tone;\n\tnt[6] = WPS;\n\tnt[7] = Dic;\n\tnt[8] = function;\n\tnt[9] = pronoun;\n\tnt[10] = ppron;\n\tnt[11] = i;\n\tnt[12] = we;\n\tnt[13] = you ;\n\tnt[14] = shehe;\n\tnt[15] = they;\n\tnt[16] = ipron;\n\tnt[17] = article;\n\tnt[18] = prep;\n\tnt[19] = auxverb;\n\tnt[20] = adverb;\n\tnt[21] = conj;\n\tnt[22] = negate;\n\tnt[23] = verb;\n\tnt[24] = adj;\n\tnt[25] = compare;\n\tnt[26] = interrog;\n\tnt[27] = number;\n\tnt[28] = quant;\n\tnt[29] = affect;\n\tnt[30] = posemo;\n\tnt[31] = negemo;\n\tnt[32] = anx;\n\tnt[33] = anger;\n\tnt[34] = sad ;\n\tnt[35] = social ;\n\tnt[36] = family;\n\tnt[37] = friends;\n\tnt[38] = female;\n\tnt[39] = male;\n\tnt[40] = cogproc;\n\tnt[41] = insight;\n\tnt[42] = cause;\n\tnt[43] = discrep;\n\tnt[44] = tentat;\n\tnt[45] = certain;\n\tnt[46] = differ;\n\tnt[47] = percept;\n\tnt[48] = see;\n\tnt[49] = hear;\n\tnt[50] = feel;\n\tnt[51] = bio;\n\tnt[52] = body;\n\tnt[53] = health;\n\tnt[54] = sexual;\n\tnt[55] = ingest;\n\tnt[56] = drives;\n\tnt[57] = affiliation;\n\tnt[58] = achiev;\n\tnt[59] = power;\n\tnt[60] = reward;\n\tnt[61] = risk;\n\tnt[62] = focuspast;\n\tnt[63] = focuspresent;\n\tnt[64] = focusfuture ;\n\tnt[65] = relativ;\n\tnt[66] = motion;\n\tnt[67] = space;\n\tnt[68] = time;\n\tnt[69] = work;\n\tnt[70] = leisure;\n\tnt[71] = home;\n\tnt[72] = money;\n\tnt[73] = relig;\n\tnt[74] = death;\n\tnt[75] = informal;\n\tnt[76] = swear;\n\tnt[77] = netspeak;\n\tnt[78] = assent;\n\tnt[79] = nonflu;\n\tnt[80] = filler;\n\tnt[81] = AllPunc;\n\tnt[82] = Period;\n\tnt[83] = Comma;\n\tnt[84] = Colon;\n\tnt[85] = SemiC;\n\tnt[86] = QMark;\n\tnt[87] = Exclam;\n\tnt[88] = Dash;\n\tnt[89] = Quote;\n\tnt[90] = Apostro;\n\tnt[91] = Parent;\n\tnt[92] = OtherP;\n\tPosemocMrFsocsci->Fill(posemo);\n\tNegemocMrFsocsci->Fill(negemo);\n\tFloat_t  drivesT = achiev + power - familyRelated;\n\t//\tdrivesT = achiev;\n\twordsSocScicMrF->Fill(wc);\n\tdrivescMrFsocsci->Fill(drivesT);\n\taffectcMrFsocsci->Fill(affect);\n\tsocialcMrFsocsci->Fill(social);\n\tcogProccMrFsocsci->Fill(cogproc);\n\ttimeOrientPastcMrFsocsci->Fill(focuspast+focuspresent);\n\ttimeOrientFuturecMrFsocsci->Fill(focusfuture);\n\tPersConccMrFsocsci->Fill(work+leisure+home+money+relig+death);\n\tworkVsSocialcMrFsocsci->Fill(work,social);\n\tworkcMrFsocsci->Fill(work);\n\thomecMrFsocsci->Fill(home);\n \tanalyticSocSciHist->Fill(Analytic);\n\n\tanalyticcMrFsocsci->Fill(Analytic);\n\tcloutcMrFsocsci->Fill(Clout);\n\tauthenticcMrFsocsci->Fill(Authentic);\n\ttonecMrFsocsci->Fill(Tone);\n\n\tsocsci->Fill(nt);\n\t++nlines;\n      }\n    }\n  }\n\n  analysisOut << \"unique Male Candidates Physics = \" << uniqueMaleCandidatesPhysics << std::endl;\n  analysisOut << \"unique Female Candidates Physics = \" << uniqueFemaleCandidatesPhysics << std::endl;\n  analysisOut << \"unique Male Candidates SocSci = \" << uniqueMaleCandidatesSocSci << std::endl;\n  analysisOut << \"unique Female Candidates SocSci = \" << uniqueFemaleCandidatesSocSci << std::endl;\n\n  physics->Write();\n  socsci->Write();\n\n\n  wordsPhysicscMrM->Write(); \n  wordsPhysicscFrM->Write(); \n  wordsPhysicscFrF->Write(); \n  wordsPhysicscMrF->Write(); \n\n\n  wordsSocScicMrM->Write(); \n  wordsSocScicMrF->Write(); \n  wordsSocScicFrF->Write(); \n  wordsSocScicFrM->Write(); \n\n  workcMrMphysics->Write(); \n  workcFrMphysics->Write(); \n  workcFrMphysics->Write(); \n  workcMrFphysics->Write(); \n\n  workcMrMsocsci->Write(); \n  workcFrMsocsci->Write(); \n  workcFrMsocsci->Write(); \n  workcMrFsocsci->Write(); \n\n \n  workVsSocialcMrFsocsci->Write();\n  workVsSocialcMrMsocsci->Write();\n  workVsSocialcFrFsocsci->Write();\n  workVsSocialcFrFsocsci->Write();\n   \n  drivescMrMphysics->Write(); \n  drivescMrFphysics->Write(); \n  drivescFrFphysics->Write(); \n  drivescFrMphysics->Write(); \n\n  drivescMrMsocsci->Write(); \n  drivescMrFsocsci->Write(); \n  drivescFrFsocsci->Write(); \n  drivescFrMsocsci->Write();\n\n\n  affectcMrMphysics->Write(); \n  affectcMrFphysics->Write(); \n  affectcFrFphysics->Write(); \n  affectcFrMphysics->Write(); \n\n  affectcMrMsocsci->Write(); \n  affectcMrFsocsci->Write(); \n  affectcFrFsocsci->Write();\n  affectcFrMsocsci->Write(); \n\n  socialcMrMphysics->Write(); \n  socialcMrFphysics->Write(); \n  socialcFrFphysics->Write(); \n  socialcFrMphysics->Write();\n   \n  socialcMrMsocsci->Write();\n  socialcMrFsocsci->Write(); \n  socialcFrFsocsci->Write(); \n  socialcFrMsocsci->Write(); \n\n  cogProccMrMphysics->Write(); \n  cogProccMrFphysics->Write(); \n  cogProccFrFphysics->Write(); \n  cogProccFrMphysics->Write(); \n\n  cogProccMrMsocsci->Write(); \n  cogProccMrFsocsci->Write(); \n  cogProccFrFsocsci->Write(); \n  cogProccFrMsocsci->Write(); \n\n  \n  timeOrientPastcMrMphysics->Write();\n  timeOrientPastcMrFphysics->Write();\n  timeOrientPastcFrFphysics->Write(); \n  timeOrientPastcFrMphysics->Write(); \n\n  timeOrientPastcMrMsocsci->Write(); \n  timeOrientPastcMrFsocsci->Write(); \n  timeOrientPastcFrFsocsci->Write(); \n  timeOrientPastcFrMsocsci->Write(); \n\n  timeOrientFuturecMrMphysics->Write(); \n  timeOrientFuturecMrFphysics->Write(); \n  timeOrientFuturecFrFphysics->Write(); \n  timeOrientFuturecMrFphysics->Write(); \n\n  timeOrientFuturecMrMsocsci->Write(); \n  timeOrientFuturecMrFsocsci->Write(); \n  timeOrientFuturecFrFsocsci->Write(); \n  timeOrientFuturecFrMsocsci->Write(); \n\n  analyticPhysicsHist->Write();\n  analyticSocSciHist->Write();\n\n  PersConccMrMphysics->Write(); \n  PersConccMrFphysics->Write(); \n  PersConccFrFphysics->Write(); \n  PersConccFrMphysics->Write(); \n\n  PersConccMrMsocsci->Write(); \n  PersConccMrFsocsci->Write(); \n  PersConccFrFsocsci->Write(); \n  PersConccFrMsocsci->Write(); \n\n  workcMrMphysics->Write();\n  workcMrFphysics->Write();\n  workcFrFphysics->Write();\n  workcFrMphysics->Write();\n\n  workcMrMsocsci->Write();\n  workcMrFsocsci->Write();\n  workcFrFsocsci->Write();\n  workcFrMsocsci->Write();\n\n\n  homecMrMphysics->Write();\n  homecMrFphysics->Write();\n  homecFrFphysics->Write();\n  homecFrMphysics->Write();\n\n  homecMrMsocsci->Write();\n  homecMrFsocsci->Write();\n  homecFrFsocsci->Write();\n  homecFrMsocsci->Write();\n\n\n  PosemocMrMphysics->Write();\n  PosemocMrFphysics->Write();\n  PosemocFrFphysics->Write();\n  PosemocFrMphysics->Write();\n\n  PosemocMrMsocsci->Write();\n  PosemocMrFsocsci->Write();\n  PosemocFrFsocsci->Write();\n  PosemocFrMsocsci->Write();\n\n  \n  analyticcMrMsocsci->Write();\n  cloutcMrMsocsci->Write();\n  authenticcMrMsocsci->Write();\n  tonecMrMsocsci->Write();\n\n  analyticcMrFsocsci->Write();\n  cloutcMrFsocsci->Write();\n  authenticcMrFsocsci->Write();\n  tonecMrFsocsci->Write();\n\n  analyticcFrFsocsci->Write();\n  cloutcFrFsocsci->Write();\n  authenticcFrFsocsci->Write();\n  tonecFrFsocsci->Write();\n\n  analyticcFrMsocsci->Write();\n  cloutcFrMsocsci->Write();\n  authenticcFrMsocsci->Write();\n  tonecFrMsocsci->Write();\n\n\n  analyticcMrMphysics->Write();\n  cloutcMrMphysics->Write();\n  authenticcMrMphysics->Write();\n  tonecMrMphysics->Write();\n\n  analyticcMrFphysics->Write();\n  cloutcMrFphysics->Write();\n  authenticcMrFphysics->Write();\n  tonecMrFphysics->Write();\n\n  analyticcFrFphysics->Write();\n  cloutcFrFphysics->Write();\n  authenticcFrFphysics->Write();\n  tonecFrFphysics->Write();\n\n  analyticcFrMphysics->Write();\n  cloutcFrMphysics->Write();\n  authenticcFrMphysics->Write();\n  tonecFrMphysics->Write();\n\n  gStyle->SetOptFit(1);\n\n  /* printouts*/\n\n\n\n  \n  analysisOut << \"Posemo\" << std::endl;\n analysisOut <<    static_cast<Float_t>(PosemocMrMphysics->GetMean()) << \" \" << \n    static_cast<Float_t>(PosemocFrMphysics->GetMean()) << \" \" << \n    static_cast<Float_t>(PosemocFrFphysics->GetMean()) << \" \" <<\n    static_cast<Float_t>(PosemocMrFphysics->GetMean()) << \" \" << std::endl;\n\n\n\t\t\t\t      \n  analysisOut <<    static_cast<Float_t>(PosemocMrMphysics->GetMeanError()) << \" \" << \n    static_cast<Float_t>(PosemocFrMphysics->GetMeanError()) << \" \" << \n    static_cast<Float_t>(PosemocFrFphysics->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(PosemocMrFphysics->GetMeanError()) << \" \" << std::endl;\n\n\n\n  analysisOut <<    static_cast<Float_t>(PosemocMrMsocsci->GetMean()) << \" \" << \n    static_cast<Float_t>(PosemocFrMsocsci->GetMean()) << \" \" << \n    static_cast<Float_t>(PosemocFrFsocsci->GetMean()) << \" \" <<\n    static_cast<Float_t>(PosemocMrFsocsci->GetMean()) << \" \" << std::endl;\n\n   \n  analysisOut <<    static_cast<Float_t>(PosemocMrMsocsci->GetMeanError()) << \" \" << \n    static_cast<Float_t>(PosemocFrMsocsci->GetMeanError()) << \" \" << \n    static_cast<Float_t>(PosemocFrFsocsci->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(PosemocMrFsocsci->GetMeanError()) << \" \" << std::endl;\n\n\n  \n\n  \n  analysisOut << \"Negemo\" << std::endl;\n analysisOut <<    static_cast<Float_t>(NegemocMrMphysics->GetMean()) << \" \" << \n    static_cast<Float_t>(NegemocFrMphysics->GetMean()) << \" \" << \n    static_cast<Float_t>(NegemocFrFphysics->GetMean()) << \" \" <<\n    static_cast<Float_t>(NegemocMrFphysics->GetMean()) << \" \" << std::endl;\n\n\n\t\t\t\t      \n  analysisOut <<    static_cast<Float_t>(NegemocMrMphysics->GetMeanError()) << \" \" << \n    static_cast<Float_t>(NegemocFrMphysics->GetMeanError()) << \" \" << \n    static_cast<Float_t>(NegemocFrFphysics->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(NegemocMrFphysics->GetMeanError()) << \" \" << std::endl;\n\n\n\n  analysisOut <<    static_cast<Float_t>(NegemocMrMsocsci->GetMean()) << \" \" << \n    static_cast<Float_t>(NegemocFrMsocsci->GetMean()) << \" \" << \n    static_cast<Float_t>(NegemocFrFsocsci->GetMean()) << \" \" <<\n    static_cast<Float_t>(NegemocMrFsocsci->GetMean()) << \" \" << std::endl;\n\n   \n  analysisOut <<    static_cast<Float_t>(NegemocMrMsocsci->GetMeanError()) << \" \" << \n    static_cast<Float_t>(NegemocFrMsocsci->GetMeanError()) << \" \" << \n    static_cast<Float_t>(NegemocFrFsocsci->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(NegemocMrFsocsci->GetMeanError()) << \" \" << std::endl;\n\n\n analysisOut << \"Drives\" << std::endl;\n analysisOut <<    static_cast<Float_t>(drivescMrMphysics->GetMean()) << \" \" << \n    static_cast<Float_t>(drivescFrMphysics->GetMean()) << \" \" << \n    static_cast<Float_t>(drivescFrFphysics->GetMean()) << \" \" <<\n    static_cast<Float_t>(drivescMrFphysics->GetMean()) << \" \" << std::endl;\n\n\n\t\t\t\t      \n  analysisOut <<    static_cast<Float_t>(drivescMrMphysics->GetMeanError()) << \" \" << \n    static_cast<Float_t>(drivescFrMphysics->GetMeanError()) << \" \" << \n    static_cast<Float_t>(drivescFrFphysics->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(drivescMrFphysics->GetMeanError()) << \" \" << std::endl;\n\n\n\n  analysisOut <<    static_cast<Float_t>(drivescMrMsocsci->GetMean()) << \" \" << \n    static_cast<Float_t>(drivescFrMsocsci->GetMean()) << \" \" << \n    static_cast<Float_t>(drivescFrFsocsci->GetMean()) << \" \" <<\n    static_cast<Float_t>(drivescMrFsocsci->GetMean()) << \" \" << std::endl;\n\n   \n  analysisOut <<    static_cast<Float_t>(drivescMrMsocsci->GetMeanError()) << \" \" << \n    static_cast<Float_t>(drivescFrMsocsci->GetMeanError()) << \" \" << \n    static_cast<Float_t>(drivescFrFsocsci->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(drivescMrFsocsci->GetMeanError()) << \" \" << std::endl;\n\n\n  /*endprintouts*/\n  TCanvas* c1 = new TCanvas();\n  c1->Divide(2,1);\n  c1->cd(2);\n  TF1* fitDrives = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitDrives->SetParNames(\"average\");\n\n  Float_t x1[4] = {1.,2.,3.,4.};\n  Float_t y1[4] = {\n    static_cast<Float_t>(drivescMrMphysics->GetMean()),\n    static_cast<Float_t>(drivescFrMphysics->GetMean()),\n    static_cast<Float_t>(drivescMrFphysics->GetMean()),\n    static_cast<Float_t>(drivescFrFphysics->GetMean())\n  };\n  Float_t ex1[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey1[4] = {\n    static_cast<Float_t>(drivescMrMphysics->GetMeanError()),\n    static_cast<Float_t>(drivescFrMphysics->GetMeanError()),\n    static_cast<Float_t>(drivescMrFphysics->GetMeanError()),\n    static_cast<Float_t>(drivescFrFphysics->GetMeanError())\n  };\n \n  TGraphErrors* drivesPhysics = new TGraphErrors(4,x1,y1,ex1,ey1);\n\n\n  drivesPhysics->SetMaximum(10.0);\n  drivesPhysics->SetMinimum(5.0);\n\n  drivesPhysics->SetTitle(\"    EPP Drives: achievement + power    \");\n  TFitResultPtr fitDrivesPhysics = drivesPhysics->Fit(\"fits\",\"S\");\n  Double_t   parDrivesPhysics = fitDrivesPhysics->Value(0);\n  Double_t  errDrivesPhysics = fitDrivesPhysics->ParError(0);\n  TAxis* yAxisDrivesPhysics = drivesPhysics->GetYaxis();\n  yAxisDrivesPhysics->SetTitle(\"% of Words\");\n  TAxis* xaxisDrivesPhysics= drivesPhysics->GetXaxis();\n  xaxisDrivesPhysics->SetTickLength(0.);\n  //  xaxisDrivesPhysics->CenterTitle(kTRUE);\n  //xaxisDrivesPhysics->SetTitle(\"#splitline{male writers                          female writers}{male candidate female candidate      }\");\n  xaxisDrivesPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisDrivesPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisDrivesPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisDrivesPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisDrivesPhysics->ChangeLabel(2,-1.,0.);\n  xaxisDrivesPhysics->ChangeLabel(4,-1.,0.);\n  xaxisDrivesPhysics->ChangeLabel(6,-1.,0.);\n  xaxisDrivesPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisDrivesPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisDrivesPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisDrivesPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisDrivesPhysics->ChangeLabel(2,-1.,0.);\n  xaxisDrivesPhysics->ChangeLabel(4,-1.,0.);\n  xaxisDrivesPhysics->ChangeLabel(6,-1.,0.);\n \n  drivesPhysics->SetFillColor(38);\n  drivesPhysics->Draw(\"AB\");\n  TBox* boxDrivesPhysics = new TBox(0.6,parDrivesPhysics-errDrivesPhysics,4.4,parDrivesPhysics+errDrivesPhysics);\n  boxDrivesPhysics->SetFillColor(kBlue);\n  boxDrivesPhysics->SetFillStyle(3004);\n  drivesPhysics->SetMaximum(parDrivesPhysics+5.*drivescFrFphysics->GetMeanError());\n  drivesPhysics->SetMinimum(TMath::Max(parDrivesPhysics-5.*drivescFrFphysics->GetMeanError(),0.));\n  boxDrivesPhysics->Draw();\n\n  drivesPhysics->Write();\n\n  //\n  // TCanvas* c2 = new TCanvas();\n  c1->cd(1);\n  TF1* fitDrivesSocSci = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitDrivesSocSci->SetParNames(\"average\");\n\n  Float_t x2[4] = {1.,2.,3.,4.};\n  // make measured adjustment for family words.\n  Float_t y2[4] = {\n    static_cast<Float_t>(drivescMrMsocsci->GetMean()),\n    static_cast<Float_t>(drivescFrMsocsci->GetMean()),\n    static_cast<Float_t>(drivescMrFsocsci->GetMean()),\n    static_cast<Float_t>(drivescFrFsocsci->GetMean())\n  };\n \n  Float_t ex2[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey2[4] = {\n    static_cast<Float_t>(drivescMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(drivescFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(drivescMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(drivescFrFsocsci->GetMeanError())\n  };\n \n  TGraphErrors* drivesSocsci = new TGraphErrors(4,x2,y2,ex2,ey2);\n\n\n  drivesSocsci->SetMaximum(10.0);\n  drivesSocsci->SetMinimum(5.0);\n\n  drivesSocsci->SetTitle(\"Social Science Drives: achievement + power\");\n  TFitResultPtr fitDrivesSocsci = drivesSocsci->Fit(\"fits\",\"S\");\n  Double_t   parDrivesSocsci = fitDrivesSocsci->Value(0);\n  Double_t  errDrivesSocsci = fitDrivesSocsci->ParError(0);\n  TAxis* xaxisDrivesSocsci= drivesSocsci->GetXaxis();\n  TAxis* yaxisDrivesSocsci = drivesSocsci->GetYaxis();\n  yaxisDrivesSocsci->SetTitle(\"% of Words\");\n  xaxisDrivesSocsci->SetTickLength(0.);\n  xaxisDrivesSocsci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisDrivesSocsci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisDrivesSocsci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisDrivesSocsci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  /* made uniform with STATA up to here 2/15/2020 8:52 AM*/ \n  xaxisDrivesSocsci->ChangeLabel(2,-1.,0.);\n  xaxisDrivesSocsci->ChangeLabel(4,-1.,0.);\n  xaxisDrivesSocsci->ChangeLabel(6,-1.,0.);\n  drivesSocsci->SetFillColor(38);\n\n  drivesSocsci->Draw(\"AB\");\n  TBox* boxDrivesSocsci = new TBox(0.6,parDrivesSocsci-errDrivesSocsci,4.4,parDrivesSocsci+errDrivesSocsci);\n  boxDrivesSocsci->SetFillColor(kBlue);\n  boxDrivesSocsci->SetFillStyle(3004);\n  drivesSocsci->SetMaximum(parDrivesSocsci+8.*drivescFrFsocsci->GetMeanError());\n  drivesSocsci->SetMinimum(TMath::Max(parDrivesSocsci-8.*drivescFrFsocsci->GetMeanError(),0.));\n \n  boxDrivesSocsci->Draw();\n\n  drivesSocsci->Write();\n\n \n  if (useBoth){\n    c1->SaveAs(\"pdfPlotsLIWCBoth/socsciDrives.pdf\");\n  }else{c1->SaveAs(\"pdfPlotsLIWC/socsciDrives.pdf\");}\n\n\n\n  // 2nd plot family; affect or posemo \n\n  \n  TCanvas* c3 = new TCanvas();\n  TF1* fitAffect = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitAffect->SetParNames(\"average\");\n\n  Float_t x3[4] = {1.,2.,3.,4.};\n  Float_t y3[4] = {\n    static_cast<Float_t>(affectcMrMphysics->GetMean()),\n    static_cast<Float_t>(affectcFrMphysics->GetMean()),\n    static_cast<Float_t>(affectcMrFphysics->GetMean()),\n    static_cast<Float_t>(affectcFrFphysics->GetMean())\n  };\n  Float_t ex3[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey3[4] = {\n    static_cast<Float_t>(affectcMrMphysics->GetMeanError()),\n    static_cast<Float_t>(affectcFrMphysics->GetMeanError()),\n    static_cast<Float_t>(affectcMrFphysics->GetMeanError()),\n    static_cast<Float_t>(affectcFrFphysics->GetMeanError())\n  };\n \n  TGraphErrors* affectPhysics = new TGraphErrors(4,x3,y3,ex3,ey3);\n\n\n\n  affectPhysics->SetTitle(\"Physics LIWC Affect\");\n  TFitResultPtr fitAffectPhysics = affectPhysics->Fit(\"fits\",\"S\");\n  Double_t   parAffectPhysics = fitAffectPhysics->Value(0);\n  Double_t  errAffectPhysics = fitAffectPhysics->ParError(0);\n  TAxis* xaxisAffectPhysics= affectPhysics->GetXaxis();\n  xaxisAffectPhysics->SetTickLength(0.);\n  xaxisAffectPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxisAffectPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxisAffectPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxisAffectPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxisAffectPhysics->ChangeLabel(2,-1.,0.);\n  xaxisAffectPhysics->ChangeLabel(4,-1.,0.);\n  xaxisAffectPhysics->ChangeLabel(6,-1.,0.);\n  affectPhysics->Draw(\"A*\");\n  TBox* boxAffectPhysics = new TBox(0.6,parAffectPhysics-errAffectPhysics,4.4,parAffectPhysics+errAffectPhysics);\n  affectPhysics->SetMaximum(parAffectPhysics + 5.*affectcFrFphysics->GetMeanError());\n  affectPhysics->SetMinimum(TMath::Max(parAffectPhysics - 5.*affectcFrFphysics->GetMeanError(),0.));\n\n  boxAffectPhysics->SetFillColor(kBlue);\n  boxAffectPhysics->SetFillStyle(3004);\n  boxAffectPhysics->Draw();\n\n  affectPhysics->Write();\n  c3->SaveAs(\"pdfPlotsLIWC/physicsAffect.pdf\");\n  //\n  TCanvas* c4 = new TCanvas();\n  TF1* fitAffectSocSci = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitAffectSocSci->SetParNames(\"average\");\n\n  Float_t x4[4] = {1.,2.,3.,4.};\n  Float_t y4[4] = {\n    static_cast<Float_t>(affectcMrMsocsci->GetMean()),\n    static_cast<Float_t>(affectcFrMsocsci->GetMean()),\n    static_cast<Float_t>(affectcMrFsocsci->GetMean()),\n    static_cast<Float_t>(affectcFrFsocsci->GetMean())\n  };\n  Float_t ex4[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey4[4] = {\n    static_cast<Float_t>(affectcMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(affectcFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(affectcMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(affectcFrFsocsci->GetMeanError())\n  };\n \n  TGraphErrors* affectSocsci = new TGraphErrors(4,x4,y4,ex4,ey4);\n\n\n  affectSocsci->SetMaximum(6.0);\n  affectSocsci->SetMinimum(3.0);\n\n  affectSocsci->SetTitle(\"SocSci LIWC Affect\");\n  TFitResultPtr fitAffectSocsci = affectSocsci->Fit(\"fits\",\"S\");\n  Double_t   parAffectSocsci = fitAffectSocsci->Value(0);\n  Double_t  errAffectSocsci = fitAffectSocsci->ParError(0);\n  TAxis* xaxisAffectSocsci= affectSocsci->GetXaxis();\n  xaxisAffectSocsci->SetTickLength(0.);\n  xaxisAffectSocsci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxisAffectSocsci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxisAffectSocsci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxisAffectSocsci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxisAffectSocsci->ChangeLabel(2,-1.,0.);\n  xaxisAffectSocsci->ChangeLabel(4,-1.,0.);\n  xaxisAffectSocsci->ChangeLabel(6,-1.,0.);\n  affectSocsci->Draw(\"A*\");\n  TBox* boxAffectSocsci = new TBox(0.6,parAffectSocsci-errAffectSocsci,4.4,parAffectSocsci+errAffectSocsci);\n  boxAffectSocsci->SetFillColor(kBlue);\n  boxAffectSocsci->SetFillStyle(3004);\n  affectSocsci->SetMaximum(parAffectSocsci + 5.*affectcFrFsocsci->GetMeanError());\n  affectSocsci->SetMinimum(TMath::Max(parAffectSocsci - 5.*affectcFrFsocsci->GetMeanError(),0.));\n\n  boxAffectSocsci->Draw();\n\n  affectSocsci->Write();\n  if (useBoth){\n    c4->SaveAs(\"pdfPlotsLIWCBoth/socsciAffect.pdf\");\n  }else\n    { c4->SaveAs(\"pdfPlotsLIWCBoth/socsciAffect.pdf\");}\n\n  //3rd plot family: social\n  \n  TCanvas* c5 = new TCanvas();\n  TF1* fitSocial = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitSocial->SetParNames(\"average\");\n\n  Float_t x5[4] = {1.,2.,3.,4.};\n  Float_t y5[4] = {\n    static_cast<Float_t>(socialcMrMphysics->GetMean()),\n    static_cast<Float_t>(socialcFrMphysics->GetMean()),\n    static_cast<Float_t>(socialcMrFphysics->GetMean()),\n    static_cast<Float_t>(socialcFrFphysics->GetMean())\n  };\n  Float_t ex5[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey5[4] = {\n    static_cast<Float_t>(socialcMrMphysics->GetMeanError()),\n    static_cast<Float_t>(socialcFrMphysics->GetMeanError()),\n    static_cast<Float_t>(socialcMrFphysics->GetMeanError()),\n    static_cast<Float_t>(socialcFrFphysics->GetMeanError())\n  };\n \n  TGraphErrors* socialPhysics = new TGraphErrors(4,x5,y5,ex5,ey5);\n\n\n  socialPhysics->SetMaximum(9.);\n  socialPhysics->SetMinimum(5.);\n\n  socialPhysics->SetTitle(\"Physics LIWC Social\");\n  TFitResultPtr fitSocialPhysics = socialPhysics->Fit(\"fits\",\"S\");\n  Double_t   parSocialPhysics = fitSocialPhysics->Value(0);\n  Double_t  errSocialPhysics = fitSocialPhysics->ParError(0);\n  TAxis* xaxisSocialPhysics= socialPhysics->GetXaxis();\n  xaxisSocialPhysics->SetTickLength(0.);\n  xaxisSocialPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxisSocialPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxisSocialPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxisSocialPhysics->ChangeLabel(6,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxisSocialPhysics->ChangeLabel(2,-1.,0.);\n  xaxisSocialPhysics->ChangeLabel(4,-1.,0.);\n  xaxisSocialPhysics->ChangeLabel(6,-1.,0.);\n  socialPhysics->Draw(\"A*\");\n  TBox* boxSocialPhysics = new TBox(0.6,parSocialPhysics-errSocialPhysics,4.4,parSocialPhysics+errSocialPhysics);\n  boxSocialPhysics->SetFillColor(kBlue);\n  boxSocialPhysics->SetFillStyle(3004);\n  socialPhysics->SetMaximum(parSocialPhysics + 5.*socialcFrFphysics->GetMeanError());\n  socialPhysics->SetMinimum(TMath::Max(parSocialPhysics - 5.*socialcFrFphysics->GetMeanError(),0.));\n\n  boxSocialPhysics->Draw();\n\n  socialPhysics->Write();\n  if (useBoth){\n    c5->SaveAs(\"pdfPlotsLIWCBoth/physicsSocial.pdf\");\n  }else {c5->SaveAs(\"pdfPlotsLIWCBoth/physicsSocial.pdf\");}\n  //\n  TCanvas* c6 = new TCanvas();\n  TF1* fitSocialSocSci = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitSocialSocSci->SetParNames(\"average\");\n\n  Float_t x6[4] = {1.,2.,3.,4.};\n  Float_t y6[4] = {\n    static_cast<Float_t>(socialcMrMsocsci->GetMean()),\n    static_cast<Float_t>(socialcFrMsocsci->GetMean()),\n    static_cast<Float_t>(socialcMrFsocsci->GetMean()),\n    static_cast<Float_t>(socialcFrFsocsci->GetMean())\n  };\n  Float_t ex6[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey6[4] = {\n    static_cast<Float_t>(socialcMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(socialcFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(socialcMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(socialcFrFsocsci->GetMeanError())\n  };\n \n  TGraphErrors* socialSocsci = new TGraphErrors(4,x6,y6,ex6,ey6);\n\n\n  socialSocsci->SetMaximum(13.);\n  socialSocsci->SetMinimum(7.);\n\n  socialSocsci->SetTitle(\"SocSci LIWC Social\");\n  TFitResultPtr fitSocialSocsci = socialSocsci->Fit(\"fits\",\"S\");\n  Double_t   parSocialSocsci = fitSocialSocsci->Value(0);\n  Double_t  errSocialSocsci = fitSocialSocsci->ParError(0);\n  TAxis* xaxisSocialSocsci= socialSocsci->GetXaxis();\n  xaxisSocialSocsci->SetTickLength(0.);\n  xaxisSocialSocsci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxisSocialSocsci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxisSocialSocsci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxisSocialSocsci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxisSocialSocsci->ChangeLabel(2,-1.,0.);\n  xaxisSocialSocsci->ChangeLabel(4,-1.,0.);\n  xaxisSocialSocsci->ChangeLabel(6,-1.,0.);\n  socialSocsci->Draw(\"A*\");\n  TBox* boxSocialSocsci = new TBox(0.6,parSocialSocsci-errSocialSocsci,4.4,parSocialSocsci+errSocialSocsci);\n  boxSocialSocsci->SetFillColor(kBlue);\n  boxSocialSocsci->SetFillStyle(3004);\n  socialSocsci->SetMaximum(parSocialSocsci + 20.*socialcFrFsocsci->GetMeanError());\n  socialSocsci->SetMinimum(TMath::Max(parSocialSocsci - 20.*socialcFrFsocsci->GetMeanError(),0.));\n\n  boxSocialSocsci->Draw();\n\n  socialSocsci->Write();\n  if (useBoth){\n    c6->SaveAs(\"pdfPlotsLIWCBoth/socsciSocial.pdf\");\n  }else {c6->SaveAs(\"pdfPlotsLIWC/socsciSocial.pdf\");}\n\n  //4th plot family: future time\n\n    \n  TCanvas* c7 = new TCanvas();\n  TF1* fittimeOrientFuture = new TF1(\"fits\",\"[0]\",0.,10.);\n  fittimeOrientFuture->SetParNames(\"average\");\n\n  Float_t x7[4] = {1.,2.,3.,4.};\n  Float_t y7[4] = {\n    static_cast<Float_t>(timeOrientFuturecMrMphysics->GetMean()),\n    static_cast<Float_t>(timeOrientFuturecFrMphysics->GetMean()),\n    static_cast<Float_t>(timeOrientFuturecMrFphysics->GetMean()),\n    static_cast<Float_t>(timeOrientFuturecFrFphysics->GetMean())\n  };\n  Float_t ex7[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey7[4] = {\n    static_cast<Float_t>(timeOrientFuturecMrMphysics->GetMeanError()),\n    static_cast<Float_t>(timeOrientFuturecFrMphysics->GetMeanError()),\n    static_cast<Float_t>(timeOrientFuturecMrFphysics->GetMeanError()),\n    static_cast<Float_t>(timeOrientFuturecFrFphysics->GetMeanError())\n  };\n \n  TGraphErrors* timeOrientFuturePhysics = new TGraphErrors(4,x7,y7,ex7,ey7);\n\n\n  timeOrientFuturePhysics->SetMaximum(1.5);\n  timeOrientFuturePhysics->SetMinimum(0.5);\n\n  timeOrientFuturePhysics->SetTitle(\"Physics LIWC timeOrientFuture\");\n  TFitResultPtr fittimeOrientFuturePhysics = timeOrientFuturePhysics->Fit(\"fits\",\"S\");\n  Double_t   partimeOrientFuturePhysics = fittimeOrientFuturePhysics->Value(0);\n  Double_t  errtimeOrientFuturePhysics = fittimeOrientFuturePhysics->ParError(0);\n  TAxis* xaxistimeOrientFuturePhysics= timeOrientFuturePhysics->GetXaxis();\n  xaxistimeOrientFuturePhysics->SetTickLength(0.);\n  xaxistimeOrientFuturePhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxistimeOrientFuturePhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxistimeOrientFuturePhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxistimeOrientFuturePhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxistimeOrientFuturePhysics->ChangeLabel(2,-1.,0.);\n  xaxistimeOrientFuturePhysics->ChangeLabel(4,-1.,0.);\n  xaxistimeOrientFuturePhysics->ChangeLabel(6,-1.,0.);\n  timeOrientFuturePhysics->SetMaximum(partimeOrientFuturePhysics + 5.*timeOrientFuturecFrFphysics->GetMeanError());\n  timeOrientFuturePhysics->SetMinimum(TMath::Max(partimeOrientFuturePhysics - 5.*timeOrientFuturecFrFphysics->GetMeanError(),0.));\n\n  timeOrientFuturePhysics->Draw(\"A*\");\n  TBox* boxtimeOrientFuturePhysics = new TBox(0.6,partimeOrientFuturePhysics-errtimeOrientFuturePhysics,4.4,partimeOrientFuturePhysics+errtimeOrientFuturePhysics);\n  boxtimeOrientFuturePhysics->SetFillColor(kBlue);\n  boxtimeOrientFuturePhysics->SetFillStyle(3004);\n\n  boxtimeOrientFuturePhysics->Draw();\n\n  timeOrientFuturePhysics->Write();\n  if (useBoth){\n    c7->SaveAs(\"pdfPlotsLIWCBoth/physicsFuture.pdf\");\n  } else {c7->SaveAs(\"pdfPlotsLIWC/physicsFuture.pdf\");}\n  //\n  TCanvas* c8 = new TCanvas();\n  TF1* fittimeOrientFutureSocSci = new TF1(\"fits\",\"[0]\",0.,10.);\n  fittimeOrientFutureSocSci->SetParNames(\"average\");\n\n  Float_t x8[4] = {1.,2.,3.,4.};\n  Float_t y8[4] = {\n    static_cast<Float_t>(timeOrientFuturecMrMsocsci->GetMean()),\n    static_cast<Float_t>(timeOrientFuturecFrMsocsci->GetMean()),\n    static_cast<Float_t>(timeOrientFuturecMrFsocsci->GetMean()),\n    static_cast<Float_t>(timeOrientFuturecFrFsocsci->GetMean())\n  };\n  Float_t ex8[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey8[4] = {\n    static_cast<Float_t>(timeOrientFuturecMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(timeOrientFuturecFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(timeOrientFuturecMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(timeOrientFuturecFrFsocsci->GetMeanError())\n  };\n \n  TGraphErrors* timeOrientFutureSocsci = new TGraphErrors(4,x8,y8,ex8,ey8);\n\n\n  timeOrientFutureSocsci->SetMaximum(1.5);\n  timeOrientFutureSocsci->SetMinimum(0.5);\n\n  timeOrientFutureSocsci->SetTitle(\"SocSci LIWC timeOrientFuture\");\n  TFitResultPtr fittimeOrientFutureSocsci = timeOrientFutureSocsci->Fit(\"fits\",\"S\");\n  Double_t   partimeOrientFutureSocsci = fittimeOrientFutureSocsci->Value(0);\n  Double_t  errtimeOrientFutureSocsci = fittimeOrientFutureSocsci->ParError(0);\n  TAxis* xaxistimeOrientFutureSocsci= timeOrientFutureSocsci->GetXaxis();\n  xaxistimeOrientFutureSocsci->SetTickLength(0.);\n  xaxistimeOrientFutureSocsci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxistimeOrientFutureSocsci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxistimeOrientFutureSocsci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxistimeOrientFutureSocsci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxistimeOrientFutureSocsci->ChangeLabel(2,-1.,0.);\n  xaxistimeOrientFutureSocsci->ChangeLabel(4,-1.,0.);\n  xaxistimeOrientFutureSocsci->ChangeLabel(6,-1.,0.);\n  timeOrientFutureSocsci->SetMaximum(partimeOrientFutureSocsci + 5.*timeOrientFuturecFrFsocsci->GetMeanError());\n  timeOrientFutureSocsci->SetMinimum(TMath::Max(partimeOrientFutureSocsci - 5.*timeOrientFuturecFrFsocsci->GetMeanError(),0.));\n\n  timeOrientFutureSocsci->Draw(\"A*\");\n  TBox* boxtimeOrientFutureSocsci = new TBox(0.6,partimeOrientFutureSocsci-errtimeOrientFutureSocsci,4.4,partimeOrientFutureSocsci+errtimeOrientFutureSocsci);\n  boxtimeOrientFutureSocsci->SetFillColor(kBlue);\n  boxtimeOrientFutureSocsci->SetFillStyle(3004);\n  boxtimeOrientFutureSocsci->Draw();\n\n  timeOrientFutureSocsci->Write();\n  if (useBoth){\n    c8->SaveAs(\"pdfPlotsLIWCBoth/socsciFuture.pdf\");\n  }else{ c8->SaveAs(\"pdfPlotsLIWCBoth/socsciFuture.pdf\");}\n  \n\n  // 5th category work\n\n\n\n    \n  TCanvas* c9 = new TCanvas();\n  TF1* fitwork = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitwork->SetParNames(\"average\");\n\n  Float_t x9[4] = {1.,2.,3.,4.};\n  Float_t y9[4] = {\n    static_cast<Float_t>(workcMrMphysics->GetMean()),\n    static_cast<Float_t>(workcFrMphysics->GetMean()),\n    static_cast<Float_t>(workcMrFphysics->GetMean()),\n    static_cast<Float_t>(workcFrFphysics->GetMean())\n  };\n  Float_t ex9[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey9[4] = {\n    static_cast<Float_t>(workcMrMphysics->GetMeanError()),\n    static_cast<Float_t>(workcFrMphysics->GetMeanError()),\n    static_cast<Float_t>(workcMrFphysics->GetMeanError()),\n    static_cast<Float_t>(workcFrFphysics->GetMeanError())\n  };\n \n  TGraphErrors* workPhysics = new TGraphErrors(4,x9,y9,ex9,ey9);\n\n\n  workPhysics->SetMaximum(15.);\n  workPhysics->SetMinimum(5.);\n\n  workPhysics->SetTitle(\"Physics LIWC work\");\n  TFitResultPtr fitworkPhysics = workPhysics->Fit(\"fits\",\"S\");\n  Double_t   parworkPhysics = fitworkPhysics->Value(0);\n  Double_t  errworkPhysics = fitworkPhysics->ParError(0);\n  TAxis* xaxisworkPhysics= workPhysics->GetXaxis();\n  xaxisworkPhysics->SetTickLength(0.);\n  xaxisworkPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxisworkPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxisworkPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxisworkPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxisworkPhysics->ChangeLabel(2,-1.,0.);\n  xaxisworkPhysics->ChangeLabel(4,-1.,0.);\n  xaxisworkPhysics->ChangeLabel(6,-1.,0.);\n  workPhysics->SetMaximum(parworkPhysics + 5.*workcFrFphysics->GetMeanError());\n  workPhysics->SetMinimum(TMath::Max(parworkPhysics - 5.*workcFrFphysics->GetMeanError(),0.));\n\n  workPhysics->Draw(\"A*\");\n  TBox* boxworkPhysics = new TBox(0.6,parworkPhysics-errworkPhysics,4.4,parworkPhysics+errworkPhysics);\n  boxworkPhysics->SetFillColor(kBlue);\n  boxworkPhysics->SetFillStyle(3004);\n  boxworkPhysics->Draw();\n\n  workPhysics->Write();\n  if (useBoth){\n    c9->SaveAs(\"pdfPlotsLIWCBoth/physicsWork.pdf\");\n  }else { c9->SaveAs(\"pdfPlotsLIWC/physicsWork.pdf\");}\n  //\n  TCanvas* c10 = new TCanvas();\n  TF1* fitworkSocSci = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitworkSocSci->SetParNames(\"average\");\n\n  Float_t x10[4] = {1.,2.,3.,4.};\n  Float_t y10[4] = {\n    static_cast<Float_t>(workcMrMsocsci->GetMean()),\n    static_cast<Float_t>(workcFrMsocsci->GetMean()),\n    static_cast<Float_t>(workcMrFsocsci->GetMean()),\n    static_cast<Float_t>(workcFrFsocsci->GetMean())\n  };\n  Float_t ex10[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey10[4] = {\n    static_cast<Float_t>(workcMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(workcFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(workcMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(workcFrFsocsci->GetMeanError())\n  };\n \n  TGraphErrors* workSocsci = new TGraphErrors(4,x10,y10,ex10,ey10);\n\n\n  workSocsci->SetMaximum(15.);\n  workSocsci->SetMinimum(5.);\n\n  workSocsci->SetTitle(\"SocSci LIWC work\");\n  TFitResultPtr fitworkSocsci = workSocsci->Fit(\"fits\",\"S\");\n  Double_t   parworkSocsci = fitworkSocsci->Value(0);\n  Double_t  errworkSocsci = fitworkSocsci->ParError(0);\n  TAxis* xaxisworkSocsci= workSocsci->GetXaxis();\n  xaxisworkSocsci->SetTickLength(0.);\n  xaxisworkSocsci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxisworkSocsci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxisworkSocsci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxisworkSocsci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxisworkSocsci->ChangeLabel(2,-1.,0.);\n  xaxisworkSocsci->ChangeLabel(4,-1.,0.);\n  xaxisworkSocsci->ChangeLabel(6,-1.,0.);\n  workSocsci->SetMaximum(parworkSocsci + 5.*workcFrFsocsci->GetMeanError());\n  workSocsci->SetMinimum(TMath::Max(parworkSocsci - 5.*workcFrFsocsci->GetMeanError(),0.));\n\n  workSocsci->Draw(\"A*\");\n  TBox* boxworkSocsci = new TBox(0.6,parworkSocsci-errworkSocsci,4.4,parworkSocsci+errworkSocsci);\n  boxworkSocsci->SetFillColor(kBlue);\n  boxworkSocsci->SetFillStyle(3004);\n  boxworkSocsci->Draw();\n\n  if (useBoth){\n    c10->SaveAs(\"pdfPlotsLIWCBoth/socsciWork.pdf\");\n  } else { c10->SaveAs(\"pdfPlotsLIWC/socsciWork.pdf\");}\n    \n  //6th category analytic\n\n\n\n\n    \n  TCanvas* c11 = new TCanvas();\n  TF1* fitanalytic = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitanalytic->SetParNames(\"average\");\n\n  Float_t x11[4] = {1.,2.,3.,4.};\n  Float_t y11[4] = {\n    static_cast<Float_t>(analyticcMrMphysics->GetMean()),\n    static_cast<Float_t>(analyticcFrMphysics->GetMean()),\n    static_cast<Float_t>(analyticcMrFphysics->GetMean()),\n    static_cast<Float_t>(analyticcFrFphysics->GetMean())\n  };\n  Float_t ex11[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey11[4] = {\n    static_cast<Float_t>(analyticcMrMphysics->GetMeanError()),\n    static_cast<Float_t>(analyticcFrMphysics->GetMeanError()),\n    static_cast<Float_t>(analyticcMrFphysics->GetMeanError()),\n    static_cast<Float_t>(analyticcFrFphysics->GetMeanError())\n  };\n \n  TGraphErrors* analyticPhysics = new TGraphErrors(4,x11,y11,ex11,ey11);\n\n\n  analyticPhysics->SetMaximum(100.);\n  analyticPhysics->SetMinimum(70.);\n\n  analyticPhysics->SetTitle(\"Physics LIWC analytic\");\n  TFitResultPtr fitanalyticPhysics = analyticPhysics->Fit(\"fits\",\"S\");\n  Double_t   paranalyticPhysics = fitanalyticPhysics->Value(0);\n  Double_t  erranalyticPhysics = fitanalyticPhysics->ParError(0);\n  TAxis* xaxisanalyticPhysics= analyticPhysics->GetXaxis();\n  xaxisanalyticPhysics->SetTickLength(0.);\n  xaxisanalyticPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxisanalyticPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxisanalyticPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxisanalyticPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxisanalyticPhysics->ChangeLabel(2,-1.,0.);\n  xaxisanalyticPhysics->ChangeLabel(4,-1.,0.);\n  xaxisanalyticPhysics->ChangeLabel(6,-1.,0.);\n  analyticPhysics->Draw(\"A*\");\n  analyticPhysics->SetMaximum(paranalyticPhysics + 5.*analyticcFrFphysics->GetMeanError());\n  analyticPhysics->SetMinimum(TMath::Max(paranalyticPhysics - 5.*analyticcFrFphysics->GetMeanError(),0.));\n\n  TBox* boxanalyticPhysics = new TBox(0.6,paranalyticPhysics-erranalyticPhysics,4.4,paranalyticPhysics+erranalyticPhysics);\n  boxanalyticPhysics->SetFillColor(kBlue);\n  boxanalyticPhysics->SetFillStyle(3004);\n  boxanalyticPhysics->Draw();\n  if (useBoth){\n    c11->SaveAs(\"pdfPlotsLIWCBoth/analyticPhysics.pdf\");\n  } else { c11->SaveAs(\"pdfPlotsLIWC/analyticPhysics.pdf\");}\n\n  analyticPhysics->Write();\n\n  //\n  TCanvas* c12 = new TCanvas();\n  TF1* fitanalyticSocSci = new TF1(\"fits\",\"[0]\",0.,12.);\n  fitanalyticSocSci->SetParNames(\"average\");\n\n  Float_t x12[4] = {1.,2.,3.,4.};\n  Float_t y12[4] = {\n    static_cast<Float_t>(analyticcMrMsocsci->GetMean()),\n    static_cast<Float_t>(analyticcFrMsocsci->GetMean()),\n    static_cast<Float_t>(analyticcMrFsocsci->GetMean()),\n    static_cast<Float_t>(analyticcFrFsocsci->GetMean())\n  };\n  Float_t ex12[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey12[4] = {\n    static_cast<Float_t>(analyticcMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(analyticcFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(analyticcMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(analyticcFrFsocsci->GetMeanError())\n  };\n \n  TGraphErrors* analyticSocsci = new TGraphErrors(4,x12,y12,ex12,ey12);\n\n\n  analyticSocsci->SetMaximum(100.);\n  analyticSocsci->SetMinimum(70.);\n\n  analyticSocsci->SetTitle(\"SocSci LIWC analytic\");\n  TFitResultPtr fitanalyticSocsci = analyticSocsci->Fit(\"fits\",\"S\");\n  Double_t   paranalyticSocsci = fitanalyticSocsci->Value(0);\n  Double_t  erranalyticSocsci = fitanalyticSocsci->ParError(0);\n  TAxis* xaxisanalyticSocsci= analyticSocsci->GetXaxis();\n  xaxisanalyticSocsci->SetTickLength(0.);\n  xaxisanalyticSocsci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxisanalyticSocsci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxisanalyticSocsci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxisanalyticSocsci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxisanalyticSocsci->ChangeLabel(2,-1.,0.);\n  xaxisanalyticSocsci->ChangeLabel(4,-1.,0.);\n  xaxisanalyticSocsci->ChangeLabel(6,-1.,0.);\n  analyticSocsci->SetMaximum(paranalyticSocsci + 5.*analyticcFrFsocsci->GetMeanError());\n  analyticSocsci->SetMinimum(TMath::Max(paranalyticSocsci - 5.*analyticcFrFsocsci->GetMeanError(),0.));\n\n  analyticSocsci->Draw(\"A*\");\n  TBox* boxanalyticSocsci = new TBox(0.6,paranalyticSocsci-erranalyticSocsci,4.4,paranalyticSocsci+erranalyticSocsci);\n  boxanalyticSocsci->SetFillColor(kBlue);\n  boxanalyticSocsci->SetFillStyle(3004);\n  boxanalyticSocsci->Draw();\n  if (useBoth){\n    c12->SaveAs(\"pdfPlotsLIWCBoth/analyticSocsci.pdf\");\n  } else { c12->SaveAs(\"pdfPlotsLIWC/analyticSocsci.pdf\");}\n\n  analyticSocsci->Write();\n\n  //  7th category clout\n\n \n\n\n\n\n    \n  TCanvas* c13 = new TCanvas();\n  TF1* fitclout = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitclout->SetParNames(\"average\");\n\n  Float_t x13[4] = {1.,2.,3.,4.};\n  Float_t y13[4] = {\n    static_cast<Float_t>(cloutcMrMphysics->GetMean()),\n    static_cast<Float_t>(cloutcFrMphysics->GetMean()),\n    static_cast<Float_t>(cloutcMrFphysics->GetMean()),\n    static_cast<Float_t>(cloutcFrFphysics->GetMean())\n  };\n  Float_t ex13[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey13[4] = {\n    static_cast<Float_t>(cloutcMrMphysics->GetMeanError()),\n    static_cast<Float_t>(cloutcFrMphysics->GetMeanError()),\n    static_cast<Float_t>(cloutcMrFphysics->GetMeanError()),\n    static_cast<Float_t>(cloutcFrFphysics->GetMeanError())\n  };\n \n  TGraphErrors* cloutPhysics = new TGraphErrors(4,x13,y13,ex13,ey13);\n\n\n  cloutPhysics->SetMaximum(80.);\n  cloutPhysics->SetMinimum(50.);\n\n  cloutPhysics->SetTitle(\"Physics LIWC clout\");\n  TFitResultPtr fitcloutPhysics = cloutPhysics->Fit(\"fits\",\"S\");\n  Double_t   parcloutPhysics = fitcloutPhysics->Value(0);\n  Double_t  errcloutPhysics = fitcloutPhysics->ParError(0);\n  TAxis* xaxiscloutPhysics= cloutPhysics->GetXaxis();\n  xaxiscloutPhysics->SetTickLength(0.);\n  xaxiscloutPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxiscloutPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxiscloutPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxiscloutPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxiscloutPhysics->ChangeLabel(2,-1.,0.);\n  xaxiscloutPhysics->ChangeLabel(4,-1.,0.);\n  xaxiscloutPhysics->ChangeLabel(6,-1.,0.);\n  cloutPhysics->SetMaximum(parcloutPhysics + 5.*cloutcFrFphysics->GetMeanError());\n  cloutPhysics->SetMinimum(TMath::Max(parcloutPhysics - 5.*cloutcFrFphysics->GetMeanError(),0.));\n\n  cloutPhysics->Draw(\"A*\");\n  TBox* boxcloutPhysics = new TBox(0.6,parcloutPhysics-errcloutPhysics,4.4,parcloutPhysics+errcloutPhysics);\n  boxcloutPhysics->SetFillColor(kBlue);\n  boxcloutPhysics->SetFillStyle(3004);\n  boxcloutPhysics->Draw();\n  if (useBoth){\n    c13->SaveAs(\"pdfPlotsLIWCBoth/cloutPhysics.pdf\");\n  } else { c13->SaveAs(\"pdfPlotsLIWC/cloutPhysics.pdf\");}\n\n  cloutPhysics->Write();\n\n  //\n  TCanvas* c14 = new TCanvas();\n  TF1* fitcloutSocSci = new TF1(\"fits\",\"[0]\",0.,14.);\n  fitcloutSocSci->SetParNames(\"average\");\n\n  Float_t x14[4] = {1.,2.,3.,4.};\n  Float_t y14[4] = {\n    static_cast<Float_t>(cloutcMrMsocsci->GetMean()),\n    static_cast<Float_t>(cloutcFrMsocsci->GetMean()),\n    static_cast<Float_t>(cloutcMrFsocsci->GetMean()),\n    static_cast<Float_t>(cloutcFrFsocsci->GetMean())\n  };\n  Float_t ex14[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey14[4] = {\n    static_cast<Float_t>(cloutcMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(cloutcFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(cloutcMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(cloutcFrFsocsci->GetMeanError())\n  };\n \n  TGraphErrors* cloutSocsci = new TGraphErrors(4,x14,y14,ex14,ey14);\n\n\n  cloutSocsci->SetMaximum(80.);\n  cloutSocsci->SetMinimum(50.);\n\n  cloutSocsci->SetTitle(\"SocSci LIWC clout\");\n  TFitResultPtr fitcloutSocsci = cloutSocsci->Fit(\"fits\",\"S\");\n  Double_t   parcloutSocsci = fitcloutSocsci->Value(0);\n  Double_t  errcloutSocsci = fitcloutSocsci->ParError(0);\n  TAxis* xaxiscloutSocsci= cloutSocsci->GetXaxis();\n  xaxiscloutSocsci->SetTickLength(0.);\n  xaxiscloutSocsci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxiscloutSocsci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxiscloutSocsci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxiscloutSocsci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxiscloutSocsci->ChangeLabel(2,-1.,0.);\n  xaxiscloutSocsci->ChangeLabel(4,-1.,0.);\n  xaxiscloutSocsci->ChangeLabel(6,-1.,0.);\n  cloutSocsci->SetMaximum(parcloutSocsci + 20.*cloutcFrFsocsci->GetMeanError());\n  cloutSocsci->SetMinimum(TMath::Max(parcloutSocsci - 20.*cloutcFrFsocsci->GetMeanError(),0.));\n\n  cloutSocsci->Draw(\"A*\");\n  TBox* boxcloutSocsci = new TBox(0.6,parcloutSocsci-errcloutSocsci,4.4,parcloutSocsci+errcloutSocsci);\n  boxcloutSocsci->SetFillColor(kBlue);\n  boxcloutSocsci->SetFillStyle(3004);\n  boxcloutSocsci->Draw();\n  if (useBoth){\n    c14->SaveAs(\"pdfPlotsLIWCBoth/cloutSocsci.pdf\");\n  } else { c14->SaveAs(\"pdfPlotsLIWC/cloutSocsci.pdf\");}\n\n  cloutSocsci->Write();\n\n\n  //home category\n  \n \n\n\n    \n  TCanvas* c15 = new TCanvas();\n  TF1* fithome = new TF1(\"fits\",\"[0]\",0.,10.);\n  fithome->SetParNames(\"average\");\n\n  Float_t x15[4] = {1.,2.,3.,4.};\n  Float_t y15[4] = {\n    static_cast<Float_t>(homecMrMphysics->GetMean()),\n    static_cast<Float_t>(homecFrMphysics->GetMean()),\n    static_cast<Float_t>(homecMrFphysics->GetMean()),\n    static_cast<Float_t>(homecFrFphysics->GetMean())\n  };\n  Float_t ex15[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey15[4] = {\n    static_cast<Float_t>(homecMrMphysics->GetMeanError()),\n    static_cast<Float_t>(homecFrMphysics->GetMeanError()),\n    static_cast<Float_t>(homecMrFphysics->GetMeanError()),\n    static_cast<Float_t>(homecFrFphysics->GetMeanError())\n  };\n \n  TGraphErrors* homePhysics = new TGraphErrors(4,x15,y15,ex15,ey15);\n\n\n  homePhysics->SetMaximum(0.5);\n  homePhysics->SetMinimum(0.);\n\n  homePhysics->SetTitle(\"Physics LIWC home\");\n  TFitResultPtr fithomePhysics = homePhysics->Fit(\"fits\",\"S\");\n  Double_t   parhomePhysics = fithomePhysics->Value(0);\n  Double_t  errhomePhysics = fithomePhysics->ParError(0);\n  TAxis* xaxishomePhysics= homePhysics->GetXaxis();\n  xaxishomePhysics->SetTickLength(0.);\n  xaxishomePhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxishomePhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxishomePhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxishomePhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxishomePhysics->ChangeLabel(2,-1.,0.);\n  xaxishomePhysics->ChangeLabel(4,-1.,0.);\n  xaxishomePhysics->ChangeLabel(6,-1.,0.);\n  homePhysics->SetMaximum(parhomePhysics + 5.*homecFrFphysics->GetMeanError());\n  homePhysics->SetMinimum(TMath::Max(parhomePhysics - 5.*homecFrFphysics->GetMeanError(),0.));\n\n  homePhysics->Draw(\"A*\");\n  TBox* boxhomePhysics = new TBox(0.6,parhomePhysics-errhomePhysics,4.4,parhomePhysics+errhomePhysics);\n  boxhomePhysics->SetFillColor(kBlue);\n  boxhomePhysics->SetFillStyle(3004);\n  boxhomePhysics->Draw();\n  if (useBoth){\n    c15->SaveAs(\"pdfPlotsLIWCBoth/homePhysics.pdf\");\n  } else { c15->SaveAs(\"pdfPlotsLIWC/homePhysics.pdf\");}\n\n  homePhysics->Write();\n\n  //\n  TCanvas* c16 = new TCanvas();\n  TF1* fithomeSocSci = new TF1(\"fits\",\"[0]\",0.,10.);\n  fithomeSocSci->SetParNames(\"average\");\n\n  Float_t x16[4] = {1.,2.,3.,4.};\n  Float_t y16[4] = {\n    static_cast<Float_t>(homecMrMsocsci->GetMean()),\n    static_cast<Float_t>(homecFrMsocsci->GetMean()),\n    static_cast<Float_t>(homecMrFsocsci->GetMean()),\n    static_cast<Float_t>(homecFrFsocsci->GetMean())\n  };\n  Float_t ex16[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey16[4] = {\n    static_cast<Float_t>(homecMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(homecFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(homecMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(homecFrFsocsci->GetMeanError())\n  };\n \n  TGraphErrors* homeSocsci = new TGraphErrors(4,x16,y16,ex16,ey16);\n\n\n  homeSocsci->SetMaximum(0.5);\n  homeSocsci->SetMinimum(0.);\n\n  homeSocsci->SetTitle(\"SocSci LIWC home\");\n  TFitResultPtr fithomeSocsci = homeSocsci->Fit(\"fits\",\"S\");\n  Double_t   parhomeSocsci = fithomeSocsci->Value(0);\n  Double_t  errhomeSocsci = fithomeSocsci->ParError(0);\n  TAxis* xaxishomeSocsci= homeSocsci->GetXaxis();\n  xaxishomeSocsci->SetTickLength(0.);\n  xaxishomeSocsci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxishomeSocsci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxishomeSocsci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxishomeSocsci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxishomeSocsci->ChangeLabel(2,-1.,0.);\n  xaxishomeSocsci->ChangeLabel(4,-1.,0.);\n  xaxishomeSocsci->ChangeLabel(6,-1.,0.);\n  homeSocsci->SetMaximum(parhomeSocsci + 5.*homecFrFsocsci->GetMeanError());\n  homeSocsci->SetMinimum(TMath::Max(parhomeSocsci - 5.*homecFrFsocsci->GetMeanError(),0.));\n\n  homeSocsci->Draw(\"A*\");\n  TBox* boxhomeSocsci = new TBox(0.6,parhomeSocsci-errhomeSocsci,4.4,parhomeSocsci+errhomeSocsci);\n  boxhomeSocsci->SetFillColor(kBlue);\n  boxhomeSocsci->SetFillStyle(3004);\n  boxhomeSocsci->Draw();\n  if (useBoth){\n    c16->SaveAs(\"pdfPlotsLIWCBoth/homeSocsci.pdf\");\n  } else { c16->SaveAs(\"pdfPlotsLIWC/homeSocsci.pdf\");}\n\n\n\n  \n  TCanvas* c19 = new TCanvas();\n  c19->Divide(2);\n  c19->cd(2);\n\n    Float_t xPosemoPhysics[4] = {1.,2.,3.,4.};\n  Float_t yPosemoPhysics[4] = {\n    static_cast<Float_t>(PosemocMrMphysics->GetMean()),\n    static_cast<Float_t>(PosemocFrMphysics->GetMean()),\n    static_cast<Float_t>(PosemocMrFphysics->GetMean()),\n    static_cast<Float_t>(PosemocFrFphysics->GetMean())\n  };\n  Float_t exPosemoPhysics[4] = {0.1,0.1,0.1,0.1};\n  Float_t eyPosemoPhysics[4] = {\n    static_cast<Float_t>(PosemocMrMphysics->GetMeanError()),\n    static_cast<Float_t>(PosemocFrMphysics->GetMeanError()),\n    static_cast<Float_t>(PosemocMrFphysics->GetMeanError()),\n    static_cast<Float_t>(PosemocFrFphysics->GetMeanError())\n  };\n\n  TGraphErrors* posemoPhysics = new TGraphErrors(4,xPosemoPhysics,yPosemoPhysics,exPosemoPhysics,eyPosemoPhysics);\n  posemoPhysics->SetMaximum(1.7);\n  posemoPhysics->SetMinimum(0.7);\n  posemoPhysics->SetTitle(\"EPP Posemo\");\n  TFitResultPtr fitPosemoPhysics = posemoPhysics->Fit(\"fits\",\"S\");\n  double par0 = fitPosemoPhysics->Value(0);\n  double err0 = fitPosemoPhysics->ParError(0);\n  TAxis* yAxisPosemoPhysics = posemoPhysics->GetYaxis();\n  yAxisPosemoPhysics->SetTitle(\"% of Words\");\n  yAxisPosemoPhysics->SetTickLength(0.);\n \n  TAxis* xaxisPosemoPhysics = posemoPhysics->GetXaxis();\n   xaxisPosemoPhysics->SetTickLength(0.);\n   xaxisPosemoPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisPosemoPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisPosemoPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisPosemoPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisPosemoPhysics->ChangeLabel(2,-1.,0.);\n  xaxisPosemoPhysics->ChangeLabel(4,-1.,0.);\n  xaxisPosemoPhysics->ChangeLabel(6,-1.,0.);\n  xaxisPosemoPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisPosemoPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisPosemoPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisPosemoPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisPosemoPhysics->ChangeLabel(2,-1.,0.);\n  xaxisPosemoPhysics->ChangeLabel(4,-1.,0.);\n  xaxisPosemoPhysics->ChangeLabel(6,-1.,0.);\n  posemoPhysics->SetFillColor(38);\n  posemoPhysics->SetMaximum(par0 + 5.*PosemocFrFphysics->GetMeanError());\n  posemoPhysics->SetMinimum(TMath::Max(par0 - 5.*PosemocFrFphysics->GetMeanError(),0.));\n\n  posemoPhysics->Draw(\"AB\");\n  TBox* boxPosemoPhysics = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxPosemoPhysics->SetFillColor(kBlue);\n  boxPosemoPhysics->SetFillStyle(3004);\n  boxPosemoPhysics->Draw();\n\n  posemoPhysics->Write();\n  if (useBoth)\n    {c19->SaveAs(\"pdfPlotsBoth/physicsPosemo.pdf\");}\n  else{c19->SaveAs(\"pdfPlots/physicsPosemo.pdf\");}\n\n  c19->cd(1);\n\n  //  analysisOut <<    static_cast<Float_t>(posemoSocScicMrM->GetMean()) << \" \" << \n  //static_cast<Float_t>(posemoSocScicFrM->GetMean()) << \" \" << \n  //static_cast<Float_t>(posemoSocScicFrF->GetMean()) << \" \" <<\n  //static_cast<Float_t>(posemoSocScicMrF->GetMean()) << \" \" << std::endl;\n\t\t\t\t\t\t\t\t\t  \n \n  Float_t xPosemoSocSci[4] = {1.,2.,3.,4.};\n  Float_t yPosemoSocSci[4] = {\n    static_cast<Float_t>(PosemocMrMsocsci->GetMean()),\n    static_cast<Float_t>(PosemocFrMsocsci->GetMean()),\n    static_cast<Float_t>(PosemocMrFsocsci->GetMean()),\n    static_cast<Float_t>(PosemocFrFsocsci->GetMean())\n  };\n  Float_t exPosemoSocSci[4] = {0.1,0.1,0.1,0.1};\n  Float_t eyPosemoSocSci[4] = {\n    static_cast<Float_t>(PosemocMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(PosemocFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(PosemocMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(PosemocFrFsocsci->GetMeanError())\n  };\n\n  TGraphErrors* posemoSocSci = new TGraphErrors(4,xPosemoSocSci,yPosemoSocSci,exPosemoSocSci,eyPosemoSocSci);\n  posemoSocSci->SetTitle(\"Social Science Posemo\");\n  TFitResultPtr fit4 = posemoSocSci->Fit(\"fits\",\"S\");\n  par0 = fit4->Value(0);\n  err0 = fit4->ParError(0);\n   TAxis* yAxisPosemoSocSci = posemoSocSci->GetYaxis();\n   yAxisPosemoSocSci->SetTitle(\"% of Words\");\n  yAxisPosemoSocSci->SetTickLength(0.);\n\n  TAxis* xaxisPosemoSocSci = posemoSocSci->GetXaxis();\n   xaxisPosemoSocSci->SetTickLength(0.);\n   xaxisPosemoSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisPosemoSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisPosemoSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisPosemoSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisPosemoSocSci->ChangeLabel(2,-1.,0.);\n  xaxisPosemoSocSci->ChangeLabel(4,-1.,0.);\n  xaxisPosemoSocSci->ChangeLabel(6,-1.,0.);\n  xaxisPosemoSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisPosemoSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisPosemoSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisPosemoSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisPosemoSocSci->ChangeLabel(2,-1.,0.);\n  xaxisPosemoSocSci->ChangeLabel(4,-1.,0.);\n  xaxisPosemoSocSci->ChangeLabel(6,-1.,0.);\n  posemoSocSci->SetFillColor(38);\n\n\n  posemoSocSci->SetMaximum(par0 + 5.*PosemocFrFsocsci->GetMeanError());\n  posemoSocSci->SetMinimum(TMath::Max(par0 - 5.*PosemocFrFsocsci->GetMeanError(),0.));\n\n  posemoSocSci->Draw(\"AB\");\n  TBox* boxPosemoSocSci = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxPosemoSocSci->SetFillColor(kBlue);\n  boxPosemoSocSci->SetFillStyle(3004);\n  boxPosemoSocSci->Draw();\n\n  posemoSocSci->Write();\n  if (useBoth){\n    c19->SaveAs(\"pdfPlotsBoth/SocSciPosemo.pdf\");\n  }else {c19->SaveAs(\"pdfPlots/SocSciPosemo.pdf\");}\n\n\n    TCanvas* c20 = new TCanvas();\n   c20->Divide(2);\n  c20->cd(2);\n\n    Float_t xNegemoPhysics[4] = {1.,2.,3.,4.};\n  Float_t yNegemoPhysics[4] = {\n    static_cast<Float_t>(NegemocMrMphysics->GetMean()),\n    static_cast<Float_t>(NegemocFrMphysics->GetMean()),\n    static_cast<Float_t>(NegemocMrFphysics->GetMean()),\n    static_cast<Float_t>(NegemocFrFphysics->GetMean())\n  };\n  Float_t exNegemoPhysics[4] = {0.1,0.1,0.1,0.1};\n  Float_t eyNegemoPhysics[4] = {\n    static_cast<Float_t>(NegemocMrMphysics->GetMeanError()),\n    static_cast<Float_t>(NegemocFrMphysics->GetMeanError()),\n    static_cast<Float_t>(NegemocMrFphysics->GetMeanError()),\n    static_cast<Float_t>(NegemocFrFphysics->GetMeanError())\n  };\n\n  TGraphErrors* negemoPhysics = new TGraphErrors(4,xNegemoPhysics,yNegemoPhysics,exNegemoPhysics,eyNegemoPhysics);\n  negemoPhysics->SetTitle(\"EPP Negemo\");\n  TFitResultPtr fitNegemoPhysics = negemoPhysics->Fit(\"fits\",\"S\");\n  par0 = fitNegemoPhysics->Value(0);\n  err0 = fitNegemoPhysics->ParError(0);\n    TAxis* yAxisNegemoPhysics = negemoPhysics->GetYaxis();\n  yAxisNegemoPhysics->SetTitle(\"% of Words\");\n  yAxisNegemoPhysics->SetTickLength(0.);\n\n  TAxis* xaxisNegemoPhysics = negemoPhysics->GetXaxis();\n  xaxisNegemoPhysics->SetTickLength(0.);\n   xaxisNegemoPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisNegemoPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisNegemoPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisNegemoPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisNegemoPhysics->ChangeLabel(2,-1.,0.);\n  xaxisNegemoPhysics->ChangeLabel(4,-1.,0.);\n  xaxisNegemoPhysics->ChangeLabel(6,-1.,0.);\n  xaxisNegemoPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisNegemoPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisNegemoPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisNegemoPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisNegemoPhysics->ChangeLabel(2,-1.,0.);\n  xaxisNegemoPhysics->ChangeLabel(4,-1.,0.);\n  xaxisNegemoPhysics->ChangeLabel(6,-1.,0.);\n  negemoPhysics->SetFillColor(38);\n\n  negemoPhysics->SetMaximum(par0 + 5.*NegemocFrFphysics->GetMeanError());\n  negemoPhysics->SetMinimum(TMath::Max(par0 - 5.*NegemocFrFphysics->GetMeanError(),0.));\n\n  negemoPhysics->Draw(\"AB\");\n  TBox* boxNegemoPhysics = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxNegemoPhysics->SetFillColor(kBlue);\n  boxNegemoPhysics->SetFillStyle(3004);\n  boxNegemoPhysics->Draw();\n\n  negemoPhysics->Write();\n  if (useBoth)\n    {c19->SaveAs(\"pdfPlotsBoth/physicsNegemo.pdf\");}\n  else{c19->SaveAs(\"pdfPlots/physicsNegemo.pdf\");}\n  \n     // TCanvas* c4 = new TCanvas();\n  c20->cd(1);\n\n  //  analysisOut <<    static_cast<Float_t>(negemoSocScicMrM->GetMean()) << \" \" << \n  // static_cast<Float_t>(negemoSocScicFrM->GetMean()) << \" \" << \n  // static_cast<Float_t>(negemoSocScicFrF->GetMean()) << \" \" <<\n  // static_cast<Float_t>(negemoSocScicMrF->GetMean()) << \" \" << std::endl;\n \n  Float_t xNegemoSocsci[4] = {1.,2.,3.,4.};\n  Float_t yNegemoSocsci[4] = {\n    static_cast<Float_t>(NegemocMrMsocsci->GetMean()),\n    static_cast<Float_t>(NegemocFrMsocsci->GetMean()),\n    static_cast<Float_t>(NegemocMrFsocsci->GetMean()),\n    static_cast<Float_t>(NegemocFrFsocsci->GetMean())\n  };\n  Float_t exNegemoSocsci[4] = {0.1,0.1,0.1,0.1};\n  Float_t eyNegemoSocsci[4] = {\n    static_cast<Float_t>(NegemocMrMsocsci->GetMeanError()),\n    static_cast<Float_t>(NegemocFrMsocsci->GetMeanError()),\n    static_cast<Float_t>(NegemocMrFsocsci->GetMeanError()),\n    static_cast<Float_t>(NegemocFrFsocsci->GetMeanError())\n  };\n\n  TGraphErrors* negemoSocSci = new TGraphErrors(4,xNegemoSocsci,yNegemoSocsci,exNegemoSocsci,eyNegemoSocsci);\n  negemoSocSci->SetMaximum(2.0);\n  negemoSocSci->SetMinimum(1.0);\n  negemoSocSci->SetTitle(\"Social Science Negemo\");\n  TFitResultPtr fitNegemoSocSci = negemoSocSci->Fit(\"fits\",\"S\");\n  par0 = fitNegemoSocSci->Value(0);\n  err0 = fitNegemoSocSci->ParError(0);\n    TAxis* yAxisNegemoSocSci = negemoSocSci->GetYaxis();\n  yAxisNegemoSocSci->SetTitle(\"% of Words\");\n  yAxisNegemoSocSci->SetTickLength(0.);\n  TAxis* xaxisNegemoSocSci = negemoSocSci->GetXaxis();\n  xaxisNegemoSocSci->SetTickLength(0.);\n  xaxisNegemoSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisNegemoSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisNegemoSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisNegemoSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisNegemoSocSci->ChangeLabel(2,-1.,0.);\n  xaxisNegemoSocSci->ChangeLabel(4,-1.,0.);\n  xaxisNegemoSocSci->ChangeLabel(6,-1.,0.);\n  xaxisNegemoSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisNegemoSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisNegemoSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisNegemoSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisNegemoSocSci->ChangeLabel(2,-1.,0.);\n  xaxisNegemoSocSci->ChangeLabel(4,-1.,0.);\n  xaxisNegemoSocSci->ChangeLabel(6,-1.,0.);\n  negemoSocSci->SetFillColor(38);\n\n  negemoSocSci->SetMaximum(par0 + 5.*NegemocFrFsocsci->GetMeanError());\n  negemoSocSci->SetMinimum(TMath::Max(par0 - 5.*NegemocFrFsocsci->GetMeanError(),0.));\n\n  negemoSocSci->Draw(\"AB\");\n  TBox* boxNegemoSocSci = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxNegemoSocSci->SetFillColor(kBlue);\n  boxNegemoSocSci->SetFillStyle(3004);\n  boxNegemoSocSci->Draw();\n\n  negemoSocSci->Write();\n  if (useBoth){\n    c20->SaveAs(\"pdfPlotsBoth/SocSciNegemo.pdf\");\n  }else {c20->SaveAs(\"pdfPlots/SocSciNegemo.pdf\");}\n\n \n  f->Close();\n}\n\n\n", "meta": {"hexsha": "a683ab15e5a3cea8ff385d8b7b095591debc3d42", "size": 104621, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "annotated_LIWC_analysisForPaper.cxx", "max_stars_repo_name": "rhbob/genderDifferences", "max_stars_repo_head_hexsha": "4c464151cb2de42a9c649b5ad1e08648281cfe6b", "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": "annotated_LIWC_analysisForPaper.cxx", "max_issues_repo_name": "rhbob/genderDifferences", "max_issues_repo_head_hexsha": "4c464151cb2de42a9c649b5ad1e08648281cfe6b", "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": "annotated_LIWC_analysisForPaper.cxx", "max_forks_repo_name": "rhbob/genderDifferences", "max_forks_repo_head_hexsha": "4c464151cb2de42a9c649b5ad1e08648281cfe6b", "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": 37.0077821012, "max_line_length": 638, "alphanum_fraction": 0.6793855918, "num_tokens": 38636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3242354120407358, "lm_q1q2_score": 0.19460231996678573}}
{"text": "\n#include \"graph_map/graph_map_fuser.h\"\n#include <ros/ros.h>\n#include <rosbag/bag.h>\n#include <rosbag/view.h>\n\n#include <ndt_map/ndt_conversions.h>\n#include \"ndt_generic/utils.h\"\n#include <pcl_conversions/pcl_conversions.h>\n#include \"pcl/point_cloud.h\"\n#include <Eigen/Eigen>\n#include \"eigen_conversions/eigen_msg.h\"\n#include <tf_conversions/tf_eigen.h>\n\n\n#include \"sensor_msgs/PointCloud2.h\"\n#include \"pcl/io/pcd_io.h\"\n\n#include <fstream>\n#include \"message_filters/subscriber.h\"\n#include \"tf/message_filter.h\"\n#include <tf/transform_broadcaster.h>\n\n#include <boost/circular_buffer.hpp>\n#include <laser_geometry/laser_geometry.h>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/PoseStamped.h>\n\n#include <visualization_msgs/MarkerArray.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <std_srvs/Empty.h>\n\n#include <boost/foreach.hpp>\n#include <ndt_map/NDTMapMsg.h>\n\n#include \"graph_map/lidarUtils/lidar_utilities.h\"\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <time.h>\n#include <fstream>\n#include <cstdio>\n#include \"tf_conversions/tf_eigen.h\"\n#ifndef SYNC_FRAMES\n#define SYNC_FRAMES 20\n#define MAX_TRANSLATION_DELTA 2.0\n#define MAX_ROTATION_DELTA 0.5\n#endif\n/** \\brief A ROS node which implements an NDTFuser or NDTFuserHMT object\n * \\author Daniel adolfsson based on code from Todor Stoyanov\n *\n */\nusing namespace perception_oru;\nusing namespace libgraphMap;\n\ntypedef message_filters::sync_policies::ApproximateTime<sensor_msgs::LaserScan, nav_msgs::Odometry> LaserOdomSync;\ntypedef message_filters::sync_policies::ApproximateTime<sensor_msgs::LaserScan, geometry_msgs::PoseStamped> LaserPoseSync;\ntypedef message_filters::sync_policies::ApproximateTime<sensor_msgs::PointCloud2, nav_msgs::Odometry> PointsOdomSync;\ntypedef message_filters::sync_policies::ApproximateTime<sensor_msgs::PointCloud2, nav_msgs::Odometry> PointsGTOdomSync;\ntypedef message_filters::sync_policies::ApproximateTime<sensor_msgs::PointCloud2, geometry_msgs::PoseStamped> PointsPoseSync;\n\nclass GraphMapFuserNode {\n\nprotected:\n  // Our NodeHandle\n  ros::NodeHandle nh_;\n  GraphMapFuser *fuser_;\n  message_filters::Subscriber<sensor_msgs::PointCloud2> *points2_sub_;\n  message_filters::Subscriber<sensor_msgs::LaserScan> *laser_sub_;\n  message_filters::Subscriber<nav_msgs::Odometry> *odom_sub_;\n  plotmarker plot_marker;\n\n  message_filters::Subscriber<nav_msgs::Odometry> *gt_fuser_sub_;\n  ros::Subscriber gt_sub,points2OdomTfSub;\n\n  // Components for publishing\n  tf::TransformBroadcaster tf_;\n  tf::TransformListener tf_listener_;\n  ros::Publisher output_pub_;\n  Eigen::Affine3d pose_, T, sensorPose_;\n\n\n  unsigned int frame_nr_;\n  double varz;\n  tf::Transform tf_sensor_pose_;\n  std::string map_type_name,reg_type_name;\n  std::string map_name=\"graph_map\";\n  std::string points_topic, laser_topic, map_dir, odometry_topic,odometry_adjusted_topic;\n  std::string file_format_map=\".JFF\";\n  std::string world_link_id, odometry_link_id, fuser_base_link_id,laser_link_id, init_pose_frame, gt_topic, bag_name,state_base_link_id;\n  double size_x, size_y, size_z, resolution, sensor_range, min_laser_range_;\n  bool visualize, match2D, matchLaser, beHMT, useOdometry,\n  initPoseFromGT, initPoseFromTF, initPoseSet, gt_mapping;\n\n  double pose_init_x,pose_init_y,pose_init_z,\n  pose_init_r,pose_init_p,pose_init_t;\n  double sensor_pose_x,sensor_pose_y,sensor_pose_z,\n  sensor_pose_r,sensor_pose_p,sensor_pose_t;\n  double sensor_offset_t_;\n\n  laser_geometry::LaserProjection projector_;\n  message_filters::Synchronizer< LaserOdomSync > *sync_lo_;\n  message_filters::Synchronizer< LaserPoseSync > *sync_lp_;\n\n  message_filters::Synchronizer< PointsGTOdomSync > *sync_GTodom_;\n  message_filters::Synchronizer< PointsOdomSync > *sync_po_;\n  message_filters::Synchronizer< PointsPoseSync > *sync_pp_;\n  ros::ServiceServer save_map_;\n  ros::Time time_now,time_last_itr;\n  ros::Publisher map_publisher_,laser_publisher_,point2_publisher_,odom_publisher_,adjusted_odom_publisher_,fuser_odom_publisher_;\n  nav_msgs::Odometry fuser_odom,adjusted_odom_msg;\n  Eigen::Affine3d last_odom, this_odom,last_gt_pose;\n\n  bool use_tf_listener_;\n  Eigen::Affine3d last_tf_frame_;\n  perception_oru::MotionModel2d::Params motion_params;\n  boost::mutex m;\npublic:\n  // Constructor\n  GraphMapFuserNode(ros::NodeHandle param_nh) : frame_nr_(0)\n  {\n    ///if we want to build map reading scans directly from bagfile\n\n\n    ///topic to wait for point clouds, if available\n    param_nh.param<std::string>(\"points_topic\",points_topic,\"points\");\n    ///topic to wait for laser scan messages, if available\n    param_nh.param<std::string>(\"laser_topic\",laser_topic,\"laser_scan\");\n\n    ///only match 2ith 3dof\n    param_nh.param(\"match2D\",match2D,true);\n    ///enable for LaserScan message input\n    param_nh.param(\"matchLaser\",matchLaser,true);\n\n\n    param_nh.param<std::string>(\"registration_type\",reg_type_name,\"default_reg\");\n    ///range to cutoff sensor measurements\n    ///\n    param_nh.param(\"sensor_range\",sensor_range,3.);\n\n    ///visualize in a local window\n    param_nh.param(\"visualize\",visualize,true);\n\n    std::string marker_str;\n    param_nh.param<std::string>(\"plot_marker\",marker_str,\"sphere\");\n    if(marker_str.compare(\"sphere\")==0)\n      plot_marker=plotmarker::sphere;\n    else if(marker_str.compare(\"point\")==0)\n      plot_marker=plotmarker::point;\n    else\n      plot_marker=plotmarker::sphere;\n\n\n\n    ///range to cutoff sensor measurements\n    param_nh.param(\"min_laser_range\",min_laser_range_,0.1);\n\n\n    ///if using the HMT fuser, NDT maps are saved in this directory.\n    ///a word of warning: if you run multiple times with the same directory,\n    ///the old maps are loaded automatically\n    param_nh.param<std::string>(\"map_directory\",map_dir,\"/map/\");\n    param_nh.param<std::string>(\"map_type\",map_type_name,\"default_map\");\n    param_nh.param<std::string>(\"file_format_map\",file_format_map,\".JFF\");\n\n\n    ///initial pose of the vehicle with respect to the map\n    param_nh.param(\"pose_init_x\",pose_init_x,0.);\n    param_nh.param(\"pose_init_y\",pose_init_y,0.);\n    param_nh.param(\"pose_init_z\",pose_init_z,0.);\n    param_nh.param(\"pose_init_r\",pose_init_r,0.);\n    param_nh.param(\"pose_init_p\",pose_init_p,0.);\n    param_nh.param(\"pose_init_t\",pose_init_t,0.);\n\n    ///pose of the sensor with respect to the vehicle odometry frame\n    param_nh.param(\"sensor_pose_x\",sensor_pose_x,0.);\n    param_nh.param(\"sensor_pose_y\",sensor_pose_y,0.);\n    param_nh.param(\"sensor_pose_z\",sensor_pose_z,0.);\n    param_nh.param(\"sensor_pose_r\",sensor_pose_r,0.);\n    param_nh.param(\"sensor_pose_p\",sensor_pose_p,0.);\n    param_nh.param(\"sensor_pose_t\",sensor_pose_t,0.);\n    param_nh.param(\"sensor_offset_t\",sensor_offset_t_,0.);\n    ///size of the map in x/y/z. if using HMT, this is the size of the central tile\n    param_nh.param(\"size_x_meters\",size_x,10.);\n    param_nh.param(\"size_y_meters\",size_y,10.);\n    param_nh.param(\"size_z_meters\",size_z,10.);\n\n    param_nh.param<double>(\"motion_params_Cd\", motion_params.Cd, 0.005);\n    param_nh.param<double>(\"motion_params_Ct\", motion_params.Ct, 0.01);\n    param_nh.param<double>(\"motion_params_Dd\", motion_params.Dd, 0.001);\n    param_nh.param<double>(\"motion_params_Dt\", motion_params.Dt, 0.01);\n    param_nh.param<double>(\"motion_params_Td\", motion_params.Td, 0.001);\n    param_nh.param<double>(\"motion_params_Tt\", motion_params.Tt, 0.005);\n\n    bool do_soft_constraints;\n    param_nh.param<bool>(\"do_soft_constraints\", do_soft_constraints, false);\n    param_nh.param(\"laser_variance_z\",varz,resolution/4);\n\n    param_nh.param<std::string>(\"bagfile_name\",bag_name,\"data.bag\");\n    cout<<\"bagfile_name\"<<points_topic<<endl;\n\n\n    ///if we want to create map based on GT pose\n    param_nh.param(\"renderGTmap\",gt_mapping,false);\n    param_nh.param<std::string>(\"gt_topic\",gt_topic,\"groundtruth\");\n    ///if we want to get the initial pose of the vehicle relative to a different frame\n    param_nh.param(\"initPoseFromGT\",initPoseFromGT,false);\n    //plot the map from the GT track if available\n\n\n    ///topic to wait for laser scan messages, if available\n    param_nh.param<std::string>(\"odometry_topic\",odometry_topic,\"odometry\");\n\n    param_nh.param<std::string>(\"odometry_adjusted\",odometry_adjusted_topic,\"odometry_adjusted\");\n    //get it from TF?\n    param_nh.param(\"initPoseFromTF\",initPoseFromTF,false);\n\n    //the frame to initialize to\n\n    param_nh.param<std::string>(\"world_frame\",world_link_id,\"/world\");\n    //our frame\n    param_nh.param<std::string>(\"fuser_frame_id\",fuser_base_link_id,\"/fuser_base_link\");\n    param_nh.param<std::string>(\"laser_frame_id\",laser_link_id,\"/velodyne\");\n\n    param_nh.param<std::string>(\"state_base_link_id\",state_base_link_id,\"/state_base_link\");\n\n    ///use standard odometry messages for initialuess\n    param_nh.param(\"useOdometry\",useOdometry,true);\n\n    param_nh.param<bool>(\"use_tf_listener\", use_tf_listener_, false);\n    param_nh.param<std::string>(\"odometry_frame_id\", odometry_link_id, std::string(\"/odom_base_link\"));\n\n    initPoseSet = false;\n    param_nh.param<bool>(\"do_soft_constraints\", do_soft_constraints, false);\n    fuser_odom.header.frame_id=\"/world\";\n    adjusted_odom_msg.header.frame_id=\"/world\";\n    laser_publisher_ =param_nh.advertise<sensor_msgs::LaserScan>(\"laserscan_in_fuser_frame\",50);\n\n    point2_publisher_ =param_nh.advertise<sensor_msgs::PointCloud2>(\"point2_fuser\",15);\n    fuser_odom_publisher_=param_nh.advertise<nav_msgs::Odometry>(\"fuser\",50);\n    adjusted_odom_publisher_=param_nh.advertise<nav_msgs::Odometry>(\"odom_gt_init\",50);\n\n    if(gt_mapping)\n      use_tf_listener_= use_tf_listener_ && state_base_link_id != std::string(\"\");// check if odometry topic exists\n    else\n      use_tf_listener_= use_tf_listener_ && odometry_link_id != std::string(\"\");// check if odometry topic exists\n\n\n    sensorPose_ =  Eigen::Translation<double,3>(sensor_pose_x,sensor_pose_y,sensor_pose_z)*\n        Eigen::AngleAxis<double>(sensor_pose_r,Eigen::Vector3d::UnitX()) *\n        Eigen::AngleAxis<double>(sensor_pose_p,Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxis<double>(sensor_pose_t,Eigen::Vector3d::UnitZ()) ;\n\n    tf::poseEigenToTF(sensorPose_,tf_sensor_pose_);\n\n    if(!initPoseFromGT){\n      pose_ =  Eigen::Translation<double,3>(pose_init_x,pose_init_y,pose_init_z)*\n          Eigen::AngleAxis<double>(pose_init_r,Eigen::Vector3d::UnitX()) *\n          Eigen::AngleAxis<double>(pose_init_p,Eigen::Vector3d::UnitY()) *\n          Eigen::AngleAxis<double>(pose_init_t,Eigen::Vector3d::UnitZ()) ;\n      initPoseSet=true;\n\n      fuser_=new GraphMapFuser(map_type_name,reg_type_name,pose_,sensorPose_);\n      cout<<\"set fuser viz=\"<<visualize<<endl;\n      fuser_->Visualize(visualize);\n\n    }\n\n\n    cout<<\"node: initial pose =\\n\"<<pose_.translation()<<endl;\n\n\n    if(!matchLaser) {\n      points2_sub_ = new message_filters::Subscriber<sensor_msgs::PointCloud2>(nh_,points_topic,2);\n      if(useOdometry) {\n        if(gt_mapping){\n          if(!use_tf_listener_){\n            gt_fuser_sub_ = new message_filters::Subscriber<nav_msgs::Odometry>(nh_,gt_topic,10);\n            sync_GTodom_ = new message_filters::Synchronizer< PointsGTOdomSync >(PointsGTOdomSync(SYNC_FRAMES), *points2_sub_, *gt_fuser_sub_);\n            sync_GTodom_->registerCallback(boost::bind(&GraphMapFuserNode::GTLaserPointsOdomCallback, this, _1, _2));\n          }\n          else\n            points2OdomTfSub=nh_.subscribe <sensor_msgs::PointCloud2>(points_topic,10,&GraphMapFuserNode::GTLaserPointsOdomCallbackTF,this);\n\n        }\n        else{\n          if(!use_tf_listener_){\n            odom_sub_ = new message_filters::Subscriber<nav_msgs::Odometry>(nh_,odometry_topic,10);\n            sync_po_ = new message_filters::Synchronizer< PointsOdomSync >(PointsOdomSync(SYNC_FRAMES), *points2_sub_, *odom_sub_);\n            sync_po_->registerCallback(boost::bind(&GraphMapFuserNode::points2OdomCallback, this,_1, _2));\n          }\n          else\n            points2OdomTfSub=nh_.subscribe <sensor_msgs::PointCloud2>(points_topic,10,&GraphMapFuserNode::points2OdomCallbackTF,this);\n        }\n      }\n    }\n    else\n    {\n      laser_sub_ = new message_filters::Subscriber<sensor_msgs::LaserScan>(nh_,laser_topic,2);\n      if(useOdometry) {\n        odom_sub_ = new message_filters::Subscriber<nav_msgs::Odometry>(nh_,odometry_topic,10);\n        sync_lo_ = new message_filters::Synchronizer< LaserOdomSync >(LaserOdomSync(SYNC_FRAMES), *laser_sub_, *odom_sub_);\n        sync_lo_->registerCallback(boost::bind(&GraphMapFuserNode::laserOdomCallback, this, _1, _2));\n      }\n      else{\n        ((void)0); //Do nothing, seriously consider using a laser only callback (no odometry sync)\n      }\n    }\n    if(initPoseFromGT) {\n      gt_sub = nh_.subscribe<nav_msgs::Odometry>(gt_topic,10,&GraphMapFuserNode::gt_callback, this);\n    }\n    save_map_ = param_nh.advertiseService(\"save_map\", &GraphMapFuserNode::save_map_callback, this);\n    cout<<\"init done\"<<endl;\n  }\n\n  void processFrame(pcl::PointCloud<pcl::PointXYZ> &cloud, Eigen::Affine3d Tmotion) {\n\n    if(!initPoseSet)\n      return;\n\n    frame_nr_++;\n    cout<<\"frame nr=\"<<frame_nr_<<endl;\n    if((Tmotion.translation().norm() <0.005 && Tmotion.rotation().eulerAngles(0,1,2).norm()< 0.005) && useOdometry) {    //sanity check for odometry\n      return;\n    }\n    (void)ResetInvalidMotion(Tmotion);\n\n    cout<<\"frame=\"<<frame_nr_<<\"movement=\"<<(fuser_->GetPoseLastFuse().inverse()*pose_).translation().norm()<<endl;\n\n    ros::Time tplot=ros::Time::now();\n    plotPointcloud2(cloud,tplot);\n    m.lock();\n    fuser_->ProcessFrame<pcl::PointXYZ>(cloud,pose_,Tmotion);\n    m.unlock();\n    fuser_->PlotMapType();\n    tf::Transform Transform;\n    tf::transformEigenToTF(pose_,Transform);\n    tf_.sendTransform(tf::StampedTransform(Transform, tplot, world_link_id, fuser_base_link_id));\n    tf_.sendTransform(tf::StampedTransform(tf_sensor_pose_, tplot, fuser_base_link_id, laser_link_id));\n    fuser_odom.header.stamp=tplot;\n\n    tf::poseEigenToMsg( pose_,fuser_odom.pose.pose);\n    fuser_odom_publisher_.publish(fuser_odom);\n  }\n\n\n  //bool save_map_callback(std_srvs::Empty::Request  &req,std_srvs::Empty::Response &res )\n  bool ResetInvalidMotion(Eigen::Affine3d &Tmotion){\n    if(Tmotion.translation().norm() > MAX_TRANSLATION_DELTA) {\n      std::cerr<<\"Ignoring Odometry (max transl)!\\n\";\n      std::cerr<<Tmotion.translation().transpose()<<std::endl;\n      Tmotion.setIdentity();\n      return true;\n    }\n    else if(Tmotion.rotation().eulerAngles(0,1,2)(2) > MAX_ROTATION_DELTA) {\n      std::cerr<<\"Ignoring Odometry (max rot)!\\n\";\n      std::cerr<<Tmotion.rotation().eulerAngles(0,1,2).transpose()<<std::endl;\n      Tmotion.setIdentity();\n      return true;\n    }\n    else return false;\n  }\n  bool save_map_callback(std_srvs::Empty::Request  &req,\n                         std_srvs::Empty::Response &res ) {\n    char path[1000];\n    string time=ndt_generic::currentDateTimeString();\n\n    if(fuser_!=NULL){\n      snprintf(path,999,\"%s/%s_.MAP\",map_dir.c_str(),time.c_str());\n      m.lock();\n      if(file_format_map.compare(\".JFF\")==0)\n        fuser_->SaveCurrentNodeAsJFF(path);\n      else\n        fuser_->SaveGraphMap(path);\n\n      m.unlock();\n      ROS_INFO(\"Current map was saved to path= %s\", path);\n      return true;\n    }\n    else\n      ROS_INFO(\"No data to save\");\n    return false;\n  }\n\n  inline bool getAffine3dTransformFromTF(const ros::Time &time,const std::string &link_id,Eigen::Affine3d& ret,const ros::Duration &wait) {\n    static tf::TransformListener tf_listener;\n    tf::StampedTransform transform;\n    tf_listener_.waitForTransform(world_link_id, link_id,  time ,wait);\n    try{\n      tf_listener_.lookupTransform(world_link_id, link_id, time, transform);\n      tf::poseTFToEigen(transform, ret);\n      cout<<\"found \"<<ret.translation().transpose()<<endl;\n    }\n    catch (tf::TransformException ex){\n      ROS_ERROR(\"%s\",ex.what());\n      return false;\n    }\n    return true;\n  }\n\n  // Callback\n  void laserCallback(const sensor_msgs::LaserScan::ConstPtr& msg_in)\n  {\n    cout<<\"laser callback\"<<endl;\n    sensor_msgs::PointCloud2 cloud;\n    pcl::PointCloud<pcl::PointXYZ> pcl_cloud_unfiltered, pcl_cloud;\n    projector_.projectLaser(*msg_in, cloud);\n    pcl::fromROSMsg (cloud, pcl_cloud_unfiltered);\n\n    pcl::PointXYZ pt;\n    //add some variance on z\n    for(int i=0; i<pcl_cloud_unfiltered.points.size(); i++) {\n      pt = pcl_cloud_unfiltered.points[i];\n      if(sqrt(pt.x*pt.x+pt.y*pt.y) > min_laser_range_) {\n        pt.z += varz*((double)rand())/(double)INT_MAX;\n        pcl_cloud.points.push_back(pt);\n      }\n    }\n    T.setIdentity();\n    cout<<\"node: laser call back, process frame\"<<endl;\n    this->processFrame(pcl_cloud,T);\n\n\n  }\n\n  // Callback\n  void laserOdomCallback(const sensor_msgs::LaserScan::ConstPtr& msg_in,\n                         const nav_msgs::Odometry::ConstPtr& odo_in)\n  {\n    cout<<\"laser odom callback\"<<endl;\n    sensor_msgs::PointCloud2 cloud;\n    pcl::PointCloud<pcl::PointXYZ> pcl_cloud, pcl_cloud_unfiltered;\n    Eigen::Affine3d Tm;\n\n    tf::poseMsgToEigen(odo_in->pose.pose,this_odom);\n    if (frame_nr_  <= 1){\n      Tm.setIdentity();\n    }\n    else\n      Tm = last_odom.inverse()*this_odom;\n\n    last_odom = this_odom;\n    projector_.projectLaser(*msg_in, cloud);\n    pcl::fromROSMsg (cloud, pcl_cloud_unfiltered);\n    sensor_msgs::LaserScan msg_out=*msg_in;\n    msg_out.header.stamp=ros::Time::now();\n    msg_out.header.frame_id=\"/fuser_laser_link\";\n    laser_publisher_.publish(msg_out);\n    pcl::PointXYZ pt;\n\n    //add some variance on z\n    for(int i=0; i<pcl_cloud_unfiltered.points.size(); i++) {\n      pt = pcl_cloud_unfiltered.points[i];\n      if(sqrt(pt.x*pt.x+pt.y*pt.y) > min_laser_range_) {\n        pt.z += varz*((double)rand())/(double)INT_MAX;\n        pcl_cloud.points.push_back(pt);\n      }\n    }\n    this->processFrame(pcl_cloud,Tm);\n    cout<< \"publish fuser data\"<<endl;\n  }\n\n  void plotPointcloud2(pcl::PointCloud<pcl::PointXYZ> & cloud,ros::Time time = ros::Time::now()){\n    sensor_msgs::PointCloud2 msg_out;\n    pcl::toROSMsg(cloud,msg_out);\n    msg_out.header.frame_id=laser_link_id;\n    msg_out.header.stamp=time;\n    point2_publisher_.publish(msg_out);\n  }\n  void points2OdomCallback(const sensor_msgs::PointCloud2::ConstPtr& msg_in,\n                           const nav_msgs::Odometry::ConstPtr& odo_in)//callback is used in conjunction with odometry time filter.\n  {\n    ros::Time tstart=ros::Time::now();\n\n    tf::poseMsgToEigen(odo_in->pose.pose,this_odom);\n\n    Eigen::Affine3d Tm;\n    pcl::PointCloud<pcl::PointXYZ> cloud;\n\n    if (frame_nr_ == 0)\n      Tm.setIdentity();\n    else {\n      Tm = last_odom.inverse()*this_odom;\n    }\n    last_odom = this_odom;\n    pcl::fromROSMsg (*msg_in, cloud);\n    this->processFrame(cloud,Tm);\n    ros::Time tend=ros::Time::now();\n    cout<<\"Total execution time= \"<<tend-tstart<<endl;\n  }\n  void points2OdomCallbackTF(const sensor_msgs::PointCloud2::ConstPtr& msg_in){//this callback is used to look up tf transformation for scan data\n    Eigen::Affine3d Tm;\n    static bool last_odom_found=false;\n    pcl::PointCloud<pcl::PointXYZ> cloud;\n    pcl::fromROSMsg (*msg_in, cloud);\n    bool found_odom= getAffine3dTransformFromTF((msg_in->header.stamp-ros::Duration(sensor_offset_t_)),odometry_link_id,this_odom,ros::Duration(0.1));\n    if (frame_nr_ =0 || !found_odom||!last_odom_found)\n      Tm.setIdentity();\n    else {\n      Tm = last_odom.inverse()*this_odom;\n    }\n    last_odom_found=found_odom;\n\n    last_odom = this_odom;\n    this->processFrame(cloud,Tm);\n    cout<<\"TF callback Point2Odom\"<<endl;\n  }\n\n  void GTLaserPointsOdomCallback(const sensor_msgs::PointCloud2::ConstPtr& msg_in,\n                                 const nav_msgs::Odometry::ConstPtr& odo_in)//this callback is used for GT based mapping\n  {\n    cout<<\"GT diff:\"<<(msg_in->header.stamp-odo_in->header.stamp).toSec()<<endl;\n    Eigen::Affine3d Tmotion;\n    if(frame_nr_==0){\n      Tmotion=Eigen::Affine3d::Identity();\n    }\n    Eigen::Affine3d GT_pose;\n    pcl::PointCloud<pcl::PointXYZ> cloud;\n    tf::poseMsgToEigen(odo_in->pose.pose,pose_);\n    pcl::fromROSMsg (*msg_in, cloud);\n    ros::Time t_stamp=ros::Time::now();//msg_in->header.stamp;\n    tf::Transform gt_base;\n    tf::poseMsgToTF(odo_in->pose.pose,gt_base);\n    tf_.sendTransform(tf::StampedTransform(gt_base, t_stamp, world_link_id, std::string(\"online_\")+state_base_link_id));\n    tf_.sendTransform(tf::StampedTransform(tf_sensor_pose_, t_stamp, std::string(\"online_\")+state_base_link_id, laser_link_id));\n    plotPointcloud2(cloud);\n    m.lock();\n    fuser_->ProcessFrame(cloud,pose_,Tmotion);\n    fuser_->PlotMapType();\n    m.unlock();\n  }\n  void GTLaserPointsOdomCallbackTF(const sensor_msgs::PointCloud2::ConstPtr& msg_in)//this callback is used for GT based mapping with TF lookup\n  {\n    cout<<\"GT-TF toffset:\"<<sensor_offset_t_<<endl;\n    Eigen::Affine3d tmp_pose;\n    Eigen::Affine3d Tmotion=Eigen::Affine3d::Identity();\n    bool found_odom= getAffine3dTransformFromTF((msg_in->header.stamp-ros::Duration(sensor_offset_t_)),state_base_link_id,tmp_pose,ros::Duration(0.1));\n\n    if(found_odom){\n      pose_=tmp_pose;\n      pcl::PointCloud<pcl::PointXYZ> cloud;\n      pcl::fromROSMsg (*msg_in, cloud);\n      ros::Time t_stamp=ros::Time::now();//msg_in->header.stamp;\n      tf::Transform tf_gt_base;\n      tf::poseEigenToTF(pose_,tf_gt_base);\n      tf_.sendTransform(tf::StampedTransform(tf_gt_base, t_stamp, world_link_id, std::string(\"online_\")+state_base_link_id));\n      tf_.sendTransform(tf::StampedTransform(tf_sensor_pose_, t_stamp, std::string(\"online_\")+state_base_link_id, laser_link_id));\n      plotPointcloud2(cloud,t_stamp);\n      fuser_->ProcessFrame(cloud,pose_,Tmotion);\n      fuser_->PlotMapType();\n      m.unlock();\n    }\n\n  }\n  // Callback\n  void gt_callback(const nav_msgs::Odometry::ConstPtr& msg_in)//This callback is used to set initial pose from GT data.\n  {\n\n    Eigen::Affine3d gt_pose;\n    tf::poseMsgToEigen(msg_in->pose.pose,gt_pose);\n\n    if(initPoseFromGT && !initPoseSet) {\n      pose_ = gt_pose;\n      ROS_INFO(\"Set initial pose from GT track\");\n      fuser_=new GraphMapFuser(map_type_name,reg_type_name,pose_,sensorPose_);\n      cout<<\"----------------------------FUSER------------------------\"<<endl;\n      cout<<fuser_->ToString()<<endl;\n      fuser_->Visualize(visualize,plot_marker);\n      cout<<\"---------------------------------------------------------\"<<endl;\n      initPoseSet = true;\n\n    }\n  }\n\npublic:\n  // map publishing function\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"graph_map_fuser_node\");\n  ros::NodeHandle param(\"~\");\n  GraphMapFuserNode t(param);\n  ros::spin();\n\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "a0a8c16519498cfa0fc1472caad63af889c2965e", "size": 22831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/graph_map/src/graph_map_fuser_node.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/graph_map/src/graph_map_fuser_node.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/graph_map/src/graph_map_fuser_node.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": 38.436026936, "max_line_length": 151, "alphanum_fraction": 0.7114011651, "num_tokens": 6112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19451571527133654}}
{"text": "#pragma once\n#include <string>\n#include <vector>\n#include <memory>\n#include <filesystem>\n#include <unordered_map>\n#include <set>\n#include <Eigen/Dense>\n\n#include \"implementation/rendering/MaterialFlags.hpp\"\n\nnamespace orbtool\n{\n\n    using namespace Eigen;\n    namespace fs = std::filesystem;\n\n\tusing MaterialFlag = orbit::MaterialFlag;\n\n    struct FBXNode;\n\n\tstruct FBXTransform\n\t{\n\t\tVector3d position = Vector3d::Zero();\n\t\tQuaterniond rotation = Quaterniond::Identity();\n\t\tVector3d scaling = Vector3d::Zero();\n\t\tFBXTransform* parent = nullptr;\n\t\tQuaterniond GetCombinedRotation()\n\t\t{\n\t\t\tif (parent != nullptr)\n\t\t\t\treturn parent->GetCombinedRotation() * rotation;\n\t\t\treturn rotation;\n\t\t}\n\t\tVector3d GetCombinedPosition()\n\t\t{\n\t\t\tif (parent != nullptr)\n\t\t\t\treturn parent->GetCombinedPosition() + position;\n\t\t\treturn position;\n\t\t}\n\t};\n\n\tenum class FBXType\n\t{\n\t\tTYPE_MODEL,\n\t\tTYPE_GEOMETRY,\n\t\tTYPE_TEXTURE,\n\t\tTYPE_MATERIAL,\n\t\tTYPE_ATTRIBUTE,\n\t\tTYPE_INTERMODEL\n\t};\n\n\tstruct FBXBase\n\t{\n\t\tint64_t id = 0;\n\t\tFBXType type;\n\t};\n\n\tenum class MappingInformationType\n\t{\n\t\tMAPPING_BY_POLYGON_VERTEX,\n\t\tMAPPING_BY_VERTEX,\n\t\tMAPPING_BY_POLYGON,\n\n\t\tMAPPING_UNKNOWN\n\t};\n\n\tenum class ReferenceInformationType\n\t{\n\t\tREFERENCE_DIRECT,\n\t\tREFERENCE_INDEX_TO_DIRECT,\n\n\t\tREFERENCE_UNKNOWN\n\t};\n\n\tstruct NormalInfo\n\t{\n\t\tstd::vector<double> normals;\n\t\tstd::vector<int> normalIndices;\n\t\tMappingInformationType mit;\n\t\tReferenceInformationType rit;\n\t};\n\n\tstruct TangentInfo\n\t{\n\t\tstd::vector<double> tangents;\n\t\tstd::vector<int> tangentIndices;\n\t\tMappingInformationType mit;\n\t\tReferenceInformationType rit;\n\t};\n\n\tstruct UVInfo\n\t{\n\t\tstd::vector<double> uvs;\n\t\tstd::vector<int> uvIndices;\n\t\tMappingInformationType mit;\n\t\tReferenceInformationType rit;\n\t};\n\n\tstruct FBXGeometry : public FBXBase\n\t{\n\t\tstd::string name;\n\t\tstd::vector<double> vertices;\n\t\tstd::vector<int> indices;\n\t\tNormalInfo normals;\n\t\tTangentInfo tangents;\n\t\tUVInfo uvs;\n\t};\n\n\tstruct FBXModel : public FBXBase\n\t{\n\t\tFBXTransform transform;\n\t\tstd::string modelType;\n\t\tstd::string modelName;\n\t};\n\n\tenum class TextureType : uint32_t\n\t{\n\t\tTEXTURE_COLOR,\n\t\tTEXTURE_NORMAL,\n\t\tTEXTURE_ROUGHNESS,\n\t\tTEXTURE_OCCLUSION,\n\t\tTEXTURE_OTHER\n\t};\n\n\tstruct FBXTexture : public FBXBase\n\t{\n\t\tfs::path filepath;\n\t\tstd::string name;\n\t\tTextureType flags = TextureType::TEXTURE_OTHER;\n\t};\n\n\tstruct FBXMaterial : public FBXBase\n\t{\n\t\tstd::string name;\n\t\tVector4f diffuse = Vector4f::Zero();\n\t\tfloat roughness = 0.f;\n\t\tstd::vector<std::shared_ptr<FBXTexture>> textures;\n\t};\n\n\t// @brief: the type of light.\n\tenum class FBXLightType\n\t{\n\t\tDirectionalLight,\n\t\tPointLight,\n\t\tSpotLight\n\t};\n\n\tstruct FBXLight : public FBXBase\n\t{\n\t\t// @member: the color of the light. All lights share this property\n\t\tVector4f color = Vector4f::Zero();\n\t\t// @member: the position of the light. Only point- and spotlights\n\t\tVector4f position = Vector4f::Zero();\n\t\t// @member: the direction of the light rays. Only directional- and spotlights\n\t\tVector4f direction = Vector4f::Zero();\n\t\t// @member: the angle of a spotlight cone. Only spotlights\n\t\tfloat spotAngle = 0.f;\n\t\t// @member: the distance at which to begin dimming the light. Only point- and spotlights\n\t\tfloat falloffBegin = 0.f;\n\t\t// @member: the maximum distance of a light source. Only point- and spotlights\n\t\tfloat falloffEnd = 0.f;\n\t\t// @member: the type of the light\n\t\tFBXLightType ltype;\n\t};\n\n\tstruct FBXAttribute : public FBXBase\n\t{\n\t\tstd::string nodeType;\n\t\tstd::string nodeName;\n\t\tconst FBXNode* attributes;\n\t};\n\n\tenum class FBXConnectionType\n\t{\n\t\tCT_OBJECT_OBJECT,\n\t\tCT_OBJECT_PROPERTY,\n\t\tCT_PROPERTY_OBJECT,\n\t\tCT_PROPERTY_PROPERTY\n\t};\n\n\tstruct FBXConnection\n\t{\n\t\tFBXConnectionType type;\n\t\tstd::string propertyName;\n\t\tint64_t id0 = 0;\n\t\tint64_t id1 = 0;\n\t};\n\n\tstruct FBXData\n\t{\n\t\tstd::unordered_map<int64_t, std::shared_ptr<FBXBase>> nodes;\n\t\tstd::vector<FBXConnection> connections;\n\t};\n\n\tstruct FBXInterModel : public FBXBase\n\t{\n\t\tstd::shared_ptr<FBXModel> model;\n\t\tstd::vector<std::shared_ptr<FBXGeometry>> geometries;\n\t\tstd::vector<std::shared_ptr<FBXAttribute>> attributes;\n\t\tstd::vector<std::shared_ptr<FBXMaterial>> materials;\n\t\tstd::vector<std::shared_ptr<FBXModel>> children;\n\t};\n\n\tstruct FBXInterType\n\t{\n\t\tstd::unordered_map<int64_t, std::shared_ptr<FBXInterModel>> models;\n\t\tstd::vector<std::shared_ptr<FBXLight>> lights;\n\t};\n\n}\n", "meta": {"hexsha": "907c80938cd60dd285fe1c18b6c5e2ee7a661106", "size": 4284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "converter/inc/fbx/FbxTypes.hpp", "max_stars_repo_name": "LarsHagemann/OrbitEngine", "max_stars_repo_head_hexsha": "33e01efaac617c53a701f01729581932fc81e8bf", "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": "converter/inc/fbx/FbxTypes.hpp", "max_issues_repo_name": "LarsHagemann/OrbitEngine", "max_issues_repo_head_hexsha": "33e01efaac617c53a701f01729581932fc81e8bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-01-18T21:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T21:02:09.000Z", "max_forks_repo_path": "converter/inc/fbx/FbxTypes.hpp", "max_forks_repo_name": "LarsHagemann/OrbitEngine", "max_forks_repo_head_hexsha": "33e01efaac617c53a701f01729581932fc81e8bf", "max_forks_repo_licenses": ["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.3033175355, "max_line_length": 90, "alphanum_fraction": 0.7224556489, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19451571527133654}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  Aggregate SIMD numerical and type limits for PPC VMX\n\n  @copyright 2012 - 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_ARCH_POWER_VMX_LIMITS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_POWER_VMX_LIMITS_HPP_INCLUDED\n\n#include <boost/simd/arch/power/tags.hpp>\n#include <boost/simd/arch/common/limits.hpp>\n#include <boost/dispatch/meta/make_integer.hpp>\n#include <boost/simd/detail/brigand.hpp>\n#include <cstdint>\n\nnamespace boost { namespace simd\n{\n  template<> struct limits<boost::simd::vmx_>\n  {\n    using parent = boost::simd::simd_;\n\n    struct largest_integer\n    {\n      template<typename Sign> struct apply : boost::dispatch::make_integer<4,Sign> {};\n    };\n\n    struct smallest_integer\n    {\n      template<typename Sign> struct apply : boost::dispatch::make_integer<1,Sign> {};\n    };\n\n    using largest_real   = float;\n    using smallest_real  = float;\n\n    enum { bits = 128, bytes = 16 };\n  };\n} }\n\n#endif\n\n", "meta": {"hexsha": "29dc0a326d5e243334a01e03a53bd5b21a37518a", "size": 1268, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/power/vmx/limits.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/power/vmx/limits.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/power/vmx/limits.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": 26.4166666667, "max_line_length": 100, "alphanum_fraction": 0.5977917981, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19451570033299365}}
{"text": "#include <math.h>\n#include <stdio.h>\n\n#include <boost/math/quaternion.hpp>\n\nextern \"C\" void externalForces(double t, double* q,double *f,double *z){\n  f[0]=00;\n  f[1]=00;\n  f[2]=0.0;\n  \n}\ndouble prevq3=0;\nextern \"C\" void externalMomentum(double t, double* q,double *m,double *z){\n\n    m[0]=0;\n    m[1]=0;\n    m[2]=0;\n  \n  double deltamax = 1e-4;\n  if (fabs(prevq3-q[2])< deltamax){\n    printf(\"externalMomentum doing\\n\");\n    m[1]=50;\n  }else{\n    printf(\"externalMomentum passif\\n\");\n  }\n  prevq3=q[2];\n  // }\n  //prevq=\n}\n\nextern \"C\" void externalForceG(double t, double* q,double *f,double *z){\n  // std::cout << \"externalForceG\"<<std::endl;\n  f[0]=1000;\n  f[1]=0;\n  f[2]=0;\n  \n}\nextern \"C\" void externalMomentumY(double t, double* q,double *m,double *z){\n  // std::cout << \"externalMomentumY\"<<std::endl;\n  m[0]=0;\n  m[1]=0;\n  m[2]=0;\n  \n}\n", "meta": {"hexsha": "2b34d3432871b1c472a7f6716d808fb16fb191e1", "size": 844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Mechanics/Mechanisms/ShaftTube/TubePlugin/TubePlugin.cpp", "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": "examples/Mechanics/Mechanisms/ShaftTube/TubePlugin/TubePlugin.cpp", "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": "examples/Mechanics/Mechanisms/ShaftTube/TubePlugin/TubePlugin.cpp", "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": 18.7555555556, "max_line_length": 75, "alphanum_fraction": 0.5947867299, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19449787629743093}}
{"text": "#ifndef CELL_HPP\n#define CELL_HPP\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <map>\n#include <random>\n#include <string>\n\n#include <assert.h>\n\n#include <boost/format.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"stats.hpp\"\n\n\nusing namespace std;\n\n\n\nconst int NUM_CHR = 23;\nconst int NORM_PLOIDY = 2;\n\n// Number of chromsomes affected in a multipolar event\nconst int MULTI_NCHR = 16;\n\nclass Mutation\n{\npublic:\n    int mut_ID;\n\n    int type;   // Mutation type\n    int size;   // 1 for SNV\n    double time_occur;\n\n    int cell_ID;\n    int chr;  // chromosome on which the Mutation occurs\n    int arm;\n    int reciprocal;\n\n    int start;  // start position\n    int end;    // end position\n\n    double vaf;     // for SNV\n    int number;     // snv number\n\n    Mutation(){\n            mut_ID = 0;\n            time_occur = 0;\n            vaf = 0;\n            number = 1;\n    }\n\n\n    Mutation(int mut_ID, double time_occur){\n            this->mut_ID = mut_ID;\n            this->time_occur = time_occur;\n            this->vaf = 0;\n            this->number = 1;\n    }\n\n    Mutation(int mut_ID, double time_occur, int chr, int arm, int type, int reciprocal){\n            this->mut_ID = mut_ID;\n            this->time_occur = time_occur;\n\n            this->vaf = 0;\n            this->number = 1;\n\n            this->chr = chr;\n            this->arm = arm;\n            this->type = type;\n            this->reciprocal = reciprocal;\n    }\n\n    Mutation(int mut_ID, double time_occur, int chr, int start, int end, int arm, int type, int reciprocal){\n            this->mut_ID = mut_ID;\n            this->time_occur = time_occur;\n            this->vaf = 0;\n            this->number = 1;\n\n            this->chr = chr;\n            this->start = start;\n            this->end = end;\n            this->arm = arm;\n            this->type = type;\n            this->reciprocal = reciprocal;\n    }\n\n    // ~Mutation() = default;\n    // Mutation(const Mutation& other) = default;\n    // Mutation(Mutation&& other) = default;\n    // Mutation& operator=(const Mutation& other) = default;\n    // Mutation& operator=(Mutation&& other) = default;\n};\n\n\nclass Cell\n{\npublic:\n    int cell_ID;\n    int parent_ID;\n    int clone_ID;\n    vector<int> daughters;\n\n    double birth_rate;\n    double death_rate;\n\n    double mutation_rate;\n    double arm_prob;\n    double chr_prob;\n    double multi_prob;\n    int multi_nchr;\n\n    double ploidy;  // change ploidy to reflect WGD\n    int num_division;\n    double time_occur;\n\n    int flag;   // whether the cell is alive or not. 0:new, 1:divided, -1: death\n    double fitness;\n\n    double pos_x;\n    double pos_y;\n    double pos_z;\n\n    int wgd;\n    // copy number for chr, arm; relative so that it is safe to ignore clonal events\n    map<pair<int, int>, int> cn_profile;        // only applied to each arm\n    map<pair<int, int>, int> obs_cn_profile;    // grouped by chr-/arm- level\n    vector<float> cn_all;   // copy number for all regions\n\n    Cell *sibling = NULL;\n\n    double chr_probs[NUM_CHR];\n    double arm_probs[2] = {0.5, 0.5};\n    //chr gain, chr loss, arm gain, arm loss, (arm) doubling\n    vector<double> cna_type_probs{0.3, 0.3, 0.2, 0.2, 0};\n\n    vector<Mutation> mutations;\n\n    ~Cell() = default;\n    Cell(const Cell& other) = default;\n    Cell(Cell&& other) = default;\n    Cell& operator=(const Cell& other) = default;\n    Cell& operator=(Cell&& other) = default;\n\n    Cell() {\n            cell_ID = 0;\n            parent_ID = 0;\n            clone_ID = 0;\n\n            birth_rate = log(2);\n            death_rate = 0;\n\n            mutation_rate = 0;\n            arm_prob = 0;\n            chr_prob = 0;\n            multi_prob = 0;\n            multi_nchr = MULTI_NCHR;\n\n            ploidy = 2;\n            num_division = 0;\n            time_occur = 0;\n            flag = 0;\n\n            // parent = NULL;\n            for(int i = 0; i < NUM_CHR; i++){\n                chr_probs[i] = double(1/NUM_CHR);\n                for(int j=0; j < 3; j++){\n                    pair<int, int> pos(i,j);\n                    cn_profile[pos] = 0;\n                }\n            }\n    }\n\n    Cell(int cell_ID, int parent_ID) {\n            this->cell_ID = cell_ID;\n            this->parent_ID = parent_ID;\n            this->clone_ID = 0;\n\n            this->birth_rate = log(2);\n            this->death_rate = 0;\n\n            this->mutation_rate = 0;\n            this->arm_prob = 0;\n            this->chr_prob = 0;\n            this->multi_prob = 0;\n            this->multi_nchr = MULTI_NCHR;\n\n            this->ploidy = 2;\n            this->num_division = 0;\n            this->time_occur = 0;\n            this->flag = 0;\n\n            for(int i = 0; i < NUM_CHR; i++){\n                chr_probs[i] = double(1/NUM_CHR);\n                for(int j=0; j < 3; j++){\n                    pair<int, int> pos(i,j);\n                    cn_profile[pos] = 0;\n                }\n            }\n    }\n\n    Cell(int cell_ID, int parent_ID, double birth_rate, double death_rate, double mutation_rate, double ploidy, double time_occur){\n            this->cell_ID = cell_ID;\n            this->parent_ID = parent_ID;\n            this->clone_ID = 0;\n\n            this->birth_rate = birth_rate;\n            this->death_rate = death_rate;\n\n            this->mutation_rate = mutation_rate;\n            this->arm_prob = 0;\n            this->chr_prob = 0;\n            this->multi_prob = 0;\n            this->multi_nchr = MULTI_NCHR;\n\n            this->ploidy = ploidy;\n            this->time_occur = time_occur;\n            this->flag = 0;\n\n            for(int i = 0; i < NUM_CHR; i++){\n                chr_probs[i] = double(1/NUM_CHR);\n                for(int j=0; j < 3; j++){\n                    pair<int, int> pos(i,j);\n                    cn_profile[pos] = 0;\n                }\n            }\n    }\n\n\n    Cell* get_parent(vector<Cell>& cells){\n        for(int i = 0; i < cells.size(); i++){\n            Cell* cell = &cells[i];\n            if(cell->cell_ID == parent_ID) return cell;\n        }\n        return NULL;\n    }\n\n    /*\n    mut_ID -- the ID of last mutation\n    generate a random number of mutations\n    */\n    int generate_mutations(double mutation_rate, int& mut_ID, double time_occur){\n            // poisson_distribution<int> pois(mutation_rate);\n            // int nu = pois(eng);\n            int nu = gsl_ran_poisson(r, mutation_rate);\n            // cout << \"Generating \" << nu << \" mutations\" << endl;\n            for (int j=0; j < nu; j++) {\n                    mut_ID += 1;\n                    // cout << mut_ID << \"\\t\" << time_occur << endl;\n                    Mutation mut(mut_ID, time_occur);\n                    this->mutations.push_back(mut);\n            }\n            // cout << this->mutations.size() << endl;\n            return nu;\n    }\n\n\n    /*\n    generate a random number of CNAs based on a single mutation rate and type probabilities\n    */\n    int generate_CNV_bytype(int& mut_ID, double time_occur, int verbose = 0){\n        assert(mutation_rate > 0);\n        // poisson_distribution<int> pois(mutation_rate);\n        // int nu = pois(eng);\n        int nu = gsl_ran_poisson(r, mutation_rate);\n        if(verbose > 1) cout << \"Generating \" << nu << \" mutations under rate \" << mutation_rate << \" in cell \" << cell_ID << endl;\n\n        cna_type_probs[0] = cna_type_probs[1] = chr_prob/2;\n        cna_type_probs[2] = cna_type_probs[3] = arm_prob/2;\n\n        // cout << \"Probabilities of each event type: \";\n        // for(int i = 0; i < 5; i++){\n        //     cout << \"\\t\" << cna_type_probs[i];\n        // }\n        // cout << endl;\n\n        gsl_ran_discrete_t* dis_chr = gsl_ran_discrete_preproc(NUM_CHR, chr_probs);\n        gsl_ran_discrete_t* dis_arm = gsl_ran_discrete_preproc(2, arm_probs);\n        int chr, arm, reciprocal = 1;\n\n        for (int j=0; j < nu; j++) {\n                // chr = gsl_ran_discrete(r, dis_chr);\n                // double u = runiform(r, 0, 1);\n                // if(u<0.5)   reciprocal = 1;\n\n                // randomly select a type\n                int e = rchoose(r, cna_type_probs);\n                mut_ID += 1;\n\n                switch (e)\n                {\n                case 0:\n                    {\n                        if(verbose > 1) cout << \"\\t\\tchromosomal gain\" << endl;\n                        generate_chr_gain(mut_ID, dis_chr, reciprocal);\n                        break;\n                    }\n                case 1:\n                    {\n                        if(verbose > 1) cout << \"\\t\\tchromosomal loss\" << endl;\n                        generate_chr_loss(mut_ID, dis_chr, reciprocal);\n                        break;\n                    }\n                case 2:\n                    {\n                        if(verbose > 1) cout << \"\\t\\tchromosomal arm gain\" << endl;\n                        generate_arm_gain(mut_ID, dis_chr, dis_arm, reciprocal);\n                        break;\n                    }\n                case 3:\n                    {\n                        if(verbose > 1) cout << \"\\t\\tchromosomal arm loss\" << endl;\n                        generate_arm_loss(mut_ID, dis_chr, dis_arm, reciprocal);\n                        break;\n                    }\n                case 4:\n                    {\n                        if(verbose > 1) cout << \"\\t\\twhole arm region doubling\" << endl;\n                        generate_arm_gain(mut_ID, dis_chr, dis_arm, reciprocal);\n                        generate_arm_gain(mut_ID, dis_chr, dis_arm, reciprocal);\n                        break;\n                    }\n                default:\n                    break;\n                }\n        }\n        // cout << this->mutations.size() << endl;\n        return nu;\n    }\n\n\n    /*\n    generate a random number of CNAs\n    */\n    vector<int> generate_CNV(int& mut_ID, double time_occur, int verbose = 0){\n        assert(arm_prob >= 0 && chr_prob >= 0);\n        // A chr is not applicable to mutation if it has 0 copy. Since only relative changes are considered, assume there are sufficient copies\n        gsl_ran_discrete_t* dis_chr = gsl_ran_discrete_preproc(NUM_CHR, chr_probs);\n        gsl_ran_discrete_t* dis_arm = gsl_ran_discrete_preproc(2, arm_probs);\n        int chr, arm, reciprocal = 1;\n        double u = 0;\n\n        int nu1 = gsl_ran_poisson(r, chr_prob);\n        if(verbose > 1 && nu1 > 0) cout << \"Generating \" << nu1 << \" chr-level mutations under rate \" << chr_prob << \" in cell \" << cell_ID << endl;\n        if(nu1 > 0){\n            for (int j=0; j < nu1; j++) {\n                u = runiform(r, 0, 1);\n                if(u < 0.5){  // gain\n                    generate_chr_gain(mut_ID, dis_chr, reciprocal, verbose);\n                }else{\n                    generate_chr_loss(mut_ID, dis_chr, reciprocal, verbose);\n                }\n            }\n        }\n\n        int nu2 = gsl_ran_poisson(r, arm_prob);\n        if(verbose > 1 && nu2 > 0) cout << \"Generating \" << nu2 << \" arm-level mutations under rate \" << arm_prob << \" in cell \" << cell_ID << endl;\n        if(nu2 > 0){\n            for (int j=0; j < nu2; j++) {\n                u = runiform(r, 0, 1);\n                if(u < 0.5){  // gain\n                    generate_arm_gain(mut_ID, dis_chr, dis_arm, reciprocal, verbose);\n                }else{\n                    generate_arm_loss(mut_ID, dis_chr, dis_arm, reciprocal, verbose);\n                }\n            }\n        }\n\n        int nu3 = 0;\n        if(multi_prob>0){\n            nu3 = gsl_ran_poisson(r, multi_prob);\n            if(verbose > 1 && nu3 > 0) cout << \"Generating \" << nu3 << \" multipolar divisions under rate \" << multi_prob << \" in cell \" << cell_ID << endl;\n            if(nu3 > 0){\n                for (int j=0; j < nu3; j++) {\n                    generate_multipolar(mut_ID, dis_chr, multi_nchr, reciprocal, verbose);\n                }\n            }\n        }\n\n        int nu = nu1 + nu2 + nu3;\n        vector<int> nnu{nu, nu1, nu2, nu3};\n        // cout << this->mutations.size() << endl;\n        return nnu;\n    }\n\n\n    // generate fixed number of mutations\n    void generate_mutations_fixed(int& mut_ID, double time_occur, int num_mut){\n            for (int j=0; j < num_mut; j++) {\n                    mut_ID += 1;\n                    // cout << mut_ID << \"\\t\" << time_occur << endl;\n                    Mutation mut(mut_ID, time_occur);\n                    this->mutations.push_back(mut);\n            }\n            // cout << this->mutations.size() << endl;\n    }\n\n\n    double get_pos_fitness(){\n        double fitness = 0;\n        double fmax = 0;\n        if(this->ploidy>2){\n            // fmax = this->ploidy / 2;\n            fmax = 1;\n        }\n        // if(this->wgd == 1){\n        //     fitness += 1;\n        // }\n        // uniform_real_distribution<double> runifu(0,fmax);\n        // fitness = runifu(eng);\n\n        fitness = runiform(r, 0, fmax);\n\n        return fitness;\n    }\n\n    /*\n    Increase the number of mutations undergoing WGD\n    */\n    void update_mut_count(int multiple){\n        for (auto mut : this->mutations){\n            mut.number *= multiple;\n        }\n    }\n\n    int get_num_mut(){\n        int sum=0;\n        for (auto mut : this->mutations){\n            sum += mut.number;\n        }\n        return sum;\n    }\n\n\n    /*\n       This method generates CNVs, whose size follow exponential distribution\n     */\n    // int generate_mutations_SV(double mutation_rate, int mut_ID, double time_occur){\n    //     poisson_distribution<int> pois(mutation_rate);\n    //     int nu = pois(eng);\n    //\n    //\n    //     // cout << \"Generating \" << nu << \" mutations\" << endl;\n    //     for (int j=0; j < nu; j++){\n    //         mut_ID += 1;\n    //         // cout << mut_ID << \"\\t\" << time_occur << endl;\n    //         Mutation mut(mut_ID, time_occur);\n    //         this->mutations.push_back(mut);\n    //     }\n    //     // cout << this->mutations.size() << endl;\n    //     return nu;\n    // }\n\n    bool is_uniq_chr(int chr, vector<int>& mut_chrs){\n        bool uniq = true;\n        for(int j = 0; j < mut_chrs.size(); j++){\n            if(mut_chrs[j] == chr){\n                uniq = false;\n                break;\n            }\n        }\n        return uniq;\n    }\n\n    void generate_multipolar(int& mut_ID, gsl_ran_discrete_t* dis_chr, int multi_nchr, int reciprocal, int verbose = 0){\n    // int generate_chr_gain(int& mut_ID, int chr, int reciprocal, int verbose = 0){\n        // cout << \"gain event on cell \" << cell_ID << endl;\n        vector<int> mut_chrs;\n        for (int i = 0; i < multi_nchr; i++){\n            int chr = gsl_ran_discrete(r, dis_chr);\n            while(!(is_uniq_chr(chr, mut_chrs))){\n                chr = gsl_ran_discrete(r, dis_chr);\n            }\n            mut_chrs.push_back(chr);\n            // dis_chr[chr] = 0;\n\n            pair<int, int> pos1(chr, 1);\n            cn_profile[pos1]++;\n            pair<int, int> pos2(chr, 2);\n            cn_profile[pos2]++;\n\n            Mutation mut(mut_ID, time_occur, chr, 0, 1, reciprocal);\n            this->mutations.push_back(mut);\n\n            if(verbose > 1) cout << \"\\tmutation on cell \" << cell_ID << \" chr \" << chr+1;\n\n            // && sibling->cn_profile[pos]>0\n            if(sibling!=NULL){\n                sibling->cn_profile[pos1]--;\n                sibling->cn_profile[pos2]--;\n                Mutation mutr(mut_ID, time_occur, chr, 0, -1, reciprocal);\n                sibling->mutations.push_back(mutr);\n                if(verbose > 1) cout << \" reciprocal event on cell \" << sibling->cell_ID << endl;\n            }\n\n            mut_ID += 1;\n        }\n\n        if(verbose > 1) cout << endl;\n    }\n\n    // Assume that one chr can only has only type of event at one division\n    void generate_chr_gain(int& mut_ID, gsl_ran_discrete_t* dis_chr, int reciprocal, int verbose = 0){\n    // int generate_chr_gain(int& mut_ID, int chr, int reciprocal, int verbose = 0){\n        // cout << \"gain event on cell \" << cell_ID << endl;\n        int chr = gsl_ran_discrete(r, dis_chr);\n        // dis_chr[chr] = 0;\n\n        pair<int, int> pos1(chr, 1);\n        cn_profile[pos1]++;\n        pair<int, int> pos2(chr, 2);\n        cn_profile[pos2]++;\n\n        Mutation mut(mut_ID, time_occur, chr, 0, 1, reciprocal);\n        this->mutations.push_back(mut);\n\n        if(verbose > 1) cout << \"\\tmutation on cell \" << cell_ID << \" chr \" << chr+1;\n\n        // && sibling->cn_profile[pos]>0\n        if(reciprocal && sibling != NULL){\n            sibling->cn_profile[pos1]--;\n            sibling->cn_profile[pos2]--;\n            Mutation mutr(mut_ID, time_occur, chr, 0, -1, reciprocal);\n            sibling->mutations.push_back(mutr);\n            if(verbose > 1) cout << \" reciprocal event on cell \" << sibling->cell_ID << endl;\n        }\n\n        mut_ID += 1;\n\n        if(verbose > 1) cout << endl;\n    }\n\n    void generate_chr_loss(int& mut_ID, gsl_ran_discrete_t* dis_chr, int reciprocal, int verbose = 0){\n        // cout << \"loss event on cell \" << cell_ID << endl;\n        int chr = gsl_ran_discrete(r, dis_chr);\n        // dis_chr[chr] = 0;\n\n        pair<int, int> pos1(chr, 1);\n        cn_profile[pos1]--;\n        pair<int, int> pos2(chr, 2);\n        cn_profile[pos2]--;\n\n        Mutation mut(mut_ID, time_occur, chr, 0, -1, reciprocal);\n        this->mutations.push_back(mut);\n\n        if(verbose > 1) cout << \"\\tmutation on cell \" << cell_ID << \" chr \" << chr+1;\n\n        //  && sibling->cn_profile[pos]>0\n        if(reciprocal && sibling != NULL){\n            sibling->cn_profile[pos1]++;\n            sibling->cn_profile[pos2]++;\n            Mutation mutr(mut_ID, time_occur, chr, 0, 1, reciprocal);\n            sibling->mutations.push_back(mutr);\n            if(verbose > 1) cout << \" reciprocal event on cell \" << sibling->cell_ID << endl;\n        }\n\n        mut_ID += 1;\n\n        if(verbose > 1) cout << endl;\n    }\n\n\n    void generate_arm_gain(int& mut_ID, gsl_ran_discrete_t* dis_chr, gsl_ran_discrete_t* dis_arm, int reciprocal, int verbose = 0){\n        // cout << \"gain event on cell \" << cell_ID << endl;\n        int chr = gsl_ran_discrete(r, dis_chr);\n        // // dis_chr[chr] = 0;\n        //\n        int arm = gsl_ran_discrete(r, dis_arm) + 1;\n\n        pair<int, int> pos(chr, arm);\n        // cout << \"\\tcopy number on cell \" << cell_ID << \" chr \" << chr+1 << \" arm \" << arm << \" is \" << cn_profile[pos] << endl;\n        // while(cn_profile[pos]==0){\n        //     // cout << \"\\tcopy number on cell \" << cell_ID << \" chr \" << chr+1 << \" arm \" << arm << \" is \" << cn_profile[pos] << endl;\n        //     chr = gsl_ran_discrete(r, dis_chr);\n        //     pos = make_pair(chr, arm);\n        // }\n        // // gain is only feasible with at least one copy\n        // assert(cn_profile[pos] > 0);\n        cn_profile[pos]++;\n\n        Mutation mut(mut_ID, time_occur, chr, arm, 1, reciprocal);\n        this->mutations.push_back(mut);\n\n        if(verbose > 1) cout << \"\\tmutation on cell \" << cell_ID << \" chr \" << chr+1 << \" arm \" << arm+1;\n\n        // && sibling->cn_profile[pos]>0\n        if(reciprocal && sibling != NULL){\n            sibling->cn_profile[pos]--;\n            Mutation mutr(mut_ID, time_occur, chr, arm, -1, reciprocal);\n            sibling->mutations.push_back(mutr);\n            if(verbose > 1) cout << \" reciprocal event on cell \" << sibling->cell_ID << endl;\n        }\n\n        mut_ID += 1;\n\n        if(verbose > 1) cout << endl;\n    }\n\n    void generate_arm_loss(int& mut_ID, gsl_ran_discrete_t* dis_chr, gsl_ran_discrete_t* dis_arm, int reciprocal, int verbose = 0){\n        // cout << \"loss event on cell \" << cell_ID << endl;\n        int chr = gsl_ran_discrete(r, dis_chr);\n        int arm = gsl_ran_discrete(r, dis_arm) + 1;\n\n        pair<int, int> pos(chr, arm);\n        // cout << \"\\tcopy number on cell \" << cell_ID << \" chr \" << chr+1 << \" arm \" << arm << \" is \" << cn_profile[pos] << endl;\n        // while(cn_profile[pos]==0){\n        //     // cout << \"\\tcopy number on cell \" << cell_ID << \" chr \" << chr+1 << \" arm \" << arm << \" is \" << cn_profile[pos] << endl;\n        //     chr = gsl_ran_discrete(r, dis_chr);\n        //     pos = make_pair(chr, arm);\n        // }\n        // // loss is only feasible with at least one copy\n        // assert(cn_profile[pos] > 0);\n        cn_profile[pos]--;\n\n        Mutation mut(mut_ID, time_occur, chr, arm, -1, reciprocal);\n        this->mutations.push_back(mut);\n\n        if(verbose > 1) cout << \"\\tmutation on cell \" << cell_ID << \" chr \" << chr+1 << \" arm \" << arm+1;\n\n        //  && sibling->cn_profile[pos]>0\n        if(reciprocal && sibling != NULL){\n            sibling->cn_profile[pos]++;\n            Mutation mutr(mut_ID, time_occur, chr, arm, 1, reciprocal);\n            sibling->mutations.push_back(mutr);\n            if(verbose > 1) cout << \" reciprocal event on cell \" << sibling->cell_ID << endl;\n        }\n\n        mut_ID += 1;\n\n        if(verbose > 1) cout << endl;\n    }\n\n    // only output CNAs\n    void set_obs_cn(){\n        obs_cn_profile.clear();\n        for(int c = 0; c < NUM_CHR; c++){\n            bool has_cna = false;\n            if(cn_profile[pair<int, int>(c,1)] == cn_profile[pair<int, int>(c,2)] && cn_profile[pair<int, int>(c,1)] != 0){\n                obs_cn_profile[pair<int, int>(c,0)] = cn_profile[pair<int, int>(c,1)];\n                has_cna = true;\n                continue;\n            }\n            if(cn_profile[pair<int, int>(c,1)]!=0){\n                obs_cn_profile[pair<int, int>(c,1)] = cn_profile[pair<int, int>(c,1)];\n                has_cna = true;\n            }\n            if(cn_profile[pair<int, int>(c,2)]!=0){\n                obs_cn_profile[pair<int, int>(c,2)] = cn_profile[pair<int, int>(c,2)];\n                has_cna = true;\n            }\n            if(!has_cna){  // no cn changes\n                obs_cn_profile[pair<int, int>(c,0)] = 0;\n            }\n        }\n    }\n\n\n    // Compute the genotype differences relative to the starting cell (the sum of absolute copy number changes over all positions)\n    double get_cn_diff(double chr_weight = 1.0){\n        double diff = 0;\n        set_obs_cn();\n        for(auto cn : obs_cn_profile){\n            // cout << cn.first.first << \"\\t\" << cn.first.second << \"\\t\" << cn.second << endl;\n            int type = cn.first.second;\n            if(type == 0){\n                // cout << \"adding weight to chr-level CNAs \" << \"\\t\" << chr_weight << endl;\n                diff += chr_weight * abs(cn.second);\n            }else{\n                diff += abs(cn.second);\n            }\n        }\n        // cout << \"sum of CN changes: \" << diff << endl;\n        // diff = (double)diff/NUM_CHR;\n        // cout << \"average of CN changes: \" << diff << endl;\n\n        return diff;\n    }\n\n\n    void set_cn_all(){\n        set_obs_cn();\n\n        int k = 0;\n        for(int i = 0; i < NUM_CHR; i++){\n            for(int j=0; j < 3; j++){\n                cn_all.push_back(0);\n            }\n        }\n        for(auto cp: obs_cn_profile){\n            int m = cp.first.first * 3 + cp.first.second;\n            cn_all[m] = cp.second;\n        }\n\n        // cout << \"relative copy number of cell \" << cell_ID << \" is \";\n        // for(int i = 0; i < cn_all.size(); i++){\n        //     cout << \"\\t\" << cn_all[i];\n        // }\n        // cout << endl;\n    }\n\n    // output the copy numbers of cells. When all = 1, printing all the cells\n    // When mutation rate is low, each pos can have at most one event\n    void write_obs_cn(ofstream& fout, int all = 1){\n        // fout << \"\\tCNAs in cell \" << cell_ID << \" with flag \" << flag << endl;\n        if(all == 0 && flag != 0) return;\n        set_obs_cn();\n        // convert cn_profile to final profile: assign chr-level event if cn[c][p]==cn[c][q] != 0\n        for(auto cn : obs_cn_profile){\n            fout << cell_ID << \"\\t\" << cn.first.first + 1 << \"\\t\" << cn.first.second << \"\\t\" << cn.second << endl;\n        }\n    }\n\n    // output the copy number profiles of all cells.\n    void print_cn_profile(){\n        // fout << \"\\tCNAs in cell \" << cell_ID << \" with flag \" << flag << endl;\n        for(auto cn : cn_profile){\n            if(cn.second!=0){\n                cout << cell_ID << \"\\t\" << cn.first.first + 1 << \"\\t\" << cn.first.second << \"\\t\" << cn.second << endl;\n            }\n        }\n    }\n};\n\n\n\n/*\nto represent a population of cells\n*/\nclass Clone\n{\npublic:\n    int clone_ID;\n\n    vector<Cell>  cells;    // all the cells in the history, used for checking lineage history\n    vector<Cell>  curr_cells;   // only available cells at present\n\n    // variables to store subclone informaton\n    vector<int> subclone_ID;  // ID of subclones\n    map<int, double> subclone_time;   // Time subclone emerges\n    // map<int, double> subclone_freq; // Subclone frequency\n    // map<int, int> subclone_mut; // Number of mutations in subclone\n    map<int, double> subclone_fitness;\n    // map<int, int> subclone_division;\n    // map<int, int> subclone_size;\n    map<int, int> subclone_parent;\n    map<int, int> subclone_psize;\n    // map<int, double> mut_freq;\n\n    int num_clonal_mutation;\n    map<pair<int, int>, int> clonal_cn_profile;\n    set<tuple<int, int, int>> uniq_cns;\n    int num_novel_mutation;\n\n    int tot_division;    // total number of divisions in the population\n    int time_first_mut;     // which division the first mutation occurs\n    // double avg_elen;   // average time until next division for cells with immediate fitness changes\n\n    // int num_cell;\n    // double ploidy;\n    // double time_occur;\n    double time_end;    // ending time of the simulation\n    double frequency;\n    double fitness;\n    int model;  // the model of evolution\n\n    // Clone(int clone_ID, double time_occur, double fitness);\n\n    ~Clone() = default;\n    Clone(const Clone& other) = default;\n    Clone& operator=(const Clone& other) = default;\n    Clone& operator=(Clone&& other) = default;\n\n    Clone(){\n            clone_ID = 0;\n            num_clonal_mutation= 0;\n            num_novel_mutation= 0;\n            // time_occur = 0;\n            frequency = 0;\n            fitness = 0; // neutral evolution\n            tot_division = 0;\n            time_end = 0;\n            // avg_elen = 0;\n    }\n\n\n    Cell* get_cell_from_ID(vector<Cell>& cells, int cID){\n        for(int i = 0; i < cells.size(); i++){\n            Cell* cell = &cells[i];\n            if(cell->cell_ID == cID) return cell;\n        }\n        return NULL;\n    }\n\n    void initialize(double death_rate, double mutation_rate, int& mut_ID, int& nu, int num_clonal_mutation, int verbose = 0){\n            this->clone_ID = 0;\n            this->cells.clear();\n            this->curr_cells.clear();\n            // this->mut_freq.clear();\n            this->subclone_ID.clear();\n            this->subclone_time.clear();\n            // this->subclone_freq.clear();\n         this->subclone_fitness.clear();\n            this->num_clonal_mutation = num_clonal_mutation;\n            this->num_novel_mutation = 0;\n            // this->avg_elen = 0;\n\n            Cell ncell(1, 0);\n\n            ncell.mutation_rate = mutation_rate;\n\n            ncell.death_rate = death_rate;\n            // Genome germline(CHR_BIN_SIZE, NORM_PLOIDY);\n            // ncell.genome = germline;\n\n            cout << \"generating a new cell with ID \" << ncell.cell_ID << endl;\n            if(num_clonal_mutation>0) {\n                nu = num_clonal_mutation;\n                ncell.generate_mutations_fixed(mut_ID, 0, num_clonal_mutation);\n            }\n            else if (mutation_rate>0) {\n                nu = ncell.generate_mutations(mutation_rate, mut_ID, 0);\n            }\n            else{\n\n            }\n\n            if(verbose > 1) {\n                this->cells.push_back(ncell);\n            }\n            this->curr_cells.push_back(ncell);\n    }\n\n\n    void initialize_with_cnv(int model, double birth_rate, double death_rate, double mutation_rate, double arm_prob, double chr_prob, double multi_prob, double fitness, int& mut_ID, int& nu, int num_clonal_mutation, string file_cmut=\"\", int verbose = 0){\n            this->clone_ID = 0;\n            this->cells.clear();\n            this->curr_cells.clear();\n            // this->mut_freq.clear();\n            this->subclone_ID.clear();\n            this->subclone_time.clear();\n            // this->subclone_freq.clear();\n            this->subclone_fitness.clear();\n            this->num_clonal_mutation = num_clonal_mutation;\n            this->num_novel_mutation = 0;\n            this->time_first_mut = 0;\n            this->tot_division = 0;\n            this->model = model;\n            // this->avg_elen = 0;\n\n            Cell ncell(1, 0);\n\n            ncell.birth_rate = birth_rate;\n            ncell.death_rate = death_rate;\n\n            // ncell.mutation_rate = mutation_rate;\n            ncell.arm_prob = arm_prob;\n            ncell.chr_prob = chr_prob;\n            ncell.multi_prob = multi_prob;\n            ncell.mutation_rate = arm_prob + chr_prob + multi_prob;\n            ncell.multi_nchr = MULTI_NCHR;\n            ncell.fitness = fitness;\n\n            // Genome germline(CHR_BIN_SIZE, NORM_PLOIDY);\n            // ncell.genome = germline;\n\n            if(verbose > 1) cout << \"generating a new cell with ID \" << ncell.cell_ID << endl;\n            // TODO: read from file or fix mutation number\n            if(file_cmut!=\"\") {\n                set_clonal_mut(file_cmut);\n                for(auto cp : this->clonal_cn_profile){\n                    ncell.cn_profile[cp.first] = cp.second;\n                }\n            }\n            else if (num_clonal_mutation > 0) {\n                // ncell.generate_mutations_fixed(mut_ID, 0, num_clonal_mutation);\n                nu = num_clonal_mutation;\n                if(verbose > 1) cout << \"Generating \" << nu << \" clonal mutations in cell \" << ncell.cell_ID << endl;\n                // mut_ID += nu;\n                for (int j=0; j < num_clonal_mutation; j++) {\n                    ncell.generate_CNV(mut_ID, 0, verbose);\n                    // cout << mut_ID << \"\\t\" << 0 << endl;\n                    Mutation mut(mut_ID, 0);\n                    ncell.mutations.push_back(mut);\n                }\n            }\n            else{   // no clonal mutations\n                // nu = ncell.generate_CNV(mut_ID, 0);\n\n                // cout << \"mutation probabilities of each chromosome on cell \" << ncell.cell_ID << endl;\n                // for(int i = 0; i < NUM_CHR; i++){\n                //     ncell.chr_probs[i] = (double) 1/NUM_CHR;\n                //     cout << \"\\t\" << ncell.chr         // }\n                // cout << endl;\n            }\n\n            if(verbose > 1) {\n                if(num_clonal_mutation>0 || file_cmut!=\"\"){\n                    cout << \"copy number profile after assigning clonal mutations\" << endl;\n                    ncell.print_cn_profile();\n                }\n            }\n            this->cells.push_back(ncell);\n            this->curr_cells.push_back(ncell);\n    }\n\n\n    /*\n       lambda: The net growth rate of the background host population\n       freq: The frequency of a subclone\n     */\n    double get_subclone_fitness(double lambda, double freq, double tend, double t1){\n            double s = (lambda * t1 + log(freq / (1 - freq))) / (lambda * (tend - t1));\n            return s;\n    }\n\n    /*\n    This function computes the theoretical subclone frequency.\n       lambda: The net growth rate of the background host population\n       freq: The frequency of a subclone\n     */\n    double get_subclone_freq_exp(double lambda, double fitness, double tend, double t1){\n            double numerator = exp(lambda * (1 + fitness) * (tend - t1));\n            // double f = numerator / (numerator + exp(lambda * tend) + exp(lambda * (tend - t1)));\n            double f = numerator / (numerator + exp(lambda * tend));\n            return f;\n    }\n\n\n    void print_summary(string outfile) {\n            ofstream out;\n            out.setf(ios::fixed);\n            out.setf(ios::showpoint);\n            out.precision(9);\n            out.open(outfile);\n\n            map<int, int> subclone_nmut = get_subclone_nmut();\n            map<int, double> subclone_freq = get_subclone_freq();\n            map<int, int> subclone_ndiv = get_subclone_ndiv();\n            map<int, double> subclone_adiv = get_subclone_adiv();\n            double ploidy = get_avg_ploidy();\n\n            out << \"Average ploidy of the population: \" << ploidy << endl;\n\n            double lambda = log(2);\n            out << \"Information for host population:\" << endl;\n            for(auto cell : curr_cells){\n                if(cell.clone_ID == 0){\n                    lambda = cell.birth_rate - cell.death_rate;\n                    out << \"\\tCell ID: \" << cell.cell_ID << endl;\n                    out << \"\\tMutation rate: \" << cell.mutation_rate << endl;\n                    out << \"\\tChr-level CNA rate: \" << cell.chr_prob << endl;\n                    out << \"\\tArm-level CNA rate: \" << cell.arm_prob << endl;\n                    out << \"\\tMultipolar spindle (hopeful monster) rate: \" << cell.multi_prob << endl;\n                    out << \"\\tBirth rate: \" << cell.birth_rate << endl;\n                    out << \"\\tDeath rate: \" << cell.death_rate << endl;\n                    out << \"\\tEffective mutation rate (\u03bc/\u03b2): \" << cell.mutation_rate / ((cell.birth_rate-cell.death_rate)/cell.birth_rate) << endl;\n                    out << endl;\n                    if(model==0) break;     // same rates under neutral evolution\n                }\n            }\n            out << endl;\n            out << \"\\tNumber of clonal mutation: \"<< num_clonal_mutation << endl;\n            out << \"\\tNumber of subclonal mutation: \"<< num_novel_mutation << endl;\n            out << \"\\tNumber of total divisions: \"<< tot_division << endl;\n            out << \"\\tEnd time of simulation: \"<< time_end << endl;\n            int num_subclone = subclone_ID.size();\n            out << \"Number of subclones: \" << num_subclone << endl;\n            if (num_subclone > 0) {\n                    out << \"Information for each subclone:\" << endl;\n                    for(int i = 0; i < num_subclone; i++){\n                        out << \"Subclone \" << subclone_ID[i] << endl;\n                        for(auto cell : curr_cells){\n                            if(cell.clone_ID == subclone_ID[i]){\n                                out << \"\\tMutation rate: \" << cell.mutation_rate << endl;\n                                out << \"\\tBirth rate: \" << cell.birth_rate << endl;\n                                out << \"\\tDeath rate: \" << cell.death_rate << endl;\n                                out << \"\\tEffective mutation rate (\u03bc/\u03b2): \" << cell.mutation_rate / ((cell.birth_rate-cell.death_rate)/cell.birth_rate) << endl;\n                                break;\n                            }\n                        }\n                        out << \"\\tFrequency: \" << subclone_freq[subclone_ID[i]] << endl;\n                        out << \"\\tNumber of mutations in subclone: \" << subclone_nmut[subclone_ID[i]] << endl;\n                        out << \"\\tFitness advantage: \" << subclone_fitness[subclone_ID[i]] << endl;\n                        out << \"\\tTime subclone emerges (simulation time): \" << subclone_time[subclone_ID[i]] << endl;\n                        out << \"\\tNumber of divisions: \" << subclone_ndiv[subclone_ID[i]] << endl;\n                        out << \"\\tAverage number of divisions per cell: \" << subclone_adiv[subclone_ID[i]] << endl;\n                        out << \"\\tPopulation size when subclone emerges: \" << subclone_psize[subclone_ID[i]] << endl;\n                        out << \"\\tTime subclone emerges (tumor doublings): \" << log(subclone_psize[subclone_ID[i]])/(lambda) << endl;\n                        // out << \"\\tParent of subclone (0 is host): \" << subclone_parent[[subclone_ID[i]]];\n                        out << endl;\n                    }\n            }\n            else{\n                    out << \"No clones\\n\\n\";\n            }\n            out.close();\n    }\n\n\n    double get_rmax(){\n            // Find  maximum birth rate (bmax) and maximum death rate (dmax) in the population\n            double bmax = 0;\n            double dmax = 0;\n            for(unsigned int i=0; i<curr_cells.size(); i++) {\n                    Cell ci = curr_cells[i];\n                    double bi = ci.birth_rate;\n                    double di = ci.death_rate;\n                    if (bi > bmax) {\n                            bmax = bi;\n                    }\n                    if(di > dmax) {\n                            dmax = di;\n                    }\n            }\n            // cout << \"Maximum birth rate: \" << bmax << endl;\n            // cout << \"Maximum death rate: \" << dmax << endl\n            return bmax + dmax;\n    }\n\n    /*\n       This method simulates tumour growth with a rejection-kinetic Monte Carlo algorithm.\n       intput:\n        Nend -- the number of cells in the final population;\n        mutation_rate -- the Mutation rate per Cell division;\n        time_occur -- defined in terms of population doublings\n       output:\n        a tree-like structure. For each Cell, its children, occurence time, birth rate, death rate\n     */\n    void grow(int num_subclone, int num_clonal_mutation, vector<double> fitness, vector<double> time_occur, int Nend, double birth_rate, double death_rate, double mutation_rate, int verbose = 0){\n            // time is defined in terms of population doublings\n            double t = 0;\n            int cell_count = 0;     // To count the total number of cells in histor\n            // Initialize the simulation with one Cell\n            int mut_ID = 0;\n            int nu = 0; // The number of new mutations\n\n            unsigned int fitmutant = 0;\n            vector<double> timeN_occur;\n            double lambda = birth_rate - death_rate;\n            // convert time_occur from tumor doublings time to real time\n            cout << \"Subclone occurring time (tumor cell number):\" << endl;\n            for (unsigned int i = 0; i< time_occur.size(); i++){\n                timeN_occur.push_back(ceil(exp(lambda * time_occur[i])));\n                cout << \"\\t\"  << timeN_occur[i];\n            }\n            // timeN_occur.push_back(0);\n            cout << \"\\n\";\n\n            initialize(death_rate, mutation_rate, mut_ID, nu, num_clonal_mutation, verbose);\n            cell_count += 1;\n            while(this->curr_cells.size() < Nend) {\n                    if (this->curr_cells.size() == 0) {\n                        t = 0;\n                        mut_ID = 0;\n                        nu = 0;\n                        cell_count = 0;\n                        initialize(death_rate, mutation_rate, mut_ID, nu, num_clonal_mutation, verbose);\n                        cell_count += 1;\n                        continue;\n                    }\n                    // Choose a random Cell from the current population\n                    // uniform_int_distribution<> iunif(0, this->curr_cells.size() - 1);\n                    // int rindex = iunif(eng);\n                    int rindex = myrng(this->curr_cells.size());\n\n                    Cell rcell = this->curr_cells[rindex];\n                    // cout << \"Selecting \" << rindex+1 << \"th cell\" << endl;\n                    // cout << \"Selecting cell \" << rcell.cell_ID << endl;\n                    double rmax = get_rmax();\n\n                    // increase time\n                    // uniform_real_distribution<double> runifu(0,1);\n                    // double tau = -log(runifu(eng)); // an exponentially distributed random variable\n                    double tau = -log(runiform(r, 0, 1));\n                    double deltaT = tau/(rmax * this->curr_cells.size());\n                    t += deltaT;\n\n                    // draw a random number\n                    // uniform_real_distribution<double> runif(0.0,rmax);\n                    // double rb = runif(eng);\n                    double rb = runiform(r, 0, rmax);\n                    // cout << \"random number \" << rb << endl;\n                    // birth event if r<birthrate\n                    if(rb < rcell.birth_rate) {\n                            // cout << \"Number of generated cells \" << this->cells.size() << endl;\n                            // increase one Cell\n                            // cout << \"birth event at time \" << t << endl;\n                            int parent_ID = rcell.cell_ID;\n                            // cout << \"   parent \" << parent_ID << endl;\n                            Cell dcell1 = Cell(rcell);\n                            dcell1.cell_ID = cell_count + 1;\n                            dcell1.parent_ID = parent_ID;\n                            dcell1.num_division = rcell.num_division + 1;\n\n                            Cell dcell2 = Cell(rcell);\n                            dcell2.cell_ID = cell_count + 2;\n                            dcell2.parent_ID = parent_ID;\n                            dcell2.num_division = rcell.num_division + 1;\n                            cell_count += 2;\n                            // cout << \"   children \" << dcell1.cell_ID  << \"\\t\" << dcell2.cell_ID << endl;\n                            // daughter cells aquire nu new mutations, where nu ~ Poisson(mutation_rate)\n                            if (mutation_rate>0) {\n                                    nu +=  dcell1.generate_mutations(mutation_rate, mut_ID, t);\n                                    // mut_ID += nu;\n                                    nu +=  dcell2.generate_mutations(mutation_rate, mut_ID, t);\n                                    // mut_ID += nu;\n                            }\n                            // introduce a fitter mutatant\n                            if(fitmutant < num_subclone && this->curr_cells.size() >= timeN_occur[fitmutant]) {\n                                    double fitval = fitness[fitmutant];\n                                    cout << \"Introducing a fitter mutatant with fitness \" << fitval << endl;\n                                    dcell1.fitness = fitval;\n                                    // dcell1.death_rate = runifu(eng) * rcell.death_rate;\n                                    dcell1.death_rate = runiform(r, 0, 1) * rcell.death_rate;\n                                    dcell1.birth_rate = (1 + dcell1.fitness) * (rcell.birth_rate - rcell.death_rate) + dcell1.death_rate;\n                                    int clone_ID = this->clone_ID + fitmutant + 1;\n                                    cout << \"   birth rate: \" << dcell1.birth_rate << endl;\n                                    cout << \"   death rate: \" << dcell1.death_rate << endl;\n                                    dcell1.clone_ID = clone_ID;\n                                    this->subclone_ID.push_back(clone_ID);\n                                    this->subclone_fitness[clone_ID] = fitval;\n                                    this->subclone_time[clone_ID] = t;\n                                    this->subclone_psize[clone_ID] = this->curr_cells.size();\n                                    fitmutant += 1;\n                            }\n                            if(verbose > 1) {\n                                    for(unsigned int i = 0; i < this->cells.size(); i++) {\n                                            if (this->cells[i].cell_ID==rcell.cell_ID) {\n                                                    rcell.num_division += 1;\n                                                    rcell.flag = 1;\n                                                    this->cells[i] = rcell;\n                                                    break;\n                                               }\n                                    }\n                            }\n                            // Remove the parent cell from the list of current cells\n                            // cout << \"Removing cell \" << this->curr_cells[rindex].cell_ID << endl;\n                            this->curr_cells.erase(this->curr_cells.begin()+rindex);\n                            dcell1.time_occur = t;\n                            dcell2.time_occur = t;\n                            this->curr_cells.push_back(dcell1);\n                            this->curr_cells.push_back(dcell2);\n\n                            if(verbose > 1) {\n                                this->cells.push_back(dcell1);\n                                this->cells.push_back(dcell2);\n                            }\n                    }\n                    // death event if b<r<b+d\n                    if(rb >= rcell.birth_rate && rb < rcell.birth_rate + rcell.death_rate) {\n                            // cout << \" death event\" << endl;\n                            if(verbose > 1) {\n                                    for(unsigned int i = 0; i < this->cells.size(); i++) {\n                                            if (this->cells[i].cell_ID==rcell.cell_ID) {\n                                                    rcell.flag = -1;\n                                                    this->cells[i] = rcell;\n                                                    break;\n                                            }\n                                    }\n                            }\n                            this->curr_cells.erase(this->curr_cells.begin()+rindex);\n                    }\n                    // cout << \"===========================\" << endl;\n            }\n            // this->set_ploidy(this->curr_cells);\n            // cout << \"The average ploidy of this clone: \" << this->ploidy << endl;\n            cout << \"Generated \" << cell_count << \" cells with \" << nu << \" mutations\"  << \" in \" << tot_division << \" divisions\"<< endl;\n            cout << \"End time: \" << t << endl;\n    }\n\n\n    /*\n       This method simulates tumour growth with a rejection-kinetic Monte Carlo algorithm.\n       intput:\n        Nend -- the cell population size at the end\n        mutation_rate -- the mutation rate per cell division;\n        model -- 0: neutral, 1: gradual, 2: punctuated\n       output:\n        a tree-like structure. For each cell, its children, occurence time, birth rate, death rate\n     */\n     void grow_with_cnv(int num_subclone, int num_clonal_mutation, int model, const vector<double>& fitness, const vector<double>& time_occur, int Nend, double birth_rate, double death_rate, double mutation_rate, double arm_prob, double chr_prob, double multi_prob, int genotype_diff = 0, double chr_weight = 1.0, int chr_sel = 0, string file_cmut = \"\", int verbose = 0){\n             double t = 0;\n             int cell_count = 0;     // To count the total number of cells in history\n             int mut_ID = 0;\n             int nu = 0; // The number of new mutations\n\n             // Initialize the simulation with one cell\n             initialize_with_cnv(model, birth_rate, death_rate, mutation_rate, arm_prob, chr_prob, multi_prob, 0, mut_ID, nu, num_clonal_mutation, file_cmut, verbose);\n             cell_count += 1;\n\n             if(verbose > 1) cout << \"simulating tumour growth with CNA\" << endl;\n             unsigned int fitmutant = 0;\n             int num_mut_event = 0; // count the number of times a CNA event is introduced\n\n             while(this->curr_cells.size() < Nend) {\n                 if (this->curr_cells.size() == 0) {\n                     t = 0;\n                     mut_ID = 0;\n                     nu = 0;\n                     cell_count = 0;\n                     initialize_with_cnv(model, birth_rate, death_rate, mutation_rate, arm_prob, chr_prob, multi_prob, 0, mut_ID, nu, num_clonal_mutation, file_cmut, verbose);\n                     cell_count += 1;\n                     continue;\n                 }\n                 // Choose a random Cell from the current population\n                 int rindex = myrng(this->curr_cells.size());\n\n                 Cell rcell = this->curr_cells[rindex];\n                 // cout << \"Selecting \" << rindex+1 << \"th cell\" << endl;\n                 // cout << \"Selecting cell \" << rcell.cell_ID << endl;\n                 double rmax = get_rmax();\n                 if(verbose > 1) cout << \"max sum of birth rate and death rate is \" << rmax << endl;\n                 // increase time\n                 double tau = -log(runiform(r, 0, 1));\n                 double deltaT = tau/(rmax * this->curr_cells.size());\n                 t += deltaT;\n\n                 // draw a random number\n                 double rb = runiform(r, 0, rmax);\n                 // cout << \"random number \" << rb << endl;\n                 // birth event if r<birthrate\n                 if(rb < rcell.birth_rate) {\n                     // cout << \"Number of generated cells \" << this->cells.size() << endl;\n                     // increase one cell\n                     if(verbose > 1){\n                         cout << \"birth rate for cell \"<< rcell.cell_ID  << \" is \" << rcell.birth_rate << endl;\n                     }\n                     // cout << \"birth event at time \" << t << endl;\n                     int parent_ID = rcell.cell_ID;\n                     // cout << \"   parent \" << parent_ID << endl;\n                     Cell dcell1 = Cell(rcell);\n                     // cout << \"birth rates: \" << dcell1.birth_rate << \"\\t\" << rcell.birth_rate << endl;\n                     dcell1.cell_ID = cell_count + 1;\n                     dcell1.parent_ID = parent_ID;\n                     dcell1.num_division = rcell.num_division + 1;\n                     copy(rcell.chr_probs, rcell.chr_probs + NUM_CHR, dcell1.chr_probs);\n                     dcell1.time_occur = t;\n\n                     Cell dcell2 = Cell(rcell);\n                     dcell2.cell_ID = cell_count + 2;\n                     dcell2.parent_ID = parent_ID;\n                     dcell2.num_division = rcell.num_division + 1;\n                     copy(rcell.chr_probs, rcell.chr_probs + NUM_CHR, dcell2.chr_probs);\n                     dcell2.time_occur = t;\n\n                     dcell1.sibling = &dcell2;\n                     dcell2.sibling = &dcell1;\n\n                     rcell.daughters.push_back(dcell1.cell_ID);\n                     rcell.daughters.push_back(dcell2.cell_ID);\n\n                     cell_count += 2;\n                     tot_division += 1;\n                     // cout << \"   children \" << dcell1.cell_ID  << \"\\t\" << dcell2.cell_ID << endl;\n                     // daughter cells aquire nu new mutations, where nu ~ Poisson(mutation_rate)\n                     if (mutation_rate > 0) {\n                         // nu1: a vector of 4 numbers (#total CNAs, #chr-level CNAs, #arm-level CNAs, #MP CNAs)\n                         vector<int> nu1 = dcell1.generate_CNV(mut_ID, t, verbose);\n                         nu += nu1[0];\n                         vector<int> nu2 = dcell2.generate_CNV(mut_ID, t, verbose);\n                         nu += nu2[0];\n\n                         if(verbose > 1){\n                             cout << \"Number of mutations (total, chr-level, arm-level) in cell \" << dcell1.cell_ID << \": \";\n                             for(int i = 0; i < nu1.size(); i++){\n                                 cout << \"\\t\" << nu1[i];\n                             }\n                             cout << endl;\n\n                             cout << \"Number of mutations (total, chr-level, arm-level) in cell \" << dcell2.cell_ID << \": \";\n                             for(int i = 0; i < nu2.size(); i++){\n                                 cout << \"\\t\" << nu2[i];\n                             }\n                             cout << endl;\n                        }\n\n                         int sentinel_nu1 = nu1[0];\n                         int sentinel_nu2 = nu2[0];\n                         if(chr_sel == 1){  // only assume selection on chr-level events\n                             sentinel_nu1 = nu1[1];\n                             sentinel_nu2 = nu2[1];\n                         }\n                         if(sentinel_nu1 > 0 || sentinel_nu2 > 0) // all simulated CNAs are reciprocal\n                         {\n                            num_mut_event += 1;     // count the order of mutations introduced\n                            if(num_mut_event == 1)  time_first_mut = tot_division;\n                            // Introduce selection to cells with CNAs using specified fitness\n                            if(model > 0) assert(fitness.size() > 0);\n\n                            double gdiff1 = 1;\n                            double gdiff2 = 1;\n                            if(genotype_diff > 0){\n                                gdiff1 = dcell1.get_cn_diff(chr_weight);\n                                gdiff2 = dcell2.get_cn_diff(chr_weight);\n                            }\n\n                            if(model == 2 && num_mut_event == 1){ // only introduce selection at first hit\n                                 // dcell1.birth_rate = (1 + gdiff1 * fitness[0]) * birth_rate;\n                                 // dcell2.birth_rate = (1 + gdiff2 * fitness[0]) * birth_rate;\n                                 if(genotype_diff > 0){\n                                     dcell1.birth_rate = birth_rate / (1 + gdiff1 * fitness[0]);\n                                     dcell2.birth_rate = birth_rate / (1 + gdiff2 * fitness[0]);\n                                 }else{\n                                     dcell1.birth_rate = rcell.birth_rate * (1 + fitness[0]);\n                                     dcell2.birth_rate = rcell.birth_rate * (1 + fitness[0]);\n                                 }\n\n                                 if(verbose > 1){\n                                     cout << \"new birth rate for cell \"<< dcell1.cell_ID  << \" is \" << dcell1.birth_rate << \" with genotype difference \" << gdiff1 << endl;\n                                     cout << \"new birth rate for cell \"<< dcell2.cell_ID  << \" is \" << dcell2.birth_rate << \" with genotype difference \" << gdiff2 << endl;\n                                 }\n                            }\n                            if(model == 1){     // gradual selection, each CNA leads to fitness change of daughter cells\n                                 if(genotype_diff > 0){ // The genotype changes are based on initial cell\n                                     dcell1.birth_rate = birth_rate / (1 + gdiff1 * fitness[0]);\n                                     dcell2.birth_rate = birth_rate / (1 + gdiff2 * fitness[0]);\n\n                                     if(verbose > 1){\n                                         cout << \"new birth rate for cell \"<< dcell1.cell_ID  << \" is \" << dcell1.birth_rate << \" with genotype difference \" << gdiff1 << endl;\n                                         cout << \"new birth rate for cell \"<< dcell2.cell_ID  << \" is \" << dcell2.birth_rate << \" with genotype difference \" << gdiff2 << endl;\n                                     }\n                                 }else{\n                                     dcell1.birth_rate = rcell.birth_rate * (1 + fitness[0]);\n                                     dcell2.birth_rate = rcell.birth_rate * (1 + fitness[0]);\n                                 }\n                            }\n                            // cout << \"fitness \" << fitness[0] << endl;\n                            if(model == 3){  // positive selection in term of genotype difference\n                                dcell1.birth_rate = birth_rate * (1 + gdiff1 * fitness[0]);\n                                dcell2.birth_rate = birth_rate * (1 + gdiff2 * fitness[0]);\n                                if(verbose > 1){\n                                    cout << \"new birth rate for cell \"<< dcell1.cell_ID  << \" is \" << dcell1.birth_rate << \" with genotype difference \" << gdiff1 << endl;\n                                    cout << \"new birth rate for cell \"<< dcell2.cell_ID  << \" is \" << dcell2.birth_rate << \" with genotype difference \" << gdiff2 << endl;\n                                }\n                            }\n                         }\n                     }\n\n                     // if(verbose > 1) {\n                         for(unsigned int i = 0; i < this->cells.size(); i++) {\n                             if (this->cells[i].cell_ID==rcell.cell_ID) {\n                                     rcell.num_division += 1;\n                                     rcell.flag = 1;\n                                     this->cells[i] = rcell;\n                                     break;\n                             }\n                         }\n                     // }\n                     // Remove the parent cell from the list of current cells\n                     // cout << \"Removing cell \" << this->curr_cells[rindex].cell_ID << endl;\n                     this->curr_cells.erase(this->curr_cells.begin()+rindex);\n                     dcell1.time_occur = t;\n                     dcell2.time_occur = t;\n                     this->curr_cells.push_back(dcell1);\n                     this->curr_cells.push_back(dcell2);\n\n                     // if(verbose > 1) {\n                         this->cells.push_back(dcell1);\n                         this->cells.push_back(dcell2);\n                     // }\n                 }\n                 // death event if b<r<b+d\n                 if(rb >= rcell.birth_rate && rb < rcell.birth_rate + rcell.death_rate) {\n                     // cout << \" death event\" << endl;\n                     // if(verbose > 1) {\n                         for(unsigned int i = 0; i < this->cells.size(); i++) {\n                             if (this->cells[i].cell_ID==rcell.cell_ID) {\n                                 rcell.flag = -1;\n                                 this->cells[i] = rcell;\n                                 break;\n                             }\n                         }\n                     // }\n                     this->curr_cells.erase(this->curr_cells.begin()+rindex);\n                 }\n                 // cout << \"===========================\" << endl;\n             }\n             // this->set_ploidy(this->curr_cells);\n             // cout << \"The average ploidy of this clone: \" << this->ploidy << endl;\n             time_end = t;\n             num_novel_mutation = nu;\n             if(verbose > 1) cout << \"Generated \" << cell_count << \" cells in total with \" << nu << \" mutations in \" << tot_division << \" divisions during time \" << t << endl;\n\n     }\n\n     /*\n        This method prints out the sum of ratios of branch lengths before and after a division (skipping first k branches)\n      */\n      void get_treelen_ratios(vector<double>& ratios, vector<Cell>& cells, int skip = 3, int only_mut = 0, int use_grandparent = 0, int verbose  = 0){\n         // double sum1 = 0, sum2 = 0;\n         // int n1 = 0, n2 = 0;\n         // cout << \"\\nbranch length ratios:\";\n         for(unsigned int i = 0; i < cells.size() ; i++) {\n             Cell *cell = &cells[i];\n             if(cell->parent_ID <= skip) continue;\n\n             Cell* pcell = cell->get_parent(cells);\n             if(pcell->parent_ID <= skip) continue;\n\n             if(cell->daughters.size() <= 0) continue;\n\n\n             double branch_len1 = 0;\n             if(use_grandparent == 1){\n               Cell* ppcell = pcell->get_parent(cells);\n               branch_len1 = pcell->time_occur - ppcell->time_occur;\n               if(verbose > 1){\n                 cout << \"checking division time of grandparent\" << endl;\n                 cout << \"blen1 \" << ppcell->cell_ID << \"\\t\" << pcell->cell_ID << \"\\t\" << branch_len1 << endl;\n               }\n             }else{\n               branch_len1 = cell->time_occur - pcell->time_occur;\n               if(verbose > 1){\n                 cout << \"checking division time of parent\" << endl;\n                 cout << \"blen1 \" << pcell->cell_ID << \"\\t\" << cell->cell_ID << \"\\t\" << branch_len1 << endl;\n               }\n             }\n\n             Cell* d = get_cell_from_ID(cells, cell->daughters[0]);\n             double branch_len2 = d->time_occur - cell->time_occur;\n             double ratio = branch_len1 / branch_len2;\n             // cout << \"blen2 \" << cell->cell_ID << \"\\t\" << d->cell_ID << \"\\t\" << branch_len2 << endl;\n\n             if(only_mut == 1){   // only consider nodes with mutations, since a fitness cost is introduced only if a new mutation occurs\n               // each mutation in the cell has a time stamp\n               int has_new_mut = 0;\n               for(auto m : cell->mutations){\n                 if(m.time_occur == cell->time_occur){\n                   if(verbose > 1){\n                     cout << \"mu time for: \" << pcell->cell_ID << \"\\t\" << m.time_occur << \"\\t\" << pcell->time_occur << endl;\n                     cout << \"blen2 \" << cell->cell_ID << \"\\t\" << d->cell_ID << \"\\t\" << branch_len2 << endl;\n                   }\n                   has_new_mut = 1;\n                   break;\n                 }\n               }\n               if(has_new_mut > 0) ratios.push_back(ratio);\n             }else{\n               ratios.push_back(ratio);\n             }\n            // if(ratio > 1){\n            //     sum1 += ratio;\n            //     n1 += 1;\n            // }else{\n            //     sum2 += ratio;\n            //     n2 += 1;\n            // }\n            // cout << \"\\t\" << ratio;\n         }\n         // cout << endl;\n         // cout << sum1 << \"\\t\" << n1 << endl;\n         // cout << sum2 << \"\\t\" << n2 << endl;\n         // double avg1 = sum1 / n1;\n         // double avg2 = sum2 / n2;\n     }\n\n\n     /*\n        This method prints out unique branch lengths (skipping first k branches)\n      */\n     void get_treelen_vec(vector<double>& blens, vector<Cell>& cells, int skip = 3){\n         double sum = 0;\n         for(unsigned int i = 0; i < cells.size() ; i++) {\n             Cell cell = cells[i];\n             if(cell.parent_ID <= skip) continue;\n             // write the cell lineages in a file for visualization\n             Cell* pcell = cell.get_parent(cells);\n             double branch_len = cell.time_occur - pcell->time_occur;\n             blens.push_back(branch_len);\n         }\n     }\n\n\n     /*\n        This method prints out half the sum of branch lengths (skipping first k branches)\n      */\n     double get_treelen(vector<Cell>& cells, int skip = 3){\n         double sum = 0;\n         for(unsigned int i = 0; i < cells.size() ; i++) {\n                 Cell cell = cells[i];\n                 if(cell.parent_ID <= skip) continue;\n                 // if (i <= skip){\n                 //     continue;\n                 // }\n                 Cell* pcell = cell.get_parent(cells);\n                 double branch_len = cell.time_occur - pcell->time_occur;\n                 // if (i <= skip){\n                 //     cout << \"Skip branch \" << i << \"\\t\" << cell.parent_ID << \"\\t\" << cell.cell_ID << \"\\t\" << branch_len << endl;\n                 //     continue;\n                 // }\n                 sum += branch_len;\n\n         }\n         sum = sum / 2;\n         return sum;\n     }\n\n\n     /*\n        This method prints out half branch lengths after immediate de novo CNAs (skipping first k branches)\n      */\n     double get_elen(vector<Cell>& cells, int skip = 3){\n         double sum = 0.0;\n         // double nblen = 0.0;\n         for(unsigned int i = 0; i < cells.size() ; i++) {\n             Cell cell = cells[i];\n             if(cell.parent_ID <= skip) continue;\n             // if (i <= skip){\n             //     continue;\n             // }\n             Cell* pcell = cell.get_parent(cells);\n             Cell* gpcell = pcell->get_parent(cells);\n\n             // check if de novo CNAs occur in the parent cell\n             int nnmut = pcell->mutations.size() - gpcell->mutations.size();\n\n\n             if(nnmut > 0){ // cell will have fitness changes, reflected in the waiting to next division\n               // find daughter cells\n               double branch_len = cell.time_occur - pcell->time_occur;\n               // nblen++;\n               sum += branch_len;\n               // cout << nnmut << \" new mutations at cell \" << pcell->cell_ID << \" compared with parent \" << gpcell->cell_ID << \" with branch length \" << branch_len << endl;\n             }\n         }\n         // if(nblen > 0) sum = sum / nblen;\n         sum = sum / 2;\n\n         return sum;\n     }\n\n\n     /*\n        This method prints out the lineage of cells in a clone in the format of edge list\n      */\n     void write_tree(vector<Cell>& cells, string fname){\n         ofstream tout(fname);\n         tout.precision(9);\n\n         // string header = \"parent\\tchild\\tbranch_len\\n\";\n         // tout << header;\n\n         for(unsigned int i = 0; i < cells.size() ; i++) {\n                 Cell cell = cells[i];\n                 if(cell.parent_ID == 0) continue;\n\n                 // write the cell lineages in a file for visualization\n                 Cell* pcell = cell.get_parent(cells);\n                 double branch_len = cell.time_occur - pcell->time_occur;\n                 tout << cell.parent_ID << \"\\t\" << cell.cell_ID << \"\\t\" << branch_len << endl;\n         }\n         tout.close();\n     }\n\n\n     // Find the preorder of nodes in the genealogy tree\n     void get_nodes_preorder(vector<Cell>& cells, Cell* root, vector<Cell*>& nodes_preorder){\n         nodes_preorder.push_back(root);\n         for(int j=0; j < root->daughters.size();j++){\n             Cell* d = get_cell_from_ID(cells, root->daughters[j]);\n             get_nodes_preorder(cells, d, nodes_preorder);\n         }\n     }\n\n     /*\n        This method prints out the lineage of cells in a clone in the format of NEWICK\n      */\n     void write_newick(vector<Cell>& cells, string fname){\n         ofstream tout(fname);\n         int precision = 9;\n         tout.precision(precision);\n         string newick = \"\";\n         const boost::format tip_node_format(boost::str(boost::format(\"%%d:%%.%df\") % precision));\n         const boost::format internal_node_format(boost::str(boost::format(\")%%d:%%.%df\") % precision));\n         const boost::format root_node_format(boost::str(boost::format(\")%%d\")));\n         stack<Cell*> node_stack;\n         vector<Cell*> nodes_preorder;\n         Cell* root;\n\n         for(int i=0; i<cells.size(); ++i){\n           if(cells[i].parent_ID == 0){\n               root = &cells[i];\n               break;\n           }\n         }\n\n         // cout << \"Get nodes preorder\" << endl;\n         get_nodes_preorder(cells, root, nodes_preorder);\n         // for(int i = 0; i < nodes_preorder.size(); i++){\n         //     cout << \"\\t\" << nodes_preorder[i]->cell_ID;\n         // }\n         // cout << endl;\n\n         Cell* pcell;\n         double branch_len = 0;\n\n         // cout << \"Traverse nodes in preorder\" << endl;\n         // Traverse nodes in preorder\n         for (int i = 0; i<nodes_preorder.size(); i++)\n         {\n             Cell* nd = nodes_preorder[i];\n             // cout << nd->cell_ID << endl;\n             if (nd->daughters.size()>0) // internal nodes\n             {\n                 newick += \"(\";\n                 node_stack.push(nd);\n             }\n             else\n             {\n                 pcell = nd->get_parent(cells);\n                 // cout << nd->cell_ID << \"\\t\" << pcell->cell_ID << \"\\t\" << pcell->daughters[0] << \"\\t\" << pcell->daughters[1] << endl;\n                 // assert(pcell->daughters.size()>0);\n                 branch_len = nd->time_occur - pcell->time_occur;\n\n                 newick += boost::str(boost::format(tip_node_format) % (nd->cell_ID) % branch_len);\n\n                 if (nd->cell_ID == pcell->daughters[0])   //left child\n                 {\n                     newick += \",\";\n                 }\n                 else\n                 {\n                     Cell* popped = (node_stack.empty() ? 0 : node_stack.top());\n                     pcell = popped->get_parent(cells);\n                     while (popped && popped->parent_ID > 0 && popped->cell_ID == pcell->daughters[1]) // right sibling of the previous node\n                     {\n                         // cout << popped->cell_ID << \"\\t\" << pcell->cell_ID << \"\\t\" << pcell->daughters[0] << \"\\t\" << pcell->daughters[1] << endl;\n                         branch_len = popped->time_occur - pcell->time_occur;\n\n                         node_stack.pop();\n\n                         newick += boost::str(boost::format(internal_node_format) % (popped->cell_ID) % branch_len);\n                         popped = node_stack.top();\n                         pcell = popped->get_parent(cells);\n                     }\n\n                     //  cout << popped->cell_ID << \"\\t\" << pcell->cell_ID << \"\\t\" << pcell->daughters[0] << \"\\t\" << pcell->daughters[1] << endl;\n                     if (popped && popped->parent_ID > 0 && popped->cell_ID == pcell->daughters[0]) // left child, with another sibling\n                     {\n                         branch_len = popped->time_occur - pcell->time_occur;\n\n                         node_stack.pop();\n\n                         newick += boost::str(boost::format(internal_node_format) % (popped->cell_ID) % branch_len);\n                         newick += \",\";\n                     }\n\n                     if (node_stack.empty())\n                     {\n                         newick += \")\";\n                     }\n                 }\n             }\n             // cout << newick << endl;\n         }\n         newick +=  boost::str(boost::format(root_node_format) % (root->cell_ID));\n         newick += \";\";\n\n         tout << newick;\n         tout.close();\n     }\n\n\n    /*\n       This method prints out the details of cells in a clone\n     */\n    void print_lineage(vector<Cell>& cells, string outdir, string suffix, int verbose = 0){\n            string fname = outdir + \"all_cells_lineage\" + suffix + \".txt\";\n            ofstream out(fname);\n            out.precision(9);\n\n            fname= outdir + \"all_cells_cn\" + suffix + \".txt\";\n            ofstream fcn(fname);\n\n            fname= outdir + \"all_cells_mut\" + suffix + \".txt\";\n            ofstream fmut(fname);\n\n            int num_cell = cells.size();\n            if(verbose > 1) cout << \"There are \" << num_cell << \" cells in the history of tumor growth\" << endl;\n\n            // string header = \"id\\tparent_ID\\tflag\\tbirth_rate\\tdeath_rate\\tmutation_rate\\tploidy\\tnum_division\\ttime_occur\\n\";\n            string header = \"id\\tparent_ID\\tflag\\tnum_mut\\tclone_ID\\ttime_occur\\tbranch_len\\n\";\n            out << header;\n\n            for(unsigned int i = 0; i < num_cell; i++) {\n                    Cell cell = cells[i];\n                    if(cell.parent_ID == 0) continue;\n                    // if(cell.daughters.size()==0){\n                    //     cout << cell.cell_ID << \"\\t\" << cell.parent_ID << \"\\t\" << -1 << \"\\t\" << -1 << \"\\t\" << cell.flag << \"\\t\" << cell.birth_rate << \"\\t\" << cell.death_rate << \"\\t\" << cell.mutation_rate  << \"\\t\" << cell.ploidy  << \"\\t\" << cell.num_division << \"\\t\" << cell.time_occur << endl;\n                    // }else{\n                    //     cout << cell.cell_ID << \"\\t\" << cell.parent_ID << \"\\t\" << cell.daughters[0] << \"\\t\" << cell.daughters[1] << \"\\t\" << cell.flag << \"\\t\" << cell.birth_rate << \"\\t\" << cell.death_rate << \"\\t\" << cell.mutation_rate  << \"\\t\" << cell.ploidy  << \"\\t\" << cell.num_division << \"\\t\" << cell.time_occur << endl;\n                    // }\n                    int num_mut = cell.get_num_mut();\n                    // int num_mut = cell.mutations.size();\n\n                    // write the cell lineages in a file for visualization\n                    Cell* pcell = cell.get_parent(cells);\n                    double branch_len = cell.time_occur - pcell->time_occur;\n                    out << cell.cell_ID << \"\\t\" << cell.parent_ID << \"\\t\" << cell.flag << \"\\t\" << num_mut << \"\\t\" << cell.clone_ID  << \"\\t\" << cell.time_occur << \"\\t\" << branch_len << endl;\n\n                    cell.write_obs_cn(fcn, 1);\n\n                    if(verbose > 1) cout << \"\\t\" << num_mut << \" mutations in cell \" << cell.cell_ID << endl;\n                    for(unsigned int j = 0; j < num_mut; j++){\n                        Mutation mut = cell.mutations[j];\n                        fmut << cell.cell_ID << \"\\t\" << mut.mut_ID << \"\\t\" << mut.time_occur << \"\\t\" << mut.chr + 1 << \"\\t\" << mut.arm << \"\\t\" << mut.type << \"\\t\" << mut.reciprocal << endl;\n                    }\n            }\n            out.close();\n            fcn.close();\n            fmut.close();\n    }\n\n    /*\n       This method computes the allele frequency of each mutation\n     */\n    map<int, double> get_allele_freq(){\n            map<int, double> mut_freq;\n\n            int num_cell = this->curr_cells.size();\n            // Collect mutations\n            for(unsigned int i = 0; i < num_cell; i++) {\n                    Cell cell = this->curr_cells[i];\n                    for(auto mut : cell.mutations) {\n                            mut_freq[mut.mut_ID] += mut.number;\n                    }\n            }\n            // Compute frequency\n            double ploidy = get_avg_ploidy();\n            // cout << \"Average ploidy of the population: \" << ploidy << endl;\n            for(auto it : mut_freq) {\n                    double vaf = it.second/num_cell;\n                    vaf = vaf / ploidy;\n                    mut_freq[it.first] = vaf;\n            }\n            return mut_freq;\n    }\n\n\n    /*\n       This method computes the average ploidy of a tumor population.\n     */\n    double get_avg_ploidy(){\n            double ploidy = 0;\n            int num_cell = this->curr_cells.size();\n            // Collect mutations\n            for(unsigned int i = 0; i < num_cell; i++) {\n                    Cell cell = this->curr_cells[i];\n                    ploidy += cell.ploidy;\n            }\n            ploidy = ploidy / num_cell;\n            return ploidy;\n    }\n\n    /*\n       This method computes the number of unique mutations in each subclone.\n     */\n    map<int, int> get_subclone_nmut(){\n            map<int, set<double>> subclone_muts;\n            map<int, int> subclone_nmut;\n\n            int num_cell = this->curr_cells.size();\n\n            for(unsigned int i = 0; i < num_cell; i++) {\n                    Cell cell = this->curr_cells[i];\n                    for (auto mut : cell.mutations){\n                        subclone_muts[cell.clone_ID].insert(mut.mut_ID);\n                    }\n            }\n\n            for(auto muts : subclone_muts) {\n                    subclone_nmut[muts.first] = muts.second.size();\n            }\n\n            return subclone_nmut;\n    }\n\n    /*\n       This method computes the maximum number of cell division in each subclone.\n     */\n    map<int, int> get_subclone_ndiv(){\n            map<int, set<int>> subclone_divs;\n            map<int, int> subclone_ndiv;\n\n            int num_cell = this->curr_cells.size();\n\n            for(unsigned int i = 0; i < num_cell; i++) {\n                    Cell cell = this->curr_cells[i];\n                    subclone_divs[cell.clone_ID].insert(cell.num_division);\n            }\n\n            // cout << \"Number of unique divisions in subclones: \" << endl;\n            for(auto divs : subclone_divs) {\n                // for(auto num : divs.second){\n                //     cout << num << \"\\t\";\n                // }\n                // cout << endl;\n                // set<int>::iterator min = divs.second.begin();\n                set<int>::reverse_iterator max = divs.second.rbegin();\n                subclone_ndiv[divs.first] = *max;\n                // cout << divs.first << \"\\t\" << *min << \"\\t\" << *max << \"\\n\";\n            }\n            return subclone_ndiv;\n    }\n\n\n    /*\n       This method computes the average number of cell division in each subclone.\n     */\n    map<int, double> get_subclone_adiv(){\n            map<int, vector<int>> subclone_divs;\n            map<int, double> subclone_adiv;\n\n            int num_cell = this->curr_cells.size();\n\n            for(unsigned int i = 0; i < num_cell; i++) {\n                    Cell cell = this->curr_cells[i];\n                    // cout << cell.cell_ID << \"\\t\" << cell.clone_ID << \"\\t\" << cell.num_division << endl;\n                    subclone_divs[cell.clone_ID].push_back(cell.num_division);\n            }\n\n            // cout << \"Number of divisions in subclones: \" << endl;\n            for(auto divs : subclone_divs) {\n                int sum = 0;\n                for (auto num : divs.second)\n                    sum += num;\n                subclone_adiv[divs.first] = sum / (divs.second).size();\n                // cout << \"\\t\" << divs.first << \"\\t\"<< sum << \"\\t\" << (divs.second).size() << \"\\n\";\n            }\n\n            return subclone_adiv;\n    }\n\n\n    /*\n       This method computes the subclone frequencies of a tumor population.\n     */\n    map<int, double> get_subclone_freq(){\n            map<int, double> subclone_freq;\n            int num_cell = this->curr_cells.size();\n\n            for(unsigned int i = 0; i < num_cell; i++) {\n                    Cell cell = this->curr_cells[i];\n                    subclone_freq[cell.clone_ID] += 1;\n            }\n\n            for(auto freq : subclone_freq) {\n                    subclone_freq[freq.first] = freq.second / num_cell;\n            }\n\n            return subclone_freq;\n    }\n\n    // void initialize(double death_rate, double mutation_rate, int& mut_ID, int& nu, int num_clonal_mutation, int verbose);\n    // void initialize_with_cnv(double birth_rate, double death_rate, double mutation_rate, double arm_prob, double chr_prob, int& mut_ID, int& nu, int num_clonal_mutation, string file_cmut, int verbose);\n    //\n    // double get_subclone_fitness(double lambda, double freq, double tend, double t1);\n    // double get_subclone_freq_exp(double lambda, double fitness, double tend, double t1);\n    // double get_rmax();\n    // double get_avg_ploidy();\n    // map<int, double> get_allele_freq();\n    // map<int, double> get_subclone_freq();\n    // map<int, int> get_subclone_nmut();\n    // map<int, int> get_subclone_ndiv();\n    // map<int, double> get_subclone_adiv();\n    //\n    // void grow(int num_subclone, int num_clonal_mutation, vector<double> fitness, vector<double> time_occur, int Nend, double birth_rate, double death_rate, double mutation_rate, int verbose);\n    // void grow_with_cnv(int num_subclone, int num_clonal_mutation, vector<double> fitness, vector<double> time_occur, int Nend, double birth_rate, double death_rate, double mutation_rate, double arm_prob, double chr_prob, string file_cmut, int verbose);\n    //\n    //\n    // void print_lineage(vector<Cell> cells, string outdir, string suffix, int verbose);\n    // void print_summary(string outfile);\n\n    template <typename T> void print_map(map<int, T> m, string outfile){\n        ofstream out;\n        out.setf(ios::fixed);\n        out.setf(ios::showpoint);\n        out.precision(9);\n        out.open(outfile);\n\n        for(auto it : m) {\n                out << it.first << \"\\t\" << it.second << endl;\n        }\n\n        out.close();\n    }\n\n    /*\n       This method prints out the copy numbers of final cells in a clone\n     */\n    void print_obs_cn(vector<Cell> cells, string fname, int verbose = 0){\n            ofstream fcn(fname);\n\n            int num_cell = cells.size();\n            if(verbose > 1) cout << \"Printing copy numbers of \" << num_cell << \" cells\" << endl;\n\n            for(unsigned int i = 0; i < num_cell; i++) {\n                    Cell cell = cells[i];\n                    cell.write_obs_cn(fcn, 0);\n            }\n            fcn.close();\n    }\n\n    /*\n       This method read clonal mutations from file\n     */\n    void set_clonal_mut(string fname){\n        ifstream infile(fname.c_str());\n        if (infile.is_open()){\n          std::string line;\n          while(!getline(infile,line).eof()){\n            if(line.empty()) continue;\n\n            std::vector<std::string> split;\n            std::string buf;\n            stringstream ss(line);\n            while (ss >> buf) split.push_back(buf);\n            assert(split.size()==3);\n\n            int chr = atoi(split[0].c_str()) - 1;\n            int arm = atoi(split[1].c_str());\n            int cn = atoi(split[2].c_str());\n            // cout << \"read chr: \" << chr << \" arm: \" << arm << \" cn: \" << cn << endl;\n            pair<int, int> pos(chr, arm);\n            clonal_cn_profile[pos] = cn;\n          }\n      }\n    }\n\n    /*\n       This method summarize subclonal mutations in terms of frequencies of events\n     */\n     void write_prop(vector<Cell> cells, string fname){\n         // compute the frequencies of arm-level events by chromosome\n         map<int, double> parm_freq;\n         map<int, double> qarm_freq;\n         for(int i = 0; i < NUM_CHR; i++){\n             parm_freq[i] = 0.0;\n             qarm_freq[i] = 0.0;\n         }\n         int num_parm_cnv = 0;\n         int num_qarm_cnv = 0;\n\n         for(unsigned int i = 0; i < cells.size(); i++) {\n             Cell cell = cells[i];\n             cell.set_obs_cn();\n             // cout << \"cell \" << cell.cell_ID << endl;\n             for(auto cp : cell.obs_cn_profile){\n                 // cout << cp.first.first << \"\\t\" << cp.first.second << \"\\t\" << cp.second << endl;\n                 if(cp.first.second == 1 && cp.second != 0){\n                     num_parm_cnv += 1;\n                     parm_freq[cp.first.first] += 1;\n                 }\n                 if(cp.first.second == 2 && cp.second != 0){\n                     num_qarm_cnv += 1;\n                     qarm_freq[cp.first.first] += 1;\n                 }\n             }\n         }\n         // cout << \"There are \" << num_parm_cnv << \" parm-level events\" << endl;\n         if(num_parm_cnv > 0){\n             for(int i = 0; i < NUM_CHR; i++){\n                 parm_freq[i] = (double) parm_freq[i] / num_parm_cnv;\n                 // cout << \"\\tchr \" << i+1 << \" with arm-level freq \" << arm_freq[i] << endl;\n             }\n         }\n         if(num_qarm_cnv > 0){\n             for(int i = 0; i < NUM_CHR; i++){\n                 qarm_freq[i] = (double) qarm_freq[i] / num_qarm_cnv;\n                 // cout << \"\\tchr \" << i+1 << \" with arm-level freq \" << arm_freq[i] << endl;\n             }\n         }\n         // compute the frequencies of chr-level events by chromosome\n         map<int, double> chr_freq;\n         for(int i = 0; i < NUM_CHR; i++){\n             chr_freq[i] = 0.0;\n         }\n         int num_chr_cnv = 0;\n         for(unsigned int i = 0; i < cells.size(); i++) {\n             Cell cell = cells[i];\n             cell.set_obs_cn();\n             // cout << \"cell \" << cell.cell_ID << endl;\n             for(auto cp : cell.obs_cn_profile){\n                 // cout << cp.first.first << \"\\t\" << cp.first.second << \"\\t\" << cp.second << endl;\n                 if(cp.first.second == 0 && cp.second != 0){\n                     num_chr_cnv += 1;\n                     chr_freq[cp.first.first] += 1;\n                 }\n             }\n         }\n         // cout << \"There are \" << num_chr_cnv << \" chr-level events\" << endl;\n         if(num_chr_cnv > 0){\n             for(int i = 0; i < NUM_CHR; i++){\n                 chr_freq[i] = (double) chr_freq[i] / num_chr_cnv;\n                 // cout << \"\\tchr \" << i+1 << \" with chr-level freq \" << chr_freq[i] << endl;\n             }\n         }\n\n         ofstream fout(fname);\n         for(int i = 0; i < NUM_CHR; i++){\n             fout << chr_freq[i] << endl;\n         }\n         for(int i = 0; i < NUM_CHR; i++){\n             fout << parm_freq[i] << endl;\n         }\n         for(int i = 0; i < NUM_CHR; i++){\n             fout << qarm_freq[i] << endl;\n         }\n         fout.close();\n     }\n\n     // get unique CNVs\n     void set_uniq_cn(vector<Cell> cells){\n         for(int c = 0; c < cells.size(); c++){\n             cells[c].set_obs_cn();\n             map<pair<int, int>, int> obs_cns = cells[c].obs_cn_profile;\n             for (auto cp : obs_cns){\n                 tuple<int, int, int> cnvec(cp.first.first, cp.first.second, cp.second);\n                 uniq_cns.insert(cnvec);\n             }\n         }\n\n         // cout << \"There are \" << uniq_cns.size() << \" unique CNA events in the clone \" << endl;\n         // for(auto cv : uniq_cns){\n         //    cout << get<0>(cv) << \"\\t\"  << get<1>(cv) << \"\\t\"  << get<2>(cv) << endl;\n         // }\n     }\n\n     // print average of absolute relative changes\n     void write_avg_cn(vector<Cell> cells, string fname){\n         vector<float> avg_cn(NUM_CHR * 3, 0);\n         // int n = 0;\n\n         for(int c = 0; c < cells.size(); c++){\n             cells[c].set_cn_all();\n         }\n         for(int i = 0; i < cells.size(); i++){\n             // for(int j = i+1; j < cells.size(); j++){\n             //     n++;\n             //     // assert(cells[i].cn_all.size() == cells[j].cn_all.size());\n             //     for(int k = 0; k < cells[i].cn_all.size(); k++){\n             //         sum_cn[k] += cells[i].cn_all[k] + cells[j].cn_all[k];   // reciprocal events will be cancelled out\n             //     }\n             // }\n             for(int k = 0; k < cells[i].cn_all.size(); k++){\n                 avg_cn[k] += abs(cells[i].cn_all[k]);\n             }\n         }\n\n         // cout << \"There are \" << n << \" combinations of cells\" << endl;\n         for(int i = 0; i < avg_cn.size(); i++){\n             // avg_cn[i] = avg_cn[i] / n;\n             avg_cn[i] = avg_cn[i] / cells.size();\n         }\n\n         ofstream fout(fname);\n         for(int i = 0; i < avg_cn.size(); i++){\n             fout << avg_cn[i] << endl;\n         }\n         fout.close();\n     }\n\n     // print average of unique absolute relative changes\n     void write_avg_uniq_cn(vector<Cell> cells, string fname){\n         map<pair<int, int>, int> cp;\n         vector<float> avg_cn(NUM_CHR * 3, 0);\n\n         set_uniq_cn(cells);\n\n         for(int i = 0; i < NUM_CHR; i++){\n             for (int j = 0; j < 3; j++){\n                 pair<int, int> pos(i,j);\n                 cp[pos] = 0;\n                 avg_cn[i * 3 + j] = 0;\n             }\n         }\n\n         for(auto cv: uniq_cns){\n             pair<int, int> pos(get<0>(cv), get<1>(cv));\n             cp[pos] += abs(get<2>(cv));\n             avg_cn[get<0>(cv) * 3 + get<1>(cv)] += abs(get<2>(cv));\n         }\n\n         // cout << \"number of CNA changes at each position\" << endl;\n         // for(auto c : cp){\n         //     if(c.second!=0)\n         //        cout << c.first.first << \"\\t\"  << c.first.second << \"\\t\" << c.second << endl;\n         // }\n\n         for(int i = 0; i < avg_cn.size(); i++){\n             avg_cn[i] = avg_cn[i] / cells.size();\n         }\n\n         ofstream fout(fname);\n         for(int i = 0; i < avg_cn.size(); i++){\n             fout << avg_cn[i] << endl;\n         }\n         fout.close();\n     }\n\n     // print average of unique absolute relative changes by ignoring chromosome information\n     void write_aggregated_uniq_cn(vector<Cell> cells, string fname){\n         vector<float> avg_cn(2, 0);    // only count chr and arm level\n\n         set_uniq_cn(cells);\n\n         for (int j = 0; j < 2; j++){\n             avg_cn[j] = 0;\n         }\n\n         for(auto cv: uniq_cns){\n             if(get<1>(cv)==0){\n                 avg_cn[0] += abs(get<2>(cv));\n             }else{\n                 avg_cn[1] += abs(get<2>(cv));\n             }\n         }\n\n         // cout << \"There are \" << n << \" combinations of cells\" << endl;\n         for(int i = 0; i < avg_cn.size(); i++){\n             avg_cn[i] = avg_cn[i] / cells.size();\n         }\n\n         ofstream fout(fname);\n         for(int i = 0; i < avg_cn.size(); i++){\n             fout << avg_cn[i] << endl;\n         }\n         fout.close();\n     }\n\n\n     void get_avg_reciprocal_cn(vector<Cell> cells, vector<int>& avg_cn, bool adjust_bias=false){\n         map<pair<int, int>, int> cp;\n         // vector<int> avg_cn(2, 0);    // only count chr and arm level\n\n         set_uniq_cn(cells);\n\n         for(int i = 0; i < NUM_CHR; i++){\n             for (int j = 0; j < 3; j++){\n                 pair<int, int> pos(i,j);\n                 cp[pos] = 0;\n             }\n         }\n\n         for (int j = 0; j < 2; j++){\n             avg_cn[j] = 0;\n         }\n\n         for(auto cv: uniq_cns){\n             pair<int, int> pos(get<0>(cv), get<1>(cv));\n             cp[pos] += abs(get<2>(cv));\n         }\n\n         // sum of reciprocal events will have sum being even\n         // cout << \"number of absolute CNA changes at each position (adjusting for odd arm-level events)\" << endl;\n         for(auto cv: cp){\n             if(adjust_bias){\n                 if(cv.second % 2 !=0)  // probably caused by further arm-level events\n                 {\n                     // cout << cv.first.first + 1 << \"\\t\"  << cv.first.second << \"\\t\" << cv.second << endl;\n                     // arm- and chr- level have different bias\n                     if(cv.first.second==0){\n                         cv.second = cv.second + 1;\n                     }\n                     else{\n                        cv.second = cv.second - 1;\n                     }\n                     // cout << cv.first.first + 1 << \"\\t\"  << cv.first.second << \"\\tafter\" << cv.second << endl;\n                 }\n             }\n             // cout << cv.first.first + 1 << \"\\t\"  << cv.first.second << \"\\t\" << cv.second << endl;\n             if(cv.first.second==0){\n                 avg_cn[0] += cv.second;\n             }else{\n                 avg_cn[1] += cv.second;\n             }\n         }\n\n         // return avg_cn;\n     }\n\n\n     // print average of reciprocal CN changes by ignoring chromosome information\n     void write_avg_reciprocal_cn(vector<Cell> cells, string fname, bool adjust_bias=false){\n         vector<int> avg_cn(2, 0);\n         get_avg_reciprocal_cn(cells, avg_cn, adjust_bias);\n\n         ofstream fout(fname);\n         for(int i = 0; i < avg_cn.size(); i++){\n             fout << (double) avg_cn[i] / cells.size() << endl;\n         }\n         fout.close();\n     }\n\n     // print odd ratio of reciprocal CN changes by ignoring chromosome information\n     void write_relative_reciprocal_cn(vector<Cell> cells, string fname, bool adjust_bias=false){\n         map<pair<int, int>, int> cp;\n         vector<int> avg_cn(2, 0);    // only count chr and arm level\n\n         set_uniq_cn(cells);\n\n         for(int i = 0; i < NUM_CHR; i++){\n             for (int j = 0; j < 3; j++){\n                 pair<int, int> pos(i,j);\n                 cp[pos] = 0;\n             }\n         }\n\n         for (int j = 0; j < 2; j++){\n             avg_cn[j] = 0;\n         }\n\n         for(auto cv: uniq_cns){\n             pair<int, int> pos(get<0>(cv), get<1>(cv));\n             cp[pos] += abs(get<2>(cv));\n         }\n\n         // sum of reciprocal events will have sum being even\n         // cout << \"number of absolute CNA changes at each position (adjusting for odd arm-level events)\" << endl;\n         for(auto cv: cp){\n             if(adjust_bias){\n                 if(cv.second % 2 !=0)  // probably caused by further arm-level events\n                 {\n                     // cout << cv.first.first + 1 << \"\\t\"  << cv.first.second << \"\\t\" << cv.second << endl;\n                     // arm- and chr- level have different bias\n                     if(cv.first.second==0){\n                         cv.second = cv.second + 1;\n                     }\n                     else{\n                        cv.second = cv.second - 1;\n                     }\n                     // cout << cv.first.first + 1 << \"\\t\"  << cv.first.second << \"\\tafter\" << cv.second << endl;\n                 }\n             }\n             // cout << cv.first.first + 1 << \"\\t\"  << cv.first.second << \"\\t\" << cv.second << endl;\n             if(cv.first.second==0){\n                 avg_cn[0] += cv.second;\n             }else{\n                 avg_cn[1] += cv.second;\n             }\n         }\n\n         double odd = (double) avg_cn[0] / (avg_cn[0] + avg_cn[1]);\n         ofstream fout(fname);\n         // for(int i = 0; i < avg_cn.size(); i++){\n         //     fout << (double) avg_cn[i] / cells.size() << endl;\n         // }\n         fout << odd << endl;\n         fout.close();\n     }\n\n     //\n     void get_avg_blen(){\n\n     }\n\n     void write_summary_stats(vector<double>& sum_stats, string fname){\n         ofstream fout(fname);\n         fout.precision(9);\n         for(int i = 0; i < sum_stats.size(); i++){\n             fout << sum_stats[i] << endl;\n         }\n         fout.close();\n     }\n\n};\n\n#endif\n", "meta": {"hexsha": "47f47c32d55c57745555a3b6d8d6841664630604", "size": 91928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/cell.hpp", "max_stars_repo_name": "ucl-cssb/CIN_PDO", "max_stars_repo_head_hexsha": "57b06e5aa24797015fc08e25e1163f74b6459d8a", "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/cell.hpp", "max_issues_repo_name": "ucl-cssb/CIN_PDO", "max_issues_repo_head_hexsha": "57b06e5aa24797015fc08e25e1163f74b6459d8a", "max_issues_repo_licenses": ["MIT"], "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/cell.hpp", "max_forks_repo_name": "ucl-cssb/CIN_PDO", "max_forks_repo_head_hexsha": "57b06e5aa24797015fc08e25e1163f74b6459d8a", "max_forks_repo_licenses": ["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.4612676056, "max_line_length": 371, "alphanum_fraction": 0.4751327126, "num_tokens": 21732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1944978762974309}}
{"text": "/*\n * Copyright 2020 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 \"phy.h\"\n#include \"../../lib/phy/synchronization/synchronization.h\"\n#include \"../../lib/phy/libphy/libphy.h\"\n#include \"../../lib/variables/common_variables/common_variables.h\"\n#include \"../../lib/utils/sequence_generator/sequence_generator.h\"\n#include \"../../lib/phy/transport_channel/transport_channel.h\"\n#include <iostream>\n#include <vector>\n#include <fftw3.h>\n#include <fstream>\n#include <boost/log/core.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/log/expressions.hpp>\n#include <boost/log/utility/setup/file.hpp>\n#include <boost/log/utility/setup/common_attributes.hpp>\n#include \"../../lib/asn1c/nr_rrc/BCCH-DL-SCH-Message.h\"\n#include \"../../lib/variables/common_structures/common_structures.h\"\n#include \"../../lib/phy/physical_channel/physical_channel.h\"\n#include \"../../lib/utils/common_utils/common_utils.h\"\n#include \"../../lib/asn1c/nr_rrc/BCCH-DL-SCH-Message.h\"\n\nusing namespace std;\n\nphy::phy(rf *rf_dev, double ssb_period, int fft_size, int scs, free5GRAN::band band_obj) {\n    /**\n     * \\fn phy\n     * \\param[in] rf_dev: RF device. (Only USRP B210 is currently supported)\n     * \\param[in] ssb_period: SSB periodicity. Default value is 0.02 (20 ms)\n     * \\param[in] fft_size: FFT/iFFT size. Represents the total number of os subcarriers to be decoded\n     * \\param[in] scs: Subcarrier spacing\n     * \\param[in] band_obj: Band object for getting Lmax value\n    */\n    this->rf_device = rf_dev;\n    this->ssb_period = ssb_period;\n    this->fft_size = fft_size;\n    this->scs = scs;\n    this->band_object = band_obj;\n    l_max = band_obj.l_max;\n    this->is_extended_cp = 0;\n}\n\nint phy::cell_synchronization(float &received_power) {\n    /**\n     * \\fn cell_synchronization\n     * \\brief Perform time synchronization\n     * \\details\n     * - PSS cross-correlation to retrieve N_ID_2\n     * - SSS correlation to retrieve N_ID_1\n     * - PCI computation based on N_ID_1 and N_ID_2\n     *\n     * \\param[in] received_power: PSS received power. Used for power ramping.\n    */\n    BOOST_LOG_TRIVIAL(trace) << \"PSS synchronization\";\n\n    int n_id_2,synchronisation_index;\n    float peak_value;\n    double time_first_sample;\n    received_power = 0;\n\n    size_t num_samples = 2 * ssb_period * rf_device->getSampleRate();\n\n    // Create buffer\n    vector<complex<float>> buff_2_ssb_periods(num_samples);\n    buff.clear();\n    buff.resize(num_samples / 2);\n\n    complex<float> j(0, 1);\n    // Get samples from RF layer and put them in buff variable\n    time_first_pss = chrono::high_resolution_clock::now();\n    try {\n        rf_device->get_samples(&buff_2_ssb_periods, time_first_sample);\n    }catch (const exception& e) {\n        return 1;\n    }\n    int num_symbols_per_subframe_pbch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * scs/15e3;\n    int cp_lengths_pbch[num_symbols_per_subframe_pbch];\n    int cum_sum_pbch[num_symbols_per_subframe_pbch];\n\n    free5GRAN::phy::signal_processing::compute_cp_lengths((int) scs/1e3, fft_size, 0, num_symbols_per_subframe_pbch, cp_lengths_pbch, cum_sum_pbch);\n    /*\n     * Take second symbol CP as common CP as SSB is never transmitted at long CP symbols (long CP are transmitted every 0.5ms)\n     */\n    common_cp_length = cp_lengths_pbch[1];\n    /*\n     * Extract first half of buffer (= 1 SSB period)\n     */\n    for (int i = 0; i < num_samples / 2; i ++){\n        buff[i] = buff_2_ssb_periods[i];\n    }\n\n    /*\n     * Get PSS correlation result\n     */\n    free5GRAN::phy::synchronization::search_pss(n_id_2,synchronisation_index,peak_value, common_cp_length, buff, fft_size);\n    BOOST_LOG_TRIVIAL(trace) << \"Peak value: \"+ to_string(peak_value/common_cp_length);\n    /*\n     * Computing symbol length and first sample index of PSS in buff\n     */\n    int symbol_duration = fft_size + common_cp_length;\n    int pss_start_index = synchronisation_index - symbol_duration + 1;\n    int sss_init_index = pss_start_index + 2 * symbol_duration + common_cp_length; // = (synchronisation_index - symbol_duration + 1) + 2 * symbol_duration;\n    /*\n     * If highest correlation peak is not fully in buffer, cell is not found\n     */\n    if (pss_start_index < 0){\n        return 1;\n    }\n\n    index_first_pss = pss_start_index;\n\n    vector<complex<float>> sss_signal(fft_size);\n    /*\n     * Extracting the SSS signal based on sss_init_index and cp_length\n     */\n    for (int i = 0; i < fft_size; i++){\n        sss_signal[i] = buff[i + sss_init_index];\n    }\n    /*\n     * Computing received power\n     */\n    for (int i = 0; i < 4 * symbol_duration; i ++){\n        received_power += pow(abs(buff[pss_start_index + i]),2);\n    }\n    received_power /= 4 * symbol_duration;\n    received_power = 10 * log10(received_power);\n    int n_id_1;\n    float peak_value_sss;\n\n    /*\n     * Get SSS correlation result\n     */\n    BOOST_LOG_TRIVIAL(trace) << \"SSS synchronization\";\n    free5GRAN::phy::synchronization::get_sss(n_id_1, peak_value_sss, sss_signal, fft_size, n_id_2);\n    BOOST_LOG_TRIVIAL(trace) << \"Peak value: \"+ to_string(peak_value_sss);\n    pci = 3 * n_id_1 + n_id_2;\n    BOOST_LOG_TRIVIAL(trace) << \"PCI : \"+ to_string(pci);\n\n\n    /*\n     * Retreive first SSB symbol of second SSB period\n     */\n    vector<complex<float>> second_pss(fft_size + common_cp_length), second_sss(fft_size);\n    int second_pss_index = pss_start_index + num_samples / 2;\n    int n_id_1_2, n_id_2_2, sync_index_pss_2;\n    float peak_value_pss_2;\n    for (int i = 0; i < fft_size + common_cp_length; i++){\n        second_pss[i] = buff_2_ssb_periods[i + second_pss_index];\n    }\n    /*\n     * Retrieve N ID 2 value from second SSB\n     */\n    free5GRAN::phy::synchronization::search_pss(n_id_2_2,sync_index_pss_2,peak_value_pss_2, common_cp_length, second_pss, fft_size);\n\n    /*\n     * Extract SSS symbol from second SSB\n     */\n    for (int i = 0; i < fft_size; i++){\n        second_sss[i] = buff_2_ssb_periods[i + second_pss_index + 2 * symbol_duration + common_cp_length];\n    }\n\n    free5GRAN::phy::synchronization::get_sss(n_id_1_2, peak_value_sss, second_sss, fft_size, n_id_2_2);\n\n    if (3 * n_id_1_2 + n_id_2_2 == pci){\n        return 0;\n    }else {\n        return 1;\n    }\n}\n\nint phy::extract_pbch() {\n    /**\n     * \\fn extract_pbch\n     * \\brief Time resynchronization, frequency synchronization, PBCH extraction and decoding.\n     * \\details\n     * - Getting 3ms signal from RF device\n     * - PSS cross-correlation to retrieve N_ID_2\n     * - SSS correlation to retrieve N_ID_1\n     * - PCI computation based on N_ID_1 and N_ID_2\n     * - Function ends if recomputed PCI differs from to initially computed one\n     * - Fine frequency synchronization by correlating cyclic prefixes and corresponding symbol part\n     * - Signal extraction and FFT\n     * - Resource element de-mapper\n     * - Channel estimation based on different values of i_ssb\n     * - Channel equalization based on best SNR value\n     * - PBCH decoding\n     * - BCH decoding\n     * - MIB parsing\n    */\n    BOOST_LOG_TRIVIAL(trace) << \"Extracting PBCH\";\n    // Get at least 30ms of signal (=3 frames, at least 2 complete ones)\n    size_t num_samples = max(0.03, ssb_period) * rf_device->getSampleRate();\n    buff.clear();\n    buff.resize(num_samples);\n\n    double second_frame_time;\n    // Getting samples\n    auto now = chrono::high_resolution_clock::now();\n    try {\n        rf_device->get_samples(&buff, second_frame_time);\n    }catch (const exception& e) {\n        return 1;\n    }\n\n    /*\n     * SYNCHRONIZING IN THE NEW RECEIVED FRAME\n     * Computing approximate PSS index inside the received buffer using the time reference of the first PSS index SSB initial search\n     */\n    auto time_window = chrono::duration_cast<chrono::microseconds>(now - time_first_pss);\n    int offset_to_ssb_period = (int)(time_window.count() - index_first_pss / (128*scs *1e-6)) % ((int) (ssb_period * 1e6));\n    int index_second_pss = (ssb_period * 1e6 - offset_to_ssb_period) * rf_device->getSampleRate() * 1e-6;\n\n    ofstream data;\n    data.open(\"data.txt\");\n    for (int i = 0; i < num_samples; i ++){\n        data << buff[i];\n        data << \"\\n\";\n    }\n    data.close();\n\n    /*\n     * Compute PBCH CP length\n     */\n    int num_symbols_per_subframe_pbch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * scs/15e3;\n    int cp_lengths_pbch[num_symbols_per_subframe_pbch];\n    int cum_sum_pbch[num_symbols_per_subframe_pbch];\n\n    free5GRAN::phy::signal_processing::compute_cp_lengths((int) scs/1e3, fft_size, 0, num_symbols_per_subframe_pbch, cp_lengths_pbch, cum_sum_pbch);\n    common_cp_length = cp_lengths_pbch[1];\n    int symbol_duration = fft_size + common_cp_length;\n\n    vector<complex<float>> pss_signal(48 * symbol_duration);\n\n    int begin_offset, end_offset;\n    if (pss_signal.size()/2 <= index_second_pss && pss_signal.size()/2  <= num_samples - index_second_pss){\n        begin_offset = pss_signal.size()/2;\n        end_offset = pss_signal.size()/2;\n    } else if (pss_signal.size()/2 > index_second_pss){\n        begin_offset = index_second_pss;\n        end_offset = pss_signal.size() - index_second_pss;\n    } else if (pss_signal.size()/2  > num_samples - index_second_pss) {\n        end_offset = num_samples - index_second_pss;\n        begin_offset = pss_signal.size() - (num_samples - index_second_pss);\n    }\n\n    // Extracting the signal around the PSS approximation\n    int count = 0;\n    for (int i = -begin_offset; i < end_offset; i ++){\n        pss_signal[count] = buff[(int) index_second_pss + i];\n        count ++;\n    }\n\n    int synchronisation_index;\n    float peak_value;\n    double time_first_sample;\n\n    // Find the PSS and its index\n    free5GRAN::phy::synchronization::search_pss(this->n_id_2,synchronisation_index,peak_value, common_cp_length, pss_signal,fft_size);\n\n    vector<complex<float>> sss_signal(fft_size);\n\n    int pss_start_index = synchronisation_index - symbol_duration + 1;\n    int buffer_pss_index = pss_start_index + index_second_pss - begin_offset;\n    index_first_pss = buffer_pss_index;\n    int sss_init_index = buffer_pss_index + 2 * symbol_duration + common_cp_length;\n\n    /*\n     * Extracting the SSS signal based on sss_init_index and common_cp_length\n     */\n    for (int i = 0; i < fft_size; i++){\n        sss_signal[i] = buff[i + sss_init_index];\n    }\n\n    float peak_value_sss;\n    /*\n     * Get SSS correlation result\n     */\n    free5GRAN::phy::synchronization::get_sss(this->n_id_1, peak_value_sss, sss_signal,fft_size,this->n_id_2);\n    if (pci == 3 * n_id_1 + n_id_2){\n        BOOST_LOG_TRIVIAL(trace) << \"PCI confirmed\";\n        cell_confirmed = true;\n    }else{\n        BOOST_LOG_TRIVIAL(trace) << \"PCI not confirmed\";\n        cell_confirmed = false;\n        return 1;\n    }\n    /*\n     * WE ARE NOW SYNCHONIZED IN OUR NEW FRAME\n     * Trying to extract DMRS AND PBCH\n     */\n\n    vector<complex<float>> ssb_signal(4 * symbol_duration), new_ssb_signal(4 * symbol_duration);\n\n    // Extract SSB signal\n    for (int i = 0; i < free5GRAN::NUM_SYMBOLS_SSB * symbol_duration; i ++){\n        ssb_signal[i] = buff[i + buffer_pss_index];\n    }\n\n    /*\n     * Fine frequency correlation\n     * Getting phase offset between CP and corresponding part of the OFDM symbol for each of the 4 symbols.\n     * phase_offset is the mean phase offset\n     */\n    free5GRAN::phy::signal_processing::compute_fine_frequency_offset(ssb_signal, symbol_duration, fft_size, common_cp_length, scs, freq_offset, free5GRAN::NUM_SYMBOLS_SSB);\n\n    // Correcting signal based on frequency offset\n    free5GRAN::phy::signal_processing::transpose_signal(&buff, freq_offset, rf_device->getSampleRate(), buff.size());\n\n    vector<complex<float>> pbch_modulation_symbols(free5GRAN::SIZE_SSB_PBCH_SYMBOLS), final_pbch_modulation_symbols(free5GRAN::SIZE_SSB_PBCH_SYMBOLS);\n\n    /*\n     * Extracting DMRS AND PBCH modulation symbols\n     * ref is the reference grid for resource element demapper\n     */\n    vector<complex<float>> temp_mod_symbols, temp_mod_symbols2,temp_mod_symbols_dmrs;\n\n    auto *pbch_symbols = new complex<float>[free5GRAN::SIZE_SSB_PBCH_SYMBOLS];\n    auto *dmrs_symbols = new complex<float>[free5GRAN::SIZE_SSB_DMRS_SYMBOLS];\n    /*\n     * ref[0] -> indexes of PBCH resource elements\n     * ref[1] -> indexes of DMRS resource elements\n     */\n    int ** dmrs_indexes, ** pbch_indexes, ***ref;\n    ref = new int **[2];\n    ref[0] = new int *[free5GRAN::NUM_SYMBOL_PBCH_SSB];\n    ref[1] = new int *[free5GRAN::NUM_SYMBOL_PBCH_SSB];\n    dmrs_indexes = new int *[2];\n    dmrs_indexes[0] = new int[free5GRAN::SIZE_SSB_DMRS_SYMBOLS];\n    dmrs_indexes[1] = new int[free5GRAN::SIZE_SSB_DMRS_SYMBOLS];\n    pbch_indexes = new int *[2];\n    pbch_indexes[0] = new int[free5GRAN::SIZE_SSB_PBCH_SYMBOLS];\n    pbch_indexes[1] = new int[free5GRAN::SIZE_SSB_PBCH_SYMBOLS];\n\n\n\n    auto **ssb_symbols = new complex<float> *[free5GRAN::NUM_SYMBOLS_SSB - 1];\n\n    int cum_sum_fft[free5GRAN::NUM_SYMBOLS_SSB];\n    for (int symbol = 0; symbol < free5GRAN::NUM_SYMBOLS_SSB; symbol ++){\n        if (symbol < free5GRAN::NUM_SYMBOLS_SSB - 1){\n            ssb_symbols[symbol] = new complex<float>[free5GRAN::NUM_SC_SSB];\n        }\n        cum_sum_fft[symbol] = symbol * symbol_duration;\n    }\n    /*\n     * Recover RE grid from time domain signal\n     */\n    free5GRAN::phy::signal_processing::fft(ssb_signal, ssb_symbols,fft_size,cp_lengths_pbch,&cum_sum_fft[0],free5GRAN::NUM_SYMBOLS_SSB - 1,free5GRAN::NUM_SC_SSB,1,0);\n\n    for (int symbol = 1; symbol < free5GRAN::NUM_SYMBOLS_SSB; symbol ++) {\n        ref[0][symbol - 1] = new int[free5GRAN::NUM_SC_SSB];\n        ref[1][symbol - 1] = new int[free5GRAN::NUM_SC_SSB];\n    }\n    free5GRAN::phy::physical_channel::compute_pbch_indexes(ref, pci);\n    /*\n     * Channel demapping using computed ref grid\n     */\n    free5GRAN::phy::signal_processing::channel_demapper(ssb_symbols, ref, new int[2]{free5GRAN::SIZE_SSB_PBCH_SYMBOLS,free5GRAN::SIZE_SSB_DMRS_SYMBOLS}, new complex<float>*[2] {pbch_symbols,dmrs_symbols}, new int **[2] {pbch_indexes,dmrs_indexes}, 2, free5GRAN::NUM_SYMBOL_PBCH_SSB, free5GRAN::NUM_SC_SSB);\n\n    /*\n     * Channel estimation and equalization\n     * Creating coefficients arrays\n     */\n    complex<float> **coefficients[free5GRAN::MAX_I_BAR_SSB];\n    for (int p = 0; p < free5GRAN::MAX_I_BAR_SSB; p ++){\n        coefficients[p] = new complex<float> * [free5GRAN::NUM_SYMBOL_PBCH_SSB];\n        for (int i = 0 ; i < free5GRAN::NUM_SYMBOL_PBCH_SSB; i ++){\n            coefficients[p][i] = new complex<float> [free5GRAN::NUM_SC_SSB];\n        }\n    }\n\n    complex<float> * dmrs_sequence;\n    float snr[free5GRAN::MAX_I_BAR_SSB];\n\n    /*\n     * For each possible iBarSSB value, estimate the corresponding transport_channel\n     */\n    for (int i = 0; i < free5GRAN::MAX_I_BAR_SSB; i ++){\n        dmrs_sequence = new complex<float>[free5GRAN::SIZE_SSB_DMRS_SYMBOLS];\n        free5GRAN::utils::sequence_generator::generate_pbch_dmrs_sequence(pci,i,dmrs_sequence);\n        free5GRAN::phy::signal_processing::channelEstimation(dmrs_symbols, dmrs_sequence, dmrs_indexes,coefficients[i], snr[i], free5GRAN::NUM_SC_SSB, free5GRAN::NUM_SYMBOL_PBCH_SSB , free5GRAN::SIZE_SSB_DMRS_SYMBOLS);\n    }\n    /*\n     * Choose the iBarSSB value that maximizes the SNR\n     */\n    max_snr = snr[0];\n    int i_b_ssb = 0;\n    for (int i = 1; i < free5GRAN::MAX_I_BAR_SSB ; i ++){\n        if (snr[i] > max_snr){\n            max_snr = snr[i];\n            i_b_ssb = i;\n        }\n    }\n\n    // Equalize transport_channel\n    for (int i = 0; i < free5GRAN::SIZE_SSB_PBCH_SYMBOLS; i ++){\n        final_pbch_modulation_symbols[i] = (pbch_symbols[i]) * conj(coefficients[i_b_ssb][pbch_indexes[0][i]][pbch_indexes[1][i]]) / (float) pow(abs(coefficients[i_b_ssb][pbch_indexes[0][i]][pbch_indexes[1][i]]),2);\n    }\n\n    this->i_b_ssb = i_b_ssb;\n    if (l_max == 4){\n        this-> i_ssb = i_b_ssb % 4;\n    }else {\n        this-> i_ssb = i_b_ssb;\n    }\n    this->pci = pci;\n\n    /*\n     * Physical and transport channel decoding\n     * MIB parsing\n     */\n    int bch_bits[free5GRAN::SIZE_SSB_PBCH_SYMBOLS * 2];\n    free5GRAN::phy::physical_channel::decode_pbch(final_pbch_modulation_symbols, i_ssb, pci, bch_bits);\n    mib_bits = new int[free5GRAN::BCH_PAYLOAD_SIZE];\n    free5GRAN::phy::transport_channel::decode_bch(bch_bits, crc_validated, mib_bits, pci);\n    free5GRAN::utils::common_utils::parse_mib(mib_bits, mib_object);\n    return 0;\n}\n\nphy::phy() {\n\n}\n\nvoid phy::print_cell_info() {\n    /**\n     * \\fn print_cell_info\n     * \\brief Print cells global informations and MIB.\n    */\n    cout << \"\\n\";\n    cout << \"###### RADIO\" << endl;\n    cout << \"# SNR: \" + to_string(max_snr) + \" db\" << endl;\n    cout << \"# Frequency offset: \" + to_string(freq_offset) + \" Hz\" << endl;\n    cout << \"\\n\";\n    cout << \"###### CELL\" << endl;\n    cout << \"## PCI: \" + to_string(pci) + ((cell_confirmed) ? \" (confirmed)\" :  \" (not confirmed)\") << endl;\n    cout << \"## CP: \";\n    cout << ((is_extended_cp == 0 ) ? \"Normal\" :  \"Extended\") << endl;\n    cout << \"## I_B_SSB: \" + to_string(i_b_ssb) << endl;\n    cout << \"## I_SSB: \" + to_string(i_ssb) << endl;\n    cout << \"\\n\";\n    cout << \"###### MIB\" << endl;\n    cout << \"## Frame number: \" + to_string(mib_object.sfn) << endl;\n    cout << \"## PDCCH configuration: \" + to_string(mib_object.pdcch_config) << endl;\n    cout << \"## Subcarrier spacing common: \" + to_string(mib_object.scs) << endl;\n    cout << \"## Cell barred: \" + to_string(mib_object.cell_barred) << endl;\n    cout << \"## DMRS type A position : \" + to_string(mib_object.dmrs_type_a_position) << endl;\n    cout << \"## k SSB: \" + to_string(mib_object.k_ssb) << endl;\n    cout << \"## Intra freq reselection: \" + to_string(mib_object.intra_freq_reselection) << endl;\n    cout << \"## CRC \";\n    cout << ((crc_validated) ? \"validated\" :  \"not validated\") << endl;\n    cout << \"\\n\";\n    cout << \"#######################################################################\" << endl;\n    cout << \"\\n\";\n}\n\nvoid phy::reconfigure(int fft_size) {\n    this->fft_size = fft_size;\n}\n\nvoid phy::search_pdcch(bool &dci_found) {\n    /**\n     * \\fn search_pdcch\n     * \\brief PDCCH config extraction, PDCCH blind search and DCI decoding\n     * \\standard TS 38.213 13\n     * \\details\n     * - Read PDCCH config from MIB\n     * - Detect frame beginning\n     * - Select frame containing PDCCH and PDSCH based of SFN\n     * - Frequency calibration to retrieve center on CORESET0\n     * - Compute CCE to REG mapping\n     * - Blind search DCI decoding over different candidates:\n     *  -# Select a candidate\n     *  -# Perform resource element de-mapping and FFT\n     *  -# Channel estimation & equalization\n     *  -# PDCCH decoding\n     *  -# DCI decoding\n     *  -# If CRC is validated, candidate is selected and function ends\n     *  -# Otherwise, function continues with another candidates\n     *\n     * \\param[out] dci_found: returns true if blind decode succeeds.\n    */\n\n    /*\n     * If SSB offset is greater than 23, PDCCH is not present in the current BWP\n     */\n    if(mib_object.k_ssb > 23){\n        dci_found = false;\n        return;\n    }\n    mu = log2(mib_object.scs/15);\n    int symbol_in_frame = band_object.ssb_symbols[this->i_ssb];\n    frame_size = 0.01 * rf_device->getSampleRate();\n    num_slots_per_frame = 10 * mib_object.scs/15;\n\n\n    /*\n     * Computing CP lengths of SSB/PBCH and recovering SSB position in frame\n     */\n    int num_symbols_per_subframe_pbch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * scs/15e3;\n    int cp_lengths_pbch[num_symbols_per_subframe_pbch];\n    int cum_sum_pbch[num_symbols_per_subframe_pbch];\n\n    free5GRAN::phy::signal_processing::compute_cp_lengths((int) scs/1e3, fft_size, is_extended_cp, num_symbols_per_subframe_pbch, &cp_lengths_pbch[0], &cum_sum_pbch[0]);\n\n    int num_samples_before_pss = (symbol_in_frame / free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP) * (15e3/scs * frame_size / 10.0) + cum_sum_pbch[symbol_in_frame % free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP];\n    int num_samples_after_pss = frame_size - num_samples_before_pss;\n\n    /*\n     * Computing new FFT size, based on MIB common SCS\n     */\n    fft_size = (int) (rf_device->getSampleRate() / (1e3 * mib_object.scs));\n\n    BOOST_LOG_TRIVIAL(trace) << \"###### PDCCH Search & decode\";\n    BOOST_LOG_TRIVIAL(trace) << \"## INDEX_1: \" + to_string(mib_object.pdcch_config/16);\n    BOOST_LOG_TRIVIAL(trace) << \"## INDEX_2: \" + to_string(mib_object.pdcch_config%16);\n    BOOST_LOG_TRIVIAL(trace) << \"## SYMBOL IN FRAME: \" + to_string(symbol_in_frame);\n    BOOST_LOG_TRIVIAL(trace) << \"## FRAME SIZE: \" + to_string(frame_size);\n    BOOST_LOG_TRIVIAL(trace) << \"## INDEX PSS: \" + to_string(index_first_pss);\n    BOOST_LOG_TRIVIAL(trace) << \"## SLOTS PER FRAME: \" + to_string(num_slots_per_frame);\n    BOOST_LOG_TRIVIAL(trace) << \"## SAMPLES AFTER PSS: \" + to_string(num_samples_after_pss);\n    BOOST_LOG_TRIVIAL(trace) << \"## BUFFER SIZE: \" + to_string(buff.size());\n    BOOST_LOG_TRIVIAL(trace) << \"## FFT SIZE: \" + to_string(fft_size);\n\n    /*\n     * Getting two candidate frames in received signal.\n     * frame_indexes are the beginning and ending indexes of the two candidate frames\n     * frame_numbers stores SFN for each candidate frame\n     */\n    int frame_indexes[2][2];\n    int frame_numbers[2];\n    if (num_samples_before_pss < index_first_pss) {\n        if (num_samples_before_pss + 2 * frame_size < index_first_pss){\n            frame_indexes[0][0] = index_first_pss - num_samples_before_pss - 2 * frame_size;\n            frame_indexes[0][1] = index_first_pss - num_samples_before_pss - frame_size - 1;\n            frame_indexes[1][0] = index_first_pss - num_samples_before_pss - frame_size;\n            frame_indexes[1][1] = index_first_pss - num_samples_before_pss - 1;\n            frame_numbers[0] = mib_object.sfn - 2;\n            frame_numbers[1] = mib_object.sfn - 1;\n        }\n        else if (num_samples_before_pss + frame_size < index_first_pss){\n            frame_indexes[0][0] = index_first_pss - num_samples_before_pss - frame_size;\n            frame_indexes[0][1] = index_first_pss - num_samples_before_pss - 1;\n            frame_indexes[1][0] = index_first_pss - num_samples_before_pss;\n            frame_indexes[1][1] = index_first_pss - num_samples_before_pss + frame_size - 1;\n            frame_numbers[0] = mib_object.sfn - 1;\n            frame_numbers[1] = mib_object.sfn;\n        }\n        else {\n            frame_indexes[0][0] = index_first_pss - num_samples_before_pss;\n            frame_indexes[0][1] = index_first_pss - num_samples_before_pss + frame_size - 1;\n            frame_indexes[1][0] = index_first_pss - num_samples_before_pss + frame_size;\n            frame_indexes[1][1] = index_first_pss - num_samples_before_pss + 2 * frame_size - 1;\n            frame_numbers[0] = mib_object.sfn;\n            frame_numbers[1] = mib_object.sfn + 1;\n        }\n    }else {\n        frame_indexes[0][0] = index_first_pss - num_samples_before_pss + frame_size;\n        frame_indexes[0][1] = index_first_pss - num_samples_before_pss + 2 * frame_size - 1;\n        frame_indexes[1][0] = index_first_pss - num_samples_before_pss + 2 * frame_size;\n        frame_indexes[1][1] = index_first_pss - num_samples_before_pss + 3 * frame_size - 1;\n        frame_numbers[0] = mib_object.sfn + 1;\n        frame_numbers[1] = mib_object.sfn + 2;\n    }\n\n    BOOST_LOG_TRIVIAL(trace) << \"## FRAME 1 FROM: \" + to_string(1e3 * frame_indexes[0][0]/rf_device->getSampleRate()) + \" TO: \" + to_string(1e3 * frame_indexes[0][1]/rf_device->getSampleRate()) + \" ms\";\n    BOOST_LOG_TRIVIAL(trace) << \"## FRAME 2 FROM: \" + to_string(1e3 * frame_indexes[1][0]/rf_device->getSampleRate()) + \" TO: \" + to_string(1e3 * frame_indexes[1][1]/rf_device->getSampleRate()) + \" ms\";\n\n    /*\n     * Computing PDCCH Search Space information\n     */\n    pdcch_ss_mon_occ = free5GRAN::phy::signal_processing::compute_pdcch_t0_ss_monitoring_occasions(mib_object.pdcch_config, scs, mib_object.scs * 1e3, i_ssb);\n    pdcch_ss_mon_occ.n0 = (int)(pdcch_ss_mon_occ.O * pow(2, mu) + floor(i_ssb * pdcch_ss_mon_occ.M)) % num_slots_per_frame;\n    pdcch_ss_mon_occ.sfn_parity = (int)((pdcch_ss_mon_occ.O * pow(2, mu) + floor(i_ssb * pdcch_ss_mon_occ.M)) / num_slots_per_frame) % 2;\n\n    BOOST_LOG_TRIVIAL(trace) << \"## n0: \" + to_string(pdcch_ss_mon_occ.n0) ;\n    BOOST_LOG_TRIVIAL(trace) << \"## ODD/EVEN ?: \" + to_string(pdcch_ss_mon_occ.sfn_parity);\n\n    /*\n     * Getting candidate frame which satisfies Search Space SFN parity\n     */\n    int frame;\n    if (frame_numbers[0] % 2 == pdcch_ss_mon_occ.sfn_parity){\n        frame = 0;\n    }else {\n        frame = 1;\n    }\n\n    BOOST_LOG_TRIVIAL(trace) << \"## FRAME: \" + to_string(frame);\n\n    /*\n     * Normalizing signal\n     */\n    complex<float> rms = 0;\n    frame_data.resize(frame_size);\n    for (int i = 0; i < frame_size; i ++){\n        frame_data[i] = buff[i + frame_indexes[frame][0]];\n        rms += abs(pow(frame_data[i],2));\n    }\n    rms = sqrt(rms/complex<float>(frame_size,0));\n    for (int i = 0; i < frame_size; i ++){\n        frame_data[i] = frame_data[i] / rms;\n    }\n\n    /*\n     * Computing phase offset from SSB, based on RB offset and k_ssb and transposing signal to center on current BWP (which is here CORESET0)\n     */\n    float freq_diff = 12 * 1e3 * mib_object.scs * (pdcch_ss_mon_occ.n_rb_coreset / 2 - (10 * ((float) scs / (1e3*mib_object.scs)) + pdcch_ss_mon_occ.offset));\n    float freq_diff2 = - 15e3 * mib_object.k_ssb;\n    free5GRAN::phy::signal_processing::transpose_signal(&frame_data, freq_diff + freq_diff2 , rf_device->getSampleRate(), frame_size);\n\n    BOOST_LOG_TRIVIAL(trace) << \"## FREQ DIFF 1: \" + to_string(freq_diff);\n    BOOST_LOG_TRIVIAL(trace) << \"## FREQ DIFF 2: \" + to_string(freq_diff2);\n\n    /*\n     * Logging frame data to text file for plotting\n     */\n    ofstream data;\n    data.open(\"output_files/studied_frame.txt\");\n    for (int i = 0; i < frame_size; i ++){\n        data << frame_data[i];\n        data << \"\\n\";\n    }\n    data.close();\n\n    /*\n     * Plotting 4 slots around PDCCH monitoring slots\n     */\n    int begin_index = (pdcch_ss_mon_occ.n0-1) * frame_size / num_slots_per_frame;\n    begin_index = max(begin_index,0);\n    ofstream data2;\n    data2.open(\"output_files/moniroting_slots.txt\");\n    for (int i = 0; i < 4 * frame_size / num_slots_per_frame; i ++){\n        data2 << frame_data[i + begin_index];\n        data2 << \"\\n\";\n    }\n    data2.close();\n\n    /*\n     * Initialize arrays\n     */\n    int num_sc_coreset_0 = 12 * pdcch_ss_mon_occ.n_rb_coreset;\n    complex<float> *dmrs_sequence, *dmrs_symbols, **coefficients, **global_sequence, *temp_pdcch_symbols, **coreset_0_samples;\n    coreset_0_samples = new complex<float>*[pdcch_ss_mon_occ.n_symb_coreset];\n    coefficients = new complex<float>*[pdcch_ss_mon_occ.n_symb_coreset];\n    for (int i = 0; i < pdcch_ss_mon_occ.n_symb_coreset; i ++){\n        coreset_0_samples[i] = new complex<float>[num_sc_coreset_0];\n        coefficients[i] = new complex<float>[num_sc_coreset_0];\n    }\n    /*\n     * Compute CCE-to-REG mapping From TS38.211 7.3.2.2\n     */\n    int height_reg_rb = free5GRAN::NUMBER_REG_PER_CCE / pdcch_ss_mon_occ.n_symb_coreset;\n    int R = 2;\n    int C = pdcch_ss_mon_occ.n_rb_coreset / (height_reg_rb * R);\n    int j;\n    int reg_index[C * R];\n    for (int c = 0; c < C; c ++){\n        for (int r = 0; r < R; r ++){\n            j = c * R + r;\n            reg_index[j] = (r * C + c + this->pci) % (pdcch_ss_mon_occ.n_rb_coreset/height_reg_rb);\n        }\n    }\n    for (int i = 0 ; i < C * R ; i ++){\n        BOOST_LOG_TRIVIAL(trace) << \"## CCE\"+ to_string(i) + \": REG\" + to_string(reg_index[i]);\n    }\n\n    /*\n     * Computing current BWP CP lengths\n     */\n    int num_symbols_per_subframe_pdcch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * mib_object.scs/15;\n    int cp_lengths_pdcch[num_symbols_per_subframe_pdcch];\n    int cum_sum_pdcch[num_symbols_per_subframe_pdcch];\n    free5GRAN::phy::signal_processing::compute_cp_lengths(mib_object.scs, fft_size, is_extended_cp, num_symbols_per_subframe_pdcch, &cp_lengths_pdcch[0], &cum_sum_pdcch[0]);\n\n    int agg_level, num_candidates;\n\n    ofstream data_pdcch;\n\n\n    int **dmrs_indexes, **pdcch_indexes, dmrs_count, pdcch_count, *reg_bundles, *reg_bundles_ns, *dci_decoded_bits, K, freq_domain_ra_size;\n    /*\n     * Number of bits for Frequency domain allocation in DCI\n     */\n    freq_domain_ra_size = ceil(log2(pdcch_ss_mon_occ.n_rb_coreset*(pdcch_ss_mon_occ.n_rb_coreset+1) / 2));\n    /*\n     * K is the DCI payload size including CRC\n     */\n    K = freq_domain_ra_size + 4 + 1 + 5 + 2 + 1 + 15 + 24;\n    float snr;\n    dmrs_indexes = new int*[2];\n    pdcch_indexes = new int*[2];\n    dci_decoded_bits = new int[K-24];\n\n    global_sequence = new complex<float>*[pdcch_ss_mon_occ.n_symb_coreset];\n\n    bool validated = false;\n\n    /*\n     * PDCCH blind search. First, loop over every monitoring slot\n     */\n    BOOST_LOG_TRIVIAL(trace) << \"### PDCCH BLIND SEARCH\";\n    for (int monitoring_slot = 0; monitoring_slot < 2; monitoring_slot ++){\n        pdcch_ss_mon_occ.monitoring_slot = monitoring_slot;\n        BOOST_LOG_TRIVIAL(trace) << \"## MONITORING SLOT: \"+ to_string(monitoring_slot);\n        /*\n         * Extract corresponding CORESET0 samples. CORESET0 number of symbols is given by PDCCH config in MIB\n         */\n        /*\n         * Recover RE grid from time domain signal\n         */\n        free5GRAN::phy::signal_processing::fft(frame_data, coreset_0_samples,fft_size,cp_lengths_pdcch,cum_sum_pdcch,pdcch_ss_mon_occ.n_symb_coreset,num_sc_coreset_0,pdcch_ss_mon_occ.first_symb_index, (pdcch_ss_mon_occ.n0 + monitoring_slot) * frame_size / num_slots_per_frame);\n\n        for (int symb = 0; symb < pdcch_ss_mon_occ.n_symb_coreset; symb ++){\n            global_sequence[symb] = new complex<float>[pdcch_ss_mon_occ.n_rb_coreset * 3 ];\n            /*\n             * Generate DMRS sequence for corresponding symbols\n             */\n            free5GRAN::utils::sequence_generator::generate_pdcch_dmrs_sequence(pci, pdcch_ss_mon_occ.n0 + monitoring_slot, pdcch_ss_mon_occ.first_symb_index + symb, global_sequence[symb], pdcch_ss_mon_occ.n_rb_coreset * 3);\n        }\n        /*\n         * Loop over possible aggregation level (from 2 to 4 included) and candidates\n         */\n        for (int i = 2; i < 5; i ++){\n            agg_level = pow(2, i);\n            if (agg_level <= pdcch_ss_mon_occ.n_rb_coreset / height_reg_rb){\n                BOOST_LOG_TRIVIAL(trace) << \"## AGGREGATION LEVEL\"+ to_string(agg_level);\n                num_candidates = pdcch_ss_mon_occ.n_rb_coreset / (agg_level * height_reg_rb);\n                /*\n                 * Loop over candidates of current aggregation level\n                 */\n                for (int p = 0; p < num_candidates; p ++){\n                    BOOST_LOG_TRIVIAL(trace) << \"## CANDIDATE \"+ to_string(p);\n\n                    /*\n                     * Initialize arrays\n                     */\n                    dmrs_indexes[0] = new int[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3];\n                    dmrs_indexes[1] = new int[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3];\n                    pdcch_indexes[0] = new int[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9];\n                    pdcch_indexes[1] = new int[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9];\n                    dmrs_symbols = new complex<float>[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3];\n                    temp_pdcch_symbols = new complex<float>[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9];\n                    dmrs_count = 0;\n                    pdcch_count = 0;\n                    dmrs_sequence = new complex<float>[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3];\n                    vector<complex<float>> pdcch_symbols(agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9);\n                    reg_bundles = new int[agg_level];\n                    reg_bundles_ns = new int[agg_level];\n\n                    /*\n                     * Extract REG bundles for current candidate and aggregation level\n                     */\n                    for (int l = 0; l < agg_level; l ++){\n                        reg_bundles[l] = reg_index[l + p * agg_level];\n                        reg_bundles_ns[l] = reg_index[l + p * agg_level];\n                    }\n                    sort(reg_bundles, reg_bundles+agg_level);\n                    /*\n                     * PDCCH samples extraction\n                     */\n                    int ***ref;\n                    ref = new int **[2];\n                    ref[0] = new int *[pdcch_ss_mon_occ.n_symb_coreset];\n                    ref[1] = new int *[pdcch_ss_mon_occ.n_symb_coreset];\n\n                    for (int symbol = 0; symbol < pdcch_ss_mon_occ.n_symb_coreset; symbol ++) {\n                        ref[0][symbol] = new int[12 * pdcch_ss_mon_occ.n_rb_coreset];\n                        ref[1][symbol] = new int[12 * pdcch_ss_mon_occ.n_rb_coreset];\n                        for (int sc = 0; sc < 12 * pdcch_ss_mon_occ.n_rb_coreset; sc ++){\n                            ref[1][symbol][sc] = 0;\n                            ref[0][symbol][sc] = 0;\n                        }\n                    }\n                    /*\n                     * Computing PDCCH candidate position in RE grid\n                     */\n                    free5GRAN::phy::physical_channel::compute_pdcch_indexes(ref, pdcch_ss_mon_occ, agg_level, reg_bundles, height_reg_rb);\n\n                    /*\n                     * Channel de-mapping\n                     */\n                    free5GRAN::phy::signal_processing::channel_demapper(coreset_0_samples, ref, new int[2]{0,0}, new complex<float>*[2] {temp_pdcch_symbols,dmrs_symbols}, new int **[2] {pdcch_indexes,dmrs_indexes}, 2, pdcch_ss_mon_occ.n_symb_coreset, 12 * pdcch_ss_mon_occ.n_rb_coreset);\n\n\n                    /*\n                     * DMRS CCE-to-REG de-mapping/de-interleaving\n                     */\n                    for (int k = 0 ; k < agg_level; k ++){\n                        for (int reg = 0; reg < free5GRAN::NUMBER_REG_PER_CCE; reg ++){\n                            dmrs_sequence[((agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3) / pdcch_ss_mon_occ.n_symb_coreset) * (reg%pdcch_ss_mon_occ.n_symb_coreset) +  k * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3] = global_sequence[reg%pdcch_ss_mon_occ.n_symb_coreset][reg_bundles[k] * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3];\n                            dmrs_sequence[((agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3) / pdcch_ss_mon_occ.n_symb_coreset) * (reg%pdcch_ss_mon_occ.n_symb_coreset) +  k * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3 + 1] = global_sequence[reg%pdcch_ss_mon_occ.n_symb_coreset][reg_bundles[k] * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3 + 1];\n                            dmrs_sequence[((agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3) / pdcch_ss_mon_occ.n_symb_coreset) * (reg%pdcch_ss_mon_occ.n_symb_coreset) +  k * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3 + 2] = global_sequence[reg%pdcch_ss_mon_occ.n_symb_coreset][reg_bundles[k] * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3 + 2];\n                        }\n                    }\n                    /*\n                     * Channel estimation\n                     */\n                    free5GRAN::phy::signal_processing::channelEstimation(dmrs_symbols, dmrs_sequence, dmrs_indexes,coefficients, snr, 12 * pdcch_ss_mon_occ.n_rb_coreset, pdcch_ss_mon_occ.n_symb_coreset , agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3);\n                    /*\n                     * Channel equalization\n                     */\n                    for (int sc = 0; sc < agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9; sc ++){\n                        pdcch_symbols[sc] = (temp_pdcch_symbols[sc]) * conj(coefficients[pdcch_indexes[0][sc]][pdcch_indexes[1][sc]]) / (float) pow(abs(coefficients[pdcch_indexes[0][sc]][pdcch_indexes[1][sc]]),2);\n                    }\n\n                    int *dci_bits = new int[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9 * 2];\n                    /*\n                     * PDCCH and DCI decoding\n                     */\n                    free5GRAN::phy::physical_channel::decode_pdcch(pdcch_symbols,dci_bits,agg_level, reg_bundles_ns, reg_bundles, pci);\n                    free5GRAN::phy::transport_channel::decode_dci(dci_bits, agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9 * 2, K, new int[16]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, validated, dci_decoded_bits);\n                    /*\n                     * If DCI CRC is validated, candidate is validated, blind search ends\n                     */\n                    if (validated){\n                        data_pdcch.open(\"output_files/pdcch_constellation.txt\");\n                        for (int sc = 0; sc < agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9; sc ++){\n                            data_pdcch << pdcch_symbols[sc];\n                            data_pdcch << \"\\n\";\n                        }\n                        data_pdcch.close();\n                        goto dci_found_and_validated;\n                    }\n\n                }\n            }else {\n                break;\n            }\n        }\n    }\n\n    dci_found_and_validated:\n    BOOST_LOG_TRIVIAL(trace) << \"## DCI FOUND AND \" << ((validated) ? \"VALIDATED\" :  \"NOT VALIDATED\");\n\n    dci_found = false;\n    if (validated){\n        parse_dci_1_0_si_rnti(dci_decoded_bits,freq_domain_ra_size,dci_1_0_si_rnti);\n        n_size_bwp = pdcch_ss_mon_occ.n_rb_coreset;\n        /*\n         * In current version, only redundancy version 0 and 3 are supported for DL-SCH decoding\n         */\n        if (dci_1_0_si_rnti.rv == 0 || dci_1_0_si_rnti.rv == 3){\n            dci_found = true;\n        }\n\n    }\n}\n\nvoid phy::print_dci_info() {\n    /**\n     * \\fn print_dci_info\n     * \\brief Print DCI decoded informations\n    */\n\n    cout << \"###### DCI\" << endl;\n    cout << \"# RIV: \" + to_string(dci_1_0_si_rnti.RIV)<< endl;\n    cout << \"# Time Domain RA: \" + to_string(dci_1_0_si_rnti.TD_ra) << endl;\n    cout << ((dci_1_0_si_rnti.vrb_prb_interleaving == 0 ) ? \"# Non-interleaved VRB to PRB\" :  \"# Interleaved VRB to PRB\") << endl;\n    cout << \"# Modulation coding scheme: \" + to_string(dci_1_0_si_rnti.mcs) << endl;\n    cout << \"# Redudancy version: \" + to_string(dci_1_0_si_rnti.rv) << endl;\n    cout << ((dci_1_0_si_rnti.si == 0 ) ? \"# SIB1 message\" :  \"# Other SIB message\") << endl;\n    cout << \"#######################################################################\" << endl;\n    if (dci_1_0_si_rnti.rv == 1 || dci_1_0_si_rnti.rv == 2){\n        cout << \"WARNING: Redudancy version \" + to_string(dci_1_0_si_rnti.rv) << \" is not supported by current decoder. To decode SIB1 data on this cell, please use CELL_SEARCH function in config and specify the cell frequency. Retry until redundancy version is not 1 or 2\" << endl;\n        cout << \"#######################################################################\" << endl;\n    }\n    cout << \"\\n\";\n}\n\nvoid phy::parse_dci_1_0_si_rnti(int *dci_bits, int freq_domain_ra_size, free5GRAN::dci_1_0_si_rnti &dci) {\n    /**\n     * \\fn parse_dci_1_0_si_rnti\n     * \\brief Parse DCI informations\n     * \\param[in] dci_bits: DCI decoded bits\n     * \\param[in] freq_domain_ra_size: Number of bits used for frequency allocation in DCI\n     * \\param[out] dci: Filled DCI object\n    */\n\n    dci.RIV = 0;\n    for (int i = 0 ; i < freq_domain_ra_size; i ++){\n        dci.RIV += dci_bits[i] * pow(2, freq_domain_ra_size - i - 1);\n    }\n    dci.TD_ra = 0;\n    for (int i = 0; i < 4; i ++){\n        dci.TD_ra += dci_bits[i + freq_domain_ra_size] * pow(2, 4 - i - 1);\n    }\n\n    dci.vrb_prb_interleaving = dci_bits[freq_domain_ra_size + 4];\n\n    dci.mcs = 0;\n    for (int i = 0; i < 5; i ++){\n        dci.mcs += dci_bits[i + freq_domain_ra_size + 4 + 1] * pow(2, 5 - i - 1);\n    }\n\n    dci.rv = 0;\n    for (int i = 0; i < 2; i ++){\n        dci.rv += dci_bits[i + freq_domain_ra_size + 4 + 1 + 5] * pow(2, 2 - i - 1);\n    }\n\n    dci.si = dci_bits[freq_domain_ra_size + 4 + 1 + 5 + 2];\n}\n\nvoid phy::extract_pdsch() {\n    /**\n     * \\fn extract_pdsch\n     * \\brief PDSCH extraction, PDSCH decoding, DL-SCH decoding and SIB1 parsing\n     * \\details\n     * - Parameters extraction from DCI and standard\n     * - Phase de-compensation. Looping over different possible phase compensation:\n     *  -# Signal extraction, FFT and resource element de-mapper\n     *  -# Channel estimation & equalization\n     *  -# PDSCH decoding\n     *  -# DL-SCH decoding\n     *  -# If CRC is validated, phase de-compensation is validated and functions continues. Otherwise, another phase de-compensation is tried.\n     * - SIB1 parsing using ASN1C\n    */\n\n    BOOST_LOG_TRIVIAL(trace) << \"#### DECODING PDSCH\";\n    /*\n     * Extracting PDSCH time and frequency position\n     */\n    int lrb, rb_start, k0, S, L, mod_order, code_rate, l0;\n    free5GRAN::phy::signal_processing::compute_rb_start_lrb_dci(dci_1_0_si_rnti.RIV, n_size_bwp,lrb,rb_start);\n    k0 = free5GRAN::TS_38_214_TABLE_5_1_2_1_1_2[dci_1_0_si_rnti.TD_ra][mib_object.dmrs_type_a_position - 2][1];\n    S = free5GRAN::TS_38_214_TABLE_5_1_2_1_1_2[dci_1_0_si_rnti.TD_ra][mib_object.dmrs_type_a_position - 2][2];\n    L = free5GRAN::TS_38_214_TABLE_5_1_2_1_1_2[dci_1_0_si_rnti.TD_ra][mib_object.dmrs_type_a_position - 2][3];\n    string mapping_type = ((free5GRAN::TS_38_214_TABLE_5_1_2_1_1_2[dci_1_0_si_rnti.TD_ra][mib_object.dmrs_type_a_position - 2][0] == 0 ) ? \"A\" :  \"B\");\n    mod_order = free5GRAN::TS_38_214_TABLE_5_1_3_1_1[dci_1_0_si_rnti.mcs][0];\n    code_rate = free5GRAN::TS_38_214_TABLE_5_1_3_1_1[dci_1_0_si_rnti.mcs][1];\n    BOOST_LOG_TRIVIAL(trace) << \"## Frequency domain RA: RB Start \" + to_string(rb_start) + \" and LRB \" + to_string(lrb) ;\n    BOOST_LOG_TRIVIAL(trace) << \"## Time domain RA: K0 \" + to_string(k0) + \", S \" + to_string(S) + \" and L \" + to_string(L) + \" (mapping type \"+mapping_type+\")\";\n    BOOST_LOG_TRIVIAL(trace) << \"## MCS: Order \" + to_string(mod_order) + \" and code rate \" + to_string(code_rate);\n    BOOST_LOG_TRIVIAL(trace) << \"## Slot number \" + to_string(pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0);\n\n\n    complex<float> **pdsch_ofdm_symbols,**pdsch_samples;\n    pdsch_ofdm_symbols = new complex<float>*[L];\n    pdsch_samples = new complex<float>*[L];\n    // Initializing fft parameters\n    fftw_complex *fft_in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * fft_size);\n    fftw_complex *fft_out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * fft_size);\n\n    fftw_plan fft_plan = fftw_plan_dft_1d(fft_size, fft_in, fft_out, FFTW_FORWARD, FFTW_MEASURE);\n\n    /*\n     * Compute number of additionnal DMRS positions\n     */\n    int additionnal_position;\n    if (mapping_type == \"A\"){\n        additionnal_position = 2;\n    }else {\n        if (L == 2 || L == 4){\n            additionnal_position = 0;\n        }else if(L == 7){\n            additionnal_position = 1;\n        }\n    }\n\n    int *dmrs_symbols, num_symbols_dmrs;\n    /*\n     * Get PDSCH DMRS symbols indexes\n     */\n    free5GRAN::phy::signal_processing::get_pdsch_dmrs_symbols(mapping_type, L + S, additionnal_position, mib_object.dmrs_type_a_position, &dmrs_symbols, num_symbols_dmrs);\n\n    int ** dmrs_indexes, ** pdsch_indexes, ***ref;\n    complex<float> *dmrs_sequence, *temp_dmrs_sequence, **coefficients;\n    float snr;\n\n    dmrs_sequence = new complex<float>[6 * lrb * num_symbols_dmrs];\n    coefficients = new complex<float>*[L];\n\n    ref = new int **[2];\n\n    /*\n     * ref is used for channel demapping\n     * ref[0] -> PDSCH symbols\n     * ref[1] -> DMRS symbols\n     */\n    ref[0] = new int *[L];\n    ref[1] = new int *[L];\n    dmrs_indexes = new int *[2];\n    dmrs_indexes[0] = new int[6 * lrb * num_symbols_dmrs];\n    dmrs_indexes[1] = new int[6 * lrb * num_symbols_dmrs];\n    pdsch_indexes = new int *[2];\n    pdsch_indexes[0] = new int[12 * lrb * (L - num_symbols_dmrs)];\n    pdsch_indexes[1] = new int[12 * lrb * (L - num_symbols_dmrs)];\n\n    int count_dmrs_symbol = 0;\n    bool dmrs_symbol;\n\n\n    int *cp_lengths_pdsch, *cum_sum_pdsch;\n    int num_symbols_per_subframe_pdsch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * mib_object.scs/15;\n    cp_lengths_pdsch = new int[num_symbols_per_subframe_pdsch];\n    cum_sum_pdsch = new int[num_symbols_per_subframe_pdsch];\n\n    /*\n     * Compute PDSCH CP lengths (same as PDCCH, as it is the same BWP)\n     */\n    free5GRAN::phy::signal_processing::compute_cp_lengths(mib_object.scs, fft_size, is_extended_cp, num_symbols_per_subframe_pdsch, cp_lengths_pdsch, cum_sum_pdsch);\n\n    for (int symb = 0; symb < L; symb ++){\n        pdsch_ofdm_symbols[symb] = new complex<float>[12 * pdcch_ss_mon_occ.n_rb_coreset];\n        pdsch_samples[symb] = new complex<float>[12 * lrb];\n    }\n    /*\n     * Recover RE grid from time domain signal\n     */\n    free5GRAN::phy::signal_processing::fft(frame_data, pdsch_ofdm_symbols,fft_size,cp_lengths_pdsch,cum_sum_pdsch,L,12 * pdcch_ss_mon_occ.n_rb_coreset,S, (pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0) * frame_size / num_slots_per_frame);\n\n    bool dmrs_symbol_array[L];\n\n    /*\n     * PDSCH extraction\n     */\n    for (int symb = 0; symb < L; symb ++){\n        dmrs_symbol = false;\n        /*\n         * Check if studied symbol is a DMRS\n         */\n        for (int j = 0; j < num_symbols_dmrs; j ++){\n            if (symb + S == dmrs_symbols[j]){\n                dmrs_symbol = true;\n                break;\n            }\n        }\n        dmrs_symbol_array[symb] = dmrs_symbol;\n\n        temp_dmrs_sequence = new complex<float>[6 * pdcch_ss_mon_occ.n_rb_coreset];\n        /*\n         * Get DMRS sequence\n         */\n        free5GRAN::utils::sequence_generator::generate_pdsch_dmrs_sequence(free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP, pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0, symb + S, 0, pci, temp_dmrs_sequence, 6 * pdcch_ss_mon_occ.n_rb_coreset);\n        if (dmrs_symbol){\n            for (int i = 0; i < 6 * lrb; i ++){\n                dmrs_sequence[count_dmrs_symbol * 6 * lrb + i] = temp_dmrs_sequence[rb_start * 6 + i];\n            }\n            count_dmrs_symbol += 1;\n        }\n\n        for (int i = 0; i < 12 * lrb; i ++){\n            pdsch_samples[symb][i] = pdsch_ofdm_symbols[symb][12 * rb_start + i];\n        }\n\n        coefficients[symb] = new complex<float>[12 * lrb];\n\n        ref[0][symb] = new int [12 * lrb];\n        ref[1][symb] = new int [12 * lrb];\n    }\n\n    free5GRAN::phy::physical_channel::compute_pdsch_indexes(ref, dmrs_symbol_array, L, lrb);\n\n    complex<float> *pdsch_samples_only, *dmrs_samples_only;\n    pdsch_samples_only = new complex<float>[12 * lrb * (L - num_symbols_dmrs)];\n    dmrs_samples_only = new complex<float>[6 * lrb * num_symbols_dmrs];\n    /*\n     * Channel de-mapping\n     */\n    free5GRAN::phy::signal_processing::channel_demapper(pdsch_samples, ref, new int[2]{12 * lrb * (L - num_symbols_dmrs), 6 * lrb * num_symbols_dmrs}, new complex<float>*[2] {pdsch_samples_only,dmrs_samples_only}, new int **[2] {pdsch_indexes,dmrs_indexes}, 2, L, 12 * lrb);\n\n    bool validated;\n    float f0 = 0;\n    float phase_offset;\n    /*\n    * Phase decompensator. As phase compensation is not known a priori, we have to loop over different possibles phase compensation for decoding\n    */\n    for (int phase_decomp_index = 0; phase_decomp_index < 50; phase_decomp_index++){\n        /*\n         * Compute phase decomp value\n         */\n        f0 += (phase_decomp_index % 2) * pow(2,mu) * 1e3;\n        phase_offset = (phase_decomp_index % 2) ? f0 : -f0;\n        BOOST_LOG_TRIVIAL(trace) << \"PHASE DECOMP \" << phase_offset ;\n        auto *phase_decomp = new complex<float>[num_symbols_per_subframe_pdsch];\n\n        /*\n         * Compute phase decompensation value for each symbol in  a subframe\n         */\n        free5GRAN::phy::signal_processing::compute_phase_decomp(cp_lengths_pdsch, cum_sum_pdsch, rf_device->getSampleRate(),phase_offset,num_symbols_per_subframe_pdsch,phase_decomp);\n\n        /*\n         * Phase de-compensation\n         */\n        for (int samp = 0; samp < 12 * lrb * (L - num_symbols_dmrs); samp ++){\n            pdsch_samples_only[samp] = pdsch_samples_only[samp] * phase_decomp[((pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0) % (num_slots_per_frame / 10)) * free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP + S + pdsch_indexes[0][samp]];\n        }\n        for (int samp = 0; samp < 6 * lrb * num_symbols_dmrs; samp ++){\n            dmrs_samples_only[samp] = dmrs_samples_only[samp] * phase_decomp[((pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0) % (num_slots_per_frame / 10)) * free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP + S + dmrs_indexes[0][samp]];\n        }\n\n        /*\n         * Channel estimation\n         */\n        free5GRAN::phy::signal_processing::channelEstimation(dmrs_samples_only, dmrs_sequence, dmrs_indexes,coefficients, snr, 12 * lrb, L, 6 * lrb * num_symbols_dmrs);\n        /*\n         * Channel equalization\n         */\n        vector<complex<float>> pdsch_samples_vector(12 * lrb * (L - num_symbols_dmrs));\n        for (int sc = 0; sc <  12 * lrb * (L - num_symbols_dmrs); sc ++){\n            pdsch_samples_vector[sc] = (pdsch_samples_only[sc]) * conj(coefficients[pdsch_indexes[0][sc]][pdsch_indexes[1][sc]]) / (float) pow(abs(coefficients[pdsch_indexes[0][sc]][pdsch_indexes[1][sc]]),2);\n        }\n\n        ofstream data_pdsch;\n        data_pdsch.open(\"output_files/pdsch_constellation.txt\");\n        for (int i = 0; i < 12 * lrb * (L - num_symbols_dmrs); i ++){\n            data_pdsch << pdsch_samples_vector[i];\n            data_pdsch << \"\\n\";\n        }\n        data_pdsch.close();\n\n        /*\n         * PDSCH and DL-SCH decoding\n         */\n        double *dl_sch_bits = new double[2 * pdsch_samples_vector.size()];\n        free5GRAN::phy::physical_channel::decode_pdsch(pdsch_samples_vector, dl_sch_bits, pci);\n        int n_re = free5GRAN::phy::signal_processing::compute_nre(L, num_symbols_dmrs);\n\n        vector<int> desegmented = free5GRAN::phy::transport_channel::decode_dl_sch(dl_sch_bits, n_re, (float) code_rate / (float) 1024, lrb,2 * pdsch_samples_vector.size(), validated, dci_1_0_si_rnti);\n        /*\n         * If DL-SCH CRC is validated, Phase decompensation is validated\n         */\n        if (validated){\n            int bytes_size = (int) ceil(desegmented.size()/8.0);\n            uint8_t dl_sch_bytes[bytes_size];\n            for (int i = 0; i < desegmented.size(); i ++){\n                if (i % 8 == 0){\n                    dl_sch_bytes[i/8] = 0;\n                }\n                dl_sch_bytes[i/8] += desegmented[i] * pow(2, 8 - (i%8) - 1);\n            }\n            asn_decode(0, ATS_UNALIGNED_BASIC_PER, &asn_DEF_BCCH_DL_SCH_Message,(void **) &sib1, dl_sch_bytes, bytes_size);\n            break;\n        }\n    }\n\n}\n\nBCCH_DL_SCH_Message_t *phy::getSib() {\n    return this->sib1;\n}\n\nvoid phy::print_sib1() {\n    asn_fprint(stdout, &asn_DEF_BCCH_DL_SCH_Message, sib1);\n}\n\nint phy::getSIB1RV() {\n    return dci_1_0_si_rnti.rv;\n}\n", "meta": {"hexsha": "03d8f89d233593c600ba91803ed17e3627a66e5e", "size": 51573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phy/phy.cpp", "max_stars_repo_name": "gmg2719/free5GRAN", "max_stars_repo_head_hexsha": "5ded60f3c5b85b507f96bdbf092886901d588dd1", "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/phy/phy.cpp", "max_issues_repo_name": "gmg2719/free5GRAN", "max_issues_repo_head_hexsha": "5ded60f3c5b85b507f96bdbf092886901d588dd1", "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/phy/phy.cpp", "max_forks_repo_name": "gmg2719/free5GRAN", "max_forks_repo_head_hexsha": "5ded60f3c5b85b507f96bdbf092886901d588dd1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-20T10:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-20T10:27:52.000Z", "avg_line_length": 44.3067010309, "max_line_length": 379, "alphanum_fraction": 0.6381246001, "num_tokens": 15071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.19423646894116542}}
{"text": "#include <string>\n#include <vector>\n#include <math.h>\n#include <gtest/gtest.h>\n#include <ros/ros.h>\n#include <tf/tf.h>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <ros/package.h>\n\n#include <cslibs_kdl/dynamic_model.h>\n#include <cslibs_kdl/kdl_conversion.h>\n#include <cslibs_kdl/external_forces.h>\nusing namespace cslibs_kdl;\n\nDynamicModel sawyerRobot;\nstd::string urdf_path;\nTEST(SawyerTests, fk)\n{\n    std::vector<double> q = {0, M_PI, M_PI, 0, 0, M_PI, 0};\n    tf::Pose res;\n    int ec = sawyerRobot.getFKPose(q,res,\"right_l6\");\n    EXPECT_TRUE(ec>=0);\n    tf::Pose res4;\n    ec = sawyerRobot.getFKPose(q,res4,\"right_l4\");\n    EXPECT_TRUE(ec>=0);\n    KDL::Frame T1;\n    ec = sawyerRobot.getFKPose(q,T1,\"right_l1\");\n    EXPECT_TRUE(ec>=0);\n\n    std::vector<double> jointAngles = { -1.12, 0.76, -2.36, 1.45, 1.81, -0.46, 4.04};\n    KDL::Vector pos1(0.080478, -0.05083, 0.317);\n    KDL::Frame p1;\n    ec = sawyerRobot.getFKPose(jointAngles, p1, \"right_l1\");\n    EXPECT_TRUE(ec>=0);\n    EXPECT_NEAR(pos1.x(), p1.p.x(), 1e-2);\n    EXPECT_NEAR(pos1.y(), p1.p.y(), 1e-2);\n    EXPECT_NEAR(pos1.z(), p1.p.z(), 1e-2);\n    KDL::Frame p4;\n    ec = sawyerRobot.getFKPose(jointAngles, p4, \"right_l4\");\n    EXPECT_TRUE(ec>=0);\n    KDL::Vector pos4(0.43247, -0.372694, 0.18323);\n    EXPECT_NEAR(pos4.x(), p4.p.x(), 1e-2);\n    EXPECT_NEAR(pos4.y(), p4.p.y(), 1e-2);\n    EXPECT_NEAR(pos4.z(), p4.p.z(), 1e-2);\n    KDL::Frame p6;\n    ec = sawyerRobot.getFKPose(jointAngles, p6, \"right_l6\");\n    EXPECT_TRUE(ec>=0);\n    KDL::Vector pos6(0.403418, -0.756068, 0.295885);\n    EXPECT_NEAR(pos6.x(), p6.p.x(), 1e-2);\n    EXPECT_NEAR(pos6.y(), p6.p.y(), 1e-2);\n    EXPECT_NEAR(pos6.z(), p6.p.z(), 1e-2);\n\n}\n\nTEST(SawyerTests, IK)\n{\n    try{\n        std::vector<double> zero;\n        std::vector<double> jointAngles  = {0, M_PI, M_PI, 0, 0, M_PI, 0};\n        zero.resize(7,0);\n        int nrTests = 10000;\n        int fails = 0;\n        for(int i = 0; i < nrTests; ++i){\n            tf::Pose fk_pose;\n            sawyerRobot.getRandomConfig(jointAngles);\n            int ec = sawyerRobot.getFKPose(jointAngles,fk_pose,\"right_l6\");\n            EXPECT_TRUE(ec>=0);\n            if(ec>=0)\n            {\n                std::vector<double> ik_solution;\n                int ecIK = sawyerRobot.getIKSolution(fk_pose,ik_solution,zero);\n                if(ecIK < 0){\n                    //                geometry_msgs::Pose msg;\n                    //                tf::poseTFToMsg(fk_pose,msg);\n                    //                std::cout << \"number of test\" << i<< std::endl << \"Pose: \" << msg << std::endl;\n\n                    //                for(auto phi : jointAngles) {\n                    //                    std::cout << phi << std::endl;\n                    //                }\n                    ++fails;\n                }\n                //            EXPECT_TRUE(ecIK >= 0);\n                if(ecIK >= 0){\n                    tf::Pose ik_pose;\n                    ecIK = sawyerRobot.getFKPose(ik_solution,ik_pose,\"right_l6\");\n                    EXPECT_NEAR(ik_pose.getOrigin().getX(), fk_pose.getOrigin().getX(), 1e-3);\n                    EXPECT_NEAR(ik_pose.getOrigin().getY(), fk_pose.getOrigin().getY(), 1e-3);\n                    EXPECT_NEAR(ik_pose.getOrigin().getZ(), fk_pose.getOrigin().getZ(), 1e-3);\n                    EXPECT_NEAR(ik_pose.getRotation().getX(), fk_pose.getRotation().getX(), 1e-3);\n                    EXPECT_NEAR(ik_pose.getRotation().getY(), fk_pose.getRotation().getY(), 1e-3);\n                    EXPECT_NEAR(ik_pose.getRotation().getZ(), fk_pose.getRotation().getZ(), 1e-3);\n                    EXPECT_NEAR(ik_pose.getRotation().getW(), fk_pose.getRotation().getW(), 1e-3);\n                }\n            }\n        }\n        double successRate = 1.0 - ((double)fails)/((double)nrTests);\n        EXPECT_NEAR(successRate,0.99, 1e-1);\n        std::cout << \"success rate: \" <<  successRate << std::endl;\n    } catch(const std::exception& e){\n        std::cout << e.what() << std::endl;\n    }\n}\n\nTEST(SawyerTests, ExtForces)\n{\n  ExternalForcesSerialChain extForces;\n  extForces.setModel(urdf_path, \"right_arm_base_link\", \"right_l6\" , \"\", \"\", \"\");\n  std::vector<double> jointAngles = { -1.12, 0.76, -2.36, 1.45, 1.81, -0.46, 4.04};\n//  KDL::Rotation r1 = KDL::Rotation::Quaternion(-0.31631,-0.42821,0.828918,-0.171694);\n  KDL::Vector pos1(0.080478, -0.05083, 0.317);\n  KDL::Frame p1 = extForces.getFKPose(jointAngles, \"right_l1\");\n  EXPECT_NEAR(pos1.x(), p1.p.x(), 1e-2);\n  EXPECT_NEAR(pos1.y(), p1.p.y(), 1e-2);\n  EXPECT_NEAR(pos1.z(), p1.p.z(), 1e-2);\n  KDL::Frame p4 = extForces.getFKPose(jointAngles, \"right_l4\");\n  KDL::Vector pos4(0.43247, -0.372694, 0.18323);\n  EXPECT_NEAR(pos4.x(), p4.p.x(), 1e-2);\n  EXPECT_NEAR(pos4.y(), p4.p.y(), 1e-2);\n  EXPECT_NEAR(pos4.z(), p4.p.z(), 1e-2);\n  KDL::Frame p6 = extForces.getFKPose(jointAngles, \"right_l6\");\n  KDL::Vector pos6(0.403418, -0.756068, 0.295885);\n  EXPECT_NEAR(pos6.x(), p6.p.x(), 1e-2);\n  EXPECT_NEAR(pos6.y(), p6.p.y(), 1e-2);\n  EXPECT_NEAR(pos6.z(), p6.p.z(), 1e-2);\n}\n\nint main(int argc, char *argv[])\n{\n    testing::InitGoogleTest(&argc, argv);\n\n    ros::init(argc, argv, \"test_sawyer_cslibs\");\n    ros::NodeHandle node(\"~\");\n    std::string robot_desc_string;\n    urdf_path = ros::package::getPath(\"cslibs_kdl\");\n    urdf_path += \"/test/sawyer.urdf\";\n    std::cout << urdf_path << std::endl;\n    sawyerRobot = DynamicModel(urdf_path,\"right_arm_base_link\",\"right_l6\");\n\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "3f88a53b9d1ebc5ae5eacaa4d109b90b65d49024", "size": 5507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cslibs_kdl/test/test_sawyer.cpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_kdl", "max_stars_repo_head_hexsha": "a71ab9a1f6f7b854d17d4fdc0c4d7b01c72bec65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T04:45:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T09:29:11.000Z", "max_issues_repo_path": "cslibs_kdl/test/test_sawyer.cpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_kdl", "max_issues_repo_head_hexsha": "a71ab9a1f6f7b854d17d4fdc0c4d7b01c72bec65", "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": "cslibs_kdl/test/test_sawyer.cpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_kdl", "max_forks_repo_head_hexsha": "a71ab9a1f6f7b854d17d4fdc0c4d7b01c72bec65", "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.5104895105, "max_line_length": 117, "alphanum_fraction": 0.567822771, "num_tokens": 1761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.1942364689411654}}
{"text": "#include <stdlib.h>\n#include <ostream>\n#include <stdio.h>\n#include <fstream>\n#include <yaml-cpp/yaml.h>\n#include <vector>\n#include \"ceres/ceres.h\"\n#include \"ceres/rotation.h\"\n#include <iostream>\n#include <ros/ros.h>\n#include <boost/shared_ptr.hpp>\n#include <boost/foreach.hpp>\n#include <boost/random/normal_distribution.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/generator_iterator.hpp>\n\n#include <industrial_extrinsic_cal/basic_types.h>\n#include <industrial_extrinsic_cal/camera_definition.h>\n#include <industrial_extrinsic_cal/camera_yaml_parser.h>\n#include <industrial_extrinsic_cal/targets_yaml_parser.h>\n#include <industrial_extrinsic_cal/points_yaml_parser.h>\n#include <industrial_extrinsic_cal/observation_data_point.h>\n#include <industrial_extrinsic_cal/ceres_costs_utils.hpp>\n#include <industrial_extrinsic_cal/ceres_costs_utils.h>\n#define SHOW_DEBUG false\n\nusing std::ifstream;\nusing std::string;\nusing std::vector;\nusing boost::shared_ptr;\nusing industrial_extrinsic_cal::Pose6d;\nusing industrial_extrinsic_cal::P_BLOCK;\nusing industrial_extrinsic_cal::Camera;\nusing industrial_extrinsic_cal::Point3d;\nusing industrial_extrinsic_cal::ObservationDataPoint;\nusing industrial_extrinsic_cal::extractCameraIntrinsics;\nusing industrial_extrinsic_cal::transformPoint;\nusing industrial_extrinsic_cal::projectPntNoDistortion;\nusing industrial_extrinsic_cal::string2CostType;\nusing industrial_extrinsic_cal::Cost_function;\n\ntypedef boost::minstd_rand base_gen_type;\nbase_gen_type gen(42);\nboost::normal_distribution<> normal_dist(0, 1);  // zero mean unit variance\nboost::variate_generator<base_gen_type&, boost::normal_distribution<> > randn(gen, normal_dist);\n\ntypedef struct observation\n{\n  double x;\n  double y;\n} Observation;\n\ntypedef struct scene\n{\n  int scene_id;\n  Pose6d target_pose;\n  std::vector<std::string> camera_names;\n} Scene;\n\n/*! Brief defines a camera with extra structures to maintain statistics */\nclass CameraWithHistory : public Camera\n{\npublic:\n  int height;\n  int width;\n  vector<Pose6d> pose_history;\n  double pose_position_mean_error;\n  double pose_position_sigma;\n  double pose_orientation_mean_error;\n  double pose_orientation_sigma;\n  double sigma_ax, sigma_ay, sigma_az;\n  int num_observations;\n};\n\n/*! Brief defines a 3d point with extra structures to maintain statistics*/\nclass Point3dWithHistory\n{\npublic:\n  Point3d point;\n  vector<double> x_history;\n  vector<double> y_history;\n  vector<double> z_history;\n  double mean_x;\n  double mean_y;\n  double mean_z;\n  double sigma_x;\n  double sigma_y;\n  double sigma_z;\n  int num_observations;\n};\n\n// local prototypes\nvoid printQTasH(double qx, double qy, double qz, double qw, double tx, double ty, double tz);\nvoid printAATasH(double x, double y, double z, double tx, double ty, double tz);\nvoid printAATasHI(double x, double y, double z, double tx, double ty, double tz);\nvoid printAAasEuler(double x, double y, double z);\nvoid printCamera(CameraWithHistory C, string words);\nvoid computeObservations(vector<CameraWithHistory>& cameras, vector<Point3dWithHistory>& points, double noise,\n                         double max_dist, vector<ObservationDataPoint>& observations);\nvoid perturbCameras(vector<CameraWithHistory>& cameras, double position_noise, double degrees_noise);\nvoid perturbPoints(vector<Point3dWithHistory>& points, double position_noise);\nvoid perturbPose(Pose6d& pose, double position_noise, double degree_noise);\nvoid independentlyPerturbCameras(vector<CameraWithHistory>& cameras);\nvoid copyCamerasWoHistory(vector<CameraWithHistory>& original_cameras, vector<CameraWithHistory>& cameras);\nvoid copyPoints(vector<Point3dWithHistory>& original_points, vector<Point3dWithHistory>& points);\nvoid addPoseToHistory(vector<CameraWithHistory>& cameras, vector<CameraWithHistory>& original_cameras);\nvoid computeHistoricPoseStatistics(vector<CameraWithHistory>& cameras);\nvoid addPointsToHistory(vector<Point3dWithHistory>& points, vector<Point3dWithHistory>& original_points);\nvoid computeHistoricPointStatistics(vector<Point3dWithHistory>& points);\nvoid compareCameras(vector<CameraWithHistory>& C1, vector<CameraWithHistory>& C2);\nvoid compareObservations(vector<ObservationDataPoint>& O1, vector<ObservationDataPoint>& O2);\nbool parseScenes(std::string& scene_file_name, std::vector<Scene>& scenes);\nvoid showScenes(vector<Scene>& scenes);\nvoid addTargetPoints(int rows, int cols, double spacing, vector<Point3dWithHistory>& points, Pose6d& target_pose);\nvoid computeObservationsFromScenes(vector<Scene>& scenes,               // pose of target, and which cameras observed it\n                                   vector<CameraWithHistory>& cameras,  // list of cameras\n                                   double target_pos_noise,  // perturb position of target by this amount then compute\n                                   double target_degree_noise,  // peturb orientation of target by this amount then\n                                                                // compute\n                                   double image_noise,          // amount of noise to add to each observation\n                                   vector<ObservationDataPoint>& observations,  // returned data\n                                   vector<Point3dWithHistory>& points);         // returned target points\nObservationDataPoint predictObservationOfPoint(CameraWithHistory& C, Point3dWithHistory& P, Pose6d& target_pose,\n                                               int scene_id, int point_id, double image_noise,\n                                               bool& results_within_image);\nvoid computeObservationsOfPoints(vector<CameraWithHistory>& cameras, vector<Point3dWithHistory>& points,\n                                 Pose6d& target_pose, int scene_id, vector<ObservationDataPoint>& observations,\n                                 double camera_position_noise = 0.0, double camera_degree_noise = 0.0,\n                                 double image_noise = 0.0);\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"nist_analysis\");\n\n  vector<Point3d> original_points_nh;               // original as read in, no history\n  vector<Point3dWithHistory> original_points;       // working copy of original points\n  vector<shared_ptr<Camera> > original_cameras_sp;  // cameras with given poses\n  vector<CameraWithHistory> original_cameras;       // cameras with given poses\n\n  vector<Point3dWithHistory> points;                 // working copy of original points\n  vector<Point3d> original_field_points_nh;          // test points for accuracy estimation\n  vector<Point3dWithHistory> original_field_points;  // test points for accuracy estimation\n  vector<Point3dWithHistory> field_points;           // working copy of original field points\n\n  vector<CameraWithHistory> cameras;                         // working copy of original cameras\n  vector<ObservationDataPoint> original_observations;        // noisless observations of original points\n  vector<ObservationDataPoint> original_field_observations;  // noisless observations field points\n  vector<ObservationDataPoint> observations;                 // working observations\n\n  // TODO use a parameter file for these, or make them arguments\n  // hard coded constants\n  double camera_pos_noise = 0.10;   // 25 cm\n  double camera_or_noise = 3.0;     // degrees\n  double point_pos_noise = 0.1;     // 10cm perturbation prior to triangulation\n  double target_pos_noise = 0.003;  // 3mm\n  double target_or_noise = 1.0;     // degrees\n  double image_noise = 0.1;         // pixels\n  int num_test_cases = 100;         // each test case is a statistical sample\n\n  google::InitGoogleLogging(argv[0]);\n  if (argc != 4)\n  {\n    std::cerr << \"usage: NistAnalysis <scene_file> <cameras_file> <fieldpoints_file\\n\";\n    return 1;\n  }\n\n  std::string scene_file_name;\n  ifstream scene_file(argv[1]);\n  scene_file_name = argv[1];\n  if (scene_file.fail())\n  {\n    ROS_ERROR_STREAM(\"ERROR can't open scene_file:  \" << scene_file_name.c_str());\n    return (false);\n  }\n\n  std::string cameras_file(argv[2]);\n  std::string field_points_file(argv[3]);\n\n  // read in the camera data, observation data and field points from yaml files\n  parseCameras(cameras_file, original_cameras_sp);\n\n  // copy each into a history capable version\n  // NOTE: pullTransform() is called which installs the results from extrinsic calibration in the camera data\n  std::string ref_frame(\"world\");\n  BOOST_FOREACH (shared_ptr<Camera>& current_camera, original_cameras_sp)\n  {\n    CameraWithHistory temp_camera;\n    temp_camera.setTransformInterface(current_camera->getTransformInterface());\n    temp_camera.camera_observer_ = current_camera->camera_observer_;\n    temp_camera.trigger_ = current_camera->trigger_;\n    temp_camera.camera_parameters_ = current_camera->camera_parameters_;\n    temp_camera.camera_name_ = current_camera->camera_name_;\n    temp_camera.intermediate_frame_ = current_camera->intermediate_frame_;\n    temp_camera.is_moving_ = current_camera->is_moving_;\n    temp_camera.height = current_camera->camera_parameters_.height;\n    temp_camera.width = current_camera->camera_parameters_.width;\n    temp_camera.setTIReferenceFrame(ref_frame);\n    temp_camera.pullTransform();\n    original_cameras.push_back(temp_camera);\n  }\n\n  // parse the scenes.\n  // This is the output from the extrinsic calibration script\n  // every scene has an id, a location of the target, and a list of cameras that observed the target\n  std::vector<Scene> scenes;\n  parseScenes(scene_file_name, scenes);\n  if (SHOW_DEBUG) showScenes(scenes);\n\n  // create original_points and original_observations from scenes\n  // Note, these are nominal, no observation data is kept from calibration\n  // it is expected that the nominal is good enough for analyis of the gometry\n  computeObservationsFromScenes(scenes, original_cameras, 0.0, 0.0, 0.0, original_observations, original_points);\n\n  // parse the field points used to generate the accuracy map\n  parsePoints(field_points_file, original_field_points_nh);\n  original_field_points.clear();\n  for (int i = 0; i < original_field_points_nh.size(); i++)\n  {\n    Point3dWithHistory temp_point;\n    temp_point.point.x = original_field_points_nh[i].x;\n    temp_point.point.y = original_field_points_nh[i].y;\n    temp_point.point.z = original_field_points_nh[i].z;\n    original_field_points.push_back(temp_point);\n  }\n\n  // Setup problem 1: A test to see if camera extrinsics may be\n  // recovered with fixed fiducials.  Create nominal observations of\n  // points using camera parameters. Perturb camera positions and\n  // orientations. Then, add all observation cost functions to problem\n  // and solve.\n  copyCamerasWoHistory(original_cameras, cameras);\n  copyPoints(original_points, points);\n  // compute noise free observations\n  // these should be exactly the same as the original observations and original points\n  computeObservationsFromScenes(scenes, cameras, 0.0, 0.0, 0.0, observations, points);\n\n  // compute noisy observations\n  computeObservationsFromScenes(scenes, cameras, 0.0, 0.0, image_noise, observations, points);\n\n  // compare noisy observations to noise free observations\n  ROS_INFO(\"Comparing %d noiseless observations to %d noisy observations\", (int)original_observations.size(),\n           (int)observations.size());\n  compareObservations(original_observations, observations);  // shows noise is correct\n\n  // regenerate noiseless observations with unperturbed cameras, note observations point to cameras parameters\n  computeObservationsFromScenes(scenes, cameras, 0.0, 0.0, 0.0, observations, points);\n\n  // perturb cameras\n  ROS_INFO(\"perturbing cameras\");\n  perturbCameras(cameras, camera_pos_noise, camera_or_noise);\n  // compare the original camera's locations to the perturbed ones\n  ROS_INFO(\"comparing perturbed cameras to original cameras\");\n  compareCameras(original_cameras, cameras);  // shows how far apart they started\n\n  // Create residuals for each observation in the bundle adjustment problem. The\n  // parameters for cameras and points are added automatically.\n  ceres::Problem problem1;\n  // each observation is noisy and points to cameras whose extrinsics are perturbed\n  // each point is a fiducial in a known/surveyed location\n  ROS_INFO(\"solving with %d observations\", (int)observations.size());\n  int b1o = 0, b2o = 0, b3o = 0, b4o = 0, b5o = 0, b6o = 0, b7o = 0;\n  BOOST_FOREACH (ObservationDataPoint obs, observations)\n  {\n    double* extrinsics = obs.camera_extrinsics_;\n    Point3d point;\n    point.x = obs.point_position_[0];\n    point.y = obs.point_position_[1];\n    point.z = obs.point_position_[2];\n    double fx, fy, cx, cy, k1, k2, k3, p1, p2;\n    industrial_extrinsic_cal::extractCameraIntrinsics(obs.camera_intrinsics_, fx, fy, cx, cy, k1, k2, k3, p1, p2);\n    ceres::CostFunction* cost_function =\n        industrial_extrinsic_cal::CameraReprjErrorPK::Create(obs.image_x_, obs.image_y_, fx, fy, cx, cy, point);\n    problem1.AddResidualBlock(cost_function, NULL, extrinsics);\n  }\n  BOOST_FOREACH (CameraWithHistory& C, cameras)\n  {\n    ROS_INFO(\"%s has %d observations\", C.camera_name_.c_str(), C.num_observations);\n  }\n\n  // solve problem\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = true;\n  options.max_num_iterations = 1000;\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem1, &summary);\n  if (SHOW_DEBUG)\n  {  // display results\n    std::cout << summary.FullReport() << \"\\n\";\n  }\n\n  // see how well original camera poses were recoved with noisy observations\n  ROS_INFO(\"comparing camera poses derived from noiseless measurements to actual\");\n  compareCameras(original_cameras, cameras);  // shows that cameras were recovered\n\n  // compute observations of cameras at solved poses to noiseless observations\n  computeObservationsFromScenes(scenes, cameras, 0.0, 0.0, 0.0, observations, points);\n  ROS_INFO(\"comparing original observations to those made from poses derived from noisy measurments\");\n  compareObservations(original_observations, observations);  // ceres minimized observation noise?\n\n  ROS_ERROR(\"verify recovery of camera poses for cameras with observations\");\n\n  // now, add noise to observations and see how well camera poses are recoverd\n  copyCamerasWoHistory(original_cameras, cameras);\n  computeObservationsFromScenes(scenes, cameras, 0.0, 0.0, image_noise, observations, points);\n  perturbCameras(cameras, camera_pos_noise, camera_or_noise);\n  ceres::Problem problem2;\n  BOOST_FOREACH (ObservationDataPoint obs, observations)\n  {\n    double* extrinsics = obs.camera_extrinsics_;\n    Point3d point;\n    point.x = obs.point_position_[0];\n    point.y = obs.point_position_[1];\n    point.z = obs.point_position_[2];\n    double fx, fy, cx, cy, k1, k2, k3, p1, p2;\n    industrial_extrinsic_cal::extractCameraIntrinsics(obs.camera_intrinsics_, fx, fy, cx, cy, k1, k2, k3, p1, p2);\n    ceres::CostFunction* cost_function =\n        industrial_extrinsic_cal::CameraReprjErrorPK::Create(obs.image_x_, obs.image_y_, fx, fy, cx, cy, point);\n    problem2.AddResidualBlock(cost_function, NULL, extrinsics);\n  }\n  // solve problem\n  ceres::Solve(options, &problem2, &summary);\n  if (SHOW_DEBUG)\n  {  // display results\n    std::cout << summary.FullReport() << \"\\n\";\n  }\n  // see how well original camera poses were recoved with noisy observations\n  ROS_INFO(\"comparing camera poses derived from noisy measurements to actual\");\n  compareCameras(original_cameras, cameras);  // shows that cameras were recovered\n\n  ROS_ERROR(\"verify recovery of camera poses with reduced accuracy for cameras with observations\");\n\n  // Now we are ready to compute each camera's statistics\n  // We answer the following questions\n  // 1. what is the mean error in pose estimate for each camera\n  // 2. what is the variance in pose estimate for each camera\n  // These two values will be stored in camera.pos so that we can\n  // use them to generate estimates of the accuracy of field point localization\n\n  // compute poses for cameras for a bunch of test cases\n  options.minimizer_progress_to_stdout = false;\n  for (int test_case = 0; test_case < num_test_cases; test_case++)\n  {\n    copyCamerasWoHistory(original_cameras, cameras);\n    computeObservationsFromScenes(scenes, cameras, 0.0, 0.0, image_noise, observations, points);\n    perturbCameras(cameras, camera_pos_noise, camera_or_noise);\n\n    ceres::Problem problem;\n    BOOST_FOREACH (ObservationDataPoint obs, observations)\n    {\n      double x = obs.image_x_;\n      double y = obs.image_y_;\n      double* extrinsics = obs.camera_extrinsics_;\n      Point3d point;\n      point.x = obs.point_position_[0];\n      point.y = obs.point_position_[1];\n      point.z = obs.point_position_[2];\n      double fx, fy, cx, cy, k1, k2, k3, p1, p2;\n      industrial_extrinsic_cal::extractCameraIntrinsics(obs.camera_intrinsics_, fx, fy, cx, cy, k1, k2, k3, p1, p2);\n      ceres::CostFunction* cost_function =\n          industrial_extrinsic_cal::CameraReprjErrorPK::Create(x, y, fx, fy, cx, cy, point);\n      problem.AddResidualBlock(cost_function, NULL, extrinsics);\n    }\n    ceres::Solve(options, &problem, &summary);\n    addPoseToHistory(cameras, original_cameras);\n  }  // end of test cases\n  computeHistoricPoseStatistics(original_cameras);\n\n  BOOST_FOREACH (CameraWithHistory& C, original_cameras)\n  {\n    ROS_INFO(\"%s\\t:mean_pos_error = %7.5lf sigma=  %7.5lf angular %7.5lf number_observations = %d\",\n             C.camera_name_.c_str(), C.pose_position_mean_error, C.pose_position_sigma,\n             C.pose_orientation_sigma * 180 / 3.1415, C.num_observations);\n  }\n\n  // at this point cameras each have an uncertianty model.\n  // the uncertianty model is the variance in both position and orientation\n  // We can now sample from this model to get uncertianty estimates for field points.\n  // for .25 pixel error, most cameras have between  in position variance\n  // and have less than .9 degrees in angular variance\n\n  // Now we are ready to compute the field accuracy of the working volume\n  // To to this we do the following.\n  // Create a grid of locations representative of the field accuracy\n  // For this optimization, the points will be solve, while the cameras are fixed\n  // The cameras will be fixed at their original/nominal locations\n  // But the observations will be made from the perturbed/real locations with each test case\n  // Loop:\n  //    Perturb the cameras using each camera's pose accuracy estimate\n  //    compute noisy observations from those perturbed cameras\n  //    Reset cameras to nominal locations, and hold fixed (at incorrect locations)\n  //    optimize to find locations of all field points\n  // end Loop\n  // Compute point statistics for each field point\n\n  // Compute noiseless observations of field points\n  // determine how many times each point gets observed (need at least 2 to be triangulated)\n  copyCamerasWoHistory(original_cameras, cameras);\n  Pose6d target_pose;  // not used, but needed to fill out the observation data structure\n  int scene_id = 0;    // not used\n  computeObservationsOfPoints(cameras, original_field_points, target_pose, scene_id, original_field_observations);\n\n  independentlyPerturbCameras(cameras);\n  ROS_ERROR(\"comparing original camera poses to those using independent perturbations\\n\");\n  compareCameras(original_cameras, cameras);  // will have some agregate overall statistics\n\n  for (int test_case = 0; test_case < num_test_cases; test_case++)\n  {\n    copyPoints(original_field_points, field_points);  // working copy of field points\n    copyCamerasWoHistory(original_cameras, cameras);  // working copy of cameras\n\n    // noiseless ideal observations of cameras at their actual locations, these observation now point toward field\n    // points\n    computeObservationsOfPoints(cameras, field_points, target_pose, scene_id, observations);\n    // noisey ideal observations of cameras at their actual locations\n    // computeObservationsOfPoints(cameras, field_points, target_pose, scene_id, observations, 0.0, 0.0, image_noise);\n\n    // cameras independently perturbed from their actual locations for triangulation\n    independentlyPerturbCameras(cameras);\n    perturbPoints(field_points, point_pos_noise);\n\n    ceres::Problem problem;\n    options.minimizer_progress_to_stdout = false;\n    BOOST_FOREACH (ObservationDataPoint obs, observations)\n    {\n      double x = obs.image_x_;\n      double y = obs.image_y_;\n      double* points = obs.point_position_;  // this is perturbed from ideal by point_pos_noise\n      double fx, fy, cx, cy, k1, k2, k3, p1, p2;\n      industrial_extrinsic_cal::extractCameraIntrinsics(obs.camera_intrinsics_, fx, fy, cx, cy, k1, k2, k3, p1, p2);\n      double tx, ty, tz, ax, ay, az;\n      industrial_extrinsic_cal::extractCameraExtrinsics(obs.camera_extrinsics_, tx, ty, tz, ax, ay, az);\n      Pose6d camera_pose(tx, ty, tz, ax, ay, az);  // note this is the pose from camera to world\n      ceres::CostFunction* cost_function =\n          industrial_extrinsic_cal::TriangulationError::Create(x, y, fx, fy, cx, cy, camera_pose);\n      problem.AddResidualBlock(cost_function, NULL, points);\n    }\n    ceres::Solve(options, &problem, &summary);\n\n    addPointsToHistory(field_points, original_field_points);\n  }\n  computeHistoricPointStatistics(original_field_points);\n  FILE* fp = fopen(\"field_results.m\", \"w\");\n  fprintf(fp, \"f = [\\n\");\n  BOOST_FOREACH (Point3dWithHistory P, original_field_points)\n  {\n    printf(\"Mean Error= %9.5lf %9.5lf %9.5lf sigma= %9.5lf %9.5lf %9.5lf num_obs=%d\\n\", P.mean_x - P.point.x,\n           P.mean_y - P.point.y, P.mean_z - P.point.z, P.sigma_x, P.sigma_y, P.sigma_z, P.num_observations);\n    fprintf(fp, \"%9.5lf %9.5lf %9.5lf %9.5lf %9.5lf %9.5lf %9.5lf %9.5lf %9.5lf;\\n\", P.point.x, P.point.y, P.point.z,\n            P.mean_x, P.mean_y, P.mean_z, P.sigma_x, P.sigma_y, P.sigma_z);\n  }\n  fprintf(fp, \"];\\n\");\n  fclose(fp);\n}\n\n// print a quaternion plus position as a homogeneous transform\nvoid printQTasH(double qx, double qy, double qz, double qw, double tx, double ty, double tz)\n{\n  double Rs11 = qw * qw + qx * qx - qy * qy - qz * qz;\n  double Rs21 = 2.0 * qx * qy + 2.0 * qw * qz;\n  double Rs31 = 2.0 * qx * qz - 2.0 * qw * qy;\n\n  double Rs12 = 2.0 * qx * qy - 2.0 * qw * qz;\n  double Rs22 = qw * qw - qx * qx + qy * qy - qz * qz;\n  double Rs32 = 2.0 * qy * qz + 2.0 * qw * qx;\n\n  double Rs13 = 2.0 * qx * qz + 2.0 * qw * qy;\n  double Rs23 = 2.0 * qy * qz - 2.0 * qw * qx;\n  double Rs33 = qw * qw - qx * qx - qy * qy + qz * qz;\n\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", Rs11, Rs12, Rs13, tx);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", Rs21, Rs22, Rs23, ty);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", Rs31, Rs32, Rs33, tz);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", 0.0, 0.0, 0.0, 1.0);\n}\n\n// angle axis to homogeneous transform inverted\nvoid printAATasH(double x, double y, double z, double tx, double ty, double tz)\n{\n  double R[9];\n  double aa[3];\n  aa[0] = x;\n  aa[1] = y;\n  aa[2] = z;\n  ceres::AngleAxisToRotationMatrix(aa, R);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", R[0], R[3], R[6], tx);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", R[1], R[4], R[7], ty);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", R[2], R[5], R[8], tz);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", 0.0, 0.0, 0.0, 1.0);\n}\n\n// angle axis to homogeneous transform\nvoid printAATasHI(double x, double y, double z, double tx, double ty, double tz)\n{\n  double R[9];\n  double aa[3];\n  aa[0] = x;\n  aa[1] = y;\n  aa[2] = z;\n  ceres::AngleAxisToRotationMatrix(aa, R);\n  double ix = -(tx * R[0] + ty * R[1] + tz * R[2]);\n  double iy = -(tx * R[3] + ty * R[4] + tz * R[5]);\n  double iz = -(tx * R[6] + ty * R[7] + tz * R[8]);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", R[0], R[1], R[2], ix);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", R[3], R[4], R[5], iy);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", R[6], R[7], R[8], iz);\n  printf(\"%6.3lf %6.3lf %6.3lf %6.3lf\\n\", 0.0, 0.0, 0.0, 1.0);\n}\n\nvoid printAAasEuler(double x, double y, double z)\n{\n  double R[9];\n  double aa[3];\n  aa[0] = x;\n  aa[1] = y;\n  aa[2] = z;\n  ceres::AngleAxisToRotationMatrix(aa, R);\n  double rx = atan2(R[7], R[8]);\n  double ry = atan2(-R[6], sqrt(R[7] * R[7] + R[8] * R[8]));\n  double rz = atan2(R[3], R[0]);\n  printf(\"rpy = %8.4f %8.4f %8.4f\\n\", rx, ry, rz);\n}\nvoid printCamera(CameraWithHistory C, string words)\n{\n  printf(\"%s\\n\", words.c_str());\n  printf(\"Point in Camera frame to points in World frame Transform:\\n\");\n  printAATasHI(C.camera_parameters_.angle_axis[0], C.camera_parameters_.angle_axis[1],\n               C.camera_parameters_.angle_axis[2], C.camera_parameters_.position[0], C.camera_parameters_.position[1],\n               C.camera_parameters_.position[2]);\n\n  printf(\"Points in World frame to points in Camera frame transform\\n\");\n  printAATasH(C.camera_parameters_.angle_axis[0], C.camera_parameters_.angle_axis[1],\n              C.camera_parameters_.angle_axis[2], C.camera_parameters_.position[0], C.camera_parameters_.position[1],\n              C.camera_parameters_.position[2]);\n\n  printAAasEuler(C.camera_parameters_.angle_axis[0], C.camera_parameters_.angle_axis[1],\n                 C.camera_parameters_.angle_axis[2]);\n  printf(\"fx = %8.3lf fy = %8.3lf\\n\", C.camera_parameters_.focal_length_x, C.camera_parameters_.focal_length_y);\n  printf(\"cx = %8.3lf cy = %8.3lf\\n\", C.camera_parameters_.center_x, C.camera_parameters_.center_y);\n}\n\nvoid computeObservations(vector<CameraWithHistory>& cameras, vector<Point3dWithHistory>& points, double noise,\n                         double max_dist, vector<ObservationDataPoint>& observations)\n{\n  double pnoise = noise / sqrt(1.58085);  // magic number found by trial and error\n  int n_observations = 0;\n  observations.clear();\n\n  // reset number of observations for the points\n  BOOST_FOREACH (Point3dWithHistory& P, points)\n  {\n    P.num_observations = 0;\n  }\n\n  // create nominal observations of points using camera parameters\n  BOOST_FOREACH (CameraWithHistory& C, cameras)\n  {\n    C.num_observations = 0;\n    int j = 0;\n    BOOST_FOREACH (Point3dWithHistory& P, points)\n    {\n      j++;\n      // find image of point in camera\n      double dx = C.camera_parameters_.position[0] - P.point.x;\n      double dy = C.camera_parameters_.position[1] - P.point.y;\n      double dz = C.camera_parameters_.position[2] - P.point.z;\n      double distance = sqrt(dx * dx + dy * dy + dz * dz);\n      if (distance < max_dist)\n      {\n        double fx, fy, cx, cy, k1, k2, k3, p1, p2;\n        Observation obs;\n        double* intrinsics = C.camera_parameters_.pb_intrinsics;\n        industrial_extrinsic_cal::extractCameraIntrinsics(intrinsics, fx, fy, cx, cy, k1, k2, k3, p1, p2);\n        P_BLOCK point = &P.point.pb[0];\n        industrial_extrinsic_cal::projectPntNoDistortion(point, fx, fy, cx, cy, obs.x, obs.y);\n        obs.x += pnoise * randn();  // add observation noise\n        obs.y += pnoise * randn();\n        if (obs.x >= 0 && obs.x < C.width && obs.y >= 0 && obs.y < C.height)\n        {\n          // save observation\n          Pose6d target_pose, intermediate_frame;\n          industrial_extrinsic_cal::Cost_function cost_type;\n          ObservationDataPoint new_obs(C.camera_name_,\n                                       \"who_cares\",                         // target name\n                                       2,                                   // target type\n                                       0,                                   // scene id (who cares)\n                                       C.camera_parameters_.pb_intrinsics,  // camera intrinsics\n                                       C.camera_parameters_.pb_extrinsics,  // camera extrinsics\n                                       0,                                   // point_id\n                                       target_pose.pb_pose,                 // target_pose\n                                       point,                               // point position\n                                       obs.x,                               // observation x\n                                       obs.x,                               // observation y\n                                       cost_type,                           // const Cost_function\n                                       intermediate_frame);                 // Pose6d of intermediate frame\n          observations.push_back(new_obs);\n          C.num_observations++;\n          P.num_observations++;\n          n_observations++;\n        }  // end if observation within field of view\n      }    // end if point close enough to camera\n    }      // end for each fiducial point\n  }        // end for each camera\n}  // end compute observations\n\nvoid perturbCameras(vector<CameraWithHistory>& cameras, double position_noise, double degrees_noise)\n{\n  double pos_noise = position_noise / sqrt(2.274625);\n  double radian_noise = degrees_noise * 3.1415 / (180.0 * sqrt(2.58047));\n  BOOST_FOREACH (CameraWithHistory& C, cameras)\n  {\n    C.camera_parameters_.position[0] += pos_noise * randn();\n    C.camera_parameters_.position[1] += pos_noise * randn();\n    C.camera_parameters_.position[2] += pos_noise * randn();\n    C.camera_parameters_.angle_axis[0] += radian_noise * randn();\n    C.camera_parameters_.angle_axis[1] += radian_noise * randn();\n    C.camera_parameters_.angle_axis[2] += radian_noise * randn();\n  }\n}\n\nvoid perturbPoints(vector<Point3dWithHistory>& points, double position_noise)\n{\n  double pos_noise = position_noise / sqrt(2.274625);\n  BOOST_FOREACH (Point3dWithHistory& P, points)\n  {\n    P.point.x += pos_noise * randn();\n    P.point.y += pos_noise * randn();\n    P.point.z += pos_noise * randn();\n  }\n}\n\nvoid independentlyPerturbCameras(vector<CameraWithHistory>& cameras)\n{\n  BOOST_FOREACH (CameraWithHistory& C, cameras)\n  {\n    double pos_noise = C.pose_position_sigma / sqrt(2.274625);\n    double radian_noise = C.pose_orientation_sigma / sqrt(2.58047);\n    C.camera_parameters_.position[0] += pos_noise * randn();\n    C.camera_parameters_.position[1] += pos_noise * randn();\n    C.camera_parameters_.position[2] += pos_noise * randn();\n    C.camera_parameters_.angle_axis[0] += radian_noise * randn();\n    C.camera_parameters_.angle_axis[1] += radian_noise * randn();\n    C.camera_parameters_.angle_axis[2] += radian_noise * randn();\n  }\n}\n\nvoid copyCamerasWoHistory(vector<CameraWithHistory>& original_cameras, vector<CameraWithHistory>& cameras)\n{\n  cameras.clear();\n  BOOST_FOREACH (CameraWithHistory& C, original_cameras)\n  {\n    CameraWithHistory newC = C;\n    newC.pose_history.clear();\n    newC.num_observations = 0;\n    cameras.push_back(newC);\n  }\n}\n\nvoid copyPoints(vector<Point3dWithHistory>& original_points, vector<Point3dWithHistory>& points)\n{\n  points.clear();\n  BOOST_FOREACH (Point3dWithHistory& P, original_points)\n  {\n    points.push_back(P);\n  }\n}\n\nvoid addPoseToHistory(vector<CameraWithHistory>& cameras, vector<CameraWithHistory>& original_cameras)\n{\n  if (cameras.size() != original_cameras.size()) ROS_ERROR_STREAM(\"number of cameras in vectors do not match\");\n\n  for (int i = 0; i < (int)cameras.size(); i++)\n  {\n    Pose6d pose;\n    pose.x = cameras[i].camera_parameters_.position[0];\n    pose.y = cameras[i].camera_parameters_.position[1];\n    pose.z = cameras[i].camera_parameters_.position[2];\n    pose.ax = cameras[i].camera_parameters_.angle_axis[0];\n    pose.ay = cameras[i].camera_parameters_.angle_axis[1];\n    pose.az = cameras[i].camera_parameters_.angle_axis[2];\n    original_cameras[i].pose_history.push_back(pose);\n  }\n}\n\nvoid computeHistoricPoseStatistics(vector<CameraWithHistory>& cameras)\n{\n  // calculate statistics of test case\n  double mean_x, mean_y, mean_z, mean_ax, mean_ay, mean_az;\n  double sigma_x, sigma_y, sigma_z, sigma_ax, sigma_ay, sigma_az;\n  BOOST_FOREACH (CameraWithHistory& C, cameras)\n  {\n    mean_x = 0.0;\n    mean_y = 0.0;\n    mean_z = 0.0;\n    mean_ax = 0.0;\n    mean_ay = 0.0;\n    mean_az = 0.0;\n    BOOST_FOREACH (Pose6d& p, C.pose_history)\n    {\n      mean_x += p.x;\n      mean_y += p.y;\n      mean_z += p.z;\n      mean_ax += p.ax;\n      mean_ay += p.ay;\n      mean_az += p.az;\n    }\n    int num_poses = (int)C.pose_history.size();\n    mean_x = mean_x / num_poses;\n    mean_y = mean_y / num_poses;\n    mean_z = mean_z / num_poses;\n    mean_ax = mean_ax / num_poses;\n    mean_ay = mean_ay / num_poses;\n    mean_az = mean_az / num_poses;\n\n    double d_x = mean_x - C.camera_parameters_.position[0];\n    double d_y = mean_y - C.camera_parameters_.position[1];\n    double d_z = mean_z - C.camera_parameters_.position[2];\n    C.pose_position_mean_error = sqrt(d_x * d_x + d_y * d_y + d_z * d_z);\n    double d_ax = mean_ax - C.camera_parameters_.angle_axis[0];\n    double d_ay = mean_ay - C.camera_parameters_.angle_axis[1];\n    double d_az = mean_az - C.camera_parameters_.angle_axis[2];\n    C.pose_orientation_mean_error = sqrt(d_ax * d_ax + d_ay * d_ay + d_az * d_az);\n\n    sigma_x = 0.0;\n    sigma_y = 0.0;\n    sigma_z = 0.0;\n    sigma_ax = 0.0;\n    sigma_ay = 0.0;\n    sigma_az = 0.0;\n    BOOST_FOREACH (Pose6d& p, C.pose_history)\n    {\n      sigma_x += (mean_x - p.x) * (mean_x - p.x);\n      ;\n      sigma_y += (mean_y - p.y) * (mean_y - p.y);\n      ;\n      sigma_z += (mean_z - p.z) * (mean_z - p.z);\n      ;\n      sigma_ax += (mean_ax - p.ax) * (mean_ax - p.ax);\n      ;\n      sigma_ay += (mean_ay - p.ay) * (mean_ay - p.ay);\n      ;\n      sigma_az += (mean_az - p.az) * (mean_az - p.az);\n      ;\n    }\n    sigma_x = sqrt(sigma_x / (num_poses - 1.0));\n    sigma_y = sqrt(sigma_y / (num_poses - 1.0));\n    sigma_z = sqrt(sigma_z / (num_poses - 1.0));\n    C.sigma_ax = sigma_ax = sqrt(sigma_ax / (num_poses - 1.0));\n    C.sigma_ay = sigma_ay = sqrt(sigma_ay / (num_poses - 1.0));\n    C.sigma_az = sigma_az = sqrt(sigma_az / (num_poses - 1.0));\n\n    double dv = sqrt(sigma_x * sigma_x + sigma_y * sigma_y + sigma_z * sigma_z);\n    double av = sqrt(sigma_ax * sigma_ax + sigma_ay * sigma_ay + sigma_az * sigma_az);\n\n    C.pose_position_sigma = dv;\n    C.pose_orientation_sigma = av;\n  }  // end for each camera\n}\n\nvoid computeHistoricPointStatistics(vector<Point3dWithHistory>& points)\n{\n  // calculate statistics of test case\n  double mean_x, mean_y, mean_z;\n\n  BOOST_FOREACH (Point3dWithHistory& P, points)\n  {\n    P.mean_x = P.mean_y = P.mean_z = 0.0;\n    BOOST_FOREACH (double& p, P.x_history)\n    {\n      P.mean_x += p;\n    }\n    BOOST_FOREACH (double& p, P.y_history)\n    {\n      P.mean_y += p;\n    }\n    BOOST_FOREACH (double& p, P.z_history)\n    {\n      P.mean_z += p;\n    }\n    int num_values = (int)P.x_history.size();\n    if (num_values == 0)\n    {\n      num_values = 1.0;\n    }\n    P.mean_x = P.mean_x / num_values;\n    P.mean_y = P.mean_y / num_values;\n    P.mean_z = P.mean_z / num_values;\n\n    P.sigma_x = P.sigma_y = P.sigma_z = 0.0;\n    BOOST_FOREACH (double& p, P.x_history)\n    {\n      P.sigma_x += (P.mean_x - p) * (P.mean_x - p);\n      ;\n    }\n    BOOST_FOREACH (double& p, P.y_history)\n    {\n      P.sigma_y += (P.mean_y - p) * (P.mean_y - p);\n      ;\n    }\n    BOOST_FOREACH (double& p, P.z_history)\n    {\n      P.sigma_z += (P.mean_z - p) * (P.mean_z - p);\n      ;\n    }\n    double denom = num_values - 1.0;\n    if (denom == 0 || P.num_observations == 0)\n    {\n      P.sigma_x = 1000;\n      P.sigma_y = 1000;\n      P.sigma_z = 1000;\n    }\n    else if (P.num_observations == 1)\n    {  // can't triangulate with only one observation\n      P.sigma_x = 0.4;\n      P.sigma_y = 0.4;\n      P.sigma_z = 0.4;\n    }\n    else\n    {\n      P.sigma_x = sqrt(P.sigma_x / denom);\n      P.sigma_y = sqrt(P.sigma_y / denom);\n      P.sigma_z = sqrt(P.sigma_z / denom);\n    }\n  }  // end for each point\n}\n\nvoid compareCameras(vector<CameraWithHistory>& C1, vector<CameraWithHistory>& C2)\n{\n  if (C1.size() != C2.size())\n  {\n    ROS_ERROR_STREAM(\"compareCameras() camera vectors different in length\");\n  }\n  double d_x, d_y, d_z, dist;\n  double mean_dist = 0;\n  double sigma_dist = 0;\n  double d_ax, d_ay, d_az, angle;\n  double mean_angle = 0;\n  double sigma_angle = 0;\n  for (int i = 0; i < (int)C1.size(); i++)\n  {\n    if (C1[i].camera_name_ == C2[i].camera_name_)\n    {\n      d_x = C1[i].camera_parameters_.position[0] - C2[i].camera_parameters_.position[0];\n      d_y = C1[i].camera_parameters_.position[1] - C2[i].camera_parameters_.position[1];\n      d_z = C1[i].camera_parameters_.position[2] - C2[i].camera_parameters_.position[2];\n      d_ax = C1[i].camera_parameters_.angle_axis[0] - C2[i].camera_parameters_.angle_axis[0];\n      d_ay = C1[i].camera_parameters_.angle_axis[1] - C2[i].camera_parameters_.angle_axis[1];\n      d_az = C1[i].camera_parameters_.angle_axis[2] - C2[i].camera_parameters_.angle_axis[2];\n      dist = sqrt(d_x * d_x + d_y * d_y + d_z * d_z);\n      angle = sqrt(d_ax * d_ax + d_ay * d_ay + d_az * d_az);\n      ROS_INFO(\"camera %s position_diff = %7.5lf meters, orientation diff = %7.5lf degrees\", C1[i].camera_name_.c_str(),\n               dist, angle * 180 / 3.14);\n      mean_dist += dist;\n      mean_angle += angle;\n    }\n    else\n    {\n      printf(\"cameras not same\\n\");\n    }\n  }\n  mean_dist = mean_dist / (int)C1.size();\n  mean_angle = mean_angle / (int)C1.size();\n  for (int i = 0; i < (int)C1.size(); i++)\n  {\n    d_x = C1[i].camera_parameters_.position[0] - C2[i].camera_parameters_.position[0];\n    d_y = C1[i].camera_parameters_.position[1] - C2[i].camera_parameters_.position[1];\n    d_z = C1[i].camera_parameters_.position[2] - C2[i].camera_parameters_.position[2];\n    d_ax = C1[i].camera_parameters_.angle_axis[0] - C2[i].camera_parameters_.angle_axis[0];\n    d_ay = C1[i].camera_parameters_.angle_axis[1] - C2[i].camera_parameters_.angle_axis[1];\n    d_az = C1[i].camera_parameters_.angle_axis[2] - C2[i].camera_parameters_.angle_axis[2];\n    dist = sqrt(d_x * d_x + d_y * d_y + d_z * d_z);\n    angle = sqrt(d_ax * d_ax + d_ay * d_ay + d_az * d_az);\n    sigma_dist += (dist - mean_dist) * (dist - mean_dist);\n    sigma_angle += (angle - mean_angle) * (angle - mean_angle);\n  }\n  sigma_dist = sqrt(sigma_dist / C1.size());\n  sigma_angle = sqrt(sigma_angle / C1.size());\n  ROS_INFO(\"mean distance between camera poses = %9.5lf meters sigma= %9.5lf\", mean_dist, sigma_dist);\n  ROS_INFO(\"mean angle between camera poses = %9.5lf degrees sigma= %9.5lf\", mean_angle * 180 / 3.1415,\n           sigma_angle * 180 / 3.1415);\n}\n\nvoid compareObservations(vector<ObservationDataPoint>& O1, vector<ObservationDataPoint>& O2)\n{\n  if (O1.size() != O2.size())\n  {\n    ROS_ERROR_STREAM(\"compareObservations() vectors different in length\");\n  }\n  double d_x, d_y, dist;\n  double mean_dist = 0.0;\n  double sigma_dist = 0.0;\n  int n_compared = 0;\n  for (int i = 0; i < (int)O1.size(); i++)\n  {\n    if (O1[i].camera_name_ == O2[i].camera_name_ && O1[i].point_id_ == O2[i].point_id_)\n    {\n      d_x = O1[i].image_x_ - O2[i].image_x_;\n      d_y = O1[i].image_y_ - O2[i].image_y_;\n      dist = sqrt(d_x * d_x + d_y * d_y);\n      mean_dist += dist;\n      n_compared++;\n    }\n  }\n  mean_dist = mean_dist / n_compared;\n  for (int i = 0; i < (int)O1.size(); i++)\n  {\n    if (O1[i].camera_name_ == O2[i].camera_name_ && O1[i].point_id_ == O2[i].point_id_)\n    {\n      d_x = O1[i].image_x_ - O2[i].image_x_;\n      d_y = O1[i].image_y_ - O2[i].image_y_;\n      dist = sqrt(d_x * d_x + d_y * d_y);\n      sigma_dist += (dist - mean_dist) * (dist - mean_dist);\n    }\n  }\n  sigma_dist = sqrt(sigma_dist / n_compared);\n  ROS_INFO(\"mean distance between observations = %9.5lf pixels sigma= %9.5lf \", mean_dist, sigma_dist);\n}\n\nvoid addPointsToHistory(vector<Point3dWithHistory>& points, vector<Point3dWithHistory>& original_points)\n{\n  if (points.size() != original_points.size()) ROS_ERROR_STREAM(\"number of points in vectors do not match\");\n\n  for (int i = 0; i < (int)points.size(); i++)\n  {\n    original_points[i].x_history.push_back(points[i].point.x);\n    original_points[i].y_history.push_back(points[i].point.y);\n    original_points[i].z_history.push_back(points[i].point.z);\n  }\n}\n\nbool parseScenes(std::string& scene_file_name, std::vector<Scene>& scenes)\n{\n  FILE* fp = fopen(scene_file_name.c_str(), \"r\");\n  if (fp == NULL)\n  {\n    ROS_ERROR(\"Can't open file %s\", scene_file_name.c_str());\n    return (false);\n  }\n  int scene_id = 10;\n  scenes.clear();\n  while (fscanf(fp, \"scene_id = %d/n\", &scene_id) == 1)\n  {\n    Scene temp_scene;\n    temp_scene.scene_id = scene_id;\n    tf::Matrix3x3 R;\n    double x, y, z;\n    char dum[100], dum2[100], dum3[100];\n    double z1, z2, z3, z4;\n    fscanf(fp, \"%s %s %s %lf %lf %lf %lf;/n\", dum, dum2, dum3, &R[0][0], &R[0][1], &R[0][2], &x);\n    fscanf(fp, \"%lf %lf %lf %lf;/n\", &R[1][0], &R[1][1], &R[1][2], &y);\n    fscanf(fp, \"%lf %lf %lf %lf;/n\", &R[2][0], &R[2][1], &R[2][2], &z);\n    fscanf(fp, \"%lf %lf %lf %lf];/n\", &z1, &z2, &z3, &z4);  // gobble last row\n    temp_scene.target_pose.setBasis(R);\n    tf::Vector3 v(x, y, z);\n    temp_scene.target_pose.setOrigin(v);\n    temp_scene.camera_names.clear();\n    char temp_char_data[100];\n    fscanf(fp, \"%s %s %s %s\", dum, dum2, dum3, temp_char_data);\n    temp_scene.camera_names.push_back(std::string(temp_char_data));\n    bool done = false;\n    do\n    {\n      fscanf(fp, \"%s\", temp_char_data);\n      if (temp_char_data[0] == ']')\n      {\n        done = true;\n        char c = 'a';\n        while (c != '\\n')\n          fscanf(fp, \"%c\", &c);\n      }\n      else\n      {\n        temp_scene.camera_names.push_back(std::string(temp_char_data));\n      }\n    } while (!done);\n    ROS_INFO(\"scene %d has %d cameras\", (int)scene_id, (int)temp_scene.camera_names.size());\n    scenes.push_back(temp_scene);\n  }  // end while there are more scenes\n  fclose(fp);\n  return (true);\n}\n\nvoid show_scenes(vector<Scene>& scenes)\n{\n  BOOST_FOREACH (Scene S, scenes)\n  {\n    ROS_INFO(\"scene_id %d\", S.scene_id);\n    S.target_pose.show(\"target pose:\");\n    BOOST_FOREACH (string s, S.camera_names)\n    {\n      ROS_INFO(\"%s\", s.c_str());\n    }\n  }\n}\nvoid perturbPose(Pose6d& pose, double position_noise, double degree_noise)\n{\n  double pos_noise = position_noise / sqrt(2.274625);\n  double radian_noise = degree_noise * 3.1415 / (180.0 * sqrt(2.58047));\n  pose.x += pos_noise * randn();\n  pose.y += pos_noise * randn();\n  pose.z += pos_noise * randn();\n  pose.ax += radian_noise * randn();\n  pose.ay += radian_noise * randn();\n  pose.ay += radian_noise * randn();\n}\n\nvoid computeObservationsOfPoints(vector<CameraWithHistory>& cameras, vector<Point3dWithHistory>& points,\n                                 Pose6d& target_pose, int scene_id, vector<ObservationDataPoint>& observations,\n                                 double camera_position_noise, double camera_degree_noise, double image_noise)\n\n{\n  observations.clear();\n  BOOST_FOREACH (CameraWithHistory& C, cameras)\n  {\n    int q = 0;\n    BOOST_FOREACH (Point3dWithHistory& P, points)\n    {\n      bool good_observation;\n      ObservationDataPoint obs =\n          predictObservationOfPoint(C, P, target_pose, scene_id, q++, image_noise, good_observation);\n      if (good_observation)\n      {\n        observations.push_back(obs);\n        P.num_observations++;\n      }\n    }\n  }\n}\nvoid computeObservationsFromScenes(vector<Scene>& scenes,               // pose of target, and which cameras observed it\n                                   vector<CameraWithHistory>& cameras,  // list of cameras\n                                   double target_pos_noise,  // perturb position of target by this amount then compute\n                                   double target_degree_noise,  // peturb orientation of target by this amount then\n                                                                // compute\n                                   double image_noise,          // amount of noise to add to each observation\n                                   vector<ObservationDataPoint>& observations,  // returned data\n                                   vector<Point3dWithHistory>& points)          // returned target points\n{\n  observations.clear();\n  BOOST_FOREACH (CameraWithHistory& C, cameras)\n    C.num_observations = 0;\n  double pnoise = image_noise / sqrt(1.58085);  // magic number found by trial and error\n  int rows = 10;\n  int cols = 10;\n  double spacing = .025;\n  points.clear();\n  BOOST_FOREACH (Scene& S, scenes)\n  {\n    // add a new set of target points to the vector of all points\n    int target_point_offset = points.size();  // points[target_point_offset] is the first of the new points being added\n    // add any target position and pose noise to target's pose\n    if (target_pos_noise > 0.0 || target_degree_noise > 0.0)\n    {\n      perturbPose(S.target_pose, target_pos_noise, target_degree_noise);\n    }\n    addTargetPoints(rows, cols, spacing, points, S.target_pose);  // added in world coordinates\n    // for each camera in scene\n    BOOST_FOREACH (string camera_name, S.camera_names)\n    {\n      CameraWithHistory* current_camera_ptr = NULL;\n      for (int i = 0; i < cameras.size(); i++)\n      {\n        if (cameras[i].camera_name_ == camera_name)\n        {\n          current_camera_ptr = &(cameras[i]);\n        }\n      }\n      if (current_camera_ptr == NULL)\n      {\n        ROS_ERROR(\"Couldn't find camera %s\", camera_name.c_str());\n      }\n      for (int i = target_point_offset; i < (int)points.size(); i++)\n      {  // for each new point\n        bool good_observation;\n        ObservationDataPoint obs = predictObservationOfPoint(*current_camera_ptr, points[i], S.target_pose, S.scene_id,\n                                                             i, image_noise, good_observation);\n        if (good_observation)\n        {\n          observations.push_back(obs);\n          current_camera_ptr->num_observations++;\n          points[i].num_observations++;\n        }\n      }\n    }  // end for each camera in scene\n  }    // end for each scene\n}  // end\n\nObservationDataPoint predictObservationOfPoint(CameraWithHistory& C, Point3dWithHistory& P, Pose6d& target_pose,\n                                               int scene_id, int point_id, double image_noise,\n                                               bool& results_within_image)\n{\n  double pnoise = image_noise / sqrt(1.58085);  // magic number found by trial and error\n  double fx, fy, cx, cy, k1, k2, k3, p1, p2;\n  double aa[3], tx[3];\n  double ox, oy;\n  double world_point[3];\n  std::string t_name(\"modified_circle_grid\");\n  Pose6d dummy_target_pose;\n  Pose6d dummy_intermediate_pose;\n  std::string cost_type_string(\"CameraReprjErrorPK\");\n  Cost_function cost_type = string2CostType(cost_type_string);\n\n  extractCameraIntrinsics(C.camera_parameters_.pb_intrinsics, fx, fy, cx, cy, k1, k2, k3, p1, p2);\n  aa[0] = C.camera_parameters_.angle_axis[0];\n  aa[1] = C.camera_parameters_.angle_axis[1];\n  aa[2] = C.camera_parameters_.angle_axis[2];\n  tx[0] = C.camera_parameters_.position[0];\n  tx[1] = C.camera_parameters_.position[1];\n  tx[2] = C.camera_parameters_.position[2];\n  transformPoint(aa, tx, P.point.pb, world_point);              // move to world coordinates\n  projectPntNoDistortion(world_point, fx, fy, cx, cy, ox, oy);  // project point into camera's image plane\n  ox += pnoise * randn();                                       // add observation noise\n  oy += pnoise * randn();\n  results_within_image = true;\n  if (ox < 0.0 || ox > C.camera_parameters_.width || oy < 0.0 || oy > C.camera_parameters_.height)\n  {\n    results_within_image = false;\n  }\n  ObservationDataPoint obs(C.camera_name_,\n                           t_name,  // target_name\n                           2,       // target type\n                           scene_id, C.camera_parameters_.pb_intrinsics, C.camera_parameters_.pb_extrinsics, point_id,\n                           target_pose.pb_pose, P.point.pb, ox, oy, cost_type, dummy_intermediate_pose, 0.0);\n  return (obs);\n}\n\nvoid addTargetPoints(int rows, int cols, double spacing, vector<Point3dWithHistory>& points, Pose6d& target_pose)\n{\n  for (int i = 0; i < rows; i++)\n  {\n    for (int j = 0; j < cols; j++)\n    {\n      double target_point[3];\n      double world_point[3];\n      target_point[0] = j * spacing;\n      target_point[1] = (rows - 1 - i) * spacing;\n      target_point[2] = 0.0;\n      poseTransformPoint(target_pose, target_point, world_point);  // move to world coordinates\n      Point3dWithHistory point;\n      point.point.x = world_point[0];\n      point.point.y = world_point[1];\n      point.point.z = world_point[2];\n      points.push_back(point);\n    }\n  }\n}\n", "meta": {"hexsha": "e79212611316e2b78107178f4b998fd8a0aadbf4", "size": 48458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "industrial_extrinsic_cal/src/nodes/nist_analysis.cpp", "max_stars_repo_name": "ipa-nhg/industrial_calibration", "max_stars_repo_head_hexsha": "fae08e9ab67392551d6c7355be7ca90cb889c1b9", "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": "industrial_extrinsic_cal/src/nodes/nist_analysis.cpp", "max_issues_repo_name": "ipa-nhg/industrial_calibration", "max_issues_repo_head_hexsha": "fae08e9ab67392551d6c7355be7ca90cb889c1b9", "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": "industrial_extrinsic_cal/src/nodes/nist_analysis.cpp", "max_forks_repo_name": "ipa-nhg/industrial_calibration", "max_forks_repo_head_hexsha": "fae08e9ab67392551d6c7355be7ca90cb889c1b9", "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.1740644038, "max_line_length": 120, "alphanum_fraction": 0.6671344257, "num_tokens": 13148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.1942364689411654}}
{"text": "//------------------------------------------------------------------------------\n/*\n  This file is part of rippled: https://github.com/ripple/rippled\n  Copyright (c) 2021 Ripple Labs Inc.\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\n  ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n  WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN\n  ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n//==============================================================================\n\n#include <ripple/app/tx/impl/NFTokenMint.h>\n#include <ripple/basics/Expected.h>\n#include <ripple/basics/Log.h>\n#include <ripple/ledger/View.h>\n#include <ripple/protocol/Feature.h>\n#include <ripple/protocol/InnerObjectFormats.h>\n#include <ripple/protocol/Rate.h>\n#include <ripple/protocol/TxFlags.h>\n#include <ripple/protocol/st.h>\n#include <boost/endian/conversion.hpp>\n#include <array>\n\nnamespace ripple {\n\nNotTEC\nNFTokenMint::preflight(PreflightContext const& ctx)\n{\n    if (!ctx.rules.enabled(featureNonFungibleTokensV1))\n        return temDISABLED;\n\n    if (auto const ret = preflight1(ctx); !isTesSuccess(ret))\n        return ret;\n\n    if (ctx.tx.getFlags() & tfNFTokenMintMask)\n        return temINVALID_FLAG;\n\n    if (auto const f = ctx.tx[~sfTransferFee])\n    {\n        if (f > maxTransferFee)\n            return temBAD_NFTOKEN_TRANSFER_FEE;\n\n        // If a non-zero TransferFee is set then the tfTransferable flag\n        // must also be set.\n        if (f > 0u && !ctx.tx.isFlag(tfTransferable))\n            return temMALFORMED;\n    }\n\n    // An issuer must only be set if the tx is executed by the minter\n    if (auto iss = ctx.tx[~sfIssuer]; iss == ctx.tx[sfAccount])\n        return temMALFORMED;\n\n    if (auto uri = ctx.tx[~sfURI])\n    {\n        if (uri->length() == 0 || uri->length() > maxTokenURILength)\n            return temMALFORMED;\n    }\n\n    return preflight2(ctx);\n}\n\nuint256\nNFTokenMint::createNFTokenID(\n    std::uint16_t flags,\n    std::uint16_t fee,\n    AccountID const& issuer,\n    nft::Taxon taxon,\n    std::uint32_t tokenSeq)\n{\n    // An issuer may issue several NFTs with the same taxon; to ensure that NFTs\n    // are spread across multiple pages we lightly mix the taxon up by using the\n    // sequence (which is not under the issuer's direct control) as the seed for\n    // a simple linear congruential generator.  cipheredTaxon() does this work.\n    taxon = nft::cipheredTaxon(tokenSeq, taxon);\n\n    // The values are packed inside a 32-byte buffer, so we need to make sure\n    // that the endianess is fixed.\n    flags = boost::endian::native_to_big(flags);\n    fee = boost::endian::native_to_big(fee);\n    taxon = nft::toTaxon(boost::endian::native_to_big(nft::toUInt32(taxon)));\n    tokenSeq = boost::endian::native_to_big(tokenSeq);\n\n    std::array<std::uint8_t, 32> buf{};\n\n    auto ptr = buf.data();\n\n    // This code is awkward but the idea is to pack these values into a single\n    // 256-bit value that uniquely identifies this NFT.\n    std::memcpy(ptr, &flags, sizeof(flags));\n    ptr += sizeof(flags);\n\n    std::memcpy(ptr, &fee, sizeof(fee));\n    ptr += sizeof(fee);\n\n    std::memcpy(ptr, issuer.data(), issuer.size());\n    ptr += issuer.size();\n\n    std::memcpy(ptr, &taxon, sizeof(taxon));\n    ptr += sizeof(taxon);\n\n    std::memcpy(ptr, &tokenSeq, sizeof(tokenSeq));\n    ptr += sizeof(tokenSeq);\n    assert(std::distance(buf.data(), ptr) == buf.size());\n\n    return uint256::fromVoid(buf.data());\n}\n\nTER\nNFTokenMint::preclaim(PreclaimContext const& ctx)\n{\n    // The issuer of the NFT may or may not be the account executing this\n    // transaction. Check that and verify that this is allowed:\n    if (auto issuer = ctx.tx[~sfIssuer])\n    {\n        auto const sle = ctx.view.read(keylet::account(*issuer));\n\n        if (!sle)\n            return tecNO_ISSUER;\n\n        if (auto const minter = (*sle)[~sfNFTokenMinter];\n            minter != ctx.tx[sfAccount])\n            return tecNO_PERMISSION;\n    }\n\n    return tesSUCCESS;\n}\n\nTER\nNFTokenMint::doApply()\n{\n    auto const issuer = ctx_.tx[~sfIssuer].value_or(account_);\n\n    auto const tokenSeq = [this, &issuer]() -> Expected<std::uint32_t, TER> {\n        auto const root = view().peek(keylet::account(issuer));\n        if (root == nullptr)\n            // Should not happen.  Checked in preclaim.\n            return Unexpected(tecNO_ISSUER);\n\n        // Get the unique sequence number for this token:\n        std::uint32_t const tokenSeq = (*root)[~sfMintedNFTokens].value_or(0);\n        {\n            std::uint32_t const nextTokenSeq = tokenSeq + 1;\n            if (nextTokenSeq < tokenSeq)\n                return Unexpected(tecMAX_SEQUENCE_REACHED);\n\n            (*root)[sfMintedNFTokens] = nextTokenSeq;\n        }\n        ctx_.view().update(root);\n        return tokenSeq;\n    }();\n\n    if (!tokenSeq.has_value())\n        return (tokenSeq.error());\n\n    std::uint32_t const ownerCountBefore =\n        view().read(keylet::account(account_))->getFieldU32(sfOwnerCount);\n\n    // Assemble the new NFToken.\n    SOTemplate const* nfTokenTemplate =\n        InnerObjectFormats::getInstance().findSOTemplateBySField(sfNFToken);\n\n    if (nfTokenTemplate == nullptr)\n        // Should never happen.\n        return tecINTERNAL;\n\n    STObject newToken(\n        *nfTokenTemplate,\n        sfNFToken,\n        [this, &issuer, &tokenSeq](STObject& object) {\n            object.setFieldH256(\n                sfNFTokenID,\n                createNFTokenID(\n                    static_cast<std::uint16_t>(ctx_.tx.getFlags() & 0x0000FFFF),\n                    ctx_.tx[~sfTransferFee].value_or(0),\n                    issuer,\n                    nft::toTaxon(ctx_.tx[sfNFTokenTaxon]),\n                    tokenSeq.value()));\n\n            if (auto const uri = ctx_.tx[~sfURI])\n                object.setFieldVL(sfURI, *uri);\n        });\n\n    if (TER const ret =\n            nft::insertToken(ctx_.view(), account_, std::move(newToken));\n        ret != tesSUCCESS)\n        return ret;\n\n    // Only check the reserve if the owner count actually changed.  This\n    // allows NFTs to be added to the page (and burn fees) without\n    // requiring the reserve to be met each time.  The reserve is\n    // only managed when a new NFT page is added.\n    if (auto const ownerCountAfter =\n            view().read(keylet::account(account_))->getFieldU32(sfOwnerCount);\n        ownerCountAfter > ownerCountBefore)\n    {\n        if (auto const reserve = view().fees().accountReserve(ownerCountAfter);\n            mPriorBalance < reserve)\n            return tecINSUFFICIENT_RESERVE;\n    }\n    return tesSUCCESS;\n}\n\n}  // namespace ripple\n", "meta": {"hexsha": "b4e391c3ee818f2ef119476d8c1f2e80cc602923", "size": 7116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ripple/app/tx/impl/NFTokenMint.cpp", "max_stars_repo_name": "shichengripple001/rippled", "max_stars_repo_head_hexsha": "7c66747d27869f9f3c96617bd4227038f1fa92b8", "max_stars_repo_licenses": ["ISC"], "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/ripple/app/tx/impl/NFTokenMint.cpp", "max_issues_repo_name": "shichengripple001/rippled", "max_issues_repo_head_hexsha": "7c66747d27869f9f3c96617bd4227038f1fa92b8", "max_issues_repo_licenses": ["ISC"], "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/ripple/app/tx/impl/NFTokenMint.cpp", "max_forks_repo_name": "shichengripple001/rippled", "max_forks_repo_head_hexsha": "7c66747d27869f9f3c96617bd4227038f1fa92b8", "max_forks_repo_licenses": ["ISC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5660377358, "max_line_length": 80, "alphanum_fraction": 0.630831928, "num_tokens": 1786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19423646169227826}}
{"text": "#include \"formats/cp.hpp\"\n#include \"atomistic.hpp\"\n#include \"types.hpp\"\n#include \"io.hpp\"\n\n#include <boost/format.hpp>\n#include <boost/regex.hpp>\n#include <boost/lexical_cast.hpp>\n\nnamespace formats {\nnamespace cp {\n\ntypedef boost::sregex_iterator RegIt;\ntypedef boost::smatch Match;\ntypedef const boost::regex Regex;\n\nusing boost::lexical_cast;\nusing namespace types;\nnamespace at = atomistic;\n\nSpectrum & Spectrum::operator*=(Real factor){\n    for(std::vector<at::EnergyLevels>::iterator it = this->spins.begin(); it != this->spins.end(); it++) {\n        *it *= factor;\n    }\n\n    return *this;\n}\n\n\nvoid Spectrum::shift(Real deltaE) {\n    for(std::vector<at::EnergyLevels>::iterator it = this->spins.begin(); it != this->spins.end(); it++) {\n        it->shift(deltaE);\n    }\n}\n\nvoid Spectrum::setFermiZero() {\n    for(std::vector<at::EnergyLevels>::iterator it = this->spins.begin(); it != this->spins.end(); it++) {\n        it->setFermiZero();\n    }\n}\n\nat::EnergyLevels Spectrum::sumSpins() const {\n    at::EnergyLevels e = at::EnergyLevels();\n    // Spins may have different Fermi. The new Fermi is the average Fermi of all spins\n    // and energy levels are shifted accordingly\n    Uint counter = 0;\n    Real fermiSum = 0;\n\n    for(std::vector<at::EnergyLevels>::const_iterator it = this->spins.begin(); it != this->spins.end(); it++) {\n        e.join(*it);\n        ++counter;\n    }\n\n    return e;\n}\n\nvoid Spectrum::print() const {\n    for(std::vector<at::EnergyLevels>::const_iterator it = this->spins.begin(); it != this->spins.end(); it++) {\n        it->print();\n    }\n}\n\nbool Spectrum::readFromCp(String filename) {\n    String content;\n    io::readFile(filename, content);\n\n    RegIt occIt(\n        content.begin(),\n        content.end(),\n        boost::regex(\"Eigenvalues (eV), kp =   1 , spin =  ([\\\\.\\\\-\\\\d\\\\s]*)\"));\n//    RegIt fermiIt(\n//        content.begin(),\n//        content.end(),\n//        boost::regex(\"Fermi Energy \\\\[eV\\\\] :([\\\\.\\\\-\\\\d\\\\s]*)\"));\n//    RegIt unoccIt(\n//        content.begin(),\n//        content.end(),\n//        boost::regex(\"Eigenvalues of the unoccupied subspace spin.*?iterations([\\\\.\\\\-\\\\d\\\\s]*)\"));\n    RegIt dummyIt;\n\n\n    Regex fermiRegex(\"\\\\-?\\\\d\\\\.\\\\d{6}\");\n    Regex levelRegex(\"\\\\-?\\\\d+\\\\.\\\\d+\");\n\n    // Iterate over spins\n    while(occIt != dummyIt) {\n        String levelData = occIt->str();\n        std::vector<Real> levels;\n        RegIt levelIt(levelData.begin(), levelData.end(), levelRegex);\n        while(levelIt != dummyIt) {\n            levels.push_back(lexical_cast<Real>(levelIt->str()));\n            ++levelIt;\n        }\n\n//        Match fermiMatch;\n//        regex_search(fermiIt->str(), fermiMatch, fermiRegex);\n//        Real fermi = lexical_cast<Real>(fermiMatch);\n//        // fermi given in eV, want Ha = 2 Ry\n//        fermi *= GSL_CONST_MKSA_ELECTRON_VOLT / \n//            (2* GSL_CONST_MKSA_RYDBERG);\n\n        at::EnergyLevels energyLevels = at::EnergyLevels(levels, 0);\n        this->spins.push_back(energyLevels);\n\n        ++occIt;\n    }\n\n    return true;\n}\n\n\n}\n}\n", "meta": {"hexsha": "50e8e1530678abf94c649660207d7d6fde1e7834", "size": 3042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/formats/cp.cpp", "max_stars_repo_name": "ltalirz/util-programs", "max_stars_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "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": "lib/formats/cp.cpp", "max_issues_repo_name": "ltalirz/util-programs", "max_issues_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_issues_repo_licenses": ["MIT"], "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/formats/cp.cpp", "max_forks_repo_name": "ltalirz/util-programs", "max_forks_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_forks_repo_licenses": ["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.6842105263, "max_line_length": 112, "alphanum_fraction": 0.5933596318, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19423646169227826}}
{"text": "#include <openvslam_ros.h>\n\n#include <chrono>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <openvslam/publish/map_publisher.h>\n#include <Eigen/Geometry>\n\nnamespace openvslam_ros {\nsystem::system(const std::shared_ptr<openvslam::config>& cfg, const std::string& vocab_file_path, const std::string& mask_img_path)\n    : SLAM_(cfg, vocab_file_path), cfg_(cfg), node_(std::make_shared<rclcpp::Node>(\"run_slam\")), custom_qos_(rmw_qos_profile_default),\n      mask_(mask_img_path.empty() ? cv::Mat{} : cv::imread(mask_img_path, cv::IMREAD_GRAYSCALE)),\n      pose_pub_(node_->create_publisher<nav_msgs::msg::Odometry>(\"~/camera_pose\", 1)) {\n    custom_qos_.depth = 1;\n    exec_.add_node(node_);\n}\n\nvoid system::publish_pose() {\n    // SLAM get the motion matrix publisher\n    auto cam_pose_wc = SLAM_.get_map_publisher()->get_current_cam_pose_wc();\n\n    // Extract rotation matrix and translation vector from\n    Eigen::Matrix3d rot = cam_pose_wc.block<3, 3>(0, 0);\n    Eigen::Vector3d trans = cam_pose_wc.block<3, 1>(0, 3);\n    Eigen::Matrix3d cv_to_ros;\n    cv_to_ros << 0, 0, 1,\n        -1, 0, 0,\n        0, -1, 0;\n\n    // Transform from CV coordinate system to ROS coordinate system on camera coordinates\n    Eigen::Quaterniond quat(cv_to_ros * rot * cv_to_ros.transpose());\n    trans = cv_to_ros * trans;\n\n    // Create odometry message and update it with current camera pose\n    nav_msgs::msg::Odometry pose_msg;\n    pose_msg.header.stamp = node_->now();\n    pose_msg.header.frame_id = \"map\";\n    pose_msg.child_frame_id = \"camera_link\";\n    pose_msg.pose.pose.orientation.x = quat.x();\n    pose_msg.pose.pose.orientation.y = quat.y();\n    pose_msg.pose.pose.orientation.z = quat.z();\n    pose_msg.pose.pose.orientation.w = quat.w();\n    pose_msg.pose.pose.position.x = trans(0);\n    pose_msg.pose.pose.position.y = trans(1);\n    pose_msg.pose.pose.position.z = trans(2);\n    pose_pub_->publish(pose_msg);\n}\n\nmono::mono(const std::shared_ptr<openvslam::config>& cfg, const std::string& vocab_file_path, const std::string& mask_img_path)\n    : system(cfg, vocab_file_path, mask_img_path) {\n    sub_ = image_transport::create_subscription(\n        node_.get(), \"camera/image_raw\", [this](const sensor_msgs::msg::Image::ConstSharedPtr& msg) { callback(msg); }, \"raw\", custom_qos_);\n}\nvoid mono::callback(const sensor_msgs::msg::Image::ConstSharedPtr& msg) {\n    const rclcpp::Time tp_1 = node_->now();\n    const double timestamp = tp_1.seconds();\n\n    // input the current frame and estimate the camera pose\n    SLAM_.feed_monocular_frame(cv_bridge::toCvShare(msg)->image, timestamp, mask_);\n\n    const rclcpp::Time tp_2 = node_->now();\n    const double track_time = (tp_2 - tp_1).seconds();\n\n    //track times in seconds\n    track_times_.push_back(track_time);\n}\n\nstereo::stereo(const std::shared_ptr<openvslam::config>& cfg, const std::string& vocab_file_path, const std::string& mask_img_path,\n               const bool rectify)\n    : system(cfg, vocab_file_path, mask_img_path),\n      rectifier_(rectify ? std::make_shared<openvslam::util::stereo_rectifier>(cfg) : nullptr),\n      left_sf_(node_, \"camera/left/image_raw\"),\n      right_sf_(node_, \"camera/right/image_raw\"),\n      sync_(left_sf_, right_sf_, 10) {\n    sync_.registerCallback(&stereo::callback, this);\n}\n\nvoid stereo::callback(const sensor_msgs::msg::Image::ConstPtr& left, const sensor_msgs::msg::Image::ConstPtr& right) {\n    auto leftcv = cv_bridge::toCvShare(left)->image;\n    auto rightcv = cv_bridge::toCvShare(right)->image;\n    if (leftcv.empty() || rightcv.empty()) {\n        return;\n    }\n\n    if (rectifier_) {\n        rectifier_->rectify(leftcv, rightcv, leftcv, rightcv);\n    }\n\n    const rclcpp::Time tp_1 = node_->now();\n    const double timestamp = tp_1.seconds();\n\n    // input the current frame and estimate the camera pose\n    SLAM_.feed_stereo_frame(leftcv, rightcv, timestamp, mask_);\n\n    const rclcpp::Time tp_2 = node_->now();\n    const double track_time = (tp_2 - tp_1).seconds();\n\n    //track times in seconds\n    track_times_.push_back(track_time);\n}\n} // namespace openvslam_ros\n", "meta": {"hexsha": "8e33fd6fab849bf8d78a3038b75c74f51d888673", "size": 4100, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ros/2/src/openvslam/src/openvslam_ros.cc", "max_stars_repo_name": "SteveMacenski/openvslam", "max_stars_repo_head_hexsha": "a797cf7d91fe3ba1e5784eb48bc94492383ee9e3", "max_stars_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T00:52:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T00:52:55.000Z", "max_issues_repo_path": "ros/2/src/openvslam/src/openvslam_ros.cc", "max_issues_repo_name": "SteveMacenski/openvslam", "max_issues_repo_head_hexsha": "a797cf7d91fe3ba1e5784eb48bc94492383ee9e3", "max_issues_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "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/2/src/openvslam/src/openvslam_ros.cc", "max_forks_repo_name": "SteveMacenski/openvslam", "max_forks_repo_head_hexsha": "a797cf7d91fe3ba1e5784eb48bc94492383ee9e3", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "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.8058252427, "max_line_length": 140, "alphanum_fraction": 0.6970731707, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19423646169227826}}
{"text": "#include \"trajopt/common.hpp\"\n#include <openrave-core.h>\n#include \"trajopt/collision_checker.hpp\"\n#include \"osgviewer/osgviewer.hpp\"\n#include \"utils/eigen_conversions.hpp\"\n#include \"trajopt/utils.hpp\"\n#include <boost/algorithm/string.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/foreach.hpp>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\nusing namespace OpenRAVE;\nusing namespace std;\nusing namespace trajopt;\nusing namespace util;\nusing namespace Eigen;\n\ntypedef Matrix<double,6,1> Vector6d;\ntypedef Matrix<double,6,Eigen::Dynamic> Matrix6Xd;\ntypedef Matrix<double,6,6> Matrix6d;\ntypedef Matrix<double,12,1> Vector12d;\ntypedef Matrix<double,12,Eigen::Dynamic> Matrix12Xd;\ntypedef Matrix<double,12,12> Matrix12d;\n\nCollisionCheckerPtr cc;\nvector<GraphHandlePtr> handles;\nEnvironmentBasePtr env;\nOSGViewerPtr viewer;\n\n// copied from rave_utils\nRobotBase::ManipulatorPtr GetManipulatorByName(RobotBase& robot, const std::string& name) {\n\tvector<RobotBase::ManipulatorPtr> manips = robot.GetManipulators();\n\tBOOST_FOREACH(RobotBase::ManipulatorPtr& manip, manips) {\n\t\tif (manip->GetName()==name) return manip;\n\t}\n\treturn RobotBase::ManipulatorPtr();\n}\n\n// copied from problem_description\nBeliefRobotAndDOFPtr RADFromName(const string& name, RobotBasePtr robot) {\n\tif (name == \"active\") {\n\t\treturn BeliefRobotAndDOFPtr(new BeliefRobotAndDOF(robot, robot->GetActiveDOFIndices(), robot->GetAffineDOF(), robot->GetAffineRotationAxis()));\n\t}\n\tvector<int> dof_inds;\n\tint affinedofs = 0;\n\tVector rotationaxis(0,0,1);\n\tvector<string> components;\n\tboost::split(components, name, boost::is_any_of(\"+\"));\n\tfor (int i=0; i < components.size(); ++i) {\n\t\tstd::string& component = components[i];\n\t\tif (RobotBase::ManipulatorPtr manip = GetManipulatorByName(*robot, component)) {\n\t\t\tvector<int> inds = manip->GetArmIndices();\n\t\t\tdof_inds.insert(dof_inds.end(), inds.begin(), inds.end());\n\t\t}\n\t\telse if (component == \"base3d\") {\n\t\t\taffinedofs |= DOF_XYZ | DOF_Rotation3D;\n\t\t}\n\t\telse if (component == \"base\") {\n\t\t\taffinedofs |= DOF_X | DOF_Y | DOF_RotationAxis;\n\t\t}\n\t\telse if (component == \"base_point\") {\n\t\t\taffinedofs |= DOF_X | DOF_Y;\n\t\t}\n\t\telse if (KinBody::JointPtr joint = robot->GetJoint(component)) {\n\t\t\tdof_inds.push_back(joint->GetDOFIndex());\n\t\t}\n\t\telse PRINT_AND_THROW( boost::format(\"error in reading manip description: %s must be a manipulator, link, or 'base'\")%component );\n\t}\n\treturn BeliefRobotAndDOFPtr(new BeliefRobotAndDOF(robot, dof_inds, affinedofs, rotationaxis));\n}\n\nvoid DiscreteCheckSigmaSigma(BeliefRobotAndDOFPtr rad0, const MatrixXd& sigma_pts0, BeliefRobotAndDOFPtr rad1, const MatrixXd& sigma_pts1, vector<Collision>& collisions) {\n\tOR::RobotBase::RobotStateSaver saver0 = rad0->Save();\n\tOR::RobotBase::RobotStateSaver saver1 = rad1->Save();\n\n\tvector<int> inds;\n\n\tKinBody::LinkPtr link0, link1;\n\tvector<KinBody::LinkPtr> links;\n\trad0->GetAffectedLinks(links, true, inds);\n\tassert(links.size() == 1);\n\tlink0 = links[0];\n\trad1->GetAffectedLinks(links, true, inds);\n\tassert(links.size() == 1);\n\tlink1 = links[0];\n\n\tvector<OR::Transform> tf0(sigma_pts0.cols()), tf1(sigma_pts1.cols());\n\n\tfor (int i=0; i<sigma_pts0.cols(); i++) {\n\t\trad0->SetDOFValues(toDblVec(sigma_pts0.col(i)));\n\t\ttf0[i] = link0->GetTransform();\n\t}\n\tfor (int i=0; i<sigma_pts1.cols(); i++) {\n\t\trad1->SetDOFValues(toDblVec(sigma_pts1.col(i)));\n\t\ttf1[i] = link1->GetTransform();\n\t}\n\tcc->MultiCastVsMultiCast(link0, tf0, link1, tf1, collisions);\n}\n\nfloat alpha = 1;\nvoid AdjustTransparency(float da) {\n\talpha += da;\n\talpha = fmin(alpha, 1);\n\talpha = fmax(alpha, 0);\n\tviewer->SetAllTransparency(alpha);\n}\n\nbool isTrajectoryInCollision(CollisionCheckerPtr cc, TrajArray traj, BeliefRobotAndDOFPtr rad) {\n\tvector<Collision> collisions;\n\tcc->DiscreteCheckTrajectory(traj, rad, collisions);\n\tfor (int i=0; i<collisions.size(); i++) {\n\t\tif (collisions[i].distance < 0) return true;\n\t}\n\treturn false;\n}\n\nOR::Vector toQuat(const Matrix3d& m) {\n\tQuaterniond rq(m);\n\treturn OR::Vector(rq.w(), rq.x(), rq.y(), rq.z());\n}\nOR::Vector toQuat(const AngleAxisd& aa) {\n\treturn toQuat(aa.toRotationMatrix());\n}\nEigen::Matrix3d toMatrix3d(OR::RaveVector<float> rq) {\n\treturn Quaterniond(rq[0], rq[1], rq[2], rq[3]).toRotationMatrix();\n}\n\nvoid renderSigmaPts(BeliefRobotAndDOFPtr rad, const MatrixXd& sigma_pts, const osg::Vec4f& colorvec) {\n\tOR::RobotBase::RobotStateSaver saver = rad->Save();\n\n\tvector<KinBody::LinkPtr> links;\n\tvector<int> joint_inds;\n\trad->GetAffectedLinks(links, true, joint_inds);\n\n\t// render sigma points\n\tfor (int j=0; j<sigma_pts.cols(); j++) {\n\t\trad->SetDOFValues(toDblVec(sigma_pts.col(j)));\n\t\thandles.push_back(viewer->PlotKinBody(rad->GetRobot()));\n\t\tSetColor(handles.back(), colorvec);\n\t}\n\n\t// render convex hulls of sigma points\n\tvector<DblVec> dofvals(sigma_pts.cols());\n\tfor (int i=0; i<sigma_pts.cols(); i++)\n\t\tdofvals[i] = toDblVec(sigma_pts.col(i));\n\tcc->SetContactDistance(100);\n\tcc->PlotCastHull(*rad, links, dofvals, handles);\n\tSetTransparency(handles.back(), 0.2);\n}\n\nMatrix3d skewSymmetric(const Vector3d& v) {\n\tMatrix3d m;\n\tm << 0, -v(2), v(1), v(2), 0, -v(0), -v(1), v(0), 0;\n\treturn m;\n}\n\nMatrix3d poseToRot(VectorXd x) {\n\tVector3d aa;\n\tif (x.rows() == 3) aa = x;\n\telse if (x.rows() == 6) aa = x.bottomRows(3);\n\tMatrix3d rot;\n\tif (aa.norm() > 1e-5)\n\t\trot = (Matrix3d) AngleAxisd(aa.norm(), aa.normalized());\n\telse\n\t\trot = Matrix3d::Identity();\n\treturn rot;\n}\nVector3d toEigenVector(OR::Vector v) {\n\treturn Vector3d(v[0], v[1], v[2]);\n}\nOR::Vector toORVector(Vector3d v) {\n\treturn OR::Vector(v[0], v[1], v[2]);\n}\n\nCollision transformedCollision(const Collision& col_rhs, const Vector6d& pose) {\n\tMatrix3d rot = poseToRot(pose);\n\tVector3d pos = pose.topRows(3);\n\tCollision col = col_rhs;\n\tcol.ptA = toORVector(rot * toEigenVector(col.ptA) + pos);\n\tcol.ptB = toORVector(rot * toEigenVector(col.ptB) + pos);\n\tcol.normalB2A = toORVector(rot * toEigenVector(col.normalB2A));\n\treturn col;\n}\n\n//VectorXd psi0, VectorXd psi1,\n// psi0 is robot\n// psi1 is obstacle\nVector6d delta(const Vector6d& psi0, const Vector6d& psi1) {\n\tVector3d pos0 = psi0.topRows(3);\n\tVector3d pos1 = psi1.topRows(3);\n\tMatrix3d rot0 = poseToRot(psi0);\n\tMatrix3d rot1 = poseToRot(psi1);\n//\tif (psi0.bottomRows(3).norm() > 1e-5)\n//\t\trot0 = (Matrix3d) AngleAxisd(psi0.bottomRows(3).norm(), psi0.bottomRows(3).normalized());\n//\telse\n//\t\trot0 = Matrix3d::Identity();\n//\tif (psi1.bottomRows(3).norm() > 1e-5)\n//\t\trot1 = (Matrix3d) AngleAxisd(psi1.bottomRows(3).norm(), psi1.bottomRows(3).normalized());\n//\telse\n//\t\trot1 = Matrix3d::Identity();\n\n//\tVector6d rel_old;\n//\trel_old.topRows(3) = rot1 * (pos0 - pos1);\n//\tVector3d rel_rot_old = Vector3d::Zero();\n//\tfor (int j=0; j<3; j++) {\n//\t\trel_rot_old += skewSymmetric(rot0.col(j)) * rot1.col(j);\n//\t}\n//\trel_old.bottomRows(3) = 0.5 * rel_rot_old;\n\n\tMatrix4d tf0 = Matrix4d::Identity();\n\ttf0.topLeftCorner(3,3) = rot0;\n\ttf0.topRightCorner(3,1) = pos0;\n\tMatrix4d tf1 = Matrix4d::Identity();\n\ttf1.topLeftCorner(3,3) = rot1;\n\ttf1.topRightCorner(3,1) = pos1;\n\tMatrix4d rel_tf = tf1.inverse() * tf0;\n\n\tVector6d rel;\n\tMatrix3d rel_rot = rot1.transpose() * rot0;\n//\tMatrix3d rel_rot = rel_tf.topLeftCorner(3,3);\n\tVector3d rel_pos = rot1.transpose() * (pos0 - pos1);\n//\tVector3d rel_pos = rel_tf.topRightCorner(3,1);\n\tAngleAxisd rel_rot_aa(rel_rot);\n\trel.topRows(3) = rel_pos;\n\trel.bottomRows(3) = rel_rot_aa.axis() * rel_rot_aa.angle();\n\n\treturn rel;\n}\n\nMatrix6Xd jointSigmaPts(const Vector12d& mean, const Matrix12d& rt_Sigma, BeliefRobotAndDOFPtr rad) {\n\tdouble lambda = 2;\n\tMatrix12d rt_scaled_cov = lambda * rt_Sigma;\n\n\tMatrix6d cov = Matrix6d::Zero();\n\tMatrix6d var1 = Matrix6d::Zero();\n\tMatrix6d var2 = Matrix6d::Zero();\n\n\tdouble w = (1/(2*lambda*lambda));\n\n\tMatrix6Xd sigmapts(6,13);\n\tfor(int i = 0; i < 12; ++i) {\n\t\tVector12d sp = mean + rt_scaled_cov.col(i);\n\t\tVector12d sm = mean - rt_scaled_cov.col(i);\n\n\t\tcov += w * delta(sp.topRows(6), mean.topRows(6)) * delta(sp.bottomRows(6), mean.bottomRows(6)).transpose();\n\t\tcov += w * delta(sm.topRows(6), mean.topRows(6)) * delta(sm.bottomRows(6), mean.bottomRows(6)).transpose();\n\n\t\tvar1 += w * delta(sp.topRows(6), mean.topRows(6)) * delta(sp.topRows(6), mean.topRows(6)).transpose();\n\t\tvar1 += w * delta(sm.topRows(6), mean.topRows(6)) * delta(sm.topRows(6), mean.topRows(6)).transpose();\n\n\t\tvar2 += w * delta(sp.bottomRows(6), mean.bottomRows(6)) * delta(sp.bottomRows(6), mean.bottomRows(6)).transpose();\n\t\tvar2 += w * delta(sm.bottomRows(6), mean.bottomRows(6)) * delta(sm.bottomRows(6), mean.bottomRows(6)).transpose();\n\t}\n\n\tVector6d rel_mean = delta(mean.topRows(6), mean.bottomRows(6));\n\tMatrix6d rel_var = var1+var2-2*cov;\n\n\tcout << \"rel_var\" << endl;\n\tcout << rel_var << endl;\n\n\tEigen::SelfAdjointEigenSolver<MatrixXd> es(rel_var);\n\tMatrix6d sqrt_rel_var = es.eigenvectors().real() * es.eigenvalues().real().cwiseSqrt().asDiagonal() * es.eigenvectors().real().transpose();\n\tsigmapts = rad->sigmaPoints(rel_mean, sqrt_rel_var);\n\n\tcout << \"cov\" << endl;\n\tcout << cov << endl;\n\tcout << \"var1\" << endl;\n\tcout << var1 << endl;\n\tcout << \"var2\" << endl;\n\tcout << var2 << endl;\n\tcout << \"sigmapts\" << endl;\n\tcout << sigmapts << endl;\n\treturn sigmapts;\n}\n\nQuaterniond quatAdd(const Quaterniond& q0, const Quaterniond& q1) {\n\treturn Quaterniond(q0.w()+q1.w(), q0.x()+q1.x(), q0.y()+q1.y(), q0.z()+q1.z());\n}\n\nclass DualQuat {\n\tQuaterniond m_qr;\n\tQuaterniond m_qt;\npublic:\n\tDualQuat(const Quaterniond& qr, const Quaterniond& qt) : m_qr(qr), m_qt(qt) {}\n\tDualQuat operator* (const DualQuat& dq) {\n\t\treturn DualQuat(m_qr*dq.m_qr, quatAdd(m_qr*dq.m_qt, m_qt*dq.m_qr));\n\t}\n\tVectorXd asVectorXd() {\n\t\tVectorXd v(8);\n\t\tv << m_qr.w(), m_qr.x(), m_qr.y(), m_qr.z(), m_qt.w(), m_qt.x(), m_qt.y(), m_qt.z();\n\t\treturn v;\n\t}\n};\n\nDualQuat DOFToDualQuat(const VectorXd& x) {\n\tDualQuat dqt(Quaterniond::Identity(), Quaterniond(0, x(0)/2.0, x(1)/2.0, x(2)/2.0));\n\tQuaterniond qr = Quaterniond::Identity();\n\tif (x.bottomRows(3).norm() > 1e-5)\n\t\tqr = Quaterniond(AngleAxisd(x.bottomRows(3).norm(), x.bottomRows(3).normalized()));\n\tDualQuat dqr(qr, Quaterniond(0,0,0,0));\n\tcout << \"---\" << endl;\n\tcout << dqt.asVectorXd().transpose() << endl;\n\tcout << dqr.asVectorXd().transpose() << endl;\n\tcout << \"---\" << endl;\n\treturn dqt*dqr;\n}\n\nint main() {\n\tRaveInitialize(false, OpenRAVE::Level_Debug);\n\tenv = RaveCreateEnvironment();\n\tenv->StopSimulation();\n\tenv->Load(DATA_DIR\"/boxes.env.xml\");\n\n\n\tvector<RobotBasePtr> robots;\n\tenv->GetRobots(robots);\n\tRobotBasePtr robot = robots[0];\n\tvector<RobotBase::ManipulatorPtr> manips = robot->GetManipulators();\n\n\tBeliefRobotAndDOFPtr rad = RADFromName(\"base3d\", robot);\n\tconst int n_steps = 10;\n\n\tBeliefRobotAndDOFPtr obstacle = RADFromName(\"base3d\", robots[1]);\n\n\tcc = CollisionChecker::GetOrCreate(*env);\n\tviewer.reset(new OSGViewer(env));\n\tenv->AddViewer(viewer);\n\tdynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(0,0,2), osg::Vec3d(0,0,0), osg::Vec3d(0,1,0));\n\n\tviewer->AddKeyCallback('=', boost::bind(&AdjustTransparency, .05));\n\tviewer->AddKeyCallback('-', boost::bind(&AdjustTransparency, -.05));\n\n\t//////////////////////////////////////////////\n\n\tVectorXd x = toVectorXd(rad->GetDOFValues());\n\t//  x << -0.3,0.4,-0.4,0,M_PI_4,M_PI_4/2.0;\n\t//x << -0.3,0.5+0.4,0,0,0,0;\n\trad->SetDOFValues(toDblVec(x));\n\tVectorXd rt_Sigma_diag(6);\n\trt_Sigma_diag << 0.1, 0.1, 0.1, 0.1, 0.1, 0.1;\n\tMatrixXd rt_Sigma = rt_Sigma_diag.asDiagonal();\n\tVectorXd theta;\n\trad->composeBelief(x, rt_Sigma, theta);\n\n\tVectorXd obstacle_x = toVectorXd(obstacle->GetDOFValues());\n\t//obstacle_x << 0.2,0.5+0.25,0,0,0,0;\n\tobstacle->SetDOFValues(toDblVec(obstacle_x));\n\tVectorXd obstacle_rt_Sigma_diag(6);\n\tobstacle_rt_Sigma_diag << 0.1, 0.1, 0.1, 0.1, 0.1, 0.1;\n\tMatrixXd obstacle_rt_Sigma = obstacle_rt_Sigma_diag.asDiagonal();\n\tVectorXd obstacle_theta;\n\tobstacle->composeBelief(obstacle_x, obstacle_rt_Sigma, obstacle_theta);\n\n\trenderSigmaPts(rad, rad->sigmaPoints(theta), osg::Vec4f(0,0,1,0.5));\n\trenderSigmaPts(obstacle, obstacle->sigmaPoints(obstacle_theta), osg::Vec4f(0,0,1,0.5));\n\n\t// plot collisions\n\tvector<Collision> collisions;\n\tDiscreteCheckSigmaSigma(rad, rad->sigmaPoints(theta), obstacle, obstacle->sigmaPoints(obstacle_theta), collisions);\n\tcout << \"collisions \" << collisions.size() << \": \";\n\tfor (int i=0; i<collisions.size(); i++) cout << collisions[i].distance << \" \"; cout << endl;\n\n\t{\n\tVector12d joint_x;\n\tjoint_x.topRows(6) = x;\n\tjoint_x.bottomRows(6) = obstacle_x;\n\tMatrix12d joint_rt_sigma = Matrix12d::Identity();\n\tjoint_rt_sigma.topLeftCorner(6,6) = rt_Sigma;\n\tjoint_rt_sigma.bottomRightCorner(6,6) = obstacle_rt_Sigma;\n\t//joint_rt_sigma.bottomLeftCorner(6,6) = 0.099*Matrix6d::Identity();\n\t//joint_rt_sigma.topRightCorner(6,6) = 0.099*Matrix6d::Identity();\n\n\tMatrix6Xd  rel_sigmapts = jointSigmaPts(joint_x, joint_rt_sigma, rad);\n\n\trenderSigmaPts(rad, rel_sigmapts, osg::Vec4f(0,0,1,0.5));\n\trenderSigmaPts(obstacle, Vector6d::Zero(), osg::Vec4f(0,0,1,0.5));\n\n\tDiscreteCheckSigmaSigma(rad, rel_sigmapts, obstacle, Vector6d::Zero(), collisions);\n\tcollisions.push_back(transformedCollision(collisions.back(), obstacle_x));\n\tcout << \"collisions \" << collisions.size() << \": \";\n\tfor (int i=0; i<collisions.size(); i++) cout << collisions[i].distance << \" \"; cout << endl;\n\t}\n\n\t{\n\tVector12d joint_x;\n\tjoint_x.topRows(6) = obstacle_x;\n\tjoint_x.bottomRows(6) = x;\n\tMatrix12d joint_rt_sigma = Matrix12d::Identity();\n\tjoint_rt_sigma.topLeftCorner(6,6) = obstacle_rt_Sigma;\n\tjoint_rt_sigma.bottomRightCorner(6,6) = rt_Sigma;\n\n\tMatrix6Xd  rel_sigmapts = jointSigmaPts(joint_x, joint_rt_sigma, obstacle);\n\n\trenderSigmaPts(rad, Vector6d::Zero(), osg::Vec4f(0,0,1,0.5));\n\trenderSigmaPts(obstacle, rel_sigmapts, osg::Vec4f(0,0,1,0.5));\n\n\tDiscreteCheckSigmaSigma(obstacle, rel_sigmapts, rad, Vector6d::Zero(), collisions);\n\tcollisions.push_back(transformedCollision(collisions.back(), x));\n\tcout << \"collisions \" << collisions.size() << \": \";\n\tfor (int i=0; i<collisions.size(); i++) cout << collisions[i].distance << \" \"; cout << endl;\n\t}\n\n\tPlotCollisions(collisions, *env, handles, 0);\n\n\tviewer->Idle();\n\n\tenv.reset();\n\tviewer.reset();\n\tRaveDestroy();\n}\n", "meta": {"hexsha": "25a00c49555ac40fbad7669a311c292525033906", "size": 14125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trajopt/test/relative_collision_test.cpp", "max_stars_repo_name": "alexlee-gk/trajopt", "max_stars_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T14:03:38.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-07T14:03:38.000Z", "max_issues_repo_path": "src/trajopt/test/relative_collision_test.cpp", "max_issues_repo_name": "alexlee-gk/trajopt", "max_issues_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "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/trajopt/test/relative_collision_test.cpp", "max_forks_repo_name": "alexlee-gk/trajopt", "max_forks_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "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": 34.1183574879, "max_line_length": 171, "alphanum_fraction": 0.6989026549, "num_tokens": 4548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19423646169227823}}
{"text": "/*\n * Copyright 2013-2017 Michael M. Magruder (https://github.com/mikemag)\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 <algorithm>\n#include <boost/range/adaptor/reversed.hpp>\n#include <cassert>\n#include <cmath>\n#include <stack>\n#include <utility>\n\n#include \"shapes.h\"\n#include \"shape-parts.h\"\n\nnamespace MonkeyCAM {\n\nusing std::string;\nusing std::vector;\n\n// Origin is at the center of the nose. Board extends right (regular\n// foot, of course!)\nBoardShape::BoardShape(string name,\n                       MCFixed noseLength, MCFixed effectiveEdge,\n                       MCFixed tailLength, MCFixed sidecutRadius,\n                       MCFixed waistWidth, MCFixed taper,\n                       std::unique_ptr<ShapeEndPart>& nosePart,\n                       std::unique_ptr<ShapeEdgePart>& edgePart,\n                       std::unique_ptr<ShapeEndPart>& tailPart,\n                       boost::optional<MCFixed> refStance,\n                       boost::optional<MCFixed> setback,\n                       MCFixed bindingDist,\n                       std::unique_ptr<InsertPack>& nosePack,\n                       std::unique_ptr<InsertPack>& tailPack,\n                       std::unique_ptr<InsertPack>& toeInserts,\n                       std::unique_ptr<InsertPack>& centerInserts,\n                       std::unique_ptr<InsertPack>& heelInserts,\n                       MCFixed spacerWidth,\n                       boost::optional<MCFixed> noseEdgeExt,\n                       boost::optional<MCFixed> tailEdgeExt,\n                       bool isSplitboard)\n    : m_name(name)\n    , m_noseLength(noseLength)\n    , m_effectiveEdge(effectiveEdge)\n    , m_tailLength(tailLength)\n    , m_waistWidth(waistWidth)\n    , m_sidecutRadius(sidecutRadius)\n    , m_taper(taper)\n    , m_nosePart(std::move(nosePart))\n    , m_edgePart(std::move(edgePart))\n    , m_tailPart(std::move(tailPart))\n    , m_setback(setback)\n    , m_refStance(refStance)\n    , m_bindingDist(bindingDist)\n    , m_noseInserts(std::move(nosePack))\n    , m_tailInserts(std::move(tailPack))\n    , m_toeInserts(std::move(toeInserts))\n    , m_centerInserts(std::move(centerInserts))\n    , m_heelInserts(std::move(heelInserts))\n    , m_spacerWidth(spacerWidth)\n    , m_noseEdgeExt(noseEdgeExt)\n    , m_tailEdgeExt(tailEdgeExt)\n    , m_isSplitboard(isSplitboard)\n    , m_maxCoreX(0)\n{\n  // Nose and tail width come from the sidecut depth...\n  m_sidecutDepth = m_sidecutRadius -\n    sqrt(((m_sidecutRadius * m_sidecutRadius) -\n         (m_effectiveEdge * m_effectiveEdge / 4)).dbl());\n  m_noseWidth = m_waistWidth + (m_sidecutDepth * 2) + (m_taper / 2);\n  m_tailWidth = m_waistWidth + (m_sidecutDepth * 2) - (m_taper / 2);\n  m_maxCoreX = m_noseLength + m_effectiveEdge + m_tailLength;\n\n  setupInserts();\n}\n\nBoardShape::~BoardShape() {\n  for (auto dps : m_debugPathSets) {\n    delete dps;\n  }\n}\n\nconst Point BoardShape::leftGuideHole(const Machine& machine) const {\n  return Point(-machine.guideHoleOffset(), 0);\n}\n\nconst Point BoardShape::rightGuideHole(const Machine& machine) const {\n  return Point(m_maxCoreX + machine.guideHoleOffset(), 0);\n}\n\nDebugPathSet& BoardShape::addDebugPathSet(std::string header) {\n  auto dps = new DebugPathSet { header };\n  m_debugPathSets.push_back(dps);\n  return *dps;\n}\n\n// Counter-clockwise from lower left.\nPath formRectanglePath(Point ll, Point ur) {\n  Path p;\n  p.push_back(ll);\n  p.push_back(Point(ur.X, ll.Y));\n  p.push_back(ur);\n  p.push_back(Point(ll.X, ur.Y));\n  p.push_back(ll);\n  return p;\n}\n\n// Pocket a given path. Result paths are in order from outside in.\n// @TODO: factor with the core top profile code.\nvector<vector<Path>> pocket(\n  const Path& outerPath,\n  const Tool& tool,\n  double toolOverlapPercentage,\n  MCFixed depth\n) {\n  // Offset the outer path until the offset disappears. nb: the first\n  // path must be offset by half the tool diameter to ensure we follow\n  // the limiting path correctly.\n  vector<vector<Path>> pathSets;\n  MCFixed offset = -tool.diameter * 0.5;\n  for (int i = 1; i < 100; i++) { // Artifical upper limit\n    auto paths = PathUtils::OffsetPath(outerPath, offset);\n    if (paths.empty()) break; // All done!\n    // Reverse each path so we're conventional cutting the pocket walls.\n    for (auto& path : paths) {\n      std::reverse(path.begin(), path.end());\n      std::transform(path.begin(), path.end(), path.begin(),\n                     [&](const Point& p) { return Point(p.X, p.Y, depth); });\n    }\n    pathSets.push_back(paths);\n    offset -= tool.diameter * toolOverlapPercentage;\n  }\n  return pathSets;\n}\n\n// Build an overall board shape, which is the true finished shape of\n// the board.\n//\n// Path is counterclockwise, start point at (0,0,0).\n//\n// NB: the Machine parameter is for informational purposes only! Board\n// shapes are independent of the machine, materials, or cutting\n// methods.\nconst Path& BoardShape::buildOverallPath(const Machine& machine) {\n  if (m_overallPath.size() != 0) return m_overallPath;\n  MCFixed noseEndX = 0;\n  MCFixed noseTranX = m_noseLength;\n  MCFixed eeCenterX = noseTranX + m_effectiveEdge / 2;\n  MCFixed tailTranX = noseTranX + m_effectiveEdge;\n  MCFixed tailEndX = tailTranX + m_tailLength;\n  MCFixed noseHalfWidth = m_noseWidth / 2;\n  MCFixed waistHalfWidth = m_waistWidth / 2;\n  MCFixed tailHalfWidth = m_tailWidth / 2;\n  auto np = m_nosePart->generate(Point(noseEndX, 0),\n                                 Point(noseTranX, -noseHalfWidth));\n  auto ep = m_edgePart->generate(Point(noseTranX, -noseHalfWidth),\n                                 Point(eeCenterX, -waistHalfWidth),\n                                 Point(tailTranX, -tailHalfWidth));\n  auto tp = m_tailPart->generate(Point(tailEndX, 0),\n                                 Point(tailTranX, -tailHalfWidth));\n  m_overallPath.push_back_path(np);\n  m_overallPath.push_back_path(ep);\n  m_overallPath.push_back_path(tp);\n  m_overallPath.push_back_path(MirroredPath(tp));\n  m_overallPath.push_back_path(MirroredPath(ep));\n  m_overallPath.push_back_path(MirroredPath(np));\n  assert(m_overallPath.size() > 0);\n  DebugPathSet& dps = addDebugPathSet(\"Overall shape\");\n  dps.addDescription(\n    \"<p>The overall shape of the board is the final, finished outline of the \"\n    \"ski or snowboard. None of the generated G-Code programs actually cuts \"\n    \"this shape, though the base shape with the edges amounts to the same \"\n    \"thing. It is shown with inserts and other guide lines to present a fairly \"\n    \"complete picture of the final board.</p>\");\n  dps.addDescription(\n    \"<ul>\"\n    \"<li>Total length: %scm</li>\"\n    \"<li>Nose / effective edge / tail length: %scm / %scm / %scm</li>\"\n    \"<li>Nose / waist / tail width: %scm / %scm / %scm</li>\"\n    \"<li>Taper: %scm</li>\"\n    \"<li>Sidecut radius / depth: %scm / %scm</li>\"\n    \"<li>Reference stance width: %s</li>\"\n    \"<li>Setback: %s</li>\"\n    \"<li>Binding distance (ski boot length or snowboard stance width): %s</li>\"\n    \"<li>Board area: %.3fcm<sup>2</sup></li>\"\n    \"<li>Extension of metal edge towards nose: %s</li>\"\n    \"<li>Extension of metal edge towards tail: %s</li>\"\n    \"</ul>\",\n    overallLength().str().c_str(),\n    m_noseLength.str().c_str(), m_effectiveEdge.str().c_str(),\n      m_tailLength.str().c_str(),\n    m_noseWidth.str().c_str(), m_waistWidth.str().c_str(),\n      m_tailWidth.str().c_str(),\n    m_taper.str().c_str(),\n    m_sidecutRadius.str().c_str(), m_sidecutDepth.str().c_str(),\n    MCFixed::strWithSuffix(m_refStance).c_str(),\n    MCFixed::strWithSuffix(m_setback).c_str(),\n    MCFixed::strWithSuffix(m_bindingDist).c_str(),\n    PathUtils::Area(m_overallPath),\n    MCFixed::strWithSuffix(m_noseEdgeExt).c_str(),\n    MCFixed::strWithSuffix(m_tailEdgeExt).c_str()\n  );\n  if (m_isSplitboard) {\n    dps.addDescription(\n      \"<h3>Splitboards</h3>\"\n      \"<p>Splitboards are created by adding space down the middle of the \"\n      \"board for a blade to cut the board in half after layup. This 'gap' is \"\n      \"not shown in the overall shape shown here but it is reflected in all of \"\n      \"the G-Code programs generated to cut the core.</p>\"\n    );\n  }\n  dps.addPath([&] {\n      return DebugPath {\n        m_overallPath,\n        DebugAnnotationDesc {\n          \"Overall shape\"\n        }\n      };\n    });\n  dps.addAnnotation([&] {\n      auto a = DebugAnnotation {\n        DebugAnnotationDesc {\n          \"Width guides\",\n          \"Guidelines to mark key widths of the board: nose/tail maximum \"\n          \"width, and waist width.\",\n          \"blue\", true\n        }\n      };\n      a.addSvgFormat(\n        R\"(<path d=\"M%f %f L%f %f M%f %f L%f %f M%f %f L%f %f\"/>)\",\n        noseTranX.dbl(), (-noseHalfWidth + 1).dbl(),\n        noseTranX.dbl(), (noseHalfWidth - 1).dbl(),\n        eeCenterX.dbl(), (-waistHalfWidth + 1).dbl(),\n        eeCenterX.dbl(), (waistHalfWidth - 1).dbl(),\n        tailTranX.dbl(), (-tailHalfWidth + 1).dbl(),\n        tailTranX.dbl(), (tailHalfWidth - 1).dbl()\n      );\n      return a;\n    });\n  dps.addAnnotation([&] {\n      auto a = DebugAnnotation {\n        DebugAnnotationDesc {\n          \"True center guide\",\n          \"Guideline to mark true center of the board.\",\n          \"orange\", true\n        }\n      };\n      MCFixed trueCenterX = (m_noseLength + m_effectiveEdge + m_tailLength) / 2;\n      a.addSvgFormat(\n        R\"(<path d=\"M%f %f L%f %f\"/>)\",\n        trueCenterX.dbl(), (-waistHalfWidth + 5).dbl(),\n        trueCenterX.dbl(), (waistHalfWidth - 5).dbl()\n      );\n      return a;\n    });\n  dps.addAnnotation([&] {\n      auto a = DebugAnnotation {\n        DebugAnnotationDesc {\n          \"Inserts\",\n          \"All inserts. The larger circle is the outter rim, the smaller \"\n          \"circle is the shaft hole.\", \"blue\"\n        }\n      };\n      for (auto& p : m_insertsPath) {\n        a.addSvgCircle(p, machine.insertRimDiameter());\n        a.addSvgCircle(p, machine.insertHoleDiameter());\n      }\n      return a;\n    });\n  if (m_refStance) {\n    dps.addAnnotation([&] {\n      auto a = DebugAnnotation {\n        DebugAnnotationDesc {\n          \"Reference stance and setback\",\n          \"The center insert group in each pack. By default, these groups are \"\n          \"centered across the waist of the board, i.e., the center of the \"\n          \"effective edge, plus the setback.\",\n          \"green\", true\n        }\n      };\n      MCFixed setback = 0.0;\n      if (m_setback) {\n        setback = *m_setback;\n      }\n      a.addSvgCircle(Point(eeCenterX - (*m_refStance / 2) + setback, 0), 0.5);\n      a.addSvgCircle(Point(eeCenterX + (*m_refStance / 2) + setback, 0), 0.5);\n      a.addSvgFormat(\n        R\"(<path d=\"M%f %f L%f %f\"/>)\",\n        (eeCenterX + setback).dbl(), -4.0,\n        (eeCenterX + setback).dbl(), 4.0);\n      return a;\n    });\n  }\n  if (m_bindingDist > 0.0) {\n    dps.addAnnotation([&] {\n      auto a = DebugAnnotation {\n        DebugAnnotationDesc {\n          \"Binding distance (ski boot length or snowboard stance width) and setback\",\n          \"Binding insert groups. By default, these groups are centered \"\n          \"across the waist of the board, i.e., the center of the \"\n          \"effective edge, plus the setback.\",\n          \"green\", true\n        }\n      };\n      MCFixed setback = 0.0;\n      if (m_setback) {\n        setback = *m_setback;\n      }\n      a.addSvgCircle(Point(eeCenterX - (m_bindingDist / 2) + setback, 0), 0.5);\n      a.addSvgCircle(Point(eeCenterX + (m_bindingDist / 2) + setback, 0), 0.5);\n      a.addSvgFormat(\n        R\"(<path d=\"M%f %f L%f %f\"/>)\",\n        (eeCenterX + setback).dbl(), -4.0,\n        (eeCenterX + setback).dbl(), 4.0);\n      return a;\n    });\n  }\n  return m_overallPath;\n}\n\nconst void BoardShape::addCoreCenterComment(GCodeWriter& g) {\n  auto centerX = m_noseLength + (m_effectiveEdge / 2);\n  g.headerComment(\"* Center of the board in G54:\");\n  g.headerCommentF(\"    X=%s Y=0.0000 Z=0.0000\", centerX.inchesStr().c_str());\n}\n\nconst Path BoardShape::spreadPathForSplitboards(const Path& p,\n                                                const Machine& machine) {\n  if (m_isSplitboard) {\n    return SpreadYPath(p, machine.splitboardCenterGap());\n  }\n  return p;\n}\n\nconst Point BoardShape::spreadPointForSplitboards(const Point& p,\n                                                  const Machine& machine) {\n  if (m_isSplitboard) {\n    Point q = p;\n    if (q.Y < 0) {\n      q.Y -= machine.splitboardCenterGap() / 2;\n    } else {\n      q.Y += machine.splitboardCenterGap() / 2;\n    }\n    return q;\n  }\n  return p;\n}\n\n\ntemplate<class TIter>\nvoid roundSpacerEnds(Path& path, TIter beginIt, TIter endIt,\n                     Point startPoint, MCFixed endX,\n                     MCFixed bpStartHandleYDelta,\n                     MCFixed bpEndHandleXDelta) {\n  auto start = std::find(beginIt, endIt, startPoint);\n  assert(start != endIt);\n  auto end = std::find_if(start, endIt,\n                          [&] (const Point& p) {\n                            if (startPoint.X > endX) {\n                              return p.X <= endX;\n                            } else {\n                              return p.X >= endX;\n                            }\n                          });\n  assert(end != endIt);\n  auto curveEndControl = *end +\n    ((*end - *(end - 1)).toVector2D().toUnitVector() * bpEndHandleXDelta.dbl());\n  BezierPath bp {\n    *start,\n    Point(start->X, start->Y + bpStartHandleYDelta),\n    curveEndControl,\n    *end\n  };\n  Path newPath;\n  newPath.insert(newPath.end(), beginIt, start);\n  newPath.insert(newPath.end(), bp.begin(), bp.end());\n  newPath.insert(newPath.end(), end, endIt);\n  path = newPath;\n}\n\n// Generate the shape of the core for a board with sidewalls, and\n// nose/tail inset to accomodate nose/tail spacers.\n//\n// The edge portion of the core extends out past the real edges by the\n// configured sidewall overhang, typically ~2mm. This gives us a bit\n// of extra play side-to-side which allows the core and base to be\n// slightly mis-aligned.\n//\n// The nose and tail portions are set inward by the width of the nose\n// and tail spacers.\n//\n// The end portions are joined to the edge portion with a gentle arc.\nconst Path& BoardShape::buildCorePath(const Machine& machine) {\n  if (m_corePath.size() != 0) return m_corePath;\n  // 1. Offset the overall path inward by the spacer size.\n  auto spacerClip = PathUtils::OffsetPath(buildOverallPath(machine),\n                                          -m_spacerWidth);\n  assert(spacerClip.size() == 1);\n\n  // 2. Form squares for the nose and tail which cut the nose and tail\n  // off at the end of the effective edge. These will become the\n  // shapes of the nose and tail spacers.\n  Path noseSpacerSquare;\n  MCFixed noseSpacerX = -machine.spacerEndOverhang();\n  MCFixed noseSpacerY = (m_noseWidth / 2) + machine.spacerSideOverhang();\n  noseSpacerSquare.push_back(Point(noseSpacerX, -noseSpacerY));\n  noseSpacerSquare.push_back(Point(m_noseLength, -noseSpacerY));\n  noseSpacerSquare.push_back(Point(m_noseLength, noseSpacerY));\n  noseSpacerSquare.push_back(Point(noseSpacerX, noseSpacerY));\n  noseSpacerSquare.push_back(Point(noseSpacerX, -noseSpacerY));\n  Path tailSpacerSquare;\n  MCFixed tailSpacerX1 = m_noseLength + m_effectiveEdge;\n  MCFixed tailSpacerX2 = tailSpacerX1 + m_tailLength +\n    machine.spacerEndOverhang();\n  MCFixed tailSpacerY = (m_tailWidth / 2) + machine.spacerSideOverhang();\n  tailSpacerSquare.push_back(Point(tailSpacerX1, -tailSpacerY));\n  tailSpacerSquare.push_back(Point(tailSpacerX2, -tailSpacerY));\n  tailSpacerSquare.push_back(Point(tailSpacerX2, tailSpacerY));\n  tailSpacerSquare.push_back(Point(tailSpacerX1, tailSpacerY));\n  tailSpacerSquare.push_back(Point(tailSpacerX1, -tailSpacerY));\n\n  // 3. Clip the squares from #2, removing the area defined by #1.\n  auto spacers = PathUtils::ClipPathsDifference(\n    vector<Path> { noseSpacerSquare, tailSpacerSquare }, spacerClip);\n  assert(spacers.size() == 2);\n\n  // 4. Round the inner corners of the of results.\n  auto& noseSpacerPath = spacers[0];\n  auto& tailSpacerPath = spacers[1];\n  if (spacers[0][0].X > spacers[1][0].X) {\n    std::swap(noseSpacerPath, tailSpacerPath);\n  }\n  // @TODO: make these control points a bit more configurable.\n  if (m_noseLength > m_spacerWidth + 4) {\n    roundSpacerEnds(noseSpacerPath,\n                    noseSpacerPath.begin(), noseSpacerPath.end(),\n                    Point(m_noseLength, -noseSpacerY), m_noseLength - 4,\n                    4, -4);\n    roundSpacerEnds(noseSpacerPath,\n                    noseSpacerPath.rbegin(), noseSpacerPath.rend(),\n                    Point(m_noseLength, noseSpacerY), m_noseLength - 4,\n                    -4, -4);\n    std::reverse(noseSpacerPath.begin(), noseSpacerPath.end());\n  }\n  if (m_tailLength > m_spacerWidth + 4) {\n    roundSpacerEnds(tailSpacerPath,\n                    tailSpacerPath.rbegin(), tailSpacerPath.rend(),\n                    Point(tailSpacerX1, -tailSpacerY), tailSpacerX1 + 4,\n                    4, -4);\n    std::reverse(tailSpacerPath.begin(), tailSpacerPath.end());\n    roundSpacerEnds(tailSpacerPath,\n                    tailSpacerPath.begin(), tailSpacerPath.end(),\n                    Point(tailSpacerX1, tailSpacerY), tailSpacerX1 + 4,\n                    -4, -4);\n  }\n\n  // 4.5. The nose and tail spacer paths we have now are what we'll\n  // need when generating cut programs later, so hang onto them.\n  m_noseSpacerPath = noseSpacerPath;\n  m_tailSpacerPath = tailSpacerPath;\n\n  // 5. Offset the overall path outward by the sidewall overhang.\n  auto overhang = PathUtils::OffsetPath(m_overallPath,\n                                        machine.sidewallOverhang());\n  assert(overhang.size() == 1);\n\n  // 6. Clip the area from #5 with the results of #4, taking the inner\n  // volume as the final core path.\n  auto final = PathUtils::ClipPathsDifference(overhang, spacers);\n  assert(final.size() == 1);\n  m_corePath = final[0];\n  DebugPathSet& dps = addDebugPathSet(\"Core shape\");\n  dps.addDescription(\n    \"<p>This is the final shape of the core with sidewalls and extra room \"\n    \"(%scm) for nose and tail spacer material. The sidewalls overhang the \"\n    \"true edge of the board by %scm.</p>\",\n    m_spacerWidth.str().c_str(),\n    machine.sidewallOverhang().str().c_str()\n  );\n  if (m_isSplitboard) {\n    dps.addDescription(\n      \"<h3>Splitboards</h3>\"\n      \"<p>Splitboards are created by adding space down the middle of the \"\n      \"board for a blade to cut the board in half after layup. This 'gap' is \"\n      \"not shown in the core shape shown here but it is reflected in all of \"\n      \"the G-Code programs generated to cut the core.</p>\"\n    );\n  }\n  dps.addPath([&] {\n      return DebugPath {\n        m_corePath,\n        DebugAnnotationDesc {\n          \"Core shape\",\n          \"The final shape of the core, including sidewall overhang past the \"\n          \"edges.\"\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        m_overallPath,\n        DebugAnnotationDesc {\n          \"Overall shape\",\n            \"The final shape of the board, including edges.\",\n            \"green\", true\n        }\n      };\n    });\n  dps.addAnnotation([&] {\n      auto a = DebugAnnotation {\n        DebugAnnotationDesc {\n          \"Width guides\",\n          \"Guidelines to mark key widths of the board: nose/tail maximum \"\n          \"width, waist width, and the true center of the board (shorter \"\n          \"line).\", \"blue\", true\n        }\n      };\n      MCFixed trueCenterX = (m_noseLength + m_effectiveEdge + m_tailLength) / 2;\n      MCFixed noseTranX = m_noseLength;\n      MCFixed eeCenterX = noseTranX + m_effectiveEdge / 2;\n      MCFixed tailTranX = noseTranX + m_effectiveEdge;\n      MCFixed noseHalfWidth = m_noseWidth / 2;\n      MCFixed waistHalfWidth = m_waistWidth / 2;\n      MCFixed tailHalfWidth = m_tailWidth / 2;\n      a.addSvgFormat(\n        R\"(<path d=\"M%f %f L%f %f M%f %f L%f %f M%f %f L%f %f M%f %f L%f %f\"/>)\",\n        noseTranX.dbl(), (-noseHalfWidth + 4).dbl(),\n        noseTranX.dbl(), (noseHalfWidth - 4).dbl(),\n        eeCenterX.dbl(), (-waistHalfWidth + 1).dbl(),\n        eeCenterX.dbl(), (waistHalfWidth - 1).dbl(),\n        trueCenterX.dbl(), (-waistHalfWidth + 5).dbl(),\n        trueCenterX.dbl(), (waistHalfWidth - 5).dbl(),\n        tailTranX.dbl(), (-tailHalfWidth + 4).dbl(),\n        tailTranX.dbl(), (tailHalfWidth - 4).dbl()\n      );\n      return a;\n    });\n  return m_corePath;\n}\n\nvoid BoardShape::setupInserts() {\n  MCFixed stanceX = 0.0;\n  if (m_bindingDist > 0.0) {\n    stanceX = m_bindingDist / 2;\n  } else if (m_refStance) {\n    stanceX = *m_refStance / 2;\n  }\n  MCFixed eeCenterX = m_noseLength + m_effectiveEdge / 2;\n  MCFixed setback = 0.0;\n  if (m_setback) {\n    setback = *m_setback;\n  }\n  if (m_noseInserts) {\n    m_noseInserts->moveIntoPosition(Point(-stanceX + setback + eeCenterX, 0));\n    auto p = m_noseInserts->insertsPath();\n    m_insertsPath.insert(m_insertsPath.end(), p.begin(), p.end());\n    m_insertsPath.push_back(Point(m_noseInserts->maxPoint().X + 4, 0)); // Pin\n  }\n  if (m_tailInserts) {\n    m_tailInserts->moveIntoPosition(Point(stanceX + setback + eeCenterX, 0));\n    m_insertsPath.push_back(Point(m_tailInserts->minPoint().X - 4, 0)); // Pin\n    auto p = m_tailInserts->insertsPath();\n    m_insertsPath.insert(m_insertsPath.end(), p.begin(), p.end());\n  }\n  if (m_toeInserts) {\n    m_toeInserts->moveIntoPosition(Point(-stanceX + setback + eeCenterX, 0));\n    auto p = m_toeInserts->insertsPath();\n    m_insertsPath.insert(m_insertsPath.end(), p.begin(), p.end());\n  }\n  if (m_centerInserts) {\n    MCFixed xOffset = setback + eeCenterX;\n    MCFixed yOffset = 0;\n    if (m_isSplitboard) {\n      // Splitboards use the center group for the touring\n      // inserts. These are relative to the center of the board, with\n      // no setback, with the two outer inserts of the touring bracket\n      // on the center line, placing the pivot point just a bit\n      // towards the nose of the centerline.\n      //\n      // @TODO: is this reasonable? Assumes the centerline of the\n      // board is the balance point of the board, which may not be\n      // true due to taper and core profile.\n      xOffset = (m_noseLength + m_effectiveEdge + m_tailLength) / 2;\n      // Center the touring bracket on the left half of the board.\n      yOffset = -m_waistWidth / 4;\n    }\n    m_centerInserts->moveIntoPosition(Point(xOffset, yOffset));\n    auto p = m_centerInserts->insertsPath();\n    m_insertsPath.insert(m_insertsPath.end(), p.begin(), p.end());\n    if (m_isSplitboard) {\n      // Duplicate the center pack for splitboards across the centerline.\n      m_centerInserts->moveIntoPosition(Point(0, m_waistWidth / 2));\n      p = m_centerInserts->insertsPath();\n      m_insertsPath.insert(m_insertsPath.end(), p.begin(), p.end());\n    }\n  }\n  if (m_heelInserts) {\n    m_heelInserts->moveIntoPosition(Point(stanceX + setback + eeCenterX, 0));\n    auto p = m_heelInserts->insertsPath();\n    m_insertsPath.insert(m_insertsPath.end(), p.begin(), p.end());\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// gcode generators\n\n//------------------------------------------------------------------------------\n// Base Cutout\n\nconst GCodeWriter BoardShape::generateBaseCutout(const Machine& machine) {\n  auto tool = machine.tool(machine.baseCutoutTool());\n  auto overallPath = buildOverallPath(machine);\n\n  // For splitboards we emit only the left half of the base. Since all\n  // boards are currently symmetrical, one can simply flip the base\n  // material and run again to get the other half.\n  if (m_isSplitboard) {\n    Path leftHalf;\n    for (auto& p : overallPath) {\n      if (p.Y > 0.0) continue;\n      leftHalf.emplace_back(p);\n    }\n    overallPath = leftHalf;\n  }\n\n  // 1. Get path assuming full wrap of metal edge\n  auto fullWrapPath = PathUtils::OffsetPath(overallPath, -0.2);\n  assert(fullWrapPath.size() == 1);\n\n  // 2. Form box outlining limit of metal edges (whole board if no partial edges)\n  MCFixed noseEdgeX = 0;\n  if (m_noseEdgeExt) {\n    noseEdgeX += (m_noseLength - *m_noseEdgeExt);\n  }\n  MCFixed tailEdgeX = m_noseLength + m_effectiveEdge + m_tailLength;\n  if (m_tailEdgeExt) {\n    tailEdgeX -= (m_tailLength - *m_tailEdgeExt);\n  }\n  MCFixed boxHalfWidth = std::max(std::max(m_noseWidth, m_waistWidth),\n                                  m_tailWidth) / 2 + 1;\n  Path edgeLimitBox;\n  edgeLimitBox.push_back(Point(noseEdgeX, -boxHalfWidth));\n  edgeLimitBox.push_back(Point(tailEdgeX, -boxHalfWidth));\n  edgeLimitBox.push_back(Point(tailEdgeX, boxHalfWidth));\n  edgeLimitBox.push_back(Point(noseEdgeX, boxHalfWidth));\n  edgeLimitBox.push_back(Point(noseEdgeX, -boxHalfWidth));\n\n  // 3. Clip square\n  auto clippedEdgeBox = PathUtils::ClipPathsDifference(\n    vector<Path> {edgeLimitBox} , fullWrapPath);\n\n  // 4. Use clipped square to clip base cutout shape\n  auto paths = PathUtils::ClipPathsDifference(\n    vector<Path> {m_overallPath} , clippedEdgeBox);\n  assert(paths.size() == 1);\n  auto trueBasePath = paths[0];\n\n  // 5. Offset to get tool path\n  auto offsetPaths = PathUtils::OffsetPath(trueBasePath, tool.diameter / 2);\n  assert(offsetPaths.size() == 1);\n  auto op = offsetPaths[0];\n\n  DebugPathSet& dps = addDebugPathSet(\"Base Cutout\");\n  if (m_isSplitboard) {\n    dps.addDescription(\n      \"<p>For splitboards, we only generate the left half of the base. Since \"\n      \"boards are symmetrical, one can simply flip the base material and run \"\n      \"the program again to get the right half.</p>\");\n  }\n  dps.addPath([&] {\n      return DebugPath {\n        op,\n        DebugAnnotationDesc {\n          \"Base cutout path\",\n          \"The path used to cut the base.\"\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        trueBasePath,\n        DebugAnnotationDesc {\n          \"Base\",\n            \"The final shape of the base material.\",\n            \"orange\", true\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        m_overallPath,\n        DebugAnnotationDesc {\n          \"Overall shape\",\n            \"The final shape of the board, including edges.\",\n            \"green\", true\n        }\n      };\n    });\n  GCodeWriter g(m_name + \"-base-cutout.nc\", tool,\n                GCodeWriter::TableTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), machine.baseRapidHeight());\n  addCoreCenterComment(g);\n  g.rapidToPoint(op[0]);\n  g.spindleOn();\n  g.emitPath(op, machine.baseCutThruHeight());\n  g.rapidToPoint(op[0]);\n  g.spindleOff();\n  g.close();\n  return g;\n}\n\n//------------------------------------------------------------------------------\n// Core guide holes\n\nconst GCodeWriter BoardShape::generateGuideHoles(const Machine& machine) {\n  // Guide holes: left hole is in negative X near the nose of the\n  // board, right hole is beyond the end of the tail. Each hole is\n  // 1/2\" diameter, and placed 1/4\" away from the overall board shape\n  // to leave room for a 1/4\" cutter releasing the core.\n  auto rapidHeight = machine.bottomRapidHeight();\n  auto holeDepth = machine.guideHoleDepth();\n  auto holeDia = machine.guideHoleDiameter();\n  auto tool = machine.tool(machine.guideHoleTool());\n  DebugPathSet& dps = addDebugPathSet(\"Guide Holes\");\n  GCodeWriter g(m_name + \"-guide-holes.nc\", tool,\n                GCodeWriter::MaterialTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), rapidHeight);\n  g.comment(\"Guide holes should be milled first so we can re-align the core if \"\n            \"something goes wrong.\");\n  addCoreCenterComment(g);\n  g.line();\n  g.spindleOn();\n  g.rapidToPoint(leftGuideHole(machine));\n  g.emitIncrementalHole(holeDia, holeDepth, rapidHeight, 3);\n  g.rapidToPoint(rightGuideHole(machine));\n  g.emitIncrementalHole(holeDia, holeDepth, rapidHeight, 3);\n  g.spindleOff();\n  g.close();\n  dps.addAnnotation([&] {\n      auto a = DebugAnnotation {\n        DebugAnnotationDesc {\n          \"Guide holes\",\n          \"Guide holes placed beyond the ends of the board.\"\n        }\n      };\n      a.addSvgCircle(leftGuideHole(machine), holeDia);\n      a.addSvgCircle(rightGuideHole(machine), holeDia);\n      return a;\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        spreadPathForSplitboards(m_overallPath, machine),\n        DebugAnnotationDesc {\n          \"Overall shape\",\n            \"The final shape of the board, including edges.\",\n            \"green\", true\n        }\n      };\n    });\n  return g;\n}\n\n//------------------------------------------------------------------------------\n// Core alignment marks\n\nconst Path BoardShape::alignmentMarksPath(const Machine& machine) {\n  // Alignment marks, based off of the core nose/waist/tail control\n  // points, set in a smidge.\n  auto eeCenterX = (m_effectiveEdge / 2) + m_noseLength;\n  auto boardLength = m_noseLength + m_effectiveEdge + m_tailLength;\n  auto boardCenterX = boardLength / 2;\n  auto markXOffset = machine.alignmentMarkOffset();\n  auto markYOffset = machine.alignmentMarkOffset() +\n    machine.edgeGrooveEdgeWidth();\n  auto markDepth = machine.alignmentMarkDepth();\n  auto centerMarkDepth = markDepth;\n  if (m_isSplitboard) {\n    // There is a center edge groove on splitboards, so we need to mark in that.\n    centerMarkDepth += machine.edgeGrooveDepth();\n  }\n  auto deepMarkDepth = machine.alignmentMarkDeepDepth();\n  Path marks;\n  // Nose, two spaced a 10cm apart to make it easy to strike a good pencil line.\n  marks.push_back(Point(m_spacerWidth + markXOffset, 0, centerMarkDepth));\n  marks.push_back(Point(m_spacerWidth + markXOffset + 10, 0, centerMarkDepth));\n  // Tail\n  marks.push_back(Point(boardLength - m_spacerWidth - markXOffset, 0,\n                        centerMarkDepth));\n  marks.push_back(Point(boardLength - m_spacerWidth - markXOffset - 10, 0,\n                        centerMarkDepth));\n  // Overall center\n  marks.push_back(Point(boardCenterX, (m_waistWidth / 2) - markYOffset,\n                        markDepth));\n  marks.push_back(Point(boardCenterX, 0, centerMarkDepth));\n  marks.push_back(Point(boardCenterX, (-m_waistWidth / 2) + markYOffset,\n                        markDepth));\n  // EE center\n  marks.push_back(Point(eeCenterX, (m_waistWidth / 2) - markYOffset,\n                        markDepth));\n  marks.push_back(Point(eeCenterX, 0, centerMarkDepth));\n  marks.push_back(Point(eeCenterX, (-m_waistWidth / 2) + markYOffset,\n                        markDepth));\n  // Extra deep mark above the guide holes, to assist with\n  // re-alignment of the machine in case of a crash.\n  auto leftDeepMark = leftGuideHole(machine) + Point(0, MCFixed::fromInches(1));\n  leftDeepMark.Z = deepMarkDepth;\n  marks.push_back(leftDeepMark);\n  auto rightDeepMark = rightGuideHole(machine) + Point(0,\n                                                       MCFixed::fromInches(1));\n  rightDeepMark.Z = deepMarkDepth;\n  marks.push_back(rightDeepMark);\n  // Sort the marks to reduce cutter movement. Forming a graph and\n  // finding the shortest path would be ideal, but more trouble than\n  // it's worth for this.\n  std::sort(marks.begin(), marks.end());\n  return marks;\n}\n\nconst GCodeWriter BoardShape::generateCoreAlignmentMarks(\n  const Machine& machine)\n{\n  auto marks = alignmentMarksPath(machine);\n  auto tool = machine.tool(machine.alignmentMarkTool());\n  DebugPathSet& dps = addDebugPathSet(\"Core Alignment Marks\");\n  dps.addPath([&] {\n      return DebugPath {\n        spreadPathForSplitboards(buildCorePath(machine), machine),\n        DebugAnnotationDesc {\n          \"Core shape\",\n          \"The final shape of the core, including sidewalls with overhang.\",\n          \"green\", true\n        }\n      };\n    });\n  auto a = DebugAnnotation {\n    DebugAnnotationDesc {\n      \"Alignment Marks\",\n      \"Small dimples placed on the bottom of the core which mark key locations \"\n      \"and are useful for aligning the base to the core. \"\n      \"Note: these are <b>very small</b> in the diagram, but they do \"\n      \"accuratley represent the diameter of the dimple which will be left in \"\n      \"the core. Zoom in!\",\n      \"red\"\n    }\n  };\n  GCodeWriter g(m_name + \"-core-alignment-marks.nc\", tool,\n                GCodeWriter::MaterialTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), machine.bottomRapidHeight());\n  addCoreCenterComment(g);\n  g.spindleOn();\n  for (auto& p : marks) {\n    g.rapidToPoint(p);\n    g.feedToPoint(p);\n    a.addSvgCircle(p, p.Z * -2);\n  }\n  g.rapidToPoint(marks.back());\n  g.spindleOff();\n  g.close();\n  dps.addAnnotation([&] { return a; });\n  return g;\n}\n\n//------------------------------------------------------------------------------\n// Core edge groove\n\nconst GCodeWriter BoardShape::generateCoreEdgeGroove(const Machine& machine) {\n  auto overallPath = spreadPathForSplitboards(buildOverallPath(machine),\n                                              machine);\n  auto tool = machine.tool(machine.edgeGrooveTool());\n  auto edgeWidth = machine.edgeGrooveEdgeWidth(); // Entire edge, not just tines\n  auto grooveWidth = machine.sidewallOverhang() + edgeWidth;\n  assert(grooveWidth >= tool.diameter);\n  DebugPathSet& dps = addDebugPathSet(\"Edge Groove\");\n  dps.addDescription(\n    \"<p>The edge groove creates a rabbet along the perimeter of the core, \"\n    \"leaving space for the edge material so the core still sits flat on the \"\n    \"base material. It is created by machining a shallow trench %scm wide into \"\n    \"the base of the core which matches precisely the edge of the core when it \"\n    \"is finally cut out. Because of the sidewall overhang this ends up being \"\n    \"slightly wider than the final rabbet width. The rabbet width should also \"\n    \"be a bit wider than the exact edge material width to leave a little play \"\n    \"when aligning the core to the base.</p>\",\n    grooveWidth.str().c_str());\n  dps.addDescription(\n    \"<p>Since the width of the rabbet is typically larger than the cutter \"\n    \"used, multiple machining passes are required.</p>\");\n  dps.addPath([&] {\n      return DebugPath {\n        spreadPathForSplitboards(buildCorePath(machine), machine),\n        DebugAnnotationDesc {\n          \"Core shape\",\n          \"The final shape of the core, including sidewalls with overhang.\",\n          \"green\", true\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        PathUtils::OffsetPath(overallPath, -edgeWidth)[0],\n        DebugAnnotationDesc {\n          \"Groove outer edge\",\n          \"The final, outer edge of the groove. This is a bit beyond the edge \"\n          \"of the overall shape and matches the sidewall extension.\",\n          \"orange\", true\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        PathUtils::OffsetPath(overallPath,\n                              grooveWidth - edgeWidth)[0],\n        DebugAnnotationDesc {\n          \"Groove inner edge\",\n          \"The final, inner edge of the groove.\",\n          \"orange\", true\n        }\n      };\n    });\n  // Outer path is exact, inner path is exact. Build others inbetween\n  // as appropriate.\n  auto stepOffset = tool.diameter * machine.edgeGrooveOverlapPercentage();\n  auto currentOffset = machine.sidewallOverhang() - (tool.diameter / 2);\n  auto endOffset = -machine.edgeGrooveEdgeWidth() + (tool.diameter / 2);\n  auto grooveDepth = machine.edgeGrooveDepth();\n  vector<vector<Path>> groovePathSets;\n  while (true) {\n    auto paths = PathUtils::OffsetPath(overallPath, currentOffset);\n    assert(paths.size() == 1);\n    std::transform(paths[0].begin(), paths[0].end(), paths[0].begin(),\n                   [&](const Point& p) { return Point(p.X, p.Y, grooveDepth); });\n    groovePathSets.push_back(paths);\n    dps.addPath([&] {\n        return DebugPath {\n          paths[0],\n          DebugAnnotationDesc {\n            \"Edge groove toolpaths\",\n            \"The toolpaths which will cut the edge groove.\"\n          }\n        };\n      });\n    if (currentOffset == endOffset) break;\n    currentOffset -= stepOffset;\n    if (currentOffset < endOffset) currentOffset = endOffset;\n  }\n\n  // Add a center groove for splitboards. This groove is straight down\n  // the middle of the board, twice the edge width (one edge on each\n  // half) plus the gap width.\n  vector<vector<Path>> centerGroovePathSets;\n  if (m_isSplitboard) {\n    auto centerGrooveWidth = edgeWidth * 2 + machine.splitboardCenterGap();\n    assert(centerGrooveWidth >= tool.diameter);\n    auto halfGroove = centerGrooveWidth / 2;\n    auto centerGroovePath = formRectanglePath(\n      Point(-machine.sidewallOverhang(), -halfGroove),\n      Point(m_noseLength + m_effectiveEdge + m_tailLength +\n            machine.sidewallOverhang(), halfGroove));\n\n    centerGroovePathSets = pocket(centerGroovePath, tool,\n                                  machine.edgeGrooveOverlapPercentage(),\n                                  grooveDepth);\n\n    dps.addDescription(\n      \"<p>Splitboards get a groove down the center, too, to allow for an edge \"\n      \"on each half including the gap between halves.</p>\");\n\n    for (auto& pathSet : centerGroovePathSets) {\n      for (auto& path : pathSet) {\n        dps.addPath([&] {\n            return DebugPath {\n              path,\n              DebugAnnotationDesc {\n                \"Splitboard center groove path\",\n                \"The paths used to pocket the center groove.\",\n                \"blue\"\n              }\n            };\n          });\n      }\n    }\n    dps.addPath([&] {\n        return DebugPath {\n          centerGroovePath,\n          DebugAnnotationDesc {\n            \"Splitboard center groove\",\n            \"The final center groove, including the splitboard center gap.\",\n            \"purple\", true\n          }\n        };\n      });\n  }\n\n  GCodeWriter g(m_name + \"-core-edge-groove.nc\", tool,\n                GCodeWriter::MaterialTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), machine.bottomRapidHeight());\n  addCoreCenterComment(g);\n  g.spindleOn();\n  g.emitPathSets(groovePathSets, true, machine.bottomRapidHeight(), 0,\n                 machine.normalSpeed());\n  if (m_isSplitboard) {\n    g.comment(\"Center groove for splitboard\");\n    g.emitPathSets(centerGroovePathSets, true, machine.bottomRapidHeight(), 0,\n                   machine.normalSpeed());\n  }\n  g.spindleOff();\n  g.close();\n  return g;\n}\n\n//------------------------------------------------------------------------------\n// Insert bowls and holes\n\n// Moves from the edge of the previous ring to the edge of the new ring.\nvoid emitInsertBowlRing(GCodeWriter& g, MCFixed prevDia, MCFixed dia,\n                        MCFixed depth) {\n  g.feedToPoint(Point(0, (dia - prevDia) / 2, depth));\n  g.emitIncrementalCircle(dia);\n}\n\n// Assumes the cutter is at the center of the bowl, at the material top.\nvoid emitBowl(GCodeWriter& g, MCFixed outerRimDia, MCFixed outerRimDepth) {\n  vector<std::pair<MCFixed, MCFixed>> bowl {\n    { outerRimDia, outerRimDepth },\n    { MCFixed::fromInches(0.6928), MCFixed::fromInches(-0.0070) },\n    { MCFixed::fromInches(0.6404), MCFixed::fromInches(-0.0065) },\n    { MCFixed::fromInches(0.5878), MCFixed::fromInches(-0.0059) },\n    { MCFixed::fromInches(0.5348), MCFixed::fromInches(-0.0054) },\n    { MCFixed::fromInches(0.4818), MCFixed::fromInches(-0.0049) },\n    { MCFixed::fromInches(0.4284), MCFixed::fromInches(-0.0044) },\n    { MCFixed::fromInches(0.3750), MCFixed::fromInches(-0.0039) }\n  };\n  g.setIncremental();\n  auto lastDia = g.tool().diameter; // By definition, the tool makes a hole ;)\n  for (auto& p : bowl) {\n    emitInsertBowlRing(g, lastDia, p.first, p.second);\n    lastDia = p.first;\n  }\n  g.setAbsolute();\n}\n\n// Cut insert hole centred on current cutter location\nvoid emitInsert(GCodeWriter& g, const Machine& machine,\n                MCFixed heightAboveMaterial) {\n  auto outerRimDia = machine.insertRimDiameter();\n  auto outerRimDepth = machine.insertRimDepth();\n  auto insertCenterHoleDia = machine.insertHoleDiameter();\n  auto insertCenterHoleDepth = -machine.coreBlankThickness();\n  g.comment(\"A single insert\");\n  g.commentF(\"  Outer rim diameter = %s\\\"\",\n    outerRimDia.inchesStr().c_str());\n  g.commentF(\"  Outer rim depth    = %s\\\"\",\n    outerRimDepth.inchesStr().c_str());\n  g.commentF(\"  Shaft diameter      = %s\\\"\",\n    insertCenterHoleDia.inchesStr().c_str());\n  g.commentF(\"  Shaft depth         = %s\\\"\",\n    insertCenterHoleDepth.inchesStr().c_str());\n  auto startPosition = g.currentPosition();\n  if (heightAboveMaterial > 0) {\n    g.feedToPoint(g.currentPosition() + Point(0, 0, -heightAboveMaterial));\n  }\n  auto holeCenter = g.currentPosition();\n  emitBowl(g, outerRimDia, outerRimDepth);\n  g.feedToPoint(holeCenter);\n  g.emitIncrementalHole(insertCenterHoleDia, insertCenterHoleDepth, 0, 3);\n  // Run the bowl again to clean it up.\n  emitBowl(g, outerRimDia, outerRimDepth);\n  g.rapidToPoint(startPosition);\n}\n\nconst GCodeWriter BoardShape::generateInsertHoles(const Machine& machine) {\n  if (m_insertsPath.size() == 0) {\n    return GCodeWriter();\n  }\n  auto tool = machine.tool(machine.insertHolesTool());\n  auto rapidHeight = machine.bottomRapidHeight();\n  GCodeWriter g(m_name + \"-core-insert-holes.nc\", tool,\n                GCodeWriter::MaterialTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), rapidHeight);\n  addCoreCenterComment(g);\n  g.spindleOn();\n  for (auto& p : m_insertsPath) {\n    g.rapidToPoint(spreadPointForSplitboards(p, machine));\n    emitInsert(g, machine, rapidHeight);\n  }\n  g.spindleOff();\n  g.close();\n  return g;\n}\n\n//------------------------------------------------------------------------------\n// Core top profile\n\nconst GCodeWriter BoardShape::generateTopProfile(const Machine& machine,\n                                                 BoardProfile& profile) {\n  auto tool = machine.tool(machine.topProfileTool());\n  // nb: use the overall path plus the sidewall overhang to limit the\n  // profiling paths. This ensures the entire sidewall, even outside\n  // the final edge, is profiled. It does mean we'll profile too much\n  // on the nose and tail, since those are inset by the nose and tail\n  // spacers, but that's an acceptable tradeoff for the simplicity of\n  // this.\n  auto overallPath = spreadPathForSplitboards(buildOverallPath(machine),\n                                              machine);\n  auto offsetPaths = PathUtils::OffsetPath(overallPath,\n                                           machine.sidewallOverhang());\n  // nb: the roughing support is pretty experimental right now!!\n#if ROUGHING\n  bool roughing = machine.topProfileRoughing();\n#else\n  bool roughing = false; // @TODO: roughing is a work in-progress. Don't use it.\n#endif\n  assert(offsetPaths.size() == 1);\n  auto overallOffset = offsetPaths[0];\n  DebugPathSet& dps = addDebugPathSet(\"Top Profile\");\n  dps.addDescription(\"<p>These are the paths which apply the thickness profile \"\n                     \"to the top of the core. They are joined inside-out, with \"\n                     \"a lead-in of %s\\\" to the beginning of each island. A \"\n                     \"%s\\\" cutter is used with an overlap of %.2f&#37;.</p>\",\n                     machine.topProfileLeadinLength().inchesStr().c_str(),\n                     tool.diameter.inchesStr().c_str(),\n                     machine.topProfileOverlapPercentage() * 100.0);\n  if (roughing) {\n    dps.addDescription(\"<p>Roughing paths are included, which limit the depth \"\n                       \"of cut to reduce cutter load. They are overlapped with \"\n                       \"the final thickness profile here.</p>\");\n  }\n  dps.addPath([&] {\n    return DebugPath {\n      spreadPathForSplitboards(buildCorePath(machine), machine),\n      DebugAnnotationDesc {\n        \"Core shape\",\n        \"The final shape of the core, including sidewalls with overhang.\",\n        \"green\", true\n      }\n    };\n  });\n  profile.debugPathSet().addPath([&] {\n    return DebugPath {\n      buildCorePath(machine),\n      DebugAnnotationDesc {\n        \"Core shape\",\n        \"The final shape of the core, including sidewalls with overhang.\",\n        \"green\", true\n      }\n    };\n  });\n  dps.addPath([&] {\n    return DebugPath {\n      overallOffset,\n      DebugAnnotationDesc {\n        \"Outer profile pocket edge\",\n        \"The outer edge of the pocket formed when machining the thickness \"\n        \"profile. This is represents the limit of the material removed.\",\n        \"orange\", true\n      }\n    };\n  });\n\n  auto exp = [](const Path& p) { // Exaggerate a path in Y\n    Path ep = p;\n    std::transform(ep.begin(), ep.end(), ep.begin(),\n                   [](const Point& p) { return Point(p.X, p.Y * 10); });\n    return ep;\n  };\n  struct PathRange {\n    MCFixed depth;\n    Path::const_iterator begin;\n    Path::const_iterator end;\n  };\n  typedef vector<PathRange> PathRanges;\n  auto boxFromRange = [&](const PathRange& range) -> Path {\n    auto x1 = (*range.begin).X;\n    if (x1 == profile.path().begin()->X) {\n      x1 -= 1;\n    }\n    auto x2 = (*(range.end - 1)).X;\n    if (x2 == (profile.path().end() - 1)->X) {\n      x2 += 1;\n    }\n    auto y = (maxWidth() / 2) + 1;\n    Path p;\n    p.push_back({x1, -y});\n    p.push_back({x2, -y});\n    p.push_back({x2, y});\n    p.push_back({x1, y});\n    p.push_back({x1, -y});\n    return p;\n  };\n\n  vector<Path> roughingProfilePaths;\n  vector<Path> roughingBoxes;\n\n  if (roughing) {\n    DebugPathSet& rdps = addDebugPathSet(\"Top Profile Roughing\");\n    rdps.addDescription(\"<p>Roughing passes for the core top profile. This \"\n                        \"shows the depth for each roughing pass. All profile \"\n                        \"paths are exaggerated by 10x.</p>\");\n    rdps.addPath([&] {\n      return DebugPath {\n        exp(profile.path()),\n        DebugAnnotationDesc {\n          \"Final Profile\",\n          \"The final profile path, exaggeragted 10x.\",\n          \"red\", true }\n      };\n    });\n    rdps.addPath([&] {\n      return DebugPath {\n        overallOffset,\n        DebugAnnotationDesc {\n          \"Offset overall\", \"Limit of material removed by top profiling.\",\n          \"blue\", true }\n      };\n    });\n\n    MCFixed roughingOffset = machine.topProfileRoughingOffset();\n    Path roughProf = PathUtils::OffsetOpenPath(profile.path(), roughingOffset);\n    std::reverse(roughProf.begin(), roughProf.end()); // Keep it left-to-right\n\n    auto roughLevel = [](const PathRange& range,\n                         MCFixed upperLimit) -> PathRanges {\n      PathRanges newRanges;\n      bool rangeStarted = false;\n      PathRange npr;\n      npr.depth = upperLimit;\n      for (auto i = range.begin; i != range.end; ++i) {\n        if (i->Y < upperLimit) {\n          if (!rangeStarted) {\n            rangeStarted = true;\n            npr.begin = i;\n          }\n        } else {\n          if (rangeStarted) {\n            rangeStarted = false;\n            npr.end = i;\n            newRanges.push_back(npr);\n          }\n        }\n      }\n      if (rangeStarted) {\n        npr.end = range.end;\n        newRanges.push_back(npr);\n      }\n      return newRanges;\n    };\n\n    // Build roughing profile paths and bounding boxes we can use to\n    // clip the overall path later.\n    std::stack<PathRange> rangeStack;\n    rangeStack.push({ machine.coreBlankThickness(),\n          roughProf.begin(), roughProf.end() });\n    while (rangeStack.size() > 0) {\n      auto r = rangeStack.top(); rangeStack.pop();\n      auto newUpperLimit = r.depth - machine.topProfileRoughingMaxCutDepth();\n      auto minPoint = std::min_element(r.begin, r.end,\n                                       [](const Point& p1, const Point& p2) {\n                                         return p1.Y < p2.Y;\n                                       });\n      if (newUpperLimit - minPoint->Y < machine.topProfileRoughingFuzz()) {\n        newUpperLimit = minPoint->Y;\n      }\n      // Pull out the portion of the profile path within the range,\n      // limiting its depth tothe new upper limit.\n      Path rp;\n      std::for_each(r.begin, r.end,\n                    [&](const Point& p) {\n                      rp.push_back({p.X, std::max(p.Y, newUpperLimit)});\n                    });\n      roughingProfilePaths.push_back(rp);\n      auto roughingBox = boxFromRange(r);\n      roughingBoxes.push_back(roughingBox);\n      auto ep = exp(rp);\n      rdps.addPath([&] {\n        return DebugPath {\n          ep,\n          DebugAnnotationDesc { \"Roughing Profile\",\n            \"Each rouging profile. These show the depth of cut for each \"\n            \"roughing pass, and are used to select and deform portions of the \"\n            \"final profiling paths.\", \"purple\", true }\n        };\n      });\n      // Find new ranges below the path we just formed.\n      for (auto r2 : roughLevel(r, newUpperLimit)) {\n        rangeStack.push(r2);\n      }\n    }\n  }\n  // Finally, add on the real profile path and a box to contain it.\n  roughingProfilePaths.push_back(profile.path());\n  roughingBoxes.push_back(\n    boxFromRange({ 0, profile.path().begin(), profile.path().end() }));\n\n  vector<vector<vector<Path>>> cutGroups;\n  for (uint i = 0; i < roughingProfilePaths.size(); i++) {\n    vector<vector<Path>> pathSets;\n    auto& roughingProfile = roughingProfilePaths[i];\n    auto& roughingBox = roughingBoxes[i];\n    // Offset the profile path to account for the width of the cutter.\n    auto profileOffset = ToolOffsetPath(roughingProfile, tool.diameter);\n    // Offset the outer path until the offset disappears. nb: the first\n    // path must be offset by half the tool diameter to ensure we follow\n    // the limiting path correctly.\n    double overlap = 0.5;\n    for (int i = 1; i < 100; i++) { // Artifical upper limit\n      auto resultPaths = PathUtils::OffsetPath(overallOffset,\n                                               -tool.diameter * overlap * i);\n      if (resultPaths.empty()) break; // All done!\n      // Deform each path with the profile.\n      vector<Path> deformedResults;\n      for (auto& path : resultPaths) {\n        Path& p = path;\n        if (roughing) {\n          auto cp = PathUtils::ClipPathsIntersect({path}, {roughingBox});\n          if (cp.size() == 0) continue; // A bit on the other end, outside the box\n          assert(cp.size() == 1);\n          p = cp[0];\n        }\n        std::reverse(p.begin(), p.end());\n        auto dp = ProfiledPath(p, profileOffset);\n        deformedResults.push_back(dp);\n        dps.addPath([&] {\n          return DebugPath {\n            dp,\n            DebugAnnotationDesc {\n              \"Top profile path\",\n              \"The paths used to profile the core.\", \"red\", true\n            }\n          };\n        });\n      }\n      pathSets.push_back(deformedResults);\n      overlap = machine.topProfileOverlapPercentage(); // Use real overlap % now\n    }\n    cutGroups.push_back(pathSets);\n  }\n  auto rapidHeight = machine.topRapidHeight();;\n  GCodeWriter g(m_name + \"-top-profile.nc\", tool,\n                GCodeWriter::TableTop, GCodeWriter::YIsPartCenter,\n                machine.topProfileDeepSpeed(), rapidHeight);\n  addCoreCenterComment(g);\n  g.spindleOn();\n  for (auto& pathSets : cutGroups) {\n    g.emitPathSets(pathSets, true, rapidHeight,\n                   machine.topProfileLeadinLength(),\n                   machine.topProfileTransitionSpeed());\n  }\n  g.spindleOff();\n  g.close();\n  return g;\n}\n\n//------------------------------------------------------------------------------\n// Nose and tail spacer cutouts\n\nconst GCodeWriter BoardShape::generateNoseTailSpacerCutout(\n  const Machine& machine)\n{\n  DebugPathSet& dps = addDebugPathSet(\"Nose Tail Spacers\");\n  dps.addDescription(\n    \"<p>Nose and tail spacers are thin sections of PTEX which act as sidewalls \"\n    \"along the nose and tail to protect the core. They are typically a bit \"\n    \"wider than normal sidewalls to act as a bit more of a 'bumper' against \"\n    \"impact. The spacers are cut wider and longer than necessary to ensure \"\n    \"they overlap the edges well, and for simplicity.</p>\");\n  auto tool = machine.tool(machine.baseCutoutTool());\n  auto nosePath = spreadPathForSplitboards(m_noseSpacerPath, machine);\n  auto tailPath = spreadPathForSplitboards(m_tailSpacerPath, machine);\n  dps.addPath([&] {\n      return DebugPath {\n        nosePath,\n        DebugAnnotationDesc {\n          \"Nose spacer\",\n          \"The shape of the nose spacer. Note that we only cut the curve which \"\n          \"interfaces with the core. The rest of the shape depends on the \"\n          \"length and width of your material.\",\n          \"orange\", true\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        tailPath,\n        DebugAnnotationDesc {\n          \"Tail spacer\",\n          \"The shape of the tail spacer. Note that we only cut the curve which \"\n          \"interfaces with the core. The rest of the shape depends on the \"\n          \"length and width of your material.\",\n          \"orange\", true\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        spreadPathForSplitboards(buildCorePath(machine), machine),\n        DebugAnnotationDesc {\n          \"Core shape\",\n          \"The final shape of the core, including sidewalls with overhang.\",\n          \"green\", true\n        }\n      };\n    });\n\n  // Offset each\n  auto ops = PathUtils::OffsetPath(nosePath, tool.diameter / 2);\n  assert(ops.size() == 1);\n  auto onp = ops[0];\n  ops = PathUtils::OffsetPath(tailPath, tool.diameter / 2);\n  assert(ops.size() == 1);\n  auto otp = ops[0];\n\n  // Trim out just the path that cuts the interface with the core\n  auto lb = nosePath[0];\n  auto ub = Point(lb.X + m_noseLength + machine.spacerEndOverhang() + 1, -lb.Y);\n  auto trimmer = [&](const Point& p) {\n    return (p.X < lb.X) || (p.X > ub.X) ||\n    (p.Y < lb.Y) || (p.Y > ub.Y);\n  };\n  auto e = std::remove_if(onp.begin(), onp.end(), trimmer);\n  onp.resize(std::distance(onp.begin(), e));\n\n  lb = tailPath[0] - Point(1, 0);\n  ub = Point(lb.X + m_tailLength + machine.spacerEndOverhang(), -lb.Y);\n  e = std::remove_if(otp.begin(), otp.end(), trimmer);\n  otp.resize(std::distance(otp.begin(), e));\n  otp.erase(otp.begin()); // First element of the tail is redundant with the end\n\n  dps.addPath([&] {\n      return DebugPath {\n        onp,\n        DebugAnnotationDesc {\n          \"Nose cut path\",\n          \"The path used to cut the nose spacer.\"\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        otp,\n        DebugAnnotationDesc {\n          \"Tail cut path\",\n          \"The path used to cut the tail spacer.\"\n        }\n      };\n    });\n\n  // Shift the nose right so it starts at X=0.\n  auto nShift = -nosePath[0].X;\n  assert(nShift >= 0);\n  std::transform(onp.begin(), onp.end(), onp.begin(),\n                 [&](const Point& p) { return p + Point(nShift, 0); });\n\n  // Shift the tail left so it comes within 2cm of the nose path.\n  auto nmax = std::max_element(onp.begin(), onp.end(),\n                               [](const Point& a, const Point& b) {\n                                 return a.X < b.X;\n                               });\n  auto tShift = nmax->X + 2 - otp[0].X;\n  assert(tShift <= 0);\n  std::transform(otp.begin(), otp.end(), otp.begin(),\n                 [&](const Point& p) { return p + Point(tShift, 0); });\n\n  GCodeWriter g(m_name + \"-nose-tail-spacers.nc\", tool,\n                GCodeWriter::TableTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), machine.baseRapidHeight());\n  auto materialLength = m_noseLength + m_tailLength + 2 +\n    machine.spacerEndOverhang() * 2;\n  addCoreCenterComment(g);\n  g.headerComment();\n  g.headerCommentF(\"Spacer material length: %s\\\" [%scm]\",\n                   materialLength.inchesStr().c_str(),\n                   materialLength.str().c_str());\n  g.headerComment();\n  g.rapidToPoint(onp[0]);\n  g.spindleOn();\n  g.emitPath(onp, machine.baseCutThruHeight());\n  g.rapidToPoint(otp[0]);\n  g.emitPath(otp, machine.baseCutThruHeight());\n  g.rapidToPoint(onp[0]);\n  g.spindleOff();\n  g.close();\n  return g;\n}\n\n//------------------------------------------------------------------------------\n// Core edge trench\n\n// Extend a path which is open, i.e., a line, on both ends the given\n// length.\nvoid extendLine(Path& p, MCFixed length) {\n  assert(p.size() > 1);\n  auto newStart = p[0] + ((p[0] - p[1]).toVector2D().toUnitVector() *\n                          length.dbl());\n  auto e = p.size() - 1;\n  auto newEnd = p[e] + ((p[e] - p[e - 1]).toVector2D().toUnitVector() *\n                        length.dbl());\n  p[0] = newStart;\n  p[e] = newEnd;\n}\n\nconst GCodeWriter BoardShape::generateEdgeTrench(const Machine& machine) {\n  // The outer edge of the edge trench is at the sidewall overhang.\n  // We need to move the edge of the overall shape to the center of\n  // the edge trench so we can offset it evenly on each side.\n  DebugPathSet& dps = addDebugPathSet(\"Edge Trench\");\n  auto& overallPath = spreadPathForSplitboards(buildOverallPath(machine),\n                                               machine);\n  auto etCenterAdjust = machine.sidewallOverhang() -\n    (machine.edgeTrenchWidth() / 2);\n  auto etCenterOverallPaths = PathUtils::OffsetPath(overallPath,\n                                                    etCenterAdjust);\n  assert(etCenterOverallPaths.size() == 1);\n  auto etCenterOverallPath = etCenterOverallPaths[0];\n\n  // Use two rectangles which will contain the nose and tail to trim\n  // out the edge paths. These extend an extra 1 unit past the ends\n  // and sides to ensure containtment of the shape.\n  auto noseTrimPath = formRectanglePath(\n    spreadPointForSplitboards(Point(-1, -(m_noseWidth / 2) - 1), machine),\n    spreadPointForSplitboards(Point(m_noseLength, (m_noseWidth / 2) + 1),\n                              machine));\n  auto tailTrimPath = formRectanglePath(\n    spreadPointForSplitboards(\n      Point(m_noseLength + m_effectiveEdge,\n            -(m_tailWidth / 2) - 1), machine),\n    spreadPointForSplitboards(\n      Point(m_noseLength + m_effectiveEdge + m_tailLength + 1,\n            (m_tailWidth / 2) + 1), machine));\n  auto etCenterPaths = PathUtils::ClipPathsDifference(\n    vector<Path> { etCenterOverallPath },\n    vector<Path> { noseTrimPath, tailTrimPath });\n  assert(etCenterPaths.size() == 1);\n  auto etCenterPath = etCenterPaths[0];\n\n  // Now pull out the individual center lines for the trenches from\n  // the trimmed path. These are not real Paths since they are open.\n  Path etLowerCenter;\n  etLowerCenter.resize(etCenterPath.size());\n  auto end = std::copy_if(\n    etCenterPath.begin(), etCenterPath.end() - 1,\n    etLowerCenter.begin(),\n    [](const Point& p) { return p.Y < 0; });\n  etLowerCenter.resize(std::distance(etLowerCenter.begin(), end));\n  end = std::remove_if(\n    etCenterPath.begin(), etCenterPath.end() - 1,\n    [](const Point& p) { return p.Y < 0; });\n  etCenterPath.resize(std::distance(etCenterPath.begin(), end));\n  auto etUpperCenter = etCenterPath;\n\n  // Extend each center line to clear the core. NB: add twice the\n  // cutter radius to leave room for the rounded corners on both\n  // ends.\n  //\n  // @TODO: older versions of MonkeyCAM used to compute the\n  // intersection with the core path, then extend from there, so older\n  // extension values were quite a bit shorter. That is preferable,\n  // and I should adjust this to do the same one day.\n  auto tool = machine.tool(machine.coreCutoutTool());\n  extendLine(etUpperCenter, machine.edgeTrenchExtension() +\n             (tool.diameter / 2));\n  extendLine(etLowerCenter, machine.edgeTrenchExtension() +\n             (tool.diameter / 2));\n\n  // Form the trench paths by offseting the two centerlines.\n  auto trenches =\n    PathUtils::OffsetLines(vector<Path> { etLowerCenter, etUpperCenter},\n                           machine.edgeTrenchWidth() / 2);\n  assert(trenches.size() == 2);\n\n  // Offset the trenches inwards for machining.\n  auto ps = PathUtils::OffsetPath(trenches[0], -tool.diameter / 2);\n  assert(ps.size() == 1);\n  auto t1 = ps[0];\n  std::reverse(t1.begin(), t1.end());\n  ps = PathUtils::OffsetPath(trenches[1], -tool.diameter / 2);\n  assert(ps.size() == 1);\n  auto t2 = ps[0];\n  std::reverse(t2.begin(), t2.end());\n\n  dps.addDescription(\n    \"<p>The edge trenches provide space in which to place a different type \"\n    \"of wood along the effective edge, as well as sidewall material. The outer \"\n    \"edge of the trenches matches the edge of the core precisely, including \"\n    \"the sidewall overhang. The trench is %scm wide and extends %scm past the \"\n    \"ends of the effective edge.</p>\",\n    machine.edgeTrenchWidth().str().c_str(),\n    (machine.edgeTrenchExtension() + (tool.diameter / 2)).str().c_str()\n  );\n  dps.addPath([&] {\n      return DebugPath {\n        t1,\n        DebugAnnotationDesc {\n          \"Edge Trench Path\",\n          \"The path used to cut the edge trench.\"\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        t2,\n        DebugAnnotationDesc {\n          \"Edge Trench Path\",\n          \"The path used to cut the edge trench.\"\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        trenches[0],\n        DebugAnnotationDesc {\n          \"Edge Trench\",\n          \"The final shape of the edge trench.\",\n          \"blue\", true\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        trenches[1],\n        DebugAnnotationDesc {\n          \"Edge Trench\",\n          \"The final shape of the edge trench.\",\n          \"blue\", true\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        spreadPathForSplitboards(buildCorePath(machine), machine),\n        DebugAnnotationDesc {\n          \"Core shape\",\n          \"The final shape of the core, including sidewalls with overhang.\",\n          \"orange\", true\n        }\n      };\n    });\n\n  GCodeWriter g(m_name + \"-edge-trench.nc\", tool,\n                GCodeWriter::TableTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), machine.topRapidHeight());\n  addCoreCenterComment(g);\n  g.rapidToPoint(t1[0]);\n  g.spindleOn();\n  g.emitSpiralPath(t1, machine.coreBlankThickness(), 3);\n  g.rapidToPoint(t1[0]);\n  g.rapidToPoint(t2[0]);\n  g.emitSpiralPath(t2, machine.coreBlankThickness(), 3);\n  g.rapidToPoint(t2[0]);\n  g.spindleOff();\n  g.close();\n  return g;\n}\n\nconst GCodeWriter BoardShape::generateSplitboardCenterTrench(\n  const Machine& machine\n) {\n  DebugPathSet& dps = addDebugPathSet(\"Splitboard Center Trench\");\n\n  // The center trench for a splitboard is straight, and extends the\n  // entire length of the core, plus twice the cutter radius to leave\n  // room for the rounded corners on both ends.\n  auto tool = machine.tool(machine.coreCutoutTool());\n  assert(machine.splitboardCenterTrenchWidth() >= tool.diameter);\n  auto halfCTW =  machine.splitboardCenterTrenchWidth() / 2;\n  auto centerTrenchPath = formRectanglePath(\n    Point(m_spacerWidth - (tool.diameter / 2), -halfCTW),\n    Point(m_noseLength + m_effectiveEdge + m_tailLength - m_spacerWidth +\n          (tool.diameter / 2), halfCTW));\n\n  // Offset the trenches inwards for machining.\n  auto ps = PathUtils::OffsetPath(centerTrenchPath, -tool.diameter / 2);\n  assert(ps.size() == 1);\n  auto cto = ps[0];\n  std::reverse(cto.begin(), cto.end());\n\n  dps.addDescription(\n    \"<p>The center trench for splitboards provides space in which to place \"\n    \"sidewall material for the inner edges of the splitboard. \"\n    \"Note carefully that the gap between the board halves, defined by the \"\n    \"'splitboard center gap' machine parameter, means that you will have a \"\n    \"bit less than half of your sidewall material on each half of the \"\n    \"board.</p>\"\n    \"<p>The trench is %scm wide and extends %scm past the \"\n    \"ends of the core. The splitboard center gap is %scm wide.</p>\"\n    \"<p>This is generated as a separate program because complicated edge and \"\n    \"center inlays could be too much for one glue-up. This gives the option of \"\n    \"doing the center seperate from the edges if one wishes. Otherwise, this \"\n    \"can be run right after the edge trench program with the same machine \"\n    \"setup.</p>\",\n    machine.splitboardCenterTrenchWidth().str().c_str(),\n    (tool.diameter / 2).str().c_str(),\n    machine.splitboardCenterGap().str().c_str()\n  );\n  dps.addPath([&] {\n      return DebugPath {\n        cto,\n        DebugAnnotationDesc {\n          \"Splitboard Center Trench Path\",\n          \"The path used to cut the splitboard center trench.\"\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        centerTrenchPath,\n        DebugAnnotationDesc {\n          \"Splitboard Center Trench\",\n          \"The final shape of the splitboard center trench.\",\n          \"blue\", true\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        spreadPathForSplitboards(buildCorePath(machine), machine),\n        DebugAnnotationDesc {\n          \"Core shape\",\n          \"The final shape of the core, including sidewalls with overhang.\",\n          \"orange\", true\n        }\n      };\n    });\n\n  GCodeWriter g(m_name + \"-splitboard-center-trench.nc\", tool,\n                GCodeWriter::TableTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), machine.topRapidHeight());\n  addCoreCenterComment(g);\n  g.rapidToPoint(cto[0]);\n  g.spindleOn();\n  g.emitSpiralPath(cto, machine.coreBlankThickness(), 3);\n  g.rapidToPoint(cto[0]);\n  g.spindleOff();\n  g.close();\n  return g;\n}\n\n//------------------------------------------------------------------------------\n// Core top cutout\n//\n// The core cutout leaves \"tabs\" on the last pass to hold the core\n// within the core blank for removal later. This makes it a lot easier\n// to hold the core down if you don't have vacuum hold down.\n\nconst GCodeWriter BoardShape::generateTopCutout(const Machine& machine) {\n  DebugPathSet& dps = addDebugPathSet(\"Core Top Cutout\");\n  // Offset the core path as usual\n  auto tool = machine.tool(machine.coreCutoutTool());\n  auto paths = PathUtils::OffsetPath(\n    spreadPathForSplitboards(buildCorePath(machine), machine),\n    tool.diameter / 2);\n  assert(paths.size() == 1);\n  auto op = paths[0];\n  dps.addPath([&] {\n      return DebugPath {\n        op,\n        DebugAnnotationDesc {\n          \"Core top cutout path\",\n          \"The path used to cut the final core.\"\n        }\n      };\n    });\n  dps.addPath([&] {\n      return DebugPath {\n        spreadPathForSplitboards(buildCorePath(machine), machine),\n        DebugAnnotationDesc {\n          \"Core shape\",\n          \"The final shape of the core, including sidewalls with overhang.\",\n          \"orange\", true\n        }\n      };\n    });\n\n  // Form a tab profile path\n  Path tabProfile;\n  auto quarterEELength = m_effectiveEdge / 4;\n  auto boardLength = m_noseLength + m_effectiveEdge + m_tailLength;\n  auto boardCenterX = boardLength / 2;\n  auto leftTabX = boardCenterX - quarterEELength;\n  auto rightTabX = boardCenterX + quarterEELength;\n  MCFixed cutThroughDepth = MCFixed::fromInches(-0.010);\n  MCFixed tabHeight = MCFixed::fromInches(0.080);\n  tabProfile.push_back(Point(-1, cutThroughDepth));\n  tabProfile.push_back(Point(leftTabX - 3, cutThroughDepth));\n  tabProfile.push_back(Point(leftTabX - 1, tabHeight));\n  tabProfile.push_back(Point(leftTabX + 1, tabHeight));\n  tabProfile.push_back(Point(leftTabX + 3, cutThroughDepth));\n  tabProfile.push_back(Point(rightTabX - 3, cutThroughDepth));\n  tabProfile.push_back(Point(rightTabX - 1, tabHeight));\n  tabProfile.push_back(Point(rightTabX + 1, tabHeight));\n  tabProfile.push_back(Point(rightTabX + 3, cutThroughDepth));\n  tabProfile.push_back(Point(boardLength + 1, cutThroughDepth));\n  // Now deform the cutout path with the tab profile.\n  auto profPath = ProfiledPath(op, tabProfile);\n\n  GCodeWriter g(m_name + \"-top-cutout.nc\", tool,\n                GCodeWriter::TableTop, GCodeWriter::YIsPartCenter,\n                machine.normalSpeed(), machine.topRapidHeight());\n  addCoreCenterComment(g);\n  g.rapidToPoint(profPath[0]);\n  g.spindleOn();\n  g.emitSpiralPath(profPath, machine.coreBlankThickness(),\n                   machine.coreCutoutPasses());\n  g.rapidToPoint(profPath[0]);\n  g.spindleOff();\n  g.close();\n  return g;\n}\n\n} // namespace MonkeyCAM\n", "meta": {"hexsha": "dc70a8dfedfafc40d4a6c2fc118ecfeb3143dd53", "size": 68399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "engine/core/shapes.cpp", "max_stars_repo_name": "jstone801/MonkeyCAM", "max_stars_repo_head_hexsha": "e8be45f0ca410bd19cf6ea0196946ef754809776", "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": "engine/core/shapes.cpp", "max_issues_repo_name": "jstone801/MonkeyCAM", "max_issues_repo_head_hexsha": "e8be45f0ca410bd19cf6ea0196946ef754809776", "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": "engine/core/shapes.cpp", "max_forks_repo_name": "jstone801/MonkeyCAM", "max_forks_repo_head_hexsha": "e8be45f0ca410bd19cf6ea0196946ef754809776", "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.5612300934, "max_line_length": 85, "alphanum_fraction": 0.6215003143, "num_tokens": 17642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19422425888809033}}
{"text": "\n// source: http://dlib.net/dnn_mmod_ex.cpp.html\n#include \"mmod.h\"\n#include \"widget.h\"\n\n#include <AnnotatorLib/Annotation.h>\n#include <AnnotatorLib/Commands/NewAnnotation.h>\n#include <AnnotatorLib/Frame.h>\n#include <AnnotatorLib/Session.h>\n\n#include <dlib/data_io.h>\n#include <dlib/gui_widgets.h>\n#include <dlib/image_processing.h>\n#include <dlib/opencv/cv_image.h>\n#include <dlib/svm_threaded.h>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <ctype.h>\n#include <iostream>\n#include <memory>\n\n#include <chrono>\n#include <thread>\n\nusing namespace Annotator::Plugins;\n\nAnnotator::Plugins::MMOD::MMOD() { widget.setMMOD(this); }\n\nMMOD::~MMOD() {}\n\nQString MMOD::getName() { return \"MMOD\"; }\n\nQWidget *MMOD::getWidget() { return &widget; }\n\nbool MMOD::setFrame(shared_ptr<Frame> frame, cv::Mat image) {\n  this->lastFrame = this->frame;\n  this->frame = frame;\n  this->frameImg = image;\n  return lastFrame != frame;\n}\n\n// first call\nvoid MMOD::setObject(shared_ptr<Object> object) {\n  if (object != this->object) {\n    this->object = object;\n    widget.setObjectPixmap(getImgCrop(object->getFirstAnnotation(), 96));\n  }\n}\n\nshared_ptr<Object> MMOD::getObject() const { return object; }\n\nvoid MMOD::setLastAnnotation(shared_ptr<Annotation> /*annotation*/) {}\n\nstd::vector<shared_ptr<Commands::Command>> MMOD::getCommands() {\n  std::vector<shared_ptr<Commands::Command>> commands;\n  if (object == nullptr || frame == nullptr || lastFrame == nullptr ||\n      lastFrame == frame)\n    return commands;\n\n  try {\n    cv::Rect res = findObject();\n\n    if (res.width > 0 && res.height > 0) {\n      int x = res.x;\n      int y = res.y;\n      int w = res.width;\n      int h = res.height;\n\n      shared_ptr<Commands::NewAnnotation> nA =\n          std::make_shared<Commands::NewAnnotation>(project->getSession(),\n                                                    this->object, this->frame,\n                                                    x, y, w, h, 0.9f);\n      commands.push_back(nA);\n    }\n  } catch (std::exception &e) {\n  }\n\n  return commands;\n}\n\nvoid MMOD::train() {\n  if (!object) return;\n  trainThread = std::thread([this] { this->trainWorker(); });\n}\n\nvoid MMOD::stop() {\n  stopTraining = true;\n  trainThread.join();\n}\n\nvoid MMOD::getImagesTrain() {\n  assert(object);\n  this->images_train.clear();\n  this->boxes_train.clear();\n  this->object->getAnnotations();\n\n  for (auto annotation : this->object->getAnnotations()) {\n    std::shared_ptr<AnnotatorLib::Annotation> a = annotation.second.lock();\n    cv::Mat image =\n        project->getImageSet()->getImage(a->getFrame()->getFrameNumber());\n\n    dlib::matrix<dlib::rgb_pixel> dlibImage;\n    dlib::assign_image(dlibImage, dlib::cv_image<dlib::rgb_pixel>(image));\n    this->images_train.push_back(dlibImage);\n    std::vector<dlib::mmod_rect> rects;\n    long x1 = std::max(0L, (long)a->getX());\n    long y1 = std::max(0L, (long)a->getY());\n    long x2 =\n        std::min((long)image.cols - 1L, (long)a->getX() + (long)a->getWidth());\n    long y2 =\n        std::min((long)image.rows - 1L, (long)a->getY() + long(a->getHeight()));\n    dlib::rectangle rect(x1, y1, x2, y2);\n    rects.push_back(dlib::mmod_rect(rect));\n    this->boxes_train.push_back(rects);\n  }\n}\n\nvoid MMOD::loadNet(std::string file) {\n  try {\n    dlib::deserialize(file) >> net;\n  } catch (...) {\n  }\n}\n\nvoid MMOD::saveNet(std::string file) {\n  try {\n    net.clean();\n    dlib::serialize(file) << net;\n  } catch (...) {\n  }\n}\n\nvoid MMOD::trainWorker() {\n  stopTraining = false;\n  widget.setProgress(10);\n  getImagesTrain();\n  widget.setProgress(20);\n  dlib::mmod_options options(boxes_train, 20 * 20, 10 * 10);//\n  net = net_type(options);\n  dlib::dnn_trainer<net_type> trainer(net);\n  trainer.set_learning_rate(0.1);\n  trainer.be_verbose();\n  trainer.set_synchronization_file(\"mmod_sync\", std::chrono::minutes(5));\n  trainer.set_iterations_without_progress_threshold(300);\n  widget.setProgress(30);\n  std::vector<dlib::matrix<dlib::rgb_pixel>> mini_batch_samples;\n  std::vector<std::vector<dlib::mmod_rect>> mini_batch_labels;\n\n  dlib::random_cropper cropper;\n  cropper.set_chip_dims(200, 200);\n  cropper.set_min_object_size(0.2);\n  dlib::rand rnd;\n  // Run the trainer until the learning rate gets small.  This will probably\n  // take several\n  // hours.\n  while (!stopTraining && trainer.get_learning_rate() >= 1e-4) {\n    try {\n      cropper(50, images_train, boxes_train, mini_batch_samples,\n              mini_batch_labels);\n      // We can also randomly jitter the colors and that often helps a detector\n      // generalize better to new images.\n      for (auto &&img : mini_batch_samples) disturb_colors(img, rnd);\n\n      trainer.train_one_step(mini_batch_samples, mini_batch_labels);\n    } catch (dlib::impossible_labeling_error &e) {\n      std::cout << this->getName().toStdString() << \": \" << e.what()\n                << std::endl;\n    }\n  }\n  // wait for training threads to stop\n  trainer.get_net();\n\n  widget.setProgress(50);\n  widget.setProgress(0);\n}\n\ncv::Rect MMOD::findObject() {\n  dlib::matrix<dlib::rgb_pixel> dlibImage;\n  dlib::assign_image(dlibImage,\n                     dlib::cv_image<dlib::rgb_pixel>(this->frameImg));\n\n  dlib::pyramid_up(dlibImage);\n\n  std::vector<dlib::mmod_rect> dets = net(dlibImage);\n  if (dets.size() < 1) return cv::Rect();\n\n  dlib::rectangle found = dets[0];\n  return cv::Rect(found.left(), found.top(), found.width(), found.height());\n}\n\nQPixmap MMOD::getImgCrop(shared_ptr<AnnotatorLib::Annotation> annotation,\n                         int size) const {\n  if (annotation == nullptr) return QPixmap();\n\n  cv::Mat cropped = getImg(annotation);\n\n  cropped.convertTo(cropped, CV_8U);\n  cv::cvtColor(cropped, cropped, CV_BGR2RGB);\n\n  QImage img((const unsigned char *)(cropped.data), cropped.cols, cropped.rows,\n             cropped.step, QImage::Format_RGB888);\n\n  QPixmap pim = QPixmap::fromImage(img);\n  pim = pim.scaledToHeight(size);\n  return pim;\n}\n\ncv::Mat MMOD::getImg(shared_ptr<Annotation> annotation) const {\n  cv::Mat tmp = project->getImageSet()->getImage(\n      annotation->getFrame()->getFrameNumber());\n\n  float x = std::max(annotation->getX(), 0.f);\n  float y = std::max(annotation->getY(), 0.f);\n  float w = std::min(annotation->getWidth(), tmp.cols - x);\n  float h = std::min(annotation->getHeight(), tmp.rows - y);\n\n  cv::Rect rect(x, y, w, h);\n  cv::Mat cropped;\n  try {\n    tmp(rect).copyTo(cropped);\n  } catch (cv::Exception &e) {\n    std::cout << e.what();\n  }\n  return cropped;\n}\n", "meta": {"hexsha": "d1481d54ec1557c8331c27df3118e311ee46c65b", "size": 6496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mmod.cpp", "max_stars_repo_name": "lasmue/annotatorplugin_dnn_mmod", "max_stars_repo_head_hexsha": "7b81d7726466d89792872c7bb7afe449ddca7e84", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-13T12:54:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-13T12:54:35.000Z", "max_issues_repo_path": "mmod.cpp", "max_issues_repo_name": "lasmue/annotatorplugin_dnn_mmod", "max_issues_repo_head_hexsha": "7b81d7726466d89792872c7bb7afe449ddca7e84", "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": "mmod.cpp", "max_forks_repo_name": "lasmue/annotatorplugin_dnn_mmod", "max_forks_repo_head_hexsha": "7b81d7726466d89792872c7bb7afe449ddca7e84", "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.4912280702, "max_line_length": 80, "alphanum_fraction": 0.6507081281, "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.1942242535060792}}
{"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 \"surround_obstacle_checker/node.hpp\"\n\n#include <autoware_auto_tf2/tf2_autoware_auto_msgs.hpp>\n\n#include <boost/assert.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/format.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include <pcl/common/transforms.h>\n#include <pcl/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#ifdef ROS_DISTRO_GALACTIC\n#include <tf2_eigen/tf2_eigen.h>\n#else\n#include <tf2_eigen/tf2_eigen.hpp>\n#endif\n\n#include <algorithm>\n#include <functional>\n#include <limits>\n#include <memory>\n#include <string>\n\n#define EIGEN_MPL2_ONLY\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace surround_obstacle_checker\n{\n\nnamespace bg = boost::geometry;\nusing Point2d = bg::model::d2::point_xy<double>;\nusing Polygon2d = bg::model::polygon<Point2d>;\nusing tier4_autoware_utils::createPoint;\nusing tier4_autoware_utils::pose2transform;\n\nnamespace\n{\nstd::string jsonDumpsPose(const geometry_msgs::msg::Pose & pose)\n{\n  const std::string json_dumps_pose =\n    (boost::format(\n       R\"({\"position\":{\"x\":%lf,\"y\":%lf,\"z\":%lf},\"orientation\":{\"w\":%lf,\"x\":%lf,\"y\":%lf,\"z\":%lf}})\") %\n     pose.position.x % pose.position.y % pose.position.z % pose.orientation.w % pose.orientation.x %\n     pose.orientation.y % pose.orientation.z)\n      .str();\n  return json_dumps_pose;\n}\n\ndiagnostic_msgs::msg::DiagnosticStatus makeStopReasonDiag(\n  const std::string no_start_reason, const geometry_msgs::msg::Pose & stop_pose)\n{\n  diagnostic_msgs::msg::DiagnosticStatus no_start_reason_diag;\n  diagnostic_msgs::msg::KeyValue no_start_reason_diag_kv;\n  no_start_reason_diag.level = diagnostic_msgs::msg::DiagnosticStatus::OK;\n  no_start_reason_diag.name = \"no_start_reason\";\n  no_start_reason_diag.message = no_start_reason;\n  no_start_reason_diag_kv.key = \"no_start_pose\";\n  no_start_reason_diag_kv.value = jsonDumpsPose(stop_pose);\n  no_start_reason_diag.values.push_back(no_start_reason_diag_kv);\n  return no_start_reason_diag;\n}\n\ngeometry_msgs::msg::Point32 createPoint32(const double x, const double y, const double z)\n{\n  geometry_msgs::msg::Point32 p;\n  p.x = x;\n  p.y = y;\n  p.z = z;\n  return p;\n}\n\nPolygon2d createObjPolygon(\n  const geometry_msgs::msg::Pose & pose, const geometry_msgs::msg::Polygon & footprint)\n{\n  geometry_msgs::msg::Polygon transformed_polygon{};\n  geometry_msgs::msg::TransformStamped geometry_tf{};\n  geometry_tf.transform = pose2transform(pose);\n  tf2::doTransform(footprint, transformed_polygon, geometry_tf);\n\n  Polygon2d object_polygon;\n  for (const auto & p : transformed_polygon.points) {\n    object_polygon.outer().push_back(Point2d(p.x, p.y));\n  }\n\n  bg::correct(object_polygon);\n\n  return object_polygon;\n}\n\nPolygon2d createObjPolygon(\n  const geometry_msgs::msg::Pose & pose, const geometry_msgs::msg::Vector3 & size)\n{\n  const double & length_m = size.x / 2.0;\n  const double & width_m = size.y / 2.0;\n\n  geometry_msgs::msg::Polygon polygon{};\n\n  polygon.points.push_back(createPoint32(length_m, -width_m, 0.0));\n  polygon.points.push_back(createPoint32(length_m, width_m, 0.0));\n  polygon.points.push_back(createPoint32(-length_m, width_m, 0.0));\n  polygon.points.push_back(createPoint32(-length_m, -width_m, 0.0));\n\n  return createObjPolygon(pose, polygon);\n}\n\nPolygon2d createSelfPolygon(const VehicleInfo & vehicle_info)\n{\n  const double & front_m = vehicle_info.max_longitudinal_offset_m;\n  const double & width_m = vehicle_info.min_lateral_offset_m;\n  const double & rear_m = vehicle_info.min_longitudinal_offset_m;\n\n  Polygon2d ego_polygon;\n\n  ego_polygon.outer().push_back(Point2d(front_m, -width_m));\n  ego_polygon.outer().push_back(Point2d(front_m, width_m));\n  ego_polygon.outer().push_back(Point2d(rear_m, width_m));\n  ego_polygon.outer().push_back(Point2d(rear_m, -width_m));\n\n  bg::correct(ego_polygon);\n\n  return ego_polygon;\n}\n}  // namespace\n\nSurroundObstacleCheckerNode::SurroundObstacleCheckerNode(const rclcpp::NodeOptions & node_options)\n: Node(\"surround_obstacle_checker_node\", node_options)\n{\n  // Parameters\n  {\n    auto & p = node_param_;\n    p.use_pointcloud = this->declare_parameter(\"use_pointcloud\", true);\n    p.use_dynamic_object = this->declare_parameter(\"use_dynamic_object\", true);\n    p.surround_check_distance = this->declare_parameter(\"surround_check_distance\", 2.0);\n    p.surround_check_recover_distance =\n      this->declare_parameter(\"surround_check_recover_distance\", 2.5);\n    p.state_clear_time = this->declare_parameter(\"state_clear_time\", 2.0);\n    p.stop_state_ego_speed = this->declare_parameter(\"stop_state_ego_speed\", 0.1);\n    p.stop_state_entry_duration_time =\n      this->declare_parameter(\"stop_state_entry_duration_time\", 0.1);\n  }\n\n  vehicle_info_ = vehicle_info_util::VehicleInfoUtil(*this).getVehicleInfo();\n\n  // Publishers\n  pub_stop_reason_ =\n    this->create_publisher<diagnostic_msgs::msg::DiagnosticStatus>(\"~/output/no_start_reason\", 1);\n  pub_clear_velocity_limit_ =\n    this->create_publisher<VelocityLimitClearCommand>(\"~/output/velocity_limit_clear_command\", 1);\n  pub_velocity_limit_ = this->create_publisher<VelocityLimit>(\"~/output/max_velocity\", 1);\n\n  // Subscribers\n  sub_pointcloud_ = this->create_subscription<sensor_msgs::msg::PointCloud2>(\n    \"~/input/pointcloud\", rclcpp::SensorDataQoS(),\n    std::bind(&SurroundObstacleCheckerNode::onPointCloud, this, std::placeholders::_1));\n  sub_dynamic_objects_ = this->create_subscription<PredictedObjects>(\n    \"~/input/objects\", 1,\n    std::bind(&SurroundObstacleCheckerNode::onDynamicObjects, this, std::placeholders::_1));\n  sub_odometry_ = this->create_subscription<nav_msgs::msg::Odometry>(\n    \"~/input/odometry\", 1,\n    std::bind(&SurroundObstacleCheckerNode::onOdometry, this, std::placeholders::_1));\n\n  using std::chrono_literals::operator\"\"ms;\n  timer_ = rclcpp::create_timer(\n    this, get_clock(), 100ms, std::bind(&SurroundObstacleCheckerNode::onTimer, this));\n\n  last_running_time_ = std::make_shared<rclcpp::Time>(this->now());\n\n  // Debug\n  debug_ptr_ = std::make_shared<SurroundObstacleCheckerDebugNode>(\n    vehicle_info_.max_longitudinal_offset_m, this->get_clock(), *this);\n}\n\nvoid SurroundObstacleCheckerNode::onTimer()\n{\n  if (node_param_.use_pointcloud && !pointcloud_ptr_) {\n    RCLCPP_WARN_THROTTLE(\n      this->get_logger(), *this->get_clock(), 1000 /* ms */, \"waiting for pointcloud info...\");\n    return;\n  }\n\n  if (node_param_.use_dynamic_object && !object_ptr_) {\n    RCLCPP_WARN_THROTTLE(\n      this->get_logger(), *this->get_clock(), 1000 /* ms */, \"waiting for dynamic object info...\");\n    return;\n  }\n\n  if (!odometry_ptr_) {\n    RCLCPP_WARN_THROTTLE(\n      this->get_logger(), *this->get_clock(), 1000 /* ms */, \"waiting for current velocity...\");\n    return;\n  }\n\n  const auto nearest_obstacle = getNearestObstacle();\n  const auto is_vehicle_stopped = isVehicleStopped();\n\n  switch (state_) {\n    case State::PASS: {\n      const auto is_obstacle_found =\n        !nearest_obstacle ? false\n                          : nearest_obstacle.get().first < node_param_.surround_check_distance;\n\n      if (!isStopRequired(is_obstacle_found, is_vehicle_stopped)) {\n        break;\n      }\n\n      state_ = State::STOP;\n\n      auto velocity_limit = std::make_shared<VelocityLimit>();\n      velocity_limit->stamp = this->now();\n      velocity_limit->max_velocity = 0.0;\n      velocity_limit->use_constraints = false;\n      velocity_limit->sender = \"surround_obstacle_checker\";\n\n      pub_velocity_limit_->publish(*velocity_limit);\n\n      // do not start when there is a obstacle near the ego vehicle.\n      RCLCPP_WARN(get_logger(), \"do not start because there is obstacle near the ego vehicle.\");\n\n      break;\n    }\n\n    case State::STOP: {\n      const auto is_obstacle_found =\n        !nearest_obstacle\n          ? false\n          : nearest_obstacle.get().first < node_param_.surround_check_recover_distance;\n\n      if (isStopRequired(is_obstacle_found, is_vehicle_stopped)) {\n        break;\n      }\n\n      state_ = State::PASS;\n\n      auto velocity_limit_clear_command = std::make_shared<VelocityLimitClearCommand>();\n      velocity_limit_clear_command->stamp = this->now();\n      velocity_limit_clear_command->command = true;\n      velocity_limit_clear_command->sender = \"surround_obstacle_checker\";\n\n      pub_clear_velocity_limit_->publish(*velocity_limit_clear_command);\n\n      break;\n    }\n\n    default:\n      break;\n  }\n\n  if (nearest_obstacle) {\n    debug_ptr_->pushObstaclePoint(nearest_obstacle.get().second, PointType::NoStart);\n  }\n\n  diagnostic_msgs::msg::DiagnosticStatus no_start_reason_diag;\n  if (state_ == State::STOP) {\n    debug_ptr_->pushPose(odometry_ptr_->pose.pose, PoseType::NoStart);\n    no_start_reason_diag = makeStopReasonDiag(\"obstacle\", odometry_ptr_->pose.pose);\n  }\n\n  pub_stop_reason_->publish(no_start_reason_diag);\n  debug_ptr_->publish();\n}\n\nvoid SurroundObstacleCheckerNode::onPointCloud(\n  const sensor_msgs::msg::PointCloud2::ConstSharedPtr msg)\n{\n  pointcloud_ptr_ = msg;\n}\n\nvoid SurroundObstacleCheckerNode::onDynamicObjects(const PredictedObjects::ConstSharedPtr msg)\n{\n  object_ptr_ = msg;\n}\n\nvoid SurroundObstacleCheckerNode::onOdometry(const nav_msgs::msg::Odometry::ConstSharedPtr msg)\n{\n  odometry_ptr_ = msg;\n}\n\nboost::optional<Obstacle> SurroundObstacleCheckerNode::getNearestObstacle() const\n{\n  boost::optional<Obstacle> nearest_pointcloud{boost::none};\n  boost::optional<Obstacle> nearest_object{boost::none};\n\n  if (node_param_.use_pointcloud) {\n    nearest_pointcloud = getNearestObstacleByPointCloud();\n  }\n\n  if (node_param_.use_dynamic_object) {\n    nearest_object = getNearestObstacleByDynamicObject();\n  }\n\n  if (!nearest_pointcloud && !nearest_object) {\n    return {};\n  }\n\n  if (!nearest_pointcloud) {\n    return nearest_object;\n  }\n\n  if (!nearest_object) {\n    return nearest_pointcloud;\n  }\n\n  return nearest_pointcloud.get().first < nearest_object.get().first ? nearest_pointcloud\n                                                                     : nearest_object;\n}\n\nboost::optional<Obstacle> SurroundObstacleCheckerNode::getNearestObstacleByPointCloud() const\n{\n  const auto transform_stamped =\n    getTransform(\"base_link\", pointcloud_ptr_->header.frame_id, pointcloud_ptr_->header.stamp, 0.5);\n\n  geometry_msgs::msg::Point nearest_point;\n  auto minimum_distance = std::numeric_limits<double>::max();\n\n  if (!transform_stamped) {\n    return {};\n  }\n\n  Eigen::Affine3f isometry = tf2::transformToEigen(transform_stamped.get().transform).cast<float>();\n  pcl::PointCloud<pcl::PointXYZ> transformed_pointcloud;\n  pcl::fromROSMsg(*pointcloud_ptr_, transformed_pointcloud);\n  pcl::transformPointCloud(transformed_pointcloud, transformed_pointcloud, isometry);\n\n  const auto ego_polygon = createSelfPolygon(vehicle_info_);\n\n  for (const auto & p : transformed_pointcloud) {\n    Point2d boost_point(p.x, p.y);\n\n    const auto distance_to_object = bg::distance(ego_polygon, boost_point);\n\n    if (distance_to_object < minimum_distance) {\n      nearest_point = createPoint(p.x, p.y, p.z);\n      minimum_distance = distance_to_object;\n    }\n  }\n\n  return std::make_pair(minimum_distance, nearest_point);\n}\n\nboost::optional<Obstacle> SurroundObstacleCheckerNode::getNearestObstacleByDynamicObject() const\n{\n  const auto transform_stamped =\n    getTransform(object_ptr_->header.frame_id, \"base_link\", object_ptr_->header.stamp, 0.5);\n\n  geometry_msgs::msg::Point nearest_point;\n  auto minimum_distance = std::numeric_limits<double>::max();\n\n  if (!transform_stamped) {\n    return {};\n  }\n\n  tf2::Transform tf_src2target;\n  tf2::fromMsg(transform_stamped.get().transform, tf_src2target);\n\n  const auto ego_polygon = createSelfPolygon(vehicle_info_);\n\n  for (const auto & object : object_ptr_->objects) {\n    const auto & object_pose = object.kinematics.initial_pose_with_covariance.pose;\n\n    tf2::Transform tf_src2object;\n    tf2::fromMsg(object_pose, tf_src2object);\n\n    geometry_msgs::msg::Pose transformed_object_pose;\n    tf2::toMsg(tf_src2target.inverse() * tf_src2object, transformed_object_pose);\n\n    const auto object_polygon =\n      object.shape.type == Shape::POLYGON\n        ? createObjPolygon(transformed_object_pose, object.shape.footprint)\n        : createObjPolygon(transformed_object_pose, object.shape.dimensions);\n\n    const auto distance_to_object = bg::distance(ego_polygon, object_polygon);\n\n    if (distance_to_object < minimum_distance) {\n      nearest_point = object_pose.position;\n      minimum_distance = distance_to_object;\n    }\n  }\n\n  return std::make_pair(minimum_distance, nearest_point);\n}\n\nboost::optional<geometry_msgs::msg::TransformStamped> SurroundObstacleCheckerNode::getTransform(\n  const std::string & source, const std::string & target, const rclcpp::Time & stamp,\n  double duration_sec) const\n{\n  geometry_msgs::msg::TransformStamped transform_stamped;\n\n  try {\n    transform_stamped =\n      tf_buffer_.lookupTransform(source, target, stamp, tf2::durationFromSec(duration_sec));\n  } catch (tf2::TransformException & ex) {\n    return {};\n  }\n\n  return transform_stamped;\n}\n\nbool SurroundObstacleCheckerNode::isStopRequired(\n  const bool is_obstacle_found, const bool is_vehicle_stopped)\n{\n  if (!is_vehicle_stopped) {\n    return false;\n  }\n\n  if (is_obstacle_found) {\n    last_obstacle_found_time_ = std::make_shared<const rclcpp::Time>(this->now());\n    return true;\n  }\n\n  if (state_ != State::STOP) {\n    return false;\n  }\n\n  // Keep stop state\n  if (last_obstacle_found_time_) {\n    const auto elapsed_time = this->now() - *last_obstacle_found_time_;\n    if (elapsed_time.seconds() <= node_param_.state_clear_time) {\n      return true;\n    }\n  }\n\n  last_obstacle_found_time_ = {};\n  return false;\n}\n\nbool SurroundObstacleCheckerNode::isVehicleStopped()\n{\n  const auto current_velocity = std::abs(odometry_ptr_->twist.twist.linear.x);\n\n  if (node_param_.stop_state_ego_speed < current_velocity) {\n    last_running_time_ = std::make_shared<rclcpp::Time>(this->now());\n  }\n\n  return node_param_.stop_state_entry_duration_time < (this->now() - *last_running_time_).seconds();\n}\n\n}  // namespace surround_obstacle_checker\n\n#include <rclcpp_components/register_node_macro.hpp>\nRCLCPP_COMPONENTS_REGISTER_NODE(surround_obstacle_checker::SurroundObstacleCheckerNode)\n", "meta": {"hexsha": "cd7117f360143cf60476ce671068da36874fd9ba", "size": 14860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "planning/surround_obstacle_checker/src/node.cpp", "max_stars_repo_name": "taikitanaka3/autoware.universe", "max_stars_repo_head_hexsha": "49d1764a5cb02924910cc5fab0f055cc337ca8ac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-30T02:26:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T02:26:07.000Z", "max_issues_repo_path": "planning/surround_obstacle_checker/src/node.cpp", "max_issues_repo_name": "taikitanaka3/autoware.universe", "max_issues_repo_head_hexsha": "49d1764a5cb02924910cc5fab0f055cc337ca8ac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-03T14:27:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T14:27:42.000Z", "max_forks_repo_path": "planning/surround_obstacle_checker/src/node.cpp", "max_forks_repo_name": "taikitanaka3/autoware.universe", "max_forks_repo_head_hexsha": "49d1764a5cb02924910cc5fab0f055cc337ca8ac", "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.3747276688, "max_line_length": 101, "alphanum_fraction": 0.736473755, "num_tokens": 3691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19422425151339656}}
{"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#ifndef CNVHAPSNPDATASINK_HPP\n#define CNVHAPSNPDATASINK_HPP\n\n#include <iostream>\n#include <string>\n#include <Eigen/Core>\n#include \"genfile/snp_data_utils.hpp\"\n#include \"genfile/gen.hpp\"\n#include \"genfile/SNPDataSink.hpp\"\n\nnamespace genfile {\n\t// A SNPDataSink which writes its data in a format suitable for input\n\t// to cnvHap's normalisation pipeline, c.f.\n\t// http://www.nature.com/nmeth/journal/v7/n7/abs/nmeth.1466.html\n\t// http://www.imperial.ac.uk/people/l.coin\n\t//\n\tclass cnvHapSNPDataSink: public SNPDataSink\n\t{\n\tpublic:\n\t\tcnvHapSNPDataSink( std::string const& filename ) ;\n\t\tSinkPos get_stream_pos() const ;\n\t\tstd::string get_spec() const ;\n\t\t\n\tprivate:\n\t\t\n\t\tvoid set_sample_names_impl( std::size_t number_of_samples, SampleNameGetter ) ;\n\t\tvoid set_metadata_impl( Metadata const& ) {} ;\n\t\tvoid write_variant_data_impl(\n\t\t\tVariantIdentifyingData const& id_data,\n\t\t\tVariantDataReader& data_reader,\n\t\t\tInfo const& info\n\t\t) ;\n\t\tvoid finalise_impl() {}\n\t\t\n\t\toperator bool() const ;\n\t\tstd::ostream& stream() { return *m_stream_ptr ; }\n\t\tstd::string const& filename() const { return m_filename ; }\n\n\tprivate:\n\t\tvoid setup( std::string const& filename ) ;\n\n\t\tstd::string m_filename ;\n\t\tstd::auto_ptr< std::ostream > m_stream_ptr ;\n\t\tstd::size_t m_number_of_samples ;\n\t\tEigen::MatrixXd m_intensities ;\n\t\tEigen::MatrixXd m_nonmissingness ;\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "9dc7dc3947b2c6ae9749c3dd859788f13ca3f3ef", "size": 1571, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "genfile/include/genfile/cnvHapSNPDataSink.hpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "genfile/include/genfile/cnvHapSNPDataSink.hpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "genfile/include/genfile/cnvHapSNPDataSink.hpp", "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": 27.5614035088, "max_line_length": 81, "alphanum_fraction": 0.72119669, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.36296919862864757, "lm_q1q2_score": 0.19422424782604975}}
{"text": "// ======================================================================\n/*!\n * \\file NFmiArea.cpp\n * \\brief Implementation of class NFmiArea\n */\n// ======================================================================\n/*!\n * \\class NFmiArea\n *\n * Undocumented\n */\n// ======================================================================\n\n#include \"NFmiArea.h\"\n#include \"NFmiAreaFactory.h\"\n#include <boost/functional/hash.hpp>\n\n// ----------------------------------------------------------------------\n/*!\n * \\bug Turha argumentti konstruktorille\n */\n// ----------------------------------------------------------------------\n\nvoid NFmiArea::Init(bool /* fKeepWorldRect */) { CheckForPacificView(); }\n// ----------------------------------------------------------------------\n/*!\n * \\param newArea Undocumented\n */\n// ----------------------------------------------------------------------\n\nvoid NFmiArea::SetXYArea(const NFmiRect &newArea)\n{\n  Place(newArea.TopLeft());\n  Size(newArea.Size());\n  Init();\n}\n\nstatic void FixPacificLongitude(NFmiPoint &lonLat)\n{\n  if (lonLat.X() < 0)\n  {\n    NFmiLongitude lon(lonLat.X(), true);\n    lonLat.X(lon.Value());\n  }\n}\n\n#if 0\nstatic void FixAtlanticLongitude(NFmiPoint &lonLat)\n{\n    if(lonLat.X() > 180)\n    {\n        NFmiLongitude lon(lonLat.X(), false);\n        lonLat.X(lon.Value());\n    }\n}\n#endif\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theArea Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiRect NFmiArea::XYArea(const NFmiArea *theArea) const\n{\n  if (PacificView() && theArea->PacificView() == false)\n  {\n    NFmiPoint topLeftLatlon = theArea->ToLatLon(theArea->TopLeft());\n    ::FixPacificLongitude(topLeftLatlon);\n    NFmiPoint bottomRightLatlon = theArea->ToLatLon(theArea->BottomRight());\n    ::FixPacificLongitude(bottomRightLatlon);\n\n    NFmiPoint topLeft(ToXY(topLeftLatlon));\n    NFmiPoint bottomRight(ToXY(bottomRightLatlon));\n    NFmiRect rect(topLeft, bottomRight);\n    return rect;\n  }\n  else if (PacificView() == false && theArea->PacificView())\n  {\n    std::unique_ptr<NFmiArea> pacificAreaFromThis(DoForcePacificFix());\n\n    NFmiPoint topLeft(pacificAreaFromThis->ToXY(theArea->ToLatLon(theArea->TopLeft())));\n    NFmiPoint bottomRight(pacificAreaFromThis->ToXY(theArea->ToLatLon(theArea->BottomRight())));\n    NFmiRect rect(topLeft, bottomRight);\n    return rect;\n  }\n  else\n  {\n    NFmiPoint topLeft(ToXY(theArea->ToLatLon(theArea->TopLeft())));\n    NFmiPoint bottomRight(ToXY(theArea->ToLatLon(theArea->BottomRight())));\n    NFmiRect rect(topLeft, bottomRight);\n    return rect;\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param file Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nstd::ostream &NFmiArea::Write(std::ostream &file) const\n{\n  file << itsXYRectArea;\n  return file;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param file Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nstd::istream &NFmiArea::Read(std::istream &file)\n{\n  file >> itsXYRectArea;\n  return file;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiArea::WorldXYSize() const { return WorldRect().Size(); }\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiArea::WorldXYPlace() const { return WorldRect().Place(); }\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiArea::WorldXYWidth() const { return WorldRect().Width(); }\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiArea::WorldXYHeight() const { return WorldRect().Height(); }\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiArea::WorldXYAspectRatio() const { return WorldXYWidth() / WorldXYHeight(); }\n// ----------------------------------------------------------------------\n/*!\n * Creates a new area from the current one by altering the corner points only.\n * Previously this method required the new area to be inside the original\n * one, but I failed to see the point in restricing the functionality - Mika\n *\n * \\param theBottomLeftLatLon Undocumented\n * \\param theTopRightLatLon Undocumented\n * \\return Undocumented\n *\n * \\todo Should return an boost::shared_ptr\n * \\todo Remove the unnecessary cast in the last return statement\n */\n// ----------------------------------------------------------------------\n\nNFmiArea *NFmiArea::CreateNewArea(const NFmiPoint &theBottomLeftLatLon,\n                                  const NFmiPoint &theTopRightLatLon) const\n{\n  return NewArea(theBottomLeftLatLon, theTopRightLatLon);\n}\n\n// ----------------------------------------------------------------------\n/*!\n *\n * Creates a new sub-area inside the current \"mother\" area.\n * The new area is defined by the input local rectangle 'theRect'\n *\n * \\note\n *   - the input rectangle defines a local XY coordinate area only, NOT the metric\n *     XY world rectangle\n *   - the sub-area MUST fit completely inside the current local area\n *   - the sub-area gets all the projection-specific properties but its dimensions\n *     from its \"mother\" area. For example, the orientation stays the same.\n *\n * \\param theRect Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiArea *NFmiArea::CreateNewArea(const NFmiRect &theRect) const\n{\n  NFmiPoint newBottomLeftXY = theRect.BottomLeft();\n  NFmiPoint newTopRightXY = theRect.TopRight();\n\n  NFmiPoint newBottomLeftLatLon = ToLatLon(newBottomLeftXY);\n  NFmiPoint newTopRightLatLon = ToLatLon(newTopRightXY);\n\n  NFmiArea *newArea = NewArea(newBottomLeftLatLon, newTopRightLatLon);\n  return newArea;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Creates a new area with its aspect ratio defined by the input parameters\n *\n * \\note\n *    - the new area MAY OR MAY NOT completely reside inside the current local area\n *    - the new area gets all the projection-specific properties but its dimensions\n *      from its \"mother\" area. For example, the orientation stays the same.\n *\n * \\param theNewAspectRatioXperY Undocumented\n * \\param theFixedPoint Undocumented\n * \\param fShrinkArea Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiArea *NFmiArea::CreateNewArea(double theNewAspectRatioXperY,\n                                  FmiDirection theFixedPoint,\n                                  bool fShrinkArea)\n{\n  double originalAspectRatio = WorldXYAspectRatio();\n\n  bool keepWidth;\n\n  if (fShrinkArea)\n  {\n    // The new area will be \"shrunk\" to completely fit inside the current area\n    if ((theNewAspectRatioXperY < originalAspectRatio))\n      keepWidth = false;  // Maintain height, compute width\n    else\n      keepWidth = true;  // Maintain width, compute height\n  }\n  else\n  {\n    // The new area will in part grow out of the current area\n    if ((theNewAspectRatioXperY < originalAspectRatio))\n      keepWidth = true;  // Maintain width, compute height\n    else\n      keepWidth = false;  // Maintain height, compute width\n  }\n\n  // Create copy of the original \"world rectangle\" to be freely modified\n  NFmiRect newWorldRect = WorldRect();\n\n  // REDIMENSIONING OF THE WORLD RECTANGLE\n  //----------------------------------------\n\n  if (!newWorldRect.AdjustAspectRatio(theNewAspectRatioXperY, keepWidth, theFixedPoint))\n    return nullptr;\n\n  // Create a new area with the new aspect ratio\n  NFmiArea *newArea =\n      NewArea(WorldXYToLatLon(newWorldRect.TopLeft()), WorldXYToLatLon(newWorldRect.BottomRight()));\n\n  // Return the re-dimensioned copy of the original area\n  return newArea;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Creates a new sub-area inside the current \"mother\" area.\n * The new area is defined by the input metric rectangle 'theWorldRect'\n *\n * \\note\n *   - the input rectangle defines a metric XY world rectangle\n *   - the sub-area MUST fit completely inside the current local area\n *   - the sub-area gets all the projection-specific properties but its dimensions\n *   - from its \"mother\" area. For example, the orientation stays the same.\n *\n * \\param theWorldRect\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiArea *NFmiArea::CreateNewAreaByWorldRect(const NFmiRect &theWorldRect)\n{\n  NFmiPoint newBottomLeftXY = theWorldRect.BottomLeft();\n  NFmiPoint newTopRightXY = theWorldRect.TopRight();\n\n  NFmiPoint newBottomLeftLatLon = WorldXYToLatLon(newBottomLeftXY);\n  NFmiPoint newTopRightLatLon = WorldXYToLatLon(newTopRightXY);\n\n  if (!IsInside(newBottomLeftLatLon) || !IsInside(newTopRightLatLon)) return nullptr;\n\n  auto *newArea = static_cast<NFmiArea *>(NewArea(newBottomLeftLatLon, newTopRightLatLon));\n\n  if (!IsInside(*newArea)) return nullptr;\n\n  return newArea;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Measured from the input point, returns the azimuth angle between\n * the true geodetic north direction and the \"up\" Y-axis of the map\n * area rectangle. Azimuth angle runs 0..360 degrees clockwise, with\n * north zero degrees.\n *\n * \\param theLatLonPoint Undocumented\n * \\param theLatitudeEpsilon Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiAngle NFmiArea::TrueNorthAzimuth(const NFmiPoint &theLatLonPoint,\n                                           double theLatitudeEpsilon) const\n{\n  using namespace std;\n\n  NFmiPoint xyWorldPoint = LatLonToWorldXY(theLatLonPoint);\n  NFmiPoint latLonIncr =\n      NFmiPoint(0., theLatitudeEpsilon);  // Arbitrary small latitude increment in degrees\n\n  // Move up toward geo-north along the meridian of the input point\n  NFmiPoint xyDistanceAlongMeridian = LatLonToWorldXY(theLatLonPoint + latLonIncr) - xyWorldPoint;\n\n  // Get the angle between 'xyDistanceAlongMeridian.X()' and map \"up\" direction Y-axis\n  if (xyDistanceAlongMeridian.Y() == 0.)\n    return xyDistanceAlongMeridian.X() > 0.\n               ? NFmiAngle(90.)\n               : NFmiAngle(\n                     270.);  // Azimuth is exactly east 90 degrees or west 270 degrees, respectively\n\n  return NFmiAngle(FmiDeg(atan2(xyDistanceAlongMeridian.X(), xyDistanceAlongMeridian.Y())));\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return center latlon coordinate\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiArea::CenterLatLon() const\n{\n  NFmiPoint bl = BottomLeft();\n  NFmiPoint tr = TopRight();\n\n  NFmiPoint center(0.5 * (bl.X() + tr.X()), 0.5 * (bl.Y() + tr.Y()));\n\n  return ToLatLon(center);\n}\n\nbool NFmiArea::IsPacificLongitude(double theLongitude)\n{\n  if (theLongitude > 180 && theLongitude <= 360)\n    return true;\n  else\n    return false;\n}\n\nvoid NFmiArea::CheckForPacificView()\n{\n  fPacificView = NFmiArea::IsPacificView(BottomLeftLatLon(), TopRightLatLon());\n}\n\n// 1. Tarkistaa kattaako annetut pisteet Atlantic vai Pacific alueen\n// 2. Jos Pacific, korjaa longitudet pacific:eiksi\n// 3. Palauta originaali/korjatut pisteet pair:issa\nPacificPointFixerData NFmiArea::PacificPointFixer(const NFmiPoint &theBottomLeftLatlon,\n                                                  const NFmiPoint &theTopRightLatlon)\n{\n  bool usePacificView = NFmiArea::IsPacificView(theBottomLeftLatlon, theTopRightLatlon);\n  if (usePacificView)\n  {\n    NFmiPoint bottomLeftLatLon = theBottomLeftLatlon;\n    NFmiPoint topRightLatLon = theTopRightLatlon;\n    NFmiAreaFactory::DoPossiblePacificFix(bottomLeftLatLon, topRightLatLon, usePacificView);\n    return PacificPointFixerData(bottomLeftLatLon, topRightLatLon, usePacificView);\n  }\n  else\n    return PacificPointFixerData(theBottomLeftLatlon, theTopRightLatlon, usePacificView);\n}\n\nbool NFmiArea::IsPacificView(const NFmiPoint &bottomleftLatlon, const NFmiPoint &toprightLatlon)\n{\n  // Obvious case\n  if (bottomleftLatlon.X() >= 0 && toprightLatlon.X() < 0) return true;\n  // 0...360 coordinate system is used\n  if (IsPacificLongitude(bottomleftLatlon.X()) || IsPacificLongitude(toprightLatlon.X()))\n    return true;\n  return false;\n}\n\ndouble NFmiArea::FixLongitude(double theLon) const\n{\n  if (!fPacificView)\n  {\n    if (theLon > 180.00000001)  // T\u00e4m\u00e4 ei voi olla tasan 180, koska SmartMet maailman rajaviivat\n                                // shapessa (maps\\\\shapes\\\\ne_10m_admin_0_countries) ja niiden\n                                // piirto imagine-kirjastolla menee jossain kohdissa sekaisin\n      // reunoilla, koska siell\u00e4 on k\u00e4ytetty v\u00e4h\u00e4n yli 180-pituuspiirin\n      // menevi\u00e4 arvoja Tyynenmeren 180 asteen pituuspiirin reunoilla\n      return theLon - 360;\n    else\n      return theLon;\n  }\n  else if (theLon < 0)\n    return theLon + 360;\n  else\n    return theLon;\n}\n\nNFmiArea *NFmiArea::DoPossiblePacificFix() const\n{\n  // On olemassa pari erikoistapausta, mitk\u00e4 halutaan eri areoissa korjata, ett\u00e4 alueet toimisivat\n  // paremmin newbase:ssa.\n  if (fPacificView)\n  {\n    bool usedPacificViewState = fPacificView;\n    NFmiPoint bottomleft = BottomLeftLatLon();\n    NFmiPoint topright = TopRightLatLon();\n    bool createNewArea =\n        NFmiAreaFactory::DoPossiblePacificFix(bottomleft, topright, usedPacificViewState);\n\n    if (createNewArea)\n    {\n      NFmiArea *newArea = NewArea(bottomleft, topright);\n      if (newArea)\n      {\n        newArea->PacificView(usedPacificViewState);\n        return newArea;\n      }\n    }\n  }\n  return nullptr;\n}\n\nNFmiArea *NFmiArea::DoForcePacificFix() const\n{\n  // Joskus on pakko muuttaa atlantic-area pacific tyyppiseksi vaikka v\u00e4kisin\n  if (!fPacificView)\n  {\n    NFmiPoint bottomleftLatlon = BottomLeftLatLon();\n    ::FixPacificLongitude(bottomleftLatlon);\n    NFmiPoint toprightLatlon = TopRightLatLon();\n    ::FixPacificLongitude(toprightLatlon);\n\n    NFmiArea *newArea = NewArea(bottomleftLatlon, toprightLatlon, false);\n    if (newArea)\n    {\n      newArea->PacificView(true);\n      return newArea;\n    }\n  }\n  return nullptr;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return hash value for the base NFmiArea components\n */\n// ----------------------------------------------------------------------\n\nstd::size_t NFmiArea::HashValue() const\n{\n  std::size_t hash = itsXYRectArea.HashValue();\n  boost::hash_combine(hash, boost::hash_value(fPacificView));\n  boost::hash_combine(hash, boost::hash_value(WKT()));\n  return hash;\n}\n", "meta": {"hexsha": "ff60fad5ce5c1990173d175f34ab597b9dcbb6a3", "size": 15296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/newbase/newbase/NFmiArea.cpp", "max_stars_repo_name": "fmidev/smartmet-workstation-vtk", "max_stars_repo_head_hexsha": "ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99", "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": "modules/newbase/newbase/NFmiArea.cpp", "max_issues_repo_name": "fmidev/smartmet-workstation-vtk", "max_issues_repo_head_hexsha": "ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99", "max_issues_repo_licenses": ["MIT"], "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/newbase/newbase/NFmiArea.cpp", "max_forks_repo_name": "fmidev/smartmet-workstation-vtk", "max_forks_repo_head_hexsha": "ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99", "max_forks_repo_licenses": ["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.6837606838, "max_line_length": 100, "alphanum_fraction": 0.5802170502, "num_tokens": 3465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19422424613138564}}
{"text": "#pragma once\n#include <geometry_msgs/Point.h>\n#include <mil_blueview_driver/BlueViewPing.h>\n#include <nav_msgs/OccupancyGrid.h>\n#include <ros/ros.h>\n\n#include <tf/transform_listener.h>\n#include <tf2/convert.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <tf2_msgs/TFMessage.h>\n#include <tf2_ros/transform_listener.h>\n#include <tf2_sensor_msgs/tf2_sensor_msgs.h>\n\n#include <opencv2/core/core.hpp>\n#include <stdexcept>\n#include \"opencv2/opencv.hpp\"\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl_ros/point_cloud.h>\n\n#include <boost/circular_buffer.hpp>\n\n#include <sub8_msgs/Bounds.h>\n\n#include <waypoint_validity.hpp>\n\n#include <Classification.hpp>\n\nclass OGridGen\n{\npublic:\n  OGridGen();\n  void publish_ogrid(const ros::TimerEvent &);\n\n  void callback(const mil_blueview_driver::BlueViewPingPtr &ping_msg);\n\nprivate:\n  ros::NodeHandle nh_;\n  ros::Subscriber sub_to_imaging_sonar_;\n\n  tf::TransformListener listener_;\n\n  ros::Publisher pub_grid_;\n  ros::Publisher pub_point_cloud_filtered_;\n  ros::Publisher pub_point_cloud_raw_;\n  ros::Timer timer_;\n\n  cv::Mat mat_ogrid_;\n  float ogrid_size_;\n  float resolution_;\n  float pool_depth_;\n  int min_intensity_;\n\n  ros::ServiceClient service_get_bounds_;\n  tf::StampedTransform transform_;\n\n  boost::circular_buffer<pcl::PointXYZI> point_cloud_buffer_;\n\n  std::vector<cv::Point> bounds_;\n\n  Classification classification_;\n};\n", "meta": {"hexsha": "e34ed3ea36c48a609052f834c13d32a253b7b3fb", "size": 1411, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perception/sub8_pointcloud/include/OGridGen.hpp", "max_stars_repo_name": "DSsoto/SubjuGator", "max_stars_repo_head_hexsha": "fb3861442399540e1dc4472af6e98a817a81e607", "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": "perception/sub8_pointcloud/include/OGridGen.hpp", "max_issues_repo_name": "DSsoto/SubjuGator", "max_issues_repo_head_hexsha": "fb3861442399540e1dc4472af6e98a817a81e607", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perception/sub8_pointcloud/include/OGridGen.hpp", "max_forks_repo_name": "DSsoto/SubjuGator", "max_forks_repo_head_hexsha": "fb3861442399540e1dc4472af6e98a817a81e607", "max_forks_repo_licenses": ["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.046875, "max_line_length": 70, "alphanum_fraction": 0.7767540751, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.1942242441387029}}
{"text": "#define BOOST_TEST_MODULE SignatureTest\n#include <boost/test/unit_test.hpp>\n\n#include <fc/crypto/elliptic.hpp>\n#include <fc/crypto/sha256.hpp>\n#include <fc/time.hpp>\n#include <fc/thread/thread.hpp>\n#include <iostream>\n#include <algorithm>\n#include <fc/crypto/sha512.hpp>\n\n#include <bts/utilities/deterministic_openssl_rand.hpp>\n\nBOOST_AUTO_TEST_CASE(ecc_signatures)\n{\n  std::string plaintext(\"Here is some text to sign\");\n  fc::sha256::encoder sha_encoder;\n  sha_encoder.write(plaintext.c_str(), plaintext.size());\n  fc::sha256 hash_of_plaintext = sha_encoder.result();\n\n  // code for generating a key:\n  //fc::ecc::private_key signing_key = fc::ecc::private_key::generate();\n  //std::string private_key_as_string = fc::variant(signing_key).as_string();\n  //fc::ecc::private_key reconstructed_private_key = fc::variant(private_key_as_string).as<fc::ecc::private_key>();\n  //assert(signing_key == reconstructed_private_key);\n  fc::ecc::private_key signing_key = fc::variant(\"940ff36f9c6d4d19d8c965bfbbe50bd318774a2af3d8c76021e681af462f943e\").as<fc::ecc::private_key>();\n\n  // generate two signatures before injecting our code into openssl    \n  fc::ecc::signature first_nondeterministic_signature = signing_key.sign(hash_of_plaintext);\n  fc::ecc::signature second_nondeterministic_signature = signing_key.sign(hash_of_plaintext);\n  BOOST_REQUIRE(first_nondeterministic_signature != second_nondeterministic_signature);\n\n  // set our fake random number generator, generate two signatures\n  bts::utilities::set_random_seed_for_testing(fc::sha512());\n\n  fc::ecc::signature first_deterministic_signature = signing_key.sign(hash_of_plaintext);\n  fc::ecc::signature second_deterministic_signature = signing_key.sign(hash_of_plaintext);\n  BOOST_REQUIRE(first_deterministic_signature != second_deterministic_signature);\n  BOOST_REQUIRE(first_deterministic_signature != first_nondeterministic_signature);\n  BOOST_REQUIRE(second_deterministic_signature != second_nondeterministic_signature);\n\n  bts::utilities::set_random_seed_for_testing(fc::sha512());\n  fc::ecc::signature third_deterministic_signature = signing_key.sign(hash_of_plaintext);\n  fc::ecc::signature fourth_deterministic_signature = signing_key.sign(hash_of_plaintext);\n  BOOST_REQUIRE(third_deterministic_signature == first_deterministic_signature);\n  BOOST_REQUIRE(fourth_deterministic_signature == second_deterministic_signature);\n}\n", "meta": {"hexsha": "5df5c11f954a25d8380ae0a5dce5fe81af551903", "size": 2389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/deterministic_signature_test.cpp", "max_stars_repo_name": "emfrias/bitshares", "max_stars_repo_head_hexsha": "8af3c28c2a7225857b2b37f7821332279b4fd66e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T21:11:35.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-08T17:53:49.000Z", "max_issues_repo_path": "tests/deterministic_signature_test.cpp", "max_issues_repo_name": "emfrias/bitshares", "max_issues_repo_head_hexsha": "8af3c28c2a7225857b2b37f7821332279b4fd66e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 428.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T18:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-08T16:08:08.000Z", "max_forks_repo_path": "tests/deterministic_signature_test.cpp", "max_forks_repo_name": "emfrias/bitshares", "max_forks_repo_head_hexsha": "8af3c28c2a7225857b2b37f7821332279b4fd66e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T02:31:30.000Z", "max_forks_repo_forks_event_max_datetime": "2015-06-05T18:50:57.000Z", "avg_line_length": 49.7708333333, "max_line_length": 144, "alphanum_fraction": 0.8049393051, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.19419805386898448}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2020.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Eugen Netz $\n// $Authors: Eugen Netz $\n// --------------------------------------------------------------------------\n\n\n#include <OpenMS/ANALYSIS/XLMS/XQuestScores.h>\n#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>\n#include <boost/math/distributions/binomial.hpp>\n#include <numeric>\n\nusing namespace std;\n\nnamespace OpenMS\n{\n\n  float XQuestScores::preScore(Size matched_alpha, Size ions_alpha, Size matched_beta, Size ions_beta)\n  {\n\n    if ( (matched_alpha <= 0 && matched_beta <= 0) || ions_alpha <= 0 || ions_beta <= 0)\n    {\n      return 0.0;\n    }\n\n    // avoid 0 values in multiplication, adds a \"dynamic range\" among candidates with no matching linear peaks to one of the peptides\n    float matched_alpha_float = matched_alpha;\n    if (matched_alpha <= 0)\n    {\n      matched_alpha_float = 0.1f;\n    }\n    float matched_beta_float = matched_beta;\n    if (matched_beta <= 0)\n    {\n      matched_beta_float = 0.1f;\n    }\n\n      float result = sqrt((static_cast<float>(matched_alpha_float) / static_cast<float>(ions_alpha)) * (static_cast<float>(matched_beta_float) / static_cast<float>(ions_beta)));\n      return result;\n  }\n\n  float XQuestScores::preScore(Size matched_alpha, Size ions_alpha)\n  {\n    if (ions_alpha <= 0)\n    {\n      return 0.0;\n    }\n\n    float result = static_cast<float>(matched_alpha) / static_cast<float>(ions_alpha);\n    return result;\n  }\n\n  double XQuestScores::matchOddsScore(const PeakSpectrum& theoretical_spec,  const Size matched_size, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, bool is_xlink_spectrum, Size n_charges)\n  {\n    using boost::math::binomial;\n    Size theo_size = theoretical_spec.size();\n\n    if (matched_size < 1 || theo_size < 1)\n    {\n      return 0;\n    }\n\n    double range = theoretical_spec[theo_size-1].getMZ() -  theoretical_spec[0].getMZ();\n\n    // Compute fragment tolerance in Da for the mean of MZ values, if tolerance in ppm (rough approximation)\n    double mean = 0.0;\n    for (Size i = 0; i < theo_size; ++i)\n    {\n      mean += theoretical_spec[i].getMZ();\n    }\n    mean = mean / theo_size;\n    double tolerance_Th = fragment_mass_tolerance_unit_ppm ? mean * 1e-6 * fragment_mass_tolerance : fragment_mass_tolerance;\n\n    // A priori probability of a random match given info about the theoretical spectrum\n    double a_priori_p = 0;\n\n    if (is_xlink_spectrum)\n    {\n      a_priori_p = (1 - ( pow( (1 - 2 * tolerance_Th / (0.5 * range)),  (static_cast<double>(theo_size) / static_cast<double>(n_charges)))));\n    }\n    else\n    {\n      a_priori_p = (1 - ( pow( (1 - 2 * tolerance_Th / (0.5 * range)),  static_cast<int>(theo_size))));\n    }\n\n    double match_odds = 0;\n\n    binomial flip(theo_size, a_priori_p);\n    // min double number to avoid 0 values, causing scores with the value \"inf\"\n    match_odds = -log(cdf(complement(flip, matched_size)) + std::numeric_limits<double>::min());\n\n    // score lower than 0 does not make sense, but can happen if cfd = 0, -log( 1 + min() ) < 0\n    if (match_odds >= 0.0)\n    {\n      return match_odds;\n    }\n    else\n    {\n      return 0;\n    }\n  }\n\n  double XQuestScores::matchOddsScoreSimpleSpec(const std::vector< SimpleTSGXLMS::SimplePeak >& theoretical_spec,  const Size matched_size, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, bool is_xlink_spectrum, Size n_charges)\n  {\n    using boost::math::binomial;\n    Size theo_size = theoretical_spec.size();\n\n    if (matched_size < 1 || theo_size < 1)\n    {\n      return 0;\n    }\n\n    double range = theoretical_spec[theo_size-1].mz - theoretical_spec[0].mz;\n\n    // Compute fragment tolerance in Da for the mean of MZ values, if tolerance in ppm (rough approximation)\n    double mean = 0.0;\n    for (Size i = 0; i < theo_size; ++i)\n    {\n      mean += theoretical_spec[i].mz;\n    }\n    mean = mean / theo_size;\n    double tolerance_Th = fragment_mass_tolerance_unit_ppm ? mean * 1e-6 * fragment_mass_tolerance : fragment_mass_tolerance;\n\n    // A priori probability of a random match given info about the theoretical spectrum\n    double a_priori_p = 0;\n\n    if (is_xlink_spectrum)\n    {\n      a_priori_p = (1 - ( pow( (1 - 2 * tolerance_Th / (0.5 * range)),  (static_cast<double>(theo_size) / static_cast<double>(n_charges)))));\n    }\n    else\n    {\n      a_priori_p = (1 - ( pow( (1 - 2 * tolerance_Th / (0.5 * range)),  static_cast<int>(theo_size))));\n    }\n\n    double match_odds = 0;\n\n    binomial flip(theo_size, a_priori_p);\n    // min double number to avoid 0 values, causing scores with the value \"inf\"\n    match_odds = -log(cdf(complement(flip, matched_size)) + std::numeric_limits<double>::min());\n\n    // score lower than 0 does not make sense, but can happen if cfd = 0, -log( 1 + min() ) < 0\n    if (match_odds >= 0.0)\n    {\n      return match_odds;\n    }\n    else\n    {\n      return 0;\n    }\n  }\n\n  double XQuestScores::logOccupancyProb(const PeakSpectrum& theoretical_spec,  const Size matched_size, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm)\n  {\n    using boost::math::binomial;\n    Size theo_size = theoretical_spec.size();\n\n    if (matched_size < 1 || theo_size < 1)\n    {\n      return 0;\n    }\n\n    double range;\n    double used_tolerance;\n\n    if (fragment_mass_tolerance_unit_ppm)\n    {\n      range = std::log(theoretical_spec.back().getMZ()) - std::log(theoretical_spec[0].getMZ());\n      used_tolerance = fragment_mass_tolerance / 1e6;\n    }\n    else\n    {\n      range = theoretical_spec.back().getMZ() - theoretical_spec[0].getMZ();\n      used_tolerance = fragment_mass_tolerance;\n    }\n\n    // A priori probability of a random match given info about the theoretical spectrum\n    double a_priori_p = 0;\n    a_priori_p = 1 - pow(1 - 2 * used_tolerance / range,  static_cast<double>(theo_size));\n\n    double log_occu_prob = 0;\n    binomial flip(theo_size, a_priori_p);\n    // min double number to avoid 0 values, causing scores with the value \"inf\"\n    log_occu_prob = -log(cdf(complement(flip, matched_size)) + std::numeric_limits<double>::min());\n\n    // score lower than 0 does not make sense, but can happen, if cfd = 0, then -log( 1 + <double>::min() ) < 0\n    if (log_occu_prob >= 0.0)\n    {\n      return log_occu_prob;\n    }\n    else // underflow warning?\n    {\n      return 0;\n    }\n  }\n\n  double XQuestScores::weightedTICScoreXQuest(Size alpha_size, Size beta_size, double intsum_alpha, double intsum_beta, double total_current, bool type_is_cross_link)\n  {\n    // maxdigestlength and mindigestlength from standard settings of xQuest\n    double maxdigestlength = 50;\n    double mindigestlength = 5;\n    if (!type_is_cross_link)\n    {\n      beta_size = ( maxdigestlength + mindigestlength ) - alpha_size;\n    }\n\n    double aatotal = alpha_size + beta_size;\n\n    double invMax = 1 / (mindigestlength / (mindigestlength + maxdigestlength));\n    double invFrac_alpha = 1 / (alpha_size / aatotal);\n    double invFrac_beta = 1 / (beta_size / aatotal);\n    double TIC_weight_alpha = invFrac_alpha / invMax;\n    double TIC_weight_beta = invFrac_beta / invMax;\n\n    double wTIC = TIC_weight_alpha * (intsum_alpha / total_current ) + TIC_weight_beta * (intsum_beta / total_current);\n    return wTIC;\n  }\n\n  double XQuestScores::weightedTICScore(Size alpha_size, Size beta_size, double intsum_alpha, double intsum_beta, double total_current, bool type_is_cross_link)\n  {\n    if (!type_is_cross_link)\n    {\n      beta_size = alpha_size;\n    }\n\n    double aatotal = alpha_size + beta_size;\n\n    // deviation from xQuest algorithm: invMax is not a constant anymore\n    // and scales by the actual length difference between alpha and beta, rather than the maximal possible difference between any two peptides\n    // this results in a local scaling, rather than a global one\n    double invMax = 1 / (min(alpha_size, beta_size) / aatotal);\n\n    double invFrac_alpha = 1 / (alpha_size / aatotal);\n    double invFrac_beta = 1 / (beta_size / aatotal);\n    double TIC_weight_alpha = invFrac_alpha / invMax;\n    double TIC_weight_beta = invFrac_beta / invMax;\n\n    double wTIC = TIC_weight_alpha * (intsum_alpha / total_current ) + TIC_weight_beta * (intsum_beta / total_current);\n    return wTIC;\n  }\n\n  double XQuestScores::matchedCurrentChain(const std::vector< std::pair< Size, Size > >& matched_spec_linear, const std::vector< std::pair< Size, Size > >& matched_spec_xlinks, const PeakSpectrum& spectrum_linear_peaks, const PeakSpectrum& spectrum_xlink_peaks)\n  {\n    double intsum = 0;\n    for (SignedSize j = 0; j < static_cast<SignedSize>(matched_spec_linear.size()); ++j)\n    {\n      intsum += spectrum_linear_peaks[matched_spec_linear[j].second].getIntensity();\n    }\n    for (SignedSize j = 0; j < static_cast<SignedSize>(matched_spec_xlinks.size()); ++j)\n    {\n      intsum += spectrum_xlink_peaks[matched_spec_xlinks[j].second].getIntensity();\n    }\n    return intsum;\n  }\n\n  double XQuestScores::totalMatchedCurrent(const std::vector< std::pair< Size, Size > >& matched_spec_linear_alpha, const std::vector< std::pair< Size, Size > >& matched_spec_linear_beta, const std::vector< std::pair< Size, Size > >& matched_spec_xlinks_alpha, const std::vector< std::pair< Size, Size > >& matched_spec_xlinks_beta, const PeakSpectrum& spectrum_linear_peaks, const PeakSpectrum& spectrum_xlink_peaks)\n  {\n    // make vectors of matched peak indices\n    double intsum(0);\n    std::vector< Size > indices_linear;\n    std::vector< Size > indices_xlinks;\n    for (Size j = 0; j < matched_spec_linear_alpha.size(); ++j)\n    {\n      indices_linear.push_back(matched_spec_linear_alpha[j].second);\n    }\n    for (Size j = 0; j < matched_spec_linear_beta.size(); ++j)\n    {\n      indices_linear.push_back(matched_spec_linear_beta[j].second);\n    }\n    for (Size j = 0; j < matched_spec_xlinks_alpha.size(); ++j)\n    {\n      indices_xlinks.push_back(matched_spec_xlinks_alpha[j].second);\n    }\n    for (Size j = 0; j < matched_spec_xlinks_beta.size(); ++j)\n    {\n      indices_xlinks.push_back(matched_spec_xlinks_beta[j].second);\n    }\n\n    // make the indices in the vectors unique, to not sum up peak intensities multiple times\n    sort(indices_linear.begin(), indices_linear.end());\n    sort(indices_xlinks.begin(), indices_xlinks.end());\n    std::vector< Size >::iterator last_unique_linear = unique(indices_linear.begin(), indices_linear.end());\n    std::vector< Size >::iterator last_unique_xlinks = unique(indices_xlinks.begin(), indices_xlinks.end());\n    indices_linear.erase(last_unique_linear, indices_linear.end());\n    indices_xlinks.erase(last_unique_xlinks, indices_xlinks.end());\n\n    // sum over intensities under the unique indices\n    for (Size j = 0; j < indices_linear.size(); ++j)\n    {\n      intsum += spectrum_linear_peaks[indices_linear[j]].getIntensity();\n    }\n    for (Size j = 0; j < indices_xlinks.size(); ++j)\n    {\n      intsum += spectrum_xlink_peaks[indices_xlinks[j]].getIntensity();\n    }\n    return intsum;\n  }\n\n  std::vector< double > XQuestScores::xCorrelation(const PeakSpectrum & spec1, const PeakSpectrum & spec2, Int maxshift, double tolerance)\n  {\n    // generate vector of results, filled with zeroes\n    std::vector< double > results(maxshift * 2 + 1, 0);\n\n    // return 0 = no correlation, when one of the spectra is empty\n    if (spec1.size() == 0 || spec2.size() == 0) {\n      return results;\n    }\n\n    double maxionsize = std::max(spec1[spec1.size()-1].getMZ(), spec2[spec2.size()-1].getMZ());\n    Int table_size = ceil(maxionsize / tolerance)+1;\n    std::vector< double > ion_table1(table_size, 0);\n    std::vector< double > ion_table2(table_size, 0);\n\n    // Build tables of the same size, each bin has the size of the tolerance\n    for (Size i = 0; i < spec1.size(); ++i)\n    {\n      Size pos = static_cast<Size>(ceil(spec1[i].getMZ() / tolerance));\n      ion_table1[pos] = 10.0;\n    }\n    for (Size i = 0; i < spec2.size(); ++i)\n    {\n      Size pos =static_cast<Size>(ceil(spec2[i].getMZ() / tolerance));\n      ion_table2[pos] = 10.0;\n    }\n\n    // Compute means\n    double mean1 = (std::accumulate(ion_table1.begin(), ion_table1.end(), 0.0)) / table_size;\n    double mean2 = (std::accumulate(ion_table2.begin(), ion_table2.end(), 0.0)) / table_size;\n\n    // Compute denominator\n    double s1 = 0;\n    double s2 = 0;\n    for (Int i = 0; i < table_size; ++i)\n    {\n      s1 += pow((ion_table1[i] - mean1), 2);\n      s2 += pow((ion_table2[i] - mean2), 2);\n    }\n    double denom = sqrt(s1 * s2);\n\n    // Calculate correlation for each shift\n    for (Int shift = -maxshift; shift <= maxshift; ++shift)\n    {\n      double s = 0;\n      for (Int i = 0; i < table_size; ++i)\n      {\n        Int j = i + shift;\n        if ( (j >= 0) && (j < table_size))\n        {\n          s += (ion_table1[i] - mean1) * (ion_table2[j] - mean2);\n        }\n      }\n      if (denom > 0)\n      {\n        results[shift + maxshift] = s / denom;\n      }\n    }\n    return results;\n  }\n\n  double XQuestScores::xCorrelationPrescore(const PeakSpectrum & spec1, const PeakSpectrum & spec2, double tolerance)\n  {\n    // return 0 = no correlation, when one of the spectra is empty\n    if (spec1.size() == 0 || spec2.size() == 0) {\n      return 0.0;\n    }\n\n    double maxionsize = std::max(spec1[spec1.size()-1].getMZ(), spec2[spec2.size()-1].getMZ());\n    Int table_size = ceil(maxionsize / tolerance)+1;\n    std::vector< double > ion_table1(table_size, 0);\n    std::vector< double > ion_table2(table_size, 0);\n\n    // Build tables of the same size, each bin has the size of the tolerance\n    for (Size i = 0; i < spec1.size(); ++i)\n    {\n      Size pos = static_cast<Size>(ceil(spec1[i].getMZ() / tolerance));\n      ion_table1[pos] = 1;\n    }\n    for (Size i = 0; i < spec2.size(); ++i)\n    {\n      Size pos =static_cast<Size>(ceil(spec2[i].getMZ() / tolerance));\n      ion_table2[pos] = 1;\n\n    }\n\n    double dot_product = 0.0;\n    for (Size i = 0; i < ion_table1.size(); ++i)\n    {\n      dot_product += ion_table1[i] * ion_table2[i];\n    }\n\n    // determine the smaller spectrum and normalize by the number of peaks in it\n    double peaks = std::min(spec1.size(), spec2.size());\n    return dot_product / peaks;\n  }\n\n}\n", "meta": {"hexsha": "a945f68a96c4515b074a4fbc60722695cd11a925", "size": 16089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/ANALYSIS/XLMS/XQuestScores.cpp", "max_stars_repo_name": "michalsta/OpenMS", "max_stars_repo_head_hexsha": "7eed34f65354c4abce0b98cf746e4bfce4a488ac", "max_stars_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-27T19:15:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-22T21:29:50.000Z", "max_issues_repo_path": "src/openms/source/ANALYSIS/XLMS/XQuestScores.cpp", "max_issues_repo_name": "michalsta/OpenMS", "max_issues_repo_head_hexsha": "7eed34f65354c4abce0b98cf746e4bfce4a488ac", "max_issues_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-10-29T20:59:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T15:37:14.000Z", "max_forks_repo_path": "src/openms/source/ANALYSIS/XLMS/XQuestScores.cpp", "max_forks_repo_name": "michalsta/OpenMS", "max_forks_repo_head_hexsha": "7eed34f65354c4abce0b98cf746e4bfce4a488ac", "max_forks_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-21T23:23:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T23:23:49.000Z", "avg_line_length": 37.8564705882, "max_line_length": 417, "alphanum_fraction": 0.6559139785, "num_tokens": 4260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.19406869663038656}}
{"text": "#include \"ros/ros.h\"\n#include \"rovi2/xyz.h\"\n#include \"rovi2/Movexyz.h\"\n#include \"rovi2/State.h\"\n#include \"rovi2/Q.h\"\n\n#include <rw/rw.hpp>\n#include <rw/math.hpp>\n#include <rw/math/Vector3D.hpp>\n#include <rw/math/Transform3D.hpp>\n#include <rw/kinematics/Frame.hpp>\n#include <rw/models/WorkCell.hpp>\n#include <rw/kinematics/State.hpp>\n#include <rw/models/Device.hpp>\n#include <rw/math/Q.hpp>\n#include <boost/algorithm/string.hpp>\n#include <rw/math/RPY.hpp>\n#include <sstream>\n\nrovi2::State robot_state;\n\nvoid robot_status_callback(const rovi2::State &msg)\n{\n  ROS_INFO(\"ROBOT_CALLBACK\");\n  robot_state = msg;\n  //ROS_INFO(\"Got a state\");\n}\n\nrw::math::Q toRw(const rovi2::Q& q)\n{ // From RobWork\n  rw::math::Q res(q.data.size());\n  for (std::size_t i = 0; i < q.data.size(); ++i)\n  {\n    res(i) = q.data[i];\n  }\n  return res;\n}\n\nint main(int argc, char** argv)\n{\n  ROS_INFO(\"vision_test_robot_node starting...\");\n  ros::init(argc, argv, \"vision_test_robot_node\");\n  ros::NodeHandle n;\n\n  ros::Subscriber subscribe_robot_status = n.subscribe(\"/rovi2/robot_node/Robot_state\",0,robot_status_callback);\n  ros::Duration(10).sleep();\n  ros::spinOnce();\n  rw::math::Vector3D<double> transP(-0.116075, -1.67057, 1.33754);\n  rw::math::Rotation3D<double> transR(rw::math::RPY<double>(-0.0375525, -0.0132076, -2.0942).toRotation3D());\n  rw::math::Transform3D<double> trans(transP, transR);\n\n  rw::kinematics::Frame* robot_base;\n  rw::kinematics::Frame* TCP_marker;\n\n  rw::models::WorkCell::Ptr _workcell = rw::loaders::WorkCellLoader::Factory::load(\"/home/mathias/catkin_ws/src/rovi2/WorkStation_3/WC3_Scene.wc.xml\");\n  rw::models::Device::Ptr _device = _workcell->findDevice(\"UR1\");\n  rw::kinematics::State _state =  _workcell->getDefaultState();\n\n  // Get frames\n  robot_base = _workcell->findFrame(\"UR1.Base\");\n  TCP_marker = _workcell->findFrame(\"WSG50.BallError\");\n  if(robot_base == NULL)\n  {\n    std::cout << \"robot_base not found\" << std::endl;\n  }\n  if(TCP_marker == NULL)\n  {\n    std::cout << \"TCP_marker not found\" << std::endl;\n  }\n\n\n  rw::math::Q q = toRw(robot_state.q);\n\n  std::stringstream buf;\n  buf << *(robot_base) << \" , \" << *(TCP_marker) << std::endl;\n  ROS_INFO(\"%s\",buf.str().c_str());\n  //rw::math::Q q(6,-0.4588, -1.7026, -0.9179, -0.5139, 0.4561, 0.0188);\n  //rw::math::Q q(6,-0.45886514427998293, -1.7026772253206577, -0.9179848271019003, -0.513925856428815, 0.45612188890540106, 0.0188171385940185);\n  _device->setQ(q,_state);\n  rw::math::Vector3D<double> robot_p = robot_base->fTf(TCP_marker,_state).P();\n  ROS_INFO(\"Robot start:\");\n  buf.str(\"\");\n  buf << \"Position: \"<< robot_p(0) << \" \" << robot_p(1) << \" \" << robot_p(2);\n  ROS_INFO(\"%s\",buf.str().c_str());\n\n  rovi2::Movexyz service_call;\n  //rovi2::xyz;\n  ROS_INFO(\"#1\");\n  rw::math::Vector3D<double> pos_robot(-0.26, -0.13, 1.22);\n  pos_robot = trans*pos_robot;\n\n  service_call.request.target.data.push_back(robot_p(0));//-0.4);//[0] = -0.4;\n  service_call.request.target.data.push_back(robot_p(1));//-0.4); //[1] = -0.4;\n  service_call.request.target.data.push_back(robot_p(2)-0.02);//0.6);\n  service_call.request.target.data.push_back(0);\n  service_call.request.target.data.push_back(0);\n  service_call.request.target.data.push_back(0);\n  for(int i = 0; i < 6; i++)\n    ROS_INFO(\"%f\",service_call.request.target.data[i]);\n  ros::service::call(\"/rovi2/robot_node/MoveXYZ\",service_call);\n  ROS_INFO(\"Response: %d\",service_call.response.success);\n  //ros::Duration(20).sleep();\n  ros::spinOnce();\n/*  ROS_INFO(\"#2\");\n  service_call.request.target.data.clear();\n  service_call.request.target.data.push_back(-0.4);//[0] = -0.4;\n  service_call.request.target.data.push_back(-0.4); //[1] = -0.4;\n  service_call.request.target.data.push_back(0.7);\n  service_call.request.target.data.push_back(0);\n  service_call.request.target.data.push_back(0);\n  service_call.request.target.data.push_back(0);\n  ros::service::call(\"/rovi2/robot_node/MoveXYZ\",service_call);\n  ROS_INFO(\"Response: %d\",service_call.response.success);\n*/\n  ros::Duration(2).sleep();\n  ros::spinOnce();\n  ROS_INFO(\"#3\");\n  ros::Duration(2).sleep();\n  ros::spinOnce();\n  ROS_INFO(\"#4\");\n  ros::Duration(2).sleep();\n  ros::spinOnce();\n}\n", "meta": {"hexsha": "ac3aa0fad64a5e40e379376ee5802a3fb4564357", "size": 4166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vision_test_move_robot.cpp", "max_stars_repo_name": "TobiasLundby/ROVI2", "max_stars_repo_head_hexsha": "d2666abf12196930074db910488e33d6fc43f7cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-07T14:33:00.000Z", "max_issues_repo_path": "src/vision_test_move_robot.cpp", "max_issues_repo_name": "TobiasLundby/ROVI2", "max_issues_repo_head_hexsha": "d2666abf12196930074db910488e33d6fc43f7cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-14T20:28:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-18T07:50:48.000Z", "max_forks_repo_path": "src/vision_test_move_robot.cpp", "max_forks_repo_name": "TobiasLundby/ROVI2", "max_forks_repo_head_hexsha": "d2666abf12196930074db910488e33d6fc43f7cc", "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.5967741935, "max_line_length": 151, "alphanum_fraction": 0.6771483437, "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.19406869268258634}}
{"text": "#ifndef ASLAM_PROB_DATA_ASSOC_POLICY_HPP\n#define ASLAM_PROB_DATA_ASSOC_POLICY_HPP\n\n#include <math.h>\n\n#include <boost/shared_ptr.hpp>\n\n#include <aslam/backend/ErrorTerm.hpp>\n#include <aslam/backend/PerIterationCallback.hpp>\n\n#include <vector>\n\nnamespace aslam {\nnamespace backend {\n\n// Update the weights of the error terms using a gaussian of the squared error,\n// i.e: exp(-lambda/2*(y -f(x))^2)\n// The matrix of error terms contains, in each row, the error terms whose\n// weights must be normalized together\nclass ProbDataAssocPolicy : public PerIterationCallback {\n public:\n  typedef boost::shared_ptr<ErrorTerm> ErrorTermPtr;\n  typedef boost::shared_ptr<std::vector<ErrorTermPtr>> ErrorTermGroup;\n  typedef boost::shared_ptr<std::vector<ErrorTermGroup>> ErrorTermGroups;\n\n  ProbDataAssocPolicy(ErrorTermGroups error_terms, double lambda);\n  // The optimizer will call this function before each iteration.\n  void callback() override;\n\n private:\n  ErrorTermGroups error_terms_;\n  double scaling_factor_;\n};\n}  // namespace backend\n}  // namespace aslam\n\n#endif /*ASLAM_PROB_DATA_ASSOC_POLICY_HPP*/\n", "meta": {"hexsha": "3fde497f599098a741c41e92a86214754660c137", "size": 1101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "aslam_backend/include/aslam/backend/ProbDataAssocPolicy.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/include/aslam/backend/ProbDataAssocPolicy.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/include/aslam/backend/ProbDataAssocPolicy.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": 28.9736842105, "max_line_length": 79, "alphanum_fraction": 0.7811080836, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.19406869268258628}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SIMD_ACOSH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIMD_ACOSH_HPP_INCLUDED\n\n#include <boost/simd/function/scalar/acosh.hpp>\n#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>\n#include <boost/simd/arch/common/simd/function/acosh.hpp>\n\n#endif\n", "meta": {"hexsha": "9ed7117713b2f831a0e78401b6b8af973cd0e792", "size": 673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/simd/acosh.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/simd/acosh.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/simd/acosh.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": 37.3888888889, "max_line_length": 100, "alphanum_fraction": 0.5631500743, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19401008630042818}}
{"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_CLZ_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_CLZ_HPP_INCLUDED\n\n#ifndef __GNUC__\n#include <boost/simd/function/scalar/ffs.hpp>\n#include <boost/simd/function/scalar/reversebits.hpp>\n#endif\n#ifdef BOOST_MSVC\n#include <intrin.h>\n#endif\n#include <boost/simd/function/scalar/bitwise_cast.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( clz_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::type64_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      result_t t1 = bitwise_cast<result_t>(a0);\n      BOOST_ASSERT_MSG( t1, \"clz not defined for 0\" );\n\n    #ifdef __GNUC__\n      return __builtin_clzll(t1);\n    #else\n      return ffs(reversebits(t1))-1;\n    #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( clz_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::type32_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      result_t t1 = bitwise_cast<result_t>(a0);\n      BOOST_ASSERT_MSG( t1, \"clz not defined for 0\" );\n\n    #ifdef __GNUC__\n      return __builtin_clz(t1);\n    #else\n      return ffs(reversebits(t1))-1;\n    #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( clz_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::type16_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE  bd::as_integer_t<A0> operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      using i_t = typename bd::as_integer_t<A0, unsigned>;\n      i_t t1 = bitwise_cast<i_t>(a0);\n      return clz(uint32_t(t1))-16;\n    }\n  };\n\n\n  BOOST_DISPATCH_OVERLOAD ( clz_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::type8_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE bd::as_integer_t<A0> operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      using i_t = typename bd::as_integer_t<A0, unsigned>;\n      i_t t1 = bitwise_cast<i_t>(a0);\n      return clz(uint32_t(t1))-24;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "4c934d50681c77690408b70b443048c9b012a1b0", "size": 2976, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/clz.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/clz.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/clz.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.1764705882, "max_line_length": 100, "alphanum_fraction": 0.5406586022, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.19401007115415148}}
{"text": "/*\n * Copyright (c) 2020 Andrew Price\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 * 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 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\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#include \"mps_voxels/planning/MotionPlanner.h\"\n#include \"mps_voxels/octree_utils.h\"\n#include \"mps_voxels/LocalOctreeServer.h\"\n#include \"mps_voxels/util/samplers.h\"\n#include \"mps_voxels/util/assert.h\"\n\n#include <moveit/planning_scene/planning_scene.h>\n\n#include <Eigen/StdVector>\n\n#include <tf_conversions/tf_eigen.h>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/convex_hull_2.h>\n#include <CGAL/circulator.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/min_quadrilateral_2.h>\n#include <boost/heap/priority_queue.hpp>\n#include <mps_voxels/planning/MotionPlanner.h>\n\n#define _unused(x) ((void)(x))\n\nnamespace mps\n{\n\nconst std::string MotionPlanner::CLUTTER_NAME = \"clutter\";\n\nEigen::Vector3d samplePointInMesh(const shapes::Mesh& m, std::mt19937& rng)\n{\n\tSimplexSampler ss(m.vertex_count);\n\tEigen::Map<const Eigen::Matrix3Xd> vertices(m.vertices, 3, m.vertex_count);\n\tEigen::VectorXd combo = ss.getPoint(rng);\n\treturn vertices * combo;\n}\n\nState stateFactory(const std::map<ObjectIndex, std::shared_ptr<Object>>& objects)\n{\n\tState objectState;\n\tfor (const auto& obj : objects)\n\t{\n\t\tobjectState.poses.emplace_hint(objectState.poses.end(), std::make_pair(obj.first, State::Pose::Identity()));\n\t}\n\treturn objectState;\n}\n\nbool arePointsInHandRegion(const octomap::OcTree* tree, const moveit::Pose& palmTworld)\n{\n\tEigen::Vector3d aabbMin(-0.05, -0.05, 0.0);\n\tEigen::Vector3d aabbMax(0.05, 0.05, 0.1);\n\n\tfor (const auto& p : getPoints(tree))\n\t{\n\t\tEigen::Vector3d p_palm = palmTworld * Eigen::Vector3d(p.x(), p.y(), p.z());\n\n\t\tbool contained = true;\n\t\tfor (int d = 0; d < 3; ++d)\n\t\t{\n\t\t\tcontained = contained && (aabbMin[d] < p_palm[d]) && (p_palm[d] < aabbMax[d]);\n\t\t}\n\n\t\tif (contained)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool arePointsInHandRegion(const Manipulator* manip, const octomap::OcTree* tree, const robot_state::RobotState& state, const moveit::Pose& robotTworld)\n{\n\tconst moveit::Pose& robotTpalm = state.getFrameTransform(manip->palmName);\n\tconst moveit::Pose palmTworld = robotTpalm.inverse(Eigen::Isometry) * robotTworld;\n\n\treturn arePointsInHandRegion(tree, palmTworld);\n}\n\nstd::priority_queue<MotionPlanner::RankedPose, std::vector<MotionPlanner::RankedPose>, ComparePoses> getGraspPoses(const octomap::OcTree* tree)\n{\n\tusing K =         CGAL::Exact_predicates_inexact_constructions_kernel;\n\tusing Point_2 =   K::Point_2;\n\tusing Polygon_2 = CGAL::Polygon_2<K>;\n\tusing RankedPose = MotionPlanner::RankedPose;\n\n\t// Get a point cloud representing the (shape-completed) segment\n\toctomap::point3d_collection segmentPoints = getPoints(tree);\n\tdouble minZ = std::numeric_limits<double>::infinity();\n\tdouble maxZ = -std::numeric_limits<double>::infinity();\n\tfor (const auto& pt : segmentPoints)\n\t{\n\t\tminZ = std::min(minZ, (double)pt.z());\n\t\tmaxZ = std::max(maxZ, (double)pt.z());\n\t}\n\n\tstd::vector<Point_2> cgal_points;\n\tfor (const auto& pt : segmentPoints)\n\t{\n\t\tcgal_points.emplace_back(Point_2(pt.x(), pt.y()));\n\t}\n\n\tPolygon_2 hull;\n//\tstd::vector<Point_2> hull;\n\tCGAL::convex_hull_2(cgal_points.begin(), cgal_points.end(), std::back_inserter(hull)); // O(nh) vs O(nlogn) ch_bykat\n\tMPS_ASSERT(hull.is_convex());\n\n//\tauto comp = [](const RankedPose& a, const RankedPose& b ) { return a.first < b.first; };\n\tstd::priority_queue<RankedPose, std::vector<RankedPose>, ComparePoses> graspPoses;\n\n\tconst size_t nPts = hull.size();\n\tfor (size_t i = 0; i < nPts; ++i)\n\t{\n\t\tconst Point_2& a_cgal = hull.vertex(i);\n\t\tconst Point_2& b_cgal = hull.vertex((i+1)%nPts);\n\t\tconst Eigen::Vector2d a(a_cgal.x(), a_cgal.y());\n\t\tconst Eigen::Vector2d b(b_cgal.x(), b_cgal.y());\n\t\tconst Eigen::Vector2d v = (hull.is_clockwise_oriented() ? b-a : a-b);\n\t\tconst Eigen::Vector2d vHat = v.normalized(); ///< Edge direction\n\t\tconst Eigen::Vector2d nHat(vHat.y(), -vHat.x()); ///< Normal direction to edge\n\n\t\tdouble minV = std::numeric_limits<double>::infinity();\n\t\tdouble maxV = -std::numeric_limits<double>::infinity();\n\t\tdouble maxN = -std::numeric_limits<double>::infinity();\n\t\tEigen::Vector2d maxNpt;\n\n\t\tfor (size_t j_step = 0; j_step < nPts-2; ++j_step)\n\t\t{\n\t\t\tsize_t j = (i+j_step)%nPts;\n\t\t\tconst Point_2& p_cgal = hull.vertex(j);\n\t\t\tconst Eigen::Vector2d p = Eigen::Vector2d(p_cgal.x(), p_cgal.y())-a;\n\n\t\t\tdouble projN = nHat.dot(p);\n\t\t\tdouble projV = vHat.dot(p);\n\n\t\t\tminV = std::min(minV, projV);\n\t\t\tmaxV = std::max(maxV, projV);\n\n\t\t\tMPS_ASSERT(projN > -1e-6);\n\t\t\tif (projN > maxN)\n\t\t\t{\n\t\t\t\tmaxN = projN;\n\t\t\t\tmaxNpt = p;\n\t\t\t}\n\t\t}\n\n//\t\tconst Eigen::Vector2d c = maxNpt - (maxN/2.0*nHat) + a; ///< Midpoint between active edge and distal point\n\t\tconst Eigen::Vector2d c = (a+b)/2.0 + (maxN/2.0*nHat);// + vHat/2.0;\n\t\tmoveit::Pose graspPose = moveit::Pose::Identity();\n\t\tgraspPose.translation().head<2>() = c;\n\t\tgraspPose.translation().z() = maxZ;\n\t\tgraspPose.linear().topLeftCorner<2,2>() << nHat, vHat;\n\n\t\tgraspPoses.push({v.norm(), graspPose});\n\t}\n\n\treturn graspPoses;\n}\n\n\nObjectSampler::ObjectSampler(const Scenario* scenario, const Scene* scene, const OccupancyData* env)\n\t: succeeded(false)\n{\n\t// By default, search through all shadow points\n\tconst octomap::point3d_collection* shadowPoints = &scene->occludedPts;\n\tif (!shadowPoints || shadowPoints->empty()) { throw std::runtime_error(\"No points shadowed in scene?!\"); }\n\n\tif (!env->obstructions.empty())\n\t{\n\t\tstd::cerr << \"Target is obstructed!\" << std::endl;\n\t\tfor (const auto& i : env->obstructions)\n\t\t{\n\t\t\tstd::cerr << i.first.id << \"\\t\";\n\t\t}\n\t\tstd::cerr << std::endl;\n\t}\n\n\t{\n\t\tstd::uniform_int_distribution<> uni(0, env->objects.size()-1);\n\t\tauto objIter = env->objects.begin();\n\t\tstd::advance(objIter, uni(scenario->rng()));\n\t\tid = objIter->first;\n\t\tcameraOrigin = octomap::point3d((float) scene->worldTcamera.translation().x(),\n\t\t                                (float) scene->worldTcamera.translation().y(),\n\t\t                                (float) scene->worldTcamera.translation().z());\n\n\t\tauto cvx = samplePointInMesh(*objIter->second->approximation, scenario->rng()).cast<float>();\n\t\tsamplePoint = {cvx.x(), cvx.y(), cvx.z()};\n\t\tray = samplePoint-cameraOrigin;\n\t\t// TODO: Set collision correctly here\n\t\tcollision = samplePoint;\n\t\tsucceeded = true;\n\t\treturn;\n\t}\n\n\tstd::uniform_real_distribution<> uni(0.0, std::nextafter(1.0, std::numeric_limits<double>::max()));\n\n\t// If the target object grasp is obstructed somehow\n\tif (!env->obstructions.empty() && uni(scenario->rng()) < 0.8)\n\t{\n\t\t// Select one obstructing object with uniform probability\n//\t\tstd::uniform_int_distribution<size_t> distr(0, env->obstructions.size()-1)\n\n\t\t// Select with weighted probability\n\t\tstd::vector<double> weights;\n\t\tfor (const auto& i : env->obstructions) { weights.push_back(i.second); }\n\t\tstd::discrete_distribution<size_t> distr(weights.begin(), weights.end());\n\n\t\tsize_t idx = distr(scenario->rng());\n\n\t\tauto it(env->obstructions.begin());\n\t\tstd::advance(it, idx);\n\t\tid = it->first;\n\n\t\t// Set that object's shadow to use for remainder of algorithm\n\t\tshadowPoints = &(env->objects.at(id)->shadow);\n\t\tstd::cerr << shadowPoints->size() << \" Shadow points in cell \" << id.id << std::endl;\n\t\tif (shadowPoints->empty()) { throw std::runtime_error(\"No points shadowed by shape?!\"); }\n\t}\n\n\tconst int N = static_cast<int>(shadowPoints->size());\n\tstd::vector<unsigned int> indices(N);\n\tstd::iota(indices.begin(), indices.end(), 0);\n\tstd::shuffle(indices.begin(), indices.end(), scenario->rng());\n\n\tcameraOrigin = octomap::point3d((float) scene->worldTcamera.translation().x(),\n\t                                (float) scene->worldTcamera.translation().y(),\n\t                                (float) scene->worldTcamera.translation().z());\n\n\tfor (const unsigned int index : indices)\n\t{\n\t\tsamplePoint = (*shadowPoints)[index];\n\n\t\t// Get a randomly selected shadowed point\n\t\tif (samplePoint.z()<0.05) { continue; }\n\t\tray = samplePoint-cameraOrigin;\n\t\tbool hit = scene->sceneOctree->castRay(cameraOrigin, ray, collision, true);\n\t\tMPS_ASSERT(hit);\n\t\tcollision = scene->sceneOctree->keyToCoord(scene->sceneOctree->coordToKey(collision)); // regularize\n\n\t\tif (scenario->shouldVisualize(\"object_sampling\"))\n\t\t{\n\t\t\t// Display occluded point and push frame\n\t\t\tstd::vector<tf::StampedTransform> tfs;\n\t\t\tconst auto time = ros::Time::now();\n\n\t\t\tEigen::Vector3d pt(samplePoint.x(), samplePoint.y(), samplePoint.z());\n\t\t\ttf::Transform t = tf::Transform::getIdentity();\n\t\t\tEigen::Vector3d pt_camera = scene->worldTcamera.inverse(Eigen::Isometry)*pt;\n\t\t\tt.setOrigin({pt_camera.x(), pt_camera.y(), pt_camera.z()});\n\t\t\ttfs.emplace_back(tf::StampedTransform(t, time, scene->cameraFrame, \"occluded_point\"));\n\n\t\t\tt.setOrigin({collision.x(), collision.y(), collision.z()});\n\t\t\ttfs.emplace_back(tf::StampedTransform(t, time, scenario->worldFrame, \"collision_point\"));\n\n\t\t\tscenario->broadcaster->sendTransform(tfs);\n\t\t}\n\n//\t\tif (!env->obstructions.empty())\n//\t\t{\n//\t\t\treturn;\n//\t\t}\n\n\t\tconst auto& objIdx = env->coordToObject({collision.x(), collision.y(), collision.z()});\n\t\tif (objIdx.id == VoxelRegion::FREE_SPACE)\n\t\t{\n\t\t\tROS_ERROR(\"Voxel was occluded by free space?\");\n\t\t\tcontinue;\n\t\t}\n\t\tObjectIndex pushSegmentID = objIdx;\n\n\t\tid = pushSegmentID;\n\t\tsucceeded = true;\n\t\treturn;\n\t}\n}\n\ndouble\nMotionPlanner::reward(const robot_state::RobotState& robotState, const Motion* motion) const\n{\n\tconst size_t nClusters = motion->state->poses.size();\n\tMPS_ASSERT(nClusters == env->objects.size());\n\n\tEigen::Matrix3Xd centroids(3, nClusters);\n\tint colIndex = 0;\n\tfor (const auto& obj : env->objects)\n\t{\n\t\tMPS_ASSERT(obj.second);\n\t\tMPS_ASSERT(obj.second->occupancy->size() > 0);\n\t\toctomap::point3d_collection segmentPoints = obj.second->points;\n\t\tEigen::Vector3d centroid = Eigen::Vector3d::Zero();\n\t\tfor (const auto& pt : segmentPoints)\n\t\t{\n\t\t\tcentroid += Eigen::Vector3d(pt.x(), pt.y(), pt.z());\n\t\t}\n\t\tcentroid /= static_cast<double>(segmentPoints.size());\n\n\t\tcentroids.col(colIndex) = motion->state->poses[obj.first] * centroid;\n\t\t++colIndex;\n\t}\n\n\tEigen::Vector3d centroid = centroids.rowwise().sum()/static_cast<double>(nClusters);\n\tEigen::Matrix3Xd deltas = centroids.colwise() - centroid;\n\tdouble spread = deltas.colwise().squaredNorm().sum();\n\n\tdouble changeScore = 0;\n\n\t// Compute change in umbras\n\tfor (const auto& obj : env->objects)\n\t{\n\t\tauto objIdx = obj.first;\n\t\tconst Pose& worldTobj_prime = motion->state->poses[objIdx];\n\t\tif (worldTobj_prime.matrix().isIdentity(1e-6)) { continue; }\n\n\t\tconst std::shared_ptr<octomap::OcTree>& segment = obj.second->occupancy;\n\n//\t\tconst Pose worldTobj_init = Pose::Identity();\n\t\tconst Pose worldTcamera_prime = /*worldTobj_init * */ worldTobj_prime.inverse(Eigen::Isometry) * scene->worldTcamera;\n\n\t\toctomap::point3d cameraOrigin((float) worldTcamera_prime.translation().x(), (float) worldTcamera_prime.translation().y(),\n\t\t                              (float) worldTcamera_prime.translation().z());\n//\n//\t\toctomap::point3d min = segment->getBBXMin(), max = segment->getBBXMax();\n//\t\tfor (int i = 0; i < 3; ++i)\n//\t\t{\n//\t\t\tmin(i) = std::min(min(i), (float)worldTcamera_prime.translation()[i]);\n//\t\t\tmax(i) = std::max(max(i), (float)worldTcamera_prime.translation()[i]);\n//\t\t}\n//\t\tsetBBox(min, max, segment);\n\n\t\t// Check occlusion of points attached to body\n\t\tconst std::vector<octomap::point3d>& umbra = obj.second->shadow;\n\t\tfor (size_t i = 0; i < umbra.size(); ++i)\n\t\t{\n\t\t\t// Check occlusion of points attached to world\n\t\t\toctomath::Vector3 ray = umbra[i]-cameraOrigin;\n\t\t\toctomap::point3d collision;\n\t\t\tbool occluded = segment->castRay(cameraOrigin, ray, collision, true, 2.0);\n\t\t\tif (!occluded)\n\t\t\t{\n\t\t\t\t// This world-attached point is now seen\n\t\t\t\tchangeScore+=1;\n\t\t\t}\n\n\t\t\t// TODO: Verify\n\t\t\tEigen::Vector3d pt_moved = worldTobj_prime * Eigen::Vector3d(umbra[i].x(), umbra[i].y(), umbra[i].z());\n\t\t\tray = octomap::point3d((float)pt_moved.x(), (float)pt_moved.y(), (float)pt_moved.z())-cameraOrigin;\n\t\t\toccluded = segment->castRay(cameraOrigin, ray, collision, true, 2.0);\n\t\t\tif (!occluded)\n\t\t\t{\n\t\t\t\t// This body-attached point is now seen\n\t\t\t\tchangeScore+=1;\n\t\t\t}\n\n\t\t}\n\n\t\tstd::cerr << \"Revealed \" << changeScore << \" voxels\" << std::endl;\n\t}\n\n\tauto compositeAction = std::dynamic_pointer_cast<CompositeAction>(motion->action);\n\n\t// Compute number of collisions\n\tcollision_detection::CollisionRequest collision_request;\n\tcollision_detection::CollisionResult collision_result;\n//\tcollision_request.contacts = true;\n\n\tint collisionCount = 0;\n\tfor (size_t actionIdx = 0; actionIdx < compositeAction->actions.size(); ++actionIdx)\n\t{\n\t\tauto jointTraj = std::dynamic_pointer_cast<JointTrajectoryAction>(compositeAction->actions[actionIdx]);\n\t\tif (jointTraj)\n\t\t{\n//\t\t\tauto* arm = scene->manipulators.front()->pModel->getJointModelGroup(jointTraj->jointGroupName);\n\t\t\tconst auto& manipulator = scenario->jointToManipulator.at(jointTraj->cmd.joint_names.front());\n\t\t\tcollision_detection::AllowedCollisionMatrix acm = gripperEnvironmentACM(manipulator);\n\n\t\t\tif (motion->state->poses.size() !=  env->objects.size()) { throw std::runtime_error(\"Whoopsie.\"); }\n\n\t\t\tfor (const auto& obj : env->objects)\n\t\t\t{\n\t\t\t\t// Since we're moving the objects, allow the gripper to touch moving objects\n\t\t\t\tif (!motion->state->poses[obj.first].matrix().isIdentity(1e-6))\n\t\t\t\t{\n\t\t\t\t\tacm.setEntry(std::to_string(obj.first.id), manipulator->gripper->getLinkModelNames(), true);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (size_t stepIdx = 0; stepIdx < jointTraj->cmd.points.size(); ++stepIdx)\n\t\t\t{\n\t\t\t\tjointTraj->cmd.points[stepIdx].positions;\n\t\t\t\trobot_state::RobotState collisionState(robotState);\n\t\t\t\tcollisionState.setJointGroupPositions(manipulator->arm, jointTraj->cmd.points[stepIdx].positions);\n\t\t\t\tcollisionState.setJointGroupPositions(manipulator->gripper, manipulator->getGripperOpenJoints());\n\t\t\t\tcollisionState.update();\n\t\t\t\tplanningScene->checkCollision(collision_request, collision_result, collisionState, acm);\n\t\t\t\tif (collision_result.collision)\n\t\t\t\t{\n\t\t\t\t\t// This step collided with the world\n\t\t\t\t\t++collisionCount;\n\n//\t\t\t\t\tfor (const auto& p : collision_result.contacts)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tstd::cerr << p.first.first << \" X \" << p.first.second << std::endl;\n//\t\t\t\t\t\tfor (const auto& c : p.second)\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tstd::cerr << c.pos.transpose() << std::endl;\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\t// Compute direction of push/slide\n\tdouble dir = 0;\n\tif (compositeAction->primaryAction >= 0)\n\t{\n\t\tauto jointTraj = std::dynamic_pointer_cast<JointTrajectoryAction>(\n\t\t\tcompositeAction->actions[compositeAction->primaryAction]);\n\t\tif (jointTraj)\n\t\t{\n\t\t\tif (jointTraj->palm_trajectory.size()>1)\n\t\t\t{\n\t\t\t\tconst Pose& begin = jointTraj->palm_trajectory.front();\n\t\t\t\tconst Pose& end = jointTraj->palm_trajectory.back();\n\t\t\t\tEigen::Vector3d cb = (begin.translation()\n\t\t\t\t                      -centroid).normalized(); ///< Vector from centroid to beginning of move\n\t\t\t\tEigen::Vector3d be = end.translation()-begin.translation(); ///< Vector of move\n\t\t\t\tdir = cb.dot(be);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn spread + 3.0*dir - 5.0*collisionCount + changeScore/2000.0;\n}\n\ncollision_detection::WorldPtr\ncomputeCollisionWorld(const Scene* scene, const OccupancyData& occupancy)\n{\n\tauto world = std::make_shared<collision_detection::World>();\n\n\tmoveit::Pose robotTworld = scene->worldTrobot.inverse(Eigen::Isometry);\n\n\tfor (const auto& obstacle : scene->scenario->staticObstacles)\n\t{\n\t\tworld->addToObject(MotionPlanner::CLUTTER_NAME, obstacle.first, robotTworld * obstacle.second);\n\t}\n\n\t// Use aliasing shared_ptr constructor\n//\tworld->addToObject(CLUTTER_NAME,\n//\t                   std::make_shared<shapes::OcTree>(std::shared_ptr<octomap::OcTree>(std::shared_ptr<octomap::OcTree>{}, sceneOctree)),\n//\t                   robotTworld);\n\n\tif (occupancy.objects.empty())\n\t{\n\t\tROS_WARN(\"No objects found in current occupancy state.\");\n\t}\n\n\tfor (const auto& obj : occupancy.objects)\n\t{\n\t\tconst std::shared_ptr<octomap::OcTree>& segment = obj.second->occupancy;\n\t\tworld->addToObject(std::to_string(obj.first.id), std::make_shared<shapes::OcTree>(segment), robotTworld);\n\t}\n\n//\tfor (auto& approxSegment : approximateSegments)\n//\t{\n//\t\tworld->addToObject(CLUTTER_NAME, approxSegment, robotTworld);\n//\t}\n\n\treturn world;\n}\n\nplanning_scene::PlanningSceneConstPtr\nMotionPlanner::computePlanningScene(bool useCollisionObjects)\n{\n\tcollision_detection::WorldPtr world;\n\tif (useCollisionObjects)\n\t{\n\t\tassert(env);\n\t\tworld = computeCollisionWorld(scene.get(), *env);\n\t}\n\telse\n\t{\n\t\tworld = std::make_shared<collision_detection::World>();\n\t}\n\tcollisionWorld = world; // NB: collisionWorld is const, but the planning scene constructor is not\n\tplanningScene = std::make_shared<planning_scene::PlanningScene>(scene->scenario->manipulators.front()->pModel, world);\n\treturn planningScene;\n}\n\ncollision_detection::AllowedCollisionMatrix\nMotionPlanner::gripperEnvironmentACM(const std::shared_ptr<Manipulator>& manipulator) const\n{\n\tcollision_detection::AllowedCollisionMatrix acm;\n//\tacm.setEntry(true); // Only check things we're explicitly requesting\n\tstd::set<std::string> gripperLinks(manipulator->gripper->getLinkModelNames().begin(), manipulator->gripper->getLinkModelNames().end());\n\tfor (const auto& linkName : manipulator->pModel->getLinkModelNames())\n\t{\n\t\t// Not sure why this is necessary, but it seems to be\n\t\tif (gripperLinks.find(linkName) == gripperLinks.end())\n\t\t{\n\t\t\tacm.setDefaultEntry(linkName, true);\n\t\t}\n\t}\n\tfor (const auto& link1Name : gripperLinks)\n\t{\n\t\tfor (const auto& link2Name : gripperLinks)\n\t\t{\n\t\t\tif (link1Name == link2Name) { continue; }\n\n\t\t\tacm.setEntry(link1Name, link2Name, true);\n\t\t}\n\t}\n\tacm.setEntry(CLUTTER_NAME, manipulator->gripper->getLinkModelNames(), false);\n\tfor (size_t s = 0; s < env->objects.size(); ++s)\n\t{\n\t\tacm.setEntry(std::to_string(s), manipulator->gripper->getLinkModelNames(), false);\n\t}\n\n\treturn acm;\n}\n\nbool\nMotionPlanner::gripperEnvironmentCollision(const std::shared_ptr<Manipulator>& manipulator, const robot_state::RobotState& collisionState) const\n{\n\tMPS_ASSERT(collisionWorld);\n\n\tcollision_detection::CollisionRequest collision_request;\n\tcollision_detection::CollisionResult collision_result;\n//\tcollision_request.contacts = true;\n\n\tcollision_detection::AllowedCollisionMatrix acm = gripperEnvironmentACM(manipulator);\n\tplanningScene->checkCollision(collision_request, collision_result, collisionState, acm);\n\n\treturn collision_result.collision;\n//\tif (collision_result.collision)\n//\t{\n//\t\tfor (size_t i = 0; i < manipulator->gripper->getVariableCount(); ++i)\n//\t\t{\n//\t\t\tconst auto& name = manipulator->gripper->getVariableNames()[i];\n//\t\t\tEigen::Map<const Eigen::VectorXd> pos(collisionState.getJointPositions(name), manipulator->gripper->getJointModel(name)->getVariableCount());\n//\t\t\tstd::cerr << name << \": \" << pos.transpose() << std::endl;\n//\t\t}\n//\t\tfor (const auto& p : collision_result.contacts)\n//\t\t{\n//\t\t\tstd::cerr << p.first.first << \" X \" << p.first.second << std::endl;\n//\t\t\tfor (const auto& c : p.second)\n//\t\t\t{\n//\t\t\t\tstd::cerr << c.pos.transpose() << std::endl;\n//\t\t\t}\n//\t\t}\n//\t\treturn true;\n//\t}\n//\treturn false;\n}\n\n\nbool MotionPlanner::addPhysicalObstructions(const std::shared_ptr<Manipulator>& manipulator,\n                                            const robot_state::RobotState& collisionState,\n                                            OccupancyData::ObstructionList& collisionObjects) const\n{\n\tif (gripperEnvironmentCollision(manipulator, collisionState))\n\t{\n\t\tstd::cerr << \"Grasp collided with environment.\" << std::endl;\n\t\tcollision_detection::CollisionRequest collision_request;\n\t\tcollision_detection::CollisionResult collision_result;\n\t\tcollision_request.contacts = true;\n\n\t\tcollision_detection::AllowedCollisionMatrix acm = gripperEnvironmentACM(manipulator);\n\t\tplanningScene->checkCollision(collision_request, collision_result, collisionState, acm);\n\n\t\toctomap::point3d cameraOrigin((float) scene->worldTcamera.translation().x(),\n\t\t                              (float) scene->worldTcamera.translation().y(),\n\t\t                              (float) scene->worldTcamera.translation().z());\n\t\tfor (auto& cts : collision_result.contacts)\n\t\t{\n\t\t\tstd::cerr << cts.second.size() << std::endl;\n\n\t\t\tfor (const auto& obj : env->objects)\n\t\t\t{\n\t\t\t\tauto objIdx = obj.first;\n\t\t\t\tconst auto& segmentOctree = obj.second->occupancy;\n\n\t\t\t\t// For each contact point, cast ray from camera to point; see if it hits completed shape\n\t\t\t\tfor (auto& c : cts.second)\n\t\t\t\t{\n\t\t\t\t\tEigen::Vector3d p = scene->worldTrobot * c.pos;\n\t\t\t\t\tstd::cerr << p.transpose() << std::endl;\n\n\t\t\t\t\toctomap::point3d collision = octomap::point3d((float)p.x(), (float)p.y(), (float)p.z());\n\t\t\t\t\t//\t\t\t\t\t\t\t\tcollision = scene->sceneOctree->keyToCoord(scene->sceneOctree->coordToKey(collision));\n\n\t\t\t\t\tstd::cerr << \"raycasting\" << std::endl;\n\t\t\t\t\toctomath::Vector3 ray = collision-cameraOrigin;\n\n\t\t\t\t\tbool hit = segmentOctree->castRay(cameraOrigin, ray, collision, true);\n\t\t\t\t\tif (hit)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (env->targetObjectID && env->targetObjectID->id == objIdx.id)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::cerr << \"Attempt to grasp object resulted in collision with object. (Are the grippers open?)\" << std::endl;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcollisionObjects[objIdx] += 1.0;\n//\t\t\t\t\t\tcollisionObjects.insert(objIdx);\n\t\t\t\t\t\tstd::cerr << \"hit \" << objIdx.id << std::endl;\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\treturn true;\n\t}\n\treturn false;\n}\n\nbool MotionPlanner::addVisualObstructions(const ObjectIndex target, OccupancyData::ObstructionList& collisionObjects) const\n{\n\tbool hasVisualObstruction = false;\n\tfor (const auto& targetPt : env->objects.at(target)->points)\n\t{\n\t\toctomap::point3d cameraOrigin((float) scene->worldTcamera.translation().x(), (float) scene->worldTcamera.translation().y(),\n\t\t                              (float) scene->worldTcamera.translation().z());\n\t\toctomath::Vector3 ray = targetPt-cameraOrigin;\n\t\toctomap::point3d collision;\n\t\tbool hit = scene->sceneOctree->castRay(cameraOrigin, ray, collision);\n\t\tif (hit)\n\t\t{\n\t\t\tcollision = scene->sceneOctree->keyToCoord(scene->sceneOctree->coordToKey(collision));\n\t\t\tconst auto& objIdx = env->coordToObject({collision.x(), collision.y(), collision.z()});\n\t\t\tif (objIdx.id == VoxelRegion::FREE_SPACE)\n\t\t\t{\n\t\t\t\tif (objIdx.id!=target.id)\n\t\t\t\t{\n\t\t\t\t\tcollisionObjects[objIdx] += 1.0;\n\t\t\t\t\thasVisualObstruction = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn hasVisualObstruction;\n}\n\nstd::shared_ptr<Motion>\nMotionPlanner::samplePush(const robot_state::RobotState& robotState, Introspection* info) const\n{\n\t// TODO: Set hand posture before planning\n\t// Check whether the hand collides with the scene\n\tfor (const auto& manipulator : scenario->manipulators)\n\t{\n\t\tif (gripperEnvironmentCollision(manipulator, robotState))\n\t\t{\n\t\t\tstd::cerr << manipulator->gripper->getName() << \" starts in collision. No solutions will be possible.\" << std::endl;\n\t\t\treturn std::shared_ptr<Motion>();\n\t\t}\n\t}\n\n\tPose robotTworld = scene->worldTrobot.inverse(Eigen::Isometry);\n\tState objectState = stateFactory(env->objects);\n\n\t// Get an object to slide\n\tconst ObjectSampler sampleInfo(scenario.get(), scene.get(), env.get());\n\tif (info) { info->objectSampleInfo = sampleInfo; }\n\tif (!sampleInfo)\n\t{\n\t\tROS_WARN_STREAM(\"Object sampling failed.\");\n\t\treturn std::shared_ptr<Motion>();\n\t}\n\tconst octomap::OcTree* tree = env->objects.at(sampleInfo.id)->occupancy.get();\n\tif (getPoints(tree).empty())\n\t{\n\t\tROS_ERROR_STREAM(\"Object occupancy tree is empty.\");\n\t}\n\n\tPose pushFrame;\n\tEigen::Vector3d gHat = -Eigen::Vector3d::UnitZ();\n\tEigen::Vector3d pHat = -Eigen::Map<const Eigen::Vector3f>(&sampleInfo.ray(0)).cast<double>().cross(gHat).normalized();\n\tEigen::Vector3d nHat = gHat.cross(pHat).normalized();\n\n\tpushFrame.linear() << pHat.normalized(), nHat.normalized(), gHat.normalized();\n\tpushFrame.translation() = Eigen::Map<const Eigen::Vector3f>(&sampleInfo.collision(0)).cast<double>();\n\n//\ttrajectory_msgs::JointTrajectory cmd;\n\tPoseSequence pushGripperFrames(2, moveit::Pose::Identity());\n\tconst octomap::point3d_collection& segmentPoints = env->objects.at(sampleInfo.id)->points;\n\n\tEigen::Vector3d minProj = Eigen::Vector3d::Ones() * std::numeric_limits<float>::max();\n\tEigen::Vector3d maxProj = Eigen::Vector3d::Ones() * std::numeric_limits<float>::lowest();\n\tfor (const auto& segPt : segmentPoints)\n\t{\n\t\tEigen::Vector3d pushFramePt = pushFrame.linear().transpose() * Eigen::Map<const Eigen::Vector3f>(&segPt(0)).cast<double>();\n\t\tfor (int d=0; d < 3; ++d)\n\t\t{\n\t\t\tminProj[d] = std::min(minProj[d], pushFramePt[d]);\n\t\t\tmaxProj[d] = std::max(maxProj[d], pushFramePt[d]);\n\t\t}\n\t}\n\n\tconst double GRIPPER_HALFWIDTH = 4.0*2.54/100.0;\n\tpushGripperFrames[0].translation() = pushFrame.linear() * Eigen::Vector3d(maxProj.x(), (maxProj.y()+minProj.y())/2.0, maxProj.z())\n\t                                     + GRIPPER_HALFWIDTH*Eigen::Vector3d::UnitZ();\n\tpushGripperFrames[1].translation() = pushFrame.linear() * Eigen::Vector3d(minProj.x(), (maxProj.y()+minProj.y())/2.0, maxProj.z())\n\t                                     + GRIPPER_HALFWIDTH*Eigen::Vector3d::UnitZ();\n\tpushGripperFrames[0].linear() = pushFrame.linear()\n\t                                *(Eigen::AngleAxisd(-M_PI/2.0, Eigen::Vector3d::UnitY())\n\t                                  *Eigen::AngleAxisd(M_PI/2.0, Eigen::Vector3d::UnitZ())).matrix();\n\tpushGripperFrames[1].linear() = pushFrame.linear()\n\t                                *(Eigen::AngleAxisd(M_PI/2.0, Eigen::Vector3d::UnitY())\n\t                                  *Eigen::AngleAxisd(-M_PI/2.0, Eigen::Vector3d::UnitZ())).matrix();\n\n\t// Display occluded point and push frame\n\tif (scenario->shouldVisualize(\"push_sampling\"))\n\t{\n\t\tstd::vector<tf::StampedTransform> tfs;\n\t\tros::Time time = ros::Time::now();\n\t\ttf::Transform t = tf::Transform::getIdentity();\n\t\ttf::poseEigenToTF(pushFrame, t);\n\t\ttfs.emplace_back(tf::StampedTransform(t, time, scenario->worldFrame, \"push_frame\"));\n\t\ttf::poseEigenToTF(pushGripperFrames[0], t);\n\t\ttfs.emplace_back(tf::StampedTransform(t, time, scenario->worldFrame, \"push_gripper_frame_0\"));\n\t\ttf::poseEigenToTF(pushGripperFrames[1], t);\n\t\ttfs.emplace_back(tf::StampedTransform(t, time, scenario->worldFrame, \"push_gripper_frame_1\"));\n\t\tscenario->broadcaster->sendTransform(tfs);\n\t}\n\n\tpushGripperFrames.erase(std::remove_if(pushGripperFrames.begin(), pushGripperFrames.end(),\n\t                                 [&](const moveit::Pose& p){ return !arePointsInHandRegion(tree, p.inverse(Eigen::Isometry));}),\n\t                        pushGripperFrames.end());\n\tif (pushGripperFrames.empty())\n\t{\n\t\tROS_WARN_STREAM(\"No pushing frames contain points.\");\n\t\treturn std::shared_ptr<Motion>();\n\t}\n\n\t// Shuffle manipulators (without shuffling underlying array)\n\tstd::vector<unsigned int> manip_indices(scenario->manipulators.size());\n\tstd::iota(manip_indices.begin(), manip_indices.end(), 0);\n\tstd::shuffle(manip_indices.begin(), manip_indices.end(), scenario->rng());\n\n\t// Shuffle push directions (without shuffling underlying array)\n\tstd::vector<unsigned int> push_indices(pushGripperFrames.size());\n\tstd::iota(push_indices.begin(), push_indices.end(), 0);\n\tstd::shuffle(push_indices.begin(), push_indices.end(), scenario->rng());\n\n\tstd::uniform_int_distribution<int> stepDistr(15, 20);\n\n\tconst int INTERPOLATE_STEPS = 25;\n\tconst int TRANSIT_INTERPOLATE_STEPS = 50;\n//\tconst int SAMPLE_ATTEMPTS = 100;\n//\tconst double PALM_DISTANCE = 0.035;\n\tconst double APPROACH_HEIGHT = 0.25;\n//\tconst double TABLE_BUFFER = 0.20;\n//\tconst double Z_SAFETY_HEIGHT = 0.18;\n\n\tfor (unsigned int push_idx : push_indices)\n\t{\n\t\tconst auto& pushGripperFrame = pushGripperFrames[push_idx];\n\t\tconst double stepSize = 0.015;\n\t\tconst int nSteps = stepDistr(scenario->rng());\n\t\tPoseSequence pushTrajectory;\n\t\tfor (int s = -15; s < nSteps; ++s)\n\t\t{\n\t\t\tmoveit::Pose step = pushGripperFrame;\n\t\t\tstep.translation() += s*stepSize*pushGripperFrame.linear().col(2);\n\t\t\tpushTrajectory.push_back(step);\n\t\t}\n\n\t\tfor (unsigned int manip_idx : manip_indices)\n\t\t{\n\t\t\tconst auto & manipulator = scenario->manipulators[manip_idx];\n\n\t\t\tstd::vector<std::vector<double>> sln;\n\n\t\t\tsln = manipulator->IK(pushTrajectory.back(), robotTworld, robotState);\n\t\t\tif (sln.empty()) { continue; }\n\n\t\t\tsln = manipulator->IK(pushTrajectory.front(), robotTworld, robotState);\n\t\t\tif (sln.empty()) { continue; }\n\n\t\t\t// Check whether the hand collides with the scene\n\t\t\t{\n\t\t\t\trobot_state::RobotState collisionState(robotState);\n\t\t\t\tcollisionState.setJointGroupPositions(manipulator->arm, sln.front());\n\t\t\t\tcollisionState.setJointGroupPositions(manipulator->gripper, manipulator->getGripperOpenJoints());\n\t\t\t\tcollisionState.update();\n\t\t\t\tif (gripperEnvironmentCollision(manipulator, collisionState))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Allocate the action sequence needed for a slide\n\t\t\tstd::shared_ptr<CompositeAction> compositeAction = std::make_shared<CompositeAction>();\n\t\t\tauto pregraspAction = std::make_shared<GripperCommandAction>();  compositeAction->actions.push_back(pregraspAction);\n\t\t\tauto transitAction = std::make_shared<JointTrajectoryAction>();  compositeAction->actions.push_back(transitAction);\n\t\t\tauto approachAction = std::make_shared<JointTrajectoryAction>(); compositeAction->actions.push_back(approachAction);\n\t\t\tauto slideAction = std::make_shared<JointTrajectoryAction>();    compositeAction->actions.push_back(slideAction);\n\t\t\tauto retractAction = std::make_shared<JointTrajectoryAction>();  compositeAction->actions.push_back(retractAction);\n\t\t\tauto homeAction = std::make_shared<JointTrajectoryAction>();     compositeAction->actions.push_back(homeAction);\n\t\t\tcompositeAction->primaryAction = 3;\n\n\t\t\t// Lay out the Cartesian Path\n\t\t\tmoveit::Pose gripperApproachPose = pushTrajectory.front();\n\t\t\tgripperApproachPose.translation() += APPROACH_HEIGHT*Eigen::Vector3d::UnitZ();\n\n\t\t\tmoveit::Pose gripperRetractPose = pushTrajectory.back();\n\t\t\tgripperRetractPose.translation() += APPROACH_HEIGHT*Eigen::Vector3d::UnitZ();\n\n\t\t\tPoseSequence approachTrajectory, slideTrajectory, retractTrajectory, fullTrajectory;\n\n\t\t\tmanipulator->interpolate(gripperApproachPose, pushTrajectory.front(), approachTrajectory, INTERPOLATE_STEPS/2);\n\t\t\tmanipulator->interpolate(pushTrajectory.front(), pushTrajectory.back(), slideTrajectory, INTERPOLATE_STEPS);\n\t\t\tmanipulator->interpolate(pushTrajectory.back(), gripperRetractPose, retractTrajectory, INTERPOLATE_STEPS/2);\n\n\t\t\tfullTrajectory.reserve(approachTrajectory.size()+slideTrajectory.size()+retractTrajectory.size());\n\t\t\tfullTrajectory.insert(fullTrajectory.end(), approachTrajectory.begin(), approachTrajectory.end());\n\t\t\tfullTrajectory.insert(fullTrajectory.end(), slideTrajectory.begin(), slideTrajectory.end());\n\t\t\tfullTrajectory.insert(fullTrajectory.end(), retractTrajectory.begin(), retractTrajectory.end());\n\n\t\t\ttrajectory_msgs::JointTrajectory cmd;\n\t\t\tif (manipulator->cartesianPath(fullTrajectory, robotTworld, robotState, cmd))\n\t\t\t{\n\t\t\t\tstd::shared_ptr<Motion> motion = std::make_shared<Motion>();\n\t\t\t\tmotion->state = std::make_shared<State>(objectState);\n\t\t\t\tmotion->action = compositeAction;\n\n\t\t\t\t// Pregrasp\n\t\t\t\tpregraspAction->grasp.finger_a_command.position = 0.0;\n\t\t\t\tpregraspAction->grasp.finger_a_command.speed = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_a_command.force = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_b_command.position = 0.0;\n\t\t\t\tpregraspAction->grasp.finger_b_command.speed = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_b_command.force = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_c_command.position = 0.0;\n\t\t\t\tpregraspAction->grasp.finger_c_command.speed = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_c_command.force = 1.0;\n\t\t\t\tpregraspAction->grasp.scissor_command.position = 0.1;\n\t\t\t\tpregraspAction->grasp.scissor_command.speed = 1.0;\n\t\t\t\tpregraspAction->grasp.scissor_command.force = 1.0;\n\t\t\t\tpregraspAction->jointGroupName = manipulator->gripper->getName();\n\n\t\t\t\t// Move to start\n\t\t\t\trobot_state::RobotState approachState(robotState);\n\t\t\t\tapproachState.setJointGroupPositions(manipulator->arm, cmd.points.front().positions);\n\t\t\t\tapproachState.updateCollisionBodyTransforms();\n\t\t\t\tif (!manipulator->interpolate(robotState, approachState, transitAction->cmd, TRANSIT_INTERPOLATE_STEPS, planningScene))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Approach\n\t\t\t\tapproachAction->palm_trajectory = approachTrajectory;\n\t\t\t\tapproachAction->cmd.joint_names = cmd.joint_names;\n\t\t\t\tapproachAction->cmd.points.insert(approachAction->cmd.points.end(), cmd.points.begin(), cmd.points.begin()+approachTrajectory.size()+1);\n\n\t\t\t\t// Slide\n\t\t\t\tslideAction->palm_trajectory = slideTrajectory;\n\t\t\t\tslideAction->cmd.joint_names = cmd.joint_names;\n\t\t\t\tslideAction->cmd.points.insert(slideAction->cmd.points.end(), cmd.points.begin()+approachTrajectory.size(), cmd.points.begin()+approachTrajectory.size()+slideTrajectory.size()+1);\n\t\t\t\tmotion->state->poses[sampleInfo.id] = pushTrajectory.front().inverse(Eigen::Isometry) * pushTrajectory.back();\n\n\t\t\t\t// Retract\n\t\t\t\tretractAction->palm_trajectory = retractTrajectory;\n\t\t\t\tretractAction->cmd.joint_names = cmd.joint_names;\n\t\t\t\tretractAction->cmd.points.insert(retractAction->cmd.points.end(), cmd.points.begin()+approachTrajectory.size()+slideTrajectory.size(), cmd.points.end());\n\n\t\t\t\t// Move to home\n\t\t\t\trobot_state::RobotState retractState(robotState);\n\t\t\t\tretractState.setJointGroupPositions(manipulator->arm, cmd.points.back().positions);\n\t\t\t\tretractState.updateCollisionBodyTransforms();\n\t\t\t\tif (!manipulator->interpolate(retractState, robotState, homeAction->cmd, TRANSIT_INTERPOLATE_STEPS, planningScene))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tmotion->targets.push_back(sampleInfo.id);\n\n\t\t\t\tMPS_ASSERT(motion->state->poses.size() == env->objects.size());\n\t\t\t\treturn motion;\n\t\t\t}\n\t\t}\n\t}\n\n\tROS_WARN_STREAM(\"Other pushing failure.\");\n\treturn std::shared_ptr<Motion>();\n}\n\nstd::shared_ptr<Motion>\nMotionPlanner::sampleSlide(const robot_state::RobotState& robotState, Introspection* info) const\n{\n\t// TODO: Set hand posture before planning\n\t// Check whether the hand collides with the scene\n\tfor (const auto& manipulator : scenario->manipulators)\n\t{\n\t\tif (gripperEnvironmentCollision(manipulator, robotState))\n\t\t{\n\t\t\tstd::cerr << manipulator->gripper->getName() << \" starts in collision. No solutions will be possible.\" << std::endl;\n\t\t\treturn std::shared_ptr<Motion>();\n\t\t}\n\t}\n\n\tPose robotTworld = scene->worldTrobot.inverse(Eigen::Isometry);\n\tState objectState = stateFactory(env->objects);\n\n\t// Get an object to slide\n\tconst ObjectSampler sampleInfo(scenario.get(), scene.get(), env.get());\n\tif (info) { info->objectSampleInfo = sampleInfo; }\n\tif (!sampleInfo)\n\t{\n\t\tROS_WARN_STREAM(\"Object sampling failed.\");\n\t\treturn std::shared_ptr<Motion>();\n\t}\n\tconst octomap::OcTree* tree = env->objects.at(sampleInfo.id)->occupancy.get();\n\tif (getPoints(tree).empty())\n\t{\n\t\tROS_ERROR_STREAM(\"Object occupancy tree is empty.\");\n\t}\n\n\t// Get potential grasps\n\tauto graspPoses = getGraspPoses(tree);\n\n\tconst int INTERPOLATE_STEPS = 25;\n\tconst int TRANSIT_INTERPOLATE_STEPS = 50;\n//\tconst int SAMPLE_ATTEMPTS = 100;\n\tconst double PALM_DISTANCE = 0.025;\n\tconst double APPROACH_DISTANCE = 0.15;\n\tconst double TABLE_BUFFER = 0.20;\n\tconst double Z_SAFETY_HEIGHT = 0.16;\n\n\ttrajectory_msgs::JointTrajectory cmd;\n\tstd::uniform_real_distribution<double> xDistr(scene->minExtent.x()+TABLE_BUFFER, scene->maxExtent.x()-TABLE_BUFFER);\n\tstd::uniform_real_distribution<double> yDistr(scene->minExtent.y()+TABLE_BUFFER, scene->maxExtent.y()-TABLE_BUFFER);\n\tstd::uniform_real_distribution<double> thetaDistr(0.0, 2.0*M_PI);\n\n\t// Shuffle manipulators (without shuffling underlying array)\n\tstd::vector<unsigned int> manip_indices(scenario->manipulators.size());\n\tstd::iota(manip_indices.begin(), manip_indices.end(), 0);\n\tstd::shuffle(manip_indices.begin(), manip_indices.end(), scenario->rng());\n\n\twhile (!graspPoses.empty())\n\t{\n\t\tmoveit::Pose gripperPose = graspPoses.top().second;\n\t\tgraspPoses.pop();\n\t\tgripperPose.linear() = gripperPose.linear() * Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitX()).matrix();\n\t\tgripperPose.translation() -= PALM_DISTANCE*gripperPose.linear().col(2);\n\t\tgripperPose.translation().z() = std::max(gripperPose.translation().z(), Z_SAFETY_HEIGHT);\n\n\t\tif (!arePointsInHandRegion(tree, gripperPose.inverse(Eigen::Isometry)))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (scenario->shouldVisualize(\"slide_sampling\"))\n\t\t{\n\t\t\ttf::Transform t = tf::Transform::getIdentity();\n\t\t\ttf::poseEigenToTF(gripperPose, t);\n\t\t\tscenario->broadcaster->sendTransform(tf::StampedTransform(t, ros::Time::now(), scenario->worldFrame, \"putative_start\"));\n\t\t}\n\n\t\tfor (unsigned int manip_idx : manip_indices)\n\t\t{\n\t\t\tconst auto& manipulator = scenario->manipulators[manip_idx];\n\t\t\tstd::vector<std::vector<double>> sln = manipulator->IK(gripperPose, robotTworld, robotState);\n\t\t\tif (!sln.empty())\n\t\t\t{\n\t\t\t\t// Check whether the hand collides with the scene\n\t\t\t\t{\n\t\t\t\t\trobot_state::RobotState collisionState(robotState);\n\t\t\t\t\tcollisionState.setJointGroupPositions(manipulator->arm, sln.front());\n\t\t\t\t\tcollisionState.setJointGroupPositions(manipulator->gripper, manipulator->getGripperOpenJoints());\n\t\t\t\t\tcollisionState.update();\n\t\t\t\t\tif (gripperEnvironmentCollision(manipulator, collisionState))\n\t\t\t\t\t{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmoveit::Pose goalPose;\n//\t\t\t\tfor (int attempt = 0; attempt < SAMPLE_ATTEMPTS; ++attempt)\n\t\t\t\t{\n\t\t\t\t\tgoalPose = moveit::Pose::Identity();\n\t\t\t\t\tgoalPose.linear() = goalPose.linear() * Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitX()).matrix();\n\t\t\t\t\tgoalPose.linear() = goalPose.linear() * Eigen::AngleAxisd(thetaDistr(scenario->rng()), Eigen::Vector3d::UnitZ()).matrix();\n\t\t\t\t\tgoalPose.translation() = Eigen::Vector3d(xDistr(scenario->rng()), yDistr(scenario->rng()), gripperPose.translation().z());\n\t\t\t\t\tgoalPose.translation() -= PALM_DISTANCE/10.0*goalPose.linear().col(2); // Go up very slightly during drag\n\t\t\t\t\tsln = manipulator->IK(goalPose, robotTworld, robotState);\n\n\t\t\t\t\tif (scenario->shouldVisualize(\"slide_sampling\"))\n\t\t\t\t\t{\n\t\t\t\t\t\ttf::Transform temp; tf::poseEigenToTF(goalPose, temp);\n\t\t\t\t\t\tscenario->broadcaster->sendTransform(tf::StampedTransform(temp, ros::Time::now(), scenario->worldFrame, \"putative_goal\"));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!sln.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\t// Allocate the action sequence needed for a slide\n\t\t\t\t\t\tstd::shared_ptr<CompositeAction> compositeAction = std::make_shared<CompositeAction>();\n\t\t\t\t\t\tauto pregraspAction = std::make_shared<GripperCommandAction>();  compositeAction->actions.push_back(pregraspAction);\n\t\t\t\t\t\tauto transitAction = std::make_shared<JointTrajectoryAction>();  compositeAction->actions.push_back(transitAction);\n\t\t\t\t\t\tauto approachAction = std::make_shared<JointTrajectoryAction>(); compositeAction->actions.push_back(approachAction);\n\t\t\t\t\t\tauto graspAction = std::make_shared<GripperCommandAction>();     compositeAction->actions.push_back(graspAction);\n\t\t\t\t\t\tauto slideAction = std::make_shared<JointTrajectoryAction>();    compositeAction->actions.push_back(slideAction);\n\t\t\t\t\t\tauto releaseAction = std::make_shared<GripperCommandAction>();   compositeAction->actions.push_back(releaseAction);\n\t\t\t\t\t\tauto retractAction = std::make_shared<JointTrajectoryAction>();  compositeAction->actions.push_back(retractAction);\n\t\t\t\t\t\tauto homeAction = std::make_shared<JointTrajectoryAction>();     compositeAction->actions.push_back(homeAction);\n\t\t\t\t\t\tcompositeAction->primaryAction = 4;\n\n\t\t\t\t\t\t// Lay out the Cartesian Path\n\t\t\t\t\t\tmoveit::Pose gripperApproachPose = gripperPose;\n\t\t\t\t\t\tgripperApproachPose.translation() -= APPROACH_DISTANCE*gripperApproachPose.linear().col(2);\n\n\t\t\t\t\t\tmoveit::Pose gripperRetractPose = goalPose;\n\t\t\t\t\t\tgripperRetractPose.translation() -= APPROACH_DISTANCE*gripperRetractPose.linear().col(2);\n\n\t\t\t\t\t\tPoseSequence approachTrajectory, slideTrajectory, retractTrajectory, fullTrajectory;\n\n\t\t\t\t\t\tmanipulator->interpolate(gripperApproachPose, gripperPose, approachTrajectory, INTERPOLATE_STEPS/2);\n\t\t\t\t\t\tmanipulator->interpolate(gripperPose, goalPose, slideTrajectory, INTERPOLATE_STEPS);\n\t\t\t\t\t\tmanipulator->interpolate(goalPose, gripperRetractPose, retractTrajectory, INTERPOLATE_STEPS/2);\n\n\t\t\t\t\t\tfullTrajectory.reserve(approachTrajectory.size()+slideTrajectory.size()+retractTrajectory.size());\n\t\t\t\t\t\tfullTrajectory.insert(fullTrajectory.end(), approachTrajectory.begin(), approachTrajectory.end());\n\t\t\t\t\t\tfullTrajectory.insert(fullTrajectory.end(), slideTrajectory.begin(), slideTrajectory.end());\n\t\t\t\t\t\tfullTrajectory.insert(fullTrajectory.end(), retractTrajectory.begin(), retractTrajectory.end());\n\n\n\t\t\t\t\t\tif (manipulator->cartesianPath(fullTrajectory, robotTworld, robotState, cmd))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::shared_ptr<Motion> motion = std::make_shared<Motion>();\n\t\t\t\t\t\t\tmotion->state = std::make_shared<State>(objectState);\n\t\t\t\t\t\t\tmotion->action = compositeAction;\n\n\t\t\t\t\t\t\t// Pregrasp\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_a_command.position = 0.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_a_command.speed = 1.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_a_command.force = 1.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_b_command.position = 0.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_b_command.speed = 1.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_b_command.force = 1.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_c_command.position = 0.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_c_command.speed = 1.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.finger_c_command.force = 1.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.scissor_command.position = 0.1;\n\t\t\t\t\t\t\tpregraspAction->grasp.scissor_command.speed = 1.0;\n\t\t\t\t\t\t\tpregraspAction->grasp.scissor_command.force = 1.0;\n\t\t\t\t\t\t\tpregraspAction->jointGroupName = manipulator->gripper->getName();\n\n\t\t\t\t\t\t\t// Move to start\n\t\t\t\t\t\t\trobot_state::RobotState approachState(robotState);\n\t\t\t\t\t\t\tapproachState.setJointGroupPositions(manipulator->arm, cmd.points.front().positions);\n\t\t\t\t\t\t\tapproachState.updateCollisionBodyTransforms();\n\t\t\t\t\t\t\tif (!manipulator->interpolate(robotState, approachState, transitAction->cmd, TRANSIT_INTERPOLATE_STEPS, planningScene))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Approach\n\t\t\t\t\t\t\tapproachAction->palm_trajectory = approachTrajectory;\n\t\t\t\t\t\t\tapproachAction->cmd.joint_names = cmd.joint_names;\n\t\t\t\t\t\t\tapproachAction->cmd.points.insert(approachAction->cmd.points.end(), cmd.points.begin(), cmd.points.begin()+approachTrajectory.size()+1);\n\n\t\t\t\t\t\t\t// Grasp\n\t\t\t\t\t\t\tgraspAction->grasp.finger_a_command.position = 0.4;\n\t\t\t\t\t\t\tgraspAction->grasp.finger_a_command.speed = 1.0;\n\t\t\t\t\t\t\tgraspAction->grasp.finger_a_command.force = 1.0;\n\t\t\t\t\t\t\tgraspAction->grasp.finger_b_command.position = 0.4;\n\t\t\t\t\t\t\tgraspAction->grasp.finger_b_command.speed = 1.0;\n\t\t\t\t\t\t\tgraspAction->grasp.finger_b_command.force = 1.0;\n\t\t\t\t\t\t\tgraspAction->grasp.finger_c_command.position = 0.4;\n\t\t\t\t\t\t\tgraspAction->grasp.finger_c_command.speed = 1.0;\n\t\t\t\t\t\t\tgraspAction->grasp.finger_c_command.force = 1.0;\n\t\t\t\t\t\t\tgraspAction->grasp.scissor_command.position = 0.2;\n\t\t\t\t\t\t\tgraspAction->grasp.scissor_command.speed = 1.0;\n\t\t\t\t\t\t\tgraspAction->grasp.scissor_command.force = 1.0;\n\t\t\t\t\t\t\tgraspAction->jointGroupName = manipulator->gripper->getName();\n\n\n\t\t\t\t\t\t\t// Slide\n\t\t\t\t\t\t\tslideAction->palm_trajectory = slideTrajectory;\n\t\t\t\t\t\t\tslideAction->cmd.joint_names = cmd.joint_names;\n\t\t\t\t\t\t\tslideAction->cmd.points.insert(slideAction->cmd.points.end(), cmd.points.begin()+approachTrajectory.size(), cmd.points.begin()+approachTrajectory.size()+slideTrajectory.size()+1);\n\t\t\t\t\t\t\tmotion->state->poses[sampleInfo.id] = gripperPose.inverse(Eigen::Isometry) * goalPose;\n\n\n\t\t\t\t\t\t\t// Release\n\t\t\t\t\t\t\treleaseAction->grasp.finger_a_command.position = 0.0;\n\t\t\t\t\t\t\treleaseAction->grasp.finger_a_command.speed = 1.0;\n\t\t\t\t\t\t\treleaseAction->grasp.finger_a_command.force = 1.0;\n\t\t\t\t\t\t\treleaseAction->grasp.finger_b_command.position = 0.0;\n\t\t\t\t\t\t\treleaseAction->grasp.finger_b_command.speed = 1.0;\n\t\t\t\t\t\t\treleaseAction->grasp.finger_b_command.force = 1.0;\n\t\t\t\t\t\t\treleaseAction->grasp.finger_c_command.position = 0.0;\n\t\t\t\t\t\t\treleaseAction->grasp.finger_c_command.speed = 1.0;\n\t\t\t\t\t\t\treleaseAction->grasp.finger_c_command.force = 1.0;\n\t\t\t\t\t\t\treleaseAction->grasp.scissor_command.position = 0.2;\n\t\t\t\t\t\t\treleaseAction->grasp.scissor_command.speed = 1.0;\n\t\t\t\t\t\t\treleaseAction->grasp.scissor_command.force = 1.0;\n\t\t\t\t\t\t\treleaseAction->jointGroupName = manipulator->gripper->getName();\n\n\t\t\t\t\t\t\t// Retract\n\t\t\t\t\t\t\tretractAction->palm_trajectory = retractTrajectory;\n\t\t\t\t\t\t\tretractAction->cmd.joint_names = cmd.joint_names;\n\t\t\t\t\t\t\tretractAction->cmd.points.insert(retractAction->cmd.points.end(), cmd.points.begin()+approachTrajectory.size()+slideTrajectory.size(), cmd.points.end());\n\n\t\t\t\t\t\t\t// Move to home\n\t\t\t\t\t\t\trobot_state::RobotState retractState(robotState);\n\t\t\t\t\t\t\tretractState.setJointGroupPositions(manipulator->arm, cmd.points.back().positions);\n\t\t\t\t\t\t\tretractState.updateCollisionBodyTransforms();\n\t\t\t\t\t\t\tif (!manipulator->interpolate(retractState, robotState, homeAction->cmd, TRANSIT_INTERPOLATE_STEPS, planningScene))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmotion->targets.push_back(sampleInfo.id);\n\n\t\t\t\t\t\t\tMPS_ASSERT(motion->state->poses.size() == env->objects.size());\n\t\t\t\t\t\t\treturn motion;\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\tROS_WARN_STREAM(\"Other sliding failure.\");\n\treturn std::shared_ptr<Motion>();\n}\n\n\nstd::shared_ptr<Motion> MotionPlanner::pick(const robot_state::RobotState& robotState, const ObjectIndex targetID,\n                                            OccupancyData::ObstructionList& collisionObjects) const\n{\n\tMPS_ASSERT(targetID.id == env->targetObjectID->id);\n\t// Check whether the hand collides with the scene\n\tfor (const auto& manipulator : scenario->manipulators)\n\t{\n\t\tif (gripperEnvironmentCollision(manipulator, robotState))\n\t\t{\n\t\t\tstd::cerr << manipulator->gripper->getName() << \" starts in collision. No solutions will be possible.\" << std::endl;\n\t\t\treturn std::shared_ptr<Motion>();\n\t\t}\n\t}\n\n\tPose robotTworld = scene->worldTrobot.inverse(Eigen::Isometry);\n\tState objectState = stateFactory(env->objects);\n\n\t// Get an object to slide\n\tconst octomap::OcTree* tree = env->objects.at(targetID)->occupancy.get();\n\tif (getPoints(tree).empty())\n\t{\n\t\tROS_ERROR_STREAM(\"Object occupancy tree is empty.\");\n\t}\n\n\t// Get potential grasps\n\tauto graspPoses = getGraspPoses(tree);\n\n\tconst int INTERPOLATE_STEPS = 25;\n\tconst int TRANSIT_INTERPOLATE_STEPS = 50;\n\tconst double PALM_DISTANCE = 0.025;\n\tconst double APPROACH_DISTANCE = 0.15;\n\tconst double Z_SAFETY_HEIGHT = 0.16;\n\n\t// Shuffle manipulators (without shuffling underlying array)\n\tstd::vector<unsigned int> manip_indices(scenario->manipulators.size());\n\tstd::iota(manip_indices.begin(), manip_indices.end(), 0);\n\tstd::shuffle(manip_indices.begin(), manip_indices.end(), scenario->rng());\n\n\twhile (!graspPoses.empty())\n\t{\n\t\tmoveit::Pose gripperPose = graspPoses.top().second;\n\t\tgraspPoses.pop();\n\t\tgripperPose.linear() = gripperPose.linear() * Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitX()).matrix();\n\t\tgripperPose.translation() -= PALM_DISTANCE*gripperPose.linear().col(2);\n\t\tgripperPose.translation().z() = std::max(gripperPose.translation().z(), Z_SAFETY_HEIGHT);\n\n\t\tif (!arePointsInHandRegion(tree, gripperPose.inverse(Eigen::Isometry)))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (scenario->shouldVisualize(\"pick_sampling\"))\n\t\t{\n\t\t\ttf::Transform t = tf::Transform::getIdentity();\n\t\t\ttf::poseEigenToTF(gripperPose, t);\n\t\t\tscenario->broadcaster->sendTransform(tf::StampedTransform(t, ros::Time::now(), scenario->worldFrame, \"putative_start\"));\n\t\t}\n\n\t\tfor (unsigned int manip_idx : manip_indices)\n\t\t{\n\t\t\tconst auto& manipulator = scenario->manipulators[manip_idx];\n\t\t\tstd::vector<std::vector<double>> sln = manipulator->IK(gripperPose, robotTworld, robotState);\n\t\t\tif (sln.empty())\n\t\t\t{\n\t\t\t\tstd::cerr << \"No solution to pick pose found.\" << std::endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Check whether the hand collides with the scene\n\t\t\t{\n\t\t\t\trobot_state::RobotState collisionState(robotState);\n\t\t\t\tcollisionState.setJointGroupPositions(manipulator->arm, sln.front());\n\t\t\t\tcollisionState.setJointGroupPositions(manipulator->gripper, manipulator->getGripperOpenJoints());\n\t\t\t\tcollisionState.update();\n\n\t\t\t\tif (addPhysicalObstructions(manipulator, collisionState, collisionObjects))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Allocate the action sequence needed for a slide\n\t\t\tstd::shared_ptr<CompositeAction> compositeAction = std::make_shared<CompositeAction>();\n\t\t\tauto pregraspAction = std::make_shared<GripperCommandAction>();  compositeAction->actions.push_back(pregraspAction);\n\t\t\tauto transitAction = std::make_shared<JointTrajectoryAction>();  compositeAction->actions.push_back(transitAction);\n\t\t\tauto approachAction = std::make_shared<JointTrajectoryAction>(); compositeAction->actions.push_back(approachAction);\n\t\t\tauto graspAction = std::make_shared<GripperCommandAction>();     compositeAction->actions.push_back(graspAction);\n\t\t\tauto retractAction = std::make_shared<JointTrajectoryAction>();  compositeAction->actions.push_back(retractAction);\n\t\t\tauto homeAction = std::make_shared<JointTrajectoryAction>();     compositeAction->actions.push_back(homeAction);\n\t\t\tcompositeAction->primaryAction = 3;\n\n\t\t\t// Lay out the Cartesian Path\n\t\t\tmoveit::Pose gripperApproachPose = gripperPose;\n\t\t\tgripperApproachPose.translation() -= APPROACH_DISTANCE*gripperApproachPose.linear().col(2);\n\n\t\t\tmoveit::Pose gripperRetractPose = gripperPose;\n\t\t\tgripperRetractPose.translation() -= APPROACH_DISTANCE*gripperRetractPose.linear().col(2);\n\n\t\t\tPoseSequence approachTrajectory, retractTrajectory, fullTrajectory;\n\n\t\t\tmanipulator->interpolate(gripperApproachPose, gripperPose, approachTrajectory, INTERPOLATE_STEPS/2);\n\t\t\tmanipulator->interpolate(gripperPose, gripperRetractPose, retractTrajectory, INTERPOLATE_STEPS/2);\n\n\t\t\tfullTrajectory.reserve(approachTrajectory.size()+retractTrajectory.size());\n\t\t\tfullTrajectory.insert(fullTrajectory.end(), approachTrajectory.begin(), approachTrajectory.end());\n\t\t\tfullTrajectory.insert(fullTrajectory.end(), retractTrajectory.begin(), retractTrajectory.end());\n\n\t\t\ttrajectory_msgs::JointTrajectory cmd;\n\t\t\tif (manipulator->cartesianPath(fullTrajectory, robotTworld, robotState, cmd))\n\t\t\t{\n\t\t\t\tstd::shared_ptr<Motion> motion = std::make_shared<Motion>();\n\t\t\t\tmotion->state = std::make_shared<State>(objectState);\n\t\t\t\tmotion->action = compositeAction;\n\n\t\t\t\t// Pregrasp\n\t\t\t\tpregraspAction->grasp.finger_a_command.position = 0.0;\n\t\t\t\tpregraspAction->grasp.finger_a_command.speed = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_a_command.force = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_b_command.position = 0.0;\n\t\t\t\tpregraspAction->grasp.finger_b_command.speed = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_b_command.force = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_c_command.position = 0.0;\n\t\t\t\tpregraspAction->grasp.finger_c_command.speed = 1.0;\n\t\t\t\tpregraspAction->grasp.finger_c_command.force = 1.0;\n\t\t\t\tpregraspAction->grasp.scissor_command.position = 0.5;\n\t\t\t\tpregraspAction->grasp.scissor_command.speed = 1.0;\n\t\t\t\tpregraspAction->grasp.scissor_command.force = 1.0;\n\t\t\t\tpregraspAction->jointGroupName = manipulator->gripper->getName();\n\n\t\t\t\t// Move to start\n\t\t\t\trobot_state::RobotState approachState(robotState);\n\t\t\t\tapproachState.setJointGroupPositions(manipulator->arm, cmd.points.front().positions);\n\t\t\t\tapproachState.updateCollisionBodyTransforms();\n\t\t\t\tif (!manipulator->interpolate(robotState, approachState, transitAction->cmd, TRANSIT_INTERPOLATE_STEPS, planningScene))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Approach\n\t\t\t\tapproachAction->palm_trajectory = approachTrajectory;\n\t\t\t\tapproachAction->cmd.joint_names = cmd.joint_names;\n\t\t\t\tapproachAction->cmd.points.insert(approachAction->cmd.points.end(), cmd.points.begin(), cmd.points.begin()+approachTrajectory.size()+1);\n\n\t\t\t\t// Grasp\n\t\t\t\tgraspAction->grasp.finger_a_command.position = 0.4;\n\t\t\t\tgraspAction->grasp.finger_a_command.speed = 1.0;\n\t\t\t\tgraspAction->grasp.finger_a_command.force = 1.0;\n\t\t\t\tgraspAction->grasp.finger_b_command.position = 0.4;\n\t\t\t\tgraspAction->grasp.finger_b_command.speed = 1.0;\n\t\t\t\tgraspAction->grasp.finger_b_command.force = 1.0;\n\t\t\t\tgraspAction->grasp.finger_c_command.position = 0.4;\n\t\t\t\tgraspAction->grasp.finger_c_command.speed = 1.0;\n\t\t\t\tgraspAction->grasp.finger_c_command.force = 1.0;\n\t\t\t\tgraspAction->grasp.scissor_command.position = 0.5;\n\t\t\t\tgraspAction->grasp.scissor_command.speed = 1.0;\n\t\t\t\tgraspAction->grasp.scissor_command.force = 1.0;\n\t\t\t\tgraspAction->jointGroupName = manipulator->gripper->getName();\n\n\t\t\t\t// Retract\n\t\t\t\tretractAction->palm_trajectory = retractTrajectory;\n\t\t\t\tretractAction->cmd.joint_names = cmd.joint_names;\n\t\t\t\tretractAction->cmd.points.insert(retractAction->cmd.points.end(), cmd.points.begin()+approachTrajectory.size(), cmd.points.end());\n\n\t\t\t\t// Move to home\n\t\t\t\trobot_state::RobotState retractState(robotState);\n\t\t\t\tretractState.setJointGroupPositions(manipulator->arm, cmd.points.back().positions);\n\t\t\t\tretractState.updateCollisionBodyTransforms();\n\t\t\t\tif (!manipulator->interpolate(retractState, robotState, homeAction->cmd, TRANSIT_INTERPOLATE_STEPS, planningScene))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tmotion->targets.push_back(targetID);\n\n\t\t\t\tMPS_ASSERT(motion->state->poses.size() == env->objects.size());\n\t\t\t\treturn motion;\n\t\t\t}\n\t\t}\n\t}\n\n\n\treturn std::shared_ptr<Motion>();\n}\n\n\nstd::shared_ptr<Motion>\nMotionPlanner::recoverCrash(const robot_state::RobotState& currentState,\n                            const robot_state::RobotState& recoveryState) const\n{\n\t// Check whether the hand collides with the scene\n\tfor (const auto& manipulator : scenario->manipulators)\n\t{\n\t\tif (gripperEnvironmentCollision(manipulator, currentState))\n\t\t{\n\t\t\tstd::cerr << manipulator->gripper->getName() << \" starts in collision. No solutions will be possible.\" << std::endl;\n\t\t\treturn std::shared_ptr<Motion>();\n\t\t}\n\t}\n\n\tconst double RETREAT_DISTANCE = 0.05;\n\tconst int INTERPOLATE_STEPS = 10;\n\tconst int TRANSIT_INTERPOLATE_STEPS = 50;\n\n\tfor (const auto& manipulator : scenario->manipulators)\n\t{\n\t\t// See if needs recovery\n\t\tEigen::VectorXd qCurrent, qRecovery;\n\t\tcurrentState.copyJointGroupPositions(manipulator->arm, qCurrent);\n\t\trecoveryState.copyJointGroupPositions(manipulator->arm, qRecovery);\n\t\tEigen::VectorXd qErr = qCurrent - qRecovery;\n\t\tbool satisfied = true; for (int i = 0; i < qErr.size(); ++i) { if (fabs(qErr[i]) > 1e-1) { satisfied = false; } }\n\t\tif (satisfied)\n\t\t{\n\t\t\tstd::cerr << manipulator->arm->getName() << \" satisfies recovery.\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tPose worldThand = scene->worldTrobot*currentState.getFrameTransform(manipulator->palmName);\n\t\tPose worldTretreat = worldThand;\n\t\tworldTretreat.translation().z() += RETREAT_DISTANCE;\n\t\tPose robotTworld = scene->worldTrobot.inverse(Eigen::Isometry);\n\n\t\tstd::shared_ptr<CompositeAction> compositeAction = std::make_shared<CompositeAction>();\n\t\tauto releaseAction = std::make_shared<GripperCommandAction>();\n\t\tcompositeAction->actions.push_back(releaseAction);\n\t\tauto retractAction = std::make_shared<JointTrajectoryAction>();\n\t\tcompositeAction->actions.push_back(retractAction);\n\t\tauto homeAction = std::make_shared<JointTrajectoryAction>();\n\t\tcompositeAction->actions.push_back(homeAction);\n\t\tcompositeAction->primaryAction = -1;\n\n\t\t// Release\n\t\treleaseAction->grasp.finger_a_command.position = 0.0;\n\t\treleaseAction->grasp.finger_a_command.speed = 1.0;\n\t\treleaseAction->grasp.finger_a_command.force = 1.0;\n\t\treleaseAction->grasp.finger_b_command.position = 0.0;\n\t\treleaseAction->grasp.finger_b_command.speed = 1.0;\n\t\treleaseAction->grasp.finger_b_command.force = 1.0;\n\t\treleaseAction->grasp.finger_c_command.position = 0.0;\n\t\treleaseAction->grasp.finger_c_command.speed = 1.0;\n\t\treleaseAction->grasp.finger_c_command.force = 1.0;\n\t\treleaseAction->grasp.scissor_command.position = 0.5;\n\t\treleaseAction->grasp.scissor_command.speed = 1.0;\n\t\treleaseAction->grasp.scissor_command.force = 1.0;\n\t\treleaseAction->jointGroupName = manipulator->gripper->getName();\n\n\t\t// Compute retraction\n\t\tPoseSequence retractTrajectory;\n\t\tif (!manipulator->interpolate(worldThand, worldTretreat, retractTrajectory, INTERPOLATE_STEPS))\n\t\t{\n\t\t\tstd::cerr << \"Failed to create Cartesian trajectory.\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\ttrajectory_msgs::JointTrajectory cmd;\n\t\tif (manipulator->cartesianPath(retractTrajectory, robotTworld, currentState, cmd))\n\t\t{\n\t\t\tstd::cerr << \"Failed to follow Cartesian trajectory.\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Retract\n\t\tretractAction->palm_trajectory = retractTrajectory;\n\t\tretractAction->cmd.joint_names = cmd.joint_names;\n\t\tretractAction->cmd.points.insert(retractAction->cmd.points.end(), cmd.points.begin(), cmd.points.end());\n\n\t\t// Move to home\n\t\trobot_state::RobotState retractState(currentState);\n\t\tretractState.setJointGroupPositions(manipulator->arm, cmd.points.back().positions);\n\t\tretractState.updateCollisionBodyTransforms();\n\t\tif (!manipulator->interpolate(retractState, recoveryState, homeAction->cmd, TRANSIT_INTERPOLATE_STEPS, planningScene))\n\t\t{\n\t\t\tstd::cerr << \"Failed to return home.\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tState objectState = stateFactory(env->objects);\n\t\tstd::shared_ptr<Motion> motion = std::make_shared<Motion>();\n\t\tmotion->state = std::make_shared<State>(objectState);\n\t\tmotion->action = compositeAction;\n\n\t\tstd::cerr << \"Got recovery motion.\" << std::endl;\n\t\treturn motion;\n\t}\n\treturn std::shared_ptr<Motion>();\n}\n\nMotionPlanner::MotionPlanner(std::shared_ptr<const Scenario> _scenario, std::shared_ptr<const Scene> _scene, std::shared_ptr<const OccupancyData> _occupancy)\n\t: scenario(std::move(_scenario)), scene(std::move(_scene)), env(std::move(_occupancy))\n{\n\tcomputePlanningScene(true);\n}\n\n}\n", "meta": {"hexsha": "bb61098902a9c3914ebb368786a6b8eb61c7c863", "size": 58683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mps_voxels/src/mps_voxels/planning/MotionPlanner.cpp", "max_stars_repo_name": "UM-ARM-Lab/multihypothesis_segmentation_tracking", "max_stars_repo_head_hexsha": "801d460afbf028100374c880bc684187ec8b909f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-31T21:42:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T12:56:02.000Z", "max_issues_repo_path": "mps_voxels/src/mps_voxels/planning/MotionPlanner.cpp", "max_issues_repo_name": "UM-ARM-Lab/multihypothesis_segmentation_tracking", "max_issues_repo_head_hexsha": "801d460afbf028100374c880bc684187ec8b909f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-11T03:46:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T03:46:08.000Z", "max_forks_repo_path": "mps_voxels/src/mps_voxels/planning/MotionPlanner.cpp", "max_forks_repo_name": "UM-ARM-Lab/multihypothesis_segmentation_tracking", "max_forks_repo_head_hexsha": "801d460afbf028100374c880bc684187ec8b909f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-02T12:32:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T12:32:21.000Z", "avg_line_length": 40.4431426602, "max_line_length": 186, "alphanum_fraction": 0.7139035155, "num_tokens": 15785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19401006860139416}}
{"text": "#ifndef NAV_CONTROLLER_HPP\n#define NAV_CONTROLLER_HPP\n\n\n#include <iostream>\n#include <cstdlib>\n#include <sys/time.h>\n#include <time.h>\n#include <lcm/lcm-cpp.hpp>\n#include \"lcmtypes/drc_lcmtypes.hpp\"\n\n#include <boost/function.hpp>\n#include <map>\n\n#include <boost/thread.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/scoped_ptr.hpp>\n\n#include <Eigen/Core> \n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\t\n\n#include <kdl/tree.hpp>\n#include <kdl_parser/kdl_parser.hpp>\n#include <string>\n#include <urdf/model.h>\n#include <kdl/chainfksolver.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n#include <kdl/chain.hpp>\n#include <kdl/chainjnttojacsolver.hpp>\n#include <kdl/frames.hpp>\n\n#include <math.h>\n#include \"reactive_navigation_2d/eigen_kdl_conversions.hpp\"\n#include \"reactive_navigation_2d/angles.hpp\"\n\n#define DIST_ERROR 0.5\n#define HEADING_ERROR 10*(M_PI/180)\n\nnamespace nav_control\n{\n\n  enum {STOPPED, RUNNING};\n  \n  enum control_type{GLOBAL, RELATIVE};\n\n// Example instantiation\n//-------------------------------------\n// int NrOfJoints  = kdl_chain.getNrOfJoints();\n// nav_control::NavController<NrOfJoints> left_arm_controller(lcm,\"LEFT_ARM_CMDS\",kdl_chain);\n\n  class NavController{\n\n    public:\n      // Ensure 128-bit alignment for Eigen\n      // See also http://eigen.tuxfamily.org/dox/StructHavingEigenMembers.html\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n      //----------------constructor/destructor\n      NavController(boost::shared_ptr<lcm::LCM> &lcm, const std::string &input_cmds_channel,\n                        const std::string &robot_name,const urdf::Model &urdf_robot_model);\n      ~NavController();\n\n      void init();\n      void update(const drc::robot_state_t &robot_state, const double &dt);\n      void computePoseError(const Eigen::Affine3d &xact, const Eigen::Affine3d &xdes, Eigen::Matrix<double,6,1> &err);\n      bool isRunning();\n\n    private:\n      //--------type defs\n      //enum { JOINTS = 6 };\n\n      typedef Eigen::Matrix<double, 6, 1> CartVector;\n      typedef Eigen::Matrix<double,Eigen::Dynamic,1> VectorXq;\n      //--------fields\n      \n    private:\n      std::string _robot_name;\n      urdf::Model _urdf_robot_model;\n      std::vector<std::string> _chain_joint_names;\n\n\n      uint controller_state;\n\n      boost::shared_ptr<lcm::LCM> _lcm;    \n      Eigen::Affine3d x, x_goal_;\n\n      //--------Gains\n      CartVector Kp_x, Kd_x;\n\n      bool uninitialized_;\n\n      int64_t latest_goal_timestamp_;\n      int64_t latest_goal_timeout_;\n      control_type latest_goal_type_;\n\n      //-------------message callback\n    private:  \n    void handleNavGoalMsg(const lcm::ReceiveBuffer* rbuf,\n                              const std::string& chan, \n                              const drc::nav_goal_timed_t* msg);\n\n    void handleRelativeNavGoalMsg(const lcm::ReceiveBuffer* rbuf,\n                              const std::string& chan, \n                              const drc::nav_goal_timed_t* msg);\n    \n    bool debug_;\n\n  }; //class NavController\n\n  \n  \n  //==================constructor \n\nNavController::NavController(boost::shared_ptr<lcm::LCM> &lcm, \n\tconst std::string& input_cmds_channel,\n\tconst std::string &robot_name,\n\tconst urdf::Model &urdf_robot_model) : _lcm(lcm), _robot_name(robot_name), _urdf_robot_model(urdf_robot_model)\n{\n  std::cout << \"\\nSpawning a nav controller that listens to \"<< input_cmds_channel << \" channel.\" << std::endl;\n\n  controller_state = STOPPED;\n  //lcm ok?\n  if(!_lcm->good())\n  {\n    std::cerr << \"\\nLCM Not Good: nav_controller\" << std::endl;\n    return;\n  }\n\n  // Set gains\n\n  uninitialized_ = true; // flag to indicate that the controller is in uninitialized_ state\n\n  // ---------------------- subscribe to goal commands \n  _lcm->subscribe(input_cmds_channel, &nav_control::NavController::handleNavGoalMsg, this); \n\n  std::cout << \"\\nalso Spawning a nav controller that listens to RELATIVE_NAV_GOAL_TIMED channel.\" << std::endl;\n  _lcm->subscribe(\"RELATIVE_NAV_GOAL_TIMED\", &nav_control::NavController::handleRelativeNavGoalMsg, this); \n}\n\n//================== destructor \nNavController::~NavController() {\n\n  drc::twist_t body_twist_cmd;\n  body_twist_cmd.linear_velocity.x =0;\n  body_twist_cmd.linear_velocity.y =0;\n  body_twist_cmd.linear_velocity.z =0;\n  body_twist_cmd.angular_velocity.x =0;\n  body_twist_cmd.angular_velocity.y =0;\n  body_twist_cmd.angular_velocity.z =0;\n  _lcm->publish(\"NAV_CMDS\", &body_twist_cmd);\n  \n  \n}\n\n\n\n//Controller needs initialization after the first robot state message is received.\n\nvoid NavController::init() \n{\n  debug_ = false;\n}\n\n//update() function is called from the robot state msg handler defined in controller_manager.\n\nvoid NavController::update(const drc::robot_state_t &robot_state, const double &dt)\n{\n\n\n  if(uninitialized_)\n  {\n    this->init();  // only run for the first instance. \n    uninitialized_ = false;\n  }\n  \n  double desired_forward_speed=0;\n  double desired_yaw_rate=0;\n\n  int64_t cmd_age = robot_state.utime - latest_goal_timestamp_;\n  if (cmd_age > latest_goal_timeout_){\n    //std::cout << \"TIMEOUT\\n\";\n    desired_forward_speed=0;\n    desired_yaw_rate=0;\n  }else{\n\n    CartVector x_err;\n    if (latest_goal_type_ == GLOBAL){// original method\n      drc::position_3d_t  body_position = robot_state.origin_position;\n      drc::covariance_t  body_pos_cov = robot_state.origin_cov; // convert to uncertainty in goal\n      // ======== Get current robot state\n      transformLCMToEigen(body_position,x);\n\n      computePoseError(x, x_goal_, x_err); //returns  x_goal_ - x\n    }else if(latest_goal_type_ == RELATIVE){\n      // ======== Set current robot state to be null - for relative control:\n      x(0,3) = 0;\n      x(1,3)=0;\n      x(2,3)=0;\n      x(0,0)=1;\n      x(0,1)=0;\n      x(0,2)=0;\n      x(1,0)=0;\n      x(1,1)=1;\n      x(1,2)=0;\n      x(2,0)=0;\n      x(2,1)=0;\n      x(2,2)=1;      \n      \n      x_err[0] = x_goal_(0,3);\n      x_err[1] = x_goal_(1,3);\n      x_err[2] =0;\n      x_err[3] =0;\n      x_err[4] =0;\n      x_err[5] =0; // heading\n      \n    }else{\n       std::cout << \"control type not recognised: \" << latest_goal_type_ << \"\\n\";\n       return;\n    }\n    \n    double dx,dy,dtheta;\n    dx = x_err[0];\n    dy = x_err[1];\n    dtheta = x_err[5]; // desired final heading error\n  \n    double desired_heading_2_goal = atan2(dy,dx);\n\n    KDL::Frame kdl_x,kdl_x_goal;\n    transformEigenToKDL(x,kdl_x);\n    KDL::Rotation kdl_M = kdl_x.M;\n    double roll,pitch,yaw;\n    kdl_M.GetRPY(roll,pitch,yaw);\n    double orientation_goal;\n    transformEigenToKDL(x_goal_,kdl_x_goal);\n    kdl_x_goal.M.GetRPY(roll,pitch,orientation_goal);\n \n\n    // INSERT CONTROL ALGORITHM HERE\n    double dtheta_goal = shortest_angular_distance(yaw,orientation_goal);\n    double dheading = shortest_angular_distance(yaw,desired_heading_2_goal);\n    double heading_gain = 1;\n    double vel_gain = 0.0075;\n    double d_goal  = sqrt(dx*dx + dy*dy); \n\n    //double lamda = std::min(0.25*(1/pow(d_goal,4)),1.0);\n    double lamda = 0;\n    if(d_goal<DIST_ERROR)\n      lamda = 1;\n    double w_dheading = (1-lamda)*dheading + lamda*dtheta_goal; \n    double wturn = std::min(1-pow((fabs(dheading)/M_PI),0.5),1.0);\n    if (fabs(w_dheading) < (M_PI/8))\n      wturn = 1;\n    \n    if (heading_gain*w_dheading >= 0){ // anti clock rotation:\n      desired_yaw_rate =  std::min(heading_gain*w_dheading,1.0);\n    }else{ // clockwise rotation:\n      desired_yaw_rate =  std::max( heading_gain*w_dheading, -1.0);\n    }\n    desired_forward_speed = wturn*std::min(vel_gain*(pow(d_goal,2)/dt),1.0);\n    if(d_goal<DIST_ERROR){\n      desired_forward_speed = 0;\n    }\n  \n    if(debug_){\n      std::cout << \"\\n desired_forward_speed: \" << desired_forward_speed<< std::endl;\n      std::cout << \" desired_yaw_rate: \" << desired_yaw_rate<< std::endl;\n      std::cout << \" d_goal: \" << d_goal << std::endl;\n\n      std::cout << \" X: \" <<  x.translation()[0] << \" \" <<  x.translation()[1] << std::endl;\n      std::cout << \" goal: \" <<  x_goal_.translation()[0] << \" \" <<  x_goal_.translation()[1] << std::endl;\n      std::cout << \" err: \" << x_err.head<2>() << std::endl;\n      std::cout << \" dtheta: \" << to_degrees(x_err[5]) << std::endl;\n      std::cout << \" dtheta_goal: \" << to_degrees(dtheta_goal) << std::endl;\n      std::cout << \" dheading: \" << to_degrees(dheading)<< std::endl;\n      std::cout << \" lamda: \" << lamda << std::endl;\n      std::cout << \" w_dheading: \" << to_degrees(w_dheading) << std::endl;\n  \n      std::cout << \"ROBS \" << robot_state.utime << \" | GOAL \" << latest_goal_timestamp_ \n\t<< \" | TO \" << latest_goal_timeout_ << \" | AGE \" << cmd_age << \"\\n\";\n    }\n  }\n  \n  drc::twist_t body_twist_cmd;\n  // body_twist_cmd.utime = getTime_now();\n   //body_twist_cmd.robot_name = _robot_name;\n  body_twist_cmd.linear_velocity.x =desired_forward_speed;\n  body_twist_cmd.linear_velocity.y =0;\n  body_twist_cmd.linear_velocity.z =0;\n  body_twist_cmd.angular_velocity.x =0;\n  body_twist_cmd.angular_velocity.y =0;\n  body_twist_cmd.angular_velocity.z =desired_yaw_rate;\n  _lcm->publish(\"NAV_CMDS\", &body_twist_cmd); \n}//end update\n\n\n\n \nvoid NavController::computePoseError(const Eigen::Affine3d &xact, const Eigen::Affine3d &xdes, Eigen::Matrix<double,6,1> &err)\n{\n  // des - act\n  // Better error metric from KDL.\t    \n  KDL::Frame kdl_xdes,kdl_xact;\n  transformEigenToKDL(xdes,kdl_xdes);\n  transformEigenToKDL(xact,kdl_xact);\n\n  KDL::Twist delta_pos;\n  // delta pos required to transform xact to xdes\n  delta_pos =KDL::diff(kdl_xact,kdl_xdes,1);\n  transformKDLtwistToEigen(delta_pos,err);\n\n  // see KDL/src/frames.hpp  \n  //  \n  //  * KDL::diff() determines the rotation axis necessary to rotate the frame b1 to the same orientation as frame b2 and the vector\n  //  * necessary to translate the origin of b1 to the origin of b2, and stores the result in a Twist datastructure.   \n  // IMETHOD Twist diff(const Frame& F_a_b1,const Frame& F_a_b2,double dt=1);\n  //   IMETHOD Vector diff(const Rotation& R_a_b1,const Rotation& R_a_b2,double dt) {\n  // \tRotation R_b1_b2(R_a_b1.Inverse()*R_a_b2);\n  // \treturn R_a_b1 * R_b1_b2.GetRot() / dt;\n  // }\n\n\n} // end computePoseError\n\n\n\n  //=============message callbacks\n\nvoid NavController::handleNavGoalMsg(const lcm::ReceiveBuffer* rbuf,\n\t\t\t\t\t\t const std::string& chan, \n\t\t\t\t\t\t const drc::nav_goal_timed_t* msg)\t\t\t\t\t\t \n{ \n\n  Eigen::Affine3d goal;\n  transformLCMToEigen(msg->goal_pos,goal);\n \n  CartVector x_err;\n  computePoseError(x, goal, x_err);\n  \n\n  double dist_err_2d  = sqrt(x_err[0]*x_err[0]  + x_err[1]*x_err[1]);\n  if((controller_state==RUNNING)&(dist_err_2d<DIST_ERROR)&(fabs(x_err[5])<HEADING_ERROR)){\n    //     controller_state=STOPPED;\n    //     uninitialized_ = true;\n  }else if((controller_state==STOPPED)&(dist_err_2d>DIST_ERROR))\n    controller_state=RUNNING; // as we just received a goal.\n   \n  if(controller_state==RUNNING){ \n    latest_goal_timestamp_ = msg->utime;\n    latest_goal_timeout_ = msg->timeout;\n    latest_goal_type_ = GLOBAL;\n    x_goal_ = goal;\n    \n    std::cout <<\"RECD NAV_GOAL_TIMED: \" << latest_goal_timestamp_ \n      << \" | Expiry: \" << latest_goal_timeout_ << \"\\n\";  \n\n\t\n  }//if(controller_state==RUNNING)\n} // end handleNavGoalMsg\n \n\n \nvoid NavController::handleRelativeNavGoalMsg(const lcm::ReceiveBuffer* rbuf,\n                                                 const std::string& chan, \n                                                 const drc::nav_goal_timed_t* msg)                                               \n{ \n  std::cout << \"got relative goal message\\n\";\n  Eigen::Affine3d goal;\n  transformLCMToEigen(msg->goal_pos,goal);\n \n  CartVector x_err;\n//  computePoseError(x, goal, x_err);\n  \n  std::cout << goal(0,3) << \" and \" << goal(1,3) << \" is the goal\\n\";\n  x_err[0] = goal(0,3);\n  x_err[1] = goal(1,3);\n  x_err[2] =0;\n  x_err[3] =0;\n  x_err[4] =0;\n  x_err[5] =0; // heading\n\n  double dist_err_2d  = sqrt(x_err[0]*x_err[0]  + x_err[1]*x_err[1]);\n  if((controller_state==RUNNING)&(dist_err_2d<DIST_ERROR)&(fabs(x_err[5])<HEADING_ERROR)){\n    //     controller_state=STOPPED;\n    //     uninitialized_ = true;\n  }else if((controller_state==STOPPED)&(dist_err_2d>DIST_ERROR))\n    controller_state=RUNNING; // as we just received a goal.\n   \n  if(controller_state==RUNNING){ \n    latest_goal_timestamp_ = msg->utime;\n    latest_goal_timeout_ = msg->timeout;\n    latest_goal_type_ = RELATIVE;\n    x_goal_ = goal;\n    \n    std::cout <<\"RECD RELATIVE_NAV_GOAL_TIMED: \" << latest_goal_timestamp_ \n      << \" | Expiry: \" << latest_goal_timeout_ << \"\\n\";  \n\n        \n  }//if(controller_state==RUNNING)\n  \n} // end handleNavGoalMsg\n \n \n \n \n \nbool NavController::isRunning()\n{\n  return (controller_state==RUNNING);\n}\n\n\n\n  \n} //end namespace \n\n\n#endif //NAV_CONTROLLER_HPP\n\n", "meta": {"hexsha": "c8281643b00612b9b40741f77e7ba8fec03d4ae2", "size": 12710, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "software/control/reactive_navigation_2d/include/reactive_navigation_2d/nav_controller.hpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/control/reactive_navigation_2d/include/reactive_navigation_2d/nav_controller.hpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/control/reactive_navigation_2d/include/reactive_navigation_2d/nav_controller.hpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 30.1184834123, "max_line_length": 132, "alphanum_fraction": 0.6474429583, "num_tokens": 3632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1939596047170351}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE Test_Adaptive_CompoundScalarHelpers\n#include <boost/test/unit_test.hpp>\n#include <popart/adaptive.hpp>\n#include <popart/compoundscalarhelper.hpp>\n#include <popart/sessionoptions.hpp>\n\nusing namespace popart;\n\nnamespace {\nvoid validate(Adaptive adaptive, float expected_lr, float expected_gs) {\n  AdaptiveLearningRateHelper lr;\n  AdaptiveGradientScalingHelper gs;\n\n  BOOST_CHECK_EQUAL(lr.val(\"\", adaptive), expected_lr);\n  BOOST_CHECK_EQUAL(gs.val(\"\", adaptive), expected_gs);\n}\n} // namespace\n\nBOOST_AUTO_TEST_CASE(TestAdaptive_Base) {\n  Adaptive adaptive{{\n                        {\"defaultLearningRate\", {0.1f, true}},\n                    },\n                    AdaptiveMode::AdaGrad,\n                    WeightDecayMode::Decay,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT};\n  SessionOptions opts;\n  adaptive.setFactorsFromOptions(opts);\n  validate(adaptive, 0.1f, 1.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestAdaptive_lossScaling) {\n  Adaptive adaptive{\n      {{\"defaultLearningRate\", {0.1f, true}}, {\"lossScaling\", {4.0f, true}}},\n      AdaptiveMode::AdaGrad,\n      WeightDecayMode::Decay,\n      DataType::FLOAT,\n      DataType::FLOAT,\n      DataType::FLOAT,\n      DataType::FLOAT};\n  SessionOptions opts;\n  adaptive.setFactorsFromOptions(opts);\n  validate(adaptive, 0.1f, 1.0f / 4.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestAdaptive_ReplicaSum) {\n  Adaptive adaptive{{\n                        {\"defaultLearningRate\", {0.1f, true}},\n                    },\n                    AdaptiveMode::AdaGrad,\n                    WeightDecayMode::Decay,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT};\n  SessionOptions opts;\n  opts.enableReplicatedGraphs = true;\n  opts.replicatedGraphCount   = 2;\n  adaptive.setFactorsFromOptions(opts);\n  validate(adaptive, 0.1f, 1.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestAdaptive_ReplicaMeanPost) {\n  Adaptive adaptive{{\n                        {\"defaultLearningRate\", {0.1f, true}},\n                    },\n                    AdaptiveMode::AdaGrad,\n                    WeightDecayMode::Decay,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT};\n  SessionOptions opts;\n  opts.enableReplicatedGraphs                  = true;\n  opts.replicatedGraphCount                    = 2;\n  opts.accumulationAndReplicationReductionType = ReductionType::Mean;\n  opts.meanAccumulationAndReplicationReductionStrategy =\n      MeanReductionStrategy::Post;\n  adaptive.setFactorsFromOptions(opts);\n  validate(adaptive, 0.1f, 1.0f / 2.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestAdaptive_ReplicaMeanRunning) {\n  Adaptive adaptive{{\n                        {\"defaultLearningRate\", {0.1f, true}},\n                    },\n                    AdaptiveMode::AdaGrad,\n                    WeightDecayMode::Decay,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT};\n  SessionOptions opts;\n  opts.enableReplicatedGraphs                  = true;\n  opts.replicatedGraphCount                    = 2;\n  opts.accumulationAndReplicationReductionType = ReductionType::Mean;\n  opts.meanAccumulationAndReplicationReductionStrategy =\n      MeanReductionStrategy::Running;\n  adaptive.setFactorsFromOptions(opts);\n  validate(adaptive, 0.1f, 1.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestAdaptive_AccumSum) {\n  Adaptive adaptive{{\n                        {\"defaultLearningRate\", {0.1f, true}},\n                    },\n                    AdaptiveMode::AdaGrad,\n                    WeightDecayMode::Decay,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT};\n  SessionOptions opts;\n  opts.enableGradientAccumulation = true;\n  opts.accumulationFactor         = 4;\n  adaptive.setFactorsFromOptions(opts);\n  validate(adaptive, 0.1f, 1.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestAdaptive_AccumMeanPost) {\n  Adaptive adaptive{{\n                        {\"defaultLearningRate\", {0.1f, true}},\n                    },\n                    AdaptiveMode::AdaGrad,\n                    WeightDecayMode::Decay,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT};\n  SessionOptions opts;\n  opts.enableGradientAccumulation              = true;\n  opts.accumulationFactor                      = 4;\n  opts.accumulationAndReplicationReductionType = ReductionType::Mean;\n  opts.meanAccumulationAndReplicationReductionStrategy =\n      MeanReductionStrategy::Post;\n  adaptive.setFactorsFromOptions(opts);\n  validate(adaptive, 0.1f, 1.0f / 4.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestAdaptive_AccumMeanRunning) {\n  Adaptive adaptive{{\n                        {\"defaultLearningRate\", {0.1f, true}},\n                    },\n                    AdaptiveMode::AdaGrad,\n                    WeightDecayMode::Decay,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT,\n                    DataType::FLOAT};\n  SessionOptions opts;\n  opts.enableGradientAccumulation              = true;\n  opts.accumulationFactor                      = 4;\n  opts.accumulationAndReplicationReductionType = ReductionType::Mean;\n  opts.meanAccumulationAndReplicationReductionStrategy =\n      MeanReductionStrategy::Running;\n  adaptive.setFactorsFromOptions(opts);\n  validate(adaptive, 0.1f, 1.0f);\n}\n", "meta": {"hexsha": "c1fd09e6af83411bb35c12e56c0e8a8567410b5f", "size": 5692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unittests/compoundscalarhelper/unittest_adaptive.cpp", "max_stars_repo_name": "graphcore/popart", "max_stars_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:51.000Z", "max_issues_repo_path": "tests/unittests/compoundscalarhelper/unittest_adaptive.cpp", "max_issues_repo_name": "graphcore/popart", "max_issues_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T01:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T11:13:14.000Z", "max_forks_repo_path": "tests/unittests/compoundscalarhelper/unittest_adaptive.cpp", "max_forks_repo_name": "graphcore/popart", "max_forks_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T06:55:00.000Z", "avg_line_length": 35.1358024691, "max_line_length": 77, "alphanum_fraction": 0.5934645116, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1939596047170351}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Defines class AdamsBashforthN\n\n#pragma once\n\n#include <algorithm>\n#include <boost/iterator/transform_iterator.hpp>\n#include <cstddef>\n#include <cstdint>\n#include <iterator>\n#include <map>\n#include <ostream>\n#include <pup.h>\n#include <type_traits>\n#include <vector>\n\n#include \"ErrorHandling/Assert.hpp\"\n#include \"ErrorHandling/Error.hpp\"\n#include \"NumericalAlgorithms/Interpolation/LagrangePolynomial.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"Time/Time.hpp\"\n#include \"Time/TimeId.hpp\"\n#include \"Time/TimeSteppers/TimeStepper.hpp\"  // IWYU pragma: keep\n#include \"Utilities/CachedFunction.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// \\cond\nnamespace TimeSteppers {\ntemplate <typename LocalVars, typename RemoteVars, typename CouplingResult>\nclass BoundaryHistory;  // IWYU pragma: keep\ntemplate <typename Vars, typename DerivVars>\nclass History;\n}  // namespace TimeSteppers\n/// \\endcond\n\n// IWYU pragma: no_include <sys/types.h>\n\nnamespace TimeSteppers {\n\n/// \\ingroup TimeSteppersGroup\n///\n/// An Nth Adams-Bashforth time stepper.\nclass AdamsBashforthN : public TimeStepper::Inherit {\n public:\n  static constexpr const size_t maximum_order = 8;\n\n  struct TargetOrder {\n    using type = size_t;\n    static constexpr OptionString help = {\n        \"Target order of Adams-Bashforth method.\"};\n    static type lower_bound() { return 1; }\n    static type upper_bound() { return maximum_order; }\n  };\n  struct SelfStart {\n    using type = bool;\n    static constexpr OptionString help = {\n        \"Start at first order and increase.\"};\n    static type default_value() { return false; }\n  };\n  using options = tmpl::list<TargetOrder, SelfStart>;\n  static constexpr OptionString help = {\n      \"An Adams-Bashforth Nth order time-stepper. The target order is the\\n\"\n      \"order of the method. If a self-starting approach is chosen then the\\n\"\n      \"method starts at first order and increases the step-size until the\\n\"\n      \"desired order is reached.\"};\n\n  AdamsBashforthN() = default;\n  explicit AdamsBashforthN(size_t target_order, bool self_start = false,\n                           const OptionContext& context = {});\n  AdamsBashforthN(const AdamsBashforthN&) noexcept = default;\n  AdamsBashforthN& operator=(const AdamsBashforthN&) noexcept = default;\n  AdamsBashforthN(AdamsBashforthN&&) noexcept = default;\n  AdamsBashforthN& operator=(AdamsBashforthN&&) noexcept = default;\n  ~AdamsBashforthN() noexcept override = default;\n\n  template <typename Vars, typename DerivVars>\n  void update_u(gsl::not_null<Vars*> u,\n                gsl::not_null<History<Vars, DerivVars>*> history,\n                const TimeDelta& time_step) const noexcept;\n\n  // This is defined as a separate type alias to keep the doxygen page\n  // width somewhat under control.\n  template <typename LocalVars, typename RemoteVars, typename Coupling>\n  using BoundaryHistoryType =\n      BoundaryHistory<LocalVars, RemoteVars,\n                      std::result_of_t<const Coupling&(LocalVars, RemoteVars)>>;\n\n  /*!\n   * An explanation of the computation being performed by this\n   * function:\n   * \\f$\\newcommand\\tL{t^L}\\newcommand\\tR{t^R}\\newcommand\\tU{\\tilde{t}\\!}\n   * \\newcommand\\mat{\\mathbf}\\f$\n   *\n   * Suppose the local and remote sides of the interface are evaluated\n   * at times \\f$\\ldots, \\tL_{-1}, \\tL_0, \\tL_1, \\ldots\\f$ and\n   * \\f$\\ldots, \\tR_{-1}, \\tR_0, \\tR_1, \\ldots\\f$, respectively, with\n   * the starting location of the numbering arbitrary in each case.\n   * Let the step we wish to calculate the effect of be the step from\n   * \\f$\\tL_{m_S}\\f$ to \\f$\\tL_{m_S+1}\\f$.  We call the sequence\n   * produced from the union of the local and remote time sequences\n   * \\f$\\ldots, \\tU_{-1}, \\tU_0, \\tU_1, \\ldots\\f$.  For example, one\n   * possible sequence of times is:\n   * \\f{equation}\n   *   \\begin{aligned}\n   *     \\text{Local side:} \\\\ \\text{Union times:} \\\\ \\text{Remote side:}\n   *   \\end{aligned}\n   *   \\cdots\n   *   \\begin{gathered}\n   *     \\, \\\\ \\tU_1 \\\\ \\tR_5\n   *   \\end{gathered}\n   *   \\leftarrow \\Delta \\tU_1 \\rightarrow\n   *   \\begin{gathered}\n   *     \\tL_4 \\\\ \\tU_2 \\\\ \\,\n   *   \\end{gathered}\n   *   \\leftarrow \\Delta \\tU_2 \\rightarrow\n   *   \\begin{gathered}\n   *     \\, \\\\ \\tU_3 \\\\ \\tR_6\n   *   \\end{gathered}\n   *   \\leftarrow \\Delta \\tU_3 \\rightarrow\n   *   \\begin{gathered}\n   *    \\, \\\\ \\tU_4 \\\\ \\tR_7\n   *   \\end{gathered}\n   *   \\leftarrow \\Delta \\tU_4 \\rightarrow\n   *   \\begin{gathered}\n   *     \\tL_5 \\\\ \\tU_5 \\\\ \\,\n   *   \\end{gathered}\n   *   \\cdots\n   * \\f}\n   * We call the indices of the step's start and end times in the\n   * union time sequence \\f$n_S\\f$ and \\f$n_E\\f$, respectively.  We\n   * define \\f$n^L_m\\f$ to be the union-time index corresponding to\n   * \\f$\\tL_m\\f$ and \\f$m^L_n\\f$ to be the index of the last local\n   * time not later than \\f$\\tU_n\\f$ and similarly for the remote\n   * side.  So for the above example, \\f$n^L_4 = 2\\f$ and \\f$m^R_2 =\n   * 5\\f$, and if we wish to compute the step from \\f$\\tL_4\\f$ to\n   * \\f$\\tL_5\\f$ we would have \\f$m_S = 4\\f$, \\f$n_S = 2\\f$, and\n   * \\f$n_E = 5\\f$.\n   *\n   * If we wish to evaluate the change over this step to \\f$k\\f$th\n   * order, we can write the change in the value as a linear\n   * combination of the values of the coupling between the elements at\n   * unequal times:\n   * \\f{equation}\n   *   \\mat{F}_{m_S} =\n   *   \\mspace{-10mu}\n   *   \\sum_{q^L = m_S-(k-1)}^{m_S}\n   *   \\,\n   *   \\sum_{q^R = m^R_{n_S}-(k-1)}^{m^R_{n_E-1}}\n   *   \\mspace{-10mu}\n   *   \\mat{D}_{q^Lq^R}\n   *   I_{q^Lq^R},\n   * \\f}\n   * where \\f$\\mat{D}_{q^Lq^R}\\f$ is the coupling function evaluated\n   * between data from \\f$\\tL_{q^L}\\f$ and \\f$\\tR_{q^R}\\f$.  The\n   * coefficients can be written as the sum of three terms,\n   * \\f{equation}\n   *   I_{q^Lq^R} = I^E_{q^Lq^R} + I^R_{q^Lq^R} + I^L_{q^Lq^R},\n   * \\f}\n   * which can be interpreted as a contribution from equal-time\n   * evaluations and contributions related to the remote and local\n   * evaluation times.  These are given by\n   * \\f{align}\n   *   I^E_{q^Lq^R} &=\n   *   \\mspace{-10mu}\n   *   \\sum_{n=n_S}^{\\min\\left\\{n_E, n^L+k\\right\\}-1}\n   *   \\mspace{-10mu}\n   *   \\tilde{\\alpha}_{n,n-n^L} \\Delta \\tU_n\n   *   &&\\text{if $\\tL_{q^L} = \\tR_{q^R}$, otherwise 0}\n   *   \\\\\n   *   I^R_{q^Lq^R} &=\n   *   \\ell_{q^L - m_S + k}\\!\\left(\n   *     \\tU_{n^R}; \\tL_{m_S - (k-1)}, \\ldots, \\tL_{m_S}\\right)\n   *   \\mspace{-10mu}\n   *   \\sum_{n=\\max\\left\\{n_S, n^R\\right\\}}\n   *       ^{\\min\\left\\{n_E, n^R+k\\right\\}-1}\n   *   \\mspace{-10mu}\n   *   \\tilde{\\alpha}_{n,n-n^R} \\Delta \\tU_n\n   *   &&\\text{if $\\tR_{q^R}$ is not in $\\{\\tL_{\\vphantom{|}\\cdots}\\}$,\n   *     otherwise 0}\n   *   \\\\\n   *   I^L_{q^Lq^R} &=\n   *   \\mspace{-10mu}\n   *   \\sum_{n=\\max\\left\\{n_S, n^R\\right\\}}\n   *       ^{\\min\\left\\{n_E, n^L+k, n^R_{q^R+k}\\right\\}-1}\n   *   \\mspace{-10mu}\n   *   \\ell_{q^R - m^R_n + k}\\!\\left(\\tU_{n^L};\n   *     \\tR_{m^R_n - (k-1)}, \\ldots, \\tR_{m^R_n}\\right)\n   *   \\tilde{\\alpha}_{n,n-n^L} \\Delta \\tU_n\n   *   &&\\text{if $\\tL_{q^L}$ is not in $\\{\\tR_{\\vphantom{|}\\cdots}\\}$,\n   *     otherwise 0,}\n   * \\f}\n   * where for brevity we write \\f$n^L = n^L_{q^L}\\f$ and \\f$n^R =\n   * n^R_{q^R}\\f$, and where \\f$\\ell_a(t; x_1, \\ldots, x_k)\\f$ a\n   * Lagrange interpolating polynomial and \\f$\\tilde{\\alpha}_{nj}\\f$\n   * is the \\f$j\\f$th coefficient for an Adams-Bashforth step over the\n   * union times from step \\f$n\\f$ to step \\f$n+1\\f$.\n   */\n  template <typename LocalVars, typename RemoteVars, typename Coupling>\n  std::result_of_t<const Coupling&(LocalVars, RemoteVars)>\n  compute_boundary_delta(\n      const Coupling& coupling,\n      gsl::not_null<BoundaryHistoryType<LocalVars, RemoteVars, Coupling>*>\n          history,\n      const TimeDelta& time_step) const noexcept;\n\n  uint64_t number_of_substeps() const noexcept override;\n\n  size_t number_of_past_steps() const noexcept override;\n\n  bool is_self_starting() const noexcept override;\n\n  double stable_step() const noexcept override;\n\n  TimeId next_time_id(const TimeId& current_id,\n                      const TimeDelta& time_step) const noexcept override;\n\n  template <typename Vars, typename DerivVars>\n  bool can_change_step_size(\n      const TimeId& time_id,\n      const TimeSteppers::History<Vars, DerivVars>& history) const noexcept;\n\n  WRAPPED_PUPable_decl_template(AdamsBashforthN);  // NOLINT\n\n  explicit AdamsBashforthN(CkMigrateMessage* /*unused*/) noexcept {}\n\n  // clang-tidy: do not pass by non-const reference\n  void pup(PUP::er& p) noexcept override;  // NOLINT\n\n private:\n  friend bool operator==(const AdamsBashforthN& lhs,\n                         const AdamsBashforthN& rhs) noexcept;\n\n  /// Get coefficients for a time step.  Arguments are an iterator\n  /// pair to past times, oldest to newest, and the time step to take.\n  template <typename Iterator>\n  static std::vector<double> get_coefficients(const Iterator& times_begin,\n                                              const Iterator& times_end,\n                                              const TimeDelta& step) noexcept;\n\n  static std::vector<double> get_coefficients_impl(\n      const std::vector<double>& steps) noexcept;\n\n  static std::vector<double> variable_coefficients(\n      const std::vector<double>& steps) noexcept;\n\n  static std::vector<double> constant_coefficients(size_t order) noexcept;\n\n  /// Comparator for ordering by \"simulation time\"\n  class SimulationLess {\n   public:\n    explicit SimulationLess(const bool forward_in_time) noexcept\n        : forward_in_time_(forward_in_time) {}\n\n    bool operator()(const Time& a, const Time& b) const noexcept {\n      return forward_in_time_ ? a < b : b < a;\n    }\n\n   private:\n    bool forward_in_time_;\n  };\n\n  size_t target_order_ = 3;\n  bool is_self_starting_ = true;\n};\n\nbool operator!=(const AdamsBashforthN& lhs,\n                const AdamsBashforthN& rhs) noexcept;\n\ntemplate <typename Vars, typename DerivVars>\nvoid AdamsBashforthN::update_u(\n    const gsl::not_null<Vars*> u,\n    const gsl::not_null<History<Vars, DerivVars>*> history,\n    const TimeDelta& time_step) const noexcept {\n  ASSERT(is_self_starting_ or target_order_ == history->size(),\n         \"Length of history should be the order, so \"\n         << target_order_ << \", but is: \" << history->size());\n  ASSERT(history->size() > 0, \"No history provided\");\n  ASSERT(history->size() <= target_order_,\n         \"Length of history (\" << history->size() << \") \"\n         << \"should not exceed target order (\" << target_order_ << \")\");\n\n  const auto& coefficients =\n      get_coefficients(history->begin(), history->end(), time_step);\n\n  const auto do_update =\n      [u, &time_step, &coefficients, &history](auto order) noexcept {\n    *u += time_step.value() * constexpr_sum<order>(\n        [order, &coefficients, &history](auto i) noexcept {\n          return coefficients[order - 1 - i] *\n              (history->begin() + static_cast<ssize_t>(i)).derivative();\n        });\n  };\n\n  switch (history->size()) {\n    case 1:\n      do_update(std::integral_constant<size_t, 1>{});\n      break;\n    case 2:\n      do_update(std::integral_constant<size_t, 2>{});\n      break;\n    case 3:\n      do_update(std::integral_constant<size_t, 3>{});\n      break;\n    case 4:\n      do_update(std::integral_constant<size_t, 4>{});\n      break;\n    case 5:\n      do_update(std::integral_constant<size_t, 5>{});\n      break;\n    case 6:\n      do_update(std::integral_constant<size_t, 6>{});\n      break;\n    case 7:\n      do_update(std::integral_constant<size_t, 7>{});\n      break;\n    case 8:\n      do_update(std::integral_constant<size_t, 8>{});\n      break;\n    default:\n      ERROR(\"Bad amount of history data: \" << history->size());\n  }\n\n  history->mark_unneeded(history->begin() + 1);\n}\n\ntemplate <typename LocalVars, typename RemoteVars, typename Coupling>\nstd::result_of_t<const Coupling&(LocalVars, RemoteVars)>\nAdamsBashforthN::compute_boundary_delta(\n    const Coupling& coupling,\n    const gsl::not_null<BoundaryHistoryType<LocalVars, RemoteVars, Coupling>*>\n        history,\n    const TimeDelta& time_step) const noexcept {\n  const auto order = history->local_size();\n\n  // Avoid billions of casts\n  const auto order_s = static_cast<ssize_t>(order);\n\n  ASSERT(is_self_starting_ or order == target_order_,\n         \"Local history has wrong length (\" << order\n         << \" should be \" << target_order_ << \")\");\n  ASSERT(order <= target_order_,\n         \"Local history is too long for target order (\" << order\n         << \" should not exceed \" << target_order_ << \")\");\n  ASSERT(history->remote_size() >= order,\n         \"Remote history is too short (\" << history->remote_size()\n         << \" should be at least \" << order << \")\");\n\n  // Start and end of the step we are trying to take\n  const Time start_time = *(history->local_end() - 1);\n  const Time end_time = start_time + time_step;\n\n  // If a remote evaluation is done at the start of the step then that\n  // is part of the history for the first union step.  When we did\n  // history cleanup at the end of the previous step we didn't know we\n  // were going to get this point so we kept an extra remote history\n  // value.\n  if (history->remote_size() > order and\n      *(history->remote_begin() + order_s) == start_time) {\n    history->remote_mark_unneeded(history->remote_begin() + 1);\n  }\n\n  // Result variable.  We evaluate the coupling only for the\n  // structure.  This evaluation may be expensive, but by choosing the\n  // most recent times on both sides we should guarantee that it is a\n  // result we need later, so this will serve to get it into the\n  // coupling cache so we don't have to compute it when we actually use it.\n  auto accumulated_change =\n      make_with_value<std::result_of_t<const Coupling&(LocalVars, RemoteVars)>>(\n          history->coupling(coupling, history->local_end() - 1,\n                            history->remote_end() - 1),\n          0.);\n\n  if (history->local_size() == history->remote_size() and\n      std::equal(history->local_begin(), history->local_end(),\n                 history->remote_begin())) {\n    // No local time-stepping going on.\n    const auto coefficients = get_coefficients(history->local_begin(),\n                                               history->local_end(), time_step);\n\n    auto local_it = history->local_begin();\n    auto remote_it = history->remote_begin();\n    for (auto coefficients_it = coefficients.rbegin();\n         coefficients_it != coefficients.rend();\n         ++coefficients_it, ++local_it, ++remote_it) {\n      accumulated_change +=\n          *coefficients_it * history->coupling(coupling, local_it, remote_it);\n    }\n    accumulated_change *= time_step.value();\n\n    // The remote-side values will all be needed if the remote step is\n    // larger than our local one.  If not, they will be cleaned up\n    // next time.\n    history->local_mark_unneeded(history->local_begin() + 1);\n\n    return accumulated_change;\n  }\n\n  ASSERT(order == target_order_,\n         \"Cannot perform local time-stepping while self-starting.\");\n\n  const SimulationLess simulation_less(time_step.is_positive());\n\n  ASSERT(std::is_sorted(history->local_begin(), history->local_end(),\n                        simulation_less),\n         \"Local history not in order\");\n  ASSERT(std::is_sorted(history->remote_begin(), history->remote_end(),\n                        simulation_less),\n         \"Remote history not in order\");\n  ASSERT(not simulation_less(start_time,\n                             *(history->remote_begin() + (order_s - 1))),\n         \"Remote history does not extend far enough back\");\n  ASSERT(simulation_less(*(history->remote_end() - 1), end_time),\n         \"Please supply only older data: \" << *(history->remote_end() - 1)\n         << \" is not before \" << end_time);\n\n  // Union of times of all step boundaries on any side.\n  const auto union_times = [&end_time, &history, &simulation_less]() noexcept {\n    std::vector<Time> ret;\n    ret.reserve(history->local_size() + history->remote_size() + 1);\n    std::set_union(history->local_begin(), history->local_end(),\n                   history->remote_begin(), history->remote_end(),\n                   std::back_inserter(ret), simulation_less);\n    ret.push_back(end_time);\n    return ret;\n  }();\n\n  using UnionIter = typename decltype(union_times)::const_iterator;\n\n  // Find the union times iterator for a given time.\n  const auto union_step =\n      [&union_times, &simulation_less](const Time& t) noexcept {\n    return std::lower_bound(union_times.cbegin(), union_times.cend(), t,\n                            simulation_less);\n  };\n\n  // The union time index for the step start and end.\n  const auto union_step_start = union_step(start_time);\n  const auto union_step_end = union_times.cend() - 1;\n\n  // min(union_step_end, it + order_s) except being careful not\n  // to create out-of-range iterators.\n  const auto advance_within_step =\n      [order_s, union_step_end](const UnionIter& it) noexcept {\n    return union_step_end - it > order_s ? it + order_s : union_step_end;\n  };\n\n  // Calculating the Adams-Bashforth coefficients is somewhat\n  // expensive, so we cache them.  ab_coefs(it) returns the\n  // coefficients used to step from it to *(it + 1).\n  auto ab_coefs = make_cached_function<UnionIter, std::map>([order_s](\n      const UnionIter& times_end) noexcept {\n    return get_coefficients(times_end - (order_s - 1), times_end + 1,\n                            *(times_end + 1) - *times_end);\n  });\n\n  for (auto local_evaluation_step = history->local_begin();\n       local_evaluation_step != history->local_end();\n       ++local_evaluation_step) {\n    const auto union_local_evaluation_step = union_step(*local_evaluation_step);\n    for (auto remote_evaluation_step = history->remote_begin();\n         remote_evaluation_step != history->remote_end();\n         ++remote_evaluation_step) {\n      double deriv_coef = 0.;\n\n      // The value of the coefficient of `evaluation_step` when doing\n      // a standard Adams-Bashforth integration over the union times\n      // from `step` to `step + 1`.\n      const auto base_summand = [&ab_coefs](\n          const UnionIter& step, const UnionIter& evaluation_step) noexcept {\n        return ((step + 1)->value() - step->value()) *\n               ab_coefs(step)[static_cast<size_t>(step - evaluation_step)];\n      };\n\n      if (*local_evaluation_step == *remote_evaluation_step) {\n        // The two elements stepped at the same time.  This gives a\n        // standard Adams-Bashforth contribution to each segment\n        // making up the current step.\n        const auto union_step_upper_bound =\n            advance_within_step(union_local_evaluation_step);\n        for (auto step = union_step_start;\n             step < union_step_upper_bound;\n             ++step) {\n          deriv_coef += base_summand(step, union_local_evaluation_step);\n        }\n      } else {\n        // In this block we consider a coupling evaluation that is not\n        // performed at equal times on the two sides of the mortar.\n\n        // Makes an iterator with a map to give time as a double.\n        const auto make_lagrange_iterator = [](const auto& it) noexcept {\n          return boost::make_transform_iterator(\n              it, [](const Time& t) noexcept { return t.value(); });\n        };\n\n        const auto union_remote_evaluation_step =\n            union_step(*remote_evaluation_step);\n        const auto union_step_lower_bound =\n            std::max(union_step_start, union_remote_evaluation_step);\n\n        // Compute the contribution to an interpolation over the local\n        // times to `remote_evaluation_step->value()`, which we will\n        // use as the coupling value for that time.  If there is an\n        // actual evaluation at that time then skip this because the\n        // Lagrange polynomial will be zero.\n        if (not std::binary_search(history->local_begin(), history->local_end(),\n                                   *remote_evaluation_step, simulation_less)) {\n          const auto union_step_upper_bound =\n              advance_within_step(union_remote_evaluation_step);\n          for (auto step = union_step_lower_bound;\n               step < union_step_upper_bound;\n               ++step) {\n            deriv_coef += base_summand(step, union_remote_evaluation_step);\n          }\n          deriv_coef *= lagrange_polynomial(\n              make_lagrange_iterator(local_evaluation_step),\n              remote_evaluation_step->value(),\n              make_lagrange_iterator(history->local_begin()),\n              make_lagrange_iterator(history->local_end()));\n        }\n\n        // Same qualitative calculation as the previous block, but\n        // interpolating over the remote times.  This case is somewhat\n        // more complicated because the latest remote time that can be\n        // used varies for the different segments making up the step.\n        if (not std::binary_search(history->remote_begin(),\n                                   history->remote_end(),\n                                   *local_evaluation_step, simulation_less)) {\n          auto union_step_upper_bound =\n              advance_within_step(union_local_evaluation_step);\n          if (history->remote_end() - remote_evaluation_step > order_s) {\n            union_step_upper_bound = std::min(\n                union_step_upper_bound,\n                union_step(*(remote_evaluation_step + order_s)));\n          }\n\n          auto control_points = make_lagrange_iterator(\n              remote_evaluation_step - history->remote_begin() >= order_s\n                  ? remote_evaluation_step - (order_s - 1)\n                  : history->remote_begin());\n          for (auto step = union_step_lower_bound;\n               step < union_step_upper_bound;\n               ++step, ++control_points) {\n            deriv_coef += base_summand(step, union_local_evaluation_step) *\n                          lagrange_polynomial(\n                              make_lagrange_iterator(remote_evaluation_step),\n                              local_evaluation_step->value(),\n                              control_points,\n                              control_points + order_s);\n          }\n        }\n      }\n\n      if (deriv_coef != 0.) {\n        // Skip the (potentially expensive) coupling calculation if\n        // the coefficient is zero.\n        accumulated_change +=\n            deriv_coef * history->coupling(coupling, local_evaluation_step,\n                                           remote_evaluation_step);\n      }\n    }  // for remote_evaluation_step\n  }  // for local_evaluation_step\n\n  // Clean up old history\n\n  // We know that the local side will step at end_time, so the step\n  // containing that time will be the next step, which is not\n  // currently in the history.  We therefore know we won't need the\n  // oldest value for the next step.\n  history->local_mark_unneeded(history->local_begin() + 1);\n  // We don't know whether the remote side will step at end_time, so\n  // we have to be conservative and assume they will not.  If it does\n  // we will remove the first value at the start of the next call to\n  // this function.\n  history->remote_mark_unneeded(history->remote_end() - order_s);\n\n  return accumulated_change;\n}\n\ntemplate <typename Vars, typename DerivVars>\nbool AdamsBashforthN::can_change_step_size(\n    const TimeId& time_id,\n    const TimeSteppers::History<Vars, DerivVars>& history) const noexcept {\n  // We need to forbid local time-stepping before initialization is\n  // complete.  The self-start procedure itself should never consider\n  // changing the step size, but we need to wait during the main\n  // evolution until the self-start history has been replaced with\n  // \"real\" values.\n  const SimulationLess less(time_id.time_runs_forward());\n  return history.size() == 0 or\n         (less(history.back(), time_id.time()) and\n          std::is_sorted(history.begin(), history.end(), less));\n}\n\ntemplate <typename Iterator>\nstd::vector<double> AdamsBashforthN::get_coefficients(\n    const Iterator& times_begin, const Iterator& times_end,\n    const TimeDelta& step) noexcept {\n  std::vector<double> steps;\n  // This may be slightly more space than we need, but we can't get\n  // the exact amount without iterating through the iterators, which\n  // is not necessarily cheap depending on the iterator type.\n  steps.reserve(maximum_order);\n  for (auto t = times_begin; std::next(t) != times_end; ++t) {\n    steps.push_back((*std::next(t) - *t) / step);\n  }\n  steps.push_back(1.);\n  return get_coefficients_impl(steps);\n}\n\n}  // namespace TimeSteppers\n", "meta": {"hexsha": "55de858327349cf00e9fe277cda015b07f4450ee", "size": 24688, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Time/TimeSteppers/AdamsBashforthN.hpp", "max_stars_repo_name": "osheamonn/spectre", "max_stars_repo_head_hexsha": "4a3332c61d749d83c161ea1c2ea014a937fd5dd8", "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/Time/TimeSteppers/AdamsBashforthN.hpp", "max_issues_repo_name": "osheamonn/spectre", "max_issues_repo_head_hexsha": "4a3332c61d749d83c161ea1c2ea014a937fd5dd8", "max_issues_repo_licenses": ["MIT"], "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/Time/TimeSteppers/AdamsBashforthN.hpp", "max_forks_repo_name": "osheamonn/spectre", "max_forks_repo_head_hexsha": "4a3332c61d749d83c161ea1c2ea014a937fd5dd8", "max_forks_repo_licenses": ["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.9482200647, "max_line_length": 80, "alphanum_fraction": 0.64330849, "num_tokens": 6442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1939596047170351}}
{"text": "#include \"wali/graph/InterGraph.hpp\"\n#include \"wali/graph/IntraGraph.hpp\"\n#include \"wali/graph/RegExp.hpp\"\n#include \"wali/graph/Functional.hpp\"\n\n#include \"wali/util/Timer.hpp\"\n\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <sstream>\n#include <boost/cast.hpp>\n\n// ::wali\n#include \"wali/SemElemTensor.hpp\"\n\ntypedef int INTER_GRAPH_INT;\n\nusing namespace std;\n\nnamespace wali {\n\n    namespace graph {\n\n        UnionFind::UnionFind(int len) {\n            n = len;\n            count = len;\n            arr = new int[n];\n            for(int i=0; i < n;i++) {\n                arr[i] = i;\n            }\n        }\n\n        UnionFind::UnionFind(UnionFind& from) : n(from.n), count(from.count){\n          arr = new int[n];\n          for(int i=0; i<n; ++i)\n            arr[i] = from.arr[i];\n        }\n\n        UnionFind::~UnionFind() {\n            delete [] arr;\n            arr = NULL;\n            n = 0;\n        }\n\n        void UnionFind::reset() {\n            for(int i=0; i < n;i++) {\n                arr[i] = i;\n            }\n        }\n\n        int UnionFind::find(int a) {\n            int r = a,p;\n            while(arr[r] != r) {\n                r = arr[r];\n            }\n            // path compression\n            while(arr[a] != a) {\n                p = arr[a];\n                arr[a] = r;\n                a = p;\n            }\n            return r;\n        }\n\n        void UnionFind::takeUnion(int a, int b) {\n            int ar = find(a);\n            int br = find(b);\n            arr[ar] = br; // FIXME: Randomize this\n            //TODO: Used ranked union\n\n            // if two sets were merged, the total number of sets has decreaseed\n            // by one\n            if(ar != br) count--;\n            assert(count > 0 && \"Count of sets reached zero: There is a bug\\n\");\n        }\n\n        int UnionFind::countSets(){\n          return count;\n        }\n\n        std::ostream& UnionFind::print(std::ostream& o)\n        {\n          std::multiset< std::pair< int, int > > shadow;\n          int curset = -1;\n\n          o << \"[ \";\n          for(int i=0; i<n; ++i){\n            shadow.insert(std::pair< int, int >(find(i),i));\n          }\n\n          for(std::multiset< std::pair< int, int > >::iterator iter = shadow.begin();\n              iter != shadow.end();\n              ++iter){\n            if(iter->first > curset){\n              if(curset != -1) \n                o << \">>>>>>>>>\" << std::endl;\n              curset = iter->first;\n            }\n            o << iter->second << \" \";\n          }\n          o << \"]\";\n          return o;\n        }\n\n        inter_node_t promote_type(inter_node_t t1, inter_node_t t2) {\n            if(t1 == InterNone)\n                return t2;\n            if(t2 == InterNone)\n                return t1;\n            if(t1 == t2)\n                return t1;\n            return InterSourceOutNode;\n        }\n\n        bool is_source_type(inter_node_t t1) {\n            return (t1 == InterSource || t1 == InterSourceOutNode);\n        }\n\n        sem_elem_tensor_t tensorSetUpFP(sem_elem_tensor_t a, sem_elem_tensor_t b)\n        {\n          return a->tensor(b.get_ptr());\n        }\n\n        void ETransHandler::addEdge(int call, int ret, sem_elem_t wtCallRule) {\n          EdgeMap::iterator it = edgeMap.find(ret);\n          if(it != edgeMap.end()) {\n            Dependency &d = it->second;\n            d.second = d.second->combine(wtCallRule);\n          } else {\n            edgeMap[ret] = Dependency(call, wtCallRule);\n          }\n        }\n\n        void ETransHandler::tensorAllWeights()\n        {\n          if(edgeMap.size() == 0)\n            return;\n          Dependency dy = edgeMap.begin()->second;\n          sem_elem_tensor_t one = boost::polymorphic_downcast<SemElemTensor*>(dy.second->one().get_ptr());\n          for(EdgeMap::iterator it = edgeMap.begin(); it != edgeMap.end(); ++it)\n            edgeMap[it->first] = Dependency(it->second.first, tensorSetUpFP(one, boost::polymorphic_downcast<SemElemTensor*>(it->second.second.get_ptr())).get_ptr());\n        }\n\n        bool ETransHandler::exists(int ret) {\n          EdgeMap::iterator it = edgeMap.find(ret);\n          if(it != edgeMap.end()) {\n            return true;\n          }\n          return false;\n        }\n\n        // return NULL if no match found\n        sem_elem_t ETransHandler::get_dependency(int ret, int &call) {\n          EdgeMap::iterator it = edgeMap.find(ret);\n          if(it != edgeMap.end()) {\n            Dependency &d = it->second;\n            call = d.first;\n            return d.second;\n          }\n          return sem_elem_t(0);\n        }\n\n        InterGraph::InterGraph(wali::sem_elem_t s, bool e, bool pre, bool n)\n        {\n          sem = s;\n          intra_graph_uf = NULL;\n          running_ewpds = e;\n          running_nwpds = n;\n          running_prestar = pre;\n          max_scc_computed = 0;\n          newtonGr = NULL;\n          runningNewton = false;\n          dag = new RegExpDag();\n          count = 0;\n          isOutputAutomatonTensored = false;\n        }\n\n        InterGraph::~InterGraph() {\n          delete dag;\n          std::set<IntraGraph*> deleteGr;\n          for(unsigned i = 0; i < nodes.size(); i++) {\n            if(nodes[i].gr && intra_graph_uf->find(i) == (int)i) {\n              deleteGr.insert(nodes[i].gr);\n              nodes[i].gr=NULL;\n            }\n              nodes[i].sccgr = NULL;\n          }\n          for(std::set<IntraGraph*>::iterator it = deleteGr.begin(); it != deleteGr.end(); ++it)\n            delete *it;\n\n          if(intra_graph_uf) {\n            delete intra_graph_uf;\n            intra_graph_uf = NULL;\n          }\n          if(newtonGr){\n            delete newtonGr;\n            newtonGr = NULL;\n          }\n        }\n\n        int InterGraph::nodeno(Transition &t) {\n          TransMap::iterator it = node_number.find(t);\n          if(it == node_number.end()) {\n            node_number[t] = static_cast<INTER_GRAPH_INT>(nodes.size());\n            nodes.push_back(GraphNode(t));\n            return (static_cast<INTER_GRAPH_INT>(nodes.size()) - 1);\n          }\n          return it->second;\n        }\n\n        bool InterGraph::exists(Transition &t) {\n          TransMap::iterator it = node_number.find(t);\n          if(it == node_number.end()) {\n            return false;\n          }\n          return true;\n        }\n\n        int InterGraph::intra_edgeno(Transition &src, Transition &tgt) {\n          int s = nodeno(src);\n          int t = nodeno(tgt);\n          std::list<int>::iterator it = nodes[s].outgoing.begin();\n          for(; it != nodes[s].outgoing.end(); it++) {\n            if(intra_edges[*it].tgt == t) {\n              return *it;\n            }\n          }\n          return -1;\n        }\n\n        int InterGraph::inter_edgeno(Transition &src1, Transition &src2, Transition &tgt) {\n          int s1 = nodeno(src1);\n          int s2 = nodeno(src2);\n          int t = nodeno(tgt);\n          std::list<int>::iterator it = nodes[s2].out_hyper_edges.begin();\n          for(; it != nodes[s2].out_hyper_edges.end(); it++) {\n            if(inter_edges[*it].tgt == t && inter_edges[*it].src1 == s1) {\n              return *it;\n            }\n          }\n          return -1;\n        }\n\n        bool InterGraph::exists(int state, int stack, WT_CHECK op) {\n          size_t i;\n          for(i=0;i<nodes.size();i++) {\n            if(static_cast<INTER_GRAPH_INT>(nodes[i].trans.src) == state\n                && static_cast<INTER_GRAPH_INT>(nodes[i].trans.stack) == stack)\n            {\n              if(newtonGr){\n                if(op((newtonGr->get_weight(nodes[i].intra_nodeno)).get_ptr())) \n                  return true;\n              }else{\n                  if(op((nodes[i].gr->get_weight(nodes[i].intra_nodeno)).get_ptr())) \n                    return true;\n              }\n            }\n          }\n          return false;\n        }\n\n        std::ostream &InterGraph::print(std::ostream &out, PRINT_OP pop) {\n          unsigned i;\n          if(CONSTANT_CONDITION(1))//intra_graph_uf == NULL) \n          {\n            out << \"Source Transitions:\\n\";\n            for(i=0;i<nodes.size();i++) {\n              if(is_source_type(nodes[i].type)) {\n                IntraGraph::print_trans(nodes[i].trans, out, pop);\n                nodes[i].weight->print(out);\n                out << \"\\n\";\n              }\n            }\n            out << \"IntraEdges:\\n\";\n            for(i=0;i<intra_edges.size();i++) {\n              Transition src = nodes[intra_edges[i].src].trans;\n              Transition tgt = nodes[intra_edges[i].tgt].trans;\n              IntraGraph::print_trans(src, out, pop);\n              out << \"-->\";\n              IntraGraph::print_trans(tgt, out, pop);\n              intra_edges[i].weight->print(out);\n              out << \"\\n\";\n            }\n          } else {\n            for(i = 0; i < nodes.size(); i++) {\n              if(nodes[i].gr && intra_graph_uf->find(i) == (int)i) {\n                nodes[i].gr->print(out,pop);\n                out << \"\\n\";\n              }\n            }\n          }\n          out << \"HyperEdges:\\n\";\n          for(i = 0; i < inter_edges.size(); i++) {\n            Transition src1 = nodes[inter_edges[i].src1].trans;\n            Transition src2 = nodes[inter_edges[i].src2].trans;\n            Transition tgt = nodes[inter_edges[i].tgt].trans;\n            IntraGraph::print_trans(src1, out, pop);\n            out << \",\";\n            IntraGraph::print_trans(src2, out, pop);\n            out << \"-->\";\n            IntraGraph::print_trans(tgt, out, pop);\n            if(inter_edges[i].weight.get_ptr()) {\n              inter_edges[i].weight->print(out);\n            } else {\n              inter_edges[i].mf->print(out);\n            }\n            out << \"\\n\";\n          }\n          return out;\n        }\n\n        void InterGraph::addEdge(Transition src, Transition tgt, wali::sem_elem_t se) {\n          int eno = intra_edgeno(src,tgt);\n          if(eno != -1) { // edge already present\n            intra_edges[eno].weight = intra_edges[eno].weight->combine(se);\n            return;\n          }\n          int s = nodeno(src);\n          int t = nodeno(tgt);\n          GraphEdge ed(s,t,se);\n          intra_edges.push_back(ed);\n          int e = intra_edges.size() - 1;\n          nodes[s].outgoing.push_back(e);\n          nodes[t].incoming.push_back(e);\n        }\n\n        void InterGraph::addCallRetEdge(Transition src, Transition tgt, wali::sem_elem_t se) {\n          addEdge(src, tgt, se->one());\n          int s = nodeno(src);\n          int t = nodeno(tgt);\n          eHandler.addEdge(s, t, se);\n        }\n\n        void InterGraph::addEdge(Transition src1, Transition src2, Transition tgt, wali::sem_elem_t se) {\n          int eno = inter_edgeno(src1,src2,tgt);\n          if(eno != -1) { // edge already present\n            inter_edges[eno].weight = inter_edges[eno].weight->combine(se);\n            return;\n          }\n          int s1 = nodeno(src1);\n          int s2 = nodeno(src2);\n          int t = nodeno(tgt);\n          HyperEdge ed(s1,s2,t,se);\n          nodes[s2].type = promote_type(nodes[s2].type, InterOutNode);\n          inter_edges.push_back(ed);\n          nodes[s2].out_hyper_edges.push_back(inter_edges.size() - 1);\n          nodes[s1].out1_hyper_edges.push_back(inter_edges.size() - 1);\n\n        }\n\n        void InterGraph::addEdge(Transition src1, Transition src2, Transition tgt, merge_fn_t mf) {\n          assert(running_ewpds);\n          int eno = inter_edgeno(src1,src2,tgt);\n          if(eno != -1 && mf == inter_edges[eno].mf) { // edge already present\n            return;\n          }\n          int s1 = nodeno(src1);\n          int s2 = nodeno(src2);\n          int t = nodeno(tgt);\n          HyperEdge ed(s1,s2,t,mf);\n          nodes[s2].type = promote_type(nodes[s2].type, InterOutNode);\n          inter_edges.push_back(ed);\n          nodes[s2].out_hyper_edges.push_back(inter_edges.size() - 1);\n          nodes[s1].out1_hyper_edges.push_back(inter_edges.size() - 1);\n        }\n\n        void InterGraph::addCallEdge(Transition src1, Transition src2) {\n          call_edges.push_back(call_edge_t(nodeno(src1),nodeno(src2)));\n        }\n\n        void InterGraph::setSource(Transition t, wali::sem_elem_t se) {\n          int n = nodeno(t);\n          nodes[n].type = promote_type(nodes[n].type, InterSource);\n          nodes[n].weight = se;\n        }\n\n        void InterGraph::setESource(Transition t, wali::sem_elem_t wtAtCall, wali::sem_elem_t wtAfterCall) {\n          // setSource\n          int n = nodeno(t);\n          nodes[n].type = promote_type(nodes[n].type, InterSource);\n          nodes[n].weight = wtAtCall;\n          // Extra dependency\n          eHandler.addEdge(-1, n, wtAfterCall);\n        }\n\n        unsigned InterGraph::SCCLight(SCCGraphs& grlist, SCCGraphs& grsorted)\n        {\n          SCCGraphs::iterator gr_it;\n          // reset visited\n          for(gr_it = grlist.begin(); gr_it != grlist.end(); gr_it++) {\n            (*gr_it)->visited = false;\n            (*gr_it)->scc_number = 0;\n          }\n          SCCGraphs finished;\n          std::map<scc_graph_t , SCCGraphs, SCCGraphLE> rev_edges;\n          // Do DFS\n          SCCGraphs::reverse_iterator gr_rit;\n          for(gr_rit = grlist.rbegin(); gr_rit != grlist.rend(); gr_rit++) {\n            scc_graph_t gr = *gr_rit;\n            if(gr->visited)\n              continue;\n            dfsLight(gr,finished,rev_edges);\n          }\n\n          unsigned scc = 0;\n\n          for(gr_it = grlist.begin(); gr_it != grlist.end(); gr_it++) {\n            (*gr_it)->visited = false;\n          }\n\n          for(gr_it = finished.begin(); gr_it != finished.end(); gr_it++) {\n            scc_graph_t gr = *gr_it;\n            if(gr->visited)\n              continue;\n            scc++;\n            typedef pair<scc_graph_t, SCCGraphs::iterator> StackEl;\n            std::list<StackEl> stack;\n            stack.push_back(StackEl(gr, rev_edges[gr].begin()));\n            while(!stack.empty()) {\n              StackEl p = stack.front();\n              stack.pop_front();\n              scc_graph_t v = p.first;\n              SCCGraphs::iterator it = p.second;\n              v->scc_number = scc;\n              if(!v->visited) grsorted.push_back(v);\n              v->visited = true;\n              while(it != rev_edges[v].end()) {\n                scc_graph_t c = *it;\n                if(c->visited) {\n                  it++;\n                } else { \n                  stack.push_front(StackEl(v,++it));\n                  stack.push_front(StackEl(c, rev_edges[c].begin()));\n                  break;\n                }\n              }\n            }\n          }\n          // reset visited\n          for(gr_it = grlist.begin(); gr_it != grlist.end(); gr_it++) {\n            (*gr_it)->visited = false;\n          }\n          return scc;\n        }\n\n        void InterGraph::dfsLight(scc_graph_t gr, SCCGraphs& finished, std::map<scc_graph_t, SCCGraphs, SCCGraphLE >& rev_edges) \n        {\n          gr->visited = true;\n          for(SCCGraphs::iterator it = gr->nextGraphs.begin();\n              it != gr->nextGraphs.end();\n              it++){\n            scc_graph_t ch = *it;\n            rev_edges[ch].push_back(gr);\n            if(!ch->visited)\n              dfsLight(ch, finished, rev_edges);\n          }\n                    \n          finished.push_front(gr);\n        }\n\n        unsigned InterGraph::SCC(list<IntraGraph *> &grlist, std::list<IntraGraph *> &grsorted) {\n          std::list<IntraGraph *>::iterator gr_it;\n          // reset visited\n          for(gr_it = grlist.begin(); gr_it != grlist.end(); gr_it++) {\n            (*gr_it)->visited = false;\n            (*gr_it)->scc_number = 0;\n            (*gr_it)->bfs_number = (unsigned)(-1);\n          }\n          std::list<IntraGraph *> finished;\n          std::map<IntraGraph *, std::list<IntraGraph *> > rev_edges;\n          // Do DFS\n          std::list<IntraGraph *>::reverse_iterator gr_rit;\n          for(gr_rit = grlist.rbegin(); gr_rit != grlist.rend(); gr_rit++) {\n            IntraGraph *gr = *gr_rit;\n            if(gr->visited)\n              continue;\n            dfsIntraForward(gr,finished,rev_edges);\n          }\n\n          unsigned scc = 0;\n\n          for(gr_it = grlist.begin(); gr_it != grlist.end(); gr_it++) {\n            (*gr_it)->visited = false;\n          }\n\n          for(gr_it = finished.begin(); gr_it != finished.end(); gr_it++) {\n            IntraGraph *gr = *gr_it;\n            if(gr->visited)\n              continue;\n            scc++;\n            typedef pair<IntraGraph *, std::list<IntraGraph *>::iterator> StackEl;\n            std::list<StackEl> stack;\n            stack.push_back(StackEl(gr, rev_edges[gr].begin()));\n            while(!stack.empty()) {\n              StackEl p = stack.front();\n              stack.pop_front();\n              IntraGraph *v = p.first;\n              std::list<IntraGraph *>::iterator it = p.second;\n              v->scc_number = scc;\n              if(!v->visited) grsorted.push_back(v);\n              v->visited = true;\n              while(it != rev_edges[v].end()) {\n                IntraGraph *c = *it;\n                if(c->visited) {\n                  it++;\n                } else { \n                  stack.push_front(StackEl(v,++it));\n                  stack.push_front(StackEl(c, rev_edges[c].begin()));\n                  break;\n                }\n              }\n            }\n          }\n          // reset visited\n          for(gr_it = grlist.begin(); gr_it != grlist.end(); gr_it++) {\n            (*gr_it)->visited = false;\n          }\n          return scc;\n        }\n\n        void InterGraph::dfsIntraForward(IntraGraph *gr, std::list<IntraGraph *> &finished, std::map<IntraGraph *, std::list<IntraGraph *> > &rev_edges) {\n          gr->visited = true;\n          std::list<int> *outnodes = gr->getOutTransitions();\n          std::list<int>::iterator it;\n          for(it = outnodes->begin(); it != outnodes->end(); it++) {\n            int n = *it;\n            std::list<int>::iterator beg = nodes[n].out_hyper_edges.begin();\n            std::list<int>::iterator end = nodes[n].out_hyper_edges.end();\n            for(; beg != end; beg++) {\n              IntraGraph *ch = nodes[inter_edges[*beg].tgt].gr;\n              rev_edges[ch].push_back(gr);\n              if(!ch->visited)\n                dfsIntraForward(ch, finished,rev_edges);\n            }\n          }\n          finished.push_front(gr);\n        }\n\n        // BFS of a SCC\n        void InterGraph::bfsIntra(IntraGraph *start, unsigned int scc_number) {\n          std::list <IntraGraph *> workset;\n          workset.push_back(start);\n          IntraGraph *gr;\n          start->bfs_number = 0;\n          while(!workset.empty()) {\n            gr = workset.front();\n            workset.pop_front();\n            if(gr->visited) continue;\n\n            gr->visited = true;\n\n            std::list<int> *outnodes = gr->getOutTransitions();\n            std::list<int>::iterator it;\n            for(it = outnodes->begin(); it != outnodes->end(); it++) {\n              int n = *it;\n              std::list<int>::iterator beg = nodes[n].out_hyper_edges.begin();\n              std::list<int>::iterator end = nodes[n].out_hyper_edges.end();\n              for(; beg != end; beg++) {\n                IntraGraph *ch = nodes[inter_edges[*beg].tgt].gr;\n                if(ch->scc_number != scc_number) continue;\n                if(!ch->visited) {\n                  ch->bfs_number = (ch->bfs_number > (gr->bfs_number) + 1) ? (gr->bfs_number+1) : ch->bfs_number;\n                  workset.push_back(ch);\n                }\n              }\n            }\n          }\n        }\n\n        // BFS of a SCC\n        void InterGraph::resetSCCedges(IntraGraph *gr, unsigned int scc_number) {\n          std::list<int> *outnodes = gr->getOutTransitions();\n          std::list<int>::iterator it;\n          for(it = outnodes->begin(); it != outnodes->end(); it++) {\n            int n = *it;\n            std::list<int>::iterator beg = nodes[n].out_hyper_edges.begin();\n            std::list<int>::iterator end = nodes[n].out_hyper_edges.end();\n            for(; beg != end; beg++) {\n              int inode = inter_edges[*beg].tgt;\n              int onode1 = inter_edges[*beg].src1;\n              IntraGraph *ch = nodes[inode].gr;\n              if(ch->scc_number != scc_number) continue;\n              ch->updateEdgeWeight(nodes[onode1].intra_nodeno, nodes[inode].intra_nodeno, sem->zero());\n            }\n          }\n        }\n\n        void InterGraph::setup_worklist(list<IntraGraph *> &gr_sorted, std::list<IntraGraph *>::iterator &gr_it, unsigned int scc_n,\n            multiset<tup> &worklist) {\n          worklist.clear();\n          while(gr_it != gr_sorted.end() && (*gr_it)->scc_number == scc_n ) {\n            std::list<int>::iterator tbeg = (*gr_it)->getOutTransitions()->begin();\n            std::list<int>::iterator tend = (*gr_it)->getOutTransitions()->end();\n            while(tbeg != tend) {\n              int onode = *tbeg;\n              worklist.insert(tup((*gr_it)->bfs_number,onode));\n              //nodes[onode].weight = nodes[onode].gr->get_weight(nodes[onode].trans);\n              tbeg++;\n            }\n            gr_it++;\n          }\n        }                       \n\n#if defined(PPP_DBG) && PPP_DBG >= 2\n        static std::ostream& pp_weight(std::ostream& o, sem_elem_t weight)\n        {\n          if(weight == NULL){\n            o << \"NULL\";\n            return o;\n          }\n\n          stringstream ss;\n          weight->print(ss);\n          string res = \"\";\n          string ssstr = ss.str();\n          for(string::iterator iter = ssstr.begin(); iter != ssstr.end();\n              iter++){\n            if(*iter == '>'){\n              res.push_back(*iter);\n              res.append(\"\\\\n\");\n            }else\n              res.push_back(*iter);\n          }\n          o << res;\n          return o;\n        }\n#endif\n\n        /**\n         * @brief From the given TDG (The original InterGraph), create linearized TDGs corresponding\n         * to each step of Newton. Then, solve the poststar problem by executing steps of the newton's \n         * method till fix-point.\n         *\n         * @note Only works for poststar\n         * @note When the function returns, the result automaton may obtain tensored or non-tensored weights\n         * based on some heuristics. You must be prepared to obtain either.\n         * @see isOutputAutomatonTensored\n         * @see setupInterSolution -- This function evolved originally from that.\n         * @see IntraGraph, RegExp, SCCGraph. Uses them heavily.\n         *\n         * Function description: \n         * A TDG is an InterGraph (yes, me!) that consists of IntraGraphs.\n         * The nodes of the TDG (referred to as n/s/c/x/r) are effectively transitions in the output\n         * automaton\n         * The edges of the TDG (referred to as e) are effectively the Grammar Flow Problem\n         * equations (poststar rules, if you will)\n         * (1) Find out SCCs in the graph.\n         * Consider a graph where each node is an IntraGraph (this is close to the callgraph of the\n         * original program).  The fix-point problem will be solved by linearizing each SCC in turn,\n         * while walking the list of SCCs in reverse topological order.\n         *\n         * For each SCC:\n         *   // Create one actual IntraGraph for current Intragraph.\n         *   // There are two options here:\n         *   //   - if |SCC| == 1 (i.e., SCC is just one procedure), mimic non-newton FWPDS\n         *   //   - if |SCC| > 1 (i.e., we must coalesce multiple procedures by linearizing), use\n         *   //     Newton's linearization\n         *   (2) Add nodes to IntraGraph, along with unique source node s.\n         *   (3) Compute |SCC|\n         *   if |SCC| == 1 then\n         *     // Mimic FWPDS\n         *     // Add IntraEdges: since there is no recursive call, all edges will be immutable\n         *        (4.1.1) For every source node n in InterGraph (roughly, procedure entry), add an\n         *        Edge from s to n with weight 1 (call to setSource())\n         *        (4.1.2) For every Edge (\\delta_1 rule) n1-e->n2, add an edge n1-e->n2 to the\n         *        IntraGraph\n         *        (4.1.3) For every HyperEdge (\\delta_2 rule) c-e-x->r (x is the external source),\n         *        add an edge c-e->r with weight w(x). Since the call can't possibly be recursive,\n         *        the summary for this procedure must already have been computed in some earlier\n         *        SCC. Use that weight.\n         *   else   \n         *     // There are multiple SCCGraphs in this SCC. We will coalesce them into one\n         *     // IntraGraph.\n         *     // The basic outline here follows that in (4.1), but the equation system we are\n         *     // forming in this case is the linear system. \n         *     // For source nodes and \\delta_1 rules, instead of edges with weight w, we create\n         *     // edges with weight (w,1^T) where (.,.) is tensor and ^T is transpose\n         *     // The case for \\delta_2 is split in two -- if the call is made to a function\n         *     // belonging to a function with lower SCC number, then this case is handled\n         *     // identically to (4.1.3). Instead, if the call is made to a function within this\n         *     // SCC, for the call c-e-x->r, we add three edges: c-e1->r with functional(x);\n         *     // x-e2->r with functional(c) and s-e3->r with functional(c,x) all mutable. This\n         *     // corresponds. A functional is a recipe that is later used to compute the weight\n         *     // that must go on the edge (between newton rounds) from the weights on the argument\n         *     // nodes. For details of the exact weights and functionals that go on various edges,\n         *     // see comments below within the function.\n         *     (4.2.1) Add edges for source nodes\n         *     (4.2.2) Add edges for \\delta_1 rules\n         *     (4.2.3.1) Add edges for \\delta_2 rules where the call is to a function with lower SCC\n         *     (4.2.3.2) Add edges for \\delta_2 rules where the call is to a function with from same\n         *     SCC.\n         *     TODO: Argue that mutable edges are not needed in (4.2.1) and (4.2.2)\n         *   (5) Use Tarjan's path listing algorithm to generate regular expressions for the\n         *   IntraGraph.\n         *   (6) Solve the linearized problem by saturation. \n         *   @see IntraGraph::saturate \n         *   Till fix-point:\n         *      -- Evaluate the regular expressions (This corresponds to one Newton's round)\n         *      -- update functionals and repeat.\n         * (7) Decide whether the output automaton is tensored.\n         * Because the weights on IntraGraphs can be both tensored and non-tensored (tensored in\n         * 4.2, non-tensored in 4.1), we must decide how the weights on the output automaton are.\n         * We do that by counting the number of extra tensor / detensor operations needed in either\n         * choice, and then using a heuristic to decide between the two.\n         * FIXME: Currently, we override the choice, and always tensor weights. This might be the\n         * best choice anyway, because detensor is a lot costlier than tensor in most cases. (Not\n         * true with nwa_detensor)\n         * (8) Set some more stuff that IntraGraph, FWPDS need after poststar. Mostly copied from\n         * setupInterSolution.\n         * \n         **/\n        void InterGraph::setupNewtonSolution()\n        {\n          runningNewton = true;         \n          // First populate SCCGraph objects\n\n          int n = nodes.size();\n          int i;\n          unsigned int max_scc_required;\n          SCCGraphs scc_gr_list;\n          SCCGraphs gr_sorted;\n          // (1) The SCC computation.\n          // We will use a light-weight graph data structure called SCCGraph to find out the \n          // SCCs in the TDG. Each SCCGraph roughly corresponds to what will later (in the function) become\n          // an IntraGraph. But SCCGraph have no extra information beyond the graph node and edge information,\n          // just enough to find the SCCs.\n          intra_graph_uf = new UnionFind(n);\n          {\n            vector<GraphEdge>::iterator it;\n            vector<HyperEdge>::iterator it2;\n            for(it = intra_edges.begin(); it != intra_edges.end(); it++) {\n              intra_graph_uf->takeUnion((*it).src,(*it).tgt);\n            }\n            for(it2 = inter_edges.begin(); it2 != inter_edges.end(); it2++) {\n              intra_graph_uf->takeUnion((*it2).src1,(*it2).tgt);\n            }\n\n            // Add nodes to SCCGraphs\n            for(i = 0; i < n;i++) {\n              int j = intra_graph_uf->find(i);\n              if(nodes[j].sccgr == NULL){\n                nodes[j].sccgr = new SCCGraph();\n                scc_gr_list.push_back(nodes[j].sccgr);\n              }\n              nodes[i].sccgr = nodes[j].sccgr;\n              nodes[i].sccgr->nodes.push_back(i);\n            }\n            // Add edges tp SCCGraphs\n            for(it = intra_edges.begin(); it != intra_edges.end(); it++)\n              nodes[(*it).src].sccgr->intraEdges.push_back(*it);\n            for(it2 = inter_edges.begin(); it2 != inter_edges.end(); it2++)\n              nodes[(*it2).tgt].sccgr->interEdges.push_back(*it2);\n            // Also populate inter graph maps for the scc\n            for (it2 = inter_edges.begin(); it2 != inter_edges.end(); ++it2)\n              nodes[(*it2).src2].sccgr->nextGraphs.push_back(nodes[(*it2).tgt].sccgr);\n\n\n            // Do SCC decomposition \n            max_scc_required = SCCLight(scc_gr_list, gr_sorted);\n            STAT(stats.ncomponents = max_scc_required);\n          }\n\n          //Setup weights so that everything is tensored\n          sem_elem_tensor_t sem_old = boost::polymorphic_downcast<SemElemTensor*>(sem.get_ptr());\n          sem = tensorSetUpFP(sem_old, sem_old);\n#if defined(PPP_DBG) && PPP_DBG >= 0\n          long totCombines=0, totExtends=0, totStars=0;\n          unsigned maxNewtonRounds = 0;\n          unsigned totNewtonRounds = 0;\n#endif\n\n\n          // For each SCC, solve completely using Newton's method.\n          {\n            SCCGraphs::iterator gr_it = gr_sorted.begin();\n            sem_elem_tensor_t one = boost::polymorphic_downcast<SemElemTensor*>(sem_old->one().get_ptr());\n            sem_elem_tensor_t zerot = boost::polymorphic_downcast<SemElemTensor*>((sem->zero()).get_ptr()); //sem is tensored\n            sem_elem_tensor_t zero = boost::polymorphic_downcast<SemElemTensor*>((sem_old->zero()).get_ptr());\n            for(unsigned scc_n = 1; scc_n <= max_scc_required; scc_n++) {\n              ////////////////We will now create the Newton IntraGraph which will store the\n              ////////////////actual weights, and from which RegExp will be generated.\n              ////////////////This is the TDG for the linearized problem for the current SCC\n\n              SCCGraphs::iterator scc_head = gr_it;\n              IntraGraph * graph = new IntraGraph(dag, false, sem); //pre = false\n              linear_gr_list.push_back(graph);\n              // (2) Add nodes to IntraGraph\n              while(gr_it != gr_sorted.end() && (*gr_it)->scc_number == scc_n){\n                scc_graph_t gr = *gr_it;\n                for(vector<int>::iterator iter = gr->nodes.begin(); iter != gr->nodes.end(); ++iter){\n                  int i = *iter;\n                  nodes[i].intra_nodeno = graph->makeNode(nodes[i].trans);\n                  nodes[i].gr = graph;\n                }\n                gr_it++;\n              }\n\n              //Reset gr_it\n              gr_it = scc_head;\n              // (3) Determine if this SCC has a recursive call\n              bool isRecursive = false;\n              while(gr_it != gr_sorted.end() && (*gr_it)->scc_number == scc_n){\n                scc_graph_t gr = *gr_it;\n                for(vector<HyperEdge>::iterator iter = gr->interEdges.begin(); iter != gr->interEdges.end(); ++iter){\n                  if(nodes[iter->src2].gr == graph){\n                    isRecursive = true;\n                    break;\n                  }                    \n                }\n                if(isRecursive)\n                  break;\n                gr_it++;\n              }\n\n              // Will the current graph have tensored weights?\n              // We need to know this for weight queries on the graph after saturation.\n              graph->hasTensoredWeights = isRecursive;\n              \n              //Reset gr_it\n              gr_it = scc_head;\n              // Now add in the myriad edges.\n              if(isRecursive){\n                //Do Newton Magic\n                dag->startSatProcess(sem);\n                while(gr_it != gr_sorted.end() && (*gr_it)->scc_number == scc_n){\n                  scc_graph_t gr = *gr_it;\n\n                  // (4.2.1) Source nodes:\n                  for(vector<int>::iterator iter = gr->nodes.begin(); iter != gr->nodes.end(); ++iter){\n                    int i = *iter;\n                    if(is_source_type(nodes[i].type)) {\n                      //This is a source node. \n                      //Create an immutable edge with weight:\n                      //Post*:  w -> (w,1^T)\n                      sem_elem_tensor_t wt = boost::polymorphic_downcast<SemElemTensor*>((nodes[i].weight).get_ptr());\n                      sem_elem_tensor_t one = boost::polymorphic_downcast<SemElemTensor*>((wt->one()).get_ptr());\n                      wt = tensorSetUpFP(wt,one);\n                      graph->setSource(nodes[i].intra_nodeno, wt);\n                    }\n                    // zero all weights (some are set by InterGraph::setSource() )\n                    if(nodes[i].weight.get_ptr() != NULL)\n                      nodes[i].weight = zerot;\n                  }\n\n                  // (4.2.2) Intra Edges:\n                  for(vector<GraphEdge>::iterator iter = gr->intraEdges.begin(); iter != gr->intraEdges.end(); iter++){\n                    //This is an edge (src--w-->tgt)\n                    //Add an immutable edge src--w'-->tgt)\n                    // w' = (w,1^T)\n                    sem_elem_tensor_t wt = boost::polymorphic_downcast<SemElemTensor*>((iter->weight).get_ptr());\n                    sem_elem_tensor_t one = boost::polymorphic_downcast<SemElemTensor*>((wt->one()).get_ptr());\n                    wt = tensorSetUpFP(wt,one);\n                    graph->addEdge(nodes[iter->src].intra_nodeno, nodes[iter->tgt].intra_nodeno, wt);\n#if 0\n                    //Also add a mutable edge (s--f-->tgt) from the source vertex s with weight 0 (tensored) and\n                    //functional f = (DetTrans(wt(src)) x w,1^T) (one untensored)\n                    sem_elem_tensor_t zerot = boost::polymorphic_downcast<SemElemTensor*>(sem->zero().get_ptr());\n                    wt = boost::polymorphic_downcast<SemElemTensor*>((iter->weight).get_ptr());\n                    functional_t f = \n                      SemElemFunctional::tensor(\n                          SemElemFunctional::extend(\n                            SemElemFunctional::detensorTranspose(\n                              SemElemFunctional::in(nodes[iter->src].intra_nodeno)),\n                            SemElemFunctional::constant(wt)),\n                          SemElemFunctional::constant(one));\n                    int e = graph->setSource(nodes[iter->tgt].intra_nodeno, zerot, f);\n                    // Back references in the node to edges that depend on it.\n                    graph->addDependentEdge(e, nodes[iter->src].intra_nodeno);                  \n#endif\n                  }\n                  int trash; \n                  // Inter Edges:\n                  for(vector<HyperEdge>::iterator iter = gr->interEdges.begin(); iter != gr->interEdges.end(); ++iter){\n\n                    //Obtain the weight on the call edge\n                    assert(eHandler.exists(iter->src1));                    \n                    sem_elem_tensor_t wtCallRule =\n                      boost::polymorphic_downcast<SemElemTensor*>(eHandler.get_dependency(iter->src1,trash).get_ptr());\n                    assert(trash != -1);\n\n                    // src2 is the external source for a hyperedge\n                    if(nodes[iter->src2].gr != NULL && nodes[iter->src2].gr != graph){\n                      // (4.2.3.1) The entry node belongs to a graph that has a lower scc.\n                      // Treat this case as an intraedge\n\n\n                      //Add an immutable edge src1--w'-->tgt)\n                      // If the graph for src2 has tensoredWeights, then\n                      // w' = (wtCallRule x DetTrans(wt(src2)), 1^T)\n                      // If it has base weights, then\n                      // w' = (wtCallRule x wt(src2), 1^T)\n                      sem_elem_t wtsrc2 = nodes[iter->src2].gr->getWeight(nodes[iter->src2].intra_nodeno);\n                      sem_elem_tensor_t wt = boost::polymorphic_downcast<SemElemTensor*>(wtsrc2.get_ptr());\n                      if(nodes[iter->src2].gr->hasTensoredWeights)\n                        wt = wt->detensorTranspose();\n                      wt = boost::polymorphic_downcast<SemElemTensor*>(wtCallRule->extend(wt.get_ptr()).get_ptr());\n                      sem_elem_tensor_t one = boost::polymorphic_downcast<SemElemTensor*>((wt->one()).get_ptr());                                     \n                      graph->addEdge(nodes[iter->src1].intra_nodeno, nodes[iter->tgt].intra_nodeno,\n                          tensorSetUpFP(wt,one));\n#if 0\n                      //Also add a mutable edge (s--f-->tgt) from the source vertex s with weight 0 (tensored) and\n                      //if graph for src2 has tensored weights, then\n                      //functional f = (DetTrans(wt(src1)) x (Constant(wtCallRule) x DetTrans(wt(src2))), 1^T) (one untensored)\n                      //else\n                      //functional f = (DetTrans(wt(src1)) x (Constant(wtCallRule) x DetTrans(wt(src2))), 1^T) (one untensored)\n                      sem_elem_tensor_t zerot = boost::polymorphic_downcast<SemElemTensor*>(sem->zero().get_ptr());\n                      functional_t f = \n                        SemElemFunctional::tensor(\n                            SemElemFunctional::extend(\n                              SemElemFunctional::detensorTranspose(\n                                SemElemFunctional::in(nodes[iter->src1].intra_nodeno)),\n                              SemElemFunctional::constant(wt)),\n                            SemElemFunctional::constant(one));\n                      int e = graph->setSource(nodes[iter->tgt].intra_nodeno, zerot, f);                    \n                      // Back references in the node to edges that depend on it.\n                      graph->addDependentEdge(e, nodes[iter->src1].intra_nodeno);\n#endif\n                    }else{\n                      // (4.2.3.2) The entry node does not belong to a graph that has a lower scc.\n                      // Note: It must belong to the same scc then\n                      assert(nodes[iter->src2].gr == graph);\n\n                      // Add mutable edge src1--f-->tgt with weight 0 (tensored) and\n                      // f = (Constant(callWt) x DetTrans(wt(src2)), 1^T)\n                      sem_elem_tensor_t zerot = boost::polymorphic_downcast<SemElemTensor*>(sem->zero().get_ptr());\n                      functional_t f = \n                        SemElemFunctional::tensor(\n                            SemElemFunctional::extend(\n                              SemElemFunctional::constant(wtCallRule),\n                              SemElemFunctional::detensorTranspose(\n                                SemElemFunctional::in(nodes[iter->src2].intra_nodeno))),\n                            SemElemFunctional::constant(one));\n                      int e = graph->addEdge(nodes[iter->src1].intra_nodeno, nodes[iter->tgt].intra_nodeno, zerot, true, f);\n                      // Back references in the node to edges that depend on it.\n                      graph->addDependentEdge(e, nodes[iter->src2].intra_nodeno);\n\n                      // Add mutable edge src2--f-->tgt with weight 0 (tensored) and\n                      // f = (1, (DetTrans(wt(src1)) x callWt)^T)\n                      f = \n                        SemElemFunctional::tensor(\n                            SemElemFunctional::constant(one),\n                            SemElemFunctional::transpose(\n                              SemElemFunctional::extend(\n                                SemElemFunctional::detensorTranspose(\n                                  SemElemFunctional::in(nodes[iter->src1].intra_nodeno)),\n                                SemElemFunctional::constant(wtCallRule))));\n                      e = graph->addEdge(nodes[iter->src2].intra_nodeno, nodes[iter->tgt].intra_nodeno, zerot, true, f);\n                      // Back references in the node to edges that depend on it.\n                      graph->addDependentEdge(e, nodes[iter->src1].intra_nodeno);\n\n                      // Add mutable edge s--f-->tgt from source node s with weight 0(tensored) and\n                      // f = (DetTrans(wt(src1)) x callWt x DetTrans(wt(src2)), 1^T)\n                      f =\n                        SemElemFunctional::tensor(\n                            SemElemFunctional::extend(\n                              SemElemFunctional::extend(                                \n                                SemElemFunctional::detensorTranspose(\n                                  SemElemFunctional::in(nodes[iter->src1].intra_nodeno)),\n                                SemElemFunctional::constant(wtCallRule)),\n                              SemElemFunctional::detensorTranspose(\n                                SemElemFunctional::in(nodes[iter->src2].intra_nodeno))),\n                            SemElemFunctional::constant(one));\n                      e = graph->setSource(nodes[iter->tgt].intra_nodeno, zerot, f);\n                      // Back references in the node to edges that depend on it.\n                      graph->addDependentEdge(e, nodes[iter->src1].intra_nodeno);\n                      graph->addDependentEdge(e, nodes[iter->src2].intra_nodeno);\n                    }\n                  }\n\n                  gr_it++;\n                }              \n              }\n              else\n              {\n                //Do Fwpds Magic\n                dag->startSatProcess(sem_old); //non tensored\n                while(gr_it != gr_sorted.end() && (*gr_it)->scc_number == scc_n){\n                  scc_graph_t gr = *gr_it;\n\n                  // (4.1.1)\n                  // Source nodes:\n                  for(vector<int>::iterator iter = gr->nodes.begin(); iter != gr->nodes.end(); ++iter){\n                    int i = *iter;\n                    if(is_source_type(nodes[i].type)) {\n                      //This is a source node. \n                      //Create an immutable edge with weight w\n                      sem_elem_t wt = nodes[i].weight;\n                      graph->setSource(nodes[i].intra_nodeno, wt);\n                    }\n                    // zero all weights (some are set by InterGraph::setSource() )\n                    if(nodes[i].weight.get_ptr() != NULL)\n                      nodes[i].weight = zero;\n                  }\n\n                  // (4.1.2)\n                  // Intra Edges:\n                  for(vector<GraphEdge>::iterator iter = gr->intraEdges.begin(); iter != gr->intraEdges.end(); iter++){\n                    //This is an edge (src--w-->tgt)\n                    //Add an immutable edge src--w-->tgt)\n                    sem_elem_t wt = iter->weight;\n                    graph->addEdge(nodes[iter->src].intra_nodeno, nodes[iter->tgt].intra_nodeno, wt);\n                  }\n                  int trash;\n                  // (4.1.3) \n                  // Inter Edges:\n                  for(vector<HyperEdge>::iterator iter = gr->interEdges.begin(); iter != gr->interEdges.end(); ++iter){\n                    // Obtain the weight on the call edge\n                    assert(eHandler.exists(iter->src1));                    \n                    sem_elem_tensor_t wtCallRule =\n                      boost::polymorphic_downcast<SemElemTensor*>(eHandler.get_dependency(iter->src1,trash).get_ptr());\n                    assert(trash != -1);\n\n                    // src2 is the external source for a hyperedge. This can't be recursive, hence --\n                    assert(nodes[iter->src2].gr != NULL && nodes[iter->src2].gr != graph);\n                    // Treat this case as an intraedge\n\n                    // Add an immutable edge src1--w'-->tgt)\n                    // If the graph for src2 has tensoredWeights, then\n                    // w' = wtCallRule x DetTrans(wt(src2))\n                    // else\n                    // w' = wtCallRule x wt(src2)\n                    sem_elem_t wtsrc2 = nodes[iter->src2].gr->getWeight(nodes[iter->src2].intra_nodeno);\n                    sem_elem_tensor_t wt = boost::polymorphic_downcast<SemElemTensor*>(wtsrc2.get_ptr());\n                    if(nodes[iter->src2].gr->hasTensoredWeights)\n                      wt = wt->detensorTranspose();\n                    wt = boost::polymorphic_downcast<SemElemTensor*>(wtCallRule->extend(wt.get_ptr()).get_ptr());\n                    graph->addEdge(nodes[iter->src1].intra_nodeno, nodes[iter->tgt].intra_nodeno, wt);\n                  }\n                  gr_it++;\n                }              \n              }\n              // (5)\n              // Use Tarjan's path listing algorithm to generate regular expressions for nodes.\n              graph->setupIntraSolution();\n\n#if defined(PPP_DBG) && PPP_DBG >= 1\n              // We have the intra graph ready at this point. \n                // DEBUGGING\n                std::stringstream ss;\n                ss << \"graph\" << scc_n << \".dot\";\n                std::ofstream foo(ss.str().c_str());\n                string dot = graph->toDot();\n                foo << \"digraph {\\n\";\n                foo << dot;\n                foo << \"}\";\n                foo.close();\n              cout << \"GRAPH \" << scc_n << \"\\n\";\n#endif \n              // (6) Now solve the linearized problem by saturating.\n              unsigned numRounds = 0;\n              graph->saturate(numRounds);\n#if defined(PPP_DBG) && PPP_DBG >= 0\n              maxNewtonRounds = numRounds > maxNewtonRounds ? numRounds : maxNewtonRounds;\n              totNewtonRounds += numRounds;\n#endif\n              // The next SCC will use another sat process phase.\n              dag->stopSatProcess();\n            }\n          }\n\n          // (7)\n          // It is time to decide whether the output automaton should have\n          // tensored weights or not.\n          // Currently, we will decide by counting the number of edges in the\n          // output automaton (i.e. the number of IntraGraph nodes that have\n          // tensored/non-tensored weights, and then switching at some\n          // ciritical ratio (decided emprically)\n          int totTensoredNodes=0, totNonTensoredNodes=0;\n          for(std::list<IntraGraph*>::iterator gr_it = linear_gr_list.begin(); gr_it != linear_gr_list.end(); ++gr_it){\n            IntraGraph * graph = *gr_it;\n            if(graph->hasTensoredWeights)\n              totTensoredNodes += graph->nnodes;\n            else\n              totNonTensoredNodes += graph->nnodes;\n          }\n          if(totTensoredNodes == 0 || ((float)totNonTensoredNodes)/((float)totTensoredNodes) > 0.33)\n            isOutputAutomatonTensored = true;\n          //XXX:HACK\n          isOutputAutomatonTensored = true; //override\n          cerr << \"Warning: overriding to OutputAutomatonTensored\\n\";\n\n          if(isOutputAutomatonTensored){\n            // Before saying you're done, tensor the weights lying around as call rule weights so that\n            // path summary will see tensored weights.\n            eHandler.tensorAllWeights();\n          }\n\n#if defined(PPP_DBG) && PPP_DBG >= 0\n          dag->sanitizeRootsAcrossSatProcesses();\n          totCombines = dag->countTotalCombines();\n          totExtends = dag->countTotalExtends();\n          totStars = dag->countTotalStars();\n\n          cout << \"Maximum number of Newton rounds: \" << maxNewtonRounds << endl;\n          cout << \"Total number of Newton rounds: \" << totNewtonRounds << endl;\n          cout << \"Total number of combines: \" << totCombines << endl;\n          cout << \"Total number of Extends: \" << totExtends << endl;\n          cout << \"Total number of Stars: \" << totStars << endl;\n\n          dag->printStructureInformation();\n#endif\n          max_scc_computed = max_scc_required;\n          dag->executingPoststar(!running_prestar);\n\n#if defined(PPP_DBG) && PPP_DBG >= 2\n            std::stringstream ss;\n            ss << \"digraph{\\n\";\n            for(i=0; i<n; i++){\n              ss << \"node\" << i << \" [label=\\\"[intergraphno: \" << i << \"](\" <<\n                key2str(nodes[i].trans.src) <<\n                \", \" << key2str(nodes[i].trans.stack) <<\n                \", \" << key2str(nodes[i].trans.tgt) << \")\\\\n\";\n              sem_elem_t wt =nodes[i].gr->get_weight(nodes[i].intra_nodeno); \n              if(wt == NULL)\n                pp_weight(ss, wt);\n              else{\n                sem_elem_tensor_t wtt =\n                  boost::polymorphic_downcast<SemElemTensor*>(wt.get_ptr());\n                pp_weight(ss, wtt->detensorTranspose());\n              }\n              ss<< \"\\\"];\\n\";\n            }\n            for(vector<GraphEdge>::iterator it = intra_edges.begin(); it != intra_edges.end(); ++it){\n              ss << \"node\" << it->src << \" -> node\" << it->tgt \n                << \" [label=\\\"\";\n              pp_weight(ss, it->weight);\n              ss  << \"\\\"];\\n\";\n            }\n            for(vector<HyperEdge>::iterator it2 = inter_edges.begin(); it2 != inter_edges.end(); ++it2){\n              ss << \"node\" << it2->src1 << \" -> node\" << it2->tgt \n                << \" [label=\\\"\";\n              pp_weight(ss, it2->weight);\n              ss << \"\\\" color=brown];\\n\";\n              if(it2->mf.get_ptr()){ \n                ss << \"node\" << it2->src2 << \" -> node\" << it2->tgt \n                  << \" [color=red, label=\\\"Has Merge Fn\\\"];\\n\";\n              }else{\n                ss << \"node\" << it2->src2 << \" -> node\" << it2->tgt \n                  << \" [color=red, label=\\\"No Merge Fn\\\"];\\n\";\n              }\n            }\n            ss << \"}\\n\";\n            ofstream foo(\"tdg.dot\");\n            foo << ss.str();\n            foo.close();\n#endif \n        }\n\n        // If an argument is passed in then only weights on those transitions will be available\n        // I can fix this (i.e., weights for others will be available on demand), but not right now.\n        void InterGraph::setupInterSolution(std::list<Transition> *wt_required) {\n          dag->startSatProcess(sem);\n          // First, find the IntraGraphs\n          int n = nodes.size();\n          int i;\n          unsigned int max_scc_required;\n          intra_graph_uf = new UnionFind(n);\n\n          vector<GraphEdge>::iterator it;\n          vector<HyperEdge>::iterator it2;\n          std::list<IntraGraph *>::iterator gr_it;\n          multiset<tup > worklist;\n\n\n          for(it = intra_edges.begin(); it != intra_edges.end(); it++) {\n            intra_graph_uf->takeUnion((*it).src,(*it).tgt);\n          }\n          for(it2 = inter_edges.begin(); it2 != inter_edges.end(); it2++) {\n            intra_graph_uf->takeUnion((*it2).src1,(*it2).tgt);\n          }\n          IntraGraph::SharedMemBuffer * memBuf = NULL;\n#ifdef INTRAGRAPH_SHARED_MEMORY\n          // Before creating IntraGraphs, create a CommonBuffer, if needed.\n          int max_size = 0;\n          for(gr_it = gr_list.begin(); gr_it != gr_list.end(); gr_it++) {\n            max_size = (max_size > (*gr_it)->getSize()) ? max_size : (*gr_it)->getSize();\n          }\n          memBuf  = new IntraGraph::SharedMemBuffer(max_size);\n#endif\n\n          for(i = 0; i < n;i++) {\n            int j = intra_graph_uf->find(i);\n            if(nodes[j].gr == NULL) {\n              nodes[j].gr = new IntraGraph(dag, running_prestar,sem, memBuf);\n              gr_list.push_back(nodes[j].gr);\n            }\n            nodes[i].gr = nodes[j].gr;\n            nodes[i].intra_nodeno = nodes[i].gr->makeNode(nodes[i].trans);\n            if(is_source_type(nodes[i].type)) {\n              nodes[i].gr->setSource(nodes[i].intra_nodeno, nodes[i].weight);\n            }\n            // zero all weights (some are set by setSource() )\n            if(nodes[i].weight.get_ptr() != NULL)\n              nodes[i].weight = nodes[i].weight->zero();\n          }\n\n          // Now fill up the IntraGraphs\n          for(it = intra_edges.begin(); it != intra_edges.end(); it++) {\n            int s = (*it).src;\n            int t = (*it).tgt;\n            nodes[s].gr->addEdge(nodes[s].intra_nodeno, nodes[t].intra_nodeno, (*it).weight);\n          }\n\n          for(it2 = inter_edges.begin(); it2 != inter_edges.end(); it2++) {\n            IntraGraph *gr = nodes[(*it2).tgt].gr;\n            gr->addEdge(nodes[(*it2).src1].intra_nodeno, nodes[(*it2).tgt].intra_nodeno, sem->zero(), true);\n            IntraGraph *gr2 = nodes[(*it2).src2].gr;\n            gr2->setOutNode(nodes[(*it2).src2].intra_nodeno, (*it2).src2);\n          }\n\n          // For SWPDS\n          vector<call_edge_t>::iterator it3;\n          for(it3 = call_edges.begin(); it3 != call_edges.end(); it3++) {\n            IntraGraph *gr1 = nodes[(*it3).first].gr;\n            IntraGraph *gr2 = nodes[(*it3).second].gr;\n            gr1->addCallEdge(gr2);\n          }\n\n          // Setup Worklist\n#if defined(PPP_DBG) && PPP_DBG >= 0\n          vector<reg_exp_t> outNodeRegExps;\n#endif\n          for(gr_it = gr_list.begin(); gr_it != gr_list.end(); gr_it++) {\n            (*gr_it)->setupIntraSolution(false);\n#if defined(PPP_DBG) && PPP_DBG >= 0\n            for(list<int>::const_iterator cit = (*gr_it)->out_nodes_intra->begin(); cit != (*gr_it)->out_nodes_intra->end(); ++cit)\n              outNodeRegExps.push_back((*gr_it)->nodes[*cit].regexp);\n#endif\n          }\n\n#if defined(PPP_DBG) && PPP_DBG >= 0\n          long totNodes = 0, totNotComputed = 0;\n          totNodes = dag->countTotalCombines() +\n            dag->countTotalExtends() +\n            dag->countTotalStars();\n          totNotComputed = dag->countExcept(outNodeRegExps); \n          cout << \"Total number of combines: \" << dag->countTotalCombines() << endl;\n          cout << \"Total number of Extends: \" << dag->countTotalExtends() << endl;\n          cout << \"Total number of Stars: \" << dag->countTotalStars() << endl;\n          cout << \"#nodes definitely not evaluated during saturation: \" << dag->countExcept(outNodeRegExps) << endl;\n          cout << \"%Nodes never computed > \" << 100 * (double)(((double)totNotComputed)/ (double)totNodes) << endl;;\n#endif\n          // Do SCC decomposition of IntraGraphs\n          std::list<IntraGraph *> gr_sorted;\n          unsigned components = SCC(gr_list, gr_sorted);\n          STAT(stats.ncomponents = components);\n\n          int numSteps = 0;\n          // Saturate\n          if(wt_required == NULL) {\n            max_scc_required = components;\n          } else {\n            max_scc_required = 0;\n            std::list<Transition>::iterator trans_it;\n            for(trans_it = wt_required->begin(); trans_it != wt_required->end(); trans_it++) {\n              int nno = nodeno(*trans_it);\n              max_scc_required = (max_scc_required >= nodes[nno].gr->scc_number) ? max_scc_required : nodes[nno].gr->scc_number;\n            }\n          }\n          gr_it = gr_sorted.begin();\n          for(unsigned scc_n = 1; scc_n <= max_scc_required; scc_n++) {\n            bfsIntra(*gr_it, scc_n);\n            setup_worklist(gr_sorted, gr_it, scc_n, worklist);\n            numSteps += saturate(worklist,scc_n);\n          }\n#if defined(PPP_DBG) && PPP_DBG >= 0\n          cout << \"Total number of steps: \" << numSteps << endl;\n#endif\n        max_scc_computed = max_scc_required;\n\n        //DEBUGGING\n#if defined(PPP_DBG) && PPP_DBG >= 1\n        {\n          stringstream ss;\n          ss << \"kleene_regexp.dot\";\n          string filename = ss.str();\n          fstream foo;\n          foo.open(filename.c_str(), fstream::out);\n          const reg_exp_hash_t& roots = dag->getRoots();\n          foo << \"digraph {\\n\";\n          std::set<long> seen;\n          for(reg_exp_hash_t::const_iterator iter = roots.begin();\n              iter != roots.end();\n              ++iter){\n            (iter->second)->toDot(foo, seen, true, true);\n          }\n          foo << \"}\\n\";\n          foo.close();\n        }\n        int graphnum = 0;\n        for(gr_it = gr_list.begin(); gr_it != gr_list.end(); ++gr_it)\n        {\n          ++graphnum;\n          stringstream ss;\n          ss << \"kleene_graph_\" << graphnum << \".dot\";\n          string filename = ss.str();\n          fstream foo;\n          foo.open(filename.c_str(), fstream::out);\n          foo << \"digraph{\\n\";\n          foo << (*gr_it)->toDot();\n          foo << \"}\";\n          foo.close();\n        }\n#endif\n        dag->stopSatProcess();\n        dag->executingPoststar(!running_prestar);\n#ifdef INTRAGRAPH_SHARED_MEMORY\n        delete memBuf;\n#endif\n    }\n\n    std::ostream &InterGraph::print_stats(std::ostream &out) {\n      InterGraphStats total_stats = stats;\n      int n = nodes.size();\n      int i;      \n      set<RegExp *> reg_equations;\n      int ned = 0;\n      for(i = 0; i < n; i++) {\n        if(intra_graph_uf->find(i) == i) {\n          std::list<int>::iterator tbeg = nodes[i].gr->getOutTransitions()->begin();\n          std::list<int>::iterator tend = nodes[i].gr->getOutTransitions()->end();\n          for(; tbeg != tend; tbeg++) {\n            int onode = nodes[i].intra_nodeno;\n            reg_equations.insert(nodes[i].gr->nodes[onode].regexp.get_ptr());\n          }\n          total_stats.ngraphs ++;\n          IntraGraphStats st = nodes[i].gr->get_stats(); \n          total_stats.ncombine += st.ncombine;\n          total_stats.nextend += st.nextend;\n          total_stats.nstar += st.nstar;\n          total_stats.nupdatable += st.nupdatable * st.nupdatable;\n          total_stats.ncutset += st.ncutset * st.ncutset * st.ncutset;\n          total_stats.nget_weight += st.nget_weight;\n          total_stats.ndom_sequence += st.ndom_sequence;\n          total_stats.ndom_components += st.ndom_components;\n          total_stats.ndom_componentsize += (st.ndom_componentsize * st.ndom_componentsize);\n          total_stats.ndom_componentcutset += st.ndom_componentcutset;\n          ned += st.nedges;\n        }\n      }\n      int changestat = dag->out_node_height(reg_equations);\n      total_stats.nhyperedges = inter_edges.size();\n      total_stats.nedges = intra_edges.size();\n      total_stats.nnodes = nodes.size();\n\n      RegExpStats rst = dag->get_stats();\n      total_stats.ncombine += rst.ncombine;\n      total_stats.nextend += rst.nextend;\n      total_stats.nstar += rst.nstar;\n      total_stats.ngraphs = (total_stats.ngraphs == 0) ? 1 : total_stats.ngraphs;\n      rst.out_nodes = (rst.out_nodes == 0) ? 1 : rst.out_nodes;\n      out << \"----------------------------------\\n\";\n      out << \"          FWPDS Stats             \\n\";\n      out << \"----------------------------------\\n\";\n      out << \"InterGraph nodes : \" << total_stats.nnodes << \"\\n\";\n      out << \"InterGraph edges : \" << total_stats.nedges << \"\\n\";\n      out << \"InterGraph hyperedges : \" << total_stats.nhyperedges << \"\\n\";\n      out << \"InterGraph iterations : \" << total_stats.niter << \"\\n\";\n      out << \"InterGraph get_weight : \" << total_stats.nget_weight << \"\\n\";\n      out << \"IntraGraphs : \" << total_stats.ngraphs << \"\\n\";\n      out << \"IntraGraph SCC : \" << total_stats.ncomponents << \"\\n\";\n      out << \"IntraGraph SCC Computed: \" << max_scc_computed << \"\\n\";\n      out << \"Avg. IntraGraph nodes : \" << (total_stats.nnodes / total_stats.ngraphs) << \"\\n\";\n      out << \"Avg. IntraGraph edges : \" << (ned / total_stats.ngraphs) << \"\\n\";\n      out << \"Avg. IntraGraph cutset : \" << (pow(total_stats.ncutset/total_stats.ngraphs,0.33)) << \"\\n\";\n      out << \"Avg. IntraGraph updatable : \" << (int)(pow((double)total_stats.nupdatable/total_stats.ngraphs,0.5)) << \"\\n\";\n      out << \"Avg. IntraGraph dom-sequence length : \" << (total_stats.ndom_sequence / total_stats.ngraphs) << \"\\n\";\n      out << \"Avg. IntraGraph dom-component size : \" << (int)pow((double)total_stats.ndom_componentsize / (total_stats.ndom_components+1),0.5) << \"\\n\";\n      out << \"Avg. IntraGraph dom-component cuset : \" << setprecision(2) << (double)total_stats.ndom_componentcutset / (total_stats.ndom_components+1) << \"\\n\";\n      out << \"Semiring Combine : \" << total_stats.ncombine << \"\\n\";\n      out << \"Semiring Extend : \" << total_stats.nextend << \"\\n\";\n      out << \"Semiring Star : \" << total_stats.nstar << \"\\n\";\n      out << \"RegExp HashMap hits : \" << rst.hashmap_hits << \"\\n\";\n      out << \"RegExp HashMap misses : \" << rst.hashmap_misses << \"\\n\";\n      out << \"OutNode Height : \" << setprecision(4) << (rst.height / rst.out_nodes) << \"\\n\"; \n      out << \"OutNode Loop ND : \" << setprecision(4) << (rst.lnd / rst.out_nodes) << \"\\n\";\n      out << \"Change Stat : \" << changestat << \"\\n\";\n      out << \"\\n\";\n      return out;\n    }\n\n    // New Saturation Procedure -- minimize calls to get_weight\n    int InterGraph::saturate(multiset<tup> &worklist, unsigned scc_n) {\n      int numSteps = 0;\n      sem_elem_t weight;\n      std::list<int> *moutnodes;\n\n      while(!worklist.empty()) {\n        // Get an outnode whose weight is to be propagated\n        multiset<tup>::iterator wit = worklist.begin();\n        int onode = (*wit).second;\n        worklist.erase(wit);\n        //int onode = worklist.front();\n        //worklist.pop_front();\n\n        numSteps++;\n        weight = nodes[onode].gr->get_weight(nodes[onode].intra_nodeno);\n        if(nodes[onode].weight.get_ptr() != NULL && nodes[onode].weight->equal(weight))\n          continue;\n        nodes[onode].weight = weight;\n\n        STAT(stats.niter++);\n\n        FWPDSDBGS(\n            cout << \"Popped \";\n            IntraGraph::print_trans(nodes[onode].trans,cout) << \"with weight \";\n            weight->print(cout) << \"\\n\";\n            );\n\n        // Go through all its targets and modify their weights\n        std::list<int>::iterator beg = nodes[onode].out_hyper_edges.begin();\n        std::list<int>::iterator end = nodes[onode].out_hyper_edges.end();\n        for(; beg != end; beg++) {\n          int inode = inter_edges[*beg].tgt;\n          int onode1 = inter_edges[*beg].src1;\n          sem_elem_t uw;\n          if(running_ewpds && inter_edges[*beg].mf.get_ptr()) {\n            uw = inter_edges[*beg].mf->apply_f(sem->one(), weight);\n            FWPDSDBGS(\n                cout << \"Apply merge function \";\n                inter_edges[*beg].mf->print(cout) << \" to \";\n                weight->print(cout) << \"\\n\";\n                uw->print(cout << \"Got \") << \"\\n\";\n                );\n          } else {\n            uw = inter_edges[*beg].weight->extend(weight);\n          }\n          STAT(stats.nextend++);\n          nodes[inode].gr->updateEdgeWeight(nodes[onode1].intra_nodeno, nodes[inode].intra_nodeno, uw);\n        }\n        // Go through all targets again and insert them into the workist without\n        // seeing if they actually got modified or not\n        beg = nodes[onode].out_hyper_edges.begin();\n        for(; beg != end; beg++) {\n          int inode = inter_edges[*beg].tgt;\n          IntraGraph *gr = nodes[inode].gr;\n          if(gr->scc_number != scc_n) {\n            assert(gr->scc_number > scc_n);\n            continue;\n          }\n          moutnodes = gr->getOutTransitions();\n          std::list<int>::iterator mbeg = moutnodes->begin();\n          std::list<int>::iterator mend = moutnodes->end();\n          for(; mbeg != mend; mbeg++) {\n            int mnode = (*mbeg);\n            worklist.insert(tup(gr->bfs_number, mnode));\n          }\n        }\n      }\n      //DEBUGGING\n      //cout << \"Kleene saturation # Steps: \" << numSteps << endl;\n      return numSteps;\n\n    }\n\n    // Must be called after saturation\n    sem_elem_t InterGraph::get_call_weight(Transition t) {\n      unsigned orig_size = nodes.size();\n      unsigned n = nodeno(t);\n      assert(orig_size == nodes.size()); // Transition t must not be a new one\n\n      if(newtonGr)\n        return newtonGr->get_weight(nodes[n].intra_nodeno);\n      else\n        return nodes[n].gr->get_weight(nodes[n].intra_nodeno);\n    }\n\n    sem_elem_t InterGraph::get_weight(Transition t){\n      unsigned orig_size = nodes.size();\n      unsigned n = nodeno(t);\n      assert(orig_size == nodes.size()); // Transition t must not be a new one\n      return get_weight(n);\n    }\n\n    // Changed for Newton Solver.  \n    // When the output automaton is tensored (@see comment above setupNewtonSolution), make sure\n    // that the returned weight is also tensored.  \n    // When the output automaton is non-tensored, make sure that the returned weight is\n    // non-tensored. \n    sem_elem_t InterGraph::get_weight(unsigned n) \n    {\n      // check eHandler\n      if(eHandler.exists(n)) {\n        // This must be a return transition\n        int nc;\n        sem_elem_t wtCallRule = eHandler.get_dependency(n, nc);\n        sem_elem_t wt;\n        if(nc != -1) {\n          wt = nodes[nc].gr->get_weight(nodes[nc].intra_nodeno);\n          sem_elem_tensor_t twt = dynamic_cast<SemElemTensor*>(wt.get_ptr());\n          if(twt != NULL){\n            if(isOutputAutomatonTensored && ! nodes[nc].gr->hasTensoredWeights)\n              wt = tensorSetUpFP(twt,boost::polymorphic_downcast<SemElemTensor*>(twt->one().get_ptr()));\n            if(! isOutputAutomatonTensored && nodes[nc].gr->hasTensoredWeights)\n              wt = twt->detensorTranspose();\n          }\n        } else {\n          // ESource\n          wt = wtCallRule->one();\n        }\n        return wt->extend(wtCallRule.get_ptr());\n      }\n      sem_elem_t wt = nodes[n].gr->get_weight(nodes[n].intra_nodeno);\n      sem_elem_tensor_t twt = dynamic_cast<SemElemTensor*>(wt.get_ptr());\n      if(twt != NULL){\n        if(isOutputAutomatonTensored && ! nodes[n].gr->hasTensoredWeights)\n          wt = tensorSetUpFP(twt,boost::polymorphic_downcast<SemElemTensor*>(twt->one().get_ptr()));\n        if(! isOutputAutomatonTensored && nodes[n].gr->hasTensoredWeights)\n          wt = twt->detensorTranspose();\n      }\n      return wt;\n    }\n\n    void InterGraph::update_all_weights() {\n      unsigned int i;\n      for(i=0;i<nodes.size();i++) {\n        sem_elem_t w;\n        if(newtonGr)\n          w = newtonGr->get_weight(nodes[i].intra_nodeno);\n        else\n          w = nodes[i].gr->get_weight(nodes[i].intra_nodeno);\n        nodes[i].weight = w;\n      }\n    }\n\n    inline int get_number(map<int,int> &intra_node_map, int src, IntraGraph *ca) {\n      std::map<int,int>::iterator it = intra_node_map.find(src);\n      if(it != intra_node_map.end()) {\n        return it->second;\n      }\n      int s = ca->makeNode();\n      intra_node_map[src] = s;\n      return s;\n    }\n\n    bool InterGraph::path_summary(int state, int stack, int accept, WT_CORRECT correct, WT_CHECK op) {\n      // Build a hashmap: transition.src -> transitions\n      typedef wali::HashMap<int, std::list<int> > trans_map_t;\n      std::map<int, int> intra_node_map; // transition.src -> intra node number\n\n      trans_map_t trans_map;\n      set<int> states_visited;\n      std::list<int> worklist;\n      unsigned int i;\n      IntraGraph *ca = new IntraGraph(dag, true, sem); // running_prestar = true because extend goes backward\n      //Transition initial_st(state, 0, 0);\n\n      ca->setSource(get_number(intra_node_map,state,ca), sem->one());\n      for(i=0;i<nodes.size();i++) {\n        trans_map_t::iterator it = trans_map.find(nodes[i].trans.src);\n        if(it == trans_map.end()) {\n          std::list<int> temp;\n          temp.push_back(i);\n          trans_map.insert(nodes[i].trans.src, temp);\n        } else {\n          it->second.push_back(i);\n        }\n        // add initial (state, stack, _) transitions\n        if(((int)nodes[i].trans.src) == state &&\n           ((int)nodes[i].trans.stack) == stack)\n        {\n          Transition t1(state,0,0);\n          Transition t2(nodes[i].trans.tgt,0,0);\n          if(newtonGr)\n            ca->addEdge(get_number(intra_node_map,state,ca), get_number(intra_node_map, nodes[i].trans.tgt,ca), \n                correct(newtonGr->get_weight(nodes[i].intra_nodeno).get_ptr()));\n          else\n            ca->addEdge(get_number(intra_node_map,state,ca), get_number(intra_node_map, nodes[i].trans.tgt,ca), \n                correct(nodes[i].gr->get_weight(nodes[i].intra_nodeno).get_ptr()));\n          worklist.push_back(nodes[i].trans.tgt);\n        }\n      }\n      states_visited.insert(state);\n      while(!worklist.empty()) {\n        int st = worklist.front();\n        worklist.pop_front();\n        if(states_visited.find(st) != states_visited.end()) \n          continue;\n        states_visited.insert(st);\n        trans_map_t::iterator trans_it = trans_map.find(st);\n        if(trans_it == trans_map.end())\n          continue;\n        std::list<int> &trans = trans_it->second;\n        std::list<int>::iterator it;\n        for(it = trans.begin(); it != trans.end(); it++) {\n          i = *it;\n          int t1 = get_number(intra_node_map,nodes[i].trans.src,ca);\n          int t2 = get_number(intra_node_map,nodes[i].trans.tgt,ca);\n          if(newtonGr)\n            ca->addEdge(t1, t2, correct(newtonGr->get_weight(nodes[i].intra_nodeno).get_ptr()));\n          else\n            ca->addEdge(t1, t2, correct(nodes[i].gr->get_weight(nodes[i].intra_nodeno).get_ptr()));\n          if(states_visited.find(nodes[i].trans.tgt) == states_visited.end()) {\n            worklist.push_back(nodes[i].trans.tgt);\n          }\n        }\n      }\n      int final_st = get_number(intra_node_map,accept, ca);\n      ca->setOutNode(final_st, 1); // second argument is not required\n      ca->setupIntraSolution(false);\n      bool r = op(ca->get_weight(final_st).get_ptr());\n      delete ca;\n      return r;\n    }\n\n} // namespace graph\n\n} // namespace wali\n\n", "meta": {"hexsha": "aa41c61fdcf06aa7c72fbb3d1c12267944f68a81", "size": 70097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/wali/lib/graph/InterGraph.cpp", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "Source/wali/lib/graph/InterGraph.cpp", "max_issues_repo_name": "jusito/WALi-OpenNWA", "max_issues_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "Source/wali/lib/graph/InterGraph.cpp", "max_forks_repo_name": "jusito/WALi-OpenNWA", "max_forks_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 43.4037151703, "max_line_length": 166, "alphanum_fraction": 0.5236458051, "num_tokens": 17025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "/**\n * @file ra_model_impl.hpp\n * @author Ryan Curtin\n *\n * Implementation of the RAModel class.\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_RANN_RA_MODEL_IMPL_HPP\n#define MLPACK_METHODS_RANN_RA_MODEL_IMPL_HPP\n\n// In case it hasn't been included yet.\n#include \"ra_model.hpp\"\n#include <mlpack/core/math/random_basis.hpp>\n#include <boost/serialization/variant.hpp>\n\nnamespace mlpack {\nnamespace neighbor {\n\n//! Monochromatic search for the given RAType instance.\ntemplate<typename RAType>\nvoid MonoSearchVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->Search(k, neighbors, distances);\n  throw std::runtime_error(\"no rank-approximate model initialized\");\n}\n\n//! Save the parameters for the rank-approximate search.\ntemplate<typename SortPolicy>\nBiSearchVisitor<SortPolicy>::BiSearchVisitor(const arma::mat& querySet,\n                                 const size_t k,\n                                 arma::Mat<size_t>& neighbors,\n                                 arma::mat& distances,\n                                 const size_t leafSize) :\n    querySet(querySet),\n    k(k),\n    neighbors(neighbors),\n    distances(distances),\n    leafSize(leafSize)\n{};\n\n//! Default Bichromatic search on the given RAType instance.\ntemplate<typename SortPolicy>\ntemplate<template<typename TreeMetricType,\n                  typename TreeStatType,\n                  typename TreeMatType> class TreeType>\nvoid BiSearchVisitor<SortPolicy>::operator()(RATypeT<TreeType>* ra) const\n{\n  if (ra)\n    return ra->Search(querySet, k, neighbors, distances);\n  throw std::runtime_error(\"no rank-approximate model initialized\");\n}\n\n//! Bichromatic search on the given RAType specialized for KDTrees.\ntemplate<typename SortPolicy>\nvoid BiSearchVisitor<SortPolicy>::operator()(RATypeT<tree::KDTree>* ra) const\n{\n  if (ra)\n    return SearchLeaf(ra);\n  throw std::runtime_error(\"no rank-approximate search model initialized\");\n}\n\n//! Bichromatic search on the given RAType specialized for Octrees.\ntemplate<typename SortPolicy>\nvoid BiSearchVisitor<SortPolicy>::operator()(RATypeT<tree::Octree>* ra) const\n{\n  if (ra)\n    return SearchLeaf(ra);\n  throw std::runtime_error(\"no rank-approximate search model initialized\");\n}\n\n//! Bichromatic search on the given RAType considering the leafSize.\ntemplate<typename SortPolicy>\ntemplate<typename RAType>\nvoid BiSearchVisitor<SortPolicy>::SearchLeaf(RAType* ra) const\n{\n  if (!ra->Naive() && !ra->SingleMode())\n  {\n    // Build a second tree and search\n    Timer::Start(\"tree_building\");\n    Log::Info << \"Building query tree....\"<< std::endl;\n    std::vector<size_t> oldFromNewQueries;\n    typename RAType::Tree queryTree(std::move(querySet), oldFromNewQueries,\n        leafSize);\n    Log::Info << \"Tree Built.\" << std::endl;\n    Timer::Stop(\"tree_building\");\n\n    arma::Mat<size_t> neighborsOut;\n    arma::mat distancesOut;\n    ra->Search(&queryTree, k, neighborsOut, distancesOut);\n\n    // Unmap the query points.\n    distances.set_size(distancesOut.n_rows, distancesOut.n_cols);\n    neighbors.set_size(neighborsOut.n_rows, neighborsOut.n_cols);\n    for (size_t i = 0; i < neighborsOut.n_cols; ++i)\n    {\n      neighbors.col(oldFromNewQueries[i]) = neighborsOut.col(i);\n      distances.col(oldFromNewQueries[i]) = distancesOut.col(i);\n    }\n  }\n  else\n  {\n    // Search without building a second tree.\n    ra->Search(querySet, k, neighbors, distances);\n  }\n}\n\n//! Save parameters for the Train.\ntemplate<typename SortPolicy>\nTrainVisitor<SortPolicy>::TrainVisitor(arma::mat&& referenceSet,\n                                       const size_t leafSize) :\n    referenceSet(std::move(referenceSet)),\n    leafSize(leafSize)\n{};\n\n//! Default Train on the given RAType instance.\ntemplate<typename SortPolicy>\ntemplate<template<typename TreeMetricType,\n                  typename TreeStatType,\n                  typename TreeMatType> class TreeType>\nvoid TrainVisitor<SortPolicy>::operator()(RATypeT<TreeType>* ra) const\n{\n  if (ra)\n    return ra->Train(std::move(referenceSet));\n  throw std::runtime_error(\"no rank-approximate search model initialized\");\n}\n\n//! Train on the given RAType specialized for KDTrees.\ntemplate<typename SortPolicy>\nvoid TrainVisitor<SortPolicy>::operator()(RATypeT<tree::KDTree>* ra) const\n{\n  if (ra)\n    return TrainLeaf(ra);\n  throw std::runtime_error(\"no rank-approximate search model initialized\");\n}\n\n//! Train on the given RAType specialized for Octrees.\ntemplate<typename SortPolicy>\nvoid TrainVisitor<SortPolicy>::operator()(RATypeT<tree::Octree>* ra) const\n{\n  if (ra)\n    return TrainLeaf(ra);\n  throw std::runtime_error(\"no rank-approximate search model is initialized\");\n}\n\n//! Train on the given RAType considering the leafSize.\ntemplate<typename SortPolicy>\ntemplate<typename RAType>\nvoid TrainVisitor<SortPolicy>::TrainLeaf(RAType* ra) const\n{\n  // Build tree, if necessary\n  if (ra->Naive())\n  {\n    ra->Train(std::move(referenceSet));\n  }\n  else\n  {\n    std::vector<size_t> oldFromNewReferences;\n    typename RAType::Tree* tree =\n        new typename RAType::Tree(std::move(referenceSet), oldFromNewReferences,\n        leafSize);\n    ra->Train(tree);\n\n    // Give the model ownership of the tree and the mappings.\n    ra->treeOwner = true;\n    ra->oldFromNewReferences = std::move(oldFromNewReferences);\n  }\n}\n\n//! Exposes the SingleSampleLimit() method of the given RAType.\ntemplate<typename RAType>\nsize_t& SingleSampleLimitVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->SingleSampleLimit();\n  throw std::runtime_error(\"no rank-approximate search model is initialized\");\n}\n\n//! Exposes the FirstLeafExact() method of the given RAType.\ntemplate<typename RAType>\nbool& FirstLeafExactVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->FirstLeafExact();\n  throw std::runtime_error(\"no rank-approximate search model is initialized\");\n}\n\n//! Exposes the SampleAtLeaves() method of the given RAType.\ntemplate<typename RAType>\nbool& SampleAtLeavesVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->SampleAtLeaves();\n  throw std::runtime_error(\"no rank-approximate search model is initialized\");\n}\n\n//! Exposes the Alpha() method of the given RAType instance.\ntemplate<typename RAType>\ndouble& AlphaVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->Alpha();\n  throw std::runtime_error(\"no rank-approximate model is initialized\");\n}\n\n//! Exposes the Tau() method of the given RAType instance.\ntemplate<typename RAType>\ndouble& TauVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->Tau();\n  throw std::runtime_error(\"no rank-approximate model is initialized\");\n}\n\n//! Exposes the SingleMode() method of the given RAType.\ntemplate<typename RAType>\nbool& SingleModeVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->SingleMode();\n  throw std::runtime_error(\"no rank-approximate model is intialized\");\n}\n\n//! Exposes the referenceSet of the given RAType.\ntemplate<typename RAType>\nconst arma::mat& ReferenceSetVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->ReferenceSet();\n  throw std::runtime_error(\"no rank-approximate model is intialized\");\n}\n\n//! Exposes the Naive() method of the given RAType instance.\ntemplate<typename RAType>\nbool& NaiveVisitor::operator()(RAType* ra) const\n{\n  if (ra)\n    return ra->Naive();\n  throw std::runtime_error(\"no rank-approximate search model is intialized\");\n}\n\n//! For cleaning memory\ntemplate<typename RSType>\nvoid DeleteVisitor::operator()(RSType* rs) const\n{\n  if (rs)\n    delete rs;\n}\n\ntemplate<typename SortPolicy>\nRAModel<SortPolicy>::RAModel(const TreeTypes treeType, const bool randomBasis) :\n    treeType(treeType),\n    leafSize(20),\n    randomBasis(randomBasis)\n{\n  // Nothing to do.\n}\n\n// Copy constructor.\ntemplate<typename SortPolicy>\nRAModel<SortPolicy>::RAModel(const RAModel& other) :\n    treeType(other.treeType),\n    leafSize(other.leafSize),\n    randomBasis(other.randomBasis),\n    q(other.q),\n    raSearch(other.raSearch)\n{\n  // Nothing to do.\n}\n\n// Move constructor.\ntemplate<typename SortPolicy>\nRAModel<SortPolicy>::RAModel(RAModel&& other) :\n    treeType(other.treeType),\n    leafSize(other.leafSize),\n    randomBasis(other.randomBasis),\n    q(std::move(other.q)),\n    raSearch(std::move(other.raSearch))\n{\n  // Clear other model.\n  other.treeType = TreeTypes::KD_TREE;\n  other.leafSize = 20;\n  other.randomBasis = false;\n  other.raSearch = decltype(other.raSearch)();\n}\n\n// Copy operator.\ntemplate<typename SortPolicy>\nRAModel<SortPolicy>& RAModel<SortPolicy>::operator=(const RAModel& other)\n{\n  // Clear current model.\n  boost::apply_visitor(DeleteVisitor(), raSearch);\n\n  treeType = other.treeType;\n  leafSize = other.leafSize;\n  randomBasis = other.randomBasis;\n  q = other.q;\n  raSearch = other.raSearch;\n\n  return *this;\n}\n\ntemplate<typename SortPolicy>\nRAModel<SortPolicy>& RAModel<SortPolicy>::operator=(RAModel&& other)\n{\n  boost::apply_visitor(DeleteVisitor(), raSearch);\n\n  treeType = other.treeType;\n  leafSize = other.leafSize;\n  randomBasis = other.randomBasis;\n  q = std::move(other.q);\n  raSearch = std::move(other.raSearch);\n\n  // Reset other model.\n  other.treeType = TreeTypes::KD_TREE;\n  other.leafSize = 20;\n  other.randomBasis = false;\n  other.raSearch = decltype(other.raSearch)();\n\n  return *this;\n}\n\n// Clean memory, if necessary\ntemplate<typename SortPolicy>\nRAModel<SortPolicy>::~RAModel()\n{\n  boost::apply_visitor(DeleteVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\ntemplate<typename Archive>\nvoid RAModel<SortPolicy>::serialize(Archive& ar,\n                                    const unsigned int /* version */)\n{\n  ar & BOOST_SERIALIZATION_NVP(treeType);\n  ar & BOOST_SERIALIZATION_NVP(randomBasis);\n  ar & BOOST_SERIALIZATION_NVP(q);\n\n  // This should never happen, but just in case, be clean with memory.\n  if (Archive::is_loading::value)\n  {\n    boost::apply_visitor(DeleteVisitor(), raSearch);\n  }\n\n  // We only need to serialize one of the kRANN objects.\n  ar & BOOST_SERIALIZATION_NVP(raSearch);\n}\n\ntemplate<typename SortPolicy>\nconst arma::mat& RAModel<SortPolicy>::Dataset() const\n{\n  return boost::apply_visitor(ReferenceSetVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nbool RAModel<SortPolicy>::Naive() const\n{\n  return boost::apply_visitor(NaiveVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nbool& RAModel<SortPolicy>::Naive()\n{\n  return boost::apply_visitor(NaiveVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nbool RAModel<SortPolicy>::SingleMode() const\n{\n  return boost::apply_visitor(SingleModeVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nbool& RAModel<SortPolicy>::SingleMode()\n{\n  return boost::apply_visitor(SingleModeVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\ndouble RAModel<SortPolicy>::Tau() const\n{\n  return boost::apply_visitor(TauVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\ndouble& RAModel<SortPolicy>::Tau()\n{\n  return boost::apply_visitor(TauVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\ndouble RAModel<SortPolicy>::Alpha() const\n{\n  return boost::apply_visitor(AlphaVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\ndouble& RAModel<SortPolicy>::Alpha()\n{\n  return boost::apply_visitor(AlphaVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nbool RAModel<SortPolicy>::SampleAtLeaves() const\n{\n  return boost::apply_visitor(SampleAtLeavesVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nbool& RAModel<SortPolicy>::SampleAtLeaves()\n{\n  return boost::apply_visitor(SampleAtLeavesVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nbool RAModel<SortPolicy>::FirstLeafExact() const\n{\n  return boost::apply_visitor(FirstLeafExactVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nbool& RAModel<SortPolicy>::FirstLeafExact()\n{\n  return boost::apply_visitor(FirstLeafExactVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nsize_t RAModel<SortPolicy>::SingleSampleLimit() const\n{\n  return boost::apply_visitor(SingleSampleLimitVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nsize_t& RAModel<SortPolicy>::SingleSampleLimit()\n{\n  return boost::apply_visitor(SingleSampleLimitVisitor(), raSearch);\n}\n\ntemplate<typename SortPolicy>\nsize_t RAModel<SortPolicy>::LeafSize() const\n{\n  return leafSize;\n}\n\ntemplate<typename SortPolicy>\nsize_t& RAModel<SortPolicy>::LeafSize()\n{\n  return leafSize;\n}\n\ntemplate<typename SortPolicy>\ntypename RAModel<SortPolicy>::TreeTypes RAModel<SortPolicy>::TreeType() const\n{\n  return treeType;\n}\n\ntemplate<typename SortPolicy>\ntypename RAModel<SortPolicy>::TreeTypes& RAModel<SortPolicy>::TreeType()\n{\n  return treeType;\n}\n\ntemplate<typename SortPolicy>\nbool RAModel<SortPolicy>::RandomBasis() const\n{\n  return randomBasis;\n}\n\ntemplate<typename SortPolicy>\nbool& RAModel<SortPolicy>::RandomBasis()\n{\n  return randomBasis;\n}\n\ntemplate<typename SortPolicy>\nvoid RAModel<SortPolicy>::BuildModel(arma::mat&& referenceSet,\n                                     const size_t leafSize,\n                                     const bool naive,\n                                     const bool singleMode)\n{\n  // Initialize random basis, if necessary.\n  if (randomBasis)\n  {\n    Log::Info << \"Creating random basis...\" << std::endl;\n    math::RandomBasis(q, referenceSet.n_rows);\n  }\n\n  // Clean memory, if necessary.\n  boost::apply_visitor(DeleteVisitor(), raSearch);\n\n  this->leafSize = leafSize;\n\n  if (randomBasis)\n    referenceSet = q * referenceSet;\n\n  if (!naive)\n  {\n    Timer::Start(\"tree_building\");\n    Log::Info << \"Building reference tree...\" << std::endl;\n  }\n\n  switch (treeType)\n  {\n    case KD_TREE:\n      raSearch = new RAType<SortPolicy, tree::KDTree>(naive, singleMode);\n      break;\n    case COVER_TREE:\n      raSearch = new RAType<SortPolicy, tree::StandardCoverTree>(naive,\n          singleMode);\n      break;\n    case R_TREE:\n      raSearch = new RAType<SortPolicy, tree::RTree>(naive, singleMode);\n      break;\n    case R_STAR_TREE:\n      raSearch = new RAType<SortPolicy, tree::RStarTree>(naive, singleMode);\n      break;\n    case X_TREE:\n      raSearch = new RAType<SortPolicy, tree::XTree>(naive, singleMode);\n      break;\n    case HILBERT_R_TREE:\n      raSearch = new RAType<SortPolicy, tree::HilbertRTree>(naive, singleMode);\n      break;\n    case R_PLUS_TREE:\n      raSearch = new RAType<SortPolicy, tree::RPlusTree>(naive, singleMode);\n      break;\n    case R_PLUS_PLUS_TREE:\n      raSearch = new RAType<SortPolicy, tree::RPlusPlusTree>(naive,\n          singleMode);\n      break;\n    case UB_TREE:\n      raSearch = new RAType<SortPolicy, tree::UBTree>(naive, singleMode);\n      break;\n    case OCTREE:\n      raSearch = new RAType<SortPolicy, tree::Octree>(naive, singleMode);\n      break;\n  }\n\n  TrainVisitor<SortPolicy> tn(std::move(referenceSet), leafSize);\n  boost::apply_visitor(tn, raSearch);\n\n  if (!naive)\n  {\n    Timer::Stop(\"tree_building\");\n    Log::Info << \"Tree built.\" << std::endl;\n  }\n}\n\ntemplate<typename SortPolicy>\nvoid RAModel<SortPolicy>::Search(arma::mat&& querySet,\n                                 const size_t k,\n                                 arma::Mat<size_t>& neighbors,\n                                 arma::mat& distances)\n{\n  // Apply the random basis if necessary.\n  if (randomBasis)\n    querySet = q * querySet;\n\n  Log::Info << \"Searching for \" << k << \" approximate nearest neighbors with \";\n  if (!Naive() && !SingleMode())\n    Log::Info << \"dual-tree rank-approximate \" << TreeName() << \" search...\";\n  else if (!Naive())\n    Log::Info << \"single-tree rank-approximate \" << TreeName() << \" search...\";\n  else\n    Log::Info << \"brute-force (naive) rank-approximate search...\";\n  Log::Info << std::endl;\n\n  BiSearchVisitor<SortPolicy> search(querySet, k, neighbors, distances,\n      leafSize);\n  boost::apply_visitor(search, raSearch);\n}\n\ntemplate<typename SortPolicy>\nvoid RAModel<SortPolicy>::Search(const size_t k,\n                                 arma::Mat<size_t>& neighbors,\n                                 arma::mat& distances)\n{\n  Log::Info << \"Searching for \" << k << \" approximate nearest neighbors with \";\n  if (!Naive() && !SingleMode())\n    Log::Info << \"dual-tree rank-approximate \" << TreeName() << \" search...\";\n  else if (!Naive())\n    Log::Info << \"single-tree rank-approximate \" << TreeName() << \" search...\";\n  else\n    Log::Info << \"brute-force (naive) rank-approximate search...\";\n  Log::Info << std::endl;\n\n  MonoSearchVisitor search(k, neighbors, distances);\n  boost::apply_visitor(search, raSearch);\n}\n\ntemplate<typename SortPolicy>\nstd::string RAModel<SortPolicy>::TreeName() const\n{\n  switch (treeType)\n  {\n    case KD_TREE:\n      return \"kd-tree\";\n    case COVER_TREE:\n      return \"cover tree\";\n    case R_TREE:\n      return \"R tree\";\n    case R_STAR_TREE:\n      return \"R* tree\";\n    case X_TREE:\n      return \"X tree\";\n    case HILBERT_R_TREE:\n      return \"Hilbert R tree\";\n    case R_PLUS_TREE:\n      return \"R+ tree\";\n    case R_PLUS_PLUS_TREE:\n      return \"R++ tree\";\n    case UB_TREE:\n      return \"UB tree\";\n    case OCTREE:\n      return \"octree\";\n    default:\n      return \"unknown tree\";\n  }\n}\n\n} // namespace neighbor\n} // namespace mlpack\n\n#endif\n", "meta": {"hexsha": "093ce74d10e0338ea351b73a4c4aef3620a5423c", "size": 17325, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/rann/ra_model_impl.hpp", "max_stars_repo_name": "MJ10/mlpack", "max_stars_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/methods/rann/ra_model_impl.hpp", "max_issues_repo_name": "MJ10/mlpack", "max_issues_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "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/rann/ra_model_impl.hpp", "max_forks_repo_name": "MJ10/mlpack", "max_forks_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "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": 27.5875796178, "max_line_length": 80, "alphanum_fraction": 0.693968254, "num_tokens": 4317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19395960471703508}}
{"text": "/*\n * $Revision: 567 $ $Date: 2011-02-24 13:28:02 -0800 (Thu, 24 Feb 2011) $\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 \"TrajectoryGeometry.h\"\n#include \"Trajectory.h\"\n#include \"RenderContext.h\"\n#include \"Material.h\"\n#include \"Debug.h\"\n#include <curveplot/curveplot.h>\n#include <Eigen/LU>\n#include <algorithm>\n\nusing namespace vesta;\nusing namespace Eigen;\nusing namespace std;\n\n\nTrajectoryGeometry::TrajectoryGeometry() :\n    m_color(Spectrum(1.0f, 1.0f, 1.0f)),\n    m_opacity(1.0f),\n    m_curvePlot(0),\n    m_startTime(0.0),\n    m_endTime(0.0),\n    m_boundingRadius(0.0),\n    m_displayedPortion(Entire),\n    m_windowDuration(0.0),\n    m_windowLead(0.),\n    m_fadeFraction(0.0),\n    m_lineWidth(1.0f)\n{\n    // Make trajectories splittable by default in order to prevent\n    // clipping artifacts.\n    setClippingPolicy(SplitToPreventClipping);\n}\n\n\nTrajectoryGeometry::~TrajectoryGeometry()\n{\n    delete m_curvePlot;\n}\n\n\nvoid\nTrajectoryGeometry::render(RenderContext& rc, double clock) const\n{\n    if (!m_curvePlot)\n    {\n        return;\n    }\n\n    bool fade = false;\n    double startTime = m_startTime;\n    double endTime = m_endTime;\n    switch (m_displayedPortion)\n    {\n    case StartToCurrentTime:\n        endTime = clock;\n        break;\n    case CurrentTimeToEnd:\n        startTime = clock;\n        break;\n    case WindowBeforeCurrentTime:\n        endTime = clock + m_windowLead;\n        startTime = clock + m_windowLead - m_windowDuration;\n        fade = m_fadeFraction > 0.0;\n        break;\n    default:\n        break;\n    }\n\n    // Abort now if there's nothing to draw\n    if (endTime <= startTime)\n    {\n        return;\n    }\n\n    // Skip drawing trajectories that are less than a pixel in size. This should be done by\n    // UniverseRenderer, except that visualizers (which is where TrajectoryGeometry is typically used)\n    // aren't size culled.\n    float projectedSize = (boundingSphereRadius() / float(rc.modelview().translation().norm())) / rc.pixelSize();\n    if (projectedSize < 0.5f)\n    {\n        return;\n    }\n\n    const Frustum& frustum = rc.frustum();\n\n    // Get a high precision modelview matrix; the full transformation is stored at single precision,\n    // but the camera space position is stored at double precision.\n    Transform3d modelview = rc.modelview().cast<double>();\n    Vector3d t = rc.modelTranslation();\n    modelview.matrix().col(3) = Vector4d(t.x(), t.y(), t.z(), 1.0);\n\n    if (m_frame.isValid())\n    {\n        modelview = modelview * m_frame->orientation(clock);\n    }\n\n    // Set the model view matrix to identity, as the curveplot module performs all transformations in\n    // software using double precision.\n    rc.pushModelView();\n    rc.identityModelView();\n\n    glLineWidth(m_lineWidth);\n    double subdivisionThreshold = rc.pixelSize() * 30.0;\n    if (fade)\n    {\n        rc.setVertexInfo(VertexSpec::PositionColor);\n        Material material;\n        material.setDiffuse(Spectrum::White());\n        rc.bindMaterial(&material);\n\n        double fadeStartTime = startTime;\n        double fadeEndTime = fadeStartTime + m_windowDuration * m_fadeFraction;\n        glEnable(GL_BLEND);\n        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n        m_curvePlot->renderFaded(modelview,\n                                 -frustum.nearZ, -frustum.farZ, frustum.planeNormals, // viewFrustum\n                                 subdivisionThreshold,\n                                 startTime, endTime,\n                                 Vector4f(m_color.red(), m_color.green(), m_color.blue(), 1.0f),\n                                 fadeStartTime, fadeEndTime);\n        glDisable(GL_BLEND);\n    }\n    else\n    {\n        rc.setVertexInfo(VertexSpec::Position);\n        Material material;\n        material.setEmission(m_color);\n        rc.bindMaterial(&material);\n\n        m_curvePlot->render(modelview,\n                            -frustum.nearZ, -frustum.farZ, frustum.planeNormals, // viewFrustum\n                            subdivisionThreshold,\n                            startTime, endTime);\n    }\n    glLineWidth(1.0f);\n\n    rc.popModelView();\n}\n\n\n/** Add a new sample to the trajectory. If this is not the first sample, the time t must\n  * be greater than the time of the last added sample; if not, the sample is discarded.\n  *\n  * \\param t time in seconds since J2000.0\n  * \\param s state vector\n  */\nvoid\nTrajectoryGeometry::addSample(double t, const StateVector& s)\n{\n    if (!m_curvePlot)\n    {\n        m_curvePlot = new CurvePlot();\n    }\n\n    if (m_curvePlot->sampleCount() == 0)\n    {\n        m_startTime = t;\n        m_endTime = t;\n    }\n\n    if (m_curvePlot->sampleCount() == 0 || t > m_curvePlot->endTime())\n    {\n        CurvePlotSample sample;\n        sample.t = t;\n        sample.position = s.position();\n        sample.velocity = s.velocity();\n        m_curvePlot->addSample(sample);\n\n        m_boundingRadius = std::max(m_boundingRadius, s.position().norm());\n        m_endTime = t;\n    }\n}\n\n\n/** Remove all trajectory plot samples.\n  */\nvoid\nTrajectoryGeometry::clearSamples()\n{\n    // Throw out the previous trajectory\n    if (m_curvePlot)\n    {\n        delete m_curvePlot;\n        m_curvePlot = NULL;\n    }\n\n    m_boundingRadius = 0.0;\n    m_startTime = 0.0;\n    m_endTime = 0.0;\n}\n\n\nclass TrajectorySampleGenerator : public TrajectoryPlotGenerator\n{\npublic:\n    TrajectorySampleGenerator(const Trajectory* trajectory) :\n        m_trajectory(trajectory)\n    {\n    }\n\n    StateVector state(double t) const\n    {\n        return m_trajectory->state(t);\n    }\n\n    double startTime() const\n    {\n        return m_trajectory->startTime();\n    }\n\n    double endTime() const\n    {\n        return m_trajectory->endTime();\n    }\n\nprivate:\n    const Trajectory* m_trajectory;\n};\n\n\n/** Automatically add samples to the trajectory plot. Samples of the specified trajectory\n  * are calculated at regular intervals between the startTime and endTime. Any existing samples\n  * in the trajectory plot are replaced.\n  */\nvoid\nTrajectoryGeometry::computeSamples(const Trajectory* trajectory, double startTime, double endTime, unsigned int steps)\n{\n    // Abort if we're asked to plot a null trajectory\n    if (!trajectory)\n    {\n        return;\n    }\n\n    TrajectorySampleGenerator gen(trajectory);\n    computeSamples(&gen, startTime, endTime, steps);\n}\n\n\n/** Automatically add samples to the trajectory plot. Samples of the specified trajectory\n  * are calculated at regular intervals between the startTime and endTime.\n  */\nvoid\nTrajectoryGeometry::updateSamples(const Trajectory* trajectory, double startTime, double endTime, unsigned int steps)\n{\n    // Abort if we're asked to plot a null trajectory\n    if (!trajectory)\n    {\n        return;\n    }\n\n    TrajectorySampleGenerator gen(trajectory);\n    updateSamples(&gen, startTime, endTime, steps);\n}\n\n\n/** Automatically add samples to the trajectory plot. States from the specified generator\n  * are calculated at regular intervals between the startTime and endTime. Any existing samples\n  * in the trajectory plot are replaced.\n  */\nvoid\nTrajectoryGeometry::computeSamples(const TrajectoryPlotGenerator* generator, double startTime, double endTime, unsigned int steps)\n{\n    // Abort if we're asked to use a null generator\n    if (!generator)\n    {\n        return;\n    }\n\n    clearSamples();\n\n    startTime = max(generator->startTime(), startTime);\n    endTime = min(generator->endTime(), endTime);\n\n    // Nothing to plot if end is before start\n    if (endTime <= startTime)\n    {\n        return;\n    }\n\n    m_curvePlot = new CurvePlot();\n\n    m_startTime = startTime;\n    m_endTime = endTime;\n    double dt = (endTime - startTime) / steps;\n\n    for (unsigned int i = 0; i <= steps; ++i)\n    {\n        double t = m_startTime + i * dt;\n        StateVector state = generator->state(t);\n        addSample(t, state);\n    }\n\n    // Adjust the bounding radius slightly to prevent culling when the\n    // trajectory lies barely inside the view frustum.\n    m_boundingRadius *= 1.1;\n}\n\n\n/** Automatically add samples to the trajectory plot. Samples of the specified\n  * generator are calculated at regular intervals between the startTime and endTime.\n  */\nvoid\nTrajectoryGeometry::updateSamples(const TrajectoryPlotGenerator* generator, double startTime, double endTime, unsigned int steps)\n{\n    // Abort if we're asked to use a null generator\n    if (!generator)\n    {\n        return;\n    }\n\n    if (!m_curvePlot)\n    {\n        // Trajectory hasn't been created yet; initialize it for the specified time range\n        computeSamples(generator, startTime, endTime, steps);\n        return;\n    }\n\n    double dt = (endTime - startTime) / (steps - 1);\n    double windowStartTime = max(generator->startTime(), startTime - dt);\n    double windowEndTime = min(generator->endTime(), endTime + dt);\n\n    if (endTime <= m_curvePlot->startTime() || startTime >= m_curvePlot->endTime())\n    {\n        computeSamples(generator, windowStartTime, windowEndTime, steps);\n    }\n    else\n    {\n        if (startTime < m_curvePlot->startTime())\n        {\n            // Add samples at the beginning\n            for (double t = m_curvePlot->startTime() - dt; t > windowStartTime; t -= dt)\n            {\n                t = max(t, windowStartTime);\n                StateVector sv = generator->state(t);\n\n                CurvePlotSample sample;\n                sample.t = t;\n                sample.position = sv.position();\n                sample.velocity = sv.velocity();\n                m_curvePlot->addSample(sample);\n                m_boundingRadius = std::max(m_boundingRadius, sv.position().norm());\n            }\n        }\n\n        if (endTime > m_curvePlot->endTime())\n        {\n            // Add samples at the end\n            for (double t = m_curvePlot->endTime() + dt; t < windowEndTime; t += dt)\n            {\n                t = min(t, windowEndTime);\n                StateVector sv = generator->state(t);\n\n                CurvePlotSample sample;\n                sample.t = t;\n                sample.position = sv.position();\n                sample.velocity = sv.velocity();\n                m_curvePlot->addSample(sample);\n                m_boundingRadius = std::max(m_boundingRadius, sv.position().norm());\n            }\n        }\n\n        // Remove samples\n        m_curvePlot->removeSamplesAfter(windowEndTime);\n        m_curvePlot->removeSamplesBefore(windowStartTime);\n    }\n\n    m_startTime = windowStartTime;\n    m_endTime = windowEndTime;\n}\n", "meta": {"hexsha": "46a5f278561c50e0385247715dc32cd89e761a6d", "size": 10648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/vesta/TrajectoryGeometry.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/TrajectoryGeometry.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/TrajectoryGeometry.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": 28.0949868074, "max_line_length": 130, "alphanum_fraction": 0.6319496619, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "/*\nCopyright 2020 The OneFlow Authors. All rights reserved.\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#include <gtest/gtest.h>\n#include \"oneflow/core/ep/test/primitive/primitive_test.h\"\n#include \"oneflow/core/ep/include/primitive/memset.h\"\n#include \"oneflow/core/ep/include/primitive/memcpy.h\"\n#include \"oneflow/core/ep/include/primitive/add.h\"\n#include <Eigen/Core>\n\nnamespace oneflow {\n\nnamespace ep {\n\nnamespace primitive {\n\nnamespace test {\n\nnamespace {\n\ntemplate<DataType data_type, typename T, size_t n>\nvoid TestAdd(DeviceManagerRegistry* registry, const std::set<DeviceType>& device_types) {\n  constexpr size_t max_arity = 10;\n  using Matrix = Eigen::Matrix<T, 1, n>;\n  std::vector<Matrix> srcs(max_arity);\n  std::vector<Matrix> dsts(max_arity);\n  for (size_t i = 0; i < max_arity; ++i) {\n    srcs[i] = Matrix::Random();\n    if (i == 0) {\n      dsts[i] = Matrix::Zero();\n    } else {\n      dsts[i] = srcs[i - 1] + dsts[i - 1];\n    }\n  }\n  const size_t vector_size = n * sizeof(T);\n  for (const auto& device_type : device_types) {\n    auto device = registry->GetDevice(device_type, 0);\n    std::vector<void*> host_srcs(max_arity);\n    std::vector<void*> device_srcs(max_arity);\n    std::vector<void*> host_dsts(max_arity);\n    std::vector<void*> device_dsts(max_arity);\n    AllocationOptions pinned_options;\n    pinned_options.SetPinnedDevice(device_type, 0);\n    AllocationOptions device_options;\n    for (size_t i = 0; i < max_arity; ++i) {\n      CHECK_JUST(device->AllocPinned(pinned_options, &host_srcs[i], vector_size));\n      CHECK_JUST(device->AllocPinned(pinned_options, &host_dsts[i], vector_size));\n      CHECK_JUST(device->Alloc(device_options, &device_srcs[i], vector_size));\n      CHECK_JUST(device->Alloc(device_options, &device_dsts[i], vector_size));\n    }\n    ep::test::StreamGuard stream(device.get());\n    std::unique_ptr<Add> add = NewPrimitive<AddFactory>(device_type, data_type);\n    ASSERT_TRUE(add.operator bool());\n    std::unique_ptr<Memcpy> h2d = NewPrimitive<MemcpyFactory>(device_type, MemcpyKind::kHtoD);\n    std::unique_ptr<Memcpy> d2h = NewPrimitive<MemcpyFactory>(device_type, MemcpyKind::kDtoH);\n    ASSERT_TRUE(d2h.operator bool());\n    ASSERT_TRUE(h2d.operator bool());\n    for (size_t i = 0; i < max_arity; ++i) {\n      std::memcpy(host_srcs[i], srcs[i].data(), vector_size);\n      h2d->Launch(stream.stream(), device_srcs[i], host_srcs[i], vector_size);\n    }\n    for (size_t i = 2; i < max_arity; ++i) {\n      add->Launch(stream.stream(), device_srcs.data(), i, device_dsts.at(i), n);\n    }\n    for (size_t i = 2; i < max_arity; ++i) {\n      d2h->Launch(stream.stream(), host_dsts[i], device_dsts[i], vector_size);\n    }\n    CHECK_JUST(stream.stream()->Sync());\n    for (size_t i = 2; i < max_arity; ++i) {\n      auto res = Eigen::Map<Matrix, Eigen::Unaligned>(reinterpret_cast<T*>(host_dsts[i]), n);\n      ASSERT_TRUE(dsts[i].template isApprox(res));\n    }\n    for (size_t i = 0; i < max_arity; ++i) {\n      device->FreePinned(pinned_options, host_srcs[i]);\n      device->FreePinned(pinned_options, host_dsts[i]);\n      device->Free(device_options, device_srcs[i]);\n      device->Free(device_options, device_dsts[i]);\n    }\n  }\n}\n\n}  // namespace\n\nTEST_F(PrimitiveTest, TestAdd) {\n  TestAdd<DataType::kDouble, double, 1024>(&device_manager_registry_, available_device_types_);\n  TestAdd<DataType::kFloat, float, 1024>(&device_manager_registry_, available_device_types_);\n  TestAdd<DataType::kFloat16, Eigen::half, 1024>(&device_manager_registry_,\n                                                 available_device_types_);\n}\n\n}  // namespace test\n\n}  // namespace primitive\n\n}  // namespace ep\n\n}  // namespace oneflow\n", "meta": {"hexsha": "aca05725ea2f228849776b853c6b4b55682968f3", "size": 4151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "oneflow/core/ep/test/primitive/add_test.cpp", "max_stars_repo_name": "Panlichen/oneflow", "max_stars_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "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": "oneflow/core/ep/test/primitive/add_test.cpp", "max_issues_repo_name": "Panlichen/oneflow", "max_issues_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "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": "oneflow/core/ep/test/primitive/add_test.cpp", "max_forks_repo_name": "Panlichen/oneflow", "max_forks_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-15T02:14:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T02:14:49.000Z", "avg_line_length": 37.7363636364, "max_line_length": 95, "alphanum_fraction": 0.6911587569, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "#include <boost/format.hpp>\n#include <facter/execution/execution.hpp>\n#include <facter/facts/fact_map.hpp>\n#include <facter/facts/fact.hpp>\n#include <facter/facts/scalar_value.hpp>\n#include <facter/facts/posix/uptime_resolver.hpp>\n#include <facter/util/file.hpp>\n#include <facter/util/string.hpp>\n#include <re2/re2.h>\n\nusing namespace std;\nusing boost::format;\nusing namespace facter::util;\nusing namespace facter::execution;\n\nnamespace facter { namespace facts { namespace posix {\n\n    uptime_resolver::uptime_resolver() :\n        fact_resolver(\n            \"uptime\",\n            {\n                fact::uptime,\n                fact::uptime_days,\n                fact::uptime_hours,\n                fact::uptime_seconds\n            })\n    {\n    }\n\n    void uptime_resolver::resolve_facts(fact_map& facts)\n    {\n        // Resolve all uptime-related facts\n        resolve_uptime_seconds(facts);  // must be first b/c the following facts are based on this\n        resolve_uptime_hours(facts);\n        resolve_uptime_days(facts);\n        resolve_uptime(facts);\n    }\n\n    void uptime_resolver::resolve_uptime_seconds(fact_map& facts)\n    {\n        int value = executable_uptime();\n        facts.add(fact::uptime_seconds, make_value<integer_value>(value));\n    }\n\n    void uptime_resolver::resolve_uptime_hours(fact_map& facts)\n    {\n        auto uptime_seconds = facts.get<integer_value>(fact::uptime_seconds, false);\n        if (!uptime_seconds) {\n            return;\n        }\n        facts.add(fact::uptime_hours, make_value<integer_value>(uptime_seconds->value() / (60 * 60)));\n    }\n\n    void uptime_resolver::resolve_uptime_days(fact_map& facts)\n    {\n        auto uptime_seconds = facts.get<integer_value>(fact::uptime_seconds, false);\n        if (!uptime_seconds) {\n            return;\n        }\n        facts.add(fact::uptime_days, make_value<integer_value>(uptime_seconds->value() / (60 * 60 * 24)));\n    }\n\n    void uptime_resolver::resolve_uptime(fact_map& facts)\n    {\n        auto uptime_seconds = facts.get<integer_value>(fact::uptime_seconds, false);\n        if (!uptime_seconds) {\n            return;\n        }\n        int seconds = uptime_seconds->value();\n\n        int days    = seconds / (60 * 60 * 24);\n        int hours   = (seconds / (60 * 60)) % 24;\n        int minutes = (seconds / 60) % 60;\n\n        string value;\n        switch (days) {\n            case 0:\n                value = (format(\"%d:%02d hours\") % hours % minutes).str();\n                break;\n            case 1:\n                value = \"1 day\";\n                break;\n            default:\n                value = (format(\"%d days\") % days).str();\n        }\n        facts.add(fact::uptime, make_value<string_value>(move(value)));\n    }\n\n    // call the uptime executable\n    int uptime_resolver::executable_uptime()\n    {\n        string uptime_output = execute(\"uptime\");\n        if (uptime_output.empty()) {\n            return 0;\n        }\n        return parse_executable_uptime(uptime_output);\n    }\n\n    // parse the output from the uptime executable\n    int uptime_resolver::parse_executable_uptime(string const& output)\n    {\n        // This regex parsing is directly ported from facter:\n        // https://github.com/puppetlabs/facter/blob/2.0.1/lib/facter/util/uptime.rb#L42-L60\n\n        int days, hours, minutes;\n\n        if (RE2::PartialMatch(output, \"(\\\\d+) day(?:s|\\\\(s\\\\))?,\\\\s+(\\\\d+):(\\\\d+)\", &days, &hours, &minutes)) {\n            return 86400 * days + 3600 * hours + 60 * minutes;\n        } else if (RE2::PartialMatch(output, \"(\\\\d+) day(?:s|\\\\(s\\\\))?,\\\\s+(\\\\d+) hr(?:s|\\\\(s\\\\))?,\", &days, &hours)) {\n            return 86400 * days + 3600 * hours;\n        } else if (RE2::PartialMatch(output, \"(\\\\d+) day(?:s|\\\\(s\\\\))?,\\\\s+(\\\\d+) min(?:s|\\\\(s\\\\))?,\", &days, &minutes)) {\n            return 86400 * days + 60 * minutes;\n        } else if (RE2::PartialMatch(output, \"(\\\\d+) day(?:s|\\\\(s\\\\))?,\", &days)) {\n            return 86400 * days;\n        } else if (RE2::PartialMatch(output, \"up\\\\s+(\\\\d+):(\\\\d+),\", &hours, &minutes)) {\n            return 3600 * hours + 60 * minutes;\n        } else if (RE2::PartialMatch(output, \"(\\\\d+) hr(?:s|\\\\(s\\\\))?,\", &hours)) {\n            return 3600 * hours;\n        } else if (RE2::PartialMatch(output, \"(\\\\d+) min(?:s|\\\\(s\\\\))?,\", &minutes)) {\n            return 60 * minutes;\n        } else {\n           return 0;\n        }\n    }\n\n}}}  // namespace facter::facts::posix\n", "meta": {"hexsha": "e320e5d7da9f86a00444af147df3d0b20a591518", "size": 4409, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/src/facts/posix/uptime_resolver.cc", "max_stars_repo_name": "ploubser/cfacter", "max_stars_repo_head_hexsha": "269717adb4472a66f9763a228498f47771d41343", "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": "lib/src/facts/posix/uptime_resolver.cc", "max_issues_repo_name": "ploubser/cfacter", "max_issues_repo_head_hexsha": "269717adb4472a66f9763a228498f47771d41343", "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": "lib/src/facts/posix/uptime_resolver.cc", "max_forks_repo_name": "ploubser/cfacter", "max_forks_repo_head_hexsha": "269717adb4472a66f9763a228498f47771d41343", "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.7165354331, "max_line_length": 122, "alphanum_fraction": 0.5661147653, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"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_IF_ELSE_ZERO_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IF_ELSE_ZERO_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-boolean\n    This function object conditionally returns @c x (respectively @ref Zero)\n    if @c c is @ref True (respectively  @ref False)\n\n\n    @par Header <boost/simd/function/if_else_zero.hpp>\n\n    @par Example:\n\n      @snippet if_else_zero.cpp if_else_zero\n\n    @par Possible output:\n\n      @snippet if_else_zero.txt if_else_zero\n\n  **/\n  Value1 if_else_zero(Value0 const& c, Value1 const& t);\n} }\n#endif\n\n#include <boost/simd/function/scalar/if_else_zero.hpp>\n#include <boost/simd/function/simd/if_else_zero.hpp>\n\n#endif\n", "meta": {"hexsha": "38db4f12a4ac7c430392882f79733f16a4daf6f4", "size": 1114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/if_else_zero.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/if_else_zero.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/if_else_zero.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": 25.9069767442, "max_line_length": 100, "alphanum_fraction": 0.6059245961, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"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_BITWISE_FUNCTIONS_SIMD_COMMON_RSHR_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_BITWISE_FUNCTIONS_SIMD_COMMON_RSHR_HPP_INCLUDED\n#include <boost/simd/toolbox/bitwise/functions/rshr.hpp>\n#include <boost/simd/sdk/meta/cardinal_of.hpp>\n#include <boost/simd/include/functions/simd/is_gtz.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/shift_left.hpp>\n#include <boost/simd/include/functions/simd/shift_right.hpp>\n#include <boost/simd/include/functions/simd/unary_minus.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION_IF ( boost::simd::tag::rshr_, tag::cpu_, (A0)(A1)(X)\n                                , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                                        , boost::simd::meta::cardinal_of<A1>\n                                                        >\n                                  )\n                                , ((simd_<arithmetic_<A0>,X>))\n                                  ((simd_<integer_<A1>,X>))\n                       )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      return if_else(is_gtz(a1),shr(a0, a1),shl(a0, -a1));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION_IF ( boost::simd::tag::rshr_, tag::cpu_, (A0)(A1)(X)\n                                , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                                        , boost::simd::meta::cardinal_of<A1>\n                                                        >\n                                  )\n                                , ((simd_<arithmetic_<A0>,X>))\n                                  ((simd_<unsigned_<A1>,X>))\n                       )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      return shr(a0, a1);\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "ad5b5892c7eeca8fd0e12952bee2b8690057ba4a", "size": 2401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/bitwise/include/boost/simd/toolbox/bitwise/functions/simd/common/rshr.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/bitwise/include/boost/simd/toolbox/bitwise/functions/simd/common/rshr.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/bitwise/include/boost/simd/toolbox/bitwise/functions/simd/common/rshr.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": 42.875, "max_line_length": 92, "alphanum_fraction": 0.4960433153, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <vector>\n\n#include <physics/objects/Vehicle.h>\n#include <physics/World.h>\n#include <physics/objects/ObjectsFactory.h>\n\nusing namespace Physics;\nusing namespace Objects;\n\nstruct VehicleTestFixture {\n\tVehicleTestFixture() :\n\t\tw(b2Vec2(0.0f, 9.8f), 4, 8),\n\t\tobj(ObjectsFactory::init(w.getWorld())),\n\t\theights(8, 1.0f){\n\t}\n\tWorld w;\n\tObjectsFactory& obj;\n\tstd::vector<float> heights;\n};\n\n\nBOOST_FIXTURE_TEST_SUITE(VehicleTests, VehicleTestFixture);\n\nBOOST_AUTO_TEST_CASE(check_creation_position) \n{\n\tVehicle v(Vector2(1.1f, 2.1f), heights, 0.1f, 0.1f);\n\tBOOST_CHECK_EQUAL(v.getPosition().x, 1.1f);\n\tBOOST_CHECK_EQUAL(v.getPosition().y, 2.1f);\n}\n\nBOOST_AUTO_TEST_CASE(check_wheels_radius)\n{\n\tVehicle v(Vector2(1.1f, 2.1f), heights, 1.1f, 2.1f);\n\tBOOST_CHECK_EQUAL(v.getFrontWheel().getRadius(), 1.1f);\n\tBOOST_CHECK_EQUAL(v.getBackWheel().getRadius(), 2.1f);\n}\n\nBOOST_AUTO_TEST_CASE(check_body_vertices)\n{\n\tVehicle v(Vector2(1.1f, 2.1f), heights, 1.1f, 2.1f);\n\tauto& vert = v.getBody().getVertices();\n\n\tBOOST_CHECK_EQUAL(vert[0].x, 0.0f);\n\tBOOST_CHECK_EQUAL(vert[0].y, 1.0f);\n\n\tBOOST_CHECK_EQUAL(vert[1].x, -1.0f);\n\tBOOST_CHECK_EQUAL(vert[1].y, 1.0f);\n\n\tBOOST_CHECK_EQUAL(vert[2].x, -1.0f);\n\tBOOST_CHECK_EQUAL(vert[2].y, 0.0f);\n\n\tBOOST_CHECK_EQUAL(vert[3].x, -1.0f);\n\tBOOST_CHECK_EQUAL(vert[3].y, -1.0f);\n\n\tBOOST_CHECK_EQUAL(vert[4].x, 0.0f);\n\tBOOST_CHECK_EQUAL(vert[4].y, -1.0f);\n\n\tBOOST_CHECK_EQUAL(vert[5].x, 1.0f);\n\tBOOST_CHECK_EQUAL(vert[5].y, -1.0f);\n\n\tBOOST_CHECK_EQUAL(vert[6].x, 1.0f);\n\tBOOST_CHECK_EQUAL(vert[6].y, 0.0f);\n\n\tBOOST_CHECK_EQUAL(vert[7].x, 1.0f);\n\tBOOST_CHECK_EQUAL(vert[7].y, 1.0f);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "d1d0c2efd3a272787d19c095538dcf064120c964", "size": 1678, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/physics/objects/Vehicle_test.cc", "max_stars_repo_name": "gajus123/Genetic-Cars", "max_stars_repo_head_hexsha": "f399ebcf0952465e91d8711e08f0c38e6c18bb92", "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/physics/objects/Vehicle_test.cc", "max_issues_repo_name": "gajus123/Genetic-Cars", "max_issues_repo_head_hexsha": "f399ebcf0952465e91d8711e08f0c38e6c18bb92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-25T21:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-25T21:06:35.000Z", "max_forks_repo_path": "tests/physics/objects/Vehicle_test.cc", "max_forks_repo_name": "gajus123/Genetic-Cars", "max_forks_repo_head_hexsha": "f399ebcf0952465e91d8711e08f0c38e6c18bb92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-28T13:39:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-28T13:39:05.000Z", "avg_line_length": 23.9714285714, "max_line_length": 59, "alphanum_fraction": 0.7187127533, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.19394754235252773}}
{"text": "#include <cstdio>\n#include <limits>\n\n#include <sstream>\n#include <iomanip>\n\n#include <boost/lexical_cast.hpp>\n\n#include \"asserts.hpp\"\n#include \"as_function_params.hpp\"\n#include \"as_object.hpp\"\n#include \"as_value.hpp\"\n#include \"swf_environment.hpp\"\n#include \"swf_player.hpp\"\n\nnamespace swf\n{\n\tas_value_ptr as_value::from_bool(bool value)\n\t{\n\t\treturn std::make_shared<as_value>(value);\n\t}\n\n\tas_value::as_value(as_value_ptr get, as_value_ptr set)\n\t\t: type_(ValueType::PROPERTY),\n\t\t  b_(false),\n\t\t  d_(0),\n\t\t  o_(nullptr),\n\t\t  p_(std::make_shared<as_property>(get, set)),\n\t\t  flags_(PropertyFlags::NONE)\n\t{\n\t}\n\n\tas_value::as_value(as_native_function_type fn)\n\t\t: type_(ValueType::OBJECT),\n\t\t  b_(false),\n\t\t  d_(0),\n\t\t  flags_(PropertyFlags::NONE)\n\t{\n\t\to_ = as_native_function::create(weak_player_ptr(), fn);\n\t}\n\n\tconst char*\tas_value::to_string() const\n\t{\n\t\treturn to_std_string().c_str();\n\t}\n\n\tstd::string as_value::to_std_string() const\n\t{\n\t\tswitch(type_) {\n\t\t\tcase ValueType::UNDEFINED: return \"undefined\";\n\t\t\tcase ValueType::BOOLEAN: return b_ ? \"true\" : \"false\";\n\t\t\tcase ValueType::NUMERIC: {\n\t\t\t\tif(d_ == std::numeric_limits<double>::quiet_NaN()\n\t\t\t\t\t|| d_ == std::numeric_limits<double>::signaling_NaN()) { \n\t\t\t\t\treturn \"NaN\";\n\t\t\t\t} else {\n\t\t\t\t\tstd::stringstream ss_fixed;\n\t\t\t\t\tss_fixed << std::setprecision(14) << std::ios::fixed << d_;\n\t\t\t\t\tstd::string s_fix = ss_fixed.str();\n\t\t\t\t\tstd::stringstream ss_sci;\n\t\t\t\t\tss_fixed << std::setprecision(14) << std::ios::scientific << d_;\n\t\t\t\t\tstd::string s_sci = ss_sci.str();\n\t\t\t\t\tif(s_sci.length() < s_fix.length()) {\n\t\t\t\t\t\treturn s_sci;\n\t\t\t\t\t} \n\t\t\t\t\treturn s_fix;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase ValueType::STRING: return s_;\n\t\t\tcase ValueType::NULL_VALUE: return \"null\";\n\t\t\tcase ValueType::OBJECT: return o_->to_string();\n\t\t\tcase ValueType::PROPERTY:\n\t\t\t\t/*\n\t\t\t\tconvert property p_ to a string.\n\t\t\t\t*/\n\t\t\tdefault: ASSERT_LOG(false, \"to_string() bad type: \" << static_cast<int>(type_));\n\t\t}\n\t\treturn \"undefined\";\n\t}\n\n\tas_value operator+(const as_value& v1, const as_value& v2)\n\t{\n\t\tauto p1 = v1.to_primitive();\n\t\tauto p2 = v2.to_primitive();\n\t\tif(p1.type_ == ValueType::STRING || p2.type_ == ValueType::STRING) {\n\t\t\treturn as_value(p1.to_string() + p2.to_std_string());\n\t\t}\n\t\treturn as_value(p1.to_number() + p2.to_number());\n\t}\n\n\tas_value as_value::to_primitive(HintType hint) const\n\t{\n\t\tif(type_ == ValueType::OBJECT && o_ != nullptr) {\n\t\t\treturn o_->default_value(hint);\n\t\t} else if(type_ == ValueType::PROPERTY) {\n\t\t\tASSERT_LOG(false, \"XXX todo PROPERTY::to_primitive\");\n\t\t} \n\t\treturn *this;\n\t}\n\n\tint32_t as_value::to_int32()\n\t{\n\t\tdouble num = to_number();\n\t\tif(num == std::numeric_limits<double>::quiet_NaN() \n\t\t\t|| num == std::numeric_limits<double>::signaling_NaN() \n\t\t\t|| abs(num) == 0 \n\t\t\t|| abs(num) == std::numeric_limits<double>::infinity()) {\n\t\t\treturn 0;\n\t\t}\n\t\tdouble pos_int = (num > 0 ? 1 : -1) * floor(abs(num));\n\t\treturn static_cast<int32_t>(fmod(pos_int, 4294967296));\n\t}\n\n\tint as_value::to_integer()\n\t{\n\t\t/// Need to double check this against the standard.\n\t\tdouble num = to_number();\n\t\tif(num == std::numeric_limits<double>::quiet_NaN() \n\t\t\t|| num == std::numeric_limits<double>::signaling_NaN() \n\t\t\t|| abs(num) == 0 \n\t\t\t|| abs(num) == std::numeric_limits<double>::infinity()) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn static_cast<int>((num > 0 ? 1 : -1) * floor(abs(num)));\n\t}\n\n\tdouble as_value::to_number()\n\t{\n\t\tswitch(type_) {\n\t\t\tcase ValueType::UNDEFINED:\t\treturn std::numeric_limits<double>::infinity();\n\t\t\tcase ValueType::BOOLEAN:\t\treturn b_ ? 1 : 0;\n\t\t\tcase ValueType::NUMERIC:\t\treturn d_;\n\t\t\tcase ValueType::NULL_VALUE:\t\treturn 0;\n\t\t\tcase ValueType::OBJECT:\t\t\treturn o_->to_number();\n\t\t\tcase ValueType::PROPERTY: {\n\t\t\t\tASSERT_LOG(false, \"XXX todo PROPERTY::to_number\");\n\t\t\t}\n\t\t}\n\t\tASSERT_LOG(type_ != ValueType::STRING, \"FATAL: unknown type_ value: \" << static_cast<int>(type_));\n\t\t// String case -- we do thing the lazy way, not the compliant way.\n\t\tdouble num = std::numeric_limits<double>::infinity();\n\t\ttry {\n\t\t\tnum = boost::lexical_cast<double>(s_);\n\t\t} catch(boost::bad_lexical_cast&) {\n\t\t\tstd::cerr << \"Caught a bad floating point cast from \" << s_ << \" assuming infinity\" << std::endl;\n\t\t}\n\t\treturn num;\n\t}\n\n\tbool as_value::to_boolean()\n\t{\n\t\t// XXX check for correctness.\n\t\treturn to_integer() != 0;\n\t}\n\n\tas_object_ptr as_value::to_object()\n\t{\n\t\tswitch(type_) {\n\t\t\tcase ValueType::UNDEFINED:\n\t\t\tcase ValueType::BOOLEAN:\n\t\t\tcase ValueType::NUMERIC:\n\t\t\tcase ValueType::NULL_VALUE:\n\t\t\tcase ValueType::STRING:\n\t\t\t\tbreak;\n\t\t\tcase ValueType::OBJECT:\t\t\treturn o_;\n\t\t\tcase ValueType::PROPERTY: {\n\n\t\t\t\tASSERT_LOG(false, \"XXX todo PROPERTY::to_object\");\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\n\tas_value_ptr as_value::clone()\n\t{\n\t\treturn std::make_shared<as_value>(*this);\n\t}\n\n\tvoid as_value::set_property(const as_value_ptr& value)\n\t{\n\t\tASSERT_LOG(is_property(), \"Attempt to set property value on non-property.\");\n\t\tp_->set(o_, value);\n\t}\n\n\tas_value_ptr as_value::get_property() const\n\t{\n\t\tASSERT_LOG(is_property(), \"Attempt to get property value on non-property.\");\n\t\treturn p_->get(o_);\n\t}\n\n\tas_value_ptr as_value::get_property(const as_value_ptr& primitive) const\n\t{\n\t\tASSERT_LOG(is_property(), \"Attempt to get property value on non-property.\");\n\t\treturn p_->get(primitive);\n\t}\n\n\tvoid as_value::set_property_target(const as_object_ptr& target)\n\t{\n\t\tASSERT_LOG(is_property(), \"Attempt to set property target on non-property.\");\n\t\to_ = target;\n\t}\n\n\tas_property::as_property(const as_value_ptr& get, const as_value_ptr& set)\n\t{\n\t\tget_ = std::dynamic_pointer_cast<as_function>(get->to_object());\n\t\tset_ = std::dynamic_pointer_cast<as_function>(set->to_object());\n\t}\n\n\tvoid as_property::set(const as_object_ptr& target, const as_value_ptr& value)\n\t{\n\t\tif(target) {\n\t\t\tif(set_) {\n\t\t\t\tauto env = environment::create(target->get_player());\n\t\t\t\tenv->push(value);\n\t\t\t\t(*set_)(function_params(as_value::create(target), env, 1, env->get_top_index()));\n\t\t\t}\n\t\t} else {\n\t\t\tLOG_WARN(\"Tried to set property on null target.\");\n\t\t}\n\t}\n\n\tas_value_ptr as_property::get(const as_object_ptr& target)\n\t{\n\t\tas_value_ptr value = as_value::create();\n\t\tif(target) {\n\t\t\tif(get_) {\n\t\t\t\tauto env = environment::create(target->get_player());\n\t\t\t\tvalue = (*get_)(function_params(as_value::create(target), env, 0, 0));\n\t\t\t}\n\t\t} else {\n\t\t\tLOG_WARN(\"Tried to set property on null target.\");\n\t\t}\n\t\treturn value;\n\t}\n\n\tas_value_ptr as_property::get(const as_value_ptr& primitive)\n\t{\n\t\tif(get_) {\n\t\t\treturn (*get_)(function_params(primitive, nullptr, 0, 0));\n\t\t}\n\t\treturn nullptr;\n\t}\n\n\tas_function_ptr as_value::to_function()\n\t{\n\t\tif(type_ == ValueType::OBJECT && o_ != nullptr) {\n\t\t\t// XXX This is a little icky -- maybe as_object should have a virtual operator().\n\t\t\treturn std::dynamic_pointer_cast<as_function>(o_);\n\t\t}\n\t\tLOG_WARN(\"couldn't convert as_value to function.\");\n\t\treturn nullptr;\n\t}\n\n\tas_value_ptr as_value::find_property(const std::string& name)\n\t{\n\t\tswitch(type_) {\n\t\t\tcase ValueType::UNDEFINED:\n\t\t\tcase ValueType::NULL_VALUE:\n\t\t\tcase ValueType::PROPERTY:\n\t\t\t\tbreak;\n\t\t\tcase ValueType::STRING:\n\t\t\t\treturn player::get_builtin_string_method(name);\n\t\t\tcase ValueType::BOOLEAN:\n\t\t\t\treturn player::get_builtin_boolean_method(name);\n\t\t\tcase ValueType::NUMERIC:\n\t\t\t\treturn player::get_builtin_numeric_method(name);\n\t\t\tcase ValueType::OBJECT: {\n\t\t\t\tif(o_) {\n\t\t\t\t\treturn o_->get_member(name);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n}\n", "meta": {"hexsha": "d0fa10f3fadeaa104b333b74550854fd158272bb", "size": 7355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/as_value.cpp", "max_stars_repo_name": "sweetkristas/swiftly", "max_stars_repo_head_hexsha": "0b5c2badc88637b8bdaa841a45d1babd8f12a703", "max_stars_repo_licenses": ["BSL-1.0", "Zlib", "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/as_value.cpp", "max_issues_repo_name": "sweetkristas/swiftly", "max_issues_repo_head_hexsha": "0b5c2badc88637b8bdaa841a45d1babd8f12a703", "max_issues_repo_licenses": ["BSL-1.0", "Zlib", "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/as_value.cpp", "max_forks_repo_name": "sweetkristas/swiftly", "max_forks_repo_head_hexsha": "0b5c2badc88637b8bdaa841a45d1babd8f12a703", "max_forks_repo_licenses": ["BSL-1.0", "Zlib", "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.5523465704, "max_line_length": 100, "alphanum_fraction": 0.6700203943, "num_tokens": 2023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19378351145161626}}
{"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_BITWISE_FUNCTIONS_SIMD_SSE_SSE2_SHRI_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_BITWISE_FUNCTIONS_SIMD_SSE_SSE2_SHRI_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n#include <boost/simd/toolbox/bitwise/functions/shri.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/include/functions/simd/bitwise_or.hpp>\n#include <boost/simd/include/constants/int_splat.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/sdk/meta/make_dependent.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::shri_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<type8_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    typedef typename meta::make_dependent<int32_t,A0>::type int_t;\n\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef native<int_t, boost::simd::tag::sse_> gen_type;\n      result_type const Mask1 =  bitwise_cast<result_type>(boost::simd::integral_constant<gen_type, 0x00ff00ff>());\n      result_type const Mask2 =  bitwise_cast<result_type>(boost::simd::integral_constant<gen_type, 0xff00ff00>());\n      result_type tmp  = b_and(a0, Mask1);\n      result_type tmp1 = _mm_srli_epi16(tmp, a1);\n      tmp1 = b_and(tmp1, Mask1);\n      tmp = b_and(a0, Mask2);\n      result_type tmp3 = _mm_srli_epi16(tmp, a1);\n      return tmp1 | b_and(tmp3, Mask2);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::shri_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<type32_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef typename dispatch::meta::as_integer<A0>::type sint;\n      sint const that = _mm_srli_epi32(bitwise_cast<sint>(a0), int(a1));\n      return bitwise_cast<A0>(that);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::shri_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<type64_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef typename dispatch::meta::as_integer<A0>::type sint;\n      sint const that = _mm_srli_epi64(bitwise_cast<sint>(a0), int(a1));\n      return bitwise_cast<result_type>(that);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::shri_, boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<type16_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      return _mm_srli_epi16(a0, int(a1));\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "c4803f5193ea162fd0620da017a4bbc67a686ee9", "size": 3880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/bitwise/include/boost/simd/toolbox/bitwise/functions/simd/sse/sse2/shri.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/bitwise/include/boost/simd/toolbox/bitwise/functions/simd/sse/sse2/shri.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/bitwise/include/boost/simd/toolbox/bitwise/functions/simd/sse/sse2/shri.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.2765957447, "max_line_length": 115, "alphanum_fraction": 0.5407216495, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1937835096821536}}
{"text": "/*\r\n\tThis software is distributed under MIT License, which means:\r\n\t\t- Do whatever you want\r\n\t\t- Please keep this notice and include the license file to your project\r\n\t\t- I provide no warranty\r\n\r\n\tCreated by Kyrylo Sovailo (github.com/Meta-chan, k.sovailo@gmail.com)\r\n\tReinventing bicycles since 2020\r\n*/\r\n\r\n#include \"../header/p6_construction.hpp\"\r\n#include \"../header/p6_linear_material.hpp\"\r\n#include \"../header/p6_nonlinear_material.hpp\"\r\n#include \"../header/p6_file.hpp\"\r\n#include <cassert>\r\n#include <Eigen>\r\n\r\nclass p6::Construction::Vector : public Eigen::Vector<p6::real, Eigen::Dynamic>\r\n{\r\npublic:\r\n\tusing Eigen::Vector<p6::real, Eigen::Dynamic>::Vector;\r\n};\r\n\r\nclass p6::Construction::Matrix : public Eigen::Matrix<p6::real, Eigen::Dynamic, Eigen::Dynamic> {};\r\n\r\np6::uint p6::Construction::create_node() noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tNode node;\r\n\tnode.freedom = 0;\r\n\tnode.coord = Coord(0.0, 0.0);\r\n\tnode.angle = 0.0;\r\n\tnode.coord_simulated = Coord(0.0, 0.0);\r\n\t_node.push_back(node);\r\n\treturn _node.size() - 1;\r\n}\r\n\r\nvoid p6::Construction::delete_node(uint node) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tfor (uint i = _stick.size() - 1; i != (uint)-1; i--)\r\n\t{\r\n\t\tif (_stick[i].node[0] == node || _stick[i].node[1] == node)\r\n\t\t{\r\n\t\t\t_stick.erase(_stick.begin() + i);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (_stick[i].node[0] > node) _stick[i].node[0]--;\r\n\t\t\tif (_stick[i].node[1] > node) _stick[i].node[1]--;\r\n\t\t}\r\n\t}\r\n\tfor (uint i = _force.size() - 1; i != (uint)-1; i--)\r\n\t{\r\n\t\tif (_force[i].node == node) _force.erase(_force.begin() + i);\r\n\t\telse if (_force[i].node > node) _force[i].node--;\r\n\t}\r\n\t_node.erase(_node.begin() + node);\r\n}\r\n\r\nvoid p6::Construction::set_node_coord(uint node, Coord coord) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tassert(coord.x == coord.x);\r\n\tassert(abs(coord.x) != std::numeric_limits<real>::infinity());\r\n\tassert(coord.y == coord.y);\r\n\tassert(abs(coord.y) != std::numeric_limits<real>::infinity());\r\n\t_node[node].coord = coord;\r\n}\r\n\r\nvoid p6::Construction::set_node_freedom(uint node, unsigned char freedom) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tassert(freedom <= 2);\r\n\t_node[node].freedom = freedom;\r\n}\r\n\r\nvoid p6::Construction::set_node_rail_angle(uint node, real angle) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tassert(_node[node].freedom == 1);\r\n\tassert(angle == angle);\r\n\tassert(abs(angle) != std::numeric_limits<real>::infinity());\r\n\t_node[node].angle = angle;\r\n}\r\n\r\np6::uint p6::Construction::get_node_count() const noexcept\r\n{\r\n\treturn _node.size();\r\n}\r\n\r\np6::Coord p6::Construction::get_node_coord(uint node) const noexcept\r\n{\r\n\treturn _simulation ? _node[node].coord_simulated : _node[node].coord;\r\n}\r\n\r\nunsigned char p6::Construction::get_node_freedom(uint node) const noexcept\r\n{\r\n\treturn _node[node].freedom;\r\n}\r\n\r\np6::real p6::Construction::get_node_rail_angle(uint node) const noexcept\r\n{\r\n\tassert(_node[node].freedom == 1);\r\n\treturn _node[node].angle;\r\n}\r\n\r\np6::uint p6::Construction::create_stick(const uint node[2]) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tassert(node[0] != node[1]);\r\n\tassert(node[0] < _node.size());\r\n\tassert(node[1] < _node.size());\r\n\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t{\r\n\t\tif((_stick[i].node[0] == node[0] && _stick[i].node[0] == node[1])\r\n\t\t&& (_stick[i].node[1] == node[1] && _stick[i].node[1] == node[1]))\r\n\t\t\treturn i;\r\n\t}\r\n\r\n\tStick stick;\r\n\tstick.node[0] = node[0];\r\n\tstick.node[1] = node[1];\r\n\tstick.material = (uint)-1;\r\n\tstick.area = 0.0;\r\n\t_stick.push_back(stick);\r\n\treturn _stick.size() - 1;\r\n}\r\n\r\nvoid p6::Construction::delete_stick(uint stick) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\t_stick.erase(_stick.begin() + stick);\r\n}\r\n\r\nvoid p6::Construction::set_stick_material(uint stick, uint material) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\t_stick[stick].material = material;\r\n}\r\n\r\nvoid p6::Construction::set_stick_area(uint stick, real area) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tassert(area == area);\r\n\t_stick[stick].area = area;\r\n}\r\n\r\np6::uint p6::Construction::get_stick_count() const noexcept\r\n{\r\n\treturn _stick.size();\r\n}\r\n\r\np6::uint p6::Construction::get_stick_material(uint stick) const noexcept\r\n{\r\n\treturn _stick[stick].material;\r\n}\r\n\r\np6::real p6::Construction::get_stick_area(uint stick) const noexcept\r\n{\r\n\treturn _stick[stick].area;\r\n}\r\n\r\nvoid p6::Construction::get_stick_node(uint stick, uint node[2]) const noexcept\r\n{\r\n\tnode[0] = _stick[stick].node[0];\r\n\tnode[1] = _stick[stick].node[1];\r\n}\r\n\r\np6::real p6::Construction::get_stick_length(uint stick) const noexcept\r\n{\r\n\tconst Node *node[2] = { &_node[_stick[stick].node[0]], &_node[_stick[stick].node[1]] };\r\n\treturn _simulation ?\r\n\t\tnode[0]->coord_simulated.distance(node[1]->coord_simulated) :\r\n\t\tnode[0]->coord.distance(node[1]->coord);\r\n}\r\n\r\np6::real p6::Construction::get_stick_strain(uint stick) const noexcept\r\n{\r\n\tassert(_simulation);\r\n\tconst Node *node[2] = { &_node[_stick[stick].node[0]], &_node[_stick[stick].node[1]] };\r\n\treturn (\r\n\t\tnode[0]->coord_simulated.distance(node[1]->coord_simulated) /\r\n\t\tnode[0]->coord.distance(node[1]->coord)\r\n\t\t) - 1.0;\r\n}\r\n\r\np6::real p6::Construction::get_stick_force(uint stick) const noexcept\r\n{\r\n\tassert(_simulation);\r\n\treturn _stick[stick].area * _material[_stick[stick].material]->stress(get_stick_strain(stick));\r\n}\r\n\r\np6::uint p6::Construction::create_force(uint node) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tassert(node < _node.size());\r\n\tForce force;\r\n\tforce.node = node;\r\n\tforce.direction = Coord(0.0, 0.0);\r\n\t_force.push_back(force);\r\n\treturn _force.size() - 1;\r\n}\r\n\r\nvoid p6::Construction::delete_force(uint force) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\t_force.erase(_force.begin() + force);\r\n}\r\n\r\nvoid p6::Construction::set_force_direction(uint force, Coord direction) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tassert(direction.x == direction.x);\r\n\tassert(direction.y == direction.y);\r\n\t_force[force].direction = direction;\r\n}\r\n\r\np6::uint p6::Construction::get_force_count() const noexcept\r\n{\r\n\treturn _force.size();\r\n}\r\n\r\np6::Coord p6::Construction::get_force_direction(uint force) const noexcept\r\n{\r\n\treturn _force[force].direction;\r\n}\r\n\r\np6::uint p6::Construction::get_force_node(uint force) const noexcept\r\n{\r\n\treturn _force[force].node;\r\n}\r\n\r\np6::uint p6::Construction::create_linear_material(const String name, real modulus)\r\n{\r\n\tassert(!_simulation);\r\n\tfor (uint i = 0; i < _material.size(); i++)\r\n\t{\r\n\t\tif (name == _material[i]->name())\r\n\t\t{\r\n\t\t\tMaterial *material = new LinearMaterial(name, modulus);\r\n\t\t\tdelete _material[i];\r\n\t\t\t_material[i] = material;\r\n\t\t\treturn i;\r\n\t\t}\r\n\t}\r\n\t_material.push_back(new LinearMaterial(name, modulus));\r\n\treturn _material.size() - 1;\r\n}\r\n\r\np6::uint p6::Construction::create_nonlinear_material(const String name, const String formula)\r\n{\r\n\tassert(!_simulation);\r\n\tfor (uint i = 0; i < _material.size(); i++)\r\n\t{\r\n\t\tif (name == _material[i]->name())\r\n\t\t{\r\n\t\t\tMaterial *material = new NonlinearMaterial(name, formula);\r\n\t\t\tdelete _material[i];\r\n\t\t\t_material[i] = material;\r\n\t\t\treturn i;\r\n\t\t}\r\n\t}\r\n\r\n\t_material.push_back(new NonlinearMaterial(name, formula));\r\n\treturn _material.size() - 1;\r\n}\r\n\r\nvoid p6::Construction::delete_material(uint material) noexcept\r\n{\r\n\tassert(!_simulation);\r\n\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t{\r\n\t\tif (_stick[i].material == material) _stick[i].material = (uint)-1;\r\n\t}\r\n\tdelete _material[material];\r\n\t_material.erase(_material.begin() + material);\r\n}\r\n\r\np6::uint p6::Construction::get_material_count() const noexcept\r\n{\r\n\treturn _material.size();\r\n}\r\n\r\np6::String p6::Construction::get_material_name(uint material) const noexcept\r\n{\r\n\treturn _material[material]->name();\r\n}\r\n\r\np6::Material::Type p6::Construction::get_material_type(uint material) const noexcept\r\n{\r\n\treturn _material[material]->type();\r\n}\r\n\r\np6::real p6::Construction::get_material_modulus(uint material) const noexcept\r\n{\r\n\tassert(_material[material]->type() == Material::Type::linear);\r\n\treturn ((LinearMaterial*)_material[material])->modulus();\r\n}\r\n\r\np6::String p6::Construction::get_material_formula(uint material) const noexcept\r\n{\r\n\tassert(_material[material]->type() == Material::Type::nonlinear);\r\n\treturn ((NonlinearMaterial*)_material[material])->formula();\r\n}\r\n\r\nvoid p6::Construction::save(const String filepath) const\r\n{\r\n\t//Open file\r\n\tOutputFile file(filepath);\r\n\tif (!file.ok()) throw std::runtime_error(\"File cannot be opened for write\");\r\n\tHeader header;\r\n\theader.node = _node.size();\r\n\theader.stick = _stick.size();\r\n\theader.force = _force.size();\r\n\theader.material = _material.size();\r\n\tfile.write(&header, sizeof(Header));\r\n\r\n\t//Nodes\r\n\tfor (uint i = 0; i < _node.size(); i++)\r\n\t{\r\n\t\tfile.write(&_node[i], sizeof(StaticNode));\r\n\t}\r\n\r\n\t//Sticks\r\n\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t{\r\n\t\tfile.write(&_stick[i], sizeof(Stick));\r\n\t}\r\n\r\n\t//Forces\r\n\tfor (uint i = 0; i < _force.size(); i++)\r\n\t{\r\n\t\tfile.write(&_force[i], sizeof(Force));\r\n\t}\r\n\r\n\t//Materials\r\n\tfor (uint i = 0; i < _material.size(); i++)\r\n\t{\r\n\t\t//Name\r\n\t\tString name = _material[i]->name();\r\n\t\tuint len = name.size();\r\n\t\tfile.write(&len, sizeof(uint));\r\n\t\tfile.write(name.data(), len);\r\n\r\n\t\t//Type\r\n\t\tMaterial::Type type = _material[i]->type();\r\n\t\tfile.write(&type, sizeof(Material::Type));\r\n\r\n\t\tif (type == Material::Type::linear)\r\n\t\t{\r\n\t\t\t//Modulus\r\n\t\t\treal modulus = ((LinearMaterial*)_material[i])->modulus();\r\n\t\t\tfile.write(&modulus, sizeof(real));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//Formula\r\n\t\t\tString formula = ((NonlinearMaterial*)_material[i])->formula();\r\n\t\t\tlen = formula.size();\r\n\t\t\tfile.write(&len, sizeof(uint));\r\n\t\t\tfile.write(formula.data(), len);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid p6::Construction::load(const String filepath)\r\n{\r\n\t//Open file\r\n\tInputFile file(filepath);\r\n\tif (!file.ok()) throw std::runtime_error(\"File cannot be opened for read\");\r\n\tHeader header, sample;\r\n\tfile.read(&header, sizeof(Header));\r\n\tif (memcmp(header.signature, sample.signature, 8) != 0) throw (\"Invalid file format\");\r\n\t\r\n\t//Nodes\r\n\t_node.resize(header.node);\r\n\tfor (uint i = 0; i < _node.size(); i++)\r\n\t{\r\n\t\tfile.read(&_node[i], sizeof(StaticNode));\r\n\t}\r\n\r\n\t//Sticks\r\n\t_stick.resize(header.stick);\r\n\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t{\r\n\t\tfile.read(&_stick[i], sizeof(Stick));\r\n\t}\r\n\r\n\t//Forces\r\n\t_force.resize(header.force);\r\n\tfor (uint i = 0; i < _force.size(); i++)\r\n\t{\r\n\t\tfile.read(&_force[i], sizeof(Force));\r\n\t}\r\n\r\n\t//Materials\r\n\tfor (uint i = 0; i < _material.size(); i++) delete _material[i];\r\n\t_material.resize(header.material);\r\n\tfor (uint i = 0; i < _material.size(); i++)\r\n\t{\r\n\t\t//Name\r\n\t\tuint len;\r\n\t\tfile.read(&len, sizeof(uint));\r\n\t\tString name(len, '\\0');\r\n\t\tfile.read(&name[0], len);\r\n\r\n\t\t//Type\r\n\t\tMaterial::Type type;\r\n\t\tfile.read(&type, sizeof(Material::Type));\r\n\r\n\t\tif (type == Material::Type::linear)\r\n\t\t{\r\n\t\t\t//Modulus\r\n\t\t\treal modulus;\r\n\t\t\tfile.read(&modulus, sizeof(real));\r\n\t\t\t_material[i] = new LinearMaterial(name, modulus);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//Formula\r\n\t\t\tfile.read(&len, sizeof(uint));\r\n\t\t\tString formula(len, '\\0');\r\n\t\t\tfile.read(&formula[0], len);\r\n\t\t\t_material[i] = new NonlinearMaterial(name, formula);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid p6::Construction::import(const String filepath)\r\n{\r\n\t//Open file\r\n\tInputFile file(filepath);\r\n\tif (!file.ok()) throw std::runtime_error(\"File cannot be opened for read\");\r\n\tHeader header, sample;\r\n\tfile.read(&header, sizeof(Header));\r\n\tif (memcmp(header.signature, sample.signature, 8) != 0) throw (\"Invalid file format\");\r\n\r\n\tuint old_node_size = _node.size();\r\n\tuint old_stick_size = _stick.size();\r\n\tuint old_force_size = _force.size();\r\n\tuint old_material_size = _material.size();\r\n\r\n\t//Nodes\r\n\t_node.resize(old_node_size + header.node);\r\n\tfor (uint i = old_node_size; i < _node.size(); i++)\r\n\t{\r\n\t\tfile.read(&_node[i], sizeof(StaticNode));\r\n\t}\r\n\r\n\t//Sticks\r\n\t_stick.resize(old_stick_size + header.stick);\r\n\tfor (uint i = old_stick_size; i < _stick.size(); i++)\r\n\t{\r\n\t\tfile.read(&_stick[i], sizeof(Stick));\r\n\t\t_stick[i].node[0] += old_node_size;\r\n\t\t_stick[i].node[1] += old_node_size;\r\n\t\t_stick[i].material += old_material_size;\r\n\t}\r\n\r\n\t//Forces\r\n\t_force.resize(old_force_size + header.force);\r\n\tfor (uint i = old_force_size; i < _force.size(); i++)\r\n\t{\r\n\t\tfile.read(&_force[i], sizeof(Force));\r\n\t\t_force[i].node += old_node_size;\r\n\t}\r\n\r\n\t//Materials\r\n\tfor (uint i = 0; i < header.material; i++)\r\n\t{\r\n\t\t//Name\r\n\t\tuint len;\r\n\t\tfile.read(&len, sizeof(uint));\r\n\t\tString name(len, '\\0');\r\n\t\tfile.read(&name[0], len);\r\n\r\n\t\t//Find existing material\r\n\t\tuint existing_material = (uint)-1;\r\n\t\tfor (uint j = 0; j < old_material_size; j++)\r\n\t\t{\r\n\t\t\tif (_material[j]->name() == name)\r\n\t\t\t{\r\n\t\t\t\texisting_material = j;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Type\r\n\t\tMaterial::Type type;\r\n\t\tfile.read(&type, sizeof(Material::Type));\r\n\r\n\t\t//Creating material\r\n\t\tMaterial *new_material = nullptr;\r\n\t\tif (type == Material::Type::linear)\r\n\t\t{\r\n\t\t\t//Modulus\r\n\t\t\treal modulus;\r\n\t\t\tfile.read(&modulus, sizeof(real));\r\n\t\t\tif (existing_material == (uint)-1) new_material = new LinearMaterial(name, modulus);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//Formula\r\n\t\t\tfile.read(&len, sizeof(uint));\r\n\t\t\tString formula(len, '\\0');\r\n\t\t\tfile.read(&formula[0], len);\r\n\t\t\tif (existing_material == (uint)-1) new_material = new NonlinearMaterial(name, formula);\r\n\t\t}\r\n\r\n\t\t//Adding material to materials\r\n\t\tif (existing_material == (uint)-1)\r\n\t\t{\r\n\t\t\t_material.push_back(new_material);\r\n\t\t\texisting_material = _material.size() - 1;\r\n\t\t}\r\n\r\n\t\t//Correcting sticks\r\n\t\tfor (uint i = old_stick_size; i < _stick.size(); i++)\r\n\t\t{\r\n\t\t\tif (_stick[i].material == old_material_size + i) _stick[i].material = existing_material;\r\n\t\t}\r\n\t}\r\n}\r\n\r\np6::uint p6::Construction::_node_equation_fx(uint free2d) const noexcept\r\n{\r\n\tassert(free2d < _nfree2d);\r\n\treturn 2 * free2d;\r\n}\r\n\r\np6::uint p6::Construction::_node_equation_fy(uint free2d) const noexcept\r\n{\r\n\tassert(free2d < _nfree2d);\r\n\treturn 2 * free2d + 1;\r\n}\r\n\r\np6::uint p6::Construction::_node_equation_fr(uint free1d) const noexcept\r\n{\r\n\tassert(free1d < _nfree1d);\r\n\treturn 2 * _nfree2d + free1d;\r\n}\r\n\r\np6::uint p6::Construction::_equation_number() const noexcept\r\n{\r\n\treturn 2 * _nfree2d + _nfree1d;\r\n}\r\n\r\np6::uint p6::Construction::_node_variable_x(uint free2d) const noexcept\r\n{\r\n\tassert(free2d < _nfree2d);\r\n\treturn 2 * free2d;\r\n}\r\n\r\np6::uint p6::Construction::_node_variable_y(uint free2d) const noexcept\r\n{\r\n\tassert(free2d < _nfree2d);\r\n\treturn 2 * free2d + 1;\r\n}\r\n\r\np6::uint p6::Construction::_node_variable_r(uint free1d) const noexcept\r\n{\r\n\tassert(free1d < _nfree1d);\r\n\treturn 2 * _nfree2d + free1d;\r\n}\r\n\r\np6::uint p6::Construction::_variable_number() const noexcept\r\n{\r\n\treturn 2 * _nfree2d + _nfree1d;\r\n}\r\n\r\nvoid p6::Construction::_check_materials_specified() const\r\n{\r\n\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t{\r\n\t\tassert(_stick[i].material < _material.size() || _stick[i].material == (uint)-1);\r\n\t\tif (_stick[i].material == (uint)-1) throw std::runtime_error(\"Material is not specified\");\r\n\t}\r\n}\r\n\r\nvoid p6::Construction::_create_map(std::vector<uint> *node_to_free) noexcept\r\n{\r\n\t_nfree2d = 0;\r\n\t_nfree1d = 0;\r\n\tnode_to_free->resize(_node.size(), (uint)-1);\r\n\tfor (uint i = 0; i < _node.size(); i++)\r\n\t{\r\n\t\tif (_node[i].freedom == 1)\r\n\t\t{\r\n\t\t\tnode_to_free->at(i) = _nfree1d;\r\n\t\t\t_nfree1d++;\r\n\t\t}\r\n\t\telse if (_node[i].freedom == 2)\r\n\t\t{\r\n\t\t\tnode_to_free->at(i) = _nfree2d;\r\n\t\t\t_nfree2d++;\r\n\t\t}\r\n\t}\r\n}\r\n\r\np6::real p6::Construction::_get_tolerance() const noexcept\r\n{\r\n\treal minforce = std::numeric_limits<real>::infinity();\r\n\tfor (uint i = 0; i < _force.size(); i++)\r\n\t{\r\n\t\treal newforce = _force[i].direction.norm();\r\n\t\tif (newforce < minforce) minforce = newforce;\r\n\t}\r\n\treturn minforce / 1000.0;\r\n}\r\n\r\nvoid p6::Construction::_create_vectors(\r\n\tconst std::vector <uint> *node_to_free,\r\n\tVector *s,\r\n\tVector *z,\r\n\tVector *m,\r\n\tMatrix *d) const noexcept\r\n{\r\n\ts->resize(_variable_number());\r\n\tfor (uint i = 0; i < _node.size(); i++)\r\n\t{\r\n\t\tif (_node[i].freedom == 1)\r\n\t\t{\r\n\t\t\tuint free1d = node_to_free->at(i);\r\n\t\t\t(*s)(_node_variable_r(free1d)) = 0.0;\r\n\t\t}\r\n\t\telse if (_node[i].freedom == 2)\r\n\t\t{\r\n\t\t\tuint free2d = node_to_free->at(i);\r\n\t\t\t(*s)(_node_variable_x(free2d)) = _node[i].coord.x;\r\n\t\t\t(*s)(_node_variable_y(free2d)) = _node[i].coord.y;\r\n\t\t}\r\n\t}\r\n\tz->resize(_equation_number());\r\n\tz->setZero();\r\n\tm->resize(_equation_number());\r\n\tm->setZero();\r\n\td->resize(_equation_number(), _variable_number());\r\n\td->setZero();\r\n}\r\n\r\nvoid p6::Construction::_set_z_to_external_forces(\r\n\tconst std::vector <uint> *node_to_free,\r\n\tVector *z) const noexcept\r\n{\r\n\tfor (uint i = 0; i < _force.size(); i++)\r\n\t{\r\n\t\tuint node = _force[i].node;\r\n\t\tif (_node[node].freedom == 1)\r\n\t\t{\r\n\t\t\tuint free1d = node_to_free->at(node);\r\n\t\t\treal angle = _node[node].angle;\r\n\t\t\t(*z)(_node_variable_r(free1d)) = _force[i].direction.x * cos(angle) + _force[i].direction.y * sin(angle);\r\n\t\t}\r\n\t\telse if (_node[node].freedom == 2)\r\n\t\t{\r\n\t\t\tuint free2d = node_to_free->at(node);\r\n\t\t\t(*z)(_node_variable_x(free2d)) = _force[i].direction.x;\r\n\t\t\t(*z)(_node_variable_y(free2d)) = _force[i].direction.y;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid p6::Construction::_set_d_to_zero(\r\n\tconst std::vector <uint> *node_to_free,\r\n\tMatrix *d) const noexcept\r\n{\r\n\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t{\r\n\t\tconst uint *node = _stick[i].node;\r\n\t\tfor (uint j = 0; j < 2; j++)\r\n\t\t{\r\n\t\t\t//If current point is fixed on rail\r\n\t\t\tif (_node[node[j]].freedom == 1)\r\n\t\t\t{\r\n\t\t\t\t//It sets own derivatives on own coordinates\r\n\t\t\t\tuint free1d = node_to_free->at(node[j]);\r\n\t\t\t\t(*d)(_node_equation_fr(free1d), _node_variable_r(free1d)) = 0.0;\r\n\r\n\t\t\t\t//And own derivatives on coordinates of other point\r\n\t\t\t\tif (_node[node[j ^ 1]].freedom == 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint other_free1d = node_to_free->at(node[j ^ 1]);\r\n\t\t\t\t\t(*d)(_node_equation_fr(free1d), _node_variable_r(other_free1d)) = 0.0;\r\n\t\t\t\t}\r\n\t\t\t\telse if (_node[node[j ^ 1]].freedom == 2)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint other_free2d = node_to_free->at(node[j ^ 1]);\r\n\t\t\t\t\t(*d)(_node_equation_fr(free1d), _node_variable_x(other_free2d)) = 0.0;\r\n\t\t\t\t\t(*d)(_node_equation_fr(free1d), _node_variable_y(other_free2d)) = 0.0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t//If current point is free\r\n\t\t\telse if (_node[node[j]].freedom == 2)\r\n\t\t\t{\r\n\t\t\t\t//It sets own derivatives on own coordinates\r\n\t\t\t\tuint free2d = node_to_free->at(node[j]);\r\n\t\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_x(free2d)) = 0.0;\r\n\t\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_y(free2d)) = 0.0;\r\n\t\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_x(free2d)) = 0.0;\r\n\t\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_y(free2d)) = 0.0;\r\n\r\n\t\t\t\t//And own derivatives on coordinates of other point\r\n\t\t\t\tif (_node[node[j ^ 1]].freedom == 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint other_free1d = node_to_free->at(node[j ^ 1]);\r\n\t\t\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_r(other_free1d)) = 0.0;\r\n\t\t\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_r(other_free1d)) = 0.0;\r\n\t\t\t\t}\r\n\t\t\t\telse if (_node[node[j ^ 1]].freedom == 2)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint other_free2d = node_to_free->at(node[j ^ 1]);\r\n\t\t\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_x(other_free2d)) = 0.0;\r\n\t\t\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_y(other_free2d)) = 0.0;\r\n\t\t\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_x(other_free2d)) = 0.0;\r\n\t\t\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_y(other_free2d)) = 0.0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\np6::Coord p6::Construction::_get_delta(\r\n\tuint stick,\r\n\tconst std::vector <uint> *node_to_free,\r\n\tconst Vector *s) const noexcept\r\n{\r\n\tconst uint *node = _stick[stick].node;\r\n\tCoord coord[2];\r\n\tfor (uint i = 0; i < 2; i++)\r\n\t{\r\n\t\tif (_node[node[i]].freedom == 1)\r\n\t\t{\r\n\t\t\tuint free1d = node_to_free->at(node[i]);\r\n\t\t\treal angle = _node[node[i]].angle;\r\n\t\t\tcoord[i] = _node[node[i]].coord + Coord(cos(angle), sin(angle)) * (*s)(_node_variable_r(free1d));\r\n\t\t}\r\n\t\telse if (_node[node[i]].freedom == 2)\r\n\t\t{\r\n\t\t\tuint free2d = node_to_free->at(node[i]);\r\n\t\t\tcoord[i] = Coord((*s)(_node_variable_x(free2d)), (*s)(_node_variable_y(free2d)));\r\n\t\t}\r\n\t\telse coord[i] = _node[node[i]].coord;\r\n\t}\r\n\treturn coord[1] - coord[0];\r\n}\r\n\r\nvoid p6::Construction::_modify_z_with_stick_force(\r\n\tuint stick,\r\n\tconst std::vector <uint> *node_to_free,\r\n\tconst Vector *s,\r\n\tVector *z) const noexcept\r\n{\r\n\tconst Material *material = _material[_stick[stick].material];\r\n\tconst uint *node = _stick[stick].node;\r\n\tCoord delta = _get_delta(stick, node_to_free, s);\r\n\treal length = delta.norm();\r\n\treal initial_length = _node[node[0]].coord.distance(_node[node[1]].coord);\r\n\treal force = _stick[stick].area * material->stress(length / initial_length - 1.0);\r\n\r\n\tfor (uint i = 0; i < 2; i++)\r\n\t{\r\n\t\tif (_node[node[i]].freedom == 1)\r\n\t\t{\r\n\t\t\tuint free1d = node_to_free->at(node[i]);\r\n\t\t\treal sign = i == 0 ? 1.0 : -1.0;\r\n\t\t\t(*z)(_node_variable_r(free1d)) +=\r\n\t\t\t\tcos(_node[node[i]].angle) * sign * force * delta.x / length +\r\n\t\t\t\tsin(_node[node[i]].angle) * sign * force * delta.y / length;\r\n\t\t}\r\n\t\telse if (_node[node[i]].freedom == 2)\r\n\t\t{\r\n\t\t\tuint free2d = node_to_free->at(node[i]);\r\n\t\t\treal sign = i == 0 ? 1.0 : -1.0;\r\n\t\t\t(*z)(_node_variable_x(free2d)) += sign * force * delta.x / length;\r\n\t\t\t(*z)(_node_variable_y(free2d)) += sign * force * delta.y / length;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid p6::Construction::_modify_d_with_stick_force(\r\n\tuint stick,\r\n\tconst std::vector <uint> *node_to_free,\r\n\tconst Vector *s,\r\n\tMatrix *d) const noexcept\r\n{\r\n\tconst uint *node = _stick[stick].node;\r\n\tconst Material *material = _material[_stick[stick].material];\r\n\tCoord delta = _get_delta(stick, node_to_free, s);\r\n\treal length = delta.norm();\r\n\treal initial_length = _node[node[0]].coord.distance(_node[node[1]].coord);\r\n\treal strain = length / initial_length - 1.0;\r\n\treal force = _stick[stick].area * material->stress(strain);\r\n\r\n\tfor (uint i = 0; i < 2; i++)\r\n\t{\r\n\t\tCoord deltaoi = (i == 0) ? delta : delta * (-1.0);\r\n\r\n\t\t//If current point is fixed on rail\r\n\t\tif (_node[node[i]].freedom == 1)\r\n\t\t{\r\n\t\t\t//It sets own derivatives on own coordinates\r\n\t\t\tuint free1d = node_to_free->at(node[i]);\r\n\t\t\treal anglei = _node[node[i]].angle;\r\n\t\t\treal dl_dri = (-deltaoi.x * cos(anglei) - deltaoi.y * sin(anglei)) / length;\r\n\t\t\treal df_dri = _stick[stick].area * material->derivative(strain) * dl_dri / initial_length;\r\n\t\t\t(*d)(_node_equation_fr(free1d), _node_variable_r(free1d)) += (\r\n\t\t\t\tcos(anglei) * ((df_dri * deltaoi.x + force * (-cos(anglei))) * length - dl_dri * force * deltaoi.x) +\r\n\t\t\t\tsin(anglei) * ((df_dri * deltaoi.y + force * (-sin(anglei))) * length - dl_dri * force * deltaoi.y)\r\n\t\t\t\t) / sqr(length);\r\n\r\n\t\t\t//And own derivatives on coordinates of other point\r\n\t\t\tif (_node[node[i ^ 1]].freedom == 1)\r\n\t\t\t{\r\n\t\t\t\tuint other_free1d = node_to_free->at(node[i ^ 1]);\r\n\t\t\t\treal angleo = _node[node[i ^ 1]].angle;\r\n\t\t\t\treal dl_dro = (deltaoi.x * cos(angleo) + deltaoi.y * sin(angleo)) / length;\r\n\t\t\t\treal df_dro = _stick[stick].area * material->derivative(strain) * dl_dro / initial_length;\r\n\t\t\t\t(*d)(_node_equation_fr(free1d), _node_variable_r(other_free1d)) += (\r\n\t\t\t\t\tcos(anglei) * ((df_dro * deltaoi.x + force * cos(angleo)) * length - dl_dro * force * deltaoi.x) +\r\n\t\t\t\t\tsin(anglei) * ((df_dro * deltaoi.y + force * sin(angleo)) * length - dl_dro * force * deltaoi.y)\r\n\t\t\t\t\t) / sqr(length);\r\n\t\t\t}\r\n\t\t\telse if (_node[node[i ^ 1]].freedom == 2)\r\n\t\t\t{\r\n\t\t\t\tuint other_free2d = node_to_free->at(node[i ^ 1]);\r\n\t\t\t\treal dl_dxo = deltaoi.x / length;\r\n\t\t\t\treal df_dxo = _stick[stick].area * material->derivative(strain) * dl_dxo / initial_length;\r\n\t\t\t\t(*d)(_node_equation_fr(free1d), _node_variable_x(other_free2d)) += (\r\n\t\t\t\t\tcos(anglei) * ((df_dxo * deltaoi.x + force * 1.0) * length - dl_dxo * force * deltaoi.x) +\r\n\t\t\t\t\tsin(anglei) * deltaoi.y * (df_dxo * length - dl_dxo * force)\r\n\t\t\t\t\t) / sqr(length);\r\n\t\t\t\treal dl_dyo = deltaoi.y / length;\r\n\t\t\t\treal df_dyo = _stick[stick].area * material->derivative(strain) * dl_dyo / initial_length;\r\n\t\t\t\t(*d)(_node_equation_fr(free1d), _node_variable_y(other_free2d)) += (\r\n\t\t\t\t\tcos(anglei) * deltaoi.x * (df_dyo * length - dl_dyo * force) +\r\n\t\t\t\t\tsin(anglei) * ((df_dyo * deltaoi.y + force * 1.0) * length - dl_dyo * force * deltaoi.y)\r\n\t\t\t\t\t) / sqr(length);\r\n\t\t\t}\r\n\t\t}\r\n\t\t//If current point is free\r\n\t\telse if (_node[node[i]].freedom == 2)\r\n\t\t{\r\n\t\t\t//It sets own derivatives on own coordinates\r\n\t\t\tuint free2d = node_to_free->at(node[i]);\r\n\t\t\t\r\n\t\t\treal dl_dxi = -deltaoi.x / length;\r\n\t\t\treal df_dxi = _stick[stick].area * material->derivative(strain) * dl_dxi / initial_length;\r\n\t\t\treal dfxi_dxi = ((df_dxi * deltaoi.x + force * (-1.0)) * length - dl_dxi * force * deltaoi.x) / sqr(length);\r\n\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_x(free2d)) += dfxi_dxi;\r\n\t\t\treal dl_dyi = -deltaoi.y / length;\r\n\t\t\treal df_dyi = _stick[stick].area * material->derivative(strain) * dl_dyi / initial_length;\r\n\t\t\treal dfxi_dyi = deltaoi.x * (df_dyi * length - dl_dyi * force) / sqr(length);\r\n\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_y(free2d)) += dfxi_dyi;\r\n\t\t\treal dfyi_dxi = deltaoi.y * (df_dxi * length - dl_dxi * force) / sqr(length);\r\n\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_x(free2d)) += dfyi_dxi;\r\n\t\t\treal dfyi_dyi = ((df_dyi * deltaoi.y + force * (-1.0)) * length - dl_dyi * force * deltaoi.y) / sqr(length);\r\n\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_y(free2d)) += dfyi_dyi;\r\n\r\n\t\t\t//And own derivatives on coordinates of other point\r\n\t\t\tif (_node[node[i ^ 1]].freedom == 1)\r\n\t\t\t{\r\n\t\t\t\tuint other_free1d = node_to_free->at(node[i ^ 1]);\r\n\t\t\t\treal angleo = _node[node[i ^ 1]].angle;\r\n\t\t\t\treal dl_dro = (deltaoi.x * cos(angleo) + deltaoi.y * sin(angleo)) / length;\r\n\t\t\t\treal df_dro = _stick[stick].area * material->derivative(strain) * dl_dro / initial_length;\r\n\t\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_r(other_free1d)) +=\r\n\t\t\t\t\t((df_dro * deltaoi.x + force * cos(angleo)) * length - dl_dro * force * deltaoi.x) / sqr(length);\r\n\t\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_r(other_free1d)) +=\r\n\t\t\t\t\t((df_dro * deltaoi.y + force * sin(angleo)) * length - dl_dro * force * deltaoi.y) / sqr(length);\r\n\t\t\t}\r\n\t\t\telse if (_node[node[i ^ 1]].freedom == 2)\r\n\t\t\t{\r\n\t\t\t\tuint other_free2d = node_to_free->at(node[i ^ 1]);\r\n\t\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_x(other_free2d)) -= dfxi_dxi;\r\n\t\t\t\t(*d)(_node_equation_fx(free2d), _node_variable_y(other_free2d)) -= dfxi_dyi;\r\n\t\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_x(other_free2d)) -= dfyi_dxi;\r\n\t\t\t\t(*d)(_node_equation_fy(free2d), _node_variable_y(other_free2d)) -= dfyi_dyi;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\np6::real p6::Construction::_get_residuum(const Vector *z) const noexcept\r\n{\r\n\treal error = 0.0;\r\n\tfor (int i = 0; i < z->rows(); i++)\r\n\t{\r\n\t\treal newabs = abs((*z)(i));\r\n\t\tif (newabs > error) error = newabs;\r\n\t}\r\n\treturn error;\r\n}\r\n\r\nvoid p6::Construction::_apply_state_vector(\r\n\tconst std::vector<uint> *node_to_free,\r\n\tconst Vector *s) noexcept\r\n{\r\n\tfor (uint i = 0; i < _node.size(); i++)\r\n\t{\r\n\t\tif (_node[i].freedom == 1)\r\n\t\t{\r\n\t\t\tuint free1d = node_to_free->at(i);\r\n\t\t\treal angle = _node[i].angle;\r\n\t\t\t_node[i].coord_simulated = _node[i].coord + Coord(cos(angle), sin(angle)) * (*s)(_node_variable_r(free1d));\r\n\t\t}\r\n\t\telse if (_node[i].freedom == 2)\r\n\t\t{\r\n\t\t\tuint free2d = node_to_free->at(i);\r\n\t\t\t_node[i].coord_simulated = Coord((*s)(_node_variable_x(free2d)), (*s)(_node_variable_y(free2d)));\r\n\t\t}\r\n\t\telse _node[i].coord_simulated = _node[i].coord;\r\n\t}\r\n}\r\n\r\nbool p6::Construction::_is_adequate(\r\n\tconst Vector *m,\r\n\tconst std::vector <uint> *node_to_free,\r\n\tconst Vector *s) const noexcept\r\n{\r\n\tfor (int i = 0; i < m->rows(); i++)\r\n\t{\r\n\t\tif ((*m)(i) != (*m)(i)) return false;\r\n\t\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t\t{\r\n\t\t\tconst uint *node = _stick[i].node;\r\n\t\t\tCoord delta = _get_delta(i, node_to_free, s);\r\n\t\t\treal length = delta.norm();\r\n\t\t\tfor (uint j = 0; j < 2; j++)\r\n\t\t\t{\r\n\t\t\t\tif (_node[node[j]].freedom == 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint free1d = node_to_free->at(node[j]);\r\n\t\t\t\t\treal modification = abs((*m)(_node_equation_fr(free1d)));\r\n\t\t\t\t\tif (modification > length * 0.01) return false;\r\n\t\t\t\t}\r\n\t\t\t\telse if (_node[node[j]].freedom == 2)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint free2d = node_to_free->at(node[j]);\r\n\t\t\t\t\treal modification = Coord((*m)(_node_equation_fx(free2d)), (*m)(_node_equation_fy(free2d))).norm();\r\n\t\t\t\t\tif (modification > length * 0.01) return false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\np6::real  p6::Construction::_get_flow_coefficient(\r\n\tconst std::vector <uint> *node_to_free,\r\n\tconst Vector *s,\r\n\tconst Vector *z) const noexcept\r\n{\r\n\treal coef = std::numeric_limits<real>::infinity();\r\n\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t{\r\n\t\tconst uint *node = _stick[i].node;\r\n\t\tCoord delta = _get_delta(i, node_to_free, s);\r\n\t\treal length = delta.norm();\r\n\t\treal initial_length = _node[node[0]].coord.distance(_node[node[1]].coord);\r\n\t\treal strain = length / initial_length - 1.0;\r\n\t\treal df_dl = _stick[i].area * _material[_stick[i].material]->derivative(strain) / initial_length;\r\n\t\tif (1.0 / df_dl < coef) coef = 1.0 / df_dl;\r\n\r\n\t\tfor (uint j = 0; j < 2; j++)\r\n\t\t{\r\n\t\t\tif (_node[node[j]].freedom == 1)\r\n\t\t\t{\r\n\t\t\t\tuint free1d = node_to_free->at(node[j]);\r\n\t\t\t\treal unbalanced_force = abs((*z)(_node_equation_fr(free1d)));\r\n\t\t\t\tif (length / unbalanced_force < coef) coef = length / unbalanced_force;\t\t\r\n\t\t\t}\r\n\t\t\telse if (_node[node[j]].freedom == 2)\r\n\t\t\t{\r\n\t\t\t\tuint free2d = node_to_free->at(node[j]);\r\n\t\t\t\treal unbalanced_force = Coord((*z)(_node_equation_fx(free2d)), (*z)(_node_equation_fy(free2d))).norm();\r\n\t\t\t\tif (length / unbalanced_force < coef) coef = length / unbalanced_force;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn coef;\r\n}\r\n\r\nvoid p6::Construction::simulate(bool sim)\r\n{\r\n\tif (sim == _simulation) return;\r\n\telse if (!sim) { _simulation = false; return; }\r\n\r\n\t//Checking if materials are specified\r\n\t_check_materials_specified();\r\n\r\n\t//Creating node-to-free map\r\n\tstd::vector<uint> node_to_free;\r\n\t_create_map(&node_to_free);\r\n\r\n\t//Calculating tolerance\r\n\treal tolerance = _get_tolerance();\r\n\r\n\t//Creating vectors and matrixes\r\n\tVector s;\t//State vector\r\n\tVector z;\t//Should-be-zero value\r\n\tVector m;\t//Modification of state vector\r\n\tMatrix d;\t//Derivative of should-be-zero value\r\n\t_create_vectors(&node_to_free, &s, &z, &m, &d);\r\n\r\n\t//Iterating\r\n\treal last_error = 0.0;\r\n\tuint not_converge_count = 0;\r\n\twhile (true)\r\n\t{\r\n\t\t_set_z_to_external_forces(&node_to_free, &z);\r\n\t\t_set_d_to_zero(&node_to_free, &d);\r\n\t\tfor (uint i = 0; i < _stick.size(); i++)\r\n\t\t{\r\n\t\t\t_modify_z_with_stick_force(i, &node_to_free, &s, &z);\r\n\t\t\t_modify_d_with_stick_force(i, &node_to_free, &s, &d);\r\n\t\t}\r\n\t\treal error = _get_residuum(&z);\r\n\t\tif (error < tolerance) break;\r\n\t\telse if (error < last_error) not_converge_count = 0;\r\n\t\telse if (++not_converge_count == 10000) throw std::runtime_error(\"Simulation does not converge\");\r\n\t\tEigen::HouseholderQR<Eigen::Matrix<real, Eigen::Dynamic, Eigen::Dynamic>> qr(d);\r\n\t\tm = qr.solve(z);\r\n\t\tif (_is_adequate(&m, &node_to_free, &s)) s -= m;\r\n\t\telse s += 0.01 * _get_flow_coefficient(&node_to_free, &s, &z) * z;\r\n\t}\r\n\t_apply_state_vector(&node_to_free, &s);\r\n\r\n\t_simulation = true;\r\n}\r\n\r\np6::Construction::~Construction()\r\n{\r\n\tfor (uint i = 0; i < _material.size(); i++) delete _material[i];\r\n}\r\n", "meta": {"hexsha": "0a46ac890e7cd2b3856cfd7548411d4a84e073b2", "size": 30823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/p6_construction.cpp", "max_stars_repo_name": "Meta-chan/P6", "max_stars_repo_head_hexsha": "2323f3f12894d2eb01a777643f69301a368f9c69", "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/p6_construction.cpp", "max_issues_repo_name": "Meta-chan/P6", "max_issues_repo_head_hexsha": "2323f3f12894d2eb01a777643f69301a368f9c69", "max_issues_repo_licenses": ["MIT"], "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/p6_construction.cpp", "max_forks_repo_name": "Meta-chan/P6", "max_forks_repo_head_hexsha": "2323f3f12894d2eb01a777643f69301a368f9c69", "max_forks_repo_licenses": ["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.7519305019, "max_line_length": 112, "alphanum_fraction": 0.6402361873, "num_tokens": 9356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19378350417746948}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef individual_model_hpp\n#define individual_model_hpp\n\n#include <vector>\n\n#include <boost/optional.hpp>\n\n#include \"genotype_prior_model.hpp\"\n#include \"core/types/haplotype.hpp\"\n#include \"core/models/haplotype_likelihood_cache.hpp\"\n#include \"core/types/genotype.hpp\"\n#include \"logging/logging.hpp\"\n\nnamespace octopus { namespace model {\n\nclass IndividualModel\n{\npublic:\n    struct Latents\n    {\n        using GenotypeProbabilityVector = std::vector<double>;\n        GenotypeProbabilityVector genotype_probabilities;\n    };\n    \n    struct InferredLatents\n    {\n        Latents posteriors;\n        double log_evidence;\n    };\n    \n    IndividualModel() = delete;\n    \n    IndividualModel(const GenotypePriorModel& genotype_prior_model,\n                    boost::optional<logging::DebugLogger> debug_log = boost::none,\n                    boost::optional<logging::TraceLogger> trace_log = boost::none);\n    \n    IndividualModel(const IndividualModel&)            = delete;\n    IndividualModel& operator=(const IndividualModel&) = delete;\n    IndividualModel(IndividualModel&&)                 = delete;\n    IndividualModel& operator=(IndividualModel&&)      = delete;\n    \n    ~IndividualModel() = default;\n    \n    const GenotypePriorModel& prior_model() const noexcept;\n    \n    InferredLatents evaluate(const std::vector<Genotype<Haplotype>>& genotypes,\n                             const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    \n    InferredLatents evaluate(const std::vector<Genotype<Haplotype>>& genotypes,\n                             const std::vector<std::vector<unsigned>>& genotype_indices,\n                             const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    \nprivate:\n    const GenotypePriorModel& genotype_prior_model_;\n    \n    mutable boost::optional<logging::DebugLogger> debug_log_;\n    mutable boost::optional<logging::TraceLogger> trace_log_;\n};\n\n} // namesapce model\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "d2837e2e9efb74b6b0fb2fbe85b51fc9bf632ade", "size": 2105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/genotype/individual_model.hpp", "max_stars_repo_name": "alimanfoo/octopus", "max_stars_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-21T23:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T23:34:28.000Z", "max_issues_repo_path": "src/core/models/genotype/individual_model.hpp", "max_issues_repo_name": "alimanfoo/octopus", "max_issues_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_issues_repo_licenses": ["MIT"], "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/genotype/individual_model.hpp", "max_forks_repo_name": "alimanfoo/octopus", "max_forks_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_forks_repo_licenses": ["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.4179104478, "max_line_length": 96, "alphanum_fraction": 0.6859857482, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19378350417746948}}
{"text": "/*\n * This file is part of the DUDS project. It is subject to the BSD-style\n * license terms in the LICENSE file found in the top-level directory of this\n * distribution and at http://www.somewhere.org/somepath/license.html.\n * No part of DUDS, including this file, may be copied, modified, propagated,\n * or distributed except according to the terms contained in the LICENSE file.\n *\n * Copyright (C) 2017  Jeff Jackowski\n */\n#include <duds/hardware/devices/instruments/INA219.hpp>\n#include <duds/hardware/interface/linux/DevSmbus.hpp>\n#include <iostream>\n#include <thread>\n#include <iomanip>\n#include <assert.h>\n#include <boost/exception/diagnostic_information.hpp>\n\nconstexpr int valw = 8;\nbool quit = false;\n\nvoid runtest(duds::hardware::devices::instruments::INA219 &ina) {\n\tstd::cout.precision(5);\n\tstd::int16_t sv, bv;\n\tdo {\n\t\tina.sample();\n\t\tduds::data::Quantity shnV = ina.shuntVoltage();\n\t\tduds::data::Quantity busV = ina.busVoltage();\n\t\tduds::data::Quantity busI = ina.busCurrent();\n\t\tassert(busV.unit == duds::data::units::Volt);\n\t\tassert(busI.unit == duds::data::units::Ampere);\n\t\tassert(shnV.unit == duds::data::units::Volt);\n\t\tduds::data::Quantity busP = busV * busI;\n\t\tassert(busP.unit == duds::data::units::Watt);\n\t\tina.vals(sv, bv);\n\t\tstd::cout << \"Shunt: \" << std::setw(valw) << shnV.value <<\n\t\t\t\"v   Bus: \" << std::setw(valw) << busV.value << \"v  \" <<\n\t\t\tstd::setw(valw) << busI.value << \"A  \" << std::setw(valw) << \n\t\t\tbusP.value <<\n\t\t\t//'W' << std::endl;\n\t\t\t\"W   s = \" << std::setw(valw-2) << sv << \" b = \" << \n\t\t\tstd::setw(valw-2) << bv << std::endl;\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t} while (!quit);\n}\n\nint main(void)\ntry {\n\tstd::unique_ptr<duds::hardware::interface::Smbus> smbus(\n\t\tnew duds::hardware::interface::linux::DevSmbus(\n\t\t\t\"/dev/i2c-1\",\n\t\t\t0x40,\n\t\t\tduds::hardware::interface::Smbus::NoPec()\n\t\t)\n\t);\n\tduds::hardware::devices::instruments::INA219 meter(smbus, 0.1);\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(2));\n\tstd::thread doit(runtest, std::ref(meter));\n\tstd::cin.get();\n\tquit = true;\n\tdoit.join();\n} catch (...) {\n\tstd::cerr << \"ERROR: \" << boost::current_exception_diagnostic_information()\n\t<< std::endl;\n\treturn 1;\n}\n", "meta": {"hexsha": "5a243f5e3cc21d9a9135988de6c218452bb6d6fd", "size": 2195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/ina219test.cpp", "max_stars_repo_name": "jjackowski/duds", "max_stars_repo_head_hexsha": "0fc4eec0face95c13575672f2a2d8625517c9469", "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": "samples/ina219test.cpp", "max_issues_repo_name": "jjackowski/duds", "max_issues_repo_head_hexsha": "0fc4eec0face95c13575672f2a2d8625517c9469", "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": "samples/ina219test.cpp", "max_forks_repo_name": "jjackowski/duds", "max_forks_repo_head_hexsha": "0fc4eec0face95c13575672f2a2d8625517c9469", "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.2575757576, "max_line_length": 78, "alphanum_fraction": 0.6619589977, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19378350417746948}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018, 2019.\n// Modifications copyright (c) 2017-2019, 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// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 5.0.0\n\n// Original copyright notice:\n\n// Purpose:  Stub projection implementation for lat/long coordinates. We\n//           don't actually change the coordinates, but we want proj=latlong\n//           to act sort of like a projection.\n// Author:   Frank Warmerdam, warmerdam@pobox.com\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_PROJECTIONS_LATLONG_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_LATLONG_HPP\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace latlong\n    {\n\n            /* very loosely based upon DMA code by Bradford W. Drew */\n\n            template <typename T, typename Parameters>\n            struct base_latlong_other\n            {\n                // FORWARD(forward)\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(Parameters const& par, T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    // TODO: in the original code a is not used\n                    // different mechanism is probably used instead\n                    xy_x = lp_lon / par.a;\n                    xy_y = lp_lat / par.a;\n                }\n\n                // INVERSE(inverse)\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(Parameters const& par, T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    // TODO: in the original code a is not used\n                    // different mechanism is probably used instead\n                    lp_lat = xy_y * par.a;\n                    lp_lon = xy_x * par.a;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"latlong_other\";\n                }\n\n            };\n\n            // Lat/long (Geodetic)\n            template <typename Parameters>\n            inline void setup_latlong(Parameters& par)\n            {\n                    par.is_latlong = 1;\n                    par.x0 = 0.0;\n                    par.y0 = 0.0;\n            }\n\n    }} // namespace detail::latlong\n    #endif // doxygen\n\n    /*!\n        \\brief Lat/long (Geodetic) projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Example\n        \\image html ex_latlong.gif\n    */\n    template <typename T, typename Parameters>\n    struct latlong_other : public detail::latlong::base_latlong_other<T, Parameters>\n    {\n        template <typename Params>\n        inline latlong_other(Params const& , Parameters & par)\n        {\n            detail::latlong::setup_latlong(par);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION_FI(srs::spar::proj_lonlat, latlong_other)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION_FI(srs::spar::proj_latlon, latlong_other)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION_FI(srs::spar::proj_latlong, latlong_other)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION_FI(srs::spar::proj_longlat, latlong_other)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(latlong_entry, latlong_other)\n        \n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(latlong_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(lonlat, latlong_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(latlon, latlong_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(latlong, latlong_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(longlat, latlong_entry)\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_LATLONG_HPP\n\n", "meta": {"hexsha": "111075ef2cbc5339c28363cf28f8ec04b2cf7c94", "size": 6127, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/proj/latlong.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/proj/latlong.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/proj/latlong.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": 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": 39.025477707, "max_line_length": 112, "alphanum_fraction": 0.670638159, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19378349867278535}}
{"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_FAST_TOINT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_FAST_TOINT_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  fast_toint generic tag\n\n      Represents the fast_toint function in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    struct fast_toint_ : ext::elementwise_<fast_toint_>\n    {\n      /// @brief Parent hierarchy\n      typedef ext::elementwise_<fast_toint_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_fast_toint_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n    template<class Site>\n    BOOST_FORCEINLINE generic_dispatcher<tag::fast_toint_, Site> dispatching_fast_toint_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n    {\n      return generic_dispatcher<tag::fast_toint_, Site>();\n    }\n    template<class... Args>\n    struct impl_fast_toint_;\n  }\n  /*!\n    Convert to integer by truncation.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    as_integer<T> r = fast_toint(x);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    as_integer<T> r = static_cast<as_integer<T> >(x)\n    @endcode\n\n    @par Notes:\n\n    @c fast_toint cast a floating value to the signed integer value of the same bit size.\n\n    This is done by C casting for scalars and corresponding intrinsic in simd (if available).\n\n    Peculiarly,  that implies that the behaviour of this function on invalid entries is\n    not defined and quite unpredictable.\n\n    (For instance it is quite frequent that the test:\n\n    @code\n    fast_toint(Inf<double>()) ==  fast_toint(1.0/0.0)\n    @endcode\n\n\n    will return false whilst the test:\n\n    @code\n    Inf<double>() == 1.0/0.0\n    @endcode\n\n\n    returns true !)\n\n    If you intend to use nans and infs entries,  consider using fast_toints instead.\n    On integral typed values, it acts as identity.\n\n    @par Alias\n\n    fast__fast_toint\n\n    @param  a0\n\n    @return      a value of the integer type associated to the input.\n\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::fast_toint_, fast_toint, 1)\n\n} }\n\n#include <boost/simd/operator/specific/common.hpp>\n\n#endif\n", "meta": {"hexsha": "a33798e8958f070e7718d79cb1631a6b3e17c93d", "size": 2891, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/fast_toint.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/fast_toint.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/fast_toint.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": 28.067961165, "max_line_length": 144, "alphanum_fraction": 0.6423382912, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1937834969033229}}
{"text": "#define SHA1_CHECKSUM\n#include \"framework/serialization/providers/providerwithchecksum.h\"\n#include \"framework/configfile.h\"\n#include \"framework/logger.h\"\n#include \"framework/trace.h\"\n#include \"library/strings.h\"\n#include \"library/strings_format.h\"\n#include <sstream>\n\n#include \"dependencies/pugixml/src/pugixml.hpp\"\n\n// Disable automatic #pragma linking for boost - only enabled in msvc and that should provide boost\n// symbols as part of the module that uses it\n#define BOOST_ALL_NO_LIB\n#include <boost/crc.hpp>\n#include <boost/version.hpp>\n#if BOOST_VERSION >= 106600\n#include <boost/uuid/detail/sha1.hpp>\n#else\n#include <boost/uuid/sha1.hpp>\n#endif\n#include <boost/uuid/uuid.hpp>\n\nnamespace OpenApoc\n{\nConfigOptionBool useCRCChecksum(\"Framework.Serialization\", \"CRC\",\n                                \"use a CRC checksum when saving files\", true);\nConfigOptionBool useSHA1Checksum(\"Framework.Serialization\", \"SHA1\",\n                                 \"use a SHA1 checksum when saving files\", false);\n\nstatic UString calculateSHA1Checksum(const std::string &str)\n{\n\tTRACE_FN;\n\tUString hashString;\n\n\tboost::uuids::detail::sha1 sha;\n\tsha.process_bytes(str.c_str(), str.size());\n\tunsigned int hash[5];\n\tsha.get_digest(hash);\n\tfor (int i = 0; i < 5; i++)\n\t{\n\t\tunsigned int v = hash[i];\n\t\tfor (int j = 0; j < 4; j++)\n\t\t{\n\t\t\t// FIXME: Probably need to do the reverse for big endian?\n\t\t\tunsigned int byteHex = v & 0xff000000;\n\t\t\tbyteHex >>= 24;\n\t\t\thashString += format(\"%02x\", byteHex).str();\n\t\t\tv <<= 8;\n\t\t}\n\t}\n\n\treturn hashString;\n}\nstatic UString calculateCRCChecksum(const std::string &str)\n{\n\tTRACE_FN;\n\tUString hashString;\n\n\tboost::crc_32_type crc;\n\tcrc.process_bytes(str.c_str(), str.size());\n\tauto hash = crc.checksum();\n\thashString = format(\"%08x\", hash);\n\treturn hashString;\n}\n\nstatic UString calculateChecksum(const UString &type, const std::string &str)\n{\n\tif (type == \"CRC\")\n\t{\n\t\treturn calculateCRCChecksum(str);\n\t}\n\telse if (type == \"SHA1\")\n\t{\n\t\treturn calculateSHA1Checksum(str);\n\t}\n\telse\n\t{\n\t\tLogWarning(\"Unknown checksum type \\\"%s\\\"\", type);\n\t\treturn \"\";\n\t}\n}\n\nstd::string ProviderWithChecksum::serializeManifest()\n{\n\tpugi::xml_document manifestDoc;\n\tauto decl = manifestDoc.prepend_child(pugi::node_declaration);\n\tdecl.append_attribute(\"version\") = \"1.0\";\n\tdecl.append_attribute(\"encoding\") = \"UTF-8\";\n\tauto root = manifestDoc.root().append_child();\n\troot.set_name(\"checksums\");\n\tfor (auto &p : checksums)\n\t{\n\t\tauto node = root.append_child();\n\t\tnode.set_name(\"file\");\n\t\tnode.text().set(p.first.cStr());\n\t\tfor (auto &csum : p.second)\n\t\t{\n\t\t\tauto checksumNode = node.append_child();\n\t\t\tchecksumNode.set_name(csum.first.cStr());\n\t\t\tchecksumNode.text().set(csum.second.cStr());\n\t\t}\n\t}\n\tstd::stringstream ss;\n\tmanifestDoc.save(ss, \"  \");\n\treturn ss.str();\n}\n\nbool ProviderWithChecksum::parseManifest(const std::string &manifestData)\n{\n\tstd::stringstream ss(manifestData);\n\tpugi::xml_document manifestDoc;\n\tauto parse_result = manifestDoc.load(ss);\n\tif (!parse_result)\n\t{\n\t\tLogWarning(\"Failed to parse checksum.xml : \\\"%s\\\" at \\\"%llu\\\"\", parse_result.description(),\n\t\t           (unsigned long long)parse_result.offset);\n\t\treturn false;\n\t}\n\tauto rootNode = manifestDoc.child(\"checksums\");\n\tif (!rootNode)\n\t{\n\t\tLogWarning(\"checksum.xml has invalid root node\");\n\t\treturn false;\n\t}\n\tauto fileNode = rootNode.child(\"file\");\n\twhile (fileNode)\n\t{\n\t\tUString fileName = fileNode.text().get();\n\n\t\tif (this->checksums.find(fileName) != this->checksums.end())\n\t\t{\n\t\t\tLogWarning(\"Multiple manifest entries for path \\\"%s\\\"\", fileName);\n\t\t}\n\n\t\tthis->checksums[fileName] = {};\n\n\t\tauto checksumNode = fileNode.first_child();\n\t\twhile (checksumNode)\n\t\t{\n\t\t\tif (checksumNode.type() == pugi::xml_node_type::node_element)\n\t\t\t{\n\t\t\t\tUString checksumType = checksumNode.name();\n\t\t\t\tthis->checksums[fileName][checksumType] = checksumNode.text().get();\n\t\t\t}\n\t\t\tchecksumNode = checksumNode.next_sibling();\n\t\t}\n\t\tfileNode = fileNode.next_sibling(\"file\");\n\t}\n\n\treturn true;\n}\nbool ProviderWithChecksum::openArchive(const UString &path, bool write)\n{\n\n\tif (!inner->openArchive(path, write))\n\t{\n\t\treturn false;\n\t}\n\n\tif (!write)\n\t{\n\t\tUString result;\n\t\tif (!inner->readDocument(\"checksum.xml\", result))\n\t\t{\n\t\t\tLogInfo(\"Missing manifest file in \\\"%s\\\"\", path);\n\t\t\treturn true;\n\t\t}\n\t\tparseManifest(result.str());\n\t}\n\treturn true;\n}\nbool ProviderWithChecksum::readDocument(const UString &path, UString &result)\n{\n\tif (inner->readDocument(path, result))\n\t{\n\t\tfor (auto &csum : checksums[path.str()])\n\t\t{\n\t\t\tauto expectedCSum = csum.second;\n\t\t\tauto calculatedCSum = calculateChecksum(csum.first, result.str());\n\t\t\tif (expectedCSum != calculatedCSum)\n\t\t\t{\n\t\t\t\tLogWarning(\"File \\\"%s\\\" has incorrect \\\"%s\\\" checksum \\\"%s\\\", expected \\\"%s\\\"\",\n\t\t\t\t           path, csum.first, calculatedCSum, expectedCSum);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLogDebug(\"File \\\"%s\\\" matches \\\"%s\\\" checksum \\\"%s\\\"\", path, csum.first,\n\t\t\t\t         calculatedCSum);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\treturn false;\n}\nbool ProviderWithChecksum::saveDocument(const UString &path, const UString &contents)\n{\n\n\tif (inner->saveDocument(path, contents))\n\t{\n\t\tif (this->checksums.find(path) != this->checksums.end())\n\t\t{\n\t\t\tLogWarning(\"Multiple document entries for path \\\"%s\\\"\", path);\n\t\t}\n\t\tthis->checksums[path.str()] = {};\n\t\tif (useCRCChecksum.get())\n\t\t\tthis->checksums[path.str()][\"CRC\"] = calculateChecksum(\"CRC\", contents.str()).str();\n\t\tif (useSHA1Checksum.get())\n\t\t\tthis->checksums[path.str()][\"SHA1\"] = calculateChecksum(\"SHA1\", contents.str()).str();\n\t\treturn true;\n\t}\n\treturn false;\n}\nbool ProviderWithChecksum::finalizeSave()\n{\n\tUString manifest = serializeManifest();\n\tinner->saveDocument(\"checksum.xml\", manifest);\n\treturn inner->finalizeSave();\n}\n} // namespace OpenApoc\n", "meta": {"hexsha": "3c3eb98a53af622b7d65c2410d7df507576cee65", "size": 5704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "framework/serialization/providers/providerwithchecksum.cpp", "max_stars_repo_name": "Skin36/OpenApoc", "max_stars_repo_head_hexsha": "ab333c6fe8d0dcfc96f044482a38ef81c10442a5", "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": "framework/serialization/providers/providerwithchecksum.cpp", "max_issues_repo_name": "Skin36/OpenApoc", "max_issues_repo_head_hexsha": "ab333c6fe8d0dcfc96f044482a38ef81c10442a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "framework/serialization/providers/providerwithchecksum.cpp", "max_forks_repo_name": "Skin36/OpenApoc", "max_forks_repo_head_hexsha": "ab333c6fe8d0dcfc96f044482a38ef81c10442a5", "max_forks_repo_licenses": ["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.6936936937, "max_line_length": 99, "alphanum_fraction": 0.6814516129, "num_tokens": 1480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1937834969033229}}
{"text": "/**\n*  @file    mdm_VolumeAnalysis.cxx\n*  @brief   Implementation of mdm_VolumeAnalysis class\n*\n*  Original author MA Berks 24 Oct 2018\n*  (c) Copyright QBI, University of Manchester 2020\n*/\n\n#ifndef MDM_API_EXPORTS\n#define MDM_API_EXPORTS\n#endif // !MDM_API_EXPORTS\n\n\n#include \"mdm_VolumeAnalysis.h\"\n\n#include <cmath>\n#include <chrono>  // chrono::system_clock\n#include <sstream> // stringstream\n#include <algorithm>\n#include <numeric>\n#include <boost/format.hpp>\n\n#include <mdm_exception.h>\n#include <madym/mdm_ProgramLogger.h>\n#include <madym/mdm_AIF.h>\n\n//Names of output maps\nconst std::string mdm_VolumeAnalysis::MAP_NAME_IAUC = \"IAUC\"; //Appended with IAUC time\nconst std::string mdm_VolumeAnalysis::MAP_NAME_RESDIUALS = \"residuals\";\nconst std::string mdm_VolumeAnalysis::MAP_NAME_ENHANCING = \"enhVox\";\nconst std::string mdm_VolumeAnalysis::MAP_NAME_ROI = \"ROI\";\nconst std::string mdm_VolumeAnalysis::MAP_NAME_ERROR_TRACKER = \"error_tracker\";\nconst std::string mdm_VolumeAnalysis::MAP_NAME_T1 = \"T1\";\nconst std::string mdm_VolumeAnalysis::MAP_NAME_M0 = \"M0\";\n//Signal derived concentration - appended with volume number\nconst std::string mdm_VolumeAnalysis::MAP_NAME_CT_SIG = \"Ct_sig\"; \n//Model estimated concentration - appended with volume number\nconst std::string mdm_VolumeAnalysis::MAP_NAME_CT_MOD = \"Ct_mod\"; \n\nMDM_API mdm_VolumeAnalysis::mdm_VolumeAnalysis()\n\t:\n\tT1Mapper_(errorTracker_, ROI_),\n\ttestEnhancement_(false),\n\tuseM0Ratio_(true),\n  useB1correction_(false),\n  outputCt_sig_(false),\n  outputCt_mod_(false),\n  useNoise_(false),\n  StDataMaps_(0),\n  CtDataMaps_(0),\n  CtModelMaps_(0),\n  dynamicTimes_(0),\n  noiseVar_(0),\n  firstImage_(0),\n  lastImage_(0),\n\tmaxIterations_(0),\n  model_(NULL)\n{\n\tsetIAUCtimes({ 60.0, 90.0, 120.0 }, true, false);\n}\n\nMDM_API mdm_VolumeAnalysis::~mdm_VolumeAnalysis()\n{\n\n}\n\nMDM_API void mdm_VolumeAnalysis::reset()\n{\n  ROI_.reset();\n  AIFmap_.reset();\n  StDataMaps_.clear();\n  CtDataMaps_.clear();\n  CtModelMaps_.clear();\n  dynamicTimes_.clear();\n  noiseVar_.clear();\n  dynamicMetaData_.reset();\n\n  T1Mapper_.reset();\n  errorTracker_.resetErrorImage();\n\n  /* Images for inputs and output */\n  pkParamMaps_.clear();\n  IAUCMaps_.clear();\n  modelResidualsMap_.reset();\n  enhVoxMap_.reset();\n  initMapParams_.clear();\n}\n\n//\nMDM_API mdm_ErrorTracker& mdm_VolumeAnalysis::errorTracker()\n{\n\treturn errorTracker_;\n}\n\n//\nMDM_API mdm_T1Mapper& mdm_VolumeAnalysis::T1Mapper()\n{\n\treturn T1Mapper_;\n}\n\n//\nMDM_API const mdm_T1Mapper& mdm_VolumeAnalysis::T1Mapper() const\n{\n  return T1Mapper_;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setROI(const mdm_Image3D ROI)\n{\n  errorTracker_.checkOrSetDimension(ROI, \"ROI\");\n  ROI_ = ROI;\n\t}\n\n//\nMDM_API mdm_Image3D mdm_VolumeAnalysis::ROI() const\n{\n\treturn ROI_;\n}\n\nMDM_API void mdm_VolumeAnalysis::setAIFmap(\n  const mdm_Image3D map)\n{\n  errorTracker_.checkOrSetDimension(map, \"AIF map\");\n\n  if (map.type() != mdm_Image3D::ImageType::TYPE_AIFVOXELMAP)\n  {\n    AIFmap_.copy(map);\n    AIFmap_.setType(mdm_Image3D::ImageType::TYPE_AIFVOXELMAP);\n    for (size_t idx = 0; idx < map.numVoxels(); idx++)\n      if (map.voxel(idx) > 0)\n        AIFmap_.setVoxel(idx, mdm_AIF::AIFmapVoxel::SELECTED);\n  }\n  else\n    AIFmap_ = map;\n}\n\n//\nMDM_API std::vector<double> mdm_VolumeAnalysis::AIFfromMap()\n{\n  if (!AIFmap_)\n    throw mdm_exception(__func__, \"AIF map not set.\");\n\n  checkDynamicsSet();\n\n  std::vector<size_t> badVoxels;\n  std::vector<double>baseAIF;\n  computeMeanCt(AIFmap_, mdm_AIF::AIFmapVoxel::SELECTED, baseAIF, badVoxels);\n  for (const auto vox : badVoxels)\n    AIFmap_.setVoxel(vox, mdm_AIF::AIFmapVoxel::INVALID_CT);\n\n  return baseAIF;\n};\n\n//\nMDM_API mdm_Image3D mdm_VolumeAnalysis::AIFmap() const\n{\n  return AIFmap_;\n}\n\nMDM_API void mdm_VolumeAnalysis::addStDataMap(const mdm_Image3D dynImg)\n{\n  //Check the image dimension match\n  errorTracker_.checkOrSetDimension(dynImg, \n    \"dynamic image \" + std::to_string(StDataMaps_.size()+1));\n\n\t//Add the image to the list\n\tStDataMaps_.push_back(dynImg);\n\n  //First map we add, set the reference image\n  if (!dynamicMetaData_)\n    setDynamicMetaData(dynImg);\n\n\t//Extract the time from the header, converted to minutes\n  setDynamicTime(dynImg);\n\n  if (useNoise_)\n  {\n    double noise = dynImg.info().noiseSigma.value();\n    if (noise != NAN)\n      noiseVar_.push_back(noise);\n  }\n  \n\tif (outputCt_sig_ && (CtDataMaps_.size() == numSt() - 1))\n\t{\n\t\tmdm_Image3D ctMap;\n\t\tctMap.copy(dynImg);\n\t\tctMap.setTimeStampFromDoubleStr(dynImg.timeStamp());\n\t\tctMap.setType(mdm_Image3D::ImageType::TYPE_CAMAP);\n\t\tCtDataMaps_.push_back(ctMap);\n\t}\n  if (outputCt_mod_ && (CtModelMaps_.size() == numSt() - 1))\n  {\n    mdm_Image3D cModMap;\n    cModMap.copy(dynImg);\n\t\tcModMap.setTimeStampFromDoubleStr(dynImg.timeStamp());\n    cModMap.setType(mdm_Image3D::ImageType::TYPE_CAMAP);\n    CtModelMaps_.push_back(cModMap);\n  }\n}\n\n//\nMDM_API mdm_Image3D mdm_VolumeAnalysis::StDataMap(size_t i) const\n{\n  if (i >= StDataMaps_.size())\n    throw mdm_exception(__func__, boost::format(\n      \"Attempting to access S(t) map at index %1% when there are only %2% S(t) maps\")\n      % i % StDataMaps_.size());\n\n  return StDataMaps_[i];\n}\n\n//\nMDM_API const std::vector<mdm_Image3D> & mdm_VolumeAnalysis::StDataMaps() const\n{\n  return StDataMaps_;\n}\n\n//\nMDM_API size_t  mdm_VolumeAnalysis::numDynamics() const\n{\n\tif (StDataMaps_.empty())\n\t\treturn numCtSignal();\n\n  return numSt();\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::computeMeanCt(\n  const mdm_Image3D &map, double map_val,\n  std::vector<double> &meanCt, std::vector<size_t> &badVoxels) const\n{\n  errorTracker_.checkDimension(map, \"Ct ROI\");\n\n  auto nTimes = numDynamics();\n  \n  if (!nTimes)\n    throw mdm_exception(__func__, \"Trying to compute mean C(t) when no dynamic maps set\");\n\n\n  meanCt.resize(nTimes, 0);\n  badVoxels.clear();\n  double numVox = 0;\n  for (size_t idx = 0; idx < map.numVoxels(); idx++)\n  {\n    if (map.voxel(idx) == map_val)\n    {\n      std::vector<double> Ct;\n      if (computeCt_)\n      {\n        mdm_DCEVoxel vox(setUpVoxel(idx));\n        if (vox.status() != mdm_DCEVoxel::OK)\n        {\n          badVoxels.push_back(idx);\n          continue;\n        }\n          \n\n        Ct = vox.CtData();\n      }\n      else\n        voxelCtData(idx, Ct);\n\n      for (size_t t = 0; t < nTimes; t++)\n        meanCt[t] += Ct[t];\n      \n      numVox++;\n    }\n  }\n\n  if (numVox)\n    for (auto &v : meanCt)\n      v /= numVox;\n\n  return;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::addCtDataMap(const mdm_Image3D ctMap)\n{\n  //Check the image dimension match\n  errorTracker_.checkOrSetDimension(ctMap,\n    \"concentration image \" + std::to_string(CtDataMaps_.size() + 1));\n\n  //We don't allow mixed setting of Ct and St maps - so if St already set, throw error\n  if (!StDataMaps_.empty())\n    throw mdm_exception(__func__, \"Attempting to add C(t) when S(t) maps already set\");\n\n\t//Add the image to the list\n\tCtDataMaps_.push_back(ctMap);\n\n  //First map we add, set the reference image\n  if (!dynamicMetaData_)\n    setDynamicMetaData(ctMap);\n\n\n\t//Extract the time from the header, converted to minutes\n\tdynamicTimes_.push_back(ctMap.minutesFromTimeStamp());\n\n  //Check if there is a noise variance associated with the volume\n  if (useNoise_)\n  {\n    double noise = ctMap.info().noiseSigma.value();\n    if (!isnan(noise))\n      noiseVar_.push_back(noise);\n  }\n}\n\n//\nMDM_API mdm_Image3D mdm_VolumeAnalysis::CtDataMap(size_t i) const\n{\n  if (i >= CtDataMaps_.size())\n    throw mdm_exception(__func__, boost::format(\n      \"Attempting to access C(t) map at index %1% when there are only %2% C(t) maps\")\n      % i % CtDataMaps_.size());\n\n  return CtDataMaps_[i];\n}\n\n//\nMDM_API const std::vector<mdm_Image3D> & mdm_VolumeAnalysis::CtDataMaps() const\n{\n  return CtDataMaps_;\n}\n\n//\nMDM_API mdm_Image3D mdm_VolumeAnalysis::CtModelMap(size_t i) const\n{\n  if (i >= CtModelMaps_.size())\n    throw mdm_exception(__func__, boost::format(\n      \"Attempting to access Cm(t) map at index %1% when there are only %2% Cm(t) maps\")\n      % i % CtDataMaps_.size());\n\n  return CtModelMaps_[i];\n}\n\n//\nMDM_API const std::vector<mdm_Image3D> & mdm_VolumeAnalysis::CtModelMaps() const\n{\n  return CtModelMaps_;\n}\n\n//\nMDM_API mdm_Image3D mdm_VolumeAnalysis::DCEMap(const std::string &mapName) const\n{\n  checkModelSet();\n\n  for (int i = 0; i < model_->numParams(); i++)\n  {\n    if (mapName == model_->paramName(i))\n      return pkParamMaps_[i];\n  }\n\n\tfor (size_t i = 0; i < IAUCTimes_.size(); i++)\n\t{\n\t\tif (mapName == (MAP_NAME_IAUC + std::to_string(int(IAUCTimes_[i]))))\n\t\t\treturn IAUCMaps_[i];\n\t}\t\n\n  if (mapName == (MAP_NAME_IAUC + \"_peak\"))\n    return IAUCMaps_.back();\n\n\tif (mapName == MAP_NAME_RESDIUALS)\n\t\treturn modelResidualsMap_;\n\n\tif (mapName == MAP_NAME_ENHANCING)\n\t\treturn enhVoxMap_;\n\t\n\t//Error map name not recognised\n\tthrow mdm_exception(__func__, boost::format(\"Map name %1% not recognised\") % mapName);\n\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setDCEMap(const std::string &mapName, const mdm_Image3D &map)\n{\n  errorTracker_.checkOrSetDimension(map, \"param map \" + mapName);\n\n  checkModelSet();\n\n  if (pkParamMaps_.size() != model_->numParams())\n    pkParamMaps_.resize(model_->numParams());\n\n  for (int i = 0; i < model_->numParams(); i++)\n  {\n    if (mapName == model_->paramName(i))\n    {\n      pkParamMaps_[i] = map;\n      return;\n    }  \n  }\n\n  for (size_t i = 0; i < IAUCTimes_.size(); i++)\n  {\n    if (mapName == (MAP_NAME_IAUC + std::to_string(int(IAUCTimes_[i]))))\n    {\n      IAUCMaps_[i] = map;\n      return;\n    }    \n  }\n\n  if (mapName == (MAP_NAME_IAUC + \"_peak\"))\n  {\n    IAUCMaps_[IAUCMaps_.size()-1] = map;\n    return;\n  }\n\n  if (mapName == MAP_NAME_RESDIUALS)\n  {\n    modelResidualsMap_ = map;\n    return;\n  }\n  if (mapName == MAP_NAME_ENHANCING)\n  {\n    enhVoxMap_ = map;\n    return;\n  }\n\n  //Error map name not recognised\n  throw mdm_exception(__func__, boost::format(\"Map name %1% not recognised\") % mapName);\n}\n\n//\nMDM_API std::string mdm_VolumeAnalysis::modelType() const\n{\n  if (model_)\n    return model_->modelType();\n  else\n    return \"\";\n}\n\n//\nMDM_API std::vector<double> mdm_VolumeAnalysis::dynamicTimes() const\n{\n\treturn dynamicTimes_;\n}\n\n//\nMDM_API double mdm_VolumeAnalysis::dynamicTime(size_t i) const\n{\n  if (i >= dynamicTimes_.size())\n    throw mdm_exception(__func__, boost::format(\n      \"Attempting to access timepoint %1% when there are only %2% timepoints\")\n      % i % dynamicTimes_.size());\n\n  return dynamicTimes_[i];\n}\n\n//\nMDM_API std::vector<std::string> mdm_VolumeAnalysis::paramNames() const\n{\n  checkModelSet();\n\treturn model_->paramNames();\n}\n\n//\nMDM_API std::vector<double> mdm_VolumeAnalysis::IAUCtimes() const\n{\n\treturn IAUCTimes_;\n}\n\n//\nMDM_API bool mdm_VolumeAnalysis::IAUCAtpeak() const\n{\n  return IAUCAtPeak_;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setR1Const(double rc)\n{\n\tr1Const_ = rc;\n}\n\nMDM_API void mdm_VolumeAnalysis::setPrebolusImage(int prebolus)\n{\n  prebolusImage_ = prebolus;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setModel(std::shared_ptr<mdm_DCEModelBase> model)\n{\n\tmodel_ = model;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setTestEnhancement(bool flag)\n{\n\ttestEnhancement_ = flag;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setM0Ratio(bool flag)\n{\n\tuseM0Ratio_ = flag;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setB1correction(bool flag)\n{\n  useB1correction_ = flag;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setComputeCt(bool flag)\n{\n\tcomputeCt_ = flag;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setOutputCtSig(bool flag)\n{\n\toutputCt_sig_ = flag;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setOutputCtMod(bool flag)\n{\n  outputCt_mod_ = flag;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setIAUCtimes(\n  const std::vector<double> &times, bool convertToMins, bool IAUCAtPeak)\n{\n\tIAUCTimes_ = times;\n\tstd::sort(IAUCTimes_.begin(), IAUCTimes_.end());\n\n\tIAUCTMinutes_ = times;\n\tif (convertToMins)\n\t{\n\t\tfor (auto &t : IAUCTMinutes_)\n\t\t\tt /= 60;\n\t}\n\tIAUCAtPeak_ = IAUCAtPeak;\t\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setUseNoise(bool b)\n{\n  useNoise_ = b;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setFirstImage(size_t t)\n{\n  firstImage_ = t;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setLastImage(size_t t)\n{\n  lastImage_ = t;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setOptimisationType(const std::string& type)\n{\n  optimisationType_ = type;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setMaxIterations(int maxItr)\n{\n\tmaxIterations_ = maxItr;\n}\n\n//\nMDM_API void mdm_VolumeAnalysis::setInitMapParams(const std::vector<int> &params)\n{\n  initMapParams_ = params;\n}\n\n//\nMDM_API void  mdm_VolumeAnalysis::fitDCEModel(\n  bool optimiseModel, const std::vector<int> initMapParams)\n{\n  checkDynamicsSet();\n  checkModelSet();\n\n  //\n  initialiseParameterMaps(*model_);\n\n  //Fit the model\n  fitModel(*model_, optimiseModel);\n\n}\n\n//------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------\n\n//\nsize_t mdm_VolumeAnalysis::numSt() const\n{\n  return StDataMaps_.size();\n}\n\n//\nsize_t mdm_VolumeAnalysis::numCtSignal() const\n{\n  return CtDataMaps_.size();\n}\n\n//\nsize_t mdm_VolumeAnalysis::numCtModel() const\n{\n  return CtModelMaps_.size();\n}\n\n//\nvoid mdm_VolumeAnalysis::checkModelSet() const\n{\n  if (!model_)\n    throw mdm_exception(__func__, \"Model not set\");\n}\n\nvoid mdm_VolumeAnalysis::checkDynamicsSet() const\n{\n  if (!numDynamics())\n    throw mdm_exception(__func__, \"Dynamic maps not loaded.\");\n}\n\n//\nvoid mdm_VolumeAnalysis::setDynamicMetaData(const mdm_Image3D& img)\n{\n  dynamicMetaData_ = std::make_unique<mdm_Image3D::MetaData>(img.info());\n  auto msg = boost::format(\n    \"Acquisition parameters for dynamic series set from %1%: \\n\"\n    \"    TR = %2% ms\\n\"\n    \"    FA = %3% deg\")\n    % dynamicMetaData_->xtrSource \n    % dynamicMetaData_->TR.value() \n    % dynamicMetaData_->flipAngle.value();\n\n  mdm_ProgramLogger::logProgramMessage(msg.str());\n}\n\n//\nvoid mdm_VolumeAnalysis::setDynamicTime(const mdm_Image3D& img)\n{\n  dynamicTimes_.push_back(img.minutesFromTimeStamp());\n  auto msg = boost::format(\n    \"Time t(%1%) = %2% mins set from %3%\")\n    % dynamicTimes_.size()\n    % dynamicTimes_.back()\n    % dynamicMetaData_->xtrSource;\n\n  mdm_ProgramLogger::logProgramMessage(msg.str());\n}\n\n//\nvoid mdm_VolumeAnalysis::initialiseParameterMaps(\n  const mdm_DCEModelBase &model)\n{\n  //Model parameter maps may already have been loaded\n  if (pkParamMaps_.size() != model.numParams())\n    pkParamMaps_.resize(model.numParams());\n\n  //For each map not already created, create it\n  for (auto &map : pkParamMaps_)\n    if (!map)\n      createMap(map);\n\n  //Create IAUC maps\n  IAUCMaps_.resize(IAUCTimes_.size() + int(IAUCAtPeak_));\n  for (auto &map : IAUCMaps_)\n    createMap(map);\n\n  //Model residuals may already have been loaded\n  if (!modelResidualsMap_)\n    createMap(modelResidualsMap_);\n\n  //Create enhancing map\n  createMap(enhVoxMap_);\n\n  //Create modelled Ct maps\n  if (outputCt_mod_)\n  {\n    CtModelMaps_.resize(numDynamics());\n    for (auto &map : CtModelMaps_)\n      createMap(map);\n  }\n}\n\n//\nmdm_DCEVoxel mdm_VolumeAnalysis::setUpVoxel(size_t voxelIndex) const\n{\n  std::vector<double> St, Ct;\n  if (computeCt_)\n    voxelStData(voxelIndex, St);\n\n  else\n    voxelCtData(voxelIndex, Ct);\n\n  mdm_DCEVoxel vox(\n    St,//dynSignals\n    Ct,//dynConc\n    prebolusImage_,//bolus_time\n    dynamicTimes_,//dynamicTimings\n    IAUCTMinutes_,\n    IAUCAtPeak_);//IAUC_times\n\n  if (computeCt_)\n  {\n    if (!dynamicMetaData_)\n      throw mdm_exception(__func__, \n        \"Attempting to convert to signal with no dynamic meta data set (eg TR, FA)\");\n\n    auto TR = dynamicMetaData_->TR.value();\n    auto FA = dynamicMetaData_->flipAngle.value();\n    \n    auto T1 = T1Mapper_.T1(voxelIndex);\n    auto M0 = useM0Ratio_ ? 0.0 : T1Mapper_.M0(voxelIndex);\n    auto B1 = useB1correction_ ? T1Mapper_.B1(voxelIndex) : 1.0;\n\n    //Convert signal (if already C(t) does nothing so can call regardless)\n    vox.computeCtFromSignal(T1, FA, TR, r1Const_, M0, B1, firstImage_);\n  }\n    \n  return vox;\n}\n\n//\nvoid  mdm_VolumeAnalysis::voxelStData(size_t voxelIndex, std::vector<double> &data) const\n{\n\tsize_t n = numSt();\n\n\tdata.resize(n);\n  for (size_t k = 0; k < n; k++)\n    data[k] = StDataMaps_[k].voxel(voxelIndex);\n}\n\n//\nvoid  mdm_VolumeAnalysis::voxelCtData(size_t voxelIndex, std::vector<double> &data) const\n{\n\tsize_t n = CtDataMaps_.size();\n\n\tdata.resize(n);\n\tfor (size_t k = 0; k < n; k++)\n\t\tdata[k] = CtDataMaps_[k].voxel(voxelIndex);\n}\n\n//\nvoid  mdm_VolumeAnalysis::voxelCtModel(size_t voxelIndex, std::vector<double> &data) const\n{\n  size_t n = CtModelMaps_.size();\n\n  data.resize(n);\n  for (size_t k = 0; k < n; k++)\n    data[k] = CtModelMaps_[k].voxel(voxelIndex);\n}\n\n//\nvoid mdm_VolumeAnalysis::setVoxelErrors(size_t voxelIndex, const mdm_DCEVoxel &vox)\n{\n\t//\n  auto status = vox.status();\n  if (status == mdm_DCEVoxel::CA_NAN)\n    errorTracker_.updateVoxel(voxelIndex, mdm_ErrorTracker::CA_IS_NAN);\n\n  else if (status == mdm_DCEVoxel::DYN_T1_BAD)\n    errorTracker_.updateVoxel(voxelIndex, mdm_ErrorTracker::DYNT1_NEGATIVE);\n\n  else if (status == mdm_DCEVoxel::M0_BAD)\n    errorTracker_.updateVoxel(voxelIndex, mdm_ErrorTracker::M0_NEGATIVE);\n\n  else if (status == mdm_DCEVoxel::NON_ENHANCING)\n    errorTracker_.updateVoxel(voxelIndex, mdm_ErrorTracker::NON_ENH_IAUC);\n}\n\n//\nvoid mdm_VolumeAnalysis::setVoxelPreFit(size_t voxelIndex,\n  const mdm_DCEVoxel  &vox, const mdm_DCEModelFitter &fitter)\n{\n  //Set any error codes returned from setting up the voxel in the error codes map\n  setVoxelErrors(voxelIndex, vox);\n\n  //Set any IAUC values\n  for (size_t i = 0; i < IAUCMaps_.size(); i++)\n    IAUCMaps_[i].setVoxel(voxelIndex, vox.IAUCVal(i));\n\n  //Set output C(t) maps\n  if (outputCt_sig_)\n    for (size_t i = 0; i < numDynamics(); i++)\n      CtDataMaps_[i].setVoxel(voxelIndex, vox.CtData()[i]);\n\n  if (outputCt_mod_)\n    for (size_t i = 0; i < numDynamics(); i++)\n      CtModelMaps_[i].setVoxel(voxelIndex, fitter.CtModel()[i]);\n\n  //Set enhancing status\n  enhVoxMap_.setVoxel(voxelIndex, vox.enhancing());\n}\n\n//\nvoid mdm_VolumeAnalysis::setVoxelPostFit(size_t voxelIndex,\n  const mdm_DCEModelBase &model, const mdm_DCEVoxel  &vox, const mdm_DCEModelFitter &fitter,\n  int &numErrors)\n{\n\n  //Check if any model fitting error codes generated\n  mdm_ErrorTracker::ErrorCode errorCode = model.getModelErrorCode();\n  if (errorCode != mdm_ErrorTracker::OK)\n  {\n    errorTracker_.updateVoxel(voxelIndex, errorCode);\n    numErrors++;\n  }\n\n  //Check if we have a target model residual to match\n  auto residual = fitter.modelFitError();\n  auto targetResidual = modelResidualsMap_.voxel(voxelIndex);\n  if (targetResidual && targetResidual < residual)\n    return; //Don't update parameter maps or model residuals\n\n  //Otherwise, residual is accepted, set parameter maps, modelled C(t) residuals\n  for (size_t i = 0; i < pkParamMaps_.size(); i++)\n\t\tpkParamMaps_[i].setVoxel(voxelIndex, model.params(int(i)));\n  \n  if (outputCt_mod_)\n    for (size_t i = 0; i < numDynamics(); i++)\n      CtModelMaps_[i].setVoxel(voxelIndex, fitter.CtModel()[i]);\n\n  modelResidualsMap_.setVoxel(voxelIndex, residual); \n    \n}\n\n//\nstd::vector <size_t> mdm_VolumeAnalysis::getVoxelsToFit() const\n{\n  std::vector<size_t> selectedVoxels;\n  if (ROI_)\n  {\n    for (size_t idx = 0; idx < ROI_.numVoxels(); idx++)\n    {\n      if (ROI_.voxel(idx))\n        selectedVoxels.push_back(idx);\n    }\n  }\n  else\n  {\n    selectedVoxels.resize(errorTracker_.errorImage().numVoxels());\n    std::iota(selectedVoxels.begin(), selectedVoxels.end(), 0);\n  }\n  return selectedVoxels;\n}\n\n//\nvoid mdm_VolumeAnalysis::initialiseModelParams(\n  const size_t voxelIndex,\n  mdm_DCEModelBase &model)\n{\n  \n  int n = model.numParams();\n  std::vector<double> initialParams = model.initialParams();\n\n  for (int i : initMapParams_)\n    initialParams[i] = pkParamMaps_[i].voxel(voxelIndex); \n\n  model.setInitialParams(initialParams);\n}\n\n//\nvoid mdm_VolumeAnalysis::logProgress(\n  double &numProcessed, const double numVoxels)\n{\n  //Increments the processed count, and logs a message at every 10th % complete\n  numProcessed++;\n  double pctComplete = 100.0*numProcessed / numVoxels;\n  if (pctComplete >= pctTarget_)\n  {\n    mdm_ProgramLogger::logProgramMessage(std::to_string(int(pctComplete)) + \"% voxels fitted.\");\n    pctTarget_ += 10;\n  }\n    \n}\n\n//\nvoid  mdm_VolumeAnalysis::fitModel(\n  mdm_DCEModelBase &model,\n  bool optimiseModel)\n{\n  //Create a new fitter object\n  mdm_DCEModelFitter modelFitter(\n    model,\n    firstImage_,\n    lastImage_ ? lastImage_ : numDynamics(),\n    noiseVar_,\n    optimisationType_,\n    maxIterations_\n  );\n\n  // Get list of voxels to fit\n  std::vector<size_t> selectedVoxels = getVoxelsToFit();\n  auto numVoxels = selectedVoxels.size();\n\tdouble numProcessed = 0;\n\tint numErrors = 0;\n  pctTarget_ = 10;\n  bool paramMapsInitialised = !initMapParams_.empty();\n\n  //Away we go...\n  mdm_ProgramLogger::logProgramMessage(\n    \"Fitting \" + modelType() + \" to \" + std::to_string(numVoxels) + \" voxels\");\n\tauto fit_start = std::chrono::system_clock::now();\n  for(const auto voxelIndex : selectedVoxels)\n  {\n    //If compute Ct from signal, skip voxels with invalid T1    \n    if (computeCt_ && T1Mapper_.T1(voxelIndex) <= 0.0)\n      continue;\n    \n    //Check if we've got parameter maps with values to initialise each voxel\n    //if not the existing values set in the model will be used\n    if (paramMapsInitialised)\n      initialiseModelParams(voxelIndex, model);\n          \n    //Set up the DCE voxel object\n    mdm_DCEVoxel vox(setUpVoxel(voxelIndex));\n\n    //Compute IAUC\n    vox.computeIAUC();\n\n    //Run an initial fit (does not optimise parameters, but\n    //sets bounds on model parameters, and compute the model residual\n    //for the initial model parameters\n    modelFitter.initialiseModelFit(vox.CtData());\n\n    //Test enhancement\n    if (testEnhancement_)\n      vox.testEnhancing();\n      \n    //Set values that don't depend on model fitting\n    setVoxelPreFit(voxelIndex, vox, modelFitter);\n\n    //The main event: If optimising the model fit, do so now\n    if (optimiseModel)\n      modelFitter.fitModel(vox.status());\n\n    //Set all the necessary values in the output maps\n    setVoxelPostFit(voxelIndex, model, vox, modelFitter, numErrors);\n\n\t\tlogProgress(numProcessed, double(numVoxels));\n  }\n\n\t// Get end time and log results\n\tauto fit_end = std::chrono::system_clock::now();\n\tstd::chrono::duration<double> elapsed_seconds = fit_end - fit_start;\n\t\n\tstd::stringstream ss;\n\tss << \"mdm_VolumeAnalysis: Processed \" << \n\t\tnumProcessed << \" voxels in \" << elapsed_seconds.count() << \"s.\\n\" << \n\t\tnumErrors << \" voxels returned fit errors\\n\";\n\tmdm_ProgramLogger::logProgramMessage(ss.str());\n}\n\n//\nvoid mdm_VolumeAnalysis::createMap(mdm_Image3D& img)\n{\n  if (!errorTracker_.errorImage())\n    throw mdm_exception(__func__,\n      \"Attempting to create parameter maps before any other images have been set to\"\n      \" to determine reference dimensions.\");\n\n  img.copy(errorTracker_.errorImage());\n\timg.setType(mdm_Image3D::ImageType::TYPE_KINETICMAP);\n}\n", "meta": {"hexsha": "57c797a17a19d1584a310c027f98c399175bc516", "size": 22931, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "madym/mdm_VolumeAnalysis.cxx", "max_stars_repo_name": "michaelberks/madym_cxx", "max_stars_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T15:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T15:43:15.000Z", "max_issues_repo_path": "madym/mdm_VolumeAnalysis.cxx", "max_issues_repo_name": "michaelberks/madym_cxx", "max_issues_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "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": "madym/mdm_VolumeAnalysis.cxx", "max_forks_repo_name": "michaelberks/madym_cxx", "max_forks_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "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.7873443983, "max_line_length": 96, "alphanum_fraction": 0.6944747285, "num_tokens": 6934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1937834969033229}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\nThis example program shows how to find frontal human faces in an image.  In\nparticular, this program shows how you can take a list of images from the\ncommand line and display each on the screen with red boxes overlaid on each\nhuman face.\nThe examples/faces folder contains some jpg images of people.  You can run\nthis program on them and see the detections by executing the following command:\n./face_detection_ex faces/*.jpg\nThis face detector is made using the now classic Histogram of Oriented\nGradients (HOG) feature combined with a linear classifier, an image pyramid,\nand sliding window detection scheme.  This type of object detector is fairly\ngeneral and capable of detecting many types of semi-rigid objects in\naddition to human faces.  Therefore, if you are interested in making your\nown object detectors then read the fhog_object_detector_ex.cpp example\nprogram.  It shows how to use the machine learning tools which were used to\ncreate dlib's face detector.\nFinally, note that the face detector is fastest when compiled with at least\nSSE2 instructions enabled.  So if you are using a PC with an Intel or AMD\nchip then you should enable at least SSE2 instructions.  If you are using\ncmake to compile this program you can enable them by using one of the\nfollowing commands when you create the build project:\ncmake path_to_dlib_root/examples -DUSE_SSE2_INSTRUCTIONS=ON\ncmake path_to_dlib_root/examples -DUSE_SSE4_INSTRUCTIONS=ON\ncmake path_to_dlib_root/examples -DUSE_AVX_INSTRUCTIONS=ON\nThis will set the appropriate compiler options for GCC, clang, Visual\nStudio, or the Intel compiler.  If you are using another compiler then you\nneed to consult your compiler's manual to determine how to enable these\ninstructions.  Note that AVX is the fastest but requires a CPU from at least\n2011.  SSE4 is the next fastest and is supported by most current machines.\n*/\n\n\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <dlib/gui_widgets.h>\n#include <dlib/image_io.h>\n#include <iostream>\n\nusing namespace dlib;\nusing namespace std;\n\n// ----------------------------------------------------------------------------------------\n\nint main(int argc, char** argv)\n{\n    try\n    {\n        if (argc == 1)\n        {\n            cout << \"Give some image files as arguments to this program.\" << endl;\n            return 0;\n        }\n\n        frontal_face_detector detector = get_frontal_face_detector();\n        image_window win;\n\n        // Loop over all the images provided on the command line.\n        for (int i = 1; i < argc; ++i)\n        {\n            cout << \"processing image \" << argv[i] << endl;\n            array2d<unsigned char> img;\n            load_image(img, argv[i]);\n            // Make the image bigger by a factor of two.  This is useful since\n            // the face detector looks for faces that are about 80 by 80 pixels\n            // or larger.  Therefore, if you want to find faces that are smaller\n            // than that then you need to upsample the image as we do here by\n            // calling pyramid_up().  So this will allow it to detect faces that\n            // are at least 40 by 40 pixels in size.  We could call pyramid_up()\n            // again to find even smaller faces, but note that every time we\n            // upsample the image we make the detector run slower since it must\n            // process a larger image.\n            pyramid_up(img);\n\n            // Now tell the face detector to give us a list of bounding boxes\n            // around all the faces it can find in the image.\n            std::vector<rectangle> dets = detector(img);\n\n            cout << \"Number of faces detected: \" << dets.size() << endl;\n            // Now we show the image on the screen and the face detections as\n            // red overlay boxes.\n            win.clear_overlay();\n            win.set_image(img);\n            win.add_overlay(dets, rgb_pixel(255, 0, 0));\n\n            cout << \"Hit enter to process the next image...\" << endl;\n            cin.get();\n        }\n    }\n    catch (exception& e)\n    {\n        cout << \"\\nexception thrown!\" << endl;\n        cout << e.what() << endl;\n    }\n}\n\n// ----------------------------------------------------------------------------------------\n", "meta": {"hexsha": "b42574ed935b4aac230709a70896134a37312900", "size": 4318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp-projects/tiny-apps/face-detection/main.cpp", "max_stars_repo_name": "juxiangwu/image-processing", "max_stars_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-09-07T02:29:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T08:40:09.000Z", "max_issues_repo_path": "cpp-projects/tiny-apps/face-detection/main.cpp", "max_issues_repo_name": "juxiangwu/image-processing", "max_issues_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "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-projects/tiny-apps/face-detection/main.cpp", "max_forks_repo_name": "juxiangwu/image-processing", "max_forks_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-20T00:09:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T10:14:36.000Z", "avg_line_length": 44.5154639175, "max_line_length": 91, "alphanum_fraction": 0.6567855489, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.19378349690332286}}
{"text": "\ufeff#define INFO\n#define TIMER\n#define _USE_MATH_DEFINES\n#include <GL/glew.h>\n\n#include <cuda_gl_interop.h>\n#include <cuda_runtime_api.h>\n\n#ifdef __gnu_linux__\n#include <sys/types.h>\n#include <sys/stat.h>\n#elif _WIN32\n#include <direct.h>\n#else \n#error \"OS not supported!\"\n#endif\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost/scoped_ptr.hpp>\n#include <boost/filesystem.hpp>\n\n#include <opencv2/core.hpp>\n#include <opencv2/cudaimgproc.hpp>\n#include <opencv2/cudaarithm.hpp>\n\n//camera calibration from a sequence of images\n#include <Eigen/Dense>\n#include <opencv2/cudaarithm.hpp>\n#include <OpenNI.h>\n#include \"Kinect.h\"\n#include \"GLUtil.hpp\"\n#include \"Camera.h\"\n#include \"VideoSourceKinect.hpp\"\n\n//Qt\n#include <QGLViewer/qglviewer.h>\n#include \"Data4Viewer.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\nusing namespace qglviewer;\n\n\n\n\nData4Viewer::Data4Viewer(){\n\t_uResolution = 0;\n\t_uPyrHeight = 3;\n\t_Cw = Eigen::Vector3d(0.f,0.f,0.f);\n\t_nStatus = 01;//1 restart; 2 //recording continue 3://pause 4://dump\n}\nData4Viewer::~Data4Viewer()\n{\n}\n\nvoid Data4Viewer::init()\n{\n\tGLenum eError = glewInit(); \n\tif (GLEW_OK != eError){\n\t\tcout << (\"glewInit() error.\") << endl;\n\t\tcout << ( glewGetErrorString(eError) ) << endl;\n\t}\n\tloadFromYml();\n\treset();\n\n\treturn;\n}//init()\n\n\nvoid Data4Viewer::loadFromYml(){\n\treturn;\n}\n\nvoid Data4Viewer::reset(){\n\treturn;\n}\n\nvoid Data4Viewer::drawGlobalView()\n{\n\t_pKinect->_pRGBCamera->setGLProjectionMatrix(0.1f, 100.f);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tEigen::Affine3d tmp; tmp.setIdentity();\n\tEigen::Matrix4d mMat;\n\tmMat.row(0) = tmp.matrix().row(0);\n\tmMat.row(1) = -tmp.matrix().row(1);\n\tmMat.row(2) = -tmp.matrix().row(2);\n\tmMat.row(3) = tmp.matrix().row(3);\n\n\tglLoadMatrixd(mMat.data());\n\tGpuMat rgb(_pKinect->_cvmRGB);\n\t_pKinect->_pRGBCamera->renderCameraInLocal(rgb, _pGL.get(), false, NULL, 0.2f, true); //render in model coordinate\n\t//cout<<(\"drawRGBView\");\n\treturn;\n}\n\n#define INFO\n#define TIMER\n", "meta": {"hexsha": "0590ac0145b50adfbb9bbc355ee8a0cfc9a82197", "size": 1970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calibration/multi_expo_capturer/multi_exposure_capturer/Data4Viewer.cpp", "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": "calibration/multi_expo_capturer/multi_exposure_capturer/Data4Viewer.cpp", "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": "calibration/multi_expo_capturer/multi_exposure_capturer/Data4Viewer.cpp", "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": 19.3137254902, "max_line_length": 115, "alphanum_fraction": 0.7086294416, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.19378349139863893}}
{"text": "/*  gameplayutility %{Cpp:License:ClassName} - Yann BOUCHER (yann) 04/06/2016\n**\n**\n**            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n**                    Version 2, December 2004\n**\n** Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>\n**\n** Everyone is permitted to copy and distribute verbatim or modified\n** copies of this license document, and changing it is allowed as long\n** as the name is changed.\n**\n**            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n**   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n**\n**  0. You just DO WHAT THE FUCK YOU WANT TO.\n*/\n\n#include \"utils/gameplayglobals.hpp\"\n\n#include <atomic>\n#include <thread>\n\n#include <boost/optional.hpp>\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include <SFML/Audio/Sound.hpp>\n#include <SFML/System/Sleep.hpp>\n\n#include <Thor/Math/Trigonometry.hpp>\n#include <Thor/Math/Random.hpp>\n\n#include \"actor.hpp\"\n\n#include \"raycasting.hpp\"\n#include \"utils/mathutility.hpp\"\n#include \"utils/graphicsutility.hpp\"\n#include \"map.hpp\"\n\n#include \"constants.hpp\"\n\n#include <iostream>\n\nnamespace Rayfun\n{\n\nstatic std::atomic_size_t g_soundNumber { 0 };\n\nboost::optional<Actor&> fireBullets(Actor &t_actor, const sf::Vector2d &t_src, const sf::Vector2d &t_dir,\n                                    const sf::Vector2d &t_spread, Map& t_map, const State::Context &t_context,\n                                    size_t t_damage, size_t t_num, const std::string &t_dmgType,\n                                    size_t t_maxDistance)\n{\n    std::sort(t_map.sprites.begin(), t_map.sprites.end(), [&t_actor](std::unique_ptr<DrawableActor>& rhs,\n              std::unique_ptr<DrawableActor>& lhs){\n        return Utility::distance(rhs->pos, t_actor.pos) < Utility::distance(lhs->pos, t_actor.pos);\n    });\n\n    for (size_t i { 0 }; i < t_num; ++i)\n    {\n        sf::Vector2d unitVector = Utility::angleToVector<double>(thor::random(0, 360));\n        double spreadIntensity = thor::random(0.f, 1.f);\n        sf::Vector2d dev { t_spread.x * spreadIntensity, t_spread.y * spreadIntensity };\n        dev = thor::cwiseProduct(unitVector, dev);\n\n        DrawableActor* actor = nullptr;\n        if (Raycasting::rayIntersectsSprite(t_src, Utility::angleToVector(dev.x + thor::polarAngle(t_dir)),\n                                            t_map, actor))\n        {\n            if (actor && actor->ondamage)\n            {\n                actor->ondamage(t_actor, *actor, t_damage, t_dmgType);\n            }\n            //TODO: implement puffs ?\n        }\n        else\n        {\n            auto result = Raycasting::castRay(t_src, Utility::angleToVector(dev.x + thor::polarAngle(t_dir)),\n                                              t_map, Raycasting::HitMode::Visibility).back();\n\n            if (result.tileHit && result.tileHit->tex[result.side] != 0)\n            {\n                if (result.distance > t_maxDistance)\n                {\n                    return boost::none;\n                }\n\n                if (!result.tileHit->decals[result.side])\n                {\n                    result.tileHit->decals[result.side] = sf::Image();\n                }\n                auto& decal = *(result.tileHit->decals[result.side]);\n\n                // FIXME : again find a way to get texture size by ID !\n\n                if (true /*decal.getSize() != {64, 64 }*/)\n                {\n                    decal.create(64,\n                            64, sf::Color::Transparent);\n                }\n\n                double wallX { 0 };\n                if (result.side == Side::North || result.side == Side::South)\n                {\n                    wallX = result.hitPos.y - std::floor(result.hitPos.y);\n                }\n                else\n                {\n                    wallX = result.hitPos.x - std::floor(result.hitPos.x);\n                }\n                if (result.side == Side::South || result.side == Side::West)\n                {\n                    wallX = 1 - wallX;\n                }\n                wallX *= decal.getSize().x;\n                double wallY = decal.getSize().y / 2.f + (result.distance / 2.f) * std::tan(thor::toRadian(dev.y))\n                               * decal.getSize().y;\n                if (result.tileHit && wallY >= 0 && wallY <= decal.getSize().y)\n                {\n                    Utility::addDecal(decal, t_context.resources.imageHolder[\"decals/bullet\"],\n                            sf::Vector2s(wallX, wallY), true);\n                    if (result.tileHit->ondamage[result.side])\n                    {\n                        result.tileHit->ondamage[result.side](t_actor, *result.tileHit, t_damage, t_dmgType);\n                    }\n                }\n            }\n        }\n    }\n\n    return boost::none;\n}\n\nvoid playSoundAt(const Resources &t_res, const std::string &t_sound,\n                 const sf::Vector2f& t_pos, float t_volume)\n{\n    if (g_soundNumber < c_maxSounds)\n    {\n        std::thread([&t_res, t_volume, t_sound, t_pos]{\n            ++g_soundNumber;\n            sf::Sound *sound = new sf::Sound;\n            sound->setBuffer(t_res.soundHolder[t_sound]);\n            sound->setVolume(t_volume);\n            sound->setPosition(t_pos.x, t_pos.y, 0);\n            sound->play();\n            while (sound->getStatus() == sf::Sound::Playing)\n            {sf::sleep(sf::seconds(0.1f));};\n            delete sound;\n            --g_soundNumber;\n        }).detach();\n    }\n}\n\nvoid playSoundUI(const Resources &t_res, const std::string &t_sound, float t_volume)\n{\n    if (g_soundNumber < c_maxSounds)\n    {\n        std::thread([&t_res, t_volume, t_sound]{\n            ++g_soundNumber;\n            sf::Sound *sound = new sf::Sound;\n            sound->setBuffer(t_res.soundHolder[t_sound]);\n            sound->setVolume(t_volume);\n            sound->setRelativeToListener(true);\n            sound->setPosition(0, 0, 0);\n            sound->play();\n            while (sound->getStatus() == sf::Sound::Playing)\n            {sf::sleep(sf::seconds(0.1f));};\n            delete sound;\n            --g_soundNumber;\n        }).detach();\n    }\n}\n\nbool spriteClipAt(const sf::Vector2d &t_pos, Map &t_map, DrawableActor *&t_hitSprite)\n{\n    typedef boost::geometry::model::d2::point_xy<double> Point;\n    Point origin = {t_pos.x, t_pos.y};\n\n    for (auto& sprite : t_map.sprites)\n    {\n        sf::Image img = sprite->renderImage();\n        boost::geometry::model::polygon<Point> spriteRect;\n        double largestSide = std::max<double>(img.getSize().x, img.getSize().y);\n        double side = img.getSize().x / largestSide;\n        std::vector<Point> points =\n        {\n            {sprite->pos.x - side / 2, sprite->pos.x - side / 2},\n            {sprite->pos.x - side / 2, sprite->pos.x + side / 2},\n            {sprite->pos.x + side / 2, sprite->pos.x + side / 2},\n            {sprite->pos.x + side / 2, sprite->pos.x - side / 2}\n        };\n        boost::geometry::assign_points(spriteRect, points);\n        if (boost::geometry::intersects(origin, spriteRect))\n        {\n            if (sprite->clip)\n            {\n                t_hitSprite = sprite.get();\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\n}\n", "meta": {"hexsha": "914e392b307d61b8f6dddc37bd222aa5f9b5377f", "size": 7252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/gameplayglobals.cpp", "max_stars_repo_name": "Stellaris-code/Rayfun", "max_stars_repo_head_hexsha": "2c9e5e2b0cd1636f0a046d6dce0efdce60f094cb", "max_stars_repo_licenses": ["WTFPL"], "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/gameplayglobals.cpp", "max_issues_repo_name": "Stellaris-code/Rayfun", "max_issues_repo_head_hexsha": "2c9e5e2b0cd1636f0a046d6dce0efdce60f094cb", "max_issues_repo_licenses": ["WTFPL"], "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/gameplayglobals.cpp", "max_forks_repo_name": "Stellaris-code/Rayfun", "max_forks_repo_head_hexsha": "2c9e5e2b0cd1636f0a046d6dce0efdce60f094cb", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6985645933, "max_line_length": 114, "alphanum_fraction": 0.5348869277, "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.1937541840877027}}
{"text": "// Copyright (c) 2015-2018 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 \"read_assigner.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <algorithm>\n#include <limits>\n#include <random>\n#include <stdexcept>\n#include <cassert>\n\n#include <boost/optional.hpp>\n\n#include \"utils/maths.hpp\"\n#include \"utils/kmer_mapper.hpp\"\n#include \"core/models/haplotype_likelihood_model.hpp\"\n#include \"core/models/error/error_model_factory.hpp\"\n\nnamespace octopus {\n\nnamespace {\n\nusing HaplotypeLikelihoods = std::vector<std::vector<double>>;\n\nvoid find_max_likelihood_haplotypes(const std::vector<Haplotype>& haplotypes, const unsigned read,\n                                    const HaplotypeLikelihoods& likelihoods,\n                                    std::vector<unsigned>& result)\n{\n    assert(result.empty());\n    auto max_likelihood = std::numeric_limits<double>::lowest();\n    for (unsigned k {0}; k < haplotypes.size(); ++k) {\n        const auto curr = likelihoods[k][read];\n        if (maths::almost_equal(curr, max_likelihood)) {\n            result.push_back(k);\n        } else if (curr > max_likelihood) {\n            result.assign({k});\n            max_likelihood = curr;\n        }\n    }\n    if (result.empty()) {\n        result.resize(haplotypes.size());\n        std::iota(std::begin(result), std::end(result), 0);\n    }\n}\n\ntemplate <typename ForwardIt, typename RandomGenerator>\nForwardIt random_select(ForwardIt first, ForwardIt last, RandomGenerator& g)\n{\n    if (first == last) return first;\n    const auto max = static_cast<std::size_t>(std::distance(first, last));\n    if (max == 1) return first;\n    std::uniform_int_distribution<std::size_t> dist {0, max - 1};\n    std::advance(first, dist(g));\n    return first;\n}\n\ntemplate <typename ForwardIt>\nForwardIt random_select(ForwardIt first, ForwardIt last)\n{\n    static thread_local std::mt19937 generator {42};\n    return random_select(first, last, generator);\n}\n\ntemplate <typename Range>\ndecltype(auto) random_select(const Range& values)\n{\n    assert(!values.empty());\n    return *random_select(std::cbegin(values), std::cend(values));\n}\n\nauto calculate_support(const std::vector<Haplotype>& haplotypes,\n                       const std::vector<AlignedRead>& reads,\n                       const HaplotypeLikelihoods& likelihoods,\n                       boost::optional<std::deque<AlignedRead>&> ambiguous,\n                       AssignmentConfig config)\n{\n    HaplotypeSupportMap result {};\n    std::vector<unsigned> top {};\n    top.reserve(haplotypes.size());\n    for (unsigned i {0}; i < reads.size(); ++i) {\n        find_max_likelihood_haplotypes(haplotypes, i, likelihoods, top);\n        if (top.size() == 1) {\n            result[haplotypes[top.front()]].push_back(reads[i]);\n        } else {\n            using UA = AssignmentConfig::AmbiguousAction;\n            switch (config.ambiguous_action) {\n                case UA::first:\n                    result[haplotypes[top.front()]].push_back(reads[i]);\n                    break;\n                case UA::all: {\n                    for (auto idx : top) result[haplotypes[idx]].push_back(reads[i]);\n                    break;\n                }\n                case UA::random: {\n                    result[haplotypes[random_select(top)]].push_back(reads[i]);\n                    break;\n                }\n                case UA::drop:\n                default:\n                    break;\n            }\n            if (ambiguous) ambiguous->push_back(reads[i]);\n        }\n        top.clear();\n    }\n    return result;\n}\n\nauto max_deletion_size(const std::vector<Haplotype>& haplotypes)\n{\n    unsigned result {0};\n    for (const auto& haplotype : haplotypes) {\n        if (region_size(haplotype) > sequence_size(haplotype)) {\n            auto diff = static_cast<unsigned>(region_size(haplotype) - sequence_size(haplotype));\n            result = std::max(result, diff);\n        }\n    }\n    return result;\n}\n\nauto compute_read_hashes(const std::vector<AlignedRead>& reads)\n{\n    static constexpr unsigned char mapperKmerSize {6};\n    std::vector<KmerPerfectHashes> result {};\n    result.reserve(reads.size());\n    std::transform(std::cbegin(reads), std::cend(reads), std::back_inserter(result),\n                   [=] (const AlignedRead& read) { return compute_kmer_hashes<mapperKmerSize>(read.sequence()); });\n    return result;\n}\n\nauto calculate_likelihoods(const std::vector<Haplotype>& haplotypes,\n                           const std::vector<AlignedRead>& reads,\n                           HaplotypeLikelihoodModel& model)\n{\n    assert(!haplotypes.empty());\n    const auto& haplotype_region = mapped_region(haplotypes.front());\n    const auto reads_region = encompassing_region(reads);\n    const auto min_flank_pad = HaplotypeLikelihoodModel::pad_requirement();\n    unsigned min_lhs_expansion{2 * min_flank_pad}, min_rhs_expansion{2 * min_flank_pad};\n    if (begins_before(reads_region, haplotype_region)) {\n        min_lhs_expansion += begin_distance(reads_region, haplotype_region);\n    }\n    if (ends_before(haplotype_region, reads_region)) {\n        min_rhs_expansion += end_distance(haplotype_region, reads_region);\n    }\n    const auto min_expansion = std::max(min_lhs_expansion, min_rhs_expansion) + max_deletion_size(haplotypes);\n    const auto read_hashes = compute_read_hashes(reads);\n    static constexpr unsigned char mapperKmerSize {6};\n    auto haplotype_hashes = init_kmer_hash_table<mapperKmerSize>();\n    HaplotypeLikelihoods result{};\n    result.reserve(haplotypes.size());\n    for (const auto& haplotype : haplotypes) {\n        const auto expanded_haplotype = expand(haplotype, min_expansion);\n        populate_kmer_hash_table<mapperKmerSize>(expanded_haplotype.sequence(), haplotype_hashes);\n        auto haplotype_mapping_counts = init_mapping_counts(haplotype_hashes);\n        model.reset(expanded_haplotype);\n        std::vector<double> likelihoods(reads.size());\n        std::transform(std::cbegin(reads), std::cend(reads), std::cbegin(read_hashes), std::begin(likelihoods),\n                       [&] (const auto& read, const auto& read_hash) {\n                           auto mapping_positions = map_query_to_target(read_hash, haplotype_hashes, haplotype_mapping_counts);\n                           reset_mapping_counts(haplotype_mapping_counts);\n                           return model.evaluate(read, mapping_positions);\n                       });\n        clear_kmer_hash_table(haplotype_hashes);\n        result.push_back(std::move(likelihoods));\n    }\n    return result;\n}\n\n} // namespace\n\nHaplotypeSupportMap compute_haplotype_support(const Genotype<Haplotype>& genotype,\n                                              const std::vector<AlignedRead>& reads,\n                                              HaplotypeLikelihoodModel model,\n                                              boost::optional<std::deque<AlignedRead>&> ambiguous,\n                                              AssignmentConfig config)\n{\n    if (!genotype.is_homozygous() && !reads.empty()) {\n        const auto unique_haplotypes = genotype.copy_unique();\n        assert(unique_haplotypes.size() > 1);\n        const auto likelihoods = calculate_likelihoods(unique_haplotypes, reads, model);\n        return calculate_support(unique_haplotypes, reads, likelihoods, ambiguous, config);\n    } else {\n        return {};\n    }\n}\n\nHaplotypeSupportMap compute_haplotype_support(const Genotype<Haplotype>& genotype,\n                                              const std::vector<AlignedRead>& reads,\n                                              std::deque<AlignedRead>& ambiguous,\n                                              AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, HaplotypeLikelihoodModel {nullptr, make_indel_error_model(), false}, ambiguous, config);\n}\n\nHaplotypeSupportMap compute_haplotype_support(const Genotype<Haplotype>& genotype,\n                                              const std::vector<AlignedRead>& reads,\n                                              AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, HaplotypeLikelihoodModel {nullptr, make_indel_error_model(), false}, config);\n}\n\nHaplotypeSupportMap compute_haplotype_support(const Genotype<Haplotype>& genotype,\n                                              const std::vector<AlignedRead>& reads,\n                                              HaplotypeLikelihoodModel model,\n                                              AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, std::move(model), boost::none, config);\n}\n\nHaplotypeSupportMap compute_haplotype_support(const Genotype<Haplotype>& genotype,\n                                              const std::vector<AlignedRead>& reads,\n                                              std::deque<AlignedRead>& ambiguous,\n                                              HaplotypeLikelihoodModel model,\n                                              AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, std::move(model), ambiguous, config);\n}\n\nAlleleSupportMap compute_allele_support(const std::vector<Allele>& alleles,\n                                        const HaplotypeSupportMap& haplotype_support)\n{\n    return compute_allele_support(alleles, haplotype_support,\n                                  [] (const Haplotype& haplotype, const Allele& allele) {\n                                      return haplotype.includes(allele);\n                                  });\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "d17b5dbd6019adb1105f698c91db2d00303ee7b6", "size": 9615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/tools/read_assigner.cpp", "max_stars_repo_name": "alimanfoo/octopus", "max_stars_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-21T23:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T23:34:28.000Z", "max_issues_repo_path": "src/core/tools/read_assigner.cpp", "max_issues_repo_name": "alimanfoo/octopus", "max_issues_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_issues_repo_licenses": ["MIT"], "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/tools/read_assigner.cpp", "max_forks_repo_name": "alimanfoo/octopus", "max_forks_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_forks_repo_licenses": ["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.4439655172, "max_line_length": 142, "alphanum_fraction": 0.613624545, "num_tokens": 2020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.19374785261872624}}
{"text": "#include<cstdlib>\n#include<algorithm>\n#include<complex>\n#include<iostream>\n#include<fstream>\n#include<map>\n#include<utility>\n#include<vector>\n#include<numeric>\n#if defined(USE_MPI)\n#include<mpi.h>\n#endif\n\n#include <Platforms/sysutil.h>\n#include \"OhmmsData/libxmldefs.h\"\n#include \"OhmmsData/AttributeSet.h\"\n#include \"OhmmsData/ParameterSet.h\"\n#include \"Utilities/SimpleParser.h\"\n#include \"Configuration.h\"\n#include \"io/hdf_archive.h\"\n#include \"Message/CommOperators.h\"\n\n#include <boost/interprocess/managed_shared_memory.hpp>\n#include <boost/interprocess/containers/vector.hpp>\n#include <boost/interprocess/allocators/allocator.hpp>\n#include <boost/interprocess/sync/interprocess_condition.hpp>\n#include <boost/interprocess/sync/interprocess_mutex.hpp>\n#include <boost/interprocess/sync/scoped_lock.hpp>\n#include <boost/interprocess/exceptions.hpp>\n\n#include \"AFQMC/config.h\"\n#include \"AFQMC/Hamiltonians/HamiltonianBase.h\"\n#include \"AFQMC/Hamiltonians/SparseGeneralHamiltonian.h\"\n#include \"AFQMC/Utilities/readHeader.h\"\n#include \"AFQMC/Numerics/DenseMatrixOperations.h\"\n#include \"AFQMC/Numerics/SparseMatrixOperations.h\"\n#include \"AFQMC/Utilities/Utils.h\"\n#include \"AFQMC/Matrix/hdf5_readers.hpp\"\n#include \"AFQMC/Matrix/array_partition.hpp\"\n\n// use lambdas FIX FIX FIX\n struct my_pair_sorter {\n  bool operator() (std::pair<qmcplusplus::RealType,int> a, std::pair<qmcplusplus::RealType,int> b) {return a.first<b.first;}\n  bool operator() (std::pair<std::complex<qmcplusplus::RealType>,int> a, std::pair<std::complex<qmcplusplus::RealType>,int> b) {return a.first.real()<b.first.real();}\n} myobject;\n\nnamespace qmcplusplus\n{\n\n\n  bool SparseGeneralHamiltonian::readFCIDUMP(const std::string& fileName, bool minimizeIO) //,\n//      std::vector<s2D<ValueType> >& hij, std::vector<s4D<ValueType> >& Vijkl)\n  {\n\n    int rnk=0;\n#if defined(USE_MPI)\n    rnk = rank();\n#endif\n\n    std::vector<s2D<ValueType> > hij_core;\n    std::vector<s4D<ValueType> > Vijkl_core, Vijkl_mixed;\n    ValueSMSpMat V2_fact_c, V2_fact_m;\n    \n     std::ifstream in;\n     in.open(fileName.c_str());\n     if(in.fail()) {\n        app_error()<<\"Problems opening ASCII integral file:  \" <<fileName <<std::endl;\n        return false;\n     }\n\n     if(!readHeader(in,NMAX,NMO_FULL,NETOT,NAEA,NAEB,NCA,NCB,MS2,spinRestricted,ISYM,occup_alpha,occup_beta,orbSymm,occupPerSymm_alpha,occupPerSymm_beta,orderStates,factorizedHamiltonian)) {\n       app_error()<<\" Error: Problem with header section of file. \\n\";\n       return false;\n     }\n\n     NMO = NMO_FULL-NCA;\n\n     // no hamiltonian distribution yet\n     min_i = 0;\n     max_i = NMO;\n     if(!spinRestricted) max_i *= 2;  // or 4?\n\n     if(orderStates && NMAX != NMO_FULL) {\n       app_error()<<\"Error in SparseGeneralHamiltonian::readFCIDUMP. orderStates can not be used in combination with NMAX!=NMO_FULL. \\n \";\n       return false;\n     }\n\n     if(NCA != NCB) {\n       app_error()<<\"Error in SparseGeneralHamiltonian::readFCIDUMP. NCA!=NCB. Not sure how to implement this! \\n\";\n       return false;\n     }\n\n     // MMORALES: It is possible to define variables (e.g. NMO_FULL, NAEA, ...) in the input xml file and these might be different from those in this file. But after the file header is read, all variables must be in an initialized state  \n     if(!checkAFQMCInfoState()) {\n       app_error()<<\" ERROR: Problem with basic parameters during Hamiltonian initialization. \\n\"\n                  <<\"        State of Hamiltonian::AFQMCInfo after reading header section of ASCII integral file. \\n\" <<std::endl;\n       printAFQMCInfoState(app_error());  \n       return false;\n     } \n     \n     if(!spinRestricted) app_log()<<\"Found UHF orbitals in Molpro integral file. Running Spin-Unrestricted calculation. \\n\";\n     else \n       app_log()<<\"Found RHF/ROHF orbitals in Molpro integral file. Running Spin-Restricted calculation. \\n\";\n\n     if(occup_alpha.size() == 0 && occup_beta.size() == 0 ) {\n       app_log()<<\" WARNING: OCCUP tag not found on integral file. Assuming ground-state occupation. \\n\";\n       occup_alpha.resize(NAEA);\n       occup_beta.resize(NAEB);\n       for(int i=0; i<NAEA; i++) occup_alpha[i]=i;\n       for(int i=0; i<NAEB; i++) occup_beta[i]=i+NMO;\n     }\n\n     if(occup_alpha.size() != NAEA) {\n       app_error() <<\"Error: size of OCCUP_ALPHA must be equal to NAEA. \\n\" <<std::endl;\n       return false;\n     }\n     if(occup_beta.size() != NAEB) {\n       app_error() <<\"Error: size of OCCUP_BETA must be equal to NAEB. \\n\" <<std::endl;\n       return false;\n     }\n\n\n     std::streampos start = in.tellg();\n     int nOne_core,nOne,nTwo,nTwo_core,nTwo_mixed;\n     int nThree,nThree_core,nThree_mixed;\n\n     std::map<IndexType,IndexType> orbMapA; \n     std::map<IndexType,IndexType> orbMapB; \n     orbMapA[0]=0;\n     orbMapB[0]=0;\n     for(int i=1; i<=NMO_FULL; i++) orbMapA[i]=i;   \n     for(int i=1; i<=NMO_FULL; i++) orbMapB[i]=i+NMO_FULL;   \n\n     // setup SM objects \n     V2.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_V2\"),TG.getNodeCommLocal());\n     V2_full.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_V2_full\"),TG.getNodeCommLocal());\n\n     V2_fact.setup(head_of_nodes,\"V2_fact\",TG.getNodeCommLocal());\n     V2_fact_c.setup(head_of_nodes,\"V2_fact_c\",TG.getNodeCommLocal());\n     V2_fact_m.setup(head_of_nodes,\"V2_fact_m\",TG.getNodeCommLocal());\n     int n3Vecs=0;\n\n     if(orderStates) { \n     // hacking these routines a bit to allow FC rotation \n    \n     // app_error()<<\" Error: reordering of states has benn temporarily disabled!!! \" <<std::endl;\n     // return false;\n \n      int NCA_tmp=NCA, NCB_tmp=NCB;\n      NCA=NCB=0;\n      NMO=NMO_FULL;\n\n    app_log()<<\" Free memory before count() : \" <<freemem() <<\" MB. \\n\";\n    \n      if(!countElementsFromFCIDUMP(in,nOne,nOne_core,nTwo,nTwo_core,nTwo_mixed,nThree,nThree_core,nThree_mixed,orbMapA,orbMapB,n3Vecs)) {\n        app_error()<<\"Error in readFCIDUMP. Problem counting elements. \\n\" <<std::endl;\n        return false;\n      }\n\n    app_log()<<\" Free memory after count() : \" <<freemem() <<\" MB. \\n\";\n\n      if(nThree > 0)  {\n        if(nTwo > 0) {\n          app_error()<<\"Found both 3-Index and 4-Index terms in FCIDUMP. Only one form is allowed. \" <<std::endl; \n          return false;\n        }\n        factorizedHamiltonian = true;\n      } else\n        factorizedHamiltonian = false;\n\n      if(nOne_core > 0 || nTwo_core > 0 || nTwo_mixed > 0 || nThree_core > 0 || nThree_mixed > 0) {\n        app_error()<<\"Error in readFCIDUMP. Problem counting elements. #core > 0 in orderStates. \\n\" <<std::endl;\n        return false;\n      }\n      if(factorizedHamiltonian) {\n        int NMO2 = NMO*NMO;\n        if(!spinRestricted) NMO2 *= 2; \n        V2_fact.setDims(NMO2,n3Vecs);\n        V2_fact_c.setDims(NMO2,n3Vecs);\n        V2_fact_m.setDims(NMO2,n3Vecs);\n        V2_fact.reserve(nThree);    // V2_fact must be reserved, since elements are added with \"add\" \n      } else {\n        if(n3Vecs > 0) {\n          app_error()<<\"Found three index terms in FCIDUMP. (Only allowed with factorized hamiltonian. Check!!!\" <<std::endl;\n          APP_ABORT(\"Found three index terms in FCIDUMP. (Only allowed with factorized hamiltonian. Check!!!\");\n        }\n        V2.resize(nTwo);\n      }\n\n      app_log()<<\" Number of one- and two- electron integrals read from file (assuming no core states for rotation)  : \" <<nOne <<\" \" <<nTwo <<std::endl;\n\n      in.clear();\n      in.seekg(start);\n\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      H1.resize(nOne); \n      hij_core.resize(nOne_core); \n\n      Vijkl_core.resize(nTwo_core);  \n      Vijkl_mixed.resize(nTwo_mixed);  \n\n      if(!readElementsFromFCIDUMP(in,H1,hij_core,V2,Vijkl_core,Vijkl_mixed,V2_fact,V2_fact_c,V2_fact_m,orbMapA,orbMapB)) {\n        app_error()<<\"Error in return from readElementsFromFCIDUMP in readFCIDUMP.\\n\" <<std::endl; \n        return false;\n      }\n\n      if(factorizedHamiltonian ) {\n        if(H1.size() != nOne || hij_core.size() != nOne_core) {\n          app_error()<<\"Error after readElementsFromFCIDUMP in readFCIDUMP, wrong number of elements.\\n\" <<std::endl;\n          return false;\n        }\n      } else {\n        if(H1.size() != nOne || hij_core.size() != nOne_core  || V2.size()!=nTwo ||  Vijkl_core.size()!=nTwo_core ||  Vijkl_mixed.size()!=nTwo_mixed) {\n          app_error()<<\"Error after readElementsFromFCIDUMP in readFCIDUMP, wrong number of elements.\\n\" <<std::endl;\n          return false;\n        }\n      }\n\n      Timer.stop(\"Generic\");\n      if(rnk==0) app_log()<<\" -- Time to read ASCII integral file: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n\n      if(occupPerSymm_alpha.size() != occupPerSymm_beta.size()) {\n        app_error()<<\" Error: Different number of symmetry groups between alpha/beta. \\n\";\n        return false; \n      } \n      int nSym=occupPerSymm_alpha.size();\n      std::vector< std::vector<int> > OrbsPerSymm(nSym);\n      for(int i=0; i<orbSymm.size(); i++) \n        OrbsPerSymm[orbSymm[i]-1].push_back(i);\n\n      // sort integral tables\n      std::sort (H1.begin(), H1.end(),mySort);\n      if(factorizedHamiltonian)\n        V2_fact.compress();\n      else\n        if(head_of_nodes) std::sort (V2.begin(), V2.end(),mySort);\n      myComm->barrier();\n    \n      orbMapA.clear(); \n      orbMapA[0]=0;\n      orbMapB.clear(); \n      orbMapB[0]=0;\n\n      if(spinRestricted) {\n        std::vector< std::pair<ValueType,int> > orbEnergies(NMO_FULL);\n\n        for(IndexType i=0; i<NMO_FULL; i++) {\n          orbEnergies[i].second = i+1; \n          orbEnergies[i].first = H(i,i); \n          // loop through symmetry groups\n          for(int j=0; j<occupPerSymm_alpha.size(); j++) {\n            // loop through all orbitals in symmetry group j\n            for(int k=0; k<occupPerSymm_alpha[j]; k++) {\n              int b = OrbsPerSymm[j][k];\n              if(i != b) orbEnergies[i].first += (H(i,b,i,b)-H(i,b,b,i));\n            }\n          }\n          for(int j=0; j<occupPerSymm_beta.size(); j++) {\n            for(int k=0; k<occupPerSymm_beta[j]; k++) {\n              int b = OrbsPerSymm[j][k]+NMO_FULL;\n              orbEnergies[i].first += H(i,b,i,b);\n            }\n          }\n        }\n\n        std::sort(orbEnergies.begin(),orbEnergies.end(),myobject);\n        for(int i=0; i<orbEnergies.size(); i++) orbMapA[orbEnergies[i].second] = i+1;\n        for(int i=0; i<orbEnergies.size(); i++) orbMapB[orbEnergies[i].second] = i+1+NMO_FULL;\n\n        if(rnk==0) {\n          app_log()<<\"Re-ordering orbitals to order them by energy. \\n\"\n              <<\"New Index      Old Index      Orbital Energy: \" <<\"\\n\";\n          for(int i=0; i<NMO_FULL; i++) \n            app_log()<<i+1     <<\"    \"    <<orbEnergies[i].second    <<\"     \"   <<orbEnergies[i].first <<\"\\n\"; \n        }\n\n      } else {\n\n        std::vector< std::pair<ValueType,int> > orbEnergies(NMO_FULL*2);\n        for(int i=0; i<NMO_FULL; i++) {\n          orbEnergies[i].second = i+1;\n          orbEnergies[i].first = H(i,i); \n          orbEnergies[i+NMO_FULL].second = i+1;\n          orbEnergies[i+NMO_FULL].first = H(NMO_FULL+i,NMO_FULL+i); \n          // loop through symmetry groups\n          for(int j=0; j<occupPerSymm_alpha.size(); j++) {\n            for(int k=0; k<occupPerSymm_alpha[j]; k++) {\n              int b = OrbsPerSymm[j][k];\n              if(i != b) orbEnergies[i].first += (H(i,b,i,b)-H(i,b,b,i));\n              orbEnergies[i+NMO_FULL].first += (H(i+NMO_FULL,b,i+NMO_FULL,b)-H(i+NMO_FULL,b,b,i+NMO_FULL));\n            }\n          }\n          for(int j=0; j<occupPerSymm_beta.size(); j++) {\n            for(int k=0; k<occupPerSymm_beta[j]; k++) {\n              int b = OrbsPerSymm[j][k]+NMO_FULL;\n              orbEnergies[i].first += (H(i,b,i,b)-H(i,b,b,i));\n              if(i+NMO_FULL != b) orbEnergies[i+NMO_FULL].first += (H(i+NMO_FULL,b,i+NMO_FULL,b)-H(i+NMO_FULL,b,b,i+NMO_FULL));\n            }\n          }\n        }\n\n        std::sort(orbEnergies.begin(),orbEnergies.begin()+NMO_FULL,myobject);\n        for(int i=0; i<NMO_FULL; i++) orbMapA[orbEnergies[i].second] = i+1;\n        std::sort(orbEnergies.begin()+NMO_FULL,orbEnergies.end(),myobject);\n        for(int i=0; i<NMO_FULL; i++) orbMapB[orbEnergies[i+NMO_FULL].second] = i+1+NMO_FULL;\n\n        if(rnk==0) {\n          app_log()<<\"Re-ordering orbitals to order them by energy. \\n\"\n              <<\"New Index      Old Index      Orbital Energy   : \" <<\"\\n\";\n          for(int i=0; i<NMO_FULL; i++) {\n            app_log()<<i+1     <<\" alpha   \"    <<orbEnergies[i].second    <<\"     \"   <<orbEnergies[i].first <<\"\\n\";\n            app_log()<<\"  \"     <<\" beta   \"    <<orbEnergies[i+NMO_FULL].second    <<\"     \"   <<orbEnergies[i+NMO_FULL].first <<\"\\n\";\n          }\n        }\n\n      } \n\n       in.clear();\n       in.seekg(start);\n\n       // restore values\n       NCA=NCA_tmp;\n       NCB=NCB_tmp;\n       NMO=NMO_FULL-NCA;\n\n       V2_fact.clear();\n\n       myComm->barrier();\n     } \n\n     if(!countElementsFromFCIDUMP(in,nOne,nOne_core,nTwo,nTwo_core,nTwo_mixed,nThree,nThree_core,nThree_mixed,orbMapA,orbMapB,n3Vecs)) {\n       app_error()<<\"Error in readFCIDUMP. Problem counting elements. \\n\" <<std::endl;\n       return false;\n     }\n\n     // need to fix the problem wirh H(i,j,k,l,Vijkl) with factorized hamiltonians\n     // right now it doesn't use the correct data structure. Need a new routine for V2_fact_mixed \n     if(nThree_core > 0) {\n       app_error()<<\" Error: Core states have been temporarily disabled with factorized hamiltonians.\" <<std::endl;\n       return false;\n     }\n\n     H1.resize(nOne);\n     hij_core.resize(nOne_core);\n\n     if(nThree > 0)  {\n       if(nTwo > 0) {\n         app_error()<<\"Found both 3-Index and 4-Index terms in FCIDUMP. Only one form is allowed. \" <<std::endl;\n         return false;\n       }\n       app_log()<<\"Found integral file with Cholesky decomposed integrals.\\n\";\n       app_log()<<\"# Chol Vec, # terms:\" <<n3Vecs <<\" \" <<nThree <<std::endl;\n       factorizedHamiltonian = true;\n       int NMO2 = NMO*NMO;\n       if(!spinRestricted) NMO2 *= 2; \n       V2_fact.setDims(NMO2,n3Vecs);\n       V2_fact_c.setDims(NMO2,n3Vecs);\n       V2_fact_m.setDims(NMO2,n3Vecs);\n       // V2_fact must be reserved, since elements are added with \"add\"\n       V2_fact.reserve(nThree);\n       V2_fact_c.reserve(nThree_core);\n       V2_fact_m.reserve(nThree_mixed);\n     } else {\n       if(n3Vecs > 0) {\n         app_error()<<\"Found three index terms in FCIDUMP. (Only allowed with factorized hamiltonian. Check!!!\" <<std::endl; \n         APP_ABORT(\"Found three index terms in FCIDUMP. (Only allowed with factorized hamiltonian. Check!!!\"); \n       } \n       factorizedHamiltonian = false;\n\n       V2.resize(nTwo,true);  // allow reduction of size if necessary\n       Vijkl_core.resize(nTwo_core);\n       Vijkl_mixed.resize(nTwo_mixed);\n     }\n \n     in.clear();\n     in.seekg(start);\n\n     Timer.reset(\"Generic\");\n     Timer.start(\"Generic\");\n\n     if(!readElementsFromFCIDUMP(in,H1,hij_core,V2,Vijkl_core,Vijkl_mixed,V2_fact,V2_fact_c,V2_fact_m,orbMapA,orbMapB)) {\n       app_error()<<\"Error in return from readElementsFromFCIDUMP in readFCIDUMP.\\n\" <<std::endl; \n       return false;\n     }\n\n     if(factorizedHamiltonian) {\n       if(H1.size() != nOne || hij_core.size() != nOne_core ) {\n         app_error()<<\"Error after readElementsFromFCIDUMP in readFCIDUMP, wrong number of elements.\\n\" <<std::endl; \n         return false;\n       }\n     } else {\n       if(H1.size() != nOne || hij_core.size() != nOne_core  || V2.size()!=nTwo ||  Vijkl_core.size()!=nTwo_core ||  Vijkl_mixed.size()!=nTwo_mixed) {\n         app_error()<<\"Error after readElementsFromFCIDUMP in readFCIDUMP, wrong number of elements.\\n\" <<std::endl; \n         return false;\n       }\n     }\n     myComm->barrier(); \n\n     Timer.stop(\"Generic\");\n     if(rnk==0) app_log()<<\" -- Time to read ASCII integral file (2nd time after reorder): \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n//     delete mybuffer; \n     in.close();\n\n     if(minimizeIO) {\n\n       //MPI_Bcast (&(oneE[0]), nq, MPI_DOUBLE, 0, MPI_COMM_WORLD); \n\n       //MPI_Bcast (&(twoEaa[0]), nq, MPI_DOUBLE, 0, MPI_COMM_WORLD); \n\n       //MPI_Bcast (&(twoEbb[0]), nq, MPI_DOUBLE, 0, MPI_COMM_WORLD); \n\n     }\n\n#ifdef AFQMC_DEBUG\n    app_log()<<\" Finished reading FCIDUMP file.\" <<std::endl; \n    app_log()<<\" Sorting integral tables.\" <<std::endl; \n#endif\n\n    Timer.reset(\"Generic\");\n    Timer.start(\"Generic\");\n\n    // sort integral tables\n    // remove repeated, needed in the (beta/alpha) and (alpha/beta) blocks\n    std::sort (H1.begin(), H1.end(),mySort);\n    s2Dit ith = std::unique(H1.begin(),H1.end(),myEqv);\n    H1.resize( std::distance(H1.begin(),ith) );\n\n    std::sort (hij_core.begin(), hij_core.end(),mySort);\n    ith = std::unique(hij_core.begin(),hij_core.end(),myEqv);\n    hij_core.resize( std::distance(hij_core.begin(),ith) );\n\n    if(factorizedHamiltonian) {\n      V2_fact.compress();\n      V2_fact_m.compress();\n      V2_fact_c.compress();\n      myComm->barrier();\n    } else {\n      if(head_of_nodes) {\n        std::sort (V2.begin(), V2.end(),mySort);\n        s4Dit itV = std::unique(V2.begin(),V2.end(),myEqv);\n        // keeping extra space because array might be quite large to reallocate \n        V2.resize_serial( std::distance(V2.begin(),itV));\n      }\n\n      std::sort (Vijkl_core.begin(), Vijkl_core.end(),mySort);\n      std::vector<s4D<ValueType>>::iterator itV = std::unique(Vijkl_core.begin(),Vijkl_core.end(),myEqv);\n      Vijkl_core.resize( std::distance(Vijkl_core.begin(),itV) );\n\n      std::sort (Vijkl_mixed.begin(), Vijkl_mixed.end(),mySort);\n      itV = std::unique(Vijkl_mixed.begin(),Vijkl_mixed.end(),myEqv);\n      Vijkl_mixed.resize( std::distance(Vijkl_mixed.begin(),itV) );\n    }\n\n    Timer.stop(\"Generic\");\n    if(rnk==0) app_log()<<\" -- Time to sort sparse integral tables: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n    // calculate list of virtuals \n    isOcc_alpha.clear();\n    isOcc_beta.clear();\n    for(IndexType i=0; i<2*NMO; i++) isOcc_alpha[i]=false;\n    for(IndexType i=0; i<2*NMO; i++) isOcc_beta[i]=false;\n    for(int i=0; i<occup_alpha.size(); i++) isOcc_alpha[ occup_alpha[i] ]=true;\n    for(int i=0; i<occup_beta.size(); i++) isOcc_beta[ occup_beta[i] ]=true;\n    virtual_alpha.clear();\n    virtual_beta.clear();\n    virtual_alpha.reserve(NMO-NAEA);\n    virtual_beta.reserve(NMO-NAEB);\n    for(IndexType i=0; i<NMO; i++)\n      if(!isOcc_alpha[i]) virtual_alpha.push_back(i);\n    for(IndexType i=NMO; i<2*NMO; i++)\n      if(!isOcc_beta[i]) virtual_beta.push_back(i);\n    \n    // define close_shell\n    if(NCA==NCB && NAEA == NAEB && occup_alpha.size() == occup_beta.size() ) { \n      close_shell = true;\n      for(int i=0; i<occup_alpha.size(); i++) \n        if( occup_alpha[i] != occup_beta[i]-NMO )\n          close_shell = false;\n    } else\n      close_shell = false;\n\n#ifdef AFQMC_DEBUG\n    app_log()<<\" Finished sorting integral tables.\" <<std::endl; \n#endif\n\n    // FZ core rotation\n    if(NCA > 0 || NCB > 0) {\n#ifdef AFQMC_DEBUG\n    app_log()<<\" Performing Frozen-Core manipulations. \\n\"; \n#endif   \n\n    Timer.reset(\"Generic\");\n    Timer.start(\"Generic\");\n\n    FrozenCoreEnergy = ValueType(0.0);\n\n    for(int i=0; i<hij_core.size(); i++) \n      if( std::get<0>( hij_core[i] ) == std::get<1>( hij_core[i] )  ) {\n        FrozenCoreEnergy += std::get<2>( hij_core[i] );\n        if(spinRestricted) FrozenCoreEnergy += std::get<2>( hij_core[i] );\n      }\n    app_log()<<\" One-Body Core Energy: \" <<FrozenCoreEnergy <<std::endl;     \n\n    for(int i=0; i<NCA; i++)\n    {\n      for(int j=i+1; j<NCA; j++)\n        FrozenCoreEnergy += (H(i,j,i,j,Vijkl_core,NMO_FULL) - H(i,j,j,i,Vijkl_core,NMO_FULL) );\n      for(int j=NMO_FULL; j<NMO_FULL+NCB; j++)\n        FrozenCoreEnergy += H(i,j,i,j,Vijkl_core,NMO_FULL);\n    }\n    for(int i=NMO_FULL; i<NMO_FULL+NCB; i++)\n    {\n      for(int j=i+1; j<NMO_FULL+NCB; j++)\n        FrozenCoreEnergy += (H(i,j,i,j,Vijkl_core,NMO_FULL) - H(i,j,j,i,Vijkl_core,NMO_FULL));\n    }    \n    app_log()<<\" Frozen core energy: \" <<FrozenCoreEnergy <<std::endl;\n    NuclearCoulombEnergy += FrozenCoreEnergy;\n\n    // lazy for now\n    std::vector<s2D<ValueType> > h1_new;\n    int cnt=0;\n    for(int i=0; i<NMO; i++) {\n      for(int j=i; j<NMO; j++) {\n        ValueType V = H(i,j); \n        for(int k=0; k<NCA; k++) \n          V += H(k,NCA+i,k,NCA+j,Vijkl_mixed,NMO_FULL) - H(k,NCA+i,NCA+j,k,Vijkl_mixed,NMO_FULL); \n        for(int k=NMO_FULL; k<NMO_FULL+NCB; k++) \n          V += H(k,NCA+i,k,NCA+j,Vijkl_mixed,NMO_FULL);\n        if(std::abs(V) > cutoff1bar ) cnt++;\n      }\n    }\n    if(!spinRestricted) {\n      for(int i=NMO; i<2*NMO; i++) {\n        for(int j=i; j<2*NMO; j++) {\n          ValueType V = H(i,j);\n          for(int k=0; k<NCA; k++) \n            V += H(k,i-NMO+NMO_FULL+NCB,k,j-NMO+NMO_FULL+NCB,Vijkl_mixed,NMO_FULL);\n          for(int k=NMO_FULL; k<NMO_FULL+NCB; k++) \n            V += H(k,i-NMO+NMO_FULL+NCB,k,j-NMO+NMO_FULL+NCB,Vijkl_mixed,NMO_FULL) - H(k,i-NMO+NMO_FULL+NCB,j-NMO+NMO_FULL+NCB,k,Vijkl_mixed,NMO_FULL);\n          if(std::abs(V) > cutoff1bar ) cnt++;\n        }\n      }\n    }\n    h1_new.reserve(cnt);\n    for(int i=0; i<NMO; i++) {\n      for(int j=i; j<NMO; j++) {\n        ValueType V = H(i,j);\n        for(int k=0; k<NCA; k++) \n          V += H(k,NCA+i,k,NCA+j,Vijkl_mixed,NMO_FULL) - H(k,NCA+i,NCA+j,k,Vijkl_mixed,NMO_FULL);\n        for(int k=NMO_FULL; k<NMO_FULL+NCB; k++)\n          V += H(k,NCA+i,k,NCA+j,Vijkl_mixed,NMO_FULL);\n        if(std::abs(V) > cutoff1bar ) h1_new.push_back(std::forward_as_tuple(i,j,V));\n      }\n    }\n    if(!spinRestricted) {\n      for(int i=NMO; i<2*NMO; i++) {\n        for(int j=i; j<2*NMO; j++) {\n          ValueType V = H(i,j);\n          for(int k=0; k<NCA; k++) \n            V += H(k,i-NMO+NMO_FULL+NCB,k,j-NMO+NMO_FULL+NCB,Vijkl_mixed,NMO_FULL);\n          for(int k=NMO_FULL; k<NMO_FULL+NCB; k++)\n            V += H(k,i-NMO+NMO_FULL+NCB,k,j-NMO+NMO_FULL+NCB,Vijkl_mixed,NMO_FULL) - H(k,i-NMO+NMO_FULL+NCB,j-NMO+NMO_FULL+NCB,k,Vijkl_mixed,NMO_FULL);\n        if(std::abs(V) > cutoff1bar ) h1_new.push_back(std::forward_as_tuple(i,j,V));\n        }\n      }\n    }  \n\n    H1 = h1_new;\n    std::sort (H1.begin(), H1.end(),mySort);\n\n    Timer.stop(\"Generic\");\n    if(rnk==0) app_log()<<\" -- Time to perform FC manipulations: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n#ifdef AFQMC_DEBUG\n    app_log()<<\" Finished performing Frozen-Core manipulations. \\n\"; \n#endif    \n    }\n\n    app_log()<<\" Calculating eigenvalues: \" <<std::endl; \n\n    ValueType ekin=0.0,epot_bb=0.0,epot_ab=0.0,epot_aa=0.0,epot_coul=0.0,epot=NuclearCoulombEnergy,Emp2=0.0;\n    for(std::vector<IndexType>::iterator ita = occup_alpha.begin(); ita!=occup_alpha.end(); ita++)\n    {\n      ekin += H(*ita,*ita);\n      for(std::vector<IndexType>::iterator itb = ita+1; itb<occup_alpha.end(); itb++) \n        epot += H_2bar(*ita,*itb,*ita,*itb);\n      for(std::vector<IndexType>::iterator itb = occup_beta.begin(); itb!=occup_beta.end(); itb++) \n        epot += H(*ita,*itb,*ita,*itb);\n    }\n    for(std::vector<IndexType>::iterator ita = occup_beta.begin(); ita!=occup_beta.end(); ita++)\n    {\n      ekin += H(*ita,*ita);\n      for(std::vector<IndexType>::iterator itb = ita+1; itb!=occup_beta.end(); itb++) \n        epot += H_2bar(*ita,*itb,*ita,*itb);\n    }\n    for(std::vector<IndexType>::iterator ita = occup_alpha.begin(); ita!=occup_alpha.end(); ita++)\n    {\n      for(std::vector<IndexType>::iterator itb = ita+1; itb<occup_alpha.end(); itb++)\n        epot_coul += H(*ita,*itb,*ita,*itb);\n      for(std::vector<IndexType>::iterator itb = occup_beta.begin(); itb!=occup_beta.end(); itb++)\n        epot_coul += H(*ita,*itb,*ita,*itb);\n    }\n    for(std::vector<IndexType>::iterator ita = occup_beta.begin(); ita!=occup_beta.end(); ita++)\n    {\n      for(std::vector<IndexType>::iterator itb = ita+1; itb!=occup_beta.end(); itb++)\n        epot_coul += H(*ita,*itb,*ita,*itb);\n    }\n    for(std::vector<IndexType>::iterator ita = occup_alpha.begin(); ita!=occup_alpha.end(); ita++)\n    {\n      for(std::vector<IndexType>::iterator itb = ita+1; itb<occup_alpha.end(); itb++)\n        epot_aa += H_2bar(*ita,*itb,*ita,*itb);\n    }\n    for(std::vector<IndexType>::iterator ita = occup_beta.begin(); ita!=occup_beta.end(); ita++)\n    {\n      for(std::vector<IndexType>::iterator itb = ita+1; itb!=occup_beta.end(); itb++)\n        epot_bb += H_2bar(*ita,*itb,*ita,*itb);\n    }\n    for(std::vector<IndexType>::iterator ita = occup_alpha.begin(); ita!=occup_alpha.end(); ita++)\n    {\n      for(std::vector<IndexType>::iterator itb = occup_beta.begin(); itb!=occup_beta.end(); itb++)\n        epot_ab += H(*ita,*itb,*ita,*itb);\n    }\n\n    // for spinRestricted, only alpha sector is populated\n    app_log()<<\"Eigenvalues: \" <<std::endl;   \n    eig.resize(2*NMO);\n    for(IndexType i=0; i<NMO; i++) {\n      eig[i] = H(i,i);\n      for(std::vector<IndexType>::iterator it = occup_alpha.begin(); it<occup_alpha.end(); it++) \n        eig[i] += H_2bar(i,*it,i,*it);\n      for(std::vector<IndexType>::iterator it = occup_beta.begin(); it<occup_beta.end(); it++) \n        eig[i] += H(i,*it,i,*it);\n      app_log()<<i <<\"   \" <<eig[i] <<std::endl;\n    }    \n    if(!spinRestricted) {\n      for(IndexType i=NMO; i<2*NMO; i++) {\n        eig[i] = H(i,i);\n        for(std::vector<IndexType>::iterator it = occup_alpha.begin(); it<occup_alpha.end(); it++) \n          eig[i] += H(i,*it,i,*it);\n        for(std::vector<IndexType>::iterator it = occup_beta.begin(); it<occup_beta.end(); it++) \n          eig[i] += H_2bar(i,*it,i,*it);\n        app_log()<<i <<\"   \" <<eig[i] <<std::endl;\n      }    \n    }\n\n    bool printFockMatrix=false; \n    if(printFockMatrix) {\n      app_log()<<\" Off-diagonal elements of the Fock matrix larger than \" <<5*std::max(cutoff1bar,cutoff1bar) <<std::endl;\n      for(IndexType i=0; i<NMO; i++) {\n       for(IndexType j=i+1; j<NMO; j++) {\n        ValueType fij = H(i,j);\n        for(std::vector<IndexType>::iterator it = occup_alpha.begin(); it<occup_alpha.end(); it++)\n          fij += H_2bar(i,*it,j,*it);\n        for(std::vector<IndexType>::iterator it = occup_beta.begin(); it<occup_beta.end(); it++) \n          fij += H(i,*it,j,*it);\n        if( std::abs(fij) > 5*std::max(cutoff1bar,cutoff1bar) )\n          app_log()<<i <<\"  \" <<j <<\"     \" <<fij <<std::endl;\n       }\n      }\n      if(!spinRestricted) {\n      }\n      app_log()<<\" Done printing Fock matrix.\" <<std::endl;\n    } \n\n    app_log()<<std::setprecision(12) <<std::endl <<\" Ekin:     \" <<ekin <<std::endl;\n    app_log()<<\" Epot:     \" <<epot <<std::endl;\n    app_log()<<\" Epot_Coulomb:     \" <<epot_coul <<std::endl;\n    app_log()<<\" Epot_aa:     \" <<epot_aa <<std::endl;\n    app_log()<<\" Epot_bb:     \" <<epot_bb <<std::endl;\n    app_log()<<\" Epot_ab:     \" <<epot_ab <<std::endl;\n    app_log()<<\" Ehf:     \" <<epot+ekin <<std::endl;\n    if(spinRestricted && NCA == NCB && NAEA==NAEB && close_shell) {\n      // right now only for close-shell RHF \n      // using \"trick\" to get 1 bar terms\n      std::vector<IndexType>::iterator iti,itj,ita,itb; \n/*\n      for(iti=occup_alpha.begin(); iti<occup_alpha.end(); iti++)\n      for(itj=occup_alpha.begin(); itj<occup_alpha.end(); itj++)\n      for(ita=virtual_alpha.begin(); ita<virtual_alpha.end(); ita++)\n      for(itb=virtual_alpha.begin(); itb<virtual_alpha.end(); itb++)\n        Emp2 += H(*iti,*itj,*ita,*itb)*(2.0*H(*ita,*itb,*iti,*itj) - H(*ita,*itb,*itj,*iti))/(eig[*iti]+eig[*itj]-eig[*ita]-eig[*itb]); \n*/\n      app_log()<<\" Emp2:     \" <<Emp2 <<std::endl;\n      app_log()<<\" Ehf+Emp2: \" <<epot+ekin+Emp2 <<std::endl <<std::endl;\n    } \n\n    app_log()<<\" Memory used by 2-el integral table: \" <<sizeof(s4D<ValueType>)*V2.size()/1024/1024 <<\" MB. \" <<std::endl;\n\n    hdf_write();\n    if(rnk == 0) {\n      ascii_write();\n    }\n\n    MPI_Barrier(TG.getNodeCommLocal()); \n    // generate IJ matrix to speedup table seaches\n    if(V2.size()>0)\n      generateIJ();\n\n    return true;\n  }\n\n  void SparseGeneralHamiltonian::get_selCI_excitations(OrbitalType I, OrbitalType J, int spinSector, RealType cutoff, OrbitalType* occs, std::vector<OrbitalType>& KLs ) {\n\n    if(!has_hamiltonian_for_selCI) \n      APP_ABORT(\"Error: SparseGeneralHamiltonian::get_selCI_excitations() 2eInts not setup. \\n\\n\\n\");\n\n    KLs.clear();\n    KLs.reserve(2*nmax_KL_selCI);\n    SMDenseVector<s2D<ValueType> >::iterator itV, itend;\n    OrbitalType NK=0,NL=0;\n    if( spinSector == 0 ) {  // aa\n      IndexType pos = mapUT_woD(I,J,NMO); \n      IndexType n0=IJ_aa[pos];\n      IndexType n1=IJ_aa[pos+1];\n      if(n0==n1) return; \n      itV = V2_selCI_aa.begin() + n0;   \n      itend = V2_selCI_aa.begin() + n1;   \n    } else if(spinSector == 1) { // ab \n      IndexType pos;\n      if(spinRestricted) {\n        pos = mapUT(I,J-NMO,NMO);\n        if(I <= J-NMO) NL=NMO; \n        else NK=NMO; \n      } else \n        pos = (I*NMO)*(J-NMO); \n      IndexType n0=IJ_ab[pos];\n      IndexType n1=IJ_ab[pos+1];\n      if(n0==n1) return;\n      itV = V2_selCI_ab.begin() + n0;   \n      itend = V2_selCI_ab.begin() + n1;   \n    } else if(spinSector == 2) { // ba\n      APP_ABORT(\" Error: SparseGeneralHamiltonian::get_selCI_excitations().  Should not be here. \\n\\n\\n\");\n    } else if(spinSector == 3) { // bb\n      IndexType pos = mapUT_woD(I-NMO,J-NMO,NMO);\n      if(spinRestricted) {\n        IndexType n0=IJ_aa[pos];\n        IndexType n1=IJ_aa[pos+1];\n        if(n0==n1) return; \n        itV = V2_selCI_aa.begin() + n0;  \n        itend = V2_selCI_aa.begin() + n1;\n        NK=NL=NMO;\n      } else {\n        IndexType n0=IJ_bb[pos];\n        IndexType n1=IJ_bb[pos+1];\n        if(n0==n1) return; \n        itV = V2_selCI_bb.begin() + n0;  \n        itend = V2_selCI_bb.begin() + n1;\n      }\n    }\n\n    register OrbitalType K,L;\n    while(itV < itend && std::abs(std::get<2>(*itV)) > cutoff) {\n      std::tie(K,L,std::ignore) = *(itV++);\n      K+=NK;  // needed for spinRestricted-ab\n      L+=NL;  // needed for spinRestricted-ab\n      if( !std::binary_search(occs,occs+NAEA+NAEB,K) && !std::binary_search(occs,occs+NAEA+NAEB,L) ) {\n        KLs.push_back(K);\n        KLs.push_back(L);\n      }\n    }\n  }\n\n  void SparseGeneralHamiltonian::generate_selCI_Ham(double cutoff) {\n\n//  IndexMatrix IJ_aa, IJ_bb, IJ_ab;\n//  SMDenseVector<s2D<ValueType> > V2_selCI_aa;\n//  SMDenseVector<s2D<ValueType> > V2_selCI_ab;\n//  SMDenseVector<s2D<ValueType> > V2_selCI_bb;\n\n    nmax_KL_selCI=0;\n    has_hamiltonian_for_selCI = true;\n    IJ_aa.resize(mapUT_woD(NMO-2,NMO-1,NMO)+2);\n    if(!spinRestricted) IJ_bb.resize( mapUT_woD(NMO-2,NMO-1,NMO)+2 );\n    if(spinRestricted)\n      IJ_ab.resize( mapUT(NMO-1,NMO-1,NMO)+2 );\n    else\n      IJ_ab.resize( NMO*NMO+1 );\n    V2_selCI_aa.setup(head_of_nodes,std::string(\"V2_selCI_aa_\"),TG.getNodeCommLocal());\n    V2_selCI_ab.setup(head_of_nodes,std::string(\"V2_selCI_ab_\"),TG.getNodeCommLocal());\n    if(!spinRestricted)\n      V2_selCI_bb.setup(head_of_nodes,std::string(\"V2_selCI_bb_\"),TG.getNodeCommLocal());\n\n    if(factorizedHamiltonian) {\n      app_error()<<\" Error in SparseGeneralHamiltonian::generate_selCI_Ham: not implemented \\n\"; \n      APP_ABORT(\" Error in SparseGeneralHamiltonian::generate_selCI_Ham: not implemented \\n\"); \n    }\n\n#ifdef AFQMC_DEBUG\n    app_log()<<\" Generating selCI integrals. \" <<std::endl; \n#endif\n\n    int cnt=0;\n    Timer.reset(\"Generic\");\n    Timer.start(\"Generic\");\n\n    IndexType cntaa=0; \n    IndexType cntab=0; \n    IndexType cntbb=0; \n\n    // using dumbest algorithm right now, improve later\n    if(head_of_nodes) {\n\n// notes:\n// 1. For aa/bb: only i<j and k<l are stored\n// 2. For spinRestricted-ab only i<j is stored\n      int tmp=0;\n      for(OrbitalType i=0; i<NMO; i++)  {  \n      for(OrbitalType j=i+1; j<NMO; j++)  {  \n        if(mapUT_woD(i,j,NMO) != tmp++) \n          APP_ABORT(\"Error: Problems with mapUT_woD. \\n\\n\\n\"); \n      for(OrbitalType k=0; k<NMO; k++)  {  \n      for(OrbitalType l=k+1; l<NMO; l++)  {  \n        ValueType v = H(i,j,k,l)-H(i,j,l,k);\n        if(std::abs(v) > cutoff) \n          cntaa++;  \n      }\n      }\n      }\n      }\n      if(!spinRestricted) {\n       for(OrbitalType i=0; i<NMO; i++)  {\n       for(OrbitalType j=NMO; j<2*NMO; j++)  {\n       for(OrbitalType k=0; k<NMO; k++)  {\n       for(OrbitalType l=NMO; l<2*NMO; l++)  {  \n         ValueType v = H(i,j,k,l);\n         if(std::abs(v) > cutoff)\n           cntab++;\n       }\n       }\n       }\n       }\n       for(OrbitalType i=NMO; i<2*NMO; i++)  {  \n       for(OrbitalType j=i+1; j<2*NMO; j++)  {  \n       for(OrbitalType k=NMO; k<2*NMO; k++)  {  \n       for(OrbitalType l=k+1; l<2*NMO; l++)  {  \n        ValueType v = H(i,j,k,l)-H(i,j,l,k);\n        if(std::abs(v) > cutoff)\n          cntbb++;\n       }\n       }\n       }\n       }\n      } else {\n       tmp=0;\n       for(OrbitalType i=0; i<NMO; i++)  {\n       for(OrbitalType j=i; j<NMO; j++)  {\n        if(mapUT(i,j,NMO) != tmp++) \n          APP_ABORT(\"Error: Problems with mapUT. \\n\\n\\n\"); \n       for(OrbitalType k=0; k<NMO; k++)  {\n       for(OrbitalType l=0; l<NMO; l++)  {\n         ValueType v = H(i,j,k,l);\n         if(std::abs(v) > cutoff)\n           cntab++;\n       }\n       }\n       }\n       }\n      }\n\n    }\n\n\n    V2_selCI_aa.resize(cntaa);\n    V2_selCI_ab.resize(cntab);\n    if(!spinRestricted)\n      V2_selCI_aa.resize(cntbb);\n\n    app_log()<<\" Memory used by selectedCI integrals: \" \n     <<((cntaa+cntbb+cntab)*sizeof(s2D<ValueType>))/1024.0/1024.0 <<\" MB. \\n\";\n\n    if(head_of_nodes) {\n\n      cnt = 0;\n      IndexVector::iterator itIJ = IJ_aa.begin();\n      SMDenseVector<s2D<ValueType> >::iterator itV = V2_selCI_aa.begin();\n      for(OrbitalType i=0; i<NMO; i++)  {\n      for(OrbitalType j=i+1; j<NMO; j++)  {\n        *(itIJ++) = cnt;\n        for(OrbitalType k=0; k<NMO; k++)  {\n        for(OrbitalType l=k+1; l<NMO; l++)  {\n          ValueType v = H(i,j,k,l)-H(i,j,l,k);\n          if(std::abs(v) > cutoff) {\n            *(itV++) = std::forward_as_tuple(k,l,v); \n            cnt++;\n          }\n        }\n        }\n      }\n      }\n      *(itIJ) = cnt;\n\n      // sort integrals\n      IndexVector::iterator itend = IJ_aa.end()-1;\n      for(itIJ = IJ_aa.begin(), itV = V2_selCI_aa.begin(); itIJ < itend; itIJ++) { \n        int nt = *(itIJ+1) - *itIJ;\n        if(nt > nmax_KL_selCI) nmax_KL_selCI = nt;\n        std::sort(itV, itV+nt,  \n               [] (const s2D<ValueType>& a, const s2D<ValueType>& b)\n               {return std::abs(std::get<2>(a))>std::abs(std::get<2>(b));} );\n        itV+=nt;\n      }  \n\n      if(!spinRestricted) {\n\n        cnt=0;\n        itIJ = IJ_ab.begin();\n        itV = V2_selCI_ab.begin(); \n        for(OrbitalType i=0; i<NMO; i++)  {\n        for(OrbitalType j=NMO; j<2*NMO; j++)  {\n          *(itIJ++) = cnt;\n          for(OrbitalType k=0; k<NMO; k++)  {\n          for(OrbitalType l=NMO; l<2*NMO; l++)  {\n            ValueType v = H(i,j,k,l);\n            if(std::abs(v) > cutoff) {\n              *(itV++) = std::forward_as_tuple(k,l,v);\n              cnt++;\n            }\n          }\n          }\n        }\n        }\n        *(itIJ) = cnt;\n\n        cnt=0;\n        itIJ = IJ_bb.begin();\n        itV = V2_selCI_bb.begin(); \n        for(OrbitalType i=NMO; i<2*NMO; i++)  {\n        for(OrbitalType j=i+1; j<2*NMO; j++)  {\n          *(itIJ++) = cnt;\n          for(OrbitalType k=NMO; k<2*NMO; k++)  {\n          for(OrbitalType l=k+1; l<2*NMO; l++)  {\n            ValueType v = H(i,j,k,l)-H(i,j,l,k);\n            if(std::abs(v) > cutoff) {\n              *(itV++) = std::forward_as_tuple(k,l,v);\n              cnt++;\n            }\n          }\n          }\n        }\n        }\n        *(itIJ) = cnt;\n\n        // sort integrals\n        itend = IJ_bb.end()-1;\n        for(itIJ = IJ_bb.begin(), itV = V2_selCI_bb.begin(); itIJ < itend; itIJ++) { \n          int nt = *(itIJ+1) - *itIJ;\n          if(nt > nmax_KL_selCI) nmax_KL_selCI = nt;\n          std::sort(itV, itV+nt,  \n                 [] (const s2D<ValueType>& a, const s2D<ValueType>& b)\n                 {return std::abs(std::get<2>(a))>std::abs(std::get<2>(b));} );\n          itV+=nt;\n        }  \n\n        itend = IJ_ab.end()-1;\n        for(itIJ = IJ_ab.begin(), itV = V2_selCI_ab.begin(); itIJ < itend; itIJ++) {\n          int nt = *(itIJ+1) - *itIJ;\n          if(nt > nmax_KL_selCI) nmax_KL_selCI = nt;\n          std::sort(itV, itV+nt,  \n                 [] (const s2D<ValueType>& a, const s2D<ValueType>& b)\n                 {return std::abs(std::get<2>(a))>std::abs(std::get<2>(b));} );\n          itV+=nt;\n        }  \n\n      } else {\n\n        // to be able to use i<j, I need to map I and J to [0:NMO-1]\n        // this means that you need to be careful to map back to original sector\n        \n        cnt=0;\n        itIJ = IJ_ab.begin();\n        itV = V2_selCI_ab.begin(); \n        for(OrbitalType i=0; i<NMO; i++)  {\n        for(OrbitalType j=i; j<NMO; j++)  {\n          *(itIJ++) = cnt;\n          for(OrbitalType k=0; k<NMO; k++)  {\n          for(OrbitalType l=0; l<NMO; l++)  {\n            ValueType v = H(i,j,k,l);\n            if(std::abs(v) > cutoff) {\n              *(itV++) = std::forward_as_tuple(k,l,v);\n              cnt++;\n            }\n          }\n          }\n        }\n        }\n        *(itIJ) = cnt;\n\n        itend = IJ_ab.end()-1;\n        for(itIJ = IJ_ab.begin(), itV = V2_selCI_ab.begin(); itIJ < itend; itIJ++) {\n          int nt = *(itIJ+1) - *itIJ;\n          if(nt > nmax_KL_selCI) nmax_KL_selCI = nt;\n          std::sort(itV, itV+nt,  \n                 [] (const s2D<ValueType>& a, const s2D<ValueType>& b)\n                 {return std::abs(std::get<2>(a))>std::abs(std::get<2>(b));} );\n          itV+=nt;\n        }  \n\n      }\n    }\n\n    myComm->bcast<int>(nmax_KL_selCI);\n    myComm->bcast<IndexType>(IJ_aa.data(),IJ_aa.size(),MPI_COMM_HEAD_OF_NODES); \n    myComm->bcast<IndexType>(IJ_ab.data(),IJ_ab.size(),MPI_COMM_HEAD_OF_NODES); \n    if(!spinRestricted)\n      myComm->bcast<IndexType>(IJ_bb.data(),IJ_bb.size(),MPI_COMM_HEAD_OF_NODES); \n    myComm->barrier();\n\n    Timer.stop(\"Generic\");\n    app_log()<<\" -- Time to generate sparse 2-bar integral tables for selectedCI: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n  }\n\n  // This routine operates on the FULL MO set, including CORE, ACTIVE and IGNORED states. \n  bool SparseGeneralHamiltonian::countElementsFromFCIDUMP(std::ifstream& in, int& n1, int& n1_c, int& n2, int& n2_c, int& n2_m, int& n3, int& n3_c, int& n3_m, std::map<IndexType,IndexType>& orbMapA, std::map<IndexType,IndexType>& orbMapB, int& n3_vec )\n  {\n\n     IndexType a,b,c,d;\n     IndexType ap,bp,cp,dp;\n     ValueType val;\n     int uhf_block=0;\n     n3_vec=n1=n2=n1_c=n2_c=n2_m=n3=n3_c=n3_m=0;\n\n     while(!in.eof()) {\n       in>>val >>ap >>bp >>cp >>dp;\n       if(in.fail()) break;\n\n       // to reduce problems from numerical roundoff \n       if(std::abs(toComplex(val).imag()) < 1e-8) setImag(val,0.0);\n\n       // FCIDUMP format encodes UHF with uhf_block. All indexes are smaller than NMAX/NMO \n       // THIS SHOULD BE DONE AFTER MAPPING!!!\n       // BUT YOU CAN'T CREATE THE MAPPING WITHOUT READING ALL STATES, CORRECT???\n       // HOW TO SOLVE THIS??? \n       // READ ALL THE FIRST TIME????\n      \n       // trying to fix problem in 3-index terms\n       auto it = orbMapA.find(cp);\n       if (it == orbMapA.end())\n        orbMapA[cp] = cp; \n       it = orbMapB.find(cp);\n       if (it == orbMapB.end())\n        orbMapB[cp] = cp; \n\n       if(spinRestricted) {\n        a=orbMapA[ap];\n        b=orbMapA[bp];\n        c=orbMapA[cp];\n        d=orbMapA[dp];\n       } else {\n         if(uhf_block == 0) {\n           a=orbMapA[ap];\n           b=orbMapA[bp];\n           c=orbMapA[cp];\n           d=orbMapA[dp];\n         } else if(uhf_block==1) {\n           a=orbMapB[ap];\n           b=orbMapB[bp];\n           c=orbMapB[cp];\n           d=orbMapB[dp];\n         } else if(uhf_block==2) {\n           a=orbMapA[ap];\n           b=orbMapA[bp];\n           c=orbMapB[cp];\n           d=orbMapB[dp];\n         } else if(uhf_block==3) {\n           a=orbMapA[ap];\n           b=orbMapA[bp];\n           if(cp != 0 && dp != 0) {\n              app_error()<<\"Error: In UHF FCIDUMP, c d should be zero in uhf_block=3.\\n\";\n              app_error()<<\"val, a, b, c, d: \" <<val <<\" \" <<ap <<\" \" <<bp <<\" \" <<cp <<\" \" <<dp <<\"\\n\";\n              return false;\n           }\n           c=d=0;\n         } else if(uhf_block==4) {\n           a=orbMapB[ap];\n           b=orbMapB[bp];\n           if(cp != 0 && dp != 0) {\n              app_error()<<\"Error: In UHF FCIDUMP, c d should be zero in uhf_block=4.\\n\";\n              app_error()<<\"val, a, b, c, d: \" <<val <<\" \" <<ap <<\" \" <<bp <<\" \" <<cp <<\" \" <<dp <<\"\\n\";\n              return false;\n           }\n           c=d=0;\n         }\n       }\n\n       if(a>0 && b>0 && c>0 && d > 0) {  // 2-electron ME (ab|cd) = <ac|bd>\n         if( std::abs(val) > cutoff1bar ) {\n           if( !goodSpinSector(a-1,c-1,b-1,d-1,NMO_FULL) ) {\n             app_error()<<\" Problems in SparseGeneralHamiltonian::countElementsFromFCIDUMP. Inconsistent two body term in integral file: \" <<a <<\" \" <<b <<\" \" <<c <<\" \" <<d <<\" \" <<ap <<\" \" <<bp <<\" \" <<cp <<\" \" <<dp <<\" \" <<val <<std::endl;\n             return false;\n           }\n           int tmp1,tmp2,tmp3,tmp4;\n           switch(uhf_block) {\n             case 0: \n             {  // AAAA\n               tmp1 = tmp2= NCA;\n               break;\n             }\n             case 1: \n             { // BBBB\n               tmp1 = tmp2 = NMO_FULL+NCB;\n               tmp3=0;\n               break;\n             }\n             case 2: \n             { // AABB\n               tmp1 = NCA;\n               tmp2 = NMO_FULL+NCB;\n               break;\n             }\n           };\n           if( a<=tmp1 && b<=tmp1 && c<=tmp2 && d<=tmp2 ) n2_c++;\n           else if( a>tmp1 && b>tmp1 && c>tmp2 && d>tmp2 ) n2++; \n           else n2_m++;\n         }\n       } else if(a>0 && b>0 && c>0) { // factorized 2-electron ME (i,k|n), where (i,k|j,l) = sum_n (i,k|n)*(l,j|n)*  \n         if( std::abs(val) > cutoff1bar ) {\n           if( !goodSpinSector(a-1,a-1,b-1,b-1,NMO_FULL) ) {\n             app_error()<<\" Problems in SparseGeneralHamiltonian::countElementsFromFCIDUMP. Inconsistent factorized two body term in integral file: \" <<a <<\" \" <<b <<\" \" <<c <<\" \" <<d <<\" \" <<ap <<\" \" <<bp <<\" \" <<cp <<\" \" <<dp <<\" \" <<val <<std::endl;\n             return false;\n           }\n           int tmp1,tmp2,tmp3,tmp4;\n           switch(uhf_block) {\n             case 0:\n             {  // AAAA\n               tmp1 = tmp2= NCA;\n               break;\n             }\n             case 1:\n             { // BBBB\n               tmp1 = tmp2 = NMO_FULL+NCB;\n               tmp3=0;\n               break;\n             }\n           };\n           if( a<=tmp1 && b<=tmp1 ) n3_c++;\n           else if( a>tmp1 && b>tmp1 ) n3++;\n           else n3_m++;\n           if(cp > n3_vec) n3_vec = cp;\n         }\n       } else if(a>0 && b>0) { // 1-electron ME (a|b) = <a|b>\n         if( std::abs(val) > cutoff1bar ) {\n\n           if(spinRestricted) {\n             if( a <= NCA && b <= NCA ) n1_c++;\n             else if( a>NCA && b>NCA  ) n1++; \n           } else {\n             if(uhf_block == 3) {\n               if( a <= NCA && b <= NCA ) n1_c++;\n               else if( a>NCA && b>NCA  ) n1++; \n             } else {\n               if( a <= NMO_FULL+NCB && b <= NMO_FULL+NCB ) n1_c++;\n               else if( a>NMO_FULL+NCB && b>NMO_FULL+NCB  ) n1++; \n             }\n           }\n \n         }\n       } else if(a==0 && b==0 && c==0 && d==0) {\n         if( std::abs(val)==0 && !spinRestricted ) {\n           uhf_block++;\n         }\n       } else if(a!=0 && b==0 && c==0 && d==0) {\n       } else {\n         app_error()<<\"Error with ASCII integral file, bad indexing. \" <<std::endl;\n         return false;\n       }\n    }\n    return true;\n  }\n\n // This routine assumes that states are ordered (after mapping) in the following way:\n // { core, active+virtual, ignored}, so make sure mappings obey this.   \n // An easy way to implement this is to have a list of all core states and \n // initialize the mapping (from 1:NC) with the index of the core states.\n // Then complete the mapping with every other orbital index not in the core list.\n // This way you always end up with a mapping with the correct format. \n  bool SparseGeneralHamiltonian::readElementsFromFCIDUMP(std::ifstream& in, \n         std::vector<s2D<ValueType> >& V1,\n         std::vector<s2D<ValueType> >& V1_c,\n         SMDenseVector<s4D<ValueType> >& V2,\n         std::vector<s4D<ValueType> >& V2_c,\n         std::vector<s4D<ValueType> >& V2_m,\n         ValueSMSpMat&  V3,\n         ValueSMSpMat&  V3_c,\n         ValueSMSpMat&  V3_m,\n         std::map<IndexType,IndexType>& orbMapA, std::map<IndexType,IndexType>& orbMapB) {   \n\n     IndexType a,b,c,d, cntS=0, cntD=0,q1;\n     IndexType ap,bp,cp,dp,ab,cd;\n\n     std::vector<s2D<ValueType> >::iterator V1_it = V1.begin();\n     SMDenseVector<s4D<ValueType> >::iterator V2_it;\n     if(V2.isAllocated()) V2_it = V2.begin();\n\n     std::vector<s2D<ValueType> >::iterator V1_itc = V1_c.begin();\n     std::vector<s4D<ValueType> >::iterator V2_itc = V2_c.begin();\n     std::vector<s4D<ValueType> >::iterator V2_itm = V2_m.begin();\n\n     ValueType val;\n     int uhf_block=0;\n     while(!in.eof()) {\n       in>>val >>ap >>bp >>cp >>dp;\n       if(in.fail()) break;\n\n       // to reduce problems from numerical roundoff \n       if(std::abs(toComplex(val).imag()) < 1e-8) setImag(val,0.0);\n\n       if(spinRestricted) { \n        a=orbMapA[ap];\n        b=orbMapA[bp];\n        c=orbMapA[cp];\n        d=orbMapA[dp];\n       } else {\n         if(uhf_block == 0) {\n           a=orbMapA[ap];\n           b=orbMapA[bp];\n           c=orbMapA[cp];\n           d=orbMapA[dp];\n         } else if(uhf_block==1) {\n           a=orbMapB[ap];\n           b=orbMapB[bp];\n           c=orbMapB[cp];\n           d=orbMapB[dp];\n         } else if(uhf_block==2) {\n           a=orbMapA[ap];\n           b=orbMapA[bp];\n           c=orbMapB[cp];\n           d=orbMapB[dp];\n         } else if(uhf_block==3) {\n           a=orbMapA[ap];\n           b=orbMapA[bp];\n           if(cp != 0 && dp != 0) {\n              app_error()<<\"Error: In UHF FCIDUMP, c d should be zero in uhf_block=3.\\n\"; \n              app_error()<<\"val, a, b, c, d: \" <<val <<\" \" <<ap <<\" \" <<bp <<\" \" <<cp <<\" \" <<dp <<\"\\n\"; \n              return false;\n           }\n           c=d=0;\n         } else if(uhf_block==4) {\n           a=orbMapB[ap];\n           b=orbMapB[bp];\n           if(cp != 0 && dp != 0) {\n              app_error()<<\"Error: In UHF FCIDUMP, c d should be zero in uhf_block=4.\\n\"; \n              app_error()<<\"val, a, b, c, d: \" <<val <<\" \" <<ap <<\" \" <<bp <<\" \" <<cp <<\" \" <<dp <<\"\\n\"; \n              return false;\n           }\n           c=d=0;\n         }\n       }\n\n       if(a>0 && b>0 && c > 0 && d>0) {  // 2-electron ME (ab|cd) = <ac|bd>\n#if true\n         if( std::abs(val) > cutoff1bar ) {\n\n           int tmp1,tmp2,tmp4=0,tmp3=0;\n           switch(uhf_block) {\n             case 0:\n             {  // AAAA\n               tmp1 = tmp2 = NCA;\n               tmp3 = tmp4 = NCA;\n               break;\n             }\n             case 1:\n             { // BBBB\n               tmp1 = tmp2 = NMO_FULL+NCB;\n               tmp3 = tmp4 = NCA+NCB; \n               break;\n             }\n             case 2:\n             { // AABB\n               tmp1 = NCA;\n               tmp3 = NCA;\n               tmp2 = NMO_FULL+NCB;\n               tmp4 = NCB+NCA;\n               break;\n             }\n             default:\n             {\n               app_error()<<\"Problems reading FCIDUMP: \" \n               <<ap <<\" \" \n               <<bp <<\" \" \n               <<cp <<\" \" \n               <<dp <<\" \" \n               <<val <<std::endl;\n               return false;\n             }\n           };\n           // later on\n           // if( isCore[a] && isCore[b] && isCore[c] && isCore[d] ) \n           if( a<=tmp1 && b<=tmp1 && c<=tmp2 && d<=tmp2 ) \n             *(V2_itc++) = find_smaller_equivalent_OneBar_for_integral_list( std::make_tuple(a-1,c-1,b-1,d-1,val) ); \n           else if( a>tmp1 && b>tmp1 && c>tmp2 && d>tmp2 ) { \n             if(head_of_nodes) *(V2_it++) = find_smaller_equivalent_OneBar_for_integral_list( std::make_tuple(a-tmp3-1,c-tmp4-1,b-tmp3-1,d-tmp4-1,val) ); \n           } else \n             *(V2_itm++) = find_smaller_equivalent_OneBar_for_integral_list( std::make_tuple(a-1,c-1,b-1,d-1,val) ); \n         }\n#else\n// reserved for non c++11 compliant compiler\n#endif\n       } else if(a > 0 && b > 0 && c>0) { // factorized 2-electron integral \n         if( std::abs(val) > cutoff1bar ) {\n\n           int tmp1,tmp2,tmp4=0,tmp3=0;\n           switch(uhf_block) {\n             case 0:\n             {  // AAAA\n               tmp1 = tmp2 = NCA;\n               tmp3 = tmp4 = NCA;\n               break;\n             }\n             case 1:\n             { // BBBB\n               tmp1 = tmp2 = NMO_FULL+NCB;\n               tmp3 = tmp4 = NCA+NCB;\n               break;\n             }\n             default:\n             {\n               app_error()<<\"Problems reading FCIDUMP: \"\n               <<ap <<\" \"\n               <<bp <<\" \"\n               <<cp <<\" \"\n               <<dp <<\" \"\n               <<val <<std::endl;\n               return false;\n             }\n           };\n\n           if(head_of_nodes) { \n            if( a<=tmp1 && b<=tmp1 )\n              V3_c.add((a-1)*NMO+Index2Col(b-1),cp-1,val);\n            else if( a>tmp1 && b>tmp1 )\n              V3.add((a-tmp3-1)*NMO+Index2Col(b-tmp3-1),cp-1,val);\n            else\n              V3_m.add((a-1)*NMO+Index2Col(b-1),cp-1,val);\n           }\n\n         }\n       } else if(a > 0 && b > 0) { // 1-electron ME (a|b) = <a|b>\n#if true\n         if( std::abs(val) > cutoff1bar ) { \n\n           if(a > b) {q1=b;b=a;a=q1;val = myconj(val);}\n\n           if(spinRestricted) {\n             if( a <= NCA && b <= NCA ) {\n               std::get<0>( *V1_itc ) = a-1;\n               std::get<1>( *V1_itc ) = b-1;\n               std::get<2>( *(V1_itc++) ) = val;\n             } else if( a>NCA && b>NCA  ) {\n               std::get<0>( *V1_it ) = a-NCA-1;\n               std::get<1>( *V1_it ) = b-NCA-1;\n               std::get<2>( *(V1_it++) ) = val;\n             } \n           } else {\n             if(uhf_block == 3) {\n               if( a <= NCA && b <= NCA ) { \n                 std::get<0>( *V1_itc ) = a-1;\n                 std::get<1>( *V1_itc ) = b-1;\n                 std::get<2>( *(V1_itc++) ) = val;\n               } else if( a>NCA && b>NCA  ) { \n                 std::get<0>( *V1_it ) = a-NCA-1;\n                 std::get<1>( *V1_it ) = b-NCA-1;\n                 std::get<2>( *(V1_it++) ) = val;\n               }\n             } else {\n               if( a <= NMO+NCB && b <= NMO+NCB ) { \n                 std::get<0>( *V1_itc ) = a-1;\n                 std::get<1>( *V1_itc ) = b-1;\n                 std::get<2>( *(V1_itc++) ) = val;\n               } else if( a>NMO+NCB && b>NMO+NCB  ) { \n                 std::get<0>( *V1_it ) = a-NCB-NCA-1;\n                 std::get<1>( *V1_it ) = b-NCB-NCA-1;\n                 std::get<2>( *(V1_it++) ) = val;\n               }\n             }\n           }\n         }\n#else\n// reserved for non c++11 compliant compiler\n#endif\n       } else if(a==0 && b==0 && c==0 && d==0) {\n         if( std::abs(val)==0 && !spinRestricted ) {\n           uhf_block++;\n         } else {\n           NuclearCoulombEnergy = val;\n         } \n       } else if(a!=0 && b==0 && c==0 && d==0) {\n         // ignore, these are the eigenvalues of the Fock operator printed by VASP  \n       } else {\n         app_error()<<\"Error with ASCII integral file, bad indexing. \" <<std::endl;\n         return false;\n       }\n     } \n\n/*\n     return (V2_it == V2.end()) &&\n            (V1_it == V1.end()) &&\n            (V2_itc == V2_c.end()) &&\n            (V2_itm == V2_m.end()) &&\n            (V1_itc == V1_c.end());\n*/\n     return true;\n  }\n\n  bool SparseGeneralHamiltonian::initFromHDF5(const std::string& fileName)\n  {\n\n    Timer.reset(\"Generic\");\n    Timer.start(\"Generic\");\n\n    //if(factorizedHamiltonian) \n    //  n_reading_cores=1; // no parallelization yet\n\n    // processor info\n    int nnodes = TG.getTotalNodes(), nodeid = TG.getNodeID();\n    int ncores = TG.getTotalCores(), coreid = TG.getCoreID();\n    int nread = (n_reading_cores<=0)?(ncores):(n_reading_cores);\n    int node_rank;\n    MPI_Comm_rank(TG.getHeadOfNodesComm(),&node_rank);\n\n    // no hamiltonian distribution yet\n    min_i = 0;\n    max_i = NMO;\n    if(!spinRestricted) max_i *= 2;  // or 4?\n\n    app_log()<<\" Initializing Hamiltonian from file: \" <<fileName <<std::endl;\n\n    V2.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_V2\"),TG.getNodeCommLocal());\n    V2_full.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_V2_full\"),TG.getNodeCommLocal());\n    V2_fact.setup(head_of_nodes,\"SparseGeneralHamiltonian_V2_fact\",TG.getNodeCommLocal());\n\n    if(rotation != \"\" && head_of_nodes ) {\n\n      rotationMatrix.resize(NMO,NMO);\n      std::ifstream in(rotation.c_str());\n      if(in.fail()) {\n        app_error()<<\" Error opening rotation file. \\n\";\n        return false;\n      }\n\n      for(int i=0; i<NMO; i++) \n       for(int j=0; j<NMO; j++) \n         in>>rotationMatrix(i,j);\n\n      in.close();\n    } \n\n    hdf_archive dump(myComm);\n    // these cores will read from hdf file\n    if( coreid < nread ) {\n\n      if(!dump.open(fileName,H5F_ACC_RDONLY)) {\n        app_error()<<\" Error opening integral file in SparseGeneralHamiltonian. \\n\";\n        return false;\n      }\n\n      std::string path = \"/Hamiltonian/SparseGeneralHamiltonian\";\n      if(!dump.is_group( path )) {\n        app_error()<<\" ERROR: H5Group /Hamiltonian/SparseGeneralHamiltonian does not exists in restart file. \\n\";\n        return false;\n      }\n\n      if(!dump.push(\"Hamiltonian\",false)) {\n        app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Group not Hamiltonian found. \\n\"; \n        return false;\n      }\n      if(!dump.push(\"SparseGeneralHamiltonian\",false)) { \n        app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Group not SparseGeneralHamiltonian found. \\n\"; \n        return false;\n      }\n\n    }\n\n    int int_blocks,nvecs;\n    std::vector<int> Idata(8);\n    std::vector<OrbitalType> ivec;    \n    std::vector<ValueType> vvec;    \n\n    if(myComm->rank() == 0) \n      if(!dump.read(Idata,\"dims\")) {\n        app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading dims. \\n\"; \n        return false;\n      } \n   \n    myComm->bcast(Idata);\n\n    int_blocks = Idata[2];\n    if(NMO < 0) NMO = Idata[3];\n    if(NAEA < 0) NAEA = Idata[4];\n    if(NAEB < 0) NAEB = Idata[5];\n    if(Idata[3] != NMO) {\n      app_error()<<\" ERROR: NMO differs from value in integral file. \\n\"; \n      return false;\n    }\n    if(Idata[4] != NAEA) {\n      app_error()<<\" ERROR: NAEA differs from value in integral file. \\n\"; \n      return false;\n    }\n    if(Idata[5] != NAEB) {\n      app_error()<<\" ERROR: NAEA differs from value in integral file. \\n\"; \n      return false;\n    }\n    spinRestricted = (Idata[6]==0)?(true):(false);\n    factorizedHamiltonian = (Idata[7]>0); \n    nvecs = Idata[7];\n\n    H1.resize(Idata[0]);\n    if(myComm->rank() == 0 && distribute_Ham && number_of_TGs > NMO) \n      APP_ABORT(\"Error: number_of_TGs > NMO. \\n\\n\\n\");\n\n    occup_alpha.resize(NAEA);\n    occup_beta.resize(NAEB);\n\n    if(myComm->rank() == 0) { \n      Idata.resize(NAEA+NAEB);\n      if(!dump.read(Idata,\"occups\")) { \n        app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading occups dataset. \\n\"; \n        return false;\n      }\n      for(int i=0; i<NAEA; i++) occup_alpha[i] = Idata[i];\n      for(int i=NAEA, j=0; i<NAEA+NAEB; i++, j++) occup_beta[j] = Idata[i];\n\n      std::vector<ValueType> Rdata(2);\n      if(!dump.read(Rdata,\"Energies\")) { \n        app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading  dataset. \\n\"; \n        return false;\n      }\n      NuclearCoulombEnergy = Rdata[0];\n      FrozenCoreEnergy = Rdata[0];\n    }\n    \n    myComm->bcast(occup_alpha);\n    myComm->bcast(occup_beta);\n    myComm->bcast(NuclearCoulombEnergy);\n    myComm->bcast(FrozenCoreEnergy);\n\n    if(myComm->rank() == 0) { \n\n      ivec.resize(2*H1.size());\n      if(!dump.read(ivec,\"H1_indx\")) {\n        app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading H1_indx. \\n\";\n        return false;\n      } \n      for(int i=0, j=0; i<H1.size(); i++, j+=2)        \n        H1[i] = std::make_tuple(ivec[j],ivec[j+1],0);  \n\n      vvec.resize(H1.size());\n      if(!dump.read(vvec,\"H1\")) {\n        app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading H1.  \\n\";\n        return false;\n      }\n\n      for(int i=0; i<H1.size(); i++) {\n        // keep i<=j by default\n        if(std::get<0>(H1[i]) <= std::get<1>(H1[i]))\n            std::get<2>(H1[i]) = vvec[i];\n        else {\n            std::swap(std::get<0>(H1[i]),std::get<1>(H1[i]));\n            std::get<2>(H1[i]) = myconj(vvec[i]);\n        }\n      }\n\n      std::sort (H1.begin(), H1.end(),mySort);\n    } \n    myComm->bcast<char>(reinterpret_cast<char*>(H1.data()),H1.size()*sizeof(s2D<ValueType>));\n     \n    // now read the integrals\n    if(skip_V2) {\n      // must anything be done???\n    } else if(factorizedHamiltonian) {\n\n      app_log()<<\" Reading factorized hamiltonian. \\n\";  \n\n      min_i = 0;\n      max_i = nvecs;\n\n      int nrows = NMO*NMO;\n      if(!spinRestricted) nrows *= 2;\n\n      if(rank()==0) {\n\n        afqmc::simple_matrix_partition<afqmc::TaskGroup,IndexType,RealType> split(nrows,nvecs,cutoff1bar);\n        std::vector<IndexType> counts;\n        // count dimensions of sparse matrix\n        afqmc::count_entries_hdf5_SpMat(dump,split,std::string(\"V2fact\"),int_blocks,false,counts,TG,true,nread);\n\n        std::vector<IndexType> sets;\n        split.partition_over_TGs(TG,false,counts,sets);\n\n        if(distribute_Ham) {\n          app_log()<<\" Partitioning of (factorized) Hamiltonian Vectors: \";\n          for(int i=0; i<=TG.getNumberOfTGs(); i++)\n            app_log()<<sets[i] <<\" \";\n          app_log()<<std::endl;\n          app_log()<<\" Number of terms in each partitioning: \";\n          for(int i=0; i<TG.getNumberOfTGs(); i++)\n            app_log()<<accumulate(counts.begin()+sets[i],counts.begin()+sets[i+1],0) <<\" \";\n          app_log()<<std::endl;\n\n          MPI_Bcast(sets.data(), sets.size(), MPI_INT, 0, myComm->getMPI());\n          min_i = sets[TG.getTGNumber()];\n          max_i = sets[TG.getTGNumber()+1];\n          //for(int i=0; i<nnodes_per_TG; i++)\n          //  nCholVec_per_node[i] = sets[i+1]-sets[i];\n          //GlobalSpvnSize = std::accumulate(counts.begin(),counts.end(),0);\n        }\n\n        // resize Spvn\n        int sz = std::accumulate(counts.begin()+min_i,counts.begin()+max_i,0);\n        MPI_Bcast(&sz, 1, MPI_INT, 0, TG.getNodeCommLocal());\n\n        V2_fact.setDims(nrows,nvecs);\n        V2_fact.allocate(sz);\n\n        // read Spvn    \n        afqmc::read_hdf5_SpMat(V2_fact,split,dump,std::string(\"V2fact\"),int_blocks,TG,true,nread);\n\n      } else {\n\n        afqmc::simple_matrix_partition<afqmc::TaskGroup,IndexType,RealType> split(nrows,nvecs,cutoff1bar);\n        std::vector<IndexType> counts;\n        // count dimensions of sparse matrix\n        afqmc::count_entries_hdf5_SpMat(dump,split,std::string(\"V2fact\"),int_blocks,false,counts,TG,true,nread);\n\n        std::vector<IndexType> sets(TG.getNumberOfTGs()+1);\n        if(distribute_Ham) {\n          MPI_Bcast(sets.data(), sets.size(), MPI_INT, 0, myComm->getMPI());\n          min_i = sets[TG.getTGNumber()];\n          max_i = sets[TG.getTGNumber()+1];\n        }\n\n        int sz;\n        if( coreid==0 )\n          sz = std::accumulate(counts.begin()+min_i,counts.begin()+max_i,0);\n        MPI_Bcast(&sz, 1, MPI_INT, 0, TG.getNodeCommLocal());\n\n        V2_fact.setDims(nrows,nvecs);\n        V2_fact.allocate(sz);\n\n        if(n_reading_cores <=0 || coreid < n_reading_cores) \n          split.partition_over_TGs(TG,false,counts,sets);\n\n        // read Spvn    \n        afqmc::read_hdf5_SpMat(V2_fact,split,dump,std::string(\"V2fact\"),int_blocks,TG,true,nread);\n\n      } \n      \n\n/*\n      // no parallel reading yet\n      if(myComm->rank() == 0) {\n\n        std::vector<double> residual(nvecs);\n        if(!dump.read(residual,\"V2fact_vec_residual\")) {\n          app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2fact_vec_residual dataset. \\n\"; \n          return false;\n        }\n\n        double cut = cutoff_cholesky;\n        int nvecs_after_cutoff=std::count_if(residual.begin(), residual.end(), \n           [cut] (double i) { return i>cut; } );\n        myComm->bcast(nvecs_after_cutoff);\n\n        std::vector<int> sz(nvecs);\n        if(!dump.read(sz,\"V2fact_block_sizes\")) {\n          app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2fact_vec_sizes dataset. \\n\";      \n          return false;\n        }\n        int nmax = *std::max_element(sz.begin(),sz.end());\n        ivec.reserve(nmax);\n        vvec.reserve(nmax);\n\n        // eliminate std::vectors with small residuals\n        std::vector<int> sz2;\n        sz2.reserve(nvecs_after_cutoff);\n        cholesky_residuals.reserve(nvecs_after_cutoff);\n        for(int i=0; i<nvecs; i++) \n          if(residual[i] > cutoff_cholesky) {\n            cholesky_residuals.push_back(residual[i]); \n            sz2.push_back(sz[i]);\n          }      \n        myComm->bcast(sz2);\n\n        int NMO2 = NMO*NMO;\n        if(!spinRestricted) NMO2 *= 2;\n        V2_fact.setDims(NMO2,nvecs_after_cutoff);\n\n        // this is an upper bound\n        int mysz = std::accumulate(sz2.begin(),sz2.end(),0); \n        V2_fact.reserve(mysz);\n        ValueMatrix Temp,Temp1;\n        if(rotation!=\"\") {\n          if(!spinRestricted) \n            APP_ABORT(\"Error: rotation only implemented with spinRestricted. \\n\\n\\n\"); \n          Temp.resize(NMO,NMO); \n          Temp1.resize(NMO,NMO); \n          ivec.reserve(NMO2);\n          vvec.reserve(NMO2);\n        }\n         \n\n        Timer.reset(\"Generic3\");\n        Timer.reset(\"Generic4\");\n\n        for(int i=0; i<nvecs; i++) {\n    \n          if( residual[i] <= cutoff_cholesky ) continue;\n\n          ivec.resize(sz[i]);\n          vvec.resize(sz[i]);\n          \n          Timer.start(\"Generic3\");\n          if(!dump.read(ivec,std::string(\"V2fact_index_\")+std::to_string(i))) {\n            app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2fact_index_\" <<std::to_string(i) <<\" dataset. \\n\";      \n            app_error()<<\" Expected size: \" <<sz[i] <<\"\\n\";\n            return false;\n          } \n          if(!dump.read(vvec,std::string(\"V2fact_vals_\")+std::to_string(i))) { \n            app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2fact_vals_ dataset. \\n\";      \n            return false;\n          }\n          Timer.stop(\"Generic3\");\n\n          if(rotation!=\"\") {\n            Temp=0;\n            for(int k=0; k<sz[i]; k++) \n              Temp(ivec[k]/NMO,ivec[k]%NMO) = vvec[k];\n            DenseMatrixOperators::product(NMO,NMO,NMO,ValueType(1),Temp.data(),NMO,rotationMatrix.data(),NMO,ValueType(0),Temp1.data(),NMO); \n            DenseMatrixOperators::product_AhB(NMO,NMO,NMO,ValueType(1.0),rotationMatrix.data(),NMO,Temp1.data(),NMO,ValueType(0.0),Temp.data(),NMO); \n            ivec.clear();\n            vvec.clear(); \n            for(int j=0; j<NMO; j++) \n             for(int k=0; k<NMO; k++) {\n               if(std::abs(Temp(j,k)) > cutoff1bar) {\n                 ivec.push_back(j*NMO+k);\n                 vvec.push_back(Temp(j,k));\n               } \n             } \n            app_log()<<\" Change in Chol Vect. number of terms, old:\" <<sz[i] <<\"  new:\" <<ivec.size() <<std::endl; \n \n          }\n\n          Timer.start(\"Generic4\");\n          myComm->bcast(ivec.data(),ivec.size(),MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast(vvec.data(),vvec.size(),0,MPI_COMM_HEAD_OF_NODES);\n          Timer.stop(\"Generic4\");\n \n            for(int k=0; k<ivec.size(); k++) {\n              if(std::abs(vvec[k]) > cutoff1bar ) \n                V2_fact.add(ivec[k],i,vvec[k],false);\n            }\n\n        }\n\n      } else {  // if(myComm->rank() == 0)\n\n        int nvecs_after_cutoff;\n        myComm->bcast(nvecs_after_cutoff);\n\n        std::vector<int> sz(nvecs_after_cutoff);\n        myComm->bcast(sz);\n\n        int NMO2 = NMO*NMO;\n        if(!spinRestricted) NMO2 *= 2;\n        V2_fact.setDims(NMO2,nvecs_after_cutoff);\n\n        // right now this is an upper bound, since terms below the 2bar cutoff can be ignored \n        int mysz = std::accumulate(sz.begin(),sz.end(),0);\n        V2_fact.reserve(mysz);\n\n        if(head_of_nodes) {\n          int nmax = *std::max_element(sz.begin(),sz.end());\n          std::vector<IndexType> ivec;\n          std::vector<ValueType> vvec;\n          ivec.reserve(nmax);\n          vvec.reserve(nmax);\n          for(int i=0; i<nvecs_after_cutoff; i++) {\n\n            ivec.resize(sz[i]);\n            vvec.resize(sz[i]);\n\n            myComm->bcast(ivec.data(),ivec.size(),MPI_COMM_HEAD_OF_NODES);\n            myComm->bcast(vvec.data(),vvec.size(),0,MPI_COMM_HEAD_OF_NODES);\n\n              for(int k=0; k<ivec.size(); k++) {\n                if(std::abs(vvec[k]) > cutoff1bar )\n                  V2_fact.add(ivec[k],i,vvec[k],false);\n              }\n\n          }\n\n        }\n\n      }\n      Timer.reset(\"Generic2\");\n      Timer.start(\"Generic2\");\n      V2_fact.compress(TG.getNodeCommLocal());\n      Timer.stop(\"Generic2\");\n\n      app_log()<<\" -- Average time to read std::vector from h5 file: \" <<Timer.average(\"Generic3\") <<\"\\n\";\n      app_log()<<\" -- Average time to bcast std::vector: \" <<Timer.average(\"Generic4\") <<\"\\n\";\n      app_log()<<\" -- Time to compress factorized Hamiltonian from h5 file: \" <<Timer.average(\"Generic2\") <<\"\\n\";\n*/\n      app_log()<<\" Memory used by factorized 2-el integral table: \" <<V2_fact.memoryUsage()/1024.0/1024.0 <<\" MB. \" <<std::endl;\n \n    } else {  // factorizedHamiltonian\n\n      std::vector<long> ntpo(NMO,0);\n      std::vector<IndexType> indxvec;\n      int ntmax;\n      std::vector<int> pool_dist;\n      if(coreid < nread) {\n\n        Idata.resize(int_blocks);\n        // Idata[i]: number of terms per block\n        if(!dump.read(Idata,\"V2_block_sizes\")) {\n          app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2_block_sizes dataset. \\n\";\n          return false;\n        }\n\n        ntmax = *std::max_element(Idata.begin(), Idata.end());\n        indxvec.reserve(2*ntmax);\n        vvec.reserve(ntmax);\n\n        // divide blocks \n        FairDivide(int_blocks,nread,pool_dist);\n\n        int first_local_block = pool_dist[coreid];\n        int last_local_block = pool_dist[coreid+1];\n\n        for(int ib=first_local_block; ib<last_local_block; ib++) {\n          if( ib%nnodes != nodeid ) continue;\n          if(Idata[ib]==0) continue;\n          indxvec.resize(2*Idata[ib]);\n          vvec.resize(Idata[ib]);\n          if(!dump.read(indxvec,std::string(\"V2_index_\")+std::to_string(ib))) {\n            app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2_index_\" <<ib <<\" dataset. \\n\";\n            return false;\n          }\n          if(!dump.read(vvec,std::string(\"V2_vals_\")+std::to_string(ib))) {\n            app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2_vals_\" <<ib <<\" dataset. \\n\";\n            return false;\n          }\n            \n          std::vector<IndexType>::iterator iti = indxvec.begin();\n          for(std::vector<ValueType>::iterator itv = vvec.begin(); itv < vvec.end(); itv++, iti+=2) {\n            if(std::abs(*itv) < cutoff1bar )\n                continue;\n            s4D<ValueType> ijkl = std::make_tuple(  static_cast<OrbitalType>((*iti)/NMO),\n                                                    static_cast<OrbitalType>((*(iti+1))/NMO),  \n                                                    static_cast<OrbitalType>((*iti)%NMO),\n                                                    static_cast<OrbitalType>((*(iti+1))%NMO), ValueType(0));     \n            find_smallest_permutation(ijkl); \n            ntpo[std::get<0>(ijkl)]++;\n          }   \n        }\n      }\n      myComm->allreduce(ntpo);\n\n      if(distribute_Ham) {\n        std::vector<long> sets(TG.getNumberOfTGs()+1);\n        if(myComm->rank() == 0) {\n          std::vector<long> nv(NMO+1);\n          nv[0]=0;\n          for(int i=0; i<NMO; i++) \n            nv[i+1]=nv[i]+ntpo[i];\n          balance_partition_ordered_set(NMO,nv.data(),sets);\n          app_log()<<\" Hamiltonian partitioning: \\n   Orbitals:        \";\n          for(int i=0; i<=TG.getNumberOfTGs(); i++) app_log()<<sets[i] <<\" \"; \n          app_log()<<std::endl <<\"   Terms per block: \";  \n          for(int i=0; i<TG.getNumberOfTGs(); i++) app_log()<<nv[sets[i+1]]-nv[sets[i]] <<\" \";\n          app_log()<<std::endl;  \n        }\n        MPI_Bcast(sets.data(),sets.size(),MPI_LONG,0,myComm->getMPI());\n        min_i = static_cast<int>(sets[TG.getTGNumber()]);\n        max_i = static_cast<int>(sets[TG.getTGNumber()+1]);\n      }\n\n      long nttot = std::accumulate(ntpo.begin()+min_i,ntpo.begin()+max_i,long(0));\n      V2.reserve(nttot);\n\n      if( coreid < nread ) {\n\n        std::vector<IndexType> ivec2;\n        std::vector<ValueType> vvec2;\n        ivec2.reserve(2*ntmax);\n        vvec2.reserve(ntmax);\n        int maxv = 10000;\n        std::vector<s4D<ValueType>> vals;\n        vals.reserve(maxv);\n\n        int first_local_block = pool_dist[coreid];\n        int last_local_block = pool_dist[coreid+1];\n        int nbtot = last_local_block-first_local_block;\n        int niter = nbtot/nnodes + std::min(nbtot%nnodes,1);\n\n        for(int iter=0; iter<niter; iter++) {\n          int first_block = first_local_block + nnodes*iter;\n          int last_block = std::min(first_block+nnodes,last_local_block);\n          int myblock_number = first_block + nodeid;\n          if(myblock_number < last_local_block && Idata[myblock_number] > 0) {\n            indxvec.resize(2*Idata[myblock_number]);\n            vvec.resize(Idata[myblock_number]);\n            if(!dump.read(indxvec,std::string(\"V2_index_\")+std::to_string(myblock_number))) {\n              app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2_index_\" <<myblock_number <<\" dataset. \\n\";\n              return false;\n            }\n            if(!dump.read(vvec,std::string(\"V2_vals_\")+std::to_string(myblock_number))) {\n              app_error()<<\" Error in SparseGeneralHamiltonian::initFromHDF5(): Problems reading V2_vals_\" <<myblock_number <<\" dataset. \\n\";\n              return false;\n            }\n          }\n         \n          for(int k=first_block,ipr=0; k<last_block; k++,ipr++) {\n            if(Idata[k] == 0) continue;\n            ivec2.resize(2*Idata[k]);\n            vvec2.resize(Idata[k]);\n            if(ipr==node_rank) {\n              assert(myblock_number==k);\n              std::copy(indxvec.begin(),indxvec.end(),ivec2.begin());\n              std::copy(vvec.begin(),vvec.end(),vvec2.begin());\n            }\n\n            MPI_Bcast(ivec2.data(), ivec2.size(), MPI_INT, ipr, TG.getHeadOfNodesComm() );\n#if defined(QMC_COMPLEX)\n            MPI_Bcast(vvec2.data(),2*vvec2.size(), MPI_DOUBLE, ipr, TG.getHeadOfNodesComm() );\n#else\n            MPI_Bcast(vvec2.data(),vvec2.size(), MPI_DOUBLE, ipr, TG.getHeadOfNodesComm() );\n#endif\n\n            std::vector<IndexType>::iterator iti = ivec2.begin(); \n            for(std::vector<ValueType>::iterator itv = vvec2.begin(); itv < vvec2.end(); itv++, iti+=2) { \n              if(std::abs(*itv) < cutoff1bar )\n                  continue;\n              s4D<ValueType> ijkl = std::make_tuple(  static_cast<OrbitalType>((*iti)/NMO),\n                                                      static_cast<OrbitalType>((*(iti+1))/NMO),  \n                                                      static_cast<OrbitalType>((*iti)%NMO),\n                                                      static_cast<OrbitalType>((*(iti+1))%NMO), *itv);     \n              find_smallest_permutation(ijkl); \n              if( std::get<0>(ijkl) >= min_i && std::get<0>(ijkl) < max_i) { \n                vals.push_back(ijkl);\n                if(vals.size()==maxv) {\n                  V2.push_back(vals,nread>1);\n                  vals.clear();\n                }\n              }\n            }\n          }   \n        }\n        if(vals.size() > 0) \n          V2.push_back(vals,nread>1);\n      }\n\n      Timer.reset(\"Generic2\");\n      Timer.start(\"Generic2\");\n      V2.sort (mySort, TG.getNodeCommLocal(),inplace);\n      Timer.stop(\"Generic2\");\n      app_log()<<\" -- Time to compress Hamiltonian from h5 file: \" <<Timer.average(\"Generic2\") <<\"\\n\";\n      app_log()<<\" Memory used by 2-el integral table: \" <<V2.memoryUsage()/1024.0/1024.0 <<\" MB. \" <<std::endl;\n\n    }\n\n    if( coreid < nread ) {\n      dump.pop();\n      dump.pop();\n      dump.close();\n    }\n    myComm->barrier();\n\n    // generate IJ matrix to speedup table seaches\n    if(!skip_V2 && V2.size()>0)\n      generateIJ();\n\n    Timer.stop(\"Generic\");\n    app_log()<<\" -- Time to initialize Hamiltonian from h5 file: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n    if(!skip_V2) hdf_write();\n    if(rank() == 0 && !skip_V2) {\n      ascii_write();\n    }\n\n/*   Meant for debugging integral codes, remove for released code\n    if(rank() == 0 ) {\n      std::vector<ValueType> eig(NMO);\n      for(IndexType i=0; i<NMO; i++) {\n        eig[i] = H(i,i);\n        for(std::vector<IndexType>::iterator it = occup_alpha.begin(); it<occup_alpha.end(); it++)\n          eig[i] += H_2bar(i,*it,i,*it);\n        for(std::vector<IndexType>::iterator it = occup_beta.begin(); it<occup_beta.end(); it++)\n          eig[i] += H(i,*it,i,*it);\n        app_log()<<i <<\"   \" <<eig[i] <<std::endl;\n      }\n      isOcc_alpha.clear();\n      isOcc_beta.clear();\n      for(IndexType i=0; i<2*NMO; i++) isOcc_alpha[i]=false;\n      for(IndexType i=0; i<2*NMO; i++) isOcc_beta[i]=false;\n      for(int i=0; i<occup_alpha.size(); i++) isOcc_alpha[ occup_alpha[i] ]=true;\n      for(int i=0; i<occup_beta.size(); i++) isOcc_beta[ occup_beta[i] ]=true;\n      virtual_alpha.clear();\n      virtual_beta.clear();\n      virtual_alpha.reserve(NMO-NAEA);\n      virtual_beta.reserve(NMO-NAEB);\n      for(IndexType i=0; i<NMO; i++)\n        if(!isOcc_alpha[i]) virtual_alpha.push_back(i);\n      for(IndexType i=NMO; i<2*NMO; i++)\n        if(!isOcc_beta[i]) virtual_beta.push_back(i);\n      ValueType Emp2=0;  \n      std::vector<IndexType>::iterator iti,itj,ita,itb;\n      for(iti=occup_alpha.begin(); iti<occup_alpha.end(); iti++)\n      for(itj=occup_alpha.begin(); itj<occup_alpha.end(); itj++)\n      for(ita=virtual_alpha.begin(); ita<virtual_alpha.end(); ita++)\n      for(itb=virtual_alpha.begin(); itb<virtual_alpha.end(); itb++)\n        Emp2 += H(*iti,*itj,*ita,*itb)*(2.0*H(*ita,*itb,*iti,*itj) - H(*ita,*itb,*itj,*iti))/(eig[*iti]+eig[*itj]-eig[*ita]-eig[*itb]);\n      app_log()<<\" Emp2: \" <<Emp2 <<std::endl;\n    }\n*/\n    return true;\n\n  }\n\n  void SparseGeneralHamiltonian::ascii_write() {\n\n    if(ascii_write_file == std::string(\"\")) return;\n\n    if(factorizedHamiltonian) {\n      app_log()<<\" factorizedHamiltonian output not yet implemented \" <<std::endl;\n      return;\n    }\n \n    std::ofstream out(ascii_write_file.c_str());\n    if(out.fail()) {\n      app_error()<<\" Error opening restart file in SparseGeneralHamiltonian::ascii_write() . \" <<std::endl; \n      return;\n    }\n\n// hack to write sparse matrix in ascii for testing\n/*\n   if(!factorizedHamiltonian) \n     APP_ABORT(\"Error: Matrix dump only for factorized hamiltonian \\n\\n\\n\");\n   if(rank()!=0) return;\n   int nvecs=V2_fact.rows();\n   out<<\"# nrows: \" <<nvecs <<\" ncols: \" <<V2_fact.cols() <<\"\\n\";\n   for(ComplexSMSpMat::intType i=0; i<nvecs; i++) {\n     int k1 = *(V2_fact.rowIndex_begin()+i+1); \n     for(int k=*(V2_fact.rowIndex_begin()+i); k<k1; k++) \n       out<<i <<\" \" <<*(V2_fact.cols_begin()+k) <<\" \"\n          <<std::setprecision(12) <<*(V2_fact.vals_begin()+k) <<\"\\n\";\n   }\n   out<<std::endl;\n   out.close();\n   APP_ABORT(\" FINISHED DUMPING ASCII FILE. \\n\\n\\n\");   \n*/\n \n    out<<\"&FCI NORB=\" <<NMO <<\",NELEC=\" <<NAEA+NAEB <<\",MS2=\" <<MS2 <<\",\" <<\"\\n\"\n       <<\"ISYM=\" <<ISYM <<\",\" <<\"\\n/\\n\"; \n\n    out.setf(std::ios::scientific, std::ios::floatfield);\n    if(factorizedHamiltonian) {\n      out<<\" factorizedHamiltonian output not yet implemented \" <<std::endl;\n      return;\n    } else {\n\n      SMDenseVector<s4D<ValueType> >::iterator it=V2.begin();\n      for( ; it!=V2.end(); it++) {\n        if(std::get<0>(*it) >= NMO) break;\n        out<<std::setprecision(16) <<std::get<4>(*it) <<std::setw(5) <<std::get<0>(*it)+1 <<std::setw(5) <<std::get<2>(*it)+1 \n            <<std::setw(5) <<std::get<1>(*it)+1 <<std::setw(5) <<std::get<3>(*it)+1 <<\"\\n\";\n      }\n      if(!spinRestricted) {\n        out<<\" UHF output not yet implemented \" <<std::endl;\n      }\n\n    }\n\n    s2Dit it=H1.begin();\n    for( ; it!=H1.end(); it++) {\n      if(std::get<0>(*it) >= NMO) break; \n      out<<std::setprecision(16) <<std::get<2>(*it) <<std::setw(5) <<std::get<0>(*it)+1 <<std::setw(5) <<std::get<1>(*it)+1 <<\"    0    0\\n\"; \n    } \n    if(!spinRestricted) {\n      out<<\" 0.0                    0    0    0    0\\n\";\n      for( ; it!=H1.end(); it++) {\n        if(std::get<0>(*it) >= NMO) break;\n        out<<std::setprecision(16) <<std::get<2>(*it) <<\" \" <<std::get<0>(*it)-NMO+1 <<\" \" <<std::get<1>(*it)-NMO+1 <<\"   0   0\\n\";\n      }\n    }\n    out<<std::setprecision(16) <<NuclearCoulombEnergy <<\"    0    0    0    0\\n\";\n\n    out.close();\n\n  } \n\n  // this needs to be modified to wread/write in blocks\n  // to avoid having to allocate the full array twice\n  // Also, you could add support in hdf_archive for tuples \n  void SparseGeneralHamiltonian::hdf_write() {\n\n    if(skip_V2) \n      return; \n\n    if(hdf_write_file == std::string(\"\")) return;\n\n    bool writeFactorized = factorizedHamiltonian;\n    if(hdf_write_type!=\"default\") {\n      if(factorizedHamiltonian) writeFactorized = (hdf_write_type == \"factorized\");\n      else writeFactorized = (hdf_write_type != \"integrals\");\n    }\n\n    // pseudo-hack to avoid a lot of indenting \n    if(myComm->rank() > 0) {\n\n\n      // only parallelized path\n      if(!writeFactorized && factorizedHamiltonian) {\n        std::vector<OrbitalType> ivec; \n        std::vector<ValueType> vvec;\n        for(int k=0; k<NMO; k++) {\n          ivec.clear();\n          vvec.clear();\n          SparseHamiltonianFromFactorization(k,ivec,vvec,cutoff1bar);\n        }\n      }\n  \n      return; \n    }\n\n    hdf_archive dump(myComm);\n    if(!dump.create(hdf_write_file)) {\n      app_error()<<\" Error opening restart file in SparseGeneralHamiltonian. \\n\";\n      return;\n    }\n\n    std::string path = \"/Hamiltonian/SparseGeneralHamiltonian\";\n    if(dump.is_group( path )) {\n      app_error()<<\" ERROR: H5Group /Hamiltonian/SparseGeneralHamiltonian already exists in restart file. Not over-writing data in file. \\n\"; \n      return;\n    }\n\n    dump.push(\"Hamiltonian\");\n    dump.push(\"SparseGeneralHamiltonian\");\n\n    int V2tot=0;\n    std::vector<int> Idata(8);\n/* writing at the end since I don't have all the information necessarily\n    Idata[0]=H1.size();\n    if(factorizedHamiltonian)\n      Idata[1]=V2_fact.size();\n    else\n      Idata[1]=V2.size();\n    Idata[2]=0;\n    Idata[3]=NMO;\n    Idata[4]=NAEA;\n    Idata[5]=NAEB;\n    Idata[6]=spinRestricted?(0):(1);\n    Idata[7]=0;\n    if(factorizedHamiltonian)\n      Idata[7] = V2_fact.cols(); \n    dump.write(Idata,\"dims\");\n*/\n\n    Idata.resize(NAEA+NAEB);\n    for(int i=0; i<NAEA; i++) Idata[i] = occup_alpha[i];\n    for(int i=NAEA, j=0; i<NAEA+NAEB; i++, j++) Idata[i] = occup_beta[j];\n    dump.write(Idata,\"occups\");\n\n    std::vector<ValueType> Rdata(2);\n    Rdata[0] = NuclearCoulombEnergy;\n    Rdata[1] = FrozenCoreEnergy; \n    dump.write(Rdata,\"Energies\");\n\n    // write H1 \n    std::vector<OrbitalType> ivec; \n    ivec.resize(2*H1.size());\n    for(int i=0, j=0; i<H1.size(); i++, j+=2) \n      std::tie (ivec[j],ivec[j+1],std::ignore) = H1[i];   \n    dump.write(ivec,\"H1_indx\");\n\n    std::vector<ValueType> vvec;\n    vvec.resize(H1.size());\n    for(int i=0; i<H1.size(); i++)\n      std::tie (std::ignore,std::ignore,vvec[i]) = H1[i];\n    dump.write(vvec,\"H1\");\n\n    if(writeFactorized) {\n\n      if(!factorizedHamiltonian) {\n        app_error()<<\" Error: Can only write factorized hamiltonian if input hamiltonian is already factorized. \\n\\n\\n\";\n        APP_ABORT(\" Error: Can only write factorized hamiltonian if input hamiltonian is already factorized. \\n\\n\\n\");\n      }\n\n      if(cholesky_residuals.size() != V2_fact.cols()) {\n        app_error()<<\"Error: Incorrect size of cholesky_residuals: \" <<cholesky_residuals.size() <<\" \" <<V2_fact.cols() <<std::endl;  \n        APP_ABORT(\"Error. \\n\\n\\n\");\n      }\n      dump.write(cholesky_residuals,std::string(\"V2fact_vec_residual\"));\n\n      V2_fact.transpose();\n\n      int nvecs=V2_fact.rows();\n      std::vector<int> sz(nvecs);\n      for(int i=0; i<nvecs; i++) \n        sz[i]=*(V2_fact.rowIndex_begin()+i+1) - *(V2_fact.rowIndex_begin()+i);\n      int nmax = *std::max_element(sz.begin(),sz.end());\n      dump.write(sz,std::string(\"V2fact_vec_sizes\"));\n      std::vector<IndexType> ivec;\n      std::vector<ValueType> vvec;\n      ivec.reserve(nmax);\n      vvec.reserve(nmax);\n      for(ComplexSMSpMat::intType i=0; i<nvecs; i++) {\n\n        ivec.resize(sz[i]);\n        vvec.resize(sz[i]);\n        std::copy(V2_fact.cols_begin()+(*(V2_fact.rowIndex_begin()+i)),V2_fact.cols_begin()+(*(V2_fact.rowIndex_begin()+i+1)),ivec.begin());\n        std::copy(V2_fact.vals_begin()+(*(V2_fact.rowIndex_begin()+i)),V2_fact.vals_begin()+(*(V2_fact.rowIndex_begin()+i+1)),vvec.begin());\n\n        dump.write(ivec,std::string(\"V2fact_index_\")+std::to_string(i));\n        dump.write(vvec,std::string(\"V2fact_vals_\")+std::to_string(i));\n\n      }\n\n      V2_fact.transpose();\n\n    } else { \n      // write V2\n      // terms with i index are found between [Idata[i-1],Idata[i])  \n      Idata.resize(NMO);\n      int ntmax=0;\n      OrbitalType i0,j0,k0,l0,iold=0;\n\n      if(factorizedHamiltonian) {\n\n        for(int k=0; k<NMO; k++) {\n          ivec.clear();\n          vvec.clear();\n          SparseHamiltonianFromFactorization(k,ivec,vvec,cutoff1bar); \n          Idata[k]= (k==0?0:Idata[k-1]+vvec.size());\n          V2tot+=vvec.size();\n          dump.write(ivec,std::string(\"V2_indx_\")+std::to_string(k));\n          dump.write(vvec,std::string(\"V2_\")+std::to_string(k));\n        }\n\n        dump.write(Idata,\"V2_block_sizes\");\n\n      } else {\n        for(int i=0; i<V2.size(); i++) {\n          std::tie (i0,j0,k0,l0,std::ignore) = V2[i];\n          if(iold != i0) {\n            for(int k=iold; k<i0; k++) Idata[k]=i; \n            iold=i0;\n          }\n        } \n        for(int k=iold; k<NMO; k++)  Idata[k]=V2.size();\n        ntmax = Idata[0];\n        for(int i=1; i<NMO; i++) {\n          if(ntmax < (Idata[i]-Idata[i-1]))\n            ntmax = Idata[i]-Idata[i-1];\n        }\n\n        dump.write(Idata,\"V2_block_sizes\");\n\n        ivec.reserve(3*ntmax);\n        vvec.reserve(ntmax);\n\n        for(int k=0; k<NMO; k++) { \n          int ik0 = (k==0)?0:Idata[k-1]; \n          if(Idata[k]==ik0) continue; \n          ivec.clear();\n          // no point in storing i\n          ivec.resize(3*(Idata[k]-ik0));\n          for (int i=ik0,jk=0; i<Idata[k]; i++,jk+=3) \n            std::tie (i0,ivec[jk],ivec[jk+1],ivec[jk+2],std::ignore) = V2[i];   \n          dump.write(ivec,std::string(\"V2_indx_\")+std::to_string(k));\n\n          vvec.clear();\n          vvec.resize(Idata[k]-ik0);\n          for(int i=ik0; i<Idata[k]; i++) \n            std::tie (std::ignore,std::ignore,std::ignore,std::ignore,vvec[i-ik0]) = V2[i];\n          V2tot+=vvec.size();\n          dump.write(vvec,std::string(\"V2_\")+std::to_string(k));\n        }\n \n      }\n\n    }\n\n    Idata.resize(8);\n    Idata[0]=H1.size();\n    Idata[1]=V2tot;\n    Idata[2]=0;\n    Idata[3]=NMO;\n    Idata[4]=NAEA;\n    Idata[5]=NAEB;\n    Idata[6]=spinRestricted?(0):(1);\n    Idata[7]=0;\n    if(writeFactorized && factorizedHamiltonian)\n      Idata[7] = V2_fact.cols();\n    dump.write(Idata,\"dims\");\n\n    dump.pop();\n    dump.pop();\n\n    dump.flush();\n    dump.close();\n\n  }\n\n  void SparseGeneralHamiltonian::calculateOneBodyPropagator(RealType cut, RealType dt, ComplexMatrix& Hadd , std::vector<s2D<ComplexType> >& Pkin) \n  {\n\n    int NMO2 = spinRestricted?(NMO):(2*NMO); \n\n    ComplexMatrix v(NMO2,NMO),P(NMO2,NMO);\n    \n    // v is the dense representation of H1+H1add+v0\n    // 1. Hadd should be the contribution from mean-field substraction, otherwise zero  \n    //    Now also includes contribution from vn0 = -0.5* sum_{i,l,sigma} (sum_j <i_sigma,j_sigma|j_sigma,l_sigma> ) c+i_sigma cl_sigma\n    for(int i=0; i<NMO; i++) { \n     v(i,i) = Hadd(i,i); \n     for(int j=i+1; j<NMO; j++) { \n       if( std::abs( Hadd(i,j) - myconj(Hadd(j,i)) ) > 1e-8 ) {\n         app_error()<<\" Error during construction of 1-body propagator. Hadd is not hermitian. \\n\";\n         app_error()<<i <<\" \" <<j <<\" \" <<Hadd(i,j) <<\" \" <<Hadd(j,i) <<std::endl;\n         APP_ABORT(\"Error in SparseGeneralHamiltonian::calculateOneBodyPropagator. \\n\");\n       }\n       v(i,j) = 0.5*(Hadd(i,j)+myconj(Hadd(j,i))); \n       v(j,i) = myconj(v(i,j)); \n     }\n    }\n    if(!spinRestricted) {\n      for(int i=0; i<NMO; i++) {\n       v(i+NMO,i) = Hadd(i+NMO,i);\n       for(int j=i+1; j<NMO; j++) {\n         if( std::abs( Hadd(i+NMO,j) - myconj(Hadd(j+NMO,i)) ) > 1e-8 ) {\n           app_error()<<\" Error during construction of 1-body propagator. Hadd is not hermitian. \\n\";\n           app_error()<<i+NMO <<\" \" <<j <<\" \" <<Hadd(i+NMO,j) <<\" \" <<Hadd(j+NMO,i) <<std::endl;\n           APP_ABORT(\"Error in SparseGeneralHamiltonian::calculateOneBodyPropagator. \\n\");\n         }\n         v(i+NMO,j) = 0.5*(Hadd(i+NMO,j)+myconj(Hadd(j+NMO,i)));\n         v(j+NMO,i) = myconj(v(i+NMO,j));\n       }\n      }\n    }\n\n    if(!DenseMatrixOperators::isHermitian(NMO,v.data(),NMO)) {\n      app_log()<<\"Hadd: \\n\"  <<Hadd <<std::endl;\n      app_error()<<\" Error during construction of 1-body propagator. Hadd is not hermitian. \\n\";\n      APP_ABORT(\"Error in SparseGeneralHamiltonian::calculateOneBodyPropagator. \\n\");\n    }  \n    if(!spinRestricted) { \n      if(!DenseMatrixOperators::isHermitian(NMO,v.data()+NMO*NMO,NMO)) {\n        app_error()<<\" Error during construction of 1-body propagator. Hadd(beta) is not hermitian. \\n\";\n        APP_ABORT(\"Error in SparseGeneralHamiltonian::calculateOneBodyPropagator. \\n\");\n      }  \n    }  \n\n    // 2. Add H1\n    for(s2Dit it = H1.begin(); it != H1.end(); it++) { \n      v( std::get<0>(*it), Index2Col(std::get<1>(*it)) ) += std::get<2>(*it);\n      if(std::get<0>(*it) != std::get<1>(*it)) \n        v( std::get<1>(*it), Index2Col(std::get<0>(*it)) ) += myconj(std::get<2>(*it));\n    }\n\n\n      // adding contribution from transformation of H2 into quadratic form\n      // 3.  -0.5* sum_{i,l,sigma} (sum_j <i_sigma,j_sigma|j_sigma,l_sigma> ) c+i_sigma cl_sigma \n      //   Calculated with HSPotential and included in Hadd!!!\n\n      // 4. scale by -0.5*dt\n      for(int i=0; i<NMO2; i++) \n       for(int j=0; j<NMO; j++) \n         v(i,j) *= -0.5*dt; \n\n      if(!DenseMatrixOperators::isHermitian(NMO,v.data(),NMO)) {\n        app_error()<<\" Error during construction of 1-body propagator. v is not hermitian. \\n\";\n        APP_ABORT(\"Error in SparseGeneralHamiltonian::calculateOneBodyPropagator. \\n\");\n      }  \n\n      if(!spinRestricted && !DenseMatrixOperators::isHermitian(NMO,v.data()+NMO*NMO,NMO)) {\n        app_error()<<\" Error during construction of 1-body propagator. v(beta) is not hermitian. \\n\";\n        APP_ABORT(\"Error in SparseGeneralHamiltonian::calculateOneBodyPropagator. \\n\");\n      }  \n\n      // 5. exponentiate v\n      if(!DenseMatrixOperators::exponentiateHermitianMatrix(NMO,v.data(),NMO,P.data(),NMO)) {\n        app_error()<<\" Error during exponentiation of one body hamiltonian. \\n\";\n        APP_ABORT(\"Error in SparseGeneralHamiltonian::calculateOneBodyPropagator. \\n\");\n      }  \n\n      if(!spinRestricted && !DenseMatrixOperators::exponentiateHermitianMatrix(NMO,v.data()+NMO*NMO,NMO,P.data()+NMO*NMO,NMO)) {\n        app_error()<<\" Error during exponentiation of one body hamiltonian. \\n\";\n        APP_ABORT(\"Error in SparseGeneralHamiltonian::calculateOneBodyPropagator. \\n\");\n      }  \n\n      // 6. get non-zero components, generate sparse representation \n      int cnt=0;\n      for(int i=0; i<NMO; i++)\n       for(int j=i; j<NMO; j++)  \n         if(std::abs(P(i,j)) > cut) cnt = ( (i==j)?(cnt+1):(cnt+2) ); \n      if(!spinRestricted) {\n        for(int i=NMO; i<2*NMO; i++)\n         for(int j=i; j<2*NMO; j++)\n           if(std::abs(P(i,j-NMO)) > cut) cnt = ( (i==j)?(cnt+1):(cnt+2) );\n      }\n\n      Pkin.clear();\n      Pkin.reserve(cnt);\n      for(IndexType i=0; i<NMO; i++)\n       for(IndexType j=i; j<NMO; j++)  \n         if(std::abs(P(i,j)) > cut) {\n           if(i==j) {\n              Pkin.push_back(std::forward_as_tuple(i,j,P(i,j)));\n            } else {\n              Pkin.push_back(std::forward_as_tuple(i,j,P(i,j)));\n              Pkin.push_back(std::forward_as_tuple(j,i,myconj(P(i,j))));\n            }\n         } \n     std::sort(Pkin.begin(),Pkin.end(),mySort);\n     int ntermsalpha = Pkin.size();\n     if(!spinRestricted) {\n        for(IndexType i=NMO; i<2*NMO; i++)\n         for(IndexType j=i; j<2*NMO; j++)\n           if(std::abs(P(i,j-NMO)) > cut) {\n             if(i==j) {\n                Pkin.push_back(std::forward_as_tuple(i-NMO,j-NMO,P(i,j-NMO)));\n              } else {\n                Pkin.push_back(std::forward_as_tuple(i-NMO,j-NMO,P(i,j-NMO)));\n                Pkin.push_back(std::forward_as_tuple(j-NMO,i-NMO,myconj(P(i,j-NMO))));\n              }\n           }\n     }     \n     std::sort(Pkin.begin()+ntermsalpha,Pkin.end(),mySort);\n\n     // 7. test and time if you want\n     int nterms = 20;\n     Timer.reset(\"Generic2\");\n     Timer.start(\"Generic2\");\n\n     ComplexMatrix S(NMO,NAEA),Snew(NMO,NAEA);\n     for(int i=0; i<NAEA; i++) S(i,i)=1.0;\n\n     for(int i=0; i<nterms; i++)\n       DenseMatrixOperators::product(NMO,NAEA,NMO,ComplexType(1),P.data(),NMO,S.data(),NAEA,ComplexType(0),Snew.data(),NAEA); \n\n     Timer.stop(\"Generic2\");\n     app_log()<<\" -- Average time for dense x dense MM product: \" <<Timer.average(\"Generic2\")/nterms <<\"\\n\";\n\n     Timer.reset(\"Generic2\");\n     Timer.start(\"Generic2\");\n\n     for(int i=0; i<nterms; i++)\n       SparseMatrixOperators::product_SD(NAEA,Pkin.data(),ntermsalpha,S.data(),NAEA,Snew.data(),NAEA);\n\n     Timer.stop(\"Generic2\");\n     app_log()<<\" -- Average time for sparse x dense MM product: \" <<Timer.average(\"Generic2\")/nterms <<\"\\n\";\n\n\n  }\n\n  void SparseGeneralHamiltonian::calculateHSPotentials_Diagonalization(RealType cut, RealType dt, ComplexMatrix& vn0, SPValueSMSpMat& Spvn, SPValueSMVector& Dvn, afqmc::TaskGroup& TGprop, std::vector<int>& nvec_per_node,  bool sparse, bool parallel)\n  {\n\n    if(skip_V2)\n      APP_ABORT(\"Error: Calling SparseGeneralHamiltonian routines with skip_V2=yes. \\n\\n\\n\");\n\n    if(factorizedHamiltonian) {\n      calculateHSPotentials_FactorizedHam(cut,dt,vn0,Spvn,Dvn,TGprop,nvec_per_node,sparse,parallel);\n      return;\n    }\n\n    if(parallel) {\n      APP_ABORT(\"Error: calculateHSPotentials_Diagonalization not implemented in parallel. \\n\");\n    }\n\n    // 3. vn0 = -0.5* sum_{i,l,sigma} (sum_j <i_sigma,j_sigma|j_sigma,l_sigma> ) c+i_sigma cl_sigma \n    if(myComm->rank()==0) \n    {  \n      if(distribute_Ham) {\n        APP_ABORT(\"Error: calculateHSPotentials_Diagonalization not implemented with distributed hamiltonian. \\n\\n\\n\"); \n      }  \n      if(spinRestricted) \n        assert(vn0.rows() >= NMO);\n      else\n        assert(vn0.rows() >= 2*NMO);\n      assert(vn0.cols() == NMO);\n      std::vector<s4D<ValueType> > v2sym; \n      vn0 = ValueType(0);\n      for(s4Dit it = V2.begin(); it != V2.end(); it++) {\n        // dumb and slow, but easy for now\n        find_equivalent_OneBar_for_integral_list(*it,v2sym); \n        for(int n=0; n<v2sym.size(); n++) {   \n          IndexType i,j,k,l;\n          ValueType V;\n          std::tie (i,j,k,l,V) = v2sym[n];   \n          int sector = getSpinSector(i,j,k,l);\n          // <i,j | j,l> -> v(i,l)  \n          if( (sector==0 || sector==3) && j==k) \n              vn0(i,Index2Col(l)) -= 0.5*V;\n        }\n      }  \n    }         \n\n    int rnk=0;\n#if defined(USE_MPI)\n    rnk = rank();\n#endif\n\n      int NMO2 = NMO*NMO; \n      if(!spinRestricted) NMO2*=2;\n      ValueMatrix Vuv(NMO2);\n      for(int i=0; i<NMO2; i++)\n       for(int j=0; j<NMO2; j++)\n         Vuv(i,j)=ValueType(0.0);\n\n      s4Dit it = V2.begin();\n      std::vector<s4D<ValueType> > vs4D;\n      vs4D.reserve(24);\n      while(it != V2.end()) {\n        find_equivalent_OneBar_for_integral_list(*it++,vs4D);\n        for(int n=0; n<vs4D.size(); n++) {\n\n          IndexType i,j,k,l,ik,lj;\n          ValueType V; \n          std::tie (i,j,k,l,V) = vs4D[n];\n\n          // do I need to check that (i,k) and (j,l) belong to the \n          // same spin sector? This would be a problem with the ME from the beginning  \n          ik = i*NMO+Index2Col(k);\n          lj = l*NMO+Index2Col(j);\n          Vuv(ik,lj) = V;\n        }\n      } \n\n      Timer.reset(\"Generic\");       \n      Timer.start(\"Generic\");       \n\n      ValueMatrix eigVec(NMO2);\n      RealVector eigVal(NMO2);\n      if(!DenseMatrixOperators::symEigenSysAll(NMO2,Vuv.data(),NMO2,eigVal.data(),eigVec.data(),NMO2) ) {\n        app_error()<<\"Problems with eigenvalue/eigenstd::vector calculation in calculateHSPotentials_Diagonalization.\\n\";\n        APP_ABORT(\"Problems with eigenvalue/eigenstd::vector calculation in calculateHSPotentials_Diagonalization.\\n\");\n      }\n\n      Timer.stop(\"Generic\");       \n      if(rnk==0) app_log()<<\" -- Time to solve eigenvalue problem: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n      if(printEig) { \n       app_log()<<\"Eigenvalues of Hamiltonian factorization: \\n\"; \n       for(int i=0; i<NMO2; i++) \n        if(std::abs(eigVal[i]) > std::abs(cutoff_cholesky)) \n         app_log()<<i <<\" \" <<eigVal[i] <<\"\\n\";\n       app_log()<<std::endl; \n      }\n        \n      // for dense storage, setting cut to 1e-8 mainly to avoid storing empty vectors\n      // with real integrals\n      if(!sparse) cut = 1e-8; \n      else if(cut < 1e-12) cut=1e-12;\n      int cnt1=0;\n      int cnt2=0;\n      int cntn=0;\n      for(int i=0; i<NMO2; i++) { \n       if(std::abs(eigVal[i]) > std::abs(cutoff_cholesky)) { \n#ifndef QMC_COMPLEX\n         if(eigVal[i] < 0) {\n           app_log()<<\" WARNING: Found negative eigenvalue in REAL build. Ignoring it: \" <<i <<\" \" <<eigVal[i] <<\"\\n\";\n           continue;\n         }\n#endif\n         ValueType eig = std::sqrt( 0.25*dt*eigVal[i] );\n         int cnt3=0;\n         for(int j=0; j<NMO; j++) \n           for(int k=0; k<NMO; k++) { \n             IndexType jk = j*NMO+k; \n             IndexType kj = k*NMO+j; \n             ValueType V = eig*(eigVec(jk,i) + myconj(eigVec(kj,i)));\n             if(std::abs(V) > cut) cnt3++;\n             if(!spinRestricted) {\n               V = eig*(eigVec(NMO*NMO+jk,i) + myconj(eigVec(NMO+NMO+kj,i)));\n               if(std::abs(V) > cut) cnt3++;\n             }\n           }\n         if(cnt3 > 0) {\n           cnt1++;\n           cnt2 += cnt3;\n         }\n#if defined(QMC_COMPLEX)\n         cnt3=0;\n         for(int j=0; j<NMO; j++) \n          for(int k=0; k<NMO; k++) { \n            IndexType jk = j*NMO+k;\n            IndexType kj = k*NMO+j;\n            ValueType V = eig*(eigVec(jk,i) - myconj(eigVec(kj,i)));\n            if(std::abs(V) > cut) cnt3++;\n            if(!spinRestricted) {\n              V = eig*(eigVec(NMO*NMO+jk,i) - myconj(eigVec(NMO+NMO+kj,i)));\n              if(std::abs(V) > cut) cnt3++;\n            }\n          }\n         if(cnt3 > 0) {\n           cntn++;\n           cnt1++;\n           cnt2 += cnt3;\n         } \n#endif\n        }\n      } \n\n      if(sparse) {\n        Spvn.setDims(NMO2,cnt1);\n        Spvn.allocate_serial(cnt2);\n      } else {\n        Dvn.allocate_serial(NMO2*cnt1);\n      }\n\n#if defined(QMC_COMPLEX)\n      if(cntn>0) \n        APP_ABORT(\"Found real Cholesky vectors with real integrals. This is not allowed with dense cholesky vectors. Run with sparse vectors or compile with complex integrals. \\n\\n\\n\");\n#endif \n \n      int ncols=cnt1;\n      cnt1=0;\n      cntn=0;\n      for(int i=0; i<NMO2; i++) {\n       if(std::abs(eigVal[i]) > std::abs(cutoff_cholesky)) {\n#ifndef QMC_COMPLEX\n         if(eigVal[i] < 0) continue; \n#endif\n         ValueType eig = std::sqrt( 0.25*dt*eigVal[i] );\n         int cnt3=0;\n         for(int j=0; j<NMO; j++)\n          for(int k=0; k<NMO; k++) {\n            IndexType jk = j*NMO+k;\n            IndexType kj = k*NMO+j;\n            ValueType V = eig*(eigVec(jk,i) + myconj(eigVec(kj,i)));\n            if(std::abs(V) > cut) {\n              cnt3++;\n              //V*=isqrtdt;\n              if(sparse) Spvn.add(jk,cnt1,static_cast<SPValueType>(V));\n              else Dvn[jk*ncols+cnt1]=static_cast<SPValueType>(V);\n            }\n            if(!spinRestricted) {\n              V = eig*(eigVec(NMO*NMO+jk,i) + myconj(eigVec(NMO*NMO+kj,i)));\n              if(std::abs(V) > cut) {\n                cnt3++;\n                //V*=isqrtdt;\n                if(sparse) Spvn.add(NMO*NMO+jk,cnt1,static_cast<SPValueType>(V));\n                else Dvn[(jk+NMO*NMO)*ncols+cnt1]=static_cast<SPValueType>(V);\n              }\n            }\n          }\n         if(cnt3 > 0) {\n           cnt1++; \n         }\n#if defined(QMC_COMPLEX)\n         eig = ComplexType(0.0,1.0)*std::sqrt( 0.25*dt*eigVal[i] );\n         cnt3=0;\n         for(int j=0; j<NMO; j++)\n          for(int k=0; k<NMO; k++) {\n            IndexType jk = j*NMO+k;\n            IndexType kj = k*NMO+j;\n            ValueType V = eig*(eigVec(jk,i) - myconj(eigVec(kj,i)));\n            if(std::abs(V) > cut) {\n              cnt3++;\n              //V*=sqrtdt;\n              if(sparse) Spvn.add(jk,cnt1,static_cast<SPValueType>(V));\n              else Dvn[jk*ncols+cnt1]=static_cast<SPValueType>(V); \n            }\n            if(!spinRestricted) {\n              V = eig*(eigVec(NMO*NMO+jk,i) - myconj(eigVec(NMO*NMO+kj,i)));\n              if(std::abs(V) > cut) {\n                cnt3++;\n                //V*=sqrtdt;\n                if(sparse) Spvn.add(NMO*NMO+jk,cnt1,static_cast<SPValueType>(V));\n                else Dvn[(jk+NMO*NMO)*ncols+cnt1]=static_cast<SPValueType>(V); \n              }\n            }\n          }\n         if(cnt3 > 0) {\n           cnt1++; \n           cntn++;\n         }\n#endif\n       }\n      }\n\n      app_log()<<\"Number of positive and negative Cholesky std::vectors: \" <<cnt1-cntn <<\" \" <<cntn <<std::endl; \n\n      app_log()<<\"Number of HS potentials: \" <<ncols <<std::endl;\n      if(sparse) {\n        app_log()<<\"Number of terms in sparse representation of HS potentials: \" <<Spvn.size() <<std::endl;\n        app_log()<<\"Compressing Spvn. \\n\";\n        Spvn.compress();\n        app_log()<<\"Done Compressing Spvn. \\n\";\n     }\n\n     if(test_breakup && sparse) {\n\n      if(rnk==0) app_log()<<\" -- Testing Hamiltonian factorization. \\n\";\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      int* cols = Spvn.column_data();\n      int* rows = Spvn.row_data();\n      int* indx = Spvn.row_index();\n      SPValueType* vals = Spvn.values(); \n\n      SPComplexMatrix v2prod(NMO2);\n      for(int i=0; i<NMO2; i++) \n       for(int j=0; j<NMO2; j++) \n        v2prod(i,j) = SparseMatrixOperators::product_SpVSpV<SPValueType>(indx[i+1]-indx[i],cols+indx[i],vals+indx[i],indx[j+1]-indx[j],cols+indx[j],vals+indx[j]);   \n\n      RealType s=0.0;\n      RealType max=0.0;\n      for(IndexType i=0; i<2*NMO; i++)\n       for(IndexType j=0; j<2*NMO; j++)\n        for(IndexType k=0; k<2*NMO; k++)\n         for(IndexType l=0; l<2*NMO; l++) {\n           if(spinRestricted) {\n            if((i>=NMO || j>=NMO || k>=NMO || l>=NMO ))\n             continue;\n           } else {\n            if(!goodSpinSector(i,j,k,l,NMO))\n             continue;\n           }\n           ComplexType v2 = dt*H(i,j,k,l);\n           ComplexType v2c = static_cast<ComplexType>(v2prod( i*NMO+Index2Col(k) , j*NMO+Index2Col(l)));\n           s+=std::abs(v2-v2c);\n           if( max < std::abs(v2-v2c) ) max = std::abs(v2-v2c);\n           if( std::abs(v2-v2c) > 10*cutoff_cholesky ) {\n             app_error()<<\" Problems with H2 decomposition, i,j,k,l,H2,H2c: \"\n                       <<i <<\" \"\n                       <<j <<\" \"\n                       <<k <<\" \"\n                       <<l <<\" \"\n                       <<v2 <<\" \"\n                       <<v2c <<std::endl;\n           }\n         }\n      double scl = spinRestricted?(1.0):(4.0);\n      app_log()<<\"\\n ********************************************\\n Average error due to truncated eigenvalue factorization (in units of cutoff), max error : \" <<s/cutoff_cholesky/NMO/NMO/NMO/NMO/scl <<\" \" <<max <<\" \\n ********************************************\\n\"<<std::endl;\n\n       Timer.stop(\"Generic\");\n       if(rnk==0) app_log()<<\" -- Time to test eigenvalue factorization: \" <<Timer.average(\"Generic\") <<\"\\n\";\n     }\n\n\n\n  }\n\n  void SparseGeneralHamiltonian::calculateHSPotentials_FactorizedHam(RealType cut, RealType dt, ComplexMatrix& vn0, SPValueSMSpMat& Spvn, SPValueSMVector& Dvn, afqmc::TaskGroup& TGprop, std::vector<int>& nvec_per_node, bool sparse, bool parallel)\n  {\n\n    if(skip_V2)\n      APP_ABORT(\"Error: Calling SparseGeneralHamiltonian routines with skip_V2=yes. \\n\\n\\n\");\n\n    if(distribute_Ham) {\n      APP_ABORT(\"Error: calculateHSPotentials_FactorizedHam not implemented with distributed Hamiltonian. \\n\");\n    }\n\n    assert(vn0.rows() >= NMO);\n    assert(vn0.cols() == NMO);\n    vn0 = ValueType(0);\n    for(int i=0; i<NMO; i++)\n     for(int l=i; l<NMO; l++) {\n       ValueType vl = ValueType(0);\n       for(int j=0; j<NMO; j++)\n         vl += H(i,j,j,l);\n       vn0(i,l) -= 0.5*vl;\n       if(i!=l) vn0(l,i) -= 0.5*myconj(vl);\n       if(!spinRestricted) {\n         vl=ValueType(0);\n         for(int j=NMO; j<2*NMO; j++)\n           vl += H(i+NMO,j,j,l+NMO);\n         vn0(i+NMO,Index2Col(l+NMO)) -= 0.5*vl;\n         if(i!=l) vn0(l+NMO,Index2Col(l+NMO)) -= 0.5*myconj(vl);\n       }\n     }\n\n    /********************************************************************\n    *  You get 2 potentials per Cholesky std::vector   \n    *\n    *    vn(+-)_{i,k} = sum_n 0.5*( L^n_{i,k} +- conj(L^n_{k,i}) )            \n    ********************************************************************/\n\n    ValueType sqrtdt = std::sqrt(dt)*0.5;\n    int NMO2 = NMO*NMO;\n    if(!spinRestricted) NMO2*=2; \n\n    int n3Vect = V2_fact.cols();\n    if(parallel) MPI_Barrier(TGprop.getNodeCommLocal()); \n\n    int ncores = TG.getTotalCores(), coreid = TG.getCoreID();\n    if(!parallel) {\n      ncores=1;\n      coreid=0;\n    }\n\n    // transpose V2_fact here and again at the end\n    Timer.reset(\"Generic\");\n    Timer.start(\"Generic\");\n    if(parallel) V2_fact.transpose(TGprop.getNodeCommLocal());\n    else if(head_of_nodes) V2_fact.transpose(); \n    Timer.stop(\"Generic\");\n    app_log()<<\" Time to transpose V2_fact inside calculateHSPotentials_FactorizedHam(): \" <<Timer.average(\"Generic\") <<std::endl;\n\n    if(parallel) MPI_Barrier(TGprop.getNodeCommLocal()); \n\n    int* cols = V2_fact.column_data();\n    int* rows = V2_fact.row_data();\n    int* indx = V2_fact.row_index();\n    ValueType* vals = V2_fact.values();\n    ValueMatrix Ln;\n\n    Ln.resize((spinRestricted?(NMO):(2*NMO)) ,NMO);  \n\n    std::vector<int> cnt_per_vec(2*n3Vect);\n    int nnodes = TGprop.getNNodesPerTG();\n    int cv0=0,cvN=2*n3Vect;\n    std::vector<int> sets;\n    std::vector<int> sz_per_node(nnodes);\n    int node_number = TGprop.getLocalNodeNumber();\n    int rk=0,npr=1;\n    if(parallel) {\n      npr = myComm->size();\n      rk = myComm->rank();\n    }\n\n    if(!sparse) cut=1e-8;\n    else if(cut < 1e-12) cut=1e-12;\n    int cnt=0;\n    int cntn=0;\n    // count terms and distribute std::vectors \n    // generate sparse version\n    for(int n=0; n<n3Vect; n++) { \n      if(n%npr != rk) continue;\n      int np=0, nm=0;\n      Ln = ValueType(0);\n      for(int p=indx[n]; p<indx[n+1]; p++) {\n        int i = cols[p]/NMO;\n        int k = cols[p]%NMO;\n        Ln(i,k) = vals[p];\n      }\n      // if hamiltonian is distributed, there needs to be communication here\n      for(IndexType i=0; i<NMO; i++) \n       for(IndexType k=0; k<NMO; k++) { \n         // v+\n         if(std::abs( (Ln(i,k) + myconj(Ln(k,i))) ) > cut) \n           np++;\n         // v-\n         if(std::abs( (Ln(i,k) - myconj(Ln(k,i))) ) > cut)  \n           nm++;\n         if(!spinRestricted) {\n           if(std::abs( (Ln(i+NMO,k) + myconj(Ln(k+NMO,i))) ) > cut) \n             np++;\n           if(std::abs( (Ln(i+NMO,k) - myconj(Ln(k+NMO,i))) ) > cut) \n             nm++;\n         }\n       }\n      cnt_per_vec[2*n] = np;\n      cnt_per_vec[2*n+1] = nm;\n      if(nm>0) cntn++;\n    }\n\n    if(parallel) {\n      myComm->allreduce(cnt_per_vec);\n      int nvec = std::count_if(cnt_per_vec.begin(),cnt_per_vec.end(),\n               [] (int i) { return i>0; } );\n      if(sparse) Spvn.setDims(NMO2,nvec); \n\n      nvec_per_node.resize(nnodes);\n      if(nnodes==1) {\n        cv0=0;\n        cvN=2*n3Vect;\n        cnt = std::accumulate(cnt_per_vec.begin(),cnt_per_vec.end(),0);\n        if(sparse) Spvn.reserve(cnt);\n        else {\n          Dvn.allocate(NMO2*nvec);\n          Dvn.resize(NMO2*nvec);\n        }\n        nvec_per_node[0] = nvec;\n        sz_per_node[0] = cnt;\n      } else {\n        sets.resize(nnodes+1);\n        if(rank()==0) {\n          // partition std::vectors over nodes in TG\n          std::vector<int> blocks(2*n3Vect+1);\n          blocks[0]=0;\n          cnt=0;\n          for(int i=0; i<2*n3Vect; i++) {\n            if(sparse) cnt+=cnt_per_vec[i];\n            else cnt+= (cnt_per_vec[i]>0)?1:0;\n            blocks[i+1] = cnt;\n          }\n          balance_partition_ordered_set(2*n3Vect,blocks.data(),sets);\n          myComm->bcast(sets);\n          cv0 = sets[node_number];\n          cvN = sets[node_number+1];\n          app_log()<<\" Partitioning of Cholesky Vectors: \";\n          for(int i=0; i<=nnodes; i++)\n            app_log()<<sets[i] <<\" \";\n          app_log()<<std::endl;\n          app_log()<<\" Number of terms in each partitioning: \";\n          for(int i=0; i<nnodes; i++)\n            app_log()<<accumulate(cnt_per_vec.begin()+sets[i],cnt_per_vec.begin()+sets[i+1],0) <<\" \";\n          app_log()<<std::endl;\n          // since many std::vectors might have zero size and will be discarded below,\n          // count only non-zero            \n          for(int i=0; i<nnodes; i++)\n            nvec_per_node[i] = std::count_if(cnt_per_vec.begin()+sets[i],cnt_per_vec.begin()+sets[i+1],\n               [] (int i) { return i>0; } );\n          for(int i=0; i<nnodes; i++)\n            sz_per_node[i] = std::accumulate(cnt_per_vec.begin()+sets[i],cnt_per_vec.begin()+sets[i+1],0);\n        } else if(head_of_nodes) {\n          myComm->bcast(sets);\n          cv0 = sets[node_number];\n          cvN = sets[node_number+1];\n        } \n        myComm->bcast(nvec_per_node);\n        myComm->bcast(sz_per_node);\n        if(sparse) Spvn.reserve(sz_per_node[node_number]);\n        else {\n          Dvn.allocate(NMO2*nvec_per_node[node_number]);\n          Dvn.resize(NMO2*nvec_per_node[node_number]);\n        }\n      }\n    } else {\n      int nvec=0;\n      cnt=0;\n      for (int i : cnt_per_vec )\n        if(i>0) {\n          cnt+=i;\n          nvec++;\n        }\n      nvec_per_node[0] = nvec;\n      if(sparse) {\n        Spvn.setDims(NMO2,nvec);\n        Spvn.allocate_serial(cnt);\n      } else {\n        Dvn.allocate_serial(NMO2*nvec);\n        Dvn.resize_serial(NMO2*nvec);\n      }\n    }            \n\n    if(parallel) MPI_Barrier(TGprop.getNodeCommLocal()); \n    int ncols = nvec_per_node[node_number];\n\n#ifndef QMC_COMPLEX\n    if(cntn>0)\n      APP_ABORT(\"Found real Cholesky vectors with real integrals. This is not allowed with dense cholesky vectors. Run with sparse vectors or compile with complex integrals. \\n\\n\\n\");\n#endif\n\n    int nmax=1000000;\n    std::vector<std::tuple<SPValueSMSpMat::intType,SPValueSMSpMat::intType,SPValueType>> vikn;\n    if(sparse)\n      vikn.reserve(nmax);\n\n// also no need to do this serially, FIX FIX FIX\n    cnt=std::accumulate(nvec_per_node.begin(),nvec_per_node.begin()+node_number,0);\n    for(int n=0; n<n3Vect; n++) { \n       if( cnt_per_vec[2*n]==0 && cnt_per_vec[2*n+1]==0 ) continue;\n       if( !(2*n>=cv0 && 2*n<cvN) && !((2*n+1)>=cv0 && (2*n+1)<cvN)  ) continue;\n       if( n%ncores != coreid ) { \n         if(2*n>=cv0 && 2*n<cvN && cnt_per_vec[2*n]>0) cnt++;\n         if((2*n+1)>=cv0 && (2*n+1)<cvN && cnt_per_vec[2*n+1]>0) cnt++;\n         continue;  \n       }\n       int np=0;\n       Ln = ValueType(0);\n       for(int p=indx[n]; p<indx[n+1]; p++) {\n         int i = cols[p]/NMO;\n         int k = cols[p]%NMO;\n         Ln(i,k) = vals[p];\n       }\n\n       if(2*n>=cv0 && 2*n<cvN && cnt_per_vec[2*n]>0) {\n         // v+\n         for(IndexType i=0; i<NMO; i++)\n          for(IndexType k=0; k<NMO; k++) { \n           ValueType V = (Ln(i,k) + myconj(Ln(k,i))); \n           if(std::abs(V) > cut) { \n             V*=sqrtdt;\n             if(sparse) { //Spvn.add(i*NMO+k,cnt,static_cast<SPValueType>(V));\n               vikn.push_back(std::make_tuple(i*NMO+k,cnt,static_cast<SPValueType>(V)));\n               if(vikn.size()==nmax) {  \n                 Spvn.add(vikn,true);\n                 vikn.clear(); \n               }  \n             } else Dvn[(i*NMO+k)*ncols+cnt]=static_cast<SPValueType>(V);\n             ++np;\n           } \n           if(!spinRestricted) {\n             V = (Ln(i+NMO,k) + myconj(Ln(k+NMO,i)));\n             if(std::abs(V) > cut) {\n               V*=sqrtdt;\n               if(sparse) { // Spvn.add(NMO*NMO+i*NMO+k,cnt,static_cast<SPValueType>(V));\n                 vikn.push_back(std::make_tuple(NMO*NMO+i*NMO+k,cnt,static_cast<SPValueType>(V)));\n                 if(vikn.size()==nmax) {  \n                   Spvn.add(vikn,true);\n                   vikn.clear(); \n                 }  \n               } else Dvn[(i*NMO+k+NMO*NMO)*ncols+cnt]=static_cast<SPValueType>(V);\n               ++np;\n             }\n           }\n         }\n         ++cnt;\n         if(np==0)\n           APP_ABORT(\"Error: This should not happen. Found empty cholesky std::vector. \\n\");\n       }\n       if((2*n+1)>=cv0 && (2*n+1)<cvN && cnt_per_vec[2*n+1]>0) {\n#if defined(QMC_COMPLEX) \n         np=0;\n         // v-\n         for(IndexType i=0; i<NMO; i++)\n          for(IndexType k=0; k<NMO; k++) {\n           ComplexType V = (Ln(i,k) - myconj(Ln(k,i))); \n           if(std::abs(V) > cut) {\n             V*=ComplexType(0.0,1.0)*sqrtdt;\n             if(sparse) { // Spvn.add(i*NMO+k,cnt,static_cast<SPValueType>(V));\n               vikn.push_back(std::make_tuple(i*NMO+k,cnt,static_cast<SPValueType>(V)));\n               if(vikn.size()==nmax) {  \n                 Spvn.add(vikn,true);\n                 vikn.clear(); \n               }  \n             } else Dvn[(i*NMO+k)*ncols+cnt]=static_cast<SPValueType>(V);\n             ++np;\n           }\n           if(!spinRestricted) {\n             V = (Ln(i+NMO,k) - myconj(Ln(k+NMO,i)));\n             if(std::abs(V) > cut) {\n               V*=ComplexType(0.0,1.0)*sqrtdt;\n               if(sparse) { //Spvn.add(NMO*NMO+i*NMO+k,cnt,static_cast<SPValueType>(V));\n                 vikn.push_back(std::make_tuple(NMO*NMO+i*NMO+k,cnt,static_cast<SPValueType>(V)));\n                 if(vikn.size()==nmax) {\n                   Spvn.add(vikn,true);\n                   vikn.clear();\n                 }\n               } else Dvn[(i*NMO+k+NMO*NMO)*ncols+cnt]=static_cast<SPValueType>(V);\n               ++np;\n             }\n           }\n         }\n         ++cnt;\n         if(np==0)\n           APP_ABORT(\"Error: This should not happen. Found empty cholesky std::vector. \\n\");\n#else\n         APP_ABORT(\"Error: THIS SHOULD NOT HAPPEN. Found complex cholesky vector in real build. \\n\\n\\n\");\n#endif\n       }\n    }\n    if(vikn.size()>0) {  \n      Spvn.add(vikn,true);\n      vikn.clear(); \n    }  \n\n    if(rank()==0 && nnodes>1 && parallel) {\n      app_log()<<\" Partition of Cholesky Vectors: 0 \";\n      cnt=0;\n      for(int i=0; i<nnodes; i++) {\n        cnt+=nvec_per_node[i];\n        app_log()<<cnt <<\" \";\n      }\n      app_log()<<std::endl;\n      if(sparse) {\n        app_log()<<\" Number of terms in Spvn per node in TG: \";\n        for(int i : sz_per_node ) app_log()<<i <<\" \";\n        app_log()<<std::endl;\n      }\n    }\n\n    app_log()<<\"Number of HS potentials: \" <<ncols <<std::endl;\n    if(sparse) {\n      app_log()<<\"Number of terms in sparse representation of HS potentials: \" <<Spvn.size() <<std::endl;\n\n      app_log()<<\"Compressing Spvn. \\n\";\n\n      if(parallel) MPI_Barrier(TGprop.getNodeCommLocal()); \n\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n      if(parallel) Spvn.compress(TGprop.getNodeCommLocal());\n      else if(head_of_nodes) Spvn.compress();\n      Timer.stop(\"Generic\");\n      app_log()<<\" Time to compress Spvn in calculateHSPotentials_FactorizedHam(): \" <<Timer.average(\"Generic\") <<std::endl;\n    }\n\n    Timer.reset(\"Generic\");\n    Timer.start(\"Generic\");\n    if(parallel) V2_fact.transpose(TGprop.getNodeCommLocal());\n    else if(head_of_nodes) V2_fact.transpose(); \n    Timer.stop(\"Generic\");\n    app_log()<<\" Time to transpose V2_fact inside calculateHSPotentials_FactorizedHam(): \" <<Timer.average(\"Generic\") <<std::endl;\n\n    if(parallel) MPI_Barrier(TGprop.getNodeCommLocal()); \n\n  }\n\n  void SparseGeneralHamiltonian::calculateHSPotentials(RealType cut, RealType dt, ComplexMatrix& vn0, SPValueSMSpMat& Spvn, SPValueSMVector& Dvn, afqmc::TaskGroup& TGprop, std::vector<int>& nvec_per_node, bool sparse, bool parallel)\n  {\n\n    if(skip_V2)\n      APP_ABORT(\"Error: Calling SparseGeneralHamiltonian routines with skip_V2=yes. \\n\\n\\n\");\n\n    if(factorizedHamiltonian) {\n      calculateHSPotentials_FactorizedHam(cut,dt,vn0,Spvn,Dvn,TGprop,nvec_per_node,sparse,parallel);\n      return;\n    }\n\n    if(distribute_Ham && !parallel) {\n        APP_ABORT(\"Error: Distributed hamiltonian requires parallel Cholesky factorization. \\n\\n\\n\");\n    }\n\n    int rnk=0;\n    rnk = rank();\n    cholesky_residuals.clear();\n    cholesky_residuals.reserve(2*NMO*NMO);\n\n    if(spinRestricted) {\n\n\n      // 0. vn0 = -0.5* sum_{i,l,sigma} (sum_j <i_sigma,j_sigma|j_sigma,l_sigma> ) c+i_sigma cl_sigma \n      assert(vn0.rows() >= NMO);\n      assert(vn0.cols() == NMO);\n      std::vector<s4D<ValueType> > v2sym; \n      vn0 = ValueType(0);\n      {\n        long nt=0,rk=0,npr=1; \n        if(distribute_Ham) {\n          npr = static_cast<long>(TG.getTGSize());\n          rk = static_cast<long>(TG.getTGRank());\n        } else if(parallel) { \n          npr = static_cast<long>(myComm->size());\n          rk = static_cast<long>(myComm->rank());\n        }\n        for(s4Dit it = V2.begin(); it != V2.end(); it++, nt++) {\n          if( nt%npr != rk) continue;\n          // dumb and slow, but easy for now\n          find_equivalent_OneBar_for_integral_list(*it,v2sym); \n          for(int n=0; n<v2sym.size(); n++) {   \n            IndexType i,j,k,l;\n            ValueType V;\n            std::tie (i,j,k,l,V) = v2sym[n];   \n            int sector = getSpinSector(i,j,k,l);\n            // <i,j | j,l> -> v(i,l)  \n            if( (sector==0 || sector==3) && j==k) \n              vn0(i,Index2Col(l)) -= 0.5*V;\n          }\n        }  \n        if(parallel) {\n          // since allreduce(vn0) somehow doesn't work\n          //myComm->allreduce(vn0);\n          std::vector<ComplexType> g(NMO*NMO);\n          std::copy(vn0.begin(),vn0.begin()+NMO*NMO,g.begin());\n          myComm->allreduce(g);\n          std::copy(g.begin(),g.end(),vn0.begin());\n        }\n      }\n             \n\n      /********************************************************************\n      *               Calculate Cholesky decomposition \n      *\n      *   1. The mapping of the 2-el repulsion integrals to a 2-D matrix\n      *      is done as follows:\n      *         V(i,j,k,l) -->  V( i*NMO+k,  l*NMO+j )\n      ********************************************************************/\n\n     Timer.reset(\"Generic\");\n     Timer.start(\"Generic\");\n\n     // used to split (i,k) space over all processors for the construction and storage of cholesky vectors\n     int npr = myComm->size(), rk = myComm->rank(); \n     int ik0=0,ik1=NMO*NMO;\n     std::vector<int> ik_partition;\n     // used for split of (i,k) space over the processors in a TG during the evaluation of H(i,kmax,k,imax) piece\n     // in case the Hamiltonian is distributed\n     int tg_npr = TG.getTGSize(), tg_rk = TG.getTGRank(); \n     int tg_ik0=0,tg_ik1=NMO*NMO;\n     std::vector<int> tgik_partition;\n     std::vector<int> cnts;\n     if(parallel) {\n       FairDivide(NMO*NMO,npr,ik_partition); \n       ik0 = ik_partition[rk];\n       ik1 = ik_partition[rk+1];\n       cnts.resize(npr);\n       for(int i=0; i<npr; i++)\n         cnts[i] = ik_partition[i+1]-ik_partition[i];\n     } else {\n       cnts.resize(1);\n       cnts[0] = ik1-ik0; \n     }\n     if(distribute_Ham) {\n       FairDivide(NMO*NMO,tg_npr,tgik_partition);\n       tg_ik0 = tgik_partition[tg_rk];\n       tg_ik1 = tgik_partition[tg_rk+1];       \n     }\n     int nterms = ik1-ik0; \n     int maxnterms = *std::max_element(cnts.begin(),cnts.end()); \n     if(nterms < 1) {\n       APP_ABORT(\"Error: Too many processors in parallel calculation of HS potential. Try reducing the number of cores, calculating in serial or reading from a file. \\n\\n\\n \");\n     }\n\n     // will store full Cholesky std::vectors now and keep sparse versions only at the end.\n     // want to avoid possible numerical issues from truncation\n     std::vector< std::vector<ValueType> > L;\n     L.reserve(NMO*NMO);\n\n     std::vector<ValueType> Lnmax(NMO*NMO);\n     std::vector<s2D<RealType> > IKLmax(npr); \n     s2D<RealType> mymax;\n     int maxloc=0;\n\n     std::vector<ValueType> Lcomm;\n     if(distribute_Ham) Lcomm.resize(NMO*NMO);\n\n     // to store diagonal elements to avoid search, since they are used often \n     std::vector<ValueType> Duv(nterms);\n     if(distribute_Ham) {\n       std::fill(Lcomm.begin(),Lcomm.end(),ValueType(0));\n       for(IndexType i=0, nt=0; i<NMO; i++) {\n         for(IndexType k=0; k<NMO; k++,nt++) {\n           if(nt<tg_ik0 || nt>=tg_ik1) continue;\n           // <i,k|k,i> \n           if( k<i ) {\n#if defined(QMC_COMPLEX)\n             // <k,i|i,k> \n             if(k>=min_i && k<max_i) Lcomm[nt] = H(k,i,i,k);\n#else\n             // <k,k|i,i> \n             if(k>=min_i && k<max_i) Lcomm[nt] = H(k,k,i,i);\n#endif\n           } else {\n#if defined(QMC_COMPLEX)\n             // <i,k|k,i> \n             if(i>=min_i && i<max_i) Lcomm[nt] = H(i,k,k,i);\n#else\n             // <i,i|k,k> \n             if(i>=min_i && i<max_i) Lcomm[nt] = H(i,i,k,k);\n#endif\n           }\n#if defined(QMC_COMPLEX)\n           if(Lcomm[nt].imag() > 1e-10 || Lcomm[nt].real() < RealType(0)) {\n             app_log()<<\" WARNING: Found negative/complex Duv: \" <<i <<\" \" <<k <<\" \" <<Lcomm[nt] <<std::endl;\n             if(zero_bad_diag_2eints)\n               Lcomm[nt] = ValueType(0);\n           }\n#else\n           if(Lcomm[nt] < ValueType(0)) {\n             app_log()<<\" WARNING: Found negative Duv: \" <<i <<\" \" <<k <<\" \" <<Lcomm[nt] <<std::endl;\n             if(zero_bad_diag_2eints)\n               Lcomm[nt] = ValueType(0);\n           }\n#endif\n         }\n         if(nt>=tg_ik1) break;\n       }\n       myComm->allreduce(Lcomm); \n       std::copy( Lcomm.begin()+ik0, Lcomm.begin()+ik1, Duv.begin() );\n     } else {\n       for(IndexType i=0, nt=0, ik=0; i<NMO; i++) {\n         for(IndexType k=0; k<NMO; k++,nt++) {\n           if(nt<ik0 || nt>=ik1) continue;\n           Duv[ik] = H(i,k,k,i);  \n#ifndef QMC_COMPLEX\n           if(Duv[ik] < ValueType(0)) {\n             app_log()<<\" WARNING: Found negative Duv: \" <<i <<\" \" <<k <<\" \" <<Duv[ik] <<std::endl;  \n             if(zero_bad_diag_2eints) \n               Duv[ik] = ValueType(0);\n           }\n#else\n           if(Duv[ik].imag() > 1e-10 || Duv[ik].real() < RealType(0)) {\n             app_log()<<\" WARNING: Found negative/complex Duv: \" <<i <<\" \" <<k <<\" \" <<Duv[ik] <<std::endl;\n             if(zero_bad_diag_2eints)\n               Duv[ik] = ValueType(0);\n           }\n#endif\n           ik++;\n         }\n         if(nt>=ik1) break;\n       }\n     }\n\n     // D(ik,lj) = H(i,j,k,l) - sum_p Lp(ik) Lp*(lj)\n     // Diagonal:  D(ik,ik) = H(i,k,k,i) - sum_p Lp(ik) Lp*(ik) \n     RealType max=0;\n     IndexType ii=-1,kk=-1;\n     mymax = std::make_tuple(-1,-1,0);\n     for(IndexType i=0, nt=0, ik=0; i<NMO; i++) {\n      for(IndexType k=0; k<NMO; k++,nt++) {\n        if(nt<ik0 || nt>=ik1) continue;\n        if( std::abs(Duv[ik]) > max) {\n          max = std::get<2>(mymax) =std::abs(Duv[ik]);  \n          ii=std::get<0>(mymax)=i;\n          kk=std::get<1>(mymax)=k;\n        } \n        ik++;\n      }\n      if(nt>=ik1) break;\n     }\n     if(ii<0 || kk<0) {\n      app_error()<<\"Problems with Cholesky decomposition. \\n\";\n      APP_ABORT(\"Problems with Cholesky decomposition. \\n\");   \n     }\n\n     if(parallel) {\n       myComm->allgather(reinterpret_cast<char*>(&mymax),reinterpret_cast<char*>(IKLmax.data()),sizeof(s2D<RealType>)); \n       ii=-1;kk=-1;\n       max=0;\n       for(int i=0; i<npr; i++) {\n         if(std::get<2>(IKLmax[i])>max) {\n           ii=std::get<0>(IKLmax[i]);\n           kk=std::get<1>(IKLmax[i]);\n           max=std::get<2>(IKLmax[i]);\n           maxloc=i;\n         } \n       }\n     }\n\n     if(printEig) {\n      app_log()<<\"Residuals of Cholesky factorization at each iteration: \\n\";\n      app_log()<<L.size() <<\" \" <<std::abs(max) <<\"\\n\";\n     }\n\n     Timer.reset(\"Generic1\");\n     Timer.reset(\"Generic2\");\n\n     if(test_2eint && !parallel && !distribute_Ham) {\n\n       /* <ij|kl> <--> M_(ik)_(lj) where M must be positive definite.\n        * --> |M_(ik)_(lj)| <= sqrt( |M_(ik)_(ik)| |M_(lj)_(lj)| )\n        * --> |<ij|kl>| <= sqrt( |<ik|ki>| |<lj|jl| )   \n        *  \n        */\n       for(s4Dit it = V2.begin(); it != V2.end(); it++) {\n         IndexType i,j,k,l;\n         ValueType w1,w2,w3;\n         std::tie (i,j,k,l,w1) = *it;  \n \n         w2 = H(i,k,k,i);\n         w3 = H(l,j,j,l);\n         ValueType w4 = H(j,l,l,j);\n         if( std::abs(w1) > std::sqrt(std::abs(w2*w3)) ) {\n           app_log()<<\" Problems with positive-definiteness: \" \n                    <<i <<\" \" <<j <<\" \" <<k <<\" \" <<l <<\" \" \n                    <<w1 <<\" \" <<w2 <<\" \" <<w3 <<\" \" <<w4 <<std::endl; \n         }\n\n       } \n\n     }\n\n     int cnt_energy_increases=0;\n     RealType max_old;\n     while(max > cutoff_cholesky) {\n\n       Timer.start(\"Generic1\");\n       RealType oneOverMax = 1/std::sqrt(std::abs(max));\n\n       cholesky_residuals.push_back(std::abs(max));\n\n       // calculate new cholesky std::vector based on (ii,kk)\n       L.push_back(std::vector<ValueType>(maxnterms));  \n       std::vector<ValueType>& Ln = L.back();\n       std::vector<ValueType>::iterator it = Ln.begin();\n\n       if(rk==maxloc) {\n         for(int n=0; n<L.size()-1; n++)\n           Lnmax[n] = L[n][ii*NMO+kk-ik0]; \n       }\n       if(parallel && L.size()>1) {\n         myComm->bcast(Lnmax.data(),L.size()-1,maxloc,myComm->getMPI()); \n       }\n\n       if(distribute_Ham) {\n         std::fill(Lcomm.begin(),Lcomm.end(),ValueType(0));\n         s4D<ValueType> s;\n         for(IndexType i=0, nt=0; i<NMO; i++) {\n           for(IndexType k=0; k<NMO; k++, nt++) {\n             if(nt<tg_ik0 || nt>=tg_ik1) continue;\n             s = std::make_tuple(i,kk,k,ii,ValueType(0));\n             bool cjgt = find_smallest_permutation(s);\n             if( std::get<0>(s) >= min_i && std::get<0>(s) < max_i ) {\n               s4Dit it_ = std::lower_bound( V2.begin(), V2.end(), s, mySort);\n               if (it_ != V2.end() &&  std::get<0>(*it_)==std::get<0>(s) &&  std::get<1>(*it_)==std::get<1>(s) && std::get<2>(*it_)==std::get<2>(s) && std::get<3>(*it_)==std::get<3>(s) ) {\n#if defined(QMC_COMPLEX)\n                 if(cjgt)\n                   Lcomm[nt] = std::conj(std::get<4>(*it_));\n                 else\n#endif\n                   Lcomm[nt] = std::get<4>(*it_);\n               }\n             } \n           }\n           if(nt>=tg_ik1) break;\n         }\n         myComm->allreduce(Lcomm);\n         std::copy( Lcomm.begin()+ik0, Lcomm.begin()+ik1, it );         \n       } else { \n         for(IndexType i=0, nt=0; i<NMO; i++) {\n           for(IndexType k=0; k<NMO; k++, nt++) {\n             if(nt<ik0 || nt>=ik1) continue;\n             *(it++) = H(i,kk,k,ii);\n           }\n           if(nt>=ik1) break;\n         }\n       }\n\n       for(int n=0; n<L.size()-1; n++) {\n         //ValueType scl = myconj(L[n][ii*NMO+kk]); \n         ValueType scl = myconj(Lnmax[n]); \n         std::vector<ValueType>::iterator it1 = L[n].begin();\n         it = Ln.begin();\n         for(IndexType i=0; i<nterms; i++) \n           *(it++) -= *(it1++)*scl; \n       }\n       it = Ln.begin();\n       for(IndexType i=0; i<nterms; i++)\n         *(it++) *= oneOverMax;\n       Timer.stop(\"Generic1\");\n       \n       Timer.start(\"Generic2\");\n       max_old = max;\n       IndexType ii0=ii,kk0=kk;\n       max=0;\n       ii=-1;\n       kk=-1;\n       mymax = std::make_tuple(-1,-1,0);\n       for(IndexType i=0,ik=0,nt=0; i<NMO; i++) {\n        for(IndexType k=0; k<NMO; k++,nt++) {\n         if(nt<ik0 || nt>=ik1) continue;\n         Duv[ik] -= Ln[ik]*myconj(Ln[ik]);  \n         if(zero_bad_diag_2eints) {\n           if( std::abs(Duv[ik]) > max && toComplex(Duv[ik]).real() > 0) {\n             max = std::get<2>(mymax) =std::abs(Duv[ik]);  \n             ii=std::get<0>(mymax)=i;\n             kk=std::get<1>(mymax)=k;\n           }\n         } else {\n           if( std::abs(Duv[ik]) > max) {\n             max = std::get<2>(mymax) =std::abs(Duv[ik]);  \n             ii=std::get<0>(mymax)=i;\n             kk=std::get<1>(mymax)=k;\n           }\n         }\n         ik++;\n        }\n        if(nt>=ik1) break;\n       }\n       if(parallel) {\n         myComm->allgather(reinterpret_cast<char*>(&mymax),reinterpret_cast<char*>(IKLmax.data()),sizeof(s2D<RealType>)); \n         ii=-1;kk=-1;\n         max=0;\n         for(int i=0; i<npr; i++) {\n           if(std::get<2>(IKLmax[i])>max) {\n             ii=std::get<0>(IKLmax[i]);\n             kk=std::get<1>(IKLmax[i]);\n             max=std::get<2>(IKLmax[i]);\n             maxloc=i;\n           }\n         }\n       }\n       if(ii<0 || kk<0) {\n        app_error()<<\"Problems with Cholesky decomposition. \\n\";\n        APP_ABORT(\"Problems with Cholesky decomposition. \\n\");\n       }\n       Timer.stop(\"Generic2\");\n       if(myComm->rank()==0 && printEig)\n         app_log()<<L.size() <<\" \" <<ii <<\" \" <<kk <<\" \" <<std::abs(max) <<\" \" <<Timer.total(\"Generic1\") <<\" \" <<Timer.total(\"Generic2\")   <<\"\\n\";\n       if(max > max_old) {\n         cnt_energy_increases++;\n         if(cnt_energy_increases == 3) { \n           app_error()<<\"ERROR: Problems with convergence of Cholesky decomposition. \\n\" \n             <<\"Number of std::vectors found so far: \" <<L.size() <<\"\\n\"\n             <<\"Current value of truncation error: \" <<max_old <<\" \" <<max <<std::endl;  \n             APP_ABORT(\"Problems with convergence of Cholesky decomposition.\\n\"); \n         }\n       }\n     }\n     app_log()<<\" Found: \" <<L.size() <<\" Cholesky std::vectors with a cutoff of: \" <<cutoff_cholesky <<\"\\n\";   \n\n     Timer.stop(\"Generic\");\n     app_log()<<\" -- Time to generate Cholesky factorization: \" <<Timer.average(\"Generic\") <<std::endl;\n\n     if(test_breakup && !parallel && !distribute_Ham) {\n\n      app_log()<<\" -- Testing Hamiltonian factorization. \\n\";\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      RealType s=0.0;\n      RealType max=0.0;\n      for(IndexType i=0,nt=0,ik=0; i<NMO; i++)\n       for(IndexType j=0; j<NMO; j++) \n        for(IndexType k=0; k<NMO; k++)\n         for(IndexType l=0; l<NMO; l++,nt++) {     \n           if(nt<ik0||nt>=ik1) continue;\n           ValueType v2 = H(i,j,k,l);\n           ValueType v2c = 0.0;\n           // is it L*L or LL*???\n           for(int n=0; n<L.size(); n++) v2c += L[n][i*NMO+k]*myconj(L[n][l*NMO+j]);\n           s+=std::abs(v2-v2c);\n           if( max < std::abs(v2-v2c) ) max = std::abs(v2-v2c); \n           if( std::abs(v2-v2c) > 10*cutoff_cholesky ) {\n             app_error()<<\" Problems with Cholesky decomposition, i,j,k,l,H2,H2c: \"\n                       <<i <<\" \"\n                       <<j <<\" \"\n                       <<k <<\" \"\n                       <<l <<\" \"\n                       <<v2 <<\" \"\n                       <<v2c <<std::endl;\n           }\n           ik++;\n         }\n      app_log()<<\"\\n ********************************************\\n Average error due to truncated Cholesky factorization (in units of cutoff), maximum error   : \" <<s/cutoff_cholesky/NMO/NMO/NMO/NMO <<\"  \" <<max <<\" \\n********************************************\\n\"<<std::endl; \n\n       Timer.stop(\"Generic\");\n       if(rnk==0) app_log()<<\" -- Time to test Cholesky factorization: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n     }\n\n      /********************************************************************\n      *  You get 2 potentials per Cholesky std::vector   \n      *\n      *    vn(+-)_{i,k} = sum_n 0.5*( L^n_{i,k} +- conj(L^n_{k,i}) )            \n      ********************************************************************/\n\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      ValueType sqrtdt = std::sqrt(dt)*0.5;\n\n      std::vector<int> cnt_per_vec(2*L.size());\n      std::vector<int> ik2padded;\n      if(parallel) { \n        Lcomm.resize(npr*maxnterms); \n        ik2padded.resize(npr*maxnterms);\n        for(int i=0; i<ik2padded.size(); i++) ik2padded[i]=i;\n        // to make it independent of behavior of FairDivide\n        const int tag = npr*maxnterms+10000;\n        std::vector<int>::iterator it = ik2padded.begin(), itc = cnts.begin();\n        for(; itc!=cnts.end(); itc++, it+=maxnterms) \n          std::fill(it+(*itc), it+maxnterms,tag); \n        std::stable_partition( ik2padded.begin(), ik2padded.end(), \n            [tag] (const int& i) { return i<tag; }\n              ); \n      } else {\n        ik2padded.resize(NMO*NMO);\n        for(int i=0; i<NMO*NMO; i++) ik2padded[i]=i;\n      }  \n\n      Timer.reset(\"Generic2\");\n      Timer.start(\"Generic2\");\n      if(!sparse) cut=1e-8;\n      else if(cut < 1e-12) cut=1e-12;\n      int cnt=0, cntn=0;\n      // generate sparse version\n      int nvecs=L.size();\n      for(int n=0; n<L.size(); n++) { \n        ValueType* Ls; \n        if(parallel) {\n#if defined(QMC_COMPLEX)\n          MPI_Gather(L[n].data(),2*maxnterms,MPI_DOUBLE,Lcomm.data(),2*maxnterms,MPI_DOUBLE,0,myComm->getMPI());\n#else\n          MPI_Gather(L[n].data(),maxnterms,MPI_DOUBLE,Lcomm.data(),maxnterms,MPI_DOUBLE,0,myComm->getMPI());\n#endif\n          if(rank()==0) Ls = Lcomm.data();\n        } else {\n          Ls = L[n].data();\n        } \n        if(rank()==0) {\n          int np=0, nm=0;\n          for(IndexType i=0; i<NMO; i++) \n           for(IndexType k=0; k<NMO; k++) { \n             // v+\n             if(std::abs( (Ls[ik2padded[i*NMO+k]] + myconj(Ls[ik2padded[k*NMO+i]])) ) > cut) \n               np++;\n             // v-\n             if(std::abs( (Ls[ik2padded[i*NMO+k]] - myconj(Ls[ik2padded[k*NMO+i]])) ) > cut)  \n               nm++;\n           }\n          cnt_per_vec[2*n] = np;\n          cnt_per_vec[2*n+1] = nm;\n          if(nm>0) cntn++;\n        }\n        if(n>0 && (n%100==0))\n          myComm->barrier();\n      } \n\n      int nnodes = TGprop.getNNodesPerTG();\n      int cv0=0,cvN=2*L.size();\n      std::vector<int> sets;\n      std::vector<int> sz_per_node(nnodes);\n      int node_number = TGprop.getLocalNodeNumber();\n      if(parallel) {\n        myComm->bcast(cnt_per_vec);\n        int nvec = std::count_if(cnt_per_vec.begin(),cnt_per_vec.end(),\n                 [] (int i) { return i>0; } ); \n        if(sparse) Spvn.setDims(NMO*NMO,nvec);\n\n        nvec_per_node.resize(nnodes);\n        if(nnodes==1) {\n          cv0=0;\n          cvN=2*L.size();\n          cnt = std::accumulate(cnt_per_vec.begin(),cnt_per_vec.end(),0);\n          if(sparse) Spvn.reserve(cnt);\n          else {\n            Dvn.allocate(NMO*NMO*nvec);\n            Dvn.resize(NMO*NMO*nvec);\n          }\n          nvec_per_node[0] = nvec; \n          sz_per_node[0] = cnt;\n        } else {\n          sets.resize(nnodes+1);\n          if(rank()==0) {\n            // partition std::vectors over nodes in TG\n            std::vector<int> blocks(2*L.size()+1); \n            blocks[0]=0;\n            cnt=0;\n            for(int i=0; i<2*L.size(); i++) {\n              if(sparse) cnt+=cnt_per_vec[i];\n              else cnt+= (cnt_per_vec[i]>0)?1:0;\n              blocks[i+1] = cnt; \n            }\n            balance_partition_ordered_set(2*L.size(),blocks.data(),sets);\n            myComm->bcast(sets.data(),sets.size(),MPI_COMM_HEAD_OF_NODES);\n            cv0 = sets[node_number];\n            cvN = sets[node_number+1];\n          \n            // since many std::vectors might have zero size and will be discarded below,\n            // count only non-zero\n            for(int i=0; i<nnodes; i++) \n              nvec_per_node[i] = std::count_if(cnt_per_vec.begin()+sets[i],cnt_per_vec.begin()+sets[i+1],\n                 [] (int i) { return i>0; } );      \n            for(int i=0; i<nnodes; i++) \n              sz_per_node[i] = std::accumulate(cnt_per_vec.begin()+sets[i],cnt_per_vec.begin()+sets[i+1],0);\n          } else if(head_of_nodes) {\n            myComm->bcast(sets.data(),sets.size(),MPI_COMM_HEAD_OF_NODES);\n            cv0 = sets[node_number];\n            cvN = sets[node_number+1];\n          }\n          myComm->bcast(nvec_per_node);  \n          myComm->bcast(sz_per_node);  \n          if(sparse) Spvn.reserve(sz_per_node[node_number]); \n          else {\n            Dvn.allocate(NMO*NMO*nvec_per_node[node_number]);\n            Dvn.resize(NMO*NMO*nvec_per_node[node_number]);\n          }\n        }\n      } else {\n        int nvec=0;\n        cnt=0; \n        for (int i : cnt_per_vec ) \n          if(i>0) { \n            cnt+=i;\n            nvec++;\n          } \n        nvec_per_node[0] = nvec;\n        if(sparse) {\n          Spvn.setDims(NMO*NMO,nvec);\n          Spvn.allocate_serial(cnt);\n        } else {\n          Dvn.allocate_serial(NMO*NMO*nvec);\n          Dvn.resize_serial(NMO*NMO*nvec);\n        }\n      } \n\n      int ncols = nvec_per_node[node_number];\n      if(parallel) myComm->barrier();\n\n      Timer.stop(\"Generic2\");\n      if(rnk==0) app_log()<<\"     -- setup: \" <<Timer.average(\"Generic2\") <<\"\\n\";\n\n      Timer.reset(\"Generic2\");\n      Timer.reset(\"Generic3\");\n\n#ifndef QMC_COMPLEX\n      if(cntn>0)\n        APP_ABORT(\"Found real Cholesky vectors with real integrals. This is not allowed with dense cholesky vectors. Run with sparse vectors or compile with complex integrals. \\n\\n\\n\");\n#endif\n\n      cnt=std::accumulate(nvec_per_node.begin(),nvec_per_node.begin()+node_number,0);\n      for(int n=0; n<L.size(); n++) { \n       if( cnt_per_vec[2*n]==0 && cnt_per_vec[2*n+1]==0 ) continue;\n       ValueType* Ls;\n       Timer.start(\"Generic2\");\n       if(parallel) {\n#if defined(QMC_COMPLEX)\n         //MPI_Allgather(L[n].data(),2*maxnterms,MPI_DOUBLE,Lcomm.data(),2*maxnterms,MPI_DOUBLE,myComm->getMPI());\n         MPI_Gather(L[n].data(),2*maxnterms,MPI_DOUBLE,Lcomm.data(),2*maxnterms,MPI_DOUBLE,0,myComm->getMPI());\n         if(head_of_nodes)\n           MPI_Bcast(Lcomm.data(),2*Lcomm.size(),MPI_DOUBLE,0,MPI_COMM_HEAD_OF_NODES);   \n#else\n         MPI_Allgather(L[n].data(),maxnterms,MPI_DOUBLE,Lcomm.data(),maxnterms,MPI_DOUBLE,myComm->getMPI());\n#endif\n         Ls = Lcomm.data();\n       } else {\n         Ls = L[n].data();\n       }\n       Timer.stop(\"Generic2\");\n       Timer.start(\"Generic3\");\n       if(head_of_nodes && 2*n>=cv0 && 2*n<cvN && cnt_per_vec[2*n]>0) {\n         int np=0;\n         // v+\n         for(IndexType i=0; i<NMO; i++)\n          for(IndexType k=0; k<NMO; k++) { \n           ValueType V = (Ls[ik2padded[i*NMO+k]] + myconj(Ls[ik2padded[k*NMO+i]])); \n           if(std::abs(V) > cut) { \n             V*=sqrtdt;\n             if(sparse) Spvn.add(i*NMO+k,cnt,static_cast<SPValueType>(V));\n             else Dvn[(i*NMO+k)*ncols + cnt]=static_cast<SPValueType>(V);\n             ++np;\n           } \n         }\n         ++cnt;\n         if(np==0) \n           APP_ABORT(\"Error: This should not happen. Found empty cholesky std::vector. \\n\"); \n       }\n       if(head_of_nodes && (2*n+1)>=cv0 && (2*n+1)<cvN && cnt_per_vec[2*n+1]>0) {\n#if defined(QMC_COMPLEX)\n         int np=0;\n         // v-\n         for(IndexType i=0; i<NMO; i++)\n          for(IndexType k=0; k<NMO; k++) { \n           ValueType V = (Ls[ik2padded[i*NMO+k]] - myconj(Ls[ik2padded[k*NMO+i]]));\n           if(std::abs(V) > cut) {\n             V*=ComplexType(0.0,1.0)*sqrtdt;\n             if(sparse) Spvn.add(i*NMO+k,cnt,static_cast<SPValueType>(V));\n             else Dvn[(i*NMO+k)*ncols + cnt]=static_cast<SPValueType>(V);\n             ++np;\n           }\n          }\n         ++cnt;\n         if(np==0) \n           APP_ABORT(\"Error: This should not happen. Found empty cholesky std::vector. \\n\"); \n#else\n       APP_ABORT(\"Error: This should not happen. Found negative cholesky vector. \\n\"); \n#endif\n       }\n       // necessary to avoid the avalanche of messages to the root from cores that are not head_of_nodes\n       if(n>0 && (n%100==0))\n         myComm->barrier(); \n       Timer.stop(\"Generic3\");\n      }\n      app_log()<<\"     -- av comm time: \" <<Timer.average(\"Generic2\") <<\"\\n\";\n      app_log()<<\"     -- av insert time: \" <<Timer.average(\"Generic3\") <<\"\\n\";\n\n      Timer.stop(\"Generic\");\n      app_log()<<\" -- Time to assemble Cholesky Matrix: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n      if(rank()==0 && nnodes>1 && parallel) { \n        app_log()<<\" Partition of Cholesky Vectors: 0 \";\n        cnt=0;\n        for(int i=0; i<nnodes; i++) { \n          cnt+=nvec_per_node[i]; \n          app_log()<<cnt <<\" \";  \n        }\n        app_log()<<std::endl;\n        if(sparse) {\n          app_log()<<\" Number of terms in Spvn per node in TG: \";\n          for(int i : sz_per_node ) app_log()<<i <<\" \"; \n          app_log()<<std::endl;\n        }\n      }\n\n      app_log()<<\"Number of HS potentials: \" <<ncols <<std::endl;\n      if(sparse) {\n\n        app_log()<<\"Number of terms in sparse representation of HS potentials: \" <<Spvn.size() <<std::endl;\n        app_log()<<\"Compressing Spvn. \\n\";\n\n        Timer.reset(\"Generic\");\n        Timer.start(\"Generic\");\n\n        if(parallel) Spvn.compress(TG.getNodeCommLocal());\n        else if(head_of_nodes) Spvn.compress();\n        //if(head_of_nodes) Spvn.compress();\n\n        Timer.stop(\"Generic\");\n        app_log()<<\"Done Compressing Spvn. \\n\";\n        if(rnk==0) app_log()<<\" -- Time to Compress Cholesky Matrix: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n      }\n\n      if(parallel) myComm->barrier();\n\n    } else {\n\n     // way behind in development, needs parallel and dense options \n     APP_ABORT(\"Error: Cholesky factorization for unrestricted disabled. Finish implementation. \\n\\n\\n\");\n\n      /********************************************************************\n      *               Calculate Cholesky decomposition \n      *\n      *   1. The mapping of the 2-el repulsion integrals to a 2-D matrix\n      *      is done as follows:\n      *         V(i,j,k,l) -->  V( i*NMO+k,  l*NMO+j )\n      ********************************************************************/\n\n     Timer.reset(\"Generic\");\n     Timer.start(\"Generic\");\n\n     // will store full Cholesky std::vectors now and keep sparse versions only at the end.\n     // want to avoid possible numerical issues from truncation\n     std::vector< std::vector<ValueType> > L;\n     L.reserve(2*NMO*NMO);\n\n     // to store diagonal elements to avoid search, since they are used often \n     ValueMatrix Duv(2*NMO,NMO);\n     for(IndexType i=0; i<NMO; i++)\n      for(IndexType k=i; k<NMO; k++) { \n        Duv(i,k) = H(i,k,k,i);\n        if(i!=k) Duv(k,i) = Duv(i,k);\n        if(i!=k) if(toComplex(Duv(i,k)).imag() > 1e-12)\n         app_error()<<\" Found std::complex Duv(i,k) term: \" <<i <<\" \" <<k <<\" \" <<Duv(i,k) <<std::endl; \n     }\n\n     for(IndexType i=NMO; i<2*NMO; i++)\n      for(IndexType k=i; k<2*NMO; k++) { \n        Duv(i,k-NMO) = H(i,k,k,i);\n        if(i!=k) Duv(k,i-NMO) = Duv(i,k-NMO);\n        if(i!=k) if(toComplex(Duv(i,k-NMO)).imag() > 1e-12)\n         app_error()<<\" Found std::complex Duv(i,k) term: \" <<i <<\" \" <<k <<\" \" <<Duv(i,k-NMO) <<std::endl; \n     }\n\n     // D(ik,lj) = H(i,j,k,l) - sum_p Lp(ik) Lp*(lj)\n     // Diagonal:  D(ik,ik) = H(i,k,k,i) - sum_p Lp(ik) Lp*(ik) \n     RealType max=0;\n     IndexType ii=-1,kk=-1;\n     for(IndexType i=0; i<NMO; i++)\n      for(IndexType k=0; k<NMO; k++) {\n       if( std::abs(Duv(i,k)) > max) {\n         max = std::abs(Duv(i,k));  \n         ii=i;\n         kk=k;\n       } \n      }\n     for(IndexType i=NMO; i<2*NMO; i++)\n      for(IndexType k=0; k<NMO; k++) {\n       if( std::abs(Duv(i,k)) > max) {\n         max = std::abs(Duv(i,k));\n         ii=i;\n         kk=k+NMO;\n       }\n      }\n     if(ii<0 || kk<0) {\n      app_error()<<\"Problems with Cholesky decomposition. \\n\";\n      APP_ABORT(\"Problems with Cholesky decomposition. \\n\");   \n     }\n\n     RealType max_old;\n     while(max > cutoff_cholesky) {\n\n       RealType oneOverMax = 1/std::sqrt(std::abs(max));\n\n       // calculate new cholesky std::vector based on (ii,kk)\n       L.push_back(std::vector<ValueType>(2*NMO*NMO));  \n       std::vector<ValueType>& Ln = L.back();\n\n       for(IndexType i=0; i<NMO; i++)\n        for(IndexType k=0; k<NMO; k++) {\n          ValueType& Lnik = Ln[i*NMO+k]; \n          Lnik = H(i,kk,k,ii);\n          for(int n=0; n<L.size()-1; n++)\n            Lnik -= L[n][i*NMO+k]*myconj(L[n][ii*NMO+Index2Col(kk)]);  \n          Lnik *= oneOverMax;\n        } \n       for(IndexType i=NMO; i<2*NMO; i++)\n        for(IndexType k=NMO; k<2*NMO; k++) {\n          ValueType& Lnik = Ln[i*NMO+Index2Col(k)];\n          Lnik = H(i,kk,k,ii);\n          for(int n=0; n<L.size()-1; n++)\n            Lnik -= L[n][i*NMO+Index2Col(k)]*myconj(L[n][ii*NMO+Index2Col(kk)]);\n          Lnik *= oneOverMax;\n        }\n       \n       max_old = max;\n       IndexType ii0=ii,kk0=kk;\n       max=0;\n       ii=-1;\n       kk=-1;\n       for(IndexType i=0; i<NMO; i++)\n        for(IndexType k=0; k<NMO; k++) {\n         Duv(i,k) -= Ln[i*NMO+k]*myconj(Ln[i*NMO+k]);  \n         if( std::abs(Duv(i,k)) > max) {\n           max = std::abs(Duv(i,k)); \n           ii=i;\n           kk=k;\n         }\n        }\n       for(IndexType i=NMO; i<2*NMO; i++)\n        for(IndexType k=0; k<NMO; k++) {\n         Duv(i,k) -= Ln[i*NMO+k]*myconj(Ln[i*NMO+k]);  \n         if( std::abs(Duv(i,k)) > max) {\n           max = std::abs(Duv(i,k));\n           ii=i;\n           kk=k+NMO;\n         }\n        }\n       if(max > max_old) {\n         app_error()<<\"ERROR: Problems with convergence of Cholesky decomposition. \\n\" \n           <<\"Number of std::vectors found so far: \" <<L.size() <<\"\\n\"\n           <<\"Current value of truncation error: \" <<max_old <<\" \" <<max <<std::endl;  \n           APP_ABORT(\"Problems with convergence of Cholesky decomposition.\\n\"); \n       }\n     }\n     app_log()<<\" Found: \" <<L.size() <<\" Cholesky std::vectors with a cutoff of: \" <<cutoff_cholesky <<std::endl;   \n\n     Timer.stop(\"Generic\");\n     if(rnk==0) app_log()<<\" -- Time to generate Cholesky factorization: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n     if(test_breakup && false) {\n\n     if(rnk==0) app_log()<<\" -- Testing Hamiltonian factorization. \\n\";\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      RealType s=0.0;\n      RealType max=0.0;\n      for(IndexType i=0; i<2*NMO; i++)\n       for(IndexType j=0; j<2*NMO; j++) \n        for(IndexType k=0; k<2*NMO; k++)\n         for(IndexType l=0; l<2*NMO; l++) {     \n           if(!goodSpinSector(i,j,k,l,NMO))\n            continue;\n           ValueType v2 = H(i,j,k,l);\n           ValueType v2c = 0.0;\n           int kp = Index2Col(k);\n           int jp = Index2Col(j);\n           for(int n=0; n<L.size(); n++) v2c += L[n][i*NMO+kp]*myconj(L[n][l*NMO+jp]);\n           s+=std::abs(v2-v2c);\n           if( max < std::abs(v2-v2c) ) max = std::abs(v2-v2c);\n           if( std::abs(v2-v2c) > 10*cutoff_cholesky ) {\n             app_error()<<\" Problems with Cholesky decomposition, i,j,k,l,H2,H2c: \"\n                       <<i <<\" \"\n                       <<j <<\" \"\n                       <<k <<\" \"\n                       <<l <<\" \"\n                       <<v2 <<\" \"\n                       <<v2c <<std::endl;\n           }\n         }\n      app_log()<<\"\\n ********************************************\\n Average error due to truncated Cholesky factorization (in units of cutoff), max error : \" <<s/cutoff_cholesky/NMO/NMO/NMO/NMO/4.0 <<\" \" <<max <<\" \\n********************************************\\n\"<<std::endl; \n\n       Timer.stop(\"Generic\");\n       if(rnk==0) app_log()<<\" -- Time to test Cholesky factorization: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n     }\n\n      /********************************************************************\n      *  You get 2 potentials per Cholesky std::vector   \n      *\n      *    vn(+-)_{i,k} = sum_n 0.5*( L^n_{i,k} +- conj(L^n_{k,i}) )            \n      ********************************************************************/\n\n      ValueType sqrtdt = std::sqrt(dt)*0.5;\n\n      int cnt=0;\n      int cntp=0, cntm=0;\n      // generate sparse version\n      for(int n=0; n<L.size(); n++) { \n       int np=0, nm=0;\n       for(IndexType i=0; i<NMO; i++)\n        for(IndexType k=0; k<NMO; k++) { \n          // v+\n          if(std::abs( (L[n][i*NMO+k] + myconj(L[n][k*NMO+i])) ) > cut) {\n            cnt++; \n            np++;\n          }\n          if(std::abs( (L[n][NMO*NMO+i*NMO+k] + myconj(L[n][NMO*NMO+k*NMO+i])) ) > cut) { \n            cnt++; \n            np++;\n          }\n          // v-\n          if(std::abs( (L[n][i*NMO+k] - myconj(L[n][k*NMO+i])) ) > cut) { \n            cnt++; \n            nm++;\n          }\n          if(std::abs( (L[n][NMO*NMO+i*NMO+k] - myconj(L[n][NMO*NMO+k*NMO+i])) ) > cut) { \n            cnt++; \n            nm++;\n          }\n        }\n        if(np>0) ++cntp;\n        if(nm>0) ++cntm;\n      }\n\n      Spvn.setDims(2*NMO*NMO,cntp+cntm);\n      Spvn.allocate_serial(cnt);\n\n#ifndef QMC_COMPLEX\n      if(cntm>0) \n        APP_ABORT(\"Error: Found negative cholesky vectors in REAL build. \\n\");\n#endif\n\n      cnt=0;\n      for(int n=0; n<L.size(); n++) { \n       int np=0;\n       // v+\n       for(IndexType i=0; i<NMO; i++)\n        for(IndexType k=0; k<NMO; k++) { \n         if(std::abs( (L[n][i*NMO+k] + myconj(L[n][k*NMO+i])) ) > cut) { \n           Spvn.add(i*NMO+k,cnt,static_cast<SPValueType>(sqrtdt*(L[n][i*NMO+k] + myconj(L[n][k*NMO+i]))));\n           ++np;\n         }\n         if(std::abs( (L[n][NMO*NMO+i*NMO+k] + myconj(L[n][NMO*NMO+k*NMO+i])) ) > cut) {\n           Spvn.add(NMO*NMO+i*NMO+k,cnt,static_cast<SPValueType>(sqrtdt*(L[n][NMO*NMO+i*NMO+k] + myconj(L[n][NMO*NMO+k*NMO+i]))));\n           ++np;\n         }\n        }\n       if(np>0) ++cnt;\n#if defined(QMC_COMPLEX)\n       np=0;\n       // v-\n       for(IndexType i=0; i<NMO; i++)\n        for(IndexType k=0; k<NMO; k++) { \n         if(std::abs( (L[n][i*NMO+k] - myconj(L[n][k*NMO+i])) ) > cut) { \n           Spvn.add(i*NMO+k,cnt,static_cast<SPValueType>(ComplexType(0,1.0)*sqrtdt*(L[n][i*NMO+k] - myconj(L[n][k*NMO+i]))));\n           ++np;\n         }\n         if(std::abs( (L[n][NMO*NMO+i*NMO+k] - myconj(L[n][NMO*NMO+k*NMO+i])) ) > cut) {\n           Spvn.add(NMO*NMO+i*NMO+k,cnt,static_cast<SPValueType>(ComplexType(0,1.0)*sqrtdt*(L[n][NMO*NMO+i*NMO+k] - myconj(L[n][NMO*NMO+k*NMO+i]))));\n           ++np;\n         }\n        }\n       if(np>0) ++cnt;\n#endif\n      }\n\n      app_log()<<\"Number of HS potentials: \" <<Spvn.cols() <<std::endl;\n      app_log()<<\"Number of terms in sparse representation of HS potentials: \" <<Spvn.size() <<std::endl;\n\n      app_log()<<\"Compressing Spvn. \\n\";\n      Spvn.compress();\n      app_log()<<\"Done Compressing Spvn. \\n\";\n\n    } \n\n     if(test_breakup) {\n\n      if(rnk==0) app_log()<<\" -- Testing Hamiltonian factorization. \\n\";\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      int* cols = Spvn.column_data();\n      int* rows = Spvn.row_data();\n      int* indx = Spvn.row_index();\n      SPValueType* vals = Spvn.values();\n\n      int NMO2 = spinRestricted?(NMO*NMO):(2*NMO*NMO);\n\n      RealType s=0.0;\n      RealType max=0.0;\n      for(IndexType i=0; i<2*NMO; i++)\n       for(IndexType j=0; j<2*NMO; j++)\n        for(IndexType k=0; k<2*NMO; k++)\n         for(IndexType l=0; l<2*NMO; l++) {\n           if(spinRestricted) {\n            if((i>=NMO || j>=NMO || k>=NMO || l>=NMO ))\n             continue;\n           } else {\n            if(!goodSpinSector(i,j,k,l,NMO))\n             continue;\n           }\n           ValueType v2 = H(i,j,k,l);\n           int ik = i*NMO+k;\n           int jl = j*NMO+l;\n           ValueType v2c = SparseMatrixOperators::product_SpVSpV<ValueType>(indx[ik+1]-indx[ik],cols+indx[ik],vals+indx[ik],indx[jl+1]-indx[jl],cols+indx[jl],vals+indx[jl]) / dt;\n           s+=std::abs(v2-v2c);\n           if( max < std::abs(v2-v2c) ) max = std::abs(v2-v2c);\n           if( std::abs(v2-v2c) > 10*cutoff_cholesky ) {\n             app_error()<<\" Problems with H2 decomposition, i,j,k,l,H2,H2c: \"\n                       <<i <<\" \"\n                       <<j <<\" \"\n                       <<k <<\" \"\n                       <<l <<\" \"\n                       <<v2 <<\" \"\n                       <<v2c <<std::endl;\n           }\n         }\n      double scl = spinRestricted?(1.0):(4.0);\n      app_log()<<\"\\n ********************************************\\n Average error due to truncated eigenvalue factorization (in units of cutoff), max error : \" <<s/cutoff_cholesky/NMO/NMO/NMO/NMO/scl <<\" \" <<max <<\" \\n ********************************************\\n\"<<std::endl;\n\n       Timer.stop(\"Generic\");\n       if(rnk==0) app_log()<<\" -- Time to test eigenvalue factorization: \" <<Timer.average(\"Generic\") <<\"\\n\";\n     }\n\n  }\n\n  bool SparseGeneralHamiltonian::parse(xmlNodePtr cur)\n  {\n\n    app_log()<<\"\\n\\n --------------- Parsing Hamiltonian input ------------------ \\n\\n\";\n\n    if(cur == NULL)\n      return false;\n\n    xmlNodePtr curRoot=cur; \n    OhmmsAttributeSet oAttrib;\n    oAttrib.add(name,\"name\");\n    oAttrib.put(cur);\n\n    std::string order(\"no\"); \n    std::string bkp(\"no\"); \n    std::string str1(\"no\"); \n    std::string str2(\"no\"); \n    std::string str3(\"no\"); \n    std::string str4(\"yes\"); \n    std::string str5(\"yes\"); \n    std::string str6(\"no\"); \n    ParameterSet m_param;\n    m_param.add(order,\"orderStates\",\"std::string\");    \n    m_param.add(cutoff1bar,\"cutoff_1bar\",\"double\");\n    m_param.add(cutoff_cholesky,\"cutoff_decomp\",\"double\");\n    m_param.add(cutoff_cholesky,\"cutoff_decomposition\",\"double\");\n    m_param.add(cutoff_cholesky,\"cutoff_factorization\",\"double\");\n    m_param.add(cutoff_cholesky,\"cutoff_cholesky\",\"double\");\n    m_param.add(filetype,\"filetype\",\"std::string\");\n    m_param.add(filename,\"filename\",\"std::string\");\n    m_param.add(hdf_write_file,\"hdf_write_file\",\"std::string\");\n    m_param.add(hdf_write_type,\"hdf_write_type\",\"std::string\");\n    m_param.add(ascii_write_file,\"ascii_write_file\",\"std::string\");\n    m_param.add(rotation,\"rotation\",\"std::string\");\n    m_param.add(number_of_TGs,\"nblocks\",\"int\");\n    m_param.add(bkp,\"test_breakup\",\"std::string\");\n    m_param.add(str1,\"printEig\",\"std::string\");\n    m_param.add(str2,\"test_2eint\",\"std::string\");\n    m_param.add(str3,\"fix_2eint\",\"std::string\");\n    m_param.add(str4,\"test_algo\",\"std::string\");\n    m_param.add(str5,\"inplace\",\"std::string\");\n    m_param.add(str6,\"skip_V2\",\"std::string\");\n    m_param.add(n_reading_cores,\"num_io_cores\",\"int\");\n    m_param.put(cur);\n\n    orderStates=false;\n    std::transform(order.begin(),order.end(),order.begin(),(int (*)(int))tolower);\n    std::transform(filetype.begin(),filetype.end(),filetype.begin(),(int (*)(int))tolower);\n    std::transform(hdf_write_type.begin(),hdf_write_type.end(),hdf_write_type.begin(),(int (*)(int))tolower);\n    std::transform(bkp.begin(),bkp.end(),bkp.begin(),(int (*)(int))tolower);\n    std::transform(str1.begin(),str1.end(),str1.begin(),(int (*)(int))tolower);\n    std::transform(str2.begin(),str2.end(),str2.begin(),(int (*)(int))tolower);\n    std::transform(str3.begin(),str3.end(),str3.begin(),(int (*)(int))tolower);\n    std::transform(str4.begin(),str4.end(),str4.begin(),(int (*)(int))tolower);\n    std::transform(str5.begin(),str5.end(),str5.begin(),(int (*)(int))tolower);\n    std::transform(str6.begin(),str6.end(),str6.begin(),(int (*)(int))tolower);\n    if(order == \"yes\" || order == \"true\") orderStates = true;  \n    if(bkp == \"yes\" || bkp == \"true\") test_breakup = true;  \n    if(str1 == \"yes\" || str1 == \"true\") printEig = true;  \n    if(str2 == \"yes\" || str2 == \"true\") test_2eint = true;  \n    if(str3 == \"yes\" || str3 == \"true\") zero_bad_diag_2eints = true;  \n    if(str4 == \"no\" || str4 == \"false\") test_algo = false;  \n    if(str5 == \"no\" || str5 == \"false\") inplace = false;  \n    if(str6 == \"yes\" || str6 == \"true\") skip_V2 = true;  \n\n    if(skip_V2) \n      app_log()<<\" Skipping 2 electron integrals. Only correct if other objects are initialized from hdf5 files. \\n\";\n   \n    cur = curRoot->children;\n    while (cur != NULL) {\n      std::string cname((const char*)(cur->name));\n      if(cname ==\"something\") {\n      }\n      cur = cur->next;\n    }\n\n    return true;\n  } \n\n  // do a general check of parameters for consistency\n  // make sure object was build consistently and correctly \n  bool SparseGeneralHamiltonian::checkObject() \n  {\n    return true;\n  }\n\n  // For a given quartet ijkl and the 3 (for real) different permutations \n  // in the reduced list, add all possible contributions to the Hamiltonian\n  // taking into account cutoff and (ik)<->(jl) symmetry  \n  // J1 = <ij|kl>\n  // J2 = <ij|lk>\n  // J3 = <ik|jl> \n  //  routine currently assumes that ijkl is the smallest of the 3 non-symmetric terms \n  //  For complex, there are 3 extra non-symmetric terms:\n  //  J1a = <il|kj>\n  //  J2a = <ik|lj>\n  //  J3a = <il|jk> \n  //    In this case, make sure you use the fact that: <ij|kl> = conj( <kl|ij> )\n  void SparseGeneralHamiltonian::find_all_contributions_to_hamiltonian_closed_shell(bool aa_only, OrbitalType i, OrbitalType j, OrbitalType k, OrbitalType l, ValueType J1, ValueType J2, ValueType J3, ValueType J1a, ValueType J2a, ValueType J3a, double cut, std::vector<s4D<ValueType> >& v)\n  {\n    // simple algorithm for now\n    // 1. add all contributions blindly\n    // 2. check for repeated and remove\n    // 3. apply symmetry elimination\n   \n    if(aa_only)\n      APP_ABORT(\" Error in SparseGeneralHamiltonian::find_all_contributions_to_hamiltonian_closed_shell(). aa_only is not allowed. \\n\\n\\n\");\n\n    v.reserve(24);  \n\n#ifndef QMC_COMPLEX \n    J1a=J1;\n    J2a=J2;\n    J3a=J3;\n#endif\n\n    // <ij||kl> -> (ijkl)\n    // Symmetries:\n    //   (ijkl) = (jilk) = (klij)* = (lkji)* = -(ijlk) = -(jikl) = -(lkij)* = -(klji)* \n\n    ValueType J1J2 = 4.0*J1-2.0*J2;\n    if(std::abs(J1J2) > cut) {\n      push_ijkl(i,j,k,l,J1J2,v);\n      push_ijkl(k,l,i,j,myconj(J1J2),v);\n    }\n    ValueType J1J3 = 4.0*J1a-2.0*J3a;\n    if(std::abs(J1J3) > cut) {\n      push_ijkl(i,l,k,j,J1J3,v);\n      push_ijkl(j,k,l,i,myconj(J1J3),v);\n    }\n\n    ValueType J2J1 = 4.0*J2-2.0*J1;\n    if(std::abs(J2J1) > cut) {\n      push_ijkl(i,j,l,k,J2J1,v);\n      push_ijkl(k,l,j,i,myconj(J2J1),v);\n    }\n    ValueType J2J3 = 4.0*J2a-2.0*J3;\n    if(std::abs(J2J3) > cut) {\n      push_ijkl(i,k,l,j,J2J3,v);\n      push_ijkl(j,l,k,i,myconj(J2J3),v);\n    }\n\n    ValueType J3J1 = 4.0*J3a-2.0*J1a;\n    if(std::abs(J3J1) > cut) {\n      push_ijkl(i,l,j,k,J3J1,v);\n      push_ijkl(k,j,l,i,myconj(J3J1),v);\n    }\n    ValueType J3J2 = 4.0*J3-2.0*J2a;\n    if(std::abs(J3J2) > cut) {\n      push_ijkl(i,k,j,l,J3J2,v);\n      push_ijkl(l,j,k,i,myconj(J3J2),v);\n    }\n\n    // order to remove consecutive repreated \n    std::sort (v.begin(), v.end(), mySort);\n    // remove consecutive repeated\n    std::vector<s4D<ValueType> >::iterator it;\n    it = std::unique(v.begin(),v.end());\n    // resize array, since unique does not remove elements\n    // just reorders them  \n    v.resize( std::distance(v.begin(),it) );\n  }\n\n  // For a given quartet ijkl and the 3 (for real) different permutations \n  // in the reduced list, add all possible contributions to the Hamiltonian\n  // taking into account cutoff and (ik)<->(jl) symmetry  \n  // J1 = <ij|kl>\n  // J2 = <ij|lk>\n  // J3 = <ik|jl> \n  //  For complex, there are 3 extra non-symmetric terms:\n  //  J1a = <il|kj>\n  //  J2a = <ik|lj>\n  //  J3a = <il|jk> \n  void SparseGeneralHamiltonian::find_all_contributions_to_hamiltonian_spinRestricted(bool aa_only, OrbitalType i, OrbitalType j, OrbitalType k, OrbitalType l, ValueType J1, ValueType J2, ValueType J3, ValueType J1a, ValueType J2a, ValueType J3a, double cut, std::vector<s4D<ValueType> >& v) \n  { \n    // simple algorithm for now\n    // 1. add all contributions blindly\n    // 2. check for repeated and remove\n    // 3. apply symmetry elimination\n    // 4. if aa_only, only alpha/alpha component is added \n    //\n   \n    v.reserve(48);  \n    v.clear();\n  \n    int i2 = i+NMO; \n    int j2 = j+NMO; \n    int k2 = k+NMO; \n    int l2 = l+NMO; \n#ifndef QMC_COMPLEX\n    J1a=J1;\n    J2a=J2;\n    J3a=J3;\n#else\n      APP_ABORT(\"Not yet working for std::complex \\n\\n\\n\");\n#endif\n    // 2bar terms\n    ValueType J1J2 = J1-J2;\n    if(std::abs(J1J2) > cut) {\n      push_ijkl(i,j,k,l,J1J2,v);\n      push_ijkl(k,l,i,j,J1J2,v);  \n      if(!aa_only) push_ijkl(i2,j2,k2,l2,J1J2,v);\n      if(!aa_only) push_ijkl(k2,l2,i2,j2,J1J2,v);  \n    }\n    ValueType J1J3 = J1-J3;\n    if(std::abs(J1J3) > cut) {\n      push_ijkl(i,l,k,j,J1J3,v);  \n      push_ijkl(j,k,l,i,J1J3,v);  \n      if(!aa_only) push_ijkl(i2,l2,k2,j2,J1J3,v);  \n      if(!aa_only) push_ijkl(j2,k2,l2,i2,J1J3,v);  \n    }\n\n    ValueType J2J1 = J2-J1;\n    if(std::abs(J2J1) > cut) {\n      push_ijkl(i,j,l,k,J2J1,v);\n      push_ijkl(k,l,j,i,J2J1,v);\n      if(!aa_only) push_ijkl(i2,j2,l2,k2,J2J1,v);\n      if(!aa_only) push_ijkl(k2,l2,j2,i2,J2J1,v);\n    }\n    ValueType J2J3 = J2-J3;\n    if(std::abs(J2J3) > cut) {\n      push_ijkl(i,k,l,j,J2J3,v);\n      push_ijkl(j,l,k,i,J2J3,v);\n      if(!aa_only) push_ijkl(i2,k2,l2,j2,J2J3,v);\n      if(!aa_only) push_ijkl(j2,l2,k2,i2,J2J3,v);\n    }\n       \n    ValueType J3J1 = J3-J1;\n    if(std::abs(J3J1) > cut) {\n      push_ijkl(i,l,j,k,J3J1,v);\n      push_ijkl(k,j,l,i,J3J1,v);\n      if(!aa_only) push_ijkl(i2,l2,j2,k2,J3J1,v);\n      if(!aa_only) push_ijkl(k2,j2,l2,i2,J3J1,v);\n    }    \n    ValueType J3J2 = J3-J2;\n    if(std::abs(J3J2) > cut) {\n      push_ijkl(i,k,j,l,J3J2,v);\n      push_ijkl(l,j,k,i,J3J2,v);\n      if(!aa_only) push_ijkl(i2,k2,j2,l2,J3J2,v);\n      if(!aa_only) push_ijkl(l2,j2,k2,i2,J3J2,v);\n    }    \n\n    // 1bar terms\n    if(std::abs(J1) > cut && !aa_only) {\n      push_ijkl(i,j2,k,l2,J1,v);\n      push_ijkl(k,l2,i,j2,J1,v);\n      push_ijkl(i,l2,k,j2,J1,v);\n      push_ijkl(j,k2,l,i2,J1,v);\n      push_ijkl(j,i2,l,k2,J1,v);\n      push_ijkl(l,k2,j,i2,J1,v);\n      push_ijkl(l,i2,j,k2,J1,v);\n      push_ijkl(k,j2,i,l2,J1,v);\n    }       \n    if(std::abs(J2) > cut && !aa_only) {\n      push_ijkl(i,j2,l,k2,J2,v);\n      push_ijkl(k,l2,j,i2,J2,v);\n      push_ijkl(i,k2,l,j2,J2,v);\n      push_ijkl(j,l2,k,i2,J2,v);\n      push_ijkl(j,i2,k,l2,J2,v);\n      push_ijkl(l,k2,i,j2,J2,v);\n      push_ijkl(k,i2,j,l2,J2,v);\n      push_ijkl(l,j2,i,k2,J2,v);\n    }    \n    if(std::abs(J3) > cut && !aa_only) {\n      push_ijkl(i,l2,j,k2,J3,v);\n      push_ijkl(k,j2,l,i2,J3,v);\n      push_ijkl(i,k2,j,l2,J3,v);\n      push_ijkl(l,j2,k,i2,J3,v);\n      push_ijkl(l,i2,k,j2,J3,v);\n      push_ijkl(j,k2,i,l2,J3,v);\n      push_ijkl(k,i2,l,j2,J3,v);\n      push_ijkl(j,l2,i,k2,J3,v);\n    }\n\n\n    // order to remove consecutive repreated \n    std::sort (v.begin(), v.end(), mySort);\n    // remove consecutive repeated\n    std::vector<s4D<ValueType> >::iterator it;\n    it = std::unique(v.begin(),v.end());\n    // resize array, since unique does not remove elements\n    // just reorders them  \n    v.resize( std::distance(v.begin(),it) );\n\n  }\n\n  // For a given quartet ijkl and the 3 (for real) different permutations \n  // in the reduced list, add all possible contributions to the Hamiltonian\n  // taking into account cutoff and (ik)<->(jl) symmetry  \n  // J1 = <ij|kl>\n  // J2 = <ij|lk>\n  // J3 = <ik|jl> \n  //  For complex, there are 3 extra non-symmetric terms:\n  //  J1a = <il|kj>\n  //  J2a = <ik|lj>\n  //  J3a = <il|jk> \n  void SparseGeneralHamiltonian::find_all_contributions_to_hamiltonian_ghf(bool aa_only, OrbitalType i, OrbitalType j, OrbitalType k, OrbitalType l, ValueType J1, ValueType J2, ValueType J3, ValueType J1a, ValueType J2a, ValueType J3a, double cut, std::vector<s4D<ValueType> >& v) \n  { \n    // simple algorithm for now\n    // 1. add all contributions blindly\n    // 2. check for repeated and remove\n    // 3. apply symmetry elimination\n    //\n    // GHF: all terms from _spinRestricted routine plus: M_(i-alpha k-beta)_(j-beta l-alpha) = <ij|lk> \n  \n    if(aa_only)\n      APP_ABORT(\" Error in SparseGeneralHamiltonian::find_all_contributions_to_hamiltonian_ghf(). aa_only is not allowed. \\n\\n\\n\");\n \n    v.reserve(48);  \n    v.clear();\n  \n    int i2 = i+NMO; \n    int j2 = j+NMO; \n    int k2 = k+NMO; \n    int l2 = l+NMO; \n#ifndef QMC_COMPLEX\n    J1a=J1;\n    J2a=J2;\n    J3a=J3;\n#else\n      APP_ABORT(\"Not yet working for std::complex \\n\\n\\n\");\n#endif\n    // 2bar terms\n    ValueType J1J2 = J1-J2;\n    if(std::abs(J1J2) > cut) {\n      push_ijkl(i,j,k,l,J1J2,v,true);\n      push_ijkl(k,l,i,j,J1J2,v,true);  \n      push_ijkl(i2,j2,k2,l2,J1J2,v,true);\n      push_ijkl(k2,l2,i2,j2,J1J2,v,true);  \n    }\n    ValueType J1J3 = J1-J3;\n    if(std::abs(J1J3) > cut) {\n      push_ijkl(i,l,k,j,J1J3,v,true);  \n      push_ijkl(j,k,l,i,J1J3,v,true);  \n      push_ijkl(i2,l2,k2,j2,J1J3,v,true);  \n      push_ijkl(j2,k2,l2,i2,J1J3,v,true);  \n    }\n\n    ValueType J2J1 = J2-J1;\n    if(std::abs(J2J1) > cut) {\n      push_ijkl(i,j,l,k,J2J1,v,true);\n      push_ijkl(k,l,j,i,J2J1,v,true);\n      push_ijkl(i2,j2,l2,k2,J2J1,v,true);\n      push_ijkl(k2,l2,j2,i2,J2J1,v,true);\n    }\n    ValueType J2J3 = J2-J3;\n    if(std::abs(J2J3) > cut) {\n      push_ijkl(i,k,l,j,J2J3,v,true);\n      push_ijkl(j,l,k,i,J2J3,v,true);\n      push_ijkl(i2,k2,l2,j2,J2J3,v,true);\n      push_ijkl(j2,l2,k2,i2,J2J3,v,true);\n    }\n       \n    ValueType J3J1 = J3-J1;\n    if(std::abs(J3J1) > cut) {\n      push_ijkl(i,l,j,k,J3J1,v,true);\n      push_ijkl(k,j,l,i,J3J1,v,true);\n      push_ijkl(i2,l2,j2,k2,J3J1,v,true);\n      push_ijkl(k2,j2,l2,i2,J3J1,v,true);\n    }    \n    ValueType J3J2 = J3-J2;\n    if(std::abs(J3J2) > cut) {\n      push_ijkl(i,k,j,l,J3J2,v,true);\n      push_ijkl(l,j,k,i,J3J2,v,true);\n      push_ijkl(i2,k2,j2,l2,J3J2,v,true);\n      push_ijkl(l2,j2,k2,i2,J3J2,v,true);\n    }    \n\n    // 1bar terms: <alpha,beta|alpha,beta>\n    if(std::abs(J1) > cut) {\n      push_ijkl(i,j2,k,l2,J1,v,true);\n      push_ijkl(k,l2,i,j2,J1,v,true);\n      push_ijkl(i,l2,k,j2,J1,v,true);\n      push_ijkl(j,k2,l,i2,J1,v,true);\n      push_ijkl(j,i2,l,k2,J1,v,true);\n      push_ijkl(l,k2,j,i2,J1,v,true);\n      push_ijkl(l,i2,j,k2,J1,v,true);\n      push_ijkl(k,j2,i,l2,J1,v,true);\n    }       \n    if(std::abs(J2) > cut) {\n      push_ijkl(i,j2,l,k2,J2,v,true);\n      push_ijkl(k,l2,j,i2,J2,v,true);\n      push_ijkl(i,k2,l,j2,J2,v,true);\n      push_ijkl(j,l2,k,i2,J2,v,true);\n      push_ijkl(j,i2,k,l2,J2,v,true);\n      push_ijkl(l,k2,i,j2,J2,v,true);\n      push_ijkl(k,i2,j,l2,J2,v,true);\n      push_ijkl(l,j2,i,k2,J2,v,true);\n    }    \n    if(std::abs(J3) > cut) {\n      push_ijkl(i,l2,j,k2,J3,v,true);\n      push_ijkl(k,j2,l,i2,J3,v,true);\n      push_ijkl(i,k2,j,l2,J3,v,true);\n      push_ijkl(l,j2,k,i2,J3,v,true);\n      push_ijkl(l,i2,k,j2,J3,v,true);\n      push_ijkl(j,k2,i,l2,J3,v,true);\n      push_ijkl(k,i2,l,j2,J3,v,true);\n      push_ijkl(j,l2,i,k2,J3,v,true);\n    }\n\n    // GHF extra exchage terms: <alpha,beta|beta,alpha>\n    // M_iakb_jbla = <iajb|lakb> \n    // J1 = <ij|kl>\n    // J2 = <ij|lk> \n    // J3 = <ik|jl> \n    J1*=RealType(-1); \n    J2*=RealType(-1); \n    J3*=RealType(-1); \n    if(std::abs(J1) > cut) {\n      push_ijkl(i,j2,l2,k,J1,v,true);\n      push_ijkl(k,j2,l2,i,J1,v,true);\n      push_ijkl(i,l2,j2,k,J1,v,true);\n      push_ijkl(k,l2,j2,i,J1,v,true);\n      push_ijkl(j,i2,k2,l,J1,v,true);\n      push_ijkl(l,i2,k2,j,J1,v,true);\n      push_ijkl(j,k2,i2,l,J1,v,true);\n      push_ijkl(l,k2,i2,j,J1,v,true);\n    }       \n    if(std::abs(J2) > cut) {\n      push_ijkl(i,j2,k2,l,J2,v,true);\n      push_ijkl(l,j2,k2,i,J2,v,true);\n      push_ijkl(i,k2,j2,l,J2,v,true);\n      push_ijkl(l,k2,j2,i,J2,v,true);\n      push_ijkl(j,i2,l2,k,J2,v,true);\n      push_ijkl(k,i2,l2,j,J2,v,true);\n      push_ijkl(j,l2,i2,k,J2,v,true);\n      push_ijkl(k,l2,i2,j,J2,v,true);\n    }    \n    if(std::abs(J3) > cut) {\n      push_ijkl(i,k2,l2,j,J3,v,true);\n      push_ijkl(j,k2,l2,i,J3,v,true);\n      push_ijkl(i,l2,k2,j,J3,v,true);\n      push_ijkl(j,l2,k2,i,J3,v,true);\n      push_ijkl(k,i2,j2,l,J3,v,true);\n      push_ijkl(l,i2,j2,k,J3,v,true);\n      push_ijkl(k,j2,i2,l,J3,v,true);\n      push_ijkl(l,j2,i2,k,J3,v,true);\n    }\n\n\n    // order to remove consecutive repreated \n    std::sort (v.begin(), v.end(), mySort);\n    // remove consecutive repeated\n    std::vector<s4D<ValueType> >::iterator it;\n    it = std::unique(v.begin(),v.end());\n    // resize array, since unique does not remove elements\n    // just reorders them  \n    v.resize( std::distance(v.begin(),it) );\n\n  }\n\n  // For a given quartet ijkl and the 3 (for real) different permutations \n  // in the reduced list, add all possible contributions to the Hamiltonian\n  // taking into account cutoff and (ik)<->(jl) symmetry  \n  // J1 = <ij|kl>\n  // J2 = <ij|lk>\n  // J3 = <ik|jl> \n  //  For complex, there are 3 extra non-symmetric terms:\n  //  J1a = <il|kj>\n  //  J2a = <ik|lj>\n  //  J3a = <il|jk> \n  void SparseGeneralHamiltonian::find_all_contributions_to_hamiltonian_general(bool aa_only, OrbitalType i, OrbitalType j, OrbitalType k, OrbitalType l, ValueType J1, ValueType J2, ValueType J3, ValueType J1a, ValueType J2a, ValueType J3a, double cut, std::vector<s4D<ValueType> >& v) \n  {\n    APP_ABORT(\"Finsigh implementation. \\n\\n\\n\");\n\n    if(aa_only)\n      APP_ABORT(\" Error in SparseGeneralHamiltonian::find_all_contributions_to_hamiltonian_general(). aa_only is not allowed. \\n\\n\\n\");\n  }\n\n  // looks for all equivalent terms associated with Vijkl \n  // Applies std::complex conjugate when needed\n  // Quite inefficient, so don't use outside initialization  \n  void SparseGeneralHamiltonian::find_equivalent_OneBar_for_integral_list(s4D<ValueType> Vijkl, std::vector<s4D<ValueType> >& v)\n  {\n    v.reserve(24);\n    v.clear();\n    IndexType i,j,k,l;\n    ValueType V;\n    std::tie (i,j,k,l,V) = Vijkl;\n    if( isComplex( std::get<4>(Vijkl) ) ) {\n      // only alpha/alpha sector is stored\n      // so there should bever be any beta index here, should I check???\n      // <ij|kl> = <ji|lk> = <kl|ij>* = <lk|ji>*\n      s3D<IndexType> ijkl = std::make_tuple(i,j,k,l); \n      s3D<IndexType> jilk = std::make_tuple(j,i,l,k); \n      s3D<IndexType> klij = std::make_tuple(k,l,i,j); \n      s3D<IndexType> lkji = std::make_tuple(l,k,j,i); \n\n      v.push_back(Vijkl);\n      if( jilk != ijkl ) v.push_back(std::make_tuple(j,i,l,k,V));  \n      if( klij != ijkl && klij != jilk ) v.push_back(std::make_tuple(k,l,i,j,myconj(V)));   \n      if( lkji != ijkl && lkji != jilk && lkji != klij ) v.push_back(std::make_tuple(l,k,j,i,myconj(V)));   \n      // order, not needed but good measure \n      std::sort (v.begin(), v.end(),mySort);\n    } else {\n      // only alpha/alpha sector is stored\n      // so there should bever be any beta index here, should I check???\n      //  For one-bar integrals: <ij|kl> = <kj|il> = <il|kj> = <kl|ij>\n      //                                 = <ji|lk> = <li|jk> = <jk|li> = <lk|ji>\n\n      v.push_back(std::make_tuple(i,j,k,l,V));  \n      v.push_back(std::make_tuple(k,j,i,l,V));  \n      v.push_back(std::make_tuple(i,l,k,j,V));  \n      v.push_back(std::make_tuple(k,l,i,j,V));  \n      v.push_back(std::make_tuple(j,i,l,k,V));  \n      v.push_back(std::make_tuple(l,i,j,k,V));  \n      v.push_back(std::make_tuple(j,k,l,i,V));  \n      v.push_back(std::make_tuple(l,k,j,i,V));  \n      // order to remove consecutive repreated \n       \n\n      std::sort (v.begin(), v.end(), mySort);\n      //std::sort (v.begin(), v.end());\n      // remove consecutive repeated\n      std::vector<s4D<ValueType> >::iterator it;\n      it = std::unique(v.begin(),v.end());\n      // resize array, since unique does not remove elements\n      // just reorders them  \n      v.resize( std::distance(v.begin(),it) );\n    } \n\n  }\n\n  // for symmetric terms (e.g. ik/jl - jl/ik, we keep 1 and multiply V by 2.\n  void SparseGeneralHamiltonian::find_equivalent_OneBar_for_hamiltonian_generation(s4D<ValueType> Vijkl, std::vector<s4D<ValueType> >& v)\n  {\n    v.reserve(24);\n    v.clear();\n    IndexType i,j,k,l;\n    ValueType V;\n    std::tie (i,j,k,l,V) = Vijkl;\n    if( isComplex( std::get<4>(Vijkl) ) ) {\n      // <ij|kl> = <ji|lk> = <kl|ij>* = <lk|ji>*\n      s3D<IndexType> ijkl = std::make_tuple(i,j,k,l); \n      s3D<IndexType> jilk = std::make_tuple(j,i,l,k); \n      s3D<IndexType> klij = std::make_tuple(k,l,i,j); \n      s3D<IndexType> lkji = std::make_tuple(l,k,j,i); \n\n      \n      if( jilk != ijkl ) {\n        v.push_back(std::make_tuple(i,j,k,l,static_cast<RealType>(2.0)*V));  \n      } else \n        v.push_back(Vijkl);\n\n      if( klij != ijkl && klij != jilk ) {\n\n        // need to add klij as conj(V). How do I add it? \n        if(klij != lkji) {  // add once with factor of 2\n          v.push_back(std::make_tuple(k,l,i,j,myconj(static_cast<RealType>(2.0)*V)));   \n          if(ijkl == lkji)  {\n            std::cerr<<\" Error in find_equivalent_OneBar_for_hamiltonian_generation: Not sure how you got here. (ijkl == lkji): \" <<i <<\" \" <<j <<\" \" <<k <<\" \" <<l <<\"  \" <<V  <<std::endl;\n            APP_ABORT(\"Error in find_equivalent_OneBar_for_hamiltonian_generation: Not sure how you got here. (ijkl == lkji) \\n\"); \n          }\n        } else \n          v.push_back(std::make_tuple(k,l,i,j,myconj(V)));\n\n      } else {\n        // just checking\n        if( klij == jilk && toComplex(V).imag() > 1e-8  ) {  \n          std::cerr<<\" Error in find_equivalent_OneBar_for_hamiltonian_generation: Not sure how you got here. (klij == jilk): \" <<i <<\" \" <<j <<\" \" <<k <<\" \" <<l <<\"  \" <<V  <<std::endl;\n          APP_ABORT(\"Error in find_equivalent_OneBar_for_hamiltonian_generation: Not sure how you got here. (klij == jilk) \\n\"); \n        } \n      } \n\n    } else {\n\n      v.push_back(std::make_tuple(i,j,k,l,V));  \n      v.push_back(std::make_tuple(k,j,i,l,V));  \n      v.push_back(std::make_tuple(i,l,k,j,V));  \n      v.push_back(std::make_tuple(k,l,i,j,V));  \n      v.push_back(std::make_tuple(j,i,l,k,V));  \n      v.push_back(std::make_tuple(l,i,j,k,V));  \n      v.push_back(std::make_tuple(j,k,l,i,V));  \n      v.push_back(std::make_tuple(l,k,j,i,V));  \n      // order to remove consecutive repreated \n      std::sort (v.begin(), v.end(), mySort);\n      // remove consecutive repeated\n      std::vector<s4D<ValueType>>::iterator it;\n      it = std::unique(v.begin(),v.end());\n      // resize array, since unique does not remove elements\n      // just reorders them  \n      v.resize( std::distance(v.begin(),it) );\n\n      //return;\n\n      // look for symmetric terms\n      it = v.begin();\n      std::vector<s4D<ValueType>>::iterator it2;\n      do {\n        it2 = it+1; \n        while(it2!=v.end()) {\n          // <i1j1|k1l1> -> i1k1/j1l1, so look for \n          //   i1==j2, k1==l2, j1==i2, l1==k2 \n          if( std::get<0>(*it)==std::get<1>(*it2) && std::get<2>(*it)==std::get<3>(*it2) && std::get<1>(*it)==std::get<0>(*it2) && std::get<3>(*it)==std::get<2>(*it2) ) { \n            it2=v.erase(it2); // since it2 > it, we can safely erase \n            std::get<4>(*it) *= static_cast<RealType>(2.0); \n          } else {\n            ++it2; \n          }\n        }\n        it++;\n      } while(it!=v.end());\n\n    } \n  }\n\n  void SparseGeneralHamiltonian::find_equivalent_TwoBar_for_integral_list(s4D<ValueType> Vijkl, std::vector<s4D<ValueType> >& v)\n  {\n\n    v.reserve(24);\n    v.clear();\n    IndexType i,j,k,l;\n    ValueType V;\n    std::tie (i,j,k,l,V) = Vijkl;\n\n    // <ij||kl> -> (ijkl)\n    // Symmetries:\n    // (ijkl) = (jilk) = (klij)* = (lkji)* = -(ijlk) = -(jikl) = -(lkij)* = -(klji)* \n    // This method doesn't work here, because I modify V. \n    //v.push_back(std::make_tuple(i,j,k,l,V));  \n    //v.push_back(std::make_tuple(j,i,l,k,V));  \n    //v.push_back(std::make_tuple(k,l,i,j,myconj(V)));  \n    //v.push_back(std::make_tuple(l,k,j,i,myconj(V)));  \n    //v.push_back(std::make_tuple(i,j,l,k,static_cast<RealType>(-1.0)*V));  \n    //v.push_back(std::make_tuple(j,i,k,l,static_cast<RealType>(-1.0)*V));  \n    //v.push_back(std::make_tuple(l,k,i,j,myconj(static_cast<RealType>(-1.0)*V)));  \n    //v.push_back(std::make_tuple(k,l,j,i,myconj(static_cast<RealType>(-1.0)*V)));  \n    \n    auto ijkl = std::make_tuple(i,j,k,l); \n    auto jilk = std::make_tuple(j,i,l,k); \n    auto klij = std::make_tuple(k,l,i,j); \n    auto lkji = std::make_tuple(l,k,j,i); \n    auto ijlk = std::make_tuple(i,j,l,k); \n    auto jikl = std::make_tuple(j,i,k,l); \n    auto lkij = std::make_tuple(l,k,i,j); \n    auto klji = std::make_tuple(k,l,j,i); \n\n    // doing it by hand \n    v.push_back(std::make_tuple(i,j,k,l,V));  \n    // slow and inefficient, but EASY to write!!!\n    if( ijkl != jilk ) \n      v.push_back(std::make_tuple(j,i,l,k,V));\n    if( klij != ijkl && klij != jilk ) \n      v.push_back(std::make_tuple(k,l,i,j,myconj(V)));  \n    if( lkji != ijkl && lkji != jilk && lkji != klij ) \n      v.push_back(std::make_tuple(l,k,j,i,myconj(V)));  \n    if( ijlk != lkji && ijlk != ijkl && ijlk != jilk && ijlk != klij ) \n      v.push_back(std::make_tuple(i,j,l,k,static_cast<RealType>(-1.0)*V));  \n    if( jikl != ijlk && jikl != lkji && jikl != ijkl && jikl != jilk && jikl != klij ) \n      v.push_back(std::make_tuple(j,i,k,l,static_cast<RealType>(-1.0)*V));  \n    if( lkij != jikl && lkij != ijlk && lkij != lkji && lkij != ijkl && lkij != jilk && lkij != klij ) \n      v.push_back(std::make_tuple(l,k,i,j,myconj(static_cast<RealType>(-1.0)*V)));  \n    if( klji != lkij && klji != jikl && klji != ijlk && klji != lkji && klji != ijkl && klji != jilk && klji != klij ) \n      v.push_back(std::make_tuple(k,l,j,i,myconj(static_cast<RealType>(-1.0)*V)));  \n\n\n    // just in case \n    std::sort (v.begin(), v.end(), mySort);\n\n  }\n\n  // to do:\n  //  3. create list of 2-bar integrals based on sparse storage of smallest element per symmetry set\n  void SparseGeneralHamiltonian::find_equivalent_TwoBar_for_hamiltonian_generation(s4D<ValueType> Vijkl, std::vector<s4D<ValueType> >& v)\n  {\n\n    v.reserve(24);\n    v.clear();\n    IndexType i,j,k,l;\n    ValueType V;\n    std::tie (i,j,k,l,V) = Vijkl;\n\n    // <ij||kl> -> (ijkl)\n    // Symmetries:\n    // (ijkl) = (jilk) = (klij)* = (lkji)* = -(ijlk) = -(jikl) = -(lkij)* = -(klji)* \n    // This method doesn't work here, because I modify V. \n    //v.push_back(std::make_tuple(i,j,k,l,V));  \n    //v.push_back(std::make_tuple(j,i,l,k,V));  \n    //v.push_back(std::make_tuple(k,l,i,j,myconj(V)));  \n    //v.push_back(std::make_tuple(l,k,j,i,myconj(V)));  \n    //v.push_back(std::make_tuple(i,j,l,k,static_cast<RealType>(-1.0)*V));  \n    //v.push_back(std::make_tuple(j,i,k,l,static_cast<RealType>(-1.0)*V));  \n    //v.push_back(std::make_tuple(l,k,i,j,myconj(static_cast<RealType>(-1.0)*V)));  \n    //v.push_back(std::make_tuple(k,l,j,i,myconj(static_cast<RealType>(-1.0)*V)));  \n    \n    auto ijkl = std::make_tuple(i,j,k,l); \n    auto jilk = std::make_tuple(j,i,l,k); \n    auto klij = std::make_tuple(k,l,i,j); \n    auto lkji = std::make_tuple(l,k,j,i); \n    auto ijlk = std::make_tuple(i,j,l,k); \n    auto jikl = std::make_tuple(j,i,k,l); \n    auto lkij = std::make_tuple(l,k,i,j); \n    auto klji = std::make_tuple(k,l,j,i); \n\n    // slow and inefficient, but EASY to write!!!\n    if( ijkl != jilk ) \n      v.push_back(std::make_tuple(i,j,k,l,static_cast<RealType>(2.0)*V));  \n    else\n      v.push_back(std::make_tuple(i,j,k,l,V));  \n\n    bool t=false;\n    if( klij != ijkl && klij != jilk ) { \n      t=true;\n      v.push_back(std::make_tuple(k,l,i,j,myconj(V)));  \n    }\n    if( lkji != ijkl && lkji != jilk && lkji != klij ) { \n      if(t) \n        std::get<4>(v.back()) *= static_cast<RealType>(2.0);\n      else\n        v.push_back(std::make_tuple(l,k,j,i,myconj(V)));  \n    }\n\n    t=false;\n    if( ijlk != lkji && ijlk != ijkl && ijlk != jilk && ijlk != klij ) {\n      t=true; \n      v.push_back(std::make_tuple(i,j,l,k,static_cast<RealType>(-1.0)*V));  \n    }\n    if( jikl != ijlk && jikl != lkji && jikl != ijkl && jikl != jilk && jikl != klij ) {\n      if(t)\n        std::get<4>(v.back()) *= static_cast<RealType>(2.0);\n      else\n        v.push_back(std::make_tuple(j,i,k,l,static_cast<RealType>(-1.0)*V));  \n    }\n\n    t=false;\n    if( lkij != jikl && lkij != ijlk && lkij != lkji && lkij != ijkl && lkij != jilk && lkij != klij ) { \n      t=true;\n      v.push_back(std::make_tuple(l,k,i,j,myconj(static_cast<RealType>(-1.0)*V)));  \n    }\n    if( klji != lkij && klji != jikl && klji != ijlk && klji != lkji && klji != ijkl && klji != jilk && klji != klij ) {\n      if(t) \n        std::get<4>(v.back()) *= static_cast<RealType>(2.0);\n      else \n        v.push_back(std::make_tuple(k,l,j,i,myconj(static_cast<RealType>(-1.0)*V)));  \n    }\n\n    std::sort (v.begin(), v.end(), mySort);\n\n  }\n\n  bool SparseGeneralHamiltonian::find_smallest_permutation(s4D<ValueType>& val) {\n\n#if defined(QMC_COMPLEX)\n    // jl < ik\n    if(  std::forward_as_tuple(std::get<1>(val),std::get<3>(val) ) < std::forward_as_tuple(std::get<0>(val),std::get<2>(val) )  ) {\n        std::swap(std::get<0>(val),std::get<1>(val));\n        std::swap(std::get<2>(val),std::get<3>(val));\n    }\n    // kl < ij\n    if(  std::forward_as_tuple(std::get<2>(val),std::get<3>(val) ) < std::forward_as_tuple(std::get<0>(val),std::get<1>(val) )  ) {\n      std::swap(std::get<0>(val),std::get<2>(val));\n      std::swap(std::get<1>(val),std::get<3>(val));\n      std::get<4>(val) = std::conj(std::get<4>(val));\n      // jl < ik again since ij<->kl swap occured  \n      if(  std::forward_as_tuple(std::get<1>(val),std::get<3>(val) ) < std::forward_as_tuple(std::get<0>(val),std::get<2>(val) )  ) {\n        std::swap(std::get<0>(val),std::get<1>(val));\n        std::swap(std::get<2>(val),std::get<3>(val));\n      }\n      return true;\n    } else {\n      // only possibility is that l < i, since I know that the current i is smaller than j and k\n      // \n      if( std::forward_as_tuple(std::get<3>(val),std::get<2>(val) ) < std::forward_as_tuple(std::get<0>(val),std::get<1>(val) )  ) { \n        std::swap(std::get<0>(val),std::get<3>(val));\n        std::swap(std::get<2>(val),std::get<1>(val));\n        std::get<4>(val) = std::conj(std::get<4>(val));\n        return true;\n      }\n      return false; \n    }\n#else\n    // i < k\n    if( std::get<2>(val) < std::get<0>(val) ) std::swap(std::get<0>(val),std::get<2>(val) );    \n    // j < l\n    if( std::get<3>(val) < std::get<1>(val) ) std::swap(std::get<1>(val),std::get<3>(val) );    \n    // ik < jl\n    if( std::get<1>(val) < std::get<0>(val) ) { \n        std::swap(std::get<0>(val),std::get<1>(val) ); \n        std::swap(std::get<2>(val),std::get<3>(val) ); \n    } else if( (std::get<1>(val) == std::get<0>(val)) && ( std::get<3>(val) < std::get<2>(val) )) \n        std::swap(std::get<2>(val),std::get<3>(val) );    \n    return false;\n#endif\n\n  } \n  \n\n  // looks for the indexes of all equivalent terms in V2 and returns\n  // the smaller one (based on s4D ordering). \n  s4D<ValueType> SparseGeneralHamiltonian::find_smaller_equivalent_OneBar_for_integral_list(s4D<ValueType> ijkl)\n  {\n    std::vector<s4D<ValueType> > v;\n    find_equivalent_OneBar_for_integral_list(ijkl,v);\n    std::sort (v.begin(), v.end(), mySort);\n    return v[0]; \n  }\n\n  // looks for the indexes of all equivalent terms in V2_2bar and returns\n  // the smaller one (based on s4D ordering). \n  s4D<ValueType> SparseGeneralHamiltonian::find_smaller_equivalent_TwoBar_for_integral_list(s4D<ValueType> ijkl)\n  {\n    std::vector<s4D<ValueType> > v;\n    find_equivalent_TwoBar_for_integral_list(ijkl,v);\n    std::sort (v.begin(), v.end(), mySort);\n    return v[0]; \n  }\n\n  // generates all symmetry inequivalent integrals V2(indx,j,k,l) for a given indx.\n  // Vijkl is only meaningful for myComm->rank()==0.\n  bool SparseGeneralHamiltonian::SparseHamiltonianFromFactorization( int indx, std::vector<OrbitalType>& jkl, std::vector<ValueType>& intgs, const RealType cut)\n  {\n\n    if(!spinRestricted) {\n      app_error()<<\" Error: SparseGeneralHamiltonian::FullHamiltonianFromFactorization only implemented for spin restricted integrals. \\n\";\n      APP_ABORT(\"Error: SparseGeneralHamiltonian::FullHamiltonianFromFactorization only implemented for spin restricted integrals. \\n\");\n    }\n\n    if(!factorizedHamiltonian) {\n      app_error()<<\" Error:  Calling SparseGeneralHamiltonian::FullHamiltonianFromFactorization without factorized hamiltonian. \\n\"; \n      APP_ABORT(\"Error:  Calling SparseGeneralHamiltonian::FullHamiltonianFromFactorization without factorized hamiltonian. \\n\");\n    }\n\n    ValueType zero = ValueType(0);\n\n#if defined(QMC_COMPLEX)\n    APP_ABORT(\" Error: SparseGeneralHamiltonian::SparseHamiltonianFromFactorization doesn't yet work for std::complex matrix elements. \\n\");\n#endif\n\n    intgs.reserve(NMO*NMO);  // reasonable guess\n    intgs.clear();\n    jkl.reserve(3*NMO*NMO);\n    jkl.clear();\n\n    long cnter=0, npr = myComm->size(), rk = myComm->rank();\n    ValueType J1;\n\n    if(DiagHam.size() == 0) {\n      DiagHam.resize(NMO,NMO);\n      for(OrbitalType i=0; i<NMO; i++)\n      for(OrbitalType k=i; k<NMO; k++, cnter++) {\n        if( cnter%npr != rk ) continue;\n        DiagHam(i,k) =  H(i,k,k,i);\n        DiagHam(k,i) = DiagHam(i,k); \n#if defined(QMC_COMPLEX)\n        if(DiagHam(i,k).imag() > 1e-8) {\n            app_error()<<\" Error: Found complex diagonal on hamiltonian. \" <<i <<\" \" <<k <<\" \" <<DiagHam(i,k) <<std::endl;\n            APP_ABORT(\"Error: Found complex diagonal on hamiltonian.\");\n        }\n#endif\n      }\n      myComm->allreduce(DiagHam);      \n    }  \n\n#if defined(QMC_COMPLEX)\n// don't know how to do this quickly in complex case\n    auto ijkl = std::make_tuple(indx,0,0,0); \n    for(OrbitalType j=indx; j<NMO; j++)  {\n    for(OrbitalType k=indx; k<NMO; k++)  {\n    for(OrbitalType l=indx; l<NMO; l++, cnter++)  {\n      if( cnter%npr != rk ) continue;\n\n      // |<ij|kl>| <= sqrt( <ik|ki> * <lj|jl>  )  \n      if( std::sqrt( std::abs(DiagHam(indx,k)*DiagHam(l,j)) ) > cut ) {\n        std::get<1>(ijkl)=j;\n        std::get<2>(ijkl)=k;\n        std::get<3>(ijkl)=l;\n        // am I the smallest equivalent permutation?\n        if( ijkl <= std::forward_as_tuple(j,indx,l,k)  &&\n            ijkl <= std::forward_as_tuple(k,l,indx,j) &&\n            ijkl <= std::forward_as_tuple(l,k,j,indx) ) { \n          J1 = H(indx,j,k,l);\n          if(std::abs(J1) > cut) {\n             jkl.push_back(j);\n             jkl.push_back(k);\n             jkl.push_back(l);\n             intgs.push_back(J1);\n          }\n        }\n      }\n\n    }\n    }\n    }\n#else\n    for(OrbitalType j=indx; j<NMO; j++)  {\n    for(OrbitalType k=indx; k<NMO; k++)  {\n      OrbitalType l0 = (j==indx)?k:j;  \n      for(OrbitalType l=l0; l<NMO; l++, cnter++)  {\n        if( cnter%npr != rk ) continue;\n\n        // |<ij|kl>| <= sqrt( <ik|ki> * <lj|jl>  )  \n        if( std::sqrt( std::abs(DiagHam(indx,k)*DiagHam(l,j)) ) > cut ) {\n          J1 = H(indx,j,k,l);\n          if(std::abs(J1) > cut) {\n             jkl.push_back(j);\n             jkl.push_back(k);\n             jkl.push_back(l);\n             intgs.push_back(J1);\n          }\n        }\n      \n      }\n    }\n    }\n#endif\n\n    std::vector<int> lnint(1);\n    std::vector<int> gnint, disp;\n    lnint[0] = intgs.size();\n    if(myComm->rank()==0) {\n      gnint.resize(npr);\n    }\n    myComm->gather(lnint,gnint,0);\n\n    if(myComm->rank() == 0) {\n\n      int ntot = 0;\n      for(int i=0; i<gnint.size(); i++) ntot += gnint[i];\n\n      disp.resize(npr);\n      disp[0]=disp[1]=0;\n      for(int i=2; i<npr; i++) \n        disp[i] = disp[i-1] + gnint[i-1]; \n\n      int nint0 = gnint[0];\n      gnint[0]=0; // no need to gather with myself, this way I avoid the need for a second vector\n      intgs.resize(ntot);\n      myComm->gatherv(intgs.data(), intgs.data()+nint0, 0, gnint, disp, 0, myComm->getMPI());\n      for(int i=2; i<npr; i++) disp[i] *= 3;\n      for(int i=1; i<npr; i++) gnint[i] *= 3;\n      jkl.resize(3*ntot);\n      myComm->gatherv(jkl.data(), jkl.data()+3*nint0, 0, gnint, disp, 0, myComm->getMPI());\n\n    } else {\n      myComm->gatherv(intgs.data(), intgs.data(), intgs.size(), gnint, disp, 0, myComm->getMPI());\n      myComm->gatherv(jkl.data(), jkl.data(), jkl.size(), gnint, disp, 0, myComm->getMPI());\n      intgs.clear();\n      jkl.clear();\n    }\n  }\n\n  bool SparseGeneralHamiltonian::createHamiltonianForPureDeterminant(int walker_type, bool aa_only, std::map<IndexType,bool>& occ_a, std::map<IndexType,bool>& occ_b, std::vector<s1D<ValueType> >& hij, SPValueSMSpMat& Vijkl, const RealType cut)\n  {\n\n    // walker_type: 0-closed_shell density matrix, 1-ROHF/UHF density matrix, 2-GHF density matrix\n   \n\n    //  For alpha-alpha and beta-beta store two-bar integrals directly\n    //  For alpha-beta and beta-alpha, store one bar integrals \n    //\n    // Symmetries for real orbitals:\n    //  For two-bar integrals: <ij||kl> = <ji||lk> = <kl||ij> = <lk||ji>  \n    //                                  = -<ij||lk> = -<ji||kl> = -<kl||ji> = -<lk||ij> \n    //\n    //                                    \n    //  For one-bar integrals: <ij|kl> = <kj|il> = <il|kj> = <kl|ij>\n    //                                 = <ji|lk> = <li|jk> = <jk|li> = <lk|ji> \n    //\n    // Symmetries for Complex orbitals:\n    //  For two-bar integrals: <ij||kl> = <ji||lk> = <kl||ij>* = <lk||ji>*  \n    //                                  = -<ij||lk> = -<ji||kl> = -<kl||ji>* = -<lk||ij>* \n    //  For one-bar integrals: <ij|kl> = <ji|lk> = <kl|ij>* = <lk|ji>*\n    //  Notice that in this case:   <ij|kl> != <kj|il> and other permutations            \n    // \n\n    if(skip_V2) \n      APP_ABORT(\"Error: Calling SparseGeneralHamiltonian routines with skip_V2=yes. \\n\\n\\n\");\n\n#ifdef AFQMC_DEBUG\n    app_log()<<\" In SparseGeneralHamiltonian :: createHamiltonianForPureDeterminant.\" <<std::endl; \n#endif\n\n    if(!spinRestricted && walker_type==2) {\n      APP_ABORT(\"Error: GHF density matrix only implemented with spinRestricted integrals. \\n\");\n    }\n\n    hij.clear();\n\n    bool closed_shell = walker_type==0;\n\n    ValueType V;\n    std::vector<s4D<ValueType> > vs4D;  \n    s4D<ValueType> s;\n \n    // First count how many elements we need\n    int cnt1=0; \n    s2Dit it1 = H1.begin();\n    while(it1 != H1.end()) {\n      IndexType i,j;\n      std::tie (i,j,V) = *it1++;\n      if( std::abs(V) <= cut ) continue; \n      // I can assume that i<=j\n      if(spinRestricted) {\n        if( i == j ) {\n          if(occ_a[i]) cnt1++; \n          if(!closed_shell) if(occ_b[i+NMO]) cnt1++; \n        } else {\n          if(occ_a[i]) cnt1++; \n          if(occ_a[j]) cnt1++; \n          if(!closed_shell) if(occ_b[i+NMO]) cnt1++; \n          if(!closed_shell) if(occ_b[j+NMO]) cnt1++; \n        }\n      } else { \n        if( i == j ) { \n          if(occ_a[i] || occ_b[i]) cnt1++; \n        } else { \n          if(occ_a[i] || occ_b[i]) cnt1++; \n          if(occ_a[j] || occ_b[j]) cnt1++; \n        }  \n      }\n    }  \n\n    hij.resize(cnt1);\n    s1Dit ith = hij.begin();\n    it1 = H1.begin();\n    while(it1 != H1.end()) {\n      IndexType i,j;\n      std::tie (i,j,V) = *it1++;\n\n      if( std::abs(V) <= cut ) continue;\n\n      if(spinRestricted) {\n        if(closed_shell) {\n          if( i == j ) {  // ii alpha / ii beta \n            if(occ_a[i]) *ith++ = std::make_tuple( i*NMO+i , ValueType(2.0)*V );\n          } else  {  // ij/ji both (alpha/alpha) and (beta/beta)\n            if(occ_a[i]) *ith++ = std::make_tuple( i*NMO+j , ValueType(2.0)*V );\n            if(occ_a[j]) *ith++ = std::make_tuple( j*NMO+i , ValueType(2.0)*myconj(V) );\n          }\n        } else {\n          if( i == j ) {  // ii alpha / ii beta \n            if(occ_a[i]) *ith++ = std::make_tuple( Index2Mat(i,i,walker_type==2) , V );\n            if(occ_b[i+NMO]) *ith++ = std::make_tuple(Index2Mat(i+NMO,i+NMO,walker_type==2), V );\n          } else  {  // ij/ji both (alpha/alpha) and (beta/beta)\n            if(occ_a[i]) *ith++ = std::make_tuple( Index2Mat(i,j,walker_type==2), V );\n            if(occ_a[j]) *ith++ = std::make_tuple( Index2Mat(j,i,walker_type==2), myconj(V) );\n            if(occ_b[i+NMO]) *ith++ = std::make_tuple( Index2Mat(i+NMO,j+NMO,walker_type==2) , V );\n            if(occ_b[j+NMO]) *ith++ = std::make_tuple( Index2Mat(j+NMO,i+NMO,walker_type==2) , myconj(V) );\n          }\n        }\n      } else {\n        if( i == j ) {\n          if(occ_a[i] || occ_b[i]) *ith++ = std::make_tuple( Index2Mat(i,j,walker_type==2), V );\n        } else {\n          if(occ_a[i] || occ_b[i]) *ith++ = std::make_tuple( Index2Mat(i,j,walker_type==2), V );\n          if(occ_a[j] || occ_b[j]) *ith++ = std::make_tuple( Index2Mat(j,i,walker_type==2), myconj(V) );\n        }\n      }\n    }\n\n    std::sort (hij.begin(), hij.end(),mySort);\n    ith = std::unique(hij.begin(),hij.end(),myEqv);\n    if(ith != hij.end()) {\n      app_log()<<\" \\n\\n\\n*************************************************************\\n\"\n             <<\"  Error! Found repeated terms in construction of hij for Pure hamiltonian. \\n\"\n             <<\"  This should only happen if the integral file contains symmetry equivalent terms. \\n\"\n             <<\" *************************************************************\\n\\n\\n\";\n      return false;\n    }\n    // Done with hij\n    \n    long cnt2=0, number_of_terms=0; \n    // add one-bar terms (mixed spin) \n    if(factorizedHamiltonian) {\n\n        Timer.reset(\"Generic\");\n        Timer.start(\"Generic\");\n\n        ValueType zero = ValueType(0);\n\n        std::vector<s4D<ValueType> > vs4D;\n        vs4D.reserve(24);\n\n        cnt2=0; \n        long cnter=0, npr = myComm->size(), rk = myComm->rank();\n        OrbitalType i,j,k,l,j1,k1,l1,j2,k2,l2;\n        ValueType J1,J2,J3,J1a=zero,J2a=zero,J3a=zero,fct;\n\n        if(!spinRestricted)\n          APP_ABORT(\"Error: Need to finish implementation for !spinRestricted. \\n\\n\\n\");\n\n        DiagHam.resize(NMO,NMO); \n        for(IndexType i=0; i<NMO; i++) \n        for(IndexType k=i; k<NMO; k++, cnter++) { \n          if( cnter%npr != rk ) continue;\n          DiagHam(i,k) =  H(i,k,k,i);\n          DiagHam(k,i) = DiagHam(i,k); \n#if defined(QMC_COMPLEX)\n          if(DiagHam(i,k).imag() > 1e-8) {\n              app_error()<<\" Error: Found complex diagonal on hamiltonian. \" <<i <<\" \" <<k <<\" \" <<DiagHam(i,k) <<std::endl;\n              APP_ABORT(\"Error: Found complex diagonal on hamiltonian.\");\n          }\n#endif\n        }\n        myComm->allreduce(DiagHam);\n/*\n        if( isComplex(Diag(0,0)) )\n          MPI_Allreduce(MPI_IN_PLACE, Diag.data(),  2*Diag.size(), MPI_DOUBLE, MPI_SUM,\n                myComm->getMPI());\n        else\n          MPI_Allreduce(MPI_IN_PLACE, Diag.data(),  Diag.size(), MPI_DOUBLE, MPI_SUM,\n                myComm->getMPI());\n*/\n\n        int occi, occj, occk, occl; \n        cnter=0;\n        // Approximation: (similar to non factorized case)\n        //   - if <ij|kl>  <  cutoff1bar, set to zero \n        for(IndexType i=0; i<NMO; i++)  {\n        for(IndexType j=i; j<NMO; j++,cnter++)  {\n         if( cnter%npr != rk ) continue;\n         occi = (occ_a[i]||occ_b[i])?1:0;\n         occj = (occ_a[j]||occ_b[j])?1:0;\n        for(IndexType k=j; k<NMO; k++)  {\n         occk = (occ_a[k]||occ_b[k])?1:0;\n        for(IndexType l=k; l<NMO; l++)  {\n\n            occl = (occ_a[l]||occ_b[l])?1:0;\n            if( occi + occj + occk + occl < 2 ) continue; \n\n            // NOTE NOTE NOTE:\n            // <ik|ik> can get a complex component due to truncation error, eliminate it here\n\n            J1=J2=J3=zero; \n            // J1 = <ij|kl>   \n            // J1 < sqrt( <ik|ki> * <lj|jl> )  \n            if( std::sqrt( std::abs(DiagHam(i,k)*DiagHam(l,j)) ) > cutoff1bar ) { \n              J1 = H(i,j,k,l);  \n#if defined(QMC_COMPLEX)\n              if(i==k && j==l) J1 = ValueType(J1.real(),0);\n#endif\n            }\n\n            // J2 = <ij|lk> \n            if(i==j || l==k) {\n              J2=J1; \n            } else { \n              if( std::sqrt( std::abs(DiagHam(i,l)*DiagHam(k,j)) ) > cutoff1bar ) {\n                J2 = H(i,j,l,k);  \n#if defined(QMC_COMPLEX)\n                if(i==l && j==k) J2 = ValueType(J2.real(),0);\n#endif\n              }  \n            }\n\n            // J3 = <ik|jl> \n            if(j==k) {\n              J3=J1; \n            } else if(i==l) {\n              J3 = myconj(J1);\n            } else { \n              if( std::sqrt( std::abs(DiagHam(i,j)*DiagHam(l,k)) ) > cutoff1bar ) { \n                J3 = H(i,k,j,l);  \n#if defined(QMC_COMPLEX)\n                if(i==j && k==l) J3 = ValueType(J3.real(),0); \n#endif\n              }\n            }\n\n#if defined(QMC_COMPLEX)\n            //  J2a = <ik|lj>\n            if(l==j) {\n              J2a=J3;\n            } else if(i==k) {\n              J2a=J3;\n            } else if(k==j) {\n              J2a=J2;\n            } else if(i==l) {\n              J2a=std::conj(J2);\n            } else {\n              if( std::sqrt( std::abs(DiagHam(i,l)*DiagHam(j,k)) ) > cutoff1bar )\n                J2a = H(i,k,l,j);\n            }\n            \n            //  J3a = <il|jk> \n            if(l==j) {\n              J3a=J2;\n            } else if(i==k) {\n              J3a=std::conj(J2);\n            } else if(k==l) {\n              J3a=J3;\n            } else if(i==j) {\n              J3a=std::conj(J3);\n            } else {\n              if( std::sqrt( std::abs(DiagHam(i,j)*DiagHam(k,l)) ) > cutoff1bar )\n                J3a = H(i,l,j,k);\n            }\n\n            //  For complex, there are 3 extra non-symmetric terms:\n            //  J1a = <il|kj>\n            if(k==l) {\n              J1a=J2a;\n            } else if(i==j) {\n              J1a=std::conj(J2a);\n            } else if(j==k) {\n              J1a=J3a;\n            } else if(i==l) {\n              J1a=J3a;\n            } else if(l==j) {\n              J1a=J1;\n            } else if(i==k) {\n              J1a=std::conj(J1);\n            } else {\n              if( std::sqrt( std::abs(DiagHam(i,k)*DiagHam(j,l)) ) > cutoff1bar )\n                J1a = H(i,l,k,j);\n            }\n#endif\n\n\n\n            if( std::abs(J1)<cutoff1bar && std::abs(J2)<cutoff1bar && std::abs(J3)<cutoff1bar && std::abs(J1a)<cutoff1bar && std::abs(J2a)<cutoff1bar && std::abs(J3a)<cutoff1bar) continue; \n\n            vs4D.clear();\n            if(walker_type==0) {\n              find_all_contributions_to_hamiltonian_closed_shell(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D); \n            } else if(walker_type==1) {\n              if(spinRestricted) \n                find_all_contributions_to_hamiltonian_spinRestricted(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D); \n              else \n                find_all_contributions_to_hamiltonian_general(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D); \n            } else if(walker_type==2) {\n                find_all_contributions_to_hamiltonian_ghf(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D); \n            } else {\n              APP_ABORT(\" Error: Unknown walker type in createHamiltonianForPureDeterminant. \\n\"); \n            }\n            cnt2+=count_allowed_terms(vs4D,occ_a,occ_b);                    \n\n        }\n        }\n        }\n        }\n\n        myComm->allreduce(cnt2);\n        number_of_terms = cnt2;\n        app_log()<<\" Number of terms in hamiltonian: \" <<cnt2 <<std::endl;\n        Vijkl.reserve(cnt2);\n        cnt2=0; \n\n        cnter=0;\n        // Approximation: (similar to non factorized case)\n        //   - if <ij|kl>  <  cutoff1bar, set to zero \n        for(IndexType i=0; i<NMO; i++)  {\n        for(IndexType j=i; j<NMO; j++,cnter++)  {\n         if( cnter%npr != rk ) continue;\n         occi = (occ_a[i]||occ_b[i])?1:0;\n         occj = (occ_a[j]||occ_b[j])?1:0;\n        for(IndexType k=j; k<NMO; k++)  {\n         occk = (occ_a[k]||occ_b[k])?1:0;\n        for(IndexType l=k; l<NMO; l++)  {\n\n            occl = (occ_a[l]||occ_b[l])?1:0;\n            if( occi + occj + occk + occl < 2 ) continue; \n\n            J1=J2=J3=zero; \n            // J1 = <ij|kl>   \n            // J1 < sqrt( <ik|ki> * <lj|jl> )  \n            if( std::sqrt( std::abs(DiagHam(i,k)*DiagHam(l,j)) ) > cutoff1bar ) { \n              J1 = H(i,j,k,l);  \n#if defined(QMC_COMPLEX)\n              if(i==k && j==l) J1 = ValueType(J1.real(),0);\n#endif\n            }\n\n            // J2 = <ij|lk> \n            if(i==j || l==k) {\n              J2=J1; \n            } else { \n              if( std::sqrt( std::abs(DiagHam(i,l)*DiagHam(k,j)) ) > cutoff1bar ) { \n                J2 = H(i,j,l,k); \n#if defined(QMC_COMPLEX)\n                if(i==l && j==k) J2 = ValueType(J2.real(),0);\n#endif\n              } \n            }\n\n            // J3 = <ik|jl> \n            if(j==k) {\n              J3=J1; \n            } else if(i==l) {\n              J3 = myconj(J1);\n            } else { \n              if( std::sqrt( std::abs(DiagHam(i,j)*DiagHam(l,k)) ) > cutoff1bar ) {\n                J3 = H(i,k,j,l);  \n#if defined(QMC_COMPLEX)\n                if(i==j && k==l) J3 = ValueType(J3.real(),0);\n#endif\n              }\n            }\n\n#if defined(QMC_COMPLEX)\n            //  J2a = <ik|lj>\n            if(l==j) {\n              J2a=J3;\n            } else if(i==k) {\n              J2a=J3;\n            } else if(k==j) {\n              J2a=J2;\n            } else if(i==l) {\n              J2a=std::conj(J2);\n            } else {\n              if( std::sqrt( std::abs(DiagHam(i,l)*DiagHam(j,k)) ) > cutoff1bar )\n                J2a = H(i,k,l,j);\n            }\n            \n            //  J3a = <il|jk> \n            if(l==j) {\n              J3a=J2;\n            } else if(i==k) {\n              J3a=std::conj(J2);\n            } else if(k==l) {\n              J3a=J3;\n            } else if(i==j) {\n              J3a=std::conj(J3);\n            } else {\n              if( std::sqrt( std::abs(DiagHam(i,j)*DiagHam(k,l)) ) > cutoff1bar )\n                J3a = H(i,l,j,k);\n            }\n\n            //  For complex, there are 3 extra non-symmetric terms:\n            //  J1a = <il|kj>\n            if(k==l) {\n              J1a=J2a;\n            } else if(i==j) {\n              J1a=std::conj(J2a);\n            } else if(j==k) {\n              J1a=J3a;\n            } else if(i==l) {\n              J1a=J3a;\n            } else if(l==j) {\n              J1a=J1;\n            } else if(i==k) {\n              J1a=std::conj(J1);\n            } else {\n              if( std::sqrt( std::abs(DiagHam(i,k)*DiagHam(j,l)) ) > cutoff1bar )\n                J1a = H(i,l,k,j);\n            }\n            \n#endif\n\n            if( std::abs(J1)<cutoff1bar && std::abs(J2)<cutoff1bar && std::abs(J3)<cutoff1bar && std::abs(J1a)<cutoff1bar && std::abs(J2a)<cutoff1bar && std::abs(J3a)<cutoff1bar) continue; \n\n            vs4D.clear();\n            if(walker_type==0) {\n              find_all_contributions_to_hamiltonian_closed_shell(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n            } else if(walker_type==1) {\n              if(spinRestricted)\n                find_all_contributions_to_hamiltonian_spinRestricted(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n              else\n                find_all_contributions_to_hamiltonian_general(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n            } else if(walker_type==2) {\n                find_all_contributions_to_hamiltonian_ghf(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n            } else {\n              APP_ABORT(\" Error: Unknown walker type in createHamiltonianForPureDeterminant. \\n\");\n            }\n            cnt2+=add_allowed_terms(vs4D,occ_a,occ_b, Vijkl, true, walker_type==2);                    \n        }\n        }\n        }\n        }\n        myComm->barrier();\n        Timer.stop(\"Generic\");\n        app_log()<<\"Time to generate full Hamiltonian from factorized form: \" <<Timer.total(\"Generic\") <<std::endl; \n \n\n    } else {  //factorizedHamiltonian \n\n// for parallel algorithm with distributed matrices, count the number of terms\n// in the hamiltonian and divide evenly among nodes on the TG.\n// Then the cores on the local node work on the local segment \n\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      std::vector<s4D<ValueType> > vs4D;  \n      vs4D.reserve(48);\n      long N = spinRestricted?NMO:2*NMO;\n      // this should already exist, just in case\n      //if(IJ.size() == 0) \n        //generateIJ();\n\n// right now, the algorithm will add all the terms associated with a given quartet (ijkl)\n// at once. For the given ijkl, 3 (6) possible combinations can appear in the list for real (complex)  \n//  Only do the smallest of the 3 (6) possible combinations to avoid duplicated \n\n#if defined(QMC_COMPLEX)\n      std::vector<s4D<ValueType>> ineq_ijkl(6);\n      std::vector<bool> setJ(6);\n#else\n      std::vector<s4D<ValueType>> ineq_ijkl(3);\n      std::vector<bool> setJ(3);\n#endif\n\n      auto search_in_V2_IJ = [] (s4Dit it1, s4Dit it2,s4D<ValueType>& ijkl) { \n          s4Dit first = std::lower_bound(it1,it2,ijkl,\n             [] (const s4D<ValueType>& a, const s4D<ValueType>& b)\n             {return (std::get<2>(a)<std::get<2>(b)) ||\n                     (!(std::get<2>(b)<std::get<2>(a))&&(std::get<3>(a)<std::get<3>(b)));} );\n          if (first!=it2 && (std::get<2>(ijkl)==std::get<2>(*first)) && (std::get<3>(ijkl)==std::get<3>(*first))) \n            return std::make_tuple(std::get<4>(*first),true);\n          return std::make_tuple(ValueType(0),false);   \n      };  \n\n      ValueType zero = ValueType(0);\n      cnt2=0; \n      long npr = myComm->size(), rk = myComm->rank();\n      OrbitalType i,j,k,l,j1,k1,l1,j2,k2,l2;\n      ValueType J1,J2,J3,J1a=zero,J2a=zero,J3a=zero,fct;\n      long p_min=0, p_max=IJ.size()-1;\n// if integrals are distributed, \n//   distribute work over min_i/max_i sector among processors in the Hamiltonian TG\n      if(distribute_Ham) {\n        p_min = mapUT(static_cast<long>(min_i),static_cast<long>(min_i),N);\n        if( max_i != NMO)   // FIX FIX FIX with SPIN_RESTRICTED \n          p_max = mapUT(static_cast<long>(max_i),static_cast<long>(max_i),N);\n        // in this case, npr and rk are based on the extended TG (the one which includes all cores within a node)\n        npr = TG.getTGSize(); \n        rk = TG.getTGRank(); \n      }  \n      for(long p=p_min, nt=0; p<p_max; p++) {\n        // from n->m, I have all non-zero (k,l) for a given (i,j), with i<=j  \n        long n = IJ[p];\n        long m = IJ[p+1];\n        if(n==m) continue; \n        nt++;  // found good term, increase counter\n        if( nt%npr != rk ) continue;\n        s4Dit end = V2.begin()+m; \n        for(s4Dit it = V2.begin()+n; it != end; it++) {\n          // J1 = <ij|kl>   \n          // J2 = <ij|lk> or <ik|lj>   \n          // J3 = <ik|jl> or <il|jk>  \n          std::tie (i,j,k,l,J1) = *it;        \n\n          IndexType occi,occj,occk,occl;\n          occi = (occ_a[i]||occ_b[i])?1:0;\n          occj = (occ_a[j]||occ_b[j])?1:0;\n          occk = (occ_a[k]||occ_b[k])?1:0;\n          occl = (occ_a[l]||occ_b[l])?1:0;\n          if( occi+occj+occk+occl < 2) continue;  \n\n// the smallest permutation will satisfy  i<=j<=k<=l\n// so need to generte smallest of the other sectors, as long as the smallest one is \n// in the list. You need to make sure that the smallest one in the list is processed\n// Algorithm:\n//  1. If (i,j,k,l) is the smallest permutation, keep going\n//  2. If it is not, make a ordered list of all inequivalent permutations and record your position in the list \n//      a. For every term in the list before yours, \n//          i1. If the element is in the list, do nothing and continue to next element in V2.\n//          i2. If not in the list, set the value of the appropriate Jx to zero and test next element in permutation list  \n//  At the end you either do nothing because there is a permutationally inequivalent term smaller than you in the list, \n//  or you process the current term with all previous Js set to zero to avoid recalculating them.         \n\n\n          if( i<=j && i<=k && i<=l && j<=k && j<=l && k<=l) {\n            ineq_ijkl[0] = *it;\n            setJ[0]=true;\n            std::fill(setJ.begin()+1,setJ.end(),false);\n#if defined(QMC_COMPLEX)\n            ineq_ijkl[1] = std::forward_as_tuple(i,j,l,k,zero);\n            ineq_ijkl[2] = std::forward_as_tuple(i,k,j,l,zero);\n            ineq_ijkl[3] = std::forward_as_tuple(i,k,l,j,zero);\n            ineq_ijkl[4] = std::forward_as_tuple(i,l,j,k,zero);\n            ineq_ijkl[5] = std::forward_as_tuple(i,l,k,j,zero);\n#else\n            ineq_ijkl[1] = (j<=k)?(std::forward_as_tuple(i,j,l,k,zero)):(std::forward_as_tuple(i,k,l,j,zero));    \n            ineq_ijkl[2] = (k<=l)?(std::forward_as_tuple(i,k,j,l,zero)):(std::forward_as_tuple(i,l,j,k,zero));    \n#endif             \n          } else {\n\n            // make sure there is a smaller one on the list\n            // 1. generate smallest permutation\n            OrbitalType i_=i,j_=j,k_=k,l_=l;\n            if(j_<i_) std::swap(i_,j_); \n            if(k_<i_) std::swap(i_,k_); \n            if(l_<i_) std::swap(i_,l_); \n            if(k_<j_) std::swap(j_,k_); \n            if(l_<j_) std::swap(j_,l_); \n            if(l_<k_) std::swap(k_,l_); \n            std::fill(setJ.begin(),setJ.end(),false);\n            ineq_ijkl[0] = std::forward_as_tuple(i_,j_,k_,l_,zero);\n#if defined(QMC_COMPLEX)\n            ineq_ijkl[1] = std::forward_as_tuple(i_,j_,l_,k_,zero);\n            ineq_ijkl[2] = std::forward_as_tuple(i_,k_,j_,l_,zero);\n            ineq_ijkl[3] = std::forward_as_tuple(i_,k_,l_,j_,zero);\n            ineq_ijkl[4] = std::forward_as_tuple(i_,l_,j_,k_,zero);\n            ineq_ijkl[5] = std::forward_as_tuple(i_,l_,k_,j_,zero);\n#else\n            ineq_ijkl[1] = (j_<=k_)?(std::forward_as_tuple(i_,j_,l_,k_,zero)):(std::forward_as_tuple(i_,k_,l_,j_,zero));\n            ineq_ijkl[2] = (k_<=l_)?(std::forward_as_tuple(i_,k_,j_,l_,zero)):(std::forward_as_tuple(i_,l_,j_,k_,zero));\n#endif\n            bool process=false;\n            for(int i=0; i<ineq_ijkl.size(); i++) {\n              if( myEqv(ineq_ijkl[i],*it) ) {\n                std::get<4>(ineq_ijkl[i])=J1;\n                setJ[i]=true;\n                process=true;\n                break; \n              } else {  \n                long p0 = mapUT(std::get<0>(ineq_ijkl[i]),std::get<1>(ineq_ijkl[i]),N);\n                if(std::get<1>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[i]))) {\n                  process=false;\n                  break;\n                } else {\n                  setJ[i]=true;\n                  std::get<4>(ineq_ijkl[i])=zero;  \n                }               \n              }  \n            }\n            if(!process) continue;\n          }\n\n          // at this point, I know that:\n          //    1. this is a term I must process \n          //    2. the smallest permutation is in ineq_ijkl[0] with J1=std::get<4>(ineq_ijkl[0])\n          //    3. some values of Js might already be calculated based on setJ[k] \n          std::tie (i,j,k,l,J1) = ineq_ijkl[0];\n\n          // look for <ij|lk>\n          if(setJ[1]) {    \n            J2 = std::get<4>(ineq_ijkl[1]);\n          } else if(i==j || l==k) {\n            J2=J1; \n          } else { \n            long p0 = mapUT(i,std::get<1>(ineq_ijkl[1]),N);\n            J2 = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[1]));\n          }\n\n          // look for <ik|jl>\n          if(setJ[2]) {\n            J3 = std::get<4>(ineq_ijkl[2]);\n          } else if(j==k) {\n            J3=J1; \n          } else if(i==l) {\n            J3 = myconj(J1);  \n          } else { \n            long p0 = mapUT(i,std::get<1>(ineq_ijkl[2]),N);\n            J3 = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[2]));\n          }\n\n#if defined(QMC_COMPLEX)\n              \n            //  J2a = <ik|lj>\n            if(setJ[3]) {\n              J2a = std::get<4>(ineq_ijkl[3]);\n            } else if(l==j) {\n              J2a=J3;\n            } else if(i==k) {\n              J2a=J3;\n            } else if(k==j) {\n              J2a=J2;\n            } else if(i==l) {\n              J2a=std::conj(J2);\n            } else {\n              long p0 = mapUT(i,std::get<1>(ineq_ijkl[3]),N);\n              J2a = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[3]));\n            }\n            \n            //  J3a = <il|jk> \n            if(setJ[4]) {\n              J3a = std::get<4>(ineq_ijkl[4]);\n            } else if(l==j) {\n              J3a=J2;\n            } else if(i==k) {\n              J3a=std::conj(J2);\n            } else if(k==l) {\n              J3a=J3;\n            } else if(i==j) {\n              J3a=std::conj(J3);\n            } else {\n              long p0 = mapUT(i,std::get<1>(ineq_ijkl[4]),N);\n              J3a = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[4]));\n            }\n\n            //  For complex, there are 3 extra non-symmetric terms:\n            //  J1a = <il|kj>\n            if(setJ[5]) {\n              J1a = std::get<4>(ineq_ijkl[5]);\n            } else if(k==l) {\n              J1a=J2a;\n            } else if(i==j) {\n              J1a=std::conj(J2a);\n            } else if(j==k) {\n              J1a=J3a;\n            } else if(i==l) {\n              J1a=J3a;\n            } else if(l==j) {\n              J1a=J1;\n            } else if(i==k) {\n              J1a=std::conj(J1);\n            } else {\n              long p0 = mapUT(i,std::get<1>(ineq_ijkl[5]),N);\n              J1a = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[5]));\n            }\n\n#endif\n\n          vs4D.clear();\n          if(walker_type==0) {\n            find_all_contributions_to_hamiltonian_closed_shell(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n          } else if(walker_type==1) {\n            if(spinRestricted)\n              find_all_contributions_to_hamiltonian_spinRestricted(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n            else\n              find_all_contributions_to_hamiltonian_general(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n          } else if(walker_type==2) {\n              find_all_contributions_to_hamiltonian_ghf(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n          } else {\n            APP_ABORT(\" Error: Unknown walker type in createHamiltonianForPureDeterminant. \\n\");\n          }\n          cnt2+=count_allowed_terms(vs4D,occ_a,occ_b);                    \n        }\n      }\n\n      myComm->allreduce(cnt2);\nlong tmp_ = cnt2;\n      Vijkl.allocate(cnt2+1000);\n      cnt2=0; \n\n      for(long p=p_min, nt=0; p<p_max; p++) {\n        // from n->m, I have all non-zero (k,l) for a given (i,j), with i<=j  \n        long n = IJ[p];\n        long m = IJ[p+1];\n        if(n==m) continue; \n        nt++;  // found good term, increase counter\n        if( nt%npr != rk ) continue;\n        s4Dit end = V2.begin()+m; \n        for(s4Dit it = V2.begin()+n; it != end; it++) {\n\n          // for details see above\n          std::tie (i,j,k,l,J1) = *it;\n\n          IndexType occi,occj,occk,occl;\n          occi = (occ_a[i]||occ_b[i])?1:0;\n          occj = (occ_a[j]||occ_b[j])?1:0;\n          occk = (occ_a[k]||occ_b[k])?1:0;\n          occl = (occ_a[l]||occ_b[l])?1:0;\n          if( occi+occj+occk+occl < 2) continue;\n\n          if( i<=j && i<=k && i<=l && j<=k && j<=l && k<=l) {\n            ineq_ijkl[0] = *it;\n            setJ[0]=true;\n            std::fill(setJ.begin()+1,setJ.end(),false);\n#if defined(QMC_COMPLEX)\n            ineq_ijkl[1] = std::forward_as_tuple(i,j,l,k,zero);\n            ineq_ijkl[2] = std::forward_as_tuple(i,k,j,l,zero);\n            ineq_ijkl[3] = std::forward_as_tuple(i,k,l,j,zero);\n            ineq_ijkl[4] = std::forward_as_tuple(i,l,j,k,zero);\n            ineq_ijkl[5] = std::forward_as_tuple(i,l,k,j,zero);\n#else\n            ineq_ijkl[1] = (j<=k)?(std::forward_as_tuple(i,j,l,k,zero)):(std::forward_as_tuple(i,k,l,j,zero));    \n            ineq_ijkl[2] = (k<=l)?(std::forward_as_tuple(i,k,j,l,zero)):(std::forward_as_tuple(i,l,j,k,zero));    \n#endif             \n          } else {\n\n            OrbitalType i_=i,j_=j,k_=k,l_=l;\n            if(j_<i_) std::swap(i_,j_); \n            if(k_<i_) std::swap(i_,k_); \n            if(l_<i_) std::swap(i_,l_); \n            if(k_<j_) std::swap(j_,k_); \n            if(l_<j_) std::swap(j_,l_); \n            if(l_<k_) std::swap(k_,l_); \n            std::fill(setJ.begin(),setJ.end(),false);\n            ineq_ijkl[0] = std::forward_as_tuple(i_,j_,k_,l_,zero);\n#if defined(QMC_COMPLEX)\n            ineq_ijkl[1] = std::forward_as_tuple(i_,j_,l_,k_,zero);\n            ineq_ijkl[2] = std::forward_as_tuple(i_,k_,j_,l_,zero);\n            ineq_ijkl[3] = std::forward_as_tuple(i_,k_,l_,j_,zero);\n            ineq_ijkl[4] = std::forward_as_tuple(i_,l_,j_,k_,zero);\n            ineq_ijkl[5] = std::forward_as_tuple(i_,l_,k_,j_,zero);\n#else\n            ineq_ijkl[1] = (j_<=k_)?(std::forward_as_tuple(i_,j_,l_,k_,zero)):(std::forward_as_tuple(i_,k_,l_,j_,zero));\n            ineq_ijkl[2] = (k_<=l_)?(std::forward_as_tuple(i_,k_,j_,l_,zero)):(std::forward_as_tuple(i_,l_,j_,k_,zero));\n#endif\n            bool process=false;\n            for(int i=0; i<ineq_ijkl.size(); i++) {\n              if( myEqv(ineq_ijkl[i],*it) ) {\n                std::get<4>(ineq_ijkl[i])=J1;\n                setJ[i]=true;\n                process=true;\n                break; \n              } else {  \n                long p0 = mapUT(std::get<0>(ineq_ijkl[i]),std::get<1>(ineq_ijkl[i]),N);\n                if(std::get<1>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[i]))) {\n                  process=false;\n                  break;\n                } else {\n                  setJ[i]=true;\n                  std::get<4>(ineq_ijkl[i])=zero;  \n                }               \n              }  \n            }\n            if(!process) continue;\n          }\n\n          std::tie (i,j,k,l,J1) = ineq_ijkl[0];\n\n          // look for <ij|lk>\n          if(setJ[1]) {    \n            J2 = std::get<4>(ineq_ijkl[1]);\n          } else if(i==j || l==k) {\n            J2=J1; \n          } else { \n            long p0 = mapUT(i,std::get<1>(ineq_ijkl[1]),N);\n            J2 = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[1]));\n          }\n\n          // look for <ik|jl>\n          if(setJ[2]) {\n            J3 = std::get<4>(ineq_ijkl[2]);\n          } else if(j==k) {\n            J3=J1; \n          } else if(i==l) {\n            J3 = myconj(J1);  \n          } else { \n            long p0 = mapUT(i,std::get<1>(ineq_ijkl[2]),N);\n            J3 = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[2]));\n          }\n\n#if defined(QMC_COMPLEX)\n            //  J2a = <ik|lj>\n            if(setJ[3]) {\n              J2a = std::get<4>(ineq_ijkl[3]);\n            } else if(l==j) {\n              J2a=J3;\n            } else if(i==k) {\n              J2a=J3;\n            } else if(k==j) {\n              J2a=J2;\n            } else if(i==l) {\n              J2a=std::conj(J2);\n            } else {\n              long p0 = mapUT(i,std::get<1>(ineq_ijkl[3]),N);\n              J2a = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[3]));\n            }\n            \n            //  J3a = <il|jk> \n            if(setJ[4]) {\n              J3a = std::get<4>(ineq_ijkl[4]);\n            } else if(l==j) {\n              J3a=J2;\n            } else if(i==k) {\n              J3a=std::conj(J2);\n            } else if(k==l) {\n              J3a=J3;\n            } else if(i==j) {\n              J3a=std::conj(J3);\n            } else {\n              long p0 = mapUT(i,std::get<1>(ineq_ijkl[4]),N);\n              J3a = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[4]));\n            }\n\n            //  For complex, there are 3 extra non-symmetric terms:\n            //  J1a = <il|kj>\n            if(setJ[5]) {\n              J1a = std::get<4>(ineq_ijkl[5]);\n            } else if(k==l) {\n              J1a=J2a;\n            } else if(i==j) {\n              J1a=std::conj(J2a);\n            } else if(j==k) {\n              J1a=J3a;\n            } else if(i==l) {\n              J1a=J3a;\n            } else if(l==j) {\n              J1a=J1;\n            } else if(i==k) {\n              J1a=std::conj(J1);\n            } else {\n              long p0 = mapUT(i,std::get<1>(ineq_ijkl[5]),N);\n              J1a = std::get<0>(search_in_V2_IJ(V2.begin()+IJ[p0], V2.begin()+IJ[p0+1], ineq_ijkl[5]));\n            }\n#endif\n\n\n          vs4D.clear();\n          if(walker_type==0) {\n            find_all_contributions_to_hamiltonian_closed_shell(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n          } else if(walker_type==1) {\n            if(spinRestricted)\n              find_all_contributions_to_hamiltonian_spinRestricted(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n            else\n              find_all_contributions_to_hamiltonian_general(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n          } else if(walker_type==2) {\n              find_all_contributions_to_hamiltonian_ghf(aa_only,i,j,k,l,J1,J2,J3,J1a,J2a,J3a,cut,vs4D);\n          } else {\n            APP_ABORT(\" Error: Unknown walker type in createHamiltonianForPureDeterminant. \\n\");\n          }\n          cnt2+=add_allowed_terms(vs4D,occ_a,occ_b, Vijkl, true, walker_type==2);                    \n        }\n      }\n\n      myComm->barrier();\n      Timer.stop(\"Generic\");\n      app_log()<<\"Time to generate 2-body Hamiltonian: \" <<Timer.total(\"Generic\") <<std::endl;\n  \n    } // factrorizedHamiltonnian\n\n    Timer.reset(\"Generic\");\n    Timer.start(\"Generic\");\n    if(!communicate_Vijkl(Vijkl)) return false;\n    Timer.stop(\"Generic\");\n    app_log()<<\"Time to communicate Hamiltonian: \" <<Timer.total(\"Generic\") <<std::endl; \n\n    Timer.reset(\"Generic\");\n    Timer.start(\"Generic\");\n\n    if(!Vijkl.remove_repeated_and_compress(TG.getNodeCommLocal())) {\n      APP_ABORT(\"Error in call to SparseMatrix::remove_repeated(). \\n\");\n    }\n\n    Timer.stop(\"Generic\");\n    app_log()<<\"Time to remove_repeated_and_compress Hamiltonian: \" <<Timer.total(\"Generic\") <<std::endl;\n\n    return true;  \n\n  }\n\n  bool SparseGeneralHamiltonian::communicate_Vijkl(SPValueSMSpMat& Vijkl) \n  {\n\n    myComm->barrier();\n\n    if(head_of_nodes) {\n\n      int rk,npr;\n      long ptr,n0;\n      MPI_Comm_rank(MPI_COMM_HEAD_OF_NODES,&rk);\n      MPI_Comm_size(MPI_COMM_HEAD_OF_NODES,&npr);\n      n0 = Vijkl.size(); // my number of terms, always from zero to n0\n      ptr = n0; // position to copy elements to \n      std::vector<long> size(npr);\n      size[rk] = n0;\n      myComm->gsum(size,MPI_COMM_HEAD_OF_NODES);\n      long ntot = 0;\n      for(int i=0; i<npr; i++) ntot+=size[i];\n\napp_log()<<\"size: \" <<ntot <<\" \" <<n0 <<std::endl;\n\n      if(ntot > Vijkl.capacity()) {\n        app_error()<<\" Problems gathering hamiltonian. Capacity of std::vector is not sufficient: \" <<ntot <<\" \" <<Vijkl.capacity() <<\" \\n\";\n        return false;\n      }\n\napp_log()<<\" before resize: \" <<std::endl;\n      Vijkl.resize_serial(ntot);\napp_log()<<\" after resize: \" <<std::endl;\n\n      for(int i=0; i<npr; i++) {\n        if(i==rk) { // I send\n          myComm->bcast<int>(Vijkl.row_data(),n0,i,MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast<int>(Vijkl.column_data(),n0,i,MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast(Vijkl.values(),n0,i,MPI_COMM_HEAD_OF_NODES);\n        } else { // I reveive\n          myComm->bcast<int>(Vijkl.row_data()+ptr,size[i],i,MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast<int>(Vijkl.column_data()+ptr,size[i],i,MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast(Vijkl.values()+ptr,size[i],i,MPI_COMM_HEAD_OF_NODES);\n          ptr+=size[i];\n        }\n      }\napp_log()<<\" after bcasts: \" <<std::endl;\n    }\n    myComm->barrier();\n    return true; \n  }\n\n#ifndef QMC_COMPLEX\n  bool SparseGeneralHamiltonian::communicate_Vijkl(SPComplexSMSpMat& Vijkl)\n  {\n\n    myComm->barrier();\n\n    if(head_of_nodes) {\n\n      int rk,npr;\n      long ptr,n0;\n      MPI_Comm_rank(MPI_COMM_HEAD_OF_NODES,&rk);\n      MPI_Comm_size(MPI_COMM_HEAD_OF_NODES,&npr);\n      n0 = Vijkl.size(); // my number of terms, always from zero to n0\n      ptr = n0; // position to copy elements to \n      std::vector<long> size(npr);\n      size[rk] = n0;\n      myComm->gsum(size,MPI_COMM_HEAD_OF_NODES);\n      long ntot = 0;\n      for(int i=0; i<npr; i++) ntot+=size[i];\n      if(ntot > Vijkl.capacity()) {\n        app_error()<<\" Problems gathering hamiltonian. Capacity of std::vector is not sufficient: \" <<ntot <<\" \" <<Vijkl.capacity() <<\" \\n\";\n        return false;\n      }\n      Vijkl.resize_serial(ntot);\n      for(int i=0; i<npr; i++) {\n        if(i==rk) { // I send\n          myComm->bcast<int>(Vijkl.row_data(),n0,i,MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast<int>(Vijkl.column_data(),n0,i,MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast(Vijkl.values(),n0,i,MPI_COMM_HEAD_OF_NODES);\n        } else { // I reveive\n          myComm->bcast<int>(Vijkl.row_data()+ptr,size[i],i,MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast<int>(Vijkl.column_data()+ptr,size[i],i,MPI_COMM_HEAD_OF_NODES);\n          myComm->bcast(Vijkl.values()+ptr,size[i],i,MPI_COMM_HEAD_OF_NODES);\n          ptr+=size[i];\n        }\n      }\n    }\n    myComm->barrier();\n    return true;\n  }\n#endif\n\n  bool SparseGeneralHamiltonian::createHamiltonianForGeneralDeterminant (int walker_type, const ComplexMatrix& A,std::vector<s1D<ComplexType> >& hij, SPComplexSMSpMat& Vijkl, const RealType cut) \n  {\n\n    ComplexMatrix M,N;\n    const ComplexType one = ComplexType(1.0);\n    const ComplexType zero = ComplexType(0.0);\n    int npr = myComm->size(), rk = myComm->rank();\n\n    if(!spinRestricted) {\n      app_error()<<\" Error: SparseGeneralHamiltonian::createHamiltonianForGeneralDeterminant not implemented for UHF matrix elements. \\n\"; \n      return false;\n    }\n\n    if(walker_type == 0) {\n      app_log()<<\" Generating rotated hamiltonian matrices for RHF walker type. \\n\"; \n      if(!spinRestricted) {\n        app_error()<<\" Error: Can not generate RHF rotated hamiltonian from spin unrestricted hamiltonian. \\n\";\n        return false;\n      }\n      if(A.rows() < NMO || A.cols() != NAEA) {\n        app_error()<<\" Error: Incorrect dimensions in Slater Matrix in  SparseGeneralHamiltonian::createHamiltonianForGeneralDeterminant: \" <<A.rows() <<\" \" <<A.cols() <<std::endl;\n        return false;\n      }\n    } else if(walker_type == 1) {\n      app_log()<<\" Generating rotated hamiltonian matrices for ROHF/UHF walker type. \\n\"; \n      // both UHF/GHF wavefunctions allowed\n      if(A.rows() != 2*NMO || (A.cols() != NAEA && A.cols() != NAEA+NAEB)) {\n        app_error()<<\" Error: Incorrect dimensions in Slater Matrix in  SparseGeneralHamiltonian::createHamiltonianForGeneralDeterminant: \" <<A.rows() <<\" \" <<A.cols() <<std::endl;\n        return false;\n      }\n    } else if(walker_type==2) {\n      app_log()<<\" Generating rotated hamiltonian matrices for GHF walker type. \\n\"; \n      // both UHF/GHF wavefunctions allowed\n      if(A.rows() != 2*NMO || (A.cols() != NAEA && A.cols() != NAEA+NAEB)) {\n        app_error()<<\" Error: Incorrect dimensions in Slater Matrix in  SparseGeneralHamiltonian::createHamiltonianForGeneralDeterminant: \" <<A.rows() <<\" \" <<A.cols() <<std::endl;\n        return false;\n      }\n      app_error()<<\" Hamiltonian rotation not yet implemented for GHF type of walker. \\n\";\n      return false;\n    } else {\n      app_error()<<\" Error: Unacceptable walker_type in SparseGeneralHamiltonian::createHamiltonianForGeneralDeterminant: \" <<walker_type <<std::endl;\n      return false;\n    }\n\n    // 1-body part \n    if(walker_type == 0) {\n\n      ValueType V;\n      M.resize(NMO,NMO);\n      N.resize(NAEA,NMO);\n      M = 0;\n      N = 0;\n      s2Dit it1 = H1.begin();\n      while(it1 != H1.end()) {\n        IndexType i,j;\n        std::tie (i,j,V) = *it1++;\n        M(i,j) = ValueType(2.0)*V; //\n        if( i!=j ) M(j,i) = ValueType(2.0)*myconj(V);\n      }\n      DenseMatrixOperators::product_AhB(NAEA,NMO,NMO,one,A.data(),NAEA,M.data(),NMO,zero,N.data(),NMO);\n      int cnt=0;\n/*\n      for(int i=0; i<NMO; i++)\n       for(int j=0; j<NMO; j++)\n         std::cout<<i <<\" \" <<j <<\" \" <<M(i,j) <<\"\\n\";\n      for(int i=0; i<NAEA; i++)\n       for(int j=0; j<NMO; j++)\n         std::cout<<i <<\" \" <<j <<\" \" <<N(i,j) <<\"\\n\";\n      for(int i=0; i<NMO; i++)\n       for(int j=0; j<NAEA; j++)\n         std::cout<<i <<\" \" <<j <<\" \" <<A(i,j) <<\"\\n\";\n*/\n      for(int i=0; i<NAEA; i++)\n       for(int j=0; j<NMO; j++)\n        if( std::abs(N(i,j)) > cut ) cnt++;\n      hij.resize(cnt);\n      std::vector<s1D<ComplexType> >::iterator ith = hij.begin(); \n      for(int i=0; i<NAEA; i++)\n       for(int j=0; j<NMO; j++)\n        if( std::abs(N(i,j)) > cut ) *ith++ = std::make_tuple( i*NMO+j , N(i,j) ); \n\n    } else if(walker_type == 1) {\n\n      M.resize(NMO,NMO);\n      N.resize(NAEA,NMO);\n      M = 0;\n      N = 0;\n      ValueType V;\n\n      // alpha-alpha block\n      s2Dit it1 = H1.begin();\n      while(it1 != H1.end()) {\n        IndexType i,j;\n        std::tie (i,j,V) = *it1++;\n        if(i<NMO && j<NMO) {\n          M(i,j) = V; //\n          if( i!=j ) M(j,i) = myconj(V);\n        }\n      }\n      DenseMatrixOperators::product_AhB(NAEA,NMO,NMO,one,A.data(),A.cols(),M.data(),NMO,zero,N.data(),NMO);\n      int cnt=0;\n      for(int i=0; i<NAEA; i++)\n       for(int j=0; j<NMO; j++)\n        if( std::abs(N(i,j)) > cut ) cnt++;\n\n      // beta-beta block\n      ComplexMatrix Q(NAEB,NMO);\n      // for spinRestricted, M matrix is the same \n      if(!spinRestricted) {\n        M=0;\n        it1 = H1.begin();\n        while(it1 != H1.end()) {\n          IndexType i,j;\n          std::tie (i,j,V) = *it1++;\n          if(i>=NMO && j>=NMO) {\n            M(i,j) = V; //\n            if( i!=j ) M(j,i) = myconj(V);\n          }\n        }      \n      }\n      if( A.cols() == NAEA )\n        DenseMatrixOperators::product_AhB(NAEB,NMO,NMO,one,A.data()+A.cols()*NMO,A.cols(),M.data(),NMO,zero,Q.data(),NMO);\n      else if( A.cols() == NAEA+NAEB )\n        DenseMatrixOperators::product_AhB(NAEB,NMO,NMO,one,A.data()+A.cols()*NMO+NAEA,A.cols(),M.data(),NMO,zero,Q.data(),NMO);\n      else {\n        app_error()<<\" Error in rotation of hamiltonian. \\n\";  \n        return false;\n      }\n\n      for(int i=0; i<NAEB; i++)\n       for(int j=0; j<NMO; j++)\n        if( std::abs(Q(i,j)) > cut ) cnt++; \n\n      hij.resize(cnt);\n      std::vector<s1D<ComplexType> >::iterator ith = hij.begin();\n      for(int i=0; i<NAEA; i++)\n       for(int j=0; j<NMO; j++)\n        if( std::abs(N(i,j)) > cut ) *ith++ = std::make_tuple( i*NMO+j , N(i,j) );  \n      for(int i=0; i<NAEB; i++)\n       for(int j=0; j<NMO; j++)\n        if( std::abs(Q(i,j)) > cut ) *ith++ = std::make_tuple( NMO*NMO+i*NMO+j , Q(i,j) );  \n\n    } else if(walker_type == 2) {\n        APP_ABORT(\"Error: TODO: createHamiltonianForGeneralDeterminant not implemented for GHF walker type yet. \\n\\n\\n\");\n    }\n\n    std::sort (hij.begin(), hij.end(),mySort);\n    std::vector<s1D<ComplexType> >::iterator ith = std::unique(hij.begin(),hij.end(),myEqv);\n    if(ith != hij.end()) {\n      app_log()<<\" \\n\\n\\n*************************************************************\\n\"\n             <<\"  Error! Found repeated terms in construction of hij for General hamiltonian. \\n\"\n             <<\"  This should never happen. \\n\"\n             <<\" *************************************************************\\n\\n\\n\";\n      return false;\n    }\n\n\n    if(factorizedHamiltonian) {\n\n      int nnodes = TG.getTotalNodes(), nodeid = TG.getNodeID();\n      int ncores = TG.getTotalCores(), coreid = TG.getCoreID();\n  \n      // <ab||kl> = sum_n Qk(a,n) * Rl(b,n) - Rl(a,n)*Qk(b,n),\n      // where:\n      //   Qk(a,n) = sum_i conj(Amat(i,a)) * V2_fact(ik,n)\n      //   Rl(a,n) = sum_i conj(Amat(i,a)) * conj(V2_fact(li,n))\n      // For real build, Qk=Rk\n      //\n      // For parallelization, distribute (k,l) pairs over nodes.\n      // Build ahead of time Qk/Rl matrices in shared memory to reduce memory/setup time.\n      // Assemble integrals in parallel and fully distributed.\n      // Collect on all nodes.\n      //    - For distributed hamiltonians, you do not need to worry about keeping contiguous\n      //    segments of the hamiltonian. Only that the distribution over nodes is roughly equal.\n      //    Write a simple algorithm that balances the number of terms in a TG. \n      //  \n\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n//      SPComplexSMVector::pointer Qkptr;\n//      SPComplexSMVector::pointer Rlptr;\n//      SPComplexSMVector tQk;    \n//      tQk.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_tQk\"),TG.getNodeCommLocal());  \n//      SPComplexSMVector Qk;    \n//      Qk.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_Qk\"),TG.getNodeCommLocal());  \n      SPComplexSMVector Rl;    \n      Rl.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_Rl\"),TG.getNodeCommLocal());  \n\n      SPComplexSMSpMat SptQk;\n      SptQk.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_SptQk\"),TG.getNodeCommLocal());\n      SPComplexSMSpMat SpQk;\n      SpQk.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_SpQk\"),TG.getNodeCommLocal());\n      SPComplexSMSpMat SpRl;\n      SpRl.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_SpRl\"),TG.getNodeCommLocal());\n\n      if(useSpMSpM) {\n        APP_ABORT(\" Error: Not fully implemented. \\n\\n\\n\");\n      }  \n\n      int NMO2 = (walker_type == 0)?NMO:2*NMO;\n      int NAEA2 = (walker_type == 0)?NAEA:2*NAEA;\n      int ngrp = std::min(NMO2,nnodes);\n      std::vector<int> M_split(ngrp+1);\n\n      // split the orbitals among processors \n      FairDivide(NMO2,ngrp,M_split);\n\n      // Construct your set of Q(k,a,m), R(l,b,m)\n      int l0 = (nodeid<ngrp)?(M_split[nodeid]):(-1);\n      int lN = (nodeid<ngrp)?(M_split[nodeid+1]):(-1);\n      bool amIAlpha = true; // for simplicity, subset of bands must be either elpha or beta, not mixed\n      if( l0 < NMO && (lN-1) < NMO )\n        amIAlpha = true;\n      else if( l0 >= NMO && lN >= NMO )\n        amIAlpha = false;\n      else {\n        std::cerr<<\"l0, lN, nodeid, ngrp, NMO: \" <<l0 <<\" \" <<lN <<\" \" <<nodeid <<\" \" <<ngrp <<\" \" <<NMO <<std::endl;  \n        std::cerr<<\" Error: Current algorithm requires an even number of processors. \\n\\n\\n\";  \n        APP_ABORT(\" Error: Current algorithm requires an even number of processors. \\n\\n\\n\");  \n      }\n      int norb = lN-l0;\n      int maxnorb = 0;\n      for(int i=0; i<ngrp; i++) maxnorb = std::max(maxnorb,M_split[i+1]-M_split[i]);  \n      int nvec = V2_fact.cols();\n      // Rl(k, a, m), k:[0:NMO2], a:[0:NAEA], m:[0:nvec] \n      int mat_size = norb * NAEA * nvec; \n      if(nodeid < ngrp ) {\n        //Qk.resize(mat_size);  \n        if(!useSpMSpM)\n          Rl.resize(mat_size);  \n      }\n      if(coreid==0 && !useSpMSpM) std::fill(Rl.begin(),Rl.end(),SPComplexType(0.0));\n//      if(coreid==0) std::fill(Qk.begin(),Qk.end(),SPComplexType(0.0));\n\n      int bl0=-1, blN=-1;\n      int nwork = std::min(norb*NAEA,ncores);  \n      if(coreid <nwork)\n        if(amIAlpha)\n          std::tie(bl0, blN) = FairDivideBoundary(coreid,norb*NAEA,nwork);\n        else\n          std::tie(bl0, blN) = FairDivideBoundary(coreid,norb*NAEB,nwork);\n      // right now this is an upper bound\n      int nak = blN-bl0;\n\n      SpQk.setDims(norb*NAEA,nvec);\n      if(useSpMSpM) \n        SpRl.setDims(nvec,norb*NAEA);\n\n      std::vector<SPComplexType> vec(nvec);\n      std::vector<std::tuple<SPValueSMSpMat::intType,SPValueSMSpMat::intType,SPComplexType>> abkl;\n      int nmax = 1000000;\n      abkl.reserve(nmax);  \n\n      if(distribute_Ham) {\n        APP_ABORT(\" Finish THIS (43)!!! \\n\\n\\n\");\n      } else {\n\n/*\n        //   Q(k,a,n) = sum_i conj(Amat(i,a)) * V2_fact(ik,n)\n        //   R(l,a,n) = sum_i conj(Amat(i,a)) * conj(V2_fact(li,n))\n        if(walker_type == 0) {\n\n          long sz=0;\n          for(int l=l0, nt=0, cnt=0; l<lN; l++, nt++) {\n            int n_ = (l<NMO)?0:NMO;\n            int NEL = (l<NMO)?NAEA:NAEB;\n            for(int a=0; a<NEL; a++, cnt++) {\n              if( cnt%ncores != coreid ) continue;\n              std::fill(vec.begin(),vec.end(),SPComplexType(0,0));\n              for(int i=0; i<NMO; i++) {\n                int il = i*NMO+l-n_;\n                SPValueSMSpMat::intType n0 = *(V2_fact.row_index(il));\n                SPValueSMSpMat::intType n1 = *(V2_fact.row_index(il+1));\n                if(n1==n0) continue;\n                SPValueSMSpMat::intType nv = n1-n0;\n                const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                const SPValueSMSpMat::intPtr itLcol = V2_fact.column_data(n0);\n                const ComplexType Aiac = std::conj(A(i+n_,a));  // alpha/beta\n                for(int n=0; n<nv; n++)\n                  vec[itLcol[n]] += Aiac * itLval[n];\n              }\n              for(int n=0; n<nvec; n++)\n                if(std::abs(vec[n])>cut) sz++;\n            }\n          }\n          {\n            long c_ = sz;\n            MPI_Allreduce(&c_,&sz,1,MPI_LONG,MPI_SUM,TG.getNodeCommLocal());\n          }\n          SpQk.allocate(sz);\n          SpQk.barrier();\n          abkl.clear();\n          for(int l=l0, nt=0, cnt=0; l<lN; l++, nt++) {\n            int n_ = (l<NMO)?0:NMO;\n            int NEL = (l<NMO)?NAEA:NAEB;\n            for(int a=0; a<NEL; a++, cnt++) {\n              if( cnt%ncores != coreid ) continue;\n              std::fill(vec.begin(),vec.end(),SPComplexType(0,0));\n              for(int i=0; i<NMO; i++) {\n                int il = i*NMO+l-n_;\n                SPValueSMSpMat::intType n0 = *(V2_fact.row_index(il));\n                SPValueSMSpMat::intType n1 = *(V2_fact.row_index(il+1));\n                if(n1==n0) continue;\n                SPValueSMSpMat::intType nv = n1-n0;\n                const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                const SPValueSMSpMat::intPtr itLcol = V2_fact.column_data(n0);\n                const ComplexType Aiac = std::conj(A(i+n_,a));  // alpha/beta\n                for(int n=0; n<nv; n++)\n                  vec[itLcol[n]] += Aiac * itLval[n];\n              }\n              for(int n=0; n<nvec; n++)\n                if(std::abs(vec[n])>cut) {\n                  abkl.push_back( std::make_tuple(cnt, n, vec[n]) );\n                  if(abkl.size()==nmax) {\n                    SpQk.add(abkl,true);\n                    abkl.clear();\n                  }\n                }\n            }\n          }\n          if(abkl.size()>0) {\n            SpQk.add(abkl,true);\n            abkl.clear();\n          }\n          SpQk.compress(TG.getNodeCommLocal())\n\n#if defined(QMC_COMPLEX)\n// Think about how to calculate Rl quickly since now it is (nvec,norb*NAEA)\n// If it is not possible to evaluate quickly, then calculate it in Qk with (norb*NAEA,nvec)\n// form and then transpose it into Rl\n          for(int l=l0, nt=0, cnt=0; l<lN; l++, nt++) {\n            for(int a=0; a<NAEA; a++, cnt++) {\n              if( cnt%ncores != coreid ) continue;\n              std::fill(vec.begin(),vec.end(),SPComplexType(0,0));\n              for(int i=0; i<NMO; i++) {\n                int li = l*NMO+i;\n                SPValueSMSpMat::intType n0 = *(V2_fact.row_index(li));  \n                SPValueSMSpMat::intType n1 = *(V2_fact.row_index(li+1));\n                if(n1==n0) continue;\n                SPValueSMSpMat::intType nv = n1-n0;  \n                const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                const SPValueSMSpMat::intPtr itLcol =  V2_fact.column_data(n0);\n                const ComplexType Aiac = std::conj(A(i,a));\n                for(int n=0; n<nv; n++)   \n                  vec[itLcol[n]] += Aiac * std::conj(itLval[n]); \n                //Rlptr = Rl.values() + nt*NAEA*nvec + a*nvec; \n                //for(int n=0; n<nv; n++)   \n                //  Rlptr[itLcol[n]] += Aiac * std::conj(itLval[n]); \n              }\n              BLAS::axpy(nvec,SPComplexType(1.0),vec.data(),1,Rl.values()+cnt,norb*NAEA);\n            }    \n          }\n#else\n          if(useSpMSpM) {\n            SpRl.allocate(SpQk.size());\n            if(coreid==0) {\n              std::copy(SpQk.values(),SpQk.values()+SpQk.size(),SpRl.values());\n              std::copy(SpQk.column_data(),SpQk.column_data()+SpQk.size(),SpRl.row_data());\n              std::copy(SpQk.row_data(),SpQk.row_data()+SpQk.size(),SpRl.column_data());\n            }\n            SpRl.compress(TG.getNodeCommLocal());\n            SpRl.barrier();\n          } else {\n            if(coreid==0)\n              std::fill(Rl.begin(),Rl.end(),SPComplexType(0));\n            Rl.barrier();\n            int n0_,n1_;\n            assert(SpQk.size() >= ncores);\n            std::tie(n0_, n1_) = FairDivideBoundary(coreid,SpQk.size(),ncores);\n            SPComplexSMSpMat::iterator val = SpQk.vals_begin()+n0_;\n            SPComplexSMSpMat::iterator vend = SpQk.vals_begin()+n1_;\n            SPComplexSMSpMat::int_iterator col = SpQk.cols_begin()+n0_;\n            SPComplexSMSpMat::int_iterator row = SpQk.rows_begin()+n0_;\n            int ncol = SpQk.rows();\n            while(val != vend)\n              Rl[ (*(col++))*ncol + (*(row++)) ] = *(val++);\n            Rl.barrier();\n          }\n#endif\n        } else if(walker_type == 1) {  \n\n          assert(spinRestricted);\n*/\n/*\n          // Construct Qk[k,n,nvec]\n          for(int l=l0, nt=0, cnt=0; l<lN; l++, nt++) {\n            int n_ = (l<NMO)?0:NMO;\n            int NEL = (l<NMO)?NAEA:NAEB;\n            for(int a=0; a<NEL; a++, cnt++) {\n              if( cnt%ncores != coreid ) continue;\n              for(int i=0; i<NMO; i++) {\n                int il = i*NMO+l-n_;\n                SPValueSMSpMat::intType n0 = *(V2_fact.row_index(il));  \n                SPValueSMSpMat::intType n1 = *(V2_fact.row_index(il+1));\n                if(n1==n0) continue;\n                SPValueSMSpMat::intType nv = n1-n0;  \n                const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                const SPValueSMSpMat::intPtr itLcol = V2_fact.column_data(n0);\n                const ComplexType Aiac = std::conj(A(i+n_,a));  // alpha/beta\n                Qkptr = Qk.values() + nt*NEL*nvec + a*nvec; \n                for(int n=0; n<nv; n++)   \n                  Qkptr[itLcol[n]] += Aiac * itLval[n]; \n              }\n            }    \n          }\n*/ \n\n        if(walker_type == 0 || walker_type == 1) {\n          // Construct SpQk[k,n,nvec]\n          long sz=0;\n          for(int l=l0, nt=0, cnt=0; l<lN; l++, nt++) {\n            int n_ = (l<NMO)?0:NMO;\n            int NEL = (l<NMO)?NAEA:NAEB;\n            for(int a=0; a<NEL; a++, cnt++) {\n              if( cnt%ncores != coreid ) continue;\n              std::fill(vec.begin(),vec.end(),SPComplexType(0,0));\n              for(int i=0; i<NMO; i++) {\n                int il = i*NMO+l-n_;\n                SPValueSMSpMat::intType n0 = *(V2_fact.row_index(il));\n                SPValueSMSpMat::intType n1 = *(V2_fact.row_index(il+1));\n                if(n1==n0) continue;\n                SPValueSMSpMat::intType nv = n1-n0;\n                const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                const SPValueSMSpMat::intPtr itLcol = V2_fact.column_data(n0);\n                const ComplexType Aiac = std::conj(A(i+n_,a));  // alpha/beta\n                for(int n=0; n<nv; n++)\n                  vec[itLcol[n]] += Aiac * itLval[n];\n              }\n              for(int n=0; n<nvec; n++)\n                if(std::abs(vec[n])>cut) sz++;     \n            }\n          }\n          {\n            long c_ = sz; \n            MPI_Allreduce(&c_,&sz,1,MPI_LONG,MPI_SUM,TG.getNodeCommLocal());  \n          }\n          SpQk.allocate(sz);\n          SpQk.barrier();\n          abkl.clear();\n          for(int l=l0, nt=0, cnt=0; l<lN; l++, nt++) {\n            int n_ = (l<NMO)?0:NMO;\n            int NEL = (l<NMO)?NAEA:NAEB;\n            for(int a=0; a<NEL; a++, cnt++) {\n              if( cnt%ncores != coreid ) continue;\n              std::fill(vec.begin(),vec.end(),SPComplexType(0,0));\n              for(int i=0; i<NMO; i++) {\n                int il = i*NMO+l-n_;\n                SPValueSMSpMat::intType n0 = *(V2_fact.row_index(il));\n                SPValueSMSpMat::intType n1 = *(V2_fact.row_index(il+1));\n                if(n1==n0) continue;\n                SPValueSMSpMat::intType nv = n1-n0;\n                const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                const SPValueSMSpMat::intPtr itLcol = V2_fact.column_data(n0);\n                const ComplexType Aiac = std::conj(A(i+n_,a));  // alpha/beta\n                for(int n=0; n<nv; n++)\n                  vec[itLcol[n]] += Aiac * itLval[n];\n              }\n              for(int n=0; n<nvec; n++)\n                if(std::abs(vec[n])>cut) { \n                  abkl.push_back( std::make_tuple(cnt, n, vec[n]) );\n                  if(abkl.size()==nmax) {\n                    SpQk.add(abkl,true);\n                    abkl.clear();\n                  }\n                }\n            }\n          }\n          if(abkl.size()>0) {\n            SpQk.add(abkl,true);\n            abkl.clear();\n          }\n          SpQk.compress(TG.getNodeCommLocal());\n\n#if defined(QMC_COMPLEX)\n          if(!useSpMSpM) {\n            for(int k=l0, nt=0, cnt=0; k<lN; k++, nt++) {\n              int n_ = (k<NMO)?0:NMO;\n              int NEL = (k<NMO)?NAEA:NAEB;\n              for(int a=0; a<NEL; a++, cnt++) {\n                if( cnt%ncores != coreid ) continue;\n                std::fill(vec.begin(),vec.end(),SPComplexType(0,0));\n                for(int i=0; i<NMO; i++) {\n                  int ki = (k-n_)*NMO+i;\n                  SPValueSMSpMat::intType n0 = *(V2_fact.row_index(ki));  \n                  SPValueSMSpMat::intType n1 = *(V2_fact.row_index(ki+1));\n                  if(n1==n0) continue;\n                  int nv = n1-n0;  \n                  const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                  const SPValueSMSpMat::intPtr itLcol = V2_fact.column_data(n0);\n                  const ComplexType Aiac = std::conj(A(i+n_,a));  // alpha/beta\n                  for(int n=0; n<nv; n++)   \n                    vec[itLcol[n]] += Aiac * std::conj(itLval[n]); \n                }\n                BLAS::axpy(nvec,SPComplexType(1.0),vec.data(),1,Rl.values()+cnt,norb*NEL);\n              }    \n            }\n            Rl.barrier();\n          } else {  \n\n            // Construct SpRl[nvec,k,n]\n            sz=0;\n            for(int l=l0, nt=0, cnt=0; l<lN; l++, nt++) {\n              int n_ = (l<NMO)?0:NMO;\n              int NEL = (l<NMO)?NAEA:NAEB;\n              for(int a=0; a<NEL; a++, cnt++) {\n                if( cnt%ncores != coreid ) continue;\n                std::fill(vec.begin(),vec.end(),SPComplexType(0,0));\n                for(int i=0; i<NMO; i++) {\n                  int li = (l-n_)*NMO+i;\n                  SPValueSMSpMat::intType n0 = *(V2_fact.row_index(li));\n                  SPValueSMSpMat::intType n1 = *(V2_fact.row_index(li+1));\n                  if(n1==n0) continue;\n                  SPValueSMSpMat::intType nv = n1-n0;\n                  const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                  const SPValueSMSpMat::intPtr itLcol = V2_fact.column_data(n0);\n                  const ComplexType Aiac = std::conj(A(i+n_,a));  // alpha/beta\n                  for(int n=0; n<nv; n++)\n                    vec[itLcol[n]] += Aiac * std::conj(itLval[n]);\n                }\n                for(int n=0; n<nvec; n++)\n                  if(std::abs(vec[n])>cut) sz++;\n              }\n            }\n            {\n              long c_ = sz;\n              MPI_Allreduce(&c_,&sz,1,MPI_LONG,MPI_SUM,TG.getNodeCommLocal());\n            }\n            SpRl.allocate(sz);\n            SpRl.barrier();\n            abkl.clear();\n            for(int l=l0, nt=0, cnt=0; l<lN; l++, nt++) {\n              int n_ = (l<NMO)?0:NMO;\n              int NEL = (l<NMO)?NAEA:NAEB;\n              for(int a=0; a<NEL; a++, cnt++) {\n                if( cnt%ncores != coreid ) continue;\n                std::fill(vec.begin(),vec.end(),SPComplexType(0,0));\n                for(int i=0; i<NMO; i++) {\n                  int li = (l-n_)*NMO+i;\n                  SPValueSMSpMat::intType n0 = *(V2_fact.row_index(li));\n                  SPValueSMSpMat::intType n1 = *(V2_fact.row_index(li+1));\n                  if(n1==n0) continue;\n                  SPValueSMSpMat::intType nv = n1-n0;\n                  const SPValueSMSpMat::pointer itLval = V2_fact.values(n0);\n                  const SPValueSMSpMat::intPtr itLcol = V2_fact.column_data(n0);\n                  const ComplexType Aiac = std::conj(A(i+n_,a));  // alpha/beta\n                  for(int n=0; n<nv; n++)\n                    vec[itLcol[n]] += Aiac * std::conj(itLval[n]);\n                }\n                for(int n=0; n<nvec; n++)\n                  if(std::abs(vec[n])>cut) {\n                    abkl.push_back( std::make_tuple(n, cnt, vec[n]) );\n                    if(abkl.size()==nmax) {\n                      SpRl.add(abkl,true);\n                      abkl.clear();\n                    }\n                  }\n              }\n            }\n            if(abkl.size()>0) {\n              SpRl.add(abkl,true);\n              abkl.clear();\n            }\n            SpRl.compress(TG.getNodeCommLocal());\n          }\n#else\n          if(useSpMSpM) {\n            SpRl.allocate(SpQk.size());\n            if(coreid==0) {\n              std::copy(SpQk.values(),SpQk.values()+SpQk.size(),SpRl.values());\n              std::copy(SpQk.column_data(),SpQk.column_data()+SpQk.size(),SpRl.row_data());\n              std::copy(SpQk.row_data(),SpQk.row_data()+SpQk.size(),SpRl.column_data());\n            }\n            SpRl.compress(TG.getNodeCommLocal());\n            SpRl.barrier();\n          } else {\n            if(coreid==0)\n              std::fill(Rl.begin(),Rl.end(),SPComplexType(0));\n            Rl.barrier();\n            int n0_,n1_,sz_=SpQk.size();\n            assert(SpQk.size() >= ncores); \n            std::tie(n0_, n1_) = FairDivideBoundary(coreid,sz_,ncores);   \n            SPComplexSMSpMat::iterator val = SpQk.vals_begin()+n0_;\n            SPComplexSMSpMat::iterator vend = SpQk.vals_begin()+n1_;\n            SPComplexSMSpMat::int_iterator col = SpQk.cols_begin()+n0_; \n            SPComplexSMSpMat::int_iterator row = SpQk.rows_begin()+n0_; \n            int ncol = SpQk.rows();\n            while(val != vend) \n              Rl[ (*(col++))*ncol + (*(row++)) ] = *(val++);\n            Rl.barrier();   \n          }\n#endif\n        } else if(walker_type == 2) {  \n          APP_ABORT(\" Error in createHamiltonianForGeneralDeterminant: GHF not implemented. \\n\\n\\n\");\n        } else {\n          APP_ABORT(\" Error in createHamiltonianForGeneralDeterminant: Unknown walker_type. \\n\\n\\n\");\n        }\n\n      }  \n      SpQk.barrier();\n\n      // let the maximum message be 1 GB\n      int maxnt = std::max(1,static_cast<int>(std::floor(1024.0*1024.0*1024.0/sizeof(SPComplexType))));\n\n      std::vector<int> nkbounds;          // local bounds for communication  \n      std::vector<int> Qknum(nnodes);     // number of blocks per node\n      std::vector<int> Qksizes;           // number of terms and number of k vectors in block for all nodes\n      if(head_of_nodes) {\n        int n_=0, ntcnt=0, n0=0; \n        int NEL = (amIAlpha)?NAEA:NAEB;\n        for(int i=0; i<norb; i++) {\n          int ntt = *SpQk.row_index((i+1)*NEL) - *SpQk.row_index(i*NEL); \n          assert(ntt < maxnt);  \n          if(ntcnt+ntt > maxnt) {\n            nkbounds.push_back(ntcnt);\n            nkbounds.push_back(i-n0);\n            ntcnt=ntt;\n            n0=i;\n            n_++;\n          } else {\n            ntcnt+=ntt;\n          }   \n        }\n        if(ntcnt > 0) {\n          // push last block\n          n_++;\n          nkbounds.push_back(ntcnt);\n          nkbounds.push_back(norb-n0);\n        }\n\n        MPI_Allgather(&n_,1,MPI_INT,Qknum.data(),1,MPI_INT,MPI_COMM_HEAD_OF_NODES);\n\n        int ntt = std::accumulate(Qknum.begin(),Qknum.end(),0); \n        Qksizes.resize(2*ntt);\n\n        std::vector<int> cnts(nnodes);\n        std::vector<int> disp(nnodes);\n        int cnt=0;\n        for(int i=0; i<nnodes; i++) {\n          cnts[i] = Qknum[i]*2;\n          disp[i]=cnt;\n          cnt+=cnts[i];  \n        }\n        MPI_Allgatherv(nkbounds.data(),nkbounds.size(),MPI_INT,Qksizes.data(),cnts.data(),disp.data(),MPI_INT,MPI_COMM_HEAD_OF_NODES );\n\n      }\n\n      MPI_Bcast(Qknum.data(),nnodes,MPI_INT,0,TG.getNodeCommLocal());\n      int ntt = std::accumulate(Qknum.begin(),Qknum.end(),0); \n      if(!head_of_nodes)  \n        Qksizes.resize(2*ntt);\n      MPI_Bcast(Qksizes.data(),Qksizes.size(),MPI_INT,0,TG.getNodeCommLocal());\n\n// store {nterms,nk} for all nodes \n// use it to know communication pattern \n\n      int maxnk = 0;        // maximum number of k vectors in communication block \n      long maxqksize = 0;   // maximum size of communication block\n      for(int i=0; i<ntt; i++) {\n        if(Qksizes[2*i] > maxqksize) maxqksize = Qksizes[2*i];\n        if(Qksizes[2*i+1] > maxnk) maxnk = Qksizes[2*i+1];\n      }    \n\n      SPComplexSMVector Ta;\n      Ta.setup(head_of_nodes,std::string(\"SparseGeneralHamiltonian_Ta\"),TG.getNodeCommLocal());\n      Ta.resize(norb*NAEA*maxnk*NAEA);\n      Ta.barrier();\n       \n      // setup working sparse matrix  \n      SptQk.setDims(maxnk * NAEA, nvec);\n      SptQk.allocate(maxqksize+1000);\n\n      abkl.clear();  \n      std::vector<SPComplexSMSpMat::intType> rowI;\n      rowI.reserve( (maxnk*NAEA/ncores) + 1 );  \n\n      Timer.stop(\"Generic\");\n      app_log()<<\"Time to construct distributed rotated Cholesky vectors: \" <<Timer.total(\"Generic\") <<std::endl;\n\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      std::size_t sz=0;  \n      std::size_t sz1=0, sz2=0, sz3=0;  \n\n      // now calculate fully distributed matrix elements\n      for(int nn=0, nb=0, nkcum=0; nn<ngrp; nn++) {\n\n        // just checking\n        assert(nkcum==M_split[nn]);\n        if(M_split[nn+1]==M_split[nn]) continue;\n        int nblk = Qknum[nn]; \n        long ntermscum=0;\n        for( int bi = 0; bi < nblk; bi++, nb++) {\n          int nterms = Qksizes[2*nb];      // number of terms in block \n          int nk = Qksizes[2*nb+1];        // number of k-blocks in block\n          int k0 = nkcum;                  // first value of k in block\n          nkcum+=nk;                       \n          int kN = nkcum;                  // last+1 value\n          int NEL0 = (k0<NMO)?NAEA:NAEB;   // number of electrons in this spin block\n          assert(nk > 0 && nk <= maxnk );  // just checking\n\n/*\nTimer.reset(\"Generic2\");\nTimer.start(\"Generic2\");\n          if(head_of_nodes) {\n            if(nn == nodeid) {\n              std::copy(Qk.values()+bi*maxnk*NEL0*nvec,Qk.values()+(bi*maxnk+nk)*NEL0*nvec,tQk.values());\n            }  \n#if defined(AFQMC_SP)\n            MPI_Bcast(tQk.values(),nk*NEL0*nvec*2,MPI_FLOAT,nn,MPI_COMM_HEAD_OF_NODES);\n#else\n            MPI_Bcast(tQk.values(),nk*NEL0*nvec*2,MPI_DOUBLE,nn,MPI_COMM_HEAD_OF_NODES);\n#endif\n          } \n          Qk.barrier();\n\nTimer.stop(\"Generic2\");\napp_log()<<\"Time to Bcast tQk: \" <<nn <<\"  \" <<Timer.total(\"Generic2\") <<std::endl;\n*/\n\nTimer.reset(\"Generic2\");\nTimer.start(\"Generic2\");\n\n          if(head_of_nodes) {\n            if(nn == nodeid) {\n              long n0 = *SpQk.row_index( (k0-M_split[nn])*NEL0 );\n              long n1 = *SpQk.row_index( (k0-M_split[nn]+nk)*NEL0 );\n              int nt_ = static_cast<int>(n1-n0);\n              assert(ntermscum==n0);\n              assert(nt_==nterms);\n              SptQk.resize_serial(nterms);\n              std::copy(SpQk.values()+n0,SpQk.values()+n1,SptQk.values());\n              std::copy(SpQk.column_data()+n0,SpQk.column_data()+n1,SptQk.column_data());\n              for(int i=0, j=(k0-M_split[nn])*NEL0; i<=nk*NEL0; i++, j++)\n                SptQk.row_index()[i] = SpQk.row_index()[j]-n0;\n            }\n            MPI_Bcast(&nterms,1,MPI_LONG,nn,MPI_COMM_HEAD_OF_NODES);\n            SptQk.resize_serial(nterms);\n#if defined(AFQMC_SP)\n            MPI_Bcast(SptQk.values(),nterms*2,MPI_FLOAT,nn,MPI_COMM_HEAD_OF_NODES);\n#else\n            MPI_Bcast(SptQk.values(),nterms*2,MPI_DOUBLE,nn,MPI_COMM_HEAD_OF_NODES);\n#endif\n            MPI_Bcast(SptQk.column_data(),nterms,MPI_INT,nn,MPI_COMM_HEAD_OF_NODES);\n            MPI_Bcast(SptQk.row_index(),nk*NEL0+1,MPI_INT,nn,MPI_COMM_HEAD_OF_NODES);\n          }\n          SptQk.setCompressed();\n          SptQk.barrier();\n\n          // for safety, keep track of sum\n          ntermscum += static_cast<long>(nterms);\n\nTimer.stop(\"Generic2\");\napp_log()<<\"Time to Bcast SptRl: \" <<nn <<\"  \" <<Timer.total(\"Generic2\") <<std::endl;\n\nTimer.reset(\"Generic2\");\nTimer.start(\"Generic2\");\n\n          if(walker_type == 0) {\n\n            // <a,b | k,l> = Qa(ka,lb) - Qb(la,kb)\n            // Qa(ka,lb) = Q(k,a,:)*R(l,b,:)\n            //DenseMatrixOperators::product(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),tQk.values(),nvec,Rl.values()+bl0,norb*NAEA,SPComplexType(0),Qa.values()+bl0,norb*NAEA);\n            //Qa.barrier();\n            SparseMatrixOperators::product_SpMatM(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),SptQk.values(),SptQk.column_data(), SptQk.row_index(), Rl.values()+bl0,norb*NAEA,SPComplexType(0),Ta.values()+bl0,norb*NAEA);\n            SpQk.barrier();\n            SPComplexType four = SPComplexType(4.0);\n            SPComplexType two = SPComplexType(2.0);\n            for(int k=k0, ka=0; k<kN; k++) {\n              for(int a=0; a<NAEA; a++, ka++) {\n                for(int lb=bl0; lb<blN; lb++) { // lb = (l-l0)*NAEA+b  \n                  int b = lb%NAEA;\n                  if(b<a) continue;\n                  int l = lb/NAEA+l0;\n                  int la = (l-l0)*NAEA+a;  \n                  int kb = (k-k0)*NAEA+b;  \n                  SPComplexType qkalb = *(Ta.values() + ka*norb*NAEA + lb);  // Qa(ka,lb)   \n                  SPComplexType qlakb = *(Ta.values() + kb*norb*NAEA + la);  // Qa(kb,la)   \n                  if(std::abs( four*qkalb - two*qlakb ) > cut) sz++;\n                }\n              }\n            }\n\n          } else if(walker_type == 1) {\n\n            if( M_split[nn] < NMO && (M_split[nn+1]-1) < NMO ) {\n              // k is alpha\n            \n              if(amIAlpha) {  \n                // <a,b | k,l> = Qa(ka,lb) - Qb(la,kb)\n                // Qa(ka,lb) = Q(k,a,:)*R(l,b,:)\n//                DenseMatrixOperators::product(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),tQk.values(),nvec,Rl.values()+bl0,norb*NAEA,SPComplexType(0),Qa.values()+bl0,norb*NAEA);\n//                Qa.barrier();\n                SparseMatrixOperators::product_SpMatM(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),SptQk.values(),SptQk.column_data(), SptQk.row_index(), Rl.values()+bl0,norb*NAEA,SPComplexType(0),Ta.values()+bl0,norb*NAEA);\n                Ta.barrier();\n                for(int k=k0, ka=0; k<kN; k++) {\n                  for(int a=0; a<NAEA; a++, ka++) {\n                    for(int lb=bl0; lb<blN; lb++) { // lb = (l-l0)*NAEA+b  \n                      int b = lb%NAEA;\n                      if(b<=a) continue;\n                      int l = lb/NAEA+l0;\n                      int la = (l-l0)*NAEA+a;\n                      int kb = (k-k0)*NAEA+b;\n                      SPComplexType qkalb = *(Ta.values() + ka*norb*NAEA + lb);  // Qa(ka,lb)   \n                      SPComplexType qlakb = *(Ta.values() + kb*norb*NAEA + la);  // Qa(kb,la)   \n                      if(std::abs( qkalb - qlakb ) > cut) sz++;\n                      if(std::abs( qkalb - qlakb ) > cut) sz1++;\n                    }\n                  }\n                }\n              } else {\n                // <a,b | k,l> = Qa(ka,lb) = Q(k,a,:)*R(l,b,:) \n                //DenseMatrixOperators::product(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),tQk.values(),nvec,Rl.values()+bl0,norb*NAEB,SPComplexType(0),Qa.values()+bl0,norb*NAEB);\n                SparseMatrixOperators::product_SpMatM(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),SptQk.values(),SptQk.column_data(), SptQk.row_index(), Rl.values()+bl0,norb*NAEB,SPComplexType(0),Ta.values()+bl0,norb*NAEB);\n                Ta.barrier();\n                for(int k=k0, ka=0; k<kN; k++) {\n                  for(int a=0; a<NAEA; a++, ka++) {\n                    for(int lb=bl0; lb<blN; lb++) { // lb = (l-l0)*NAEB+b  \n                      SPComplexType qkalb = *(Ta.values() + ka*norb*NAEB + lb);  // Qa(ka,lb)   \n                      if(std::abs( qkalb ) > cut) sz++;\n                      if(std::abs( qkalb ) > cut) sz2++;\n                    }\n                  }\n                }\n              }  \n\n            } else if(M_split[nn] >= NMO && M_split[nn+1] >= NMO) {\n              // k is beta           \n              if(!amIAlpha) {\n                // <a,b | k,l> = Qa(ka,lb) - Qb(la,kb)\n                // Qa(ka,lb) = Q(k,a,:)*R(l,b,:)                \n                //DenseMatrixOperators::product(nk*NAEB,int(blN-bl0),nvec,SPComplexType(1.0),tQk.values(),nvec,Rl.values()+bl0,norb*NAEB,SPComplexType(0),Qa.values()+bl0,norb*NAEB);\n                //Qa.barrier();\n                SparseMatrixOperators::product_SpMatM(nk*NAEB,int(blN-bl0),nvec,SPComplexType(1.0),SptQk.values(),SptQk.column_data(), SptQk.row_index(), Rl.values()+bl0,norb*NAEB,SPComplexType(0),Ta.values()+bl0,norb*NAEB);\n                Ta.barrier();\n                for(int k=k0, ka=0; k<kN; k++) {\n                  for(int a=0; a<NAEB; a++, ka++) {\n                    for(int lb=bl0; lb<blN; lb++) { // lb = (l-l0)*NAEB+b  \n                      int b = lb%NAEB;\n                      if(b<=a) continue;\n                      int l = lb/NAEB+l0;\n                      int la = (l-l0)*NAEB+a;\n                      int kb = (k-k0)*NAEB+b;\n                      SPComplexType qkalb = *(Ta.values() + ka*norb*NAEB + lb);  // Qa(ka,lb)   \n                      SPComplexType qlakb = *(Ta.values() + kb*norb*NAEB + la);  // Qa(kb,la)   \n                      if(std::abs( qkalb - qlakb ) > cut) sz++;\n                      if(std::abs( qkalb - qlakb ) > cut) sz3++;\n                    }\n                  }\n                }\n              }  \n            } else {\n              APP_ABORT(\" Error: This should not happen. \\n\\n\\n\");\n            } \n\n          } else if(walker_type == 2) {\n            APP_ABORT(\" Error in createHamiltonianForGeneralDeterminant: GHF not implemented. \\n\\n\\n\");\n          }\nMPI_Barrier(myComm->getMPI()); // to measure actual time\nTimer.stop(\"Generic2\");\napp_log()<<\"Time to calculate Qab: \" <<nn <<\"  \" <<Timer.total(\"Generic2\") <<std::endl;\n\n        }\n\n      }\n\n      std::size_t sz_local=sz;\n      MPI_Allreduce(&sz_local,&sz,1,MPI_UNSIGNED_LONG,MPI_SUM,myComm->getMPI()); \n      // not yet distributed, later on decide distribution here based on FairDivide\n      // and allocate appropriately          \n      app_log()<<\"Number of terms in Vijkl: \" <<sz <<\" \" <<sz*(sizeof(ValueType)+sizeof(int)*2)/1024.0/1024.0 <<\" MB\" <<std::endl;\n      Vijkl.allocate(sz);\n\n      std::size_t sz_1=0, sz_2=0, sz_3=0;\n\n      // now calculate fully distributed matrix elements\n      for(int nn=0, nb=0, nkcum=0; nn<ngrp; nn++) {\n\n        assert(nkcum==M_split[nn]);\n        if(M_split[nn+1]==M_split[nn]) continue;\n        int nblk = Qknum[nn];\n        long ntermscum=0;\n        for( int bi = 0; bi < nblk; bi++, nb++) {\n          int nterms = Qksizes[2*nb];      // number of terms in block \n          int nk = Qksizes[2*nb+1];        // number of k-blocks in block\n          int k0 = nkcum;                  // first value of k in block\n          nkcum+=nk;\n          int kN = nkcum;                  // last+1 value\n          int NEL0 = (k0<NMO)?NAEA:NAEB;   // number of electrons in this spin block\n          assert(nk > 0 && nk <= maxnk );  // just checking\n\n/*\n          if(head_of_nodes) {\n            if(nn == nodeid) {\n              std::copy(Qk.values()+bi*maxnk*NEL0*nvec,Qk.values()+(bi*maxnk+nk)*NEL0*nvec,tQk.values());\n            }  \n#if defined(AFQMC_SP)\n            MPI_Bcast(tQk.values(),nk*NEL0*nvec*2,MPI_FLOAT,nn,MPI_COMM_HEAD_OF_NODES);\n#else\n            MPI_Bcast(tQk.values(),nk*NEL0*nvec*2,MPI_DOUBLE,nn,MPI_COMM_HEAD_OF_NODES);\n#endif\n          } \n          tQk.barrier();\n\n*/\n\nTimer.reset(\"Generic2\");\nTimer.start(\"Generic2\");\n\n          assert(nblk==1);\n          if(head_of_nodes) {\n            if(nn == nodeid) {\n              long n0 = *SpQk.row_index( (k0-M_split[nn])*NEL0 );\n              long n1 = *SpQk.row_index( (k0-M_split[nn]+nk)*NEL0 );\n              int nt_ = static_cast<int>(n1-n0);\n              assert(ntermscum==n0);\n              assert(nt_==nterms);\n              SptQk.resize_serial(nterms);\n              std::copy(SpQk.values()+n0,SpQk.values()+n1,SptQk.values());\n              std::copy(SpQk.column_data()+n0,SpQk.column_data()+n1,SptQk.column_data());\n              for(int i=0, j=(k0-M_split[nn])*NEL0; i<=nk*NEL0; i++, j++)\n                SptQk.row_index()[i] = SpQk.row_index()[j]-n0;\n            }\n            MPI_Bcast(&nterms,1,MPI_LONG,nn,MPI_COMM_HEAD_OF_NODES);\n            SptQk.resize_serial(nterms);\n#if defined(AFQMC_SP)\n            MPI_Bcast(SptQk.values(),nterms*2,MPI_FLOAT,nn,MPI_COMM_HEAD_OF_NODES);\n#else\n            MPI_Bcast(SptQk.values(),nterms*2,MPI_DOUBLE,nn,MPI_COMM_HEAD_OF_NODES);\n#endif\n            MPI_Bcast(SptQk.column_data(),nterms,MPI_INT,nn,MPI_COMM_HEAD_OF_NODES);\n            MPI_Bcast(SptQk.row_index(),nk*NEL0+1,MPI_INT,nn,MPI_COMM_HEAD_OF_NODES);\n          }\n          SptQk.setCompressed();\n          SptQk.barrier();\n\nTimer.stop(\"Generic2\");\napp_log()<<\"Time to Bcast SptQk: \" <<nn <<\"  \" <<Timer.total(\"Generic2\") <<std::endl;\n\n          // for safety, keep track of sum\n          ntermscum += static_cast<long>(nterms);\n\n//*/\n          if(walker_type == 0) {\n\n            // <a,b | k,l> = Qa(ka,lb) - Qb(la,kb)\n            // Qa(ka,lb) = 4*Q(k,a,:)*R(l,b,:)\n            //DenseMatrixOperators::product(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),tQk.values(),nvec,Rl.values()+bl0,norb*NAEA,SPComplexType(0),Qa.values()+bl0,norb*NAEA);\n            //Qa.barrier();\n            SparseMatrixOperators::product_SpMatM(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),\n                     SptQk.values(),SptQk.column_data(), SptQk.row_index(),\n                     Rl.values()+bl0,norb*NAEA,SPComplexType(0),Ta.values()+bl0,norb*NAEA);\n            Ta.barrier();\n            SPComplexType four = SPComplexType(4.0);\n            SPComplexType two = SPComplexType(2.0);\n            for(int k=k0, ka=0; k<kN; k++) {\n              for(int a=0; a<NAEA; a++, ka++) {\n                for(int lb=bl0; lb<blN; lb++) { // lb = (l-l0)*NAEA+b  \n                  int b = lb%NAEA;\n                  if(b<a) continue;\n                  int l = lb/NAEA+l0;\n                  int la = (l-l0)*NAEA+a;\n                  int kb = (k-k0)*NAEA+b;\n                  SPComplexType qkalb = *(Ta.values() + ka*norb*NAEA + lb);  // Qa(ka,lb)   \n                  SPComplexType qlakb = *(Ta.values() + kb*norb*NAEA + la);  // Qa(kb,la)   \n                  if(std::abs( four*qkalb - two*qlakb ) > cut) {\n                    abkl.push_back( std::make_tuple(a*NMO+k, b*NMO+l, 2.0*(four*qkalb - two*qlakb)) );\n                    if(abkl.size()==nmax) {\n                      Vijkl.add(abkl,true);\n                      abkl.clear();\n                    } \n                  }\n                }\n              }\n            }\n\n          } else if(walker_type == 1) {\n\n            if( M_split[nn] < NMO && (M_split[nn+1]-1) < NMO ) {\n              // k is alpha\n\n              if(amIAlpha) {\n                // <a,b | k,l> = Qa(ka,lb) - Qb(la,kb)\n                // Qa(ka,lb) = Q(k,a,:)*R(l,b,:)\n              \n/*\n                Qa.barrier();\nTimer.reset(\"Generic2\");\nTimer.start(\"Generic2\");\n\n                DenseMatrixOperators::product(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),tQk.values(),nvec,Rl.values()+bl0,norb*NAEA,SPComplexType(0),Qa.values()+bl0,norb*NAEA);\n                Qa.barrier();\n\n\nTimer.stop(\"Generic2\");\napp_log()<<\"Time for dense DGEMM : \" <<nn <<\"  \" <<Timer.total(\"Generic2\") <<std::endl;\n*/\n/*\n              SptQk.toOneBase();\n              SpRl.toOneBase();\n              if(coreid==0)  \n                std::fill(Ta.begin(),Ta.end(),SPComplexType(0));  \n              SpRl.barrier();\nTimer.reset(\"Generic2\");\nTimer.start(\"Generic2\");\n\n#if defined(HAVE_MKL)\n              if(coreid < nk*NAEA) {\n                // partition on the fly\n                int nwork = std::min(nk*NAEA,ncores);\n                int ak0,akN;\n                std::tie(ak0, akN) = FairDivideBoundary(coreid,nk*NAEA,nwork);\n\n                char TRANS = 'N';\n                int M_ = (akN-ak0), N_ = norb*NAEA;\n                int ldc_ = nk*NAEA;\n                rowI.resize(M_+1);\n                SPComplexSMSpMat::intPtr r = SptQk.row_index(ak0);\n                int p0 = *r; \n                std::vector<SPComplexSMSpMat::intType>::iterator it=rowI.begin();\n                std::vector<SPComplexSMSpMat::intType>::iterator itend=rowI.end();\n                int i_=0;\n                for(; it!=itend; it++,r++) \n                  *it = *r-p0+1;\n                // CAREFUL!!! C matrix in fortran format\n                mkl_zcsrmultd (&TRANS, &M_ , &N_ , &nvec , \n                        SptQk.values(p0-1), SptQk.column_data(p0-1) , rowI.data(), //SptQk.row_index(ak0), \n                        SpRl.values()  , SpRl.column_data()  , SpRl.row_index() , \n                        Ta.values()+ak0, &ldc_ );     \n              }\n              SptQk.barrier();  \n#else \n              APP_ABORT(\" Error: Requires MKL. Code alternative (Talk to Miguel) \\n\\n\\n\");\n#endif\n\nTimer.stop(\"Generic2\");\napp_log()<<\"Time for zcsrmultd : \" <<nn <<\"  \" <<Timer.total(\"Generic2\") <<std::endl;\n\n              if(coreid==0) {\n                for(int a=0; a<nk*NAEA; a++)\n                  for(int b=0; b<norb*NAEA; b++)\n                    if( std::abs(*(Qa.values()+a*norb*NAEA+b) - *(Ta.values()+b*nk*NAEA+a) ) > 5e-5)\n                      app_log()<<\" Diff: \" <<a <<\" \" <<b <<\" \" <<*(Qa.values()+a*norb*NAEA+b) <<\" \" <<*(Ta.values()+b*nk*NAEA+a) <<std::endl;\n              }  \n\n              SptQk.toZeroBase();\n              SpRl.toZeroBase();\n              SpQk.barrier();  \n*/\n///*\n//Timer.reset(\"Generic2\");\n//Timer.start(\"Generic2\");\n              SparseMatrixOperators::product_SpMatM(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),\n                            SptQk.values(),SptQk.column_data(), SptQk.row_index(), \n                            Rl.values()+bl0,norb*NAEA,SPComplexType(0),Ta.values()+bl0,norb*NAEA);\n              SpQk.barrier();  \n//Timer.stop(\"Generic2\");\n//app_log()<<\"Time for sparse DGEMM : \" <<nn <<\"  \" <<Timer.total(\"Generic2\") <<std::endl;\n//              SpQk.barrier();  \n\n//              if(coreid==0) {\n//                for(int a=0; a<nk*NAEA; a++)\n//                  for(int b=0; b<norb*NAEA; b++)\n//                    if( std::abs(*(Qa.values()+a*norb*NAEA+b) - *(Ta.values()+a*norb*NAEA+b) ) > 1e-6)\n//                      app_log()<<\" Diff: \" <<a <<\" \" <<b <<\" \" <<*(Qa.values()+a*norb*NAEA+b) <<\" \" <<*(Ta.values()+a*norb*NAEA+b) <<std::endl;\n//              }\n\n//*/\n                for(int k=k0, ka=0; k<kN; k++) {\n                  for(int a=0; a<NAEA; a++, ka++) {\n                    for(int lb=bl0; lb<blN; lb++) { // lb = (l-l0)*NAEA+b  \n                      int b = lb%NAEA;\n                      if(b<=a) continue;\n                      int l = lb/NAEA+l0;\n                      int la = (l-l0)*NAEA+a;\n                      int kb = (k-k0)*NAEA+b;\n                      SPComplexType qkalb = *(Ta.values() + ka*norb*NAEA + lb);  // Qa(ka,lb)   \n                      SPComplexType qlakb = *(Ta.values() + kb*norb*NAEA + la);  // Qa(kb,la)\n                      if(std::abs( qkalb - qlakb ) > cut) {\n                        sz_1++;\n                        abkl.push_back( std::make_tuple(a*NMO+k, b*NMO+l, 2.0*(qkalb - qlakb)) );\n                        if(abkl.size()==nmax) {\n                          Vijkl.add(abkl,true);\n                          abkl.clear();\n                        }\n                      }\n                    }\n                  }\n                }\n\n              } else {\n                //DenseMatrixOperators::product(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),tQk.values(),nvec,Rl.values()+bl0,norb*NAEB,SPComplexType(0),Qa.values()+bl0,norb*NAEB);\n                SparseMatrixOperators::product_SpMatM(nk*NAEA,int(blN-bl0),nvec,SPComplexType(1.0),\n                            SptQk.values(),SptQk.column_data(), SptQk.row_index(),\n                            Rl.values()+bl0,norb*NAEB,SPComplexType(0),Ta.values()+bl0,norb*NAEB);\n                Ta.barrier();\n                for(int k=k0, ka=0; k<kN; k++) {\n                  for(int a=0; a<NAEA; a++, ka++) {\n                    for(int lb=bl0; lb<blN; lb++) { // lb = (l-l0)*NAEB+b  \n                      int b = lb%NAEB;\n                      int l = lb/NAEB+l0;\n                      SPComplexType qkalb = *(Ta.values() + ka*norb*NAEB + lb);  // Qa(ka,lb)   \n                      if(std::abs( qkalb ) > cut) { \n                        sz_2++;\n                        abkl.push_back( std::make_tuple(a*NMO+k, NMO*NMO+b*NMO+l-NMO, 2.0*(qkalb)));\n                        if(abkl.size()==nmax) {\n                          Vijkl.add(abkl,true);\n                          abkl.clear();\n                        }\n                      }\n                    }\n                  }\n                }\n              }  \n\n            } else if(M_split[nn] >= NMO && M_split[nn+1] >= NMO) {\n              // k is beta\n              if(!amIAlpha) {\n                // <a,b | k,l> = Qa(ka,lb) - Qb(la,kb)\n                // Qa(ka,lb) = Q(k,a,:)*R(l,b,:)\n                //DenseMatrixOperators::product(nk*NAEB,int(blN-bl0),nvec,SPComplexType(1.0),tQk.values(),nvec,Rl.values()+bl0,norb*NAEB,SPComplexType(0),Qa.values()+bl0,norb*NAEB);\n                //Qa.barrier(); \n                SparseMatrixOperators::product_SpMatM(nk*NAEB,int(blN-bl0),nvec,SPComplexType(1.0),\n                            SptQk.values(),SptQk.column_data(), SptQk.row_index(),\n                            Rl.values()+bl0,norb*NAEB,SPComplexType(0),Ta.values()+bl0,norb*NAEB);\n                Ta.barrier(); \n                for(int k=k0, ka=0; k<kN; k++) {\n                  for(int a=0; a<NAEB; a++, ka++) {\n                    for(int lb=bl0; lb<blN; lb++) { // lb = (l-l0)*NAEB+b  \n                      int b = lb%NAEB;\n                      if(b<=a) continue;\n                      int l = lb/NAEB+l0;\n                      int la = (l-l0)*NAEB+a;\n                      int kb = (k-k0)*NAEB+b;\n                      SPComplexType qkalb = *(Ta.values() + ka*norb*NAEB + lb);  // Qa(ka,lb)   \n                      SPComplexType qlakb = *(Ta.values() + kb*norb*NAEB + la);  // Qa(kb,la)   \n                      if(std::abs( qkalb - qlakb ) > cut) {\n                        sz_3++;\n                        abkl.push_back( std::make_tuple(NMO*NMO+a*NMO+k-NMO, NMO*NMO+b*NMO+l-NMO, 2.0*(qkalb - qlakb)) );\n                        if(abkl.size()==nmax) {\n                          Vijkl.add(abkl,true);\n                          abkl.clear();\n                        }\n                      } \n                    }\n                  }\n                }\n              }\n            } else {\n              APP_ABORT(\" Error: This should not happen. \\n\\n\\n\");\n            }\n\n          } else if(walker_type == 2) {\n            APP_ABORT(\" Error in createHamiltonianForGeneralDeterminant: GHF not implemented. \\n\\n\\n\");\n          }\n        } // bi < nblk\n      }\n\n      if(abkl.size()>0) {\n        Vijkl.add(abkl,true);\n        abkl.clear();\n      }\n      SpQk.barrier();\n      myComm->barrier();\n\n      //debug debug debug\n      assert(sz1==sz_1);\n      assert(sz2==sz_2);\n      assert(sz3==sz_3);\n\n      Timer.stop(\"Generic\");\n      app_log()<<\"Time to calculate distributed Hamiltonian: \" <<Timer.total(\"Generic\") <<std::endl;\n\n      if(!communicate_Vijkl(Vijkl)) return false;\n      myComm->barrier();\n\n      Timer.stop(\"Generic\");\n      app_log()<<\"Time to generate 2-body Hamiltonian: \" <<Timer.total(\"Generic\") <<std::endl;\n\n    } else {\n\n        // Alg:\n        // 0. Erase V2. Create full sparse hamiltonian (with symmetric terms)  \n        // 1. swap indexes, (i,j) <-> (k,l)\n        // 2. sort\n        // 3. use A*M*A algorithm\n        \n\n        Timer.reset(\"Generic\");\n        Timer.reset(\"Generic1\");\n        Timer.reset(\"Generic2\");\n        //Timer.reset(\"Generic3\");\n        Timer.start(\"Generic\");\n\n        std::vector<s4D<ValueType> > v2sym;\n        v2sym.reserve(24);\n        \n        // to improve memory usage, split work based on index\n        // and only generate the (i,j) sectors that you need locally \n        if(V2_full.size()==0) {\n        \n          app_log()<<\" Generating V2_full in SparseGeneralHamiltonian::createHamiltonianForGeneralDeterminant() \\n\";\n          Timer.start(\"Generic1\"); \n          long cnter=0;\n          if(head_of_nodes) {\n            for(s4Dit it = V2.begin(); it != V2.end(); it++) {\n              find_equivalent_OneBar_for_integral_list(*it,v2sym);\n              for(int n=0; n<v2sym.size(); n++) {\n                IndexType i0,j0,k0,l0;\n                ValueType V;\n                std::tie (i0,j0,k0,l0,V) = v2sym[n];\n                if(k0<l0) continue;\n                cnter++;\n              }\n            }\n          }\n\n          V2_full.reserve(cnter);\n\n          if(head_of_nodes) {\n            for(s4Dit it = V2.begin(); it != V2.end(); it++) {\n              find_equivalent_OneBar_for_integral_list(*it,v2sym);\n              for(int n=0; n<v2sym.size(); n++) {\n                IndexType i0,j0,k0,l0;\n                ValueType V;\n                std::tie (i0,j0,k0,l0,V) = v2sym[n];\n                if(k0<l0) continue;\n                V2_full.push_back(v2sym[n]);\n                std::swap( std::get<0>( V2_full.back() ), std::get<2>( V2_full.back() ) );\n                std::swap( std::get<1>( V2_full.back() ), std::get<3>( V2_full.back() ) );\n              }\n            }\n            std::sort (V2_full.begin(), V2_full.end(),mySort);\n          }\n          v2full_transposed=true;\n          myComm->barrier();\n          IndexType k0=std::get<0>(V2_full[0]); \n          IndexType l0=std::get<1>(V2_full[0]); \n          IndexType i,j,k,l;\n          ValueType V;\n          if(spinRestricted)\n            KL.reserve(NMO*(NMO+1)/2+1);\n          else\n            KL.reserve(2*NMO*(2*NMO+1)/2+1);\n          KL.push_back(0);\n          long nt=0;\n          for(s4Dit it = V2_full.begin(); it != V2_full.end(); it++, nt++) {\n            std::tie (k,l,i,j,V) = *it;\n            if(k!=k0 || l!=l0) {\n              KL.push_back(nt);\n              k0=k;\n              l0=l;\n            }\n          }\n          KL.push_back(nt);\n          Timer.stop(\"Generic1\"); \n          app_log()<<\" Time to generate V2_full: \" <<Timer.total(\"Generic1\") <<std::endl; \n          app_log()<<\" Size of V2_full: \" <<V2_full.size()*sizeof(s4D<ValueType>)/1024.0/1024.0 <<\" MB. \" <<std::endl;\n\n        }\n        if(!v2full_transposed) {\n          Timer.reset(\"Generic1\");\n          Timer.start(\"Generic1\");\n          if(head_of_nodes) { \n            //swap         \n            for(s4Dit it = V2_full.begin(); it != V2_full.end(); it++) { \n              std::swap( std::get<0>(*it), std::get<2>(*it));  \n              std::swap( std::get<1>(*it), std::get<3>(*it));  \n            }\n            std::sort (V2_full.begin(), V2_full.end(),mySort); \n          }\n          myComm->barrier();\n          IndexType k0=std::get<0>(V2_full[0]);\n          IndexType l0=std::get<1>(V2_full[0]);\n          IndexType i,j,k,l;\n          ValueType V;\n          KL.clear();\n          KL.reserve(2*NMO*(2*NMO+1)/2+1);\n          KL.push_back(0);\n          long nt=0;\n          for(s4Dit it = V2_full.begin(); it != V2_full.end(); it++, nt++) {\n            std::tie (k,l,i,j,V) = *it;\n            if(k!=k0 || l!=l0) {\n              KL.push_back(nt);\n              k0=k;\n              l0=l;\n            }\n          }\n          KL.push_back(nt);\n          v2full_transposed=true;\n          Timer.stop(\"Generic1\");\n          app_log()<<\" Time to transpose and sort V2_full: \" <<Timer.total(\"Generic1\") <<std::endl; \n          app_log()<<\" Size of V2_full: \" <<V2_full.size()*sizeof(s4D<ValueType>)/1024.0/1024.0 <<\" MB. \" <<std::endl;\n        }\n\n      int nrows = (walker_type==0)?NMO:2*NMO;\n      int ncols = (walker_type==2)?(NAEA+NAEB):NAEA;\n      ComplexMatrix Ac(nrows,ncols);\n      // Ac = myconj(A) \n      for(int i=0; i<nrows; i++)    \n       for(int j=0; j<ncols; j++)    \n        Ac(i,j) = myconj(A(i,j));\n      if(NAEA>NAEB && walker_type==1) {\n        // fill empty spaces with 0\n        for(int i=NMO; i<2*NMO; i++)\n         for(int j=NAEB; j<NAEA; j++)\n          Ac(i,j) = ComplexType(0); \n      }\n      double fct=1.0, fct2=1.0;        \n      ComplexMatrix::iterator itQa,itQb,itQab, itQab2, itAia, itAib, itAja, itAjb; \n      ComplexMatrix::iterator itBia, itBib, itBja, itBjb; \n      ComplexType s1, s2, s3, s4, s5, s6;\n      long cnter = 0;\n      ComplexMatrix Qa,Qb,Qab,Qab2;\n\n      if(walker_type == 0) {\n  \n        Qa.resize(NAEA,NAEA);\n        for(int p=0, nt=0; p<KL.size()-1; p++, nt++) {\n          if( nt%npr != rk ) continue;\n          long n = KL[p];\n          long m = KL[p+1];\n          IndexType k0 = std::get<0>(V2_full[n]);\n          IndexType l0 = std::get<1>(V2_full[n]);\n          IndexType i,j,k,l;\n          ValueType V,fct; \n          Qa=0;\n          // from n->m, I have all non-zero (i,j) for a given (k,l), with k<=l\n          for(s4Dit it = V2_full.begin()+n; it != V2_full.begin()+m; it++) {\n            std::tie (k,l,i,j,V) = *it;\n            // V (a,b,k,l) = sum_i,j A*(i,a) * A*(j,b) * V(i,j,k,l)\n            if(k0==l0) fct=1.0;\n            else fct=2.0;\n            itAia = Ac.begin(i);\n            itAja = Ac.begin(j);\n            for(int a=0; a<NAEA; a++, itAia++, itAja++) {\n             s1 = fct*ValueType(4.0)*V*(*itAia);\n             s2 = fct*ValueType(2.0)*V*(*itAja);\n             itQa = Qa.begin(a);\n             itAib = Ac.begin(i);\n             itAjb = Ac.begin(j);          \n             for(int b=0; b<NAEA; b++, itQa++, itAib++, itAjb++) \n               *itQa += ( s1*(*itAjb) - s2*(*itAib) );\n            } \n          } \n          // Now I have Q(a,b,k0,l0);\n          for(int a=0; a<NAEA; a++)\n           for(int b=0; b<NAEA; b++) \n             if(std::abs(Qa(a,b)) > cut) cnter++; \n        }\n\n      } else if(walker_type == 1) {\n\n        Qa.resize(NAEA,NAEA);  // Vaa(a,b,k,l)   k<=l\n        Qb.resize(NAEA,NAEA);  // Vbb(a,b,k,l)   k<=l\n        Qab.resize(NAEA,NAEA); // Vab(a,b,k,l)   k<=l\n        Qab2.resize(NAEA,NAEA); // Vab(a,b,l,k)  k<=l\n        int del = (walker_type==2)?NAEA:0;\n        for(int p=0, nt=0; p<KL.size()-1; p++, nt++) {\n          if( nt%npr != rk ) continue;\n          long n = KL[p];\n          long m = KL[p+1];\n          IndexType k0 = std::get<0>(V2_full[n]);\n          IndexType l0 = std::get<1>(V2_full[n]);\n          IndexType i,j,k,l;\n          ValueType V,fct; \n          if(spinRestricted) {      \n            Qa=0;\n            Qb=0;\n            Qab=0;\n            Qab2=0;\n            // from n->m, I have all non-zero (i,j) for a given (k,l), with k<=l\n            for(s4Dit it = V2_full.begin()+n; it != V2_full.begin()+m; it++) {\n              std::tie (k,l,i,j,V) = *it;\n              // V (a,b,k,l) = sum_i,j A*(i,a) * A*(j,b) * V(i,j,k,l)\n              if(k0==l0) fct=0.0;\n              else fct=2.0;\n              itAia = Ac.begin(i);\n              itBia = Ac.begin(i+NMO)+del;\n              itAja = Ac.begin(j);\n              itBja = Ac.begin(j+NMO)+del;\n              for(int a=0; a<NAEA; a++, itAia++, itAja++, itBia++, itBja++) {\n                s1 = fct*V*(*itAia);  // Coul aa\n                s2 = fct*V*(*itAja);  // Exch aa\n                s3 = fct*V*(*itBia);  // Coul bb\n                s4 = fct*V*(*itBja);  // Exch bb\n                s5 = 2.0*V*(*itAia);  // Coul ab (kl) \n                s6 = 2.0*V*(*itAja);  // Coul ab (lk) \n                itQa = Qa.begin(a);\n                itQab = Qab.begin(a);\n                itQab2 = Qab2.begin(a);\n                itQb = Qb.begin(a);\n                itAib = Ac.begin(i);\n                itAjb = Ac.begin(j);          \n                itBib = Ac.begin(i+NMO)+del;\n                itBjb = Ac.begin(j+NMO)+del;          \n                for(int b=0; b<NAEA; b++, itQa++, itQb++, itQab++, itQab2++, itAib++, itAjb++, itBib++, itBjb++) { \n                  *itQa += ( s1*(*itAjb) - s2*(*itAib) );\n                  *itQb += ( s3*(*itBjb) - s4*(*itBib) );\n                  *itQab += s5*(*itBjb);\n                  *itQab2 += s6*(*itBib);\n                }\n              }\n            }\n            // Now I have Q(a,b,k0,l0);\n            for(int a=0; a<NAEA; a++)\n             for(int b=0; b<NAEA; b++) { \n               if(std::abs(Qa(a,b)) > cut) cnter++; \n               if(std::abs(Qb(a,b)) > cut) cnter++; \n               if(std::abs(Qab(a,b)) > cut) cnter++; \n               if(std::abs(Qab2(a,b)) > cut && k0!=l0) cnter++; \n             }\n\n          } else {\n            app_error()<<\" Error: Finish implementation. \\n\\n\\n\";\n            return false;\n            if(k0 < NMO && l0 < NMO) { // aa \n              for(int a=0; a<NAEA; a++, itAia++, itAja++) {\n               s1 = fct*4.0*V*(*itAia);\n               s2 = fct*2.0*V*(*itAja);\n               itQa = Qa.begin(a);\n               itAib = Ac.begin(i);\n               itAjb = Ac.begin(j);\n               for(int b=0; b<NAEA; b++, itQa++, itAib++, itAjb++)\n                 *itQa += ( s1*(*itAjb) - s2*(*itAib) );\n              }\n            } else if(k0 >= NMO && l0 >= NMO) { // bb \n               app_error()<<\" Error: Finish implementation. \\n\\n\\n\";\n               return false;\n            } else if(k0 < NMO && l0 >= NMO) { // ab\n               app_error()<<\" Error: Finish implementation. \\n\\n\\n\";\n               return false;\n            } else {\n               app_error()<<\" Error: Problems in createHamiltonianForGeneralDeterminant. \\n\";\n               return false;\n            }\n          } // spinRestricted\n        } // KL loop\n\n      } else if(walker_type == 2) {\n        APP_ABORT(\"Error: TODO: createHamiltonianForGeneralDeterminant not implemented for GHF walker type yet. \\n\\n\\n\");\n      }\n\n      myComm->allreduce(cnter);\n      Vijkl.allocate(cnter+1000);\n\n      if(walker_type == 0) {\n\n        for(int p=0, nt=0; p<KL.size()-1; p++, nt++) {\n          if( nt%npr != rk ) continue;\n          long n = KL[p];\n          long m = KL[p+1];\n          IndexType k0 = std::get<0>(V2_full[n]);\n          IndexType l0 = std::get<1>(V2_full[n]);\n          IndexType i,j,k,l;\n          ValueType V,fct; \n          Qa=0;\n          // from n->m, I have all non-zero (i,j) for a given (k,l), with k<=l\n          for(s4Dit it = V2_full.begin()+n; it != V2_full.begin()+m; it++) {\n            std::tie (k,l,i,j,V) = *it;\n            // V (a,b,k,l) = sum_i,j A*(i,a) * A*(j,b) * V(i,j,k,l)\n            if(k0==l0) fct=1.0;\n            else fct=2.0;\n            itAia = Ac.begin(i);\n            itAja = Ac.begin(j);\n            for(int a=0; a<NAEA; a++, itAia++, itAja++) {\n             s1 = fct*4.0*V*(*itAia);\n             s2 = fct*2.0*V*(*itAja);\n             itQa = Qa.begin(a);\n             itAib = Ac.begin(i);\n             itAjb = Ac.begin(j);\n             for(int b=0; b<NAEA; b++, itQa++, itAib++, itAjb++) \n               *itQa += ( s1*(*itAjb) - s2*(*itAib) );\n            }\n          } \n          // Now I have Q(a,b,k0,l0);\n          for(int a=0; a<NAEA; a++)\n           for(int b=0; b<NAEA; b++) \n            if(std::abs(Qa(a,b)) > cut) \n             Vijkl.add( a*NMO+k0, b*NMO+l0, static_cast<SPComplexType>(Qa(a,b)), true);\n        }\n\n      } else if(walker_type == 1) {\n\n        int del = (walker_type==2)?NAEA:0;\n        for(int p=0, nt=0; p<KL.size()-1; p++, nt++) {\n          if( nt%npr != rk ) continue;\n          long n = KL[p];\n          long m = KL[p+1];\n          IndexType k0 = std::get<0>(V2_full[n]);\n          IndexType l0 = std::get<1>(V2_full[n]);\n          IndexType i,j,k,l;\n          ValueType V,fct; \n          if(spinRestricted) {      \n            Qa=0;\n            Qb=0;\n            Qab=0;\n            Qab2=0;\n            // from n->m, I have all non-zero (i,j) for a given (k,l), with k<=l\n            for(s4Dit it = V2_full.begin()+n; it != V2_full.begin()+m; it++) {\n              std::tie (k,l,i,j,V) = *it;\n              // V (a,b,k,l) = sum_i,j A*(i,a) * A*(j,b) * V(i,j,k,l)\n              if(k0==l0) fct=0.0;\n              else fct=2.0;\n              itAia = Ac.begin(i);\n              itBia = Ac.begin(i+NMO)+del;\n              itAja = Ac.begin(j);\n              itBja = Ac.begin(j+NMO)+del;\n              for(int a=0; a<NAEA; a++, itAia++, itAja++, itBia++, itBja++) {\n                s1 = fct*V*(*itAia);  // Coul aa\n                s2 = fct*V*(*itAja);  // Exch aa\n                s3 = fct*V*(*itBia);  // Coul bb\n                s4 = fct*V*(*itBja);  // Exch bb\n                s5 = 2.0*V*(*itAia);  // Coul ab (kl) \n                s6 = 2.0*V*(*itAja);  // Coul ab (lk) \n                itQa = Qa.begin(a);\n                itQab = Qab.begin(a);\n                itQab2 = Qab2.begin(a);\n                itQb = Qb.begin(a);\n                itAib = Ac.begin(i);\n                itAjb = Ac.begin(j);          \n                itBib = Ac.begin(i+NMO)+del;\n                itBjb = Ac.begin(j+NMO)+del;          \n                for(int b=0; b<NAEA; b++, itQa++, itQb++, itQab++, itQab2++, itAib++, itAjb++, itBib++, itBjb++) { \n                  *itQa += ( s1*(*itAjb) - s2*(*itAib) );\n                  *itQb += ( s3*(*itBjb) - s4*(*itBib) );\n                  *itQab += s5*(*itBjb);\n                  *itQab2 += s6*(*itBib);\n                }\n              }\n            }\n            // Now I have Q(a,b,k0,l0);\n            for(int a=0; a<NAEA; a++)\n             for(int b=0; b<NAEA; b++) { \n               if(std::abs(Qa(a,b)) > cut) \n                 Vijkl.add( a*NMO+k0, b*NMO+l0, static_cast<SPComplexType>(Qa(a,b)), true);\n               if(std::abs(Qb(a,b)) > cut) \n                 Vijkl.add( NMO*NMO+a*NMO+k0, NMO*NMO+b*NMO+l0, static_cast<SPComplexType>(Qb(a,b)), true);\n               if(std::abs(Qab(a,b)) > cut)\n                 Vijkl.add( a*NMO+k0, NMO*NMO+b*NMO+l0, static_cast<SPComplexType>(Qab(a,b)), true);\n               if(std::abs(Qab2(a,b)) > cut && k0!=l0)\n                 Vijkl.add( a*NMO+l0, NMO*NMO+b*NMO+k0, static_cast<SPComplexType>(Qab2(a,b)), true);\n             }\n\n          } else {\n            app_error()<<\" Error: Finish implementation. \\n\\n\\n\";\n            return false;\n            if(k0 < NMO && l0 < NMO) { // aa \n              for(int a=0; a<NAEA; a++, itAia++, itAja++) {\n               s1 = fct*4.0*V*(*itAia);\n               s2 = fct*2.0*V*(*itAja);\n               itQa = Qa.begin(a);\n               itAib = Ac.begin(i);\n               itAjb = Ac.begin(j);\n               for(int b=0; b<NAEA; b++, itQa++, itAib++, itAjb++)\n                 *itQa += ( s1*(*itAjb) - s2*(*itAib) );\n              }\n            } else if(k0 >= NMO && l0 >= NMO) { // bb \n               app_error()<<\" Error: Finish implementation. \\n\\n\\n\";\n               return false;\n            } else if(k0 < NMO && l0 >= NMO) { // ab\n               app_error()<<\" Error: Finish implementation. \\n\\n\\n\";\n               return false;\n            } else {\n               app_error()<<\" Error: Problems in createHamiltonianForGeneralDeterminant. \\n\";\n               return false;\n            }\n          } // spinRestricted\n        } // KL loop\n      } else if(walker_type == 2) {\n        APP_ABORT(\"Error: TODO: createHamiltonianForGeneralDeterminant not implemented for GHF walker type yet. \\n\\n\\n\");\n      }\n\n      if(!communicate_Vijkl(Vijkl)) return false;\n      myComm->barrier();\n\n      Timer.stop(\"Generic\");\n      app_log()<<\"Time to generate 2-body Hamiltonian: \" <<Timer.total(\"Generic\") <<std::endl;\n\n    }  // factorizedHamiltonian\n\n#ifdef AFQMC_DEBUG\n    app_log()<<\" Done generating sparse hamiltonians. \" <<std::endl;\n    app_log()<<\" Compressing sparse hamiltonians. \" <<std::endl;\n#endif\n\n    if(!Vijkl.remove_repeated_and_compress(TG.getNodeCommLocal())) {\n      APP_ABORT(\"Error in call to SparseMatrix::remove_repeated(). \\n\");\n    }\n\n#ifdef AFQMC_DEBUG\n      app_log()<<\" Done compressing sparse hamiltonians. \" <<std::endl;\n#endif\n    \n    myComm->barrier();\n    return true;\n  }\n\n\n  bool SparseGeneralHamiltonian::initializeCCProjector(ComplexMatrix& Pmat, RealType cut) {\n\n    ValueType V;\n    std::vector<s4D<ValueType> > vs4D;  \n    s4D<ValueType> s;\n\n    int nvira = (NMO-NAEA);\n    int nvirb = (NMO-NAEB);\n    int na = nvira*NAEA;\n    int nb = nvirb*NAEB;\n\n    if(NAEA != NAEB) {\n      app_error()<<\"Error: NAEA != NAEB not supported in CCProjector yet. \\n\"; \n      return false;\n    }\n \n    s4Dit it2 = V2.begin();\n    while(it2 != V2.end()) {\n\n      if( std::abs( std::get<4>(*it2) ) <= cut ) { it2++; continue; }\n\n      if(spinRestricted) {\n\n        vs4D.clear();\n        s = *it2++;\n        // generate alpha/alpha sector \n        find_equivalent_OneBar_for_hamiltonian_generation(s,vs4D);\n\n        for(int n=0; n<vs4D.size(); n++) {\n          int a=std::get<0>(vs4D[n]);\n          int b=std::get<1>(vs4D[n]);\n          int i=std::get<2>(vs4D[n]);\n          int j=std::get<3>(vs4D[n]);\n          if( a >= NAEA && i<NAEA && b >= NAEA && j < NAEA ) { \n            Pmat(i*nvira+(a-NAEA),j*nvirb+(b-NAEA)) = std::get<4>(vs4D[n]); \n            Pmat(na+i*nvira+(a-NAEA),j*nvirb+(b-NAEA)) = std::get<4>(vs4D[n]); \n            Pmat(i*nvira+(a-NAEA),nb+j*nvirb+(b-NAEA)) = std::get<4>(vs4D[n]); \n            Pmat(na+i*nvira+(a-NAEA),nb+j*nvirb+(b-NAEA)) = std::get<4>(vs4D[n]); \n\n            Pmat(j*nvirb+(b-NAEA),i*nvira+(a-NAEA)) = std::get<4>(vs4D[n]); \n            Pmat(j*nvirb+(b-NAEA),na+i*nvira+(a-NAEA)) = std::get<4>(vs4D[n]); \n            Pmat(nb+j*nvirb+(b-NAEA),i*nvira+(a-NAEA)) = std::get<4>(vs4D[n]); \n            Pmat(nb+j*nvirb+(b-NAEA),na+i*nvira+(a-NAEA)) = std::get<4>(vs4D[n]); \n          }\n        }\n\n      } else {\n\n        app_error()<<\"Error: initializeCCProjector not implemented for UHF. DO IT!!! \\n\";\n        return false;\n\n        int sector = getSpinSector(std::get<0>(*it2),std::get<1>(*it2),std::get<2>(*it2),std::get<3>(*it2));\n        switch(sector) { \n          case 0:\n          { \n            break;\n          } \n          case 1: \n          { \n            find_equivalent_OneBar_for_hamiltonian_generation(*it2,vs4D);\n            for(int n=0; n<vs4D.size(); n++) {\n              int a=std::get<0>(vs4D[n]);\n              int b=std::get<1>(vs4D[n]);\n              int i=std::get<2>(vs4D[n]);\n              int j=std::get<3>(vs4D[n]);\n              if( a >= NAEA && i<NAEA && b >= NAEA && j < NAEA ) {\n                Pmat((a-NAEA)*i,(b-NAEA)*j) = std::get<4>(vs4D[n]);\n                Pmat(na+(a-NAEA)*i,(b-NAEA)*j) = std::get<4>(vs4D[n]);\n                Pmat((a-NAEA)*i,nb+(b-NAEA)*j) = std::get<4>(vs4D[n]);\n                Pmat(na+(a-NAEA)*i,nb+(b-NAEA)*j) = std::get<4>(vs4D[n]);\n              }\n            }\n            break;\n          } \n          case 2: \n          { \n            app_error()<<\"Error in SparseGeneralHamiltonian :: createHamiltonianForPureDeterminant(). I should never get here. \\n\"; \n            return false;  \n            break;\n          } \n          case 3: \n          { \n            break;\n          } \n        } \n\n      }\n    }\n\n  }\n\n/*\n  template< >\n  void SQCHamMatElms<double>::calculateEigenvalueDecomposition(int N, std::vector<double>& A, std::vector<double>& eigR, std::vector<double>& eigI, std::vector<double>& V) {   \n\n    int rnk=0;\n#if defined(USE_MPI)\n    MPI_Comm_rank(MPI_COMM_WORLD, &rnk);\n#endif\n    if(rnk!=0) return;\n\n#ifdef _TIMER_\n    TIMER.reset(TTAG11);\n    TIMER.start(TTAG11);\n#endif\n\n    char JOBVL('N');\n    char JOBVR('V');\n    double dummy;\n    int dumI = 1;\n    std::vector<double> WORK(1);\n    int LWORK = -1;\n    int INFO;\n\n    dgeev(JOBVL,JOBVR,N,&(A[0]),N, &(eigR[0]), &(eigI[0]), \n             &dummy,dumI,&(V[0]),N,&(WORK[0]),LWORK,&INFO );\n\n    LWORK = int(WORK[0]);\n    std::cout<<\"Optimal LWORK used in dgeev: \" <<LWORK <<std::endl;\n    WORK.resize(LWORK);\n\n    dgeev(JOBVL,JOBVR,N,&(A[0]),N, &(eigR[0]), &(eigI[0]), \n             &dummy,dumI,&(V[0]),N,&(WORK[0]),LWORK,&INFO );\n\n    if(INFO != 0) {\n      std::cerr<<\"Error in solveEigenvalueProblem: FAIL != 0.\\n\";\n      std::cerr<<\"INFO: \" <<INFO <<std::endl;\n      SQCAbort(\"Error in solveEigenvalueProblem: FAIL != 0.\\n\");\n    }\n\n#ifdef _TIMER_\n    TIMER.stop(TTAG11);\n    if(rnk==0) std::cout<<\" -- Time to solve eigenvalue problem: \" <<TIMER.average(TTAG11) <<\"\\n\";\n#endif\n\n  }\n*/\n\n}\n\n", "meta": {"hexsha": "12f6c38eeab8b93d564b643c4ec7b6ba93eeb622", "size": 292920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AFQMC/Hamiltonians/SparseGeneralHamiltonian.cpp", "max_stars_repo_name": "markdewing/qmcpack", "max_stars_repo_head_hexsha": "4bd3e10ceb0faf8d2b3095338da5a56eda0dc1ba", "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/AFQMC/Hamiltonians/SparseGeneralHamiltonian.cpp", "max_issues_repo_name": "markdewing/qmcpack", "max_issues_repo_head_hexsha": "4bd3e10ceb0faf8d2b3095338da5a56eda0dc1ba", "max_issues_repo_licenses": ["NCSA"], "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/AFQMC/Hamiltonians/SparseGeneralHamiltonian.cpp", "max_forks_repo_name": "markdewing/qmcpack", "max_forks_repo_head_hexsha": "4bd3e10ceb0faf8d2b3095338da5a56eda0dc1ba", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T17:44:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-23T17:44:39.000Z", "avg_line_length": 37.8547428276, "max_line_length": 292, "alphanum_fraction": 0.5192714734, "num_tokens": 90563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.19373853797437632}}
{"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 \"sensitivityanalysis2.hpp\"\n#include \"testmarket.hpp\"\n#include \"testportfolio.hpp\"\n\n#include <orea/cube/inmemorycube.hpp>\n#include <orea/cube/npvcube.hpp>\n#include <orea/engine/all.hpp>\n#include <orea/engine/observationmode.hpp>\n#include <orea/engine/sensitivityanalysis.hpp>\n#include <orea/scenario/clonescenariofactory.hpp>\n#include <orea/scenario/scenariosimmarket.hpp>\n#include <orea/scenario/scenariosimmarketparameters.hpp>\n#include <orea/scenario/sensitivityscenariogenerator.hpp>\n\n#include <ored/model/lgmdata.hpp>\n#include <ored/portfolio/builders/capfloor.hpp>\n#include <ored/portfolio/builders/fxforward.hpp>\n#include <ored/portfolio/builders/fxoption.hpp>\n#include <ored/portfolio/builders/swap.hpp>\n#include <ored/portfolio/builders/swaption.hpp>\n#include <ored/portfolio/fxoption.hpp>\n#include <ored/portfolio/portfolio.hpp>\n#include <ored/portfolio/swap.hpp>\n#include <ored/portfolio/swaption.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/osutils.hpp>\n\n#include <ql/math/randomnumbers/mt19937uniformrng.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/date.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <boost/timer.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\nusing namespace ore;\nusing namespace ore::data;\nusing namespace ore::analytics;\n\nnamespace testsuite {\n\nnamespace {\nboost::shared_ptr<data::Conventions> conv() {\n    boost::shared_ptr<data::Conventions> conventions(new data::Conventions());\n\n    boost::shared_ptr<data::Convention> swapIndexConv(\n        new data::SwapIndexConvention(\"EUR-CMS-2Y\", \"EUR-6M-SWAP-CONVENTIONS\"));\n    conventions->add(swapIndexConv);\n\n    // boost::shared_ptr<data::Convention> swapConv(\n    //     new data::IRSwapConvention(\"EUR-6M-SWAP-CONVENTIONS\", \"TARGET\", \"Annual\", \"MF\", \"30/360\", \"EUR-EURIBOR-6M\"));\n    conventions->add(boost::make_shared<data::IRSwapConvention>(\"EUR-6M-SWAP-CONVENTIONS\", \"TARGET\", \"A\", \"MF\",\n                                                                \"30/360\", \"EUR-EURIBOR-6M\"));\n    conventions->add(boost::make_shared<data::IRSwapConvention>(\"USD-3M-SWAP-CONVENTIONS\", \"TARGET\", \"Q\", \"MF\",\n                                                                \"30/360\", \"USD-LIBOR-3M\"));\n    conventions->add(boost::make_shared<data::IRSwapConvention>(\"USD-6M-SWAP-CONVENTIONS\", \"TARGET\", \"Q\", \"MF\",\n                                                                \"30/360\", \"USD-LIBOR-6M\"));\n    conventions->add(boost::make_shared<data::IRSwapConvention>(\"GBP-6M-SWAP-CONVENTIONS\", \"TARGET\", \"A\", \"MF\",\n                                                                \"30/360\", \"GBP-LIBOR-6M\"));\n    conventions->add(boost::make_shared<data::IRSwapConvention>(\"JPY-6M-SWAP-CONVENTIONS\", \"TARGET\", \"A\", \"MF\",\n                                                                \"30/360\", \"JPY-LIBOR-6M\"));\n    conventions->add(boost::make_shared<data::IRSwapConvention>(\"CHF-6M-SWAP-CONVENTIONS\", \"TARGET\", \"A\", \"MF\",\n                                                                \"30/360\", \"CHF-LIBOR-6M\"));\n\n    conventions->add(boost::make_shared<data::DepositConvention>(\"EUR-DEP-CONVENTIONS\", \"EUR-EURIBOR\"));\n    conventions->add(boost::make_shared<data::DepositConvention>(\"USD-DEP-CONVENTIONS\", \"USD-LIBOR\"));\n    conventions->add(boost::make_shared<data::DepositConvention>(\"GBP-DEP-CONVENTIONS\", \"GBP-LIBOR\"));\n    conventions->add(boost::make_shared<data::DepositConvention>(\"JPY-DEP-CONVENTIONS\", \"JPY-LIBOR\"));\n    conventions->add(boost::make_shared<data::DepositConvention>(\"CHF-DEP-CONVENTIONS\", \"CHF-LIBOR\"));\n\n    return conventions;\n}\n\nboost::shared_ptr<analytics::ScenarioSimMarketParameters> setupSimMarketData5() {\n    boost::shared_ptr<analytics::ScenarioSimMarketParameters> simMarketData(\n        new analytics::ScenarioSimMarketParameters());\n\n    simMarketData->baseCcy() = \"EUR\";\n    simMarketData->ccys() = {\"EUR\", \"GBP\", \"USD\", \"CHF\", \"JPY\"};\n    simMarketData->setYieldCurveTenors(\"\", {1 * Months, 6 * Months, 1 * Years, 2 * Years, 3 * Years, 4 * Years,\n                                            5 * Years, 7 * Years, 10 * Years, 15 * Years, 20 * Years, 30 * Years});\n    simMarketData->setYieldCurveDayCounters(\"\", \"ACT/ACT\");\n    simMarketData->indices() = {\"EUR-EURIBOR-6M\", \"USD-LIBOR-3M\", \"USD-LIBOR-6M\",\n                                \"GBP-LIBOR-6M\",   \"CHF-LIBOR-6M\", \"JPY-LIBOR-6M\"};\n    simMarketData->interpolation() = \"LogLinear\";\n    simMarketData->extrapolate() = true;\n\n    simMarketData->swapVolTerms() = {1 * Years, 2 * Years, 3 * Years, 5 * Years, 7 * Years, 10 * Years, 20 * Years};\n    simMarketData->swapVolExpiries() = {6 * Months, 1 * Years, 2 * Years,  3 * Years,\n                                        5 * Years,  7 * Years, 10 * Years, 20 * Years};\n    simMarketData->swapVolCcys() = {\"EUR\", \"GBP\", \"USD\", \"CHF\", \"JPY\"};\n    simMarketData->swapVolDecayMode() = \"ForwardVariance\";\n    simMarketData->simulateSwapVols() = true; // false;\n    simMarketData->setSwapVolDayCounters(\"\", \"ACT/ACT\");\n    simMarketData->fxVolExpiries() = {6 * Months, 1 * Years, 2 * Years,  3 * Years,\n                                      5 * Years,  7 * Years, 10 * Years, 20 * Years};\n    simMarketData->fxVolDecayMode() = \"ConstantVariance\";\n    simMarketData->simulateFXVols() = true; // false;\n    simMarketData->fxVolCcyPairs() = {\"EURUSD\", \"EURGBP\", \"EURCHF\", \"EURJPY\", \"GBPCHF\"};\n    simMarketData->fxVolIsSurface() = false;\n    simMarketData->fxVolMoneyness() = {0};\n    simMarketData->setFxVolDayCounters(\"\", \"ACT/ACT\");\n\n    simMarketData->fxCcyPairs() = {\"EURUSD\", \"EURGBP\", \"EURCHF\", \"EURJPY\"};\n\n    simMarketData->simulateCapFloorVols() = true;\n    simMarketData->capFloorVolDecayMode() = \"ForwardVariance\";\n    simMarketData->capFloorVolCcys() = {\"EUR\", \"USD\"};\n    simMarketData->setCapFloorVolExpiries(\n        \"\", {6 * Months, 1 * Years, 2 * Years, 3 * Years, 5 * Years, 7 * Years, 10 * Years, 15 * Years, 20 * Years});\n    simMarketData->capFloorVolStrikes() = {0.00, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06};\n    simMarketData->setCapFloorVolDayCounters(\"\", \"A365\");\n\n    return simMarketData;\n}\n\nboost::shared_ptr<SensitivityScenarioData> setupSensitivityScenarioData5() {\n    boost::shared_ptr<SensitivityScenarioData> sensiData = boost::make_shared<SensitivityScenarioData>();\n\n    SensitivityScenarioData::CurveShiftData cvsData;\n\n    // identical to sim market tenor structure, we can only check this case, because the analytic engine\n    // assumes either linear in zero or linear in log discount interpolation, while the sensitivity analysis\n    // assumes a lienar in zero interpolation for rebucketing, but uses the linear in log discount interpolation\n    // of the sim market yield curves for the scenario calculation\n    cvsData.shiftTenors = {1 * Months, 6 * Months, 1 * Years,  2 * Years,  3 * Years,  4 * Years,\n                           5 * Years,  7 * Years,  10 * Years, 15 * Years, 20 * Years, 30 * Years};\n    cvsData.shiftType = \"Absolute\";\n    cvsData.shiftSize = 1E-5;\n\n    SensitivityScenarioData::SpotShiftData fxsData;\n    fxsData.shiftType = \"Absolute\";\n    fxsData.shiftSize = 1E-5;\n\n    SensitivityScenarioData::VolShiftData fxvsData;\n    fxvsData.shiftType = \"Absolute\";\n    fxvsData.shiftSize = 1E-5;\n    fxvsData.shiftExpiries = {5 * Years};\n\n    SensitivityScenarioData::CapFloorVolShiftData cfvsData;\n    cfvsData.shiftType = \"Absolute\";\n    cfvsData.shiftSize = 1E-5;\n    cfvsData.shiftExpiries = {1 * Years, 2 * Years, 3 * Years, 5 * Years, 10 * Years};\n    cfvsData.shiftStrikes = {0.01, 0.02, 0.03, 0.04, 0.05};\n\n    SensitivityScenarioData::SwaptionVolShiftData swvsData;\n    swvsData.shiftType = \"Absolute\";\n    swvsData.shiftSize = 1E-5;\n    swvsData.shiftExpiries = {6 * Months, 1 * Years, 2 * Years,  3 * Years,\n                              5 * Years,  7 * Years, 10 * Years, 20 * Years};\n    swvsData.shiftTerms = {1 * Years, 2 * Years, 3 * Years, 5 * Years, 7 * Years, 10 * Years, 20 * Years};\n\n    sensiData->discountCurrencies() = {\"EUR\", \"USD\", \"GBP\", \"CHF\", \"JPY\"};\n    sensiData->discountCurveShiftData()[\"EUR\"] = boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n    sensiData->discountCurveShiftData()[\"USD\"] = boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n    sensiData->discountCurveShiftData()[\"GBP\"] = boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n    sensiData->discountCurveShiftData()[\"JPY\"] = boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n    sensiData->discountCurveShiftData()[\"CHF\"] = boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n\n    sensiData->indexNames() = {\"EUR-EURIBOR-6M\", \"USD-LIBOR-3M\", \"GBP-LIBOR-6M\", \"CHF-LIBOR-6M\", \"JPY-LIBOR-6M\"};\n    sensiData->indexCurveShiftData()[\"EUR-EURIBOR-6M\"] =\n        boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n    sensiData->indexCurveShiftData()[\"USD-LIBOR-3M\"] =\n        boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n    sensiData->indexCurveShiftData()[\"GBP-LIBOR-6M\"] =\n        boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n    sensiData->indexCurveShiftData()[\"JPY-LIBOR-6M\"] =\n        boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n    sensiData->indexCurveShiftData()[\"CHF-LIBOR-6M\"] =\n        boost::make_shared<SensitivityScenarioData::CurveShiftData>(cvsData);\n\n    sensiData->fxCcyPairs() = {\"EURUSD\", \"EURGBP\", \"EURCHF\", \"EURJPY\"};\n    sensiData->fxShiftData()[\"EURUSD\"] = fxsData;\n    sensiData->fxShiftData()[\"EURGBP\"] = fxsData;\n    sensiData->fxShiftData()[\"EURJPY\"] = fxsData;\n    sensiData->fxShiftData()[\"EURCHF\"] = fxsData;\n\n    sensiData->fxVolCcyPairs() = {\"EURUSD\", \"EURGBP\", \"EURCHF\", \"EURJPY\", \"GBPCHF\"};\n    sensiData->fxVolShiftData()[\"EURUSD\"] = fxvsData;\n    sensiData->fxVolShiftData()[\"EURGBP\"] = fxvsData;\n    sensiData->fxVolShiftData()[\"EURJPY\"] = fxvsData;\n    sensiData->fxVolShiftData()[\"EURCHF\"] = fxvsData;\n    sensiData->fxVolShiftData()[\"GBPCHF\"] = fxvsData;\n\n    sensiData->swaptionVolCurrencies() = {\"EUR\", \"USD\", \"GBP\", \"CHF\", \"JPY\"};\n    sensiData->swaptionVolShiftData()[\"EUR\"] = swvsData;\n    sensiData->swaptionVolShiftData()[\"GBP\"] = swvsData;\n    sensiData->swaptionVolShiftData()[\"USD\"] = swvsData;\n    sensiData->swaptionVolShiftData()[\"JPY\"] = swvsData;\n    sensiData->swaptionVolShiftData()[\"CHF\"] = swvsData;\n\n    sensiData->capFloorVolCurrencies() = {\"EUR\", \"USD\"};\n    sensiData->capFloorVolShiftData()[\"EUR\"] = cfvsData;\n    sensiData->capFloorVolShiftData()[\"EUR\"].indexName = \"EUR-EURIBOR-6M\";\n    sensiData->capFloorVolShiftData()[\"USD\"] = cfvsData;\n    sensiData->capFloorVolShiftData()[\"USD\"].indexName = \"USD-LIBOR-3M\";\n\n    sensiData->crossGammaFilter() = {{\"DiscountCurve/EUR\", \"DiscountCurve/EUR\"},\n                                     {\"DiscountCurve/USD\", \"DiscountCurve/USD\"},\n                                     {\"DiscountCurve/EUR\", \"IndexCurve/EUR\"},\n                                     {\"IndexCurve/EUR\", \"IndexCurve/EUR\"},\n                                     {\"DiscountCurve/EUR\", \"DiscountCurve/USD\"}};\n\n    return sensiData;\n}\n\nbool check(const Real reference, const Real value) {\n    if (std::fabs(reference) >= 1E-2) {\n        return std::fabs((reference - value) / reference) < 5E-3;\n    } else {\n        return std::fabs(reference - value) < 1E-3;\n    }\n}\n\n} // anonymous namespace\n\nvoid SensitivityAnalysis2Test::testSensitivities() {\n\n    BOOST_TEST_MESSAGE(\"Checking sensitivity analysis results vs analytic sensi engine results...\");\n\n    SavedSettings backup;\n\n    ObservationMode::Mode backupMode = ObservationMode::instance().mode();\n    ObservationMode::instance().setMode(ObservationMode::Mode::None);\n\n    Date today = Date(14, April, 2016); // Settings::instance().evaluationDate();\n    Settings::instance().evaluationDate() = today;\n\n    BOOST_TEST_MESSAGE(\"Today is \" << today);\n\n    // Init market\n    boost::shared_ptr<Market> initMarket = boost::make_shared<TestMarket>(today);\n\n    // build scenario sim market parameters\n    boost::shared_ptr<analytics::ScenarioSimMarketParameters> simMarketData = setupSimMarketData5();\n\n    // sensitivity config\n    boost::shared_ptr<SensitivityScenarioData> sensiData = setupSensitivityScenarioData5();\n\n    // build scenario sim market\n    Conventions conventions = *conv();\n\n    // build porfolio\n    boost::shared_ptr<EngineData> data = boost::make_shared<EngineData>();\n    data->model(\"Swap\") = \"DiscountedCashflows\";\n    data->engine(\"Swap\") = \"DiscountingSwapEngine\";\n    data->model(\"CrossCurrencySwap\") = \"DiscountedCashflows\";\n    data->engine(\"CrossCurrencySwap\") = \"DiscountingCrossCurrencySwapEngine\";\n    data->model(\"EuropeanSwaption\") = \"BlackBachelier\";\n    data->engine(\"EuropeanSwaption\") = \"BlackBachelierSwaptionEngine\";\n    data->model(\"FxOption\") = \"GarmanKohlhagen\";\n    data->engine(\"FxOption\") = \"AnalyticEuropeanEngine\";\n\n    // boost::shared_ptr<Portfolio> portfolio = buildSwapPortfolio(portfolioSize, factory);\n    boost::shared_ptr<Portfolio> portfolio(new Portfolio());\n    portfolio->add(\n        buildSwap(\"1_Swap_EUR\", \"EUR\", true, 10.0, 0, 10, 0.03, 0.00, \"1Y\", \"30/360\", \"6M\", \"A360\", \"EUR-EURIBOR-6M\"));\n    portfolio->add(buildEuropeanSwaption(\"5_Swaption_EUR\", \"Long\", \"EUR\", true, 10.0, 10, 10, 0.03, 0.00, \"1Y\",\n                                         \"30/360\", \"6M\", \"A360\", \"EUR-EURIBOR-6M\", \"Physical\"));\n    portfolio->add(buildFxOption(\"7_FxOption_EUR_USD\", \"Long\", \"Call\", 3, \"EUR\", 10.0, \"USD\", 11.0));\n\n    // analytic results\n    map<string, Real> analyticalResultsDelta = {{\"1_Swap_EUR DiscountCurve/EUR/0/1M\", 0},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/1/6M\", -0.0251638},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/10/20Y\", 0},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/11/30Y\", 0},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/2/1Y\", 0.146855},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/3/2Y\", 0.190109},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/4/3Y\", 0.279228},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/5/4Y\", 0.364784},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/6/5Y\", 0.66847},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/7/7Y\", 1.49473},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/8/10Y\", 2.05151},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/9/15Y\", 0},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M\", -4.95025},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0.146584},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0.385931},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0.567839},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0.74296},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y\", 1.35326},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y\", 3.03756},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y\", 84.7885},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/0/1M\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/1/6M\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y\", -0.747105},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y\", 7.54828e-05},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y\", -0.53418},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y\", -1.3424},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/10/20Y\", 53.6536},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0.0210198},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y\", -29.6507},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/9/15Y\", 4.23344},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/0/6M/1Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/1/6M/2Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/10/1Y/5Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/11/1Y/7Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/12/1Y/10Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/13/1Y/20Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/14/2Y/1Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/15/2Y/2Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/16/2Y/3Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/17/2Y/5Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/18/2Y/7Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/19/2Y/10Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/2/6M/3Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/20/2Y/20Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/21/3Y/1Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/22/3Y/2Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/23/3Y/3Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/24/3Y/5Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/25/3Y/7Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/26/3Y/10Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/27/3Y/20Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/28/5Y/1Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/29/5Y/2Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/3/6M/5Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/30/5Y/3Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/31/5Y/5Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/32/5Y/7Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/33/5Y/10Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/34/5Y/20Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/35/7Y/1Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/36/7Y/2Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/37/7Y/3Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/38/7Y/5Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/39/7Y/7Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/4/6M/7Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/40/7Y/10Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/41/7Y/20Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/42/10Y/1Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/43/10Y/2Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/44/10Y/3Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/45/10Y/5Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/46/10Y/7Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/47/10Y/10Y/ATM\", 1.78576},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/48/10Y/20Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/49/20Y/1Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/5/6M/10Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/50/20Y/2Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/51/20Y/3Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/52/20Y/5Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/53/20Y/7Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/54/20Y/10Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/55/20Y/20Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/6/6M/20Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/7/1Y/1Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/8/1Y/2Y/ATM\", 0},\n                                                {\"5_Swaption_EUR SwaptionVolatility/EUR/9/1Y/3Y/ATM\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y\", -21.0493},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y\", -0.0770026},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/10/20Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/11/30Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y\", 16.9542},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/5/4Y\", 0.0620218},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/6/5Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/7/7Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/8/10Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/9/15Y\", 0},\n                                                {\"7_FxOption_EUR_USD FXSpot/EURUSD/0/spot\", 4.72549},\n                                                {\"7_FxOption_EUR_USD FXVolatility/EURUSD/0/5Y/ATM\", 5.21067}};\n\n    map<string, Real> analyticalResultsGamma = {{\"1_Swap_EUR DiscountCurve/EUR/0/1M\", 0},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/1/6M\", 0.0125819},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/10/20Y\", 0},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/11/30Y\", 0},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/2/1Y\", -0.16852},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/3/2Y\", -0.558829},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/4/3Y\", -1.24741},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/5/4Y\", -2.19217},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/6/5Y\", -3.64545},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/7/7Y\", -8.45766},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/8/10Y\", -17.5009},\n                                                {\"1_Swap_EUR DiscountCurve/EUR/9/15Y\", 0},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M\", 2.47512},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y\", 14.3979},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y\", 37.7122},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y\", 84.1478},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y\", 148.04},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y\", 170.402},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y\", 178.37},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y\", 141.3},\n                                                {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/0/1M\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/1/6M\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y\", 9.16378},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y\", -4.94345e-07},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y\", 0},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y\", 3.7521},\n                                                {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y\", 13.0565},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/10/20Y\", 8237.22},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0.00142014},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y\", 2512.58},\n                                                {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/9/15Y\", 177.559},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y\", 192.286},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y\", 0.00257327},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/10/20Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/11/30Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y\", 78.6621},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/5/4Y\", 0.00105269},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/6/5Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/7/7Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/8/10Y\", 0},\n                                                {\"7_FxOption_EUR_USD DiscountCurve/USD/9/15Y\", 0},\n                                                {\"7_FxOption_EUR_USD FXSpot/EURUSD/0/spot\", 2.17301}};\n\n    map<string, Real> analyticalResultsCrossGamma = {\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/3/2Y\", 0.0439491},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 4.8864},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", -7.2595},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", -4.99316},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/4/3Y\", 0.136543},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0.108392},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 14.1881},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", -19.1426},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", -14.5467},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/5/4Y\", 0.274041},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0.0784567},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 42.4881},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", -42.7095},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", -28.3908},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/6/5Y\", 0.459076},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0.10308},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 83.8339},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", -75.1334},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", -46.1375},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/7/7Y\", -0.376937},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 137.497},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", -87.5996},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", -117.899},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y DiscountCurve/EUR/8/10Y\", -2.10692},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 193.901},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", -96.4279},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", -250.112},\n        {\"1_Swap_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 343.241},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", -490.385},\n        {\"1_Swap_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/2/1Y\", -4.8864},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/3/2Y\", -0.108392},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/10/20Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", -9.24531},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", -0.0784567},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", -28.0873},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", -0.10308},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", -55.7263},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", -91.8185},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", -77.9517},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", -98.9016},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/9/15Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"1_Swap_EUR IndexCurve/EUR-EURIBOR-6M/9/15Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M DiscountCurve/EUR/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/0/1M IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M DiscountCurve/EUR/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/1/6M IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y DiscountCurve/EUR/11/30Y\", -0.00135078},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", -540.615},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", -0.404414},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", -22.3523},\n        {\"5_Swaption_EUR DiscountCurve/EUR/10/20Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 439.141},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", -0.00991954},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", -0.000159855},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", -0.0175782},\n        {\"5_Swaption_EUR DiscountCurve/EUR/11/30Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0.0338876},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/2/1Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/3/2Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/4/3Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/5/4Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/6/5Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/7/7Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y DiscountCurve/EUR/10/20Y\", -0.111935},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y DiscountCurve/EUR/11/30Y\", -8.79058e-05},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y DiscountCurve/EUR/9/15Y\", 2.46712},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", -22.4684},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", -0.00880242},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 148.263},\n        {\"5_Swaption_EUR DiscountCurve/EUR/8/10Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", -205.555},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y DiscountCurve/EUR/10/20Y\", 4.50176},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y DiscountCurve/EUR/11/30Y\", 1.29719e-05},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/0/1M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", -365.581},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0.00129894},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 239.064},\n        {\"5_Swaption_EUR DiscountCurve/EUR/9/15Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", -84.4702},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/1/6M\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/0/1M IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/2/1Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/1/6M IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/10/20Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 3.22683},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/3/2Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/2/1Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/4/3Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/3/2Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/5/4Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/4/3Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/6/5Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/5/4Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/7/7Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/6/5Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y IndexCurve/EUR-EURIBOR-6M/8/10Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/7/7Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", 0},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", -4492.95},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", -1.76019},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/8/10Y IndexCurve/EUR-EURIBOR-6M/9/15Y\", -398.959},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/9/15Y IndexCurve/EUR-EURIBOR-6M/10/20Y\", 561.152},\n        {\"5_Swaption_EUR IndexCurve/EUR-EURIBOR-6M/9/15Y IndexCurve/EUR-EURIBOR-6M/11/30Y\", 0.219937},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/0/1M DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/1/6M DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/10/20Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/11/30Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/2/1Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/EUR/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/EUR/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/3/2Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/EUR/5/4Y\", 0.703423},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/4/3Y\", -129.352},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/5/4Y\", -0.473197},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/4/3Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/EUR/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/4/3Y\", -0.473197},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/5/4Y\", -0.00173105},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/5/4Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/EUR/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/6/5Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/EUR/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/7/7Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/EUR/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/8/10Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/EUR/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/EUR/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/0/1M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/EUR/9/15Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/1/6M\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/0/1M DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/2/1Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/1/6M DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/10/20Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/3/2Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/2/1Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y DiscountCurve/USD/4/3Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y DiscountCurve/USD/5/4Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/3/2Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y DiscountCurve/USD/5/4Y\", 0.287762},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/4/3Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/5/4Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/5/4Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/5/4Y DiscountCurve/USD/6/5Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/5/4Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/5/4Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/5/4Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/6/5Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/6/5Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/6/5Y DiscountCurve/USD/7/7Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/6/5Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/6/5Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/7/7Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/7/7Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/7/7Y DiscountCurve/USD/8/10Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/7/7Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/8/10Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/8/10Y DiscountCurve/USD/11/30Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/8/10Y DiscountCurve/USD/9/15Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/9/15Y DiscountCurve/USD/10/20Y\", 0},\n        {\"7_FxOption_EUR_USD DiscountCurve/USD/9/15Y DiscountCurve/USD/11/30Y\", 0}};\n    // sensitivity analysis\n    boost::shared_ptr<SensitivityAnalysis> sa = boost::make_shared<SensitivityAnalysis>(\n        portfolio, initMarket, Market::defaultConfiguration, data, simMarketData, sensiData, conventions, false);\n    sa->generateSensitivities();\n    map<pair<string, string>, Real> deltaMap;\n    map<pair<string, string>, Real> gammaMap;\n    for (auto p : portfolio->trades()) {\n        for (auto f : sa->sensiCube()->upFactors()) {\n            deltaMap[make_pair(p->id(), f.first)] = sa->delta(p->id(), f.first);\n            gammaMap[make_pair(p->id(), f.first)] = sa->gamma(p->id(), f.first);\n        }\n    }\n    std::vector<ore::analytics::SensitivityScenarioGenerator::ScenarioDescription> scenDesc =\n        sa->scenarioGenerator()->scenarioDescriptions();\n\n    Real shiftSize = 1E-5; // shift size\n\n    // check deltas\n    BOOST_TEST_MESSAGE(\"Checking deltas...\");\n    Size foundDeltas = 0, zeroDeltas = 0;\n    for (auto const& x : deltaMap) {\n        string key = x.first.first + \" \" + x.first.second;\n        Real scaledResult = x.second / shiftSize;\n        if (analyticalResultsDelta.count(key) > 0) {\n            if (!check(analyticalResultsDelta.at(key), scaledResult))\n                BOOST_ERROR(\"Sensitivity analysis result \" << key << \" (\" << scaledResult\n                                                           << \") could not be verified against analytic result (\"\n                                                           << analyticalResultsDelta.at(key) << \")\");\n            ++foundDeltas;\n        } else {\n            if (!close_enough(x.second, 0.0))\n                BOOST_ERROR(\"Sensitivity analysis result \" << key << \" (\" << scaledResult << \") expected to be zero\");\n            ++zeroDeltas;\n        }\n    }\n    if (foundDeltas != analyticalResultsDelta.size())\n        BOOST_ERROR(\"Mismatch between number of analytical results for delta (\"\n                    << analyticalResultsDelta.size() << \") and sensitivity results (\" << foundDeltas << \")\");\n    BOOST_TEST_MESSAGE(\"Checked \" << foundDeltas << \" deltas against analytical values (and \" << zeroDeltas\n                                  << \" deal-unrelated deltas for zero).\");\n\n    // check gammas\n    BOOST_TEST_MESSAGE(\"Checking gammas...\");\n    Size foundGammas = 0, zeroGammas = 0;\n    for (auto const& x : gammaMap) {\n        string key = x.first.first + \" \" + x.first.second;\n        Real scaledResult = x.second / (shiftSize * shiftSize);\n        if (analyticalResultsGamma.count(key) > 0) {\n            if (!check(analyticalResultsGamma.at(key), scaledResult))\n                BOOST_ERROR(\"Sensitivity analysis result \" << key << \" (\" << scaledResult\n                                                           << \") could not be verified against analytic result (\"\n                                                           << analyticalResultsGamma.at(key) << \")\");\n            ++foundGammas;\n        } else {\n            // the sensi framework produces a Vomma, which we don't check (it isn't produced by the analytic sensi\n            // engine)\n            if (!close_enough(x.second, 0.0) && key != \"5_Swaption_EUR SwaptionVolatility/EUR/47/10Y/10Y/ATM\" &&\n                key != \"7_FxOption_EUR_USD FXVolatility/EURUSD/0/5Y/ATM\")\n                BOOST_ERROR(\"Sensitivity analysis result \" << key << \" (\" << scaledResult << \") expected to be zero\");\n            ++zeroGammas;\n        }\n    }\n    if (foundGammas != analyticalResultsGamma.size())\n        BOOST_ERROR(\"Mismatch between number of analytical results for gamma (\"\n                    << analyticalResultsGamma.size() << \") and sensitivity results (\" << foundGammas << \")\");\n    BOOST_TEST_MESSAGE(\"Checked \" << foundGammas << \" gammas against analytical values (and \" << zeroGammas\n                                  << \" deal-unrelated gammas for zero).\");\n\n    // check cross gammas\n    BOOST_TEST_MESSAGE(\"Checking cross-gammas...\");\n    Size foundCrossGammas = 0, zeroCrossGammas = 0;\n    for (Size i = 0; i < portfolio->size(); i++) {\n        string id = portfolio->trades()[i]->id();\n        for (auto const& s : scenDesc) {\n            if (s.type() == ShiftScenarioGenerator::ScenarioDescription::Type::Cross) {\n                string key = id + \" \" + s.factor1() + \" \" + s.factor2();\n                Real scaledResult = sa->crossGamma(id, s.factor1(), s.factor2()) / (shiftSize * shiftSize);\n                // BOOST_TEST_MESSAGE(key << \" \" << scaledResult); // debug\n                if (analyticalResultsCrossGamma.count(key) > 0) {\n                    if (!check(analyticalResultsCrossGamma.at(key), scaledResult))\n                        BOOST_ERROR(\"Sensitivity analysis result \"\n                                    << key << \" (\" << scaledResult\n                                    << \") could not be verified against analytic result (\"\n                                    << analyticalResultsCrossGamma.at(key) << \")\");\n                    ++foundCrossGammas;\n                } else {\n                    if (!check(sa->crossGamma(id, s.factor1(), s.factor2()), 0.0))\n                        BOOST_ERROR(\"Sensitivity analysis result \" << key << \" (\"\n                                                                   << sa->crossGamma(id, s.factor1(), s.factor2())\n                                                                   << \") expected to be zero\");\n                    ++zeroCrossGammas;\n                }\n            }\n        }\n    }\n    if (foundCrossGammas != analyticalResultsCrossGamma.size())\n        BOOST_ERROR(\"Mismatch between number of analytical results for gamma (\"\n                    << analyticalResultsCrossGamma.size() << \") and sensitivity results (\" << foundCrossGammas << \")\");\n    BOOST_TEST_MESSAGE(\"Checked \" << foundCrossGammas << \" cross gammas against analytical values (and \"\n                                  << zeroCrossGammas << \" deal-unrelated cross gammas for zero).\");\n\n    // debug: dump analytical cross gamma results\n    // for(auto const& x: analyticalResultsCrossGamma) {\n    //     BOOST_TEST_MESSAGE(x.first << \" \" << x.second);\n    // }\n\n    ObservationMode::instance().setMode(backupMode);\n    IndexManager::instance().clearHistories();\n\n    BOOST_CHECK(true);\n}\n\ntest_suite* SensitivityAnalysis2Test::suite() {\n\n    test_suite* suite = BOOST_TEST_SUITE(\"SensitivityAnalysis2Test\");\n    suite->add(BOOST_TEST_CASE(&SensitivityAnalysis2Test::testSensitivities));\n    return suite;\n}\n} // namespace testsuite\n", "meta": {"hexsha": "7088a5ebf78c51f3618dcdad05baec12b22d405c", "size": 111115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/test/sensitivityanalysis2.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": "OREAnalytics/test/sensitivityanalysis2.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": "OREAnalytics/test/sensitivityanalysis2.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": 77.3242867084, "max_line_length": 120, "alphanum_fraction": 0.6294109706, "num_tokens": 39985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.19369124598242193}}
{"text": "/*\n * =====================================================================================\n *\n *       Filename:  tutor.cpp\n *\n *    Description:  Tutor class implementation\n *\n *        Version:  1.0\n *        Created:  12/13/2011 08:35:46 AM\n *       Revision:  none\n *       Compiler:  gcc\n *\n *         Author:  Sabelnikov Daniil (), dsabelnikov@gmail.com\n *        Company:  \n *\n * =====================================================================================\n */\n\n#include \"tutor.h\"\n\n#include \"common/common_include.h\"\n\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/regex.hpp>\n#include <boost/algorithm/string.hpp>\n#include \"tools/topology_factory.h\"\n#include <boost/tokenizer.hpp>\n#include \"cpu_tutor_algorithms.h\"\n#include \"cpu_tutor_algorithms_alpha.h\"\n\n#ifdef CUDA_ENABLED\n#include \"cuda_tutor_algorithms.h\"\n#endif\n\n#include <utility>\n\nusing namespace mb;\nusing namespace std;\n\nnamespace fs = boost::filesystem;\nnamespace algo = boost::algorithm;\n\ntypedef boost::tokenizer< boost::escaped_list_separator<char> > t_tokenizer;\n\n/* Constants */\nconst static char* DEVICE_OPTION = \"computation-device\";\nconst static char* POOL_SIZE_OPTION = \"pool-size\";\nconst static char* TOPOLOGY_TYPE_OPTION = \"topology-type\";\nconst static char* TOPOLOGY_INPUT_SIZE_OPTION = \"topology-input-size\";\nconst static char* TOPOLOGY_OUTPUT_SIZE_OPTION = \"topology-output-size\";\nconst static char* CONNECTED_LAYERS_TYPE = \"connected-layers\";\nconst static char* CONNECTED_LAYERS_SIZES = \"connected-layers-sizes\";\nconst static char* STEPS_OPTION = \"steps\";\nconst static char* MAX_WEIGHT_OPTION = \"max-weight\";\nconst static char* MAX_BIAS_OPTION = \"max-bias\";\nconst static char* NETWORK_TYPE_OPTION = \"network-type\";\n\nconst static boost::regex UINT_REGEX( \"[+]?[0-9]+\" );\n\n/*\n *--------------------------------------------------------------------------------------\n *       Class:  Tutor\n *      Method:  Tutor\n * Description:  constructor\n * \t\t\t\t During class initialization configuration will be parsed from a \n * \t\t\t\t configuration file.\n *--------------------------------------------------------------------------------------\n */\nTutor::Tutor () : config_file( \"conf/tutor.conf\" )\n{\n\tinit();\n}  /* -----  end of method Tutor::Tutor  (constructor)  ----- */\nTutor::Tutor ( string config_file ) : config_file( config_file )\n{\n\tinit();\n}  /* -----  end of method Tutor::Tutor  (constructor)  ----- */\n\n\nvoid Tutor::init ()\n{\n\tLOG(INFO) << \"Tutor initializaton begins...\";\n\t// Parse parameters from config file\n\tfs::path config_path( config_file );\n\n\tif ( fs::exists( config_path ) ){\n\t\ttry{\n\t\t\tfs::ifstream config_ifs( config_path, ios_base::in ); \n\t\t\tpo::store( po::parse_config_file( config_ifs, *(get_options()), true), options_vm );\n\t\t\tconfig_ifs.close();\n\t\t\tpo::notify( options_vm );\n\t\t} catch (po::required_option err) {\n\t\t\tLOG(FATAL) << \"Required option not found: \" << err.get_option_name();\n\t\t} catch (po::validation_error err) {\n\t\t\tLOG(FATAL) << \"Option value invalid: \" << err.get_option_name();\n\t\t}\n\t} else {\n\t\tLOG(FATAL) << \"Tutor config file \" << config_file << \" not found!\";\n\t}\n\n\t// Initializing topology\n\n\t/* Topology type */\n\tstring topology_type = options_vm[ TOPOLOGY_TYPE_OPTION ].as<string>();\n\n\t/* Input size */\n\tuint input_size = options_vm[ TOPOLOGY_INPUT_SIZE_OPTION ].as<uint>();\n\n\t/* Output size */\n\tuint output_size = options_vm[ TOPOLOGY_OUTPUT_SIZE_OPTION ].as<uint>();\n\n\t/* Type-specific initialization */\n\n\tif (topology_type == CONNECTED_LAYERS_TYPE){\n\n\t\t/* Connected layers sizes */\n\t\tif (options_vm.count(CONNECTED_LAYERS_SIZES) < 1){\n\t\t\tLOG(FATAL) << \"Configuration error: \\\"\" << CONNECTED_LAYERS_SIZES << \"\\\" option is required for connected layers topology\";\n\t\t}\n\t\tstring layers_sizes = options_vm[ CONNECTED_LAYERS_SIZES ].as< string >();\n\t\tt_tokenizer tok( layers_sizes );\n\n\t\tvector<uint> layers;\n\t\tforeach( string s, make_pair( tok.begin(), tok.end() ) ){\n\t\t\ttry{\n\t\t\t\tlayers.push_back( boost::lexical_cast<uint>( s ) );\n\t\t\t}catch(boost::bad_lexical_cast err){\n\t\t\t\tLOG(WARNING) << \"Configuration error: \\\"\" << CONNECTED_LAYERS_SIZES <<\n\t\t\t\t\t\"\\\", invalid format value \\\"\" << s << \"\\\" skipped\";\n\t\t\t}\n\t\t};\n\n\t\ttopology = TopologyFactory::create_connected_layers_topology(input_size, output_size, layers);\n\t}\n\n\tLOG(INFO) << \"Tutor initialization finished successfully.\";\n}\t\t/* -----  end of method Tutor::init  ----- */\n\n\n\tNetworkPtr\nTutor::get_best ()\n{\n\t// TODO\n\tNetworkPtr empty;\n\tif (pool.size() == 0){\n\t\treturn empty;\n\t}\n\tNetworkPtr best = pool[0];\n\tfloat r_max = 0;\n\tforeach(NetworkPtr net, pool){\n\t\tfloat r = NetworkTest::getReliability(net, tests);\n\t\tif (r > r_max){\n\t\t\tr_max = r;\n\t\t\tbest = net;\n\t\t}\n\t}\n\treturn best;\n}\t\t/* -----  end of method Tutor::get_best  ----- */\n\n\nvoid Tutor::set_tests ( vector<TestCasePtr> tests )\n{\n\tthis->tests = tests;\n}\t\t/* -----  end of method Tutor::set_tests  ----- */\n\n\tconst boost::shared_ptr<po::options_description>\nTutor::get_options ()\n{\n\tif (options.get() == 0){\n\t\tinit_options();\n\t}\n\treturn options;\n}\t\t/* -----  end of method Tutor::get_options  ----- */\n\n\n\tconst boost::shared_ptr<Topology>\nTutor::get_topology ()\n{\n\treturn topology;\n}\t\t/* -----  end of method Tutor::get_topology  ----- */\n\n\nvoid Tutor::init_options ()\n{\n\tpo::options_description* opt = new po::options_description(\"Tutor options\");\n\topt->add_options()\n\t\t( DEVICE_OPTION, po::value<string>(), \"CPU or CUDA\")\n\t\t( TOPOLOGY_TYPE_OPTION, po::value<string>()->required(), \"Type of topology, currently supported: connected-layers\")\n\t\t( TOPOLOGY_INPUT_SIZE_OPTION, po::value<uint>()->required(), \"Input layer size\")\n\t\t( TOPOLOGY_OUTPUT_SIZE_OPTION, po::value<uint>()->required(), \"Output layer size\")\n\t\t( CONNECTED_LAYERS_SIZES, po::value< string >(), \"'connected-layers' topology settings: sizes of layers, delimeted by commas or whitespaces.\")\n\t\t( POOL_SIZE_OPTION, po::value< uint >()->required(), \"Network pool size, the number of networks in one generation\")\n\t\t( STEPS_OPTION, po::value<uint>()->required(), \"The number of education steps to perform\")\n\t\t( MAX_WEIGHT_OPTION, po::value<t_weight>(), \"The maximum connection weight for generated networks\")\n\t\t( MAX_BIAS_OPTION, po::value<t_weight>(), \"The maximum bias for generated networks\")\n\t\t( NETWORK_TYPE_OPTION, po::value<string>()->default_value(\"omega\"), \"The type of the neuro-network\");\n\toptions.reset( opt );\n}\t\t/* -----  end of method Tutor::init_options  ----- */\n\n\n\tboost::shared_ptr<TutorAlgorithms>\nTutor::init_algorithms ()\n{\n\tboost::shared_ptr<TutorAlgorithms> ptr;\n\tstring device = options_vm[ DEVICE_OPTION ].as< string >();\n\n#ifndef CUDA_ENABLED\n\tif(device == \"CUDA\"){\n\t\tLOG(WARNING) << \"Tutor has been compiled without CUDA support, 'CUDA' device not allowed. Falling back to CPU.\";\n\t\tdevice = \"CPU\";\n\t}\n#endif\n\tif (device != \"CPU\" && device != \"CUDA\"){\n\t\tLOG(WARNING) << \"Specified computation device \" << device << \" is not supported. Using default - CPU.\";\n\t\tdevice = \"CPU\";\n\t}\n\n\tstring network_type = options_vm[ NETWORK_TYPE_OPTION ].as<string>();\n\n\tif (device == \"CPU\"){\n\t\tif (network_type == \"alpha\"){\n\t\t\tLOG(INFO) << \"Network type: Alpha\";\n\t\t\tptr.reset( new CPUTutorAlgorithmsAlpha() ); \n\t\t} else {\n\t\t\tLOG(INFO) << \"Network type: Omega\";\n\t\t\tptr.reset( new CPUTutorAlgorithms() ); \n\t\t}\n\t} else if (device == \"CUDA\"){\n#ifdef CUDA_ENABLED\n\t\tif (network_type == \"alpha\"){\n\t\t\tLOG(INFO) << \"Network type: Alpha\";\n\t\t\tptr.reset( new CUDATutorAlgorithms(\"alpha\") );\n\t\t} else {\n\t\t\tLOG(INFO) << \"Network type: Omega\";\n\t\t\tptr.reset( new CUDATutorAlgorithms() );\n\t\t}\n#endif\n\t}\n\treturn ptr;\n}\t\t/* -----  end of method Tutor::init_algorithms  ----- */\n\n\nbool\nTutor::is_CUDA ()\n{\n\tstring device = options_vm[ DEVICE_OPTION ].as< string >();\n\treturn device == \"CUDA\";\n}\t\t/* -----  end of method Tutor::is_CUDA  ----- */\n\n\n\n/*\n *--------------------------------------------------------------------------------------\n *       Class:  Tutor\n *      Method:  Tutor :: educate\n * Description:  Perform neural network education. This method calls the TutorAlgorithms\n * \t\t\t\t routines to perform following steps in education process:\n * \t\t\t\t 1. reproduction() - fill certain amount of next generation pool with\n * \t\t\t\t    children originated from current pool.\n * \t\t\t\t 2. mutation() - perform a rendom mutation on current generation pool.\n * \t\t\t\t 3. examination() - test all network with loaded testcases,\n * \t\t\t\t    result of the examination will be returned in an array of scores\n * \t\t\t\t    that will be used to select the best network on next step.\n * \t\t\t\t 4. selection() - do a natural selection, this is a partly rendom process\n * \t\t\t\t    that selects best networks according to their scores at examination.\n * \t\t\t\t 5. check if stop condition emerged.\n *--------------------------------------------------------------------------------------\n */\nvoid Tutor::educate ()\n{\n\tif (tests.size() == 0){\n\t\tLOG(WARNING) << \"No test cases loaded. Ignoring call to education()...\";\n\t\treturn;\n\t}\n\n\tLOG(INFO) << \"Education process start.\";\n\n\tboost::shared_ptr<TutorAlgorithms> algos = init_algorithms();\t\n\tuint pool_size = options_vm[ POOL_SIZE_OPTION ].as< uint >();\n\n\tfloat reproduction_ratio = 0.5;\n\tfloat mutation_ratio = 0.5;\n\n\t// -- Load Max weight and max bias from options\n\t//\n\tt_weight max_weight = 1;\n\tt_weight max_bias = 1;\n\n\tif ( options_vm.count( MAX_WEIGHT_OPTION ) != 0 ){\n\t\tmax_weight = options_vm[ MAX_WEIGHT_OPTION ].as<t_weight>();\n\t}\n\tif ( options_vm.count( MAX_BIAS_OPTION ) != 0 ){\n\t\tmax_bias = options_vm[ MAX_BIAS_OPTION ].as<t_weight>();\n\t}\n\n\tuint steps = options_vm[ STEPS_OPTION ].as<uint>();\n\n\t// -- Clear network pools\n\t//\n\tpool.clear();\n\t_pool.clear();\n\n\t// -- Fill first pool with random networks\n\t//\n\tsrand( time(NULL) );\n\tNetworkPtr *ptr;\n\tfor (uint i = 0; i < pool_size; i++){\n\t\tptr = new NetworkPtr( new Network(topology.get(), max_weight, max_bias) ); \n\t\tpool.push_back( *ptr );\n\t}\n\n\t// -- Education cycle start\n\t//\n\tuint step = 1;\n\twhile (true){\n\n\t\tLOG(INFO) << \" -- Starting step #\" << step;\n\t\tclock_t step_start = clock();\n\n\t\t// -- 1. Reproduction.\n\t\t//\n\t\tforeach( NetworkPtr ptr, algos->reproduction( pool, reproduction_ratio ) ){\n\t\t\t_pool.push_back(ptr);\n\t\t}\n\t\t// FIXME experimentail feature: throwing in two new networks\n\t\tif (_pool.size() > 2){\n\t\t\t_pool.pop_back();\n\t\t\t_pool.pop_back();\n\t\t\t_pool.push_back( *(new NetworkPtr(new Network(topology.get(), max_weight, max_bias))) );\n\t\t\t_pool.push_back( *(new NetworkPtr(new Network(topology.get(), max_weight, max_bias))) );\n\t\t}\n\t\tassert( pool.size() == pool_size );\n\n\t\t// -- 2. Mutation.\n\t\t//\n//\t\talgos->mutation( _pool, mutation_ratio, step/100 );\n\t\talgos->mutation( pool, mutation_ratio, 0 );\n\t\tassert( pool.size() == pool_size );\n\n\t\t// -- 3. Examination.\n\t\t//\n\t\tvector<float> scores = algos->examination( pool, tests );\n\t\tassert( pool.size() == pool_size );\n\n\t\t// -- Print scores\n\t\t//\n\t\tvector<float> sorted_scores;\n\t\tsorted_pool.clear();\n\t\tfor(uint i = 0; i < scores.size(); i++){\n\t\t\tfloat score = scores[i];\n\t\t\tvector<float>::iterator iter = lower_bound(sorted_scores.begin(), sorted_scores.end(), score);\n\t\t\tint index = iter - sorted_scores.begin();\n\t\t\tsorted_scores.insert(iter, score);\n\t\t\tsorted_pool.insert(sorted_pool.begin() + index, pool[i]);\n\t\t}\n\t\tLOG(INFO) << \"  Sorted scores:\";\n\t\tfor (uint i = 0; i < 5 && i < sorted_scores.size(); i++){\n\t\t\tLOG(INFO) << \"    \" << sorted_scores[i];\n\t\t}\n \n\t\t// -- 4. Selection.\n\t\t//\n\t\tforeach( NetworkPtr ptr, algos->selection( pool, scores, 1 - reproduction_ratio ) ){\n\t\t\t_pool.push_back( ptr );\n\t\t}\n\n\t\tassert( pool.size() == pool_size );\n\t\tassert( _pool.size() == pool_size );\n\n\t\t// -- 5. Check stop condition\n\t\t//\n\t\tif (step >= steps){\n\t\t\tbreak;\n\t\t}\n\n\t\t// -- Increment step counter\n\t\tstep++;\n\n\t\t// -- Swap pools\n\t\tpool.clear();\n\t\tforeach( NetworkPtr ptr, _pool ){\n\t\t\tpool.push_back( ptr );\n\t\t}\n\t\t_pool.clear();\n\n\t\t// -- Step finished\n\t\tLOG(INFO) << \" -- Step finished in: \" << (float)( clock() - step_start ) / CLOCKS_PER_SEC << \"sec.\";\n\n\t\t// -- Debug\n\t\tif (step % 20 == 0){\n\t\t\tcout << \"Starting step #\" << step << endl;\n\t\t\tif (pool.size() >= 5){\n\t\t\t\tcout << \"Top 5 reliabilities: \";\n\t\t\t\tfor (uint i = 0; i < 5; i++){\n\t\t\t\t\tcout << NetworkTest::getReliability(sorted_pool[i], tests) << \", \";\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t\tcout << \"Top 5 advantages: \";\n\t\t\t\tfor (uint i = 0; i < 5; i++){\n\t\t\t\t\tcout << NetworkTest::getAdvantage(sorted_pool[i], tests) << \", \";\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t}\n\n\t}\n\n#ifdef CUDA_ENABLED\n\t// -- Releasing memory for CUDA device\n\t//\n\tif (is_CUDA()){\n\t\tboost::static_pointer_cast<CUDATutorAlgorithms>(algos)->free();\n\t}\n#endif\n\n\tLOG(INFO) << \"Education finished\";\n}\t\t/* -----  end of method Tutor::educate  ----- */\n\n", "meta": {"hexsha": "877b1557833f733ca938a8674b4f29495046c901", "size": 12644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/education/tutor.cpp", "max_stars_repo_name": "dragn/monster-bid", "max_stars_repo_head_hexsha": "a4df5205a59941fbae77393efa00a005f2ec96cc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T10:05:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-05T10:05:33.000Z", "max_issues_repo_path": "src/education/tutor.cpp", "max_issues_repo_name": "dragn/monster-bid", "max_issues_repo_head_hexsha": "a4df5205a59941fbae77393efa00a005f2ec96cc", "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/education/tutor.cpp", "max_forks_repo_name": "dragn/monster-bid", "max_forks_repo_head_hexsha": "a4df5205a59941fbae77393efa00a005f2ec96cc", "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.1047619048, "max_line_length": 144, "alphanum_fraction": 0.6270167668, "num_tokens": 3269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.359364145160102, "lm_q1q2_score": 0.1936912443580682}}
{"text": "\r\n#include \"OpenCVStitcher.h\"\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <cstdint>\r\n\r\n#include <Eigen/LU>\r\n\r\n#include <opencv2/imgcodecs.hpp>\r\n#include <opencv2/core.hpp>\r\n#include <opencv2/core/utility.hpp>\r\n#include <opencv2/imgproc.hpp>\r\n\r\n\r\nOpenCVStitcher::OpenCVStitcher()\r\n{\r\n}\r\n\r\nOpenCVStitcher::~OpenCVStitcher()\r\n{\r\n\r\n}\r\n\r\nvoid OpenCVStitcher::setup()\r\n{\r\n\tcv::setUseOptimized(true);\r\n\r\n\tcv::Ptr<cv::kinfu::Params> params = cv::kinfu::Params::defaultParams();\r\n\tparams->volumeDims(0) = 128;\r\n\tparams->volumeDims(1) = 128;\r\n\tparams->volumeDims(2) = 128;\r\n\tparams->depthFactor = 1000.0;\r\n\tdepthFactor_ = params->depthFactor;\r\n\r\n\tdynfu_ = cv::dynafu::DynaFu::create(params);\r\n\t//dynfu_ = cv::kinfu::KinFu::create(params);\r\n}\r\n\r\nvoid OpenCVStitcher::addNewImage(const open3d::geometry::Image& colorImg, const open3d::geometry::Image& depthImg)\r\n{\r\n\tstd::unique_lock<std::mutex> lock(mutex_);\r\n\r\n\tcv::Mat depth, depthF;\r\n\tdepth.create(depthImg.height_, depthImg.width_, CV_16UC1);\r\n\tstd::int_fast16_t* cvPtr = depth.ptr<std::int_fast16_t>(0);\r\n\tunsigned char* dataPtr = depthImg.PointerAt<unsigned char>(0, 0, 0);\r\n\tmemcpy(cvPtr, &(depthImg.data_[0]), 2 * depthImg.height_ * depthImg.width_);\r\n\r\n\tdepth.convertTo(depthF, CV_32F);\r\n\r\n\r\n\tcv::UMat cvt8;\r\n\tconvertScaleAbs(depthF, cvt8, 0.25 * 256. / depthFactor_);\r\n\r\n\tbool isOk = dynfu_->update(cvt8);\r\n\r\n\tif (isOk)\r\n\t\tstd::cout << \"Registering successful\" << std::endl;\r\n\telse\r\n\t\tstd::cout << \"Registering not successful\" << std::endl;\r\n}\r\n\r\nvoid OpenCVStitcher::saveVolume()\r\n{\r\n\tstd::unique_lock<std::mutex> lock(mutex_);\r\n\r\n\t//cv::Mat3d points, normals;\r\n\tcv::Mat points, normals;\r\n\r\n\tdynfu_->getCloud(points, normals);\r\n\r\n\tcv::Mat img;\r\n\timg.create(512, 512, CV_8UC3);\r\n\tdynfu_->render(img);\r\n\tcv::imwrite(\"render.png\", img);\r\n}\r\n\r\nvoid OpenCVStitcher::reset()\r\n{\r\n\tstd::unique_lock<std::mutex> lock(mutex_);\r\n\r\n}\r\n\r\nopen3d::geometry::Image OpenCVStitcher::convertCVToO3D(const cv::Mat& cvimg)\r\n{\r\n\topen3d::geometry::Image img;\r\n\tif (cvimg.channels() == 3)\r\n\t{\r\n\t\t// Color\r\n\t\tcv::Mat tmpI;\r\n\t\tcv::cvtColor(cvimg, tmpI, cv::COLOR_RGB2BGR);\r\n\t\timg.Prepare(tmpI.cols, tmpI.rows, 3, 1);\r\n\t\tunsigned char* dataPtr = img.PointerAt<unsigned char>(0, 0, 0);\r\n\t\tmemcpy(dataPtr, tmpI.ptr(), 3 * tmpI.cols * tmpI.rows);\r\n\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// Depth\r\n\t\t//double minVal, maxVal;\r\n\t\t//cv::minMaxLoc(cvimg, &minVal, &maxVal);\r\n\t\t//std::cout << \"Min: \" << minVal << \", max: \" << maxVal << std::endl;\r\n\r\n\t\timg.Prepare(cvimg.cols, cvimg.rows, 1, 2);\r\n\t\tunsigned char* dataPtr = img.PointerAt<unsigned char>(0, 0, 0);\r\n\t\tmemcpy(dataPtr, cvimg.ptr(), 2 * cvimg.cols * cvimg.rows);\r\n\t}\r\n\r\n\treturn img;\r\n}\r\n", "meta": {"hexsha": "0e259eda59cc19d199349d215a193a1296782c23", "size": 2652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OpenCVStitcher.cpp", "max_stars_repo_name": "rhiestan/Open3DTest", "max_stars_repo_head_hexsha": "36aa3398dc6a1e5f0d7cda39a3e53c16081a63c9", "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/OpenCVStitcher.cpp", "max_issues_repo_name": "rhiestan/Open3DTest", "max_issues_repo_head_hexsha": "36aa3398dc6a1e5f0d7cda39a3e53c16081a63c9", "max_issues_repo_licenses": ["MIT"], "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/OpenCVStitcher.cpp", "max_forks_repo_name": "rhiestan/Open3DTest", "max_forks_repo_head_hexsha": "36aa3398dc6a1e5f0d7cda39a3e53c16081a63c9", "max_forks_repo_licenses": ["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.6785714286, "max_line_length": 115, "alphanum_fraction": 0.657239819, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19369124435806817}}
{"text": "/***************************************************************************\n * Copyright 1998-2017 by authors (see AUTHORS.txt)                        *\n *                                                                         *\n *   This file is part of LuxRender.                                       *\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 <stdexcept>\n#include <boost/foreach.hpp>\n#include <boost/regex.hpp>\n\n#include \"luxrays/kernels/kernels.h\"\n#include \"slg/kernels/kernels.h\"\n#include \"slg/film/film.h\"\n#include \"slg/film/imagepipeline/plugins/mist.h\"\n\nusing namespace std;\nusing namespace luxrays;\nusing namespace slg;\n\n//------------------------------------------------------------------------------\n// Mist plugin\n//------------------------------------------------------------------------------\n\nBOOST_CLASS_EXPORT_IMPLEMENT(slg::MistPlugin)\n\nMistPlugin::MistPlugin(const luxrays::Spectrum &color, float amount, float start, float end, bool excludeBackground) \n\t: color(color), amount(amount), start(start), end(end), excludeBackground(excludeBackground)\n{}\n\nMistPlugin::MistPlugin() \n\t: color(1.f), amount(1.f), start(0.f), end(1000.f), excludeBackground(false)\n{}\n\nImagePipelinePlugin *MistPlugin::Copy() const {\n\treturn new MistPlugin(color, amount, start, end, excludeBackground);\n}\n\n//------------------------------------------------------------------------------\n// CPU version\n//------------------------------------------------------------------------------\n\nvoid MistPlugin::Apply(Film &film, const u_int index) {\n\tif (!film.HasChannel(Film::DEPTH)) {\n\t\t// I can not work without depth channel\n\t\treturn;\n\t}\n\n\tSpectrum *pixels = (Spectrum *)film.channel_IMAGEPIPELINEs[index]->GetPixels();\n\tconst u_int pixelCount = film.GetWidth() * film.GetHeight();\n\t\n\t// Optimization: invert to avoid division in the loop\n\tconst float rangeInv = 1.f / (end - start);\n\n\t#pragma omp parallel for\n\tfor (\n\t\t\t// Visual C++ 2013 supports only OpenMP 2.5\n#if _OPENMP >= 200805\n\t\t\tunsigned\n#endif\n\t\t\tint i = 0; i < pixelCount; ++i) {\n\t\tif (*(film.channel_FRAMEBUFFER_MASK->GetPixel(index))) {\n\t\t\tconst float depthValue = *(film.channel_DEPTH->GetPixel(i));\n\t\t\tif(depthValue <= start) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(isinf(depthValue)) {\n\t\t\t\tif(excludeBackground) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpixels[i] = Lerp(amount, pixels[i], color);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// The use of -3 instead of -1 will cause weight to be 95% at end and then slowly go to 100% towards infinity\n\t\t\t\tconst float weight = 1.f - exp(-3.f * (depthValue - start) * rangeInv);\n\t\t\t\tpixels[i] = Lerp(weight * amount, pixels[i], color);\n\t\t\t}\n\t\t}\n\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", "meta": {"hexsha": "dc7db8bd89b9263cd2f4c36bcd9a4bb0dfbfa9b1", "size": 3623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/slg/film/imagepipeline/plugins/mist.cpp", "max_stars_repo_name": "LuxRender/LuxRays", "max_stars_repo_head_hexsha": "edb001ddeb744b534f6fe98c7b789d4635196718", "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/film/imagepipeline/plugins/mist.cpp", "max_issues_repo_name": "LuxRender/LuxRays", "max_issues_repo_head_hexsha": "edb001ddeb744b534f6fe98c7b789d4635196718", "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/film/imagepipeline/plugins/mist.cpp", "max_forks_repo_name": "LuxRender/LuxRays", "max_forks_repo_head_hexsha": "edb001ddeb744b534f6fe98c7b789d4635196718", "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.4453781513, "max_line_length": 117, "alphanum_fraction": 0.5059343086, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.19369124066003043}}
{"text": "#include <iostream>\n#include <unordered_map>\n#include <cstdlib>\n\n#include \"corpus/corpus.h\"\n#include \"cpyp/m.h\"\n#include \"cpyp/random.h\"\n#include \"cpyp/crp.h\"\n#include \"cpyp/mf_crp.h\"\n#include \"cpyp/tied_parameter_resampler.h\"\n#include \"uvector.h\"\n#include \"dhpyplm.h\"\n\n#include \"cpyp/boost_serializers.h\"\n#include <boost/serialization/vector.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n\n// A not very memory-efficient implementation of a domain adapting\n// HPYP language model, as described by Wood & Teh (AISTATS, 2009)\n//\n// I use templates to handle the recursive formalation of the prior, so\n// the order of the model has to be specified here, at compile time:\n#define kORDER 3\n\nusing namespace std;\nusing namespace cpyp;\n\nDict dict;\n\nint main(int argc, char** argv) {\n  if (argc < 4) {\n    cerr << argv[0] << \" <training1.txt> <training2.txt> [...] <output.dlm> <nsamples>\\n\\nInfer a \" << kORDER << \"-gram HPYP LM and write the trained model\\n100 is usually sufficient for <nsamples>\\n\";\n    return 1;\n  }\n  MT19937 eng;\n  vector<string> train_files;\n  for (int i = 1; i < argc - 2; ++i)\n    train_files.push_back(argv[i]);\n  string output_file = argv[argc - 2];\n  int samples = atoi(argv[argc - 1]);\n  assert(samples > 0);\n  {\n    ifstream test(output_file);\n    if (test.good()) {\n      cerr << \"File \" << output_file << \" appears to exist: please remove\\n\";\n      return 1;\n    }\n  }\n\n  int d = 1;\n  for (auto& tf : train_files)\n    cerr << (d++==1 ? \"  [primary] \" : \"[secondary] \")\n         << \"training corpus \"<< \": \" << tf << endl;\n  set<unsigned> vocab;\n  const unsigned kSOS = dict.Convert(\"<s>\");\n  const unsigned kEOS = dict.Convert(\"</s>\");\n  vector<vector<vector<unsigned> > > corpora(train_files.size());\n  d = 0;\n  for (const auto& train_file : train_files)\n    ReadFromFile(train_file, &dict, &corpora[d++], &vocab);\n\n  PYPLM<kORDER> latent_lm(vocab.size(), 1, 1, 1, 1);\n  vector<DAPYPLM<kORDER>> dlm(corpora.size(), DAPYPLM<kORDER>(latent_lm)); // domain LMs\n  vector<unsigned> ctx(kORDER - 1, kSOS);\n  for (int sample=0; sample < samples; ++sample) {\n    int ci = 0;\n    for (const auto& corpus : corpora) {\n      DAPYPLM<kORDER>& lm = dlm[ci];\n      ++ci;\n      for (const auto& s : corpus) {\n        ctx.resize(kORDER - 1);\n        for (unsigned i = 0; i <= s.size(); ++i) {\n          unsigned w = (i < s.size() ? s[i] : kEOS);\n          if (sample > 0) lm.decrement(w, ctx, eng);\n          lm.increment(w, ctx, eng);\n          ctx.push_back(w);\n        }\n      }\n    }\n    if (sample % 10 == 9) {\n      double llh = latent_lm.log_likelihood();\n      for (auto& lm : dlm) llh += lm.log_likelihood();\n      cerr << \" [LLH=\" << llh << \"]\\n\";\n      if (sample % 30u == 29) {\n        for (auto& lm : dlm) lm.resample_hyperparameters(eng);\n        latent_lm.resample_hyperparameters(eng);\n      }\n    } else { cerr << '.' << flush; }\n  }\n  cerr << \"Writing LM to \" << output_file << \" ...\\n\";\n  ofstream ofile(output_file.c_str(), ios::out | ios::binary);\n  if (!ofile.good()) {\n    cerr << \"Failed to open \" << output_file << \" for writing\\n\";\n    return 1;\n  }\n  boost::archive::binary_oarchive oa(ofile);\n  oa & dict;\n  oa & latent_lm;\n  unsigned num_domains = dlm.size();\n  oa & num_domains;\n  for (unsigned i = 0; i < num_domains; ++i)\n    oa & dlm[i];\n  return 0;\n}\n\n", "meta": {"hexsha": "92350022986d731a1dca3b7d0ea9ed9ec69d72a8", "size": 3301, "ext": "cc", "lang": "C++", "max_stars_repo_path": "hpyplm/dhpyplm_train.cc", "max_stars_repo_name": "redpony/cpyp", "max_stars_repo_head_hexsha": "7ecb1801af3636f9d5ae008799ae412d476153e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-01-21T07:18:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T00:57:54.000Z", "max_issues_repo_path": "hpyplm/dhpyplm_train.cc", "max_issues_repo_name": "redpony/cpyp", "max_issues_repo_head_hexsha": "7ecb1801af3636f9d5ae008799ae412d476153e2", "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": "hpyplm/dhpyplm_train.cc", "max_forks_repo_name": "redpony/cpyp", "max_forks_repo_head_hexsha": "7ecb1801af3636f9d5ae008799ae412d476153e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-02-25T06:02:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T00:57:38.000Z", "avg_line_length": 31.141509434, "max_line_length": 201, "alphanum_fraction": 0.6073916995, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.1936912406600304}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include\"Eigen/Dense\"\n#include <vector>\n#include <iostream>\n#include <QString>\n#include <QList>\n#include \"Robot.h\"\n//#include\"TaskSpace.h\"\n#include\"taskspaceoffline.h\"\n#include <qmath.h>\n#include <cstring>\n#include<qdebug.h>\n#include <Eigen/Geometry>\n#include <cstdlib>\n//#include <link.h>\n#include \"Eigen/eiquadprog.h\"\n#include \"Eigen/Core\"\n#include \"Eigen/Cholesky\"\n#include \"Eigen/LU\"\n#include<std_msgs/Int32MultiArray.h>\n#include<std_msgs/Float32MultiArray.h>\n#include<math.h>\n#include<sensor_msgs/Imu.h>\n#include<std_msgs/Float64.h>\n#include \"qcgenerator.h\"\n\n\n#include<sensor_msgs/Imu.h>\n#include<std_msgs/Float64.h>\n#include \"pidcontroller.h\"\n#include<rosgraph_msgs/Clock.h>\n\n#include \"std_msgs/String.h\"\n#include<gazebo_msgs/ApplyBodyWrench.h>\n\n#include<gazebo_msgs/ApplyBodyWrenchRequest.h>\n#include <gazebo_msgs/GetLinkState.h>\n#include<gazebo_msgs/LinkStates.h>\n#include <nav_msgs/Odometry.h>\n#include \"std_srvs/Empty.h\"\n#include \"qcgenerator.h\"\n#include \"/home/cast/humanoid/surena4/devel/include/xsens_msgs/Internal.h\"\n#include \"/home/cast/humanoid/surena4/devel/include/xsens_msgs/velocityEstimate.h\"\n#include \"/home/cast/humanoid/surena4/devel/include/xsens_msgs/sensorSample.h\"\n#include \"/home/cast/humanoid/surena4/devel/include/xsens_msgs/ImuSensorSample.h\"\n#include \"/home/cast/humanoid/surena4/devel/include/xsens_msgs/orientationEstimate.h\"\n#include \"/home/cast/humanoid/surena4/devel/include/xsens_msgs/positionEstimate.h\"\n#include \"/home/cast/humanoid/surena4/devel/include/xsens_msgs/velocityEstimate.h\"\n#include \"/home/cast/humanoid/surena4/devel/include/xsens_msgs/XsensQuaternion.h\"\n\nusing namespace  std;\nusing namespace  Eigen;\n//data of left foot sensor\n\ndouble n_f;\ndouble w_y;\ndouble w_y_f;\ndouble pitch;\ndouble pitch_bias;\n\n\nvector<double> w_y_s(100);\nros::Publisher pub1  ;\nros::Publisher pub2  ;\nros::Publisher pub3  ;\nros::Publisher pub4  ;\nros::Publisher pub5  ;\nros::Publisher pub6  ;\nros::Publisher pub7  ;\nros::Publisher pub8  ;\nros::Publisher pub9  ;\nros::Publisher pub10 ;\nros::Publisher pub11 ;\nros::Publisher pub12 ;\nros::Publisher pub13 ;\nros::Publisher pub14 ;\nros::Publisher pub15 ;\nros::Publisher pub16 ;\nros::Publisher pub17 ;\nros::Publisher pub18 ;\nros::Publisher pub19 ;\nros::Publisher pub20 ;\nros::Publisher pub21 ;\nros::Publisher pub22 ;\nros::Publisher pub23 ;\nros::Publisher pub24 ;\nros::Publisher pub25 ;\nros::Publisher pub26 ;\nros::Publisher pub27 ;\nros::Publisher pub28 ;\n\n//ros::Publisher pid1 ;\n\nPIDController push_recovery_knee;\nPIDController push_recovery_hip;\nPIDController push_recovery_ankle;\n\n\n//void  SendGazebo(QList<LinkM> links){\n//    if(links.count()<28){qDebug()<<\"index err\";return;}\n//    std_msgs::Float64 data;\n//    data.data=links[1].JointAngle;\n//    pub1.publish(data);\n//    data.data=links[2].JointAngle;\n//    pub2.publish(data);\n//    data.data=links[3].JointAngle;\n//    pub3.publish(data);\n//    data.data=links[4].JointAngle;\n//    pub4.publish(data);\n//    data.data=links[5].JointAngle;\n//    pub5.publish(data);\n//    data.data=links[6].JointAngle;\n//    pub6.publish(data);\n//    data.data=links[7].JointAngle;\n//    pub7.publish(data);\n//    data.data=links[8].JointAngle;\n//    pub8.publish(data);\n//    data.data=links[9].JointAngle;\n//    pub9.publish(data);\n//    data.data=links[10].JointAngle;\n//    pub10.publish(data);\n//    data.data=links[11].JointAngle;\n//    pub11.publish(data);\n//    data.data=links[12].JointAngle;\n//    pub12.publish(data);\n//    data.data=links[13].JointAngle;\n//    pub13.publish(data);\n//    data.data=links[14].JointAngle;\n//    pub14.publish(data);\n//    data.data=links[15].JointAngle;\n//    pub15.publish(data);\n//    data.data=links[16].JointAngle;\n//    pub16.publish(data);\n//    data.data=links[17].JointAngle;\n//    pub17.publish(data);\n//    data.data=links[18].JointAngle;\n//    pub18.publish(data);\n//    data.data=links[19].JointAngle;\n//    pub19.publish(data);\n//    data.data=links[20].JointAngle;\n//    pub20.publish(data);\n//    data.data=links[21].JointAngle;\n//    pub21.publish(data);\n//    data.data=links[22].JointAngle;\n//    pub22.publish(data);\n//    data.data=links[23].JointAngle;\n//    pub23.publish(data);\n//    data.data=links[24].JointAngle;\n//    pub24.publish(data);\n//    data.data=links[25].JointAngle;\n//    pub25.publish(data);\n//    data.data=links[26].JointAngle;\n//    pub26.publish(data);\n//    data.data=links[27].JointAngle;\n//    pub27.publish(data);\n//    data.data=links[28].JointAngle;\n//    pub28.publish(data);\n//}\n\n\n\n\nvoid  SendGazebo(vector<double> ctrl){\n\n    std_msgs::Float64 data;\n    data.data=ctrl[1];\n    pub1.publish(data);\n    data.data=ctrl[2];\n    pub2.publish(data);\n    data.data=ctrl[3];\n    pub3.publish(data);\n    data.data=ctrl[4];\n    pub4.publish(data);\n    data.data=ctrl[5];\n    pub5.publish(data);\n    data.data=ctrl[6];\n    pub6.publish(data);\n    data.data=ctrl[7];\n    pub7.publish(data);\n    data.data=ctrl[8];\n    pub8.publish(data);\n    data.data=ctrl[9];\n    pub9.publish(data);\n    data.data=ctrl[10];\n    pub10.publish(data);\n    data.data=ctrl[11];\n    pub11.publish(data);\n    data.data=ctrl[12];\n    pub12.publish(data);\n    data.data=0;\n    pub13.publish(data);\n    data.data=0;\n    pub14.publish(data);\n    data.data=0;\n    pub15.publish(data);\n    data.data=0-10*M_PI/180;\n    pub16.publish(data);\n    data.data=0;\n    pub17.publish(data);\n    data.data=0;\n    pub18.publish(data);\n    data.data=0;\n    pub19.publish(data);\n    data.data=0;\n    pub20.publish(data);\n    data.data=0;\n    pub21.publish(data);\n    data.data=0;\n    pub22.publish(data);\n    data.data=0+10*M_PI/180;\n    pub23.publish(data);\n    data.data=0;\n    pub24.publish(data);\n    data.data=0;\n    pub25.publish(data);\n    data.data=0;\n    pub26.publish(data);\n    data.data=0;\n    pub27.publish(data);\n    data.data=0;\n    pub28.publish(data);\n\n\n\n}\n\n\nvoid RecievIMU_w(const sensor_msgs::Imu & msg)\n{\n\n    for (int var = n_f-1; var > 0; --var) {\n        w_y_s[var]=w_y_s[var-1];\n    }\n    w_y= msg.angular_velocity.y;\n    w_y_s[0]=w_y;\n    double sum=0;\n    for (int var = 0; var < n_f; ++var) {\n        sum=sum+w_y_s[var];\n    }\n    w_y_f=sum/n_f;\n}\n\nvoid RecievIMU_pitch(const xsens_msgs::orientationEstimate & msg)\n{\n    pitch=msg.pitch;\n}\n\n\n\nint main(int argc, char **argv)\n{\n    n_f=5;\n    for (int var = 0; var < n_f; ++var) {\n        w_y_s[var]=0;\n    }\n    vector<double> cntrl(13);\n    vector<double> push_state(13);\n    QCgenerator QC;\n    //check _timesteps\n    QElapsedTimer timer;\n    Robot SURENA;\n    TaskSpaceOffline SURENAOffilneTaskSpace;\n    QList<LinkM> links;\n    MatrixXd PoseRoot;\n    MatrixXd PoseRFoot;\n    MatrixXd PoseLFoot;\n    double dt;\n\n    double k_ankle=0;\n    double k_knee=-.3;\n    double k_hip=0;\n\n\n\n\n\n    double StartTime=0;\n\n    double  DurationOfStartPhase=6;\n    double DurationOfPitchBias=.1;\n    double DurationOfPushPhase=30;\n    double  DurationOfBacktoKnee=2;\n    double  DurationOfendPhase=6;\n    //SURENAOffilneTaskSpace.GetAccVelPos();\n    bool startPhase=true;\n\n    PoseRoot.resize(6,1);\n    PoseRFoot.resize(6,1);\n    PoseLFoot.resize(6,1);\n\n    //*******************This part of code is for initialization of joints of the robot for walking**********************************\n    int count = 0;\n\n    ros::init(argc, argv, \"myNode\");\n\n    ros::NodeHandle nh;\n    ros::Publisher  chatter_pub  = nh.advertise<std_msgs::Int32MultiArray>(\"jointdata/qc\",1000);\n\n\n    ros::Subscriber  IMU_xsense = nh.subscribe(\"/mti/sensor/imu\", 100, RecievIMU_w);\n   // ros::Subscriber  IMU_xsense = nh.subscribe(\"/mti/filter/orientation\", 100, RecievIMU_pitch);\n\n\n        pub1  = nh.advertise<std_msgs::Float64>(\"rrbot/joint1_position_controller/command\",1000);\n        pub2  = nh.advertise<std_msgs::Float64>(\"rrbot/joint2_position_controller/command\",1000);\n        pub3  = nh.advertise<std_msgs::Float64>(\"rrbot/joint3_position_controller/command\",1000);\n        pub4  = nh.advertise<std_msgs::Float64>(\"rrbot/joint4_position_controller/command\",1000);\n        pub5  = nh.advertise<std_msgs::Float64>(\"rrbot/joint5_position_controller/command\",1000);\n        pub6  = nh.advertise<std_msgs::Float64>(\"rrbot/joint6_position_controller/command\",1000);\n        pub7  = nh.advertise<std_msgs::Float64>(\"rrbot/joint7_position_controller/command\",1000);\n        pub8  = nh.advertise<std_msgs::Float64>(\"rrbot/joint8_position_controller/command\",1000);\n        pub9  = nh.advertise<std_msgs::Float64>(\"rrbot/joint9_position_controller/command\",1000);\n        pub10 = nh.advertise<std_msgs::Float64>(\"rrbot/joint10_position_controller/command\",1000);\n        pub11 = nh.advertise<std_msgs::Float64>(\"rrbot/joint11_position_controller/command\",1000);\n        pub12 = nh.advertise<std_msgs::Float64>(\"rrbot/joint12_position_controller/command\",1000);\n        pub13 = nh.advertise<std_msgs::Float64>(\"rrbot/joint13_position_controller/command\",1000);\n        pub14 = nh.advertise<std_msgs::Float64>(\"rrbot/joint14_position_controller/command\",1000);\n        pub15 = nh.advertise<std_msgs::Float64>(\"rrbot/joint15_position_controller/command\",1000);\n        pub16 = nh.advertise<std_msgs::Float64>(\"rrbot/joint16_position_controller/command\",1000);\n        pub17 = nh.advertise<std_msgs::Float64>(\"rrbot/joint17_position_controller/command\",1000);\n        pub18 = nh.advertise<std_msgs::Float64>(\"rrbot/joint18_position_controller/command\",1000);\n        pub19 = nh.advertise<std_msgs::Float64>(\"rrbot/joint19_position_controller/command\",1000);\n        pub20 = nh.advertise<std_msgs::Float64>(\"rrbot/joint20_position_controller/command\",1000);\n        pub21 = nh.advertise<std_msgs::Float64>(\"rrbot/joint21_position_controller/command\",1000);\n        pub22 = nh.advertise<std_msgs::Float64>(\"rrbot/joint22_position_controller/command\",1000);\n        pub23 = nh.advertise<std_msgs::Float64>(\"rrbot/joint23_position_controller/command\",1000);\n        pub24 = nh.advertise<std_msgs::Float64>(\"rrbot/joint24_position_controller/command\",1000);\n        pub25 = nh.advertise<std_msgs::Float64>(\"rrbot/joint25_position_controller/command\",1000);\n        pub26 = nh.advertise<std_msgs::Float64>(\"rrbot/joint26_position_controller/command\",1000);\n        pub27 = nh.advertise<std_msgs::Float64>(\"rrbot/joint27_position_controller/command\",1000);\n        pub28 = nh.advertise<std_msgs::Float64>(\"rrbot/joint28_position_controller/command\",1000);\n\n    //pid1= nh.advertise<std_msgs::Float64>(\"rrbot/joint28_position_controller/pid/parameter_updates\",1000);\n    double p_hip ,i_hip ,d_hip;\n    double p_knee ,i_knee, d_knee;\n    double p_ankle ,i_ankle ,d_ankle;\n\n\n\n    ros::Rate loop_rate(100);\n    std_msgs::Int32MultiArray msg;\n    std_msgs::MultiArrayDimension msg_dim;\n\n    msg_dim.label = \"joint_position\";\n    msg_dim.size = 1;\n    msg.layout.dim.clear();\n    msg.layout.dim.push_back(msg_dim);\n    pitch_bias=0;\n\n    bool b;\n    int bias_count=0;\n    bool pitch_bias_ok;\n    while (ros::ok())\n    {\n        // qDebug()<<StartTime;\n\n\n\n\n        //start phase\n        if (startPhase==true && StartTime<=DurationOfStartPhase) {\n            MinimumJerkInterpolation Coef;\n            MatrixXd ZPosition(1,2);\n            ZPosition<<0.95100,0.9000;\n            MatrixXd ZVelocity(1,2);\n            ZVelocity<<0.000,0.000;\n            MatrixXd ZAcceleration(1,2);\n            ZAcceleration<<0.000,0.000;\n\n\n            MatrixXd Time(1,2);\n            Time<<0,DurationOfStartPhase;\n            MatrixXd CoefZStart =Coef.Coefficient(Time,ZPosition,ZVelocity,ZAcceleration);\n\n            //R1=AnkleRollRight\n            //R2=AnklePitchRight\n            //R3=KneePitchRight\n            //R4=HipPitchRight\n            //R5=HipRollRight\n            //R6=HipYawRight\n\n            //L1=AnkleRollLeft\n            //L2=AnklePitchLeft\n            //L3=KneePitchLeft\n            //L4=HipPitchLeft\n            //L5=HipRollLeft\n            //L6=HipYawLeft\n\n            //R1=0*(1/2Pi)*(2304)*100  R2=1*-1*(1/2Pi)*(2304)*100   R3=2(1/2Pi)*(2304)*50   R4=3*-1(1/2Pi)*(2304)*80    L2=4*(1/2Pi)*(2304)*100    L1=5*(1/2Pi)*(2304)*100   L3=6*-1*(1/2Pi)*(2304)*50     L4=7*(1/2Pi)*(2304)*80   R6=8*-1*(1/2Pi)*(2304)*120   R5=9*(1/2Pi)*(2304)*120    L5=10*(1/2Pi)*(2304)*120    L6=11*-1*(1/2Pi)*(2304)*120\n\n\n            //qDebug()<<mm(0,0);\n            double zStart=0;\n            double yStart=0;\n            double xStart=0;\n            StartTime=StartTime+SURENAOffilneTaskSpace._timeStep;\n\n            MatrixXd outputZStart= SURENAOffilneTaskSpace.GetAccVelPos(CoefZStart,StartTime,0,5);\n            zStart=outputZStart(0,0);\n\n            PoseRoot<<xStart,yStart,zStart,0,0,0;\n\n            PoseRFoot<<0,\n                    -0.11500,\n                    0.112000,\n                    0,\n                    0,\n                    0;\n\n            PoseLFoot<<0,\n                    0.11500,\n                    0.11200,\n                    0,\n                    0,\n                    0;\n\n            SURENA.doIK(\"LLeg_AnkleR_J6\",PoseLFoot,\"Body\", PoseRoot);\n            SURENA.doIK(\"RLeg_AnkleR_J6\",PoseRFoot,\"Body\", PoseRoot);\n            links = SURENA.GetLinks();\n\n\n\n\n            cntrl[0]=0.0;\n            cntrl[1]=links[1].JointAngle;\n            cntrl[2]=links[2].JointAngle;\n            cntrl[3]=links[3].JointAngle;\n            cntrl[4]=links[4].JointAngle;\n            cntrl[5]=links[5].JointAngle;//+teta_motor_R;//pitch\n            cntrl[6]=links[6].JointAngle;//roll\n            cntrl[7]=links[7].JointAngle;\n            cntrl[8]=links[8].JointAngle;\n            cntrl[9]=links[9].JointAngle;\n            cntrl[10]=links[10].JointAngle;\n            cntrl[11]=links[11].JointAngle;\n            cntrl[12]=links[12].JointAngle;\n\n\n\n\n            b=true;\n            ROS_INFO(\"wait!\");\n            // ROS_INFO(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t\",cntrl[3],cntrl[4],cntrl[5],cntrl[9],cntrl[10],cntrl[11]);\n            //tested for orientation\n//            p_hip=.007;//.007;//.01;//.007;//.005;//.01;(jumping)//.02;(jumping)//008;\n//            d_hip=0;//.00000000001;//.02;//.006;//.002;//.001;//0;//0.00006;\n\n            //tested for angular velocity\n            p_hip=.02;\n            d_hip=0;\n            i_hip=.0;\n\n\n\n            push_recovery_hip.Init(.01,0.3,-.3,p_hip,d_hip,i_hip);\n\n\n//            p_knee=.007;//.007;//.007;//.01;//.007;//.005;//.01;(jumping)//.03;(jumping)//.016;\n//            d_knee=0;//.00000000001;//.04;//.02;//.01;//.002;//.001;//0;//0.00016;\n            p_knee=.04;//.02;\n            d_knee=0;\n            i_knee=.0;\n\n            push_recovery_knee.Init(.01,0.3,-.3,p_knee,d_knee,i_knee);\n\n\n            p_ankle=.001;//.005;//.01;(jumping)//.02;(jumping)//.004;\n            i_ankle=0.0;\n            d_ankle=0;//.002;//.001;//0;//0.00003;\n            push_recovery_ankle.Init(.01,0.3,-.3,p_ankle,d_ankle,i_ankle);\n\n\n\n        }\n        //bias phase\n        if( StartTime>DurationOfStartPhase && StartTime<=DurationOfStartPhase+DurationOfPitchBias){\n            StartTime=StartTime+SURENAOffilneTaskSpace._timeStep;\n            pitch_bias+=pitch;\n            bias_count++;\n            pitch_bias_ok=true;\n        }\n        //push phase\n        if( StartTime>DurationOfStartPhase+DurationOfPitchBias && StartTime<DurationOfStartPhase+DurationOfPitchBias+DurationOfPushPhase) {\n            StartTime=StartTime+SURENAOffilneTaskSpace._timeStep;\n            if(pitch_bias_ok){\n                pitch_bias/=double(bias_count);\n                pitch_bias_ok=false;\n            }\n            //ROS_INFO(\"push!\\tpitch_bias=%f\\tpitch=%f\\tpitch-pitch_bias=%f\",pitch_bias,pitch,pitch-pitch_bias);\n            ROS_INFO(\"push!\\twy=%f\",w_y);\n\n\n//            double p_r_ankle=push_recovery_ankle.Calculate(0,pitch-pitch_bias);\n//            double p_r_knee=push_recovery_knee.Calculate(0,pitch-pitch_bias);\n//            double p_r_hip=push_recovery_hip.Calculate(0,pitch-pitch_bias);\n            double p_r_ankle=push_recovery_ankle.Calculate(0,w_y_f);\n            double p_r_knee=push_recovery_knee.Calculate(0,w_y_f);\n            double p_r_hip=push_recovery_hip.Calculate(0,w_y_f);\n            cntrl[0]=0.0;\n            cntrl[1]=links[1].JointAngle;\n            cntrl[2]=links[2].JointAngle;\n            cntrl[3]=links[3].JointAngle+p_r_hip;//+k_hip*w_y_f;\n            cntrl[4]=links[4].JointAngle+p_r_knee;//;//-push_recovery_knee.Calculate(0,w_y_f);//k_knee*w_y_f;\n            cntrl[5]=links[5].JointAngle+p_r_ankle;//+k_ankle*w_y_f;\n            cntrl[6]=links[6].JointAngle;\n            cntrl[7]=links[7].JointAngle;\n            cntrl[8]=links[8].JointAngle;\n            cntrl[9]=links[9].JointAngle+p_r_hip;//+k_hip*w_y_f;\n            cntrl[10]=links[10].JointAngle+p_r_knee;//-push_recovery_knee.Calculate(0,w_y_f);//k_knee*w_y_f;\n            cntrl[11]=links[11].JointAngle+p_r_ankle;//+k_ankle*w_y_f;\n            cntrl[12]=links[12].JointAngle;\n            //            ROS_INFO(\"pitch = %f\",pitch);\n            ROS_INFO(\"w_y=%f\\tw_y_filtered=%f\\t\",w_y,w_y_f);\n            ROS_INFO(\"hip=%f\\tkee=%f\\tankle=%f\\t\",p_r_hip,p_r_knee,p_r_ankle);\n\n            ROS_INFO(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t\",cntrl[3],cntrl[4],cntrl[5],cntrl[9],cntrl[10],cntrl[11]);\n        }\n        //back to knee phase\n        if (StartTime>=(DurationOfStartPhase+DurationOfPitchBias+DurationOfPushPhase) && StartTime<=DurationOfBacktoKnee+DurationOfStartPhase+DurationOfPushPhase+DurationOfPitchBias) {\n            StartTime=StartTime+SURENAOffilneTaskSpace._timeStep;\n            ROS_INFO(\"STOP pushing!\");\n            cntrl[0]=0.0;\n            cntrl[1]=links[1].JointAngle;\n            cntrl[2]=links[2].JointAngle;\n            cntrl[3]=links[3].JointAngle;\n            cntrl[4]=links[4].JointAngle;\n            cntrl[5]=links[5].JointAngle;\n            cntrl[6]=links[6].JointAngle;\n            cntrl[7]=links[7].JointAngle;\n            cntrl[8]=links[8].JointAngle;\n            cntrl[9]=links[9].JointAngle;\n            cntrl[10]=links[10].JointAngle;\n            cntrl[11]=links[11].JointAngle;\n            cntrl[12]=links[12].JointAngle;\n\n            ROS_INFO(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t\",cntrl[3],cntrl[4],cntrl[5],cntrl[9],cntrl[10],cntrl[11]);\n\n\n        }\n        //stand up phase\n        if (StartTime>=(DurationOfStartPhase+DurationOfPitchBias+DurationOfPushPhase+DurationOfBacktoKnee) && StartTime<=DurationOfBacktoKnee+DurationOfendPhase+DurationOfStartPhase+DurationOfPushPhase+DurationOfPitchBias) {\n            MinimumJerkInterpolation Coef;\n            MatrixXd ZPosition(1,2);\n            ZPosition<<0.90,0.95100;\n            MatrixXd ZVelocity(1,2);\n            ZVelocity<<0.000,0.000;\n            MatrixXd ZAcceleration(1,2);\n            ZAcceleration<<0.000,0.000;\n\n\n            MatrixXd Time(1,2);\n            Time<<DurationOfStartPhase+DurationOfPitchBias+DurationOfPushPhase+DurationOfBacktoKnee,DurationOfStartPhase+DurationOfPitchBias+DurationOfPushPhase+DurationOfBacktoKnee+DurationOfendPhase;\n            MatrixXd CoefZStart =Coef.Coefficient(Time,ZPosition,ZVelocity,ZAcceleration);\n\n            double zStart=0;\n            double yStart=0;\n            double xStart=0;\n            StartTime=StartTime+SURENAOffilneTaskSpace._timeStep;\n\n            MatrixXd outputZStart= SURENAOffilneTaskSpace.GetAccVelPos(CoefZStart,StartTime,DurationOfStartPhase+DurationOfPitchBias+DurationOfPushPhase+DurationOfBacktoKnee,5);\n            zStart=outputZStart(0,0);\n\n            PoseRoot<<xStart,yStart,zStart,0,0,0;\n\n            PoseRFoot<<0,\n                    -0.11500,\n                    0.112000,\n                    0,\n                    0,\n                    0;\n\n            PoseLFoot<<0,\n                    0.11500,\n                    0.11200,\n                    0,\n                    0,\n                    0;\n\n            SURENA.doIK(\"LLeg_AnkleR_J6\",PoseLFoot,\"Body\", PoseRoot);\n            SURENA.doIK(\"RLeg_AnkleR_J6\",PoseRFoot,\"Body\", PoseRoot);\n\n\n            links = SURENA.GetLinks();\n\n\n            cntrl[0]=0.0;\n            cntrl[1]=links[1].JointAngle;\n            cntrl[2]=links[2].JointAngle;\n            cntrl[3]=links[3].JointAngle;\n            cntrl[4]=links[4].JointAngle;\n            cntrl[5]=links[5].JointAngle;//+teta_motor_R;//pitch\n            cntrl[6]=links[6].JointAngle;//roll\n            cntrl[7]=links[7].JointAngle;\n            cntrl[8]=links[8].JointAngle;\n            cntrl[9]=links[9].JointAngle;\n            cntrl[10]=links[10].JointAngle;\n            cntrl[11]=links[11].JointAngle;\n            cntrl[12]=links[12].JointAngle;\n        }\n\n\n\n        vector<int> qref(12);\n        qref=QC.ctrldata2qc(cntrl);\n        msg.data.clear();\n\n        for(int  i = 0;i < 12;i++)\n        {\n            msg.data.push_back(qref[i]);\n        }\n        ROS_INFO(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t\",cntrl[3],cntrl[4],cntrl[5],cntrl[9],cntrl[10],cntrl[11]);\n\n\n\n        // std::string varAsString = std::to_string(qref[i-1]);\n        // msg.data =varAsString;\n        SendGazebo(cntrl);\n        // SendGazeboPID();\n        chatter_pub.publish(msg);\n        //  ROS_INFO(\"t={%d} c={%d}\",timer.elapsed(),count);\n\n        ros::spinOnce();\n        loop_rate.sleep();\n        ++count;\n\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "1b138fd1a6ccda540f06c03545f4696562f176e6", "size": 21052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "surena4/src/trajectory_generation/src/trajectory_generation_imu_pushrecovery.cpp", "max_stars_repo_name": "amin-amani/humanoid", "max_stars_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T08:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T08:51:26.000Z", "max_issues_repo_path": "surena4/src/trajectory_generation/src/trajectory_generation_imu_pushrecovery.cpp", "max_issues_repo_name": "amin-amani/humanoid", "max_issues_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-27T13:34:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-27T13:34:18.000Z", "max_forks_repo_path": "surena4/src/trajectory_generation/src/trajectory_generation_imu_pushrecovery.cpp", "max_forks_repo_name": "amin-amani/humanoid", "max_forks_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_forks_repo_licenses": ["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.3629160063, "max_line_length": 339, "alphanum_fraction": 0.6233612008, "num_tokens": 6175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.1936551320743027}}
{"text": "// Copyright (c) 2005 - 2015 Marc de Kamps\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//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//    * Redistributions in binary form must reproduce the above copyright notice, 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 copyright holder nor the names of its 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\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 POSSIBILITY OF SUCH DAMAGE.\n//\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <TwoDLib.hpp>\n#include <vector>\n#include <fstream>\n#include <iostream>\n\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace std;\nusing namespace TwoDLib;\n/*\nBOOST_AUTO_TEST_CASE(TransitionMatrixConstructionTest)\n{\n\tTransitionMatrix mat(\"condee2a5ff4-0087-4d69-bae3-c0a223d03693.mat\");\n}\n\nBOOST_AUTO_TEST_CASE(SimpleMeshTest){\n\ttry {\n\t\tMesh m(\"simple.mesh\");\n\t\tvector<Redistribution> vec_dummy;\n\t\tOde2DSystem sys(m,vec_dummy,vec_dummy);\n\n\t\tTransitionMatrix mat(\"simple.mat\");\n\t\tCSRMatrix csrmat(mat,sys);\n\n\t\tvector<double> out{ 0., 0., 0., 0., };\n\t\tvector<double> v{ 1.0, 0., 0., 0. };\n\n\t\tcsrmat.MV(out,v);\n\n\t\tBOOST_REQUIRE(out[0] == 0.5);\n\t\tBOOST_REQUIRE(out[1] == 0.0);\n\t\tBOOST_REQUIRE(out[2] == 0.5);\n\t\tBOOST_REQUIRE(out[3] == 0.0);\n\n\t}\n\tcatch(const TwoDLibException& excep){\n\t\tstd::cout << excep.what() << std::endl;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(TransitionMatrixUblasTest)\n{\n\tTransitionMatrix mat(\"condee2a5ff4-0087-4d69-bae3-c0a223d03693.mat\");\n\t// little odd, but TransitionMatrix does not record the size of the system it has to work on,\n\t// we get that from the mesh and add one for the stationary point\n\n\tMesh mesh(\"condee2a5ff4-0087-4d69-bae3-c0a223d03693.mesh\");\n    using namespace boost::numeric::ublas;\n\n    MPILib::Number n_cells = 1;\n    for (MPILib::Index i = 0; i < mesh.NrStrips(); i++)\n    \tfor(MPILib::Index j = 0; j < mesh.NrCellsInStrip(i); j++)\n    \t\t++n_cells;\n\n    compressed_matrix<double> m (n_cells, n_cells);\n    m(10,10) = 5.;\n\n    typedef compressed_matrix<double>::iterator1 i1_t;\n    typedef compressed_matrix<double>::iterator2 i2_t;\n\n#ifdef EXPERIMENT\n    for (i1_t i1 = m.begin1(); i1 != m.end1(); ++i1) {\n       for (i2_t i2 = i1.begin(); i2 != i1.end(); ++i2){\n          cout << \"(\" << i2.index1() << \",\" << i2.index2()\n               << \":\" << *i2 << \")  \";\n          cout << endl; }\n    }\n#endif\n}\n*/\n", "meta": {"hexsha": "4a8458d50c663dbf01f342319753fb039588c26c", "size": 3515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/UnitTwoDLib/TransitionMatrixTest.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/UnitTwoDLib/TransitionMatrixTest.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/UnitTwoDLib/TransitionMatrixTest.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": 38.6263736264, "max_line_length": 162, "alphanum_fraction": 0.7143669986, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.19358781864024524}}
{"text": "/*\nLightweight Automated Planning Toolkit\nCopyright (C) 2012\nMiquel Ramirez <miquel.ramirez@rmit.edu.au>\nNir Lipovetzky <nirlipo@gmail.com>\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 3 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#include <boost/program_options.hpp>\n#include <aptk/time.hxx>\n#include <strips_prob.hxx>\n#include <strips_state.hxx>\n#include <ff_to_aptk.hxx>\n#include <fwd_search_prob.hxx>\n#include <h_2.hxx>\n#include <conj_comp_prob.hxx>\n#include <h_C.hxx>\n#include <rp_heuristic.hxx>\n\n#include <iostream>\n#include <fstream>\n\nnamespace po = boost::program_options;\n\nusing   aptk::STRIPS_Problem;\nusing\taptk::agnostic::Fwd_Search_Problem;\nusing   aptk::agnostic::H2_Heuristic;\nusing\taptk::agnostic::CC_Problem;\nusing\taptk::agnostic::HC_Heuristic;\nusing\taptk::agnostic::Relaxed_Plan_Extractor;\n\nvoid process_command_line_options( int ac, char** av, po::variables_map& vars ) {\n\tpo::options_description desc( \"Options:\" );\n\t\n\tdesc.add_options()\n\t\t( \"help\", \"Show help message\" )\n\t\t( \"domain\", po::value<std::string>(), \"Input PDDL domain description\" )\n\t\t( \"problem\", po::value<std::string>(), \"Input PDDL problem description\" )\n\t;\n\t\n\ttry {\n\t\tpo::store( po::parse_command_line( ac, av, desc ), vars );\n\t\tpo::notify( vars );\n\t}\n\tcatch ( std::exception& e ) {\n\t\tstd::cerr << \"Error: \" << e.what() << std::endl;\n\t\tstd::exit(1);\n\t}\n\tcatch ( ... ) {\n\t\tstd::cerr << \"Exception of unknown type!\" << std::endl;\n\t\tstd::exit(1);\n\t}\n\n\tif ( vars.count(\"help\") ) {\n\t\tstd::cout << desc << std::endl;\n\t\tstd::exit(0);\n\t}\n\t\n}\n\nint main( int argc, char** argv ) {\n\n\tpo::variables_map vm;\n\n\tprocess_command_line_options( argc, argv, vm );\n\n\tif ( !vm.count( \"domain\" ) ) {\n\t\tstd::cerr << \"No PDDL domain was specified!\" << std::endl;\n\t\tstd::exit(1);\n\t}\n\n\tif ( !vm.count( \"problem\" ) ) {\n\t\tstd::cerr << \"No PDDL problem was specified!\" << std::endl;\n\t\tstd::exit(1);\n\t}\n\n\tSTRIPS_Problem\tprob;\n\n\taptk::FF_Parser::get_problem_description( vm[\"domain\"].as<std::string>(), vm[\"problem\"].as<std::string>(), prob );\n\n\tstd::cout << \"PDDL problem description loaded: \" << std::endl;\n\tstd::cout << \"\\tDomain: \" << prob.domain_name() << std::endl;\n\tstd::cout << \"\\tProblem: \" << prob.problem_name() << std::endl;\n\tstd::cout << \"\\t#Actions: \" << prob.num_actions() << std::endl;\n\tstd::cout << \"\\t#Fluents: \" << prob.num_fluents() << std::endl;\n\n\tFwd_Search_Problem\tsearch_prob( &prob );\n\taptk::State \t\ts0( prob );\n\ts0.set( prob.init() );\n\n\tfloat t0 = aptk::time_used();\n\tH2_Heuristic< Fwd_Search_Problem >  h2( search_prob );\n\tfloat tf = aptk::time_used();\n\tstd::cout << \"Time to initialize h^2: \" << tf - t0 << \" secs\" << std::endl;\n\t\n\tfloat h;\n\tt0 = aptk::time_used();\n\th2.eval( s0, h );\n\ttf = aptk::time_used();\n\tstd::cout << \"Time to evaluate h^2: \" << tf - t0 << \" secs\" << std::endl;\n\tstd::cout << \"h^2 value = \" << h << std::endl;\n\n\tstd::ofstream\th2_values(\"h2.values\");\n\th2.print_values( h2_values );\n\th2_values.close();\n\n\tt0 = aptk::time_used();\n\tCC_Problem\tpi_2_ce_task( prob, 2 );\n\tHC_Heuristic<>\th2_ce( pi_2_ce_task );\n\ttf = aptk::time_used();\n\tstd::cout << \"Time to initialize h^{2}_{ce}: \" << tf - t0 << \" secs\" << std::endl;\n\tstd::cout << \"# Fluents in \\\\Pi^{2}_{ce} task: \" << pi_2_ce_task.num_fluents() << std::endl;\n\t\n\tt0 = aptk::time_used();\n\th2_ce.eval( s0, h );\n\ttf = aptk::time_used();\n\tstd::cout << \"Time to evaluate h^{2}_{ce}: \" << tf - t0 << \" secs\" << std::endl;\n\tstd::cout << \"h^{2}_{ce} value = \" << h << std::endl;\n\t\n\tstd::ofstream\th2_ce_values(\"h2_ce.values\");\n\th2_ce.print_values( h2_ce_values );\n\th2_ce_values.close();\n\n\tt0 = aptk::time_used();\n\tCC_Problem\tpi_1_ce_task( prob, 1);\n\tHC_Heuristic<>\th1_ce( pi_1_ce_task );\n\ttf = aptk::time_used();\n\tstd::cout << \"Time to initialize h^{1}_{ce}: \" << tf - t0 << \" secs\" << std::endl;\n\tstd::cout << \"# Fluents in \\\\Pi^{1}_{ce} task: \" << pi_1_ce_task.num_fluents() << std::endl;\n\t\n\tt0 = aptk::time_used();\n\th1_ce.eval( s0, h );\n\ttf = aptk::time_used();\n\tstd::cout << \"Time to evaluate h^{1}_{ce}: \" << tf - t0 << \" secs\" << std::endl;\n\tstd::cout << \"h^{1}_{ce} value = \" << h << std::endl;\n\t\n\tstd::ofstream\th1_ce_values(\"h1_ce.values\");\n\th1_ce.print_values( h1_ce_values );\n\th1_ce_values.close();\n\n\tRelaxed_Plan_Extractor< HC_Heuristic<> >\trp_h2_ce( prob, h2_ce );\n\tstd::vector<aptk::Action_Idx> pref_ops;\n\trp_h2_ce.compute( s0, h, pref_ops );\n\n\tstd::cout << \"Relaxed plan h^2_ce heuristic = \" << h << std::endl;\n\tstd::cout << \"Preferred operators: \" << std::endl;\n\tfor ( auto it = pref_ops.begin(); it != pref_ops.end(); it++ )\n\t\tstd::cout << \"\\t\" << prob.actions()[*it]->signature() << std::endl;\t\n\n\tRelaxed_Plan_Extractor< HC_Heuristic<> >\trp_h1_ce( prob, h1_ce );\n\tpref_ops.clear();\n\trp_h1_ce.compute( s0, h, pref_ops );\n\n\tstd::cout << \"Relaxed plan h^1_ce heuristic = \" << h << std::endl;\n\tstd::cout << \"Preferred operators: \" << std::endl;\n\tfor ( auto it = pref_ops.begin(); it != pref_ops.end(); it++ )\n\t\tstd::cout << \"\\t\" << prob.actions()[*it]->signature() << std::endl;\t\n\n\treturn 0;\n}\n", "meta": {"hexsha": "270615bfc4634e8702f406427a85e686cfa06774", "size": 5477, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "planners/lapkt-public/examples/agnostic-examples/h_C_heuristics/main.cxx", "max_stars_repo_name": "miquelramirez/aamas18-planning-for-transparency", "max_stars_repo_head_hexsha": "dff3e635102bf351906807c5181113fbf4b67083", "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": "planners/lapkt-public/examples/agnostic-examples/h_C_heuristics/main.cxx", "max_issues_repo_name": "miquelramirez/aamas18-planning-for-transparency", "max_issues_repo_head_hexsha": "dff3e635102bf351906807c5181113fbf4b67083", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "planners/lapkt-public/examples/agnostic-examples/h_C_heuristics/main.cxx", "max_forks_repo_name": "miquelramirez/aamas18-planning-for-transparency", "max_forks_repo_head_hexsha": "dff3e635102bf351906807c5181113fbf4b67083", "max_forks_repo_licenses": ["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.8430232558, "max_line_length": 115, "alphanum_fraction": 0.648712799, "num_tokens": 1704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "/*\n\nCopyright (c) 2005-2017, 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 ABSTRACTODEBASEDCELLCYCLEMODEL_HPP_\n#define ABSTRACTODEBASEDCELLCYCLEMODEL_HPP_\n\n#include <vector>\n\n#include \"ChasteSerialization.hpp\"\n#include \"ClassIsAbstract.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractCellCycleModel.hpp\"\n#include \"CellCycleModelOdeHandler.hpp\"\n#include \"SimulationTime.hpp\"\n\n/**\n * This class contains all the functionality shared by 'ODE-based' cell-cycle models,\n * where the duration of the cell cycle is evaluated 'on the fly'\n * as the cell ages, according to a system of ordinary differential equations (ODEs)\n * governing (for example) the concentrations of key intracellular proteins. To\n * determine when cell division should occur, one or more stopping conditions for\n * this ODE system may be specified.\n *\n * This class of cell-cycle models is distinct from 'simple' cell-cycle models, where\n * the duration of the cell cycle is determined when the cell-cycle model is\n * created.\n */\nclass AbstractOdeBasedCellCycleModel : public AbstractCellCycleModel, public CellCycleModelOdeHandler\n{\nprivate:\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the cell-cycle model and 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<AbstractCellCycleModel>(*this);\n        archive & boost::serialization::base_object<CellCycleModelOdeHandler>(*this);\n        archive & mDivideTime;\n    }\n\nprotected:\n\n    /** The time at which the cell should divide - Set this to DBL_MAX in constructor. */\n    double mDivideTime;\n\n    /**\n     * Protected copy-constructor for use by CreateCellCycleModel.\n     * The only way for external code to create a copy of a cell cycle model\n     * is by calling that method, to ensure that a model of the correct subclass is created.\n     * This copy-constructor helps subclasses to ensure that all member variables are correctly copied when this happens.\n     *\n     * This method is called by child classes to set member variables for a daughter cell upon cell division.\n     * Note that the parent cell cycle model will have had ResetForDivision() called just before CreateCellCycleModel() is called,\n     * so performing an exact copy of the parent is suitable behaviour. Any daughter-cell-specific initialisation\n     * can be done in InitialiseDaughterCell().\n     *\n     * @param rModel the cell cycle model to copy.\n     */\n    AbstractOdeBasedCellCycleModel(const AbstractOdeBasedCellCycleModel& rModel);\n\npublic:\n\n    /**\n     * Creates an AbstractOdeBasedCellCycleModel, calls SetBirthTime on the\n     * AbstractPhaseBasedCellCycleModel to make sure that can be set 'back in time' for\n     * cells which did not divide at the current time.\n     *\n     * @param lastTime  The birth time of the cell / last time model was evaluated (defaults to the current SimulationTime)\n     * @param pOdeSolver An optional pointer to a cell-cycle model ODE solver object (allows the use of different ODE solvers)\n     */\n    AbstractOdeBasedCellCycleModel(double lastTime = SimulationTime::Instance()->GetTime(),\n                                   boost::shared_ptr<AbstractCellCycleModelOdeSolver> pOdeSolver = boost::shared_ptr<AbstractCellCycleModelOdeSolver>());\n\n    /**\n     * Destructor.\n     */\n    virtual ~AbstractOdeBasedCellCycleModel();\n\n    /**\n     * Get the time at which the ODE stopping event occurred.\n     * Only called in those subclasses for which stopping events\n     * are defined.\n     *\n     * @return the time at which the ODE system reached its stopping event\n     */\n    double GetOdeStopTime();\n\n    /**\n     * This overrides the AbstractCellCycleModel::SetBirthTime(double birthTime)\n     * because an ODE based cell-cycle model has more to reset...\n     *\n     * @param birthTime the simulation time when the cell was born\n     */\n    void SetBirthTime(double birthTime);\n\n    /**\n     * See AbstractCellCycleModel::ResetForDivision()\n     *\n     * @return whether the cell is ready to divide (enter M phase).\n     */\n    virtual bool ReadyToDivide();\n\n    /**\n     * For a naturally cycling model this does not need to be overridden in the\n     * subclasses. But most models should override this function and then\n     * call AbstractOdeBasedCellCycleModel::ResetForDivision() from inside their version.\n     */\n    virtual void ResetForDivision();\n\n    /**\n     * Outputs cell cycle model parameters to file.\n     *\n     * @param rParamsFile the file stream to which the parameters are output\n     */\n    virtual void OutputCellCycleModelParameters(out_stream& rParamsFile);\n};\n\nCLASS_IS_ABSTRACT(AbstractOdeBasedCellCycleModel)\n\n#endif /*ABSTRACTODEBASDCELLCYCLEMODEL_HPP_*/\n", "meta": {"hexsha": "edd8884aa79e72571cdbda4a6d3ec56a273018eb", "size": 6594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/cell/cycle/AbstractOdeBasedCellCycleModel.hpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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/cycle/AbstractOdeBasedCellCycleModel.hpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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/cycle/AbstractOdeBasedCellCycleModel.hpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": 40.9565217391, "max_line_length": 153, "alphanum_fraction": 0.7432514407, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"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 \"exact_synthesis.hpp\"\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <tuple>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/assign/std/set.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/range/iterator_range.hpp>\n\n#include <core/utils/timer.hpp>\n#include <formal/utils/z3_utils.hpp>\n\n#include <reversible/functions/fully_specified.hpp>\n#include <reversible/functions/add_gates.hpp>\n#include <reversible/functions/copy_metadata.hpp>\n\n#include <c++/z3++.h>\n\nnamespace cirkit\n{\nusing namespace boost::assign;\n\nusing gate_constraint_fun = std::function<void( z3::context& ctx, z3::solver& solver,\n                                                circuit&, std::vector<std::vector<z3::expr>>& network,\n                                                std::vector<std::vector<z3::expr> >& gate_values, const binary_truth_table&,\n                                                unsigned k, unsigned n )>;\n\nusing evaluation_fun = std::function<bool( z3::solver& solver, circuit& circ,\n                                           std::vector<std::vector<z3::expr>>& network, unsigned k, unsigned n )>;\n\nusing symmetry_fun = std::function<void( z3::context&, z3::solver&, std::vector<std::vector<z3::expr>>&, unsigned)>;\n\nvoid gate_constraints_original( z3::context& ctx, z3::solver& solver, circuit&,\n                                std::vector<std::vector<z3::expr> >& network,\n                                std::vector<std::vector<z3::expr> >& gate_values,\n                                const binary_truth_table& spec, unsigned k, unsigned n )\n{\n  using boost::str;\n  using boost::format;\n\n  auto rows = boost::distance( spec );\n\n  auto zero = ctx.bv_val(0, n);\n  auto one = ctx.bv_val(1, n);\n\n  for ( auto i = 0u; i < k; ++i )\n  {\n    auto control = ctx.bv_const(str(format(\"control-%d\") % i).c_str(), n);\n    auto target = ctx.bv_const(str(format(\"target-%d\") % i).c_str(), n);\n\n    network += std::vector<z3::expr>{ control, target };\n\n    solver.add( (control | (one << target)) != control );\n    solver.add( z3::ule(target, ctx.bv_val(n, n)) );\n\n    for ( auto j = 0u; j < rows; ++j )\n    {\n      auto hit = ctx.bool_const(str(format(\"hit-%d-%d\") % i % j).c_str());\n      solver.add( hit == ((gate_values[i][j] & control) == control) );\n      solver.add(\n          gate_values[i + 1][j]\n          == (gate_values[i][j] ^ (ite(hit, one, zero) << target)));\n    }\n  }\n}\n\nvoid gate_constraints_negative_control( z3::context& ctx, z3::solver& solver,\n                                        circuit&, std::vector<std::vector<z3::expr> >& network,\n                                        std::vector<std::vector<z3::expr> >& gate_values,\n                                        const binary_truth_table& spec, unsigned k, unsigned n )\n{\n  using boost::str;\n  using boost::format;\n\n  auto rows = boost::distance( spec );\n\n  auto zero = ctx.bv_val(0, n);\n  auto one = ctx.bv_val(1, n);\n  for ( auto i = 0u; i < k; ++i )\n  {\n    auto control = ctx.bv_const(str(format(\"control-%d\") % i).c_str(), n);\n    auto target = ctx.bv_const(str(format(\"target-%d\") % i).c_str(), n);\n    auto polarity = ctx.bv_const(str(format(\"polarity-%d\") % i).c_str(), n);\n\n    network += std::vector<z3::expr>{ control, target, polarity };\n\n    solver.add( (control | (one << target)) != control );\n    solver.add( z3::ule(target, ctx.bv_val(n, n)) );\n\n    for ( auto j = 0u; j < rows; ++j )\n    {\n      auto hit = ctx.bool_const(str(format(\"hit-%d-%d\") % i % j).c_str());\n      solver.add(\n          hit == (((gate_values[i][j] ^ polarity) & control) == control));\n      solver.add(\n          gate_values[i + 1][j]\n          == (gate_values[i][j] ^ (ite(hit, one, zero) << target)));\n    }\n  }\n}\n\nvoid gate_constraints_negative_control_multiple_target( z3::context& ctx,\n                                                        z3::solver& solver, circuit&, std::vector<std::vector<z3::expr> >& gates,\n                                                        std::vector<std::vector<z3::expr> >& line_values,\n                                                        const binary_truth_table& spec, unsigned k, unsigned n )\n{\n\n  using boost::str;\n  using boost::format;\n\n  auto rows = boost::distance( spec );\n\n  auto zero = ctx.bv_val(0, n);\n  auto one = ctx.bv_val(1, n);\n  for ( auto i = 0u; i < k; ++i )\n  {\n    auto control = ctx.bv_const(str(format(\"control-%d\") % i).c_str(), n);\n    auto target = ctx.bv_const(str(format(\"target-%d\") % i).c_str(), n);\n    auto polarity = ctx.bv_const(str(format(\"polarity-%d\") % i).c_str(), n);\n\n    gates += std::vector<z3::expr>{ control, target, polarity };\n\n    solver.add((control & target) == zero);\n\n    for ( auto j = 0u; j < rows; ++j )\n    {\n      auto hit = ctx.bool_const(str(format(\"hit-%d-%d\") % i % j).c_str());\n      solver.add(\n          hit == (((line_values[i][j] ^ polarity) & control) == control));\n      solver.add(\n          line_values[i + 1][j]\n          == ite(hit, line_values[i][j] ^ target, line_values[i][j]));\n    }\n  }\n}\n\nvoid gate_constraints_multiple_target( z3::context& ctx, z3::solver& solver,\n                                       circuit&, std::vector<std::vector<z3::expr> >& network,\n                                       std::vector<std::vector<z3::expr> >& gate_values,\n                                       const binary_truth_table& spec, unsigned k, unsigned n )\n{\n  using boost::str;\n  using boost::format;\n\n  auto rows = boost::distance( spec );\n\n  auto zero = ctx.bv_val(0, n);\n  auto one = ctx.bv_val(1, n);\n\n  for ( auto i = 0u; i < k; ++i )\n  {\n    auto control = ctx.bv_const(str(format(\"control-%d\") % i).c_str(), n);\n    auto target = ctx.bv_const(str(format(\"target-%d\") % i).c_str(), n);\n\n    network += std::vector<z3::expr>{ control, target };\n\n    solver.add((control & target) == zero);\n\n    for ( auto j = 0u; j < rows; ++j )\n    {\n      auto hit = ctx.bool_const(str(format(\"hit-%d-%d\") % i % j).c_str());\n      solver.add(hit == ((gate_values[i][j] & control) == control));\n      solver.add(\n          gate_values[i + 1][j]\n          == ite(hit, gate_values[i][j] ^ target, gate_values[i][j]));\n    }\n  }\n}\n\nbool eval_original(z3::solver& solver, circuit& circ,\n    std::vector<std::vector<z3::expr>>& network, unsigned k, unsigned n)\n{\n  if (solver.check() == z3::sat)\n  {\n    z3::model m = solver.get_model();\n    for (unsigned i : boost::irange(0u, k))\n    {\n      auto eval_control = to_bitset(m.eval(network[i][0]));\n      auto eval_target = to_bitset(m.eval(network[i][1])).to_ulong();\n\n      gate::control_container controls;\n      for (unsigned j : boost::irange(0u, n))\n      {\n        if (eval_control.test(j))\n        {\n          controls += make_var(j);\n        }\n      }\n\n      append_toffoli(circ, controls, eval_target);\n    }\n    return true;\n  } else\n  {\n    return false;\n  }\n}\n\nbool eval_multiple_target(z3::solver& solver, circuit& circ,\n    std::vector<std::vector<z3::expr>>& gates, unsigned k, unsigned n)\n{\n  if (solver.check() == z3::sat)\n  {\n    z3::model m = solver.get_model();\n\n    for (unsigned i : boost::irange(0u, k))\n    {\n      auto eval_control = to_bitset(m.eval(gates[i][0]));\n      auto eval_target = to_bitset(m.eval(gates[i][1]));\n\n      gate::control_container controls;\n      for (unsigned j : boost::irange(0u, n))\n      {\n        if (eval_control.test(j))\n        {\n          controls += make_var(j);\n        }\n      }\n\n      gate::target_container targets;\n      for (unsigned j : boost::irange(0u, n))\n      {\n        if (eval_target.test(j))\n        {\n          targets += j;\n        }\n      }\n\n      for ( const auto& target : targets )\n      {\n        append_toffoli(circ, controls, target);\n      }\n    }\n\n    return true;\n  } else\n  {\n    return false;\n  }\n}\n\nbool eval_negative_control(z3::solver& solver, circuit& circ,\n    std::vector<std::vector<z3::expr>>& gates, unsigned k, unsigned n)\n{\n  if (solver.check() == z3::sat)\n  {\n    z3::model m = solver.get_model();\n\n    for (unsigned i : boost::irange(0u, k))\n    {\n      auto eval_control = to_bitset(m.eval(gates[i][0]));\n      auto eval_target = to_bitset(m.eval(gates[i][1])).to_ulong();\n      auto eval_polarity = to_bitset(m.eval(gates[i][2]));\n\n      gate::control_container controls;\n      for (unsigned j : boost::irange(0u, n))\n      {\n        if (eval_control.test(j))\n        {\n          controls += make_var(j, !eval_polarity.test(j));\n        }\n      }\n\n      append_toffoli(circ, controls, eval_target);\n    }\n\n    return true;\n  } else\n  {\n    return false;\n  }\n\n}\n\nbool eval_negative_control_multiple_target(z3::solver& solver, circuit& circ,\n    std::vector<std::vector<z3::expr>>& gates, unsigned k, unsigned n)\n{\n  if (solver.check() == z3::sat)\n  {\n    z3::model m = solver.get_model();\n\n    for (unsigned i : boost::irange(0u, k))\n    {\n      auto eval_control = to_bitset(m.eval(gates[i][0]));\n      auto eval_polarity = to_bitset(m.eval(gates[i][2]));\n      auto eval_target = to_bitset(m.eval(gates[i][1]));\n\n//      std::cout << \"control: \" << eval_control << \"\\n\";\n//      std::cout << \"polarity: \" << eval_polarity << \"\\n\";\n//      std::cout << \"target: \" << eval_target << \"\\n\";\n\n\n      gate::control_container controls;\n      for (unsigned j : boost::irange(0u, n))\n      {\n        if (eval_control.test(j))\n        {\n          controls += make_var(j, !eval_polarity.test(j));\n        }\n      }\n\n      gate::target_container targets;\n      for (unsigned j : boost::irange(0u, n))\n      {\n        if (eval_target.test(j))\n        {\n//          std::cout <<\"j: \" <<  j << \"\\n\";\n          targets += j;\n        }\n      }\n\n      for ( const auto& target : targets )\n      {\n        append_toffoli(circ, controls, target);\n      }\n    }\n\n    return true;\n  } else\n  {\n    return false;\n  }\n}\n\nvoid input_output_constraints(z3::context& ctx, z3::solver solver,\n    const binary_truth_table& spec,\n    std::vector<std::vector<z3::expr> >& gate_values, unsigned k, unsigned n)\n{\n// Constraints for inputs and outputs. This is\n  for (binary_truth_table::const_iterator iter = spec.begin();\n      iter != spec.end(); ++iter)\n  {\n    boost::dynamic_bitset<> in(n);\n    boost::dynamic_bitset<> mask(n);\n    boost::dynamic_bitset<> out(n);\n\n    unsigned bitpos = 0;\n    for (const auto& bit : boost::make_iterator_range(iter->first))\n    {\n      in.set(bitpos++, *bit);\n    }\n\n    bitpos = 0;\n    for (const auto& bit : boost::make_iterator_range(iter->second))\n    {\n      mask.set(bitpos, (bool)bit);\n      out.set(bitpos++, (bool)bit && *bit);\n    }\n    unsigned pos = std::distance<binary_truth_table::const_iterator>(\n        spec.begin(), iter);\n    solver.add(gate_values[0][pos] == ctx.bv_val((__uint64) in.to_ulong(), n));\n    solver.add(\n        (gate_values[k][pos] & ctx.bv_val((__uint64) mask.to_ulong(), n))\n            == ctx.bv_val((__uint64) out.to_ulong(), n));\n  }\n}\n\n/******************************************************************************\n * symmetry breaking                                                          *\n ******************************************************************************/\n\nvoid symmetry_breaking_no_double_gate( z3::context& ctx, z3::solver& solver, const std::vector<std::vector<z3::expr>>& network, unsigned n )\n{\n  if ( network.size() >= 2 )\n  {\n    for ( auto i = 0u; i < network.size() - 1; ++i )\n    {\n      solver.add( !( ( network[i][0] == network[i + 1][0] ) && ( network[i][1] == network[i + 1][1] ) ) );\n    }\n  }\n}\n\nvoid symmetry_breaking_colexicographic( z3::context& ctx, z3::solver& solver, const std::vector<std::vector<z3::expr>>& network, unsigned n )\n{\n  const auto one = ctx.bv_val( 1u, n );\n  const auto zero = ctx.bv_val( 0u, n );\n\n  if ( network.size() >= 2 )\n  {\n    for ( auto i = 0u; i < network.size() - 1; ++i )\n    {\n      const z3::expr move1 = ( ( one << network[i][0] ) & network[i + 1][1] ) == zero;\n      const z3::expr move2 = ( network[i][1] & ( one << network[i + 1][0] ) ) == zero;\n\n      const z3::expr cless = z3::ule( network[i][0], network[i + 1][0] );\n      const z3::expr ceq   = ( network[i][0] == network[i + 1][0] ) && ( z3::ule( network[i][1], network[i + 1][1] ) );\n\n      solver.add( implies( move1 && move2, cless || ceq ) );\n    }\n  }\n}\n\nvoid symmetry_breaking_one_not_per_line( z3::context& ctx, z3::solver& solver, const std::vector<std::vector<z3::expr>>& network, unsigned n )\n{\n  const auto zero = ctx.bv_val( 0u, n );\n\n  for ( auto i = 0u; i < network.size(); ++i )\n  {\n    for ( auto j = i + 1; j < network.size(); ++j )\n    {\n      /* if some gate i has no controls (i.e., NOT), then there can't be another on that line */\n      solver.add( implies( network[i][0] == zero && network[i][1] == network[j][1], network[j][0] != zero ) );\n    }\n  }\n}\n\nbool synth_len(circuit& circ, const binary_truth_table& spec,\n               gate_constraint_fun gate_constraints,\n               evaluation_fun eval, const std::vector<symmetry_fun>& symmetry_breaking, bool only_toffoli, unsigned gate_count)\n{\n  using boost::str;\n  using boost::format;\n\n  unsigned n = spec.num_inputs();\n  unsigned rows = std::distance(spec.begin(), spec.end());\n\n  z3::context ctx;\n  z3::solver solver(ctx);\n\n  // Instead of having vector<pair<exp,exp>> we use vector<vector<exp>>. This\n  // allows for more flexibility. The inner vector should have a length of\n  // 2 or 3.\n  // In case of len 2, the first entry contains the controls, the second the targets\n  // In case of len 3, the last entry contains the polarity of the controls\n  std::vector<std::vector<z3::expr> > network;\n\n  // this vector of vectores stores, for every input pattern (outer vector index), the\n  // line values after the k'th gate (inner vector index)\n  std::vector<std::vector<z3::expr> > gate_values;\n\n  // initialize the gate values\n  for (int i : boost::irange(0u, gate_count + 1u))\n  {\n    gate_values += std::vector<z3::expr>();\n    for (int j : boost::irange(0u, rows))\n    {\n      gate_values[i] += ctx.bv_const(\n          str(format(\"gate-value-%d-%d\") % i % j).c_str(), n);\n    }\n  }\n\n  input_output_constraints(ctx, solver, spec, gate_values, gate_count, n);\n\n  gate_constraints(ctx, solver, circ, network, gate_values, spec, gate_count,\n      n);\n\n  for ( const auto& f : symmetry_breaking )\n  {\n    f( ctx, solver, network, n );\n  }\n\n  if ( only_toffoli )\n  {\n    for ( auto i = 0u; i < gate_count; ++i )\n    {\n      auto constr = ( network[i][0] == ctx.bv_val( 0u, n ) );\n      for ( auto j = 0u; j < n; ++j )\n      {\n        auto mask = 1 << j;\n        constr = constr || ( network[i][0] == ctx.bv_val( mask, n ) );\n\n        for ( auto k = j + 1; k < n; ++k )\n        {\n          constr = constr || ( network[i][0] == ctx.bv_val( mask | ( 1 << k ), n ) );\n        }\n      }\n      solver.add( constr );\n    }\n  }\n\n  return eval(solver, circ, network, gate_count, n);\n}\n\n/******************************************************************************\n * public functions                                                           *\n ******************************************************************************/\n\n\nbool exact_synthesis(circuit& circ, const binary_truth_table& spec,\n    properties::ptr settings, properties::ptr statistics)\n{\n  const auto start_depth  = get( settings, \"start_depth\",  0u );\n  const auto max_depth    = get( settings, \"max_depth\",    20u );\n  const auto negative     = get( settings, \"negative\",     false );\n  const auto multiple     = get( settings, \"multiple\",     false );\n  const auto only_toffoli = get( settings, \"only_toffoli\", false );\n  const auto verbose      = get( settings, \"verbose\",      false );\n\n  properties_timer t( statistics );\n\n  circ.set_lines(spec.num_inputs());\n\n  unsigned gate_count = start_depth;\n  bool result = false;\n\n  gate_constraint_fun gate_constraints = &gate_constraints_original;\n  evaluation_fun eval = &eval_original;\n  std::vector<symmetry_fun> symmetry_breaking;\n\n  symmetry_breaking.push_back( symmetry_breaking_no_double_gate );\n  if (negative && multiple)\n  {\n    gate_constraints = &gate_constraints_negative_control_multiple_target;\n    eval = &eval_negative_control_multiple_target;\n    symmetry_breaking.push_back( symmetry_breaking_one_not_per_line );\n  }\n  else\n  {\n    //symmetry_breaking.push_back( symmetry_breaking_colexicographic );\n    if (negative)\n    {\n      gate_constraints = &gate_constraints_negative_control;\n      eval = &eval_negative_control;\n      symmetry_breaking.push_back( symmetry_breaking_one_not_per_line );\n    }\n    if (multiple)\n    {\n      gate_constraints = &gate_constraints_multiple_target;\n      eval = &eval_multiple_target;\n    }\n  }\n\n  do\n  {\n    if ( verbose )\n    {\n      std::cout << \"[i] check for depth \" << gate_count << std::endl;\n    }\n    result = synth_len( circ, spec, gate_constraints, eval, symmetry_breaking, only_toffoli, gate_count );\n  } while (!result && gate_count++ < max_depth);\n\n  if (result)\n  {\n    copy_metadata(spec, circ);\n  } else\n  {\n    set_error_message(statistics,\n        \"Could not find a circuit within the predefined depth.\");\n  }\n\n  return result;\n}\n\ntruth_table_synthesis_func exact_synthesis_func(properties::ptr settings,\n    properties::ptr statistics)\n{\n  truth_table_synthesis_func f =\n      [&settings, &statistics]( circuit& circ, const binary_truth_table& spec )\n      {\n        return exact_synthesis( circ, spec, settings, statistics );\n      };\n  f.init(settings, statistics);\n  return f;\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": "895f25ddf803f07012b79321ff5d6bec058b003c", "size": 18847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/exact_synthesis.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": "addons/cirkit-addon-reversible/src/reversible/synthesis/exact_synthesis.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": "addons/cirkit-addon-reversible/src/reversible/synthesis/exact_synthesis.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": 31.6224832215, "max_line_length": 142, "alphanum_fraction": 0.5814718523, "num_tokens": 4995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <string>\n#include <boost/program_options.hpp>\n\n#include \"msa.hpp\"\n#include \"model.hpp\"\n#include \"OptParam.hpp\"\n#include \"PartFunc.hpp\"\nusing namespace std;\n\nnamespace po = boost::program_options;\n\nint main(int argc, char *argv[])\n{\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\",\"produce help message\")\n    (\"in,i\", po::value<string>(), \"set input file (multiple FASTA)\")\n    (\"default,d\", po::value<bool>(), \"Set default (NULL) sequence for training\")\n    (\"ipair\", po::value<string>(), \"interacting pairs of reference sequence\")\n    (\"rmap\", po::value<string>(), \"HMMer3 alignment of reference sequence\")\n    (\"param,p\", po::value<string>(), \"input LGM parameter file\")\n    (\"alpha\", po::value<double>(), \"alpha (for update)\")\n    (\"niter,n\", po::value<int>(), \"number of iterations\")\n    (\"logbase,l\", po::value<string>(), \"basename for log files\")\n    ;\n\n  po::positional_options_description p;\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc,argv).\n\t    options(desc).positional(p).run(), vm);\n  po::notify(vm);\n\n  if(vm.count(\"help\")) {\n    cerr << desc << endl;\n    return 1;\n  }\n  string logbase = \"exJ\";\n  if(vm.count(\"logbase\")) {\n    logbase = vm[\"logbase\"].as<string>();\n  }\n  cerr << \"# LOGBASE= \" << logbase << endl;\n  if(!vm.count(\"in\")) {\n    cerr << \"Specify the input MSA!\" << endl;\n    exit(1);\n  }\n  \n  cerr << \"Input file was set to \" << vm[\"in\"].as<string>() << endl;\n  string infile = vm[\"in\"].as<string>();\n  Msa msa(infile);\n  Model model(msa);\n  if(vm.count(\"param\")) {\n    model.read_parameters(vm[\"param\"].as<string>());\n    cerr << \"Setting parameters from \" << vm[\"param\"].as<string>() << endl;\n  }\n  \n  if(vm.count(\"default\")) {\n    if(vm[\"default\"].as<bool>()) {\n      //      model.set_null_sequence();\n      model.set_uniform_sequence();\n      cerr << \"Setting default NULL sequence for training\" << endl;\n    }\n  }\n\n  if(vm.count(\"ipair\")) {\n    cerr << \"#reading ipair \" << (vm[\"ipair\"].as<string>()) << endl;\n    model.read_ipairs(vm[\"ipair\"].as<string>());\n    if(vm.count(\"rmap\")) {\n      cerr << \"#reading rmap \" << (vm[\"rmap\"].as<string>()) << endl;\n      model.read_reference_3Dalignment(vm[\"rmap\"].as<string>());\n    } else {\n      cerr << \"Give --rmap for 3D contact mapping!\" << endl;\n      exit(2);\n    }\n    model.init_KOO_corr();\n  } else {\n    cerr << \"Setting NO ipairs.\" << endl;\n  }\n\n  PartFunc pfunc(model);\n  double alpha = 0.1;\n  if(vm.count(\"alpha\")) {\n    alpha = vm[\"alpha\"].as<double>();\n  }\n  cerr << \"alpha= \" << alpha << endl;\n  int niter = 300;\n  if(vm.count(\"niter\")) {\n    niter = vm[\"niter\"].as<int>();\n  }\n  cerr << \"Optimizing for \" << niter << \" iterations.\" << endl;\n  pfunc.learn_J(model, niter, alpha);\n  model.write_parameters(logbase + \".param\");\n\n  cerr << \"energy(obs)= \" << model.get_energy() << endl;\n  cerr << \"energy(exp)= \" << model.get_energy_exp() << endl;\n\n  cerr << \"max adel (site) \" << model.check_site(false) << endl;\n  cerr << \"max adel (bonded) \" << model.check_bonded(false) << endl;\n  cerr << \"max adel (nonbonded) \" << model.check_nonbonded(false) << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "7da143fdbb724c2a6c0bd15cb17fab122169e29c", "size": 3188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lgm_trainJ.cpp", "max_stars_repo_name": "arkinjo/lgm_mc", "max_stars_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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": "src/lgm_trainJ.cpp", "max_issues_repo_name": "arkinjo/lgm_mc", "max_issues_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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": "src/lgm_trainJ.cpp", "max_forks_repo_name": "arkinjo/lgm_mc", "max_forks_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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.3619047619, "max_line_length": 80, "alphanum_fraction": 0.5978670013, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "/*=============================================================================\n    Copyright (c) 2009 Christopher Schmidt\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#ifndef BOOST_FUSION_VIEW_REVERSE_VIEW_DETAIL_VALUE_AT_IMPL_HPP\n#define BOOST_FUSION_VIEW_REVERSE_VIEW_DETAIL_VALUE_AT_IMPL_HPP\n\n#include <boost/fusion/sequence/intrinsic/value_at.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/int.hpp>\n\nnamespace boost { namespace fusion { namespace extension\n{\n    template <typename>\n    struct value_at_impl;\n\n    template <>\n    struct value_at_impl<reverse_view_tag>\n    {\n        template <typename Seq, typename N>\n        struct apply\n          : result_of::value_at<\n                typename Seq::seq_type\n              , mpl::minus<typename Seq::size, mpl::int_<1>, N>\n            >\n        {};\n    };\n}}}\n\n#endif\n", "meta": {"hexsha": "90f5129bc91c335441765c8ab42627159fb100c9", "size": 1028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/fusion/view/reverse_view/detail/value_at_impl.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1930.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T14:05:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:07:17.000Z", "max_issues_repo_path": "boost/boost/fusion/view/reverse_view/detail/value_at_impl.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/fusion/view/reverse_view/detail/value_at_impl.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 297.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T17:50:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:11:26.000Z", "avg_line_length": 30.2352941176, "max_line_length": 80, "alphanum_fraction": 0.5826848249, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "/*\n * Copyright (c) 2019 Samsung Electronics Co., Ltd. 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 <algorithm>\n#include <atomic>\n#include <chrono>\n#include <forward_list>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <numeric>\n#include <stdexcept>\n#include <string>\n#include <thread>\n\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n#include <boost/program_options.hpp>\n\n#include <cmath>\n#include <cstdint>\n#include <signal.h>\n\n#include <tensorflow/lite/context.h>\n#include <tensorflow/lite/interpreter.h>\n#include <tensorflow/lite/model.h>\n\n#include \"labels.h\"\n#include \"tflite/ext/nnapi_delegate.h\"\n#include \"tflite/ext/kernels/register.h\"\n\nconst std::string kDefaultImagesDir = \"res/input/\";\nconst std::string kDefaultModelFile = \"res/model.tflite\";\n\ntemplate <typename... Args> void Print(const char *fmt, Args... args)\n{\n#if __cplusplus >= 201703L\n  std::cerr << boost::str(boost::format(fmt) % ... % std::forward<Args>(args)) << std::endl;\n#else\n  boost::format f(fmt);\n  using unroll = int[];\n  unroll{0, (f % std::forward<Args>(args), 0)...};\n  std::cerr << boost::str(f) << std::endl;\n#endif\n}\n\ntemplate <typename DataType> struct BaseLabelData\n{\n  explicit BaseLabelData(int label = -1, DataType confidence = 0)\n    : label(label), confidence(confidence)\n  {\n  }\n\n  static std::vector<BaseLabelData<DataType>> FindLabels(const DataType *output_tensor,\n                                                         unsigned int top_n = 5)\n  {\n    top_n = top_n > 1000 ? 1000 : top_n;\n    size_t n = 0;\n    std::vector<size_t> indices(1000);\n    std::generate(indices.begin(), indices.end(), [&n]() { return n++; });\n    std::sort(indices.begin(), indices.end(), [output_tensor](const size_t &i1, const size_t &i2) {\n      return output_tensor[i1] > output_tensor[i2];\n    });\n    std::vector<BaseLabelData<DataType>> results(top_n);\n    for (unsigned int i = 0; i < top_n; ++i)\n    {\n      results[i].label = indices[i];\n      results[i].confidence = output_tensor[indices[i]];\n    }\n    return results;\n  }\n\n  int label;\n  DataType confidence;\n};\n\nclass BaseRunner\n{\npublic:\n  virtual ~BaseRunner() = default;\n\n  /**\n   * @brief Run a model for each file in a directory, and collect and print\n   * statistics.\n   */\n  virtual void IterateInDirectory(const std::string &dir_path, const int labels_offset) = 0;\n\n  /**\n   * @brief Request that the iteration be stopped after the current file.\n   */\n  virtual void ScheduleInterruption() = 0;\n};\n\ntemplate <typename DataType_> class Runner : public BaseRunner\n{\npublic:\n  using DataType = DataType_;\n  using LabelData = BaseLabelData<DataType>;\n\n  const int kInputSize;\n  const int KOutputSize = 1001 * sizeof(DataType);\n\n  Runner(std::unique_ptr<tflite::Interpreter> interpreter,\n         std::unique_ptr<tflite::FlatBufferModel> model,\n         std::unique_ptr<::nnfw::tflite::NNAPIDelegate> delegate, unsigned img_size)\n    : interpreter(std::move(interpreter)), model(std::move(model)), delegate(std::move(delegate)),\n      interrupted(false), kInputSize(1 * img_size * img_size * 3 * sizeof(DataType))\n  {\n    inference_times.reserve(500);\n    top1.reserve(500);\n    top5.reserve(500);\n  }\n\n  virtual ~Runner() = default;\n\n  /**\n   * @brief Get the model's input tensor.\n   */\n  virtual DataType *GetInputTensor() = 0;\n\n  /**\n   * @brief Get the model's output tensor.\n   */\n  virtual DataType *GetOutputTensor() = 0;\n\n  /**\n   * @brief Load Image file into tensor.\n   * @return Class number if present in filename, -1 otherwise.\n   */\n  virtual int LoadFile(const boost::filesystem::path &input_file)\n  {\n    DataType *input_tensor = GetInputTensor();\n    if (input_file.extension() == \".bin\")\n    {\n      // Load data as raw tensor\n      std::ifstream input_stream(input_file.string(), std::ifstream::binary);\n      input_stream.read(reinterpret_cast<char *>(input_tensor), kInputSize);\n      input_stream.close();\n      int class_num = boost::lexical_cast<int>(input_file.filename().string().substr(0, 4));\n      return class_num;\n    }\n    else\n    {\n      // Load data as image file\n      throw std::runtime_error(\"Runner can only load *.bin files\");\n    }\n  }\n\n  void Invoke()\n  {\n    TfLiteStatus status;\n    if (delegate)\n    {\n      status = delegate->Invoke(interpreter.get());\n    }\n    else\n    {\n      status = interpreter->Invoke();\n    }\n    if (status != kTfLiteOk)\n    {\n      throw std::runtime_error(\"Failed to invoke interpreter.\");\n    }\n  }\n\n  int Process()\n  {\n    auto t0 = std::chrono::high_resolution_clock::now();\n    Invoke();\n    auto t1 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> fs = t1 - t0;\n    auto d = std::chrono::duration_cast<std::chrono::milliseconds>(fs);\n    inference_times.push_back(d.count());\n    if (d > std::chrono::milliseconds(10))\n    {\n      Print(\"  -- inference duration: %lld ms\", d.count());\n    }\n    else\n    {\n      auto du = std::chrono::duration_cast<std::chrono::microseconds>(fs);\n      Print(\"  -- inference duration: %lld us\", du.count());\n    }\n    return 0;\n  }\n\n  void DumpOutputTensor(const std::string &output_file)\n  {\n    DataType *output_tensor = GetOutputTensor();\n    std::ofstream output_stream(output_file, std::ofstream::binary);\n    output_stream.write(reinterpret_cast<char *>(output_tensor), KOutputSize);\n  }\n\n  void PrintExecutionSummary() const\n  {\n    Print(\"Execution summary:\");\n    Print(\"  -- # of processed images: %d\", num_images);\n    if (num_images == 0)\n    {\n      return;\n    }\n    // Inference time - mean\n    double mean = std::accumulate(inference_times.begin(), inference_times.end(), 0.0) / num_images;\n    Print(\"  -- mean inference time: %.1f ms\", mean);\n    // Inference time - std\n    std::vector<double> diff(num_images);\n    std::transform(inference_times.begin(), inference_times.end(), diff.begin(),\n                   [mean](size_t n) { return n - mean; });\n    double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);\n    double std_inference_time = std::sqrt(sq_sum / num_images);\n    Print(\"  -- std inference time: %.1f ms\", std_inference_time);\n    // Top-1 and Top-5 accuracies\n    float num_top1 = std::accumulate(top1.begin(), top1.end(), 0);\n    float num_top5 = std::accumulate(top5.begin(), top5.end(), 0);\n    Print(\"  -- top1: %.3f, top5: %.3f\", num_top1 / num_images, num_top5 / num_images);\n  }\n\n  virtual void ScheduleInterruption() override { interrupted = true; }\n\n  virtual void IterateInDirectory(const std::string &dir_path, const int labels_offset) override\n  {\n    interrupted = false;\n    namespace fs = boost::filesystem;\n    if (!fs::is_directory(dir_path))\n    {\n      throw std::runtime_error(\"Could not open input directory.\");\n    }\n\n    inference_times.clear();\n    top1.clear();\n    top5.clear();\n    int class_num;\n    num_images = 0;\n    std::vector<LabelData> lds;\n    fs::directory_iterator end;\n    for (auto it = fs::directory_iterator(dir_path); it != end; ++it)\n    {\n      if (interrupted)\n      {\n        break;\n      }\n      if (!fs::is_regular_file(*it))\n      {\n        continue;\n      }\n      Print(\"File : %s\", it->path().string());\n      try\n      {\n        class_num = LoadFile(*it) + labels_offset;\n        Print(\"Class: %d\", class_num);\n      }\n      catch (std::exception &e)\n      {\n        Print(\"%s\", e.what());\n        continue;\n      }\n      int status = Process();\n      if (status == 0)\n      {\n        DataType *output_tensor = GetOutputTensor();\n        lds = LabelData::FindLabels(output_tensor, 5);\n        bool is_top1 = lds[0].label == class_num;\n        bool is_top5 = false;\n        for (const auto &ld : lds)\n        {\n          is_top5 = is_top5 || (ld.label == class_num);\n          Print(\"  -- label: %s (%d), prob: %.3f\", ld.label >= 0 ? labels[ld.label] : \"\", ld.label,\n                static_cast<float>(ld.confidence));\n        }\n        Print(\"  -- top1: %d, top5: %d\", is_top1, is_top5);\n        top1.push_back(is_top1);\n        top5.push_back(is_top5);\n      }\n      ++num_images;\n    }\n    PrintExecutionSummary();\n  }\n\nprotected:\n  std::unique_ptr<tflite::Interpreter> interpreter;\n  std::unique_ptr<tflite::FlatBufferModel> model;\n  std::unique_ptr<::nnfw::tflite::NNAPIDelegate> delegate;\n\n  std::vector<size_t> inference_times;\n  std::vector<bool> top1;\n  std::vector<bool> top5;\n  uint num_images;\n  std::atomic_bool interrupted;\n};\n\nclass FloatRunner : public Runner<float>\n{\npublic:\n  using Runner<float>::DataType;\n\n  FloatRunner(std::unique_ptr<tflite::Interpreter> interpreter,\n              std::unique_ptr<tflite::FlatBufferModel> model,\n              std::unique_ptr<::nnfw::tflite::NNAPIDelegate> delegate, unsigned img_size)\n    : Runner<float>(std::move(interpreter), std::move(model), std::move(delegate), img_size)\n  {\n  }\n\n  virtual ~FloatRunner() = default;\n\n  virtual DataType *GetInputTensor() override\n  {\n    return interpreter->tensor(interpreter->inputs()[0])->data.f;\n  }\n\n  virtual DataType *GetOutputTensor() override\n  {\n    return interpreter->tensor(interpreter->outputs()[0])->data.f;\n  }\n};\n\nclass QuantizedRunner : public Runner<uint8_t>\n{\npublic:\n  using Runner<uint8_t>::DataType;\n\n  QuantizedRunner(std::unique_ptr<tflite::Interpreter> interpreter,\n                  std::unique_ptr<tflite::FlatBufferModel> model,\n                  std::unique_ptr<::nnfw::tflite::NNAPIDelegate> delegate, unsigned img_size)\n    : Runner<uint8_t>(std::move(interpreter), std::move(model), std::move(delegate), img_size)\n  {\n  }\n\n  virtual ~QuantizedRunner() = default;\n\n  virtual DataType *GetInputTensor() override\n  {\n    return interpreter->tensor(interpreter->inputs()[0])->data.uint8;\n  }\n\n  virtual DataType *GetOutputTensor() override\n  {\n    return interpreter->tensor(interpreter->outputs()[0])->data.uint8;\n  }\n};\n\nenum class Target\n{\n  TfLiteCpu,      /**< Use Tensorflow Lite's CPU kernels. */\n  TfLiteDelegate, /**< Use Tensorflow Lite's NN API delegate. */\n  NnfwDelegate    /**< Use NNFW's NN API delegate. */\n};\n\nstd::unique_ptr<BaseRunner> MakeRunner(const std::string &model_path, unsigned img_size,\n                                       Target target = Target::NnfwDelegate)\n{\n  auto model = tflite::FlatBufferModel::BuildFromFile(model_path.c_str());\n  if (not model)\n  {\n    throw std::runtime_error(model_path + \": file not found or corrupted.\");\n  }\n  Print(\"Model loaded.\");\n\n  std::unique_ptr<tflite::Interpreter> interpreter;\n  nnfw::tflite::BuiltinOpResolver resolver;\n  tflite::InterpreterBuilder(*model, resolver)(&interpreter);\n  if (not interpreter)\n  {\n    throw std::runtime_error(\"interpreter construction failed.\");\n  }\n  if (target == Target::TfLiteCpu)\n  {\n    interpreter->SetNumThreads(std::max(std::thread::hardware_concurrency(), 1U));\n  }\n  else\n  {\n    interpreter->SetNumThreads(1);\n  }\n  if (target == Target::TfLiteDelegate)\n  {\n    interpreter->UseNNAPI(true);\n  }\n\n  int input_index = interpreter->inputs()[0];\n  interpreter->ResizeInputTensor(input_index,\n                                 {1, static_cast<int>(img_size), static_cast<int>(img_size), 3});\n  if (interpreter->AllocateTensors() != kTfLiteOk)\n  {\n    throw std::runtime_error(\"tensor allocation failed.\");\n  }\n\n  if (target == Target::TfLiteDelegate)\n  {\n    // Do a fake run to load NN API functions.\n    interpreter->Invoke();\n  }\n\n  std::unique_ptr<::nnfw::tflite::NNAPIDelegate> delegate;\n  if (target == Target::NnfwDelegate)\n  {\n    delegate.reset(new ::nnfw::tflite::NNAPIDelegate);\n    delegate->BuildGraph(&(interpreter.get()->primary_subgraph()));\n  }\n\n  if (interpreter->tensor(input_index)->type == kTfLiteFloat32)\n  {\n    return std::unique_ptr<FloatRunner>(\n      new FloatRunner(std::move(interpreter), std::move(model), std::move(delegate), img_size));\n  }\n  else if (interpreter->tensor(input_index)->type == kTfLiteUInt8)\n  {\n    return std::unique_ptr<QuantizedRunner>(\n      new QuantizedRunner(std::move(interpreter), std::move(model), std::move(delegate), img_size));\n  }\n  throw std::invalid_argument(\"data type of model's input tensor is not supported.\");\n}\n\nTarget GetTarget(const std::string &str)\n{\n  static const std::map<std::string, Target> target_names{\n    {\"tflite-cpu\", Target::TfLiteCpu},\n    {\"tflite-delegate\", Target::TfLiteDelegate},\n    {\"nnfw-delegate\", Target::NnfwDelegate}};\n  if (target_names.find(str) == target_names.end())\n  {\n    throw std::invalid_argument(\n      str + \": invalid target. Run with --help for a list of available targets.\");\n  }\n  return target_names.at(str);\n}\n\n// We need a global pointer to the runner for the SIGINT handler\nBaseRunner *runner_ptr = nullptr;\nvoid HandleSigInt(int)\n{\n  if (runner_ptr != nullptr)\n  {\n    Print(\"Interrupted. Execution will stop after current image.\");\n    runner_ptr->ScheduleInterruption();\n    runner_ptr = nullptr;\n  }\n  else\n  {\n    exit(1);\n  }\n}\n\nint main(int argc, char *argv[])\ntry\n{\n  namespace po = boost::program_options;\n  po::options_description desc(\"Run a model on multiple binary images and print\"\n                               \" statistics\");\n  // clang-format off\n  desc.add_options()\n    (\"help\", \"print this message and quit\")\n    (\"model\", po::value<std::string>()->default_value(kDefaultModelFile), \"tflite file\")\n    (\"input\", po::value<std::string>()->default_value(kDefaultImagesDir), \"directory with input images\")\n    (\"offset\", po::value<int>()->default_value(1), \"labels offset\")\n    (\"target\", po::value<std::string>()->default_value(\"nnfw-delegate\"),\n      \"how the model will be run (available targets: tflite-cpu, tflite-delegate, nnfw-delegate)\")\n    (\"imgsize\", po::value<unsigned>()->default_value(224), \"the width and height of the image\");\n  // clang-fomrat on\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  if (vm.count(\"help\"))\n  {\n    std::cerr << desc << std::endl;\n    return 0;\n  }\n\n  auto runner = MakeRunner(vm[\"model\"].as<std::string>(), vm[\"imgsize\"].as<unsigned>(),\n                           GetTarget(vm[\"target\"].as<std::string>()));\n  runner_ptr = runner.get();\n\n  struct sigaction sigint_handler;\n  sigint_handler.sa_handler = HandleSigInt;\n  sigemptyset(&sigint_handler.sa_mask);\n  sigint_handler.sa_flags = 0;\n  sigaction(SIGINT, &sigint_handler, nullptr);\n\n  Print(\"Running TensorFlow Lite...\");\n  runner->IterateInDirectory(vm[\"input\"].as<std::string>(), vm[\"offset\"].as<int>());\n  Print(\"Done.\");\n  return 0;\n}\ncatch (std::exception &e)\n{\n  Print(\"%s: %s\", argv[0], e.what());\n  return 1;\n}\n", "meta": {"hexsha": "66c19a868d37027446af51c2c3825bb2e383a0a7", "size": 15008, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/tflite_accuracy/src/tflite_accuracy.cc", "max_stars_repo_name": "chogba6/ONE", "max_stars_repo_head_hexsha": "3d35259f89ee3109cfd35ab6f38c231904487f3b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 255.0, "max_stars_repo_stars_event_min_datetime": "2020-05-22T07:45:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T23:58:22.000Z", "max_issues_repo_path": "tools/tflite_accuracy/src/tflite_accuracy.cc", "max_issues_repo_name": "chogba6/ONE", "max_issues_repo_head_hexsha": "3d35259f89ee3109cfd35ab6f38c231904487f3b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5102.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:48:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:43:39.000Z", "max_forks_repo_path": "tools/tflite_accuracy/src/tflite_accuracy.cc", "max_forks_repo_name": "chogba6/ONE", "max_forks_repo_head_hexsha": "3d35259f89ee3109cfd35ab6f38c231904487f3b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 120.0, "max_forks_repo_forks_event_min_datetime": "2020-05-22T07:51:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T19:08:05.000Z", "avg_line_length": 30.1365461847, "max_line_length": 104, "alphanum_fraction": 0.6501865672, "num_tokens": 3853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "// Copyright 2016-2019 Doug Moen\n// Licensed under the Apache License, version 2.0\n// See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0\n\n#include <libcurv/builtin.h>\n\n#include <libcurv/analyser.h>\n#include <libcurv/array_op.h>\n#include <libcurv/die.h>\n#include <libcurv/dir_record.h>\n#include <libcurv/exception.h>\n#include <libcurv/function.h>\n#include <libcurv/sc_compiler.h>\n#include <libcurv/sc_context.h>\n#include <libcurv/import.h>\n#include <libcurv/math.h>\n#include <libcurv/pattern.h>\n#include <libcurv/picker.h>\n#include <libcurv/program.h>\n#include <libcurv/source.h>\n#include <libcurv/system.h>\n#include <libcurv/typeconv.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/filesystem.hpp>\n\n#include <cassert>\n#include <climits>\n#include <cmath>\n#include <cstdlib>\n#include <string>\n\nusing namespace std;\nusing namespace boost::math::double_constants;\n\nnamespace curv {\n\nShared<Meaning>\nBuiltin_Value::to_meaning(const Identifier& id) const\n{\n    return make<Constant>(share(id), value_);\n}\n\n//----------------------------------------------//\n// Templates for constructing builtin functions //\n//----------------------------------------------//\n\ntemplate <class Prim>\nstruct Unary_Array_Func : public Function\n{\n    static const char* name() { return Prim::name(); }\n    Unary_Array_Func() : Function(name()) {}\n    static Unary_Array_Op<Prim> array_op;\n    Value call(Value arg, Frame& f) override\n    {\n        return array_op.op(At_Arg(*this, f), arg);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase> ph, SC_Frame& f)\n    const override\n    {\n        return array_op.sc_op(At_SC_Arg_Expr(*this, ph, f), argx, f);\n    }\n};\n\ntemplate <class Prim>\nstruct Binary_Array_Func : public Legacy_Function\n{\n    static const char* name() { return Prim::name(); }\n    Binary_Array_Func() : Legacy_Function(2,name()) {}\n    static Binary_Array_Op<Prim> array_op;\n    Value call(Frame& args) override\n    {\n        return array_op.op(At_Arg(*this, args), args[0], args[1]);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase> ph, SC_Frame& f)\n    const override\n    {\n        return array_op.sc_op(At_SC_Arg_Expr(*this, ph, f), argx, f);\n    }\n};\n\ntemplate <class Prim>\nstruct Monoid_Func final : public Function\n{\n    static const char* name() { return Prim::name(); }\n    Monoid_Func() : Function(name()) {}\n    static Binary_Array_Op<Prim> array_op;\n    Value call(Value arg, Frame& f) override\n    {\n        return array_op.reduce(At_Arg(*this, f), Prim::zero(), arg);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase> ph, SC_Frame& f)\n    const override\n    {\n        return array_op.sc_reduce(At_SC_Arg_Expr(*this, ph, f),\n            Prim::zero(), argx, f);\n    }\n};\n\n//-------------------//\n// Builtin Functions //\n//-------------------//\n\nstruct Is_Bool_Function : public Function\n{\n    static const char* name() { return \"is_bool\"; }\n    Is_Bool_Function() : Function(name()) {}\n    Value call(Value arg, Frame&) override\n    {\n        return {isbool(arg)};\n    }\n};\nstruct Is_Symbol_Function : public Function\n{\n    static const char* name() { return \"is_symbol\"; }\n    Is_Symbol_Function() : Function(name()) {}\n    Value call(Value arg, Frame&) override\n    {\n        return {issymbol(arg)};\n    }\n};\nstruct Is_Num_Function : public Function\n{\n    static const char* name() { return \"is_num\"; }\n    Is_Num_Function() : Function(name()) {}\n    Value call(Value arg, Frame&) override\n    {\n        return {isnum(arg)};\n    }\n};\nstruct Is_String_Function : public Function\n{\n    static const char* name() { return \"is_string\"; }\n    Is_String_Function() : Function(name()) {}\n    Value call(Value arg, Frame&) override\n    {\n        return {arg.dycast<String>() != nullptr};\n    }\n};\nstruct Is_List_Function : public Function\n{\n    static const char* name() { return \"is_list\"; }\n    Is_List_Function() : Function(name()) {}\n    Value call(Value arg, Frame&) override\n    {\n        return {islist(arg)};\n    }\n};\nstruct Is_Record_Function : public Function\n{\n    static const char* name() { return \"is_record\"; }\n    Is_Record_Function() : Function(name()) {}\n    Value call(Value arg, Frame&) override\n    {\n        return {arg.dycast<Record>() != nullptr};\n    }\n};\nstruct Is_Fun_Function : public Function\n{\n    static const char* name() { return \"is_fun\"; }\n    Is_Fun_Function() : Function(name()) {}\n    Value call(Value arg, Frame&) override\n    {\n        return {arg.dycast<Function>() != nullptr};\n    }\n};\n\nstruct Bit_Prim : public Unary_Bool_Prim\n{\n    static const char* name() { return \"bit\"; }\n    static Value call(bool b, const Context&)\n    {\n        return {double(b)};\n    }\n    static SC_Value sc_call(SC_Frame& f, SC_Value arg)\n    {\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = float(\"<<arg<<\");\\n\";\n        return result;\n    }\n};\nusing Bit_Function = Unary_Array_Func<Bit_Prim>;\n\n#define UNARY_NUMERIC_FUNCTION(Class_Name,curv_name,c_name,glsl_name) \\\nstruct Class_Name : public Legacy_Function \\\n{ \\\n    static const char* name() { return #curv_name; } \\\n    Class_Name() : Legacy_Function(1,name()) {} \\\n    struct Prim { \\\n        static double call(double x) { return c_name(x); } \\\n        Shared<Operation> make_expr(Shared<Operation> x) const \\\n        { \\\n            return make<Call_Expr>( \\\n                cx.call_frame_.call_phrase_, \\\n                make<Constant>( \\\n                    func_part(cx.call_frame_.call_phrase_), \\\n                    Value{share(cx.func_)}), \\\n                x); \\\n        } \\\n        static Shared<const String> callstr(Value x) { \\\n            return stringify(x); \\\n        } \\\n        At_Arg cx; \\\n        Prim(Function& func, Frame& args) : cx(func,args) {} \\\n    }; \\\n    static Unary_Numeric_Array_Op<Prim> array_op; \\\n    Value call(Frame& args) override \\\n    { \\\n        return array_op.op(Prim(*this, args), args[0]); \\\n    } \\\n    SC_Value sc_call_legacy(SC_Frame& f) const override \\\n    { \\\n        return sc_call_unary_numeric(f, #glsl_name); \\\n    } \\\n}; \\\n\nUNARY_NUMERIC_FUNCTION(Sqrt_Function, sqrt, sqrt, sqrt)\nUNARY_NUMERIC_FUNCTION(Log_Function, log, log, log)\nUNARY_NUMERIC_FUNCTION(Abs_Function, abs, abs, abs)\nUNARY_NUMERIC_FUNCTION(Floor_Function, floor, floor, floor)\nUNARY_NUMERIC_FUNCTION(Ceil_Function, ceil, ceil, ceil)\nUNARY_NUMERIC_FUNCTION(Trunc_Function, trunc, trunc, trunc)\nUNARY_NUMERIC_FUNCTION(Round_Function, round, rint, roundEven)\n\ninline double frac(double n) { return n - floor(n); }\nUNARY_NUMERIC_FUNCTION(Frac_Function, frac, frac, fract)\n\nUNARY_NUMERIC_FUNCTION(Sin_Function, sin, sin, sin)\nUNARY_NUMERIC_FUNCTION(Cos_Function, cos, cos, cos)\nUNARY_NUMERIC_FUNCTION(Tan_Function, tan, tan, tan)\nUNARY_NUMERIC_FUNCTION(Acos_Function, acos, acos, acos)\nUNARY_NUMERIC_FUNCTION(Asin_Function, asin, asin, asin)\nUNARY_NUMERIC_FUNCTION(Atan_Function, atan, atan, atan)\n\nUNARY_NUMERIC_FUNCTION(Sinh_Function, sinh, sinh, sinh)\nUNARY_NUMERIC_FUNCTION(Cosh_Function, cosh, cosh, cosh)\nUNARY_NUMERIC_FUNCTION(Tanh_Function, tanh, tanh, tanh)\nUNARY_NUMERIC_FUNCTION(Acosh_Function, acosh, acosh, acosh)\nUNARY_NUMERIC_FUNCTION(Asinh_Function, asinh, asinh, asinh)\nUNARY_NUMERIC_FUNCTION(Atanh_Function, atanh, atanh, atanh)\n\nstruct Atan2_Function : public Legacy_Function\n{\n    static const char* name() { return \"atan2\"; }\n    Atan2_Function() : Legacy_Function(2,name()) {}\n\n    struct Prim {\n        static double call(double x, double y) { return atan2(x, y); }\n        Shared<Operation> make_expr(\n            Shared<Operation> x, Shared<Operation> y) const\n        {\n            throw Exception(cx,\n                \"Internal error: atan2 applied to a reactive value\");\n            //return make<Divide_Expr>(share(syntax), std::move(x), std::move(y));\n        }\n        static const char* name() { return \"atan2\"; }\n        static Shared<const String> callstr(Value x, Value y) {\n            return stringify(\"[\",x,\",\",y,\"]\");\n        }\n        At_Arg cx;\n        Prim(Function& func, Frame& args) : cx(func, args) {}\n    };\n    static Binary_Numeric_Array_Op<Prim> array_op;\n    Value call(Frame& args) override\n    {\n        return array_op.op(Prim(*this, args), args[0], args[1]);\n    }\n    SC_Value sc_call_legacy(SC_Frame& f) const override\n    {\n        auto x = f[0];\n        auto y = f[1];\n\n        SC_Type rtype = SC_Type::Bool();\n        if (x.type == y.type)\n            rtype = x.type;\n        else if (x.type == SC_Type::Num())\n            rtype = y.type;\n        else if (y.type == SC_Type::Num())\n            rtype = x.type;\n        if (rtype == SC_Type::Bool())\n            throw Exception(At_SC_Phrase(f.call_phrase_, f),\n                \"domain error\");\n\n        SC_Value result = f.sc_.newvalue(rtype);\n        f.sc_.out() <<\"  \"<<rtype<<\" \"<<result<<\" = atan(\";\n        sc_put_as(f, x, At_SC_Arg(0, f), rtype);\n        f.sc_.out() << \",\";\n        sc_put_as(f, y, At_SC_Arg(1, f), rtype);\n        f.sc_.out() << \");\\n\";\n        return result;\n    }\n};\n\nSC_Value sc_minmax(const char* name, Operation& argx, SC_Frame& f)\n{\n    auto list = dynamic_cast<List_Expr*>(&argx);\n    if (list) {\n        std::list<SC_Value> args;\n        SC_Type type = SC_Type::Num();\n        for (auto op : *list) {\n            auto val = sc_eval_op(f, *op);\n            args.push_back(val);\n            if (val.type == SC_Type::Num())\n                ;\n            else if (val.type.is_vec()) {\n                if (type == SC_Type::Num())\n                    type = val.type;\n                else if (type != val.type)\n                    throw Exception(At_SC_Phrase(op->syntax_, f), stringify(\n                        name, \": vector arguments of different lengths\"));\n            } else {\n                throw Exception(At_SC_Phrase(op->syntax_, f), stringify(\n                    name,\": argument has bad type\"));\n            }\n        }\n        auto result = f.sc_.newvalue(type);\n        if (args.size() == 0) {\n            // TODO: BUG: this only works for 'max'. min requires +inf.\n            f.sc_.out() << \"  \" << type << \" \" << result << \" = -0.0/0.0;\\n\";\n        }\n        else if (args.size() == 1)\n            return args.front();\n        else {\n            f.sc_.out() << \"  \" << type << \" \" << result << \" = \";\n            int rparens = 0;\n            while (args.size() > 2) {\n                f.sc_.out() << name << \"(\" << args.front() << \",\";\n                args.pop_front();\n                ++rparens;\n            }\n            f.sc_.out() << name << \"(\" << args.front() << \",\" << args.back() << \")\";\n            while (rparens > 0) {\n                f.sc_.out() << \")\";\n                --rparens;\n            }\n            f.sc_.out() << \";\\n\";\n        }\n        return result;\n    } else {\n        auto arg = sc_eval_op(f, argx);\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = \";\n        if (arg.type == SC_Type::Vec(2))\n            f.sc_.out() << name <<\"(\"<<arg<<\".x,\"<<arg<<\".y);\\n\";\n        else if (arg.type == SC_Type::Vec(3))\n            f.sc_.out() << name<<\"(\"<<name<<\"(\"<<arg<<\".x,\"<<arg<<\".y),\"\n                <<arg<<\".z);\\n\";\n        else if (arg.type == SC_Type::Vec(4))\n            f.sc_.out() << name<<\"(\"<<name<<\"(\"<<name<<\"(\"<<arg<<\".x,\"<<arg<<\".y),\"\n                <<arg<<\".z),\"<<arg<<\".w);\\n\";\n        else\n            throw Exception(At_SC_Phrase(argx.syntax_, f), stringify(\n                name,\": argument is not a vector\"));\n        return result;\n    }\n}\n\nstruct Max_Function : public Legacy_Function\n{\n    static const char* name() { return \"max\"; }\n    Max_Function() : Legacy_Function(1,name()) {}\n\n    struct Prim {\n        static double call(double x, double y) {\n            // return NaN if either argument is NaN.\n            if (x >= y) return x;\n            if (x < y) return y;\n            return 0.0/0.0;\n        }\n        Shared<Operation> make_expr(\n            Shared<Operation> x, Shared<Operation> y) const\n        {\n            Shared<List_Expr> args =\n                List_Expr::make({x, y}, arg_part(cx.call_frame_.call_phrase_));\n            args->init();\n            return make<Call_Expr>(\n                cx.call_frame_.call_phrase_,\n                make<Constant>(\n                    func_part(cx.call_frame_.call_phrase_),\n                    Value{share(cx.func_)}),\n                args);\n        }\n        static const char* name() { return \"max\"; }\n        static Shared<const String> callstr(Value x, Value y) {\n            return stringify(\"[\",x,\",\",y,\"]\");\n        }\n        At_Arg cx;\n        Prim(Function& func, Frame& args) : cx(func,args) {}\n    };\n    static Binary_Numeric_Array_Op<Prim> array_op;\n    Value call(Frame& args) override\n    {\n        return array_op.reduce(Prim(*this, args), -INFINITY, args[0]);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase>, SC_Frame& f)\n    const override\n    {\n        return sc_minmax(name(),argx,f);\n    }\n};\n\nstruct Min_Function : public Legacy_Function\n{\n    static const char* name() { return \"min\"; }\n    Min_Function() : Legacy_Function(1,name()) {}\n\n    struct Prim {\n        static double call(double x, double y) {\n            // return NaN if either argument is NaN\n            if (x <= y) return x;\n            if (x > y) return y;\n            return 0.0/0.0;\n        }\n        Shared<Operation> make_expr(\n            Shared<Operation> x, Shared<Operation> y) const\n        {\n            Shared<List_Expr> args =\n                List_Expr::make({x, y}, arg_part(cx.call_frame_.call_phrase_));\n            args->init();\n            return make<Call_Expr>(\n                cx.call_frame_.call_phrase_,\n                make<Constant>(\n                    func_part(cx.call_frame_.call_phrase_),\n                    Value{share(cx.func_)}),\n                args);\n        }\n        static const char* name() { return \"min\"; }\n        static Shared<const String> callstr(Value x, Value y) {\n            return stringify(\"[\",x,\",\",y,\"]\");\n        }\n        At_Arg cx;\n        Prim(Function& func, Frame& args) : cx(func, args) {}\n    };\n    static Binary_Numeric_Array_Op<Prim> array_op;\n    Value call(Frame& args) override\n    {\n        return array_op.reduce(Prim(*this, args), INFINITY, args[0]);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase>, SC_Frame& f)\n    const override\n    {\n        return sc_minmax(\"min\",argx,f);\n    }\n};\n\nstruct Sum_Prim : public Binary_Num_Prim\n{\n    static const char* name() { return \"sum\"; }\n    static Value zero() { return {0.0}; }\n    static Value call(double x, double y, const Context&) { return {x + y}; }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x, SC_Value y)\n    {\n        auto result = f.sc_.newvalue(x.type);\n        f.sc_.out() << \"  \" << result.type << \" \" << result << \" = \"\n            << x << \"+\" << y << \";\\n\";\n        return result;\n    }\n};\nusing Sum_Function = Monoid_Func<Sum_Prim>;\n\nstruct And_Prim : public Binary_Bool_Or_Bool32_Prim\n{\n    static const char* name() { return \"and\"; }\n    static Value zero() { return {true}; }\n    static Value call(bool x, bool y, const Context&) { return {x && y}; }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x, SC_Value y)\n    {\n        auto result = f.sc_.newvalue(x.type);\n        f.sc_.out() << \"  \" << x.type << \" \" << result << \" = \" << x\n            << (x.type.is_bool32() ? \"&\" : \"&&\")\n            << y << \";\\n\";\n        return result;\n    }\n};\nusing And_Function = Monoid_Func<And_Prim>;\n\nstruct Or_Prim : public Binary_Bool_Or_Bool32_Prim\n{\n    static const char* name() { return \"or\"; }\n    static Value zero() { return {false}; }\n    static Value call(bool x, bool y, const Context&) { return {x || y}; }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x, SC_Value y)\n    {\n        auto result = f.sc_.newvalue(x.type);\n        f.sc_.out() << \"  \" << x.type << \" \" << result << \" = \" << x\n            << (x.type.is_bool32() ? \"|\" : \"||\")\n            << y << \";\\n\";\n        return result;\n    }\n};\nusing Or_Function = Monoid_Func<Or_Prim>;\n\nstruct Xor_Prim : public Binary_Bool_Or_Bool32_Prim\n{\n    static const char* name() { return \"xor\"; }\n    static Value zero() { return {false}; }\n    static Value call(bool x, bool y, const Context&) { return {x != y}; }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x, SC_Value y)\n    {\n        auto result = f.sc_.newvalue(x.type);\n        f.sc_.out() << \"  \" << x.type << \" \" << result << \" = \";\n        if (x.type.is_bool32())\n            f.sc_.out() << x << \"^\" << y;\n        else if (x.type == SC_Type::Bool())\n            f.sc_.out() << x << \"!=\" << y;\n        else if (x.type.is_bool())\n            f.sc_.out() << \"notEqual(\" << x << \",\" << y << \")\";\n        else\n            die(\"Xor_Prim::sc_call: unknown type\");\n        f.sc_.out() << \";\\n\";\n        return result;\n    }\n};\nusing Xor_Function = Monoid_Func<Xor_Prim>;\n\nstruct Lshift_Prim : public Shift_Prim\n{\n    static const char* name() { return \"lshift\"; }\n    static Value call(Shared<const List> a, double b, const Context &cx)\n    {\n        At_Index acx(0, cx);\n        At_Index bcx(1, cx);\n        unsigned n = (unsigned) num_to_int(b, 0, a->size()-1, bcx);\n        Shared<List> result = List::make(a->size());\n        for (unsigned i = 0; i < n; ++i)\n            result->at(i) = {false};\n        for (unsigned i = n; i < a->size(); ++i)\n            result->at(i) = {a->at(i-n).to_bool(acx)};\n        return {result};\n    }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x, SC_Value y)\n    {\n        auto result = f.sc_.newvalue(x.type);\n        f.sc_.out() << \"  \" << x.type << \" \" << result << \" = \"\n            << x << \" << int(\" << y << \");\\n\";\n        return result;\n    }\n};\nusing Lshift_Function = Binary_Array_Func<Lshift_Prim>;\n\nstruct Rshift_Prim : public Shift_Prim\n{\n    static const char* name() { return \"rshift\"; }\n    static Value call(Shared<const List> a, double b, const Context &cx)\n    {\n        At_Index acx(0, cx);\n        At_Index bcx(1, cx);\n        unsigned n = (unsigned) num_to_int(b, 0, a->size()-1, bcx);\n        Shared<List> result = List::make(a->size());\n        for (unsigned i = a->size()-n; i < a->size(); ++i)\n            result->at(i) = {false};\n        for (unsigned i = 0; i < a->size()-n; ++i)\n            result->at(i) = {a->at(i+n).to_bool(acx)};\n        return {result};\n    }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x, SC_Value y)\n    {\n        auto result = f.sc_.newvalue(x.type);\n        f.sc_.out() << \"  \" << x.type << \" \" << result << \" = \"\n            << x << \" >> int(\" << y << \");\\n\";\n        return result;\n    }\n};\nusing Rshift_Function = Binary_Array_Func<Rshift_Prim>;\n\nstruct Bool32_Sum_Prim : public Binary_Bool32_Prim\n{\n    static const char* name() { return \"bool32_sum\"; }\n    static Value zero()\n    {\n        static Value z = {nat_to_bool32(0)};\n        return z;\n    }\n    static Value call(unsigned a, unsigned b, const Context&)\n    {\n        return {nat_to_bool32(a + b)};\n    }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x, SC_Value y)\n    {\n        auto result = f.sc_.newvalue(x.type);\n        f.sc_.out() << \"  \" << x.type << \" \" << result << \" = \"\n            << x << \" + \" << y << \";\\n\";\n        return result;\n    }\n};\nusing Bool32_Sum_Function = Monoid_Func<Bool32_Sum_Prim>;\n\nstruct Bool32_Product_Prim : public Binary_Bool32_Prim\n{\n    static const char* name() { return \"bool32_product\"; }\n    static Value zero()\n    {\n        static Value z = {nat_to_bool32(1)};\n        return z;\n    }\n    static Value call(unsigned a, unsigned b, const Context&)\n    {\n        return {nat_to_bool32(a * b)};\n    }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x, SC_Value y)\n    {\n        auto result = f.sc_.newvalue(x.type);\n        f.sc_.out() << \"  \" << x.type << \" \" << result << \" = \"\n            << x << \" * \" << y << \";\\n\";\n        return result;\n    }\n};\nusing Bool32_Product_Function = Monoid_Func<Bool32_Product_Prim>;\n\nstruct Bool32_To_Nat_Function : public Function\n{\n    static const char* name() { return \"bool32_to_nat\"; }\n    Bool32_To_Nat_Function() : Function(name()) {}\n    struct Prim : public Unary_Bool32_Prim\n    {\n        static Value call(unsigned n, const Context&)\n        {\n            return {double(n)};\n        }\n        // No SubCurv support because a Num (32 bit float)\n        // cannot hold a Nat (32 bit natural).\n    };\n    static Unary_Array_Op<Prim> array_op;\n    Value call(Value arg, Frame& f) override\n    {\n        return array_op.op(At_Arg(*this, f), arg);\n    }\n};\n\nstruct Nat_To_Bool32_Function : public Function\n{\n    static const char* name() { return \"nat_to_bool32\"; }\n    Nat_To_Bool32_Function() : Function(name()) {}\n    struct Prim : public Unary_Num_Prim\n    {\n        static Value call(double n, const Context& cx)\n        {\n            return {nat_to_bool32(num_to_nat(n, cx))};\n        }\n    };\n    static Unary_Array_Op<Prim> array_op;\n    Value call(Value arg, Frame& f) override\n    {\n        return array_op.op(At_Arg(*this, f), arg);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase> ph, SC_Frame& f)\n    const override\n    {\n        At_SC_Arg_Expr cx(*this, ph, f);\n        if (auto k = dynamic_cast<const Constant*>(&argx)) {\n            unsigned n = num_to_nat(k->value_.to_num(cx), cx);\n            auto type = SC_Type::Bool32();\n            auto result = f.sc_.newvalue(type);\n            f.sc_.out() << \"  \" << type << \" \" << result << \" = \"\n                << n << \"u;\\n\";\n            return result;\n        }\n        else {\n            throw Exception(cx, \"argument must be a constant\");\n        }\n    }\n};\n\nstruct Bool32_To_Float_Prim : public Unary_Bool32_Prim\n{\n    static const char* name() { return \"bool32_to_float\"; }\n    static Value call(unsigned n, const Context&)\n    {\n        return {nat_to_float(n)};\n    }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x)\n    {\n        unsigned count = x.type == SC_Type::Bool32() ? 1 : x.type.count();\n        auto result = f.sc_.newvalue(SC_Type::Num_Or_Vec(count));\n        f.sc_.out() << \"  \" << result.type << \" \" << result\n            << \" = uintBitsToFloat(\" << x << \");\\n\";\n        return result;\n    }\n};\nusing Bool32_To_Float_Function = Unary_Array_Func<Bool32_To_Float_Prim>;\n\nstruct Float_To_Bool32_Prim : public Unary_Num_Prim\n{\n    static const char* name() { return \"float_to_bool32\"; }\n    static Value call(double n, const Context&)\n    {\n        return {nat_to_bool32(float_to_nat(n))};\n    }\n    static SC_Value sc_call(SC_Frame& f, SC_Value x)\n    {\n        auto result = f.sc_.newvalue(SC_Type::Bool32(x.type.count()));\n        f.sc_.out() << \"  \" << result.type << \" \" << result\n            << \" = floatBitsToUint(\" << x << \");\\n\";\n        return result;\n    }\n};\nusing Float_To_Bool32_Function = Unary_Array_Func<Float_To_Bool32_Prim>;\n\n// Generalized dot product that includes vector dot product and matrix product.\n// Same as Mathematica Dot[A,B]. Like APL A+.\u00d7B, Python numpy.dot(A,B)\nstruct Dot_Function : public Legacy_Function\n{\n    static const char* name() { return \"dot\"; }\n    Dot_Function() : Legacy_Function(2,name()) {}\n    Value call(Frame& args) override\n    {\n        return dot(args[0], args[1], At_Arg(*this, args));\n    }\n    SC_Value sc_call_legacy(SC_Frame& f) const override\n    {\n        auto a = f[0];\n        auto b = f[1];\n        if (!a.type.is_vec())\n            throw Exception(At_SC_Arg(0, f), \"dot: argument is not a vector\");\n        if (a.type != b.type)\n            throw Exception(At_SC_Arg(1, f), \"dot: arguments have different types\");\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = dot(\"<<a<<\",\"<<b<<\");\\n\";\n        return result;\n    }\n};\n\nstruct Mag_Function : public Legacy_Function\n{\n    static const char* name() { return \"mag\"; }\n    Mag_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        // TODO: use hypot() or BLAS DNRM2 or Eigen stableNorm/blueNorm?\n        // Avoids overflow/underflow due to squaring of large/small values.\n        // Slower.  https://forum.kde.org/viewtopic.php?f=74&t=62402\n        auto list = args[0].to<List>(At_Arg(*this, args));\n        // Fast path: assume we have a list of number, compute a result.\n        double sum = 0.0;\n        for (auto val : *list) {\n            double x = val.to_num_or_nan();\n            sum += x * x;\n        }\n        if (sum == sum)\n            return {sqrt(sum)};\n        // The computation failed. Second fastest path: assume a mix of numbers\n        // and reactive numbers, try to return a reactive result.\n        Shared<List_Expr> rlist =\n            List_Expr::make(list->size(),arg_part(args.call_phrase_));\n        for (unsigned i = 0; i < list->size(); ++i) {\n            Value val = list->at(i);\n            if (val.is_num()) {\n                rlist->at(i) = make<Constant>(arg_part(args.call_phrase_), val);\n                continue;\n            }\n            auto r = val.dycast<Reactive_Value>();\n            if (r && r->sctype_ == SC_Type::Num()) {\n                rlist->at(i) = r->expr(*arg_part(args.call_phrase_));\n                continue;\n            }\n            rlist = nullptr;\n            break;\n        }\n        if (rlist) {\n            rlist->init();\n            return {make<Reactive_Expression>(\n                SC_Type::Num(),\n                make<Call_Expr>(\n                    args.call_phrase_,\n                    make<Constant>(\n                        func_part(args.call_phrase_),\n                        Value{share(*this)}),\n                    rlist),\n                At_Arg(*this, args))};\n        }\n        throw Exception(At_Arg(*this, args),\n            stringify(args[0],\": domain error\"));\n    }\n    SC_Value sc_call_legacy(SC_Frame& f) const override\n    {\n        auto arg = f[0];\n        if (!arg.type.is_vec())\n            throw Exception(At_SC_Arg(0, f), \"mag: argument is not a vector\");\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = length(\"<<arg<<\");\\n\";\n        return result;\n    }\n};\n\nstruct Count_Function : public Legacy_Function\n{\n    static const char* name() { return \"count\"; }\n    Count_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        if (auto list = args[0].dycast<const List>())\n            return {double(list->size())};\n        if (auto string = args[0].dycast<const String>())\n            return {double(string->size())};\n        if (auto re = args[0].dycast<const Reactive_Value>()) {\n            if (re->sctype_.is_list())\n                return {double(re->sctype_.count())};\n            //TODO:\n            //if (re->sctype_ == SC_Type::Any())\n        }\n        throw Exception(At_Arg(*this, args), \"not a list or string\");\n    }\n    SC_Value sc_call_legacy(SC_Frame& f) const override\n    {\n        auto arg = f[0];\n        if (!arg.type.is_list())\n            throw Exception(At_SC_Arg(0, f), \"count: argument is not a list\");\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = \"<<arg.type.count()<<\";\\n\";\n        return result;\n    }\n};\nstruct Fields_Function : public Legacy_Function\n{\n    static const char* name() { return \"fields\"; }\n    Fields_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        if (auto record = args[0].dycast<const Record>())\n            return {record->fields()};\n        throw Exception(At_Arg(*this, args), \"not a record\");\n    }\n};\n\nstruct Strcat_Function : public Legacy_Function\n{\n    static const char* name() { return \"strcat\"; }\n    Strcat_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        if (auto list = args[0].dycast<const List>()) {\n            String_Builder sb;\n            for (auto val : *list) {\n                if (auto str = val.dycast<const String_or_Symbol>())\n                    sb << *str;\n                else if (val.is_bool())\n                    sb << (val.to_bool_unsafe() ? \"true\" : \"false\");\n                else\n                    sb << val;\n            }\n            return {sb.get_string()};\n        }\n        throw Exception(At_Arg(*this, args), \"not a list\");\n    }\n};\nstruct Repr_Function : public Legacy_Function\n{\n    static const char* name() { return \"repr\"; }\n    Repr_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        String_Builder sb;\n        sb << args[0];\n        return {sb.get_string()};\n    }\n};\nstruct Decode_Function : public Legacy_Function\n{\n    static const char* name() { return \"decode\"; }\n    Decode_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& f) override\n    {\n        String_Builder sb;\n        At_Arg cx(*this, f);\n        auto list = f[0].to<List>(cx);\n        for (size_t i = 0; i < list->size(); ++i)\n            sb << (char)(*list)[i].to_int(1, 127, At_Index(i,cx));\n        return {sb.get_string()};\n    }\n};\nstruct Encode_Function : public Legacy_Function\n{\n    static const char* name() { return \"encode\"; }\n    Encode_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& f) override\n    {\n        List_Builder lb;\n        At_Arg cx(*this, f);\n        auto str = f[0].to<String>(cx);\n        for (size_t i = 0; i < str->size(); ++i)\n            lb.push_back({(double)(int)str->at(i)});\n        return {lb.get_list()};\n    }\n};\n\nstruct Match_Function : public Legacy_Function\n{\n    static const char* name() { return \"match\"; }\n    Match_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& f) override\n    {\n        At_Arg ctx0(*this, f);\n        auto list = f[0].to<List>(ctx0);\n        std::vector<Shared<Function>> cases;\n        for (size_t i = 0; i < list->size(); ++i)\n            cases.push_back(list->at(i).to<Function>(At_Index(i,ctx0)));\n        auto mf = make<Piecewise_Function>(cases);\n        mf->name_ = name_;\n        mf->argpos_ = 1;\n        return {mf};\n    }\n};\n\n// The filename argument to \"file\", if it is a relative filename,\n// is interpreted relative to the parent directory of the source file from\n// which \"file\" is called.\n//\n// Because \"file\" has this hidden parameter (the name of the source file from\n// which it is called), it is not a pure function. For this reason, it isn't\n// a function value at all, it's a metafunction.\nstruct File_Expr : public Just_Expression\n{\n    Shared<Operation> arg_;\n    File_Expr(Shared<const Call_Phrase> src, Shared<Operation> arg)\n    :\n        Just_Expression(std::move(src)),\n        arg_(std::move(arg))\n    {}\n    virtual Value eval(Frame& f) const override\n    {\n        // Metafunction calls do not automatically get a new stack frame\n        // allocated. But I want the call to `file pathname` to appear\n        // in stack traces, so I need a Frame.\n        auto& callphrase = dynamic_cast<const Call_Phrase&>(*syntax_);\n        std::unique_ptr<Frame> f2 =\n            Frame::make(0, f.system_, &f, &callphrase, nullptr);\n        At_Metacall_With_Call_Frame cx(\"file\", 0, *f2);\n\n        // construct file pathname from argument\n        Value arg = arg_->eval(f);\n        auto argstr = arg.to<String>(cx);\n        namespace fs = boost::filesystem;\n        fs::path filepath;\n        auto caller_filename = syntax_->location().source().name_;\n        if (caller_filename->empty()) {\n            filepath = fs::path(argstr->c_str());\n        } else {\n            filepath = fs::path(caller_filename->c_str()).parent_path()\n                / fs::path(argstr->c_str());\n        }\n\n        return import(filepath, cx);\n    }\n};\nstruct File_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<File_Expr>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\n/// The meaning of a call to `print`, such as `print \"foo\"`.\nstruct Print_Action : public Operation\n{\n    Shared<Operation> arg_;\n    Print_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        Value arg = arg_->eval(f);\n        auto str = arg.dycast<String>();\n        if (str == nullptr)\n            str = stringify(arg);\n        f.system_.print(str->c_str());\n    }\n};\n/// The meaning of the phrase `print` in isolation.\nstruct Print_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Print_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\nstruct Warning_Action : public Operation\n{\n    Shared<Operation> arg_;\n    Warning_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        Value arg = arg_->eval(f);\n        Shared<String> msg;\n        if (auto str = arg.dycast<String>())\n            msg = str;\n        else\n            msg = stringify(arg);\n        Exception exc{At_Phrase(*syntax_, f), msg};\n        f.system_.warning(exc);\n    }\n};\n/// The meaning of the phrase `warning` in isolation.\nstruct Warning_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Warning_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\n/// The meaning of a call to `error`, such as `error(\"foo\")`.\nstruct Error_Operation : public Operation\n{\n    Shared<Operation> arg_;\n    Error_Operation(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    [[noreturn]] void run(Frame& f) const\n    {\n        Value val = arg_->eval(f);\n        Shared<const String> msg;\n        if (auto s = val.dycast<String>())\n            msg = s;\n        else\n            msg = stringify(val);\n        throw Exception{At_Phrase(*syntax_, f), msg};\n    }\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        run(f);\n    }\n    virtual Value eval(Frame& f) const override\n    {\n        run(f);\n    }\n};\n/// The meaning of the phrase `error` in isolation.\nstruct Error_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Error_Operation>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\n// exec(expr) -- a debug action that evaluates expr, then discards the result.\n// It is used to call functions or source files for their side effects.\nstruct Exec_Action : public Operation\n{\n    Shared<Operation> arg_;\n    Exec_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        arg_->eval(f);\n    }\n};\nstruct Exec_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Exec_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\nstruct Assert_Action : public Operation\n{\n    Shared<Operation> arg_;\n    Assert_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        At_Metacall cx{\"assert\", 0, *arg_->syntax_, f};\n        bool b = arg_->eval(f).to_bool(cx);\n        if (!b)\n            throw Exception(At_Phrase(*syntax_, f), \"assertion failed\");\n    }\n};\nstruct Assert_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        auto arg = analyse_op(*ph.arg_, env);\n        return make<Assert_Action>(share(ph), arg);\n    }\n};\n\nstruct Assert_Error_Action : public Operation\n{\n    Shared<Operation> expected_message_;\n    Shared<const String> actual_message_;\n    Shared<Operation> expr_;\n\n    Assert_Error_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> expected_message,\n        Shared<const String> actual_message,\n        Shared<Operation> expr)\n    :\n        Operation(std::move(syntax)),\n        expected_message_(std::move(expected_message)),\n        actual_message_(std::move(actual_message)),\n        expr_(std::move(expr))\n    {}\n\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        Value expected_msg_val = expected_message_->eval(f);\n        auto expected_msg_str = expected_msg_val.to<const String>(\n            At_Phrase(*expected_message_->syntax_, f));\n\n        if (actual_message_ != nullptr) {\n            if (*actual_message_ != *expected_msg_str)\n                throw Exception(At_Phrase(*syntax_, f),\n                    stringify(\"assertion failed: expected error \\\"\",\n                        expected_msg_str,\n                        \"\\\", actual error \\\"\",\n                        actual_message_,\n                        \"\\\"\"));\n            return;\n        }\n\n        Value result;\n        try {\n            result = expr_->eval(f);\n        } catch (Exception& e) {\n            if (*e.shared_what() != *expected_msg_str) {\n                throw Exception(At_Phrase(*syntax_, f),\n                    stringify(\"assertion failed: expected error \\\"\",\n                        expected_msg_str,\n                        \"\\\", actual error \\\"\",\n                        e.shared_what(),\n                        \"\\\"\"));\n            }\n            return;\n        }\n        throw Exception(At_Phrase(*syntax_, f),\n            stringify(\"assertion failed: expected error \\\"\",\n                expected_msg_str,\n                \"\\\", got value \", result));\n    }\n};\nstruct Assert_Error_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        auto parens = cast<Paren_Phrase>(ph.arg_);\n        Shared<Comma_Phrase> commas = nullptr;\n        if (parens) commas = cast<Comma_Phrase>(parens->body_);\n        if (parens && commas && commas->args_.size() == 2) {\n            auto msg = analyse_op(*commas->args_[0].expr_, env);\n            Shared<Operation> expr = nullptr;\n            Shared<const String> actual_msg = nullptr;\n            try {\n                expr = analyse_op(*commas->args_[1].expr_, env);\n            } catch (Exception& e) {\n                actual_msg = e.shared_what();\n            }\n            return make<Assert_Error_Action>(share(ph), msg, actual_msg, expr);\n        } else {\n            throw Exception(At_Phrase(ph, env),\n                \"assert_error: expecting 2 arguments\");\n        }\n    }\n};\n\nstruct Defined_Expression : public Just_Expression\n{\n    Shared<const Operation> expr_;\n    Symbol_Expr selector_;\n\n    Defined_Expression(\n        Shared<const Phrase> syntax,\n        Shared<const Operation> expr,\n        Symbol_Expr selector)\n    :\n        Just_Expression(std::move(syntax)),\n        expr_(std::move(expr)),\n        selector_(std::move(selector))\n    {\n    }\n\n    virtual Value eval(Frame& f) const override\n    {\n        auto val = expr_->eval(f);\n        auto s = val.dycast<Record>();\n        if (s) {\n            auto id = selector_.eval(f);\n            return {s->hasfield(id)};\n        } else {\n            return {false};\n        }\n    }\n};\nstruct Defined_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        auto arg = analyse_op(*ph.arg_, env);\n        auto dot = cast<Dot_Expr>(arg);\n        if (dot != nullptr)\n            return make<Defined_Expression>(\n                share(ph), dot->base_, dot->selector_);\n        throw Exception(At_Phrase(*ph.arg_, env),\n            \"defined: argument must be `expression.identifier`\");\n    }\n};\n\nconst Namespace&\nbuiltin_namespace()\n{\n    #define FUNCTION(f) {make_symbol(f::name()), make<Builtin_Value>(Value{make<f>()})}\n\n    static const Namespace names = {\n    {make_symbol(\"pi\"), make<Builtin_Value>(pi)},\n    {make_symbol(\"tau\"), make<Builtin_Value>(two_pi)},\n    {make_symbol(\"inf\"), make<Builtin_Value>(INFINITY)},\n    {make_symbol(\"false\"), make<Builtin_Value>(Value(false))},\n    {make_symbol(\"true\"), make<Builtin_Value>(Value(true))},\n\n    FUNCTION(Is_Bool_Function),\n    FUNCTION(Is_Symbol_Function),\n    FUNCTION(Is_Num_Function),\n    FUNCTION(Is_String_Function),\n    FUNCTION(Is_List_Function),\n    FUNCTION(Is_Record_Function),\n    FUNCTION(Is_Fun_Function),\n    FUNCTION(Bit_Function),\n    FUNCTION(Sqrt_Function),\n    FUNCTION(Log_Function),\n    FUNCTION(Abs_Function),\n    FUNCTION(Floor_Function),\n    FUNCTION(Ceil_Function),\n    FUNCTION(Trunc_Function),\n    FUNCTION(Round_Function),\n    FUNCTION(Frac_Function),\n    FUNCTION(Sin_Function),\n    FUNCTION(Cos_Function),\n    FUNCTION(Tan_Function),\n    FUNCTION(Asin_Function),\n    FUNCTION(Acos_Function),\n    FUNCTION(Atan_Function),\n    FUNCTION(Atan2_Function),\n    FUNCTION(Sinh_Function),\n    FUNCTION(Cosh_Function),\n    FUNCTION(Tanh_Function),\n    FUNCTION(Asinh_Function),\n    FUNCTION(Acosh_Function),\n    FUNCTION(Atanh_Function),\n    FUNCTION(Max_Function),\n    FUNCTION(Min_Function),\n    FUNCTION(Sum_Function),\n    FUNCTION(And_Function),\n    FUNCTION(Or_Function),\n    FUNCTION(Xor_Function),\n    FUNCTION(Lshift_Function),\n    FUNCTION(Rshift_Function),\n    FUNCTION(Bool32_Sum_Function),\n    FUNCTION(Bool32_Product_Function),\n    FUNCTION(Bool32_To_Nat_Function),\n    FUNCTION(Nat_To_Bool32_Function),\n    FUNCTION(Bool32_To_Float_Function),\n    FUNCTION(Float_To_Bool32_Function),\n    FUNCTION(Dot_Function),\n    FUNCTION(Mag_Function),\n    FUNCTION(Count_Function),\n    FUNCTION(Fields_Function),\n    FUNCTION(Strcat_Function),\n    FUNCTION(Repr_Function),\n    FUNCTION(Decode_Function),\n    FUNCTION(Encode_Function),\n    FUNCTION(Match_Function),\n\n    {make_symbol(\"file\"), make<Builtin_Meaning<File_Metafunction>>()},\n    {make_symbol(\"print\"), make<Builtin_Meaning<Print_Metafunction>>()},\n    {make_symbol(\"warning\"), make<Builtin_Meaning<Warning_Metafunction>>()},\n    {make_symbol(\"error\"), make<Builtin_Meaning<Error_Metafunction>>()},\n    {make_symbol(\"assert\"), make<Builtin_Meaning<Assert_Metafunction>>()},\n    {make_symbol(\"assert_error\"), make<Builtin_Meaning<Assert_Error_Metafunction>>()},\n    {make_symbol(\"exec\"), make<Builtin_Meaning<Exec_Metafunction>>()},\n    {make_symbol(\"defined\"), make<Builtin_Meaning<Defined_Metafunction>>()},\n    };\n    return names;\n}\n\n} // namespace curv\n", "meta": {"hexsha": "bad309b8dae21a1ab2029ccc4841e2305cfc1167", "size": 42921, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libcurv/builtin.cc", "max_stars_repo_name": "daitomanabe/curv", "max_stars_repo_head_hexsha": "4aaca4ee3c384c9a21e8731fb8b6d927c5172147", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T19:15:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-06T19:15:31.000Z", "max_issues_repo_path": "libcurv/builtin.cc", "max_issues_repo_name": "daitomanabe/curv", "max_issues_repo_head_hexsha": "4aaca4ee3c384c9a21e8731fb8b6d927c5172147", "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": "libcurv/builtin.cc", "max_forks_repo_name": "daitomanabe/curv", "max_forks_repo_head_hexsha": "4aaca4ee3c384c9a21e8731fb8b6d927c5172147", "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.7391304348, "max_line_length": 87, "alphanum_fraction": 0.5783416043, "num_tokens": 10832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19358781864024519}}
{"text": "#ifndef PARTICLE\n#define PARTICLE\n\n#include <vector>\n#include <boost/numeric/ublas/vector.hpp>\n#include <string>\n#include <sstream>\n#include <random>\n\nclass DecayChannel;\n\nnamespace ublas = boost::numeric::ublas;\n\nclass Particle {\n  private:\n    double mass;\n    int charge;\n    int neutrons;\n    double spin;\n    double currentExcitationEnergy;\n\n    std::string name;\n\n    ublas::vector<double> fourMomentum;\n    std::vector<DecayChannel*> decayChannels;\n\n    static std::default_random_engine randomGen;\n  public:\n    Particle();\n    Particle(const std::string&, double, int, int, double, double);\n    Particle(const Particle&);\n    Particle& operator=(const Particle& rhs);\n\n    inline std::string ListInformation() const {\n      std::ostringstream oss;\n      oss << \"-------------------------------------------------\\n\";\n      oss << \"  Particle: \" << name << \"\\n\";\n      oss << \"-------------------------------------------------\\n\";\n      oss << \"  Charge: \" << charge << \"\\t\\tNeutrons: \" << neutrons << \"\\tSpin: \" << spin << \"\\n\";\n      oss << \"  Mass: \" << mass << \"\\tG.S. Lifetime: \" << GetLifetime() << \"\\n\";\n      return oss.str();\n    }\n    std::vector<Particle*> Decay();\n    double GetDecayTime();\n    inline std::string GetName() const {\n      std::string n;\n      std::ostringstream oss(n);\n      oss << name << \" (\" << currentExcitationEnergy << \" keV) Kin. En.: \" << GetKinEnergy();\n      return oss.str();\n    };\n    inline std::string GetRawName() const { return name; };\n    inline std::string GetInfoForFile() const {\n      std::string n;\n      std::ostringstream oss(n);\n      oss << name << \"\\t\" << currentExcitationEnergy << \"\\t\" << GetKinEnergy() << \"\\t\" << fourMomentum(0) << \"\\t\" << fourMomentum(1) << \"\\t\" << fourMomentum(2) << \"\\t\" << fourMomentum(3);\n      return oss.str();\n    };\n    inline void SetMomentum(ublas::vector<double> v) { fourMomentum = v; };\n    inline void SetExcitationEnergy(double e) { currentExcitationEnergy = e; fourMomentum(0)+=e; };\n    double GetLifetime() const;\n    inline int GetCharge() const { return charge; };\n    inline int GetNeutrons() const { return neutrons; };\n    inline double GetMass() const { return mass + currentExcitationEnergy; };\n    inline ublas::vector<double> GetMomentum() const { return fourMomentum; };\n    inline double GetExcitationEnergy() const { return currentExcitationEnergy; };\n    inline void AddDecayChannel(DecayChannel* dc) { decayChannels.push_back(dc); };\n    ublas::vector<double> GetVelocity() const;\n    inline double GetKinEnergy() const { return fourMomentum(0)-GetMass(); };\n    inline void SetKinEnergy(double e) { fourMomentum(0) = GetMass() + e; };\n    inline ublas::vector<double> Get3Momentum() const {\n      ublas::vector<double> v (3);\n      v[0] = fourMomentum[1];\n      v[1] = fourMomentum[2];\n      v[2] = fourMomentum[3];\n      return v;\n    };\n    inline std::vector<DecayChannel*>& GetDecayChannels() { return decayChannels; };\n};\n\n#endif\n", "meta": {"hexsha": "14fc138b2892e01be6fc7d95cb5fdfa38e4402f7", "size": 2956, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/include/Particle.hh", "max_stars_repo_name": "leenderthayen/CRADLE", "max_stars_repo_head_hexsha": "8b7979a201c6d95abbc00cf44159b8fa577a17f5", "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/include/Particle.hh", "max_issues_repo_name": "leenderthayen/CRADLE", "max_issues_repo_head_hexsha": "8b7979a201c6d95abbc00cf44159b8fa577a17f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-04-22T13:07:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T04:49:09.000Z", "max_forks_repo_path": "source/include/Particle.hh", "max_forks_repo_name": "leenderthayen/CRADLE", "max_forks_repo_head_hexsha": "8b7979a201c6d95abbc00cf44159b8fa577a17f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T19:03:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T19:03:55.000Z", "avg_line_length": 36.4938271605, "max_line_length": 187, "alphanum_fraction": 0.6092692828, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.1935662781237855}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Geometry>\n#include <chrono>\n#include \"mpi.h\"\n#include <vector>\n#include <random>\n\n#include \"General_Utilities.hpp\"\n#include \"Physical_Parameters.hpp\"\n#include \"IC_Generator.hpp\"\n#include \"Trajectory_Simulation.hpp\"\n#include \"PREM.hpp\"\n#include \"RN_Generators.hpp\"\n\nusing namespace std;\nusing namespace std::chrono;\n\nint main(int argc, char *argv[])\n{\n\n//INITIALIZATION\t\n////////////////////////////////////////////////////////////\n\t//MPI Enviroment\n\t\t// Initialize the MPI environment\n\t    \tMPI_Init(NULL, NULL);\n\t    // Get the number of processes\n\t    \tint numprocs;\n\t    \tMPI_Comm_size(MPI_COMM_WORLD, &numprocs);\n\t    // Get the ID number of the process\n\t    \tint myRank;\n\t    \tMPI_Comm_rank(MPI_COMM_WORLD, &myRank);\n\n\t//Starting time\n\t    high_resolution_clock::time_point tStart,t1,t2,tEnd;\n\t    double durationIni=0.0;\n\t    double durationMain=0.0;\n\t    if(myRank==0)\n\t    {\n\t    \ttStart = high_resolution_clock::now();\n\t    }\n\t//Read in configuration file, set up the detector and define the earth velocity\n\t\tRead_Config_File(argv[1]);\n\t//Initialize Logfile and create folders for inputfiles\n\t\tif(myRank==0)\n\t\t{\n\t\t\tCopy_Config_File(argv[1]);\n\t\t\tstd::chrono::time_point<std::chrono::system_clock> start;\n\t\t\tstart = std::chrono::system_clock::now();\n\t\t\tstd::time_t start_time = std::chrono::system_clock::to_time_t(start);\n\t\t\tcout <<\"\\n##############################\"<<endl\n\t\t\t<<\"DaMaSCUS\"<<version<<\" - Simulation\"<<endl<<endl\n\t\t\t<<\"Starting Time: \" <<std::ctime(&start_time)\n\t\t\t<<\"Simulation ID: \" <<SimID <<endl<<endl\n\t\t\t<<\"Creating logfile.\" <<endl;\n\t\t\tLogFile_Initialize(numprocs);\n\t\t}\n\t//Initialize Random Number Generator:\n\t\tstd::random_device rd;\n\t\tstd::mt19937 PRNG(rd());\n\t//Synchronize processes:\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\n////////////////////////////////////////////////////////////\n\t\n\t//1. Initial MC run without scatterings:\n\t\t//Initialize the earth model for initial run\n\t\t\tdouble sigmaInitial=1e-20*pb;\n\t\t\tInitialize_PREM(mChi,sigmaInitial);\n\t\t//Deactivate formfactor, if it is used:\n\t\t\tstring formfactor0=FormFactor;\n\t\t\tFormFactor=\"None\";\n\t\tif (myRank==0) cout <<\"Start initial MC simulation run without DM scatterings.\" <<endl;\n\t\t//Desired Data Sample for inital and main MC simulation\t\n\t\t\tunsigned long long int Local_SampleSize_Initial =ceil((double)Global_SampleSize_Initial/numprocs);\n\t\t\tGlobal_SampleSize_Initial=Local_SampleSize_Initial*numprocs;\n\t\t//Particle counter per isodetection ring\n\t\t\tunsigned long long int Global_N0[Isodetection_Rings];\n\t\t\tunsigned long long int Local_N0[Isodetection_Rings];\n\t\t\tfor (int i=0;i<Isodetection_Rings;i++)Local_N0[i]=0;\n\t\t\tlong double Global_W0[Isodetection_Rings];\n\t\t\tlong double Local_W0[Isodetection_Rings];\n\t\t\tfor (int i=0;i<Isodetection_Rings;i++)Local_W0[i]=0.0;\n\t\t\tlong double Global_W0sq[Isodetection_Rings];\n\t\t\tlong double Local_W0sq[Isodetection_Rings];\n\t\t\tfor (int i=0;i<Isodetection_Rings;i++)Local_W0sq[i]=0.0;\n\n\t\t//Depth crossing counter\n\t\t\tunsigned long long int Global_Counter_Crossings0=0;\n\t\t\tunsigned long long int Local_Counter_Crossings0=0;\n\t\t\t\n\t\t//Simulation of trajectories without scatterings and without formfactor implementation\n\t\t\tfor(unsigned int i=0;i<Local_SampleSize_Initial;i++)\n\t\t\t{\n\t\t\t\tEvent IC = InitialCondition(0,vEarth,PRNG);\n\t\t\t\tTrajectory trajectory=ParticleTrack(mChi,sigmaInitial,IC,vcut,PRNG);\n\t\t\t\tstd::vector<Event> CrossingEvents=trajectory.DepthCrossing(Detector_Depth);\n\t\t\t\tLocal_Counter_Crossings0+=CrossingEvents.size();\n\t\t\t\t//Increment the isodetection counters and record the weighted velocity norm.\n\t\t\t\tfor (unsigned int j=0;j<CrossingEvents.size();j++)\n\t\t\t\t{\n\t\t\t\t\tint IsoRing=CrossingEvents[j].IsodetectionRing(Isodetection_Rings);\n\t\t\t\t\tLocal_N0[IsoRing]++;\n\t\t\t\t\t\n\t\t\t\t\tdouble speed_ratio = IC.NormVelocity() / CrossingEvents[j].NormVelocity();\n\t\t\t\t\tdouble weight = CrossingEvents[j].DataWeight(speed_ratio);\n\t\t\t\t\tLocal_W0[IsoRing]+=weight;\n\t\t\t\t\tLocal_W0sq[IsoRing]+=weight*weight;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Reactivate form factor\n\t\t\t\tFormFactor=formfactor0;\n\t\t//Reduce the local isodetection counter\n\t\t\tMPI_Reduce(&Local_N0,&Global_N0,Isodetection_Rings,MPI_UNSIGNED_LONG_LONG,MPI_SUM,0,MPI_COMM_WORLD);\n\t\t\tMPI_Reduce(&Local_Counter_Crossings0,&Global_Counter_Crossings0,1,MPI_UNSIGNED_LONG_LONG,MPI_SUM,0,MPI_COMM_WORLD);\n\t\t\tMPI_Reduce(&Local_W0,&Global_W0,Isodetection_Rings,MPI_LONG_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);\n\t\t\tMPI_Reduce(&Local_W0sq,&Global_W0sq,Isodetection_Rings,MPI_LONG_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);\n\n\t\t\n\t\t//Status update on the console\t\n\t\t\tif(myRank==0)\n\t\t\t{\n\t\t\t\t//computing time\n\t\t\t\tt1 = high_resolution_clock::now();\n\t\t\t\tdurationIni =1e-6*duration_cast<microseconds>( t1 - tStart ).count();\n\t\t\t\tcout <<\"\\tInitial run finished\\t(\" <<floor(durationIni) <<\" s).\" <<endl <<endl;\n\t\t\t}\t\n\t//2. MC run with scatterings and velocity data collection.\n\t\t//Initialize the earth model for the main run\n\t\t\tInitialize_PREM(mChi,sigma0);\n\t\tif (myRank==0) cout <<\"Start main MC simulation run with scatterings.\" <<endl;\n\t\t//Particle counter per isodetection ring\n\t\t\tunsigned long long int Global_N[Isodetection_Rings];\n\t\t\tunsigned long long int Local_N[Isodetection_Rings];\n\t\t\tfor (int i=0;i<Isodetection_Rings;i++)Local_N[i]=0;\n\t\t//Sum of data weights, necessary for determination of local DM number density \n\t\t\tlong double Global_W[Isodetection_Rings];\n\t\t\tlong double Local_W[Isodetection_Rings];\n\t\t\tfor (int i=0;i<Isodetection_Rings;i++)Local_W[i]=0.0;\n\t\t//Sum of squared data weights, necessary for determination of the local DM number density uncertainty.\n\t\t\tlong double Global_Wsq[Isodetection_Rings];\n\t\t\tlong double Local_Wsq[Isodetection_Rings];\n\t\t\tfor (int i=0;i<Isodetection_Rings;i++)Local_Wsq[i]=0.0;\n\t\t//Work Load Distribution: Desired Velocity Data Sample Size for each isodetection ring for each MPI process.\n\t\t\tunsigned int Local_SampleSize_Velocity=ceil((double)Global_SampleSize_Velocity/numprocs);\n\t\t\tGlobal_SampleSize_Velocity=Local_SampleSize_Velocity*numprocs;\n\t\t//Counter for simulated trajectories\n\t\t\tunsigned long long int Global_Counter_Tracks=0;\n\t\t\tunsigned long long int Local_Counter_Tracks=0;\n\t\t//Counter for scattering events\n\t\t\tunsigned long long int Global_Counter_Scatterings=0;\n\t\t\tunsigned long long int Local_Counter_Scatterings=0;\n\t\t//Counter for free particles:\n\t\t\tunsigned long long int Global_Counter_Free=0;\n\t\t\tunsigned long long int Local_Counter_Free=0;\n\t\t//Counter for depth crossing\n\t\t\tunsigned long long int Global_Counter_Crossings=0;\n\t\t\tunsigned long long int Local_Counter_Crossings=0;\n\t\t//Counter for velocity cutoffs\n\t\t\tunsigned long long int Global_Counter_vCutoff=0;\n\t\t\tunsigned long long int Local_Counter_vCutoff=0;\n\t\t//Local Counter for velocity data \n\t\t\tunsigned int Local_Counter_DatapointsTotal=0;\n\t\t\tunsigned int Local_Counter_Datapoints[Isodetection_Rings];\n\t\t\tfor(int i=0;i<Isodetection_Rings;i++) Local_Counter_Datapoints[i]=0;\n\t\t\t\n\t\t//MPI Output File and Offset\n\t\t\tMPI_Offset offset;\n \t\t\tMPI_File   file_Velocity[Isodetection_Rings];\n \t\t\tMPI_File   file_Weights[Isodetection_Rings];\n \t\t   \tMPI_Status status;\n \t\t//Velocity Output files including process dependent offset\n \t\t   \tfor(int i=0;i<Isodetection_Rings;i++)\n \t\t   \t{\n \t\t   \t\t//Velocity output files\n\t \t\t   \t\tstring filename=\"../data/\"+SimID+\"_data/velocity.\"+std::to_string(i);\n\t \t\t   \t\tint test=MPI_File_open(MPI_COMM_WORLD,const_cast<char*>(filename.c_str()),MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_WRONLY,MPI_INFO_NULL, &file_Velocity[i]);\n\t \t   \t\t\t//if it already exists, it will be overwritten!\n\t\t    \t\t\tif(test != MPI_SUCCESS)\n\t\t    \t\t\t{\n\t\t    \t\t\t\tif (myRank == 0) MPI_File_delete(const_cast<char*>(filename.c_str()),MPI_INFO_NULL);\n\t\t    \t\t\t\t//MPI_Barrier(MPI_COMM_WORLD);\n\t\t    \t\t\t\ttest=MPI_File_open(MPI_COMM_WORLD,const_cast<char*>(filename.c_str()),MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_WRONLY,MPI_INFO_NULL, &file_Velocity[i]);\n\t\t    \t\t\t}\n\t\t    \t\t//Offset\n\t\t \t\t   \t\toffset = myRank * Local_SampleSize_Velocity * sizeof(Eigen::Vector3d);\n\t\t\t\t \t\tMPI_File_seek(file_Velocity[i], offset,MPI_SEEK_SET);\n\t\t\t \t//Weights output files\n\t\t\t \t\tfilename=\"../data/\"+SimID+\"_data/weights.\"+std::to_string(i);\n\t \t\t   \t\ttest=MPI_File_open(MPI_COMM_WORLD,const_cast<char*>(filename.c_str()),MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_WRONLY,MPI_INFO_NULL, &file_Weights[i]);\n\t \t   \t\t\t//if it already exists, it will be overwritten!\n\t\t    \t\t\tif(test != MPI_SUCCESS)\n\t\t    \t\t\t{\n\t\t    \t\t\t\tif (myRank == 0) MPI_File_delete(const_cast<char*>(filename.c_str()),MPI_INFO_NULL);\n\t\t    \t\t\t\t//MPI_Barrier(MPI_COMM_WORLD);\n\t\t    \t\t\t\ttest=MPI_File_open(MPI_COMM_WORLD,const_cast<char*>(filename.c_str()),MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_WRONLY,MPI_INFO_NULL, &file_Weights[i]);\n\t\t    \t\t\t}\n\t\t    \t\t//Offset\n\t \t\t   \t\t\toffset = myRank * Local_SampleSize_Velocity * sizeof(double);\n\t\t\t \t\t\tMPI_File_seek(file_Weights[i], offset,MPI_SEEK_SET);\t\n \t\t   \t}\n \t\t//Simulation of Tracks\n \t\t   \twhile(Local_Counter_DatapointsTotal<Isodetection_Rings*Local_SampleSize_Velocity)\n \t\t   \t{\n \t\t   \t\t//Simulate track.\n\t\t\t\t\tEvent IC = InitialCondition(0,vEarth,PRNG);\n \t\t   \t\t\tTrajectory trajectory=ParticleTrack(mChi,sigma0,IC,vcut,PRNG); \t\t   \t\t\n \t\t   \t\t//Increase counter of tracks and scatterings and vcutoff reachers \n \t\t   \t\t\tLocal_Counter_Tracks++;\n \t\t   \t\t\tint scatterings = trajectory.NoOfScatterings();\n \t\t   \t\t\tif(scatterings==0) Local_Counter_Free++;\n \t\t   \t\t\telse Local_Counter_Scatterings+=scatterings;\n \t\t   \t\t\tif(trajectory.Trajectory_Type()==2)\tLocal_Counter_vCutoff++;\t\n\t\t\t\t//Where did the particle pass the isodetection rings.\n\t\t\t\t\tstd::vector<Event> CrossingEvents=trajectory.DepthCrossing(Detector_Depth);\n\t\t\t\t\tLocal_Counter_Crossings+=CrossingEvents.size();\n\t\t\t\t\tfor (unsigned int j=0;j<CrossingEvents.size();j++)\n\t\t\t\t\t{\n\t\t\t\t\t\t//Which ring?\n\t\t\t\t\t\t\tint IsoRing=CrossingEvents[j].IsodetectionRing(Isodetection_Rings);\n\t\t\t\t\t\t//Increase the weight sums\n\t\t\t\t\t\t\tdouble speed_ratio = IC.NormVelocity() / CrossingEvents[j].NormVelocity();\n\t\t\t\t\t\t\tdouble weight = CrossingEvents[j].DataWeight(speed_ratio);\n\t\t\t\t\t\t\tLocal_W[IsoRing]+=weight;\n\t\t\t\t\t\t\tLocal_Wsq[IsoRing]+=weight*weight;\n\t\t\t\t\t\t//Increase the particle counter.\n\t\t\t\t\t\t\tLocal_N[IsoRing]++;\t\n\t\t\t\t\t\t//If this isodetection ring is not finished collecting data, save the velocity and weight\n\t\t\t\t\t\t\tif(Local_Counter_Datapoints[IsoRing]<Local_SampleSize_Velocity)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//Save velocity.\n\t\t\t\t\t\t\t\t\tEigen::Vector3d vel = CrossingEvents[j].Velocity();\n\t\t\t\t\t\t\t\t//Increase data counters\n\t\t\t\t\t\t\t\t\tLocal_Counter_Datapoints[IsoRing]++;\n\t\t\t\t\t\t\t\t\tLocal_Counter_DatapointsTotal++;\n\t\t\t\t\t\t\t\t//Save velocity and weights to file\n\t\t\t\t\t\t\t\t\tMPI_File_write(file_Velocity[IsoRing],vel.data(),vel.size(),MPI_DOUBLE,&status);\n\t\t\t\t\t\t\t\t\tMPI_File_write(file_Weights[IsoRing],&weight,1,MPI_DOUBLE,&status);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n \t\t   \t}\n \t\t   \tMPI_Barrier(MPI_COMM_WORLD);\n \t\t//MPI Reductions\n  \t  \t\tMPI_Reduce(&Local_Counter_Tracks,&Global_Counter_Tracks,1,MPI_UNSIGNED_LONG_LONG,MPI_SUM,0,MPI_COMM_WORLD);\n  \t  \t\tMPI_Reduce(&Local_Counter_Scatterings,&Global_Counter_Scatterings,1,MPI_UNSIGNED_LONG_LONG,MPI_SUM,0,MPI_COMM_WORLD);\n  \t  \t\tMPI_Reduce(&Local_Counter_vCutoff,&Global_Counter_vCutoff,1,MPI_UNSIGNED_LONG_LONG,MPI_SUM,0,MPI_COMM_WORLD);\n  \t  \t\tMPI_Reduce(&Local_Counter_Free,&Global_Counter_Free,1,MPI_UNSIGNED_LONG_LONG,MPI_SUM,0,MPI_COMM_WORLD);\n  \t  \t\tMPI_Reduce(&Local_Counter_Crossings,&Global_Counter_Crossings,1,MPI_UNSIGNED_LONG_LONG,MPI_SUM,0,MPI_COMM_WORLD);\n  \t  \t\tMPI_Reduce(&Local_N,&Global_N,Isodetection_Rings,MPI_UNSIGNED_LONG_LONG,MPI_SUM,0,MPI_COMM_WORLD);  \t\n\t\t\tMPI_Reduce(&Local_W,&Global_W,Isodetection_Rings,MPI_LONG_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);\n\t\t\tMPI_Reduce(&Local_Wsq,&Global_Wsq,Isodetection_Rings,MPI_LONG_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);\n\n  \t  \t//Calculate DM Densities\n  \t  \t\tvector<vector<double>> Edensity=DM_EnergyDensity(Global_W0,Global_SampleSize_Initial,Global_W,Global_Counter_Tracks,Global_W0sq,Global_Wsq,Isodetection_Rings);\n  \t  \t\tvector<vector<double>> Ndensity=DM_NumberDensity(mChi,Edensity);\n\t\t\tdouble averageNdensity=DM_AverageDensity(Ndensity,Isodetection_Rings,Detector_Depth);\n \t   \t//Status update and save N(theta) and rho(theta)\n \t   \t\tif(myRank==0)\n\t\t\t{\t  \t\t\t\t\t\n\t\t\t\t//Save density\n\t\t\t\t\tofstream f;\n\t\t\t\t\tf.open(\"../data/\"+SimID+\".rho\");\n\t\t\t\t\tfor(int i=0;i<Isodetection_Rings;i++) f <<180.0 / Isodetection_Rings * i  <<\"\\t\" <<InUnits(Edensity[i][0],GeV/cm/cm/cm)<<\"\\t\" <<InUnits(Edensity[i][1],GeV/cm/cm/cm) <<endl;//<<\"\\t\" <<InUnits(AverageVelocity_0[i],km/sec)<<\"\\t\" <<InUnits(AverageVelocity[i],km/sec)<<endl;// <<\"\\t\" <<Global_N0[i]<<\"\\t\" <<Global_N[i] <<endl; \n\t\t\t\t\tf.close();\n\t\t\t\t//computing time\n\t\t\t\t\tt2 = high_resolution_clock::now();\n\t\t\t\t\tdurationMain =1e-6*duration_cast<microseconds>( t2 - t1 ).count();\n\t\t\t\t\tcout <<\"\\tMain MC run finished\\t\" <<\"(\"<<floor(durationMain) <<\" s).\" <<endl;\n\t\t\t}\n\t\t//Close all output files\n\t\tfor(int i=0;i<Isodetection_Rings;i++)\n\t\t{\n\t\t\tMPI_File_close(&file_Velocity[i]);\n\t\t\tMPI_File_close(&file_Weights[i]);\n\t\t} \t\n////////////////////////////////////////////////////////////\n\n//Finalize simulation\n////////////////////////////////////////////////////////////\n    //Master process finishes logfile\n\t\tif(myRank==0)\n\t\t{\n\t\t\t//Ending time and computing time\n\t\t\t\ttEnd = high_resolution_clock::now();\n\t\t\t\tdouble durationTotal =1e-6*duration_cast<microseconds>( tEnd - tStart ).count();\n\t\t\t\tcout <<\"\\nProcessing Time:\\t\"<< durationTotal<<\"s (\"<< floor(durationTotal/3600.0)<<\":\"<<floor(fmod(durationTotal/60.0,60.0))<<\":\"<<floor(fmod(durationTotal,60.0))<<\":\"<<floor(fmod(1000*durationTotal,1000.0))<<\").\"<<endl\n\t\t\t\t<<\"##############################\"<<endl;\n\t\t\t//Finalize Logfile\n\t\t\t\tLogFile_Finalize(Global_Counter_Tracks,Global_Counter_Scatterings,Global_Counter_Free,Global_Counter_vCutoff,Global_SampleSize_Initial,Global_SampleSize_Velocity,Global_Counter_Crossings0,Global_Counter_Crossings,averageNdensity,durationIni,durationMain,durationTotal);\n\t\t}\t\n\t// Finalize the MPI environment.\n\t    MPI_Finalize();\n    \treturn 0;\n////////////////////////////////////////////////////////////\n}\n", "meta": {"hexsha": "b56b765876a644a0da2ea32ac8552ff275886204", "size": 14022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/main.cpp", "max_stars_repo_name": "temken/DaMaSCUS", "max_stars_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-13T13:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T19:35:12.000Z", "max_issues_repo_path": "src/simulation/main.cpp", "max_issues_repo_name": "temken/DaMaSCUS", "max_issues_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-06-06T14:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:01:56.000Z", "max_forks_repo_path": "src/simulation/main.cpp", "max_forks_repo_name": "temken/DaMaSCUS", "max_forks_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-09T09:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-09T09:48:10.000Z", "avg_line_length": 47.0536912752, "max_line_length": 327, "alphanum_fraction": 0.7083868207, "num_tokens": 3827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.19339461798390398}}
{"text": "// Copyright (c) 2015-2021 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef subclone_model_hpp\n#define subclone_model_hpp\n\n#include <vector>\n#include <unordered_map>\n#include <utility>\n\n#include <boost/optional.hpp>\n\n#include \"config/common.hpp\"\n#include \"core/types/haplotype.hpp\"\n#include \"core/types/indexed_haplotype.hpp\"\n#include \"core/types/genotype.hpp\"\n#include \"core/types/cancer_genotype.hpp\"\n#include \"core/models/haplotype_likelihood_array.hpp\"\n#include \"containers/mappable_block.hpp\"\n#include \"exceptions/unimplemented_feature_error.hpp\"\n#include \"variational_bayes_mixture_model.hpp\"\n#include \"genotype_prior_model.hpp\"\n#include \"cancer_genotype_prior_model.hpp\"\n\nnamespace octopus { namespace model {\n\ntemplate <typename GenotypeType, typename GenotypePriorModel_>\nclass SubcloneModelBase\n{\npublic:\n    constexpr static unsigned max_ploidy = 100;\n    \n    struct AlgorithmParameters\n    {\n        unsigned max_iterations = 1000;\n        double epsilon          = 0.05;\n        unsigned max_seeds      = 12;\n        boost::optional<MemoryFootprint> target_max_memory = boost::none;\n        ExecutionPolicy execution_policy = ExecutionPolicy::seq;\n    };\n    \n    struct Priors\n    {\n        using GenotypeMixturesDirichletAlphas   = std::vector<double>;\n        using GenotypeMixturesDirichletAlphaMap = std::unordered_map<SampleName, GenotypeMixturesDirichletAlphas>;\n        \n        const GenotypePriorModel_& genotype_prior_model;\n        GenotypeMixturesDirichletAlphaMap alphas;\n    };\n    \n    struct Latents\n    {\n        using GenotypeMixturesDirichletAlphas   = std::vector<double>;\n        using GenotypeMixturesDirichletAlphaMap = std::unordered_map<SampleName, GenotypeMixturesDirichletAlphas>;\n        using ProbabilityVector                 = std::vector<double>;\n        using LogProbabilityVector              = std::vector<double>;\n        \n        ProbabilityVector genotype_probabilities;\n        LogProbabilityVector genotype_log_probabilities;\n        GenotypeMixturesDirichletAlphaMap alphas;\n    };\n    \n    struct InferredLatents\n    {\n        Latents max_evidence_params;\n        typename Latents::LogProbabilityVector genotype_log_priors;\n        typename Latents::ProbabilityVector weighted_genotype_posteriors;\n        double approx_log_evidence;\n    };\n    \n    SubcloneModelBase() = delete;\n    \n    SubcloneModelBase(std::vector<SampleName> samples, Priors priors);\n    SubcloneModelBase(std::vector<SampleName> samples, Priors priors, AlgorithmParameters parameters);\n    \n    SubcloneModelBase(const SubcloneModelBase&)            = default;\n    SubcloneModelBase& operator=(const SubcloneModelBase&) = default;\n    SubcloneModelBase(SubcloneModelBase&&)                 = default;\n    SubcloneModelBase& operator=(SubcloneModelBase&&)      = default;\n    \n    ~SubcloneModelBase() = default;\n    \n    const Priors& priors() const noexcept;\n    \n    void prime(const MappableBlock<Haplotype>& haplotypes);\n    void unprime() noexcept;\n    bool is_primed() const noexcept;\n    \n    InferredLatents\n    evaluate(const std::vector<GenotypeType>& genotypes,\n             const HaplotypeLikelihoodArray& haplotype_likelihoods,\n             std::vector<typename Latents::LogProbabilityVector> hints = {}) const;\n    \nprivate:\n    std::vector<SampleName> samples_;\n    Priors priors_;\n    AlgorithmParameters parameters_;\n    const MappableBlock<Haplotype>* haplotypes_;\n};\n\nusing SubcloneModel = SubcloneModelBase<Genotype<IndexedHaplotype<>>, GenotypePriorModel>;\nusing SomaticSubcloneModel = SubcloneModelBase<CancerGenotype<IndexedHaplotype<>>, CancerGenotypePriorModel>;\n\ntemplate <typename G, typename GPM>\nconstexpr unsigned SubcloneModelBase<G, GPM>::max_ploidy;\n\ntemplate <typename G, typename GPM>\nSubcloneModelBase<G, GPM>::SubcloneModelBase(std::vector<SampleName> samples, Priors priors)\n: SubcloneModelBase {std::move(samples), std::move(priors), AlgorithmParameters {}}\n{}\n\ntemplate <typename G, typename GPM>\nSubcloneModelBase<G, GPM>::SubcloneModelBase(std::vector<SampleName> samples, Priors priors, AlgorithmParameters parameters)\n: samples_ {std::move(samples)}\n, priors_ {std::move(priors)}\n, parameters_ {parameters}\n{}\n\ntemplate <typename G, typename GPM>\nconst typename SubcloneModelBase<G, GPM>::Priors& SubcloneModelBase<G, GPM>::priors() const noexcept\n{\n    return priors_;\n}\n\ntemplate <typename G, typename GPM>\nvoid SubcloneModelBase<G, GPM>::prime(const MappableBlock<Haplotype>& haplotypes)\n{\n    haplotypes_ = std::addressof(haplotypes);\n}\n\ntemplate <typename G, typename GPM>\nvoid SubcloneModelBase<G, GPM>::unprime() noexcept\n{\n    haplotypes_ = nullptr;\n}\n\ntemplate <typename G, typename GPM>\nbool SubcloneModelBase<G, GPM>::is_primed() const noexcept\n{\n    return haplotypes_;\n}\n\nnamespace detail {\n\nstd::vector<LogProbabilityVector>\ngenerate_seeds(const std::vector<SampleName>& samples,\n               const std::vector<Genotype<IndexedHaplotype<>>>& genotypes,\n               const LogProbabilityVector& genotype_log_priors,\n               const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n               const SubcloneModel::Priors& priors,\n               std::size_t max_seeds,\n               std::vector<LogProbabilityVector> hints = {},\n               const MappableBlock<Haplotype>* haplotypes = nullptr);\n\nstd::vector<LogProbabilityVector>\ngenerate_seeds(const std::vector<SampleName>& samples,\n               const std::vector<CancerGenotype<IndexedHaplotype<>>>& genotypes,\n               const LogProbabilityVector& genotype_log_priors,\n               const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n               const SomaticSubcloneModel::Priors& priors,\n               std::size_t max_seeds,\n               std::vector<LogProbabilityVector> hints = {},\n               const MappableBlock<Haplotype>* haplotypes = nullptr);\n\ntemplate <std::size_t K, typename G, typename GPM>\nVBAlpha<K> flatten(const typename SubcloneModelBase<G, GPM>::Priors::GenotypeMixturesDirichletAlphas& alpha)\n{\n    VBAlpha<K> result {};\n    std::copy_n(std::cbegin(alpha), K, std::begin(result));\n    return result;\n}\n\ntemplate <std::size_t K, typename G, typename GPM>\nVBAlphaVector<K> flatten(const typename SubcloneModelBase<G, GPM>::Priors::GenotypeMixturesDirichletAlphaMap& alphas,\n                         const std::vector<SampleName>& samples)\n{\n    VBAlphaVector<K> result(samples.size());\n    std::transform(std::cbegin(samples), std::cend(samples), std::begin(result),\n                   [&alphas] (const auto& sample) { return flatten<K, G, GPM>(alphas.at(sample)); });\n    return result;\n}\n\ntemplate <std::size_t K>\nVBGenotype<K>\nflatten(const Genotype<IndexedHaplotype<>>& genotype,\n        const SampleName& sample,\n        const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    VBGenotype<K> result {};\n    haplotype_likelihoods.prime(sample);\n    std::transform(std::cbegin(genotype), std::cend(genotype), std::begin(result),\n                   [&] (const auto& haplotype) { return std::cref(haplotype_likelihoods[haplotype]); });\n    return result;\n}\n\ntemplate <std::size_t K>\nauto copy_cref(const Genotype<IndexedHaplotype<>>& genotype,\n               const SampleName& sample,\n               const HaplotypeLikelihoodArray& haplotype_likelihoods,\n               typename VBGenotype<K>::iterator result_itr)\n{\n    haplotype_likelihoods.prime(sample);\n    return std::transform(std::cbegin(genotype), std::cend(genotype), result_itr,\n                          [&] (const auto& haplotype) { return std::cref(haplotype_likelihoods[haplotype]); });\n}\n\ntemplate <std::size_t K>\nVBGenotype<K>\nflatten(const CancerGenotype<IndexedHaplotype<>>& genotype,\n        const SampleName& sample,\n        const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    VBGenotype<K> result {};\n    assert(genotype.ploidy() == K);\n    auto itr = copy_cref<K>(genotype.germline(), sample, haplotype_likelihoods, std::begin(result));\n    copy_cref<K>(genotype.somatic(), sample, haplotype_likelihoods, itr);\n    return result;\n}\n\ntemplate <std::size_t K, typename G>\nVBGenotypeVector<K>\nflatten(const std::vector<G>& genotypes, const SampleName& sample,\n        const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    VBGenotypeVector<K> result(genotypes.size());\n    std::transform(std::cbegin(genotypes), std::cend(genotypes), std::begin(result),\n                   [&sample, &haplotype_likelihoods] (const auto& genotype) {\n                       return flatten<K>(genotype, sample, haplotype_likelihoods);\n                   });\n    return result;\n}\n\ntemplate <std::size_t K, typename G>\nVBReadLikelihoodMatrix<K>\nflatten(const std::vector<G>& genotypes,\n        const std::vector<SampleName>& samples,\n        const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    VBReadLikelihoodMatrix<K> result {};\n    result.reserve(samples.size());\n    std::transform(std::cbegin(samples), std::cend(samples), std::back_inserter(result),\n                   [&genotypes, &haplotype_likelihoods] (const auto& sample) {\n                       return flatten<K>(genotypes, sample, haplotype_likelihoods);\n                   });\n    return result;\n}\n\ntemplate <std::size_t K, typename G, typename GPM>\nauto expand(VBAlpha<K>& alpha)\n{\n    return typename SubcloneModelBase<G, GPM>::Latents::GenotypeMixturesDirichletAlphas(std::begin(alpha), std::end(alpha));\n}\n\ntemplate <std::size_t K, typename G, typename GPM>\nauto expand(const std::vector<SampleName>& samples, VBAlphaVector<K>&& alphas)\n{\n    typename SubcloneModelBase<G, GPM>::Latents::GenotypeMixturesDirichletAlphaMap result {};\n    std::transform(std::cbegin(samples), std::cend(samples), std::begin(alphas),\n                   std::inserter(result, std::begin(result)),\n                   [] (const auto& sample, auto&& vb_alpha) {\n                       return std::make_pair(sample, expand<K, G, GPM>(vb_alpha));\n                   });\n    return result;\n}\n\ntemplate <std::size_t K, typename G, typename GPM>\ntypename SubcloneModelBase<G, GPM>::InferredLatents\nexpand(VBResultPacket<K>& vb_results, const std::vector<SampleName>& samples, LogProbabilityVector genotype_log_priors)\n{\n    typename SubcloneModelBase<G, GPM>::Latents posterior_latents {\n        std::move(vb_results.map_latents.genotype_posteriors),\n        std::move(vb_results.map_latents.genotype_log_posteriors),\n        expand<K, G, GPM>(samples, std::move(vb_results.map_latents.alphas))\n        };\n    return {std::move(posterior_latents),\n            std::move(genotype_log_priors),\n            std::move(vb_results.evidence_weighted_genotype_posteriors),\n            vb_results.max_log_evidence};\n}\n\ntemplate <std::size_t K, typename G, typename GPM>\ntypename SubcloneModelBase<G, GPM>::InferredLatents\nrun_variational_bayes_helper(const std::vector<SampleName>& samples,\n                             const std::vector<G>& genotypes,\n                             const typename SubcloneModelBase<G, GPM>::Priors::GenotypeMixturesDirichletAlphaMap& prior_alphas,\n                             const LogProbabilityVector& genotype_log_priors,\n                             const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n                             const typename SubcloneModelBase<G, GPM>::AlgorithmParameters& params,\n                             std::vector<LogProbabilityVector>&& seeds)\n{\n    VariationalBayesParameters vb_params {params.epsilon, params.max_iterations};\n    if (params.target_max_memory) {\n        const auto estimated_memory_default = estimate_memory_requirement<K>(samples, haplotype_log_likelihoods, genotypes.size(), vb_params);\n        if (estimated_memory_default > *params.target_max_memory) {\n            vb_params.save_memory = true;\n        }\n    }\n    if (params.execution_policy == ExecutionPolicy::par) {\n        vb_params.parallel_execution = true;\n    }\n    const auto vb_prior_alphas = flatten<K, G, GPM>(prior_alphas, samples);\n    const auto log_likelihoods = flatten<K>(genotypes, samples, haplotype_log_likelihoods);\n    auto vb_results = octopus::model::run_variational_bayes(vb_prior_alphas, genotype_log_priors, log_likelihoods, vb_params, std::move(seeds));\n    return expand<K, G, GPM>(vb_results, samples, std::move(genotype_log_priors));\n}\n\ntemplate <typename G, typename GPM,\n          std::size_t... Is>\ntypename SubcloneModelBase<G, GPM>::InferredLatents\nrun_variational_bayes_helper(const std::vector<SampleName>& samples,\n                             const std::vector<G>& genotypes,\n                             const typename SubcloneModelBase<G, GPM>::Priors::GenotypeMixturesDirichletAlphaMap& prior_alphas,\n                             LogProbabilityVector genotype_log_priors,\n                             const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n                             const typename SubcloneModelBase<G, GPM>::AlgorithmParameters& params,\n                             std::vector<LogProbabilityVector>&& seeds,\n                             std::index_sequence<Is...>)\n{\n    constexpr auto max_ploidy = std::index_sequence<Is...>::size();\n    const auto ploidy = genotypes.front().ploidy();\n    if (ploidy > max_ploidy) {\n        throw UnimplementedFeatureError {\"ploidies above \" + std::to_string(max_ploidy), \"SubcloneModel\"};\n    }\n    typename SubcloneModelBase<G, GPM>::InferredLatents result;\n    int unused[] = {(ploidy == Is ?\n                    (result = run_variational_bayes_helper<Is, G, GPM>(samples, genotypes, prior_alphas, std::move(genotype_log_priors),\n                                                                       haplotype_log_likelihoods, params, std::move(seeds))\n                                                                       , 0) : 0)...};\n    (void) unused;\n    return result;\n}\n\ntemplate<std::size_t N, std::size_t... Seq>\nconstexpr std::index_sequence<N + Seq ...>\nadd(std::index_sequence<Seq...>) { return {}; }\n\ntemplate<std::size_t Min, std::size_t Max>\nusing make_index_range = decltype(add<Min>(std::make_index_sequence<Max - Min>()));\n\ntemplate <typename G, typename GPM>\ntypename SubcloneModelBase<G, GPM>::InferredLatents\nrun_variational_bayes(const std::vector<SampleName>& samples,\n                      const std::vector<G>& genotypes,\n                      const typename SubcloneModelBase<G, GPM>::Priors& priors,\n                      const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n                      const typename SubcloneModelBase<G, GPM>::AlgorithmParameters& params,\n                      std::vector<typename SubcloneModelBase<G, GPM>::Latents::LogProbabilityVector> hints,\n                      const MappableBlock<Haplotype>* haplotypes)\n{\n    constexpr auto max_ploidy = SubcloneModelBase<G, GPM>::max_ploidy;\n    auto genotype_log_priors = evaluate(genotypes, priors.genotype_prior_model);\n    auto seeds = generate_seeds(samples, genotypes, genotype_log_priors, haplotype_log_likelihoods, priors, params.max_seeds, std::move(hints), haplotypes);\n    return run_variational_bayes_helper<G, GPM>(samples, genotypes, priors.alphas, std::move(genotype_log_priors),\n                                                    haplotype_log_likelihoods, params, std::move(seeds),\n                                                    make_index_range<1, max_ploidy + 1> {});\n}\n\n} // namespace detail\n\ntemplate <typename G, typename GPM>\ntypename SubcloneModelBase<G, GPM>::InferredLatents\nSubcloneModelBase<G, GPM>::evaluate(const std::vector<G>& genotypes,\n                                    const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                                    std::vector<typename Latents::LogProbabilityVector> hints) const\n{\n    assert(!genotypes.empty());\n    return detail::run_variational_bayes<G, GPM>(samples_, genotypes, priors_, haplotype_likelihoods, parameters_, std::move(hints), haplotypes_);\n}\n\n} // namespace model\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "95392e8ebb56fd887cb30952de90dc7ba123f759", "size": 15950, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/genotype/subclone_model.hpp", "max_stars_repo_name": "Schaudge/octopus", "max_stars_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "src/core/models/genotype/subclone_model.hpp", "max_issues_repo_name": "Schaudge/octopus", "max_issues_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "src/core/models/genotype/subclone_model.hpp", "max_forks_repo_name": "Schaudge/octopus", "max_forks_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 42.6470588235, "max_line_length": 156, "alphanum_fraction": 0.6830094044, "num_tokens": 3786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.19339461401101607}}
{"text": "#include <koinos/system/system_calls.hpp>\n#include <koinos/contracts/token/token.h>\n\n#include <koinos/buffer.hpp>\n#include <koinos/common.h>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <string>\n\nusing namespace koinos;\nusing namespace koinos::contracts;\n\nusing int128_t = boost::multiprecision::int128_t;\n\nnamespace constants {\n\nstatic const std::string koinos_name   = \"Test Koinos\";\nstatic const std::string koinos_symbol = \"tKOIN\";\nconstexpr uint32_t koinos_decimals     = 8;\nconstexpr uint64_t mana_regen_time_ms  = 1200000; // 20 minutes\nconstexpr std::size_t max_address_size = 25;\nconstexpr std::size_t max_name_size    = 32;\nconstexpr std::size_t max_symbol_size  = 8;\nconstexpr std::size_t max_buffer_size  = 2048;\nconstexpr uint32_t supply_id           = 0;\nconstexpr uint32_t balance_id          = 1;\nstd::string supply_key                 = \"\";\nconst auto contract_id                 = system::get_contract_id();\n\n} // constants\n\nnamespace state {\n\nnamespace detail {\n\nsystem::object_space create_supply_space()\n{\n   system::object_space supply_space;\n   supply_space.mutable_zone().set( reinterpret_cast< const uint8_t* >( constants::contract_id.data() ), constants::contract_id.size() );\n   supply_space.set_id( constants::supply_id );\n   return supply_space;\n}\n\nsystem::object_space create_balance_space()\n{\n   system::object_space balance_space;\n   balance_space.mutable_zone().set( reinterpret_cast< const uint8_t* >( constants::contract_id.data() ), constants::contract_id.size() );\n   balance_space.set_id( constants::balance_id );\n   return balance_space;\n}\n\n} // detail\n\nconst system::object_space& supply_space()\n{\n   static const auto supply_space = detail::create_supply_space();\n   return supply_space;\n}\n\nconst system::object_space& balance_space()\n{\n   static const auto balance_space = detail::create_balance_space();\n   return balance_space;\n}\n\n} // state\n\nenum entries : uint32_t\n{\n   get_account_rc_entry     = 0,\n   consume_account_rc_entry = 1,\n   name_entry               = 0x76ea4297,\n   symbol_entry             = 0x7e794b24,\n   decimals_entry           = 0x59dc15ce,\n   total_supply_entry       = 0xcf2e8212,\n   balance_of_entry         = 0x15619248,\n   transfer_entry           = 0x62efa292,\n   mint_entry               = 0xc2f82bdc\n};\n\nusing get_account_rc_arguments\n   = chain::get_account_rc_arguments<\n      constants::max_name_size\n   >;\n\nusing consume_account_rc_arguments\n   = chain::consume_account_rc_arguments<\n      constants::max_name_size\n   >;\n\nvoid regenerate_mana( token::mana_balance_object& bal )\n{\n   auto head_block_time = system::get_head_info().head_block_time();\n   auto delta = std::min( head_block_time - bal.last_mana_update(), constants::mana_regen_time_ms );\n   if ( delta )\n   {\n      auto new_mana = bal.mana() + ( ( int128_t( delta ) * int128_t( bal.balance() ) ) / constants::mana_regen_time_ms ).convert_to< uint64_t >() ;\n      bal.set_mana( std::min( new_mana, bal.balance() ) );\n      bal.set_last_mana_update( head_block_time );\n   }\n}\n\nchain::get_account_rc_result get_account_rc( const get_account_rc_arguments& args )\n{\n   std::string owner( reinterpret_cast< const char* >( args.get_account().get_const() ), args.get_account().get_length() );\n   token::mana_balance_object bal_obj;\n   system::get_object( state::balance_space(), owner, bal_obj );\n\n   regenerate_mana( bal_obj );\n\n   chain::get_account_rc_result res;\n   res.set_value( bal_obj.get_mana() );\n   return res;\n}\n\nchain::consume_account_rc_result consume_account_rc( const consume_account_rc_arguments& args )\n{\n   chain::consume_account_rc_result res;\n   res.set_value( false );\n\n   const auto [caller, privilege] = system::get_caller();\n   if ( privilege != chain::privilege::kernel_mode )\n   {\n      system::print( \"consume_account_rc must be called from kernel context\\n\" );\n      return res;\n   }\n\n   std::string owner( reinterpret_cast< const char* >( args.get_account().get_const() ), args.get_account().get_length() );\n   token::mana_balance_object bal_obj;\n   system::get_object( state::balance_space(), owner, bal_obj );\n\n   regenerate_mana( bal_obj );\n\n   // Assumes mana cannot go negative...\n   if ( bal_obj.mana() < args.value() )\n   {\n      system::print( \"account has insufficient mana for consumption\\n\" );\n      return res;\n   }\n\n   bal_obj.set_mana( bal_obj.mana() - args.value() );\n\n   system::put_object( state::balance_space(), owner, bal_obj );\n\n   res.set_value( true );\n   return res;\n}\n\ntoken::name_result< constants::max_name_size > name()\n{\n   token::name_result< constants::max_name_size > res;\n   res.mutable_value() = constants::koinos_name.c_str();\n   return res;\n}\n\ntoken::symbol_result< constants::max_symbol_size > symbol()\n{\n   token::symbol_result< constants::max_symbol_size > res;\n   res.mutable_value() = constants::koinos_symbol.c_str();\n   return res;\n}\n\ntoken::decimals_result decimals()\n{\n   token::decimals_result res;\n   res.mutable_value() = constants::koinos_decimals;\n   return res;\n}\n\ntoken::total_supply_result total_supply()\n{\n   token::total_supply_result res;\n\n   token::balance_object bal_obj;\n   system::get_object( state::supply_space(), constants::supply_key, bal_obj );\n\n   res.mutable_value() = bal_obj.get_value();\n   return res;\n}\n\ntoken::balance_of_result balance_of( const token::balance_of_arguments< constants::max_address_size >& args )\n{\n   token::balance_of_result res;\n\n   std::string owner( reinterpret_cast< const char* >( args.get_owner().get_const() ), args.get_owner().get_length() );\n\n   token::mana_balance_object bal_obj;\n   system::get_object( state::balance_space(), owner, bal_obj );\n\n   res.set_value( bal_obj.get_balance() );\n   return res;\n}\n\ntoken::transfer_result transfer( const token::transfer_arguments< constants::max_address_size, constants::max_address_size >& args )\n{\n   token::transfer_result res;\n   res.set_value( false );\n\n   std::string from( reinterpret_cast< const char* >( args.get_from().get_const() ), args.get_from().get_length() );\n   std::string to( reinterpret_cast< const char* >( args.get_to().get_const() ), args.get_to().get_length() );\n   uint64_t value = args.get_value();\n\n   if ( from == to )\n   {\n      system::print( \"cannot transfer to self\\n\" );\n      return res;\n   }\n\n   const auto [ caller, privilege ] = system::get_caller();\n   if ( caller != from )\n   {\n      system::require_authority( from );\n   }\n\n   token::mana_balance_object from_bal_obj;\n   system::get_object( state::balance_space(), from, from_bal_obj );\n\n   if ( from_bal_obj.balance() < value )\n   {\n      system::print( \"'from' has insufficient balance\\n\" );\n      return res;\n   }\n\n   regenerate_mana( from_bal_obj );\n\n   if ( from_bal_obj.mana() < value )\n   {\n      system::print( \"'from' has insufficient mana for transfer\\n\" );\n      return res;\n   }\n\n   token::mana_balance_object to_bal_obj;\n   system::get_object( state::balance_space(), to, to_bal_obj );\n\n   regenerate_mana( to_bal_obj );\n\n   from_bal_obj.set_balance( from_bal_obj.balance() - value );\n   from_bal_obj.set_mana( from_bal_obj.mana() - value );\n   to_bal_obj.set_balance( to_bal_obj.balance() + value );\n   to_bal_obj.set_mana( to_bal_obj.mana() + value );\n\n   system::put_object( state::balance_space(), from, from_bal_obj );\n   system::put_object( state::balance_space(), to, to_bal_obj );\n\n   token::transfer_event< constants::max_address_size, constants::max_address_size > transfer_event;\n   transfer_event.mutable_from().set( args.get_from().get_const(), args.get_from().get_length() );\n   transfer_event.mutable_to().set( args.get_to().get_const(), args.get_to().get_length() );\n   transfer_event.set_value( args.get_value() );\n\n   std::vector< std::string > impacted;\n   impacted.push_back( to );\n   impacted.push_back( from );\n   koinos::system::event( \"koin.transfer\", transfer_event, impacted );\n\n   res.set_value( true );\n   return res;\n}\n\ntoken::mint_result mint( const token::mint_arguments< constants::max_address_size >& args )\n{\n   token::mint_result res;\n   res.set_value( false );\n\n   std::string to( reinterpret_cast< const char* >( args.get_to().get_const() ), args.get_to().get_length() );\n   uint64_t amount = args.get_value();\n\n   const auto [ caller, privilege ] = system::get_caller();\n   if ( privilege != chain::privilege::kernel_mode )\n   {\n      system::print( \"can only mint token from kernel context\\n\" );\n      return res;\n   }\n\n   auto supply = total_supply().get_value();\n   auto new_supply = supply + amount;\n\n   // Check overflow\n   if ( new_supply < supply )\n   {\n      system::print( \"mint would overflow supply\\n\" );\n      return res;\n   }\n\n   token::mana_balance_object to_bal_obj;\n   system::get_object( state::balance_space(), to, to_bal_obj );\n\n   regenerate_mana( to_bal_obj );\n\n   to_bal_obj.set_balance( to_bal_obj.balance() + amount );\n   to_bal_obj.set_mana( to_bal_obj.mana() + amount );\n\n   token::balance_object supply_obj;\n   supply_obj.set_value( new_supply );\n\n   system::put_object( state::supply_space(), constants::supply_key, supply_obj );\n   system::put_object( state::balance_space(), to, to_bal_obj );\n\n   token::mint_event< constants::max_address_size > mint_event;\n   mint_event.mutable_to().set( args.get_to().get_const(), args.get_to().get_length() );\n   mint_event.set_value( amount );\n\n   std::vector< std::string > impacted;\n   impacted.push_back( to );\n   koinos::system::event( \"koin.mint\", mint_event, impacted );\n\n   res.set_value( true );\n   return res;\n}\n\nint main()\n{\n   auto entry_point = system::get_entry_point();\n   auto args = system::get_contract_arguments();\n\n   std::array< uint8_t, constants::max_buffer_size > retbuf;\n\n   koinos::read_buffer rdbuf( (uint8_t*)args.c_str(), args.size() );\n   koinos::write_buffer buffer( retbuf.data(), retbuf.size() );\n\n   switch( std::underlying_type_t< entries >( entry_point ) )\n   {\n      case entries::get_account_rc_entry:\n      {\n         get_account_rc_arguments arg;\n         arg.deserialize( rdbuf );\n\n         auto res = get_account_rc( arg );\n         res.serialize( buffer );\n         break;\n      }\n      case entries::consume_account_rc_entry:\n      {\n         consume_account_rc_arguments arg;\n         arg.deserialize( rdbuf );\n\n         auto res = consume_account_rc( arg );\n         res.serialize( buffer );\n         break;\n      }\n      case entries::name_entry:\n      {\n         auto res = name();\n         res.serialize( buffer );\n         break;\n      }\n      case entries::symbol_entry:\n      {\n         auto res = symbol();\n         res.serialize( buffer );\n         break;\n      }\n      case entries::decimals_entry:\n      {\n         auto res = decimals();\n         res.serialize( buffer );\n         break;\n      }\n      case entries::total_supply_entry:\n      {\n         auto res = total_supply();\n         res.serialize( buffer );\n         break;\n      }\n      case entries::balance_of_entry:\n      {\n         token::balance_of_arguments< constants::max_address_size > arg;\n         arg.deserialize( rdbuf );\n\n         auto res = balance_of( arg );\n         res.serialize( buffer );\n         break;\n      }\n      case entries::transfer_entry:\n      {\n         token::transfer_arguments< constants::max_address_size, constants::max_address_size > arg;\n         arg.deserialize( rdbuf );\n\n         auto res = transfer( arg );\n         res.serialize( buffer );\n         break;\n      }\n      case entries::mint_entry:\n      {\n         token::mint_arguments< constants::max_address_size > arg;\n         arg.deserialize( rdbuf );\n\n         auto res = mint( arg );\n         res.serialize( buffer );\n         break;\n      }\n      default:\n         system::exit_contract( 1 );\n   }\n\n   std::string retval( reinterpret_cast< const char* >( buffer.data() ), buffer.get_size() );\n   system::set_contract_result_bytes( retval );\n\n   system::exit_contract( 0 );\n   return 0;\n}\n", "meta": {"hexsha": "2e27e7c347983763165e84eef37ec174d1b336e8", "size": 11824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contracts/koin/koin.cpp", "max_stars_repo_name": "koinos/koinos-system-contracts", "max_stars_repo_head_hexsha": "652ab29ce418a9237e881c4ddebc82fb3151ab26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-23T14:29:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:29:40.000Z", "max_issues_repo_path": "contracts/koin/koin.cpp", "max_issues_repo_name": "koinos/koinos-system-contracts", "max_issues_repo_head_hexsha": "652ab29ce418a9237e881c4ddebc82fb3151ab26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2021-07-06T18:20:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T08:58:29.000Z", "max_forks_repo_path": "contracts/koin/koin.cpp", "max_forks_repo_name": "koinos/koinos-system-contracts", "max_forks_repo_head_hexsha": "652ab29ce418a9237e881c4ddebc82fb3151ab26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T08:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T23:08:40.000Z", "avg_line_length": 29.4129353234, "max_line_length": 147, "alphanum_fraction": 0.6726150203, "num_tokens": 2864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.19338474769098477}}
{"text": "/*\n * Copyright 2008-2016 Jan Gasthaus\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 <iostream>\n#include <fstream>\n#include <libgen.h>\n#include <cmath>\n#include <boost/program_options.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/convenience.hpp>\n#include <boost/scoped_ptr.hpp>\n\n#include <libplump/libplump.h>\n#include <libplump/switching_restaurant.h>\n\nusing namespace std;\nusing namespace gatsby::libplump;\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nstatic unsigned int num_types = 256;\n\n/**\n * Predict probabilities on test file.\n */\nd_vec predict(po::variables_map& vm, HPYPModel& m, int start_pos, seq_type seq) {\n  d_vec predictive;\n  for(int i = start_pos; i < (int)seq.size(); ++i) {    \n    if (vm.count(\"sum\")) {\n        d_vec dist = m.predictiveDistribution(start_pos, i);\n        if (!closeTo(sum(dist), 1)) {\n          std::cout << \"probs don't sum to one, but \" << sum(dist) << \", probs: \" << iterableToString(dist) << std::endl;\n        }\n    }\n    switch (vm[\"fragment\"].as<int>()) {\n      case 1:\n        predictive.push_back(m.predict(start_pos, i, seq[i]));\n        break;\n      case 2:\n        predictive.push_back(m.predictWithFragmentation(start_pos, i, seq[i]));\n        break;\n      case 3:\n        predictive.push_back(m.predictBelow(start_pos, i, seq[i]));\n        break;\n    }\n  }\n  return predictive;\n}\n\nIParameters* getParameters(po::variables_map& vm) {\n  switch(vm[\"parameters\"].as<int>()) {\n    case 0:\n      cerr << \"getParameters(): Using SimpleParameters\" << endl;\n      return new SimpleParameters(vm[\"disc\"].as<d_vec>(), vm[\"alpha\"].as<double>());\n    case 1:\n      cerr << \"getParameters(): Using GradientParameters\" << endl;\n      return new GradientParameters(vm[\"disc\"].as<d_vec>(), vm[\"alpha\"].as<double>());\n  }\n}\n\nIAddRemoveRestaurant* getRestaurant(po::variables_map& vm) {\n  switch(vm[\"restaurant\"].as<int>()) {\n    case 0:\n      cerr << \"getRestaurant(): Using KneserNeyRestaurant\" << endl;\n      return new KneserNeyRestaurant();\n    case 1:\n      cerr << \"getRestaurant(): Using SimpleFullRestaurant\" << endl;\n      return new SimpleFullRestaurant();\n    case 2:\n      cerr << \"getRestaurant(): Using HistogramRestaurant\" << endl;\n      return new HistogramRestaurant();\n    case 3:\n      cerr << \"getRestaurant(): Using ReinstantiatingCompactRestaurant\" << endl;\n      return new ReinstantiatingCompactRestaurant();\n    case 4:\n      cerr << \"getRestaurant(): Using StirlingCompactRestaurant\" << endl;\n      return new StirlingCompactRestaurant();\n    case 5:\n      cerr << \"getRestaurant(): \"\n           << \"Using SwitchingRestaurant(SimpleFullRestaurant, 10)\"\n           << endl;\n      return new SwitchingRestaurant(new SimpleFullRestaurant(), 10);\n    case 6:\n      cerr << \"getRestaurant(): Using PowerLawRestaurant\" << endl;\n      return new PowerLawRestaurant();\n    case 7:\n      cerr << \"getRestaurant(): Using FractionalRestaurant\" << endl;\n      return new FractionalRestaurant();\n    case 8:\n      cerr << \"getRestaurant(): Using ExpectedTablesCompactRestaurant\" << endl;\n      return new ExpectedTablesCompactRestaurant();\n    case 9:\n      cerr << \"getRestaurant(): Using LocallyOptimalRestaurant\" << endl;\n      return new LocallyOptimalRestaurant();\n  }\n  cout << \"Unknown restaurant type (--restaurant)!\";\n  exit(1);\n}\n\nINodeManager* getNodeManager(po::variables_map& vm,\n    const IPayloadFactory& payloadFactory) {\n  return new SimpleNodeManager(payloadFactory);\n}\n\nvoid pushFileToSeq(po::variables_map& vm, std::string filename, seq_type& seq) {\n  if (vm.count(\"read-int32\")) {\n    pushFileToVec<int>(filename, seq, vm[\"head\"].as<int>());\n  } else {\n    pushFileToVec<unsigned char>(filename, seq, vm[\"head\"].as<int>());\n  }\n}\n\nvoid runSampler(po::variables_map& vm, HPYPModel& model, int train_length) {\n  if (vm[\"sampler\"].as<int>() == 1) {\n    model.runGibbsSampler(false);\n  } \n  if (vm[\"sampler\"].as<int>() == 2) {\n    model.runGibbsSampler(true);\n  } \n  if (vm[\"sampler\"].as<int>() == 3) {\n    model.removeAddSweep(1, train_length);\n  } \n}\n\n\ndouble score_file(po::variables_map& vm) {\n  string filename = vm[\"input-file\"].as<string>();\n  fs::path input_path(filename);\n  if (!fs::exists(input_path)) {\n    cerr << \"Input file not found!\" << endl;\n    exit(1);\n  }\n\n  seq_type seq;\n  pushFileToSeq(vm, filename, seq);\n  cout << \"Sequence length: \" << seq.size() << endl;\n  cout << \"Number of types:  \" << num_types << endl;\n  cout << seq[0] << endl;\n\n  boost::scoped_ptr<IParameters> parameters(getParameters(vm));\n  boost::scoped_ptr<IAddRemoveRestaurant> restaurant(getRestaurant(vm));\n  boost::scoped_ptr<INodeManager> nodeManager(\n      getNodeManager(vm, restaurant->getFactory()));\n\n  HPYPModel model(seq, *nodeManager, *restaurant, *parameters, num_types);\n\n  d_vec losses;\n  if (vm.count(\"load-serialized-nodes\")) {\n    Serializer nodeSerializer(vm[\"load-serialized-nodes\"].as<string>());\n    nodeSerializer.loadNodesAndPayloads(*nodeManager, restaurant->getFactory());\n  } else {\n    int lag = vm[\"train-lag\"].as<int>();\n    if (lag == 0) {\n      losses = model.computeLosses(0, seq.size());\n    } else {\n      losses = model.computeLossesWithDeletion(0, seq.size(), lag);\n    }\n  }\n  \n  if (vm.count(\"debug\")) {\n    model.checkConsistency();\n  }\n\n  cout << \"Training loss: \" << mean(losses) << endl;\n\n  if (vm.count(\"print-tree\")) {\n    cout << model.toString() << endl;\n  }\n\n\n  if (vm.count(\"dump-losses\")) {\n    iterableToCSVFile(losses,\"train-losses\");\n  }\n\n\n  if (vm.count(\"test-file\")) {\n    d_vec current_sample_losses;\n    int start_pos = seq.size();\n    pushFileToSeq(vm, vm[\"test-file\"].as<string>(), seq);\n    cout << \"Test sequence length: \" << seq.size()-start_pos << endl;\n    int mode = vm[\"mode\"].as<int>();\n    ostringstream dump_fn;\n    dump_fn << \"losses_\" << fs::basename(input_path); // <<  \"_\"  << m.parameters.alpha;\n    dump_fn << \"_\" << vm[\"restaurant\"].as<int>()  << \"_\" << vm[\"mode\"].as<int>() << \"_\" << vm[\"fragment\"].as<int>() << \"_\" << vm[\"prefix\"].as<string>() << \".csv\";\n    ofstream losses_f(dump_fn.str().c_str());\n    current_sample_losses.push_back(prob2loss<double>(predict(vm, model, start_pos, seq)));\n    losses_f << current_sample_losses.back() << \", \";\n    cout << \"loss: \" << current_sample_losses.back() << endl;\n    if (vm.count(\"burn-in\")) {\n      for (int i = 0; i < vm[\"burn-in\"].as<int>(); ++i) {\n        cout << \"Burn-in iteration: \" << i << endl;\n        if (vm.count(\"joint\")) {\n          double joint = model.computeLogJoint();\n          cout << \"log-joint: \" << joint << endl;\n          cerr << joint << \", \" << current_sample_losses.back() << endl; \n        }\n        runSampler(vm, model, start_pos);\n        if (vm.count(\"debug\")) {\n          if (model.checkConsistency()) {\n            cout << \"Model consistent.\" << endl;\n          } else {\n            cout << \"Consitency check failed.\" << endl;\n          }\n        }\n        current_sample_losses.push_back(prob2loss<double>(predict(vm, model, start_pos, seq)));\n        losses_f << current_sample_losses.back() << \", \";\n        cout << \"loss: \" << current_sample_losses.back() << endl;\n        losses_f.flush();\n        if (vm.count(\"debug\") && vm.count(\"print-tree\")) {\n          cout << model.toString() << endl;\n        }\n      }\n      if (vm.count(\"dump-losses\")) {\n        iterableToCSVFile(predict(vm, model, start_pos, seq), \"test-probs_0\");\n      }\n      d_vec_vec sample_predictions;\n      for (int i = 0; i < vm[\"samples\"].as<int>(); ++i) {\n        cout << \"sampling iteration iteration: \" << i << endl;\n        runSampler(vm, model, start_pos);\n        sample_predictions.push_back(predict(vm, model, start_pos, seq));\n        cout << \"loss (this sample): \" << prob2loss<double>(sample_predictions.back()) << endl;\n        cout << \"loss (avg): \" << prob2loss<double>(average(sample_predictions)) << endl;\n        if (vm.count(\"dump-losses\")) {\n          ostringstream dump_test_loss_fn;\n          dump_test_loss_fn << \"test-probs_\" << i + 1;\n          iterableToCSVFile(sample_predictions.back(), dump_test_loss_fn.str());\n        }\n        if (vm.count(\"joint\")) {\n          double joint = model.computeLogJoint();\n          cerr << joint << \", \" \n               << prob2loss<double>(sample_predictions.back()) << \", \"\n               << prob2loss<double>(average(sample_predictions)) << endl;\n        }\n      }\n    }\n\n    d_vec online_losses;\n    int lag = vm[\"lag\"].as<int>();\n    if (lag == 0) {\n      online_losses = model.computeLosses(start_pos, seq.size());\n    } else {\n      online_losses = model.computeLossesWithDeletion(start_pos, seq.size(), lag);\n    }\n    if (vm.count(\"dump-losses\")) {\n      iterableToCSVFile(online_losses,\"online-test-losses\");\n    }\n    cout << \"loss (online): \" << mean(online_losses) << endl;\n  }\n\n  if (vm.count(\"save-serialized-nodes\")) {\n    Serializer nodeSerializer(vm[\"save-serialized-nodes\"].as<string>());\n    nodeSerializer.saveNodesAndPayloads(*nodeManager, restaurant->getFactory());\n  }\n  cout << \"Discounts: \";\n  for (int i=0; i < vm[\"disc\"].as<d_vec>().size(); ++i) {\n    cout << parameters->getDiscount(i) << \", \";\n  }\n  cout << endl;\n  cout << \"Concentration: \" << parameters->getConcentration(1., -1, 0) << endl;\n\n\n  return mean(losses);\n}\n\n\nint main(int argc, char* argv[]) {\n  const double sm_disc[] = {0.05, 0.7, 0.8, 0.82, 0.84, 0.88, 0.91, 0.92, 0.93, 0.94, 0.95};\n  //const double sm_disc[] = {.62, .69, .74, .80, .95};\n  d_vec default_discounts;\n  default_discounts.assign(sm_disc,&sm_disc[11]);\n  // Declare the supported options.\n  po::options_description generic(\"Generic options\");\n  po::options_description dumping(\"Dumping options\");\n  po::options_description hidden(\"Hidden options\");\n  generic.add_options()\n    (\"help\", \"produce help message\")\n    (\"debug,D\", \"Print debugging output\")\n    (\"joint,J\", \"Compute joint distribution\")\n    (\"sum,s\", \"Check that probabilities sum to one\")\n    (\"print-tree\", \"Print the context tree to the screen\")\n    (\"fragment\", po::value<int>()->default_value(1), \"1: nofrag; 2: frag; 3:below\")\n    (\"read-int32\", \"Read input data as 32 bit integers\")\n    (\"test-file\", po::value<string>(), \"Test file\")\n    (\"save-serialized-nodes\", po::value<string>(), \"File to contain serialized nodes\")\n    (\"load-serialized-nodes\", po::value<string>(), \"File to contain serialized nodes\")\n    (\"head\",po::value<int>()->default_value(0), \"If given, cuts input to this number of symbols\")\n    (\"mode\", po::value<int>()->default_value(1), \"1: particle filter, 2: no fragment, 3: fragment\")\n    (\"sampler\", po::value<int>()->default_value(1), \"1: add/remove, 2: direct gibbs; 3: remove-add\")\n    (\"restaurant\", po::value<int>()->default_value(1),\n     \"0:KN, 1: SimpleFull, 2: Histogram, 3: ReinstantiatingCompact, 4: StirlingCompact, 5: Switching, 6: PowerLaw, 7: Fractional\")\n    (\"parameters\", po::value<int>()->default_value(0),\n     \"0:Simple, 1: Gradient\")\n    (\"burn-in\",po::value<int>()->default_value(0), \"Number of Gibbs iterations for burn in\")\n    (\"samples,s\",po::value<int>()->default_value(1), \"Number of samples used for prediction\")\n    (\"lag,l\",po::value<int>()->default_value(0), \"Lag for deleted prediction (0=off)\")\n    (\"train-lag\",po::value<int>()->default_value(0), \"Lag for deleted training (0=off)\")\n    (\"num-types\", po::value<int>()->default_value(256), \"Number of types\") \n    (\"alpha,a\", po::value<double>()->default_value(5), \"Concentration parameter\") \n    (\"disc,d\", po::value<d_vec>()->default_value(default_discounts,\"...\"), \"Discount parameter(s)\") \n    ;\n\n  dumping.add_options()\n    (\"dump-losses\", \"Dump per-symbol losses into a file named losses\")\n    (\"prefix\",po::value<std::string>()->default_value(\"\"), \"Prefix for output files\")\n    ;\n\n  hidden.add_options()\n    (\"input-file\", po::value<string>(), \"input file\")\n    ;\n\n  po::options_description cmdline_options;\n  cmdline_options.add(generic).add(hidden).add(dumping);\n\n  po::options_description visible_options;\n  visible_options.add(generic).add(dumping);\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(argc, argv).\n      options(cmdline_options).positional(p).run(), vm);\n  po::notify(vm);\n\n  string usage = \"Usage: score_file [OPTIONS]... FILENAME\\n\";\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\")) {\n    cout << usage << visible_options << \"\\n\";\n    exit(1);\n  }\n\n  num_types = vm[\"num-types\"].as<int>();\n\n  init_rng();\n\n  if (vm.count(\"input-file\")) {\n    double score;\n    score = score_file(vm);\n    cout << \"log-loss: \" << score << endl;\n    //exit(0); // force exit to avoid expensive cleanup\n  }\n  free_rng();\n}\n", "meta": {"hexsha": "1b1177709e1fb118b67df4da6b303cbce024fd9b", "size": 13226, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/utils/score_file.cc", "max_stars_repo_name": "jgasthaus/libPLUMP", "max_stars_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T03:50:37.000Z", "max_issues_repo_path": "src/utils/score_file.cc", "max_issues_repo_name": "jgasthaus/libPLUMP", "max_issues_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "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/score_file.cc", "max_forks_repo_name": "jgasthaus/libPLUMP", "max_forks_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-17T19:19:37.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-20T00:56:17.000Z", "avg_line_length": 36.8412256267, "max_line_length": 162, "alphanum_fraction": 0.6301980947, "num_tokens": 3439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.19338474303921943}}
{"text": "#include <iostream>\n#include <string>\n#include <ncurses.h>\n#include <vector>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <algorithm>\n#include <iterator>\n#include <boost/variant.hpp>\n#include \"visitors.h\"\n#include \"player.h\"\n#include \"enemy.h\"\n#include \"color.h\"\n#include \"map.h\"\n#include \"equipmenttype.h\"\n#include \"weaponInstance.h\"\n\nextern bool checkIfAttackHit(double acc, double eva);\n\nPlayer::Player(std::string p_class)\n{\n    for (int j = 0; j < 5; j++) {\n        Armor defArm;\n        equipped_armor.push_back(defArm);\n    }\n    this->vision = 6;\n    this->primary_weapon = new Sword(1);\n    this->secondary_weapon = new Dagger(1);\n\n    this->inventory.food_capacity = 5;\n    this->inventory.weapon_capacity = 3;\n    this->inventory.armor_capacity = 3;\n    this->inventory.food_count = 0;\n    this->inventory.armor_count = 0;\n    this->inventory.weapon_count = 0;\n\n    this->race = p_class;\n    std::string element;\n    std::ifstream infile(\"playerAttributes.csv\");\n    while(infile.good()) {\n        getline(infile, element, ',');\n        if (element == p_class) {\n            getline(infile, element, ',');\n            this->accuracy = std::atof(element.c_str()); \n            getline(infile, element, ',');\n            this->speed = std::atoi(element.c_str());\n            getline(infile, element, ',');\n            this->base_damage = std::atoi(element.c_str());\n            getline(infile, element, ',');\n            this->allowed_moves = std::atoi(element.c_str());\n            getline(infile, element, ',');\n            this->base_evasion = std::atof(element.c_str());\n            getline(infile, element, ',');\n            this->base_protection = std::atof(element.c_str());\n            getline(infile, element, ',');\n            this->base_total_health = std::atoi(element.c_str());\n            getline(infile, element, ',');\n            this->level_up_multiplier_health = std::atof(element.c_str());\n            getline(infile, element, ',');\n            this->level_up_multiplier_damage = std::atof(element.c_str());\n            getline(infile, element, '\\n');\n            this->crit_chance = std::atof(element.c_str());\n            infile.close();\n            break;\n        }\n        else {\n            getline(infile, element);\n        }\n    }\n\n    //placeholder. For debugging only\n    this->base_total_health = 5000;\n    \n    //These attributes are constant for all player types\n    this->current_total_health = this->base_total_health;\n    this->current_health = this->base_total_health;\n    this->used_moves = 0;\n    this->level_up_multiplier_xp = 1.25;\n    this->current_xp_cap = 150;\n    this->level = 1;\n    this->level_points = 0;\n    this->current_xp = 0;\n    this->passive_health_regen_counter = 0;\n    this->passive_health_regen_trigger = 50;\n    this->passive_health_regen_amount = 0;\n    this->inventory_index = 0;\n    this->max_inventory_index = 2;\n    this->souls_cap = 25;\n    this->souls = 0;\n    this->souls_multiplier = 1.15;\n    this->current_evasion = this->base_evasion;\n    this->current_protection = this->base_protection;\n    this->in_combat = false;\n    this->is_stunned = false;\n    this->bleed_damage = 0;\n    this->bleed_rounds = 0;\n}\n\nint getLootIndex(std::vector<Enemy::Loot> *loot, long loot_id) \n{\n    for (size_t i = 0; i < loot->size(); i++) {\n        if (loot->at(i).l_id == loot_id) {\n            return i;\n        }\n    }\n    return -1;\n}\n\n/*\n*foodEvents()\n*   Goes through the list of the food items that the player has eaten,\n*   and for each item checks if the item should trigger health gain (and if so, gives health to player),\n*   increments the given counters, and deletes the food item if it should expire.\n*/\nvoid Player::foodEvents() \n{\n    bool deleted;\n    std::vector<Food>::iterator food_iter;\n    for (food_iter = this->active_food.begin(); food_iter != this->active_food.end();) {\n        deleted = false;\n        food_iter->trigger_count++;\n        this->current_health += food_iter->health_gain_per_trigger;\n        if (food_iter->trigger_count == food_iter->total_triggers) {\n            food_iter = this->active_food.erase(food_iter);\n            deleted = true;\n        }\n        if (!deleted) {\n            food_iter++;\n        }\n    }\n}\n\n/*\n*eatFood(Food, WINDOW*)\n*   Gets passed a food item, adds it to the player's active_food vector, \n*   and gives initial health boost to player.\n*/\nvoid Player::eatFood(Food *food_item, WINDOW *player_status_window) \n{\n    this->active_food.push_back(*food_item);\n    this->current_health += food_item->initial_health_gain;\n    if (this->current_health > this->current_total_health) {\n        this->current_health = this->current_total_health;\n    }\n    this->printStatus(player_status_window);\n    this->inventory.food_count--;\n    return;\n}\n\nvoid Player::setPrimaryWeapon(Weapon weapon) \n{\n    *this->primary_weapon = weapon;\n}\n\nvoid Player::setSecondaryWeapon(Weapon weapon)\n{\n    *this->secondary_weapon = weapon;\n}\n\nvoid Player::setBleedDamage(int damage, int rounds) \n{\n    this->bleed_damage += damage;\n    this->bleed_rounds += rounds;\n}\n\nvoid Player::takeDamageOverTime(WINDOW *alert_window)\n{\n    if (this->bleed_rounds > 0) {\n        wattron(alert_window, Color::RedBlack);\n        wprintw(alert_window, \"You bleed for %d damage.\\n\", this->bleed_damage);\n        wattroff(alert_window, Color::RedBlack);\n        wrefresh(alert_window);\n        this->bleed_rounds--;\n        this->current_health -= this->bleed_damage;\n    }\n    else {\n        this->bleed_damage = 0;\n    }\n}\n\n/*\n*printInventory(WINDOW*, int, WINDOW*)\n*   Prints player's inventory in a categorical manner according to equipment.\n*   Simply goes down the corresponding list (Weapon, Food, Armor, etc), prints a counter\n*   and the item's name and description\n*/\nvoid Player::printInventory(WINDOW *inv_window, int index, WINDOW *item_description_window) \n{\n    wclear(inv_window);\n    wclear(item_description_window);\n    int counter = 0;\n    std::vector<boost::variant<Weapon, Food, Armor>> equipment;\n    std::vector<Equipment>::iterator iter;\n    boost::variant<Weapon, Food, Armor> current_equipped;\n\n    wattron(inv_window, A_BOLD);\n\n    /*\n    *There's a bit of code repetition here that I'd like to reduce later\n    */\n    switch(this->inventory_index) {\n        case static_cast<int>(EquipmentType::Weapon):\n            equipment.insert(equipment.end(), this->inventory.weapons.begin(), this->inventory.weapons.end());\n            wprintw(inv_window, \"WEAPONS [%d/%d] ->\\n\", this->inventory.weapon_count, this->inventory.weapon_capacity);\n            wattrset(inv_window, A_NORMAL);\n            if (equipment.size() == 0) {\n                wprintw(inv_window, \"<EMPTY>\");\n                wrefresh(inv_window);\n                return;\n            }\n            if (boost::get<Weapon>(equipment.at(index)).is_primary) {\n                current_equipped = *(this->primary_weapon);\n            }\n            else {\n                current_equipped = *(this->secondary_weapon);\n            }\n            break;\n        case static_cast<int>(EquipmentType::Food):\n            equipment.insert(equipment.end(), this->inventory.food.begin(), this->inventory.food.end());\n            wprintw(inv_window, \"<- FOOD [%d/%d]\\n\", this->inventory.food_count, this->inventory.food_capacity);\n            wattrset(inv_window, A_NORMAL);\n            if (equipment.size() == 0) {\n                wprintw(inv_window, \"<EMPTY>\");\n                wrefresh(inv_window);\n                return;\n            }\n            current_equipped = *(new Food());\n            break;\n        case static_cast<int>(EquipmentType::Armor):\n            equipment.insert(equipment.end(), this->inventory.armor.begin(), this->inventory.armor.end());\n            wprintw(inv_window, \"<- ARMOR [%d/%d] ->\\n\", this->inventory.armor_count, this->inventory.armor_capacity);\n            wattrset(inv_window, A_NORMAL);\n            if (equipment.size() == 0) {\n                wprintw(inv_window, \"<EMPTY>\");\n                wrefresh(inv_window);\n                return;\n            }\n            if (this->inventory.armor.size() > 0) {\n                current_equipped = equipped_armor.at(static_cast<int>(this->inventory.armor.at(index).armor_type));\n            }\n            break;\n        default:\n            return;\n    }\n    \n    for (size_t i = 0; i < equipment.size(); i++) {\n        if (counter == index) {\n            wattron(inv_window, A_STANDOUT);\n            boost::apply_visitor(Visitors::compare_to(current_equipped, item_description_window), equipment.at(i));\n        }\n        boost::apply_visitor(Visitors::output_list_name(counter, inv_window), equipment.at(i));\n        if (counter == index) {\n            wattroff(inv_window, A_STANDOUT);\n        }\n        counter++;\n    }\n    \n    wrefresh(inv_window);\n}\n\n/*\n*findValidLootID(std::vector<Enemy::Loot>)\n*   Returns a valid (unused at time of creation) loot id for use when the player drops \n*   an item and it is added to the loot table.\n*/\nint findValidLootID(std::vector<Enemy::Loot> loot)\n{\n    std::vector<int> used_ids;\n    int new_id = 0;\n    for (size_t i = 0; i < loot.size(); i++) {\n        used_ids.push_back(loot.at(i).l_id);\n    }\n    while(true) {\n        if (!(std::find(used_ids.begin(), used_ids.end(), new_id) != used_ids.end())) {\n            return new_id;\n        }\n        new_id++;\n    }\n}\n\n/*\n*manageInventory(WINDOW*, WINDOW*, WINDOW*, std::vector<Enemy::Loot>*)\n*   Main inventory management system of player.\n*   Player can switch between windows for each type of equipment (Armor, Weapon, Food, ...) using left and right arrow keys\n*   <ENTER>: allows player to equip Weapon/Armor or eat Food\n*   <d>: allows player to drop an item, will be put into world as a standard loot object \n*   <KEY_UP>/<KEY_DOWN>: Allows player to navigate menus\n*/\nvoid Player::manageInventory(WINDOW *inv_window, WINDOW *player_status_window, WINDOW *alert_win, WINDOW *item_description_window, std::vector<Enemy::Loot> *loot)\n{\n    int ch;\n    int index = 0;\n    Weapon wtemp;\n    Armor atemp;\n    Enemy::Loot loot_obj;\n    bool valid_drop = false;\n    std::vector<Weapon> *weapon_vect;\n    //WINDOW *item_description_window = newwin(30, 30, 22, 60);\n    while (true) {\n        //temp = NULL;\n        printInventory(inv_window, index, item_description_window);\n        ch = getch();\n        switch(ch) {\n            //player movement\n            case KEY_UP:\n                if (index > 0) {\n                    index--;\n                }\n                break;\n            case KEY_DOWN:\n                if (this->inventory_index == static_cast<int>(EquipmentType::Weapon) && index < this->inventory.weapons.size() - 1) {\n                    index++;\n                }\n                else if (this->inventory_index == static_cast<int>(EquipmentType::Food) && index < this->inventory.food.size() - 1) {\n                    index++;\n                }\n                else if (this->inventory_index == static_cast<int>(EquipmentType::Armor) && index < this->inventory.armor.size() - 1) {\n                    index++;\n                }\n                break;\n            case KEY_RIGHT:\n                if (this->inventory_index < this->max_inventory_index) {\n                    this->inventory_index++;\n                    index = 0;\n                    wclear(item_description_window);\n                    wrefresh(item_description_window);\n                }\n                break;\n            case KEY_LEFT:\n                if (this->inventory_index > 0) {\n                    this->inventory_index--;\n                    index = 0;\n                    wclear(item_description_window);\n                    wrefresh(item_description_window);\n                }\n                break;\n            case KEY_ENTER: case '\\n':\n                if (this->inventory_index == static_cast<int>(EquipmentType::Weapon) && this->inventory.weapons.size() > 0) {\n                    weapon_vect = &this->inventory.weapons;\n                    wtemp = weapon_vect->at(index);\n\n                    if (wtemp.type == \"P\") {\n                        weapon_vect->at(index) = *this->primary_weapon;\n                        this->setPrimaryWeapon(wtemp);\n                    }\n                    else {\n                        weapon_vect->at(index) = *this->secondary_weapon;\n                        this->setSecondaryWeapon(wtemp);\n                    }\n                    \n                    wprintw(alert_win, \"Equipped %s\\n\", (wtemp.name).c_str());\n                    wrefresh(alert_win);\n                    index = 0;\n                }\n                else if (this->inventory_index == static_cast<int>(EquipmentType::Food) && this->inventory.food.size() > 0) {\n                    this->eatFood(&this->inventory.food.at(index), player_status_window);\n                    this->inventory.food.erase(this->inventory.food.begin() + index);\n                    index = 0;\n                }\n                else if (this->inventory_index == static_cast<int>(EquipmentType::Armor) && this->inventory.armor.size() > 0) {\n                    atemp = this->inventory.armor.at(index);\n                    this->inventory.armor.erase(this->inventory.armor.begin() + index);\n                    if (equipped_armor.at(static_cast<int>(atemp.armor_type)).armor_type != ArmorType::Default) {\n                        this->inventory.armor.push_back(equipped_armor.at(static_cast<int>(atemp.armor_type)));\n                    }\n                    else {\n                        this->inventory.armor_count--;\n                    }\n                    equipped_armor.at(static_cast<int>(atemp.armor_type)) = atemp;\n                    wprintw(alert_win, \"Equipped %s\\n\", (atemp.name).c_str());\n                    wrefresh(alert_win);  \n                    wclear(item_description_window);\n                    wrefresh(item_description_window); \n                    index = 0; \n                }\n                break;\n            case 'd':\n                loot_obj.food.clear();\n                loot_obj.weapons.clear();\n                loot_obj.armor.clear();\n\n                /*\n                TODO: reduce repetition here with a boost static visitor\n                */\n                if (this->inventory_index == static_cast<int>(EquipmentType::Weapon) && this->inventory.weapons.size() > 0) {\n                    loot_obj.weapons.push_back(this->inventory.weapons.at(index));\n                    this->inventory.weapons.erase(this->inventory.weapons.begin() + index);\n                    this->inventory.weapon_count--;\n                    valid_drop = true;\n                }\n                else if (this->inventory_index == static_cast<int>(EquipmentType::Food) && this->inventory.food.size() > 0) {\n                    loot_obj.food.push_back(this->inventory.food.at(index));\n                    this->inventory.food.erase(this->inventory.food.begin() + index);   \n                    this->inventory.food_count--;\n                    valid_drop = true;\n                }\n                else if (this->inventory_index == static_cast<int>(EquipmentType::Armor) && this->inventory.armor.size() > 0) {\n                    loot_obj.armor.push_back(this->inventory.armor.at(index));\n                    this->inventory.armor.erase(this->inventory.armor.begin() + index); \n                    this->inventory.armor_count--;\n                    valid_drop = true;\n                }\n\n                if (valid_drop) {\n                    loot_obj.l_id = findValidLootID(*loot);\n                    loot_obj.row = this->row;\n                    loot_obj.col = this->col;\n                    loot_obj.dropped_by = this->race;\n                    loot_obj.despawn_counter = 0;\n                    loot->push_back(loot_obj);\n                    index = 0;\n                    valid_drop = false;\n                }\n                break;\n            case 'e': case 'l': case 'a':\n                wclear(inv_window);\n                wclear(item_description_window);\n                wrefresh(inv_window);\n                wrefresh(item_description_window);\n                return;\n            default:\n                break;\n        }\n    }\n    wclear(item_description_window);\n    wrefresh(item_description_window);\n}\n\nvoid Player::printEquipped(WINDOW *inv_window, WINDOW *item_description_window, int index)\n{\n    wclear(inv_window);\n    wclear(item_description_window);\n    std::string armor_names[] = {\"[BOOT]\", \"[LEGS]\", \"[CHST]\", \"[GLVS]\", \"[HELM]\"};\n    wattron(inv_window, A_BOLD);\n    wprintw(inv_window, \"EQUIPPED ARMOR\\n\");\n    wattroff(inv_window, A_BOLD);\n\n    for (size_t i = 0; i < this->equipped_armor.size(); i++) {\n        if (i == index) {\n            wattron(inv_window, A_STANDOUT);\n            this->equipped_armor.at(i).printDescription(item_description_window);\n        }\n        wprintw(inv_window, \" %s %s\\n\", armor_names[i].c_str(), this->equipped_armor.at(i).name.c_str());\n        wattroff(inv_window, A_STANDOUT);\n    }\n    double armor_score = getArmorScore();\n    wprintw(inv_window, \" TOTAL PROT: %.0f%%\\n\", armor_score * 100);\n\n    wattron(inv_window, A_BOLD);\n    wprintw(inv_window, \"\\nEQUIPPED WEAPONS\\n\");\n    wattroff(inv_window, A_BOLD);\n\n    if (index == 5) {\n        wattron(inv_window, A_STANDOUT);\n        wprintw(inv_window, \" [PRIM] %s\\n\", (this->primary_weapon->name).c_str());\n        this->primary_weapon->printDescription(item_description_window);\n        wattroff(inv_window, A_STANDOUT);\n    }\n    else {\n        wprintw(inv_window, \" [PRIM] %s\\n\", (this->primary_weapon->name).c_str());\n    }\n\n    if (index == 6) {\n        wattron(inv_window, A_STANDOUT);\n        wprintw(inv_window, \" [SCND] %s\\n\", (this->secondary_weapon->name).c_str());\n        this->secondary_weapon->printDescription(item_description_window);\n        wattroff(inv_window, A_STANDOUT);\n    }\n    else {\n        wprintw(inv_window, \" [SCND] %s\\n\", (this->secondary_weapon->name).c_str());\n    }\n    \n    wrefresh(inv_window);\n    wrefresh(item_description_window);\n}\n\nvoid Player::unequipArmor(WINDOW *alert_win, int index)\n{\n    if (this->equipped_armor.at(index).name != \"<NONE>\") {\n        if ((this->inventory.armor_count < this->inventory.armor_capacity)) {\n            Armor defaultArmor;\n            wprintw(alert_win, \"Unequipped %s.\\n\", this->equipped_armor.at(index).name.c_str());\n            wrefresh(alert_win);\n            this->inventory.armor.push_back(this->equipped_armor.at(index));\n            this->equipped_armor.at(index) = defaultArmor;\n            this->inventory.armor_count++;\n        }\n        else {\n            wprintw(alert_win, \"No room in inventory for %s.\\n\", this->equipped_armor.at(index).name.c_str());\n            wrefresh(alert_win);\n        }\n    }\n}\n\n/*\n*manageArmor(WINDOW*, WINDOW*, WINDOW*)\n*When 'a' is pressed in the main game loop, currently equipped armor is displayed using this function.\n*The player can navigate the equipped armor and unequip it and check statistics.\n*/\nvoid Player::manageArmor(WINDOW *inv_window, WINDOW *item_description_window, WINDOW *alert_win)\n{\n    int ch;\n    int index = 0;\n    int n_weapons = 2;\n\n    while (true) {\n        printEquipped(inv_window, item_description_window, index);\n        ch = getch();\n        switch(ch) {\n            case KEY_UP:\n                if (index > 0) {\n                    index--;\n                }\n                break;\n            case KEY_DOWN:\n                if (index < (this->equipped_armor.size() - 1) + n_weapons) {\n                    index++;\n                }\n                break;\n            case KEY_ENTER: case '\\n':\n                if (!(index > (this->equipped_armor.size() - 1))) {\n                    this->unequipArmor(alert_win, index); \n                }\n                break;\n            case 'a': case 'e':\n                wclear(inv_window);\n                wclear(item_description_window);\n                wrefresh(inv_window);\n                wrefresh(item_description_window);\n                return;\n            default:\n                break;\n        }\n    }\n}\n\nvoid Player::gainSouls(int souls_to_gain, WINDOW *alert_win)\n{\n    this->souls += souls_to_gain;\n    if (this->souls > souls_cap) {\n        this->souls = souls_cap;\n    }\n    wattrset(alert_win, A_NORMAL);\n    wattron(alert_win, Color::GreenBlack);\n    wprintw(alert_win, \"Acquired %d souls.\\n\", souls_to_gain);\n    wrefresh(alert_win);\n    wattroff(alert_win, Color::GreenBlack);\n}\n\nbool Player::pickupLoot(Weapon weapon_item) \n{\n    if (this->inventory.weapon_count < this->inventory.weapon_capacity) {\n        this->inventory.weapons.push_back(weapon_item);\n        this->inventory.weapon_count++;\n        return true;\n    }\n    return false;\n}\n\nbool Player::pickupLoot(Food food_item) \n{\n    if (this->inventory.food_count < this->inventory.food_capacity) {\n        this->inventory.food.push_back(food_item);\n        this->inventory.food_count++;\n        return true;\n    }\n    return false;\n}\n\nbool Player::pickupLoot(Armor armor_item) \n{\n    if (this->inventory.armor_count < this->inventory.armor_capacity) {\n        this->inventory.armor.push_back(armor_item);\n        this->inventory.armor_count++;\n        return true;\n    }\n    return false;\n}\n\ndouble Player::getArmorScore()\n{\n    double score = 0;\n    for (Armor a : equipped_armor) {\n        score += a.protection;\n    }\n    return score;\n}\n\nvoid Player::levelUp(WINDOW *alert_win)\n{\n    this->current_xp -= this->current_xp_cap;\n    this->level++;\n    this->current_xp_cap *= this->level_up_multiplier_xp;\n\n    wattroff(alert_win, Color::RedBlack);\n    wattron(alert_win, Color::CyanBlack);\n    wprintw(alert_win, \"Level up! %d -> %d\\n\", this->level - 1, this->level);\n    wrefresh(alert_win);\n    wattroff(alert_win, Color::CyanBlack);\n    wattron(alert_win, Color::RedBlack);\n    \n    this->base_total_health = std::ceil(this->base_total_health * this->level_up_multiplier_health);\n    this->base_damage = std::ceil(this->base_damage * this->level_up_multiplier_damage);\n    this->current_total_health = this->base_total_health;\n    this->level_points++;\n}\n\nvoid Player::gainExp(int xp, WINDOW *alert_win) \n{\n    wattrset(alert_win, A_NORMAL);\n    wattron(alert_win, Color::GreenBlack);\n    wprintw(alert_win, \"You gained %d XP.\\n\", xp);\n    wattroff(alert_win, Color::GreenBlack);\n    this->current_xp += xp;\n    if (this->current_xp >= this->current_xp_cap) {\n        this->levelUp(alert_win);\n    }\n}\n\nvoid Player::setPosition(int row, int col)\n{\n    this->row = row;\n    this->col = col;\n}\n\nvoid Player::setInCombatAbsolute(bool toggle)\n{\n    this->in_combat = toggle;\n}\n\nvoid Player::setInCombatCheck(std::vector<Enemy> enemies)\n{\n    for (Enemy e : enemies){\n        if (e.isInCombat()) {\n            this->in_combat = true;\n            return;\n        }\n    }\n    this->in_combat = false;\n}\n\nbool Player::isInCombat()\n{\n    return this->in_combat;\n}\n\n//Will print things like player gold count, health, status, and \n//directional indicators to next obelisk\nvoid Player::printStatus(WINDOW *player_window)\n{\n    wmove(player_window, 0, 0);\n    wclrtoeol(player_window);\n    double ratio = (double)this->current_health / (double)this->current_total_health;\n\n    if (ratio > 0.75) {\n        wattron(player_window, Color::GreenBlack);\n    }\n    else if (ratio > 0.30) {\n        wattron(player_window, Color::YellowBlack);\n    }\n    else {\n        wattron(player_window, Color::RedBlack);\n    }\n\n    wprintw(player_window, \"Health: \");\n    //If health is below a certain threshold display it in red\n    wprintw(player_window, \"%d/%d\\n\", this->current_health, this->current_total_health);\n    wattrset(player_window, A_NORMAL);\n\n    wprintw(player_window, \"Level: %d        XP: %d/%d\\n\", this->level, this->current_xp, this->current_xp_cap);\n    if (this->souls == this->souls_cap) {\n        wattron(player_window, Color::YellowBlack);\n    }\n    wprintw(player_window, \"SOULS: %d/%d\", this->souls, this->souls_cap);\n    wattroff(player_window, Color::YellowBlack);\n    wrefresh(player_window);\n}\n\nint Player::computeAttackPower(Weapon weapon, WINDOW *alert_window) {\n    Attack w_attack = weapon.attack;\n    int damage = (weapon.damage + this->base_damage) * w_attack.damage_mod;\n    int damage_range = weapon.damage_range;\n    double crit_chance = (weapon.crit_chance + this->crit_chance) * w_attack.crit_chance_mod;\n    double crit_roll = ((double) rand() / RAND_MAX);\n    \n    if (damage_range != 0) {\n        damage += (rand() % damage_range);\n    }\n    if (this->souls == this->souls_cap) {\n        damage *= this->souls_multiplier;\n    }\n    if (crit_chance >= crit_roll) {\n        damage *= 2;\n        wprintw(alert_window, \"CRITICAL HIT\\n\");\n        wrefresh(alert_window);\n    }\n    return (int)damage;\n}\n\n/*\n*Attacks enemy. Returns true if enemy is killed, false otherwise\n*\n*/\nbool Player::attack(Enemy *enemy, bool usePrimary, WINDOW *alert_window)\n{\n    Weapon player_weapon;\n    if (usePrimary) {\n        player_weapon = *(this->primary_weapon);\n    }\n    else {\n        player_weapon = *(this->secondary_weapon);\n    }\n    this->takeDamageOverTime(alert_window);\n    if (this->current_health <= 0 || this->is_stunned) {\n        if (this->is_stunned) {\n            this->is_stunned = false;\n        }\n        return false;\n    }\n\n    bool attack_hit = checkIfAttackHit((player_weapon.accuracy + this->accuracy) * player_weapon.attack.accuracy_mod, enemy->current_evasion);\n    \n    wattron(alert_window, Color::MagentaBlack);\n    if (attack_hit) {\n        int dmg = this->computeAttackPower(player_weapon, alert_window) * (1 - enemy->current_protection);\n        double bleed_roll = ((double) rand() / RAND_MAX);\n        double stun_roll = ((double) rand() / RAND_MAX);\n        //Roll for bleed\n        if (bleed_roll <= (player_weapon.bleed_chance * player_weapon.attack.bleed_chance_mod) - enemy->bleed_resist) {\n            wprintw(alert_window, \"%s is bleeding.\\n\", (enemy->name).c_str());\n            enemy->setBleedDamage(player_weapon.attack.bleed_damage, player_weapon.attack.bleed_rounds);\n        }\n        //Roll for stun\n        if (stun_roll <= (player_weapon.stun_chance * player_weapon.attack.stun_chance_mod)) {\n            wattroff(alert_window, Color::MagentaBlack);\n            wattron(alert_window, Color::YellowBlack);\n            wprintw(alert_window, \"%s is stunned.\\n\", (enemy->name).c_str());\n            wattroff(alert_window, Color::YellowBlack);\n            wattron(alert_window, Color::MagentaBlack);\n            enemy->is_stunned = true;\n        }\n        enemy->current_health -= dmg;\n        wprintw(alert_window, \"You hit %s for %d damage.\\n\", (enemy->name).c_str(), dmg);\n        wrefresh(alert_window);\n        wattroff(alert_window, Color::MagentaBlack);\n    }\n    else {\n        wprintw(alert_window, \"You miss %s.\\n\", (enemy->name).c_str());\n        wrefresh(alert_window);\n        wattroff(alert_window, Color::MagentaBlack);\n    }\n    return enemy->current_health <= 0;\n}\n\n//Only passively regenerate on active moves (no skips)\n//This promotes active gameplay\n//Also only do if health is not capped\nvoid Player::passiveHealthRegeneration(WINDOW *player_window)\n{\n    if (this->current_health < this->current_total_health) {\n        this->passive_health_regen_counter++;\n        if (this->passive_health_regen_counter == this->passive_health_regen_trigger) {\n            this->passive_health_regen_counter = 0;\n            this->current_health += this->passive_health_regen_amount;\n        }\n        this->printStatus(player_window);\n    }\n}\n\n//Returns true if the movement was valid, false otherwise\nbool Player::moveSpace(int direction, Map map, WINDOW *player_window, std::vector<Enemy> enemies)\n{\n    int row_mod = 0;\n    int col_mod = 0;\n    switch (direction) {\n        case KEY_UP:\n            row_mod = -1;\n            break;\n        case KEY_DOWN:\n            row_mod = 1;\n            break;\n        case KEY_LEFT:\n            col_mod = -1;\n            break;\n        case KEY_RIGHT:\n            col_mod = 1;\n            break;\n        default:\n            break;\n    }\n    \n    if (map.isValidMove(this->row + row_mod, this->col + col_mod, enemies)) {\n        this->row += row_mod;\n        this->col += col_mod;\n        if (this->passive_health_regen_amount > 0) {\n            passiveHealthRegeneration(player_window);  \n        }\n        return true; \n    }\n    return false;\n    \n}\n\n", "meta": {"hexsha": "fcb0369c8a70941d2343b8e08004bb05f9deee51", "size": 28381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/player.cpp", "max_stars_repo_name": "evancasey1/Aurora", "max_stars_repo_head_hexsha": "5342f143ee25643fde610bdf26f275a920300741", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-30T17:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-30T17:53:26.000Z", "max_issues_repo_path": "src/player.cpp", "max_issues_repo_name": "evancasey1/Aurora", "max_issues_repo_head_hexsha": "5342f143ee25643fde610bdf26f275a920300741", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-01-21T00:10:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-12T12:46:15.000Z", "max_forks_repo_path": "src/player.cpp", "max_forks_repo_name": "evancasey1/Aurora", "max_forks_repo_head_hexsha": "5342f143ee25643fde610bdf26f275a920300741", "max_forks_repo_licenses": ["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.2559006211, "max_line_length": 162, "alphanum_fraction": 0.5889503541, "num_tokens": 6705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19334202598069933}}
{"text": "#include \"kernel.h\"\n#include \"structure.h\"\n#include \"y_grad.h\"\n#include \"sparse_gp.h\"\n#include \"b2.h\"\n#include \"b2_simple.h\"\n#include \"b2_norm.h\"\n#include \"b3.h\"\n#include \"two_body.h\"\n#include \"three_body.h\"\n#include \"three_body_wide.h\"\n#include \"four_body.h\"\n#include \"squared_exponential.h\"\n#include \"normalized_dot_product.h\"\n#include \"norm_dot_icm.h\"\n\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace py = pybind11;\n\nPYBIND11_MODULE(_C_flare, m) {\n  // Structure\n  py::class_<Structure>(m, \"Structure\")\n      .def(py::init<const Eigen::MatrixXd &, const std::vector<int> &,\n                    const Eigen::MatrixXd &>())\n      .def(py::init<const Eigen::MatrixXd &, const std::vector<int> &,\n                    const Eigen::MatrixXd &, double,\n                    std::vector<Descriptor *>>())\n      .def_readwrite(\"noa\", &Structure::noa)\n      .def_readwrite(\"cell\", &Structure::cell)\n      .def_readwrite(\"species\", &Structure::species)\n      .def_readwrite(\"positions\", &Structure::positions)\n      .def_readwrite(\"cell_transpose\", &Structure::cell_transpose)\n      .def_readwrite(\"wrapped_positions\", &Structure::wrapped_positions)\n      .def_readwrite(\"volume\", &Structure::volume)\n      .def_readwrite(\"energy\", &Structure::energy)\n      .def_readwrite(\"forces\", &Structure::forces)\n      .def_readwrite(\"stresses\", &Structure::stresses)\n      .def_readwrite(\"mean_efs\", &Structure::mean_efs)\n      .def_readwrite(\"variance_efs\", &Structure::variance_efs)\n      .def_readwrite(\"local_uncertainties\", &Structure::local_uncertainties)\n      .def_readonly(\"descriptors\", &Structure::descriptors)\n      .def_readonly(\"descriptor_calculators\",\n                    &Structure::descriptor_calculators)\n      .def(\"compute_descriptors\", &Structure::compute_descriptors)\n      .def(\"wrap_positions\", &Structure::wrap_positions)\n      .def_static(\"to_json\", &Structure::to_json)\n      .def_static(\"from_json\", &Structure::from_json);\n\n  // Descriptor values\n  py::class_<DescriptorValues>(m, \"DescriptorValues\")\n      .def(py::init<>())\n      .def_readwrite(\"n_descriptors\", &DescriptorValues::n_descriptors)\n      .def_readwrite(\"n_types\", &DescriptorValues::n_types)\n      .def_readwrite(\"n_atoms\", &DescriptorValues::n_atoms)\n      .def_readwrite(\"volume\", &DescriptorValues::volume)\n      .def_readwrite(\"descriptors\", &DescriptorValues::descriptors)\n      .def_readwrite(\"descriptor_force_dervs\",\n                     &DescriptorValues::descriptor_force_dervs)\n      .def_readwrite(\"neighbor_coordinates\",\n                     &DescriptorValues::neighbor_coordinates)\n      .def_readwrite(\"descriptor_norms\", &DescriptorValues::descriptor_norms)\n      .def_readwrite(\"descriptor_force_dots\",\n                     &DescriptorValues::descriptor_force_dots)\n      .def_readwrite(\"cutoff_values\", &DescriptorValues::cutoff_values)\n      .def_readwrite(\"cutoff_dervs\", &DescriptorValues::cutoff_dervs)\n      .def_readwrite(\"neighbor_counts\", &DescriptorValues::neighbor_counts)\n      .def_readwrite(\"cumulative_neighbor_counts\",\n                     &DescriptorValues::cumulative_neighbor_counts)\n      .def_readwrite(\"atom_indices\", &DescriptorValues::atom_indices)\n      .def_readwrite(\"neighbor_indices\", &DescriptorValues::neighbor_indices)\n      .def_readwrite(\"n_clusters_by_type\",\n                     &DescriptorValues::n_clusters_by_type)\n      .def_readwrite(\"n_neighbors_by_type\",\n                     &DescriptorValues::n_neighbors_by_type);\n\n  py::class_<ClusterDescriptor>(m, \"ClusterDescriptor\")\n      .def_readonly(\"descriptors\", &ClusterDescriptor::descriptors);\n\n  // Descriptor calculators\n  py::class_<Descriptor>(m, \"Descriptor\")\n      .def(\"compute_struc\", &Descriptor::compute_struc);\n\n  py::class_<TwoBody, Descriptor>(m, \"TwoBody\")\n      .def(py::init<double, int, const std::string &,\n                    const std::vector<double> &>());\n\n  py::class_<ThreeBody, Descriptor>(m, \"ThreeBody\")\n      .def(py::init<double, int, const std::string &,\n                    const std::vector<double> &>());\n\n  py::class_<ThreeBodyWide, Descriptor>(m, \"ThreeBodyWide\")\n      .def(py::init<double, int, const std::string &,\n                    const std::vector<double> &>());\n\n  py::class_<FourBody, Descriptor>(m, \"FourBody\")\n      .def(py::init<double, int, const std::string &,\n                    const std::vector<double> &>());\n\n  py::class_<B2, Descriptor>(m, \"B2\")\n      .def(py::init<const std::string &, const std::string &,\n                    const std::vector<double> &, const std::vector<double> &,\n                    const std::vector<int> &>())\n      .def(py::init<const std::string &, const std::string &,\n                    const std::vector<double> &, const std::vector<double> &,\n                    const std::vector<int> &,\n                    const Eigen::MatrixXd &>())\n      .def_readonly(\"radial_basis\", &B2::radial_basis)\n      .def_readonly(\"cutoff_function\", &B2::cutoff_function)\n      .def_readonly(\"radial_hyps\", &B2::radial_hyps)\n      .def_readonly(\"cutoff_hyps\", &B2::cutoff_hyps)\n      .def_readonly(\"cutoffs\", &B2::cutoffs)\n      .def_readonly(\"descriptor_settings\", &B2::descriptor_settings);\n\n  py::class_<B2_Simple, Descriptor>(m, \"B2_Simple\")\n      .def(py::init<const std::string &, const std::string &,\n                    const std::vector<double> &, const std::vector<double> &,\n                    const std::vector<int> &>());\n\n  py::class_<B2_Norm, Descriptor>(m, \"B2_Norm\")\n      .def(py::init<const std::string &, const std::string &,\n                    const std::vector<double> &, const std::vector<double> &,\n                    const std::vector<int> &>());\n\n  py::class_<B3, Descriptor>(m, \"B3\")\n      .def(py::init<const std::string &, const std::string &,\n                    const std::vector<double> &, const std::vector<double> &,\n                    const std::vector<int> &>());\n\n  // Kernel functions\n  py::class_<Kernel>(m, \"Kernel\");\n\n  py::class_<NormalizedDotProduct, Kernel>(m, \"NormalizedDotProduct\")\n      .def(py::init<double, double>())\n      .def_readonly(\"sigma\", &NormalizedDotProduct::sigma)\n      .def_readonly(\"power\", &NormalizedDotProduct::power)\n      .def_readonly(\"kernel_hyperparameters\",\n                    &NormalizedDotProduct::kernel_hyperparameters)\n      .def(\"envs_envs\", &NormalizedDotProduct::envs_envs)\n      .def(\"envs_struc\", &NormalizedDotProduct::envs_struc)\n      .def(\"struc_struc\", &NormalizedDotProduct::struc_struc);\n\n  py::class_<NormalizedDotProduct_ICM, Kernel>(m, \"NormalizedDotProduct_ICM\")\n      .def(py::init<double, double, Eigen::MatrixXd>());\n\n  py::class_<SquaredExponential, Kernel>(m, \"SquaredExponential\")\n      .def(py::init<double, double>());\n\n  // Sparse GP DTC\n  py::class_<SparseGP>(m, \"SparseGP\")\n      .def(py::init<>())\n      .def(py::init<std::vector<Kernel *>, double, double, double>())\n      .def(\"set_hyperparameters\", &SparseGP::set_hyperparameters)\n      .def(\"predict_mean\", &SparseGP::predict_mean)\n      .def(\"predict_SOR\", &SparseGP::predict_SOR)\n      .def(\"predict_DTC\", &SparseGP::predict_DTC)\n      .def(\"predict_local_uncertainties\",\n           &SparseGP::predict_local_uncertainties)\n      .def(\"add_all_environments\", &SparseGP::add_all_environments)\n      .def(\"add_specific_environments\", &SparseGP::add_specific_environments)\n      .def(\"add_random_environments\", &SparseGP::add_random_environments)\n      .def(\"add_uncertain_environments\",\n           &SparseGP::add_uncertain_environments)\n      .def(\"add_training_structure\", &SparseGP::add_training_structure)\n      .def(\"update_matrices_QR\", &SparseGP::update_matrices_QR)\n      .def(\"compute_likelihood\", &SparseGP::compute_likelihood)\n      .def(\"compute_likelihood_stable\", &SparseGP::compute_likelihood_stable)\n      .def(\"compute_likelihood_gradient\",\n           &SparseGP::compute_likelihood_gradient)\n      .def(\"write_mapping_coefficients\", &SparseGP::write_mapping_coefficients)\n      .def_readonly(\"varmap_coeffs\", &SparseGP::varmap_coeffs) // for debugging and unit test\n      .def(\"compute_cluster_uncertainties\", &SparseGP::compute_cluster_uncertainties) // for debugging and unit test\n      .def(\"write_varmap_coefficients\", &SparseGP::write_varmap_coefficients)\n      .def_readwrite(\"Kuu_jitter\", &SparseGP::Kuu_jitter)\n      .def_readonly(\"complexity_penalty\", &SparseGP::complexity_penalty)\n      .def_readonly(\"data_fit\", &SparseGP::data_fit)\n      .def_readonly(\"constant_term\", &SparseGP::constant_term)\n      .def_readwrite(\"log_marginal_likelihood\",\n                     &SparseGP::log_marginal_likelihood)\n      .def_readwrite(\"likelihood_gradient\", &SparseGP::likelihood_gradient)\n      .def_readonly(\"kernels\", &SparseGP::kernels)\n      .def_readonly(\"hyperparameters\", &SparseGP::hyperparameters)\n      .def_readonly(\"training_structures\", &SparseGP::training_structures)\n      .def_readonly(\"sparse_indices\", &SparseGP::sparse_indices)\n      .def_readonly(\"sparse_descriptors\", &SparseGP::sparse_descriptors)\n      .def_readonly(\"n_energy_labels\", &SparseGP::n_energy_labels)\n      .def_readonly(\"n_force_labels\", &SparseGP::n_force_labels)\n      .def_readonly(\"n_stress_labels\", &SparseGP::n_stress_labels)\n      .def_readonly(\"force_noise\", &SparseGP::force_noise)\n      .def_readonly(\"energy_noise\", &SparseGP::energy_noise)\n      .def_readonly(\"stress_noise\", &SparseGP::stress_noise)\n      .def_readonly(\"noise_vector\", &SparseGP::noise_vector)\n      .def_readonly(\"Kuu\", &SparseGP::Kuu)\n      .def_readonly(\"Kuu_kernels\", &SparseGP::Kuu_kernels)\n      .def_readonly(\"Kuf\", &SparseGP::Kuf)\n      .def_readonly(\"Kuf_kernels\", &SparseGP::Kuf_kernels)\n      .def_readonly(\"alpha\", &SparseGP::alpha)\n      .def_readonly(\"Kuu_inverse\", &SparseGP::Kuu_inverse)\n      .def_readonly(\"Sigma\", &SparseGP::Sigma)\n      .def_readonly(\"n_sparse\", &SparseGP::n_sparse)\n      .def_readonly(\"n_labels\", &SparseGP::n_labels)\n      .def_readonly(\"y\", &SparseGP::y)\n      .def_static(\"to_json\", &SparseGP::to_json)\n      .def_static(\"from_json\", &SparseGP::from_json);\n}\n", "meta": {"hexsha": "63afcd375b7bb5a02f06b4276e05b38989bb33ee", "size": 10096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ace_binding.cpp", "max_stars_repo_name": "stevetorr/flare_pp", "max_stars_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "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/ace_binding.cpp", "max_issues_repo_name": "stevetorr/flare_pp", "max_issues_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "max_issues_repo_licenses": ["MIT"], "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/ace_binding.cpp", "max_forks_repo_name": "stevetorr/flare_pp", "max_forks_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "max_forks_repo_licenses": ["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.8483412322, "max_line_length": 116, "alphanum_fraction": 0.669770206, "num_tokens": 2586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.19334201339180346}}
{"text": "#include <iostream>\n#include <fstream>\n#include <ctime>\n\n#include <boost/program_options.hpp>\n\n#include <harp.hpp>\n\n#include \"specex_message.h\"\n#include \"specex_fits.h\"\n#include \"specex_psf.h\"\n#include \"specex_psf_io.h\"\n#include \"specex_gauss_hermite_psf.h\"\n#include \"specex_image_data.h\"\n#include \"specex_serialization.h\"\n#include \"specex_model_image.h\"\n\nusing namespace std;\nnamespace popts = boost::program_options;\n\nint main( int argc, char *argv[] ) {\n  \n  string input_psf_xml_filename=\"\";\n  string input_psf_fits_filename=\"\";\n  string output_image_fits_filename=\"\";\n  string output_psf_fits_filename=\"\";\n  \n  specex_set_verbose(true);\n  \n  popts::options_description desc ( \"Allowed Options\" );\n  desc.add_options()\n    ( \"help,h\", \"display usage information\" )\n    ( \"in_xml\", popts::value<string>( & input_psf_xml_filename ), \"input PSF xml file name\" )\n    ( \"in_fits\", popts::value<string>( & input_psf_fits_filename ), \"input PSF fits file name\" )\n    ( \"out_fits_image\", popts::value<string>( & output_image_fits_filename ), \"output image fits file name\" )\n    ( \"out_fits_psf\", popts::value<string>( & output_psf_fits_filename ), \"output psf fits file name\" )\n    ;\n  \n  popts::variables_map vm;\n  try {\n    popts::store(popts::command_line_parser( argc, argv ).options(desc).run(), vm);\n    popts::notify(vm);\n    \n    if ( ( argc < 2 ) || vm.count( \"help\" ) || ( ! vm.count( \"in_xml\" ) && ( ! vm.count( \"in_fits\" ) ) )  ||  ( ! vm.count( \"out_fits_image\") && ( ! vm.count( \"out_fits_psf\" ) ) ) ) {\n      cerr << endl;\n      cerr << desc << endl;\n      return EXIT_FAILURE;\n    }\n  }catch(std::exception) {\n    cerr << \"error in arguments\" << endl;\n    cerr << endl;\n    cerr << desc << endl;\n    return EXIT_FAILURE;\n  }\n  \n  specex::PSF_p psf;\n  \n  if(vm.count( \"in_fits\" ))\n    SPECEX_ERROR(\"reading fits not implemented yet\");\n  \n  specex::read_psf_xml(psf,input_psf_xml_filename);\n  \n  /*\n  if(psf->Name() !=  \"GaussHermite2PSF\") {\n    cout << \"code only works with GAUSSHERMITE2PSF\" << endl;\n    return 0;\n  }\n  */\n\n  \n  if(vm.count( \"out_fits_psf\" ))\n  specex::write_psf_fits(psf,output_psf_fits_filename);\n  \n\n  if(0){\n    // testing coordinate system  \n    double xc = 400;\n    double yc = 2000;\n    harp::vector_double P(psf->LocalNAllPar());\n    P.clear();\n    int i=floor(xc);\n    //for(i=floor(xc)-3;i<=floor(xc)+3;i++)\n    for(int j=floor(yc)-3;j<=floor(yc)+3;j++) \n      cout << i << \" \" << j << \" \" << psf->PSFValueWithParamsXY(400,2000,i,j,P,NULL,NULL) << endl;\n    \n    return 0;\n  }\n  \n  \n  // now create a test image\n  SPECEX_INFO(\"Generate an image with spots of flux=1 at each 50A starting at 3500A for each fiber addressed by PSF\");\n  \n  \n  \n  SPECEX_INFO(\"create list of spots ...\");\n  \n  vector<specex::Spot_p> spots;\n  \n  double wave_step = 50;\n\n  for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf->ParamsOfBundles.begin();\n      bundle_it != psf->ParamsOfBundles.end(); ++bundle_it) {\n    for(int fiber = bundle_it->second.fiber_min;\n\tfiber <= bundle_it->second.fiber_max; ++fiber) {\n      \n      const specex::Trace& trace = psf->GetTrace(fiber);\n      double trace_wave_min = trace.X_vs_W.xmin;\n      double trace_wave_max = trace.X_vs_W.xmax;\n      double min_wave = 3600; //wave_step*int(max(3500.,trace_wave_min)/wave_step+1);\n      \n      SPECEX_INFO(\"bundle \" << bundle_it->first << \" fiber \" << fiber << \" wave range = \" << trace_wave_min << \" \" << trace_wave_max);\n      SPECEX_INFO(\"bundle \" << bundle_it->first << \" fiber \" << fiber << \" coefs = \" << trace.X_vs_W.coeff);\n      \n      \n\n      // loop on wavelength\n      for(double wave = min_wave ; wave<= trace_wave_max; wave += wave_step) {\n\t\n\tspecex::Spot_p spot(new specex::Spot());\n\t\n\tspot->xc = trace.X_vs_W.Value(wave);\n\tspot->yc = trace.Y_vs_W.Value(wave);\n\tspot->flux = 1;\n\tspot->wavelength = wave;\n\tspot->fiber = fiber;\n\tspot->fiber_bundle = bundle_it->first;\n\tspots.push_back(spot);\n\tSPECEX_INFO(\"fiber=\" << spot->fiber << \" wave=\" << spot->wavelength << \" x=\" << spot->xc << \" y=\" << spot->yc);\n\n\t//break; // DEBUG, only one spot per fiber\n      }\n      \n      //exit(12); // DEBUG\n    }\n  }\n  \n#ifdef CONTINUUM\n  SPECEX_INFO(\"remove continuum\");\n  for(std::map<int,specex::PSF_Params>::iterator bundle_it = psf->ParamsOfBundles.begin();\n      bundle_it != psf->ParamsOfBundles.end(); ++bundle_it) {\n    bundle_it->second.ContinuumPol.coeff.clear();\n  }\n#endif\n\n  if(0) {\n    SPECEX_INFO(\"remove psf tail\");\n    for(std::map<int,specex::PSF_Params>::iterator bundle_it = psf->ParamsOfBundles.begin();\n\tbundle_it != psf->ParamsOfBundles.end(); ++bundle_it) {\n      bundle_it->second.AllParPolXW[psf->ParamIndex(\"TAILAMP\")]->coeff.clear();\n    }\n  }\n\n   // create image\n  specex::image_data img(psf->ccd_image_n_cols,psf->ccd_image_n_rows);\n  \n  specex::image_data weight(psf->ccd_image_n_cols,psf->ccd_image_n_rows);\n  for(size_t i=0;i<weight.data.size();i++) weight.data(i)=1;\n  \n  bool only_on_spots = false;\n  bool only_psf_core = false;\n  bool only_positive = false;\n\n  if(output_image_fits_filename!=\"\") {\n    SPECEX_INFO(\"computing  image ...\");  \n    specex::parallelized_compute_model_image(img,weight,psf,spots,only_on_spots,only_psf_core,only_positive,0,0);\n    //specex::compute_model_image(img,weight,psf,spots,only_on_spots,only_psf_core,only_positive,-1,-1,12);\n  \n    SPECEX_INFO(\"writing image ...\");\n    fitsfile * fp;  \n    harp::fits::create ( fp, output_image_fits_filename );\n    harp::fits::img_append < double > ( fp, img.n_rows(), img.n_cols() );\n    harp::fits::img_write ( fp, img.data, false );\n    \n    int status=0;\n    char comment[800];\n    fits_write_comment(fp,\"generateds by specex_test_psf_specter_io\",&status);\n    sprintf(comment,\"from %s\",input_psf_xml_filename.c_str());\n    fits_write_comment(fp,comment,&status);\n    sprintf(comment,\"spots generated every %fA, starting at %fA\",wave_step,spots[0]->wavelength);\n    fits_write_comment(fp,comment,&status);\n    fits_write_comment(fp,\"flux in each spot is 1 electron\",&status);\n    harp::fits::close ( fp );\n    \n\n\n  }else{\n    SPECEX_INFO(\"no full image\");  \n  }\n  \n  { // one spot\n    vector<specex::Spot_p> one_spot;\n    specex::Spot_p spot = spots[0];\n    spot->wavelength = (double)((int)spot->wavelength); \n    one_spot.push_back(spot);\n    \n    img    = specex::image_data(spot->xc+50,spot->yc+50);\n    weight = specex::image_data(spot->xc+50,spot->yc+50);\n    for(size_t i=0;i<weight.data.size();i++) weight.data(i)=1;\n    \n    char filename[1000];\n    \n    specex::PSF_Params& params_of_bundle = psf->ParamsOfBundles.find(spot->fiber_bundle)->second;\n    \n    /*\n    if(psf->HasParam(\"GHNSIG\")) {\n      params_of_bundle.AllParPolXW[psf->ParamIndex(\"GHNSIG\")]->coeff.clear();\n      params_of_bundle.AllParPolXW[psf->ParamIndex(\"GHNSIG\")]->coeff(0)=1000; // don't want to cut off core\n      cout << \"set GHNSIG to very large value\" << endl;\n    }\n    */\n    \n    harp::vector_double psf_params = psf->AllLocalParamsFW(spot->fiber,spot->wavelength,spot->fiber_bundle);\n    \n    double scal2    = 0;\n    if(psf->Name() ==  \"GaussHermite2PSF\") {\n      scal2    = psf_params[psf->ParamIndex(\"GH2-0-0\")];\n      cout << \"norm of first  GH PSF = \" << (1-scal2) << endl;\n      cout << \"norm of second GH PSF = \" <<  scal2 << endl;\n    }\n    \n    vector<string> names = psf->DefaultParamNames();\n    for(size_t k=0;k<psf_params.size(); k++) {\n      cout << k << \" \" << names[k] << \" \" << psf_params(k) << endl;\n    }\n    \n    img.data.clear();\n    specex::parallelized_compute_model_image(img,weight,psf,one_spot,only_on_spots,only_psf_core,only_positive,50,50,spot->fiber_bundle);\n    specex::image_data all_contributions_img = img;\n    \n    \n    params_of_bundle.AllParPolXW[psf->ParamIndex(\"TAILAMP\")]->coeff.clear();\n    img.data.clear();\n    specex::parallelized_compute_model_image(img,weight,psf,one_spot,only_on_spots,only_psf_core,only_positive,50,50,spot->fiber_bundle);\n    specex::image_data without_tails_img = img;\n    specex::image_data only_tails_img = all_contributions_img;\n    only_tails_img.data -= without_tails_img.data;\n    \n    for(size_t p=0;p<params_of_bundle.AllParPolXW.size();p++) {\n      if(names[p].find(\"GH2-\")!=names[p].npos) {\n\tcout << \"clearing \" << names[p] << endl;\n\tparams_of_bundle.AllParPolXW[p]->coeff.clear();\n      }\n    }\n    \n    sprintf(filename,\"single_spot_fiber_%d_wave_%d.fits\",spot->fiber,(int)spot->wavelength);\n    specex::write_new_fits_image(filename,all_contributions_img);\n    sprintf(filename,\"single_spot_fiber_%d_wave_%d_without_tails.fits\",spot->fiber,(int)spot->wavelength);\n    specex::write_new_fits_image(filename,without_tails_img);\n\n    //sprintf(filename,\"single_spot_fiber_%d_wave_%d_only_tails.fits\",spot->fiber,(int)spot->wavelength);\n    //specex::write_new_fits_image(filename,only_tails_img);\n    \n    if(psf->Name() ==  \"GaussHermite2PSF\") {\n      img.data.clear();\n      specex::parallelized_compute_model_image(img,weight,psf,one_spot,only_on_spots,only_psf_core,only_positive,50,50,spot->fiber_bundle);\n      specex::image_data only_core_gaussian_img = img;\n    \n      // need to compute naked gaussian to fix amplitude offset\n      for(size_t p=0;p<params_of_bundle.AllParPolXW.size();p++) {\n\tif(names[p].find(\"GH-\")!=names[p].npos) {\n\t  cout << \"clearing \" << names[p] << endl;\n\t  params_of_bundle.AllParPolXW[p]->coeff.clear();\n\t}\n      }\n      \n      img.data.clear();\n      specex::parallelized_compute_model_image(img,weight,psf,one_spot,only_on_spots,only_psf_core,only_positive,50,50,spot->fiber_bundle);\n      specex::image_data only_core_naked_gaussian_img = img;\n      only_core_gaussian_img.data -= scal2*only_core_naked_gaussian_img.data;\n      \n      \n      \n      specex::image_data only_second_gaussian_img = without_tails_img;\n      only_second_gaussian_img.data -= only_core_gaussian_img.data;\n      \n    \n      specex::image_data zero = all_contributions_img;\n      zero.data -= only_core_gaussian_img.data;\n      zero.data -= only_second_gaussian_img.data;\n      zero.data -= only_tails_img.data;\n      \n      sprintf(filename,\"single_spot_fiber_%d_wave_%d_only_core_gaussian.fits\",spot->fiber,(int)spot->wavelength);\n      specex::write_new_fits_image(filename,only_core_gaussian_img);\n      sprintf(filename,\"single_spot_fiber_%d_wave_%d_only_second_gaussian.fits\",spot->fiber,(int)spot->wavelength);\n      specex::write_new_fits_image(filename,only_second_gaussian_img);\n      \n      sprintf(filename,\"zero.fits\");\n      specex::write_new_fits_image(filename,zero);\n    \n    \n    \n    }\n  } // end of one spot\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "21769a192f588da162eef86851895d3420e56f2d", "size": 10557, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/specex_test_psf_specter_io.cc", "max_stars_repo_name": "marcelo-alvarez/specex", "max_stars_repo_head_hexsha": "809c5540e76dc1681453488732d5845078427ad1", "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/tests/specex_test_psf_specter_io.cc", "max_issues_repo_name": "marcelo-alvarez/specex", "max_issues_repo_head_hexsha": "809c5540e76dc1681453488732d5845078427ad1", "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/tests/specex_test_psf_specter_io.cc", "max_forks_repo_name": "marcelo-alvarez/specex", "max_forks_repo_head_hexsha": "809c5540e76dc1681453488732d5845078427ad1", "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.5454545455, "max_line_length": 183, "alphanum_fraction": 0.6654352562, "num_tokens": 3084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.19330883256225248}}
{"text": "#include <iostream>\n\n#include <boost/generator_iterator.hpp>\n#include <boost/random.hpp>\n\n#include \"tmod.h\"\n\n#include <chrono>\n#include <cstdint>\n#include <iostream>\n\nuint64_t timeSinceEpochMillisec()\n{\n    using namespace std::chrono;\n    return duration_cast<milliseconds>(system_clock::now().time_since_epoch())\n        .count();\n}\n\nint16_t tmodReadAdc(uint16_t hardwareAddress)\n{\n    // Hardware address can't be negative as it is uint16_t.\n    if (hardwareAddress > tmodMaxAdcs())\n        return TMOD_INVALID_VOLTAGE_MEASUREMENT;\n\n    boost::mt19937 rng(timeSinceEpochMillisec());\n    boost::uniform_int<> adcMeasurementRange(0, TMOD_MAX_ADC_VALUE);\n    boost::variate_generator<boost::mt19937, boost::uniform_int<>>\n        randomMeasurement(rng, adcMeasurementRange);\n    return randomMeasurement();\n}\n\nuint16_t tmodMaxAdcs() { return TMOD_MAX_ADCS; }\n", "meta": {"hexsha": "bf3d433c8f27c00913d3b5bef713231a76d1ae23", "size": 859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/tmod/tmod.cpp", "max_stars_repo_name": "don4get/taking_the_temperature", "max_stars_repo_head_hexsha": "28ee36c98cb97bda06dc1b945e4300900bbf8234", "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/tmod/tmod.cpp", "max_issues_repo_name": "don4get/taking_the_temperature", "max_issues_repo_head_hexsha": "28ee36c98cb97bda06dc1b945e4300900bbf8234", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-09T21:56:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-09T21:56:16.000Z", "max_forks_repo_path": "libs/tmod/tmod.cpp", "max_forks_repo_name": "don4get/taking_the_temperature", "max_forks_repo_head_hexsha": "28ee36c98cb97bda06dc1b945e4300900bbf8234", "max_forks_repo_licenses": ["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.0303030303, "max_line_length": 78, "alphanum_fraction": 0.7380675204, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.19330883256225245}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LOG_HPP\n#define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LOG_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/prob/categorical_logit_lpmf.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * @deprecated use <code>categorical_logit_lpmf</code>\n */\ntemplate <bool propto, typename T_prob>\ntypename boost::math::tools::promote_args<T_prob>::type categorical_logit_log(\n    int n, const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& beta) {\n  return categorical_logit_lpmf<propto, T_prob>(n, beta);\n}\n\n/**\n * @deprecated use <code>categorical_logit_lpmf</code>\n */\ntemplate <typename T_prob>\ninline typename boost::math::tools::promote_args<T_prob>::type\ncategorical_logit_log(int n,\n                      const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& beta) {\n  return categorical_logit_lpmf<T_prob>(n, beta);\n}\n\n/**\n * @deprecated use <code>categorical_logit_lpmf</code>\n */\ntemplate <bool propto, typename T_prob>\ntypename boost::math::tools::promote_args<T_prob>::type categorical_logit_log(\n    const std::vector<int>& ns,\n    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& beta) {\n  return categorical_logit_lpmf<propto, T_prob>(ns, beta);\n}\n\n/**\n * @deprecated use <code>categorical_logit_lpmf</code>\n */\ntemplate <typename T_prob>\ninline typename boost::math::tools::promote_args<T_prob>::type\ncategorical_logit_log(const std::vector<int>& ns,\n                      const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& beta) {\n  return categorical_logit_lpmf<T_prob>(ns, beta);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "a9fa406a30f1f1fdf091e5534832420734da5894", "size": 1662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/prob/categorical_logit_log.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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/mat/prob/categorical_logit_log.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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/mat/prob/categorical_logit_log.hpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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.7777777778, "max_line_length": 78, "alphanum_fraction": 0.7346570397, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19330882526403356}}
{"text": "#include <cstring>\n\n#include <boost/foreach.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <epecur/types.hpp>\n#include <epecur/track.hpp>\n#include <epecur/StdHits.hpp>\n\n#include \"DriftCalibHook.hpp\"\n\nDriftCalibHook::DriftCalibHook(Geometry &g, int _drift_calib_cut)\n    : StdHits(g, NULL)\n    , drift_calib_cut(_drift_calib_cut)\n{\n\t// Nothing\n}\n\nunsigned int\tDriftCalibHook::generate_calibration_curve( chamber_id_t chamber_id )\n{\n\tuint16_t\ttime = 0;\n\tunsigned int\toveral_integral = 0, integral = 0;\n\tauto\t&calib = calibration_curve[chamber_id];\n\n\tcalib.resize(MAX_TIME_COUNTS);\n\n\tBOOST_FOREACH(auto counts, time_distributions[chamber_id])\n\t{\n\t\toveral_integral += counts;\n\t}\n\n\tBOOST_FOREACH(auto counts, time_distributions[chamber_id])\n\t{\n\t\tintegral += counts;\n\t\tauto\tvalue = integral / (float)overal_integral;\n\t\tcalib[time] = value;\n\t\ttime++;\n\t}\n\n\treturn overal_integral;\n}\n\nvoid\tDriftCalibHook::generate_calibration_curves()\n{\n\tBOOST_FOREACH(auto gr_tup, geom.group_chambers)\n\t{\n\t\tgroup_id_t\tgroup_id = gr_tup.first;\n\t\tdevice_type_t\tdevice_type = geom.group_device_type[group_id];\n\n\t\tif (device_type != DEV_TYPE_DRIFT)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tBOOST_FOREACH(auto axis_tup, gr_tup.second)\n\t\t{\n\t\t\tdevice_axis_t\taxis = axis_tup.first;\n\t\t\tvector<chamber_id_t>\t&chambers =\n\t\t\t\tgeom.group_chambers[group_id][axis];\n\n\t\t\tBOOST_FOREACH(chamber_id_t chamber_id, chambers)\n\t\t\t{\n\t\t\t\tgenerate_calibration_curve(chamber_id);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid\tDriftCalibHook::handle_event_end()\n{\n\tBOOST_FOREACH(auto gr_tup, geom.group_chambers)\n\t{\n\t\tgroup_id_t\tgroup_id = gr_tup.first;\n\n\t\tif (geom.group_device_type[group_id] != DEV_TYPE_DRIFT)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tBOOST_FOREACH(auto &axis_tup, gr_tup.second)\n\t\t{\n\t\t\tconst vector<chamber_id_t>\t&chambers = axis_tup.second;\n\n\t\t\tBOOST_FOREACH(chamber_id_t chamber_id, chambers)\n\t\t\t{\n\t\t\t\tvector<wire_pos_t> &wire_pos = last_event_drift_wire_pos[chamber_id];\n\t\t\t\tauto it = wire_pos.begin();\n\n\t\t\t\tBOOST_FOREACH(uint16_t time, last_event_drift_time[chamber_id])\n\t\t\t\t{\n\t\t\t\t\tauto\t&calib = time_distributions[chamber_id];\n\n\t\t\t\t\t// Here we are removing hits from the adjacent cells\n\t\t\t\t\tbool fail = false;\n\t\t\t\t\tfor(auto it2 = wire_pos.begin(); it2 != it; it2++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (fabs(*it - *it2) <= 2.001)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfail = true;\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 (fail)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tit++;\n\n\t\t\t\t\tif (calib.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tcalib.resize(MAX_TIME_COUNTS);\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((drift_calib_cut < 0) || (time < drift_calib_cut))\n\t\t\t\t\t{\n\t\t\t\t\t\tcalib[time]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "ea94abe66a473821fba12005a407c74f2cdcb7e6", "size": 2513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/export_tree/DriftCalibHook.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/utils/export_tree/DriftCalibHook.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/utils/export_tree/DriftCalibHook.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": 20.7685950413, "max_line_length": 82, "alphanum_fraction": 0.6856346996, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19330882526403356}}
{"text": "// Copyright 2018-2019 Carnegie Mellon University.  See LICENSE file for terms.\n\n#include <boost/graph/topological_sort.hpp>\n#include <z3++.h>\n\n#include <boost/range/algorithm/for_each.hpp>\n\n// For the main pharos infastructure that tracks functions.\n#include \"descriptors.hpp\"\n\n// For IR\n#include \"ir.hpp\"\n\n#include \"wp.hpp\"\n\n// For get_func_containing_addr\n#include \"path.hpp\"\n\nusing namespace pharos;\nusing namespace pharos::ir;\n\nnamespace {\n  using Rose::BinaryAnalysis::SmtSolver;\n\n  // LET crap.\n  auto constexpr OP_LET = Rose::BinaryAnalysis::SymbolicExpr::Operator::OP_LET;\n\n  // map from variables to their bound expressions\n  using letmap = std::map<Register, IRExprPtr>;\n\n  using InteriorPtr = SymbolicExpr::InteriorPtr;\n\n  // We *must* use pass by value here\n  IRExprPtr expand_lets (IRExprPtr e, letmap lm) {\n    Register v;\n    InteriorPtr i;\n\n    if ((v = e->isLeafNode ())) {\n      if ((v->isVariable () || v->isMemory ()) && lm.count (v)) {\n        // It's a reference to v that has been bound\n        return lm[v];\n      } else {\n        // It's some other leaf node that we don't have to change\n        return e;\n      }\n    } else {\n      i = e->isInteriorNode ();\n      assert (i);\n      auto children = i->children ();\n      if (i->getOperator () == OP_LET) {\n        // This is a let expression!\n        IRExprPtr v_, ve, vin;\n        std::tie(v_, ve, vin) = std::make_tuple(children.at (0), children.at (1), children.at (2));\n        v = v_->isLeafNode ();\n        // First expand ve\n        ve = expand_lets (ve, lm);\n        // Now add v -> ve to lm\n        lm[v] = ve;\n        // And recurse on vin\n        return expand_lets (vin, lm);\n      } else {\n        // A non-let interior expression.  Recurse on each child and rebuild the expression\n        std::vector <IRExprPtr> new_children;\n\n        std::transform (children.begin (), children.end (),\n                        std::back_inserter (new_children),\n                        [lm] (IRExprPtr childe) {\n                          return expand_lets (childe, lm);\n                        });\n        return SymbolicExpr::Interior::create (i->nBits (),\n                                               i->getOperator (),\n                                               new_children);\n      }\n    }\n  }\n\n  IRExprPtr makeLet (Register a, IRExprPtr b, IRExprPtr c) {\n    return SymbolicExpr::Interior::create (c->nBits (), OP_LET, a, b, c);\n  }\n\n}\n\nnamespace pharos {\n  IRExprPtr expand_lets (const IRExprPtr &e) {\n    letmap l;\n    return ::expand_lets (e, l);\n  }\n}\n\n// Better names for variables during Z3 translation.\n// Very dangerous to enable because it changes all Pharos programs!\n// Please do not commit (only for debugging).\n#if 0\nnamespace Rose {\n  namespace BinaryAnalysis {\nvoid\nZ3Solver::ctxVariableDeclarations(const VariableSet &vars) {\n  BOOST_FOREACH (const SymbolicExpr::LeafPtr &var, vars.values()) {\n    ASSERT_not_null(var);\n    ASSERT_require(var->isVariable() || var->isMemory());\n    if (ctxVarDecls_.exists(var)) {\n      // already emitted a declaration for this variable\n    } else if (var->isScalar()) {\n      z3::sort range = ctx_->bv_sort(var->nBits());\n      std::stringstream ss;\n      ss << *var;\n      z3::func_decl decl = z3::function(ss.str().c_str(), 0, NULL, range);\n      ctxVarDecls_.insert(var, decl);\n    } else {\n      ASSERT_require(var->domainWidth() > 0);\n      z3::sort addr = ctx_->bv_sort(var->domainWidth());\n      z3::sort value = ctx_->bv_sort(var->nBits());\n      z3::sort range = ctx_->array_sort(addr, value);\n      std::stringstream ss;\n      ss << *var;\n      z3::func_decl decl = z3::function(ss.str().c_str(), 0, NULL, range);\n      ctxVarDecls_.insert(var, decl);\n    }\n  }\n}\n}\n}\n#endif\n\nnamespace {\n  IRExprPtr wp_stmt(const Stmt& s, const IRExprPtr& post, const Register& mem) {\n    struct StmtVisitor : public boost::static_visitor<IRExprPtr> {\n      const IRExprPtr& post;\n      const Register& mem;\n      StmtVisitor(const IRExprPtr& post_, const Register& mem_)\n        : post(post_), mem(mem_) {}\n\n      IRExprPtr operator()(const RegWriteStmt &rs) {\n        // Substitute instances of var (rs.first) with exp (rs.second) in post\n        return makeLet (rs.first, rs.second, post);\n        //return post->substitute(rs.first, rs.second);\n      }\n      IRExprPtr operator()(const MemWriteStmt &ms) {\n        // Update memory\n        IRExprPtr newmem = SymbolicExpr::makeWrite (mem, ms.first, ms.second);\n        return makeLet (mem, newmem, post);\n        //return post->substitute(mem, newmem);\n      }\n      IRExprPtr operator()(UNUSED const SpecialStmt &ss) {\n        // Return false? It's not clear what the best thing to do here is.\n        return SymbolicExpr::makeBoolean (false);\n      }\n      IRExprPtr operator()(UNUSED const CallStmt &cs) {\n        // Return false? It's not clear what the best thing to do here is.\n        return SymbolicExpr::makeBoolean (false);\n      }\n      IRExprPtr operator()(UNUSED const InsnStmt &is) {\n        // Instruction statements do not effect weakest preconditions\n        return post;\n      }\n    };\n\n    StmtVisitor vis(post, mem);\n    return boost::apply_visitor(vis, s);\n  }\n\n  IRExprPtr wp_stmts(const Stmts& stmts, const IRExprPtr& post, const Register& mem) {\n    return std::accumulate(stmts.rbegin(), stmts.rend(), post,\n                           [&mem](const IRExprPtr& e,\n                                  const Stmt &stmt)\n                           { return wp_stmt(stmt, e, mem); });\n  }\n\n  // When we remove edges from the CFG, we are left with some vertices that are partially\n  // specified.  If we do not do anything, the unspecified executions are 'true' in the WP\n  // formula which is not what we want.  This function adds edges for those executions to the\n  // error node.\n  IR add_error_edges (const IR& ir) {\n    IRCFG cfg = ir.get_cfg ();\n    auto edgecond_map = boost::get(boost::edge_name_t(), cfg);\n\n    auto error = ir.get_error ();\n\n    BGL_FORALL_VERTICES (v, cfg, IRCFG) {\n      if (boost::out_degree (v, cfg) == 1) {\n        IRCFGEdge e = *boost::begin (boost::out_edges (v, cfg));\n        auto cond = edgecond_map [e];\n        if (cond) {\n          auto d = boost::target (e, cfg);\n          if (d == error) {\n            // Conditional edge to error.  Make it unconditional.\n            edgecond_map [e] = EdgeCond ();\n          } else {\n            // Otherwise add a new edge to error.\n            IRCFGEdge new_edge;\n            bool succ;\n            std::tie (new_edge, succ) = boost::add_edge (v, error, cfg);\n            assert (succ);\n            auto t = SymbolicExpr::makeInvert (*cond);\n            edgecond_map [new_edge] = EdgeCond (t);\n          }\n        }\n      }\n\n    }\n    return IR (ir, cfg);\n  }\n}\n\nnamespace pharos {\n\n  IRExprPtr wp_cfg(const IR& ir_, const IRExprPtr &post) {\n    std::vector<IRCFGVertex> rtopo;\n\n    IR ir = add_error_edges (split_edges (filter_backedges (ir_)));\n\n    const IRCFG& cfg = ir.get_cfg();\n    auto ir_map = boost::get(boost::vertex_ir_t(), cfg);\n    //auto name_map = boost::get(boost::vertex_name_t(), cfg);\n    auto edgecond_map = boost::get(boost::edge_name_t(), cfg);\n\n    topological_sort (cfg,\n                      std::back_inserter (rtopo));\n\n    // This maps a BB to its WP\n    std::map<IRCFGVertex, IRExprPtr> bbwp;\n\n    for (auto v : rtopo) {\n      IRExprPtr bbpost;\n      if (boost::out_degree (v, cfg) == 0) {\n        // This is the exit\n        bbpost = post;\n      } else {\n        auto it = boost::out_edges (v, cfg);\n        bbpost = std::accumulate (it.first,\n                                  it.second,\n                                  SymbolicExpr::makeBoolean (true),\n                                  [&] (IRExprPtr exp, const IRCFGEdge &e) {\n                                    auto sv = boost::target (e, cfg);\n                                    assert (bbwp.count (sv) == 1);\n                                    return SymbolicExpr::makeAnd (exp, bbwp[sv]);\n                                  });\n      }\n\n      IRExprPtr wp = wp_stmts (*ir_map[v], bbpost, ir.get_mem ());\n\n      // Because we called split_edges, there is at most one incoming edge that has a condition.\n      // If there is one, we treat it like an assume statement, so e => q\n      auto incoming_edges = boost::in_edges (v, cfg);\n      auto edgeit = std::find_if (incoming_edges.first,\n                                  incoming_edges.second,\n                                  [&] (IRCFGEdge e) {\n                                    return (edgecond_map[e]);\n                                  });\n      if (edgeit != incoming_edges.second) {\n        wp = SymbolicExpr::makeIte (*edgecond_map[*edgeit], wp, SymbolicExpr::makeBoolean (true));\n        //std::cout << \"added edge condition \" << **edgecond_map[*edgeit] << std::endl;\n      }\n\n      bbwp[v] = wp;\n\n      // PharosZ3Solver solver;\n      // solver.insert (expand_lets (bbwp[v]));\n      // solver.z3Update ();\n      // std::cout << \"WP \" << name_map[v] << \" \" << (solver.check() == Rose::BinaryAnalysis::SmtSolver::Satisfiable::SAT_YES) << \" \" << solver.z3Assertions ().at (0) << std::endl;\n      // if (solver.check () == Rose::BinaryAnalysis::SmtSolver::Satisfiable::SAT_YES) {\n      //        std::cout << solver.z3Solver ()->get_model () << std::endl;\n      // }\n    }\n\n    const IRCFGVertex &entry = ir.get_entry ();\n\n    return bbwp[entry];\n  }\n\n\n  std::pair<IR,IRExprPtr> add_reached_postcondition (const IR& ir, const std::set<rose_addr_t> targets, boost::optional<Register> hit_var_) {\n    IRCFG cfg = ir.get_cfg ();\n\n    Register hit_var;\n\n    // Create the variable if necessary\n    if (hit_var_) {\n      hit_var = *hit_var_;\n    } else {\n      hit_var = SymbolicExpr::makeVariable (1, \"hit_target\")->isLeafNode ();\n    }\n\n    std::set<rose_addr_t> targetbbs;\n\n    // Find the basic blocks that the target addresses are in\n    std::transform (targets.begin (),\n                    targets.end (),\n                    std::inserter (targetbbs, targetbbs.end ()),\n                    [&] (rose_addr_t addr) {\n                      // Because we are using an instruction level CFG, this is a noop for now.\n                      return addr;\n                    });\n\n    // Check for NULL\n\n    auto bb_map = boost::get (boost::vertex_name_t (), cfg);\n    auto ir_map = boost::get (boost::vertex_ir_t (), cfg);\n\n    // Initialize the variable to false in the entry\n    auto entry = ir.get_entry ();\n    auto irstmts = ir_map[entry];\n    auto newstmt = RegWriteStmt (hit_var, SymbolicExpr::makeBoolean (false));\n    irstmts->insert (irstmts->begin (), newstmt);\n\n    // Loop over each BB.  If the BB matches one of the targets, adjust\n    // the IR to insert writes at the proper places.\n\n    // Note that we do NOT care if we successfully reach the exit.\n    // Therefore we add a write before the first matching target and\n    // remove any outgoing edges which effectively makes the node an\n    // exit.\n\n    BGL_FORALL_VERTICES(v, cfg, IRCFG) {\n      auto insn_addr = bb_map[v].get_insn_addr ();\n      if (insn_addr && targetbbs.count (*insn_addr)) {\n        auto stmts = ir_map[v];\n        auto firstaddrstmt = std::find_if (stmts->begin (),\n                                           stmts->end (),\n                                           [&] (Stmt s) {\n                                             auto addr = addrFromStmt (s);\n                                             return addr && targets.count (*addr) == 1;\n                                           });\n        assert (firstaddrstmt != stmts->end ());\n\n        stmts->erase (firstaddrstmt+1, stmts->end ());\n        newstmt = RegWriteStmt (hit_var, SymbolicExpr::makeBoolean (true));\n        stmts->push_back (newstmt);\n\n        // Remove all outgoing edges\n        boost::clear_out_edges (v, cfg);\n      } else if (boost::out_degree (v, cfg) == 0) {\n        // This is just an optimization to make WP simplify a little bit better\n        auto stmts = ir_map[v];\n        newstmt = RegWriteStmt (hit_var, SymbolicExpr::makeBoolean (false));\n        stmts->push_back (newstmt);\n      }\n    }\n\n    return std::make_pair (IR (ir, cfg), hit_var);\n  }\n\n}\n\nnamespace {\n  struct HelperVisitor : public boost::static_visitor<boost::optional<Stmt>> {\n    const DescriptorSet &ds;\n    const std::set<ImportCall> &funcs;\n    const IR &ir;\n    int &n;\n    bool ignore = false;\n    HelperVisitor (const DescriptorSet &ds_, IR &ir_, const std::set<ImportCall> &funcs_, int &n_) : ds(ds_), funcs(funcs_), ir(ir_), n(n_) {}\n    boost::optional<Stmt> operator () (const InsnStmt &is) {\n      ignore = false;\n      return (Stmt) is;\n    }\n    boost::optional<Stmt> operator () (const CallStmt &cs) {\n      if (const ImportCall *ec = boost::get<ImportCall> (&(std::get<1> (cs)))) {\n        // Is it one of the targeted functions?\n        auto i = std::find (funcs.begin (), funcs.end (), *ec);\n        if (i != funcs.end ()) {\n          int nbits = ds.get_arch_bits ();\n          Register eax = ir.get_reg(ds.get_arch_reg(\"eax\"));\n\t  std::stringstream vname;\n\t  vname << ec->first << \"!\" << ec->second << \"@\" << addr_str (std::get<2> (cs)->get_address ())\n\t\t<< \":\" << n;\n          IRExprPtr nv = SymbolicExpr::makeVariable (nbits, vname.str ());\n          ignore = true;\n          n++;\n          return (Stmt) (RegWriteStmt (eax, nv));\n        }\n      }\n\n      return (Stmt) cs;\n    }\n    template <typename T>\n    boost::optional<Stmt> operator () (T const &x) const {\n      if (ignore)\n        return boost::none;\n      else\n        return (Stmt) x;\n    }\n  };\n}\n\nnamespace pharos {\n  IR rewrite_imported_calls (const DescriptorSet& ds, IR &ir, const std::set<ImportCall> funcs) {\n    int n = 0;\n\n    IRCFG cfg = ir.get_cfg ();\n    auto ir_map = boost::get(boost::vertex_ir_t(), cfg);\n\n    BGL_FORALL_VERTICES (v, cfg, IRCFG) {\n      auto stmts = *ir_map [v];\n      StmtsPtr newstmts (new Stmts ());\n      HelperVisitor vis (ds, ir, funcs, n);\n      // Visit each stmt backwards.  If we see a call to a matching\n      // callsite, we ignore any stmt until we see the InsnStmt which\n      // marks the beginning of that instruction.  This is used to\n      // ignore stack adjustments among other things.\n      std::for_each (stmts.rbegin (),\n                     stmts.rend (),\n                     [&] (Stmt &os) {\n                       if (boost::optional<Stmt> ns = boost::apply_visitor (vis, os)) {\n                         newstmts->push_back (*ns);\n                       }\n                      });\n      // Put the new statements in the right order.\n      std::reverse (newstmts->begin (), newstmts->end ());\n      ir_map [v] = newstmts;\n    }\n\n    GINFO << \"Rewrote \" << n << \" imported calls.\" << LEND;\n\n    return IR(ir, cfg);\n  }\n}\n\n/* Local Variables:   */\n/* mode: c++          */\n/* fill-column:    95 */\n/* comment-column: 0  */\n/* End:               */\n", "meta": {"hexsha": "a9209da1d106e673f8ad61d84a7f9427a3e6d875", "size": 14858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libpharos/wp.cpp", "max_stars_repo_name": "Seabreg/pharos", "max_stars_repo_head_hexsha": "90f9011a54d7469555a229af4de1f66748fe5ded", "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": "libpharos/wp.cpp", "max_issues_repo_name": "Seabreg/pharos", "max_issues_repo_head_hexsha": "90f9011a54d7469555a229af4de1f66748fe5ded", "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": "libpharos/wp.cpp", "max_forks_repo_name": "Seabreg/pharos", "max_forks_repo_head_hexsha": "90f9011a54d7469555a229af4de1f66748fe5ded", "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": 35.0424528302, "max_line_length": 180, "alphanum_fraction": 0.5660923408, "num_tokens": 3828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19330882526403356}}
{"text": "// Copyright (c) 2020 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\n#ifndef MODULES_MODELS_DYNAMIC_DYNAMIC_MODEL_HPP_\n#define MODULES_MODELS_DYNAMIC_DYNAMIC_MODEL_HPP_\n\n#include <Eigen/Core>\n#include <boost/variant.hpp>\n#include <queue>\n#include <memory>\n#include <utility>\n\n#include \"modules/commons/base_type.hpp\"\n\nnamespace modules {\nnamespace models {\nnamespace dynamic {\n\ntypedef enum StateDefinition : int {\n  TIME_POSITION = 0,  // unit is seconds\n  X_POSITION = 1,  // unit is meter\n  Y_POSITION = 2,  // unit is meter\n  THETA_POSITION = 3,  // unit is rad\n  VEL_POSITION = 4,  // unit is meter/second\n  MIN_STATE_SIZE = 5,\n  Z_POSITION = 6  // only placeholder, not used at the moment\n} StateDefinition;\n\nusing State = Eigen::Matrix<float, Eigen::Dynamic, 1>;\nusing Input = Eigen::Matrix<float, Eigen::Dynamic, 1>;\n\nusing Trajectory = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>;\n\n\nclass DynamicModel : public commons::BaseType {\n public:\n  explicit DynamicModel(modules::commons::ParamsPtr params) :\n    BaseType(params), input_size_(0) {}\n\n  virtual ~DynamicModel() {}\n\n  virtual State StateSpaceModel(const State &x, const Input &u) const = 0;\n\n  virtual std::shared_ptr<DynamicModel> Clone() const = 0;\n\n  int input_size_;\n};\n\ntypedef std::shared_ptr<DynamicModel> DynamicModelPtr;\n\n}  // namespace dynamic\n}  // namespace models\n}  // namespace modules\n\n#endif  // MODULES_MODELS_DYNAMIC_DYNAMIC_MODEL_HPP_\n", "meta": {"hexsha": "04c3d5ed8a4303fe5f52aba629167e416d9d7f53", "size": 1577, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/models/dynamic/dynamic_model.hpp", "max_stars_repo_name": "Lizhu-Chen/bark", "max_stars_repo_head_hexsha": "fad029f658e462eb1772c28c2c0971faf5176dc1", "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": "modules/models/dynamic/dynamic_model.hpp", "max_issues_repo_name": "Lizhu-Chen/bark", "max_issues_repo_head_hexsha": "fad029f658e462eb1772c28c2c0971faf5176dc1", "max_issues_repo_licenses": ["MIT"], "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/models/dynamic/dynamic_model.hpp", "max_forks_repo_name": "Lizhu-Chen/bark", "max_forks_repo_head_hexsha": "fad029f658e462eb1772c28c2c0971faf5176dc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T17:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T17:09:05.000Z", "avg_line_length": 26.2833333333, "max_line_length": 74, "alphanum_fraction": 0.7336715282, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.19330881796581478}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n// Copyright (c) 2020 Alexander Sokolov <asokolov@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_SHA1_HPP\n#define CRYPTO3_HASH_SHA1_HPP\n\n#include <boost/crypto3/hash/detail/sha1/sha1_policy.hpp>\n#include <boost/crypto3/hash/detail/state_adder.hpp>\n#include <boost/crypto3/hash/detail/davies_meyer_compressor.hpp>\n#include <boost/crypto3/hash/detail/merkle_damgard_construction.hpp>\n#include <boost/crypto3/hash/detail/block_stream_processor.hpp>\n#include <boost/crypto3/hash/detail/merkle_damgard_padding.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n            /*!\n             * @brief SHA1. Widely adopted NSA designed hashes function. Starting\n             * to show significant signs of weakness, and collisions can now be\n             * generated. Avoid in new designs.\n             * @ingroup hashes\n             */\n            class sha1 {\n                typedef detail::sha1_policy policy_type;\n                typedef typename policy_type::block_cipher_type block_cipher_type;\n\n            public:\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 block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                constexpr static const std::size_t digest_bits = policy_type::digest_bits;\n                typedef typename policy_type::digest_type digest_type;\n\n                struct construction {\n                    struct params_type {\n                        typedef typename policy_type::digest_endian digest_endian;\n\n                        constexpr static const std::size_t length_bits = policy_type::length_bits;\n                        constexpr static const std::size_t digest_bits = policy_type::digest_bits;\n                    };\n\n                    typedef merkle_damgard_construction<params_type, typename policy_type::iv_generator,\n                                                        davies_meyer_compressor<block_cipher_type, detail::state_adder>,\n                                                        detail::merkle_damgard_padding<policy_type>>\n                        type;\n                };\n\n                template<typename StateAccumulator, std::size_t ValueBits>\n                struct stream_processor {\n                    struct params_type {\n                        typedef typename policy_type::digest_endian digest_endian;\n\n                        constexpr static const std::size_t value_bits = ValueBits;\n                    };\n\n                    typedef block_stream_processor<construction, StateAccumulator, params_type> type;\n                };\n            };\n        }    // namespace hashes\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_HASH_SHA1_HPP\n", "meta": {"hexsha": "a1519f0d9d859d4cd48af6b812a8a8028a6fd66a", "size": 3414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/sha1.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/sha1.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/sha1.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": 45.52, "max_line_length": 120, "alphanum_fraction": 0.5949033392, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3345894346180165, "lm_q1q2_score": 0.19322384773204573}}
{"text": "// Copyright (c) 2017-2019 The Particl Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <smsg/smessage.h>\n\n#include <test/setup_common.h>\n#include <net.h>\n#ifdef ENABLE_WALLET\n#include <wallet/wallet.h>\n#endif\n#include <xxhash/xxhash.h>\n\n#include <boost/test/unit_test.hpp>\n\nstruct SmsgTestingSetup : public TestingSetup {\n    SmsgTestingSetup() : TestingSetup(CBaseChainParams::MAIN, true) {}\n};\n\nBOOST_FIXTURE_TEST_SUITE(smsg_tests, SmsgTestingSetup)\n\nconst std::string sTestMessage = \"A short test message 0123456789 !@#$%^&*()_+-=\";\n\nBOOST_AUTO_TEST_CASE(smsg_test_xxhash)\n{\n    XXH32_state_t *state = XXH32_createState();\n    XXH32_reset(state, 1);\n    XXH32_update(state, sTestMessage.data(), sTestMessage.length());\n    uint32_t hash_new = XXH32_digest(state);\n    BOOST_CHECK(hash_new == 474992878);\n    XXH32_freeState(state);\n}\n\nBOOST_AUTO_TEST_CASE(smsg_test_ckeyId_inits_null)\n{\n    CKeyID k;\n    BOOST_CHECK(k.IsNull());\n}\n\n#ifdef ENABLE_WALLET\n\nvoid CheckValid(smsg::SecureMessage &smsg, CKeyID &kFrom, CKeyID &kTo, bool expect_pass)\n{\n    int rv = 0;\n    BOOST_CHECK(0 == smsgModule.Encrypt(smsg, kFrom, kTo, sTestMessage));\n    BOOST_CHECK(0 == smsgModule.SetHash((uint8_t*)&smsg, smsg.pPayload, smsg.nPayload));\n    if (expect_pass) {\n        BOOST_CHECK_MESSAGE(0 == (rv = smsgModule.Validate((uint8_t*)&smsg, smsg.pPayload, smsg.nPayload)), \"Validate failed \" << rv);\n    } else {\n        BOOST_CHECK_MESSAGE(0 != (rv = smsgModule.Validate((uint8_t*)&smsg, smsg.pPayload, smsg.nPayload)), \"Validate passed \" << rv);\n    }\n\n    // Reset\n    delete[] smsg.pPayload;\n    smsg.pPayload = nullptr;\n    smsg.nPayload = 0;\n}\n\nBOOST_AUTO_TEST_CASE(smsg_test)\n{\n    SeedInsecureRand();\n\n    int rv = 0;\n    const int nKeys = 12;\n    auto chain = interfaces::MakeChain();\n    std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), WalletLocation(), WalletDatabase::CreateDummy());\n    std::vector<CKey> keyOwn(nKeys);\n    for (int i = 0; i < nKeys; i++) {\n        InsecureNewKey(keyOwn[i], true);\n        LOCK(wallet->cs_wallet);\n        wallet->AddKey(keyOwn[i]);\n    }\n\n    std::vector<CKey> keyRemote(nKeys);\n    for (int i = 0; i < nKeys; i++) {\n        InsecureNewKey(keyRemote[i], true);\n        LOCK(wallet->cs_wallet);\n        wallet->AddKey(keyRemote[i]); // need pubkey\n    }\n\n    std::vector<std::shared_ptr<CWallet>> temp_vpwallets;\n    BOOST_CHECK(true == smsgModule.Start(wallet, temp_vpwallets, false));\n\n    smsg::SecureMessage smsg;\n    smsg.m_ttl = 1;\n    CKeyID kFrom = keyOwn[0].GetPubKey().GetID();\n    CKeyID kTo = keyRemote[0].GetPubKey().GetID();\n    CheckValid(smsg, kFrom, kTo, false);\n    smsg.m_ttl = smsg::SMSG_MAX_FREE_TTL + 1;\n    CheckValid(smsg, kFrom, kTo, false);\n    smsg.m_ttl = smsg::SMSG_MAX_FREE_TTL;\n    CheckValid(smsg, kFrom, kTo, true);\n    smsg.m_ttl = smsg::SMSG_MIN_TTL;\n    CheckValid(smsg, kFrom, kTo, true);\n\n    CKeyID idNull;\n    for (int i = 0; i < nKeys; i++) {\n        smsg::SecureMessage smsg;\n        smsg::MessageData msg;\n        smsg.m_ttl = 1 * smsg::SMSG_SECONDS_IN_DAY;\n        CKeyID kFrom = keyOwn[i].GetPubKey().GetID();\n        CKeyID kTo = keyRemote[i].GetPubKey().GetID();\n        CKeyID kFail = keyRemote[(i+1) % nKeys].GetPubKey().GetID();\n        std::string sAddrFrom = EncodeDestination(PKHash(kFrom));\n        std::string sAddrTo = EncodeDestination(PKHash(kTo));\n        std::string sAddrFail = EncodeDestination(PKHash(kFail));\n\n        bool fSendAnonymous = rand() % 3 == 0;\n\n        BOOST_CHECK_MESSAGE(0 == (rv = smsgModule.Encrypt(smsg, fSendAnonymous ? idNull : kFrom, kTo, sTestMessage)), \"SecureMsgEncrypt \" << rv);\n\n        BOOST_CHECK_MESSAGE(0 == (rv = smsgModule.SetHash((uint8_t*)&smsg, smsg.pPayload, smsg.nPayload)), \"SecureMsgSetHash \" << rv);\n\n        BOOST_CHECK_MESSAGE(0 == (rv = smsgModule.Validate((uint8_t*)&smsg, smsg.pPayload, smsg.nPayload)), \"SecureMsgValidate \" << rv);\n\n        BOOST_CHECK_MESSAGE(0 == (rv = smsgModule.Decrypt(false, kTo, smsg, msg)), \"SecureMsgDecrypt \" << rv);\n\n        BOOST_CHECK(msg.vchMessage.size()-1 == sTestMessage.size()\n            && 0 == memcmp(&msg.vchMessage[0], sTestMessage.data(), msg.vchMessage.size()-1));\n\n        rv = smsgModule.Decrypt(false, kFail, smsg, msg);\n        BOOST_CHECK_MESSAGE(smsg::SMSG_MAC_MISMATCH == rv, \"SecureMsgDecrypt \" << smsg::GetString(rv));\n    }\n\n    smsgModule.Shutdown();\n}\n#endif\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c87b441ca6b8ff98082d64dda1b0c332cd581b59", "size": 4527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/smsg_tests.cpp", "max_stars_repo_name": "dmuralov/falcon", "max_stars_repo_head_hexsha": "53aa5b40e77fbee40507e9d71339341f0a91d6c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-07T13:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T08:56:05.000Z", "max_issues_repo_path": "src/test/smsg_tests.cpp", "max_issues_repo_name": "dmuralov/falcon", "max_issues_repo_head_hexsha": "53aa5b40e77fbee40507e9d71339341f0a91d6c3", "max_issues_repo_licenses": ["MIT"], "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/smsg_tests.cpp", "max_forks_repo_name": "dmuralov/falcon", "max_forks_repo_head_hexsha": "53aa5b40e77fbee40507e9d71339341f0a91d6c3", "max_forks_repo_licenses": ["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.8230769231, "max_line_length": 145, "alphanum_fraction": 0.6684338414, "num_tokens": 1334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406758018019, "lm_q1q2_score": 0.1931938327590141}}
{"text": "// copyright (c) 2009-2014 the moorecoin core developers\n// distributed under the mit software license, see the accompanying\n// file copying or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"checkpoints.h\"\n\n#include \"chainparams.h\"\n#include \"main.h\"\n#include \"uint256.h\"\n\n#include <stdint.h>\n\n#include <boost/foreach.hpp>\n\nnamespace checkpoints {\n\n    /**\n     * how many times slower we expect checking transactions after the last\n     * checkpoint to be (from checking signatures, which is skipped up to the\n     * last checkpoint). this number is a compromise, as it can't be accurate\n     * for every system. when reindexing from a fast disk with a slow cpu, it\n     * can be up to 20, while when downloading from a slow network with a\n     * fast multicore cpu, it won't be much higher than 1.\n     */\n    static const double sigcheck_verification_factor = 5.0;\n\n    //! guess how far we are in the verification process at the given block index\n    double guessverificationprogress(const ccheckpointdata& data, cblockindex *pindex, bool fsigchecks) {\n        if (pindex==null)\n            return 0.0;\n\n        int64_t nnow = time(null);\n\n        double fsigcheckverificationfactor = fsigchecks ? sigcheck_verification_factor : 1.0;\n        double fworkbefore = 0.0; // amount of work done before pindex\n        double fworkafter = 0.0;  // amount of work left after pindex (estimated)\n        // work is defined as: 1.0 per transaction before the last checkpoint, and\n        // fsigcheckverificationfactor per transaction after.\n\n        if (pindex->nchaintx <= data.ntransactionslastcheckpoint) {\n            double ncheapbefore = pindex->nchaintx;\n            double ncheapafter = data.ntransactionslastcheckpoint - pindex->nchaintx;\n            double nexpensiveafter = (nnow - data.ntimelastcheckpoint)/86400.0*data.ftransactionsperday;\n            fworkbefore = ncheapbefore;\n            fworkafter = ncheapafter + nexpensiveafter*fsigcheckverificationfactor;\n        } else {\n            double ncheapbefore = data.ntransactionslastcheckpoint;\n            double nexpensivebefore = pindex->nchaintx - data.ntransactionslastcheckpoint;\n            double nexpensiveafter = (nnow - pindex->getblocktime())/86400.0*data.ftransactionsperday;\n            fworkbefore = ncheapbefore + nexpensivebefore*fsigcheckverificationfactor;\n            fworkafter = nexpensiveafter*fsigcheckverificationfactor;\n        }\n\n        return fworkbefore / (fworkbefore + fworkafter);\n    }\n\n    int gettotalblocksestimate(const ccheckpointdata& data)\n    {\n        const mapcheckpoints& checkpoints = data.mapcheckpoints;\n\n        if (checkpoints.empty())\n            return 0;\n\n        return checkpoints.rbegin()->first;\n    }\n\n    cblockindex* getlastcheckpoint(const ccheckpointdata& data)\n    {\n        const mapcheckpoints& checkpoints = data.mapcheckpoints;\n\n        boost_reverse_foreach(const mapcheckpoints::value_type& i, checkpoints)\n        {\n            const uint256& hash = i.second;\n            blockmap::const_iterator t = mapblockindex.find(hash);\n            if (t != mapblockindex.end())\n                return t->second;\n        }\n        return null;\n    }\n\n} // namespace checkpoints\n", "meta": {"hexsha": "7bef8ffd7f615a6e9083507231ff1acd2d1a5e13", "size": 3215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/checkpoints.cpp", "max_stars_repo_name": "moorecoin/MooreCoinMiningAlgorithm", "max_stars_repo_head_hexsha": "fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d", "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/checkpoints.cpp", "max_issues_repo_name": "moorecoin/MooreCoinMiningAlgorithm", "max_issues_repo_head_hexsha": "fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d", "max_issues_repo_licenses": ["MIT"], "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/checkpoints.cpp", "max_forks_repo_name": "moorecoin/MooreCoinMiningAlgorithm", "max_forks_repo_head_hexsha": "fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d", "max_forks_repo_licenses": ["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.2073170732, "max_line_length": 105, "alphanum_fraction": 0.6818040435, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1931938291751268}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2019, University of Stuttgart\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 University of Stuttgart 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#include <ompl/geometric/planners/quotientspace/algorithms/QRRTImpl.h>\n#include <ompl/tools/config/SelfConfig.h>\n#include <boost/foreach.hpp>\n\n#define foreach BOOST_FOREACH\n\nompl::geometric::QRRTImpl::QRRTImpl(const base::SpaceInformationPtr &si, QuotientSpace *parent_) : BaseT(si, parent_)\n{\n    setName(\"QRRTImpl\" + std::to_string(id_));\n    Planner::declareParam<double>(\"range\", this, &QRRTImpl::setRange, &QRRTImpl::getRange, \"0.:1.:10000.\");\n    Planner::declareParam<double>(\"goal_bias\", this, &QRRTImpl::setGoalBias, &QRRTImpl::getGoalBias, \"0.:.1:1.\");\n    qRandom_ = new Configuration(Q1);\n}\n\nompl::geometric::QRRTImpl::~QRRTImpl()\n{\n    deleteConfiguration(qRandom_);\n}\n\nvoid ompl::geometric::QRRTImpl::setGoalBias(double goalBias)\n{\n    goalBias_ = goalBias;\n}\n\ndouble ompl::geometric::QRRTImpl::getGoalBias() const\n{\n    return goalBias_;\n}\n\nvoid ompl::geometric::QRRTImpl::setRange(double maxDistance)\n{\n    maxDistance_ = maxDistance;\n}\n\ndouble ompl::geometric::QRRTImpl::getRange() const\n{\n    return maxDistance_;\n}\n\nvoid ompl::geometric::QRRTImpl::setup()\n{\n    BaseT::setup();\n    ompl::tools::SelfConfig sc(Q1, getName());\n    sc.configurePlannerRange(maxDistance_);\n    goal_ = pdef_->getGoal().get();\n}\n\nvoid ompl::geometric::QRRTImpl::clear()\n{\n    BaseT::clear();\n}\n\nbool ompl::geometric::QRRTImpl::getSolution(base::PathPtr &solution)\n{\n    if (hasSolution_)\n    {\n        bool baset_sol = BaseT::getSolution(solution);\n        if (baset_sol)\n        {\n            shortestPathVertices_ = shortestVertexPath_;\n        }\n        return baset_sol;\n    }\n    else\n    {\n        return false;\n    }\n}\n\nvoid ompl::geometric::QRRTImpl::grow()\n{\n    if (firstRun_)\n    {\n        init();\n        firstRun_ = false;\n    }\n\n    if (hasSolution_)\n    {\n        // No Goal Biasing if we already found a solution on this quotient space\n        sample(qRandom_->state);\n    }\n    else\n    {\n        double s = rng_.uniform01();\n        if (s < goalBias_)\n        {\n            Q1->copyState(qRandom_->state, qGoal_->state);\n        }\n        else\n        {\n            sample(qRandom_->state);\n        }\n    }\n\n    const Configuration *q_nearest = nearest(qRandom_);\n    double d = Q1->distance(q_nearest->state, qRandom_->state);\n    if (d > maxDistance_)\n    {\n        Q1->getStateSpace()->interpolate(q_nearest->state, qRandom_->state, maxDistance_ / d, qRandom_->state);\n    }\n\n    totalNumberOfSamples_++;\n    if (Q1->checkMotion(q_nearest->state, qRandom_->state))\n    {\n        totalNumberOfFeasibleSamples_++;\n        Configuration *q_next = new Configuration(Q1, qRandom_->state);\n        Vertex v_next = addConfiguration(q_next);\n        if (!hasSolution_)\n        {\n            // only add edge if no solution exists\n            addEdge(q_nearest->index, v_next);\n\n            double dist = 0.0;\n            bool satisfied = goal_->isSatisfied(q_next->state, &dist);\n            if (satisfied)\n            {\n                vGoal_ = addConfiguration(qGoal_);\n                addEdge(q_nearest->index, vGoal_);\n                hasSolution_ = true;\n            }\n        }\n    }\n}\n\ndouble ompl::geometric::QRRTImpl::getImportance() const\n{\n    // Should depend on\n    // (1) level : The higher the level, the more importance\n    // (2) total samples: the more we already sampled, the less important it\n    // becomes\n    // (3) has solution: if it already has a solution, we should explore less\n    // (only when nothing happens on other levels)\n    // (4) vertices: the more vertices we have, the less important (let other\n    // levels also explore)\n    //\n    // exponentially more samples on level i. Should depend on ALL levels.\n    // const double base = 2;\n    // const double normalizer = powf(base, level);\n    // double N = (double)GetNumberOfVertices()/normalizer;\n    double N = (double)getNumberOfVertices();\n    return 1.0 / (N + 1);\n}\n\n// Make it faster by removing the validity check\nbool ompl::geometric::QRRTImpl::sample(base::State *q_random)\n{\n    if (parent_ == nullptr)\n    {\n        Q1_sampler_->sampleUniform(q_random);\n    }\n    else\n    {\n        if (X1_dimension_ > 0)\n        {\n            X1_sampler_->sampleUniform(s_X1_tmp_);\n            parent_->sampleQuotient(s_Q0_tmp_);\n            mergeStates(s_Q0_tmp_, s_X1_tmp_, q_random);\n        }\n        else\n        {\n            parent_->sampleQuotient(q_random);\n        }\n    }\n    return true;\n}\n\nbool ompl::geometric::QRRTImpl::sampleQuotient(base::State *q_random_graph)\n{\n    // RANDOM VERTEX SAMPLING\n    const Vertex v = boost::random_vertex(graph_, rng_boost);\n    Q1->getStateSpace()->copyState(q_random_graph, graph_[v]->state);\n    return true;\n}\n", "meta": {"hexsha": "1714e78f5ec5c5b1f4c8755a25902e2d796c735e", "size": 6511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/geometric/planners/quotientspace/algorithms/src/QRRTImpl.cpp", "max_stars_repo_name": "ericpairet/ompl", "max_stars_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "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/geometric/planners/quotientspace/algorithms/src/QRRTImpl.cpp", "max_issues_repo_name": "ericpairet/ompl", "max_issues_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "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/geometric/planners/quotientspace/algorithms/src/QRRTImpl.cpp", "max_forks_repo_name": "ericpairet/ompl", "max_forks_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "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": 30.8578199052, "max_line_length": 117, "alphanum_fraction": 0.6422976501, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1931938291751268}}
{"text": "// This file is part of CBOR-lite which is copyright Isode Limited\n// and others and released under a MIT license. For details, see the\n// COPYRIGHT.md file in the top-level folder of the CBOR-lite software\n// distribution.\n#include \"../include/cbor-lite/codec.h\"\n#include <boost/test/unit_test.hpp>\n#include <tuple>\n\nBOOST_AUTO_TEST_SUITE(cbor_lite)\nBOOST_AUTO_TEST_SUITE(codec)\n\nBOOST_AUTO_TEST_CASE(non_negative) {\n    const std::vector<std::pair<std::uint_fast64_t, const std::string>> cases{\n        {0u, std::string(\"\\x00\", 1)},\n        {1u, \"\\x01\"},\n        {10u, \"\\x0a\"},\n        {23u, \"\\x17\"},\n        {24u, \"\\x18\\x18\"},\n        {25u, \"\\x18\\x19\"},\n        {100u, \"\\x18\\x64\"},\n        {1000u, \"\\x19\\x03\\xe8\"},\n        {1000000u, std::string(\"\\x1a\\x00\\x0f\\x42\\x40\", 5)},\n        {1000000000000u, std::string(\"\\x1b\\x00\\x00\\x00\\xe8\\xd4\\xa5\\x10\\x00\", 9)},\n        {18446744073709551615u, std::string(\"\\x1b\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\", 9)},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeUnsigned(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n            std::uint_fast64_t value = 0u;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeUnsigned(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n        });\n    }\n}\n\nBOOST_AUTO_TEST_CASE(negative) {\n    const std::vector<std::pair<std::uint_fast64_t, const std::string>> cases{\n        {0, \"\\x20\"},\n        {9, \"\\x29\"},\n        {99, \"\\x38\\x63\"},\n        {999, \"\\x39\\x03\\xe7\"},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeNegative(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n            std::uint_fast64_t value = 0u;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeNegative(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n        });\n    }\n}\n\nBOOST_AUTO_TEST_CASE(integer) {\n    const std::vector<std::pair<std::int_fast64_t, const std::string>> cases{\n        {0, std::string(\"\\x00\", 1)},\n        {1, \"\\x01\"},\n        {10, \"\\x0a\"},\n        {23, \"\\x17\"},\n        {24, \"\\x18\\x18\"},\n        {25, \"\\x18\\x19\"},\n        {100, \"\\x18\\x64\"},\n        {1000, \"\\x19\\x03\\xe8\"},\n        {1000000, std::string(\"\\x1a\\x00\\x0f\\x42\\x40\", 5)},\n        {1000000000000, std::string(\"\\x1b\\x00\\x00\\x00\\xe8\\xd4\\xa5\\x10\\x00\", 9)},\n        {-1, \"\\x20\"},\n        {-10, \"\\x29\"},\n        {-100, \"\\x38\\x63\"},\n        {-1000, \"\\x39\\x03\\xe7\"},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeInteger(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n            std::int_fast64_t value = 0;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeInteger(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n        });\n    }\n}\n\nBOOST_AUTO_TEST_CASE(boolean) {\n    const std::vector<std::pair<bool, const std::string>> cases{\n        {false, \"\\xf4\"},\n        {true, \"\\xf5\"},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeBool(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n            auto value = false;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeBool(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n        });\n    }\n}\n\nBOOST_AUTO_TEST_CASE(bytes) {\n    const std::vector<std::pair<const std::string, const std::string>> cases{\n        {\"\", \"\\x40\"},\n        {\"a\", \"\\x41\\x61\"},\n        {\"A\", \"\\x41\\x41\"},\n        {\"IETF\", \"\\x44\\x49\\x45\\x54\\x46\"},\n        {\"\\\"\\\\\", \"\\x42\\x22\\x5c\"},\n        {\"\\xc3\\xbc\", \"\\x42\\xc3\\xbc\"},\n        {\"\\xe6\\xb0\\xb4\", \"\\x43\\xe6\\xb0\\xb4\"},\n        {\"\\xf0\\x90\\x85\\x91\", \"\\x44\\xf0\\x90\\x85\\x91\"},\n        {\"\\x01\\x02\\x03\\x04\", \"\\x44\\x01\\x02\\x03\\x04\"},\n        {\"@@@@\", \"\\x44\\x40\\x40\\x40\\x40\"},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeBytes(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n            std::string value;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeBytes(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n        });\n    }\n    BOOST_CHECK_NO_THROW({\n        std::vector<char> buffer;\n        std::string input = \"@@@@\";\n        std::vector<char> payload(std::begin(input), std::end(input));\n        auto len = CborLite::encodeBytes(buffer, payload);\n        std::string expect = \"\\x44\\x40\\x40\\x40\\x40\";\n        BOOST_CHECK_EQUAL(len, expect.length());\n        BOOST_CHECK_EQUAL(std::string(std::begin(buffer), std::end(buffer)), expect);\n    });\n}\n\nBOOST_AUTO_TEST_CASE(encodedBytes) {\n    const std::vector<std::pair<const std::string, const std::string>> cases{\n        {\"\", \"\\xd8\\x18\\x40\"},\n        {\"a\", \"\\xd8\\x18\\x41\\x61\"},\n        {\"A\", \"\\xd8\\x18\\x41\\x41\"},\n        {\"IETF\", \"\\xd8\\x18\\x44\\x49\\x45\\x54\\x46\"},\n        {\"\\\"\\\\\", \"\\xd8\\x18\\x42\\x22\\x5c\"},\n        {\"\\xc3\\xbc\", \"\\xd8\\x18\\x42\\xc3\\xbc\"},\n        {\"\\xe6\\xb0\\xb4\", \"\\xd8\\x18\\x43\\xe6\\xb0\\xb4\"},\n        {\"\\xf0\\x90\\x85\\x91\", \"\\xd8\\x18\\x44\\xf0\\x90\\x85\\x91\"},\n        {\"\\x01\\x02\\x03\\x04\", \"\\xd8\\x18\\x44\\x01\\x02\\x03\\x04\"},\n        {\"@@@@\", \"\\xd8\\x18\\x44\\x40\\x40\\x40\\x40\"},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeEncodedBytes(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n\n            buffer.clear();\n            len = CborLite::encodeEncodedBytesPrefix(buffer, test.first.length());\n            BOOST_CHECK_EQUAL(len, 3);\n            BOOST_CHECK_EQUAL(buffer, test.second.substr(0, 3));\n\n            std::string value;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeEncodedBytes(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n\n            std::size_t got = 0u;\n            pos = std::begin(test.second);\n            len = CborLite::decodeEncodedBytesPrefix(pos, pos + 3, got);\n            BOOST_CHECK_EQUAL(len, 3);\n            BOOST_CHECK_EQUAL(got, test.first.length());\n        });\n    }\n    BOOST_CHECK_NO_THROW({\n        std::vector<char> buffer;\n        std::string input = \"@@@@\";\n        std::vector<char> payload(std::begin(input), std::end(input));\n        auto len = CborLite::encodeEncodedBytes(buffer, payload);\n        std::string expect = \"\\xd8\\x18\\x44\\x40\\x40\\x40\\x40\";\n        BOOST_CHECK_EQUAL(len, expect.length());\n        BOOST_CHECK_EQUAL(std::string(std::begin(buffer), std::end(buffer)), expect);\n    });\n}\n\nBOOST_AUTO_TEST_CASE(strings) {\n    const std::vector<std::pair<const std::string, const std::string>> cases{\n        {\"\", \"\\x60\"},\n        {\"a\", \"\\x61\\x61\"},\n        {\"A\", \"\\x61\\x41\"},\n        {\"IETF\", \"\\x64\\x49\\x45\\x54\\x46\"},\n        {\"\\\"\\\\\", \"\\x62\\x22\\x5c\"},\n        {\"\\xc3\\xbc\", \"\\x62\\xc3\\xbc\"},\n        {\"\\xe6\\xb0\\xb4\", \"\\x63\\xe6\\xb0\\xb4\"},\n        {\"\\xf0\\x90\\x85\\x91\", \"\\x64\\xf0\\x90\\x85\\x91\"},\n        {\"\\x01\\x02\\x03\\x04\", \"\\x64\\x01\\x02\\x03\\x04\"},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeText(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n            std::string value;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeText(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n        });\n    }\n}\n\nBOOST_AUTO_TEST_CASE(array) {\n    const std::vector<std::pair<std::uint_fast64_t, const std::string>> cases{\n        {0u, \"\\x80\"},\n        {1u, \"\\x81\"},\n        {10u, \"\\x8a\"},\n        {23u, \"\\x97\"},\n        {24u, \"\\x98\\x18\"},\n        {25u, \"\\x98\\x19\"},\n        {100u, \"\\x98\\x64\"},\n        {1000u, \"\\x99\\x03\\xe8\"},\n        {1000000u, std::string(\"\\x9a\\x00\\x0f\\x42\\x40\", 5)},\n        {1000000000000u, std::string(\"\\x9b\\x00\\x00\\x00\\xe8\\xd4\\xa5\\x10\\x00\", 9)},\n        {18446744073709551615u, std::string(\"\\x9b\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\", 9)},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeArraySize(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n            unsigned long long value = 0;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeArraySize(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n        });\n    }\n}\n\nBOOST_AUTO_TEST_CASE(map) {\n    const std::vector<std::pair<std::uint_fast64_t, const std::string>> cases{\n        {0u, \"\\xa0\"},\n        {1u, \"\\xa1\"},\n        {10u, \"\\xaa\"},\n        {23u, \"\\xb7\"},\n        {24u, \"\\xb8\\x18\"},\n        {25u, \"\\xb8\\x19\"},\n        {100u, \"\\xb8\\x64\"},\n        {1000u, \"\\xb9\\x03\\xe8\"},\n        {1000000u, std::string(\"\\xba\\x00\\x0f\\x42\\x40\", 5)},\n        {1000000000000u, std::string(\"\\xbb\\x00\\x00\\x00\\xe8\\xd4\\xa5\\x10\\x00\", 9)},\n        {18446744073709551615u, std::string(\"\\xbb\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\", 9)},\n    };\n    for (const auto& test : cases) {\n        BOOST_CHECK_NO_THROW({\n            std::string buffer;\n            auto len = CborLite::encodeMapSize(buffer, test.first);\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(buffer, test.second);\n            unsigned long long value = 0;\n            auto pos = std::begin(test.second);\n            len = CborLite::decodeMapSize(pos, std::end(test.second), value);\n            BOOST_CHECK(pos == std::end(test.second));\n            BOOST_CHECK_EQUAL(len, test.second.size());\n            BOOST_CHECK_EQUAL(value, test.first);\n        });\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e30428d467839bf4f3bee7d1027db438707ac3d4", "size": 11530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "roswasm/external/cbor-lite/unit/codec.cpp", "max_stars_repo_name": "Jollerprutt/roswasm_suite", "max_stars_repo_head_hexsha": "bc623a894273a8febf7912bcba5265e80ef1f023", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 42.0, "max_stars_repo_stars_event_min_datetime": "2020-05-31T20:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:19:46.000Z", "max_issues_repo_path": "roswasm/external/cbor-lite/unit/codec.cpp", "max_issues_repo_name": "Jollerprutt/roswasm_suite", "max_issues_repo_head_hexsha": "bc623a894273a8febf7912bcba5265e80ef1f023", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T18:22:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T19:32:47.000Z", "max_forks_repo_path": "roswasm/external/cbor-lite/unit/codec.cpp", "max_forks_repo_name": "Jollerprutt/roswasm_suite", "max_forks_repo_head_hexsha": "bc623a894273a8febf7912bcba5265e80ef1f023", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T01:57:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T15:53:28.000Z", "avg_line_length": 38.8215488215, "max_line_length": 88, "alphanum_fraction": 0.553859497, "num_tokens": 3126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1931938291751268}}
{"text": "#pragma once\n\n#include <nano/lib/config.hpp>\n#include <nano/lib/locks.hpp>\n#include <nano/lib/numbers.hpp>\n#include <nano/lib/utility.hpp>\n\n#include <boost/optional.hpp>\n#include <boost/thread/thread.hpp>\n\n#include <atomic>\n#include <memory>\n\nnamespace nano\n{\nenum class work_version\n{\n\tunspecified,\n\twork_1\n};\nstd::string to_string (nano::work_version const version_a);\n\nclass block;\nclass block_details;\nenum class block_type : uint8_t;\nbool work_validate_entry (nano::block const &);\nbool work_validate_entry (nano::work_version const, nano::root const &, uint64_t const);\n\nuint64_t work_difficulty (nano::work_version const, nano::root const &, uint64_t const);\n\nuint64_t work_threshold_base (nano::work_version const);\nuint64_t work_threshold_entry (nano::work_version const, nano::block_type const);\n// Ledger threshold\nuint64_t work_threshold (nano::work_version const, nano::block_details const);\n\nnamespace work_v1\n{\n\tuint64_t value (nano::root const & root_a, uint64_t work_a);\n\tuint64_t threshold_base ();\n\tuint64_t threshold_entry ();\n\tuint64_t threshold (nano::block_details const);\n}\n\ndouble normalized_multiplier (double const, uint64_t const);\ndouble denormalized_multiplier (double const, uint64_t const);\nclass opencl_work;\nclass work_item final\n{\npublic:\n\twork_item (nano::work_version const version_a, nano::root const & item_a, uint64_t difficulty_a, std::function<void(boost::optional<uint64_t> const &)> const & callback_a) :\n\tversion (version_a), item (item_a), difficulty (difficulty_a), callback (callback_a)\n\t{\n\t}\n\tnano::work_version const version;\n\tnano::root const item;\n\tuint64_t const difficulty;\n\tstd::function<void(boost::optional<uint64_t> const &)> const callback;\n};\nclass work_pool final\n{\npublic:\n\twork_pool (unsigned, std::chrono::nanoseconds = std::chrono::nanoseconds (0), std::function<boost::optional<uint64_t> (nano::work_version const, nano::root const &, uint64_t, std::atomic<int> &)> = nullptr);\n\t~work_pool ();\n\tvoid loop (uint64_t);\n\tvoid stop ();\n\tvoid cancel (nano::root const &);\n\tvoid generate (nano::work_version const, nano::root const &, uint64_t, std::function<void(boost::optional<uint64_t> const &)>);\n\tboost::optional<uint64_t> generate (nano::work_version const, nano::root const &, uint64_t);\n\t// For tests only\n\tboost::optional<uint64_t> generate (nano::root const &);\n\tboost::optional<uint64_t> generate (nano::root const &, uint64_t);\n\tsize_t size ();\n\tnano::network_constants network_constants;\n\tstd::atomic<int> ticket;\n\tbool done;\n\tstd::vector<boost::thread> threads;\n\tstd::list<nano::work_item> pending;\n\tstd::mutex mutex;\n\tnano::condition_variable producer_condition;\n\tstd::chrono::nanoseconds pow_rate_limiter;\n\tstd::function<boost::optional<uint64_t> (nano::work_version const, nano::root const &, uint64_t, std::atomic<int> &)> opencl;\n\tnano::observer_set<bool> work_observers;\n};\n\nstd::unique_ptr<container_info_component> collect_container_info (work_pool & work_pool, const std::string & name);\n}\n", "meta": {"hexsha": "d518fc4a22b08b1ac5c9a4c4cf134fc47dcb794e", "size": 2974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nano/lib/work.hpp", "max_stars_repo_name": "LenWilliamson/nano-node", "max_stars_repo_head_hexsha": "27b206cac571c8937da3f73df1cb8c1c230977fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-13T12:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T15:57:11.000Z", "max_issues_repo_path": "nano/lib/work.hpp", "max_issues_repo_name": "LenWilliamson/nano-node", "max_issues_repo_head_hexsha": "27b206cac571c8937da3f73df1cb8c1c230977fd", "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": "nano/lib/work.hpp", "max_forks_repo_name": "LenWilliamson/nano-node", "max_forks_repo_head_hexsha": "27b206cac571c8937da3f73df1cb8c1c230977fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-15T19:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-15T19:43:31.000Z", "avg_line_length": 34.183908046, "max_line_length": 208, "alphanum_fraction": 0.7592468056, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19319382917512676}}
{"text": "\n#include \"MechanicsFwd.hpp\"\n#include \"NewtonEulerDS.hpp\"\n#include \"BodyDS.hpp\"\n#include \"SiconosContactor.hpp\"\n\n#include <boost/make_shared.hpp>\n\nBodyDS::BodyDS(SP::SiconosVector position,\n               SP::SiconosVector velocity,\n               double mass,\n               SP::SimpleMatrix inertia)\n  : NewtonEulerDS(position, velocity, mass, inertia)\n  , _contactors(std11::make_shared<SiconosContactorSet>())\n  , _useContactorInertia(true)\n  , _allowSelfCollide(true)\n{\n}\n\nBodyDS::~BodyDS()\n{\n}\n", "meta": {"hexsha": "e5b21871d73778cf353538345628e53b24e5835c", "size": 500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mechanics/src/collision/BodyDS.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": "mechanics/src/collision/BodyDS.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": "mechanics/src/collision/BodyDS.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": 21.7391304348, "max_line_length": 58, "alphanum_fraction": 0.69, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.19319382559123954}}
{"text": "\n#include <NTL/GF2X.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\nvoid print_flag()\n{\n\n\n#ifdef NTL_GF2X_ALTCODE\nprintf(\"NTL_GF2X_ALTCODE \");\n#endif\n\n\n#ifdef NTL_GF2X_ALTCODE1\nprintf(\"NTL_GF2X_ALTCODE1 \");\n#endif\n\n\n#ifdef NTL_GF2X_NOINLINE\nprintf(\"NTL_GF2X_NOINLINE \");\n#endif\n\n\nprintf(\"\\n\");\n\n}\n\nint main()\n{\n   long n, i, j, iter, s, k;\n   double t;\n\n   SetSeed(ZZ(0));\n\n\n   for (i = 0; i < 10000; i++) {\n      GF2X a, b, c, d;\n      long da = RandomBnd(5*NTL_BITS_PER_LONG);\n      long db = RandomBnd(5*NTL_BITS_PER_LONG);\n      long dc = RandomBnd(5*NTL_BITS_PER_LONG);\n      long dd = RandomBnd(5*NTL_BITS_PER_LONG);\n      random(a, da);  random(b, db);  random(c, dc);  random(d, dd);\n\n      if ((a + b)*(c + d) != c*a + d*a + c*b + d*b) {\n\t printf(\"999999999999999 \");\n\t print_flag();\n\t return 0;\n      }\n   }\n   \n\n   n = 16;\n   s = 56;\n\n   GF2X *a = new GF2X[s];\n   GF2X *b = new GF2X[s];\n\n   GF2X c;\n\n   for (k = 0; k < s; k++) {\n      random(a[k], (n + (k % 7))*NTL_BITS_PER_LONG);\n      random(b[k], (n + (k % 8))*NTL_BITS_PER_LONG);\n   }\n\n   for (k = 0; k < s; k++) mul(c, a[k], b[k]);\n\n\n   iter = 1;\n\n   do {\n     t = GetTime();\n     for (i = 0; i < iter; i++) {\n        for (j = 0; j < 1; j++) for (k = 0; k < s; k++) mul(c, a[k], b[k]);\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   double tvec[5];\n   long w;\n\n   for (w = 0; w < 5; w++) {\n     t = GetTime();\n     for (i = 0; i < iter; i++) {\n        for (j = 0; j < 1; j++) for (k = 0; k < s; k++) mul(c, a[k], b[k]);\n     }\n     t = GetTime() - t;\n     tvec[w] = t;\n   }\n\n\n   t = clean_data(tvec);\n\n   t = floor((t/iter)*1e14);\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   \n\n", "meta": {"hexsha": "f6ca8698322a2ef3e331ae35eb74c4a6af71f726", "size": 2243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2XTimeTest.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/GF2XTimeTest.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/GF2XTimeTest.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": 15.3630136986, "max_line_length": 75, "alphanum_fraction": 0.4480606331, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.19319382200735233}}
{"text": "#pragma once\n\n#include <src/common.hpp>\n#include <src/lib/interface.h>\n\n#include <boost/asio.hpp>\n\n#include <bitset>\n\n#include <xxhash/xxhash.h>\n\n#include <src/lib/epoch.h>\n#include <unordered_set>\n\nnamespace germ\n{\nusing endpoint = boost::asio::ip::udp::endpoint;\nbool parse_port (std::string const &, uint16_t &);\nbool parse_address_port (std::string const &, boost::asio::ip::address &, uint16_t &);\nusing tcp_endpoint = boost::asio::ip::tcp::endpoint;\nbool parse_endpoint (std::string const &, germ::endpoint &);\nbool parse_tcp_endpoint (std::string const &, germ::tcp_endpoint &);\nbool reserved_address (germ::endpoint const &, bool);\n}\nstatic uint64_t endpoint_hash_raw (germ::endpoint const & endpoint_a)\n{\n    assert (endpoint_a.address ().is_v6 ());\n    germ::uint128_union address;\n    address.bytes = endpoint_a.address ().to_v6 ().to_bytes ();\n    XXH64_state_t hash;\n    XXH64_reset (&hash, 0);\n    XXH64_update (&hash, address.bytes.data (), address.bytes.size ());\n    auto port (endpoint_a.port ());\n    XXH64_update (&hash, &port, sizeof (port));\n    auto result (XXH64_digest (&hash));\n    return result;\n}\nstatic uint64_t ip_address_hash_raw (boost::asio::ip::address const & ip_a)\n{\n    assert (ip_a.is_v6 ());\n    germ::uint128_union bytes;\n    bytes.bytes = ip_a.to_v6 ().to_bytes ();\n    XXH64_state_t hash;\n    XXH64_reset (&hash, 0);\n    XXH64_update (&hash, bytes.bytes.data (), bytes.bytes.size ());\n    auto result (XXH64_digest (&hash));\n    return result;\n}\n\nnamespace std\n{\ntemplate <size_t size>\nstruct endpoint_hash\n{\n};\ntemplate <>\nstruct endpoint_hash<8>\n{\n    size_t operator() (germ::endpoint const & endpoint_a) const\n    {\n        return endpoint_hash_raw (endpoint_a);\n    }\n};\ntemplate <>\nstruct endpoint_hash<4>\n{\n    size_t operator() (germ::endpoint const & endpoint_a) const\n    {\n        uint64_t big (endpoint_hash_raw (endpoint_a));\n        uint32_t result (static_cast<uint32_t> (big) ^ static_cast<uint32_t> (big >> 32));\n        return result;\n    }\n};\ntemplate <>\nstruct hash<germ::endpoint>\n{\n    size_t operator() (germ::endpoint const & endpoint_a) const\n    {\n        endpoint_hash<sizeof (size_t)> ehash;\n        return ehash (endpoint_a);\n    }\n};\ntemplate <size_t size>\nstruct ip_address_hash\n{\n};\ntemplate <>\nstruct ip_address_hash<8>\n{\n    size_t operator() (boost::asio::ip::address const & ip_address_a) const\n    {\n        return ip_address_hash_raw (ip_address_a);\n    }\n};\ntemplate <>\nstruct ip_address_hash<4>\n{\n    size_t operator() (boost::asio::ip::address const & ip_address_a) const\n    {\n        uint64_t big (ip_address_hash_raw (ip_address_a));\n        uint32_t result (static_cast<uint32_t> (big) ^ static_cast<uint32_t> (big >> 32));\n        return result;\n    }\n};\ntemplate <>\nstruct hash<boost::asio::ip::address>\n{\n    size_t operator() (boost::asio::ip::address const & ip_a) const\n    {\n        ip_address_hash<sizeof (size_t)> ihash;\n        return ihash (ip_a);\n    }\n};\n}\nnamespace boost\n{\ntemplate <>\nstruct hash<germ::endpoint>\n{\n    size_t operator() (germ::endpoint const & endpoint_a) const\n    {\n        std::hash<germ::endpoint> hash;\n        return hash (endpoint_a);\n    }\n};\n}\n\nnamespace germ\n{\nenum class message_type : uint8_t\n{\n    invalid,\n    not_a_type,\n    keepalive,\n    publish,\n    confirm_req,\n    confirm_ack,\n    bulk_pull,\n    bulk_push,\n    frontier_req,\n    bulk_pull_blocks,\n    node_id_handshake,\n    epoch_req,\n    epoch_bulk_pull,\n    epoch_bulk_push,\n    transaction\n};\nenum class bulk_pull_blocks_mode : uint8_t\n{\n    list_blocks,\n    checksum_blocks\n};\nclass message_visitor;\nclass message_header\n{\npublic:\n    message_header (germ::message_type, size_t body_size_a);\n    message_header (bool &, germ::stream &);\n    void serialize (germ::stream &);\n    bool deserialize (germ::stream &);\n    germ::block_type block_type () const;\n    void block_type_set (germ::block_type);\n    bool ipv4_only ();\n    void ipv4_only_set (bool);\n    static std::array<uint8_t, 2> constexpr magic_number = germ::rai_network == germ::germ_networks::germ_test_network ? std::array<uint8_t, 2>{ { 'R', 'A' } } : germ::rai_network == germ::germ_networks::germ_beta_network ? std::array<uint8_t, 2>{ { 'R', 'B' } } : std::array<uint8_t, 2>{ { 'R', 'C' } };\n    uint8_t version;\n    germ::message_type type;\n    std::bitset<16> extensions;\n    static size_t constexpr ipv4_only_position = 1;\n    static size_t constexpr bootstrap_server_position = 2;\n    static std::bitset<16> constexpr block_type_mask = std::bitset<16> (0x0f00);\n    size_t body_size;\n};\nclass message\n{\npublic:\n    message (germ::message_type, size_t);\n    message (germ::message_header const &);\n    virtual ~message () = default;\n    virtual void serialize (germ::stream &) = 0;\n    virtual bool deserialize (germ::stream &) = 0;\n    virtual void visit (germ::message_visitor &) const = 0;\n    germ::message_header header;\n};\nclass work_pool;\nclass message_parser\n{\npublic:\n    enum class parse_status\n    {\n        success,\n        invalid_header,\n        invalid_message_type,\n        invalid_keepalive_message,\n        invalid_publish_message,\n        invalid_confirm_req_message,\n        invalid_confirm_ack_message,\n        invalid_node_id_handshake_message,\n        invalid_epoch_req_message,\n        invalid_epoch_bulk_pull_message,\n        invalid_epoch_bulk_push_message,\n        invalid_transaction_message\n    };\n    message_parser (germ::message_visitor &, germ::work_pool &);\n    void deserialize_buffer (uint8_t const *, size_t);\n    void deserialize_keepalive (germ::stream &, germ::message_header const &);\n    void deserialize_publish (germ::stream &, germ::message_header const &);\n    void deserialize_confirm_req (germ::stream &, germ::message_header const &);\n    void deserialize_confirm_ack (germ::stream &, germ::message_header const &);\n    void deserialize_node_id_handshake (germ::stream &, germ::message_header const &);\n\n    void deserialize_epoch_req(germ::stream & stream_r, germ::message_header const & header_r);\n    void deserialize_epoch_bulk_pull(germ::stream & stream_r, germ::message_header const & header_r);\n    void deserialize_epoch_bulk_push(germ::stream & stream_r, germ::message_header const & header_r);\n\n    void deserialize_transaction(germ::stream & stream_r, germ::message_header const & header_r);\n\n    bool at_end (germ::stream &);\n    germ::message_visitor & visitor;\n    germ::work_pool & pool;\n    parse_status status;\n};\nclass keepalive : public message\n{\npublic:\n    keepalive (bool &, germ::stream &, germ::message_header const &);\n    keepalive ();\n    void visit (germ::message_visitor &) const override;\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    bool operator== (germ::keepalive const &) const;\n    std::array<germ::endpoint, 8> peers;\n};\nclass publish : public message\n{\npublic:\n    publish (bool &, germ::stream &, germ::message_header const &);\n    publish (std::shared_ptr<germ::tx>);\n    void visit (germ::message_visitor &) const override;\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    bool operator== (germ::publish const &) const;\n    std::shared_ptr<germ::tx> block;\n};\nclass confirm_req : public message\n{\npublic:\n    confirm_req (bool &, germ::stream &, germ::message_header const &);\n    confirm_req (std::shared_ptr<germ::tx>);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n    bool operator== (germ::confirm_req const &) const;\n    std::shared_ptr<germ::tx> block;\n};\nclass confirm_ack : public message\n{\npublic:\n    confirm_ack (bool &, germ::stream &, germ::message_header const &);\n    confirm_ack (std::shared_ptr<germ::vote>);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n    bool operator== (germ::confirm_ack const &) const;\n    std::shared_ptr<germ::vote> vote;\n};\nclass frontier_req : public message\n{\npublic:\n    frontier_req ();\n    frontier_req (bool &, germ::stream &, germ::message_header const &);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n    bool operator== (germ::frontier_req const &) const;\n    germ::account start;\n    uint32_t age;\n    uint32_t count;\n};\nclass bulk_pull : public message\n{\npublic:\n    bulk_pull ();\n    bulk_pull (bool &, germ::stream &, germ::message_header const &);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n    germ::uint256_union start;\n    germ::block_hash end;\n};\nclass bulk_pull_blocks : public message\n{\npublic:\n    bulk_pull_blocks ();\n    bulk_pull_blocks (bool &, germ::stream &, germ::message_header const &);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n    germ::block_hash min_hash;\n    germ::block_hash max_hash;\n    bulk_pull_blocks_mode mode;\n    uint32_t max_count;\n};\nclass bulk_push : public message\n{\npublic:\n    bulk_push ();\n    bulk_push (germ::message_header const &);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n};\nclass node_id_handshake : public message\n{\npublic:\n    node_id_handshake (bool &, germ::stream &, germ::message_header const &);\n    node_id_handshake (boost::optional<germ::block_hash>, boost::optional<std::pair<germ::account, germ::signature>>);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n    bool operator== (germ::node_id_handshake const &) const;\n    boost::optional<germ::uint256_union> query;\n    boost::optional<std::pair<germ::account, germ::signature>> response;\n    static size_t constexpr query_flag = 0;\n    static size_t constexpr response_flag = 1;\n};\n\nclass epoch_req : public message\n{\npublic:\n    epoch_req();\n    epoch_req(bool & error_r, germ::stream & stream_r, germ::message_header const & header_r);\n    bool deserialize (germ::stream & stream_r) override ;\n    void serialize (germ::stream & stream_r) override ;\n    void visit (germ::message_visitor & visit_r) const override ;\n    bool operator== (germ::epoch_req const & epoch) const;\n\n    germ::epoch_hash start;\n//    germ::epoch_hash end;\n    uint32_t age;\n    uint32_t count;\n};\n\nclass epoch_bulk_pull : public message\n{\npublic:\n    epoch_bulk_pull ();\n    epoch_bulk_pull (bool &, germ::stream &, germ::message_header const &);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n    germ::epoch_hash start;\n    germ::epoch_hash end;\n};\n\nclass epoch_bulk_push : public message\n{\npublic:\n    epoch_bulk_push ();\n    epoch_bulk_push (germ::message_header const &);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n};\n\nclass transaction_message : public message\n{\npublic:\n    transaction_message (bool &, germ::stream &, germ::message_header const &);\n    transaction_message (std::shared_ptr<germ::tx>);\n    bool deserialize (germ::stream &) override;\n    void serialize (germ::stream &) override;\n    void visit (germ::message_visitor &) const override;\n    bool operator== (germ::transaction_message const &) const;\n    std::shared_ptr<germ::tx> block;\n};\n\nclass message_visitor\n{\npublic:\n    virtual void keepalive (germ::keepalive const &) = 0;\n    virtual void publish (germ::publish const &) = 0;\n    virtual void confirm_req (germ::confirm_req const &) = 0;\n    virtual void confirm_ack (germ::confirm_ack const &) = 0;\n    virtual void bulk_pull (germ::bulk_pull const &) = 0;\n    virtual void bulk_pull_blocks (germ::bulk_pull_blocks const &) = 0;\n    virtual void bulk_push (germ::bulk_push const &) = 0;\n    virtual void frontier_req (germ::frontier_req const &) = 0;\n    virtual void node_id_handshake (germ::node_id_handshake const &) = 0;\n    virtual void epoch_req (germ::epoch_req const &) = 0;\n    virtual void epoch_bulk_pull (germ::epoch_bulk_pull const &) = 0;\n    virtual void epoch_bulk_push (germ::epoch_bulk_push const &) = 0;\n    virtual void transaction (germ::transaction_message const &) = 0;\n    \n    virtual ~message_visitor ();\n};\n\n/**\n * Returns seconds passed since unix epoch (posix time)\n */\ninline uint64_t seconds_since_epoch ()\n{\n    return std::chrono::duration_cast<std::chrono::seconds> (std::chrono::system_clock::now ().time_since_epoch ()).count ();\n}\n}\n", "meta": {"hexsha": "a18099dbdb057871608cdd1ff521e2c362f63b3a", "size": 12860, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/node/common.hpp", "max_stars_repo_name": "mar348/village", "max_stars_repo_head_hexsha": "fecc81b19018b1e9bf48c352696325869a2847a2", "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/node/common.hpp", "max_issues_repo_name": "mar348/village", "max_issues_repo_head_hexsha": "fecc81b19018b1e9bf48c352696325869a2847a2", "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/node/common.hpp", "max_forks_repo_name": "mar348/village", "max_forks_repo_head_hexsha": "fecc81b19018b1e9bf48c352696325869a2847a2", "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.6748768473, "max_line_length": 304, "alphanum_fraction": 0.6887247278, "num_tokens": 3212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19313713417939343}}
{"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/*-- DISCLAIMER AND CRITICAL APPLICATIONS */\n/*--\n * ---------------------------------------------------------------------------------------------------------------------*/\n/*-- */\n/*-- (c) Copyright 2019 Xilinx, Inc. All rights reserved. */\n/*-- */\n/*-- This file contains confidential and proprietary information of Xilinx, Inc. and is protected under U.S. and */\n/*-- international copyright and other intellectual property laws. */\n/*-- */\n/*-- DISCLAIMER */\n/*-- This disclaimer is not a license and does not grant any rights to the materials distributed herewith. Except as */\n/*-- otherwise provided in a valid license issued to you by Xilinx, and to the maximum extent permitted by applicable */\n/*-- law: (1) THESE MATERIALS ARE MADE AVAILABLE \"AS IS\" AND WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES\n */\n/*-- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- */\n/*-- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether in contract or\n * tort,*/\n/*-- including negligence, or under any other theory of liability) for any loss or damage of any kind or nature */\n/*-- related to, arising under or in connection with these materials, including for any direct, or any indirect, */\n/*-- special, incidental, or consequential loss or damage (including loss of data, profits, goodwill, or any type of */\n/*-- loss or damage suffered as a retVal of any action brought by a third party) even if such damage or loss was */\n/*-- reasonably foreseeable or Xilinx had been advised of the possibility of the same. */\n/*-- */\n/*-- CRITICAL APPLICATIONS */\n/*-- Xilinx products are not designed or intended to be fail-safe, or for use in any application requiring fail-safe */\n/*-- performance, such as life-support or safety devices or systems, Class III medical devices, nuclear facilities, */\n/*-- applications related to the deployment of airbags, or any other applications that could lead to death, personal */\n/*-- injury, or severe property or environmental damage (individually and collectively, \"Critical */\n/*-- Applications\"). Customer assumes the sole risk and liability of any use of Xilinx products in Critical */\n/*-- Applications, subject only to applicable laws and regulations governing limitations on product liability. */\n/*-- */\n/*-- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT ALL TIMES. */\n/*--\n * ---------------------------------------------------------------------------------------------------------------------*/\n\n#include <stdio.h>\n#include <string.h>\n\n#include <chrono>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n\n#include \"xf_fintech_api.hpp\"\n#include \"models/xf_fintech_fdbslv.hpp\"\nusing namespace xf::fintech;\n\nstruct testcaseParams {\n    unsigned int solverN;\n    unsigned int solverM;\n    double solverTheta;\n    double modelS;\n    double modelK;\n    double boundaryLower;\n    double boundaryUpper;\n};\n\nint ReadVector(const std::string filename, std::vector<float>& A, const unsigned int size) {\n    std::ifstream file(filename);\n\n    std::vector<std::string> v;\n    std::string line;\n\n    if (file.good()) {\n        std::cout << \"Opened \" << filename << \" OK\" << std::endl;\n\n        unsigned int i = 0;\n        while (file.good()) {\n            getline(file, line);\n            if (line.length()) {\n                A[i] = std::stof(line);\n                i++;\n            }\n            if (i > size) {\n                std::cout << \"Warning! File has more than expected \" << size << \" lines...\" << std::endl;\n                break;\n            }\n        }\n    } else {\n        std::cout << \"Couldn't open \" << filename << std::endl;\n        return 1;\n    }\n    return 0;\n}\n\n/// @brief Read testcase parameters\nint ReadTestcaseParameters(std::string filename, testcaseParams& params) {\n    std::ifstream file(filename);\n\n    std::vector<std::string> v;\n    std::string line;\n\n    if (file.good()) {\n        std::cout << \"Opened \" << filename << \" OK\" << std::endl;\n\n        getline(file, line);\n        boost::split(v, line, [](char c) { return c == ','; });\n        params.solverN = std::stoi(v[0]);\n        params.solverM = std::stoi(v[1]);\n        params.solverTheta = std::stod(v[2]);\n        params.modelS = std::stod(v[3]);\n        params.modelK = std::stod(v[4]);\n        params.boundaryLower = std::stod(v[5]);\n        params.boundaryUpper = std::stod(v[6]);\n    } else {\n        std::cout << \"Couldn't open \" << filename << std::endl;\n        return 1;\n    }\n    return 0;\n}\n\nint main(int argc, char** argv) {\n    // xclbin file\n    std::string path = std::string(argv[1]);\n\n    // test data\n    std::string test_dir = std::string(argv[2]);\n\n    // Get the testcase parameters\n    testcaseParams params;\n    std::cout << \"Loading testcase...\" << std::endl;\n    if (ReadTestcaseParameters(test_dir + \"/parameters.csv\", params)) return EXIT_FAILURE;\n\n    // Extract N, M to aid readability\n    const unsigned int N = params.solverN;\n    const unsigned int M = params.solverM;\n\n    // device\n    std::string device = TOSTRING(DEVICE_PART);\n    if (argc == 4) {\n        device = std::string(argv[3]);\n    }\n\n    // Create the FD solver object\n    fdbslv fdbslv(N, M, path);\n\n    int retval = XLNX_OK;\n\n    std::vector<Device*> deviceList;\n    Device* pChosenDevice;\n\n    deviceList = DeviceManager::getDeviceList(device);\n\n    if (deviceList.size() == 0) {\n        printf(\"No matching devices found\\n\");\n        exit(0);\n    }\n\n    printf(\"Found %zu matching devices\\n\", deviceList.size());\n\n    // we'll just pick the first device in the...\n    pChosenDevice = deviceList[0];\n\n    if (retval == XLNX_OK) {\n        // turn off trace output...turn it on here if you want extra debug output...\n        Trace::setEnabled(true);\n    }\n\n    // clain the device\n    printf(\"\\n\\n\\n\");\n    printf(\"[XF_FINTECH] trying to claim device...\\n\");\n    retval = fdbslv.claimDevice(pChosenDevice);\n    if (retval != XLNX_OK) {\n        printf(\"[XF_FINTECH] Failed to claim device - error = %d\\n\", retval);\n    }\n\n    // read input data\n    std::vector<float> xGrid(N);\n    std::vector<float> tGrid(M);\n    std::vector<float> sigma(N * M);\n    std::vector<float> rate(M);\n    std::vector<float> initialCondition(N);\n    std::vector<float> solution(N);\n    std::vector<float> reference(N);\n\n    if (ReadVector(test_dir + \"/xGrid.csv\", xGrid, N)) return 1;\n    if (ReadVector(test_dir + \"/tGrid.csv\", tGrid, M)) return 1;\n    if (ReadVector(test_dir + \"/sigma.csv\", sigma, N * M)) return 1;\n    if (ReadVector(test_dir + \"/rate.csv\", rate, M)) return 1;\n    if (ReadVector(test_dir + \"/initialCondition.csv\", initialCondition, N)) return 1;\n    if (ReadVector(test_dir + \"/reference.csv\", reference, N)) return 1;\n\n    // run the kernel\n    retval = fdbslv.run(xGrid, tGrid, sigma, rate, initialCondition, params.solverTheta, params.boundaryLower,\n                        params.boundaryUpper, solution);\n\n    // check the results\n    float max_diff = 0;\n    int index = 0;\n    std::cout << \"actual (expected)\" << std::endl;\n    for (unsigned int i = 0; i < N; i++) {\n        std::cout << solution[i] << \"  (\" << reference[i] << \")\" << std::endl;\n        if (std::abs(solution[i] - reference[i]) > max_diff) {\n            max_diff = std::abs(solution[i] - reference[i]);\n            index = i;\n        }\n    }\n    std::cout << \"Max difference = \" << max_diff << \" at index \" << index << std::endl;\n\n    // release the device\n    retval = fdbslv.releaseDevice();\n\n    int ret = 0; // assume pass\n    if (max_diff > 0.003) {\n        std::cout << \"FAIL\" << std::endl;\n        ret = 1;\n    } else {\n        std::cout << \"PASS\" << std::endl;\n    }\n\n    return ret;\n}\n", "meta": {"hexsha": "39bfae57188989b3239bac0cfd8646b851aad5b2", "size": 8468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "quantitative_finance/L3/tests/fdbslv/xf_fintech_fdbslv_exe.cpp", "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/L3/tests/fdbslv/xf_fintech_fdbslv_exe.cpp", "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/L3/tests/fdbslv/xf_fintech_fdbslv_exe.cpp", "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": 36.9781659389, "max_line_length": 122, "alphanum_fraction": 0.6041568257, "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.19313713047127562}}
{"text": "#include <cmath>\n#include <ctime>\n#include <regex>\n\n#include <boost/filesystem.hpp>\n\n#include \"util.h\"\n\nvoid ReadFileNames(const std::string& directory, std::vector<std::string>& fileNames, int nDocs) {\n    boost::filesystem::path dirPath(directory);\n    boost::filesystem::recursive_directory_iterator start(dirPath);\n    boost::filesystem::recursive_directory_iterator end;\n    for (auto it = start; it != end; it++) {\n        if (boost::filesystem::is_directory(it->path())) {\n            continue;\n        }\n        std::string path = it->path().string();\n        if (path.substr(path.length() - 5) == \".html\") {\n            fileNames.push_back(path);\n        }\n        if (nDocs != -1 && fileNames.size() == static_cast<size_t>(nDocs)) {\n            break;\n        }\n    }\n}\n\nconst std::regex hostRegex(\"(http|https)://(?:www\\\\.)?([^/ :]+):?([^/ ]*)(/?[^ #?]*)\\\\x3f?([^ #]*)#?([^ ]*)\");\n\nstd::string GetHost(const std::string& url) {\n    // if u know better way to do it - it would be nice if u rewrite it\n    std::string output = \"\";\n    // https://stackoverflow.com/questions/2616011/easy-way-to-parse-a-url-in-c-cross-platform\n    try {\n        std::smatch what;\n        if (std::regex_match(url, what, hostRegex) && what.size() >= 3) {\n            output = std::string(what[2].first, what[2].second);\n        }\n    } catch (...) {\n        LOG_DEBUG(\"Can't parse host from url: \" << url);\n        return output;\n    }\n    return output;\n}\n\nstd::string CleanFileName(const std::string& fileName) {\n    return fileName.substr(fileName.find_last_of(\"/\") + 1);\n}\n\nfloat Sigmoid(float x) {\n    if (x >= 0.0f) {\n        float z = exp(-x);\n        return 1.0f / (1.0f + z);\n    }\n    float z = exp(x);\n    return z / (1.0f + z);\n}\n\ndouble Sigmoid(double x) {\n    if (x >= 0.0) {\n        double z = exp(-x);\n        return 1.0 / (1.0 + z);\n    }\n    double z = exp(x);\n    return z / (1.0 + z);\n}\n\nuint64_t DateToTimestamp(const std::string& date) {\n    std::regex ex(\"(\\\\d\\\\d\\\\d\\\\d)-(\\\\d\\\\d)-(\\\\d\\\\d)T(\\\\d\\\\d):(\\\\d\\\\d):(\\\\d\\\\d)([+-])(\\\\d\\\\d):(\\\\d\\\\d)\");\n    std::smatch what;\n    if (!std::regex_match(date, what, ex) || what.size() < 10) {\n        throw std::runtime_error(\"wrong date format\");\n    }\n    std::tm t = {};\n    t.tm_sec = std::stoi(what[6]);\n    t.tm_min = std::stoi(what[5]);\n    t.tm_hour = std::stoi(what[4]);\n    t.tm_mday = std::stoi(what[3]);\n    t.tm_mon = std::stoi(what[2]) - 1;\n    t.tm_year = std::stoi(what[1]) - 1900;\n\n    time_t timestamp = timegm(&t);\n    uint64_t zone_ts = std::stoi(what[8]) * 60 * 60 + std::stoi(what[9]) * 60;\n    if (what[7] == \"+\") {\n        timestamp = timestamp - zone_ts;\n    } else if (what[7] == \"-\") {\n        timestamp = timestamp + zone_ts;\n    }\n    return timestamp > 0 ? timestamp : 0;\n}\n\n", "meta": {"hexsha": "e1db7049a4d6309c2948127a31f89b291d151523", "size": 2754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util.cpp", "max_stars_repo_name": "IlyaGusev/tgcontest", "max_stars_repo_head_hexsha": "8945b9f6d1527ca21920998e86a8ecc1ebfdf526", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T11:46:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T04:50:12.000Z", "max_issues_repo_path": "src/util.cpp", "max_issues_repo_name": "IlyaGusev/tgcontest", "max_issues_repo_head_hexsha": "8945b9f6d1527ca21920998e86a8ecc1ebfdf526", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-10T11:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-05T20:57:10.000Z", "max_forks_repo_path": "src/util.cpp", "max_forks_repo_name": "IlyaGusev/tgcontest", "max_forks_repo_head_hexsha": "8945b9f6d1527ca21920998e86a8ecc1ebfdf526", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2020-01-14T17:37:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T15:28:01.000Z", "avg_line_length": 30.2637362637, "max_line_length": 110, "alphanum_fraction": 0.5417574437, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19281265153914087}}
{"text": "// Copyright (c) 2020-2021 Franz Alt\n// This code is licensed under MIT license (see LICENSE.txt for details).\n\n#include <libcvpg/imageproc/scripting/algorithms/mean.hpp>\n\n#include <chrono>\n#include <functional>\n#include <string>\n\n#include <boost/asynchronous/continuation_task.hpp>\n\n#include <libcvpg/core/exception.hpp>\n#include <libcvpg/core/image.hpp>\n#include <libcvpg/imageproc/algorithms/tiling.hpp>\n#include <libcvpg/imageproc/algorithms/tiling/mean.hpp>\n#include <libcvpg/imageproc/scripting/item.hpp>\n#include <libcvpg/imageproc/scripting/processing_context.hpp>\n#include <libcvpg/imageproc/scripting/detail/compiler.hpp>\n#include <libcvpg/imageproc/scripting/detail/handler.hpp>\n#include <libcvpg/imageproc/scripting/detail/parser.hpp>\n\nnamespace detail {\n\nstruct mean_task :  public boost::asynchronous::continuation_task<std::shared_ptr<cvpg::imageproc::scripting::processing_context> >\n{\n    mean_task(std::shared_ptr<cvpg::imageproc::scripting::processing_context> context, std::uint32_t result_id, cvpg::imageproc::scripting::detail::parser::item item)\n        : boost::asynchronous::continuation_task<std::shared_ptr<cvpg::imageproc::scripting::processing_context> >(\"algorithms::mean_task\")\n        , m_context(context)\n        , m_result_id(result_id)\n        , m_item(std::move(item))\n    {}\n\n    void operator()()\n    {\n        try\n        {\n            auto id = std::any_cast<std::uint32_t>(m_item.arguments.at(0).value());\n            auto width = std::any_cast<std::int32_t>(m_item.arguments.at(1).value());\n            auto height = std::any_cast<std::int32_t>(m_item.arguments.at(2).value());\n            auto border_mode_str = std::any_cast<std::string>(m_item.arguments.at(3).value());\n\n            auto input = m_context->load(id);\n            auto parameters = m_context->parameters();\n\n            std::uint32_t cutoff_x = 512;\n            std::uint32_t cutoff_y = 512;\n\n            {\n                auto it = parameters.find(\"cutoff_x\");\n\n                if (it != parameters.end())\n                {\n                    cutoff_x = std::any_cast<std::uint32_t>(it->second);\n                }\n            }\n\n            {\n                auto it = parameters.find(\"cutoff_y\");\n\n                if (it != parameters.end())\n                {\n                    cutoff_y = std::any_cast<std::uint32_t>(it->second);\n                }\n            }\n\n            auto border_mode = cvpg::imageproc::algorithms::to_border_mode(border_mode_str);\n\n            if (input.type() == cvpg::imageproc::scripting::item::types::grayscale_8_bit_image)\n            {\n                auto image = std::any_cast<cvpg::image_gray_8bit>(input.value());\n\n                const auto image_width = image.width();\n                const auto image_height = image.height();\n\n                auto start = std::chrono::system_clock::now();\n\n                auto tf = cvpg::imageproc::algorithms::tiling_functors::image<cvpg::image_gray_8bit>({{ std::move(image) }});\n                tf.parameters.image_width = image_width;\n                tf.parameters.image_height = image_height;\n                tf.parameters.cutoff_x = cutoff_x;\n                tf.parameters.cutoff_y = cutoff_y;\n                tf.parameters.signed_integer_numbers.push_back(width); // filter width\n                tf.parameters.signed_integer_numbers.push_back(height); // filter height\n                tf.parameters.border_mode = border_mode;\n\n                tf.tile_algorithm_task = [](std::shared_ptr<cvpg::image_gray_8bit> src1, std::shared_ptr<cvpg::image_gray_8bit> /*src2*/, std::shared_ptr<cvpg::image_gray_8bit> dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n                {\n                    cvpg::imageproc::algorithms::mean_gray_8bit(src1->data(0).get(), dst->data(0).get(), from_x, to_x, from_y, to_y, std::move(parameters));\n                };\n\n                boost::asynchronous::create_callback_continuation(\n                    [result = this->this_task_result(), context = m_context, result_id = m_result_id, start](auto cont_res) mutable\n                    {\n                        auto stop = std::chrono::system_clock::now();\n\n                        try\n                        {\n                            context->store(result_id, std::move(std::get<0>(cont_res).get()), std::chrono::duration_cast<std::chrono::microseconds>(stop - start));\n\n                            result.set_value(context);\n                        }\n                        catch (...)\n                        {\n                            result.set_exception(std::current_exception());\n                        }\n                    },\n                    cvpg::imageproc::algorithms::tiling(std::move(tf))\n                );\n            }\n            else if (input.type() == cvpg::imageproc::scripting::item::types::rgb_8_bit_image)\n            {\n                auto image = std::any_cast<cvpg::image_rgb_8bit>(input.value());\n\n                const auto image_width = image.width();\n                const auto image_height = image.height();\n\n                auto start = std::chrono::system_clock::now();\n\n                auto tf = cvpg::imageproc::algorithms::tiling_functors::image<cvpg::image_rgb_8bit>({{ std::move(image) }});\n                tf.parameters.image_width = image_width;\n                tf.parameters.image_height = image_height;\n                tf.parameters.cutoff_x = cutoff_x;\n                tf.parameters.cutoff_y = cutoff_y;\n                tf.parameters.signed_integer_numbers.push_back(width); // filter width\n                tf.parameters.signed_integer_numbers.push_back(height); // filter height\n                tf.parameters.border_mode = border_mode;\n\n                tf.tile_algorithm_task = [](std::shared_ptr<cvpg::image_rgb_8bit> src1, std::shared_ptr<cvpg::image_rgb_8bit> /*src2*/, std::shared_ptr<cvpg::image_rgb_8bit> dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n                {\n                    cvpg::imageproc::algorithms::mean_gray_8bit(src1->data(0).get(), dst->data(0).get(), from_x, to_x, from_y, to_y, parameters);\n                    cvpg::imageproc::algorithms::mean_gray_8bit(src1->data(1).get(), dst->data(1).get(), from_x, to_x, from_y, to_y, parameters);\n                    cvpg::imageproc::algorithms::mean_gray_8bit(src1->data(2).get(), dst->data(2).get(), from_x, to_x, from_y, to_y, std::move(parameters));\n                };\n\n                boost::asynchronous::create_callback_continuation(\n                    [result = this->this_task_result(), context = m_context, result_id = m_result_id, start](auto cont_res) mutable\n                    {\n                        auto stop = std::chrono::system_clock::now();\n\n                        try\n                        {\n                            context->store(result_id, std::move(std::get<0>(cont_res).get()), std::chrono::duration_cast<std::chrono::microseconds>(stop - start));\n\n                            result.set_value(context);\n                        }\n                        catch (...)\n                        {\n                            result.set_exception(std::current_exception());\n                        }\n                    },\n                    cvpg::imageproc::algorithms::tiling(std::move(tf))\n                );\n            }\n        }\n        catch (...)\n        {\n            this->this_task_result().set_exception(std::current_exception());\n        }\n    }\n\nprivate:\n    std::shared_ptr<cvpg::imageproc::scripting::processing_context> m_context;\n\n    std::uint32_t m_result_id;\n\n    cvpg::imageproc::scripting::detail::parser::item m_item;\n};\n\nauto mean(std::shared_ptr<cvpg::imageproc::scripting::processing_context> context, std::uint32_t result_id, cvpg::imageproc::scripting::detail::parser::item item)\n{\n    return boost::asynchronous::top_level_callback_continuation<std::shared_ptr<cvpg::imageproc::scripting::processing_context> >(\n               mean_task(context, result_id, std::move(item))\n           );\n}\n\n} // namespace detail\n\nnamespace cvpg::imageproc::scripting::algorithms {\n\nstd::string mean::name() const\n{\n    return \"mean\";\n}\n\nstd::string mean::category() const\n{\n    return \"filters/smoothing\";\n}\n\nstd::vector<scripting::item::types> mean::result() const\n{\n    return\n    {\n        scripting::item::types::grayscale_8_bit_image,\n        scripting::item::types::rgb_8_bit_image,\n    };\n}\n\nparameter_set mean::parameters() const\n{\n    using namespace std::string_literals;\n\n    return parameter_set\n           ({\n               parameter(\"image\", \"input image\", \"\", { scripting::item::types::grayscale_8_bit_image, scripting::item::types::rgb_8_bit_image }),\n               parameter(\"filter_width\", \"filter width\", \"pixels\", scripting::item::types::signed_integer, static_cast<std::int32_t>(3), static_cast<std::int32_t>(65535), static_cast<std::int32_t>(2)),\n               parameter(\"filter_height\", \"filter height\", \"pixels\", scripting::item::types::signed_integer, static_cast<std::int32_t>(3), static_cast<std::int32_t>(65535), static_cast<std::int32_t>(2)),\n               parameter(\"border_mode\", \"border mode\", \"\", scripting::item::types::characters, { \"ignore\"s, \"constant\"s, \"mirror\"s })\n           });\n}\n\nvoid mean::on_parse(std::shared_ptr<detail::parser> parser) const\n{\n    // all parameters\n    {\n        std::function<std::uint32_t(std::uint32_t, std::uint32_t, std::uint32_t, std::string)> fct =\n            [parser, parameters = this->parameters()](std::uint32_t image_id, std::uint32_t width, std::uint32_t height, std::string border_mode)\n            {\n                std::uint32_t result_id = 0;\n\n                // find image\n                if (!parser)\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid parser\");\n                }\n\n                auto image = parser->find_item(image_id);\n\n                if (image.arguments.empty())\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid input ID\");\n                }\n\n                auto input_type = image.arguments.front().type();\n\n                // check parameters\n                if (!(input_type == scripting::item::types::grayscale_8_bit_image || input_type == scripting::item::types::rgb_8_bit_image))\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid input type\");\n                }\n\n                if (!parameters.is_valid(\"filter_width\", static_cast<std::int32_t>(width)))\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid filter width\");\n                }\n\n                if (!parameters.is_valid(\"filter_height\", static_cast<std::int32_t>(height)))\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid filter height\");\n                }\n\n                if (!parameters.is_valid(\"border_mode\", border_mode))\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid border mode\");\n                }\n\n                switch (input_type)\n                {\n                    case scripting::item::types::grayscale_8_bit_image:\n                    {\n                        detail::parser::item result_item\n                        {\n                            \"mean\",\n                            {\n                                scripting::item(scripting::item::types::grayscale_8_bit_image, image_id),\n                                scripting::item(scripting::item::types::signed_integer, static_cast<std::int32_t>(width)),\n                                scripting::item(scripting::item::types::signed_integer, static_cast<std::int32_t>(height)),\n                                scripting::item(scripting::item::types::characters, border_mode)\n                            }\n                        };\n\n                        result_id = parser->register_item(std::move(result_item));\n\n                        break;\n                    }\n\n                    case scripting::item::types::rgb_8_bit_image:\n                    {\n                        detail::parser::item result_item\n                        {\n                            \"mean\",\n                            {\n                                scripting::item(scripting::item::types::rgb_8_bit_image, image_id),\n                                scripting::item(scripting::item::types::signed_integer, static_cast<std::int32_t>(width)),\n                                scripting::item(scripting::item::types::signed_integer, static_cast<std::int32_t>(height)),\n                                scripting::item(scripting::item::types::characters, border_mode)\n                            }\n                        };\n\n                        result_id = parser->register_item(std::move(result_item));\n\n                        break;\n                    }\n\n                    default:\n                    {\n                        // to make the compiler happy ; other input types are not allowed and should be handled above\n                        break;\n                    }\n                }\n\n                if (result_id != 0)\n                {\n                    parser->register_link(image_id, result_id);\n                }\n\n                return result_id;\n            };\n\n        parser->register_specification(name(), std::move(fct));\n    }\n\n    // default for border mode\n    {\n        std::function<std::uint32_t(std::uint32_t, std::uint32_t, std::uint32_t)> fct =\n            [parser, parameters = this->parameters()](std::uint32_t image_id, std::uint32_t width, std::uint32_t height)\n            {\n                // find image\n                if (!parser)\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid parser\");\n                }\n\n                auto image = parser->find_item(image_id);\n\n                if (image.arguments.empty())\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid input ID\");\n                }\n\n                auto input_type = image.arguments.front().type();\n\n                // check parameters\n                if (!(input_type == scripting::item::types::grayscale_8_bit_image || input_type == scripting::item::types::rgb_8_bit_image))\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid input type\");\n                }\n\n                if (!parameters.is_valid(\"filter_width\", static_cast<std::int32_t>(width)))\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid filter width\");\n                }\n\n                if (!parameters.is_valid(\"filter_height\", static_cast<std::int32_t>(height)))\n                {\n                    throw cvpg::invalid_parameter_exception(\"invalid filter height\");\n                }\n\n                std::uint32_t result_id = 0;\n\n                std::string border_mode = \"constant\";\n\n                switch (input_type)\n                {\n                    case scripting::item::types::grayscale_8_bit_image:\n                    {\n                        detail::parser::item result_item\n                        {\n                            \"mean\",\n                            {\n                                scripting::item(scripting::item::types::grayscale_8_bit_image, image_id),\n                                scripting::item(scripting::item::types::signed_integer, static_cast<std::int32_t>(width)),\n                                scripting::item(scripting::item::types::signed_integer, static_cast<std::int32_t>(height)),\n                                scripting::item(scripting::item::types::characters, border_mode)\n                            }\n                        };\n\n                        result_id = parser->register_item(std::move(result_item));\n\n                        break;\n                    }\n\n                    case scripting::item::types::rgb_8_bit_image:\n                    {\n                        detail::parser::item result_item\n                        {\n                            \"mean\",\n                            {\n                                scripting::item(scripting::item::types::rgb_8_bit_image, image_id),\n                                scripting::item(scripting::item::types::signed_integer, static_cast<std::int32_t>(width)),\n                                scripting::item(scripting::item::types::signed_integer, static_cast<std::int32_t>(height)),\n                                scripting::item(scripting::item::types::characters, border_mode)\n                            }\n                        };\n\n                        result_id = parser->register_item(std::move(result_item));\n\n                        break;\n                    }\n\n                    default:\n                    {\n                        // to make the compiler happy ; other input types are not allowed and should be handled above\n                        break;\n                    }\n                }\n\n                if (result_id != 0)\n                {\n                    parser->register_link(image_id, result_id);\n                }\n\n                return result_id;\n            };\n\n        parser->register_specification(name(), std::move(fct));\n    }\n}\n\nvoid mean::on_compile(std::uint32_t item_id, std::shared_ptr<detail::compiler> compiler) const\n{\n    auto handler =\n        detail::handler(\n            [result_id = item_id, item = compiler->get_item(item_id)](std::shared_ptr<processing_context> context)\n            {\n                return ::detail::mean(context, result_id, std::move(item));\n            });\n\n    compiler->register_handler(item_id, name(), std::move(handler));\n}\n\n} // namespace cvpg::imageproc::scripting::algorithms\n", "meta": {"hexsha": "b487b541e2ce13bac9c763c6c97acc178ed106e2", "size": 17832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libcvpg/imageproc/scripting/algorithms/mean.cpp", "max_stars_repo_name": "franz-alt/cv-playground", "max_stars_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "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/libcvpg/imageproc/scripting/algorithms/mean.cpp", "max_issues_repo_name": "franz-alt/cv-playground", "max_issues_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "max_issues_repo_licenses": ["MIT"], "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/libcvpg/imageproc/scripting/algorithms/mean.cpp", "max_forks_repo_name": "franz-alt/cv-playground", "max_forks_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "max_forks_repo_licenses": ["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.1560283688, "max_line_length": 316, "alphanum_fraction": 0.5337595334, "num_tokens": 3621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19281264960563574}}
{"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#ifndef BOOST_UNITS_CODATA_TYPEDEFS_HPP\r\n#define BOOST_UNITS_CODATA_TYPEDEFS_HPP\r\n\r\n#include <boost/units/operators.hpp>\r\n#include <boost/units/systems/si/amount.hpp>\r\n#include <boost/units/systems/si/area.hpp>\r\n#include <boost/units/systems/si/capacitance.hpp>\r\n#include <boost/units/systems/si/electric_charge.hpp>\r\n#include <boost/units/systems/si/current.hpp>\r\n#include <boost/units/systems/si/electric_potential.hpp>\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/frequency.hpp>\r\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\r\n#include <boost/units/systems/si/mass.hpp>\r\n#include <boost/units/systems/si/length.hpp>\r\n#include <boost/units/systems/si/power.hpp>\r\n#include <boost/units/systems/si/solid_angle.hpp>\r\n#include <boost/units/systems/si/temperature.hpp>\r\n#include <boost/units/systems/si/time.hpp>\r\n#include <boost/units/systems/si/volume.hpp>\r\n\r\nnamespace boost {\r\n\r\nnamespace units { \r\n\r\nnamespace si {\r\n                            \r\nnamespace constants {\r\n\r\nnamespace codata {\r\n\r\ntypedef divide_typeof_helper<frequency,electric_potential>::type frequency_over_electric_potential;\r\ntypedef divide_typeof_helper<electric_charge,mass>::type electric_charge_over_mass;\r\ntypedef divide_typeof_helper<mass,amount>::type mass_over_amount;\r\ntypedef divide_typeof_helper<energy,magnetic_flux_density>::type energy_over_magnetic_flux_density;\r\ntypedef divide_typeof_helper<frequency,magnetic_flux_density>::type frequency_over_magnetic_flux_density;\r\ntypedef divide_typeof_helper<current,energy>::type current_over_energy;\r\ntypedef divide_typeof_helper<dimensionless,amount>::type inverse_amount;\r\ntypedef divide_typeof_helper<energy,temperature>::type energy_over_temperature;\r\ntypedef divide_typeof_helper<energy_over_temperature,amount>::type energy_over_temperature_amount;\r\ntypedef divide_typeof_helper<\r\n            divide_typeof_helper<power,area>::type,\r\n            power_typeof_helper<temperature,static_rational<4> >::type\r\n        >::type power_over_area_temperature_4;\r\ntypedef multiply_typeof_helper<power,area>::type power_area;\r\ntypedef divide_typeof_helper<power_area,solid_angle>::type power_area_over_solid_angle;\r\ntypedef multiply_typeof_helper<length,temperature>::type length_temperature;\r\ntypedef divide_typeof_helper<frequency,temperature>::type frequency_over_temperature;\r\ntypedef divide_typeof_helper<divide_typeof_helper<force,current>::type,current>::type force_over_current_squared;\r\ntypedef divide_typeof_helper<capacitance,length>::type capacitance_over_length;\r\ntypedef divide_typeof_helper<\r\n            divide_typeof_helper<divide_typeof_helper<volume,mass>::type,time>::type,\r\n            time\r\n        >::type volume_over_mass_time_squared;\r\ntypedef multiply_typeof_helper<energy,time>::type energy_time;\r\ntypedef divide_typeof_helper<electric_charge,amount>::type electric_charge_over_amount;\r\n\r\n} // namespace codata\r\n\r\n} // namespace constants    \r\n\r\n} // namespace si\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\n#endif\r\n", "meta": {"hexsha": "58fe131a68f16cd3926042786fd8bbf348998084", "size": 3452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/typedefs.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/units/systems/si/codata/typedefs.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/units/systems/si/codata/typedefs.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": 43.15, "max_line_length": 114, "alphanum_fraction": 0.7888180765, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1928126442180458}}
{"text": "//Released under the MIT License - https://opensource.org/licenses/MIT\n//\n//Copyright (c) 2019 AIT Austrian Institute of Technology GmbH\n//\n//Permission is hereby granted, free of charge, to any person obtaining\n//a 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,\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 OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n//DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n//OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n//USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n//Author: Josef Maier (josefjohann-dot-maier-at-gmail-dot-at)\n/**********************************************************************************************************\n FILE: pose_estim.cpp\n\n PLATFORM: Windows 7, MS Visual Studio 2010, OpenCV 2.4.9\n\n CODE: C++\n\n AUTOR: Josef Maier, AIT Austrian Institute of Technology\n\n DATE: May 2016\n\n LOCATION: TechGate Vienna, Donau-City-Strasse 1, 1220 Vienna\n\n VERSION: 1.0\n\n DISCRIPTION: This file provides functionalities for the estimation and optimization of poses between\n\t\t\t  two camera views (images).\n**********************************************************************************************************/\n\n#include \"poselib/pose_estim.h\"\n#include \"poselib/pose_helper.h\"\n#include \"five-point-nister/five-point.hpp\"\n#include \"BA_driver.h\"\n#include \"usac/usac_estimations.h\"\n#include <Eigen/StdVector>\n\nusing namespace cv;\nusing namespace std;\n\nnamespace poselib\n{\n\n/* --------------------------- Defines --------------------------- */\n\n\n\n/* --------------------- Function prototypes --------------------- */\n\n\n\n/* --------------------- Functions --------------------- */\n\n/* Estimation of the Essential matrix based on the 5-pt Nister algorithm integrated in an ARRSAC framework with an automatic threshold\n * estimation based on the reprojection errors.\n *\n * InputArray p1\t\t\t\t\t\tInput  -> Observed point coordinates of the left image in the camera coordinate system\n *\t\t\t\t\t\t\t\t\t\t\t\t  (n rows, 2 cols)\n * InputArray p2\t\t\t\t\t\tInput  -> Observed point coordinates of the right image in the camera coordinate system\n *\t\t\t\t\t\t\t\t\t\t\t\t  (n rows, 2 cols)\n * OutputArray E\t\t\t\t\t\tOutput -> Essential matrix\n * OutputArray mask\t\t\t\t\t\tOutput -> Inlier mask\n * double *th\t\t\t\t\t\t\tI/O\t   -> Pointer to the inlier threshold (must be in the camera coordinate system)\n * int *nrgoodPts\t\t\t\t\t\tOutput -> Number of inliers to E\n *\n * Return value:\t\t\t\t\t\t0 :\t\tEverything ok\n *\t\t\t\t\t\t\t\t\t\t-1:\t\tCalculation of Essential matrix not possible (execute addFailedProps() within uncalibartedRectify)\n *\t\t\t\t\t\t\t\t\t\t-2:\t\tMat for essential matrix missing\n */\nint AutoThEpi::estimateEVarTH(cv::InputArray p1, cv::InputArray p2, cv::OutputArray E, cv::OutputArray mask, double *th, int *nrgoodPts)\n{\n\tbool th_sem[3] = {true, true, false};\n\tint th_fail_cnt = 2;\n\tdouble th_failed = *th;\n\tdouble th_old;\n\tMat p1_ = p1.getMat();\n\tMat p2_ = p2.getMat();\n\tMat mask_, E_;\n\n\tdo\n\t{\n\t\tif(!mask_.empty()) mask_.release();\n\t\tth_old = *th;\n\t\tif(!findEssentialMat(E_, p1_, p2_, ARRSAC, 0.99, *th, mask_,true,robustEssentialRefine))\n\t\t{\n\t\t\tif((*th < PIX_MIN_GOOD_TH * pixToCamFact) && !th_stable && !th_sem[2])\n\t\t\t{\n\t\t\t\tif(!mask_.empty()) mask_.release();\n\t\t\t\tth_failed = *th;\n\t\t\t\t*th = PIX_MIN_GOOD_TH * pixToCamFact;\n\t\t\t\tth_old = *th;\n\t\t\t\tif(!findEssentialMat(E_, p1_, p2_, ARRSAC, 0.99, *th, mask_,true,robustEssentialRefine))\n\t\t\t\t{\n\t\t\t\t\t//addFailedProps();-------------------------------------------------------------------->execute this for a return value = -1 within  class StereoAutoCalib in project uncalibratedRectify, file RectStructMot.cpp\n\t\t\t\t\treturn -1; //Calculation of Essential matrix not possible\n\t\t\t\t}\n\t\t\t\tth_sem[2] = true;\n\t\t\t}\n\t\t\telse if(th_sem[2])\n\t\t\t{\n\t\t\t\tth_fail_cnt *= 2;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//addFailedProps();\n\t\t\t\treturn -1; //Calculation of Essential matrix not possible\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(th_sem[2] && (th_fail_cnt > 2))\n\t\t\t\tcorr_filt_min_pix_th = *th / pixToCamFact;\n\t\t\tth_sem[2] = false;\n\t\t}\n\t\tif((th_fail_cnt <= 2) || !th_sem[2])\n\t\t\t*nrgoodPts = cv::countNonZero(mask_);\n\t\tif(!th_stable)\n\t\t{\n\t\t\tif((th_fail_cnt <= 2) || !th_sem[2])\n\t\t\t\t*th = estimateThresh(p1_, p2_, E_);\n\t\t\telse\n\t\t\t\t*th = th_failed * (double)th_fail_cnt;\n\t\t\tif(th_sem[2] && (th_failed >= *th))\n\t\t\t\t*th = th_failed * (double)th_fail_cnt;\n\t\t\tif(!th_sem[2])\n\t\t\t{\n\t\t\t\tif(th_old / *th > 1.0 + 1e-6)\n\t\t\t\t\tth_sem[0] = false;\n\t\t\t\telse if(th_old / *th < 1.0 - 1e-6)\n\t\t\t\t\tth_sem[1] = false;\n\t\t\t}\n\t\t}\n\t}\n\twhile(((th_old / *th < 0.9) || (*th/th_old < 0.9)) && ((((float)*nrgoodPts/(float)p1_.rows < 0.67) &&\n\t\t\t(th_sem[0] || th_sem[1])) || th_sem[2])); //Try to find a good threshold if the initial wasnt a good choice\n\n\tif(E.needed())\n\t{\n\t\tif(E.empty())\n\t\t\tE.create(3, 3, CV_64F);\n\t\tE_.copyTo(E.getMat());\n\t}\n\telse\n\t\treturn -2;\n\n\tif(mask.needed())\n\t{\n\t\tMat mask_tmp;\n\t\tmask.create(mask_.size(), mask_.type());\n\t\tmask_tmp = mask.getMat();\n\t\tmask_.copyTo(mask_tmp);\n\t}\n\n\treturn 0;\n}\n\n/* Estimates a new threshold based on the correspondences and the given essential matrix.\n *\n * InputArray p1\t\t\t\t\tInput  -> Left image projections (n rows x 2 columns)\n * InputArray p2\t\t\t\t\tInput  -> Right image projections (n rows x 2 columns)\n * InputArray E\t\t\t\t\t\tInput  -> Essential matrix\n * bool useImgCoordSystem\t\t\tInput  -> Specifies if the input thresh and the return value should be\n *\t\t\t\t\t\t\t\t\t\t\t  in camera (false) or pixel (true) units\n *\t\t\t\t\t\t\t\t\t\t\t  (default: false -> camera coord. system)\n * bool storeGlobally\t\t\t\tInput  -> If true (default: false), the threshold is stored globally in the\n *\t\t\t\t\t\t\t\t\t\t\t  class member variable\n *\n * Return value:\t\t\t\t\tThreshold in the camera coordinate system if\n *\t\t\t\t\t\t\t\t\tuseImgCoordSystem = false (default) and in the image coordinate system\n *\t\t\t\t\t\t\t\t\totherwise\n */\ndouble AutoThEpi::estimateThresh(cv::InputArray p1, cv::InputArray p2, cv::InputArray E, bool useImgCoordSystem,\n\t\t\t\t\t\t\t\t\t   bool storeGlobally)\n{\n\tstatVals qp_act;\n\tMat _E = E.getMat();\n\tMat _p1 = p1.getMat();\n\tMat _p2 = p2.getMat();\n\tstd::vector<double> error;\n\tdouble th, th_tmp, maxInlDist;\n\t//double pixToCamFact = 4.0/(std::sqrt((double)2)*(this->K1.at<double>(0,0)+this->K1.at<double>(1,1)+this->K2.at<double>(0,0)+this->K2.at<double>(1,1)));\n\n\tgetReprojErrors(_E,_p1,_p2,useImgCoordSystem,nullptr,&error);\n\n\tfor(auto &i : error)\n\t\ti = std::sqrt(i);\n\n\tif(useImgCoordSystem)\n\t{\n\t\tth = this->corr_filt_pix_th;\n\t\tmaxInlDist = 4.0 * th;\n\t\tmaxInlDist = maxInlDist > 5.0 ? 5.0:maxInlDist;\n\t}\n\telse\n\t{\n\t\tth = this->corr_filt_cam_th;\n\t\tmaxInlDist = 4.0 * th;\n\t\tmaxInlDist = maxInlDist > 5.0 * pixToCamFact ? (5.0 * pixToCamFact):maxInlDist;\n\t}\n\n\tdouble r1 = *std::max_element(error.begin(),error.end()) - *std::min_element(error.begin(),error.end());\n\tif(r1 > maxInlDist)\n\t{\n\t\tgetStatsfromVec(error, &qp_act,true);\n\t}\n\telse\n\t{\n\t\tgetStatsfromVec(error, &qp_act);\n\t}\n\n\tif((qp_act.arithErr/qp_act.medErr > 2.0) || (qp_act.arithErr/qp_act.medErr < 0.5))\n\t\tth_tmp = qp_act.medErr + 3.0 * qp_act.medStd;\n\telse\n\t\tth_tmp = qp_act.arithErr + 3.0 * qp_act.arithStd;\n\n\tif((th_tmp < 5.0 * th) || (th_tmp < 4.0 * PIX_MIN_GOOD_TH))\n\t\tth = setCorrTH(th_tmp,useImgCoordSystem,storeGlobally);\n\telse\n\t{\n\t\tif(th < (useImgCoordSystem ? (MAX_PIX_TH/2):((MAX_PIX_TH/2) * pixToCamFact)))\n\t\t\tth = setCorrTH(th * 2.0,useImgCoordSystem,storeGlobally);\n\t\telse\n\t\t{\n\t\t\tth = setCorrTH(corr_filt_min_pix_th,true,storeGlobally);\n\t\t\tif(!useImgCoordSystem)\n\t\t\t\tth *= pixToCamFact;\n\t\t}\n\t}\n\n\treturn th;\n}\n\n/* Sets a new threshold for marking correspondences as in- or outliers.\n *\n * double thresh\t\t\t\t\tInput  -> New threshold (default: in the camera coordinate system)\n * bool useImgCoordSystem\t\t\tInput  -> Specifies if the input thresh and the return value should be\n *\t\t\t\t\t\t\t\t\t\t\t  in camera (false) or pixel (true) units\n *\t\t\t\t\t\t\t\t\t\t\t  (default: false -> camera coord. system)\n * bool storeGlobally\t\t\t\tInput  -> If true (default), the threshold is stored globally in the\n *\t\t\t\t\t\t\t\t\t\t\t  class member variable\n *\n * Return value:\t\t\t\t\tThreshold in the camera coordinate system if\n *\t\t\t\t\t\t\t\t\tuseImgCoordSystem = false (default) and in the image coordinate system\n *\t\t\t\t\t\t\t\t\totherwise\n */\ndouble AutoThEpi::setCorrTH(double thresh, bool useImgCoordSystem, bool storeGlobally)\n{\n\t//CV_Assert(!this->K1.empty() && !this->K2.empty());\n\n\tdouble pix_th_tmp, cam_th_tmp;\n\t//double pixToCamFact = 4.0/(std::sqrt((double)2)*(this->K1.at<double>(0,0)+this->K1.at<double>(1,1)+this->K2.at<double>(0,0)+this->K2.at<double>(1,1)));\n\n\tif(useImgCoordSystem)\n\t\tpix_th_tmp = thresh;\n\telse\n\t\tpix_th_tmp = thresh / pixToCamFact;\n\n\tif(pix_th_tmp < corr_filt_min_pix_th)\n\t\tpix_th_tmp = corr_filt_min_pix_th;\n\telse if(pix_th_tmp > MAX_PIX_TH)\n\t\tpix_th_tmp = MAX_PIX_TH;\n\n\tcam_th_tmp = pix_th_tmp * pixToCamFact;\n\n\tif(storeGlobally)\n\t{\n\t\tthis->corr_filt_pix_th = pix_th_tmp;\n\t\tthis->corr_filt_cam_th = cam_th_tmp;\n\t}\n\n\tif(useImgCoordSystem)\n\t\treturn pix_th_tmp;\n\n\treturn cam_th_tmp;\n}\n\n/* Refines the essential matrix E by using the 8-point-algorithm and SVD (currently the\n * solution is not found by SVD but by calculating the eigenvalues and eigenvectors of\n * A^T*A and selcting the eigenvector corresponding to the smallest eigenvalue which is\n * much faster than SVD) with a pseudo-huber cost function. Thus, this methode is very\n * robust and can refine E also in an iterative manner. If the input variable iters is\n * set to 0, the essential matrix is as long refined as the sum of squared errors reaches\n * a minimum value, its reduction is too small or the maximum number of iterations is\n * reached.\n *\n * InputArray points1\t\t\t\tInput  -> Image projections in the left camera without\n *\t\t\t\t\t\t\t\t\t\t\t  outliers (1 projection per column with 2 channels\n *\t\t\t\t\t\t\t\t\t\t\t  or 1 projection per row with 2 columns)\n * InputArray points2\t\t\t\tInput  -> Image projections in the right camera without\n *\t\t\t\t\t\t\t\t\t\t\t  outliers (1 projection per column with 2 channels\n *\t\t\t\t\t\t\t\t\t\t\t  or 1 projection per row with 2 columns)\n * InputArray E_init\t\t\t\tInput  -> Initial estimate of the essential matrix\n * Mat & E_refined\t\t\t\t\tOutput -> Refined essential matrix\n * double th\t\t\t\t\t\tInput  -> Threshold for the pseudo-huber cost function.\n *\t\t\t\t\t\t\t\t\t\t\t  Can be really small (e.g. 0.005 for image\n *\t\t\t\t\t\t\t\t\t\t\t  coordinate system)\n * unsigned int iters\t\t\t\tInput  -> Number of iterations that should be performed.\n *\t\t\t\t\t\t\t\t\t\t\t  If 0, the essential matrix is as long refined\n *\t\t\t\t\t\t\t\t\t\t\t  as the sum of squared errors reaches a minimum\n *\t\t\t\t\t\t\t\t\t\t\t  value, its reduction is too small or the\n *\t\t\t\t\t\t\t\t\t\t\t  maximum number of iterations is reached.\n * bool makeClosestE\t\t\t\tInput  -> Specifies if the closest essential matrix\n *\t\t\t\t\t\t\t\t\t\t\t  should be computed by enforcing the singularity\n *\t\t\t\t\t\t\t\t\t\t\t  constraint (first 2 singular values are equal\n *\t\t\t\t\t\t\t\t\t\t\t  and third is zero).\n * unsigned int *sumSqrErr_init\t\tOutput -> Initial sum of squared errors (after first\n *\t\t\t\t\t\t\t\t\t\t\t  refinement).\n * unsigned int *sumSqrErr\t\t\tOutput -> Final sum of squared errors\n * OutputArray errors\t\t\t\tOutput -> Final Sampson error for every correspondence\n * InputOutputArray mask\t\t\tI/O    -> Inlier mask (input) and mask to exclude points which do not\n *\t\t\t\t\t\t\t\t\t\t\t  correspond with the oriented epipolar constraint combined with\n *\t\t\t\t\t\t\t\t\t\t\t  the input inlier mask (output).\n * int model\t\t\t\t\t\tInput  -> Optional input (Default = 0) to specify the used\n *\t\t\t\t\t\t\t\t\t\t\t  model (0 = Normal essential matrix, 1 = affine\n *\t\t\t\t\t\t\t\t\t\t\t  essential matrix, 2 = translational essential matrix).\n * bool tryOrientedEpipolar\t\t\tInput  -> Optional input [DEFAULT = false] to specify if a essential matrix\n *\t\t\t\t\t\t\t\t\t\t\t  should be evaluated by the oriented epipolar constraint. Maybe this\n *\t\t\t\t\t\t\t\t\t\t\t  is only possible for a fundamental matrix?\n * bool normalizeCorrs\t\t\t\tInput  -> If true [DEFAULT=false], the coordinates are normalized. Normalization has\n *\t\t\t\t\t\t\t\t\t\t\t  an impact on the properties of the essential matrix! Thus, after normalization,\n *\t\t\t\t\t\t\t\t\t\t\t  the properties of the fundamental matrix are valid!\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid robustEssentialRefine(cv::InputArray points1, cv::InputArray points2, cv::InputArray E_init, cv::Mat & E_refined,\n\t\t\t\t\t\t  double th, unsigned int iters, bool makeClosestE, double *sumSqrErr_init,\n\t\t\t\t\t\t  double *sumSqrErr, cv::OutputArray errors, cv::InputOutputArray mask, int model, bool tryOrientedEpipolar, bool normalizeCorrs)\n{\n\n\tMat _points1 = points1.getMat(), _points2 = points2.getMat();\n\tMat pointsRedu1, pointsRedu2;\n\tMat E, mask_;\n\tdouble err = -9999.0, err_old = 1e12;//, err_min = 1e12;\n    int npoints;\n\tif(_points1.channels() == 2)\n\t\tnpoints = _points1.checkVector(2);\n\telse\n\t\tnpoints = _points1.rows;\n\n    CV_Assert( npoints >= 0 &&\n\t\t\t  ((_points2.checkVector(2) == npoints &&\n              _points1.type() == CV_64FC2 &&\n\t\t\t  _points1.rows == 1 && _points1.cols > _points1.rows) ||\n\t\t\t  (_points1.rows == npoints &&\n\t\t\t  _points1.type() == CV_64FC1 &&\n\t\t\t  _points1.cols == 2 && _points1.rows > _points1.cols)) &&\n              _points1.type() == _points2.type());\n\n\tif(mask.needed() && !mask.getMat().empty())\n\t{\n\t\tMat pointsRedu1_tmp;\n\t\tMat pointsRedu2_tmp;\n\t\tmask_ = mask.getMat();\n\t\tif(_points1.channels() == 2)\n\t\t{\n\t\t\tpointsRedu1_tmp = _points1.reshape(1,2).t();\n\t\t\tpointsRedu2_tmp = _points2.reshape(1,2).t();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpointsRedu1_tmp = _points1;\n\t\t\tpointsRedu2_tmp = _points2;\n\t\t}\n\t\tfor(int i = 0; i < npoints; i++)\n\t\t{\n\t\t\tif(mask_.at<bool>(i))\n\t\t\t{\n\t\t\t\tpointsRedu1.push_back(pointsRedu1_tmp.row(i));\n\t\t\t\tpointsRedu2.push_back(pointsRedu2_tmp.row(i));\n\t\t\t}\n\t\t}\n\t\tnpoints = pointsRedu1.rows;\n\t\t//pointsRedu1 = pointsRedu1.t();\n\t\tpointsRedu1 = pointsRedu1.reshape(2,1);\n\t\t//pointsRedu2 = pointsRedu2.t();\n\t\tpointsRedu2 = pointsRedu2.reshape(2,1);\n\t}\n\telse\n\t{\n\t\tif(_points1.channels() == 2)\n\t\t{\n\t\t\tpointsRedu1 = _points1;\n\t\t\tpointsRedu2 = _points2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//pointsRedu1 = _points1.t();\n\t\t\t//pointsRedu1 = pointsRedu1.reshape(2, 1);\n\t\t\tpointsRedu1 = _points1.reshape(2,1);\n\t\t\t//pointsRedu2 = _points2.t();\n\t\t\t//pointsRedu2 = pointsRedu2.reshape(2,1);\n\t\t\tpointsRedu2 = _points2.reshape(2, 1);\n\t\t}\n\t}\n\n\tif(npoints < 50)\n\t{\n\t\tE_init.getMat().copyTo(E_refined);\n\t\tcout << \"There are too less points for a refinement left!\" << endl;\n\t\treturn;\n\t}\n\tE = E_init.getMat().clone();\n\n\t//Thresholds for iterative refinement\n\tconst double minSumSqrErrDiff = th/10;\n\tconst double minSumSqrErr = th*th/100 * npoints;\n\tconst unsigned int maxIters = 50;\n\n    cv::Point2d m0c = cv::Point2d(0, 0);\n    cv::Point2d m1c = cv::Point2d(0, 0);\n//    CvPoint2D64f m0c = {0,0}, m1c = {0,0};\n    double t, scale0 = 0, scale1 = 0;\n\n    std::vector<Point2d> _m1, _m2;\n    _m1 = (std::vector<Point2d>) pointsRedu1;\n    _m2 = (std::vector<Point2d>) pointsRedu2;\n//\tconst CvPoint2D64f* _m1 = (const CvPoint2D64f*)pointsRedu1.data;\n//    const CvPoint2D64f* _m2 = (const CvPoint2D64f*)pointsRedu2.data;\n\n    int i;\n\n    // compute centers and average distances for each of the two point sets\n\tMat H0, H1;\n\tif (normalizeCorrs)\n\t{\n\t\tfor (i = 0; i < npoints; i++)\n\t\t{\n\t\t\tdouble x = _m1[i].x, y = _m1[i].y;\n\t\t\tm0c.x += x; m0c.y += y;\n\n\t\t\tx = _m2[i].x, y = _m2[i].y;\n\t\t\tm1c.x += x; m1c.y += y;\n\t\t}\n\n\t\t// calculate the normalizing transformations for each of the point sets:\n\t\t// after the transformation each set will have the mass center at the coordinate origin\n\t\t// and the average distance from the origin will be ~sqrt(2).\n\t\tt = 1. / npoints;\n\t\tif (model != 2)\n\t\t{\n\t\t\tm0c.x *= t; m0c.y *= t;\n\t\t\tm1c.x *= t; m1c.y *= t;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tt *= 0.5;\n\t\t\tm1c.x = m0c.x = (m0c.x + m1c.x) * t;\n\t\t\tm1c.y = m0c.y = (m0c.y + m1c.y) * t;\n\t\t}\n\n\t\tfor (i = 0; i < npoints; i++)\n\t\t{\n\t\t\tdouble x = _m1[i].x - m0c.x, y = _m1[i].y - m0c.y;\n\t\t\tscale0 += sqrt(x*x + y*y);\n\n\t\t\tx = _m2[i].x - m1c.x, y = _m2[i].y - m1c.y;\n\t\t\tscale1 += sqrt(x*x + y*y);\n\t\t}\n\n\t\tif (model != 2)\n\t\t{\n\t\t\tscale0 *= t;\n\t\t\tscale1 *= t;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tscale1 = scale0 = (scale0 + scale1) * t;\n\t\t}\n\n\t\tif (scale0 < FLT_EPSILON || scale1 < FLT_EPSILON)\n\t\t\treturn;\n\n\t\tscale0 = sqrt(2.) / scale0;\n\t\tscale1 = sqrt(2.) / scale1;\n\n\t\tH0 = (Mat_<double>(3, 3) << scale0, 0, -scale0*m0c.x,\n\t\t\t0, scale0, -scale0*m0c.y,\n\t\t\t0, 0, 1);\n\n\t\tH1 = (Mat_<double>(3, 3) << scale1, 0, -scale1*m1c.x,\n\t\t\t0, scale1, -scale1*m1c.y,\n\t\t\t0, 0, 1);\n\t}\n\n\ttypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic > TAMat;\n\tTAMat A1, A2;\n\n\tif(!model)\n\t{\n\t\tA1.resize(npoints, 9);\n\t\tA2.resize(9, 9);\n\t}\n\telse if(model == 1)\n\t{\n\t\tA1.resize(npoints, 5);\n\t\tA2.resize(5, 5);\n\t}\n\telse if(model == 2)\n\t{\n\t\tA1.resize(npoints, 3);\n\t\tA2.resize(3, 3);\n\t}\n\n\tMat F3 = E.clone();\n\n\tunsigned int j;\n\tfor(j = 0; j < (iters ? iters:maxIters); j++)\n\t{\n\t\t// form a linear system Ax=0: for each selected pair of points m1 & m2,\n\t\t// the row of A(=a) represents the coefficients of equation: (m2, 1)'*F*(m1, 1) = 0\n\t\t// to save computation time, we compute (At*A) instead of A and then solve (At*A)x=0.\n\t\tstd::vector<double> weights(npoints), denom1s(npoints);\n\t\tfor (i = 0; i < npoints; i++)\n\t\t{\n\t\t\tdouble denom1, num;\n\t\t\tSampsonL1(pointsRedu1.col(i).reshape(1, 2), pointsRedu2.col(i).reshape(1, 2), F3, denom1, num);\n\t\t\tconst double weight = costPseudoHuber(num*denom1, th);\n\t\t\tweights[i] = weight;\n\t\t\tdenom1s[i] = denom1;\n\t\t}\n\t\tdouble weightnorm = 0;\n\t\tfor (i = 0; i < npoints; i++)\n\t\t{\n\t\t\tweightnorm += pow(weights[i]* denom1s[i], 2);\n\t\t}\n\t\tweightnorm = sqrt(weightnorm);\n\n\t\tfor (i = 0; i < npoints; i++)\n\t\t{\n\n\n\t\t\tdouble x0;\n\t\t\tdouble y0;\n\t\t\tdouble x1;\n\t\t\tdouble y1;\n\t\t\tif (normalizeCorrs)\n\t\t\t{\n\t\t\t\tx0 = (_m1[i].x - m0c.x)*scale0;\n\t\t\t\ty0 = (_m1[i].y - m0c.y)*scale0;\n\t\t\t\tx1 = (_m2[i].x - m1c.x)*scale1;\n\t\t\t\ty1 = (_m2[i].y - m1c.y)*scale1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx0 = _m1[i].x;\n\t\t\t\ty0 = _m1[i].y;\n\t\t\t\tx1 = _m2[i].x;\n\t\t\t\ty1 = _m2[i].y;\n\t\t\t}\n\n\t\t\tif(!model)\n\t\t\t{\n\t\t\t\tA1(i, 0) = x1 * x0;\n\t\t\t\tA1(i, 1) = x1 * y0;\n\t\t\t\tA1(i, 2) = x1;\n\t\t\t\tA1(i, 3) = y1 * x0;\n\t\t\t\tA1(i, 4) = y1 * y0;\n\t\t\t\tA1(i, 5) = y1;\n\t\t\t\tA1(i, 6) = x0;\n\t\t\t\tA1(i, 7) = y0;\n\t\t\t\tA1(i, 8) = 1;\n\t\t\t}\n\t\t\telse if(model == 1)\n\t\t\t{\n\t\t\t\tA1(i, 0) = x1;\n\t\t\t\tA1(i, 1) = y1;\n\t\t\t\tA1(i, 2) = x0;\n\t\t\t\tA1(i, 3) = y0;\n\t\t\t\tA1(i, 4) = 1.0;\n\t\t\t}\n\t\t\telse if(model == 2)\n\t\t\t{\n\t\t\t\tdouble ww = x1 * y0 - x0 * y1;\n\t\t\t\tif(fabs(ww) < DBL_EPSILON)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tww = 1./ww;\n\n\t\t\t\tA1(i, 0) = (y1 - y0) * ww;\n\t\t\t\tA1(i, 1) = (x0 - x1) * ww;\n\t\t\t\tA1(i, 2) = 1.0;\n\t\t\t}\n\n\t\t\tA1.row(i) *= denom1s[i] * weights[i] / weightnorm; /* multiply by 1/dominator of the Sampson L1-distance to eliminate\n\t\t\t\t\t\t\t\t\t\t* it from the dominator of the pseudo-huber weight value (which is\n\t\t\t\t\t\t\t\t\t\t* actually sqrt(cost_pseudo_huber)/Sampson_L1_distance). This is\n\t\t\t\t\t\t\t\t\t\t* necessary because the SVD calculates the least squared algebraic\n\t\t\t\t\t\t\t\t\t\t* error of the fundamental matrix (x2^T*F*x1)^2. This algebraic\n\t\t\t\t\t\t\t\t\t\t* error is the same as the numerator of the Sampson distance and\n\t\t\t\t\t\t\t\t\t\t* should be replaced by the pseudo-huber cost function during SVD.\n\t\t\t\t\t\t\t\t\t\t*/\n\t\t}\n\n\t\tA2 = A1.transpose()*A1;\n\n\t\tEigen::Matrix3d F2;\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1> lastCol;\n\t\tif(!model)\n\t\t{\n\t\t\tEigen::EigenSolver<Eigen::Matrix<double,9,9>> eigA(A2);\n\t\t\tfor( i = 0; i < 9; i++ )\n\t\t\t{\n\t\t\t\tif( fabs(eigA.eigenvalues().real()[i]) < DBL_EPSILON )\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif( i < 8 )\n\t\t\t{\n\t\t\t\tE.copyTo(E_refined);\n\t\t\t\tcout << \"Refinement failed!\" << endl;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tdouble smallestEigVal = fabs(eigA.eigenvalues().real()[0]);\n\t\t\tint smallestEigValIdx = 0;\n\t\t\tfor( i = 1; i < 9; i++ )\n\t\t\t{\n\t\t\t\tif( fabs(eigA.eigenvalues().real()[i]) < smallestEigVal )\n\t\t\t\t{\n\t\t\t\t\tsmallestEigVal = fabs(eigA.eigenvalues().real()[i]);\n\t\t\t\t\tsmallestEigValIdx = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlastCol.resize(9,1);\n\t\t\tlastCol = eigA.eigenvectors().col(smallestEigValIdx).real();\n\n\t\t\t//Much slower then solving for eigenvectors of A^T*A\n\t\t\t/*Eigen::JacobiSVD<TAMat> svdA(A1, Eigen::ComputeFullV);\n\t\t\tlastCol = svdA.matrixV().col(8);*/\n\n\t\t\t//Convert to F\n\n\t\t\tF2 = Eigen::Matrix3d(lastCol.data());\n\t\t\tF2.transposeInPlace();\n\t\t\tif(makeClosestE)\n\t\t\t{\n\t\t\t\tif(getClosestE(F2))\n\t\t\t\t{\n\t\t\t\t\tcout << \"E is no essential matrix - taking last valid E!\" << endl;\n\t\t\t\t\t//E = H1.inv().t() * E * H0.inv();\n\t\t\t\t\t//cv::cv2eigen(E,F2);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(makeClosestE)\n\t\t\t{\n\t\t\t\tbool validE;\n\t\t\t\tif(mask.needed())\n\t\t\t\t\tvalidE = validateEssential(_points1, _points2, F2, false, mask, tryOrientedEpipolar);\n\t\t\t\telse\n\t\t\t\t\tvalidE = validateEssential(_points1, _points2, F2, false, cv::noArray(), tryOrientedEpipolar);\n\t\t\t\tif(!validE)\n\t\t\t\t{\n\t\t\t\t\tcout << \"E is no valid essential matrix - taking last valid E!\" << endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbool validE;\n\t\t\t\tif(mask.needed())\n\t\t\t\t\tvalidE = validateEssential(_points1, _points2, F2, true, mask, tryOrientedEpipolar);\n\t\t\t\telse\n\t\t\t\t\tvalidE = validateEssential(_points1, _points2, F2, true, cv::noArray(), tryOrientedEpipolar);\n\t\t\t\tif(!validE)\n\t\t\t\t{\n\t\t\t\t\tcout << \"E is no valid essential matrix - taking last valid E!\" << endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(model == 1)\n\t\t{\n\t\t\tEigen::EigenSolver<Eigen::Matrix<double,5,5>> eigA(A2);\n\t\t\tfor( i = 0; i < 5; i++ )\n\t\t\t{\n\t\t\t\tif( fabs(eigA.eigenvalues().real()[i]) < DBL_EPSILON )\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif( i < 5 )\n\t\t\t\treturn;\n\n\t\t\tdouble smallestEigVal = fabs(eigA.eigenvalues().real()[0]);\n\t\t\tint smallestEigValIdx = 0;\n\t\t\tfor( i = 1; i < 5; i++ )\n\t\t\t{\n\t\t\t\tif( fabs(eigA.eigenvalues().real()[i]) < smallestEigVal )\n\t\t\t\t{\n\t\t\t\t\tsmallestEigVal = fabs(eigA.eigenvalues().real()[i]);\n\t\t\t\t\tsmallestEigValIdx = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlastCol.resize(3,1);\n\t\t\tlastCol = eigA.eigenvectors().col(smallestEigValIdx).real();\n\n\t\t\t//Much slower then solving for eigenvectors of A^T*A\n\t\t\t/*Eigen::JacobiSVD<TAMat> svdA(A1, Eigen::ComputeFullV);\n\t\t\tEigen::Matrix<double, 5, 1 > lastCol = svdA.matrixV().col(4);*/\n\n\t\t\t//Convert to Fa\n\t\t\tF2 = Eigen::Matrix3d::Zero();\n\t\t\tF2(0,2) = lastCol(0);\n\t\t\tF2(1,2) = lastCol(1);\n\t\t\tF2(2,0) = lastCol(2);\n\t\t\tF2(2,1) = lastCol(3);\n\t\t\tF2(2,2) = lastCol(4);\n\n\t\t\tbool validE;\n\t\t\tif(mask.needed())\n\t\t\t\tvalidE = validateEssential(_points1, _points2, F2, false, mask, tryOrientedEpipolar);\n\t\t\telse\n\t\t\t\tvalidE = validateEssential(_points1, _points2, F2, false, cv::noArray(), tryOrientedEpipolar);\n\t\t\tif(!validE)\n\t\t\t{\n\t\t\t\tcout << \"E is no valid essential matrix - taking last valid E!\" << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if(model == 2)\n\t\t{\n\t\t\tEigen::EigenSolver<Eigen::Matrix<double,3,3>> eigA(A2);\n\t\t\tfor( i = 0; i < 3; i++ )\n\t\t\t{\n\t\t\t\tif( fabs(eigA.eigenvalues().real()[i]) < DBL_EPSILON )\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif( i < 3 )\n\t\t\t\treturn;\n\n\t\t\tdouble smallestEigVal = fabs(eigA.eigenvalues().real()[0]);\n\t\t\tint smallestEigValIdx = 0;\n\t\t\tfor( i = 1; i < 3; i++ )\n\t\t\t{\n\t\t\t\tif( fabs(eigA.eigenvalues().real()[i]) < smallestEigVal )\n\t\t\t\t{\n\t\t\t\t\tsmallestEigVal = fabs(eigA.eigenvalues().real()[i]);\n\t\t\t\t\tsmallestEigValIdx = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//Much slower then solving for eigenvectors of A^T*A\n\t\t\t/*Eigen::JacobiSVD<TAMat> svdA(A1, Eigen::ComputeFullV);\n\t\t\tEigen::Matrix<double, 5, 1 > lastCol = svdA.matrixV().col(4);*/\n\n\t\t\tlastCol.resize(3,1);\n\t\t\tlastCol = eigA.eigenvectors().col(smallestEigValIdx).real();\n\n\t\t\tlastCol /= lastCol.norm();\n\n\t\t\t//Convert to Ft\n\t\t\tF2 = Eigen::Matrix3d::Zero();\n\t\t\tF2(0,1) = lastCol(2);\n\t\t\tF2(0,2) = -1.0 * lastCol(1);\n\t\t\tF2(1,0) = -1.0 * lastCol(2);\n\t\t\tF2(1,2) = lastCol(0);\n\t\t\tF2(2,0) = lastCol(1);\n\t\t\tF2(2,1) = -1.0 * lastCol(0);\n\n\t\t\tbool validE;\n\t\t\tif(mask.needed())\n\t\t\t\tvalidE = validateEssential(_points1, _points2, F2, false, mask, tryOrientedEpipolar);\n\t\t\telse\n\t\t\t\tvalidE = validateEssential(_points1, _points2, F2, false, cv::noArray(), tryOrientedEpipolar);\n\t\t\tif(!validE)\n\t\t\t{\n\t\t\t\tcout << \"E is no valid essential matrix - taking last valid E!\" << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tcv::eigen2cv(F2,F3);\n\t\tif(normalizeCorrs)\n\t\t\tF3 = H1.t() * F3 * H0;\n\n\n\t\tif(!iters)\n\t\t{\n\t\t\terr = (A1 * lastCol).squaredNorm();\n\t\t\t//if(err < err_min)\n\t\t\t//{\n\t\t\t//\tE_refined = F3.clone();\n\t\t\t//\terr_min = err;\n\t\t\t//}\n\t\t\tconst double errdiff = abs(err_old - err);\n\t\t\tif((j > 1) && ((errdiff < minSumSqrErrDiff) ||\n\t\t\t\t(err < minSumSqrErr)))\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\terr_old = err;\n\t\t}\n\t\telse if((j == (iters-1)) && sumSqrErr)\n\t\t{\n\t\t\terr = (A1 * lastCol).squaredNorm();\n\t\t}\n\n\t\tif(!j && sumSqrErr_init)\n\t\t{\n\t\t\tif(!iters) *sumSqrErr_init = err;\n\t\t\telse *sumSqrErr_init = (A1 * lastCol).squaredNorm();\n\t\t}\n\t}\n\n\tif(sumSqrErr && j) *sumSqrErr = err;\n\n\tif(errors.needed())\n\t{\n\t\terrors.create(npoints,1, CV_64FC1);\n\t\tMat sdist = errors.getMat();\n\t\tfor(i = 0; i < npoints; i++)\n\t\t{\n\t\t\tdouble denom1, num;\n\t\t\tSampsonL1(_points1.col(i).reshape(1,2), _points2.col(i).reshape(1,2), F3, denom1, num);\n\t\t\tsdist.row(i) = denom1 * denom1 * num * num;\n\t\t}\n\t}\n\n\tE_refined = F3.clone();\n\t/*if(model != 2)\n\t\tE_refined /= E_refined.at<double>(2,2);\n\telse*/\n\t\t//cv::normalize(E_refined, E_refined);\n}\n\n\n/* Estimation of the Essential matrix based on the 5-pt Nister algorithm integrated in an ARRSAC, RANSAC or LMEDS framework. For\n * ARRSAC optional refinement (refine=true) is performed using a Pseudo Huber cost function. For RANSAC optional refinement\n * (refine=true) is performed using a least squares solution. For LMEDS no refinement is available.\n *\n * OutputArray E\t\t\t\t\t\tOutput -> Essential matrix\n * InputArray p1\t\t\t\t\t\tInput  -> Observed point coordinates of the left image in the camera coordinate system\n *\t\t\t\t\t\t\t\t\t\t\t\t  (n rows, 2 cols)\n * InputArray p2\t\t\t\t\t\tInput  -> Observed point coordinates of the right image in the camera coordinate system\n *\t\t\t\t\t\t\t\t\t\t\t\t  (n rows, 2 cols)\n * string method\t\t\t\t\t\tInput  -> Name of preferred algorithm: ARRSAC, RANSAC, or LMEDS [Default = ARRSAC]\n * double threshold\t\t\t\t\t\tInput  -> Threshold [Default=PIX_MIN_GOOD_TH]\n * bool refine\t\t\t\t\t\t\tInput  -> If true [Default=true], the essential matrix is refined (except for LMEDS)\n * OutputArray mask\t\t\t\t\t\tOutput -> Inlier mask\n *\n * Return value:\t\t\t\t\t\ttrue :\tSuccess\n *\t\t\t\t\t\t\t\t\t\tfalse:\tFailed\n */\nbool estimateEssentialMat(cv::OutputArray E,\n        cv::InputArray p1,\n        cv::InputArray p2,\n        const std::string &method,\n        double threshold,\n        bool refine,\n        cv::OutputArray mask)\n{\n\tbool result = false;\n\tif(method == \"ARRSAC\")\n\t{\n\t\tresult = findEssentialMat(E, p1, p2, ARRSAC, 0.999, threshold, mask, refine, robustEssentialRefine); //ARRSAC with optional robust refinement using a Pseudo Huber cost function\n\t}\n\telse if(method == \"RANSAC\")\n\t{\n\t\tresult = findEssentialMat(E, p1, p2, cv::RANSAC, 0.999, threshold, mask, refine); //RANSAC with possible subsequent least squares solution\n\t}\n\telse if(method == \"LMEDS\")//Only LMEDS without least squares solution\n\t{\n\t\tresult = findEssentialMat(E, p1, p2, cv::LMEDS, 0.999, threshold, mask);\n\t}\n\telse if (method == \"USAC\")\n\t{\n\t\tcout << \"USAC must be executed by function estimateEssentialOrPoseUSAC as it needs additional paramters! Exiting.\" << endl;\n\t\texit(1);\n\t}\n\telse\n\t{\n\t\tcout << \"Either there is a typo in the specified robust estimation method or the method is not supported. Exiting.\" << endl;\n\t\texit(1);\n\t}\n\n\treturn result;\n}\n\n/* Recovers the rotation and translation from an essential matrix and triangulates the given correspondences to form 3D coordinates.\n * If the given essential matrix corresponds to a translational essential matrix, set \"translatE\" to true. Moreover 3D coordintes with\n * a z-value lager than \"dist\" are marked as invalid within \"mask\" due to their numerical instability (such 3D points are also not\n * considered in the returned number of valid 3D points.\n *\n * InputArray E\t\t\t\t\t\t\tInput  -> Essential matrix\n * InputArray p1\t\t\t\t\t\tInput  -> Observed point coordinates of the left image in the camera coordinate system\n *\t\t\t\t\t\t\t\t\t\t\t\t  (n rows, 2 cols)\n * InputArray p2\t\t\t\t\t\tInput  -> Observed point coordinates of the right image in the camera coordinate system\n *\t\t\t\t\t\t\t\t\t\t\t\t  (n rows, 2 cols)\n * OutputArray R\t\t\t\t\t\tOutput -> Rotation matrix\n * OutputArray t\t\t\t\t\t\tOutput -> Translation vector (3 rows x 1 column)\n * OutputArray Q\t\t\t\t\t\tOutput -> Triangulated 3D-points including invalid points (n rows x 3 columns)\n * InputOutputArray mask\t\t\t\tI/O\t   -> Inlier mask / Valid 3D points [Default=noArray()]\n * double dist\t\t\t\t\t\t\tInput  -> Threshold on the distance of the normalized 3D coordinates to the camera [Default=50]\n * bool translatE\t\t\t\t\t\tInput  -> Should be true, if a translational essential matrix is given (R corresponds to identity)\n *\t\t\t\t\t\t\t\t\t\t\t\t  [Default=false]\n *\n * Return value:\t\t\t\t\t\t>=0:\tNumber of valid 3D points\n *\t\t\t\t\t\t\t\t\t\t-1:\t\tR, t, or Q are mandatory output variables (one or more are missing)\n */\nint getPoseTriangPts(cv::InputArray E,\n        cv::InputArray p1,\n        cv::InputArray p2,\n        cv::OutputArray R,\n        cv::OutputArray t,\n        cv::OutputArray Q,\n        cv::InputOutputArray mask,\n        const double dist,\n        bool translatE)\n{\n\tint n;\n\tMat R_, t_, Q_;\n\tif(!R.needed() || !t.needed() || !Q.needed())\n\t\treturn -1;\n\n\tn = recoverPose( E.getMat(), p1.getMat(), p2.getMat(), R_, t_, Q_, mask, dist, translatE ? getTfromTransEssential(E.getMat()):(cv::noArray()));\n\n\tif(R.empty())\n\t{\n\t\tR.create(3, 3, CV_64F);\n\t}\n\tR_.copyTo(R.getMat());\n\n\tif(t.empty())\n\t{\n\t\tt.create(3, 1, CV_64F);\n\t}\n\tt_.copyTo(t.getMat());\n\n\tQ.create(Q_.size(),Q_.type());\n\tQ_.copyTo(Q.getMat());\n\n\treturn n;\n}\n\n/* Triangulates 3D-points from correspondences with provided R and t. The world coordinate\n * system is located in the left camera centre.\n *\n * InputArray R\t\t\t\t\t\t\tInput  -> Rotation matrix R\n * InputArray t\t\t\t\t\t\t\tInput  -> Translation vector t\n * InputArray _points1\t\t\t\tInput  -> Image projections in the left camera\n *\t\t\t\t\t\t\t\t\t\t\t  in camera coordinates (1 projection per row)\n * InputArray _points2\t\t\t\tInput  -> Image projections in the right camera\n *\t\t\t\t\t\t\t\t\t\t\t  in camera coordinates (1 projection per row)\n * Mat & Q3D\t\t\t\t\t\tOutput -> Triangulated 3D points (1 coordinate per row)\n * Mat & mask\t\t\t\t\t\tOutput -> Mask marking points near infinity (mask(i) = 0)\n * double dist\t\t\t\t\t\tInput  -> Optional threshold (Default: 50.0) for far points (near infinity)\n *\n * Return value:\t\t\t\t\t>= 0:\tValid triangulated 3D-points\n *\t\t\t\t\t\t\t\t\t  -1:\tThe matrix for the 3D points must be provided\n */\nint triangPts3D(cv::InputArray R, cv::InputArray t, cv::InputArray _points1, cv::InputArray _points2, cv::OutputArray Q3D, cv::InputOutputArray mask, const double dist)\n{\n\tMat points1, points2;\n\tpoints1 = _points1.getMat();\n\tpoints2 = _points2.getMat();\n\tMat R_ = R.getMat();\n\tMat t_ = t.getMat();\n\tMat mask_;\n//\tint npoints = points1.checkVector(2);\n\tif(mask.needed())\n\t{\n\t\tmask_ = mask.getMat();\n\t}\n\n\tpoints1 = points1.t();\n\tpoints2 = points2.t();\n\n\tMat P0 = Mat::eye(3, 4, R_.type());\n\tMat P1(3, 4, R_.type());\n\tP1(Range::all(), Range(0, 3)) = R_ * 1.0;\n\tP1.col(3) = t_ * 1.0;\n\n\t// Notice here a threshold dist is used to filter\n\t// out far away points (i.e. infinite points) since\n\t// there depth may vary between postive and negtive.\n\t//const double dist = 50.0;\n\tMat Q1,q1;\n\ttriangulatePoints(P0, P1, points1, points2, Q1);\n\tif(Q1.empty() || (Q1.cols == 0)){\n\t    return -1;\n\t}\n\n\tq1 = P1 * Q1;\n\tif(mask_.empty())\n\t{\n\t\tmask_ = (q1.row(2).mul(Q1.row(3)) > 0);\n\t}\n\telse\n\t{\n\t\tmask_ = (q1.row(2).mul(Q1.row(3)) > 0) & mask_;\n\t}\n\n\tQ1.row(0) /= Q1.row(3);\n\tQ1.row(1) /= Q1.row(3);\n\tQ1.row(2) /= Q1.row(3);\n\tmask_ = (Q1.row(2) < dist) & (Q1.row(2) > 0) & mask_;\n\n\tif(!Q3D.needed())\n\t\treturn -1; //The matrix for the 3D points must be provided\n\n\tQ3D.create(Q1.cols, 3, Q1.type());\n\tMat Q3D_tmp = Q3D.getMat();\n\tQ3D_tmp = Q1.rowRange(0,3).t();\n\n\t/*points1 = points1.t();\n\tpoints2 = points2.t();\n\n\tdouble scale = 0;\n\tdouble scale1 = 0;\n\tMat Qs;\n\tfor(int i = 0; i < points1.rows;i++)\n\t{\n\t\tscale = points1.at<double>(i,0) * Q3D.at<double>(i,2) / Q3D.at<double>(i,0);\n\t\tscale += points1.at<double>(i,1) * Q3D.at<double>(i,2) / Q3D.at<double>(i,1);\n\t\tscale /= 2;\n\t\tif(abs(scale - 1.0) > 0.001)\n\t\t{\n\t\t\tQ3D.row(i) *= scale;\n\t\t\tscale = points1.at<double>(i,0) * Q3D.at<double>(i,2) / Q3D.at<double>(i,0);\n\t\t\tscale += points1.at<double>(i,1) * Q3D.at<double>(i,2) / Q3D.at<double>(i,1);\n\t\t\tscale /= 2;\n\t\t}\n\t\tQs = R_*Q3D.row(i).t() + t_;\n\t\tscale1 = points2.at<double>(i,0) * Qs.at<double>(2) / Qs.at<double>(0);\n\t\tscale1 += points2.at<double>(i,1) * Qs.at<double>(2) / Qs.at<double>(1);\n\t\tscale1 /= 2;\n\t}\n\t//scale /= points1.rows * 2;*/\n\n\treturn countNonZero(mask_);\n}\n\n/* Bundle adjustment (BA) on motion (=extrinsics) and structure with or without camera metrices. For refinement of motion and structure without intrinsics,\n * the correspondences p1 and p2 must be in the camera coordinate system (pointsInImgCoords=false). Otherwise the correspondences must be\n * in the image coordinate system (pointsInImgCoords=true). If a mask is provided, only structure elements and correspondences marked as valid\n * used for BA. If BA fails or the refined motion differs too much from the initial motion (thresholds can be modified with angleThresh and t_norm_tresh),\n * the initial motion and structure are stored and the refined data is rejected.\n *\n * InputArray p1\t\t\t\t\t\tInput  -> Observed point coordinates of the first image in the camera (pointsInImgCoords=false) or image\n *\t\t\t\t\t\t\t\t\t\t\t\t  (pointsInImgCoords=true) coordinate system (n rows, 2 cols). If pointsInImgCoords=false or \n \t\t\t\t\t\t\t\t\t\t\t\t  dist1 and dist2 are not provided, points must be undistorted.\n * InputArray p2\t\t\t\t\t\tInput  -> Observed point coordinates of the second image in the camera (pointsInImgCoords=false) or image\n *\t\t\t\t\t\t\t\t\t\t\t\t  (pointsInImgCoords=true) coordinate system (n rows, 2 cols). If pointsInImgCoords=false or \n \t\t\t\t\t\t\t\t\t\t\t\t  dist1 and dist2 are not provided, points must be undistorted.\n * InputOutputArray R\t\t\t\t\tI/O\t   -> Rotation matrix\n * InputOutputArray t\t\t\t\t\tI/O\t   -> Translation vector (3 rows x 1 column)\n * InputOutputArray Q\t\t\t\t\tI/O\t   -> Triangulated 3D-points (n rows x 3 columns)\n * InputOutputArray K1\t\t\t\t\tI/O\t   -> Camera matrix of the first camera\n * InputOutputArray K2\t\t\t\t\tI/O\t   -> Camera matrix of the second camera\n * bool pointsInImgCoords\t\t\t\tInput  -> Must be true if p1 and p2 are in image coordinates (pixels) or false if they are in camera coordinates\n *\t\t\t\t\t\t\t\t\t\t\t\t  [Default=false]. If true, BA is always performed with intrinsics.\n * InputOutputArray mask\t\t\t\tInput  -> Inlier mask [Default=cv::noArray()]\n * double angleThresh\t\t\t\t\tInput  -> Threshold on the angular difference in degrees between the initial and refined rotation matrices [Default=1.25]\n * double t_norm_tresh\t\t\t\t\tInput  -> Threshold on the norm of the difference between initial and refined translation vectors [Default=0.05]\n * double huber_thresh\t\t\t\t\tInput  -> Threshold for the Pseudo-Huber cost function in the image coordinate system (pixels)\n * bool optimFocalOnly\t\t\t\t\tInput  -> If pointsInImgCoords=true, only the focal length is optimized (in addition to extrinsics and optionally\n * \t\t\t\t\t\t\t\t\t\t\t\t  structure and distortion)\n * bool optimMotionOnly\t\t\t\t\tInput  -> Only extrinsics and intrinsics are optimized, structure remains fixed.\n * bool fixCamMat\t\t\t\t\t\tInput  -> All parameters within camera matrices are fixed - only extrinsics, distortion, and/or structure are optimized.\n * InputOutputArray dist1\t\t\t\tI/O\t   -> Exactly 5 distortion coeffitients (k1, k2, t1, t2, k3) of the first camera. \n * \t\t\t\t\t\t\t\t\t\t\t\t  If provided, also dist2 has to be provided. Only if both are provided and pointsInImgCoords=true, \n * \t\t\t\t\t\t\t\t\t\t\t\t  they are optimized.\n * InputOutputArray dist2\t\t\t\tI/O\t   -> Exactly 5 distortion coeffitients (k1, k2, t1, t2, k3) of the second camera. \n * \t\t\t\t\t\t\t\t\t\t\t\t  If provided, also dist1 has to be provided. Only if both are provided and pointsInImgCoords=true, \n * \t\t\t\t\t\t\t\t\t\t\t\t  they are optimized.\n *\n * Return value:\t\t\t\t\t\ttrue :\tSuccess\n *\t\t\t\t\t\t\t\t\t\tfalse:\tFailed\n */\nbool refineStereoBA(cv::InputArray p1,\n\t\t\t\t\tcv::InputArray p2,\n\t\t\t\t\tcv::InputOutputArray R,\n\t\t\t\t\tcv::InputOutputArray t,\n\t\t\t\t\tcv::InputOutputArray Q,\n\t\t\t\t\tcv::InputOutputArray K1,\n\t\t\t\t\tcv::InputOutputArray K2,\n\t\t\t\t\tbool pointsInImgCoords,\n\t\t\t\t\tcv::InputArray mask,\n\t\t\t\t\tconst double angleThresh,\n\t\t\t\t\tconst double t_norm_tresh,\n\t\t\t\t\tconst double huber_thresh,\n\t\t\t\t\tconst bool optimFocalOnly,\n\t\t\t\t\tconst bool optimMotionOnly,\n\t\t\t\t\tconst bool fixCamMat,\n\t\t\t\t\tcv::InputOutputArray dist1,\n\t\t\t\t\tcv::InputOutputArray dist2)\n{\n    if(p1.empty() || p2.empty() || Q.empty()){\n        return false;\n    }\n    if((p1.rows() != p2.rows()) || (p1.rows() != Q.rows())){\n        return false;\n    }\n\t/*const double angleThresh = 0.3;\n\tconst double t_norm_tresh = 0.05;*/\n\tBAinfo info;\n\tdouble t_norm;\n\tstd::vector<double *> t_vec;\n\tstd::vector<double *> R_vec;\n\tEigen::Matrix3d R1e;\n\tEigen::Vector4d R1quat, R1quat_old;\n\tdouble R0[4] = {1.0,0.0,0.0,0.0};\n\tdouble t0[3] = {0.0,0.0,0.0};\n\tstd::vector<double *> pts2D_vec;\n\tstd::vector<int> num2Dpts;\n\tMat t_ = t.getMat();\n\tMat Rq_new;\n\tdouble r_diff, t_diff;\n\tEigen::Vector3d t1e, t2e;\n\tMat t_after_refine;\n\tMat K1_tmp, K2_tmp;\n\tMat p1_tmp, p2_tmp, Q_tmp;\n\n\tint optPars = BA_MOTSTRUCT;\n\tif (optimMotionOnly){\n\t\toptPars = BA_MOT;\n\t}\n\n\tdouble th = huber_thresh;\n\tif (th < 0)\n\t{\n\t\tth = ROBUST_THRESH;\n\t}\n\n\t//Prepare input data for the BA interface\n\tdouble *pts3D_vec = nullptr;\n\n\tcv::cv2eigen(R.getMat(),R1e);\n\tMatToQuat(R1e, R1quat);\n\tR1quat_old = R1quat;\n\n\tt_vec.push_back(t0);\n\tt_vec.push_back((double*)t_.data);\n\n\tR_vec.push_back(R0);\n\tR_vec.push_back((double *)R1quat.data());\n\n\tif(mask.empty())\n\t{\n\t\tQ_tmp = Q.getMat().clone();\n\t\tpts3D_vec = (double*)Q_tmp.data;\n\n\t\tnum2Dpts.push_back((int)(p1.getMat().rows));\n\t\tnum2Dpts.push_back((int)(p2.getMat().rows));\n\n\t\tpts2D_vec.push_back((double *)p1.getMat().data);\n\t\tpts2D_vec.push_back((double *)p2.getMat().data);\n\t}\n\telse\n\t{\n\t\tMat mask_ = mask.getMat();\n\t\tMat p1_ = p1.getMat();\n\t\tMat p2_ = p2.getMat();\n\t\tMat Q_ = Q.getMat();\n\t\tint n = p1_.rows;\n\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tif(mask_.at<unsigned char>(i))\n\t\t\t{\n\t\t\t\tp1_tmp.push_back(p1_.row(i));\n\t\t\t\tp2_tmp.push_back(p2_.row(i));\n\t\t\t\tQ_tmp.push_back(Q_.row(i));\n\t\t\t}\n\t\t}\n\t\tpts3D_vec = (double*)Q_tmp.data;\n\n\t\tnum2Dpts.push_back((int)(p1_tmp.rows));\n\t\tnum2Dpts.push_back((int)(p2_tmp.rows));\n\n\t\tpts2D_vec.push_back((double *)p1_tmp.data);\n\t\tpts2D_vec.push_back((double *)p2_tmp.data);\n\t}\n\n\tt_after_refine = t_.clone();\n\n\tif(!pointsInImgCoords) //BA for extrinsics and structure\n\t{\n\t\tEigen::Vector4d R1quat_old2;\n\n\t\t//Convert the threshold into the camera coordinate system\n\t\tth = 4.0*th/(std::sqrt((double)2)*(K1.getMat().at<double>(1,1)+K1.getMat().at<double>(2,2)+K2.getMat().at<double>(1,1)+K2.getMat().at<double>(2,2)));\n\n\t\tSBAdriver optiMotStruct(true, optPars, COST_PSEUDOHUBER, th, optPars);\n\n\t\tif(optiMotStruct.perform_sba(R_vec,t_vec,pts2D_vec,num2Dpts,pts3D_vec,Q_tmp.rows) < 0)\n\t\t{\n\t\t\tt_ = t_after_refine.clone();\n\t\t\treturn false; //BA failed\n\t\t}\n\n\t\tinfo = optiMotStruct.getFinalSBAinfo();\n\t}\n\telse //BA with internals\n\t{\n\t\tMat K1_ = K1.getMat();\n\t\tMat K2_ = K2.getMat();\n\n\t\tvector<double *> intr_vec;\n\t\tdouble intr1[5] = {K1_.at<double>(0, 0), K1_.at<double>(0, 2), K1_.at<double>(1, 2), K1_.at<double>(1, 1) / K1_.at<double>(0, 0), 0.};\n\t\tintr_vec.push_back(intr1);\n\n\t\tdouble intr2[5] = {K2_.at<double>(0, 0), K2_.at<double>(0, 2), K2_.at<double>(1, 2), K2_.at<double>(1, 1) / K2_.at<double>(0, 0), 0.};\n\t\tintr_vec.push_back(intr2);\n\n\t\tint optimInternals = 2;\n\t\tif (optimFocalOnly)\n\t\t{\n\t\t\toptimInternals = 4;\n\t\t}\n\n\t\tdouble dist1_arr[5] = {0, 0, 0, 0, 0};\n\t\tdouble dist2_arr[5] = {0, 0, 0, 0, 0};\n\t\tvector<double *> dist_vec, *dist_vec_ptr = nullptr;\n\t\tif (!dist1.empty() && !dist2.empty())\n\t\t{\n\t\t\tMat dist1_ = dist1.getMat();\n\t\t\tMat dist2_ = dist2.getMat();\n\t\t\tif (!nearZero(cv::sum(dist1_)[0]))\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 5; i++)\n\t\t\t\t{\n\t\t\t\t\tdist1_arr[i] = dist1_.at<double>(i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdist_vec.push_back(dist1_arr);\n\t\t\tif (!nearZero(cv::sum(dist2_)[0]))\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 5; i++)\n\t\t\t\t{\n\t\t\t\t\tdist2_arr[i] = dist2_.at<double>(i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdist_vec.push_back(dist2_arr);\n\t\t\tdist_vec_ptr = &dist_vec;\n\t\t\tif (fixCamMat)\n\t\t\t{\n\t\t\t\toptimInternals = 5;\n\t\t\t}\n\t\t}\n\n\t\tSBAdriver optiMotStruct(false, optPars, COST_PSEUDOHUBER, th, optPars, optimInternals, 0, 0, 0, true);\n\n\t\tif (optiMotStruct.perform_sba(R_vec, t_vec, pts2D_vec, num2Dpts, pts3D_vec, Q_tmp.rows, nullptr, &intr_vec, dist_vec_ptr) < 0)\n\t\t{\n\t\t\t/*this->t = oldRTs.back().second.clone(); //-------------------------------> these two lines are executed within uncalibratedRectify for bundle adjustment with internal paramters (if it fails)\n\t\t\tdelLastPose(true);*/\n\t\t\tt_ = t_after_refine.clone();\n\t\t\treturn false; //BA failed\n\t\t}\n\n\t\tinfo = optiMotStruct.getFinalSBAinfo();\n\n\t\tK1_tmp = cv::Mat::eye(3,3,CV_64FC1);\n\t\tK2_tmp = cv::Mat::eye(3,3,CV_64FC1);\n\n\t\tK1_tmp.at<double>(0,0) = intr1[0];\n\t\tK1_tmp.at<double>(0,2) = intr1[1];\n\t\tK1_tmp.at<double>(1,2) = intr1[2];\n\t\tK1_tmp.at<double>(1,1) = intr1[3] * intr1[0];\n\n\t\tK2_tmp.at<double>(0,0) = intr2[0];\n\t\tK2_tmp.at<double>(0,2) = intr2[1];\n\t\tK2_tmp.at<double>(1,2) = intr2[2];\n\t\tK2_tmp.at<double>(1,1) = intr2[3] * intr2[0];\n\n\t\tif (!dist1.empty() && !dist2.empty()){\n\t\t\tMat dist1_ = dist1.getMat();\n\t\t\tMat dist2_ = dist2.getMat();\n\t\t\tfor (int i = 0; i < 5; i++)\n\t\t\t{\n\t\t\t\tdist1_.at<double>(i) = dist1_arr[i];\n\t\t\t\tdist2_.at<double>(i) = dist2_arr[i];\n\t\t\t}\n\t\t}\n\n\t\t// free(intr1);\n\t\t// free(intr2);\n\t}\n\n\t//Normalize the translation vector\n\tt_norm = cv::norm(t_);\n\tif(!nearZero(t_norm) && std::abs(t_norm - 1.0) > 1e-4)\n\t\tt_ /= t_norm;\n\n\t//Check for the difference of extrinsics before and after BA to detect possible local minimas\n\tt1e << t_after_refine.at<double>(0), t_after_refine.at<double>(1), t_after_refine.at<double>(2);\n\tt2e << t_.at<double>(0), t_.at<double>(1), t_.at<double>(2);\n\n\tgetRTQuality(R1quat_old, R1quat, t1e, t2e, &r_diff, &t_diff);\n\tr_diff = r_diff/PI * 180.0;\n\tif((abs(r_diff) > angleThresh) || (t_diff > t_norm_tresh) ||\n\t\t(info.terminatingReason > 5))\n\t{\n\t\t/*this->t = oldRTs.back().second.clone(); //-------------------------------> these two lines are executed within uncalibratedRectify for bundle adjustment with internal paramters (if it fails)\n\t\tdelLastPose(true);*/\n\t\tt_ = t_after_refine.clone();\n\t\treturn false; //BA failed\n\t}\n\n\t//Store the refined paramteres\n\tif (!optimMotionOnly){\n\t\tif (mask.empty())\n\t\t{\n\t\t\tQ_tmp.copyTo(Q.getMat());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tMat mask_ = mask.getMat();\n\t\t\tMat Q_ = Q.getMat();\n\t\t\tint j = 0, n = Q_.rows;\n\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\tif (mask_.at<unsigned char>(i))\n\t\t\t\t{\n\t\t\t\t\tQ_tmp.row(j).copyTo(Q_.row(i));\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif(pointsInImgCoords)\n\t{\n\t\tK1_tmp.copyTo(K1.getMat());\n\t\tK2_tmp.copyTo(K2.getMat());\n\t}\n\n\tcv::eigen2cv(R1quat,Rq_new);\n\tMat R_new = R.getMat();\n\tquatToMatrix(R_new,Rq_new);\n\n\treturn true;\n}\n\n/* Bundle adjustment (BA) on motion (=extrinsics) and structure with or without camera metrices and/or distortion. \n * For refinement of motion and structure without intrinsics, the correspondences p1 and p2 must be in the \n * camera coordinate system (pointsInImgCoords=false). Otherwise the correspondences must be\n * in the image coordinate system (pointsInImgCoords=true). If a mask is provided, only structure elements and correspondences marked as valid\n * are used for BA. If BA fails or the refined motion differs too much from the initial motion \n * (thresholds can be modified with angleThresh and t_norm_tresh), the initial motion and structure are stored and the refined data is rejected.\n *\n * InputArray ps\t\t\t\t\t\tInput  -> Observed point coordinates of all images in the camera (pointsInImgCoords=false) or image\n *\t\t\t\t\t\t\t\t\t\t\t\t  (pointsInImgCoords=true) coordinate system (vector<Mat>(n rows, 2 cols)). \n *\t\t\t\t\t\t\t\t\t\t\t\t  If pointsInImgCoords=false or dists are not provided, points must be undistorted. \n *\t\t\t\t\t\t\t\t\t\t\t\t  The ordering must be the same as in \"Qs\".\n * InputArray map3D\t\t\t\t\t\tInput  -> Masks of type char with the same size as Qs for every camera (vector<Mat>(n rows/cols)).\n * \t\t\t\t\t\t\t\t\t\t\t\t  The ordering of corresponding 2D points in \"ps\" must be the same as in \"Qs\"\n * InputOutputArray Rs\t\t\t\t\tI/O\t   -> Rotation matrices (vector<Mat>(3 rows, 3 cols))\n * InputOutputArray ts\t\t\t\t\tI/O\t   -> Translation vectors (vector<Mat>(3 rows x 1 column))\n * InputOutputArray Qs\t\t\t\t\tI/O\t   -> Triangulated 3D-points (Mat(n rows x 3 columns))\n * InputOutputArray Ks\t\t\t\t\tI/O\t   -> Camera matrices (vector<Mat>(3 rows, 3 cols))\n\n * bool pointsInImgCoords\t\t\t\tInput  -> Must be true if ps are in image coordinates (pixels) or false if they are in camera coordinates\n *\t\t\t\t\t\t\t\t\t\t\t\t  [Default=false]. If true, BA is always performed with intrinsics.\n * InputArray masks\t\t\t\t\t\tInput  -> Inlier masks [Default=cv::noArray()]: vector<Mat<unsigned char>>(n rows)\n * double angleThresh\t\t\t\t\tInput  -> Threshold on the angular difference in degrees between the initial and refined rotation matrices [Default=1.25]\n * double t_norm_tresh\t\t\t\t\tInput  -> Threshold on the norm of the difference between initial and refined translation vectors [Default=0.05]\n * double huber_thresh\t\t\t\t\tInput  -> Threshold for the Pseudo-Huber cost function in the image coordinate system (pixels)\n * bool optimFocalOnly\t\t\t\t\tInput  -> If pointsInImgCoords=true, only the focal length is optimized (in addition to extrinsics and optionally\n * \t\t\t\t\t\t\t\t\t\t\t\t  structure and distortion)\n * bool optimMotionOnly\t\t\t\t\tInput  -> Only extrinsics and intrinsics are optimized, structure remains fixed.\n * bool fixCamMat\t\t\t\t\t\tInput  -> All parameters within camera matrices are fixed - only extrinsics, distortion, and/or structure are optimized.\n * InputOutputArray dists\t\t\t\tI/O\t   -> Exactly 5 distortion coeffitients (k1, k2, t1, t2, k3) for all cameras (vector<Mat>(5 coeffitients)). \n * \t\t\t\t\t\t\t\t\t\t\t\t  Only if pointsInImgCoords=true, they are optimized.\n *\n * Return value:\t\t\t\t\t\ttrue :\tSuccess\n *\t\t\t\t\t\t\t\t\t\tfalse:\tFailed\n */\nbool refineMultCamBA(cv::InputArray ps,\n\t\t\t\t\t cv::InputArray map3D,\n\t\t\t\t\t cv::InputOutputArray Rs,\n\t\t\t\t\t cv::InputOutputArray ts,\n\t\t\t\t\t cv::InputOutputArray Qs,\n\t\t\t\t\t cv::InputOutputArray Ks,\n\t\t\t\t\t bool pointsInImgCoords,\n\t\t\t\t\t cv::InputArray masks,\n\t\t\t\t\t const double angleThresh,\n\t\t\t\t\t const double t_norm_tresh,\n\t\t\t\t\t const double huber_thresh,\n\t\t\t\t\t const bool optimFocalOnly,\n\t\t\t\t\t const bool optimMotionOnly,\n\t\t\t\t\t const bool fixCamMat,\n\t\t\t\t\t cv::InputOutputArray dists)\n{\n\tif (ps.empty() || Qs.empty() || map3D.empty() || Rs.empty() || ts.empty() || Ks.empty())\n\t{\n\t\tcerr << \"Some input variables to BA are empty. Skipping!\" << endl;\n\t\treturn false;\n\t}\n\tif (!ps.isMatVector() || !map3D.isMatVector() || !Rs.isMatVector() || !ts.isMatVector() || !Ks.isMatVector())\n\t{\n\t\tcerr << \"Inputs must be of type vector<Mat>. Skipping!\" << endl;\n\t\treturn false;\n\t}\n\tif(!Qs.isMat())\n\t{\n\t\tcerr << \"Input Qs must be of type Mat. Skipping!\" << endl;\n\t\treturn false;\n\t}\n\tMat Q = Qs.getMat();\n\tint nr_Qs = Q.size().height;\n\tif(nr_Qs < 15){\n\t\tcerr << \"Too less 3D points. Skipping!\" << endl;\n\t\treturn false;\n\t}\n\n\tvector<Mat> p2D_vec, map3D_vec, R_mvec, t_mvec, K_vec;\n\tps.getMatVector(p2D_vec);\n\tmap3D.getMatVector(map3D_vec);\n\tRs.getMatVector(R_mvec);\n\tts.getMatVector(t_mvec);\n\tKs.getMatVector(K_vec);\n\tconst size_t vecSi = p2D_vec.size();\n\tif (map3D_vec.size() != vecSi || R_mvec.size() != vecSi || t_mvec.size() != vecSi || K_vec.size() != vecSi)\n\t{\n\t\tcerr << \"Inputs of type vector<Mat> must be of same size. Skipping!\" << endl;\n\t\treturn false;\n\t}\n\tbool haveMasks = false;\n\tvector<Mat> kpMask_vec;\n\tif (!masks.empty())\n\t{\n\t\tmasks.getMatVector(kpMask_vec);\n\t\tif (kpMask_vec.size() != vecSi)\n\t\t{\n\t\t\tcerr << \"Input masks of type vector<Mat> must be of same size as other inputs. Skipping!\" << endl;\n\t\t\treturn false;\n\t\t}\n\t\tfor (size_t i = 0; i < kpMask_vec.size(); ++i)\n\t\t{\n\t\t\tconst int mSi = kpMask_vec[i].size().area();\n\t\t\tconst int pSi = p2D_vec[i].size().height;\n\t\t\tif (pSi != mSi)\n\t\t\t{\n\t\t\t\tcerr << \"Input mask \" << i << \" does not have the same size as corresponding 2D features. Skipping BA!\" << endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\thaveMasks = true;\n\t}\n\tfor (size_t i = 0; i < map3D_vec.size(); ++i)\n\t{\n\t\tconst int mapSi = map3D_vec[i].size().area();\n\t\tconst int ones = cv::countNonZero(map3D_vec[i]);\n\t\tint pSi = p2D_vec[i].size().height;\n\t\tif (haveMasks){\n\t\t\tpSi = kpMask_vec[i].size().area();\n\t\t}\n\t\tif (nr_Qs != mapSi){\n\t\t\tcerr << \"3D map \" << i << \" does not have the same size as number of available 3D points. Skipping BA!\" << endl;\n\t\t\treturn false;\n\t\t}\n\t\tif (ones != pSi){\n\t\t\tcerr << \"3D map \" << i << \" does not contain the same number of non-zero values as provided 2D correspondences. Skipping BA!\" << endl;\n\t\t\treturn false;\n\t\t}\n\t\tif (map3D_vec[i].type() != CV_8SC1){\n\t\t\tcerr << \"3D map \" << i << \" must be of type char. Skipping BA!\" << endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\tvector<Mat> dist_mvec;\n\tbool haveDists = false;\n\tif (!dists.empty())\n\t{\n\t\tdists.getMatVector(dist_mvec);\n\t\tif (dist_mvec.size() != vecSi)\n\t\t{\n\t\t\tcerr << \"Input dists of type vector<Mat> must be of same size as other inputs. Skipping!\" << endl;\n\t\t\treturn false;\n\t\t}\n\t\thaveDists = true;\n\t}\n\tBAinfo info;\n\tstd::vector<double> t_norm;\n\tstd::vector<double *> t_vec;\n\tstd::vector<double *> R_vec;\n\tstd::vector<Eigen::Vector4d, Eigen::aligned_allocator<Eigen::Vector4d>> Rquat(vecSi), Rquat_old;\n\t// double R0[4] = {1.0, 0.0, 0.0, 0.0};\n\t// double t0[3] = {0.0, 0.0, 0.0}; \n\tstd::vector<double *> pts2D_vec;\n\tstd::vector<int> num2Dpts;\n\tstd::vector<char *> map3D_vec_ptr;\n\tstd::vector<Mat> t_save, K_save;\n\tMat Q_tmp;\n\tstd::vector<Mat> dist_tmp;\n\tstd::vector<double> f_rel_diff;\n\n\tint optPars = BA_MOTSTRUCT;\n\tif (optimMotionOnly)\n\t{\n\t\toptPars = BA_MOT;\n\t}\n\n\tdouble th = huber_thresh;\n\tif (th < 0)\n\t{\n\t\tth = ROBUST_THRESH;\n\t}\n\n\t//Prepare input data for the BA interface\n\tvector<Mat> pts2d_masked;\n\tif (haveMasks){\n\t\tfor (size_t i = 0; i < vecSi; ++i){\n\t\t\tMat p_ = p2D_vec[i];\n\t\t\tint n = p_.rows;\n\t\t\tMat mask = kpMask_vec[i];\n\t\t\tMat p_tmp1;\n\t\t\tfor (int j = 0; j < n; j++)\n\t\t\t{\n\t\t\t\tif (mask.at<unsigned char>(j))\n\t\t\t\t{\n\t\t\t\t\tp_tmp1.push_back(p_.row(j));\n\t\t\t\t}\n\t\t\t}\n\t\t\tpts2d_masked.emplace_back(p_tmp1.clone());\n\t\t}\n\t}else{\n\t\tpts2d_masked = p2D_vec;\n\t}\n\n\tdouble *pts3D_vec = nullptr;\n\tfor (size_t i = 0; i < vecSi; ++i)\n\t{\n\t\tEigen::Matrix3d Rei;\n\t\tEigen::Vector4d Rquati;\n\t\tcv::cv2eigen(R_mvec[i], Rei);\n\t\tMatToQuat(Rei, Rquat[i]);\n\t\t// Rquat.push_back(Rquati);\n\t\tR_vec.push_back((double *)Rquat[i].data());\n\t\tt_vec.push_back((double *)t_mvec[i].data);\n\t\tt_save.emplace_back(t_mvec[i].clone());\n\t}\n\tRquat_old = Rquat;\n\n\tQ_tmp = Q.clone();\n\tpts3D_vec = (double *)Q_tmp.data;\n\n\tfor (size_t i = 0; i < vecSi; ++i){\n\t\tnum2Dpts.push_back(pts2d_masked[i].rows);\n\t\tpts2D_vec.push_back((double *)pts2d_masked[i].data);\n\t\tmap3D_vec_ptr.push_back((char *)map3D_vec[i].data);\n\t}\n\n\tint err = 0;\n\tbool failed = false;\n\tif (!pointsInImgCoords) //BA for extrinsics and structure\n\t{\n\t\tEigen::Vector4d R1quat_old2;\n\n\t\tdouble f_mean = 0;\n\t\tfor (auto &Kx : K_vec){\n\t\t\tf_mean += (Kx.at<double>(1, 1) + Kx.at<double>(2, 2)) / 2.0;\n\t\t}\n\t\tf_mean /= static_cast<double>(vecSi);\n\t\tth /= f_mean;\n\n\t\tSBAdriver optiMotStruct(true, optPars, COST_PSEUDOHUBER, th, optPars);\n\n\t\terr = optiMotStruct.perform_sba(R_vec, t_vec, pts2D_vec, num2Dpts, pts3D_vec, Q_tmp.rows, &map3D_vec_ptr);\n\t\tif(err >= 0){\n\t\t\tinfo = optiMotStruct.getFinalSBAinfo();\n\t\t\tif (info.terminatingReason > 5){\n\t\t\t\tfailed = true;\n\t\t\t}\n\t\t}else{\n\t\t\tfailed = true;\n\t\t}\t\t\n\t}\n\telse //BA with internals\n\t{\n\t\tvector<std::array<double, 5>> intr_vec_data;\n\t\tvector<double *> intr_vec;\n\t\tfor (auto &Kx : K_vec)\n\t\t{\n\t\t\tintr_vec_data.push_back(std::array<double, 5>{{Kx.at<double>(0, 0), Kx.at<double>(0, 2), Kx.at<double>(1, 2), Kx.at<double>(1, 1) / Kx.at<double>(0, 0), Kx.at<double>(0, 1)}});\n\t\t\tK_save.emplace_back(Kx.clone());\n\t\t}\n\t\tfor (auto &iv : intr_vec_data)\n\t\t{\n\t\t\tintr_vec.push_back(iv.data());\n\t\t}\n\n\t\tint optimInternals = 2;\n\t\tif (optimFocalOnly)\n\t\t{\n\t\t\toptimInternals = 4;\n\t\t}\n\n\t\tvector<double *> dist_vec, *dist_vec_ptr = nullptr;\n\t\tif (haveDists)\n\t\t{\n\t\t\tfor (auto &distX : dist_mvec)\n\t\t\t{\n\t\t\t\tdist_tmp.emplace_back(distX.clone());\n\t\t\t\tdist_vec.push_back((double *)distX.data);\n\t\t\t}\n\t\t\tdist_vec_ptr = &dist_vec;\n\t\t\tif (fixCamMat)\n\t\t\t{\n\t\t\t\toptimInternals = 5;\n\t\t\t}\n\t\t}\n\n\t\tSBAdriver optiMotStruct(false, optPars, COST_PSEUDOHUBER, th, optPars, optimInternals, 0, 0, 0, true);\n\t\t//optiMotStruct.setVerbosityLevel(5);\n\n\t\terr = optiMotStruct.perform_sba(R_vec, t_vec, pts2D_vec, num2Dpts, pts3D_vec, Q_tmp.rows, &map3D_vec_ptr, &intr_vec, dist_vec_ptr);\n\t\tif (err >= 0)\n\t\t{\n\t\t\tinfo = optiMotStruct.getFinalSBAinfo();\n\t\t\tif (info.terminatingReason > 5)\n\t\t\t{\n\t\t\t\tfailed = true;\n\t\t\t}else{\n\t\t\t\tfor (size_t i = 0; i < vecSi; ++i)\n\t\t\t\t{\n\t\t\t\t\tstd::array<double, 5> &arr = intr_vec_data[i];\n\t\t\t\t\tMat K = K_vec[i];\n\t\t\t\t\tK.at<double>(0, 0) = arr[0];\n\t\t\t\t\tK.at<double>(0, 1) = arr[4];\n\t\t\t\t\tK.at<double>(0, 2) = arr[1];\n\t\t\t\t\tK.at<double>(1, 2) = arr[2];\n\t\t\t\t\tK.at<double>(1, 1) = arr[3] * arr[0];\n\t\t\t\t\tif(K_save[i].at<double>(0, 0) > arr[0]){\n\t\t\t\t\t\tf_rel_diff.push_back(K_save[i].at<double>(0, 0) / arr[0]);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tf_rel_diff.push_back(arr[0] / K_save[i].at<double>(0, 0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\tif (!failed){\n\t\tfor (size_t i = 0; i < vecSi; ++i)\n\t\t{\n\t\t\tMat t_new = t_mvec[i].clone();\n\t\t\tMat t_old = t_save[i].clone();\n\t\t\t//Normalize the translation vectors\n\t\t\tdouble t_norm1 = cv::norm(t_new);\n\t\t\tif (!nearZero(t_norm1) && std::abs(t_norm1 - 1.0) > 1e-4)\n\t\t\t{\n\t\t\t\tt_new /= t_norm1;\n\t\t\t}\n\t\t\tdouble t_norm2 = cv::norm(t_save[i]);\n\t\t\tif (!nearZero(t_norm2) && std::abs(t_norm2 - 1.0) > 1e-4)\n\t\t\t{\n\t\t\t\tt_old /= t_norm2;\n\t\t\t}\n\n\t\t\t//Check for the difference of extrinsics before and after BA to detect possible local minimas\n\t\t\tEigen::Vector3d t1e, t2e;\n\t\t\tt1e << t_old.at<double>(0), t_old.at<double>(1), t_old.at<double>(2);\n\t\t\tt2e << t_new.at<double>(0), t_new.at<double>(1), t_new.at<double>(2);\n\n\t\t\tdouble r_diff, t_diff;\n\t\t\tgetRTQuality(Rquat_old[i], Rquat[i], t1e, t2e, &r_diff, &t_diff);\n\t\t\tr_diff = r_diff / PI * 180.0;\n\t\t\tdouble rf_factor = 1.0, tf_factor = 1.0;\n\t\t\tif (!f_rel_diff.empty())\n\t\t\t{\n\t\t\t\ttf_factor = std::min(f_rel_diff[i], 2.0);\n\t\t\t\trf_factor = std::max(1.0, 0.9 * tf_factor);\n\t\t\t\ttf_factor = std::min(1.5 * tf_factor, 2.0);\n\t\t\t}\n\t\t\tconst double angleThresh2 = rf_factor * angleThresh;\n\t\t\tconst double t_norm_tresh2 = tf_factor * t_norm_tresh;\n\t\t\tif ((abs(r_diff) > angleThresh2) || (t_diff > t_norm_tresh2))\n\t\t\t{\n\t\t\t\tfailed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(failed){\n\t\tint i = 0;\n\t\tfor (auto &&old_t : t_save)\n\t\t{\n\t\t\tt_mvec[i++] = std::move(old_t);\n\t\t}\n\t\tif (pointsInImgCoords && haveDists)\n\t\t{\n\t\t\ti = 0;\n\t\t\tfor (auto &&distX : dist_tmp)\n\t\t\t{\n\t\t\t\tdist_mvec[i++] = std::move(distX);\n\t\t\t}\n\t\t}\n\t\tif(!K_save.empty()){\n\t\t\tfor (size_t i = 0; i < vecSi; ++i){\n\t\t\t\tK_save[i].copyTo(K_vec[i]);\n\t\t\t}\n\t\t}\n\t\treturn false; //BA failed\n\t}\n\n\t//Store the refined paramteres\n\tif (!optimMotionOnly)\n\t{\n\t\tQ_tmp.copyTo(Q);\n\t}\n\n\tEigen::Matrix3d Rei;\n\tEigen::Vector4d Rquati;\n\n\tfor (size_t i = 0; i < vecSi; ++i)\n\t{\n\t\tMat Rq_new;\n\t\tcv::eigen2cv(Rquat[i], Rq_new);\n\t\tquatToMatrix(R_mvec[i], Rq_new);\n\t}\n\n\treturn true;\n}\n\nint estimateEssentialOrPoseUSAC(const cv::Mat &p1,\n\t\t\t\t\t\t\t\tconst cv::Mat &p2,\n\t\t\t\t\t\t\t\tcv::OutputArray E,\n\t\t\t\t\t\t\t\tdouble th,\n\t\t\t\t\t\t\t\tConfigUSAC &cfg,\n\t\t\t\t\t\t\t\tbool &isDegenerate,\n\t\t\t\t\t\t\t\tcv::OutputArray inliers,\n\t\t\t\t\t\t\t\tcv::OutputArray R_degenerate,\n\t\t\t\t\t\t\t\tcv::OutputArray inliers_degenerate_R,\n\t\t\t\t\t\t\t\tcv::OutputArray R,\n\t\t\t\t\t\t\t\tcv::OutputArray t,\n\t\t\t\t\t\t\t\tbool verbose)\n{\n\t//const double degenerateDecisionThreshold = 0.85;//Used for the option UsacChkDegenType::DEGEN_USAC_INTERNAL: Threshold on the fraction of degenerate inliers compared to the E-inlier fraction\n\tUSACConfig::EssentialMatEstimatorUsed used_estimator;\n\tUSACConfig::RefineAlgorithm\trefineMethod;\n\tunsigned int nrInliers = 0;\n\tdouble prosac_beta = 0.09, sprt_delta = 0.05, sprt_epsilon = 0.15, sprt_delta_res = 0, sprt_epsilon_res = 0;\n\tstatic double sprt_delta_old = 0, sprt_delta_new = 0, sprt_epsilon_old = 0, sprt_epsilon_new = 0;\n\tconst int historylength = 20;//If this value is changed, also the array sizes of sprt_delta_history and sprt_epsilon_history have to be changed to the same value\n\tstatic double sprt_delta_history[20], sprt_epsilon_history[20];\n\tstatic int historyCnt = 0;\n\tstatic bool historyBufFull = false;\n\tstatic statVals sprt_delta_stat, sprt_epsilon_stat;\n\tstatic bool statistic_valid = false;\n\tstd::vector<unsigned int> sortedMatchIdx, *sortedMatchIdxPtr = nullptr;\n\tswitch (cfg.estimator)\n\t{\n\tcase(PoseEstimator::POSE_EIG_KNEIP):\n\t\tused_estimator = USACConfig::EssentialMatEstimatorUsed::ESTIM_EIG_KNEIP;\n\t\tbreak;\n\tcase(PoseEstimator::POSE_NISTER):\n\t\tused_estimator = USACConfig::EssentialMatEstimatorUsed::ESTIM_NISTER;\n\t\tbreak;\n\tcase(PoseEstimator::POSE_STEWENIUS):\n\t\tused_estimator = USACConfig::EssentialMatEstimatorUsed::ESTIM_STEWENIUS;\n\t\tbreak;\n\tdefault:\n\t\tcout << \"Estimator not supported!\" << endl;\n\t\treturn -1;\n\t}\n\tswitch (cfg.refinealg)\n\t{\n\tcase(RefineAlg::REF_8PT_PSEUDOHUBER):\n\t\trefineMethod = USACConfig::RefineAlgorithm::REFINE_8PT_PSEUDOHUBER;\n\t\tbreak;\n\tcase(RefineAlg::REF_EIG_KNEIP):\n\t\trefineMethod = USACConfig::RefineAlgorithm::REFINE_EIG_KNEIP;\n\t\tbreak;\n\tcase(RefineAlg::REF_EIG_KNEIP_WEIGHTS):\n\t\trefineMethod = USACConfig::RefineAlgorithm::REFINE_EIG_KNEIP_WEIGHTS;\n\t\tbreak;\n\tcase(RefineAlg::REF_WEIGHTS):\n\t\trefineMethod = USACConfig::RefineAlgorithm::REFINE_WEIGHTS;\n\t\tbreak;\n\tcase(RefineAlg::REF_STEWENIUS):\n\t\trefineMethod = USACConfig::RefineAlgorithm::REFINE_STEWENIUS;\n\t\tbreak;\n\tcase(RefineAlg::REF_STEWENIUS_WEIGHTS):\n\t\trefineMethod = USACConfig::RefineAlgorithm::REFINE_STEWENIUS_WEIGHTS;\n\t\tbreak;\n\tcase(RefineAlg::REF_NISTER):\n\t\trefineMethod = USACConfig::RefineAlgorithm::REFINE_NISTER;\n\t\tbreak;\n\tcase(RefineAlg::REF_NISTER_WEIGHTS):\n\t\trefineMethod = USACConfig::RefineAlgorithm::REFINE_NISTER_WEIGHTS;\n\t\tbreak;\n\tdefault:\n\t\tcout << \"Refinement algorithm not supported!\" << endl;\n\t\treturn -1;\n\t}\n\n\t//Estimate initial values for delta and epsilon of the SPRT test\n\tconst double statStdDivTh[2] = { 0.1, 0.2 };//Threshold for delta and epsilon on their history standard deviation\n\tconst double relativeDifferenceTh[2] = { 0.33, 0.4 };//Threshold for delta and epsilon on their relative difference of the last two values\n\tconst double relDiffArithToStd = 0.45;//Used to choose if the statistic should be used: The standard deviation must be smaller than relDiffArithToStd times the arithmetic mean value\n\tconst double ignoreRelDiffATSTh[2] = { 0.1, 0.1 };//The relative threshold using relDiffArithToStd is ignored, if the arithmetic mean is below this value for delta and epsilon\n\tif (cfg.automaticSprtInit == SprtInit::SPRT_DELTA_AUTOM_INIT)\n\t{\n\t\tif (sprt_delta_old == 0 || sprt_delta_new == 0)\n\t\t{\n\t\t\tsprt_delta = estimateSprtDeltaInit(*cfg.matches, *cfg.keypoints1, *cfg.keypoints2, cfg.th_pixels, cfg.imgSize);\n\t\t\tsprt_delta_new = sprt_delta;\n\t\t}\n\t\telse if (!statistic_valid || (statistic_valid && ((sprt_delta_stat.arithStd > statStdDivTh[0]) || ((sprt_delta_stat.arithErr > ignoreRelDiffATSTh[0]) && (sprt_delta_stat.arithStd > relDiffArithToStd * sprt_delta_stat.arithErr)))))\n\t\t{\n\t\t\tif (abs((sprt_delta_old - sprt_delta_new) / sprt_delta_old) < relativeDifferenceTh[0])\n\t\t\t{\n\t\t\t\tsprt_delta = sprt_delta_new;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsprt_delta = estimateSprtDeltaInit(*cfg.matches, *cfg.keypoints1, *cfg.keypoints2, cfg.th_pixels, cfg.imgSize);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsprt_delta = sprt_delta_stat.arithErr;\n\t\t}\n\n\t\t/*if (statistic_valid &&\n\t\t\t(sprt_epsilon_stat.arithStd <= statStdDivTh[1]) &&\n\t\t\t((sprt_epsilon_stat.arithErr <= ignoreRelDiffATSTh[1]) ||\n\t\t\t(sprt_epsilon_stat.arithStd <= relDiffArithToStd * sprt_epsilon_stat.arithErr)))\n\t\t{\n\t\t\tsprt_epsilon = sprt_epsilon_stat.arithErr;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsprt_epsilon = 0.15;\n\t\t}*/\n\t}\n\telse if (cfg.automaticSprtInit == SprtInit::SPRT_EPSILON_AUTOM_INIT)\n\t{\n\t\tif (sprt_epsilon_old == 0 || sprt_epsilon_new == 0)\n\t\t{\n\t\t\tsprt_epsilon = estimateSprtEpsilonInit(*cfg.matches, cfg.nrMatchesVfcFiltered);\n\t\t\tsprt_epsilon_new = sprt_epsilon;\n\t\t}\n\t\telse if (!statistic_valid || \n\t\t\t(statistic_valid && \n\t\t\t((sprt_epsilon_stat.arithStd > statStdDivTh[1]) || \n\t\t\t\t((sprt_epsilon_stat.arithErr > ignoreRelDiffATSTh[1]) && \n\t\t\t\t(sprt_epsilon_stat.arithStd > relDiffArithToStd * sprt_epsilon_stat.arithErr)))))\n\t\t{\n\t\t\tif (abs((sprt_epsilon_old - sprt_epsilon_new) / sprt_epsilon_old) < relativeDifferenceTh[1])\n\t\t\t{\n\t\t\t\tsprt_epsilon = sprt_epsilon_new;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsprt_epsilon = estimateSprtEpsilonInit(*cfg.matches, cfg.nrMatchesVfcFiltered);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsprt_epsilon = sprt_epsilon_stat.arithErr;\n\t\t}\n\n\t\t/*if (statistic_valid &&\n\t\t\t(sprt_delta_stat.arithStd <= statStdDivTh[0]) &&\n\t\t\t((sprt_delta_stat.arithErr <= ignoreRelDiffATSTh[0]) ||\n\t\t\t(sprt_delta_stat.arithStd <= relDiffArithToStd * sprt_delta_stat.arithErr)))\n\t\t{\n\t\t\tsprt_delta = sprt_delta_stat.arithErr;\n\t\t\tprosac_beta = sprt_delta;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsprt_delta = 0.05;\n\t\t\tprosac_beta = 0.09;\n\t\t}*/\n\t}\n\telse if (cfg.automaticSprtInit == (SprtInit::SPRT_DELTA_AUTOM_INIT | SprtInit::SPRT_EPSILON_AUTOM_INIT))\n\t{\n\t\tif (sprt_delta_old == 0 || sprt_delta_new == 0)\n\t\t{\n\t\t\tsprt_delta = estimateSprtDeltaInit(*cfg.matches, *cfg.keypoints1, *cfg.keypoints2, cfg.th_pixels, cfg.imgSize);\n\t\t\tsprt_delta_new = sprt_delta;\n\t\t}\n\t\telse if (!statistic_valid || \n\t\t\t(statistic_valid && \n\t\t\t((sprt_delta_stat.arithStd > statStdDivTh[0]) || \n\t\t\t\t((sprt_delta_stat.arithErr > ignoreRelDiffATSTh[0]) && \n\t\t\t\t(sprt_delta_stat.arithStd > relDiffArithToStd * sprt_delta_stat.arithErr)))))\n\t\t{\n\t\t\tif (abs((sprt_delta_old - sprt_delta_new) / sprt_delta_old) < relativeDifferenceTh[0])\n\t\t\t{\n\t\t\t\tsprt_delta = sprt_delta_new;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsprt_delta = estimateSprtDeltaInit(*cfg.matches, *cfg.keypoints1, *cfg.keypoints2, cfg.th_pixels, cfg.imgSize);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsprt_delta = sprt_delta_stat.arithErr;\n\t\t}\n\t\tif (sprt_epsilon_old == 0 || sprt_epsilon_new == 0)\n\t\t{\n\t\t\tsprt_epsilon = estimateSprtEpsilonInit(*cfg.matches, cfg.nrMatchesVfcFiltered);\n\t\t\tsprt_epsilon_new = sprt_epsilon;\n\t\t}\n\t\telse if (!statistic_valid || \n\t\t\t(statistic_valid && \n\t\t\t((sprt_epsilon_stat.arithStd > statStdDivTh[1]) || \n\t\t\t\t((sprt_epsilon_stat.arithErr > ignoreRelDiffATSTh[1]) && \n\t\t\t\t(sprt_epsilon_stat.arithStd > relDiffArithToStd * sprt_epsilon_stat.arithErr)))))\n\t\t{\n\t\t\tif (abs((sprt_epsilon_old - sprt_epsilon_new) / sprt_epsilon_old) < relativeDifferenceTh[1])\n\t\t\t{\n\t\t\t\tsprt_epsilon = sprt_epsilon_new;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsprt_epsilon = estimateSprtEpsilonInit(*cfg.matches, cfg.nrMatchesVfcFiltered);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsprt_epsilon = sprt_epsilon_stat.arithErr;\n\t\t}\n\t}\n\t/*else if (cfg.automaticSprtInit == SprtInit::SPRT_DEFAULT_INIT)\n\t{\n\t\tif (statistic_valid && \n\t\t\t(sprt_delta_stat.arithStd <= statStdDivTh[0]) && \n\t\t\t((sprt_delta_stat.arithErr <= ignoreRelDiffATSTh[0]) || \n\t\t\t(sprt_delta_stat.arithStd <= relDiffArithToStd * sprt_delta_stat.arithErr)))\n\t\t{\n\t\t\tsprt_delta = sprt_delta_stat.arithErr;\n\t\t\tprosac_beta = sprt_delta;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsprt_delta = 0.05;\n\t\t\tprosac_beta = 0.09;\n\t\t}\n\t\tif (statistic_valid && \n\t\t\t(sprt_epsilon_stat.arithStd <= statStdDivTh[1]) && \n\t\t\t((sprt_epsilon_stat.arithErr <= ignoreRelDiffATSTh[1]) || \n\t\t\t(sprt_epsilon_stat.arithStd <= relDiffArithToStd * sprt_epsilon_stat.arithErr)))\n\t\t{\n\t\t\tsprt_epsilon = sprt_epsilon_stat.arithErr;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsprt_epsilon = 0.15;\n\t\t}\n\t}*/\n\telse if (cfg.automaticSprtInit != SprtInit::SPRT_DEFAULT_INIT)\n\t{\n\t\tcout << \"Method for SPRT initialization not supported!\" << endl;\n\t\treturn -1;\n\t}\n\tif (!cfg.noAutomaticProsacParamters)\n\t{\n\t\tprosac_beta = sprt_delta;\n\t}\n\tif (cfg.matches)\n\t{\n\t\tgetSortedMatchIdx(*cfg.matches, sortedMatchIdx);\n\t\tsortedMatchIdxPtr = &sortedMatchIdx;\n\t}\n\n\tif (cfg.degeneracyCheck == UsacChkDegenType::DEGEN_NO_CHECK)\n\t{\n\t\tMat R_degen, inl_degen, inliers_degenerate_noMotion, R_kneip, t_kneip;\n\t\tdouble fraction_degen_inliers_R = 0, fraction_degen_inliers_noMot = 0;\n\t\tif (estimateEssentialMatUsac(p1,\n\t\t\tp2,\n\t\t\tE,\n\t\t\tsprt_delta_res,\n\t\t\tsprt_epsilon_res,\n\t\t\tth,\n\t\t\tcfg.focalLength,\n\t\t\tcfg.th_pixels,\n\t\t\tprosac_beta,\n\t\t\tsprt_delta,\n\t\t\tsprt_epsilon,\n\t\t\tfalse,\n\t\t\tused_estimator,\n\t\t\trefineMethod,\n\t\t\tinliers,\n\t\t\t&nrInliers,\n\t\t\tcv::noArray(),\n\t\t\tcv::noArray(),\n\t\t\tR_degen,\n\t\t\tinl_degen,\n\t\t\tcv::noArray(),\n\t\t\tcv::noArray(),\n\t\t\tinliers_degenerate_noMotion,\n                                     nullptr,\n\t\t\t&fraction_degen_inliers_R,\n                                     nullptr,\n\t\t\t&fraction_degen_inliers_noMot,\n\t\t\t*sortedMatchIdxPtr,\n\t\t\tR_kneip,\n\t\t\tt_kneip,\n\t\t\tverbose) == EXIT_FAILURE)\n\t\t{\n\t\t\tcout << \"USAC failed!\" << endl;\n\t\t\treturn -2;\n\t\t}\n\t\tisDegenerate = false;\n\t\tif ((used_estimator == USACConfig::ESTIM_EIG_KNEIP\n\t\t|| refineMethod == USACConfig::REFINE_EIG_KNEIP\n\t\t|| refineMethod == USACConfig::REFINE_EIG_KNEIP_WEIGHTS) &&\n\t\t\t!R_kneip.empty() && !t_kneip.empty() && R.needed() && t.needed())\n\t\t{\n\t\t\tif (R.empty())\n\t\t\t\tR.create(3, 3, CV_64F);\n\t\t\tR_kneip.copyTo(R.getMat());\n\t\t\tif (t.empty())\n\t\t\t\tt.create(3, 1, CV_64F);\n\t\t\tt_kneip.copyTo(t.getMat());\n\t\t}\n\t\telse if (R.needed() || t.needed())\n\t\t{\n\t\t\tif (R.needed() && !R.empty())\n\t\t\t\tR.clear();\n\t\t\tif (t.needed() && !t.empty())\n\t\t\t\tt.clear();\n\t\t}\n\t}\n\telse if (cfg.degeneracyCheck == UsacChkDegenType::DEGEN_USAC_INTERNAL)\n\t{\n\t\tMat R_degen, inl_degen, inliers_degenerate_noMotion, R_kneip, t_kneip;\n\t\tdouble fraction_degen_inliers_R = 0, fraction_degen_inliers_noMot = 0, fraction_inliers = 0;\n\t\tif (estimateEssentialMatUsac(p1,\n\t\t\tp2,\n\t\t\tE,\n\t\t\tsprt_delta_res,\n\t\t\tsprt_epsilon_res,\n\t\t\tth,\n\t\t\tcfg.focalLength,\n\t\t\tcfg.th_pixels,\n\t\t\tprosac_beta,\n\t\t\tsprt_delta,\n\t\t\tsprt_epsilon,\n\t\t\ttrue,\n\t\t\tused_estimator,\n\t\t\trefineMethod,\n\t\t\tinliers,\n\t\t\t&nrInliers,\n\t\t\tcv::noArray(),\n\t\t\tcv::noArray(),\n\t\t\tR_degen,\n\t\t\tinl_degen,\n\t\t\tcv::noArray(),\n\t\t\tcv::noArray(),\n\t\t\tinliers_degenerate_noMotion,\n                                     nullptr,\n\t\t\t&fraction_degen_inliers_R,\n                                     nullptr,\n\t\t\t&fraction_degen_inliers_noMot,\n\t\t\t*sortedMatchIdxPtr,\n\t\t\tR_kneip,\n\t\t\tt_kneip,\n\t\t\tverbose) == EXIT_FAILURE)\n\t\t{\n\t\t\tcout << \"USAC failed!\" << endl;\n\t\t\treturn -2;\n\t\t}\n\n\t\tif ((used_estimator == USACConfig::ESTIM_EIG_KNEIP\n\t\t|| refineMethod == USACConfig::REFINE_EIG_KNEIP\n\t\t|| refineMethod == USACConfig::REFINE_EIG_KNEIP_WEIGHTS) &&\n\t\t\t!R_kneip.empty() && !t_kneip.empty() && R.needed() && t.needed())\n\t\t{\n\t\t\tif (R.empty())\n\t\t\t\tR.create(3, 3, CV_64F);\n\t\t\tR_kneip.copyTo(R.getMat());\n\t\t\tif (t.empty())\n\t\t\t\tt.create(3, 1, CV_64F);\n\t\t\tt_kneip.copyTo(t.getMat());\n\t\t}\n\t\telse if (R.needed() || t.needed())\n\t\t{\n\t\t\tif (R.needed() && !R.empty())\n\t\t\t\tR.clear();\n\t\t\tif (t.needed() && !t.empty())\n\t\t\t\tt.clear();\n\t\t}\n\t\tfraction_inliers = (double)nrInliers / (double)p1.rows;\n\t\tif (cfg.degenDecisionTh * fraction_inliers < fraction_degen_inliers_R)\n\t\t{\n\t\t\tisDegenerate = true;\n\t\t\tif (R_degenerate.needed() && !R_degen.empty())\n\t\t\t{\n\t\t\t\tif(R_degenerate.empty())\n\t\t\t\t\tR_degenerate.create(3, 3, CV_64F);\n\t\t\t\tR_degen.copyTo(R_degenerate.getMat());\n\t\t\t}\n\t\t\tif (inliers_degenerate_R.needed() && !inl_degen.empty())\n\t\t\t{\n\t\t\t\tif (inliers_degenerate_R.empty())\n\t\t\t\t\tinliers_degenerate_R.create(1, inl_degen.cols, CV_8U);\n\t\t\t\tinl_degen.copyTo(inliers_degenerate_R.getMat());\n\t\t\t}\n\t\t}\n\t\telse if (cfg.degenDecisionTh * fraction_inliers < fraction_degen_inliers_noMot)\n\t\t{\n\t\t\tisDegenerate = true;\n\t\t\tif (R_degenerate.needed())\n\t\t\t{\n\t\t\t\tR_degen = cv::Mat::eye(3, 3, CV_64FC1);\n\t\t\t\tif (R_degenerate.empty())\n\t\t\t\t\tR_degenerate.create(3, 3, CV_64F);\n\t\t\t\tR_degen.copyTo(R_degenerate.getMat());\n\t\t\t}\n\t\t\tif (inliers_degenerate_R.needed() && !inliers_degenerate_noMotion.empty())\n\t\t\t{\n\t\t\t\tif (inliers_degenerate_R.empty())\n\t\t\t\t\tinliers_degenerate_R.create(1, inliers_degenerate_noMotion.cols, CV_8U);\n\t\t\t\tinliers_degenerate_noMotion.copyTo(inliers_degenerate_R.getMat());\n\t\t\t}\n\t\t}\n\t}\n\telse if (cfg.degeneracyCheck == UsacChkDegenType::DEGEN_QDEGSAC)\n\t{\n\t\tMat R_degen, inl_degen, R_kneip, t_kneip, E_, inliers_;\n\t\tdouble fraction_degen_inliers_R = 0;\n\t\tif (estimateEssentialQDEGSAC(p1,\n\t\t\tp2,\n\t\t\tE_,\n\t\t\tsprt_delta_res,\n\t\t\tsprt_epsilon_res,\n\t\t\tth,\n\t\t\tcfg.focalLength,\n\t\t\tcfg.th_pixels,\n\t\t\tprosac_beta,\n\t\t\tsprt_delta,\n\t\t\tsprt_epsilon,\n\t\t\t0.5,//Inlier ratio threshold for detecting degeneracy (should be between 0.5 and 0.8)\n\t\t\tused_estimator,\n\t\t\trefineMethod,\n\t\t\tinliers_,\n\t\t\t&nrInliers,\n\t\t\tR_degen,\n\t\t\tinl_degen,\n\t\t\t&fraction_degen_inliers_R,\n\t\t\t*sortedMatchIdxPtr,\n\t\t\tR_kneip,\n\t\t\tt_kneip,\n\t\t\tverbose) == EXIT_FAILURE)\n\t\t{\n\t\t\tcout << \"USAC failed!\" << endl;\n\t\t\treturn -2;\n\t\t}\n\t\tif ((used_estimator == USACConfig::ESTIM_EIG_KNEIP\n\t\t|| refineMethod == USACConfig::REFINE_EIG_KNEIP\n\t\t|| refineMethod == USACConfig::REFINE_EIG_KNEIP_WEIGHTS) &&\n\t\t\t!R_kneip.empty() && !t_kneip.empty() && R.needed() && t.needed())\n\t\t{\n\t\t\tif (R.empty())\n\t\t\t\tR.create(3, 3, CV_64F);\n\t\t\tR_kneip.copyTo(R.getMat());\n\t\t\tif (t.empty())\n\t\t\t\tt.create(3, 1, CV_64F);\n\t\t\tt_kneip.copyTo(t.getMat());\n\t\t}\n\t\telse if (R.needed() || t.needed())\n\t\t{\n\t\t\tif (R.needed() && !R.empty())\n\t\t\t\tR.clear();\n\t\t\tif (t.needed() && !t.empty())\n\t\t\t\tt.clear();\n\t\t}\n\t\tif (E_.empty() || inliers_.empty())\n\t\t{\n\t\t\tisDegenerate = true;\n\t\t\tif (R_degenerate.needed() && !R_degen.empty())\n\t\t\t{\n\t\t\t\tif (R_degenerate.empty())\n\t\t\t\t\tR_degenerate.create(3, 3, CV_64F);\n\t\t\t\tR_degen.copyTo(R_degenerate.getMat());\n\t\t\t}\n\t\t\tif (inliers_degenerate_R.needed() && !inl_degen.empty())\n\t\t\t{\n\t\t\t\tif (inliers_degenerate_R.empty())\n\t\t\t\t\tinliers_degenerate_R.create(1, inl_degen.cols, CV_8U);\n\t\t\t\tinl_degen.copyTo(inliers_degenerate_R.getMat());\n\t\t\t}\n\t\t\tif (!E.empty())\n\t\t\t\tE.clear();\n\t\t\tif (inliers.needed() && !inliers.empty())\n\t\t\t\tinliers.clear();\n\t\t\tif (R.needed() && !R.empty())\n\t\t\t\tR.clear();\n\t\t\tif (t.needed() && !t.empty())\n\t\t\t\tt.clear();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tisDegenerate = false;\n\t\t\tif (E.empty())\n\t\t\t\tE.create(3, 3, CV_64F);\n\t\t\tE_.copyTo(E.getMat());\n\t\t\tif (inliers.needed())\n\t\t\t{\n\t\t\t\tif (inliers.empty())\n\t\t\t\t\tinliers.create(1, inliers_.cols, CV_8U);\n\t\t\t\tinliers_.copyTo(inliers.getMat());\n\t\t\t}\n\t\t\tif (inliers_degenerate_R.needed() && !inliers_degenerate_R.empty())\n\t\t\t\tinliers_degenerate_R.clear();\n\t\t\tif (R_degenerate.needed() && !R_degenerate.empty())\n\t\t\t\tR_degenerate.clear();\n\t\t}\n\t}\n\telse\n\t{\n\t\tcout << \"Mothod for checking degeneracy not available!\" << endl;\n\t\treturn -1;\n\t}\n\tsprt_delta_old = sprt_delta_new;\n\tsprt_delta_new = sprt_delta_res;\n\tsprt_epsilon_old = sprt_epsilon_new;\n\tsprt_epsilon_new = sprt_epsilon_res;\n\n\t//History\n\tif (!nearZero(sprt_delta_res) && !nearZero(sprt_epsilon_res))\n\t{\n\t\tsprt_delta_history[historyCnt] = sprt_delta_res;\n\t\tsprt_epsilon_history[historyCnt] = sprt_epsilon_res;\n\t\thistoryCnt = (historyCnt + 1) % historylength;\n\t\tif (historyCnt == 0) historyBufFull = true;\n\n\t\tif (historyBufFull)\n\t\t{\n\t\t\tgetStatsfromVec(std::vector<double>(sprt_delta_history, sprt_delta_history + historylength), &sprt_delta_stat, true);\n\t\t\tgetStatsfromVec(std::vector<double>(sprt_epsilon_history, sprt_epsilon_history + historylength), &sprt_epsilon_stat, true);\n\t\t}\n\t\telse if (historyCnt > 5)\n\t\t{\n\t\t\tgetStatsfromVec(std::vector<double>(sprt_delta_history, sprt_delta_history + historyCnt), &sprt_delta_stat, true);\n\t\t\tgetStatsfromVec(std::vector<double>(sprt_epsilon_history, sprt_epsilon_history + historyCnt), &sprt_epsilon_stat, true);\n\t\t\tstatistic_valid = true;\n\t\t}\n\t}\n\n\treturn 0;\n}\n}\n", "meta": {"hexsha": "2c22197f4d6d70f507e02f2beaea461d51af7ccb", "size": 71316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matchinglib_poselib/source/poselib/source/pose_estim.cpp", "max_stars_repo_name": "josefmaierfl/matchinglib_poselib", "max_stars_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-30T14:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T14:58:18.000Z", "max_issues_repo_path": "matchinglib_poselib/source/poselib/source/pose_estim.cpp", "max_issues_repo_name": "josefmaierfl/matchinglib_poselib", "max_issues_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-19T16:11:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-19T16:11:15.000Z", "max_forks_repo_path": "matchinglib_poselib/source/poselib/source/pose_estim.cpp", "max_forks_repo_name": "josefmaierfl/matchinglib_poselib", "max_forks_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T13:20:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T10:56:02.000Z", "avg_line_length": 31.5139195758, "max_line_length": 232, "alphanum_fraction": 0.6503309215, "num_tokens": 23045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.1928126442180458}}
{"text": "#ifndef VEXCL_FFT_KERNELS_HPP\n#define VEXCL_FFT_KERNELS_HPP\n\n/*\nThe MIT License\n\nCopyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com>\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/**\n * \\file   vexcl/fft/kernels.hpp\n * \\author Pascal Germroth <pascal@ensieve.org>\n * \\brief  Kernel generator for FFT.\n */\n\n#include <boost/math/constants/constants.hpp>\n\n#ifndef VEX_FAST_MATH_OPTS\n#  if defined(VEXCL_BACKEND_OPENCL) || defined(VEXCL_BACKEND_COMPUTE)\n#    define VEX_FAST_MATH_OPTS \"-cl-mad-enable -cl-fast-relaxed-math\"\n#  elif defined(VEXCL_BACKEND_CUDA)\n#    define VEX_FAST_MATH_OPTS \"--use_fast_math\"\n#  elif defined(VEXCL_BACKEND_JIT)\n#    define VEX_FAST_MATH_OPTS \"-ffast-math\"\n#  endif\n#endif\n\nnamespace vex {\nnamespace fft {\n\nstruct pow {\n    size_t base, exponent, value;\n    pow(size_t b, size_t e) : base(b), exponent(e),\n        value(static_cast<size_t>(std::pow(static_cast<double>(b), static_cast<double>(e)))) {}\n};\n\ninline std::ostream &operator<<(std::ostream &o, const pow &p) {\n    o << p.base;\n    if(p.exponent != 1) o << '^' << p.exponent;\n    return o;\n}\n\nstruct kernel_call {\n    bool once;\n    size_t count;\n    std::string desc;\n    backend::kernel kernel;\n    kernel_call(bool o, std::string d, backend::kernel k)\n        : once(o), count(0), desc(d), kernel(k)\n    {}\n};\n\n\n\n// generates \"(prefix vfrom,vfrom+1,...,vto)\"\ninline void param_list(backend::source_generator &o,\n        std::string prefix, size_t from, size_t to, size_t step = 1)\n{\n    o << '(';\n    for(size_t i = from ; i != to ; i += step) {\n        if(i != from) o << \", \";\n        o << prefix << 'v' << i;\n    } o << ')';\n}\n\ntemplate <class T, class T2>\ninline void kernel_radix(backend::source_generator &o, pow radix, bool invert) {\n    o << in_place_dft(radix.value, invert);\n\n    // kernel.\n    o.begin_kernel(\"radix\");\n    o.begin_kernel_parameters();\n    o.template parameter< global_ptr<const T2> >(\"x\");\n    o.template parameter< global_ptr<      T2> >(\"y\");\n    o.template parameter< cl_uint              >(\"p\");\n    o.template parameter< cl_uint              >(\"threads\");\n    o.end_kernel_parameters();\n\n    o.new_line() << \"const size_t i = \" << o.global_id(0) << \";\";\n    o.new_line() << \"if(i >= threads) return;\";\n\n    // index in input sequence, in 0..P-1\n    o.new_line() << \"const size_t k = i % p;\";\n    o.new_line() << \"const size_t batch_offset = \" << o.global_id(1) << \" * threads * \" << radix.value << \";\";\n\n    // read\n    o.new_line() << \"x += i + batch_offset;\";\n    for(size_t i = 0; i < radix.value; ++i)\n        o.new_line() << type_name<T2>() << \" v\" << i << \" = x[\" << i << \" * threads];\";\n\n    // twiddle\n    o.new_line() << \"if(p != 1)\";\n    o.open(\"{\");\n    for(size_t i = 1; i < radix.value; ++i) {\n        const T alpha = -boost::math::constants::two_pi<T>() * i / radix.value;\n        o.new_line() << \"v\" << i << \" = mul(v\" << i << \", twiddle(\"\n          << \"(\" << type_name<T>() << \")\" << std::setprecision(16) << alpha << \" * k / p));\";\n    }\n    o.close(\"}\");\n\n    // inplace DFT\n    o.new_line() << \"dft\" << radix.value;\n    param_list(o, \"&\", 0, radix.value);\n    o << \";\";\n\n    // write back\n    o.new_line() << \"const size_t j = k + (i - k) * \" << radix.value << \";\";\n    o.new_line() << \"y += j + batch_offset;\";\n    for(size_t i = 0; i < radix.value; i++)\n        o.new_line() << \"y[\" << i << \" * p] = v\" << i << \";\";\n    o.end_kernel();\n}\n\n\ntemplate <class T>\ninline std::string fft_kernel_header() {\n    std::ostringstream src;\n    src\n#ifndef VEXCL_BACKEND_CUDA\n      << \"#define DEVICE\\n\"\n#else\n      << \"#define DEVICE __device__\\n\"\n#endif\n      << \"typedef \" << type_name<T>() << \" real_t;\\n\"\n      << \"typedef \" << type_name<T>() << \"2 real2_t;\\n\";\n\n    return src.str();\n}\n\n// Return A*B (complex multiplication)\ntemplate <class T2>\ninline void mul_code(backend::source_generator &o, bool invert) {\n    o.begin_function<T2>(\"mul\");\n    o.begin_function_parameters();\n    o.template parameter<T2>(\"a\");\n    o.template parameter<T2>(\"b\");\n    o.end_function_parameters();\n\n    if(invert) { // conjugate b\n        o.new_line() << type_name<T2>() << \" r = {\"\n            \"a.x * b.x + a.y * b.y, \"\n            \"a.y * b.x - a.x * b.y};\";\n    } else {\n        o.new_line() << type_name<T2>() << \" r = {\"\n            \"a.x * b.x - a.y * b.y, \"\n            \"a.y * b.x + a.x * b.y};\";\n    }\n\n    o.new_line() << \"return r;\";\n    o.end_function();\n}\n\n// A * exp(alpha * I) == A  * (cos(alpha) + I * sin(alpha))\n// native_cos(), native_sin() is a *lot* faster than sincos, on nVidia.\ntemplate <class T, class T2>\ninline void twiddle_code(backend::source_generator &o) {\n    o.begin_function<T2>(\"twiddle\");\n    o.begin_function_parameters();\n    o.template parameter<T>(\"alpha\");\n    o.end_function_parameters();\n\n    if(std::is_same<T, cl_double>::value) {\n        // use sincos with double since we probably want higher precision\n#if defined(VEXCL_BACKEND_OPENCL) || defined(VEXCL_BACKEND_COMPUTE)\n        o.new_line() << type_name<T>() << \" cs, sn = sincos(alpha, &cs);\";\n#else\n        o.new_line() << type_name<T>() << \" sn, cs;\";\n        o.new_line() << \"sincos(alpha, &sn, &cs);\";\n#endif\n        o.new_line() << type_name<T2>() << \" r = {cs, sn};\";\n    } else {\n        // use native with float since we probably want higher performance\n#if defined(VEXCL_BACKEND_OPENCL) || defined(VEXCL_BACKEND_COMPUTE)\n        o.new_line() << type_name<T2>() << \" r = {\"\n            \"native_cos(alpha), native_sin(alpha)};\";\n#elif defined(VEXCL_BACKEND_CUDA)\n        o.new_line() << type_name<T>() << \" sn, cs;\";\n        o.new_line() << \"__sincosf(alpha, &sn, &cs);\";\n        o.new_line() << type_name<T2>() << \" r = {cs, sn};\";\n#elif defined(VEXCL_BACKEND_JIT)\n        o.new_line() << type_name<T>() << \" sn, cs;\";\n        o.new_line() << \"sincosf(alpha, &sn, &cs);\";\n        o.new_line() << type_name<T2>() << \" r = {cs, sn};\";\n#else\n#  error Unsupported backend!\n#endif\n    }\n\n    o.new_line() << \"return r;\";\n    o.end_function();\n}\n\n\ntemplate <class T, class T2>\ninline kernel_call radix_kernel(\n        bool once, const backend::command_queue &queue, size_t n, size_t batch,\n        bool invert, pow radix, size_t p,\n        const backend::device_vector<T2> &in,\n        const backend::device_vector<T2> &out\n        )\n{\n    scoped_program_header header(queue, fft_kernel_header<T>());\n\n    backend::source_generator o(queue);\n    o << std::setprecision(25);\n\n    mul_code<T2>(o, invert);\n    twiddle_code<T, T2>(o);\n\n    const size_t m = n / radix.value;\n    kernel_radix<T, T2>(o, radix, invert);\n\n    backend::kernel kernel(queue, o.str(), \"radix\", 0, VEX_FAST_MATH_OPTS);\n\n    kernel.push_arg(in);\n    kernel.push_arg(out);\n    kernel.push_arg(static_cast<cl_uint>(p));\n    kernel.push_arg(static_cast<cl_uint>(m));\n\n    const size_t wg_mul = kernel.preferred_work_group_size_multiple(queue);\n    //const size_t max_cu = device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();\n    //const size_t max_wg = device.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>();\n    size_t wg = wg_mul;\n    //while(wg * max_cu < max_wg) wg += wg_mul;\n    //wg -= wg_mul;\n    const size_t threads = (m + wg - 1) / wg;\n\n    kernel.config(backend::ndrange(threads, batch), backend::ndrange(wg, 1));\n\n    std::ostringstream desc;\n    desc << \"dft{r=\" << radix << \", p=\" << p << \", n=\" << n << \", batch=\" << batch << \", threads=\" << m << \"(\" << threads << \"), wg=\" << wg << \"}\";\n\n    return kernel_call(once, desc.str(), kernel);\n}\n\n\ntemplate <class T, class T2>\ninline kernel_call transpose_kernel(\n        const backend::command_queue &queue, size_t width, size_t height,\n        const backend::device_vector<T2> &in,\n        const backend::device_vector<T2> &out\n        )\n{\n    scoped_program_header header(queue, fft_kernel_header<T>());\n\n    backend::source_generator o(queue);\n    o << std::setprecision(25);\n\n    // determine max block size to fit into local memory/workgroup\n    size_t block_size = is_cpu(queue) ? 1 : 128;\n    {\n#if defined(VEXCL_BACKEND_OPENCL) || defined(VEXCL_BACKEND_COMPUTE)\n        cl_device_id dev = backend::get_device_id(queue);\n        cl_ulong local_size;\n        size_t workgroup;\n        clGetDeviceInfo(dev, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong), &local_size, NULL);\n        clGetDeviceInfo(dev, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &workgroup, NULL);\n#else\n        const auto local_size = queue.device().max_shared_memory_per_block();\n        const auto workgroup = queue.device().max_threads_per_block();\n#endif\n        while(block_size * block_size * sizeof(T) * 2 > local_size) block_size /= 2;\n        while(block_size * block_size > workgroup) block_size /= 2;\n    }\n\n    // from NVIDIA SDK.\n    o.begin_kernel(\"transpose\");\n    o.begin_kernel_parameters();\n    o.template parameter< global_ptr<const T2> >(\"input\");\n    o.template parameter< global_ptr<      T2> >(\"output\");\n    o.template parameter< cl_uint              >(\"width\");\n    o.template parameter< cl_uint              >(\"height\");\n    o.end_kernel_parameters();\n\n    o.new_line() << \"const size_t global_x = \" << o.global_id(0) << \";\";\n    o.new_line() << \"const size_t global_y = \" << o.global_id(1) << \";\";\n    o.new_line() << \"const size_t local_x  = \" << o.local_id(0)  << \";\";\n    o.new_line() << \"const size_t local_y  = \" << o.local_id(1)  << \";\";\n    o.new_line() << \"const bool range = global_x < width && global_y < height;\";\n\n    // local memory\n    {\n        std::ostringstream s;\n        s << \"block[\" << block_size * block_size << \"]\";\n        o.smem_static_var(type_name<T2>(), s.str());\n    }\n\n    // copy from input to local memory\n    o.new_line() << \"if(range) \"\n        << \"block[local_x + local_y * \" << block_size << \"] = input[global_x + global_y * width];\";\n\n    // wait until the whole block is filled\n    o.new_line().barrier();\n\n    // transpose local block to target\n    o.new_line() << \"if(range) \"\n      << \"output[global_x * height + global_y] = block[local_x + local_y * \" << block_size << \"];\";\n\n    o.end_kernel();\n\n    backend::kernel kernel(queue, o.str(), \"transpose\");\n\n    kernel.push_arg(in);\n    kernel.push_arg(out);\n    kernel.push_arg(static_cast<cl_uint>(width));\n    kernel.push_arg(static_cast<cl_uint>(height));\n\n    // range multiple of wg size, last block maybe not completely filled.\n    size_t r_w = (width  + block_size - 1) / block_size;\n    size_t r_h = (height + block_size - 1) / block_size;\n\n    kernel.config(backend::ndrange(r_w, r_h), backend::ndrange(block_size, block_size));\n\n    std::ostringstream desc;\n    desc << \"transpose{\"\n         << \"w=\" << width << \"(\" << r_w << \"), \"\n         << \"h=\" << height << \"(\" << r_h << \"), \"\n         << \"bs=\" << block_size << \"}\";\n\n    return kernel_call(false, desc.str(), kernel);\n}\n\n\n\ntemplate <class T, class T2>\ninline kernel_call bluestein_twiddle(\n        const backend::command_queue &queue, size_t n, bool inverse,\n        const backend::device_vector<T2> &out\n        )\n{\n    scoped_program_header header(queue, fft_kernel_header<T>());\n\n    backend::source_generator o(queue);\n    o << std::setprecision(25);\n\n    twiddle_code<T, T2>(o);\n\n    o.begin_kernel(\"bluestein_twiddle\");\n    o.begin_kernel_parameters();\n    o.template parameter< size_t         >(\"n\");\n    o.template parameter< global_ptr<T2> >(\"output\");\n    o.end_kernel_parameters();\n\n    o.new_line() << \"const size_t x = \" << o.global_id(0) << \";\";\n\n    o.new_line() << \"const size_t xx = ((ulong)x * x) % (2 * n);\";\n    o.new_line() << \"if (x < n) output[x] = twiddle(\"\n        << std::setprecision(16)\n        << (inverse ? 1 : -1) * boost::math::constants::pi<T>()\n        << \" * xx / n);\";\n\n    o.end_kernel();\n\n    backend::kernel kernel(queue, o.str(), \"bluestein_twiddle\");\n    kernel.push_arg(n);\n    kernel.push_arg(out);\n\n    size_t ws = kernel.preferred_work_group_size_multiple(queue);\n    size_t gs = (n + ws - 1) / ws;\n\n    kernel.config(gs, ws);\n\n    std::ostringstream desc;\n    desc << \"bluestein_twiddle{n=\" << n << \", inverse=\" << inverse << \"}\";\n    return kernel_call(true, desc.str(), kernel);\n}\n\ntemplate <class T, class T2>\ninline kernel_call bluestein_pad_kernel(\n        const backend::command_queue &queue, size_t n, size_t m,\n        const backend::device_vector<T2> &in,\n        const backend::device_vector<T2> &out\n        )\n{\n    scoped_program_header header(queue, fft_kernel_header<T>());\n\n    backend::source_generator o(queue);\n    o << std::setprecision(25);\n\n    o.begin_function<T2>(\"conj\");\n    o.begin_function_parameters();\n    o.template parameter<T2>(\"v\");\n    o.end_function_parameters();\n    o.new_line() << type_name<T2>() << \" r = {v.x, -v.y};\";\n    o.new_line() << \"return r;\";\n    o.end_function();\n\n    o.begin_kernel(\"bluestein_pad_kernel\");\n    o.begin_kernel_parameters();\n    o.template parameter< global_ptr<const T2> >(\"input\");\n    o.template parameter< global_ptr<      T2> >(\"output\");\n    o.template parameter< cl_uint              >(\"n\");\n    o.template parameter< cl_uint              >(\"m\");\n    o.end_kernel_parameters();\n    o.new_line() << \"const uint x = \" << o.global_id(0) << \";\";\n    o.new_line() << \"if (x < m)\";\n    o.open(\"{\");\n    o.new_line() << \"if(x < n || m - x < n)\";\n    o.open(\"{\");\n    o.new_line() << \"output[x] = conj(input[min(x, m - x)]);\";\n    o.close(\"}\");\n    o.new_line() << \"else\";\n    o.open(\"{\");\n    o.new_line() << type_name<T2>() << \" r = {0,0};\";\n    o.new_line() << \"output[x] = r;\";\n    o.close(\"}\");\n    o.close(\"}\");\n    o.end_kernel();\n\n    backend::kernel kernel(queue, o.str(), \"bluestein_pad_kernel\");\n    kernel.push_arg(in);\n    kernel.push_arg(out);\n    kernel.push_arg(static_cast<cl_uint>(n));\n    kernel.push_arg(static_cast<cl_uint>(m));\n\n    size_t ws = kernel.preferred_work_group_size_multiple(queue);\n    size_t gs = (m + ws - 1) / ws;\n\n    kernel.config(gs, ws);\n\n    std::ostringstream desc;\n    desc << \"bluestein_pad_kernel{n=\" << n << \", m=\" << m << \"}\";\n    return kernel_call(true, desc.str(), kernel);\n}\n\ntemplate <class T, class T2>\ninline kernel_call bluestein_mul_in(\n        const backend::command_queue &queue, bool inverse, size_t batch,\n        size_t radix, size_t p, size_t threads, size_t stride,\n        const backend::device_vector<T2> &data,\n        const backend::device_vector<T2> &exp,\n        const backend::device_vector<T2> &out\n        )\n{\n    scoped_program_header header(queue, fft_kernel_header<T>());\n\n    backend::source_generator o(queue);\n    o << std::setprecision(25);\n\n    mul_code<T2>(o, false);\n    twiddle_code<T, T2>(o);\n\n    o.begin_kernel(\"bluestein_mul_in\");\n    o.begin_kernel_parameters();\n    o.template parameter< global_ptr<const T2> >(\"data\");\n    o.template parameter< global_ptr<const T2> >(\"exp\");\n    o.template parameter< global_ptr<      T2> >(\"output\");\n    o.template parameter< cl_uint              >(\"radix\");\n    o.template parameter< cl_uint              >(\"p\");\n    o.template parameter< cl_uint              >(\"out_stride\");\n    o.end_kernel_parameters();\n\n    o.new_line() << \"const size_t thread  = \" << o.global_id(0)   << \";\";\n    o.new_line() << \"const size_t threads = \" << o.global_size(0) << \";\";\n    o.new_line() << \"const size_t batch   = \" << o.global_id(1)   << \";\";\n    o.new_line() << \"const size_t element = \" << o.global_id(2)   << \";\";\n\n    o.new_line() << \"if(element < out_stride)\";\n    o.open(\"{\");\n\n    o.new_line() << \"const size_t in_off  = thread + batch * radix * threads + element * threads;\";\n    o.new_line() << \"const size_t out_off = thread * out_stride + batch * out_stride * threads + element;\";\n\n    o.new_line() << \"if(element < radix)\";\n    o.open(\"{\");\n\n    o.new_line() << type_name<T2>() << \" w = exp[element];\";\n\n    o.new_line() << \"if(p != 1)\";\n    o.open(\"{\");\n\n    o.new_line() << \"ulong a = (ulong)element * (thread % p);\";\n    o.new_line() << \"ulong b = (ulong)radix * p;\";\n    o.new_line() << type_name<T2>() << \" t = twiddle(\" << std::setprecision(16)\n        << (inverse ? 1 : -1) * boost::math::constants::two_pi<T>()\n        << \" * (a % (2 * b)) / b);\";\n    o.new_line() << \"w = mul(w, t);\";\n    o.close(\"}\");\n\n    o.new_line() << \"output[out_off] = mul(data[in_off], w);\";\n\n    o.close(\"}\");\n    o.new_line() << \"else\";\n    o.open(\"{\");\n\n    o.new_line() << type_name<T2>() << \" r = {0,0};\";\n    o.new_line() << \"output[out_off] = r;\";\n\n    o.close(\"}\");\n    o.close(\"}\");\n    o.end_kernel();\n\n    backend::kernel kernel(queue, o.str(), \"bluestein_mul_in\");\n    kernel.push_arg(data);\n    kernel.push_arg(exp);\n    kernel.push_arg(out);\n    kernel.push_arg(static_cast<cl_uint>(radix));\n    kernel.push_arg(static_cast<cl_uint>(p));\n    kernel.push_arg(static_cast<cl_uint>(stride));\n\n    const size_t wg = kernel.preferred_work_group_size_multiple(queue);\n    const size_t stride_pad = (stride + wg - 1) / wg;\n\n    kernel.config(\n            backend::ndrange(threads, batch, stride_pad),\n            backend::ndrange(      1,     1,         wg)\n            );\n\n    std::ostringstream desc;\n    desc << \"bluestein_mul_in{batch=\" << batch << \", radix=\" << radix << \", p=\" << p << \", threads=\" << threads << \", stride=\" << stride << \"(\" << stride_pad << \"), wg=\" << wg << \"}\";\n    return kernel_call(false, desc.str(), kernel);\n}\n\ntemplate <class T, class T2>\ninline kernel_call bluestein_mul_out(\n        const backend::command_queue &queue, size_t batch, size_t p,\n        size_t radix, size_t threads, size_t stride,\n        const backend::device_vector<T2> &data,\n        const backend::device_vector<T2> &exp,\n        const backend::device_vector<T2> &out\n        )\n{\n    scoped_program_header header(queue, fft_kernel_header<T>());\n\n    backend::source_generator o(queue);\n    o << std::setprecision(25);\n\n    mul_code<T2>(o, false);\n\n    o.begin_function<T2>(\"scale\");\n    o.begin_function_parameters();\n    o.template parameter<T2>(\"x\");\n    o.template parameter<T >(\"a\");\n    o.end_function_parameters();\n\n    o.new_line() << type_name<T2>() << \" r = {x.x * a, x.y * a};\";\n    o.new_line() << \"return r;\";\n    o.end_function();\n\n    o.begin_kernel(\"bluestein_mul_out\");\n    o.begin_kernel_parameters();\n    o.template parameter< global_ptr<const T2> >(\"data\");\n    o.template parameter< global_ptr<const T2> >(\"exp\");\n    o.template parameter< global_ptr<      T2> >(\"output\");\n    o.template parameter< T                    >(\"div\");\n    o.template parameter< cl_uint              >(\"p\");\n    o.template parameter< cl_uint              >(\"in_stride\");\n    o.template parameter< cl_uint              >(\"radix\");\n    o.end_kernel_parameters();\n\n    o.new_line() << \"const size_t i = \" << o.global_id(0) << \";\";\n    o.new_line() << \"const size_t threads = \" << o.global_size(0) << \";\";\n    o.new_line() << \"const size_t b = \" << o.global_id(1) << \";\";\n    o.new_line() << \"const size_t l = \" << o.global_id(2) << \";\";\n\n    o.new_line() << \"if(l < radix)\";\n    o.open(\"{\");\n\n    o.new_line() << \"const size_t k = i % p;\";\n    o.new_line() << \"const size_t j = k + (i - k) * radix;\";\n    o.new_line() << \"const size_t in_off = i * in_stride + b * in_stride * threads + l;\";\n    o.new_line() << \"const size_t out_off = j + b * threads * radix + l * p;\";\n\n    o.new_line() << \"output[out_off] = mul(scale(data[in_off], div), exp[l]);\";\n\n    o.close(\"}\");\n    o.end_kernel();\n\n    backend::kernel kernel(queue, o.str(), \"bluestein_mul_out\");\n    kernel.push_arg(data);\n    kernel.push_arg(exp);\n    kernel.push_arg(out);\n    kernel.push_arg(static_cast<T>(1.0 / stride));\n    kernel.push_arg(static_cast<cl_uint>(p));\n    kernel.push_arg(static_cast<cl_uint>(stride));\n    kernel.push_arg(static_cast<cl_uint>(radix));\n\n    const size_t wg = kernel.preferred_work_group_size_multiple(queue);\n    const size_t radix_pad = (radix + wg - 1) / wg;\n\n    kernel.config(\n            backend::ndrange(threads, batch, radix_pad),\n            backend::ndrange(      1,     1,        wg)\n            );\n\n    std::ostringstream desc;\n    desc << \"bluestein_mul_out{r=\" << radix << \"(\" << radix_pad << \"), wg=\" << wg << \", batch=\" << batch << \", p=\" << p << \", thr=\" << threads << \", stride=\" << stride << \"}\";\n    return kernel_call(false, desc.str(), kernel);\n}\n\ntemplate <class T, class T2>\ninline kernel_call bluestein_mul(\n        const backend::command_queue &queue, size_t n, size_t batch,\n        const backend::device_vector<T2> &data,\n        const backend::device_vector<T2> &exp,\n        const backend::device_vector<T2> &out\n        )\n{\n    scoped_program_header header(queue, fft_kernel_header<T>());\n\n    backend::source_generator o(queue);\n    o << std::setprecision(25);\n\n    mul_code<T2>(o, false);\n\n    o.begin_kernel(\"bluestein_mul\");\n    o.begin_kernel_parameters();\n    o.template parameter< global_ptr<const T2> >(\"data\");\n    o.template parameter< global_ptr<const T2> >(\"exp\");\n    o.template parameter< global_ptr<      T2> >(\"output\");\n    o.template parameter< cl_uint              >(\"stride\");\n    o.end_kernel_parameters();\n\n    o.new_line() << \"const size_t x = \" << o.global_id(0) << \";\";\n    o.new_line() << \"const size_t y = \" << o.global_id(1) << \";\";\n\n    o.new_line() << \"if(x < stride)\";\n    o.open(\"{\");\n\n    o.new_line() << \"const size_t off = x + stride * y;\";\n    o.new_line() << \"output[off] = mul(data[off], exp[x]);\";\n\n    o.close(\"}\");\n    o.end_kernel();\n\n    backend::kernel kernel(queue, o.str(), \"bluestein_mul\");\n    kernel.push_arg(data);\n    kernel.push_arg(exp);\n    kernel.push_arg(out);\n    kernel.push_arg(static_cast<cl_uint>(n));\n\n    const size_t wg = kernel.preferred_work_group_size_multiple(queue);\n    const size_t threads = (n + wg - 1) / wg;\n\n    kernel.config(backend::ndrange(threads, batch), backend::ndrange(wg, 1));\n\n    std::ostringstream desc;\n    desc << \"bluestein_mul{n=\" << n << \"(\" << threads << \"), wg=\" << wg << \", batch=\" << batch << \"}\";\n    return kernel_call(false, desc.str(), kernel);\n}\n\n} // namespace fft\n} // namespace vex\n\n\n#endif\n", "meta": {"hexsha": "18c87328b9905b6b4fd37698f623afb829ee365c", "size": 22843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/vexcl/fft/kernels.hpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/vexcl/fft/kernels.hpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/vexcl/fft/kernels.hpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 34.3503759398, "max_line_length": 183, "alphanum_fraction": 0.5978199011, "num_tokens": 6217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.19281264228454062}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017-2020.\n// Modifications copyright (c) 2017-2020, 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_PROJECTIONS_FACTORY_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_FACTORY_HPP\n\n#include <map>\n#include <string>\n\n#include <boost/shared_ptr.hpp>\n\n#include <boost/geometry/core/static_assert.hpp>\n\n#include <boost/geometry/srs/projections/dpar.hpp>\n#include <boost/geometry/srs/projections/proj4.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/proj/aea.hpp>\n#include <boost/geometry/srs/projections/proj/aeqd.hpp>\n#include <boost/geometry/srs/projections/proj/airy.hpp>\n#include <boost/geometry/srs/projections/proj/aitoff.hpp>\n#include <boost/geometry/srs/projections/proj/august.hpp>\n#include <boost/geometry/srs/projections/proj/bacon.hpp>\n#include <boost/geometry/srs/projections/proj/bipc.hpp>\n#include <boost/geometry/srs/projections/proj/boggs.hpp>\n#include <boost/geometry/srs/projections/proj/bonne.hpp>\n#include <boost/geometry/srs/projections/proj/cass.hpp>\n#include <boost/geometry/srs/projections/proj/cc.hpp>\n#include <boost/geometry/srs/projections/proj/cea.hpp>\n#include <boost/geometry/srs/projections/proj/chamb.hpp>\n#include <boost/geometry/srs/projections/proj/collg.hpp>\n#include <boost/geometry/srs/projections/proj/crast.hpp>\n#include <boost/geometry/srs/projections/proj/denoy.hpp>\n#include <boost/geometry/srs/projections/proj/eck1.hpp>\n#include <boost/geometry/srs/projections/proj/eck2.hpp>\n#include <boost/geometry/srs/projections/proj/eck3.hpp>\n#include <boost/geometry/srs/projections/proj/eck4.hpp>\n#include <boost/geometry/srs/projections/proj/eck5.hpp>\n#include <boost/geometry/srs/projections/proj/eqc.hpp>\n#include <boost/geometry/srs/projections/proj/eqdc.hpp>\n#include <boost/geometry/srs/projections/proj/etmerc.hpp>\n#include <boost/geometry/srs/projections/proj/fahey.hpp>\n#include <boost/geometry/srs/projections/proj/fouc_s.hpp>\n#include <boost/geometry/srs/projections/proj/gall.hpp>\n#include <boost/geometry/srs/projections/proj/geocent.hpp>\n#include <boost/geometry/srs/projections/proj/geos.hpp>\n#include <boost/geometry/srs/projections/proj/gins8.hpp>\n#include <boost/geometry/srs/projections/proj/gn_sinu.hpp>\n#include <boost/geometry/srs/projections/proj/gnom.hpp>\n#include <boost/geometry/srs/projections/proj/goode.hpp>\n#include <boost/geometry/srs/projections/proj/gstmerc.hpp>\n#include <boost/geometry/srs/projections/proj/hammer.hpp>\n#include <boost/geometry/srs/projections/proj/hatano.hpp>\n#include <boost/geometry/srs/projections/proj/healpix.hpp>\n#include <boost/geometry/srs/projections/proj/krovak.hpp>\n#include <boost/geometry/srs/projections/proj/igh.hpp>\n#include <boost/geometry/srs/projections/proj/imw_p.hpp>\n#include <boost/geometry/srs/projections/proj/isea.hpp>\n#include <boost/geometry/srs/projections/proj/laea.hpp>\n#include <boost/geometry/srs/projections/proj/labrd.hpp>\n#include <boost/geometry/srs/projections/proj/lagrng.hpp>\n#include <boost/geometry/srs/projections/proj/larr.hpp>\n#include <boost/geometry/srs/projections/proj/lask.hpp>\n#include <boost/geometry/srs/projections/proj/latlong.hpp>\n#include <boost/geometry/srs/projections/proj/lcc.hpp>\n#include <boost/geometry/srs/projections/proj/lcca.hpp>\n#include <boost/geometry/srs/projections/proj/loxim.hpp>\n#include <boost/geometry/srs/projections/proj/lsat.hpp>\n#include <boost/geometry/srs/projections/proj/mbtfpp.hpp>\n#include <boost/geometry/srs/projections/proj/mbtfpq.hpp>\n#include <boost/geometry/srs/projections/proj/mbt_fps.hpp>\n#include <boost/geometry/srs/projections/proj/merc.hpp>\n#include <boost/geometry/srs/projections/proj/mill.hpp>\n#include <boost/geometry/srs/projections/proj/mod_ster.hpp>\n#include <boost/geometry/srs/projections/proj/moll.hpp>\n#include <boost/geometry/srs/projections/proj/natearth.hpp>\n#include <boost/geometry/srs/projections/proj/nell.hpp>\n#include <boost/geometry/srs/projections/proj/nell_h.hpp>\n#include <boost/geometry/srs/projections/proj/nocol.hpp>\n#include <boost/geometry/srs/projections/proj/nsper.hpp>\n#include <boost/geometry/srs/projections/proj/nzmg.hpp>\n#include <boost/geometry/srs/projections/proj/ob_tran.hpp>\n#include <boost/geometry/srs/projections/proj/ocea.hpp>\n#include <boost/geometry/srs/projections/proj/oea.hpp>\n#include <boost/geometry/srs/projections/proj/omerc.hpp>\n#include <boost/geometry/srs/projections/proj/ortho.hpp>\n#include <boost/geometry/srs/projections/proj/qsc.hpp>\n#include <boost/geometry/srs/projections/proj/poly.hpp>\n#include <boost/geometry/srs/projections/proj/putp2.hpp>\n#include <boost/geometry/srs/projections/proj/putp3.hpp>\n#include <boost/geometry/srs/projections/proj/putp4p.hpp>\n#include <boost/geometry/srs/projections/proj/putp5.hpp>\n#include <boost/geometry/srs/projections/proj/putp6.hpp>\n#include <boost/geometry/srs/projections/proj/robin.hpp>\n#include <boost/geometry/srs/projections/proj/rouss.hpp>\n#include <boost/geometry/srs/projections/proj/rpoly.hpp>\n#include <boost/geometry/srs/projections/proj/sconics.hpp>\n#include <boost/geometry/srs/projections/proj/somerc.hpp>\n#include <boost/geometry/srs/projections/proj/stere.hpp>\n#include <boost/geometry/srs/projections/proj/sterea.hpp>\n#include <boost/geometry/srs/projections/proj/sts.hpp>\n#include <boost/geometry/srs/projections/proj/tcc.hpp>\n#include <boost/geometry/srs/projections/proj/tcea.hpp>\n#include <boost/geometry/srs/projections/proj/tmerc.hpp>\n#include <boost/geometry/srs/projections/proj/tpeqd.hpp>\n#include <boost/geometry/srs/projections/proj/urm5.hpp>\n#include <boost/geometry/srs/projections/proj/urmfps.hpp>\n#include <boost/geometry/srs/projections/proj/vandg.hpp>\n#include <boost/geometry/srs/projections/proj/vandg2.hpp>\n#include <boost/geometry/srs/projections/proj/vandg4.hpp>\n#include <boost/geometry/srs/projections/proj/wag2.hpp>\n#include <boost/geometry/srs/projections/proj/wag3.hpp>\n#include <boost/geometry/srs/projections/proj/wag7.hpp>\n#include <boost/geometry/srs/projections/proj/wink1.hpp>\n#include <boost/geometry/srs/projections/proj/wink2.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n\nnamespace detail\n{\n\ntemplate <typename Params>\nstruct factory_key\n{\n    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\n        \"Invalid parameters type.\",\n        Params);\n};\n\ntemplate <>\nstruct factory_key<srs::detail::proj4_parameters>\n{\n    typedef std::string type;\n    template <typename ProjParams>\n    static type const& get(ProjParams const& par)\n    {\n        return par.id.name;\n    }\n    static const char* get(const char* name, srs::dpar::value_proj id)\n    {\n        return name;\n    }\n};\n\ntemplate <typename T>\nstruct factory_key<srs::dpar::parameters<T> >\n{\n    typedef srs::dpar::value_proj type;\n    template <typename ProjParams>\n    static type const& get(ProjParams const& par)\n    {\n        return par.id.id;\n    }\n    static srs::dpar::value_proj get(const char* name, srs::dpar::value_proj id)\n    {\n        return id;\n    }\n};\n\n\ntemplate <typename Params, typename CT, typename ProjParams>\nclass factory\n{\nprivate:\n    typedef detail::factory_entry\n        <\n            Params,\n            CT,\n            ProjParams\n        > entry_base;\n\n    typedef factory_key<Params> key;\n    typedef typename key::type key_type;\n    typedef boost::shared_ptr<entry_base> entry_ptr;\n\n    typedef std::map<key_type, entry_ptr> entries_map;\n\n    entries_map m_entries;\n\npublic:\n\n    factory()\n    {\n        detail::aea_init(*this);\n        detail::aeqd_init(*this);\n        detail::airy_init(*this);\n        detail::aitoff_init(*this);\n        detail::august_init(*this);\n        detail::bacon_init(*this);\n        detail::bipc_init(*this);\n        detail::boggs_init(*this);\n        detail::bonne_init(*this);\n        detail::cass_init(*this);\n        detail::cc_init(*this);\n        detail::cea_init(*this);\n        detail::chamb_init(*this);\n        detail::collg_init(*this);\n        detail::crast_init(*this);\n        detail::denoy_init(*this);\n        detail::eck1_init(*this);\n        detail::eck2_init(*this);\n        detail::eck3_init(*this);\n        detail::eck4_init(*this);\n        detail::eck5_init(*this);\n        detail::eqc_init(*this);\n        detail::eqdc_init(*this);\n        detail::etmerc_init(*this);\n        detail::fahey_init(*this);\n        detail::fouc_s_init(*this);\n        detail::gall_init(*this);\n        detail::geocent_init(*this);\n        detail::geos_init(*this);\n        detail::gins8_init(*this);\n        detail::gn_sinu_init(*this);\n        detail::gnom_init(*this);\n        detail::goode_init(*this);\n        detail::gstmerc_init(*this);\n        detail::hammer_init(*this);\n        detail::hatano_init(*this);\n        detail::healpix_init(*this);\n        detail::krovak_init(*this);\n        detail::igh_init(*this);\n        detail::imw_p_init(*this);\n        detail::isea_init(*this);\n        detail::labrd_init(*this);\n        detail::laea_init(*this);\n        detail::lagrng_init(*this);\n        detail::larr_init(*this);\n        detail::lask_init(*this);\n        detail::latlong_init(*this);\n        detail::lcc_init(*this);\n        detail::lcca_init(*this);\n        detail::loxim_init(*this);\n        detail::lsat_init(*this);\n        detail::mbtfpp_init(*this);\n        detail::mbtfpq_init(*this);\n        detail::mbt_fps_init(*this);\n        detail::merc_init(*this);\n        detail::mill_init(*this);\n        detail::mod_ster_init(*this);\n        detail::moll_init(*this);\n        detail::natearth_init(*this);\n        detail::nell_init(*this);\n        detail::nell_h_init(*this);\n        detail::nocol_init(*this);\n        detail::nsper_init(*this);\n        detail::nzmg_init(*this);\n        detail::ob_tran_init(*this);\n        detail::ocea_init(*this);\n        detail::oea_init(*this);\n        detail::omerc_init(*this);\n        detail::ortho_init(*this);\n        detail::qsc_init(*this);\n        detail::poly_init(*this);\n        detail::putp2_init(*this);\n        detail::putp3_init(*this);\n        detail::putp4p_init(*this);\n        detail::putp5_init(*this);\n        detail::putp6_init(*this);\n        detail::robin_init(*this);\n        detail::rouss_init(*this);\n        detail::rpoly_init(*this);\n        detail::sconics_init(*this);\n        detail::somerc_init(*this);\n        detail::stere_init(*this);\n        detail::sterea_init(*this);\n        detail::sts_init(*this);\n        detail::tcc_init(*this);\n        detail::tcea_init(*this);\n        detail::tmerc_init(*this);\n        detail::tpeqd_init(*this);\n        detail::urm5_init(*this);\n        detail::urmfps_init(*this);\n        detail::vandg_init(*this);\n        detail::vandg2_init(*this);\n        detail::vandg4_init(*this);\n        detail::wag2_init(*this);\n        detail::wag3_init(*this);\n        detail::wag7_init(*this);\n        detail::wink1_init(*this);\n        detail::wink2_init(*this);\n    }\n\n    void add_to_factory(const char* name, srs::dpar::value_proj id, entry_base* entry)\n    {\n        // The pointer has to be owned before std::map::operator[] in case it thrown an exception.\n        entry_ptr ptr(entry);\n        m_entries[key::get(name, id)] = ptr;\n    }\n\n    detail::dynamic_wrapper_b<CT, ProjParams>* create_new(Params const& params, ProjParams const& proj_par) const\n    {\n        typedef typename entries_map::const_iterator const_iterator;\n        const_iterator it = m_entries.find(key::get(proj_par));\n        if (it != m_entries.end())\n        {\n            return it->second->create_new(params, proj_par);\n        }\n\n        return 0;\n    }\n};\n\ntemplate <typename T>\ninline detail::dynamic_wrapper_b<T, projections::parameters<T> >*\n    create_new(srs::detail::proj4_parameters const& params,\n               projections::parameters<T> const& parameters)\n{\n    static factory<srs::detail::proj4_parameters, T, projections::parameters<T> > const fac;\n    return fac.create_new(params, parameters);\n}\n\ntemplate <typename T>\ninline detail::dynamic_wrapper_b<T, projections::parameters<T> >*\n    create_new(srs::dpar::parameters<T> const& params,\n               projections::parameters<T> const& parameters)\n{\n    static factory<srs::dpar::parameters<T>, T, projections::parameters<T> > const fac;\n    return fac.create_new(params, parameters);\n}\n\n\n} // namespace detail\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_FACTORY_HPP\n", "meta": {"hexsha": "0fddb0a27c39233212338ad299fdfd2fd82e08f7", "size": 12740, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/factory.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/geometry/srs/projections/factory.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/geometry/srs/projections/factory.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": 37.8041543027, "max_line_length": 113, "alphanum_fraction": 0.7095761381, "num_tokens": 3337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.19281263689695083}}
{"text": "#pragma once\n\n#include \"generator/feature_builder.hpp\"\n#include \"generator/regions/region_info.hpp\"\n#include \"generator/translation.hpp\"\n\n#include \"geometry/rect2d.hpp\"\n\n#include \"coding/string_utf8_multilang.hpp\"\n\n#include \"base/geo_object_id.hpp\"\n\n#include <cstdint>\n#include <string>\n\n#include <boost/geometry.hpp>\n#include <boost/optional.hpp>\n\nnamespace generator\n{\nnamespace regions\n{\nusing Point = feature::FeatureBuilder::PointSeq::value_type;\nusing BoostPoint = boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>;\nusing BoostPolygon = boost::geometry::model::polygon<BoostPoint>;\nusing BoostRect = boost::geometry::model::box<BoostPoint>;\n\nclass RegionWithName\n{\npublic:\n  explicit RegionWithName(StringUtf8Multilang name) : m_name(std::move(name)) {}\n\n  std::string GetTranslatedOrTransliteratedName(LanguageCode languageCode) const;\n  // returns default name if int_name is empty\n  std::string GetInternationalName() const;\n  std::string GetName(int8_t lang = StringUtf8Multilang::kDefaultCode) const;\n  StringUtf8Multilang const & GetMultilangName() const;\n\nprotected:\n  StringUtf8Multilang m_name;\n};\n\nclass RegionWithData\n{\npublic:\n  explicit RegionWithData(RegionDataProxy const & regionData) : m_regionData(regionData) {}\n\n  base::GeoObjectId GetId() const;\n  boost::optional<std::string> GetIsoCode() const;\n\n  boost::optional<base::GeoObjectId> GetLabelOsmId() const;\n\n  AdminLevel GetAdminLevel() const { return m_regionData.GetAdminLevel(); }\n  PlaceType GetPlaceType() const { return m_regionData.GetPlaceType(); }\n\n  void SetAdminLevel(AdminLevel adminLevel) { m_regionData.SetAdminLevel(adminLevel); }\n  void SetPlaceType(PlaceType placeType) { m_regionData.SetPlaceType(placeType); }\n\n  RegionDataProxy const & GetRegionData() const { return m_regionData; }\n\nprotected:\n  RegionDataProxy m_regionData;\n};\n\ntemplate <typename Place>\nstd::string GetRegionNotation(Place const & place)\n{\n  auto notation = place.GetTranslatedOrTransliteratedName(StringUtf8Multilang::GetLangIndex(\"en\"));\n  if (notation.empty())\n    return place.GetName();\n\n  if (notation != place.GetName())\n    notation += \" / \" + place.GetName();\n  return notation;\n}\n}  // namespace regions\n}  // namespace generator\n", "meta": {"hexsha": "5387fbc4b75394e4d0a91071e1c22eff8e0b2f26", "size": 2231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "generator/regions/region_base.hpp", "max_stars_repo_name": "vmihaylenko/omim", "max_stars_repo_head_hexsha": "00087f340e723fc611cbc82e0ae898b9053b620a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T17:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T15:51:52.000Z", "max_issues_repo_path": "generator/regions/region_base.hpp", "max_issues_repo_name": "mapsme/geocore", "max_issues_repo_head_hexsha": "346fceb020cd909b37706ab6ad454aec1a11f52e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2019-10-04T00:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-27T15:13:19.000Z", "max_forks_repo_path": "generator/regions/region_base.hpp", "max_forks_repo_name": "vmihaylenko/omim", "max_forks_repo_head_hexsha": "00087f340e723fc611cbc82e0ae898b9053b620a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-10-02T15:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T13:06:22.000Z", "avg_line_length": 28.6025641026, "max_line_length": 99, "alphanum_fraction": 0.7664724339, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19277782022841533}}
{"text": "/******************************************************************************  \n  Copyright 2015-2017 Matthew The <matthew.the@scilifelab.se>\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 \"FeatureAlignment.h\"\n\n#include <boost/lexical_cast.hpp>\n#include <boost/assign/list_of.hpp>\n\nnamespace quandenser {\n\nconst std::vector<std::pair<std::string, double> > \nFeatureAlignment::kLinkFeatureNames =\n  boost::assign::list_of(make_pair(\"ppmDiff\", -3.0))\n    (make_pair(\"rtDiff\",-1.0))\n    (make_pair(\"precMz\", 0.0))\n    (make_pair(\"rTime\", 0.0))\n    /* (make_pair(\"xicRateDiff\", -0.5)) */\n    (make_pair(\"queryIsPlaceHolder\", 0.0))\n    (make_pair(\"targetIsPlaceHolder\", 0.0))\n    (make_pair(\"charge1\", 0.0))\n    (make_pair(\"charge2\", 0.0))\n    (make_pair(\"charge3\", 0.0))\n    (make_pair(\"charge4plus\", 0.0));\n    \nbool operator<(const FeatureFeatureMatch& l, const FeatureFeatureMatch& r) {\n  return l.score < r.score;\n}\n    \nvoid FeatureAlignment::matchFeatures(\n    const std::vector<std::pair<int, FilePair> >& featureAlignmentQueue,\n    const maracluster::SpectrumFileList& fileList,\n    AlignRetention& alignRetention,\n    std::vector<DinosaurFeatureList>& allFeatures,\n    const std::string& tmpFilePrefix) {  \n  std::vector<std::pair<int, FilePair> >::const_iterator filePairIt;\n  size_t alignmentCnt = 1u;\n  for (filePairIt = featureAlignmentQueue.begin(); \n        filePairIt != featureAlignmentQueue.end(); ++filePairIt, ++alignmentCnt) {\n    FilePair filePair = filePairIt->second;\n    if (Globals::VERB > 1) {\n      std::cerr << \"Matching features \" << filePair.fileIdx1 \n                << \"->\" << filePair.fileIdx2 \n                << \" (\" << alignmentCnt << \"/\" \n                << featureAlignmentQueue.size() << \")\" << std::endl;\n    }\n    std::string targetMzMLFile = fileList.getFilePath(filePair.fileIdx2);\n    getFeatureMap(filePair, targetMzMLFile, \n        alignRetention.getAlignment(filePair), \n        allFeatures.at(filePair.fileIdx1), \n        allFeatures.at(filePair.fileIdx2),\n        tmpFilePrefix);\n  }\n}\n\nvoid FeatureAlignment::getFeatureMap(FilePair& filePair,\n    const std::string& targetMzMLFile,\n    SplineRegression& alignment, \n    DinosaurFeatureList& featuresQueryRun, \n    DinosaurFeatureList& featuresTargetRun,\n    const std::string& tmpFilePrefix) {\n  if (!tmpFilePrefix.empty()) {\n    std::string fileName = tmpFilePrefix + \"/features.\"  + boost::lexical_cast<std::string>(filePair.fileIdx1) + \".dat\";\n    featuresQueryRun.loadFromFile(fileName);\n    \n    bool withIdxMap = true;\n    fileName = tmpFilePrefix + \"/features.\"  + boost::lexical_cast<std::string>(filePair.fileIdx2) + \".dat\";\n    featuresTargetRun.loadFromFile(fileName, withIdxMap);\n  }\n  \n  std::vector<double> rTimesQueryRun, predictedRTimesTargetRun;\n  DinosaurFeatureList::const_iterator ftIt;\n  for (ftIt = featuresQueryRun.begin(); ftIt != featuresQueryRun.end(); ++ftIt) {\n    rTimesQueryRun.push_back(ftIt->rTime);\n  }\n  alignment.predict(rTimesQueryRun, predictedRTimesTargetRun);\n  float rTimeStdev = alignment.getRmse();\n  DinosaurFeatureList candidateFeaturesTargetRun;\n  \n  std::string percolatorOutputFile = percolatorOutputFileBaseFN_ + \"/link_\" + \n    boost::lexical_cast<std::string>(filePair.fileIdx1) + \"_to_\" + \n    boost::lexical_cast<std::string>(filePair.fileIdx2) + \".psms\";\n  if (Globals::fileIsEmpty(percolatorOutputFile)) {\n    matchFeatures(percolatorOutputFile, featuresQueryRun, featuresTargetRun, \n                 predictedRTimesTargetRun, rTimeStdev);\n  }\n  addFeatureLinks(percolatorOutputFile, candidateFeaturesTargetRun, \n                  featuresTargetRun, featureMatches_[filePair]);\n  \n  if (linkPEPMbrSearchThreshold_ < 1.0) {\n    std::string percolatorMbrOutputFile = percolatorOutputFileBaseFN_ + \n      \"/search_and_link_\" + \n      boost::lexical_cast<std::string>(filePair.fileIdx1) + \"_to_\" + \n      boost::lexical_cast<std::string>(filePair.fileIdx2) + \".psms.pout\";\n    mbrMatchFeatures(featureMatches_[filePair], \n        percolatorMbrOutputFile, targetMzMLFile, \n        featuresQueryRun, featuresTargetRun, predictedRTimesTargetRun, \n        rTimeStdev, candidateFeaturesTargetRun);\n    \n    addFeatureLinks(percolatorMbrOutputFile, candidateFeaturesTargetRun, \n        featuresTargetRun, featureMatches_[filePair]);\n  }\n  \n  insertPlaceholderFeatures(featuresQueryRun, predictedRTimesTargetRun, \n      featuresTargetRun, featureMatches_[filePair]);\n  \n  featuresTargetRun.sortByPrecMz();\n  \n  if (!tmpFilePrefix.empty()) {\n    std::string fileName = tmpFilePrefix + \"/features.\"  + boost::lexical_cast<std::string>(filePair.fileIdx2) + \".dat\";\n    bool append = false;\n    featuresTargetRun.saveToFile(fileName, append);\n    \n    featuresQueryRun.clear();\n    featuresTargetRun.clear();\n    \n    std::string matchesFileName = tmpFilePrefix + \"/matches.\"  + \n        boost::lexical_cast<std::string>(filePair.fileIdx1) + \".\" + \n        boost::lexical_cast<std::string>(filePair.fileIdx2) + \".dat\";\n    saveToFile(matchesFileName, featureMatches_[filePair], append);\n    featureMatches_[filePair].clear();\n  }\n}\n\nvoid FeatureAlignment::insertPlaceholderFeatures(\n    const DinosaurFeatureList& featuresQueryRun, \n    const std::vector<double>& predictedRTimesTargetRun,\n    DinosaurFeatureList& featuresTargetRun,\n    std::map<int, FeatureIdxMatch>& precursorLinks) {\n  DinosaurFeatureList::const_iterator queryIt;\n  std::vector<double>::const_iterator predRTimeIt;\n  int targetFileIdx = featuresTargetRun.begin()->fileIdx;\n  size_t placeholdersAdded = 0u;\n  for (queryIt = featuresQueryRun.begin(), predRTimeIt = predictedRTimesTargetRun.begin(); \n       queryIt != featuresQueryRun.end(); ++queryIt, ++predRTimeIt) {\n    if (precursorLinks[queryIt->featureIdx].posteriorErrorProb > linkPEPThreshold_) {\n      DinosaurFeature placeholderFt = *queryIt;\n      placeholderFt.fileIdx = targetFileIdx;\n      placeholderFt.featureIdx = featuresTargetRun.size();\n      placeholderFt.intensity = 0.0;\n      placeholderFt.rTime = *predRTimeIt;\n      featuresTargetRun.push_back(placeholderFt);\n      precursorLinks[queryIt->featureIdx] = \n          FeatureIdxMatch(placeholderFt.featureIdx, 1.0, placeholderFt.intensity);\n      ++placeholdersAdded;\n    }\n  }\n  \n  if (Globals::VERB > 1) {\n    std::cerr << \"Added \" << placeholdersAdded << \" placeholders.\" << std::endl;\n  }\n} \n\nvoid FeatureAlignment::matchFeatures(\n    const std::string& percolatorOutputFile,\n    const DinosaurFeatureList& featuresQueryRun, \n    const DinosaurFeatureList& featuresTargetRun, \n    const std::vector<double>& predictedRTimesTargetRun, \n    float rTimeStdev) {  \n  float rTimeTol = rTimeStdevTol_ * rTimeStdev;\n  \n  std::vector<std::string> percolatorArgs = percolatorArgs_;\n  \n  percolatorArgs.push_back(\"--results-psms\");\n  percolatorArgs.push_back(percolatorOutputFile);\n  percolatorArgs.push_back(\"--decoy-results-psms\");\n  percolatorArgs.push_back(percolatorOutputFile + \".decoys\");\n  /*\n  percolatorArgs.push_back(\"--tab-out\");\n  percolatorArgs.push_back(percolatorOutputFile + \".pin\");\n  */\n  \n  PercolatorAdapter percolatorAdapter;\n  percolatorAdapter.parseOptions(percolatorArgs);\n  percolatorAdapter.init(kLinkFeatureNames);\n  \n  DinosaurFeatureList::const_iterator queryIt, targetIt;\n  std::vector<double>::const_iterator predRTimeIt;\n  for (queryIt = featuresQueryRun.begin(), predRTimeIt = predictedRTimesTargetRun.begin(); \n       queryIt != featuresQueryRun.end(); ++queryIt, ++predRTimeIt) {\n    std::vector<FeatureFeatureMatch> topTargets;\n    \n    DinosaurFeature queryFeature = *queryIt;\n    queryFeature.rTime = *predRTimeIt;\n    int label = 1;\n    findMatches(label, rTimeTol, featuresTargetRun, queryFeature, topTargets);\n    \n    queryFeature.precMz += decoyOffset_;\n    label = -1;\n    findMatches(label, rTimeTol, featuresTargetRun, queryFeature, topTargets);\n    \n    std::sort(topTargets.begin(), topTargets.end());\n    \n    \n    int numAdded = 0;\n    std::vector<FeatureFeatureMatch>::const_iterator ffmIt;\n    for (ffmIt = topTargets.begin(); \n          ffmIt != topTargets.end() && numAdded < maxFeatureCandidates_; \n          ++ffmIt, ++numAdded) {\n      addLinkPsm(ffmIt->label, ffmIt->queryFeature, ffmIt->targetFeature, \n                 percolatorAdapter);\n    }\n  }\n  \n  percolatorAdapter.process();\n}\n\n\nvoid FeatureAlignment::addFeatureLinks(const std::string& percolatorOutputFile,\n    DinosaurFeatureList& candidateFeaturesTargetRun,\n    DinosaurFeatureList& featuresTargetRun,\n    std::map<int, FeatureIdxMatch>& precursorLinks) {\n  std::ifstream dataStream(percolatorOutputFile.c_str(), ios::in);\n  \n  std::cerr << \"Links before \"<< precursorLinks.size() << std::endl;\n  \n  int targetFileIdx = featuresTargetRun.begin()->fileIdx;\n  std::string psmLine;\n  getline(dataStream, psmLine); /* skip header */\n  while (getline(dataStream, psmLine)) {\n    TabReader reader(psmLine);\n  \n    std::string querySpecId = reader.readString();\n    DinosaurFeature queryFt = parsePsmIdAsFeature(querySpecId);\n    \n    reader.readDouble(); /* score */\n    double qval = reader.readDouble();\n    double posteriorErrorProb = reader.readDouble();\n    \n    if (posteriorErrorProb > linkPEPThreshold_) break;\n    \n    if (posteriorErrorProb < precursorLinks[queryFt.featureIdx].posteriorErrorProb) {\n      std::string peptide = reader.readString();\n      std::string targetSpecId = peptide.substr(2, peptide.size() - 4);\n      DinosaurFeature targetFt = parsePsmIdAsFeature(targetSpecId);\n      if (targetFt.featureIdx < 0) {\n        DinosaurFeature& candFt = candidateFeaturesTargetRun.at(\n            getCandidatePos(targetFt.featureIdx));\n        if (candFt.featureIdx < 0) {\n          candFt.featureIdx = featuresTargetRun.size();\n          candFt.fileIdx = targetFileIdx;\n          featuresTargetRun.push_back(candFt);\n        }\n        targetFt = candFt;\n      }\n      precursorLinks[queryFt.featureIdx] = FeatureIdxMatch(targetFt.featureIdx, \n          posteriorErrorProb, targetFt.intensity);\n    }\n  }\n  \n  std::cerr << \"Links after \"<< precursorLinks.size() << std::endl;\n}\n\nvoid FeatureAlignment::findMatches(int label, double rTimeTol,\n    const DinosaurFeatureList& featuresTargetRun, \n    const DinosaurFeature& queryFeature, \n    std::vector<FeatureFeatureMatch>& topTargets) {\n  DinosaurFeatureList::const_iterator lowerBound = \n      featuresTargetRun.getPrecMzIterator(queryFeature.precMz*(1 - ppmTol_*1e-6));\n  DinosaurFeatureList::const_iterator upperBound = \n      featuresTargetRun.getPrecMzIterator(queryFeature.precMz*(1 + ppmTol_*1e-6));\n  DinosaurFeatureList::const_iterator targetIt;\n  for (targetIt = lowerBound; targetIt != upperBound; ++targetIt) {\n    float rTimeDiff = std::abs(targetIt->rTime - queryFeature.rTime);\n    if (targetIt->charge == queryFeature.charge && rTimeDiff <= rTimeTol) {\n      DinosaurFeature targetFeature = *targetIt;\n      float ppmDiff = getPpmDiff(targetIt->precMz, queryFeature.precMz);\n      float score = rTimeDiff / rTimeTol + ppmDiff / ppmTol_; /* score <= 1.0 */\n      /* put placeholder features in the back of the queue */\n      if (targetIt->intensity == 0.0) score += 1.0; \n      \n      topTargets.push_back(FeatureFeatureMatch(score, queryFeature, targetFeature, label));\n    }\n  }\n}\n    \nvoid FeatureAlignment::addLinkPsm(int label,\n    const DinosaurFeature& queryFeature, \n    const DinosaurFeature& targetFeature, \n    PercolatorAdapter& percolatorAdapter) {\n  int scannr = queryFeature.featureIdx;\n  std::string querySpecId = convertFeatureToPsmId(queryFeature);\n  std::string targetSpecId = convertFeatureToPsmId(targetFeature);\n  std::string peptide = \"A.\" + targetSpecId + \".A\";\n  \n  double ppmDiff = getPpmDiff(targetFeature.precMz, queryFeature.precMz);\n  double rTimeDiff = std::abs(queryFeature.rTime - targetFeature.rTime);\n  /* double xicRateDiff = getXicRateDiff(targetFeature, queryFeature); */\n  int queryIsPlaceHolder = (queryFeature.intensity == 0.0) ? 1 : 0;\n  int targetIsPlaceHolder = (targetFeature.intensity == 0.0) ? 1 : 0;\n  \n  std::vector<double> features;\n  features.push_back(ppmDiff);\n  features.push_back(rTimeDiff);\n  features.push_back(targetFeature.precMz);\n  features.push_back(targetFeature.rTime);\n  /* features.push_back(xicRateDiff); */\n  features.push_back(queryIsPlaceHolder);\n  features.push_back(targetIsPlaceHolder);\n  for (int charge = 1; charge <= 4; ++charge) {\n    int isCharge = (queryFeature.charge == charge || \n                    (queryFeature.charge > 4 && charge == 4)) ? 1 : 0;\n    features.push_back(isCharge);\n  }\n  \n  percolatorAdapter.addPsm(querySpecId, label, scannr, peptide, features);\n}\n\ndouble FeatureAlignment::getXicRateDiff(const DinosaurFeature& queryFt, \n    const DinosaurFeature& targetFt) {\n  double queryIntensity = (queryFt.intensity == 0.0) ? targetFt.intensity : queryFt.intensity;\n  double targetIntensity = (targetFt.intensity == 0.0) ? queryFt.intensity : targetFt.intensity;\n  if (queryIntensity * targetIntensity == 0.0) {\n    queryIntensity = targetIntensity = 1e6;\n  }\n  double targetXicRate = getXicRate(targetIntensity, targetFt.rtStart, targetFt.rtEnd);\n  double queryXicRate = getXicRate(queryIntensity, queryFt.rtStart, queryFt.rtEnd);\n  return std::abs(queryXicRate - targetXicRate);\n}\n\ndouble FeatureAlignment::getXicRate(const double intensity, \n    const double rtStart, const double rtEnd) {\n  return log(intensity) / ((rtEnd - rtStart)*60.0);\n}\n\nvoid FeatureAlignment::mbrMatchFeatures(\n    const std::map<int, FeatureIdxMatch>& precursorLinks,\n    const std::string& percolatorOutputFile,\n    const std::string& targetMzMLFile,\n    const DinosaurFeatureList& featuresQueryRun, \n    const DinosaurFeatureList& featuresTargetRun, \n    const std::vector<double>& predictedRTimesTargetRun, \n    float rTimeStdev,\n    DinosaurFeatureList& candidateFeaturesTargetRun) {\n  float rTimeTol = rTimeStdevTol_ * rTimeStdev;\n  \n  /* TODO: put these in a separate folder */\n  std::string targetFile = percolatorOutputFile + \".dinosaur_targets.tsv\";\n  if (Globals::fileIsEmpty(targetFile)) {\n    std::ofstream targetFileStream(targetFile.c_str(), ios::out);\n    targetFileStream << \"mz\\tcharge\\tmzDiff\\trtStart\\trtEnd\\tminApexInt\\tid\" << std::endl;\n    \n    DinosaurFeatureList::const_iterator queryIt;\n    std::vector<double>::const_iterator predRTimeIt;\n    int targetFileIdx = featuresTargetRun.begin()->fileIdx;\n    size_t placeholdersAdded = 0u;\n    for (queryIt = featuresQueryRun.begin(), predRTimeIt = predictedRTimesTargetRun.begin(); \n         queryIt != featuresQueryRun.end(); ++queryIt, ++predRTimeIt) {\n      if (precursorLinks.find(queryIt->featureIdx) == precursorLinks.end() || \n          precursorLinks.find(queryIt->featureIdx)->second.posteriorErrorProb >= linkPEPMbrSearchThreshold_) {\n        std::ostringstream commonStream;\n        commonStream << queryIt->charge << \"\\t\" <<\n                        queryIt->precMz * ppmTol_ * 1e-6 << \"\\t\" <<\n                        *predRTimeIt - rTimeTol << \"\\t\" <<\n                        *predRTimeIt + rTimeTol << \"\\t\" <<\n                        10000 << \"\\t\" <<\n                        queryIt->featureIdx << std::endl;\n        \n        targetFileStream << queryIt->precMz << \"\\t\" << commonStream.str() << \n            queryIt->precMz + decoyOffset_ << \"\\t\" << commonStream.str();\n      }\n    }\n    targetFileStream.close();\n  }\n  \n  boost::filesystem::path targetMzMLFilePath(targetMzMLFile);\n  std::string outputDir = percolatorOutputFile + \"_dinosaur\"; /* TODO: put these in a separate folder */\n  std::string dinosaurOutputFile = outputDir + \"/\" + \n      targetMzMLFilePath.stem().string() + \".targets.csv\";\n  if (Globals::fileIsEmpty(dinosaurOutputFile)) {\n    boost::filesystem::path dinosaurOutputDir(outputDir);\n    boost::system::error_code returnedError;\n    boost::filesystem::create_directories(dinosaurOutputDir, returnedError);\n    if (!boost::filesystem::exists(dinosaurOutputDir)) {\n      std::ostringstream oss;\n      oss << \"Error: could not create output directory at \" << \n             dinosaurOutputDir.string() << std::endl;\n      throw MyException(oss.str());\n    }\n    \n    int rc = DinosaurIO::runDinosaurTargeted(outputDir, targetMzMLFile, targetFile);\n    if (rc != EXIT_SUCCESS) {\n      std::ostringstream oss;\n      oss << \"Dinosaur failed with exit code \" << rc << \n             \". Terminating..\" << std::endl;\n      throw MyException(oss.str());\n    }\n  }\n  \n  processDinosaurTargets(precursorLinks, dinosaurOutputFile, \n      percolatorOutputFile, featuresQueryRun, featuresTargetRun, \n      predictedRTimesTargetRun, candidateFeaturesTargetRun);\n}\n    \nvoid FeatureAlignment::processDinosaurTargets(\n    const std::map<int, FeatureIdxMatch>& precursorLinks,\n    const std::string& dinosaurTargetOutputFile, \n    const std::string& percolatorOutputFile, \n    const DinosaurFeatureList& featuresQueryRun,\n    const DinosaurFeatureList& featuresTargetRun,\n    const std::vector<double>& predictedRTimesTargetRun,\n    DinosaurFeatureList& candidateFeaturesTargetRun) {\n  std::vector<std::string> percolatorArgs = percolatorArgs_;\n  \n  PercolatorAdapter percolatorAdapter;\n  bool runPercolator = false;\n  if (Globals::fileIsEmpty(percolatorOutputFile)) {\n    runPercolator = true;\n    percolatorArgs.push_back(\"--results-psms\");\n    percolatorArgs.push_back(percolatorOutputFile);\n    percolatorArgs.push_back(\"--decoy-results-psms\");\n    percolatorArgs.push_back(percolatorOutputFile + \".decoys\");\n    /*\n    percolatorArgs.push_back(\"--tab-out\");\n    percolatorArgs.push_back(percolatorOutputFile + \".pin\");\n    */\n    \n    percolatorAdapter.parseOptions(percolatorArgs);  \n    percolatorAdapter.init(kLinkFeatureNames);\n  }\n  \n  std::ifstream dinosaurOutputStream(dinosaurTargetOutputFile.c_str(), ios::in);\n  \n  std::string targetLine;\n  getline(dinosaurOutputStream, targetLine); /* skip header */\n  \n  DinosaurFeatureList::const_iterator queryIt;\n  std::vector<double>::const_iterator predRTimeIt;\n  for (queryIt = featuresQueryRun.begin(), predRTimeIt = predictedRTimesTargetRun.begin(); \n       queryIt != featuresQueryRun.end(); ++queryIt, ++predRTimeIt) {\n    if (precursorLinks.find(queryIt->featureIdx) == precursorLinks.end() || \n        precursorLinks.find(queryIt->featureIdx)->second.posteriorErrorProb >= linkPEPMbrSearchThreshold_) {\n      getline(dinosaurOutputStream, targetLine);\n      DinosaurFeature targetFeature = DinosaurIO::parseDinosaurFeatureRow(targetLine);\n      targetFeature.featureIdx = featuresTargetRun.getFeatureIdx(targetFeature);\n      targetFeature.fileIdx = -1;\n      if (targetFeature.intensity > 0.0 && targetFeature.featureIdx == -1) {\n        targetFeature.featureIdx = candidateFeaturesTargetRun.getFeatureIdx(targetFeature);\n        if (targetFeature.featureIdx == -1) {\n          targetFeature.featureIdx = getCandidateIdx(candidateFeaturesTargetRun.size());\n          candidateFeaturesTargetRun.push_back(targetFeature);\n        }\n      }\n      \n      getline(dinosaurOutputStream, targetLine);\n      if (runPercolator) {\n        DinosaurFeature decoyFeature = DinosaurIO::parseDinosaurFeatureRow(targetLine);\n        decoyFeature.featureIdx = -1;\n        decoyFeature.fileIdx = -1;\n        \n        DinosaurFeature queryFeature = *queryIt;\n        queryFeature.rTime = *predRTimeIt;\n        if (targetFeature.intensity > 0.0)\n          addLinkPsm(1, queryFeature, targetFeature, percolatorAdapter);\n        \n        queryFeature.precMz += decoyOffset_;\n        if (decoyFeature.intensity > 0.0)\n          addLinkPsm(-1, queryFeature, decoyFeature, percolatorAdapter);\n      }\n    }\n  }\n  \n  if (runPercolator) {    \n    percolatorAdapter.process();\n  }\n}\n\nstd::string FeatureAlignment::convertFeatureToPsmId(const DinosaurFeature& feature) {\n  return boost::lexical_cast<std::string>(feature.featureIdx) + \"_\" + \n         boost::lexical_cast<std::string>(feature.precMz) + \"_\" + \n         boost::lexical_cast<std::string>(feature.rTime) + \"_\" + \n         boost::lexical_cast<std::string>(feature.intensity) + \"_\" + \n         boost::lexical_cast<std::string>(feature.charge);\n}\n\nDinosaurFeature FeatureAlignment::parsePsmIdAsFeature(const std::string& specId) {\n  DinosaurFeature ft;\n  \n  size_t prev = 0u;\n  size_t next = specId.find_first_of(\"_\", prev);\n  ft.featureIdx = boost::lexical_cast<int>(specId.substr(prev, next - prev));\n  prev = next+1;\n  \n  next = specId.find_first_of(\"_\", prev);\n  ft.precMz = boost::lexical_cast<float>(specId.substr(prev, next - prev));\n  prev = next+1;\n  \n  next = specId.find_first_of(\"_\", prev);\n  ft.rTime = boost::lexical_cast<float>(specId.substr(prev, next - prev));\n  prev = next+1;\n  \n  next = specId.find_first_of(\"_\", prev);\n  ft.intensity = boost::lexical_cast<float>(specId.substr(prev, next - prev));\n  prev = next+1;\n  \n  next = specId.find_first_of(\"_\", prev);\n  ft.charge = boost::lexical_cast<int>(specId.substr(prev, next - prev));\n  \n  return ft;\n}\n\n} /* namespace quandenser */\n", "meta": {"hexsha": "841f93f8e6f5c4d651a3b1af2e834f8c38a7e806", "size": 21466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FeatureAlignment.cpp", "max_stars_repo_name": "statisticalbiotechnology/quandenser", "max_stars_repo_head_hexsha": "9441b9b9ccff443cea05274359685823b2eabd9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-02-07T01:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T01:01:34.000Z", "max_issues_repo_path": "src/FeatureAlignment.cpp", "max_issues_repo_name": "statisticalbiotechnology/quandenser", "max_issues_repo_head_hexsha": "9441b9b9ccff443cea05274359685823b2eabd9c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2018-12-07T10:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T13:56:42.000Z", "max_forks_repo_path": "src/FeatureAlignment.cpp", "max_forks_repo_name": "statisticalbiotechnology/quandenser", "max_forks_repo_head_hexsha": "9441b9b9ccff443cea05274359685823b2eabd9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-19T14:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-19T14:14:00.000Z", "avg_line_length": 41.6815533981, "max_line_length": 120, "alphanum_fraction": 0.699058977, "num_tokens": 5559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19277782022841533}}
{"text": "/**\n * algorithm.cpp\n *\n * MIT License\n *\n * Copyright (c) 2018 LandZERO\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 \"algorithm.h\"\n\n#include <dlib/opencv.h>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/imgproc.hpp>\n\n// down sample ratio\n#define DSRATIO 4\n\nclass Detection {\npublic:\n  Detection(dlib::full_object_detection *rawDet) : _rawDet(rawDet) {}\n\n  cv::Point2d operator[](size_t index) { return cv::Point2d(_rawDet->part(index).x(), _rawDet->part(index).y()); }\n\nprivate:\n  dlib::full_object_detection *_rawDet;\n};\n\nbool _cameraPointsConsideredSame(std::vector<cv::Point2d> &last, std::vector<cv::Point2d> &current) {\n  if (last.empty() || (last.size() != current.size()))\n    return false;\n  double base = cv::norm(current[0] - current[1]);\n  if (base == 0)\n    return false;\n  double total = 0;\n  for (size_t i = 0; i < last.size(); i++) {\n    total += cv::norm(current[i] - last[i]);\n  }\n  return (total / base) < 0.1;\n}\n\nbool _compareRectangleArea(dlib::rectangle &lhs, dlib::rectangle &rhs) { return lhs.area() < rhs.area(); }\n\naltego::Algorithm::Algorithm() {\n  // initialize detector\n  _detector = dlib::get_frontal_face_detector();\n\n  // initialize reference points\n  // The first must be (0,0,0) while using POSIT\n  _referencePoints.emplace_back(0.0f, 0.0f, 0.0f);          // 30\n  _referencePoints.emplace_back(0.0f, -330.0f, -65.0f);     // 8\n  _referencePoints.emplace_back(-225.0f, 170.0f, -135.0f);  // 36\n  _referencePoints.emplace_back(225.0f, 170.0f, -135.0f);   // 45\n  _referencePoints.emplace_back(-150.0f, -150.0f, -125.0f); // 48\n  _referencePoints.emplace_back(150.0f, -150.0f, -125.0f);  // 54\n\n  // initialize distCoeffs\n  _distCoeffs = cv::Mat::zeros(4, 1, cv::DataType<double>::type);\n}\n\nbool altego::Algorithm::ResolveAndAnnotate(cv::Mat &im, altego::Result &res) {\n  // down sample for face detection\n  cv::Mat imSmall;\n  cv::resize(im, imSmall, cv::Size(), 1.0 / DSRATIO, 1.0 / DSRATIO);\n  // convert type with zero copy\n  dlib::cv_image<dlib::bgr_pixel> dim(im);\n  dlib::cv_image<dlib::bgr_pixel> dimSmall(imSmall);\n  // detect faces\n  auto faces = _detector(dimSmall);\n  if (faces.empty())\n    return false;\n  // find largest face\n  auto face = *std::max_element(faces.begin(), faces.end(), _compareRectangleArea).base();\n  // upscale\n  face.left() *= DSRATIO;\n  face.top() *= DSRATIO;\n  face.right() *= DSRATIO;\n  face.bottom() *= DSRATIO;\n  // detection\n  auto rawDet = _predictor(dim, face);\n  // check num_parts()\n  if (rawDet.num_parts() != 68)\n    return false;\n  // draw detection\n  for (size_t i = 0; i < rawDet.num_parts(); i++) {\n    dlib::point p = rawDet.part(i);\n    // check part valid\n    if (p == dlib::OBJECT_PART_NOT_PRESENT)\n      return false;\n    cv::circle(im, cv::Point(static_cast<int>(p.x()), static_cast<int>(p.y())), 2, cv::Scalar(255, 0, 72), -1);\n  }\n\n  // wrap dlib::full_object_detection\n  Detection det(&rawDet);\n\n  // cameraPoints\n  std::vector<cv::Point2d> cp;\n  // nose tip\n  cp.push_back(det[30]);\n  // chin\n  cp.push_back(det[8]);\n  // left eye left corner\n  cp.push_back(det[36]);\n  // right eye right corner\n  cp.push_back(det[45]);\n  // left Mouth corner\n  cp.push_back(det[48]);\n  // right mouth corner\n  cp.push_back(det[54]);\n\n  // stabilize\n  if (_cameraPointsConsideredSame(_lastCameraPoints, cp))\n    return false;\n\n  // update lastCameraPoints\n  _lastCameraPoints = cp;\n\n  // camera matrix\n  cv::Mat_<double> cameraMatrix(3, 3);\n  cameraMatrix << im.cols, 0, im.cols / 2.f, 0, im.cols, im.rows / 2.f, 0, 0, 1;\n\n  // rotation vector, translation vector\n  cv::Mat rv, tv;\n\n  // solve\n  cv::solvePnP(_referencePoints, cp, cameraMatrix, _distCoeffs, rv, tv);\n\n  // set rv, tv to result\n  res.r1 = rv.at<double>(0, 1);\n  res.r2 = rv.at<double>(0, 2);\n\n  return true;\n}\n\nvoid altego::Algorithm::LoadModelFile(std::string &modelFile) { dlib::deserialize(modelFile) >> _predictor; }\n", "meta": {"hexsha": "0d6499161edbb98f66d8938df6e6b68853650369", "size": 4909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithm.cpp", "max_stars_repo_name": "etanaru/altego", "max_stars_repo_head_hexsha": "a85e96768cd7baaf96208a57ebb20df8ac327797", "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/algorithm.cpp", "max_issues_repo_name": "etanaru/altego", "max_issues_repo_head_hexsha": "a85e96768cd7baaf96208a57ebb20df8ac327797", "max_issues_repo_licenses": ["MIT"], "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/algorithm.cpp", "max_forks_repo_name": "etanaru/altego", "max_forks_repo_head_hexsha": "a85e96768cd7baaf96208a57ebb20df8ac327797", "max_forks_repo_licenses": ["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.0849673203, "max_line_length": 114, "alphanum_fraction": 0.6803829701, "num_tokens": 1457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19277781303396463}}
{"text": "// Copyright (c) 2020 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE CTCLossCodeletTest\n#include <iomanip>\n#include <random>\n\n#include <poplar/Engine.hpp>\n#include <poplar/Graph.hpp>\n#include <poplar/IPUModel.hpp>\n#include <poplibs_support/LogArithmetic.hpp>\n#include <poplibs_support/TestDevice.hpp>\n#include <poplibs_test/CTCLoss.hpp>\n#include <poplibs_test/CTCUtil.hpp>\n#include <poplibs_test/Embedding.hpp>\n#include <poplibs_test/MatrixTransforms.hpp>\n#include <poplibs_test/Util.hpp>\n#include <popnn/codelets.hpp>\n#include <poputil/VertexTemplates.hpp>\n#include <poputil/exceptions.hpp>\n\n#include <boost/multi_array.hpp>\n#include <boost/program_options.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\nnamespace po = boost::program_options;\n\nusing namespace poplar;\nusing namespace poplar::program;\nusing namespace poplibs_test::ctc;\nusing namespace poplibs_test;\nusing namespace poplibs_test::matrix;\nusing namespace poplibs_test::util;\nusing namespace poplibs_support;\nusing namespace poputil;\n\n// Default tolerances used in tests\n#define FLOAT_REL_TOL 0.01\n#define HALF_REL_TOL 0.1\n#define FLOAT_ABS_TOL 1e-6\n#define HALF_ABS_TOL 1e-5\n\nenum class TestType { ALPHA, BETA, GRAD_GIVEN_ALPHA, GRAD_GIVEN_BETA };\n\nstd::ostream &operator<<(std::ostream &os, const TestType &test) {\n  if (test == TestType::ALPHA)\n    return os << \"alpha\";\n  else if (test == TestType::BETA)\n    return os << \"beta\";\n  else if (test == TestType::GRAD_GIVEN_ALPHA)\n    return os << \"gradGivenAlpha\";\n  return os << \"gradGivenBeta\";\n}\n\nstd::istream &operator>>(std::istream &is, TestType &test) {\n  std::string token;\n  is >> token;\n  if (token == \"alpha\")\n    test = TestType::ALPHA;\n  else if (token == \"beta\")\n    test = TestType::BETA;\n  else if (token == \"gradGivenAlpha\")\n    test = TestType::GRAD_GIVEN_ALPHA;\n  else if (token == \"gradGivenBeta\")\n    test = TestType::GRAD_GIVEN_BETA;\n  else\n    throw poputil::poplibs_error(\"Unknown test type\");\n  return is;\n}\n\nboost::multi_array<double, 2>\nmaskResults(const boost::multi_array<double, 2> &in) {\n  auto out = in;\n  const auto symbols = out.shape()[0];\n  const auto timeSteps = out.shape()[1];\n  for (unsigned sym = 0; sym < symbols; sym++) {\n    if (sym > 1) {\n      out[sym][0] = 0;\n    }\n    if (sym < symbols - 2) {\n      out[sym][timeSteps - 1] = 0;\n    }\n  }\n  return out;\n}\n\nboost::multi_array<double, 2>\nmaskTimeSteps(const boost::multi_array<double, 2> &in, unsigned timeStep,\n              bool invertMask) {\n  auto out = in;\n  const auto symbols = out.shape()[0];\n  const auto timeSteps = out.shape()[1];\n  for (unsigned time = 0; time < timeSteps; time++) {\n    if ((invertMask && time == timeStep) || (!invertMask && time != timeStep)) {\n      for (unsigned sym = 0; sym < symbols; sym++) {\n        out[sym][time] = 0;\n      }\n    }\n  }\n  return out;\n}\n\n// Print a sequence, inserting `-` for the blank symbol\nvoid print(const std::string &prefix, const std::vector<unsigned> &idx,\n           unsigned blank, bool verbose = true) {\n  if (!verbose) {\n    return;\n  }\n  std::cout << \"\\n\" << prefix << \" \";\n  for (auto &i : idx) {\n    if (i == blank) {\n      std::cout << \"- \";\n    } else {\n      std::cout << i << \" \";\n    }\n  }\n  std::cout << \"\\n\";\n}\n\n// Print the matrix `in`, using `paddedSequence` as row labels\ntemplate <typename FPType>\nvoid print(const std::string &prefix, const boost::multi_array<FPType, 2> &in,\n           const std::vector<unsigned> &paddedSequence, unsigned blank,\n           bool verbose = true) {\n  if (!verbose) {\n    return;\n  }\n  std::cout << \"\\n\" << prefix << \"\\n          \";\n  for (unsigned i = 0; i < in[0].size(); i++) {\n    std::cout << \"         t\" << i;\n  }\n\n  for (unsigned i = 0; i < in.size(); i++) {\n    std::cout << \"\\nIndex:\" << i << \"  \";\n    if (paddedSequence[i] == blank) {\n      std::cout << \"- \";\n    } else {\n      std::cout << paddedSequence[i] << \" \";\n    }\n    for (unsigned j = 0; j < in[i].size(); j++) {\n      std::cout << std::setw(10) << std::setprecision(4) << in[i][j] << \",\";\n    }\n  }\n  std::cout << \"\\n\";\n}\n\n// Print the matrix `in`\ntemplate <typename FPType>\nvoid print(const std::string &prefix, const boost::multi_array<FPType, 2> &in,\n           unsigned blank, bool verbose = true) {\n  if (!verbose) {\n    return;\n  }\n  std::cout << \"\\n\" << prefix << \"\\n        \";\n  for (unsigned i = 0; i < in[0].size(); i++) {\n    std::cout << \"         t\" << i;\n  }\n\n  for (unsigned i = 0; i < in.size(); i++) {\n    if (i == blank) {\n      std::cout << \"\\nIndex:-  \";\n    } else {\n      std::cout << \"\\nIndex:\" << i << \"  \";\n    }\n    for (unsigned j = 0; j < in[i].size(); j++) {\n      std::cout << std::setw(10) << std::setprecision(4) << in[i][j] << \",\";\n    }\n  }\n  std::cout << \"\\n\";\n}\n\n// Struct and function to return the test inputs\ntemplate <typename FPType> struct InputSequence {\n  boost::multi_array<FPType, 2> input;\n  std::vector<unsigned> idx;\n  unsigned alphabetSizeIncBlank;\n};\n\ntemplate <typename FPType>\nboost::multi_array<FPType, 2>\ngradReference(const InputSequence<FPType> &test, unsigned blankClass,\n              TestType vertexToTest, bool verbose) {\n\n  auto paddedSequence = extendedLabels(test.idx, blankClass);\n  auto validTimesteps = test.input.shape()[1];\n\n  print(\"Log Softmax in\", test.input, blankClass, verbose);\n  boost::multi_array<FPType, 2> logSequence(\n      boost::extents[paddedSequence.size()][test.input.shape()[1]]);\n  poplibs_test::embedding::multiSlice(test.input, paddedSequence, logSequence);\n\n  print(\"Reference sequence\", logSequence, paddedSequence, blankClass, verbose);\n\n  auto alphaLog =\n      alpha(logSequence, paddedSequence, blankClass, validTimesteps);\n  if (vertexToTest == TestType::ALPHA) {\n    print(\"Reference alphas\", alphaLog, paddedSequence, blankClass, verbose);\n    return alphaLog;\n  }\n\n  auto betaLog = beta(logSequence, paddedSequence, blankClass, validTimesteps);\n  if (vertexToTest == TestType::BETA) {\n    print(\"Reference betas\", betaLog, paddedSequence, blankClass, verbose);\n    return betaLog;\n  }\n  auto expandedGradient =\n      expandedGrad(logSequence, alphaLog, betaLog, paddedSequence, blankClass,\n                   validTimesteps);\n  print(\"Expanded Reference gradient\", expandedGradient, paddedSequence,\n        blankClass, verbose);\n\n  auto gradient =\n      ctcGrad(logSequence, alphaLog, betaLog, paddedSequence,\n              test.alphabetSizeIncBlank, blankClass, validTimesteps);\n  print(\"Reference gradient\", gradient, blankClass, verbose);\n\n  std::cout << \"\\n\";\n  return gradient;\n}\n\nboost::multi_array<double, 2>\ngradIPU(const InputSequence<double> &input, unsigned timeStep,\n        unsigned blankClass, const boost::multi_array<double, 2> &initialValues,\n        TestType vertexToTest, Type inType, Type outType,\n        const DeviceType &deviceType, bool profile) {\n\n  auto device = createTestDevice(deviceType, 1, 1);\n  const auto &target = device.getTarget();\n  Graph graph(target);\n  popnn::addCodelets(graph);\n  Sequence prog;\n\n  const auto labelLen = input.idx.size();\n  const auto extendedLabelLen = 2 * labelLen + 1;\n  const auto maxT = input.input.shape()[1];\n  const auto numClasses = input.input.shape()[0];\n\n  const auto resultIsGrad = (vertexToTest == TestType::GRAD_GIVEN_ALPHA ||\n                             vertexToTest == TestType::GRAD_GIVEN_BETA);\n  const auto findingAlpha = (vertexToTest == TestType::ALPHA ||\n                             vertexToTest == TestType::GRAD_GIVEN_BETA);\n\n  auto probabilities =\n      graph.addVariable(inType, {maxT, numClasses}, \"probabilities\");\n  auto labels = graph.addVariable(UNSIGNED_INT, {labelLen}, \"label\");\n  auto result = graph.addVariable(\n      outType, {maxT, resultIsGrad ? numClasses : extendedLabelLen}, \"result\");\n  auto prevTime = graph.addVariable(\n      outType, {resultIsGrad ? 2u : 1u, extendedLabelLen}, \"prevTime\");\n  graph.setTileMapping(prevTime, 0);\n  auto prevLabel =\n      graph.addVariable(outType, {findingAlpha ? 1u : 2u, maxT}, \"prevLabel\");\n  graph.setTileMapping(prevLabel, 0);\n  auto prevSymbol = graph.addConstant<unsigned>(UNSIGNED_INT, {}, input.idx[0]);\n  graph.setTileMapping(prevSymbol, 0);\n  Tensor initialAlphaOrBeta;\n  if (resultIsGrad) {\n    initialAlphaOrBeta = graph.addVariable(outType, {maxT, extendedLabelLen},\n                                           \"initialAlphaOrBeta\");\n    graph.setTileMapping(initialAlphaOrBeta, 0);\n  }\n  Tensor loss;\n  if (findingAlpha) {\n    loss = graph.addVariable(outType, {}, \"loss\");\n    graph.setTileMapping(loss, 0);\n  }\n  auto cs = graph.addComputeSet(\"cs\");\n  std::string vertexName;\n  if (vertexToTest == TestType::ALPHA) {\n    vertexName =\n        templateVertex(\"popnn::CTCAlpha\", inType, outType, UNSIGNED_INT, true);\n  } else if (vertexToTest == TestType::BETA) {\n    vertexName =\n        templateVertex(\"popnn::CTCBeta\", inType, outType, UNSIGNED_INT, true);\n  } else if (vertexToTest == TestType::GRAD_GIVEN_ALPHA) {\n    vertexName = templateVertex(\"popnn::CTCGradGivenAlpha\", inType, outType,\n                                UNSIGNED_INT, true);\n  } else if (vertexToTest == TestType::GRAD_GIVEN_BETA) {\n    vertexName = templateVertex(\"popnn::CTCGradGivenBeta\", inType, outType,\n                                UNSIGNED_INT, true);\n  }\n  auto vertex = graph.addVertex(cs, vertexName);\n\n  // TODO - Vertex features to support < maxT and < labelsLen sized\n  // inputs, and accepting data from the previous label inputs\n  // are only tested in the context of the whole IPU implementation.\n  // Suggest that when optimising the vertices this test is improved.\n  auto validLabel = graph.addConstant(UNSIGNED_INT, {}, labelLen);\n  auto validTime = graph.addConstant(UNSIGNED_INT, {}, maxT);\n  auto initialCount = graph.addConstant(UNSIGNED_INT, {}, timeStep);\n  auto count = graph.addVariable(UNSIGNED_INT, {}, \"count\");\n  prog.add(Copy(initialCount, count));\n  graph.setTileMapping(validLabel, 0);\n  graph.setTileMapping(validTime, 0);\n  graph.setTileMapping(initialCount, 0);\n  graph.setTileMapping(count, 0);\n  graph.connect(vertex[\"validLabel\"], validLabel);\n  graph.connect(vertex[\"validTime\"], validTime);\n  graph.connect(vertex[\"count\"], count);\n\n  graph.setInitialValue(vertex[\"maxT\"], maxT);\n  graph.setInitialValue(vertex[\"numClasses\"], numClasses);\n  graph.setInitialValue(vertex[\"blankClass\"], blankClass);\n  graph.setInitialValue(vertex[\"labelOffset\"], 0);\n  graph.setInitialValue(vertex[\"timeOffset\"], 0);\n\n  auto labelWithPreviousOrNext = findingAlpha\n                                     ? concat(prevSymbol.reshape({1}), labels)\n                                     : concat(labels, prevSymbol.reshape({1}));\n  graph.connect(vertex[\"label\"], labelWithPreviousOrNext);\n  graph.connect(vertex[\"probabilities\"], probabilities.flatten());\n\n  if (vertexToTest == TestType::ALPHA) {\n    graph.connect(vertex[\"alphas\"], result.flatten());\n    graph.connect(vertex[\"alphaPrevTime\"], prevTime.flatten());\n    graph.connect(vertex[\"alphaPrevLabel\"], prevLabel.flatten());\n    graph.connect(vertex[\"loss\"], loss);\n\n    graph.connect(vertex[\"alphaPrevLabelOut\"], prevLabel.flatten());\n    graph.connect(vertex[\"alphaPrevLabelTime\"], prevLabel.flatten());\n  } else if (vertexToTest == TestType::BETA) {\n    graph.connect(vertex[\"betas\"], result.flatten());\n    graph.connect(vertex[\"betaPrevTime\"], prevTime.flatten());\n    graph.connect(vertex[\"betaPrevLabel\"], prevLabel.flatten());\n\n    graph.connect(vertex[\"betaPrevLabelOut\"], prevLabel.flatten());\n    graph.connect(vertex[\"betaPrevLabelTime\"], prevLabel.flatten());\n  } else if (vertexToTest == TestType::GRAD_GIVEN_ALPHA) {\n    graph.connect(vertex[\"grads\"], result.flatten());\n    graph.connect(vertex[\"alphas\"], initialAlphaOrBeta.flatten());\n    graph.connect(vertex[\"betaPrevTime\"], prevTime.flatten());\n    graph.connect(vertex[\"betaPrevLabel\"], prevLabel.flatten());\n\n    graph.connect(vertex[\"betaPrevPartition\"], prevTime.flatten());\n    graph.connect(vertex[\"betaPrevLabelOut\"], prevLabel.flatten());\n    graph.connect(vertex[\"betaPrevLabelTime\"], prevLabel.flatten());\n  } else if (vertexToTest == TestType::GRAD_GIVEN_BETA) {\n    graph.connect(vertex[\"grads\"], result.flatten());\n    graph.connect(vertex[\"betas\"], initialAlphaOrBeta.flatten());\n    graph.connect(vertex[\"alphaPrevTime\"], prevTime.flatten());\n    graph.connect(vertex[\"alphaPrevLabel\"], prevLabel.flatten());\n    graph.connect(vertex[\"loss\"], loss);\n\n    graph.connect(vertex[\"alphaPrevPartition\"], prevTime.flatten());\n    graph.connect(vertex[\"alphaPrevLabelOut\"], prevLabel.flatten());\n    graph.connect(vertex[\"alphaPrevLabelTime\"], prevLabel.flatten());\n  }\n\n  graph.setTileMapping(probabilities, 0);\n  graph.setTileMapping(labels, 0);\n  graph.setTileMapping(result, 0);\n  graph.setTileMapping(vertex, 0);\n\n  Sequence uploadProg, downloadProg;\n  std::vector<std::pair<std::string, char *>> tmap;\n  std::unique_ptr<char[]> rawProbabilities, rawResult, rawLabels,\n      rawInitialAlphaOrBeta, rawPrevTime, rawPrevLabel;\n\n  rawProbabilities = allocateHostMemoryForTensor(\n      probabilities, \"probabilities\", graph, uploadProg, downloadProg, tmap);\n  rawLabels = allocateHostMemoryForTensor(labels, \"labels\", graph, uploadProg,\n                                          downloadProg, tmap);\n  rawResult = allocateHostMemoryForTensor(result, \"result\", graph, uploadProg,\n                                          downloadProg, tmap);\n\n  copy(target, transpose(input.input), inType, rawProbabilities.get());\n  copy(target, input.idx.data(), input.idx.size(), labels.elementType(),\n       rawLabels.get());\n\n  // Initialise alpha or beta if needed by the test, otherwise uninitialised\n  if (resultIsGrad) {\n    rawInitialAlphaOrBeta =\n        allocateHostMemoryForTensor(initialAlphaOrBeta, \"initialAlphaOrBeta\",\n                                    graph, uploadProg, downloadProg, tmap);\n  } else {\n    rawInitialAlphaOrBeta = allocateHostMemoryForTensor(\n        result, \"initialResult\", graph, uploadProg, downloadProg, tmap);\n  }\n  copy(target, transpose(initialValues), outType, rawInitialAlphaOrBeta.get());\n  boost::multi_array<double, 2> zeroResult(\n      boost::extents[result.dim(0)][result.dim(1)]);\n  std::fill(zeroResult.data(), zeroResult.data() + zeroResult.num_elements(),\n            log::probabilityZero);\n  copy(target, zeroResult, outType, rawResult.get());\n  // Initialise the first Timeslice input of the vertex - in practice this could\n  // be \"carried over\" from a previous vertex alpha or beta calculation\n  rawPrevTime = allocateHostMemoryForTensor(prevTime, \"prevTime\", graph,\n                                            uploadProg, downloadProg, tmap);\n  boost::multi_array<double, 2> prevTimeInit(\n      boost::extents[prevTime.dim(0)][prevTime.dim(1)]);\n  std::fill(prevTimeInit.data(),\n            prevTimeInit.data() + prevTimeInit.num_elements(),\n            log::probabilityZero);\n\n  if (findingAlpha) {\n    // 1st symbol probability=1\n    prevTimeInit[0][0] = log::probabilityOne;\n    copy(target, prevTimeInit, outType, rawPrevTime.get());\n  } else {\n    // last symbol probability=1\n    prevTimeInit[0][extendedLabelLen - 1] = log::probabilityOne;\n    copy(target, prevTimeInit, outType, rawPrevTime.get());\n  }\n\n  rawPrevLabel = allocateHostMemoryForTensor(prevLabel, \"prevLabel\", graph,\n                                             uploadProg, downloadProg, tmap);\n  boost::multi_array<double, 2> prevLabelInit(\n      boost::extents[prevLabel.dim(0)][prevLabel.dim(1)]);\n  std::fill(prevLabelInit.data(),\n            prevLabelInit.data() + prevLabelInit.num_elements(),\n            log::probabilityZero);\n  copy(target, prevLabelInit, outType, rawPrevLabel.get());\n\n  prog.add(Execute(cs));\n  OptionFlags engineOptions;\n  if (profile) {\n    engineOptions.set(\"debug.instrumentCompute\", \"true\");\n  }\n  Engine engine(graph, Sequence{uploadProg, prog, downloadProg}, engineOptions);\n  attachStreams(engine, tmap);\n  device.bind([&](const Device &d) {\n    engine.load(d);\n    engine.run();\n  });\n  boost::multi_array<double, 2> output(\n      boost::extents[result.dim(0)][result.dim(1)]);\n  copy(target, outType, rawResult.get(), output);\n\n  if (profile && deviceType != DeviceType::Cpu) {\n    engine.printProfileSummary(std::cout,\n                               OptionFlags{{\"showExecutionSteps\", \"true\"}});\n  }\n  return transpose(output);\n}\n\nint main(int argc, char **argv) {\n  // Default input parameters.\n  DeviceType deviceType = DeviceType::IpuModel2;\n  bool verbose = false;\n  bool profile = false;\n  unsigned blankClass = 0;\n  unsigned testTime = 15;\n  unsigned testSymbols = 3;\n  unsigned numClasses = 4;\n  unsigned timeStep = 0;\n  TestType vertexToTest = TestType::ALPHA;\n  Type inType = FLOAT;\n  Type outType = FLOAT;\n\n  po::options_description desc(\"Options\");\n  // clang-format off\n  desc.add_options()\n    (\"help\", \"Produce help message\")\n    (\"device-type\",\n     po::value<DeviceType>(&deviceType)->default_value(deviceType),\n     deviceTypeHelp)\n    (\"in-type\", po::value(&inType)->default_value(inType),\n     \"Vertex input data type\")\n    (\"out-type\", po::value(&outType)->default_value(outType),\n     \"Vertex output data type\")\n    (\"profile\", po::value(&profile)->default_value(profile),\n     \"Show profile report\")\n    (\"test\", po::value(&vertexToTest)->default_value(vertexToTest),\n     \"Test: alpha, beta, gradGivenAlpha, gradGivenBeta\")\n    (\"blank-class\", po::value(&blankClass)->default_value(blankClass),\n     \"Index of the blank symbol. Range 0 to (num-classes-1)\")\n    (\"test-symbols\", po::value(&testSymbols)->default_value(testSymbols),\n     \"Test length (symbols)\")\n    (\"time\", po::value(&testTime)->default_value(testTime),\n     \"Test length (time)\")\n    (\"num-classes\", po::value(&numClasses)->default_value(numClasses),\n     \"Classes in the alphabet including blank\")\n    (\"time-step\", po::value(&timeStep)->default_value(timeStep),\n     \"The timestep (loop count) to process\")\n    (\"verbose\", po::value(&verbose)->default_value(verbose),\n     \"Provide debug printout\");\n  // clang-format on\n\n  po::variables_map vm;\n  try {\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\\n\";\n      return 1;\n    }\n\n  } catch (std::exception &e) {\n    std::cerr << \"error parsing command line: \" << e.what() << \"\\n\";\n    return 1;\n  }\n  // Needed to set default arguments.\n  po::notify(vm);\n  if (testTime < testSymbols) {\n    throw poputil::poplibs_error(\"The test time must be >= sequence symbols\");\n  }\n  if (blankClass >= numClasses) {\n    throw poputil::poplibs_error(\"The blank class must be in the range 0 to \"\n                                 \"(number of classes - 1)\");\n  }\n\n  RandomUtil rand{42};\n  auto [input, label] = getRandomTestInput<double>(\n      testTime, testTime, testSymbols, numClasses, blankClass, true, rand);\n  auto test = InputSequence<double>{transpose(input), label, numClasses};\n\n  print(\"Test sequence:\", test.idx, blankClass, verbose);\n\n  // Produce a sensible input by calling the model.\n  // This will contain all alpha/beta inputs for a gradGivenAlpha/Beta vertex\n  // test, or all but the timeStep to be tested for alpha/beta vertices\n  auto initialOutputType = (vertexToTest == TestType::ALPHA ||\n                            vertexToTest == TestType::GRAD_GIVEN_ALPHA)\n                               ? TestType::ALPHA\n                               : TestType::BETA;\n  auto initialOutput =\n      gradReference<double>(test, blankClass, initialOutputType, false);\n  if (vertexToTest == TestType::ALPHA || vertexToTest == TestType::BETA) {\n    // For alpha, beta vertices an effective test can by made by masking out\n    // the one timeslice that the vertex should be calculating\n    initialOutput = maskTimeSteps(initialOutput, timeStep, true);\n  }\n  auto reference =\n      gradReference<double>(test, blankClass, vertexToTest, verbose);\n  auto output = gradIPU(test, timeStep, blankClass, initialOutput, vertexToTest,\n                        inType, outType, deviceType, profile);\n\n  double relativeTolerance = inType == FLOAT ? FLOAT_REL_TOL : HALF_REL_TOL;\n  double absoluteTolerance = inType == FLOAT ? FLOAT_ABS_TOL : HALF_ABS_TOL;\n\n  // When finding alpha, beta some results aren't relevant. Mask them out\n  if (vertexToTest == TestType::ALPHA || vertexToTest == TestType::BETA) {\n    print(\"IPU result:\", output, extendedLabels(test.idx, blankClass),\n          blankClass, verbose);\n    reference = maskResults(reference);\n    output = maskResults(output);\n  } else {\n    print(\"IPU result:\", output, blankClass, verbose);\n    // Mask out all but the timestep processed.\n    // TODO - This is a bit of a cheat, only the 1st (alpha) or last (beta)\n    // timestep works at the moment, plus we should verify the whole output\n    // is untouched.  Suggest doing this when making assembler vertices\n    output = maskTimeSteps(output, timeStep, false);\n    reference = maskTimeSteps(reference, timeStep, false);\n  }\n\n  bool success = checkIsClose(\"result\", output, reference, relativeTolerance,\n                              absoluteTolerance);\n  if (!success) {\n    std::cerr << \"Data mismatch\\n\";\n  }\n  return !success;\n}\n", "meta": {"hexsha": "fa584eb78cde32f0f1ef9137aff6649a7879e22a", "size": 21110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popnn/codelets/CTCLossCodeletTest.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": "tests/popnn/codelets/CTCLossCodeletTest.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": "tests/popnn/codelets/CTCLossCodeletTest.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": 38.3121597096, "max_line_length": 80, "alphanum_fraction": 0.6649928944, "num_tokens": 5378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.19268157606943337}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ 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 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 \"bempp/common/config_ahmed.hpp\"\n#include \"bempp/common/config_trilinos.hpp\"\n\n#include \"hmat_global_assembler.hpp\"\n\n#include \"assembly_options.hpp\"\n#include \"context.hpp\"\n#include \"evaluation_options.hpp\"\n#include \"discrete_boundary_operator_composition.hpp\"\n#include \"discrete_sparse_boundary_operator.hpp\"\n#include \"weak_form_hmat_assembly_helper.hpp\"\n#include \"discrete_hmat_boundary_operator.hpp\"\n\n#include \"../common/armadillo_fwd.hpp\"\n#include \"../common/auto_timer.hpp\"\n#include \"../common/chunk_statistics.hpp\"\n#include \"../common/to_string.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../fiber/local_assembler_for_integral_operators.hpp\"\n#include \"../fiber/scalar_traits.hpp\"\n#include \"../fiber/shared_ptr.hpp\"\n#include \"../space/space.hpp\"\n#include \"../common/bounding_box.hpp\"\n\n#include \"../hmat/block_cluster_tree.hpp\"\n#include \"../hmat/geometry_interface.hpp\"\n#include \"../hmat/geometry_data_type.hpp\"\n#include \"../hmat/geometry.hpp\"\n#include \"../hmat/hmatrix.hpp\"\n#include \"../hmat/data_accessor.hpp\"\n#include \"../hmat/hmatrix_dense_compressor.hpp\"\n#include \"../hmat/hmatrix_aca_compressor.hpp\"\n\n#include <stdexcept>\n#include <fstream>\n#include <iostream>\n\n#include <boost/type_traits/is_complex.hpp>\n\n#include <tbb/atomic.h>\n#include <tbb/parallel_for.h>\n#include <tbb/task_scheduler_init.h>\n#include <tbb/concurrent_queue.h>\n\n#include <Teuchos_ParameterList.hpp>\n\nnamespace Bempp {\n\nnamespace {\n\ntemplate <typename BasisFunctionType>\nclass SpaceHMatGeometryInterface : public hmat::GeometryInterface {\n\npublic:\n  typedef typename Fiber::ScalarTraits<BasisFunctionType>::RealType\n  CoordinateType;\n  SpaceHMatGeometryInterface(const Space<BasisFunctionType> &space)\n      : m_counter(0) {\n    space.getGlobalDofBoundingBoxes(m_bemppBoundingBoxes);\n  }\n  shared_ptr<const hmat::GeometryDataType> next() override {\n\n    if (m_counter == m_bemppBoundingBoxes.size())\n      return shared_ptr<hmat::GeometryDataType>();\n\n    auto lbound = m_bemppBoundingBoxes[m_counter].lbound;\n    auto ubound = m_bemppBoundingBoxes[m_counter].ubound;\n    auto center = m_bemppBoundingBoxes[m_counter].reference;\n    m_counter++;\n    return shared_ptr<hmat::GeometryDataType>(new hmat::GeometryDataType(\n        hmat::BoundingBox(lbound.x, ubound.x, lbound.y, ubound.y, lbound.z,\n                          ubound.z),\n        std::array<double, 3>({{center.x, center.y, center.z}})));\n  }\n\n  std::size_t numberOfEntities() const override {\n    return m_bemppBoundingBoxes.size();\n  }\n  void reset() override { m_counter = 0; }\n\nprivate:\n  std::size_t m_counter;\n  std::vector<BoundingBox<CoordinateType>> m_bemppBoundingBoxes;\n};\n\ntemplate <typename BasisFunctionType>\nshared_ptr<hmat::DefaultBlockClusterTreeType>\ngenerateBlockClusterTree(const Space<BasisFunctionType> &testSpace,\n                         const Space<BasisFunctionType> &trialSpace,\n                         int minBlockSize, int maxBlockSize, double eta) {\n\n  hmat::Geometry testGeometry;\n  hmat::Geometry trialGeometry;\n\n  auto testSpaceGeometryInterface = shared_ptr<hmat::GeometryInterface>(\n      new SpaceHMatGeometryInterface<BasisFunctionType>(testSpace));\n\n  auto trialSpaceGeometryInterface = shared_ptr<hmat::GeometryInterface>(\n      new SpaceHMatGeometryInterface<BasisFunctionType>(trialSpace));\n\n  hmat::fillGeometry(testGeometry, *testSpaceGeometryInterface);\n  hmat::fillGeometry(trialGeometry, *trialSpaceGeometryInterface);\n\n  auto testClusterTree = shared_ptr<hmat::DefaultClusterTreeType>(\n      new hmat::DefaultClusterTreeType(testGeometry, minBlockSize));\n\n  auto trialClusterTree = shared_ptr<hmat::DefaultClusterTreeType>(\n      new hmat::DefaultClusterTreeType(trialGeometry, minBlockSize));\n\n  shared_ptr<hmat::DefaultBlockClusterTreeType> blockClusterTree(\n      new hmat::DefaultBlockClusterTreeType(testClusterTree, trialClusterTree,\n                                            maxBlockSize,\n                                            hmat::StandardAdmissibility(eta)));\n\n  return blockClusterTree;\n}\n} // end anonymous namespace\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::unique_ptr<DiscreteBoundaryOperator<ResultType>>\nHMatGlobalAssembler<BasisFunctionType, ResultType>::assembleDetachedWeakForm(\n    const Space<BasisFunctionType> &testSpace,\n    const Space<BasisFunctionType> &trialSpace,\n    const std::vector<LocalAssemblerForIntegralOperators *> &localAssemblers,\n    const std::vector<LocalAssemblerForIntegralOperators *> &\n        localAssemblersForAdmissibleBlocks,\n    const std::vector<const DiscreteBndOp *> &sparseTermsToAdd,\n    const std::vector<ResultType> &denseTermMultipliers,\n    const std::vector<ResultType> &sparseTermMultipliers,\n    const Context<BasisFunctionType, ResultType> &context, int symmetry) {\n\n  const AssemblyOptions &options = context.assemblyOptions();\n  const auto hMatParameterList =\n      context.globalParameterList().sublist(\"HMatParameters\");\n  const bool indexWithGlobalDofs =\n      (hMatParameterList.template get<std::string>(\"HMatAssemblyMode\") ==\n       \"GlobalAssembly\");\n  const bool verbosityAtLeastDefault =\n      (options.verbosityLevel() >= VerbosityLevel::DEFAULT);\n  const bool verbosityAtLeastHigh =\n      (options.verbosityLevel() >= VerbosityLevel::HIGH);\n\n  auto testSpacePointer = Fiber::make_shared_from_const_ref(testSpace);\n  auto trialSpacePointer = Fiber::make_shared_from_const_ref(trialSpace);\n\n  shared_ptr<const Space<BasisFunctionType>> actualTestSpace;\n  shared_ptr<const Space<BasisFunctionType>> actualTrialSpace;\n  if (indexWithGlobalDofs) {\n    actualTestSpace = testSpacePointer->discontinuousSpace(testSpacePointer);\n    actualTrialSpace = trialSpacePointer->discontinuousSpace(trialSpacePointer);\n  } else {\n    actualTestSpace = testSpacePointer;\n    actualTrialSpace = trialSpacePointer;\n  }\n\n  auto minBlockSize =\n      hMatParameterList.template get<unsigned int>(\"minBlockSize\");\n  auto maxBlockSize =\n      hMatParameterList.template get<unsigned int>(\"maxBlockSize\");\n  auto eta = hMatParameterList.template get<double>(\"eta\");\n\n  auto blockClusterTree = generateBlockClusterTree(\n      *actualTestSpace, *actualTrialSpace, minBlockSize, maxBlockSize, eta);\n\n  // blockClusterTree->writeToPdfFile(\"tree.pdf\", 1024, 1024);\n\n  WeakFormHMatAssemblyHelper<BasisFunctionType, ResultType> helper(\n      *actualTestSpace, *actualTrialSpace, blockClusterTree, localAssemblers,\n      sparseTermsToAdd, denseTermMultipliers, sparseTermMultipliers);\n\n  // hmat::HMatrixDenseCompressor<ResultType, 2> compressor(helper);\n  // shared_ptr<hmat::CompressedMatrix<ResultType>> hMatrix(\n  //    new hmat::DefaultHMatrixType<ResultType>(blockClusterTree, compressor));\n\n  hmat::HMatrixAcaCompressor<ResultType, 2> compressor(helper, 1E-3, 30);\n  shared_ptr<hmat::CompressedMatrix<ResultType>> hMatrix(\n      new hmat::DefaultHMatrixType<ResultType>(blockClusterTree, compressor));\n\n  return std::unique_ptr<DiscreteBoundaryOperator<ResultType>>(\n      new DiscreteHMatBoundaryOperator<ResultType>(hMatrix));\n\n  // return std::unique_ptr<DiscreteBoundaryOperator<ResultType>>();\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::unique_ptr<DiscreteBoundaryOperator<ResultType>>\nHMatGlobalAssembler<BasisFunctionType, ResultType>::assembleDetachedWeakForm(\n    const Space<BasisFunctionType> &testSpace,\n    const Space<BasisFunctionType> &trialSpace,\n    LocalAssemblerForIntegralOperators &localAssembler,\n    LocalAssemblerForIntegralOperators &localAssemblerForAdmissibleBlocks,\n    const Context<BasisFunctionType, ResultType> &context, int symmetry) {\n  typedef LocalAssemblerForIntegralOperators Assembler;\n  std::vector<Assembler *> localAssemblers(1, &localAssembler);\n  std::vector<Assembler *> localAssemblersForAdmissibleBlocks(\n      1, &localAssemblerForAdmissibleBlocks);\n  std::vector<const DiscreteBndOp *> sparseTermsToAdd;\n  std::vector<ResultType> denseTermsMultipliers(1, 1.0);\n  std::vector<ResultType> sparseTermsMultipliers;\n\n  return assembleDetachedWeakForm(testSpace, trialSpace, localAssemblers,\n                                  localAssemblersForAdmissibleBlocks,\n                                  sparseTermsToAdd, denseTermsMultipliers,\n                                  sparseTermsMultipliers, context, symmetry);\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(HMatGlobalAssembler);\n\n} // namespace Bempp\n", "meta": {"hexsha": "7eb22cd2436003ed6ee90636a6b8822927e0b387", "size": 9502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/hmat_global_assembler.cpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/assembly/hmat_global_assembler.cpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/assembly/hmat_global_assembler.cpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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.4934497817, "max_line_length": 80, "alphanum_fraction": 0.7611029257, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.19265414291785643}}
{"text": "#ifndef EXTRACTION_HELPER_FUNCTIONS_HPP\n#define EXTRACTION_HELPER_FUNCTIONS_HPP\n\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/spirit/include/qi.hpp>\n\n#include <limits>\n#include <string>\n\n#include \"extractor/guidance/toolkit.hpp\"\n\nnamespace osrm\n{\nnamespace extractor\n{\n\nnamespace detail\n{\n\nnamespace qi = boost::spirit::qi;\n\ntemplate <typename Iterator> struct iso_8601_grammar : qi::grammar<Iterator, unsigned()>\n{\n    iso_8601_grammar() : iso_8601_grammar::base_type(root)\n\n    {\n        using qi::_1;\n        using qi::_a;\n        using qi::_b;\n        using qi::_c;\n        using qi::_pass;\n        using qi::_val;\n        using qi::eoi;\n        using qi::eps;\n        using qi::uint_;\n        using qi::char_;\n\n        hh = uint2_p[_pass = bind([](unsigned x) { return x < 24; }, _1), _val = _1];\n        mm = uint2_p[_pass = bind([](unsigned x) { return x < 60; }, _1), _val = _1];\n        ss = uint2_p[_pass = bind([](unsigned x) { return x < 60; }, _1), _val = _1];\n\n        osm_time = (uint_p[_a = _1] >> eoi)[_val = _a * 60] |\n                   (uint_p[_a = _1] >> ':' >> uint_p[_b = _1] >> eoi)[_val = _a * 3600 + _b * 60] |\n                   (uint_p[_a = _1] >> ':' >> uint_p[_b = _1] >> ':' >> uint_p[_c = _1] >>\n                    eoi)[_val = _a * 3600 + _b * 60 + _c];\n\n        alternative_time =\n            ('T' >> hh[_a = _1] >> mm[_b = _1] >> ss[_c = _1])[_val = _a * 3600 + _b * 60 + _c];\n\n        extended_time = ('T' >> hh[_a = _1] >> ':' >> mm[_b = _1] >> ':' >>\n                         ss[_c = _1])[_val = _a * 3600 + _b * 60 + _c];\n\n        standard_time =\n            ('T' >> -(uint_ >> char_(\"Hh\"))[_a = _1] >> -(uint_ >> char_(\"Mm\"))[_b = _1] >>\n             -(uint_ >> char_(\"Ss\"))[_c = _1])[_val = _a * 3600 + _b * 60 + _c];\n\n        standard_date = (uint_ >> char_(\"Dd\"))[_val = _1 * 86400];\n\n        standard_week = (uint_ >> char_(\"Ww\"))[_val = _1 * 604800];\n\n        iso_period =\n            osm_time[_val = _1] | ('P' >> standard_week >> eoi)[_val = _1] |\n            ('P' >> (alternative_time[_a = 0, _b = _1] | extended_time[_a = 0, _b = _1] |\n                     (eps[_a = 0, _b = 0] >> -standard_date[_a = _1] >> -standard_time[_b = _1])) >>\n             eoi)[_val = _a + _b];\n\n        root = iso_period;\n    }\n\n    qi::rule<Iterator, unsigned()> root;\n    qi::rule<Iterator, unsigned(), qi::locals<unsigned, unsigned>> iso_period;\n    qi::rule<Iterator, unsigned(), qi::locals<unsigned, unsigned, unsigned>> osm_time,\n        standard_time, alternative_time, extended_time;\n    qi::rule<Iterator, unsigned()> standard_date, standard_week;\n    qi::rule<Iterator, unsigned()> hh, mm, ss;\n\n    qi::uint_parser<unsigned, 10, 1, 2> uint_p;\n    qi::uint_parser<unsigned, 10, 2, 2> uint2_p;\n};\n}\n\ninline bool durationIsValid(const std::string &s)\n{\n    static detail::iso_8601_grammar<std::string::const_iterator> const iso_8601_grammar;\n\n    std::string::const_iterator iter = s.begin();\n    unsigned duration = 0;\n    boost::spirit::qi::parse(iter, s.end(), iso_8601_grammar, duration);\n\n    return !s.empty() && iter == s.end();\n}\n\ninline unsigned parseDuration(const std::string &s)\n{\n    static detail::iso_8601_grammar<std::string::const_iterator> const iso_8601_grammar;\n\n    std::string::const_iterator iter = s.begin();\n    unsigned duration = 0;\n    boost::spirit::qi::parse(iter, s.end(), iso_8601_grammar, duration);\n\n    return !s.empty() && iter == s.end() ? duration : std::numeric_limits<unsigned>::max();\n}\n\ninline std::string\ntrimLaneString(std::string lane_string, std::int32_t count_left, std::int32_t count_right)\n{\n    return extractor::guidance::trimLaneString(std::move(lane_string), count_left, count_right);\n}\n\ninline std::string applyAccessTokens(const std::string &lane_string,\n                                     const std::string &access_tokens)\n{\n    return extractor::guidance::applyAccessTokens(lane_string, access_tokens);\n}\n}\n}\n\n#endif // EXTRACTION_HELPER_FUNCTIONS_HPP\n", "meta": {"hexsha": "f3240dec96585b01d623606c9f4160d91f40f509", "size": 3960, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/extractor/extraction_helper_functions.hpp", "max_stars_repo_name": "AccessMap/accessmaplite-osrm-backend", "max_stars_repo_head_hexsha": "1a7586b7cc33c6ba7bff63c418df5b4822fd7f27", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-15T22:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-15T22:58:23.000Z", "max_issues_repo_path": "include/extractor/extraction_helper_functions.hpp", "max_issues_repo_name": "zummach/osrm", "max_issues_repo_head_hexsha": "7ab1b0893729064aa35b29d78cec605eb9831433", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-21T09:59:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-21T09:59:27.000Z", "max_forks_repo_path": "osrm-ch/include/extractor/extraction_helper_functions.hpp", "max_forks_repo_name": "dingchunda/osrm-backend", "max_forks_repo_head_hexsha": "8750749b83bd9193ca3481c630eefda689ecb73c", "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.2773109244, "max_line_length": 100, "alphanum_fraction": 0.5861111111, "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.19265414177889667}}
{"text": "#include <opencv2/imgproc/imgproc.hpp>\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <dlib/image_processing.h>\n#include <dlib/opencv.h>\n\n#include \"openbr/plugins/openbr_internal.h\"\n\n#include <QTemporaryFile>\n\nusing namespace std;\nusing namespace dlib;\n\nnamespace br\n{\n\n/*!\n * \\ingroup transforms\n * \\brief Wrapper to dlib's landmarker.\n * \\author Scott Klum \\cite sklum\n */\nclass DLibShapeResourceMaker : public ResourceMaker<shape_predictor>\n{\n\nprivate:\n    shape_predictor *make() const\n    {\n        shape_predictor *sp = new shape_predictor();\n        dlib::deserialize(qPrintable(Globals->sdkPath + \"/share/openbr/models/dlib/shape_predictor_68_face_landmarks.dat\")) >> *sp;\n        return sp;\n    }\n};\n\nclass DLandmarkerTransform : public UntrainableTransform\n{\n    Q_OBJECT\n\nprivate:\n    Resource<shape_predictor> shapeResource;\n\n    void init()\n    {\n        shapeResource.setResourceMaker(new DLibShapeResourceMaker());\n        shapeResource.release(shapeResource.acquire()); // Pre-load one instance of the model\n    }\n\n    QPointF averagePoints(const QList<QPointF> &points, int rangeBegin, int rangeEnd) const\n    {\n        QPointF point;\n        for (int i=rangeBegin; i<rangeEnd; i++)\n            point += points[i];\n        point /= (rangeEnd-rangeBegin);\n        return point;\n    }\n\n    void setFacePoints(Template &dst) const\n    {\n        const QList<QPointF> points = dst.file.points();\n        dst.file.set(\"RightEye\", averagePoints(points, 36, 42));\n        dst.file.set(\"LeftEye\" , averagePoints(points, 42, 48));\n        dst.file.set(\"Chin\", points[8]);\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = src;\n\n        shape_predictor *const sp = shapeResource.acquire();\n\n        cv::Mat cvImage = src.m();\n        if (cvImage.channels() == 3)\n            cv::cvtColor(cvImage, cvImage, CV_BGR2GRAY);\n\n        cv_image<unsigned char> cimg(cvImage);\n        array2d<unsigned char> image;\n        assign_image(image,cimg);\n\n        rectangle r;\n        if (src.file.rects().isEmpty()) { // If the image has no rects assume the whole image is a face\n            r = rectangle(0, 0, cvImage.cols, cvImage.rows);\n        } else { // Crop the image on the first rect\n            const QRectF rect = src.file.rects().first();\n            r = rectangle(rect.left(), rect.top(), rect.right(), rect.bottom());\n        }\n\n        full_object_detection shape = (*sp)(image, r);\n        QList<QPointF> points;\n        for (size_t i=0; i<shape.num_parts(); i++)\n            points.append(QPointF(shape.part(i)(0), shape.part(i)(1)));\n        dst.file.setPoints(points);\n        setFacePoints(dst);\n\n        shapeResource.release(sp);\n    }\n};\n\nBR_REGISTER(Transform, DLandmarkerTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Wrapper to dlib's trainable object detector.\n * \\author Scott Klum \\cite sklum\n */\nclass DObjectDetectorTransform : public Transform\n{\n    Q_OBJECT\n\n    Q_PROPERTY(int winSize READ get_winSize WRITE set_winSize RESET reset_winSize STORED true)\n    Q_PROPERTY(float C READ get_C WRITE set_C RESET reset_C STORED true)\n    Q_PROPERTY(float epsilon READ get_epsilon WRITE set_epsilon RESET reset_epsilon STORED true)\n    BR_PROPERTY(int, winSize, 80)\n    BR_PROPERTY(float, C, 1)\n    BR_PROPERTY(float, epsilon, .01)\n\nprivate:\n    typedef scan_fhog_pyramid<pyramid_down<6> > image_scanner_type;\n    mutable object_detector<image_scanner_type> detector;\n    mutable QMutex mutex;\n\n    void train(const TemplateList &data)\n    {\n        dlib::array<array2d<unsigned char> > samples;\n        std::vector<std::vector<rectangle> > boxes;\n\n        foreach (const Template &t, data) {\n            if (!t.file.rects().isEmpty()) {\n                cv_image<unsigned char> cimg(t.m());\n\n                array2d<unsigned char> image;\n                assign_image(image,cimg);\n\n                samples.push_back(image);\n\n                std::vector<rectangle> b;\n                foreach (const QRectF &r, t.file.rects())\n                    b.push_back(rectangle(r.left(),r.top(),r.right(),r.bottom()));\n\n                boxes.push_back(b);\n            }\n        }\n\n        if (samples.size() == 0)\n            qFatal(\"Training data has no bounding boxes.\");\n\n        image_scanner_type scanner;\n\n        scanner.set_detection_window_size(winSize, winSize);\n        structural_object_detection_trainer<image_scanner_type> trainer(scanner);\n        trainer.set_num_threads(max(1,QThread::idealThreadCount()));\n        trainer.set_c(C);\n        trainer.set_epsilon(epsilon);\n\n        if (Globals->verbose)\n            trainer.be_verbose();\n\n        detector = trainer.train(samples, boxes);\n    }\n\n    void project(const Template &src, Template &dst) const\n   {\n        dst = src;\n        cv_image<unsigned char> cimg(src.m());\n        array2d<unsigned char> image;\n        assign_image(image,cimg);\n\n        QMutexLocker locker(&mutex);\n        std::vector<rectangle> dets = detector(image);\n        locker.unlock();\n\n        for (size_t i=0; i<dets.size(); i++)\n            dst.file.appendRect(QRectF(QPointF(dets[i].left(),dets[i].top()),QPointF(dets[i].right(),dets[i].bottom())));\n    }\n\n    void store(QDataStream &stream) const\n    {\n        // Create local file\n        QTemporaryFile tempFile;\n        tempFile.open();\n        tempFile.close();\n\n        dlib::serialize(qPrintable(tempFile.fileName())) << detector;\n\n        // Copy local file contents to stream\n        tempFile.open();\n        QByteArray data = tempFile.readAll();\n        tempFile.close();\n        stream << data;\n    }\n\n    void load(QDataStream &stream)\n    {\n        // Copy local file contents from stream\n        QByteArray data;\n        stream >> data;\n\n        // Create local file\n        QTemporaryFile tempFile(QDir::tempPath()+\"/model\");\n        tempFile.open();\n        tempFile.write(data);\n        tempFile.close();\n\n        // Load MLP from local file\n        dlib::deserialize(qPrintable(tempFile.fileName())) >> detector;\n    }\n};\n\nBR_REGISTER(Transform, DObjectDetectorTransform)\n\n} // namespace br\n\n#include \"dlib.moc\"\n", "meta": {"hexsha": "6dbbb880102099b6ff38a9c5e7d1be954c49875a", "size": 6093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/classification/dlib.cpp", "max_stars_repo_name": "wittayaatt/openbr", "max_stars_repo_head_hexsha": "26cb128f740f46b7c18b346e2bcf2af7a8de29da", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1883.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:33:37.000Z", "max_issues_repo_path": "openbr/plugins/classification/dlib.cpp", "max_issues_repo_name": "wittayaatt/openbr", "max_issues_repo_head_hexsha": "26cb128f740f46b7c18b346e2bcf2af7a8de29da", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 272.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T09:53:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:04:33.000Z", "max_forks_repo_path": "openbr/plugins/classification/dlib.cpp", "max_forks_repo_name": "wittayaatt/openbr", "max_forks_repo_head_hexsha": "26cb128f740f46b7c18b346e2bcf2af7a8de29da", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 718.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T18:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T08:10:53.000Z", "avg_line_length": 28.8767772512, "max_line_length": 131, "alphanum_fraction": 0.6274413261, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.19265413797843947}}
{"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 - 2013   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_OPTIMIZE_FMS_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_OPTIMIZE_FMS_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/fms.hpp>\n#include <boost/simd/operator/functions/unary_minus.hpp>\n#include <boost/simd/include/functions/fnma.hpp>\n#include <boost/dispatch/dsl/category.hpp>\n#include <boost/dispatch/functor/preprocessor/call.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT         ( fms_ , tag::formal_, (D)(A0)(A1)(A2)\n                                   , ((node_<A0, boost::simd::tag::unary_minus_, mpl::long_<3> , D>))\n                                     (unspecified_<A1>)\n                                     (unspecified_<A2>)\n                                   )\n  {\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      fnma(boost::proto::child_c<0>(a0), a1, a2)\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT         ( fms_ , tag::formal_, (D)(A0)(A1)(A2)\n                                   , (unspecified_<A0>)\n                                     ((node_<A1, boost::simd::tag::unary_minus_, mpl::long_<3> , D>))\n                                     (unspecified_<A2>)\n                                   )\n  {\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      fnma(boost::proto::child_c<0>(a1), a0, a2)\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT         ( fms_ , tag::formal_, (D)(A0)(A1)(A2)\n                                   , ((node_<A0, boost::simd::tag::unary_minus_, mpl::long_<3> , D>))\n                                     ((node_<A1, boost::simd::tag::unary_minus_, mpl::long_<3> , D>))\n                                     (unspecified_<A2>)\n                                   )\n  {\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      fms(boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1), a2)\n    )\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "cb239c602e913b5da94fbd23d818c8b52ffaed0c", "size": 2474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/optimize/fms.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/optimize/fms.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/optimize/fms.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": 44.1785714286, "max_line_length": 101, "alphanum_fraction": 0.4983831851, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.35220178884745906, "lm_q1q2_score": 0.19256215516013497}}
{"text": "//   Copyright Maarten L. Hekkelman, Radboud University 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 \"M6Lib.h\"\n#include \"M6Log.h\"\n\n#include <limits>\n#include <numeric>\n#include <atomic>\n\n#include <boost/regex.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/iostreams/device/mapped_file.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/thread.hpp>\n\n#include <zeep/xml/writer.hpp>\n\n#include \"M6Blast.h\"\n#include \"M6Matrix.h\"\n#include \"M6Error.h\"\n#include \"M6Progress.h\"\n\nusing namespace std;\nusing namespace zeep;\n\nnamespace ba = boost::algorithm;\nnamespace fs = boost::filesystem;\nnamespace io = boost::iostreams;\n\n// --------------------------------------------------------------------\n\nnamespace M6Blast\n{\n\n// Code for amino acid sequences\ntypedef std::basic_string<uint8> sequence;\n\n// 24 real letters and 1 dummy (X is the dummy, B and Z are pseudo letters)\nconst char kResidues[] = \"ABCDEFGHIKLMNPQRSTVWYZXUO\";\nconst uint8 kResidueNrTable[] = {\n//  A   B   C   D   E   F   G   H   I   J   K   L   M   N   O   P   Q   R   S   T   U   V   W   X   Y   Z\n    0,  1,  2,  3,  4,  5,  6,  7,  8, 25,  9, 10, 11, 12, 24, 13, 14, 15, 16, 17, 23, 18, 19, 22, 20, 21\n};\n\ninline uint8 ResidueNr(char inAA)\n{\n    int result = 25;\n\n    inAA |= 040;  // to lower case\n    if (inAA >= 'a' and inAA <= 'z')\n        result = kResidueNrTable[inAA - 'a'];\n\n    return result;\n}\n\ninline bool is_gap(char aa)\n{\n    return aa == ' ' or aa == '.' or aa == '-';\n}\n\nsequence encode(const std::string& s);\nstd::string decode(const sequence& s);\n\nconst uint32\n    kAACount                = 22,    // 20 + B and Z\n    kResCount                = 25,    // includes X, U, O\n    kBits                    = 5,\n    kThreshold                = 11,\n    kUngappedDropOff        = 7,\n    kGappedDropOff            = 15,\n    kGappedDropOffFinal        = 25,\n    kGapTrigger                = 22,\n\n    kMaxSequenceLength        = numeric_limits<uint16>::max();\n\nconst uint8\n    kGapCode                = 25;\n\nconst int32\n    kHitWindow                = 40;\n\nconst double\n    kLn2                    = log(2.);\n\nconst int16\n    kSentinalScore = -9999;\n\nclass Matrix\n{\n  public:\n                    Matrix(const string& inName, int32 inGapOpen, int32 inGapExtend);\n\n    int8            operator()(char inAA1, char inAA2) const;\n    int8            operator()(uint8 inAA1, uint8 inAA2) const;\n\n    int32            OpenCost() const        { return mData.mGapOpen; }\n    int32            ExtendCost() const        { return mData.mGapExtend; }\n\n    double            GappedLambda() const    { return mData.mGappedStats.lambda; }\n    double            GappedKappa() const        { return mData.mGappedStats.kappa; }\n    double            GappedEntropy() const    { return mData.mGappedStats.entropy; }\n    double            GappedAlpha() const        { return mData.mGappedStats.alpha; }\n    double            GappedBeta() const        { return mData.mGappedStats.beta; }\n\n    double            UngappedLambda() const    { return mData.mUngappedStats.lambda; }\n    double            UngappedKappa() const    { return mData.mUngappedStats.kappa; }\n    double            UngappedEntropy() const    { return mData.mUngappedStats.entropy; }\n    double            UngappedAlpha() const    { return mData.mUngappedStats.alpha; }\n    double            UngappedBeta() const    { return mData.mUngappedStats.beta; }\n\n  private:\n    MatrixData        mData;\n};\n\nMatrix::Matrix(const string& inName, int32 inGapOpen, int32 inGapExtend)\n{\n    mData.mName = nullptr;\n    for (const MatrixData* data = kMatrixData; data->mName != nullptr; ++data)\n    {\n        if (ba::iequals(inName, data->mName) and\n            inGapOpen == data->mGapOpen and\n            inGapExtend == data->mGapExtend)\n        {\n            mData = *data;\n            break;\n        }\n    }\n\n    if (mData.mName == nullptr)\n        throw M6Exception(\"Unsupported matrix/gap combination (%s/%d/%d)\", inName.c_str(), inGapOpen, inGapExtend);\n}\n\ninline int8 Matrix::operator()(uint8 inAA1, uint8 inAA2) const\n{\n    int8 result;\n\n    if (inAA1 >= inAA2)\n        result = mData.mMatrix[(inAA1 * (inAA1 + 1)) / 2 + inAA2];\n    else\n        result = mData.mMatrix[(inAA2 * (inAA2 + 1)) / 2 + inAA1];\n\n    return result;\n}\n\ninline int8 Matrix::operator()(char inAA1, char inAA2) const\n{\n    return operator()(ResidueNr(inAA1), ResidueNr(inAA2));\n}\n\n// --------------------------------------------------------------------\n//    Simplified low complexity filter code, based on DUST/SEG. Dropped\n//    DNA code, we're protein only.\n\nnamespace filter\n{\n\n//const char kAlphabet[] = { 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y' };\n\nconst uint32 kAlphabetSize        = 20;\nconst double kLnAlphabetSize    = log(20.);\n\nconst uint8 kAlphabetIndex[] = {\n//  A   B   C   D   E   F   G   H   I  J=X  K   L   M   N  O=X  P   Q   R   S   T  U=X  V   W   X   Y   Z\n    0, 20,  1,  2,  3,  4,  5,  6,  7, 20,  8,  9, 10, 11, 20, 12, 13, 14, 15, 16, 20, 17, 18, 20, 19, 20\n};\n\nstruct Alphabet\n{\n    static int32    GetIndex(char inChar)\n                    {\n                        inChar |= 040;\n                        return (inChar >= 'a' and inChar <= 'y') ? kAlphabetIndex[inChar - 'a'] : 20;\n                    }\n\n    static bool        Contains(char inChar)                        { return GetIndex(inChar) < 20; }\n};\n\nclass Window\n{\n  public:\n            Window(const string& inSequence, int32 inStart, int32 inLength);\n\n    void    CalcEntropy();\n    bool    ShiftWindow();\n\n    double    GetEntropy() const            { return mEntropy; }\n    int32    GetBogus() const            { return mBogus; }\n\n    void    DecState(int32 inCount);\n    void    IncState(int32 inCount);\n\n    void    Trim(int32& ioEndL, int32& ioEndR, int32 inMaxTrim);\n\n  private:\n    const string&    mSequence;\n    int32            mComposition[kAlphabetSize];\n    int32            mState[kAlphabetSize + 1];\n    int32            mStart;\n    int32            mLength;\n    int32            mBogus;\n    double            mEntropy;\n};\n\nWindow::Window(const string& inSequence, int32 inStart, int32 inLength)\n    : mSequence(inSequence)\n    , mStart(inStart)\n    , mLength(inLength)\n    , mBogus(0)\n    , mEntropy(-2.0)\n{\n    fill(mComposition, mComposition + kAlphabetSize, 0);\n    fill(mState, mState + kAlphabetSize + 1, 0);\n\n    for (int32 i = mStart; i < mStart + mLength; ++i)\n    {\n        if (Alphabet::Contains(mSequence[i]))\n            ++mComposition[Alphabet::GetIndex(mSequence[i])];\n        else\n            ++mBogus;\n    }\n\n    int n = 0;\n    for (int32 i = 0; i < kAlphabetSize; ++i)\n    {\n        if (mComposition[i] > 0)\n        {\n            mState[n] = mComposition[i];\n            ++n;\n        }\n    }\n\n    sort(mState, mState + n, greater<int32>());\n}\n\nvoid Window::CalcEntropy()\n{\n    mEntropy = 0.0;\n\n    double total = 0.0;\n    for (uint32 i = 0; i < kAlphabetSize and mState[i] != 0; ++i)\n        total += mState[i];\n\n    if (total != 0.0)\n    {\n        for (uint32 i = 0; i < kAlphabetSize and mState[i]; ++i)\n        {\n            double t = mState[i] / total;\n            mEntropy += t * log(t);\n        }\n        mEntropy = fabs(mEntropy / log(0.5));\n    }\n}\n\nvoid Window::DecState(int32 inClass)\n{\n    for (uint32 ix = 0; ix < kAlphabetSize and mState[ix] != 0; ++ix)\n    {\n        if (mState[ix] == inClass and mState[ix + 1] < inClass)\n        {\n            --mState[ix];\n            break;\n        }\n    }\n}\n\nvoid Window::IncState(int32 inClass)\n{\n    for (uint32 ix = 0; ix < kAlphabetSize; ++ix)\n    {\n        if (mState[ix] == inClass)\n        {\n            ++mState[ix];\n            break;\n        }\n    }\n}\n\nbool Window::ShiftWindow()\n{\n    if (uint32(mStart + mLength) >= mSequence.length())\n        return false;\n\n    char ch = mSequence[mStart];\n    if (Alphabet::Contains(ch))\n    {\n        int32 ix = Alphabet::GetIndex(ch);\n        DecState(mComposition[ix]);\n        --mComposition[ix];\n    }\n    else\n        --mBogus;\n\n    ++mStart;\n\n    ch = mSequence[mStart + mLength - 1];\n    if (Alphabet::Contains(ch))\n    {\n        int32 ix = Alphabet::GetIndex(ch);\n        IncState(mComposition[ix]);\n        ++mComposition[ix];\n    }\n    else\n        ++mBogus;\n\n    if (mEntropy > -2.0)\n        CalcEntropy();\n\n    return true;\n}\n\ndouble lnfac(int32 inN)\n{\n    const double c[] = {\n         76.18009172947146,\n        -86.50532032941677,\n         24.01409824083091,\n        -1.231739572450155,\n         0.1208650973866179e-2,\n        -0.5395239384953e-5\n    };\n\n    static double sLnFacMap[100] = {};\n\n    double result;\n    if (inN >= 0 and inN < 100 and sLnFacMap[inN] != 0)\n        result = sLnFacMap[inN];\n    else\n    {\n        double x = inN + 1;\n        double t = x + 5.5;\n        t -= (x + 0.5) * log(t);\n        double ser = 1.000000000190015;\n        for (int i = 0; i <= 5; i++)\n        {\n            ++x;\n            ser += c[i] / x;\n        }\n\n        result = -t + log(2.5066282746310005 * ser / (inN + 1));\n        if (inN >= 0 and inN < 100)\n            sLnFacMap[inN] = result;\n    }\n\n    return result;\n}\n\ndouble lnperm(int32 inState[], int32 inTotal)\n{\n    double ans = lnfac(inTotal);\n    for (uint32 i = 0; i < kAlphabetSize and inState[i] != 0; ++i)\n        ans -= lnfac(inState[i]);\n    return ans;\n}\n\ndouble lnass(int32 inState[])\n{\n    double result = lnfac(kAlphabetSize);\n    if (kAlphabetSize == 0 or inState[0] == 0)\n        return result;\n\n    int total = kAlphabetSize;\n    int cl = 1;\n    int i = 1;\n    int sv_cl = inState[0];\n\n    while (inState[i] != 0)\n    {\n        if (inState[i] == sv_cl)\n            cl++;\n        else\n        {\n            total -= cl;\n            result -= lnfac(cl);\n            sv_cl = inState[i];\n            cl = 1;\n        }\n        i++;\n    }\n\n    result -= lnfac(cl);\n    total -= cl;\n    if (total > 0)\n        result -= lnfac(total);\n\n    return result;\n}\n\ndouble lnprob(int32 inState[], int32 inTotal)\n{\n    double ans1, ans2 = 0, totseq;\n\n    totseq = inTotal * kLnAlphabetSize;\n    ans1 = lnass(inState);\n    if (ans1 > -100000.0 and inState[0] != numeric_limits<int32>::min())\n        ans2 = lnperm(inState, inTotal);\n    else\n        throw M6Exception(\"Error in calculating lnass\");\n    return ans1 + ans2 - totseq;\n}\n\nvoid Window::Trim(int32& ioEndL, int32& ioEndR, int32 inMaxTrim)\n{\n    double minprob = 1.0;\n    int32 lEnd = 0;\n    int32 rEnd = mLength - 1;\n    int minLen = 1;\n    int maxTrim = inMaxTrim;\n    if (minLen < mLength - maxTrim)\n        minLen = mLength - maxTrim;\n\n    for (int32 len = mLength; len > minLen; --len)\n    {\n        Window w(mSequence, mStart, len);\n\n        int i = 0;\n        bool shift = true;\n        while (shift)\n        {\n            double prob = lnprob(&w.mState[0], len);\n            if (prob < minprob)\n            {\n                minprob = prob;\n                lEnd = i;\n                rEnd = len + i - 1;\n            }\n            shift = w.ShiftWindow();\n            ++i;\n        }\n    }\n\n    ioEndL += lEnd;\n    ioEndR -= mLength - rEnd - 1;\n}\n\nbool GetEntropy(const string& inSequence, int32 inWindow, int32 inMaxBogus, vector<double>& outEntropy)\n{\n    bool result = false;\n\n    int32 downset = (inWindow + 1) / 2 - 1;\n    int32 upset = inWindow - downset;\n\n    if (inWindow <= inSequence.length())\n    {\n        result = true;\n        outEntropy.clear();\n        outEntropy.insert(outEntropy.begin(), inSequence.length(), -1.0);\n\n        Window win(inSequence, 0, inWindow);\n        win.CalcEntropy();\n\n        int32 first = downset;\n        int32 last = static_cast<int32>(inSequence.length() - upset);\n        for (int32 i = first; i <= last; ++i)\n        {\n//            if (GetPunctuation() and win.HasDash())\n//            {\n//                win.ShiftWindow();\n//                continue;\n//            }\n            if (win.GetBogus() > inMaxBogus)\n                continue;\n\n            outEntropy[i] = win.GetEntropy();\n            win.ShiftWindow();\n        }\n    }\n\n    return result;\n}\n\nvoid GetMaskSegments(const string& inSequence, int32 inOffset, vector<pair<int32,int32> >& outSegments)\n{\n    double loCut, hiCut;\n    int32 window, maxbogus, maxtrim;\n\n    window = 12;\n    loCut = 2.2;\n    hiCut = 2.5;\n    maxtrim = 50;\n    maxbogus = 2;\n\n    int32 downset = (window + 1) / 2 - 1;\n    int32 upset = window - downset;\n\n    vector<double> e;\n    GetEntropy(inSequence, window, maxbogus, e);\n\n    int32 first = downset;\n    int32 last = static_cast<int32>(inSequence.length() - upset);\n    int32 lowlim = first;\n\n    for (int32 i = first; i <= last; ++i)\n    {\n        if (e[i] <= loCut and e[i] != -1.0)\n        {\n            int32 loi = i;\n            while (loi >= lowlim and e[loi] != -1.0 and e[loi] <= hiCut)\n                --loi;\n            ++loi;\n\n            int32 hii = i;\n            while (hii <= last and e[hii] != -1.0 and e[hii] <= hiCut)\n                ++hii;\n            --hii;\n\n            int32 leftend = loi - downset;\n            int32 rightend = hii + upset - 1;\n\n            string s(inSequence.substr(leftend, rightend - leftend + 1));\n            Window w(s, 0, rightend - leftend + 1);\n            w.Trim(leftend, rightend, maxtrim);\n\n            if (i + upset - 1 < leftend)\n            {\n                int32 lend = loi - downset;\n                int32 rend = leftend - 1;\n\n                string left(inSequence.substr(lend, rend - lend + 1));\n                GetMaskSegments(left, inOffset + lend, outSegments);\n            }\n\n            outSegments.push_back(\n                pair<int32,int32>(leftend + inOffset, rightend + inOffset + 1));\n            i = rightend + downset;\n            if (i > hii)\n                i = hii;\n            lowlim = i + 1;\n        }\n    }\n}\n\nstring SEG(const string& inSequence)\n{\n    string result = inSequence;\n\n    vector<pair<int32,int32> > segments;\n    GetMaskSegments(result, 0, segments);\n\n    for (uint32 i = 0; i < segments.size(); ++i)\n    {\n        for (int32 j = segments[i].first; j < segments[i].second; ++j)\n            result[j] = 'X';\n    }\n\n    return result;\n}\n\n}\n\n// --------------------------------------------------------------------\n\nnamespace ncbi\n{\n\n/**\n * Computes the adjustment to the lengths of the query and database sequences\n * that is used to compensate for edge effects when computing evalues.\n *\n * The length adjustment is an integer-valued approximation to the fixed\n * point of the function\n *\n *    f(ell) = beta +\n *               (alpha/lambda) * (log K + log((m - ell)*(n - N ell)))\n *\n * where m is the query length n is the length of the database and N is the\n * number of sequences in the database. The values beta, alpha, lambda and\n * K are statistical, Karlin-Altschul parameters.\n *\n * The value of the length adjustment computed by this routine, A,\n * will always be an integer smaller than the fixed point of\n * f(ell). Usually, it will be the largest such integer.  However, the\n * computed length adjustment, A, will also be so small that\n *\n *    K * (m - A) * (n - N * A) > min(m,n).\n *\n * Moreover, an iterative method is used to compute A, and under\n * unusual circumstances the iterative method may not converge.\n *\n * @param K      the statistical parameter K\n * @param logK   the natural logarithm of K\n * @param alpha_d_lambda    the ratio of the statistical parameters\n *                          alpha and lambda (for ungapped alignments, the\n *                          value 1/H should be used)\n * @param beta              the statistical parameter beta (for ungapped\n *                          alignments, beta == 0)\n * @param query_length      the length of the query sequence\n * @param db_length         the length of the database\n * @param db_num_seq        the number of sequences in the database\n * @param length_adjustment the computed value of the length adjustment [out]\n *\n * @return   0 if length_adjustment is known to be the largest integer less\n *           than the fixed point of f(ell); 1 otherwise.\n */\n\nint32 BlastComputeLengthAdjustment(\n    double K, double alpha_d_lambda, double beta,\n    int32 query_length, int64 db_length, int32 db_num_seqs,\n    int32& length_adjustment)\n{\n    double logK = log(K);\n\n    int32 i;                     /* iteration index */\n    const int32 maxits = 20;     /* maximum allowed iterations */\n    double m = query_length, n = static_cast<double>(db_length), N = db_num_seqs;\n\n    double ell;            /* A float value of the length adjustment */\n    double ss;             /* effective size of the search space */\n    double ell_min = 0, ell_max;   /* At each iteration i,\n                                         * ell_min <= ell <= ell_max. */\n    bool converged    = false;       /* True if the iteration converged */\n    double ell_next = 0;   /* Value the variable ell takes at iteration\n                                 * i + 1 */\n    /* Choose ell_max to be the largest nonnegative value that satisfies\n     *\n     *    K * (m - ell) * (n - N * ell) > max(m,n)\n     *\n     * Use quadratic formula: 2 c /( - b + sqrt( b*b - 4 * a * c )) */\n    { /* scope of a, mb, and c, the coefficients in the quadratic formula\n       * (the variable mb is -b) */\n        double a  = N;\n        double mb = m * N + n;\n        double c  = n * m - std::max(m, n) / K;\n\n        if(c < 0) {\n            length_adjustment = 0;\n            return 1;\n        } else {\n            ell_max = 2 * c / (mb + sqrt(mb * mb - 4 * a * c));\n        }\n    } /* end scope of a, mb and c */\n\n    for(i = 1; i <= maxits; i++) {      /* for all iteration indices */\n        double ell_bar;    /* proposed next value of ell */\n        ell      = ell_next;\n        ss       = (m - ell) * (n - N * ell);\n        ell_bar  = alpha_d_lambda * (logK + log(ss)) + beta;\n        if(ell_bar >= ell) { /* ell is no bigger than the true fixed point */\n            ell_min = ell;\n            if(ell_bar - ell_min <= 1.0) {\n                converged = true;\n                break;\n            }\n            if(ell_min == ell_max) { /* There are no more points to check */\n                break;\n            }\n        } else { /* else ell is greater than the true fixed point */\n            ell_max = ell;\n        }\n        if(ell_min <= ell_bar && ell_bar <= ell_max) {\n          /* ell_bar is in range. Accept it */\n            ell_next = ell_bar;\n        } else { /* else ell_bar is not in range. Reject it */\n            ell_next = (i == 1) ? ell_max : (ell_min + ell_max) / 2;\n        }\n    } /* end for all iteration indices */\n    if(converged) { /* the iteration converged */\n        /* If ell_fixed is the (unknown) true fixed point, then we\n         * wish to set length_adjustment to floor(ell_fixed).  We\n         * assume that floor(ell_min) = floor(ell_fixed) */\n        length_adjustment = (int32) ell_min;\n        /* But verify that ceil(ell_min) != floor(ell_fixed) */\n        ell = ceil(ell_min);\n        if( ell <= ell_max ) {\n          ss = (m - ell) * (n - N * ell);\n          if(alpha_d_lambda * (logK + log(ss)) + beta >= ell) {\n            /* ceil(ell_min) == floor(ell_fixed) */\n            length_adjustment = (int32) ell;\n          }\n        }\n    } else { /* else the iteration did not converge. */\n        /* Use the best value seen so far */\n        length_adjustment = (int32) ell_min;\n    }\n\n    return converged ? 0 : 1;\n}\n\nint32 BlastComputeLengthAdjustment(const Matrix& inMatrix, int32 query_length, int64 db_length, int32 db_num_seqs)\n{\n    int32 lengthAdjustment;\n    (void)BlastComputeLengthAdjustment(inMatrix.GappedKappa(), inMatrix.GappedAlpha() / inMatrix.GappedLambda(),\n        inMatrix.GappedBeta(), query_length, db_length, db_num_seqs, lengthAdjustment);\n    return lengthAdjustment;\n}\n\n} // namespace ncbi\n\n// --------------------------------------------------------------------\n\ntemplate<int WORDSIZE>\nstruct Word\n{\n    static const uint32 kMaxWordIndex, kMaxIndex;\n\n                    Word()\n                    {\n                        for (uint32 i = 0; i <= WORDSIZE; ++i)\n                            aa[i] = 0;\n                    }\n\n                    Word(const uint8* inSequence)\n                    {\n                        for (uint32 i = 0; i < WORDSIZE; ++i)\n                            aa[i] = inSequence[i];\n                        aa[WORDSIZE] = 0;\n                    }\n\n    uint8&            operator[](uint32 ix)    { return aa[ix]; }\n    const uint8*    c_str() const            { return aa; }\n    size_t            length() const            { return WORDSIZE; }\n\n    class PermutationIterator\n    {\n      public:\n                        PermutationIterator(Word inWord, const Matrix& inMatrix, int32 inThreshold)\n                            : mWord(inWord), mIndex(0), mMatrix(inMatrix), mThreshold(inThreshold) {}\n\n        bool            Next(uint32& outIndex);\n\n      private:\n        Word            mWord;\n        uint32            mIndex;\n        const Matrix&    mMatrix;\n        int32            mThreshold;\n    };\n\n    uint8            aa[WORDSIZE + 1];\n};\n\ntemplate<> const uint32 Word<2>::kMaxWordIndex = 0x0003FF;\ntemplate<> const uint32 Word<2>::kMaxIndex = kAACount * kAACount;\ntemplate<> const uint32 Word<3>::kMaxWordIndex = 0x007FFF;\ntemplate<> const uint32 Word<3>::kMaxIndex = kAACount * kAACount * kAACount;\ntemplate<> const uint32 Word<4>::kMaxWordIndex = 0x0FFFFF;\ntemplate<> const uint32 Word<4>::kMaxIndex = kAACount * kAACount * kAACount * kAACount;\n\ntemplate<int WORDSIZE>\nbool Word<WORDSIZE>::PermutationIterator::Next(uint32& outIndex)\n{\n    bool result = false;\n    Word w;\n\n    while (mIndex < kMaxIndex)\n    {\n        uint32 ix = mIndex;\n        ++mIndex;\n\n        int32 score = 0;\n        outIndex = 0;\n\n        for (uint32 i = 0; i < WORDSIZE; ++i)\n        {\n            uint32 resNr = ix % kAACount;\n            w[i] = resNr;\n            ix /= kAACount;\n            score += mMatrix(mWord[i], w[i]);\n            outIndex = outIndex << kBits | resNr;\n        }\n\n        if (score >= mThreshold)\n        {\n            result = true;\n            break;\n        }\n    }\n\n    return result;\n}\n\ntemplate<int WORDSIZE>\nclass WordHitIterator\n{\n    static const uint32 kMask;\n\n    struct Entry\n    {\n        uint16                    mCount;\n        uint16                    mDataOffset;\n    };\n\n  public:\n\n    typedef Word<WORDSIZE>                        IWord;\n    typedef typename IWord::PermutationIterator    WordPermutationIterator;\n\n    struct WordHitIteratorStaticData\n    {\n        vector<Entry>        mLookup;\n        vector<uint16>        mOffsets;\n    };\n                            WordHitIterator(const WordHitIteratorStaticData& inStaticData)\n                                : mLookup(inStaticData.mLookup), mOffsets(inStaticData.mOffsets) {}\n\n    static void                Init(const sequence& inQuery, const Matrix& inMatrix,\n                                uint32 inThreshhold, WordHitIteratorStaticData& outStaticData);\n\n    void                    Reset(const sequence& inTarget);\n    bool                    Next(uint16& outQueryOffset, uint16& outTargetOffset);\n    uint32                    Index() const        { return mIndex; }\n\n  private:\n\n    const uint8*            mTargetCurrent;\n    const uint8*            mTargetEnd;\n    uint16                    mTargetOffset;\n    const vector<Entry>&    mLookup;\n    const vector<uint16>&    mOffsets;\n    uint32                    mIndex;\n    const uint16*            mOffset;\n    uint16                    mCount;\n};\n\ntemplate<> const uint32 WordHitIterator<2>::kMask = 0x0001F;\ntemplate<> const uint32 WordHitIterator<3>::kMask = 0x003FF;\ntemplate<> const uint32 WordHitIterator<4>::kMask = 0x07FFF;\n\ntemplate<int WORDSIZE>\nvoid WordHitIterator<WORDSIZE>::Init(const sequence& inQuery,\n    const Matrix& inMatrix, uint32 inThreshhold, WordHitIteratorStaticData& outStaticData)\n{\n    uint64 N = IWord::kMaxWordIndex;\n    size_t M = 0;\n\n    vector<vector<uint16>> test(N);\n\n    for (uint16 i = 0; i < inQuery.length() - WORDSIZE + 1; ++i)\n    {\n        IWord w(inQuery.c_str() + i);\n\n        WordPermutationIterator p(w, inMatrix, inThreshhold);\n        uint32 ix;\n\n        while (p.Next(ix))\n        {\n            test[ix].push_back(i);\n            ++M;\n        }\n    }\n\n    outStaticData.mLookup = vector<Entry>(N);\n    outStaticData.mOffsets = vector<uint16>(M);\n\n    uint16* data = &outStaticData.mOffsets[0];\n\n    for (uint32 i = 0; i < N; ++i)\n    {\n        outStaticData.mLookup[i].mCount = static_cast<uint16>(test[i].size());\n        outStaticData.mLookup[i].mDataOffset = static_cast<uint16>(data - &outStaticData.mOffsets[0]);\n\n        for (uint32 j = 0; j < outStaticData.mLookup[i].mCount; ++j)\n            *data++ = test[i][j];\n    }\n\n    assert(data == &outStaticData.mOffsets[0] + M);\n#if DEBUG\n    outStaticData.mOffsets.push_back(0);\n#endif\n}\n\ntemplate<int WORDSIZE>\nvoid WordHitIterator<WORDSIZE>::Reset(const sequence& inTarget)\n{\n    mTargetCurrent = inTarget.c_str();\n    mTargetEnd = mTargetCurrent + inTarget.length();\n    mTargetOffset = 0;\n    mIndex = 0;\n\n    for (uint32 i = 0; i < WORDSIZE and mTargetCurrent != mTargetEnd; ++i)\n        mIndex = mIndex << kBits | *mTargetCurrent++;\n\n    Entry current = mLookup[mIndex];\n    mCount = current.mCount;\n    mOffset = &mOffsets[current.mDataOffset];\n}\n\ntemplate<int WORDSIZE>\nbool WordHitIterator<WORDSIZE>::Next(uint16& outQueryOffset, uint16& outTargetOffset)\n{\n    bool result = false;\n\n    for (;;)\n    {\n        if (mCount-- > 0)\n        {\n            outQueryOffset = *mOffset++;\n            outTargetOffset = mTargetOffset;\n            result = true;\n            break;\n        }\n\n        if (mTargetCurrent == mTargetEnd)\n            break;\n\n        mIndex = ((mIndex & kMask) << kBits) | *mTargetCurrent++;\n        ++mTargetOffset;\n\n        Entry current = mLookup[mIndex];\n        mCount = current.mCount;\n        mOffset = &mOffsets[current.mDataOffset];\n    }\n\n    return result;\n}\n\n// --------------------------------------------------------------------\n\nstruct DiagonalStartTable\n{\n            DiagonalStartTable() : mTable(nullptr), mTableLength(0) {}\n            ~DiagonalStartTable() { delete[] mTable; }\n\n    void    Reset(int32 inQueryLength, int32 inTargetLength)\n            {\n                mTargetLength = inTargetLength;\n\n                int32 n = inQueryLength + inTargetLength + 1;\n                if (mTable == nullptr or n >= mTableLength)\n                {\n                    uint32 k = ((n / 10240) + 1) * 10240;\n                    int32* t = new int32[k];\n                    delete[] mTable;\n                    mTable = t;\n                    mTableLength = k;\n                }\n\n                fill(mTable, mTable + n, -inTargetLength);\n            }\n\n    int32&    operator()(uint16 inQueryOffset, uint16 inTargetOffset)\n                { return mTable[mTargetLength - inTargetOffset + inQueryOffset]; }\n\n  private:\n                            DiagonalStartTable(const DiagonalStartTable&);\n    DiagonalStartTable&    operator=(const DiagonalStartTable&);\n\n    int32*    mTable;\n    int32    mTableLength, mTargetLength;\n};\n\n// --------------------------------------------------------------------\n\nstruct DPData\n{\n                DPData(size_t inDimX, size_t inDimY) : mDimX(inDimX), mDimY(inDimY)\n                {\n                    mDPDataLength = (inDimX + 1) * (inDimY + 1);\n                    mDPData = new int16[mDPDataLength];\n                }\n                ~DPData()                                            { delete[] mDPData; }\n\n    int16        operator()(uint32 inI, uint32 inJ) const            { return mDPData[inI * mDimY + inJ]; }\n    int16&        operator()(uint32 inI, uint32 inJ)                    { return mDPData[inI * mDimY + inJ]; }\n\n    int16*        mDPData;\n    size_t        mDPDataLength;\n    size_t        mDimX;\n    size_t        mDimY;\n};\n\nstruct DiscardTraceBack\n{\n    int16        operator()(int16 inB, int16 inIx, int16 inIy, uint32 /*inI*/, uint32 /*inJ*/) const\n                    { return max(max(inB, inIx), inIy); }\n    void        Set(uint32 inI, uint32 inJ, int16 inD) {}\n};\n\nstruct RecordTraceBack\n{\n                RecordTraceBack(DPData& inTraceBack) : mTraceBack(inTraceBack) { }\n\n    int16        operator()(int16 inB, int16 inIx, int16 inIy, uint32 inI, uint32 inJ)\n                {\n                    int16 result;\n\n                    if (inB >= inIx and inB >= inIy)\n                    {\n                        result = inB;\n                        mTraceBack(inI, inJ) = 0;\n                    }\n                    else if (inIx >= inB and inIx >= inIy)\n                    {\n                        result = inIx;\n                        mTraceBack(inI, inJ) = 1;\n                    }\n                    else\n                    {\n                        result = inIy;\n                        mTraceBack(inI, inJ) = -1;\n                    }\n\n                    return result;\n                }\n\n    void        Set(uint32 inI, uint32 inJ, int16 inD)            { mTraceBack(inI, inJ) = inD; }\n\n    DPData&    mTraceBack;\n};\n\n// --------------------------------------------------------------------\n\ninline void ReadEntry(const char*& inFasta, const char* inEnd, sequence& outTarget)\n{\n    assert(inFasta == inEnd or *inFasta == '>');\n\n    while (inFasta != inEnd and *inFasta++ != '\\n')\n        ;\n\n    outTarget.clear();\n\n    bool bol = false;\n    while (inFasta != inEnd)\n    {\n        char ch = *inFasta++;\n\n        if (ch == '\\n')\n            bol = true;\n        else if (ch == '>' and bol)\n        {\n            --inFasta;\n            break;\n        }\n        else\n        {\n            uint8 rn = ResidueNr(ch);\n            if (rn < kResCount)\n                outTarget += rn;\n            bol = false;\n        }\n    }\n}\n\n// --------------------------------------------------------------------\n\nstruct HspData\n{\n    uint32        mScore;\n    uint32        mQueryStart, mQueryEnd, mTargetStart, mTargetEnd, mTargetLength;\n    sequence    mAlignedQuery, mAlignedTarget;\n    double        mBitScore;\n    double        mExpect;\n    bool        mGapped;\n\n    bool        operator>(const HspData& inHsp) const                { return mScore > inHsp.mScore; }\n    void        CalculateExpect(int64 inSearchSpace, double inLambda, double inLogKappa);\n    bool        Overlaps(const HspData& inOther) const\n                {\n                    return\n                        mQueryEnd >= inOther.mQueryStart and mQueryStart <= inOther.mQueryEnd and\n                        mTargetEnd >= inOther.mTargetStart and mTargetStart <= inOther.mTargetEnd;\n                }\n};\n\nvoid HspData::CalculateExpect(int64 inSearchSpace, double inLambda, double inLogKappa)\n{\n    mBitScore = floor((inLambda * mScore - inLogKappa) / kLn2);\n    mExpect = inSearchSpace / pow(2., mBitScore);\n}\n\n// --------------------------------------------------------------------\n\nstruct HitData;\ntypedef shared_ptr<HitData> HitPtr;\n\nstruct HitData\n{\n                    HitData(const char* inEntry, const sequence& inTarget);\n\n    void            AddHsp(const HspData& inHsp);\n    void            Cleanup(int64 inSearchSpace, double inLambda, double inLogKappa, double inExpect);\n\n    string            mDefLine;\n    sequence        mTarget;\n    vector<HspData>    mHsps;\n};\n\nHitData::HitData(const char* inEntry, const sequence& inTarget)\n    : mTarget(inTarget)\n{\n    const char* b = inEntry;\n    const char* e = strchr(inEntry, '\\n');\n    mDefLine.assign(b, e);\n}\n\nvoid HitData::AddHsp(const HspData& inHsp)\n{\n    bool found = false;\n\n    for (auto& hsp : mHsps)\n    {\n        if (inHsp.Overlaps(hsp))\n        {\n            if (hsp.mScore < inHsp.mScore)\n                hsp = inHsp;\n            found = true;\n            break;\n        }\n    }\n\n    if (not found)\n        mHsps.push_back(inHsp);\n}\n\nvoid HitData::Cleanup(int64 inSearchSpace, double inLambda, double inLogKappa, double inExpect)\n{\n    sort(mHsps.begin(), mHsps.end(), greater<HspData>());\n\n    vector<HspData>::iterator a = mHsps.begin();\n    while (a != mHsps.end() and a + 1 != mHsps.end())\n    {\n        vector<HspData>::iterator b = a + 1;\n        while (b != mHsps.end())\n        {\n            if (a->Overlaps(*b))\n                b = mHsps.erase(b);\n            else\n                ++b;\n        }\n        ++a;\n    }\n\n    for_each(mHsps.begin(), mHsps.end(), [=](HspData& hsp) {\n        hsp.CalculateExpect(inSearchSpace, inLambda, inLogKappa);\n    });\n\n    sort(mHsps.begin(), mHsps.end(), greater<HspData>());\n\n    mHsps.erase(\n        remove_if(mHsps.begin(), mHsps.end(), [=](const HspData& hsp) -> bool {\n            return hsp.mExpect > inExpect;\n        }),\n        mHsps.end());\n}\n\n// --------------------------------------------------------------------\n\ntemplate<int WORDSIZE>\nclass BlastQuery\n{\n  public:\n                    BlastQuery(const string& inQuery, bool inFilter, double inExpect,\n                        const string& inMatrix, bool inGapped, int32 inGapOpen, int32 inGapExtend,\n                        uint32 inReportLimit);\n                    ~BlastQuery();\n\n    void            Search(const vector<fs::path>& inDatabanks, M6Progress& inProgress, uint32 inNrOfThreads);\n    void            Report(Result& outResult);\n    void            WriteAsFasta(ostream& inStream);\n\n  private:\n\n    void            SearchPart(const char* inFasta, size_t inLength, M6Progress& inProgress,\n                        uint32& outDbCount, int64& outDbLength, vector<HitPtr>& outHits) const;\n\n    int32            Extend(int32& ioQueryStart, const sequence& inTarget, int32& ioTargetStart, int32& ioDistance) const;\n    template<class Iterator1, class Iterator2, class TraceBack>\n    int32            AlignGapped(Iterator1 inQueryBegin, Iterator1 inQueryEnd,\n                        Iterator2 inTargetBegin, Iterator2 inTargetEnd,\n                        TraceBack& inTraceBack, int32 inDropOff, uint32& outBestX, uint32& outBestY) const;\n\n    int32            AlignGappedFirst(const sequence& inTarget, HspData& ioHsp) const;\n    int32            AlignGappedSecond(const sequence& inTarget, HspData& ioHsp) const;\n\n    void            AddHit(HitPtr inHit, vector<HitPtr>& inHitList) const;\n\n    typedef WordHitIterator<WORDSIZE>                                IWordHitIterator;\n    typedef typename IWordHitIterator::WordHitIteratorStaticData    StaticData;\n\n    string            mUnfiltered;\n    sequence        mQuery;\n    Matrix        mMatrix;\n    double            mExpect, mCutOff;\n    bool            mGapped;\n    int32            mS1, mS2, mXu, mXg, mXgFinal;\n    uint32            mReportLimit;\n\n    uint32            mDbCount;\n    int64            mDbLength, mSearchSpace;\n\n    vector<HitPtr>    mHits;\n\n    StaticData    mWordHitData;\n};\n\ntemplate<int WORDSIZE>\nBlastQuery<WORDSIZE>::BlastQuery(const string& inQuery, bool inFilter, double inExpect,\n        const string& inMatrix, bool inGapped, int32 inGapOpen, int32 inGapExtend, uint32 inReportLimit)\n    : mUnfiltered(inQuery), mMatrix(inMatrix, inGapOpen, inGapExtend)\n    , mExpect(inExpect), mGapped(inGapped), mReportLimit(inReportLimit)\n    , mDbCount(0), mDbLength(0), mSearchSpace(0)\n{\n    if (mQuery.length() >= kMaxSequenceLength)\n        throw M6Exception(\"Query length exceeds maximum\");\n\n    mUnfiltered.erase(remove_if(mUnfiltered.begin(), mUnfiltered.end(), [](char aa) -> bool {\n        return ResidueNr(aa) >= kResCount;\n    }), mUnfiltered.end());\n\n    string query(mUnfiltered);\n    if (inFilter)\n        query = filter::SEG(query);\n\n    transform(query.begin(), query.end(), back_inserter(mQuery), [](char aa) -> uint8 {\n        return ResidueNr(aa);\n    });\n\n    mXu =        static_cast<int32>(ceil((kLn2 * kUngappedDropOff) / mMatrix.UngappedLambda()));\n    mXg =        static_cast<int32>((kLn2 * kGappedDropOff) / mMatrix.GappedLambda());\n    mXgFinal =    static_cast<int32>((kLn2 * kGappedDropOffFinal) / mMatrix.GappedLambda());\n    mS1 =        static_cast<int32>((kLn2 * kGapTrigger + log(mMatrix.UngappedKappa())) / mMatrix.UngappedLambda());\n\n    // we're not using S2\n    mS2 =        static_cast<int32>((kLn2 * kGapTrigger + log(mMatrix.GappedKappa())) / mMatrix.GappedLambda());;    // yeah, that sucks... perhaps\n\n    IWordHitIterator::Init(mQuery, mMatrix, kThreshold, mWordHitData);\n}\n\ntemplate<int WORDSIZE>\nBlastQuery<WORDSIZE>::~BlastQuery()\n{\n}\n\ntemplate<int WORDSIZE>\nvoid BlastQuery<WORDSIZE>::Search(const vector<fs::path>& inDatabanks, M6Progress& inProgress, uint32 inNrOfThreads)\n{\n    exception_ptr ex;\n\n    for (const fs::path& p : inDatabanks)\n    {\n        io::mapped_file file(p.string().c_str(), io::mapped_file::readonly);\n        if (not file.is_open())\n            throw M6Exception(\"FastA file %s not open\", p.string().c_str());\n\n        const char* data = file.const_data();\n        size_t length = file.size();\n\n        if (inNrOfThreads <= 1)\n            SearchPart(data, length, inProgress, mDbCount, mDbLength, mHits);\n        else\n        {\n            boost::thread_group t;\n            boost::mutex m;\n\n            size_t k = length / inNrOfThreads;\n            const char *prevEnd = data;\n            for (uint32 i = 0; i < inNrOfThreads and length > 0; ++i)\n            {\n                size_t n = k;\n                if (n > length)\n                    n = length;\n                const char* end = data + n;\n\n                while (end <= prevEnd)\n                {\n                    end++;\n                    n++;\n                }\n                prevEnd = end;\n\n                while (n < length and *end != '>')\n                {\n                    ++end;\n                    ++n;\n                }\n\n                t.create_thread([data, n, &m, &inProgress, &ex, this]() {\n                    try\n                    {\n                        uint32 dbCount = 0;\n                        int64 dbLength = 0;\n                        vector<HitPtr> hits;\n\n                        this->SearchPart(data, n, inProgress, dbCount, dbLength, hits);\n\n                        boost::mutex::scoped_lock lock(m);\n                        mDbCount += dbCount;\n                        mDbLength += dbLength;\n                        this->mHits.insert(mHits.end(), hits.begin(), hits.end());\n                    }\n                    catch (...)\n                    {\n                        ex = current_exception();\n                    }\n                });\n\n                data += n;\n                length -= n;\n            }\n\n            try\n            {\n                t.join_all();\n            }\n            catch (boost::thread_interrupted&)\n            {\n                t.interrupt_all();\n                t.join_all();\n                throw;\n            }\n        }\n    }\n\n    if (not (ex == exception_ptr()))\n        rethrow_exception(ex);\n\n    int32 lengthAdjustment = ncbi::BlastComputeLengthAdjustment(mMatrix, static_cast<uint32>(mQuery.length()), mDbLength, mDbCount);\n\n    int64 effectiveQueryLength = mQuery.length() - lengthAdjustment;\n    int64 effectiveDbLength = mDbLength - mDbCount * lengthAdjustment;\n\n    mSearchSpace = effectiveDbLength * effectiveQueryLength;\n\n    if (not mHits.empty())\n    {\n        boost::thread_group t;\n        atomic<int> ix(-1);\n        //boost::detail::atomic_count ix(-1);\n\n        for (uint32 i = 0; i < inNrOfThreads; ++i)\n        {\n            t.create_thread([this, &ix, &ex]() {\n                try\n                {\n                    double lambda = mMatrix.GappedLambda(), logK = log(mMatrix.GappedKappa());\n\n                    for (;;)\n                    {\n                        uint32 next = ++ix;\n                        if (next >= this->mHits.size())\n                            break;\n\n                        HitPtr hit = this->mHits[next];\n\n                        for (HspData& hsp : hit->mHsps)\n                            hsp.mScore = this->AlignGappedSecond(hit->mTarget, hsp);\n\n                        hit->Cleanup(this->mSearchSpace, lambda, logK, this->mExpect);\n                    }\n                }\n                catch (...)\n                {\n                    ex = current_exception();\n                }\n            });\n        }\n\n        try\n        {\n            t.join_all();\n        }\n        catch (boost::thread_interrupted&)\n        {\n            t.interrupt_all();\n            t.join_all();\n            throw;\n        }\n\n        if (not (ex == exception_ptr()))\n            rethrow_exception(ex);\n    }\n\n    mHits.erase(\n        remove_if(mHits.begin(), mHits.end(), [](const HitPtr hit) -> bool { return hit->mHsps.empty(); }),\n        mHits.end());\n\n    sort(mHits.begin(), mHits.end(), [](const HitPtr a, const HitPtr b) -> bool {\n        return a->mHsps.front().mScore > b->mHsps.front().mScore or\n            (a->mHsps.front().mScore == b->mHsps.front().mScore and a->mDefLine < b->mDefLine);\n    });\n\n    if (mHits.size() > mReportLimit and mReportLimit > 0)\n        mHits.erase(mHits.begin() + mReportLimit, mHits.end());\n}\n\ntemplate<int WORDSIZE>\nvoid BlastQuery<WORDSIZE>::Report(Result& outResult)\n{\n    outResult.mStats.mDbCount = mDbCount;\n    outResult.mStats.mDbLength = mDbLength;\n    outResult.mStats.mEffectiveSpace = mSearchSpace;\n    outResult.mStats.mKappa = mMatrix.GappedKappa();\n    outResult.mStats.mLambda = mMatrix.GappedLambda();\n    outResult.mStats.mEntropy = mMatrix.GappedEntropy();\n\n    boost::regex\n        kDefLineParser(\"^>gnl\\\\|([^| ]*)\\\\|([^| ]*)(?:\\\\|([^| ]*))?(?: (.*))\\n?\");\n\n    for (HitPtr hit : mHits)\n    {\n        boost::smatch m;\n        if (not boost::regex_match(hit->mDefLine, m, kDefLineParser, boost::match_not_dot_newline))\n            throw M6Exception(\"Invalid defline: %s\", hit->mDefLine.c_str());\n\n        Hit h;\n        h.mHitNr = static_cast<uint32>(outResult.mHits.size() + 1);\n        h.mDefLine = hit->mDefLine.substr(1);\n//        h.mLength = static_cast<uint32>(hit->mTarget.length());\n        h.mSequence.reserve(hit->mTarget.length());\n        transform(hit->mTarget.begin(), hit->mTarget.end(),\n            back_inserter(h.mSequence), [](uint8 r) -> char { return kResidues[r]; });\n\n        h.mDb = m[1];\n        h.mID = m[2];\n        h.mChain = m[3];\n        h.mTitle = m[4];\n\n        for (HspData& hsp : hit->mHsps)\n        {\n            Hsp p = { static_cast<uint32>(h.mHsps.size() + 1), hsp.mQueryStart + 1, hsp.mQueryEnd,\n                hsp.mTargetStart + 1, hsp.mTargetEnd, hsp.mTargetLength,\n                hsp.mScore, hsp.mBitScore, hsp.mExpect };\n\n            p.mQueryAlignment.reserve(hsp.mAlignedQuery.length());\n            p.mTargetAlignment.reserve(hsp.mAlignedTarget.length());\n\n            string::const_iterator qu = mUnfiltered.begin() + hsp.mQueryStart;\n            for (sequence::const_iterator qf = hsp.mAlignedQuery.begin(), t = hsp.mAlignedTarget.begin();\n                qf != hsp.mAlignedQuery.end(); ++qf, ++t, ++qu)\n            {\n                char r = *qf >= kGapCode ? '-' : kResidues[*qf];\n                if (r == 'X')\n                    r = tolower(*qu);\n                assert((r >= 'a' and r <= 'z') or (r >= 'A' and r <= 'Z') or r == '-');\n                p.mQueryAlignment += r;\n                p.mTargetAlignment += *t >= kGapCode ? '-' : kResidues[*t];\n\n                if (*t >= kGapCode or r == '-')\n                {\n                    if (r == '-')\n                        --qu;\n                    p.mGaps += 1;\n                    p.mMidLine += ' ';\n                }\n                else if (*qu == kResidues[*t])\n                {\n                    p.mMidLine += *qu;\n                    ++p.mIdentity;\n                    ++p.mPositive;\n                }\n                else if (mMatrix(ResidueNr(*qu), *t) > 0)\n                {\n                    ++p.mPositive;\n                    p.mMidLine += '+';\n                }\n                else\n                    p.mMidLine += ' ';\n            }\n\n            h.mHsps.push_back(p);\n        }\n        outResult.mHits.push_back(h);\n    }\n}\n\ntemplate<int WORDSIZE>\nvoid BlastQuery<WORDSIZE>::WriteAsFasta(ostream& inStream)\n{\n    for (HitPtr hit : mHits)\n    {\n        string seq;\n        for (uint8 r : hit->mTarget)\n        {\n            if (seq.length() % 73 == 72)\n                seq += '\\n';\n            seq += kResidues[r];\n        }\n\n        inStream << hit->mDefLine << endl\n                 << seq << endl;\n    }\n}\n\ntemplate<int WORDSIZE>\nvoid BlastQuery<WORDSIZE>::SearchPart(const char* inFasta, size_t inLength, M6Progress& inProgress,\n    uint32& outDbCount, int64& outDbLength, vector<HitPtr>& outHits) const\n{\n    const char* end = inFasta + inLength;\n    int32 queryLength = static_cast<int32>(mQuery.length());\n\n    IWordHitIterator iter(mWordHitData);\n    DiagonalStartTable diagonals;\n    sequence target;\n    target.reserve(kMaxSequenceLength);\n\n    int64 hitsToDb = 0, extensions = 0, successfulExtensions = 0;\n    HitPtr hit;\n\n    LOG(INFO, \"running SearchPart with inLength=%d\", inLength);\n\n    while (inFasta != end)\n    {\n        // make it possible to interrupt a search\n        boost::this_thread::interruption_point();\n\n        if (hit)\n        {\n            AddHit(hit, outHits);\n            hit.reset();\n        }\n\n        const char* entry = inFasta;\n        ReadEntry(inFasta, end, target);\n\n        inProgress.Consumed(inFasta - entry);\n\n        if (target.empty() or target.length() > kMaxSequenceLength)\n            continue;\n\n        outDbCount += 1;\n        outDbLength += target.length();\n\n        iter.Reset(target);\n        diagonals.Reset(queryLength, static_cast<int32>(target.length()));\n\n        uint16 queryOffset, targetOffset;\n        while (iter.Next(queryOffset, targetOffset))\n        {\n            ++hitsToDb;\n\n            int32& ds = diagonals(queryOffset, targetOffset);\n            int32 distance = queryOffset - ds;\n\n            if (distance >= kHitWindow)\n                ds = queryOffset;\n            else if (distance > WORDSIZE)\n            {\n                int32 queryStart = ds;\n                int32 targetStart = targetOffset - distance;\n                int32 alignmentDistance = distance + WORDSIZE;\n\n                if (targetStart < 0 or queryStart < 0)\n                    continue;\n\n                ++extensions;\n\n                int32 score = Extend(queryStart, target, targetStart, alignmentDistance);\n\n                if (score >= mS1)\n                {\n                    ++successfulExtensions;\n\n                    HspData hsp;\n\n                    // extension results, to be updated later\n                    hsp.mQueryStart = queryStart;\n                    hsp.mQueryEnd = queryStart + alignmentDistance;\n                    hsp.mTargetStart = targetStart;\n                    hsp.mTargetEnd = targetStart + alignmentDistance;\n                    hsp.mTargetLength = static_cast<uint32>(target.length());\n\n                    if (not hit)\n                        hit.reset(new HitData(entry, target));\n\n                    if (mGapped)\n                        hsp.mScore = AlignGappedFirst(target, hsp);\n                    else\n                    {\n                        hsp.mScore = score;\n                        hsp.mAlignedQuery = mQuery.substr(hsp.mQueryStart, hsp.mQueryEnd - hsp.mQueryStart);\n                        hsp.mAlignedTarget = hit->mTarget.substr(hsp.mTargetStart, hsp.mTargetEnd - hsp.mTargetStart);\n                    }\n\n                    hit->AddHsp(hsp);\n                }\n\n                ds = queryStart + alignmentDistance;\n            }\n        }\n    }\n\n    if (hit)\n        AddHit(hit, outHits);\n\n    LOG(INFO, \"finished SearchPart with inLength=%d\", inLength);\n}\n\ntemplate<int WORDSIZE>\nint32 BlastQuery<WORDSIZE>::Extend(int32& ioQueryStart, const sequence& inTarget, int32& ioTargetStart, int32& ioDistance) const\n{\n    // use iterators\n    sequence::const_iterator ai = mQuery.begin() + ioQueryStart;\n    sequence::const_iterator bi = inTarget.begin() + ioTargetStart;\n\n    int32 score = 0;\n    for (int i = 0; i < ioDistance; ++i, ++ai, ++bi)\n        score += mMatrix(*ai, *bi);\n\n    // record start and stop positions for optimal score\n    sequence::const_iterator qe = ai;\n\n    for (int32 test = score, n = static_cast<int32>(min(mQuery.end() - ai, inTarget.end() - bi));\n         test >= score - mXu and n > 0;\n         --n, ++ai, ++bi)\n    {\n        test += mMatrix(*ai, *bi);\n\n        if (test > score)\n        {\n            score = test;\n            qe = ai;\n        }\n    }\n\n    ai = mQuery.begin() + ioQueryStart;\n    bi = inTarget.begin() + ioTargetStart;\n    sequence::const_iterator qs = ai + 1;\n\n    for (int32 test = score, n = min(ioQueryStart, ioTargetStart);\n         test >= score - mXu and n > 0;\n         --n)\n    {\n        test += mMatrix(*--ai, *--bi);\n\n        if (test > score)\n        {\n            score = test;\n            qs = ai;\n        }\n    }\n\n    int32 delta = static_cast<int32>(ioQueryStart - (qs - mQuery.begin()));\n    ioQueryStart -= delta;\n    ioTargetStart -= delta;\n    ioDistance = static_cast<int32>(qe - qs);\n\n    return score;\n}\n\ntemplate<int WORDSIZE>\ntemplate<class Iterator1, class Iterator2, class TraceBack>\nint32 BlastQuery<WORDSIZE>::AlignGapped(\n    Iterator1 inQueryBegin, Iterator1 inQueryEnd, Iterator2 inTargetBegin, Iterator2 inTargetEnd,\n    TraceBack& inTraceBack, int32 inDropOff, uint32& outBestX, uint32& outBestY) const\n{\n    const Matrix& s = mMatrix;    // for readability\n    TraceBack& tb_max = inTraceBack;\n    int32 d = s.OpenCost();\n    int32 e = s.ExtendCost();\n\n    uint32 dimX = static_cast<uint32>(inQueryEnd - inQueryBegin);\n    uint32 dimY = static_cast<uint32>(inTargetEnd - inTargetBegin);\n\n    DPData B(dimX, dimY);\n    DPData Ix(dimX, dimY);\n    DPData Iy(dimX, dimY);\n\n    int32 bestScore = 0;\n    uint32 bestX;\n    uint32 bestY;\n    uint32 colStart = 1;\n    uint32 lastColStart = 1;\n    uint32 colEnd = dimY;\n\n    // first column\n    uint32 i = 1, j = 1;\n    Iterator1 x = inQueryBegin;\n    Iterator2 y = inTargetBegin;\n\n    // first cell\n    int32 Ix1 = kSentinalScore, Iy1 = kSentinalScore;\n\n    // (1)\n    int32 M = s(*x, *y);\n\n    // (2)\n    (void)tb_max(M, kSentinalScore, kSentinalScore, 1, 1);\n    bestScore = B(1, 1) = M;\n    bestX = bestY = 1;\n\n    // (3)\n    Ix(1, 1) = M - d;\n\n    // (4)\n    Iy(1, 1) = M - d;\n\n    // remaining cells in the first column\n    y = inTargetBegin + 1;\n    Ix1 = kSentinalScore;\n    M = kSentinalScore;\n\n    for (j = 2; y != inTargetEnd; ++j, ++y)\n    {\n        Iy1 = Iy(i, j - 1);\n\n        // (2)\n        int32 Bij = B(i, j) = Iy1;\n        tb_max.Set(i, j, -1);\n\n        // (3)\n        Ix(i, j) = kSentinalScore;\n\n        // (4)\n        Iy(i, j) = Iy1 - e;\n\n        if (Bij < bestScore - inDropOff)\n        {\n            colEnd = j;\n            break;\n        }\n    }\n\n    // remaining columns\n    ++x;\n    for (i = 2; x != inQueryEnd and colEnd >= colStart; ++i, ++x)\n    {\n        y = inTargetBegin + colStart - 1;\n        uint32 newColStart = colStart;\n        bool beforeFirstRow = true;\n\n        for (j = colStart; y != inTargetEnd; ++j, ++y)\n        {\n            Ix1 = kSentinalScore;\n            Iy1 = kSentinalScore;\n\n            if (j < colEnd)\n                Ix1 = Ix(i - 1, j);\n\n            if (j > colStart)\n                Iy1 = Iy(i, j - 1);\n\n            // (1)\n            if (j <= lastColStart or j > colEnd)\n                M = kSentinalScore;\n            else\n                M = B(i - 1, j - 1) + s(*x, *y);\n\n            // cut off the max value\n            if (M > numeric_limits<int16>::max())\n                M = numeric_limits<int16>::max();\n\n            // (2)\n            int32 Bij = B(i, j) = tb_max(M, Ix1, Iy1, i, j);\n\n            // (3)\n            Ix(i, j) = max(M - d, Ix1 - e);\n\n            // (4)\n            Iy(i, j) = max(M - d, Iy1 - e);\n\n            if (Bij > bestScore)\n            {\n                bestScore = Bij;\n                bestX = i;\n                bestY = j;\n                beforeFirstRow = false;\n            }\n            else if (Bij < bestScore - inDropOff)\n            {\n                if (beforeFirstRow)\n                {\n                    newColStart = j;\n                    if (newColStart > colEnd)\n                        break;\n                }\n                else if (j > bestY + 1)\n                {\n                    colEnd = j;\n                    break;\n                }\n            }\n            else\n            {\n                beforeFirstRow = false;\n                if (j > colEnd)\n                    colEnd = j;\n            }\n        }\n\n        lastColStart = colStart;\n        colStart = newColStart;\n    }\n\n    outBestY = bestY;\n    outBestX = bestX;\n\n    return bestScore;\n}\n\ntemplate<int WORDSIZE>\nint32 BlastQuery<WORDSIZE>::AlignGappedFirst(const sequence& inTarget, HspData& ioHsp) const\n{\n    int32 score;\n\n    uint32 x, y;\n    uint32 targetSeed = (ioHsp.mTargetStart + ioHsp.mTargetEnd) / 2;\n    uint32 querySeed = (ioHsp.mQueryStart + ioHsp.mQueryEnd) / 2;\n\n    DiscardTraceBack tb;\n\n    score = AlignGapped(\n        mQuery.begin() + querySeed + 1, mQuery.end(),\n        inTarget.begin() + targetSeed + 1, inTarget.end(),\n        tb, mXg, x, y);\n\n    score += AlignGapped(\n        mQuery.rbegin() + (mQuery.length() - querySeed), mQuery.rend(),\n        inTarget.rbegin() + (inTarget.length() - targetSeed), inTarget.rend(),\n        tb, mXg, x, y);\n\n    score += mMatrix(mQuery[querySeed], inTarget[targetSeed]);\n\n    return score;\n}\n\ntemplate<int WORDSIZE>\nint32 BlastQuery<WORDSIZE>::AlignGappedSecond(const sequence& inTarget, HspData& ioHsp) const\n{\n    uint32 x, y;\n    int32 score = 0;\n\n    ioHsp.mGapped = false;\n\n    sequence alignedQuery;\n    sequence alignedTarget;\n\n    uint32 targetSeed = (ioHsp.mTargetStart + ioHsp.mTargetEnd) / 2;\n    uint32 querySeed = (ioHsp.mQueryStart + ioHsp.mQueryEnd) / 2;\n\n    // start with the part before the seed\n    DPData d1(querySeed + 1, targetSeed + 1);\n    RecordTraceBack tbb(d1);\n\n    score = AlignGapped(\n        mQuery.rbegin() + (mQuery.length() - querySeed), mQuery.rend(),\n        inTarget.rbegin() + (inTarget.length() - targetSeed), inTarget.rend(),\n        tbb, mXgFinal, x, y);\n    ioHsp.mQueryStart = querySeed - x;\n    ioHsp.mTargetStart = targetSeed - y;\n\n    sequence::const_iterator qi = mQuery.begin() + querySeed - x, qis = qi;\n    sequence::const_iterator si = inTarget.begin() + targetSeed - y, sis = si;\n\n    uint32 qLen = 1;\n    uint32 sLen = 1;\n\n    while (x >= 1 and y >= 1)\n    {\n        if (x >= 1 and y >= 1 and d1(x, y) == 0)\n        {\n            alignedQuery += *qi++;\n            alignedTarget += *si++;\n            --x;\n            --y;\n        }\n        else if (y >= 1 and d1(x, y) < 0)\n        {\n            alignedQuery += kGapCode;\n            alignedTarget += *si++;\n            --y;\n            ioHsp.mGapped = true;\n        }\n        else // if (x >= 1 and d1(x, y) > 0)\n        {\n            alignedQuery += *qi++;\n            alignedTarget += kGapCode;\n            --x;\n            ioHsp.mGapped = true;\n        }\n    }\n\n    qLen += static_cast<uint32>(qi - qis);\n    sLen += static_cast<uint32>(si - sis);\n\n    // the seed itself\n    alignedQuery += mQuery[querySeed];\n    alignedTarget += inTarget[targetSeed];\n    score += mMatrix(mQuery[querySeed], inTarget[targetSeed]);\n\n    // and the part after the seed\n    DPData d2(mQuery.length() - querySeed, inTarget.length() - targetSeed);\n    RecordTraceBack tba(d2);\n\n    score += AlignGapped(\n        mQuery.begin() + querySeed + 1, mQuery.end(),\n        inTarget.begin() + targetSeed + 1, inTarget.end(),\n        tba, mXgFinal, x, y);\n\n    sequence::const_reverse_iterator qri = mQuery.rbegin() + (mQuery.length() - querySeed) - 1 - x, qris = qri;\n    sequence::const_reverse_iterator sri = inTarget.rbegin() + (inTarget.length() - targetSeed) - 1 - y, sris = sri;\n\n    sequence q, s;\n\n    while (x >= 1 and y >= 1)\n    {\n        if (x >= 1 and y >= 1 and d2(x, y) == 0)\n        {\n            q += *qri++;\n            s += *sri++;\n            --x;\n            --y;\n        }\n        else if (y >= 1 and d2(x, y) < 0)\n        {\n            q += kGapCode;\n            s += *sri++;\n            --y;\n            ioHsp.mGapped = true;\n        }\n        else // if (x >= 1 and d2(x, y) > 0)\n        {\n            q += *qri++;\n            s += kGapCode;\n            --x;\n            ioHsp.mGapped = true;\n        }\n    }\n\n    reverse(q.begin(), q.end());\n    reverse(s.begin(), s.end());\n\n    alignedQuery += q;\n    alignedTarget += s;\n\n    qLen += static_cast<uint32>(qri - qris);\n    sLen += static_cast<uint32>(sri - sris);\n\n    ioHsp.mAlignedQuery.assign(alignedQuery.begin(), alignedQuery.end());\n    ioHsp.mAlignedTarget.assign(alignedTarget.begin(), alignedTarget.end());\n    ioHsp.mQueryEnd = ioHsp.mQueryStart + qLen;\n    ioHsp.mTargetEnd = ioHsp.mTargetStart + sLen;\n\n    return score;\n}\n\ntemplate<int WORDSIZE>\nvoid BlastQuery<WORDSIZE>::AddHit(HitPtr inHit, vector<HitPtr>& inHitList) const\n{\n    sort(inHit->mHsps.begin(), inHit->mHsps.end(), greater<HspData>());\n\n    inHitList.push_back(inHit);\n\n    auto cmp = [](const HitPtr a, const HitPtr b) -> bool {\n        return a->mHsps.front().mScore > b->mHsps.front().mScore;\n    };\n\n    push_heap(inHitList.begin(), inHitList.end(), cmp);\n    if (inHitList.size() > mReportLimit and mReportLimit > 0)\n    {\n        pop_heap(inHitList.begin(), inHitList.end(), cmp);\n        inHitList.erase(inHitList.end() - 1);\n    }\n}\n\n// --------------------------------------------------------------------\n\nResult* Search(const vector<fs::path>& inDatabanks,\n    const string& inQuery, const string& inProgram,\n    const string& inMatrix, uint32 inWordSize, double inExpect,\n    bool inFilter, bool inGapped, int32 inGapOpen, int32 inGapExtend,\n    uint32 inReportLimit, uint32 inThreads)\n{\n    if (inProgram != \"blastp\")\n        throw M6Exception(\"Unsupported program %s\", inProgram.c_str());\n\n    for (const fs::path& db : inDatabanks)\n    {\n        if (not fs::exists(db))\n            throw M6Exception(\"Databank not found (%s)\", db.string().c_str());\n    }\n\n    if (inGapped)\n    {\n        if (inGapOpen == -1) inGapOpen = 11;\n        if (inGapExtend == -1) inGapExtend = 1;\n    }\n\n    if (inWordSize == 0) inWordSize = 3;\n\n    if (inQuery.length() < inWordSize)\n        throw M6Exception(\"query length is less than wordsize\");\n\n    string query, queryID, queryDef;\n    string::const_iterator i = inQuery.begin();\n\n    if (inQuery[0] == '>' and not isspace(inQuery[1]))\n    {\n        ++i;\n\n        do\n            queryID += *i;\n        while (i != inQuery.end() and not isspace(*++i));\n\n        while (i != inQuery.end() and *i != '\\r' and *i != '\\n')\n            queryDef += *i++;\n    }\n\n    while (i != inQuery.end())\n    {\n        if (isspace(*i))\n        {\n            ++i;\n            continue;\n        }\n\n        if (*i == '>')\n            break;\n\n        uint8 nr = ResidueNr(*i);\n        if (nr >= 25)\n            THROW(((boost::format(\"Query contains invalid characters: \\'%c\\'\")\n                            % *i).str().c_str()));\n\n        query += *i++;\n    }\n\n    if (query.length() < inWordSize)\n        THROW((\"Query length should be at least wordsize\"));\n\n    int64 totalLength = accumulate(inDatabanks.begin(), inDatabanks.end(), 0LL,\n        [](int64 l, const fs::path& p) -> int64 { return l + fs::file_size(p); });\n\n    M6Progress progress(\"blast\", totalLength, \"blast\");\n\n    unique_ptr<Result> result(new Result);\n\n    result->mParams.mProgram = inProgram;\n    for (const fs::path& db : inDatabanks)\n    {\n        if (not result->mDb.empty())\n            result->mDb += ',';\n        result->mDb += db.string();\n    }\n    result->mParams.mExpect = inExpect;\n    result->mQueryID = queryID;\n    result->mQueryDef = queryDef;\n    result->mQueryLength = static_cast<uint32>(query.length());\n    result->mParams.mMatrix = inMatrix;\n    result->mParams.mGapped = inGapped;\n    result->mParams.mGapOpen = inGapOpen;\n    result->mParams.mGapExtend = inGapExtend;\n    result->mParams.mFilter = inFilter;\n\n    if (inThreads < 1)\n        inThreads = boost::thread::hardware_concurrency();\n\n    switch (inWordSize)\n    {\n        case 2:\n        {\n            BlastQuery<2> q(query, inFilter, inExpect, inMatrix, inGapped, inGapOpen, inGapExtend, inReportLimit);\n            q.Search(inDatabanks, progress, inThreads);\n            q.Report(*result);\n            break;\n        }\n\n        case 3:\n        {\n            BlastQuery<3> q(query, inFilter, inExpect, inMatrix, inGapped, inGapOpen, inGapExtend, inReportLimit);\n            q.Search(inDatabanks, progress, inThreads);\n            q.Report(*result);\n            break;\n        }\n\n        case 4:\n        {\n            BlastQuery<4> q(query, inFilter, inExpect, inMatrix, inGapped, inGapOpen, inGapExtend, inReportLimit);\n            q.Search(inDatabanks, progress, inThreads);\n            q.Report(*result);\n            break;\n        }\n\n        default:\n            throw M6Exception(\"Unsupported word size %d\", inWordSize);\n    }\n\n    return result.release();\n}\n\n// --------------------------------------------------------------------\n\nvoid operator&(xml::writer& w, const Hsp& inHsp)\n{\n    w.start_element(\"Hsp\");\n    w.element(\"Hsp_num\", to_string(inHsp.mHspNr));\n    w.element(\"Hsp_bit-score\", to_string(inHsp.mBitScore));\n    w.element(\"Hsp_score\", to_string(inHsp.mScore));\n    w.element(\"Hsp_evalue\", to_string(inHsp.mExpect));\n    w.element(\"Hsp_query-from\", to_string(inHsp.mQueryStart));\n    w.element(\"Hsp_query-to\", to_string(inHsp.mQueryEnd));\n    w.element(\"Hsp_hit-from\", to_string(inHsp.mTargetStart));\n    w.element(\"Hsp_hit-to\", to_string(inHsp.mTargetEnd));\n    w.element(\"Hsp_identity\", to_string(inHsp.mIdentity));\n    w.element(\"Hsp_positive\", to_string(inHsp.mPositive));\n    w.element(\"Hsp_align-len\", to_string(inHsp.mQueryAlignment.length()));\n    w.element(\"Hsp_qseq\", inHsp.mQueryAlignment);\n    w.element(\"Hsp_hseq\", inHsp.mTargetAlignment);\n    w.element(\"Hsp_midline\", inHsp.mMidLine);\n    w.end_element();\n}\n\nvoid operator&(xml::writer& w, const Hit& inHit)\n{\n    w.start_element(\"Hit\");\n    w.element(\"Hit_num\", to_string(inHit.mHitNr));\n    if (inHit.mChain.empty())\n        w.element(\"Hit_id\", inHit.mID);\n    else\n        w.element(\"Hit_id\", inHit.mID + ':' + inHit.mChain);\n    if (not inHit.mDefLine.empty())\n        w.element(\"Hit_def\", inHit.mDefLine);\n    //if (not inHit.mAccession.empty())\n    //    w.element(\"Hit_accession\", inHit.mAccession);\n    w.element(\"Hit_len\", to_string(inHit.mSequence.length()));\n    w.start_element(\"Hit_hsps\");\n    for_each(inHit.mHsps.begin(), inHit.mHsps.end(), [&](const Hsp& hsp) {\n        w & hsp;\n    });\n    w.end_element();\n    w.end_element();\n}\n\nvoid Result::WriteAsNCBIBlastXML(ostream& os)\n{\n    xml::writer w(os, true);\n    w.doctype(\"BlastOutput\", \"-//NCBI//NCBI BlastOutput/EN\", \"http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd\");\n    w.start_element(\"BlastOutput\");\n    w.element(\"BlastOutput_program\", mParams.mProgram);\n    w.element(\"BlastOutput_db\", mDb);\n    w.element(\"BlastOutput_query-ID\", mQueryID);\n    w.element(\"BlastOutput_query-def\", mQueryDef);\n    w.element(\"BlastOutput_query-len\", to_string(mQueryLength));\n\n    w.start_element(\"BlastOutput_param\");\n    w.start_element(\"Parameters\");\n    w.element(\"Parameters_matrix\", mParams.mMatrix);\n    w.element(\"Parameters_expect\", to_string(mParams.mExpect));\n    if (mParams.mGapped)\n    {\n        w.element(\"Parameters_gap-open\", to_string(mParams.mGapOpen));\n        w.element(\"Parameters_gap-extend\", to_string(mParams.mGapExtend));\n    }\n    w.element(\"Parameters_filter\", mParams.mFilter ? \"T\" : \"F\");\n    w.end_element();\n    w.end_element();\n\n    w.start_element(\"BlastOutput_iterations\");\n    w.start_element(\"Iteration\");\n    w.element(\"Iteration_iter-num\", \"1\");\n    w.element(\"Iteration_query-ID\", mQueryID);\n    if (not mQueryDef.empty())\n        w.element(\"Iteration_query-def\", mQueryDef);\n    w.element(\"Iteration_query-len\", to_string(mQueryLength));\n    w.start_element(\"Iteration_hits\");\n    for_each(mHits.begin(), mHits.end(), [&](const Hit& hit) {\n        w & hit;\n    });\n    w.end_element();    // Iteration_hits\n    w.start_element(\"Iteration_stat\");\n    w.start_element(\"Statistics\");\n    w.element(\"Statistics_db-num\", to_string(mStats.mDbCount));\n    w.element(\"Statistics_db-len\", to_string(mStats.mDbLength));\n    w.element(\"Statistics_eff-space\", to_string(mStats.mEffectiveSpace));\n    w.element(\"Statistics_kappa\", to_string(mStats.mKappa));\n    w.element(\"Statistics_lambda\", to_string(mStats.mLambda));\n    w.element(\"Statistics_entropy\", to_string(mStats.mEntropy));\n    w.end_element();    // Statistics\n    w.end_element();    // Iteration_stat\n    w.end_element();    // Iteration\n    w.end_element();    // BlastOutput_iterations\n    w.end_element();    // BlastOutput\n}\n\n}\n", "meta": {"hexsha": "9134a8dfeac030ef3fb5c93ab5547d418f9b4788", "size": 64924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/M6Blast.cpp", "max_stars_repo_name": "mhekkel/mrs", "max_stars_repo_head_hexsha": "934ebfdbd6decc8e1471a6459afc3ec66572a323", "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": "src/M6Blast.cpp", "max_issues_repo_name": "mhekkel/mrs", "max_issues_repo_head_hexsha": "934ebfdbd6decc8e1471a6459afc3ec66572a323", "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/M6Blast.cpp", "max_forks_repo_name": "mhekkel/mrs", "max_forks_repo_head_hexsha": "934ebfdbd6decc8e1471a6459afc3ec66572a323", "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.9603137979, "max_line_length": 147, "alphanum_fraction": 0.532946214, "num_tokens": 17392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19256215144255093}}
{"text": "// Copyright 2018, Intel Corporation\n\n#include \"tile/codegen/thread_inner.h\"\n\n#include <algorithm>\n\n#include <boost/format.hpp>\n\n#include \"base/util/throw.h\"\n#include \"tile/codegen/tile.h\"\n#include \"tile/math/util.h\"\n#include \"tile/stripe/stripe.h\"\n\nnamespace vertexai {\nnamespace tile {\nnamespace codegen {\n\nusing namespace stripe;  // NOLINT\nusing math::NearestPo2;\nusing math::RoundUp;\n\nvoid DoThreadInnerPass(const AliasMap& scope, Block* block, const proto::ThreadInnerPass& options) {\n  if (block->ref_outs(true).size() != 1) {\n    if (block->ref_outs(true).size() == 0) {\n      // We may remove the output refinements in the contracts during optimizations,\n      // so here is not definitely wrong.\n      return;\n    }\n    throw std::runtime_error(\"Thread inner pass only works with a single output\");\n  }\n  const Refinement* out_ref = block->ref_outs(true)[0];\n  const auto& idxs = block->idxs;\n  Affine flat = out_ref->FlatAccess();\n  std::vector<size_t> sorted_idxs;\n  // Pull across indexes that are part of the output\n  for (size_t i = 0; i < idxs.size(); i++) {\n    // TODO: Rollup\n    if (flat.get(idxs[i].name) != 0) {\n      sorted_idxs.push_back(i);\n    }\n  }\n  IVLOG(1, \"Output indexes: \" << sorted_idxs);\n  // Sort indexes by is_out, power-of-twoness, then size\n  auto sort_func = [&](size_t i, size_t j) {\n    bool out_i = flat.get(idxs[i].name) == 0;\n    bool out_j = flat.get(idxs[j].name) == 0;\n    if (out_i != out_j) {\n      return out_j;\n    }\n    double ratio_i = static_cast<double>(idxs[i].range) / NearestPo2(idxs[i].range);\n    double ratio_j = static_cast<double>(idxs[j].range) / NearestPo2(idxs[j].range);\n    if (ratio_i != ratio_j) {\n      return ratio_i > ratio_j;\n    }\n    return idxs[i].range > idxs[j].range;\n  };\n  TileShape tile(block->idxs.size(), 1);\n  std::sort(sorted_idxs.begin(), sorted_idxs.end(), sort_func);\n  IVLOG(1, \"Sorted indexes: \" << sorted_idxs);\n  size_t cur = 0;\n  size_t threads = options.threads();\n  while (threads > 1 && cur < sorted_idxs.size()) {\n    size_t ci = sorted_idxs[cur];\n    size_t split = std::min(size_t(threads), size_t(NearestPo2(idxs[ci].range)));\n    tile[ci] = split;\n    threads /= split;\n    cur++;\n  }\n  for (size_t i = 0; i < tile.size(); i++) {\n    tile[i] = RoundUp(block->idxs[i].range, tile[i]);\n  }\n  ApplyTile(block, tile, false, false, true);\n  block->add_tags(FromProto(options.outer_set()));\n  block->SubBlock(0)->add_tags(FromProto(options.inner_set()));\n}\n\n// Localize starting from root for things that match reqs\nvoid ThreadInnerPass::Apply(CompilerState* state) const {\n  auto reqs = stripe::FromProto(options_.reqs());\n  RunOnBlocks(state->entry(), reqs, [this](const AliasMap& map, stripe::Block* block) {  //\n    DoThreadInnerPass(map, block, options_);\n  });\n}\n\nnamespace {\n[[gnu::unused]] char reg = []() -> char {\n  CompilePassFactory<ThreadInnerPass, proto::ThreadInnerPass>::Register();\n  return 0;\n}();\n}  // namespace\n}  // namespace codegen\n}  // namespace tile\n}  // namespace vertexai\n", "meta": {"hexsha": "0f74d09ae59bcbad973a111c1bb1a4af2e72c8ce", "size": 3000, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tile/codegen/thread_inner.cc", "max_stars_repo_name": "DaniDeniz/plaidml", "max_stars_repo_head_hexsha": "7e686a2123f4dd9941030d4b08a3b90f9ae324d2", "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": "tile/codegen/thread_inner.cc", "max_issues_repo_name": "DaniDeniz/plaidml", "max_issues_repo_head_hexsha": "7e686a2123f4dd9941030d4b08a3b90f9ae324d2", "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": "tile/codegen/thread_inner.cc", "max_forks_repo_name": "DaniDeniz/plaidml", "max_forks_repo_head_hexsha": "7e686a2123f4dd9941030d4b08a3b90f9ae324d2", "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.914893617, "max_line_length": 100, "alphanum_fraction": 0.6596666667, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.192562147724967}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n#include <cctbx/xray/scatterer.h>\n#include <cctbx/adptbx.h>\n#include <cctbx/uctbx.h>\n\n#include <boost/python/class.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/str.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_arg.hpp>\n#include <scitbx/array_family/boost_python/shared_wrapper.h>\n#include <scitbx/array_family/boost_python/selections_wrapper.h>\n#include <iotbx/pdb/hierarchy_atoms.h>\n#include <boost/format.hpp>\n\nnamespace iotbx { namespace pdb { namespace hierarchy { namespace atoms {\n\nnamespace {\n\n  boost::python::dict\n  build_dict(\n    af::const_ref<atom> const& atoms,\n    bool strip_names,\n    bool upper_names,\n    bool convert_stars_to_primes,\n    bool throw_runtime_error_if_duplicate_keys)\n  {\n    namespace bp = boost::python;\n    bp::dict result;\n    bp::object none;\n    for(unsigned i=0;i<atoms.size();i++) {\n      str4 name = atoms[i].data->name;\n      if (strip_names) name = name.strip();\n      if (upper_names) name.upper_in_place();\n      if (convert_stars_to_primes) name.replace_in_place('*', '\\'');\n      bp::str key = name.elems;\n      bp::object prev_atom = result.get(key);\n      if (prev_atom.ptr() == none.ptr()) {\n        result[key] = atoms[i];\n      }\n      else if (throw_runtime_error_if_duplicate_keys) {\n        throw std::runtime_error((boost::format(\n          \"Duplicate keys in build_dict(\"\n          \"strip_names=%s, upper_names=%s, convert_stars_to_primes=%s):\\n\"\n          \"  %s\\n\"\n          \"  %s\")\n            % (strip_names ? \"true\" : \"false\")\n            % (upper_names ? \"true\" : \"false\")\n            % (convert_stars_to_primes ? \"true\" : \"false\")\n            % bp::extract<atom const&>(prev_atom)().id_str()\n            % atoms[i].id_str()).str());\n      }\n    }\n    return result;\n  }\n\n  void\n  set_adps_from_scatterers(\n    af::const_ref<atom> const& atoms,\n    af::const_ref<cctbx::xray::scatterer<> > const& scatterers,\n    cctbx::uctbx::unit_cell const& unit_cell)\n  {\n    namespace adptbx = cctbx::adptbx;\n    for (unsigned i = 0; i < atoms.size(); i++) {\n      if (scatterers[i].flags.use_u_iso()) {\n        atoms[i].data->b = adptbx::u_as_b(scatterers[i].u_iso);\n        atoms[i].uij_erase();\n      } else if (scatterers[i].flags.use_u_aniso()) {\n        atoms[i].data->uij = adptbx::u_star_as_u_cart(unit_cell,\n          scatterers[i].u_star);\n        atoms[i].data->b = adptbx::u_as_b(adptbx::u_cart_as_u_iso(\n          atoms[i].data->uij));\n      }\n    }\n  }\n\n} // namespace <anonymous>\n\n  void\n  bpl_wrap()\n  {\n    using namespace boost::python;\n    class_<atom_tmp_sentinel,\n           std::auto_ptr<atom_tmp_sentinel>,\n           boost::noncopyable>(\"atom_data_tmp_sentinel\", no_init);\n    typedef scitbx::af::boost_python::shared_wrapper<atom> wat;\n    class_<wat::w_t> wa = wat::wrap(\"af_shared_atom\");\n    scitbx::af::boost_python::select_wrappers<\n      atom, af::shared<atom> >::wrap(wa);\n    typedef scitbx::af::boost_python::shared_wrapper<atom_with_labels> wawl_t;\n    class_<wawl_t::w_t> wawl = wawl_t::wrap(\"af_shared_atom_with_labels\");\n    scitbx::af::boost_python::select_wrappers<\n      atom_with_labels, af::shared<atom_with_labels> >::wrap(wawl);\n    wa.def(\"extract_serial\", extract_serial)\n      .def(\"extract_name\", extract_name)\n      .def(\"extract_segid\", extract_segid)\n      .def(\"extract_xyz\", extract_xyz)\n      .def(\"extract_sigxyz\", extract_sigxyz)\n      .def(\"extract_occ\", extract_occ)\n      .def(\"extract_sigocc\", extract_sigocc)\n      .def(\"extract_b\", extract_b)\n      .def(\"extract_sigb\", extract_sigb)\n      .def(\"extract_uij\", extract_uij)\n#ifdef IOTBX_PDB_ENABLE_ATOM_DATA_SIGUIJ\n      .def(\"extract_siguij\", extract_siguij)\n#endif\n      .def(\"extract_fp\", extract_fp)\n      .def(\"extract_fdp\", extract_fdp)\n      .def(\"extract_hetero\", extract_hetero)\n      .def(\"extract_element\", extract_element, (arg(\"strip\")=false))\n      .def(\"extract_i_seq\", extract_i_seq)\n      .def(\"extract_tmp_as_size_t\", extract_tmp_as_size_t)\n      .def(\"set_xyz\", set_xyz, (arg(\"new_xyz\")), return_self<>())\n      .def(\"set_sigxyz\", set_sigxyz, (arg(\"new_sigxyz\")), return_self<>())\n      .def(\"set_occ\", set_occ, (arg(\"new_occ\")), return_self<>())\n      .def(\"set_sigocc\", set_sigocc, (arg(\"new_sigocc\")), return_self<>())\n      .def(\"set_b\", set_b, (arg(\"new_b\")), return_self<>())\n      .def(\"set_sigb\", set_sigb, (arg(\"new_sigb\")), return_self<>())\n      .def(\"set_uij\", set_uij, (arg(\"new_uij\")), return_self<>())\n#ifdef IOTBX_PDB_ENABLE_ATOM_DATA_SIGUIJ\n      .def(\"set_siguij\", set_siguij, (arg(\"new_siguij\")), return_self<>())\n#endif\n      .def(\"set_fp\", set_fp, (arg(\"new_fp\")), return_self<>())\n      .def(\"set_fdp\", set_fdp, (arg(\"new_fdp\")), return_self<>())\n      .def(\"reset_serial\", reset_serial, (arg(\"first_value\")=1))\n      .def(\"set_chemical_element_simple_if_necessary\",\n        set_chemical_element_simple_if_necessary, (\n          arg(\"tidy_existing\")=true))\n      .def(\"reset_i_seq\", reset_i_seq)\n      .def(\"reset_tmp\", reset_tmp, (\n        arg(\"first_value\")=0,\n        arg(\"increment\")=1))\n      .def(\"reset_tmp_for_occupancy_groups_simple\",\n        reset_tmp_for_occupancy_groups_simple)\n      .def(\"build_dict\", build_dict, (\n        arg(\"strip_names\")=false,\n        arg(\"upper_names\")=false,\n        arg(\"convert_stars_to_primes\")=false,\n        arg(\"throw_runtime_error_if_duplicate_keys\")=true))\n      .def(\"set_adps_from_scatterers\", set_adps_from_scatterers, (\n        arg(\"scatterers\"),\n        arg(\"unit_cell\")));\n    ;\n  }\n\n}}}} // namespace iotbx::pdb::hierarchy::atoms\n", "meta": {"hexsha": "433d042ebbf37ddf2d23e09e8c5cf0931dedd2cb", "size": 5567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iotbx/pdb/hierarchy_atoms_bpl.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": "iotbx/pdb/hierarchy_atoms_bpl.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": "iotbx/pdb/hierarchy_atoms_bpl.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.8707482993, "max_line_length": 78, "alphanum_fraction": 0.6459493444, "num_tokens": 1579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19256214400738306}}
{"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 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//\n// Sparse Pose Adjustment classes and functions\n//\n\n//\n// Ok, we're going with 2-pose constraints, and added scale variables.\n// Format for files:\n// Format for files:\n//   #nodes #scales #p2p_constraints #scale_constraints\n//   x y z rx ry rz   ; first node, vector part of unit quaternion\n//   ...\n//   p1 p2 Lambda_12  ; first p2p constraint\n//   ...\n//   p1 p2 s1 K_12 w  ; first scale constraint, \n//                    ; (p1-p2)^2 = s1*K_12 with weight w\n\n\n#include <stdio.h>\n#include \"sparse_bundle_adjustment/sba.h\"\n#include <Eigen/Cholesky>\n#include <chrono>\n\nusing namespace Eigen;\nusing namespace std;\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <utility>\n\n// elapsed time in microseconds\nstatic long long utime()\n{\n  auto duration = std::chrono::system_clock::now().time_since_epoch();\n  return std::chrono::duration_cast<std::chrono::microseconds>(duration).count();\n}\n\nnamespace sba\n{\n  // reads in a file of pose constraints\n  bool readP2File(char *fname, SysSPA spa)\n  {\n    // Format for files:\n    //   #nodes #scales #p2p_constraints #scale_constraints\n    //   x y z rx ry rz   ; first node, vector part of unit quaternion\n    //   ...\n    //   p1 p2 Lambda_12  ; first p2p constraint\n    //   ...\n    //   p1 p2 s1 K_12 w  ; first scale constraint, \n    //                    ; (p1-p2)^2 = s1*K_12 with weight w\n\n    ifstream ifs(fname);\n    if (!ifs)\n      {\n        cout << \"Can't open file \" << fname << endl;\n        return false;\n      }\n    ifs.precision(10);          // what is this for???\n\n    // read header\n    string line;\n    if (!getline(ifs,line) || line != \"# P2 Constraint File\")\n    {\n      cout << \"Bad header\" << endl;\n      return false;\n    }\n    cout << \"Found P2 constraint file\" << endl;\n\n    // read number of cameras, scalers, and p2p constraints\n    int ncams, nss, nscs, np2s;\n    if (!(ifs >> ncams >> nss >> np2s >> nscs))\n    {\n      cout << \"Bad entity count\" << endl;  \n      return false;\n    }\n    cout << \"Number of cameras: \" << ncams \n         << \"  Number of scalers: \" << nss\n         << \"  Number of p2p constraints: \" << np2s\n         << \"  Number of scale constraints: \" << nscs << endl;\n    \n    cout << \"Reading in camera data...\" << flush;\n    std::vector<Node,Eigen::aligned_allocator<Node> > &nodes = spa.nodes;\n    Node nd;\n\n    for (int i=0; i<ncams; i++)\n      {\n        double v1,v2,v3;\n        if (!(ifs >> v1 >> v2 >> v3))\n          {\n            cout << \"Bad node translation params at number \" << i << endl;\n            return false;\n          }\n        nd.trans = Vector4d(v1,v2,v3,1.0);\n\n        if (!(ifs >> v1 >> v2 >> v3))\n          {\n            cout << \"Bad node rotation quaternion at number \" << i << endl;\n            return false;\n          }\n        Matrix3d m;\n        nd.qrot = Quaternion<double>(v1,v2,v2,0.0);\n        nd.normRot();           // normalize to unit vector and compute w\n        \n        nodes.push_back(nd);\n      }\n    cout << \"done\" << endl;\n\n    // read in p2p constraints\n    cout << \"Reading in constraint data...\" << flush;\n    std::vector<ConP2,Eigen::aligned_allocator<ConP2> > &cons = spa.p2cons;\n    ConP2 con;\n\n    for (int i=0; i<np2s; i++)\n      {\n        int p1, p2;\n        double vz[6];           // mean\n        double vv[36];          // prec\n\n        if (!(ifs >> p1 >> p2))\n          {\n            cout << \"Bad node indices at constraint \" << i << endl;\n            return false;\n          }\n\n        for (int i=0; i<6; i++)\n          {\n            if (!(ifs >> vz[i]))\n              {\n                cout << \"Bad constraint mean at constraint \" << i << endl;\n                return false;\n              }\n          }\n\n        for (int i=0; i<36; i++)\n          {\n            if (!(ifs >> vv[i]))\n              {\n                cout << \"Bad constraint precision at constraint \" << i << endl;\n                return false;\n              }\n          }\n\n        con.ndr = p1;\n        con.nd1 = p2;\n\n        //        con.setMean(Matrix<double,6,1>(vz));\n        con.prec = Matrix<double,6,6>(vv);\n\n        cons.push_back(con);\n      }\n\n\n    // read in scale constraints\n    cout << \"Reading in scale constraint data...\" << flush;\n    std::vector<ConScale,Eigen::aligned_allocator<ConScale> > &scons = spa.scons;\n    ConScale scon;\n\n    for (int i=0; i<nscs; i++)\n      {\n        int p1, p2, sv;\n        double ks, w;\n\n        if (!(ifs >> p1 >> p2 >> sv >> ks >> w))\n          {\n            cout << \"Bad scale constraint at constraint \" << i << endl;\n            return false;\n          }\n        \n        scon.nd0 = p1;\n        scon.nd1 = p2;\n        scon.sv  = sv;\n        scon.ks  = ks;\n        scon.w   = w;\n\n        scons.push_back(scon);\n      }\n\n    return true;\n  }\n\n// Do we want to normalize quaternion vectors based on the sign of w?\n#define NORMALIZE_Q\n\n  // set up Jacobians\n  // see Konolige RSS 2010 submission for details\n\n  void ConP2::setJacobians(std::vector<Node,Eigen::aligned_allocator<Node> > &nodes)\n  {\n    // node references\n    Node &nr = nodes[ndr];\n    Matrix<double,4,1> &tr = nr.trans;\n    Quaternion<double> &qr = nr.qrot;\n    Node &n1 = nodes[nd1];\n    Matrix<double,4,1> &t1 = n1.trans;\n    Quaternion<double> &q1 = n1.qrot;\n\n    // first get the second frame in first frame coords\n    Eigen::Matrix<double,3,1> pc = nr.w2n * t1;\n\n    // Jacobians wrt first frame parameters\n\n    // translational part of 0p1 wrt translational vars of p0\n    // this is just -R0'  [from 0t1 = R0'(t1 - t0)]\n    J0.block<3,3>(0,0) = -nr.w2n.block<3,3>(0,0);\n\n\n    // translational part of 0p1 wrt rotational vars of p0\n    // dR'/dq * [pw - t]\n    Eigen::Matrix<double,3,1> pwt;\n    pwt = (t1-tr).head(3);   // transform translations\n\n    // dx\n    Eigen::Matrix<double,3,1> dp = nr.dRdx * pwt; // dR'/dq * [pw - t]\n    J0.block<3,1>(0,3) = dp;\n    // dy\n    dp = nr.dRdy * pwt; // dR'/dq * [pw - t]\n    J0.block<3,1>(0,4) = dp;\n    // dz\n    dp = nr.dRdz * pwt; // dR'/dq * [pw - t]\n    J0.block<3,1>(0,5) = dp;\n\n    // rotational part of 0p1 wrt translation vars of p0 => zero\n    J0.block<3,3>(3,0).setZero();\n\n    // rotational part of 0p1 wrt rotational vars of p0\n    // from 0q1 = qpmean * s0' * q0' * q1\n\n    // dqdx\n    Eigen::Quaternion<double> qr0, qr1, qrn, qrd;\n    qr1.coeffs() = q1.coeffs();\n    qrn.coeffs() = Vector4d(-qpmean.w(),-qpmean.z(),qpmean.y(),qpmean.x());  // qpmean * ds0'/dx\n    qr0.coeffs() = Vector4d(-qr.x(),-qr.y(),-qr.z(),qr.w());\n    qr0 = qr0*qr1;              // rotate to zero mean\n    qrd = qpmean*qr0;           // for normalization check\n    qrn = qrn*qr0;\n\n#ifdef NORMALIZE_Q\n    if (qrd.w() < 0.0)\n      qrn.vec() = -qrn.vec();\n#endif\n\n    J0.block<3,1>(3,3) = qrn.vec();\n\n    // dqdy\n    qrn.coeffs() = Vector4d(qpmean.z(),-qpmean.w(),-qpmean.x(),qpmean.y());  // qpmean * ds0'/dy\n    qrn = qrn*qr0;\n\n#ifdef NORMALIZE_Q\n    if (qrd.w() < 0.0)\n      qrn.vec() = -qrn.vec();\n#endif\n\n    J0.block<3,1>(3,4) = qrn.vec();\n\n    // dqdz\n    qrn.coeffs() = Vector4d(-qpmean.y(),qpmean.x(),-qpmean.w(),qpmean.z());  // qpmean * ds0'/dz\n    qrn = qrn*qr0;\n\n#ifdef NORMALIZE_Q\n    if (qrd.w() < 0.0)\n      qrn.vec() = -qrn.vec();\n#endif\n\n    J0.block<3,1>(3,5) = qrn.vec();\n\n    // transpose\n    J0t = J0.transpose();\n\n    //  cout << endl << \"J0 \" << ndr << endl << J0 << endl;\n\n    // Jacobians wrt second frame parameters\n    // translational part of 0p1 wrt translational vars of p1\n    // this is just R0'  [from 0t1 = R0'(t1 - t0)]\n    J1.block<3,3>(0,0) = nr.w2n.block<3,3>(0,0);\n\n    // translational part of 0p1 wrt rotational vars of p1: zero\n    J1.block<3,3>(0,3).setZero();\n\n    // rotational part of 0p1 wrt translation vars of p0 => zero\n    J1.block<3,3>(3,0).setZero();\n\n\n    // rotational part of 0p1 wrt rotational vars of p0\n    // from 0q1 = q0'*s1*q1\n\n    Eigen::Quaternion<double> qrc;\n    qrc.coeffs() = Vector4d(-qr.x(),-qr.y(),-qr.z(),qr.w());\n    qrc = qpmean*qrc*qr1;       // mean' * qr0' * qr1\n    qrc.normalize();\n\n    //    cout << endl << \"QRC  : \" << qrc.coeffs().transpose() << endl;\n\n    double dq = 1.0e-8;\n    double wdq = 1.0 - dq*dq;\n    qr1.coeffs() = Vector4d(dq,0,0,wdq);\n    //    cout << \"QRC+x: \" << (qrc*qr1).coeffs().transpose() << endl;    \n    //    cout << \"QRdx:  \" << ((qrc*qr1).coeffs().transpose() - qrc.coeffs().transpose())/dq << endl;\n\n    // dqdx\n    qrn.coeffs() = Vector4d(1,0,0,0);\n    qrn = qrc*qrn;\n\n    //    cout << \"J1dx:  \" << qrn.coeffs().transpose() << endl;\n\n#ifdef NORMALIZE_Q\n    if (qrc.w() < 0.0)\n      qrn.vec() = -qrn.vec();\n#endif\n\n    J1.block<3,1>(3,3) = qrn.vec();\n\n    // dqdy\n    qrn.coeffs() = Vector4d(0,1,0,0);\n    qrn = qrc*qrn;\n\n#ifdef NORMALIZE_Q\n    if (qrc.w() < 0.0)\n      qrn.vec() = -qrn.vec();\n#endif\n\n    J1.block<3,1>(3,4) = qrn.vec();\n\n    // dqdz\n    qrn.coeffs() = Vector4d(0,0,1,0);\n    qrn = qrc*qrn;\n\n#ifdef NORMALIZE_Q\n    if (qrc.w() < 0.0)\n      qrn.vec() = -qrn.vec();\n#endif\n\n    J1.block<3,1>(3,5) = qrn.vec();\n\n    // transpose\n    J1t = J1.transpose();\n\n    //  cout << endl << \"J1 \" << nd1 << endl << J1 << endl;\n\n  };\n\n\n\n  // set up Jacobians\n  // see Konolige RSS 2010 submission for details\n\n  void ConScale::setJacobians(std::vector<Node,Eigen::aligned_allocator<Node> > &nodes)\n  {\n    // node references\n    Node &n0 = nodes[nd0];\n    Matrix<double,4,1> &t0 = n0.trans;\n    Node &n1 = nodes[nd1];\n    Matrix<double,4,1> &t1 = n1.trans;\n\n    Eigen::Matrix<double,3,1> td = (t1-t0).head(3);\n\n    // Jacobians wrt first frame parameters\n    //  (ti - tj)^2 - a*kij\n\n    // scale error wrt translational vars t0\n    J0 = -2.0 * td;\n\n    // scale error wrt translational vars t1\n    J1 =  2.0 * td;\n\n    // scale error wrt scale variable is just -kij\n  };\n\n\n\n  // \n  // This hasn't been tested, and is probably wrong.\n  //\n\n  void ConP3P::setJacobians(std::vector<Node,Eigen::aligned_allocator<Node> > nodes)\n  {\n    // node references\n    Node nr = nodes[ndr];\n    Matrix<double,4,1> &tr = nr.trans;\n    Quaternion<double> &qr = nr.qrot;\n    Node n1 = nodes[nd1];\n    Matrix<double,4,1> &t1 = n1.trans;\n    Quaternion<double> &q1 = n1.qrot;\n    Node n2 = nodes[nd2];\n    Matrix<double,4,1> &t2 = n2.trans;\n    Quaternion<double> &q2 = n2.qrot;\n\n    // calculate J10 -> d(0p1)/d(p0)\n    // rows are indexed by 0p1 parameters\n    // cols are indexed by p0 parameters\n\n    // translational part of 0p1 wrt translational vars of p0\n    // this is just -R0'  [from 0t1 = R0'(t1 - t0)]\n    J10.block<3,3>(0,0) = -nr.w2n.block<3,3>(0,0);\n\n    // translational part of 0p1 wrt rotational vars of p0\n    // dR'/dq * [pw - t]\n    Matrix<double,3,1> pwt = (t1-tr).head(3);\n    Matrix<double,3,1> dp = nr.dRdx * pwt; // dR'/dqx * [pw - t]\n    J10.block<3,1>(0,3) = dp;\n    dp = nr.dRdy * pwt; // dR'/dqy * [pw - t]\n    J10.block<3,1>(0,4) = dp;\n    dp = nr.dRdz * pwt; // dR'/dqz * [pw - t]\n    J10.block<3,1>(0,5) = dp;\n\n    // rotational part of 0p1 wrt translation vars of p0 => zero\n    J10.block<3,3>(3,0).setZero();\n\n    // rotational part of 0p1 wrt rotational vars of p0\n    // from 0q1 = q0'*q1\n\n    // dqdx\n    double wn = -1.0/qr.w();  // need to switch params for small qr(3)\n    dp[0] = wn*t1[0]*qr.x() - t1[3];\n    dp[1] = wn*t1[1]*qr.x() + t1[2];\n    dp[2] = wn*t1[2]*qr.x() - t1[1];\n    J10.block<3,1>(3,3) = dp;\n\n    // dqdy\n    dp[0] = wn*t1[0]*qr.y() - t1[2];\n    dp[1] = wn*t1[1]*qr.y() - t1[3];\n    dp[2] = wn*t1[2]*qr.y() + t1[0];\n    J10.block<3,1>(3,4) = dp;\n\n    // dqdz\n    dp[0] = wn*t1[0]*qr.z() + t1[1];\n    dp[1] = wn*t1[1]*qr.z() - t1[0];\n    dp[2] = wn*t1[2]*qr.z() - t1[3];\n    J10.block<3,1>(3,5) = dp;\n\n    // whew, J10 done...\n\n    // J20 is similar, just using p2\n    // translational part of 0p2 wrt translational vars of p0\n    // this is just -R0'  [from 0t2 = R0'(t2 - t0)]\n    J20.block<3,3>(0,0) = -nr.w2n.block<3,3>(0,0);\n\n    // translational part of 0p2 wrt rotational vars of p0\n    // dR'/dq * [pw - t]\n    pwt = (t2-tr).head(3);\n    dp = nr.dRdx * pwt; // dR'/dqx * [pw - t]\n    J20.block<3,1>(0,3) = dp;\n    dp = nr.dRdy * pwt; // dR'/dqy * [pw - t]\n    J20.block<3,1>(0,4) = dp;\n    dp = nr.dRdz * pwt; // dR'/dqz * [pw - t]\n    J20.block<3,1>(0,5) = dp;\n\n    // rotational part of 0p1 wrt translation vars of p0 => zero\n    J20.block<3,3>(3,0).setZero();\n\n    // rotational part of 0p2 wrt rotational vars of p0\n    // from 0q1 = q0'*q2\n\n    // dqdx\n    wn = -1.0/qr.w();  // need to switch params for small qr(3)\n    dp[0] = wn*q2.x()*qr.x() - q2.w();\n    dp[1] = wn*q2.y()*qr.x() + q2.z();\n    dp[2] = wn*q2.z()*qr.x() - q2.y();\n    J20.block<3,1>(3,3) = dp;\n\n    // dqdy\n    dp[0] = wn*q2.x()*qr.y() - q2.z();\n    dp[1] = wn*q2.y()*qr.y() - q2.w();\n    dp[2] = wn*q2.z()*qr.y() + q2.x();\n    J20.block<3,1>(3,4) = dp;\n\n    // dqdz\n    dp[0] = wn*q2.x()*qr.z() + q2.y();\n    dp[1] = wn*q2.y()*qr.z() - q2.x();\n    dp[2] = wn*q2.z()*qr.z() - q2.w();\n    J20.block<3,1>(3,5) = dp;\n\n    // calculate J11 -> d(0p1)/d(p1)\n    // rows are indexed by 0p1 parameters\n    // cols are indexed by p1 parameters\n\n    // translational part of 0p1 wrt translational vars of p1\n    // this is just R0'  [from 0t1 = R0'(t1 - t0)]\n    J11.block<3,3>(0,0) = nr.w2n.block<3,3>(0,0);\n\n    // translational part of 0p1 wrt rotational vars of p1 => zero\n    J11.block<3,3>(0,3).setZero();\n\n    // rotational part of 0p1 wrt translation vars of p1 => zero\n    J11.block<3,3>(3,0).setZero();\n\n    // rotational part of 0p1 wrt rotational vars of p1\n    // from 0q1 = q0'*q1\n\n    // dqdx1\n    wn = 1.0/q1.w();  // need to switch params for small q1(3)\n    dp[0] = wn*qr.x()*q1.x() + qr.w();\n    dp[1] = wn*qr.y()*q1.x() - qr.z();\n    dp[2] = wn*qr.z()*q1.x() + qr.y();\n    J11.block<3,1>(3,3) = dp;\n\n    // dqdy1\n    dp[0] = wn*qr.x()*q1.y() + qr.z();\n    dp[1] = wn*qr.y()*q1.y() + qr.w();\n    dp[2] = wn*qr.z()*q1.y() - qr.x();\n    J11.block<3,1>(3,4) = dp;\n\n    // dqdz1\n    dp[0] = wn*qr.x()*q1.z() - qr.y();\n    dp[1] = wn*qr.y()*q1.z() + qr.x();\n    dp[2] = wn*qr.z()*q1.z() + qr.w();\n    J11.block<3,1>(3,5) = dp;\n\n    // whew, J11 done...    \n\n    // J22 is similar to J11\n    // rows are indexed by 0p2 parameters\n    // cols are indexed by p2 parameters\n\n    // translational part of 0p2 wrt translational vars of p2\n    // this is just R0'  [from 0t2 = R0'(t2 - t0)]\n    J22.block<3,3>(0,0) = nr.w2n.block<3,3>(0,0);\n\n    // translational part of 0p2 wrt rotational vars of p2 => zero\n    J22.block<3,3>(0,3).setZero();\n\n    // rotational part of 0p2 wrt translation vars of p2 => zero\n    J22.block<3,3>(3,0).setZero();\n\n    // rotational part of 0p2 wrt rotational vars of p2\n    // from 0q2 = q0'*q2\n\n    // dqdx2\n    wn = 1.0/q2.w();  // need to switch params for small q2.w()\n    dp[0] = wn*qr.x()*q2.x() + qr.w();\n    dp[1] = wn*qr.y()*q2.x() - qr.z();\n    dp[2] = wn*qr.z()*q2.x() + qr.y();\n    J22.block<3,1>(3,3) = dp;\n\n    // dqdy1\n    dp[0] = wn*qr.x()*q2.y() + qr.z();\n    dp[1] = wn*qr.y()*q2.y() + qr.w();\n    dp[2] = wn*qr.z()*q2.y() - qr.x();\n    J22.block<3,1>(3,4) = dp;\n\n    // dqdz1\n    dp[0] = wn*qr.x()*q2.z() - qr.y();\n    dp[1] = wn*qr.y()*q2.z() + qr.x();\n    dp[2] = wn*qr.z()*q2.z() + qr.w();\n    J22.block<3,1>(3,5) = dp;\n\n    // whew, J22 done...    \n\n  };\n\n\n  // error function\n  inline double ConP2::calcErr(const Node &nd0, const Node &nd1)\n    { \n      Quaternion<double> q0p,q1;\n      q0p.vec()   = -nd0.qrot.coeffs().head(3); // invert quaternion\n      q0p.w()     =  nd0.qrot.w();\n      q1          =  nd1.qrot;\n      err.block<3,1>(0,0) = nd0.w2n * nd1.trans - tmean;\n\n      //      cout << endl;\n      //      cout << q0p.coeffs().transpose() << endl;\n      //      cout << q1.coeffs().transpose() << endl;\n      //      cout << qpmean.coeffs().transpose() << endl;\n\n      q1 = qpmean * q0p * q1;\n\n      //      cout << q1.coeffs().transpose() << endl << endl;\n\n// this seems to mess up convergence...\n#ifdef NORMALIZE_Q                              \n      if (q1.w() < 0.0)\n        err.block<3,1>(3,0) = -q1.vec(); // normalized\n      else\n#endif\n        err.block<3,1>(3,0) = q1.vec(); // do we have to normalize w???\n      //      cout << endl << \"Error: \" << err.transpose() << endl << endl;\n      return err.dot(prec * err);\n    }\n\n\n  // error function for distance cost\n  double ConP2::calcErrDist(const Node &nd0, const Node &nd1)\n    { \n      Vector3d derr;\n      Quaternion<double> q0p,q1;\n      q0p.vec()   = -nd0.qrot.vec(); // invert quaternion\n      q0p.w()     =  nd0.qrot.w();\n      q1          =  nd1.qrot;\n      derr = nd0.w2n * nd1.trans - tmean;\n      return derr.dot(derr);\n    }\n\n\n  // error function\n  inline double ConScale::calcErr(const Node &nd0, const Node &nd1, double alpha)\n    { \n      err = (nd1.trans - nd0.trans).squaredNorm();\n      err -= ks*alpha;\n      //      cout << \"Scale err: \" << err << endl;\n      return w*err*err;\n    }\n\n\n  // Adds a node to the system. \n  // \\return the index of the node added.\n  int SysSPA::addNode(Eigen::Matrix<double,4,1> &trans, \n                      Eigen::Quaternion<double> &qrot,\n                      bool isFixed)\n  {\n    Node nd;\n    nd.trans = trans;\n    nd.qrot = qrot;\n    nd.isFixed = isFixed;\n    nd.setTransform(); // set up world2node transform\n    nd.setDr(true); // set rotational derivatives\n    // Should this be local or global?\n    nd.normRot();//Local();\n    nodes.push_back(nd);\n    return nodes.size()-1;\n  }\n\n\n  // add a constraint\n  // <nd0>, <nd1> are node id's\n  // <mean> is x,y,th, with th in radians\n  // <prec> is a 3x3 precision matrix (inverse covariance\n  // returns true if nodes are found\n  bool SysSPA::addConstraint(int nd0, int nd1,\n                             Eigen::Vector3d &tmean,\n                             Eigen::Quaterniond &qpmean,\n                             Eigen::Matrix<double,6,6> &prec)\n  {\n    if (nd0 >= (int)nodes.size() || nd1 >= (int)nodes.size()) \n      return false;\n    \n    ConP2 con;\n    con.ndr = nd0;\n    con.nd1 = nd1;\n\n    con.tmean = tmean;\n    Quaternion<double> qr;\n    qr = qpmean;\n    qr.normalize();\n    con.qpmean = qr.inverse(); // inverse of the rotation measurement\n    con.prec = prec;            \n\n    p2cons.push_back(con);\n    return true;\n  }\n\n\n  // error measure, squared\n  // assumes node transforms have already been calculated\n  // <tcost> is true if we just want the distance offsets\n  double SysSPA::calcCost(bool tcost)\n  {\n    double cost = 0.0;\n    \n    // do distance offset\n    if (tcost)\n      {\n        for(size_t i=0; i<p2cons.size(); i++)\n          {\n            ConP2 &con = p2cons[i];\n            double err = con.calcErrDist(nodes[con.ndr],nodes[con.nd1]);\n            cost += err;\n          }\n      }\n\n    // full cost\n    else \n      {\n        for(size_t i=0; i<p2cons.size(); i++)\n          {\n            ConP2 &con = p2cons[i];\n            double err = con.calcErr(nodes[con.ndr],nodes[con.nd1]);\n            cost += err;\n          }\n        if (scons.size() > 0)       // can have zero scale constraints\n          for(size_t i=0; i<scons.size(); i++)\n            {\n              ConScale &con = scons[i];\n              double err = con.calcErr(nodes[con.nd0],nodes[con.nd1],scales[con.sv]);\n              cost += err;\n            }\n      }\n\n    return cost;\n  }\n\n\n  // Set up linear system, from RSS submission (konolige 2010)\n  // This is a relatively compact version of the algorithm! \n  // but not Jacobians\n\n  void SysSPA::setupSys(double sLambda)\n  {\n    // set matrix sizes and clear\n    // assumes scales vars are all free\n    int nFree = nodes.size() - nFixed;\n    int nscales = scales.size();\n    A.setZero(6*nFree+nscales,6*nFree+nscales);\n    B.setZero(6*nFree+nscales);\n    VectorXi dcnt(nFree);\n    dcnt.setZero(nFree);\n\n    // lambda augmentation\n    double lam = 1.0 + sLambda;\n\n    // loop over P2 constraints\n    for(size_t pi=0; pi<p2cons.size(); pi++)\n      {\n        ConP2 &con = p2cons[pi];\n        con.setJacobians(nodes);\n\n        // add in 4 blocks of A; actually just need upper triangular\n        // i0 < i1\n        int i0 = 6*(con.ndr-nFixed); // will be negative if fixed\n        int i1 = 6*(con.nd1-nFixed); // will be negative if fixed\n        \n        if (i0>=0)\n          {\n            A.block<6,6>(i0,i0) += con.J0t * con.prec * con.J0;\n            dcnt(con.ndr - nFixed)++;\n          }\n        if (i1>=0)\n          {\n            dcnt(con.nd1 - nFixed)++;\n            Matrix<double,6,6> tp = con.prec * con.J1;\n            A.block<6,6>(i1,i1) += con.J1t * tp;\n            if (i0>=0)\n              {\n                A.block<6,6>(i0,i1) += con.J0t * con.prec * con.J1;\n                A.block<6,6>(i1,i0) += con.J1t * con.prec * con.J0;\n              }\n          }\n\n        // add in 2 blocks of B\n        if (i0>=0)\n          B.block<6,1>(i0,0) -= con.J0t * con.prec * con.err;\n        if (i1>=0)\n          B.block<6,1>(i1,0) -= con.J1t * con.prec * con.err;\n      } // finish P2 constraints\n\n    // loop over Scale constraints\n    if (scons.size() > 0)       // could be zero\n      for(size_t pi=0; pi<scons.size(); pi++)\n        {\n          ConScale &con = scons[pi];\n          con.setJacobians(nodes);\n        // add in 4 blocks of A for t0, t1; actually just need upper triangular\n        // i0 < i1\n        int i0 = 6*(con.nd0-nFixed); // will be negative if fixed\n        int i1 = 6*(con.nd1-nFixed); // will be negative if fixed\n        \n        if (i0>=0)\n          {\n            A.block<3,3>(i0,i0) += con.w * con.J0 * con.J0.transpose();\n          }\n        if (i1>=0)\n          {\n            A.block<3,3>(i1,i1) += con.w * con.J1 * con.J1.transpose();\n            if (i0>=0)\n              {\n                A.block<3,3>(i0,i1) += con.w * con.J0 * con.J1.transpose();\n                A.block<3,3>(i1,i0) = A.block<3,3>(i0,i1).transpose();\n              }\n          }\n\n        // add in 2 blocks of B\n        if (i0>=0)\n          B.block<3,1>(i0,0) -= con.w * con.J0 * con.err;\n        if (i1>=0)\n          B.block<3,1>(i1,0) -= con.w * con.J1 * con.err;\n\n        // scale variable, add in 5 blocks; actually just need upper triangular\n        int is = 6*nFree+con.sv;\n        A(is,is) += con.w * con.ks * con.ks;\n        if (i0>=0)\n          {\n            A.block<3,1>(i0,is) += con.w * con.J0 * -con.ks;\n            A.block<1,3>(is,i0) = A.block<3,1>(i0,is).transpose();\n          }\n        if (i1>=0)\n          {\n            A.block<3,1>(i1,is) += con.w * con.J1 * -con.ks;\n            A.block<1,3>(is,i1) = A.block<3,1>(i1,is).transpose();\n          }\n\n        // add in scale block of B\n        B(is) -= con.w * (-con.ks) * con.err;\n\n      } // finish Scale constraints\n\n\n    // augment diagonal\n    A.diagonal() *= lam;\n\n    // check the matrix and vector\n    for (int i=0; i<6*nFree; i++)\n      for (int j=0; j<6*nFree; j++)\n        if (std::isnan(A(i,j)) ) { printf(\"[SetupSys] NaN in A\\n\"); *(int *)0x0 = 0; }\n\n    for (int j=0; j<6*nFree; j++)\n      if (std::isnan(B[j]) ) { printf(\"[SetupSys] NaN in B\\n\"); *(int *)0x0 = 0; }\n\n    int ndc = 0;\n    for (int i=0; i<nFree; i++)\n      if (dcnt(i) == 0) ndc++;\n\n    if (ndc > 0)\n      cout << \"[SetupSys] \" << ndc << \" disconnected nodes\" << endl;\n  }\n\n\n  // Set up sparse linear system; see setupSys for algorithm.\n  // Currently doesn't work with scale variables\n  void SysSPA::setupSparseSys(double sLambda, int iter, int sparseType)\n  {\n    // set matrix sizes and clear\n    // assumes scales vars are all free\n    int nFree = nodes.size() - nFixed;\n\n    //    long long t0, t1, t2, t3;\n    //    t0 = utime();\n\n    if (iter == 0)\n      csp.setupBlockStructure(nFree); // initialize CSparse structures\n    else\n      csp.setupBlockStructure(0); // zero out CSparse structures\n\n    //    t1 = utime();\n\n    VectorXi dcnt(nFree);\n    dcnt.setZero(nFree);\n\n    // lambda augmentation\n    double lam = 1.0 + sLambda;\n\n    // loop over P2 constraints\n    for(size_t pi=0; pi<p2cons.size(); pi++)\n      {\n        ConP2 &con = p2cons[pi];\n        con.setJacobians(nodes);\n\n        // add in 4 blocks of A; actually just need upper triangular\n        int i0 = con.ndr-nFixed; // will be negative if fixed\n        int i1 = con.nd1-nFixed; // will be negative if fixed\n        \n        if (i0>=0)\n          {\n           Matrix<double,6,6> m = con.J0t*con.prec*con.J0;\n            csp.addDiagBlock(m,i0);\n            dcnt(con.ndr - nFixed)++;\n          }\n        if (i1>=0)\n          {\n            dcnt(con.nd1 - nFixed)++;\n            Matrix<double,6,6> tp = con.prec * con.J1;\n            Matrix<double,6,6> m = con.J1t * tp;\n            csp.addDiagBlock(m,i1);\n            if (i0>=0)\n              {\n                Matrix<double,6,6> m2 = con.J0t * tp;\n                if (i1 < i0)\n                  {\n                    m = m2.transpose();\n                    csp.addOffdiagBlock(m,i1,i0);\n                  }\n                else\n                  csp.addOffdiagBlock(m2,i0,i1);\n              }\n          }\n\n        // add in 2 blocks of B\n        if (i0>=0)\n          csp.B.block<6,1>(i0*6,0) -= con.J0t * con.prec * con.err;\n        if (i1>=0)\n          csp.B.block<6,1>(i1*6,0) -= con.J1t * con.prec * con.err;\n      } // finish P2 constraints\n\n    //    t2 = utime();\n\n    // set up sparse matrix structure from blocks\n    if (sparseType == SBA_BLOCK_JACOBIAN_PCG)\n      csp.incDiagBlocks(lam);   // increment diagonal block\n    else\n      csp.setupCSstructure(lam,iter==0); \n\n    //    t3 = utime();\n\n    //    printf(\"\\n[SetupSparseSys] Block: %0.1f   Cons: %0.1f  CS: %0.1f\\n\",\n    //           (t1-t0)*.001, (t2-t1)*.001, (t3-t2)*.001);\n\n    int ndc = 0;\n    for (int i=0; i<nFree; i++)\n      if (dcnt(i) == 0) ndc++;\n\n    if (ndc > 0)\n      cout << \"[SetupSparseSys] \" << ndc << \" disconnected nodes\" << endl;\n  }\n  \n\n  /// Run the LM algorithm that computes a nonlinear SPA estimate.\n  /// <niter> is the max number of iterations to perform; returns the\n  /// number actually performed.\n  /// <lambda> is the diagonal augmentation for LM.  \n  /// <useCSparse> is true for sparse Cholesky.\n  ///                2 for gradient system, 3 for block jacobian PCG\n  /// <initTol> is the initial tolerance for CG \n  /// <maxCGiters> is max # of iterations in BPCG\n\n  int SysSPA::doSPA(int niter, double sLambda, int useCSparse, double initTol,\n                      int maxCGiters)\n  {\n    Node::initDr();\n    int nFree = nodes.size() - nFixed; // number of free nodes\n\n    // number of nodes\n    int ncams = nodes.size();\n    // number of scale variables\n    int nscales = scales.size();\n\n    // save old scales\n    vector<double> oldscales;   \n    oldscales.resize(nscales);\n    \n    // initialize vars\n    if (sLambda > 0.0)          // do we initialize lambda?\n      lambda = sLambda;\n\n    // set number of constraints\n    int ncons = p2cons.size();\n\n    // check for fixed frames\n    for (int i=0; i<ncams; i++)\n      {\n        Node &nd = nodes[i];\n        if (i >= nFixed)\n          nd.isFixed = false;\n        else \n          nd.isFixed = true;\n        nd.setTransform();      // set up world-to-node transform for cost calculation\n        nd.setDr(true);         // always use local angles\n      }\n\n    // initialize vars\n    double laminc = 2.0;        // how much to increment lambda if we fail\n    double lamdec = 0.5;        // how much to decrement lambda if we succeed\n    int iter = 0;               // iterations\n    sqMinDelta = 1e-8 * 1e-8;\n    double cost = calcCost();\n    if (verbose)\n      cout << iter << \" Initial squared cost: \" << cost << \" which is \" \n           << sqrt(cost/ncons) << \" rms error\" << endl; \n\n    int good_iter = 0;\n    for (; iter<niter; iter++)  // loop at most <niter> times\n    {\n        // set up and solve linear system\n        // NOTE: shouldn't need to redo all calcs in setupSys if we \n        //   got here from a bad update\n\n        long long t0, t1, t2, t3;\n        t0 = utime();\n        if (useCSparse)\n          setupSparseSys(lambda,iter,useCSparse); // set up sparse linear system\n        else\n          setupSys(lambda);     // set up linear system\n\n        // use appropriate linear solver\n        if (useCSparse == SBA_BLOCK_JACOBIAN_PCG)\n          {\n            if (csp.B.rows() != 0)\n              {\n                int iters = csp.doBPCG(maxCGiters,initTol,iter);\n                if (verbose)\n                  cout << \"[Block PCG] \" << iters << \" iterations\" << endl;\n              }\n          }\n        else if (useCSparse > 0)\n        {\n            bool ok = csp.doChol();\n            if (!ok)\n              cout << \"[DoSPA] Sparse Cholesky failed!\" << endl;\n        }\n        else\n          A.ldlt().solveInPlace(B); // Cholesky decomposition and solution\n\n        // get correct result vector\n        VectorXd &BB = useCSparse ? csp.B : B;\n\n        // check for convergence\n        // this is a pretty crummy convergence measure...\n        double sqDiff = BB.squaredNorm();\n        if (sqDiff < sqMinDelta) // converged, done...\n        {\n          break;\n        }\n\n        // update the frames\n        int ci = 0;\n        for(int i=0; i < ncams; i++)\n        {\n            Node &nd = nodes[i];\n            if (nd.isFixed) continue; // not to be updated\n            nd.oldtrans = nd.trans; // save in case we don't improve the cost\n            nd.oldqrot = nd.qrot;\n            nd.trans.head<3>() += BB.segment<3>(ci);\n\n            Quaternion<double> qr;\n            qr.vec() = BB.segment<3>(ci+3); \n            qr.w() = sqrt(1.0 - qr.vec().squaredNorm());\n\n            Quaternion<double> qrn,qrx;\n            qrn = nd.qrot;\n            qr = qrn*qr;        // post-multiply\n            qr.normalize();\n            if (qr.w() < 0.0)\n              nd.qrot.coeffs() = -qr.coeffs();\n            else\n              nd.qrot.coeffs() = qr.coeffs();\n\n            nd.setTransform();  // set up projection matrix for cost calculation\n            nd.setDr(true);     // set rotational derivatives\n            ci += 6;            // advance B index\n        }\n\n        // update the scales\n        ci = 6*nFree;       // head of scale vars\n        if (nscales > 0)        // could be empty\n          for(int i=0; i < nscales; i++)\n          {\n              oldscales[i] = scales[i];\n              scales[i] += B(ci);\n              ci++;\n          }\n\n\n        // new cost\n        double newcost = calcCost();\n        if (verbose)\n          cout << iter << \" Updated squared cost: \" << newcost << \" which is \" \n           << sqrt(newcost/ncons) << \" rms error\" << endl;\n        \n        // check if we did good\n        if (newcost < cost) // && iter != 0) // NOTE: iter==0 case is for checking\n        {\n            cost = newcost;\n            lambda *= lamdec;   // decrease lambda\n            //      laminc = 2.0;       // reset bad lambda factor; not sure if this is a good idea...\n            good_iter++;\n        }\n        else\n        {\n            lambda *= laminc;   // increase lambda\n            laminc *= 2.0;      // increase the increment\n\n            // reset nodes\n            for(int i=0; i<ncams; i++)\n            {\n                Node &nd = nodes[i];\n                if (nd.isFixed) continue; // not to be updated\n                nd.trans = nd.oldtrans;\n                nd.qrot = nd.oldqrot;\n                nd.setTransform(); // set up projection matrix for cost calculation\n                nd.setDr(true);\n            }\n\n            // reset scales\n            if (nscales > 0)    // could be empty\n              for(int i=0; i < nscales; i++)\n                scales[i] = oldscales[i];\n\n\n            cost = calcCost();  // need to reset errors\n            if (verbose)\n              cout << iter << \" Downdated cost: \" << cost << endl;\n            // NOTE: shouldn't need to redo all calcs in setupSys\n        }\n      }\n\n    // return number of iterations performed\n    return good_iter;\n\n  }\n\n\n  // write out the precision matrix for CSparse\n  void SysSPA::writeSparseA(char *fname, bool useCSparse)\n  {\n    ofstream ofs(fname);\n    if (!ofs)\n      {\n        cout << \"Can't open file \" << fname << endl;\n        return;\n      }\n\n    // cameras\n    if (useCSparse)\n      {\n        setupSparseSys(0.0,0,useCSparse);\n        \n        int *Ai = csp.A->i;\n        int *Ap = csp.A->p;\n        double *Ax = csp.A->x;\n\n        for (int i=0; i<csp.csize; i++)\n          for (int j=Ap[i]; j<Ap[i+1]; j++)\n            if (Ai[j] <= i)\n              ofs << Ai[j] << \" \" << i << setprecision(16) << \" \" << Ax[j] << endl;\n      }\n    else\n      {\n        Eigen::IOFormat pfmt(16);\n\n        int nrows = A.rows();\n        int ncols = A.cols();\n    \n        for (int i=0; i<nrows; i++)\n          for (int j=i; j<ncols; j++)\n            {\n              double a = A(i,j);\n              if (A(i,j) != 0.0)\n                ofs << i << \" \" << j << setprecision(16) << \" \" << a << endl;\n            }\n      }\n\n    ofs.close();\n  }\n\n\n  // Set up spanning tree initialization\n  void SysSPA::spanningTree(int node)\n  {\n    int nnodes = nodes.size();\n\n    // set up an index from nodes to their constraints\n    vector<vector<int> > cind;\n    cind.resize(nnodes);\n\n    for(size_t pi=0; pi<p2cons.size(); pi++)\n      {\n        ConP2 &con = p2cons[pi];\n        int i0 = con.ndr;\n        int i1 = con.nd1;\n        cind[i0].push_back(i1);\n        cind[i1].push_back(i0);        \n      }\n\n    // set up breadth-first algorithm\n    VectorXd dist(nnodes);\n    dist.setConstant(1e100);\n    if (node >= nnodes)\n      node = 0;\n    dist[node] = 0.0;\n    std::multimap<double,int> open;  // open list, priority queue - can have duplicates\n    open.emplace(0.0,node);\n\n    // do breadth-first computation\n    while (!open.empty())\n      {\n        // get top node, remove it\n        int ni = open.begin()->second;\n        double di = open.begin()->first;\n        open.erase(open.begin());\n        if (di > dist[ni]) continue; // already dealt with\n\n        // update neighbors\n        Node &nd = nodes[ni];\n        Matrix<double,3,4> n2w;\n        transformF2W(n2w,nd.trans,nd.qrot); // from node to world coords\n\n        vector<int> &nns = cind[ni];\n        for (int i=0; i<(int)nns.size(); i++)\n          {\n            ConP2 &con = p2cons[nns[i]];\n            double dd = con.tmean.norm(); // incremental distance\n            // neighbor node index\n            int nn = con.nd1;\n            if (nn == ni)\n              nn = con.ndr;\n            Node &nd2 = nodes[nn];\n            Vector3d tmean = con.tmean;\n            Quaterniond qpmean = con.qpmean;\n            if (nn == con.ndr)       // wrong way, reverse\n              {\n                qpmean = qpmean.inverse();\n                tmean = nd.qrot.toRotationMatrix().transpose()*nd2.qrot.toRotationMatrix()*tmean;\n              }\n                \n            if (dist[nn] > di + dd) // is neighbor now closer?\n              {\n                // set priority queue\n                dist[nn] = di+dd;\n                open.emplace(di+dd,nn);\n                // update initial pose\n                Vector4d trans;\n                trans.head(3) = tmean;\n                trans(3) = 1.0;\n                nd2.trans.head(3) = n2w*trans;\n                nd2.qrot = qpmean*nd.qrot;\n                nd2.normRot();\n                nd2.setTransform();\n                nd2.setDr(true);\n              }\n          }\n      }\n    \n  }\n  \n\n}  // namespace sba\n", "meta": {"hexsha": "5f40b4ef2d40f3b4cce610a9020e71d04a9c8624", "size": 36902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sparse_bundle_adjustment/src/spa.cpp", "max_stars_repo_name": "Kin-Zhang/turtlebot_simulation", "max_stars_repo_head_hexsha": "9ddbe66401cae602031b4d04a8741450bbd2aace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 165.0, "max_stars_repo_stars_event_min_datetime": "2020-11-24T12:09:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:56:09.000Z", "max_issues_repo_path": "src/sparse_bundle_adjustment/src/spa.cpp", "max_issues_repo_name": "Kin-Zhang/turtlebot_simulation", "max_issues_repo_head_hexsha": "9ddbe66401cae602031b4d04a8741450bbd2aace", "max_issues_repo_licenses": ["MIT"], "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_bundle_adjustment/src/spa.cpp", "max_forks_repo_name": "Kin-Zhang/turtlebot_simulation", "max_forks_repo_head_hexsha": "9ddbe66401cae602031b4d04a8741450bbd2aace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T02:21:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T02:12:22.000Z", "avg_line_length": 29.5689102564, "max_line_length": 102, "alphanum_fraction": 0.5151482304, "num_tokens": 11554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.19256214400738303}}
{"text": "#pragma once\r\n#include <Eigen/Dense>\r\n\r\nenum class MaterialType\r\n{\r\n    Diffuse,\r\n\r\n    // light\r\n    LightArea\r\n};\r\n\r\nclass MaterialBase\r\n{\r\npublic:\r\n    MaterialType get_type() const { return type; };\r\n\r\n    virtual bool has_emission() const = 0;\r\n\r\n    virtual Eigen::Vector3f calc_brdf(Eigen::Vector3f normal, Eigen::Vector3f in, Eigen::Vector3f out) const = 0;\r\n\r\n    virtual Eigen::Vector3f sample(Eigen::Vector3f normal, Eigen::Vector3f in) const = 0;\r\n\r\n    virtual Eigen::Vector3f at(double u, double v) const = 0;\r\n\r\nprotected:\r\n    MaterialBase(MaterialType type) : type(type) {};\r\n\r\n    MaterialType type;\r\n};\r\n", "meta": {"hexsha": "29fb0b3e3e35dcdc5fc518d1d6f02c12c69bc17f", "size": 623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/render/material/MaterialBase.hpp", "max_stars_repo_name": "yzx9/NeuronSdfViewer", "max_stars_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T10:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T10:29:56.000Z", "max_issues_repo_path": "src/render/material/MaterialBase.hpp", "max_issues_repo_name": "yzx9/NeuronSdfViewer", "max_issues_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_issues_repo_licenses": ["MIT"], "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/render/material/MaterialBase.hpp", "max_forks_repo_name": "yzx9/NeuronSdfViewer", "max_forks_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_forks_repo_licenses": ["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.7666666667, "max_line_length": 114, "alphanum_fraction": 0.658105939, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846137, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19256214400738303}}
{"text": "/*\n * The MIT License (MIT)\n * =====================\n *\n * Copyright \u00a9 2019-2020 Azavea\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 \u201cSoftware\u201d), 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 \u201cAS IS\u201d, 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 <cstdio>\n#include <cmath>\n\n#include <string>\n#include <fstream>\n#include <streambuf>\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include \"medial.h\"\n\nnamespace bg = boost::geometry;\n\ntypedef bg::model::d2::point_xy<int64_t> polygon_integral_point;\ntypedef bg::model::referring_segment<polygon_integral_point> polygon_segment;\ntypedef bg::model::polygon<polygon_integral_point> polygon;\n\nint main(int argc, char **argv)\n{\n    // https://upload.wikimedia.org/wikipedia/commons/5/55/SFA_Polygon_with_hole.svg\n    const int f = 1000;\n    polygon bg_polygon;\n    std::vector<int64_t> segments;\n\n    std::ifstream t(argv[1]);\n    std::string wkt_polygon = std::string(std::istreambuf_iterator<char>(t),\n                                          std::istreambuf_iterator<char>());\n\n    int n = -1;\n    double *return_data;\n\n    bg::read_wkt(wkt_polygon.data(), bg_polygon);\n    bg::for_each_segment(bg_polygon, [&segments](polygon_segment s) {\n        segments.push_back(s.first.x() * f);\n        segments.push_back(s.first.y() * f);\n        segments.push_back(s.second.x() * f);\n        segments.push_back(s.second.y() * f);\n    });\n\n    // Compute the internal axis\n    n = get_skeleton(segments.size(), segments.data(), &return_data);\n    fprintf(stderr, \"n = %d\\n\", n);\n\n    // Display the internal axis\n    for (int i = 0; i < n; i += 6)\n    {\n        double x1, y1, d1, x2, y2, d2, length;\n\n        x1 = return_data[i + 0] / f;\n        y1 = return_data[i + 1] / f;\n        x2 = return_data[i + 2] / f;\n        y2 = return_data[i + 3] / f;\n        d1 = return_data[i + 4] / f;\n        d2 = return_data[i + 5] / f;\n        length = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n\n        fprintf(stderr, \"INTERNAL EDGE: (%lf %lf) (%lf %lf) with distances %lf %lf and length %lf\\n\", x1, y1, x2, y2, d1, d2, length);\n    }\n\n    // Cleanup\n    free(return_data);\n    return_data = nullptr;\n\n    return 0;\n}\n", "meta": {"hexsha": "05907c41039f3c5a55d1fa347a8d7e97e5a4cdcf", "size": 3198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libmedial/main.cpp", "max_stars_repo_name": "geotrellis/deeplab-nlcd", "max_stars_repo_head_hexsha": "9444299597e1d1bc34ee187f2092890449c188be", "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/libmedial/main.cpp", "max_issues_repo_name": "geotrellis/deeplab-nlcd", "max_issues_repo_head_hexsha": "9444299597e1d1bc34ee187f2092890449c188be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-08-21T20:01:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T19:59:23.000Z", "max_forks_repo_path": "src/libmedial/main.cpp", "max_forks_repo_name": "geotrellis/deeplab-nlcd", "max_forks_repo_head_hexsha": "9444299597e1d1bc34ee187f2092890449c188be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-21T20:44:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T02:58:15.000Z", "avg_line_length": 32.9690721649, "max_line_length": 134, "alphanum_fraction": 0.6582238899, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19256213880502568}}
{"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// Copyright (c) 2014-2015 Samuel Debionne, Grenoble, France.\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// 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_GEOMETRY_ALGORITHMS_DETAIL_EXPAND_POINT_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_EXPAND_POINT_HPP\n\n#include <cstddef>\n#include <algorithm>\n\n#include <boost/mpl/assert.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_system.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n\n#include <boost/geometry/strategies/compare.hpp>\n#include <boost/geometry/policies/compare.hpp>\n\n#include <boost/geometry/algorithms/detail/normalize.hpp>\n#include <boost/geometry/algorithms/detail/envelope/transform_units.hpp>\n\n#include <boost/geometry/algorithms/dispatch/expand.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace expand\n{\n\n\ntemplate\n<\n    typename StrategyLess, typename StrategyGreater,\n    std::size_t Dimension, std::size_t DimensionCount\n>\nstruct point_loop\n{\n    template <typename Box, typename Point>\n    static inline void apply(Box& box, Point const& source)\n    {\n        typedef typename strategy::compare::detail::select_strategy\n            <\n                StrategyLess, 1, Point, Dimension\n            >::type less_type;\n\n        typedef typename strategy::compare::detail::select_strategy\n            <\n                StrategyGreater, -1, Point, Dimension\n            >::type greater_type;\n\n        typedef typename select_coordinate_type\n            <\n                Point, Box\n            >::type coordinate_type;\n\n        less_type less;\n        greater_type greater;\n\n        coordinate_type const coord = get<Dimension>(source);\n\n        if (less(coord, get<min_corner, Dimension>(box)))\n        {\n            set<min_corner, Dimension>(box, coord);\n        }\n\n        if (greater(coord, get<max_corner, Dimension>(box)))\n        {\n            set<max_corner, Dimension>(box, coord);\n        }\n\n        point_loop\n            <\n                StrategyLess, StrategyGreater, Dimension + 1, DimensionCount\n            >::apply(box, source);\n    }\n};\n\n\ntemplate\n<\n    typename StrategyLess, typename StrategyGreater, std::size_t DimensionCount\n>\nstruct point_loop\n    <\n        StrategyLess, StrategyGreater, DimensionCount, DimensionCount\n    >\n{\n    template <typename Box, typename Point>\n    static inline void apply(Box&, Point const&) {}\n};\n\n\n// implementation for the spherical equatorial and geographic coordinate systems\ntemplate\n<\n    typename StrategyLess,\n    typename StrategyGreater,\n    std::size_t DimensionCount\n>\nstruct point_loop_on_spheroid\n{\n    template <typename Box, typename Point>\n    static inline void apply(Box& box, Point const& point)\n    {\n        typedef typename point_type<Box>::type box_point_type;\n        typedef typename coordinate_type<Box>::type box_coordinate_type;\n\n        typedef math::detail::constants_on_spheroid\n            <\n                box_coordinate_type,\n                typename coordinate_system<Box>::type::units\n            > constants;\n\n        // normalize input point and input box\n        Point p_normalized = detail::return_normalized<Point>(point);\n        detail::normalize(box, box);\n\n        // transform input point to be of the same type as the box point\n        box_point_type box_point;\n        detail::envelope::transform_units(p_normalized, box_point);\n\n        box_coordinate_type p_lon = geometry::get<0>(box_point);\n        box_coordinate_type p_lat = geometry::get<1>(box_point);\n\n        typename coordinate_type<Box>::type\n            b_lon_min = geometry::get<min_corner, 0>(box),\n            b_lat_min = geometry::get<min_corner, 1>(box),\n            b_lon_max = geometry::get<max_corner, 0>(box),\n            b_lat_max = geometry::get<max_corner, 1>(box);\n\n        if (math::equals(math::abs(p_lat), constants::max_latitude()))\n        {\n            // the point of expansion is the either the north or the\n            // south pole; the only important coordinate here is the\n            // pole's latitude, as the longitude can be anything;\n            // we, thus, take into account the point's latitude only and return\n            geometry::set<min_corner, 1>(box, (std::min)(p_lat, b_lat_min));\n            geometry::set<max_corner, 1>(box, (std::max)(p_lat, b_lat_max));\n            return;\n        }\n\n        if (math::equals(b_lat_min, b_lat_max)\n            && math::equals(math::abs(b_lat_min), constants::max_latitude()))\n        {\n            // the box degenerates to either the north or the south pole;\n            // the only important coordinate here is the pole's latitude, \n            // as the longitude can be anything;\n            // we thus take into account the box's latitude only and return\n            geometry::set<min_corner, 0>(box, p_lon);\n            geometry::set<min_corner, 1>(box, (std::min)(p_lat, b_lat_min));\n            geometry::set<max_corner, 0>(box, p_lon);\n            geometry::set<max_corner, 1>(box, (std::max)(p_lat, b_lat_max));\n            return;\n        }\n\n        // update latitudes\n        b_lat_min = (std::min)(b_lat_min, p_lat);\n        b_lat_max = (std::max)(b_lat_max, p_lat);\n\n        // update longitudes\n        if (math::smaller(p_lon, b_lon_min))\n        {\n            box_coordinate_type p_lon_shifted = p_lon + constants::period();\n\n            if (math::larger(p_lon_shifted, b_lon_max))\n            {\n                // here we could check using: ! math::larger(.., ..)\n                if (math::smaller(b_lon_min - p_lon, p_lon_shifted - b_lon_max))\n                {\n                    b_lon_min = p_lon;\n                }\n                else\n                {\n                    b_lon_max = p_lon_shifted;\n                }\n            }\n        }\n        else if (math::larger(p_lon, b_lon_max))\n        {\n            // in this case, and since p_lon is normalized in the range\n            // (-180, 180], we must have that b_lon_max <= 180\n            if (b_lon_min < 0\n                && math::larger(p_lon - b_lon_max,\n                                constants::period() - p_lon + b_lon_min))\n            {\n                b_lon_min = p_lon;\n                b_lon_max += constants::period();\n            }\n            else\n            {\n                b_lon_max = p_lon;\n            }\n        }\n\n        geometry::set<min_corner, 0>(box, b_lon_min);\n        geometry::set<min_corner, 1>(box, b_lat_min);\n        geometry::set<max_corner, 0>(box, b_lon_max);\n        geometry::set<max_corner, 1>(box, b_lat_max);\n\n        point_loop\n            <\n                StrategyLess, StrategyGreater, 2, DimensionCount\n            >::apply(box, point);\n    }\n};\n\n\n}} // namespace detail::expand\n#endif // DOXYGEN_NO_DETAIL\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\n// Box + point -> new box containing also point\ntemplate\n<\n    typename BoxOut, typename Point,\n    typename StrategyLess, typename StrategyGreater,\n    typename CSTagOut, typename CSTag\n>\nstruct expand\n    <\n        BoxOut, Point,\n        StrategyLess, StrategyGreater,\n        box_tag, point_tag,\n        CSTagOut, CSTag\n    > : detail::expand::point_loop\n        <\n            StrategyLess, StrategyGreater, 0, dimension<Point>::value\n        >\n{\n    BOOST_MPL_ASSERT_MSG((geofeatures_boost::is_same<CSTagOut, CSTag>::value),\n                         COORDINATE_SYSTEMS_MUST_BE_THE_SAME,\n                         (types<CSTagOut, CSTag>()));\n};\n\ntemplate\n<\n    typename BoxOut, typename Point,\n    typename StrategyLess, typename StrategyGreater\n>\nstruct expand\n    <\n        BoxOut, Point,\n        StrategyLess, StrategyGreater,\n        box_tag, point_tag,\n        spherical_equatorial_tag, spherical_equatorial_tag\n    > : detail::expand::point_loop_on_spheroid\n        <\n            StrategyLess, StrategyGreater, dimension<Point>::value\n        >\n{};\n\ntemplate\n<\n    typename BoxOut, typename Point,\n    typename StrategyLess, typename StrategyGreater\n>\nstruct expand\n    <\n        BoxOut, Point,\n        StrategyLess, StrategyGreater,\n        box_tag, point_tag,\n        geographic_tag, geographic_tag\n    > : detail::expand::point_loop_on_spheroid\n        <\n            StrategyLess, StrategyGreater, dimension<Point>::value\n        >\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_EXPAND_POINT_HPP\n", "meta": {"hexsha": "a3fb0849530b17909a1ffc32013657015fdd927f", "size": 9387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/detail/expand/point.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/detail/expand/point.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/detail/expand/point.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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.8782894737, "max_line_length": 116, "alphanum_fraction": 0.6323639075, "num_tokens": 2156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.19248092801967306}}
{"text": "#ifndef GIFS_SH_QM_INTERFACE_HPP\n#define GIFS_SH_QM_INTERFACE_HPP\n\n#include \"properties.hpp\"\n#include <armadillo>\n\n/*\n  Abstract base class for all implementations of QMInterface \n*/\n\nclass QMInterface{\n  friend class PrintBomd;\npublic:\n  QMInterface(const arma::uvec& in_qmids, \n\t      arma::mat& in_qm_crd, \n\t      arma::mat& in_mm_crd, \n\t      arma::vec& in_mm_chg, \n\t      const int charge, \n\t      const int mult,\n\t      const int excited_states,\n              const int min_state);\n  virtual void update(); // if overriding, be sure to call the parent too.\n  inline size_t nqm() const noexcept { return NQM; };\n  inline int call_idx() const noexcept { return qm_call_idx; };\n  \n  virtual void get_properties(PropMap &props) =0;\n  virtual ~QMInterface(){};\n\nprotected:\n  //Properties\n  const size_t NQM;             // const, actually NQM+NLink\n  const int qm_charge;\n  int qm_multiplicity;          // non-const since a child might want to override\n  size_t excited_states;        // non-const since a child might want to override\n  size_t min_state;             // non-const since a child might want to override\n  \n  //  fixed size\n  const arma::uvec& atomids;    // NQM\n  arma::mat& crd_qm;      // NQM*3\n  // flexible\n  size_t NMM;\n  arma::mat& crd_mm;      // NMM*3\n  arma::vec& chg_mm;      // NMM\n\nprivate:\n  int qm_call_idx = 0; // tracks each call to update;\n};\n\n#endif\n", "meta": {"hexsha": "db679927d596b924d75e8a7df631b83ca49dd4e1", "size": 1384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/qm_interface.hpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "include/qm_interface.hpp", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "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/qm_interface.hpp", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 27.68, "max_line_length": 81, "alphanum_fraction": 0.6596820809, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.19248092514938006}}
{"text": "// Copyright (c) 2015-2019 Daniel Cooke and Gerton Lunter\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef simd_pair_hmm_wrapper_hpp\n#define simd_pair_hmm_wrapper_hpp\n\n#include <tuple>\n\n#include <boost/variant.hpp>\n\n#include \"exceptions/user_error.hpp\"\n#include \"simd_pair_hmm_factory.hpp\"\n\nnamespace octopus { namespace hmm { namespace simd {\n\nnamespace detail {\n\nconstexpr unsigned ipow(unsigned base, unsigned exponent) noexcept\n{\n    return exponent == 0 ? 1 : base * ipow(base, exponent - 1);\n}\n\ntemplate <typename T, std::size_t... I>\nconstexpr auto make_phmm_tuple(std::index_sequence<I...>) { return std::make_tuple(SimdPairHMM<ipow(2, I + 3), T>{}...); }\n\ntemplate <typename Tuple>\nstruct to_variant;\n\ntemplate <typename... Ts>\nstruct to_variant<std::tuple<Ts...>>\n{\n    using type = boost::variant<Ts...>;\n};\n\ntemplate <typename Tuple>\nusing to_variant_t = typename to_variant<Tuple>::type;\n\n} // namespace detail\n\nclass PairHMMWrapper\n{\npublic:\n    enum class ScorePrecision { int16, int32 };\n    \n    class TooLargeBandSizeError : public std::runtime_error\n    {\n    public:\n        TooLargeBandSizeError() = delete;\n        \n        TooLargeBandSizeError(int requested, int max)\n        : std::runtime_error {\"requested band size is too large\"}\n        , requested_ {requested}\n        , max_ {max}\n        {}\n    \n        int requested() const noexcept { return requested_; };\n        int max() const noexcept { return max_; }\n    \n    private:\n        int requested_, max_;\n    };\n    \n    PairHMMWrapper(int min_band_size = 8, ScorePrecision score_precision = ScorePrecision::int16)\n    {\n        reset(min_band_size, score_precision);\n    }\n    \n    PairHMMWrapper(const PairHMMWrapper&)            = default;\n    PairHMMWrapper& operator=(const PairHMMWrapper&) = default;\n    PairHMMWrapper(PairHMMWrapper&&)                 = default;\n    PairHMMWrapper& operator=(PairHMMWrapper&&)      = default;\n    \n    ~PairHMMWrapper() = default;\n    \n    int band_size() const noexcept\n    {\n        return boost::apply_visitor([] (const auto& hmm) noexcept { return hmm.band_size(); }, hmm_);\n    }\n    \n    const char* name() const noexcept\n    {\n        return boost::apply_visitor([] (const auto& hmm) noexcept { return hmm.name(); }, hmm_);\n    }\n    \n    void reset(int min_band_size, ScorePrecision score_precision = ScorePrecision::int16)\n    {\n        hmm_ = make_simd_pair_hmm(min_band_size, score_precision);\n    }\n    \n    template <typename OpenPenaltyArrayOrConstant,\n              typename ExtendPenaltyArrayOrConstant>\n    int\n    align(const char* truth,\n          const char* target,\n          const std::int8_t* qualities,\n          const int truth_len,\n          const int target_len,\n          const OpenPenaltyArrayOrConstant gap_open,\n          const ExtendPenaltyArrayOrConstant gap_extend,\n          short nuc_prior) const noexcept\n    {\n        return boost::apply_visitor([&] (const auto& hmm) noexcept {\n            return hmm.align(truth, target, qualities, truth_len, target_len, gap_open, gap_extend, nuc_prior);\n        }, hmm_);\n    }\n    template <typename OpenPenaltyArrayOrConstant,\n              typename ExtendPenaltyArrayOrConstant>\n    int\n    align(const char* truth,\n          const char* target,\n          const std::int8_t* qualities,\n          const int truth_len,\n          const int target_len,\n          const char* snv_mask,\n          const std::int8_t* snv_prior,\n          const OpenPenaltyArrayOrConstant gap_open,\n          const ExtendPenaltyArrayOrConstant gap_extend,\n          short nuc_prior) const noexcept\n    {\n        return boost::apply_visitor([&] (const auto& hmm) noexcept {\n            return hmm.align(truth, target, qualities, truth_len, target_len, snv_mask, snv_prior, gap_open, gap_extend, nuc_prior);\n        }, hmm_);\n    }\n    template <typename OpenPenaltyArrayOrConstant,\n              typename ExtendPenaltyArrayOrConstant>\n    int\n    align(const char* truth,\n          const char* target,\n          const std::int8_t* qualities,\n          const int truth_len,\n          const int target_len,\n          const OpenPenaltyArrayOrConstant gap_open,\n          const ExtendPenaltyArrayOrConstant gap_extend,\n          short nuc_prior,\n          int& first_pos,\n          char* align1,\n          char* align2) const noexcept\n    {\n        return boost::apply_visitor([&] (const auto& hmm) noexcept {\n            return hmm.align(truth, target, qualities, truth_len, target_len, gap_open, gap_extend, nuc_prior, first_pos, align1, align2);\n        }, hmm_);\n    }\n    template <typename OpenPenaltyArrayOrConstant,\n              typename ExtendPenaltyArrayOrConstant>\n    int\n    align(const char* truth,\n          const char* target,\n          const std::int8_t* qualities,\n          const int truth_len,\n          const int target_len,\n          const char* snv_mask,\n          const std::int8_t* snv_prior,\n          const OpenPenaltyArrayOrConstant gap_open,\n          const ExtendPenaltyArrayOrConstant gap_extend,\n          short nuc_prior,\n          int& first_pos,\n          char* align1,\n          char* align2) const noexcept\n    {\n        return boost::apply_visitor([&] (const auto& hmm) noexcept {\n            return hmm.align(truth, target, qualities, truth_len, target_len, snv_mask, snv_prior, gap_open, gap_extend, nuc_prior, first_pos, align1, align2);\n        }, hmm_);\n    }\n    template <typename OpenPenaltyArrayOrConstant,\n              typename ExtendPenaltyArrayOrConstant>\n    int\n    calculate_flank_score(const int truth_len,\n                          const int lhs_flank_len,\n                          const int rhs_flank_len,\n                          const std::int8_t* quals,\n                          const OpenPenaltyArrayOrConstant gap_open,\n                          const ExtendPenaltyArrayOrConstant gap_extend,\n                          const short nuc_prior,\n                          const int first_pos,\n                          const char* aln1,\n                          const char* aln2,\n                          int& target_mask_size) const noexcept\n    {\n        return boost::apply_visitor([&] (const auto& hmm) noexcept {\n            return hmm.calculate_flank_score(truth_len, lhs_flank_len, rhs_flank_len, quals, gap_open, gap_extend, nuc_prior, first_pos, aln1, aln2, target_mask_size);\n        }, hmm_);\n    }\n    template <typename OpenPenaltyArrayOrConstant,\n              typename ExtendPenaltyArrayOrConstant>\n    int\n    calculate_flank_score(int truth_len,\n                          int lhs_flank_len,\n                          int rhs_flank_len,\n                          const char* target,\n                          const std::int8_t* quals,\n                          const char* snv_mask,\n                          const std::int8_t* snv_prior,\n                          const OpenPenaltyArrayOrConstant gap_open,\n                          const ExtendPenaltyArrayOrConstant gap_extend,\n                          short nuc_prior,\n                          int first_pos,\n                          const char* aln1,\n                          const char* aln2,\n                          int& target_mask_size) const noexcept\n    {\n        return boost::apply_visitor([&] (const auto& hmm) noexcept {\n            return hmm.calculate_flank_score(truth_len, lhs_flank_len, rhs_flank_len, target, quals, snv_mask, snv_prior, gap_open, gap_extend, nuc_prior, first_pos, aln1, aln2, target_mask_size);\n        }, hmm_);\n    }\n\nprivate:\n    using ShortPairHMMs = decltype(detail::make_phmm_tuple<short>(std::make_index_sequence<6>()));\n    using IntPairHMMs   = decltype(detail::make_phmm_tuple<int>(std::make_index_sequence<6>()));\n    using PairHMMs      = decltype(std::tuple_cat(ShortPairHMMs {}, IntPairHMMs {}));\n    \n    using PairHmmVariant = detail::to_variant_t<PairHMMs>;\n    \n    PairHmmVariant hmm_;\n    \n    template <typename Hmms>\n    constexpr static int max_band_size() { return std::tuple_element_t<std::tuple_size<Hmms>::value - 1, Hmms>::band_size(); }\n    \n    template <typename Hmms, std::size_t... Is>\n    PairHmmVariant make_simd_pair_hmm_helper(const int min_band_size, std::index_sequence<Is...>) const\n    {\n        if (min_band_size <= max_band_size<Hmms>()) {\n            PairHmmVariant result {};\n            int unused[] = {((Is == 0 || std::tuple_element_t<(Is > 0 ? Is - 1 : 0), Hmms>::band_size() < min_band_size)\n                            && min_band_size <= std::tuple_element_t<Is, Hmms>::band_size()\n                            ? (result = std::tuple_element_t<Is, Hmms> {}, 0) : 0)...};\n            (void) unused;\n            return result;\n        } else {\n            throw TooLargeBandSizeError {min_band_size, max_band_size<Hmms>()};\n        }\n    }\n    PairHmmVariant make_simd_pair_hmm(const int min_band_size, const ScorePrecision score_precision) const\n    {\n        if (score_precision == ScorePrecision::int16) {\n            using Hmms = ShortPairHMMs;\n            return make_simd_pair_hmm_helper<Hmms>(min_band_size, std::make_index_sequence<std::tuple_size<Hmms>::value>());\n        } else {\n            using Hmms = IntPairHMMs;\n            return make_simd_pair_hmm_helper<Hmms>(min_band_size, std::make_index_sequence<std::tuple_size<Hmms>::value>());\n        }\n    }\n\npublic:\n    static int max_band_size(ScorePrecision score_precision) noexcept\n    {\n        if (score_precision == ScorePrecision::int16) {\n            return max_band_size<ShortPairHMMs>();\n        } else {\n            return max_band_size<IntPairHMMs>();\n        }\n    }\n};\n\n} // namespace simd\n} // namespace hmm\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "99f7db77a41612ece48d0c904f66330107dff91d", "size": 9672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/pairhmm/simd_pair_hmm_wrapper.hpp", "max_stars_repo_name": "gunjanbaid/octopus", "max_stars_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "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/pairhmm/simd_pair_hmm_wrapper.hpp", "max_issues_repo_name": "gunjanbaid/octopus", "max_issues_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_issues_repo_licenses": ["MIT"], "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/pairhmm/simd_pair_hmm_wrapper.hpp", "max_forks_repo_name": "gunjanbaid/octopus", "max_forks_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_forks_repo_licenses": ["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.3436293436, "max_line_length": 196, "alphanum_fraction": 0.6190033085, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.1924442774792858}}
{"text": "/* ----------------------------------------------------------------------\n *\n *                    *** Smooth Mach Dynamics ***\n *\n * This file is part of the USER-SMD package for LAMMPS.\n * Copyright (2014) Georg C. Ganzenmueller, georg.ganzenmueller@emi.fhg.de\n * Fraunhofer Ernst-Mach Institute for High-Speed Dynamics, EMI,\n * Eckerstrasse 4, D-79104 Freiburg i.Br, Germany.\n *\n * ----------------------------------------------------------------------- */\n\n/* ----------------------------------------------------------------------\n LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator\n http://lammps.sandia.gov, Sandia National Laboratories\n Steve Plimpton, sjplimp@sandia.gov\n\n Copyright (2003) Sandia Corporation.  Under the terms of Contract\n DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains\n certain rights in this software.  This software is distributed under\n the GNU General Public License.\n\n See the README file in the top-level LAMMPS directory.\n ------------------------------------------------------------------------- */\n\n#include <stdio.h>\n#include <string.h>\n#include \"fix_smd_integrate_ulsph.h\"\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"atom.h\"\n#include \"comm.h\"\n#include \"force.h\"\n#include \"neighbor.h\"\n#include \"neigh_list.h\"\n#include \"neigh_request.h\"\n#include \"update.h\"\n#include \"integrate.h\"\n#include \"respa.h\"\n#include \"memory.h\"\n#include \"error.h\"\n#include \"pair.h\"\n#include \"domain.h\"\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\nusing namespace LAMMPS_NS;\nusing namespace FixConst;\n\n/* ---------------------------------------------------------------------- */\n\nFixSMDIntegrateUlsph::FixSMDIntegrateUlsph(LAMMPS *lmp, int narg, char **arg) :\n\t\tFix(lmp, narg, arg) {\n\n\tif ((atom->e_flag != 1) || (atom->vfrac_flag != 1))\n\t\terror->all(FLERR, \"fix smd/integrate_ulsph command requires atom_style with both energy and volume\");\n\n\tif (narg < 3)\n\t\terror->all(FLERR, \"Illegal number of arguments for fix smd/integrate_ulsph command\");\n\n\tadjust_radius_flag = false;\n\txsphFlag = false;\n\tvlimit = -1.0;\n\tint iarg = 3;\n\n\tif (comm->me == 0) {\n\t\tprintf(\"\\n>>========>>========>>========>>========>>========>>========>>========>>========\\n\");\n\t\tprintf(\"fix smd/integrate_ulsph is active for group: %s \\n\", arg[1]);\n\t}\n\twhile (true) {\n\n\t\tif (iarg >= narg) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (strcmp(arg[iarg], \"xsph\") == 0) {\n\t\t\txsphFlag = true;\n\t\t\tif (comm->me == 0) {\n\t\t\t\terror->one(FLERR, \"XSPH is currently not available\");\n\t\t\t\tprintf(\"... will use XSPH time integration\\n\");\n\t\t\t}\n\t\t} else if (strcmp(arg[iarg], \"adjust_radius\") == 0) {\n\t\t\tadjust_radius_flag = true;\n\n\t\t\tiarg++;\n\t\t\tif (iarg == narg) {\n\t\t\t\terror->all(FLERR, \"expected three numbers following adjust_radius: factor, min, max\");\n\t\t\t}\n\n\t\t\tadjust_radius_factor = force->numeric(FLERR, arg[iarg]);\n\n\t\t\tiarg++;\n\t\t\tif (iarg == narg) {\n\t\t\t\terror->all(FLERR, \"expected three numbers following adjust_radius: factor, min, max\");\n\t\t\t}\n\n\t\t\tmin_nn = force->inumeric(FLERR, arg[iarg]);\n\n\t\t\tiarg++;\n\t\t\tif (iarg == narg) {\n\t\t\t\terror->all(FLERR, \"expected three numbers following adjust_radius: factor, min, max\");\n\t\t\t}\n\n\t\t\tmax_nn = force->inumeric(FLERR, arg[iarg]);\n\n\t\t\tif (comm->me == 0) {\n\t\t\t\tprintf(\"... will adjust smoothing length dynamically with factor %g to achieve %d to %d neighbors per particle.\\n \",\n\t\t\t\t\t\tadjust_radius_factor, min_nn, max_nn);\n\t\t\t}\n\n\t\t} else if (strcmp(arg[iarg], \"limit_velocity\") == 0) {\n\t\t\tiarg++;\n\t\t\tif (iarg == narg) {\n\t\t\t\terror->all(FLERR, \"expected number following limit_velocity\");\n\t\t\t}\n\t\t\tvlimit = force->numeric(FLERR, arg[iarg]);\n\n\t\t\tif (comm->me == 0) {\n\t\t\t\tprintf(\"... will limit velocities to <= %g\\n\", vlimit);\n\t\t\t}\n\t\t} else {\n\t\t\tchar msg[128];\n\t\t\tsprintf(msg, \"Illegal keyword for smd/integrate_ulsph: %s\\n\", arg[iarg]);\n\t\t\terror->all(FLERR, msg);\n\t\t}\n\n\t\tiarg++;\n\n\t}\n\n\tif (comm->me == 0) {\n\t\tprintf(\">>========>>========>>========>>========>>========>>========>>========>>========\\n\\n\");\n\t}\n\n\t// set comm sizes needed by this fix\n\tatom->add_callback(0);\n\n\ttime_integrate = 1;\n}\n\n/* ---------------------------------------------------------------------- */\n\nint FixSMDIntegrateUlsph::setmask() {\n\tint mask = 0;\n\tmask |= INITIAL_INTEGRATE;\n\tmask |= FINAL_INTEGRATE;\n\treturn mask;\n}\n\n/* ---------------------------------------------------------------------- */\n\nvoid FixSMDIntegrateUlsph::init() {\n\tdtv = update->dt;\n\tdtf = 0.5 * update->dt * force->ftm2v;\n\tvlimitsq = vlimit * vlimit;\n}\n\n/* ----------------------------------------------------------------------\n allow for both per-type and per-atom mass\n ------------------------------------------------------------------------- */\n\nvoid FixSMDIntegrateUlsph::initial_integrate(int vflag) {\n\tdouble **x = atom->x;\n\tdouble **v = atom->v;\n\tdouble **f = atom->f;\n\tdouble **vest = atom->vest;\n\tdouble *rmass = atom->rmass;\n\n\tint *mask = atom->mask;\n\tint nlocal = atom->nlocal;\n\tint i, itmp;\n\tdouble dtfm, vsq, scale;\n\tdouble vxsph_x, vxsph_y, vxsph_z;\n\n\t//printf(\"initial_integrate at timestep %d\\n\", update->ntimestep);\n\n\t/*\n\t * get smoothed velocities from ULSPH pair style\n\t */\n\n\tVector3d *smoothVel = (Vector3d *) force->pair->extract(\"smd/ulsph/smoothVel_ptr\", itmp);\n\n\tif (xsphFlag) {\n\t\tif (smoothVel == NULL) {\n\t\t\terror->one(FLERR, \"fix smd/integrate_ulsph failed to access smoothVel array\");\n\t\t}\n\t}\n\n\tif (igroup == atom->firstgroup)\n\t\tnlocal = atom->nfirst;\n\n\tfor (i = 0; i < nlocal; i++) {\n\t\tif (mask[i] & groupbit) {\n\t\t\tdtfm = dtf / rmass[i];\n\n\t\t\tv[i][0] += dtfm * f[i][0];\n\t\t\tv[i][1] += dtfm * f[i][1];\n\t\t\tv[i][2] += dtfm * f[i][2];\n\n\t\t\tif (vlimit > 0.0) {\n\t\t\t\tvsq = v[i][0] * v[i][0] + v[i][1] * v[i][1] + v[i][2] * v[i][2];\n\t\t\t\tif (vsq > vlimitsq) {\n\t\t\t\t\tscale = sqrt(vlimitsq / vsq);\n\t\t\t\t\tv[i][0] *= scale;\n\t\t\t\t\tv[i][1] *= scale;\n\t\t\t\t\tv[i][2] *= scale;\n\n\t\t\t\t\tvest[i][0] = v[i][0];\n\t\t\t\t\tvest[i][1] = v[i][1];\n\t\t\t\t\tvest[i][2] = v[i][2];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (xsphFlag) {\n\n\t\t\t\t// construct XSPH velocity\n\t\t\t\tvxsph_x = v[i][0] - 0.5 * smoothVel[i](0);\n\t\t\t\tvxsph_y = v[i][1] - 0.5 * smoothVel[i](1);\n\t\t\t\tvxsph_z = v[i][2] - 0.5 * smoothVel[i](2);\n\n\t\t\t\tvest[i][0] = vxsph_x + dtfm * f[i][0];\n\t\t\t\tvest[i][1] = vxsph_y + dtfm * f[i][1];\n\t\t\t\tvest[i][2] = vxsph_z + dtfm * f[i][2];\n\n\t\t\t\tx[i][0] += dtv * vxsph_x;\n\t\t\t\tx[i][1] += dtv * vxsph_y;\n\t\t\t\tx[i][2] += dtv * vxsph_z;\n\n\n\n\n\t\t\t} else {\n\n\t\t\t\t// extrapolate velocity from half- to full-step\n\t\t\t\tvest[i][0] = v[i][0] + dtfm * f[i][0];\n\t\t\t\tvest[i][1] = v[i][1] + dtfm * f[i][1];\n\t\t\t\tvest[i][2] = v[i][2] + dtfm * f[i][2];\n\n\t\t\t\tx[i][0] += dtv * v[i][0];\n\t\t\t\tx[i][1] += dtv * v[i][1];\n\t\t\t\tx[i][2] += dtv * v[i][2];\n\t\t\t}\n\t\t}\n\t}\n}\n\n/* ---------------------------------------------------------------------- */\n\nvoid FixSMDIntegrateUlsph::final_integrate() {\n\tdouble **v = atom->v;\n\tdouble **f = atom->f;\n\tdouble *e = atom->e;\n\tdouble *de = atom->de;\n\tdouble *vfrac = atom->vfrac;\n\tdouble *radius = atom->radius;\n\tdouble *contact_radius = atom->contact_radius;\n\tint *mask = atom->mask;\n\tint nlocal = atom->nlocal;\n\tif (igroup == atom->firstgroup)\n\t\tnlocal = atom->nfirst;\n\tdouble dtfm, vsq, scale;\n\tdouble *rmass = atom->rmass;\n\tdouble vol_increment;\n\tMatrix3d D;\n\n\t/*\n\t * get current number of SPH neighbors from ULSPH pair style\n\t */\n\n\tint itmp;\n\tint *nn = (int *) force->pair->extract(\"smd/ulsph/numNeighs_ptr\", itmp);\n\tif (nn == NULL) {\n\t\terror->one(FLERR, \"fix smd/integrate_ulsph failed to accesss num_neighs array\");\n\t}\n\n\tMatrix3d *L = (Matrix3d *) force->pair->extract(\"smd/ulsph/velocityGradient_ptr\", itmp);\n\tif (L == NULL) {\n\t\terror->one(FLERR, \"fix smd/integrate_ulsph failed to accesss velocityGradient array\");\n\t}\n\n\tfor (int i = 0; i < nlocal; i++) {\n\t\tif (mask[i] & groupbit) {\n\n\t\t\tdtfm = dtf / rmass[i];\n\t\t\tv[i][0] += dtfm * f[i][0];\n\t\t\tv[i][1] += dtfm * f[i][1];\n\t\t\tv[i][2] += dtfm * f[i][2];\n\n\t\t\tif (vlimit > 0.0) {\n\t\t\t\tvsq = v[i][0] * v[i][0] + v[i][1] * v[i][1] + v[i][2] * v[i][2];\n\t\t\t\tif (vsq > vlimitsq) {\n\t\t\t\t\tscale = sqrt(vlimitsq / vsq);\n\t\t\t\t\tv[i][0] *= scale;\n\t\t\t\t\tv[i][1] *= scale;\n\t\t\t\t\tv[i][2] *= scale;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\te[i] += dtf * de[i];\n\n\t\t\tif (adjust_radius_flag) {\n\t\t\t\tif (nn[i] < min_nn) {\n\t\t\t\t\tradius[i] *= adjust_radius_factor;\n\t\t\t\t} else if (nn[i] > max_nn) {\n\t\t\t\t\tradius[i] /= adjust_radius_factor;\n\t\t\t\t}\n\t\t\t\tradius[i] = MAX(radius[i], 1.25 * contact_radius[i]);\n\t\t\t\tradius[i] = MIN(radius[i], 4.0 * contact_radius[i]);\n\n\t\t\t}\n\n\t\t\tD = 0.5 * (L[i] + L[i].transpose());\n\t\t\tvol_increment = vfrac[i] * update->dt * D.trace(); // Jacobian of deformation\n\t\t\tvfrac[i] += vol_increment;\n\t\t}\n\t}\n}\n\n/* ---------------------------------------------------------------------- */\n\nvoid FixSMDIntegrateUlsph::reset_dt() {\n\tdtv = update->dt;\n\tdtf = 0.5 * update->dt * force->ftm2v;\n}\n\n", "meta": {"hexsha": "3dbf453349a539b8d3e50599c846a420e81f9932", "size": 8662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/USER-SMD/fix_smd_integrate_ulsph.cpp", "max_stars_repo_name": "luwei0917/GlpG_Nature_Communication", "max_stars_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T15:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T15:04:55.000Z", "max_issues_repo_path": "src/USER-SMD/fix_smd_integrate_ulsph.cpp", "max_issues_repo_name": "luwei0917/GlpG_Nature_Communication", "max_issues_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_issues_repo_licenses": ["MIT"], "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/USER-SMD/fix_smd_integrate_ulsph.cpp", "max_forks_repo_name": "luwei0917/GlpG_Nature_Communication", "max_forks_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_forks_repo_licenses": ["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.5705521472, "max_line_length": 120, "alphanum_fraction": 0.5357885015, "num_tokens": 2711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19233999260145246}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <cstring>\n\n#include <sstream>\n#include <vector>\n#include <string>\n#include <set>\n#include <iostream>\n#include <fstream>\n#include <time.h>\n#include <limits.h>\n#include <map>\n#include <chrono>\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <functional>\n\n#include <getopt.h>\n\n#include <mutex>\n#include <unistd.h>\n#include <unordered_map>\n#include <unordered_set>\n#include <thread>\n\n#include \"../common/Common.h\"\n#include \"../common/abundance.h\"\n\n#include \"../function/distance.h\"\n#include \"../function/funcAB.h\"\n#include \"../function/cluster.h\"\n\n#include \"../io/ioMatrix.h\"\n#include \"../io/ioHT.h\"\n#include \"../io/ioFastQ.h\"\n\n#include \"../utils/fastq.h\"\n\n#include \"../hash/HashTables.h\"\n#include \"../hash/hash.h\"\n#include \"../hash/lshash.h\"\n\n#include \"../kmer/kmc_api/kmc_file.h\"\n#include \"../kmer/kmc_reader.h\"\n#include \"../kmer/Kmer.h\"\n\n//#include \"../utils/threadpool.hpp\"\n//#include <boost/bind.hpp>\n\n#include \"../utils/alglib-3.17.0/src/statistics.h\"\n#include \"../utils/alglib-3.17.0/src/ap.h\"\n//#include <boost/thread.hpp>\n\nusing namespace std;\n//using namespace boost;\n//using namespace boost::threadpool;\nusing namespace std::chrono;\nusing namespace Core;\nusing namespace Utility;\n\nstruct HyperParams\n{\n  size_t k;\n  float min_similarity, max_similarity;\n  float scale;\n  int cluster_iteration;\n  int max_memory;\n  int count_min;\n  int size_thresh;\n  uint64_t batch_size, extracted_size;\n  float pval_thresh;\n  float kmer_vote;\n  bool verbose;\n  bool kmc, bin, clustering, extracting;\n  unsigned int threads_to_use;\n  string tmp_dir;\n  string input1, input2;\n  string output1, output2;\n  string clust_file_name;\n};\n\nvoid PrintHyperParams(const HyperParams& params) {\n  cout << \"************ kmers Cluster for Subtractiva Assembly Params Setting ****************\" << endl;\n  cout << \"cluster iteration: \" << params.cluster_iteration << endl;\n  cout << \"group1 result prefix: \" << params.output1 << endl;\n  cout << \"group2 result prefix: \" << params.output2 << endl;\n  cout << \"cluster result file: \" << params.clust_file_name << endl;\n  cout << \"group1 input file: \" << params.input1 << endl;\n  cout << \"group2 input file: \" << params.input2 << endl;\n  cout << \"min similarity: \" << params.min_similarity << endl;\n  cout << \"max similarity: \" << params.max_similarity << endl;\n  cout << \"threds to use: \" << params.threads_to_use << endl;\n  cout << \"cluster size threshold: \" << params.size_thresh << endl;\n  cout << \"percentage threshold of differential k-mers in distinctive reads\" << params.kmer_vote << endl;\n  cout << \"********************************************************\" << endl;\n}\n\nvoid kLSH_PrintUsage() {\n  cerr << \"kmerLSHSA \"<< KLSH_VERSION << endl << endl;\n  cerr << \"Clustering of k-mers for Subtractive Assembly \" << endl << endl;\n  cerr << \"Usage: ./kmerLSHSA -a input1 -b input2 -o output1_prefix -p output2_prefix [options]\";\n  cerr << endl << endl <<\n\t\"-a, --input1=STRING             Input filename for metagenome group A\" << endl <<\n  \"-b, --input2=STRING             Input filename for metagenome group B\" << endl <<\n\t\"-o, --output1=STRING            Prefix for output of metagenome A\" << endl <<\n  \"-p, --output2=STRING            Prefix for output of metagenome B\" << endl <<\n  \"-I, --cluster_iteration=INT           number of iteration for LSH <default 100>\" << endl <<\n  \"-N, --min_similarity=FLOAT           minimum threshold of similarity <default 0.85>\" << endl <<\n  \"-X, --min_similarity=FLOAT           maximum threshold of similarity <default 0.95>\" << endl <<\n  \"-K, --kmer_size=INT             Size of k-mers, at most \" << (int) (Kmer::MAX_K-1)<< endl <<\n\t\"-T, --threads_to_use=INT        Number of threads for running KMC etc. <default 8>\" << endl <<\n\t\"-R, --max-memory=INT            Max memory for running KMC <default 12>\" << endl <<\n\t\"-C, --count-min=INT            Min threshold of k-mer count for running KMC <default 2>\" << endl <<\n  \"-S, --size_thresh=INT       Threshold of the size of clustering for T-Test <default 500000>\" << endl <<\n  \"-V, --kmer_vote=FLOAT           Percentage threshold of differential k-mers in distinctive reads <default 0.5>\" << endl <<\n  \"-F, --clust_file_name=STRING           intermediate clustering result file name <default 'clustering_result.txt'>\" << endl <<\n\t\"-M, --mode=STRING                Optional K : run kmc, B : make bin file, C : clustering, E : extract differential reads \" << endl <<\n\t\"    --verbose                   Print messages during run\" << endl << endl <<\n\t\"    --only                   Run only the setting mode \" << endl << endl\n\t;\n}\n\nvoid SetHyperParams(HyperParams* params) {\n  (*params).cluster_iteration = 100;  //TODO: Tune this param.\n  (*params).max_similarity = 0.95;\n  (*params).min_similarity = 0.85;  //TODO: Tune this param.\n  (*params).scale = 1;\n  (*params).threads_to_use = 12;\n  (*params).kmc = true;\n  (*params).bin = true;\n  (*params).extracting = true;\n  (*params).clustering = true;\n  (*params).max_memory = 12;\n  (*params).count_min = 2;\n  (*params).k = 23;\n  (*params).size_thresh = 500000;\n  (*params).kmer_vote = 0.5;\n  (*params).tmp_dir = \"tmp/\";\n  (*params).clust_file_name = \"clustering_result.txt\";\n}\n\nvoid ParsingCommands(int argc, char*argv[], HyperParams* params) {\n  int verbose_flag = 0;\n  int only_flag = 0;\n  string mode = \"\";\n  const char* opt_string = \"o:p:a:b:H:I:N:X:C:T:K:S:P:V:F:M:\";\n  static struct option long_options[] =\n  {\n    {\"verbose\", no_argument,  &verbose_flag, 1},\n    {\"only\", no_argument,  &only_flag, 1},\n    {\"output1\", required_argument, 0, 'o'},\n    {\"output2\", required_argument, 0, 'p'},\n  \t{\"input1\", required_argument, 0, 'a'},\n    {\"input2\", required_argument, 0, 'b'},\n    {\"cluster_iteration\", optional_argument, 0, 'I'},\n    {\"min_similarity\", optional_argument, 0, 'N'},\n    {\"max_similarity\", optional_argument, 0, 'X'},\n  \t{\"max-memory\", optional_argument, 0, 'R'},\n  \t{\"count-min\", optional_argument, 0, 'C'},\n  \t{\"threads_to_use\", optional_argument, 0, 'T'},\n    {\"kmer_size\", optional_argument, 0, 'K'},\n    {\"size_thresh\", optional_argument, 0, 'S'},\n    {\"kmer_vote\", optional_argument, 0, 'V'},\n    {\"tmp_dir\", optional_argument, 0, 'D'},\n    {\"clust_file_name\", optional_argument, 0, 'F'},\n    {\"mode\", optional_argument, 0, 'M'},\n  \t{0,0,0,0}\n  };\n\n    int option_index = 0;\n    int c;\n    stringstream ss;\n    while (true) {\n      c = getopt_long(argc,argv,opt_string, long_options, &option_index);\n\n      if (c == -1) {\n        break;\n      }\n      switch (c) {\n        case 'o':\n          (*params).output1 = optarg;\n          break;\n        case 'p':\n          (*params).output2 = optarg;\n          break;\n        case 'a':\n          (*params).input1 = optarg;\n  \t      break;\n        case 'b':\n          (*params).input2 = optarg;\n  \t      break;\n        case 'I':\n          (*params).cluster_iteration = atoi(optarg);\n          break;\n      \tcase 'N':\n          (*params).min_similarity = atof(optarg);\n          break;\n        case 'X':\n          (*params).max_similarity = atof(optarg);\n          break;\n        case 'R':\n          (*params).max_memory = atoi(optarg);\n          break;\n        case 'C':\n          (*params).count_min = atoi(optarg);\n          break;\n        case 'T':\n          (*params).threads_to_use = atoi(optarg);\n          break;\n        case 'K':\n          (*params).k = atoi(optarg);\n          break;\n        case 'S':\n          (*params).size_thresh = atoi(optarg);\n          break;\n        case 'V':\n          (*params).kmer_vote = atof(optarg);\n          break;\n        case 'D':\n          (*params).tmp_dir = optarg;\n          break;\n        case 'F':\n          (*params).clust_file_name = optarg;\n          break;\n        case 'M':\n          mode = optarg;\n          break;\n        default:\n          break;\n      }\n    }\n    if (verbose_flag) {\n      (*params).verbose = true;\n    }\n\n    if (only_flag){\n      if (mode == \"K\"){\n        (*params).bin = false;\n        (*params).clustering = false;\n        (*params).extracting = false;\n      }\n      else if (mode == \"B\"){\n        (*params).kmc = false;\n        (*params).clustering = false;\n        (*params).extracting = false;\n      }\n      else if (mode == \"C\"){\n        (*params).bin = false;\n        (*params).kmc = false;\n        (*params).extracting = false;\n      }\n      else if (mode == \"E\"){\n        (*params).bin = false;\n        (*params).kmc = false;\n        (*params).clustering = false;\n      }\n    } else {\n      if (mode == \"B\"){\n        (*params).kmc = false;\n      }\n      else if (mode == \"C\"){\n        (*params).bin = false;\n        (*params).kmc = false;\n      }\n      else if (mode == \"E\"){\n        (*params).bin = false;\n        (*params).kmc = false;\n        (*params).clustering = false;\n      }\n    }\n  }\n\nvoid init_clustering(vector<Abundance*>* unknown_abundance_ptr, int dim, float min_similarity, float max_similarity, int cluster_iteration, unsigned int threads_to_use, int tot_sample, size_t kmap_size, vector<float_t> v_kmers, int bucket_size_threshold, string tmp_dir, const uint64_t batch_thresh, bool verbose){\n  auto start_time = chrono::high_resolution_clock::now();\n  ifstream inStream(\"kmer_count.bin\", ios::binary);\n  vector<Abundance*> out_abundance, local_abundance, *out_abundance_ptr, *local_abundance_ptr;\n  local_abundance_ptr = & local_abundance;\n  out_abundance_ptr = & out_abundance;\n  float similarity = min_similarity;\n  //const uint64_t batch_thresh = 100000000; //if changed, remember to change 2D array parameter vec_count in readHT and batchTest\n  uint64_t batch_size;\n  string read_tmp_file = \"\", write_tmp_file = \"\", read_tmp_file_clust = \"\", write_tmp_file_clust = \"\";\n  deque<int> tmp_files;\n  size_t total_size = 0;\n\n  //initialize 2D array\n  uint16_t** ary_count = new uint16_t*[tot_sample];\n  for (int i=0; i < tot_sample; i++) {\n  \tary_count[i] = new uint16_t[batch_thresh];\n  }\n\n  if (verbose) {\n    cout << \"\\n...Loading and testing in batches...\" << endl;\n\t  cout << v_kmers.size() << endl;\n  }\n\n  //load and test kmer count info in batches\n  uint64_t kcnt_rem = kmap_size;\n  streamoff batch_offset = 0;\n  int iter = kmap_size / batch_thresh;\n  int tmp = 0;\n  if(verbose){\n    cout << \"iteration : \" << iter << \" kmap_size : \" << kmap_size << endl;\n  }\n  //First, read the binary file of k-mers hash table. \n  //Clustering the block of hash table\n  //Saving to the other binary file.\n  for(int i = 0; i< iter+1 ; i++){\n    if(i == iter){\n      //batch_offset = batch_thresh*i;\n      batch_size = kcnt_rem - batch_offset;\n    }\n    else{\n      batch_size = batch_thresh;\n      //batch_offset = batch_thresh * i;\n    }\n    //cout << \"i: \" << i << \" batch_size : \" << batch_size << \" batch_offset : \" << batch_offset << endl;\n    ReadHT(inStream, tot_sample, kmap_size, ary_count, batch_size, batch_offset);\n    IOMat::convertHTMat(ary_count, v_kmers,  tot_sample, verbose, batch_size, batch_offset, local_abundance_ptr);\n    Cluster(local_abundance_ptr, similarity, max_similarity,  cluster_iteration,  threads_to_use, dim, bucket_size_threshold, verbose);\n    total_size += local_abundance.size();\n    //////write result on tmp bin\n    if(i == 0){\n      write_tmp_file = tmp_dir+to_string(tmp)+\".bin\";\n      write_tmp_file_clust = write_tmp_file+\".clust\";\n      IOMat::SaveResult(local_abundance_ptr,  write_tmp_file_clust, true, 0, verbose);\n      IOMat::SaveBinary(local_abundance_ptr, write_tmp_file, true, 0, verbose);\n      tmp++;\n    }\n    else{\n      IOMat::SaveResult(local_abundance_ptr,  write_tmp_file_clust, false, 0, verbose);\n      IOMat::SaveBinary(local_abundance_ptr, write_tmp_file, false,  0, verbose);\n    }\n\t  for(size_t j = 0; j< local_abundance.size(); j++){\n      delete local_abundance[j];\n    }\n    vector<Abundance*>().swap(local_abundance);\n\t  batch_offset += batch_size;\n    if (verbose) {\n  \t  cout << \"# loaded kmers: \" << batch_offset << endl;\n  \t}\n  }\n  \n  for (int i = 0; i < tot_sample; ++i) {\n  \tdelete [] ary_count[i];\n  }\n  delete [] ary_count;\n  inStream.close();\n\n  /////read temporary directory files/////////\n  while (total_size > batch_thresh*5){\n    similarity -=0.001;\n    batch_offset = 0;\n    read_tmp_file = write_tmp_file;\n    read_tmp_file_clust = write_tmp_file_clust;\n    write_tmp_file = tmp_dir+to_string(tmp)+\".bin\";\n    write_tmp_file_clust = write_tmp_file+\".clust\";\n    tmp++;\n    iter = total_size / batch_thresh;\n    kcnt_rem = total_size;\n    total_size = 0;\n    for(int i = 0; i< iter+1; i++){\n      if (i == iter ){\n        //batch_offset = batch_thresh*i;\n        batch_size = kcnt_rem - batch_offset;\n      }\n      else{\n        //batch_offset = batch_thresh*i;\n        batch_size = batch_thresh;\n      }\n      cout << \"i: \" << i << \" batch_size : \" << batch_size << \" batch_offset : \" << batch_offset << endl;\n      IOMat::ReadCluster(local_abundance_ptr, dim, read_tmp_file, batch_offset, batch_size, verbose);\n      //IOMat::ReadCluster(local_abundance_ptr, read_tmp_file+\".clust\", batch_offset, batch_size, verbose);\n      Cluster(local_abundance_ptr, similarity, max_similarity, cluster_iteration+4,  threads_to_use, dim, bucket_size_threshold, verbose);\n      total_size += local_abundance.size();\n\n      if(i == 0){\n        IOMat::SaveResult(local_abundance_ptr,  write_tmp_file_clust, true, 0, verbose);\n        IOMat::SaveBinary(local_abundance_ptr, write_tmp_file, true, 0, verbose);\n      }\n      else{\n        IOMat::SaveResult(local_abundance_ptr,  write_tmp_file_clust, false, 0, verbose);\n        IOMat::SaveBinary(local_abundance_ptr, write_tmp_file, false, 0, verbose);\n      }\n    \n      for(size_t j = 0; j< local_abundance.size(); j++){\n        delete local_abundance[j];\n      }\n      vector<Abundance*>().swap(local_abundance);\n\t    batch_offset += batch_size;\n\t    if (verbose) {\n      \tcout << \"# loaded kmers: \" << batch_offset << endl;\n      }\n    }\n    ///////////delete read temporary file ///////////////\n    if(remove(read_tmp_file.c_str()) != 0){\n      perror(\"The temporary file deletion failed\");\n    }\n    else{\n      cout << read_tmp_file << \"file are removed\" << endl;\n    }\n    if(remove(read_tmp_file_clust.c_str()) != 0){\n      perror(\"The temporary file deletion failed\");\n    }\n    else{\n      cout << read_tmp_file_clust << \"file are removed\" << endl;\n    }\n  }\n  \n  read_tmp_file = write_tmp_file;\n  read_tmp_file_clust = write_tmp_file_clust;\n  IOMat::ReadClusterAll(local_abundance_ptr, dim, read_tmp_file, verbose);\n  //IOMat::ReadClusterAll(local_abundance_ptr, read_tmp_file+\".clust\");\n\n  unknown_abundance_ptr->swap(local_abundance);\n  vector<Abundance*>().swap(local_abundance);\n\n  \n  auto end_time = chrono::high_resolution_clock::now();\n  auto elapsed_read = chrono::duration_cast<std::chrono::duration<float>>(end_time - start_time).count();\n  \n  if(verbose){\n    cout << \"Finish conversion matrix\" << endl;\n\t  cout << \"reading Matrix takes secs:\\t\" << elapsed_read << endl;\n  }\n  \n}\n\nvoid kmerCluster(HyperParams& params){\n  vector<string> samples1, samples2, kmc_names1, kmc_names2 ;\n  vector<string> samples, kmc_names;\n  vector<float_t> v_kmers;\n  int tot_sample, num_sample1, num_sample2;\n  Kmer::set_k(params.k);\n  size_t kmap_size;\n  float_t kmer_coverage;\n  int bucket_size_threshold = BUCKET_SIZE_THRESH;\n  const uint64_t batch_thresh = BATCH_THRESH;\n  uint64_t extracted_size_thresh = EXTRACTED_SIZE_THRESH;\n\n  auto start_time_total = chrono::high_resolution_clock::now();\n\n  GetInput(params.input1, samples1, kmc_names1);\n  GetInput(params.input2, samples2, kmc_names2);\n\n  samples = samples1;\n\tsamples.insert(samples.end(), samples2.begin(), samples2.end());\n\tkmc_names = kmc_names1;\n\tkmc_names.insert(kmc_names.end(), kmc_names2.begin(), kmc_names2.end());\n\n\tnum_sample1 = samples1.size();\n\tnum_sample2 = samples2.size();\n\ttot_sample = samples.size();\n\tif (params.verbose) {\n\t\tcout << endl << \"# samples in group 1: \" << num_sample1 << endl << \"# samples in group 2: \" << num_sample2 << endl;\n\t}\n\n  if (params.kmc || params.bin){\n     buildKHtable( &v_kmers, &kmap_size,   params.kmc, params.verbose, params.k, params.count_min, params.threads_to_use, params.max_memory, samples, kmc_names);\n  }\n\n\n  if (params.clustering){\n    //store v_kmer without buildKHtable\n    if(!params.bin){\n      v_kmers.reserve(tot_sample);\n      ifstream logStream(\"kmer_count.log\");\n      string line;\n      getline(logStream, line);\n      istringstream ss(line);\n      ss >> kmap_size;\n      for (int i = 0; i < tot_sample; i++) {\n        ss >> kmer_coverage;\n        v_kmers.push_back(kmer_coverage/kmap_size);\n      }\n\t  }\n  \n    // Creating a directory\n    if (mkdir((params.tmp_dir).c_str(), 0777) == -1)\n        cerr << \"Error :  \" << strerror(errno) << endl;\n  \n    else\n        cout << \"Temporary Directory created\";\n\n    vector<Abundance*> unknown_abundance, *unknown_abundance_ptr;\n    unknown_abundance_ptr = & unknown_abundance;\n\n    init_clustering(unknown_abundance_ptr, tot_sample, params.max_similarity, 0.97, 1, params.threads_to_use, tot_sample, kmap_size, v_kmers, bucket_size_threshold, params.tmp_dir, batch_thresh, params.verbose);\n\n  \n    Cluster(unknown_abundance_ptr, params.min_similarity, params.max_similarity, params.cluster_iteration, params.threads_to_use,tot_sample, bucket_size_threshold, params.verbose);\n\n    \n    // Save clusters.\n    auto start_time_save_result = chrono::high_resolution_clock::now();\n    if(params.verbose){\n      cout << \"Saving cluster results starts: \" << endl;\n    }\n    IOMat::SaveResult(unknown_abundance_ptr,  params.clust_file_name+\".clust\", true, 5, params.verbose);\n    IOMat::SaveBinary(unknown_abundance_ptr, params.clust_file_name, true, 5, params.verbose);\n    auto end_time = chrono::high_resolution_clock::now();\n    auto elapsed_read = chrono::duration_cast<std::chrono::duration<float>>(end_time - start_time_save_result).count();\n    if(params.verbose){\n      cout << \"Save cluster results takes secs: \" << elapsed_read << endl;\n    }\n    // Release allocated memory for spectra w/ charge; save pointers to spectra\n    // w/o charge to variable 'spectra_of_no_charge'.\n    auto start_time = chrono::high_resolution_clock::now();\n    if(params.verbose){\n      cout << \"Releasing memory starts.\" << endl;\n    }\n    for(size_t i = 0; i< unknown_abundance.size(); i++){\n        delete unknown_abundance[i];\n    }\n\n    end_time = chrono::high_resolution_clock::now();\n    elapsed_read = chrono::duration_cast<std::chrono::duration<float>>(end_time - start_time).count();\n    if(params.verbose){\n      cout << \"Releasing memory takes: \" << elapsed_read << endl;\n    }\n\n  }\n  if (params.extracting){\n    if(params.verbose){\n      cout << \"Start to extract the differential reads from raw data\" << endl;\n    }\n    auto start_time_extracting = chrono::high_resolution_clock::now();\n    vector<Abundance*> clusteredab, *clusteredab_ptr;\n    clusteredab_ptr = &clusteredab;\n\n    uset_t g_kmer1, g_kmer2, *g_kmer1_ptr, *g_kmer2_ptr;  //differential kmers for two groups in comparison\n\t  g_kmer1_ptr = &g_kmer1;\n\t  g_kmer2_ptr = &g_kmer2;\n\n    unordered_set<uint64_t> g_kmer_id1, g_kmer_id2, *g_kmer_id1_ptr, *g_kmer_id2_ptr;\n    g_kmer_id1_ptr = &g_kmer_id1;\n    g_kmer_id2_ptr = &g_kmer_id2;\n\n    string head = \"\";\n    int dim = 0;\n    //read clustering result and do statistical testing(WRS)\n    IOMat::ReadClusterAll(clusteredab_ptr, tot_sample, params.clust_file_name, params.verbose);\n    AB::dynamicST(g_kmer_id1_ptr, g_kmer_id2_ptr, clusteredab_ptr, num_sample1, num_sample2, params.pval_thresh, params.size_thresh, extracted_size_thresh, params.verbose);\n    for(size_t i; i< clusteredab.size(); i++){\n      delete clusteredab[i];\n    }\n    \n    if(params.verbose){\n      cout << \"# of differential kmers in group A : \" << g_kmer_id1.size() << endl;\n      cout << \"# of differential kmers in group B : \" << g_kmer_id2.size() << endl;\n    }\n    //read kmers in kvec to restore the original kmer order in kmap\n    \n    ifstream logStream(\"kmer_count.log\");\n    string line;\n    getline(logStream, line);\n    istringstream ss(line);\n    ss >> kmap_size;\n    logStream.close();\n\n    ifstream kmer_file(\"kmer_set.hex\");\n\t  //kvec.resize(kmap_size);\n\t  uint8_t bytes[(Kmer::MAX_K)/4];\n\t  size_t idx_k = 0;\n\n\t  for (size_t i = 0; i < kmap_size; i++) {\n\t    kmer_file.read(reinterpret_cast<char*> (&bytes[0]), sizeof(bytes[0])*(Kmer::MAX_K)/4);\n\t    Kmer km(bytes);\n      \n      if(g_kmer_id1.find(i) != g_kmer_id1.end() ){\n        g_kmer1.insert(km);\n      }\n      else if(g_kmer_id2.find(i) != g_kmer_id2.end()){\n        g_kmer2.insert(km);\n      }\n\t    idx_k ++;\n    }\n\n    //clear the id sets and close file\n    unordered_set<uint64_t>().swap(g_kmer_id1);\n    unordered_set<uint64_t>().swap(g_kmer_id2);\n    kmer_file.close();\n\n    IOFQ::Extracting(samples1, g_kmer1_ptr, params.output1, params.threads_to_use, params.kmer_vote, params.verbose);\n    IOFQ::Extracting(samples2, g_kmer2_ptr, params.output2, params.threads_to_use, params.kmer_vote, params.verbose);\n\n    // Report time for all the procedures done above.\n    auto end_time_extracting = chrono::high_resolution_clock::now();\n    auto elapsed_read = chrono::duration_cast<std::chrono::duration<float>>(end_time_extracting - start_time_extracting).count();\n    if(params.verbose){\n      cout << \"extracting reads takes (secs): \" << elapsed_read << endl;\n    }\n  }\n\n  // Report time for all the procedures done above.\n  auto end_time = chrono::high_resolution_clock::now();\n  auto elapsed_read = chrono::duration_cast<std::chrono::duration<float>>(end_time - start_time_total).count();\n  cout << \"kmerLSHSA algorithm in total takes (secs): \" << elapsed_read << endl;\n  \n}\n\nint main(int argc, char **argv) {\n\tif (argc < 2) {\n\t\tkLSH_PrintUsage();\n\t} else {\n    \tHyperParams params;\n    \tSetHyperParams(&params);\n    \tParsingCommands(argc, argv, &params);\n    \tPrintHyperParams(params);\n    \tkmerCluster(params);\n\t}\n\n}\n", "meta": {"hexsha": "3fe04f470aa907d86387c5a0474d241a178329c3", "size": 21902, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/app/kmerLSH.cc", "max_stars_repo_name": "mgtools/kmerLSHSA", "max_stars_repo_head_hexsha": "dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1", "max_stars_repo_licenses": ["Intel", "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/app/kmerLSH.cc", "max_issues_repo_name": "mgtools/kmerLSHSA", "max_issues_repo_head_hexsha": "dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1", "max_issues_repo_licenses": ["Intel", "MIT"], "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/app/kmerLSH.cc", "max_forks_repo_name": "mgtools/kmerLSHSA", "max_forks_repo_head_hexsha": "dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1", "max_forks_repo_licenses": ["Intel", "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.3828756058, "max_line_length": 314, "alphanum_fraction": 0.6397132682, "num_tokens": 5852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.1923399889914721}}
{"text": "\n#include <ripple/beast/clock/manual_clock.h>\n#include <ripple/beast/unit_test.h>\n#include <test/csf.h>\n#include <utility>\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <algorithm>\n#include <sstream>\n#include <fstream>\n#include <string>\n\nnamespace ripple {\nnamespace test {\n\n\nclass DistributedValidators_test : public beast::unit_test::suite\n{\n\n    void\n    completeTrustCompleteConnectFixedDelay(\n            std::size_t numPeers,\n            std::chrono::milliseconds delay = std::chrono::milliseconds(200),\n            bool printHeaders = false)\n    {\n        using namespace csf;\n        using namespace std::chrono;\n\n        std::string const prefix =\n                \"DistributedValidators_\"\n                \"completeTrustCompleteConnectFixedDelay\";\n        std::fstream\n                txLog(prefix + \"_tx.csv\", std::ofstream::app),\n                ledgerLog(prefix + \"_ledger.csv\", std::ofstream::app);\n\n        log << prefix << \"(\" << numPeers << \",\" << delay.count() << \")\"\n            << std::endl;\n\n        BEAST_EXPECT(numPeers >= 1);\n\n        Sim sim;\n        PeerGroup peers = sim.createGroup(numPeers);\n\n        peers.trust(peers);\n\n        peers.connect(peers, delay);\n\n        TxCollector txCollector;\n        LedgerCollector ledgerCollector;\n        auto colls = makeCollectors(txCollector, ledgerCollector);\n        sim.collectors.add(colls);\n\n        sim.run(1);\n\n        std::chrono::nanoseconds const simDuration = 10min;\n        std::chrono::nanoseconds const quiet = 10s;\n        Rate const rate{100, 1000ms};\n\n        HeartbeatTimer heart(sim.scheduler);\n\n        auto peerSelector = makeSelector(peers.begin(),\n                                     peers.end(),\n                                     std::vector<double>(numPeers, 1.),\n                                     sim.rng);\n        auto txSubmitter = makeSubmitter(ConstantDistribution{rate.inv()},\n                                     sim.scheduler.now() + quiet,\n                                     sim.scheduler.now() + simDuration - quiet,\n                                     peerSelector,\n                                     sim.scheduler,\n                                     sim.rng);\n\n        heart.start();\n        sim.run(simDuration);\n\n\n        log << std::right;\n        log << \"| Peers: \"<< std::setw(2) << peers.size();\n        log << \" | Duration: \" << std::setw(6)\n            << duration_cast<milliseconds>(simDuration).count() << \" ms\";\n        log << \" | Branches: \" << std::setw(1) << sim.branches();\n        log << \" | Synchronized: \" << std::setw(1)\n            << (sim.synchronized() ? \"Y\" : \"N\");\n        log << \" |\" << std::endl;\n\n        txCollector.report(simDuration, log, true);\n        ledgerCollector.report(simDuration, log, false);\n\n        std::string const tag = std::to_string(numPeers);\n        txCollector.csv(simDuration, txLog, tag, printHeaders);\n        ledgerCollector.csv(simDuration, ledgerLog, tag, printHeaders);\n\n        log << std::endl;\n    }\n\n    void\n    completeTrustScaleFreeConnectFixedDelay(\n            std::size_t numPeers,\n            std::chrono::milliseconds delay = std::chrono::milliseconds(200),\n            bool printHeaders = false)\n    {\n        using namespace csf;\n        using namespace std::chrono;\n\n        std::string const prefix =\n                \"DistributedValidators__\"\n                \"completeTrustScaleFreeConnectFixedDelay\";\n        std::fstream\n                txLog(prefix + \"_tx.csv\", std::ofstream::app),\n                ledgerLog(prefix + \"_ledger.csv\", std::ofstream::app);\n\n        log << prefix << \"(\" << numPeers << \",\" << delay.count() << \")\"\n            << std::endl;\n\n        int const numCNLs    = std::max(int(1.00 * numPeers), 1);\n        int const minCNLSize = std::max(int(0.25 * numCNLs),  1);\n        int const maxCNLSize = std::max(int(0.50 * numCNLs),  1);\n        BEAST_EXPECT(numPeers >= 1);\n        BEAST_EXPECT(numCNLs >= 1);\n        BEAST_EXPECT(1 <= minCNLSize\n                && minCNLSize <= maxCNLSize\n                && maxCNLSize <= numPeers);\n\n        Sim sim;\n        PeerGroup peers = sim.createGroup(numPeers);\n\n        peers.trust(peers);\n\n        std::vector<double> const ranks =\n                sample(peers.size(), PowerLawDistribution{1, 3}, sim.rng);\n        randomRankedConnect(peers, ranks, numCNLs,\n                std::uniform_int_distribution<>{minCNLSize, maxCNLSize},\n                sim.rng, delay);\n\n        TxCollector txCollector;\n        LedgerCollector ledgerCollector;\n        auto colls = makeCollectors(txCollector, ledgerCollector);\n        sim.collectors.add(colls);\n\n        sim.run(1);\n\n        std::chrono::nanoseconds simDuration = 10min;\n        std::chrono::nanoseconds quiet = 10s;\n        Rate rate{100, 1000ms};\n\n        HeartbeatTimer heart(sim.scheduler);\n\n        auto peerSelector = makeSelector(peers.begin(),\n                                     peers.end(),\n                                     std::vector<double>(numPeers, 1.),\n                                     sim.rng);\n        auto txSubmitter = makeSubmitter(ConstantDistribution{rate.inv()},\n                                     sim.scheduler.now() + quiet,\n                                     sim.scheduler.now() + simDuration - quiet,\n                                     peerSelector,\n                                     sim.scheduler,\n                                     sim.rng);\n\n        heart.start();\n        sim.run(simDuration);\n\n\n        log << std::right;\n        log << \"| Peers: \"<< std::setw(2) << peers.size();\n        log << \" | Duration: \" << std::setw(6)\n            << duration_cast<milliseconds>(simDuration).count() << \" ms\";\n        log << \" | Branches: \" << std::setw(1) << sim.branches();\n        log << \" | Synchronized: \" << std::setw(1)\n            << (sim.synchronized() ? \"Y\" : \"N\");\n        log << \" |\" << std::endl;\n\n        txCollector.report(simDuration, log, true);\n        ledgerCollector.report(simDuration, log, false);\n\n        std::string const tag = std::to_string(numPeers);\n        txCollector.csv(simDuration, txLog, tag, printHeaders);\n        ledgerCollector.csv(simDuration, ledgerLog, tag, printHeaders);\n\n        log << std::endl;\n    }\n\n    void\n    run() override\n    {\n        std::string const defaultArgs = \"5 200\";\n        std::string const args = arg().empty() ? defaultArgs : arg();\n        std::stringstream argStream(args);\n\n        int maxNumValidators = 0;\n        int delayCount(200);\n        argStream >> maxNumValidators;\n        argStream >> delayCount;\n\n        std::chrono::milliseconds const delay(delayCount);\n\n        log << \"DistributedValidators: 1 to \" << maxNumValidators << \" Peers\"\n            << std::endl;\n\n        \n        completeTrustCompleteConnectFixedDelay(1, delay, true);\n        for(int i = 2; i <= maxNumValidators; i++)\n        {\n            completeTrustCompleteConnectFixedDelay(i, delay);\n        }\n\n        \n        completeTrustScaleFreeConnectFixedDelay(1, delay, true);\n        for(int i = 2; i <= maxNumValidators; i++)\n        {\n            completeTrustScaleFreeConnectFixedDelay(i, delay);\n        }\n    }\n};\n\nBEAST_DEFINE_TESTSUITE_MANUAL_PRIO(DistributedValidators, consensus, ripple, 2);\n\n}  \n}  \n\n\n\n\n\n\n", "meta": {"hexsha": "fabb6b9953806026f7574e0d192c2180d3c6db39", "size": 7276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/consensus/DistributedValidatorsSim_test.cpp", "max_stars_repo_name": "dfm-official/dfm", "max_stars_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_stars_repo_licenses": ["ISC"], "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/test/consensus/DistributedValidatorsSim_test.cpp", "max_issues_repo_name": "dfm-official/dfm", "max_issues_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_issues_repo_licenses": ["ISC"], "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/consensus/DistributedValidatorsSim_test.cpp", "max_forks_repo_name": "dfm-official/dfm", "max_forks_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_forks_repo_licenses": ["ISC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3377777778, "max_line_length": 80, "alphanum_fraction": 0.5421935129, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.1923399817715115}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n\n#include <boost/program_options.hpp>\n#include <poplar/Engine.hpp>\n#include <poplar/OptionFlags.hpp>\n#include <poplibs_support/TestDevice.hpp>\n#include <poplibs_test/Util.hpp>\n#include <poplin/codelets.hpp>\n#include <popops/ElementWise.hpp>\n#include <popops/Expr.hpp>\n#include <popops/codelets.hpp>\n#include <poputil/TileMapping.hpp>\n#include <poputil/exceptions.hpp>\n\n#include <sstream>\n#include <utility>\n#include <vector>\n\nusing namespace poplibs_support;\nusing namespace popops;\nusing namespace popops::expr;\n\nstatic DeviceType deviceType;\n\nstd::pair<std::vector<float>, std::vector<float>>\nexecuteExpr(const Expr &expression, const poplar::Type &dType, bool inPlace,\n            bool enableFusedCodelets = true) {\n  auto device = createTestDevice(TEST_TARGET);\n  const auto &target = device.getTarget();\n  poplar::Graph g(device.getTarget());\n  popops::addCodelets(g);\n\n  const std::vector<unsigned> hostInA = {1, 2, 3, 4, 5, 6, 7, 8};\n\n  const std::vector<unsigned> hostInC = hostInA;\n\n  const std::vector<unsigned> hostInB = {8, 7, 6, 5, 4, 3, 2, 1};\n\n  unsigned size = hostInA.size();\n\n  auto a = g.addVariable(dType, {size}, \"inputa\");\n  g.setTileMapping(a, 0);\n  auto b = g.addVariable(dType, {size}, \"inputb\");\n  g.setTileMapping(b, 0);\n  auto c = g.addVariable(dType, {size}, \"inputc\");\n  g.setTileMapping(c, 0);\n\n  auto rawBufSize = target.getTypeSize(dType) * size;\n\n  std::vector<char> rawInA(rawBufSize);\n  std::vector<char> rawInB(rawBufSize);\n  std::vector<char> rawInC(rawBufSize);\n  std::vector<char> rawOutOpt(rawBufSize);\n  std::vector<char> rawOutNoOpt(rawBufSize);\n\n  poplibs_test::util::copy(target, hostInA.data(), size, dType,\n                           reinterpret_cast<void *>(rawInA.data()));\n  poplibs_test::util::copy(target, hostInC.data(), size, dType,\n                           reinterpret_cast<void *>(rawInC.data()));\n\n  poplar::OptionFlags enableOptims = {\n      {\"enableExpressionOptimizations\", \"true\"}};\n  poplar::OptionFlags disableOptims = {\n      {\"enableExpressionOptimizations\", \"false\"}};\n\n  enableOptims.set(\"enableGenerateCodelet\",\n                   enableFusedCodelets ? \"true\" : \"false\");\n\n  poplar::program::Sequence progOpt;\n  poplar::Tensor tOpt;\n  if (!inPlace) {\n    tOpt =\n        popops::map(g, expression, {a, b}, progOpt, \"test1Opt\", enableOptims);\n  } else {\n    popops::mapInPlace(g, expression, {a, b}, progOpt, \"test1Opt\",\n                       enableOptims);\n  }\n\n  poplar::program::Sequence progNoOpt;\n  poplar::Tensor tNoOpt;\n  if (!inPlace) {\n    tNoOpt = popops::map(g, expression, {c, b}, progNoOpt, \"test1NoOpt\",\n                         disableOptims);\n  } else {\n    popops::mapInPlace(g, expression, {c, b}, progNoOpt, \"test1NoOpt\",\n                       disableOptims);\n  }\n  g.createHostWrite(\"inA\", a);\n  g.createHostWrite(\"inC\", c);\n  g.createHostWrite(\"inB\", b);\n  if (!inPlace) {\n    g.createHostRead(\"tOpt\", tOpt);\n    g.createHostRead(\"tNoOpt\", tNoOpt);\n  } else {\n    g.createHostRead(\"tOpt\", a);\n    g.createHostRead(\"tNoOpt\", c);\n  }\n\n  poplar::program::Sequence controlProg(\n      {std::move(progOpt), std::move(progNoOpt)});\n\n  poplar::Engine e(g, controlProg);\n  device.bind([&](const poplar::Device &d) {\n    e.load(d);\n    e.writeTensor(\"inA\", rawInA.data(), rawInA.data() + rawInA.size());\n    e.writeTensor(\"inC\", rawInC.data(), rawInC.data() + rawInC.size());\n    e.writeTensor(\"inB\", rawInB.data(), rawInB.data() + rawInB.size());\n    e.run();\n    e.readTensor(\"tOpt\", rawOutOpt.data(), rawOutOpt.data() + rawOutOpt.size());\n    e.readTensor(\"tNoOpt\", rawOutNoOpt.data(),\n                 rawOutNoOpt.data() + rawOutNoOpt.size());\n  });\n\n  std::vector<float> hostOutOpt(size);\n  poplibs_test::util::copy(target, dType,\n                           reinterpret_cast<void *>(rawOutOpt.data()),\n                           hostOutOpt.data(), size);\n  std::vector<float> hostOutNoOpt(size);\n  poplibs_test::util::copy(target, dType,\n                           reinterpret_cast<void *>(rawOutNoOpt.data()),\n                           hostOutNoOpt.data(), size);\n\n  return std::make_pair(hostOutOpt, hostOutNoOpt);\n}\n\nint main(int argc, char **argv) {\n  namespace po = boost::program_options;\n\n  std::string test;\n  poplar::Type dataType;\n  bool rhsIsSigned, powerOfTwo, inPlace;\n\n  po::options_description desc(\"Options\");\n  // clang-format off\n  desc.add_options() (\"help\", \"Print help\")\n    (\"device-type\",\n     po::value<DeviceType>(&deviceType)->required(),\n     \"Device Type\")\n    (\"rhs-is-signed\",\n     po::value<bool>(&rhsIsSigned)->required(),\n     \"Right hand side is signed\")     \n    (\"power-of-two\",\n     po::value<bool>(&powerOfTwo)->required(),\n     \"right hand side is power of two\")\n    (\"data-type\",\n     po::value<poplar::Type>(&dataType)->required(),\n     \"Data Type: unsigned, int\")\n    (\"in-place\",\n     po::value<bool>(&inPlace)->required(),\n     \"operation is inplace\")\n    (\"test-type\",\n     po::value<std::string>(&test)->required(),\n     \"The test to run: REMAINDER | DIVIDE \");\n  // clang-format on\n\n  po::variables_map vm;\n  try {\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\\n\";\n      return 1;\n    }\n    po::notify(vm);\n  } catch (std::exception &e) {\n    std::cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  // Only allow tests for types for which codelets are instantiated\n  if (dataType != poplar::UNSIGNED_INT && dataType != poplar::INT) {\n    std::cerr << \"Unsupported data type\\n\";\n    return 1;\n  }\n\n  std::unique_ptr<popops::expr::Expr> subExpr;\n\n  if (test == \"REMAINDER\") {\n    if (rhsIsSigned) {\n      int rhsValue = powerOfTwo ? 4 : 3;\n      auto e = Rem(_2, Const(rhsValue));\n      subExpr = e.clone();\n    } else {\n      unsigned rhsValue = powerOfTwo ? 4 : 3;\n      auto e = Rem(_2, Const(rhsValue));\n      subExpr = e.clone();\n    }\n  } else if (test == \"DIVIDE\") {\n    if (rhsIsSigned) {\n      int rhsValue = powerOfTwo ? 4 : 3;\n      auto e = Divide(_2, Const(rhsValue));\n      subExpr = e.clone();\n    } else {\n      unsigned rhsValue = powerOfTwo ? 4 : 3;\n      auto e = Divide(_2, Const(rhsValue));\n      subExpr = e.clone();\n    }\n  } else {\n    std::cerr << \"Unsupported test type \\n\";\n    return 1;\n  }\n  auto mainExpr = Add(Add(Add(_1, _2), *subExpr), Const(3));\n  auto [opt, noOpt] = executeExpr(mainExpr, dataType, inPlace);\n  for (unsigned i = 0; i != opt.size(); ++i) {\n    if (opt[i] != noOpt[i]) {\n      std::cerr << \"mismatch at position \" << i << \" expected \" << noOpt[i];\n      std::cerr << \" actual \" << opt[i];\n      return 1;\n    }\n  }\n  return 0;\n}", "meta": {"hexsha": "3ed0059b99a1fac05fe5f076599cc503f686cbf6", "size": 6651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popops/MapExprRemAndDivideOptimisations.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": "tests/popops/MapExprRemAndDivideOptimisations.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": "tests/popops/MapExprRemAndDivideOptimisations.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": 31.5213270142, "max_line_length": 80, "alphanum_fraction": 0.615396181, "num_tokens": 1918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.19233997816153123}}
{"text": "//The PCL_NO_PRECOMPILE is necessary to use my own Point T template PointXYZVI within the pcl functions\n#include <memory>\n//#include <boost/foreach.hpp>\n#include <functional>\n#include <chrono>\n\n#include <Eigen/Geometry> \n\n#include <rclcpp/rclcpp.hpp>\n#include <sensor_msgs/msg/point_cloud2.hpp>\n#include <pcl/pcl_base.h>\n\n#include <tf2_ros/transform_listener.h>\n#include <tf2_ros/buffer.h>\n#include <tf2/exceptions.h>\n\n#include <pcl/PCLHeader.h>\n#include <pcl/filters/crop_box.h>\n#include <pcl/filters/passthrough.h>   \n#include <pcl/filters/impl/passthrough.hpp>\n\n#include <pcl/filters/voxel_grid.h>\n#include \"pcl_conversions/pcl_conversions.h\"\n\n\nusing namespace std::chrono_literals;\n\n/* The PointFilterCopy node filters unimportent points based on three criteria:\n1. RoI: The region of interest is described by a box. All points inside this box are considered relevant. The parameters of the box\nare described in world coordinates. Thus, a transformation from sensor to world needs to be given. It is recommended to set the world \ncoordinate system onto the road surface. This allows you to easily remove the ground points by defining a box just a bit higher then the road surface.\n2. Velocity: All points with low absolute velocity are filtered (considered to be background - especially useful, if the sensor itself does not move).\n**/\nclass PointFilterCopy : public rclcpp::Node\n{\n  public:\n    PointFilterCopy()\n    : Node(\"PointFilterCopy\")\n    {\n      subscription_ = this->create_subscription<sensor_msgs::msg::PointCloud2> (\n      \"input_cloud\", 10, std::bind(&PointFilterCopy::topic_callback, this, std::placeholders::_1)\n      );\n      publisher_ = this->create_publisher<sensor_msgs::msg::PointCloud2>(\"filtered_cloud\", 10); \n      \n      //tf2 listener\n      tf_buffer_ = std::make_unique<tf2_ros::Buffer>(this->get_clock());\n      transform_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);\n      \n      //filter objects\n      cropBoxFilter_ = new pcl::CropBox<pcl::PCLPointCloud2>();\n      vel_filter_ = new pcl::PassThrough<pcl::PCLPointCloud2>();\n      vel_filter_ ->setFilterFieldName(\"velocity\");\n      vel_filter_ ->setNegative(true);\n      sor_ = std::make_unique<pcl::VoxelGrid<pcl::PCLPointCloud2>>();\n      \n      //parameters\n      this->declare_parameter<std::string>(\"input_frame\", \"input_frame\");\n      this->declare_parameter<float>(\"box_min_x\", 0.f);\n      this->declare_parameter<float>(\"box_min_y\", 0.f);\n      this->declare_parameter<float>(\"box_min_z\", -10.f);\n      this->declare_parameter<float>(\"box_max_x\", 100.f);\n      this->declare_parameter<float>(\"box_max_y\", 30.f);\n      this->declare_parameter<float>(\"box_max_z\", 10.f);\n      this->declare_parameter<float>(\"vel_min\", -0.1f);\n      this->declare_parameter<float>(\"vel_max\", 0.1f);\n      this->declare_parameter<float>(\"voxel_size\", 0.3f);\n\n      timer_ = this->create_wall_timer(\n      10000ms, std::bind(&PointFilterCopy::setParameters, this));\n      setParameters();\n    }\n\n    void setParameters()\n    {\n      this->get_parameter(\"input_frame\", fromFrameRel);\n      this->get_parameter(\"box_min_x\", box_min_x);\n      this->get_parameter(\"box_min_y\", box_min_y);\n      this->get_parameter(\"box_min_z\", box_min_z);\n      this->get_parameter(\"box_max_x\", box_max_x);\n      this->get_parameter(\"box_max_y\", box_max_y);\n      this->get_parameter(\"box_max_z\", box_max_z);\n      this->get_parameter(\"vel_low\", vel_low);\n      this->get_parameter(\"vel_high\", vel_high);\n      this->get_parameter(\"voxel_size\", voxel_size);\n      min_pt << box_min_x, box_min_y, box_min_z, 1.f;\n      max_pt << box_max_x, box_max_y, box_max_z, 1.f;\n      cropBoxFilter_->setMin(min_pt);\n      cropBoxFilter_->setMax(max_pt);\n      vel_filter_ ->setFilterLimits(vel_low, vel_high);\n      sor_->setLeafSize (voxel_size, voxel_size, voxel_size);\n      //RCLCPP_INFO(this->get_logger(), \"Filter box parameter set to: x %f - %f, y %f - %f, z %f - %f \\n\"\n      //                                \" Velocity filter set to: %f - %f\",\n      //                                 box_min_x,box_max_x, box_min_y,box_max_y, box_min_z,box_max_z, vel_low, vel_high);\n    }\n\n  private:\n    \n    rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr subscription_;\n    rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr publisher_;\n    \n    //tf2 listener\n    std::shared_ptr<tf2_ros::TransformListener> transform_listener_{nullptr};\n    std::unique_ptr<tf2_ros::Buffer> tf_buffer_;\n\n    //listener parameters\n    std::string fromFrameRel;\n    std::string toFrameRel = \"world\";\n    \n    //filter elements\n    pcl::CropBox<pcl::PCLPointCloud2> * cropBoxFilter_;\n    Eigen::Vector4f min_pt;\n    Eigen::Vector4f max_pt;\n    pcl::PassThrough<pcl::PCLPointCloud2> * vel_filter_;\n    rclcpp::TimerBase::SharedPtr timer_;\n    std::unique_ptr<pcl::VoxelGrid<pcl::PCLPointCloud2>> sor_;\n    \n    //filter parameter\n    float box_min_x;\n    float box_min_y;\n    float box_min_z;\n    float box_max_x;\n    float box_max_y;\n    float box_max_z;\n\n    float vel_low;\n    float vel_high;\n\n    float voxel_size;\n\n    void topic_callback(const sensor_msgs::msg::PointCloud2::SharedPtr point_cloud2_msgs) const\n    {    \n      using std::chrono::high_resolution_clock;\n      using std::chrono::duration_cast;\n      using std::chrono::duration;\n      using std::chrono::milliseconds;\n\n      auto t1 = high_resolution_clock::now();\n      //----------deserialize--------------\n      //pcl::PointCloud<PointXYZVI> cloud_out;\n      //pcl::PointCloud<PointXYZVI> input_cloud;\n      //fromROSMsg(*point_cloud2_msgs, input_cloud);\n      \n      //---------tf2 transformation------------\n      //this stuff should be done with pcl_ros as soon as a filter transformation is available.\n      geometry_msgs::msg::TransformStamped transformStamped;\n      try {\n          transformStamped = tf_buffer_->lookupTransform(\n            toFrameRel, fromFrameRel,\n            tf2::TimePointZero);\n        } catch (tf2::TransformException & ex) {\n          RCLCPP_INFO(\n            this->get_logger(), \"Could not transform %s to %s: %s\",\n            toFrameRel.c_str(), fromFrameRel.c_str(), ex.what());\n          return;\n        }\n     \n      \n      Eigen::Affine3f transform;\n      Eigen::AngleAxisf rotation;\n      Eigen::Transform<float,3,Eigen::Affine> t;\n      Eigen::Quaternion<float> quat(transformStamped.transform.rotation.w,\n                          transformStamped.transform.rotation.x,\n                          transformStamped.transform.rotation.y,\n                          transformStamped.transform.rotation.z);\n      rotation = quat;\n      Eigen::Translation<float,3> translation(transformStamped.transform.translation.x, transformStamped.transform.translation.y, transformStamped.transform.translation.z);\n      t = translation * rotation;\n      cropBoxFilter_->setTransform(t);  \n      \n      //---------filter-----------\n      //I don't like copying the data, but I have not found another way to get the pointcloud behind a shared Ptr.\n      //pcl::PointCloud<PointXYZVI>::Ptr boxfilter_cloud(new pcl::PointCloud<PointXYZVI>(input_cloud));\n      //pcl::PointCloud<PointXYZVI>::Ptr vel_cloud(new pcl::PointCloud<PointXYZVI>(cloud_out));\n      \n      pcl::PCLPointCloud2::Ptr boxfiltered_cloud (new pcl::PCLPointCloud2());\n      pcl::PCLPointCloud2::Ptr velocity_filtered_cloud (new pcl::PCLPointCloud2());\n      pcl::PCLPointCloud2::Ptr output_cloud (new pcl::PCLPointCloud2());\n      pcl::PCLPointCloud2* cloud = new pcl::PCLPointCloud2(); \n      //pcl::PCLPointCloud2 cloud_filtered;\n      //Performance note: Not sure if PCLPointCloud2ConstPtr copies the data - if so this should be optimized\n      pcl_conversions::toPCL(*point_cloud2_msgs, *cloud);\n      //pcl::PCLPointCloud2::Ptr input_cloud (new pcl::PCLPointCloud2());\n      pcl::PCLPointCloud2ConstPtr cloudPtr(cloud);\n      cropBoxFilter_ ->setInputCloud(cloudPtr);\n      cropBoxFilter_ ->filter(*boxfiltered_cloud);\n      //----------velocity based filtering-------------\n      pcl::PCLPointCloud2ConstPtr vel_input_cloudPtr(boxfiltered_cloud);\n      vel_filter_ ->setInputCloud(vel_input_cloudPtr);\n      vel_filter_ ->filter(*velocity_filtered_cloud);\n      //----------down sampling------------\n      pcl::PCLPointCloud2ConstPtr voxel_input_cloudPtr(velocity_filtered_cloud);\n      sor_->setInputCloud (voxel_input_cloudPtr);\n      sor_->filter (*output_cloud);\n\n      //----------serialize---------------\n      sensor_msgs::msg::PointCloud2 output;\n      pcl_conversions::fromPCL(*output_cloud, output);\n      publisher_->publish(output);\n\n      //Get runtime info\n      auto t2 = high_resolution_clock::now();\n      duration<double, std::milli> ms_double = t2 - t1;\n\n      RCLCPP_INFO(\n        this->get_logger(), \"Pointfilter took %f ms to complete\",\n            ms_double.count());\n    }\n};\n\n\n\nint main(int argc, char * argv[])\n{\n  rclcpp::init(argc, argv);\n  rclcpp::spin(std::make_shared<PointFilterCopy>());\n  rclcpp::shutdown();\n  return 0;\n}\n\n\n    \n", "meta": {"hexsha": "02582459cb9886a7675ac6364f3eaecb60169721", "size": 8999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PointFilter_copy.cpp", "max_stars_repo_name": "FelixSchmidtBrand/lidar_perception_ws", "max_stars_repo_head_hexsha": "f91d0c5b16a2fb019a01d9983429779f82e70cd5", "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/PointFilter_copy.cpp", "max_issues_repo_name": "FelixSchmidtBrand/lidar_perception_ws", "max_issues_repo_head_hexsha": "f91d0c5b16a2fb019a01d9983429779f82e70cd5", "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/PointFilter_copy.cpp", "max_forks_repo_name": "FelixSchmidtBrand/lidar_perception_ws", "max_forks_repo_head_hexsha": "f91d0c5b16a2fb019a01d9983429779f82e70cd5", "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.536036036, "max_line_length": 172, "alphanum_fraction": 0.6740748972, "num_tokens": 2182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.19233997816153123}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2013 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 <gnuradio/filter/pfb_arb_resampler.h>\n#include <gnuradio/logger.h>\n#include <cstdio>\n#include <stdexcept>\n#include <boost/math/special_functions/round.hpp>\n\nnamespace gr {\n  namespace filter {\n    namespace kernel {\n\n      pfb_arb_resampler_ccf::pfb_arb_resampler_ccf(float rate,\n                                                   const std::vector<float> &taps,\n                                                   unsigned int filter_size)\n      {\n        d_acc = 0; // start accumulator at 0\n\n        /* The number of filters is specified by the user as the\n           filter size; this is also the interpolation rate of the\n           filter. We use it and the rate provided to determine the\n           decimation rate. This acts as a rational resampler. The\n           flt_rate is calculated as the residual between the integer\n           decimation rate and the real decimation rate and will be\n           used to determine to interpolation point of the resampling\n           process.\n        */\n        d_int_rate = filter_size;\n        set_rate(rate);\n\n        d_last_filter = (taps.size()/2) % filter_size;\n\n        d_filters = std::vector<fir_filter_ccf*>(d_int_rate);\n        d_diff_filters = std::vector<fir_filter_ccf*>(d_int_rate);\n\n        // Create an FIR filter for each channel and zero out the taps\n        std::vector<float> vtaps(0, d_int_rate);\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          d_filters[i] = new fir_filter_ccf(1, vtaps);\n          d_diff_filters[i] = new fir_filter_ccf(1, vtaps);\n        }\n\n        // Now, actually set the filters' taps\n        set_taps(taps);\n\n        // Delay is based on number of taps per filter arm. Round to\n        // the nearest integer.\n        float delay = rate * (taps_per_filter() - 1.0) / 2.0;\n        d_delay = static_cast<int>(boost::math::iround(delay));\n\n        // This calculation finds the phase offset induced by the\n        // arbitrary resampling. It's based on which filter arm we are\n        // at the filter's group delay plus the fractional offset\n        // between the samples. Calculated here based on the rotation\n        // around nfilts starting at start_filter.\n        float accum = d_delay * d_flt_rate;\n        int   accum_int = static_cast<int>(accum);\n        float accum_frac = accum - accum_int;\n        int end_filter = static_cast<int>\n          (boost::math::iround(fmodf(d_last_filter + d_delay * d_dec_rate + accum_int, \\\n                                     static_cast<float>(d_int_rate))));\n\n        d_est_phase_change = d_last_filter - (end_filter + accum_frac);\n      }\n\n      pfb_arb_resampler_ccf::~pfb_arb_resampler_ccf()\n      {\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          delete d_filters[i];\n          delete d_diff_filters[i];\n        }\n      }\n\n      void\n      pfb_arb_resampler_ccf::create_taps(const std::vector<float> &newtaps,\n                                         std::vector< std::vector<float> > &ourtaps,\n                                         std::vector<fir_filter_ccf*> &ourfilter)\n      {\n        unsigned int ntaps = newtaps.size();\n        d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_int_rate);\n\n        // Create d_numchan vectors to store each channel's taps\n        ourtaps.resize(d_int_rate);\n\n        // Make a vector of the taps plus fill it out with 0's to fill\n        // each polyphase filter with exactly d_taps_per_filter\n        std::vector<float> tmp_taps;\n        tmp_taps = newtaps;\n        while((float)(tmp_taps.size()) < d_int_rate*d_taps_per_filter) {\n          tmp_taps.push_back(0.0);\n        }\n\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out\n          ourtaps[i] = std::vector<float>(d_taps_per_filter, 0);\n          for(unsigned int j = 0; j < d_taps_per_filter; j++) {\n            ourtaps[i][j] = tmp_taps[i + j*d_int_rate];\n          }\n\n          // Build a filter for each channel and add it's taps to it\n          ourfilter[i]->set_taps(ourtaps[i]);\n        }\n      }\n\n      void\n      pfb_arb_resampler_ccf::create_diff_taps(const std::vector<float> &newtaps,\n                                              std::vector<float> &difftaps)\n      {\n        // Calculate the differential taps using a derivative filter\n        std::vector<float> diff_filter(2);\n        diff_filter[0] = -1;\n        diff_filter[1] = 1;\n\n        for(unsigned int i = 0; i < newtaps.size()-1; i++) {\n          float tap = 0;\n          for(unsigned int j = 0; j < diff_filter.size(); j++) {\n            tap += diff_filter[j]*newtaps[i+j];\n          }\n          difftaps.push_back(tap);\n        }\n        difftaps.push_back(0);\n      }\n\n      void\n      pfb_arb_resampler_ccf::set_taps(const std::vector<float> &taps)\n      {\n        std::vector<float> dtaps;\n        create_diff_taps(taps, dtaps);\n        create_taps(taps, d_taps, d_filters);\n        create_taps(dtaps, d_dtaps, d_diff_filters);\n      }\n\n      std::vector<std::vector<float> >\n      pfb_arb_resampler_ccf::taps() const\n      {\n        return d_taps;\n      }\n\n      void\n      pfb_arb_resampler_ccf::print_taps()\n      {\n        unsigned int i, j;\n        for(i = 0; i < d_int_rate; i++) {\n          printf(\"filter[%d]: [\", i);\n          for(j = 0; j < d_taps_per_filter; j++) {\n            printf(\" %.4e\", d_taps[i][j]);\n          }\n          printf(\"]\\n\");\n        }\n      }\n\n      void\n      pfb_arb_resampler_ccf::set_rate(float rate)\n      {\n        d_dec_rate = (unsigned int)floor(d_int_rate/rate);\n        d_flt_rate = (d_int_rate/rate) - d_dec_rate;\n      }\n\n      void\n      pfb_arb_resampler_ccf::set_phase(float ph)\n      {\n        if((ph < 0) || (ph >= 2.0*M_PI)) {\n          throw std::runtime_error(\"pfb_arb_resampler_ccf: set_phase value out of bounds [0, 2pi).\\n\");\n        }\n\n        float ph_diff = 2.0*M_PI / (float)d_filters.size();\n        d_last_filter = static_cast<int>(ph / ph_diff);\n      }\n\n      float\n      pfb_arb_resampler_ccf::phase() const\n      {\n        float ph_diff = 2.0*M_PI / static_cast<float>(d_filters.size());\n        return d_last_filter * ph_diff;\n      }\n\n      unsigned int\n      pfb_arb_resampler_ccf::taps_per_filter() const\n      {\n        return d_taps_per_filter;\n      }\n\n      float\n      pfb_arb_resampler_ccf::phase_offset(float freq, float fs)\n      {\n        float adj = (2.0*M_PI)*(freq/fs)/static_cast<float>(d_int_rate);\n        return -adj * d_est_phase_change;\n      }\n\n      int\n      pfb_arb_resampler_ccf::filter(gr_complex *output, gr_complex *input,\n                                    int n_to_read, int &n_read)\n      {\n        int i_out = 0, i_in = 0;\n        unsigned int j = d_last_filter;;\n        gr_complex o0, o1;\n\n        while(i_in < n_to_read) {\n          // start j by wrapping around mod the number of channels\n          while(j < d_int_rate) {\n            // Take the current filter and derivative filter output\n            o0 = d_filters[j]->filter(&input[i_in]);\n            o1 = d_diff_filters[j]->filter(&input[i_in]);\n\n            output[i_out] = o0 + o1*d_acc;     // linearly interpolate between samples\n            i_out++;\n\n            // Adjust accumulator and index into filterbank\n            d_acc += d_flt_rate;\n            j += d_dec_rate + (int)floor(d_acc);\n            d_acc = fmodf(d_acc, 1.0);\n          }\n          i_in += (int)(j / d_int_rate);\n          j = j % d_int_rate;\n        }\n        d_last_filter = j; // save last filter state for re-entry\n\n        n_read = i_in;   // return how much we've actually read\n        return i_out;    // return how much we've produced\n      }\n\n      /****************************************************************/\n\n      pfb_arb_resampler_ccc::pfb_arb_resampler_ccc(float rate,\n                                                   const std::vector<gr_complex> &taps,\n                                                   unsigned int filter_size)\n      {\n        d_acc = 0; // start accumulator at 0\n\n        /* The number of filters is specified by the user as the\n           filter size; this is also the interpolation rate of the\n           filter. We use it and the rate provided to determine the\n           decimation rate. This acts as a rational resampler. The\n           flt_rate is calculated as the residual between the integer\n           decimation rate and the real decimation rate and will be\n           used to determine to interpolation point of the resampling\n           process.\n        */\n        d_int_rate = filter_size;\n        set_rate(rate);\n\n        d_last_filter = (taps.size()/2) % filter_size;\n\n        d_filters = std::vector<fir_filter_ccc*>(d_int_rate);\n        d_diff_filters = std::vector<fir_filter_ccc*>(d_int_rate);\n\n        // Create an FIR filter for each channel and zero out the taps\n        std::vector<gr_complex> vtaps(0, d_int_rate);\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          d_filters[i] = new fir_filter_ccc(1, vtaps);\n          d_diff_filters[i] = new fir_filter_ccc(1, vtaps);\n        }\n\n        // Now, actually set the filters' taps\n        set_taps(taps);\n\n        // Delay is based on number of taps per filter arm. Round to\n        // the nearest integer.\n        float delay = rate * (taps_per_filter() - 1.0) / 2.0;\n        d_delay = static_cast<int>(boost::math::iround(delay));\n\n        // This calculation finds the phase offset induced by the\n        // arbitrary resampling. It's based on which filter arm we are\n        // at the filter's group delay plus the fractional offset\n        // between the samples. Calculated here based on the rotation\n        // around nfilts starting at start_filter.\n        float accum = d_delay * d_flt_rate;\n        int   accum_int = static_cast<int>(accum);\n        float accum_frac = accum - accum_int;\n        int end_filter = static_cast<int>\n          (boost::math::iround(fmodf(d_last_filter + d_delay * d_dec_rate + accum_int, \\\n                                     static_cast<float>(d_int_rate))));\n\n        d_est_phase_change = d_last_filter - (end_filter + accum_frac);\n      }\n\n      pfb_arb_resampler_ccc::~pfb_arb_resampler_ccc()\n      {\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          delete d_filters[i];\n          delete d_diff_filters[i];\n        }\n      }\n\n      void\n      pfb_arb_resampler_ccc::create_taps(const std::vector<gr_complex> &newtaps,\n                                         std::vector< std::vector<gr_complex> > &ourtaps,\n                                         std::vector<fir_filter_ccc*> &ourfilter)\n      {\n        unsigned int ntaps = newtaps.size();\n        d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_int_rate);\n\n        // Create d_numchan vectors to store each channel's taps\n        ourtaps.resize(d_int_rate);\n\n        // Make a vector of the taps plus fill it out with 0's to fill\n        // each polyphase filter with exactly d_taps_per_filter\n        std::vector<gr_complex> tmp_taps;\n        tmp_taps = newtaps;\n        while((float)(tmp_taps.size()) < d_int_rate*d_taps_per_filter) {\n          tmp_taps.push_back(0.0);\n        }\n\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out\n          ourtaps[i] = std::vector<gr_complex>(d_taps_per_filter, 0);\n          for(unsigned int j = 0; j < d_taps_per_filter; j++) {\n            ourtaps[i][j] = tmp_taps[i + j*d_int_rate];\n          }\n\n          // Build a filter for each channel and add it's taps to it\n          ourfilter[i]->set_taps(ourtaps[i]);\n        }\n      }\n\n      void\n      pfb_arb_resampler_ccc::create_diff_taps(const std::vector<gr_complex> &newtaps,\n                                              std::vector<gr_complex> &difftaps)\n      {\n        // Calculate the differential taps using a derivative filter\n        std::vector<gr_complex> diff_filter(2);\n        diff_filter[0] = -1;\n        diff_filter[1] = 1;\n\n        for(unsigned int i = 0; i < newtaps.size()-1; i++) {\n          gr_complex tap = 0;\n          for(unsigned int j = 0; j < diff_filter.size(); j++) {\n            tap += diff_filter[j]*newtaps[i+j];\n          }\n          difftaps.push_back(tap);\n        }\n        difftaps.push_back(0);\n      }\n\n      void\n      pfb_arb_resampler_ccc::set_taps(const std::vector<gr_complex> &taps)\n      {\n        std::vector<gr_complex> dtaps;\n        create_diff_taps(taps, dtaps);\n        create_taps(taps, d_taps, d_filters);\n        create_taps(dtaps, d_dtaps, d_diff_filters);\n      }\n\n      std::vector<std::vector<gr_complex> >\n      pfb_arb_resampler_ccc::taps() const\n      {\n        return d_taps;\n      }\n\n      void\n      pfb_arb_resampler_ccc::print_taps()\n      {\n        unsigned int i, j;\n        for(i = 0; i < d_int_rate; i++) {\n          printf(\"filter[%d]: [\", i);\n          for(j = 0; j < d_taps_per_filter; j++) {\n            printf(\" %.4e + j%.4e\", d_taps[i][j].real(), d_taps[i][j].imag());\n          }\n          printf(\"]\\n\");\n        }\n      }\n\n      void\n      pfb_arb_resampler_ccc::set_rate(float rate)\n      {\n        d_dec_rate = (unsigned int)floor(d_int_rate/rate);\n        d_flt_rate = (d_int_rate/rate) - d_dec_rate;\n      }\n\n      void\n      pfb_arb_resampler_ccc::set_phase(float ph)\n      {\n        if((ph < 0) || (ph >= 2.0*M_PI)) {\n          throw std::runtime_error(\"pfb_arb_resampler_ccc: set_phase value out of bounds [0, 2pi).\\n\");\n        }\n\n        float ph_diff = 2.0*M_PI / (float)d_filters.size();\n        d_last_filter = static_cast<int>(ph / ph_diff);\n      }\n\n      float\n      pfb_arb_resampler_ccc::phase() const\n      {\n        float ph_diff = 2.0*M_PI / static_cast<float>(d_filters.size());\n        return d_last_filter * ph_diff;\n      }\n\n      unsigned int\n      pfb_arb_resampler_ccc::taps_per_filter() const\n      {\n        return d_taps_per_filter;\n      }\n\n      float\n      pfb_arb_resampler_ccc::phase_offset(float freq, float fs)\n      {\n        float adj = (2.0*M_PI)*(freq/fs)/static_cast<float>(d_int_rate);\n        return -adj * d_est_phase_change;\n      }\n\n      int\n      pfb_arb_resampler_ccc::filter(gr_complex *output, gr_complex *input,\n                                    int n_to_read, int &n_read)\n      {\n        int i_out = 0, i_in = 0;\n        unsigned int j = d_last_filter;;\n        gr_complex o0, o1;\n\n        while(i_in < n_to_read) {\n          // start j by wrapping around mod the number of channels\n          while(j < d_int_rate) {\n            // Take the current filter and derivative filter output\n            o0 = d_filters[j]->filter(&input[i_in]);\n            o1 = d_diff_filters[j]->filter(&input[i_in]);\n\n            output[i_out] = o0 + o1*d_acc;     // linearly interpolate between samples\n            i_out++;\n\n            // Adjust accumulator and index into filterbank\n            d_acc += d_flt_rate;\n            j += d_dec_rate + (int)floor(d_acc);\n            d_acc = fmodf(d_acc, 1.0);\n          }\n          i_in += (int)(j / d_int_rate);\n          j = j % d_int_rate;\n        }\n        d_last_filter = j; // save last filter state for re-entry\n\n        n_read = i_in;   // return how much we've actually read\n        return i_out;    // return how much we've produced\n      }\n\n      /****************************************************************/\n\n      pfb_arb_resampler_fff::pfb_arb_resampler_fff(float rate,\n                                                   const std::vector<float> &taps,\n                                                   unsigned int filter_size)\n      {\n        d_acc = 0; // start accumulator at 0\n\n        /* The number of filters is specified by the user as the\n           filter size; this is also the interpolation rate of the\n           filter. We use it and the rate provided to determine the\n           decimation rate. This acts as a rational resampler. The\n           flt_rate is calculated as the residual between the integer\n           decimation rate and the real decimation rate and will be\n           used to determine to interpolation point of the resampling\n           process.\n        */\n        d_int_rate = filter_size;\n        set_rate(rate);\n\n        d_last_filter = (taps.size()/2) % filter_size;\n\n        d_filters = std::vector<fir_filter_fff*>(d_int_rate);\n        d_diff_filters = std::vector<fir_filter_fff*>(d_int_rate);\n\n        // Create an FIR filter for each channel and zero out the taps\n        std::vector<float> vtaps(0, d_int_rate);\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          d_filters[i] = new fir_filter_fff(1, vtaps);\n          d_diff_filters[i] = new fir_filter_fff(1, vtaps);\n        }\n\n        // Now, actually set the filters' taps\n        set_taps(taps);\n\n        // Delay is based on number of taps per filter arm. Round to\n        // the nearest integer.\n        float delay = rate * (taps_per_filter() - 1.0) / 2.0;\n        d_delay = static_cast<int>(boost::math::iround(delay));\n\n        // This calculation finds the phase offset induced by the\n        // arbitrary resampling. It's based on which filter arm we are\n        // at the filter's group delay plus the fractional offset\n        // between the samples. Calculated here based on the rotation\n        // around nfilts starting at start_filter.\n        float accum = d_delay * d_flt_rate;\n        int   accum_int = static_cast<int>(accum);\n        float accum_frac = accum - accum_int;\n        int end_filter = static_cast<int>\n          (boost::math::iround(fmodf(d_last_filter + d_delay * d_dec_rate + accum_int, \\\n                                     static_cast<float>(d_int_rate))));\n\n        d_est_phase_change = d_last_filter - (end_filter + accum_frac);\n      }\n\n      pfb_arb_resampler_fff::~pfb_arb_resampler_fff()\n      {\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          delete d_filters[i];\n          delete d_diff_filters[i];\n        }\n      }\n\n      void\n      pfb_arb_resampler_fff::create_taps(const std::vector<float> &newtaps,\n                                         std::vector< std::vector<float> > &ourtaps,\n                                         std::vector<fir_filter_fff*> &ourfilter)\n      {\n        unsigned int ntaps = newtaps.size();\n        d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_int_rate);\n\n        // Create d_numchan vectors to store each channel's taps\n        ourtaps.resize(d_int_rate);\n\n        // Make a vector of the taps plus fill it out with 0's to fill\n        // each polyphase filter with exactly d_taps_per_filter\n        std::vector<float> tmp_taps;\n        tmp_taps = newtaps;\n        while((float)(tmp_taps.size()) < d_int_rate*d_taps_per_filter) {\n          tmp_taps.push_back(0.0);\n        }\n\n        for(unsigned int i = 0; i < d_int_rate; i++) {\n          // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out\n          ourtaps[i] = std::vector<float>(d_taps_per_filter, 0);\n          for(unsigned int j = 0; j < d_taps_per_filter; j++) {\n            ourtaps[i][j] = tmp_taps[i + j*d_int_rate];\n          }\n\n          // Build a filter for each channel and add it's taps to it\n          ourfilter[i]->set_taps(ourtaps[i]);\n        }\n      }\n\n      void\n      pfb_arb_resampler_fff::create_diff_taps(const std::vector<float> &newtaps,\n                                              std::vector<float> &difftaps)\n      {\n        // Calculate the differential taps using a derivative filter\n        std::vector<float> diff_filter(2);\n        diff_filter[0] = -1;\n        diff_filter[1] = 1;\n\n        for(unsigned int i = 0; i < newtaps.size()-1; i++) {\n          float tap = 0;\n          for(unsigned int j = 0; j < diff_filter.size(); j++) {\n            tap += diff_filter[j]*newtaps[i+j];\n          }\n          difftaps.push_back(tap);\n        }\n        difftaps.push_back(0);\n      }\n\n      void\n      pfb_arb_resampler_fff::set_taps(const std::vector<float> &taps)\n      {\n        std::vector<float> dtaps;\n        create_diff_taps(taps, dtaps);\n        create_taps(taps, d_taps, d_filters);\n        create_taps(dtaps, d_dtaps, d_diff_filters);\n      }\n\n      std::vector<std::vector<float> >\n      pfb_arb_resampler_fff::taps() const\n      {\n        return d_taps;\n      }\n\n      void\n      pfb_arb_resampler_fff::print_taps()\n      {\n        unsigned int i, j;\n        for(i = 0; i < d_int_rate; i++) {\n          printf(\"filter[%d]: [\", i);\n          for(j = 0; j < d_taps_per_filter; j++) {\n            printf(\" %.4e\", d_taps[i][j]);\n          }\n          printf(\"]\\n\");\n        }\n      }\n\n      void\n      pfb_arb_resampler_fff::set_rate(float rate)\n      {\n        d_dec_rate = (unsigned int)floor(d_int_rate/rate);\n        d_flt_rate = (d_int_rate/rate) - d_dec_rate;\n      }\n\n      void\n      pfb_arb_resampler_fff::set_phase(float ph)\n      {\n        if((ph < 0) || (ph >= 2.0*M_PI)) {\n          throw std::runtime_error(\"pfb_arb_resampler_fff: set_phase value out of bounds [0, 2pi).\\n\");\n        }\n\n        float ph_diff = 2.0*M_PI / (float)d_filters.size();\n        d_last_filter = static_cast<int>(ph / ph_diff);\n      }\n\n      float\n      pfb_arb_resampler_fff::phase() const\n      {\n        float ph_diff = 2.0*M_PI / static_cast<float>(d_filters.size());\n        return d_last_filter * ph_diff;\n      }\n\n      unsigned int\n      pfb_arb_resampler_fff::taps_per_filter() const\n      {\n        return d_taps_per_filter;\n      }\n\n      float\n      pfb_arb_resampler_fff::phase_offset(float freq, float fs)\n      {\n        float adj = (2.0*M_PI)*(freq/fs)/static_cast<float>(d_int_rate);\n        return -adj * d_est_phase_change;\n      }\n\n      int\n      pfb_arb_resampler_fff::filter(float *output, float *input,\n                                    int n_to_read, int &n_read)\n      {\n        int i_out = 0, i_in = 0;\n        unsigned int j = d_last_filter;;\n        float o0, o1;\n\n        while(i_in < n_to_read) {\n          // start j by wrapping around mod the number of channels\n          while(j < d_int_rate) {\n            // Take the current filter and derivative filter output\n            o0 = d_filters[j]->filter(&input[i_in]);\n            o1 = d_diff_filters[j]->filter(&input[i_in]);\n\n            output[i_out] = o0 + o1*d_acc;     // linearly interpolate between samples\n            i_out++;\n\n            // Adjust accumulator and index into filterbank\n            d_acc += d_flt_rate;\n            j += d_dec_rate + (int)floor(d_acc);\n            d_acc = fmodf(d_acc, 1.0);\n          }\n          i_in += (int)(j / d_int_rate);\n          j = j % d_int_rate;\n        }\n        d_last_filter = j; // save last filter state for re-entry\n\n        n_read = i_in;   // return how much we've actually read\n        return i_out;    // return how much we've produced\n      }\n\n    } /* namespace kernel */\n  } /* namespace filter */\n} /* namespace gr */\n", "meta": {"hexsha": "5c874471496d3cc7648fc44273472731f991aea4", "size": 23719, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/pfb_arb_resampler.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-filter/lib/pfb_arb_resampler.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-filter/lib/pfb_arb_resampler.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": 35.348733234, "max_line_length": 103, "alphanum_fraction": 0.5705130908, "num_tokens": 6046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.19233997816153123}}
{"text": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <iostream>\r\n#include \"Components.h\"\r\n#include <vector>\r\n#include \"Object.h\"\r\n#include <fstream>\r\n#include <string>\r\n#include \"Transform.hpp\"\r\n\r\n#include <GL/glu.h>\r\n#include <GLFW/glfw3.h>\r\n#include <armadillo>\r\n\r\n//Vectors that will be used as auxiliaries to send them to the figures.\r\nvector <Vertex> verts;\r\nvector<Edge> edgs;\r\nvector<Face>fcs;\r\nvector<Object> models;\r\n\r\n//function prototypes\r\nvoid readFile(string* nombre, string* archivo, string enter);\r\nint paintModels2();\r\nint inicializacion(GLFWwindow* window);\r\nvector <Vertex> bezier(double x);\r\nint main(int argc, char** argv)\r\n{\r\n\t//Variables that will be used as auxiliaries to temporarily save the data and then send them to the figures\r\n\tstring nombre;\r\n\tstring archivo;\r\n\treadFile(&nombre, &archivo, \"BMX.obj\");\r\n\tObject model = Object(nombre, archivo, verts, edgs, fcs);\r\n\tmodels.push_back(model);\r\n\tnombre = \"\";archivo = \"\";verts.clear();edgs.clear();fcs.clear();\r\n\tpaintModels2();\r\n\t\r\n\treturn 0;\r\n}//main (END).\r\n\r\n/*The following function reads the data of the obj file receiving as parameters nombre and archivo these are by reference and\r\n  an enter string that is the name of the file to read this goes by value.*/\r\nvoid readFile(string* nombre, string* archivo, string enter) {\r\n\tchar cadena[500];\r\n\tfloat a, b, c;\r\n\tint d, e, f, aux = 0;\r\n\tstring dcadena, ecadena, fcadena;\r\n\tint indiVer = 1;\r\n\tifstream fe(enter);\r\n\tfe >> cadena;\r\n\t//Assign the file name to the archivo variable\r\n\t*archivo = cadena;\r\n\tfe >> cadena;\r\n\tfe >> cadena;\r\n\tfe >> cadena;\r\n\t//Assign the name to the nombre variable\r\n\t*nombre = cadena;\r\n\t//While not end of file\r\n\twhile (!fe.eof()) {\r\n\t\tfe >> cadena;\r\n\t\t//Verify that only vertices are read\r\n\t\tif (cadena[1] != 'n' && fe.eof() == 0 && cadena[0] == 'v') {\r\n\t\t\tfe >> cadena;\r\n\t\t\ta = atof(cadena);\r\n\t\t\tfe >> cadena;\r\n\t\t\tb = atof(cadena);\r\n\t\t\tfe >> cadena;\r\n\t\t\tc = atof(cadena);\r\n\t\t\t//A temporary vertex is created and added to the array of vertices.\r\n\t\t\tVertex v(a, b, c, indiVer);\r\n\t\t\tverts.push_back(v);\r\n\t\t\tindiVer++;\r\n\t\t}\r\n\t\t//Verify that only the faces are read.\r\n\t\telse if (cadena[1] != 'n' && fe.eof() == 0 && cadena[0] == 'f') {\r\n\t\t\tvector<Vertex> vertic;\r\n\t\t\tvector<Edge> edgaux;\r\n\t\t\tfe >> cadena;\r\n\t\t\td = atof(cadena);\r\n\t\t\tvertic.push_back(verts[d - 1]);\r\n\t\t\tfe >> cadena;\r\n\t\t\te = atof(cadena);\r\n\t\t\tvertic.push_back(verts[e - 1]);\r\n\t\t\tfe >> cadena;\r\n\t\t\tf = atof(cadena);\r\n\t\t\tvertic.push_back(verts[f - 1]);\r\n\t\t\t//The three edges are deducted and added to the edge vector.\r\n\t\t\tEdge j(verts[d - 1], verts[e - 1]);\r\n\t\t\tEdge k(verts[e - 1], verts[f - 1]);\r\n\t\t\tEdge l(verts[f - 1], verts[d - 1]);\r\n\t\t\tedgs.push_back(j);\r\n\t\t\tedgs.push_back(k);\r\n\t\t\tedgs.push_back(l);\r\n\t\t\t//Those same edges are sent to the edgaux temporary vector that will be sent to the face that will be formed by a vector of vertices and one of edges.\r\n\t\t\tedgaux.push_back(j);\r\n\t\t\tedgaux.push_back(k);\r\n\t\t\tedgaux.push_back(l);\r\n\t\t\tFace fac(vertic, edgaux);\r\n\t\t\tfcs.push_back(fac);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfe >> cadena;\r\n\t\t\tfe >> cadena;\r\n\t\t\tfe >> cadena;\r\n\t\t}\r\n\t}\r\n\tfe.close();\r\n}\r\n\r\n\r\n\r\nint paintModels2() {\r\n\tarma::frowvec eye = { 0.0, 0.0, 10.0 };\r\n\tarma::frowvec camera = { 0.0, 0.0, 0.0 };\r\n\r\n\tif (!glfwInit())\r\n\t{\r\n\t\tfprintf(stderr, \"Fallo al inicializar GLFW\\n\");\r\n\t\tgetchar();\r\n\t\treturn -1;\r\n\t}\r\n\tGLFWwindow* window;\r\n\twindow = glfwCreateWindow(1024, 768, \"Motocicleta Freestyle\", NULL, NULL);\r\n\tif (window == NULL) {\r\n\t\tfprintf(stderr, \"Fallo al abrir la ventana de GLFW.\\n\");\r\n\t\tgetchar();\r\n\t\tglfwTerminate();\r\n\t\treturn -1;\r\n\t}\r\n\tglfwMakeContextCurrent(window);\r\n\tglfwSetInputMode(window, GLFW_STICKY_KEYS,GL_TRUE);\r\n\tglEnable(GL_DEPTH_TEST);\r\n\tglDepthFunc(GL_LESS);\r\n\r\n\tglClearColor(0.0f, 0.0f, 0.0f, 0.0f);\r\n\r\n\t//  Proyecciones\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglLoadIdentity();\r\n\tint width, height;\r\n\tglfwGetFramebufferSize(window, &width, &height);\r\n\tfloat ar = width / height;\r\n\r\n\t//  Proyecci\ufffdn en paralelo\r\n\tglViewport(0, 0, width, height);\r\n\tglOrtho(-ar, ar, -1.0, 1.0, -20.0, 20.0);\r\n\t//  Proyecci\ufffdn en perspectiva\r\n\t//    glFrustum(-ar, ar, -ar, ar, 2.0, 4.0);\r\n\r\n\tglMatrixMode(GL_MODELVIEW);\r\n\tglLoadIdentity();\r\n\tTransform Tr = Transform();\r\n\tdouble t_angle = 0.0f;\r\n\tint cont = 0;\r\n\tint bcont = 0;\r\n\tdouble dt = 13.0;\r\n\tstd::vector< Vertex > p_vertices;\r\n\tfor (int f = 0; f < models[0].getSizevectorface();f++) {\r\n\t\t//Cycle to pass each vertex\r\n\t\tfor (int v = 0;v < 3;v++) {\r\n\t\t\tp_vertices.push_back(models[0].getFace(f).getVert(v));\r\n\t\t}\r\n\t}\r\n\t\r\n\tvector <Vertex> vet = bezier(1.0);\r\n\tdo {\r\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n\t\tglMatrixMode(GL_MODELVIEW);\r\n\t\tglLoadIdentity();\r\n\t\t/*gluLookAt(eye[0], eye[1], eye[2],\r\n\t\t\tcamera[0], camera[1], camera[2],\r\n\t\t\t0.0, 1.0, 0.0);*/\r\n\r\n\t    // Dibujar la moto\r\n\t\tarma::dmat transd;\r\n\t\tif (dt > 1) {\r\n\t\t\ttransd = Tr.S(0.05, 0.05, 0.05) * Tr.R(0.0, 0.5, 0.0, 180.0) * Tr.T(dt, 0.0, 0.0);\r\n\t\t\tdt -= 0.3;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tif (bcont < 20)\r\n\t\t\t{\r\n\t\t\t\ttransd = Tr.S(0.05, 0.05, 0.05) * Tr.R(0.0, 0.5, 0.0, 180.0) * Tr.T(vet[bcont].getX(), vet[bcont].getY(), vet[bcont].getZ());\r\n\t\t\t\tdt = vet[bcont].getX();\r\n\t\t\t\tbcont++;\r\n\t\t\t}\r\n\t\t\telse {\r\n\r\n\t\t\t\ttransd = Tr.S(0.05, 0.05, 0.05) * Tr.R(0.0, 0.5, 0.0, 180.0) * Tr.T(dt, 0.0, 0.0);\r\n\t\t\t\tdt -= 0.3;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\t\r\n\t\t\r\n\t\tstd::vector< Vertex > moto_vertices;\r\n\t\tfor (unsigned int i = 0; i < p_vertices.size(); i++) {\r\n\t\t\tarma::dcolvec v = p_vertices[i].h();\r\n\t\t\tarma::dcolvec vp = transd * v;\r\n\t\t\tVertex rv = Vertex();\r\n\t\t\trv.set_value(arma::trans(vp));\r\n\t\t\tmoto_vertices.push_back(rv);\r\n\t\t}\r\n\t\tglColor3f(1.0, 1.0, 0.0);\r\n\t\tglBegin(GL_TRIANGLES);\r\n\t\tfor (unsigned int i = 0; i < moto_vertices.size(); i++) {\r\n\t\t\tglVertex3d(moto_vertices[i].getX(), moto_vertices[i].getY(), moto_vertices[i].getZ());\r\n\t\t}\r\n\t\tglEnd();\r\n\r\n\t\tglfwSwapBuffers(window);\r\n\t\tglfwPollEvents();\r\n\r\n\t} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&\r\n\t\tglfwWindowShouldClose(window) == 0);\r\n\r\n\tglfwTerminate();\r\n\treturn 0;\r\n}\r\n\r\nvector <Vertex> bezier(double x) {\r\n\r\n\tvector<Vertex> vertic;\r\n\tarma::dmat MB = { {-1.0, 3.0, -3.0, 1.0},\r\n\t\t\t\t  {3.0, -6.0, 3.0, 0.0},\r\n\t\t\t\t  {-3.0, 3.0, 0.0, 0.0},\r\n\t\t\t\t  {1.0, 0.0, 0.0, 0.0} };\r\n\t//MH.print();\r\n\r\n\t//cout << endl;\r\n\r\n\tarma::dmat GH = { {x, 0.0, 0.0},\r\n\t\t\t\t\t  {-1.0, 5.0, 0.0},\r\n\t\t\t\t\t  {-3.0,4.0,0.0},\r\n\t\t\t\t\t  {-5.0, 0.0, 0.0} };\r\n\t//GH.print();\r\n\r\n\tdouble dt = 0.05;\r\n\tarma::dmat Qt;\r\n\tfor (double t = 0.0; t <= 1.0 + dt; t += dt) {\r\n\t\tarma::drowvec T = { powf(t, 3.0), powf(t,2.0), t, 1.0 };\r\n\t\tQt = T * MB * GH;\r\n\t\tQt.print();\r\n\t\tVertex vert(Qt[0], Qt[1], Qt[2], 1.0);\r\n\t\tvertic.push_back(vert);\r\n\t}\r\n\treturn vertic;\r\n}\r\n", "meta": {"hexsha": "07e21f010efeeacc2804032fdc70a430d63e1b91", "size": 6600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "proyecto/MotocicletaFreestyle.cpp", "max_stars_repo_name": "Pedejeca135/GRAFICACION_UASLP", "max_stars_repo_head_hexsha": "51674129cc3a853450509acc7e8c579bb167da11", "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": "proyecto/MotocicletaFreestyle.cpp", "max_issues_repo_name": "Pedejeca135/GRAFICACION_UASLP", "max_issues_repo_head_hexsha": "51674129cc3a853450509acc7e8c579bb167da11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proyecto/MotocicletaFreestyle.cpp", "max_forks_repo_name": "Pedejeca135/GRAFICACION_UASLP", "max_forks_repo_head_hexsha": "51674129cc3a853450509acc7e8c579bb167da11", "max_forks_repo_licenses": ["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.6129032258, "max_line_length": 154, "alphanum_fraction": 0.5960606061, "num_tokens": 2243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.1923399781615312}}
{"text": "// Copyright Louis Dionne 2013-2016\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/integral_constant.hpp>\n#include <boost/hana/map.hpp>\n#include <boost/hana/pair.hpp>\n\n#include <memory>\nnamespace hana = boost::hana;\n\n\nint main() {\n    auto map = hana::make_map(\n        hana::make_pair(hana::int_c<0>, 123),\n        hana::make_pair(hana::int_c<1>, 456)\n    );\n\n    std::unique_ptr<decltype(map)> p1{}, p2{};\n    using std::swap;\n    swap(p1, p2);\n}\n", "meta": {"hexsha": "33dd8c5daba1732c34bf7459b611f237e9a36bef", "size": 568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.62.0/libs/hana/test/issues/github_297.cpp", "max_stars_repo_name": "sita1999/arangodb", "max_stars_repo_head_hexsha": "6a4f462fa209010cd064f99e63d85ce1d432c500", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-03-04T15:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T11:06:25.000Z", "max_issues_repo_path": "3rdParty/boost/1.62.0/libs/hana/test/issues/github_297.cpp", "max_issues_repo_name": "lipper/arangodb", "max_issues_repo_head_hexsha": "66ea1fd4946668192e3f0d1060f0844f324ad7b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2016-02-29T17:59:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-05T04:59:26.000Z", "max_forks_repo_path": "3rdParty/boost/1.62.0/libs/hana/test/issues/github_297.cpp", "max_forks_repo_name": "lipper/arangodb", "max_forks_repo_head_hexsha": "66ea1fd4946668192e3f0d1060f0844f324ad7b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-07-30T10:17:12.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-11T20:31:46.000Z", "avg_line_length": 24.6956521739, "max_line_length": 81, "alphanum_fraction": 0.6690140845, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.19233997626313268}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/timing.h\"\n#include \"dynet/dict.h\"\n#include \"dynet/expr.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/serialization/access.hpp>\n\nusing namespace std;\nusing namespace dynet;\n\nunsigned REP_DIM = 128;\nunsigned INPUT_VOCAB_SIZE = 0;\nunsigned OUTPUT_VOCAB_SIZE = 0;\n\ndynet::Dict sd;\ndynet::Dict td;\nint kSRC_SOS;\nint kSRC_EOS;\nint kTRG_SOS;\nint kTRG_EOS;\n\nstruct Encoder {\n  LookupParameter p_s;\n  LookupParameter p_t;\n  vector<Expression> m;\n\n  Encoder() {}\n\n  explicit Encoder(Model& model) {\n    p_s = model.add_lookup_parameters(INPUT_VOCAB_SIZE, {REP_DIM}); \n    p_t = model.add_lookup_parameters(OUTPUT_VOCAB_SIZE, {REP_DIM}); \n  }\n\n  Expression EmbedSource(const vector<int>& sent, ComputationGraph& cg) {\n    m.resize(sent.size() + 2);\n    m[0] = lookup(cg, p_s, kSRC_SOS);\n    int i = 1;\n    for (auto& w : sent)\n      m[i++] = lookup(cg, p_s, w);\n    m[i] = lookup(cg, p_s, kSRC_EOS);\n#define DUMB_ADDITIVE\n#ifdef DUMB_ADDITIVE\n    return sum(m);\n#else\n    return sum_cols(tanh(kmh_ngram(concatenate_cols(m), 2)));\n#endif\n  }\n\n  Expression EmbedTarget(const vector<int>& sent, ComputationGraph& cg) {\n    m.resize(sent.size() + 2);\n    m[0] = lookup(cg, p_s, kTRG_SOS);\n    int i = 1;\n    for (auto& w : sent)\n      m[i++] = lookup(cg, p_t, w);\n    m[i] = lookup(cg, p_s, kTRG_EOS);\n#ifdef DUMB_ADDITIVE\n    return sum(m);\n#else\n    return sum_cols(tanh(kmh_ngram(concatenate_cols(m), 2)));\n#endif\n  }\n\n  friend class boost::serialization::access;\n  template<class Archive>\n  void serialize(Archive& ar, const unsigned int) {\n    ar & p_s;\n    ar & p_t;\n  }\n};\n\nint main(int argc, char** argv) {\n  dynet::initialize(argc, argv);\n  if (argc != 3 && argc != 4) {\n    cerr << \"Usage: \" << argv[0] << \" corpus.txt dev.txt [model.params]\\n\";\n    return 1;\n  }\n  vector<pair<vector<int>, vector<int>>> training, dev;\n  string line;\n  kSRC_SOS = sd.convert(\"<s>\");\n  kSRC_EOS = sd.convert(\"</s>\");\n  kTRG_SOS = td.convert(\"<s>\");\n  kTRG_EOS = td.convert(\"</s>\");\n  int tlc = 0;\n  cerr << \"Reading training data from \" << argv[1] << \"...\\n\";\n  {\n    ifstream in(argv[1]);\n    assert(in);\n    while(getline(in, line)) {\n      ++tlc;\n      vector<int> src, trg;\n      read_sentence_pair(line, src, sd, trg, td);\n      training.push_back(make_pair(src, trg));\n    }\n    cerr << tlc << \" lines, \" << sd.size() << \" source types, \" << td.size() << \" target types\\n\";\n  }\n  sd.freeze(); // no new word types allowed\n  td.freeze(); // no new word types allowed\n  INPUT_VOCAB_SIZE = sd.size();\n  OUTPUT_VOCAB_SIZE = td.size();\n#if 0\n\n  int dlc = 0;\n  int dtoks = 0;\n  cerr << \"Reading dev data from \" << argv[2] << \"...\\n\";\n  {\n    ifstream in(argv[2]);\n    assert(in);\n    while(getline(in, line)) {\n      ++dlc;\n      dev.push_back(read_sentence(line, &d));\n      dtoks += dev.back().size();\n      if (dev.back().front() != kSOS && dev.back().back() != kEOS) {\n        cerr << \"Dev sentence in \" << argv[2] << \":\" << tlc << \" didn't start or end with <s>, </s>\\n\";\n        abort();\n      }\n    }\n    cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n  }\n  ostringstream os;\n  os << \"bilm\"\n     << '_' << LAYERS\n     << '_' << INPUT_DIM\n     << '_' << HIDDEN_DIM\n     << \"-pid\" << getpid() << \".params\";\n  const string fname = os.str();\n  cerr << \"Parameters will be written to: \" << fname << endl;\n  double best = 9e+99;\n#endif\n  Model model;\n  Encoder emb;\n  if (argc == 4) {\n    string fname = argv[3];\n    ifstream in(fname);\n    boost::archive::text_iarchive ia(in);\n    ia >> model >> emb;\n  }\n  else {\n    emb = Encoder(model);\n  }\n\n  bool use_momentum = false;\n  Trainer* sgd = nullptr;\n  if (use_momentum)\n    sgd = new MomentumSGDTrainer(model);\n  else\n    sgd = new SimpleSGDTrainer(model);\n\n  unsigned report_every_i = 100;\n  unsigned si = training.size();\n  vector<unsigned> order(training.size());\n  for (unsigned i = 0; i < order.size(); ++i) order[i] = i;\n  bool first = true;\n  // int report = 0;\n  // unsigned dev_every_i_reports = 10;\n  unsigned lines = 0;\n  while(1) {\n    Timer iteration(\"completed in\");\n    double loss = 0;\n    unsigned chars = 0;\n    for (unsigned i = 0; i < report_every_i; ++i) {\n      if (si == training.size()) {\n        si = 0;\n        if (first) { first = false; } else { sgd->update_epoch(); }\n        cerr << \"**SHUFFLE\\n\";\n        random_shuffle(order.begin(), order.end());\n      }\n\n      // build graph for this instance\n      ComputationGraph cg;\n      auto& sent_pair = training[order[si]];\n      ++si;\n      Expression s = emb.EmbedSource(sent_pair.first, cg);\n      Expression sim = squared_distance(s, emb.EmbedTarget(sent_pair.second, cg));\n      float margin = 2;\n      const unsigned K = 20;\n      vector<Expression> noise(K);\n      for (unsigned j = 0; j < K; ++j) {\n        unsigned sample = rand01() * training.size();\n        while (sample == order[si] || sample == training.size()) { sample = rand01() * training.size(); }\n        Expression sim_n = squared_distance(s, emb.EmbedTarget(training[sample].second, cg));\n        noise[j] = pairwise_rank_loss(sim, sim_n, margin);\n      }\n      Expression l = sum(noise);\n      auto iloss = as_scalar(cg.forward(l));\n      assert(iloss >= 0);\n      if (iloss > 0) {\n        loss += iloss;\n        cg.backward(l);\n        sgd->update();\n      }\n      ++lines;\n    }\n    sgd->status();\n    cerr << \" E = \" << (loss) << \" ppl=\" << exp(loss / chars) << ' ';\n\n#if 0\n    lm.RandomSample();\n#endif\n#if 0\n    // show score on dev data?\n    report++;\n    if (report % dev_every_i_reports == 0) {\n      double dloss = 0;\n      int dchars = 0;\n      for (auto& sent : dev) {\n        ComputationGraph cg;\n        lm.BuildGraph(sent, sent, cg);\n        dloss += as_scalar(cg.forward());\n        dchars += sent.size() - 1;\n      }\n      if (dloss < best) {\n        best = dloss;\n        ofstream out(fname);\n        boost::archive::text_oarchive oa(out);\n        oa << model << emb;\n      }\n      cerr << \"\\n***DEV [epoch=\" << (lines / (double)training.size()) << \"] E = \" << (dloss / dchars) << \" ppl=\" << exp(dloss / dchars) << ' ';\n    }\n#endif\n  }\n  delete sgd;\n}\n\n", "meta": {"hexsha": "6a2ef31d64c0d8430b8e3e626497e1bf24bc1bbc", "size": 6267, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/cpp/embed-cl/train_embed-cl.cc", "max_stars_repo_name": "MalcolmSun/dynet", "max_stars_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-10T17:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T17:40:09.000Z", "max_issues_repo_path": "examples/cpp/embed-cl/train_embed-cl.cc", "max_issues_repo_name": "MalcolmSun/dynet", "max_issues_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "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/cpp/embed-cl/train_embed-cl.cc", "max_forks_repo_name": "MalcolmSun/dynet", "max_forks_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "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.1298701299, "max_line_length": 143, "alphanum_fraction": 0.5811393011, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.19229519672268344}}
{"text": "// Copyright (c) 2019 yshurik\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 <boost/assign/list_of.hpp>\n\n#include \"base58.h\"\n#include \"rpcserver.h\"\n#include \"txdb.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"net.h\"\n#include \"keystore.h\"\n#include \"wallet.h\"\n\n#include \"pegops.h\"\n#include \"pegopsp.h\"\n#include \"pegdata.h\"\n\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/split.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace json_spirit;\n\nvoid printpegshift(const CFractions & frPegShift,\n                   const CPegLevel & peglevel,\n                   Object & result);\n\nvoid printpeglevel(const CPegLevel & peglevel,\n                   Object & result);\n\nvoid printpegbalance(const CPegData & pegdata,\n                     Object & result,\n                     string prefix);\n\n// API calls\n\nValue getpeglevel(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 3)\n        throw runtime_error(\n            \"getpeglevel \"\n                \"<exchange_pegdata_base64> \"\n                \"<pegshift_pegdata_base64> \"\n                \"<previous_cycle>\\n\"\n            );\n    \n    string exchange_pegdata64 = params[0].get_str();\n    string pegshift_pegdata64 = params[1].get_str();\n    int nCyclePrev = params[2].get_int();\n    \n    CPegData pdExchange(exchange_pegdata64);\n    if (!pdExchange.IsValid()) {\n        string err = \"Can not unpack 'exchange' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n\n    CPegData pdPegShift(pegshift_pegdata64);\n    if (!pdPegShift.IsValid()) {\n        string err = \"Can not unpack 'pegshift' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    int nSupplyNow = pindexBest ? pindexBest->nPegSupplyIndex : 0;\n    int nSupplyNext = pindexBest ? pindexBest->GetNextIntervalPegSupplyIndex() : 0;\n    int nSupplyNextNext = pindexBest ? pindexBest->GetNextNextIntervalPegSupplyIndex() : 0;\n    \n    int nPegInterval = Params().PegInterval(nBestHeight);\n    int nCycleNow = nBestHeight / nPegInterval;\n    int nBuffer = 3;\n    \n    if (nCycleNow <= nCyclePrev) {\n        std::stringstream ss;\n        ss << \"Current cycle \"\n           << nCycleNow\n           << \" should be greater than previous \"\n           << nCyclePrev;\n        string err = ss.str();\n        throw JSONRPCError(RPC_MISC_ERROR, err);\n    }\n    \n    if (nBestHeight < nPegStartHeight) { // run on zero levels before the peg\n        nBuffer = 0;\n        nSupplyNow = 0;\n        nSupplyNext = 0;\n        nSupplyNextNext = 0;\n    }\n    \n    string err;\n    CPegLevel peglevel(\"\");\n    CPegData pdPegPool;\n    \n    bool ok = pegops::getpeglevel(\n                nCycleNow,\n                nCyclePrev,\n                nBuffer,\n                nSupplyNow,\n                nSupplyNext,\n                nSupplyNextNext,\n                pdExchange,\n                pdPegShift,\n                \n                peglevel,\n                pdPegPool,\n                err\n    );\n    if (!ok) {\n        throw JSONRPCError(RPC_MISC_ERROR, err);\n    }\n    \n    // update exchange datas \n    pdExchange.peglevel = peglevel;\n    pdExchange.nLiquid = pdExchange.fractions.High(peglevel);\n    pdExchange.nReserve = pdExchange.fractions.Low(peglevel);\n    \n    Object result;\n    result.push_back(Pair(\"cycle\", peglevel.nCycle));\n\n    printpeglevel(peglevel, result);\n    printpegbalance(pdPegPool, result, \"pegpool_\");\n    printpegbalance(pdExchange, result, \"exchange_\");\n    printpegshift(pdPegShift.fractions, peglevel, result);\n    \n    return result;\n}\n\nValue makepeglevel(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 8)\n        throw runtime_error(\n            \"makepeglevel \"\n                \"<current_cycle> \"\n                \"<previous_cycle> \"\n                \"<pegbuffer> \"\n                \"<pegsupplyindex> \"\n                \"<pegsupplyindex_next> \"\n                \"<pegsupplyindex_nextnext> \"\n                \"<exchange_pegdata_base64> \"\n                \"<pegshift_pegdata_base64>\\n\"\n            );\n    \n    int cycle_now = params[0].get_int();\n    int cycle_prev = params[1].get_int();\n    int buffer = params[2].get_int();\n    int supply_now = params[3].get_int();\n    int supply_next = params[4].get_int();\n    int supply_next_next = params[5].get_int();\n    string exchange_pegdata64 = params[6].get_str();\n    string pegshift_pegdata64 = params[7].get_str();\n    \n    CPegData pdExchange(exchange_pegdata64);\n    if (!pdExchange.IsValid()) {\n        string err = \"Can not unpack 'exchange' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n\n    CPegData pdPegShift(pegshift_pegdata64);\n    if (!pdPegShift.IsValid()) {\n        string err = \"Can not unpack 'pegshift' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    string err;\n    CPegLevel peglevel(\"\");\n    CPegData pdPegPool;\n\n    bool ok = pegops::getpeglevel(\n                cycle_now,\n                cycle_prev,\n                buffer,\n                supply_now,\n                supply_next,\n                supply_next_next,\n                pdExchange,\n                pdPegShift,\n                \n                peglevel,\n                pdPegPool,\n                err\n    );\n    if (!ok) {\n        throw JSONRPCError(RPC_MISC_ERROR, err);\n    }\n    \n    // update exchange datas \n    pdExchange.peglevel = peglevel;\n    pdExchange.nLiquid = pdExchange.fractions.High(peglevel);\n    pdExchange.nReserve = pdExchange.fractions.Low(peglevel);\n    \n    Object result;\n    result.push_back(Pair(\"cycle\", peglevel.nCycle));\n\n    printpeglevel(peglevel, result);\n    printpegbalance(pdPegPool, result, \"pegpool_\");\n    printpegbalance(pdExchange, result, \"exchange_\");\n    printpegshift(pdPegShift.fractions, peglevel, result);\n    \n    return result;\n}\n\nValue updatepegbalances(const Array& params, bool fHelp)\n{\n    if (fHelp || (params.size() != 3))\n        throw runtime_error(\n            \"updatepegbalances \"\n                \"<balance_pegdata_base64> \"\n                \"<pegpool_pegdata_base64> \"\n                \"<peglevel_hex>\\n\"\n            );\n    \n    string inp_balance_pegdata64 = params[0].get_str();\n    string inp_pegpool_pegdata64 = params[1].get_str();\n    string inp_peglevel_hex = params[2].get_str();\n        \n    CPegData pdBalance(inp_balance_pegdata64);\n    if (!pdBalance.IsValid()) {\n        string err = \"Can not unpack 'balance' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n\n    CPegData pdPegPool(inp_pegpool_pegdata64);\n    if (!pdPegPool.IsValid()) {\n        string err = \"Can not unpack 'pegpool' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    CPegLevel peglevelNew(inp_peglevel_hex);\n    if (!peglevelNew.IsValid()) {\n        string err = \"Can not unpack peglevel\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n\n    string err;\n    \n    bool ok = pegops::updatepegbalances(\n            pdBalance,\n            pdPegPool,\n            peglevelNew,\n\n            err);\n    \n    if (!ok) {\n        throw JSONRPCError(RPC_MISC_ERROR, err);\n    }\n\n    Object result;\n\n    result.push_back(Pair(\"completed\", true));\n    result.push_back(Pair(\"cycle\", peglevelNew.nCycle));\n    \n    printpeglevel(peglevelNew, result);\n    printpegbalance(pdBalance, result, \"balance_\");\n    printpegbalance(pdPegPool, result, \"pegpool_\");\n    \n    return result;\n}\n\nValue movecoins(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 4)\n        throw runtime_error(\n            \"movecoins \"\n                \"<amount> \"\n                \"<src_pegdata_base64> \"\n                \"<dst_pegdata_base64> \"\n                \"<peglevel_hex>\\n\"\n            );\n    \n    int64_t inp_move_amount = params[0].get_int64();\n    string inp_src_pegdata64 = params[1].get_str();\n    string inp_dst_pegdata64 = params[2].get_str();\n    string inp_peglevel_hex = params[3].get_str();\n    \n    CPegData pdSrc(inp_src_pegdata64);\n    if (!pdSrc.IsValid()) {\n        string err = \"Can not unpack 'src' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n\n    CPegData pdDst(inp_dst_pegdata64);\n    if (!pdDst.IsValid()) {\n        string err = \"Can not unpack 'dst' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    CPegLevel peglevel(inp_peglevel_hex);\n    if (!peglevel.IsValid()) {\n        string err = \"Can not unpack peglevel\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    string err;\n    \n    bool ok = pegops::movecoins(\n                inp_move_amount,\n                pdSrc,\n                pdDst,\n                peglevel,\n                true,\n            \n                err);\n    \n    if (!ok) {\n        throw JSONRPCError(RPC_MISC_ERROR, err);\n    }\n    \n    Object result;\n    \n    result.push_back(Pair(\"cycle\", peglevel.nCycle));\n    \n    printpeglevel(peglevel, result);\n    printpegbalance(pdSrc, result, \"src_\");\n    printpegbalance(pdDst, result, \"dst_\");\n    \n    return result;\n}\n\nValue moveliquid(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 4)\n        throw runtime_error(\n            \"moveliquid \"\n                \"<liquid> \"\n                \"<src_pegdata_base64> \"\n                \"<dst_pegdata_base64> \"\n                \"<peglevel_hex>\\n\"\n            );\n    \n    int64_t inp_move_liquid = params[0].get_int64();\n    string inp_src_pegdata64 = params[1].get_str();\n    string inp_dst_pegdata64 = params[2].get_str();\n    string inp_peglevel_hex = params[3].get_str();\n    \n    CPegData pdSrc(inp_src_pegdata64);\n    if (!pdSrc.IsValid()) {\n        string err = \"Can not unpack 'src' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n\n    CPegData pdDst(inp_dst_pegdata64);\n    if (!pdDst.IsValid()) {\n        string err = \"Can not unpack 'dst' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    CPegLevel peglevel(inp_peglevel_hex);\n    if (!peglevel.IsValid()) {\n        string err = \"Can not unpack peglevel\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    string err;\n    \n    bool ok = pegops::moveliquid(\n            inp_move_liquid,\n            pdSrc,\n            pdDst,\n            peglevel,\n            \n            err);\n    \n    if (!ok) {\n        throw JSONRPCError(RPC_MISC_ERROR, err);\n    }\n    \n    Object result;\n    \n    result.push_back(Pair(\"cycle\", peglevel.nCycle));\n    \n    printpeglevel(peglevel, result);\n    printpegbalance(pdSrc, result, \"src_\");\n    printpegbalance(pdDst, result, \"dst_\");\n    \n    return result;\n}\n\nValue movereserve(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 4)\n        throw runtime_error(\n            \"movereserve \"\n                \"<reserve> \"\n                \"<src_pegdata_base64> \"\n                \"<dst_pegdata_base64> \"\n                \"<peglevel_hex>\\n\"\n            );\n    \n    int64_t inp_move_reserve = params[0].get_int64();\n    string inp_src_pegdata64 = params[1].get_str();\n    string inp_dst_pegdata64 = params[2].get_str();\n    string inp_peglevel_hex = params[3].get_str();\n    \n    CPegData pdSrc(inp_src_pegdata64);\n    if (!pdSrc.IsValid()) {\n        string err = \"Can not unpack 'src' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n\n    CPegData pdDst(inp_dst_pegdata64);\n    if (!pdDst.IsValid()) {\n        string err = \"Can not unpack 'dst' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    CPegLevel peglevel(inp_peglevel_hex);\n    if (!peglevel.IsValid()) {\n        string err = \"Can not unpack peglevel\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    string err;\n    \n    bool ok = pegops::movereserve(\n            inp_move_reserve,\n            pdSrc,\n            pdDst,\n            peglevel,\n            \n            err);\n    \n    if (!ok) {\n        throw JSONRPCError(RPC_MISC_ERROR, err);\n    }\n    \n    Object result;\n    \n    result.push_back(Pair(\"cycle\", peglevel.nCycle));\n    \n    printpeglevel(peglevel, result);\n    printpegbalance(pdSrc, result, \"src_\");\n    printpegbalance(pdDst, result, \"dst_\");\n    \n    return result;\n}\n\nValue removecoins(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 2)\n        throw runtime_error(\n            \"removecoins \"\n                \"<from_pegdata_base64> \"\n                \"<remove_pegdata_base64>\\n\"\n            );\n    \n    string inp_from_pegdata64 = params[0].get_str();\n    string inp_remove_pegdata64 = params[1].get_str();\n    \n    CPegData pdFrom(inp_from_pegdata64);\n    if (!pdFrom.IsValid()) {\n        string err = \"Can not unpack 'from' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n\n    CPegData pdRemove(inp_remove_pegdata64);\n    if (!pdRemove.IsValid()) {\n        string err = \"Can not unpack 'remove' pegdata\";\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n    }\n    \n    pdFrom.fractions    -= pdRemove.fractions;\n    pdFrom.nLiquid      -= pdRemove.nLiquid;\n    pdFrom.nReserve     -= pdRemove.nReserve;\n    \n    Object result;\n    \n    printpegbalance(pdFrom, result, \"out_\");\n    \n    return result;\n}\n", "meta": {"hexsha": "40b518d8e493cea93a337cf9e229048a2fd35237", "size": 13337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/exchange/rpcexchange.cpp", "max_stars_repo_name": "bitbaymarket/BitBay", "max_stars_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-07-12T01:05:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T03:11:36.000Z", "max_issues_repo_path": "src/exchange/rpcexchange.cpp", "max_issues_repo_name": "bitbaymarket/BitBay", "max_issues_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2016-05-06T11:02:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-26T12:43:20.000Z", "max_forks_repo_path": "src/exchange/rpcexchange.cpp", "max_forks_repo_name": "bitbaymarket/BitBay", "max_forks_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-01-04T11:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T19:20:16.000Z", "avg_line_length": 28.1966173362, "max_line_length": 91, "alphanum_fraction": 0.5918122516, "num_tokens": 3424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.19229518937991608}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef denovo_model_hpp\n#define denovo_model_hpp\n\n#include <cstddef>\n#include <unordered_map>\n#include <string>\n#include <utility>\n\n#include <boost/optional.hpp>\n#include <boost/functional/hash.hpp>\n\n#include \"core/types/haplotype.hpp\"\n#include \"../pairhmm/pair_hmm.hpp\"\n#include \"indel_mutation_model.hpp\"\n\nnamespace octopus {\n\nclass DeNovoModel\n{\npublic:\n    struct Parameters\n    {\n        double snv_mutation_rate, indel_mutation_rate;\n    };\n    \n    enum class CachingStrategy { none, value, address };\n    \n    DeNovoModel() = delete;\n    \n    DeNovoModel(Parameters parameters,\n                std::size_t num_haplotypes_hint = 1000,\n                CachingStrategy caching = CachingStrategy::value);\n    \n    DeNovoModel(const DeNovoModel&)            = default;\n    DeNovoModel& operator=(const DeNovoModel&) = default;\n    DeNovoModel(DeNovoModel&&)                 = default;\n    DeNovoModel& operator=(DeNovoModel&&)      = default;\n    \n    ~DeNovoModel() = default;\n    \n    void prime(std::vector<Haplotype> haplotypes);\n    void unprime() noexcept;\n    bool is_primed() const noexcept;\n    \n    // ln p(target | given)\n    double evaluate(const Haplotype& target, const Haplotype& given) const;\n    double evaluate(unsigned target, unsigned given) const;\n    \nprivate:\n    struct AddressPairHash\n    {\n        std::size_t operator()(const std::pair<const Haplotype*, const Haplotype*>& p) const noexcept\n        {\n            auto result = boost::hash_value(p.first);\n            boost::hash_combine(result, p.second);\n            return result;\n        }\n    };\n    \n    using PenaltyVector   = hmm::VariableGapOpenMutationModel::PenaltyVector;\n    using GapPenaltyModel = std::pair<PenaltyVector, PenaltyVector>;\n    \n    hmm::FlatGapMutationModel flat_mutation_model_;\n    IndelMutationModel indel_model_;\n    boost::optional<double> min_ln_probability_;\n    std::size_t num_haplotypes_hint_;\n    std::vector<Haplotype> haplotypes_;\n    CachingStrategy caching_;\n    \n    mutable PenaltyVector gap_open_penalties_, gap_extend_penalties_;\n    mutable std::vector<boost::optional<GapPenaltyModel>> gap_model_index_cache_;\n    mutable std::unordered_map<Haplotype, std::unordered_map<Haplotype, double>> value_cache_;\n    mutable std::unordered_map<std::pair<const Haplotype*, const Haplotype*>, double, AddressPairHash> address_cache_;\n    mutable std::vector<std::vector<boost::optional<double>>> guarded_index_cache_;\n    mutable std::vector<std::vector<double>> unguarded_index_cache_;\n    mutable std::string padded_given_;\n    mutable bool use_unguarded_;\n    \n    void set_gap_penalties(const Haplotype& given) const;\n    void set_gap_penalties(unsigned given) const;\n    hmm::VariableGapExtendMutationModel make_hmm_model_from_cache() const;\n    double evaluate_uncached(const Haplotype& target, const Haplotype& given, bool gap_penalties_cached = false) const;\n    double evaluate_uncached(unsigned target, unsigned given) const;\n    double evaluate_basic_cache(const Haplotype& target, const Haplotype& given) const;\n    double evaluate_address_cache(const Haplotype& target, const Haplotype& given) const;\n};\n\n} // namespace octopus\n\n \n#endif\n", "meta": {"hexsha": "9c13360c63ed8c49e987031f31ea9692e3a3f508", "size": 3310, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/mutation/denovo_model.hpp", "max_stars_repo_name": "alimanfoo/octopus", "max_stars_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-21T23:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T23:34:28.000Z", "max_issues_repo_path": "src/core/models/mutation/denovo_model.hpp", "max_issues_repo_name": "alimanfoo/octopus", "max_issues_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_issues_repo_licenses": ["MIT"], "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/denovo_model.hpp", "max_forks_repo_name": "alimanfoo/octopus", "max_forks_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_forks_repo_licenses": ["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.8421052632, "max_line_length": 119, "alphanum_fraction": 0.7148036254, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19229518937991608}}
{"text": "/******************************************************************************\n *\n * Copyright 2018 Xaptum, 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#include <xtt/asio.hpp>\n\n#include <sodium.h>\n\n#include <boost/asio.hpp>\n\n#include <cstdlib>\n\n#include <iostream>\n#include <fstream>\n#include <memory>\n\nconst char *daa_gpk_file = \"daa_gpk.bin\";\nconst char *basename_file = \"basename.bin\";\nconst char *server_certificate_file = \"server_certificate.bin\";\nconst char *server_privatekey_file = \"server_privatekey.bin\";\n\nclass xtt_server {\npublic:\n    xtt_server(boost::asio::io_context& io_context,\n               short port,\n               const std::vector<unsigned char>& certificate,\n               const std::vector<unsigned char>& private_key,\n               xtt::server_cookie_context& cookie_ctx,\n               std::unordered_map<xtt::group_identity, std::unique_ptr<xtt::group_public_key_context>>& gpk_map)\n        : acceptor_(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)),\n          certificate_(certificate),\n          private_key_(private_key),\n          cookie_ctx_(cookie_ctx),\n          gpk_map_(gpk_map),\n          xtt_contexts_(),\n          io_context_(io_context)\n    {\n        do_accept();\n    }\n\nprivate:\n    void do_accept()\n    {\n        acceptor_.async_accept([this](boost::system::error_code ec, boost::asio::ip::tcp::socket socket)\n                               {\n                                   if (!ec) {\n                                       run_handshake(std::move(socket));\n                                   }\n\n                                   do_accept();\n                               });\n    }\n\n    void run_handshake(boost::asio::ip::tcp::socket socket)\n    {\n        xtt_contexts_.emplace_back(std::move(socket), cookie_ctx_);\n        xtt::asio::server_context& xtt_context = xtt_contexts_.back();\n\n        boost::system::error_code cert_ec;\n        xtt_context.load_certificate(certificate_, private_key_, cert_ec);\n        if (cert_ec) {\n            std::cerr << \"Error deserializing certificate\\n\";\n            return;\n        }\n\n        xtt_context.async_handle_connect([this](xtt::group_identity claimed_gid,\n                                                xtt::identity requested_client_id,\n                                                auto&& continuation)\n                                         {\n                                            (void)requested_client_id;\n\n                                             this->async_lookup_gpk(claimed_gid, continuation);\n                                         },\n                                         [this, &xtt_context](xtt::group_identity claimed_gid,\n                                                              xtt::identity requested_client_id,\n                                                              auto&& continuation)\n                                         {\n                                             this->async_assign_id(claimed_gid, requested_client_id, xtt_context, continuation);\n                                         },\n                                         [this, &xtt_context](const boost::system::error_code& ec)\n                                         {\n                                             this->handle_handshake(ec, xtt_context);\n                                         });\n    }\n\n    template <typename AsyncContinuation>\n    void\n    async_lookup_gpk(const xtt::group_identity& claimed_gid, AsyncContinuation continuation)\n    {\n        auto gpk_it = gpk_map_.find(claimed_gid);\n        if (gpk_map_.end() == gpk_it) {\n            std::cerr << \"Error: claimed group ID '\" << claimed_gid << \"' doesn't match any known\\n\";\n            boost::asio::post(io_context_,\n                              [continuation]()\n                              {\n                                  continuation(xtt::asio::get_unknown_gid_ec(),\n                                               std::unique_ptr<xtt::group_public_key_context>());\n                              });\n            return;\n        }\n\n        boost::asio::post(io_context_,\n                          [continuation, gpk_it]()\n                          {\n                              continuation(boost::system::error_code(), gpk_it->second->clone());\n                          });\n    }\n\n    template <typename AsyncContinuation>\n    void\n    async_assign_id(const xtt::group_identity& claimed_gid,\n                    const xtt::identity requested_client_id,\n                    xtt::asio::server_context& xtt_context,\n                    AsyncContinuation continuation)\n    {\n        auto clients_pseudonym = xtt_context.get_clients_pseudonym();\n        if (!clients_pseudonym) {\n            std::cerr << \"Unable to get client's pseudonym, while assigning an ID\\n\";\n            boost::asio::post(io_context_,\n                              [continuation]()\n                              {\n                                  continuation(xtt::asio::get_bad_id_ec(),\n                                               xtt::identity());\n                              });\n            return;\n        }\n\n        xtt::identity assigned_id;\n        // If the client sent xtt_null_client_id assign them id = SHA-256(GID || pseudonym) (truncated to first 16bytes)\n        // Otherwise, just echo back what they requested.\n        if (requested_client_id.is_null()) {\n            std::vector<unsigned char> new_id_serialized(crypto_hash_sha256_BYTES);\n            crypto_hash_sha256_state h;\n            crypto_hash_sha256_init(&h);\n            std::vector<unsigned char> gid_serial = claimed_gid.serialize();\n            crypto_hash_sha256_update(&h, gid_serial.data(), gid_serial.size());\n            std::vector<unsigned char> pseudonym_serial = clients_pseudonym->serialize();\n            crypto_hash_sha256_update(&h, pseudonym_serial.data(), pseudonym_serial.size());\n            crypto_hash_sha256_final(&h, new_id_serialized.data());\n            new_id_serialized.resize(sizeof(xtt_identity_type));\n            auto new_id = xtt::identity::deserialize(new_id_serialized);\n            if (!new_id) {\n                std::cerr << \"Error creating new identity\\n\";\n                boost::asio::post(io_context_,\n                                  [continuation]()\n                                  {\n                                      continuation(xtt::asio::get_bad_id_ec(),\n                                                   xtt::identity());\n                                  });\n                return;\n            }\n\n            assigned_id = *new_id;\n        } else {\n            assigned_id = requested_client_id;\n        }\n\n        boost::asio::post(io_context_,\n                          [continuation, assigned_id]()\n                          {\n                              continuation(boost::system::error_code(), assigned_id);\n                          });\n    }\n\n    void handle_handshake(const boost::system::error_code& ec,\n                          xtt::asio::server_context& xtt_context)\n    {\n        if (!ec) {\n            std::cout << \"Successfully finished handshake:\\n\";\n\n            auto clients_pseudonym = xtt_context.get_clients_pseudonym();\n            if (!clients_pseudonym) {\n                std::cerr << \"Error retrieving client's pseudonym!\";\n                return;\n            }\n            std::cout << \"\\tClient's pseudonym:       \" << *clients_pseudonym << \"\\n\";\n\n            auto clients_id = xtt_context.get_clients_identity();\n            if (!clients_id) {\n                std::cerr << \"Error retrieving client's assigned id!\";\n                return;\n            }\n            std::cout << \"\\tWe assigned the identity: \" << *clients_id << \"\\n\";\n\n            auto clients_longterm_key = xtt_context.get_clients_longterm_key();\n            if (!clients_longterm_key) {\n                std::cerr << \"Error retrieving client's longterm public key!\";\n                return;\n            }\n            std::cout << \"\\tClient has longterm key:  \" << *clients_longterm_key << \"\\n\";\n        } else {\n            std::cout << \"Error during handshake: \" << ec << std::endl;\n        }\n\n        xtt_context.lowest_layer().close(); // we should also remove xtt_context from our vector\n    }\n\nprivate:\n    boost::asio::ip::tcp::acceptor acceptor_;\n\n    std::vector<unsigned char> certificate_;\n    std::vector<unsigned char> private_key_;\n\n    xtt::server_cookie_context& cookie_ctx_;\n    std::unordered_map<xtt::group_identity, std::unique_ptr<xtt::group_public_key_context>>& gpk_map_;\n\n    std::vector<xtt::asio::server_context> xtt_contexts_;\n\n    boost::asio::io_context& io_context_;\n};\n\nvoid parse_cmd_args(int argc, char *argv[], short *port);\n\nint initialize(std::vector<unsigned char>& certificate,\n               std::vector<unsigned char>& private_key,\n               std::unordered_map<xtt::group_identity, std::unique_ptr<xtt::group_public_key_context>>& gpk_map);\n\nint main(int argc, char *argv[])\n{\n    // 1) Parse args\n    short server_port;\n    parse_cmd_args(argc, argv, &server_port);\n\n    // 2) Setup necessary XTT information (used by all handshakes)\n    std::vector<unsigned char> certificate;\n    std::vector<unsigned char> private_key;\n    xtt::server_cookie_context cookie_ctx;\n    std::unordered_map<xtt::group_identity, std::unique_ptr<xtt::group_public_key_context>> gpk_map;\n    int ret;\n    ret = initialize(certificate, private_key, gpk_map);\n    if (0 != ret) {\n        std::cerr << \"Error initializing persistent XTT contexts\\n\";\n        return 1;\n    }\n\n    // 3) Start server\n    boost::asio::io_context io_context;\n    xtt_server serv{io_context, server_port, certificate, private_key, cookie_ctx, gpk_map};\n\n    // 4) Run event loop\n    io_context.run();\n}\n\nvoid parse_cmd_args(int argc, char *argv[], short *port)\n{\n    if (2 != argc) {\n        std::cerr<< \"usage: \" << argv[0] << \" <server port>\\n\";\n        exit(1);\n    }\n\n    *port = std::atoi(argv[1]);\n}\n\nint initialize(std::vector<unsigned char>& certificate,\n               std::vector<unsigned char>& private_key,\n               std::unordered_map<xtt::group_identity, std::unique_ptr<xtt::group_public_key_context>>& gpk_map)\n{\n    // 1) Read DAA GPK from file.\n    std::ifstream gpk_file(daa_gpk_file, std::ios::in | std::ios::binary);\n    std::vector<unsigned char> serialized_gpk((std::istreambuf_iterator<char>(gpk_file)), std::istreambuf_iterator<char>());\n    \n    // 2) Read DAA basename from file\n    std::ifstream bsn_file(basename_file, std::ios::in | std::ios::binary);\n    std::vector<unsigned char> basename((std::istreambuf_iterator<char>(bsn_file)), std::istreambuf_iterator<char>());\n\n    // 3) Initialize DAA context\n    auto gpk = xtt::group_public_key_context_lrsw::from_gpk_and_basename(serialized_gpk, basename);\n    if (!gpk) {\n        std::cerr << \"Error deserializing GPK and basename\\n\";\n        return -1;\n    }\n    std::cout << \"Using group public key context: \" << *gpk << std::endl;\n\n    // 4) Generate GID from GPK (GID = SHA-256(GPK))\n    std::vector<unsigned char> raw_gid(crypto_hash_sha256_BYTES);\n    crypto_hash_sha256_state h;\n    crypto_hash_sha256_init(&h);\n    std::vector<unsigned char> gpk_serial = gpk->get_gpk();\n    crypto_hash_sha256_update(&h, gpk_serial.data(), gpk_serial.size());\n    crypto_hash_sha256_final(&h, raw_gid.data());\n    auto gid = xtt::group_identity::deserialize(raw_gid);\n    if (!gid) {\n        std::cerr << \"Error computing GID from GPK\\n\";\n        return -1;\n    }\n    std::cout << \"\\twith GID: \" << *gid << std::endl;\n\n    // 4ii) Insert gpk into map\n    gpk_map[*gid] = std::move(gpk);\n\n    // 5) Read in my certificate from file\n    std::ifstream cert_file(server_certificate_file, std::ios::in | std::ios::binary);\n    certificate.assign((std::istreambuf_iterator<char>(cert_file)), std::istreambuf_iterator<char>());\n\n    // 6) Read in my private key from file\n    std::ifstream privkey_file(server_privatekey_file, std::ios::in | std::ios::binary);\n    private_key.assign((std::istreambuf_iterator<char>(privkey_file)), std::istreambuf_iterator<char>());\n\n    return 0;\n}\n", "meta": {"hexsha": "875fe2031b1e34adbc1403d6a36406ac10ddd563", "size": 12737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/xtt_asio_server.cpp", "max_stars_repo_name": "xaptum/xtt-cpp", "max_stars_repo_head_hexsha": "d82f4c33e6c67e343da70f3b73dea67c0a8bf6f1", "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/xtt_asio_server.cpp", "max_issues_repo_name": "xaptum/xtt-cpp", "max_issues_repo_head_hexsha": "d82f4c33e6c67e343da70f3b73dea67c0a8bf6f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-05-14T15:29:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-19T22:04:40.000Z", "max_forks_repo_path": "examples/xtt_asio_server.cpp", "max_forks_repo_name": "xaptum/xtt-cpp", "max_forks_repo_head_hexsha": "d82f4c33e6c67e343da70f3b73dea67c0a8bf6f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-05-07T14:27:00.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-20T18:29:43.000Z", "avg_line_length": 40.4349206349, "max_line_length": 128, "alphanum_fraction": 0.5524848866, "num_tokens": 2685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19229518937991608}}
{"text": "// Copyright (c) 2018 Graphcore Ltd. All rights reserved.\n\n#include \"PoolPlan.hpp\"\n#include \"../poplin/ConvPlan.hpp\"\n#include \"PerformanceEstimation.hpp\"\n#include \"PoolVertices.hpp\"\n#include \"poplibs_support/VectorUtils.hpp\"\n#include \"poplibs_support/gcd.hpp\"\n#include \"poplibs_support/print.hpp\"\n#include \"poplin/ConvUtil.hpp\"\n#include \"poputil/VarStructure.hpp\"\n#include <poplibs_support/Memoize.hpp>\n#include <popsolver/Model.hpp>\n\n#include <boost/range/adaptor/reversed.hpp>\n\n#include <unordered_set>\n\nusing namespace poputil;\n\nnamespace popnn {\nnamespace pooling {\n\n// Constraint variables that represent how variables are partitioned per tile\nstruct PartitionVariables {\n  popsolver::Variable batchSplit;\n  popsolver::Variable chanGroupsSplit;\n  popsolver::Variable chansPerGroup;\n  std::vector<popsolver::Variable> fieldSplit;\n  PartitionVariables() = default;\n};\n\n// Create Partition from the solution to the Pooling Plan solver\nstatic Partition makePartition(const popsolver::Solution &solution,\n                               const PartitionVariables &vars) {\n  Partition partition;\n  partition.chansPerGroup = solution[vars.chansPerGroup].getAs<unsigned>();\n  partition.batch = solution[vars.batchSplit].getAs<unsigned>();\n  partition.chanGroups = solution[vars.chanGroupsSplit].getAs<unsigned>();\n  partition.field.reserve(vars.fieldSplit.size());\n  partition.kernel.reserve(vars.fieldSplit.size());\n  for (unsigned i = 0; i < vars.fieldSplit.size(); i++) {\n    partition.field.push_back(solution[vars.fieldSplit[i]].getAs<unsigned>());\n\n    // currently kernel is not split. set it to 1\n    partition.kernel.push_back(1);\n  }\n  return partition;\n}\n\n// Create Partition from component vector\nstatic Partition makePartition(const std::vector<unsigned> &values,\n                               const unsigned numFieldDims) {\n  Partition partition;\n  partition.batch = values[0];\n  partition.chanGroups = values[1];\n  partition.chansPerGroup = values[2];\n  partition.field.insert(partition.field.begin(), values.begin() + 3,\n                         values.begin() + 3 + numFieldDims);\n  partition.kernel.insert(partition.kernel.begin(),\n                          values.begin() + 3 + numFieldDims,\n                          values.begin() + 3 + (2 * numFieldDims));\n  return partition;\n}\n\n// dim is given as an index into an activation shaped tensor\n// [N][....F..][C]\nstatic bool canFlattenDim(const poplin::ConvParams &params, unsigned dim) {\n  if (dim >= params.getNumFieldDims() + 1) {\n    return false;\n  }\n  if (dim == 0) {\n    return true;\n  }\n  if (params.kernelShape[dim - 1] != 1) {\n    return false;\n  }\n  // With striding in this dimension this doesn't make\n  // a lot of sense.\n  if (params.outputTransform.stride[dim - 1] != 1 ||\n      params.inputTransform.dilation[dim - 1] != 1) {\n    return false;\n  }\n  return true;\n}\n\nstatic Transform getTransform(const poplar::Graph &graph,\n                              const poplin::ConvParams &params,\n                              const poplar::Tensor &in,\n                              std::size_t chanGrainSize) {\n  Transform transform;\n  // If we don't have enough channels, prefer to take some elements\n  // of another dimension to introducing padding.\n  const std::size_t numChans = params.getNumInputChans();\n  if (numChans < chanGrainSize) {\n    std::size_t currentFactor = 1;\n    const auto desiredFactor = lcm(numChans, chanGrainSize) / numChans;\n\n    auto groupings = detectDimGroupings(graph, in);\n\n    // Flatten independent spatial dimensions into channels.\n    //\n    // Try to flatten spatial dimensions with a detectable grouping first.\n    std::unordered_set<std::size_t> transformedDims;\n    for (const auto &entry : groupings) {\n      const auto d = entry.first;\n      const std::size_t grouping = entry.second;\n      if (canFlattenDim(params, d) && transformedDims.count(d) == 0 &&\n          currentFactor < desiredFactor) {\n        const auto f =\n            gcd(desiredFactor / currentFactor, gcd(in.dim(d), grouping));\n        transform.flattenDims.push_back(std::make_pair(d, f));\n        transformedDims.emplace(d);\n        currentFactor *= f;\n      }\n    }\n    // Flatten any remaining dims possible, innermost spatial dimension first.\n    for (int d = params.getNumFieldDims(); d >= 0; --d) {\n      if (canFlattenDim(params, d) && transformedDims.count(d) == 0 &&\n          currentFactor < desiredFactor) {\n        const auto f = gcd(desiredFactor / currentFactor, in.dim(d));\n        transform.flattenDims.push_back(std::make_pair(d, f));\n        transformedDims.emplace(d);\n        currentFactor *= f;\n      }\n    }\n  }\n  return transform;\n}\n// Functions to cache cycle estimates using a map. We need std::hash and ==\n// operator to be implemented in order to memoize\n\nclass EstimateCache {\npublic:\n  decltype(poplibs_support::memoize(\n      poolVertexCycleEstimate)) mPoolVertexCycleEstimate;\n  EstimateCache() : mPoolVertexCycleEstimate(poolVertexCycleEstimate) {}\n};\n\nstatic std::uint64_t getNumberOfOperations(const poplin::ConvParams &params) {\n  // The operations used in pooling can be calculated in a similar way to\n  // convolution, except that each channel is independent.\n  auto convParams = params;\n  convParams.inputChannelsPerConvGroup = 1;\n\n  return getNumberOfMACs(convParams);\n}\n\nstatic std::size_t getBytesRequiredPerTile(const Partition &perTile,\n                                           const poplin::ConvParams &params,\n                                           const PoolConfig &poolCfg,\n                                           unsigned bytesPerInputElement) {\n  // In each dimension that the kernel moves in, each new output needs a\n  // contiguous slice of input of size \"stride\" plus the amount the kernel adds\n  // which is \"kernelSize-stride\"\n  std::size_t inFieldElementsPerTile = 1;\n  for (unsigned i = 0; i < perTile.field.size(); i++) {\n    const auto factor = perTile.field[i] * params.outputTransform.stride[i] +\n                        perTile.kernel[i] - params.outputTransform.stride[i];\n    inFieldElementsPerTile *= factor;\n  }\n  const std::size_t inBytesPerTile =\n      inFieldElementsPerTile * perTile.batch * perTile.chanGroups *\n      perTile.chansPerGroup * bytesPerInputElement;\n  const std::size_t outBytesPerTile =\n      product(perTile.field) * perTile.batch * perTile.chanGroups *\n      perTile.chansPerGroup * bytesPerInputElement;\n  // Some vertices require more inputs.\n  if (poolCfg.pass == PoolPass::POOL_BWD && poolCfg.type == PoolingType::MAX) {\n    // 3 inputs: `fwdActsIn` is the size of the output field, `fwdActsOut` and\n    // `in` are the size of the input field\n    return 2 * inBytesPerTile + outBytesPerTile;\n  }\n  if (poolCfg.pass == PoolPass::POOL_FWD && poolCfg.type == PoolingType::MAX &&\n      poolCfg.scaledGradient) {\n    // 2 inputs: `fwdActsOut` is the size of the output field, `in` is the size\n    // of the input field\n    return inBytesPerTile + outBytesPerTile;\n  }\n  return inBytesPerTile;\n}\n\n// Build a popsolver model with the appropriate Pooling Planning variables and\n// constraints. Return the \"cycle\" cost as the derived variable which needs to\n// be optimized.\nstatic popsolver::Variable constructModel(\n    popsolver::Model &m, const poplar::Target &target, PartitionVariables &vars,\n    const PoolConfig &poolCfg, const poplin::ConvParams &params,\n    const unsigned minGrainsPerChanGroup, const unsigned maxGrainsPerChanGroup,\n    const std::size_t chanGrainSize, const std::size_t numChannels,\n    const std::size_t detChansPerGroup, const std::size_t minChannelsPerGroup,\n    EstimateCache &cache) {\n\n  auto numTiles = target.getNumTiles();\n  auto fieldShape = params.getOutputFieldShape();\n  auto kernelShape = params.kernelShape;\n  auto nChGrain = m.addVariable(minGrainsPerChanGroup,\n                                std::min(maxGrainsPerChanGroup, numTiles));\n  auto nCh = m.addConstant(numChannels);\n  auto chGrainSize = m.addConstant(chanGrainSize);\n\n  // Sweep Channels Per Group\n  vars.chansPerGroup = m.product({nChGrain, chGrainSize});\n\n  // Channel-Group split sweep\n  auto nChGroupsMax = m.ceildiv(nCh, vars.chansPerGroup);\n  auto nTiles = m.addConstant(numTiles);\n  vars.chanGroupsSplit = m.addVariable(1, numTiles);\n  m.lessOrEqual(vars.chanGroupsSplit, nChGroupsMax);\n\n  // Batch split sweep\n  vars.batchSplit = m.addVariable(1, params.batchSize);\n\n  // Sweep across each field dimension\n  vars.fieldSplit.reserve(fieldShape.size());\n  for (auto dimSize : fieldShape) {\n    vars.fieldSplit.push_back(m.addVariable(1, dimSize));\n  }\n\n  // Constrain splits to not exceed the given number of tiles\n  std::vector<popsolver::Variable> splits = {vars.chanGroupsSplit,\n                                             vars.batchSplit};\n  splits.insert(splits.end(), vars.fieldSplit.begin(), vars.fieldSplit.end());\n  auto usedTiles = m.product(splits);\n  m.lessOrEqual(usedTiles, nTiles);\n\n  // Constrain channels to be >= minChannelsPerGroup\n  m.lessOrEqual(m.addConstant(minChannelsPerGroup), vars.chansPerGroup);\n\n  // Work out the size of each partition after applying the split\n  std::vector<popsolver::Variable> fieldVar;\n  std::vector<popsolver::Variable> kernelVar;\n  fieldVar.reserve(vars.fieldSplit.size());\n  kernelVar.reserve(vars.fieldSplit.size());\n  auto nChGroups = m.ceildiv(nChGroupsMax, vars.chanGroupsSplit);\n  auto batchSize = m.addConstant(params.batchSize);\n  auto nBatch = m.ceildiv(batchSize, vars.batchSplit);\n\n  for (unsigned i = 0; i < vars.fieldSplit.size(); i++) {\n    auto fieldDim = m.addConstant(fieldShape[i]);\n    fieldVar.push_back(m.ceildiv(fieldDim, vars.fieldSplit[i]));\n    kernelVar.push_back(m.addConstant(kernelShape[i]));\n  }\n\n  // Compute lower bound on cycles - define some constants\n  auto totalOperations = m.addConstant(getNumberOfOperations(params));\n\n  auto vertexCyclesPerInnerLoop = m.addConstant(poolVertexCyclesPerVector(\n      poolCfg.type == PoolingType::MAX, poolCfg.pass == PoolPass::POOL_BWD));\n  auto vectorWidth = m.addConstant(target.getVectorWidth(params.inputType));\n  auto vertexCyclesPerRow = m.addConstant(poolVertexCyclesPerRow());\n\n  // Compute lower bound on cycles, rounding down as it is a lower bound\n  auto rowsPerTile = m.floordiv(m.product(fieldVar), fieldVar.back());\n  auto rowOverheadPerTile = m.product({rowsPerTile, vertexCyclesPerRow});\n  auto operationsPerTile = m.floordiv(totalOperations, usedTiles);\n  auto minCyclesPerTile = m.sum(\n      {rowOverheadPerTile, m.product({m.ceildiv(operationsPerTile, vectorWidth),\n                                      vertexCyclesPerInnerLoop})});\n\n  // Evaluate the cycle-cost for each possible partition\n  std::vector<popsolver::Variable> splitVars = {\n      nBatch,\n      nChGroups,\n      vars.chansPerGroup,\n  };\n  splitVars.insert(splitVars.end(), fieldVar.begin(), fieldVar.end());\n  splitVars.insert(splitVars.end(), kernelVar.begin(), kernelVar.end());\n\n  auto cycles = m.call<unsigned>(\n      splitVars, [&target, poolCfg, &params, fieldShape, detChansPerGroup,\n                  &cache](const std::vector<unsigned> &values) {\n        // Note that \"perTile\" is not a partition per se, but it contains\n        // the variables after they were partitioned for each tile:\n        //      perTile->batch = batchSize / batchSplit\n        //      perTile->chanGroups = numChannels / channelSplit\n        //      perTile->field[d] = ConvParams::fieldShape[d] / fieldSplit[d]\n        //      perTile->kernel[d] = ConvParams::kernelShape[d] / kernelSplit[d]\n        Partition perTile = makePartition(values, fieldShape.size());\n\n        const unsigned strideX = params.inputTransform.dilation.back();\n        const unsigned numKernelPositions = product(params.kernelShape);\n        const unsigned inputVectorWidth =\n            params.inputType == poplar::HALF ? 4 : 2;\n        const unsigned workers = target.getNumWorkerContexts();\n        auto computeCost = cache.mPoolVertexCycleEstimate(\n            perTile, poolCfg, strideX, numKernelPositions, inputVectorWidth,\n            workers);\n        // Where the field was divided it was rounded up.  For plans where\n        // that is not exact, the tiles which take the rounded down field\n        // pieces can use more cycles.  This could be true for any dimension, so\n        // we try them all and allow the planning cost to determine which is\n        // best rather than coding assumptions about the planning cost here. It\n        // could be that the slowest tile has a combination of rounded down dims\n        // to deal with, but that is not necessarily going to happen and adds\n        // many more calls to the estimator, so is not implemented.\n        for (unsigned i = 0; i < fieldShape.size(); i++) {\n          if (fieldShape[i] % perTile.field[i]) {\n            auto altPerTile = perTile;\n            altPerTile.field[i] -= 1;\n            computeCost = std::max(computeCost, cache.mPoolVertexCycleEstimate(\n                                                    altPerTile, poolCfg,\n                                                    strideX, numKernelPositions,\n                                                    inputVectorWidth, workers));\n          }\n        }\n        // But the partitioned field size is the output, we'll be exchanging\n        // and rearranging the input - scale to find the input needed to\n        // produce the tile's partitioned output.  In some cases there are\n        // multiple inputs\n        // exchange cost: assume everything brought onto tile\n        const auto bytesPerTile = getBytesRequiredPerTile(\n            perTile, params, poolCfg, target.getTypeSize(params.inputType));\n        const unsigned exchangeBytesPerCycle =\n            target.getExchangeBytesPerCycle();\n        uint64_t exchangeCost = bytesPerTile / exchangeBytesPerCycle;\n\n        // Penalise for changing from detected group\n        std::uint64_t rearrangementCost = 0;\n        if (detChansPerGroup != perTile.chansPerGroup) {\n          rearrangementCost += bytesPerTile / 4;\n        }\n        return popsolver::DataType{computeCost + exchangeCost +\n                                   rearrangementCost};\n      });\n\n  // Constrain so that the min cycles estimate per tile is < cycles\n  // which avoids calling the costly cycle estimator in cases where it is clear\n  // that the cycles estimate will be large\n  m.lessOrEqual(minCyclesPerTile, cycles);\n\n  return cycles;\n}\n\npoplin::ConvParams applyTransform(poplin::ConvParams params,\n                                  const Transform &transform,\n                                  const std::vector<poplar::Tensor *> &as) {\n  for (const auto &entry : transform.flattenDims) {\n    const auto d = entry.first;\n    const auto f = entry.second;\n    // Spatial dimension 0 means batch size\n    if (d == 0) {\n      assert(params.batchSize % f == 0);\n      params.inputChannelsPerConvGroup *= f;\n      params.outputChannelsPerConvGroup *= f;\n      params.batchSize /= f;\n    } else {\n      assert(params.inputFieldShape[d - 1] % f == 0);\n      params.inputChannelsPerConvGroup *= f;\n      params.outputChannelsPerConvGroup *= f;\n      params.inputFieldShape[d - 1] /= f;\n      // N.B. This is only possible if kernel size in this dimension is\n      // 1 so we don't touch kernel shape.\n      assert(params.kernelShape[d - 1] == 1);\n    }\n    for (poplar::Tensor *a : as) {\n      if (a != nullptr) {\n        *a = a->dimRoll(d, a->rank() - 2)\n                 .reshapePartial(a->rank() - 2, a->rank(),\n                                 {a->dim(d) / f, a->dim(a->rank() - 1) * f})\n                 .dimRoll(a->rank() - 2, d);\n      }\n    }\n  }\n  return params;\n}\n\nvoid applyTransformInverse(const poplin::ConvParams &params,\n                           const Transform &transform,\n                           const std::vector<poplar::Tensor *> &as) {\n  for (const auto &entry : boost::adaptors::reverse(transform.flattenDims)) {\n    const auto d = entry.first;\n    const auto f = entry.second;\n    for (poplar::Tensor *a : as) {\n      if (a != nullptr) {\n        *a = a->dimRoll(d, a->rank() - 2)\n                 .reshapePartial(a->rank() - 2, a->rank(),\n                                 {a->dim(d) * f, a->dim(a->rank() - 1) / f})\n                 .dimRoll(a->rank() - 2, d);\n      }\n    }\n  }\n}\n\n// Get plan based on compute and exchange cost. As a further improvement, the\n// plan could incorporate introspection. For now, keep it simple.\n// Fwd and Bwd plans are kept separate as there is possibly no benefit for\n// doing a joint one.\nPlanResult getPlan(const poplar::Graph &graph, const PoolConfig &poolCfg,\n                   const TransformedInput &input,\n                   const TransformedInput &inputGrouped) {\n  Plan plan;\n\n  // Don't use getTypeSize here because IpuModel will report something\n  // different to what it actually uses.\n  // We can change this once T6380 is fixed.\n  const auto typeSize = (input.params.inputType == poplar::HALF ? 2 : 4);\n  const auto chanGrainSize = 8UL / typeSize;\n\n  plan.transform = getTransform(graph, input.params, input.in, chanGrainSize);\n\n  // Apply any transform to the parameters and input then work\n  // out partitioning.\n  poplar::Tensor in = input.in;\n  const auto transformedParams =\n      applyTransform(input.params, plan.transform, {&in});\n  const auto inShape = in.shape();\n  auto chansPerGroupDet = detectInnermostGrouping(graph, in);\n  auto numChannels = inShape[inShape.size() - 1];\n\n  // Do not allow a large number of grains as memory cost of exchanging and\n  // rearranging is significant\n  auto minGrainsPerChanGroup = 1UL;\n  auto maxGrainsPerChanGroup =\n      std::min((chansPerGroupDet + chanGrainSize - 1) / chanGrainSize,\n               (numChannels + chanGrainSize - 1) / chanGrainSize);\n  maxGrainsPerChanGroup =\n      std::max(std::min(maxGrainsPerChanGroup, 8UL), minGrainsPerChanGroup);\n\n  // Construct model with variables and constraints\n  popsolver::Model m;\n  PartitionVariables vars;\n  EstimateCache cache;\n\n  auto cycles =\n      constructModel(m, graph.getTarget(), vars, poolCfg, transformedParams,\n                     minGrainsPerChanGroup, maxGrainsPerChanGroup,\n                     chanGrainSize, numChannels, chansPerGroupDet, 1, cache);\n\n  // Optimise within constraints\n  auto s = m.minimize({cycles});\n  assert(s.validSolution());\n  plan.partition = makePartition(s, vars);\n  auto sResult = *s[cycles];\n\n  // Consider a second plan, constrained to a minimum number of channels, as\n  // operations that use the output can benefit from this.  Allow the pooling\n  // cycles to degrade by a fairly large percentage in order to achieve the\n  // minimum number of channels as pooling is a relatively cheap operation,\n  // and the other operations that it may affect are more expensive.\n\n  // Use the grouped input for this plan, as the input may have been transformed\n  // so that channels were combined into the spatial dimensions no longer\n  // giving enough channels to meet the preferred channel grouping.\n  const auto minChannelsPerGroup =\n      getPreferredChannelGrouping(inputGrouped.params.inputType, poolCfg.type);\n  auto numChannelsGrouped = inputGrouped.in.shape().back();\n  if (plan.partition.chansPerGroup < minChannelsPerGroup &&\n      numChannelsGrouped >= minChannelsPerGroup) {\n    maxGrainsPerChanGroup =\n        (minChannelsPerGroup + chanGrainSize - 1) / chanGrainSize;\n    Plan plan;\n    plan.transform = getTransform(graph, inputGrouped.params, inputGrouped.in,\n                                  chanGrainSize);\n    const auto transformedParams =\n        applyTransform(inputGrouped.params, plan.transform, {&in});\n    auto chansPerGroupDet = detectInnermostGrouping(graph, inputGrouped.in);\n\n    popsolver::Model mConstrained;\n    PartitionVariables varsConstrained;\n    auto cyclesConstrained =\n        constructModel(mConstrained, graph.getTarget(), varsConstrained,\n                       poolCfg, transformedParams, minGrainsPerChanGroup,\n                       maxGrainsPerChanGroup, chanGrainSize, numChannelsGrouped,\n                       chansPerGroupDet, minChannelsPerGroup, cache);\n\n    // Optimise within constraints of minChannelsPerGroup.  There may not be a\n    // solution for all targets\n    auto sConstrained = mConstrained.minimize({cyclesConstrained});\n    if (sConstrained.validSolution()) {\n      auto sConstrainedResult = *sConstrained[cyclesConstrained];\n      if (sConstrainedResult < (sResult * 4) / 3) {\n        plan.partition = makePartition(sConstrained, varsConstrained);\n        return {plan, sConstrainedResult, true};\n      }\n    }\n  }\n  return {plan, sResult, false};\n}\n\nstd::ostream &operator<<(std::ostream &os, const Partition &p) {\n  os << \"Partition:\\n\";\n  os << \"        Batch split              \" << p.batch << \"\\n\";\n  os << \"        Channel split            \" << p.chanGroups << \"\\n\";\n  os << \"        Chans per group          \" << p.chansPerGroup << \"\\n\";\n  os << \"        Kernel split             \";\n  printContainer(p.kernel, os);\n  os << \"\\n\";\n  os << \"        Field split              \";\n  printContainer(p.field, os);\n  os << \"\\n\";\n  return os;\n}\n\nstd::ostream &operator<<(std::ostream &o, const Transform &t) {\n  o << \"Transform:\\n\"\n    << \"        Flatten dims \";\n  printContainer(t.flattenDims, o);\n  o << \"\\n\";\n  return o;\n}\n\nstd::ostream &operator<<(std::ostream &o, const Plan &p) {\n  o << p.transform << p.partition;\n  return o;\n}\n\n} // namespace pooling\n} // namespace popnn\n", "meta": {"hexsha": "6b30f8abb7a3e05759432ec0e94a83c8b72da7e3", "size": 21373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/popnn/PoolPlan.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/popnn/PoolPlan.cpp", "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": "lib/popnn/PoolPlan.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "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": 41.9078431373, "max_line_length": 80, "alphanum_fraction": 0.6639685585, "num_tokens": 5100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19216348762874366}}
{"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) 2007-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#ifndef BOOST_UNIT_SYSTEMS_METRIC_BARN_HPP_INCLUDED\r\n#define BOOST_UNIT_SYSTEMS_METRIC_BARN_HPP_INCLUDED\r\n\r\n#include <boost/units/conversion.hpp>\r\n#include <boost/units/systems/si/area.hpp>\r\n\r\nBOOST_UNITS_DEFINE_BASE_UNIT_WITH_CONVERSIONS(metric, barn, \"barn\", \"b\", 1.0e-28, si::area, 11);\r\n\r\n#endif // BOOST_UNIT_SYSTEMS_METRIC_BARN_HPP_INCLUDED\r\n", "meta": {"hexsha": "cd439f3f650e8930804429362d1af0150b43a8f6", "size": 738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/units/base_units/metric/barn.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/units/base_units/metric/barn.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/units/base_units/metric/barn.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": 36.9, "max_line_length": 97, "alphanum_fraction": 0.7682926829, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.19209889176289366}}
{"text": "\t/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2015 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   License for the specific language governing rights and limitations under\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#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/GeometryPrimitives/Point.h>\n#include <Core/GeometryPrimitives/Vector.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Algorithms/BrainStimulator/ElectrodeCoilSetupAlgorithm.h>\n#include <Core/Algorithms/Legacy/Fields/DistanceField/CalculateSignedDistanceField.h>\n#include <Core/Algorithms/Legacy/Fields/FieldData/ConvertFieldBasisType.h>\n#include <Core/Algorithms/Legacy/Fields/FieldData/GetFieldData.h>\n#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/SplitByConnectedRegion.h>\n#include <Core/Algorithms/Legacy/Fields/DomainFields/SplitFieldByDomainAlgo.h>\n#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>\n#include <Core/Algorithms/Legacy/Fields/MeshData/GetMeshNodes.h>\n#include <Core/Datatypes/Legacy/Field/Field.h>\n#include <Core/Datatypes/Legacy/Field/VField.h>\n#include <Core/Datatypes/Legacy/Field/VMesh.h>\n#include <Core/Datatypes/Legacy/Field/FieldInformation.h>\n#include <Core/Datatypes/Matrix.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Core/Datatypes/MatrixComparison.h>\n#include <string>\n#include <boost/range/algorithm/count.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/format.hpp>\n#include <boost/assign.hpp>\n#include <math.h>\n#include <Core/Math/MiscMath.h>\n#include <iostream>\n\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::BrainStimulator;\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun;\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace  Eigen;\n\nALGORITHM_PARAMETER_DEF(BrainStimulator, NumberOfPrototypes);\nALGORITHM_PARAMETER_DEF(BrainStimulator, TableValues);\nALGORITHM_PARAMETER_DEF(BrainStimulator, ProtoTypeInputCheckbox);\nALGORITHM_PARAMETER_DEF(BrainStimulator, AllInputsTDCS);\nALGORITHM_PARAMETER_DEF(BrainStimulator, ProtoTypeInputComboBox);\nALGORITHM_PARAMETER_DEF(BrainStimulator, ElectrodethicknessCheckBox);\nALGORITHM_PARAMETER_DEF(BrainStimulator, ElectrodethicknessSpinBox);\n\nconst AlgorithmOutputName ElectrodeCoilSetupAlgorithm::FINAL_ELECTRODES_FIELD(\"FINAL_ELECTRODES_FIELD\");\nconst AlgorithmOutputName ElectrodeCoilSetupAlgorithm::MOVED_ELECTRODES_FIELD(\"MOVED_ELECTRODES_FIELD\");\nconst AlgorithmInputName ElectrodeCoilSetupAlgorithm::SCALP_SURF(\"SCALP_SURF\");\nconst AlgorithmInputName ElectrodeCoilSetupAlgorithm::ELECTRODECOILPROTOTYPES(\"ELECTRODECOILPROTOTYPES\");\nconst AlgorithmOutputName ElectrodeCoilSetupAlgorithm::ELECTRODE_SPONGE_LOCATION_AVR(\"ELECTRODE_SPONGE_LOCATION_AVR\");\nconst AlgorithmOutputName ElectrodeCoilSetupAlgorithm::COILS_FIELD(\"COILS_FIELD\");\nconst AlgorithmInputName ElectrodeCoilSetupAlgorithm::LOCATIONS(\"LOCATIONS\");\n\nconst int ElectrodeCoilSetupAlgorithm::unknown_stim_type = 0; \nconst int ElectrodeCoilSetupAlgorithm::TMS_stim_type     = 1; \nconst int ElectrodeCoilSetupAlgorithm::tDCS_stim_type    = 2;\nconst double ElectrodeCoilSetupAlgorithm::direction_bound = -0.99;\n\nconst AlgorithmParameterName ElectrodeCoilSetupAlgorithm::columnNames[] = \n{ Name(\"Input #\"), \nName(\"Type\"),\nName(\"X\"),\nName(\"Y\"),\nName(\"Z\"), \nName(\"Angle\"),\nName(\"NX\"),\nName(\"NY\"), \nName(\"NZ\"), \nName(\"thickness\")\n};\n\nElectrodeCoilSetupAlgorithm::ElectrodeCoilSetupAlgorithm()\n{\n using namespace Parameters;\n {\n  addParameter(MOVED_ELECTRODES_FIELD, 0);\n  addParameter(NumberOfPrototypes, 0);\n  addParameter(TableValues, 0);\n  addParameter(ProtoTypeInputCheckbox, false);\n  addParameter(ProtoTypeInputComboBox, false);\n  addParameter(AllInputsTDCS, false);\n  addParameter(ElectrodethicknessCheckBox, false);\n  addParameter(ElectrodethicknessSpinBox, 1.0); \n }\n}\n\n\nVariableHandle ElectrodeCoilSetupAlgorithm::fill_table(FieldHandle scalp, DenseMatrixHandle locations, const std::vector<FieldHandle>& input) const\n{\n  Variable::List table;\n  if (locations->ncols()!=3)\n  {\n   THROW_ALGORITHM_PROCESSING_ERROR(\" LOCATIONS needs to have dimensions such as: (#CoilsOrElectrodes) x 3 \"); \n  }\n  \n  auto tab_values = get(Parameters::TableValues).toVector();\n \n  for (int i=0;i<locations->nrows();i++)\n  {  \n  \n   Variable::List tmp;\n\n   if (tab_values.size()<locations->nrows())\n   {\n   tmp += \n     Variable(columnNames[0], boost::str(boost::format(\"%s\") % \"0\")),\n     Variable(columnNames[1], boost::str(boost::format(\"%s\") % \"0\")),\n     Variable(columnNames[2], boost::str(boost::format(\"%.3f\") % (* locations)(i,0))),\n     Variable(columnNames[3], boost::str(boost::format(\"%.3f\") % (* locations)(i,1))),\n     Variable(columnNames[4], boost::str(boost::format(\"%.3f\") % (* locations)(i,2))),\n     Variable(columnNames[5], boost::str(boost::format(\"???\"))),\n     Variable(columnNames[6], std::string(\"???\")),\n     Variable(columnNames[7], std::string(\"???\")),\n     Variable(columnNames[8], std::string(\"???\")),\n     Variable(columnNames[9], std::string(\"???\")); \n     \n   } else\n   {\n      auto col = tab_values[i].toVector();\n\n     if (col.size()==number_of_columns)\n     {\n      std::string str1=col[0].toString();\n      std::string str2=col[1].toString();\n      std::string str3=col[2].toString();\n      std::string str4=col[3].toString();\n      std::string str5=col[4].toString();\n      std::string str6=col[5].toString();\n      std::string str7=col[6].toString();\n      std::string str8=col[7].toString();\n      std::string str9=col[8].toString();\n      std::string str10=col[9].toString();      \n\n      Variable var1=makeVariable(\"Input #\", boost::str(boost::format(\"%s\") % str1));\n      Variable var2=makeVariable(\"Type\",   boost::str(boost::format(\"%s\") % str2)); \n\n      Variable var3,var4,var5;\n      \n      if (str3.compare(\"???\")==0)\n       var3=makeVariable(\"X\",     boost::str(boost::format(\"%.3f\") % (* locations)(i,0)));\n        else\n         var3=makeVariable(\"X\",   boost::str(boost::format(\"%s\") % str3));\n\n      if (str4.compare(\"???\")==0) \n       var4=makeVariable(\"Y\",     boost::str(boost::format(\"%.3f\") % (* locations)(i,1)));\n\telse\n\t var4=makeVariable(\"Y\",   boost::str(boost::format(\"%s\") % str4));\n\n      if (str5.compare(\"???\")==0) \n       var5=makeVariable(\"Y\",     boost::str(boost::format(\"%.3f\") % (* locations)(i,2)));\n\telse\n         var5=makeVariable(\"Z\",   boost::str(boost::format(\"%s\") % str5));\n\n      Variable var6=makeVariable(\"Angle\",  boost::str(boost::format(\"%s\") % str6));  \n\n      ///if this table row was selected as tDCS -> project point to scalp surface and put its normal in table (NX,NY,NZ)\n      Variable var7=makeVariable(\"NX\", boost::str(boost::format(\"%s\") % str7));\n      Variable var8=makeVariable(\"NY\", boost::str(boost::format(\"%s\") % str8));\n      Variable var9=makeVariable(\"NZ\", boost::str(boost::format(\"%s\") % str9));\n      Variable var10=makeVariable(\"thickness\",boost::str(boost::format(\"%s\") % str10));\n      tmp += var1,var2,var3,var4,var5,var6,var7,var8,var9,var10;\n   \n     }\n   }  \n  \n   table.push_back(makeVariable(\"row\" + boost::lexical_cast<std::string>(i), tmp));   \n  }  \n  VariableHandle output(new Variable(Name(\"Table\"), table));\n \n  return output;\n}\n\n\nDenseMatrixHandle ElectrodeCoilSetupAlgorithm::make_rotation_matrix(const double angle, const std::vector<double>& normal) const\n{\n DenseMatrixHandle result(new DenseMatrix(3, 3));\n\n  double normal_vector_norm=sqrt(normal[0]*normal[0]+normal[1]*normal[1]+normal[2]*normal[2]); \n  Vector3d normal_vector((double)normal[0]/normal_vector_norm, (double)normal[1]/normal_vector_norm, (double)normal[2]/normal_vector_norm);\n  \n  Vector3d tan_vector1, tan_vector2;\n  if (normal_vector(0)!=0 || normal_vector(2)!=0)\n  {\n   tan_vector1(0)= normal_vector(2);\n   tan_vector1(1)= 0.0;\n   if (normal_vector(0)==0)\n    tan_vector1(2) = 0.0;\n     else\n       tan_vector1(2)= -1*normal_vector(0);\n   } else\n  {\n   tan_vector1(0)= normal_vector(1);\n   tan_vector1(1)= 0.0;\n   tan_vector1(2)= 0.0;\n  }\n \n normal_vector_norm=sqrt(tan_vector1(0)*tan_vector1(0)+tan_vector1(1)*tan_vector1(1)+tan_vector1(2)*tan_vector1(2));\n tan_vector1(0)/=normal_vector_norm; tan_vector1(1)/=normal_vector_norm; tan_vector1(2)/=normal_vector_norm;\n tan_vector2 = normal_vector.cross(tan_vector1);    \n normal_vector_norm=sqrt(tan_vector2(0)*tan_vector2(0)+tan_vector2(1)*tan_vector2(1)+tan_vector2(2)*tan_vector2(2));\n tan_vector2(0)/=normal_vector_norm; tan_vector2(1)/=normal_vector_norm; tan_vector2(2)/=normal_vector_norm;\n DenseMatrixHandle rotation_matrix2;\n Matrix3d rotation_matrix(3,3), rotation_matrix1(3,3);\n\n (*result)(0,2)=normal_vector(0);\n (*result)(1,2)=normal_vector(1);\n (*result)(2,2)=normal_vector(2);\n (*result)(0,1)=tan_vector2(0);\n (*result)(1,1)=tan_vector2(1);\n (*result)(2,1)=tan_vector2(2);\n (*result)(0,0)=tan_vector1(0);\n (*result)(1,0)=tan_vector1(1);\n (*result)(2,0)=tan_vector1(2);\n\n return result; \n}\n\nDenseMatrixHandle ElectrodeCoilSetupAlgorithm::make_rotation_matrix_around_axis(double angle, std::vector<double>& axis_vector) const\n{\n   DenseMatrixHandle result(new DenseMatrix(3, 3));\n  \n   angle = angle * M_PI / 180.0;\n   double cos_angle = cos(angle);\n   double sin_angle = sin(angle);\n   double ux=axis_vector[0],uy=axis_vector[1], uz=axis_vector[2];\n   (*result)(0,0)=cos_angle+ux*ux*(1-cos_angle);\n   (*result)(0,1)=ux*uy*(1-cos_angle)-uz*sin_angle;\n   (*result)(0,2)=ux*uz*(1-cos_angle)+uy*sin_angle;\n   (*result)(1,0)=uy*ux*(1-cos_angle)+uz*sin_angle;\n   (*result)(1,1)=cos_angle+uy*uy*(1-cos_angle);\n   (*result)(1,2)=uy*uz*(1-cos_angle)-ux*sin_angle;\n   (*result)(2,0)=uz*ux*(1-cos_angle)-uy*sin_angle;\n   (*result)(2,1)=uz*uy*(1-cos_angle)+ux*sin_angle;\n   (*result)(2,2)=cos_angle+uz*uz*(1-cos_angle);\n  \n  return result; \n}\n\n\nFieldHandle ElectrodeCoilSetupAlgorithm::make_tms(FieldHandle scalp, const std::vector<FieldHandle>& elc_coil_proto, const std::vector<double>& coil_prototyp_map, const std::vector<double>& coil_x, const std::vector<double>& coil_y, const std::vector<double>& coil_z, const std::vector<double>& coil_angle_rotation, const std::vector<double>& coil_nx, const std::vector<double>& coil_ny, const std::vector<double>& coil_nz) const \n{  \n  FieldInformation fieldinfo(\"PointCloudMesh\", 0, \"Vector\");\n  FieldHandle tms_coils_field = CreateField(fieldinfo);        \n  VMesh* tms_coils_vmesh = tms_coils_field->vmesh();  \n  VField* tms_coils_vfld  = tms_coils_field->vfield();\n  std::vector<Point> tms_coils_field_values;\n  \n  for (int i=0; i<coil_prototyp_map.size(); i++)\n  {  \n   if (coil_prototyp_map[i]<=elc_coil_proto.size() && coil_prototyp_map[i]>=0) \n   {    \n    if( !(coil_x.size()-1>=i && coil_y.size()-1>=i && coil_z.size()-1>=i))\n     {\n       THROW_ALGORITHM_PROCESSING_ERROR(\"Internal error: definition of coil (x,y,z) seems to be empty.\");  \n     }\n      \n    /// 1) move coil to predetermined position and orientation\n    FieldHandle coil_fld = elc_coil_proto[coil_prototyp_map[i]-1];\n    if (!coil_fld)\n    {\n      THROW_ALGORITHM_PROCESSING_ERROR(\"Internal error: coil field .\"); \n    }\n    \n    FieldInformation fi(coil_fld);\n    if(fi.is_pointcloudmesh()) \n    {    \n     GetFieldDataAlgo algo_getfielddata;\n     DenseMatrixHandle fielddata;\n     try\n     {\n      fielddata  = algo_getfielddata.run(coil_fld);\n     }\n     catch (...)\n     {  \n     }\n     \n     GetMeshNodesAlgo algo_getfieldnodes;\n     DenseMatrixHandle fieldnodes;\n     try\n     {\n      algo_getfieldnodes.run(coil_fld,fieldnodes);\n     }\n     catch (...)\n     {\n      THROW_ALGORITHM_PROCESSING_ERROR(\"Internal error: could not retrieve positions from  \");\n     }\n    \n     DenseMatrixHandle magnetic_dipoles(boost::make_shared<DenseMatrix>(fielddata->nrows(),3));\n    \n     /// subtract the mean from the coil positions to move them accourding to GUI table entries\n     double mean_loc_x=0,mean_loc_y=0,mean_loc_z=0; \n     for(int j=0; j<fieldnodes->nrows(); j++)\n     {\n      mean_loc_x+=(*fieldnodes)(j,0);\n      mean_loc_y+=(*fieldnodes)(j,1);\n      mean_loc_z+=(*fieldnodes)(j,2);\n     }\n     mean_loc_x/=fieldnodes->nrows();\n     mean_loc_y/=fieldnodes->nrows();\n     mean_loc_z/=fieldnodes->nrows();\n    \n     for(int j=0; j<fieldnodes->nrows(); j++)\n     {\n      (*fieldnodes)(j,0)-=mean_loc_x;\n      (*fieldnodes)(j,1)-=mean_loc_y;\n      (*fieldnodes)(j,2)-=mean_loc_z;\n     }\n    \n     /// 2) create normals and rotate if needed\n     if (coil_nx.size()-1>=i && coil_ny.size()-1>=i && coil_nz.size()-1>=i && coil_angle_rotation.size()-1>=i)\n     {\n      double angle = coil_angle_rotation[i];\n      DenseMatrixHandle rotation_matrix,rotation_matrix1,rotation_matrix2;\n      // 2.1) create rotation matrices\n      std::vector<double> coil_vector;\n      coil_vector.push_back(coil_nx[i]);\n      coil_vector.push_back(coil_ny[i]);\n      coil_vector.push_back(coil_nz[i]);\n\n      rotation_matrix1 = make_rotation_matrix(angle, coil_vector);\n\n      if (angle!=0) /// test it !\n      {\n       std::vector<double> axis;\n       axis.push_back(coil_nx[i]);\n       axis.push_back(coil_ny[i]);\n       axis.push_back(coil_nz[i]);\n       rotation_matrix2 = make_rotation_matrix_around_axis(angle, axis);\n       rotation_matrix = boost::make_shared<DenseMatrix>((*rotation_matrix2) * (*rotation_matrix1));\n      }   \n     \n      /// 2.2) apply rotation and move points\n      for(int j=0; j<fieldnodes->nrows(); j++)\n      {\n       if(coil_x.size()-1>=i && coil_y.size()-1>=i && coil_z.size()-1>=i)\n       { \n        DenseMatrixHandle pos_vec (boost::make_shared<DenseMatrix>(3,1));\n\n       (*pos_vec)(0,0)=(*fieldnodes)(j,0);\n       (*pos_vec)(1,0)=(*fieldnodes)(j,1);\n       (*pos_vec)(2,0)=(*fieldnodes)(j,2);\n       \n       DenseMatrixHandle rotated_positions;\n\n       if (angle==0)\n        rotated_positions = boost::make_shared<DenseMatrix>((*rotation_matrix1) * (*pos_vec));\n\t else\n\t   rotated_positions = boost::make_shared<DenseMatrix>((*rotation_matrix) * (*pos_vec));\n\n       (*fieldnodes)(j,0)=(*rotated_positions)(0,0)+coil_x[i];\n       (*fieldnodes)(j,1)=(*rotated_positions)(1,0)+coil_y[i];\n       (*fieldnodes)(j,2)=(*rotated_positions)(2,0)+coil_z[i];\n      \n      } else\n      {\n       THROW_ALGORITHM_PROCESSING_ERROR(\"Internal error: definition of coil (x,y,z) seems to be empty.\");  \n      }\n    }\n\n   /// 2.3) use normal as magnetic dipole orientation if there are no normals defined at prototyp\n   if(coil_nx.size()-1>=i && coil_ny.size()-1>=i && coil_nz.size()-1>=i) \n    {\n     if(fielddata->ncols()==1) /// if there are no dipoles but only scalar values use GUI normal\n     {\n      for (int j=0; j<fielddata->nrows(); j++)\n      {\n       (*magnetic_dipoles)(j,0)=(*fielddata)(j,0)*coil_nx[i];\n       (*magnetic_dipoles)(j,1)=(*fielddata)(j,0)*coil_ny[i];\n       (*magnetic_dipoles)(j,2)=(*fielddata)(j,0)*coil_nz[i];\n      }\n     } else\n      if(fielddata->ncols()==3) /// roatate magnetic dipoles\n      { \n       for (int j=0; j<fielddata->nrows(); j++)\n       { \n    \t DenseMatrixHandle pos_vec(boost::make_shared<DenseMatrix>(3,1));\n         (*pos_vec)(0,0)=(*fielddata)(j,0);\n         (*pos_vec)(1,0)=(*fielddata)(j,1);\n         (*pos_vec)(2,0)=(*fielddata)(j,2);\n\t \n\t DenseMatrixHandle rotated_positions;\n\t if (angle==0 || IsNan(angle))\n\t {\n          rotated_positions = boost::make_shared<DenseMatrix>((*rotation_matrix1) * (*pos_vec));\n\t }\n\t   else\n\t     rotated_positions = boost::make_shared<DenseMatrix>((*rotation_matrix) * (*pos_vec));\n \n \t(*magnetic_dipoles)(j,0)=(*rotated_positions)(0,0);\n\t(*magnetic_dipoles)(j,1)=(*rotated_positions)(1,0);\n\t(*magnetic_dipoles)(j,2)=(*rotated_positions)(2,0);\n       }\n      } \n      if (fielddata->ncols()!=3)\n      {\n       std::ostringstream ostr4;\n       ostr4 << \" Trying to generate magnetic dipoles for TMS coil defined in table row \" << i+1 << \" could not find any prototyp normals - using (NX,NY,NZ) from GUI instead! \" << std::endl;\n       remark(ostr4.str());\t\n      }\n    }   \n   } else\n   {\n     THROW_ALGORITHM_PROCESSING_ERROR(\"Internal error: coil normals or coil prototype or coil angle rotation did not make it to algorithm. \"); \n   }\n\n    /// 4) join coil to output coil Field \n    for (VMesh::index_type j=0; j<fieldnodes->nrows(); j++)\n    {\n      Point p((*fieldnodes)(j,0),(*fieldnodes)(j,1),(*fieldnodes)(j,2));\n      tms_coils_vmesh->add_point(p);\n      Point vec((*magnetic_dipoles)(j,0),(*magnetic_dipoles)(j,1),(*magnetic_dipoles)(j,2));\n      tms_coils_field_values.push_back(vec);\n    }  \n   } else\n   {\n     std::ostringstream ostr3;\n     ostr3 << \" TMS coil definition for \" << i+1 << \". row needs be a point cloud (with defined scalar or vectors data).\" << std::endl;\n     remark(ostr3.str());\n     continue; \n   }  \n  } else\n  {\n     THROW_ALGORITHM_PROCESSING_ERROR(\"Internal error: coil definition inconsistent. \");\n  }\n }\n\n  VMesh::Node::iterator it, it_end;\n  tms_coils_vmesh->begin(it);\n  tms_coils_vmesh->end(it_end);\n  index_type j = 0;    \n  tms_coils_vfld->resize_values();\n  while (it!=it_end)\n  {\n   Vector vec(tms_coils_field_values[j].x(),tms_coils_field_values[j].y(),tms_coils_field_values[j].z());\n   tms_coils_vfld->set_value(vec,*it);\n   j++;\n   ++it;\n  } \n  \n  return tms_coils_field;\n} \n  \nboost::tuple<Variable::List,double, double, double> ElectrodeCoilSetupAlgorithm::make_table_row(int i, double x, double y, double z, double nx, double ny, double nz) const\n{\n Variable::List tmp;\n double out_nx, out_ny, out_nz;\n auto tab_values = get(Parameters::TableValues).toVector(); \n auto col = tab_values[i].toVector();\n std::string str1=col[0].toString();\n std::string str2=col[1].toString();\n std::string str3=col[2].toString();\n std::string str4=col[3].toString();\n std::string str5=col[4].toString();\n std::string str6=col[5].toString();\n \n std::string str7=col[6].toString();\n std::string str8=col[7].toString();\n std::string str9=col[8].toString();\n \n std::string str10=col[9].toString(); \n \n if (str7.compare(\"???\")==0)\n {\n  str7 = boost::str(boost::format(\"%.3f\") % nx);\n  out_nx=nx;\n } else\n {\n  try \n  {\n   out_nx = boost::lexical_cast<double>(col[6].toString());\n  } catch(bad_lexical_cast&) { } \n }\n \n if (str8.compare(\"???\")==0)\n {\n  str8 = boost::str(boost::format(\"%.3f\") % ny);\n  out_ny=ny;\n } else\n {\n  try \n  {\n   out_ny = boost::lexical_cast<double>(col[7].toString());\n  } catch(bad_lexical_cast&) { } \n }\n \n if (str9.compare(\"???\")==0)\n {\n  str9 = boost::str(boost::format(\"%.3f\") % nz);\n  out_nz=nz;\n } else\n {\n  try \n  {\n   out_nz = boost::lexical_cast<double>(col[8].toString());\n  } catch(bad_lexical_cast&) { } \n }\n \n Variable var1=makeVariable(\"Input #\", boost::str(boost::format(\"%s\") % str1));\n Variable var2=makeVariable(\"Type\",   boost::str(boost::format(\"%s\") % str2)); \n\n Variable var3,var4,var5;\n      \n if (str3.compare(\"???\")==0)\n  var3=makeVariable(\"X\",     boost::str(boost::format(\"%.3f\") % x));\n  else\n    var3=makeVariable(\"X\",   boost::str(boost::format(\"%s\") % str3));     \n   \n if (str4.compare(\"???\")==0) \n  var4=makeVariable(\"Y\",     boost::str(boost::format(\"%.3f\") % y));\n   else\n    var4=makeVariable(\"Y\",   boost::str(boost::format(\"%s\") % str4));\n\n if (str5.compare(\"???\")==0) \n  var5=makeVariable(\"Y\",     boost::str(boost::format(\"%.3f\") % z));\n   else\n    var5=makeVariable(\"Z\",   boost::str(boost::format(\"%s\") % str5));\n\n Variable var6=makeVariable(\"Angle\",  boost::str(boost::format(\"%s\") % str6));  \n\n ///if this table row was selected as tDCS -> project point to scalp surface and put its normal in table (NX,NY,NZ)\n Variable var7=makeVariable(\"NX\", boost::str(boost::format(\"%s\") % str7));\n Variable var8=makeVariable(\"NY\", boost::str(boost::format(\"%s\") % str8));\n Variable var9=makeVariable(\"NZ\", boost::str(boost::format(\"%s\") % str9));\n \n Variable var10=makeVariable(\"thickness\",boost::str(boost::format(\"%s\") % str10));\n tmp += var1,var2,var3,var4,var5,var6,var7,var8,var9,var10;\n   \n return boost::make_tuple(tmp, out_nx, out_ny, out_nz);\n}\n  \n  \nboost::tuple<DenseMatrixHandle, FieldHandle, FieldHandle, VariableHandle> ElectrodeCoilSetupAlgorithm::make_tdcs_electrodes(FieldHandle scalp, const std::vector<FieldHandle>& elc_coil_proto, const std::vector<double>& elc_prototyp_map, const std::vector<double>& elc_x, const std::vector<double>& elc_y, const std::vector<double>& elc_z, const std::vector<double>& elc_angle_rotation, const std::vector<double>& elc_thickness, VariableHandle table) const \n{\n int nr_elc_sponge_triangles=0, num_valid_electrode_definition=0, nr_elc_sponge_triangles_on_scalp=0;\n std::vector<double> field_values, field_values_elc_on_scalp;\n std::vector<int> valid_electrode_definition;\n FieldInformation fieldinfo(\"TriSurfMesh\", CONSTANTDATA_E, \"int\");\n FieldHandle electrode_field = CreateField(fieldinfo); \n VMesh* tdcs_vmesh = electrode_field->vmesh(); \n VField* tdcs_vfld  = electrode_field->vfield();\n FieldInformation fieldinfo3(\"TriSurfMesh\", CONSTANTDATA_E, \"int\");\n FieldHandle output = CreateField(fieldinfo3);\n VMesh* output_vmesh = output->vmesh(); \n VField* output_vfld = output->vfield();\n Variable::List new_table;\n DenseMatrixHandle elc_sponge_locations;  \n auto tab_values = get(Parameters::TableValues).toVector(); \n bool flip_normal=false;\n if (tab_values.size()==elc_prototyp_map.size() && elc_thickness.size()==elc_prototyp_map.size() && elc_x.size()==elc_prototyp_map.size() && elc_y.size()==elc_prototyp_map.size() && elc_z.size()==elc_prototyp_map.size() && elc_angle_rotation.size()==elc_prototyp_map.size())\n {  \n  VMesh* scalp_vmesh = scalp->vmesh(); \n  VField* scalp_vfld = scalp->vfield(); \n  valid_electrode_definition.resize(elc_prototyp_map.size());\n  for (int i=0; i<elc_prototyp_map.size(); i++)\n  {\n   if (elc_thickness[i]<=0 || IsNan(elc_thickness[i]))\n   { \n    continue; \n   }\n   double distance=0;\n   bool skip_current_iteration=false;\n   VMesh::Node::index_type didx;\n   Point elc(elc_x[i],elc_y[i],elc_z[i]),r;\n   scalp_vmesh->synchronize(Mesh::NODE_LOCATE_E);\n   scalp_vmesh->find_closest_node(distance,r,didx,elc);  /// project GUI (x,y,z) onto scalp and ...\n   Vector norm;\n   scalp_vmesh->synchronize(Mesh::NORMALS_E);\n   scalp_vmesh->get_normal(norm,didx); /// ... get its normal\n   //update GUI table normals\n   double nx,ny,nz;\n   Variable::List new_row;\n   boost::tie(new_row,nx,ny,nz)=make_table_row(i,elc_x[i],elc_y[i],elc_z[i],norm.x(),norm.y(),norm.z());\n   new_table.push_back(makeVariable(\"row\" + boost::lexical_cast<std::string>(i), new_row));  \n   if (!(nx==0.0 && ny==0.0 && nz==0.0))\n   {\n    Vector norm2(nx,ny,nz);\n    double dot_product=Dot(norm, norm2);\n    norm = Vector(nx,ny,nz);  \n    if (dot_product<direction_bound)\n    {\n      flip_normal=true;\n    }   \n   } \n     \n   /// move coil prototype to projected location\n   /// first, compute the transfer matrices\n   std::vector<double> axis;\n   axis.push_back(norm[0]);\n   axis.push_back(norm[1]);\n   axis.push_back(norm[2]);\n   double angle=elc_angle_rotation[i];\n   DenseMatrixHandle rotation_matrix,rotation_matrix1,rotation_matrix2;\n   rotation_matrix1 = make_rotation_matrix(angle, axis);\n   if (elc_angle_rotation[i]!=0) \n   {\n    rotation_matrix2 = make_rotation_matrix_around_axis(angle, axis);\n    rotation_matrix = boost::make_shared<DenseMatrix>((*rotation_matrix2) * (*rotation_matrix1));\n   }   \n   FieldHandle prototype = elc_coil_proto[elc_prototyp_map[i]-1];\n   FieldInformation fi(prototype);\n   if(fi.is_trisurfmesh()) \n   {\n    GetMeshNodesAlgo algo_getfieldnodes;\n    DenseMatrixHandle fieldnodes;\n    try\n    {\n     algo_getfieldnodes.run(prototype,fieldnodes);\n    }\n    catch (...)\n    {\n     THROW_ALGORITHM_PROCESSING_ERROR(\"Internal error: could not retrieve positions from assigned prototype \");\n    }\n \n    if (fieldnodes->nrows()<=0) // put this to tms as well\n    {\n     THROW_ALGORITHM_PROCESSING_ERROR(\"Internal error: could not retrieve positions from assigned prototype \");\n    }\n\n    ///second, subtract the mean of the prototyp positions to center it in origin\n    double mean_loc_x=0,mean_loc_y=0,mean_loc_z=0; \n    for(int j=0; j<fieldnodes->nrows(); j++)\n    {\n     mean_loc_x+=(*fieldnodes)(j,0);\n     mean_loc_y+=(*fieldnodes)(j,1);\n     mean_loc_z+=(*fieldnodes)(j,2);\n    }\n     mean_loc_x/=fieldnodes->nrows();\n     mean_loc_y/=fieldnodes->nrows();\n     mean_loc_z/=fieldnodes->nrows();\n    \n     for(int j=0; j<fieldnodes->nrows(); j++)\n     {\n      (*fieldnodes)(j,0)-=mean_loc_x;\n      (*fieldnodes)(j,1)-=mean_loc_y;\n      (*fieldnodes)(j,2)-=mean_loc_z;\n     }\n    \n     DenseMatrixHandle rotated_positions;\n\n     for(int j=0; j<fieldnodes->nrows(); j++)\n     {\n      DenseMatrixHandle pos_vec (boost::make_shared<DenseMatrix>(3,1));\n\n      (*pos_vec)(0,0)=(*fieldnodes)(j,0);\n      (*pos_vec)(1,0)=(*fieldnodes)(j,1);\n      (*pos_vec)(2,0)=(*fieldnodes)(j,2);\n       \n      if (angle==0)\n       rotated_positions = boost::make_shared<DenseMatrix>((*rotation_matrix1) * (*pos_vec));\n\t else\n\t  rotated_positions = boost::make_shared<DenseMatrix>((*rotation_matrix) * (*pos_vec));\n\n      (*fieldnodes)(j,0)=(*rotated_positions)(0,0)+elc_x[i];\n      (*fieldnodes)(j,1)=(*rotated_positions)(1,0)+elc_y[i];\n      (*fieldnodes)(j,2)=(*rotated_positions)(2,0)+elc_z[i];\n     }\n\n     VMesh* prototype_vmesh = prototype->vmesh();\n     \n     FieldInformation fieldinfo(\"TriSurfMesh\", CONSTANTDATA_E, \"double\"); /// this is the final moved prototype for elc i\n     FieldHandle tmp_tdcs_elc = CreateField(fieldinfo); \n     VMesh*  tmp_tdcs_elc_vmesh = tmp_tdcs_elc->vmesh(); \n     VField* tmp_tdcs_elc_vfld  = tmp_tdcs_elc->vfield();\n \n     Point p;\n     for (int l=0; l<fieldnodes->nrows(); l++)\n     {\n      Point p((*fieldnodes)(l,0),(*fieldnodes)(l,1),(*fieldnodes)(l,2));\n      tdcs_vmesh->add_point(p); \n      tmp_tdcs_elc_vmesh->add_point(p);\n     }\n     \n     for (VMesh::Elem::index_type l=0; l<prototype_vmesh->num_elems(); l++) \n     {\n      VMesh::Node::array_type onodes(3); \n      prototype_vmesh->get_nodes(onodes, l);\n      tmp_tdcs_elc_vmesh->add_elem(onodes);\n      onodes[0]+=nr_elc_sponge_triangles;\n      onodes[1]+=nr_elc_sponge_triangles;\n      onodes[2]+=nr_elc_sponge_triangles;\n      tdcs_vmesh->add_elem(onodes);\n      field_values.push_back(i);\n     }  \n    nr_elc_sponge_triangles+=fieldnodes->nrows();\n    valid_electrode_definition[i]=1;\n    num_valid_electrode_definition++;   \n    \n    tmp_tdcs_elc_vfld->set_all_values(0.0);\n    \n    /// since the protoype has to be centered around coordinate origin\n    /// it will envelop the scalp/electrode sponge surface at its final location (it is now!)\n    /// scalp needs to have data stored on nodes for clipping to prevent having frayed electrode sponge corners\n    FieldHandle scalp_linear_data;\n    ConvertFieldBasisTypeAlgo convert_field_basis;\n    if (!scalp_vfld->is_lineardata()) \n    {\n     using namespace SCIRun::Core::Algorithms::Fields::Parameters;\n     {\n      convert_field_basis.set_option(OutputType, \"Linear\");\n      convert_field_basis.set(BuildBasisMapping, false); \n      convert_field_basis.runImpl(scalp, scalp_linear_data);\n     }\n    }\n   \n    CalculateSignedDistanceFieldAlgo algo_sdf;\n    FieldHandle sdf_output;\n    if(scalp_vfld->is_lineardata())\n     algo_sdf.run(scalp, tmp_tdcs_elc, sdf_output);  \n       else\n         algo_sdf.run(scalp_linear_data, tmp_tdcs_elc, sdf_output); /// assumed that CalculateSignedDistanceFieldAlgo output has always values defined on nodes\n\t \n    VField* tmp_sdf_vfld  = sdf_output->vfield();   \n    VMesh*  tmp_sdf_vmsh  = sdf_output->vmesh(); \n    if (!tmp_sdf_vfld || tmp_sdf_vfld->num_values()<=0)\n    {\n     std::ostringstream ostr3;\n     ostr3 << \" Electrode sponge/scalp surface could not be found for \" << i+1 << \". electrode. Make sure that prototype encapsulated scalp.\" << std::endl;\n     remark(ostr3.str());\n     skip_current_iteration=true;\n     continue;/// in that case go to the next electrode -> leave the for loop thats iterating over i \t\n    } \n    \n    std::vector<double> tmp_field_bin_values;\n    bool found_elc_surf=false;\n    tmp_field_bin_values.resize(tmp_sdf_vfld->num_values());\n    for (VMesh::Node::index_type l=0; l<tmp_sdf_vfld->num_values(); l++) /// find out which nodes are inside the \n    {\n     double tmp_sdf_fld_val=std::numeric_limits<double>::quiet_NaN(); /// store binary classification of which scalp nodes are inside prototype and which are outside\n     tmp_sdf_vfld->get_value(tmp_sdf_fld_val,l);\n     if (tmp_sdf_fld_val <= 0.0)\n     {\n      tmp_field_bin_values[l]=1.0;\n      found_elc_surf=true;\n     } else\n       tmp_field_bin_values[l]=0.0;\n    }     \n    FieldHandle final_electrode_sponge_surf;\n          \n    if(!found_elc_surf)\n    {\n     std::ostringstream ostr3;\n     ostr3 << \" Electrode sponge/scalp surface could not be found for \" << i+1 << \". electrode (after sdf binarization). Make sure that prototype encapsulates scalp.\" << std::endl;\n     remark(ostr3.str());\n     skip_current_iteration=true;\n     continue;/// in that case go to the next electrode -> leave the for loop thats iterating over\n    }  \n\t  \n    using namespace SCIRun::Core::Algorithms::Fields::Parameters;  /// convert the data values (zero's) to elements\n    {\n     convert_field_basis.set_option(OutputType, \"Constant\");\n     convert_field_basis.set(BuildBasisMapping, false); \n     convert_field_basis.runImpl(sdf_output, final_electrode_sponge_surf);\n    }    \n    VField* final_electrode_sponge_surf_fld = final_electrode_sponge_surf->vfield();\n    VMesh*  final_electrode_sponge_surf_msh = final_electrode_sponge_surf->vmesh();\n    \n    if (!final_electrode_sponge_surf_fld || final_electrode_sponge_surf_fld->num_values()<=0 || !final_electrode_sponge_surf_msh || final_electrode_sponge_surf_msh->num_elems()<=0)\n    {\n     std::ostringstream ostr3;\n     ostr3 << \" Electrode sponge/scalp surface could not be found for \" << i+1 << \". electrode (conversion to constant data storage). Make sure that prototype encapsulates scalp.\" << std::endl;\n     remark(ostr3.str());\n     skip_current_iteration=true;\n     continue;/// in that case go to the next electrode -> leave the for loop thats iterating over i \n    }   \n     \n    final_electrode_sponge_surf_fld->set_all_values(0.0); /// Precaution: set data values (defined at elements) to zero   \n    for (VMesh::Elem::index_type l=0; l<final_electrode_sponge_surf_msh->num_elems(); l++) \n    {\n      VMesh::Node::array_type onodes(3); \n      tmp_sdf_vmsh->get_nodes(onodes, l);\n      if (tmp_field_bin_values[onodes[0]]==1.0 && tmp_field_bin_values[onodes[1]]==1.0 && tmp_field_bin_values[onodes[2]]==1.0)\n      {\n        final_electrode_sponge_surf_fld->set_value(1.0,l); \n\tfound_elc_surf=true;\n      }\n        else\n          final_electrode_sponge_surf_fld->set_value(0.0,l);\n    } \n      \n    if (!found_elc_surf)\n    {\n     std::ostringstream ostr3;\n     ostr3 << \" Electrode sponge/scalp surface could not be found for \" << i+1 << \". electrode (conversion to constant data storage). Make sure that prototype encapsulates scalp.\" << std::endl;\n     remark(ostr3.str());\n     skip_current_iteration=true;\n     continue;/// in that case go to the next electrode -> leave the for loop thats iterating over i   \n    }\n     /// are there multiple not connected scalp surfaces that are inside the prototype\n     /// use projected point r (that was projected on scalp surface) to differentiate which surface is the one to use\n     /// but first splitbydomain to get the surface with tha value 1.0\n     SplitFieldByDomainAlgo algo_splitfieldbydomain;\n     algo_splitfieldbydomain.setLogger(getLogger());\n     FieldList final_electrode_sponge_surf_domainsplit;  \n     algo_splitfieldbydomain.set(SplitFieldByDomainAlgo::SortBySize, true);\n     algo_splitfieldbydomain.set(SplitFieldByDomainAlgo::SortAscending, false);\n     algo_splitfieldbydomain.runImpl(final_electrode_sponge_surf, final_electrode_sponge_surf_domainsplit);\n     found_elc_surf=false;\n     FieldHandle find_elc_surf;\n     VMesh::Elem::index_type c_ind=0;\n     for(long l=0;l<final_electrode_sponge_surf_domainsplit.size();l++)\n     {\n      VField* final_electrode_sponge_surf_domainsplit_fld = final_electrode_sponge_surf_domainsplit[l]->vfield(); \n      double tmp_val=std::numeric_limits<double>::quiet_NaN();\n      final_electrode_sponge_surf_domainsplit_fld->get_value(tmp_val,c_ind);\n      if(tmp_val==1.0)\n      {\n       find_elc_surf=final_electrode_sponge_surf_domainsplit[l];\n       found_elc_surf=true;\n      }\n     }\n     \n     if(!found_elc_surf)\n     {\n       std::ostringstream ostr3;\n       ostr3 << \" Electrode sponge/scalp surface could not be found for \" << i+1 << \". electrode (after domainsplit). Make sure that prototype encapsulates scalp.\" << std::endl;\n       remark(ostr3.str());\n       found_elc_surf=false;\n       continue;/// in that case go to the next electrode -> leave the for loop thats iterating over i   \n     }\n     \n     SplitFieldByConnectedRegionAlgo algo_splitbyconnectedregion;\n     algo_splitbyconnectedregion.set(SplitFieldByConnectedRegionAlgo::SortDomainBySize(), true);\n     algo_splitbyconnectedregion.set(SplitFieldByConnectedRegionAlgo::SortAscending(), false);\n     std::vector<FieldHandle> result = algo_splitbyconnectedregion.run(find_elc_surf);\n     found_elc_surf=false;\n     double distance=std::numeric_limits<double>::quiet_NaN();\n     VMesh::Node::index_type didx;\n     for(int l=0;l<result.size();l++)\n     {\n      FieldHandle tmp_fld = result[l];\n      VMesh*  tmp_fld_msh  = tmp_fld->vmesh();\n\n      tmp_fld_msh->synchronize(Mesh::NODE_LOCATE_E); \n      tmp_fld_msh->find_closest_node(distance,p,didx,r);\n \n      if (distance==0)\n      {    \n       found_elc_surf=true;\n       scalp_vmesh->synchronize(Mesh::NODE_LOCATE_E);\n       Point q;\n       Vector norm;\n       \n       /// create scalp/electrode sponge triangle nodes  \n       for (VMesh::Node::index_type k=0; k<tmp_fld_msh->num_nodes(); k++) \n       {\n        tmp_fld_msh->get_center(p,k);\n\toutput_vmesh->add_point(p);\n       }\n       /// create electrode sponge top triangle nodes\n       long count_pts=0;\n       for (VMesh::Node::index_type k=0; k<tmp_fld_msh->num_nodes(); k++) \n       {\n        tmp_fld_msh->get_center(p,k);\n\tscalp_vmesh->find_closest_node(distance,q,didx,p);\n\tif (distance==0)\n\t{\n\t scalp_vmesh->synchronize(Mesh::NORMALS_E);\n\t scalp_vmesh->get_normal(norm,didx);\n\t double x=norm.x(),y=norm.y(),z=norm.z();\n\t double normal_mag=sqrt(x*x+y*y+z*z);\n\t x/=normal_mag;\n         y/=normal_mag;\n         z/=normal_mag;\n\t Point tmp_pt;\n\t if (!flip_normal)\n\t   tmp_pt=Point(q.x()+x*elc_thickness[i],q.y()+y*elc_thickness[i],q.z()+z*elc_thickness[i]);\n\t     else\n\t      tmp_pt=Point(q.x()-x*elc_thickness[i],q.y()-y*elc_thickness[i],q.z()-z*elc_thickness[i]); \n\t      \n\t output_vmesh->add_point(tmp_pt);\n\t count_pts++;\n\t}\n       }\n       int offset=nr_elc_sponge_triangles_on_scalp;\n       for (int iter_tmp=0;iter_tmp<2;iter_tmp++)\n       {\n        for (VMesh::Elem::index_type k=0; k<tmp_fld_msh->num_elems(); k++) \n        {\n         VMesh::Node::array_type onodes(3); \n         tmp_fld_msh->get_nodes(onodes, k);\n         onodes[0]+=offset;\n         onodes[1]+=offset;\n         onodes[2]+=offset;\n         output_vmesh->add_elem(onodes);\n         field_values_elc_on_scalp.push_back(i);\n        } \n\toffset+=tmp_fld_msh->num_nodes();\n       }  \n       \n       MatrixHandle mapping;\n       GetFieldBoundaryAlgo algo_getfldbnd;     \n       FieldHandle boundary;       \n       algo_getfldbnd.run(tmp_fld, boundary, mapping);\n       VMesh* boundary_msh  = boundary->vmesh();\n       /// connect electrode sponge surfaces\n       if (boundary->vmesh()->is_curvemesh())\n       {\n         tmp_fld_msh->synchronize(Mesh::NODE_LOCATE_E);\n\tVMesh::Edge::iterator meshEdgeIter;\n        VMesh::Edge::iterator meshEdgeEnd;\n        VMesh::Node::array_type nodesFromEdge(2);\n\tboundary_msh->end(meshEdgeEnd);\n\tfor (boundary_msh->begin(meshEdgeIter); meshEdgeIter != meshEdgeEnd; ++meshEdgeIter)\n        {\n          VMesh::Edge::index_type edgeID = *meshEdgeIter;\n\t  boundary_msh->get_nodes(nodesFromEdge, edgeID);\n\t  Point p0, p1;\n\t  boundary_msh->get_point(p0, nodesFromEdge[0]);\n          boundary_msh->get_point(p1, nodesFromEdge[1]);\n\t  VMesh::Node::index_type idx1;\n\t  tmp_fld_msh->find_closest_node(distance,r,idx1,p0);\n\t  if (distance!=0)\n\t  {\n\t   std::ostringstream ostr3;\n           ostr3 << \" Electrode sponge/scalp surface could not be found for \" << i+1 << \". electrode (could not find scalp bnd fragment node in scalp fragment). Make sure that prototype encapsulates scalp.\" << std::endl;\n           remark(ostr3.str());\n           break;   \n\t  }\n\t  VMesh::Node::index_type idx2;\n\t  tmp_fld_msh->find_closest_node(distance,r,idx2,p1);\n\t  if (distance!=0)\n\t  {\n\t   std::ostringstream ostr3;\n           ostr3 << \" Electrode sponge/scalp surface could not be found for \" << i+1 << \". electrode (could not find scalp bnd fragment node in scalp fragment). Make sure that prototype encapsulates scalp.\" << std::endl;         \n           remark(ostr3.str());\n           break;    \n\t  }\n\t  long i1=(long)idx1, i2=(long)idx2;\n\t  long i3=i1+tmp_fld_msh->num_nodes(), i4=i2+tmp_fld_msh->num_nodes();\n\t  VMesh::Node::array_type onodes(3); \n\t  onodes[0]=i3+nr_elc_sponge_triangles_on_scalp;\n\t  onodes[1]=i1+nr_elc_sponge_triangles_on_scalp;\n\t  onodes[2]=i4+nr_elc_sponge_triangles_on_scalp;\n\t  output_vmesh->add_elem(onodes);\n\t  field_values_elc_on_scalp.push_back(i);\n\t  onodes[0]=i4+nr_elc_sponge_triangles_on_scalp;\n\t  onodes[1]=i1+nr_elc_sponge_triangles_on_scalp;\n\t  onodes[2]=i2+nr_elc_sponge_triangles_on_scalp;\n\t  output_vmesh->add_elem(onodes);\n\t  field_values_elc_on_scalp.push_back(i);\n        }   \n\t\n        nr_elc_sponge_triangles_on_scalp+=tmp_fld_msh->num_nodes()+count_pts; \n       } else\n       {\n         std::ostringstream ostr3;\n         ostr3 << \" Trying to get boundary for scalp peace usind to create electrode \" << i+1 << \". Make sure that prototype encapsulates scalp.\" << std::endl;         \n         remark(ostr3.str());\n         continue;    \n       }\n       \n      }\n     }\n     \n   } else\n   {\n    std::ostringstream ostr3;\n    ostr3 << \" tDCS electrode definition for \" << i+1 << \". row needs be a point cloud (with defined scalar or vectors data).\" << std::endl;\n    remark(ostr3.str());\n    skip_current_iteration=true;\n    continue; \t    \n   }\n  \n  tdcs_vfld->resize_values();\n  tdcs_vfld->set_values(field_values);\n  output_vfld->resize_values();\n  output_vfld->set_values(field_values_elc_on_scalp);\n  elc_sponge_locations = boost::make_shared<DenseMatrix>(DenseMatrix::Zero(num_valid_electrode_definition,4));\n  int count=0;\n  for(int j=0;j<valid_electrode_definition.size();j++)\n  {\n   if(valid_electrode_definition[j]==1)\n   {\n    if(count<elc_sponge_locations->nrows())\n    {\n     (*elc_sponge_locations)(count,0)=elc_x[i];\n     (*elc_sponge_locations)(count,1)=elc_y[i];\n     (*elc_sponge_locations)(count,2)=elc_z[i];\n     (*elc_sponge_locations)(count,3)=elc_thickness[i];\n     count++;\n    }\n   }\n  }\n }\n } else\n {\n  std::ostringstream ostr3;\n  ostr3 << \" Internal error: tDCS electrode could not be generated. \" << std::endl;\n  remark(ostr3.str());\t\n }\n \n VariableHandle table2(new Variable(Name(\"Table\"), new_table));\n \n return boost::make_tuple(elc_sponge_locations, electrode_field, output, table2);\n}\n\nboost::tuple<VariableHandle, DenseMatrixHandle, FieldHandle, FieldHandle, FieldHandle> ElectrodeCoilSetupAlgorithm::run(const FieldHandle scalp, const DenseMatrixHandle locations, const std::vector<FieldHandle>& elc_coil_proto) const\n{\n VariableHandle table_output = fill_table(scalp, locations, elc_coil_proto);\n DenseMatrixHandle elc_sponge_locations;\n FieldHandle electrodes_field, coils_field, final_electrodes_field;\n auto table = table_output->toVector();\n  \n /// check GUI inputs:\n /// 1) Is there any valid row in the GUI table, so at least one row where both ComboBoxes are set\n ///  \n std::vector<double> elc_prototyp_map; \n std::vector<double> elc_thickness; \n std::vector<double> elc_angle_rotation; \n std::vector<double> elc_x;\n std::vector<double> elc_y;\n std::vector<double> elc_z;\n \n std::vector<double> coil_prototyp_map; \n std::vector<double> coil_angle_rotation; \n std::vector<double> coil_x;\n std::vector<double> coil_y;\n std::vector<double> coil_z;\n std::vector<double> coil_nx;\n std::vector<double> coil_ny;\n std::vector<double> coil_nz;\n \n /// The rest of the run function checks the validity of the GUI inputs. If there are not valid (=\"???\") it tries to use the prototype inputs and if valid it calls functions make_tdcs_electrodes or make_tms\n for(int i=0;i<table.size();i++)\n {\n  auto row = (table[i]).toVector();\n\n  /// the c* integer variables refine the column vales (1,2,3,...,10) for the current row\n  int c1=std::numeric_limits<double>::quiet_NaN(),c2=std::numeric_limits<double>::quiet_NaN();\n  double c3=std::numeric_limits<double>::quiet_NaN(),c4=std::numeric_limits<double>::quiet_NaN(),c5=std::numeric_limits<double>::quiet_NaN(),\n  c6=std::numeric_limits<double>::quiet_NaN(),c7=std::numeric_limits<double>::quiet_NaN(),c8=std::numeric_limits<double>::quiet_NaN(),\n  c9=std::numeric_limits<double>::quiet_NaN(),c10=std::numeric_limits<double>::quiet_NaN();\n\n  bool valid_position=true, valid_normal=true, row_valid=true;\n\n  try\n  {\n   c1 = lexical_cast<int>(row[0].toString());\n  } catch(bad_lexical_cast &)\n  {\n   c1=std::numeric_limits<double>::quiet_NaN();\n   row_valid=false;\n  }\n\n  try\n  { \n   c2 = lexical_cast<int>(row[1].toString());\n  } catch(bad_lexical_cast &)\n  {\n   c2=std::numeric_limits<double>::quiet_NaN();\n   row_valid=false;\n  }\n   \n  auto str_x = row[2].toString();\n  if (str_x.compare(\"???\")==0)\n  {\n    valid_position=false;\n  } else\n  {\n   try  \n   {\n     c3 = lexical_cast<double>(str_x);\n   } catch(bad_lexical_cast &)\n   {\n     c3=std::numeric_limits<double>::quiet_NaN();\n     valid_position=false;\n   }\n  }\n  \n  auto str_y = row[3].toString();\n  if (str_y.compare(\"???\")==0)\n  {\n   valid_position=false;\n  } else\n  {\n   try  ///get the electrode thickness from GUI\n   {\n     c4 = lexical_cast<double>(str_y);\n   } catch(bad_lexical_cast &)\n   {\n     c4=std::numeric_limits<double>::quiet_NaN();\n     valid_position=false;\n   }\n  }\n  \n  auto str_z = row[4].toString();\n  if (str_z.compare(\"???\")==0)\n  {\n     valid_position=false;\n  }  else\n  {\n   try  ///get the electrode thickness from GUI\n   {\n     c5 = lexical_cast<double>(str_z);\n   } catch(bad_lexical_cast &)\n   {\n     c5=std::numeric_limits<double>::quiet_NaN(); \n     valid_position=false;\n   }\n  }\n    \n  c6=-1;\n  auto angle = row[5].toString();\n  if (angle.compare(\"???\")!=0)\n  {\n   try \n   {\n    c6 = lexical_cast<double>(row[5].toString());\n   } catch(bad_lexical_cast &)\n   {\n    c6=std::numeric_limits<double>::quiet_NaN();\n   }\n  } else\n    c6=std::numeric_limits<double>::quiet_NaN();  \n\t\n  if (IsNan(c6))\t\n  {\t \n   c6=0;\n  }\n    \n  if(row_valid && c1>0 && c2>0)   ///both combo boxes are set up, so this could be a valid row but first check if ... \n                     /// its a tDCS electrode and if so if the thickness is provided in the GUI\n\t\t     /// or if its a TMS coil check if the prototype has normals - if so lets put the normal in the GUI \n  {\n    \n     FieldHandle prototyp = elc_coil_proto[c1-1]; \n\n     if (!prototyp)\n     {\n       std::ostringstream ostr1;\n       ostr1 << \"Module input \" << (c1+2) << \" seems to be empty\" << std::endl;\n       THROW_ALGORITHM_PROCESSING_ERROR(ostr1.str());\n     }\n     \n     GetFieldDataAlgo algo_getfielddata;\n     DenseMatrixHandle fielddata;\n     try\n     {\n      fielddata  = algo_getfielddata.run(prototyp);\n     }\n     catch (...)\n     {\n       \n     }\n     \n     GetMeshNodesAlgo algo_getfieldnodes;\n     DenseMatrixHandle fieldnodes;\n     try\n     {\n      algo_getfieldnodes.run(prototyp,fieldnodes);\n     }\n     catch (...)\n     {\n     \n     }\n\n     if ( (fieldnodes->nrows()!=fielddata->nrows()) )\n     {      \n      if( !((fieldnodes->nrows()==3 || fieldnodes->nrows()==1) && (fielddata->nrows()==3 || fielddata->nrows()==1)) )\n      { \n       std::ostringstream ostr_;\n       ostr_ << \"Module input \" << (c1+2) << \" (assigned tms coil prototype) does not contain same number of nodes as data values (linear basis).\" << std::endl;\n       THROW_ALGORITHM_PROCESSING_ERROR(ostr_.str());\n      }\n     }\n          \n     /// get Coil normal from GUI\n     /// get NX\n     try\n     {\n       c7 = lexical_cast<double>(row[6].toString());\n     } catch(bad_lexical_cast &)\n     {\n      c7=std::numeric_limits<double>::quiet_NaN();\n      valid_normal=false;\n     }\n     \n     /// get NY\n     try\n     {\n       c8 = lexical_cast<double>(row[7].toString());\n     } catch(bad_lexical_cast &)\n     {\n      c8=std::numeric_limits<double>::quiet_NaN();\n      valid_normal=false;\n     }\n     \n     /// get NZ\n     try\n     {\n       c9 = lexical_cast<double>(row[8].toString());\n     } catch(bad_lexical_cast &)\n     {\n      c9=std::numeric_limits<double>::quiet_NaN();\n      valid_normal=false;\n     } \n     \n     /// get electrode thickness\n     try\n     {\n       c10 = lexical_cast<double>(row[9].toString());\n     } catch(bad_lexical_cast &)\n     {\n      c10=std::numeric_limits<double>::quiet_NaN();\n     } \n     \n     if (!valid_normal && fielddata->ncols()==3 && fielddata->nrows()>=1) /// use FIRST(!) mag. dipole direction to infer coil orientation. Note that the determined direction could be anti parallel\n     {\n       double norm=sqrt((*fielddata)(0,0)*(*fielddata)(0,0)+(*fielddata)(0,1)*(*fielddata)(0,1)+(*fielddata)(0,2)*(*fielddata)(0,2)); /// normalize mag. dipole to get coil direction estimate\n       c7=(*fielddata)(0,0)/norm;\n       c8=(*fielddata)(0,1)/norm;\n       c9=(*fielddata)(0,2)/norm;\n       valid_normal=true;\n     }\n     \n     if(c7==0 && c8==0 && c9==0)\n     {\n      std::ostringstream ostr3;\n      ostr3 << \" The TMS coil defined in table row \" << i+1 << \" could not get any valid normal information, found normal contained only zeros (0,0,0). \" << std::endl;\n      remark(ostr3.str());\t\n      valid_normal=false;\n     }\n\n     if (!valid_position && fieldnodes->nrows()>=1 && fieldnodes->ncols()==3)\n     {\n       double x=0,y=0,z=0;\n       for(int j=0;j<fieldnodes->nrows();j++)\n        {\n\t x+=(*fieldnodes)(j,0);\n\t y+=(*fieldnodes)(j,1);\n\t z+=(*fieldnodes)(j,2);\n\t}\n       x/=fieldnodes->nrows();\n       y/=fieldnodes->nrows();\n       z/=fieldnodes->nrows();\n       c3=x;\n       c4=y;\n       c5=z;\n       valid_position=true;\n     }\n     \t\n    if (c2==tDCS_stim_type) /// tDCS?\n    {\n     if(valid_position)\n     {\n      elc_prototyp_map.push_back(c1); \n      elc_angle_rotation.push_back(c6); \n      elc_x.push_back(c3);\n      elc_y.push_back(c4);\n      elc_z.push_back(c5); \n      elc_thickness.push_back(c10);; \n     }\n    \n    } else\n    \n    if (c2==TMS_stim_type) /// TMS?\n    {\n     if(valid_normal && valid_position)\n     {\n      coil_prototyp_map.push_back(c1); \n      coil_angle_rotation.push_back(c6); \n      coil_x.push_back(c3);\n      coil_y.push_back(c4);\n      coil_z.push_back(c5);\n      coil_nx.push_back(c7);\n      coil_ny.push_back(c8);\n      coil_nz.push_back(c9);\n     } else\n        {\n\t  std::ostringstream ostr3;\n\t  ostr3 << \" The TMS coil defined in table row \" << i+1 << \" has no normal defined (NX,NY,NZ). Further, no normal could be taken from the linked prototyp field data. \" << std::endl;\n\t  remark(ostr3.str());\t\n\t}\n    }  \n      \n  }\n }  \n  \n  bool valid_tdcs=false, valid_tms=false; \n  int t1=elc_angle_rotation.size();\n  int t2=elc_thickness.size();\n  int t3=elc_x.size();\n  int t4=elc_y.size();\n  int t5=elc_z.size();\n  int t14=elc_coil_proto.size();\n  \n  if (t1==t2 && t1==t3 && t1==t4 && t1==t5 && t14>0 && t1>0)\n  {\n    boost::tie(elc_sponge_locations, electrodes_field, final_electrodes_field, table_output) = make_tdcs_electrodes(scalp, elc_coil_proto, elc_prototyp_map, elc_x, elc_y, elc_z, elc_angle_rotation, elc_thickness, table_output);\n    valid_tdcs=true;\n  }\n  \n  int t6=coil_prototyp_map.size();\n  int t7=coil_angle_rotation.size();\n  int t8=coil_x.size();\n  int t9=coil_y.size();\n  int t10=coil_z.size();\n  int t11=coil_nx.size();\n  int t12=coil_ny.size();\n  int t13=coil_nz.size();\n\n  if (t6==t7 && t6==t8 && t6==t9 && t6==t10 && t6==t11 && t6==t12 && t6==t13 && t14>0 && t6>0)\n  {\n   coils_field = make_tms(scalp, elc_coil_proto, coil_prototyp_map, coil_x, coil_y, coil_z, coil_angle_rotation, coil_nx, coil_ny, coil_nz); \n   valid_tms =true;     \n  }\n\n  if (!valid_tdcs && !valid_tms)\n  {  \n   std::ostringstream ostr0;\n   ostr0 << \" Not a single table row contains valid information. \" << std::endl;\n   remark(ostr0.str());\n  }\n\n return boost::make_tuple(table_output, elc_sponge_locations, electrodes_field, final_electrodes_field, coils_field);\n} \n\n\nAlgorithmOutput ElectrodeCoilSetupAlgorithm::run_generic(const AlgorithmInput& input) const\n{\n  auto scalp = input.get<Field>(SCALP_SURF);\n  auto locations = input.get<DenseMatrix>(LOCATIONS);\n  auto elc_coil_proto = input.getList<Field>(ELECTRODECOILPROTOTYPES);\n  \n  if (!scalp)\n  {\n    THROW_ALGORITHM_PROCESSING_ERROR(\" SCALP_SURF (first input) field empty. \");\n  }\n  \n  if (!locations)\n  {\n    THROW_ALGORITHM_PROCESSING_ERROR(\" LOCATIONS (second input) matrix empty. \");\n  }\n  \n  if (!(elc_coil_proto.size()>=1))\n  {\n    THROW_ALGORITHM_PROCESSING_ERROR(\" At least one prototypical coil (POINTMESH) or electrode (TRISURFMESH) definition as a field input must be provided.\");\n  }\n \n  if(locations->ncols()!=3)\n  {\n    THROW_ALGORITHM_PROCESSING_ERROR(\" Locations (second module input) needs to be a dense matrix input with dimensions lx3 (l being > 0). \");  \n  }\n  \n  VariableHandle table;\n  DenseMatrixHandle elc_sponge_loc_avr;\n  FieldHandle coils_field,electrodes_field, final_electrode_field;\n  boost::tie(table, elc_sponge_loc_avr, electrodes_field, final_electrode_field, coils_field) = run(scalp, locations, elc_coil_proto);\n\n  AlgorithmOutput output;\n  output[ELECTRODE_SPONGE_LOCATION_AVR] = elc_sponge_loc_avr;\n  output[MOVED_ELECTRODES_FIELD] = electrodes_field;\n  output[FINAL_ELECTRODES_FIELD] = final_electrode_field;\n  output[COILS_FIELD] = coils_field;\n  output.setAdditionalAlgoOutput(table);\n\n  return output;\n}\n", "meta": {"hexsha": "cd55cd170b960320ba5b765cc1f53110b90022df", "size": 51360, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/BrainStimulator/ElectrodeCoilSetupAlgorithm.cc", "max_stars_repo_name": "mhansen1/SCIRun", "max_stars_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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/Core/Algorithms/BrainStimulator/ElectrodeCoilSetupAlgorithm.cc", "max_issues_repo_name": "mhansen1/SCIRun", "max_issues_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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/Core/Algorithms/BrainStimulator/ElectrodeCoilSetupAlgorithm.cc", "max_forks_repo_name": "mhansen1/SCIRun", "max_forks_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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.9230769231, "max_line_length": 455, "alphanum_fraction": 0.6720404984, "num_tokens": 14789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1920988917628936}}
{"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     interaction.cpp\n * \\author   Collin Johnson\n *\n * Definition of find_interactions.\n */\n\n#include \"mpepc/evaluation/interaction.h\"\n#include \"hssh/local_topological/area.h\"\n#include \"hssh/local_topological/local_topo_map.h\"\n#include \"math/interpolation.h\"\n#include \"mpepc/evaluation/mpepc_log.h\"\n#include \"mpepc/social/social_norm_utils.h\"\n#include <boost/range/iterator_range.hpp>\n#include <tuple>\n\nnamespace vulcan\n{\nnamespace mpepc\n{\n\nstd::tuple<pose_t, velocity_t>\n  motion_state_at_time(int64_t time, MPEPCLog::motion_state_iterator begin, MPEPCLog::motion_state_iterator end);\ninteraction_t create_interaction(const pose_t& pose,\n                                 const velocity_t& velocity,\n                                 const tracker::DynamicObjectCollection& objects,\n                                 const hssh::LocalTopoMap& topoMap,\n                                 int numLateralBins,\n                                 double maxDistance,\n                                 double ignoreConeAngle);\nbool is_interacting_with_object(const pose_t& pose,\n                                const tracker::DynamicObject& object,\n                                double maxDistance,\n                                double ignoreConeAngle);\n\n\nstd::vector<interaction_t> find_interactions(MPEPCLog& log,\n                                             const hssh::LocalTopoMap& topoMap,\n                                             int numLateralBins,\n                                             double maxDistance,\n                                             double ignoreConeAngle)\n{\n    const int64_t kChunkDurationUs = 5000000;\n\n    std::vector<interaction_t> interactions;\n\n    // Process the log in chunks to ensure we don't run out of memory trying to load the big planning logs\n    int64_t startTimeUs = 0;\n\n    pose_t pose;\n    velocity_t velocity;\n\n    while (startTimeUs < log.durationUs()) {\n        log.loadTimeRange(startTimeUs, startTimeUs + (2 * kChunkDurationUs));\n\n        // The objects are detected at a lower rate than the poses, so for each object collection, create an interaction\n        // using the interpolated pose\n        for (auto& objs : boost::make_iterator_range(log.beginObjects(startTimeUs),\n                                                     log.endObjects(startTimeUs + kChunkDurationUs))) {\n            std::tie(pose, velocity) =\n              motion_state_at_time(objs.timestamp(), log.beginMotionState(), log.endMotionState());\n            interactions.push_back(\n              create_interaction(pose, velocity, objs, topoMap, numLateralBins, maxDistance, ignoreConeAngle));\n        }\n\n        startTimeUs += kChunkDurationUs;\n    }\n\n    return interactions;\n}\n\n\nstd::tuple<pose_t, velocity_t>\n  motion_state_at_time(int64_t time, MPEPCLog::motion_state_iterator begin, MPEPCLog::motion_state_iterator end)\n{\n    // If there's nothing to interpolate, then return one of the ends\n    assert(begin != end);\n\n    if (time <= begin->timestamp) {\n        return std::make_tuple(begin->pose, begin->velocity);\n    } else if (time >= (end - 1)->timestamp) {\n        return std::make_tuple((end - 1)->pose, (end - 1)->velocity);\n    }\n\n    pose_t pose;\n    velocity_t velocity;\n\n    pose.timestamp = time;\n    velocity.timestamp = time;\n\n    for (auto next = begin + 1; next < end; ++begin, ++next) {\n        // Find the range to interpolate between.\n        if ((begin->timestamp <= time) && (time <= next->timestamp)) {\n            // Ensure the timestamps are converted, since MPEPCLog doesn't deep-change the time\n            pose_t startPose = begin->pose;\n            startPose.timestamp = begin->timestamp;\n\n            pose_t nextPose = next->pose;\n            nextPose.timestamp = next->timestamp;\n\n            pose = interpolate_pose(startPose, nextPose, time);\n\n            double scale = static_cast<double>(time - begin->timestamp) / (next->timestamp - begin->timestamp);\n            velocity.linear = math::linear_interpolation(begin->velocity.linear, next->velocity.linear, scale);\n            velocity.angular = math::linear_interpolation(begin->velocity.angular, next->velocity.angular, scale);\n        }\n    }\n\n    return std::make_tuple(pose, velocity);\n}\n\n\ninteraction_t create_interaction(const pose_t& pose,\n                                 const velocity_t& velocity,\n                                 const tracker::DynamicObjectCollection& objects,\n                                 const hssh::LocalTopoMap& topoMap,\n                                 int numLateralBins,\n                                 double maxDistance,\n                                 double ignoreConeAngle)\n{\n    interaction_t interaction;\n    interaction.timestamp = objects.timestamp();\n    interaction.velocity = velocity;\n    interaction.pose = pose;\n\n    for (auto obj : objects) {\n        if (is_interacting_with_object(pose, *obj, maxDistance, ignoreConeAngle)) {\n            if (auto agent = convert_to_topo_agent(obj, topoMap)) {\n                interaction.agents.push_back(*agent);\n            }\n        }\n    }\n\n    auto robotAgent = create_agent_for_robot(motion_state_t(pose, velocity), topoMap);\n\n    if (topoMap.pathSegmentWithId(robotAgent.areaId)) {\n        interaction.pathSituation = PathSituation(robotAgent, interaction.agents, numLateralBins, topoMap);\n    } else if (is_about_to_transition(robotAgent, topoMap)) {\n        interaction.placeSituation = PlaceSituation(robotAgent, interaction.agents, topoMap);\n    }\n\n    interaction.robotAgent = robotAgent;\n    interaction.areaId = robotAgent.areaId;\n\n    return interaction;\n}\n\n\nbool is_interacting_with_object(const pose_t& pose,\n                                const tracker::DynamicObject& object,\n                                double maxDistance,\n                                double ignoreConeAngle)\n{\n    bool is_close_enough = distance_between_points(pose.toPoint(), object.position()) < maxDistance;\n    bool is_in_cone = angle_diff_abs(angle_to_point(pose.toPoint(), object.position()), pose.theta) < ignoreConeAngle;\n\n    return is_close_enough && is_in_cone;\n}\n\n\n}   // namespace mpepc\n}   // namespace vulcan\n", "meta": {"hexsha": "f594e15d456b21c4f9dc36eadf6433088ce76ba3", "size": 6510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mpepc/evaluation/interaction.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/mpepc/evaluation/interaction.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/mpepc/evaluation/interaction.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": 37.8488372093, "max_line_length": 120, "alphanum_fraction": 0.6238095238, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1920988917628936}}
{"text": "// Copyright (c) 2009-2013 The Dacrs 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 \"crypter.h\"\n\n//#include \"script.h\"\n#include \"util.h\"\n#include <string>\n#include <vector>\n#include <boost/foreach.hpp>\n#include <openssl/aes.h>\n#include <openssl/evp.h>\n\nbool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const vector<unsigned char>& vchSalt,\n\t\tconst unsigned int unRounds, const unsigned int unDerivationMethod) {\n\tif (unRounds < 1 || vchSalt.size() != g_kWalletCryptoSaltSize) {\n\t\treturn false;\n\t}\n\tint i = 0;\n\tif (unDerivationMethod == 0) {\n\t\ti = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &vchSalt[0], (unsigned char *) &strKeyData[0],\n\t\t\t\t\t\tstrKeyData.size(), unRounds, m_chKey, m_chIV);\n\t}\n\tif (i != (int) g_kWalletCryptoKeySize) {\n\t\tOPENSSL_cleanse(m_chKey, sizeof(m_chKey));\n\t\tOPENSSL_cleanse(m_chIV, sizeof(m_chIV));\n\t\treturn false;\n\t}\n\tm_bKeySet = true;\n\n\treturn true;\n}\n\nbool CCrypter::SetKey(const CKeyingMaterial& vchNewKey, const vector<unsigned char>& vchNewIV) {\n\tif (vchNewKey.size() != g_kWalletCryptoKeySize || vchNewIV.size() != g_kWalletCryptoKeySize) {\n\t\treturn false;\n\t}\n\tmemcpy(&m_chKey[0], &vchNewKey[0], sizeof m_chKey);\n\tmemcpy(&m_chIV[0], &vchNewIV[0], sizeof m_chIV);\n\tm_bKeySet = true;\n\n\treturn true;\n}\n\nbool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, vector<unsigned char> &vchCiphertext) {\n\tif (!m_bKeySet) {\n\t\treturn false;\n\t}\n\t// max ciphertext len for a n bytes of plaintext is\n\t// n + AES_BLOCK_SIZE - 1 bytes\n\tint nLen = vchPlaintext.size();\n\tint nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;\n\tvchCiphertext = vector<unsigned char>(nCLen);\n\n\tEVP_CIPHER_CTX sEvpCipherCtx;\n\n\tbool bOk = true;\n\n\tEVP_CIPHER_CTX_init(&sEvpCipherCtx);\n\tif (bOk) {\n\t\tbOk = EVP_EncryptInit_ex(&sEvpCipherCtx, EVP_aes_256_cbc(), NULL, m_chKey, m_chIV);\n\t}\n\tif (bOk) {\n\t\tbOk = EVP_EncryptUpdate(&sEvpCipherCtx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);\n\t}\n\tif (bOk) {\n\t\tbOk = EVP_EncryptFinal_ex(&sEvpCipherCtx, (&vchCiphertext[0]) + nCLen, &nFLen);\n\t}\n\n\tEVP_CIPHER_CTX_cleanup(&sEvpCipherCtx);\n\n\tif (!bOk) {\n\t\treturn false;\n\t}\n\tvchCiphertext.resize(nCLen + nFLen);\n\n\treturn true;\n}\n\nbool CCrypter::Decrypt(const vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) {\n\tif (!m_bKeySet) {\n\t\treturn false;\n\t}\n\t// plaintext will always be equal to or lesser than length of ciphertext\n\tint nLen = vchCiphertext.size();\n\tint nPLen = nLen, nFLen = 0;\n\n\tvchPlaintext = CKeyingMaterial(nPLen);\n\tEVP_CIPHER_CTX sEvpCipherCtx;\n\tbool bOk = true;\n\n\tEVP_CIPHER_CTX_init(&sEvpCipherCtx);\n\tif (bOk) {\n\t\tbOk = EVP_DecryptInit_ex(&sEvpCipherCtx, EVP_aes_256_cbc(), NULL, m_chKey, m_chIV);\n\t}\n\tif (bOk) {\n\t\tbOk = EVP_DecryptUpdate(&sEvpCipherCtx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);\n\t}\n\tif (bOk) {\n\t\tbOk = EVP_DecryptFinal_ex(&sEvpCipherCtx, (&vchPlaintext[0]) + nPLen, &nFLen);\n\t}\n\n\tEVP_CIPHER_CTX_cleanup(&sEvpCipherCtx);\n\n\tif (!bOk) {\n\t\treturn false;\n\t}\n\tvchPlaintext.resize(nPLen + nFLen);\n\n\treturn true;\n}\n\nbool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vPlaintext, const uint256& cIV,\n\t\tvector<unsigned char> &vchCiphertext) {\n\tCCrypter cKeyCrypter;\n\tvector<unsigned char> vchIV(g_kWalletCryptoKeySize);\n\tmemcpy(&vchIV[0], &cIV, g_kWalletCryptoKeySize);\n\tif (!cKeyCrypter.SetKey(vMasterKey, vchIV)) {\n\t\treturn false;\n\t}\n\n\treturn cKeyCrypter.Encrypt(*((const CKeyingMaterial*) &vPlaintext), vchCiphertext);\n}\n\nbool DecryptSecret(const CKeyingMaterial& vMasterKey, const vector<unsigned char>& vchCiphertext, const uint256& cIV,\n\t\tCKeyingMaterial& vPlaintext) {\n\tCCrypter cKeyCrypter;\n\tvector<unsigned char> vchIV(g_kWalletCryptoKeySize);\n\tmemcpy(&vchIV[0], &cIV, g_kWalletCryptoKeySize);\n\tif (!cKeyCrypter.SetKey(vMasterKey, vchIV)) {\n\t\treturn false;\n\t}\n\n\treturn cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*) &vPlaintext));\n}\n\nbool CCryptoKeyStore::SetCrypted() {\n\tLOCK(cs_KeyStore);\n\tif (m_bUseCrypto) {\n\t\treturn true;\n\t}\n\tif (IsContainMainKey()) {\n\t\treturn false;\n\t}\n\tm_bUseCrypto = true;\n\n\treturn true;\n}\n\nbool CCryptoKeyStore::Lock() {\n\tif (!SetCrypted()) {\n\t\treturn false;\n\t}\n\t{\n\t\tLOCK(cs_KeyStore);\n\t\tm_vMasterKey.clear();\n\t}\n\tg_pUIInterface->NotifyMessage(\"Lock\");\n\tNotifyStatusChanged(this);\n\n\treturn true;\n}\n\nbool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) {\n\t{\n\t\tLOCK(cs_KeyStore);\n\t\tif (!SetCrypted()) {\n\t\t\treturn false;\n\t\t}\n\t\tCryptedKeyMap::const_iterator mi = m_mapCryptedKeys.begin();\n\t\tfor (; mi != m_mapCryptedKeys.end(); ++mi) {\n\t\t\tconst CPubKey &cPubKey = (*mi).second.first;\n\t\t\tconst vector<unsigned char> &vchCryptedSecret = (*mi).second.second;\n\t\t\tCKeyingMaterial vSecret;\n\t\t\tif (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, cPubKey.GetHash(), vSecret)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (vSecret.size() != 32) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tCKey cKey;\n\t\t\tcKey.Set(vSecret.begin(), vSecret.end(), cPubKey.IsCompressed());\n\t\t\tif (cKey.GetPubKey() == cPubKey) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\t\tm_vMasterKey = vMasterKeyIn;\n\t}\n\tg_pUIInterface->NotifyMessage(\"UnLock\");\n\tNotifyStatusChanged(this);\n\n\treturn true;\n}\n\nbool CCryptoKeyStore::AddKeyCombi(const CKeyID & cKeyId, const CKeyCombi &cKeyCombi) {\n\t{\n\t\tLOCK(cs_KeyStore);\n\n\t\tif (!IsCrypted()) {\n\t\t\treturn CBasicKeyStore::AddKeyCombi(cKeyId, cKeyCombi);\n\t\t}\n\t\tif (IsLocked()) {\n\t\t\treturn false;\n\t\t}\n\t\tCKey cMainKey;\n\t\tcKeyCombi.GetCKey(cMainKey, false);\n\t\tCKeyCombi newkeyCombi = cKeyCombi;\n\t\tnewkeyCombi.CleanMainKey();\n\t\tCBasicKeyStore::AddKeyCombi(cKeyId, cKeyCombi);\n\n\t\tvector<unsigned char> vchCryptedSecret;\n\t\tCKeyingMaterial vchSecret(cMainKey.begin(), cMainKey.end());\n\t\tCPubKey cPubKey;\n\t\tcPubKey = cMainKey.GetPubKey();\n\t\tif (!EncryptSecret(m_vMasterKey, vchSecret, cPubKey.GetHash(), vchCryptedSecret)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!AddCryptedKey(cPubKey, vchCryptedSecret)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool CCryptoKeyStore::AddCryptedKey(const CPubKey &cPubKey, const vector<unsigned char> &vchCryptedSecret) {\n\t{\n\t\tLOCK(cs_KeyStore);\n\t\tif (!SetCrypted()) {\n\t\t\treturn false;\n\t\t}\n\t\tm_mapCryptedKeys[cPubKey.GetKeyID()] = make_pair(cPubKey, vchCryptedSecret);\n\t}\n\n\treturn true;\n}\n\nbool CCryptoKeyStore::GetKey(const CKeyID &cAddress, CKey& ckeyOut, bool bIsMine) const {\n\t{\n\t\tLOCK(cs_KeyStore);\n\t\tif (bIsMine) {\n\t\t\treturn CBasicKeyStore::GetKey(cAddress, ckeyOut, bIsMine);\n\t\t} else {\n\t\t\tif (!IsCrypted()) {\n\t\t\t\treturn CBasicKeyStore::GetKey(cAddress, ckeyOut);\n\t\t\t}\n\t\t\tCryptedKeyMap::const_iterator mi = m_mapCryptedKeys.find(cAddress);\n\t\t\tif (mi != m_mapCryptedKeys.end()) {\n\t\t\t\tconst CPubKey &cPubKey = (*mi).second.first;\n\t\t\t\tconst vector<unsigned char> &vchCryptedSecret = (*mi).second.second;\n\t\t\t\tCKeyingMaterial vSecret;\n\t\t\t\tif (!DecryptSecret(m_vMasterKey, vchCryptedSecret, cPubKey.GetHash(), vSecret)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (vSecret.size() != 32) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tckeyOut.Set(vSecret.begin(), vSecret.end(), cPubKey.IsCompressed());\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool CCryptoKeyStore::GetPubKey(const CKeyID &cAddress, CPubKey& cPubKeyOut, bool bIsMine) const {\n\t{\n\t\tLOCK(cs_KeyStore);\n\t\tif (bIsMine) {\n\t\t\treturn CKeyStore::GetPubKey(cAddress, cPubKeyOut, bIsMine);\n\t\t} else {\n\t\t\tif (!IsCrypted()) {\n\t\t\t\treturn CKeyStore::GetPubKey(cAddress, cPubKeyOut, bIsMine);\n\t\t\t}\n\t\t\tCryptedKeyMap::const_iterator mi = m_mapCryptedKeys.find(cAddress);\n\t\t\tif (mi != m_mapCryptedKeys.end()) {\n\t\t\t\tcPubKeyOut = (*mi).second.first;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool CCryptoKeyStore::GetKeyCombi(const CKeyID & cAddress, CKeyCombi & cKeyCombiOut) const {\n\tCBasicKeyStore::GetKeyCombi(cAddress, cKeyCombiOut);\n\tif (!IsCrypted()) {\n\t\treturn true;\n\t}\n\tCKey cKeyOut;\n\tif (!IsLocked()) {\n\t\tif (!GetKey(cAddress, cKeyOut)) {\n\t\t\treturn false;\n\t\t}\n\t\tcKeyCombiOut.SetMainKey(cKeyOut);\n\t}\n\n\treturn true;\n}\n\nbool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) {\n\t{\n\t\tLOCK(cs_KeyStore);\n\t\tif (!m_mapCryptedKeys.empty() || IsCrypted()) {\n\t\t\treturn false;\n\t\t}\n\t\tm_bUseCrypto = true;\n\t\tfor (auto& mKey : mapKeys) {\n\t\t\tCKey cMainKey;\n\t\t\tmKey.second.GetCKey(cMainKey, false);\n\t\t\tCPubKey cPubKey = cMainKey.GetPubKey();\n\t\t\tCKeyingMaterial vSecret(cMainKey.begin(), cMainKey.end());\n\t\t\tvector<unsigned char> vchCryptedSecret;\n\t\t\tif (!EncryptSecret(vMasterKeyIn, vSecret, cPubKey.GetHash(), vchCryptedSecret)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!AddCryptedKey(cPubKey, vchCryptedSecret)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tmKey.second.CleanMainKey();\n\t\t}\n\t}\n\n\treturn true;\n}\n", "meta": {"hexsha": "0587018c18d88dbcd9f8335c23961a4d715a6e75", "size": 8559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crypter.cpp", "max_stars_repo_name": "SoyPay/dacrs", "max_stars_repo_head_hexsha": "ddeb4741beb83756ccc85fd611c66d8be8cb3bad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T09:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-15T13:49:21.000Z", "max_issues_repo_path": "src/crypter.cpp", "max_issues_repo_name": "SoyPay/dacrs", "max_issues_repo_head_hexsha": "ddeb4741beb83756ccc85fd611c66d8be8cb3bad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-03-11T08:51:51.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-25T01:39:43.000Z", "max_forks_repo_path": "src/crypter.cpp", "max_forks_repo_name": "SoyPay/dacrs", "max_forks_repo_head_hexsha": "ddeb4741beb83756ccc85fd611c66d8be8cb3bad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T04:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T09:47:27.000Z", "avg_line_length": 25.7801204819, "max_line_length": 117, "alphanum_fraction": 0.7080266386, "num_tokens": 2771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1920988917628936}}
{"text": "#ifndef STAN_MATH_TORSTEN_EVENTS_MANAGER_HPP\n#define STAN_MATH_TORSTEN_EVENTS_MANAGER_HPP\n\n#include <stan/math/torsten/dsolve/pk_vars.hpp>\n#include <stan/math/torsten/ev_history.hpp>\n#include <stan/math/torsten/ev_record.hpp>\n#include <stan/math/torsten/event.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <Eigen/Dense>\n#include <string>\n#include <vector>\n\nnamespace torsten {\n  template <typename T_event_record, typename T_params>\n  struct EventsManager;\n\n  template <typename T0, typename T1, typename T2, typename T3, typename T4,\n            template<class...> class theta_container, typename... tuple_pars_t, typename... Ts>\n  struct EventsManager<NONMENEventsRecord<T0, T1, T2, T3>,\n                       NonEventParameters<T0, T4, theta_container, std::tuple<tuple_pars_t...>, Ts...> > {\n    using param_t = NonEventParameters<T0, T4, theta_container, std::tuple<tuple_pars_t...>, Ts...>;\n    using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n    using T_scalar = typename stan::return_type_t<typename ER::T_scalar, T4, tuple_pars_t..., Ts...>;\n    using T_time   = typename stan::return_type_t<typename ER::T_time, typename param_t::lag_t>;\n    using T_rate   = typename stan::return_type_t<typename ER::T_rate, typename param_t::biovar_t>;\n    using T_amt    = typename stan::return_type_t<typename ER::T_amt, typename param_t::biovar_t>;\n    using T_par    = T4;\n    using T_par_rate = T2;\n    using T_par_ii   = T3;\n\n    param_t params;\n    EventHistory<T0, T1, T2, T3, typename param_t::lag_t> event_his;\n\n    int nKeep;\n    int ncmt;\n\n    static int nCmt(const ER& rec) {\n      return rec.ncmt;\n    }\n\n    /*\n     * the index in the result/input where subject @c id begins.\n     */\n    static int begin(int id, const ER& rec) {\n      return rec.begin_.at(id);\n    }\n\n    /*\n     * For population models, we need generate events using\n     * ragged arrays.\n     */\n    template<typename... Tss>\n    EventsManager(const ER& rec,\n                  const std::vector<theta_container<T4>>& theta,\n                  const std::vector<std::vector<Tss>>&... non_event_params) :\n      EventsManager(0, rec, theta, non_event_params...)\n    {}\n\n    /*\n     * For population models, we need generate events using\n     * ragged arrays.\n     */\n    template<typename... Tss>\n    EventsManager(int id, const ER& rec,\n                  const std::vector<theta_container<T4>>& theta,\n                  const std::vector<std::vector<Tss>>&... non_event_params) :\n      params(id, rec, theta, non_event_params...),\n      event_his(rec.ncmt, rec.begin_[id], rec.len_[id], rec.time_, rec.amt_, rec.rate_, rec.ii_, rec.evid_, rec.cmt_, rec.addl_, rec.ss_)\n    {\n      ncmt = rec.ncmt;\n\n      attach_event_parameters();\n      insert_lag_dose();\n      event_his.generate_rates(ncmt);\n      attach_event_parameters();\n\n      nKeep = event_his.num_event_times;\n    }\n\n    template<typename... Tss>\n    EventsManager(int id, const ER& rec,\n                  int ibegin_theta, int isize_theta,\n                  int ibegin_biovar, int isize_biovar,\n                  int ibegin_tlag, int isize_tlag,\n                  const std::vector<theta_container<T4>>& theta,\n                  const std::vector<std::vector<Tss>>&... non_event_params) :\n      params(id, rec, ibegin_theta, isize_theta, ibegin_biovar, isize_biovar, ibegin_tlag, isize_tlag, theta, non_event_params...),\n      event_his(rec.ncmt, rec.begin_[id], rec.len_[id], rec.time_, rec.amt_, rec.rate_, rec.ii_, rec.evid_, rec.cmt_, rec.addl_, rec.ss_)\n    {\n      ncmt = rec.ncmt;\n\n      attach_event_parameters();\n      insert_lag_dose();\n      event_his.generate_rates(ncmt);\n      attach_event_parameters();\n\n      nKeep = event_his.num_event_times;\n    }\n\n    /**\n     * Implement absorption lag times by modifying the times of the dosing events.\n     * Two cases: parameters are either constant or vary with each event.\n     * Function sorts events at the end of the procedure.\n     * The old event is set with a special EVID = 9 and it introduces no action.\n     */\n    void insert_lag_dose() {\n      // reverse loop so we don't process same lagged events twice\n      int nEvent = event_his.size();\n      int iEvent = nEvent - 1;\n      while (iEvent >= 0) {\n        if (event_his.is_dosing(iEvent)) {\n          if (params.lag_time(iEvent, event_his.cmt(iEvent) - 1) > ER::lag_time_min) {\n            event_his.insert_event(iEvent);\n            event_his.gen_time.back() += params.lag_time(iEvent, event_his.cmt(iEvent) - 1);\n            event_his.idx[iEvent][2] = 9;\n          }\n        }\n        iEvent--;\n      }\n      event_his.sort_state_time();\n    }\n\n    const EventHistory<T0, T1, T2, T3, typename param_t::lag_t>& events() const {\n      return event_his;\n    }\n\n    void attach_event_parameters() {\n      int nEvent = event_his.size();\n      assert(nEvent > 0);\n      int len_Parameters = params.size();  // numbers of events for which parameters are determined\n      assert(len_Parameters > 0);\n\n      if (!params.is_ordered()) params.sort();\n      params.pars.resize(nEvent);\n\n      int iEvent = 0;\n      for (int i = 0; i < len_Parameters - 1; ++i) {\n        while (event_his.isnew(iEvent)) iEvent++;  // skip new events\n        assert(params.get_par_time(i) == event_his.time(iEvent));  // compare time of \"old' events to time of parameters.\n        iEvent++;\n      }\n\n      if (len_Parameters == 1)  {\n        for (int i = 0; i < nEvent; ++i) {\n          params.set_par_time(i, stan::math::value_of(event_his.time(i)));\n          params.set_par_array(i, params.get_par_array(0));\n          event_his.idx[i][3] = 0;\n        }\n      } else {  // parameters are event dependent.\n        std::vector<double> times(nEvent, 0);\n        for (int i = 0; i < nEvent; ++i) times[i] = params.pars[i].first;\n        iEvent = 0;\n\n        using par_t = typename param_t::par_t;\n        par_t newParameter;\n        int j = 0;\n        typename std::vector<par_t>::const_iterator lower = params.pars.begin();\n        typename std::vector<par_t>::const_iterator it_param_end = params.pars.begin() + len_Parameters;\n        for (int iEvent = 0; iEvent < nEvent; ++iEvent) {\n          if (event_his.isnew(iEvent)) {\n            // Find the index corresponding to the time of the new event in the\n            // times vector.\n            const double t = stan::math::value_of(event_his.time(iEvent));\n            lower = std::lower_bound(lower, it_param_end, t,\n                                     [](const par_t& t1, const double& t2) {return t1.first < t2;});\n            newParameter = lower == (it_param_end) ? params.pars[len_Parameters-1] : *lower;\n            newParameter.first = t;\n            params.pars[len_Parameters + j] = newParameter;\n            event_his.idx[iEvent][3] = 0; /**< item is \"new\" no more, set \"isnew\" false */\n            j++;\n          }\n        }\n      }\n      params.sort();\n    }\n\n    /** \n     * Get model param for certain subject\n     * \n     * @param i subject id\n     * \n     * @return model param\n     */\n    inline const theta_container<T4>& theta(int i) const {\n      return params.theta(i);\n    }\n\n    template<size_t Is>\n    inline auto& get_model_array_1d_param(int i) const {\n      return params.template get_model_array_1d_param<Is>(i);\n    }\n\n    /** \n     * Get dosing rate adjusted with bioavailability for a subject\n     * \n     * @param i subject id\n     * \n     * @return dosing rate\n     */\n    inline std::vector<T_rate> fractioned_rates(int i) const {\n      const int n = event_his.rates[0].second.size();\n      const std::vector<T2>& r = event_his.rates[event_his.rate_index[i]].second;\n      std::vector<T_rate> res(r.size());\n      for (size_t j = 0; j < r.size(); ++j) {\n        res[j] = r[j] * params.bioavailability(i, j);\n      }\n      return res;\n    }\n\n    /** \n     * Get dosing amount adjusted with bioavailability for a subject\n     * \n     * @param i subject id\n     * \n     * @return dosing amount\n     */\n    inline T_amt fractioned_amt(int i) const {\n      // return bioavailability(i, cmt(i) - 1) * amt(i);\n      return params.bioavailability(i, event_his.cmt(i) - 1) * event_his.amt(i);\n    }\n\n    Event<T_time, T3, T_amt, T_rate, T2> event(int i) const {\n      int id;\n      switch (event_his.evid(i)) {\n      case 2:                   // \"other\" type given \"-cmt\" indicates turn-off/reset\n        if (event_his.cmt(i) < 0) {\n            id = 5;\n        } else {\n          id = 0;\n        }\n        break;\n      case 3:                   // reset\n        id = 1;\n        break;\n      case 4:                   // reset + dosing\n        if (event_his.is_ss_dosing(i)) {\n          // since it's reset, SS reset is irrelevant \n          id = 4;\n        } else {\n          id = 2;\n        }\n        break;\n      case 8:                   // mrgsolve: \"evid=9\" overwrite cmt\n        if (event_his.cmt(i) > 0) {\n          id = 6;\n        }\n        break;\n      default:\n        if (event_his.is_ss_dosing(i)) {\n          if (event_his.ss(i) == 2) {\n            id = 3;\n          } else {\n            id = 4;\n          }\n        } else {\n          id = 0;\n        }\n      }\n\n      T_time t0, t1;\n      if (event_his.is_ss_dosing(i)) {\n        // t0 = event_his.time(i);\n        // t1 = event_his.ii(i);\n        t0 = i == 0 ? event_his.time(0) : event_his.time(i-1);\n        t1 = event_his.time(i);\n      } else {\n        t0 = i == 0 ? event_his.time(0) : event_his.time(i-1);\n        t1 = event_his.time(i);\n      }\n      PKRec<T_amt> amt = PKRec<T_amt>::Zero(ncmt);\n      if (event_his.is_bolus_dosing(i) || event_his.is_ss_dosing(i)) {\n        amt(event_his.cmt(i) - 1) = fractioned_amt(i);\n      }\n      std::vector<T_rate> rate(fractioned_rates(i));\n      return {id, t0, t1, event_his.ii(i),\n              amt, rate, event_his.rate(i), event_his.cmt(i)};\n    }\n\n    /*\n     * number of events for a sinlge individual\n     */\n    template<typename... Tss>\n    static int num_events(const ER& rec,\n                          const std::vector<theta_container<T4>>& theta,\n                          const std::vector<std::vector<Tss>>&... non_event_params) {\n      return num_events(0, rec, theta, non_event_params...);\n    }\n\n    static int num_events(int id, const ER& rec,\n                          const std::vector<theta_container<T4>>& theta) {\n      int res;\n      int n = rec.len_[id];\n      for (int i = rec.begin_[id]; i < rec.begin_[id] + rec.len_[id]; ++i) {\n        if (rec.evid_[i] == 1 || rec.evid_[i] == 4) {      // is dosing event\n          if (rec.addl_[i] > 0 && rec.ii_[i] > 0) {        // has addl doses\n            if (rec.rate_[i] > 0 && rec.amt_[i] > 0) {\n              n++;                               // end event for original IV dose\n              n += 2 * rec.addl_[i];                  // end event for addl IV dose\n            } else {\n              n += rec.addl_[i];\n            }\n          } else if (rec.rate_[i] > 0 && rec.amt_[i] > 0) {\n            n++;                                 // end event for IV dose\n          }\n        }\n      }\n      res = n;\n      return res;\n    }\n    \n    template<typename T5>\n    static int num_events(int id, const ER& rec,\n                          const std::vector<theta_container<T4>>& theta,\n                          const std::vector<std::vector<T5> >& biovar) {\n      return num_events(id, rec, theta);\n    }\n\n    template<typename T5, typename T6, typename... Tss>\n    static int num_events(int id, const ER& rec,\n                          const std::vector<theta_container<T4>>& theta,\n                          const std::vector<std::vector<T5> >& biovar,\n                          const std::vector<std::vector<T6> >& tlag,\n                          const std::vector<std::vector<Tss>>&... non_event_params) {\n      int res;\n      bool has_lag = rec.has_positive_param(id, tlag);\n\n      if (!has_lag) {\n        res = num_events(id, rec, theta);\n      } else if (rec.len_param(id, tlag) == 1) {\n        int n = rec.len_[id];\n        std::vector<std::tuple<double, int>> dose;\n        dose.reserve(rec.len_[id]);\n        for (int i = rec.begin_[id]; i < rec.begin_[id] + rec.len_[id]; ++i) {\n          if (rec.evid_[i] == 1 || rec.evid_[i] == 4) {      // is dosing event\n            if (tlag[rec.begin_param(id, tlag)][rec.cmt_[i] - 1] > 0.0) {       // tlag dose\n              n++;\n            }\n            if (rec.addl_[i] > 0 && rec.ii_[i] > 0) {        // has addl doses\n              if (rec.rate_[i] > 0 && rec.amt_[i] > 0) {\n                n++;                               // end ev for IV dose\n                n += 2 * rec.addl_[i];                  // end ev for addl IV dose\n              } else {\n                n += rec.addl_[i];\n              }\n              if (tlag[rec.begin_param(id, tlag)][rec.cmt_[i] - 1] > 0.0) {     // tlag dose\n                n += rec.addl_[i];\n              }\n            } else if (rec.rate_[i] > 0 && rec.amt_[i] > 0) {\n              n++;                                 // end event for IV dose\n            }\n          }\n        }\n        res = n;\n      } else {\n        // FIXME not to use brute force\n        res = EventsManager(id, rec, theta, biovar, tlag, non_event_params...).events().size();\n      }\n\n      return res;\n    }\n  };\n\n}\n\n#endif\n", "meta": {"hexsha": "83bac2b13314b8adaf2ae9837720eb054f5b48cf", "size": 13209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ev_manager.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": "ev_manager.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": "ev_manager.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": 36.0901639344, "max_line_length": 137, "alphanum_fraction": 0.5475054887, "num_tokens": 3594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1920988917628936}}
{"text": "//  Copyright John Maddock 2005-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_PRECISION_INCLUDED\n#define BOOST_MATH_TOOLS_PRECISION_INCLUDED\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/limits.hpp>\n#include <boost/assert.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/math/policies/policy.hpp>\n\n// These two are for LDBL_MAN_DIG:\n#include <limits.h>\n#include <math.h>\n\nnamespace boost{ namespace math\n{\nnamespace tools\n{\n// If T is not specialized, the functions digits, max_value and min_value,\n// all get synthesised automatically from std::numeric_limits.\n// However, if numeric_limits is not specialised for type RealType,\n// for example with NTL::RR type, then you will get a compiler error\n// when code tries to use these functions, unless you explicitly specialise them.\n\n// For example if the precision of RealType varies at runtime,\n// then numeric_limits support may not be appropriate,\n// see boost/math/tools/ntl.hpp  for examples like\n// template <> NTL::RR max_value<NTL::RR> ...\n// See  Conceptual Requirements for Real Number Types.\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR int digits(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(T)) BOOST_NOEXCEPT\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   BOOST_STATIC_ASSERT( ::std::numeric_limits<T>::is_specialized);\n   BOOST_STATIC_ASSERT( ::std::numeric_limits<T>::radix == 2 || ::std::numeric_limits<T>::radix == 10);\n#else\n   BOOST_ASSERT(::std::numeric_limits<T>::is_specialized);\n   BOOST_ASSERT(::std::numeric_limits<T>::radix == 2 || ::std::numeric_limits<T>::radix == 10);\n#endif\n   return std::numeric_limits<T>::radix == 2 \n      ? std::numeric_limits<T>::digits\n      : ((std::numeric_limits<T>::digits + 1) * 1000L) / 301L;\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T max_value(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T))  BOOST_MATH_NOEXCEPT(T)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   BOOST_STATIC_ASSERT( ::std::numeric_limits<T>::is_specialized);\n#else\n   BOOST_ASSERT(::std::numeric_limits<T>::is_specialized);\n#endif\n   return (std::numeric_limits<T>::max)();\n} // Also used as a finite 'infinite' value for - and +infinity, for example:\n// -max_value<double> = -1.79769e+308, max_value<double> = 1.79769e+308.\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T min_value(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   BOOST_STATIC_ASSERT( ::std::numeric_limits<T>::is_specialized);\n#else\n   BOOST_ASSERT(::std::numeric_limits<T>::is_specialized);\n#endif\n   return (std::numeric_limits<T>::min)();\n}\n\nnamespace detail{\n//\n// Logarithmic limits come next, note that although\n// we can compute these from the log of the max value\n// that is not in general thread safe (if we cache the value)\n// so it's better to specialise these:\n//\n// For type float first:\n//\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T log_max_value(const boost::integral_constant<int, 128>& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T)\n{\n   return 88.0f;\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T log_min_value(const boost::integral_constant<int, 128>& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T)\n{\n   return -87.0f;\n}\n//\n// Now double:\n//\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T log_max_value(const boost::integral_constant<int, 1024>& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T)\n{\n   return 709.0;\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T log_min_value(const boost::integral_constant<int, 1024>& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T)\n{\n   return -708.0;\n}\n//\n// 80 and 128-bit long doubles:\n//\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T log_max_value(const boost::integral_constant<int, 16384>& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T)\n{\n   return 11356.0L;\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T log_min_value(const boost::integral_constant<int, 16384>& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T)\n{\n   return -11355.0L;\n}\n\ntemplate <class T>\ninline T log_max_value(const boost::integral_constant<int, 0>& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T))\n{\n   BOOST_MATH_STD_USING\n#ifdef __SUNPRO_CC\n   static const T m = boost::math::tools::max_value<T>();\n   static const T val = log(m);\n#else\n   static const T val = log(boost::math::tools::max_value<T>());\n#endif\n   return val;\n}\n\ntemplate <class T>\ninline T log_min_value(const boost::integral_constant<int, 0>& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T))\n{\n   BOOST_MATH_STD_USING\n#ifdef __SUNPRO_CC\n   static const T m = boost::math::tools::min_value<T>();\n   static const T val = log(m);\n#else\n   static const T val = log(boost::math::tools::min_value<T>());\n#endif\n   return val;\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T epsilon(const boost::true_type& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T)\n{\n   return std::numeric_limits<T>::epsilon();\n}\n\n#if defined(__GNUC__) && ((LDBL_MANT_DIG == 106) || (__LDBL_MANT_DIG__ == 106))\ntemplate <>\ninline BOOST_MATH_CONSTEXPR long double epsilon<long double>(const boost::true_type& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(long double)) BOOST_MATH_NOEXCEPT(long double)\n{\n   // numeric_limits on Darwin (and elsewhere) tells lies here:\n   // the issue is that long double on a few platforms is\n   // really a \"double double\" which has a non-contiguous\n   // mantissa: 53 bits followed by an unspecified number of\n   // zero bits, followed by 53 more bits.  Thus the apparent\n   // precision of the type varies depending where it's been.\n   // Set epsilon to the value that a 106 bit fixed mantissa\n   // type would have, as that will give us sensible behaviour everywhere.\n   //\n   // This static assert fails for some unknown reason, so\n   // disabled for now...\n   // BOOST_STATIC_ASSERT(std::numeric_limits<long double>::digits == 106);\n   return 2.4651903288156618919116517665087e-32L;\n}\n#endif\n\ntemplate <class T>\ninline T epsilon(const boost::false_type& BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(T))\n{\n   // Note: don't cache result as precision may vary at runtime:\n   BOOST_MATH_STD_USING  // for ADL of std names\n   return ldexp(static_cast<T>(1), 1-policies::digits<T, policies::policy<> >());\n}\n\ntemplate <class T>\nstruct log_limit_traits\n{\n   typedef typename mpl::if_c<\n      (std::numeric_limits<T>::radix == 2) &&\n      (std::numeric_limits<T>::max_exponent == 128\n         || std::numeric_limits<T>::max_exponent == 1024\n         || std::numeric_limits<T>::max_exponent == 16384),\n      boost::integral_constant<int, (std::numeric_limits<T>::max_exponent > INT_MAX ? INT_MAX : static_cast<int>(std::numeric_limits<T>::max_exponent))>,\n      boost::integral_constant<int, 0>\n   >::type tag_type;\n   BOOST_STATIC_CONSTANT(bool, value = tag_type::value ? true : false);\n   BOOST_STATIC_ASSERT(::std::numeric_limits<T>::is_specialized || (value == 0));\n};\n\ntemplate <class T, bool b> struct log_limit_noexcept_traits_imp : public log_limit_traits<T> {};\ntemplate <class T> struct log_limit_noexcept_traits_imp<T, false> : public boost::integral_constant<bool, false> {};\n\ntemplate <class T>\nstruct log_limit_noexcept_traits : public log_limit_noexcept_traits_imp<T, BOOST_MATH_IS_FLOAT(T)> {};\n\n} // namespace detail\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4309)\n#endif\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T log_max_value(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_NOEXCEPT_IF(detail::log_limit_noexcept_traits<T>::value)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   return detail::log_max_value<T>(typename detail::log_limit_traits<T>::tag_type());\n#else\n   BOOST_ASSERT(::std::numeric_limits<T>::is_specialized);\n   BOOST_MATH_STD_USING\n   static const T val = log((std::numeric_limits<T>::max)());\n   return val;\n#endif\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T log_min_value(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_NOEXCEPT_IF(detail::log_limit_noexcept_traits<T>::value)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   return detail::log_min_value<T>(typename detail::log_limit_traits<T>::tag_type());\n#else\n   BOOST_ASSERT(::std::numeric_limits<T>::is_specialized);\n   BOOST_MATH_STD_USING\n   static const T val = log((std::numeric_limits<T>::min)());\n   return val;\n#endif\n}\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T epsilon(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(T)) BOOST_MATH_NOEXCEPT(T)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   return detail::epsilon<T>(boost::integral_constant<bool, ::std::numeric_limits<T>::is_specialized>());\n#else\n   return ::std::numeric_limits<T>::is_specialized ?\n      detail::epsilon<T>(boost::true_type()) :\n      detail::epsilon<T>(boost::false_type());\n#endif\n}\n\nnamespace detail{\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T root_epsilon_imp(const boost::integral_constant<int, 24>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.00034526698300124390839884978618400831996329879769945L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T root_epsilon_imp(const T*, const boost::integral_constant<int, 53>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.1490116119384765625e-7L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T root_epsilon_imp(const T*, const boost::integral_constant<int, 64>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.32927225399135962333569506281281311031656150598474e-9L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T root_epsilon_imp(const T*, const boost::integral_constant<int, 113>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.1387778780781445675529539585113525390625e-16L);\n}\n\ntemplate <class T, class Tag>\ninline T root_epsilon_imp(const T*, const Tag&)\n{\n   BOOST_MATH_STD_USING\n   static const T r_eps = sqrt(tools::epsilon<T>());\n   return r_eps;\n}\n\ntemplate <class T>\ninline T root_epsilon_imp(const T*, const boost::integral_constant<int, 0>&)\n{\n   BOOST_MATH_STD_USING\n   return sqrt(tools::epsilon<T>());\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T cbrt_epsilon_imp(const boost::integral_constant<int, 24>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.0049215666011518482998719164346805794944150447839903L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T cbrt_epsilon_imp(const T*, const boost::integral_constant<int, 53>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(6.05545445239333906078989272793696693569753008995e-6L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T cbrt_epsilon_imp(const T*, const boost::integral_constant<int, 64>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(4.76837158203125e-7L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T cbrt_epsilon_imp(const T*, const boost::integral_constant<int, 113>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(5.7749313854154005630396773604745549542403508090496e-12L);\n}\n\ntemplate <class T, class Tag>\ninline T cbrt_epsilon_imp(const T*, const Tag&)\n{\n   BOOST_MATH_STD_USING;\n   static const T cbrt_eps = pow(tools::epsilon<T>(), T(1) / 3);\n   return cbrt_eps;\n}\n\ntemplate <class T>\ninline T cbrt_epsilon_imp(const T*, const boost::integral_constant<int, 0>&)\n{\n   BOOST_MATH_STD_USING;\n   return pow(tools::epsilon<T>(), T(1) / 3);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T forth_root_epsilon_imp(const T*, const boost::integral_constant<int, 24>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.018581361171917516667460937040007436176452688944747L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T forth_root_epsilon_imp(const T*, const boost::integral_constant<int, 53>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.0001220703125L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T forth_root_epsilon_imp(const T*, const boost::integral_constant<int, 64>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.18145860519450699870567321328132261891067079047605e-4L);\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T forth_root_epsilon_imp(const T*, const boost::integral_constant<int, 113>&) BOOST_MATH_NOEXCEPT(T)\n{\n   return static_cast<T>(0.37252902984619140625e-8L);\n}\n\ntemplate <class T, class Tag>\ninline T forth_root_epsilon_imp(const T*, const Tag&)\n{\n   BOOST_MATH_STD_USING\n   static const T r_eps = sqrt(sqrt(tools::epsilon<T>()));\n   return r_eps;\n}\n\ntemplate <class T>\ninline T forth_root_epsilon_imp(const T*, const boost::integral_constant<int, 0>&)\n{\n   BOOST_MATH_STD_USING\n   return sqrt(sqrt(tools::epsilon<T>()));\n}\n\ntemplate <class T>\nstruct root_epsilon_traits\n{\n   typedef boost::integral_constant<int, (::std::numeric_limits<T>::radix == 2) && (::std::numeric_limits<T>::digits != INT_MAX) ? std::numeric_limits<T>::digits : 0> tag_type;\n   BOOST_STATIC_CONSTANT(bool, has_noexcept = (tag_type::value == 113) || (tag_type::value == 64) || (tag_type::value == 53) || (tag_type::value == 24));\n};\n\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T root_epsilon() BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && detail::root_epsilon_traits<T>::has_noexcept)\n{\n   return detail::root_epsilon_imp(static_cast<T const*>(0), typename detail::root_epsilon_traits<T>::tag_type());\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T cbrt_epsilon() BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && detail::root_epsilon_traits<T>::has_noexcept)\n{\n   return detail::cbrt_epsilon_imp(static_cast<T const*>(0), typename detail::root_epsilon_traits<T>::tag_type());\n}\n\ntemplate <class T>\ninline BOOST_MATH_CONSTEXPR T forth_root_epsilon() BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && detail::root_epsilon_traits<T>::has_noexcept)\n{\n   return detail::forth_root_epsilon_imp(static_cast<T const*>(0), typename detail::root_epsilon_traits<T>::tag_type());\n}\n\n} // namespace tools\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_TOOLS_PRECISION_INCLUDED\n\n", "meta": {"hexsha": "73757295d219ec4f5e114ce7ea2892f11bad06f9", "size": 14133, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/math/tools/precision.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": "3rdparty/boost_1_73_0/boost/math/tools/precision.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/boost/math/tools/precision.hpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T14:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T07:53:36.000Z", "avg_line_length": 34.4707317073, "max_line_length": 176, "alphanum_fraction": 0.7599235831, "num_tokens": 3689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1920988917628936}}
{"text": "// D3DDlg.cpp : implementation file\n//\n\n#include \"pch.h\"\n#include \"FaceMorph.h\"\n#include \"DxDlg.h\" \n#include \"vertex.h\" \n#include \"FileHandle.h\" \n\n \n//#include <iostream>\n//#include <Eigen/Dense>\nconst int LINE_BUFF_SIZE = 4096;\n// CDxWnd \n\nIMPLEMENT_DYNAMIC(CDxWnd, CWnd)\n\nCDxWnd::CDxWnd()\n{\n\tm_nNumVertices = 0;\n\tm_bWireframe = false;\n\tm_pVB = nullptr;\n\tm_pIB = nullptr;\n\tg_hWnd = NULL;\n\tg_hMainDlg = NULL;\n\tg_pD3D = nullptr;\n\tg_pD3DDevice = nullptr;\n\tg_pTexture = nullptr;\n\tg_fScale = 1.0f;\n\tm_pVertexPNTDecl = nullptr;\n\tg_pEffect = nullptr;\n\tm_pFaceMesh = nullptr;\n\tm_hTech = NULL;\n\tm_hWVP = NULL;\n\tm_hWorldInvTrans = NULL;\n\tm_hLightVecW = NULL;\n\tm_hDiffuseMtrl = NULL;\n\tm_hDiffuseLight = NULL;\n\tm_hAmbientMtrl = NULL;\n\tm_hAmbientLight = NULL;\n\tm_hSpecularMtrl = NULL;\n\tm_hSpecularLight = NULL;\n\tm_hSpecularPower = NULL;\n\tm_hEyePos = NULL;\n\tm_hWorld = NULL;\n\tm_hTex = NULL;\n\tm_LightVecW = D3DXVECTOR3(0.0, 0.8f, 1.0f);\n\n\tD3DXVec3Normalize(&m_LightVecW, &m_LightVecW);\n\t \n\tm_DiffuseMtrl = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);\n\tm_DiffuseLight = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);\n\tm_AmbientMtrl = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);\n\tm_AmbientLight = D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f);\n\tm_SpecularMtrl = D3DXCOLOR(0.8f, 0.8f, 0.8f, 1.0f);\n\tm_SpecularLight = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);\n\tm_SpecularPower = 8.0f;\n}\n//---------------------------------------------------------------//\nCDxWnd::~CDxWnd()\n{\n\tShutDown();\n} \n//---------------------------------------------------------------//\nBEGIN_MESSAGE_MAP(CDxWnd, CWnd)\n\tON_WM_TIMER()\nEND_MESSAGE_MAP()\n//---------------------------------------------------------------//\n// CDxWnd message handlers\nbool CDxWnd::Initialize(CWnd* pParent)\n{ \n\tbool bResult = SUCCEEDED(InitD3D());\n\tif (bResult)\n\t{ \n\t\tInitAllVertexDeclarations(g_pD3DDevice);  \n\t\t{\n\t\t\tHRESULT hr = S_OK;\n\t\t\tif (m_pVB == nullptr)\n\t\t\t{\n\t\t\t\thr = g_pD3DDevice->CreateVertexBuffer((UINT)m_nNumVertices * sizeof(VertexPNT), D3DUSAGE_WRITEONLY, 0, D3DPOOL_MANAGED, &m_pVB, 0);\n\t\t\t}\n\t\t\tif (m_pIB == nullptr)\n\t\t\t{\n\t\t\t\thr = g_pD3DDevice->CreateIndexBuffer((UINT)m_vIndices.size() * sizeof(DWORD), D3DUSAGE_WRITEONLY, D3DFMT_INDEX32, D3DPOOL_MANAGED, &m_pIB, 0);\n\t\t\t}\n\t\t\tCEigenValues c;//default mesh to mean mesh only i.e. all eigenvalues set to zero)\n\t\t\tRecalcMesh(c);\n\t\t}\n\t}\n\telse\n\t{\n\t\tATLASSERT(!L\"InitD3D failed\");\n\t}\n\treturn bResult;\n}  \n//---------------------------------------------------------------//\nvoid CDxWnd::OnTimer(UINT_PTR nIDEvent)\n{ \n\tCWnd::OnTimer(nIDEvent);\n}\n//---------------------------------------------------------------//\nvoid CDxWnd::RecalcMesh(CEigenValues& e)\n{\n\tif (m_nNumVertices == 0) return;\n\tint nNumVerticesXYZ = m_nNumVertices * 3;\n\t//the following could be vectorized with Intel IPP, but seems to run fast enough\n\tfor (int j = 0; j < nNumVerticesXYZ; j++)\n\t{\n\t\tfloat r = m_AveFace[j] / 8.0f;\n\t\tfor (int h = 0; h < NUM_EIGENS; h++)\n\t\t{\n\t\t\tr = r + e.m_Next[h] * m_Eigen[h][j];\n\t\t}\n\t\tm_Mesh[j] = r;\n\t}\n\t \n\tif (m_pVB && m_pIB)\n\t{\n\t\tVertexPNT* v = 0;\n\t\tHRESULT hr = m_pVB->Lock(0, 0, (void**)&v, 0); \n\t\tfor (int j = 0; j < m_nNumVertices; j++)\n\t\t{\n\t\t\tfloat x = m_Mesh[j];\n\t\t\tfloat y = m_Mesh[m_nNumVertices + j];\n\t\t\tfloat z = m_Mesh[2 * m_nNumVertices + j];\n\t\t\tv[j] = VertexPNT(x, y, z, 0, 0, 0, 0, 0);\n\t\t}\n\t\t{\n\t\t\tDWORD* k = 0;\n\t\t\tHRESULT hr = m_pIB->Lock(0, 0, (void**)&k, 0);\n\t\t\tsize_t nNumTriangles = m_vIndices.size();\n\t\t\tfor (int j = 0; j < nNumTriangles; j++)\n\t\t\t{\n\t\t\t\tk[j] = m_vIndices[j];\n\t\t\t}\n\n\t\t\t//compute normals (or at least approximate them)\n\t\t\tfor (int j = 0; j < nNumTriangles; j++)\n\t\t\t{ \n\t\t\t\tif (j > 1 && j < nNumTriangles - 2)\n\t\t\t\t{\t\n\t\t\t\t\tint vip = k[j - 1];//prev\n\t\t\t\t\tint vic = k[j];//current\t\t\t\t\t\n\t\t\t\t\tint vin = k[j + 1];//next \n\t\t\t\t\tD3DXVECTOR3 va = v[vip].pos;\n\t\t\t\t\tD3DXVECTOR3 vb = v[vic].pos;\n\t\t\t\t\tD3DXVECTOR3 vc = v[vin].pos;\n\t\t\t\t\tD3DXVECTOR3 cross;\n\t\t\t\t\tD3DXVECTOR3 vc1 = vb - va;\n\t\t\t\t\tD3DXVECTOR3 vc2 = vc - va;\n\t\t\t\t\tD3DXVec3Cross(&cross, &vc1, &vc2);\n\t\t\t\t\tD3DXVec3Normalize(&cross, &cross);  \n\t\t\t\t\tv[vip].normal = cross;\n\t\t\t\t\tv[vic].normal = cross;\n\t\t\t\t\tv[vin].normal = cross;\n\t\t\t\t}\n\t\t\t}\n\t\t\thr = m_pIB->Unlock();\n\t\t}\n\t\thr = m_pVB->Unlock();\n\t}\n}\n//---------------------------------------------------------------//\nvoid CDxWnd::Render()\n{\n\tif (g_pD3DDevice == 0) return;\n\n\tHRESULT hr = S_OK;\n\t  \n\tif (FAILED(g_pD3DDevice->BeginScene()))\n\t\treturn;\n \n\tg_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 170, 50), 1.0f, 0);\n\tg_pD3DDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);\n\t// Draw the background gradient.\n\tRECT rClient;\n\tGetClientRect(&rClient);\n \n\tD3DXCOLOR c1(0.2f, 0.2f, 0.2f, 1.0f);\n\tD3DXCOLOR c2(0.45f, 0.45f, 0.45f, 1.0f);\n\tg_pD3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);\n\tDrawTransformedQuad(g_pD3DDevice, -0.5f, -0.5f, 0.f,\n\t\t(FLOAT)(rClient.right - rClient.left),\n\t\t(FLOAT)(rClient.bottom - rClient.top),\n\t\tc1, c1, c2, c2);\n\tg_pD3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);\n\t \n\tg_pD3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);\n\tif (m_bWireframe)\n\t{\n\t\tg_pD3DDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);\n\t}\n\n\tD3DXMatrixIdentity(&m_World);\n\tD3DXVECTOR3 vEye(0, 0, 10);\n\tfloat nRenderFOV = 12.59f;\n\tD3DXMatrixLookAtLH(&m_View, &vEye, &(D3DXVECTOR3(0, 0, 0)), &(D3DXVECTOR3(0, 1, 0)));\n\tD3DXMatrixPerspectiveFovLH(&m_Proj, nRenderFOV, 1, 1, 50);\n\n\tm_WVP = m_World * m_View * m_Proj;\n\tD3DXMATRIX WI;\n\tD3DXMatrixInverse(&WI, NULL, &m_World);\n\tD3DXMatrixTranspose(&m_WIT, &WI);\n\thr = g_pEffect->SetTechnique(m_hTech); \n\t \n\thr = g_pD3DDevice->SetVertexDeclaration( VertexPNT::Decl);\n\tUINT numPasses = 0;\n \n\thr = g_pEffect->Begin(&numPasses, 0);\n\tfor (UINT k = 0; k < numPasses; ++k)\n\t{\n\t\thr = g_pEffect->BeginPass(k);\n\t\thr = g_pEffect->SetMatrix(m_hWorldInvTrans, &m_WIT);\n\t\thr = g_pEffect->SetMatrix(m_hWVP, &m_WVP);\n\t\thr = g_pEffect->SetValue(m_hLightVecW, &m_LightVecW, sizeof(D3DXVECTOR3));\n\t\thr = g_pEffect->SetValue(m_hDiffuseMtrl, &m_DiffuseMtrl, sizeof(D3DXCOLOR));\n\t\thr = g_pEffect->SetValue(m_hDiffuseLight, &m_DiffuseLight, sizeof(D3DXCOLOR));\n\t\thr = g_pEffect->SetValue(m_hAmbientMtrl, &m_AmbientMtrl, sizeof(D3DXCOLOR));\n\t\thr = g_pEffect->SetValue(m_hAmbientLight, &m_AmbientLight, sizeof(D3DXCOLOR));\n\t\thr = g_pEffect->SetValue(m_hSpecularLight, &m_SpecularLight, sizeof(D3DXCOLOR));\n\t\thr = g_pEffect->SetValue(m_hSpecularMtrl, &m_SpecularMtrl, sizeof(D3DXCOLOR));\n\t\thr = g_pEffect->SetFloat(m_hSpecularPower, m_SpecularPower);\n\t\thr = g_pEffect->SetMatrix(m_hWorld, &m_World);\n\t\thr = g_pEffect->SetTexture(m_hTex, g_pTexture);\n\t\thr = g_pEffect->SetValue(m_hEyePos, &vEye, sizeof(D3DXVECTOR3));\n\t\tg_pEffect->CommitChanges();\n\t\thr = g_pD3DDevice->SetStreamSource(0, m_pVB, 0, sizeof(VertexPNT));\n\t\thr = g_pD3DDevice->SetIndices(m_pIB);\t\t \n\t\thr = g_pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_nNumVertices, 0, (UINT)m_vIndices.size() / 3);\n\t\tif (FAILED(hr))\n\t\t{\n\t\t\tATLASSERT(0);\n\t\t}\n\t\thr = g_pEffect->EndPass();\n\t} \n\tg_pD3DDevice->EndScene();\n\tg_pD3DDevice->Present(NULL, NULL, NULL, NULL);\n}\n//---------------------------------------------------------------//\n// Initialize Direct3D stuff.\nHRESULT CDxWnd::InitD3D()\n{\n\tHRESULT hr;\n\n\tg_pD3D = Direct3DCreate9(D3D_SDK_VERSION);\n\n\tif (!g_pD3D)\n\t\treturn E_FAIL;\n\n\tD3DDISPLAYMODE d3ddm;\n\n\tg_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm);\n\n\tD3DPRESENT_PARAMETERS d3dpp;\n\tZeroMemory(&d3dpp, sizeof(d3dpp));\n\n\td3dpp.Windowed = TRUE;\n\td3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;\n\td3dpp.BackBufferFormat = d3ddm.Format;\n\td3dpp.EnableAutoDepthStencil = TRUE;\n\td3dpp.AutoDepthStencilFormat = D3DFMT_D16;\n\td3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // v-sync on - No need to burn the CPU and GPU over nothing.\n\td3dpp.hDeviceWindow = m_hWnd;\n\n\tif (FAILED(hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,\n\t\tm_hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_pD3DDevice)))\n\t\treturn hr;\n\n\treturn OnCreateDevice();\n}\n//---------------------------------------------------------------//\n// This is called after the device has been created.\nHRESULT CDxWnd::OnCreateDevice()\n{\n\tHRESULT hr;\n\tCString strFileName;\n\tTCHAR szFilePath[MAX_PATH + _ATL_QUOTES_SPACE];\n\tDWORD dwFLen = ::GetModuleFileName(NULL, szFilePath + 0, MAX_PATH);\n\tif (dwFLen == 0 || dwFLen == MAX_PATH)\n\t{\n\t\tATLASSERT(0);\n\t\treturn E_FAIL;\n\t}\n\telse\n\t{\n\t\tstrFileName = CString(szFilePath);\n\t\tbool bFoundFX = false;\n\t\tint nNumAttempts = 0;\n\t\t//search for the .fx file. Might be better to embed it as a resource\n\t\twhile (!bFoundFX && nNumAttempts < 3)\n\t\t{\n\t\t\tlong nRight = strFileName.ReverseFind(_T('\\\\'));//move one folder up\n\t\t\tstrFileName = strFileName.Left(nRight);\n\t\t\tnNumAttempts++;\n\t\t\tif (CFileHelper::DoesFileExist(strFileName + L\"\\\\FaceMorph.fx\")) {\n\t\t\t\tbFoundFX = true;\n\t\t\t\tstrFileName.Append(L\"\\\\FaceMorph.fx\");\n\t\t\t}\n\t\t\telse if (CFileHelper::DoesFileExist(strFileName + L\"\\\\FaceMorph\\\\FaceMorph.fx\")) {\n\t\t\t\tbFoundFX = true;\n\t\t\t\tstrFileName.Append(L\"\\\\FaceMorph\\\\FaceMorph.fx\");\n\t\t\t}\n\t\t} \n\t}\n\t// Load the effect from file.\n\tLPD3DXBUFFER pErrors = NULL;\n\thr = D3DXCreateEffectFromFile(g_pD3DDevice, strFileName, NULL, NULL, 0, NULL, &g_pEffect, &pErrors);\n\tif (FAILED(hr))\n\t{\n\t\tif (pErrors)\n\t\t{\n\t\t\tCA2T tErrors = (char*)pErrors->GetBufferPointer();\n\t\t\tAfxMessageBox((LPCTSTR)tErrors, MB_OK | MB_ICONSTOP);\n\t\t\tpErrors->Release();\n\t\t}\n\t\treturn hr;\n\t}\n\tstrFileName.Replace(_T(\"FaceMorph.fx\"), _T(\"texture.png\"));\n\thr = D3DXCreateTextureFromFile(g_pD3DDevice, strFileName, &g_pTexture);\n\t \n\tm_hTech\t\t\t\t= g_pEffect->GetTechniqueByName(\"DirLightTexTech\");\n\tm_hWVP\t\t\t\t= g_pEffect->GetParameterByName(0, \"gWVP\");\n\tm_hWorldInvTrans\t= g_pEffect->GetParameterByName(0, \"gWorldInvTrans\");\n\tm_hLightVecW\t\t= g_pEffect->GetParameterByName(0, \"gLightVecW\");\n\tm_hDiffuseMtrl\t\t= g_pEffect->GetParameterByName(0, \"gDiffuseMtrl\");\n\tm_hDiffuseLight\t\t= g_pEffect->GetParameterByName(0, \"gDiffuseLight\");\n\tm_hAmbientMtrl\t\t= g_pEffect->GetParameterByName(0, \"gAmbientMtrl\");\n\tm_hAmbientLight\t\t= g_pEffect->GetParameterByName(0, \"gAmbientLight\");\n\tm_hSpecularMtrl\t\t= g_pEffect->GetParameterByName(0, \"gSpecularMtrl\");\n\tm_hSpecularLight\t= g_pEffect->GetParameterByName(0, \"gSpecularLight\");\n\tm_hSpecularPower\t= g_pEffect->GetParameterByName(0, \"gSpecularPower\");\n\tm_hEyePos\t\t\t= g_pEffect->GetParameterByName(0, \"gEyePosW\");\n\tm_hWorld\t\t\t= g_pEffect->GetParameterByName(0, \"gWorld\");\n\tm_hTex\t\t\t\t= g_pEffect->GetParameterByName(0, \"gTex\");\n\n\tD3DVERTEXELEMENT9 VertexPNTElements[] =\n\t{\n\t\t{0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},\n\t\t{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},\n\t\t{0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},\n\t\tD3DDECL_END()\n\t};\n\thr = g_pD3DDevice->CreateVertexDeclaration(VertexPNTElements, &m_pVertexPNTDecl);\n\n\n\treturn S_OK;\n}\n//---------------------------------------------------------------//\nvoid CDxWnd::ShutDown()\n{\n\tSAFE_RELEASE(g_pTexture); \n\n\tSAFE_RELEASE(g_pEffect);\n\tSAFE_RELEASE(m_pFaceMesh);\n\tSAFE_RELEASE(m_pVB);\n\tSAFE_RELEASE(m_pIB);\n\t\n\tSAFE_RELEASE(g_pD3DDevice);\n\tSAFE_RELEASE(g_pD3D);\n}\n//---------------------------------------------------------------//\nHRESULT CDxWnd::DrawTransformedQuad(LPDIRECT3DDEVICE9 pDevice,\n\tFLOAT x, FLOAT y, FLOAT z,\n\tFLOAT width, FLOAT height,\n\tD3DCOLOR c1,\n\tD3DCOLOR c2,\n\tD3DCOLOR c3,\n\tD3DCOLOR c4)\n{\n\treturn DrawTransformedQuad(pDevice, x, y, z, width, height,\n\t\tD3DXVECTOR2(0, 0), D3DXVECTOR2(1, 0), D3DXVECTOR2(0, 1), D3DXVECTOR2(1, 1),\n\t\tc1, c2, c3, c4);\n}\n//---------------------------------------------------------------//\nHRESULT CDxWnd::DrawTransformedQuad(LPDIRECT3DDEVICE9 pDevice,\n\tFLOAT x, FLOAT y, FLOAT z,\n\tFLOAT width, FLOAT height,\n\tD3DXVECTOR2 uvTopLeft, D3DXVECTOR2 uvTopRight,\n\tD3DXVECTOR2 uvBottomLeft, D3DXVECTOR2 uvBottomRight,\n\tD3DCOLOR c1, D3DCOLOR c2, D3DCOLOR c3, D3DCOLOR c4)\n{\n\tstruct\n\t{\n\t\tfloat pos[4];\n\t\tD3DCOLOR color;\n\t\tfloat uv[2];\n\t} quad[] =\n\t{\n\t\tx,\t\t\ty,\t\t\t\tz, 1.f,\t\tc1, uvTopLeft.x,\t\tuvTopLeft.y,\n\t\tx + width,\ty,\t\t\t\tz, 1.f,\t\tc2, uvBottomRight.x,\tuvTopLeft.y,\n\t\tx,\t\t\ty + height,\t\tz, 1.f,\t\tc3, uvTopLeft.x,\t\tuvBottomRight.y,\n\t\tx + width,\ty + height,\t\tz, 1.f,\t\tc4, uvBottomRight.x,\tuvBottomRight.y,\n\t};\n\tpDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0));\n\treturn pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(quad[0]));\n}\n//---------------------------------------------------------------//", "meta": {"hexsha": "e8ac4fa4dafe309e602d6ee9bd71a43d8af76218", "size": 12333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FaceMorph/DxDlg.cpp", "max_stars_repo_name": "nodecomplete/3DMM-Face-Sample", "max_stars_repo_head_hexsha": "fc9584e32674477097eae1520207c0166d797ce3", "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": "FaceMorph/DxDlg.cpp", "max_issues_repo_name": "nodecomplete/3DMM-Face-Sample", "max_issues_repo_head_hexsha": "fc9584e32674477097eae1520207c0166d797ce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FaceMorph/DxDlg.cpp", "max_forks_repo_name": "nodecomplete/3DMM-Face-Sample", "max_forks_repo_head_hexsha": "fc9584e32674477097eae1520207c0166d797ce3", "max_forks_repo_licenses": ["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.0654911839, "max_line_length": 146, "alphanum_fraction": 0.6529635936, "num_tokens": 4337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19209889176289358}}
{"text": "#include \"Expression.h\"\n#include \"mapnikvt/StringUtils.h\"\n\n#include <stdexcept>\n#include <utility>\n\n#include <boost/lexical_cast.hpp>\n\nnamespace {\n    using carto::css::Color;\n    using carto::css::Value;\n\n    struct NotOp {\n        Value operator() (bool val) const { return Value(!val); }\n        template <typename T> Value operator() (T val) const { throw std::invalid_argument(\"Unexpected type in ! operator\"); }\n    };\n    \n    struct NegOp {\n        Value operator() (long long val) const { return Value(-val); }\n        Value operator() (double val) const { return Value(-val); }\n        template <typename T> Value operator() (T val) const { throw std::invalid_argument(\"Unexpected type in - operator\"); }\n    };\n\n    struct AndOp {\n        Value operator() (bool val1, bool val2) const { return Value(val1 && val2); }\n        template <typename S, typename T> Value operator() (S val1, T val2) const { throw std::invalid_argument(\"Unexpected types in binary && operator\"); }\n    };\n\n    struct OrOp {\n        Value operator() (bool val1, bool val2) const { return Value(val1 || val2); }\n        template <typename S, typename T> Value operator() (S val1, T val2) const { throw std::invalid_argument(\"Unexpected types in binary || operator\"); }\n    };\n\n    template <template <typename> class OpImpl, bool NullResult, bool MismatchResult>\n    struct CompOp  {\n        Value operator() (std::monostate, std::monostate) const { return Value(NullResult); }\n        Value operator() (bool val1, long long val2) const { return Value(OpImpl<long long>()(static_cast<long long>(val1), val2)); }\n        Value operator() (bool val1, double val2) const { return Value(OpImpl<double>()(static_cast<double>(val1), val2)); }\n        Value operator() (long long val1, bool val2) const { return Value(OpImpl<long long>()(val1, static_cast<long long>(val2))); }\n        Value operator() (long long val1, double val2) const { return Value(OpImpl<double>()(static_cast<double>(val1), val2)); }\n        Value operator() (double val1, bool val2) const { return Value(OpImpl<double>()(val1, static_cast<double>(val2))); }\n        Value operator() (double val1, long long val2) const { return Value(OpImpl<double>()(val1, static_cast<double>(val2))); }\n        template <typename T> Value operator() (T val1, T val2) const { return Value(OpImpl<T>()(val1, val2)); }\n        template <typename S, typename T> Value operator() (S val1, T val2) const { return Value(MismatchResult); }\n    };\n\n    struct MatchOp {\n        Value operator() (const std::string& val1, const std::string& val2) const { return Value(carto::mvt::regexMatch(val1, val2)); }\n        template <typename S, typename T> Value operator() (S val1, T val2) const { return Value(false); }\n    };\n\n    struct AddOp {\n        Value operator() (const std::string& val1, const std::string& val2) const { return Value(val1 + val2); }\n        Value operator() (const std::string& val1, std::monostate) const { return Value(val1); }\n        Value operator() (std::monostate, const std::string& val2) const { return Value(val2); }\n        template <typename T> Value operator() (const std::string& val1, T val2) const { return Value(val1 + boost::lexical_cast<std::string>(val2)); }\n        template <typename S> Value operator() (S val1, const std::string& val2) const { return Value(boost::lexical_cast<std::string>(val1) + val2); }\n        Value operator() (long long val1, long long val2) const { return Value(val1 + val2); }\n        Value operator() (long long val1, double val2) const { return Value(static_cast<double>(val1) + val2); }\n        Value operator() (double val1, long long val2) const { return Value(val1 + static_cast<double>(val2)); }\n        Value operator() (double val1, double val2) const { return Value(val1 + val2); }\n        Value operator() (Color val1, Color val2) const { return Value(val1 + val2); }\n        template <typename S, typename T> Value operator() (S val1, T val2) const { throw std::invalid_argument(\"Unexpected types in binary + operator\"); }\n    };\n\n    struct SubOp {\n        Value operator() (long long val1, long long val2) const { return Value(val1 - val2); }\n        Value operator() (long long val1, double val2) const { return Value(static_cast<double>(val1) - val2); }\n        Value operator() (double val1, long long val2) const { return Value(val1 - static_cast<double>(val2)); }\n        Value operator() (double val1, double val2) const { return Value(val1 - val2); }\n        Value operator() (Color val1, Color val2) const { return Value(val1 - val2); }\n        template <typename S, typename T> Value operator() (S val1, T val2) const { throw std::invalid_argument(\"Unexpected types in binary - operator\"); }\n    };\n\n    struct MulOp {\n        Value operator() (long long val1, long long val2) const { return Value(val1 * val2); }\n        Value operator() (long long val1, double val2) const { return Value(static_cast<double>(val1) * val2); }\n        Value operator() (double val1, long long val2) const { return Value(val1 * static_cast<double>(val2)); }\n        Value operator() (double val1, double val2) const { return Value(val1 * val2); }\n        Value operator() (Color val1, Color val2) const { return Value(val1 * val2); }\n        Value operator() (Color val1, long long val2) const { return Value(val1 * static_cast<float>(val2)); }\n        Value operator() (Color val1, double val2) const { return Value(val1 * static_cast<float>(val2)); }\n        Value operator() (long long val1, Color val2) const { return Value(static_cast<float>(val1) * val2); }\n        Value operator() (double val1, Color val2) const { return Value(static_cast<float>(val1) * val2); }\n        template <typename S, typename T> Value operator() (S val1, T val2) const { throw std::invalid_argument(\"Unexpected types in binary * operator\"); }\n    };\n\n    struct DivOp {\n        Value operator() (long long val1, long long val2) const { return val2 == 0 ? Value() : Value(static_cast<double>(val1) / static_cast<double>(val2)); }\n        Value operator() (long long val1, double val2) const { return Value(static_cast<double>(val1) / val2); }\n        Value operator() (double val1, long long val2) const { return Value(val1 / static_cast<double>(val2)); }\n        Value operator() (double val1, double val2) const { return Value(val1 / val2); }\n        Value operator() (Color val1, Color val2) const { return Value(val1 / val2); }\n        Value operator() (Color val1, long long val2) const { return Value(val1 * (1.0f / static_cast<float>(val2))); }\n        Value operator() (Color val1, double val2) const { return Value(val1 * (1.0f / static_cast<float>(val2))); }\n        template <typename S, typename T> Value operator() (S val1, T val2) const { throw std::invalid_argument(\"Unexpected types in binary / operator\"); }\n    };\n}\n\nnamespace carto { namespace css {\n    Value UnaryExpression::applyOp(Op op, const Value& val) {\n        switch (op) {\n        case Op::NOT:\n            return std::visit(NotOp(), val);\n        case Op::NEG:\n            return std::visit(NegOp(), val);\n        }\n        throw std::invalid_argument(\"Unsupported unary operation\");\n    }\n\n    Value BinaryExpression::applyOp(Op op, const Value& val1, const Value& val2) {\n        switch (op) {\n        case Op::AND:\n            return std::visit(AndOp(), val1, val2);\n        case Op::OR:\n            return std::visit(OrOp(), val1, val2);\n        case Op::EQ:\n            return std::visit(CompOp<std::equal_to, true, false>(), val1, val2);\n        case Op::NEQ:\n            return std::visit(CompOp<std::not_equal_to, false, true>(), val1, val2);\n        case Op::LT:\n            return std::visit(CompOp<std::less, false, false>(), val1, val2);\n        case Op::LTE:\n            return std::visit(CompOp<std::less_equal, true, false>(), val1, val2);\n        case Op::GT:\n            return std::visit(CompOp<std::greater, false, false>(), val1, val2);\n        case Op::GTE:\n            return std::visit(CompOp<std::greater_equal, true, false>(), val1, val2);\n        case Op::MATCH:\n            return std::visit(MatchOp(), val1, val2);\n        case Op::ADD:\n            return std::visit(AddOp(), val1, val2);\n        case Op::SUB:\n            return std::visit(SubOp(), val1, val2);\n        case Op::MUL:\n            return std::visit(MulOp(), val1, val2);\n        case Op::DIV:\n            return std::visit(DivOp(), val1, val2);\n        }\n        throw std::invalid_argument(\"Unsupported binary operation\");\n    }\n\n    Value FunctionExpression::applyFunc(const std::string& func, const std::vector<Value>& vals) {\n        if (func == \"url\" && vals.size() == 1) {\n            return Value(getString(vals[0]));\n        }\n        else if (func == \"rgb\" && vals.size() == 3) {\n            std::array<float, 3> components;\n            std::transform(vals.begin(), vals.end(), components.begin(), [](const Value& val) { return getFloat(val) / 255.0f; });\n            Color color = Color::fromRGBA(components[0], components[1], components[2], 1.0f);\n            return Value(color);\n        }\n        else if (func == \"rgba\" && vals.size() == 4) {\n            std::array<float, 4> components;\n            std::transform(vals.begin(), vals.begin() + 3, components.begin(), [](const Value& val) { return getFloat(val) / 255.0f; });\n            components[3] = getFloat(vals[3]);\n            Color color = Color::fromRGBA(components[0], components[1], components[2], components[3]);\n            return Value(color);\n        }\n        else if (func == \"mix\" && vals.size() == 3) {\n            Color color = Color::mix(getColor(vals[0]), getColor(vals[1]), getFloat(vals[2]));\n            return Value(color);\n        }\n        else if (func == \"lighten\" && vals.size() == 2) {\n            Color color = Color::lighten(getColor(vals[0]), getFloat(vals[1]));\n            return Value(color);\n        }\n        else if (func == \"darken\" && vals.size() == 2) {\n            Color color = Color::lighten(getColor(vals[0]), -getFloat(vals[1]));\n            return Value(color);\n        }\n        else if (func == \"saturate\" && vals.size() == 2) {\n            Color color = Color::saturate(getColor(vals[0]), getFloat(vals[1]));\n            return Value(color);\n        }\n        else if (func == \"desaturate\" && vals.size() == 2) {\n            Color color = Color::saturate(getColor(vals[0]), -getFloat(vals[1]));\n            return Value(color);\n        }\n        else if (func == \"fadein\" && vals.size() == 2) {\n            Color color = Color::fade(getColor(vals[0]), getFloat(vals[1]));\n            return Value(color);\n        }\n        else if (func == \"fadeout\" && vals.size() == 2) {\n            Color color = Color::fade(getColor(vals[0]), -getFloat(vals[1]));\n            return Value(color);\n        }\n        return Value();\n    }\n\n    Color FunctionExpression::getColor(const Value& value) {\n        if (auto colorVal = std::get_if<Color>(&value)) {\n            return *colorVal;\n        }\n        throw std::invalid_argument(\"Wrong type, expecting color\");\n    }\n    \n    float FunctionExpression::getFloat(const Value& value) {\n        if (auto longVal = std::get_if<long long>(&value)) {\n            return static_cast<float>(*longVal);\n        }\n        else if (auto doubleVal = std::get_if<double>(&value)) {\n            return static_cast<float>(*doubleVal);\n        }\n        throw std::invalid_argument(\"Wrong type, expecting float\");\n    }\n\n    std::string FunctionExpression::getString(const Value& value) {\n        if (auto strVal = std::get_if<std::string>(&value)) {\n            return *strVal;\n        }\n        throw std::invalid_argument(\"Wrong type, expecting string\");\n    }\n} }\n", "meta": {"hexsha": "310510424809378d4923c5675862286c3d6749ad", "size": 11671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cartocss/src/cartocss/Expression.cpp", "max_stars_repo_name": "farfromrefug/mobile-carto-libs", "max_stars_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "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": "cartocss/src/cartocss/Expression.cpp", "max_issues_repo_name": "farfromrefug/mobile-carto-libs", "max_issues_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "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": "cartocss/src/cartocss/Expression.cpp", "max_forks_repo_name": "farfromrefug/mobile-carto-libs", "max_forks_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "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": 54.2837209302, "max_line_length": 158, "alphanum_fraction": 0.6074029646, "num_tokens": 3013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.19202966684547867}}
{"text": "#include \"shape_reconstruction/ShapeRecPlotter.h\"\n\n#include <pcl/conversions.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/filter_indices.h>\n#include <sensor_msgs/Image.h>\n\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/video/tracking.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/video/tracking.hpp>\n\n#include <pcl_conversions/pcl_conversions.h>\n\n#include <ros/package.h>\n\n#include <cmath>\n\n#include <ros/console.h>\n\n#include \"shape_reconstruction/RangeImagePlanar.hpp\"\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/filters/passthrough.h>\n\n#include <boost/filesystem.hpp>\n#include <ctime>\n\n#include <std_msgs/Bool.h>\n\n#include <iostream>\n#include <pcl/common/common.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/ply_io.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/features/normal_3d_omp.h>\n#include <pcl/point_types.h>\n#include <pcl/surface/mls.h>\n#include <pcl/surface/poisson.h>\n#include <pcl/surface/marching_cubes.h>\n#include <pcl/surface/marching_cubes_rbf.h>\n#include <pcl/surface/marching_cubes_hoppe.h>\n#include <pcl/surface/ear_clipping.h>\n#include <pcl/surface/vtk_smoothing/vtk_mesh_smoothing_laplacian.h>\n#include <pcl/surface/vtk_smoothing/vtk_mesh_smoothing_windowed_sinc.h>\n#include <pcl/surface/vtk_smoothing/vtk_mesh_subdivision.h>\n#include <pcl/filters/passthrough.h>\n\n#include <pcl/io/vtk_lib_io.h>\n#include <pcl/visualization/pcl_visualizer.h>\n\n\n#include <vcg/complex/complex.h> //class UpdateCurvature\n#include <vcg/complex/all_types.h>     //class UpdateNormals\n#include <vcg/complex/algorithms/clean.h> //class UpdateCurvature\n\n#include <vcg/complex/algorithms/update/bounding.h> //class UpdateCurvature\n#include <vcg/complex/algorithms/update/normal.h> //class UpdateCurvature\n#include <vcg/complex/algorithms/update/topology.h> //class UpdateCurvature\n\n#include <pcl/surface/convex_hull.h>\n#include <pcl/surface/concave_hull.h>\n\n#include <pcl/filters/normal_refinement.h>\n\n#include <pcl/surface/simplification_remove_unused_vertices.h>\n\n#include <sensor_msgs/PointCloud2.h>\n#include <geometry_msgs/TransformStamped.h>\n\n#include <pcl_ros/transforms.h>\n\n\nusing namespace omip;\n\nShapeRecPlotter::ShapeRecPlotter()\n{\n    std::string topic_name = std::string(\"\");\n    //this->_node_handle.getParam(\"/surface_smoother/topic_name\", topic_name);\n    ROS_INFO_STREAM_NAMED(\"ShapeRecPlotter\",\"topic_name: \" << topic_name);\n    this->_pc_subscriber = this->_node_handle.subscribe(topic_name, 1,\n                                                        &ShapeRecPlotter::InputPCmeasurementCallback, this);\n\n    std::string topic_name2 = std::string(\"moved_pc\");\n    this->_pc_publisher = this->_node_handle.advertise<sensor_msgs::PointCloud2>(topic_name2,10, true);\n\n    this->_current_pc.reset(new SRPointCloud());\n\n\n\n    _tf_listener = new tf::TransformListener();\n\n}\n\nShapeRecPlotter::~ShapeRecPlotter()\n{\n}\n\nvoid ShapeRecPlotter::plotShape()\n{\n    if(_current_pc->size())\n    {\n    sensor_msgs::PointCloud2 pc2, pcout;\n\n    pcl::toROSMsg(*this->_current_pc, pc2);\n\n    _tf_listener->waitForTransform(\"/camera_rgb_optical_frame\", \"/ip/rb2\", ros::Time(0), ros::Duration(0.1));\n\n    bool nooo = false;\n    tf::StampedTransform tfTransform;\n    try{\n\n    _tf_listener->lookupTransform (\"/camera_rgb_optical_frame\", \"/ip/rb2\",ros::Time(0), tfTransform);\n\n    }catch(...){\n        nooo = true;\n        std::cout << \".\" << std::endl ;\n    }\n\n    if(!nooo)\n    {\n        std::cout << std::endl ;\n    Eigen::Matrix4f transform;\n    transform(0,0) = tfTransform.getBasis()[0][0];\n    transform(0,1) = tfTransform.getBasis()[0][1];\n    transform(0,2) = tfTransform.getBasis()[0][2];\n    transform(1,0) = tfTransform.getBasis()[1][0];\n    transform(1,1) = tfTransform.getBasis()[1][1];\n    transform(1,2) = tfTransform.getBasis()[1][2];\n    transform(2,0) = tfTransform.getBasis()[2][0];\n    transform(2,1) = tfTransform.getBasis()[2][1];\n    transform(2,2) = tfTransform.getBasis()[2][2];\n    transform(0,3) = tfTransform.getOrigin()[0];\n    transform(1,3) = tfTransform.getOrigin()[1];\n    transform(2,3) = tfTransform.getOrigin()[2];\n    transform(3,0) = 0;\n    transform(3,1) = 0;\n    transform(3,2) = 0;\n    transform(3,3) = 1;\n\n    std::cout << transform << std::endl;\n    pcl_ros::transformPointCloud(transform, pc2, pcout);\n\n    _pc_publisher.publish(pcout);\n    }else{\n        std::cout << std::endl ;\n    Eigen::Matrix4f transform;\n    transform(0,0) = 1;\n    transform(0,1) = 0;\n    transform(0,2) = 0;\n    transform(1,0) = 0;\n    transform(1,1) = 1;\n    transform(1,2) = 0;\n    transform(2,0) = 0;\n    transform(2,1) = 0;\n    transform(2,2) = 1;\n    transform(0,3) = 0;\n    transform(1,3) = 0;\n    transform(2,3) = 0;\n    transform(3,0) = 0;\n    transform(3,1) = 0;\n    transform(3,2) = 0;\n    transform(3,3) = 1;\n    pcl_ros::transformPointCloud(transform, pc2, pcout);\n\n    _pc_publisher.publish(pcout);\n    }\n    }\n\n}\n\nvoid ShapeRecPlotter::InputPCmeasurementCallback(const sensor_msgs::PointCloud2ConstPtr &pc_msg)\n{\n    std::cout << \"received\" << std::endl;\n    // Convert ROS PC message into a pcl point cloud\n    pcl::fromROSMsg(*pc_msg, *this->_current_pc);\n\n}\n\n// Main program\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"ShapeRecPlotter\");\n    ShapeRecPlotter sr_node;\n\n    ros::Rate r(30); // 10 hz\n    while (ros::ok())\n    {\n        ros::spinOnce();\n        sr_node.plotShape();\n        r.sleep();\n    }\n\n    std::cout << \" Shutting down ShapeRecPlotter \" << std::endl;\n\n    return (0);\n}\n", "meta": {"hexsha": "136c5b6bd60fefaadea76e5aa3c0f90ce85aca68", "size": 5571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shape_reconstruction/src/ShapeRecPlotter.cpp", "max_stars_repo_name": "tu-rbo/omip", "max_stars_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-11-10T16:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T20:11:39.000Z", "max_issues_repo_path": "shape_reconstruction/src/ShapeRecPlotter.cpp", "max_issues_repo_name": "tu-rbo/omip", "max_issues_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-28T13:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T22:01:58.000Z", "max_forks_repo_path": "shape_reconstruction/src/ShapeRecPlotter.cpp", "max_forks_repo_name": "tu-rbo/omip", "max_forks_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-11-25T18:24:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T03:20:33.000Z", "avg_line_length": 27.7164179104, "max_line_length": 109, "alphanum_fraction": 0.6853347693, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.19202966684547865}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef cell_caller_hpp\n#define cell_caller_hpp\n\n#include <vector>\n#include <string>\n#include <memory>\n#include <functional>\n\n#include <boost/optional.hpp>\n\n#include \"config/common.hpp\"\n#include \"basics/phred.hpp\"\n#include \"core/types/haplotype.hpp\"\n#include \"core/types/genotype.hpp\"\n#include \"core/models/mutation/coalescent_model.hpp\"\n#include \"core/models/genotype/genotype_prior_model.hpp\"\n#include \"core/models/genotype/single_cell_model.hpp\"\n#include \"caller.hpp\"\n\nnamespace octopus {\n\nclass GenomicRegion;\nclass ReadPipe;\nclass Variant;\nclass HaplotypeLikelihoodArray;\nclass VariantCall;\n\nclass CellCaller : public Caller\n{\npublic:\n    using Caller::CallTypeSet;\n    \n    struct Parameters\n    {\n        unsigned ploidy;\n        boost::optional<CoalescentModel::Parameters> prior_model_params;\n        Phred<double> min_variant_posterior, min_refcall_posterior;\n        bool deduplicate_haplotypes_with_prior_model = false;\n        unsigned max_clones;\n        unsigned max_genotypes, max_joint_genotypes;\n        double dropout_concentration;\n        DeNovoModel::Parameters mutation_model_parameters;\n        boost::optional<unsigned> max_vb_seeds = boost::none; // Use default if none\n    };\n    \n    CellCaller() = delete;\n    \n    CellCaller(Caller::Components&& components,\n               Caller::Parameters general_parameters,\n               Parameters specific_parameters);\n    \n    CellCaller(const CellCaller&)            = delete;\n    CellCaller& operator=(const CellCaller&) = delete;\n    CellCaller(CellCaller&&)                 = delete;\n    CellCaller& operator=(CellCaller&&)      = delete;\n    \n    ~CellCaller() = default;\n\nprivate:\n    class Latents;\n    friend Latents;\n    \n    Parameters parameters_;\n    \n    std::string do_name() const override;\n    CallTypeSet do_call_types() const override;\n    unsigned do_min_callable_ploidy() const override;\n    unsigned do_max_callable_ploidy() const override;\n    \n    std::size_t do_remove_duplicates(std::vector<Haplotype>& haplotypes) const override;\n    \n    std::unique_ptr<Caller::Latents>\n    infer_latents(const std::vector<Haplotype>& haplotypes,\n                  const HaplotypeLikelihoodArray& haplotype_likelihoods) const override;\n    \n    boost::optional<double>\n    calculate_model_posterior(const std::vector<Haplotype>& haplotypes,\n                              const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                              const Caller::Latents& latents) const override;\n    \n    boost::optional<double>\n    calculate_model_posterior(const std::vector<Haplotype>& haplotypes,\n                              const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                              const Latents& latents) const;\n    \n    std::vector<std::unique_ptr<VariantCall>>\n    call_variants(const std::vector<Variant>& candidates, const Caller::Latents& latents) const override;\n    \n    std::vector<std::unique_ptr<VariantCall>>\n    call_variants(const std::vector<Variant>& candidates, const Latents& latents) const;\n    \n    std::vector<std::unique_ptr<ReferenceCall>>\n    call_reference(const std::vector<Allele>& alleles, const Caller::Latents& latents,\n                   const ReadPileupMap& pileup) const override;\n    \n    std::vector<std::unique_ptr<ReferenceCall>>\n    call_reference(const std::vector<Allele>& alleles, const Latents& latents,\n                   const ReadPileupMap& pileup) const;\n    \n    std::unique_ptr<GenotypePriorModel> make_prior_model(const std::vector<Haplotype>& haplotypes) const;\n};\n\nclass CellCaller::Latents : public Caller::Latents\n{\npublic:\n    using Caller::Latents::HaplotypeProbabilityMap;\n    using Caller::Latents::GenotypeProbabilityMap;\n    \n    Latents() = delete;\n    \n    Latents(const CellCaller& caller,\n            std::vector<Haplotype> haplotypes,\n            std::vector<Genotype<Haplotype>> genotypes,\n            std::vector<model::SingleCellModel::Inferences> inferences);\n    \n    std::shared_ptr<HaplotypeProbabilityMap> haplotype_posteriors() const noexcept override;\n    std::shared_ptr<GenotypeProbabilityMap> genotype_posteriors() const noexcept override;\n\nprivate:\n    mutable std::shared_ptr<GenotypeProbabilityMap> genotype_posteriors_;\n    mutable std::shared_ptr<HaplotypeProbabilityMap> haplotype_posteriors_;\n    \n    const CellCaller& caller_;\n    std::vector<Haplotype> haplotypes_;\n    std::vector<Genotype<Haplotype>> genotypes_;\n    std::vector<model::SingleCellModel::Inferences> phylogeny_inferences_;\n    std::vector<double> phylogeny_posteriors_;\n    \n    friend CellCaller;\n};\n\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "85a8d8698c8f2d843b5e81120305f0e485574ab6", "size": 4750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/callers/cell_caller.hpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "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/callers/cell_caller.hpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/callers/cell_caller.hpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.4202898551, "max_line_length": 105, "alphanum_fraction": 0.7046315789, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1920296618342123}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <ctime>\n#include <stdlib.h>\n#include <time.h> \n#include <algorithm>\n#include <deque>\n#include <unordered_set>\n#include <math.h>\n//PCL\n#include <pcl/common/transforms.h>\n#include <pcl/ModelCoefficients.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/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/filters/impl/passthrough.hpp>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/features/normal_3d.h> \n\n#include <pcl/visualization/impl/point_cloud_geometry_handlers.hpp>//\u81ea\u5b9a\u4e49\u70b9\u4e91\u7c7b\u578b\u65f6\u8981\u52a0\n\n//Eigen\n#include <Eigen/Dense>\n#include <queue> \n\n#include <unordered_map>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/imgproc.hpp>\n\n//ROS\n#include <ros/ros.h>\n#include <pcl_ros/transforms.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <cv_bridge/cv_bridge.h> \n#include <image_transport/image_transport.h>\n#include <sensor_msgs/Image.h>\n\n\nusing namespace std;\n\n#include \"jpc_groundremove.h\"\n\nint get_quadrant(pcl::PointXYZI point)\n{\n\tint res = 0;\n\tfloat x = point.x;\n\tfloat y = point.y;\n\tif (x > 0 && y >= 0)\n\t\tres = 1;\n\telse if (x <= 0 && y > 0)\n\t\tres = 2;\n\telse if (x < 0 && y <= 0)\n\t\tres = 3;\n\telse if (x >= 0 && y < 0)\n\t\tres = 4;\n\treturn res;\n}\n\n\n\nvoid add_ring_info(pcl::PointCloud<pcl::PointXYZI>& input, pcl::PointCloud<PointXYZIR>& output)\n{\n\tint previous_quadrant = 0;\n\tuint16_t ring_ = (uint16_t)64-1;\n\tfor (pcl::PointCloud<pcl::PointXYZI>::iterator pt = input.points.begin(); pt < input.points.end()-1; ++pt){\n\t\tint quadrant = get_quadrant(*pt);\n\t\tif (quadrant == 1 && previous_quadrant == 4 && ring_ > 0)\n\t\t\tring_ -= 1;\n\t\tPointXYZIR point;\n\t\tpoint.x = pt->x;\n\t\tpoint.y = pt->y;\n\t\tpoint.z = pt->z;\n\t\tpoint.intensity = pt->intensity;\n\t\tpoint.ring = ring_;\n\t\toutput.push_back(point);\n\t\tprevious_quadrant = quadrant;\n\t}\n}\n\n\nclass SubscribeAndPublish {\npublic:\n\tSubscribeAndPublish(ros::NodeHandle nh, std::string lidar_topic_name);\n\n\n\t~SubscribeAndPublish(){\n\t}\n\n\tvoid callback(const sensor_msgs::PointCloud2ConstPtr& cloudmsg) {\n\n\t\tpcl::PointCloud<pcl::PointXYZI>::Ptr cloud(\n\t\t\tnew pcl::PointCloud<pcl::PointXYZI>);\n\n   \t\tpcl::fromROSMsg(*cloudmsg, *cloud);\n\n\t\tpcl::PointCloud<PointXYZIR>::Ptr cloud_ring(new pcl::PointCloud<PointXYZIR>);\n\t\tadd_ring_info(*cloud, *cloud_ring);\n\n\t\tROS_INFO(\"Reciving data!\");\n\n\t\tpcl::PointCloud<PointXYZIR>::Ptr cloud_gr(new pcl::PointCloud<PointXYZIR>);\n\t\tpcl::PointCloud<PointXYZIR>::Ptr cloud_ob(new pcl::PointCloud<PointXYZIR>);\n\t\tcv::Mat range_image;\n\n\t\tJpcGroundRemove groundremove;\n\t\tgroundremove.GroundRemove(*cloud_ring, *cloud_gr, *cloud_ob, range_image);\n\t\tROS_INFO(\"segmentation\");\n\n\t\tsensor_msgs::ImagePtr imgmsg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\",range_image).toImageMsg(); \n\t\tpubimage_.publish(imgmsg);\n\n\t\tsensor_msgs::PointCloud2 ros_cloud2;\n\t\tpcl::toROSMsg(*cloud_gr, ros_cloud2);\n\t\tros_cloud2.header.frame_id = \"global_init_frame\";\n\t\tpub_.publish(ros_cloud2);\n\n\t\tsensor_msgs::PointCloud2 ros_cloud3;\n\t\tpcl::toROSMsg(*cloud_ob, ros_cloud3);\n\t\tros_cloud3.header.frame_id = \"global_init_frame\";\n\t\tpub2_.publish(ros_cloud3);\n\n\t}\nprivate:\n\tros::NodeHandle n_;\n\tros::Publisher pub_;\n\tros::Publisher pub2_;\n\tros::Subscriber sub_;\n  \timage_transport::Publisher pubimage_; \n};\n\nSubscribeAndPublish::SubscribeAndPublish(ros::NodeHandle nh,\n\t\tstd::string lidar_topic_name) :\n\t\tn_(nh){\n\n\tpub_  = nh.advertise < sensor_msgs::PointCloud2 > (\"/ground_point\", 1);\n\tpub2_ = nh.advertise < sensor_msgs::PointCloud2 > (\"/obstacle_point\", 1);\n\tsub_ = nh.subscribe(lidar_topic_name, 10, &SubscribeAndPublish::callback, this);\n  \timage_transport::ImageTransport it(nh);\n\tpubimage_ = it.advertise(\"/seg_image\", 1);\n}\n\n\n\nint main(int argc, char** argv){\n\n \tros::init(argc, argv, \"jpc_seg_node\");\n\tSubscribeAndPublish SAPObject(ros::NodeHandle(), \"pointcloud\");\n\tROS_INFO(\"waiting for data!\");\n\tros::spin();\n\treturn 0;\n}\n", "meta": {"hexsha": "2ffa3e093fd6f3a9c6805cf0fa69323423bf6cff", "size": 4064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jpc_seg/src/kitti_topic_main.cpp", "max_stars_repo_name": "wangx1996/Fast-Ground-Segmentation-for-Pointcloud-Based-on-JPC", "max_stars_repo_head_hexsha": "0b4dc317db79197078e78a741b499c5042cdb7df", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2021-09-22T02:10:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:04:14.000Z", "max_issues_repo_path": "jpc_seg/src/kitti_topic_main.cpp", "max_issues_repo_name": "wangx1996/Fast-Ground-Segmentation-for-Pointcloud-Based-on-JPC", "max_issues_repo_head_hexsha": "0b4dc317db79197078e78a741b499c5042cdb7df", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-10-09T12:18:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-05T11:18:36.000Z", "max_forks_repo_path": "jpc_seg/src/kitti_topic_main.cpp", "max_forks_repo_name": "wangx1996/Fast-Ground-Segmentation-for-Pointcloud-Based-on-JPC", "max_forks_repo_head_hexsha": "0b4dc317db79197078e78a741b499c5042cdb7df", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T13:36:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T14:39:30.000Z", "avg_line_length": 25.5597484277, "max_line_length": 108, "alphanum_fraction": 0.7217027559, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1920296618342123}}
{"text": "#include <iostream>\n#include <sstream>\n#include <sys/resource.h>\n#include <thread>\n#include <algorithm>\n//#include <boost/asio/thread_pool.hpp>\n//#include <boost/asio/post.hpp>\n//#include <boost/bind.hpp>\n#include <mutex>\n#include \"emissionprobabilitycomputer.hpp\"\n#include \"copynumber.hpp\"\n#include \"variantreader.hpp\"\n#include \"uniquekmercomputer.hpp\"\n#include \"hmm.hpp\"\n#include \"commandlineparser.hpp\"\n#include \"timer.hpp\"\n#include \"threadpool.hpp\"\n#include <cassert>\n\nusing namespace std;\n\n// TODO\n/** version of the main algorithm that uses only path information for genotyping and ignores kmers **/\n\nstruct Results {\n\tmutex result_mutex;\n\tmap<string, vector<GenotypingResult>> result;\n\tmap<string, double> runtimes;\n};\n\nvoid run_genotyping_paths(string chromosome, KmerCounter* genomic_kmer_counts, KmerCounter* read_kmer_counts, VariantReader* variant_reader, ProbabilityTable* probs, size_t kmer_abundance_peak, bool only_genotyping, bool only_phasing, long double effective_N, Results* results) {\n\tTimer timer;\n\t// determine sets of kmers unique to each variant region\n\tUniqueKmerComputer kmer_computer(genomic_kmer_counts, read_kmer_counts, variant_reader, chromosome, kmer_abundance_peak);\n\tstd::vector<UniqueKmers*> unique_kmers;\n\tkmer_computer.compute_empty(&unique_kmers);\n\t// construct HMM and run genotyping/phasing\n\tHMM hmm(&unique_kmers, probs, !only_phasing, !only_genotyping, 1.26, false, effective_N);\n\t// store the results\n\t{\n\t\tlock_guard<mutex> lock (results->result_mutex);\n\t\tresults->result.insert(pair<string, vector<GenotypingResult>> (chromosome, move(hmm.get_genotyping_result())));\n\t}\n\t// destroy unique kmers\n\tfor (size_t i = 0; i < unique_kmers.size(); ++i) {\n\t\tdelete unique_kmers[i];\n\t\tunique_kmers[i] = nullptr;\n\t}\n\tlock_guard<mutex> lock (results->result_mutex);\n\tresults->runtimes.insert(pair<string,double>(chromosome, timer.get_total_time()));\n}\n\nint main (int argc, char* argv[])\n{\n\tTimer timer;\n\tdouble time_preprocessing;\n\tdouble time_writing;\n\tdouble time_total;\n\n\tcerr << endl;\n\tcerr << \"program: PanGenie-paths - genotyping and phasing based on known haplotype paths.\" << endl;\n\tcerr << \"author: Jana Ebler\" << endl << endl;\n\tstring reffile = \"\";\n\tstring vcffile = \"\";\n\tstring outname = \"result\";\n\tstring sample_name = \"sample\";\n\tsize_t nr_core_threads = 1;\n\tbool only_genotyping = false;\n\tbool only_phasing = false;\n\tdouble effective_N = 0.00001L;\n\tbool add_reference = true;\n\n\t// parse the command line arguments\n\tCommandLineParser argument_parser;\n\targument_parser.add_command(\"PanGenie-paths [options] -r <reference.fa> -v <variants.vcf>\");\n\targument_parser.add_mandatory_argument('r', \"reference genome in FASTA format\");\n\targument_parser.add_mandatory_argument('v', \"variants in VCF format\");\n\targument_parser.add_optional_argument('o', \"result\", \"prefix of the output files\");\n\targument_parser.add_optional_argument('s', \"sample\", \"name of the sample (will be used in the output VCFs)\");\n\targument_parser.add_optional_argument('t', \"1\", \"number of threads to use for core algorithm. Largest number of threads possible is the number of chromosomes given in the VCF\");\n\targument_parser.add_optional_argument('n', \"0.00001\", \"effective population size\");\n\targument_parser.add_flag_argument('g', \"only run genotyping (Forward backward algorithm)\");\n\targument_parser.add_flag_argument('p', \"only run phasing (Viterbi algorithm)\");\n\targument_parser.add_flag_argument('d', \"do not add reference as additional path.\");\n\n\ttry {\n\t\targument_parser.parse(argc, argv);\n\t} catch (const runtime_error& e) {\n\t\targument_parser.usage();\n\t\tcerr << e.what() << endl;\n\t\treturn 1;\n\t} catch (const exception& e) {\n\t\treturn 0;\n\t}\n\treffile = argument_parser.get_argument('r');\n\tvcffile = argument_parser.get_argument('v');\n\toutname = argument_parser.get_argument('o');\n\tsample_name = argument_parser.get_argument('s');\n\tnr_core_threads = stoi(argument_parser.get_argument('t'));\n\tonly_genotyping = argument_parser.get_flag('g');\n\tonly_phasing = argument_parser.get_flag('p');\n\teffective_N = stold(argument_parser.get_argument('n'));\n\tadd_reference = !argument_parser.get_flag('d');\n\n\t// print info\n\tcerr << \"Files and parameters used:\" << endl;\n\targument_parser.info();\n\n\t// read allele sequences and unitigs inbetween, write them into file\n\tcerr << \"Determine allele sequences ...\" << endl;\n\tVariantReader variant_reader (vcffile, reffile, 31, add_reference, sample_name);\n\n\t// determine chromosomes present in VCF\n\tvector<string> chromosomes;\n\tvariant_reader.get_chromosomes(&chromosomes);\n\tcerr << \"Found \" << chromosomes.size() << \" chromosome(s) in the VCF.\" << endl;\n\n\t// TODO: only for analysis\n\tstruct rusage r_usage0;\n\tgetrusage(RUSAGE_SELF, &r_usage0);\n\tcerr << \"#### Memory usage until now: \" << (r_usage0.ru_maxrss / 1E6) << \" GB ####\" << endl;\n\n\t// prepare output files\n\tif (! only_phasing) variant_reader.open_genotyping_outfile(outname + \"_genotyping.vcf\");\n\tif (! only_genotyping) variant_reader.open_phasing_outfile(outname + \"_phasing.vcf\");\n\n\ttime_preprocessing = timer.get_interval_time();\n\n\tcerr << \"Construct HMM and run core algorithm ...\" << endl;\n\tProbabilityTable probabilities;\n\n\t// determine max number of available threads (at most one thread per chromosome possible)\n\tsize_t available_threads = min(thread::hardware_concurrency(), (unsigned int) chromosomes.size());\n\tif (nr_core_threads > available_threads) {\n\t\tcerr << \"Warning: set nr_core_threads to \" << available_threads << \".\" << endl;\n\t\tnr_core_threads = available_threads;\n\t}\n\tResults results;\n\t{\n\t\t// create thread pool\n\t\tThreadPool threadPool (nr_core_threads);\n\t\tfor (auto chromosome : chromosomes) {\n\t\t\tKmerCounter* genomic = nullptr;\n\t\t\tVariantReader* variants = &variant_reader;\n\t\t\tResults* r = &results;\n\t\t\tProbabilityTable* probs = &probabilities;\n\t\t\tfunction<void()> f_genotyping = bind(run_genotyping_paths, chromosome, genomic, nullptr, variants, probs, 28, only_genotyping, only_phasing, effective_N, r);\n\t\t\tthreadPool.submit(f_genotyping);\n\t\t}\n\t}\n\n/**\tboost::asio::thread_pool threadPool(nr_core_threads);\n\tfor (auto chromosome : chromosomes) {\n\t\tboost::asio::post(threadPool, boost::bind(run_genotyping_paths, chromosome, nullptr, nullptr, &variant_reader, 28, only_genotyping, only_phasing, effective_N, &results));\n\t} \n\tthreadPool.join();\n**/\n\ttimer.get_interval_time();\n\n\t// output VCF\n\tcerr << \"Write results to VCF ...\" << endl;\n\tassert (results.result.size() == chromosomes.size());\n\t// write VCF\n\tfor (auto it = results.result.begin(); it != results.result.end(); ++it) {\n\t\tif (!only_phasing) {\n\t\t\t// output genotyping results\n\t\t\tvariant_reader.write_genotypes_of(it->first, it->second);\n\t\t}\n\t\tif (!only_genotyping) {\n\t\t\t// output phasing results\n\t\t\tvariant_reader.write_phasing_of(it->first, it->second);\n\t\t}\n\t}\n\n\tif (! only_phasing) variant_reader.close_genotyping_outfile();\n\tif (! only_genotyping) variant_reader.close_phasing_outfile();\n\n\ttime_writing = timer.get_interval_time();\n\ttime_total = timer.get_total_time();\n\n\tcerr << endl << \"###### Summary ######\" << endl;\n\t// output times\n\tcerr << \"time spent reading input files:\\t\" << time_preprocessing << \" sec\" << endl;\n\t// output per chromosome time\n\tdouble time_hmm = time_writing;\n\tfor (auto chromosome : chromosomes) {\n\t\tdouble time_chrom = results.runtimes.at(chromosome);\n\t\tcerr << \"time spent genotyping chromosome \" << chromosome << \":\\t\" << time_chrom << endl;\n\t\ttime_hmm += time_chrom;\n\t}\n\tcerr << \"total running time:\\t\" << time_preprocessing + time_hmm << \" sec\"<< endl;\n\tcerr << \"total wallclock time: \" << time_total  << \" sec\" << endl;\n\n\t// memory usage\n\tstruct rusage r_usage;\n\tgetrusage(RUSAGE_SELF, &r_usage);\n\tcerr << \"Total maximum memory usage: \" << (r_usage.ru_maxrss / 1E6) << \" GB\" << endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "f0a76a9162dd0883cce6b2af9db17b70ee55c10f", "size": 7726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pggtyper-paths.cpp", "max_stars_repo_name": "ASLeonard/pangenie", "max_stars_repo_head_hexsha": "aeb0c2aa28bf69041755855306d32f5523371274", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:49:01.000Z", "max_issues_repo_path": "src/pggtyper-paths.cpp", "max_issues_repo_name": "ASLeonard/pangenie", "max_issues_repo_head_hexsha": "aeb0c2aa28bf69041755855306d32f5523371274", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-09T15:28:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T10:12:50.000Z", "max_forks_repo_path": "src/pggtyper-paths.cpp", "max_forks_repo_name": "ASLeonard/pangenie", "max_forks_repo_head_hexsha": "aeb0c2aa28bf69041755855306d32f5523371274", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T09:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T09:56:36.000Z", "avg_line_length": 38.2475247525, "max_line_length": 279, "alphanum_fraction": 0.7346621797, "num_tokens": 1924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19202965429805816}}
{"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// 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_GEOMETRY_HPP\n#define BOOST_GEOMETRY_GEOMETRY_HPP\n\n// Shortcut to include all header files\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/tag.hpp>\n#include <boost/geometry/core/tag_cast.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n// Core algorithms\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/topological_dimension.hpp>\n\n\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/algorithms/append.hpp>\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/algorithms/buffer.hpp>\n#include <boost/geometry/algorithms/centroid.hpp>\n#include <boost/geometry/algorithms/clear.hpp>\n#include <boost/geometry/algorithms/comparable_distance.hpp>\n#include <boost/geometry/algorithms/convert.hpp>\n#include <boost/geometry/algorithms/convex_hull.hpp>\n#include <boost/geometry/algorithms/correct.hpp>\n#include <boost/geometry/algorithms/covered_by.hpp>\n#include <boost/geometry/algorithms/difference.hpp>\n#include <boost/geometry/algorithms/disjoint.hpp>\n#include <boost/geometry/algorithms/distance.hpp>\n#include <boost/geometry/algorithms/envelope.hpp>\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/algorithms/expand.hpp>\n#include <boost/geometry/algorithms/for_each.hpp>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/algorithms/intersects.hpp>\n#include <boost/geometry/algorithms/length.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/num_geometries.hpp>\n#include <boost/geometry/algorithms/num_interior_rings.hpp>\n#include <boost/geometry/algorithms/num_points.hpp>\n#include <boost/geometry/algorithms/overlaps.hpp>\n#include <boost/geometry/algorithms/perimeter.hpp>\n#include <boost/geometry/algorithms/reverse.hpp>\n#include <boost/geometry/algorithms/simplify.hpp>\n#include <boost/geometry/algorithms/sym_difference.hpp>\n#include <boost/geometry/algorithms/touches.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/algorithms/union.hpp>\n#include <boost/geometry/algorithms/unique.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n\n// Include multi a.o. because it can give weird effects\n// if you don't (e.g. area=0 of a multipolygon)\n#include <boost/geometry/multi/multi.hpp>\n\n// check includes all concepts\n#include <boost/geometry/geometries/concepts/check.hpp>\n\n#include <boost/geometry/util/for_each_coordinate.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n#include <boost/geometry/io/dsv/write.hpp>\n\n#include <boost/geometry/views/box_view.hpp>\n#include <boost/geometry/views/segment_view.hpp>\n\n#include <boost/geometry/io/io.hpp>\n#include <boost/geometry/io/svg/svg_mapper.hpp>\n\n#endif // BOOST_GEOMETRY_GEOMETRY_HPP\n", "meta": {"hexsha": "dce17e260c9d4bfb75cc9fcc6190e448615a65d7", "size": 3755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "venv/bin/boost/geometry/geometry.hpp", "max_stars_repo_name": "NixaSoftware/CVis", "max_stars_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_stars_repo_licenses": ["Apache-2.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": "venv/bin/boost/geometry/geometry.hpp", "max_issues_repo_name": "NixaSoftware/CVis", "max_issues_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_issues_repo_licenses": ["Apache-2.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": "venv/bin/boost/geometry/geometry.hpp", "max_forks_repo_name": "NixaSoftware/CVis", "max_forks_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_forks_repo_licenses": ["Apache-2.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": 40.376344086, "max_line_length": 79, "alphanum_fraction": 0.8010652463, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.19196658319933493}}
{"text": "#pragma once\n\n/** STL */\n#include <algorithm>\n#include <vector>\n\n/** Third Party */\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/unordered_map.hpp>\n#include <boost/serialization/unordered_set.hpp>\n#include <boost/serialization/utility.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n\n/** Ligero */\n#include \"Common.hpp\"\n#include \"Hash.hpp\"\n#include \"Math.hpp\"\n#include \"MerkleTree.hpp\"\n#include \"SecretSharingNTT.hpp\"\n#include \"Transport.hpp\"\n\n#include \"protocol/Builder.hpp\"\n#include \"protocol/Constraint.hpp\"\n#include \"protocol/ConstraintSystem.hpp\"\n#include \"protocol/ExpressNPStatement.hpp\"\n\n/**\n * ==============================================================================\n */\n/** ZKSnark Definitions */\n#define OPEN_COLUMNS 2\n\n#define STATE_UPDATE_LINEAR_COMBOS 1\n#define STATE_UPDATE_OPEN_COLS 2\n\n#define TEST_INTERLEAVED 0\n#define TEST_LINEAR_INTERBLOC_CONSTRAINTS 1\n#define TEST_LINEAR_INTRABLOC_CONSTRAINTS 2\n#define TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS 3\n#define TEST_QUADRATIC_CONSTRAINTS 4\n#define OPEN_COLUMNS 5\n\nstd::vector<std::string> testDescription = {\n    \"TEST_INTERLEAVED\",\n    \"TEST_LINEAR_INTERBLOC_CONSTRAINTS\",\n    \"TEST_LINEAR_INTRABLOC_CONSTRAINTS\",\n    \"TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS\",\n    \"TEST_QUADRATIC_CONSTRAINTS\",\n    \"OPEN_COLUMNS\"};\n\nconstexpr size_t numberOfRounds = 1;\nconstexpr size_t numberOfIterations = 3;\nconstexpr uint8_t nbBlindingRows = 6;\n\n/** These are the offset for the location various blinding rows from the # of\n * rows of the main witness */\nstd::vector<int8_t> offsetIntrablocBlinding = {-1, -2, -3};\n\nstd::vector<int8_t> offsetStitchingBlinding = {-4, -5, -6};\n\nstd::vector<int8_t> offsetLDTBlinding = {-6, -7, -8};\n\n/**\n * ==============================================================================\n */\n/** Structured Objects */\nnamespace ligero {\nnamespace zksnark {\n\ntemplate <typename FieldT>\nstd::vector<FieldT> pick(std::vector<FieldT> data,\n                         std::vector<size_t> indices) {\n  std::vector<FieldT> tmp(indices.size());\n  transform(indices.begin(), indices.end(), tmp.begin(),\n            [&](size_t index) { return data[index]; });\n\n  return tmp;\n}\n\n/** Data Structures */\n\n/** Fiat-Shamir Transformation: We generate \"random\" choices by the Verifier\n *  based on the values of the partial transcript\n */\ntemplate <typename FieldT>\nclass VerifierSimulation {\n  uint64_t *&_randomness;\n  size_t _modulusIdx;\n\n public:\n  VerifierSimulation(uint64_t *&randomness, size_t modulusIdx,\n                     const hash::HashIntegerSeedGeneratorF<FieldT> &generator,\n                     const hash::HashStringSeedGeneratorF &generatorString)\n      : _randomness(randomness),\n        _modulusIdx(modulusIdx),\n        _hashIntegerSeedGenerator(generator),\n        _hashStringSeedGenerator(generatorString){};\n\n  const hash::HashIntegerSeedGeneratorF<FieldT> &_hashIntegerSeedGenerator;\n  const hash::HashStringSeedGeneratorF &_hashStringSeedGenerator;\n\n  /** Consume preprocessed randomness to yield random field elements\n   * @param randomness reference to the randomness matrix to populate\n   * @param ncols number of columns in the matrix\n   * @param nrows number of rows in the matrix\n   * @return 0 if successful\n   */\n  int pickFieldTupleIntra(std::vector<FieldT> &randomness, size_t ncols,\n                          size_t nrows) {\n    size_t idx = 0;\n    randomness.resize(nrows * ncols, FieldT(0));\n    for (size_t row = 0; row < nrows; row++) {\n      for (size_t col = 0; col < ncols; col++) {\n        randomness[row * ncols + col] = FieldT(\n            ligero::math::scaleToPrime(*this->_randomness++, _modulusIdx));\n      }\n    }\n\n    return 0;\n  }\n\n  /** Consume preprocessed randomness to yield random field elements\n   * @param randomness reference to the randomness vector to populate\n   * @param n number of elements to generate\n   * @return 0 if successful\n   */\n  int pickFieldTuple(std::vector<FieldT> &randomness, const size_t n) {\n    randomness.resize(n);\n    for (size_t idx = 0; idx < n; idx++) {\n      randomness[idx] =\n          FieldT(ligero::math::scaleToPrime(*this->_randomness++, _modulusIdx));\n    }\n\n    return 0;\n  }\n\n  /** Consume preprocessed randomness to yield random field elements\n   * @param randomness reference to the randomness vector to populate\n   * @return 0 if successful\n   */\n  int pickFieldTuple(std::vector<FieldT> &randomness) {\n    randomness.push_back(\n        FieldT(ligero::math::scaleToPrime(*this->_randomness++, _modulusIdx)));\n    return 0;\n  }\n\n  /** Consume preprocessed randomness to yield random 64-bit unsigned integers\n   * @param randomness reference to the randomness vector to populate\n   * @param n number of elements to populate\n   * @param upperBound integers will be in the interval [0,upperBound)\n   * @return 0 if successful\n   */\n  int pickUintTuple(std::vector<size_t> &randomness, const size_t n,\n                    size_t upperBound) {\n    randomness.resize(n);\n    for (size_t idx = 0; idx < n; idx++) {\n      randomness[idx] =\n          ligero::math::scaleToUpperBound(*this->_randomness++, upperBound);\n    }\n\n    return 0;\n  }\n};\n\n/**\n *  Parameters for Interleaved Reed-Solomon Code:\n *  - each row is a linear code over F consisting of n-tuples (p(\u03b71), ... ,\n *  p(\u03b7n)) given \u03b7 \u2208 Fn and p is a polynomial of degree less than k.\n *  - m rows are interleaved.\n */\nstruct InterleavedRSCode {\n  size_t n;\n  size_t k;\n  size_t m; /** Private witness */\n};\n\n/**\n *  Full transcript for a single round\n */\ntemplate <typename FieldT>\nclass roundFSTranscript {\n public:\n  hash::digest proverCommitment;\n  hash::digest proverCommitment_early;\n  std::vector<std::unordered_map<size_t, std::vector<FieldT>>>\n      proverResponsesLinearCombinations;\n  std::vector<size_t> verifierColumnQueries;\n  hash::sparseMultipleDecommitment<FieldT> proverDecommitment;\n  hash::sparseMultipleDecommitment<FieldT> proverDecommitment_early;\n\n private:\n  friend class boost::serialization::access;\n\n  /** Implements seralization and deserialization for a round of transcript */\n  template <class Archive>\n  void serialize(Archive &ar, const unsigned int version) {\n    ar & this->proverCommitment;\n    ar & this->proverCommitment_early;\n    ar & this->proverResponsesLinearCombinations;\n    ar & this->proverDecommitment;\n    ar & this->proverDecommitment_early;\n    _initialized = true;\n  }\n\n  bool _initialized;\n};\n\n/** This structure holds on to the indices of the blocs where variables can be\n * found across multiple witnesses */\nstruct multiWitnessesReferences {\n  std::vector<size_t> si_early_BlocIdxs;\n  std::vector<size_t> si_BlocIdxs;\n\n  std::vector<size_t> ei_early_BlocIdxs;\n  std::vector<size_t> ei_BlocIdxs;\n\n  std::vector<size_t> ri_early_BlocIdxs;\n  std::vector<size_t> ri_BlocIdxs;\n\n  size_t size(PublicData &p) {\n    return (this->si_BlocIdxs.size() + this->ei_BlocIdxs.size() +\n            ((p.modulusIdx < p.p) ? 1 : 0));\n  }\n};\n\ntemplate <typename FieldT>\nusing FullFSTranscript = std::vector<roundFSTranscript<FieldT>>;\n\n/**\n * ==============================================================================\n */\n/** Prover Column Commitment Scheme */\ntemplate <typename FieldT>\nclass ProverColumnCS : public ligero::MT_CommitmentScheme<FieldT> {\n public:\n  ProverColumnCS(ligero::MTParameters<FieldT> pcs, FieldT *U)\n      : ligero::MT_CommitmentScheme<FieldT>(\n            pcs.hashInnerNodeF, pcs.hashLeafContentF, pcs.hashZKRandomnessF,\n            pcs.digestLength, pcs.zkByteSize, pcs.leavesNumber,\n            pcs.leavesEntropy),\n        _U(U) {}\n\n  hash::digest performInitialCommit(FieldT *U) { return (this->commit(U)); }\n\n  hash::sparseMultipleDecommitment<FieldT> performProverDecommit(\n      std::vector<size_t> &q) {\n    return (this->decommit(q));\n  } /** This includes the values picked as well as the MT authentication path,\n       which are both added to the transcript */\n\n  FieldT *_U;\n};\n\ntemplate <typename FieldT>\nclass VerifierColumnCS : public ligero::MT_CommitmentScheme<FieldT> {\n public:\n  VerifierColumnCS(ligero::MTParameters<FieldT> pcs)\n      : ligero::MT_CommitmentScheme<FieldT>(\n            pcs.hashInnerNodeF, pcs.hashLeafContentF, pcs.hashZKRandomnessF,\n            pcs.digestLength, pcs.zkByteSize, pcs.leavesNumber,\n            pcs.leavesEntropy) {}\n};\n\n/**\n * ==============================================================================\n */\n/** Generic Non Interactive Protocol */\ntemplate <typename FieldT>\nclass NonInteractiveArgument {\n public:\n  Statements _statement;\n\n  /** Protocol Parameters */\n  InterleavedRSCode &_rs;\n  InterleavedRSCode _rs_early;\n  size_t _l;\n  size_t _t;\n  hash::HashIntegerSeedGeneratorF<FieldT> _gen;\n  hash::HashStringSeedGeneratorF _genS;\n  ligero::MTParameters<FieldT> _mtParams;\n  ligero::MTParameters<FieldT> _mtParams_early;\n\n  /** Functionality */\n  FullFSTranscript<FieldT> _transcript;\n  VerifierSimulation<FieldT> _vs;\n\n  /** Constraint System */\n  ConstraintSystem<FieldT> _constraints_early;\n  ConstraintSystem<FieldT> _constraints;\n\n  /** Current Round */\n  size_t _round;\n\n  /** Timing Information */\n  timers _myTimer;\n\n  /** Inputs */\n  PublicData &_publicData;\n  SigmaProtocolPublicData &_sigmaProtocolPublicData;\n  SecretData &_secretData;\n\n  /** Randomness */\n  uint64_t *_randomness;\n  uint64_t *_alloc;\n\n  /** Verifying Integrity Multi-Witness */\n  multiWitnessesReferences _splitWitness;\n\n  /** Size of the Constraint System Randomness */\n  size_t _constraintSystemRandomnessSize;\n\n  /** Cross-Moduli References */\n  std::vector<size_t> _uxBlocks;\n  std::vector<size_t> _uzBlocks;\n\n  std::vector<size_t> _eiBlocks;\n  std::vector<size_t> _siBlocks;\n\n  std::vector<std::vector<size_t>> _varBlocks;\n  uint64_t _stitching;\n\n  /** Bit Reverse Templates */\n  void (*_computeSmall)(uint64_t *, uint64_t const *);\n  void (*_computeLarge)(uint64_t *, uint64_t const *);\n\n  /** Maintaining a Hash */\n  std::string _hashedPublicData;\n\n public:\n  ~NonInteractiveArgument() {\n    cleanup();\n    cleanupEarly();\n  }\n\n  /** Constructor for the Generic Non Interactive Argument */\n  NonInteractiveArgument(\n      Statements statement, InterleavedRSCode &irs, size_t t, size_t l,\n      const hash::HashIntegerSeedGeneratorF<FieldT> &generator,\n      const hash::HashStringSeedGeneratorF &generatorString,\n      ligero::MTParameters<FieldT> &mt, PublicData &pdata,\n      SigmaProtocolPublicData &spdata, SecretData &sdata,\n      void (*computeSmall)(uint64_t *, uint64_t const *),\n      void (*computeLarge)(uint64_t *, uint64_t const *),\n      std::string &hashedPublicData)\n      : _statement(statement),\n        _rs(irs),\n        _t(t),\n        _l(l),\n        _gen(generator),\n        _genS(generatorString),\n        _mtParams(mt),\n        _mtParams_early(mt),\n        _vs(this->_randomness, pdata.modulusIdx, generator, generatorString),\n        _publicData(pdata),\n        _sigmaProtocolPublicData(spdata),\n        _secretData(sdata),\n        _computeSmall(computeSmall),\n        _computeLarge(computeLarge),\n        _hashedPublicData(hashedPublicData){\n\n            /** We need to increase the leaves entropy by one to account for the\n                     blinding row */\n            /** _mtParams.leavesEntropy++; */\n        };\n\n  void cleanup() {\n    for (constraint *p : this->_constraints.constraints) {\n      delete p;\n    }\n  }\n\n  void cleanupEarly() {\n    for (constraint *p : this->_constraints_early.constraints) {\n      delete p;\n    }\n  }\n\n  /** Here we compute the product of the transpose of the randomness vector r,\n   * namely the row vector (rT), with the linear constraint matrix A.\n   * The linear constraint matrix A is defined as : Ax = b, where x \u2208 Fml, b \u2208\n   * Fml and A \u2208 Fml x ml\n   * In this implementation, for a sparse representation of the matrix A, we\n   * use the transformaton_constraint\n   * class, each object representing the relationship between two elements of\n   * the extended witness.\n   * The resulting matrix (rT) x A will then be multiplied pointwise by our\n   * secret matrix U,\n   * subsequently shared, with a limited number of columns being opened based\n   * on security preferences.\n   * @param out reference to the (rT) x A matrix, stored in vector form\n   * @param constraint reference to the transformation constraint processed\n   * @param rml dense matrix of randomness\n   * @param targetBlocIdx block index target for the generative constraint\n   * @param processed reference to the set of blocks connected to transformation\n   * constraints\n   */\n  void calculateRTAmatrix(std::vector<FieldT> &out,\n                          transformation_constraint<FieldT> &constraint,\n                          std::vector<FieldT> &rml, size_t targetBlocIdx,\n                          std::unordered_set<size_t> &processed) {\n    if (processed.find(targetBlocIdx) == processed.end()) {\n      processed.insert(targetBlocIdx);\n    }\n\n    /** Browse through each component */\n    for (size_t idx = 0; idx < constraint.scalar.size(); idx++) {\n      size_t sourceWidx = (constraint.block[idx] * this->_rs.n) +\n                          constraint.source_position[idx];\n      size_t targetWidx =\n          (targetBlocIdx * this->_rs.n) + constraint.target_position[idx];\n\n      out[sourceWidx] +=\n          constraint.scalar[idx] *\n          rml[(targetBlocIdx * this->_l) + constraint.target_position[idx]];\n      out[targetWidx] +=\n          FieldT(FieldT::getModulus() - 1) *\n          rml[(targetBlocIdx * this->_l) + constraint.target_position[idx]];\n\n      if (processed.find(constraint.block[idx]) == processed.end()) {\n        processed.insert(constraint.block[idx]);\n      }\n    }\n  }\n\n  /** Similar functionality, except on the (rT) x A' matrix here to generate\n   * linear combinations used for the stitching of proofs accross moduli\n   * @param out reference to the (rT) x A' matrix, stored in vector form\n   * @param constraint reference to the transformation constraint processed\n   * @param rml dense matrix of randomness\n   * @param targetBlocIdx block index target for the generative constraint\n   * @param processed reference to the set of blocks connected to transformation\n   * @param iteration the index of the iteration in the proof\n   * @param populate flag indicating whether we are storing randomness or\n   * reusing what is already stored\n   */\n  void calculateRTAStitchingMatrix(\n      std::vector<FieldT> &out, transformation_constraint<FieldT> &constraint,\n      std::vector<FieldT> &rml, size_t targetBlocIdx,\n      std::unordered_set<size_t> &processed, size_t iteration,\n      bool populate = false) {\n    if (constraint.stitching ==\n        LinearCombinationsStitching::StitchingNoScalar) {\n      /** Browse through each component */\n      for (size_t idx = 0; idx < constraint.scalar.size(); idx++) {\n        size_t sourceWidx = (constraint.block[idx] * this->_rs.n) +\n                            constraint.source_position[idx];\n\n        out[sourceWidx] += constraint.scalar[idx];\n\n        if (processed.find(constraint.block[idx]) == processed.end()) {\n          processed.insert(constraint.block[idx]);\n        }\n      }\n    } else {\n      auto findVarIdx = [&](size_t index) -> std::pair<size_t, size_t> {\n        std::pair<size_t, size_t> out;\n        for (size_t i = 0; i < this->_varBlocks.size(); i++) {\n          auto it = find(this->_varBlocks[i].begin(), this->_varBlocks[i].end(),\n                         index);\n\n          if (it != this->_varBlocks[i].end()) {\n            out = {i, it - this->_varBlocks[i].begin()};\n            break;\n          }\n        }\n\n        return out;\n      };\n\n      auto [varIdx, blockIdx] = findVarIdx(constraint.block[0]);\n\n      if (this->_publicData.modulusIdx == 0) {\n        /** Record randomness */\n        for (size_t idx = 0; idx < constraint.scalar.size(); idx++) {\n          size_t sourceWidx = (constraint.block[idx] * this->_rs.n) +\n                              constraint.source_position[idx];\n          FieldT scalar(rml[(targetBlocIdx * this->_l) +\n                            constraint.target_position[idx]]);\n\n          out[sourceWidx] += scalar;\n          this->_secretData.ai[iteration][varIdx][blockIdx]\n                              [constraint.source_position[idx]] =\n              scalar.getValue();\n\n          if (processed.find(constraint.block[idx]) == processed.end()) {\n            processed.insert(constraint.block[idx]);\n          }\n        }\n      } else {\n        /** Use recorded randomness */\n        for (size_t idx = 0; idx < constraint.scalar.size(); idx++) {\n          size_t sourceWidx = (constraint.block[idx] * this->_rs.n) +\n                              constraint.source_position[idx];\n\n          out[sourceWidx] +=\n              FieldT(this->_secretData.ai[iteration][varIdx][blockIdx]\n                                         [constraint.source_position[idx]]);\n\n          if (processed.find(constraint.block[idx]) == processed.end()) {\n            processed.insert(constraint.block[idx]);\n          }\n        }\n      }\n    }\n  }\n\n  /** Generate Seed from Public Data and Transcript\n   * @param transcript the full transcript up to this point\n   * @return a hash of the combined information\n   */\n  std::vector<unsigned char> generateFSSeed(\n      FullFSTranscript<FieldT> &transcript) {\n    std::string msg;\n\n    msg += this->_hashedPublicData;\n    msg += std::to_string(this->_publicData.modulusIdx);\n    msg += serialize(transcript[0].proverCommitment);\n    msg += serialize(transcript[0].proverDecommitment);\n\n    for (size_t idx = 0;\n         idx < transcript[0].proverResponsesLinearCombinations.size(); idx++) {\n      msg += serialize(\n          transcript[0]\n              .proverResponsesLinearCombinations[idx][TEST_INTERLEAVED]);\n      msg += serialize(transcript[0].proverResponsesLinearCombinations\n                           [idx][TEST_LINEAR_INTERBLOC_CONSTRAINTS]);\n      msg += serialize(transcript[0].proverResponsesLinearCombinations\n                           [idx][TEST_LINEAR_INTRABLOC_CONSTRAINTS]);\n      msg += serialize(transcript[0].proverResponsesLinearCombinations\n                           [idx][TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS]);\n      msg += serialize(\n          transcript[0]\n              .proverResponsesLinearCombinations[idx]\n                                                [TEST_QUADRATIC_CONSTRAINTS]);\n    }\n\n    return (this->_vs._hashStringSeedGenerator(msg.c_str(), msg.size()));\n  }\n\n  /** Bulk generation of randomness based on the state of the transcript up to\n   * this point\n   * @param sizeRandomness number of random field elements to generate at once\n   * @param transcript the full transcript up to this point\n   */\n  void pickFiatShamirRandomness(size_t sizeRandomness,\n                                FullFSTranscript<FieldT> &transcript) {\n    std::vector<unsigned char> seed = this->generateFSSeed(transcript);\n    this->_randomness =\n        static_cast<uint64_t *>(malloc(sizeRandomness * sizeof(uint64_t)));\n    randombytes_buf_deterministic((void *)this->_randomness,\n                                  sizeRandomness * sizeof(uint64_t), &seed[0]);\n    this->_alloc = this->_randomness;\n  }\n\n  /** These will be implemented by specialized classes, as the logic will differ\n   * here between the prover and the verifier */\n  virtual void runRound(size_t, bool) = 0;\n\n  /** Running the protocol\n   * @param nbRounds number of rounds included in the protocol (1 for the RSA\n   * Ceremony)\n   * @param earlyOnly if true, all that will be done is to generate the early\n   * witness, no proof generated at this point\n   */\n  void runProtocol(size_t nbRounds, bool earlyOnly = false) {\n    for (size_t round = 0; round < nbRounds; round++)\n      runRound(round, earlyOnly);\n  }\n\n  /** Pick challenges for the simulated verifier based on Fiat-Shamir\n   * transformation\n   * @param round index of the current protocol round\n   * @param phase the type of test we are generating challenges for\n   * @param r reference to the vector of challenges\n   * @param size target size for the challenge vector\n   */\n  void pickVerifierChallenges(size_t round, unsigned int phase,\n                              vector<FieldT> &r, size_t size = 0) {\n    /** Pick randomness */\n    switch (phase) {\n      case TEST_INTERLEAVED:\n        this->_vs.pickFieldTuple(r, size); /** r \u2208 Fm */\n        break;\n\n      case TEST_QUADRATIC_CONSTRAINTS:\n      case TEST_LINEAR_INTERBLOC_CONSTRAINTS:\n        this->_vs.pickFieldTuple(r);\n        break;\n\n      case TEST_LINEAR_INTRABLOC_CONSTRAINTS:\n        this->_vs.pickFieldTupleIntra(r, this->_l, size); /** r \u2208 Fml */\n        break;\n\n      default:\n        throw internalError(\"incorrect phase for pickVerifierChallenges: \" +\n                            std::to_string(phase));\n        break;\n    }\n  }\n\n  /** Pick challenges for the simulated verifier for opening columns based on\n   * Fiat-Shamir transformation\n   * @param round index of the current protocol round\n   * @param phase the type of test we are generating challenges for (here\n   * opening columns)\n   * @param r reference to the vector of challenges\n   */\n  void pickVerifierChallenges(size_t round, unsigned int phase,\n                              std::vector<size_t> &r) {\n    /** Pick randomness */\n    switch (phase) {\n      case OPEN_COLUMNS:\n        this->_vs.pickUintTuple(r, this->_t, this->_rs.n);\n\n        std::sort(r.begin(), r.end());\n        r.erase(std::unique(r.begin(), r.end()), r.end());\n\n        break;\n\n      default:\n        throw internalError(\"incorrect phase for pickVerifierChallenges: \" +\n                            std::to_string(phase));\n        break;\n    }\n  }\n\n  /** Interleaved: prover helper function to compute linear combinations over\n   * the full witness as the prover response to the verifier's challenges\n   * @param res reference to the vector containing the linear combinations\n   * @param interleaved_r verifiers challenges\n   * @param U pointer to the witness\n   */\n  void interbloc(std::vector<FieldT> &res,\n                 const std::vector<FieldT> &interleaved_r, const FieldT *U) {\n    if (res.size() == 0) {\n      res.resize(this->_rs.n, FieldT(0));\n    }\n\n    for (size_t col = 0; col < this->_rs.n; col++) {\n      for (size_t row = 0; row < interleaved_r.size(); row++) {\n        res[col] += U[col + (row * this->_rs.n)] * interleaved_r[row];\n      }\n    }\n  }\n\n  /** Interleaved: verifier helper function to compute linear combinations over\n   * the opened columns as the prover response to the verifier's challenges\n   * @param res reference to the vector containing the linear combinations\n   * @param interleaved_r verifiers challenges\n   * @param Uq matrix of opened columns\n   */\n  void interbloc(std::vector<FieldT> &res,\n                 const std::vector<FieldT> &interleaved_r,\n                 const std::vector<std::vector<FieldT>> &Uq) {\n    if (res.size() == 0) {\n      res.resize(Uq.size(), FieldT(0));\n    }\n\n    for (size_t col = 0; col < Uq.size(); col++) {\n      for (size_t row = 0; row < interleaved_r.size(); row++) {\n        res[col] += Uq[col][row] * interleaved_r[row];\n      }\n    }\n  }\n\n  /** Interbloc Linear Constraint: prover helper function to compute linear\n   * combinations over the full witness as the prover response to the\n   * verifier's challenges\n   * @param res reference to the vector containing the linear combinations\n   * @param block indices of the input blocks involved in the linear constraint\n   * @param scalar scalars for each of the blocks\n   * @param target index of the target block for the linear constraint (output)\n   * @param r verifiers challenges\n   * @param U pointer to the witness\n   */\n  void interbloc(std::vector<FieldT> &res, const std::vector<size_t> &block,\n                 const std::vector<FieldT> &scalar, const size_t target,\n                 const FieldT &r, const FieldT *U) {\n    if (res.size() == 0) {\n      res.resize(this->_rs.n, FieldT(0));\n    }\n\n    for (size_t col = 0; col < this->_rs.n; col++) {\n      for (size_t idx = 0; idx < block.size(); idx++) {\n        res[col] += U[col + (block[idx] * this->_rs.n)] * scalar[idx] * r;\n      }\n      res[col] = res[col] - U[col + (target * this->_rs.n)] * r;\n    }\n  }\n\n  /** Interbloc Linear Constraint: verifier helper function to compute linear\n   * combinations over opened columns as the prover response to the\n   * verifier's challenges\n   * @param res reference to the vector containing the linear combinations\n   * @param block indices of the input blocks involved in the linear constraint\n   * @param scalar scalars for each of the blocks\n   * @param target index of the target block for the linear constraint (output)\n   * @param r verifiers challenges\n   * @param Uq matrix of opened columns\n   */\n  void interbloc(std::vector<FieldT> &res, const std::vector<size_t> &block,\n                 const std::vector<FieldT> &scalar, const size_t target,\n                 const FieldT &r, const std::vector<std::vector<FieldT>> &Uq) {\n    if (res.size() == 0) {\n      res.resize(Uq.size(), FieldT(0));\n    }\n\n    for (size_t col = 0; col < Uq.size(); col++) {\n      for (size_t idx = 0; idx < block.size(); idx++) {\n        res[col] += Uq[col][block[idx]] * scalar[idx] * r;\n      }\n\n      res[col] = res[col] - Uq[col][target] * r;\n    }\n  }\n\n  /** Interbloc Linear Constraint Across Witnesses : prover helper\n   * function to compute linear combinations across witnesses to prove\n   * consistency\n   * @param res reference to the vector containing the linear combinations\n   * @param block_early indices of the target blocks in the early witness\n   * @param block indices of the corresponding target blocks in the main witness\n   * @param r verifiers challenges\n   * @param U_early pointer to the early witness\n   * @param U pointer to the witness\n   */\n  void splitWitnessInterbloc(std::vector<FieldT> &res,\n                             const size_t &block_early, const size_t &block,\n                             const FieldT &r, FieldT *U_early, FieldT *U) {\n    if (res.size() == 0) {\n      res.resize(this->_rs.n, FieldT(0));\n    }\n\n    for (size_t col = 0; col < this->_rs.n; col++) {\n      res[col] += U_early[col + (block_early * this->_rs.n)] * r;\n      res[col] -= U[col + (block * this->_rs.n)] * r;\n    }\n  }\n\n  /** Interbloc Linear Constraint Across Witnesses : verifier helper\n   * function to compute linear combinations over opened columns across\n   * witnesses to prove consistency\n   * @param res reference to the vector containing the linear combinations\n   * @param block_early indices of the target blocks in the early witness\n   * @param block indices of the corresponding target blocks in the main witness\n   * @param r verifiers challenges\n   * @param Uq_early matrix of opened columns in the early witness\n   * @param Uq matrix of opened columns in the main witness\n   */\n  void splitWitnessInterbloc(std::vector<FieldT> &res,\n                             const size_t &block_early, const size_t &block,\n                             const FieldT &r,\n                             const std::vector<std::vector<FieldT>> &Uq_early,\n                             const std::vector<std::vector<FieldT>> &Uq) {\n    if (res.size() == 0) {\n      res.resize(Uq.size(), FieldT(0));\n    }\n\n    for (size_t col = 0; col < Uq.size(); col++) {\n      res[col] += Uq_early[col][block_early] * r;\n      res[col] -= Uq[col][block] * r;\n    }\n  }\n\n  /** Quadratic Constraint: prover helper function to compute linear\n   * combinations over the full witness as the prover response to the\n   * verifier's challenges\n   * @param res reference to the vector containing the linear combinations\n   * @param block_pl indices of the blocks containing the left-handside operand\n   * of the quadratic constraint\n   * @param block_pr indices of the blocks containing the right-handside operand\n   * of the quadratic constraint\n   * @param scalar scalars for each of the blocks\n   * @param target index of the target block for the quadratic constraint\n   * (output)\n   * @param r verifier's challenges\n   * @param U pointer to the witness\n   */\n  void interbloc(std::vector<FieldT> &res, const std::vector<size_t> &block_pl,\n                 const std::vector<size_t> &block_pr,\n                 const std::vector<FieldT> &scalar, const size_t target,\n                 const FieldT &r, const FieldT *U) {\n    if (res.size() == 0) {\n      res.resize(this->_rs.n, FieldT(0));\n    }\n\n    for (size_t col = 0; col < this->_rs.n; col++) {\n      for (size_t idx = 0; idx < block_pl.size(); idx++) {\n        res[col] += U[col + (block_pl[idx] * this->_rs.n)] *\n                    U[col + (block_pr[idx] * this->_rs.n)] * scalar[idx] * r;\n      }\n\n      res[col] = res[col] - U[col + (target * this->_rs.n)] * r;\n    }\n  }\n\n  /** Quadratic Constraint: verifier helper function to compute linear\n   * combinations over opened columns as the prover response to the\n   * verifier's challenges\n   * @param res reference to the vector containing the linear combinations\n   * @param block_pl indices of the blocks containing the left-handside operand\n   * of the quadratic constraint\n   * @param block_pr indices of the blocks containing the right-handside operand\n   * of the quadratic constraint\n   * @param scalar scalars for each of the blocks\n   * @param target index of the target block for the quadratic constraint\n   * (output)\n   * @param r verifier's challenges\n   * @param Uq matrix of opened columns\n   */\n  void interbloc(std::vector<FieldT> &res, const std::vector<size_t> &block_pl,\n                 const std::vector<size_t> &block_pr,\n                 const std::vector<FieldT> &scalar, const size_t target,\n                 const FieldT &r, const std::vector<std::vector<FieldT>> &Uq) {\n    if (res.size() == 0) {\n      res.resize(Uq.size(), FieldT(0));\n    }\n\n    for (size_t col = 0; col < Uq.size(); col++) {\n      for (size_t idx = 0; idx < block_pl.size(); idx++) {\n        res[col] +=\n            Uq[col][block_pl[idx]] * Uq[col][block_pr[idx]] * scalar[idx] * r;\n      }\n\n      res[col] = res[col] - Uq[col][target] * r;\n    }\n  }\n\n  /** Transformation Constraint: verifier helper function to compute linear\n   * combinations over opened columns as the prover response to the\n   * verifier's challenges\n   * @param res reference to the vector containing the linear combinations\n   * @param r verifiers challenges\n   * @param Uq matrix of opened columns in the main witness\n   * @param Q positions of the opened columns\n   * @param processed reference to the set of blocks involved in this linear\n   * constraint\n   * @param iteration index of the current iteration within the current round\n   */\n  void intrabloc(std::vector<FieldT> &res, const std::vector<FieldT> &r,\n                 const std::vector<std::vector<FieldT>> &Uq,\n                 const vector<size_t> &Q, std::unordered_set<size_t> &processed,\n                 uint8_t iteration) {\n    if (res.size() == 0) {\n      res.resize(Uq.size(), FieldT(0));\n    }\n\n    for (size_t col = 0; col < Uq.size(); col++) {\n      for (size_t row : processed) {\n        res[col] += Uq[col][row] * r[Q[col] + (row * this->_rs.n)];\n      }\n\n      res[col] += Uq[col][this->_rs.m + offsetIntrablocBlinding[iteration]];\n    }\n  }\n\n  /** Stitching: verifier helper function to compute linear\n   * combinations over opened columns as the prover response to the\n   * verifier's challenges\n   * @param res reference to the vector containing the linear combinations\n   * @param r verifiers challenges\n   * @param Uq matrix of opened columns in the main witness\n   * @param Q positions of the opened columns\n   * @param processed reference to the set of blocks involved in this linear\n   * constraint\n   * @param iteration index of the current iteration within the current round\n   */\n  void intrablocStitching(std::vector<FieldT> &res,\n                          const std::vector<FieldT> &r,\n                          const std::vector<std::vector<FieldT>> &Uq,\n                          const vector<size_t> &Q,\n                          std::unordered_set<size_t> &processed,\n                          uint8_t iteration) {\n    if (res.size() == 0) {\n      res.resize(Uq.size(), FieldT(0));\n    }\n\n    for (size_t col = 0; col < Uq.size(); col++) {\n      for (size_t row : processed) {\n        res[col] += Uq[col][row] * r[Q[col] + (row * this->_rs.n)];\n      }\n\n      res[col] += Uq[col][this->_rs.m + offsetStitchingBlinding[iteration]];\n    }\n  }\n};\n\ntemplate <typename FieldT>\nclass Prover : public NonInteractiveArgument<FieldT> {\n  /** Extended Witness */\n  FieldT *_w_early;\n  FieldT *_w;\n  ligero::ZeroMQClientTransport &_transport;\n\n public:\n  /** Constructor for the Prover */\n  Prover(Statements statement, InterleavedRSCode &irs, size_t t,\n         size_t blocSize,\n         const hash::HashIntegerSeedGeneratorF<FieldT> &generator,\n         const hash::HashStringSeedGeneratorF &generatorString,\n         ligero::MTParameters<FieldT> &mt, PublicData &pdata,\n         SigmaProtocolPublicData &spdata, SecretData &sdata,\n         void (*computeSmall)(uint64_t *, uint64_t const *),\n         void (*computeLarge)(uint64_t *, uint64_t const *),\n         ligero::ZeroMQClientTransport &transport,\n         std::string &hashedPublicData)\n      : NonInteractiveArgument<FieldT>(\n            statement, irs, t, blocSize, generator, generatorString, mt, pdata,\n            spdata, sdata, computeSmall, computeLarge, hashedPublicData),\n        _transport(transport) {}\n\n  /** Updating an aggregate linear combination vector with the prover's response\n   * to the simulated verifier's challenges for a specific constraint\n   * @param round current round\n   * @param target target block for the constraint handled\n   * @param ct pointer to the constraint being handled\n   * @param type type of underlying constraint\n   * @param r verifier challenges\n   * @param rU reference to an aggregate linear combination vector\n   */\n  inline void obtainProverResponses(size_t round, size_t target, constraint *ct,\n                                    int type, const vector<FieldT> &r,\n                                    vector<FieldT> &rU) {\n    ligero::SecretSharingInterface<FieldT> localSecretSharing(\n        this->_publicData.modulusIdx, (size_t)this->_l, (size_t)this->_rs.k,\n        (size_t)this->_rs.n, this->_computeSmall, this->_computeLarge);\n\n    switch (type) {\n      case TEST_LINEAR_INTERBLOC_CONSTRAINTS: {\n        linear_constraint<FieldT> constraint =\n            *static_cast<const linear_constraint<FieldT> *>(ct);\n        this->interbloc(rU, constraint.block, constraint.scalar, target,\n                        r.back(), this->_w);\n\n#ifndef NDEBUG\n\n        {\n          std::string report(std::to_string(target) +\n                             std::string(\",test,interbloc,blocs,\"));\n          for (size_t idx = 0; idx < constraint.block.size() - 1; idx++) {\n            report += std::to_string(constraint.block[idx]) + std::string(\",\");\n          }\n          report += std::to_string(constraint.block.back());\n\n          DBG(report);\n        }\n\n        {\n          std::string report(std::to_string(target) +\n                             std::string(\",test,interbloc,coefs,\"));\n          for (size_t idx = 0; idx < constraint.scalar.size() - 1; idx++) {\n            report += std::to_string(constraint.scalar[idx].getValue()) +\n                      std::string(\",\");\n          }\n          report += std::to_string(constraint.scalar.back().getValue());\n\n          DBG(report);\n        }\n\n#endif\n\n      } break;\n\n      case TEST_LINEAR_INTRABLOC_CONSTRAINTS:\n        break;\n\n      case TEST_QUADRATIC_CONSTRAINTS: {\n        quadratic_constraint<FieldT> constraint =\n            *static_cast<const quadratic_constraint<FieldT> *>(ct);\n        this->interbloc(rU, constraint.left_block, constraint.right_block,\n                        constraint.scalar, target, r.back(), this->_w);\n\n#ifndef NDEBUG\n\n        {\n          std::string report(std::to_string(target) +\n                             std::string(\",quadratic,left_bloc,\"));\n          for (size_t idx = 0; idx < constraint.left_block.size() - 1; idx++) {\n            report +=\n                std::to_string(constraint.left_block[idx]) + std::string(\",\");\n          }\n          report += std::to_string(constraint.left_block.back());\n\n          DBG(report);\n        }\n\n        {\n          std::string report(std::to_string(target) +\n                             std::string(\",quadratic,right_bloc,\"));\n          for (size_t idx = 0; idx < constraint.right_block.size() - 1; idx++) {\n            report +=\n                std::to_string(constraint.right_block[idx]) + std::string(\",\");\n          }\n          report += std::to_string(constraint.right_block.back());\n\n          DBG(report);\n        }\n\n        {\n          std::string report(std::to_string(target) +\n                             std::string(\",quadratic,coefs,\"));\n          for (size_t idx = 0; idx < constraint.scalar.size() - 1; idx++) {\n            report += std::to_string(constraint.scalar[idx].getValue()) +\n                      std::string(\",\");\n          }\n          report += std::to_string(constraint.scalar.back().getValue());\n\n          DBG(report);\n        }\n\n#endif\n      } break;\n      default:\n        throw std::runtime_error(\"incorrect test type for prover responses:\" +\n                                 std::to_string(type));\n        break;\n    }\n  }\n\n  /** Builds the constraint system and witness for the statement currently\n   * stored, then generates a ZKP and sends it to the coordinator\n   * @param nbRounds total number of rounds (1 for the RSA Ceremony)\n   * @param earlyCommitmentOnly if true, all we will do is build and commit the\n   * merkle tree for the early witness\n   */\n  void produceArgumentOfKnowledge(size_t nbRounds, bool earlyCommitmentOnly) {\n    this->_myTimer.initialize_timer();\n    this->_myTimer.begin(1, \"Producing Proof\", 0);\n\n    /** Initialize Fpp */\n    /** =========================== */\n\n    auto assessBlocIdx = [&](auto &builder,\n                             std::vector<size_t> idxs) -> std::vector<size_t> {\n      std::vector<size_t> ret;\n      for (auto idx : idxs) {\n        ret.emplace_back(builder.proof_values_location[idx]);\n      }\n\n      return ret;\n    };\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      /** Build a first witness/constraint system for Early Commitment */\n      /** ================================================================== */\n\n      this->_rs_early = this->_rs;\n      this->_myTimer.begin(\n          2, \"Build Extended Witness & Constraint System For Early Commitment\",\n          0);\n      builder<FieldT> helper(this->_l);\n      vector<vector<FieldT>> earlyCommitments2DVector;\n\n      expressNPStatement<FieldT> expressStatementEarlyCommitment(\n          this->_publicData, this->_sigmaProtocolPublicData, this->_secretData,\n          helper, &earlyCommitments2DVector, this->_l, this->_randomness);\n      expressStatementEarlyCommitment.buildConstraintSet(\n          Statements::RSACeremony_EarlyCommitments);\n\n      this->_myTimer.begin(3, \"compile\", 0);\n      this->_constraints_early = helper.compile(earlyCommitments2DVector);\n      this->_myTimer.end(3, \"compile\", 0);\n\n      /** Dimensioning the circuit accordingly */\n      /** We reserve one additional row for blinding */\n      this->_mtParams_early.leavesEntropy = this->_rs_early.m =\n          earlyCommitments2DVector.size() +\n          this->_constraints_early.constant_blocks + 1;\n\n      /** Record Position of Variables in the Witness */\n      this->_splitWitness.si_early_BlocIdxs = assessBlocIdx(\n          helper, expressStatementEarlyCommitment._siCoefsBlocIds);\n      this->_splitWitness.ei_early_BlocIdxs = assessBlocIdx(\n          helper, expressStatementEarlyCommitment._eiCoefsBlocIds);\n      if (this->_publicData.modulusIdx < this->_publicData.p)\n        this->_splitWitness.ri_early_BlocIdxs = assessBlocIdx(\n            helper, {expressStatementEarlyCommitment._riCoefsBlocId});\n\n      /** Embedding the early commit witness */\n      /** ================================== */\n\n      this->_myTimer.begin(3, \"Embedding the early extended witness\", 0);\n\n      /** Migrate the extended witness to an expandable matrix */\n      FieldT *earlyWitnessCArray =\n          new FieldT[this->_rs_early.n * this->_rs_early.m]{FieldT(0)};\n\n      {\n        /** Populate the private witness */\n        size_t idx = 0;\n        for (auto &row : earlyCommitments2DVector) {\n          memcpy(static_cast<void *>(\n                     &earlyWitnessCArray[(idx++) * this->_rs_early.n]),\n                 static_cast<void *>(&row[0]), row.size() * sizeof(FieldT));\n          row.clear();\n        }\n\n        /** Add public constants */\n        size_t topConstantRow =\n            this->_rs_early.m - this->_constraints.constant_blocks -\n            1; /** Accounting for constants and blinding row */\n        for (size_t row = 0; row < this->_constraints_early.constant_blocks;\n             row++) {\n          for (size_t col = 0; col < this->_l; col++) {\n            earlyWitnessCArray[(topConstantRow + row) * this->_rs_early.n +\n                               col] =\n                this->_constraints_early\n                    .constants[col * this->_constraints.constant_blocks + row];\n          }\n        }\n      }\n\n      this->_w_early = earlyWitnessCArray;\n\n      this->_myTimer.end(3, \"Embedding the early extended witness\", 0);\n      this->_myTimer.end(\n          2, \"Build Extended Witness & Constraint System For Early Commitment\",\n          0);\n    }\n\n    if (earlyCommitmentOnly) {\n      /** Dimension Randomness for the Constraint System */\n      this->_constraintSystemRandomnessSize = determineCSrandomnessSize(\n          this->_statement, this->_publicData.ptNumberEvaluation);\n\n      this->_myTimer.begin(2, \"Generating the Proof\", 0);\n      this->runProtocol(nbRounds, earlyCommitmentOnly);\n      this->_myTimer.end(2, \"Generating the Proof\", 0);\n\n      return;\n    }\n\n    /** Building the constraint system and populating the extended witness */\n    /** ================================================================== */\n\n    this->_myTimer.begin(2, \"Build Extended Witness & Constraint System\", 0);\n    vector<vector<FieldT>> extendedWitness2DVector;\n\n    {\n      builder<FieldT> bob(this->_l);\n\n      this->_myTimer.begin(3, \"Express NP statement\", 0);\n      expressNPStatement<FieldT> expressStatement(\n          this->_publicData, this->_sigmaProtocolPublicData, this->_secretData,\n          bob, &extendedWitness2DVector, this->_l, this->_randomness);\n      expressStatement.buildConstraintSet(this->_statement, false);\n      this->_myTimer.end(3, \"Express NP statement\", 0);\n\n      this->_myTimer.begin(3, \"compile\", 0);\n      this->_constraints = bob.compile(\n          extendedWitness2DVector); /** Main functionality to retain */\n      this->_myTimer.end(3, \"compile\", 0);\n\n      this->_myTimer.end(2, \"Build Extended Witness & Constraint System\", 0);\n      DBG(this->_constraints.constraints.size());\n\n      /** Details of the witness constructed */\n      /** We need to add */\n      DBG(\"witness rows:\" << extendedWitness2DVector.size());\n      DBG(\"witness cols:\" << extendedWitness2DVector[0].size());\n      this->_mtParams.leavesEntropy = this->_rs.m =\n          extendedWitness2DVector.size() + this->_constraints.constant_blocks +\n          nbBlindingRows;\n\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        /** Record Position of Variables in the Witness */\n        this->_splitWitness.si_BlocIdxs =\n            assessBlocIdx(bob, expressStatement._siBlocs);\n        this->_splitWitness.ei_BlocIdxs =\n            assessBlocIdx(bob, expressStatement._eiBlocs);\n        this->_splitWitness.ri_BlocIdxs =\n            assessBlocIdx(bob, {expressStatement._riCoefsBlocId});\n      }\n\n      /** Here checking that we got the referencing right */\n      this->_uxBlocks = assessBlocIdx(bob, expressStatement._uxBlocs);\n      this->_uzBlocks = assessBlocIdx(bob, expressStatement._uzBlocs);\n\n      this->_siBlocks = assessBlocIdx(bob, expressStatement._siBlocs);\n      this->_eiBlocks = assessBlocIdx(bob, expressStatement._eiBlocs);\n\n      /** Storing for Cross-Moduli Integrity Checking */\n      this->_varBlocks.emplace_back(this->_siBlocks);\n      this->_varBlocks.emplace_back(this->_eiBlocks);\n      this->_varBlocks.emplace_back(this->_uxBlocks);\n      this->_varBlocks.emplace_back(this->_uzBlocks);\n    }\n\n    /** Embedding the extended witness */\n    /** ============================== */\n\n    this->_myTimer.begin(2, \"Embedding the extended witness\", 0);\n\n    /** Migrate the extended witness to an expandable matrix */\n    FieldT *extendedWitnessCArray =\n        new FieldT[this->_rs.n * this->_rs.m]{FieldT(0)};\n\n    {\n      /** Populate the private witness */\n      size_t idx = 0;\n      for (auto &row : extendedWitness2DVector) {\n        memcpy(\n            static_cast<void *>(&extendedWitnessCArray[(idx++) * this->_rs.n]),\n            static_cast<void *>(&row[0]), row.size() * sizeof(FieldT));\n        row.clear();\n      }\n\n      /** Add public constants */\n      size_t topConstantRow =\n          this->_rs.m - this->_constraints.constant_blocks -\n          nbBlindingRows; /** Accounting for constants and blinding row */\n      for (size_t row = 0; row < this->_constraints.constant_blocks; row++) {\n        for (size_t col = 0; col < this->_l; col++) {\n          extendedWitnessCArray[(topConstantRow + row) * this->_rs.n + col] =\n              this->_constraints\n                  .constants[col * this->_constraints.constant_blocks + row];\n        }\n      }\n    }\n\n    this->_w = extendedWitnessCArray;\n\n    this->_myTimer.end(2, \"Embedding the extended witness\", 0);\n\n    /** Debug: dump of the extended witness and constraints [first 10 elements\n     * of each row] */\n    /**\n     * ===================================================================================\n     */\n    std::stringstream ss;\n    ss << boost::uuids::random_generator()();\n    std::string id(ss.str());\n    constexpr auto nDisplayCol = 20;\n\n    for (size_t row = 0; row < this->_rs.m; row++) {\n      std::string line = id + std::string(\",dump_witness,\");\n\n      line += std::to_string(row) + std::string(\",\");\n      for (size_t col = 0; col < nDisplayCol; col++) {\n        char buf[100];\n        sprintf(buf, \"%lu\",\n                (uint64_t)this->_w[col + row * this->_rs.n].getValue());\n        line += std::string(buf) + std::string(\",\");\n      }\n\n      DBG(line);\n    }\n\n    /** Testing constraints */\n    size_t target = 0;\n\n#ifndef NDEBUG\n    /** Dump of the constraint system for debug */\n    for (auto constraint : this->_constraints.constraints) {\n      switch (constraint->type) {\n        case linear: {\n          linear_constraint<FieldT> ct =\n              *static_cast<const linear_constraint<FieldT> *>(constraint);\n\n          std::string s =\n              id + std::string(\",dump_constraints,linear_constraint,block,\");\n          for (size_t i = 0; i < std::min(nDisplayCol, (int)ct.block.size());\n               i++) {\n            s += std::to_string(ct.block[i]) + std::string(\",\");\n          }\n          DBG(s);\n\n          s = id + std::string(\",dump_constraints,-,scalar,\");\n          for (size_t i = 0; i < std::min(nDisplayCol, (int)ct.scalar.size());\n               i++) {\n            char buf[100];\n            sprintf(buf, \"%lu\", ct.scalar[i].getValue());\n            s += std::string(buf) + std::string(\",\");\n          }\n          DBG(s);\n\n          s = id + std::string(\",dump_constraints,-,target_block,\");\n          s += std::to_string(this->_constraints.targets[target]) +\n               std::string(\",\");\n          DBG(s);\n        } break;\n\n        case transformation: {\n          transformation_constraint<FieldT> ct =\n              *static_cast<const transformation_constraint<FieldT> *>(\n                  constraint);\n\n          std::string s =\n              id +\n              std::string(\",dump_constraints,transformation,source_block,\");\n          for (size_t i = 0; i < std::min(nDisplayCol, (int)ct.block.size());\n               i++) {\n            s += std::to_string(ct.block[i]) + std::string(\",\");\n          }\n          DBG(s);\n\n          s = id + std::string(\",dump_constraints,-,source_pos,\");\n          for (size_t i = 0;\n               i < std::min(nDisplayCol, (int)ct.source_position.size()); i++) {\n            char buf[100];\n            sprintf(buf, \"%lu\", ct.source_position[i]);\n            s += std::string(buf) + std::string(\",\");\n          }\n          DBG(s);\n\n          s = id + std::string(\",dump_constraints,-,target_pos,\");\n          for (size_t i = 0;\n               i < std::min(nDisplayCol, (int)ct.target_position.size()); i++) {\n            char buf[100];\n            sprintf(buf, \"%lu\", ct.target_position[i]);\n            s += std::string(buf) + std::string(\",\");\n          }\n          DBG(s);\n\n          s = id + std::string(\",dump_constraints,-,target_block,\");\n          s += std::to_string(this->_constraints.targets[target]) +\n               std::string(\",\");\n          DBG(s);\n        } break;\n\n        case quadratic: {\n          quadratic_constraint<FieldT> ct =\n              *static_cast<const quadratic_constraint<FieldT> *>(constraint);\n\n          std::string s =\n              id +\n              std::string(\",dump_constraints,quadratic_constraint,left_block,\");\n          for (size_t i = 0;\n               i < std::min(nDisplayCol, (int)ct.left_block.size()); i++) {\n            s += std::to_string(ct.left_block[i]) + std::string(\",\");\n          }\n          DBG(s);\n\n          s = id + std::string(\",dump_constraints,-,right_bloc,\");\n          for (size_t i = 0;\n               i < std::min(nDisplayCol, (int)ct.right_block.size()); i++) {\n            s += std::to_string(ct.right_block[i]) + std::string(\",\");\n          }\n          DBG(s);\n\n          s = id + std::string(\",dump_constraints,-,scalar,\");\n          for (size_t i = 0; i < std::min(nDisplayCol, (int)ct.scalar.size());\n               i++) {\n            char buf[100];\n            sprintf(buf, \"%lu\", ct.scalar[i].getValue());\n            s += std::string(buf) + std::string(\",\");\n          }\n          DBG(s);\n\n          s = id + std::string(\",dump_constraints,-,target_block,\");\n          s += std::to_string(this->_constraints.targets[target]) +\n               std::string(\",\");\n          DBG(s);\n        } break;\n\n        default:\n          throw std::runtime_error(\"incorrect constraint type for test:\" +\n                                   std::to_string(constraint->type));\n          break;\n      }\n\n      target++;\n    }\n#endif\n\n    /** Generating and sending the proof */\n    /** ================================ */\n\n    /** Dimension Randomness for the Constraint System */\n    this->_constraintSystemRandomnessSize = determineCSrandomnessSize(\n        this->_statement, this->_publicData.ptNumberEvaluation);\n\n    this->_myTimer.begin(2, \"Generating the Proof\", 0);\n    this->runProtocol(nbRounds, earlyCommitmentOnly);\n    this->_myTimer.end(2, \"Generating the Proof\", 0);\n\n    this->_myTimer.begin(2, \"Sending the Proof\", 0);\n    this->sendArgumentOfKnowledge();\n    this->_myTimer.end(2, \"Sending the Proof\", 0);\n\n    /** Clean Up */\n    delete[] extendedWitnessCArray;\n\n    this->_myTimer.end(1, \"Producing Proof\", 0);\n  }\n\n  /** Once the coordinator announces it has provided verifiers with\n   * the data linked to the sigma protocol then we can start sending our proofs\n   */\n  void sendArgumentOfKnowledge() {\n#ifndef NDEBUG\n    DBG(\"Linear Combinations Sizes Sent By Prover\");\n    DBG(\"========================================\");\n    DBG(this->_transcript[0]\n            .proverResponsesLinearCombinations[0][TEST_INTERLEAVED]\n            .size());\n    DBG(this->_transcript[0]\n            .proverResponsesLinearCombinations\n                [0][TEST_LINEAR_INTERBLOC_CONSTRAINTS]\n            .size());\n    DBG(this->_transcript[0]\n            .proverResponsesLinearCombinations\n                [0][TEST_LINEAR_INTRABLOC_CONSTRAINTS]\n            .size());\n    DBG(this->_transcript[0]\n            .proverResponsesLinearCombinations\n                [0][TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS]\n            .size());\n    DBG(this->_transcript[0]\n            .proverResponsesLinearCombinations[0][TEST_QUADRATIC_CONSTRAINTS]\n            .size());\n#endif\n\n    /** Send Data and the argument to the Coordinator */\n\n    if (this->_publicData.modulusIdx == 0) {\n      auto msg = _transport.awaitReply();\n      if (hasError(msg)) {\n        throw std::runtime_error(showError(getError(msg)));\n      }\n      assert(getResult(msg) == MessageType::GATHER_PROOFS);\n    }\n\n    _transport.send(MessageType::GATHER_PROOFS, this->_transcript, false);\n  }\n\n  /** This section will add multiple blinding rows:\n   * two for LDT testing\n   * two for regular intra-bloc constraints\n   * two for stitching proofs together */\n  void addBlindingRows() {\n    for (uint8_t blindingRowIdx = 0; blindingRowIdx < nbBlindingRows;\n         blindingRowIdx++) {\n      std::vector<FieldT> blindingRow(this->_l);\n\n      FieldT::randomVector(&blindingRow[0], this->_l - 1, true);\n      FieldT sum = FieldT(0);\n      for (size_t idx = 0; idx < this->_l - 1; idx++) {\n        sum += blindingRow[idx];\n      }\n      blindingRow[this->_l - 1] = FieldT(0) - sum;\n\n      memcpy(this->_w + ((this->_rs.m - blindingRowIdx - 1) * this->_rs.n),\n             (const void *)&blindingRow[0], this->_l * sizeof(FieldT));\n    }\n  }\n\n  /** Prover runs a round of the protocol\n   * (there is only one round in total for the RSA Ceremony)\n   *\n   * @param round current round\n   * @param earlyOnly if true, only populate and generate the commitment for the\n   * early witness\n   */\n  void runRound(size_t round, bool earlyOnly) {\n    /** Expand the transcript */\n    this->_transcript.emplace_back(roundFSTranscript<FieldT>());\n\n    /** Initialize secret sharing interface */\n    ligero::SecretSharingInterface<FieldT> localSecretSharing(\n        this->_publicData.modulusIdx, (size_t)this->_l, (size_t)this->_rs.k,\n        (size_t)this->_rs.n, this->_computeSmall, this->_computeLarge);\n\n    /** Have the \"Verifier\" pick randomness for all tests according to the\n     * Fiat-Shamir transform\n     */\n    std::vector<FieldT> interleaved_r, interleaved_r_early,\n        linearConstraintsInterBloc_r, quadraticConstraints_r,\n        linearConstraintsIntraBloc_ri, linearConstraintsSigma_r,\n        linearConstraintsStitchingIntraBloc_ri;\n\n    /** Early witness\n     * ========================================================================================\n     */\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      this->_myTimer.begin(3, \"Sharing early witness\", 0);\n\n      /** Pad the early witness with randomness */\n      localSecretSharing.padMany(this->_w_early, this->_rs_early.m);\n\n      /** Share the early witness */\n      localSecretSharing.shareMany(this->_w_early, this->_rs_early.m);\n\n      this->_myTimer.end(3, \"Sharing early witness\", 0);\n    }\n\n    /** Commit to the early witness */\n    ProverColumnCS<FieldT> proverCCS_early(this->_mtParams_early,\n                                           this->_w_early);\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      /** Merkel Tree Commitment */\n      this->_myTimer.begin(3, \"Commit Early Witness MT\", 0);\n\n      this->_transcript[round].proverCommitment_early =\n          proverCCS_early.performInitialCommit(this->_w_early);\n\n      this->_myTimer.end(3, \"Commit Early Witness MT\", 0);\n    }\n\n    /** End here if all we wanted was the early commitment */\n    if (earlyOnly) return;\n\n    /** Moving on to the main witness */\n    /* =========================================================================\n     */\n\n    /** Adding blinding */\n    addBlindingRows();\n\n    this->_myTimer.begin(3, \"Sharing witness\", 0);\n\n    /** Pad the extended witness with randomness */\n    localSecretSharing.padMany(this->_w, this->_rs.m);\n\n    /** Share the extended witness */\n    localSecretSharing.shareMany(this->_w, this->_rs.m);\n\n    this->_myTimer.end(3, \"Sharing witness\", 0);\n\n    /** Merkel Tree Commitment */\n    this->_myTimer.begin(3, \"Commit MT\", 0);\n\n    ProverColumnCS<FieldT> proverCCS(this->_mtParams, this->_w);\n    this->_transcript[round].proverCommitment =\n        proverCCS.performInitialCommit(this->_w);\n\n    this->_myTimer.end(3, \"Commit MT\", 0);\n\n    this->_myTimer.begin(3, \"Estimate Randomness\", 0);\n    bool hasTransformation = false;\n\n    /** Estimate All Randomness */\n    size_t sizeRandomness = this->_rs.m; /** LDT testing */\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      sizeRandomness +=\n          this->_rs_early.m + this->_splitWitness.size(this->_publicData);\n    }\n\n    for (auto constraint : this->_constraints.constraints) {\n      switch (constraint->type) {\n        case linear:\n          sizeRandomness++;\n          break;\n\n        case transformation:\n          if (!hasTransformation) {\n            hasTransformation = true;\n            sizeRandomness += this->_rs.m * this->_l;\n          }\n          break;\n\n        case quadratic:\n          sizeRandomness++;\n          break;\n\n        default:\n          throw std::runtime_error(\n              \"incorrect constraint type to obtain prover responses:\" +\n              std::to_string(constraint->type));\n          break;\n      }\n    }\n\n    this->_myTimer.end(3, \"Estimate Randomness\", 0);\n\n    for (size_t iteration = 0; iteration < numberOfIterations; iteration++) {\n      std::vector<FieldT> interleaved_rU, linearConstraintsInterBloc_rU,\n          linearConstraintsSigma_rU, linearConstraintsIntraBloc_riU,\n          linearConstraintsStitchingIntraBloc_riU, quadraticConstraints_rU;\n      std::unordered_map<size_t, std::vector<FieldT>> linearCombinations;\n\n      /** Update the state (= establish a new seed for Fiat-Shamir randomness)\n       * and pick all randomness in a bulk */\n      sizeRandomness += this->_constraintSystemRandomnessSize;\n\n      this->_myTimer.begin(3, \"Pick Randomness\", 0);\n      this->pickFiatShamirRandomness(sizeRandomness, this->_transcript);\n      this->_myTimer.end(3, \"Pick Randomness\", 0);\n\n      /** Rebuild the constraint system based on this round's randomness\n       * We are locally scoping objects so as to invoke their destructor\n       * immediately; they won't be needed here\n       */\n      {\n        this->cleanup();\n\n        builder<FieldT> bob(this->_l);\n        vector<vector<FieldT>> extendedWitness2DVector;\n\n        this->_myTimer.begin(3, \"Express NP statement\", 0);\n        expressNPStatement<FieldT> expressStatement(\n            this->_publicData, this->_sigmaProtocolPublicData,\n            this->_secretData, bob, &extendedWitness2DVector, this->_l,\n            this->_randomness);\n        expressStatement.buildConstraintSet(this->_statement);\n        this->_myTimer.end(3, \"Express NP statement\", 0);\n\n        this->_myTimer.begin(3, \"compile\", 0);\n        this->_constraints = bob.compile(\n            extendedWitness2DVector, false); /** Main functionality to retain */\n        this->_myTimer.end(3, \"compile\", 0);\n      }\n\n      /** LDT testing */\n      this->_myTimer.begin(3, \"LDT Testing Core Witness\", 0);\n      this->pickVerifierChallenges(round, TEST_INTERLEAVED, interleaved_r,\n                                   this->_rs.m);\n      this->interbloc(interleaved_rU, interleaved_r, this->_w);\n      this->_myTimer.end(3, \"LDT Testing Core Witness\", 0);\n\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        this->_myTimer.begin(3, \"LDT Testing Early Commit\", 0);\n        this->pickVerifierChallenges(round, TEST_INTERLEAVED,\n                                     interleaved_r_early, this->_rs_early.m);\n        this->interbloc(interleaved_rU, interleaved_r_early, this->_w_early);\n        this->_myTimer.end(3, \"LDT Testing Early Commit\", 0);\n      }\n\n      /** transformation constraints, sparse randomness */\n      std::unordered_set<size_t> processed, processedStitched;\n      std::vector<FieldT> localRandomness;\n\n      /** Testing constraints */\n      size_t target = 0;\n\n      /** Intrabloc constraints only when there are transformations */\n      this->_myTimer.begin(3, \"Pick Randomness\", 0);\n      this->pickVerifierChallenges(round, TEST_LINEAR_INTRABLOC_CONSTRAINTS,\n                                   localRandomness, this->_rs.m);\n      this->_myTimer.end(3, \"Pick Randomness\", 0);\n\n      if (hasTransformation) {\n        linearConstraintsIntraBloc_ri.assign(this->_rs.n * this->_rs.m,\n                                             FieldT(0));\n      }\n\n      /** Stitching constraints for all moduli */\n      linearConstraintsStitchingIntraBloc_ri.assign(this->_rs.n * this->_rs.m,\n                                                    FieldT(0));\n\n      this->_myTimer.begin(3, \"Linear Combinations for Constraints Testing\", 0);\n\n      for (auto constraint : this->_constraints.constraints) {\n        switch (constraint->type) {\n          case linear: {\n            this->_myTimer.begin(3, \"Linear Combination\", 0);\n\n            this->pickVerifierChallenges(\n                round, TEST_LINEAR_INTERBLOC_CONSTRAINTS,\n                linearConstraintsInterBloc_r, this->_rs.m);\n            this->obtainProverResponses(\n                round, this->_constraints.targets[target], constraint,\n                TEST_LINEAR_INTERBLOC_CONSTRAINTS, linearConstraintsInterBloc_r,\n                linearConstraintsInterBloc_rU);\n\n            this->_myTimer.end(3, \"Linear Combination\", 0);\n          } break;\n\n          case transformation: {\n            transformation_constraint<FieldT> transfCt =\n                *static_cast<const transformation_constraint<FieldT> *>(\n                    constraint);\n\n            this->_myTimer.begin(3, \"Calc Matrix\", 0);\n            if (transfCt.stitching == LinearCombinationsStitching::Regular) {\n              this->calculateRTAmatrix(\n                  linearConstraintsIntraBloc_ri, transfCt, localRandomness,\n                  this->_constraints.targets[target], processed);\n            } else {\n              this->calculateRTAStitchingMatrix(\n                  linearConstraintsStitchingIntraBloc_ri, transfCt,\n                  localRandomness, this->_constraints.targets[target],\n                  processedStitched, iteration);\n            }\n            this->_myTimer.end(3, \"Calc Matrix\", 0);\n          } break;\n\n          case quadratic: {\n            this->_myTimer.begin(3, \"Quadratic\", 0);\n            this->pickVerifierChallenges(round, TEST_QUADRATIC_CONSTRAINTS,\n                                         quadraticConstraints_r, this->_rs.m);\n            this->obtainProverResponses(\n                round, this->_constraints.targets[target], constraint,\n                TEST_QUADRATIC_CONSTRAINTS, quadraticConstraints_r,\n                quadraticConstraints_rU);\n            this->_myTimer.end(3, \"Quadratic\", 0);\n          } break;\n\n          default:\n            throw std::runtime_error(\n                \"incorrect constraint type to obtain prover responses:\" +\n                std::to_string(constraint->type));\n            break;\n        }\n\n        target++;\n      }\n\n      auto vectorInterBloc =\n          [&](std::vector<FieldT> &linearConstraintsInterBloc_rU,\n              const std::vector<size_t> &v_early,\n              const std::vector<size_t> &v) -> void {\n        for (size_t idx = 0; idx < v.size(); idx++) {\n          this->splitWitnessInterbloc(\n              linearConstraintsInterBloc_rU, v_early[idx], v[idx],\n              FieldT(ligero::math::scaleToPrime(*this->_randomness++,\n                                                this->_publicData.modulusIdx)),\n              this->_w_early, this->_w);\n        }\n      };\n\n      /** In the specific case of the full ceremony,\n       * add inter-bloc constraints tying the variables\n       * across the split witness\n       */\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        vectorInterBloc(linearConstraintsInterBloc_rU,\n                        this->_splitWitness.si_early_BlocIdxs,\n                        this->_splitWitness.si_BlocIdxs);\n        vectorInterBloc(linearConstraintsInterBloc_rU,\n                        this->_splitWitness.ei_early_BlocIdxs,\n                        this->_splitWitness.ei_BlocIdxs);\n        if (this->_publicData.modulusIdx < this->_publicData.p)\n          vectorInterBloc(linearConstraintsInterBloc_rU,\n                          this->_splitWitness.ri_early_BlocIdxs,\n                          this->_splitWitness.ri_BlocIdxs);\n      }\n\n      this->_myTimer.end(3, \"Linear Combinations for Constraints Testing\", 0);\n\n      /** Sharing & Committing */\n      /* ================================================================== */\n      this->_myTimer.begin(\n          3, \"Sharing + linear combination intrabloc randomness\", 0);\n\n      if (hasTransformation) {\n        /** Perform linear combinations */\n        linearConstraintsIntraBloc_riU.resize(this->_rs.n, FieldT(0));\n\n        for (size_t row : processed) {\n          /** Pad randomness */\n          localSecretSharing.padIntrablocRandomness(\n              &linearConstraintsIntraBloc_ri[this->_rs.n * row]);\n\n          /** Secret Share Randomness First */\n          localSecretSharing.share(\n              &linearConstraintsIntraBloc_ri[this->_rs.n * row]);\n\n          for (size_t col = 0; col < this->_rs.n; col++) {\n            linearConstraintsIntraBloc_riU[col] +=\n                this->_w[col + (row * this->_rs.n)] *\n                linearConstraintsIntraBloc_ri[col + (row * this->_rs.n)];\n          }\n        }\n\n        /** Adding Blinding */\n        for (size_t col = 0; col < this->_rs.n; col++) {\n          linearConstraintsIntraBloc_riU[col] +=\n              this->_w[col +\n                       ((this->_rs.m + offsetIntrablocBlinding[iteration]) *\n                        this->_rs.n)];\n        }\n\n#ifndef NDEBUG\n        /** Sanity check */\n        std::vector<FieldT> check;\n        for (size_t col = 0; col < this->_rs.n; col++) {\n          check.push_back(this->_w[col + ((this->_rs.m +\n                                           offsetIntrablocBlinding[iteration]) *\n                                          this->_rs.n)]);\n        }\n\n        localSecretSharing.reconstruct(&check[0], false);\n\n        FieldT sanityCheck(0);\n        for (size_t col = 0; col < this->_l; col++) {\n          sanityCheck += check[col];\n        }\n\n        assert(sanityCheck == FieldT(0));\n#endif\n      }\n\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        /** Perform linear combinations */\n        linearConstraintsStitchingIntraBloc_riU.resize(this->_rs.n, FieldT(0));\n\n        for (size_t row : processedStitched) {\n          /** Pad randomness */\n          localSecretSharing.padIntrablocRandomness(\n              &linearConstraintsStitchingIntraBloc_ri[this->_rs.n * row]);\n\n          /** Secret Share Randomness First */\n          localSecretSharing.share(\n              &linearConstraintsStitchingIntraBloc_ri[this->_rs.n * row]);\n\n          for (size_t col = 0; col < this->_rs.n; col++) {\n            linearConstraintsStitchingIntraBloc_riU[col] +=\n                this->_w[col + (row * this->_rs.n)] *\n                linearConstraintsStitchingIntraBloc_ri[col +\n                                                       (row * this->_rs.n)];\n          }\n        }\n\n        /** Adding Blinding */\n        for (size_t col = 0; col < this->_rs.n; col++) {\n          linearConstraintsStitchingIntraBloc_riU[col] +=\n              this->_w[col +\n                       ((this->_rs.m + offsetStitchingBlinding[iteration]) *\n                        this->_rs.n)];\n        }\n      }\n\n      this->_myTimer.end(3, \"Sharing + linear combination intrabloc randomness\",\n                         0);\n\n      /** Prepare for a new protocol round */\n      this->_round = round;\n\n      /** Populate the transcript */\n      linearCombinations.insert(std::pair<int, std::vector<FieldT>>(\n          TEST_INTERLEAVED, interleaved_rU));\n      linearCombinations.insert(std::pair<int, std::vector<FieldT>>(\n          TEST_LINEAR_INTERBLOC_CONSTRAINTS, linearConstraintsInterBloc_rU));\n      linearCombinations.insert(std::pair<int, std::vector<FieldT>>(\n          TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS,\n          linearConstraintsStitchingIntraBloc_riU));\n      linearCombinations.insert(std::pair<int, std::vector<FieldT>>(\n          TEST_LINEAR_INTRABLOC_CONSTRAINTS, linearConstraintsIntraBloc_riU));\n      linearCombinations.insert(std::pair<int, std::vector<FieldT>>(\n          TEST_QUADRATIC_CONSTRAINTS, quadraticConstraints_rU));\n      this->_transcript[round].proverResponsesLinearCombinations.emplace_back(\n          linearCombinations);\n\n#ifndef NDEBUG\n      /** Display Randomness */\n      displayVector(\",Prover,local, Verifier LDT Combinations Challenge:\",\n                    interleaved_r);\n      displayVector(\n          \",Prover,local, Verifier Linear Interbloc Constraints Combinations \"\n          \"Challenge:\",\n          linearConstraintsInterBloc_r);\n      if (hasTransformation)\n        displayVector(\n            \",Prover,local, Verifier Linear Intrabloc Constraints Combinations \"\n            \"Challenge:\",\n            linearConstraintsIntraBloc_ri);\n      displayVector(\n          \",Prover,local, Verifier Quadratic Constraints Combinations \"\n          \"Challenge:\",\n          quadraticConstraints_r);\n\n      /** Display Linear Combinations */\n      displayVector(\",Prover,transcript, Prover LDT Response:\", interleaved_rU);\n      displayVector(\n          \",Prover,transcript, Prover Interbloc Constraints Response:\",\n          linearConstraintsInterBloc_rU);\n      displayVector(\n          \",Prover,transcript, Prover Intrabloc Stitching Constraints \"\n          \"Response:\",\n          linearConstraintsStitchingIntraBloc_riU);\n      displayVector(\n          \",Prover,transcript, Prover Sigma Protocol Constraints Response:\",\n          linearConstraintsSigma_rU);\n      displayVector(\n          \",Prover,transcript, Prover Intrabloc Constraints Response:\",\n          linearConstraintsIntraBloc_riU);\n      displayVector(\n          \",Prover,transcript, Prover Quadratic Constraints Response:\",\n          quadraticConstraints_rU);\n#endif\n\n      /** Free Randomness */\n      free(this->_alloc);\n    }\n\n    /** Verifier Checking Certain Columns */\n    /* ==================================================================== */\n\n    /** Source Randomness */\n    this->_myTimer.begin(3, \"Pick Randomness to Open Up Columns\", 0);\n    this->pickFiatShamirRandomness(this->_t, this->_transcript);\n    this->_myTimer.end(3, \"Pick Randomness to Open Up Columns\", 0);\n\n    this->_myTimer.begin(3, \"Decommit Columns\", 0);\n\n    /** Open columns */\n    this->pickVerifierChallenges(\n        round, OPEN_COLUMNS, this->_transcript[round].verifierColumnQueries);\n    displayVector(\",Prover,local, Opening Columns:\",\n                  this->_transcript[round].verifierColumnQueries);\n\n    /** Free Randomness */\n    free(this->_alloc);\n\n    /** Test out the columns */\n    for (size_t idx = 0;\n         idx < this->_transcript[round].verifierColumnQueries.size(); idx++) {\n      assert(this->_transcript[round].verifierColumnQueries[idx] <\n             (size_t)this->_rs.n);\n    }\n\n    /** Add to transcript round */\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      this->_transcript[round].proverDecommitment_early =\n          proverCCS_early.performProverDecommit(\n              this->_transcript[round].verifierColumnQueries);\n    }\n\n    this->_transcript[round].proverDecommitment =\n        proverCCS.performProverDecommit(\n            this->_transcript[round].verifierColumnQueries);\n\n#ifndef NDEBUG\n    displayVector(\",Prover,transcript, Column 1 Content:\",\n                  this->_transcript[round].proverDecommitment.contents.front());\n    displayVector(\",Prover,transcript, Column q Content:\",\n                  this->_transcript[round].proverDecommitment.contents.back());\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      displayVector(\n          \",Prover,transcript, Column 1 Content:\",\n          this->_transcript[round].proverDecommitment_early.contents.front());\n      displayVector(\n          \",Prover,transcript, Column q Content:\",\n          this->_transcript[round].proverDecommitment_early.contents.back());\n    }\n#endif\n\n    this->_myTimer.end(3, \"Decommit Columns\", 0);\n  }\n};\n\ntemplate <typename FieldT>\nclass Verifier : public NonInteractiveArgument<FieldT> {\n  const size_t _l;\n\n public:\n  /** Constructor for the verifier */\n  Verifier(Statements statement, InterleavedRSCode &irs, size_t t,\n           size_t blockSize,\n           const hash::HashIntegerSeedGeneratorF<FieldT> &generator,\n           const hash::HashStringSeedGeneratorF &generatorString,\n           ligero::MTParameters<FieldT> &mt, PublicData &pdata,\n           SigmaProtocolPublicData &spdata, SecretData &sdata,\n           void (*computeSmall)(uint64_t *, uint64_t const *),\n           void (*computeLarge)(uint64_t *, uint64_t const *),\n           std::string &hashedPublicData)\n      : _l(blockSize),\n        NonInteractiveArgument<FieldT>(\n            statement, irs, t, blockSize, generator, generatorString, mt, pdata,\n            spdata, sdata, computeSmall, computeLarge, hashedPublicData) {\n    /** By definition, the verifier does not have access to the secret data */\n    this->_secretData.isAvailable = false;\n  };\n\n  /** Run tests */\n  void test(int type, vector<FieldT> &rU,\n            ligero::SecretSharingInterface<FieldT> &secretSharing) {\n    bool success = true;\n\n    switch (type) {\n      case TEST_INTERLEAVED:\n        success = secretSharing.degreeTest(&rU[0]);\n        break;\n      case TEST_LINEAR_INTERBLOC_CONSTRAINTS:\n        success = secretSharing.zeroTest(&rU[0]);\n        break;\n      case TEST_LINEAR_INTRABLOC_CONSTRAINTS:\n        success = secretSharing.zeroSumTest(&rU[0]);\n        break;\n      case TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS:\n        this->_stitching = secretSharing.sumReconstruct(&rU[0]).getValue();\n        break;\n      case TEST_QUADRATIC_CONSTRAINTS:\n        success = secretSharing.zeroTest(&rU[0], true);\n        break;\n      default:\n        throw std::runtime_error(\"incorrect test type:\" + std::to_string(type));\n        break;\n    }\n\n    if (success)\n      DBG(\"Success:\" << testDescription[type]);\n    else\n      throw failedTest(\n          (std::string(\"test failed:\") + testDescription[type]).c_str());\n  }\n\n  /** Compares linear combinations calculated by the verifier for the opened\n   * columns with those provided by the prover for the entire witness\n   * @param rU reference to linear combinations for the entire witness provided\n   * by the prover\n   * @param Q indices of the opened columns\n   * @param c_rUq reference to the linear combinations for the opened columns\n   */\n  bool compare(const vector<FieldT> &rU, const vector<size_t> &Q,\n               const vector<FieldT> &c_rUq) {\n    bool success = true;\n    for (size_t i = 0; i < Q.size(); i++) {\n      if (!(rU[Q[i]] == c_rUq[i])) {\n        return false;\n      }\n    }\n\n    return success;\n  }\n\n  /** Checks consistency of the linear combinations provided by the prover with\n   * the calculations of the verifier for the opened columns\n   * @param r simulated verifier's challenges for the main witness\n   * @param r_early simulated verifier's challenges for the early witness\n   * @param rU reference to linear combinations for the entire witness provided\n   * by the prover\n   * @param Q indices of the opened columns\n   * @param Uq reference to the matrix of opened columns for the main witness\n   * @param Uq_early reference to the matrix of opened columns for the early\n   * witness\n   */\n  void checkConsistency(const vector<FieldT> &r, const vector<FieldT> &r_early,\n                        const vector<FieldT> &rU, const vector<size_t> &Q,\n                        const std::vector<std::vector<FieldT>> &Uq,\n                        const std::vector<std::vector<FieldT>> &Uq_early) {\n    std::vector<FieldT> c_rUq;\n\n    this->interbloc(c_rUq, r, Uq);\n    this->interbloc(c_rUq, r_early, Uq_early);\n\n    if (compare(rU, Q, c_rUq))\n      DBG(\"Success: consistency \" << testDescription[TEST_INTERLEAVED]);\n    else\n      throw failedTest((std::string(\"consistency check failed:\") +\n                        testDescription[TEST_INTERLEAVED])\n                           .c_str());\n  }\n\n  /** verifier helper function updating the prover's response to the simulated\n   * verifier's challenges for the opened columns\n   * @param type the type of underlying constraint\n   * @param c_rUq reference to the prover's response (linear combinations for\n   * the opened columns as a vector)\n   * @param r simulated verifier's challenges for the main witness\n   * @param Q indices of the opened columns\n   * @param Uq reference to the matrix of opened columns for the main witness\n   * @param processed set of blocks involved in the linear constraint\n   * @param iteration current iteration within the current round\n   * witness\n   */\n  void linearCombinationPerConstraint(\n      int type, std::vector<FieldT> &c_rUq, std::vector<FieldT> &r,\n      const vector<size_t> &Q, const std::vector<std::vector<FieldT>> &Uq,\n      std::unordered_set<size_t> &processed, uint8_t iteration) {\n    /** Have The Secret Sharing Interface Ready */\n    ligero::SecretSharingInterface<FieldT> localSecretSharing(\n        this->_publicData.modulusIdx, (size_t)this->_l, (size_t)this->_rs.k,\n        (size_t)this->_rs.n, this->_computeSmall, this->_computeLarge);\n\n    for (auto idx : processed) {\n      localSecretSharing.padIntrablocRandomness(&r[0] + (idx * this->_rs.n));\n      localSecretSharing.share(&r[0] + (idx * this->_rs.n));\n    }\n\n    switch (type) {\n      case TEST_LINEAR_INTRABLOC_CONSTRAINTS:\n        this->intrabloc(c_rUq, r, Uq, Q, processed, iteration);\n        break;\n      case TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS:\n        this->intrablocStitching(c_rUq, r, Uq, Q, processed, iteration);\n        break;\n      default:\n        throw internalError(\"incorrect consistency check type:\" +\n                            testDescription[type]);\n        break;\n    }\n  }\n\n  /** verifier helper function updating the prover's response to the simulated\n   * verifier's challenges for the opened columns for a specific constraint\n   * @param type the type of underlying constraint\n   * @param c_rUq reference to the prover's response (linear combinations for\n   * the opened columns as a vector)\n   * @param ct pointer to the contraint being handled\n   * @param r simulated verifier's challenges for the main witness\n   * @param Q indices of the opened columns\n   * @param Uq reference to the matrix of opened columns for the main witness\n   * @param processed set of blocks involved in the linear constraint\n   * @param iteration current iteration within the current round\n   * witness\n   */\n  void linearCombinationPerConstraint(\n      int type, std::vector<FieldT> &c_rUq, constraint *ct, size_t target,\n      const FieldT &r, const vector<size_t> &Q,\n      const std::vector<std::vector<FieldT>> &Uq) {\n    switch (type) {\n      case TEST_QUADRATIC_CONSTRAINTS: {\n        quadratic_constraint<FieldT> constraint =\n            *static_cast<const quadratic_constraint<FieldT> *>(ct);\n        this->interbloc(c_rUq, constraint.left_block, constraint.right_block,\n                        constraint.scalar, target, r, Uq);\n      } break;\n      case TEST_LINEAR_INTERBLOC_CONSTRAINTS: {\n        linear_constraint<FieldT> constraint =\n            *static_cast<const linear_constraint<FieldT> *>(ct);\n        this->interbloc(c_rUq, constraint.block, constraint.scalar, target, r,\n                        Uq);\n      } break;\n      default:\n        throw internalError(\"incorrect consistency check type:\" +\n                            testDescription[type]);\n        break;\n    }\n  }\n\n  /** Run a round of the protocol for the verifier\n   * @param round the current round\n   * @param earlyOnly if true, only generate and commit to the merkle tree for\n   * the early witness\n   */\n  void runRound(size_t round, bool earlyOnly) {\n    /** Have The Secret Sharing Interface Ready */\n    ligero::SecretSharingInterface<FieldT> localSecretSharing(\n        this->_publicData.modulusIdx, (size_t)this->_l, (size_t)this->_rs.k,\n        (size_t)this->_rs.n, this->_computeSmall, this->_computeLarge);\n\n    /** Prepare this transcript round */\n    FullFSTranscript<FieldT> replicatingTranscript;\n\n    if (round > 0) {\n      replicatingTranscript.resize(round - 1);\n\n      for (size_t i = 0; i < round; i++) {\n        replicatingTranscript[i].proverCommitment.swap(\n            this->_transcript[i].proverCommitment);\n        replicatingTranscript[i].proverResponsesLinearCombinations.swap(\n            this->_transcript[i].proverResponsesLinearCombinations);\n        replicatingTranscript[i].verifierColumnQueries.swap(\n            this->_transcript[i].verifierColumnQueries);\n\n        replicatingTranscript[i].proverDecommitment.randomnessHashes.swap(\n            this->_transcript[i].proverDecommitment.randomnessHashes);\n        replicatingTranscript[i].proverDecommitment.auxiliaryHashes.swap(\n            this->_transcript[i].proverDecommitment.auxiliaryHashes);\n        replicatingTranscript[i].proverDecommitment.contentHashes.swap(\n            this->_transcript[i].proverDecommitment.contentHashes);\n        replicatingTranscript[i].proverDecommitment.contents.swap(\n            this->_transcript[i].proverDecommitment.contents);\n        replicatingTranscript[i].proverDecommitment.positions.swap(\n            this->_transcript[i].proverDecommitment.positions);\n\n        if ((this->_statement == Statements::RSACeremony) ||\n            (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n          replicatingTranscript[i].proverCommitment_early.swap(\n              this->_transcript[i].proverCommitment_early);\n\n          replicatingTranscript[i]\n              .proverDecommitment_early.randomnessHashes.swap(\n                  this->_transcript[i]\n                      .proverDecommitment_early.randomnessHashes);\n          replicatingTranscript[i]\n              .proverDecommitment_early.auxiliaryHashes.swap(\n                  this->_transcript[i]\n                      .proverDecommitment_early.auxiliaryHashes);\n          replicatingTranscript[i].proverDecommitment_early.contentHashes.swap(\n              this->_transcript[i].proverDecommitment_early.contentHashes);\n          replicatingTranscript[i].proverDecommitment_early.contents.swap(\n              this->_transcript[i].proverDecommitment_early.contents);\n          replicatingTranscript[i].proverDecommitment_early.positions.swap(\n              this->_transcript[i].proverDecommitment_early.positions);\n        }\n      }\n    }\n\n    roundFSTranscript<FieldT> current;\n    replicatingTranscript.emplace_back(current);\n\n    roundFSTranscript<FieldT> &transcriptRound = this->_transcript[round];\n\n    /** Instantiate Tests */\n    VerifierColumnCS<FieldT> verifierCCS_early(this->_mtParams_early);\n    VerifierColumnCS<FieldT> verifierCCS(this->_mtParams);\n\n    this->_myTimer.begin(3, \"Estimate Randomness\", 0);\n    bool hasTransformation = false;\n\n    /** Estimate All Randomness */\n    size_t sizeRandomness = this->_rs.m; /** LDT testing */\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      sizeRandomness +=\n          this->_rs_early.m + this->_splitWitness.size(this->_publicData);\n    }\n\n    for (auto constraint : this->_constraints.constraints) {\n      switch (constraint->type) {\n        case linear:\n          sizeRandomness++;\n          break;\n\n        case transformation:\n          if (!hasTransformation) {\n            hasTransformation = true;\n            sizeRandomness += this->_rs.m * this->_l;\n          }\n          break;\n\n        case quadratic:\n          sizeRandomness++;\n          break;\n\n        default:\n          throw std::runtime_error(\n              \"incorrect constraint type to obtain prover responses:\" +\n              std::to_string(constraint->type));\n          break;\n      }\n    }\n\n    this->_myTimer.end(3, \"Estimate Randomness\", 0);\n\n    /** Open columns */\n    /* =========================================================================\n     */\n\n    /** Replicate the state of the prover transcript */\n    replicatingTranscript.back().proverCommitment.swap(\n        transcriptRound.proverCommitment);\n    replicatingTranscript.back().proverResponsesLinearCombinations.swap(\n        transcriptRound.proverResponsesLinearCombinations);\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      replicatingTranscript.back().proverCommitment_early.swap(\n          transcriptRound.proverCommitment_early);\n    }\n\n    /** Source Randomness */\n    this->_myTimer.begin(3, \"Pick Randomness to Open Up Columns\", 0);\n    this->pickFiatShamirRandomness(this->_t, replicatingTranscript);\n    this->_myTimer.end(3, \"Pick Randomness to Open Up Columns\", 0);\n\n    /** Pick columns */\n    this->pickVerifierChallenges(\n        round, OPEN_COLUMNS,\n        replicatingTranscript.back().verifierColumnQueries);\n\n    vector<size_t> &Q = replicatingTranscript.back().verifierColumnQueries;\n    displayVector(\",Verifier,local, Opening Columns:\", Q);\n\n    /** Free Randomness */\n    free(this->_alloc);\n\n    DBG(\"Verifying decommitment root for main witness.\");\n\n    /** Now verify the decommitment vs. initial commitment */\n    if (!verifierCCS.verify(\n            replicatingTranscript.back().proverCommitment,\n            transcriptRound.proverDecommitment,\n            replicatingTranscript.back().verifierColumnQueries)) {\n      throw failedTest(\"openColumns|contents\");\n    }\n\n    DBG(\"Verification successful for decommitment root for main witness.\");\n    DBG(\"Verifying decommitment root for early witness.\");\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      if (!verifierCCS_early.verify(\n              replicatingTranscript.back().proverCommitment_early,\n              transcriptRound.proverDecommitment_early,\n              replicatingTranscript.back().verifierColumnQueries)) {\n        throw failedTest(\"openColumns|contents\");\n      }\n    }\n\n    DBG(\"Verification successful for decommitment root for early witness.\");\n\n    /** The transcript is already populated, see what we read in */\n    std::vector<std::vector<FieldT>> &Uq =\n        transcriptRound.proverDecommitment.contents;\n    std::vector<std::vector<FieldT>> &Uq_early =\n        transcriptRound.proverDecommitment_early.contents;\n\n    /** Debug: Opened Column Content */\n    displayVector(\",Verifier,transcript, First Opened Column:\", Uq[0]);\n\n    /** Unwind the linear combinations */\n    replicatingTranscript.back().proverResponsesLinearCombinations.swap(\n        transcriptRound.proverResponsesLinearCombinations);\n\n    /** Verifying Linear Combinations */\n    /* =========================================================================\n     */\n\n    for (size_t iteration = 0; iteration < numberOfIterations; iteration++) {\n      /** Replicate the state of the prover transcript */\n      if (iteration > 0) {\n        std::unordered_map<size_t, std::vector<FieldT>> a;\n\n        replicatingTranscript.back()\n            .proverResponsesLinearCombinations.push_back(a);\n        replicatingTranscript.back()\n            .proverResponsesLinearCombinations.back()\n            .swap(this->_transcript[round]\n                      .proverResponsesLinearCombinations[iteration - 1]);\n      }\n\n      /** Pick Randomness for this iteration */\n      sizeRandomness += this->_constraintSystemRandomnessSize;\n\n      this->_myTimer.begin(3, \"Pick Randomness\", 0);\n      this->pickFiatShamirRandomness(sizeRandomness, replicatingTranscript);\n      this->_myTimer.end(3, \"Pick Randomness\", 0);\n\n      /** Rebuild the constraint system based on this round's randomness\n       * We are locally scoping objects so as to invoke their destructor\n       * immediately; they won't be needed here\n       */\n      {\n        this->cleanup();\n\n        builder<FieldT> bob(this->_l);\n        vector<vector<FieldT>> extendedWitness2DVector;\n\n        this->_myTimer.begin(3, \"Express NP statement\", 0);\n        expressNPStatement<FieldT> expressStatement(\n            this->_publicData, this->_sigmaProtocolPublicData,\n            this->_secretData, bob, &extendedWitness2DVector, this->_l,\n            this->_randomness);\n\n        expressStatement.buildConstraintSet(this->_statement);\n        this->_myTimer.end(3, \"Express NP statement\", 0);\n\n        this->_myTimer.begin(3, \"compile\", 0);\n        this->_constraints = bob.compile(\n            extendedWitness2DVector, false); /** Main functionality to retain */\n        this->_myTimer.end(3, \"compile\", 0);\n      }\n\n      /** Have the \"Verifier\" pick randomness for all tests according to the\n       * Fiat-Shamir transform\n       */\n      std::vector<FieldT> interleaved_r, interleaved_r_early,\n          linearConstraintsInterBloc_r, quadraticConstraints_r,\n          linearConstraintsSigma_r, linearConstraintsIntraBloc_ri,\n          linearConstraintsStitchingIntraBloc_ri;\n\n      /** Read provers' responses from the transcript */\n      std::vector<FieldT> &interleaved_rU =\n          transcriptRound\n              .proverResponsesLinearCombinations[iteration][TEST_INTERLEAVED];\n      std::vector<FieldT> &linearConstraintsInterBloc_rU =\n          transcriptRound.proverResponsesLinearCombinations\n              [iteration][TEST_LINEAR_INTERBLOC_CONSTRAINTS];\n      std::vector<FieldT> &linearConstraintsStitchingIntraBloc_riU =\n          transcriptRound.proverResponsesLinearCombinations\n              [iteration][TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS];\n      std::vector<FieldT> &linearConstraintsIntraBloc_riU =\n          transcriptRound.proverResponsesLinearCombinations\n              [iteration][TEST_LINEAR_INTRABLOC_CONSTRAINTS];\n      std::vector<FieldT> &quadraticConstraints_rU =\n          transcriptRound\n              .proverResponsesLinearCombinations[iteration]\n                                                [TEST_QUADRATIC_CONSTRAINTS];\n\n      /** Basic Sanity Checks */\n      assert((interleaved_rU.size() == this->_rs.n) ||\n             (interleaved_rU.size() == 0));\n      assert((linearConstraintsInterBloc_rU.size() == this->_rs.n) ||\n             (linearConstraintsInterBloc_rU.size() == 0));\n      assert((linearConstraintsIntraBloc_riU.size() == this->_rs.n) ||\n             (linearConstraintsIntraBloc_riU.size() == 0));\n      assert((linearConstraintsStitchingIntraBloc_riU.size() == this->_rs.n) ||\n             (linearConstraintsStitchingIntraBloc_riU.size() == 0));\n      assert((quadraticConstraints_rU.size() == this->_rs.n) ||\n             (quadraticConstraints_rU.size() == 0));\n\n      /** Pick Randomness for Low Degree Testing */\n      this->pickVerifierChallenges(round, TEST_INTERLEAVED, interleaved_r,\n                                   this->_rs.m);\n\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        this->pickVerifierChallenges(round, TEST_INTERLEAVED,\n                                     interleaved_r_early, this->_rs_early.m);\n      }\n\n      /** Low Degree Testing Debug */\n      displayVector(\",Verifier,local, Verifier LDT Combinations Challenge:\",\n                    interleaved_r);\n      displayVector(\",Verifier,transcript, Prover LDT Response:\",\n                    interleaved_rU);\n\n      /** Low Degree Test */\n      test(TEST_INTERLEAVED, interleaved_rU, localSecretSharing);\n\n      /** Testing constraints */\n      size_t target = 0;\n      std::unordered_set<size_t> processed, processedStitched;\n      std::vector<FieldT> localRandomness;\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        linearConstraintsStitchingIntraBloc_ri.assign(this->_rs.n * this->_rs.m,\n                                                      FieldT(0));\n      }\n\n      /** Intrabloc constraints */\n      this->_myTimer.begin(3, \"Pick Randomness\", 0);\n      this->pickVerifierChallenges(round, TEST_LINEAR_INTRABLOC_CONSTRAINTS,\n                                   localRandomness, this->_rs.m);\n      this->_myTimer.end(3, \"Pick Randomness\", 0);\n\n      if (hasTransformation) {\n        linearConstraintsIntraBloc_ri.assign(this->_rs.n * this->_rs.m,\n                                             FieldT(0));\n      }\n\n      /** Generating randomness for testing constraints */\n      for (auto constraint : this->_constraints.constraints) {\n        switch (constraint->type) {\n          case linear:\n            this->pickVerifierChallenges(\n                round, TEST_LINEAR_INTERBLOC_CONSTRAINTS,\n                linearConstraintsInterBloc_r, this->_rs.m);\n            break;\n\n          case transformation: {\n            transformation_constraint<FieldT> transfCt =\n                *static_cast<const transformation_constraint<FieldT> *>(\n                    constraint);\n            if (transfCt.stitching == LinearCombinationsStitching::Regular) {\n              this->calculateRTAmatrix(\n                  linearConstraintsIntraBloc_ri, transfCt, localRandomness,\n                  this->_constraints.targets[target], processed);\n            } else {\n              this->calculateRTAStitchingMatrix(\n                  linearConstraintsStitchingIntraBloc_ri, transfCt,\n                  localRandomness, this->_constraints.targets[target],\n                  processedStitched, iteration, true);\n            }\n\n          } break;\n\n          case quadratic:\n            this->pickVerifierChallenges(round, TEST_QUADRATIC_CONSTRAINTS,\n                                         quadraticConstraints_r, this->_rs.m);\n            break;\n\n          default:\n            throw std::runtime_error(\"incorrect constraint type for test:\" +\n                                     std::to_string(constraint->type));\n            break;\n        }\n\n        target++;\n      }\n\n      /** Testing */\n\n      /** Aggregate test for each constraint */\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        test(TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS,\n             linearConstraintsStitchingIntraBloc_riU, localSecretSharing);\n      }\n\n      if (linearConstraintsInterBloc_r.size() > 0) {\n        displayVector(\n            \",Verifier,local, Verifier Linear Interbloc Constraints \"\n            \"Combinations Challenge:\",\n            linearConstraintsInterBloc_r);\n        displayVector(\n            \",Verifier,transcript, Prover Interbloc Constraints Response:\",\n            linearConstraintsInterBloc_rU);\n        test(TEST_LINEAR_INTERBLOC_CONSTRAINTS, linearConstraintsInterBloc_rU,\n             localSecretSharing);\n      }\n\n      if (hasTransformation) {\n        displayVector(\n            \",Verifier,local, Verifier Linear Interbloc Constraints \"\n            \"Combinations Challenge:\",\n            linearConstraintsIntraBloc_ri);\n        displayVector(\n            \",Verifier,transcript, Prover Interbloc Constraints Response:\",\n            linearConstraintsIntraBloc_riU);\n        test(TEST_LINEAR_INTRABLOC_CONSTRAINTS, linearConstraintsIntraBloc_riU,\n             localSecretSharing);\n      }\n\n      if (quadraticConstraints_r.size() > 0) {\n        displayVector(\n            \",Verifier,local, Verifier Quadratic Constraints Combinations \"\n            \"Challenge:\",\n            quadraticConstraints_r);\n        displayVector(\n            \",Verifier,transcript, Prover Quadratic Constraints Response:\",\n            quadraticConstraints_rU);\n        test(TEST_QUADRATIC_CONSTRAINTS, quadraticConstraints_rU,\n             localSecretSharing);\n      }\n\n      /** Checking consistency with decommitment */\n      checkConsistency(interleaved_r, interleaved_r_early, interleaved_rU, Q,\n                       Uq, Uq_early);\n\n      /** Read provers' responses from the transcript */\n      std::vector<FieldT> linearConstraintsInterBloc_c_rUq;\n      std::vector<FieldT> linearConstraintsInterBlocSigmaProtocol_c_rUq;\n      std::vector<FieldT> linearConstraintsIntraBloc_c_riUq;\n      std::vector<FieldT> linearConstraintsStitchingIntraBloc_c_riUq;\n      std::vector<FieldT> quadraticConstraints_c_rUq;\n\n      size_t idxLinear = 0, idxTransformation = 0, idxQuadratic = 0;\n      target = 0;\n\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        linearCombinationPerConstraint(\n            TEST_LINEAR_INTRABLOC_STITCHING_CONSTRAINTS,\n            linearConstraintsStitchingIntraBloc_c_riUq,\n            linearConstraintsStitchingIntraBloc_ri, Q, Uq, processedStitched,\n            iteration);\n      }\n\n      if (hasTransformation) {\n        linearCombinationPerConstraint(TEST_LINEAR_INTRABLOC_CONSTRAINTS,\n                                       linearConstraintsIntraBloc_c_riUq,\n                                       linearConstraintsIntraBloc_ri, Q, Uq,\n                                       processed, iteration);\n      }\n\n      for (auto &constraint : this->_constraints.constraints) {\n        switch (constraint->type) {\n          case linear:\n            linearCombinationPerConstraint(\n                TEST_LINEAR_INTERBLOC_CONSTRAINTS,\n                linearConstraintsInterBloc_c_rUq, constraint,\n                this->_constraints.targets[target],\n                linearConstraintsInterBloc_r[idxLinear++], Q, Uq);\n            break;\n\n          case transformation:\n            break;\n\n          case quadratic:\n            linearCombinationPerConstraint(\n                TEST_QUADRATIC_CONSTRAINTS, quadraticConstraints_c_rUq,\n                constraint, this->_constraints.targets[target],\n                quadraticConstraints_r[idxQuadratic++], Q, Uq);\n            break;\n\n          default:\n            throw std::runtime_error(\n                \"incorrect constraint type for checking consistency:\" +\n                std::to_string(constraint->type));\n            break;\n        }\n\n        target++;\n      }\n\n      /** Split Witness Handling */\n      auto vectorInterBloc =\n          [&](std::vector<FieldT> &linearConstraintsInterBloc_c_rUq,\n              const std::vector<size_t> &v_early,\n              const std::vector<size_t> &v) -> void {\n        for (size_t idx = 0; idx < v.size(); idx++) {\n          this->splitWitnessInterbloc(\n              linearConstraintsInterBloc_c_rUq, v_early[idx], v[idx],\n              FieldT(ligero::math::scaleToPrime(*this->_randomness++,\n                                                this->_publicData.modulusIdx)),\n              Uq_early, Uq);\n        }\n      };\n\n      /** In the specific case of the full ceremony,\n       * add inter-bloc constraints tying the variables\n       * across the split witness\n       */\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        if (linearConstraintsInterBloc_c_rUq.size() == 0) {\n          linearConstraintsInterBloc_c_rUq.resize(Uq.size(), FieldT(0));\n        }\n\n        vectorInterBloc(linearConstraintsInterBloc_c_rUq,\n                        this->_splitWitness.si_early_BlocIdxs,\n                        this->_splitWitness.si_BlocIdxs);\n        vectorInterBloc(linearConstraintsInterBloc_c_rUq,\n                        this->_splitWitness.ei_early_BlocIdxs,\n                        this->_splitWitness.ei_BlocIdxs);\n        if (this->_publicData.modulusIdx < this->_publicData.p)\n          vectorInterBloc(linearConstraintsInterBloc_c_rUq,\n                          this->_splitWitness.ri_early_BlocIdxs,\n                          this->_splitWitness.ri_BlocIdxs);\n      }\n\n#ifndef NDEBUG\n      displayVector(\n          \",Verifier,transcript, Verifier Linear Interbloc Constraints \"\n          \"Combinations Challenge Open Col:\",\n          linearConstraintsInterBloc_c_rUq);\n      displayVector(\n          \",Verifier,transcript, Verifier Linear Sigma Protocol Constraints \"\n          \"Combinations Challenge Open Col:\",\n          linearConstraintsInterBlocSigmaProtocol_c_rUq);\n      displayVector(\n          \",Verifier,transcript, Verifier Linear Intrabloc Constraints \"\n          \"Combinations Challenge Open Col:\",\n          linearConstraintsIntraBloc_c_riUq);\n      displayVector(\n          \",Verifier,transcript, Verifier Linear Intrabloc Constraints \"\n          \"Combinations Challenge Open Col:\",\n          linearConstraintsStitchingIntraBloc_c_riUq);\n      displayVector(\n          \",Verifier,transcript, Verifier Quadratic Constraints Combinations \"\n          \"Challenge Open Col:\",\n          quadraticConstraints_c_rUq);\n#endif\n\n      /** Aggregate test for each constraint */\n      if (linearConstraintsInterBloc_r.size() > 0) {\n        if (compare(linearConstraintsInterBloc_rU, Q,\n                    linearConstraintsInterBloc_c_rUq))\n          DBG(\"Success: consistency linearConstraintsInterBloc\");\n        else\n          throw failedTest(\n              (std::string(\n                   \"consistency check failed: linearConstraintsInterBloc\"))\n                  .c_str());\n      }\n\n      if (linearConstraintsIntraBloc_ri.size() > 0) {\n        if (compare(linearConstraintsIntraBloc_riU, Q,\n                    linearConstraintsIntraBloc_c_riUq))\n          DBG(\"Success: consistency linearConstraintsIntraBloc\");\n        else\n          throw failedTest(\n              (std::string(\n                   \"consistency check failed: linearConstraintsIntraBloc\"))\n                  .c_str());\n      }\n\n      if (quadraticConstraints_r.size() > 0) {\n        if (compare(quadraticConstraints_rU, Q, quadraticConstraints_c_rUq))\n          DBG(\"Success: consistency quadraticConstraints\");\n        else\n          throw failedTest(\n              (std::string(\"consistency check failed: quadraticConstraints\"))\n                  .c_str());\n      }\n\n      if ((this->_statement == Statements::RSACeremony) ||\n          (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n        if (compare(linearConstraintsStitchingIntraBloc_riU, Q,\n                    linearConstraintsStitchingIntraBloc_c_riUq))\n          DBG(\"Success: consistency linearConstraintsStitchingIntraBloc\");\n        else\n          throw failedTest((std::string(\"consistency check failed: \"\n                                        \"linearConstraintsStitchingIntraBloc\"))\n                               .c_str());\n      }\n\n      /** Free Randomness */\n      free(this->_alloc);\n    }\n  }\n\n  /** Verify A Zero-Knowledge Proof\n   * @param t full transcript provided by the prover\n   */\n  void verifyProof(FullFSTranscript<FieldT> &t) {\n    this->_myTimer.initialize_timer();\n    this->_transcript = t;\n\n    /** Initialize Fpp */\n    /** =========================== */\n\n    auto assessBlocIdx = [&](auto &builder,\n                             std::vector<size_t> idxs) -> std::vector<size_t> {\n      std::vector<size_t> ret;\n      for (auto idx : idxs) {\n        ret.emplace_back(builder.proof_values_location[idx]);\n      }\n\n      return ret;\n    };\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      /** Build a first witness/constraint system for Early Commitment */\n      /** ================================================================== */\n\n      this->_rs_early = this->_rs;\n      this->_myTimer.begin(\n          2, \"Build Extended Witness & Constraint System For Early Commitment\",\n          0);\n\n      builder<FieldT> helper(this->_l);\n      vector<vector<FieldT>> earlyCommitments2DVector;\n\n      expressNPStatement<FieldT> expressStatementEarlyCommitment(\n          this->_publicData, this->_sigmaProtocolPublicData, this->_secretData,\n          helper, &earlyCommitments2DVector, this->_l, this->_randomness);\n      expressStatementEarlyCommitment.buildConstraintSet(\n          Statements::RSACeremony_EarlyCommitments);\n\n      this->_myTimer.begin(3, \"compile\", 0);\n      this->_constraints_early = helper.compile(earlyCommitments2DVector);\n      this->_myTimer.end(3, \"compile\", 0);\n\n      this->_myTimer.end(\n          2, \"Build Extended Witness & Constraint System For Early Commitment\",\n          0);\n\n      this->_splitWitness.si_early_BlocIdxs = assessBlocIdx(\n          helper, expressStatementEarlyCommitment._siCoefsBlocIds);\n      this->_splitWitness.ei_early_BlocIdxs = assessBlocIdx(\n          helper, expressStatementEarlyCommitment._eiCoefsBlocIds);\n      if (this->_publicData.modulusIdx < this->_publicData.p)\n        this->_splitWitness.ri_early_BlocIdxs = assessBlocIdx(\n            helper, {expressStatementEarlyCommitment._riCoefsBlocId});\n\n      this->_mtParams_early.leavesEntropy = this->_rs_early.m =\n          earlyCommitments2DVector.size() +\n          this->_constraints_early.constant_blocks + 1;\n    }\n\n    /** Building the constraint system and populating the extended witness */\n    /** ================================================================== */\n\n    builder<FieldT> bob(this->_l);\n    vector<vector<FieldT>> extendedWitness2DVector;\n\n    expressNPStatement<FieldT> expressStatement(\n        this->_publicData, this->_sigmaProtocolPublicData, this->_secretData,\n        bob, &extendedWitness2DVector, this->_l, this->_randomness);\n    expressStatement.buildConstraintSet(this->_statement, false);\n\n    this->_constraints = bob.compile(\n        extendedWitness2DVector); /** Main functionality to retain */\n    DBG(this->_constraints.constraints.size());\n\n    /** Dimensioning the circuit accordingly */\n    this->_mtParams.leavesEntropy = this->_rs.m =\n        extendedWitness2DVector.size() + this->_constraints.constant_blocks +\n        nbBlindingRows;\n\n    if ((this->_statement == Statements::RSACeremony) ||\n        (this->_statement == Statements::RSACeremony_Rounds3to6)) {\n      this->_splitWitness.si_BlocIdxs =\n          assessBlocIdx(bob, expressStatement._siBlocs);\n      this->_splitWitness.ei_BlocIdxs =\n          assessBlocIdx(bob, expressStatement._eiBlocs);\n      this->_splitWitness.ri_BlocIdxs =\n          assessBlocIdx(bob, {expressStatement._riCoefsBlocId});\n    }\n\n    /** Here checking that we got the referencing right */\n    this->_uxBlocks = assessBlocIdx(bob, expressStatement._uxBlocs);\n    this->_uzBlocks = assessBlocIdx(bob, expressStatement._uzBlocs);\n\n    this->_siBlocks = assessBlocIdx(bob, expressStatement._siBlocs);\n    this->_eiBlocks = assessBlocIdx(bob, expressStatement._eiBlocs);\n\n    /** Storing for Cross-Moduli Integrity Checking */\n    this->_varBlocks.emplace_back(this->_siBlocks);\n    this->_varBlocks.emplace_back(this->_eiBlocks);\n    this->_varBlocks.emplace_back(this->_uxBlocks);\n    this->_varBlocks.emplace_back(this->_uzBlocks);\n\n    /** Generating and sending the proof */\n    /** ================================ */\n\n    /** Dimension Randomness for the Constraint System */\n    this->_constraintSystemRandomnessSize = determineCSrandomnessSize(\n        this->_statement, this->_publicData.ptNumberEvaluation);\n\n    DBG(\"Processing New Protocol Round.\");\n\n    this->_myTimer.begin(2, \"Verifying the Proof\", 0);\n    this->runProtocol(numberOfRounds);\n    this->_myTimer.end(2, \"Verifying the Proof\", 0);\n  }\n};\n\n}  // namespace zksnark\n}  // namespace ligero\n", "meta": {"hexsha": "47ccb3a1b62d80a5d7c7908e5aec059fa8b9919b", "size": 108277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ZkArgument.hpp", "max_stars_repo_name": "JustinDrake/LigeroRSA", "max_stars_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "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/ZkArgument.hpp", "max_issues_repo_name": "JustinDrake/LigeroRSA", "max_issues_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "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/ZkArgument.hpp", "max_forks_repo_name": "JustinDrake/LigeroRSA", "max_forks_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-31T15:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T15:48:20.000Z", "avg_line_length": 38.601426025, "max_line_length": 95, "alphanum_fraction": 0.6227176593, "num_tokens": 25242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19196657947290122}}
{"text": "#include <iostream>\n#include <sstream>\n#include <cfloat>\n#include <set>\n\n#include <armadillo>\n\n#include <cpp-argparse/OptionParser.h>\n#include <besiq/io/covariates.hpp>\n#include <besiq/stats/snp_count.hpp>\n#include <glm/irls.hpp>\n#include <glm/models/normal.hpp>\n#include <glm/models/binomial.hpp>\n\n#include <plink/plink_file.hpp>\n#include <dcdflib/libdcdf.hpp>\n\nusing namespace arma;\nusing namespace optparse;\n\nconst std::string USAGE = \"besiq-mglm [OPTIONS] plink_file\";\nconst std::string DESCRIPTION = \"Multivariate additive GLM.\";\nconst std::string VERSION = \"besiq 0.0.1\";\nconst std::string EPILOG = \"\";\n\nstd::set<std::string>\nparse_variants(std::ifstream &input_file)\n{\n    std::set<std::string> variant_set;\n    std::string variant;\n    while( input_file >> variant )\n    {\n        variant_set.insert( variant );\n    }\n\n    return variant_set;\n}\n\nstd::vector<std::string>\ncreate_design_matrix(genotype_matrix_ptr genotypes, const arma::mat &cov, const std::set<std::string> &variant_set, arma::uvec &missing, arma::mat &X)\n{\n\n    bool all_variants = variant_set.size( ) == 0;\n    size_t num_variants = variant_set.size( );\n    if( all_variants )\n    {\n        num_variants = genotypes->size( );\n    }\n\n    X.resize( missing.n_elem, num_variants + cov.n_cols + 1 );\n\n    std::vector<std::string> names = genotypes->get_snp_names( );\n    std::vector<std::string> valid_names;\n    size_t cur_col = 0;\n    for(int i = 0; i < genotypes->size( ); i++)\n    {\n        if( !all_variants && variant_set.count( names[ i ] ) <= 0 )\n        {\n            continue;\n        }\n        \n        snp_row &cur_row = genotypes->get_row( i );\n        for(int j = 0; j < cur_row.size( ); j++)\n        {\n            if( cur_row[ j ] != 3 )\n            {\n                X( j, cur_col ) = cur_row[ j ];   \n            }\n            else\n            {\n                X( j, cur_col ) = 0;\n                missing[ j ] = 1;\n            }\n        }\n\n        if( arma::var( X.col( cur_col ) ) > 1e-4 )\n        {\n            valid_names.push_back( names[ i ] );\n            cur_col++;\n        }\n    }\n\n    for(int i = 0; i < cov.n_cols; i++)\n    {\n        X.col( cur_col ) = cov.col( i );\n        cur_col++;\n    }\n\n    X.col( cur_col ) = arma::ones<arma::vec>( missing.n_elem );\n    cur_col++;\n    X.resize( missing.n_elem, cur_col );\n\n    return valid_names;\n}\n\nint\nmain(int argc, char *argv[])\n{\n    char const* const model_choices[] = { \"binomial\", \"normal\" };\n    char const* const link_choices[] = { \"logit\", \"logc\", \"odds\", \"identity\", \"log\" };\n    OptionParser parser = OptionParser( ).usage( USAGE )\n                                         .version( VERSION )\n                                         .description( DESCRIPTION )\n                                         .epilog( EPILOG ); \n \n    parser.add_option( \"-p\", \"--pheno\" ).help( \"Read phenotypes from this file instead of a plink file.\" );\n    parser.add_option( \"-e\", \"--mpheno\" ).help( \"Name of the phenotype that you want to read (if there are more than one in the phenotype file).\" );\n    parser.add_option( \"-c\", \"--cov\" ).action( \"store\" ).type( \"string\" ).metavar( \"filename\" ).help( \"Performs the analysis by including the covariates in this file.\" );\n    parser.add_option( \"-s\", \"--variants\" ).action( \"store\" ).type( \"string\" ).metavar( \"filename\" ).help( \"Only use these variants.\" );\n    parser.add_option( \"-o\", \"--out\" ).help( \"The output file that will contain the results (binary).\" );\n    parser.add_option( \"-t\", \"--threshold\" ).help( \"Only output p-values less or equal to this value.\" ).set_default( 1.0 );\n    parser.add_option( \"-m\", \"--model\" ).choices( &model_choices[ 0 ], &model_choices[ 2 ] ).metavar( \"model\" ).help( \"The model to use for the phenotype, 'binomial' or 'normal', default = 'binomial'.\" ).set_default( \"binomial\" );\n    parser.add_option( \"-l\", \"--link-function\" ).choices( &link_choices[ 0 ], &link_choices[ 5 ] ).metavar( \"link\" ).help( \"The link function, or scale, that is used for the penetrance: 'logit' log(p/(1-p)), 'logc' log(1 - p), 'odds' p/(1-p), 'identity' p, 'log' log(p).\" );\n\n    Values options = parser.parse_args( argc, argv );\n    if( parser.args( ).size( ) != 1 )\n    {\n        parser.print_help( );\n        exit( 1 );\n    }\n\n    std::ios_base::sync_with_stdio( false );\n    \n    /* Read all genotypes */\n    plink_file_ptr genotype_file = open_plink_file( parser.args( )[ 0 ] );\n    genotype_matrix_ptr genotypes = create_genotype_matrix( genotype_file );\n    std::vector<std::string> order = genotype_file->get_sample_iids( );\n\n    /* Make error streams separate from stdout */\n    arma::set_stream_err1( std::cerr );\n    arma::set_stream_err2( std::cerr );\n\n    /* Parse phenotypes */\n    arma::uvec missing = arma::zeros<arma::uvec>( genotype_file->get_samples( ).size( ) );\n    arma::vec phenotype;\n    arma::mat cov;\n    std::vector<std::string> cov_names;\n    if( options.is_set( \"pheno\" ) )\n    {\n        std::ifstream phenotype_file( options[ \"pheno\" ].c_str( ) );\n        phenotype = parse_phenotypes( phenotype_file, missing, order, options[ \"mpheno\" ] );\n    }\n    else\n    {\n        phenotype = create_phenotype_vector( genotype_file->get_samples( ), missing );\n    }\n    if( options.is_set( \"cov\" ) )\n    {\n        std::ifstream covariate_file( options[ \"cov\" ].c_str( ) );\n        cov = parse_covariate_matrix( covariate_file, missing, order, &cov_names );\n    }\n\n    std::set<std::string> variant_set;\n    if( options.is_set( \"variants\" ) )\n    {\n        std::ifstream variant_file( options[ \"variants\" ].c_str( ) );\n        variant_set = parse_variants( variant_file );\n    }\n\n    /* Open output stream */\n    std::ofstream output_file;\n    if( options.is_set( \"out\" ) )\n    {\n        output_file.open( options[ \"out\" ].c_str( ) );\n    }\n    std::ostream &out = options.is_set( \"out\" ) ? output_file : std::cout;\n\n    arma::mat X;\n    std::vector<std::string> variant_names = create_design_matrix( genotypes, cov, variant_set, missing, X );\n    \n    glm_model *model = NULL;\n    if( options[ \"model\" ] == \"binomial\" )\n    {\n        std::string link = \"logit\";\n        if( options.is_set( \"link_function\" ) )\n        {\n            link = options[ \"link_function\" ];\n        }\n\n        model= new binomial( link );\n    }\n    else if( options[ \"model\" ] == \"normal\" )\n    {\n        std::string link = \"identity\";\n        if( options.is_set( \"link_function\" ) )\n        {\n            link = options[ \"link_function\" ];\n        }\n\n        model = new normal( link );\n    }\n\n    glm_info result;\n    arma::vec beta = irls( X, phenotype, missing, *model, result);\n\n    /* The design matrix is constructed such that the variants appear first */\n    out << \"snp\\tbeta\\tse_beta\\tpvalue\\n\";\n    if( result.success && result.converged )\n    {\n        for(int i = 0; i < variant_names.size( ); i++)\n        {\n            out << variant_names[ i ] << \"\\t\" <<\n                beta[ i ] << \"\\t\" <<\n                result.se_beta[ i ] << \"\\t\" <<\n                result.p_value[ i ] << \"\\n\";\n        }\n    }\n\n    if( model != NULL )\n    {\n        delete model; \n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "2ab0218f6dcc1c5c1f2c42fc77449a2098014ff4", "size": 7095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/besiq_mglm.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "src/besiq_mglm.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "src/besiq_mglm.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 32.8472222222, "max_line_length": 274, "alphanum_fraction": 0.5740662438, "num_tokens": 1924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.1919467350731556}}
{"text": "#include \"Sensor.h\"\n#include <boost/iterator/iterator_concepts.hpp>\n\n\nusing namespace A2O;\nusing namespace Eigen;\n\nSensor::Sensor(ISensorConfig::ConstPtr config)\n      : Sensor(config->getName(), config->getPerceptorName(), config->getPose())\n{\n\n}\n\nSensor::Sensor(const std::string& name,\n\t       const std::string& perceptorName,\n\t       const Pose3D& pose)\n      : _name(name), _perceptorName(perceptorName), _lastMeasurementTime(0), _pose(pose)\n{\n  \n}\n\nSensor::~Sensor()\n{\n  \n}\n\nconst std::string& Sensor::getName() const\n{\n  return _name;\n}\n\nconst std::string& Sensor::getPerceptorName() const\n{\n  return _perceptorName;\n}\n\nconst Pose3D& Sensor::getPose() const\n{\n  return _pose;\n}\n\nconst long& Sensor::getLastMeasurementTime() const\n{\n  return _lastMeasurementTime;\n}\n\nconst Vector3d Sensor::toCarSystem(const Vector3d& localPos) const\n{\n  return _pose * localPos;\n}\n\nconst Quaterniond Sensor::toCarSystem(const Quaterniond& localOrientation) const\n{\n  return _pose.getOrientation() * localOrientation;\n}\n\nconst Pose3D Sensor::toCarSystem(const Pose3D& localPose) const\n{\n  return _pose * localPose;\n}\n\nconst bool Sensor::isInitialized() const\n{\n  return true;\n}\n", "meta": {"hexsha": "79d9b09027f86a37620b17b09f6ea679471125ee", "size": 1168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/aadcUser/src/HSOG_Runtime/a2o/carmodel/impl/Sensor.cpp", "max_stars_repo_name": "AppliedAutonomyOffenburg/AADC_2015_A2O", "max_stars_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T21:39:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-09T21:39:29.000Z", "max_issues_repo_path": "src/aadcUser/src/HSOG_Runtime/a2o/carmodel/impl/Sensor.cpp", "max_issues_repo_name": "TeamAutonomousCarOffenburg/A2O_2015", "max_issues_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "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": "src/aadcUser/src/HSOG_Runtime/a2o/carmodel/impl/Sensor.cpp", "max_forks_repo_name": "TeamAutonomousCarOffenburg/A2O_2015", "max_forks_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-04-05T06:34:08.000Z", "max_forks_repo_forks_event_max_datetime": "2016-04-05T06:34:08.000Z", "avg_line_length": 17.696969697, "max_line_length": 88, "alphanum_fraction": 0.7251712329, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.19188053494651464}}
{"text": "//\n// Created by june on 19. 12. 5..\n//\n\n// from ros-control meta packages\n#include <ros/ros.h>\n#include <controller_interface/controller.h>\n#include <hardware_interface/joint_command_interface.h>\n#include <pluginlib/class_list_macros.h>\n#include <urdf/model.h>\n#include <sensor_msgs/JointState.h>\n#include <realtime_tools/realtime_buffer.h>\n#include <realtime_tools/realtime_publisher.h>\n#include \"dualarm_controller/JointDesiredState.h\"\n#include \"dualarm_controller/JointCurrentState.h\"\n#include \"utils.h\"\n\n// from kdl packages\n#include <kdl/tree.hpp>\n#include <kdl/chain.hpp>\n#include <kdl_parser/kdl_parser.hpp>\n#include <kdl/chaindynparam.hpp>              // inverse dynamics\n#include <kdl/chainjnttojacsolver.hpp>        // jacobian\n#include <kdl/chainfksolverpos_recursive.hpp> // forward kinematics\n\n#include <boost/scoped_ptr.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <cmath>\n#define _USE_MATH_DEFINES\n\n#include <SerialManipulator.h>\n#include <Controller.h>\n#include <Motion.h>\n\n#define D2R M_PI/180.0\n#define R2D 180.0/M_PI\n\n#define A 0.25\n#define b1 0.451\n#define b2 -0.316\n#define b3 0.843\n#define f 0.3\n\n#define l_p1 0.470\n#define l_p2 0.40\n#define l_p3 0.812\n\n#define Deg_A 70\n#define Deg_f 0.5\n\nnamespace dualarm_controller\n{\n    class JointSpace_Control : 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\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            K_inf_.resize(n_joints_);\n            aKp_.resize(n_joints_);\n            aKd_.resize(n_joints_);\n            aKi_.resize(n_joints_);\n            aK_inf_.resize(n_joints_);\n            std::vector<double> Kp(n_joints_), Ki(n_joints_), Kd(n_joints_), K_inf(n_joints_);\n\n            for (size_t i = 0; i < n_joints_; i++)\n            {\n                std::string si = std::to_string(i + 1);\n                if (n.getParam(\"/dualarm/jointspace_control/gains/dualarm_joint\" + si + \"/pid/p\", Kp[i]))\n                {\n                    Kp_(i) = Kp[i];\n                }\n                else\n                {\n                    std::cout << \"/dualarm/jointspace_control/gains/dualarm_joint\" + si + \"/pid/p\" << std::endl;\n                    ROS_ERROR(\"Cannot find pid/p gain\");\n                    return false;\n                }\n\n                if (n.getParam(\"/dualarm/jointspace_control/gains/dualarm_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(\"/dualarm/jointspace_control/gains/dualarm_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                if (n.getParam(\"/dualarm/jointspace_control/gains/dualarm_joint\" + si + \"/pid/h\", K_inf[i]))\n                {\n                    K_inf_(i) = K_inf[i];\n                }\n                else\n                {\n                    ROS_ERROR(\"Cannot find pid/h 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_name1, tip_name2;\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_link1\", tip_name1))\n            {\n                ROS_ERROR(\"Could not find tip link name\");\n                return false;\n            }\n            if (!n.getParam(\"tip_link2\", tip_name2))\n            {\n                ROS_ERROR(\"Could not find tip link name\");\n                return false;\n            }\n\n\n            if (!kdl_tree_.getChain(root_name, tip_name1, kdl_chain_))\n            {\n                ROS_ERROR_STREAM(\"Failed to get KDL chain from tree: \");\n                ROS_ERROR_STREAM(\"  \" << root_name << \" --> \" << tip_name1);\n                ROS_ERROR_STREAM(\"  Chain has \" << kdl_chain_.getNrOfJoints() << \" joints\");\n                ROS_ERROR_STREAM(\"  Chain has \" << kdl_chain_.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_STREAM(\"Got kdl first chain\");\n                ROS_INFO_STREAM(\"  \" << root_name << \" --> \" << tip_name1);\n                ROS_INFO_STREAM(\"  Chain has \" << kdl_chain_.getNrOfJoints() << \" joints\");\n                ROS_INFO_STREAM(\"  Chain has \" << kdl_chain_.getNrOfSegments() << \" segments\");\n            }\n\n            if(!kdl_tree_.getChain(root_name, tip_name2, kdl_chain2_))\n            {\n                ROS_ERROR_STREAM(\"Failed to get KDL chain from tree: \");\n                ROS_ERROR_STREAM(\"  \" << root_name << \" --> \" << tip_name2);\n                ROS_ERROR_STREAM(\"  Chain has \" << kdl_chain2_.getNrOfJoints() << \" joints\");\n                ROS_ERROR_STREAM(\"  Chain has \" << kdl_chain2_.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_STREAM(\"Got kdl second chain\");\n                ROS_INFO_STREAM(\"  \" << root_name << \" --> \" << tip_name2);\n                ROS_INFO_STREAM(\"  Chain has \" << kdl_chain2_.getNrOfJoints() << \" joints\");\n                ROS_INFO_STREAM(\"  Chain has \" << kdl_chain2_.getNrOfSegments() << \" segments\");\n            }\n\n            // 4.3 inverse dynamics solver \ucd08\uae30\ud654\n            g_kdl_ = KDL::Vector::Zero();\n            g_kdl_(2) = -9.81; // 0: x-axis 1: y-axis 2: z-axis\n\n            id_solver_.reset(new KDL::ChainDynParam(kdl_chain_, g_kdl_));\n            jnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(kdl_chain_));\n            fk_pos_solver_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_));\n            J1_kdl_.resize(kdl_chain_.getNrOfJoints());\n            M_kdl_.resize(kdl_chain_.getNrOfJoints());\n            C_kdl_.resize(kdl_chain_.getNrOfJoints());\n            G_kdl_.resize(kdl_chain_.getNrOfJoints());\n\n            id_solver1_.reset(new KDL::ChainDynParam(kdl_chain2_, g_kdl_));\n            jnt_to_jac_solver1_.reset(new KDL::ChainJntToJacSolver(kdl_chain2_));\n            fk_pos_solver1_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain2_));\n            J2_kdl_.resize(kdl_chain2_.getNrOfJoints());\n            M1_kdl_.resize(kdl_chain2_.getNrOfJoints());\n            C1_kdl_.resize(kdl_chain2_.getNrOfJoints());\n            G1_kdl_.resize(kdl_chain2_.getNrOfJoints());\n\n            // ********* 5. \uac01\uc885 \ubcc0\uc218 \ucd08\uae30\ud654 *********\n            // 5.1 KDL Vector \ucd08\uae30\ud654 (\uc0ac\uc774\uc988 \uc815\uc758 \ubc0f \uac12 0)\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\n            q_.data = Eigen::VectorXd::Zero(n_joints_);\n            qdot_.data = Eigen::VectorXd::Zero(n_joints_);\n            dq.setZero(n_joints_);\n            frictiontorque_.data = Eigen::VectorXd::Zero(n_joints_);\n\n\n            des_torque.setZero(n_joints_);\n            act_torque.setZero(n_joints_);\n//            frictiontorque.setZero(n_joints_);\n\n\n            targetpos.setZero(16);\n\n\n            // ********* 6. ROS \uba85\ub839\uc5b4 *********\n            // 6.1 publisher\n            state_pub_.reset(new realtime_tools::RealtimePublisher<dualarm_controller::JointCurrentState>(n, \"states\", 10));\n            state_pub_->msg_.header.stamp = ros::Time::now();\n            for(int i=0; i<(n_joints_); i++)\n            {\n                state_pub_->msg_.name.push_back(joint_names_[i].c_str()) ;\n                state_pub_->msg_.q.push_back(q_.data(i));\n                state_pub_->msg_.qdot.push_back(qdot_.data(i));\n                state_pub_->msg_.dq.push_back(qd_.data(i));\n                state_pub_->msg_.dqdot.push_back(qd_dot_.data(i));\n                state_pub_->msg_.dqddot.push_back(qd_ddot_.data(i));\n\n                state_pub_->msg_.effort_command.push_back(act_torque(i));\n                state_pub_->msg_.Kp.push_back(Kp_.data(i));\n                state_pub_->msg_.Kd.push_back(Kd_.data(i));\n                state_pub_->msg_.frictiontorque.push_back(frictiontorque_.data(i));\n\n            }\n            pub_buffer_.writeFromNonRT(std::vector<double>(n_joints_, 0.0));\n\n            // 6.2 subsriber\n            const auto joint_state_cb = utils::makeCallback<dualarm_controller::JointDesiredState>([&](const auto& msg){\n                for(int i=0; i<n_joints_; i++)\n                {\n                    ControlSubIndex = msg.SubIndex;\n                    JointState = ControlSubIndex;\n                    targetpos(i)=msg.dq[i].data*D2R;\n                    dq(i) = msg.dq[i].data*D2R;\n//                    Kp_.data(i) = msg.Kp[i].data;\n//                    Kd_.data(i) = msg.Kd[i].data;\n                }\n                qd_.data = dq;\n            });\n            sub_x_cmd_ = n.subscribe<dualarm_controller::JointDesiredState>( \"command\", 5, joint_state_cb);\n\n            return true;\n        }\n\n        void starting(const ros::Time &time) override\n        {\n            t = 0.0;\n            InitTime=5.0;\n\n            ROS_INFO_STREAM(\"Starting Joint-Space Controller\");\n\n            cManipulator = std::make_shared<SerialManipulator>();\n            Control = std::make_unique<HYUControl::Controller>(cManipulator);\n            motion = std::make_unique<HYUControl::Motion>(cManipulator);\n            ControlSubIndex = MOVE_ZERO;\n            JointState = MOVE_ZERO;\n            cManipulator->UpdateManipulatorParam();\n        }\n\n        void update(const ros::Time &time, const ros::Duration &period) override\n        {\n            std::vector<double> &commands = *pub_buffer_.readFromRT();\n            // ********* 0. Get states from gazebo *********\n            // 0.1 sampling time\n            double dt = period.toSec();\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                act_torque(i) = joints_[i].getEffort();\n            }\n\n            //----------------------\n            // dynamics calculation\n            //----------------------\n            cManipulator->pKin->PrepareJacobian(q_.data);\n            cManipulator->pDyn->PrepareDynamics(q_.data, qdot_.data);\n            cManipulator->pDyn->MG_Mat_Joint(M, G);\n            //cManipulator->pDyn->C_Matrix(C);\n\n            cManipulator->pKin->GetForwardKinematics(ForwardPos, ForwardOri, NumChain);\n            cManipulator->pKin->GetAngleAxis(ForwardAxis, ForwardAngle, NumChain);\n            Control->SetPIDGain(Kp_.data, Kd_.data, Ki_.data, K_inf_.data);\n            Control->GetPIDGain(aKp_.data, aKd_.data, aKi_.data);\n\n            q1_.data = q_.data.head(9);\n            q1dot_.data = qdot_.data.head(9);\n            jnt_to_jac_solver_->JntToJac(q1_, J1_kdl_);\n            id_solver_->JntToMass(q1_, M_kdl_);\n            id_solver_->JntToCoriolis(q1_, q1dot_, C_kdl_);\n            id_solver_->JntToGravity(q1_, G_kdl_);\n            fk_pos_solver_->JntToCart(q1_, x_[0]);\n\n            q2_.resize(9);\n            q2dot_.resize(9);\n            q2_.data.tail(7) = q_.data.tail(7);\n            q2_.data.head(2) = q_.data.head(2);\n            q2dot_.data = qdot_.data.tail(7);\n            q2dot_.data.head(2) = qdot_.data.head(2);\n            jnt_to_jac_solver1_->JntToJac(q2_, J2_kdl_);\n            id_solver1_->JntToMass(q2_, M1_kdl_);\n            id_solver1_->JntToCoriolis(q2_, q2dot_, C1_kdl_);\n            id_solver1_->JntToGravity(q2_, G1_kdl_);\n            fk_pos_solver1_->JntToCart(q2_, x_[1]);\n\n            if( t <= InitTime )\n            {\n                qd_.data.setZero();\n\n                qd_.data(0) = -0.0*D2R;\n                qd_.data(1) = -0.0*D2R;\n\n                qd_.data(2) = 0.0*D2R;\n                qd_.data(3) = -20.0*D2R;\n                qd_.data(4) = -0.0*D2R;\n                qd_.data(5) = -0.0*D2R;\n                qd_.data(6) = -70.0*D2R;\n                qd_.data(7) = 0.0*D2R;\n                qd_.data(8) = 0.0*D2R;\n\n                qd_.data(9) = 0.0*D2R;\n                qd_.data(10) = 20.0*D2R;\n                qd_.data(11) = 0.0*D2R;\n                qd_.data(12) = -0.0*D2R;\n                qd_.data(13) = 70.0*D2R;\n                qd_.data(14) = -0.0*D2R;\n                qd_.data(15) = -0.0*D2R;\n            }\n\n            qd_ddot_.data.setZero();\n            qd_dot_.data.setZero();\n            motion->JointMotion(qd_.data, qd_dot_.data, qd_ddot_.data, targetpos, q_.data, qdot_.data, t, JointState, ControlSubIndex);\n            Control->InvDynController2(q_.data, qdot_.data, qd_.data, qd_dot_.data, qd_ddot_.data, des_torque, frictiontorque_.data, dt);\n            e=qd_.data-q_.data;\n            for (int i = 0; i < n_joints_; i++)\n            {\n                if(des_torque(i) >= 100)\n                    des_torque(i) = 100;\n                else if(des_torque(i) <= -100)\n                    des_torque(i) = -100;\n\n                joints_[i].setCommand(des_torque(i));\n            }\n\n            // ********* 4. data \uc800\uc7a5 *********\n            publish_data();\n\n            // ********* 5. state \ucd9c\ub825 *********\n            print_state();\n\n            t = t + dt;\n        }\n\n        void stopping(const ros::Time &time) override\n        {\n            ROS_INFO_STREAM(\"Stop Joint-Space Controller\");\n        }\n\n        void publish_data()\n        {\n            static int loop_count_ = 0;\n            if(loop_count_ > 2)\n            {\n                if(state_pub_->trylock())\n                {\n                    state_pub_->msg_.header.stamp = ros::Time::now();\n                    for(size_t i=0; i<(n_joints_-1); i++)\n                    {\n                        state_pub_->msg_.q[i] = q_.data(i);\n                        state_pub_->msg_.qdot[i] = qdot_.data(i);\n                        state_pub_->msg_.dq[i] = qd_.data(i);\n                        state_pub_->msg_.dqdot[i] = qd_dot_.data(i);\n                        state_pub_->msg_.dqddot[i] = qd_ddot_.data(i);\n\n                        state_pub_->msg_.effort_command[i] = act_torque(i);\n                        state_pub_->msg_.frictiontorque[i] = frictiontorque_.data(i);\n\n                        state_pub_->msg_.Kp[i] = Kp_.data(i);\n                        state_pub_->msg_.Kd[i] = Kd_.data(i);\n                    }\n                    state_pub_->unlockAndPublish();\n                }\n                loop_count_=0;\n            }\n            loop_count_++;\n        }\n\n        void print_state()\n        {\n            static int count = 0;\n            if (count > 499)\n            {\n                printf(\"*********************************************************\\n\\n\");\n                printf(\"*** Simulation Time (unit: sec)  ***\\n\");\n                printf(\"t = %f\\n\", t);\n                printf(\"\\n\");\n\n                printf(\"*** States in Joint Space (unit: deg) ***\\n\");\n\n                for(int i=0; i < n_joints_; i++)\n                {\n                    printf(\"[%s]:  \\t\", joint_names_[i].c_str());\n                    printf(\"q: %0.3lf,\\t\", q_.data(i) * R2D);\n                    printf(\"dq: %0.3lf,\\t\", qd_.data(i) * R2D);\n                    printf(\"e: %0.3lf,\\t\", e(i) * R2D);\n\n                    printf(\"qdot: %0.3lf,\\t\", qdot_.data(i) * R2D);\n//                    printf(\"dqdot: %0.3lf,\\t\", qd_dot_.data(i) * R2D);\n                    printf(\"tau: %0.3f\\t\", des_torque(i));\n                    printf(\"tau_friction: %0.3f\\t\", frictiontorque_.data(i));\n\n//                    printf(\"Kp:%0.1lf, Kd:%0.1lf, Ki:%0.1lf\\t\", aKp_.data(i), aKd_.data(i),  aKi_.data(i));\n                    printf(\"SubIndex:%d\\n\", ControlSubIndex);\n\n\n                }\n\n                printf(\"\\nForward Kinematics:\\n\");\n                for(int j=0; j<NumChain; j++)\n                {\n                    printf(\"no.%d, PoE: x:%0.3lf, y:%0.3lf, z:%0.3lf, u:%0.2lf, v:%0.2lf, w:%0.2lf\\n\", j,\n                           ForwardPos[j](0), ForwardPos[j](1),ForwardPos[j](2),\n                           ForwardOri[j](0), ForwardOri[j](1), ForwardOri[j](2));\n                    double a, b, g;\n                    x_[j].M.GetEulerZYX(a, b, g);\n                    printf(\"no.%d, DH: x:%0.3lf, y:%0.3lf, z:%0.3lf, u:%0.2lf, v:%0.2lf, w:%0.2lf\\n\",\n                           j, x_[j].p(0), x_[j].p(1),x_[j].p(2), g, b, a);\n                    printf(\"no.%d, AngleAxis x: %0.2lf, y: %0.2lf, z: %0.2lf, Angle: %0.3lf\\n\\n\",\n                           j, ForwardAxis[j](0), ForwardAxis[j](1), ForwardAxis[j](2), ForwardAngle[j]);\n                }\n                printf(\"\\n*********************************************************\\n\");\n                count = 0;\n                /*\n                M_mat_collect.resize(16,16);\n                M_mat_collect.setZero();\n                M_mat_collect.block(0,0,2,2) = M_kdl_.data.block(0,0,2,2) + M1_kdl_.data.block(0,0,2,2);\n                M_mat_collect.block(0,2,2,7) = M_kdl_.data.block(0,2,2,7);\n                M_mat_collect.block(0,9,2,7) = M1_kdl_.data.block(0,2,2,7);\n                M_mat_collect.block(2,0,7,2) = M_kdl_.data.block(2,0,7,2);\n                M_mat_collect.block(9,0,7,2) = M1_kdl_.data.block(2,0,7,2);\n                M_mat_collect.block(2,2,7,7) = M_kdl_.data.block(2,2,7,2);\n                M_mat_collect.block(9,9,7,7) = M1_kdl_.data.block(2,2,7,2);\n                std::cout << \"M_kdl\" << std::endl;\n                std::cout << M_mat_collect << std::endl;\n                std::cout << \"M_PoE\" << std::endl;\n                std::cout << M << std::endl;\n                */\n                /*\n                C_mat_collect.resize(16,16);\n                C_mat_collect.setZero();\n                C_mat_collect.block(0,0,2,2) = C_kdl_.data.block(0,0,2,2) + C1_kdl_.data.block(0,0,2,2);\n                C_mat_collect.block(0,2,2,7) = C_kdl_.data.block(0,2,2,7);\n                C_mat_collect.block(0,9,2,7) = C1_kdl_.data.block(0,2,2,7);\n                C_mat_collect.block(2,0,7,2) = C_kdl_.data.block(2,0,7,2);\n                C_mat_collect.block(9,0,7,2) = C1_kdl_.data.block(2,0,7,2);\n                C_mat_collect.block(2,2,7,7) = C_kdl_.data.block(2,2,7,2);\n                C_mat_collect.block(9,9,7,7) = C1_kdl_.data.block(2,2,7,2);\n                std::cout << \"C_kdl\" << std::endl;\n                std::cout << C_mat_collect << std::endl;\n                std::cout << \"C_PoE\" << std::endl;\n                std::cout << C << std::endl;\n                */\n\n            }\n            count++;\n        }\n\n    private:\n        // others\n        double t;\n        double InitTime=0;\n\n        //Joint handles\n        unsigned int n_joints_;\n        unsigned char ControlSubIndex;\n        unsigned char JointState;\n\n\n        std::vector<std::string> joint_names_;\n        std::vector<hardware_interface::JointHandle> joints_;\n        std::vector<urdf::JointConstSharedPtr> joint_urdfs_;\n\n        // kdl\n        KDL::Tree kdl_tree_;\n        KDL::Chain kdl_chain_;\n        KDL::Chain kdl_chain2_;\n\n        KDL::JntSpaceInertiaMatrix M_kdl_, M1_kdl_;\n        KDL::JntArray C_kdl_, C1_kdl_;\n        KDL::JntArray G_kdl_, G1_kdl_;\n        KDL::Vector g_kdl_;\n        Eigen::VectorXd g_vec_collect;\n        Eigen::MatrixXd g_mat_collect;\n        Eigen::MatrixXd M_mat_collect;\n        Eigen::MatrixXd C_mat_collect;\n        Eigen::VectorXd e, e_dev, e_int, e_int_sat;\n\n\n        KDL::Jacobian J1_kdl_, J2_kdl_;\n\n        // kdl solver\n        boost::scoped_ptr<KDL::ChainFkSolverPos_recursive> fk_pos_solver_, fk_pos_solver1_;     // Solver to compute the forward kinematics (position)\n        boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_, jnt_to_jac_solver1_;    // Solver to compute the jacobian\n        boost::scoped_ptr<KDL::ChainDynParam> id_solver_, id_solver1_;                          // Solver To compute the inverse dynamics\n\n        MatrixXd M;\n        VectorXd G;\n        MatrixXd C;\n\n        Vector3d ForwardPos[2];\n        Vector3d ForwardOri[2];\n        int NumChain=2;\n        Vector3d ForwardAxis[2];\n        double ForwardAngle[2];\n\n        // Joint Space State\n        KDL::JntArray qd_;\n        KDL::JntArray qd_dot_;\n        KDL::JntArray qd_ddot_;\n        KDL::JntArray q_, q1_, q2_;\n        KDL::JntArray qdot_, q1dot_, q2dot_;\n        KDL::JntArray frictiontorque_;\n\n        Eigen::VectorXd targetpos;\n\n\n        VectorXd dq;\n        VectorXd des_torque;\n        VectorXd act_torque;\n        VectorXd frictiontorque;\n\n\n\n        // Task Space State\n        KDL::Frame x_[2];\n\n        // gains\n        KDL::JntArray Kp_, Ki_, Kd_, K_inf_;\n        KDL::JntArray aKp_, aKi_, aKd_, aK_inf_;\n\n        // publisher\n        realtime_tools::RealtimeBuffer<std::vector<double>> pub_buffer_;\n        boost::scoped_ptr<realtime_tools::RealtimePublisher<dualarm_controller::JointCurrentState>> state_pub_;\n\n        // subscriber\n        ros::Subscriber sub_x_cmd_;\n\n        std::shared_ptr<SerialManipulator> cManipulator;\n        std::unique_ptr<HYUControl::Controller> Control;\n        std::unique_ptr<HYUControl::Motion> motion;\n\n    };\n}\n\nPLUGINLIB_EXPORT_CLASS(dualarm_controller::JointSpace_Control,controller_interface::ControllerBase)", "meta": {"hexsha": "118c75f57b4cf710228cbdb77d06d2af3db7baee", "size": 24421, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dualarm_controller/src/jointspace_control.cpp", "max_stars_repo_name": "hyujun/DualArm_Sim", "max_stars_repo_head_hexsha": "5a0eea7cfec45b4db8f097dbcfb101ecdc1ce7e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T04:41:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T13:36:59.000Z", "max_issues_repo_path": "dualarm_controller/src/jointspace_control.cpp", "max_issues_repo_name": "hyujun/DualArm_Sim", "max_issues_repo_head_hexsha": "5a0eea7cfec45b4db8f097dbcfb101ecdc1ce7e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dualarm_controller/src/jointspace_control.cpp", "max_forks_repo_name": "hyujun/DualArm_Sim", "max_forks_repo_head_hexsha": "5a0eea7cfec45b4db8f097dbcfb101ecdc1ce7e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T04:41:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T04:43:26.000Z", "avg_line_length": 37.9208074534, "max_line_length": 150, "alphanum_fraction": 0.5025592728, "num_tokens": 6445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.1918805349465146}}
{"text": "//\n//  ExporterOBJ.cpp\n//  Kuplung\n//\n//  Created by Sergey Petrov on 12/16/15.\n//  Copyright \u00a9 2015 supudo.net. All rights reserved.\n//\n\n#include \"ExporterOBJ.hpp\"\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include <fstream>\n#include <glm/gtx/matrix_decompose.hpp>\n\nnamespace KuplungApp {\nnamespace Utilities {\nnamespace Export {\n\nExporterOBJ::~ExporterOBJ() {}\n\nvoid ExporterOBJ::init(const std::function<void(float)>& doProgress) {\n  this->funcProgress = doProgress;\n  this->addSuffix = false;\n#ifdef _WIN32\n  this->nlDelimiter = \"\\n\";\n#elif defined macintosh // OS 9\n  this->nlDelimiter = \"\\r\";\n#else\n  this->nlDelimiter = \"\\n\";\n#endif\n\n  this->parserUtils = std::make_unique<ParserUtils>();\n}\n\nvoid ExporterOBJ::exportToFile(const FBEntity& file, const std::vector<ModelFaceBase*>& faces, const std::vector<std::string>& settings, std::unique_ptr<ObjectsManager>& managerObjects) {\n  this->exportFile = file;\n  this->objSettings = settings;\n  this->exportGeometry(faces);\n  this->exportMaterials(faces);\n}\n\nstd::string ExporterOBJ::exportMesh(const ModelFaceBase& face) {\n  MeshModel model = face.meshModel;\n  std::string meshData(\"\");\n  std::string v(\"\"), vt(\"\"), vn(\"\"), f(\"\");\n\n  //    int Setting_Axis_Forward = 4;\n  //    if (this->objSettings.size() > 0 && !this->objSettings[0].empty())\n  //        Setting_Axis_Forward = std::stoi(this->objSettings[0]);\n  //    int Setting_Axis_Up = 5;\n  //    if (this->objSettings.size() > 1 && !this->objSettings[1].empty())\n  //        Setting_Axis_Up = std::stoi(this->objSettings[1]);\n\n  glm::vec3 scale;\n  glm::quat rotation;\n  glm::vec3 translation;\n  glm::vec3 skew;\n  glm::vec4 perspective;\n  glm::decompose(face.matrixModel, scale, rotation, translation, skew, perspective);\n\n  this->funcProgress(0.0f);\n  const int totalProgress = int(model.indices.size()) * 2;\n  float progressCounter = 0.0f;\n\n  meshData += this->nlDelimiter;\n  meshData += \"o \" + model.ModelTitle + this->nlDelimiter;\n  for (size_t j = 0; j < model.indices.size(); j++) {\n    int idx = model.indices[j];\n    //glm::vec3 vertex = this->parserUtils->fixVectorAxis(model.vertices[idx], Setting_Axis_Forward, Setting_Axis_Up);\n    glm::vec3 vertex = model.vertices[idx];\n\n    vertex += glm::vec3(face.positionX->point, face.positionY->point, face.positionZ->point);\n    vertex = vertex * rotation;\n    vertex = vertex * scale;\n\n    glm::vec2 texture_coordinate;\n    if (model.texture_coordinates.size() > 0)\n      texture_coordinate = model.texture_coordinates[idx];\n    //glm::vec3 normal = this->parserUtils->fixVectorAxis(model.normals[idx], Setting_Axis_Forward, Setting_Axis_Up);\n    glm::vec3 normal = model.normals[idx];\n\n    if (find(this->uniqueVertices.begin(), this->uniqueVertices.end(), vertex) == this->uniqueVertices.end()) {\n      this->uniqueVertices.push_back(vertex);\n      v += \"v \" + std::to_string(vertex.x) + \" \" + std::to_string(vertex.y) + \" \" + std::to_string(vertex.z) + this->nlDelimiter;\n    }\n\n    if (model.texture_coordinates.size() && find(this->uniqueTextureCoordinates.begin(), this->uniqueTextureCoordinates.end(), texture_coordinate) == this->uniqueTextureCoordinates.end()) {\n      this->uniqueTextureCoordinates.push_back(texture_coordinate);\n      vt += \"vt \" + std::to_string(texture_coordinate.x) + \" \" + std::to_string(texture_coordinate.y) + this->nlDelimiter;\n    }\n\n    if (find(this->uniqueNormals.begin(), this->uniqueNormals.end(), normal) == this->uniqueNormals.end()) {\n      this->uniqueNormals.push_back(normal);\n      vn += \"vn \" + std::to_string(normal.x) + \" \" + std::to_string(normal.y) + \" \" + std::to_string(normal.z) + this->nlDelimiter;\n    }\n\n    progressCounter += 1;\n\n    this->funcProgress((progressCounter / float(totalProgress)) * 100.0f);\n  }\n\n  meshData += v;\n  meshData += vt;\n  meshData += vn;\n\n  std::string triangleFace(\"\");\n  for (size_t k = 0, vCounterT = 1; k < model.indices.size(); k++, vCounterT++) {\n    int j = model.indices[int(k)];\n\n    glm::vec3 vertex = model.vertices[j];\n    vertex += glm::vec3(face.positionX->point, face.positionY->point, face.positionZ->point);\n    vertex = vertex * rotation;\n    vertex = vertex * scale;\n\n    long v = find(this->uniqueVertices.begin(), this->uniqueVertices.end(), vertex) - this->uniqueVertices.begin() + 1;\n    long vn = find(this->uniqueNormals.begin(), this->uniqueNormals.end(), model.normals[j]) - this->uniqueNormals.begin() + 1;\n\n    long vt = -1;\n    if (model.texture_coordinates.size() > 0)\n      vt = find(this->uniqueTextureCoordinates.begin(), this->uniqueTextureCoordinates.end(), model.texture_coordinates[j]) - this->uniqueTextureCoordinates.begin();\n\n    triangleFace += \" \" + std::to_string(v) + \"/\" + (vt > -1 ? std::to_string(vt + 1) : \"\") + \"/\" + std::to_string(vn);\n\n    if (vCounterT % 3 == 0) {\n      f += \"f\" + triangleFace + this->nlDelimiter;\n      triangleFace.clear();\n    }\n\n    progressCounter += 1;\n\n    this->funcProgress((progressCounter / float(totalProgress)) * 100.0f);\n  }\n\n  meshData += \"usemtl \" + model.MaterialTitle + this->nlDelimiter;\n  meshData += \"s off\" + this->nlDelimiter;\n  meshData += f;\n\n  return meshData;\n}\n\nvoid ExporterOBJ::exportGeometry(const std::vector<ModelFaceBase*>& faces) {\n  std::string fileContents = \"# Kuplung v1.0 OBJ File Export\" + this->nlDelimiter;\n  fileContents += \"# http://www.github.com/supudo/kuplung/\" + this->nlDelimiter;\n  std::string fn = this->exportFile.title;\n  boost::replace_all(fn, \".obj\", \"\");\n  fileContents += \"mtllib \" + fn + \".mtl\" + this->nlDelimiter;\n\n  this->uniqueVertices.clear();\n  this->uniqueTextureCoordinates.clear();\n  this->uniqueNormals.clear();\n  this->vCounter = 1;\n  this->vtCounter = 1;\n  this->vnCounter = 1;\n\n  std::vector<ModelFaceBase*>::const_iterator faceIterator;\n  for (faceIterator = faces.begin(); faceIterator != faces.end(); ++faceIterator) {\n    fileContents += this->exportMesh(**faceIterator);\n  }\n  fileContents += this->nlDelimiter;\n\n  if (!fileContents.empty()) {\n    time_t t = time(0);\n    const struct tm* now = localtime(&t);\n\n    const int year = now->tm_year + 1900;\n    const int month = now->tm_mon + 1;\n    const int day = now->tm_mday;\n    const int hour = now->tm_hour;\n    const int minute = now->tm_min;\n    const int seconds = now->tm_sec;\n\n    std::string fileSuffix = \"_\" + std::to_string(year) + std::to_string(month) + std::to_string(day) + std::to_string(hour) + std::to_string(minute) + std::to_string(seconds);\n\n    if (!this->addSuffix)\n      fileSuffix.clear();\n    std::string filePath = this->exportFile.path.substr(0, this->exportFile.path.find_last_of(\"\\\\/\"));\n    std::string fileName = this->exportFile.title;\n    if (boost::algorithm::ends_with(fileName, \".obj\"))\n      fileName = fileName.substr(0, fileName.size() - 4);\n    this->saveFile(fileContents, filePath + \"/\" + fileName + fileSuffix + \".obj\");\n  }\n}\n\nvoid ExporterOBJ::exportMaterials(const std::vector<ModelFaceBase*>& faces) {\n  std::map<std::string, std::string> materials;\n  std::vector<ModelFaceBase*>::const_iterator faceIterator;\n  for (faceIterator = faces.begin(); faceIterator != faces.end(); ++faceIterator) {\n    MeshModelMaterial mat = (*faceIterator)->meshModel.ModelMaterial;\n    if (materials[mat.MaterialTitle].empty()) {\n      materials[mat.MaterialTitle] = this->nlDelimiter;\n      materials[mat.MaterialTitle] += \"newmtl \" + mat.MaterialTitle + this->nlDelimiter;\n      materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ns %g\", mat.SpecularExp) + this->nlDelimiter;\n      materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ka %g %g %g\", mat.AmbientColor.r, mat.AmbientColor.g, mat.AmbientColor.b) + this->nlDelimiter;\n      materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Kd %g %g %g\", mat.DiffuseColor.r, mat.DiffuseColor.g, mat.DiffuseColor.b) + this->nlDelimiter;\n      materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ks %g %g %g\", mat.SpecularColor.r, mat.SpecularColor.g, mat.SpecularColor.b) + this->nlDelimiter;\n      materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ke %g %g %g\", mat.EmissionColor.r, mat.EmissionColor.g, mat.EmissionColor.b) + this->nlDelimiter;\n      if (mat.OpticalDensity >= 0.0f)\n        materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ni %g\", mat.OpticalDensity) + this->nlDelimiter;\n      materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"d %g\", mat.Transparency) + this->nlDelimiter;\n      materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"illum %i\", mat.IlluminationMode) + this->nlDelimiter;\n\n      if (!mat.TextureAmbient.Image.empty())\n        materials[mat.MaterialTitle] += \"map_Ka \" + mat.TextureAmbient.Image + this->nlDelimiter;\n      if (!mat.TextureDiffuse.Image.empty())\n        materials[mat.MaterialTitle] += \"map_Kd \" + mat.TextureDiffuse.Image + this->nlDelimiter;\n      if (!mat.TextureDissolve.Image.empty())\n        materials[mat.MaterialTitle] += \"map_d \" + mat.TextureDissolve.Image + this->nlDelimiter;\n      if (!mat.TextureBump.Image.empty())\n        materials[mat.MaterialTitle] += \"map_Bump \" + mat.TextureBump.Image + this->nlDelimiter;\n      if (!mat.TextureDisplacement.Image.empty())\n        materials[mat.MaterialTitle] += \"disp \" + mat.TextureDisplacement.Image + this->nlDelimiter;\n      if (!mat.TextureSpecular.Image.empty())\n        materials[mat.MaterialTitle] += \"map_Ks \" + mat.TextureSpecular.Image + this->nlDelimiter;\n      if (!mat.TextureSpecularExp.Image.empty())\n        materials[mat.MaterialTitle] += \"map_Ns \" + mat.TextureSpecularExp.Image + this->nlDelimiter;\n    }\n  }\n\n  std::string fileContents = \"# Kuplung MTL File\" + this->nlDelimiter;\n  fileContents += \"# Material Count: \" + std::to_string(materials.size()) + this->nlDelimiter;\n  fileContents += \"# http://www.github.com/supudo/kuplung/\" + this->nlDelimiter;\n\n  for (std::map<std::string, std::string>::iterator iter = materials.begin(); iter != materials.end(); ++iter) {\n    fileContents += iter->second;\n  }\n\n  fileContents += this->nlDelimiter;\n\n  if (!fileContents.empty()) {\n    std::string filePath = this->exportFile.path.substr(0, this->exportFile.path.find_last_of(\"\\\\/\"));\n    std::string fileName = this->exportFile.title;\n    if (boost::algorithm::ends_with(fileName, \".obj\"))\n      fileName = fileName.substr(0, fileName.size() - 4);\n    this->saveFile(fileContents, filePath + \"/\" + fileName + \".mtl\");\n  }\n}\n\n//void ExporterOBJ::exportMaterials(const std::vector<ModelFaceBase*>& faces) {\n//    std::map<std::string, std::string> materials;\n//    for (int i=0; i<(int)faces.size(); i++) {\n//        MeshModelMaterial mat = faces[i]->meshModel.ModelMaterial;\n//        if (materials[mat.MaterialTitle].empty()) {\n//            materials[mat.MaterialTitle] = this->nlDelimiter;\n//            materials[mat.MaterialTitle] += \"newmtl \" + mat.MaterialTitle + this->nlDelimiter;\n//            materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ns %f\", mat.SpecularExp) + this->nlDelimiter;\n//            materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ka %f %f %f\", mat.AmbientColor.r, mat.AmbientColor.g, mat.AmbientColor.b) + this->nlDelimiter;\n//            materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Kd %f %f %f\", mat.DiffuseColor.r, mat.DiffuseColor.g, mat.DiffuseColor.b) + this->nlDelimiter;\n//            materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ks %f %f %f\", mat.SpecularColor.r, mat.SpecularColor.g, mat.SpecularColor.b) + this->nlDelimiter;\n//            materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ke %f %f %f\", mat.EmissionColor.r, mat.EmissionColor.g, mat.EmissionColor.b) + this->nlDelimiter;\n//            if (mat.OpticalDensity >= 0.0f)\n//                materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"Ni %f\", mat.OpticalDensity) + this->nlDelimiter;\n//            materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"d %f\", mat.Transparency) + this->nlDelimiter;\n//            materials[mat.MaterialTitle] += Settings::Instance()->string_format(\"illum %i\", mat.IlluminationMode) + this->nlDelimiter;\n\n//            if (!mat.TextureAmbient.Image.empty())\n//                materials[mat.MaterialTitle] += \"map_Ka \" + mat.TextureAmbient.Image + this->nlDelimiter;\n//            if (!mat.TextureDiffuse.Image.empty())\n//                materials[mat.MaterialTitle] += \"map_Kd \" + mat.TextureDiffuse.Image + this->nlDelimiter;\n//            if (!mat.TextureDissolve.Image.empty())\n//                materials[mat.MaterialTitle] += \"map_d \" + mat.TextureDissolve.Image + this->nlDelimiter;\n//            if (!mat.TextureBump.Image.empty())\n//                materials[mat.MaterialTitle] += \"map_Bump \" + mat.TextureBump.Image + this->nlDelimiter;\n//            if (!mat.TextureDisplacement.Image.empty())\n//                materials[mat.MaterialTitle] += \"disp \" + mat.TextureDisplacement.Image + this->nlDelimiter;\n//            if (!mat.TextureSpecular.Image.empty())\n//                materials[mat.MaterialTitle] += \"map_Ks \" + mat.TextureSpecular.Image + this->nlDelimiter;\n//            if (!mat.TextureSpecularExp.Image.empty())\n//                materials[mat.MaterialTitle] += \"map_Ns \" + mat.TextureSpecularExp.Image + this->nlDelimiter;\n//        }\n//    }\n\n//    std::string fileContents = \"# Kuplung MTL File\" + this->nlDelimiter;\n//    fileContents += \"# Material Count: \" + std::to_string(materials.size()) + this->nlDelimiter;\n//    fileContents += \"# http://www.github.com/supudo/kuplung/\" + this->nlDelimiter;\n\n//    for (std::map<std::string, std::string>::iterator iter = materials.begin(); iter != materials.end(); ++iter) {\n//        fileContents += iter->second;\n//    }\n\n//    fileContents += this->nlDelimiter;\n\n//    if (!fileContents.empty()) {\n//        std::string filePath = this->exportFile.path.substr(0, this->exportFile.path.find_last_of(\"\\\\/\"));\n//        std::string fileName = this->exportFile.title;\n//        if (boost::algorithm::ends_with(fileName, \".obj\"))\n//            fileName = fileName.substr(0, fileName.size() - 4);\n//        this->saveFile(fileContents, filePath + \"/\" + fileName + \".mtl\");\n//    }\n//}\n\nvoid ExporterOBJ::saveFile(const std::string& fileContents, const std::string& fileName) const {\n  //    printf(\"--------------------------------------------------------\\n\");\n  //    printf(\"%s\\n\", fileName.c_str());\n  //    printf(\"%s\\n\", fileContents.c_str());\n  //    printf(\"--------------------------------------------------------\\n\");\n\n  std::ofstream out(fileName);\n  if (out.is_open()) {\n    out << fileContents;\n    out.close();\n  }\n}\n\n} // namespace Export\n} // namespace Utilities\n} // namespace KuplungApp\n", "meta": {"hexsha": "5c288cbf6269cdbd9569acfce2ce72d8cfda8b37", "size": 14786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kuplung/kuplung/utilities/export/ExporterOBJ.cpp", "max_stars_repo_name": "supudo/Kuplung", "max_stars_repo_head_hexsha": "f0e11934fde0675fa531e6dc263bedcc20a5ea1a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-02-17T17:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T01:55:06.000Z", "max_issues_repo_path": "Kuplung/kuplung/utilities/export/ExporterOBJ.cpp", "max_issues_repo_name": "supudo/Kuplung", "max_issues_repo_head_hexsha": "f0e11934fde0675fa531e6dc263bedcc20a5ea1a", "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": "Kuplung/kuplung/utilities/export/ExporterOBJ.cpp", "max_forks_repo_name": "supudo/Kuplung", "max_forks_repo_head_hexsha": "f0e11934fde0675fa531e6dc263bedcc20a5ea1a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-15T08:10:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T08:10:10.000Z", "avg_line_length": 48.1628664495, "max_line_length": 189, "alphanum_fraction": 0.6571757067, "num_tokens": 3829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.1918805349465146}}
{"text": "#include \"../chainparams.h\"\n#include \"../lelantus.h\"\n#include \"../script/standard.h\"\n#include \"../validation.h\"\n#include \"../wallet/coincontrol.h\"\n#include \"../wallet/wallet.h\"\n\n#include \"test_bitcoin.h\"\n#include \"fixtures.h\"\n\n#include <boost/test/unit_test.hpp>\n\nnamespace lelantus {\n\nstruct JoinSplitScriptGenerator {\n    Params const *params;\n    std::vector<std::pair<PrivateCoin, uint32_t>> coins;\n    std::map<uint32_t, std::vector<PublicCoin>> anons;\n    CAmount vout;\n    std::vector<PrivateCoin> coinsOut;\n    CAmount fee;\n    std::map<uint32_t, uint256> groupBlockHashes;\n    uint256 txHash;\n\n    std::pair<CScript, JoinSplit> Get() {\n        // auto p = params ? params : Params::get_default();\n        auto p = Params::get_default();\n\n        CScript script;\n\n        JoinSplit joinSplit(p, coins, anons, vout, coinsOut, fee, groupBlockHashes, txHash);\n        joinSplit.setVersion(LELANTUS_TX_VERSION_4);\n\n        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n        ss << joinSplit;\n\n        script << OP_LELANTUSJOINSPLIT;\n        script.insert(script.end(), ss.begin(), ss.end());\n\n        return {script, joinSplit};\n    }\n};\n\nclass LelantusTests : public LelantusTestingSetup {\npublic:\n    LelantusTests() :\n        LelantusTestingSetup(),\n        lelantusState(CLelantusState::GetState()),\n        consensus(::Params().GetConsensus()) {\n    }\n\n    ~LelantusTests() {\n        lelantusState->Reset();\n    }\n\npublic:\n\n    std::vector<PublicCoin> ExtractCoins(std::vector<PrivateCoin> const &coins) {\n        std::vector<PublicCoin> pubs;\n        pubs.reserve(coins.size());\n\n        for (auto &c : coins) {\n            pubs.push_back(c.getPublicCoin());\n        }\n\n        return pubs;\n    }\n\n    void ExtractJoinSplit(CMutableTransaction const &tx,\n        std::vector<PublicCoin> &newMints,\n        std::vector<Scalar> &serials) {\n        for (auto const &in : tx.vin) {\n            if (in.IsLelantusJoinSplit()) {\n                auto js = ParseLelantusJoinSplit(in);\n                auto const &s = js->getCoinSerialNumbers();\n                serials.insert(serials.end(), s.begin(), s.end());\n            }\n        }\n\n        for (auto const &out : tx.vout) {\n            if (out.scriptPubKey.IsLelantusJMint()) {\n                GroupElement coin;\n                ParseLelantusMintScript(out.scriptPubKey, coin);\n\n                newMints.push_back(coin);\n            }\n        }\n    }\n\n    CBlock GetCBlock(CBlockIndex const *blockIdx) {\n        CBlock block;\n        if (!ReadBlockFromDisk(block, blockIdx, ::Params().GetConsensus())) {\n            throw std::invalid_argument(\"No block index data\");\n        }\n\n        return block;\n    }\n\n    void PopulateLelantusTxInfo(\n        CBlock &block,\n        std::vector<std::pair<lelantus::PublicCoin, std::pair<uint64_t, uint256>>> const &mints,\n        std::vector<std::pair<Scalar, int>> const &serials) {\n        block.lelantusTxInfo = std::make_shared<lelantus::CLelantusTxInfo>();\n        block.lelantusTxInfo->mints.insert(block.lelantusTxInfo->mints.end(), mints.begin(), mints.end());\n\n        for (auto const &s : serials) {\n            block.lelantusTxInfo->spentSerials.emplace(s);\n        }\n\n        block.lelantusTxInfo->Complete();\n    }\n\n    CTransaction GenerateJoinSplit(\n        std::vector<CAmount> const &outs,\n        std::vector<CAmount> const &mints,\n        CCoinControl const *coinControl = nullptr) {\n\n        std::vector<CRecipient> vecs;\n        for (auto const &out : outs) {\n            LOCK(pwalletMain->cs_wallet);\n            auto pub = pwalletMain->GenerateNewKey();\n\n            vecs.push_back(\n            {\n                GetScriptForDestination(pub.GetID()),\n                out,\n                false\n            });\n        }\n\n        std::vector<CLelantusEntry>  spendCoins;\n        std::vector<CHDMint> mintCoins;\n\n        CAmount fee;\n        auto result = pwalletMain->CreateLelantusJoinSplitTransaction(\n            vecs, fee, mints, spendCoins, mintCoins, coinControl);\n\n        if (!pwalletMain->CommitLelantusTransaction(\n            result, spendCoins, mintCoins)) {\n            throw std::runtime_error(\"Fail to commit transaction\");\n        }\n\n        return result;\n    }\n\npublic:\n    CLelantusState *lelantusState;\n    Consensus::Params const &consensus;\n};\n\nBOOST_FIXTURE_TEST_SUITE(lelantus_tests, LelantusTests)\n\nBOOST_AUTO_TEST_CASE(schnorr_proof)\n{\n    auto params = Params::get_default();\n\n    PrivateCoin coin(params, 1);\n\n    CDataStream  serializedSchnorrProof(SER_NETWORK, PROTOCOL_VERSION);\n    GenerateMintSchnorrProof(coin, serializedSchnorrProof);\n\n    auto commitment = coin.getPublicCoin();\n    SchnorrProof proof;\n    serializedSchnorrProof >> proof;\n\n    BOOST_CHECK(VerifyMintSchnorrProof(1, commitment.getValue(), proof));\n}\n\nBOOST_AUTO_TEST_CASE(is_lelantus_allowed)\n{\n    auto start = ::Params().GetConsensus().nLelantusStartBlock;\n    BOOST_CHECK(!IsLelantusAllowed(0));\n    BOOST_CHECK(!IsLelantusAllowed(start - 1));\n    BOOST_CHECK(IsLelantusAllowed(start));\n    BOOST_CHECK(IsLelantusAllowed(start + 1));\n}\n\nBOOST_AUTO_TEST_CASE(parse_lelantus_mintscript)\n{\n    // payload: op_code + pubcoin + schnorrproof\n    PrivateCoin priv(params, 1);\n    auto &pub = priv.getPublicCoin();\n\n    CDataStream  proofSerialized(SER_NETWORK, PROTOCOL_VERSION);\n\n    GenerateMintSchnorrProof(priv, proofSerialized);\n\n    CScript script(OP_LELANTUSMINT);\n\n    auto vch = pub.getValue().getvch();\n    script.insert(script.end(), vch.begin(), vch.end());\n    script.insert(script.end(), proofSerialized.begin(), proofSerialized.end());\n\n    // verify\n    secp_primitives::GroupElement parsedCoin;\n    ParseLelantusMintScript(script, parsedCoin);\n\n    BOOST_CHECK(pub.getValue() == parsedCoin);\n\n    SchnorrProof proof;\n    uint256 mintTag;\n    ParseLelantusMintScript(script, parsedCoin, proof, mintTag);\n\n    BOOST_CHECK(pub.getValue() == parsedCoin);\n    BOOST_CHECK(VerifyMintSchnorrProof(1, parsedCoin, proof));\n\n    CDataStream  parsedProof(SER_NETWORK, PROTOCOL_VERSION);\n    parsedProof << proof;\n\n    BOOST_CHECK(proofSerialized.vch == parsedProof.vch);\n\n    GroupElement parsedCoin2;\n    ParseLelantusMintScript(script, parsedCoin2);\n\n    BOOST_CHECK(pub.getValue() == parsedCoin2);\n\n    script.resize(script.size() - 1);\n    BOOST_CHECK_THROW(ParseLelantusMintScript(script, parsedCoin, proof, mintTag), std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(parse_lelantus_jmint)\n{\n    GroupElement val;\n    val.randomize();\n\n    CScript script(OP_LELANTUSJMINT);\n\n    auto vch = val.getvch();\n    script.insert(script.end(), vch.begin(), vch.end());\n\n    std::vector<unsigned char> encrypted;\n    encrypted.resize(16);\n\n    std::fill(encrypted.begin(), encrypted.end(), 0xff);\n    script.insert(script.end(), encrypted.begin(), encrypted.end());\n\n    // parse and verify\n    GroupElement outCoin;\n    std::vector<unsigned char> outEnc;\n    ParseLelantusJMintScript(script, outCoin, outEnc);\n\n    BOOST_CHECK(val == outCoin);\n    BOOST_CHECK(encrypted == outEnc);\n\n    GroupElement outCoin2;\n    ParseLelantusMintScript(script, outCoin2);\n\n    BOOST_CHECK(val == outCoin2);\n\n    // parse invalid\n    script.resize(script.size() - 1);\n    BOOST_CHECK_THROW(ParseLelantusJMintScript(script, outCoin, outEnc), std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(get_outpoint)\n{\n    GenerateBlocks(110);\n\n    // generate mints\n    std::vector<CMutableTransaction> txs;\n    auto mints = GenerateMints({2, 10}, txs);\n    auto mint = mints[0];\n    auto nonCommitted = mints[1];\n    auto tx = txs[0];\n    size_t mintIdx = 0;\n    for (; mintIdx < tx.vout.size(); mintIdx++) {\n        if (tx.vout[mintIdx].scriptPubKey.IsLelantusMint()) {\n            break;\n        }\n    }\n\n    auto blockIdx = GenerateBlock({txs[0]});\n\n    CBlock block;\n    BOOST_CHECK(ReadBlockFromDisk(block, blockIdx, ::Params().GetConsensus()));\n\n    block.lelantusTxInfo = std::make_shared<lelantus::CLelantusTxInfo>();\n    block.lelantusTxInfo->mints.emplace_back(std::make_pair(mint.GetPubcoinValue(), std::make_pair(mint.GetAmount(), uint256())));\n\n    lelantusState->AddMintsToStateAndBlockIndex(blockIdx, &block);\n    lelantusState->AddBlock(blockIdx);\n\n    // verify\n    COutPoint expectedOut(tx.GetHash(), mintIdx);\n\n    // GetOutPointFromBlock\n    COutPoint out;\n    BOOST_CHECK(GetOutPointFromBlock(out, mint.GetPubcoinValue(), block));\n    BOOST_CHECK(expectedOut == out);\n\n    BOOST_CHECK(!GetOutPointFromBlock(out, nonCommitted.GetPubcoinValue(), block));\n\n    // GetOutPoint\n    // by pubcoin\n    out = COutPoint();\n    BOOST_CHECK(GetOutPoint(out, PublicCoin(mint.GetPubcoinValue())));\n    BOOST_CHECK(expectedOut == out);\n\n    BOOST_CHECK(!GetOutPoint(out, PublicCoin(nonCommitted.GetPubcoinValue())));\n\n    // by pubcoin value\n    out = COutPoint();\n    BOOST_CHECK(GetOutPoint(out, mint.GetPubcoinValue()));\n    BOOST_CHECK(expectedOut == out);\n\n    BOOST_CHECK(!GetOutPoint(out, nonCommitted.GetPubcoinValue()));\n\n    // by pubcoin hash\n    out = COutPoint();\n    BOOST_CHECK(GetOutPoint(out, mint.GetPubCoinHash()));\n    BOOST_CHECK(expectedOut == out);\n\n    BOOST_CHECK(!GetOutPoint(out, nonCommitted.GetPubCoinHash()));\n}\n\nBOOST_AUTO_TEST_CASE(build_lelantus_state)\n{\n    GenerateBlocks(110);\n\n    // generate mints\n    std::vector<CMutableTransaction> txs;\n    auto mints = GenerateMints({1 * COIN, 2 * COIN, 10 * COIN, 100 * COIN}, txs);\n\n    GenerateBlock({txs[0], txs[1]});\n    auto blockIdx1 = chainActive.Tip();\n    auto block1 = GetCBlock(blockIdx1);\n\n    GenerateBlock({txs[2], txs[3]});\n    auto blockIdx2 = chainActive.Tip();\n    auto block2 = GetCBlock(blockIdx2);\n\n    block1.lelantusTxInfo = std::make_shared<lelantus::CLelantusTxInfo>();\n    block2.lelantusTxInfo = std::make_shared<lelantus::CLelantusTxInfo>();\n\n    block1.lelantusTxInfo->mints.emplace_back(std::make_pair(mints[0].GetPubcoinValue(), std::make_pair(mints[0].GetAmount(), uint256())));\n    block1.lelantusTxInfo->mints.emplace_back(std::make_pair(mints[1].GetPubcoinValue(), std::make_pair(mints[1].GetAmount(), uint256())));\n    block1.lelantusTxInfo->mints.emplace_back(std::make_pair(mints[2].GetPubcoinValue(), std::make_pair(mints[2].GetAmount(), uint256())));\n    block1.lelantusTxInfo->mints.emplace_back(std::make_pair(mints[3].GetPubcoinValue(), std::make_pair(mints[3].GetAmount(), uint256())));\n\n    lelantusState->AddMintsToStateAndBlockIndex(blockIdx1, &block1);\n    lelantusState->AddMintsToStateAndBlockIndex(blockIdx2, &block2);\n\n    BOOST_CHECK(BuildLelantusStateFromIndex(&chainActive));\n    BOOST_CHECK(lelantusState->HasCoin(mints[0].GetPubcoinValue()));\n    BOOST_CHECK(lelantusState->HasCoin(mints[1].GetPubcoinValue()));\n    BOOST_CHECK(lelantusState->HasCoin(mints[2].GetPubcoinValue()));\n    BOOST_CHECK(lelantusState->HasCoin(mints[3].GetPubcoinValue()));\n}\n\nBOOST_AUTO_TEST_CASE(connect_and_disconnect_block)\n{\n    // util function\n    auto reconnect = [](CBlock const &block) {\n        LOCK(cs_main);\n\n        std::shared_ptr<CBlock const> sharedBlock =\n        std::make_shared<CBlock const>(block);\n\n        CValidationState state;\n        ActivateBestChain(state, ::Params(), sharedBlock);\n    };\n\n    GenerateBlocks(1000);\n\n    std::vector<CMutableTransaction> mintTxs;\n    auto hdMints = GenerateMints({3 * COIN, 3 * COIN, 3 * COIN}, mintTxs);\n\n    struct {\n        // expected state.\n        std::vector<PublicCoin> coins;\n        std::vector<Scalar> serials;\n\n        // first group\n        CBlockIndex *first = nullptr;\n        CBlockIndex *last = nullptr;\n\n        int lastId = 0;\n\n        // real state\n        CLelantusState *state;\n\n        void Verify() const {\n            auto const &spends = state->GetSpends();\n            BOOST_CHECK_EQUAL(serials.size(), spends.size());\n            for (auto const &s : serials) {\n                BOOST_CHECK_MESSAGE(spends.count(s), \"serial is not found on state\");\n            }\n\n            auto const &mints = state->GetMints();\n            BOOST_CHECK_EQUAL(coins.size(), mints.size());\n            for (auto const &c : coins) {\n                BOOST_CHECK_MESSAGE(mints.count(c), \"public is not found on state\");\n            }\n\n            auto retrievedId = state->GetLatestCoinID();\n\n            CLelantusState::LelantusCoinGroupInfo group;\n            state->GetCoinGroupInfo(retrievedId, group);\n            BOOST_CHECK_EQUAL(lastId, retrievedId);\n            BOOST_CHECK_EQUAL(first, group.firstBlock);\n            BOOST_CHECK_EQUAL(last, group.lastBlock);\n            BOOST_CHECK_EQUAL(coins.size(), group.nCoins);\n        }\n    } checker;\n    checker.state = lelantusState;\n\n    // Cache empty checker\n    auto emptyChecker = checker;\n\n    // Generate some txs which contain mints\n    auto blockIdx1 = GenerateBlock({mintTxs[0], mintTxs[1]});\n    BOOST_CHECK(blockIdx1);\n    auto block1 = GetCBlock(blockIdx1);\n\n    checker.coins.push_back(hdMints[0].GetPubcoinValue());\n    checker.coins.push_back(hdMints[1].GetPubcoinValue());\n    checker.first = blockIdx1;\n    checker.last = blockIdx1;\n    checker.lastId = 1;\n    checker.Verify();\n\n    // Generate empty blocks should not effect state\n    GenerateBlocks(10);\n    checker.Verify();\n\n    // Add spend tx\n\n    // Create two txs which contains same serial.\n    CCoinControl coinControl;\n\n    {\n        auto tx = mintTxs[0];\n        auto it = std::find_if(tx.vout.begin(), tx.vout.end(), [](CTxOut const &out) -> bool {\n            return out.scriptPubKey.IsLelantusMint();\n        });\n        BOOST_CHECK(it != tx.vout.end());\n\n        coinControl.Select(COutPoint(tx.GetHash(), std::distance(tx.vout.begin(), it)));\n    }\n\n    auto jsTx1 = GenerateJoinSplit({1 * COIN}, {}, &coinControl);\n\n    // Update isused status\n    {\n        auto mint = hdMints[0];\n        auto hash = primitives::GetPubCoinValueHash(mint.GetPubcoinValue());\n\n        CLelantusMintMeta meta;\n        BOOST_CHECK(pwalletMain->zwallet->GetTracker()\n            .GetLelantusMetaFromPubcoin(hash, meta));\n\n        BOOST_CHECK(meta.isUsed);\n\n        meta.isUsed = false;\n        BOOST_CHECK(pwalletMain->zwallet->GetTracker().UpdateState(meta));\n\n        meta = CLelantusMintMeta();\n        BOOST_CHECK(pwalletMain->zwallet->GetTracker()\n            .GetLelantusMetaFromPubcoin(hash, meta));\n        BOOST_CHECK(!meta.isUsed);\n    }\n\n    // Create duplicated serial tx and test this at the bottom\n    auto dupJsTx1 = GenerateJoinSplit({1 * COIN}, {}, &coinControl);\n\n    std::vector<PublicCoin> dupNewCoins1;\n    std::vector<Scalar> dupSerials1;\n    ExtractJoinSplit(dupJsTx1, dupNewCoins1, dupSerials1);\n\n    std::vector<PublicCoin> newCoins1;\n    std::vector<Scalar> serials1;\n    ExtractJoinSplit(jsTx1, newCoins1, serials1);\n    BOOST_CHECK_EQUAL(1, newCoins1.size());\n    BOOST_CHECK_EQUAL(1, serials1.size());\n    BOOST_CHECK(dupSerials1[0] == serials1[0]);\n\n    auto blockIdx2 = GenerateBlock({jsTx1});\n    BOOST_CHECK(blockIdx2);\n    auto block2 = GetCBlock(blockIdx2);\n\n    auto cacheChecker = checker;\n    checker.coins.push_back(newCoins1.front());\n    checker.serials.push_back(serials1.front());\n    checker.last = blockIdx2;\n\n    checker.Verify();\n\n    // state should be rolled back\n    DisconnectBlocks(1);\n    BOOST_CHECK_EQUAL(chainActive.Tip()->nHeight, blockIdx2->nHeight - 1);\n    cacheChecker.Verify();\n\n    // reconnect\n    reconnect(block2);\n    checker.Verify();\n\n    // add more block contain both mint and serial\n    auto jsTx2 = GenerateJoinSplit({1 * COIN}, {CENT});\n    std::vector<PublicCoin> newCoins2;\n    std::vector<Scalar> serials2;\n    ExtractJoinSplit(jsTx2, newCoins2, serials2);\n    BOOST_CHECK_EQUAL(2, newCoins2.size());\n    BOOST_CHECK_EQUAL(1, serials2.size());\n\n    auto blockIdx3 = GenerateBlock({mintTxs[2], jsTx2});\n    BOOST_CHECK(blockIdx3);\n    auto block3 = GetCBlock(blockIdx3);\n\n    checker.coins.insert(checker.coins.end(), newCoins2.begin(), newCoins2.end());\n    checker.coins.push_back(hdMints[2].GetPubcoinValue());\n    checker.serials.push_back(serials2[0]);\n    checker.last = blockIdx3;\n\n    checker.Verify();\n\n    // Clear state and rebuild\n    lelantusState->Reset();\n    emptyChecker.Verify();\n\n    BuildLelantusStateFromIndex(&chainActive);\n    checker.Verify();\n\n    // Disconnect all and reconnect\n    std::vector<CBlock> blocks;\n    while (chainActive.Tip() != chainActive.Genesis()) {\n        blocks.push_back(GetCBlock(chainActive.Tip()));\n        DisconnectBlocks(1);\n    }\n\n    emptyChecker.Verify();\n\n    for (auto const &block : blocks) {\n        reconnect(block);\n    }\n\n    checker.Verify();\n\n    // double spend\n    auto currentBlock = chainActive.Tip()->nHeight;\n    BOOST_CHECK(!GenerateBlock({dupJsTx1}));\n    BOOST_CHECK_EQUAL(currentBlock, chainActive.Tip()->nHeight);\n    mempool.clear();\n    lelantusState->Reset();\n}\n\nBOOST_AUTO_TEST_CASE(checktransaction)\n{\n    GenerateBlocks(1000);\n\n    // mints\n    std::vector<CMutableTransaction> txs;\n    auto mints = GenerateMints({1 * CENT}, txs);\n    auto &tx = txs[0];\n\n    CValidationState state;\n    CLelantusTxInfo info;\n    BOOST_CHECK(CheckLelantusTransaction(\n        txs[0], state, tx.GetHash(), true, chainActive.Height(), true, true, NULL, &info));\n\n    std::vector<std::pair<PublicCoin, std::pair<uint64_t, uint256>>> expectedCoins = {{mints[0].GetPubcoinValue(), {1 * CENT, info.mints[0].second.second}}};\n\n    BOOST_CHECK(expectedCoins == info.mints);\n\n    // join split\n    txs.clear();\n    mints = GenerateMints({10 * CENT, 11 * CENT, 100 * CENT}, txs);\n    GenerateBlock(txs);\n    GenerateBlocks(10);\n\n    auto outputAmount = 8 * CENT;\n    auto mintAmount = 2 * CENT - CENT; // a cent as fee\n\n    CWalletTx wtx;\n    pwalletMain->JoinSplitLelantus(\n        {{script, outputAmount, false}},\n        {mintAmount},\n        wtx);\n\n    CMutableTransaction joinsplitTx(wtx);\n    auto joinsplit = ParseLelantusJoinSplit(joinsplitTx.vin[0]);\n\n    // test get join split amounts\n    BOOST_CHECK_EQUAL(1, GetSpendInputs(joinsplitTx));\n    BOOST_CHECK_EQUAL(1, GetSpendInputs(joinsplitTx, joinsplitTx.vin[0]));\n\n    info = CLelantusTxInfo();\n\n    BOOST_CHECK(CheckLelantusTransaction(\n        joinsplitTx, state, joinsplitTx.GetHash(), false, chainActive.Height(), false, true, NULL, &info));\n\n    auto &serials = joinsplit->getCoinSerialNumbers();\n    auto &ids = joinsplit->getCoinGroupIds();\n\n    for (size_t i = 0; i != serials.size(); i++) {\n        bool hasSerial = false;\n        BOOST_CHECK_MESSAGE(hasSerial = (info.spentSerials.count(serials[i]) > 0), \"No serial as expected\");\n        if (hasSerial) {\n            BOOST_CHECK_MESSAGE(ids[i] == info.spentSerials[serials[i]], \"Serials group id is invalid\");\n        }\n    }\n\n    info = CLelantusTxInfo();\n    BOOST_CHECK(CheckLelantusTransaction(\n        joinsplitTx, state, joinsplitTx.GetHash(), false, INT_MAX, false, true, NULL, &info));\n\n    // test surge dection.\n    while (!lelantusState->IsSurgeConditionDetected()) {\n        Scalar s;\n        s.randomize();\n\n        lelantusState->AddSpend(s, 1);\n    }\n\n    BOOST_CHECK(!CheckLelantusTransaction(\n        joinsplitTx, state, joinsplitTx.GetHash(), false, INT_MAX, false, true, NULL, &info));\n}\n\nBOOST_AUTO_TEST_CASE(spend_limitation_per_tx)\n{\n    PrivateCoin coinOut(params, 0);\n    JoinSplitScriptGenerator invalidG, validG;\n    invalidG.fee = 0;\n    invalidG.vout = 0;\n    invalidG.coinsOut = {coinOut};\n    invalidG.groupBlockHashes[1] = {ArithToUint256(0)};\n    invalidG.txHash = ArithToUint256(0);\n\n    validG.fee = 0;\n    validG.vout = 0;\n    validG.coinsOut = {coinOut};\n    validG.groupBlockHashes[1] = ArithToUint256(0);\n    validG.txHash = ArithToUint256(0);\n\n    for (size_t i = 0; i != consensus.nMaxLelantusInputPerTransaction + 1; i++) {\n        PrivateCoin coin(params, 0);\n        invalidG.coins.emplace_back(coin, 1);\n        invalidG.anons[1].push_back(coin.getPublicCoin());\n\n        if (i != 0) { // skip first\n            validG.coins.emplace_back(coin, 1);\n            validG.anons[1].push_back(coin.getPublicCoin());\n        }\n    }\n\n    CMutableTransaction invalidTx, validTx;\n    invalidTx.vin.resize(1);\n    invalidTx.vin[0].scriptSig = invalidG.Get().first;\n\n    validTx.vin.resize(1);\n    validTx.vin[0].scriptSig = validG.Get().first;\n\n    CBlock invalidBlock, validBlock;\n    invalidBlock.vtx.push_back(MakeTransactionRef(invalidTx));\n    validBlock.vtx.push_back(MakeTransactionRef(validTx));\n\n    CValidationState state;\n    BOOST_CHECK(!CheckLelantusBlock(state, invalidBlock));\n    BOOST_CHECK(CheckLelantusBlock(state, validBlock));\n}\n\nBOOST_AUTO_TEST_CASE(spend_limitation_per_block)\n{\n    CBlock block;\n    size_t spends = 0;\n\n    for (size_t i = 0; spends <= consensus.nMaxLelantusInputPerBlock; i++) {\n        PrivateCoin coinOut(params, 0);\n        JoinSplitScriptGenerator g;\n        g.fee = 0;\n        g.vout = 0;\n        g.coinsOut = {coinOut};\n        for (size_t i = 0; i != consensus.nMaxLelantusInputPerTransaction; i++) {\n            PrivateCoin coin(params, 0);\n            g.coins.emplace_back(coin, 1);\n            g.anons[1].push_back(coin.getPublicCoin());\n\n            spends++;\n        }\n\n        g.groupBlockHashes[1] = ArithToUint256(i);\n        g.txHash = ArithToUint256(i);\n\n        CMutableTransaction tx;\n        tx.vin.resize(1);\n        tx.vin[0].scriptSig = g.Get().first;\n\n\n        block.vtx.push_back(MakeTransactionRef(tx));\n    }\n\n    CValidationState state;\n    BOOST_CHECK(!CheckLelantusBlock(state, block));\n\n    block.vtx.pop_back();\n    BOOST_CHECK(CheckLelantusBlock(state, block));\n}\n\nBOOST_AUTO_TEST_CASE(parse_joinsplit)\n{\n    auto coins = GenerateMints({1 * COIN, 10 * COIN, 1 * COIN, 1 * COIN});\n\n    JoinSplitScriptGenerator g;\n    g.params = params;\n    g.coins = {{coins[0], 1}, {coins[1], 1}, {coins[2], 2}};\n    for (auto id : {1, 2}) {\n        for (size_t i = 0; i != 10; i++) {\n            GroupElement e;\n            e.randomize();\n\n            g.anons[id].emplace_back(e);\n        }\n    }\n\n    g.anons[1][0] = coins[0].getPublicCoin();\n    g.anons[1][1] = coins[1].getPublicCoin();\n    g.anons[2][0] = coins[2].getPublicCoin();\n\n    g.vout = 11 * COIN - CENT;\n    g.coinsOut.push_back(coins[3]);\n    g.fee = CENT;\n    g.groupBlockHashes[1] = ArithToUint256(1);\n    g.groupBlockHashes[2] = ArithToUint256(2);\n    g.txHash = ArithToUint256(3);\n\n    auto gs = g.Get();\n    CTxIn inp(COutPoint(), gs.first);\n\n    auto result = ParseLelantusJoinSplit(inp);\n\n    BOOST_CHECK(gs.second.getCoinSerialNumbers() == result->getCoinSerialNumbers());\n    BOOST_CHECK(gs.second.getFee() == result->getFee());\n    BOOST_CHECK(gs.second.getCoinGroupIds() == result->getCoinGroupIds());\n    BOOST_CHECK(gs.second.getIdAndBlockHashes() == result->getIdAndBlockHashes());\n    BOOST_CHECK(gs.second.getVersion() == result->getVersion());\n    BOOST_CHECK(gs.second.HasValidSerials() == result->HasValidSerials());\n\n    BOOST_CHECK(gs.second.Verify(g.anons, ExtractCoins(g.coinsOut), g.vout, g.txHash));\n    BOOST_CHECK(result->Verify(g.anons, ExtractCoins(g.coinsOut), g.vout, g.txHash));\n}\n\nBOOST_AUTO_TEST_CASE(coingroup)\n{\n    GenerateBlocks(1000);\n\n    // util function\n    auto reconnect = [](CBlock const &block) {\n        LOCK2(cs_main, pwalletMain->cs_wallet);\n        LOCK(mempool.cs);\n\n        std::shared_ptr<CBlock const> sharedBlock =\n        std::make_shared<CBlock const>(block);\n\n        CValidationState state;\n        ActivateBestChain(state, ::Params(), sharedBlock);\n    };\n\n    struct {\n        // expected state.\n        std::vector<PublicCoin> coins;\n\n        // first group\n        CBlockIndex *first = nullptr;\n        CBlockIndex *last = nullptr;\n\n        int lastId = 0;\n        size_t lastGroupCoins = 0;\n\n        // real state\n        CLelantusState *state;\n\n        void Verify(std::string stateName = \"\") const {\n            auto const &mints = state->GetMints();\n            BOOST_CHECK_EQUAL(coins.size(), mints.size());\n            for (auto const &c : coins) {\n                BOOST_CHECK_MESSAGE(mints.count(c), \"public is not found on state : \" + stateName);\n            }\n\n            auto retrievedId = state->GetLatestCoinID();\n\n            CLelantusState::LelantusCoinGroupInfo group;\n            state->GetCoinGroupInfo(retrievedId, group);\n\n            BOOST_CHECK_EQUAL(lastId, retrievedId);\n            BOOST_CHECK_EQUAL(first, group.firstBlock);\n            BOOST_CHECK_EQUAL(last, group.lastBlock);\n            BOOST_CHECK_EQUAL(lastGroupCoins, group.nCoins);\n        }\n    } checker;\n    checker.state = lelantusState;\n\n    lelantusState->~CLelantusState();\n    new (lelantusState) CLelantusState(65, 16);\n    lelantusState->Reset();\n\n    // logic\n    std::vector<CMutableTransaction> txs;\n    std::vector<lelantus::PrivateCoin> coins;\n    auto hdMints = GenerateMints(std::vector<CAmount>(66, 1), txs, coins);\n\n    auto txRange = [&](size_t start, size_t end) -> std::vector<CMutableTransaction> {\n        std::vector<CMutableTransaction> rangeTxs;\n        for (auto i = start; i < end && i < txs.size(); i++) {\n            rangeTxs.push_back(txs[i]);\n        }\n\n        return rangeTxs;\n    };\n\n    std::vector<PublicCoin> pubCoins;\n    for (auto const &hdMint : hdMints) {\n        pubCoins.push_back(hdMint.GetPubcoinValue());\n    }\n\n    auto emptyChecker = checker;\n    emptyChecker.Verify();\n\n    // add one block\n    auto idx1 = GenerateBlock(txRange(0, 1));\n    auto block1 = GetCBlock(idx1);\n\n    checker.coins.push_back(pubCoins[0]);\n    checker.lastId = 1;\n    checker.first = idx1;\n    checker.last = idx1;\n    checker.lastGroupCoins = 1;\n    checker.Verify();\n\n    // add more\n    auto idx2 = GenerateBlock(txRange(1, 32));\n    auto block2 = GetCBlock(idx2);\n\n    checker.coins.insert(checker.coins.end(), pubCoins.begin() + 1, pubCoins.begin() + 32);\n    checker.last = idx2;\n    checker.lastGroupCoins = 32;\n    checker.Verify();\n\n    auto cacheIdx2Checker = checker;\n\n    // add more to fill group\n    auto idx3 = GenerateBlock(txRange(32, 65));\n    auto block3 = GetCBlock(idx3);\n\n    checker.coins.insert(checker.coins.end(), pubCoins.begin() + 32, pubCoins.begin() + 65);\n    checker.last = idx3;\n    checker.lastGroupCoins = 65;\n    checker.Verify();\n\n    auto cacheIdx3Checker = checker;\n\n    // add one more to create new group\n    auto idx4 = GenerateBlock(txRange(65, 66));\n    auto block4 = GetCBlock(idx4);\n\n    checker.coins.push_back(pubCoins[65]);\n    checker.lastId = 2;\n    checker.lastGroupCoins = 34;\n    checker.first = idx3;\n    checker.last = idx4;\n\n    checker.Verify();\n\n    // remove last block check coingroup\n    DisconnectBlocks(1);\n    cacheIdx3Checker.Verify();\n\n    // remove one more block\n    DisconnectBlocks(1);\n    cacheIdx2Checker.Verify();\n\n    // reconnect them all and check state\n    reconnect(block2);\n    reconnect(block3);\n    checker.Verify();\n\n    lelantusState->~CLelantusState();\n    new (lelantusState) CLelantusState();\n    lelantusState->Reset();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n};", "meta": {"hexsha": "3e5add8ca98adc40dfb9a5977a4ea9394066df6a", "size": 26831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/lelantus_tests.cpp", "max_stars_repo_name": "xinya-123/firo", "max_stars_repo_head_hexsha": "738c8e1f96fa4c332a157776366b884a451194a2", "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/test/lelantus_tests.cpp", "max_issues_repo_name": "xinya-123/firo", "max_issues_repo_head_hexsha": "738c8e1f96fa4c332a157776366b884a451194a2", "max_issues_repo_licenses": ["MIT"], "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/lelantus_tests.cpp", "max_forks_repo_name": "xinya-123/firo", "max_forks_repo_head_hexsha": "738c8e1f96fa4c332a157776366b884a451194a2", "max_forks_repo_licenses": ["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.4206349206, "max_line_length": 157, "alphanum_fraction": 0.6520442771, "num_tokens": 7205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.19188053132436725}}
{"text": "#include \"Time.h\"\n#include \"TimeScale.h\"\n\n#include <boost/date_time/posix_time/posix_time.hpp>\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\nusing boost::gregorian::date;\nusing boost::gregorian::days;\n\nnamespace teatime {\n\nconst int64 Epoch1400 = 510974; // number of days between 1.1.1 and 1.1.1400\nconst int64 Epoch1970 = 719162; // number of days between 1.1.1 and 1.1.1970\n\nTime::Time(int64 ticks)\n{\n  this->ticks_ = ticks;\n}\n\nTime::Time(ptime t)\n{\n  auto datePart = t.date();\n  auto timePart = t.time_of_day();\n\n  TimeScale timeScale = TimeScale::Master();\n\n  // consider date part only\n  auto d = datePart - date(1970, 1, 1);\n  int offsetFromEpochDays = d.days();  \n  this->ticks_ = timeScale.TicksPerDay() * offsetFromEpochDays;\n    \n  // add ticks for time of day\n  if(time_duration::ticks_per_second() > timeScale.TicksPerSecond()) // since the following computations are integer calculcations, we distinguish here\n  {\n    int64 conversionRate = time_duration::ticks_per_second() / timeScale.TicksPerSecond();\n    this->ticks_ += timePart.ticks() / conversionRate;\n  }\n  else\n  {\n    int64 conversionRate = timeScale.TicksPerSecond() / time_duration::ticks_per_second();\n    this->ticks_ += timePart.ticks() * conversionRate;\n  }  \n}\n\nptime Time::ToPosixTime() const\n{\n  return this->ToPosixTime(TimeScale::Master());\n}\n\nptime Time::ToPosixTime(TimeScale& timeScale) const\n{\n  auto ticks = this->ticks_;\n\n  //  adjust ticks for epoch 1970\n  int64 epochDelta = Epoch1970 - timeScale.Epoch();\n  ticks -= epochDelta * timeScale.TicksPerDay(); // now the ticks are epoch'd 1970, so we use 1970,1,1 below\n  \n  // create time duration considering resolution.\n  if(time_duration::ticks_per_second() > timeScale.TicksPerSecond()) // since the following computations are integer calculcations, we distinguish here\n  {\n    int64 conversionRate = time_duration::ticks_per_second() / timeScale.TicksPerSecond();\n    ticks = conversionRate * ticks;\n  }\n  else\n  {\n    int64 conversionRate = timeScale.TicksPerSecond() / time_duration::ticks_per_second();\n    ticks = ticks / conversionRate;\n  }\n  \n  // date(1970) + ptime ticks since (1970)\n  time_duration durationSinceEpoch(0, 0, 0, ticks);\n  ptime pt(date(1970, 1, 1), durationSinceEpoch);\n  return pt;\n}\n\nTime Time::AddDays(int numberOfDays)\n{\n    return Time(this->ticks_ + numberOfDays * TimeScale::Master().TicksPerDay());\n}\n\nTime Time::Date() const\n{\n  return Time(this->ticks_ - this->ticks_ % TimeScale::Master().TicksPerDay());\n}\n\nint Time::Year() const\n{\n  return this->ToPosixTime().date().year();\n}\n\nint Time::Month() const\n{\n  return this->ToPosixTime().date().month();\n}\n\nint Time::Day() const\n{\n  return this->ToPosixTime().date().day();\n}\n\ntime_duration Time::TimeOfDay() const\n{\n  return this->ToPosixTime().time_of_day();\n}\n\nint Time::Hour() const\n{\n  return this->TimeOfDay().hours();\n}\n\nint Time::Minute() const\n{\n  return this->TimeOfDay().minutes();\n}\n\nint Time::Second() const\n{\n  return this->TimeOfDay().seconds();\n}\n\nbool Time::operator> (const Time& other) const\n{\n  return this->ticks_ > other.ticks_;\n}\n\nbool Time::operator>=(const Time& other) const\n{\n  return this->ticks_ >= other.ticks_;\n}\n\nbool Time::operator< (const Time& other) const\n{\n  return this->ticks_ < other.ticks_;\n}\n\nbool Time::operator<=(const Time& other) const\n{\n  return this->ticks_ <= other.ticks_;\n}\n\nbool Time::operator== (const Time& other) const\n{\n  return this->ticks_ == other.ticks_;\n}\n\nbool Time::operator!=(const Time& other) const\n{\n  return this->ticks_ != other.ticks_;\n}\n\n} // namespace teatime\n", "meta": {"hexsha": "f29374b1698685eda444e8204dd86f722ab5c8c6", "size": 3585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TeaFiles/time/Time.cpp", "max_stars_repo_name": "fced42/TeaFiles.Cpp", "max_stars_repo_head_hexsha": "6702a2056d025da9d18d0112ba294ac47269e861", "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": "TeaFiles/time/Time.cpp", "max_issues_repo_name": "fced42/TeaFiles.Cpp", "max_issues_repo_head_hexsha": "6702a2056d025da9d18d0112ba294ac47269e861", "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": "TeaFiles/time/Time.cpp", "max_forks_repo_name": "fced42/TeaFiles.Cpp", "max_forks_repo_head_hexsha": "6702a2056d025da9d18d0112ba294ac47269e861", "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.5855263158, "max_line_length": 151, "alphanum_fraction": 0.69986053, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.1918805294958869}}
{"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_DEFINITION_SATURATE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DEFINITION_SATURATE_HPP_INCLUDED\n\n#include <boost/simd/config.hpp>\n#include <boost/simd/detail/dispatch.hpp>\n#include <boost/simd/as.hpp>\n#include <boost/simd/detail/dispatch/function/make_callable.hpp>\n#include <boost/simd/detail/dispatch/hierarchy/functions.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    BOOST_DISPATCH_MAKE_TAG(ext, saturate_, boost::dispatch::elementwise_<saturate_>);\n  }\n\n  namespace ext\n  {\n    BOOST_DISPATCH_FUNCTION_DECLARATION(tag, saturate_);\n  }\n\n  namespace functional\n  {\n    BOOST_DISPATCH_CALLABLE_DEFINITION(tag::saturate_,saturate);\n  }\n\n  template<typename T, typename A> BOOST_FORCEINLINE A saturate(const A& a) BOOST_NOEXCEPT\n  {\n    return functional::saturate(a, as_<T>());\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "e0a24ebc565ca64cddfa8292be67bbd200287719", "size": 1258, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/definition/saturate.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/function/definition/saturate.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/definition/saturate.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": 27.9555555556, "max_line_length": 100, "alphanum_fraction": 0.6406995231, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19188052770221994}}
{"text": "/* Noah Himed\n *\n * Implement the Board type.\n *\n * Licensed under MIT License. Terms and conditions enclosed in \"LICENSE.txt\".\n */\n\n#include \"board.h\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <cctype>\n#include <chrono>\n#include <cstdint>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n\n#include \"bad_move.h\"\n#include \"move.h\"\n\nnamespace omegazero {\n\nusing std::invalid_argument;\nusing std::string;\n\nusing std::cout;\nusing std::endl;\n\ntypedef boost::multiprecision::uint128_t U128;\n\nBoard::Board(const string& init_pos) {\n  for (S8 piece_type = kPawn; piece_type <= kKing; ++piece_type) {\n    pieces_[piece_type] = 0ULL;\n  }\n  for (S8 player = kWhite; player <= kBlack; ++player) {\n    player_pieces_[player] = 0ULL;\n    // Initialize all castling rights to false before parsing the FEN string to\n    // set the board, which may reset some castling rights to true.\n    for (S8 board_side = kQueenSide; board_side <= kKingSide; ++board_side) {\n      castling_rights_[player][board_side] = false;\n    }\n  }\n  ep_target_sq_ = kNA;\n\n  // Set the piece positions, castling rights, and player to move.\n  InitBoardPos(init_pos);\n  InitBoardHash();\n}\n\nauto Board::GetAttackMap(S8 attacking_player, S8 sq, S8 attacking_piece) const\n    -> Bitboard {\n  if (!SqOnBoard(sq)) {\n    throw invalid_argument(\"sq in Board::GetAttackMap()\");\n  }\n\n  Bitboard attack_map = 0X0;\n  S8 attacked_player = GetOtherPlayer(attacking_player);\n  switch (attacking_piece) {\n    case kPawn: {\n      Bitboard capture_attacks;\n      Bitboard push_attacks;\n      if (attacking_player == kWhite) {\n        capture_attacks = kNonSliderAttackMaps[kWhitePawnCapture][sq];\n        push_attacks = kNonSliderAttackMaps[kWhitePawnPush][sq];\n      } else {\n        capture_attacks = kNonSliderAttackMaps[kBlackPawnCapture][sq];\n        push_attacks = kNonSliderAttackMaps[kBlackPawnPush][sq];\n      }\n      // Include captures that attack occupied squares and push moves that move\n      // onto empty squares only. Note that the resulting attack map may include\n      // squares in front of the pawn occupied by other pieces. This is\n      // necessary due to how the function is used by other parts of the engine.\n      attack_map =\n          (capture_attacks & player_pieces_[attacked_player]) | push_attacks;\n      break;\n    }\n    case kKnight:\n      attack_map = kNonSliderAttackMaps[kKnightAttack][sq];\n      break;\n    // Use the magic bitboard method to get possible moves for bishops and\n    // rooks. The Boost library's 128 bit unsigned int data type \"U128\"\n    // is used here to avoid integer overflow.\n    case kBishop: {\n      Bitboard all_pieces = player_pieces_[kWhite] | player_pieces_[kBlack];\n      Bitboard blockers = kSliderPieceMaps[kBishopMoves][sq] & all_pieces;\n      if (blockers == 0X0) {\n        attack_map = kUnblockedSliderAttackMaps[kBishopMoves][sq];\n      } else {\n        U128 magic = kMagics[kBishopMoves][sq];\n        U128 index = (blockers * magic) >> (kNumSq - kBishopMagicLengths[sq]);\n        U64 index_U64 = static_cast<U64>(index);\n        attack_map = kMagicIndexToAttackMap.at(index_U64);\n      }\n      break;\n    }\n    case kRook: {\n      Bitboard all_pieces = player_pieces_[kWhite] | player_pieces_[kBlack];\n      Bitboard blockers = kSliderPieceMaps[kRookMoves][sq] & all_pieces;\n      if (blockers == 0X0) {\n        attack_map = kUnblockedSliderAttackMaps[kRookMoves][sq];\n      } else {\n        U128 magic = kMagics[kRookMoves][sq];\n        U128 index = (blockers * magic) >> (kNumSq - kRookMagicLengths[sq]);\n        U64 index_U64 = static_cast<U64>(index);\n        attack_map = kMagicIndexToAttackMap.at(index_U64);\n      }\n      break;\n    }\n    // Combine the attack maps of a rook and bishop to get a queen's attack.\n    case kQueen: {\n      Bitboard bishop_attack = GetAttackMap(attacking_player, sq, kBishop);\n      Bitboard rook_attack = GetAttackMap(attacking_player, sq, kRook);\n      return bishop_attack | rook_attack;\n    }\n    case kKing:\n      attack_map = kNonSliderAttackMaps[kKingAttack][sq];\n      break;\n    default:\n      throw invalid_argument(\"attacking_piece in Board::GetAttackMap()\");\n  }\n\n  return attack_map;\n}\n\nauto Board::GetPiecesByType(S8 piece_type, S8 player) const -> Bitboard {\n  if (piece_type == kNA) {\n    if (player == kWhite || player == kBlack) {\n      return player_pieces_[player];\n    }\n    throw invalid_argument(\"player in Board::GetPiecesByType()\");\n  }\n  if (player == kNA) {\n    if (piece_type >= kPawn && piece_type <= kKing) {\n      return pieces_[piece_type];\n    }\n    throw invalid_argument(\"piece_type in Board::GetPiecesByType()\");\n  }\n  if ((piece_type >= kPawn && piece_type <= kKing) &&\n      (player == kWhite || player == kBlack)) {\n    return pieces_[piece_type] & player_pieces_[player];\n  }\n\n  throw invalid_argument(\"player, piece_type in Board::GetPiecesByType\");\n}\n\nauto Board::CastlingLegal(S8 board_side) const -> bool {\n  // For castling moves, check that the following hold:\n  //   * Neither the king nor the chosen rook has previously moved.\n  //   * There are no pieces between the king and the chosen rook.\n  //   * The king is not currently in check.\n  //   * The king does not pass through a square that is attacked by an enemy\n  //     piece.\n  if (board_side == kQueenSide) {\n    return castling_rights_[player_to_move_][kQueenSide] && !KingInCheck() &&\n           ((player_to_move_ == kWhite && piece_layout_[kSqB1] == kNA &&\n             piece_layout_[kSqC1] == kNA && piece_layout_[kSqD1] == kNA &&\n             GetAttackersToSq(kSqD1, kWhite) == 0X0) ||\n            (player_to_move_ == kBlack && GetPieceOnSq(kSqB8) == kNA &&\n             piece_layout_[kSqC8] == kNA && piece_layout_[kSqD8] == kNA &&\n             GetAttackersToSq(kSqD8, kBlack) == 0X0));\n  }\n  if (board_side == kKingSide) {\n    return castling_rights_[player_to_move_][kKingSide] && !KingInCheck() &&\n           ((player_to_move_ == kWhite && piece_layout_[kSqF1] == kNA &&\n             GetAttackersToSq(kSqF1, kWhite) == 0X0 &&\n             piece_layout_[kSqG1] == kNA) ||\n            (player_to_move_ == kBlack && GetPieceOnSq(kSqF8) == kNA &&\n             GetAttackersToSq(kSqF8, kBlack) == 0X0 &&\n             piece_layout_[kSqG8] == kNA));\n  }\n\n  throw invalid_argument(\"board_side in Board::CastlingLegal()\");\n}\n\nauto Board::DoublePawnPushLegal(S8 file) const -> bool {\n  if (!FileOnBoard(file)) {\n    throw invalid_argument(\"file in Board::DoublePawnPushLegal()\");\n  }\n\n  if (player_to_move_ == kWhite) {\n    S8 rank3_double_pawn_push_sq = GetSqFromRankFile(kRank3, file);\n    S8 rank2_double_pawn_push_sq = GetSqFromRankFile(kRank2, file);\n    return piece_layout_[rank3_double_pawn_push_sq] == kNA &&\n           piece_layout_[rank2_double_pawn_push_sq] == kPawn &&\n           player_layout_[rank2_double_pawn_push_sq] == kWhite;\n  }\n  // Handle the case of evaluating if a double pawn push from black is legal.\n  S8 rank6_double_pawn_push_sq = GetSqFromRankFile(kRank6, file);\n  S8 rank7_double_pawn_push_sq = GetSqFromRankFile(kRank7, file);\n  return piece_layout_[rank6_double_pawn_push_sq] == kNA &&\n         piece_layout_[rank7_double_pawn_push_sq] == kPawn &&\n         player_layout_[rank7_double_pawn_push_sq] == kBlack;\n}\n\nauto Board::Evaluate() const -> int {\n  Bitboard white_pieces;\n  Bitboard black_pieces;\n  int board_score = 0;\n  for (S8 piece_type = kPawn; piece_type <= kKing; ++piece_type) {\n    white_pieces = pieces_[piece_type] & player_pieces_[kWhite];\n    black_pieces = pieces_[piece_type] & player_pieces_[kBlack];\n    board_score += kPieceVals[piece_type] *\n                   (GetNumSetSq(white_pieces) - GetNumSetSq(black_pieces));\n  }\n  S8 moving_side = (player_to_move_ == kWhite) ? 1 : -1;\n  return board_score * moving_side;\n}\n\nauto Board::MakeMove(const Move& move) -> void {\n  if (move.castling_type == kNA) {\n    MakeNonCastlingMove(move);\n  } else if (move.castling_type == kQueenSide) {\n    // Make queenside castling moves.\n    if (player_to_move_ == kWhite) {\n      MovePiece(kRook, kSqA1, kSqD1);\n      MovePiece(kKing, kSqE1, kSqC1);\n    } else if (player_to_move_ == kBlack) {\n      MovePiece(kRook, kSqA8, kSqD8);\n      MovePiece(kKing, kSqE8, kSqC8);\n    }\n  } else if (move.castling_type == kKingSide) {\n    // Make kingside castling moves.\n    if (player_to_move_ == kWhite) {\n      MovePiece(kRook, kSqH1, kSqF1);\n      MovePiece(kKing, kSqE1, kSqG1);\n    } else if (player_to_move_ == kBlack) {\n      MovePiece(kRook, kSqH8, kSqF8);\n      MovePiece(kKing, kSqE8, kSqG8);\n    }\n  }\n\n  // Update the en passent target square and the board hash to reflect a change\n  // in the file of the en passent target square.\n  ep_target_sq_history_.push(ep_target_sq_);\n  S8 prev_ep_target_file =\n      (ep_target_sq_ == kNA) ? kNA : GetFileFromSq(ep_target_sq_);\n  ep_target_sq_ = move.new_ep_target_sq;\n  S8 curr_ep_target_file =\n      (ep_target_sq_ == kNA) ? kNA : GetFileFromSq(ep_target_sq_);\n  if (prev_ep_target_file != curr_ep_target_file) {\n    if (prev_ep_target_file != kNA) {\n      board_hash_ ^= ep_file_rand_nums_[prev_ep_target_file];\n    }\n    if (curr_ep_target_file != kNA) {\n      board_hash_ ^= ep_file_rand_nums_[curr_ep_target_file];\n    }\n  }\n\n  // Reset the halfmove clock if a pawn was moved or if a move resulted in a\n  // capture.\n  halfmove_clock_history_.push(halfmove_clock_);\n  if (move.captured_piece != kNA || move.moving_piece == kPawn) {\n    halfmove_clock_ = 0;\n  } else {\n    ++halfmove_clock_;\n  }\n\n  UpdateCastlingRights(move);\n\n  // Undo the move if it puts the king in check.\n  if (KingInCheck()) {\n    SwitchPlayer();\n    UnmakeMove(move);\n    throw BadMove(\"move leaves king in check\");\n  }\n\n  SwitchPlayer();\n  // Update the board hash to reflect player turnover.\n  board_hash_ ^= black_to_move_rand_num_;\n}\n\n// Assume the passed move has been made use MakeMove(). Calling UnmakeMove()\n// on a move that wasn't already made will result in undefined behavior.\nauto Board::UnmakeMove(const Move& move) -> void {\n  // Revert back to the previous player.\n  SwitchPlayer();\n  // Update the board hash to reflect player turnover.\n  board_hash_ ^= black_to_move_rand_num_;\n\n  if (move.castling_type == kNA) {\n    // Undo all non-castling moves.\n    UnmakeNonCastlingMove(move);\n  } else if (move.castling_type == kQueenSide) {\n    // Undo queenside castling moves.\n    if (player_to_move_ == kWhite) {\n      MovePiece(kRook, kSqD1, kSqA1);\n      MovePiece(kKing, kSqC1, kSqE1);\n    } else if (player_to_move_ == kBlack) {\n      MovePiece(kRook, kSqD8, kSqA8);\n      MovePiece(kKing, kSqC8, kSqE8);\n    }\n  } else if (move.castling_type == kKingSide) {\n    // Undo kingside castling moves.\n    if (player_to_move_ == kWhite) {\n      MovePiece(kRook, kSqF1, kSqH1);\n      MovePiece(kKing, kSqG1, kSqE1);\n    } else if (player_to_move_ == kBlack) {\n      MovePiece(kRook, kSqF8, kSqH8);\n      MovePiece(kKing, kSqG8, kSqE8);\n    }\n  }\n\n  // Revert the halfmove clock.\n  halfmove_clock_ = halfmove_clock_history_.top();\n  halfmove_clock_history_.pop();\n\n  // Revert the en passent target square and update the board hash.\n  if (ep_target_sq_ != kNA) {\n    S8 ep_file = GetFileFromSq(ep_target_sq_);\n    board_hash_ ^= ep_file_rand_nums_[ep_file];\n  }\n  ep_target_sq_ = ep_target_sq_history_.top();\n  ep_target_sq_history_.pop();\n  if (ep_target_sq_ != kNA) {\n    S8 ep_file = GetFileFromSq(ep_target_sq_);\n    board_hash_ ^= ep_file_rand_nums_[ep_file];\n  }\n\n  // Revert all castling rights and update the board hash.\n  if (castling_rights_[kWhite][kQueenSide] !=\n      white_queenside_castling_rights_history_.top()) {\n    board_hash_ ^= castling_rights_rand_nums_[kWhite][kQueenSide];\n    castling_rights_[kWhite][kQueenSide] =\n        white_queenside_castling_rights_history_.top();\n  }\n  white_queenside_castling_rights_history_.pop();\n  if (castling_rights_[kWhite][kKingSide] !=\n      white_kingside_castling_rights_history_.top()) {\n    board_hash_ ^= castling_rights_rand_nums_[kWhite][kKingSide];\n    castling_rights_[kWhite][kKingSide] =\n        white_kingside_castling_rights_history_.top();\n  }\n  white_kingside_castling_rights_history_.pop();\n  if (castling_rights_[kBlack][kQueenSide] !=\n      black_queenside_castling_rights_history_.top()) {\n    board_hash_ ^= castling_rights_rand_nums_[kBlack][kQueenSide];\n    castling_rights_[kBlack][kQueenSide] =\n        black_queenside_castling_rights_history_.top();\n  }\n  black_queenside_castling_rights_history_.pop();\n  if (castling_rights_[kBlack][kKingSide] !=\n      black_kingside_castling_rights_history_.top()) {\n    board_hash_ ^= castling_rights_rand_nums_[kBlack][kKingSide];\n    castling_rights_[kBlack][kKingSide] =\n        black_kingside_castling_rights_history_.top();\n  }\n  black_kingside_castling_rights_history_.pop();\n}\n\n// Implemement private member functions.\n\nauto Board::GetAttackersToSq(S8 sq, S8 attacked_player) const -> Bitboard {\n  if (!SqOnBoard(sq)) {\n    throw invalid_argument(\"sq in Board::GetAttackersToSq()\");\n  }\n\n  Bitboard potential_pawn_attacks;\n  S8 attacking_player = GetOtherPlayer(attacked_player);\n  // Capture only diagonal squares to sq in the direction of movement.\n  if (attacked_player == kWhite) {\n    potential_pawn_attacks = kNonSliderAttackMaps[kWhitePawnCapture][sq];\n  } else {\n    potential_pawn_attacks = kNonSliderAttackMaps[kBlackPawnCapture][sq];\n  }\n  // Compute the union (bitwise OR) of all pieces of each type that could\n  // capture the square \"sq\"; each of these bitboards are computed by\n  // finding the intersection (bitwise AND) between all spots a piece of a\n  // given type could move to from sq, and all the positions that pieces of\n  // this type from the opposing player are located.\n  return (potential_pawn_attacks & GetPiecesByType(kPawn, attacking_player)) |\n         (GetAttackMap(attacked_player, sq, kKnight) &\n          GetPiecesByType(kKnight, attacking_player)) |\n         (GetAttackMap(attacked_player, sq, kBishop) &\n          GetPiecesByType(kBishop, attacking_player)) |\n         (GetAttackMap(attacked_player, sq, kRook) &\n          GetPiecesByType(kRook, attacking_player)) |\n         (GetAttackMap(attacked_player, sq, kQueen) &\n          GetPiecesByType(kQueen, attacking_player)) |\n         (GetAttackMap(attacked_player, sq, kKing) &\n          GetPiecesByType(kKing, attacking_player));\n}\n\nauto Board::AddPiece(S8 piece_type, S8 player, S8 sq) -> void {\n  if (!SqOnBoard(sq)) {\n    throw invalid_argument(\"sq in Board::AddPiece()\");\n  }\n\n  if (piece_type == kNA && player == kNA) {\n    piece_layout_[sq] = kNA;\n    player_layout_[sq] = kNA;\n  } else if (piece_type >= kPawn && piece_type <= kKing &&\n             (player == kWhite || player == kBlack)) {\n    Bitboard piece_mask = 1ULL << sq;\n    pieces_[piece_type] |= piece_mask;\n    player_pieces_[player] |= piece_mask;\n    piece_layout_[sq] = piece_type;\n    player_layout_[sq] = player;\n  } else {\n    throw invalid_argument(\"piece_type, player in Board::AddPiece()\");\n  }\n}\n\nauto Board::InitBoardHash() -> void {\n  board_hash_ = 0X0;\n  // Initialize the Mersenne Twister 64 bit pseudo-random number generator.\n  U64 seed = std::chrono::system_clock::now().time_since_epoch().count();\n  std::mt19937_64 rand_num_gen(seed);\n  // Generate a set of random numbers for Zobrist Hashing.\n  for (S8 player = kWhite; player < kNumPlayers; ++player) {\n    for (S8 board_side = kQueenSide; board_side <= kKingSide; ++board_side) {\n      castling_rights_rand_nums_[player][board_side] = rand_num_gen();\n      if (castling_rights_[player][board_side]) {\n        board_hash_ ^= castling_rights_rand_nums_[player][board_side];\n      }\n    }\n  }\n  for (S8 file = kFileA; file <= kFileH; ++file) {\n    ep_file_rand_nums_[file] = rand_num_gen();\n  }\n  // Update the hash using the current en passent target square.\n  if (ep_target_sq_ != kNA) {\n    S8 ep_target_file = GetFileFromSq(ep_target_sq_);\n    board_hash_ ^= ep_file_rand_nums_[ep_target_file];\n  }\n  S8 piece_type;\n  for (S8 piece = kPawn; piece <= kKing; ++piece) {\n    for (S8 sq = kSqA1; sq <= kSqH8; ++sq) {\n      piece_rand_nums_[piece][sq] = rand_num_gen();\n      // Update the hash using the current piece placement.\n      piece_type = piece_layout_[sq];\n      if (piece_type != kNA) {\n        board_hash_ ^= piece_rand_nums_[piece_type][sq];\n      }\n    }\n  }\n  black_to_move_rand_num_ = rand_num_gen();\n  // Update the hash using the side to move.\n  if (player_to_move_ == kBlack) {\n    board_hash_ ^= black_to_move_rand_num_;\n  }\n}\n\nauto Board::InitBoardPos(const std::string& init_pos) -> void {\n  S8 FEN_field = 0;\n  S8 current_sq = kSqA8;\n  for (char ch : init_pos) {\n    // Keep track of which of the six fields is currently being parsed.\n    if (ch == ' ') {\n      ++FEN_field;\n      continue;\n    }\n\n    if (FEN_field == 0) {\n      // Add pieces to the board.\n      if (isalpha(ch)) {\n        switch (ch) {\n          // Check for white pieces.\n          case 'P':\n            AddPiece(kPawn, kWhite, current_sq);\n            break;\n          case 'N':\n            AddPiece(kKnight, kWhite, current_sq);\n            break;\n          case 'B':\n            AddPiece(kBishop, kWhite, current_sq);\n            break;\n          case 'R':\n            AddPiece(kRook, kWhite, current_sq);\n            break;\n          case 'Q':\n            AddPiece(kQueen, kWhite, current_sq);\n            break;\n          case 'K':\n            AddPiece(kKing, kWhite, current_sq);\n            break;\n          // Check for black pieces.\n          case 'p':\n            AddPiece(kPawn, kBlack, current_sq);\n            break;\n          case 'n':\n            AddPiece(kKnight, kBlack, current_sq);\n            break;\n          case 'b':\n            AddPiece(kBishop, kBlack, current_sq);\n            break;\n          case 'r':\n            AddPiece(kRook, kBlack, current_sq);\n            break;\n          case 'q':\n            AddPiece(kQueen, kBlack, current_sq);\n            break;\n          case 'k':\n            AddPiece(kKing, kBlack, current_sq);\n            break;\n          default:\n            throw invalid_argument(\"init_pos in Board::InitBoardPos()\");\n        }\n        ++current_sq;\n      } else if (ch - '0' >= 0 && ch - '0' <= 8) {\n        S8 empty_sq_count = static_cast<S8>(ch - '0');\n        S8 empty_sq = current_sq;\n        for (; empty_sq < current_sq + empty_sq_count; ++empty_sq) {\n          AddPiece(kNA, kNA, empty_sq);\n        }\n        current_sq = empty_sq;\n      } else if (ch == '/') {\n        // Set the current square to the rank below the current position.\n        current_sq = static_cast<S8>(current_sq - 2 * kNumFiles);\n      } else {\n        throw invalid_argument(\"init_pos in Board::InitBoardPos()\");\n      }\n    } else if (FEN_field == 1) {\n      // Record the player to move.\n      if (ch == 'w') {\n        player_to_move_ = kWhite;\n      } else if (ch == 'b') {\n        player_to_move_ = kBlack;\n      } else {\n        throw invalid_argument(\"init_pos in Board::InitBoardPos()\");\n      }\n    } else if (FEN_field == 2) {\n      // Assign castling rights for each player and board side.\n      switch (ch) {\n        case 'Q':\n          castling_rights_[kWhite][kQueenSide] = true;\n          break;\n        case 'K':\n          castling_rights_[kWhite][kKingSide] = true;\n          break;\n        case 'q':\n          castling_rights_[kBlack][kQueenSide] = true;\n          break;\n        case 'k':\n          castling_rights_[kBlack][kKingSide] = true;\n          break;\n        case '-':\n          break;\n        default:\n          throw invalid_argument(\"init_pos in Board::InitBoardPos()\");\n      }\n    } else if (FEN_field == 3) {\n      // Assign the en passent target square.\n      if (ep_target_sq_ == kNA) {\n        S8 ep_target_sq_file = static_cast<S8>(ch - 'a');\n        if (FileOnBoard(ep_target_sq_file)) {\n          ep_target_sq_ = ep_target_sq_file;\n        } else if (ch != '-') {\n          throw invalid_argument(\"init_pos in Board::InitBoardPos()\");\n        }\n      } else {\n        // Assume ep_target_sq_ is initialized to the target\n        // square's file.\n        S8 ep_target_sq_rank = static_cast<S8>(ch - '1');\n        if (RankOnBoard(ep_target_sq_rank)) {\n          ep_target_sq_ = GetSqFromRankFile(ep_target_sq_rank, ep_target_sq_);\n        } else {\n          throw invalid_argument(\"init_pos in Board::InitBoardPos()\");\n        }\n      }\n    } else if (FEN_field == 4) {\n      // Initialize the halfmove clock.\n      if (isdigit(ch)) {\n        S8 next_digit = static_cast<S8>(ch - '0');\n        if (halfmove_clock_ == kNA) {\n          halfmove_clock_ = next_digit;\n        } else {\n          halfmove_clock_ = static_cast<S8>(10 * halfmove_clock_ + next_digit);\n        }\n      } else {\n        throw invalid_argument(\"init_pos in Board::InitBoardPos()\");\n      }\n    } else if (FEN_field == 5) {\n      // Ignore the fullmove counter.\n      ;\n    } else {\n      throw invalid_argument(\"init_pos in Board::InitBoardPos()\");\n    }\n  }\n}\n\nauto Board::MakeNonCastlingMove(const Move& move) -> void {\n  // Remove a captured piece from the board.\n  if (move.captured_piece != kNA) {\n    S8 other_player = GetOtherPlayer(player_to_move_);\n    if (move.is_ep) {\n      S8 ep_capture_sq = 0X0;\n      S8 target_file = GetFileFromSq(move.target_sq);\n      // Compute the position for a captured pawn in an en passent,\n      // and then remove it from the board.\n      if (player_to_move_ == kWhite) {\n        ep_capture_sq = GetSqFromRankFile(kRank5, target_file);\n        piece_layout_[ep_capture_sq] = kNA;\n        player_layout_[ep_capture_sq] = kNA;\n      } else if (player_to_move_ == kBlack) {\n        ep_capture_sq = GetSqFromRankFile(kRank4, target_file);\n        piece_layout_[ep_capture_sq] = kNA;\n        player_layout_[ep_capture_sq] = kNA;\n      }\n      Bitboard ep_capture_mask = ~(1ULL << ep_capture_sq);\n      pieces_[kPawn] &= ep_capture_mask;\n      player_pieces_[other_player] &= ep_capture_mask;\n      // Update the board hash to reflect piece removal.\n      board_hash_ ^= piece_rand_nums_[kPawn][ep_capture_sq];\n    } else {\n      // Remove the captured piece from the board.\n      Bitboard piece_capture_mask = ~(1ULL << move.target_sq);\n      pieces_[move.captured_piece] &= piece_capture_mask;\n      player_pieces_[other_player] &= piece_capture_mask;\n      // Update the board hash to reflect piece removal.\n      board_hash_ ^= piece_rand_nums_[move.captured_piece][move.target_sq];\n    }\n  }\n\n  MovePiece(move.moving_piece, move.start_sq, move.target_sq,\n            move.promoted_to_piece);\n}\n\nauto Board::MovePiece(S8 piece, S8 start_sq, S8 target_sq, S8 promoted_to_piece)\n    -> void {\n  if (piece < kPawn || piece > kKing) {\n    throw invalid_argument(\"piece in Board::MovePiece()\");\n  } else if (!SqOnBoard(start_sq)) {\n    throw invalid_argument(\"start_sq in Board::MovePiece()\");\n  } else if (!SqOnBoard(target_sq)) {\n    throw invalid_argument(\"target_sq in Board::MovePiece()\");\n  } else if (promoted_to_piece != kNA &&\n             (promoted_to_piece <= kPawn || promoted_to_piece >= kKing)) {\n    throw invalid_argument(\"promoted_to_piece in Board::MovePiece()\");\n  }\n\n  // Remove the selected piece from its start position on the board.\n  piece_layout_[start_sq] = kNA;\n  player_layout_[start_sq] = kNA;\n  Bitboard rm_piece_mask = ~(1ULL << start_sq);\n  pieces_[piece] &= rm_piece_mask;\n  player_pieces_[player_to_move_] &= rm_piece_mask;\n  // Update the board hash to reflect piece removal.\n  board_hash_ ^= piece_rand_nums_[piece][start_sq];\n\n  // Add the selected piece back at its target position on the board and update\n  // the board hash to reflect piece addition.\n  Bitboard new_piece_pos_mask = 1ULL << target_sq;\n  if (promoted_to_piece == kNA) {\n    pieces_[piece] |= new_piece_pos_mask;\n    piece_layout_[target_sq] = piece;\n    board_hash_ ^= piece_rand_nums_[piece][target_sq];\n  } else {\n    // Add a piece back as the type it promotes to if move is a pawn promotion.\n    pieces_[promoted_to_piece] |= new_piece_pos_mask;\n    piece_layout_[target_sq] = promoted_to_piece;\n    board_hash_ ^= piece_rand_nums_[promoted_to_piece][target_sq];\n  }\n\n  player_layout_[target_sq] = player_to_move_;\n  player_pieces_[player_to_move_] |= new_piece_pos_mask;\n}\n\nauto Board::UnmakeNonCastlingMove(const Move& move) -> void {\n  // Move the moving piece back to its original position and undo\n  // any pawn promotion.\n  if (move.promoted_to_piece == kNA) {\n    MovePiece(move.moving_piece, move.target_sq, move.start_sq);\n  } else {\n    // Remove the promoted-to piece from the board.\n    Bitboard piece_promotion_rm_mask = ~(1ULL << move.target_sq);\n    pieces_[move.promoted_to_piece] &= piece_promotion_rm_mask;\n    player_pieces_[player_to_move_] &= piece_promotion_rm_mask;\n    piece_layout_[move.target_sq] = kNA;\n    player_layout_[move.target_sq] = kNA;\n    // Update the board hash to reflect piece removal.\n    board_hash_ ^= piece_rand_nums_[move.promoted_to_piece][move.target_sq];\n\n    // Add the original pawn back to its start position.\n    Bitboard og_piece_pos_mask = 1ULL << move.start_sq;\n    pieces_[kPawn] |= og_piece_pos_mask;\n    player_pieces_[player_to_move_] |= og_piece_pos_mask;\n    piece_layout_[move.start_sq] = kPawn;\n    player_layout_[move.start_sq] = player_to_move_;\n    // Update the board hash to reflect piece addition.\n    board_hash_ ^= piece_rand_nums_[kPawn][move.start_sq];\n  }\n\n  // Place a captured piece back onto the board.\n  if (move.captured_piece != kNA) {\n    S8 other_player = GetOtherPlayer(player_to_move_);\n    if (move.is_ep) {\n      S8 ep_capture_sq = 0X0;\n      S8 target_file = GetFileFromSq(move.target_sq);\n      // Place a captured pawn back onto the board after an en passent.\n      if (player_to_move_ == kWhite) {\n        ep_capture_sq = GetSqFromRankFile(kRank5, target_file);\n        piece_layout_[ep_capture_sq] = kPawn;\n        player_layout_[ep_capture_sq] = kBlack;\n      } else if (player_to_move_ == kBlack) {\n        ep_capture_sq = GetSqFromRankFile(kRank4, target_file);\n        piece_layout_[ep_capture_sq] = kPawn;\n        player_layout_[ep_capture_sq] = kWhite;\n      }\n      Bitboard undo_ep_capture_mask = 1ULL << ep_capture_sq;\n      pieces_[kPawn] |= undo_ep_capture_mask;\n      player_pieces_[other_player] |= undo_ep_capture_mask;\n      // Update the board hash to reflect piece addition.\n      board_hash_ ^= piece_rand_nums_[kPawn][ep_capture_sq];\n    } else {\n      Bitboard undo_capture_mask = 1ULL << move.target_sq;\n      // Add the captured piece back to its original position.\n      pieces_[move.captured_piece] |= undo_capture_mask;\n      player_pieces_[other_player] |= undo_capture_mask;\n      piece_layout_[move.target_sq] = move.captured_piece;\n      player_layout_[move.target_sq] = other_player;\n      // Update the board hash to reflect piece addition.\n      board_hash_ ^= piece_rand_nums_[move.captured_piece][move.target_sq];\n    }\n  }\n}\n\nauto Board::UpdateCastlingRights(const Move& move) -> void {\n  // Record the current castling rights before updating them.\n  white_queenside_castling_rights_history_.push(\n      castling_rights_[kWhite][kQueenSide]);\n  white_kingside_castling_rights_history_.push(\n      castling_rights_[kWhite][kKingSide]);\n  black_queenside_castling_rights_history_.push(\n      castling_rights_[kBlack][kQueenSide]);\n  black_kingside_castling_rights_history_.push(\n      castling_rights_[kBlack][kKingSide]);\n\n  if (move.castling_type != kNA || move.moving_piece == kKing) {\n    // Revoke all castling rights for a player after moving the king.\n    if (castling_rights_[player_to_move_][kQueenSide]) {\n      castling_rights_[player_to_move_][kQueenSide] = false;\n      board_hash_ ^= castling_rights_rand_nums_[player_to_move_][kQueenSide];\n    }\n    if (castling_rights_[player_to_move_][kKingSide]) {\n      castling_rights_[player_to_move_][kKingSide] = false;\n      board_hash_ ^= castling_rights_rand_nums_[player_to_move_][kKingSide];\n    }\n  } else if (move.moving_piece == kRook) {\n    S8 start_rank = GetRankFromSq(move.start_sq);\n    S8 start_file = GetFileFromSq(move.start_sq);\n    // Check that a rook is moving from its original starting position\n    // and that the player still has castling rights on that side before\n    // revoking castling rights.\n    if ((player_to_move_ == kWhite && start_rank == kRank1) ||\n        (player_to_move_ == kBlack && start_rank == kRank8)) {\n      if (start_file == kFileA &&\n          castling_rights_[player_to_move_][kQueenSide]) {\n        castling_rights_[player_to_move_][kQueenSide] = false;\n        board_hash_ ^= castling_rights_rand_nums_[player_to_move_][kQueenSide];\n      } else if (start_file == kFileH &&\n                 castling_rights_[player_to_move_][kKingSide]) {\n        castling_rights_[player_to_move_][kKingSide] = false;\n        board_hash_ ^= castling_rights_rand_nums_[player_to_move_][kKingSide];\n      }\n    }\n  }\n\n  if (move.captured_piece == kRook) {\n    // Revoke the other player's castling rights if a player's rook is captured.\n    if (player_to_move_ == kWhite) {\n      if (move.target_sq == kSqA8 && castling_rights_[kBlack][kQueenSide]) {\n        castling_rights_[kBlack][kQueenSide] = false;\n        board_hash_ ^= castling_rights_rand_nums_[kBlack][kQueenSide];\n      } else if (move.target_sq == kSqH8 &&\n                 castling_rights_[kBlack][kKingSide]) {\n        castling_rights_[kBlack][kKingSide] = false;\n        board_hash_ ^= castling_rights_rand_nums_[kBlack][kKingSide];\n      }\n    } else if (player_to_move_ == kBlack) {\n      if (move.target_sq == kSqA1 && castling_rights_[kWhite][kQueenSide]) {\n        castling_rights_[kWhite][kQueenSide] = false;\n        board_hash_ ^= castling_rights_rand_nums_[kWhite][kQueenSide];\n      } else if (move.target_sq == kSqH1 &&\n                 castling_rights_[kWhite][kKingSide]) {\n        castling_rights_[kWhite][kKingSide] = false;\n        board_hash_ ^= castling_rights_rand_nums_[kWhite][kKingSide];\n      }\n    }\n  }\n}\n\n}  // namespace omegazero\n", "meta": {"hexsha": "363b6b32e353edd4257ba4c42202a0f6a5f2d2e5", "size": 29948, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/board.cc", "max_stars_repo_name": "noah8368/OmegaZero", "max_stars_repo_head_hexsha": "4f660f5258b44dc3cbda5da80e593a96f1994bea", "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/board.cc", "max_issues_repo_name": "noah8368/OmegaZero", "max_issues_repo_head_hexsha": "4f660f5258b44dc3cbda5da80e593a96f1994bea", "max_issues_repo_licenses": ["MIT"], "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/board.cc", "max_forks_repo_name": "noah8368/OmegaZero", "max_forks_repo_head_hexsha": "4f660f5258b44dc3cbda5da80e593a96f1994bea", "max_forks_repo_licenses": ["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.1989795918, "max_line_length": 80, "alphanum_fraction": 0.6668558835, "num_tokens": 8050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19188052770221994}}
{"text": "// -*- C++ -*-\n//\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n//\n//                                   Jiao Lin\n//                      California Institute of Technology\n//                         (C) 2007 All Rights Reserved\n//\n// {LicenseText}\n//\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n//\n\n\n#include <sstream>\n#include <boost/python.hpp>\n#include \"mccomponents/kernels/sample/phonon/IncoherentInelastic.h\"\n#include \"mccomponents/boostpython_binding/wrap_kernel.h\"\n#include \"mccomponents/kernels/sample/phonon/AbstractDOS.h\"\n#include \"mccomponents/kernels/sample/phonon/AbstractDebyeWallerFactor.h\"\n\n\nnamespace wrap_mccomponents {\n\n  void wrap_Phonon_IncoherentInelastic_kernel()\n  {\n    using namespace boost::python;\n    using namespace mccomponents::boostpython_binding;\n\n    typedef mccomponents::kernels::phonon::IncoherentInelastic w_t;\n\n    kernel_wrapper<w_t>::wrap\n      ( \"Phonon_IncoherentInelastic_kernel\",\n\tinit<\n\tconst w_t::atoms_t &, // atoms\n\tw_t::float_t, // unitcell_vol. AA**3\n\tw_t::dos_t &, // DOS\n\tw_t::dwcalculator_t &, // Debye Waller calculator\n\tw_t::float_t, // temperature. K\n\tw_t::float_t, // average mass. atomic weight. default 0\n\tw_t::float_t, // total scattering xs. barn. default 0\n\tw_t::float_t  // total absorption xs. barn. default 0\n\t> ()\n\t[with_custodian_and_ward<1,2,\n\t with_custodian_and_ward<1,4,\n\t with_custodian_and_ward<1,5 > > > () ]\n\t)\n      ;\n    \n  }\n\n}\n\n\n// version\n// $Id: wrap_Phonon_IncoherentInelastic_kernel.cc 603 2010-10-04 15:58:16Z linjiao $\n\n// End of file \n", "meta": {"hexsha": "7dd992801bc2f17388b296e43394f55f2afbc93c", "size": 1598, "ext": "cc", "lang": "C++", "max_stars_repo_path": "packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_IncoherentInelastic_kernel.cc", "max_stars_repo_name": "mcvine/mcvine", "max_stars_repo_head_hexsha": "42232534b0c6af729628009bed165cd7d833789d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T03:59:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-23T02:54:19.000Z", "max_issues_repo_path": "packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_IncoherentInelastic_kernel.cc", "max_issues_repo_name": "mcvine/mcvine", "max_issues_repo_head_hexsha": "42232534b0c6af729628009bed165cd7d833789d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 293.0, "max_issues_repo_issues_event_min_datetime": "2015-10-29T17:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T16:31:09.000Z", "max_forks_repo_path": "packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_IncoherentInelastic_kernel.cc", "max_forks_repo_name": "mcvine/mcvine", "max_forks_repo_head_hexsha": "42232534b0c6af729628009bed165cd7d833789d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-25T00:53:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-25T00:53:31.000Z", "avg_line_length": 27.0847457627, "max_line_length": 84, "alphanum_fraction": 0.6082603254, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19188052770221994}}
{"text": "/*\n * Copyright 2015-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n#ifdef BOOST_TEST_MAIN\n#  undef BOOST_TEST_MAIN\n#endif\n#include <mc_control/api.h>\n#include <mc_control/mc_controller.h>\n#include <mc_rtc/logging.h>\n\n#include <boost/test/unit_test.hpp>\n\nnamespace mc_control\n{\n\nstruct MC_CONTROL_DLLAPI TestPostureController : public MCController\n{\npublic:\n  TestPostureController(std::shared_ptr<mc_rbdyn::RobotModule> rm, double dt) : MCController(rm, dt)\n  {\n    // Check that the default constructor loads the robot + ground environment\n    BOOST_CHECK_EQUAL(robots().robots().size(), 2);\n    // Check that JVRC-1 was loaded\n    BOOST_CHECK_EQUAL(robot().name(), \"jvrc1\");\n    qpsolver->addConstraintSet(contactConstraint);\n    qpsolver->addConstraintSet(kinematicsConstraint);\n    postureTask->stiffness(20);\n    qpsolver->addTask(postureTask.get());\n    qpsolver->setContacts({});\n    BOOST_CHECK(robot().hasJoint(\"NECK_P\"));\n    BOOST_CHECK_NO_THROW(head_joint_index = robot().jointIndexByName(\"NECK_P\"));\n    head_joint_target = std::min(std::abs(robot().ql()[head_joint_index][0]), robot().qu()[head_joint_index][0]) - 0.1;\n    LOG_SUCCESS(\"Created TestPostureController\")\n  }\n\n  virtual bool run() override\n  {\n    bool ret = MCController::run();\n    BOOST_CHECK(ret);\n    if(nrIter++ > 250)\n    {\n      BOOST_CHECK_SMALL(robot().mbc().q[head_joint_index][0] - head_joint_target, 0.05);\n    }\n    return ret;\n  }\n\n  virtual void reset(const ControllerResetData & reset_data) override\n  {\n    MCController::reset(reset_data);\n    postureTask->target({{\"NECK_P\", {head_joint_target}}});\n  }\n\nprivate:\n  unsigned int nrIter = 0;\n  unsigned int head_joint_index;\n  double head_joint_target;\n};\n\n} // namespace mc_control\n\nSIMPLE_CONTROLLER_CONSTRUCTOR(\"TestPostureController\", mc_control::TestPostureController)\n", "meta": {"hexsha": "ff8bebb07342a8afa66297d7192a827944557cc0", "size": 1811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/controllers/TestPostureController.cpp", "max_stars_repo_name": "SaeidSamadi/mc_rtc", "max_stars_repo_head_hexsha": "fed695d7458da5231ae887506134c0e783556780", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T15:15:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T15:15:26.000Z", "max_issues_repo_path": "tests/controllers/TestPostureController.cpp", "max_issues_repo_name": "SaeidSamadi/mc_rtc", "max_issues_repo_head_hexsha": "fed695d7458da5231ae887506134c0e783556780", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T03:11:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T02:53:26.000Z", "max_forks_repo_path": "tests/controllers/TestPostureController.cpp", "max_forks_repo_name": "SaeidSamadi/mc_rtc", "max_forks_repo_head_hexsha": "fed695d7458da5231ae887506134c0e783556780", "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.746031746, "max_line_length": 119, "alphanum_fraction": 0.7211485367, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658972248185995, "lm_q1q2_score": 0.19188052045792534}}
{"text": "// (C) Copyright 2016 by Autodesk, Inc.\n\n#ifdef TEST_ON\n\n#include \"ChecksumFile.hh\"\n#include \"Base/Utils/OStringStream.hh\"\n\n#include <boost/functional/hash.hpp>\n#include <boost/filesystem.hpp>\n\n#include <fstream>\n\nnamespace Test {\nnamespace Checksum {\n\nvoid File::record(const char* _flnm)\n{\n  // Reads the file, makes a has number form its data and finally record \n  // hash_number and filename.\n  std::ifstream fstr(_flnm);\n  std::array<char, 1000> buf;\n  size_t file_hash = 0;\n  size_t file_size = 0;\n  while(fstr)\n  {\n    fstr.read(buf.data(), buf.size());\n    auto buf_hash = boost::hash_range(buf.data(), buf.data() + fstr.gcount());\n    file_size += fstr.gcount();\n    boost::hash_combine(file_hash, buf_hash);\n  }\n  Base::OStringStream strm;\n  strm << \"\\\"\" << _flnm << '\\\"' << \" (Size: \" << file_size << \")\" <<  \n    \"(Hash: \" << Base::format_hex(file_hash) << \")\";\n\n  add(Result::OK, strm.str);\n}\n\n}//namespace Checksum\n}//namespace Test\n\n#endif//TEST_ON\n", "meta": {"hexsha": "0ee203baa90f9a00b36cf9ba6115f7b603b4e5a9", "size": 964, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ACAP_linux/3rd/CoMISo/Base/Test/ChecksumFile.cc", "max_stars_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_stars_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T11:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:41:35.000Z", "max_issues_repo_path": "ACAP_linux/3rd/CoMISo/Base/Test/ChecksumFile.cc", "max_issues_repo_name": "gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer", "max_issues_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T08:29:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T06:45:34.000Z", "max_forks_repo_path": "ACAP_linux/3rd/CoMISo/Base/Test/ChecksumFile.cc", "max_forks_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_forks_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-09-13T08:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T00:33:54.000Z", "avg_line_length": 22.9523809524, "max_line_length": 78, "alphanum_fraction": 0.6524896266, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.1917567053090231}}
{"text": "#include \"my_capture_d400.h\"\n\n#include <iostream>\n#include <boost/thread.hpp>\n#include <boost/bind.hpp>\n#include <librealsense2/rsutil.h>\n\nMyCaptureD400::MyCaptureD400(StreamSetting ss)\n{\n\tbagrec = false;\n\n\tstartStreams(ss);\n\n\tnum_camera = cameras.size();\n\n\tstd::cout << \"number of cameras: \" << num_camera << std::endl;\n\n\tpc_filter_setting.color_filt_on = false;\n\tpc_filter_setting.outlier_removal_on = false;\n}\n\nvoid MyCaptureD400::startStreams(StreamSetting ss)\n{\n\trs2::context rs_ctx;\n\tconst std::string platform_camera_name = \"Platform Camera\";\n\n\tcameras.clear();\n\n\tint fps, c_w, c_h, d_w, d_h;\n\n\tif (ss.fps == 2) fps = 90;\n\telse if (ss.fps == 1) fps = 60;\n\telse fps = 30;\n\n\tif (ss.depth_res == 2) { d_w = 1280; d_h = 720; }\n\telse if (ss.depth_res == 1) { d_w = 848; d_h = 480; }\n\telse { d_w = 424; d_h = 240; }\n\n\tif (ss.color_res == 2) { c_w = 1280; c_h = 720; }\n\telse if (ss.color_res == 1) { c_w = 848; c_h = 480; }\n\telse { c_w = 424; c_h = 240; }\n\n\tsmode = ss.smode;\n\n\tfor (auto&& dev : rs_ctx.query_devices())\n\t{\n\t\tif (dev.get_info(RS2_CAMERA_INFO_NAME) == platform_camera_name) continue;\n\n\t\trs2::pipeline pipe;\n\t\trs2::config cfg;\n\n\t\tcfg.enable_device(dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER));\n\n\t\tif (smode == SMODE_DEPTH_COLOR)\n\t\t{\n\t\t\tcfg.enable_stream(RS2_STREAM_COLOR, c_w, c_h, RS2_FORMAT_BGR8, fps);\n\t\t\tcfg.enable_stream(RS2_STREAM_DEPTH, d_w, d_h, RS2_FORMAT_Z16, fps);\n\t\t}\n\t\telse if (smode == SMODE_DEPTH_IR)\n\t\t{\n\t\t\tcfg.enable_stream(RS2_STREAM_INFRARED, 1, d_w, d_h, RS2_FORMAT_Y8, fps);\n\t\t\tcfg.enable_stream(RS2_STREAM_DEPTH, d_w, d_h, RS2_FORMAT_Z16, fps);\n\t\t}\n\n\t\tif (bagrec)\n\t\t{\n\t\t\tcfg.enable_record_to_file(bagrec_path + bagrec_sessionname + \".rosbag.\" + std::to_string(cameras.size() + 1) + \".bag\");\n\t\t}\n\n\t\trs2::pipeline_profile prof = pipe.start(cfg);\n\n\t\tCamera cam;\n\n\t\tcam.pipe = pipe;\n\t\tcam.pc.clear(); \n\t\tcam.ci.depth_intrin = prof.get_stream(RS2_STREAM_DEPTH).as<rs2::video_stream_profile>().get_intrinsics();\n\n\t\tif (smode == SMODE_DEPTH_COLOR)\n\t\t{\n\t\t\tcam.ci.color_intrin = prof.get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>().get_intrinsics();\n\t\t\tcam.ci.depth_to_color = prof.get_stream(RS2_STREAM_DEPTH).get_extrinsics_to(prof.get_stream(RS2_STREAM_COLOR));\n\t\t\tcam.ci.scale = prof.get_device().first<rs2::depth_sensor>().get_depth_scale();\n\t\t}\n\t\telse if (smode == SMODE_DEPTH_IR)\n\t\t{\n\t\t\tcam.ci.color_intrin = prof.get_stream(RS2_STREAM_INFRARED, 1).as<rs2::video_stream_profile>().get_intrinsics();\n\t\t\tcam.ci.depth_to_color = prof.get_stream(RS2_STREAM_DEPTH).get_extrinsics_to(prof.get_stream(RS2_STREAM_INFRARED, 1));\n\t\t\tcam.ci.scale = prof.get_device().first<rs2::depth_sensor>().get_depth_scale();\n\t\t}\n\n\t\tcameras.push_back(cam);\n\t}\n}\n\nvoid MyCaptureD400::stopStreams()\n{\n\tfor (auto & c : cameras)\n\t{\n\t\tc.pipe.stop();\n\t}\n}\n\nvoid MyCaptureD400::getNextFrames()\n{\n\tboost::thread_group thr_grp;\n\n\tfor (auto & c : cameras)\n\t{\n\t\tthr_grp.create_thread(boost::bind(&MyCaptureD400::updateFrame, this, boost::ref(c)));\n\t}\n\n\tthr_grp.join_all();\n}\n\nvoid MyCaptureD400::updateFrame(Camera & c)\n{\n\trs2::frameset fset = c.pipe.wait_for_frames();\n\n\trs2::frame color_frame, depth_frame;\n\n\tif (smode == SMODE_DEPTH_COLOR)\n\t{\n\t\tcolor_frame = fset.get_color_frame(); \n\t\tc.color_frame = cv::Mat(cv::Size(c.ci.color_intrin.width, c.ci.color_intrin.height), CV_8UC3, (void*)color_frame.get_data(), cv::Mat::AUTO_STEP);\n\t}\n\telse if (smode == SMODE_DEPTH_IR)\n\t{\n\t\tcolor_frame = fset.get_infrared_frame();\n\t\tcv::Mat ir = cv::Mat(cv::Size(c.ci.color_intrin.width, c.ci.color_intrin.height), CV_8UC1, (void*)color_frame.get_data(), cv::Mat::AUTO_STEP);\n\t\tcv::cvtColor(ir, c.color_frame, CV_GRAY2BGR);\n\t}\n\tdepth_frame = fset.get_depth_frame();\n\tc.depth_frame = cv::Mat(cv::Size(c.ci.depth_intrin.width, c.ci.depth_intrin.height), CV_16UC1, (void*)depth_frame.get_data(), cv::Mat::AUTO_STEP);\n\t\n\tc.timestamp = fset.get_timestamp();\n}\n\nvoid MyCaptureD400::getFrameData(cv::Mat & frame, int camera_id, std::string frame_type)\n{\n\tif (frame_type == \"DEPTH\")\n\t{\n\t\tframe = cameras[camera_id].depth_frame.clone();\n\t}\n\telse if (frame_type == \"COLOR\")\n\t{\n\t\tframe = cameras[camera_id].color_frame.clone();\n\t}\n}\n\nvoid MyCaptureD400::getPointClouds()\n{\n\tboost::thread_group thr_grp;\n\n\tfor (auto & c : cameras)\n\t{\n\t\tthr_grp.create_thread(boost::bind(&MyCaptureD400::updatePointCloud, this, boost::ref(c)));\n\t}\n\n\tthr_grp.join_all();\n}\n\nvoid MyCaptureD400::updatePointCloud(Camera & c)\n{\n\tframe2PointCloud(c.color_frame, c.depth_frame, c.pc, c.ci, pc_filter_setting);\n}\n\nvoid MyCaptureD400::frame2PointCloud(const cv::Mat & color_frame, const cv::Mat & depth_frame, pcl::PointCloud<pcl::PointXYZRGB>& pc, const RsCameraIntrinsics2 & intrinsics, const PointCloudFilterSetting & filter_setting)\n{\n\tcv::Mat hsv_frame, detection_frame;\n\tif (filter_setting.color_filt_on) // pre processing for color filtering; finding pixels within the range in HSV color space\n\t{\n\t\tcv::cvtColor(color_frame, hsv_frame, cv::COLOR_BGR2HSV);\n\t\tcv::inRange(hsv_frame, filter_setting.color_filt_hsv_min, filter_setting.color_filt_hsv_max, detection_frame);\n\t}\n\n\tpc.clear();\n\n\tfor (int dy = 0; dy < intrinsics.depth_intrin.height; ++dy)\n\t{\n\t\tfor (int dx = 0; dx < intrinsics.depth_intrin.width; ++dx)\n\t\t{\n\t\t\t// Retrieve the 16-bit depth value and map it into a depth in meters\n\t\t\tuint16_t depth_value = depth_frame.at<unsigned __int16>(dy, dx);\n\n\t\t\t// Skip over pixels with a depth value of zero, which is used to indicate no data\n\t\t\tif (depth_value == 0) continue;\n\n\t\t\tfloat depth_in_meters = (float)depth_value * intrinsics.scale;\n\n\t\t\t// Map from pixel coordinates in the depth image to pixel coordinates in the color image\n\t\t\tfloat depth_pixel[2] = { (float)dx - 0.5f, (float)dy - 0.5f };\n\t\t\tfloat depth_point[3], color_point[3], color_pixel[2];\n\t\t\trs2_deproject_pixel_to_point(depth_point, &intrinsics.depth_intrin, depth_pixel, depth_in_meters);\n\t\t\trs2_transform_point_to_point(color_point, &intrinsics.depth_to_color, depth_point);\n\t\t\trs2_project_point_to_pixel(color_pixel, &intrinsics.color_intrin, color_point);\n\n\t\t\tconst int cx = static_cast<int>(color_pixel[0] + 0.5f), cy = static_cast<int>(color_pixel[1] + 0.5f);\n\n\t\t\tif (cx < 0 || cy < 0 || cx >= intrinsics.color_intrin.width || cy >= intrinsics.color_intrin.height) continue;\n\n\t\t\tif (filter_setting.color_filt_on && detection_frame.at<unsigned char>(cy, cx) == 0) continue;\n\n\t\t\tpcl::PointXYZRGB p;\n\n\t\t\t// Use the color from the nearest color pixel\n\t\t\tauto clr = color_frame.at<cv::Vec3b>(cy, cx);\n\t\t\tp.r = clr[2]; p.g = clr[1]; p.b = clr[0];\n\n\t\t\t// Emit a vertex at the 3D location of this depth pixel\n\t\t\tp.x = -depth_point[0];\n\t\t\tp.y = -depth_point[1];\n\t\t\tp.z = depth_point[2];\n\n\t\t\tpc.push_back(p);\n\t\t}\n\t}\n\n\tif (filter_setting.outlier_removal_on)\n\t{\n\t\tremoveNoiseFromThresholdedPc(pc, filter_setting.outlier_filt_meanK, filter_setting.outlier_filt_thresh);\n\t}\n}\n\nvoid MyCaptureD400::startBagRecording(const std::string & path_data_dir, const std::string & name_session, int res_idx, int fps)\n{\n\tStreamSetting ss = { smode, res_idx, res_idx, fps };\n\tbagrec = true;\n\tbagrec_path = path_data_dir;\n\tbagrec_sessionname = name_session;\n\n\trestartStreams(ss);\n\n\t/*\n\tfor (int i = 0; i < num_camera; i++)\n\t{\n\t\tstd::string s_num = cameras[i].pipe.get_active_profile().get_device().get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);\n\t\t\n\t\tcameras[i].pipe.stop();\n\n\t\trs2::config cfg;\n\n\t\tcfg.enable_device(s_num);\n\t\tcfg.enable_stream(RS2_STREAM_COLOR, w, h, RS2_FORMAT_BGR8, frate);\n\t\tcfg.enable_stream(RS2_STREAM_DEPTH, w, h, RS2_FORMAT_Z16, frate);\n\t\t\n\t\tcfg.enable_record_to_file(path_data_dir + name_session + \".rosbag.\" + std::to_string(i+1) + \".bag\");\n\n\t\tcameras[i].pipe.start(cfg);\n\n\t\t//update intrinsics\n\t\tauto prof = cameras[i].pipe.get_active_profile();\n\t\tcameras[i].ci.color_intrin = prof.get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>().get_intrinsics();\n\t\t\n\t\t\tcameras[i].ci.depth_intrin = prof.get_stream(RS2_STREAM_DEPTH).as<rs2::video_stream_profile>().get_intrinsics();\n\t\t\tcameras[i].ci.depth_to_color = prof.get_stream(RS2_STREAM_DEPTH).get_extrinsics_to(prof.get_stream(RS2_STREAM_COLOR));\n\t\t\tcameras[i].ci.scale = prof.get_device().first<rs2::depth_sensor>().get_depth_scale();\n\t}\n\t*/\n}\n\nvoid MyCaptureD400::stopBagRecording()\n{\n\tStreamSetting ss = { smode, 0, 0, 30 };\n\tbagrec = false;\n\n\trestartStreams(ss);\n\n\t/*\n\tfor (int i = 0; i < num_camera; i++)\n\t{\n\t\tstd::string s_num = cameras[i].pipe.get_active_profile().get_device().get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);\n\n\t\tcameras[i].pipe.stop();\n\n\t\trs2::config cfg;\n\n\t\tcfg.enable_device(s_num);\n\t\t//!! resolution should be original value !!\n\t\tcfg.enable_stream(RS2_STREAM_COLOR, 848, 480, RS2_FORMAT_BGR8, 30);\n\t\tif (!depth_off) cfg.enable_stream(RS2_STREAM_DEPTH, 424, 240, RS2_FORMAT_Z16, 30);\n\n\t\tcameras[i].pipe.start(cfg);\n\n\t\t//update intrinsics\n\t\tauto prof = cameras[i].pipe.get_active_profile();\n\t\tcameras[i].ci.color_intrin = prof.get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>().get_intrinsics();\n\t\tif (!depth_off)\n\t\t{\n\t\t\tcameras[i].ci.depth_intrin = prof.get_stream(RS2_STREAM_DEPTH).as<rs2::video_stream_profile>().get_intrinsics();\n\t\t\tcameras[i].ci.depth_to_color = prof.get_stream(RS2_STREAM_DEPTH).get_extrinsics_to(prof.get_stream(RS2_STREAM_COLOR));\n\t\t\tcameras[i].ci.scale = prof.get_device().first<rs2::depth_sensor>().get_depth_scale();\n\t\t}\n\t}\n\t*/\n}\n\nvoid MyCaptureD400::getPointCloudData(pcl::PointCloud<pcl::PointXYZRGB>& pc, int camera_id)\n{\n\tpc = cameras[camera_id].pc;\n}\n\nvoid MyCaptureD400::getCameraIntrinsics(RsCameraIntrinsics2 & ci, int camera_id)\n{\n\tci = cameras[camera_id].ci;\n}\n\nvoid MyCaptureD400::getColorCameraSettings(MyColorCameraSettings & cs, int camera_id)\n{\n\t/*\n\tCamera & c = cameras[camera_id];\n\n\tc.dev->get_option_range(rs::option::color_gain, cs.gain.min, cs.gain.max, cs.gain.step);\n\tc.dev->get_option_range(rs::option::color_exposure, cs.exposure.min, cs.exposure.max, cs.exposure.step);\n\tc.dev->get_option_range(rs::option::color_contrast, cs.contrast.min, cs.contrast.max, cs.contrast.step);\n\tc.dev->get_option_range(rs::option::color_brightness, cs.brightness.min, cs.brightness.max, cs.brightness.step);\n\tc.dev->get_option_range(rs::option::color_gamma, cs.gamma.min, cs.gamma.max, cs.gamma.step);\n\n\tcs.gain.value = c.dev->get_option(rs::option::color_gain);\n\tcs.exposure.value = c.dev->get_option(rs::option::color_exposure);\n\tcs.contrast.value = c.dev->get_option(rs::option::color_contrast);\n\tcs.brightness.value = c.dev->get_option(rs::option::color_brightness);\n\tcs.gamma.value = c.dev->get_option(rs::option::color_gamma);\n\n\tcs.auto_exposure = static_cast<bool>(c.dev->get_option(rs::option::color_enable_auto_exposure));\n\t*/\n}\n\nvoid MyCaptureD400::setColorCameraSettings(MyColorCameraSettings & cs, int camera_id)\n{\n\t/*\n\tCamera & c = cameras[camera_id];\n\n\tbool flag_update_exposure = (cs.exposure.value != c.dev->get_option(rs::option::color_exposure));\n\n\tc.dev->set_option(rs::option::color_gain, cs.gain.value);\n\tc.dev->set_option(rs::option::color_contrast, cs.contrast.value);\n\tc.dev->set_option(rs::option::color_brightness, cs.brightness.value);\n\tc.dev->set_option(rs::option::color_gamma, cs.gamma.value);\n\n\tif (flag_update_exposure) {\n\t\tc.dev->set_option(rs::option::color_exposure, cs.exposure.value);\n\t\tcs.auto_exposure = false;\n\t}\n\n\tbool flag_update_auto_exposure = (cs.auto_exposure != static_cast<bool>(c.dev->get_option(rs::option::color_enable_auto_exposure)));\n\tif (flag_update_auto_exposure)\n\t{\n\t\tc.dev->set_option(rs::option::color_enable_auto_exposure, static_cast<bool>(cs.auto_exposure));\n\t}\n\t//reload color camera setting after setting (some parameters are rounded by R200 after setting)\n\tgetColorCameraSettings(cs, camera_id);\n\t*/\n}\n\nbool MyCaptureD400::getInfraredEmitter(int camera_id)\n{\n\treturn cameras[camera_id].pipe.get_active_profile().get_device().first<rs2::depth_sensor>().get_option(RS2_OPTION_EMITTER_ENABLED) > 0;\n}\n\nvoid MyCaptureD400::setInfraredEmitter(bool emitter_on, int camera_id)\n{\n\tif (emitter_on)\n\t{\n\t\tcameras[camera_id].pipe.get_active_profile().get_device().first<rs2::depth_sensor>().set_option(RS2_OPTION_EMITTER_ENABLED, 1.0f);\n\t}\n\telse\n\t{\n\t\tcameras[camera_id].pipe.get_active_profile().get_device().first<rs2::depth_sensor>().set_option(RS2_OPTION_EMITTER_ENABLED, 0.0f);\n\t}\n}\n\nvoid MyCaptureD400::setInfraredCamGain(double gain_value)\n{\n\tfor (auto c : cameras) c.pipe.get_active_profile().get_device().first<rs2::depth_sensor>().set_option(RS2_OPTION_LASER_POWER, gain_value);\n}\n\nvoid MyCaptureD400::setInfraredCamExposure(double exp_value)\n{\n\t\n\tfor (auto c : cameras)\n\t{\n\t\tauto dev = c.pipe.get_active_profile().get_device().first<rs2::depth_sensor>();\n\n\t\tif (exp_value < 0.0)\n\t\t{\n\t\t\tdev.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE, 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto range = dev.get_option_range(RS2_OPTION_EXPOSURE);\n\t\t\tdev.set_option(RS2_OPTION_EXPOSURE, exp_value*(range.max - range.min) + range.min);\n\t\t}\n\t}\n}\n\nvoid MyCaptureD400::setColorFilter(PointCloudFilterSetting pcfs)\n{\n\tpc_filter_setting = pcfs;\n}\n\nMyCaptureD400::~MyCaptureD400()\n{\n}\n\n", "meta": {"hexsha": "b096ee911f4e41fdf1f7150abec1843d425a5790", "size": 12963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/my_capture_d400.cpp", "max_stars_repo_name": "ThreeD-Tracker-FAB/3DTrackerFAB-main", "max_stars_repo_head_hexsha": "e91660f9391feac02f5657a792771230450cf4f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T09:15:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-18T08:45:33.000Z", "max_issues_repo_path": "common/my_capture_d400.cpp", "max_issues_repo_name": "ThreeD-Tracker-FAB/3DTrackerFAB-main", "max_issues_repo_head_hexsha": "e91660f9391feac02f5657a792771230450cf4f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T13:10:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-18T13:34:50.000Z", "max_forks_repo_path": "common/my_capture_d400.cpp", "max_forks_repo_name": "ThreeD-Tracker-FAB/3DTrackerFAB-main", "max_forks_repo_head_hexsha": "e91660f9391feac02f5657a792771230450cf4f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-03-11T22:16:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-05T15:36:14.000Z", "avg_line_length": 32.0074074074, "max_line_length": 221, "alphanum_fraction": 0.729460773, "num_tokens": 3798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.19171963797668357}}
{"text": "#include \"MBTB_TimeStepping.hpp\"\n#include \"MBTB_PYTHON_API.hpp\"\n#include \"MBTB_internalTool.hpp\"\n#include <boost/math/quaternion.hpp>\n//#define TS_DEBUG\nMBTB_TimeStepping::MBTB_TimeStepping(SP::TimeDiscretisation td,\n                                     SP::OneStepIntegrator osi,\n                                     SP::OneStepNSProblem osnspb_velo):TimeStepping(td,osi,osnspb_velo)\n{\n}\n\n\nvoid MBTB_TimeStepping::updateWorldFromDS()\n{\n#ifdef TS_DEBUG\n  printf(\"MBTB_TimeStepping::updateWordFromDS \\n\");\n#endif\n  MBTB_updateDSFromSiconos();\n  _MBTB_updateContactFromDS();\n}\n", "meta": {"hexsha": "265a877b70f45a12de989b8cc78367657fbb8bb7", "size": 575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mechanics/src/mechanisms/MBTB/MBTB_TimeStepping.cpp", "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": "mechanics/src/mechanisms/MBTB/MBTB_TimeStepping.cpp", "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": "mechanics/src/mechanisms/MBTB/MBTB_TimeStepping.cpp", "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.380952381, "max_line_length": 103, "alphanum_fraction": 0.6991304348, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.19171963797668354}}
{"text": "/*\n * Throttling.actor.cpp\n *\n * This source file is part of the FoundationDB open source project\n *\n * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors\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/lexical_cast.hpp>\n\n#include \"fdbclient/ManagementAPI.actor.h\"\n#include \"fdbclient/ReadYourWrites.h\"\n#include \"fdbclient/Schemas.h\"\n#include \"fdbserver/workloads/workloads.actor.h\"\n#include \"flow/actorcompiler.h\" // This must be the last include\n\nstruct TokenBucket {\n\tstatic constexpr const double addTokensInterval = 0.1;\n\tstatic constexpr const double maxSleepTime = 60.0;\n\n\tdouble transactionRate;\n\tdouble maxBurst;\n\tdouble bucketSize;\n\tFuture<Void> tokenAdderActor;\n\n\tACTOR static Future<Void> tokenAdder(TokenBucket* self) {\n\t\tloop {\n\t\t\tself->bucketSize = std::min(self->bucketSize + self->transactionRate * addTokensInterval, self->maxBurst);\n\t\t\tif (deterministicRandom()->randomInt(0, 100) == 0)\n\t\t\t\tTraceEvent(\"AddingTokensx100\")\n\t\t\t\t    .detail(\"BucketSize\", self->bucketSize)\n\t\t\t\t    .detail(\"TransactionRate\", self->transactionRate);\n\t\t\twait(delay(addTokensInterval));\n\t\t}\n\t}\n\n\tTokenBucket(double maxBurst = 1000) : transactionRate(0), maxBurst(maxBurst), bucketSize(maxBurst) {\n\t\ttokenAdderActor = tokenAdder(this);\n\t}\n\n\tACTOR static Future<Void> startTransaction(TokenBucket* self) {\n\t\tstate double sleepTime = addTokensInterval;\n\t\tloop {\n\t\t\tif (self->bucketSize >= 1.0) {\n\t\t\t\t--self->bucketSize;\n\t\t\t\treturn Void();\n\t\t\t}\n\t\t\tif (deterministicRandom()->randomInt(0, 100) == 0)\n\t\t\t\tTraceEvent(\"ThrottlingTransactionx100\").detail(\"SleepTime\", sleepTime);\n\t\t\twait(delay(sleepTime));\n\t\t\tsleepTime = std::min(sleepTime * 2, maxSleepTime);\n\t\t}\n\t}\n};\n\n// workload description:\n// The Throttling workload runs a simple random read-write workload while throttling using a token bucket algorithm\n// using the TPS limit obtained from the health metrics namespace. It periodically reads health metrics from the special\n// key and tests whether or not the received health metrics are reasonable.\nstruct ThrottlingWorkload : KVWorkload {\n\n\tdouble testDuration;\n\tint actorsPerClient;\n\tint writesPerTransaction;\n\tint readsPerTransaction;\n\tdouble throttlingMultiplier;\n\tint transactionsCommitted;\n\tTokenBucket tokenBucket;\n\tbool correctSpecialKeys = true;\n\n\tstatic constexpr const char* NAME = \"Throttling\";\n\n\tThrottlingWorkload(WorkloadContext const& wcx)\n\t  : KVWorkload(wcx), transactionsCommitted(0) {\n\t\ttestDuration = getOption(options, LiteralStringRef(\"testDuration\"), 60.0);\n\t\tactorsPerClient = getOption(options, LiteralStringRef(\"actorsPerClient\"), 10);\n\t\twritesPerTransaction = getOption(options, LiteralStringRef(\"writesPerTransaction\"), 10);\n\t\treadsPerTransaction = getOption(options, LiteralStringRef(\"readsPerTransaction\"), 10);\n\t\tthrottlingMultiplier = getOption(options, LiteralStringRef(\"throttlingMultiplier\"), 0.5);\n\t\tint maxBurst = getOption(options, LiteralStringRef(\"maxBurst\"), 1000);\n\t\ttokenBucket.maxBurst = maxBurst;\n\t}\n\n\tstatic Value getRandomValue() { return Standalone<StringRef>(format(\"Value/%d\", deterministicRandom()->randomInt(0, 10e6))); }\n\n\tACTOR static Future<Void> clientActor(Database cx, ThrottlingWorkload* self) {\n\t\tstate ReadYourWritesTransaction tr(cx);\n\n\t\tloop {\n\t\t\twait(TokenBucket::startTransaction(&self->tokenBucket));\n\t\t\ttr.reset();\n\t\t\ttry {\n\t\t\t\tstate int i;\n\t\t\t\tfor (i = 0; i < self->readsPerTransaction; ++i) {\n\t\t\t\t\tstate Optional<Value> value = wait(tr.get(self->getRandomKey()));\n\t\t\t\t}\n\t\t\t\tfor (i = 0; i < self->writesPerTransaction; ++i) {\n\t\t\t\t\ttr.set(self->getRandomKey(), getRandomValue());\n\t\t\t\t}\n\t\t\t\twait(tr.commit());\n\t\t\t\tif (deterministicRandom()->randomInt(0, 1000) == 0) TraceEvent(\"TransactionCommittedx1000\");\n\t\t\t\t++self->transactionsCommitted;\n\t\t\t} catch (Error& e) {\n\t\t\t\tif (e.code() == error_code_actor_cancelled) throw;\n\t\t\t\t// ignore failing transactions\n\t\t\t}\n\t\t}\n\t}\n\n\tACTOR static Future<Void> specialKeysActor(Database cx, ThrottlingWorkload* self) {\n\t\tstate ReadYourWritesTransaction tr(cx);\n\t\tstate json_spirit::mValue aggregateSchema =\n\t\t    readJSONStrictly(JSONSchemas::aggregateHealthSchema.toString()).get_obj();\n\t\tstate json_spirit::mValue storageSchema =\n\t\t    readJSONStrictly(JSONSchemas::storageHealthSchema.toString()).get_obj();\n\t\tstate json_spirit::mValue logSchema = readJSONStrictly(JSONSchemas::logHealthSchema.toString()).get_obj();\n\t\tloop {\n\t\t\ttry {\n\t\t\t\tStandalone<RangeResultRef> result = wait(\n\t\t\t\t    tr.getRange(prefixRange(LiteralStringRef(\"\\xff\\xff/metrics/health/\")), CLIENT_KNOBS->TOO_MANY));\n\t\t\t\tASSERT(!result.more);\n\t\t\t\tfor (const auto& [k, v] : result) {\n\t\t\t\t\tASSERT(k.startsWith(LiteralStringRef(\"\\xff\\xff/metrics/health/\")));\n\t\t\t\t\tauto valueObj = readJSONStrictly(v.toString()).get_obj();\n\t\t\t\t\tif (k.removePrefix(LiteralStringRef(\"\\xff\\xff/metrics/health/\")) == LiteralStringRef(\"aggregate\")) {\n\t\t\t\t\t\tTEST(true); // Test aggregate health metrics schema\n\t\t\t\t\t\tstd::string errorStr;\n\t\t\t\t\t\tif (!schemaMatch(aggregateSchema, valueObj, errorStr, SevError, true)) {\n\t\t\t\t\t\t\tTraceEvent(SevError, \"AggregateHealthSchemaValidationFailed\")\n\t\t\t\t\t\t\t    .detail(\"ErrorStr\", errorStr.c_str())\n\t\t\t\t\t\t\t    .detail(\"JSON\", json_spirit::write_string(json_spirit::mValue(v.toString())));\n\t\t\t\t\t\t\tself->correctSpecialKeys = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tauto tpsLimit = valueObj.at(\"tps_limit\").get_real();\n\t\t\t\t\t\tself->tokenBucket.transactionRate = tpsLimit * self->throttlingMultiplier / self->clientCount;\n\t\t\t\t\t} else if (k.removePrefix(LiteralStringRef(\"\\xff\\xff/metrics/health/\"))\n\t\t\t\t\t               .startsWith(LiteralStringRef(\"storage/\"))) {\n\t\t\t\t\t\tTEST(true); // Test storage health metrics schema\n\t\t\t\t\t\tUID::fromString(k.removePrefix(LiteralStringRef(\"\\xff\\xff/metrics/health/storage/\"))\n\t\t\t\t\t\t                    .toString()); // Will throw if it's not a valid uid\n\t\t\t\t\t\tstd::string errorStr;\n\t\t\t\t\t\tif (!schemaMatch(storageSchema, valueObj, errorStr, SevError, true)) {\n\t\t\t\t\t\t\tTraceEvent(SevError, \"StorageHealthSchemaValidationFailed\")\n\t\t\t\t\t\t\t    .detail(\"ErrorStr\", errorStr.c_str())\n\t\t\t\t\t\t\t    .detail(\"JSON\", json_spirit::write_string(json_spirit::mValue(v.toString())));\n\t\t\t\t\t\t\tself->correctSpecialKeys = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (k.removePrefix(LiteralStringRef(\"\\xff\\xff/metrics/health/\"))\n\t\t\t\t\t               .startsWith(LiteralStringRef(\"log/\"))) {\n\t\t\t\t\t\tTEST(true); // Test log health metrics schema\n\t\t\t\t\t\tUID::fromString(k.removePrefix(LiteralStringRef(\"\\xff\\xff/metrics/health/log/\"))\n\t\t\t\t\t\t                    .toString()); // Will throw if it's not a valid uid\n\t\t\t\t\t\tstd::string errorStr;\n\t\t\t\t\t\tif (!schemaMatch(logSchema, valueObj, errorStr, SevError, true)) {\n\t\t\t\t\t\t\tTraceEvent(SevError, \"LogHealthSchemaValidationFailed\")\n\t\t\t\t\t\t\t    .detail(\"ErrorStr\", errorStr.c_str())\n\t\t\t\t\t\t\t    .detail(\"JSON\", json_spirit::write_string(json_spirit::mValue(v.toString())));\n\t\t\t\t\t\t\tself->correctSpecialKeys = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tASSERT(false); // Unrecognized key\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twait(delayJittered(5));\n\t\t\t} catch (Error& e) {\n\t\t\t\twait(tr.onError(e));\n\t\t\t}\n\t\t}\n\t}\n\n\tACTOR static Future<Void> _start(Database cx, ThrottlingWorkload* self) {\n\t\tstate vector<Future<Void>> clientActors;\n\t\tstate int actorId;\n\t\tfor (actorId = 0; actorId < self->actorsPerClient; ++actorId) {\n\t\t\tclientActors.push_back(timeout(clientActor(cx, self), self->testDuration, Void()));\n\t\t}\n\t\tclientActors.push_back(timeout(specialKeysActor(cx, self), self->testDuration, Void()));\n\t\tclientActors.push_back(timeout(self->tokenBucket.tokenAdderActor, self->testDuration, Void()));\n\t\twait(delay(self->testDuration));\n\t\treturn Void();\n\t}\n\n\tstd::string description() const override { return ThrottlingWorkload::NAME; }\n\tFuture<Void> start(Database const& cx) override { return _start(cx, this); }\n\tFuture<bool> check(Database const& cx) override { return correctSpecialKeys; }\n\n\tvoid getMetrics(vector<PerfMetric>& m) override {\n\t\tm.push_back(PerfMetric(\"TransactionsCommitted\", transactionsCommitted, false));\n\t}\n};\n\nWorkloadFactory<ThrottlingWorkload> ThrottlingWorkloadFactory(ThrottlingWorkload::NAME);\n", "meta": {"hexsha": "6df3f6bc696714aebb6c61beb3e3c3047b0ddb9f", "size": 8527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fdbserver/workloads/Throttling.actor.cpp", "max_stars_repo_name": "nik-io/foundationdb", "max_stars_repo_head_hexsha": "24ea35e56fe40a79646caa57b151c981c6bfd872", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-04T16:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-04T16:31:00.000Z", "max_issues_repo_path": "fdbserver/workloads/Throttling.actor.cpp", "max_issues_repo_name": "nik-io/foundationdb", "max_issues_repo_head_hexsha": "24ea35e56fe40a79646caa57b151c981c6bfd872", "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": "fdbserver/workloads/Throttling.actor.cpp", "max_forks_repo_name": "nik-io/foundationdb", "max_forks_repo_head_hexsha": "24ea35e56fe40a79646caa57b151c981c6bfd872", "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.5951219512, "max_line_length": 127, "alphanum_fraction": 0.7127946523, "num_tokens": 2137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1917196308636039}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\r\n// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.\r\n\r\n// This file was modified by Oracle on 2014-2018.\r\n// Modifications copyright (c) 2014-2018 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\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_STRATEGIES_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_STRATEGIES_HPP\r\n\r\n\r\n#include <boost/geometry/strategies/tags.hpp>\r\n\r\n#include <boost/geometry/strategies/area.hpp>\r\n#include <boost/geometry/strategies/azimuth.hpp>\r\n#include <boost/geometry/strategies/buffer.hpp>\r\n#include <boost/geometry/strategies/centroid.hpp>\r\n#include <boost/geometry/strategies/compare.hpp>\r\n#include <boost/geometry/strategies/convex_hull.hpp>\r\n#include <boost/geometry/strategies/covered_by.hpp>\r\n#include <boost/geometry/strategies/densify.hpp>\r\n#include <boost/geometry/strategies/disjoint.hpp>\r\n#include <boost/geometry/strategies/distance.hpp>\r\n#include <boost/geometry/strategies/envelope.hpp>\r\n#include <boost/geometry/strategies/intersection.hpp>\r\n#include <boost/geometry/strategies/intersection_strategies.hpp> // for backward compatibility\r\n#include <boost/geometry/strategies/relate.hpp>\r\n#include <boost/geometry/strategies/side.hpp>\r\n#include <boost/geometry/strategies/transform.hpp>\r\n#include <boost/geometry/strategies/within.hpp>\r\n\r\n#include <boost/geometry/strategies/cartesian/area.hpp>\r\n#include <boost/geometry/strategies/cartesian/azimuth.hpp>\r\n#include <boost/geometry/strategies/cartesian/box_in_box.hpp>\r\n#include <boost/geometry/strategies/cartesian/buffer_end_flat.hpp>\r\n#include <boost/geometry/strategies/cartesian/buffer_end_round.hpp>\r\n#include <boost/geometry/strategies/cartesian/buffer_join_miter.hpp>\r\n#include <boost/geometry/strategies/cartesian/buffer_join_round.hpp>\r\n#include <boost/geometry/strategies/cartesian/buffer_join_round_by_divide.hpp>\r\n#include <boost/geometry/strategies/cartesian/buffer_point_circle.hpp>\r\n#include <boost/geometry/strategies/cartesian/buffer_point_square.hpp>\r\n#include <boost/geometry/strategies/cartesian/buffer_side_straight.hpp>\r\n#include <boost/geometry/strategies/cartesian/centroid_average.hpp>\r\n#include <boost/geometry/strategies/cartesian/centroid_bashein_detmer.hpp>\r\n#include <boost/geometry/strategies/cartesian/centroid_weighted_length.hpp>\r\n#include <boost/geometry/strategies/cartesian/densify.hpp>\r\n#include <boost/geometry/strategies/cartesian/disjoint_segment_box.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_pythagoras_point_box.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_pythagoras_box_box.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_projected_point.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_projected_point_ax.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_segment_box.hpp>\r\n#include <boost/geometry/strategies/cartesian/envelope_segment.hpp>\r\n#include <boost/geometry/strategies/cartesian/intersection.hpp>\r\n#include <boost/geometry/strategies/cartesian/point_in_box.hpp>\r\n#include <boost/geometry/strategies/cartesian/point_in_poly_franklin.hpp>\r\n#include <boost/geometry/strategies/cartesian/point_in_poly_crossings_multiply.hpp>\r\n#include <boost/geometry/strategies/cartesian/point_in_poly_winding.hpp>\r\n#include <boost/geometry/strategies/cartesian/line_interpolate.hpp>\r\n#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>\r\n\r\n#include <boost/geometry/strategies/spherical/area.hpp>\r\n#include <boost/geometry/strategies/spherical/azimuth.hpp>\r\n#include <boost/geometry/strategies/spherical/densify.hpp>\r\n#include <boost/geometry/strategies/spherical/disjoint_segment_box.hpp>\r\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\r\n#include <boost/geometry/strategies/spherical/distance_cross_track.hpp>\r\n#include <boost/geometry/strategies/spherical/distance_cross_track_box_box.hpp>\r\n#include <boost/geometry/strategies/spherical/distance_cross_track_point_box.hpp>\r\n#include <boost/geometry/strategies/spherical/distance_segment_box.hpp>\r\n#include <boost/geometry/strategies/spherical/compare.hpp>\r\n#include <boost/geometry/strategies/spherical/envelope_segment.hpp>\r\n#include <boost/geometry/strategies/spherical/intersection.hpp>\r\n#include <boost/geometry/strategies/spherical/point_in_poly_winding.hpp>\r\n#include <boost/geometry/strategies/spherical/line_interpolate.hpp>\r\n#include <boost/geometry/strategies/spherical/ssf.hpp>\r\n\r\n#include <boost/geometry/strategies/geographic/area.hpp>\r\n#include <boost/geometry/strategies/geographic/azimuth.hpp>\r\n#include <boost/geometry/strategies/geographic/buffer_point_circle.hpp>\r\n#include <boost/geometry/strategies/geographic/densify.hpp>\r\n#include <boost/geometry/strategies/geographic/disjoint_segment_box.hpp>\r\n#include <boost/geometry/strategies/geographic/distance.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_andoyer.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_cross_track.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_cross_track_box_box.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_cross_track_point_box.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_segment_box.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_thomas.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_vincenty.hpp>\r\n#include <boost/geometry/strategies/geographic/envelope_segment.hpp>\r\n#include <boost/geometry/strategies/geographic/intersection.hpp>\r\n//#include <boost/geometry/strategies/geographic/intersection_elliptic.hpp>\r\n#include <boost/geometry/strategies/geographic/point_in_poly_winding.hpp>\r\n#include <boost/geometry/strategies/geographic/line_interpolate.hpp>\r\n#include <boost/geometry/strategies/geographic/side.hpp>\r\n#include <boost/geometry/strategies/geographic/side_andoyer.hpp>\r\n#include <boost/geometry/strategies/geographic/side_thomas.hpp>\r\n#include <boost/geometry/strategies/geographic/side_vincenty.hpp>\r\n\r\n#include <boost/geometry/strategies/agnostic/buffer_distance_symmetric.hpp>\r\n#include <boost/geometry/strategies/agnostic/buffer_distance_asymmetric.hpp>\r\n#include <boost/geometry/strategies/agnostic/hull_graham_andrew.hpp>\r\n#include <boost/geometry/strategies/agnostic/point_in_box_by_side.hpp>\r\n#include <boost/geometry/strategies/agnostic/point_in_point.hpp>\r\n#include <boost/geometry/strategies/agnostic/point_in_poly_winding.hpp>\r\n#include <boost/geometry/strategies/agnostic/simplify_douglas_peucker.hpp>\r\n\r\n#include <boost/geometry/strategies/strategy_transform.hpp>\r\n\r\n#include <boost/geometry/strategies/transform/matrix_transformers.hpp>\r\n#include <boost/geometry/strategies/transform/map_transformer.hpp>\r\n#include <boost/geometry/strategies/transform/inverse_transformer.hpp>\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_STRATEGIES_HPP\r\n", "meta": {"hexsha": "2873c85784aad19038efab4c119058bbb05954e6", "size": 7531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dep/win/include/boost/geometry/strategies/strategies.hpp", "max_stars_repo_name": "Netis/packet-agent", "max_stars_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "dep/win/include/boost/geometry/strategies/strategies.hpp", "max_issues_repo_name": "Netis/packet-agent", "max_issues_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "dep/win/include/boost/geometry/strategies/strategies.hpp", "max_forks_repo_name": "Netis/packet-agent", "max_forks_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 57.4885496183, "max_line_length": 95, "alphanum_fraction": 0.8243261187, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1917196308636039}}
{"text": "#pragma once\n\n#include <crab/analysis/graphs/cdg.hpp>\n#include <crab/cfg/cfg.hpp>\n#include <crab/cg/cg_bgl.hpp> // for sccg.hpp\n#include <crab/domains/discrete_domains.hpp>\n#include <crab/iterators/killgen_fixpoint_iterator.hpp>\n#include <crab/support/debug.hpp>\n#include <crab/support/stats.hpp>\n#include <crab/types/indexable.hpp>\n\n#include <boost/range/iterator_range.hpp>\n#include <unordered_map>\n#include <unordered_set>\n\n/**\n *  Dataflow analysis that for each block b it computes facts <i,V>\n *  meaning that there exists a path emanating from b that will reach\n *  assertion with id=i and its evaluation depends on the set of\n *  variables V.\n **/\nnamespace crab {\nnamespace analyzer {\n  \nusing namespace crab::iterators;\nusing namespace crab::domains;\nusing namespace crab::cfg;\n\nnamespace assertion_crawler_impl{\n// Convenient wrapper for using an assert statement as a key in\n// patricia tries.\ntemplate <typename CFG>\nclass assert_wrapper : public indexable {\npublic:\n  using statement_t = statement<typename CFG::basic_block_label_t,\n\t\t\t\ttypename CFG::number_t,\n\t\t\t\ttypename CFG::varname_t>;\nprivate:  \n  using this_type = assert_wrapper<CFG>;\n  // unique identifier for the assert needed for being used as key\n  ikos::index_t m_id;\n  // the assert statement\n  statement_t *m_assert;\npublic:\n  assert_wrapper(ikos::index_t id, statement_t *assert)\n    : m_id(id), m_assert(assert) {\n    if (!m_assert) {\n      CRAB_ERROR(\"assert_wrapper with null assert statement\");\n    }\n    if (!(m_assert->is_assert() || m_assert->is_ref_assert() || m_assert->is_bool_assert())) {\n      CRAB_ERROR(\"assert_wrapper must be assert, ref_assert, or bool_assert\");\n    }\n  }\n  \n  statement_t &get() {\n    return *m_assert;\n  }\n  const statement_t &get() const {\n    return *m_assert;\n  }\n  virtual ikos::index_t index() const override {\n    return m_id;\n  }\n  bool operator==(this_type o) const {\n    return m_id == o.m_id;\n  }\n  bool operator<(this_type o) const {\n    return m_id < o.m_id;\n  }\n  virtual void write(crab::crab_os &o) const override {\n    o << \"\\\"\" << *m_assert << \"\\\"\";\n  }\n};\n\ntemplate<typename CFG>\nclass assertion_crawler_domain {\n public:\n  using variable_t = typename CFG::variable_t;\n  using number_t = typename CFG::number_t;\n  using assert_wrapper_t = typename assertion_crawler_impl::assert_wrapper<CFG>;  \n  using var_dom_t = ikos::discrete_domain<variable_t>;\n  \n  using first_domain_t = discrete_pair_domain<assert_wrapper_t, var_dom_t>;\n  using second_domain_t = discrete_pair_domain<variable_t, var_dom_t>;\n  using this_type = assertion_crawler_domain<CFG>;\n\n private:\n  // the dataflow solution: map assertions to set of variables.\n  first_domain_t m_first;\n  // for inter-procedural analysis: map output variables to the set of\n  // variables whose data may flow to.\n  second_domain_t m_second;\n  \n public:\n\n  assertion_crawler_domain(const std::vector<variable_t> &vars)\n    : m_first(first_domain_t::bottom()), m_second(second_domain_t::bottom()) {\n    \n    for (variable_t v: vars) {\n      m_second.set(v, var_dom_t(v));\n    }\n  }\n  \n  assertion_crawler_domain()\n    : m_first(first_domain_t::bottom()), m_second(second_domain_t::bottom()) {}\n\n  void set_to_bottom() {\n    m_first = first_domain_t::bottom();\n    m_second = second_domain_t::bottom();\n  }\n\n  void set_to_top() {\n    m_first = first_domain_t::top();\n    m_second = second_domain_t::top();\n  }\n  \n  static this_type top() {\n    this_type res;\n    res.get_first() = first_domain_t::top();\n    res.get_second() = second_domain_t::top();\n    return res;\n  }\n\n  static this_type bottom() {\n    this_type res;\n    res.get_first() = first_domain_t::bottom();\n    res.get_second() = second_domain_t::bottom();\n    return res;\n  }\n\n  first_domain_t &get_first() {\n    return m_first;\n  }\n\n  const first_domain_t &get_first() const {\n    return m_first;\n  }\n  \n  second_domain_t &get_second() {\n    return m_second;\n  }\n  \n  const second_domain_t &get_second() const {\n    return m_second;\n  }\n\n  bool operator<=(const this_type& other) const {\n    return (get_first() <= other.get_first() && get_second() <= other.get_second());\n  }\n  \n  this_type merge(const this_type& other) const {\n    this_type res(*this);\n    res.get_first() = res.get_first() | other.get_first();\n    res.get_second() = res.get_second() | other.get_second();\n    return res;\n  }\n\n  void write(crab::crab_os &o) const {\n    o << \"(\";\n    m_first.write(o);\n    o << \",\";\n    m_second.write(o);\n    o << \")\";\n  }\n\n  friend crab::crab_os &operator<<(crab::crab_os &o, const assertion_crawler_domain<CFG> &dom) {\n    dom.write(o);\n    return o;\n  }\n};\n\n// Helper that applies a function to each pair of discrete_pair_domain.\ntemplate<typename Key, typename Value>\nstruct transform_discrete_pair_domain\n  : public std::unary_function<discrete_pair_domain<Key,Value>,\n\t\t\t       discrete_pair_domain<Key,Value>> {\n  using discrete_pair_domain_t = discrete_pair_domain<Key, Value>;\n  \n  template<typename Op>\n  discrete_pair_domain_t apply_on_value(discrete_pair_domain_t sol, Op &op) {\n    // All of this is needed because discrete_pair_domain_t cannot\n    // be modified in-place\n    if (sol.is_bottom() || sol.is_top()) {\n      return sol;\n    }\n    for (auto kv : sol) {\n      std::pair<Value,bool> p = op(kv.second);\n      if (p.second) {\n\tsol.set(kv.first, p.first);\n      }\n    }\n    return sol;\n  }\n  \n  template<typename Op>      \n  discrete_pair_domain_t apply_on_key_and_value(discrete_pair_domain_t sol, Op &op) {\n    // All of this is needed because discrete_pair_domain_t cannot\n    // be modified in-place\n    if (sol.is_bottom() || sol.is_top()) {\n      return sol;\n    }\n    for (auto kv : sol) {\n      std::pair<Value,bool> p = op(kv.first, kv.second);\n      if (p.second) {\n\tsol.set(kv.first, p.first);\n      }\n    }\n    return sol;\n  }  \n};\n\n// Wrapper to store a function summary that is represented by\n// assertion_crawler_domain.\ntemplate<class CFG>  \nclass summary {\npublic:\n  using variable_t = typename CFG::variable_t;\n  using abs_dom_t = assertion_crawler_domain<CFG>;\n  \nprivate:  \n  std::vector<variable_t> m_inputs;\n  std::vector<variable_t> m_outputs;\n  abs_dom_t m_sum;\npublic:\n  summary(const std::vector<variable_t> &inputs,\n\t  const std::vector<variable_t> &outputs,\n\t  abs_dom_t sum)\n    : m_sum(sum) {\n    std::copy(inputs.begin(), inputs.end(), std::back_inserter(m_inputs));\n    std::copy(outputs.begin(), outputs.end(), std::back_inserter(m_outputs));    \n  }\n  const std::vector<variable_t> &get_inputs() const {\n    return m_inputs;\n  }\n  const std::vector<variable_t> &get_outputs() const {\n    return m_outputs;\n  }\n  const abs_dom_t &get_summary() const {\n    return m_sum;\n  }\n  abs_dom_t &get_summary() {\n    return m_sum;\n  }\n\n  void write(crab_os &o) const {\n    o << \"Inputs:{\";\n    for(unsigned i=0,sz=m_inputs.size();i<sz;) {\n      o << m_inputs[i];\n      ++i;\n      if (i<sz) {\n\to << \",\";\n      }\n    }\n    o << \"} Outputs:{\";\n    for(unsigned i=0,sz=m_outputs.size();i<sz;) {\n      o << m_outputs[i];\n      ++i;\n      if (i<sz) {\n\to << \",\";\n      }\n    }\n    o << \"} \" << m_sum;\n  }\n};\n} // end namespace assertion_crawler_impl\n\ntemplate<class CFG>\nclass assertion_crawler;\n\n// Define the operations of the dataflow analysis\ntemplate <class CFG>\nclass assertion_crawler_operations\n  : public killgen_operations_api<CFG, assertion_crawler_impl::assertion_crawler_domain<CFG>> {\n\n  friend class assertion_crawler<CFG>;\n  \nprivate:\n  using basic_block_label_t = typename CFG::basic_block_label_t;\n  using basic_block_t = typename CFG::basic_block_t;\n  using statement_t = typename basic_block_t::statement_t;\n  using variable_t = typename CFG::variable_t;    \n  using varname_t = typename CFG::varname_t;  \n  using number_t = typename CFG::number_t;\n  using fdecl_t = typename CFG::fdecl_t;  \n  using live_t = typename statement_t::live_t;\npublic:\n  using assertion_crawler_domain_t = assertion_crawler_impl::assertion_crawler_domain<CFG>;\n  using var_dom_t = typename assertion_crawler_domain_t::var_dom_t;  \n  using assert_wrapper_t = assertion_crawler_impl::assert_wrapper<CFG>;  \n  using assert_map_t = typename std::unordered_map<statement_t *, assert_wrapper_t>;\n  // control-dependency graph: map a CFG block to the set of blocks\n  // which control-dependent on it.\n  using cdg_t = std::unordered_map<basic_block_label_t, std::vector<basic_block_label_t>>;\n  // inter-procedural analysis\n  using summary_map_t = callsite_or_fdecl_map<CFG, assertion_crawler_impl::summary<CFG>>;\nprivate:  \n  using killgen_operations_api_t = killgen_operations_api<CFG, assertion_crawler_domain_t>;\n  using assert_map_domain_t =  typename assertion_crawler_domain_t::first_domain_t;\n  using summary_dependencies_domain_t =  typename assertion_crawler_domain_t::second_domain_t;\npublic:\n  ////============================================================////\n  //            Propagate data/control dependencies\n  ////============================================================////  \n  class transfer_function : public statement_visitor<basic_block_label_t, number_t, varname_t> {\n    using visitor_t = statement_visitor<basic_block_label_t, number_t, varname_t>; \n    using bin_op_t = typename visitor_t::bin_op_t;\n    using assign_t = typename visitor_t::assign_t;\n    using assume_t = typename visitor_t::assume_t;\n    using select_t = typename visitor_t::select_t;\n    using assert_t = typename visitor_t::assert_t;\n    using int_cast_t = typename visitor_t::int_cast_t;\n    using havoc_t = typename visitor_t::havoc_t;\n    using unreach_t = typename visitor_t::unreach_t;\n    using callsite_t = typename visitor_t::callsite_t;\n    using intrinsic_t = typename visitor_t::intrinsic_t;\n    using make_ref_t = typename visitor_t::make_ref_t;\n    using remove_ref_t = typename visitor_t::remove_ref_t;\n    using region_init_t = typename visitor_t::region_init_t;\n    using region_copy_t = typename visitor_t::region_copy_t;\n    using region_cast_t = typename visitor_t::region_cast_t;\n    using load_from_ref_t = typename visitor_t::load_from_ref_t;\n    using store_to_ref_t = typename visitor_t::store_to_ref_t;\n    using gep_ref_t = typename visitor_t::gep_ref_t;\n    using assume_ref_t = typename visitor_t::assume_ref_t;\n    using assert_ref_t = typename visitor_t::assert_ref_t;\n    using select_ref_t = typename visitor_t::select_ref_t;\n    using bool_bin_op_t = typename visitor_t::bool_bin_op_t;\n    using bool_assign_cst_t = typename visitor_t::bool_assign_cst_t;\n    using bool_assign_var_t = typename visitor_t::bool_assign_var_t;\n    using bool_assume_t = typename visitor_t::bool_assume_t;\n    using bool_select_t = typename visitor_t::bool_select_t;\n    using bool_assert_t = typename visitor_t::bool_assert_t;\n    using variable_t = typename CFG::variable_t;\n\n    /** Add data-dependencies **/\n    class add_data_deps:\n      public std::unary_function<var_dom_t,  std::pair<var_dom_t, bool>> {\n\t\t\t\t\t\t    \n      var_dom_t m_uses;\n      var_dom_t m_defs;\n    public:\n      add_data_deps(const live_t &l): m_uses(var_dom_t::bottom()), m_defs(var_dom_t::bottom()) {\n        for (auto v : boost::make_iterator_range(l.uses_begin(), l.uses_end())) {\n          m_uses += v;\n\t}\n        for (auto v : boost::make_iterator_range(l.defs_begin(), l.defs_end())) {\n          m_defs += v;\n\t}\n      }\n      \n      add_data_deps(const var_dom_t &uses, const var_dom_t &defs) {\n\tfor (auto v: uses) { m_uses += v;}\n\tfor (auto v: defs) { m_defs += v;}\t\n      }\n\n      add_data_deps(const add_data_deps &o) = delete;\n\n      std::pair<var_dom_t, bool> operator()(var_dom_t d) {\n        bool change = false;\n        if (m_defs.is_bottom() && !m_uses.is_bottom() && !(m_uses & d).is_bottom()) {\n          d += m_uses;\n          change = true;\n        }\n        if (!(d & m_defs).is_bottom()) {\n          d -= m_defs;\n          d += m_uses;\n          change = true;\n        }\n        return std::make_pair(d, change);\n      }\n    };\n\n    /** Add control-dependencies **/\n    class add_control_deps :\n      public std::binary_function<assert_wrapper_t, var_dom_t, std::pair<var_dom_t, bool>> {\n\t\t\t\t  \n      const cdg_t &cdg;\n      const std::vector<basic_block_label_t> &roots;\n      var_dom_t uses;\n\n      // return true if we find a path in cdg from root to target\n      // FIXME: do caching for the queries\n      bool reach(const basic_block_label_t &root,\n                 const basic_block_label_t &target,\n                 std::unordered_set<basic_block_label_t> &visited) {\n        if (root == target)\n          return true;\n\n        // break cycles\n        if (visited.find(root) != visited.end())\n          return false;\n\n        visited.insert(root);\n        auto it = cdg.find(root);\n        if (it == cdg.end())\n          return false;\n\n        for (auto child : it->second) {\n          if (reach(child, target, visited))\n            return true;\n        }\n        return false;\n      }\n\n      bool reach(const basic_block_label_t &target) {\n        std::unordered_set<basic_block_label_t> visited;\n        for (auto r : roots)\n          if (reach(r, target, visited))\n            return true;\n        return false;\n      }\n\n    public:\n      add_control_deps(const cdg_t &_cdg,\n                       const std::vector<basic_block_label_t> &_roots,\n                       const live_t &l)\n          : cdg(_cdg), roots(_roots), uses(var_dom_t::bottom()) {\n        for (auto v : boost::make_iterator_range(l.uses_begin(), l.uses_end())) {\n          uses += v;\n\t}\n      }\n\n      add_control_deps(const add_data_deps &o) = delete;\n\n      std::pair<var_dom_t, bool> operator()(assert_wrapper_t w, var_dom_t d) {\n        bool change = false;\n        if (reach(w.get().get_parent()->label())) {\n          d += uses;\n          change = true;\n        }\n        return std::make_pair(d, change);\n      }\n    };\n\n    /** Remove data-dependencies **/\n    class remove_deps\n      : public std::unary_function<var_dom_t, std::pair<var_dom_t, bool>> {\n      \n      var_dom_t vars;\n    public:\n      remove_deps(const variable_t &v) : vars(var_dom_t::bottom()) {\n        vars += v;\n      }\n\n      remove_deps(const std::vector<variable_t> &vs)\n          : vars(var_dom_t::bottom()) {\n        for (auto v : vs) {\n          vars += v;\n        }\n      }\n\n      remove_deps(const remove_deps &o) = delete;\n\n      std::pair<var_dom_t, bool> operator()(var_dom_t d) {\n        bool change = false;\n        if (!(d & vars).is_bottom()) {\n          d -= vars;\n          change = true;\n        }\n        return std::make_pair(d, change);\n      }\n    };\n\n    using transform_sol_t =\n\t assertion_crawler_impl::transform_discrete_pair_domain<assert_wrapper_t, var_dom_t>;\n    using transform_sum_deps_t =\n\t assertion_crawler_impl::transform_discrete_pair_domain<variable_t, var_dom_t>;\n    \n    assertion_crawler_domain_t m_sol;\n    // map each assertion to a unique identifier\n    assert_map_t &m_assert_map;\n    // control-dependence graph (it can be empty)\n    const cdg_t &m_cdg;\n    // summaries from other functions\n    summary_map_t &m_summaries;\n    bool m_opt_ignore_region_offset;\n    \n    inline void process_assertion(statement_t &s) {\n      assert(s.is_assert() || s.is_ref_assert() || s.is_bool_assert());\n      \n      auto it = m_assert_map.find(&s);\n      if (it != m_assert_map.end())\n        return;\n\n      var_dom_t vdom = var_dom_t::bottom();\n      auto const &l = s.get_live();\n      for (auto v : boost::make_iterator_range(l.uses_begin(), l.uses_end())) {\n        vdom += v;\n      }\n\n      unsigned id = m_assert_map.size();\n      assert_wrapper_t val(id, &s);\n      m_assert_map.insert(typename assert_map_t::value_type(&s, val));\n      m_sol.get_first().set(val, vdom);\n      CRAB_LOG(\"assertion-crawler-step\", crab::outs()\n                                             << \"*** \" << s << \"\\n\"\n                                             << \"\\tAdded \" << vdom << \"\\n\";);\n    }\n    \n    inline void propagate_data(statement_t &s) {\n      CRAB_LOG(\"assertion-crawler-step\",\n\t       crab::outs() << \"*** \" << s << \"\\n\" << \"\\tBEFORE: \" << m_sol << \"\\n\");\n      \n      if (m_opt_ignore_region_offset) {\n\tstd::unique_ptr<add_data_deps> op = nullptr;\n\n\tif (s.is_ref_make()) {\n\t  auto make_ref = static_cast<make_ref_t*>(&s);\n\t  var_dom_t defs = var_dom_t::bottom();\n\t  var_dom_t uses = var_dom_t::bottom();\n\t  defs += make_ref->lhs();\n\t  uses += make_ref->region();\n\t  op.reset(new add_data_deps(uses, defs));\n\t} else if (s.is_ref_remove()) {\n\t  auto remove_ref = static_cast<remove_ref_t*>(&s);\n\t  var_dom_t defs = var_dom_t::bottom();\n\t  var_dom_t uses = var_dom_t::bottom();\n\t  uses += remove_ref->region();\n\t  op.reset(new add_data_deps(uses, defs));\n\t} else if (s.is_ref_load()) { \n\t  auto load_ref = static_cast<load_from_ref_t*>(&s);\n\t  var_dom_t defs = var_dom_t::bottom();\n\t  var_dom_t uses = var_dom_t::bottom();\n\t  defs += load_ref->lhs();\n\t  uses += load_ref->region();\n\t  op.reset(new add_data_deps(uses, defs));\n\t} else if (s.is_ref_store()) {\n\t  auto store_ref = static_cast<store_to_ref_t*>(&s);\n\t  var_dom_t defs = var_dom_t::bottom();\n\t  var_dom_t uses = var_dom_t::bottom();\n\t  defs += store_ref->region();\n\t  uses += store_ref->region();\n\t  if (store_ref->val().is_variable()) {\n\t    uses += store_ref->val().get_variable();\n\t  }\n\t  op.reset(new add_data_deps(uses, defs));\n\t} else if (s.is_ref_gep()) {\n\t  auto gep_ref = static_cast<gep_ref_t*>(&s);\n\t  if (gep_ref->lhs() != gep_ref->rhs()) {\n\t    var_dom_t defs = var_dom_t::bottom();\n\t    var_dom_t uses = var_dom_t::bottom();\n\t    defs += gep_ref->lhs();\n\t    uses += gep_ref->rhs();\n\t    op.reset(new add_data_deps(uses, defs));\t  \n\t  }\n\t} else {\n\t  op.reset(new add_data_deps(s.get_live()));\t  \t\n\t}\n\tif (op) {\n\t  transform_sol_t f1; \n\t  m_sol.get_first() = std::move(f1.apply_on_value(m_sol.get_first(), *op));\n\t  transform_sum_deps_t f2;\n\t  m_sol.get_second() = std::move(f2.apply_on_value(m_sol.get_second(), *op));\t\n\t}\n      }  else {\n\tadd_data_deps op(s.get_live());\n\ttransform_sol_t f1;\n\tm_sol.get_first() = std::move(f1.apply_on_value(m_sol.get_first(), op));\n\ttransform_sum_deps_t f2;\n\tm_sol.get_second() = std::move(f2.apply_on_value(m_sol.get_second(), op));\n      }\n      \n      CRAB_LOG(\"assertion-crawler-step\", crab::outs() << \"\\tAFTER \" << m_sol << \"\\n\";);\n    }\n\n    inline void propagate_data_and_control(statement_t &s) {\n      CRAB_LOG(\"assertion-crawler-step\", crab::outs()\n\t       << \"*** \" << s << \"\\n\"\n\t       << \"\\tBEFORE: \" << m_sol << \"\\n\");\n      // -- add data dependencies\n      add_data_deps op(s.get_live());\n      transform_sol_t df1;\n      m_sol.get_first() = std::move(df1.apply_on_value(m_sol.get_first(), op));\n      transform_sum_deps_t df2;\n      m_sol.get_second() = std::move(df2.apply_on_value(m_sol.get_second(), op));      \n      CRAB_LOG(\"assertion-crawler-step\",\n               crab::outs() << \"\\tAFTER data-dep \" << m_sol << \"\\n\";);\n\n      if (!m_cdg.empty()) {\n\t// -- add control dependencies\n\tfor (auto const &pred : boost::make_iterator_range(s.get_parent()->prev_blocks())) {\n\t  // it->second is the set of basic blocks that control\n\t  // dependent on s' block\n\t  auto it = m_cdg.find(pred);\n\t  if (it != m_cdg.end()) {\n\t    auto const &children = it->second;\n\t    CRAB_LOG(\"assertion-crawler-step-control\", crab::outs() << \"{\";\n\t\t     for (auto &c : children) {\n\t\t       crab::outs() << c << \";\";\n\t\t     }\n\t\t     crab::outs() << \"} control-dependent on \" << pred << \"\\n\";);\n\t    add_control_deps op(m_cdg, children, s.get_live());\n\t    transform_sol_t cf;\n\t    m_sol.get_first() = std::move(cf.apply_on_key_and_value(m_sol.get_first(), op));\n\t    CRAB_LOG(\"assertion-crawler-step-control\",\n\t\t     crab::outs() << \"\\tAFTER control-dep \" << m_sol << \"\\n\";);\n\t  }\n\t}\n      }\n    }\n    \n  public:\n    transfer_function(assertion_crawler_domain_t init,\n\t\t      const cdg_t &g,\n\t\t      assert_map_t &assert_map,\n\t\t      summary_map_t &summaries,\n\t\t      bool ignore_region_offset)\n      : m_sol(init), m_assert_map(assert_map), m_cdg(g), m_summaries(summaries),\n\tm_opt_ignore_region_offset(ignore_region_offset) {}\n\n    assertion_crawler_domain_t get_solution() const {\n      return m_sol;\n    }\n\n    void visit(bin_op_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(assign_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(assume_t &s) {\n      propagate_data_and_control(s);\n    }\n\n    void visit(select_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(assert_t &s) {\n      process_assertion(s);\n    }\n\n    void visit(int_cast_t &s) {\n      propagate_data(s);\n    }\n    \n    void visit(unreach_t &) {\n      m_sol.set_to_bottom();\n    }\n\n    void visit(havoc_t &s) {\n      CRAB_LOG(\"assertion-crawler-step\", crab::outs()\n                                             << \"*** \" << s << \"\\n\"\n                                             << \"\\tBEFORE: \" << m_sol << \"\\n\");\n      remove_deps op(s.get_variable());\n      transform_sol_t f1;\n      m_sol.get_first() = std::move(f1.apply_on_value(m_sol.get_first(), op));\n      transform_sum_deps_t f2;      \n      m_sol.get_second() = std::move(f2.apply_on_value(m_sol.get_second(), op));      \n      CRAB_LOG(\"assertion-crawler-step\", crab::outs()\n                                             << \"\\tAFTER \" << m_sol << \"\\n\";);\n    }\n\n    // For each key-value pair rename from variables with to variables\n    // *only* on the value. This is an expensive operation because it\n    // creates a new discrete_pair_domain from scratch.\n    template<typename Key>\n    static void rename(discrete_pair_domain<Key, var_dom_t> &dpd,\n\t\t       const std::vector<variable_t> &from, const std::vector<variable_t> &to) {\n      using discrete_pair_domain_t = discrete_pair_domain<Key, var_dom_t>;\n      if (from.empty() || dpd.is_top() || dpd.is_bottom()) {\n\treturn;\n      }\n      if (from.size() != to.size()) {\n\tCRAB_ERROR(\"discrete_pair_domain::rename with input vectors of different sizes\");\n      }\n      discrete_pair_domain_t res = discrete_pair_domain_t::bottom();\n      for (auto kv: dpd) {\n\tauto key = kv.first;\n\tauto dom = kv.second;\n\tdom.rename(from, to);\n\tres.set(key, dom);\n      }\n      std::swap(dpd, res);\n    }\n\n    // dpd is of the form [key1 -> {o1,x1,...}, key2 -> {o2,x2,...}, ...]\n    //     \n    // sdd is a map that relates outputs with inputs.\n    //     It is of the form [o1 -> {i1,i2}, o2  -> {i3,i4}]\n    // This function replaces the occurrences of each sdd's key in dpd with its value.\n    // That is, [key1 -> {i1,i2,x1,...}, key2 -> {i3,i4,x2,...}, ...]\n    template<typename Key>\n    static void apply_summary(discrete_pair_domain<Key, var_dom_t> &dpd,\n\t\t\t      summary_dependencies_domain_t &sdd) {\n      auto outputs_to_inputs = [&sdd](const var_dom_t &var_dom) {\n\t\t\t\t if (var_dom.is_top()) {\n\t\t\t\t   return var_dom_t::top();\n\t\t\t\t } else if (var_dom.is_bottom()) {\n\t\t\t\t   return var_dom_t::bottom();\n\t\t\t\t } else {\n\t\t\t\t   var_dom_t res = var_dom_t::bottom();\n\t\t\t\t   for (auto it=var_dom.begin(), et=var_dom.end(); it!=et; ++it) {\n\t\t\t\t     variable_t v = *it;\n\t\t\t\t     var_dom_t inputs(sdd[v]);\n\t\t\t\t     if (inputs.is_bottom()) {\n\t\t\t\t       // the callee doesn't know\n\t\t\t\t       // about v so we just propagate\n\t\t\t\t       // it as it's.\n\t\t\t\t       var_dom_t vs(v);\n\t\t\t\t       res += vs; // not in sdd\n\t\t\t\t     } else {\n\t\t\t\t       res += inputs;\n\t\t\t\t     }\n\t\t\t\t   }\n\t\t\t\t   return res;\n\t\t\t\t }};\n\n      using discrete_pair_domain_t = discrete_pair_domain<Key, var_dom_t>;      \n      discrete_pair_domain_t out = discrete_pair_domain_t::bottom();\n      for (auto kv: dpd) {\n\tvar_dom_t res = outputs_to_inputs(kv.second);\n\tout.set(kv.first, res);\n      }\n      std::swap(dpd, out);\n    }\n\t\t\t\t      \n    \n    void visit(callsite_t &s) {\n\n      CRAB_LOG(\"assertion-crawler-step-cs\", crab::outs()\n\t       << \"*** \" << s << \"\\n\"\n\t       << \"\\tBEFORE: \" << m_sol << \"\\n\");\n      \n      auto it = m_summaries.find(&s);\n      if (it != m_summaries.end()) {\n\tauto callee_summary_info = it->second;\n\tconst std::vector<variable_t> &callsite_inputs = s.get_args();\n\tconst std::vector<variable_t> &callsite_outputs = s.get_lhs();\n\tconst std::vector<variable_t> &callee_inputs = callee_summary_info.get_inputs();\n\tconst std::vector<variable_t> &callee_outputs = callee_summary_info.get_outputs();\t\n\tauto &callee_summary = callee_summary_info.get_summary();\n\n\tCRAB_LOG(\"assertion-crawler-step-cs\",\n\t\t crab::outs() << \"\\tSummary at the callee: \"\n\t\t << callee_summary.get_second() << \"\\n\";\n\t\t crab::outs() << \"\\tCallee input variables: {\";\n\t\t for (auto const& v: callee_inputs) {\n\t\t   crab::outs() << v << \";\";\n\t\t }\n\t\t crab::outs() << \"}\\n\\tCallee output variables: {\";\n\t\t for (auto const& v: callee_outputs) {\n\t\t   crab::outs() << v << \";\";\n\t\t }\n\t\t crab::outs() << \"}\\n\";);\n\n\t// -- Update assertion map domain at the caller\n\tassert_map_domain_t amd(m_sol.get_first());\n\trename(amd, callsite_outputs, callee_outputs);\n\tapply_summary(amd, callee_summary.get_second());\n\trename(amd, callee_inputs, callsite_inputs);\n\t// Propagate the assertion map domain from the callee to the caller\n\tassert_map_domain_t callee_amd(callee_summary.get_first());\n\trename(callee_amd, callee_inputs, callsite_inputs);\n\tm_sol.get_first() = amd | callee_amd;\n\t\n\t// -- Update the summary dependencies at the caller\n\tsummary_dependencies_domain_t sdm(m_sol.get_second());\n\trename(sdm, callsite_outputs, callee_outputs);\n\tapply_summary(sdm, callee_summary.get_second());\n\trename(sdm, callee_inputs, callsite_inputs);\n\tm_sol.get_second() = sdm;\n      } else {\n\tCRAB_LOG(\"assertion-crawler-step-cs\",\n\t\t CRAB_WARN(\"assertion-crawler did not find summary for callee at \", s));\n\n\t// crab::outs() << \"Summary table:\\n\";\n\t// for (auto &kv: m_summaries) {\n\t//   crab::outs() << \"\\t\";\n\t//   crab::outs() << &(kv.first) << \" \";\t  \n\t//   kv.first.write(crab::outs());\n\t//   crab::outs() << \" -> \";\n\t//   crab::outs() << &(kv.second) << \" \";\t  \n\t//   kv.second.write(crab::outs());\n\t//   crab::outs() << \"\\n\";\n\t// }\n\tpropagate_data(s);\n      }\n      \n      CRAB_LOG(\"assertion-crawler-step-cs\", crab::outs()\n\t       << \"\\tAFTER \" << m_sol << \"\\n\";);\n    }\n\n    void visit(intrinsic_t &s) {\n      propagate_data(s);      \n    }\n\n    void visit(make_ref_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(remove_ref_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(region_init_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(region_copy_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(region_cast_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(load_from_ref_t &s) {\n      propagate_data(s);             \n    }\n\n    void visit(store_to_ref_t &s) {\n      propagate_data(s);       \n    }\n\n    void visit(gep_ref_t &s) {\n      propagate_data(s); \n    }\n\n    void visit(assume_ref_t &s) {\n      propagate_data_and_control(s);\n    }\n\n    void visit(assert_ref_t &s) {\n      process_assertion(s);\n    }\n    \n    void visit(select_ref_t &s) {\n      propagate_data(s);\n    }    \n\n    void visit(bool_bin_op_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(bool_assign_var_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(bool_assign_cst_t &s) {\n      propagate_data(s);\n    }\n\n    void visit(bool_select_t &s) {\n      propagate_data(s);\n    }\n    \n    void visit(bool_assume_t &s) {\n      propagate_data_and_control(s);\n    }\n    \n    void visit(bool_assert_t &s) {\n      process_assertion(s);\n    }\n  };\n\nprivate:\n  assert_map_t &m_assert_map;\n  summary_map_t &m_summaries;\n  cdg_t m_cdg; // control dependencies\n\n  // only data-dependencies (no control)  \n  bool m_opt_only_data; \n  // ignore dependencies from references used to access regionsa  \n  bool m_opt_ignore_region_offset; \n  \npublic:\n  assertion_crawler_operations\n  (CFG cfg, assert_map_t &assert_map, summary_map_t &summaries,\n   bool only_data, bool ignore_region_offset)\n    : killgen_operations_api_t(cfg),\n      m_assert_map(assert_map),\n      m_summaries(summaries),\n      m_opt_only_data(only_data),\n      m_opt_ignore_region_offset(ignore_region_offset) {}\n\n  /* === Begin killgen_operations_api === */\n  virtual bool is_forward() override {\n    // This is a backward analysis\n    return false;\n  }\n\n  virtual std::string name() override {\n    return \"assertion-crawler\";\n  }\n\n  virtual void init_fixpoint() override {\n    if (!m_opt_only_data) {\n      crab::ScopedCrabStats __st__(\"Control-Dependency Graph\");\n      crab::analyzer::graph_algo::control_dep_graph(this->m_cfg, m_cdg);\n    }\n  }\n\n  virtual assertion_crawler_domain_t entry() override {\n    if (this->m_cfg.has_func_decl()) {\n      return assertion_crawler_domain_t(this->m_cfg.get_func_decl().get_outputs());\n    } else {\n      return assertion_crawler_domain_t();\n    }\n  }\n\n  virtual assertion_crawler_domain_t\n  merge(assertion_crawler_domain_t d1, assertion_crawler_domain_t d2) override {\n    return d1.merge(d2);\n  }\n\n  virtual assertion_crawler_domain_t analyze(const basic_block_label_t &bb_id,\n\t\t\t\t\t     assertion_crawler_domain_t out) override {\n    auto &bb = this->m_cfg.get_node(bb_id);\n    transfer_function vis(out, m_cdg, m_assert_map, m_summaries,\n\t\t\t  m_opt_ignore_region_offset);\n    for (auto &s : boost::make_iterator_range(bb.rbegin(), bb.rend())) {\n      s.accept(&vis);\n    }\n    return vis.get_solution();\n  }\n  /* ===  End killgen_operations_api === */\n  \n  const cdg_t &get_cdg() const {\n    return m_cdg;\n  }\n  assert_map_t &get_assert_map() {\n    return m_assert_map;\n  }\n  const assert_map_t &get_assert_map() const {\n    return m_assert_map;\n  }\n  summary_map_t &get_summary_map() {\n    return m_summaries;\n  }\n  const summary_map_t &get_summary_map() const {\n    return m_summaries;\n  }\n};\n\ntemplate<typename CallGraph>\nclass inter_assertion_crawler;\n\n/**\n * Intra-procedural assertion crawler dataflow analysis\n *\n * Compute for each basic block b a set of facts (i,V) such that\n * there exists a path from b that will check assertion i and its\n * evaluation depends on the set of variables V.\n **/\ntemplate <class CFG>\nclass assertion_crawler : public crab::iterators::killgen_fixpoint_iterator<\n                              CFG, assertion_crawler_operations<CFG>> {\n\n  template<typename T> friend class inter_assertion_crawler;\npublic:\n  using basic_block_label_t = typename CFG::basic_block_label_t;\n  using varname_t = typename CFG::varname_t;\n\nprivate:\n  using assertion_crawler_op_t = assertion_crawler_operations<CFG>;\n  using fixpo_t = crab::iterators::killgen_fixpoint_iterator<CFG, assertion_crawler_op_t>; \n  using basic_block_t = typename CFG::basic_block_t;\n\npublic:\n  using assertion_crawler_domain_t = typename assertion_crawler_op_t::assertion_crawler_domain_t;\n  using assert_map_domain_t = typename assertion_crawler_domain_t::first_domain_t;\n  using assert_map_t = typename assertion_crawler_op_t::assert_map_t;\n  using summary_map_t = typename assertion_crawler_op_t::summary_map_t;    \n  using results_map_t = std::unordered_map<basic_block_label_t, assertion_crawler_domain_t>;\nprivate:\n\n  results_map_t m_results;  \n  assertion_crawler_op_t m_assert_crawler_op;\n\n  // used by inter_assertion_crawler\n  assertion_crawler_domain_t &lookup_results(const basic_block_label_t &bb) {\n    auto it = m_results.find(bb);\n    if (it == m_results.end()) {\n      auto res = m_results.insert({bb, assertion_crawler_domain_t::top()});\n      return res.first->second;\n    } else {\n      return it->second;\n    }\n  }\n  \npublic:\n  assertion_crawler(CFG cfg, assert_map_t &assert_map, summary_map_t &summaries,\n\t\t    bool only_data = false,\n\t\t    bool ignore_region_offset = false) \n    : fixpo_t(cfg, m_assert_crawler_op),\n      m_assert_crawler_op(cfg, assert_map, summaries, only_data, ignore_region_offset) {\n  }\n\n  assertion_crawler(const assertion_crawler<CFG> &o) = delete;\n  assertion_crawler<CFG> &operator=(const assertion_crawler<CFG> &o) = delete;\n\n  void exec(void) {\n    this->run();\n    for (auto p : boost::make_iterator_range(this->in_begin(), this->in_end())) {\n      m_results.insert(std::make_pair(p.first, p.second));\n    }\n    this->release_memory();\n  }\n\n  // return the dataflow facts that hold at the entry of the block bb\n  assert_map_domain_t get_results(const basic_block_label_t &bb) const {\n    auto it = m_results.find(bb);\n    if (it == m_results.end()) {\n      return assert_map_domain_t::top();\n    } else {\n      return it->second.get_first();\n    }\n  }\n\n  // return the dataflow facts of the pre-state at each program point in bb\n  void get_results(\n      const basic_block_label_t &b,\n      std::map<typename CFG::statement_t *, assert_map_domain_t> &res) const {\n    auto it = m_results.find(b);\n    if (it != m_results.end()) {\n      if (!it->second.get_first().is_bottom()) {\n        auto &bb = this->m_cfg.get_node(b);\n        typename assertion_crawler_op_t::transfer_function vis\n\t  (it->second /* OUT dataflow facts */,\n\t   m_assert_crawler_op.m_cdg,\n\t   m_assert_crawler_op.m_assert_map,\n\t   m_assert_crawler_op.m_summaries,\n\t   m_assert_crawler_op.m_opt_ignore_region_offset);\n        for (auto &s : boost::make_iterator_range(bb.rbegin(), bb.rend())) {\n          s.accept(&vis);\n          auto in = vis.get_solution().get_first();\n          res.insert(std::make_pair(&s, in));\n        }\n      }\n    }\n  }\n\n  void write(crab_os &o) const {\n    o << \"Assertion Crawler Analysis \";    \n    if (this->m_cfg.has_func_decl()) {\n      auto const &fdecl = this->m_cfg.get_func_decl();\n      o << \"for \" << fdecl.get_func_name() <<\"\\n\";\n    } else {\n      o << \"\\n\";\n    }\n    \n    // Print invariants in DFS to enforce a fixed order\n    std::set<basic_block_label_t> visited;\n    std::vector<basic_block_label_t> worklist;\n    worklist.push_back(this->m_cfg.entry());\n    visited.insert(this->m_cfg.entry());\n    while (!worklist.empty()) {\n      auto cur_label = worklist.back();\n      worklist.pop_back();\n      auto it = m_results.find(cur_label);\n      assert(it != m_results.end());\n      auto inv = it->second.get_first();\n      crab::outs() << basic_block_traits<basic_block_t>::to_string(cur_label)\n                   << \"=\" << inv << \"\\n\";\n      auto const &cur_node = this->m_cfg.get_node(cur_label);\n      for (auto const &kid_label :\n           boost::make_iterator_range(cur_node.next_blocks())) {\n        if (visited.insert(kid_label).second) {\n          worklist.push_back(kid_label);\n        }\n      }\n    }\n  }\n};\n\ntemplate <typename CFG>\ninline crab_os &operator<<(crab_os &o, const assertion_crawler<CFG> &ac) {\n  ac.write(o);\n  return o;\n}\n\n\n/** Context-insensitive interprocedural analysis **/\ntemplate <typename CallGraph>\nclass inter_assertion_crawler {\n  using cg_node_t = typename CallGraph::node_t;\n  using cg_edge_t = typename CallGraph::edge_t;\n  using this_type = inter_assertion_crawler<CallGraph>;\n\npublic:\n  using cg_t = CallGraph;\n  using cg_ref_t = crab::cg::call_graph_ref<cg_t>;\n  using cfg_t = typename cg_node_t::cfg_t;\n  using basic_block_label_t = typename cfg_t::basic_block_label_t;  \n  using varname_t = typename cfg_t::varname_t;\n  using number_t = typename cfg_t::number_t;\n  using variable_t = typename cfg_t::variable_t;\n  using assertion_crawler_t = assertion_crawler<cfg_t>;\n  using assertion_crawler_domain_t = typename assertion_crawler_t::assertion_crawler_domain_t;   \n  using assert_map_domain_t = typename assertion_crawler_t::assert_map_domain_t;\nprivate:\n  using summary_map_t = typename assertion_crawler_t::summary_map_t;\n  using summary_t = typename summary_map_t::mapped_type;\n  using assert_map_t = typename assertion_crawler_t::assert_map_t;      \n  using inter_results_map_t = std::unordered_map<cfg_t, std::unique_ptr<assertion_crawler_t>>;\n  \n  cg_t &m_cg; // the call graph\n  assert_map_t m_assert_map; // to assign id's to assert statements\n  summary_map_t m_summaries; // summaries\n  inter_results_map_t m_inter_results; // the results of the analysis\n  bool m_opt_only_data; // whether consider only data dependencies\n  // ignore dependencies from references used to access regions\n  bool m_opt_ignore_region_offset;\npublic:\n  inter_assertion_crawler(cg_t &cg, bool only_data = false, bool ignore_region_offset = false)\n    : m_cg(cg), m_opt_only_data(only_data), m_opt_ignore_region_offset(ignore_region_offset) {\n  }\n\n  inter_assertion_crawler(const this_type &other) = delete;\n  this_type &operator=(const this_type &other) = delete;\n  \n  void run(bool do_type_checking = true) {\n    if (do_type_checking) {\n      CRAB_VERBOSE_IF(1, get_msg_stream() << \"Type checking call graph ... \";);\n      crab::CrabStats::resume(\"CallGraph type checking\");\n      m_cg.type_check();\n      crab::CrabStats::stop(\"CallGraph type checking\");\n      CRAB_VERBOSE_IF(1, get_msg_stream() << \"OK\\n\";);\n    }\n    \n    CRAB_VERBOSE_IF(1, get_msg_stream()\n                           << \"Started inter-procedural assertion crawler analysis\\n\";);\n    CRAB_LOG(\"assertion-crawler\", m_cg.write(crab::outs()); crab::outs() << \"\\n\");\n    crab::ScopedCrabStats __st__(\"InterAssertionCrawler\");\n\n    auto analyze = [this](cfg_t cfg) {\n\t\t     assert(cfg.has_func_decl());\n\t\t     auto const &fdecl = cfg.get_func_decl();\n\t\t     const std::string &fun_name = fdecl.get_func_name();\n\t\t     CRAB_VERBOSE_IF(1, get_msg_stream() << \"++ Analyzing \" << fun_name << \"...\\n\";);\n\t\t     // --- Run the intra-procedural analysis to compute summaries.\n\t\t     std::unique_ptr<assertion_crawler_t> intra_analysis\n\t\t       (new assertion_crawler_t(cfg, m_assert_map, m_summaries,\n\t\t\t\t\t\tm_opt_only_data, m_opt_ignore_region_offset));\n\t\t     intra_analysis->exec();\n\t\t     // --- Store the cfg's summary \n\t\t     assertion_crawler_domain_t &results = intra_analysis->lookup_results(cfg.entry());\n\t\t     summary_t summary(fdecl.get_inputs(), fdecl.get_outputs(), results);\n\t\t     auto it = m_summaries.find(&fdecl);\n\t\t     if (it == m_summaries.end()) {\n\t\t       m_summaries.insert(std::make_pair(&fdecl, std::move(summary)));\t\t       \n\t\t     } else {\n\t\t       it->second = std::move(summary);\n\t\t     }\n\t\t     \n\t\t     return std::move(intra_analysis);\t   \n\t\t   };\n\n    auto hasStabilized = [](assertion_crawler_t &old, assertion_crawler_t &current, cfg_t cfg) {\n\t\t\t     for (auto it = cfg.label_begin(), et=cfg.label_end(); it!=et; ++it) {\n\t\t\t       const basic_block_label_t &bb = *it;\n\t\t\t       const assertion_crawler_domain_t &old_d = old.lookup_results(bb);\n\t\t\t       const assertion_crawler_domain_t &current_d = current.lookup_results(bb);\n\t\t\t       if (!(current_d <= old_d)) {\n\t\t\t\t return false;\n\t\t\t       }\n\t\t\t     }\n\t\t\t     return true;\n\t\t\t   };\n\n    // If the fixpoint converges very slowly we give up after\n    // max_fixpo_iters iterations\n    const unsigned max_fixpo_iters = 10;\n    \n    std::vector<cg_node_t> rev_order;\n    graph_algo::scc_graph<cg_ref_t> Scc_g(m_cg);\n    graph_algo::rev_topo_sort(Scc_g, rev_order);\n    for (auto const &n : rev_order) {\n      std::vector<cg_node_t> &scc_mems = Scc_g.get_component_members(n);\n\n      // The SCC is recursive if it has more than one element or\n      // there is only one that calls directly to itself.\n      bool isRecursive =\n\t(scc_mems.size() > 1) ||\n\tstd::any_of(m_cg.succs(n).first, m_cg.succs(n).second,\n\t\t    [n](const cg_edge_t &e) { return (n == e.dest()); });\n      \n      if (isRecursive) {\n\t// standard fixpoint among all the SCC members\n\tunsigned iter = 0;\n\tbool change = true;\n\twhile (change || iter > max_fixpo_iters) {\n\t  change = false;\n\t  for (unsigned i=0, num_sccs=scc_mems.size();i<num_sccs;++i) {\n\t    cfg_t cfg = scc_mems[i].get_cfg();\n\t    std::unique_ptr<assertion_crawler_t> current = analyze(cfg);\n\t    if (iter == 0) {\n\t      m_inter_results.insert(std::make_pair(cfg, std::move(current)));\n\t      change = true;\n\t    } else {\n\t      auto it = m_inter_results.find(cfg);\n\t      assert(it != m_inter_results.end());\n\t      assertion_crawler_t &last = *(it->second);\n\t      change |= !hasStabilized(last, *current, cfg);\n\t      it->second = std::move(current);\n\t    }\n\t  }\n\t  ++iter;\n\t}\n\tif (iter > max_fixpo_iters) {\n\t  CRAB_WARN(\"Inter-procedural Assertion Crawler analysis was abruptly stopped on a \",\n\t\t    \"recursive SCC after \", max_fixpo_iters, \" iterations\");\n\t}\n      } else {\n\tfor (auto m : scc_mems) {\n\t  cfg_t cfg = m.get_cfg();\n\t  std::unique_ptr<assertion_crawler_t> intra_analysis = analyze(cfg);\n\t  m_inter_results.insert(std::make_pair(cfg, std::move(intra_analysis)));\n\t}\n      } \n    }\n\n    CRAB_VERBOSE_IF(1, get_msg_stream()\n\t\t    << \"Finished inter-procedural assertion crawler analysis\\n\";);\n  }\n\n  // Return the dataflow facts that hold at the entry of the basic block b in cfg.\n  assert_map_domain_t get_results(const cfg_t &cfg, const basic_block_label_t &bb) const {\n    auto it = m_inter_results.find(cfg);\n    if (it != m_inter_results.end()) {\n      return it->second->get_results(bb);\n    } else {\n      return assert_map_domain_t::top();\n    }\n  }\n\n  void write(crab_os &o) const {\n    for (auto &kv: m_inter_results) {\n      kv.second->write(o);\n    }\n  }\n  \n};\n\n} // namespace analyzer\n} // namespace crab\n", "meta": {"hexsha": "37fe85558136e71171d66e9aa2a9f4fad7bd719f", "size": 40829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/analysis/dataflow/assertion_crawler.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/analysis/dataflow/assertion_crawler.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/analysis/dataflow/assertion_crawler.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 32.9266129032, "max_line_length": 97, "alphanum_fraction": 0.6486076073, "num_tokens": 10540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19171963086360388}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 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_BLOCK_MODE_CIPHER_FEEDBACK_HPP\n#define CRYPTO3_BLOCK_MODE_CIPHER_FEEDBACK_HPP\n\n#include <memory>\n#include <limits>\n\n#include <boost/static_assert.hpp>\n\n#include <nil/crypto3/modes/mode.hpp>\n#include <nil/crypto3/modes/cts.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace block {\n            namespace modes {\n                namespace detail {\n                    template<typename Cipher, typename Padding, template<typename> class Allocator = std::allocator>\n                    struct cfb_policy {\n                        typedef std::size_t size_type;\n\n                        typedef Cipher cipher_type;\n                        typedef Padding padding_type;\n\n                        constexpr static const size_type block_bits = cipher_type::block_bits;\n                        constexpr static const size_type block_words = cipher_type::block_words;\n                        typedef typename cipher_type::block_type block_type;\n\n                        static void shift_register(cipher_type &cipher) {\n                            const size_t shift = feedback();\n                            const size_t carryover = block_size() - shift;\n\n                            if (carryover > 0) {\n                                copy_mem(m_state.data(), &m_state[shift], carryover);\n                            }\n                            copy_mem(&m_state[carryover], m_keystream.data(), shift);\n                            cipher().encrypt(m_state, m_keystream);\n                            m_keystream_pos = 0;\n                        }\n\n                        static inline void xor_copy(uint8_t buf[], uint8_t key_buf[], size_t len) {\n                            for (size_t i = 0; i != len; ++i) {\n                                uint8_t k = key_buf[i];\n                                key_buf[i] = buf[i];\n                                buf[i] ^= k;\n                            }\n                        }\n                    };\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding,\n                             typename CiphertextStealingMode>\n                    struct cfb_encryption_policy : public cfb_policy<Cipher, Padding> {};\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding>\n                    struct cfb_encryption_policy<Cipher, FeedbackBits, Padding, cts<0, Cipher, Padding>>\n                        : public cfb_policy<Cipher, Padding> {\n                        typedef typename cfb_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename cfb_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename cfb_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const size_type block_bits = cfb_policy<Cipher, Padding>::block_bits;\n                        constexpr static const size_type block_words = cfb_policy<Cipher, Padding>::block_words;\n                        typedef typename cfb_policy<Cipher, Padding>::block_type block_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext) {\n                            if (!valid_nonce_length(nonce_len)) {\n                                throw invalid_iv_length(name(), nonce_len);\n                            }\n\n                            if (nonce_len == 0) {\n                                if (m_state.empty()) {\n                                    throw invalid_state(\"CFB requires a non-empty initial nonce\");\n                                }\n                                // No reason to encipher state->keystream_buf, because no change\n                            } else {\n                                m_state.assign(nonce, nonce + nonce_len);\n                                m_keystream.resize(m_state.size());\n                                cipher().encrypt(m_state, m_keystream);\n                                m_keystream_pos = 0;\n                            }\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext) {\n                            const size_t shift = feedback();\n\n                            size_t left = sz;\n\n                            if (m_keystream_pos != 0) {\n                                const size_t take = std::min<size_t>(left, shift - m_keystream_pos);\n\n                                xor_buf(m_keystream.data() + m_keystream_pos, buf, take);\n                                copy_mem(buf, m_keystream.data() + m_keystream_pos, take);\n\n                                m_keystream_pos += take;\n                                left -= take;\n                                buf += take;\n\n                                if (m_keystream_pos == shift) {\n                                    shift_register();\n                                }\n                            }\n\n                            while (left >= shift) {\n                                xor_buf(m_keystream.data(), buf, shift);\n                                copy_mem(buf, m_keystream.data(), shift);\n\n                                left -= shift;\n                                buf += shift;\n                                shift_register();\n                            }\n\n                            if (left > 0) {\n                                xor_buf(m_keystream.data(), buf, left);\n                                copy_mem(buf, m_keystream.data(), left);\n                                m_keystream_pos += left;\n                            }\n\n                            return sz;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = {0};\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding>\n                    struct cfb_encryption_policy<Cipher, FeedbackBits, Padding, cts<1, Cipher, Padding>>\n                        : public cfb_policy<Cipher, Padding> {\n                        typedef typename cfb_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename cfb_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename cfb_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const size_type block_bits = cfb_policy<Cipher, Padding>::block_bits;\n                        constexpr static const size_type block_words = cfb_policy<Cipher, Padding>::block_words;\n                        typedef typename cfb_policy<Cipher, Padding>::block_type block_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = {0};\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = {0};\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = {0};\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding>\n                    struct cfb_encryption_policy<Cipher, FeedbackBits, Padding, cts<2, Cipher, Padding>>\n                        : public cfb_policy<Cipher, Padding> {\n                        typedef typename cfb_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename cfb_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename cfb_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const size_type block_bits = cfb_policy<Cipher, Padding>::block_bits;\n                        constexpr static const size_type block_words = cfb_policy<Cipher, Padding>::block_words;\n                        typedef typename cfb_policy<Cipher, Padding>::block_type block_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = {0};\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = {0};\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = {0};\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding>\n                    struct cfb_encryption_policy<Cipher, FeedbackBits, Padding, cts<3, Cipher, Padding>>\n                        : public cfb_policy<Cipher, Padding> {\n                        typedef typename cfb_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename cfb_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename cfb_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const size_type block_bits = cfb_policy<Cipher, Padding>::block_bits;\n                        constexpr static const size_type block_words = cfb_policy<Cipher, Padding>::block_words;\n                        typedef typename cfb_policy<Cipher, Padding>::block_type block_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = {0};\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = {0};\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = {0};\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding,\n                             typename CiphertextStealingMode>\n                    struct cfb_decryption_policy : public cfb_policy<Cipher, Padding> {};\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding>\n                    struct cfb_decryption_policy<Cipher, FeedbackBits, Padding, cts<0, Cipher, Padding>>\n                        : public cfb_policy<Cipher, Padding> {\n                        typedef typename cfb_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename cfb_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename cfb_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const std::size_t block_bits = cfb_policy<Cipher, Padding>::block_bits;\n                        constexpr static const std::size_t block_words = cfb_policy<Cipher, Padding>::block_words;\n                        typedef typename cfb_policy<Cipher, Padding>::block_type block_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(block, iv);\n\n                            return block;\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext) {\n                            const size_t shift = feedback();\n\n                            size_t left = sz;\n\n                            if (m_keystream_pos != 0) {\n                                const size_t take = std::min<size_t>(left, shift - m_keystream_pos);\n\n                                xor_copy(buf, m_keystream.data() + m_keystream_pos, take);\n\n                                m_keystream_pos += take;\n                                left -= take;\n                                buf += take;\n\n                                if (m_keystream_pos == shift) {\n                                    shift_register();\n                                }\n                            }\n\n                            while (left >= shift) {\n                                xor_copy(buf, m_keystream.data(), shift);\n                                left -= shift;\n                                buf += shift;\n                                shift_register();\n                            }\n\n                            if (left > 0) {\n                                xor_copy(buf, m_keystream.data(), left);\n                                m_keystream_pos += left;\n                            }\n\n                            return sz;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, iv);\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding>\n                    struct cfb_decryption_policy<Cipher, FeedbackBits, Padding, cts<1, Cipher, Padding>>\n                        : public cfb_policy<Cipher, Padding> {\n                        typedef typename cfb_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename cfb_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename cfb_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const std::size_t block_bits = cfb_policy<Cipher, Padding>::block_bits;\n                        constexpr static const std::size_t block_words = cfb_policy<Cipher, Padding>::block_words;\n                        typedef typename cfb_policy<Cipher, Padding>::block_type block_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(block, iv);\n\n                            return block;\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, previous);\n\n                            return result;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, iv);\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding>\n                    struct cfb_decryption_policy<Cipher, FeedbackBits, Padding, cts<2, Cipher, Padding>>\n                        : public cfb_policy<Cipher, Padding> {\n                        typedef typename cfb_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename cfb_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename cfb_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const std::size_t block_bits = cfb_policy<Cipher, Padding>::block_bits;\n                        constexpr static const std::size_t block_words = cfb_policy<Cipher, Padding>::block_words;\n                        typedef typename cfb_policy<Cipher, Padding>::block_type block_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(block, iv);\n\n                            return block;\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, previous);\n\n                            return result;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, iv);\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, std::size_t FeedbackBits, typename Padding>\n                    struct cfb_decryption_policy<Cipher, FeedbackBits, Padding, cts<3, Cipher, Padding>>\n                        : public cfb_policy<Cipher, Padding> {\n                        typedef typename cfb_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename cfb_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename cfb_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const std::size_t block_bits = cfb_policy<Cipher, Padding>::block_bits;\n                        constexpr static const std::size_t block_words = cfb_policy<Cipher, Padding>::block_words;\n                        typedef typename cfb_policy<Cipher, Padding>::block_type block_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type block = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(block, iv);\n\n                            return block;\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, previous);\n\n                            return result;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, iv);\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Policy>\n                    class cipher_feedback {\n                        typedef Policy policy_type;\n\n                    public:\n                        typedef typename policy_type::cipher_type cipher_type;\n                        typedef typename policy_type::padding_type padding_type;\n\n                        typedef typename policy_type::size_type size_type;\n\n                        typedef typename cipher_type::key_type key_type;\n                        typedef typename policy_type::iv_type iv_type;\n\n                        constexpr static const size_type block_bits = policy_type::block_bits;\n                        constexpr static const size_type block_words = policy_type::block_words;\n                        typedef typename cipher_type::block_type block_type;\n\n                        cipher_feedback(const cipher_type &cipher) : cipher(cipher) {\n                        }\n\n                        block_type begin_message(const block_type &plaintext) {\n                            previous = policy_type::begin_message(cipher, plaintext);\n                            return previous;\n                        }\n\n                        block_type process_block(const block_type &plaintext) {\n                            previous = policy_type::process_block(cipher, plaintext, previous);\n                            return previous;\n                        }\n\n                        block_type end_message(const block_type &plaintext) {\n                            return policy_type::end_message(cipher, plaintext);\n                        }\n\n                        inline static size_type required_output_size(size_type inputlen) {\n                            return padding_type::required_output_size(inputlen);\n                        }\n\n                    protected:\n                        block_type previous;\n                        cipher_type cipher;\n                    };\n                }    // namespace detail\n\n                /*!\n                 * @brief Cipher Feedback Mode (CBC).\n                 *\n                 * @tparam Cipher\n                 * @tparam FeedbackBits\n                 * @tparam Padding\n                 * @tparam CiphertextStealingMode\n                 *\n                 * @ingroup block_modes\n                 */\n                template<typename Cipher, std::size_t FeedbackBits, template<typename> class Padding,\n                         template<typename, typename> class CiphertextStealingMode = cts0>\n                struct cipher_feedback {\n                    typedef Cipher cipher_type;\n                    typedef Padding<Cipher> padding_type;\n                    typedef CiphertextStealingMode<Cipher, Padding<Cipher>> ciphertext_stealing_type;\n\n                    constexpr static const std::size_t feedback_bits = FeedbackBits;\n                    BOOST_STATIC_ASSERT(feedback_bits <= cipher_type::block_bits);\n                    BOOST_STATIC_ASSERT(feedback_bits % CHAR_BIT == 0);\n\n                    typedef detail::cfb_encryption_policy<cipher_type, feedback_bits, padding_type,\n                                                          ciphertext_stealing_type>\n                        encryption_policy;\n                    typedef detail::cfb_decryption_policy<cipher_type, feedback_bits, padding_type,\n                                                          ciphertext_stealing_type>\n                        decryption_policy;\n\n                    template<template<typename, typename> class Policy>\n                    struct bind {\n                        typedef detail::cipher_feedback<Policy<cipher_type, padding_type>> type;\n                    };\n                };\n\n                /*!\n                 * @brief\n                 * @tparam Cipher\n                 * @tparam FeedbackBits\n                 * @tparam Padding\n                 * @tparam CiphertextStealingMode\n                 *\n                 * @ingroup block_modes\n                 */\n                template<typename Cipher, std::size_t FeedbackBits, template<typename> class Padding,\n                         template<typename, typename> class CiphertextStealingMode = cts0>\n                using cfb = cipher_feedback<Cipher, FeedbackBits, Padding, CiphertextStealingMode>;\n            }    // namespace modes\n        }        // namespace block\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "d20c533c37944bc4a98e9357b98fc49f8aa8d611", "size": 25938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/modes/cfb.hpp", "max_stars_repo_name": "NilFoundation/crypto3-modes", "max_stars_repo_head_hexsha": "f21ae3185dcd37ccef31523e40ec0203c201da36", "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/modes/cfb.hpp", "max_issues_repo_name": "NilFoundation/crypto3-modes", "max_issues_repo_head_hexsha": "f21ae3185dcd37ccef31523e40ec0203c201da36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T18:20:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T14:26:17.000Z", "max_forks_repo_path": "include/nil/crypto3/modes/cfb.hpp", "max_forks_repo_name": "NilFoundation/crypto3-modes", "max_forks_repo_head_hexsha": "f21ae3185dcd37ccef31523e40ec0203c201da36", "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": 49.9768786127, "max_line_length": 120, "alphanum_fraction": 0.5031999383, "num_tokens": 4163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19171963086360388}}
{"text": "/* VLFeat_SIFT.cpp : Defines the entry point for the console application.\n\nIntegration of the classifier Copyright (c) 2014\nWilfried Hartmann and Michal Havlena, IGP, D-BAUG, ETH Zurich.\n\nWhen using the code either in source or binary form, please cite:\n\"W.Hartmann, M.Havlena, and K.Schindler: Predicting Matchability, CVPR 2014\"\nhttp://www.igp.ethz.ch/photogrammetry/publications/pdf_folder/CVPR2014_Hartmann.pdf\n\nRandom forest classifier code Copyright (c) 2014 Stefan Walk.\nCode made available under the terms of the MIT license (see the LICENSE file).\n*/\n\n/** @internal\n ** @file     sift.c\n ** @author   Andrea Vedaldi\n ** @brief    Scale Invariant Feature Transform (SIFT) - Driver\n **/\n\n/*\nCopyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\nAll rights reserved.\n\nThis file is part of the VLFeat library and is made available under\nthe terms of the BSD license (see the COPYING file).\n*/\n\nextern \"C\" {\n//#include <vl/generic.h>\n//#include <vl/getopt_long.h>\n}\n\n#include <cstddef>\n#include \"random-forest/node-gini.hpp\"\n#include \"random-forest/forest.hpp\"\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <fstream>\n#include <sstream>\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n\n#include <vector>\n#include \"keys2a.h\"\n\nusing namespace std;\n\nint main(int argc, char **argv)\n{\n\tprintf(\"\\nLiblearning\");\n\tfflush(stdout);\n\tliblearning::RandomForest::RandomForest< liblearning::RandomForest::NodeGini<liblearning::RandomForest::AxisAlignedSplitter> > rtrees ;\n\n\n\tstd::ifstream ifs(\"rforest.gz\", std::ios_base::in | std::ios_base::binary) ;\n\t\n  \tchar     err_msg [1024] ;\n\tif (!ifs.is_open()) {\n\t\tsnprintf(err_msg, sizeof(err_msg),\n\t\t\t\t\"Could not open rforests for reading.\") ;\n\t\tfprintf (stderr, \"sift: err: %s\\n\", err_msg) ;\n\t\treturn 1 ;\n\t}\n\t\n\tprintf(\"sift: read classifier from 'rforests'\\n\") ;\n\t\n\tboost::iostreams::filtering_istream ins ;\n\tins.push(boost::iostreams::gzip_decompressor()) ;\n\tins.push(ifs) ;\n\tboost::archive::text_iarchive ias(ins) ;\n\tias >> BOOST_SERIALIZATION_NVP(rtrees) ;\n\n\n\tunsigned char* desc;\n\tkeypt_t* keys;\n\tint numKeys = ReadKeyFile(argv[1], &desc, &keys);\n\n\tprintf(\"\\nRead %d keys\", numKeys);\n\n\tfloat cl_thresh = 0.525;\n\n\n\tprintf(\"\\nLiblearning\");\n\tfflush(stdout);\n\tfor(int i=0; i < numKeys; i++) {\n\t\t//printf(\"\\nKey %d\", i);\n\t\tfflush(stdout);\n\t\tstd::vector<float> siftdesc(128) ;\n\t\tstd::vector<float> results(rtrees.params.n_classes);\n\n\t\tunsigned char* des = desc+128*i;\n\t\tfor (int l = 0; l < 128; ++l)\n\t\t\tsiftdesc [l] = (float)(des[l]) ;\n\n\t\t//printf(\"\\nKey %d copied\", i);\n\t\tfflush(stdout);\n\t\trtrees.evaluate(&siftdesc[0], &results[0]) ;\n\n\t\t//printf(\"\\nKey %d evaluated\", i);\n\t\tfflush(stdout);\n\n\t\tif (results[0] > 1.0 - cl_thresh) {\n\t\t\tcontinue ; \n\t\t} else {\n\t\t\tprintf(\"%d\\n\", i);\n\t\t}\n\t}\n\n\t/* quit */\n\treturn 0 ;\n}\n", "meta": {"hexsha": "4186807870e714e8860bf47269d8aa0c9cbef42f", "size": 2864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/thirdparty/predict_match/ClassifySIFT.cpp", "max_stars_repo_name": "rajvishah/ms-sfm", "max_stars_repo_head_hexsha": "0de1553c471c416ce5ca3d19c65abe36d8e17a07", "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/thirdparty/predict_match/ClassifySIFT.cpp", "max_issues_repo_name": "rajvishah/ms-sfm", "max_issues_repo_head_hexsha": "0de1553c471c416ce5ca3d19c65abe36d8e17a07", "max_issues_repo_licenses": ["MIT"], "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/thirdparty/predict_match/ClassifySIFT.cpp", "max_forks_repo_name": "rajvishah/ms-sfm", "max_forks_repo_head_hexsha": "0de1553c471c416ce5ca3d19c65abe36d8e17a07", "max_forks_repo_licenses": ["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.6896551724, "max_line_length": 136, "alphanum_fraction": 0.6927374302, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.32766828768970435, "lm_q1q2_score": 0.1917190933230424}}
{"text": "// Copyright (c) 2015-2016 Hypha\n\n#include \"hyphaplugins/deepnetvideo/deepnetvideo.h\"\n\n#include <cmath>\n#include <cstdlib>\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <thread>\n#include <vector>\n\n#include <boost/filesystem.hpp>\n#include <boost/foreach.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include <dlib/opencv.h>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/opencv.hpp>\n\n#include <Poco/ClassLibrary.h>\n#include <Poco/DateTime.h>\n#include <Poco/DateTimeFormatter.h>\n#include <Poco/LocalDateTime.h>\n#include <Poco/Timezone.h>\n\n#include <hypha/plugin/hyphaplugin.h>\n#include <hypha/utils/logger.h>\n\nusing namespace hypha::utils;\nusing namespace hypha::plugin;\nusing namespace hypha::plugin::deepnetvideo;\n\nusing namespace cv;\nusing namespace cv::dnn;\n\nusing namespace std;\n\nDeepNetVideo::~DeepNetVideo() {}\n\n/* Find best class for the blob (i. e. class with maximal probability) */\nvoid getMaxClass(dnn::Blob &probBlob, int *classId, double *classProb) {\n  Mat probMat = probBlob.matRefConst().reshape(\n      1, 1);  // reshape the blob to 1x1000 matrix\n  Point classNumber;\n  minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);\n  *classId = classNumber.x;\n}\n\nstd::vector<String> readClassNames(const char *filename = \"synset_words.txt\") {\n  std::vector<String> classNames;\n  std::ifstream fp(filename);\n  if (!fp.is_open()) {\n    std::cerr << \"File with classes labels not found: \" << filename\n              << std::endl;\n    throw std::runtime_error(\"File with classes labels not found\");\n  }\n  std::string name;\n  while (!fp.eof()) {\n    std::getline(fp, name);\n    if (name.length()) classNames.push_back(name.substr(name.find(' ') + 1));\n  }\n  fp.close();\n  return classNames;\n}\n\nvoid DeepNetVideo::doWork() {\n  std::this_thread::sleep_for(std::chrono::seconds(1) / fps);\n  try {\n    std::thread captureT = std::thread([this] { captureCamera(); });\n    if (captureT.joinable()) captureT.join();\n    currentImage_mutex.lock();\n    currentImage = captureMat;\n    currentImage_mutex.unlock();\n  } catch (cv::Exception &e) {\n    Logger::error(e.what());\n  } catch (std::exception e) {\n    Logger::error(e.what());\n  } catch (...) {\n    Logger::error(\"Something terrible happened.\");\n  }\n\n  std::vector<std::string> classes = classify();\n  Logger::info(\"current class: \");\n  for (std::string className : classes) Logger::info(className);\n  // sendMessage(className);\n}\n\nvoid DeepNetVideo::captureCamera() {\n  if (getFilmState() == FILM) {\n    if (filmCounter++ >= 100) setFilmState(IDLE);\n    if (capture_mutex.try_lock()) {\n      try {\n        cv::Mat capt;\n        if (capture.isOpened()) {\n          // read five times to clear buffered old images\n          capture.read(capt);\n          capture.read(capt);\n          capture.read(capt);\n          capture.read(capt);\n          capture.read(capt);\n        }\n        if (captureMat_mutex.try_lock()) {\n          captureMat = capt.clone();\n          captureMat_mutex.unlock();\n        }\n        capture_mutex.unlock();\n      } catch (cv::Exception &e) {\n        Logger::error(\"Could not capture from camera\");\n        Logger::error(e.what());\n      } catch (std::exception &e) {\n        Logger::warning(\"Could not capture from camera\");\n      }\n    }\n  }\n}\n\ncv::Mat DeepNetVideo::rotateMat(cv::Mat mat) {\n  if (mat.rows < 1) return mat;\n  cv::Point2f src_center(mat.cols / 2.0F, mat.rows / 2.0F);\n  cv::Mat rot_mat = cv::getRotationMatrix2D(src_center, 180, 1.0);\n  cv::warpAffine(mat, mat, rot_mat, mat.size());\n  return mat;\n}\n\ncv::Mat DeepNetVideo::fillMat(cv::Mat mat) {\n  if (mat.rows != height)\n    cv::vconcat(mat, cv::Mat(height - mat.rows, mat.cols, mat.type()), mat);\n  if (mat.cols != width)\n    cv::hconcat(mat, cv::Mat(mat.rows, width - mat.cols, mat.type()), mat);\n  return mat;\n}\n\nvoid DeepNetVideo::setup() {\n  if (!device.empty()) {\n    capture.open(std::stoi(device));\n    capture.set(CV_CAP_PROP_FRAME_WIDTH, width);\n    capture.set(CV_CAP_PROP_FRAME_HEIGHT, height);\n    capture.set(CV_CAP_PROP_FPS, fps);\n    captureMat = cv::Mat(height, width, CV_8UC3);\n  }\n  filmCounter = 0;\n  filmState = FILM;\n\n  loadNet();\n}\n\nstd::string DeepNetVideo::communicate(std::string UNUSED(message)) {\n  return \"SUCCESS\";\n}\n\nvoid DeepNetVideo::loadConfig(std::string json) {\n  boost::property_tree::ptree pt;\n  std::stringstream ss(json);\n  boost::property_tree::read_json(ss, pt);\n  if (pt.get_optional<int>(\"fps\")) {\n    fps = pt.get<int>(\"fps\");\n  }\n  if (pt.get_optional<int>(\"width\")) {\n    width = pt.get<int>(\"width\");\n  }\n  if (pt.get_optional<int>(\"height\")) {\n    height = pt.get<int>(\"height\");\n  }\n  if (pt.get_optional<std::string>(\"device\")) {\n    device = pt.get<std::string>(\"device\");\n  }\n\n  if (pt.get_optional<std::string>(\"modelTxt\")) {\n    modelTxt = pt.get<std::string>(\"modelTxt\");\n  }\n\n  if (pt.get_optional<std::string>(\"modelBin\")) {\n    modelBin = pt.get<std::string>(\"modelBin\");\n  }\n\n  if (pt.get_optional<std::string>(\"classNamesFile\")) {\n    classNamesFile = pt.get<std::string>(\"classNamesFile\");\n  }\n}\n\nstd::string DeepNetVideo::getConfig() { return \"{}\"; }\n\nHyphaPlugin *DeepNetVideo::getInstance(std::string id) {\n  DeepNetVideo *instance = new DeepNetVideo();\n  instance->setId(id);\n  return instance;\n}\n\nvoid DeepNetVideo::receiveMessage(std::string message) {\n  try {\n    boost::property_tree::ptree pt;\n    std::stringstream ss(message);\n    boost::property_tree::read_json(ss, pt);\n    if (pt.get_optional<bool>(\"run\")) {\n      if (pt.get<bool>(\"run\")) {\n        setState(FILM);\n      } else {\n        setState(IDLE);\n      }\n    }\n  } catch (std::exception &e) {\n    Logger::error(e.what());\n  }\n}\n\nvoid DeepNetVideo::loadNet() {\n  deserialize(this->modelBin) >> net >> labels;\n  snet.subnet() = net.subnet();\n}\n\n// ----------------------------------------------------------------------------------------\n\ndlib::rectangle make_random_cropping_rect_resnet(const matrix<rgb_pixel> &img,\n                                                 dlib::rand &rnd) {\n  // figure out what rectangle we want to crop from the image\n  double mins = 0.466666666, maxs = 0.875;\n  auto scale = mins + rnd.get_random_double() * (maxs - mins);\n  auto size = scale * std::min(img.nr(), img.nc());\n  dlib::rectangle rect(size, size);\n  // randomly shift the box around\n  point offset(rnd.get_random_32bit_number() % (img.nc() - rect.width()),\n               rnd.get_random_32bit_number() % (img.nr() - rect.height()));\n  return move_rect(rect, offset);\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid randomly_crop_images(const matrix<rgb_pixel> &img,\n                          dlib::array<matrix<rgb_pixel>> &crops,\n                          dlib::rand &rnd, long num_crops) {\n  std::vector<chip_details> dets;\n  for (long i = 0; i < num_crops; ++i) {\n    auto rect = make_random_cropping_rect_resnet(img, rnd);\n    dets.push_back(chip_details(rect, chip_dims(227, 227)));\n  }\n\n  extract_image_chips(img, dets, crops);\n\n  for (auto &&img : crops) {\n    // Also randomly flip the image\n    if (rnd.get_random_double() > 0.5) img = fliplr(img);\n\n    // And then randomly adjust the colors.\n    apply_random_color_offset(img, rnd);\n  }\n}\n\ndlib::matrix<rgb_pixel> MatToMatrix(cv::Mat mat) {\n  dlib::matrix<rgb_pixel> result(mat.rows, mat.cols);\n\n  rgb_pixel *p;\n  for (int i = 0; i < mat.rows; i++) {\n    p = mat.ptr<rgb_pixel>(i);\n    for (int j = 0; j < mat.cols; j++) {\n      result(i, j) = p[j];\n    }\n  }\n\n  return result;\n}\n\n// ----------------------------------------------------------------------------------------\n\nstd::vector<std::string> DeepNetVideo::classify() {\n  std::vector<std::string> tags;\n  Mat cvimg = getCurrentImage();\n  if (cvimg.empty()) {\n    std::cerr << \"can't get image\" << std::endl;\n    throw std::runtime_error(\"can't get image\");\n  }\n  // cv_image<bgr_pixel> cimg(img);\n  dlib::array<matrix<rgb_pixel>> images;\n  matrix<rgb_pixel> mimg, crop;\n  cv::cvtColor(cvimg, cvimg, CV_BGR2RGB);\n  mimg = MatToMatrix(cvimg);\n  const int num_crops = 8;\n  // Grab 16 random crops from the image.  We will run all of them through the\n  // network and average the results.\n  randomly_crop_images(mimg, images, rnd, num_crops);\n  // p(i) == the probability the image contains object of class i.\n  matrix<float, 1, 1000> p =\n      sum_rows(dlib::mat(snet(images.begin(), images.end()))) / num_crops;\n\n  win.set_image(mimg);\n  // Print the 5 most probable labels\n  for (int k = 0; k < 1; ++k) {\n    unsigned long predicted_label = index_of_max(p);\n    cout << p(predicted_label) << \": \" << labels[predicted_label] << endl;\n    p(predicted_label) = 0;\n  }\n  return tags;\n}\n\ncv::Mat DeepNetVideo::getCurrentImage() {\n  setFilmState(FILM);\n  cv::Mat frame;\n  currentImage_mutex.lock();\n  frame = currentImage.clone();\n  currentImage_mutex.unlock();\n  return frame;\n}\n\nDeepNetVideo::State DeepNetVideo::getState() {\n  State state = IDLE;\n  state_mutex.lock();\n  state = currentState;\n  state_mutex.unlock();\n  return state;\n}\n\nvoid DeepNetVideo::setState(State state) {\n  state_mutex.lock();\n  currentState = state;\n  state_mutex.unlock();\n}\n\nDeepNetVideo::State DeepNetVideo::getFilmState() {\n  State state = IDLE;\n  state_mutex.lock();\n  state = filmState;\n  state_mutex.unlock();\n  return state;\n}\n\nvoid DeepNetVideo::setFilmState(State state) {\n  state_mutex.lock();\n  if (filmState == IDLE && state == FILM) {\n    filmState = FILM;\n    if (!device.empty()) {\n      capture.open(std::stoi(device));\n      capture.set(CV_CAP_PROP_FRAME_WIDTH, width);\n      capture.set(CV_CAP_PROP_FRAME_HEIGHT, height);\n      capture.set(CV_CAP_PROP_FPS, fps);\n      cameras++;\n    }\n  } else if (filmState == FILM && state == IDLE) {\n    filmState = IDLE;\n    if (!device.empty()) {\n      capture.release();\n    }\n    cameras = 0;\n  }\n  state_mutex.unlock();\n}\n\nPOCO_BEGIN_MANIFEST(HyphaPlugin)\nPOCO_EXPORT_CLASS(DeepNetVideo)\nPOCO_END_MANIFEST\n", "meta": {"hexsha": "3cc56bf3287b00c9261fbea80a9f7b9177dab509", "size": 10096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/deepnetvideo/source/deepnetvideo.cpp", "max_stars_repo_name": "hyphaproject/hyphaplugins", "max_stars_repo_head_hexsha": "b41b396392c5546e3c2802bfc34213c5da04fdf4", "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/deepnetvideo/source/deepnetvideo.cpp", "max_issues_repo_name": "hyphaproject/hyphaplugins", "max_issues_repo_head_hexsha": "b41b396392c5546e3c2802bfc34213c5da04fdf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-18T10:51:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-18T10:51:07.000Z", "max_forks_repo_path": "source/deepnetvideo/source/deepnetvideo.cpp", "max_forks_repo_name": "hyphaproject/hyphaplugins", "max_forks_repo_head_hexsha": "b41b396392c5546e3c2802bfc34213c5da04fdf4", "max_forks_repo_licenses": ["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.2801120448, "max_line_length": 91, "alphanum_fraction": 0.6303486529, "num_tokens": 2681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.19170383054884158}}
{"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_OPERATOR_FUNCTIONS_SIMD_VMX_ALTIVEC_MULTIPLIES_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_OPERATOR_FUNCTIONS_SIMD_VMX_ALTIVEC_MULTIPLIES_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_VMX_SUPPORT\n\n#include <boost/simd/toolbox/operator/functions/multiplies.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n#include <boost/dispatch/meta/upgrade.hpp>\n#include <boost/simd/include/constants/digits.hpp>\n#include <boost/simd/include/constants/mzero.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::multiplies_, boost::simd::tag::altivec_, (A0)\n                            , ((simd_<single_<A0>,boost::simd::tag::altivec_>))\n                              ((simd_<single_<A0>,boost::simd::tag::altivec_>))\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return vec_madd(a0(),a1(), boost::simd::Mzero<A0>()());\n    }\n  };\n\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::multiplies_, boost::simd::tag::altivec_, (A0)\n                            , ((simd_<type16_<A0>,boost::simd::tag::altivec_>))\n                              ((simd_<type16_<A0>,boost::simd::tag::altivec_>))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return vec_mladd(a0(),a1(),Zero<A0>()());\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::multiplies_, boost::simd::tag::altivec_, (A0)\n                            , ((simd_<type8_<A0>,boost::simd::tag::altivec_>))\n                              ((simd_<type8_<A0>,boost::simd::tag::altivec_>))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename dispatch::meta::upgrade<A0>::type uptype;\n      uptype l = vec_mule(a0(),a1());\n      uptype r = vec_mulo(a0(),a1());\n      return vec_mergel(vec_pack(l(),l()),vec_pack(r(),r()));\n    }\n  };\n\n/*\n * TODO : FINISH THIS\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2,int32_t )\n    {\n      static inline type_t Multiply( const type_t& a, const type_t& b, const ttt::boxed<2>&, const true_t&  )\n      {\n        typedef __vu32_4 cast_t;\n        type_t r  = type_t( av_multiply<__vu32_4>::Multiply(cast_t(a),cast_t(b), ttt::boxed<2>(), false_t()) );\n        return vec_sel(r,vec_sub(vec_splat_u32(0), r),vec_cmpgt(vec_splat_u32(0), vec_xor(a, b)));\n      }\n    }\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2,uint32_t )\n    {\n\n      static inline type_t Multiply( const type_t& a, const type_t& b, const ttt::boxed<2>&, const false_t&  )\n      {\n        typedef __vu16_8 short_t;\n        type_t sixteen = type_t(vec_vspltisw (-16));\n        type_t low = vec_mulo (short_t(a),short_t(b));\n        type_t high = vec_msum (short_t(a),short_t(vec_rl(b, sixteen)),vec_splat_u32(0));\n        return vec_add(vec_sl(high, sixteen),low);\n      }\n\n*/\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "fe4706485ae98a910e87ce3520e898cefbfe8717", "size": 3462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/operator/include/boost/simd/toolbox/operator/functions/simd/vmx/altivec/multiplies.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/operator/include/boost/simd/toolbox/operator/functions/simd/vmx/altivec/multiplies.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/operator/include/boost/simd/toolbox/operator/functions/simd/vmx/altivec/multiplies.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": 37.6304347826, "max_line_length": 111, "alphanum_fraction": 0.5918544194, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.19170381822380628}}
{"text": "#include \"forces/qa/QuasiAdiabatic.hpp\"\n#include <Eigen/Core>\n#include <algorithm>\nusing namespace mdk;\nusing namespace mdk::param;\n\nvoid QuasiAdiabatic::bind(Simulation &simulation) {\n    NonlocalForce::bind(simulation);\n\n    stats = &simulation.var<Stats>();\n\n    types = &simulation.data<Types>();\n    chains = &simulation.data<Chains>();\n\n    bb_lj = LennardJones(5.0 * angstrom, 1.0 * eps);\n    bs_lj = LennardJones(6.8 * angstrom, 1.0 * eps);\n\n    auto& params = simulation.data<param::Parameters>();\n    for (auto const& [acids, r]: params.pairwiseMinDist) {\n        auto acid1 = (int8_t)acids.first, acid2 = (int8_t)acids.second;\n        auto sslj = SidechainLJ(1.0 * eps, r);\n        ss_ljs[acid1][acid2] = ss_ljs[acid2][acid1] = sslj;\n    }\n\n    n = h = Vectors(state->n);\n\n    formationMaxDistSq = 0.0;\n    formationMaxDistSq = std::max(formationMaxDistSq, bb_lj.r_min);\n    formationMaxDistSq = std::max(formationMaxDistSq, bs_lj.r_min);\n    for (int8_t acid1 = 0; acid1 < AminoAcid::N; ++acid1) {\n        for (int8_t acid2 = 0; acid2 < AminoAcid::N; ++acid2) {\n            auto ss_r_min = ss_ljs[acid1][acid2].sink_max;\n            formationMaxDistSq = std::max(formationMaxDistSq, ss_r_min);\n        }\n    }\n    formationMaxDistSq = pow(formationMaxDistSq, 2.0);\n\n    installIntoVL();\n}\n\nvoid QuasiAdiabatic::asyncPart(Dynamics &dyn) {\n    computeNH();\n\n    for (auto& cont: pairs) {\n        if (cont.status == QAContact::Status::REMOVED)\n            continue;\n\n        double stage;\n        if (cont.status == QAContact::Status::FORMING) {\n            stage = std::min((state->t - cont.t0) / formationTime, 1.0);\n        }\n        else {\n            stage = std::max(1.0 - (state->t - cont.t0) / breakingTime, 0.0);\n        }\n\n        Vector r = state->top(state->r[cont.i2] - state->r[cont.i1]);\n        auto norm = r.norm();\n        auto unit = r / norm;\n        double r_min;\n\n        if (stage > 0.0) {\n            if (cont.type == Stats::Type::BB) {\n                bb_lj.computeF(unit, norm, dyn.V, dyn.F[cont.i1],\n                    dyn.F[cont.i2]);\n                r_min = bb_lj.r_min;\n            }\n            else if (cont.type != Stats::Type::SS) {\n                bs_lj.computeF(unit, norm, dyn.V, dyn.F[cont.i1],\n                    dyn.F[cont.i2]);\n                r_min = bs_lj.r_min;\n            }\n            else {\n                auto const& ss_lj = ss_ljs[(*types)[cont.i1]][(*types)[cont.i2]];\n                ss_lj.computeF(unit, norm, dyn.V, dyn.F[cont.i1], dyn.F[cont.i2]);\n                r_min = ss_lj.sink_max;\n            }\n\n            if (cont.status == QAContact::Status::FORMING &&\n                norm > breakingTolerance * pow(2.0, -1.0/6.0) * r_min) {\n\n                cont.status = QAContact::Status::BREAKING;\n                cont.t0 = state->t;\n            }\n        }\n\n        if (cont.status == QAContact::Status::BREAKING && stage == 0.0) {\n            cont.status = QAContact::Status::REMOVED;\n            freePairs.emplace_back((QAFreePair) {\n                .i1 = cont.i1, .i2 = cont.i2,\n                .status = QAFreePair::Status::FREE\n            });\n        }\n    }\n}\n\nvl::Spec QuasiAdiabatic::spec() const {\n    double maxCutoff = 0.0;\n    maxCutoff = std::max(maxCutoff, bb_lj.cutoff());\n    maxCutoff = std::max(maxCutoff, bs_lj.cutoff());\n\n    for (int8_t acid1 = 0; acid1 < AminoAcid::N; ++acid1) {\n        for (int8_t acid2 = 0; acid2 < AminoAcid::N; ++acid2) {\n            maxCutoff = std::max(maxCutoff, ss_ljs[acid1][acid2].cutoff());\n        }\n    }\n\n    return (vl::Spec) {\n        .cutoffSq = pow(maxCutoff, 2.0),\n        .minBondSep = 3,\n    };\n}\n\nstatic bool operator<(QAContact const& p1, std::pair<int, int> const& p2) {\n    return std::make_pair(p1.i1, p1.i2) < p2;\n}\n\nstatic bool operator==(QAContact const& p1, std::pair<int, int> const& p2) {\n    return std::make_pair(p1.i1, p1.i2) == p2;\n}\n\nvoid QuasiAdiabatic::vlUpdateHook() {\n    std::swap(oldPairs, pairs);\n    freePairs.clear();\n\n    auto oldPairsIter = oldPairs.begin();\n    auto oldPairsEnd = oldPairs.end();\n\n    for (auto& pair : vl->pairs) {\n        if (chains->isTerminal[pair.first] || chains->isTerminal[pair.second]\n            || !chains->sepByAtLeastN(pair.first, pair.second, 3)) {\n\n            continue;\n        }\n\n        while (oldPairsIter != oldPairsEnd && *oldPairsIter < pair)\n            ++oldPairsIter;\n\n        if (oldPairsIter != oldPairsEnd\n            && oldPairsIter->status != QAContact::Status::REMOVED\n            && *oldPairsIter == pair) {\n\n            pairs.emplace_back(*oldPairsIter);\n        }\n        else {\n            freePairs.emplace_back((QAFreePair) {\n                .i1 = pair.first, .i2 = pair.second,\n                .status = QAFreePair::Status::FREE\n            });\n        }\n    }\n}\n\nbool QuasiAdiabatic::geometryPhase(vl::PairInfo const& p, QADiff &diff) const {\n    Vector h1 = h[p.i1], h2 = h[p.i2];\n    double cos_h1_r12 = h1.dot(p.unit), cos_h2_r12 = h2.dot(p.unit),\n        cos_h1_h2 = h1.dot(h2);\n\n    if (abs(cos_h1_r12) >= hr_abs_min && abs(cos_h2_r12) >= hr_abs_min &&\n        abs(cos_h1_h2) >= hh_abs_min && p.norm <= bb_lj.r_min) {\n\n        diff.cont.type = Stats::Type::BB;\n        return true;\n    }\n\n    Vector n1 = n[p.i1];\n    double cos_n1_r12 = n1.dot(p.unit);\n    if (cos_n1_r12 <= nr_max && abs(cos_h1_r12) >= hr_abs_min &&\n        p.norm <= bs_lj.r_min * formationTolerance) {\n\n        diff.cont.type = Stats::Type::BS;\n        return true;\n    }\n\n    Vector n2 = n[p.i2];\n    double cos_n2_r12 = n2.dot(p.unit);\n    if (cos_n2_r12 <= nr_max && abs(cos_h1_r12) >= hr_abs_min &&\n        p.norm <= bs_lj.r_min * formationTolerance) {\n\n        diff.cont.type = Stats::Type::SB;\n        return true;\n    }\n\n    if (cos_n1_r12 <= nr_max && -cos_n2_r12 <= nr_max &&\n        p.norm <= ss_ljs[(*types)[p.i1]][(*types)[p.i2]].sink_max * formationTolerance) {\n\n        diff.cont.type = Stats::Type::SS;\n        return true;\n    }\n\n    return false;\n}\n\nvoid QuasiAdiabatic::syncPart(Dynamics &dyn) {\n    qaDiffs.clear();\n    for (int i = 0; i < (int)freePairs.size(); ++i) {\n        auto const& p = freePairs[i];\n\n        if (p.status == QAFreePair::Status::TAKEN)\n            continue;\n\n        vl::PairInfo pairInfo;\n        pairInfo.i1 = p.i1;\n        pairInfo.i2 = p.i2;\n\n        auto r = state->top(state->r[p.i1] - state->r[p.i2]);\n        auto r_normsq = r.squaredNorm();\n        if (r_normsq >= formationMaxDistSq)\n            continue;\n\n        pairInfo.norm = sqrt(r_normsq);\n        pairInfo.unit = r / pairInfo.norm;\n\n        QADiff diff;\n        if (!geometryPhase(pairInfo, diff))\n            continue;\n\n        stats->creationDiffs(p.i1, p.i2, diff.cont.type, diff.statDiffs);\n\n        auto stat1 = stats->stats[p.i1] + diff.statDiffs[0];\n        if (!stat1.valid()) continue;\n\n        auto stat2 = stats->stats[p.i2] + diff.statDiffs[1];\n        if (!stat2.valid()) continue;\n\n        diff.oldIdx = i;\n        diff.cont.i1 = p.i1;\n        diff.cont.i2 = p.i2;\n        diff.cont.t0 = state->t;\n        diff.cont.status = QAContact::Status::FORMING;\n\n        qaDiffsMutex.lock();\n        qaDiffs.emplace_back(diff);\n        qaDiffsMutex.unlock();\n    }\n\n    std::sort(qaDiffs.begin(), qaDiffs.end());\n    for (auto const& diff: qaDiffs) {\n        auto& stat1 = stats->stats[diff.cont.i1];\n        auto res1 = stat1 + diff.statDiffs[0];\n        if (!res1.valid()) continue;\n\n        auto& stat2 = stats->stats[diff.cont.i2];\n        auto res2 = stat2 + diff.statDiffs[1];\n        if (!res2.valid()) continue;\n\n        freePairs[diff.oldIdx].status = QAFreePair::Status::TAKEN;\n        stat1 = res1;\n        stat2 = res2;\n        pairs.push_back(diff.cont);\n    }\n}\n\nvoid QuasiAdiabatic::computeNH() {\n    for (int i = 0; i < (int)chains->triples.size(); ++i) {\n        if (!chains->triples[i]) continue;\n\n        auto r0 = state->r[i-1], r1 = state->r[i], r2 = state->r[i+1];\n        auto v0 = r1 - r0, v1 = r2 - r1;\n        n[i] = (v1 - v0).normalized();\n        h[i] = (v1.cross(v0)).normalized();\n    }\n}\n", "meta": {"hexsha": "f8402350be3a7bd47e2684ef5c34832eaf564fdc", "size": 8024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mdk/src/forces/qa/QuasiAdiabatic.cpp", "max_stars_repo_name": "if-pan-zpp/mdk", "max_stars_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "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": "mdk/src/forces/qa/QuasiAdiabatic.cpp", "max_issues_repo_name": "if-pan-zpp/mdk", "max_issues_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mdk/src/forces/qa/QuasiAdiabatic.cpp", "max_forks_repo_name": "if-pan-zpp/mdk", "max_forks_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-19T09:24:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T09:24:34.000Z", "avg_line_length": 30.5095057034, "max_line_length": 89, "alphanum_fraction": 0.5519690927, "num_tokens": 2433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.297469948832931, "lm_q1q2_score": 0.1916376094633899}}
{"text": "// Copyright (c) 2014-2020 The Virie Project\n// Copyright (c) 2012-2013 The Cryptonote 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 <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <fstream>\n\n#include \"include_base_utils.h\"\n#include \"account.h\"\n#include \"warnings.h\"\n#include \"crypto/crypto.h\"\n#include \"currency_core/currency_format_utils.h\"\n#include \"common/mnemonic-encoding.h\"\n#include \"string_tools.h\"\n\nusing namespace std;\n\nDISABLE_VS_WARNINGS(4244 4345)\n\nnamespace currency\n{\n\n  //-----------------------------------------------------------------\n  account_base::account_base()\n  {\n    set_null();\n  }\n  //-----------------------------------------------------------------\n  void account_base::set_null()\n  {\n    m_seed.clear();\n    m_keys = account_keys();\n    m_creation_timestamp = 0;\n  }\n  //-----------------------------------------------------------------\n  void account_base::generate()\n  {\n    //generate_keys(m_keys.m_account_address.m_spend_public_key, m_keys.m_spend_secret_key);\n    generate_brain_keys(m_keys.m_account_address.m_spend_public_key, m_keys.m_spend_secret_key, m_seed);\n    dependent_key(m_keys.m_spend_secret_key, m_keys.m_view_secret_key);\n    if (!crypto::secret_key_to_public_key(m_keys.m_view_secret_key, m_keys.m_account_address.m_view_public_key))\n      throw std::runtime_error(\"Failed to create public view key\");\n\n    m_creation_timestamp = time(NULL);\n  }\n  //-----------------------------------------------------------------\n  const account_keys& account_base::get_keys() const\n  {\n    return m_keys;\n  }\n  //-----------------------------------------------------------------\n  std::string account_base::get_restore_data() const\n  {\n    return m_seed;\n  }\n  //-----------------------------------------------------------------\n  std::string account_base::get_restore_braindata() const \n  {\n    std::string restore_string;\n    if (!m_seed.empty())\n    {\n      std::string restore_buff = get_restore_data();\n      restore_string = tools::mnemonic_encoding::binary2text(restore_buff);\n\n      uint64_t date_offset = m_creation_timestamp > WALLET_BRAIN_DATE_OFFSET ? m_creation_timestamp - WALLET_BRAIN_DATE_OFFSET : 0;\n      uint64_t weeks_count = date_offset / WALLET_BRAIN_DATE_QUANTUM;\n      CHECK_AND_ASSERT_THROW_MES(weeks_count < std::numeric_limits<uint32_t>::max(), \"internal error: unable to converto to uint32, val = \" << weeks_count);\n      uint32_t weeks_count_32 = static_cast<uint32_t>(weeks_count);\n\n      restore_string.append(tools::mnemonic_encoding::word_by_num(weeks_count_32));\n    }\n    else\n    {\n      if (m_keys.is_watch_only())\n      {\n        return std::string(\"\");\n      }\n      crypto::secret_key spend_key = get_keys().m_spend_secret_key;\n      restore_string = epee::string_tools::pod_to_hex(spend_key);\n\n      time_t timestamp = get_createtime();\n      std::string date;\n      epee::misc_utils::get_restore_str_from_time(date, timestamp);\n\n      restore_string.append(\" \" + date);\n    }\n\n    return restore_string;\n  }\n  //-----------------------------------------------------------------\n  bool account_base::restore_keys(const std::string& restore_data)\n  {\n    //CHECK_AND_ASSERT_MES(restore_data.size() == ACCOUNT_RESTORE_DATA_SIZE, false, \"wrong restore data size\");\n    if (restore_data.size() == BRAINWALLET_DEFAULT_SEED_SIZE)\n    {\n      crypto::keys_from_default((unsigned char*)restore_data.data(), m_keys.m_account_address.m_spend_public_key, m_keys.m_spend_secret_key);\n    }\n    else if(restore_data.size() == BRAINWALLET_SHORT_SEED_SIZE)\n    {\n      crypto::keys_from_short((unsigned char*)restore_data.data(), m_keys.m_account_address.m_spend_public_key, m_keys.m_spend_secret_key);\n    }\n    else \n    {\n      LOG_ERROR(\"wrong restore data size=\" << restore_data.size());\n      return false;\n    }\n    m_seed = restore_data;\n    crypto::dependent_key(m_keys.m_spend_secret_key, m_keys.m_view_secret_key);\n    bool r = crypto::secret_key_to_public_key(m_keys.m_view_secret_key, m_keys.m_account_address.m_view_public_key);\n    CHECK_AND_ASSERT_MES(r, false, \"failed to secret_key_to_public_key for view key\");\n    return true;\n  }\n  //-----------------------------------------------------------------\n  bool account_base::restore_keys_from_braindata(const std::string& restore_data)\n  {\n    set_createtime(0);\n    std::stringstream restore_phrase_stream(restore_data);\n    size_t words_count = std::distance(std::istream_iterator<std::string>(restore_phrase_stream), std::istream_iterator<std::string>());\n\n    if (words_count == SPEND_KEY_WORDS_COUNT_WITH_TS)\n    {\n      time_t restore_create_time;\n      std::istringstream date(restore_data.substr(1 + (restore_data.find_last_of(' '))));\n      if (epee::misc_utils::get_restore_time_from_str(restore_create_time, date.str()))\n      {\n        set_createtime(restore_create_time);\n      }\n    }\n    else if (words_count == PHRASE_WORDS_COUNT_WITH_TS)\n    {\n      auto index = restore_data.find_last_of(' ');\n      std::string last_word = restore_data.substr(++index);\n\n      uint64_t count_of_weeks = tools::mnemonic_encoding::num_by_word(last_word);\n      time_t timestamp = count_of_weeks * WALLET_BRAIN_DATE_QUANTUM + WALLET_BRAIN_DATE_OFFSET;\n\n      if (timestamp < time(nullptr) && timestamp > WALLET_BRAIN_DATE_OFFSET)\n      {\n        set_createtime(timestamp);\n      }\n    }\n\n    if (words_count == SPEND_KEY_WORDS_COUNT || words_count == SPEND_KEY_WORDS_COUNT_WITH_TS)\n    {\n      return restore_keys_from_spend_key(restore_data);      \n    }\n    else\n    {\n      string::size_type start = 0;\n      string::size_type last = restore_data.find_first_of(\" \");\n      uint32_t copied_words_count = 0;\n      std::string restore_string;\n      while (start - 1 != restore_data.size() && copied_words_count < PHRASE_WORDS_COUNT)\n      {\n        if (last > start)\n        {\n          restore_string.append(restore_data.substr(start, last - start) + \" \");\n          copied_words_count++;\n        }\n\n        start = ++last;\n        last = restore_data.find_first_of(\" \", last);\n        if (last == std::string::npos)\n        {\n          last = restore_data.size();\n        }\n      }\n      std::string restore_buff = tools::mnemonic_encoding::text2binary(restore_string);\n      if (!restore_buff.size())\n        return false;\n      return restore_keys(restore_buff);\n    }\n    \n    return false;\n  }\n  //-----------------------------------------------------------------\n  bool account_base::restore_keys_from_view_key(const std::string& restore_data)\n  {\n    m_seed.clear();\n    m_keys.m_spend_secret_key = currency::null_skey;\n    bool r = epee::string_tools::hex_to_pod(restore_data, m_keys.m_view_secret_key);\n    CHECK_AND_ASSERT_MES(r, false, \"failed to restore secret_view_key\");\n    r = crypto::secret_key_to_public_key(m_keys.m_view_secret_key, m_keys.m_account_address.m_view_public_key);\n    CHECK_AND_ASSERT_MES(r, false, \"failed to secret_key_to_public_key for view key\");\n    set_createtime(0);\n    return true;\n  }\n  //-----------------------------------------------------------------\n  bool account_base::restore_keys_from_spend_key(const std::string& restore_data)\n  {\n    m_seed.clear();\n    std::string spend_key = restore_data.substr(0, restore_data.find(\" \"));\n\n    bool r = epee::string_tools::hex_to_pod(spend_key, m_keys.m_spend_secret_key);\n    CHECK_AND_ASSERT_MES(r, false, \"failed to restore spend_secret_key\");\n    r = crypto::secret_key_to_public_key(m_keys.m_spend_secret_key, m_keys.m_account_address.m_spend_public_key);\n    CHECK_AND_ASSERT_MES(r, false, \"failed to secret_spend_key_to_public_key for view key\");\n    try\n    {\n      dependent_key(m_keys.m_spend_secret_key, m_keys.m_view_secret_key);\n    }\n    catch (...)\n    {\n      ASSERT_MES_AND_THROW(\"failed to depend spend key to view key\");\n      return false;\n    }\n    r = crypto::secret_key_to_public_key(m_keys.m_view_secret_key, m_keys.m_account_address.m_view_public_key);\n    CHECK_AND_ASSERT_MES(r, false, \"failed to secret_key_to_public_view_key for view key\");\n    return true;\n  }\n  //-----------------------------------------------------------------\n  std::string account_base::get_public_address_str()\n  {\n    //TODO: change this code into base 58\n    return get_account_address_as_str(m_keys.m_account_address);\n  }\n  //-----------------------------------------------------------------\n  void account_base::make_account_watch_only()\n  {\n    m_keys.m_spend_secret_key = currency::null_skey;\n    m_seed.clear();\n  }\n  //-----------------------------------------------------------------\n  std::string transform_addr_to_str(const account_public_address& addr)\n  {\n    return get_account_address_as_str(addr);\n  }\n\n  account_public_address transform_str_to_addr(const std::string& str)\n  {\n    account_public_address ad = AUTO_VAL_INIT(ad);\n    if (!get_account_address_from_str(ad, str))\n    {\n      LOG_ERROR(\"cannot parse address from string: \" << str);\n    }\n    return ad;\n  }\n}", "meta": {"hexsha": "de307182cc545ab6ef029836c477778a92a8c59b", "size": 9075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/currency_core/account.cpp", "max_stars_repo_name": "Virie/Virie", "max_stars_repo_head_hexsha": "fc5ad5816678b06b88d08a6842e43d4205915b39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T13:26:43.000Z", "max_issues_repo_path": "src/currency_core/account.cpp", "max_issues_repo_name": "Virie/Virie", "max_issues_repo_head_hexsha": "fc5ad5816678b06b88d08a6842e43d4205915b39", "max_issues_repo_licenses": ["MIT"], "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/currency_core/account.cpp", "max_forks_repo_name": "Virie/Virie", "max_forks_repo_head_hexsha": "fc5ad5816678b06b88d08a6842e43d4205915b39", "max_forks_repo_licenses": ["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.8125, "max_line_length": 156, "alphanum_fraction": 0.6438567493, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19139965954844793}}
{"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: falcon_driver.cpp\n * \n * Description: This file contains the ROS node that interfaces with the \n * Novint Falcon 3D Controller\n * \n * Log\n * ----\n * 2015-02-09 File created by Hazen Eckert\n *\n */\n \n// ROS includes\n#include \"ros/ros.h\"\n#include \"geometry_msgs/Vector3.h\"\n\n#include \"novint_falcon_driver/NovintFalcon.h\"\n\n#include <string>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n/*\nProcess:\n- get configuration parameters\n- setup flacon class\n- \n*/\nusing namespace Eigen;\nVector3d force;\n\nvoid force_callback(const geometry_msgs::Vector3::ConstPtr& msg)\n{\n\tforce(0) = msg->x;\n\tforce(1) = msg->y;\n\tforce(2) = msg->z;\n}\n\n\n int main(int argc, char **argv)\n{\n\t// ROS Initalization\n\tros::init(argc, argv, \"falcon_driver\");\n\tros::NodeHandle n;\n\tros::NodeHandle private_n(\"~\");\n\n\t// ROS Parameters\n\tstd::string firmware;\n\tbool force_firmware, skip_checksum;\n\tint device_index;\n\n\tprivate_n.param<std::string>(\"firmware\", firmware, \"nvent_firmware\");\n\n\tprivate_n.param<bool>(\"force_firmware\", force_firmware, false);\n\n\tprivate_n.param<bool>(\"skip_checksum\", skip_checksum, true);\n\n\tprivate_n.param<int>(\"device_index\", device_index, 0);\n\n\t// ROS Subscribers\n\n\tros::Subscriber force_sub = n.subscribe(\"force\", 10, force_callback);\n\n\t// ROS Publishers\n\n\tros::Publisher position_pub = n.advertise<geometry_msgs::Vector3>(\"position\", 10);\n\n\t// Falcon Initialization\n\tNovintFalcon falcon;\n\tif(!falcon.initialize( firmware, force_firmware, skip_checksum, device_index ))\n\t{\n\t\tROS_FATAL(\"Unable to initialize the falcon device. Exiting...\");\n\t\treturn 1;\n\t}\n\n\twhile(!falcon.calibrate() && ros::ok());\n\n\t// ROS loop\n\n\twhile(ros::ok())\n\t{\n\t\tif (!falcon.update())\n\t\t\tcontinue;\n\n\t\tros::spinOnce();\n\n\t\tVector3d position = falcon.getPosition();\n\n\t\tgeometry_msgs::Vector3 msg;\n\t\tmsg.x = position(0);\n\t\tmsg.y = position(1);\n\t\tmsg.z = position(2);\n\n\t\tposition_pub.publish(msg);\n\n\t\tif(force_sub.getNumPublishers() != 1)\n\t\t\tfalcon.setForce(Vector3d(0,0,0));\n\t\telse\n\t\t\tfalcon.setForce(force);\n\n\t}\n\n}", "meta": {"hexsha": "1762b81db967f63061cf5134b3e9ba58d17ed24b", "size": 3700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/novint_falcon_driver/src/falcon_driver.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/novint_falcon_driver/src/falcon_driver.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/novint_falcon_driver/src/falcon_driver.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": 27.6119402985, "max_line_length": 87, "alphanum_fraction": 0.7237837838, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19139965954844793}}
{"text": "// chapter 10\n\n\n#include <iostream>\n\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/type_traits/add_pointer.hpp>\n#include <boost/type_traits/is_function.hpp>\n#include <boost/type_traits/is_const.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/apply.hpp>\n\n#include <boost/mpl/vector_c.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/not_equal_to.hpp>\n#include <boost/mpl/greater.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/or.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/multiplies.hpp>\n\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/next.hpp>\n#include <boost/mpl/prior.hpp>\n#include <boost/mpl/begin.hpp>\n#include <boost/mpl/end.hpp>\n#include <boost/mpl/advance.hpp>\n#include <boost/mpl/push_front.hpp>\n#include <boost/mpl/pop_front.hpp>\n#include <boost/mpl/insert.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/mpl/max_element.hpp>\n#include <boost/mpl/min_element.hpp>\n#include <boost/mpl/sizeof.hpp>\n#include <boost/mpl/less.hpp>\n#include <boost/mpl/copy.hpp>\n#include <boost/mpl/print.hpp>\n#include <boost/mpl/for_each.hpp>\n#include <boost/mpl/bind.hpp>\n#include <boost/bind.hpp>\n#include <boost/foreach.hpp>\n\n#pragma warning(disable: 4819)\n#include <boost/spirit/core.hpp>\n#include <boost/spirit/attribute.hpp>\n\n\n\n// using namespace boost::mpl::placeholders;\n//namespace mpl = boost::mpl;\n// using namespace boost::lambda;\n\n#include <iterator>\n#include <utility>\n#include <list>\n#include <map>\n#include <vector>\n#include <string>\n#include <assert.h>\n#include <algorithm>\n\n//using namespace boost;\n//using namespace boost::mpl;\n\nusing namespace boost::spirit;\nusing namespace phoenix;\n\nstruct vars : boost::spirit::closure<vars, int>\n{\n\tmember1 value;\n};\n\nstruct calculator\n\t: public grammar<calculator, vars::context_t>\n{\n\ttemplate<class Tokenizer>\n\tstruct definition\n\t{\n\t\trule<Tokenizer, vars::context_t>\n\t\t\texpression, term, factor, group, integer;\n\n\t\trule<Tokenizer> top;\n\n\t\tdefinition(calculator const &self)\n\t\t{\n\t\t\ttop = expression[self.value = arg1];\n\n\t\t\tgroup = '(' >> expression[group.value = arg1] >> ')';\n\n\t\t\tfactor = integer[factor.value = arg1] \n\t\t\t\t| group[factor.value = arg1]\n\t\t\t\t;\n\n\t\t\tterm = factor[term.value = arg1]\n\t\t\t>> *( ('*' >> factor[term.value *= arg1])\n\t\t\t\t| ('/' >> factor[term.value /= arg1])\n\t\t\t\t)\n\t\t\t\t;\n\n\t\t\texpression = term[expression.value = arg1]\n\t\t\t>> *( ('+' >> term[expression.value += arg1])\n\t\t\t\t| ('-' >> term[expression.value -= arg1])\n\t\t\t\t)\n\t\t\t\t;\n\n\t\t\tinteger = int_p[integer.value = arg1];\n\t\t}\n\n\t\trule<Tokenizer> const &start() { return top; }\n\n\t};\n};\n\n\nvoid main()\n{\n\tcalculator calc;\n\n\tstd::string str;\n\twhile (std::getline(std::cin, str))\n\t{\n\t\tint n= 0;\n// \t\tparse(str.c_str(), calc[var(n) = arg1], space_p);\n// \t\tstd::cout << \"result = \" << n << std::endl;\n\n\t}\n\n}\n", "meta": {"hexsha": "9af66560a135d3c9842986042f2b4eda7007e289", "size": 3249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ex10/Spirits/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": "Ex10/Spirits/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": "Ex10/Spirits/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": 23.0425531915, "max_line_length": 56, "alphanum_fraction": 0.701446599, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19139965954844793}}
{"text": "// Copyright 2020-2022 OpenDR European 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#ifndef GAUSSIAN_MIXTURE_MODEL_H\n#define GAUSSIAN_MIXTURE_MODEL_H\n\n#include <eigen_conversions/eigen_msg.h>\n#include <ros/assert.h>\n#include <ros/ros.h>\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <tf_conversions/tf_eigen.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <boost/asio.hpp>\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/system/error_code.hpp>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include \"tf/transform_datatypes.h\"\n\n#include <mobile_manipulation_rl/utils.hpp>\n\nclass GaussianMixtureModel {\npublic:\n  // GaussianMixtureModel();\n  ~GaussianMixtureModel();\n  GaussianMixtureModel(double max_speed_gripper_rot, double max_speed_base_rot);\n\n  void adaptModel(tf::Transform obj_origin_goal, tf::Vector3 gmm_base_offset);\n  bool loadFromFile(std::string &filename);\n  void integrateModel(double current_time, double dt, Eigen::VectorXf *current_pose, Eigen::VectorXf *current_speed,\n                      const double &min_velocity, const double &max_velocity, bool do_update);\n\n  int getNrModes() const { return _nr_modes; };\n  std::string getType() const { return _type; };\n  void setType(std::string type) { _type = type; };\n  double getkP() const { return _kP; };\n  double getkV() const { return _kV; };\n  std::vector<double> getPriors() const { return _Priors; };\n  std::vector<Eigen::VectorXf> getMu() const { return _MuEigen; };\n  std::vector<Eigen::MatrixXf> getSigma() const { return _Sigma; };\n  tf::StampedTransform getGoalState() const { return _goalState; };\n  tf::Transform getStartState() const { return _startState; };\n  tf::Transform getGraspPose() const { return _related_object_grasp_pose; };\n  tf::Transform getRelatedObjPose() const { return _related_object_pose; };\n  tf::Transform getLastMuEigenBckGripper() const;\n  std::string getObjectName() const { return _related_object_name; };\n\n  double gmm_time_offset_;\n\nprotected:\n  int _nr_modes;\n  std::string _type;\n  double _kP;\n  double _kV;\n  double _motion_duration;\n  double _max_speed_gripper_rot;\n  double _max_speed_base_rot;\n  std::vector<double> _Priors;\n  std::vector<std::vector<double>> _Mu;\n  std::vector<Eigen::VectorXf> _MuEigen;\n  std::vector<Eigen::VectorXf> _MuEigenBck;\n  std::vector<Eigen::MatrixXf> _Sigma;\n  std::vector<Eigen::MatrixXf> _SigmaBck;\n  tf::StampedTransform _goalState;\n  tf::Transform _startState;\n  tf::Transform _related_object_pose;\n  tf::Transform _related_object_grasp_pose;\n  std::string _related_object_name;\n\n  template<typename T> bool parseVector(std::ifstream &is, std::vector<T> &pts, const std::string &name);\n  double gaussPDF(double &current_time, int mode_nr);\n  void plotEllipses(Eigen::VectorXf &curr_pose, Eigen::VectorXf &curr_speed, double dt);\n  void clearMarkers(int nrPoints);\n  template<typename T1, typename T2> T1 extract(const T2 &full, const T1 &ind);\n};\n\n#endif  // GAUSSIAN_MIXTURE_MODEL_H\n", "meta": {"hexsha": "6c4656a671e16feb113f0f30ebdfb67ace4d569d", "size": 3569, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/opendr/control/mobile_manipulation/include/gripper_planner/gaussian_mixture_model.hpp", "max_stars_repo_name": "ad-daniel/opendr", "max_stars_repo_head_hexsha": "cc71138ae22ec39b186960ff98c74bc2cdca3623", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 217.0, "max_stars_repo_stars_event_min_datetime": "2020-04-10T16:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:39:04.000Z", "max_issues_repo_path": "src/opendr/control/mobile_manipulation/include/gripper_planner/gaussian_mixture_model.hpp", "max_issues_repo_name": "ad-daniel/opendr", "max_issues_repo_head_hexsha": "cc71138ae22ec39b186960ff98c74bc2cdca3623", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-12-16T13:23:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:36:29.000Z", "max_forks_repo_path": "src/opendr/control/mobile_manipulation/include/gripper_planner/gaussian_mixture_model.hpp", "max_forks_repo_name": "ad-daniel/opendr", "max_forks_repo_head_hexsha": "cc71138ae22ec39b186960ff98c74bc2cdca3623", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2021-12-16T09:26:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T15:19:18.000Z", "avg_line_length": 37.5684210526, "max_line_length": 116, "alphanum_fraction": 0.7503502382, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.19139965591472596}}
{"text": "/*\n * Analysis.cpp\n *\n *  Created on: 12 Jul 2010\n *      Author: kreczko\n */\n\n#include \"Analysis.h\"\n#include \"TROOT.h\"\n#include <iostream>\n#include <boost/scoped_ptr.hpp>\n#include <boost/array.hpp>\n#include \"../interface/EventCounter.h\"\n#include <cmath>\n#include <math.h>\n#include \"../interface/Printers/EventTablePrinter.h\"\n#include \"../interface/ReconstructionModules/ChiSquaredBasedTopPairReconstruction.h\"\n#include \"../interface/LumiReWeighting.h\"\n#include \"../interface/GlobalVariables.h\"\n#include \"../interface/BTagWeight.h\"\n\nusing namespace reweight;\nusing namespace BAT;\nusing namespace std;\n\nvoid Analysis::analyse() {\n\tcreateHistograms();\n\tcout << \"detected samples:\" << endl;\n\tfor (unsigned int sample = 0; sample < DataType::NUMBER_OF_DATA_TYPES; ++sample) {\n\t\tif (eventReader->getSeenDatatypes()[sample])\n\t\t\tcout << DataType::names[sample] << endl;\n\t}\n\twhile (eventReader->hasNextEvent()) {\n\t\tinitiateEvent();\n\t\tprintNumberOfProccessedEventsEvery(Globals::printEveryXEvents);\n\t\tinspectEvents();\n\t\tconst JetCollection jets(currentEvent->Jets());\n\t\tunsigned int numberOfJets(jets.size());\n\t\tunsigned int numberOfBJets(0);\n\t\tfor (unsigned int index = 0; index < numberOfJets; ++index) {\n\t\t\tconst JetPointer jet(currentEvent->Jets().at(index));\n\t\t\tif (jet->isBJet(BtagAlgorithm::CombinedSecondaryVertex, BtagAlgorithm::MEDIUM))\n\t\t\t\t++numberOfBJets;\n\t\t}\n\t\thistMan->setCurrentBJetBin(numberOfBJets);\n\t\thistMan->setCurrentJetBin(numberOfJets);\n\n\t\tvector<double> bjetWeights;\n\t\tif (currentEvent->isRealData()) {\n\t\t\tfor (unsigned int index = 0; index <= numberOfBJets; ++index) {\n\t\t\t\tif (index == numberOfBJets)\n\t\t\t\t\tbjetWeights.push_back(1.);\n\t\t\t\telse\n\t\t\t\t\tbjetWeights.push_back(0);\n\t\t\t}\n\t\t} else\n\t\t\tbjetWeights = BjetWeights(jets, numberOfBJets);\n\n\t\teventcountAnalyser->analyse(currentEvent);\n//\t\tmttbarAnalyser->analyse(currentEvent);\n\t\tttbar_plus_X_analyser_->analyse(currentEvent);\n\t\tdiffVariablesAnalyser->analyse(currentEvent);\n//\t\tbinningAnalyser->analyse(currentEvent);\n\t}\n}\n\nvoid Analysis::printNumberOfProccessedEventsEvery(unsigned long printEvery) {\n\tunsigned long eventIndex = eventReader->getNumberOfProccessedEvents();\n\tif (eventIndex % printEvery == 0 || eventIndex == 1) {\n\t\tcout << \"Analysing event no \" << eventIndex << \", sample: \" << DataType::names[currentEvent->getDataType()]\n\t\t\t\t<< endl;\n\t\tcout << \"File: \" << eventReader->getCurrentFile() << endl;\n\t}\n\n}\n\nvoid Analysis::initiateEvent() {\n\tcurrentEvent = eventReader->getNextEvent();\n\tweight = 1.;\n\thistMan->setCurrentDataType(currentEvent->getDataType());\n\thistMan->setCurrentJetBin(currentEvent->Jets().size());\n\thistMan->setCurrentBJetBin(0);\n\n\tif (!currentEvent->isRealData()) {\n\t\tweight = weights->getWeight(currentEvent->getDataType());\n\t\t//TODO: fix this dirty little thing\n\t\tpileUpWeight = weights->reweightPileUp(currentEvent->getTrueNumberOfVertices().at(1));\n\t\tweight *= pileUpWeight;\n\t\tif (Globals::pdfWeightNumber != 0) {\n\t\t\ttry {\n\t\t\t\tdouble pdf_weight(currentEvent->PDFWeights().at(Globals::pdfWeightNumber) / currentEvent->PDFWeights().at(0));\n\t\t\t\tweight *= pdf_weight;\n\n\t\t\t\thistMan->setCurrentHistogramFolder(\"\");\n\t\t\t\thistMan->H1D(\"PDFweights\")->Fill(pdf_weight);\n\t\t\t} catch (exception& e) {\n\t\t\t\tcout << \"PDF weight assigning exception: \" << e.what() << endl;\n\t\t\t}\n\t\t}\n\t}\n\n\t//top pt weight\n\tif(Globals::applyTopPtReweighting == true && currentEvent->getDataType() == DataType::TTJets){\n\n\tdouble topPtweight = 1.;\n\ttopPtweight = weights->reweightTopPt(currentEvent);\n\n\tweight *= topPtweight;\n\t}\n\n\tcurrentEvent->setEventWeight(weight);\n\tcurrentEvent->setPileUpWeight(pileUpWeight);\n\n}\n\nvoid Analysis::inspectEvents() {\n\tstd::vector<InterestingEvent> eventsToInspect;\n\n\tfor (unsigned int index = 0; index < eventsToInspect.size(); ++index) {\n\t\tif ((currentEvent->runnumber() == eventsToInspect.at(index).candidate->runnumber()\n\t\t\t\t&& currentEvent->eventnumber() == eventsToInspect.at(index).candidate->eventnumber())) {\n\t\t\tcout << \"file: \" << eventReader->getCurrentFile() << endl;\n\t\t\tcurrentEvent->inspect();\n\t\t}\n\t}\n\n}\n\nvoid Analysis::printInterestingEvents() {\n\tcout << \"Interesting events:\" << endl;\n\tfor (unsigned int index = 0; index < interestingEvents.size(); ++index) {\n\t\tinterestingEvents.at(index).print();\n\t}\n}\n\nvoid Analysis::printSummary() {\n\tcout << \"total number of processed events: \" << eventReader->getNumberOfProccessedEvents() << endl;\n\tcout << \"number of events without electrons: \" << brokenEvents.size() << endl;\n\tcout << \"number of events with too high pileup: \" << weights->getNumberOfEventsWithTooHighPileUp() << endl;\n}\n\nvoid Analysis::createHistograms() {\n\thistMan->prepareForSeenDataTypes(eventReader->getSeenDatatypes());\n\tunsigned int numberOfHistograms(0), lastNumberOfHistograms(0);\n\n\teventcountAnalyser->createHistograms();\n\tnumberOfHistograms = histMan->size();\n\tcout << \"Number of histograms added by eventcountAnalyser: \" << numberOfHistograms - lastNumberOfHistograms << endl;\n\tlastNumberOfHistograms = numberOfHistograms;\n\n\tttbar_plus_X_analyser_->createHistograms();\n\tnumberOfHistograms = histMan->size();\n\tcout << \"Number of histograms added by ttbar_plus_X_analyser: \" << numberOfHistograms - lastNumberOfHistograms\n\t\t\t<< endl;\n\tlastNumberOfHistograms = numberOfHistograms;\n\n\tdiffVariablesAnalyser->createHistograms();\n\tnumberOfHistograms = histMan->size();\n\tcout << \"Number of histograms added by diffVariablesAnalyser: \" << numberOfHistograms - lastNumberOfHistograms << endl;\n\tlastNumberOfHistograms = numberOfHistograms;\n\n\thistMan->setCurrentHistogramFolder(\"\");\n\thistMan->addH1D(\"PDFweights\", \"PDF weights\", 1000, 0.8, 1.2);\n\n\tcout << \"Total number of histograms: \" << histMan->size() << endl;\n}\n\nAnalysis::Analysis(std::string datasetInfoFile) : //\n\t\teventReader(new NTupleEventReader()), //\n\t\tcurrentEvent(), //\n\t\thistMan(new BAT::HistogramManager()), //\n\t\tinterestingEvents(), //\n\t\tbrokenEvents(), //\n\t\teventCheck(), //\n\t\tweights(new EventWeightProvider(datasetInfoFile)), //\n\t\tweight(0), //\n\t\tpileUpWeight(1), //\n\t\tabcdMethodAnalyser_(new ABCDMethodAnalyser(histMan)), //\n\t\tbjetAnalyser(new BJetAnalyser(histMan)), //\n\t\tdiElectronAnalyser(new DiElectronAnalyser(histMan)), //\n\t\telectronAnalyser(new ElectronAnalyser(histMan)), //\n\t\teventcountAnalyser(new EventCountAnalyser(histMan)), //\n\t\thltriggerAnalyser(new HLTriggerTurnOnAnalyser(histMan)), //\n\t\thltriggerQCDAnalyserInclusive_(new HLTriggerQCDAnalyser(histMan, \"HLTQCDAnalyser_inclusive\", false)), //\n\t\thltriggerQCDAnalyserExclusive_(new HLTriggerQCDAnalyser(histMan, \"HLTQCDAnalyser_exclusive\", true)), //\n\t\tjetAnalyser(new JetAnalyser(histMan)), //\n\t\tmcAnalyser(new MCAnalyser(histMan)), //\n\t\tmetAnalyser(new METAnalyser(histMan)), //\n\t\tmttbarAnalyser(new MTtbarAnalyser(histMan)), //\n\t\tmuonAnalyser(new MuonAnalyser(histMan)), //\n\t\tmvAnalyser(new MVAnalyser(histMan)), //\n\t\tneutrinoRecoAnalyser(new NeutrinoReconstructionAnalyser(histMan)), //\n\t\tttbar_plus_X_analyser_(new TTbar_plus_X_analyser(histMan)), //\n\t\tvertexAnalyser(new VertexAnalyser(histMan)),\n\t\tdiffVariablesAnalyser(new DiffVariablesAnalyser(histMan)),\n\t\tbinningAnalyser(new BinningAnalyser(histMan)) {\n\thistMan->enableDebugMode(true);\n}\n\nAnalysis::~Analysis() {\n\n}\n\nvoid Analysis::finishAnalysis() {\n\tprintSummary();\n\thistMan->writeToDisk();\n}\n\nvoid Analysis::addInputFile(const char* fileName) {\n\teventReader->addInputFile(fileName);\n}\n\nvoid Analysis::setMaximalNumberOfEvents(long maxEvents) {\n\tif (maxEvents > 0) {\n\t\teventReader->setMaximumNumberOfEvents(maxEvents);\n\t}\n}\n\nvoid Analysis::checkForDuplicatedEvents() {\n\tmap<unsigned long, std::vector<unsigned long> >::const_iterator iter;\n\tstd::vector<pair<unsigned long, unsigned long> > duplicateEvents;\n\n\tfor (iter = eventCheck.begin(); iter != eventCheck.end(); ++iter) {\n\t\tstd::vector<unsigned long> events = (*iter).second;\n\t\tstd::sort(events.begin(), events.end());\n\t\tfor (unsigned long ev = 0; ev < events.size() - 1; ++ev) {\n\t\t\tif (events.at(ev) == events.at(ev + 1)) {\n\t\t\t\tduplicateEvents.push_back(make_pair((*iter).first, events.at(ev)));\n\t\t\t}\n\t\t}\n\t}\n\n\tif (duplicateEvents.size() > 0) {\n\t\tcout << \"found duplicate events\" << endl;\n\t\tfor (unsigned long ev = 0; ev < duplicateEvents.size() - 1; ++ev) {\n\t\t\tcout << \"run: \" << duplicateEvents.at(ev).first << \" event: \" << duplicateEvents.at(ev).second << endl;\n\t\t}\n\t}\n}\n\nunsigned long Analysis::getNumberOfProccessedEvents() const {\n\treturn eventReader->getNumberOfProccessedEvents();\n}\n\n", "meta": {"hexsha": "87603feccdeac42e6ff7330be731f2d9381c43c6", "size": 8368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bin/Analysis.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": "bin/Analysis.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": "bin/Analysis.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": 34.1551020408, "max_line_length": 120, "alphanum_fraction": 0.7260994264, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36296919862864746, "lm_q1q2_score": 0.19139965591472594}}
{"text": "#include \"translation_table.h\"\n\n#include <string>\n#include <vector>\n\n#include <boost/functional/hash.hpp>\n\n#include \"alignment.h\"\n#include \"data_array.h\"\n\nusing namespace std;\n\nnamespace extractor {\n\nTranslationTable::TranslationTable(shared_ptr<DataArray> source_data_array,\n                                   shared_ptr<DataArray> target_data_array,\n                                   shared_ptr<Alignment> alignment) :\n    source_data_array(source_data_array), target_data_array(target_data_array) {\n  const vector<int>& source_data = source_data_array->GetData();\n  const vector<int>& target_data = target_data_array->GetData();\n\n  unordered_map<int, int> source_links_count;\n  unordered_map<int, int> target_links_count;\n  unordered_map<pair<int, int>, int, PairHash> links_count;\n\n  // For each pair of aligned source target words increment their link count by\n  // 1. Unaligned words are paired with the NULL token.\n  for (size_t i = 0; i < source_data_array->GetNumSentences(); ++i) {\n    vector<pair<int, int>> links = alignment->GetLinks(i);\n    int source_start = source_data_array->GetSentenceStart(i);\n    int target_start = target_data_array->GetSentenceStart(i);\n    // Ignore END_OF_LINE markers.\n    int next_source_start = source_data_array->GetSentenceStart(i + 1) - 1;\n    int next_target_start = target_data_array->GetSentenceStart(i + 1) - 1;\n    vector<int> source_sentence(source_data.begin() + source_start,\n        source_data.begin() + next_source_start);\n    vector<int> target_sentence(target_data.begin() + target_start,\n        target_data.begin() + next_target_start);\n    vector<int> source_linked_words(source_sentence.size());\n    vector<int> target_linked_words(target_sentence.size());\n\n    for (pair<int, int> link: links) {\n      source_linked_words[link.first] = 1;\n      target_linked_words[link.second] = 1;\n      IncrementLinksCount(source_links_count, target_links_count, links_count,\n          source_sentence[link.first], target_sentence[link.second]);\n    }\n\n    for (size_t i = 0; i < source_sentence.size(); ++i) {\n      if (!source_linked_words[i]) {\n        IncrementLinksCount(source_links_count, target_links_count, links_count,\n                            source_sentence[i], DataArray::NULL_WORD);\n      }\n    }\n\n    for (size_t i = 0; i < target_sentence.size(); ++i) {\n      if (!target_linked_words[i]) {\n        IncrementLinksCount(source_links_count, target_links_count, links_count,\n                            DataArray::NULL_WORD, target_sentence[i]);\n      }\n    }\n  }\n\n  // Calculating:\n  //   p(e | f) = count(e, f) / count(f)\n  //   p(f | e) = count(e, f) / count(e)\n  for (pair<pair<int, int>, int> link_count: links_count) {\n    int source_word = link_count.first.first;\n    int target_word = link_count.first.second;\n    double score1 = 1.0 * link_count.second / source_links_count[source_word];\n    double score2 = 1.0 * link_count.second / target_links_count[target_word];\n    translation_probabilities[link_count.first] = make_pair(score1, score2);\n  }\n}\n\nTranslationTable::TranslationTable() {}\n\nTranslationTable::~TranslationTable() {}\n\nvoid TranslationTable::IncrementLinksCount(\n    unordered_map<int, int>& source_links_count,\n    unordered_map<int, int>& target_links_count,\n    unordered_map<pair<int, int>, int, PairHash>& links_count,\n    int source_word_id,\n    int target_word_id) const {\n  ++source_links_count[source_word_id];\n  ++target_links_count[target_word_id];\n  ++links_count[make_pair(source_word_id, target_word_id)];\n}\n\ndouble TranslationTable::GetTargetGivenSourceScore(\n    const string& source_word, const string& target_word) {\n  int source_id = source_data_array->GetWordId(source_word);\n  int target_id = target_data_array->GetWordId(target_word);\n  if (source_id == -1 || target_id == -1) {\n    return -1;\n  }\n\n  auto entry = make_pair(source_id, target_id);\n  auto it = translation_probabilities.find(entry);\n  if (it == translation_probabilities.end()) {\n    return 0;\n  }\n  return it->second.first;\n}\n\ndouble TranslationTable::GetSourceGivenTargetScore(\n    const string& source_word, const string& target_word) {\n  int source_id = source_data_array->GetWordId(source_word);\n  int target_id = target_data_array->GetWordId(target_word);\n  if (source_id == -1 || target_id == -1) {\n    return -1;\n  }\n\n  auto entry = make_pair(source_id, target_id);\n  auto it = translation_probabilities.find(entry);\n  if (it == translation_probabilities.end()) {\n    return 0;\n  }\n  return it->second.second;\n}\n\nbool TranslationTable::operator==(const TranslationTable& other) const {\n  return *source_data_array == *other.source_data_array &&\n         *target_data_array == *other.target_data_array &&\n         translation_probabilities == other.translation_probabilities;\n}\n\n} // namespace extractor\n", "meta": {"hexsha": "11e29e1eec5f39b802e88184bb21a647b50f8512", "size": 4791, "ext": "cc", "lang": "C++", "max_stars_repo_path": "extractor/translation_table.cc", "max_stars_repo_name": "kho/cdec", "max_stars_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 114.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T05:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T03:47:12.000Z", "max_issues_repo_path": "extractor/translation_table.cc", "max_issues_repo_name": "kho/cdec", "max_issues_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T01:00:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-25T06:04:02.000Z", "max_forks_repo_path": "extractor/translation_table.cc", "max_forks_repo_name": "kho/cdec", "max_forks_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T13:48:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-07T09:45:11.000Z", "avg_line_length": 36.8538461538, "max_line_length": 80, "alphanum_fraction": 0.7056981841, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1913996541559289}}
{"text": "#include \"llvm/Pass.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/CFG.h\"\n#include \"llvm/IR/InstVisitor.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/DataLayout.h\"\n#include \"llvm/Transforms/Utils/UnifyFunctionExitNodes.h\"\n#include \"llvm/Analysis/TargetLibraryInfo.h\"\n#include \"llvm/Analysis/CFG.h\"\n#include \"llvm/ADT/DenseMap.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include \"llvm/Support/Debug.h\"\n\n#include \"crab_llvm/config.h\"\n#include \"crab_llvm/crab_domains.hh\"\n#include \"crab_llvm/wrapper_domain.hh\"\n#include \"crab_llvm/CrabLlvm.hh\"\n#include \"crab_llvm/CfgBuilder.hh\"\n#include \"crab_llvm/HeapAbstraction.hh\"\n#include \"crab_llvm/Support/NameValues.hh\"\n\n#include \"crab/common/debug.hpp\"\n#include \"crab/common/stats.hpp\"\n#include \"crab/analysis/fwd_analyzer.hpp\"\n#include \"crab/analysis/bwd_analyzer.hpp\"\n#include \"crab/analysis/inter_fwd_analyzer.hpp\"\n#include \"crab/analysis/dataflow/liveness.hpp\"\n#include \"crab/analysis/dataflow/assumptions.hpp\"\n#include \"crab/checkers/assertion.hpp\"\n#include \"crab/checkers/null.hpp\"\n#include \"crab/checkers/checker.hpp\"\n#include \"crab/cg/cg.hpp\"\n#include \"crab/cg/cg_bgl.hpp\"\n\n#include \"./crab/path_analyzer.hpp\"\n\n#include <boost/shared_ptr.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/unordered_set.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <memory>\n#include <functional>\n#include <map>\n\n#ifdef HAVE_DSA\n#include \"dsa/DSNode.h\"\n#include \"dsa/Steensgaard.hh\"\n#endif \n\nusing namespace llvm;\nusing namespace crab_llvm;\nusing namespace crab::cfg;\n\ncl::opt<bool>\nCrabPrintAns (\"crab-print-invariants\", \n              cl::desc (\"Print Crab invariants\"),\n              cl::init (false));\n\ncl::opt<bool>\nCrabPrintSumm (\"crab-print-summaries\", \n               cl::desc (\"Print Crab function summaries\"),\n               cl::init (false));\n\ncl::opt<bool>\nCrabPrintPreCond (\"crab-print-preconditions\", \n               cl::desc (\"Print Crab necessary preconditions\"),\n               cl::init (false));\n\ncl::opt<bool>\nCrabStoreInvariants (\"crab-store-invariants\", \n               cl::desc (\"Store invariants\"),\n               cl::init (true));\n\ncl::opt<bool>\nCrabStats (\"crab-stats\", \n           cl::desc (\"Show Crab statistics and analysis results\"),\n           cl::init (false));\n\ncl::opt<bool>\nCrabPrintAssumptions (\"crab-print-unjustified-assumptions\", \n       cl::desc (\"Print unjustified assumptions done by Crab (for now only integer overflow)\"),\n       cl::init (false));\n\ncl::opt<unsigned int>\nCrabWideningDelay(\"crab-widening-delay\", \n   cl::desc(\"Max number of fixpoint iterations until widening is applied\"),\n   cl::init (1));\n\ncl::opt<unsigned int>\nCrabNarrowingIters(\"crab-narrowing-iterations\", \n                   cl::desc(\"Max number of narrowing iterations\"),\n                   cl::init (10));\n\ncl::opt<unsigned int>\nCrabWideningJumpSet(\"crab-widening-jump-set\", \n                    cl::desc(\"Size of the jump set used for widening\"),\n                    cl::init (0));\n\ncl::opt<CrabDomain>\nCrabLlvmDomain(\"crab-dom\",\n      cl::desc (\"Crab numerical abstract domain used to infer invariants\"),\n      cl::values \n      (clEnumValN (INTERVALS, \"int\",\n\t\t   \"Classical interval domain (default)\"),\n       clEnumValN (TERMS_INTERVALS, \"term-int\",\n\t\t   \"Intervals with uninterpreted functions.\"),       \n       clEnumValN (INTERVALS_CONGRUENCES, \"ric\",\n\t\t   \"Reduced product of intervals with congruences\"),\n       clEnumValN (DIS_INTERVALS, \"dis-int\",\n\t\t   \"Disjunctive intervals based on Clousot's DisInt domain\"),\n       clEnumValN (TERMS_DIS_INTERVALS, \"term-dis-int\",\n\t\t   \"Disjunctive Intervals with uninterpreted functions.\"),\n       clEnumValN (BOXES, \"boxes\",\n\t\t   \"Disjunctive intervals based on ldds\"),\n       clEnumValN (ZONES_SPLIT_DBM, \"zones\",\n\t\t   \"Zones domain with Sparse DBMs in Split Normal Form\"),\n       clEnumValN (OPT_OCT_APRON, \"oct\",\n\t\t   \"Optimized octagons domain using Elina\"),\n       clEnumValN (PK_APRON, \"pk\",\n\t\t   \"Polyhedra domain using Apron library\"),\n       clEnumValN (TERMS_ZONES, \"rtz\",\n\t\t   \"Reduced product of term-dis-int and zones.\"),\n       clEnumValN (WRAPPED_INTERVALS, \"w-int\",\n\t\t   \"Wrapped interval domain\"),       \n       clEnumValEnd),\n       cl::init (INTERVALS));\n\ncl::opt<bool>\nCrabBackward (\"crab-backward\", \n           cl::desc (\"Perform an iterative forward/backward analysis\\n\"\n\t\t     \"(Only intra-procedural version implemented)\"),\n           cl::init (false));\n\n// If domain is num\ncl::opt<unsigned>\nCrabRelationalThreshold(\"crab-relational-threshold\", \n   cl::desc(\"Max number of live vars per block before switching \"\n\t    \"to a non-relational domain\"),\n   cl::init (10000),\n   cl::Hidden);\n\ncl::opt<bool>\nCrabLive(\"crab-live\", \n\t cl::desc(\"Run Crab with live ranges. \"\n\t\t  \"It can lose precision if relational domains\"),\n\t cl::init (false));\n\ncl::opt<bool>\nCrabInter (\"crab-inter\",\n           cl::desc (\"Crab Inter-procedural analysis\"), \n           cl::init (false));\n\n// It does not make much sense to have non-relational domains here.\ncl::opt<CrabDomain>\nCrabSummDomain(\"crab-inter-sum-dom\",\n    cl::desc (\"Crab relational domain to generate function summaries\"),\n    cl::values \n    (clEnumValN (ZONES_SPLIT_DBM, \"zones\",\n\t\t \"Zones domain with sparse DBMs in Split Normal Form\"),\n     clEnumValN (OPT_OCT_APRON, \"oct\",\n\t\t \"Optimized octagons using Elina\"),\n     clEnumValN (TERMS_ZONES, \"rtz\",\n\t\t \"Reduced product of term-dis-int and zones.\"),\n     clEnumValEnd),\n    cl::init (ZONES_SPLIT_DBM));\n\ncl::opt<enum tracked_precision>\nCrabTrackLev(\"crab-track\",\n   cl::desc (\"Track abstraction level of the Crab Cfg\"),\n   cl::values\n    (clEnumValN (NUM, \"num\", \"Integer and Boolean registers only\"),\n     clEnumValN (PTR, \"ptr\", \"num + pointer offsets\"),\n     clEnumValN (ARR, \"arr\", \"ptr + memory contents via array abstraction\"),\n     clEnumValEnd),\n   cl::init (tracked_precision::NUM));\n\n\n// llvm-dsa options\ncl::opt<bool>\nCrabDsaDisambiguateUnknown (\"crab-dsa-disambiguate-unknown\",\n    cl::desc (\"Disambiguate unknown pointers (unsound)\"), \n    cl::init (false),\n    cl::Hidden);\n\ncl::opt<bool>\nCrabDsaDisambiguatePtrCast (\"crab-dsa-disambiguate-ptr-cast\",\n    cl::desc (\"Disambiguate pointers that have been casted from/to integers (unsound)\"), \n    cl::init (false),\n    cl::Hidden);\n\ncl::opt<bool>\nCrabDsaDisambiguateExternal (\"crab-dsa-disambiguate-external\",\n    cl::desc (\"Disambiguate pointers that have been passed to external functions (unsound)\"), \n    cl::init (false),\n    cl::Hidden);\n\n// Prove assertions\ncl::opt<assert_check_kind_t>\nCrabCheck (\"crab-check\", \n\t   cl::desc (\"Check user assertions\"),\n\t   cl::values(\n\t       clEnumValN (NOCHECKS  , \"none\"  , \"None\"),\n\t       clEnumValN (ASSERTION , \"assert\", \"User assertions\"),\n\t       clEnumValN (NULLITY   , \"null\"  , \"Null dereference\"),\n\t       clEnumValEnd),\n\t   cl::init (assert_check_kind_t::NOCHECKS));\n\ncl::opt<unsigned int>\nCrabCheckVerbose (\"crab-check-verbose\", \n                 cl::desc (\"Print verbose information about checks\"),\n                 cl::init (0));\n\n// Important to crab-llvm clients (e.g., SeaHorn):\n// Shadow variables are variables that cannot be mapped back to a\n// const Value*. These are created for instance for memory heaps.\ncl::opt<bool>\nCrabKeepShadows (\"crab-keep-shadows\",\n    cl::desc (\"Preserve shadow variables in invariants, summaries, and preconditions\"), \n    cl::init (false),\n    cl::Hidden);\n\n// In C++11 we need to pass to std::bind \"this\" (if class member\n// functions are called) as well as all placeholders for each\n// argument. This is wrapper to avoid that and improve readability.\ntemplate <class C, typename Ret, typename ... Ts>\nstatic std::function<Ret(Ts...)> bind_this(C* c, Ret (C::*m)(Ts...)) {\n  return [=](Ts&&... args) { return (c->*m)(std::forward<decltype(args)>(args)...); };\n}\n\nnamespace crab_llvm {\n\n  static crab::crab_os& get_crab_os(bool show_time = true) {\n    crab::crab_os* result = &crab::outs();\n    if (show_time) {\n      time_t now = time(0);\n      struct tm tstruct;\n      char buf[80];\n      tstruct = *localtime(&now);\n      strftime(buf, sizeof(buf), \"[%Y-%m-%d.%X] \", &tstruct);\n      *result << buf;\n    }\n    return *result;\n  }\n  \n  using namespace crab::analyzer;\n  using namespace crab::checker;\n  using namespace crab::cg;\n\n  /** Begin typedefs **/\n  typedef crab::analyzer::liveness<cfg_ref_t> liveness_t;\n  typedef crab::cg::call_graph<cfg_ref_t> call_graph_t; \n  typedef crab::cg::call_graph_ref<call_graph_t> call_graph_ref_t;\n  typedef boost::unordered_map<cfg_ref_t, const liveness_t*> liveness_map_t;\n  typedef DenseMap<const BasicBlock*, lin_cst_sys_t> assumption_map_t;\n  typedef typename IntraCrabLlvm::wrapper_dom_ptr wrapper_dom_ptr;    \n  typedef typename IntraCrabLlvm::checks_db_t checks_db_t;\n  typedef typename IntraCrabLlvm::invariant_map_t invariant_map_t;\n  typedef typename IntraCrabLlvm::heap_abs_ptr heap_abs_ptr;\n  /** End typedefs **/\n  \n  /** Begin global counters **/\n  static unsigned num_invars; // some measure for the size of invariants\n  static unsigned num_nontrivial_blocks;\n  /** End global counters **/\n  \n  static bool isRelationalDomain(CrabDomain dom) {\n    return (dom == ZONES_SPLIT_DBM || dom == OPT_OCT_APRON ||\n\t    dom == PK_APRON        || dom == TERMS_ZONES);\n  }\n\n  static bool isTrackable(const Function &fun) {\n    return !fun.isDeclaration () && !fun.empty () && !fun.isVarArg ();\n  }\n\n  /** convenient wrapper for the invariance analysis datastructures **/\n  struct InvarianceAnalysisResults {\n    // invariants that hold at the entry of a block\n    invariant_map_t &premap;\n    // invariants that hold at the exit of a block\n    invariant_map_t &postmap;\n    // database with all the checks\n    checks_db_t &checksdb;\n\n    InvarianceAnalysisResults(invariant_map_t &pre, invariant_map_t &post,\n\t\t\t      checks_db_t &db)\n      : premap(pre), postmap(post), checksdb(db) {}\n  };\n\n  /** return invariant for block in table but filtering out shadow_varnames **/\n  static wrapper_dom_ptr lookup(const invariant_map_t &table,\n\t\t\t\tconst llvm::BasicBlock &block,\n\t\t\t\tconst std::vector<varname_t> &shadow_varnames) {\n    auto it = table.find (&block);\n    if (it == table.end()) {\n      return nullptr;\n    }\n    \n    if (shadow_varnames.empty()) {\n      return it->second;\n    } else {\n      std::vector<var_t> shadow_vars;\n      shadow_vars.reserve(shadow_varnames.size());\n      for(unsigned i=0; i<shadow_vars.size(); ++i) {\n\t// we need to create a typed variable\n\tshadow_vars.push_back(var_t(shadow_varnames[i], crab::UNK_TYPE, 0));\n      }\n      auto invs = it->second->clone();\n      invs->forget(shadow_vars); \n      return invs;\n    }\n  }   \n\n  /** update table with pre or post invariants **/\n  static bool update(invariant_map_t &table, \n\t\t     const llvm::BasicBlock &block, wrapper_dom_ptr absval) {\n    bool already = false;\n    auto it = table.find(&block);\n    if (it == table.end()) {\n      table.insert(std::make_pair(&block, absval));\n    } else {\n      it->second = absval;\n      already = true;\n    }\n    return already;\n  }\n      \n  /** Pretty-printer utilities **/\n  namespace pretty_printer_impl {\n\n    /** Generic class for a block annotation **/\n    class block_annotation {\n    public:\n      typedef typename cfg_ref_t::statement_t statement_t;\n      \n      block_annotation() {}\n      virtual ~block_annotation() {}\n\n      virtual std::string name() const = 0;\n      virtual void print_begin(basic_block_label_t bbl, crab::crab_os &o) const {}\n      virtual void print_end(basic_block_label_t bbl, crab::crab_os &o) const {}\n      virtual void print_begin(const statement_t &s, crab::crab_os &o) const {}\n      virtual void print_end(const statement_t &s, crab::crab_os &o) const {}\n\t\t\t      \n    };\n\n    /** Annotation for invariants **/\n    class invariant_annotation: public block_annotation {\n    private:\n      const invariant_map_t &m_premap;\n      const invariant_map_t &m_postmap;\n      std::vector<varname_t> m_shadow_vars;\n      \n    public:\n      invariant_annotation (const llvm_variable_factory &vfac,\n\t\t\t    const invariant_map_t &premap,\n\t\t\t    const invariant_map_t &postmap,\n\t\t\t    const bool keep_shadows)\n\t: block_annotation(), m_premap(premap), m_postmap(postmap) {\n\tif (keep_shadows) {\n\t  m_shadow_vars.reserve(std::distance(vfac.get_shadow_vars().begin(),\n\t\t\t\t\t      vfac.get_shadow_vars().end()));\n\t  m_shadow_vars.insert(m_shadow_vars.begin(),\n\t\t\t       vfac.get_shadow_vars().begin(),\n\t\t\t       vfac.get_shadow_vars().end());\n\t}\n      }\n      \n      std::string name() const { return \"INVARIANTS\";}\n      \n      void print_begin(basic_block_label_t bbl, crab::crab_os &o) const {\n\tif (const llvm::BasicBlock *bb = bbl.get_basic_block()) {\n\t  wrapper_dom_ptr pre = lookup(m_premap, *bb, m_shadow_vars);\n\t  o << \"  \" << name() << \": \";\n\t  if (pre){\n\t    o << pre << \"\\n\";\n\t  } else {\n\t    o << \"null\\n\";\n\t  }\n\t}\n      }\n      \n      void print_end(basic_block_label_t bbl, crab::crab_os &o) const {\n\tif (const llvm::BasicBlock *bb = bbl.get_basic_block()) {\n\t  wrapper_dom_ptr post = lookup(m_postmap, *bb, m_shadow_vars);\n\t  o << \"  \" << name() << \": \";\n\t  if (post) {\n\t    o << post << \"\\n\";\n\t  } else {\n\t    o << \"null\\n\";\n\t  }\n\t}\n      }\n    };\n\n    /** Annotation for neccesary_preconditions **/\n    template<typename Analyzer>\n    class nec_precondition_annotation: public block_annotation {\n    private:\n      Analyzer &m_analyzer;\n      \n    public:\n      nec_precondition_annotation (Analyzer &analyzer)\n\t: block_annotation(), m_analyzer(analyzer) {}\n      \n      std::string name() const { return \"NECESSARY PRECONDITIONS\";}\n      \n      void print_begin(basic_block_label_t bbl, crab::crab_os &o) const {\n\tauto pre = m_analyzer.get_preconditions(bbl);\n\to << \"  \" << name() << \": \" << pre << \"\\n\";\t\n      }\n    };\n\n    /** Annotation for unjustified assumptions done by the analysis **/\n    class assumption_annotation: public block_annotation {\n    private:\n      typedef typename assumption_analysis<cfg_ref_t>::assumption_ptr assumption_ptr;\n      typedef assumption_analysis<cfg_ref_t> assumption_analysis_t;\n      typedef typename cfg_ref_t::statement_t statement_t;\n      \n      cfg_ref_t m_cfg;\n      assumption_analysis_t *m_analyzer;\n      \n    public:\n      assumption_annotation (cfg_ref_t cfg, assumption_analysis_t *analyzer)\n\t: block_annotation(), m_cfg(cfg), m_analyzer(analyzer) { }\n      \n      std::string name() const { return \"UNJUSTIFIED ASSUMPTIONS\";}\n      \n      void print_begin(const statement_t &s, crab::crab_os &o) const {\n\tstd::vector<assumption_ptr> assumes;\n\tif (s.is_assert()) {\n\t  typedef typename cfg_ref_t::basic_block_t::assert_t assert_t;\n\t  m_analyzer->get_assumptions(static_cast<const assert_t *>(&s), assumes);\n\t  if (!assumes.empty()) {\n\t    o << \"  /** assert verified as \";\n\t    for (std::vector<assumption_ptr>::iterator it = assumes.begin(),\n\t\t   et = assumes.end(); it!=et;) {\n\t      o << (*it)->get_id_str();\n\t      ++it;\n\t      if (it != et)\n\t\to << \",\";\n\t      else\n\t\to << \";\";\n\t    }\n\t    o << \"**/\\n\";\n\t  }\n\t} else {\n\t  m_analyzer->get_originated_assumptions(&s, assumes);\n\t  for (auto assume_ptr: assumes) {\n\t    o << \"  /** \"; assume_ptr->write(o); o << \"**/\\n\";\n\t  }\n\t}\n      }\n      \n    };\n    \n    /** Print a block together with its annotations **/\n    class print_block {\n      cfg_ref_t m_cfg;\n      crab::crab_os &m_o;\n      const std::vector<std::unique_ptr<block_annotation>> &m_annotations;\n\n    public:\n      \n      print_block (cfg_ref_t cfg, crab::crab_os &o,\n\t\t   const std::vector<std::unique_ptr<block_annotation>> &annotations)\n\t: m_cfg(cfg), m_o(o), m_annotations(annotations) {} \n\n      void operator()(basic_block_label_t bbl) const {\n\t// do not print block if no annotations\n\tif (m_annotations.empty()) return;\n\t\n\tm_o << bbl.get_name() << \":\\n\";\n\n\tcrab::crab_string_os o;\n\tfor (auto& p: m_annotations) {\n\t  p->print_begin(bbl,o);\n\t}\n\tif (o.str() != \"\") {\n\t  m_o << \"/**\\n\" << o.str() << \"**/\\n\";\n\t}\n\t\n\tconst basic_block_t &bb = m_cfg.get_node(bbl);\n\tbool empty_block = (std::distance(bb.begin(), bb.end()) == 0);\n\tfor (auto const &s: bb) {\n\t  for (auto& p: m_annotations) {\n\t    p->print_begin(s, m_o);\n\t  }\t  \n\t  m_o << \"  \" << s << \";\\n\";\n\t  for (auto& p: m_annotations) {\n\t    p->print_end(s, m_o);\n\t  }\t  \n\t}\n\tif (!empty_block) {\n\t  crab::crab_string_os o;\n\t  for (auto& p: m_annotations) {\n\t    p->print_end(bbl, o);\n\t  }\n\t  if (o.str() != \"\") {\n\t    m_o << \"/**\\n\" << o.str() << \"**/\\n\";\n\t  }\n\t}\n\n\tstd::pair<cfg_ref_t::const_succ_iterator, \n\t\t  cfg_ref_t::const_succ_iterator> p = bb.next_blocks();\n\tcfg_ref_t::const_succ_iterator it = p.first;\n\tcfg_ref_t::const_succ_iterator et = p.second;\n\tif (it != et) {\n\t  m_o << \"  \" << \"goto \";\n\t  for (; it != et; ) {\n\t    m_o << crab::cfg_impl::get_label_str (*it);\n\t    ++it;\n\t    if (it == et) {\n\t      m_o << \";\";\n\t    } else {\n\t      m_o << \",\";\n\t    }\n\t  }\n\t}\n\tm_o << \"\\n\";\n      }\n    };\n\n    typedef boost::unordered_set<basic_block_label_t> visited_t;\n    template<typename T>\n    void dfs_rec (cfg_ref_t cfg, basic_block_label_t curId, visited_t &visited, T f) {\n      if (visited.find (curId) != visited.end ()) return;\n      visited.insert (curId);\n      const basic_block_t &cur = cfg.get_node(curId);\n      f (curId);\n      for (auto const n : boost::make_iterator_range (cur.next_blocks ())) {\n    \tdfs_rec (cfg, n, visited, f);\n      }\n    }\n    \n    template<typename T>\n    void dfs (cfg_ref_t cfg, T f) {\n      visited_t visited;\n      dfs_rec (cfg, cfg.entry(), visited, f);\n    }\n\n    void print_annotations(cfg_ref_t cfg, const std::vector<std::unique_ptr<block_annotation>> &annotations) {\n      print_block f(cfg, crab::outs(), annotations);\n      dfs(cfg, f);\n    }\n  } //end namespace\n\n  static std::string dom_to_str(CrabDomain dom) {\n    switch (dom) {\n    case INTERVALS:             return interval_domain_t::getDomainName();\n    case INTERVALS_CONGRUENCES: return ric_domain_t::getDomainName();\n    case BOXES:                 return boxes_domain_t::getDomainName();\n    case DIS_INTERVALS:         return dis_interval_domain_t::getDomainName();\n    case ZONES_SPLIT_DBM:       return split_dbm_domain_t::getDomainName();\n    case TERMS_DIS_INTERVALS:   return term_dis_int_domain_t::getDomainName();\n    case TERMS_ZONES:           return num_domain_t::getDomainName();\n    case OPT_OCT_APRON:         return opt_oct_apron_domain_t::getDomainName();\n    case PK_APRON:              return pk_apron_domain_t::getDomainName();\n    case WRAPPED_INTERVALS:     return wrapped_interval_domain_t::getDomainName();\n    default:                    return \"none\";\n    }\n  }\n  \n  std::string AnalysisParams::abs_dom_to_str() const {\n    return dom_to_str(dom);\n  }\n\n  std::string AnalysisParams::sum_abs_dom_to_str() const {\n    return dom_to_str(sum_dom);\n  }\n  \n  /* CFG Manager class */\n  CfgManager::CfgManager(){}\n  CfgManager::~CfgManager(){\n    for (auto &kv: m_cfg_map) {\n      delete kv.second;\n    }\n  }\n  \n  bool CfgManager::has_cfg(const Function &f) const {\n    return m_cfg_map.find(&f) != m_cfg_map.end();\n  }\n  \n  cfg_ref_t CfgManager::operator[](const Function &f) const {\n    assert(has_cfg(f));\n    \n    auto it = m_cfg_map.find(&f);\n    cfg_t *cfg = it->second;\n    return cfg_ref_t(*cfg);\n  }\n  \n  void CfgManager::add(const Function &f, cfg_t *cfg) {\n    if (!has_cfg(f)) {\n      m_cfg_map.insert(std::make_pair(&f, cfg));\n    }\n  }\n  \n  /**\n   * Internal implementation of the intra-procedural analysis\n   **/\n  class IntraCrabLlvm_Impl {\n    \n    cfg_t *m_cfg;\n    Function &m_fun;\n    llvm_variable_factory &m_vfac;\n    typename CfgBuilder::edge_to_bb_map_t m_edge_bb_map;\n    \n    template<typename Dom>\n    void analyzeCfg(const AnalysisParams &params,\n\t\t    const BasicBlock *entry,\n\t\t    const assumption_map_t &assumptions, liveness_t *live,\n\t\t    InvarianceAnalysisResults &results) {\n      \n      // -- we use the combined forward/backward analyzer\n      typedef intra_forward_backward_analyzer<cfg_ref_t,Dom> intra_analyzer_t;\n      // -- checkers for assertions and nullity\n      typedef intra_checker<intra_analyzer_t> intra_checker_t;\n      typedef assert_property_checker<intra_analyzer_t> assert_prop_t;\n      typedef null_property_checker<intra_analyzer_t> null_prop_t;\n      \n      CRAB_VERBOSE_IF(1,\n\t\t      auto fdecl = m_cfg->get_func_decl ();            \n\t\t      assert (fdecl);\n\t\t      get_crab_os() << \"Running intra-procedural analysis with \" \n\t\t                    << \"\\\"\" << Dom::getDomainName ()  << \"\\\"\"\n\t\t                    << \" for \"  << (*fdecl).get_func_name ()\n\t\t                    << \"  ... \\n\";);\n      \n      // -- run intra-procedural analysis\n      intra_analyzer_t analyzer (*m_cfg);\n      typename intra_analyzer_t::assumption_map_t crab_assumptions;\n      typedef typename intra_analyzer_t::assumption_map_t::value_type binding_t;\n      // reconstruct a crab assumption map from our assumption DenseMap\n      for (auto &kv: assumptions) {\n\tDom absval = Dom::top();\n\tabsval += kv.second;\n\tcrab_assumptions.insert(binding_t(kv.first, absval));\n      }\n      \n      Dom post_cond = Dom::top();\n      if (params.check && params.run_backward) {\n\t// XXX: we compute preconditions that ensure that the program\n\t// fail. If those preconditions are false then we can conclude\n\t// the program is safe.\n\tpost_cond = Dom::bottom();\n      }\n\n      analyzer.run(basic_block_label_t(entry), Dom::top(), post_cond,\n\t\t   !params.run_backward, crab_assumptions, live,\n\t\t   params.widening_delay, params.narrowing_iters, params.widening_jumpset);\n      CRAB_VERBOSE_IF(1, get_crab_os() << \"Finished intra-procedural analysis.\\n\"); \n\n      // -- store invariants\n      if (params.store_invariants || params.print_invars) {\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"Storing invariants.\\n\");       \n\tfor (basic_block_label_t bl: boost::make_iterator_range(m_cfg->label_begin(),\n\t\t\t\t\t\t\t\tm_cfg->label_end())) {\n\t  const BasicBlock *B = bl.get_basic_block();\n\t  if (!B) continue; // we only store those which correspond to llvm basic blocks\n\t  \n\t  // --- invariants that hold at the entry of the blocks\n\t  auto pre = analyzer.get_pre (bl);\n\t  update(results.premap, *B,  mkGenericAbsDomWrapper(pre));\n\t  // --- invariants that hold at the exit of the blocks\n\t  auto post = analyzer.get_post (bl);\n\t  update(results.postmap, *B,  mkGenericAbsDomWrapper(post));\t\n\t  if (params.stats) {\n\t    unsigned num_block_invars = 0;\n\t    // TODO CRAB: for boxes we would like to use\n\t    // to_disjunctive_linear_constraint_system() but it needs to\n\t    // be exposed to all domains\n\t    num_block_invars += pre.to_linear_constraint_system().size();\n\t    num_invars += num_block_invars;\n\t    if (num_block_invars > 0) num_nontrivial_blocks++;\n\t  }\n\t}\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"All invariants stored.\\n\");\n      }\n      \n      // -- print all cfg annotations (if any)\n      if (params.print_invars ||\n\t  (params.print_preconds && params.run_backward) ||\n\t  params.print_assumptions) {\n\n\ttypedef pretty_printer_impl::block_annotation block_annotation_t;\n\ttypedef pretty_printer_impl::invariant_annotation inv_annotation_t;\n\ttypedef pretty_printer_impl::nec_precondition_annotation<intra_analyzer_t> pre_annotation_t;\n\ttypedef pretty_printer_impl::assumption_annotation assume_annotation_t;\n\tstd::vector<std::unique_ptr<block_annotation_t>> pool_annotations;\n\t\n\tllvm::outs() << \"\\n\" << \"function \" << m_fun.getName() << \"\\n\";\n\tif (params.print_invars) {\n\t  pool_annotations.emplace_back(\n\t       make_unique<inv_annotation_t>(m_vfac, results.premap, results.postmap, \n\t\t\t\t\t     params.keep_shadow_vars));\n\t}\n\n\tif (params.print_preconds && params.run_backward) {\n\t  pool_annotations.emplace_back(make_unique<pre_annotation_t>(analyzer));\n\t}\n\n\t// XXX: it must be alive when print_annotations is called.\n\t#if 0\n\tassumption_naive_analysis<cfg_ref_t> assumption_analyzer(*m_cfg);\n\t#else\n\tassumption_dataflow_analysis<cfg_ref_t> assumption_analyzer(*m_cfg);\n\t#endif \n\t\n\tif (params.print_assumptions) {\n\t  // -- run first the analysis\n\t  assumption_analyzer.exec();\n\t  pool_annotations.emplace_back(\n\t       make_unique<assume_annotation_t>(*m_cfg, &assumption_analyzer));\n\t}\n\n\tpretty_printer_impl::print_annotations(*m_cfg, pool_annotations);\n      }\n          \n      if (params.check) {\n\t// --- checking assertions and collecting data\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"Checking assertions ... \\n\"); \n\ttypename intra_checker_t::prop_checker_ptr\n\t  prop (new assert_prop_t (params.check_verbose));\n\tif (params.check == NULLITY)\n\t  prop.reset (new null_prop_t(params.check_verbose));\n\tintra_checker_t checker (analyzer, {prop});\n\tchecker.run ();\n\tCRAB_VERBOSE_IF(1,\n\t\t\tllvm::outs() << \"Function \" << m_fun.getName() << \"\\n\";\n\t\t\tchecker.show (crab::outs()));\n\tresults.checksdb += checker.get_all_checks();\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"Finished assert checking.\\n\");      \n      }\n\n      \n      return;\n    }\n\n    template<typename AbsDom>\n    void wrapperPathAnalyze(const std::vector<llvm_basic_block_wrapper>& path,\n\t\t\t    std::vector<crab::cfg::statement_wrapper>& core,\n\t\t\t    bool populate_maps,\n\t\t\t    invariant_map_t& post, invariant_map_t& pre, bool &res) {\n      \n      typedef path_analyzer<cfg_ref_t, AbsDom> path_analyzer_t;\n      AbsDom init;\n      path_analyzer_t path_analyzer(*m_cfg, init);\n      res = path_analyzer.solve(path, /*compute_preconditions=*/ populate_maps);\n      if (populate_maps) {\n\tfor(auto n: path) {\n\t  if (const llvm::BasicBlock* bb = n.get_basic_block()) {\n\t    AbsDom abs_val = path_analyzer.get_fwd_constraints(n);\n\t    post.insert(std::make_pair(bb, mkGenericAbsDomWrapper(abs_val)));\n\t    if (abs_val.is_bottom()) {\n\t      // the rest of blocks must be also bottom so we don't\n\t      // bother storing them.\n\t      break;\n\t    }\n\t  }\n\t}\n      }\n\n      if (!res) {\n\tpath_analyzer.get_unsat_core(core);\n\n\tif (populate_maps) {\n\t  for(auto n: path) {\n\t    if (const llvm::BasicBlock* bb = n.get_basic_block()) {\n\t      AbsDom abs_val = path_analyzer.get_bwd_constraints(n);\n\t      pre.insert(std::make_pair(bb, mkGenericAbsDomWrapper(abs_val)));\n\t      if (abs_val.is_bottom()) {\n\t\t// the rest of blocks must be also bottom so we don't\n\t\t// bother storing them.\n\t\tbreak;\n\t      }\n\t    }\n\t  }\n\t}\n      }\n    }\n        \n    \n    struct intra_analysis {\n      std::function<void(const AnalysisParams&,\n\t\t\t const BasicBlock*,\n\t\t\t const assumption_map_t&,\n\t\t\t liveness_t*,\n\t\t\t InvarianceAnalysisResults&)> analyze;\n      std::string name;\n    };\n\n    struct path_analysis {\n      std::function<void(const std::vector<llvm_basic_block_wrapper>&,\n\t\t\t std::vector<crab::cfg::statement_wrapper>&,\n\t\t\t bool, invariant_map_t&, invariant_map_t&,bool&)> analyze;\n      std::string name;\n    };\n    \n    // Domains used for intra-procedural analysis\n    const std::map<CrabDomain, intra_analysis> intra_analyses {\n      { INTERVALS               , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<interval_domain_t>), \"classical intervals\" } } \n      #ifdef HAVE_ALL_DOMAINS\t\n      , { INTERVALS_CONGRUENCES , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<ric_domain_t>), \"reduced product of intervals and congruences\" }}\n      , { DIS_INTERVALS         , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<dis_interval_domain_t>), \"disjunctive intervals\" }}\n      , { TERMS_INTERVALS       , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<term_int_domain_t>), \"terms with intervals\" }}\n      #endif \t\n      , { WRAPPED_INTERVALS     , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<wrapped_interval_domain_t>), \"wrapped intervals\" }}\n      , { ZONES_SPLIT_DBM       , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<split_dbm_domain_t>), \"zones\" }}\n      , { BOXES                 , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<boxes_domain_t>), \"boxes\" }}\n      , { OPT_OCT_APRON         , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<opt_oct_apron_domain_t>), \"elina octagons\" }}\n      , { PK_APRON              , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<pk_apron_domain_t>), \"apron pk\" }}\n      , { TERMS_ZONES           , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<num_domain_t>), \"terms with zones\" }}\n      , { TERMS_DIS_INTERVALS   , { bind_this(this, &IntraCrabLlvm_Impl::analyzeCfg<term_dis_int_domain_t>), \"terms with disjunctive intervals\" }}\n    };\n\n\n    // Domains used for path-based analysis\n    const std::map<CrabDomain, path_analysis> path_analyses {\n      { INTERVALS               , { bind_this(this, &IntraCrabLlvm_Impl::wrapperPathAnalyze<interval_domain_t>), \"classical intervals\" } } \n      #ifdef HAVE_ALL_DOMAINS\t\n      , { TERMS_INTERVALS       , { bind_this(this, &IntraCrabLlvm_Impl::wrapperPathAnalyze<term_int_domain_t>), \"terms with intervals\" }}\n      #endif \t\n      , { WRAPPED_INTERVALS     , { bind_this(this, &IntraCrabLlvm_Impl::wrapperPathAnalyze<wrapped_interval_domain_t>), \"wrapped intervals\" }}\n      , { ZONES_SPLIT_DBM       , { bind_this(this, &IntraCrabLlvm_Impl::wrapperPathAnalyze<split_dbm_domain_t>), \"zones\" }}      \n      , { TERMS_ZONES           , { bind_this(this, &IntraCrabLlvm_Impl::wrapperPathAnalyze<num_domain_t>), \"terms with zones\" }}\n      /* \n\t To add new domains here make sure you add an explicit\n\t instantiation in crab/path_analyzer.cc \n      */\n      //, { TERMS_DIS_INTERVALS , { bind_this(this, &IntraCrabLlvm_Impl::wrapperPathAnalyze<term_dis_int_domain_t>), \"terms with disjunctive intervals\" }}\n    };\n\n  public:\n    \n    IntraCrabLlvm_Impl(Function &fun,\n\t\t       crab::cfg::tracked_precision cfg_precision,\n\t\t       heap_abs_ptr mem, llvm_variable_factory &vfac,\n\t\t       CfgManager &cfg_man, const TargetLibraryInfo &tli)\n\t\t       \n      : m_cfg(nullptr), m_fun(fun), m_vfac(vfac) {\n      if (isTrackable(m_fun)) {\n\t// -- build a crab cfg for func\n\tCfgBuilder builder(m_fun, m_vfac, *mem, cfg_precision, true, &tli);\n\tm_cfg = builder.get_cfg();\n\tm_edge_bb_map = builder.getEdgeToBBMap();\n\tCRAB_VERBOSE_IF(1, llvm::outs() << \"Built Crab CFG for \"\n\t\t\t                << fun.getName() << \"\\n\");\n\tcfg_man.add(fun, m_cfg);\n\t  \n      } else {\n\tCRAB_VERBOSE_IF(1, llvm::outs() << \"Cannot build CFG for \"\n\t\t\t                << fun.getName() << \"\\n\");\n      }\n    }\n\n    void Analyze(AnalysisParams &params,\n\t\t const llvm::BasicBlock *entry,\n\t\t const assumption_map_t &assumptions,\n\t\t InvarianceAnalysisResults &results) {\n\n      if (!m_cfg) {\n\tCRAB_VERBOSE_IF(1, llvm::outs() << \"Skipped analysis for \"\n\t\t\t                << m_fun.getName() << \"\\n\");\n\treturn;\n      }\n      \n      // -- run liveness\n      liveness_t live(*m_cfg);\n      if (params.run_liveness || isRelationalDomain(params.dom)) {\n\tCRAB_VERBOSE_IF(1,\n\t\t\tauto fdecl = m_cfg->get_func_decl ();            \n\t\t\tassert (fdecl);\n\t\t\tget_crab_os() << \"Running liveness analysis for \" \n\t\t\t              << (*fdecl).get_func_name ()\n\t\t                      << \"  ...\\n\";);\n\tlive.exec ();\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"Finished liveness analysis.\\n\");\n\t// some stats\n\tunsigned total_live, avg_live_per_blk, max_live_per_blk;\n\tlive.get_stats (total_live, max_live_per_blk, avg_live_per_blk);\n\tCRAB_VERBOSE_IF(1, \n\t\t  crab::outs() << \"-- Max number of out live vars per block=\" \n                               << max_live_per_blk << \"\\n\"\n                               << \"-- Avg number of out live vars per block=\" \n                               << avg_live_per_blk << \"\\n\";);\n\tcrab::CrabStats::count_max (\"Liveness.count.maxOutVars\",\n\t\t\t\t    max_live_per_blk);\n\n\tif (isRelationalDomain(params.dom)) {\n\t  CRAB_VERBOSE_IF(1, \n\t\t    crab::outs() << \"Max live per block: \"\n\t\t                 << max_live_per_blk << \"\\n\"\n\t\t                 << \"Threshold: \"\n\t\t                 << params.relational_threshold << \"\\n\");\n\t  if (max_live_per_blk > params.relational_threshold) {\n\t    // default domain\n\t    params.dom = INTERVALS;\n\t  }\n\t}\n      }\n\n      if (intra_analyses.count(params.dom)) {\n      \tintra_analyses.at(params.dom).analyze(params, entry, assumptions,\n\t\t\t\t\t     (params.run_liveness)? &live : nullptr,\n\t\t\t\t\t     results);\n      } else {\n      \tcrab::outs() << \"Warning: abstract domain not found or enabled.\\n\"\n      \t\t     << \"Running \" << intra_analyses.at(INTERVALS).name << \" ...\\n\"; \n      \tintra_analyses.at(INTERVALS).analyze(params, entry, assumptions,\n\t\t\t\t\t    (params.run_liveness)? &live : nullptr,\n\t\t\t\t\t    results);\n      }\n    }\n    \n    bool pathAnalyze(const AnalysisParams& params,\n\t\t     const std::vector<const llvm::BasicBlock*>& blocks,\n\t\t     std::vector<crab::cfg::statement_wrapper>& core,\n\t\t     bool populate_maps, \n\t\t     invariant_map_t& post, invariant_map_t& pre) const {\n      assert(m_cfg);\n\n      // build the full path (included internal basic blocks added\n      // during the translation to Crab)\n      std::vector<llvm_basic_block_wrapper> path;\n      path.reserve(blocks.size());\n      for(unsigned i=0; i < blocks.size(); ++i) {\n\tpath.push_back(blocks[i]);\n\tif (i < blocks.size() - 1) {\n\t  auto it = m_edge_bb_map.find(std::make_pair(blocks[i], blocks[i+1]));\n\t  if (it != m_edge_bb_map.end()) {\n\t    path.push_back(it->second);\n\t  }\n\t}\n      }\n\n      bool res;\n      if (path_analyses.count(params.dom)) {\n      \tpath_analyses.at(params.dom).analyze(path, core, populate_maps, post, pre, res);\n      } else {\n      \tcrab::outs() << \"Warning: abstract domain not found or enabled.\\n\"\n      \t\t     << \"Running \" << path_analyses.at(INTERVALS).name << \" ...\\n\";\n      \tpath_analyses.at(INTERVALS).analyze(path, core, populate_maps, post, pre, res);\n\t\n      }\n      return res;\n    }\n    \n  }; // end class\n\n  /**\n   *   Begin IntraCrabLlvm methods\n   **/\n  IntraCrabLlvm::IntraCrabLlvm(Function &fun, const TargetLibraryInfo &tli,\n\t\t\t       CfgManager &cfg_man,\n\t\t\t       crab::cfg::tracked_precision cfg_precision,\n\t\t\t       heap_abs_ptr heap_abs)\n    : m_impl(nullptr), m_fun(&fun) {\n    if (!heap_abs)\n      heap_abs = boost::make_shared<DummyHeapAbstraction>();\n    \n    m_impl = make_unique<IntraCrabLlvm_Impl>(fun, cfg_precision,\n\t\t\t\t\t     heap_abs, m_vfac, cfg_man, tli);\n  }\n\n  IntraCrabLlvm::~IntraCrabLlvm() {}\n\n  void IntraCrabLlvm::clear() {\n    m_pre_map.clear();\n    m_post_map.clear();\n    m_checks_db.clear();\n  }\n  \n  void IntraCrabLlvm::analyze(AnalysisParams &params,\n\t\t\t      const assumption_map_t &assumptions) {\n    InvarianceAnalysisResults results = { m_pre_map, m_post_map, m_checks_db};\n    \n    m_impl->Analyze(params, &(m_fun->getEntryBlock()), assumptions, results);\n  }\n\n  void IntraCrabLlvm::analyze(AnalysisParams &params,\n\t\t\t      const llvm::BasicBlock *entry,\n\t\t\t      const assumption_map_t &assumptions) {\n    InvarianceAnalysisResults results = { m_pre_map, m_post_map, m_checks_db};\n    m_impl->Analyze(params, entry, assumptions, results);\n  }\n  \n  template<>\n  bool IntraCrabLlvm::path_analyze(const AnalysisParams& params,\n\t\t\t\t   const std::vector<const llvm::BasicBlock*>& path,\n\t\t\t\t   std::vector<crab::cfg::statement_wrapper>& core) const {\n    invariant_map_t pre_conditions, post_conditions;\n    return m_impl->pathAnalyze(params, path, core, false, post_conditions, pre_conditions);\n  }\n\n  template<>\n  bool IntraCrabLlvm::path_analyze(const AnalysisParams& params,\n\t\t\t\t   const std::vector<const llvm::BasicBlock*>& path,\n\t\t\t\t   std::vector<crab::cfg::statement_wrapper>& core,\n\t\t\t\t   invariant_map_t& post_conditions,\n\t\t\t\t   invariant_map_t& pre_conditions) const {\n    return m_impl->pathAnalyze(params, path, core, true, post_conditions, pre_conditions);\n  }\n\n  wrapper_dom_ptr IntraCrabLlvm::get_pre(const llvm::BasicBlock *block,\n\t\t\t\t\t bool keep_shadows) const {\n    std::vector<varname_t> shadows;\n    if (!keep_shadows)\n      shadows = std::vector<varname_t>(m_vfac.get_shadow_vars().begin(),\n\t\t\t\t       m_vfac.get_shadow_vars().end());    \n    return lookup(m_pre_map, *block, shadows);\n  }   \n\n  wrapper_dom_ptr IntraCrabLlvm::get_post(const llvm::BasicBlock *block,\n\t\t\t\t\t  bool keep_shadows) const {\n    std::vector<varname_t> shadows;\n    if (!keep_shadows)\n      shadows = std::vector<varname_t>(m_vfac.get_shadow_vars().begin(),\n\t\t\t\t       m_vfac.get_shadow_vars().end());    \n    return lookup(m_post_map, *block, shadows);\n  }\n\n  const checks_db_t& IntraCrabLlvm::get_checks_db() const { return m_checks_db;}\n  \n  /**\n   *   End IntraCrabLlvm methods\n   **/\n\n  /**\n   *   Internal implementation of the inter-procedural analysis\n   **/\n  class InterCrabLlvm_Impl {\n    std::unique_ptr<call_graph_t> m_cg;\n    Module& m_M;\n    llvm_variable_factory &m_vfac;\n    liveness_map_t m_live_map;\n      \n    /** Run inter-procedural analysis on the whole call graph **/\n    template<typename BUDom, typename TDDom>\n    void analyzeCg(const AnalysisParams &params,\n\t\t   InvarianceAnalysisResults &results) {\n      \n      typedef inter_fwd_analyzer<call_graph_ref_t, BUDom, TDDom> inter_analyzer_t;\n      typedef inter_checker<inter_analyzer_t> inter_checker_t;\n      typedef assert_property_checker<inter_analyzer_t> assert_prop_t;\n      typedef null_property_checker<inter_analyzer_t> null_prop_t;\n      \n      CRAB_VERBOSE_IF(1, \n \t\t      get_crab_os() << \"Running inter-procedural analysis with \" \n\t\t                    << \"forward domain:\" \n\t\t                    << \"\\\"\" << TDDom::getDomainName () << \"\\\"\"\n\t\t                    << \" and bottom-up domain:\" \n\t\t                    << \"\\\"\" << BUDom::getDomainName () << \"\\\"\" \n\t\t                    << \"  ...\\n\";);\n      \n      inter_analyzer_t analyzer(*m_cg, (params.run_liveness ? &m_live_map : nullptr),\n\t\t\t\tparams.widening_delay, \n\t\t\t\tparams.narrowing_iters, \n\t\t\t\tparams.widening_jumpset);\n      analyzer.Run (TDDom::top ());\n    \n      CRAB_VERBOSE_IF(1, get_crab_os() << \"Finished inter-procedural analysis.\\n\");\n      \n      // -- store invariants\n      if (params.store_invariants || params.print_invars) {\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"Storing invariants.\\n\");\n      }\n      \n      for (auto &n: boost::make_iterator_range(vertices(*m_cg))) {\n\tcfg_ref_t cfg = n.get_cfg ();\n\tif (const Function *F = m_M.getFunction(n.name())) {\n\t  \n\n\t  if (params.store_invariants || params.print_invars) {\n\t    for (auto &B : *F) {\n\t      // --- invariants that hold at the entry of the blocks\n\t      auto pre = analyzer.get_pre (cfg, &B);\n\t      update(results.premap, B, mkGenericAbsDomWrapper(pre));\n\t      // --- invariants that hold at the exit of the blocks\n\t      auto post = analyzer.get_post (cfg, &B);\n\t      update(results.postmap, B, mkGenericAbsDomWrapper(post));\n\t      \n\t      if (params.stats) {\n\t\tunsigned num_block_invars = 0;\n\t\t// TODO CRAB: for boxes we would like to use\n\t\t// to_disjunctive_linear_constraint_system() but it needs to\n\t\t// be exposed to all domains\n\t\tnum_block_invars += pre.to_linear_constraint_system().size();\n\t\tnum_invars += num_block_invars;\n\t      if (num_block_invars > 0) num_nontrivial_blocks++;\n\t      }\n\t    }\n\t    \n\t    // --- print invariants and summaries\n\t    if (params.print_invars && isTrackable(*F)) {\n\t      llvm::outs() << \"\\n\" << \"function \" << F->getName () << \"\\n\";\n\t      std::vector<std::unique_ptr<pretty_printer_impl::block_annotation>> annotations;\n\t      annotations.emplace_back(make_unique<pretty_printer_impl::invariant_annotation>\n\t\t\t\t       (m_vfac, results.premap, results.postmap,\n\t\t\t\t\tparams.keep_shadow_vars));\n\t      pretty_printer_impl::print_annotations(cfg, annotations);\t    \n\t    }\n\t  }\n\t  \n\t  // Summaries are not currently stored but it would be easy to do so.\t    \n\t  if (params.print_summaries && analyzer.has_summary (cfg)) {\n\t    auto summ = analyzer.get_summary (cfg);\n\t    crab::outs() << \"SUMMARY \" << *summ << \"\\n\";\n\t  }\n\t}\n      }\n      \n      if (params.store_invariants || params.print_invars) {\t\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"All invariants stored.\\n\");\n      }\n      \n      // --- checking assertions and collecting data\n      if (params.check) {\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"Checking assertions ... \\n\"); \n\ttypename inter_checker_t::prop_checker_ptr\n\t  prop(new assert_prop_t(params.check_verbose));\n\tif (params.check == NULLITY)\n\t  prop.reset (new null_prop_t(params.check_verbose));      \n\tinter_checker_t checker (analyzer, {prop});\n\tchecker.run ();\n\t//CRAB_VERBOSE_IF(1, checker.show (crab::outs()));\n\tresults.checksdb += checker.get_all_checks();\n\tCRAB_VERBOSE_IF(1, get_crab_os() << \"Finished assert checking.\\n\"); \n      }\n      return;\n    }\n    // Domains used for inter-procedural analysis\n    struct inter_analysis {\n      std::function<void(const AnalysisParams&, InvarianceAnalysisResults&)> analyze;\n      std::string name;\n    };\n\n    // Domains used for intra-procedural analysis\n    const std::map<std::pair<CrabDomain,CrabDomain>, inter_analysis> inter_analyses {\n        {{ZONES_SPLIT_DBM, INTERVALS},\n\t { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<split_dbm_domain_t, interval_domain_t>), \"bottom-up:zones, top-down:intervals\" }}\n      , {{ZONES_SPLIT_DBM, WRAPPED_INTERVALS},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<split_dbm_domain_t, wrapped_interval_domain_t>), \"bottom-up:zones, top-down:wrapped intervals\" }}\n      , {{ZONES_SPLIT_DBM, ZONES_SPLIT_DBM},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<split_dbm_domain_t, split_dbm_domain_t>), \"bottom-up:zones, top-down:zones\" }}\n      , {{ZONES_SPLIT_DBM, BOXES},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<split_dbm_domain_t, boxes_domain_t>), \"bottom-up:zones, top-down:boxes\" }}\n      , {{ZONES_SPLIT_DBM, OPT_OCT_APRON},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<split_dbm_domain_t, opt_oct_apron_domain_t>), \"bottom-up:zones, top-down:elina oct\" }}\n      , {{ZONES_SPLIT_DBM, PK_APRON},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<split_dbm_domain_t, pk_apron_domain_t>), \"bottom-up:zones, top-down:apron pk\" }}\n      , {{ZONES_SPLIT_DBM, TERMS_ZONES},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<split_dbm_domain_t, num_domain_t>), \"bottom-up:zones, top-down:terms+zones\" }}\n      , {{ZONES_SPLIT_DBM, TERMS_DIS_INTERVALS},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<split_dbm_domain_t, term_dis_int_domain_t>), \"bottom-up:zones, top-down:terms+dis_intervals\" }}\n      //////////////////////////////////////////////////////\n      , {{OPT_OCT_APRON, INTERVALS},\n\t { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<opt_oct_apron_domain_t, interval_domain_t>), \"bottom-up:elina oct, top-down:intervals\" }}\n      , {{OPT_OCT_APRON, WRAPPED_INTERVALS},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<opt_oct_apron_domain_t, wrapped_interval_domain_t>), \"bottom-up:elina oct, top-down:wrapped intervals\" }}\n      , {{OPT_OCT_APRON, ZONES_SPLIT_DBM},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<opt_oct_apron_domain_t, split_dbm_domain_t>), \"bottom-up:elina oct, top-down:zones\" }}\n      , {{OPT_OCT_APRON, BOXES},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<opt_oct_apron_domain_t, boxes_domain_t>), \"bottom-up:elina oct, top-down:boxes\" }}\n      , {{OPT_OCT_APRON, OPT_OCT_APRON},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<opt_oct_apron_domain_t, opt_oct_apron_domain_t>), \"bottom-up:elina oct, top-down:elina oct\" }}\n      , {{OPT_OCT_APRON, PK_APRON},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<opt_oct_apron_domain_t, pk_apron_domain_t>), \"bottom-up:elina oct, top-down:apron pk\" }}\n      , {{OPT_OCT_APRON, TERMS_ZONES},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<opt_oct_apron_domain_t, num_domain_t>), \"bottom-up:elina oct, top-down:terms+zones\" }}\n      , {{OPT_OCT_APRON, TERMS_DIS_INTERVALS},\n\t  { bind_this(this, &InterCrabLlvm_Impl::analyzeCg<opt_oct_apron_domain_t, term_dis_int_domain_t>), \"bottom-up:elina oct, top-down:terms+dis_intervals\" }}\n    };\n    \n  public:\n    \n    InterCrabLlvm_Impl(Module& M,\n\t\t       crab::cfg::tracked_precision cfg_precision,\n\t\t       heap_abs_ptr mem, llvm_variable_factory &vfac,\n\t\t       CfgManager &cfg_man, const TargetLibraryInfo &tli)\n      : m_cg(nullptr), m_M(M), m_vfac(vfac) {\n\n      std::vector<cfg_ref_t> cfg_ref_vector;\n      for (auto &F : m_M) {\n        if (!isTrackable(F)) continue;\n        // -- build cfg's \n        CfgBuilder B(F, m_vfac, *mem, cfg_precision,\n\t\t     /*include function decls and callsites*/\n\t\t     true,  &tli);\n        cfg_t *cfg = B.get_cfg();\n\tcfg_man.add(F, cfg);\n        cfg_ref_vector.push_back (*cfg);\n      }\n      // build call graph\n      m_cg = make_unique<call_graph_t>(cfg_ref_vector.begin(), cfg_ref_vector.end());\n    }\n    \n    void Analyze(AnalysisParams &params,\n\t\t const assumption_map_t &/*assumptions*/ /*unused*/,\n\t\t InvarianceAnalysisResults &results) {\n\n      // If the number of live variables per block is too high we\n      // switch to a cheap domain regardless what the user wants.\n      CrabDomain absdom =  params.dom;\n      \n      /* Compute liveness information and choose statically the\n\t abstract domain */\n      if (params.run_liveness || isRelationalDomain(absdom)) {\n\tunsigned max_live_per_blk = 0;\n\tfor (auto cg_node: boost::make_iterator_range(vertices(*m_cg))) {\n\t  auto cfg_ref = cg_node.get_cfg();\n          CRAB_VERBOSE_IF(1,\n\t\t\t  auto fdecl = cfg_ref.get_func_decl ();            \n\t\t\t  assert (fdecl);\n\t\t\t  get_crab_os() << \"Running liveness analysis for \" \n\t\t\t                << (*fdecl).get_func_name () << \"  ...\\n\";);\n\t  liveness_t* live = new liveness_t (cfg_ref);\n          live->exec ();\n          CRAB_VERBOSE_IF(1, get_crab_os() << \"Finished liveness analysis.\\n\";);\n          // some stats\n          unsigned total_live, max_live_per_blk_, avg_live_per_blk;\n          live->get_stats (total_live, max_live_per_blk_, avg_live_per_blk);\n          max_live_per_blk = std::max (max_live_per_blk, max_live_per_blk_);\n          CRAB_VERBOSE_IF(1,\n\t\t    crab::outs() << \"-- Max number of out live vars per block=\" \n                                 << max_live_per_blk_ << \"\\n\";\n\t\t    crab::outs() << \"-- Avg number of out live vars per block=\" \n                                 << avg_live_per_blk << \"\\n\";);\n          crab::CrabStats::count_max (\"Liveness.count.maxOutVars\",\n\t\t\t\t      max_live_per_blk);\n\n\t  if (isRelationalDomain(absdom)) {\n\t    // FIXME: the selection of the final domain is fixed for the\n\t    //        whole program. That is, if there is one function that\n\t    //        exceeds the threshold then the cheaper domain will be\n\t    //        used for all functions. We should be able to change\n\t    //        from one function to another.\n\t    CRAB_VERBOSE_IF(1,\n\t\t      crab::outs() << \"Max live per block: \"\n\t\t                   << max_live_per_blk << \"\\n\"\n\t\t                   << \"Threshold: \"\n\t\t                   << params.relational_threshold << \"\\n\");\n\t    if (max_live_per_blk > params.relational_threshold) {\n\t      // default domain\n\t      absdom = INTERVALS;\n\t    }\n\t  }\n\t  \n\t  if (params.run_liveness) {\n\t    m_live_map.insert(std::make_pair(cfg_ref, live));\t    \n\t  } else {\n\t    delete live;\n\t  }\n\t} // end for\n      }\n      \n      // -- run the interprocedural analysis\n      if (inter_analyses.count({params.sum_dom, params.dom})) {\n      \tinter_analyses.at({params.sum_dom, params.dom}).analyze(params, results);\n      } else {\n      \tcrab::outs() << \"Warning: abstract domains not found or enabled.\\n\"\n      \t\t     << \"Running \" << inter_analyses.at({ZONES_SPLIT_DBM, INTERVALS}).name << \"\\n\";\n      \tinter_analyses.at({ZONES_SPLIT_DBM, INTERVALS}).analyze(params, results);\t\n      }\n      \n      // free liveness map\n      if (params.run_liveness) {\n        for (auto &p : m_live_map) {\n          delete p.second;\n\t}\n      }\n    }\n  };\n\n\n  /**\n   *   Begin InterCrabLlvm methods\n   **/\n  InterCrabLlvm::InterCrabLlvm(Module &module, const TargetLibraryInfo &tli,\n\t\t\t       CfgManager &cfg_man,\n\t\t\t       crab::cfg::tracked_precision cfg_precision,\n\t\t\t       heap_abs_ptr heap_abs)\n    : m_impl(nullptr) {\n    if (!heap_abs)\n      heap_abs = boost::make_shared<DummyHeapAbstraction>();\n\n    m_impl = make_unique<InterCrabLlvm_Impl>(module, cfg_precision,\n\t\t\t\t\t     heap_abs, m_vfac, cfg_man, tli);\n  }\n\n  InterCrabLlvm::~InterCrabLlvm() {}\n\n  void InterCrabLlvm::clear() {\n    m_pre_map.clear();\n    m_post_map.clear();\n    m_checks_db.clear();\n  }\n  \n  void InterCrabLlvm::analyze(AnalysisParams &params,\n\t\t\t      const assumption_map_t &assumptions) {\n    InvarianceAnalysisResults results = { m_pre_map, m_post_map, m_checks_db};\n    m_impl->Analyze(params, assumptions, results);\n  }\n\n  wrapper_dom_ptr InterCrabLlvm::get_pre(const llvm::BasicBlock *block,\n\t\t\t\t\t bool keep_shadows) const {\n    std::vector<varname_t> shadows;\n    if (!keep_shadows)\n      shadows = std::vector<varname_t>(m_vfac.get_shadow_vars().begin(),\n\t\t\t\t       m_vfac.get_shadow_vars().end());    \n    return lookup(m_pre_map, *block, shadows);\n  }   \n\n  wrapper_dom_ptr InterCrabLlvm::get_post(const llvm::BasicBlock *block,\n\t\t\t\t\t  bool keep_shadows) const {\n    std::vector<varname_t> shadows;\n    if (!keep_shadows)\n      shadows = std::vector<varname_t>(m_vfac.get_shadow_vars().begin(),\n\t\t\t\t       m_vfac.get_shadow_vars().end());    \n    return lookup(m_post_map, *block, shadows);\n  }\n\n  const checks_db_t& InterCrabLlvm::get_checks_db() const { return m_checks_db;}\n  \n  /**\n   * End InterCrabLlvm methods\n   **/\n  \n  /**\n   * Begin CrabLlvmPass methods\n   **/\n  CrabLlvmPass::CrabLlvmPass ()\n    : llvm::ModulePass (ID), \n      m_mem(boost::make_shared<DummyHeapAbstraction>()),\n      m_tli(nullptr) { }\n\n  void CrabLlvmPass::releaseMemory () {\n    m_pre_map.clear(); \n    m_post_map.clear();\n    m_checks_db.clear();\n  }\n\n  bool CrabLlvmPass::runOnFunction (Function &F) {\n    if (!CrabInter && isTrackable(F)) {\n      IntraCrabLlvm_Impl crab(F, CrabTrackLev, m_mem, m_vfac, m_cfg_man, *m_tli);\n      InvarianceAnalysisResults results = { m_pre_map, m_post_map, m_checks_db};\n      crab.Analyze(m_params, &F.getEntryBlock(), assumption_map_t(), results);\n    }\n    return false;\n  }\n  \n  bool CrabLlvmPass::runOnModule (Module &M) {\n    #ifdef HAVE_DSA\n    m_mem.reset\n      (new LlvmDsaHeapAbstraction(M,&getAnalysis<SteensgaardDataStructures>(),\n\t\t\t\t  CrabDsaDisambiguateUnknown,\n\t\t\t\t  CrabDsaDisambiguatePtrCast,\n\t\t\t\t  CrabDsaDisambiguateExternal));\n    #endif     \n\n    m_tli = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();\n    \n    m_params.dom = CrabLlvmDomain;\n    m_params.sum_dom = CrabSummDomain;\n    m_params.run_backward = CrabBackward;\n    m_params.run_liveness = CrabLive;\n    m_params.relational_threshold = CrabRelationalThreshold;\n    m_params.widening_delay = CrabWideningDelay;\n    m_params.narrowing_iters = CrabNarrowingIters;\n    m_params.widening_jumpset = CrabWideningJumpSet;\n    m_params.stats = CrabStats;\n    m_params.print_invars = CrabPrintAns;\n    m_params.print_preconds = CrabPrintPreCond;\n    m_params.print_assumptions = CrabPrintAssumptions;\n    m_params.print_summaries = CrabPrintSumm;\n    m_params.store_invariants = CrabStoreInvariants;\n    m_params.keep_shadow_vars = CrabKeepShadows;\n    m_params.check = CrabCheck;\n    m_params.check_verbose = CrabCheckVerbose;\n    \n    CRAB_VERBOSE_IF(1,\n\t     get_crab_os() << \"Started crab-llvm\\n\"; \n             unsigned num_analyzed_funcs = 0;\n             for (auto &F : M) {\n\t       if (!isTrackable(F)) continue;\n               num_analyzed_funcs++;\n             }\n             get_crab_os() << \"Total number of analyzed functions:\" \n                           << num_analyzed_funcs << \"\\n\";);\n    \n    if (CrabInter){\n      InterCrabLlvm_Impl inter_crab(M, CrabTrackLev, m_mem, m_vfac, m_cfg_man, *m_tli);\n      InvarianceAnalysisResults results = { m_pre_map, m_post_map, m_checks_db};\n      inter_crab.Analyze(m_params, assumption_map_t(), results);\n    } else {\n      for (auto &f : M) {\n        runOnFunction (f); \n      }\n    }\n\n    if (CrabStats) {\n      crab::CrabStats::PrintBrunch (crab::outs());\n    }\n    \n    if (CrabCheck) {\n      llvm::outs() << \"\\n************** ANALYSIS RESULTS ****************\\n\";\n      print_checks(llvm::outs());\n      llvm::outs() << \"************** ANALYSIS RESULTS END*************\\n\";\n\t\t      \n      if (CrabStats) {\t\t     \n        llvm::outs() << \"\\n************** BRUNCH STATS ********************\\n\";\n        if (get_total_checks() == 0) {\n\t  llvm::outs() << \"BRUNCH_STAT Result NOCHECKS\\n\";\n        } else if (get_total_error_checks() > 0) {\n \t  llvm::outs() << \"BRUNCH_STAT Result FALSE\\n\";\n        } else if (get_total_warning_checks() == 0) {\n\t  llvm::outs() << \"BRUNCH_STAT Result TRUE\\n\";\n        } else {\n  \t  llvm::outs() << \"BRUNCH_STAT Result INCONCLUSIVE\\n\";\n        }\n        llvm::outs() << \"BRUNCH_STAT NumOfBlocksWithInvariants \"\n \t \t     << num_nontrivial_blocks << \"\\n\";\n        llvm::outs() << \"BRUNCH_STAT SizeOfInvariants \"       \n\t\t     << num_invars << \"\\n\";\n        llvm::outs() << \"************** BRUNCH STATS END *****************\\n\\n\";\n      }\n    }\n   return false;\n  }\n\n  void CrabLlvmPass::getAnalysisUsage (AnalysisUsage &AU) const {\n    AU.setPreservesAll ();\n    #ifdef HAVE_DSA\n    AU.addRequiredTransitive<SteensgaardDataStructures> ();\n    #endif \n    AU.addRequired<TargetLibraryInfoWrapperPass>();\n    AU.addRequired<UnifyFunctionExitNodes>();\n    AU.addRequired<crab_llvm::NameValues>();\n  } \n  \n  /**\n   * For crab-llvm clients\n   **/\n\n  bool CrabLlvmPass::has_cfg(llvm::Function &F) {\n    return m_cfg_man.has_cfg(F);\n  }\n  \n  cfg_ref_t CrabLlvmPass::get_cfg(llvm::Function &F) {\n    assert(m_cfg_man.has_cfg(F));\n    return m_cfg_man[F];\n  }\n  \n  // return invariants that hold at the entry of block\n  wrapper_dom_ptr\n  CrabLlvmPass::get_pre(const llvm::BasicBlock *block, bool keep_shadows) const {\n    std::vector<varname_t> shadows;\n    if (!keep_shadows)\n      shadows = std::vector<varname_t>(m_vfac.get_shadow_vars().begin(),\n\t\t\t\t       m_vfac.get_shadow_vars().end());    \n    return lookup(m_pre_map, *block, shadows);\n  }   \n\n  // return invariants that hold at the exit of block\n  wrapper_dom_ptr\n  CrabLlvmPass::get_post(const llvm::BasicBlock *block, bool keep_shadows) const {\n    std::vector<varname_t> shadows;\n    if (!keep_shadows)\n      shadows = std::vector<varname_t>(m_vfac.get_shadow_vars().begin(),\n\t\t\t\t       m_vfac.get_shadow_vars().end());    \n    return lookup(m_post_map, *block, shadows);\n  }\n\n  /**\n   * For assertion checking\n   **/\n  \n  unsigned CrabLlvmPass::get_total_checks() const {\n    return get_total_safe_checks() +  \n           get_total_error_checks() + \n           get_total_warning_checks();\n  }\n\n  unsigned CrabLlvmPass::get_total_safe_checks () const {\n    return m_checks_db.get_total_safe();\n  }\n\n  unsigned CrabLlvmPass::get_total_error_checks () const {\n    return m_checks_db.get_total_error();\n  }\n\n  unsigned CrabLlvmPass::get_total_warning_checks () const {\n    return m_checks_db.get_total_warning();\n  }\n\n  void CrabLlvmPass::print_checks (raw_ostream &o) const {\n    unsigned safe = get_total_safe_checks();\n    unsigned unsafe = get_total_error_checks ();\n    unsigned warning = get_total_warning_checks ();\n    std::vector<unsigned> cnts = { safe, unsafe, warning};\n    unsigned MaxValLen = 0;\n    for (auto c: cnts)\n      MaxValLen = std::max(MaxValLen,\n\t\t\t   (unsigned)std::to_string(c).size());\n    o << std::string((int) MaxValLen - std::to_string(safe).size(), ' ') \n      << safe << std::string (2, ' ') << \"Number of total safe checks\\n\"\n      << std::string((int) MaxValLen - std::to_string(unsafe).size(), ' ') \n      << unsafe << std::string (2, ' ') << \"Number of total error checks\\n\"\n      << std::string((int) MaxValLen - std::to_string(warning).size(), ' ') \n      << warning << std::string(2, ' ') << \"Number of total warning checks\\n\";\n  }\n\n  char crab_llvm::CrabLlvmPass::ID = 0;\n  \n} // end namespace \n\nstatic RegisterPass<crab_llvm::CrabLlvmPass> \nX (\"crab-llvm\", \"Infer invariants using Crab\", false, false);\n  \n   \n\n\n", "meta": {"hexsha": "4015127ef48ce2c65c8bcddec5fa13239e66e143", "size": 55755, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/CrabLlvm/CrabLlvm.cc", "max_stars_repo_name": "hbgit/crab-llvm", "max_stars_repo_head_hexsha": "3e51d12b5d3d079ba54e50d5fea1aed376e61659", "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": "lib/CrabLlvm/CrabLlvm.cc", "max_issues_repo_name": "hbgit/crab-llvm", "max_issues_repo_head_hexsha": "3e51d12b5d3d079ba54e50d5fea1aed376e61659", "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": "lib/CrabLlvm/CrabLlvm.cc", "max_forks_repo_name": "hbgit/crab-llvm", "max_forks_repo_head_hexsha": "3e51d12b5d3d079ba54e50d5fea1aed376e61659", "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.5127701375, "max_line_length": 157, "alphanum_fraction": 0.6514931396, "num_tokens": 14993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.191399652281004}}
{"text": "/**********************************************************************\nCopyright (c) 2017, team frAIburg\nLicensed under BSD-3.\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    * 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 <organization> 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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON 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\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n**********************************************************************/\n//\n//  map_element.hpp\n//  map elemnts used in the GlobalMap\n//      - id,types, timestamps\n//      - a polygons (boost geometry) in a local and global frame\n//        to describe the potions\n//      - updates distances, angle measurments based on the car position\n//      - simple similar check to new elements\n//      -\n//  Created by Markus on 05.07.17.\n\n#ifndef AADCUSER_FRAIBURG_MAP_ELEMENT_LIB_H_\n#define AADCUSER_FRAIBURG_MAP_ELEMENT_LIB_H_\n\n// set the maximum of points a map element can have when its fused\n#define MAP_ELEMENT_RESOURCES_MAX_NUMER_OF_POINTS 500U\n#define MAP_ELEMENT_FUSE_CNT_INFO_MSG 1000\n\n#include <math.h>\n#include <stdio.h>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"adtf_log_macros.h\"\n#include \"map_types.h\"\n\n#include <boost/version.hpp>\n#if BOOST_VERSION >= 106000\n#include <boost/qvm/mat_operations.hpp>\n#endif\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/algorithms/centroid.hpp>\n#include <boost/geometry/strategies/transform.hpp>\n#include <boost/geometry/strategies/transform/matrix_transformers.hpp>\n#include <boost/thread/mutex.hpp>\n\nnamespace frAIburg {\nnamespace map {\n\nclass __attribute__((visibility(\"default\"))) MapElement {\n public:\n    /*! created am map element defined by a polygon and type\n     *   \\param type enum type of the element\n     *   \\param local_poly define the outline of an map element, in [m]\n     *           local car frame: to the front x pos, to the left y pos,\n     *           points in clockwise order\n     *   \\param timestamp creation time\n     *   \\note -transform to a gloabal frame by calling local_to_global.\n     *         the map calls this method if not called before\n     *         -if timestamp creation time is 0, this element will be ignored\n     *          by the map in remove_elements_over_distance\n     *          and update_reposition_car()\n     *    \\note the id will bet set by the map if the element is added\n     */\n    MapElement(MapElementType type, const std::vector<tMapPoint> &local_poly,\n               tTimeMapStamp timestamp = 0);\n\n    /*! see above MapElement(...)\n     *   \\param local_orientation_angle set and enable a angle angle, in [rad],\n     *            angle is define zero at front and positive vals to the left\n     */\n    MapElement(MapElementType type, const std::vector<tMapPoint> &local_poly,\n               tTimeMapStamp timestamp, tMapData local_orientation_angle);\n\n    virtual ~MapElement(){};  // polymorphic class to enable dynamic_cast child\n                              // types\n\n public:\n    /* user_tag_ which can be set by the user to add addtion information      */\n    std::string user_tag_;\n\n    /* user_tag_ which will be shown instelead of the type name in the map ui */\n    std::string user_tag_ui_;  // use only in debug mode\n    /* user color for the ui, poly fill color and outer line\n     * valid names: https://www.w3.org/TR/SVG/types.html#ColorKeywords */\n    std::string user_color_ui_;  // use only in debug mode\n\n    /*! check if the elemnt is one from the given types\n    *   \\param types types to check\n    *   \\return true if the elemnt is one of the types in the vector\n    */\n    bool IsType(const std::vector<MapElementType> &types) const;\n\n    /*! calculate distance to MapElement\n    *   \\param MapElement el to comapre with\n    *   \\param to_center true distance form the center, else closest distance\n    *   \\note update_mutex_ is used\n    *   \\note if the elements are Disjoint and to_center = false, the distatnce\n    *         is zero\n    *   \\return distance\n    */\n    tMapData GlobalDistance(const MapElement &el, bool to_center = true);\n\n    /*! calculate distance to Point\n    *   \\param MapElement el to comapre with\n    *   \\param to_center true distance form the center, else closest distance\n    *   \\note update_mutex_ is used\n    *   \\return distance\n    */\n    tMapData GlobalDistance(const tMapPoint &p, bool to_center = true);\n\n    /* check if elements are disjoint in the global frame\n     * \\note check with if(!el->GlobalPolyDisjoint(el2)) for collisions\n     */\n    bool GlobalPolyDisjoint(const MapElement &p);\n    /* check if a map point is disjoint in the global polyon frame\n     */\n    bool GlobalPolyDisjoint(const tMapPoint &p);\n\n    /* check if other element is (complitly) within the global polygon*/\n    bool GlobalPolyWithin(const MapElement &p);\n    /* check if other element is touches the outer line of the global polygon*/\n    bool GlobalPolyTouches(const MapElement &p);\n    bool GlobalPolyOverlaps(const MapElement &p);\n\n    /* \\return true if local_orientation_angle was used in the constructor*/\n    bool IsOrientationUsed() const;\n    /* return the angle of the element in the global fram in [rad]*/\n    tMapData GetGlobalOrientation() const;\n\n    tMapData GetArea() const;\n    /* \\return an copy of the polygon in the global frame */\n    tMapPolygon GetGlobalPoly() const;\n\n    /* \\return polygon center in the global frame if transfromed from local to\n     *    global before\n     *  EXAMPLE: tMapPoint center = el->GetGlobalPolyCenter();\n     *           tMapData x = center.get<0>();\n    //  *           tMapData y = center.get<1>();\n     */\n    tMapPoint GetGlobalPolyCenter() const;\n\n    /*! orientation angle based on the poly center point from -pi to pi\n     * returns zero if the element is in the front, negative value to the right\n     */\n    tMapData GetOrientationAngleToCar() const;\n\n    /* ret the distance to the center of the poly form the last update call\n       with car pos\n      \\note distance and angle updated by the map with the call of Update\n    */\n    tMapData GetDistanceToCar() const;\n    tMapData GetPreviousDistanceCar() const;\n\n    /*! return prejedted distance based on the OrientationAngleToCar of the last\n     *  Update() call\n     */\n    tMapData ProjectedDistanceToCar() const;\n\n    tTimeMapStamp GetUpdateTime() const;\n    tTimeMapStamp GetCreateTime() const;\n\n    MapElementType GetType() const;\n\n    /*! return how often the element was fused */\n    unsigned int GetFuseCount() const;\n\n    /*! element string for the element with different information*/\n    virtual std::string ToString() const;\n\n    /*! set a live time for the map element, after this time the map deletes\n    *    the element\n    *   \\param life_time_microseconds set a live time of the element\n    *   \\param start_time_microseconds optinal start time of the life time,\n    *          use if AFTER the element is GlobalMap::AddFuseElement to\n    * overwrite\n    *          the life time if fused\n    *   \\note call BEFORE the element is GlobalMap::AddFuseElement map if\n    *         life time reset wanted with fuse start_time_microseconds\n    *   \\note call AFTER the element is GlobalMap::AddFuseElement map if\n    *         life time reset form creation time of the first element added to\n    *          the map\n    *   \\note creation timestamp must no be zero if used or negative\n    *   \\note map delets then the element with RemoveAllElementsOverLifeTime\n    *   \\note if elements if fused the life time setting of the new elment will\n    *         be taken\n    *   \\note once enableld the life time can not disabled\n    */\n    void EnableTimeOfLife(tTimeMapStamp life_time_microseconds,\n                          tTimeMapStamp *start_time_microseconds = NULL);\n    bool IsOverTimeOfLive(tTimeMapStamp time_microseconds);\n\n    /*! get the ID of the alement\n    *   \\note call after element was added to the map\n    *   \\note the id will bet set by the map\n    */\n    tMapID GetID() const;\n\n    /*! set if the elment is updated in a map repostion jump,\n       call after the element is added to the map, in case the of a fusion,\n       the default is ture\n    */\n    void SetUpdateWithRepostionJumps(bool set);\n\n    // FUNCTION CALLED BY THE MAP:\n\n    /*! set the ID of the alement\n    *   \\note the id will bet set by the map if the element is added\n    */\n    void SetID(tMapID id);\n\n    /*! transfrom the local polygon and angle if set a glabale frame\n    *   \\param tMapCarPosition position of the car to transformation\n    *   \\note only use this there is a long time needed for data porcessing:\n    *         save the car postion with the sensor information and\n    *         perform the tranfromation after the computation\n    *   \\note this method is called by the map, unless it was called before\n    *   \\note element update time stamp is set to car pos time_pos_update\n    *   \\note update_mutex_ is used\n    */\n    void LocalToGlobal(const tMapCarPosition &global_car_pos);\n\n    /*! transfrom the globale polygon, trans and roation based on car pos\n     *  \\note distance and angle to car is not updated\n     *  \\note element update time stamp is set to car pos time_pos_update\n     *  \\note update_mutex_ is used\n     */\n    void TransfromGlobal(const tMapCarPosition &global_car_pos);\n\n    /*! rotate the globale polygon, angle in rad\n     *  \\note distance and angle to car is not updated\n     *  \\note update_mutex_ is used\n     */\n    void RotateAroundCenterGlobal(const tMapData angle_clockwise,\n                                  tTimeMapStamp t = 0);\n\n    /*! rotate the globale polygon, angle in rad\n     *  \\note distance and angle to car is not updated\n     *  \\note update_mutex_ is used\n     */\n    void RotateAroundCenterThenTranslateGlobal(\n        const tMapData angle_rad_clockwise, const tMapData trans_x,\n        const tMapData trans_y, tTimeMapStamp t = 0);\n\n    /*! update global position distance and angle to the car\n     *   \\param tMapCarPosition position update of the car\n     *   \\note timestamp is set to the global_car_pos time_pos_update\n     *   \\note this method is called by the map\n     *   \\note update_mutex_ is used\n     */\n    void Update(const tMapCarPosition &global_car_pos);\n\n    /*! combines the GLOBAL polygon with a diffrent element,\n     *  user_tag_ and user_tag_ui_ will be used from the element to fuse with\n     *   \\param type enum type of the element\n     *   \\param element_fuse to fuse with\n     *   \\param local_poly define the, ob\n     *           local car frame: to the front x pos, to the left y pos,\n     *           points in clockwise order\n     *   \\param timestamp creation time\n     *   \\param fuse_type MAP_FUSE_APPEND, polygon points will be appended.\n     *                    MAP_FUSE_REPLACE, replace the polygon\n     *                    MAP_FUSE_FIXED_POINT_MEAN, number of points stays\n     *                     same by computing the mean,\n     *                     point number and order must be the same\n     *   \\return MapFuseReturn to inform the map if which element to keep in\n     *           the map\n     *   \\note  this method is called by the map\n     *   \\note user_tag_, user_tag_ui_, user_color_ui_ will be change to\n     *        the one of element_fuse if not empty\n     *   \\note update_mutex_ is used\n     */\n    virtual MapFuseReturn UpdateFuse(const tMapCarPosition &global_car_pos,\n                                     MapElement &element_fuse,\n                                     tTimeMapStamp timestamp = 0,\n                                     MapFuseType fuse_type = MAP_FUSE_APPEND);\n\n    /*! check if element are similar based of area, type and center distance\n    *   \\note  the map calls IsSimilar to check if elements should be fused\n    *          child classes can change this func to fuse with differnt types\n    *   \\param MapElement element to compare with\n    *   \\param tolerance_distance max distance between the two elements,\n    *            -1 to ignore\n    *   \\param tolerance_area,-1 to ignore\n    *            note area might change if element s were fuesed before\n    *   \\param similar_fuse true to check if the elements should\n    *          be fused: the type must be same,\n    *          if fuse the type of the elment is ignored\n    *   \\return true if the element are similar based on the args\n    */\n    virtual bool IsSimilar(const MapElement &el,\n                           tMapData tolerance_distance = 0.1,\n                           tMapData tolerance_area = -1,\n                           bool similar_fuse = true);//TODO as const\n\n    /*! simialr factor based on distance, type and area\n    *   \\param MapElement element to compare with\n    *   \\return simialr factor based on distance, type and area\n    *   \\note update_mutex_ is used\n    */\n    float SimilarFactor(const MapElement &el);\n\n    /*! return ture if the element should be updated in a repostion jump*/\n    bool IsUpdateWithRepostionJumpEnabled() const;\n\n private:\n    /* mutx car pos update and vector updated */\n    boost::mutex update_mutex_;\n    /* type of element */\n    const MapElementType type_;\n    /* id of the element wich can be set by the map*/\n    tMapID id_;\n    /* keep track if the angle for the map element is set in a\n     construtctor*/\n    const bool element_angle_used_;\n\n    /*counter with the indicates how often the element was fused*/\n    unsigned int fused_cnt_;\n    tMapData fuse_center_mean_decay_weight_factor_;\n    bool update_with_repostion_jump_;\n    tMapData fuse_sin_global_mean_;\n    tMapData fuse_cos_global_mean_;\n\n    /* local positions and oriantation of the element*/\n    tMapPolygon local_element_polygon_;\n    tMapData local_element_orientation_angle_;\n\n    /* global position and oriantation of the element*/\n    tMapPolygon global_element_polygon_;\n    tMapPoint global_element_polygon_center_;\n    tMapData global_element_orientation_angle_;  // in rad\n    // zero if the element is in the front, to the right negative, updated\n    tMapData orientation_angle_to_car_;  // in rad\n\n    /* distance to the last update car position of the center of the poly */\n    tMapData car_distance_;\n    tMapData car_distance_previous_;\n    // tMapData hight_;//TODO(markus) needed?\n\n    /* save the last calculated area*/\n    tMapData polygon_area_;\n\n    /// TIMESTAMPS\n    /* creation timestamp set in the construtctor */\n    const tTimeMapStamp timestamp_create_microseconds_;\n    /* creation timestamp for the last update for the element */\n    tTimeMapStamp timestamp_update_microseconds_;\n    tTimeMapStamp timestamp_of_life_microseconds_;\n    tTimeMapStamp timestamp_start_life_microseconds_;\n\n    bool time_of_life_is_used_;\n    bool time_of_life_reset_with_fuse_;\n\n    /*! init func, for multiple contributors, c11 is not used */\n    void Init(const std::vector<tMapPoint> &local_poly);\n\n    /*! calculate the areo of the polygon*/\n    void UpdateArea();\n\n    /*! set the decrete orientation to the last update position\n     */\n    void UpdateOrientationToCar(const tMapCarPosition &global_car_pos);\n\n    /*calculate the inear distance to the car pos and saved center of the global\n     * polygon */\n    void UpdateDistanceToCar(const tMapCarPosition &global_car_pos);\n    /*calculate the center of the gobal polygon*/\n    void UpdateGlobalPolyCenter();\n\n    /*! change the global angle of the map el in clockwise in rad*/\n    void DoAngleRotation(const tMapData angle_diff_rad_clockwise);\n\n    /*! transforamtion of the local to the gloabal car coord based on the\n     *  current car pos */\n    void Transformation(const tMapPolygon &poly_from, tMapPolygon &poly_to,\n                        const tMapCarPosition &global_car_pos);\n\n    /// FUSE FUNCTIONS all are using update_mutex_\n    void DoFuseReplace(const MapElement &p);\n    void DoFuseAppend(const MapElement &p);\n\n    /*fuse with fix number of points and same area\n      decay_factor to -1 to disable, if not and between 1 and zero\n      the new center poly is computed:\n       new_center=(old_mean * decay_factor + new)\n                    / (old_mean * decay_factor + 1 )\n    */\n    void DoFuseCenterMean(const MapElement &p,\n                          const tMapData decay_factor = -1.);\n\n    void DoFuseExpDecay(MapElement const &p, const tMapData decay_factor);\n    /*! creats a convex hull of two poly, -1 to disable simplify.\n    simplify_distance (in units of input coordinates)\n    of a vertex to other segments to be removed\n    */\n    void DoFuseConvecHull(const MapElement &p,\n                          const tMapData simplify_distance = -1.);\n    /*enable time of life if set for one element and\n      use the time of life and creation time form p (the new element)*/\n    void DoTimeOfLifeFuse(const MapElement &p);\n};\n}\n} /*NAME SPACE frAIburg,map*/\n\n#endif /* AADCUSER_FRAIBURG_MAP_ELEMENT_LIB_H_ */\n", "meta": {"hexsha": "a27277ea167d4131d13aeb1bb12444dbe1236473", "size": 18113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "aadcUser/lib_map/map_element.hpp", "max_stars_repo_name": "PhilJd/frAIburg", "max_stars_repo_head_hexsha": "7585999953486bceb945f1eb7a96cbe94ea72186", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-11-21T09:34:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T21:15:28.000Z", "max_issues_repo_path": "aadcUser/lib_map/map_element.hpp", "max_issues_repo_name": "PhilJd/frAIburg", "max_issues_repo_head_hexsha": "7585999953486bceb945f1eb7a96cbe94ea72186", "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": "aadcUser/lib_map/map_element.hpp", "max_forks_repo_name": "PhilJd/frAIburg", "max_forks_repo_head_hexsha": "7585999953486bceb945f1eb7a96cbe94ea72186", "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.2214452214, "max_line_length": 80, "alphanum_fraction": 0.6818859383, "num_tokens": 4195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1913579235446116}}
{"text": "/** Boost */\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/unordered_map.hpp>\n#include <boost/serialization/unordered_set.hpp>\n#include <boost/serialization/utility.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n/** STL */\n#include <chrono>\n#include <condition_variable>\n#include <future>\n#include <mutex>\n#include <thread>\n#include <vector>\n\n/** Ligero */\n#include \"Common.hpp\"\n\n#include \"EncryptedClient.hpp\"\n#include \"EncryptedCoordinator.hpp\"\n\n#include \"ZkArgument.hpp\"\n#include \"protocol/ExpressNPStatement.hpp\"\n\n#include \"FiniteFields.hpp\"\n#include \"Hash.hpp\"\n#include \"SecretSharingNTT.hpp\"\n\nusing namespace ligero;\nusing namespace std::chrono_literals;\n\n/** ===== Thread synchronization ===== */\nstd::mutex mutex;\nstd::condition_variable cv;\nbool thread_aborted = false;\n\n/** Parameters RSA Ceremony */\n/** ======================= */\n\nconstexpr auto degree = 1 << 16;\nconstexpr auto p = 9;\nconstexpr auto q = 21;\nconstexpr auto sigma = 8;\nconstexpr auto lambda = 128;\nconstexpr auto tau_limit_bit = 175;\nconstexpr auto tau = 1000;\nconstexpr auto numCandidates = 2048;\n\n/** throughput parties */\nconstexpr auto wait_timeout = 300 * 1000; /* wait 5 min when start */\nconstexpr auto timeout = 25 * 1000;       /* a little longer than test */\nconstexpr auto data_size = 32 * 1024;     /* 32 KB */\nconstexpr auto nb_max_send = 1024;\nconstexpr auto parties = 1;\n\n/** throughtput coordinator */\nconstexpr auto pbs = 1000;\nconstexpr auto duration = 20s;\nconstexpr auto wait_time = 120s;\nconstexpr auto cleanup_time = 5s;\nconstexpr auto throughput_cutoff = 100 * 1024; /* 200 KB/s */\n\nconstexpr auto receive_timeout = 60min;\n\n/** Parameters Zero-Knowledge */\n/** ========================= */\n\n/** Settings Zero-Knowledge */\nRegularInteger p_zk(10514644122014433281ULL);\ntypedef Fpp_Fixed<p_zk> FieldT;\n\nzksnark::InterleavedRSCode irs;        /** Reed-Solomon Interleaved Code */\nligero::MTParameters<FieldT> mtParams; /** Merkle Tree Parameters */\nconstexpr size_t l = 8192;             // 4096;             /** Bloc size */\nconstexpr size_t k = 16384;            // 8192;             /** Degree */\nconstexpr size_t n = 65536;            // 16384;            /** # of Shares */\n\n/** Columns to Open Up (By default half the columns) */\nconstexpr size_t t = 189;\nconstexpr auto ptNumberEvaluation = 3;\n\n/** Random Generator */\nconst hash::HashIntegerSeedGeneratorF<FieldT>& fieldGenerator =\n    hash::blake2bIntegerSeedGenerator<FieldT>;\nconst hash::HashStringSeedGeneratorF& stringGenerator = hash::blake2bStringHash;\n\n/** Threading */\nconstexpr size_t maxNumberThreads = 50;\n/** [m5.metal has 96 threads over 48 cores] */\n\n/** Selecting a port for distributed verifying */\nconstexpr char* port = \"5556\";\n\n/** Depositing the data here */\nPublicData pdata;\nSigmaProtocolPublicData spdata;\nstd::vector<ligero::zksnark::FullFSTranscript<FieldT>> transcripts;\nsize_t availableTranscriptsIndex = 0;\nbool firstIteration = true;\n\nstd::string localIpAddr = \"UNKNOWN\";\n\n/** Stitching Proofs */\nconstexpr int nbIterations = 3;\nconstexpr int nbVarsStitched = 4;\nconstexpr int nbBlocksPerVar = degree / l;\n\n/** Data */\nstd::string hashedPublicData;\n\nvoid resetGlobalVariables() {\n  pdata = PublicData{};\n  transcripts.clear();\n  availableTranscriptsIndex = 0;\n  firstIteration = true;\n  thread_aborted = false;\n  hashedPublicData.clear();\n}\n\n/** This separate function handles the data coming in from the coordinator, as\n * well as sigma protocol verification. The concern is that otherwise we might\n * fall behind on receiving public data & proof because of processing delays.\n * @param transport the transport object handling communication with the\n * coordinator\n */\nvoid collectData(ZeroMQClientTransport& transport) {\n  DBG(\"Verifier \" << transport.getSocketId() << \" begining data acquisition.\");\n\n  /** Tell the gathering coodrinator we are ready */\n  if (firstIteration) transport.send(MessageType::VERIFIER_READY, localIpAddr, false);\n\n  /** Receive Sigma Protocol Public Data */\n  auto maybe_sigma = transport.awaitReply<SigmaProtocolPublicData>(\n      MessageType::GATHER_SIGMA_DATA, true);\n\n  if (hasError(maybe_sigma)) {\n    LOG(ERROR) << \"Kill/Restart received\";\n    thread_aborted = true;\n    cv.notify_one();\n    return;\n  } else {\n    spdata = getResult(maybe_sigma);\n  }\n\n  /** Receive public data */\n  auto maybe_pdata =\n      transport.awaitReply<PublicData>(MessageType::GATHER_PUBLIC_DATA, true);\n\n  if (hasError(maybe_pdata)) {\n    LOG(ERROR) << \"Kill/Restart received\";\n    thread_aborted = true;\n    cv.notify_one();\n    return;\n  } else {\n    pdata = getResult(maybe_pdata);\n    DBG(\"Received and deserialized public data.\");\n\n    /** Hashing Public Data */\n    pdata.modulusIdx = 0;\n    pdata.roots.clear();\n    pdata.ptNumberEvaluation = ptNumberEvaluation;\n    hashedPublicData = hash::hashPublicData(stringGenerator, pdata, spdata);\n  }\n\n  /** Verify Sigma Protocol */\n  LOG(INFO) << \"Verifying Sigma protocol proof\";\n\n  auto [alphasGCD, _drop_val] =\n      math::fixed_bucket_n_primes(3210, primesGCD, 175);\n  std::vector<mpz_class> coefs;\n  std::vector<mpz_class> nfl_primes;\n  std::vector<mpz_class> nfl_primes_full;\n  for (int i = 0; i < 9; i++)\n    nfl_primes.emplace_back(mpz_class(nfl::params<uint64_t>::P[i]));\n  for (int i = 0; i < NbPrimesQ; i++)\n    nfl_primes_full.emplace_back(mpz_class(nfl::params<uint64_t>::P[i]));\n\n  /** Recomputing the final candidate from the CRT factors */\n  std::vector<mpz_class> finalModuli_GCD;\n  finalModuli_GCD.resize(alphasGCD.size());\n  for (int alphaGCDidx = 0; alphaGCDidx < alphasGCD.size(); alphaGCDidx++) {\n    std::vector<mpz_class> prime_decomp_f;\n    for (int i = 0; i < NbPrimesQ; i++) {\n      prime_decomp_f.emplace_back(\n          mpz_class(pdata.finalModuli_GCD[alphaGCDidx * NbPrimesQ + i]));\n    }\n    finalModuli_GCD[alphaGCDidx] =\n        math::crt_reconstruct(prime_decomp_f, coefs, nfl_primes_full);\n  }\n  std::vector<mpz_class> candidates;\n  candidates.emplace_back(\n      math::crt_reconstruct(finalModuli_GCD, coefs, alphasGCD));\n\n  /** Recomputing the gamma values */\n  mpz_class gammaSeed = pdata.gammaSeed;\n  std::vector<mpz_class> gammaValues;\n  gammaValues.resize(candidates.size() * 128);\n  std::vector<mpz_class> engine =\n      math::generateRandomVector(gammaSeed, kJacobiNumberOfRandomValues, 2048);\n  mpz_t one;\n  mpz_init(one);\n  mpz_set_ui(one, 1);\n  size_t engineCount = 0;\n\n  {\n    mpz_t gcdResult;\n    mpz_init(gcdResult);\n\n    for (int i = 0; i < candidates.size(); ++i) {\n      const mpz_class& N = candidates[i];\n\n      DBG(\" N % 2 = 1; N = \" << N);\n      /** We expect that N is 3 (mod 4), and therefore must be odd. */\n      assert(N % 2 == 1);\n\n      int foundGamma = 0;\n      while (foundGamma < 128) {\n        mpz_class g = engine[engineCount];\n        ++engineCount;\n        if (engineCount >= engine.size()) {\n          engineCount = 0;\n          DBG(\"Regenerating random values for Jacobi (GCD) gamma values\");\n          engine = math::generateRandomVector(\n              engine[0], kJacobiNumberOfRandomValues, 2048);\n        }\n        g = g % N;\n        assert(g != 0);\n\n        DBG(\"g = \" << g);\n        if (mpz_jacobi(g.get_mpz_t(), N.get_mpz_t()) == 1) {\n          gammaValues[i * 128 + foundGamma] = g;\n          foundGamma++;\n        }\n      }\n\n      /** Sanity check, assert if gcd(gammaValues[i], N) == 1 */\n      for (int j = 0; j < 128; ++j) {\n        mpz_gcd(gcdResult, gammaValues[i * 128 + j].get_mpz_t(), N.get_mpz_t());\n        assert(mpz_cmp(gcdResult, one) == 0);\n      }\n    }\n\n    mpz_clear(one);\n    mpz_clear(gcdResult);\n  }\n  for (int j = 0; j < 128; j++) {\n    std::vector<mpz_class> sigma_a_GCD;\n    sigma_a_GCD.resize(alphasGCD.size());\n    std::vector<mpz_class> sigma_e_GCD;\n    sigma_e_GCD.resize(alphasGCD.size());\n    std::vector<mpz_class> sigma_z_GCD;\n    sigma_z_GCD.resize(alphasGCD.size());\n    std::vector<mpz_class> sigma_g_GCD;\n    sigma_g_GCD.resize(alphasGCD.size());\n    for (int alphaGCDidx = 0; alphaGCDidx < alphasGCD.size(); alphaGCDidx++) {\n      std::vector<mpz_class> prime_decomp_a;\n      std::vector<mpz_class> prime_decomp_e;\n      std::vector<mpz_class> prime_decomp_z;\n      std::vector<mpz_class> prime_decomp_g;\n      for (int i = 0; i < 9; i++) {\n        prime_decomp_a.emplace_back(\n            mpz_class(spdata.sigmaaGCD[i * 128 * alphasGCD.size() +\n                                       j * alphasGCD.size() + alphaGCDidx]));\n        prime_decomp_e.emplace_back(\n            mpz_class(spdata.sigmaeGCD[i * 128 * alphasGCD.size() +\n                                       j * alphasGCD.size() + alphaGCDidx]));\n        prime_decomp_z.emplace_back(\n            mpz_class(spdata.sigmazGCD[i * 128 * alphasGCD.size() +\n                                       j * alphasGCD.size() + alphaGCDidx]));\n        prime_decomp_g.emplace_back(\n            mpz_class(spdata.sigmagGCD[i * 128 * alphasGCD.size() +\n                                       j * alphasGCD.size() + alphaGCDidx]));\n      }\n      sigma_a_GCD[alphaGCDidx] =\n          math::crt_reconstruct(prime_decomp_a, coefs, nfl_primes);\n      sigma_e_GCD[alphaGCDidx] =\n          math::crt_reconstruct(prime_decomp_e, coefs, nfl_primes);\n      sigma_z_GCD[alphaGCDidx] =\n          math::crt_reconstruct(prime_decomp_z, coefs, nfl_primes);\n      sigma_g_GCD[alphaGCDidx] =\n          math::crt_reconstruct(prime_decomp_g, coefs, nfl_primes);\n    }\n    mpz_class sigmaa = math::crt_reconstruct(sigma_a_GCD, coefs, alphasGCD);\n    mpz_class sigmae = math::crt_reconstruct(sigma_e_GCD, coefs, alphasGCD);\n    mpz_class sigmaz = math::crt_reconstruct(sigma_z_GCD, coefs, alphasGCD);\n    mpz_class sigmag = math::crt_reconstruct(sigma_g_GCD, coefs, alphasGCD);\n    mpz_class sigma_lhs = math::powm(gammaValues[j], sigmaz, candidates[0]);\n    mpz_class sigma_rhs = math::mod(\n        sigmaa * math::powm(sigmag, sigmae, candidates[0]), candidates[0]);\n\n    assert(sigma_lhs == sigma_rhs);\n  }\n\n  LOG(INFO) << \"Verified Sigma protocol proof\";\n\n  for (size_t modulusIdx = 0; modulusIdx < q; modulusIdx++) {\n    /** Receive proofs */\n    auto maybe_proof =\n        transport.awaitReply<ligero::zksnark::FullFSTranscript<FieldT>>(\n            MessageType::GATHER_PROOFS, true);\n\n    if (hasError(maybe_proof)) {\n      LOG(ERROR) << \"Kill/Restart received\";\n      thread_aborted = true;\n      cv.notify_one();\n      return;\n    } else {\n      /** get lock and notify verifier */\n      std::unique_lock<std::mutex> lock(mutex);\n\n      transcripts.push_back(getResult(maybe_proof));\n      availableTranscriptsIndex++;\n\n      lock.unlock();\n      cv.notify_one();\n    }\n  }\n\n  LOG(INFO) << \"Got all proofs\";\n\n  return;\n}\n\n/** This function verifies the proofs as they are gathered as well as\n * cross-moduli integrity constraints (\"stitching\")\n * @param transport the transport object handling communication with the\n * coordinator\n * @param myTimers reference to the timers to use for this run\n * @return Unit if successful\n */\nexpected<Unit> verify(ZeroMQClientTransport& transport, timers& myTimers) {\n  /** Reset all global variables */\n  resetGlobalVariables();\n\n  /** Verifying */\n  /** ================================================================ */\n  FieldT::modulusIdx_ = 0;\n  size_t aggregateSuccess = 0;\n\n  Statements statement = Statements::RSACeremony;\n  Statements localStatement = statement;\n\n  /** Primitive Roots of Unity for All Moduli */\n  nfl::poly_p<uint64_t, degree, q> roots({0});\n  for (size_t idx = 0; idx < q; idx++) {\n    roots(idx, 1) = 1ull;\n  }\n  roots.ntt_pow_phi();\n\n  ligero::zksnark::FullFSTranscript<FieldT> transcript;\n\n  SecretData sdata;\n\n  /** Dimensioning ai scalars */\n  sdata.ai.resize(nbIterations);\n  for (size_t iter = 0; iter < nbIterations; iter++) {\n    sdata.ai[iter].resize(nbVarsStitched);\n    for (size_t var = 0; var < nbVarsStitched; var++) {\n      sdata.ai[iter][var].resize(nbBlocksPerVar);\n      for (size_t block = 0; block < nbBlocksPerVar; block++) {\n        sdata.ai[iter][var][block].resize(l);\n      }\n    }\n  }\n\n  /** Storing the results of the verification per modulus */\n  std::vector<int> report(q, 0);\n\n  /** Import Public Data */\n  std::thread* dataCollection =\n      new std::thread(collectData, std::ref(transport));\n\n  /** CRT representation to check integrity for the proofs */\n  std::vector<mpz_class> stitchingCRT;\n  mpz_class stitching0;\n\n  for (size_t modulusIdx = 0; modulusIdx < q; modulusIdx++) {\n    std::string timerVerificationIdle =\n        std::string(\"6.a. verification, idle, modulus \") +\n        std::to_string(modulusIdx);\n    myTimers.begin(1, timerVerificationIdle.c_str(), 0);\n\n    {\n      /** get lock and wait for complete */\n      std::unique_lock<std::mutex> lock(mutex);\n      auto received = cv.wait_for(lock, receive_timeout, [&] {\n        return thread_aborted || (availableTranscriptsIndex > modulusIdx);\n      });\n\n      /** check if thread failed or timeout */\n      /** we won't restart this verifier because the corresponding party will be\n       */\n      /** kicked out */\n      if (thread_aborted || !received) {\n        LOG(INFO) << \"Working thread failed or timed out, quit verifier\";\n        dataCollection->join();\n        delete dataCollection;\n        return Error::TIMED_OUT;\n      }\n\n      lock.unlock();\n    }\n\n    myTimers.end(1, timerVerificationIdle.c_str(), 0, true);\n\n    std::string timerVerificationCompute =\n        std::string(\"6.a. verification, compute, modulus \") +\n        std::to_string(modulusIdx);\n    myTimers.begin(1, timerVerificationCompute.c_str(), 0);\n\n    auto& transcript = transcripts[modulusIdx];\n    bool success = true;\n\n    LOG(INFO) << \"Verifying modulus idx:\" << modulusIdx;\n\n    /** Zero-Knowledge */\n    p_zk = nfl::params<uint64_t>::P[modulusIdx];\n    FieldT::modulusIdx_ = modulusIdx;\n    FieldT::preprocessing(log2(n) + 1);\n\n    pdata.modulusIdx = modulusIdx;\n\n    /** For portions 7 to 12, only run the first 9 moduli */\n    if ((localStatement == Statements::RSACeremony) && (pdata.modulusIdx > 8))\n      localStatement = Statements::RSACeremony_Rounds3to6;\n\n    /** Roots of Unity */\n    pdata.roots.assign(\n        roots.poly_obj().data() + pdata.modulusIdx * (size_t)roots.degree,\n        roots.poly_obj().data() +\n            (pdata.modulusIdx + 1) * (size_t)roots.degree);\n    pdata.ptNumberEvaluation = ptNumberEvaluation;\n\n    zksnark::Verifier<FieldT> verifier(\n        localStatement, irs, t, l, fieldGenerator, stringGenerator, mtParams,\n        pdata, spdata, sdata, permut<k>::compute, permut<n>::compute,\n        hashedPublicData);\n\n    try {\n      verifier.verifyProof(transcript);\n\n      LOG(INFO) << \"Verifier mod \" << modulusIdx << \":\" << verifier._stitching;\n    } catch (failedTest& e) {\n      DBG(\"Failed Test: \" << e.what());\n      success = false;\n    }\n\n    if (modulusIdx == 0) {\n      stitching0 = verifier._stitching;\n    } else {\n      stitchingCRT.push_back(verifier._stitching);\n    }\n\n    if (success) {\n      LOG(INFO) << \"Verification for modulus idx:\" << modulusIdx\n                << \" succeeded\";\n      report[modulusIdx] = 1;\n      aggregateSuccess++;\n    } else {\n      LOG(INFO) << \"Verification for modulus idx:\" << modulusIdx << \" failed\";\n      report[modulusIdx] = 0;\n    }\n\n    myTimers.end(1, timerVerificationCompute.c_str(), 0, true);\n  }\n\n  /** Cross-Moduli Verification */\n  {\n    bool success = false;\n    std::vector<mpz_class> mods, coefs;\n    for (size_t i = 1; i < q; i++) {\n      mods.emplace_back(params<uint64_t>::P[i]);\n    }\n    success = (math::mod(stitching0 -\n                             math::crt_reconstruct(stitchingCRT, coefs, mods),\n                         mpz_class(params<uint64_t>::P[0])) == mpz_class(0));\n\n    if (success) {\n      LOG(INFO) << \"Verification for cross-moduli integrity succeeded\";\n    } else {\n      LOG(INFO) << \"Verification for cross-moduli integrity failed\";\n      for (size_t idx = 0; idx < q; idx++) {\n        report[idx] = 0;\n      }\n      aggregateSuccess = 0;\n    }\n  }\n\n  dataCollection->join();\n  delete dataCollection;\n\n  /** Wait for the signal from the gathering coordinator */\n  auto maybe_response_reports = transport.awaitReply();\n\n  if (hasError(maybe_response_reports)) {\n    if (getError(maybe_response_reports) == Error::RESTART) {\n      LOG(INFO) << \"Restart verifier\";\n      myTimers.reset();\n      return verify(transport, myTimers);\n    } else {\n      LOG(INFO) << \"Timed out\";\n      return Unit{};\n    }\n  } else {\n    if (getResult(maybe_response_reports) != MessageType::GATHER_REPORTS) {\n      LOG(ERROR) << \"Out of sequence message received when expecting gathering \"\n                    \"reports, aborting.\";\n      return Error::OUT_OF_SYNC;\n    }\n  }\n\n  if (aggregateSuccess == q) {\n    LOG(INFO) << \"All proofs successfully verified.\";\n  } else {\n    LOG(INFO) << \"Failed to verify some of the proofs.\";\n  }\n\n  /** Send the verifier report to the gathering coordinator */\n  transport.send<std::vector<int>>(MessageType::VERIFIER_REPORT, report, false);\n\n  /** Finally wait for restart message if any verification failed */\n  auto maybeRestart = transport.awaitReply();\n\n  if (hasError(maybeRestart) && getError(maybeRestart) == Error::RESTART) {\n    LOG(INFO) << \"Restart message received, restarting verifier\";\n    myTimers.reset();\n    return verify(transport, myTimers);\n  } else if (getResult(maybeRestart) == MessageType::END) {\n    LOG(INFO) << \"All done.\";\n    return Unit{};\n  } else {\n    LOG(INFO) << \"Unknown error happened!\";\n    return Error::UNKNOWN_ERROR;\n  }\n}\n\nint main(int argc, char** argv) {\n  std::string coordinatorIP(\"127.0.0.1\");\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help\", \"produce help message\")(\n      \"localIPaddress\", po::value<std::string>(), \"sets the local IP address\")(\n      \"ip\", po::value<std::string>(), \"coordinator IP address\");\n\n  po::variables_map vm;\n  po::positional_options_description p;\n  p.add(\"coordinator-ip\", -1);\n\n  po::store(\n      po::command_line_parser(argc, argv).options(desc).positional(p).run(),\n      vm);\n\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    LOG(INFO) << desc << \"\\n\";\n    LOG(INFO)\n        << \"USAGE: --localIPaddress <IP Distributed Verifier> <IP Coordinator>\";\n    return 0;\n  }\n\n  if (vm.count(\"localIPaddress\")) {\n    localIpAddr = vm[\"localIPaddress\"].as<std::string>();\n    LOG(INFO) << \"Local IP Address \" << localIpAddr;\n  }\n\n  if (vm.count(\"ip\")) {\n    coordinatorIP = vm[\"ip\"].as<std::string>();\n    LOG(INFO) << \"Gathering Coordinator IP \" << coordinatorIP;\n  }\n\n  SocketId socketId = boost::uuids::random_generator()();\n  ZeroMQClientTransport transport(std::string(\"tcp://\") + coordinatorIP +\n                                      std::string(\":\") + std::string(port),\n                                  socketId, receive_timeout);\n\n  /** Set Zero-Knowledge Parameters */\n  irs.k = k; /** Degree of the Polynomial */\n  irs.n = n; /** Number of Shares */\n\n  mtParams.digestLength = 32;\n  mtParams.zkByteSize = 8;\n  mtParams.hashInnerNodeF = hash::blake2bTwoToOneHash;\n  mtParams.hashLeafContentF = hash::blake2bFieldElementHash<FieldT>;\n  mtParams.hashZKRandomnessF = hash::blake2bZKElementHash;\n  mtParams.leavesNumber = irs.n;\n\n  /** Configure easylogging */\n  configureEasyLogging(\"distributed_verifier\");\n\n  /** Add timers */\n  timers myTimers;\n  myTimers.initialize_timer();\n\n  auto result = verify(transport, myTimers);\n\n  if (hasError(result)) {\n    return EXIT_FAILURE;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "24382ab09a13b5e457040a1683a664c86040efa0", "size": 19601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distributed_verifier.cpp", "max_stars_repo_name": "JustinDrake/LigeroRSA", "max_stars_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "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/distributed_verifier.cpp", "max_issues_repo_name": "JustinDrake/LigeroRSA", "max_issues_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "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/distributed_verifier.cpp", "max_forks_repo_name": "JustinDrake/LigeroRSA", "max_forks_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-31T15:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T15:48:20.000Z", "avg_line_length": 32.1855500821, "max_line_length": 86, "alphanum_fraction": 0.6483342687, "num_tokens": 5133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1913506851297436}}
{"text": "#pragma once    \n\n#include <map>\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n#include \"libhmsbeagle/beagle.h\"\n#include \"tree.hpp\"\n#include \"tree_manip.hpp\"   \n#include \"data.hpp\"\n#include \"model.hpp\"\n#include \"xlorad.hpp\"\n\n#include \"output_manager.hpp\"\nextern lorad::OutputManager om;\n\nnamespace lorad {\n\n    class Likelihood {\n        public:\n                                                    Likelihood();\n                                                    ~Likelihood();\n\n            void                                    setRooted(bool is_rooted);\n            void                                    setPreferGPU(bool prefer_gpu);\n            void                                    setAmbiguityEqualsMissing(bool ambig_equals_missing);\n        \n            bool                                    usingStoredData() const;\n            void                                    useStoredData(bool using_data);\n            void                                    useUnderflowScaling(bool do_scaling);\n\n            std::string                             beagleLibVersion() const;\n            std::string                             availableResources() const;\n            std::string                             usedResources() const;\n\n            void                                    initBeagleLib();\n            void                                    finalizeBeagleLib(bool use_exceptions);\n\n            double                                  calcLogLikelihood(Tree::SharedPtr t);\n\n            Data::SharedPtr                         getData();\n            void                                    setData(Data::SharedPtr d);\n\n            Model::SharedPtr                        getModel();\n            void                                    setModel(Model::SharedPtr m);\n\n            void                                    clear();\n            \n            unsigned                                calcNumEdgesInFullyResolvedTree() const;\n            unsigned                                calcNumInternalsInFullyResolvedTree() const;\n            \n        private:\n        \n            struct InstanceInfo {\n                int handle;\n                int resourcenumber;\n                std::string resourcename;\n                unsigned nstates;\n                unsigned nratecateg;\n                unsigned npatterns;\n                unsigned partial_offset;\n                unsigned tmatrix_offset;\n                bool invarmodel;\n                std::vector<unsigned> subsets;\n                \n                InstanceInfo() : handle(-1), resourcenumber(-1), resourcename(\"\"), nstates(0), nratecateg(0), npatterns(0), partial_offset(0), tmatrix_offset(0), invarmodel(false) {}\n            };\n\n            typedef std::pair<unsigned, int>        instance_pair_t;\n\n            unsigned                                getScalerIndex(Node * nd, InstanceInfo & info) const;\n            unsigned                                getPartialIndex(Node * nd, InstanceInfo & info) const;\n            unsigned                                getTMatrixIndex(Node * nd, InstanceInfo & info, unsigned subset_index) const;\n            void                                    updateInstanceMap(instance_pair_t & p, unsigned subset);\n            void                                    newInstance(unsigned nstates, int nrates, std::vector<unsigned> & subset_indices);\n            void                                    setTipStates();\n            void                                    setTipPartials();\n            void                                    setPatternPartitionAssignments();\n            void                                    setPatternWeights();\n            void                                    setAmongSiteRateHeterogenetity();\n            void                                    setModelRateMatrix();\n            void                                    addOperation(InstanceInfo & info, Node * nd, Node * lchild, Node * rchild, unsigned subset_index);\n            void                                    queuePartialsRecalculation(Node * nd, Node * lchild, Node * rchild, Node * polytomy = 0);   \n            void                                    queueTMatrixRecalculation(Node * nd);\n            void                                    defineOperations(Tree::SharedPtr t);\n            void                                    updateTransitionMatrices();\n            void                                    calculatePartials();\n            double                                  calcInstanceLogLikelihood(InstanceInfo & inst, Tree::SharedPtr t);\n\n\n            std::vector<InstanceInfo>               _instances;\n            std::map<int, std::string>              _beagle_error;\n            std::map<int, std::vector<int> >        _operations;\n            std::map<int, std::vector<int> >        _pmatrix_index;\n            std::map<int, std::vector<double> >     _edge_lengths;\n            std::map<int, std::vector<int> >        _eigen_indices;\n            std::map<int, std::vector<int> >        _category_rate_indices;\n            double                                  _relrate_normalizing_constant;\n\n            std::vector<int>                        _subset_indices;\n            std::vector<int>                        _parent_indices;\n            std::vector<int>                        _child_indices;\n            std::vector<int>                        _tmatrix_indices;\n            std::vector<int>                        _weights_indices;\n            std::vector<int>                        _freqs_indices;\n            std::vector<int>                        _scaling_indices;\n\n            Model::SharedPtr                        _model;\n\n            Data::SharedPtr                         _data;\n            unsigned                                _ntaxa;\n            bool                                    _rooted;\n            bool                                    _prefer_gpu;\n            bool                                    _ambiguity_equals_missing;\n            bool                                    _underflow_scaling;\n            bool                                    _using_data;\n\n            std::vector<Node *>                     _polytomy_helpers;  \n            std::map<int, std::vector<int> >        _polytomy_map;\n            std::vector<double>                     _identity_matrix;   \n\n        public:\n            typedef std::shared_ptr< Likelihood >   SharedPtr;\n    };\n    \n    inline Likelihood::Likelihood() {\n        clear();\n    }\n\n    inline Likelihood::~Likelihood() {\n        finalizeBeagleLib(false);\n        clear();\n    }\n    \n    inline unsigned Likelihood::calcNumEdgesInFullyResolvedTree() const {\n        assert(_ntaxa > 0);\n        return (_rooted ? (2*_ntaxa - 2) : (2*_ntaxa - 3));\n    }\n    \n    inline unsigned Likelihood::calcNumInternalsInFullyResolvedTree() const {\n        assert(_ntaxa > 0);\n        return (_rooted ? (_ntaxa - 1) : (_ntaxa - 2));\n    }\n\n    inline void Likelihood::finalizeBeagleLib(bool use_exceptions) {\n        // Close down all BeagleLib instances if active\n        for (auto info : _instances) {\n            if (info.handle >= 0) {\n                int code = beagleFinalizeInstance(info.handle);\n                if (code != 0) {\n                    if (use_exceptions)\n                        throw XLorad(boost::format(\"Likelihood failed to finalize BeagleLib instance. BeagleLib error code was %d (%s).\") % code % _beagle_error[code]);\n                    else\n                        std::cerr << boost::format(\"Likelihood destructor failed to finalize BeagleLib instance. BeagleLib error code was %d (%s).\") % code % _beagle_error[code] << std::endl;\n                }\n            }\n        }\n        _instances.clear();\n    }\n\n    inline void Likelihood::clear() {   \n        finalizeBeagleLib(true);\n        \n        _ntaxa                      = 0;\n        _rooted                     = false;\n        _prefer_gpu                 = false;\n        _ambiguity_equals_missing   = true;\n        _underflow_scaling          = false;\n        _using_data                 = true;\n        _data                       = nullptr;\n        \n        _operations.clear();\n        _pmatrix_index.clear();\n        _edge_lengths.clear();\n        _eigen_indices.clear();\n        _category_rate_indices.clear();\n        _relrate_normalizing_constant = 1.0;\n        _subset_indices.assign(1, 0);\n        _parent_indices.assign(1, 0);\n        _child_indices.assign(1, 0);\n        _tmatrix_indices.assign(1, 0);\n        _weights_indices.assign(1, 0);\n        _freqs_indices.assign(1, 0);\n        _scaling_indices.assign(1, 0);\n        _identity_matrix.assign(1, 0.0);    \n\n        _model = Model::SharedPtr(new Model());        \n\n        // Store BeagleLib error codes so that useful\n        // error messages may be provided to the user\n        _beagle_error.clear();\n        _beagle_error[0]  = std::string(\"success\");\n        _beagle_error[-1] = std::string(\"unspecified error\");\n        _beagle_error[-2] = std::string(\"not enough memory could be allocated\");\n        _beagle_error[-3] = std::string(\"unspecified exception\");\n        _beagle_error[-4] = std::string(\"the instance index is out of range, or the instance has not been created\");\n        _beagle_error[-5] = std::string(\"one of the indices specified exceeded the range of the array\");\n        _beagle_error[-6] = std::string(\"no resource matches requirements\");\n        _beagle_error[-7] = std::string(\"no implementation matches requirements\");\n        _beagle_error[-8] = std::string(\"floating-point range exceeded\");\n    }   \n\n    inline std::string Likelihood::beagleLibVersion() const {\n        return std::string(beagleGetVersion());\n    }\n    \n    inline std::string Likelihood::availableResources() const {\n        BeagleResourceList * rsrcList = beagleGetResourceList();\n        std::string s;\n        for (int i = 0; i < rsrcList->length; ++i) {\n            std::string desc = rsrcList->list[i].description;\n            boost::trim(desc);\n            if (desc.size() > 0)\n                s += boost::str(boost::format(\"  resource %d: %s (%s)\\n\") % i % rsrcList->list[i].name % desc);\n            else\n                s += boost::str(boost::format(\"  resource %d: %s\\n\") % i % rsrcList->list[i].name);\n        }\n        boost::trim_right(s);\n        return s;\n    }\n    \n    inline std::string Likelihood::usedResources() const {\n        std::string s;\n        for (unsigned i = 0; i < _instances.size(); i++) {\n            s += boost::str(boost::format(\"  instance %d: %s (resource %d)\\n\") % _instances[i].handle % _instances[i].resourcename % _instances[i].resourcenumber);\n        }\n        return s;\n    }\n    \n    inline Data::SharedPtr Likelihood::getData() {\n        return _data;\n    }\n    \n    inline void Likelihood::setData(Data::SharedPtr data) {\n        assert(_instances.size() == 0);\n        assert(!data->getDataMatrix().empty());\n        _data = data;\n    }\n\n    inline Model::SharedPtr Likelihood::getModel() {\n        return _model;\n    }\n    \n    inline void Likelihood::setModel(Model::SharedPtr m) {\n        assert(_instances.size() == 0); // can't change model after initBeagleLib called\n        _model = m;\n    }\n\n    inline void Likelihood::setRooted(bool is_rooted) {\n        assert(_instances.size() == 0 || _rooted == is_rooted); // can't change rooting status after initBeagleLib called\n        _rooted = is_rooted;\n    }\n    \n    inline void Likelihood::setAmbiguityEqualsMissing(bool ambig_equals_missing) {\n        // Can't change GPU preference status after initBeagleLib called\n        assert(_instances.size() == 0 || _ambiguity_equals_missing == ambig_equals_missing);\n        _ambiguity_equals_missing = ambig_equals_missing;\n    }\n    \n    inline void Likelihood::setPreferGPU(bool prefer_gpu) {\n        // Can't change GPU preference status after initBeagleLib called\n        assert(_instances.size() == 0 || _prefer_gpu == prefer_gpu);\n        _prefer_gpu = prefer_gpu;\n    }\n    \n    inline bool Likelihood::usingStoredData() const {\n        return _using_data;\n    }\n    \n    inline void Likelihood::useStoredData(bool using_data) {\n        _using_data = using_data;\n    }\n\n    inline void Likelihood::useUnderflowScaling(bool do_scaling) { \n        _underflow_scaling = do_scaling;\n    } \n\n    inline void Likelihood::initBeagleLib() {\n        assert(_data);\n        assert(_model);\n\n        // Close down any existing BeagleLib instances\n        finalizeBeagleLib(true);\n\n        _ntaxa = _data->getNumTaxa();\n        \n        unsigned nsubsets = _data->getNumSubsets();\n        std::set<instance_pair_t> nstates_ncateg_combinations;\n        std::map<instance_pair_t, std::vector<unsigned> > subsets_for_pair;\n        for (unsigned subset = 0; subset < nsubsets; subset++) {\n            // Create a pair comprising number of states and number of rate categories\n            unsigned nstates = _data->getNumStatesForSubset(subset);\n            bool invar_model = _model->getSubsetIsInvarModel(subset);\n            int nrates = (invar_model ? -1 : 1)*_model->getSubsetNumCateg(subset);\n            instance_pair_t p = std::make_pair(nstates, nrates);\n            \n            // Add combo to set\n            nstates_ncateg_combinations.insert(p);\n            subsets_for_pair[p].push_back(subset);\n        }\n\n        // Create one instance for each distinct nstates-nrates combination\n        _instances.clear();\n        for (auto p : nstates_ncateg_combinations) {\n            newInstance(p.first, p.second, subsets_for_pair[p]);\n            \n            InstanceInfo & info = *_instances.rbegin();\n            ::om.outputConsole(boost::format(\"Created BeagleLib instance %d (%d states, %d rate%s, %d subset%s, %s invar. sites model)\\n\") % info.handle % info.nstates % info.nratecateg % (info.nratecateg == 1 ? \"\" : \"s\") % info.subsets.size() % (info.subsets.size() == 1 ? \"\" : \"s\") % (info.invarmodel ? \"is\" : \"not\"));\n        }\n        \n        if (_ambiguity_equals_missing)\n            setTipStates();\n        else\n            setTipPartials();\n        setPatternWeights();\n        setPatternPartitionAssignments();\n    }\n    \n    inline void Likelihood::newInstance(unsigned nstates, int nrates, std::vector<unsigned> & subset_indices) { \n        unsigned num_subsets = (unsigned)subset_indices.size();\n    \n        bool is_invar_model = (nrates < 0 ? true : false);\n        unsigned ngammacat = (unsigned)(is_invar_model ? -nrates : nrates);\n    \n        // Create an identity matrix used for computing partials    \n        // for polytomies (represents the transition matrix\n        // for the zero-length edges inserted to arbitrarily \n        // resolve each polytomy)\n        _identity_matrix.assign(nstates*nstates*ngammacat, 0.0);\n        for (unsigned k = 0; k < ngammacat; k++) {\n            unsigned offset = k*nstates*nstates;\n            _identity_matrix[0+offset]  = 1.0;\n            _identity_matrix[5+offset]  = 1.0;\n            _identity_matrix[10+offset] = 1.0;\n            _identity_matrix[15+offset] = 1.0;\n        }   \n        \n        //...   \n        \n                \n        unsigned num_patterns = 0;\n        for (auto s : subset_indices) {\n            num_patterns += _data->getNumPatternsInSubset(s);\n        }\n        \n        unsigned num_internals = calcNumInternalsInFullyResolvedTree();\n        \n        // add 1 to num_edges so that subroot node will have a tmatrix, root tip's tmatrix is never used\n        unsigned num_edges = calcNumEdgesInFullyResolvedTree();\n        unsigned num_nodes = num_edges + 1;\n        unsigned num_transition_probs = num_nodes*num_subsets;\n\n        long requirementFlags = 0;\n\n        long preferenceFlags = BEAGLE_FLAG_PRECISION_SINGLE | BEAGLE_FLAG_THREADING_CPP;\n        if (_underflow_scaling) {\n            preferenceFlags |= BEAGLE_FLAG_SCALING_MANUAL;\n            preferenceFlags |= BEAGLE_FLAG_SCALERS_LOG;\n        }\n        if (_prefer_gpu)\n            preferenceFlags |= BEAGLE_FLAG_PROCESSOR_GPU;\n        else\n            preferenceFlags |= BEAGLE_FLAG_PROCESSOR_CPU;\n        \n        BeagleInstanceDetails instance_details;\n        unsigned npartials = num_internals + _ntaxa;\n        unsigned nscalers = num_internals;  // one scale buffer for every internal node \n        unsigned nsequences = 0;\n        if (_ambiguity_equals_missing) {\n            npartials -= _ntaxa;\n            nsequences += _ntaxa;\n        }\n        \n        int inst = beagleCreateInstance(\n             _ntaxa,                        // tips\n             2*npartials,                   // partials\n             nsequences,                    // sequences\n             nstates,                       // states\n             num_patterns,                  // patterns (total across all subsets that use this instance)\n             num_subsets,                   // models (one for each distinct eigen decomposition)\n             2*num_subsets*num_transition_probs, // transition matrices (one for each edge in each subset)\n             ngammacat,                     // rate categories\n             (_underflow_scaling ? 2*nscalers + 1 : 0),  // scale buffers (+1 is for the cumulative scaler at index 0)\n             NULL,                          // resource restrictions\n             0,                             // length of resource list\n             preferenceFlags,               // preferred flags\n             requirementFlags,              // required flags\n             &instance_details);            // pointer for details\n        \n        if (inst < 0) {\n            // beagleCreateInstance returns one of the following:\n            //   valid instance (0, 1, 2, ...)\n            //   error code (negative integer)\n            throw XLorad(boost::str(boost::format(\"Likelihood init function failed to create BeagleLib instance (BeagleLib error code was %d)\") % _beagle_error[inst]));\n        }\n        \n        InstanceInfo info;\n        info.handle         = inst;\n        info.resourcenumber = instance_details.resourceNumber;\n        info.resourcename   = instance_details.resourceName;\n        info.nstates        = nstates;\n        info.nratecateg     = ngammacat;\n        info.invarmodel     = is_invar_model;\n        info.subsets        = subset_indices;\n        info.npatterns      = num_patterns;\n        info.partial_offset = num_internals;\n        info.tmatrix_offset = num_nodes;\n        _instances.push_back(info);\n    }   \n\n    inline void Likelihood::setTipStates() {\n        assert(_instances.size() > 0);\n        assert(_data);\n        Data::state_t one = 1;\n\n        for (auto & info : _instances) {\n            std::vector<int> states(info.nstates*info.npatterns);\n            \n            // Loop through all rows of the data matrix, setting the tip states for one taxon each row\n            unsigned t = 0;\n            for (auto & row : _data->getDataMatrix()) {\n            \n                // Loop through all subsets assigned to this instance\n                unsigned k = 0;\n                for (unsigned s : info.subsets) {\n                \n                    // Loop through all patterns in this subset\n                    auto interval = _data->getSubsetBeginEnd(s);\n                    for (unsigned p = interval.first; p < interval.second; p++) {\n                    \n                        // d is the state for taxon t, pattern p (in subset s)\n                        // d is stored as a bit field (e.g., for nucleotide data, A=1, C=2, G=4, T=8, ?=15),\n                        // but BeagleLib expects states to be integers (e.g. for nucleotide data,\n                        // A=0, C=1, G=2, T=3, ?=4).\n                        Data::state_t d = row[p];\n                        \n                        // Handle common nucleotide case separately\n                        if (info.nstates == 4) {\n                            if (d == 1)\n                                states[k++] = 0;\n                            else if (d == 2)\n                                states[k++] = 1;\n                            else if (d == 4)\n                                states[k++] = 2;\n                            else if (d == 8)\n                                states[k++] = 3;\n                            else\n                                states[k++] = 4;\n                        }\n                        else {\n                            // This case is for any other data type except nucleotide\n                            int s = -1;\n                            for (unsigned b = 0; b < info.nstates; b++) {\n                                if (d == one << b) {\n                                    s = b;\n                                    break;\n                                }\n                            }\n                            if (s == -1)\n                                states[k++] = info.nstates;\n                            else\n                                states[k++] = s;\n                        }\n                    } // pattern loop\n                }   // subset loop\n\n            int code = beagleSetTipStates(\n                info.handle,    // Instance number\n                t,              // Index of destination compactBuffer\n                &states[0]);    //  Pointer to compact states vector\n\n            if (code != 0)\n                throw XLorad(boost::format(\"failed to set tip state for taxon %d (\\\"%s\\\"; BeagleLib error code was %d)\") % (t+1) % _data->getTaxonNames()[t] % code % _beagle_error[code]);\n            ++t;\n            }\n        }\n    }\n\n    inline void Likelihood::setTipPartials() {\n        assert(_instances.size() > 0);\n        assert(_data);\n        Data::state_t one = 1;\n        \n        for (auto & info : _instances) {\n            std::vector<double> partials(info.nstates*info.npatterns);\n            \n            // Loop through all rows of data matrix, setting the tip states for one taxon each row\n            unsigned t = 0;\n            for (auto & row : _data->getDataMatrix()) {\n            \n                // Loop through all subsets assigned to this instance\n                unsigned k = 0;\n                for (unsigned s : info.subsets) {\n                \n                    // Loop through all patterns in this subset\n                    auto interval = _data->getSubsetBeginEnd(s);\n                    for (unsigned p = interval.first; p < interval.second; p++) {\n                    \n                        // d is the state for taxon t, pattern p (in subset s)\n                        Data::state_t d = row[p];\n                        \n                        // Handle common nucleotide case separately\n                        if (info.nstates == 4) {\n                            partials[k++] = d & 1 ? 1.0 : 0.0;\n                            partials[k++] = d & 2 ? 1.0 : 0.0;\n                            partials[k++] = d & 4 ? 1.0 : 0.0;\n                            partials[k++] = d & 8 ? 1.0 : 0.0;\n                        }\n                        else {\n                            // This case is for any other data type except nucleotide\n                            for (unsigned b = 0; b < info.nstates; b++) {\n                                partials[k++] = d & (one << b) ? 1.0 : 0.0;\n                            }\n                        }\n                    }\n                }\n                \n            int code = beagleSetTipPartials(\n                info.handle,    // Instance number\n                t,              // Index of destination compactBuffer\n                &partials[0]);  // Pointer to compact states vector\n\n            if (code != 0)\n                throw XLorad(boost::format(\"failed to set tip state for taxon %d (\\\"%s\\\"; BeagleLib error code was %d)\") % (t+1) % _data->getTaxonNames()[t] % code % _beagle_error[code]);\n            ++t;\n            }\n        }\n    }\n\n    inline void Likelihood::setPatternPartitionAssignments() {\n        assert(_instances.size() > 0);\n        assert(_data);\n        \n        // beagleSetPatternPartitions does not need to be called if data are unpartitioned\n        // (and, in fact, BeagleLib only supports partitioning for 4-state instances if GPU is used,\n        // so not calling beagleSetPatternPartitions allows unpartitioned codon model analyses)\n        if (_instances.size() == 1 && _instances[0].subsets.size() == 1)\n            return;\n        \n        Data::partition_key_t v;\n\n        // Loop through all instances\n        for (auto & info : _instances) {\n            unsigned nsubsets = (unsigned)info.subsets.size();\n            v.resize(info.npatterns);\n            unsigned pattern_index = 0;\n\n            // Loop through all subsets assigned to this instance\n            unsigned instance_specific_subset_index = 0;\n            for (unsigned s : info.subsets) {\n                // Loop through all patterns in this subset\n                auto interval = _data->getSubsetBeginEnd(s);\n                for (unsigned p = interval.first; p < interval.second; p++) {\n                    v[pattern_index++] = instance_specific_subset_index;\n                }\n                ++instance_specific_subset_index;\n            }\n\n            int code = beagleSetPatternPartitions(\n               info.handle, // instance number\n               nsubsets,    // number of data subsets (equals 1 if data are unpartitioned)\n               &v[0]);      // vector of subset indices: v[i] = 0 means pattern i is in subset 0\n\n            if (code != 0) {\n                throw XLorad(boost::format(\"failed to set pattern partition. BeagleLib error code was %d (%s)\") % code % _beagle_error[code]);\n            }\n        }\n    }\n    \n    inline void Likelihood::setPatternWeights() {\n        assert(_instances.size() > 0);\n        assert(_data);\n        Data::pattern_counts_t v;\n        auto pattern_counts = _data->getPatternCounts();\n        assert(pattern_counts.size() > 0);\n\n        // Loop through all instances\n        for (auto & info : _instances) {\n            v.resize(info.npatterns);\n            unsigned pattern_index = 0;\n\n            // Loop through all subsets assigned to this instance\n            for (unsigned s : info.subsets) {\n            \n                // Loop through all patterns in this subset\n                auto interval = _data->getSubsetBeginEnd(s);\n                for (unsigned p = interval.first; p < interval.second; p++) {\n                    v[pattern_index++] = pattern_counts[p];\n                }\n            }\n\n            int code = beagleSetPatternWeights(\n               info.handle,   // instance number\n               &v[0]);        // vector of pattern counts: v[i] = 123 means pattern i was encountered 123 times\n\n            if (code != 0)\n                throw XLorad(boost::format(\"Failed to set pattern weights for instance %d. BeagleLib error code was %d (%s)\") % info.handle % code % _beagle_error[code]);\n        }\n    }\n\n    inline void Likelihood::setAmongSiteRateHeterogenetity() {\n        assert(_instances.size() > 0);\n        int code = 0;\n        \n        // Loop through all instances\n        for (auto & info : _instances) {\n\n            // Loop through all subsets assigned to this instance\n            unsigned instance_specific_subset_index = 0;\n            for (unsigned s : info.subsets) {\n                code = _model->setBeagleAmongSiteRateVariationRates(info.handle, s, instance_specific_subset_index);\n                if (code != 0)\n                    throw XLorad(boost::str(boost::format(\"Failed to set category rates for BeagleLib instance %d. BeagleLib error code was %d (%s)\") % info.handle % code % _beagle_error[code]));\n            \n                code = _model->setBeagleAmongSiteRateVariationProbs(info.handle, s, instance_specific_subset_index);\n                if (code != 0)\n                    throw XLorad(boost::str(boost::format(\"Failed to set category probabilities for BeagleLib instance %d. BeagleLib error code was %d (%s)\") % info.handle % code % _beagle_error[code]));\n                    \n                ++instance_specific_subset_index;\n            }\n        }\n    }\n\n    inline void Likelihood::setModelRateMatrix() {\n        // Loop through all instances\n        for (auto & info : _instances) {\n\n            // Loop through all subsets assigned to this instance\n            unsigned instance_specific_subset_index = 0;\n            for (unsigned s : info.subsets) {\n                int code = _model->setBeagleStateFrequencies(info.handle, s, instance_specific_subset_index);\n                if (code != 0)\n                    throw XLorad(boost::str(boost::format(\"Failed to set state frequencies for BeagleLib instance %d. BeagleLib error code was %d (%s)\") % info.handle % code % _beagle_error[code]));\n\n                code = _model->setBeagleEigenDecomposition(info.handle, s, instance_specific_subset_index);\n                if (code != 0)\n                    throw XLorad(boost::str(boost::format(\"Failed to set eigen decomposition for BeagleLib instance %d. BeagleLib error code was %d (%s)\") % info.handle % code % _beagle_error[code]));\n                \n                ++instance_specific_subset_index;\n            }\n        }\n    }\n    \n    inline unsigned Likelihood::getScalerIndex(Node * nd, InstanceInfo & info) const {\n        unsigned sindex = BEAGLE_OP_NONE;\n        if (_underflow_scaling) {\n            sindex = nd->_number - _ntaxa + 1; // +1 to skip the cumulative scaler vector\n            if (nd->isAltPartial())\n                sindex += info.partial_offset;\n        }\n        return sindex;\n    }\n    \n    inline unsigned Likelihood::getPartialIndex(Node * nd, InstanceInfo & info) const {\n        // Note: do not be tempted to subtract _ntaxa from pindex: BeagleLib does this itself\n        assert(nd->_number >= 0);\n        unsigned pindex = nd->_number;\n        if (pindex >= _ntaxa) {\n            if (nd->isAltPartial())\n                pindex += info.partial_offset;\n        }\n        return pindex;\n    }\n    \n    inline unsigned Likelihood::getTMatrixIndex(Node * nd, InstanceInfo & info, unsigned subset_index) const {\n        unsigned tindex = 2*subset_index*info.tmatrix_offset + nd->_number;\n        if (nd->isAltTMatrix())\n            tindex += info.tmatrix_offset;\n        return tindex;\n    }\n    \n    inline void Likelihood::defineOperations(Tree::SharedPtr t) {   \n        assert(_instances.size() > 0);\n        assert(t);\n        assert(t->isRooted() == _rooted);\n        assert(_polytomy_helpers.empty());\n        assert(_polytomy_map.empty());\n\n        _relrate_normalizing_constant = _model->calcNormalizingConstantForSubsetRelRates();\n\n        // Start with a clean slate\n        for (auto & info : _instances) {\n            _operations[info.handle].clear();\n            _pmatrix_index[info.handle].clear();\n            _edge_lengths[info.handle].clear();\n            _eigen_indices[info.handle].clear();\n            _category_rate_indices[info.handle].clear();\n        }\n\n        // Loop through all nodes in reverse level order\n        for (auto nd : boost::adaptors::reverse(t->_levelorder)) {\n            assert(nd->_number >= 0);\n            if (!nd->_left_child) {\n                // This is a leaf\n                if (nd->isSelTMatrix())\n                    queueTMatrixRecalculation(nd);\n            }\n            else {\n                // This is an internal node\n                if (nd->isSelTMatrix())\n                    queueTMatrixRecalculation(nd);\n\n                // Internal nodes have partials to be calculated, so define\n                // an operation to compute the partials for this node\n                if (nd->isSelPartial()) {\n                    TreeManip tm(t);   \n                    if (tm.isPolytomy(nd)) {\n                        // Internal node is a polytomy\n                        unsigned nchildren = tm.countChildren(nd);\n                        Node * a = nd->_left_child;\n                        Node * b = a->_right_sib;\n                        Node * c = 0;\n                        for (unsigned k = 0; k < nchildren - 2; k++) {\n                            c = tm.getUnusedNode();\n                            c->_left_child = a;\n                            _polytomy_helpers.push_back(c);\n\n                            queuePartialsRecalculation(c, a, b, nd);\n                            \n                            // Tackle next arm of the polytomy\n                            b = b->_right_sib;\n                            a = c;\n                        }\n                        \n                        // Now add operation to compute the partial for the real internal node\n                        queuePartialsRecalculation(nd, a, b);\n                    }\n                    else {\n                        // Internal node is not a polytomy\n                        Node * lchild = nd->_left_child;\n                        assert(lchild);\n                        Node * rchild = lchild->_right_sib;\n                        assert(rchild);\n                        queuePartialsRecalculation(nd, lchild, rchild);\n                    }   \n                }\n            }\n        }\n    }   \n\n    inline void Likelihood::queuePartialsRecalculation(Node * nd, Node * lchild, Node * rchild, Node * polytomy) {  \n        for (auto & info : _instances) {\n            unsigned instance_specific_subset_index = 0;\n            // line below produces warning about s not being used, but this is unavoidable\n            // because values in vector info.subsets may not be sequential\n            for (unsigned s : info.subsets) {\n                (void)s;    // to prevent compiler warning about s not being used\n            \n                if (polytomy) {  \n                    // nd has been pulled out of tree's _unused_nodes vector to break up the polytomy\n                    // Note that the parameter \"polytomy\" is the polytomous node itself\n                    \n                    // First get the transition matrix index\n                    unsigned tindex = getTMatrixIndex(nd, info, instance_specific_subset_index);\n\n                    // Set the transition matrix for nd to the identity matrix\n                    // note: last argument 1 is the value used for ambiguous states (should be 1 for transition matrices)\n                    int code = beagleSetTransitionMatrix(info.handle, tindex, &_identity_matrix[0], 1);\n                    if (code != 0)\n                        throw XLorad(boost::str(boost::format(\"Failed to set transition matrix for instance %d. BeagleLib error code was %d (%s)\") % info.handle % code % _beagle_error[code]));\n                    \n                    // Set the edgelength to 0.0 to maintain consistency with the transition matrix\n                    nd->setEdgeLength(0.0);\n                    \n                    // If employing underflow scaling, the scaling factors for these fake nodes need to be\n                    // transferred to the polytomous node, as that will be the only node remaining after the\n                    // likelihood has been calculated. Save the scaling factor index, associating it with\n                    // the scaling factor index of the polytomy node.\n                    if (_underflow_scaling) {\n                        // Get the polytomy's scaling factor index\n                        int spolytomy = getScalerIndex(polytomy, info);\n                        \n                        // Get nd's scaling factor index\n                        int snd = getScalerIndex(nd, info);\n                        \n                        // Save nd's index in the vector associated with polytomy's index\n                        _polytomy_map[spolytomy].push_back(snd);\n                    }\n                    \n                }  \n                \n                addOperation(info, nd, lchild, rchild, instance_specific_subset_index);\n                ++instance_specific_subset_index;\n            }\n        }\n    }   \n    \n    inline void Likelihood::queueTMatrixRecalculation(Node * nd) {\n        Model::subset_relrate_vect_t & subset_relrates = _model->getSubsetRelRates();\n\n        for (auto & info : _instances) {\n            unsigned instance_specific_subset_index = 0;\n            for (unsigned s : info.subsets) {\n                double subset_relative_rate = subset_relrates[s]/_relrate_normalizing_constant;\n\n                unsigned tindex = getTMatrixIndex(nd, info, instance_specific_subset_index);\n                _pmatrix_index[info.handle].push_back(tindex);\n                _edge_lengths[info.handle].push_back(nd->_edge_length*subset_relative_rate);\n                _eigen_indices[info.handle].push_back(s);\n                _category_rate_indices[info.handle].push_back(s);\n\n                ++instance_specific_subset_index;\n            }\n        }\n    }\n\n    inline void Likelihood::addOperation(InstanceInfo & info, Node * nd, Node * lchild, Node * rchild, unsigned subset_index) {\n        assert(nd);\n        assert(lchild);\n        assert(rchild);\n\n        // 1. destination partial to be calculated\n        int partial_dest = getPartialIndex(nd, info);\n        _operations[info.handle].push_back(partial_dest);\n\n        // 2. destination scaling buffer index to write to\n        int scaler_index = getScalerIndex(nd, info);\n        _operations[info.handle].push_back(scaler_index);\n\n        // 3. destination scaling buffer index to read from\n        _operations[info.handle].push_back(BEAGLE_OP_NONE);\n\n        // 4. left child partial index\n        int partial_lchild = getPartialIndex(lchild, info);\n        _operations[info.handle].push_back(partial_lchild);\n\n        // 5. left child transition matrix index\n        unsigned tindex_lchild = getTMatrixIndex(lchild, info, subset_index);\n        _operations[info.handle].push_back(tindex_lchild);\n\n        // 6. right child partial index\n        int partial_rchild = getPartialIndex(rchild, info);\n        _operations[info.handle].push_back(partial_rchild);\n\n        // 7. right child transition matrix index\n        unsigned tindex_rchild = getTMatrixIndex(rchild, info, subset_index);\n        _operations[info.handle].push_back(tindex_rchild);\n\n        if (info.subsets.size() > 1) {\n            // 8. index of partition subset\n            _operations[info.handle].push_back(subset_index);\n            \n            // 9. cumulative scale index\n            _operations[info.handle].push_back(BEAGLE_OP_NONE); // accumulate in calcInstanceLogLikelihood\n        }\n    }\n    \n    inline void Likelihood::updateTransitionMatrices() {\n        assert(_instances.size() > 0);\n        if (_pmatrix_index.size() == 0)\n            return;\n        \n        // Loop through all instances\n        for (auto & info : _instances) {\n            int code = 0;\n\n            unsigned nsubsets = (unsigned)info.subsets.size();\n            if (nsubsets > 1) {\n                code = beagleUpdateTransitionMatricesWithMultipleModels(\n                    info.handle,                                // Instance number\n                    &_eigen_indices[info.handle][0],            // Index of eigen-decomposition buffer\n                    &_category_rate_indices[info.handle][0],    // category rate indices\n                    &_pmatrix_index[info.handle][0],            // transition probability matrices to update\n                    NULL,                                       // first derivative matrices to update\n                    NULL,                                       // second derivative matrices to update\n                    &_edge_lengths[info.handle][0],             // List of edge lengths\n                    (int)_pmatrix_index[info.handle].size());   // Length of lists\n            }\n            else {\n                code = beagleUpdateTransitionMatrices(\n                    info.handle,                                // Instance number\n                    0,                                          // Index of eigen-decomposition buffer\n                    &_pmatrix_index[info.handle][0],            // transition probability matrices to update\n                    NULL,                                       // first derivative matrices to update\n                    NULL,                                       // second derivative matrices to update\n                    &_edge_lengths[info.handle][0],             // List of edge lengths\n                    (int)_pmatrix_index[info.handle].size());   // Length of lists\n            }\n\n            if (code != 0)\n                throw XLorad(boost::str(boost::format(\"Failed to update transition matrices for instance %d. BeagleLib error code was %d (%s)\") % info.handle % code % _beagle_error[code]));\n                \n        }\n    }\n    \n    inline void Likelihood::calculatePartials() {   \n        assert(_instances.size() > 0);\n        if (_operations.size() == 0)\n            return;\n        int code = 0;\n        \n        // Loop through all instances\n        for (auto & info : _instances) {\n            unsigned nsubsets = (unsigned)info.subsets.size();\n\n            if (nsubsets > 1) {\n                code = beagleUpdatePartialsByPartition(\n                    info.handle,                                                    // Instance number\n                    (BeagleOperationByPartition *) &_operations[info.handle][0],    // BeagleOperation list specifying operations\n                    (int)(_operations[info.handle].size()/9));                      // Number of operations\n                if (code != 0)\n                    throw XLorad(boost::format(\"failed to update partials. BeagleLib error code was %d (%s)\") % code % _beagle_error[code]);\n                \n                if (_underflow_scaling) {   \n                    // Accumulate scaling factors across polytomy helpers and assign them to their parent node\n                    for (auto & m : _polytomy_map) {\n                        for (unsigned subset = 0; subset < nsubsets; subset++) {\n                            code = beagleAccumulateScaleFactorsByPartition(info.handle, &m.second[0], (int)m.second.size(), m.first, subset);\n                            if (code != 0) {\n                                throw XLorad(boost::format(\"failed to transfer scaling factors to polytomous node. BeagleLib error code was %d (%s)\") % code % _beagle_error[code]);\n                            }\n                        }\n                    }\n                }   \n            }\n            else {\n                // no partitioning, just one data subset\n                code = beagleUpdatePartials(\n                    info.handle,                                        // Instance number\n                    (BeagleOperation *) &_operations[info.handle][0],   // BeagleOperation list specifying operations\n                    (int)(_operations[info.handle].size()/7),           // Number of operations\n                    BEAGLE_OP_NONE);                                    // Index number of scaleBuffer to store accumulated factors\n                if (code != 0) \n                    throw XLorad(boost::format(\"failed to update partials. BeagleLib error code was %d (%s)\") % code % _beagle_error[code]);\n                \n                if (_underflow_scaling) { \n                    // Accumulate scaling factors across polytomy helpers and assign them to their parent node\n                    for (auto & m : _polytomy_map) {\n                        code = beagleAccumulateScaleFactors(info.handle, &m.second[0], (int)m.second.size(), m.first);\n                        if (code != 0) {\n                            throw XLorad(boost::format(\"failed to transfer scaling factors to polytomous node. BeagleLib error code was %d (%s)\") % code % _beagle_error[code]);\n                        }\n                    }\n                }   \n            }   \n        }\n    }   \n    \n    inline double Likelihood::calcInstanceLogLikelihood(InstanceInfo & info, Tree::SharedPtr t) {\n        int code = 0;\n        unsigned nsubsets = (unsigned)info.subsets.size();\n        assert(nsubsets > 0);\n\n        // Assuming there are as many transition matrices as there are edge lengths\n        assert(_pmatrix_index[info.handle].size() == _edge_lengths[info.handle].size());\n\n        int state_frequency_index  = 0;\n        int category_weights_index = 0;\n        int cumulative_scale_index = (_underflow_scaling ? 0 : BEAGLE_OP_NONE);\n        int child_partials_index   = getPartialIndex(t->_root, info);\n        int parent_partials_index = getPartialIndex(t->_preorder[0], info);\n        int parent_tmatrix_index = getTMatrixIndex(t->_preorder[0], info, 0);\n\n        // storage for results of the likelihood calculation\n        std::vector<double> subset_log_likelihoods(nsubsets, 0.0);\n        double log_likelihood = 0.0;\n        \n        if (_underflow_scaling) {\n            // Create vector of all scaling vector indices in current use\n            std::vector<int> internal_node_scaler_indices;\n            for (auto nd : t->_preorder) {\n                if (nd->_left_child) {\n                    unsigned s = getScalerIndex(nd, info);\n                    internal_node_scaler_indices.push_back(s);\n                }\n            }\n            \n            if (nsubsets == 1) {\n                code = beagleResetScaleFactors(info.handle, cumulative_scale_index);\n                if (code != 0)\n                    throw XLorad(boost::str(boost::format(\"failed to reset scale factors in calcInstanceLogLikelihood. BeagleLib error code was %d (%s)\") % code % _beagle_error[code]));\n\n                code = beagleAccumulateScaleFactors(\n                     info.handle,\n                     &internal_node_scaler_indices[0],\n                     (int)internal_node_scaler_indices.size(),\n                     cumulative_scale_index);\n                if (code != 0)\n                    throw XLorad(boost::str(boost::format(\"failed to accumulate scale factors in calcInstanceLogLikelihood. BeagleLib error code was %d (%s)\") % code % _beagle_error[code]));\n            }\n            else {\n                for (unsigned s = 0; s < nsubsets; ++s) {\n                    code = beagleResetScaleFactorsByPartition(info.handle, cumulative_scale_index, s);\n                    if (code != 0)\n                        throw XLorad(boost::str(boost::format(\"failed to reset scale factors for subset %d in calcInstanceLogLikelihood. BeagleLib error code was %d (%s)\") % s % code % _beagle_error[code]));\n                        \n                    code = beagleAccumulateScaleFactorsByPartition(\n                        info.handle,\n                        &internal_node_scaler_indices[0],\n                        (int)internal_node_scaler_indices.size(),\n                        cumulative_scale_index,\n                        s);\n                    if (code != 0)\n                        throw XLorad(boost::str(boost::format(\"failed to acccumulate scale factors for subset %d in calcInstanceLogLikelihood. BeagleLib error code was %d (%s)\") % s % code % _beagle_error[code]));\n                }\n            }\n        }\n\n        if (nsubsets > 1) {\n            _parent_indices.assign(nsubsets, parent_partials_index);\n            _child_indices.assign(nsubsets, child_partials_index);\n            _weights_indices.assign(nsubsets, category_weights_index);\n            _scaling_indices.resize(nsubsets);\n            _subset_indices.resize(nsubsets);\n            _freqs_indices.resize(nsubsets);\n            _tmatrix_indices.resize(nsubsets);\n\n            for (unsigned s = 0; s < nsubsets; s++) {\n                _scaling_indices[s]  = (_underflow_scaling ? 0 : BEAGLE_OP_NONE);\n                _subset_indices[s]  = s;\n                _freqs_indices[s]   = s;\n                _tmatrix_indices[s] = getTMatrixIndex(t->_preorder[0], info, s); //index_focal_child + s*tmatrix_skip;\n            }\n            \n            code = beagleCalculateEdgeLogLikelihoodsByPartition(\n                info.handle,                 // instance number\n                &_parent_indices[0],         // indices of parent partialsBuffers\n                &_child_indices[0],          // indices of child partialsBuffers\n                &_tmatrix_indices[0],        // transition probability matrices for this edge\n                NULL,                        // first derivative matrices\n                NULL,                        // second derivative matrices\n                &_weights_indices[0],        // weights to apply to each partialsBuffer\n                &_freqs_indices[0],          // state frequencies for each partialsBuffer\n                &_scaling_indices[0],        // scaleBuffers containing accumulated factors\n                &_subset_indices[0],         // indices of subsets\n                nsubsets,                    // partition subset count\n                1,                           // number of distinct eigen decompositions\n                &subset_log_likelihoods[0],  // address of vector of log likelihoods (one for each subset)\n                &log_likelihood,             // destination for resulting log likelihood\n                NULL,                        // destination for vector of first derivatives (one for each subset)\n                NULL,                        // destination for first derivative\n                NULL,                        // destination for vector of second derivatives (one for each subset)\n                NULL);                       // destination for second derivative\n        }\n        else {\n            code = beagleCalculateEdgeLogLikelihoods(\n                info.handle,                 // instance number\n                &parent_partials_index,      // indices of parent partialsBuffers\n                &child_partials_index,       // indices of child partialsBuffers\n                &parent_tmatrix_index,       // transition probability matrices for this edge\n                NULL,                        // first derivative matrices\n                NULL,                        // second derivative matrices\n                &category_weights_index,     // weights to apply to each partialsBuffer\n                &state_frequency_index,      // state frequencies for each partialsBuffer\n                &cumulative_scale_index,     // scaleBuffers containing accumulated factors\n                1,                           // Number of partialsBuffer\n                &log_likelihood,             // destination for log likelihood\n                NULL,                        // destination for first derivative\n                NULL);                       // destination for second derivative\n        }\n        \n        // ...\n        \n        if (code != 0) {\n            std::cerr << \"Problem computing likelihood for this tree:\\n\";\n            std::cerr << TreeManip(t).makeNewick(9, true) << std::endl;\n            throw XLorad(boost::str(boost::format(\"failed to calculate edge log-likelihoods in calcInstanceLogLikelihood. BeagleLib error code was %d (%s)\") % code % _beagle_error[code]));\n        }\n        \n        if (info.invarmodel) {\n            auto monomorphic = _data->getMonomorphic();\n            auto counts = _data->getPatternCounts();\n            std::vector<double> site_log_likelihoods(info.npatterns, 0.0);\n            double * siteLogLs = &site_log_likelihoods[0];\n\n            beagleGetSiteLogLikelihoods(info.handle, siteLogLs);\n\n            // Loop through all subsets assigned to this instance\n            double lnL = 0.0;\n            unsigned i = 0;\n            for (unsigned s : info.subsets) {\n                const ASRV & asrv = _model->getASRV(s);\n                const QMatrix & qmatrix = _model->getQMatrix(s);\n                const double * freq = qmatrix.getStateFreqs();\n                \n                double pinvar = *(asrv.getPinvarSharedPtr());\n                assert(pinvar >= 0.0 && pinvar <= 1.0);\n\n                if (pinvar == 0.0) {\n                    // log likelihood for this subset is equal to the sum of site log-likelihoods\n                    auto interval = _data->getSubsetBeginEnd(s);\n                    for (unsigned p = interval.first; p < interval.second; p++) {\n                        lnL += counts[p]*site_log_likelihoods[i++];\n                    }\n                }\n                else {\n                    // Loop through all patterns in this subset\n                    double log_pinvar = log(pinvar);\n                    double log_one_minus_pinvar = log(1.0 - pinvar);\n                    auto interval = _data->getSubsetBeginEnd(s);\n                    for (unsigned p = interval.first; p < interval.second; p++) {\n                        // Loop through all states for this pattern\n                        double invar_like = 0.0;\n                        if (monomorphic[p] > 0) {\n                            for (unsigned k = 0; k < info.nstates; ++k) {\n                                Data::state_t x = (Data::state_t)1 << k;\n                                double condlike = (x & monomorphic[p] ? 1.0 : 0.0);\n                                double basefreq = freq[k];\n                                invar_like += condlike*basefreq;\n                            }\n                        }\n                        double site_lnL = site_log_likelihoods[i++];\n                        double log_like_term = log_one_minus_pinvar + site_lnL;\n                        if (invar_like > 0.0) {\n                            double log_invar_term = log_pinvar + log(invar_like);\n                            double site_log_like = (log_like_term + log(1.0 + exp(log_invar_term - log_like_term)));\n                            lnL += counts[p]*site_log_like;\n                        }\n                        else {\n                            lnL += counts[p]*log_like_term;\n                        }\n                    }\n                }\n            }\n            log_likelihood = lnL;\n        }\n\n        return log_likelihood;\n    }\n    \n    inline double Likelihood::calcLogLikelihood(Tree::SharedPtr t) {    \n        assert(_instances.size() > 0);\n        \n        if (!_using_data)\n            return 0.0;\n        \n        // Must call setData and setModel before calcLogLikelihood\n        assert(_data);\n        assert(_model);\n\n        if (t->_is_rooted)\n            throw XLorad(\"This version of the program can only compute likelihoods for unrooted trees\");\n\n        // Assuming \"root\" is leaf 0\n        assert(t->_root->_number == 0 && t->_root->_left_child == t->_preorder[0] && !t->_preorder[0]->_right_sib);\n\n        setModelRateMatrix();\n        setAmongSiteRateHeterogenetity();\n        defineOperations(t);\n        updateTransitionMatrices();\n        calculatePartials();\n        \n        double log_likelihood = 0.0;\n        for (auto & info : _instances) {\n            log_likelihood += calcInstanceLogLikelihood(info, t);\n        }\n\n        // We no longer need the internal nodes brought out of storage  \n        // and used to compute partials for polytomies\n        TreeManip tm(t);\n        for (Node * h : _polytomy_helpers) {\n            tm.putUnusedNode(h);\n        }\n        _polytomy_helpers.clear();\n        _polytomy_map.clear();  \n                \n        return log_likelihood;\n    }   \n\n}\n", "meta": {"hexsha": "78afe0271df2fd878ecfe08ef18f596b1b0c4382", "size": 55202, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/likelihood.hpp", "max_stars_repo_name": "plewis/lorad", "max_stars_repo_head_hexsha": "bdc70e966e423e92aef66ef9d52220a5c241e6f3", "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/likelihood.hpp", "max_issues_repo_name": "plewis/lorad", "max_issues_repo_head_hexsha": "bdc70e966e423e92aef66ef9d52220a5c241e6f3", "max_issues_repo_licenses": ["MIT"], "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/likelihood.hpp", "max_forks_repo_name": "plewis/lorad", "max_forks_repo_head_hexsha": "bdc70e966e423e92aef66ef9d52220a5c241e6f3", "max_forks_repo_licenses": ["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.5060240964, "max_line_length": 320, "alphanum_fraction": 0.5171008297, "num_tokens": 11427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.19135068512974354}}
{"text": "/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http://www.mitk.org for details.\n\n===================================================================*/\n\n#include \"itkTractsToDWIImageFilter.h\"\n#include <boost/progress.hpp>\n#include <vtkSmartPointer.h>\n#include <vtkPolyData.h>\n#include <vtkCellArray.h>\n#include <vtkPoints.h>\n#include <vtkPolyLine.h>\n#include <itkImageRegionIteratorWithIndex.h>\n#include <itkResampleImageFilter.h>\n#include <itkNearestNeighborInterpolateImageFunction.h>\n#include <itkBSplineInterpolateImageFunction.h>\n#include <itkCastImageFilter.h>\n#include <itkImageFileWriter.h>\n#include <itkRescaleIntensityImageFilter.h>\n#include <itkWindowedSincInterpolateImageFunction.h>\n#include <itkResampleDwiImageFilter.h>\n#include <itkKspaceImageFilter.h>\n#include <itkDftImageFilter.h>\n#include <itkAddImageFilter.h>\n#include <itkConstantPadImageFilter.h>\n#include <itkCropImageFilter.h>\n#include <mitkAstroStickModel.h>\n#include <vtkTransform.h>\n#include <iostream>\n#include <fstream>\n#include <itkImageDuplicator.h>\n#include <boost/lexical_cast.hpp>\n\nnamespace itk\n{\n\ntemplate< class PixelType >\nTractsToDWIImageFilter< PixelType >::TractsToDWIImageFilter()\n    : m_CircleDummy(false)\n    , m_VolumeAccuracy(10)\n    , m_AddGibbsRinging(false)\n    , m_NumberOfRepetitions(1)\n    , m_EnforcePureFiberVoxels(false)\n    , m_InterpolationShrink(1000)\n    , m_FiberRadius(0)\n    , m_SignalScale(25)\n    , m_kOffset(0)\n    , m_tLine(1)\n    , m_UseInterpolation(false)\n    , m_SimulateRelaxation(true)\n    , m_tInhom(50)\n    , m_TE(100)\n    , m_FrequencyMap(NULL)\n    , m_EddyGradientStrength(0.001)\n    , m_SimulateEddyCurrents(false)\n    , m_Spikes(0)\n    , m_Wrap(1.0)\n    , m_NoiseModel(NULL)\n    , m_SpikeAmplitude(1)\n    , m_AddMotionArtifact(false)\n{\n    m_Spacing.Fill(2.5); m_Origin.Fill(0.0);\n    m_DirectionMatrix.SetIdentity();\n    m_ImageRegion.SetSize(0, 10);\n    m_ImageRegion.SetSize(1, 10);\n    m_ImageRegion.SetSize(2, 10);\n\n    m_MaxTranslation.Fill(0.0);\n    m_MaxRotation.Fill(0.0);\n\n    m_RandGen = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();\n    m_RandGen->SetSeed();\n}\n\ntemplate< class PixelType >\nTractsToDWIImageFilter< PixelType >::~TractsToDWIImageFilter()\n{\n\n}\n\ntemplate< class PixelType >\nTractsToDWIImageFilter< PixelType >::DoubleDwiType::Pointer TractsToDWIImageFilter< PixelType >::DoKspaceStuff( std::vector< DoubleDwiType::Pointer >& images )\n{\n    // create slice object\n    ImageRegion<2> sliceRegion;\n    sliceRegion.SetSize(0, m_UpsampledImageRegion.GetSize()[0]);\n    sliceRegion.SetSize(1, m_UpsampledImageRegion.GetSize()[1]);\n    Vector< double, 2 > sliceSpacing;\n    sliceSpacing[0] = m_UpsampledSpacing[0];\n    sliceSpacing[1] = m_UpsampledSpacing[1];\n\n    // frequency map slice\n    SliceType::Pointer fMapSlice = NULL;\n    if (m_FrequencyMap.IsNotNull())\n    {\n        fMapSlice = SliceType::New();\n        ImageRegion<2> region;\n        region.SetSize(0, m_UpsampledImageRegion.GetSize()[0]);\n        region.SetSize(1, m_UpsampledImageRegion.GetSize()[1]);\n        fMapSlice->SetLargestPossibleRegion( region );\n        fMapSlice->SetBufferedRegion( region );\n        fMapSlice->SetRequestedRegion( region );\n        fMapSlice->Allocate();\n    }\n\n    DoubleDwiType::Pointer newImage = DoubleDwiType::New();\n    newImage->SetSpacing( m_Spacing );\n    newImage->SetOrigin( m_Origin );\n    newImage->SetDirection( m_DirectionMatrix );\n    newImage->SetLargestPossibleRegion( m_ImageRegion );\n    newImage->SetBufferedRegion( m_ImageRegion );\n    newImage->SetRequestedRegion( m_ImageRegion );\n    newImage->SetVectorLength( images.at(0)->GetVectorLength() );\n    newImage->Allocate();\n\n    MatrixType transform = m_DirectionMatrix;\n    for (int i=0; i<3; i++)\n        for (int j=0; j<3; j++)\n        {\n            if (j<2)\n                transform[i][j] *= m_UpsampledSpacing[j];\n            else\n                transform[i][j] *= m_Spacing[j];\n        }\n\n    std::vector< unsigned int > spikeVolume;\n    for (int i=0; i<m_Spikes; i++)\n        spikeVolume.push_back(rand()%images.at(0)->GetVectorLength());\n    std::sort (spikeVolume.begin(), spikeVolume.end());\n    std::reverse (spikeVolume.begin(), spikeVolume.end());\n\n    m_StatusText += \"0%   10   20   30   40   50   60   70   80   90   100%\\n\";\n    m_StatusText += \"|----|----|----|----|----|----|----|----|----|----|\\n*\";\n    unsigned long lastTick = 0;\n\n    boost::progress_display disp(2*images.at(0)->GetVectorLength()*images.at(0)->GetLargestPossibleRegion().GetSize(2));\n    for (unsigned int g=0; g<images.at(0)->GetVectorLength(); g++)\n    {\n        std::vector< int > spikeSlice;\n        while (!spikeVolume.empty() && spikeVolume.back()==g)\n        {\n            spikeSlice.push_back(rand()%images.at(0)->GetLargestPossibleRegion().GetSize(2));\n            spikeVolume.pop_back();\n        }\n        std::sort (spikeSlice.begin(), spikeSlice.end());\n        std::reverse (spikeSlice.begin(), spikeSlice.end());\n\n        for (unsigned int z=0; z<images.at(0)->GetLargestPossibleRegion().GetSize(2); z++)\n        {\n            std::vector< SliceType::Pointer > compartmentSlices;\n            std::vector< double > t2Vector;\n\n            for (unsigned int i=0; i<images.size(); i++)\n            {\n                DiffusionSignalModel<double>* signalModel;\n                if (i<m_FiberModels.size())\n                    signalModel = m_FiberModels.at(i);\n                else\n                    signalModel = m_NonFiberModels.at(i-m_FiberModels.size());\n\n                SliceType::Pointer slice = SliceType::New();\n                slice->SetLargestPossibleRegion( sliceRegion );\n                slice->SetBufferedRegion( sliceRegion );\n                slice->SetRequestedRegion( sliceRegion );\n                slice->SetSpacing(sliceSpacing);\n                slice->Allocate();\n                slice->FillBuffer(0.0);\n\n                // extract slice from channel g\n                for (unsigned int y=0; y<images.at(0)->GetLargestPossibleRegion().GetSize(1); y++)\n                    for (unsigned int x=0; x<images.at(0)->GetLargestPossibleRegion().GetSize(0); x++)\n                    {\n                        SliceType::IndexType index2D; index2D[0]=x; index2D[1]=y;\n                        DoubleDwiType::IndexType index3D; index3D[0]=x; index3D[1]=y; index3D[2]=z;\n\n                        slice->SetPixel(index2D, images.at(i)->GetPixel(index3D)[g]);\n\n                        if (fMapSlice.IsNotNull() && i==0)\n                            fMapSlice->SetPixel(index2D, m_FrequencyMap->GetPixel(index3D));\n                    }\n\n                compartmentSlices.push_back(slice);\n                t2Vector.push_back(signalModel->GetT2());\n            }\n\n            if (this->GetAbortGenerateData())\n                return NULL;\n\n            // create k-sapce (inverse fourier transform slices)\n            itk::Size<2> outSize; outSize.SetElement(0, m_ImageRegion.GetSize(0)); outSize.SetElement(1, m_ImageRegion.GetSize(1));\n            itk::KspaceImageFilter< SliceType::PixelType >::Pointer idft = itk::KspaceImageFilter< SliceType::PixelType >::New();\n            idft->SetCompartmentImages(compartmentSlices);\n            idft->SetT2(t2Vector);\n            idft->SetkOffset(m_kOffset);\n            idft->SettLine(m_tLine);\n            idft->SetTE(m_TE);\n            idft->SetTinhom(m_tInhom);\n            idft->SetSimulateRelaxation(m_SimulateRelaxation);\n            idft->SetSimulateEddyCurrents(m_SimulateEddyCurrents);\n            idft->SetEddyGradientMagnitude(m_EddyGradientStrength);\n            idft->SetZ((double)z-(double)images.at(0)->GetLargestPossibleRegion().GetSize(2)/2.0);\n            idft->SetDirectionMatrix(transform);\n            idft->SetDiffusionGradientDirection(m_FiberModels.at(0)->GetGradientDirection(g));\n            idft->SetFrequencyMap(fMapSlice);\n            idft->SetSignalScale(m_SignalScale);\n            idft->SetOutSize(outSize);\n            int numSpikes = 0;\n            while (!spikeSlice.empty() && spikeSlice.back()==z)\n            {\n                numSpikes++;\n                spikeSlice.pop_back();\n            }\n            idft->SetSpikes(numSpikes);\n            idft->SetSpikeAmplitude(m_SpikeAmplitude);\n            idft->Update();\n\n            ComplexSliceType::Pointer fSlice;\n            fSlice = idft->GetOutput();\n\n            ++disp;\n            unsigned long newTick = 50*disp.count()/disp.expected_count();\n            for (int tick = 0; tick<(newTick-lastTick); tick++)\n                m_StatusText += \"*\";\n            lastTick = newTick;\n\n            // fourier transform slice\n            SliceType::Pointer newSlice;\n            itk::DftImageFilter< SliceType::PixelType >::Pointer dft = itk::DftImageFilter< SliceType::PixelType >::New();\n            dft->SetInput(fSlice);\n            dft->Update();\n            newSlice = dft->GetOutput();\n\n            // put slice back into channel g\n            for (unsigned int y=0; y<fSlice->GetLargestPossibleRegion().GetSize(1); y++)\n                for (unsigned int x=0; x<fSlice->GetLargestPossibleRegion().GetSize(0); x++)\n                {\n                    DoubleDwiType::IndexType index3D; index3D[0]=x; index3D[1]=y; index3D[2]=z;\n                    SliceType::IndexType index2D; index2D[0]=x; index2D[1]=y;\n\n                    DoubleDwiType::PixelType pix3D = newImage->GetPixel(index3D);\n                    pix3D[g] = newSlice->GetPixel(index2D);\n                    newImage->SetPixel(index3D, pix3D);\n                }\n            ++disp;\n            newTick = 50*disp.count()/disp.expected_count();\n            for (int tick = 0; tick<(newTick-lastTick); tick++)\n                m_StatusText += \"*\";\n            lastTick = newTick;\n        }\n    }\n    m_StatusText += \"\\n\\n\";\n    return newImage;\n}\n\ntemplate< class PixelType >\nvoid TractsToDWIImageFilter< PixelType >::GenerateData()\n{\n    m_StartTime = clock();\n    m_StatusText = \"Starting simulation\\n\";\n\n    // check input data\n    if (m_FiberBundle.IsNull())\n        itkExceptionMacro(\"Input fiber bundle is NULL!\");\n\n    int numFibers = m_FiberBundle->GetNumFibers();\n    if (numFibers<=0)\n        itkExceptionMacro(\"Input fiber bundle contains no fibers!\");\n\n    if (m_FiberModels.empty())\n        itkExceptionMacro(\"No diffusion model for fiber compartments defined!\");\n\n    if (m_EnforcePureFiberVoxels)\n        while (m_FiberModels.size()>1)\n            m_FiberModels.pop_back();\n\n    if (m_NonFiberModels.empty())\n        itkExceptionMacro(\"No diffusion model for non-fiber compartments defined!\");\n\n    int baselineIndex = m_FiberModels[0]->GetFirstBaselineIndex();\n    if (baselineIndex<0)\n        itkExceptionMacro(\"No baseline index found!\");\n\n    // initialize output dwi image\n    ImageRegion<3> croppedRegion = m_ImageRegion; croppedRegion.SetSize(1, croppedRegion.GetSize(1)*m_Wrap);\n    itk::Point<double,3> shiftedOrigin = m_Origin; shiftedOrigin[1] += (m_ImageRegion.GetSize(1)-croppedRegion.GetSize(1))*m_Spacing[1]/2;\n\n    typename OutputImageType::Pointer outImage = OutputImageType::New();\n    outImage->SetSpacing( m_Spacing );\n    outImage->SetOrigin( shiftedOrigin );\n    outImage->SetDirection( m_DirectionMatrix );\n    outImage->SetLargestPossibleRegion( croppedRegion );\n    outImage->SetBufferedRegion( croppedRegion );\n    outImage->SetRequestedRegion( croppedRegion );\n    outImage->SetVectorLength( m_FiberModels[0]->GetNumGradients() );\n    outImage->Allocate();\n    typename OutputImageType::PixelType temp;\n    temp.SetSize(m_FiberModels[0]->GetNumGradients());\n    temp.Fill(0.0);\n    outImage->FillBuffer(temp);\n\n    // ADJUST GEOMETRY FOR FURTHER PROCESSING\n    // is input slize size a power of two?\n    unsigned int x=m_ImageRegion.GetSize(0); unsigned int y=m_ImageRegion.GetSize(1);\n    if ( x%2 == 1 )\n        m_ImageRegion.SetSize(0, x+1);\n    if ( y%2 == 1 )\n        m_ImageRegion.SetSize(1, y+1);\n\n    // apply in-plane upsampling\n    double upsampling = 1;\n    if (m_AddGibbsRinging)\n    {\n        m_StatusText += \"Gibbs ringing enabled\\n\";\n        MITK_INFO << \"Adding ringing artifacts.\";\n        upsampling = 2;\n    }\n    m_UpsampledSpacing = m_Spacing;\n    m_UpsampledSpacing[0] /= upsampling;\n    m_UpsampledSpacing[1] /= upsampling;\n    m_UpsampledImageRegion = m_ImageRegion;\n    m_UpsampledImageRegion.SetSize(0, m_ImageRegion.GetSize()[0]*upsampling);\n    m_UpsampledImageRegion.SetSize(1, m_ImageRegion.GetSize()[1]*upsampling);\n    m_UpsampledOrigin = m_Origin;\n    m_UpsampledOrigin[0] -= m_Spacing[0]/2; m_UpsampledOrigin[0] += m_UpsampledSpacing[0]/2;\n    m_UpsampledOrigin[1] -= m_Spacing[1]/2; m_UpsampledOrigin[1] += m_UpsampledSpacing[1]/2;\n    m_UpsampledOrigin[2] -= m_Spacing[2]/2; m_UpsampledOrigin[2] += m_UpsampledSpacing[2]/2;\n\n    // generate double images to store the individual compartment signals\n    std::vector< DoubleDwiType::Pointer > compartments;\n    for (unsigned int i=0; i<m_FiberModels.size()+m_NonFiberModels.size(); i++)\n    {\n        DoubleDwiType::Pointer doubleDwi = DoubleDwiType::New();\n        doubleDwi->SetSpacing( m_UpsampledSpacing );\n        doubleDwi->SetOrigin( m_UpsampledOrigin );\n        doubleDwi->SetDirection( m_DirectionMatrix );\n        doubleDwi->SetLargestPossibleRegion( m_UpsampledImageRegion );\n        doubleDwi->SetBufferedRegion( m_UpsampledImageRegion );\n        doubleDwi->SetRequestedRegion( m_UpsampledImageRegion );\n        doubleDwi->SetVectorLength( m_FiberModels[0]->GetNumGradients() );\n        doubleDwi->Allocate();\n        DoubleDwiType::PixelType pix;\n        pix.SetSize(m_FiberModels[0]->GetNumGradients());\n        pix.Fill(0.0);\n        doubleDwi->FillBuffer(pix);\n        compartments.push_back(doubleDwi);\n    }\n\n    // initialize volume fraction images\n    m_VolumeFractions.clear();\n    for (unsigned int i=0; i<m_FiberModels.size()+m_NonFiberModels.size(); i++)\n    {\n        ItkDoubleImgType::Pointer doubleImg = ItkDoubleImgType::New();\n        doubleImg->SetSpacing( m_UpsampledSpacing );\n        doubleImg->SetOrigin( m_UpsampledOrigin );\n        doubleImg->SetDirection( m_DirectionMatrix );\n        doubleImg->SetLargestPossibleRegion( m_UpsampledImageRegion );\n        doubleImg->SetBufferedRegion( m_UpsampledImageRegion );\n        doubleImg->SetRequestedRegion( m_UpsampledImageRegion );\n        doubleImg->Allocate();\n        doubleImg->FillBuffer(0);\n        m_VolumeFractions.push_back(doubleImg);\n    }\n\n    // resample mask image and frequency map to fit upsampled geometry\n    if (m_AddGibbsRinging)\n    {\n        if (m_TissueMask.IsNotNull())\n        {\n            // rescale mask image (otherwise there are problems with the resampling)\n            itk::RescaleIntensityImageFilter<ItkUcharImgType,ItkUcharImgType>::Pointer rescaler = itk::RescaleIntensityImageFilter<ItkUcharImgType,ItkUcharImgType>::New();\n            rescaler->SetInput(0,m_TissueMask);\n            rescaler->SetOutputMaximum(100);\n            rescaler->SetOutputMinimum(0);\n            rescaler->Update();\n\n            // resample mask image\n            itk::ResampleImageFilter<ItkUcharImgType, ItkUcharImgType>::Pointer resampler = itk::ResampleImageFilter<ItkUcharImgType, ItkUcharImgType>::New();\n            resampler->SetInput(rescaler->GetOutput());\n            resampler->SetOutputParametersFromImage(m_TissueMask);\n            resampler->SetSize(m_UpsampledImageRegion.GetSize());\n            resampler->SetOutputSpacing(m_UpsampledSpacing);\n            resampler->SetOutputOrigin(m_UpsampledOrigin);\n            resampler->Update();\n            m_TissueMask = resampler->GetOutput();\n        }\n\n        // resample frequency map\n        if (m_FrequencyMap.IsNotNull())\n        {\n            itk::ResampleImageFilter<ItkDoubleImgType, ItkDoubleImgType>::Pointer resampler = itk::ResampleImageFilter<ItkDoubleImgType, ItkDoubleImgType>::New();\n            resampler->SetInput(m_FrequencyMap);\n            resampler->SetOutputParametersFromImage(m_FrequencyMap);\n            resampler->SetSize(m_UpsampledImageRegion.GetSize());\n            resampler->SetOutputSpacing(m_UpsampledSpacing);\n            resampler->SetOutputOrigin(m_UpsampledOrigin);\n            resampler->Update();\n            m_FrequencyMap = resampler->GetOutput();\n        }\n    }\n\n    // no input tissue mask is set -> create default\n    bool maskImageSet = true;\n    if (m_TissueMask.IsNull())\n    {\n        m_StatusText += \"No tissue mask set\\n\";\n        MITK_INFO << \"No tissue mask set\";\n        m_TissueMask = ItkUcharImgType::New();\n        m_TissueMask->SetSpacing( m_UpsampledSpacing );\n        m_TissueMask->SetOrigin( m_UpsampledOrigin );\n        m_TissueMask->SetDirection( m_DirectionMatrix );\n        m_TissueMask->SetLargestPossibleRegion( m_UpsampledImageRegion );\n        m_TissueMask->SetBufferedRegion( m_UpsampledImageRegion );\n        m_TissueMask->SetRequestedRegion( m_UpsampledImageRegion );\n        m_TissueMask->Allocate();\n        m_TissueMask->FillBuffer(1);\n        maskImageSet = false;\n    }\n    else\n    {\n        m_StatusText += \"Using tissue mask\\n\";\n        MITK_INFO << \"Using tissue mask\";\n    }\n\n    m_ImageRegion = croppedRegion;\n    x=m_ImageRegion.GetSize(0); y=m_ImageRegion.GetSize(1);\n    if ( x%2 == 1 )\n        m_ImageRegion.SetSize(0, x+1);\n    if ( y%2 == 1 )\n        m_ImageRegion.SetSize(1, y+1);\n\n    // resample fiber bundle for sufficient voxel coverage\n    m_StatusText += \"\\n\"+this->GetTime()+\" > Resampling fibers ...\\n\";\n    double segmentVolume = 0.0001;\n    float minSpacing = 1;\n    if(m_UpsampledSpacing[0]<m_UpsampledSpacing[1] && m_UpsampledSpacing[0]<m_UpsampledSpacing[2])\n        minSpacing = m_UpsampledSpacing[0];\n    else if (m_UpsampledSpacing[1] < m_UpsampledSpacing[2])\n        minSpacing = m_UpsampledSpacing[1];\n    else\n        minSpacing = m_UpsampledSpacing[2];\n    FiberBundleType fiberBundle = m_FiberBundle->GetDeepCopy();\n    fiberBundle->ResampleFibers(minSpacing/m_VolumeAccuracy);\n    double mmRadius = m_FiberRadius/1000;\n    if (mmRadius>0)\n        segmentVolume = M_PI*mmRadius*mmRadius*minSpacing/m_VolumeAccuracy;\n\n    double interpFact = 2*atan(-0.5*m_InterpolationShrink);\n    double maxVolume = 0;\n    double voxelVolume = m_UpsampledSpacing[0]*m_UpsampledSpacing[1]*m_UpsampledSpacing[2];\n\n    if (m_AddMotionArtifact)\n    {\n        if (m_RandomMotion)\n        {\n            m_StatusText += \"Adding random motion artifacts:\\n\";\n            m_StatusText += \"Maximum rotation: +/-\" + boost::lexical_cast<std::string>(m_MaxRotation) + \"\u00b0\\n\";\n            m_StatusText += \"Maximum translation: +/-\" + boost::lexical_cast<std::string>(m_MaxTranslation) + \"mm\\n\";\n        }\n        else\n        {\n            m_StatusText += \"Adding linear motion artifacts:\\n\";\n            m_StatusText += \"Maximum rotation: \" + boost::lexical_cast<std::string>(m_MaxRotation) + \"\u00b0\\n\";\n            m_StatusText += \"Maximum translation: \" + boost::lexical_cast<std::string>(m_MaxTranslation) + \"mm\\n\";\n        }\n        MITK_INFO << \"Adding motion artifacts\";\n        MITK_INFO << \"Maximum rotation: \" << m_MaxRotation;\n        MITK_INFO << \"Maxmimum translation: \" << m_MaxTranslation;\n    }\n    maxVolume = 0;\n\n    m_StatusText += \"\\n\"+this->GetTime()+\" > Generating signal of \" + boost::lexical_cast<std::string>(m_FiberModels.size()) + \" fiber compartments\\n\";\n    MITK_INFO << \"Generating signal of \" << m_FiberModels.size() << \" fiber compartments\";\n    boost::progress_display disp(numFibers*m_FiberModels.at(0)->GetNumGradients());\n\n    ofstream logFile;\n    logFile.open(\"fiberfox_motion.log\");\n    logFile << \"0 rotation: 0,0,0; translation: 0,0,0\\n\";\n\n    // get transform for motion artifacts\n    FiberBundleType fiberBundleTransformed = fiberBundle;\n    VectorType rotation = m_MaxRotation/m_FiberModels.at(0)->GetNumGradients();\n    VectorType translation = m_MaxTranslation/m_FiberModels.at(0)->GetNumGradients();\n\n    // creat image to hold transformed mask (motion artifact)\n    ItkUcharImgType::Pointer tempTissueMask = ItkUcharImgType::New();\n    itk::ImageDuplicator<ItkUcharImgType>::Pointer duplicator = itk::ImageDuplicator<ItkUcharImgType>::New();\n    duplicator->SetInputImage(m_TissueMask);\n    duplicator->Update();\n    tempTissueMask = duplicator->GetOutput();\n\n    // second upsampling needed for motion artifacts\n    ImageRegion<3>                      upsampledImageRegion = m_UpsampledImageRegion;\n    itk::Vector<double,3>               upsampledSpacing = m_UpsampledSpacing;\n    upsampledSpacing[0] /= 4;\n    upsampledSpacing[1] /= 4;\n    upsampledSpacing[2] /= 4;\n    upsampledImageRegion.SetSize(0, m_UpsampledImageRegion.GetSize()[0]*4);\n    upsampledImageRegion.SetSize(1, m_UpsampledImageRegion.GetSize()[1]*4);\n    upsampledImageRegion.SetSize(2, m_UpsampledImageRegion.GetSize()[2]*4);\n    itk::Point<double,3> upsampledOrigin = m_UpsampledOrigin;\n    upsampledOrigin[0] -= m_UpsampledSpacing[0]/2; upsampledOrigin[0] += upsampledSpacing[0]/2;\n    upsampledOrigin[1] -= m_UpsampledSpacing[1]/2; upsampledOrigin[1] += upsampledSpacing[1]/2;\n    upsampledOrigin[2] -= m_UpsampledSpacing[2]/2; upsampledOrigin[2] += upsampledSpacing[2]/2;\n    ItkUcharImgType::Pointer upsampledTissueMask = ItkUcharImgType::New();\n    itk::ResampleImageFilter<ItkUcharImgType, ItkUcharImgType>::Pointer upsampler = itk::ResampleImageFilter<ItkUcharImgType, ItkUcharImgType>::New();\n    upsampler->SetInput(m_TissueMask);\n    upsampler->SetOutputParametersFromImage(m_TissueMask);\n    upsampler->SetSize(upsampledImageRegion.GetSize());\n    upsampler->SetOutputSpacing(upsampledSpacing);\n    upsampler->SetOutputOrigin(upsampledOrigin);\n    itk::NearestNeighborInterpolateImageFunction<ItkUcharImgType>::Pointer nn_interpolator\n            = itk::NearestNeighborInterpolateImageFunction<ItkUcharImgType>::New();\n    upsampler->SetInterpolator(nn_interpolator);\n    upsampler->Update();\n    upsampledTissueMask = upsampler->GetOutput();\n\n    m_StatusText += \"0%   10   20   30   40   50   60   70   80   90   100%\\n\";\n    m_StatusText += \"|----|----|----|----|----|----|----|----|----|----|\\n*\";\n    unsigned int lastTick = 0;\n\n    for (int g=0; g<m_FiberModels.at(0)->GetNumGradients(); g++)\n    {\n        vtkPolyData* fiberPolyData = fiberBundleTransformed->GetFiberPolyData();\n\n        ItkDoubleImgType::Pointer intraAxonalVolume = ItkDoubleImgType::New();\n        intraAxonalVolume->SetSpacing( m_UpsampledSpacing );\n        intraAxonalVolume->SetOrigin( m_UpsampledOrigin );\n        intraAxonalVolume->SetDirection( m_DirectionMatrix );\n        intraAxonalVolume->SetLargestPossibleRegion( m_UpsampledImageRegion );\n        intraAxonalVolume->SetBufferedRegion( m_UpsampledImageRegion );\n        intraAxonalVolume->SetRequestedRegion( m_UpsampledImageRegion );\n        intraAxonalVolume->Allocate();\n        intraAxonalVolume->FillBuffer(0);\n\n        // generate fiber signal\n        for( int i=0; i<numFibers; i++ )\n        {\n            vtkCell* cell = fiberPolyData->GetCell(i);\n            int numPoints = cell->GetNumberOfPoints();\n            vtkPoints* points = cell->GetPoints();\n\n            if (numPoints<2)\n                continue;\n\n            for( int j=0; j<numPoints; j++)\n            {\n                if (this->GetAbortGenerateData())\n                {\n                    m_StatusText += \"\\n\"+this->GetTime()+\" > Simulation aborted\\n\";\n                    return;\n                }\n\n                double* temp = points->GetPoint(j);\n                itk::Point<float, 3> vertex = GetItkPoint(temp);\n                itk::Vector<double> v = GetItkVector(temp);\n\n                itk::Vector<double, 3> dir(3);\n                if (j<numPoints-1)\n                    dir = GetItkVector(points->GetPoint(j+1))-v;\n                else\n                    dir = v-GetItkVector(points->GetPoint(j-1));\n\n                if (dir.GetSquaredNorm()<0.0001 || dir[0]!=dir[0] || dir[1]!=dir[1] || dir[2]!=dir[2])\n                    continue;\n\n                itk::Index<3> idx;\n                itk::ContinuousIndex<float, 3> contIndex;\n                tempTissueMask->TransformPhysicalPointToIndex(vertex, idx);\n                tempTissueMask->TransformPhysicalPointToContinuousIndex(vertex, contIndex);\n\n                if (!m_UseInterpolation)    // use nearest neighbour interpolation\n                {\n                    if (!tempTissueMask->GetLargestPossibleRegion().IsInside(idx) || tempTissueMask->GetPixel(idx)<=0)\n                        continue;\n\n                    // generate signal for each fiber compartment\n                    for (unsigned int k=0; k<m_FiberModels.size(); k++)\n                    {\n                        DoubleDwiType::Pointer doubleDwi = compartments.at(k);\n                        m_FiberModels[k]->SetFiberDirection(dir);\n                        DoubleDwiType::PixelType pix = doubleDwi->GetPixel(idx);\n                        pix[g] += segmentVolume*m_FiberModels[k]->SimulateMeasurement(g);\n\n                        if (pix[g]!=pix[g])\n                        {\n                            std::cout << \"pix[g] \" << pix[g] << std::endl;\n                            std::cout << \"dir \" << dir << std::endl;\n                            std::cout << \"segmentVolume \" << segmentVolume << std::endl;\n                            std::cout << \"m_FiberModels[k]->SimulateMeasurement(g) \" << m_FiberModels[k]->SimulateMeasurement(g) << std::endl;\n                        }\n\n                        doubleDwi->SetPixel(idx, pix );\n\n                        double vol = intraAxonalVolume->GetPixel(idx) + segmentVolume;\n                        intraAxonalVolume->SetPixel(idx, vol );\n\n                        if (g==0 && vol>maxVolume)\n                            maxVolume = vol;\n                    }\n                    continue;\n                }\n\n                double frac_x = contIndex[0] - idx[0]; double frac_y = contIndex[1] - idx[1]; double frac_z = contIndex[2] - idx[2];\n                if (frac_x<0)\n                {\n                    idx[0] -= 1;\n                    frac_x += 1;\n                }\n                if (frac_y<0)\n                {\n                    idx[1] -= 1;\n                    frac_y += 1;\n                }\n                if (frac_z<0)\n                {\n                    idx[2] -= 1;\n                    frac_z += 1;\n                }\n\n                frac_x = atan((0.5-frac_x)*m_InterpolationShrink)/interpFact + 0.5;\n                frac_y = atan((0.5-frac_y)*m_InterpolationShrink)/interpFact + 0.5;\n                frac_z = atan((0.5-frac_z)*m_InterpolationShrink)/interpFact + 0.5;\n\n                // use trilinear interpolation\n                itk::Index<3> newIdx;\n                for (int x=0; x<2; x++)\n                {\n                    frac_x = 1-frac_x;\n                    for (int y=0; y<2; y++)\n                    {\n                        frac_y = 1-frac_y;\n                        for (int z=0; z<2; z++)\n                        {\n                            frac_z = 1-frac_z;\n\n                            newIdx[0] = idx[0]+x;\n                            newIdx[1] = idx[1]+y;\n                            newIdx[2] = idx[2]+z;\n\n                            double frac = frac_x*frac_y*frac_z;\n\n                            // is position valid?\n                            if (!tempTissueMask->GetLargestPossibleRegion().IsInside(newIdx) || tempTissueMask->GetPixel(newIdx)<=0)\n                                continue;\n\n                            // generate signal for each fiber compartment\n                            for (unsigned int k=0; k<m_FiberModels.size(); k++)\n                            {\n                                DoubleDwiType::Pointer doubleDwi = compartments.at(k);\n                                m_FiberModels[k]->SetFiberDirection(dir);\n                                DoubleDwiType::PixelType pix = doubleDwi->GetPixel(newIdx);\n                                pix[g] += segmentVolume*frac*m_FiberModels[k]->SimulateMeasurement(g);\n                                doubleDwi->SetPixel(newIdx, pix );\n\n                                double vol = intraAxonalVolume->GetPixel(idx) + segmentVolume;\n                                intraAxonalVolume->SetPixel(idx, vol );\n\n                                if (g==0 && vol>maxVolume)\n                                    maxVolume = vol;\n                            }\n                        }\n                    }\n                }\n            }\n            ++disp;\n            unsigned long newTick = 50*disp.count()/disp.expected_count();\n            for (int tick = 0; tick<(newTick-lastTick); tick++)\n                m_StatusText += \"*\";\n            lastTick = newTick;\n        }\n\n        // generate non-fiber signal\n        ImageRegionIterator<ItkUcharImgType> it3(tempTissueMask, tempTissueMask->GetLargestPossibleRegion());\n        double fact = 1;\n        if (m_FiberRadius<0.0001)\n            fact = voxelVolume/maxVolume;\n        while(!it3.IsAtEnd())\n        {\n            if (it3.Get()>0)\n            {\n                DoubleDwiType::IndexType index = it3.GetIndex();\n\n                // get fiber volume fraction\n                DoubleDwiType::Pointer fiberDwi = compartments.at(0);\n                DoubleDwiType::PixelType fiberPix = fiberDwi->GetPixel(index); // intra axonal compartment\n                if (fact>1) // auto scale intra-axonal if no fiber radius is specified\n                {\n                    fiberPix[g] *= fact;\n                    fiberDwi->SetPixel(index, fiberPix);\n                }\n                double f = intraAxonalVolume->GetPixel(index)*fact;\n\n                if (f>voxelVolume || (f>0.0 && m_EnforcePureFiberVoxels) )  // more fiber than space in voxel?\n                {\n                    fiberPix[g] *= voxelVolume/f;\n                    fiberDwi->SetPixel(index, fiberPix);\n                    m_VolumeFractions.at(0)->SetPixel(index, 1);\n                }\n                else\n                {\n                    m_VolumeFractions.at(0)->SetPixel(index, f/voxelVolume);\n\n                    double nonf = voxelVolume-f;    // non-fiber volume\n                    double inter = 0;\n                    if (m_FiberModels.size()>1)\n                        inter = nonf * f/voxelVolume;   // inter-axonal fraction of non fiber compartment scales linearly with f\n                    double other = nonf - inter;        // rest of compartment\n                    double singleinter = inter/(m_FiberModels.size()-1);\n\n                    // adjust non-fiber and intra-axonal signal\n                    for (unsigned int i=1; i<m_FiberModels.size(); i++)\n                    {\n                        DoubleDwiType::Pointer doubleDwi = compartments.at(i);\n                        DoubleDwiType::PixelType pix = doubleDwi->GetPixel(index);\n                        if (f>0)\n                            pix[g] /= f;\n                        pix[g] *= singleinter;\n                        doubleDwi->SetPixel(index, pix);\n                        m_VolumeFractions.at(i)->SetPixel(index, singleinter/voxelVolume);\n                    }\n                    for (unsigned int i=0; i<m_NonFiberModels.size(); i++)\n                    {\n                        DoubleDwiType::Pointer doubleDwi = compartments.at(i+m_FiberModels.size());\n                        DoubleDwiType::PixelType pix = doubleDwi->GetPixel(index);\n                        //                        if (dynamic_cast< mitk::AstroStickModel<double>* >(m_NonFiberModels.at(i)))\n                        //                        {\n                        //                            mitk::AstroStickModel<double>* model = dynamic_cast< mitk::AstroStickModel<double>* >(m_NonFiberModels.at(i));\n                        //                            model->SetSeed(8111984);\n                        //                        }\n                        pix[g] += m_NonFiberModels[i]->SimulateMeasurement(g)*other*m_NonFiberModels[i]->GetWeight();\n                        doubleDwi->SetPixel(index, pix);\n                        m_VolumeFractions.at(i+m_FiberModels.size())->SetPixel(index, other/voxelVolume*m_NonFiberModels[i]->GetWeight());\n                    }\n                }\n            }\n            ++it3;\n        }\n\n        // move fibers\n        if (m_AddMotionArtifact)\n        {\n            if (m_RandomMotion)\n            {\n                fiberBundleTransformed = fiberBundle->GetDeepCopy();\n                rotation[0] = m_RandGen->GetVariateWithClosedRange(m_MaxRotation[0]*2)-m_MaxRotation[0];\n                rotation[1] = m_RandGen->GetVariateWithClosedRange(m_MaxRotation[1]*2)-m_MaxRotation[1];\n                rotation[2] = m_RandGen->GetVariateWithClosedRange(m_MaxRotation[2]*2)-m_MaxRotation[2];\n                translation[0] = m_RandGen->GetVariateWithClosedRange(m_MaxTranslation[0]*2)-m_MaxTranslation[0];\n                translation[1] = m_RandGen->GetVariateWithClosedRange(m_MaxTranslation[1]*2)-m_MaxTranslation[1];\n                translation[2] = m_RandGen->GetVariateWithClosedRange(m_MaxTranslation[2]*2)-m_MaxTranslation[2];\n            }\n\n            // rotate mask image\n            if (maskImageSet)\n            {\n                ImageRegionIterator<ItkUcharImgType> maskIt(upsampledTissueMask, upsampledTissueMask->GetLargestPossibleRegion());\n                tempTissueMask->FillBuffer(0);\n\n                while(!maskIt.IsAtEnd())\n                {\n                    if (maskIt.Get()<=0)\n                    {\n                        ++maskIt;\n                        continue;\n                    }\n\n                    DoubleDwiType::IndexType index = maskIt.GetIndex();\n                    itk::Point<double, 3> point;\n                    upsampledTissueMask->TransformIndexToPhysicalPoint(index, point);\n                    if (m_RandomMotion)\n                        point = fiberBundle->TransformPoint(point.GetVnlVector(), rotation[0],rotation[1],rotation[2],translation[0],translation[1],translation[2]);\n                    else\n                        point = fiberBundle->TransformPoint(point.GetVnlVector(), rotation[0]*(g+1),rotation[1]*(g+1),rotation[2]*(g+1),translation[0]*(g+1),translation[1]*(g+1),translation[2]*(g+1));\n\n                    tempTissueMask->TransformPhysicalPointToIndex(point, index);\n                    if (tempTissueMask->GetLargestPossibleRegion().IsInside(index))\n                        tempTissueMask->SetPixel(index,100);\n                    ++maskIt;\n                }\n            }\n\n            // rotate fibers\n            logFile << g+1 << \" rotation:\" << rotation[0] << \",\" << rotation[1] << \",\" << rotation[2] << \";\";\n            logFile << \" translation:\" << translation[0] << \",\" << translation[1] << \",\" << translation[2] << \"\\n\";\n            fiberBundleTransformed->TransformFibers(rotation[0],rotation[1],rotation[2],translation[0],translation[1],translation[2]);\n        }\n    }\n    logFile.close();\n    m_StatusText += \"\\n\\n\";\n    if (this->GetAbortGenerateData())\n    {\n        m_StatusText += \"\\n\"+this->GetTime()+\" > Simulation aborted\\n\";\n        return;\n    }\n\n    // do k-space stuff\n    DoubleDwiType::Pointer doubleOutImage;\n    if (m_Spikes>0 || m_FrequencyMap.IsNotNull() || m_kOffset>0 || m_SimulateRelaxation || m_SimulateEddyCurrents || m_AddGibbsRinging || m_Wrap<1.0)\n    {\n        m_StatusText += this->GetTime()+\" > Adjusting complex signal\\n\";\n        MITK_INFO << \"Adjusting complex signal\";\n        doubleOutImage = DoKspaceStuff(compartments);\n        m_SignalScale = 1;\n    }\n    else\n    {\n        m_StatusText += this->GetTime()+\" > Summing compartments\\n\";\n        MITK_INFO << \"Summing compartments\";\n        doubleOutImage = compartments.at(0);\n\n        for (unsigned int i=1; i<compartments.size(); i++)\n        {\n            itk::AddImageFilter< DoubleDwiType, DoubleDwiType, DoubleDwiType>::Pointer adder = itk::AddImageFilter< DoubleDwiType, DoubleDwiType, DoubleDwiType>::New();\n            adder->SetInput1(doubleOutImage);\n            adder->SetInput2(compartments.at(i));\n            adder->Update();\n            doubleOutImage = adder->GetOutput();\n        }\n    }\n    if (this->GetAbortGenerateData())\n    {\n        m_StatusText += \"\\n\"+this->GetTime()+\" > Simulation aborted\\n\";\n        return;\n    }\n\n    m_StatusText += this->GetTime()+\" > Finalizing image\\n\";\n    MITK_INFO << \"Finalizing image\";\n    unsigned int window = 0;\n    unsigned int min = itk::NumericTraits<unsigned int>::max();\n    ImageRegionIterator<OutputImageType> it4 (outImage, outImage->GetLargestPossibleRegion());\n    DoubleDwiType::PixelType signal; signal.SetSize(m_FiberModels[0]->GetNumGradients());\n    boost::progress_display disp2(outImage->GetLargestPossibleRegion().GetNumberOfPixels());\n\n    m_StatusText += \"0%   10   20   30   40   50   60   70   80   90   100%\\n\";\n    m_StatusText += \"|----|----|----|----|----|----|----|----|----|----|\\n*\";\n    lastTick = 0;\n\n    while(!it4.IsAtEnd())\n    {\n        if (this->GetAbortGenerateData())\n        {\n            m_StatusText += \"\\n\"+this->GetTime()+\" > Simulation aborted\\n\";\n            return;\n        }\n\n        ++disp2;\n        unsigned long newTick = 50*disp2.count()/disp2.expected_count();\n        for (int tick = 0; tick<(newTick-lastTick); tick++)\n            m_StatusText += \"*\";\n        lastTick = newTick;\n\n        typename OutputImageType::IndexType index = it4.GetIndex();\n        signal = doubleOutImage->GetPixel(index)*m_SignalScale;\n\n        if (m_NoiseModel!=NULL)\n        {\n            DoubleDwiType::PixelType accu = signal; accu.Fill(0.0);\n            for (unsigned int i=0; i<m_NumberOfRepetitions; i++)\n            {\n                DoubleDwiType::PixelType temp = signal;\n                m_NoiseModel->AddNoise(temp);\n                accu += temp;\n            }\n            signal = accu/m_NumberOfRepetitions;\n        }\n\n        for (unsigned int i=0; i<signal.Size(); i++)\n        {\n            if (signal[i]>0)\n                signal[i] = floor(signal[i]+0.5);\n            else\n                signal[i] = ceil(signal[i]-0.5);\n\n            if (!m_FiberModels.at(0)->IsBaselineIndex(i) && signal[i]>window)\n                window = signal[i];\n            if (!m_FiberModels.at(0)->IsBaselineIndex(i) && signal[i]<min)\n                min = signal[i];\n        }\n        it4.Set(signal);\n        ++it4;\n    }\n    window -= min;\n    unsigned int level = window/2 + min;\n    m_LevelWindow.SetLevelWindow(level, window);\n    this->SetNthOutput(0, outImage);\n\n    m_StatusText += \"\\n\\n\";\n    m_StatusText += \"Finished simulation\\n\";\n    m_StatusText += \"Simulation time: \"+GetTime();\n}\n\ntemplate< class PixelType >\nitk::Point<float, 3> TractsToDWIImageFilter< PixelType >::GetItkPoint(double point[3])\n{\n    itk::Point<float, 3> itkPoint;\n    itkPoint[0] = point[0];\n    itkPoint[1] = point[1];\n    itkPoint[2] = point[2];\n    return itkPoint;\n}\n\ntemplate< class PixelType >\nitk::Vector<double, 3> TractsToDWIImageFilter< PixelType >::GetItkVector(double point[3])\n{\n    itk::Vector<double, 3> itkVector;\n    itkVector[0] = point[0];\n    itkVector[1] = point[1];\n    itkVector[2] = point[2];\n    return itkVector;\n}\n\ntemplate< class PixelType >\nvnl_vector_fixed<double, 3> TractsToDWIImageFilter< PixelType >::GetVnlVector(double point[3])\n{\n    vnl_vector_fixed<double, 3> vnlVector;\n    vnlVector[0] = point[0];\n    vnlVector[1] = point[1];\n    vnlVector[2] = point[2];\n    return vnlVector;\n}\n\ntemplate< class PixelType >\nvnl_vector_fixed<double, 3> TractsToDWIImageFilter< PixelType >::GetVnlVector(Vector<float,3>& vector)\n{\n    vnl_vector_fixed<double, 3> vnlVector;\n    vnlVector[0] = vector[0];\n    vnlVector[1] = vector[1];\n    vnlVector[2] = vector[2];\n    return vnlVector;\n}\n\ntemplate< class PixelType >\nstd::string TractsToDWIImageFilter< PixelType >::GetTime()\n{\n    unsigned long total = (double)(clock() - m_StartTime)/CLOCKS_PER_SEC;\n    unsigned long hours = total/3600;\n    unsigned long minutes = (total%3600)/60;\n    unsigned long seconds = total%60;\n    std::string out = \"\";\n    out.append(boost::lexical_cast<std::string>(hours));\n    out.append(\":\");\n    out.append(boost::lexical_cast<std::string>(minutes));\n    out.append(\":\");\n    out.append(boost::lexical_cast<std::string>(seconds));\n    return out;\n}\n\n}\n", "meta": {"hexsha": "732b38f10e924e355ecc0e0b37c3ed5c0c819f70", "size": 40498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp", "max_stars_repo_name": "rfloca/MITK", "max_stars_repo_head_hexsha": "b7dcb830dc36a5d3011b9828c3d71e496d3936ad", "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/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp", "max_issues_repo_name": "rfloca/MITK", "max_issues_repo_head_hexsha": "b7dcb830dc36a5d3011b9828c3d71e496d3936ad", "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/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp", "max_forks_repo_name": "rfloca/MITK", "max_forks_repo_head_hexsha": "b7dcb830dc36a5d3011b9828c3d71e496d3936ad", "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.1854166667, "max_line_length": 200, "alphanum_fraction": 0.5917329251, "num_tokens": 10281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.1913506763136411}}
{"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 \"NDDODipoleMatrixCalculator.h\"\n#include \"Sparrow/Implementations/Nddo/Utils/DipoleUtils/AtomPairDipole.h\"\n#include \"Sparrow/Implementations/Nddo/Utils/DipoleUtils/GTODipoleMatrixBlock.h\"\n#include <Sparrow/Implementations/Nddo/Am1/AM1Method.h>\n#include <Sparrow/Implementations/Nddo/Mndo/MNDOMethod.h>\n#include <Sparrow/Implementations/Nddo/Pm6/PM6Method.h>\n#include <Sparrow/Implementations/Nddo/Utils/NDDOInitializer.h>\n#include <Sparrow/Implementations/Nddo/Utils/ParameterUtils/ElementParameters.h>\n#include <Utils/DataStructures/AtomsOrbitalsIndexes.h>\n#include <Utils/Geometry.h>\n#include <Utils/Typenames.h>\n#include <Eigen/Core>\n\nnamespace Scine {\nnamespace Sparrow {\n\ntemplate<class NDDOMethod>\nNDDODipoleMatrixCalculator<NDDOMethod>::~NDDODipoleMatrixCalculator() = default;\n\ntemplate<class NDDOMethod>\nvoid NDDODipoleMatrixCalculator<NDDOMethod>::initialize() {\n  nAtoms_ = aoIndexes_.getNAtoms();\n  nAOs_ = aoIndexes_.getNAtomicOrbitals();\n  dipoleMatrix_.reset(nAOs_);\n  valid_ = false;\n}\ntemplate<class NDDOMethod>\nvoid NDDODipoleMatrixCalculator<NDDOMethod>::setIntegralMethod(const IntegralMethod& method) {\n  integralMethod_ = method;\n  valid_ = false;\n}\n\ntemplate<class NDDOMethod>\nvoid NDDODipoleMatrixCalculator<NDDOMethod>::fillDipoleMatrix(const Eigen::RowVector3d& dipoleEvaluationCoordinate) {\n  initialize();\n  valid_ = false;\n  for (int atom_i = 0; atom_i < nAtoms_; ++atom_i) {\n    auto const firstAOIndex_i = aoIndexes_.getFirstOrbitalIndex(atom_i);\n    auto const& parA = elementParameters_.get(elementTypes_[atom_i]);\n    auto const Ri = positions_.row(atom_i);\n\n    for (int atom_j = atom_i; atom_j < nAtoms_; ++atom_j) {\n      auto const firstAOIndex_j = aoIndexes_.getFirstOrbitalIndex(atom_j);\n      auto const& parB = elementParameters_.get(elementTypes_[atom_j]);\n      auto const Rj = positions_.row(atom_j);\n\n      Eigen::RowVector3d Rij = Rj - Ri;\n\n      AtomPairDipole::fillAtomPairDipoleBlock(dipoleMatrix_, firstAOIndex_i, firstAOIndex_j, integralMethod_,\n                                              parA.GTOs(), parB.GTOs(), Ri, Rj, Rij, dipoleEvaluationCoordinate);\n    }\n  }\n  valid_ = true;\n}\n\ntemplate<class NDDOMethod>\nconst Utils::DipoleMatrix& NDDODipoleMatrixCalculator<NDDOMethod>::getAODipoleMatrix() const {\n  return dipoleMatrix_;\n}\n\ntemplate<class NDDOMethod>\nvoid NDDODipoleMatrixCalculator<NDDOMethod>::setAODipoleMatrix(Utils::DipoleMatrix dipoleMatrix) {\n  dipoleMatrix_ = std::move(dipoleMatrix);\n  valid_ = true;\n}\n\ntemplate<class NDDOMethod>\nbool NDDODipoleMatrixCalculator<NDDOMethod>::isValid() const {\n  return valid_;\n}\n\ntemplate<class NDDOMethod>\nNDDODipoleMatrixCalculator<NDDOMethod>::NDDODipoleMatrixCalculator(NDDOMethod& method)\n  : aoIndexes_(method.getAtomsOrbitalsIndexesHolder()),\n    elementTypes_(method.getElementTypes()),\n    positions_(method.getPositions()),\n    elementParameters_(method.getInitializer().getElementParameters()),\n    overlapMatrix_(method.getOverlapMatrix()),\n    molecularOrbitals_(method.getMolecularOrbitals()) {\n  initialize();\n}\n\ntemplate<class NDDOMethod>\nstd::unique_ptr<NDDODipoleMatrixCalculator<NDDOMethod>> NDDODipoleMatrixCalculator<NDDOMethod>::create(NDDOMethod& method) {\n  NDDODipoleMatrixCalculator<NDDOMethod> instance(method);\n  return std::make_unique<NDDODipoleMatrixCalculator<NDDOMethod>>(std::move(instance));\n}\n\ntemplate<class NDDOMethod>\nUtils::DipoleMatrix NDDODipoleMatrixCalculator<NDDOMethod>::getMODipoleMatrix() const {\n  if (molecularOrbitals_.isRestricted())\n    return calculateMODipoleMatrixRestricted();\n  else\n    return calculateMODipoleMatrixUnrestricted();\n}\n\ntemplate<class NDDOMethod>\nvoid NDDODipoleMatrixCalculator<NDDOMethod>::invalidate() {\n  valid_ = false;\n}\n\ntemplate<class NDDOMethod>\nUtils::DipoleMatrix NDDODipoleMatrixCalculator<NDDOMethod>::calculateMODipoleMatrixRestricted() const {\n  Utils::DipoleMatrix moDipoleMatrix;\n  auto& MOMatrix = molecularOrbitals_.restrictedMatrix();\n  moDipoleMatrix.reset(MOMatrix.cols());\n  // Get the MO matrix as D_{MO} = C^T * D_{AO} * C\n  for (int dimension = 0; dimension < 3; ++dimension) {\n    moDipoleMatrix[dimension] = MOMatrix.transpose() * dipoleMatrix_[dimension] * MOMatrix;\n  }\n  return moDipoleMatrix;\n}\n\ntemplate<class NDDOMethod>\nUtils::DipoleMatrix NDDODipoleMatrixCalculator<NDDOMethod>::calculateMODipoleMatrixUnrestricted() const {\n  Utils::DipoleMatrix moDipoleMatrix;\n  auto& alphaMOMatrix = molecularOrbitals_.alphaMatrix();\n  auto& betaMOMatrix = molecularOrbitals_.betaMatrix();\n  moDipoleMatrix.reset(alphaMOMatrix.cols());\n  // Get the MO matrix as D_{MO} = C_\\alpha^T * D_{AO} * C_\\alpha\n  //                             + C_\\beta^T  * D_{AO} * C_\\beta\n  for (int dimension = 0; dimension < 3; ++dimension) {\n    auto alphaContribution = alphaMOMatrix.transpose() * dipoleMatrix_[dimension] * alphaMOMatrix;\n    auto betaContribution = betaMOMatrix.transpose() * dipoleMatrix_[dimension] * betaMOMatrix;\n    moDipoleMatrix[dimension] = alphaContribution + betaContribution;\n  }\n  return moDipoleMatrix;\n}\n\ntemplate class NDDODipoleMatrixCalculator<nddo::PM6Method>;\ntemplate class NDDODipoleMatrixCalculator<nddo::AM1Method>;\ntemplate class NDDODipoleMatrixCalculator<nddo::MNDOMethod>;\n\n} // namespace Sparrow\n} // namespace Scine\n", "meta": {"hexsha": "e4f2ba180420cd8ac789c7b1f04873d9e006296d", "size": 5479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Sparrow/Sparrow/Implementations/Nddo/Utils/DipoleUtils/NDDODipoleMatrixCalculator.cpp", "max_stars_repo_name": "DockBio/sparrow", "max_stars_repo_head_hexsha": "f82cf86584e9edfc6f2c78af4896dc6f2ee8a455", "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/Sparrow/Sparrow/Implementations/Nddo/Utils/DipoleUtils/NDDODipoleMatrixCalculator.cpp", "max_issues_repo_name": "DockBio/sparrow", "max_issues_repo_head_hexsha": "f82cf86584e9edfc6f2c78af4896dc6f2ee8a455", "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/Sparrow/Sparrow/Implementations/Nddo/Utils/DipoleUtils/NDDODipoleMatrixCalculator.cpp", "max_forks_repo_name": "DockBio/sparrow", "max_forks_repo_head_hexsha": "f82cf86584e9edfc6f2c78af4896dc6f2ee8a455", "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.3146853147, "max_line_length": 124, "alphanum_fraction": 0.7660156963, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19135067496686795}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/miller/phase_transfer.h>\n#include <boost/python/def.hpp>\n\nnamespace cctbx { namespace miller { namespace boost_python {\n\n  void wrap_phase_transfer()\n  {\n    using namespace boost::python;\n\n    def(\"phase_transfer\",\n      (af::shared<std::complex<double> >(*)\n        (sgtbx::space_group const&,\n         af::const_ref<index<> > const&,\n         af::const_ref<double> const&,\n         af::const_ref<std::complex<double> > const&,\n         double const&))\n           phase_transfer);\n\n    def(\"phase_transfer\",\n      (af::shared<std::complex<double> >(*)\n        (sgtbx::space_group const&,\n         af::const_ref<index<> > const&,\n         af::const_ref<double> const&,\n         af::const_ref<double> const&,\n         bool))\n           phase_transfer);\n  }\n\n}}} // namespace cctbx::miller::boost_python\n", "meta": {"hexsha": "2894aa51e06a547f78f31aecd2bad3d3eb14028d", "size": 861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/miller/boost_python/phase_transfer.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": "cctbx/miller/boost_python/phase_transfer.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": "cctbx/miller/boost_python/phase_transfer.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": 26.90625, "max_line_length": 61, "alphanum_fraction": 0.6120789779, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.19134845783953025}}
{"text": "#include <booster/BoosterNetworkSimulator.hpp>\n#include <booster/BoosterImpactOptions.hpp>\n\n#include <merlion/Merlion.hpp>\n#include <merlion/BlasWrapper.hpp>\n#include <merlion/TriSolve.hpp>\n#include <merlion/MerlionDefines.hpp>\n#include <merlion/SparseMatrix.hpp>\n\n#include <merlionUtils/TaskTimer.hpp>\n\n#include <set>\n#include <exception>\n#include <algorithm>\n\n\nusing namespace merlionUtils;\n\n//forward declarations\nvoid PerformBoosterSimulations(const BoosterNetworkSimulator& chl_net,\n                               const NetworkSimulator& tox_net,\n\t\t\t       const BoosterImpactOptions& options,\n                               bool pd_impacts=false);\n\nint main(int argc, char** argv)\n{  \n   // Handle the optional inputs to this executable\n   BoosterImpactOptions options;\n   options.ParseInputs(argc, argv);\n\n   // Helpful interface for setting up the booster station simulations\n   BoosterNetworkSimulator chl_net(options.disable_warnings);\n   NetworkSimulator tox_net(true);\n   \n   if (options.logging) {\n      chl_net.StartLogging(options.output_prefix+\"boosterimpact.log\");  \n      tox_net.StartLogging(options.output_prefix+\"boosterimpact.log\");  \n      options.PrintSummary(chl_net.Log());\n   }\n\n   std::cout << \"\\n@@@ PARSING INPUT FILES @@@\" << std::endl;\n   // Read Chlorine network info\n   if ((options.chl_inp_filename != \"\") && (options.chl_wqm_filename != \"\")) {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Both a wqm file and an inp file cannot be specified for the boosters.\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n   if (options.chl_inp_filename != \"\") {\n      // Read an epanet input file\n      merlionUtils::TaskTimer Run_Hydraulics;\n      chl_net.ReadINPFile(options.chl_inp_filename,\n                          options.sim_duration_min,\n                          options.qual_step_min,\n                          options.chl_epanet_output_filename,\n                          options.chl_merlion_save_filename,\n                          -1,\n                          -1,\n                          options.ignore_merlion_warnings,\n                          options.chl_decay_k);\n      Run_Hydraulics.StopAndPrint(std::cout, \"\\n\\t- Built booster Merlion Water Quality Model \");\n   }\n   else if (options.chl_wqm_filename != \"\") {\n      if (options.chl_decay_k != -1.0f) {\n         std::cerr << std::endl;\n         std::cerr << \"ERROR: A booster decay coefficient cannot be specified when using the --booster-wqm option.\" << std::endl;\n         std::cerr << std::endl;\n         return 1;\n      }\n      merlionUtils::TaskTimer Read_WQM;\n      // read a merlion water quality model file\n      chl_net.ReadWQMFile(options.chl_wqm_filename);\n      Read_WQM.StopAndPrint(std::cout, \"\\n\\t- Read booster Merlion Water Quality Model \");\n   }\n   else {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Missing network input file for the boosters.\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n   /////////////////\n\n   // Read Toxin network info\n   if ((options.tox_inp_filename != \"\") && (options.tox_wqm_filename != \"\")) {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Both a wqm file and an inp file cannot be specified for the toxin.\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n   if (options.tox_inp_filename != \"\") {\n      // Read an epanet input file\n      merlionUtils::TaskTimer Run_Hydraulics;\n      tox_net.ReadINPFile(options.tox_inp_filename,\n                          options.sim_duration_min,\n                          options.qual_step_min,\n                          options.tox_epanet_output_filename,\n                          options.tox_merlion_save_filename,\n                          -1,\n                          -1,\n                          options.ignore_merlion_warnings,\n                          options.tox_decay_k);\n      Run_Hydraulics.StopAndPrint(std::cout, \"\\n\\t- Built toxin Merlion Water Quality Model \");\n   }\n   else if (options.tox_wqm_filename != \"\") {\n      if (options.tox_decay_k != -1.0f) {\n         std::cerr << std::endl;\n         std::cerr << \"ERROR: A toxin decay coefficient cannot be specified when using the --tox-wqm option.\" << std::endl;\n         std::cerr << std::endl;\n         return 1;\n      }\n      merlionUtils::TaskTimer Read_WQM;\n      // read a merlion water quality model file\n      tox_net.ReadWQMFile(options.tox_wqm_filename);\n      Read_WQM.StopAndPrint(std::cout, \"\\n\\t- Read toxin Merlion Water Quality Model \");\n   }\n   else {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Missing network input file for the toxin.\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n   ///////////////\n\n\n   // **A weak way of checking the the models match (except for, of course, their decay coefficients)\n   if ((tox_net.Model().N != chl_net.Model().N) ||\n       (tox_net.Model().n_nodes != chl_net.Model().n_nodes) ||\n       (tox_net.Model().n_links != chl_net.Model().n_links) ||\n       (tox_net.Model().n_steps != chl_net.Model().n_steps) ||\n       (tox_net.Model().qual_steps_per_hour != chl_net.Model().qual_steps_per_hour)) {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Toxin and Booster models don't match in network layout or simulation length.\" << std::endl;\n      std::cerr << std::endl;\n      exit(1);\n   }\n\n\n   // Read in the booster station specs\n   if (options.booster_filename != \"\") {\n      merlionUtils::TaskTimer Read_BoosterFile;\n      // read in the file defining he booster station parameters\n      // this function also defines the booster candidates\n      // depending on what is in the booster .spec file. Default is all\n      // NZD junctions\n      chl_net.ReadBoosterFile(options.booster_filename);\n      Read_BoosterFile.StopAndPrint(std::cout, \"\\n\\t- Read water booster spec file \");\n   }\n   else {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Missing booster station specs file.\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n\n   bool detection_times_provided(false);\n   // Read in the Scenarios\n   if (options.tsg_filename != \"\") {\n      merlionUtils::TaskTimer Read_Scen;\n      // Read in the injection scenarios define by the *.tsg file\n      tox_net.ReadTSGFile(options.tsg_filename);\n      Read_Scen.StopAndPrint(std::cout, \"\\n\\t- Read scenario data in .tsg file\");\n   }\n   else if (options.tsi_filename != \"\") {\n      merlionUtils::TaskTimer Read_tsi;\n      // Read in the injection scenarios define by the *.tsi file\n      if (options.isDefault(\"tsi-species-id\")) {\n         tox_net.ReadTSIFile(options.tsi_filename);\n      }\n      else {\n         if (options.tsi_species_id < 0) {\n            std::cerr << std::endl;\n            std::cerr << \"ERROR: A TSI species id must be positive\" << std::endl;\n            std::cerr << std::endl;\n            return 1;\n         }\n         tox_net.ReadTSIFile(options.tsi_filename, false, options.tsi_species_id);\n      }\n      Read_tsi.StopAndPrint(std::cout, \"\\n\\t- Read scenario data in .tsi file\");\n   }\n   else if (options.scn_filename != \"\") {\n      merlionUtils::TaskTimer Read_Scen;\n      // Read in the injection scenarios define by the *.scn file\n      tox_net.ReadSCNFile(options.scn_filename);\n      Read_Scen.StopAndPrint(std::cout, \"\\n\\t- Read scenario data in .scn file\");\n   }\n   else if (options.dscn_filename != \"\") {\n      merlionUtils::TaskTimer Read_Scen;\n      // Read in the injection scenarios define by the *.dscn file\n      tox_net.ReadSCNFile(options.dscn_filename);\n      Read_Scen.StopAndPrint(std::cout, \"\\n\\t- Read scenario data in .dscn file\");\n      detection_times_provided = true;\n   }\n   else {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Missing scenario file.\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n   int scen_file_cnt = (options.tsg_filename != \"\")?(1):(0);\n   scen_file_cnt += (options.tsi_filename != \"\")?(1):(0);\n   scen_file_cnt += (options.scn_filename != \"\")?(1):(0);\n   scen_file_cnt += (options.dscn_filename != \"\")?(1):(0);\n   if (scen_file_cnt > 1) {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Too many scenario options specified. Choose one: TSG, TSI, SCN, DSCN\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n\n   // Read in the sensor node list or inverse\n   if (options.wqm_inverse_filename != \"\") {\n      merlionUtils::TaskTimer Read_Inverse;\n      tox_net.ReadInverse(options.wqm_inverse_filename);\n      Read_Inverse.StopAndPrint(std::cout, \"\\n\\t- Read Merlion Inverse File \");\n   }\n   else if (options.sensor_filename != \"\") {\n      merlionUtils::TaskTimer Read_Sensors;\n      // Read the file defining the set of sensors\n      tox_net.ReadSensorFile(options.sensor_filename);\n      Read_Sensors.StopAndPrint(std::cout,\"\\n\\t- Read sensor file \");\n   }\n   else if (!detection_times_provided) {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Missing sensor or inverse file which is required when detection times are not provided.\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n   if ((options.sensor_filename != \"\") && (options.wqm_inverse_filename != \"\")) {\n      std::cerr << std::endl;\n      std::cerr << \"ERROR: Both a sensor file and an inverse file cannot be specified.\" << std::endl;\n      std::cerr << std::endl;\n      return 1;\n   }\n\n   std::cout << \"\\n@@@ DETERMINING SCENARIO DETECT TIMES @@@\" << std::endl;\n   if ((options.wqm_inverse_filename == \"\") && (!detection_times_provided)) {\n      merlionUtils::TaskTimer Build_Inverse;\n      \n      // Build reduced inverse so sensor node detections can be rapidly\n      // determined for each injection\n      int min_inj_timestep = tox_net.Model().n_steps;\n      for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, tox_net.InjectionScenarios()) {\n         int scen_start = (*p_scen)->EarliestInjectionTimestep(tox_net.Model());\n         if (scen_start < min_inj_timestep) {\n            min_inj_timestep = scen_start;\n         }\n      }\n      \n      // Build a list of node/time tuple where rows of the inverse are needed.\n      if (tox_net.SensorNodeIDS().empty() && tox_net.GrabSampleIDS().empty()) {\n         std::cerr << std::endl;\n         std::cerr << \"ERROR: A non-empty list of sensor nodes or grab samples is required when \"\n\t           << \"using a tsg or scn file.\" << std::endl;\n         std::cerr << std::endl;\n         return 1;\n      }\n      \n      tox_net.GenerateReducedInverse(min_inj_timestep,tox_net.Model().n_steps-1,0,1,true);\n      Build_Inverse.StopAndPrint(std::cout, \"\\n\\t- Inverse Built \");\n   }\n   \n   merlionUtils::TaskTimer Classify;\n   // Apply the sensor layout and generate the new scenario data\n   // based on detection times\n   bool scenario_aggregation = true;\n   tox_net.ClassifyScenarios(detection_times_provided,\n                             tox_net.Model().n_steps-1,\n                             options.detection_tol_gpm3,\n                             options.detection_interval_min);\n   chl_net.CopyScenarioList(tox_net);\n   chl_net.ClassifyBoosterScenarios(true,\n                                    scenario_aggregation, \n                                    options.detection_tol_gpm3,\n                                    options.detection_interval_min);\n   Classify.StopAndPrint(std::cout, \"\\n\\t- Classified Scenarios \");\n\n   bool pd_impacts = false;\n   if (options.demand_percapita_m3pmin ||\n       options.ingestion_rate_m3pmin) {\n      pd_impacts = true;\n      merlionUtils::TaskTimer GeneratePopUsageData;\n      tox_net.GeneratePopulationUsageData(options.demand_percapita_m3pmin,\n                                          options.ingestion_rate_m3pmin);\n      GeneratePopUsageData.StopAndPrint(std::cout, \"\\n\\t- Generated Population Usage Data\");\n   }\n\n   // Free the memory for the reduced system inverse\n   tox_net.ResetInverse();\n   // Free the memory for the list of sensors\n   tox_net.ResetSensorData();\n\n   double booster_seconds = 0.0;\n   std::cout << \"\\n@@@ SIMULATING BOOSTER STATIONS @@@\" << std::endl;\n   merlionUtils::TaskTimer SimAndSave;\n   PerformBoosterSimulations(chl_net,tox_net,options,pd_impacts); \n   SimAndSave.StopAndSave(booster_seconds);\n\n   double sims_per_second = (chl_net.BoosterCandidates().size()*chl_net.BoosterScenarios().size() + chl_net.DetectedScenarios().size())/booster_seconds;\n   std::cout << \"\\n\\t- Finished Booster Station Simulations (time in seconds): \" << booster_seconds << std::endl;\n   std::cout << \"\\n\\t- Approximate Simulations Per Second: \" << sims_per_second << std::endl;\n\n   chl_net.StopLogging();\n   tox_net.StopLogging();\n\n   // Free all other memory being used\n   chl_net.clear();\n   tox_net.clear();\n\n   return 0;\n}\n\n\n//forward declarations\nvoid PerformBoosterSimulations(const BoosterNetworkSimulator& chl_net,\n                               const NetworkSimulator& tox_net,\n\t\t\t       const BoosterImpactOptions& options,\n                               bool pd_impacts/*=false*/)\n{\n   // Create a timer but don't start it\n   TaskTimer timer(false);\n\n   const BoosterNetworkSimulator& net = chl_net;\n   const MerlionModelContainer& model = chl_net.Model();\n   const MerlionModelContainer& tox_model = tox_net.Model();\n\n   const float zero_conc_gpm3 = std::max(options.zero_conc_tol_gpm3,ZERO_CONC_GPM3);\n\n   int num_booster_stations = net.BoosterCandidates().size();\n   std::cout << \"\\nNetwork Stats:\\n\";\n   std::cout << \"\\tNumber of Booster Station Candidates - \" << num_booster_stations << \"\\n\";\n   std::cout << \"\\tNumber of Junctions                  - \" << model.junctions.size() << \"\\n\";\n   std::cout << \"\\tNumber of Nonzero Demand Junctions   - \" << model.nzd_junctions.size() << \"\\n\";\n   std::cout << \"\\tNumber of Tanks                      - \" << model.tanks.size() << \"\\n\";\n   std::cout << \"\\tNumber of Reservoirs                 - \" << model.reservoirs.size() << \"\\n\";\n   std::cout << \"\\tWater Quality Timestep (minutes)     - \" << model.qual_step_minutes << \"\\n\";\n   std::cout << std::endl;\n   \n   // A shortcut for specifying all possible \n   // right hand sides in one call of the multiple\n   // right hand side triangular solver\n   int nrhs = options.max_rhs;\n   if (nrhs <= 0) {\n      nrhs = num_booster_stations; \n   } \n\n   // Allocate the right hand side and solution vector for toxin injection sims\n   float* tox_mass_inj_gpmin = new float[model.N];\n   BlasInitZero(model.N, tox_mass_inj_gpmin);\n\n   std::set<int> positive_demand_u_ids;\n   for (int u_idx = 0; u_idx < model.N; ++u_idx) {\n      if (model.demand_ut_m3[u_idx] > 0.0f) {\n         positive_demand_u_ids.insert(u_idx);\n      }\n   }\n\n   std::vector<double> volume_ingested_ut_m3;\n   std::vector<double> node_total_dose_g;\n   std::vector<double> node_total_pre_dose_g;\n   if (pd_impacts) {\n      volume_ingested_ut_m3.clear();\n      volume_ingested_ut_m3.resize(model.N,0.0);\n      node_total_dose_g.clear();\n      node_total_dose_g.resize(model.n_nodes, 0.0);\n      node_total_pre_dose_g.clear();\n      node_total_pre_dose_g.resize(model.n_nodes, 0.0);\n      for (int nt_idx = 0; nt_idx < model.N; ++nt_idx) {\n         if (tox_net.VolumeIngested_m3()[nt_idx] > 0.0) {\n            volume_ingested_ut_m3[model.perm_nt_to_upper[nt_idx]] = tox_net.VolumeIngested_m3()[nt_idx];\n         }\n      }\n   }\n   \n   // Allocate memory for the rhs and solution vector for the booster sims\n   // depending on the number right hand sides specified in options\n   float* chl_mass_inj_gpmin(NULL);\n   if (nrhs > 1) {\n      int TMP_RHS = (nrhs<num_booster_stations)?nrhs:num_booster_stations;\n      chl_mass_inj_gpmin = new float[model.N * TMP_RHS];\n      BlasInitZero(model.N*TMP_RHS, chl_mass_inj_gpmin);\n   }\n   else {\n      chl_mass_inj_gpmin = new float[model.N];\n      BlasInitZero(model.N, chl_mass_inj_gpmin);\n   }\n\n   timer.Start();\n   for STL_CONST_ITERATE(BoosterScenList, p_boost, p_boost_stop, net.BoosterScenarios()) {\n      timer.Start();\n      const BoosterScenario& booster_scen = **p_boost;\n      \n      const int sim_stop_timestep = booster_scen.sim_stop_timestep;\n      const int min_row = model.N-model.n_nodes*(sim_stop_timestep+1);\n\n      // the set of node,time ids in upper trianglular orientation where \n      // chlorine is present (0 indicates no chlorine)\n      std::vector<int> disinf_u_ids(model.N,0);\n      \n      if (nrhs > 1 && !net.BoosterCandidates().empty()) {\n         // Code optimized for solving booster station sims using set of matrix rhs\n         // FASTED METHOD WHERE MEMORY IS LEVERAGED WITH SPEED\n         //////////////////////////////////////////////\n         if (nrhs > num_booster_stations) {\n            nrhs = num_booster_stations;\n         }\n         const int total_blocks = (num_booster_stations/nrhs) + (((num_booster_stations%nrhs)>0)?1:0);\n\t const int odd_count = num_booster_stations%nrhs;\n\t int current_block(0);\n\n\n\t std::vector<int>::const_iterator p_bid = chl_net.BoosterCandidates().begin();\n\t std::vector<int>::const_iterator p_bid_stop = chl_net.BoosterCandidates().end();\n         std::vector<int>::const_iterator p_bid_block_start;\n\t Injection booster_injection = *(booster_scen.Injections().front());\n\n         std::vector<int> block_booster_ids;\n         while (current_block < total_blocks) {\n            block_booster_ids.resize(nrhs);\n            p_bid_block_start = p_bid;\n\t    // set the rhs matrix\n\t    int max_row_chl = 0;\n\t    for (int r = 0; (r < nrhs) && (p_bid != p_bid_stop); ++r, ++p_bid) {\n\t       float mass_injected_g(0.0);\n\t       int max_row_index(model.N-1);\n\t       booster_injection.NodeName() = model.NodeName(*p_bid);\n\t       booster_injection.SetMultiArray(model,nrhs,r,chl_mass_inj_gpmin,mass_injected_g,max_row_index);\n\t       block_booster_ids[r] = *p_bid;\n\t       if (max_row_index > max_row_chl) {\n\t\t  max_row_chl = max_row_index;\n\t       }\n            }\n\n            // do the backsolve\n            usolvem( model.N, \n\t\t     min_row,\n\t\t     max_row_chl,\n\t\t     nrhs,\n\t\t     model.G->Values(),\n\t\t     model.G->iRows(),\n\t\t     model.G->pCols(),\n\t\t     chl_mass_inj_gpmin );\n\t    \n            // Create a reference variable to make units more obvious. The linear solver\n            // converts the rhs vector (units gpmin) into the solution vector (gpm3). We will\n            // use this reference when it make sense for units (e.g below the linear solve).\n            float*& chl_conc_gpm3 = chl_mass_inj_gpmin;\n\t    \n            // analyze the solution\n\t    // keep track of the nodes/times where chlorine is present\n            for (int i = min_row*nrhs, i_stop = (max_row_chl+1)*nrhs - 1; i <= i_stop; ++i) {\n\t       if (chl_conc_gpm3[i] > zero_conc_gpm3) {\n\t\t  disinf_u_ids[i/nrhs] += 1;\n\t       }\n            }\n\n\t    // reset the sparse set of locations where the injections modifed the array,\n\t    // these may have been outside the region of interest in the linear solver,\n\t    // in which case, the BlasResetZero code after this loop would not have\n\t    // zero that region of the array\n\t    p_bid = p_bid_block_start;\n\t    for (int r = 0; (r < nrhs) && (p_bid != p_bid_stop); ++r, ++p_bid) {\n\t       booster_injection.NodeName() = model.NodeName(*p_bid);\n\t       booster_injection.ClearMultiArray(model, nrhs, r, chl_conc_gpm3);\n\t    }\n            // reset to zero only the values where chl_conc_gpm3\n            // was possibly modified by linear solver, this saves time\n            const int num_elements = nrhs*(max_row_chl-min_row+1);\n            const int p_offset = min_row*nrhs;\n            BlasResetZero(num_elements, chl_conc_gpm3+p_offset);\n\t    \n\t    ++current_block;\n\t    // for the last multiple-rhs block, reduce the leading dimension\n\t    // of the rhs/sol matrix to match the number of rhs left over.\n\t    // The extra memory that was allocated will just be left unused\n\t    if (current_block == total_blocks-1) {\n\t       nrhs = (odd_count)?(odd_count):(nrhs);\n\t    }\n         }\n      }\n      else if (!net.BoosterCandidates().empty()) {\n         // Code optimized for solving booster station sims using all single rhs solves\n         // SLOWEST METHOD BUT IN SOME CASES MAY BE OPTIMIZED FOR DATA ACCESS\n         //////////////////////////////////////////////\n         Injection booster_injection = *(booster_scen.Injections().front());\n         for STL_CONST_ITERATE(std::vector<int>, p_bid, p_bid_end, chl_net.BoosterCandidates()) {\n\n            int bnode_id = *p_bid;\n            booster_injection.NodeName() = model.NodeName(bnode_id);\n\t    float mass_injected_g(0.0);\n\t    int max_row_chl(model.N-1);\n            booster_injection.SetArray(model,chl_mass_inj_gpmin,mass_injected_g,max_row_chl);\n\n            // do the backsolve\n            usolve ( model.N,\n\t\t     min_row, \n\t\t     max_row_chl, \n\t\t     model.G->Values(), \n\t\t     model.G->iRows(), \n\t\t     model.G->pCols(), \n\t\t     chl_mass_inj_gpmin );\n         \n            // Create a reference variable to make units make more obvious. The linear solver\n            // converts the rhs vector (units gpmin) into the solution vector (gpm3). We will\n            // use this reference when it make sense for units (e.g below the linear solve).\n            float*& chl_conc_gpm3 = chl_mass_inj_gpmin;\n         \n            // analyze the solution\n            for (int u_idx = min_row; u_idx <= max_row_chl; ++u_idx) {\n               if (chl_conc_gpm3[u_idx] > zero_conc_gpm3) {\n                  disinf_u_ids[u_idx] += 1;\n               }\n            }\n            \n\t    // reset the sparse set of locations where the injections modifed the array,\n\t    // these may have been outside the region of interest in the linear solver,\n\t    // in which case, the BlasResetZero code after this loop would not have\n\t    // zero that region of the array\n            booster_injection.ClearArray(model, chl_conc_gpm3);\n\t    // reset to zero only the values where chl_conc_gpm3\n            // was possibly modified by linear solver, this saves time\n            const int num_elements = max_row_chl-min_row+1;\n            const int p_offset = min_row;\n            BlasResetZero(num_elements, chl_conc_gpm3+p_offset);\n         }\n      }\n      \n      timer.Stop();\n      if (options.report_scenario_timing) {\n         std::cout << \"\\tBOOSTER SCENARIO ID:    \" << (*p_boost)->Name() << std::endl;\n         std::cout << \"\\t- Booster Simulations:  \" << timer.LastLap() << std::endl;\n      }\n      timer.Start();\n   \n      // this is the maximum row after which chlorine injections have not begun\n      const int chl_start_timestep = booster_scen.Injections().front()->StartTimestep(model);\n      const int max_row_chl = (model.N-1)-model.n_nodes*chl_start_timestep;\n      const InjScenList& toxin_scen_list = booster_scen.ToxinScenarios();\n      for STL_CONST_ITERATE(InjScenList, ptox_scen_pos, ptox_scen_pos_stop, toxin_scen_list) {\n         const PInjScenario ptox_scen = *ptox_scen_pos;\n         // set the rhs for the toxin injection\n         float scenario_mass_injected_g(0.0);\n         int max_row_tox(model.N-1);\n         ptox_scen->SetArray(model, tox_mass_inj_gpmin, scenario_mass_injected_g, max_row_tox);\n         ptox_scen->AddImpact(scenario_mass_injected_g, \"Response-Window Mass Injected Grams\");\n\n         // Solver the linear system\n         usolve ( model.N,\n\t\t  min_row,\n\t\t  max_row_tox,\n\t\t  tox_model.G->Values(),\n\t\t  tox_model.G->iRows(),\n\t\t  tox_model.G->pCols(),\n\t\t  tox_mass_inj_gpmin );\n      \n         // Create a reference variable to make units make more obvious. The linear solver\n         // converts the rhs vector (units gpmin) into the solution vector (gpm3). We will\n         // use this reference when it make sense for units (e.g below the linear solve).\n         float*& tox_conc_gpm3 = tox_mass_inj_gpmin;\n\n         const int u_idx_start = model.N-model.n_nodes*(sim_stop_timestep+1);\n         std::set<int>::const_iterator p_dem_u_idx = positive_demand_u_ids.begin();\n         while(*p_dem_u_idx < u_idx_start) {++p_dem_u_idx;}\n         std::set<int>::const_iterator p_dem_u_idx_stop = --(positive_demand_u_ids.end());\n         while(*p_dem_u_idx_stop > max_row_tox) {--p_dem_u_idx_stop;}\n         ++p_dem_u_idx_stop;\n         // determine full scenario impact\n         float scenario_mass_consumed_g(0.0);\n         // Check the mass balance\n         float mass_check(0.0);\n         if (!pd_impacts) {\n            for (; p_dem_u_idx != p_dem_u_idx_stop; ++p_dem_u_idx) {\n               int u_idx = *p_dem_u_idx;\n               if (tox_conc_gpm3[u_idx] > zero_conc_gpm3) {\n                  mass_check += tox_conc_gpm3[u_idx]*model.demand_ut_m3[u_idx];\n                  if (!disinf_u_ids[u_idx]) {\n                     // mc\n                     scenario_mass_consumed_g += tox_conc_gpm3[u_idx]*model.demand_ut_m3[u_idx];\n                  }\n               }\n            }\n         }\n         else { // Includes the code above, just minimizes checking if pd_impacts\n            for (; p_dem_u_idx != p_dem_u_idx_stop; ++p_dem_u_idx) {\n               int u_idx = *p_dem_u_idx;\n               if (tox_conc_gpm3[u_idx] > zero_conc_gpm3) {\n                  mass_check += tox_conc_gpm3[u_idx]*model.demand_ut_m3[u_idx];\n                  if (!disinf_u_ids[u_idx]) {\n                     // mc\n                     scenario_mass_consumed_g += tox_conc_gpm3[u_idx]*model.demand_ut_m3[u_idx];\n                     // pd\n                     int n = model.perm_upper_to_nt[u_idx] / model.n_steps;\n                     node_total_dose_g[n] += tox_conc_gpm3[u_idx] * volume_ingested_ut_m3[u_idx];\n                  }\n               }\n            }\n         }\n\n         // determine impact before booster stations activate\n         p_dem_u_idx = p_dem_u_idx_stop;\n         --p_dem_u_idx;\n         while(*p_dem_u_idx >= (max_row_chl+1)) {--p_dem_u_idx;}\n         ++p_dem_u_idx;\n         float scenario_pre_booster_mass_consumed_g(0.0);\n         if (!pd_impacts) {\n            for (; p_dem_u_idx != p_dem_u_idx_stop; ++p_dem_u_idx) {\n               int u_idx = *p_dem_u_idx;\n               if (tox_conc_gpm3[u_idx] > zero_conc_gpm3) {\n                  scenario_pre_booster_mass_consumed_g += tox_conc_gpm3[u_idx]*model.demand_ut_m3[u_idx];\n               }\n            }\n         }\n         else { // Includes the code above, just minimizes checking if pd_impacts\n            for (; p_dem_u_idx != p_dem_u_idx_stop; ++p_dem_u_idx) {\n               int u_idx = *p_dem_u_idx;\n               if (tox_conc_gpm3[u_idx] > zero_conc_gpm3) {\n                  // pre mc\n                  scenario_pre_booster_mass_consumed_g += tox_conc_gpm3[u_idx]*model.demand_ut_m3[u_idx];\n                  // pre pd\n                  int n = model.perm_upper_to_nt[u_idx] / model.n_steps;\n                  node_total_pre_dose_g[n] += tox_conc_gpm3[u_idx] * volume_ingested_ut_m3[u_idx];\n               }\n            }\n         }\n\n         // Include mass remaining in tanks in mass balance check\n         float tank_mass(0.0);\n         for (std::vector<std::pair<int,int> >::const_iterator pos = model.tanks.begin(), stop = model.tanks.end(); pos != stop; ++pos) {\n            int n = pos->first;\n            int tank_n = pos->second;\n            int t = sim_stop_timestep;\n            int nt_tank_idx = tank_n*model.n_steps + t;\n            int nt_idx = n*model.n_steps + t;\n            int u_idx = model.perm_nt_to_upper[nt_idx];\n            if (((tox_conc_gpm3[u_idx] > zero_conc_gpm3) && (!disinf_u_ids[u_idx]))) {\n               tank_mass += tox_conc_gpm3[u_idx]*model.tank_volume_m3[nt_tank_idx];\n            }\n            mass_check += tox_conc_gpm3[u_idx]*model.tank_volume_m3[nt_tank_idx];\n         }\n         ptox_scen->AddImpact(scenario_mass_consumed_g, \"Mass Consumed Grams\");\n         ptox_scen->AddImpact(scenario_pre_booster_mass_consumed_g, \"Pre-Booster Mass Consumed Grams\");\n         ptox_scen->AddImpact(tank_mass, \"Final Mass In Tanks Grams\");\n         ptox_scen->AddImpact(mass_check/scenario_mass_injected_g*100.0f, \"Simulation Mass Balance\");\n\n         if (pd_impacts) {\n            double population_dosed = 0.0;\n            for (int n = 0; n < model.n_nodes; ++n) {\n               if (node_total_dose_g[n] > options.population_dosed_threshold_g) {\n                  population_dosed += tox_net.NodePopulation()[n];\n               }\n            }\n            ptox_scen->AddImpact(population_dosed, \"Population Dosed\");\n            double pre_population_dosed = 0.0;\n            for (int n = 0; n < model.n_nodes; ++n) {\n               if (node_total_pre_dose_g[n] > options.population_dosed_threshold_g) {\n                  pre_population_dosed += tox_net.NodePopulation()[n];\n               }\n            }\n            ptox_scen->AddImpact(pre_population_dosed, \"Pre-Population Dosed\");\n            // reset the node dose vectors\n            BlasResetZero(model.n_nodes, &(node_total_dose_g[0]));\n            BlasResetZero(model.n_nodes, &(node_total_pre_dose_g[0]));\n         }\n\n\t // reset the sparse set of locations where the injections modifed the array,\n\t // these may have been outside the region of interest in the linear solver,\n\t // in which case, the BlasResetZero code after this loop would not have\n\t // zero that region of the array\n\t ptox_scen->ClearArray(model, tox_mass_inj_gpmin);\n         // reset the rhs for the toxin backsolves\n         const int num_elements = max_row_tox-min_row+1;\n         const int p_offset = min_row;\n         BlasResetZero(num_elements, tox_conc_gpm3+p_offset);\n      }\n      timer.Stop();\n      if (options.report_scenario_timing) {\n         std::cout << \"\\t- Toxin Simulations:  \" << timer.LastLap() << std::endl;\n         std::cout << std::endl;\n      }\n   }\n\n   timer.Start();\n   for STL_CONST_ITERATE(InjScenList, ptox_scen_pos, ptox_scen_pos_stop, chl_net.NonDetectedScenarios()) {\n      const PInjScenario ptox_scen = *ptox_scen_pos;\n\n      // We simulate until the end of the time horizon\n      const int sim_stop_timestep = model.n_steps-1;\n      const int min_row = 0;\n\n      // Set the mass injected label for the non-detected scenarios\n      ptox_scen->AddImpact(ptox_scen->MassInjected(chl_net.Model()),\"Mass Injected Grams\");\n         \n      // set the rhs for the toxin injection\n      float scenario_mass_injected_g(0.0);\n      int max_row_tox(model.N-1);\n      ptox_scen->SetArray(model, tox_mass_inj_gpmin, scenario_mass_injected_g, max_row_tox);\n\n      // Solver the linear system\n      usolve (model.N,\n              min_row,\n              max_row_tox,\n              tox_model.G->Values(),\n              tox_model.G->iRows(),\n              tox_model.G->pCols(),\n              tox_mass_inj_gpmin );\n      \n      // Create a reference variable to make units make more obvious. The linear solver\n      // converts the rhs vector (units gpmin) into the solution vector (gpm3). We will\n      // use this reference when it make sense for units (e.g below the linear solve).\n      float*& tox_conc_gpm3 = tox_mass_inj_gpmin;\n\n      std::set<int>::const_iterator p_dem_u_idx = positive_demand_u_ids.begin();\n      while(*p_dem_u_idx < min_row) {++p_dem_u_idx;}\n      std::set<int>::const_iterator p_dem_u_idx_stop = --(positive_demand_u_ids.end());\n      while(*p_dem_u_idx_stop > max_row_tox) {--p_dem_u_idx_stop;}\n      ++p_dem_u_idx_stop;\n      // determine full scenario impact\n      float scenario_mass_consumed_g(0.0);\n      // Check the mass balance\n      float mass_check(0.0);\n      for (; p_dem_u_idx != p_dem_u_idx_stop; ++p_dem_u_idx) {\n         int u_idx = *p_dem_u_idx;\n         if (tox_conc_gpm3[u_idx] > zero_conc_gpm3) {\n            mass_check += tox_conc_gpm3[u_idx]*model.demand_ut_m3[u_idx];\n            // mc\n            scenario_mass_consumed_g += tox_conc_gpm3[u_idx]*model.demand_ut_m3[u_idx];\n            // pd\n            if (pd_impacts) {\n               int n = model.perm_upper_to_nt[u_idx] / model.n_steps;\n               node_total_dose_g[n] += tox_conc_gpm3[u_idx] * volume_ingested_ut_m3[u_idx];\n            }\n         }\n      }\n\n      // Include mass remaining in tanks in mass balance check\n      float tank_mass(0.0);\n      for (std::vector<std::pair<int,int> >::const_iterator pos = model.tanks.begin(), stop = model.tanks.end(); pos != stop; ++pos) {\n         int n = pos->first;\n         int tank_n = pos->second;\n         int t = sim_stop_timestep;\n         int nt_tank_idx = tank_n*model.n_steps + t;\n         int nt_idx = n*model.n_steps + t;\n         int u_idx = model.perm_nt_to_upper[nt_idx];\n         if (tox_conc_gpm3[u_idx] > zero_conc_gpm3) {\n            tank_mass += tox_conc_gpm3[u_idx]*model.tank_volume_m3[nt_tank_idx];\n         }\n         mass_check += tox_conc_gpm3[u_idx]*model.tank_volume_m3[nt_tank_idx];\n      }\n      ptox_scen->AddImpact(scenario_mass_consumed_g, \"Mass Consumed Grams\");\n      ptox_scen->AddImpact(tank_mass, \"Final Mass In Tanks Grams\");\n      ptox_scen->AddImpact(mass_check/scenario_mass_injected_g*100.0f, \"Simulation Mass Balance\");\n\n      if (pd_impacts) {\n         double population_dosed = 0.0;\n         for (int n = 0; n < model.n_nodes; ++n) {\n            if (node_total_dose_g[n] > options.population_dosed_threshold_g) {\n               population_dosed += tox_net.NodePopulation()[n];\n            }\n         }\n         ptox_scen->AddImpact(population_dosed, \"Population Dosed\");\n      }\n\n      // reset the node dose vector\n      BlasResetZero(model.n_nodes, &(node_total_dose_g[0]));\n\n      // reset the sparse set of locations where the injections modifed the array,\n      // these may have been outside the region of interest in the linear solver,\n      // in which case, the BlasResetZero code after this loop would not have\n      // zero that region of the array\n      ptox_scen->ClearArray(model, tox_mass_inj_gpmin);\n      // reset the rhs for the toxin backsolves\n      const int num_elements = max_row_tox-min_row+1;\n      const int p_offset = min_row;\n      BlasResetZero(num_elements, tox_conc_gpm3+p_offset);\n   }\n   timer.Stop();\n   if (options.report_scenario_timing) {\n      std::cout << \"\\t- Non-Detected Toxin Simulations:  \" << timer.LastLap() << std::endl;\n      std::cout << std::endl;\n   }\n\n   //print scenario impact\n   std::ofstream out;\n   out.precision(12);\n   out.setf(std::ios::scientific,std::ios::floatfield);\n   if (options.yaml) {\n      std::string fname = options.output_prefix+\"DetectedScenarioImpacts.yml\";\n      out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n      merlionUtils::PrintScenarioListYAML(net.DetectedScenarios(), out);\n      out.close();\n      fname = options.output_prefix+\"NonDetectedScenarioImpacts.yml\";\n      out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n      merlionUtils::PrintScenarioListYAML(net.NonDetectedScenarios(), out);\n      out.close();\n      fname = options.output_prefix+\"DiscardedScenarioImpacts.yml\";\n      out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n      merlionUtils::PrintScenarioListYAML(net.DiscardedScenarios(), out);\n      out.close();\n   }\n   if (options.json) {\n      std::string fname = options.output_prefix+\"DetectedScenarioImpacts.json\";\n      out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n      merlionUtils::PrintScenarioListJSON(net.DetectedScenarios(), out);\n      out.close();\n      fname = options.output_prefix+\"NonDetectedScenarioImpacts.json\";\n      out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n      merlionUtils::PrintScenarioListJSON(net.NonDetectedScenarios(), out);\n      out.close();\n      fname = options.output_prefix+\"DiscardedScenarioImpacts.json\";\n      out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n      merlionUtils::PrintScenarioListJSON(net.DiscardedScenarios(), out);\n      out.close();\n   }\n   if (!options.yaml && !options.json) {\n\n      std::string fname = options.output_prefix+\"ScenarioImpacts.txt\";\n      out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n      out << \"Detected \" << net.DetectedScenarios().size() << \"\\n\";\n      out << \"label   weight   normalized-weight   orig-mass-injected   window-mass-injected   mass-in-tanks   percent-balance\\n\";\n      for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.DetectedScenarios()) {\n         out << (*p_scen)->Name() << \" \"\n             << (*p_scen)->Impact(\"Weight\") << \" \"\n             << (*p_scen)->Impact(\"Normalized Weight\") << \" \"\n             << (*p_scen)->Impact(\"Original Mass Injected Grams\") << \" \"\n             << (*p_scen)->Impact(\"Response-Window Mass Injected Grams\") << \" \"\n             << (*p_scen)->Impact(\"Final Mass In Tanks Grams\") << \" \"\n             << (*p_scen)->Impact(\"Simulation Mass Balance\") << \"\\n\";\n      }\n      out << \"\\n\";\n      out << \"UnDetected \" << net.NonDetectedScenarios().size() << std::endl;\n      out << \"label   weight   normalized-weight   mass-injected   mass-in-tanks   percent-balance\\n\";\n      for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.NonDetectedScenarios()) {\n         out << (*p_scen)->Name() << \" \"\n             << (*p_scen)->Impact(\"Weight\") << \" \"\n             << (*p_scen)->Impact(\"Normalized Weight\") << \" \"\n             << (*p_scen)->Impact(\"Mass Injected Grams\") << \" \"\n             << (*p_scen)->Impact(\"Final Mass In Tanks Grams\") << \" \"\n             << (*p_scen)->Impact(\"Simulation Mass Balance\") << \"\\n\";\n      }\n      out << \"\\n\";\n      out << \"Discarded \" << net.DiscardedScenarios().size() << std::endl;\n      out << \"label   weight   normalized-weight   percent-balance\\n\";\n      for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.DiscardedScenarios()) {\n         out << (*p_scen)->Name() << \" \"\n             << (*p_scen)->Impact(\"Weight\") << \" \"\n             << (*p_scen)->Impact(\"Normalized Weight\") << \" \"\n             << 0.0 << \"\\n\";\n      }\n      out.close();\n\n\n      fname = options.output_prefix+\"ScenarioImpacts_MC.txt\";\n      out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n      out << \"Detected \" << net.DetectedScenarios().size() << std::endl;\n      out << \"label   mass-consumed  pre-booster-mass-consumed\\n\";\n      for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.DetectedScenarios()) {\n         out << (*p_scen)->Name() << \" \"\n             << (*p_scen)->Impact(\"Mass Consumed Grams\") << \" \"\n             << (*p_scen)->Impact(\"Pre-Booster Mass Consumed Grams\") << \"\\n\";\n      }\n      out << \"\\n\";\n      out << \"UnDetected \" << net.NonDetectedScenarios().size() << std::endl;\n      out << \"label   mass-consumed\\n\";\n      for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.NonDetectedScenarios()) {\n         out << (*p_scen)->Name() << \" \"\n             << (*p_scen)->Impact(\"Mass Consumed Grams\") << \"\\n\";\n      }\n      out << \"\\n\";\n      out << \"Discarded \" << net.DiscardedScenarios().size() << std::endl;\n      out << \"label\\n\";\n      for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.DiscardedScenarios()) {\n         out << (*p_scen)->Name() << \"\\n\";\n      }\n      out.close();\n\n      if (pd_impacts) {\n         fname = options.output_prefix+\"ScenarioImpacts_PD.txt\";\n         out.open(fname.c_str(), std::ios_base::out | std::ios_base::trunc);\n         out << \"Detected \" << net.DetectedScenarios().size() << std::endl;\n         out << \"label   population-dosed  pre-booster-population-dosed\\n\";\n         for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.DetectedScenarios()) {\n            out << (*p_scen)->Name() << \" \"\n                << (*p_scen)->Impact(\"Population Dosed\") << \" \"\n                << (*p_scen)->Impact(\"Pre-Population Dosed\") << \"\\n\";\n         }\n         out << \"\\n\";\n         out << \"UnDetected \" << net.NonDetectedScenarios().size() << std::endl;\n         out << \"label   population-dosed\\n\";\n         for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.NonDetectedScenarios()) {\n            out << (*p_scen)->Name() << \" \"\n                << (*p_scen)->Impact(\"Population Dosed\") << \"\\n\";\n         }\n         out << \"\\n\";\n         out << \"Discarded \" << net.DiscardedScenarios().size() << std::endl;\n         out << \"label\\n\";\n         for STL_CONST_ITERATE(InjScenList, p_scen, p_stop, net.DiscardedScenarios()) {\n            out << (*p_scen)->Name() << \"\\n\";\n         }\n      }\n   }\n}\n", "meta": {"hexsha": "a0d735bb82d3ea6b2a788acddba197c4396ef4bf", "size": 40007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/sim/merlion/applications/booster/src/booster/BoosterImpact.cpp", "max_stars_repo_name": "USEPA/Water-Security-Toolkit", "max_stars_repo_head_hexsha": "6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-10T18:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-05T18:11:40.000Z", "max_issues_repo_path": "packages/sim/merlion/applications/booster/src/booster/BoosterImpact.cpp", "max_issues_repo_name": "USEPA/Water-Security-Toolkit", "max_issues_repo_head_hexsha": "6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb", "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/sim/merlion/applications/booster/src/booster/BoosterImpact.cpp", "max_forks_repo_name": "USEPA/Water-Security-Toolkit", "max_forks_repo_head_hexsha": "6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-24T19:04:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T18:11:43.000Z", "avg_line_length": 44.4028856826, "max_line_length": 152, "alphanum_fraction": 0.6152423326, "num_tokens": 10378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716967, "lm_q1q2_score": 0.1913184666097089}}
{"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_X86_SSE2_SIMD_FUNCTION_INTERLEAVE_EVEN_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_INTERLEAVE_EVEN_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd =  boost::dispatch;\n  namespace bs =  boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( interleave_even_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::double_<A0>, bs::sse_>\n                          , bs::pack_<bd::double_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator()(const A0 & a0, const A0 & a1) const BOOST_NOEXCEPT\n    {\n      return _mm_unpacklo_pd(a0,a1);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( interleave_even_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::ints32_<A0>, bs::sse_>\n                          , bs::pack_<bd::ints32_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator()(const A0 & a0, const A0 & a1) const BOOST_NOEXCEPT\n    {\n      return _mm_unpacklo_epi32 ( _mm_castps_si128(_mm_shuffle_ps ( _mm_castsi128_ps(a0)\n                                                                  , _mm_castsi128_ps(a0)\n                                                                  , _MM_SHUFFLE(2,0,2,0)\n                                                                  )\n                                                  )\n                                , _mm_castps_si128(_mm_shuffle_ps ( _mm_castsi128_ps(a1)\n                                                                  , _mm_castsi128_ps(a1)\n                                                                  , _MM_SHUFFLE(2,0,2,0)\n                                                                  )\n                                                  )\n                                );\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( interleave_even_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::ints64_<A0>, bs::sse_>\n                          , bs::pack_<bd::ints64_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator()(const A0 & a0, const A0 & a1) const BOOST_NOEXCEPT\n    {\n      return _mm_unpacklo_epi64(a0,a1);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "780bae56579197e9bc37a1897880b2fd3edc801b", "size": 2768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/sse2/simd/function/interleave_even.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/x86/sse2/simd/function/interleave_even.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/x86/sse2/simd/function/interleave_even.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": 39.5428571429, "max_line_length": 100, "alphanum_fraction": 0.4132947977, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970886}}
{"text": "/*\n   Copyright 2012 efalex <email>\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\nhttp://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 \"box_solver.hpp\"\n#include <algorithm>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/foreach.hpp>\n#include <limits.h>\n#include \"box.hpp\"\n#include \"figure.hpp\"\n#include \"box_solution.hpp\"\n#include \"glwidget.hpp\"\n\nusing namespace boost::numeric::ublas;\n\nvoid box_solver::init()\n{\n    count = 0;\n    rotate_matrix.resize(0);\n    matrix < int >r(3, 3);\n    r(0, 0) =  1; r(0, 1) =  0; r(0, 2) =  0;\n    r(1, 0) =  0; r(1, 1) =  0; r(1, 2) = -1;\n    r(2, 0) =  0; r(2, 1) =  1; r(2, 2) =  0;\n    rotate_matrix.push_back(r);\n    r(0, 0) =  0; r(0, 1) =  0; r(0, 2) =  1;\n    r(1, 0) =  0; r(1, 1) =  1; r(1, 2) =  0;\n    r(2, 0) = -1; r(2, 1) =  0; r(2, 2) =  0;\n    rotate_matrix.push_back(r);\n    r(0, 0) =  0; r(0, 1) = -1; r(0, 2) =  0;\n    r(1, 0) =  1; r(1, 1) =  0; r(1, 2) =  0;\n    r(2, 0) =  0; r(2, 1) =  0; r(2, 2) =  1;\n    rotate_matrix.push_back(r);\n    depth.resize(8);\n    for (unsigned int d = 0; d < depth.size(); ++d) {\n        depth[d] = 0;\n    }\n}\nbox_solver::box_solver():check_count(1000000),stopComputingFlag(false),updateStatusFlag(false)\n{\n    init();\n}\n\nvoid box_solver::run()\n{\n#if 1\n    initFigures();\n    solve();\n#else\n    initSolution();\n    std::cout << box_solution::isUnique(solution, solution_pos) << std::endl;\n    GLWidget::gl_count = figures.size();\n    GLWidget::gl_solution = solution;\n    GLWidget::gl_solution_pos = solution_pos;\n    emit drawBox();\n    sleep(2);\n    box_solution::addSolution(solution, solution_pos);\n    std::cout << box_solution::isUnique(solution, solution_pos) << std::endl;\n    std::cout << box_solution(solution, solution_pos);\n    std::cout << \"Depth: \" << depth << std::endl;\n    std::cout << std::endl;\n    sleep(1);\n    box_solution::addSolution(solution, solution_pos);\n    sleep(1);\n    box_solution::addSolution(solution, solution_pos);\n    sleep(1);\n    box_solution::addSolution(solution, solution_pos);\n    sleep(1);\n    box_solution::addSolution(solution, solution_pos);\n    sleep(1);\n    box_solution::addSolution(solution, solution_pos);\n    sleep(1);\n    box_solution::addSolution(solution, solution_pos);\n#endif\n}\n\nint box_solver::iterateFigure(unsigned int i)\n{\n    if (stopComputingFlag) {\n        return 0;\n    }\n    if (i >= figures.size()) {\n        if (box_solution::isUnique(solution, solution_pos)) {\n            // found solution!\n            box_solution::addSolution(solution, solution_pos);\n            GLWidget::gl_count = figures.size();\n            GLWidget::gl_solution = solution;\n            GLWidget::gl_solution_pos = solution_pos;\n            GLWidget::gl_pos = box_solution::solution_list.size() - 1;\n            std::cout << \"Solution found!\" << std::endl << \" After \" << count << \" iterations\" << std::endl;\n            std::cout << \"Solution: \" << GLWidget::gl_pos << std::endl;\n            std::cout << box_solution(solution, solution_pos);\n            std::cout << \"Depth: \" << depth << std::endl;\n            std::cout << std::endl;\n            emit drawBox();\n            usleep(100000);\n            //stopComputingFlag = true;\n        }\n        return 0;\n    }\n    figure *f = &(figures[i]);\n    for (int rx = 0; rx < 4; ++rx) {\n        for (int ry = 0; ry < 4; ++ry) {\n            for (int rz = 0; rz < 4; ++rz) {\n                // find figure boundaries\n                vector_int min_v(3);\n                vector_int max_v(3);\n                min_v[0] = min_v[1] = min_v[2] = INT_MAX;\n                max_v[0] = max_v[1] = max_v[2] = INT_MIN;\n                BOOST_FOREACH(figure_cube & c, f->cubes) {\n                    min_v[0] = std::min(min_v[0], c.pos[0]);\n                    max_v[0] = std::max(max_v[0], c.pos[0]);\n                    min_v[1] = std::min(min_v[1], c.pos[1]);\n                    max_v[1] = std::max(max_v[1], c.pos[1]);\n                    min_v[2] = std::min(min_v[2], c.pos[2]);\n                    max_v[2] = std::max(max_v[2], c.pos[2]);\n                }\n                //                std::cout << \"min: \" << min_v << \" max: \" << max_v << std::endl;\n                //                std::cout << \" x : \"<< -min_v[0] << \" <-> \" << 4 - max_v[0] << std::endl;\n                //                std::cout << \" y : \"<< -min_v[1] << \" <-> \" << 3 - max_v[1] << std::endl;\n                //                std::cout << \" z : \"<< -min_v[2] << \" <-> \" << 2 - max_v[2] << std::endl;\n                if (max_v[0] - min_v[0] > 4 || max_v[1] - min_v[1] > 3 || max_v[2] - min_v[2] > 2) {\n                    continue;\n                }\n                // Move figure in the box\n                vector_int v(3);\n                for (int x = -min_v[0]; x < /*-min_v[0] + 1*/4 - max_v[0]; ++x) {\n                    v[0] = x;\n                    for (int y = -min_v[1]; y < /*-min_v[1] + 1 */3 - max_v[1]; ++y) {\n                        v[1] = y;\n                        for (int z = -min_v[2]; z < /*-min_v[2] + 1 */2 - max_v[2]; ++z) {\n                            v[2] = z;\n                            //b.dump();\n#if 0\n                            box *tmp_box = NULL;\n                            if (i > 0 && i < 3) {\n                                tmp_box = new box;\n                                *tmp_box = b;\n                            }\n#endif\n                            if (b.addFigure(*f, v)) {\n                                //b.dump();\n                                ++count;\n                                ++depth[i];\n                                solution[i] = *f;\n                                solution_pos[i] = v;\n#if 0\n                                if (b.getVolume() != (i+1) * 6) {\n                                    std::cerr << \"Volume check error!!!\" << std::endl;\n                                    std::cerr << \"Iteration: \" << count << std::endl;\n                                    for (int s = 0; s < i; ++s) {\n                                        std::cout << \"Item: \" << s << \" Position: \" <<  solution_pos[s] << \" Direction[0]: \" << solution[s].direction[0] << \" Direction[1]: \" << solution[s].direction[1] << std::endl;\n                                    }\n                                    std::cerr << \"Depth: \" << depth << std::endl;\n                                    std::cerr << std::endl;\n                                }\n#endif\n                                if (count % check_count == 0 || updateStatusFlag /*|| i >= 6*/) {\n                                    updateStatusFlag = false;\n                                    std::cout << \"Iteration: \" << count << std::endl;\n                                    for (unsigned int s = 0; s <= i; ++s) {\n                                        std::cout << \"Item: \" << s << \" Position: \" <<  solution_pos[s] << \" Direction[0]: \" << solution[s].direction[0] << \" Direction[1]: \" << solution[s].direction[1] << std::endl;\n                                    }\n                                    std::cout << \"Depth: \" << depth << std::endl;\n                                    std::cout << std::endl;\n                                    GLWidget::gl_count = i + 1;\n                                    GLWidget::gl_solution = solution;\n                                    GLWidget::gl_solution_pos = solution_pos;\n                                    emit drawBox();\n                                    //usleep(10000);\n                                    //stopComputingFlag = true;\n                                }\n                                // do recursive call\n                                iterateFigure(i + 1);\n                                if (stopComputingFlag) {\n                                    return 0;\n                                }\n                                if (!b.delFigure(*f, v)) {\n                                    std::cerr << \"Delete error!\" << std:: endl;\n                                    exit(1);\n                                }\n                                //b.dump();\n#if 0\n                                if (tmp_box) {\n                                    if (*tmp_box != b) {\n                                        std::cerr << \"Figure add/delete logic error!\" << std:: endl;\n                                        delete tmp_box;\n                                        tmp_box = NULL;\n                                        exit(1);\n                                    }\n                                    delete tmp_box;\n                                    tmp_box = NULL;\n                                }\n#endif\n#if 0\n                                if (i == 0) {\n                                    if (!b.isEmpty()) {\n                                        std::cerr << \"Figure add/delete logic error!\" << std:: endl;\n                                        exit(1);\n                                    }\n                                }\n#endif\n                            }\n                        }\n                    }\n                }\n                f->rotate(rotate_matrix[2]);\n            }\n            f->rotate(rotate_matrix[1]);\n        }\n        f->rotate(rotate_matrix[0]);\n    }\n    return 0;\n}\n\nint box_solver::solve()\n{\n    int res=iterateFigure(0);\n    std::cout << \"Total iterations: \" << count << std::endl;\n    std::cout << \"Depth: \" << depth << std::endl;\n    //emit drawBox();\n    return res;\n}\n\nvoid box_solver::initFigures()\n{\n    figures.resize(0);\n    solution.resize(8);\n    solution_pos.resize(8);\n    for (unsigned int p = 0; p < solution_pos.size(); ++p) {\n        solution_pos[p].resize(3);\n    }\n    // Figure 1\n    {\n        figure f;\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 1;\n            int v[3];\n            v[0] = 0;\n            v[1] = -1;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 2;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 1;\n            v[1] = 0;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        figures.push_back(f);\n    }\n    // Figure 2\n    {\n        figure f;\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 0;\n            fc.pos[1] = -1;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = -1;\n            v[1] = -1;\n            v[2] = 0;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 1;\n            fc.pos[1] = -1;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 0;\n            v[1] = -1;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        figures.push_back(f);\n    }\n    // Figure 3\n    {\n        figure f;\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 0;\n            fc.pos[1] = -1;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 1;\n            v[1] = -1;\n            v[2] = 0;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 2;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 1;\n            v[1] = 0;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        figures.push_back(f);\n    }\n    // Figure 4\n    {\n        figure f;\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 0;\n            fc.pos[1] = 1;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 0;\n            v[1] = 1;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 1;\n            fc.pos[1] = -1;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = -1;\n            v[1] = -1;\n            v[2] = 0;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        figures.push_back(f);\n    }\n    // Figure 5\n    {\n        figure f;\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = -1;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 0;\n            fc.pos[1] = -1;\n            fc.pos[2] = 1;\n            int v[3];\n            v[0] = 0;\n            v[1] = 1;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 1;\n            v[1] = -1;\n            v[2] = 0;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        figures.push_back(f);\n    }\n    // Figure 6\n    {\n        figure f;\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 1;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 1;\n            v[1] = 0;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 0;\n            fc.pos[1] = -1;\n            fc.pos[2] = 1;\n            int v[3];\n            v[0] = 1;\n            v[1] = -1;\n            v[2] = 0;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        figures.push_back(f);\n    }\n    //Figure 7\n    {\n        figure f;\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = -1;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = -1;\n            v[1] = 1;\n            v[2] = 0;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 1;\n            fc.pos[1] = -1;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 1;\n            v[1] = 0;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        figures.push_back(f);\n    }\n    //Figure 8\n    {\n        figure f;\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_full);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 1;\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 0;\n            fc.pos[1] = 0;\n            fc.pos[2] = 0;\n            int v[3];\n            v[0] = 0;\n            v[1] = -1;\n            v[2] = -1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        {\n            figure_cube fc;\n            fc.c.setState(cell_half);\n            fc.pos[0] = 1;\n            fc.pos[1] = 0;\n            fc.pos[2] = 1;\n            int v[3];\n            v[0] = 0;\n            v[1] = 1;\n            v[2] = 1;\n            fc.c.setVector(v);\n            f.addFigureCube(fc);\n        }\n        figures.push_back(f);\n    }\n}\n\nvoid box_solver::stopComputing()\n{\n    stopComputingFlag = true;\n}\n\nvoid box_solver::updateStatus()\n{\n    updateStatusFlag = true;\n}\n\nvoid box_solver::setRotateVector(boost::numeric::ublas::matrix < int > & m, int x1, int y1, int z1, int x2, int y2 , int z2)\n{\n    m(0,0) = x1;\n    m(1,0) = y1;\n    m(2,0) = z1;\n\n    m(0,1) = x2;\n    m(1,1) = y2;\n    m(2,1) = z2;\n\n    m(0,2) = y1 * z2 - z1 * y2;\n    m(1,2) = z1 * x2 - x1 * z2;\n    m(2,2) = x1 * y2 - y1 * x2;\n}\n\n\nvoid box_solver::initSolution() {\n    initFigures();\n    matrix < int >r(3, 3);\n\n    setRotateVector(r, 0,1,0,-1,0,0);\n    solution[0] = figures[0];\n    solution[0].rotate(r);\n    solution_pos[0][0] = 0;\n    solution_pos[0][1] = 0;\n    solution_pos[0][2] = 0;\n\n    setRotateVector(r, 1,0,0, 0,1,0);\n    solution[1] = figures[1];\n    solution[1].rotate(r);\n    solution_pos[1][0] = 2;\n    solution_pos[1][1] = 1;\n    solution_pos[1][2] = 0;\n\n    setRotateVector(r, -1,0,0, 0,0,-1);\n    solution[2] = figures[2];\n    solution[2].rotate(r);\n    solution_pos[2][0] = 3;\n    solution_pos[2][1] = 2;\n    solution_pos[2][2] = 0;\n\n    setRotateVector(r, 0,0,1, 1,0,0);\n    solution[3] = figures[3];\n    solution[3].rotate(r);\n    solution_pos[3][0] = 1;\n    solution_pos[3][1] = 0;\n    solution_pos[3][2] = 0;\n\n\n    setRotateVector(r, 0,0,-1, 0,1,0);\n    solution[4] = figures[4];\n    solution[4].rotate(r);\n    solution_pos[4][0] = 0;\n    solution_pos[4][1] = 2;\n    solution_pos[4][2] = 1;\n\n    setRotateVector(r, 0,1,0, 0,0,1);\n    solution[5] = figures[5];\n    solution[5].rotate(r);\n    solution_pos[5][0] = 2;\n    solution_pos[5][1] = 0;\n    solution_pos[5][2] = 1;\n\n    setRotateVector(r, 1,0,0, 0,-1,0);\n    solution[6] = figures[6];\n    solution[6].rotate(r);\n    solution_pos[6][0] = 2;\n    solution_pos[6][1] = 1;\n    solution_pos[6][2] = 1;\n\n    setRotateVector(r, 0,0,1, -1,0,0);\n    solution[7] = figures[7];\n    solution[7].rotate(r);\n    solution_pos[7][0] = 1;\n    solution_pos[7][1] = 2;\n    solution_pos[7][2] = 0;\n\n    GLWidget::gl_count = figures.size();\n    GLWidget::gl_solution = solution;\n    GLWidget::gl_solution_pos = solution_pos;\n}\n", "meta": {"hexsha": "54ef062f6faaefd70c3a55e59abd47b7c8b3715e", "size": 21074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "box_solver.cpp", "max_stars_repo_name": "EfAlex/Puzzle-Box-Solver", "max_stars_repo_head_hexsha": "03316f936f567d98916f94d4571e01fb24b93617", "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": "box_solver.cpp", "max_issues_repo_name": "EfAlex/Puzzle-Box-Solver", "max_issues_repo_head_hexsha": "03316f936f567d98916f94d4571e01fb24b93617", "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": "box_solver.cpp", "max_forks_repo_name": "EfAlex/Puzzle-Box-Solver", "max_forks_repo_head_hexsha": "03316f936f567d98916f94d4571e01fb24b93617", "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.4741258741, "max_line_length": 215, "alphanum_fraction": 0.3909082281, "num_tokens": 5872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970886}}
{"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\u00dfe 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\n *\n */\n\n#ifndef KP_TSF_DATA_INTEGRATION_HH\n#define KP_TSF_DATA_INTEGRATION_HH\n\n#include <iostream>\n#include <fstream>\n#include <float.h>\n#include <Eigen/Dense>\n#include <opencv2/core/core.hpp>\n#include \"opencv2/video/tracking.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include <boost/thread/mutex.hpp>\n#include <boost/thread.hpp>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/io/io.h>\n#include <boost/shared_ptr.hpp>\n#include <v4r/common/impl/DataMatrix2D.hpp>\n#include <v4r/camera_tracking_and_mapping/TSFData.h>\n#include <v4r/camera_tracking_and_mapping/OcclusionClustering.hh>\n#include <v4r/core/macros.h>\n\n\nnamespace v4r\n{\n\n\n\n/**\n * TSFDataIntegration\n */\nclass V4R_EXPORTS TSFDataIntegration \n{\npublic:\n\n  /**\n   * Parameter\n   */\n  class Parameter\n  {\n  public:\n    int max_integration_frames;\n    float sigma_depth;\n    bool filter_occlusions;\n    double diff_cam_distance_map; // minimum distance the camera must move to select a keyframe\n    double diff_delta_angle_map;  // or minimum angle a camera need to rotate to be selected\n    int min_frames_integrated;\n    Parameter()\n      : max_integration_frames(20), sigma_depth(0.008), filter_occlusions(true), diff_cam_distance_map(0.5), diff_delta_angle_map(7.), min_frames_integrated(10) {}\n  };\n\n \n\nprivate:\n  bool tsf_mapping;\n  Parameter param;\n\n  double sqr_diff_cam_distance_map;\n  double cos_diff_delta_angle_map;\n\n  static std::vector<cv::Vec4i> npat;\n\n  cv::Mat_<double> intrinsic;\n\n  bool run, have_thread;\n\n  boost::thread th_obectmanagement;\n  boost::thread th_init;\n\n  std::vector<float> exp_error_lookup;\n\n  TSFData *data;\n\n  cv::Mat_<float> depth_norm;\n  cv::Mat_<float> depth_weight;\n  cv::Mat_<float> tmp_z;\n  cv::Mat_<float> nan_z;\n\n  Eigen::Matrix4f inv_pose0, inv_pose1;\n\n  cv::Mat_<unsigned char> occ_mask;\n\n  OcclusionClustering occ;\n\n  void operate();\n\n  bool selectFrame(const Eigen::Matrix4f &pose0, const Eigen::Matrix4f &pose1);\n  void integrateData(const pcl::PointCloud<pcl::PointXYZRGB> &cloud, const Eigen::Matrix4f &pose, const Eigen::Matrix4f &filt_pose, v4r::DataMatrix2D<Surfel> &filt_cloud);\n  inline float sqr(const float &d) {return d*d;}\n\n\npublic:\n  cv::Mat dbg;\n\n  TSFDataIntegration(const Parameter &p=Parameter());\n  ~TSFDataIntegration();\n\n  void start();\n  void stop();\n\n  inline bool isStarted() {return have_thread;}\n\n  inline void lock(){ data->lock(); }        // threaded object management, so we need to lock\n  inline void unlock() { data->unlock(); }\n\n  void reset();\n  void setData(TSFData *_data) { data = _data; }\n\n  void initCloud(const pcl::PointCloud<pcl::PointXYZRGB> &cloud, v4r::DataMatrix2D<Surfel> &sf_cloud);\n\n  static void computeRadius(v4r::DataMatrix2D<Surfel> &sf_cloud, const cv::Mat_<double> &intrinsic);\n  static void computeNormals(v4r::DataMatrix2D<Surfel> &sf_cloud, int nb_dist=1);\n\n  void setCameraParameter(const cv::Mat &_intrinsic);\n  void setParameter(const Parameter &p);\n  void setSelectMappingFrames(const int &_tsf_mapping) { tsf_mapping = _tsf_mapping; }\n\n  typedef boost::shared_ptr< ::v4r::TSFDataIntegration> Ptr;\n  typedef boost::shared_ptr< ::v4r::TSFDataIntegration const> ConstPtr;\n};\n\n\n\n/*************************** INLINE METHODES **************************/\n\n\n\n} //--END--\n\n#endif\n\n", "meta": {"hexsha": "0510e9b312a35f7f6622167b5cbc7d875e0d128e", "size": 4287, "ext": "hh", "lang": "C++", "max_stars_repo_path": "modules/camera_tracking_and_mapping/include/v4r/camera_tracking_and_mapping/TSFDataIntegration.hh", "max_stars_repo_name": "ToMadoRe/v4r", "max_stars_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T14:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T02:57:33.000Z", "max_issues_repo_path": "modules/camera_tracking_and_mapping/include/v4r/camera_tracking_and_mapping/TSFDataIntegration.hh", "max_issues_repo_name": "ToMadoRe/v4r", "max_issues_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T15:04:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T10:52:35.000Z", "max_forks_repo_path": "modules/camera_tracking_and_mapping/include/v4r/camera_tracking_and_mapping/TSFDataIntegration.hh", "max_forks_repo_name": "ToMadoRe/v4r", "max_forks_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T09:26:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T01:31:00.000Z", "avg_line_length": 26.3006134969, "max_line_length": 171, "alphanum_fraction": 0.7168182878, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970883}}
{"text": "#include <boost/python/class.hpp>\n#include <boost/python/implicit.hpp>\n\n#include <scitbx/boost_python/container_conversions.h>\n\n#include <smtbx/refinement/constraints/geometrical_hydrogens.h>\n\n#include <sstream>\n\nnamespace smtbx { namespace refinement { namespace constraints {\nnamespace boost_python {\n\n  template <int n_hydrogens, bool staggered>\n  struct terminal_tetrahedral_xhn_sites_wrapper\n  {\n    typedef terminal_tetrahedral_xhn_sites<n_hydrogens, staggered> wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      std::ostringstream sname;\n      if (staggered) sname << \"staggered_\";\n      sname << \"terminal_tetrahedral_xh\";\n      if (n_hydrogens > 1) sname << n_hydrogens;\n      sname << \"_site\";\n      if (n_hydrogens > 1) sname << \"s\";\n      std::string name = sname.str();\n      if (staggered) {\n        class_<wt,\n               bases<asu_parameter>,\n               std::auto_ptr<wt> >(name.c_str(), no_init)\n          .def(init<site_parameter *,\n                    site_parameter *,\n                    site_parameter *,\n                    independent_scalar_parameter *,\n                    af::tiny<typename wt::scatterer_type *,\n                             n_hydrogens> const &>\n               ((arg(\"pivot\"), arg(\"pivot_neighbour\"), arg(\"stagger_on\"),\n                 arg(\"length\"),\n                 arg(\"hydrogen\"))))\n          ;\n      }\n      else {\n        class_<wt,\n               bases<asu_parameter>,\n               std::auto_ptr<wt> >(name.c_str(), no_init)\n          .def(init<site_parameter *,\n                    site_parameter *,\n                    independent_scalar_parameter *,\n                    independent_scalar_parameter *,\n                    cart_t const &,\n                    af::tiny<typename wt::scatterer_type *,\n                             n_hydrogens> const &>\n               ((arg(\"pivot\"), arg(\"pivot_neighbour\"),\n                 arg(\"azimuth\"), arg(\"length\"),\n                 arg(\"e_zero_azimuth\"),\n                 arg(\"hydrogen\"))))\n          ;\n      }\n      implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();\n    }\n  };\n\n  struct angle_parameter_wrapper {\n    typedef angle_parameter wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      class_<wt,\n             bases<scalar_parameter>,\n             std::auto_ptr<wt> >(\"angle_parameter\", no_init)\n        .def(init<site_parameter *,\n                site_parameter *,\n                site_parameter *,\n                double>\n           ((arg(\"left\"), arg(\"center\"), arg(\"right\"), arg(\"value\"))));\n      implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();\n    }\n  };\n\n  struct secondary_xh2_sites_wrapper\n  {\n    typedef secondary_xh2_sites wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      class_<wt,\n             bases<asu_parameter>,\n             std::auto_ptr<wt> >(\"secondary_xh2_sites\", no_init)\n        .def(init<site_parameter *,\n                site_parameter *,\n                site_parameter *,\n                independent_scalar_parameter *,\n                scalar_parameter *,\n                wt::scatterer_type *,\n                wt::scatterer_type *>\n           ((arg(\"pivot\"), arg(\"pivot_neighbour_0\"), arg(\"pivot_neighbour_1\"),\n             arg(\"length\"), arg(\"h_c_h_angle\"),\n             arg(\"hydrogen_0\"), arg(\"hydrogen_1\"))));\n      implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();\n    }\n  };\n\n  struct tertiary_xh_site_wrapper\n  {\n    typedef tertiary_xh_site wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      class_<wt,\n             bases<asu_parameter>,\n             std::auto_ptr<wt> >(\"tertiary_xh_site\", no_init)\n        .def(init<site_parameter *,\n                  site_parameter *,\n                  site_parameter *,\n                  site_parameter *,\n                  independent_scalar_parameter *,\n                  wt::scatterer_type *>\n             ((arg(\"pivot\"), arg(\"pivot_neighbour_0\"), arg(\"pivot_neighbour_1\"),\n               arg(\"pivot_neighbour_2\"), arg(\"length\"),\n               arg(\"hydrogen\"))));\n      implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();\n    }\n  };\n\n  struct secondary_planar_xh_site_wrapper\n  {\n    typedef secondary_planar_xh_site wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      class_<wt,\n             bases<asu_parameter>,\n             std::auto_ptr<wt> >(\"secondary_planar_xh_site\", no_init)\n        .def(init<site_parameter *,\n                  site_parameter *,\n                  site_parameter *,\n                  independent_scalar_parameter *,\n                  wt::scatterer_type *>\n             ((arg(\"pivot\"), arg(\"pivot_neighbour_0\"), arg(\"pivot_neighbour_1\"),\n               arg(\"length\"),\n               arg(\"hydrogen\"))));\n      implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();\n    }\n  };\n\n  struct terminal_planar_xh2_sites_wrapper\n  {\n    typedef terminal_planar_xh2_sites wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      class_<wt,\n             bases<asu_parameter>,\n             std::auto_ptr<wt> >(\"terminal_planar_xh2_sites\", no_init)\n        .def(init<site_parameter *,\n                  site_parameter *,\n                  site_parameter *,\n                  independent_scalar_parameter *,\n                  wt::scatterer_type *, wt::scatterer_type *>\n             ((arg(\"pivot\"), arg(\"pivot_neighbour\"),\n               arg(\"pivot_neighbour_substituent\"), arg(\"length\"),\n               arg(\"hydrogen_0\"), arg(\"hydrogen_1\"))));\n      implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();\n    }\n  };\n\n\n  struct terminal_linear_ch_site_wrapper\n  {\n    typedef terminal_linear_ch_site wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      class_<wt,\n             bases<asu_parameter>,\n             std::auto_ptr<wt> >(\"terminal_linear_ch_site\", no_init)\n        .def(init<site_parameter *,\n                  site_parameter *,\n                  independent_scalar_parameter *,\n                  wt::scatterer_type *>\n             ((arg(\"pivot\"), arg(\"pivot_neighbour\"), arg(\"length\"),\n               arg(\"hydrogen\"))));\n      implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();\n    }\n  };\n\n  struct polyhedral_bh_site_wrapper\n  {\n    typedef polyhedral_bh_site wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      class_<wt,\n             bases<asu_parameter>,\n             std::auto_ptr<wt> >(\"polyhedral_bh_site\", no_init)\n        .def(init<site_parameter *,\n                  af::shared<site_parameter *> const&,\n                  independent_scalar_parameter *,\n                  wt::scatterer_type *>\n             ((arg(\"pivot\"), arg(\"pivot_neighbours\"), arg(\"length\"),\n               arg(\"hydrogen\"))));\n      implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();\n    }\n  };\n\n  void wrap_geometrical_hydrogens() {\n    {\n      using namespace scitbx::boost_python::container_conversions;\n      tuple_mapping_fixed_size<af::tiny<asu_parameter::scatterer_type *, 1> >();\n      tuple_mapping_fixed_size<af::tiny<asu_parameter::scatterer_type *, 2> >();\n      tuple_mapping_fixed_size<af::tiny<asu_parameter::scatterer_type *, 3> >();\n      tuple_mapping_variable_capacity<af::shared<site_parameter *> >();\n    }\n    //                                    #H  #staggered?\n    terminal_tetrahedral_xhn_sites_wrapper<1, false>::wrap();\n    terminal_tetrahedral_xhn_sites_wrapper<2, false>::wrap();\n    terminal_tetrahedral_xhn_sites_wrapper<3, false>::wrap();\n    terminal_tetrahedral_xhn_sites_wrapper<1, true>::wrap();\n    terminal_tetrahedral_xhn_sites_wrapper<2, true>::wrap();\n    terminal_tetrahedral_xhn_sites_wrapper<3, true>::wrap();\n\n    angle_parameter_wrapper::wrap();\n    secondary_xh2_sites_wrapper::wrap();\n    tertiary_xh_site_wrapper::wrap();\n    secondary_planar_xh_site_wrapper::wrap();\n    terminal_planar_xh2_sites_wrapper::wrap();\n    terminal_linear_ch_site_wrapper::wrap();\n    polyhedral_bh_site_wrapper::wrap();\n  }\n\n\n}}}}\n", "meta": {"hexsha": "b95e831b3e987d629e1dc18c3ac3b2c5b99a5fd8", "size": 8081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "smtbx/refinement/constraints/boost_python/geometrical_hydrogens.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": "smtbx/refinement/constraints/boost_python/geometrical_hydrogens.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": "smtbx/refinement/constraints/boost_python/geometrical_hydrogens.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.6824034335, "max_line_length": 80, "alphanum_fraction": 0.5795074867, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.19131846660970883}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/miller/match_bijvoet_mates.h>\n#include <boost/python/class.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/copy_const_reference.hpp>\n\nnamespace cctbx { namespace miller { namespace boost_python {\n\nnamespace {\n\n  struct match_bijvoet_mates_wrappers\n  {\n    typedef match_bijvoet_mates w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      typedef return_value_policy<copy_const_reference> ccr;\n      class_<w_t>(\"match_bijvoet_mates\", no_init)\n        .def(init<sgtbx::space_group_type const&,\n                  af::shared<index<> > const&,\n                  bool>((\n                    arg(\"sg_type\"), arg(\"indices\"),\n                    arg(\"assert_is_unique_set_under_symmetry\")=true)))\n        .def(init<sgtbx::reciprocal_space::asu const&,\n                  af::shared<index<> > const&,\n                  bool>((\n                    arg(\"asu\"), arg(\"indices\"),\n                    arg(\"assert_is_unique_set_under_symmetry\")=true)))\n        .def(init<af::shared<index<> > const&,\n                  bool>((\n                    arg(\"indices\"),\n                    arg(\"assert_is_unique_set_under_symmetry\")=true)))\n        .def(\"pairs\", &w_t::pairs)\n        .def(\"singles\", &w_t::singles)\n        .def(\"n_singles\", &w_t::n_singles)\n        .def(\"pairs_hemisphere_selection\", &w_t::pairs_hemisphere_selection)\n        .def(\"singles_hemisphere_selection\",\n          &w_t::singles_hemisphere_selection, ccr())\n        .def(\"miller_indices_in_hemisphere\",\n          &w_t::miller_indices_in_hemisphere)\n#define CCTBX_DEF(function_name) \\\n        .def(# function_name, \\\n          (af::shared<double>(w_t::*)(af::const_ref<double> const&) const) \\\n          &w_t::function_name)\n        CCTBX_DEF(minus)\n        CCTBX_DEF(additive_sigmas)\n        CCTBX_DEF(average)\n#undef CCTBX_DEF\n      ;\n    }\n  };\n\n} // namespace <anoymous>\n\n  void wrap_match_bijvoet_mates()\n  {\n    match_bijvoet_mates_wrappers::wrap();\n  }\n\n}}} // namespace cctbx::miller::boost_python\n", "meta": {"hexsha": "261fb7926110ed8bdc36a5f12b51e0f6b088351f", "size": 2069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/miller/boost_python/match_bijvoet_mates.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": "cctbx/miller/boost_python/match_bijvoet_mates.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": "cctbx/miller/boost_python/match_bijvoet_mates.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": 32.328125, "max_line_length": 76, "alphanum_fraction": 0.610439826, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.19131846660970883}}
{"text": "#include \"../Positive_Matrix_With_Prefactor.hxx\"\n#include \"../../sdp_read.hxx\"\n\n#include <boost/filesystem.hpp>\n\nvoid read_json(const boost::filesystem::path &input_path,\n               std::vector<El::BigFloat> &objectives,\n               std::vector<El::BigFloat> &normalization,\n               std::vector<Positive_Matrix_With_Prefactor> &matrices);\n\nvoid read_mathematica(const boost::filesystem::path &input_path,\n                      std::vector<El::BigFloat> &objectives,\n                      std::vector<El::BigFloat> &normalization,\n                      std::vector<Positive_Matrix_With_Prefactor> &matrices);\n\nvoid read_input(const boost::filesystem::path &input_file,\n                std::vector<El::BigFloat> &objectives,\n                std::vector<El::BigFloat> &normalization,\n                std::vector<Positive_Matrix_With_Prefactor> &matrices)\n{\n  if(input_file.extension() == \".nsv\")\n    {\n      for(auto &filename : read_file_list(input_file))\n        {\n          read_input(filename, objectives, normalization, matrices);\n        }\n    }\n  else if(input_file.extension() == \".json\")\n    {\n      read_json(input_file, objectives, normalization, matrices);\n    }\n  else\n    {\n      read_mathematica(input_file, objectives, normalization, matrices);\n    }\n\n  for(auto &matrix : matrices)\n    {\n      for(auto &pole : matrix.damped_rational.poles)\n        {\n          if(pole > 0)\n            {\n              throw std::runtime_error(\n                \"All poles must be negative, but found '\" + to_string(pole)\n                + \"'\");\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "b76d8defb4afa50ce7bad27cbfd363821520f355", "size": 1588, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/sdp_read/read_input/read_input.cxx", "max_stars_repo_name": "maneandrea/sdpb", "max_stars_repo_head_hexsha": "3387616c69cd50f17b7b40da238be23f6c810dcb", "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/sdp_read/read_input/read_input.cxx", "max_issues_repo_name": "maneandrea/sdpb", "max_issues_repo_head_hexsha": "3387616c69cd50f17b7b40da238be23f6c810dcb", "max_issues_repo_licenses": ["MIT"], "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/sdp_read/read_input/read_input.cxx", "max_forks_repo_name": "maneandrea/sdpb", "max_forks_repo_head_hexsha": "3387616c69cd50f17b7b40da238be23f6c810dcb", "max_forks_repo_licenses": ["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.76, "max_line_length": 77, "alphanum_fraction": 0.5900503778, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.1913184594697211}}
{"text": "#include <boost/mpl/vector.hpp>\n#include <boost/mpl/insert_range.hpp>\n#include <boost/mpl/begin_end.hpp>\n#include \"tessellated_icosahedron.hpp\"\n#include \"prog_interface_static_link.h\"\n#include \"basic_voxel.hpp\"\n#include \"image_model.hpp\"\n#include \"odf_decomposition.hpp\"\n#include \"odf_process.hpp\"\n\n#include \"sample_model.hpp\"\n#include \"space_mapping.hpp\"\n\n#include \"dti_process.hpp\"\n#include \"dsi_process.hpp\"\n#include \"qbi_process.hpp\"\n#include \"sh_process.hpp\"\n#include \"gqi_process.hpp\"\n#include \"gqi_mni_reconstruction.hpp\"\n\n#include \"odf_deconvolusion.hpp\"\n#include \"odf_decomposition.hpp\"\n#include \"image_model.hpp\"\n\n\nextern std::string t1w_template_file_name;\n\ntypedef boost::mpl::vector<\n    ReadDWIData,\n    Dwi2Tensor\n> dti_process;\n\ntypedef boost::mpl::vector<\n    ReadDWIData,\n    HQSpace2Odf,\n    DetermineFiberDirections,\n    ScaleZ0ToMinODF,\n    SaveFA,\n    SaveDirIndex,\n    OutputODF\n> hgqi_process;\n\n\ntemplate<class reco_type>\nstruct odf_reco_type{\n    typedef boost::mpl::vector<\n        ODFDeconvolusion,\n        ODFDecomposition,\n        DetermineFiberDirections,\n        ScaleZ0ToMinODF,\n        SaveFA,\n        SaveDirIndex,\n        OutputODF\n    > common_odf_process;\n    typedef typename boost::mpl::insert_range<common_odf_process,boost::mpl::begin<common_odf_process>::type,reco_type>::type type0;\n    typedef typename boost::mpl::push_front<type0,ReadDWIData>::type type; // add ReadDWIData to the front\n};\n\ntemplate<class reco_type>\nstruct estimation_type{\n    typedef boost::mpl::vector<\n        DetermineFiberDirections,\n        EstimateResponseFunction\n    > common_estimation_process;\n\n    typedef typename boost::mpl::insert_range<common_estimation_process,boost::mpl::begin<common_estimation_process>::type,reco_type>::type type0;\n    typedef typename boost::mpl::push_front<type0,ReadDWIData>::type type; // add ReadDWIData to the front\n};\n\n\ntypedef odf_reco_type<boost::mpl::vector<\n    QSpace2Pdf,\n    Pdf2Odf\n> >::type dsi_process;\n\nconst unsigned int equator_sample_count = 40;\ntypedef odf_reco_type<boost::mpl::vector<\n    QBIReconstruction<equator_sample_count>\n> >::type qbi_process;\n\ntypedef odf_reco_type<boost::mpl::vector<\n    SHDecomposition\n> >::type qbi_sh_process;\n\n\ntypedef odf_reco_type<boost::mpl::vector<\n    BalanceScheme,\n    QSpace2Odf,\n    RestrictedDiffusionImaging\n> >::type gqi_process;\n\ntypedef boost::mpl::vector<\n    ReadDWIData,\n    QSpaceSpectral\n> gqi_spectral_process;\n\ntypedef boost::mpl::vector<\n    ReadDWIData,\n    BalanceScheme,\n    SchemeConverter\n> hardi_convert_process;\n\n// for ODF deconvolution\ntypedef estimation_type<boost::mpl::vector<\n    QSpace2Pdf,\n    Pdf2Odf\n> >::type dsi_estimate_response_function;\n\n// for ODF deconvolution\ntypedef estimation_type<boost::mpl::vector<\n    QBIReconstruction<equator_sample_count>\n> >::type qbi_estimate_response_function;\n\n// for ODF deconvolution\ntypedef estimation_type<boost::mpl::vector<\n    SHDecomposition\n> >::type qbi_sh_estimate_response_function;\n\n\n// for ODF deconvolution\ntypedef boost::mpl::vector<\n    ReadDWIData,\n    BalanceScheme,\n    QSpace2Odf,\n    DetermineFiberDirections,\n    RecordQA,\n    EstimateResponseFunction\n\n> gqi_estimate_response_function;\n\ntypedef boost::mpl::vector<\n    DWINormalization,\n    BalanceScheme,\n    QSDR,\n    RestrictedDiffusionImaging,\n    ODFDeconvolusion,\n    ODFDecomposition,\n    EstimateZ0_MNI,\n    DetermineFiberDirections,\n    SaveFA,\n    SaveDirIndex,\n    OutputODF\n> gqi_mni_process;\n\ntypedef boost::mpl::vector<\n    ODFLoader,\n    DetermineFiberDirections,\n    SaveFA,\n    SaveDirIndex\n> reprocess_odf;\n\ndouble base_function(double theta)\n{\n    if(std::abs(theta) < 0.000001)\n        return 1.0/3.0;\n    return (2*std::cos(theta)+(theta-2.0/theta)*std::sin(theta))/theta/theta;\n}\n\nstd::pair<float,float> evaluate_fib(\n        const image::geometry<3>& dim,\n        const std::vector<std::vector<float> >& fib_fa,\n        const std::vector<std::vector<float> >& fib_dir)\n{\n    unsigned char num_fib = fib_fa.size();\n    char dx[13] = {1,0,0,1,1,0, 1, 1, 0, 1,-1, 1, 1};\n    char dy[13] = {0,1,0,1,0,1,-1, 0, 1, 1, 1,-1, 1};\n    char dz[13] = {0,0,1,0,1,1, 0,-1,-1, 1, 1, 1,-1};\n    std::vector<image::vector<3> > dis(13);\n    for(unsigned int i = 0;i < 13;++i)\n    {\n        dis[i] = image::vector<3>(dx[i],dy[i],dz[i]);\n        dis[i].normalize();\n    }\n    float otsu = *std::max_element(fib_fa[0].begin(),fib_fa[0].end())*0.1;\n    std::vector<std::vector<unsigned char> > connected(fib_fa.size());\n    for(unsigned int index = 0;index < connected.size();++index)\n        connected[index].resize(dim.size());\n    float connection_count = 0;\n    for(image::pixel_index<3> index(dim);index < dim.size();++index)\n    {\n        if(fib_fa[0][index.index()] <= otsu)\n            continue;\n        unsigned int index3 = index.index()+index.index()+index.index();\n        for(unsigned char fib1 = 0;fib1 < num_fib;++fib1)\n        {\n            if(fib_fa[fib1][index.index()] <= otsu)\n                break;\n            for(unsigned int j = 0;j < 2;++j)\n            for(unsigned int i = 0;i < 13;++i)\n            {\n                image::vector<3,int> pos;\n                pos = j ? image::vector<3,int>(index[0] + dx[i],index[1] + dy[i],index[2] + dz[i])\n                          :image::vector<3,int>(index[0] - dx[i],index[1] - dy[i],index[2] - dz[i]);\n                if(!dim.is_valid(pos))\n                    continue;\n                image::pixel_index<3> other_index(pos[0],pos[1],pos[2],dim);\n                unsigned int other_index3 = other_index.index()+other_index.index()+other_index.index();\n                if(std::abs(image::vector<3>(&fib_dir[fib1][index3])*dis[i]) <= 0.8665)\n                    continue;\n                for(unsigned char fib2 = 0;fib2 < num_fib;++fib2)\n                    if(fib_fa[fib2][other_index.index()] > otsu &&\n                            std::abs(image::vector<3>(&fib_dir[fib2][other_index3])*dis[i]) > 0.8665)\n                    {\n                        connected[fib1][index.index()] = 1;\n                        connected[fib2][other_index.index()] = 1;\n                        connection_count += fib_fa[fib2][other_index.index()];\n                    }\n            }\n        }\n    }\n    float no_connection_count = 0;\n    for(image::pixel_index<3> index(dim);index < dim.size();++index)\n    {\n        for(unsigned int i = 0;i < num_fib;++i)\n            if(fib_fa[i][index.index()] > otsu && !connected[i][index.index()])\n            {\n                no_connection_count += fib_fa[i][index.index()];\n            }\n\n    }\n\n    return std::make_pair(connection_count,no_connection_count);\n}\n\nvoid flip_fib_dir(std::vector<float>& fib_dir,const unsigned char* order)\n{\n    for(unsigned int j = 0;j+2 < fib_dir.size();j += 3)\n    {\n        float x = fib_dir[j+order[0]];\n        float y = fib_dir[j+order[1]];\n        float z = fib_dir[j+order[2]];\n        fib_dir[j] = x;\n        fib_dir[j+1] = y;\n        fib_dir[j+2] = z;\n        if(order[3])\n            fib_dir[j] = -fib_dir[j];\n        if(order[4])\n            fib_dir[j+1] = -fib_dir[j+1];\n        if(order[5])\n            fib_dir[j+2] = -fib_dir[j+2];\n    }\n}\n\n\n\nconst char* reconstruction(ImageModel* image_model,\n                           unsigned int method_id,\n                           const float* param_values,\n                           bool check_b_table)\n{\n    static std::string output_name;\n    try\n    {\n        if(!image_model->is_human_data())\n            image_model->voxel.csf_calibration = false;\n        image_model->voxel.recon_report.clear();\n        image_model->voxel.recon_report.str(\"\");\n        image_model->voxel.param = param_values;\n        std::ostringstream out;\n        if(method_id != 4 && method_id != 7)\n            image_model->voxel.output_rdi = 0;\n        if(method_id == 1) // DTI\n        {\n            image_model->voxel.need_odf = 0;\n            image_model->voxel.output_jacobian = 0;\n            image_model->voxel.output_mapping = 0;\n            image_model->voxel.scheme_balance = 0;\n            image_model->voxel.half_sphere = 0;\n            image_model->voxel.odf_deconvolusion = 0;\n            image_model->voxel.odf_decomposition = 0;\n        }\n        else\n        {\n            out << \".odf\" << image_model->voxel.ti.fold;// odf_order\n            out << \".f\" << image_model->voxel.max_fiber_number;\n            if (image_model->voxel.need_odf)\n                out << \"rec\";\n            if (image_model->voxel.scheme_balance)\n                out << \".bal\";\n            if (image_model->voxel.half_sphere)\n                out << \".hs\";\n            if (image_model->voxel.csf_calibration &&(method_id == 4 || method_id == 7)) // GQI or QSDR\n                out << \".csfc\";\n            else\n                image_model->voxel.csf_calibration = false;\n            if (image_model->voxel.odf_deconvolusion)\n            {\n                out << \".de\" << param_values[2];\n                if(image_model->voxel.odf_xyz[0] != 0 ||\n                   image_model->voxel.odf_xyz[1] != 0 ||\n                   image_model->voxel.odf_xyz[2] != 0)\n                    out << \".at_\" << image_model->voxel.odf_xyz[0]\n                        << \"_\" << image_model->voxel.odf_xyz[1]\n                        << \"_\" << image_model->voxel.odf_xyz[2];\n            }\n            if (image_model->voxel.odf_decomposition)\n            {\n                out << \".dec\" << param_values[3] << \"m\" << (int)param_values[4];\n                if(image_model->voxel.odf_xyz[0] != 0 ||\n                   image_model->voxel.odf_xyz[1] != 0 ||\n                   image_model->voxel.odf_xyz[2] != 0)\n                    out << \".at_\" << image_model->voxel.odf_xyz[0]\n                        << \"_\" << image_model->voxel.odf_xyz[1]\n                        << \"_\" << image_model->voxel.odf_xyz[2];\n            }\n        }\n\n        // Copy SRC b-table to voxel b-table and sort it\n        image_model->voxel.load_from_src(*image_model);\n\n        // correct for b-table orientation\n        if(check_b_table)\n        {\n            set_title(\"checking b-table\");\n            bool output_dif = image_model->voxel.output_diffusivity;\n            bool output_tensor = image_model->voxel.output_tensor;\n            image_model->voxel.output_diffusivity = false;\n            image_model->voxel.output_tensor = false;\n            image_model->reconstruct<dti_process>();\n            image_model->voxel.output_diffusivity = output_dif;\n            image_model->voxel.output_tensor = output_tensor;\n            std::vector<std::vector<float> > fib_fa(1);\n            std::vector<std::vector<float> > fib_dir(1);\n            fib_fa[0].swap(image_model->voxel.fib_fa);\n            fib_dir[0].swap(image_model->voxel.fib_dir);\n\n            const unsigned char order[18][6] = {\n                                    {0,1,2,1,0,0},\n                                    {0,1,2,0,1,0},\n                                    {0,1,2,0,0,1},\n                                    {0,2,1,1,0,0},\n                                    {0,2,1,0,1,0},\n                                    {0,2,1,0,0,1},\n                                    {1,0,2,1,0,0},\n                                    {1,0,2,0,1,0},\n                                    {1,0,2,0,0,1},\n                                    {1,2,0,1,0,0},\n                                    {1,2,0,0,1,0},\n                                    {1,2,0,0,0,1},\n                                    {2,1,0,1,0,0},\n                                    {2,1,0,0,1,0},\n                                    {2,1,0,0,0,1},\n                                    {2,0,1,1,0,0},\n                                    {2,0,1,0,1,0},\n                                    {2,0,1,0,0,1}};\n            const char txt[18][6] = {\"012fx\",\"012fy\",\"012fz\",\n                                     \"021fx\",\"021fy\",\"021fz\",\n                                     \"102fx\",\"102fy\",\"102fz\",\n                                     \"120fx\",\"120fy\",\"120fz\",\n                                     \"210fx\",\"210fy\",\"210fz\",\n                                     \"201fx\",\"201fy\",\"201fz\"};\n\n            float result[18] = {0};\n            float cur_score = evaluate_fib(image_model->voxel.dim,fib_fa,fib_dir).first;\n            for(int i = 0;i < 18;++i)\n            {\n                std::vector<std::vector<float> > new_dir(fib_dir);\n                flip_fib_dir(new_dir[0],order[i]);\n                result[i] = evaluate_fib(image_model->voxel.dim,fib_fa,new_dir).first;\n            }\n            int best = std::max_element(result,result+18)-result;\n\n            if(result[best] > cur_score)\n            {\n                out << \".\" << txt[best];\n                image_model->flip_b_table(order[best]);\n                image_model->voxel.load_from_src(*image_model);\n            }\n        }\n\n\n        switch (method_id)\n        {\n        case 0: //DSI local max\n            image_model->voxel.recon_report <<\n            \" The diffusion data were reconstructed using diffusion spectrum imaging (Wedeen et al. MRM, 2005) with a Hanning filter of \" << (int)param_values[0] << \".\";\n            if (image_model->voxel.odf_deconvolusion || image_model->voxel.odf_decomposition)\n            {\n                if (!image_model->reconstruct<dsi_estimate_response_function>())\n                    return \"reconstruction canceled\";\n            }\n            out << \".dsi.\"<< (int)param_values[0] << \".fib.gz\";\n            if (!image_model->reconstruct<dsi_process>())\n                return \"reconstruction canceled\";\n            break;\n        case 1://DTI\n            image_model->voxel.recon_report << \" The diffusion tensor was calculated.\";\n            out << \".dti.fib.gz\";\n            image_model->voxel.max_fiber_number = 1;\n            if (!image_model->reconstruct<dti_process>())\n                return \"reconstruction canceled\";\n            break;\n\n        case 2://QBI\n            image_model->voxel.recon_report << \" The diffusion data was reconstructed using q-ball imaging (Tuch, MRM 2004).\";\n            if (image_model->voxel.odf_deconvolusion || image_model->voxel.odf_decomposition)\n            {\n                if (!image_model->reconstruct<qbi_estimate_response_function>())\n                    return \"reconstruction canceled\";\n            }\n            out << \".qbi.\"<< param_values[0] << \"_\" << param_values[1] << \".fib.gz\";\n            if (!image_model->reconstruct<qbi_process>())\n                return \"reconstruction canceled\";\n            break;\n        case 3://QBI\n            image_model->voxel.recon_report << \" The diffusion data was reconstructed using spherical-harmonic-based q-ball imaging (Descoteaux et al., MRM 2007).\";\n            if (image_model->voxel.odf_deconvolusion || image_model->voxel.odf_decomposition)\n            {\n                if (!image_model->reconstruct<qbi_sh_estimate_response_function>())\n                    return \"reconstruction canceled\";\n            }\n            out << \".qbi.sh\"<< (int) param_values[1] << \".\" << param_values[0] << \".fib.gz\";\n            if (!image_model->reconstruct<qbi_sh_process>())\n                return \"reconstruction canceled\";\n            break;\n\n        case 4://GQI\n            if(param_values[0] == 0.0) // spectral analysis\n            {\n                image_model->voxel.recon_report <<\n                \" The diffusion data were reconstructed using generalized q-sampling imaging (Yeh et al., IEEE TMI, ;29(9):1626-35, 2010).\";\n                out << (image_model->voxel.r2_weighted ? \".gqi2.spec.fib.gz\":\".gqi.spec.fib.gz\");\n                if (!image_model->reconstruct<gqi_spectral_process>())\n                    return \"reconstruction canceled\";\n                break;\n            }\n            image_model->voxel.recon_report <<\n            \" The diffusion data were reconstructed using generalized q-sampling imaging (Yeh et al., IEEE TMI, ;29(9):1626-35, 2010) with a diffusion sampling length ratio of \" << (float)param_values[0] << \".\";\n            if(image_model->voxel.output_rdi)\n                image_model->voxel.recon_report <<\n                    \" The restricted diffusion was quantified using restricted diffusion imaging (Yeh et al., MRM, 77:603\u2013612 (2017)).\";\n\n            if (image_model->voxel.odf_deconvolusion || image_model->voxel.odf_decomposition)\n            {\n                if (!image_model->reconstruct<gqi_estimate_response_function>())\n                    return \"reconstruction canceled\";\n            }\n            if(image_model->voxel.r2_weighted)\n                image_model->voxel.recon_report << \" The ODF calculation was weighted by the square of the diffuion displacement.\";\n            if (image_model->voxel.output_rdi)\n                out << \".rdi\";\n            out << (image_model->voxel.r2_weighted ? \".gqi2.\":\".gqi.\") << param_values[0] << \".fib.gz\";\n            if(image_model->src_dwi_data.size() == 1)\n            {\n                if (!image_model->reconstruct<hgqi_process>())\n                    return \"reconstruction canceled\";\n                break;\n            }\n\n            if (!image_model->reconstruct<gqi_process>())\n                return \"reconstruction canceled\";\n            break;\n        case 6:\n            image_model->voxel.recon_report\n                    << \" The diffusion data were converted to HARDI using generalized q-sampling method with a regularization parameter of \" << param_values[2] << \".\";\n            out << \".hardi.\"<< param_values[0]\n                << \".b\" << param_values[1]\n                << \".reg\" << param_values[2] << \".src.gz\";\n            if (!image_model->reconstruct<hardi_convert_process>())\n                return \"reconstruction canceled\";\n            break;\n        case 7:\n\n            if(image_model->voxel.reg_method == 4) // DMDM\n            {\n                {\n                    gz_nifti in;\n                    if(!in.load_from_file(t1w_template_file_name.c_str()) || !in.toLPS(image_model->voxel.t1wt))\n                        return \"Cannot load T1W template\";\n                    in.get_voxel_size(image_model->voxel.t1wt_vs.begin());\n                    in.get_image_transformation(image_model->voxel.t1wt_tran);\n                }\n                {\n                    gz_nifti in;\n                    if(!in.load_from_file(image_model->voxel.t1w_file_name.c_str()) || !in.toLPS(image_model->voxel.t1w))\n                        return \"Cannot load T1W for DMDM normaliztion\";\n                    in.get_voxel_size(image_model->voxel.t1w_vs.begin());\n                }\n            }\n\n\n            image_model->voxel.recon_report\n            << \" The diffusion data were reconstructed in the MNI space using q-space diffeomorphic reconstruction (Yeh et al., Neuroimage, 58(1):91-9, 2011) to obtain the spin distribution function (Yeh et al., IEEE TMI, ;29(9):1626-35, 2010). \"\n            << \" A diffusion sampling length ratio of \"\n            << (float)param_values[0] << \" was used, and the output resolution was \" << param_values[1] << \" mm.\";\n            // run gqi to get the spin quantity\n\n            if(image_model->voxel.output_rdi)\n                image_model->voxel.recon_report <<\n                    \" The restricted diffusion was quantified using restricted diffusion imaging (Yeh et al., MRM, 77:603\u2013612 (2017)).\";\n\n            {\n                std::vector<image::pointer_image<float,3> > tmp;\n                tmp.swap(image_model->voxel.grad_dev);\n                // clear mask to create whole volume QA map\n                std::fill(image_model->voxel.mask.begin(),image_model->voxel.mask.end(),1.0);\n                if (!image_model->reconstruct<gqi_estimate_response_function>())\n                    return \"reconstruction canceled\";\n                tmp.swap(image_model->voxel.grad_dev);\n            }\n\n            if(image_model->voxel.reg_method < 4) // 0,1,2 SPM norm, 3 CDM, 4 CDM-T1W\n            {\n                if(image_model->voxel.reg_method == 3)\n                    out << \".cdm\";\n                else\n                    out << \".reg\" << (int)image_model->voxel.reg_method;\n            }\n            else\n                out << \".cdmt1w\";\n\n\n            out << (image_model->voxel.r2_weighted ? \".qsdr2.\":\".qsdr.\");\n            out << param_values[0] << \".\" << param_values[1] << \"mm\";\n            if(image_model->voxel.output_jacobian)\n                out << \".jac\";\n            if(image_model->voxel.output_mapping)\n                out << \".map\";\n            if (!image_model->reconstruct<gqi_mni_process>())\n                return \"reconstruction canceled\";\n            out << \".R\" << (int)std::floor(image_model->voxel.R2*100.0) << \".fib.gz\";\n            break;\n        }\n        image_model->save_fib(out.str());\n        output_name = image_model->file_name + out.str();\n    }\n    catch (std::exception& e)\n    {\n        output_name = e.what();\n        return output_name.c_str();\n    }\n    catch (...)\n    {\n        return \"unknown exception\";\n    }\n    return output_name.c_str();\n}\n\n\nbool output_odfs(const image::basic_image<unsigned char,3>& mni_mask,\n                 const char* out_name,\n                 const char* ext,\n                 std::vector<std::vector<float> >& odfs,\n                 const tessellated_icosahedron& ti,\n                 const float* vs,\n                 const float* mni,\n                 const std::string& report,\n                 bool record_odf = true)\n{\n    begin_prog(\"output\");\n    ImageModel image_model;\n    if(report.length())\n        image_model.voxel.report = report.c_str();\n    image_model.voxel.dim = mni_mask.geometry();\n    image_model.voxel.ti = ti;\n    image_model.voxel.max_fiber_number = 5;\n    image_model.voxel.need_odf = record_odf;\n    image_model.voxel.template_odfs.swap(odfs);\n    image_model.voxel.param = mni;\n    image_model.file_name = out_name;\n    image_model.voxel.mask = mni_mask;\n    std::copy(vs,vs+3,image_model.voxel.vs.begin());\n    if (prog_aborted() || !image_model.reconstruct<reprocess_odf>())\n        return false;\n    image_model.save_fib(ext);\n    image_model.voxel.template_odfs.swap(odfs);\n    return true;\n}\n\n\nconst char* odf_average(const char* out_name,std::vector<std::string>& file_names)\n{\n    static std::string error_msg,report;\n    tessellated_icosahedron ti;\n    float vs[3];\n    image::basic_image<unsigned char,3> mask;\n    std::vector<std::vector<float> > odfs;\n    unsigned int half_vertex_count = 0;\n    unsigned int row,col;\n    float mni[16]={0};\n    begin_prog(\"averaging\");\n    for (unsigned int index = 0;check_prog(index,file_names.size());++index)\n    {\n        const char* file_name = file_names[index].c_str();\n        gz_mat_read reader;\n        set_title(file_names[index].c_str());\n        if(!reader.load_from_file(file_name))\n        {\n            error_msg = \"Cannot open file \";\n            error_msg += file_name;\n            check_prog(0,0);\n            return error_msg.c_str();\n        }\n        if(index == 0)\n        {\n            {\n                const char* report_buf = 0;\n                if(reader.read(\"report\",row,col,report_buf))\n                    report = std::string(report_buf,report_buf+row*col);\n            }\n            const float* odf_buffer;\n            const short* face_buffer;\n            const unsigned short* dimension;\n            const float* vs_ptr;\n            const float* fa0;\n            const float* mni_ptr;\n            unsigned int face_num,odf_num;\n            error_msg = \"\";\n            if(!reader.read(\"dimension\",row,col,dimension))\n                error_msg = \"dimension\";\n            if(!reader.read(\"fa0\",row,col,fa0))\n                error_msg = \"fa0\";\n            if(!reader.read(\"voxel_size\",row,col,vs_ptr))\n                error_msg = \"voxel_size\";\n            if(!reader.read(\"odf_faces\",row,face_num,face_buffer))\n                error_msg = \"odf_faces\";\n            if(!reader.read(\"odf_vertices\",row,odf_num,odf_buffer))\n                error_msg = \"odf_vertices\";\n            if(!reader.read(\"trans\",row,col,mni_ptr))\n                error_msg = \"trans\";\n            if(error_msg.length())\n            {\n                error_msg += \" missing in \";\n                error_msg += file_name;\n                check_prog(0,0);\n                return error_msg.c_str();\n            }\n            mask.resize(image::geometry<3>(dimension));\n            for(unsigned int index = 0;index < mask.size();++index)\n                if(fa0[index] != 0.0)\n                    mask[index] = 1;\n            std::copy(vs_ptr,vs_ptr+3,vs);\n            ti.init(odf_num,odf_buffer,face_num,face_buffer);\n            half_vertex_count = odf_num >> 1;\n            std::copy(mni_ptr,mni_ptr+16,mni);\n        }\n        else\n        // check odf consistency\n        {\n            const float* odf_buffer;\n            const unsigned short* dimension;\n            unsigned int odf_num;\n            error_msg = \"\";\n            if(!reader.read(\"dimension\",row,col,dimension))\n                error_msg = \"dimension\";\n            if(!reader.read(\"odf_vertices\",row,odf_num,odf_buffer))\n                error_msg = \"odf_vertices\";\n            if(error_msg.length())\n            {\n                error_msg += \" missing in \";\n                error_msg += file_name;\n                check_prog(0,0);\n                return error_msg.c_str();\n            }\n\n            if(odf_num != ti.vertices_count || dimension[0] != mask.width() ||\n                    dimension[1] != mask.height() || dimension[2] != mask.depth())\n            {\n                error_msg = \"Inconsistent dimension in \";\n                error_msg += file_name;\n                check_prog(0,0);\n                return error_msg.c_str();\n            }\n            for (unsigned int index = 0;index < col;++index,odf_buffer += 3)\n            {\n                if(ti.vertices[index][0] != odf_buffer[0] ||\n                   ti.vertices[index][1] != odf_buffer[1] ||\n                   ti.vertices[index][2] != odf_buffer[2])\n                {\n                    error_msg = \"Inconsistent ODF orientations in \";\n                    error_msg += file_name;\n                    return error_msg.c_str();\n                }\n            }\n        }\n\n        {\n            const float* fa0;\n            if(!reader.read(\"fa0\",row,col,fa0))\n            {\n                error_msg = \"Cannot find image information in \";\n                error_msg += file_name;\n                check_prog(0,0);\n                return error_msg.c_str();\n            }\n            for(unsigned int index = 0;index < mask.size();++index)\n                if(fa0[index] != 0.0)\n                    mask[index] = 1;\n        }\n\n        std::vector<const float*> odf_bufs;\n        std::vector<unsigned int> odf_bufs_size;\n        //get_odf_bufs(reader,odf_bufs,odf_bufs_size);\n        {\n            odf_bufs.clear();\n            odf_bufs_size.clear();\n            for (unsigned int odf_index = 0;1;++odf_index)\n            {\n                std::ostringstream out;\n                out << \"odf\" << odf_index;\n                const float* odf_buf = 0;\n                if (!reader.read(out.str().c_str(),row,col,odf_buf))\n                    break;\n                odf_bufs.push_back(odf_buf);\n                odf_bufs_size.push_back(row*col);\n            }\n        }\n        if(odf_bufs.empty())\n        {\n            error_msg += \"No ODF data found in \";\n            error_msg += file_name;\n            check_prog(0,0);\n            return error_msg.c_str();\n        }\n        if(index == 0)\n        {\n            odfs.resize(odf_bufs.size());\n            for(unsigned int i = 0;i < odf_bufs.size();++i)\n                odfs[i].resize(odf_bufs_size[i]);\n        }\n        else\n        {\n            bool inconsistence = false;\n            if(odfs.size() != odf_bufs.size())\n                inconsistence = true;\n            for(unsigned int i = 0;i < odf_bufs.size();++i)\n                if(odfs[i].size() != odf_bufs_size[i])\n                    inconsistence = true;\n            if(inconsistence)\n            {\n                error_msg = \"Inconsistent mask coverage in \";\n                error_msg += file_name;\n                check_prog(0,0);\n                return error_msg.c_str();\n            }\n        }\n        for(unsigned int i = 0;i < odf_bufs.size();++i)\n            image::add(odfs[i].begin(),odfs[i].end(),odf_bufs[i]);\n    }\n    if (prog_aborted())\n        return 0;\n\n    set_title(\"averaging odfs\");\n    for (unsigned int odf_index = 0;odf_index < odfs.size();++odf_index)\n        for (unsigned int j = 0;j < odfs[odf_index].size();++j)\n            odfs[odf_index][j] /= (double)file_names.size();\n\n    std::ostringstream out;\n    out << \"A group average template was constructed from a total of \" << file_names.size() << \" subjects.\" << report.c_str();\n    report = out.str();\n    set_title(\"output files\");\n    output_odfs(mask,out_name,\".mean.odf.fib.gz\",odfs,ti,vs,mni,report);\n    output_odfs(mask,out_name,\".mean.fib.gz\",odfs,ti,vs,mni,report,false);\n    return 0;\n}\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "15a4cc9f7adb2a0ed171474474d8e28a5aa54ceb", "size": 28889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/dsi/dsi_interface_imp.cpp", "max_stars_repo_name": "cbutakoff/DSI-Studio", "max_stars_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "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/dsi/dsi_interface_imp.cpp", "max_issues_repo_name": "cbutakoff/DSI-Studio", "max_issues_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "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/dsi/dsi_interface_imp.cpp", "max_forks_repo_name": "cbutakoff/DSI-Studio", "max_forks_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "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.7633986928, "max_line_length": 246, "alphanum_fraction": 0.537921008, "num_tokens": 7140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.19122011876909253}}
{"text": "\ufeff#include <controller_interface/controller.h>\n#include <hardware_interface/joint_command_interface.h>\n#include <control_toolbox/pid.h>\n#include <realtime_tools/realtime_buffer.h>\n\n#include <pluginlib/class_list_macros.h>\n\n#include \"std_msgs/MultiArrayLayout.h\"\n#include \"std_msgs/MultiArrayDimension.h\"\n\n#include <std_msgs/Float64MultiArray.h>\n#include <angles/angles.h>\n#include <geometry_msgs/WrenchStamped.h>\n\n#include <urdf/model.h>\n\n#include <kdl/tree.hpp>\n#include <kdl/kdl.hpp>\n#include <kdl/chain.hpp>\n#include <kdl/chaindynparam.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n#include <kdl/chainiksolvervel_pinv.hpp>\n#include <kdl/chainiksolverpos_nr_jl.hpp>\n#include <kdl_parser/kdl_parser.hpp>\n#include <tf_conversions/tf_kdl.h>\n\n#include <boost/scoped_ptr.hpp>\n\n// from computed torque clik\n#include <boost/lexical_cast.hpp>\n//\n#include <math.h>\n#include <Eigen/LU>\n#include <utils/pseudo_inversion.h>\n#include <utils/skew_symmetric.h>\n\n//#define SaveDataMax 97\n#define num_taskspace 6\n#define A 0.1\n#define b 2.5\n#define f 1\n#define t_set 1\n\n#include <string>\n#include <iostream>\n//\n\n\n\n#define PI 3.141592\n#define D2R PI/180.0\n#define R2D 180.0/PI\n#define JointMax 6\n#define SaveDataMax 7\n\nnamespace arm_controllers{\n\nclass AdmittanceController: public controller_interface::Controller<hardware_interface::EffortJointInterface>\n{\npublic:\n    ~AdmittanceController() {sub_q_cmd_.shutdown(); sub_forcetorque_sensor_.shutdown();}\n\n    bool init(hardware_interface::EffortJointInterface* hw, ros::NodeHandle &n)\n    {\n        // List of controlled joints\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\n        // urdf\n        urdf::Model urdf;\n        if (!urdf.initParam(\"elfin/robot_description\"))\n        {\n            ROS_ERROR(\"Failed to parse urdf file\");\n            return false;\n        }\n\n        // joint handle\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        // kdl parser\n        if (!kdl_parser::treeFromUrdfModel(urdf, kdl_tree_)){\n            ROS_ERROR(\"Failed to construct kdl tree\");\n            return false;\n        }\n\n        // 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\n        gravity_ = KDL::Vector::Zero();\n        gravity_(2) = -9.81;\n        G_.resize(n_joints_);\n\n        // inverse dynamics solver\n        id_solver_.reset( new KDL::ChainDynParam(kdl_chain_, gravity_) );\n        fk_solver_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_));\n        ik_vel_solver_.reset(new KDL::ChainIkSolverVel_pinv(kdl_chain_));\n        //ik_pos_solver_.reset(new KDL::ChainIkSolverPos_NR_JL(kdl_chain_, fk_solver_, ik_vel_solver_));\n\n        // command and state\n        tau_cmd_.data = Eigen::VectorXd::Zero(n_joints_);\n        tau_cmd_old_.data = Eigen::VectorXd::Zero(n_joints_);\n        q_cmd_sp_.data = Eigen::VectorXd::Zero(n_joints_);\n        q_cmd_.data = Eigen::VectorXd::Zero(n_joints_);\n        q_cmd_old_.data = Eigen::VectorXd::Zero(n_joints_);\n        qdot_cmd_.data = Eigen::VectorXd::Zero(n_joints_);\n        qdot_cmd_old_.data = Eigen::VectorXd::Zero(n_joints_);\n        qddot_cmd_.data = Eigen::VectorXd::Zero(n_joints_);\n        q_cmd_end_.data = Eigen::VectorXd::Zero(n_joints_);\n\n        q_.data = Eigen::VectorXd::Zero(n_joints_);\n        q_init_.data = Eigen::VectorXd::Zero(n_joints_);\n        qdot_.data = Eigen::VectorXd::Zero(n_joints_);\n        qdot_old_.data = Eigen::VectorXd::Zero(n_joints_);\n        qddot_.data = Eigen::VectorXd::Zero(n_joints_);\n\n        for (size_t i = 0; i < 6; i++)\n        {\n            Xc_dot_(i) = 0.0;\n            Xc_dot_old_(i) = 0.0;\n            Xc_ddot_(i) = 0.0;\n        }\n\n        // gains\n        Mbar_.resize(n_joints_);\n        Mbar_dot_.resize(n_joints_);\n        Ramda_.resize(n_joints_);\n        Alpha_.resize(n_joints_);\n        Omega_.resize(n_joints_);\n\n        Xr_dot_ = 0.0;\n        Xe_dot_ = 0.0;\n        Xe_ddot_ = 0.0;\n        Fd_ = 0.0;\n        Fd_temp_ = 0.0;\n        Fd_old_ = 0.0;\n        Fe_ = 0.0;\n        Fe_old_ = 0.0;\n        M_ = 0.0;\n        B_ = 0.0;\n        del_B_ = 0.0;\n        B_buffer_ = 0.0;\n        PI_ = 0.0;\n        PI_old_ = 0.0;\n\n        filt_old_ = 0.0;\n        filt_ = 0.0;\n        tau_ = 1.0/(2*PI*9.0);\n\n        f_cur_buffer_ = 0.0;\n\n        experiment_mode_ = 0;\n\n        std::vector<double> Mbar(n_joints_), Ramda(n_joints_), Alpha(n_joints_), Omega(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/admittance_controller/joint\" + si + \"/tdc/mbar\", Mbar[i]) )\n            {\n                Mbar_(i) = Mbar[i];\n            }\n            else\n            {\n                std::cout << \"/elfin/admittance_controller/joint\" + si + \"/tdc/mbar\" << std::endl;\n                ROS_ERROR(\"Cannot find tdc/mbar gain\");\n                return false;\n            }\n\n            if ( n.getParam(\"/elfin/admittance_controller/joint\" + si + \"/tdc/r\", Ramda[i]) )\n            {\n                Ramda_(i) = Ramda[i];\n            }\n            else\n            {\n                ROS_ERROR(\"Cannot find tdc/r gain\");\n                return false;\n            }\n\n            if ( n.getParam(\"/elfin/admittance_controller/joint\" + si + \"/tdc/a\", Alpha[i]) )\n            {\n                Alpha_(i) = Alpha[i];\n            }\n            else\n            {\n                ROS_ERROR(\"Cannot find tdc/a gain\");\n                return false;\n            }\n\n            if ( n.getParam(\"/elfin/admittance_controller/joint\" + si + \"/tdc/w\", Omega[i]) )\n            {\n                Omega_(i) = Omega[i];\n            }\n            else\n            {\n                ROS_ERROR(\"Cannot find tdc/w gain\");\n                return false;\n            }\n        }\n\n        if (!n.getParam(\"/elfin/admittance_controller/aic/fd\", Fd_temp_))\n        {\n            ROS_ERROR(\"Cannot find aci/fd\");\n            return false;\n        }\n\n        if (!n.getParam(\"/elfin/admittance_controller/aic/m\", M_))\n        {\n            ROS_ERROR(\"Cannot find aci/m\");\n            return false;\n        }\n\n        if (!n.getParam(\"/elfin/admittance_controller/aic/b\", B_))\n        {\n            ROS_ERROR(\"Cannot find aci/b\");\n            return false;\n        }\n\n        if (!n.getParam(\"/elfin/admittance_controller/mode\", experiment_mode_))\n        {\n            ROS_ERROR(\"Cannot find mode\");\n            return false;\n        }\n\n        // command\n        sub_q_cmd_ = n.subscribe(\"command\", 1, &AdmittanceController::commandCB, this);\n        sub_forcetorque_sensor_ = n.subscribe<geometry_msgs::WrenchStamped>(\"/elfin/elfin/ft_sensor_topic\", 1, &AdmittanceController::updateFTsensor, this);\n\n        pub_SaveData_ = n.advertise<std_msgs::Float64MultiArray>(\"SaveData\", 1000);\n\n\n        // ---------------------from Control clik-------------\n\n        // ********* 1.  joint name / gain from the parameter server *********\n        // 1.0 Control objective & Inverse Kinematics mode\n        if (!n.getParam(\"ctr_obj\", cctr_obj_))\n        {\n            ROS_ERROR(\"Could not find control objective\");\n            return false;\n        }\n\n        if (!n.getParam(\"ik_mode\", iik_mode_))\n        {\n            ROS_ERROR(\"Could not find control objective\");\n            return false;\n        }\n\n        // 1.1 Joint Name\n        if (!n.getParam(\"joints\", jjoint_names_))\n        {\n            ROS_ERROR(\"Could not find joint name\");\n            return false;\n        }\n\n        // had to subtract 1 manually. Sorry!\n        nn_joints_ = jjoint_names_.size()-1;\n\n        if (nn_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\", nn_joints_);\n            for (int i = 0; i < nn_joints_; i++)\n            {\n                ROS_INFO(\"%s\", jjoint_names_[i].c_str());\n            }\n        }\n\n        // 1.2 Gain\n        // 1.2.1 Joint Controller\n        KKp_.resize(nn_joints_);\n        KKd_.resize(nn_joints_);\n        KKi_.resize(nn_joints_);\n\n        std::vector<double> KKp(nn_joints_), KKi(nn_joints_), KKd(nn_joints_);\n\n        for (size_t i = 0; i < nn_joints_; i++)\n        {\n            ROS_INFO(\"%d\",i);\n            std::string si = boost::lexical_cast<std::string>(i + 1);\n            if (n.getParam(\"/elfin/admittance_controller/gains/elfin_joint\" + si + \"/pid/p\", KKp[i]))\n            {\n                KKp_(i) = KKp[i];\n            }\n            else\n            {\n                std::cout << \"/elfin/admittance_controller/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/admittance_controller/gains/elfin_joint\" + si + \"/pid/i\", KKi[i]))\n            {\n                KKi_(i) = KKi[i];\n            }\n            else\n            {\n                ROS_ERROR(\"Cannot find pid/i gain\");\n                return false;\n            }\n\n            if (n.getParam(\"/elfin/admittance_controller/gains/elfin_joint\" + si + \"/pid/d\", KKd[i]))\n            {\n                KKd_(i) = KKd[i];\n            }\n            else\n            {\n                ROS_ERROR(\"Cannot find pid/d gain\");\n                return false;\n            }\n        }\n\n        // 1.2.2 Closed-loop Inverse Kinematics Controller\n        if (cctr_obj_ == 1)\n        {\n            if (!n.getParam(\"/elfin/admittance_controller/clik_gain/K_regulation\", KK_regulation_))\n            {\n                ROS_ERROR(\"Cannot find clik regulation gain\");\n                return false;\n            }\n        }\n\n        else if (cctr_obj_ == 2)\n        {\n            if (!n.getParam(\"/elfin/admittance_controller/clik_gain/K_tracking\", KK_tracking_))\n            {\n                ROS_ERROR(\"Cannot find clik tracking gain\");\n                return false;\n            }\n        }\n        /*\n        // 2. ********* urdf *********\n        urdf::Model uurdf;\n        if (!uurdf.initParam(\"elfin/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 < nn_joints_; i++)\n        {\n            try\n            {\n                jjoints_.push_back(hw->getHandle(jjoint_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 jjoint_urdf = urdf.getJoint(jjoint_names_[i]);\n            if (!jjoint_urdf)\n            {\n                ROS_ERROR(\"Could not find joint '%s' in urdf\", jjoint_names_[i].c_str());\n                return false;\n            }\n            jjoint_urdfs_.push_back(jjoint_urdf);\n        }\n\n        // 4. ********* KDL *********\n        // 4.1 kdl parser\n        if (!kdl_parser::treeFromUrdfModel(urdf, kkdl_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 rroot_name, ttip_name;\n\n        rroot_name=\"world\";\n        ttip_name=\"elfin_link6\";\n\n        /*\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        */\n\n        if (!kdl_tree_.getChain(rroot_name, ttip_name, kkdl_chain_))\n        {\n            ROS_ERROR_STREAM(\"Failed to get KDL chain from tree: \");\n            ROS_ERROR_STREAM(\"  \" << rroot_name << \" --> \" << ttip_name);\n            ROS_ERROR_STREAM(\"  Tree has \" << kkdl_tree_.getNrOfJoints() << \" joints\");\n            ROS_ERROR_STREAM(\"  Tree has \" << kkdl_tree_.getNrOfSegments() << \" segments\");\n            ROS_ERROR_STREAM(\"  The segments are:\");\n\n            KDL::SegmentMap ssegment_map = kkdl_tree_.getSegments();\n            KDL::SegmentMap::iterator it;\n\n            for (it = ssegment_map.begin(); it != ssegment_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 \ucd08\uae30\ud654\n        ggravity_ = KDL::Vector::Zero();\n        ggravity_(2) = -9.81; // 0: x-axis 1: y-axis 2: z-axis\n\n        iid_solver_.reset(new KDL::ChainDynParam(kkdl_chain_, gravity_));\n\n        // 4.4 jacobian solver \ucd08\uae30\ud654\n        jjnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(kkdl_chain_));\n\n        // 4.5 forward kinematics solver \ucd08\uae30\ud654\n        ffk_pos_solver_.reset(new KDL::ChainFkSolverPos_recursive(kkdl_chain_));\n\n        // ********* 5. \uac01\uc885 \ubcc0\uc218 \ucd08\uae30\ud654 *********\n\n        // 5.1 KDL Vector \ucd08\uae30\ud654 (\uc0ac\uc774\uc988 \uc815\uc758 \ubc0f \uac12 0)\n        ttau_d_.data = Eigen::VectorXd::Zero(nn_joints_);\n        xx_cmd_.data = Eigen::VectorXd::Zero(num_taskspace);\n\n        qqd_.data = Eigen::VectorXd::Zero(nn_joints_);\n        qqd_dot_.data = Eigen::VectorXd::Zero(nn_joints_);\n        qqd_ddot_.data = Eigen::VectorXd::Zero(nn_joints_);\n        qqd_old_.data = Eigen::VectorXd::Zero(nn_joints_);\n\n        qq_.data = Eigen::VectorXd::Zero(nn_joints_);\n        qqdot_.data = Eigen::VectorXd::Zero(nn_joints_);\n\n        ee_.data = Eigen::VectorXd::Zero(nn_joints_);\n        ee_dot_.data = Eigen::VectorXd::Zero(nn_joints_);\n        ee_int_.data = Eigen::VectorXd::Zero(nn_joints_);\n\n\n        // 5.2 KDL Matrix \ucd08\uae30\ud654 (\uc0ac\uc774\uc988 \uc815\uc758 \ubc0f \uac12 0)\n        JJ_.resize(nn_joints_);\n        // J_inv_.resize(kdl_chain_.getNrOfJoints());\n        MM_.resize(nn_joints_);\n        CC_.resize(nn_joints_);\n        GG_.resize(nn_joints_);\n\n        // ********* 6. ROS \uba85\ub839\uc5b4 *********\n        // 6.1 publisher\n        ppub_qd_ = n.advertise<std_msgs::Float64MultiArray>(\"qd\", 1000);\n        ppub_q_ = n.advertise<std_msgs::Float64MultiArray>(\"q\", 1000);\n        ppub_e_ = n.advertise<std_msgs::Float64MultiArray>(\"e\", 1000);\n\n        ppub_xd_ = n.advertise<std_msgs::Float64MultiArray>(\"xd\", 1000);\n        ppub_x_ = n.advertise<std_msgs::Float64MultiArray>(\"x\", 1000);\n        ppub_ex_ = n.advertise<std_msgs::Float64MultiArray>(\"ex\", 1000);\n\n        ppub_SaveData_ = n.advertise<std_msgs::Float64MultiArray>(\"SaveData\", 1000); // \ub4a4\uc5d0 \uc22b\uc790\ub294?\n\n        // 6.2 subsriber\n        //ssub_x_cmd_ = n.subscribe<std_msgs::Float64MultiArray>(\"command\", 1, &Computed_Torque_Controller_CLIK::commandCB, this);\n        eevent = 0; // subscribe \ubc1b\uae30 \uc804: 0\n        // subscribe \ubc1b\uc740 \ud6c4: 1\n\n\n        mmsg_x_.layout.dim.push_back(std_msgs::MultiArrayDimension());\n\n\n        mmsg_x_.data.resize(6);\n\n\n        for(int i=0;i<6;i++){\n            mmsg_x_.data[i]=0;\n        }\n\n        k_stiff_damp_sub = n.subscribe<std_msgs::Float64MultiArray>(\"admittance_gains\", 1, &AdmittanceController::admit_gains, this);\n\n        // admittance params\n        z=0;\n        zdot=0;\n        zddot=0;\n        z_pre=0;\n        zdot_pre=0;\n        zddot_pre=0;\n        K_damp=20;\n        K_stiff=50;\n        M_ad=5;\n\n        publisher_ = n.advertise<std_msgs::Float64MultiArray>(\"publish_admittance\", 1000);\n\n        msg_temp.data.resize(6);\n\n        for(int i=0;i<6;i++){\n            msg_temp.data[i]=0;\n        }\n        return true;\n    } // end of initialize\n\n\n    void admit_gains(const std_msgs::Float64MultiArrayConstPtr &msg)\n    {\n        K_stiff = msg->data[0];\n        K_damp  = msg->data[1];\n        M_ad= msg->data[2];\n    }\n\n    void starting(const ros::Time& time)\n    {\n        // get joint positions\n        for(size_t i=0; i<n_joints_; i++)\n        {\n            ROS_INFO(\"JOINT %d\", (int)i);\n            q_(i) = joints_[i].getPosition();\n            q_init_(i) = q_(i);\n            qdot_(i) = joints_[i].getVelocity();\n        }\n\n        time_ = 0.0;\n        total_time_ = 0.0;\n\n        ROS_INFO(\"Starting Adaptive Impedance Controller\");\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        for (unsigned int i = 0; i<n_joints_; i++)\n            q_cmd_sp_(i) = msg->data[i];\n    }\n\n    //void updateFTsensor(const geometry_msgs::WrenchStamped::ConstPtr &msg)\n    void updateFTsensor(const geometry_msgs::WrenchStamped::ConstPtr &msg)\n    {\n        // Convert Wrench msg to KDL wrench\n        geometry_msgs::Wrench f_meas = msg->wrench;\n\n        f_cur_[0] = f_meas.force.x;\n        f_cur_buffer_ = f_meas.force.y;\n        f_cur_[2] = f_meas.force.z;\n        f_cur_[3] = f_meas.torque.x;\n        f_cur_[4] = f_meas.torque.y;\n        f_cur_[5] = f_meas.torque.z;\n\n        if (experiment_mode_ == 1 || experiment_mode_ == 2)\n            f_cur_[1] = first_order_lowpass_filter();\n    }\n\n    // load gain is not permitted during controller loading?\n    void loadGainCB()\n    {\n\n    }\n\n    void update(const ros::Time& time, const ros::Duration& period)\n    {\n        //---------------------\n\n        // ********* 0. Get states from gazebo *********\n        // 0.1 sampling time\n        double ddt = period.toSec();\n        tt = tt + 0.001;\n\n        //----------------------------\n\n        // simple trajectory interpolation from joint command setpoint\n        dt_ = period.toSec();\n\n        if(total_time_ < 5.0)\n        {\n            task_init();\n        }\n        else if(total_time_ >= 5.0 && total_time_ < 6.0)\n        {\n            task_via();\n        }\n        else if(total_time_ >= 6.0 && total_time_ < 16.0)\n        {\n            task_ready();\n        }\n        else if (total_time_ >= 16.0 && total_time_ < 17.0)\n        {\n            task_via();\n        }\n        else if (total_time_ >= 17.0 && total_time_ < 27.0)\n        {\n            task_freespace();\n        }\n        else if (total_time_ >= 27.0 && total_time_ < 28.0)\n        {\n            task_via();\n            //        }\n            //        else if (total_time_ >= 28.0 && total_time_ < 48.0)\n            //        {\n            //            //task_contactspace();\n        }\n        else if (total_time_ >= 48.0 && total_time_ < 49.0)\n        {\n            task_via();\n        }\n        else if (total_time_ >= 49.0 && total_time_ < 59.0)\n        {\n            task_homming();\n        }\n\n        // get joint states\n        for (size_t i=0; i<n_joints_; i++)\n        {\n            q_(i) = joints_[i].getPosition();\n            qdot_(i) = joints_[i].getVelocity();\n        }\n\n\n        //fk_solver_->JntToCart(qq_, xx_);\n\n        for (size_t i=0; i<nn_joints_; i++)\n        {\n            qq_(i) = jjoints_[i].getPosition();\n            qqdot_(i) = jjoints_[i].getVelocity();\n        }\n\n        // 0.3 end-effector state by Compute forward kinematics\n        ffk_pos_solver_->JntToCart(qq_, xx_);\n\n        for(int i=0 ; i<3; i++){\n            mmsg_x_.data[i]=xx_.p(i);\n        }\n\n        ppub_x_.publish(mmsg_x_);\n\n        //        if (total_time_ >= 28.0 && total_time_ < 48.0)\n        if (total_time_ >= 28.0)\n        {\n\n            if (flag!=2)\n            {\n                xxd_= xx_;\n                xx=xx_.p(0)-0.02;\n                //yy=xx_.p(1);\n                zz=xx_.p(2)-0.05;\n\n                xxd_dot_(0) = 0;\n                xxd_dot_(1) = 0;\n                xxd_dot_(2) = 0;\n                xxd_dot_(3) = 0;\n                xxd_dot_(4) = 0;\n                xxd_dot_(5) = 0;\n\n                xxd_.p(2)=zz;\n\n                flag = 2;\n            }\n\n\n\n            double amp=0.18;\n            double ttt=(total_time_-28)/30;\n            ttt=ttt-floor(ttt);\n            xxd_.p(0) = xx+amp*sin(PI*ttt);\n\n            //xxd_dot_(0) = amp*PI*cos(PI*ttt);\n            //xxd_ddot_(0)=-1*amp*PI*PI*sin(PI*ttt);\n\n\n            // ADMITTACE CONTROL IMPLEMENTATION***********************************************************\n\n            double F =abs(f_cur_[1]);\n            //double F =f_cur_[1];\n\n            zddot= (F-K_damp*zdot_pre-K_stiff*z_pre)/M_ad;\n            zdot=zdot_pre+zddot*ddt;\n            z=z_pre+zdot*ddt;\n            z_pre=z;\n            zdot_pre=zdot;\n\n           xxd_.p(2) = zz+z;\n           xxd_dot_(2)=0+zdot;\n           xxd_ddot_(2)=0+zddot;\n\n\n            // publisher    *************************************\n            msg_temp.data[0]=zz;\n            msg_temp.data[1]=zdot;\n            msg_temp.data[2]=zddot;\n            msg_temp.data[3]=xxd_.p(2);\n            msg_temp.data[4]=F;\n            msg_temp.data[5]=total_time_;\n\n            publisher_.publish(msg_temp);\n\n\n            // ********* 2. Inverse Kinematics *********\n            // *** 2.0 Error Definition in Task Space ***\n            eex_temp_ = diff(xx_, xxd_);\n            eex_(0) = eex_temp_(0);\n            eex_(1) = eex_temp_(1);\n            eex_(2) = eex_temp_(2);\n            eex_(3) = eex_temp_(3);\n            eex_(4) = eex_temp_(4);\n            eex_(5) = eex_temp_(5);\n\n            // *** 2.1 computing Jacobian J(q) ***\n            jjnt_to_jac_solver_->JntToJac(qq_, JJ_);\n\n            xxdot_ = JJ_.data * qqdot_.data;\n            eex_dot_ = xxd_dot_ - xxdot_;\n\n            // *** 2.1 computing Jacobian J(q) ***\n            jjnt_to_jac_solver_->JntToJac(qq_, JJ_);\n\n            // *** 2.2 computing Jacobian transpose/inversion ***\n            JJ_transpose_ = JJ_.data.transpose();\n            JJ_inv_ = JJ_.data.inverse();\n\n            if (tt < t_set)\n            {\n                qqd_.data = qqd_old_.data;\n            }\n            else\n            {\n                qqd_.data = qqd_old_.data + JJ_transpose_ * KK_regulation_ * eex_ * ddt;\n                qqd_old_.data = qqd_.data;\n            }\n\n\n            // ********* 3. Motion Controller in Joint Space*********\n            // *** 3.1 Error Definition in Joint Space ***\n            ee_.data = qqd_.data - qq_.data;\n            ee_dot_.data = qqd_dot_.data - qqdot_.data;\n            ee_int_.data = qqd_.data - qq_.data; // (To do: e_int \uc5c5\ub370\uc774\ud2b8 \ud544\uc694\uc694 (Update required))\n\n\n            // *** 3.2 Compute model(M,C,G) ***\n            iid_solver_->JntToMass(qq_, MM_);\n            iid_solver_->JntToCoriolis(qq_, qqdot_, CC_);\n            iid_solver_->JntToGravity(qq_, GG_); // output\uc740 \uba38\uc9c0? , id_solver\ub294 \uc5b4\ub514\uc5d0\uc11c?\n\n            // *** 3.3 Apply Torque Command to Actuator ***\n\n            aaux_d_.data =MM_.data*(JJ_inv_*(xxd_ddot_ + KKd_.data.cwiseProduct(eex_dot_)+KKp_.data.cwiseProduct(eex_)));\n\n\n            //aaux_d_.data = MM_.data * (qqd_ddot_.data + KKp_.data.cwiseProduct(ee_.data) + KKd_.data.cwiseProduct(ee_dot_.data));\n            ccomp_d_.data = CC_.data + GG_.data; //(n(q,q_dot))\n            ttau_d_.data = aaux_d_.data + ccomp_d_.data;\n\n\n            for (int i = 0; i < nn_joints_; i++)\n            {\n                jjoints_[i].setCommand(ttau_d_(i));\n            }\n\n\n        }else {\n\n            qddot_.data = (qdot_.data - qdot_old_.data) / dt_;\n\n            // error\n            KDL::JntArray q_error;\n            KDL::JntArray q_error_dot;\n            KDL::JntArray ded;\n            KDL::JntArray tde;\n            KDL::JntArray s;\n\n            q_error.data = Eigen::VectorXd::Zero(n_joints_);\n            q_error_dot.data = Eigen::VectorXd::Zero(n_joints_);\n            ded.data = Eigen::VectorXd::Zero(n_joints_);\n            tde.data = Eigen::VectorXd::Zero(n_joints_);\n            s.data = Eigen::VectorXd::Zero(n_joints_);\n\n\n\n            double db = 0.001;\n\n            q_error.data = q_cmd_.data - q_.data;\n            q_error_dot.data = qdot_cmd_.data - qdot_.data;\n\n            for(size_t i=0; i<n_joints_; i++)\n            {\n                s(i) = q_error_dot(i) + Ramda_(i)*q_error(i);\n\n                if(db < Mbar_(i) && Mbar_(i) > Ramda_(i)/Alpha_(i))\n                {\n                    Mbar_dot_(i) = Alpha_(i)*s(i)*s(i) - Alpha_(i)*Omega_(i)*Mbar_(i);\n                }\n\n                if(Mbar_(i) < db)\n                {\n                    Mbar_(i) = db;\n                }\n\n                if(Mbar_(i) > Ramda_(i)/Alpha_(i))\n                {\n                    Mbar_(i) = Ramda_(i)/Alpha_(i) - db;\n                }\n\n                Mbar_(i) = Mbar_(i) + dt_*Mbar_dot_(i);\n            }\n\n            // torque command\n            for(size_t i=0; i<n_joints_; i++)\n            {\n                ded(i) = qddot_cmd_(i) + 2.0 * Ramda_(i)*q_error(i) + Ramda_(i)*Ramda_(i)*q_error_dot(i);\n                tde(i) = tau_cmd_old_(i) - Mbar_(i)*qddot_(i);\n                tau_cmd_(i) = Mbar_(i)*ded(i) + tde(i);\n            }\n\n            for(size_t i=0; i<n_joints_; i++)\n            {\n                joints_[i].setCommand(tau_cmd_(i));\n            }\n\n        }\n\n\n\n        tau_cmd_old_.data = tau_cmd_.data;\n        qdot_old_.data = qdot_.data;\n\n        KDL::Frame Xdes;\n\n        fk_solver_->JntToCart(q_cmd_, Xdes);\n\n        SaveData_[0] = total_time_;\n        SaveData_[1] = 0.122;\n        SaveData_[2] = Xdes.p(2);\n        SaveData_[3] = Fd_;\n        SaveData_[4] = f_cur_(1);\n        SaveData_[5] = f_cur_buffer_;\n        SaveData_[6] = B_buffer_;\n\n        msg_SaveData_.data.clear();\n\n        for (size_t i = 0; i < SaveDataMax; i++)\n        {\n            msg_SaveData_.data.push_back(SaveData_[i]);\n        }\n        pub_SaveData_.publish(msg_SaveData_);\n\n        time_ = time_ + dt_;\n        total_time_ = total_time_ + dt_;\n\n    }\n\n    void stopping(const ros::Time& time) { }\n\n    void task_via()\n    {\n        time_ = 0.0;\n\n        for (size_t i = 0; i < n_joints_; i++)\n        {\n            q_init_(i) = joints_[i].getPosition();\n            q_cmd_(i) = q_cmd_end_(i);\n            qdot_cmd_(i) = 0.0;\n            qddot_cmd_(i) = 0.0;\n        }\n    }\n\n    void task_init()\n    {\n        for (size_t i=0; i<n_joints_; i++)\n        {\n            q_cmd_(i) = 0.0;\n            qdot_cmd_(i) = 0.0;\n            qddot_cmd_(i) = 0.0;\n        }\n\n        q_cmd_end_.data = q_cmd_.data;\n    }\n\n    void task_ready()\n    {\n        for (size_t i=0; i<n_joints_; i++)\n        {\n            if (i == 2 || i == 4)\n            {\n                q_cmd_(i) = trajectory_generator_pos(q_init_(i), PI/2.0, 10.0);\n                qdot_cmd_(i) = trajectory_generator_vel(q_init_(i), PI/2.0, 10.0);\n                qddot_cmd_(i) = trajectory_generator_acc(q_init_(i), PI/2.0, 10.0);\n            }\n            else\n            {\n                q_cmd_(i) = q_init_(i);\n                qdot_cmd_(i) = 0.0;\n                qddot_cmd_(i) = 0.0;\n            }\n        }\n\n        q_cmd_end_.data = q_cmd_.data;\n    }\n\n    void task_freespace()\n    {\n        KDL::Frame start;\n        KDL::Twist target_vel;\n        KDL::JntArray cart_cmd;\n\n        cart_cmd.data = Eigen::VectorXd::Zero(3);\n\n        fk_solver_->JntToCart(q_init_, start);\n\n        for (size_t i=0; i<6; i++)\n        {\n            if(i == 2)\n            {\n                target_vel(i) = trajectory_generator_vel(start.p(i), 0.122, 10.0);\n            }\n            else\n            {\n                target_vel(i) = 0.0;\n            }\n        }\n\n        ik_vel_solver_->CartToJnt(q_cmd_, target_vel, qdot_cmd_);\n\n        for (size_t i=0; i<n_joints_; i++)\n        {\n            q_cmd_(i) = q_cmd_(i) + qdot_cmd_(i)*dt_;\n            qddot_cmd_(i) = (qdot_cmd_(i) - qdot_cmd_old_(i))/dt_;\n            qdot_cmd_old_(i) = qdot_cmd_(i);\n        }\n\n        q_cmd_end_.data = q_cmd_.data;\n    }\n\n    void task_contactspace()\n    {\n        KDL::Frame start;\n\n        if (experiment_mode_ == 0 || experiment_mode_ == 1)\n            Fd_ = Fd_temp_;\n        else if (experiment_mode_ == 2)\n            Fd_ = Fd_temp_ * 1 / 5 * sin(2 * PI * 0.2 * total_time_) + Fd_temp_;\n\n        fk_solver_->JntToCart(q_init_, start);\n\n        for (size_t i = 0; i < 6; i++)\n        {\n            if (i == 0)\n            {\n                Xc_dot_(i) = trajectory_generator_vel(start.p(i), 0.5, 20.0);\n            }\n            else if (i == 2)\n            {\n                Fe_ = f_cur_[1];\n                PI_ = PI_old_ + dt_ * (Fd_old_ - Fe_old_) / B_;\n                B_buffer_ = B_ + del_B_;\n                Xc_ddot_(i) = 1/M_*((Fe_ - Fd_) - (B_ + del_B_)*Xc_dot_old_(i));\n                Xc_dot_(i) = Xc_dot_old_(i) + Xc_ddot_(i)*dt_;\n                del_B_ = B_ / Xc_dot_(i) * PI_;\n                Xc_dot_old_(i) = Xc_dot_(i);\n                Fd_old_ = Fd_;\n                Fe_old_ = Fe_;\n                PI_old_ = PI_;\n            }\n            else\n            {\n                Xc_ddot_(i) = 0.0;\n                Xc_dot_(i) = 0.0;\n            }\n        }\n\n        ik_vel_solver_->CartToJnt(q_cmd_, Xc_dot_, qdot_cmd_);\n\n        for (size_t i=0; i<n_joints_; i++)\n        {\n            q_cmd_(i) = q_cmd_(i) + qdot_cmd_(i)*dt_;\n            qddot_cmd_(i) = (qdot_cmd_(i) - qdot_cmd_old_(i))/dt_;\n            qdot_cmd_old_(i) = qdot_cmd_(i);\n        }\n\n        q_cmd_end_.data = q_cmd_.data;\n    }\n\n    void task_homming()\n    {\n        for (size_t i = 0; i < n_joints_; i++)\n        {\n            q_cmd_(i) = trajectory_generator_pos(q_init_(i), 0.0, 10.0);\n            qdot_cmd_(i) = trajectory_generator_vel(q_init_(i), 0.0, 10.0);\n            qddot_cmd_(i) = trajectory_generator_acc(q_init_(i), 0.0, 10.0);\n        }\n\n        q_cmd_end_.data = q_cmd_.data;\n    }\n\n    double trajectory_generator_pos(double dStart, double dEnd, double dDuration)\n    {\n        double dA0 = dStart;\n        double dA3 = (20.0*dEnd - 20.0*dStart) / (2.0*dDuration*dDuration*dDuration);\n        double dA4 = (30.0*dStart - 30*dEnd) / (2.0*dDuration*dDuration*dDuration*dDuration);\n        double dA5 = (12.0*dEnd - 12.0*dStart) / (2.0*dDuration*dDuration*dDuration*dDuration*dDuration);\n\n        return dA0 + dA3*time_*time_*time_ + dA4*time_*time_*time_*time_ + dA5*time_*time_*time_*time_*time_;\n    }\n\n    double trajectory_generator_vel(double dStart, double dEnd, double dDuration)\n    {\n        double dA0 = dStart;\n        double dA3 = (20.0*dEnd - 20.0*dStart) / (2.0*dDuration*dDuration*dDuration);\n        double dA4 = (30.0*dStart - 30*dEnd) / (2.0*dDuration*dDuration*dDuration*dDuration);\n        double dA5 = (12.0*dEnd - 12.0*dStart) / (2.0*dDuration*dDuration*dDuration*dDuration*dDuration);\n\n        return 3.0*dA3*time_*time_ + 4.0*dA4*time_*time_*time_ + 5.0*dA5*time_*time_*time_*time_;\n    }\n\n    double trajectory_generator_acc(double dStart, double dEnd, double dDuration)\n    {\n        double dA0 = dStart;\n        double dA3 = (20.0*dEnd - 20.0*dStart) / (2.0*dDuration*dDuration*dDuration);\n        double dA4 = (30.0*dStart - 30*dEnd) / (2.0*dDuration*dDuration*dDuration*dDuration);\n        double dA5 = (12.0*dEnd - 12.0*dStart) / (2.0*dDuration*dDuration*dDuration*dDuration*dDuration);\n\n        return 6.0*dA3*time_ + 12.0*dA4*time_*time_ + 20.0*dA5*time_*time_*time_;\n    }\n\n    double first_order_lowpass_filter()\n    {\n        filt_ = (tau_ * filt_old_ + dt_*f_cur_buffer_)/(tau_ + dt_);\n        filt_old_ = filt_;\n\n        return filt_;\n    }\n\n\n\n\n\n\nprivate:\n    // joint handles\n    unsigned int n_joints_;\n    std::vector<std::string> joint_names_;\n    std::vector<hardware_interface::JointHandle> joints_;\n    std::vector<urdf::JointConstSharedPtr> joint_urdfs_;\n\n    // kdl\n    KDL::Tree \tkdl_tree_;\n    KDL::Chain\tkdl_chain_;\n    boost::scoped_ptr<KDL::ChainDynParam> id_solver_;\n    boost::scoped_ptr<KDL::ChainFkSolverPos> fk_solver_;\n    boost::scoped_ptr<KDL::ChainIkSolverVel_pinv> ik_vel_solver_;\n    boost::scoped_ptr<KDL::ChainIkSolverPos_NR_JL> ik_pos_solver_;\n    KDL::JntArray G_;\n    KDL::Vector gravity_;\n\n    // tdc gain\n    KDL::JntArray Mbar_, Mbar_dot_, Ramda_, Alpha_, Omega_;\n\n    // cmd, state\n    KDL::JntArray q_init_;\n    KDL::JntArray tau_cmd_, tau_cmd_old_;\n    KDL::JntArray q_cmd_, q_cmd_old_, qdot_cmd_, qdot_cmd_old_, qddot_cmd_;\n    KDL::JntArray q_cmd_end_;\n    KDL::JntArray q_cmd_sp_;\n    KDL::JntArray q_, qdot_, qdot_old_, qddot_;\n    KDL::Wrench f_cur_;\n    double f_cur_buffer_;\n\n    KDL::Twist Xc_dot_, Xc_dot_old_, Xc_ddot_;\n\n    double Xr_dot_, Xe_dot_;\n    double Xe_ddot_;\n\n    double Fd_, Fd_temp_, Fd_old_, Fe_, Fe_old_;\n    double M_, B_, del_B_, B_buffer_;\n    double PI_, PI_old_;\n\n    double dt_;\n    double time_;\n    double total_time_;\n\n    double filt_old_;\n    double filt_;\n    double tau_;\n\n    int experiment_mode_;\n\n    // topic\n    ros::Subscriber sub_q_cmd_;\n    ros::Subscriber sub_forcetorque_sensor_;\n\n    double SaveData_[SaveDataMax];\n\n    ros::Publisher pub_SaveData_;\n\n    std_msgs::Float64MultiArray msg_SaveData_;\n\n\n    // new from computed torque controller:\n\n\n    // others\n    double tt;\n    int cctr_obj_;\n    int iik_mode_;\n    int eevent;\n\n    //Joint handles\n    unsigned int nn_joints_;                               // joint \uc22b\uc790\n    std::vector<std::string> jjoint_names_;                // joint name ??\n    std::vector<hardware_interface::JointHandle> jjoints_; // ??\n    std::vector<urdf::JointConstSharedPtr> jjoint_urdfs_;  // ??\n\n    // kdl\n    KDL::Tree kkdl_tree_;   // tree?\n    KDL::Chain kkdl_chain_; // chain?\n\n    // kdl M,C,G\n    KDL::JntSpaceInertiaMatrix MM_; // intertia matrix\n    KDL::JntArray CC_;              // coriolis\n    KDL::JntArray GG_;              // gravity torque vector\n    KDL::Vector ggravity_;\n\n    // kdl and Eigen Jacobian\n    KDL::Jacobian JJ_;\n    // KDL::Jacobian J_inv_;\n    // Eigen::Matrix<double, num_taskspace, num_taskspace> J_inv_;\n    Eigen::MatrixXd JJ_inv_;\n    Eigen::Matrix<double, num_taskspace, num_taskspace> JJ_transpose_;\n\n    // kdl solver\n    boost::scoped_ptr<KDL::ChainFkSolverPos_recursive> ffk_pos_solver_; //Solver to compute the forward kinematics (position)\n    // boost::scoped_ptr<KDL::ChainFkSolverVel_recursive> fk_vel_solver_; //Solver to compute the forward kinematics (velocity)\n    boost::scoped_ptr<KDL::ChainJntToJacSolver> jjnt_to_jac_solver_; //Solver to compute the jacobian\n    boost::scoped_ptr<KDL::ChainDynParam> iid_solver_;               // Solver To compute the inverse dynamics\n\n    // Joint Space State\n    KDL::JntArray qqd_, qqd_dot_, qqd_ddot_;\n    KDL::JntArray qqd_old_;\n    KDL::JntArray qq_, qqdot_;\n    KDL::JntArray ee_, ee_dot_, ee_int_;\n\n    // Task Space State\n    // ver. 01\n    KDL::Frame xxd_; // x.p: frame position(3x1), x.m: frame orientation (3x3)\n    KDL::Frame xx_;\n    KDL::Twist eex_temp_;\n\n    // KDL::Twist xd_dot_, xd_ddot_;\n    Eigen::Matrix<double, num_taskspace, 1> eex_;\n    Eigen::Matrix<double, num_taskspace, 1> xxd_dot_, xxd_ddot_;\n    Eigen::Matrix<double, num_taskspace, 1> xxdot_;\n    Eigen::Matrix<double, num_taskspace, 1> eex_dot_, eex_int_;\n\n    // ver. 02\n    // Eigen::Matrix<double, num_taskspace, 1> xd_, xd_dot_, xd_ddot_;\n    // Eigen::Matrix<double, num_taskspace, 1> x_, xdot_;\n    // KDL::Frame x_temp_;\n    // Eigen::Matrix<double, num_taskspace, 1> ex_, ex_dot_, ex_int_;\n\n    // Input\n    KDL::JntArray xx_cmd_;\n\n    // Torque\n    KDL::JntArray aaux_d_;\n    KDL::JntArray ccomp_d_;\n    KDL::JntArray ttau_d_;\n\n    // gains\n    KDL::JntArray KKp_, KKi_, KKd_;\n    double KK_regulation_, KK_tracking_;\n\n    // save the data\n    double SSaveData_[SaveDataMax];\n\n    // ros subscriber\n    ros::Subscriber ssub_x_cmd_;\n\n    // ros publisher\n    ros::Publisher ppub_qd_, ppub_q_, ppub_e_;\n    ros::Publisher ppub_xd_, ppub_x_, ppub_ex_;\n    ros::Publisher ppub_SaveData_;\n\n    // ros message\n    std_msgs::Float64MultiArray mmsg_qd_, mmsg_q_, mmsg_e_;\n    std_msgs::Float64MultiArray mmsg_xd_, mmsg_x_, mmsg_ex_;\n    std_msgs::Float64MultiArray mmsg_SaveData_;\n\n    // magni\n    int flag = 0;\n    double xx;\n    double zz;\n\n    // admittance params\n    double z_pre;\n    double zdot_pre;\n    double zddot_pre;\n    double z;\n    double zdot;\n    double zddot;\n    double K_damp;\n    double K_stiff;\n    double M_ad;\n    int window;\n\n    ros::Subscriber k_stiff_damp_sub;\n\n    std_msgs::Float64MultiArray msg_temp;\n    ros::Publisher publisher_;\n\n\n};\n}\n\nPLUGINLIB_EXPORT_CLASS(arm_controllers::AdmittanceController, controller_interface::ControllerBase)\n", "meta": {"hexsha": "845ae7dd08c80a50ca18a6e366393ea5eb75deb3", "size": 38025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "arm_controllers/src/admittance_controller.cpp", "max_stars_repo_name": "trannguyenle95/arm-tutorial", "max_stars_repo_head_hexsha": "2526694a992026e69dc0a7585fff85d4407194cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-03T03:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-13T12:17:56.000Z", "max_issues_repo_path": "arm_controllers/src/admittance_controller.cpp", "max_issues_repo_name": "trannguyenle95/arm-tutorial", "max_issues_repo_head_hexsha": "2526694a992026e69dc0a7585fff85d4407194cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-17T11:11:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T08:15:22.000Z", "max_forks_repo_path": "arm_controllers/src/admittance_controller.cpp", "max_forks_repo_name": "trannguyenle95/arm-tutorial", "max_forks_repo_head_hexsha": "2526694a992026e69dc0a7585fff85d4407194cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T09:37:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T13:48:33.000Z", "avg_line_length": 29.8001567398, "max_line_length": 156, "alphanum_fraction": 0.5347534517, "num_tokens": 10648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.19122011876909248}}
{"text": "#include \"ros/ros.h\"\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <math.h>\n#include <sstream>\n#include <string>\n#include <iostream>\n#include <cstdio>\n#include <ctime>\n#include <unistd.h>\n#include <cmath>\n#include <stdio.h>\n#include <stdlib.h>\n#include <tbb/atomic.h>\n#include <tf/transform_broadcaster.h>\n#include \"std_msgs/Int32.h\"\n#include \"std_msgs/String.h\"\n#include \"std_msgs/Bool.h\"\n#include \"sepanta_msgs/omnidata.h\"\n#include <dynamixel_msgs/MotorStateList.h>\n#include <dynamixel_msgs/JointState.h>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <nav_msgs/Path.h>\n#include <geometry_msgs/PolygonStamped.h>\n#include <move_base_msgs/MoveBaseActionGoal.h>\n#include <dynamixel_controllers/SetComplianceSlope.h>\n#include <dynamixel_controllers/SetCompliancePunch.h>\n#include <boost/thread.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"std_msgs/Int32.h\"\n#include \"std_msgs/String.h\"\n#include \"std_msgs/Bool.h\"\n#include \"geometry_msgs/Twist.h\"\n#include <sensor_msgs/LaserScan.h>\n#include <termios.h>\n#include <nav_msgs/Odometry.h>\n#include <tf/transform_datatypes.h>\n#include <sepanta_msgs/command.h>\n#include <sepanta_msgs/omnidata.h>\n#include <sepanta_msgs/sepantaAction.h> //movex movey turngl turngllocal actions\n#include <sepanta_msgs/slamactionAction.h> //slam action\n#include <ros/package.h>\n#include <fstream>\n#include <iostream>\n#include <stdlib.h>\n#include <sstream>\n#include <vector>\n#include <fstream>\n#include <nav_core/base_local_planner.h>\n#include <nav_core/base_global_planner.h>\n#include <nav_core/recovery_behavior.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <costmap_2d/costmap_2d_ros.h>\n#include <costmap_2d/costmap_2d.h>\n#include <nav_msgs/GetPlan.h>\n#include <std_srvs/Empty.h>\n#include <tf/transform_datatypes.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <visualization_msgs/Marker.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <sepanta_msgs/Objects.h>\n#include <sepanta_msgs/Object.h>\n#include <k2_client/BodyArray.h>\n///////////////////////////////////////////////////////////\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"opencv2/highgui/highgui_c.h\"\n#include <opencv2/core/core.hpp>\n#include \"opencv/cv.h\"\n#include \"opencv2/calib3d/calib3d.hpp\"\n//********************************************** cv_bridge\n#include <cv_bridge/cv_bridge.h>\n#include <ros/ros.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/time_synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n\n#include <sensor_msgs/Image.h>\n#include <sepanta_msgs/Objects.h>\n#include <image_transport/image_transport.h>\n\n#include <boost/thread/mutex.hpp>\n\n#include <actionlib/client/simple_action_client.h>\n#include <actionlib/client/terminal_state.h>\n#include <sepanta_msgs/LookForObjectsAction.h>\n\n#include <actionlib/client/simple_action_client.h>\n#include <actionlib/client/terminal_state.h>\n#include <sepanta_msgs/MasterAction.h>\n#include <sepanta_msgs/led.h>\n\nusing std::string;\nusing std::exception;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nusing namespace std;\nusing namespace boost;\nusing namespace ros;\n\n//=============================================================\n#define waypoint_1 \"roomcenter\"\n#define waypoint_2 \"bedroom\"\n#define waypoint_3 \"shelf\"\n#define waypoint_4 \"kitchen\"\n#define ask_for_recover\n\nenum _logic_state { idle, wait_for_door, on_waypoint1 , on_waypoint2 , on_waypoint3 , on_waypoint4 , go_to_waypoint1 , go_to_waypoint2 , go_to_waypoint3 , go_to_waypoint4 , recover_door , recover_obstacle , recover_human };\nenum _navigation_state { ready , run , cancel , error };\n//=============================================================\n\nstd::string coutcolor0 = \"\\033[0;0m\";\nstd::string coutcolor_red = \"\\033[0;31m\";\nstd::string coutcolor_green = \"\\033[0;32m\";\nstd::string coutcolor_blue = \"\\033[0;34m\";\nstd::string coutcolor_magenta = \"\\033[0;35m\";\nstd::string coutcolor_brown = \"\\033[0;33m\";\n\nint Function_state = 0;\nbool Function1_result = false;\nbool Function2_result = false; //dummy\nbool Function3_result = false;\nint question_counter = 0;\nint door_distance = 0;\nbool isdooropened_kinect2 = true;\n\nbool App_exit = false;\nros::Publisher pub_tts;\nros::Publisher pub_spr;\nros::Publisher pub_led;\nbool say_enable = false;\n\n_logic_state logic_state = idle;\nbool isdooropened = false;\nbool ishumanthere = false;\nbool isspeechready = false;\nbool isttsready = true;\n\nstring sayMessageId;\n\nstring speech_last_command = \"\";\nstring temp_speech_last_command = \"\";\nros::ServiceClient client_navigation;\nros::ServiceClient say_service;\n\nactionlib::SimpleActionClient<sepanta_msgs::MasterAction> * ac_navigation;\n\nvoid change_led(int r,int g,int b)\n{\n  sepanta_msgs::led _msg;\n\n  if( r != 0 || g != 0 || b != 0)\n  {\n     _msg.enable = true;\n     _msg.colorR = r;\n     _msg.colorG = g;\n     _msg.colorB = b;\n  }\n  else\n  {\n    _msg.enable = false;\n  }\n\n  pub_led.publish(_msg);\n}\n\n\nstring last_print_message = \"\";\nvoid print_color(string msg,string color,bool once = false)\n{\n  if ( once == false )\n  {\n    if ( color == \"red\" )\n    {\n      std::cout<<coutcolor_red<<msg<<coutcolor0<<std::endl;\n    }\n    if ( color == \"green\" )\n    {\n      std::cout<<coutcolor_green<<msg<<coutcolor0<<std::endl;\n    }\n    if ( color == \"blue\" )\n    {\n      std::cout<<coutcolor_blue<<msg<<coutcolor0<<std::endl;\n    }\n    if ( color == \"brown\" )\n    {\n      std::cout<<coutcolor_brown<<msg<<coutcolor0<<std::endl;\n    }\n    if ( color == \"coutcolor_magenta\" )\n    {\n      std::cout<<coutcolor_magenta<<msg<<coutcolor0<<std::endl;\n    }\n  }\n  else\n  {\n       if ( last_print_message != msg)\n       {\n           speech_last_command = msg;\n\n           if ( color == \"red\" )\n          {\n            std::cout<<coutcolor_red<<speech_last_command<<coutcolor0<<std::endl;\n          }\n          if ( color == \"green\" )\n          {\n            std::cout<<coutcolor_green<<speech_last_command<<coutcolor0<<std::endl;\n          }\n          if ( color == \"blue\" )\n          {\n            std::cout<<coutcolor_blue<<speech_last_command<<coutcolor0<<std::endl;\n          }\n          if ( color == \"brown\" )\n          {\n            std::cout<<coutcolor_brown<<speech_last_command<<coutcolor0<<std::endl;\n          }\n          if ( color == \"coutcolor_magenta\" )\n          {\n            std::cout<<coutcolor_magenta<<speech_last_command<<coutcolor0<<std::endl;\n          }\n\n\n       }\n  }\n}\n\nvoid sepanta_wait(int ms)\n{\n  boost::this_thread::sleep(boost::posix_time::milliseconds(ms));\n}\n\nstring navigation_go_to(string location)\n{\n  sepanta_msgs::MasterGoal goal;\n  goal.action = \"exe\";\n  goal.id = location;\n\n  ac_navigation->sendGoal(goal);\n\n  //wait for the action to return\n  bool finished_before_timeout = ac_navigation->waitForResult(ros::Duration(1000));\n\n  if (finished_before_timeout)\n  {\n    actionlib::SimpleClientGoalState state = ac_navigation->getState();\n    ROS_INFO(\"Action finished: %s\",state.toString().c_str());\n    sepanta_msgs::MasterResult::ConstPtr _res = ac_navigation->getResult();\n    ROS_INFO(\"Action result : %s\",_res->result.c_str());\n\n    return _res->result.c_str();\n\n  }\n  else\n  {\n     ac_navigation->cancelGoal();\n     ROS_INFO(\"Action did not finish before the time out.\");\n\n      return \"time_out\";\n  }\n\n}\n\nvoid navigation_cancel()\n{\n   ac_navigation->cancelGoal();\n}\n\nstring temp_say_message = \"\";\n\nvoid say_message(string data,bool once = false)\n{\n    if  ( once )\n    {\n      if ( temp_say_message == data ) return;\n      temp_say_message = data;\n    }\n    if ( say_enable == false ) return;\n  \tisttsready = false;\n    sepanta_msgs::command _msg;\n   _msg.request.command = data;\n    say_service.call(_msg);\n    sayMessageId = _msg.response.result;\n    while(!isttsready)\n    {\n    \tsepanta_wait(1000);\n    }\n}\n\nvoid chatterCallback_kinect2_body(const k2_client::BodyArray::ConstPtr &msg)\n{\n   bool detect = false; \n\n   for ( int i = 0 ; i < msg->bodies.size() ; i++)\n   {\n       if ( msg->bodies.at(i).isTracked)\n       {\n          int _z =  msg->bodies.at(i).jointPositions.at(11).position.z * 100;\n          int _x =  msg->bodies.at(i).jointPositions.at(11).position.x * 100;\n\n          stringstream convert; // stringstream used for the conversion\n          convert << _z;\n\n          string z = convert.str();\n\n          if ( _z < 200 && _z > 10 )\n          {\n             if (  abs(_x) < 50 )\n             {\n                 ishumanthere = true;\n                 detect = true;\n             }\n          }\n   \n          print_color(z,\"red\",false);\n       }\n\n   }\n\n   if ( detect == false)\n   {\n      ishumanthere = false;\n   }\n}\n\nvoid chatterCallback_door(const std_msgs::Bool::ConstPtr &msg)\n{\n   isdooropened = msg->data;\n}\n\nvoid chatterCallback_speech(const std_msgs::String::ConstPtr &msg)\n{\n   cout<<coutcolor_brown<<\"Speech Get : \"<<msg->data<<coutcolor0<<endl;\n   if ( temp_speech_last_command != msg->data )\n   {\n      temp_speech_last_command = msg->data;\n      speech_last_command = temp_speech_last_command;\n      isspeechready = true;\n   }  \n}\n\nvoid chatterCallback_ttsfb(const std_msgs::String::ConstPtr &msg)\n{\n\tif(!isttsready && msg->data==sayMessageId)\n\t{\n\t\tisttsready = true;\n\t}\n}\n\nvoid send_feedback_to_speech(string cmd)\n{\n   std_msgs::String _msg;\n   _msg.data = cmd;\n   pub_spr.publish(_msg);\n}\n\n\n\nvoid Function_1()\n{\n   // if ( Function_state == 0 )\n   // {\n   //    say_message(\"I am going to kitchen and i should bring a coca for you!\");\n   //    Function_state = 1;\n   // }\n   // else if ( Function_state == 1)\n   // {\n   //    navigation_go_to(\"kitchen\");\n   //    Function_state = 2;\n   // }\n   // else if ( Function_state == 2)\n   // {\n   //      cout<<coutcolor_blue<<\"Function [1] STATE [2] : wait for navigation to kitchen\"<<coutcolor0<<endl;\n\t  //   \tFunction_state = 3;\n   // }\n   // else if ( Function_state == 3)\n   // {\n   //     Function1_result = false;\n   //     cout<<coutcolor_blue<<\"Function [1] STATE [3] : Send Start for object\"<<coutcolor0<<endl;\n   //     Function_state = 4;\n   // }\n   // else if ( Function_state == 4)\n   // {\n   // \t   cout<<coutcolor_blue<<\"Function [1] STATE [4] : wait for object recognition\"<<coutcolor0<<endl;\n   // \t   Function_state = 5;\n   // }\n   // else if ( Function_state == 5)\n   // {\n   //    Function1_result = process_object(\"coca\");\n   //    if ( Function1_result )\n   //    {\n   //      say_message(\"well done ! , i found the coca !\");\n   //      say_message(\"i wonder, if i had my arms , could i pick up the coca? Money does not guarantee hapiness. But no money, no arms! \");\n   //    }\n   //    else\n   //    {\n   //      say_message(\"I cant find the coca.\");\n   //      say_message(\"it does not matter. I could not grab it even if I found it. Money does not guarantee hapiness. But no money, no arms! \");\n   //    }\n\n   //    Function_state = 6;\n   // }\n   // else if ( Function_state == 6)\n   // {\n   //    say_message(\"i am goint to room center to report my perception\");\n   //    navigation_go_to(\"roomcenter\");\n   //    Function_state = 7;\n   // }\n   // else if ( Function_state == 7)\n   // {\n   // \t   cout<<coutcolor_blue<<\"Function [1] STATE [7] : wait for navigation to room center\"<<coutcolor0<<endl;\n\t  //    Function_state = 8;\n   // }\n   // else if ( Function_state == 8 )\n   // {\n   \t   \n   //    if ( Function1_result )\n   //    {\n   //         say_message(\"well done ! , i found the coca !\");\n   //         say_message(\"But if you expect me to bring it for you, prepare a set of arms for me!\");\n   //    }\n   //    else\n   //    {\n   //         say_message(\"I cant find the coca.\");\n   //         say_message(\"it does not matter. I could not grab it even if I found it.\");\n   //    }\n   // \t   //========================================\n   // \t   say_message(\"operation Done\");\n\n   // \t   Function_state = 0;\n   // \t   logic_state = 3;\n   // }\n}\n\nvoid Function_2()\n{\n   // cout<<\"Header :\"<<Function_state<<endl;\n   // if ( Function_state == 0 )\n   // {\n   //   question_counter = 0;\n   // \t say_message(\"It is my pleasure to answer your questions!\");\n   // \t Function_state = 1;\n   // }\n   // else if ( Function_state == 1)\n   // {\n   // \t  say_message(\"ask\");\n   //    send_feedback_to_speech(\"qstart\");\n   //    Function_state = 2;\n   // }\n   // else if ( Function_state == 2)\n   // {\n   //    if ( isspeechready )\n   //    { \n   //        isspeechready = false;\n   //        if ( speech_last_command == \"qready\")\n   //        {\n   //          //say_message(\"ask\");\n   //          Function_state = 3;\n   //        }\n   //        else\n   //        {\n\n   //           send_feedback_to_speech(\"qstart\");\n   //        }\n   //    }\n   // }\n   // else if ( Function_state == 3)\n   // {\n   //          //Ready \n   //          if ( isspeechready )\n   //          {\n   //             isspeechready = false;\n   //             if ( speech_last_command != \"0\")\n   //             {\n   //               say_message(speech_last_command);\n   //               if ( question_counter < 4)\n   //               {\n   //               question_counter++;\n   //               Function_state = 1;\n   //               }\n   //               else\n   //               {\n   //                  say_message(\"Finished\");\n   //                  Function_state = 4;\n   //               }\n   //             }\n   //             else\n   //             {\n   //                 Function_state = 1;\n   //             }\n   //          }\n   //          else\n   //          {\n   //                cout<<coutcolor_blue<<\"Function [2] STATE [3] : wait for user question\"<<coutcolor0<<endl;\n   //          }\n   // }\n   // else if ( Function_state == 4)\n   // {\n   //     Function_state = 0;\n   //     logic_state = 3;\n   // }\n}\n\nvoid Function_3()\n{\n     // if ( Function_state == 0 )\n     // {\n     //   string cmd = \"I am going to find the \" + desire_object_name + \" for you\";\n     //   say_message(cmd);\n     //   Function_state = 1;\n     // }\n     // else if ( Function_state == 1)\n     // {\n     //   navigation_go_to(\"bedroom\");\n     //   Function_state = 2;\n     // }\n     // else if ( Function_state == 2)\n     // {\n     //      cout<<coutcolor_blue<<\"Function [3] STATE [2] : wait for navigation to bedroom\"<<coutcolor0<<endl;\n  \t  //   \tFunction_state = 3;\n     // }\n     // else if ( Function_state == 3)\n     // {\n     //     Function3_result = false;\n     // \t   Function_state = 4;\n     // }\n     // else if ( Function_state == 4)\n     // {\n     //     cout<<coutcolor_blue<<\"Function [3] STATE [4] : wait for object recognition\"<<coutcolor0<<endl;\n     // \t   Function_state = 5;\n     // }\n     // else if ( Function_state == 5)\n     // {\n     //    bool result = process_object(desire_object_name);\n\n     //    if ( result )\n     //    {\n     //      //we find it\n     //      string cmd = \"I Find the \" + desire_object_name + \" for you\";\n     //      say_message(cmd);\n\n     //      cmd = \"i wonder, if i had my arms could i pick up the  \" +  desire_object_name + \" ? Oh money ! money is the problem\";\n     //      say_message(cmd);\n          \n              \n     //      say_message(\"i am going to the room center\");\n     //      navigation_go_to(\"roomcenter\");\n         \n     //      Function_state = 10;\n\n     //    }\n     //    else \n     //    {\n     //      //we cant find it\n     //      string cmd = \"I Could not find the \" + desire_object_name + \" in bedroom \";\n     //      say_message(cmd);\n\n     //      say_message(\"it is better to check the shelf , maybe i will find it there \");\n     //      navigation_go_to(\"shelf\");\n        \n     //      Function_state = 6;\n     //    }\n     // }\n     // else if ( Function_state == 6)\n     // {\n     //      cout<<coutcolor_blue<<\"Function [3] STATE [6] : wait for navigation to shelf\"<<coutcolor0<<endl;\n  \t  //   \tFunction_state = 7;    \n     // }\n     // else if ( Function_state == 7)\n     // {\n     //    Function3_result = false;\n     // \t  Function_state = 8;\n     // }\n     // else if ( Function_state == 8)\n     // {\n     //     cout<<coutcolor_blue<<\"Function [3] STATE [8] : wait for object recognition\"<<coutcolor0<<endl;\n     // \t   Function_state = 9;\n     // }\n     // else if ( Function_state == 9)\n     // {\n     //   bool result = process_object(desire_object_name);\n   \t //   string cmd = \"\";\n     //   if ( result )\n     //    {\n     //      //we find it\n     //       cmd = \"I Find the \" + desire_object_name + \" for you\";\n     //       say_message(cmd);\n     //       cmd = \"I have the  \" +  desire_object_name + \". But wait! How on earth can I pick it up when I have no arms!?\";\n     //       say_message(cmd);\n     //    }\n     //    else \n     //    {\n     //      //we cant find it\n     //     cmd = \"I Could not find the \" + desire_object_name + \" on the shelf \";\n     //     say_message(cmd);\n     //     cmd = \"i want to have 2 arms like my other friends and humans ! Oh money ! money is the problem\";\n     //     say_message(cmd);\n         \n     //    }\n\n     //      say_message(\"i am going to the room center\");\n     //      navigation_go_to(\"roomcenter\");\n     //      Function_state = 10;\n     //   }\n     //   else if ( Function_state == 10)\n     //   {\n     //   \t    cout<<coutcolor_blue<<\"Function [3] STATE [10] : wait for navigation to room center\"<<coutcolor0<<endl;\n    \t//     \tFunction_state = 11;\n    \t    \n     //   }\n     //   else if ( Function_state == 11 )\n     //   {\n     //   \t   //report object recognition status\n     //   \t   //========================================\n     //   \t   say_message(\"operation Done\");\n     //   \t   Function_state = 0;\n     //   \t   logic_state = 3;\n     //   }\n} \n\nvoid process_speech_command(string message)\n{\n   // isspeechready = false;\n   // speech_last_command = \"\";\n\n   // if ( logic_state == 4 )\n   // {\n\t  //  \tif ( message == \"ready\")\n\t  //  \t{\n\t\t //   \tlogic_state = 5;\n\t\t //   \tcout<<coutcolor_green<<\"Speech is ready !\"<<coutcolor0<<endl;\n\t  //   }\n\t  //   else if ( message == \"#error#\" )\n\t  //   {\n\t  //   \tlogic_state = 3;\n\t  //   \tcout<<coutcolor_red<<\"Speech has error :\"<< message <<coutcolor0<<endl;\n\t  //   }\n   // }\n   // else if ( logic_state == 5 )\n   // {\n   //    //6 kitchen\n   //    //7 questions\n   //    //8 object\n   //    //=================================================\n   //     // cout<<coutcolor_green<<\"SPEECH GET PROCESS : \"<<message<<coutcolor0<<endl;\n   // \t   // if ( message == \"1\" ){logic_state = 6;}else\n   // \t   // if ( message == \"2\" ){logic_state = 7;}else\n   // \t   // if ( message == \"3\" ){logic_state = 8; desire_object_name = \"soda\";}else\n   // \t   // if ( message == \"4\" ){logic_state = 8; desire_object_name = \"coffee\";}else\n   // \t   // if ( message == \"5\" ){logic_state = 9;}\n   \t \n   // \t   // else\n   // \t   // {\n   //     // cout<<coutcolor_red<<\"Invalid Speech Command for logic state 5 : \"<< message <<coutcolor0<<endl;\n   //     // logic_state = 3;\n   // \t   // }\n   // }\n}\n\n\nstring desire_location = \"\";\n_navigation_state navigation_state = ready;\n\nvoid navigation_thread()\n{\n   sepanta_wait(1000);\n   while ( App_exit == false && ros::ok())\n   {\n          if ( navigation_state == ready )\n          {\n              //wait for state\n          }\n          else if ( navigation_state == run)\n          {\n              navigation_go_to(desire_location);\n              navigation_state = ready;\n          }\n          else if (navigation_state == cancel)\n          {\n             navigation_cancel();\n             navigation_state = error;\n          }\n          else if ( navigation_state == error)\n          {\n            //there was a problem with navigation\n          }\n\n          sepanta_wait(100);\n   }\n}\n\n_logic_state temp_logic_state = idle;\n\nvoid check_for_obstacles()\n{\n                 if ( isdooropened == false && isdooropened_kinect2 == false)\n                 {\n                    change_led(255,0,0); //door\n                    temp_logic_state = logic_state;\n                    logic_state = recover_door;\n                    navigation_state = cancel; \n                    say_message(\"the door is closed\");\n                 }\n                 else if ( isdooropened == false && isdooropened_kinect2 == true )\n                 {\n                    change_led(200,50,0); //object\n                    temp_logic_state = logic_state;\n                    logic_state = recover_obstacle;\n                    navigation_state = cancel; \n                    say_message(\"there is an object on my way\");\n                 }\n                 else if ( isdooropened == true && isdooropened_kinect2 == true )\n                 {\n                    //change_led(0,255,0); //no obstacle\n                 }\n                 //===================================================\n                 if ( ishumanthere )\n                 {\n                    change_led(255,0,255);\n                    temp_logic_state = logic_state;\n                    logic_state = recover_human;\n                    navigation_state = cancel; \n                    say_message(\"There is a human on my way\");\n                    say_message(\"Please move away!\");\n                 }\n}\n\n\n\nvoid logic_thread()\n{\n    sepanta_wait(1000);\n    say_message(\"Sepanta Stage 1. Navigation test started\");\n\n    while(ros::ok() && !App_exit )\n    {\n         sepanta_wait(50);\n\n         if ( logic_state == idle )\n         {\n           print_color(\"idle\",\"blue\",false);\n           change_led(0,0,0);\n           isspeechready = false;\n           logic_state = wait_for_door;    \n         }\n         else if ( logic_state == wait_for_door )\n         {\n            if ( isdooropened == false )\n            {\n                print_color(\"wait for door\",\"brown\",true);\n                change_led(0,0,250);\n            }\n            else\n            {\n                print_color(\"the door is opened\",\"green\",false);\n                say_message(\"The door is opened!\");\n                change_led(0,250,0);\n                sepanta_wait(1000);\n                change_led(0,0,0);\n                desire_location = waypoint_1;\n                navigation_state = run;\n                logic_state = go_to_waypoint1; \n            }\n         }\n         else\n         if ( logic_state == go_to_waypoint1 )\n         {\n            print_color(\"STATE : wait for navigation to reach waypoint one\",\"green\",true);\n\n            if ( navigation_state == ready )\n            {\n               logic_state = on_waypoint1; \n            }\n            else\n            {\n               check_for_obstacles();\n            }\n\n         }\n         else if ( logic_state == on_waypoint1)\n         {\n          say_message(\"i reached waypoint one\");\n\n          desire_location = waypoint_2;\n          navigation_state = run;\n          logic_state = go_to_waypoint2;\n         \n         }\n         else if ( logic_state == go_to_waypoint2)\n         {\n            print_color(\"STATE : wait for navigation to reach waypoint two\",\"green\",true);\n\n            if ( navigation_state == ready )\n            {\n               logic_state = on_waypoint2; \n            }\n            else\n            {\n               check_for_obstacles();\n            }\n         }\n         else if ( logic_state == on_waypoint2 )\n         {\n          say_message(\"i reached waypoint two\");\n\n          desire_location = waypoint_3;\n          navigation_state = run;\n          logic_state = go_to_waypoint3;\n         }\n         else if ( logic_state == go_to_waypoint3)\n         {\n            print_color(\"STATE : wait for navigation to reach waypoint three\",\"green\",true);\n\n            if ( navigation_state == ready )\n            {\n               logic_state = on_waypoint3; \n            }\n            else\n            {\n               check_for_obstacles();\n            }\n         }\n         else if ( logic_state == on_waypoint3 )\n         {\n          say_message(\"i reached waypoint three\");\n          say_message(\"i am ready to follow someone\");\n          //comming soon\n         }\n         else if ( logic_state == recover_door )\n         {\n             navigation_state = run;\n             logic_state = temp_logic_state;\n         }\n         else if ( logic_state == recover_human )\n         {\n            if ( ishumanthere == false )\n            {\n            navigation_state = run;\n            logic_state = temp_logic_state;\n            }\n         }\n         else if ( logic_state == recover_obstacle )\n         {\n\n            #ifdef ask_for_recover\n           \n            say_message(\"Please move the object a way\",true);\n\n            if ( isdooropened )\n            {\n              say_message(\"Thanks for your copration\");\n              navigation_state == run;\n              logic_state = temp_logic_state;\n            }\n           \n            #else \n             navigation_state = run;\n             logic_state = temp_logic_state;\n            #endif \n         }\n\n\n\n\n\n    }\n\n     print_color(\"scenario logic terminated\",\"red\");\n}\n\nvoid chatterCallback_doorDistance(const std_msgs::Int32::ConstPtr& msg)\n{\n   door_distance = msg->data;\n   if ( door_distance < 80 && door_distance > 10 )\n   {\n     isdooropened_kinect2 = false;\n   }\n   else\n   {\n     isdooropened_kinect2 = true;\n   }\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"scenario1\");\n    ros::Time::init();\n\n    print_color(\"stage 1 , navigation test started\",\"green\");\n  \n    ros::NodeHandle node_handle;\n    ros::Subscriber sub_handles[5];   \n    //=========================================================================================\n    pub_tts = node_handle.advertise<std_msgs::String>(\"/texttospeech/message\", 10);\n    sub_handles[0] = node_handle.subscribe(\"lowerbodycore/isdooropened\", 10, chatterCallback_door);\n    sub_handles[1] = node_handle.subscribe(\"/speechRec/cmd_spch\", 10, chatterCallback_speech);\n    sub_handles[2] = node_handle.subscribe(\"/texttospeech/queue\", 10, chatterCallback_ttsfb);\n    sub_handles[3] = node_handle.subscribe(\"kinect2/bodyArray\",10,chatterCallback_kinect2_body);\n    sub_handles[4] = node_handle.subscribe(\"/doorDistance\",10,chatterCallback_doorDistance);\n\n    pub_spr = node_handle.advertise<std_msgs::String>(\"/speechRec/feedback_spch\", 10);\n    client_navigation = node_handle.serviceClient<sepanta_msgs::command>(\"sepantamovebase/command\");\n    say_service = node_handle.serviceClient<sepanta_msgs::command>(\"texttospeech/say\");\n    pub_led = node_handle.advertise<sepanta_msgs::led>(\"/lowerbodycore/led\", 10);\n\n    //==========================================================================================\n    ros::Rate loop_rate(20);\n    //action #1 SepantaNavigation\n    ac_navigation = new actionlib::SimpleActionClient<sepanta_msgs::MasterAction>(\"SepantaMoveBaseAction\", true);\n    ROS_INFO(\"Waiting for action server to start [SepantaNavigation].\");\n    ac_navigation->waitForServer(); \n    ROS_INFO(\"SepantaNavigation Action Server Started ready\");\n\n    boost::thread _thread_Logic(&logic_thread);\n    boost::thread _thread_Navigation(&navigation_thread);\n   \n    while (ros::ok() && App_exit == false)\n    {\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n\n    _thread_Logic.interrupt();\n    _thread_Logic.join();\n\n    _thread_Navigation.interrupt();\n    _thread_Navigation.join();\n    \n    App_exit = true;\n    return 0;\n}\n\n", "meta": {"hexsha": "64f7dc1e5d0055428492fc55c54ef343a8b4975b", "size": 27204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SMACH/sepantascenario/src/stage_base.cpp", "max_stars_repo_name": "cxdcxd/sepanta3", "max_stars_repo_head_hexsha": "a65a3415f046631ac4d6b91f9342966b0c030226", "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": "SMACH/sepantascenario/src/stage_base.cpp", "max_issues_repo_name": "cxdcxd/sepanta3", "max_issues_repo_head_hexsha": "a65a3415f046631ac4d6b91f9342966b0c030226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SMACH/sepantascenario/src/stage_base.cpp", "max_forks_repo_name": "cxdcxd/sepanta3", "max_forks_repo_head_hexsha": "a65a3415f046631ac4d6b91f9342966b0c030226", "max_forks_repo_licenses": ["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.0951871658, "max_line_length": 223, "alphanum_fraction": 0.5528231142, "num_tokens": 6749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19122011495727528}}
{"text": "#include <njson/json.hpp>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include \"tachikoma.h\"\n#include \"defs.h\"\n#include <signal.h>\n#include <SDL/SDL.h>\n#include <armadillo>\n\n#define FPS 15\n\nusing namespace std;\nusing namespace arma;\nusing json = nlohmann::json;\n\nstatic bool stopsig;\n\nstatic void stopsignal(int) {\n  stopsig = true;\n}\n\nint main(int argc, char *argv[]) {\n  signal(SIGINT, stopsignal);\n\n  // create a window to show the results of the calibration\n  SDL_Init(SDL_INIT_EVERYTHING);\n  SDL_Surface *screen;\n  screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);\n\n  // try to connect to the tachikoma's arduinos\n  // NOTE: this will try to do ALL-IN-ONE Calibration\n  Tachikoma *tachikoma;\n  tachikoma = new Tachikoma();\n  if (!tachikoma->connected()) {\n    printf(\"[TACHI CALIBRATE] Not connected to anything, disconnecting...\\n\");\n    tachikoma->disconnect();\n    return 1;\n  }\n\n  // create space to store the position information\n  mat leg_sensors;\n  mat leg_feedback;\n\n  uint32_t start;\n  mat min_sensors;\n  mat max_sensors;\n  bool minset = false;\n  bool maxset = false;\n\n  // start reading events\n  while (!stopsig) {\n    SDL_Event event;\n    start = SDL_GetTicks();\n\n    while (SDL_PollEvent(&event)) {\n      switch (event.type) {\n        case SDL_QUIT:\n          stopsig = true;\n          break;\n        default:\n          break;\n      }\n    }\n    if (stopsig) {\n      continue;\n    }\n\n    // grab sensor readings\n    tachikoma->recv(leg_sensors, leg_feedback);\n    if (!minset) {\n      minset = true;\n      min_sensors = leg_sensors;\n    } else {\n      min_sensors += (leg_sensors - min_sensors) % (leg_sensors < min_sensors || min_sensors == 0);\n    }\n    if (!maxset) {\n      maxset = true;\n      max_sensors = leg_sensors;\n    } else {\n      max_sensors += (leg_sensors - max_sensors) % (leg_sensors > max_sensors || leg_sensors == 0);\n    }\n    \n    cout << \"[TACHI CALIBRATE] New data: \\n\";\n    cout << leg_sensors.t() << endl;\n    cout << min_sensors.t() << endl;\n    cout << max_sensors.t() << endl;\n\n    // SDL render\n    SDL_Flip(screen);\n    if (1000 / FPS > SDL_GetTicks() - start) {\n      SDL_Delay(1000 / FPS - (SDL_GetTicks() - start));\n    }\n  }\n\n  // convert to string and save to file\n  json potvals = json({});\n  vector<string> legnames = { \"ul\", \"ur\", \"dl\", \"dr\" };\n  vector<int> legids = { UL, UR, DL, DR };\n  vector<string> jointnames = { \"waist\", \"thigh\", \"knee\" };\n  vector<int> jointids = { WAIST, THIGH, KNEE };\n  for (int i = 0; i < NUM_LEGS; i++) {\n    for (int j = 0; j < NUM_JOINTS; j++) {\n      string legname = legnames[i];\n      int legid = legids[i];\n      string jointname = jointnames[j];\n      int jointid = jointids[j];\n      potvals[legname][jointname][\"min\"] = min_sensors(legid, jointid);\n      potvals[legname][jointname][\"max\"] = max_sensors(legid, jointid);\n      potvals[legname][jointname][\"reversed\"] = false;\n    }\n  }\n  FILE *fp = fopen(\"calib_params.json\", \"w\");\n  fprintf(fp, \"%s\", potvals.dump().c_str());\n  fclose(fp);\n  cout << \"[TACHI CALIBRATE] saved information to: calib_params.json\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "d3227c859851b0057acaf403352140282c6c78c9", "size": 3092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robot/tachikoma/oldmotion/calibrate.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "robot/tachikoma/oldmotion/calibrate.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "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/tachikoma/oldmotion/calibrate.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["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.9831932773, "max_line_length": 99, "alphanum_fraction": 0.6206338939, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.19119742312419763}}
{"text": "#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/Temperature.h>\n#include <sensor_msgs/TimeReference.h>\n#include <string>                   \n#include <iostream>                 \n#include <fstream>\n#include <serial/serial.h>          \n#include <vector>                   \n#include <sstream>\n#include <exception>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n//#include <chiki-briki_i_v_damki.h>\n\n\n#include <dynamic_reconfigure/server.h>\n#include <mcu_interface/parametersConfig.h>\n#include \"mcu_interface/AlignMcuCamPhase.h\"\n#include \"mcu_interface/StartMcuCamTriggering.h\"\n#include \"mcu_interface/PublishS10ToMcuOffset.h\"\n\nstd::string IMU_TOPIC = \"mcu_imu\";\nstd::string IMU_TEMP_TOPIC_POSTFIX = \"_temp\";\nstd::string CAMERAS_TS_TOPIC = \"mcu_cameras_ts\";\nstd::string LIDAR_TS_TOPIC = \"mcu_lidar_ts\";\nstd::string S10_TS_TOPIC = \"mcu_s10_ts\";\n\nstd::string IMU_TEMP_TOPIC = IMU_TOPIC + IMU_TEMP_TOPIC_POSTFIX;\nstd::string PORT;// = \"/dev/ttyUSB200\";  // port name\nconst int BAUD = 500000;            \nint RATE = 10000;                   \nint TIMOUT = 10;                    \nuint32_t FRACT_NUMBER = 25600000; \ndouble G = 9.81;\nconst double PI = boost::math::constants::pi<double>();\nint TEMP_BUF_SIZE = 200;\nint NUM_OF_IMUS = 1;\nint NUM_OF_TS_FIELDS = 4;\nint NUM_OF_IMU_FIELDS = 7;\nint PLD_STRT_INDX = 2; // payload starting index in received string line\n\nconst uint8_t OUTPUT_DATA_LENGTH_BYTES = 5;\nuint8_t ALIGN_FRAMES_CMD = 34;\nuint8_t START_TRIGGER_CMD = 56;\nuint8_t STOP_TRIGGER_CMD = 57;\n\nuint8_t output_buffer[OUTPUT_DATA_LENGTH_BYTES];\nuint32_t CAMERAS_TIM_FRACT_NUMBER = 2560000; \nuint32_t alignment_subs = 0;\nuint32_t alignment_subs_old = 0;\nros::Time last_cameras_ts = ros::Time(0);\nfloat CAMERAS_FRAME_RATE = 30.0;\nfloat SAMSUNG_CAMERA_FRAME_RATE = 30.0;\nfloat SAMSUNG_CAMERA_FRAMING_PERIOD = 1.0 / SAMSUNG_CAMERA_FRAME_RATE;\ndouble MANUAL_ADDITION = 0.005493;//-0.01243;//0.02064;//+0.0123; //sec\ndouble phase_old = 0;\n\nclass FieldsCount{\n  public:\n    int count;   \n    FieldsCount (int start = 0) {\n        count = start;\n    }\n    void add (int additive) {\n        count += additive;\n    }\n    int current (void) {\n        return count;\n    }\n};\n\nstd::vector<int16_t> string_to_ints(std::string str, int start_from = 0) { \n    std::stringstream ss;    \n    /* Storing the whole string into string stream */\n    ss << str.substr(start_from); \n    /* Running loop till the end of the stream */\n    std::string temp; \n    int found; \n    \n    std::vector<int16_t> ints;        \n\n    while (!ss.eof()) { \n        /* extracting word by word from stream */\n        ss >> temp; \n        /* Checking the given word is integer or not */\n        if (std::stringstream(temp) >> std::hex >> found) {\n            ints.push_back(static_cast<int16_t>(found));\n        }\n        temp = \"\"; \n    } \n    return ints;\n} \n\nstd::vector<int16_t> subvector(std::vector<int16_t> const &initial_v, int starting_index) {\n   std::vector<int16_t> sub_v(initial_v.begin() + starting_index, initial_v.end());\n   return sub_v;\n}\n\nros::Time ints_to_board_ts(std::vector<int16_t> input_ints, FieldsCount * fc_pointer, int first_element=0) {\n\tstd::vector<int16_t> ints = subvector(input_ints, fc_pointer->current());\n\t\n\tdouble secs = static_cast<uint16_t>(ints[0]) * 60.0 + static_cast<uint16_t>(ints[1]) * 1.0 + static_cast<uint32_t>(ints[2]<<16 | static_cast<uint16_t>(ints[3]))*1.0/FRACT_NUMBER;\n\tros::Time board_ts = ros::Time(secs);\n\n    fc_pointer->add(NUM_OF_TS_FIELDS);\n    return board_ts;\n}\n\nboost::numeric::ublas::vector<double> ints_to_imu_meas(std::vector<int16_t> input_ints, FieldsCount * fc_pointer, int first_element=0) {\n    std::vector<int16_t> ints = subvector(input_ints, fc_pointer->current());\n    boost::numeric::ublas::vector<double> imu_meas(NUM_OF_IMU_FIELDS);\n    for (int i = 0; i < imu_meas.size(); i++) {\n        // acc\n        if (i < 3) {\n            imu_meas(i) = ints[i] / 16384.0 * G;\n        }\n        // temperature\n        else if (i == 3) {\n            imu_meas(i) = ints[3] / 340.0 + 35.0;\n        }\n        // gyro\n        else if (i >= 3) {\n            imu_meas(i) =  ints[i] / 131.0 / 180.0 * PI;\n        }\n    }\n\n    fc_pointer->add(NUM_OF_IMU_FIELDS);\n    return imu_meas;\n}\n\nvoid publish_imu(ros::Publisher pub, uint8_t imu_n, ros::Time ts, boost::numeric::ublas::vector<double> imu_meas) {\n    // publish_imu data [a in m/s^2] and [w in rad/s]\n    std::string frame_id = IMU_TOPIC + std::to_string(imu_n);\n    sensor_msgs::Imu msg;\n\n    msg.header.frame_id = frame_id;\n    msg.header.stamp = ts;\n    // linear_acceleration\n    msg.linear_acceleration.x = imu_meas[0];\n    msg.linear_acceleration.y = imu_meas[1];\n    msg.linear_acceleration.z = imu_meas[2];\n    // angular_velocity\n    msg.angular_velocity.x = imu_meas[4];\n    msg.angular_velocity.y = imu_meas[5];\n    msg.angular_velocity.z = imu_meas[6];\n    // Publish the message.\n    pub.publish(msg);\n}\n\nvoid publish_imu_temperature(ros::Publisher pub, uint8_t imu_n, ros::Time ts, boost::numeric::ublas::vector<double> imu_meas) {\n    std::string frame_id = IMU_TOPIC + std::to_string(imu_n) + IMU_TEMP_TOPIC_POSTFIX;\n    sensor_msgs::Temperature msg;\n\n    msg.header.frame_id = frame_id;\n    msg.header.stamp = ts;\n    msg.temperature = imu_meas[3];\n    \n    pub.publish(msg);\n}\n\nvoid publish_cameras_ts(ros::Publisher pub, ros::Time ts) {\n    std::string frame_id = CAMERAS_TS_TOPIC;\n    sensor_msgs::TimeReference msg;\n\n    msg.header.frame_id = frame_id;\n    msg.header.stamp = ts;\n    msg.time_ref = ros::Time::now();\n    pub.publish(msg);\n}\n\nvoid publish_lidar_ts(ros::Publisher pub, ros::Time ts) {\n    std::string frame_id = LIDAR_TS_TOPIC;\n    sensor_msgs::TimeReference msg;\n\n    msg.header.frame_id = frame_id;\n    msg.header.stamp = ts;\n    msg.time_ref = ros::Time::now();\n    pub.publish(msg);\n}\n\nvoid publish_s10_ts(ros::Publisher pub, ros::Time mcu_ts, ros::Time s10_ts) {\n    std::string frame_id = S10_TS_TOPIC;\n    sensor_msgs::TimeReference msg;\n\n    msg.header.frame_id = frame_id;\n    msg.header.stamp = mcu_ts;\n    msg.time_ref = s10_ts;\n    pub.publish(msg);\n}\n\nvoid pub_distributer(std::string str) {\n}\n\n\n// dynamic reconfigure callback\nvoid dynamic_reconfigure_callback(mcu_interface::parametersConfig &config, uint32_t level)\n{\n    if (config.start_sync)\n    {\n        // Marsel, here goes the sync function/code only when set to True\n        ROS_WARN(\"dynamic_reconfigure_callback: Flag set to True\");//TODO change/remove this\n    }\n}\n\nvoid send_to_mcu(serial::Serial *serial, uint8_t cmd, uint32_t data=0) {\n    uint8_t buf[OUTPUT_DATA_LENGTH_BYTES];\n    buf[0] = cmd;\n    for(uint8_t i=1; i<OUTPUT_DATA_LENGTH_BYTES; i++) {\n            buf[i] = (uint8_t)(data >> ((i-1) * 8));\n    }\n    serial->write(buf, OUTPUT_DATA_LENGTH_BYTES);\n}\n// Service server\nbool align_phase(mcu_interface::AlignMcuCamPhase::Request  &req,\n         mcu_interface::AlignMcuCamPhase::Response &res, serial::Serial *serial)\n{\n    double phase = req.a + MANUAL_ADDITION;\n    ROS_WARN(\"phase %f\", phase);\n\n    double delta = phase - last_cameras_ts.toSec();\n    ROS_WARN(\"last_cameras_ts.toSec() %f\", last_cameras_ts.toSec());\n    ROS_WARN(\"delta = phase - last_ts %f\", delta);\n    \n    double delta_mod = std::fmod(delta, SAMSUNG_CAMERA_FRAMING_PERIOD);\n    ROS_WARN(\"delta_mod %f\", delta_mod);\n\n    double delta_mod_pos = 0;\n    if (delta_mod < 0) {\n        delta_mod_pos = delta_mod + SAMSUNG_CAMERA_FRAMING_PERIOD;\n    }\n    ROS_WARN(\"delta_mod_pos %f\", delta_mod_pos);\n\n    double subs = delta_mod_pos * CAMERAS_TIM_FRACT_NUMBER * CAMERAS_FRAME_RATE; //-1\n    ROS_WARN(\"subs %f\", subs);\n    \n    alignment_subs = static_cast<uint32_t> (std::round(subs));\n    //alignment_subs = 0x1A2B3C4D;//static_cast<uint32_t> (std::round(req.a));\n    //ROS_WARN(\"alignment_subs %x\\n\", alignment_subs);\n    ROS_WARN(\"alignment_subs %d\\n\", alignment_subs);\n    send_to_mcu(serial, ALIGN_FRAMES_CMD, alignment_subs);\n    //serial->write((uint8_t *)&alignment_subs, 4);\n    \n    // Stub\n    res.response = \"done\";\n    //ROS_WARN(\"sending back response: [%s]\", res.response.c_str());\n\n    // Writing debug info into file\n    time_t t = time(0);   // get time now\n    struct tm * now = localtime( & t );\n\n    char buffer [90];\n    strftime(buffer, 90, \"/home/mrob/samsung-avatar-dataset-sync/out/mcu_interface/%m(%b)%d_%Y_%H%M%S.csv\", now);\n    std::ofstream my_file(buffer);\n    //my_file.open (buffer);\n    //std::string temp(buffer)\n    //ROS_WARN(\"%s\", temp.c_str());\n    ROS_WARN(buffer);\n    if(my_file.is_open()) {\n        my_file << \"phase,\" << phase << std::endl;\n        my_file << \"last_cameras_ts.toSec(),\" << last_cameras_ts.toSec() << std::endl;\n        my_file << \"delta = phase - last_ts,\" << delta << std::endl;\n        my_file << \"delta_mod,\" << delta_mod << std::endl;\n        my_file << \"delta_mod_pos,\" << delta_mod_pos << std::endl;\n        my_file << \"subs,\" << subs << std::endl;\n        my_file << \"alignment_subs,\" << alignment_subs << std::endl;\n    }\n    else {\n        ROS_WARN(\"error\");\n    }\n    my_file.close();\n\n    return true;\n}\n\nbool start_triggering(mcu_interface::StartMcuCamTriggering::Request  &req,\n         mcu_interface::StartMcuCamTriggering::Response &res, serial::Serial *serial)\n{\n    send_to_mcu(serial, START_TRIGGER_CMD);\n\n    // Stub\n    res.response = \"done\";\n    ROS_WARN(\"start_triggering OK\");\n    return true;\n}\n\nbool publish_s10_to_mcu_offset(mcu_interface::PublishS10ToMcuOffset::Request  &req,\n         mcu_interface::PublishS10ToMcuOffset::Response &res, ros::Publisher *pub)\n{\n    publish_s10_ts(*pub, ros::Time(last_cameras_ts), ros::Time(last_cameras_ts.toSec() + req.offset));\n    // Stub\n    res.response = \"done\";\n    //ROS_WARN(\"sending back response: [%s]\", res.response.c_str());\n    return true;\n}\n\nint main(int argc, char **argv) {\n    // Register signal and signal handler\n    if (argc < 2) {\n        std::cout << \"Please, specify serial device. For example, \\\"/dev/ttyUSB0\\\"\" << std::endl;\n        return 0;\n    }\n    \n    PORT = argv[1];\n    bool board_starting_ts_is_read = false;\n    std::string str;\n    \n    ros::Time sys_starting_ts, board_starting_ts, ts, ts_old;\n    ros::Duration delta_ts;\n    // Initialize the ROS system and become a node.\n    ros::init(argc, argv, \"mcu_interface\");\n    \n\n    // Create a publisher object.\n    ros::NodeHandle nh;\n    ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>(IMU_TOPIC, RATE);\n\tros::Publisher imu_temp_pub = nh.advertise<sensor_msgs::Temperature>(IMU_TEMP_TOPIC, RATE);\n\tros::Publisher cameras_ts_pub = nh.advertise<sensor_msgs::TimeReference>(CAMERAS_TS_TOPIC, RATE);\n\tros::Publisher lidar_ts_pub = nh.advertise<sensor_msgs::TimeReference>(LIDAR_TS_TOPIC, RATE);\n    ros::Publisher s10_ts_pub = nh.advertise<sensor_msgs::TimeReference>(S10_TS_TOPIC, 2, true);\n    \n\t// Configure dynamic reconfigure\n\tdynamic_reconfigure::Server<mcu_interface::parametersConfig> server;\n    dynamic_reconfigure::Server<mcu_interface::parametersConfig>::CallbackType f;\n    f = boost::bind(&dynamic_reconfigure_callback, _1, _2);\n    server.setCallback(f);\n\t\n\t// open port, baudrate, timeout in milliseconds\n    serial::Serial serial(PORT, BAUD, serial::Timeout::simpleTimeout(TIMOUT));\n    \n    // Service configure\n    ros::ServiceServer phase_align_service = nh.advertiseService<mcu_interface::AlignMcuCamPhase::Request, mcu_interface::AlignMcuCamPhase::Response>(\n        \"align_mcu_cam_phase\", boost::bind(align_phase, _1, _2, &serial));\n\n    ros::ServiceServer camera_start_service = nh.advertiseService<mcu_interface::StartMcuCamTriggering::Request, mcu_interface::StartMcuCamTriggering::Response>(\n        \"start_mcu_cam_triggering\", boost::bind(start_triggering, _1, _2, &serial));\n\n    ros::ServiceServer publish_s10_to_mcu_offset_service = nh.advertiseService<mcu_interface::PublishS10ToMcuOffset::Request, mcu_interface::PublishS10ToMcuOffset::Response>(\n        \"publish_s10_to_mcu_offset\", boost::bind(publish_s10_to_mcu_offset, _1, _2, &s10_ts_pub));\n\n\n    // check if serial port open\n    std::cout << \"Serial port is...\";\n    if(serial.isOpen())\n        std::cout << \" open.\" << std::endl;\n    else\n        std::cout << \" not open!\" << std::endl;\n\n    // Clean from possibly broken string\n    while(serial.available() < TEMP_BUF_SIZE) {\n        str = serial.readline(); \n        if(str.at(str.size()-1)=='\\n') {\n            break;\n        }\n    }\n\n    //publish_s10_ts(s10_ts_pub, ros::Time(0.5), ros::Time(50));\n    //ros::Time some1 = ros::Time::now();\n    //uint8_t flag_some = 1;\n    //serial.write((uint8_t *)&alignment_subs, 4);\n    //send_to_mcu(&serial, START_TRIGGER_CMD);\n\n    // Main loop\n    while(ros::ok()) {\n        if(serial.available() > TEMP_BUF_SIZE) {\n            str = serial.readline();\n            //std::cout << str << std::endl;\n            std::vector<int16_t> ints = string_to_ints(str, PLD_STRT_INDX);\n            FieldsCount fields_count;\n            ros::Time ts = ints_to_board_ts(ints, &fields_count);\n\t\t   \tswitch (str.at(0)) {\n\t\t\t\tcase 'i': {\n\t\t\t\t\tboost::numeric::ublas::vector<double> imu_meas;\n\t\t\t\t\timu_meas = ints_to_imu_meas(ints, &fields_count);\n\t\t\t\t\tpublish_imu(imu_pub, 0, ts, imu_meas);\n\t\t\t\t\tpublish_imu_temperature(imu_temp_pub, 0, ts, imu_meas);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'c': {\n\t\t\t\t\tpublish_cameras_ts(cameras_ts_pub, ts);\n                    last_cameras_ts = ts;\n                    //ROS_WARN(\"phase=phase*CAMERAS_TIM_FRACT_NUMBER %f\", last_cameras_ts.toSec());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'l': {\n                    publish_lidar_ts(lidar_ts_pub, ts);\n                    //ROS_WARN(\"%s\", str.c_str());\n                    //std::cout << ts << std::endl;\n                    //publish_s10_ts(s10_ts_pub, ros::Time(0.5), ros::Time(50));\n                    break;\n                }\n                case 't': {\n                    ROS_WARN(\"%s\", str.c_str());\n                    break;\n                }\n\t\t\t}\n\t\t\tros::spinOnce();// this checks for callbacks (dynamic reconfigure)\n\t    }\n        //if (flag_some == 1 && (ros::Time::now() - some1).toSec() > 5) {\n            //send_to_mcu(&serial, START_TRIGGER_CMD);\n            //serial.write((uint8_t *)&alignment_subs, 5);\n            //flag_some = 0;\n            //ROS_WARN(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\");\n        //}\n\t    usleep(100);\n\t}\n    send_to_mcu(&serial, STOP_TRIGGER_CMD);\n}\n", "meta": {"hexsha": "19dc9b78c2842001f5b0fe9f9f3db132f4d3f7d5", "size": 14405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mcu_interface/src/mcu.cpp", "max_stars_repo_name": "MobileRoboticsSkoltech/smartdepthsync-ros-src", "max_stars_repo_head_hexsha": "7156c846ab89c35a2b30e2ca3d8562e5bd8e3669", "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": "mcu_interface/src/mcu.cpp", "max_issues_repo_name": "MobileRoboticsSkoltech/smartdepthsync-ros-src", "max_issues_repo_head_hexsha": "7156c846ab89c35a2b30e2ca3d8562e5bd8e3669", "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": "mcu_interface/src/mcu.cpp", "max_forks_repo_name": "MobileRoboticsSkoltech/smartdepthsync-ros-src", "max_forks_repo_head_hexsha": "7156c846ab89c35a2b30e2ca3d8562e5bd8e3669", "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.1341463415, "max_line_length": 179, "alphanum_fraction": 0.6521346755, "num_tokens": 3978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.19119742312419763}}
{"text": "#include <math.h>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <sys/types.h>\n//#include <dirent.h>\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"caffe/blob.hpp\"\n#include \"caffe/filler.hpp\"\n#include \"caffe/layers/DenseBlock_layer.hpp\"\n\nnamespace caffe {\n\n\tbool dirExists(string dirStr) {\n\t\t//     const char* dirCStr = dirStr.c_str();\n\t\t//     DIR* dir = opendir(dirCStr);\n\t\t//     if (ENOENT == errno){\n\t\t//       return false;\n\t\t//     }\n\t\t//     closedir(dir);\n\t\treturn true;\n\t}\n\n\tvoid tryCreateDirectory(string fileName) {\n\t\t//     vector<string> strVec;\n\t\t//     boost::split(strVec,fileName,boost::is_any_of(\"/\"));\n\t\t//     string newStr=\"\";\n\t\t//     for (int i=0;i<strVec.size()-1;++i){\n\t\t//       newStr += strVec[i] + (i==strVec.size()-2?\"\":\"/\");\n\t\t//     }\n\t\t//     boost::filesystem::path dirToCreate(newStr);\n\t\t//     if (!dirExists(newStr)){\n\t\t//       boost::filesystem::create_directories(dirToCreate);\n\t\t//     }\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) \n\t{\n\t\tthis->cpuInited = false;\n// #ifndef CPU_ONLY\n// \t\tthis->gpuInited = false;\n// #endif\n\n\t\tthis->N = bottom[0]->shape()[0];\n\t\tthis->H = bottom[0]->shape()[2];\n\t\tthis->W = bottom[0]->shape()[3];\n\n\t\tDenseBlockParameter dbParam = this->layer_param_.denseblock_param();\n\t\tthis->numTransition = dbParam.numtransition();\n\t\t//this->initChannel = dbParam.initchannel();\n\t\tthis->initChannel = bottom[0]->channels();//modified by jxs\n\t\tthis->growthRate = dbParam.growthrate();\n\t\tthis->trainCycleIdx = 0; //initially, trainCycleIdx = 0\n\t\tthis->EMA_decay = dbParam.moving_average_fraction();\n#ifndef CPU_ONLY\n\t\tthis->workspace_size_bytes = dbParam.workspace_mb() * 1024 * 1024;\n\t\tthis->gpu_idx_ = dbParam.gpuidx();\n#endif\n\t\tthis->useDropout = dbParam.use_dropout();\n\t\tthis->dropoutAmount = dbParam.dropout_amount();\n\t\tthis->DB_randomSeed = 124816;\n\t\tthis->useBC = dbParam.use_bc();\n\t\tthis->BC_ultra_spaceEfficient = dbParam.bc_ultra_space_efficient();\n\t\t//Parameter Blobs\n\t//for transition i, \n\t//blobs_[i] is its filter blob\n\t//blobs_[numTransition + i] is its scaler blob\n\t//blobs_[2*numTransition + i] is its bias blob\n\t//blobs_[3*numTransition + i] is its globalMean\n\t//blobs_[4*numTransition + i] is its globalVar\n\t\tif (useBC) {\n\t\t\tthis->blobs_.resize(10 * this->numTransition + 1);\n\t\t}\n\t\telse {\n\t\t\tthis->blobs_.resize(5 * this->numTransition + 1);\n\t\t}\n\t\tfor (int transitionIdx = 0; transitionIdx < this->numTransition; ++transitionIdx) {\n\t\t\t//filter\n\t\t\t//No BC case\n\t\t\tif (!useBC) {\n\t\t\t\tint inChannels = initChannel + transitionIdx * growthRate;\n\t\t\t\tint filterShape_Arr[] = { growthRate,inChannels,3,3 };\n\t\t\t\tvector<int> filterShape(filterShape_Arr, filterShape_Arr + 4);\n\t\t\t\tthis->blobs_[transitionIdx].reset(new Blob<Dtype>(filterShape));\n\t\t\t\tshared_ptr<Filler<Dtype> > filter_Filler(GetFiller<Dtype>(dbParam.filter_filler()));\n\t\t\t\tfilter_Filler->Fill(this->blobs_[transitionIdx].get());\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//3*3 kernel\n\t\t\t\tint filter_33_shapeArr[] = { growthRate,4 * growthRate,3,3 };\n\t\t\t\tvector<int> filter33Shape(filter_33_shapeArr, filter_33_shapeArr + 4);\n\t\t\t\tthis->blobs_[transitionIdx].reset(new Blob<Dtype>(filter33Shape));\n\t\t\t\tshared_ptr<Filler<Dtype> > filter_Filler3(GetFiller<Dtype>(dbParam.filter_filler()));\n\t\t\t\tfilter_Filler3->Fill(this->blobs_[transitionIdx].get());\n\n\t\t\t\t//1*1 kernel\n\t\t\t\tint inChannels = initChannel + transitionIdx * growthRate;\n\t\t\t\tint filter_11_shapeArr[] = { 4 * growthRate,inChannels,1,1 };\n\t\t\t\tvector<int> filter11Shape(filter_11_shapeArr, filter_11_shapeArr + 4);\n\t\t\t\tthis->blobs_[5 * numTransition + transitionIdx].reset(new Blob<Dtype>(filter11Shape));\n\t\t\t\tshared_ptr<Filler<Dtype> > filter_Filler1(GetFiller<Dtype>(dbParam.filter_filler()));\n\t\t\t\tfilter_Filler1->Fill(this->blobs_[5 * numTransition + transitionIdx].get());\n\t\t\t}\n\t\t\t//scaler & bias\n\t\t\tint inChannels = initChannel + transitionIdx * growthRate;\n\t\t\tint BNparamShape_Arr[] = { 1,inChannels,1,1 };\n\t\t\tvector<int> BNparamShape(BNparamShape_Arr, BNparamShape_Arr + 4);\n\t\t\t//scaler\n\t\t\tthis->blobs_[numTransition + transitionIdx].reset(new Blob<Dtype>(BNparamShape));\n\t\t\tshared_ptr<Filler<Dtype> > weight_filler0(GetFiller<Dtype>(dbParam.bn_scaler_filler()));\n\t\t\tweight_filler0->Fill(this->blobs_[numTransition + transitionIdx].get());\n\n\t\t\tint BN_4G_Shape[] = { 1,4 * growthRate,1,1 };\n\t\t\tvector<int> BN_4Gparam_ShapeVec(BN_4G_Shape, BN_4G_Shape + 4);\n\t\t\t//scaler BC\n\t\t\tif (useBC) {\n\t\t\t\tthis->blobs_[6 * numTransition + transitionIdx].reset(new Blob<Dtype>(BN_4Gparam_ShapeVec));\n\t\t\t\tshared_ptr<Filler<Dtype> > weight_filler0_4G(GetFiller<Dtype>(dbParam.bn_scaler_filler()));\n\t\t\t\tweight_filler0_4G->Fill(this->blobs_[6 * numTransition + transitionIdx].get());\n\t\t\t}\n\t\t\t//bias\n\t\t\tthis->blobs_[2 * numTransition + transitionIdx].reset(new Blob<Dtype>(BNparamShape));\n\t\t\tshared_ptr<Filler<Dtype> > weight_filler1(GetFiller<Dtype>(dbParam.bn_bias_filler()));\n\t\t\tweight_filler1->Fill(this->blobs_[2 * numTransition + transitionIdx].get());\n\t\t\t//bias BC\n\t\t\tif (useBC) {\n\t\t\t\tthis->blobs_[7 * numTransition + transitionIdx].reset(new Blob<Dtype>(BN_4Gparam_ShapeVec));\n\t\t\t\tshared_ptr<Filler<Dtype> > weight_filler1_4G(GetFiller<Dtype>(dbParam.bn_bias_filler()));\n\t\t\t\tweight_filler1_4G->Fill(this->blobs_[7 * numTransition + transitionIdx].get());\n\t\t\t}\n\t\t\t//globalMean\n\t\t\tthis->blobs_[3 * numTransition + transitionIdx].reset(new Blob<Dtype>(BNparamShape));\n\t\t\tfor (int blobIdx = 0; blobIdx < inChannels; ++blobIdx) {\n\t\t\t\tshared_ptr<Blob<Dtype> > localB = this->blobs_[3 * numTransition + transitionIdx];\n\t\t\t\tlocalB->mutable_cpu_data()[localB->offset(0, blobIdx, 0, 0)] = 0;\n\t\t\t}\n\t\t\t//globalMean BC\n\t\t\tif (useBC) {\n\t\t\t\tthis->blobs_[8 * numTransition + transitionIdx].reset(new Blob<Dtype>(BN_4Gparam_ShapeVec));\n\t\t\t\tshared_ptr<Blob<Dtype> > localB = this->blobs_[8 * numTransition + transitionIdx];\n\t\t\t\tfor (int blobIdx = 0; blobIdx < 4 * growthRate; ++blobIdx) {\n\t\t\t\t\tlocalB->mutable_cpu_data()[localB->offset(0, blobIdx, 0, 0)] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//globalVar\n\t\t\tthis->blobs_[4 * numTransition + transitionIdx].reset(new Blob<Dtype>(BNparamShape));\n\t\t\tfor (int blobIdx = 0; blobIdx < inChannels; ++blobIdx) {\n\t\t\t\tshared_ptr<Blob<Dtype> > localB = this->blobs_[4 * numTransition + transitionIdx];\n\t\t\t\tlocalB->mutable_cpu_data()[localB->offset(0, blobIdx, 0, 0)] = 1;\n\t\t\t}\n\t\t\t//globalVar BC\n\t\t\tif (useBC) {\n\t\t\t\tthis->blobs_[9 * numTransition + transitionIdx].reset(new Blob<Dtype>(BN_4Gparam_ShapeVec));\n\t\t\t\tshared_ptr<Blob<Dtype> > localB = this->blobs_[9 * numTransition + transitionIdx];\n\t\t\t\tfor (int blobIdx = 0; blobIdx < 4 * growthRate; ++blobIdx) {\n\t\t\t\t\tlocalB->mutable_cpu_data()[localB->offset(0, blobIdx, 0, 0)] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//final parameter for the equivalent of blobs_[2] in Caffe-BN\n\t\tvector<int> singletonShapeVec;\n\t\tsingletonShapeVec.push_back(1);\n\t\tint singletonIdx = useBC ? 10 * numTransition : 5 * numTransition;\n\t\tthis->blobs_[singletonIdx].reset(new Blob<Dtype>(singletonShapeVec));\n\t\tthis->blobs_[singletonIdx]->mutable_cpu_data()[0] = Dtype(0);\n\t\t//parameter specification: globalMean/Var weight decay and lr is 0\n\t\tif (!useBC) {\n\t\t\tfor (int i = 0; i < this->blobs_.size(); ++i) {\n\t\t\t\tif (this->layer_param_.param_size() != i) {\n\t\t\t\t\tCHECK_EQ(0, 1)\n\t\t\t\t\t\t<< \"Nope\";\n\t\t\t\t}\n\t\t\t\tParamSpec* fixed_param_spec = this->layer_param_.add_param();\n\t\t\t\t//global Mean/Var\n\t\t\t\tif (i >= 3 * this->numTransition) {\n\t\t\t\t\tfixed_param_spec->set_lr_mult(0.f);\n\t\t\t\t\tfixed_param_spec->set_decay_mult(0.f);\n\t\t\t\t}\n\t\t\t\t//BN Scaler and Bias\n\t\t\t\telse if (i >= this->numTransition) {\n\t\t\t\t\tfixed_param_spec->set_lr_mult(1.f);\n\t\t\t\t\tfixed_param_spec->set_decay_mult(1.f);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfixed_param_spec->set_lr_mult(1.f);\n\t\t\t\t\tfixed_param_spec->set_decay_mult(1.f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int i = 0; i < this->blobs_.size(); ++i) {\n\t\t\t\tif (this->layer_param_.param_size() != i) {\n\t\t\t\t\tCHECK_EQ(0, 1)\n\t\t\t\t\t\t<< \"Nope\";\n\t\t\t\t}\n\t\t\t\tParamSpec* fixed_param_spec = this->layer_param_.add_param();\n\t\t\t\tif ((i >= 3 * numTransition) && (i < 5 * numTransition)) {\n\t\t\t\t\tfixed_param_spec->set_lr_mult(0.f);\n\t\t\t\t\tfixed_param_spec->set_decay_mult(0.f);\n\t\t\t\t}\n\t\t\t\telse if (i >= 8 * numTransition) {\n\t\t\t\t\tfixed_param_spec->set_lr_mult(0.f);\n\t\t\t\t\tfixed_param_spec->set_decay_mult(0.f);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfixed_param_spec->set_lr_mult(1.f);\n\t\t\t\t\tfixed_param_spec->set_decay_mult(1.f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n#ifndef CPU_ONLY\n\t\tGPU_Initialization();\n#endif\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {\n\t\tint batch_size = bottom[0]->shape()[0];\n\t\tint h = bottom[0]->shape()[2];\n\t\tint w = bottom[0]->shape()[3];\n\n#ifndef CPU_ONLY\n\t\treshape_gpu_data(this->H, this->W,this->N, h, w,batch_size);\n#endif\n\t\tthis->N = batch_size;\n\t\tthis->H = h;\n\t\tthis->W = w;\n\t\tint topShapeArr[] = { this->N, this->initChannel + this->numTransition*this->growthRate,this->H,this->W };\n\t\tvector<int> topShape(topShapeArr, topShapeArr + 4);\n\t\ttop[0]->Reshape(topShape);\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::syncBlobs(DenseBlockLayer<Dtype>* originLayer) {\n\t\tvector<shared_ptr<Blob<Dtype> > >& originBlobs = originLayer->blobs();\n\t\tfor (int blobIdx = 0; blobIdx < originBlobs.size(); ++blobIdx) {\n\t\t\tshared_ptr<Blob<Dtype> > localBlob = originBlobs[blobIdx];\n\t\t\tBlob<Dtype> * newBlob = new Blob<Dtype>(localBlob->shape());\n\t\t\tnewBlob->CopyFrom(*(localBlob.get()), false);\n\t\t\tshared_ptr<Blob<Dtype> > sharedPtrBlob(newBlob);\n\t\t\tthis->blobs_[blobIdx] = sharedPtrBlob;\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::setLogId(int uid) {\n\t\tthis->logId = uid;\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid logBlob(Blob<Dtype>* B, string fileName) {\n\t\tstring dataNameStr = fileName + \"_data\";\n\t\tstring gradNameStr = fileName + \"_grad\";\n\t\tconst char* dataName = (dataNameStr).c_str();\n\t\tconst char* gradName = (gradNameStr).c_str();\n\n\t\ttryCreateDirectory(dataName);\n\t\ttryCreateDirectory(gradName);\n\t\tstd::ofstream outWriter_data(dataName, std::ofstream::out);\n\t\tstd::ofstream outWriter_grad(gradName, std::ofstream::out);\n\t\tfor (int n = 0; n < B->shape(0); ++n) {\n\t\t\tfor (int c = 0; c < B->shape(1); ++c) {\n\t\t\t\tfor (int h = 0; h < B->shape(2); ++h) {\n\t\t\t\t\tfor (int w = 0; w < B->shape(3); ++w) {\n\t\t\t\t\t\toutWriter_data << B->data_at(n, c, h, w) << \",\";\n\t\t\t\t\t\toutWriter_grad << B->diff_at(n, c, h, w) << \",\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toutWriter_data << std::endl;\n\t\toutWriter_grad << std::endl;\n\t}\n\n\tstring itos(int i) {\n\t\tstring output = boost::lexical_cast<string>(i);\n\t\treturn output;\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::logInternal_cpu(string dir) {\n\t\tstring localDir = dir + \"/cpu_\" + itos(this->logId) + \"/\";\n\t\t//batch_Mean\n\t\tfor (int i = 0; i < this->batch_Mean.size(); ++i) {\n\t\t\tstring blobStr = localDir + \"batch_Mean_\" + itos(i);\n\t\t\tlogBlob(this->batch_Mean[i], blobStr);\n\t\t}\n\t\t//batch_Var\n\t\tfor (int i = 0; i < this->batch_Var.size(); ++i) {\n\t\t\tstring blobStr = localDir + \"batch_Var_\" + itos(i);\n\t\t\tlogBlob(this->batch_Var[i], blobStr);\n\t\t}\n\t\tif (useBC) {\n\t\t\t//batch_Mean\n\t\t\tfor (int i = 0; i < this->batch_Mean4G.size(); ++i) {\n\t\t\t\tstring blobStr = localDir + \"batch_Mean_BC_\" + itos(i);\n\t\t\t\tlogBlob(this->batch_Mean4G[i], blobStr);\n\t\t\t}\n\t\t\t//batch_Var\n\t\t\tfor (int i = 0; i < this->batch_Var4G.size(); ++i) {\n\t\t\t\tstring blobStr = localDir + \"batch_Var_BC_\" + itos(i);\n\t\t\t\tlogBlob(this->batch_Var4G[i], blobStr);\n\t\t\t}\n\t\t}\n\t\t//merged_conv\n\t\tfor (int i = 0; i < this->merged_conv.size(); ++i) {\n\t\t\tstring blobStr = localDir + \"merged_conv_\" + itos(i);\n\t\t\tlogBlob(this->merged_conv[i], blobStr);\n\t\t}\n\t\t//BN_XhatVec\n\t\tfor (int i = 0; i < this->BN_XhatVec.size(); ++i) {\n\t\t\tstring blobStr = localDir + \"BN_XhatVec_\" + itos(i);\n\t\t\tlogBlob(this->BN_XhatVec[i], blobStr);\n\t\t}\n\t\t//postBN_blobVec\n\t\tfor (int i = 0; i < this->postBN_blobVec.size(); ++i) {\n\t\t\tstring blobStr = localDir + \"postBN_blobVec_\" + itos(i);\n\t\t\tlogBlob(this->postBN_blobVec[i], blobStr);\n\t\t}\n\t\t//postReLU_blobVec\n\t\tfor (int i = 0; i < this->postReLU_blobVec.size(); ++i) {\n\t\t\tstring blobStr = localDir + \"postReLU_blobVec_\" + itos(i);\n\t\t\tlogBlob(this->postReLU_blobVec[i], blobStr);\n\t\t}\n\t\t//postConv_blobVec\n\t\tfor (int i = 0; i < this->postConv_blobVec.size(); ++i) {\n\t\t\tstring blobStr = localDir + \"postConv_blobVec_\" + itos(i);\n\t\t\tlogBlob(this->postConv_blobVec[i], blobStr);\n\t\t}\n\t\tif (useBC) {\n\t\t\t//BC_BN_XhatVec\n\t\t\tfor (int i = 0; i < this->BC_BN_XhatVec.size(); ++i) {\n\t\t\t\tstring blobStr = localDir + \"BC_BN_XhatVec_\" + itos(i);\n\t\t\t\tlogBlob(this->BC_BN_XhatVec[i], blobStr);\n\t\t\t}\n\t\t\t//postBN_BCVec\n\t\t\tfor (int i = 0; i < this->postBN_BCVec.size(); ++i) {\n\t\t\t\tstring blobStr = localDir + \"postBN_BCVec_\" + itos(i);\n\t\t\t\tlogBlob(this->postBN_BCVec[i], blobStr);\n\t\t\t}\n\t\t\t//postReLU_BCVec\n\t\t\tfor (int i = 0; i < this->postReLU_BCVec.size(); ++i) {\n\t\t\t\tstring blobStr = localDir + \"postReLU_BCVec_\" + itos(i);\n\t\t\t\tlogBlob(this->postReLU_BCVec[i], blobStr);\n\t\t\t}\n\t\t\t//postConv_BCVec\n\t\t\tfor (int i = 0; i < this->postConv_BCVec.size(); ++i) {\n\t\t\t\tstring blobStr = localDir + \"postConv_BCVec_\" + itos(i);\n\t\t\t\tlogBlob(this->postConv_BCVec[i], blobStr);\n\t\t\t}\n\t\t}\n\t\t//filter\n\t\tfor (int i = 0; i < this->numTransition; ++i) {\n\t\t\tstring blobStr = localDir + \"filter_\" + itos(i);\n\t\t\tlogBlob(this->blobs_[i].get(), blobStr);\n\t\t}\n\t\t//scaler \n\t\tfor (int i = 0; i < this->numTransition; ++i) {\n\t\t\tstring blobStr = localDir + \"scaler_\" + itos(i);\n\t\t\tlogBlob(this->blobs_[this->numTransition + i].get(), blobStr);\n\t\t}\n\t\t//bias\n\t\tfor (int i = 0; i < this->numTransition; ++i) {\n\t\t\tstring blobStr = localDir + \"bias_\" + itos(i);\n\t\t\tlogBlob(this->blobs_[this->numTransition * 2 + i].get(), blobStr);\n\t\t}\n\t\tif (useBC) {\n\t\t\t//filter\n\t\t\tfor (int i = 0; i < this->numTransition; ++i) {\n\t\t\t\tstring blobStr = localDir + \"filter_BC_\" + itos(i);\n\t\t\t\tlogBlob(this->blobs_[5 * numTransition + i].get(), blobStr);\n\t\t\t}\n\t\t\t//scaler \n\t\t\tfor (int i = 0; i < this->numTransition; ++i) {\n\t\t\t\tstring blobStr = localDir + \"scaler_BC_\" + itos(i);\n\t\t\t\tlogBlob(this->blobs_[6 * numTransition + i].get(), blobStr);\n\t\t\t}\n\t\t\t//bias\n\t\t\tfor (int i = 0; i < this->numTransition; ++i) {\n\t\t\t\tstring blobStr = localDir + \"bias_BC_\" + itos(i);\n\t\t\t\tlogBlob(this->blobs_[7 * numTransition + i].get(), blobStr);\n\t\t\t}\n\t\t\t//Mean\n\t\t\tfor (int i = 0; i < this->numTransition; ++i) {\n\t\t\t\tstring blobStr = localDir + \"Mean_BC_\" + itos(i);\n\t\t\t\tlogBlob(this->blobs_[8 * numTransition + i].get(), blobStr);\n\t\t\t}\n\t\t\t//Var\n\t\t\tfor (int i = 0; i < this->numTransition; ++i) {\n\t\t\t\tstring blobStr = localDir + \"Var_BC_\" + itos(i);\n\t\t\t\tlogBlob(this->blobs_[9 * numTransition + i].get(), blobStr);\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tDtype getZeroPaddedValue(bool isDiff, Blob<Dtype>* inputData, int n, int c, int h, int w) {\n\t\tint n_blob = inputData->shape(0);\n\t\tint c_blob = inputData->shape(1);\n\t\tint h_blob = inputData->shape(2);\n\t\tint w_blob = inputData->shape(3);\n\t\tif ((n < 0) || (n >= n_blob)) return 0;\n\t\tif ((c < 0) || (c >= c_blob)) return 0;\n\t\tif ((h < 0) || (h >= h_blob)) return 0;\n\t\tif ((w < 0) || (w >= w_blob)) return 0;\n\t\tif (isDiff) return inputData->diff_at(n, c, h, w);\n\t\telse return inputData->data_at(n, c, h, w);\n\t}\n\n\t//Assumption, h_filter and w_filter must be 3 for now\n\t//naivest possible implementation of convolution, CPU forward and backward should not be used in production.\n\t//CPU version of convolution assume img H,W does not change after convolution, which corresponds to denseBlock without BC\n\t//input of size N*c_input*h_img*w_img\n\ttemplate <typename Dtype>\n\tvoid convolution_Fwd(Blob<Dtype>* input, Blob<Dtype>* output, Blob<Dtype>* filter, int N, int c_output, int c_input, int h_img, int w_img, int h_filter, int w_filter) {\n\t\tint outputShape[] = { N,c_output,h_img,w_img };\n\t\tvector<int> outputShapeVec(outputShape, outputShape + 4);\n\t\toutput->Reshape(outputShapeVec);\n\t\tDtype * outputPtr = output->mutable_cpu_data();\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int c_outIdx = 0; c_outIdx < c_output; ++c_outIdx) {\n\t\t\t\tfor (int hIdx = 0; hIdx < h_img; ++hIdx) {\n\t\t\t\t\tfor (int wIdx = 0; wIdx < w_img; ++wIdx) {\n\t\t\t\t\t\toutputPtr[output->offset(n, c_outIdx, hIdx, wIdx)] = 0;\n\t\t\t\t\t\tfor (int c_inIdx = 0; c_inIdx < c_input; ++c_inIdx) {\n\t\t\t\t\t\t\tfor (int filter_x = 0; filter_x < h_filter; ++filter_x) {\n\t\t\t\t\t\t\t\tfor (int filter_y = 0; filter_y < w_filter; ++filter_y) {\n\t\t\t\t\t\t\t\t\tint localX = hIdx + (h_filter / 2) - filter_x;\n\t\t\t\t\t\t\t\t\tint localY = wIdx + (w_filter / 2) - filter_y;\n\t\t\t\t\t\t\t\t\toutputPtr[output->offset(n, c_outIdx, hIdx, wIdx)] += (filter->data_at(c_outIdx, c_inIdx, filter_x, filter_y) * getZeroPaddedValue(false, input, n, c_inIdx, localX, localY));\n\t\t\t\t\t\t\t\t}\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\t}\n\n\t//beta = 1 Convolution for bottomDiff\n\ttemplate <typename Dtype>\n\tvoid convolution_Bwd(Blob<Dtype>* bottom, Blob<Dtype>* top, Blob<Dtype>* filter, int N, int c_output, int c_input, int h_img, int w_img, int h_filter, int w_filter) {\n\t\tDtype * filterDiffPtr = filter->mutable_cpu_diff();\n\t\tDtype * bottomDiffPtr = bottom->mutable_cpu_diff();\n\t\t//compute FilterGrad\n\t\tfor (int coutIdx = 0; coutIdx < c_output; ++coutIdx) {\n\t\t\tfor (int cinIdx = 0; cinIdx < c_input; ++cinIdx) {\n\t\t\t\tfor (int filter_x = 0; filter_x < h_filter; ++filter_x) {\n\t\t\t\t\tfor (int filter_y = 0; filter_y < w_filter; ++filter_y) {\n\t\t\t\t\t\tDtype localGradSum = 0;\n\t\t\t\t\t\tfor (int n = 0; n < N; ++n) {\n\t\t\t\t\t\t\tfor (int i_img = 0; i_img < h_img; ++i_img) {\n\t\t\t\t\t\t\t\tfor (int j_img = 0; j_img < w_img; ++j_img) {\n\t\t\t\t\t\t\t\t\tint localX = i_img + (h_filter / 2) - filter_x;\n\t\t\t\t\t\t\t\t\tint localY = j_img + (w_filter / 2) - filter_y;\n\t\t\t\t\t\t\t\t\tlocalGradSum += top->diff_at(n, coutIdx, i_img, j_img) * getZeroPaddedValue(false, bottom, n, cinIdx, localX, localY);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfilterDiffPtr[filter->offset(coutIdx, cinIdx, filter_x, filter_y)] = localGradSum;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//compute BottomGrad\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int cinIdx = 0; cinIdx < c_input; ++cinIdx) {\n\t\t\t\tfor (int i_img = 0; i_img < h_img; ++i_img) {\n\t\t\t\t\tfor (int j_img = 0; j_img < w_img; ++j_img) {\n\t\t\t\t\t\tDtype localGradSum = 0;\n\t\t\t\t\t\tfor (int coutIdx = 0; coutIdx < c_output; ++coutIdx) {\n\t\t\t\t\t\t\tfor (int x_img = 0; x_img < h_img; ++x_img) {\n\t\t\t\t\t\t\t\tfor (int y_img = 0; y_img < w_img; ++y_img) {\n\t\t\t\t\t\t\t\t\tint localX = x_img - i_img + (h_filter / 2);\n\t\t\t\t\t\t\t\t\tint localY = y_img - j_img + (w_filter / 2);\n\t\t\t\t\t\t\t\t\tlocalGradSum += top->diff_at(n, coutIdx, x_img, y_img) * getZeroPaddedValue(false, filter, coutIdx, cinIdx, localX, localY);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbottomDiffPtr[bottom->offset(n, cinIdx, i_img, j_img)] = localGradSum;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid ReLU_Fwd(Blob<Dtype>* bottom, Blob<Dtype>* top, int N, int C, int h_img, int w_img) {\n\t\t//Reshape top\n\t\tint topShapeArr[] = { N,C,h_img,w_img };\n\t\tvector<int> topShapeVec(topShapeArr, topShapeArr + 4);\n\t\ttop->Reshape(topShapeVec);\n\t\t//ReLU Fwd\n\t\tDtype* topPtr = top->mutable_cpu_data();\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int cIdx = 0; cIdx < C; ++cIdx) {\n\t\t\t\tfor (int hIdx = 0; hIdx < h_img; ++hIdx) {\n\t\t\t\t\tfor (int wIdx = 0; wIdx < w_img; ++wIdx) {\n\t\t\t\t\t\tDtype bottomData = bottom->data_at(n, cIdx, hIdx, wIdx);\n\t\t\t\t\t\ttopPtr[top->offset(n, cIdx, hIdx, wIdx)] = bottomData >= 0 ? bottomData : 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid ReLU_Bwd(Blob<Dtype>* bottom, Blob<Dtype>* top, int N, int C, int h_img, int w_img) {\n\t\tDtype* bottomDiffPtr = bottom->mutable_cpu_diff();\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int cIdx = 0; cIdx < C; ++cIdx) {\n\t\t\t\tfor (int hIdx = 0; hIdx < h_img; ++hIdx) {\n\t\t\t\t\tfor (int wIdx = 0; wIdx < w_img; ++wIdx) {\n\t\t\t\t\t\tbottomDiffPtr[bottom->offset(n, cIdx, hIdx, wIdx)] = bottom->data_at(n, cIdx, hIdx, wIdx) >= 0 ? top->diff_at(n, cIdx, hIdx, wIdx) : 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tDtype getMean(Blob<Dtype>* A, int channelIdx) {\n\t\tint N = A->shape(0);\n\t\tint H = A->shape(2);\n\t\tint W = A->shape(3);\n\t\tint totalCount = N*H*W;\n\n\t\tDtype sum = 0;\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int h = 0; h < H; ++h) {\n\t\t\t\tfor (int w = 0; w < W; ++w) {\n\t\t\t\t\tsum += A->data_at(n, channelIdx, h, w);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn sum / totalCount;\n\t}\n\n\ttemplate <typename Dtype>\n\tDtype getVar(Blob<Dtype>* A, int channelIdx) {\n\t\tint N = A->shape(0);\n\t\tint H = A->shape(2);\n\t\tint W = A->shape(3);\n\t\tint totalCount = N*H*W;\n\t\tDtype mean = getMean(A, channelIdx);\n\n\t\tDtype sum = 0;\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int h = 0; h < H; ++h) {\n\t\t\t\tfor (int w = 0; w < W; ++w) {\n\t\t\t\t\tsum += (A->data_at(n, channelIdx, h, w) - mean) * (A->data_at(n, channelIdx, h, w) - mean);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn sum / totalCount;\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid BN_inf_Fwd(Blob<Dtype>* input, Blob<Dtype>* output, int N, int C, int h_img, int w_img, Blob<Dtype>* globalMean, Blob<Dtype>* globalVar, Blob<Dtype>* scaler, Blob<Dtype>* bias, Blob<Dtype>* factor_b) {\n\t\tint channelShape[] = { 1,C,1,1 };\n\t\tvector<int> channelShapeVec(channelShape, channelShape + 4);\n\t\tBlob<Dtype>* localInf_Mean = new Blob<Dtype>(channelShapeVec);\n\t\tBlob<Dtype>* localInf_Var = new Blob<Dtype>(channelShapeVec);\n\t\tDtype scale_factor = factor_b->cpu_data()[0] == 0 ? 0 : (1 / factor_b->cpu_data()[0]);\n\t\tcaffe_cpu_scale(localInf_Mean->count(), scale_factor, globalMean->cpu_data(), localInf_Mean->mutable_cpu_data());\n\t\tcaffe_cpu_scale(localInf_Var->count(), scale_factor, globalVar->cpu_data(), localInf_Var->mutable_cpu_data());\n\t\t//Reshape output\n\t\tint outputShape[] = { N,C,h_img,w_img };\n\t\tvector<int> outputShapeVec(outputShape, outputShape + 4);\n\t\toutput->Reshape(outputShapeVec);\n\t\t//BN Fwd inf\n\t\tdouble epsilon = 1e-5;\n\t\tDtype* outputPtr = output->mutable_cpu_data();\n\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int cIdx = 0; cIdx < C; ++cIdx) {\n\t\t\t\tDtype denom = 1.0 / sqrt(localInf_Var->data_at(0, cIdx, 0, 0) + epsilon);\n\t\t\t\tfor (int hIdx = 0; hIdx < h_img; ++hIdx) {\n\t\t\t\t\tfor (int wIdx = 0; wIdx < w_img; ++wIdx) {\n\t\t\t\t\t\toutputPtr[output->offset(n, cIdx, hIdx, wIdx)] = scaler->data_at(0, cIdx, 0, 0) * (denom * (input->data_at(n, cIdx, hIdx, wIdx) - localInf_Mean->data_at(0, cIdx, 0, 0))) + bias->data_at(0, cIdx, 0, 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid BN_train_Fwd(Blob<Dtype>* bottom, Blob<Dtype>* top, Blob<Dtype>* output_xhat, Blob<Dtype>* globalMean, Blob<Dtype>* globalVar, Blob<Dtype>* batchMean, Blob<Dtype>* batchVar, Blob<Dtype>* scaler, Blob<Dtype>* bias, int N, int C, int h_img, int w_img, Dtype EMA_decay) {\n\t\t//reshape output\n\t\tint outputShape[] = { N,C,h_img,w_img };\n\t\tvector<int> outputShapeVec(outputShape, outputShape + 4);\n\t\ttop->Reshape(outputShapeVec);\n\t\toutput_xhat->Reshape(outputShapeVec);\n\t\t//BN Fwd train\n\t\tdouble epsilon = 1e-5;\n\t\t//get batch/global Mean/Var\n\t\tfor (int channelIdx = 0; channelIdx < C; ++channelIdx) {\n\t\t\tint variance_adjust_m = N*h_img*w_img;\n\t\t\t//batch\n\t\t\tDtype* batchMean_mutable = batchMean->mutable_cpu_data();\n\t\t\tDtype* batchVar_mutable = batchVar->mutable_cpu_data();\n\t\t\tbatchMean_mutable[channelIdx] = getMean(bottom, channelIdx);\n\t\t\tbatchVar_mutable[channelIdx] = (variance_adjust_m / (variance_adjust_m - 1.0)) * getVar(bottom, channelIdx);\n\t\t\t//global\n\t\t\tDtype* globalMean_mutable = globalMean->mutable_cpu_data();\n\t\t\tDtype* globalVar_mutable = globalVar->mutable_cpu_data();\n\t\t\tglobalMean_mutable[channelIdx] = EMA_decay * globalMean->data_at(0, channelIdx, 0, 0) + batchMean->data_at(0, channelIdx, 0, 0);\n\t\t\tglobalVar_mutable[channelIdx] = EMA_decay * globalVar->data_at(0, channelIdx, 0, 0) + batchVar->data_at(0, channelIdx, 0, 0);\n\t\t}\n\t\t//process data\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int c = 0; c < C; ++c) {\n\t\t\t\tfor (int h = 0; h < h_img; ++h) {\n\t\t\t\t\tfor (int w = 0; w < w_img; ++w) {\n\t\t\t\t\t\tDtype* xhat_mutable = output_xhat->mutable_cpu_data();\n\t\t\t\t\t\txhat_mutable[output_xhat->offset(n, c, h, w)] = (bottom->data_at(n, c, h, w) - batchMean->data_at(0, c, 0, 0)) / sqrt(batchVar->data_at(0, c, 0, 0) + epsilon);\n\t\t\t\t\t\tDtype* output_mutable = top->mutable_cpu_data();\n\t\t\t\t\t\toutput_mutable[top->offset(n, c, h, w)] = (scaler->data_at(0, c, 0, 0)) * (output_xhat->data_at(n, c, h, w)) + bias->data_at(0, c, 0, 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tbool decide_channelDiffAllZero(Blob<Dtype>* B, int channelIdx, int N, int C, int H, int W) {\n\t\tbool output = true;\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int h = 0; h < H; ++h) {\n\t\t\t\tfor (int w = 0; w < W; ++w) {\n\t\t\t\t\toutput = output && (B->diff_at(n, channelIdx, h, w) < 0.001) && (B->diff_at(n, channelIdx, h, w) > -0.001);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid BN_train_Bwd(Blob<Dtype>* bottom, Blob<Dtype>* bottom_xhat, Blob<Dtype>* top, Blob<Dtype>* batchMean, Blob<Dtype>* batchVar, Blob<Dtype>* scaler, Blob<Dtype>* bias, int N, int C, int h_img, int w_img, bool betaOneData) {\n\t\tdouble epsilon = 1e-5;\n\t\t//bias and scaler grad\n\t\tDtype* biasGrad = bias->mutable_cpu_diff();\n\t\tDtype* scalerGrad = scaler->mutable_cpu_diff();\n\t\tfor (int channelIdx = 0; channelIdx < C; ++channelIdx) {\n\t\t\tbiasGrad[channelIdx] = 0;\n\t\t\tscalerGrad[channelIdx] = 0;\n\t\t\tfor (int n = 0; n < N; ++n) {\n\t\t\t\tfor (int hIdx = 0; hIdx < h_img; ++hIdx) {\n\t\t\t\t\tfor (int wIdx = 0; wIdx < w_img; ++wIdx) {\n\t\t\t\t\t\tbiasGrad[channelIdx] += top->diff_at(n, channelIdx, hIdx, wIdx);\n\t\t\t\t\t\tscalerGrad[channelIdx] += top->diff_at(n, channelIdx, hIdx, wIdx) * bottom_xhat->data_at(n, channelIdx, hIdx, wIdx);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//bottom data grad\n\t\t//helper 1:\n\t\tDtype* XhatGrad = bottom_xhat->mutable_cpu_diff();\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int c = 0; c < C; ++c) {\n\t\t\t\tfor (int h = 0; h < h_img; ++h) {\n\t\t\t\t\tfor (int w = 0; w < w_img; ++w) {\n\t\t\t\t\t\tXhatGrad[bottom_xhat->offset(n, c, h, w)] = top->diff_at(n, c, h, w) * scaler->data_at(0, c, 0, 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//helper 2:\n\t\tDtype* varGrad = batchVar->mutable_cpu_diff();\n\t\tfor (int c = 0; c < C; ++c) {\n\t\t\tfor (int n = 0; n < N; ++n) {\n\t\t\t\tfor (int h = 0; h < h_img; ++h) {\n\t\t\t\t\tfor (int w = 0; w < w_img; ++w) {\n\t\t\t\t\t\t//varGrad[c] += bottom_xhat->diff_at(n,c,h,w) * (bottom->data_at(n,c,h,w)-batchMean->data_at(0,c,0,0)) * (-0.5) * pow(batchVar->data_at(0,c,0,0) + epsilon,-1.5);\n\t\t\t\t\t\tvarGrad[c] += bottom_xhat->diff_at(n, c, h, w) * (bottom->data_at(n, c, h, w) - batchMean->data_at(0, c, 0, 0)) * (-0.5) * (1.0 / ((batchVar->data_at(0, c, 0, 0) + epsilon) * sqrt(batchVar->data_at(0, c, 0, 0) + epsilon)));\n\t\t\t\t\t\t//flag\n\t\t\t\t\t\t//if (decide_channelDiffAllZero<Dtype>(top,c,N,C,h_img,w_img)){\n\t\t\t\t\t\t//  std::cout<<varGrad[c]<<std::endl;\n\t\t\t\t\t\t//}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//helper 3:\n\t\tdouble m = N * h_img * w_img;\n\t\tDtype* meanGrad = batchMean->mutable_cpu_diff();\n\t\tfor (int c = 0; c < C; ++c) {\n\t\t\tfor (int n = 0; n < N; ++n) {\n\t\t\t\tfor (int h = 0; h < h_img; ++h) {\n\t\t\t\t\tfor (int w = 0; w < w_img; ++w) {\n\t\t\t\t\t\tmeanGrad[c] += bottom_xhat->diff_at(n, c, h, w) * (-1.0 / sqrt(batchVar->data_at(0, c, 0, 0) + epsilon)) + batchVar->diff_at(0, c, 0, 0) * (-2.0) * (bottom->data_at(n, c, h, w) - batchMean->data_at(0, c, 0, 0)) / m;\n\t\t\t\t\t\t//if (decide_channelDiffAllZero<Dtype>(top,c,N,C,h_img,w_img)){\n\t\t\t\t\t//  std::cout<<varGrad[c]<<std::endl;\n\t\t\t\t\t//}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//combine helpers\n\t\tDtype* bottomDataGrad = bottom->mutable_cpu_diff();\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int c = 0; c < C; ++c) {\n\t\t\t\tfor (int h = 0; h < h_img; ++h) {\n\t\t\t\t\tfor (int w = 0; w < w_img; ++w) {\n\t\t\t\t\t\t//Dtype term1=bottom_xhat->diff_at(n,c,h,w)*pow(batchVar->data_at(0,c,0,0)+epsilon,-0.5);\n\t\t\t\t\t\tDtype term1 = bottom_xhat->diff_at(n, c, h, w) / (sqrt(batchVar->data_at(0, c, 0, 0) + epsilon));\n\t\t\t\t\t\tDtype term2 = batchVar->diff_at(0, c, 0, 0)*2.0*(bottom->data_at(n, c, h, w) - batchMean->data_at(0, c, 0, 0)) / m;\n\t\t\t\t\t\tDtype term3 = batchMean->diff_at(0, c, 0, 0) / m;\n\t\t\t\t\t\tif (betaOneData) {\n\t\t\t\t\t\t\tbottomDataGrad[bottom->offset(n, c, h, w)] += term1 + term2 + term3;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbottomDataGrad[bottom->offset(n, c, h, w)] = term1 + term2 + term3;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//std::cout<<term1<<\",\"<<term2<<\",\"<<term3<<std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::CPU_Initialization() {\n\t\tthis->batch_Mean.resize(this->numTransition);\n\t\tthis->batch_Var.resize(this->numTransition);\n\n\t\tthis->merged_conv.resize(this->numTransition + 1);\n\t\tthis->BN_XhatVec.resize(this->numTransition);\n\t\tthis->postBN_blobVec.resize(this->numTransition);\n\t\tthis->postReLU_blobVec.resize(this->numTransition);\n\t\tthis->postConv_blobVec.resize(this->numTransition);\n\t\tif (useBC) {\n\t\t\tBC_BN_XhatVec.resize(this->numTransition);\n\t\t\tpostBN_BCVec.resize(this->numTransition);\n\t\t\tpostReLU_BCVec.resize(this->numTransition);\n\t\t\tpostConv_BCVec.resize(this->numTransition);\n\t\t\tbatch_Mean4G.resize(numTransition);\n\t\t\tbatch_Var4G.resize(numTransition);\n\t\t}\n\t\tfor (int transitionIdx = 0; transitionIdx < this->numTransition; ++transitionIdx) {\n\t\t\tint conv_y_Channels = this->growthRate;\n\t\t\tint mergeChannels = this->initChannel + this->growthRate * transitionIdx;\n\t\t\tint channelShapeArr[] = { 1,mergeChannels,1,1 };\n\t\t\tint conv_y_ShapeArr[] = { this->N,conv_y_Channels,this->H,this->W };\n\t\t\tint mergeShapeArr[] = { this->N,mergeChannels,this->H,this->W };\n\t\t\tvector<int> channelShape(channelShapeArr, channelShapeArr + 4);\n\t\t\tvector<int> conv_y_Shape(conv_y_ShapeArr, conv_y_ShapeArr + 4);\n\t\t\tvector<int> mergeShape(mergeShapeArr, mergeShapeArr + 4);\n\n\t\t\tthis->batch_Mean[transitionIdx] = new Blob<Dtype>(channelShape);\n\t\t\tthis->batch_Var[transitionIdx] = new Blob<Dtype>(channelShape);\n\n\t\t\tthis->merged_conv[transitionIdx] = new Blob<Dtype>(mergeShape);\n\t\t\tthis->BN_XhatVec[transitionIdx] = new Blob<Dtype>(mergeShape);\n\t\t\tthis->postBN_blobVec[transitionIdx] = new Blob<Dtype>(mergeShape);\n\t\t\tthis->postReLU_blobVec[transitionIdx] = new Blob<Dtype>(mergeShape);\n\t\t\tthis->postConv_blobVec[transitionIdx] = new Blob<Dtype>(conv_y_Shape);\n\t\t\tif (useBC) {\n\t\t\t\tint quadGShapeArr[] = { N,4 * growthRate,H,W };\n\t\t\t\tint quadChannelArr[] = { 1,4 * growthRate,1,1 };\n\t\t\t\tvector<int> quadGShape(quadGShapeArr, quadGShapeArr + 4);\n\t\t\t\tvector<int> quadChannelShape(quadChannelArr, quadChannelArr + 4);\n\t\t\t\tthis->BC_BN_XhatVec[transitionIdx] = new Blob<Dtype>(quadGShape);\n\t\t\t\tthis->postBN_BCVec[transitionIdx] = new Blob<Dtype>(quadGShape);\n\t\t\t\tthis->postReLU_BCVec[transitionIdx] = new Blob<Dtype>(quadGShape);\n\t\t\t\tthis->postConv_BCVec[transitionIdx] = new Blob<Dtype>(quadGShape);\n\t\t\t\tbatch_Mean4G[transitionIdx] = new Blob<Dtype>(quadChannelShape);\n\t\t\t\tbatch_Var4G[transitionIdx] = new Blob<Dtype>(quadChannelShape);\n\t\t\t}\n\t\t}\n\t\t//the last element of merged_conv serve as output of forward\n\t\tint extraMergeOutputShapeArr[] = { this->N,this->initChannel + this->growthRate*this->numTransition,this->H,this->W };\n\t\tvector<int> extraMergeOutputShapeVector(extraMergeOutputShapeArr, extraMergeOutputShapeArr + 4);\n\t\tthis->merged_conv[this->numTransition] = new Blob<Dtype>(extraMergeOutputShapeVector);\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid mergeChannelData(Blob<Dtype>* outputBlob, Blob<Dtype>* blobA, Blob<Dtype>* blobB) {\n\t\tint N = blobA->shape(0);\n\t\tint frontC = blobA->shape(1); int backC = blobB->shape(1);\n\t\tint H = blobA->shape(2);\n\t\tint W = blobA->shape(3);\n\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int c = 0; c < frontC + backC; ++c) {\n\t\t\t\tfor (int h = 0; h < H; ++h) {\n\t\t\t\t\tfor (int w = 0; w < W; ++w) {\n\t\t\t\t\t\tDtype inData;\n\t\t\t\t\t\tif (c < frontC) {\n\t\t\t\t\t\t\tinData = blobA->cpu_data()[blobA->offset(n, c, h, w)];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tint readC = c - frontC;\n\t\t\t\t\t\t\tinData = blobB->cpu_data()[blobB->offset(n, readC, h, w)];\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutputBlob->mutable_cpu_data()[outputBlob->offset(n, c, h, w)] = inData;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid distributeChannelDiff(Blob<Dtype>* inputBlob, Blob<Dtype>* blobA, Blob<Dtype>* blobB) {\n\t\tint N = blobA->shape(0);\n\t\tint frontC = blobA->shape(1); int backC = blobB->shape(1);\n\t\tint H = blobA->shape(2);\n\t\tint W = blobA->shape(3);\n\n\t\tfor (int n = 0; n < N; ++n) {\n\t\t\tfor (int c = 0; c < frontC + backC; ++c) {\n\t\t\t\tfor (int h = 0; h < H; ++h) {\n\t\t\t\t\tfor (int w = 0; w < W; ++w) {\n\t\t\t\t\t\tDtype readData = inputBlob->cpu_diff()[inputBlob->offset(n, c, h, w)];\n\t\t\t\t\t\tif (c < frontC) {\n\t\t\t\t\t\t\tblobA->mutable_cpu_diff()[blobA->offset(n, c, h, w)] = readData;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tint writeC = c - frontC;\n\t\t\t\t\t\t\tblobB->mutable_cpu_diff()[blobB->offset(n, writeC, h, w)] = readData;\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\ttemplate <typename Dtype>\n\tvoid BlobSetZero(Blob<Dtype>* B, int count) {\n\t\tDtype* B_mutable_data = B->mutable_cpu_data();\n\t\tDtype* B_mutable_diff = B->mutable_cpu_diff();\n\t\tfor (int i = 0; i < count; ++i) {\n\t\t\tB_mutable_data[i] = 0;\n\t\t\tB_mutable_diff[i] = 0;\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::LoopEndCleanup_cpu() {\n\t\tfor (int transitionIdx = 0; transitionIdx < this->numTransition; ++transitionIdx) {\n\t\t\tint tensorCount = this->N * growthRate * this->H * this->W;\n\t\t\tint tensorMergeCount = this->N * (this->initChannel + this->growthRate * transitionIdx) * this->H * this->W;\n\t\t\tBlobSetZero<Dtype>(this->merged_conv[transitionIdx], tensorMergeCount);\n\t\t\tBlobSetZero<Dtype>(this->BN_XhatVec[transitionIdx], tensorMergeCount);\n\t\t\tBlobSetZero<Dtype>(this->postBN_blobVec[transitionIdx], tensorMergeCount);\n\t\t\tBlobSetZero<Dtype>(this->postReLU_blobVec[transitionIdx], tensorMergeCount);\n\t\t\tBlobSetZero<Dtype>(this->postConv_blobVec[transitionIdx], tensorCount);\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n\t\tconst vector<Blob<Dtype>*>& top)\n\t{\n\t\t//init CPU\n\t\tif (!this->cpuInited) {\n\t\t\t//std::cout<<\"fwd cpu init\"<<std::endl;\n\t\t\tthis->CPU_Initialization();\n\t\t\tthis->cpuInited = true;\n\t\t\t//std::cout<<\"fwd cpu init done\"<<std::endl;\n\t\t}\n\t\tint bnTimerIdx = useBC ? 10 * numTransition : 5 * numTransition;\n\t\t//deploy init data\n\t\tthis->merged_conv[0]->CopyFrom(*(bottom[0]));\n\t\t//init CPU finish\n\t\tfor (int transitionIdx = 0; transitionIdx < this->numTransition; ++transitionIdx) {\n\t\t\t//BN\n\t\t\tBlob<Dtype>* BN_bottom = this->merged_conv[transitionIdx];\n\t\t\tBlob<Dtype>* BN_top = this->postBN_blobVec[transitionIdx];\n\t\t\tBlob<Dtype>* Scaler = this->blobs_[numTransition + transitionIdx].get();\n\t\t\tBlob<Dtype>* Bias = this->blobs_[2 * numTransition + transitionIdx].get();\n\t\t\tint localChannels = this->initChannel + transitionIdx*this->growthRate;\n\t\t\tif (this->phase_ == TEST) {\n\t\t\t\t//std::cout<<\"cpu BN test forward\"<<std::endl;\n\t\t\t\tBN_inf_Fwd<Dtype>(BN_bottom, BN_top, this->N, localChannels, this->H, this->W, this->blobs_[3 * this->numTransition + transitionIdx].get(), this->blobs_[4 * this->numTransition + transitionIdx].get(), Scaler, Bias, this->blobs_[bnTimerIdx].get());\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//std::cout<<\"cpu BN train forward\"<<std::endl;\n\t\t\t\tBN_train_Fwd<Dtype>(BN_bottom, BN_top, this->BN_XhatVec[transitionIdx], this->blobs_[3 * this->numTransition + transitionIdx].get(), this->blobs_[4 * this->numTransition + transitionIdx].get(), this->batch_Mean[transitionIdx], this->batch_Var[transitionIdx], Scaler, Bias, this->N, localChannels, this->H, this->W, this->EMA_decay);\n\t\t\t}\n\t\t\t//ReLU\n\t\t\tBlob<Dtype>* ReLU_top = this->postReLU_blobVec[transitionIdx];\n\t\t\tReLU_Fwd<Dtype>(BN_top, ReLU_top, this->N, localChannels, this->H, this->W);\n\t\t\t//if useBC, Conv1*1-BN(BC)-ReLU(BC)\n\t\t\tif (useBC) {\n\t\t\t\t//BC Conv 1*1\n\t\t\t\tBlob<Dtype>* BC_filterBlob = this->blobs_[5 * numTransition + transitionIdx].get();\n\t\t\t\tBlob<Dtype>* BC_conv_x = postReLU_blobVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_conv_y = postConv_BCVec[transitionIdx];\n\t\t\t\tint BC_conv_inChannel = initChannel + growthRate*transitionIdx;\n\t\t\t\tint BC_conv_outChannel = 4 * growthRate;\n\t\t\t\tconvolution_Fwd<Dtype>(BC_conv_x, BC_conv_y, BC_filterBlob, N, BC_conv_outChannel, BC_conv_inChannel, H, W, 1, 1);\n\t\t\t\t//BC BN \n\t\t\t\tBlob<Dtype>* BC_BN_x = postConv_BCVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_BN_y = postBN_BCVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_Scaler = this->blobs_[6 * numTransition + transitionIdx].get();\n\t\t\t\tBlob<Dtype>* BC_Bias = this->blobs_[7 * numTransition + transitionIdx].get();\n\t\t\t\tBlob<Dtype>* BC_Mean = this->blobs_[8 * numTransition + transitionIdx].get();\n\t\t\t\tBlob<Dtype>* BC_Var = this->blobs_[9 * numTransition + transitionIdx].get();\n\t\t\t\tif (this->phase_ == TEST) {\n\t\t\t\t\tBN_inf_Fwd<Dtype>(BC_BN_x, BC_BN_y, N, 4 * growthRate, H, W, BC_Mean, BC_Var, BC_Scaler, BC_Bias, this->blobs_[bnTimerIdx].get());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tBlob<Dtype>* BC_xhat = BC_BN_XhatVec[transitionIdx];\n\t\t\t\t\tBlob<Dtype>* BC_batchMean = batch_Mean4G[transitionIdx];\n\t\t\t\t\tBlob<Dtype>* BC_batchVar = batch_Var4G[transitionIdx];\n\t\t\t\t\tBN_train_Fwd<Dtype>(BC_BN_x, BC_BN_y, BC_xhat, BC_Mean, BC_Var, BC_batchMean, BC_batchVar, BC_Scaler, BC_Bias, N, 4 * growthRate, H, W, EMA_decay);\n\t\t\t\t}\n\t\t\t\t//BC ReLU \n\t\t\t\tBlob<Dtype>* ReLU_x = postBN_BCVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* ReLU_y = postReLU_BCVec[transitionIdx];\n\t\t\t\tReLU_Fwd<Dtype>(ReLU_x, ReLU_y, N, 4 * growthRate, H, W);\n\t\t\t}\n\t\t\t//Conv\n\t\t\tBlob<Dtype>* filterBlob = this->blobs_[transitionIdx].get();\n\t\t\tBlob<Dtype>* conv_x = useBC ? postReLU_BCVec[transitionIdx] : postReLU_blobVec[transitionIdx];\n\t\t\tBlob<Dtype>* conv_y = this->postConv_blobVec[transitionIdx];\n\t\t\tint inConvChannel = useBC ? 4 * growthRate : initChannel + growthRate*transitionIdx;\n\t\t\tconvolution_Fwd<Dtype>(conv_x, conv_y, filterBlob, N, growthRate, inConvChannel, H, W, 3, 3);\n\t\t\t//post Conv merge\n\t\t\tBlob<Dtype>* mergeOutput = merged_conv[transitionIdx + 1];\n\t\t\tBlob<Dtype>* mergeInputA = merged_conv[transitionIdx];\n\t\t\tBlob<Dtype>* mergeInputB = postConv_blobVec[transitionIdx];\n\t\t\tmergeChannelData(mergeOutput, mergeInputA, mergeInputB);\n\t\t}\n\t\t//deploy output data\n\t\ttop[0]->CopyFrom(*(this->merged_conv[this->numTransition]));\n\t\tif (this->phase_ == TRAIN) {\n\t\t\tthis->blobs_[bnTimerIdx]->mutable_cpu_data()[0] *= this->EMA_decay;\n\t\t\tthis->blobs_[bnTimerIdx]->mutable_cpu_data()[0] += 1;\n\t\t\tthis->trainCycleIdx += 1;\n\t\t}\n\t\t//logInternal_cpu(\"TC_TrueFwdlog\");\n\t}\n\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n\t\tconst vector<bool>& propagate_down,\n\t\tconst vector<Blob<Dtype>*>& bottom)\n\t{\n\t\tif (!this->cpuInited) {\n\t\t\tthis->CPU_Initialization();\n\t\t\tthis->cpuInited = true;\n\t\t}\n\t\t//deploy top diff\n\t\tthis->merged_conv[this->numTransition]->CopyFrom(*(top[0]), true);\n\t\tfor (int transitionIdx = this->numTransition - 1; transitionIdx >= 0; --transitionIdx) {\n\t\t\t//distribute diff\n\t\t\tdistributeChannelDiff(this->merged_conv[transitionIdx + 1], this->merged_conv[transitionIdx], this->postConv_blobVec[transitionIdx]);\n\t\t\t//Conv Bwd\n\t\t\tBlob<Dtype>* conv_top = this->postConv_blobVec[transitionIdx];\n\t\t\tBlob<Dtype>* conv_bottom = useBC ? postReLU_BCVec[transitionIdx] : postReLU_blobVec[transitionIdx];\n\t\t\tBlob<Dtype>* filter = this->blobs_[transitionIdx].get();\n\t\t\tint c_input = useBC ? 4 * growthRate : initChannel + growthRate*transitionIdx;\n\t\t\tconvolution_Bwd<Dtype>(conv_bottom, conv_top, filter, this->N, this->growthRate, c_input, this->H, this->W, 3, 3);\n\t\t\t//BC ReLU_BC_Bwd - BN_BC_Bwd - Conv1*1_BC_Bwd\n\t\t\tif (useBC) {\n\t\t\t\t//ReLU BC Bwd\n\t\t\t\tBlob<Dtype>* BC_ReLU_y = postReLU_BCVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_ReLU_x = postBN_BCVec[transitionIdx];\n\t\t\t\tReLU_Bwd<Dtype>(BC_ReLU_x, BC_ReLU_y, N, 4 * growthRate, H, W);\n\t\t\t\t//BN BC Bwd\n\t\t\t\tBlob<Dtype>* BC_BN_y = postBN_BCVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_BN_x = postConv_BCVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_BN_xhat = BC_BN_XhatVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_Scaler = this->blobs_[6 * numTransition + transitionIdx].get();\n\t\t\t\tBlob<Dtype>* BC_Bias = this->blobs_[7 * numTransition + transitionIdx].get();\n\t\t\t\tBlob<Dtype>* BC_batchMean = batch_Mean4G[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_batchVar = batch_Var4G[transitionIdx];\n\t\t\t\tBN_train_Bwd<Dtype>(BC_BN_x, BC_BN_xhat, BC_BN_y, BC_batchMean, BC_batchVar, BC_Scaler, BC_Bias, N, 4 * growthRate, H, W, false);\n\t\t\t\t//Conv1*1 BC Bwd\n\t\t\t\tBlob<Dtype>* BC_conv_x = postReLU_blobVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_conv_y = postConv_BCVec[transitionIdx];\n\t\t\t\tBlob<Dtype>* BC_filter = this->blobs_[5 * numTransition + transitionIdx].get();\n\t\t\t\tint BC_c_input = initChannel + growthRate*transitionIdx;\n\t\t\t\tint BC_c_output = 4 * growthRate;\n\t\t\t\tconvolution_Bwd<Dtype>(BC_conv_x, BC_conv_y, BC_filter, N, BC_c_output, BC_c_input, H, W, 1, 1);\n\t\t\t}\n\t\t\t//ReLU Bwd\n\t\t\tint localChannel = this->initChannel + this->growthRate*transitionIdx;\n\t\t\tReLU_Bwd<Dtype>(postBN_blobVec[transitionIdx], postReLU_blobVec[transitionIdx], this->N, localChannel, this->H, this->W);\n\t\t\t//BN Bwd\n\t\t\tBlob<Dtype>* BN_bottom = this->merged_conv[transitionIdx];\n\t\t\tBlob<Dtype>* scaler = this->blobs_[this->numTransition + transitionIdx].get();\n\t\t\tBlob<Dtype>* bias = this->blobs_[2 * this->numTransition + transitionIdx].get();\n\t\t\tBN_train_Bwd<Dtype>(BN_bottom, this->BN_XhatVec[transitionIdx], this->postBN_blobVec[transitionIdx], this->batch_Mean[transitionIdx], this->batch_Var[transitionIdx], scaler, bias, this->N, localChannel, this->H, this->W, true);\n\t\t}\n\t\tbottom[0]->CopyFrom(*(this->merged_conv[0]), true);\n\t\t//logInternal_cpu(\"TC_TrueBwdlog\");\n\t\tthis->LoopEndCleanup_cpu();\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::Forward_cpu_public(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {\n\t\tthis->Forward_cpu(bottom, top);\n\t}\n\n\ttemplate <typename Dtype>\n\tvoid DenseBlockLayer<Dtype>::Backward_cpu_public(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {\n\t\tthis->Backward_cpu(top, propagate_down, bottom);\n\t}\n\n\n\n#ifdef CPU_ONLY\n\tSTUB_GPU(DenseBlockLayer);\n#endif\n\n\tINSTANTIATE_CLASS(DenseBlockLayer);\n\tREGISTER_LAYER_CLASS(DenseBlock);\n\n}  // namespace caffe  \n", "meta": {"hexsha": "86713aa2ecb32b681ac7d71caa91eb8f7c6de6f1", "size": 41765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layers/DenseBlock_layer.cpp", "max_stars_repo_name": "ilaotan/License-Plate-Detect-Recognition-via-Deep-Neural-Networks-accuracy-up-to-99.9", "max_stars_repo_head_hexsha": "a2cf438a8d2df7b3a55f869fb01f5410741aae5e", "max_stars_repo_licenses": ["OLDAP-2.2.1"], "max_stars_count": 1437.0, "max_stars_repo_stars_event_min_datetime": "2018-07-13T02:37:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:37:15.000Z", "max_issues_repo_path": "src/caffe/layers/DenseBlock_layer.cpp", "max_issues_repo_name": "ilaotan/License-Plate-Detect-Recognition-via-Deep-Neural-Networks-accuracy-up-to-99.9", "max_issues_repo_head_hexsha": "a2cf438a8d2df7b3a55f869fb01f5410741aae5e", "max_issues_repo_licenses": ["OLDAP-2.2.1"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2018-07-20T14:12:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-20T03:51:24.000Z", "max_forks_repo_path": "src/caffe/layers/DenseBlock_layer.cpp", "max_forks_repo_name": "ilaotan/License-Plate-Detect-Recognition-via-Deep-Neural-Networks-accuracy-up-to-99.9", "max_forks_repo_head_hexsha": "a2cf438a8d2df7b3a55f869fb01f5410741aae5e", "max_forks_repo_licenses": ["OLDAP-2.2.1"], "max_forks_count": 317.0, "max_forks_repo_forks_event_min_datetime": "2018-07-13T02:37:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T03:37:17.000Z", "avg_line_length": 40.509214355, "max_line_length": 336, "alphanum_fraction": 0.6501616186, "num_tokens": 14004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1911974231241976}}
{"text": "#include \"Vehicle.h\"\n#include \"Block.h\"\n#include \"CylObject.h\"\n#include \"EventQueue.h\"\n#include \"IObus.h\"\n#include \"Log.h\"\n#include \"MathDef.h\"\n#include \"OrientationCone.h\"\n#include \"Room.h\"\n#include \"XYZrZ.h\"\n\n#include <algorithm>\n#include <boost/thread/thread.hpp>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const Vehicle &rhs)\n{\n   os << rhs.R_ << \" \" << rhs.H_ << \" \" << rhs.nextXYZrZ_;\n   return os;\n}\n\nVehicle::Vehicle(double R, double H, const XYZrZ &xyzRz)\n   : Drawable()\n   , DoPhysics()\n   , R_(R)\n   , H_(H)\n   , XYZrZ_(xyzRz)\n   , nextXYZrZ_(xyzRz)\n   , drawables()\n   , collisionDetector()\n   , physicsProcesses()\n   , IO()\n   , IOint(IO)\n   , IOext(IO)\n   , IRQs()\n   , timer(this)\n   , memory_()\n   , bumper_(*this, -110, 110, 6, memory_, hardware::BUMPER0)\n   , motorLeft_(IOext, MOTORLEFT_PWM_INT, MOTORLEFT_FORWARD_BOOL)\n   , motorRight_(IOext, MOTORRIGHT_PWM_INT, MOTORRIGHT_FORWARD_BOOL)\n   , pBody_(gluNewQuadric())\n   , controlExecuteIsRunning_(true)\n   , simProgram_(std::thread(&Vehicle::controlExecute, this))\n{\n   SET_FNAME(\"Vehicle::Vehicle()\");\n   // Physics part\n   physicsProcesses.push_back(&timer);\n   physicsProcesses.push_back(&bumper_);\n   physicsProcesses.push_back(&motorLeft_);\n   physicsProcesses.push_back(&motorRight_);\n   // Drawable part\n   gluQuadricDrawStyle(pBody_, GLU_FILL);\n   // Control part\n   controlInit();\n   LOGI(\"initialized\");\n}\n\nVehicle::~Vehicle()\n{\n   SET_FNAME(\"Vehicle::~Vehicle()\");\n   controlExecuteIsRunning_ = false;\n   simProgram_.join();\n   LOGI(\"\");\n}\n\nXYZrZ Vehicle::expectedNextXYZrZ() const\n{\n   double speedMotorLeft = 1.2;   // 0.6;   //m_motorLeft.getSpeed();\n   double speedMotorRight = 1.14; // 0.57; //m_motorRight.getSpeed();\n   double translationSpeed = (speedMotorLeft + speedMotorRight) / 2;\n   double translation = translationSpeed * physics::SIMTIME_SEC;\n   double rotationSpeed = (speedMotorRight - speedMotorLeft) / (2 * R_);\n   double rotation = rotationSpeed * physics::SIMTIME_SEC;\n   double rz = math::toRadians(XYZrZ_.Rz);\n\n   return {XYZrZ_.position.get_x() + cos(rz) * translation,\n           XYZrZ_.position.get_y() + sin(rz) * translation,\n           XYZrZ_.position.get_z(), XYZrZ_.Rz + math::toDegrees(rotation)};\n}\n\n/// @todo Remove vehicle control from physics to controlExecute.\nvoid Vehicle::process()\n{\n   SET_FNAME(\"Vehicle::process()\");\n   checkIRQs();\n   std::for_each(physicsProcesses.begin(), physicsProcesses.end(),\n                 std::mem_fun(&DoPhysics::process));\n\n   // Vehicle physics\n   double speedMotorLeft = 1.2;   // 0.6;   //m_motorLeft.getSpeed();\n   double speedMotorRight = 1.14; // 0.57; //m_motorRight.getSpeed();\n   double translationSpeed = (speedMotorLeft + speedMotorRight) / 2;\n   double translation = translationSpeed * physics::SIMTIME_SEC;\n   double rotationSpeed = (speedMotorRight - speedMotorLeft) / (2 * R_);\n   double rotation = rotationSpeed * physics::SIMTIME_SEC;\n   double rz = math::toRadians(XYZrZ_.getRz());\n\n   if (physicsState[physics::CYLOBJ_COLLISION] != 1 &&\n       physicsState[physics::WALL_COLLISION] != 1) {\n      nextXYZrZ_.position.set_x(XYZrZ_.position.get_x() +\n                                cos(rz) * translation);\n      nextXYZrZ_.position.set_y(XYZrZ_.position.get_y() +\n                                sin(rz) * translation);\n      nextXYZrZ_.Rz = XYZrZ_.Rz + math::toDegrees(rotation);\n   } else {\n      static int incr = 0;\n      nextXYZrZ_ = XYZrZ_ - math::CartVec(cos(rz) * translation,\n                                          sin(rz) * translation, 0);\n      // m_nextXYZrZ.position.x = m_XYZrZ.position.x - cos(rz) *\n      // translation; m_nextXYZrZ.position.y = m_XYZrZ.position.y - sin(rz)\n      // * translation;\n      nextXYZrZ_.Rz = XYZrZ_.Rz - 27 + incr;\n      ++incr;\n      if (incr > 15) {\n         incr = 0;\n      }\n   }\n   nextXYZrZ_.Rz = math::normalizeDegrees(nextXYZrZ_.Rz);\n   XYZrZ_ = nextXYZrZ_;\n}\n\nvoid Vehicle::draw() const\n{\n   glPushMatrix();\n   XYZrZ_.draw();\n   glPointSize(5);\n   glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // point color\n   glBegin(GL_POINTS);\n   glVertex3f(R_ * 0.8, 0.0, H_);\n   glEnd();\n   glPointSize(1);\n   glColor4f(0.5f, 0.5f, 0.5f, 1.0f); // line color\n   gluCylinder(pBody_, R_, R_, H_, 20, 20);\n   glPopMatrix();\n   std::for_each(drawables.begin(), drawables.end(),\n                 std::mem_fun(&Drawable::draw));\n}\n\nvoid Vehicle::controlInit()\n{\n   SET_FNAME(\"Vehicle::controlInit()\");\n   // Install ISRs\n   IRQs[IRQ0].setISR(&Vehicle::ISR0);\n   IRQs[IRQ1].setISR(&Vehicle::ISR1);\n   IRQs[IRQ2].setISR(&Vehicle::ISR2);\n   // Init timers\n   timer.setISR(&Vehicle::ISR0);\n   timer.setTime(10000L, hardware::mode_t::PERIODIC);\n   timer.start();\n   // Init shared vars\n   shared1 = shared2 = 1;\n   LOGI(\"ready\");\n}\n\nvoid Vehicle::controlExecute()\n{\n   SET_FNAME(\"Vehicle::controlExecute()\");\n   LOGI(\"started\");\n   try {\n      unsigned long long tick = 0ull;\n      EventQueue eventQueue;\n\n      while (controlExecuteIsRunning_) {\n         ++tick;\n         const boost::system_time timeout(\n            boost::get_system_time() +\n            boost::posix_time::milliseconds(physics::SIMTIME_MSEC * 4));\n         if (tick % 10 == 0)\n            eventQueue.post(1);\n         boost::thread::sleep(timeout);\n         // std::this_thread::sleep_for(timeout);\n      }\n   }\n   catch (std::exception &x) {\n      LOGE(x.what());\n   }\n   catch (...) {\n      LOGE(\"UNKNOWN EXCEPTION\");\n   }\n   LOGI(\"stopped\");\n}\n\nvoid Vehicle::stopControlExecute()\n{\n   controlExecuteIsRunning_ = false;\n}\n\nvoid Vehicle::ISR0()\n{\n   SET_FNAME(\"Vehicle::ISR0()\");\n   LOGI(\"Heartbeat ------------------------->\");\n}\n\nvoid Vehicle::ISR1() {}\n\nvoid Vehicle::ISR2() {}\n\nvoid Vehicle::checkIRQs()\n{\n   for (int i = IRQ0; i < N_IRQ_IN; ++i) {\n      IRQs[i].react(this);\n   }\n}\n\nbool Vehicle::isColliding(const Room &room)\n{\n   SET_FNAME(\"Vehicle::isColliding()\");\n   if (collisionDetector.isColliding(getCollisionShape(),\n                                     room.getCollisionShape())) {\n      const size_t maxIteration = 4;\n      size_t iteration = 0;\n      while (iteration < maxIteration) {\n         ++iteration;\n      }\n   }\n   const auto &corners(room.getCorners());\n   int nCollisions = 0;\n   for (size_t wallID = 0; wallID < corners.size(); ++wallID) {\n      math::Point closestPoint(room.closestPointWall(wallID, XYZrZ_.position));\n\n      if ((closestPoint - XYZrZ_.position).length() <= R_) {\n         double overshoot =\n            (R_ - (closestPoint - XYZrZ_.position).length()) / R_;\n         ++nCollisions;\n\n         vehicleCollisions.push_back(closestPoint - XYZrZ_.position);\n\n         std::ostringstream msg;\n         msg << \"WCS: \" << closestPoint << \" \"\n             << (closestPoint - XYZrZ_.position) << \" \" << std::setw(2)\n             << int(overshoot * 100) << \"%\";\n\n         // CartVec delta((closestPoint - m_XYZrZ.position)  * overshoot);\n         math::CartVec delta{closestPoint - XYZrZ_.position};\n         nextXYZrZ_ = XYZrZ_ + delta;\n         msg << \" nextXYZrZ: \" << nextXYZrZ_;\n         LOGD(msg.str());\n      }\n   }\n   return nCollisions > 0;\n}\n\nbool Vehicle::isColliding(const CylObject &object)\n{\n   SET_FNAME(\"Vehicle::isColliding()\");\n   vehicleCollisions.clear();\n   if (collisionDetector.isColliding(getCollisionShape(),\n                                     object.getCollisionShape())) {\n      /// In Vehicle CS.\n      vehicleCollisions.push_back(collisionDetector.getCollisionPoints()[0] -\n                                  XYZrZ_.position);\n      return true;\n   }\n   return false;\n}\n\nbool Vehicle::isColliding(const Block &object)\n{\n   SET_FNAME(\"Vehicle::isColliding()\");\n   vehicleCollisions.clear();\n   if (collisionDetector.isColliding(getCollisionShape(),\n                                     object.getCollisionShape())) {\n      {\n         std::ostringstream msg;\n         msg << \"############# Is colliding with block\";\n         LOGD(msg.str());\n      }\n      for(const auto &collisionPoints : collisionDetector.getCollisionPoints())\n      {\n         /// In Vehicle CS.\n         vehicleCollisions.push_back(collisionPoints - XYZrZ_.position);\n      }\n      return true;\n   }\n   return false;\n}\n", "meta": {"hexsha": "4ec3ad923019205c8a1481ec08465ebbfeef177c", "size": 8201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/Vehicle.cpp", "max_stars_repo_name": "josokw/YAAV-simulation", "max_stars_repo_head_hexsha": "4647b363a96b2564bdae725cb1b0a84188627cbc", "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/Vehicle.cpp", "max_issues_repo_name": "josokw/YAAV-simulation", "max_issues_repo_head_hexsha": "4647b363a96b2564bdae725cb1b0a84188627cbc", "max_issues_repo_licenses": ["MIT"], "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/Vehicle.cpp", "max_forks_repo_name": "josokw/YAAV-simulation", "max_forks_repo_head_hexsha": "4647b363a96b2564bdae725cb1b0a84188627cbc", "max_forks_repo_licenses": ["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.2892857143, "max_line_length": 79, "alphanum_fraction": 0.6144372637, "num_tokens": 2256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19119741574172447}}
{"text": "#include \"edit_distance.hpp\"\n#include \"samples.hpp\"\n#include \"windows.hpp\"\n#include \"immunoseq.hpp\"\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/exception/diagnostic_information.hpp> \n#include <iostream>\n#include <set>\n\n\ntypedef std::multimap<std::pair<std::size_t, std::int64_t>, sequences::sequence_ptr_type> distances_type;\nstd::size_t const maximum_distance(2);\n\n\nvoid next_iteration(distances_type const& previous, sequences::sequences_type const& current, distances_type& next)\n{\n\tstd::map<sequences::sequence_ptr_type, std::size_t> inverse;\n\n\tif(previous.empty())\n\t{\n\t\tsequences::sequence_ptr_type top;\n\t\tfor(auto const& c: current)\n\t\t{\n\t\t\tif(!top || top->reads < c->reads)\n\t\t\t{\n\t\t\t\ttop = c;\n\t\t\t}\n\t\t}\n\n\t\tfor(auto const& c: current)\n\t\t{\n\t\t\tinverse[c] = edit_distance::levenshtein(top->rearrangement->nucleotides, c->rearrangement->nucleotides);\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor(auto const& p: previous)\n\t\t{\n\t\t\tfor(auto const& c: current)\n\t\t\t{\n\t\t\t\tif(inverse.count(c))\n\t\t\t\t{\n\t\t\t\t\tinverse[c] = std::min(inverse[c], edit_distance::levenshtein( p.second->rearrangement->nucleotides, c->rearrangement->nucleotides));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tinverse[c] = edit_distance::levenshtein( p.second->rearrangement->nucleotides, c->rearrangement->nucleotides);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(auto const& i: inverse)\n\t{\n\t\tif(i.second <= maximum_distance)\n\t\t{\n\t\t\tnext.insert(std::make_pair(std::make_pair(i.second, i.first->id), i.first));\n\t\t}\n\t}\n}\n\n\ntypedef std::vector<samples::sample_ptr_type> stack_type;\nvoid process(samples::samples_type const& samples, samples::sample_ptr_type const& parent, distances_type const& previous, std::string const& report, boost::filesystem::path const& directory, stack_type& stack)\n{\n\tfor(auto const& current: samples)\n\t{\n\t\tstd::set<samples::sample_ptr_type> parents;\n\t\tfor(auto const& tag: current.second->tags)\n\t\t{\n\t\t\tif(boost::iequals(tag.first, \"ParentSample\"))\n\t\t\t{\n\t\t\t\tauto const iter(samples.find(tag.second));\n\t\t\t\tif(iter == samples.end())\n\t\t\t\t{\n\t\t\t\t\tthrow std::runtime_error(\"Sample \" + current.first + \" references non-existant parent \" + tag.second);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tparents.insert(iter->second);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(!parent && !parents.empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(parent && !parents.count(parent))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tstack.push_back(current.second);\n\t\tfor(std::size_t i(0); i < stack.size(); ++ i)\n\t\t{\n\t\t\tstd::cout << \"\\t\";\n\t\t}\n\t\tstd::cout << current.first << \": \" << current.second->sequences.size() << \" sequences\";\n\t\tdistances_type next;\n\t\tnext_iteration(previous, current.second->sequences, next);\n\t\tstd::cout << \" -> \" << next.size() << \" in next iteration\" << std::endl;\n\t\t\n\t\tstd::ostringstream buffer;\n\t\tbuffer << report;\n\t\tbuffer << current.second->sequences.size() << \" sequences from sample \" << current.first << std::endl;\n\t\tfor(auto const& distance: next)\n\t\t{\n\t\t\tbuffer << \"\\t\" << distance.first.first << \"\\t\" << distance.second << std::endl;\n\t\t}\n\n\t\tstd::string filename;\n\t\tfor(auto const& iteration: stack)\n\t\t{\n\t\t\tif(filename.empty())\n\t\t\t{\n\t\t\t\tfilename = iteration->id;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfilename += \"_\" + iteration->id;\n\t\t\t}\n\t\t}\n\t\tboost::filesystem::ofstream stream(directory / (filename + \".txt\"), std::ios::trunc);\n\t\tstream << buffer.str();\n\t\tprocess(samples, current.second, next, buffer.str(), directory, stack);\n\t\tstack.pop_back();\n\t}\n}\n\n\nvoid try_directory(boost::filesystem::path const& directory)\n{\n\tif(boost::filesystem::is_directory(directory))\n\t{\n\t\tsamples::samples_type samples;\n\n\t\tboost::filesystem::directory_iterator end;\n\t\tfor(boost::filesystem::directory_iterator iter(directory); iter != end; ++ iter)\n\t\t{\n\t\t\tif(boost::filesystem::is_regular_file(iter->path()) && boost::iequals(iter->path().extension().string(), \".tsv\"))\n\t\t\t{\n\t\t\t\timmunoseq::load(iter->path(), samples);\t\n\t\t\t}\n\t\t}\n\n\t\tstd::cout << \"Performing iterative analysis:\" << std::endl;\n\t\tdistances_type previous;\n\t\tstd::string report;\n\t\tstack_type stack;\n\t\tprocess(samples, samples::sample_ptr_type(), previous, report, directory, stack);\n\t}\n\telse\n\t{\n\t\tstd::cout << \"Not a directory: \" << directory << std::endl;\n\t}\n}\n\n\nint main(int argc, char* argv[])\n{\n\ttry\n\t{\n\t\tif(argc > 1)\n\t\t{\n\t\t\tfor(int i(1); i < argc; ++ i)\n\t\t\t{\n\t\t\t\ttry_directory(argv[i]);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"This program processes a collection of immunoSEQ samples located in tab-separated-values (.tsv) files. Example:\" << std::endl;\n\t\t\tstd::cout << \"samples\" << std::endl << \"\\tproject1.tsv\" << std::endl << \"\\tproject2.tsv\" << std::endl << \"\\tproject3.tsv\" << std::endl << \"\\t...\" << std::endl << std::endl;\n\t\t\tstd::cout << \"You can pass the directory (i.e. \\\"samples\\\" above) containing the files you wish to process on the command line.\" << std::endl;\n\t\t\tstd::cout << \"For now you can manually select a directory to process...\" << std::endl;\n\t\t\ttry_directory(windows::select_directory());\n\t\t}\n\t\t\n\t\tstd::cout << std::endl << \"Press (almost) any key to continue.\" << std::endl;\n\t\tstd::cin.get();\n\t\treturn 0;\n\t}\n\n\tcatch(...)\n\t{\n\t\tstd::cout << boost::current_exception_diagnostic_information() << std::endl;\n\t\treturn 1;\n\t}\n}", "meta": {"hexsha": "5c53c9c64a928bfc03150eefa8c7c9e7c7976ea3", "size": 5094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "daderma/sequence_tracker", "max_stars_repo_head_hexsha": "33c5e3cf54c4bce29199fb4acca426c6736dd804", "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": "daderma/sequence_tracker", "max_issues_repo_head_hexsha": "33c5e3cf54c4bce29199fb4acca426c6736dd804", "max_issues_repo_licenses": ["MIT"], "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": "daderma/sequence_tracker", "max_forks_repo_head_hexsha": "33c5e3cf54c4bce29199fb4acca426c6736dd804", "max_forks_repo_licenses": ["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.53125, "max_line_length": 210, "alphanum_fraction": 0.6511582254, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.19119741422331477}}
{"text": "/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n * Copyright Projet JRL-Japan, 2008\n *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n *\n * File:      PatternGenerator.cpp\n * Project:   SOT\n * Author:    Olivier Stasse\n *\n * Version control\n * ===============\n *\n *  $Id$\n *\n * Description\n * ============\n *\n *\n * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n\n//#define VP_DEBUG\n//#define VP_DEBUG_MODE 45\n#include <sot/core/debug.hh>\n#ifdef VP_DEBUG\nclass sotPG__INIT\n{\n  public:sotPG__INIT( void ) { dynamicgraph::sot::DebugTrace::openFile(); }\n};\nsotPG__INIT sotPG_initiator;\n#endif //#ifdef VP_DEBUG\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n\n#include <jrl/mal/matrixabstractlayer.hh>\n#include \"pinocchio/parsers/urdf.hpp\"\n#include \"pinocchio/parsers/srdf.hpp\"\n\n#include <dynamic-graph/factory.h>\n#include <dynamic-graph/all-commands.h>\n#include <sot/core/matrix-geometry.hh>\n\n#include <sot-pattern-generator/pg.h>\n\nusing namespace std;\nnamespace dynamicgraph {\n  namespace sot {\n\n    DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(PatternGenerator,\"PatternGenerator\");\n\n    PatternGenerator::\n    PatternGenerator( const std::string & name )\n      :Entity(name)\n      ,m_PGI(0)\n      ,m_PreviewControlParametersFile()\n      ,m_urdfFile(\"\")\n      ,m_srdfFile(\"\")\n      ,m_xmlRankFile(\"\")\n      ,m_soleLength(0)\n      ,m_soleWidth(0)\n      ,m_init(false)\n      ,m_InitPositionByRealState(true)\n      ,firstSINTERN( boost::bind(&PatternGenerator::InitOneStepOfControl,this,_1,_2),\n                     sotNOSIGNAL,\"PatternGenerator(\"+name+\")::intern(dummy)::init\" )\n\n      ,OneStepOfControlS( boost::bind(&PatternGenerator::OneStepOfControl,this,_1,_2),\n                          firstSINTERN << jointPositionSIN ,\"PatternGenerator(\"+name+\")::onestepofcontrol\" )\n\n      ,m_dataInProcess(0)\n      ,m_rightFootContact(true) // It is assumed that the robot is standing.\n      ,m_leftFootContact(true)\n      ,jointPositionSIN(NULL,\"PatternGenerator(\"+name+\")::input(vector)::position\")\n\n      ,motorControlJointPositionSIN(NULL,\"PatternGenerator(\"+name+\")::input(vector)::motorcontrol\")\n\n      ,ZMPPreviousControllerSIN(NULL,\"PatternGenerator(\"+name+\")::input(vector)::zmppreviouscontroller\")\n\n      ,ZMPRefSOUT( boost::bind(&PatternGenerator::getZMPRef,this,_1,_2),\n                   OneStepOfControlS,\n                   \"PatternGenerator(\"+name+\")::output(vector)::zmpref\" )\n\n      ,CoMRefSOUT( boost::bind(&PatternGenerator::getCoMRef,this,_1,_2),\n                   OneStepOfControlS,\n                   \"PatternGenerator(\"+name+\")::output(matrix)::comref\" )\n\n      ,dCoMRefSOUT( boost::bind(&PatternGenerator::getdCoMRef,this,_1,_2),\n                    OneStepOfControlS,\n                    \"PatternGenerator(\"+name+\")::output(matrix)::dcomref\" )\n\n      ,comSIN(NULL,\"PatternGenerator(\"+name+\")::input(vector)::com\")\n\n      ,comStateSIN(NULL,\"PatternGenerator(\"+name+\")::input(vector)::comStateSIN\")\n\n      ,zmpSIN(NULL,\"PatternGenerator(\"+name+\")::input(vector)::zmpSIN\")\n\n      ,forceSIN(NULL,\"PatternGenerator(\"+name+\")::input(vector)::forceSIN\")\n\n      ,forceSOUT(boost::bind(&PatternGenerator::getExternalForces,this,_1,_2),\n                 OneStepOfControlS,\n                 \"PatternGenerator(\"+name+\")::output(matrix)::forceSOUT\" )\n\n      ,velocitydesSIN(NULL,\"PatternGenerator(\"+name+\")::input(vector)::velocitydes\")\n\n      ,LeftFootCurrentPosSIN(NULL,\"PatternGenerator(\"+name+\")::input(homogeneousmatrix)::leftfootcurrentpos\")\n\n      ,RightFootCurrentPosSIN(NULL,\"PatternGenerator(\"+name+\")::input(homogeneousmatrix)::rightfootcurrentpos\")\n\n      ,LeftFootRefSOUT( boost::bind(&PatternGenerator::getLeftFootRef,this,_1,_2),\n                        OneStepOfControlS,\n                        \"PatternGenerator(\"+name+\")::output(homogeneousmatrix)::leftfootref\" )\n\n      ,RightFootRefSOUT( boost::bind(&PatternGenerator::getRightFootRef,this,_1,_2),\n                         OneStepOfControlS,\n                         \"PatternGenerator(\"+name+\")::output(homogeneousmatrix)::rightfootref\" )\n      ,dotLeftFootRefSOUT( boost::bind(&PatternGenerator::getdotLeftFootRef,this,_1,_2),\n                           OneStepOfControlS,\n                           \"PatternGenerator(\"+name+\")::output(homogeneousmatrix)::dotleftfootref\" )\n\n      ,dotRightFootRefSOUT( boost::bind(&PatternGenerator::getdotRightFootRef,this,_1,_2),\n                            OneStepOfControlS,\n                            \"PatternGenerator(\"+name+\")::output(homogeneousmatrix)::dotrightfootref\" )\n\n      ,FlyingFootRefSOUT( boost::bind(&PatternGenerator::getFlyingFootRef,this,_1,_2),\n                          OneStepOfControlS,\n                          \"PatternGenerator(\"+name+\")::output(homogeneousmatrix)::flyingfootref\" )\n\n\n      ,SupportFootSOUT( boost::bind(&PatternGenerator::getSupportFoot,this,_1,_2),\n                        OneStepOfControlS,\n                        \"PatternGenerator(\"+name+\")::output(uint)::SupportFoot\" )\n      ,jointWalkingErrorPositionSOUT(boost::bind(&PatternGenerator::getjointWalkingErrorPosition,this,_1,_2),\n                                     OneStepOfControlS,\n                                     \"PatternGenerator(\"+name+\")::output(vector)::walkingerrorposition\")\n\n      ,comattitudeSOUT(boost::bind(&PatternGenerator::getComAttitude,this,_1,_2),\n                       OneStepOfControlS,\n                       \"sotPatternGenerator(\"+name+\")::output(vectorRPY)::comattitude\")\n      ,dcomattitudeSOUT(boost::bind(&PatternGenerator::getdComAttitude,this,_1,_2),\n                        OneStepOfControlS,\n                        \"sotPatternGenerator(\"+name+\")::output(vectorRPY)::dcomattitude\")\n\n      ,waistattitudeSOUT(boost::bind(&PatternGenerator::getWaistAttitude,this,_1,_2),\n                         OneStepOfControlS,\n                         \"PatternGenerator(\"+name+\")::output(vectorRPY)::waistattitude\")\n      ,waistattitudeabsoluteSOUT(boost::bind(&PatternGenerator::getWaistAttitudeAbsolute,this,_1,_2),\n                                 OneStepOfControlS,\n                                 \"PatternGenerator(\"+name+\")::output(vectorRPY)::waistattitudeabsolute\")\n\n      ,waistpositionSOUT(boost::bind(&PatternGenerator::getWaistPosition,this,_1,_2),\n                         OneStepOfControlS,\n                         \"PatternGenerator(\"+name+\")::output(vector)::waistposition\")\n      ,waistpositionabsoluteSOUT(boost::bind(&PatternGenerator::getWaistPositionAbsolute,this,_1,_2),\n                                 OneStepOfControlS,\n                                 \"PatternGenerator(\"+name+\")::output(vector)::waistpositionabsolute\")\n\n      ,dataInProcessSOUT(boost::bind(&PatternGenerator::getDataInProcess, this, _1, _2),\n                         OneStepOfControlS,\n                         \"PatternGenerator(\"+name+\")::output(bool)::inprocess\")\n      ,InitZMPRefSOUT( boost::bind(&PatternGenerator::getInitZMPRef,this,_1,_2),\n                       OneStepOfControlS,\n                       \"PatternGenerator(\"+name+\")::output(vector)::initzmpref\" )\n\n      ,InitCoMRefSOUT( boost::bind(&PatternGenerator::getInitCoMRef,this,_1,_2),\n                       OneStepOfControlS,\n                       \"PatternGenerator(\"+name+\")::output(matrix)::initcomref\" )\n\n      ,InitWaistPosRefSOUT( boost::bind(&PatternGenerator::getInitWaistPosRef,this,_1,_2),\n                            OneStepOfControlS,\n                            \"PatternGenerator(\"+name+\")::output(vector)::initwaistposref\" )\n\n      ,InitWaistAttRefSOUT( boost::bind(&PatternGenerator::getInitWaistAttRef,this,_1,_2),\n                            OneStepOfControlS,\n                            \"PatternGenerator(\"+name+\")::output(vectorRPY)::initwaistattref\" )\n\n      ,InitLeftFootRefSOUT( boost::bind(&PatternGenerator::getInitLeftFootRef,this,_1,_2),\n                            OneStepOfControlS,\n                            \"PatternGenerator(\"+name+\")::output(homogeneousmatrix)::initleftfootref\" )\n\n      ,InitRightFootRefSOUT( boost::bind(&PatternGenerator::getInitRightFootRef,this,_1,_2),\n                             OneStepOfControlS,\n                             \"PatternGenerator(\"+name+\")::output(homogeneousmatrix)::initrightfootref\" )\n      ,leftFootContactSOUT( boost::bind(&PatternGenerator::getLeftFootContact,this,_1,_2),\n                            OneStepOfControlS,\n                            \"PatternGenerator(\"+name+\")::output(bool)::leftfootcontact\" )\n      ,rightFootContactSOUT( boost::bind(&PatternGenerator::getRightFootContact,this,_1,_2),\n                             OneStepOfControlS,\n                             \"PatternGenerator(\"+name+\")::output(bool)::rightfootcontact\")\n\n\n    {\n      m_MotionSinceInstanciationToThisSequence.setIdentity();\n\n      m_LocalTime = 0;\n      m_TimeStep = 0.005;\n      m_DoubleSupportPhaseState = false;\n      m_forceFeedBack = false ;\n      m_feedBackControl = false ;\n\n      m_ZMPRefPos.resize(4);\n      m_ZMPRefPos.fill(0.0);\n      m_ZMPRefPos(3) = 1.0;\n      m_COMRefPos.resize(3);\n      m_COMRefPos.fill(0.0);\n      m_ZMPPrevious.resize(4);\n      m_ZMPPrevious(3) = 1.0;\n      m_dCOMRefPos.resize(3);\n      m_dCOMRefPos.fill(0.0);\n      m_InitZMPRefPos.resize(3);\n      m_InitZMPRefPos.fill(0);\n      m_InitCOMRefPos.resize(3);\n      m_InitCOMRefPos.fill(0);\n      m_InitWaistRefPos.resize(3);\n      m_InitWaistRefPos.fill(0);\n      m_InitWaistRefAtt.resize(3);\n      m_InitWaistRefAtt.fill(0);\n      m_dComAttitude.resize(3);\n      m_dComAttitude.fill(0);\n      m_VelocityReference.resize(3);\n      m_VelocityReference.fill(0.0);\n      m_WaistAttitude.resize(3);\n      m_WaistAttitude.fill(0);\n      m_ComAttitude.resize(3);\n      m_ComAttitude.fill(0);\n      m_WaistPosition.resize(3);\n      m_WaistPosition.fill(0);\n      m_WaistAttitudeAbsolute.resize(3);\n      m_WaistAttitudeAbsolute.fill(0);\n      m_WaistPositionAbsolute.resize(3);\n      m_WaistPositionAbsolute.fill(0);\n\n      m_k_Waist_kp1.setIdentity();\n\n      m_SupportFoot = 1; // Means that we do not know which support foot it is.\n      m_ReferenceFrame = WORLD_FRAME;\n\n      sotDEBUGIN(5);\n\n      firstSINTERN.setDependencyType(TimeDependency<int>::BOOL_DEPENDENT);\n      // TODO: here, the 'setConstant' destroy the pointer toward\n      // function initOneStepOfControl. By calling firstSINTERN(t), whatever t,\n      // nothing will happen (well, it will just return 0).\n      // To initialize firstSINTERN (without destroying the pointer), use\n      // firstSINTERN.setReady() instead.\n      // TODO: Remove the next line: // firstSINTERN.setConstant(0);\n      firstSINTERN.setReady(true);\n\n      //OneStepOfControlS.setDependencyType(TimeDependency<int>::ALWAYS_READY);\n      //  OneStepOfControlS.setConstant(0);\n\n\n      OneStepOfControlS.addDependency( LeftFootCurrentPosSIN  );\n      OneStepOfControlS.addDependency( RightFootCurrentPosSIN );\n      OneStepOfControlS.addDependency( velocitydesSIN );\n      OneStepOfControlS.addDependency( firstSINTERN );\n      OneStepOfControlS.addDependency( motorControlJointPositionSIN );\n      OneStepOfControlS.addDependency( comSIN );\n      OneStepOfControlS.addDependency( comStateSIN );\n      OneStepOfControlS.addDependency( zmpSIN );\n      OneStepOfControlS.addDependency( forceSIN );\n\n      // For debug, register OSOC (not relevant for normal use).\n      signalRegistration( OneStepOfControlS );\n\n#if 0\n\n      signalRegistration( jointPositionSIN <<\n                          motorControlJointPositionSIN <<\n                          ZMPPreviousControllerSIN <<\n                          ZMPRefSOUT <<\n                          CoMRefSOUT <<\n                          dCoMRefSOUT);\n      signalRegistration( dataInProcessSOUT <<\n                          LeftFootCurrentPosSIN <<\n                          RightFootCurrentPosSIN <<\n                          LeftFootRefSOUT <<\n                          RightFootRefSOUT);\n\n      signalRegistration( SupportFootSOUT <<\n                          jointWalkingErrorPositionSOUT <<\n                          waistattitudeSOUT <<\n                          waistpositionSOUT <<\n                          waistattitudeabsoluteSOUT <<\n                          waistpositionabsoluteSOUT);\n\n      signalRegistration( comattitudeSOUT <<\n                          dcomattitudeSOUT );\n\n      signalRegistration( dotLeftFootRefSOUT <<\n                          dotRightFootRefSOUT);\n\n      signalRegistration( InitZMPRefSOUT <<\n                          InitCoMRefSOUT <<\n                          InitWaistPosRefSOUT <<\n                          InitWaistAttRefSOUT <<\n                          InitLeftFootRefSOUT <<\n                          InitRightFootRefSOUT <<\n                          comSIN <<\n                          velocitydesSIN);\n#else\n      signalRegistration( dataInProcessSOUT );\n\n      signalRegistration( jointPositionSIN <<\n                          motorControlJointPositionSIN <<\n                          ZMPPreviousControllerSIN <<\n                          ZMPRefSOUT <<\n                          CoMRefSOUT <<\n                          dCoMRefSOUT);\n\n      signalRegistration( comStateSIN << zmpSIN << forceSIN << forceSOUT );\n\n      signalRegistration(comSIN <<\n                         velocitydesSIN <<\n                         LeftFootCurrentPosSIN <<\n                         RightFootCurrentPosSIN <<\n                         LeftFootRefSOUT <<\n                         RightFootRefSOUT);\n\n      signalRegistration( SupportFootSOUT <<\n                          jointWalkingErrorPositionSOUT <<\n                          comattitudeSOUT <<\n                          dcomattitudeSOUT <<\n                          waistattitudeSOUT );\n\n      signalRegistration( waistpositionSOUT <<\n                          waistattitudeabsoluteSOUT <<\n                          waistpositionabsoluteSOUT);\n\n\n      signalRegistration( dotLeftFootRefSOUT <<\n                          dotRightFootRefSOUT);\n\n      signalRegistration( InitZMPRefSOUT <<\n                          InitCoMRefSOUT <<\n                          InitWaistPosRefSOUT <<\n                          InitWaistAttRefSOUT <<\n                          InitLeftFootRefSOUT <<\n                          InitRightFootRefSOUT );\n\n      signalRegistration( leftFootContactSOUT <<\n                          rightFootContactSOUT);\n\n#endif\n      initCommands();\n\n      // init filter for force signals \"to be removed\"\n      m_bufferForce.clear();\n      int n=10;\n      double sum=0,tmp=0;\n      m_filterWindow.resize(n+1);\n      for(int i=0;i<n+1;i++)\n      {\n        tmp =sin((M_PI*i)/n);\n        m_filterWindow[i]=tmp*tmp;\n      }\n\n      for(int i=0;i<n+1;i++)\n        sum+= m_filterWindow[i];\n\n      for(int i=0;i<n+1;i++)\n        m_filterWindow[i]/= sum;\n\n      m_initForce.resize(6);\n      m_currentForces.resize(6);\n      //dataInProcessSOUT.setReference( &m_dataInProcess );\n      //m_wrml2urdfIndex.clear();\n\n      sotDEBUGOUT(5);\n    }\n\n    bool PatternGenerator::InitState(void)\n    {\n\n\n      sotDEBUGIN(5);\n      // TODO\n      // Instead of (0) ie .access(0), it could be rather used:\n      // .accessCopy()\n      // Instead of copy value (ml::Vector pos) it could be rather\n      // used reference (const ml::Vector & post)\n      Vector res;\n\t  MAL_VECTOR_TYPE(double) lWaistPosition;\n      if (m_InitPositionByRealState)\n\t{\n\t  const Vector& pos = jointPositionSIN(m_LocalTime);\n\n      MAL_VECTOR_RESIZE(lWaistPosition, 6);\n      for(unsigned int i = 0; i < 6; ++i)\n      {\n        lWaistPosition(i) = pos(i);\n      }\n\t  //  m_ZMPPrevious[2] =m_AnkleSoilDistance; // Changed the reference frame.\n\n\t  res.resize( pos.size()-6);\n\n\t  for(unsigned i=0;i<res.size();i++)\n\t    res(i) = pos(i+6);\n\n\t  Vector lZMPPrevious = ZMPPreviousControllerSIN(m_LocalTime);\n\t  for(unsigned int i=0;i<3;i++)\n\t    m_ZMPPrevious[i] = lZMPPrevious(i);\n\t}\n      else\n\t{\n\t  res = motorControlJointPositionSIN(m_LocalTime);\n\t  //for(unsigned i=0;i<res.size();i++)\n\t  //res(m_wrml2urdfIndex[i]) = res(i);\n\t}\n\n      Vector com = comSIN(m_LocalTime);\n\n\n      m_JointErrorValuesForWalking.resize(res.size());\n\n      sotDEBUG(5) << \"m_LocalTime:\" << m_LocalTime << endl;\n      sotDEBUG(5) << \"Joint Values:\" << res << endl;\n\n      try\n\t{\n\t  boost::numeric::ublas::vector<double> bres; bres.resize(res.size());\n\t  for(int i=0;i<res.size();i++) bres(i) = res(i);\n\t  m_PGI->SetCurrentJointValues(bres);\n\t  //      m_ZMPPrevious[2] = -m_AnkleSoilDistance; // Changed the reference frame.\n\n\n\t  // Evaluate current position of the COM, ZMP and feet\n\t  // according to the state of the robot.\n\t  PatternGeneratorJRL::COMState lStartingCOMState;\n\t  MAL_S3_VECTOR_TYPE(double) lStartingZMPPosition;\n\t  PatternGeneratorJRL::FootAbsolutePosition InitLeftFootAbsPos;\n\t  PatternGeneratorJRL::FootAbsolutePosition InitRightFootAbsPos;\n\n\t  m_PGI->EvaluateStartingState(lStartingCOMState,\n\t\t\t\t       lStartingZMPPosition,\n\t\t\t\t       lWaistPosition,\n\t\t\t\t       InitLeftFootAbsPos,\n\t\t\t\t       InitRightFootAbsPos);\n\n\t  // Put inside sotHomogeneous representation\n\t  m_InitCOMRefPos(0) = lStartingCOMState.x[0];\n\t  m_InitCOMRefPos(1) = lStartingCOMState.y[0];\n\t  m_InitCOMRefPos(2) = lStartingCOMState.z[0];\n\n\t  m_InitZMPRefPos(0) = lStartingCOMState.x[0];\n\t  m_InitZMPRefPos(1) = lStartingCOMState.y[0];\n\t  m_InitZMPRefPos(2) = 0;\n\n\t  if (m_InitPositionByRealState)\n\t    {\n\t      m_ZMPPrevious[0] = lStartingCOMState.x[0];\n\t      m_ZMPPrevious[1] = lStartingCOMState.y[0];\n\t      m_ZMPPrevious[2] = 0;\n\t    }\n\t  sotDEBUG(5) << \"InitZMPRefPos :\" <<m_InitZMPRefPos<< endl;\n\n\t  m_InitWaistRefPos(0) =\n\t    m_WaistPositionAbsolute(0) = lWaistPosition(0);\n\t  m_InitWaistRefPos(1) =\n\t    m_WaistPositionAbsolute(1) = lWaistPosition(1);\n\t  m_InitWaistRefPos(2) =\n\t    m_WaistPositionAbsolute(2) = lWaistPosition(2);\n\n\t  m_InitWaistRefAtt(0) =\n\t    m_WaistAttitudeAbsolute(0) = lWaistPosition(3);\n\t  m_InitWaistRefAtt(1) =\n\t    m_WaistAttitudeAbsolute(1) = lWaistPosition(4);\n\t  m_InitWaistRefAtt(2) =\n\t    m_WaistAttitudeAbsolute(2) = lWaistPosition(5);\n\n\n\t  FromAbsoluteFootPosToDotHomogeneous(InitRightFootAbsPos,\n\t\t\t\t\t      m_InitRightFootPosition,\n\t\t\t\t\t      m_dotRightFootPosition);\n\t  FromAbsoluteFootPosToDotHomogeneous(InitLeftFootAbsPos,\n\t\t\t\t\t      m_InitLeftFootPosition,\n\t\t\t\t\t      m_dotLeftFootPosition);\n\t  Eigen::Matrix<double, 4,1> newtmp,oldtmp;\n\t  oldtmp(0) =  m_InitCOMRefPos(0); oldtmp(1) =  m_InitCOMRefPos(1);\n\t  oldtmp(2) =  m_InitCOMRefPos(2); oldtmp(3)=1.0;\n\t  newtmp = m_MotionSinceInstanciationToThisSequence* oldtmp;\n\t  m_InitCOMRefPos(0) = newtmp(0);\tm_InitCOMRefPos(1) = newtmp(1);\n\t  m_InitCOMRefPos(2) = newtmp(2);\n\n\t  oldtmp(0) =  m_InitZMPRefPos(0); oldtmp(1) =  m_InitZMPRefPos(1);\n\t  oldtmp(2) =  m_InitZMPRefPos(2);\n\t  newtmp = m_MotionSinceInstanciationToThisSequence* oldtmp;\n\t  m_InitZMPRefPos(0) = newtmp(0); m_InitZMPRefPos(1) = newtmp(1);\n\t  m_InitZMPRefPos(2) = newtmp(2);\n\n\n\t  if (!m_InitPositionByRealState)\n\t    {\n\n\t      MatrixHomogeneous invInitLeftFootRef;\n\t      invInitLeftFootRef = m_InitLeftFootPosition.inverse();\n\t      m_k_Waist_kp1 = m_k_Waist_kp1 * invInitLeftFootRef;\n\t      m_MotionSinceInstanciationToThisSequence =\n\t\tm_MotionSinceInstanciationToThisSequence * m_k_Waist_kp1;\n\t    }\n\n\t  m_k_Waist_kp1 = m_InitLeftFootPosition;\n\n\t  m_InitLeftFootPosition = m_MotionSinceInstanciationToThisSequence*\n\t    m_InitLeftFootPosition;\n\t  m_InitRightFootPosition = m_MotionSinceInstanciationToThisSequence*\n\t    m_InitRightFootPosition;\n\n\t  m_LeftFootPosition = m_InitLeftFootPosition;\n\t  m_RightFootPosition = m_InitRightFootPosition;\n\n\t  sotDEBUG(5) << \"m_InitCOMRefPos: \" << m_InitCOMRefPos;\n\n\t  sotDEBUG(5) << \"m_InitZMPRefPos: \" << m_InitZMPRefPos;\n\t  sotDEBUG(5) << \"m_LeftFootPosition: \" << m_LeftFootPosition;\n\t  sotDEBUG(5) << \"m_RightFootPosition: \" << m_RightFootPosition;\n\t  sotDEBUG(5) << \"m_MotionSinceInstanciationToThisSequence\" <<\n\t    m_MotionSinceInstanciationToThisSequence<< std::endl;\n\n\t  sotDEBUG(5) << \" Init Waist Ref. Position \" << m_InitWaistRefPos << endl;\n\t  sotDEBUG(5) << \" Init Waist Ref. Attitude \" << m_InitWaistRefAtt << endl;\n\n\t  sotDEBUG(5) << \"ILF :\" <<m_InitLeftFootPosition << \" \"\n\t\t      << \"LRF :\" <<m_InitRightFootPosition << endl;\n\n\t}\n      catch(...)\n\t{\n\t  SOT_THROW ExceptionPatternGenerator( ExceptionPatternGenerator::PATTERN_GENERATOR_JRL,\n\t\t\t\t\t       \"Error while setting the current joint values of the WPG.\");\n\t  return false;\n\t}\n\n      m_InitPositionByRealState = false;\n      sotDEBUGOUT(5);\n      return true;\n    }\n\n    bool PatternGenerator::buildModel( void )\n    {\n      bool ok=true;\n      // Parsing the file.\n      se3::urdf::buildModel(m_urdfFile, se3::JointModelFreeFlyer(), m_robotModel);\n\n\n      m_robotData = new se3::Data(m_robotModel) ;\n      // Creating the humanoid robot.\n      m_PR = new pg::PinocchioRobot() ;\n      m_PR->initializeRobotModelAndData(&m_robotModel,m_robotData);\n      // Read xml/srdf stream\n      std::ifstream srdf_stream(m_srdfFile.c_str());\n      using boost::property_tree::ptree;\n      ptree pt;\n      try{\n        read_xml(srdf_stream, pt);\n        // Initialize the Right Foot\n        pg::PRFoot aFoot ;\n        string path = \"robot.specificities.feet.right.size\" ;\n        BOOST_FOREACH(const ptree::value_type & v, pt.get_child(path.c_str()))\n        {\n          aFoot.soleHeight = v.second.get<double>(\"height\");\n          aFoot.soleWidth  = v.second.get<double>(\"width\");\n          aFoot.soleDepth  = v.second.get<double>(\"depth\");\n        } // BOOST_FOREACH\n        path = \"robot.specificities.feet.right.anklePosition\" ;\n        BOOST_FOREACH(const ptree::value_type & v, pt.get_child(path.c_str()))\n        {\n          aFoot.anklePosition(0) = v.second.get<double>(\"x\");\n          aFoot.anklePosition(1) = v.second.get<double>(\"y\");\n          aFoot.anklePosition(2) = v.second.get<double>(\"z\");\n        } // BOOST_FOREACH\n        se3::FrameIndex ra = m_robotModel.getFrameId(\"r_ankle\");\n        aFoot.associatedAnkle = m_robotModel.frames.at(ra).parent ;\n        m_PR->initializeRightFoot(aFoot);\n        // Initialize the Left Foot\n        path = \"robot.specificities.feet.left.size\" ;\n        BOOST_FOREACH(const ptree::value_type & v, pt.get_child(path.c_str()))\n        {\n          aFoot.soleHeight = v.second.get<double>(\"height\");\n          aFoot.soleWidth  = v.second.get<double>(\"width\");\n          aFoot.soleDepth  = v.second.get<double>(\"depth\");\n        } // BOOST_FOREACH\n        path = \"robot.specificities.feet.left.anklePosition\" ;\n        BOOST_FOREACH(const ptree::value_type & v, pt.get_child(path.c_str()))\n        {\n          aFoot.anklePosition(0) = v.second.get<double>(\"x\");\n          aFoot.anklePosition(1) = v.second.get<double>(\"y\");\n          aFoot.anklePosition(2) = v.second.get<double>(\"z\");\n        } // BOOST_FOREACH\n        se3::FrameIndex la = m_robotModel.getFrameId(\"l_ankle\");\n        aFoot.associatedAnkle = m_robotModel.frames.at(la).parent ;\n        m_PR->initializeLeftFoot(aFoot);\n      }catch(...)\n      {\n        cerr << \"problem while reading the srdf file. File corrupted?\" << endl;\n        ok=false;\n      }\n\n      if (m_PR!=0)\n    {\n      pg::PRFoot * rightFoot = m_PR->rightFoot();\n      if (rightFoot!=0)\n        {\n          vector3d AnkleInFoot;\n          AnkleInFoot = rightFoot->anklePosition ;\n          m_AnkleSoilDistance = fabs(AnkleInFoot(2));\n        }\n      else ok=false;\n    }\n      else ok=false;\n\n      if (!ok)\n    {\n\t  SOT_THROW ExceptionPatternGenerator( ExceptionPatternGenerator::PATTERN_GENERATOR_JRL,\n\t\t\t\t\t       \"Error while creating humanoid robot dynamical model.\",\n\t\t\t\t\t       \"(PG creation process for object %s).\",\n\t\t\t\t\t       getName().c_str());\n\t}\n      try\n\t{\n      m_PGI = PatternGeneratorJRL::patternGeneratorInterfaceFactory(m_PR);\n\t}\n\n      catch (...)\n\t{\n\t  SOT_THROW ExceptionPatternGenerator( ExceptionPatternGenerator::PATTERN_GENERATOR_JRL,\n\t\t\t\t\t       \"Error while allocating the Pattern Generator.\",\n\t\t\t\t\t       \"(PG creation process for object %s).\",\n\t\t\t\t\t       getName().c_str());\n\t}\n      m_init = true;\n      return false;\n    }\n\n    PatternGenerator::\n    ~PatternGenerator( void )\n    {\n      sotDEBUGIN(25);\n      if( 0!=m_PR )\n    {\n      delete m_PR;\n      m_PR = 0;\n    }\n      if( 0!=m_PGI )\n    {\n      delete m_PGI;\n      m_PGI = 0;\n    }\n      if( 0!=m_robotData )\n\t{\n      delete m_robotData;\n      m_robotData = 0;\n    }\n      sotDEBUGOUT(25);\n      return;\n    }\n\n\n    /* --- CONFIG --------------------------------------------------------------- */\n    /* --- CONFIG --------------------------------------------------------------- */\n    /* --- CONFIG --------------------------------------------------------------- */\n    /* --- CONFIG --------------------------------------------------------------- */\n    void PatternGenerator::\n    setParamPreviewFile( const std::string& filename )\n    {\n      m_PreviewControlParametersFile = filename;\n    }\n\n    void PatternGenerator::\n    setURDFFile( const std::string& filename )\n    {\n      m_urdfFile = filename;\n    }\n    void PatternGenerator::\n    setSRDFFile( const std::string& filename )\n    {\n      m_srdfFile = filename;\n    }\n    void PatternGenerator::\n    setXmlRankFile( const std::string& filename )\n    {\n      m_xmlRankFile = filename;\n    }\n    void PatternGenerator::\n    addJointMapping(const std::string &link, const std::string &repName)\n    {\n      specialJoints_[link] = repName;\n    }\n\n    /* --- COMPUTE -------------------------------------------------------------- */\n    /* --- COMPUTE -------------------------------------------------------------- */\n    /* --- COMPUTE -------------------------------------------------------------- */\n\n#include <jrl/mal/boostspecific.hh>\n\n    Vector & PatternGenerator::\n    getZMPRef(Vector & ZMPRefval, int time)\n    {\n      sotDEBUGIN(5);\n\n      OneStepOfControlS(time);\n\n      ZMPRefval.resize(3);\n      ZMPRefval(0) = m_ZMPRefPos(0);\n      ZMPRefval(1) = m_ZMPRefPos(1);\n      ZMPRefval(2) = m_ZMPRefPos(2);\n      sotDEBUG(5) << \"ZMPRefPos transmitted\" << m_ZMPRefPos\n\t\t  << \" \" << ZMPRefval << endl;\n\n      sotDEBUGOUT(5);\n      return ZMPRefval;\n    }\n\n    Vector & PatternGenerator::\n    getCoMRef(Vector & CoMRefval, int time)\n    {\n      sotDEBUGIN(25);\n\n      OneStepOfControlS(time);\n      CoMRefval = m_COMRefPos;\n\n      sotDEBUGOUT(25);\n      return CoMRefval;\n    }\n\n    Vector & PatternGenerator::\n    getdCoMRef(Vector & CoMRefval, int time)\n    {\n      sotDEBUGIN(25);\n\n      OneStepOfControlS(time);\n      CoMRefval = m_dCOMRefPos;\n\n      sotDEBUGOUT(25);\n      return CoMRefval;\n    }\n\n    Vector & PatternGenerator::\n    getExternalForces(Vector & forces, int time)\n    {\n      sotDEBUGIN(25);\n\n      OneStepOfControlS(time);\n      forces = m_currentForces;\n\n      sotDEBUGOUT(25);\n      return forces;\n    }\n\n    Vector & PatternGenerator::\n    getInitZMPRef(Vector & InitZMPRefval, int /*time*/)\n    {\n      sotDEBUGIN(25);\n\n      sotDEBUG(25) << \"InitZMPRefPos transmitted\" << m_InitZMPRefPos\n\t\t   << \" \" << InitZMPRefval << std::endl;\n      InitZMPRefval.resize(3);\n      InitZMPRefval(0) = m_InitZMPRefPos(0);\n      InitZMPRefval(1) = m_InitZMPRefPos(1);\n      InitZMPRefval(2) = m_InitZMPRefPos(2);\n\n      sotDEBUGOUT(25);\n      return InitZMPRefval;\n    }\n\n    Vector & PatternGenerator::\n    getInitCoMRef(Vector & InitCoMRefval, int /*time*/)\n    {\n      sotDEBUGIN(25);\n\n      InitCoMRefval.resize(3);\n      InitCoMRefval(0) = m_InitCOMRefPos(0);\n      InitCoMRefval(1) = m_InitCOMRefPos(1);\n      InitCoMRefval(2) = m_InitCOMRefPos(2);\n\n\n      sotDEBUGOUT(25);\n      return InitCoMRefval;\n    }\n\n    Vector & PatternGenerator::\n    getInitWaistPosRef(Vector & InitWaistRefval, int /*time*/)\n    {\n      sotDEBUGIN(25);\n\n      InitWaistRefval = m_InitWaistRefPos;\n\n      sotDEBUGOUT(25);\n      return InitWaistRefval;\n    }\n    VectorRollPitchYaw & PatternGenerator::\n    getInitWaistAttRef(VectorRollPitchYaw & InitWaistRefval, int /*time*/)\n    {\n      sotDEBUGIN(25);\n\n      for(unsigned int i=0;i<3;++i)\n\tInitWaistRefval(i) = m_InitWaistRefAtt(i);\n\n      sotDEBUGOUT(25);\n      return InitWaistRefval;\n    }\n\n\n\n    MatrixHomogeneous & PatternGenerator::\n    getLeftFootRef(MatrixHomogeneous & LeftFootRefVal, int time)\n    {\n      sotDEBUGIN(25);\n\n      OneStepOfControlS(time);\n      LeftFootRefVal = m_LeftFootPosition;\n      sotDEBUGOUT(25) ;\n      return LeftFootRefVal;\n    }\n    MatrixHomogeneous & PatternGenerator::\n    getRightFootRef(MatrixHomogeneous & RightFootRefval, int time)\n    {\n      sotDEBUGIN(25);\n\n      OneStepOfControlS(time);\n\n      RightFootRefval = m_RightFootPosition;\n      sotDEBUGOUT(25);\n      return RightFootRefval;\n    }\n    MatrixHomogeneous & PatternGenerator::\n    getdotLeftFootRef(MatrixHomogeneous & LeftFootRefVal, int time)\n    {\n      sotDEBUGIN(25);\n\n      OneStepOfControlS(time);\n      LeftFootRefVal = m_dotLeftFootPosition;\n      sotDEBUGOUT(25) ;\n      return LeftFootRefVal;\n    }\n    MatrixHomogeneous & PatternGenerator::\n    getdotRightFootRef(MatrixHomogeneous & RightFootRefval, int time)\n    {\n      sotDEBUGIN(25);\n\n      OneStepOfControlS(time);\n\n      RightFootRefval = m_dotRightFootPosition;\n      sotDEBUGOUT(25);\n      return RightFootRefval;\n    }\n\n    MatrixHomogeneous & PatternGenerator::\n    getInitLeftFootRef(MatrixHomogeneous & LeftFootRefVal, int /*time*/)\n    {\n      sotDEBUGIN(25);\n\n      LeftFootRefVal = m_InitLeftFootPosition;\n      sotDEBUGOUT(25) ;\n      return LeftFootRefVal;\n    }\n    MatrixHomogeneous & PatternGenerator::\n    getInitRightFootRef(MatrixHomogeneous & RightFootRefval, int /*time*/)\n    {\n      sotDEBUGIN(25);\n\n      RightFootRefval = m_InitRightFootPosition;\n      sotDEBUGOUT(25);\n      return RightFootRefval;\n    }\n\n    MatrixHomogeneous & PatternGenerator::\n    getFlyingFootRef(MatrixHomogeneous & FlyingFootRefval, int time)\n    {\n      sotDEBUGIN(25);\n      OneStepOfControlS(time);\n      FlyingFootRefval = m_FlyingFootPosition;\n      sotDEBUGOUT(25);\n      return FlyingFootRefval;\n    }\n\n    bool & PatternGenerator ::\n    getLeftFootContact(bool &res, int time)\n    {\n      sotDEBUGIN(25);\n      OneStepOfControlS(time);\n      res = m_leftFootContact;\n      sotDEBUGOUT(25);\n      return res;\n\n    }\n\n    bool & PatternGenerator ::\n    getRightFootContact(bool &res, int time)\n    {\n      sotDEBUGIN(25);\n      OneStepOfControlS(time);\n      res = m_rightFootContact;\n      sotDEBUGOUT(25);\n      return res;\n\n    }\n\n    int &PatternGenerator::\n    InitOneStepOfControl(int &dummy, int /*time*/)\n    {\n      sotDEBUGIN(15);\n      // TODO: modified first to avoid the loop.\n      firstSINTERN.setReady(false);\n      //  buildModel();\n      // Todo: modified the order of the calls\n      //OneStepOfControlS(time);\n      sotDEBUGIN(15);\n      return dummy;\n    }\n\n    void PatternGenerator::getAbsoluteWaistPosAttHomogeneousMatrix(MatrixHomogeneous &aWaistMH)\n    {\n\n      const double cr = cos(m_WaistAttitudeAbsolute(0)); // ROLL\n      const double sr = sin(m_WaistAttitudeAbsolute(0));\n      const double cp = cos(m_WaistAttitudeAbsolute(1)); // PITCH\n      const double sp = sin(m_WaistAttitudeAbsolute(1));\n      const double cy = cos(m_WaistAttitudeAbsolute(2)); // YAW\n      const double sy = sin(m_WaistAttitudeAbsolute(2));\n\n      aWaistMH.matrix().setZero();\n\n      aWaistMH(0,0) = cy*cp;\n      aWaistMH(0,1) = cy*sp*sr-sy*cr;\n      aWaistMH(0,2) = cy*sp*cr+sy*sr;\n      aWaistMH(0,3) = m_WaistPositionAbsolute(0);\n\n      aWaistMH(1,0) = sy*cp;\n      aWaistMH(1,1) = sy*sp*sr+cy*cr;\n      aWaistMH(1,2) = sy*sp*cr-cy*sr;\n      aWaistMH(1,3) = m_WaistPositionAbsolute(1);\n\n      aWaistMH(2,0) = -sp;\n      aWaistMH(2,1) = cp*sr;\n      aWaistMH(2,2) = cp*cr;\n      aWaistMH(2,3) = m_WaistPositionAbsolute(2);\n\n      aWaistMH(3,3) = 1.0;\n\n    }\n\n    void PatternGenerator::FromAbsoluteFootPosToDotHomogeneous(pg::FootAbsolutePosition aFootPosition,\n\t\t\t\t\t\t\t       MatrixHomogeneous &aFootMH,\n\t\t\t\t\t\t\t       MatrixHomogeneous &adotFootMH)\n    {\n      MatrixRotation dRot,Twist,Rot;\n      adotFootMH.setIdentity();\n      FromAbsoluteFootPosToHomogeneous(aFootPosition,aFootMH);\n\n      for(unsigned int i=0;i<3;i++)\n\tfor(unsigned int j=0;j<3;j++)\n\t  Rot(i,j) = aFootMH(i,j);\n\n      Twist(0,0)=0.0; Twist(0,1)= -aFootPosition.dtheta; Twist(0,2) = aFootPosition.domega;\n      Twist(1,0)= aFootPosition.dtheta; Twist(1,1)= 0.0; Twist(1,2) = aFootPosition.domega2;\n      Twist(2,0)= -aFootPosition.domega; Twist(2,1)= -aFootPosition.domega2; Twist(2,2) = 0.0;\n\n      dRot = Twist * Rot;\n\n      for(unsigned int i=0;i<3;i++)\n\tfor(unsigned int j=0;j<3;j++)\n\t  adotFootMH(i,j) = dRot(i,j);\n\n      adotFootMH(0,3) = aFootPosition.dx;\n      adotFootMH(1,3) = aFootPosition.dy;\n      adotFootMH(2,3) = aFootPosition.dz;\n\n    }\n\n    void PatternGenerator::FromAbsoluteFootPosToHomogeneous(pg::FootAbsolutePosition aFootPosition,\n\t\t\t\t\t\t\t    MatrixHomogeneous &aFootMH)\n    {\n      double c,s,co,so;\n      c = cos(aFootPosition.theta*M_PI/180.0);\n      s = sin(aFootPosition.theta*M_PI/180.0);\n\n      co = cos(aFootPosition.omega*M_PI/180.0);\n      so = sin(aFootPosition.omega*M_PI/180.0);\n\n      aFootMH(0,0) = c*co;        aFootMH(0,1) = -s;       aFootMH(0,2) = c*so;\n      aFootMH(1,0) = s*co;        aFootMH(1,1) =  c;       aFootMH(1,2) = s*so;\n      aFootMH(2,0) = -so ;        aFootMH(2,1) =  0;       aFootMH(2,2) =   co;\n      aFootMH(3,0) = 0 ;          aFootMH(3,1) =  0;       aFootMH(3,2) =   0;\n\n      aFootMH(0,3) = aFootPosition.x + m_AnkleSoilDistance*so;\n      aFootMH(1,3) = aFootPosition.y;\n      aFootMH(2,3) = aFootPosition.z + m_AnkleSoilDistance*co;\n      aFootMH(3,3) = 1.0;\n    }\n\n    int &PatternGenerator::\n    OneStepOfControl(int &dummy, int time)\n    {\n      m_LocalTime=time;\n      int lSupportFoot; // Local support foot.\n      // Default value\n      m_JointErrorValuesForWalking.fill(0.0);\n      const int robotSize = m_JointErrorValuesForWalking.size()+6;\n\n      try\n\t{\n\t  for(unsigned int i=0;i<3;i++)\n\t    m_ZMPRefPos(i) = m_ZMPPrevious[i];\n\t}\n      catch(...)\n\t{ m_ZMPRefPos(0) = m_ZMPRefPos(1) = m_ZMPRefPos(2) = 0.0;\n\t  m_ZMPRefPos(3) = 1.0;};\n      //  m_WaistAttitudeAbsolute.fill(0);\n      //  m_WaistPositionAbsolute.fill(0);\n\n      try\n\t{\n\t  m_LeftFootPosition = LeftFootCurrentPosSIN(time);\n\t  m_RightFootPosition = RightFootCurrentPosSIN(time);\n\t}\n      catch (...)\n\t{ };\n\n      try\n\t{\n\t  m_VelocityReference = velocitydesSIN(time);\n\t}\n      catch(...)\n\t{ };\n\n      sotDEBUG(25) << \"LeftFootCurrentPos:  \" << m_LeftFootPosition << endl;\n      sotDEBUG(25) << \"RightFootCurrentPos:  \" << m_RightFootPosition << endl;\n\n      sotDEBUGIN(15);\n      if (m_PGI!=0)\n\t{\n\t  // TODO: Calling firstSINTERN may cause an infinite loop\n\t  // since the function initonestepofcontrol calls without\n\t  // control this actual function. 'Hopefully', the function\n\t  // pointer of firstSINTERN has been earlier destroyed\n\t  // by setconstant(0).\n\t  firstSINTERN(time);\n\t  Vector CurrentState = motorControlJointPositionSIN(time);\n\t  assert( CurrentState.size() == robotSize );\n\n\t  /*! \\brief Absolute Position for the left and right feet. */\n\t  pg::FootAbsolutePosition lLeftFootPosition,lRightFootPosition;\n\t  lLeftFootPosition.x=0.0;lLeftFootPosition.y=0.0;lLeftFootPosition.z=0.0;\n\t  lRightFootPosition.x=0.0;lRightFootPosition.y=0.0;lRightFootPosition.z=0.0;\n\t  /*! \\brief Absolute position of the reference CoM. */\n\t  pg::COMState lCOMRefState;\n\t  sotDEBUG(45) << \"mc = \" << CurrentState << std::endl;\n\n\t  MAL_VECTOR_DIM(CurrentConfiguration,double,robotSize);\n\t  MAL_VECTOR_DIM(CurrentVelocity,double,robotSize);\n\t  MAL_VECTOR_DIM(CurrentAcceleration,double,robotSize);\n\t  MAL_VECTOR_DIM(ZMPTarget,double,3);\n\t  MAL_VECTOR_FILL(ZMPTarget,0);\n\n\t  sotDEBUG(25) << \"Before One Step of control \" << lCOMRefState.x[0] << \" \"\n\t\t       << lCOMRefState.y[0] << \" \" << lCOMRefState.z[0] << endl;\n\t  sotDEBUG(4) << \" VelocityReference \" << m_VelocityReference << endl;\n\n\t  m_PGI->setVelocityReference(m_VelocityReference(0),\n\t\t\t\t      m_VelocityReference(1),\n\t\t\t\t      m_VelocityReference(2));\n\n      try{\n        if(m_feedBackControl)\n        {\n          Vector curCoMState (3) ;\n          Vector curZMP (3) ;\n\n          curCoMState = comStateSIN(time);\n          curZMP = zmpSIN(time);\n\n          lCOMRefState.x[0] = curCoMState(0) ;\n          lCOMRefState.y[0] = curCoMState(1) ;\n          lCOMRefState.z[0] = curCoMState(2) ;\n          lCOMRefState.x[2] = (lCOMRefState.x[0]-curZMP(0))*9.81/lCOMRefState.z[0];\n          lCOMRefState.y[2] = (lCOMRefState.y[0]-curZMP(1))*9.81/lCOMRefState.z[0];\n          lCOMRefState.z[2] = 0.0 ;\n\n//          for (unsigned i=0 ; i<3 ; ++i)\n//            lCOMRefState.x[i] = curCoMState(i) ;\n//          for (unsigned i=0 ; i<3 ; ++i)\n//            lCOMRefState.y[i] = curCoMState(i+3) ;\n//          for (unsigned i=0 ; i<3 ; ++i)\n//            lCOMRefState.z[i] = curCoMState(i+6) ;\n\n//          ZMPTarget(0) = lCOMRefState.x[0]-lCOMRefState.x[2]*lCOMRefState.z[0]/9.81 ;\n//          ZMPTarget(1) = lCOMRefState.y[0]-lCOMRefState.y[2]*lCOMRefState.z[0]/9.81 ;\n//          ZMPTarget(2) = 0.0; //to be fixed considering the support foot\n        }\n      }catch(...)\n      {\n        cout << \"problems with signals reading\" << endl;\n        useFeedBackSignals(false);\n      };\n\n      try{\n          if(m_forceFeedBack)\n          {\n        Vector extForce (3);\n        extForce = forceSIN(time);\n        if(time<50*0.005)\n        {\n          m_initForce=extForce;\n        }\n        extForce -= m_initForce;\n        unsigned int n=321;\n        if(m_bufferForce.size()<n-1)\n        {\n          m_bufferForce.push_back(extForce);\n        }\n        else\n        {\n          m_bufferForce.push_back(extForce);\n          double ltmp1(0.0), ltmp2(0.0), ltmp3(0.0) ;\n          for(unsigned int k=0;k<m_filterWindow.size();k++)\n          {\n            ltmp1 += m_filterWindow[k]*m_bufferForce[n-1-k](0);\n            ltmp2 += m_filterWindow[k]*m_bufferForce[n-1-k](1);\n            ltmp3 += m_filterWindow[k]*m_bufferForce[n-1-k](2);\n          }\n          extForce(0) = ltmp1 ;\n          extForce(1) = ltmp2 ;\n          extForce(2) = ltmp3 ;\n          m_bufferForce.pop_front();\n        }\n        double threshold = 7.0;\n        double thresholdy = 4.0;\n        if(extForce(0)>threshold)\n          extForce(0)=threshold;\n        if(extForce(0)<-threshold)\n          extForce(0)=-threshold;\n\n        if(extForce(1)>thresholdy)\n          extForce(1)=thresholdy;\n        if(extForce(1)<-thresholdy)\n          extForce(1)=-thresholdy;\n\n        if(extForce(2)>threshold)\n          extForce(2)=threshold;\n        if(extForce(2)<-threshold)\n          extForce(2)=-threshold;\n\n        if((extForce(0)*extForce(0)+extForce(1)*extForce(1)) < 100)\n        {\n          extForce(0)=0.0;\n          extForce(1)=0.0;\n        }\n        m_currentForces = extForce ;\n        ostringstream oss (\"\");\n        //oss << \":perturbationforce \" << extForce(0) << \" \" << extForce(1) << \" \" << extForce(2);\n        oss << \":perturbationforce \" << -m_currentForces(1) << \" \" << /*m_currentForces(0)*/0.0 << \" \" << m_currentForces(2);\n        // cout << oss.str() << endl ;\n        pgCommandLine(oss.str());\n          }\n      }catch(...)\n      {\n        //cout << \"problems with force signals reading\" << endl;\n      };\n\n      // Test if the pattern value has some value to provide.\n\t  if (m_PGI->RunOneStepOfTheControlLoop(CurrentConfiguration,\n\t\t\t\t\t\tCurrentVelocity,\n\t\t\t\t\t\tCurrentAcceleration,\n\t\t\t\t\t\tZMPTarget,\n\t\t\t\t\t\tlCOMRefState,\n\t\t\t\t\t\tlLeftFootPosition,\n\t\t\t\t\t\tlRightFootPosition))\n\t    {\n\t      sotDEBUG(25) << \"After One Step of control \" << endl\n\t\t\t   << \"CurrentState:\" << CurrentState << endl\n\t\t\t   << \"CurrentConfiguration:\" << CurrentConfiguration << endl;\n\n\t      m_ZMPRefPos(0) = ZMPTarget[0];\n\t      m_ZMPRefPos(1) = ZMPTarget[1];\n\t      m_ZMPRefPos(2) = ZMPTarget[2];\n\t      m_ZMPRefPos(3) = 1.0;\n\t      sotDEBUG(2) << \"ZMPTarget returned by the PG: \"<< m_ZMPRefPos <<endl;\n\t      for(int i=0;i<3;i++)\n\t\t{\n\t\t  m_WaistPositionAbsolute(i) = CurrentConfiguration(i);\n\t\t  m_WaistAttitudeAbsolute(i) = CurrentConfiguration(i+3);\n\t\t}\n\t      m_COMRefPos(0) = lCOMRefState.x[0];\n\t      m_COMRefPos(1) = lCOMRefState.y[0];\n\t      m_COMRefPos(2) = lCOMRefState.z[0];\n\t      sotDEBUG(2) << \"COMRefPos returned by the PG: \"<< m_COMRefPos <<endl;\n\t      m_dCOMRefPos(0) = lCOMRefState.x[1];\n\t      m_dCOMRefPos(1) = lCOMRefState.y[1];\n\t      m_dCOMRefPos(2) = lCOMRefState.z[1];\n\n\t      m_ComAttitude(0) = lCOMRefState.roll[0];\n\t      m_ComAttitude(1) = lCOMRefState.pitch[0];\n\t      m_ComAttitude(2) = lCOMRefState.yaw[0];\n\n\t      m_dComAttitude(0) = lCOMRefState.roll[1];\n\t      m_dComAttitude(1) = lCOMRefState.pitch[1];\n\t      m_dComAttitude(2) = lCOMRefState.yaw[1];\n\n\t      sotDEBUG(2) << \"dCOMRefPos returned by the PG: \"<< m_dCOMRefPos <<endl;\n\t      sotDEBUG(2) << \"CurrentState.size()\"<< CurrentState.size()<<endl;\n\t      sotDEBUG(2) << \"CurrentConfiguration.size()\"<< CurrentConfiguration.size()<<endl;\n\t      sotDEBUG(2) << \"m_JointErrorValuesForWalking.size(): \"<< m_JointErrorValuesForWalking.size() <<endl;\n\n\n\t      // In this setting we assume that there is a proper mapping between\n\t      // CurrentState and CurrentConfiguration.\n\t      unsigned int SizeCurrentState = CurrentState.size();\n\t      unsigned int SizeCurrentConfiguration = CurrentConfiguration.size()-6;\n\t      unsigned int MinSize = std::min(SizeCurrentState,SizeCurrentConfiguration);\n\n\t      if (m_JointErrorValuesForWalking.size()>=MinSize)\n\t\t{\n\t\t  for(unsigned int li=0;li<MinSize;li++)\n\t\t    m_JointErrorValuesForWalking(li)= (CurrentConfiguration(li+6)- CurrentState(li) )/m_TimeStep;\n\t\t}\n\t      else\n\t\t{\n\t\t  std::cout <<\"The state of the robot and the one return by the WPG are different\" << std::endl;\n\t\t  sotDEBUG(25) << \"Size not coherent between CurrentState and m_JointErrorValuesForWalking: \"\n\t\t\t       << CurrentState.size()<< \" \"\n\t\t\t       << m_JointErrorValuesForWalking.size()<< \" \"\n\t\t\t       << endl;\n\t\t}\n\t      sotDEBUG(2) << \"Juste after updating m_JointErrorValuesForWalking\" << endl;\n\n\t      sotDEBUG(1) << \"lLeftFootPosition : \"\n\t\t\t  << lLeftFootPosition.x << \" \"\n\t\t\t  << lLeftFootPosition.y << \" \"\n\t\t\t  << lLeftFootPosition.z << \" \"\n\t\t\t  << lLeftFootPosition.theta << endl;\n\t      sotDEBUG(1) << \"lRightFootPosition : \"\n\t\t\t  << lRightFootPosition.x << \" \"\n\t\t\t  << lRightFootPosition.y << \" \"\n\t\t\t  << lRightFootPosition.z << \" \"\n\t\t\t  << lRightFootPosition.theta << endl;\n\n\t      sotDEBUG(25) << \"lCOMPosition : \"\n\t\t\t   << lCOMRefState.x[0] << \" \"\n\t\t\t   << lCOMRefState.y[0] << \" \"\n\t\t\t   << lCOMRefState.z[0] <<  endl;\n\n\t      /* Fill in the homogeneous matrix using the world reference frame*/\n\t      FromAbsoluteFootPosToDotHomogeneous(lLeftFootPosition,\n\t\t\t\t\t\t  m_LeftFootPosition,\n\t\t\t\t\t\t  m_dotLeftFootPosition);\n\t      FromAbsoluteFootPosToDotHomogeneous(lRightFootPosition,\n\t\t\t\t\t\t  m_RightFootPosition,\n\t\t\t\t\t\t  m_dotRightFootPosition);\n\n\t      /* We assume that the left foot is always the origin of the new frame. */\n\t      m_LeftFootPosition = m_MotionSinceInstanciationToThisSequence * m_LeftFootPosition;\n\t      m_RightFootPosition = m_MotionSinceInstanciationToThisSequence * m_RightFootPosition;\n\n\t       Eigen::Matrix<double, 4,1> newRefPos, oldRefPos;\n\t      oldRefPos(0) = m_COMRefPos(0); oldRefPos(1) = m_COMRefPos(1);\n\t      oldRefPos(2) = m_COMRefPos(2); oldRefPos(3) = 1.0;\n\t      newRefPos = m_MotionSinceInstanciationToThisSequence * oldRefPos;\n\t      m_COMRefPos(0) = newRefPos(0);\n\t      m_COMRefPos(1) = newRefPos(1);\n\t      m_COMRefPos(2) = newRefPos(2);\n\n\t      oldRefPos(0) = m_ZMPRefPos(0); oldRefPos(1) = m_ZMPRefPos(1);\n\t      oldRefPos(2) = m_ZMPRefPos(2); oldRefPos(3) = 1.0;\n\t      newRefPos = m_MotionSinceInstanciationToThisSequence * oldRefPos;\n\t      m_ZMPRefPos(0) = newRefPos(0);\n\t      m_ZMPRefPos(1) = newRefPos(1);\n\t      m_ZMPRefPos(2) = newRefPos(2);\n\n\t      sotDEBUG(25) << \"lLeftFootPosition.stepType: \" << lLeftFootPosition.stepType\n\t\t\t   << \" lRightFootPosition.stepType: \" << lRightFootPosition.stepType <<endl;\n\t      // Find the support foot feet.\n\t      m_leftFootContact = true;\n\t      m_rightFootContact = true;\n\t      if (lLeftFootPosition.stepType==-1)\n\t\t{\n\t\t  lSupportFoot=1; m_leftFootContact = true;\n\t\t  if (lRightFootPosition.stepType!=-1)\n\t\t    m_rightFootContact = false;\n\t\t  m_DoubleSupportPhaseState = 0;\n\t\t}\n\t      else if (lRightFootPosition.stepType==-1)\n\t\t{\n\t\t  lSupportFoot=0; m_rightFootContact = true;\n\t\t  if (lLeftFootPosition.stepType!=-1)\n\t\t    m_leftFootContact = false;\n\t\t  m_DoubleSupportPhaseState = 0;\n\t\t}\n\t      else /* m_LeftFootPosition.z ==m_RightFootPosition.z\n\t\t      We keep the previous support foot half the time of the double support phase..\n\t\t   */\n\t\t{\n\t\t  lSupportFoot=m_SupportFoot;\n\t\t}\n\n\t      /* Update the class related member. */\n\t      m_SupportFoot = lSupportFoot;\n\n\t      if ((m_ReferenceFrame==EGOCENTERED_FRAME) ||\n\t\t  (m_ReferenceFrame==LEFT_FOOT_CENTERED_FRAME) ||\n\t\t  (m_ReferenceFrame==WAIST_CENTERED_FRAME))\n\t\t{\n\t\t  sotDEBUG(25) << \"Inside egocentered frame \" <<endl;\n\t\t  MatrixHomogeneous PoseOrigin,iPoseOrigin, WaistPoseAbsolute;\n\n\t\t  getAbsoluteWaistPosAttHomogeneousMatrix(WaistPoseAbsolute);\n\n\t\t  if (m_ReferenceFrame==EGOCENTERED_FRAME)\n\t\t    {\n\t\t      if (m_SupportFoot==1)\n\t\t\tPoseOrigin = m_LeftFootPosition;\n\t\t      else\n\t\t\tPoseOrigin = m_RightFootPosition;\n\t\t    }\n\t\t  else if (m_ReferenceFrame==LEFT_FOOT_CENTERED_FRAME)\n\t\t    {\n\t\t      PoseOrigin = m_LeftFootPosition;\n\t\t    }\n\t\t  else if (m_ReferenceFrame==WAIST_CENTERED_FRAME)\n\t\t    {\n\t\t      PoseOrigin = WaistPoseAbsolute;\n\t\t    }\n\t\t  iPoseOrigin = PoseOrigin.inverse();\n\n\t\t  sotDEBUG(25) << \"Old ComRef:  \" << m_COMRefPos << endl;\n\t\t  sotDEBUG(25) << \"Old LeftFootRef:  \" << m_LeftFootPosition << endl;\n\t\t  sotDEBUG(25) << \"Old RightFootRef:  \" << m_RightFootPosition << endl;\n\t\t  sotDEBUG(25) << \"Old PoseOrigin:  \" << PoseOrigin << endl;\n\n\n\t\t  Eigen::Matrix<double, 4,1> lVZMPRefPos, lV2ZMPRefPos;\n\t\t  Eigen::Matrix<double, 4,1> lVCOMRefPos, lV2COMRefPos;\n\n\t\t  for(unsigned int li=0;li<3;li++)\n\t\t    {\n\t\t      lVZMPRefPos(li) = m_ZMPRefPos(li);\n\t\t      lVCOMRefPos(li) = m_COMRefPos(li);\n\t\t    }\n\t\t  lVZMPRefPos(3) = lVCOMRefPos(3) = 1.0;\n\n\t\t  // We do not touch to ZMP.\n\t\t  lV2ZMPRefPos = iPoseOrigin * (WaistPoseAbsolute * lVZMPRefPos);\n\n\t\t  // Put the CoM reference pos in the Pos Origin reference frame.\n\t\t  lV2COMRefPos = iPoseOrigin * lVCOMRefPos;\n\n\t\t  MatrixHomogeneous lMLeftFootPosition = m_LeftFootPosition;\n\t\t  MatrixHomogeneous lMRightFootPosition = m_RightFootPosition;\n\n\t\t  m_LeftFootPosition = iPoseOrigin * lMLeftFootPosition;\n\t\t  m_RightFootPosition = iPoseOrigin * lMRightFootPosition;\n\n\t\t  for(unsigned int i=0;i<3;i++)\n\t\t    {\n\t\t      m_ZMPRefPos(i) = lV2ZMPRefPos(i);\n\t\t      m_COMRefPos(i) = lV2COMRefPos(i);\n\t\t    }\n\n\t\t  MatrixHomogeneous lWaistPoseAbsoluste = WaistPoseAbsolute;\n\t\t  WaistPoseAbsolute = iPoseOrigin * WaistPoseAbsolute;\n\n\t\t  MatrixRotation newWaistRot;\n\t\t  newWaistRot = WaistPoseAbsolute.linear();\n\t\t  VectorRollPitchYaw newWaistRPY;\n\t\t  newWaistRPY = (newWaistRot.eulerAngles(2,1,0)).reverse();\n\t\t  m_WaistAttitude = newWaistRPY;\n\n\t\t  m_WaistPosition = WaistPoseAbsolute.translation();\n\n\t\t  sotDEBUG(25) << \"ComRef:  \" << m_COMRefPos << endl;\n\t\t  sotDEBUG(25) << \"iPoseOrigin:  \" << iPoseOrigin << endl;\n\t\t}\n\t      sotDEBUG(25) << \"After egocentered frame \" << endl;\n\n\t      sotDEBUG(25) << \"ComRef:  \" << m_COMRefPos << endl;\n\t      sotDEBUG(25) << \"LeftFootRef:  \" << m_LeftFootPosition << endl;\n\t      sotDEBUG(25) << \"RightFootRef:  \" << m_RightFootPosition << endl;\n\t      sotDEBUG(25) << \"ZMPRefPos:  \" << m_ZMPRefPos << endl;\n\t      sotDEBUG(25) << \"m_MotionSinceInstanciationToThisSequence\" <<\n\t\tm_MotionSinceInstanciationToThisSequence<< std::endl;\n\n\t      for(unsigned int i=0;i<3;i++)\n\t\tm_ZMPPrevious[i] = m_ZMPRefPos(i);\n\n\t      m_dataInProcess = 1;\n\t    }\n\t  else\n\t    {\n\t      sotDEBUG(1) << \"Error while compute one step of PG.\"\n\t\t\t  << m_dataInProcess << std::endl;\n\t      // TODO: SOT_THROW\n\t      if (m_dataInProcess==1)\n\t\t{\n\t\t  MatrixHomogeneous invInitLeftFootRef,Diff;\n\t\t  invInitLeftFootRef = m_InitLeftFootPosition.inverse();\n\t\t  Diff = invInitLeftFootRef * m_LeftFootPosition;\n\n\t\t  m_k_Waist_kp1 = m_k_Waist_kp1 * Diff;\n\n\t\t}\n\t      m_dataInProcess = 0;\n\t    }\n\t  sotDEBUG(25) << \"After computing error \" << m_JointErrorValuesForWalking << endl;\n\t}\n      else\n\t{\n\t  m_COMRefPos = comSIN.access(time);\n\t  m_ZMPRefPos(0) = m_COMRefPos(0);\n\t  m_ZMPRefPos(1) = m_COMRefPos(1);\n\t  m_ZMPRefPos(2) = 0.0;\n\t  m_ZMPRefPos(3) = 1.0;\n\t}\n      sotDEBUG(25) << \"LeftFootRef:  \" << m_LeftFootPosition << endl;\n      sotDEBUG(25) << \"RightFootRef:  \" << m_RightFootPosition << endl;\n      sotDEBUG(25) << \"COMRef:  \" << m_COMRefPos << endl;\n\n      sotDEBUGOUT(15);\n      return dummy;\n    }\n\n\n    /* --- PARAMS --------------------------------------------------------------- */\n    /* --- PARAMS --------------------------------------------------------------- */\n\n    void PatternGenerator::\n    initCommands( void )\n    {\n      using namespace command;\n      addCommand(\"setURDFpath\",\n         makeCommandVoid1(*this,&PatternGenerator::setURDFFile,\n                  docCommandVoid1(\"Set URDF directory+name.\",\n\t\t\t\t\t\t  \"string (path name)\")));\n      addCommand(\"setSRDFpath\",\n         makeCommandVoid1(*this,&PatternGenerator::setSRDFFile,\n                  docCommandVoid1(\"Set SRDF directory+name.\",\n\t\t\t\t\t\t  \"string (file name)\")));\n\n      addCommand(\"setXmlRank\",\n         makeCommandVoid1(*this,&PatternGenerator::setXmlRankFile,\n                  docCommandVoid1(\"Set XML rank file directory+name.\",\n                          \"string (file name)\")));\n\n      std::string docstring = \"    \\n\"\n        \"    Set foot parameters\\n\"\n        \"      Input:\\n\"\n        \"        - a floating point number: the sole length,\\n\"\n        \"        - a floating point number: the sole width,\\n\"\n        \"    \\n\";\n      addCommand(\"setSoleParameters\",\n\t\t makeCommandVoid2(*this,&PatternGenerator::setSoleParameters,\n                        docstring));\n\n\n      addCommand(\"addJointMapping\",\n\t\t makeCommandVoid2(*this,&PatternGenerator::addJointMapping,\n\t\t\t\t  docCommandVoid1(\"Map link names.\",\n\t\t\t\t\t\t  \"string (link name)\"\n\t\t\t\t\t\t  \"string (rep name)\")));\n\n      addCommand(\"setParamPreview\",\n\t\t makeCommandVoid1(*this,&PatternGenerator::setParamPreviewFile,\n\t\t\t\t  docCommandVoid1(\"Set [guess what!] file\",\n\t\t\t\t\t\t  \"string (path/filename)\")));\n      // for the setFiles, need to implement the makeCmdVoid5... later\n      // displayfiles... later too\n      addCommand(\"buildModel\",\n       \t\t makeCommandVoid0(*this,\n\t\t\t\t  (void (PatternGenerator::*) (void))&PatternGenerator::buildModel,\n\t\t\t\t  docCommandVoid0(\"From the files, parse and build.\")));\n      addCommand(\"initState\",\n       \t\t makeCommandVoid0(*this,\n\t\t\t\t  (void (PatternGenerator::*) (void))&PatternGenerator::InitState,\n\t\t\t\t  docCommandVoid0(\"From q and model, compute the initial geometry.\")));\n      addCommand(\"frameReference\",\n       \t\t makeCommandVoid1(*this,\n\t\t\t\t  &PatternGenerator::setReferenceFromString,\n\t\t\t\t  docCommandVoid1(\"Set the reference.\",\n\t\t\t\t\t\t  \"string among \"\n\t\t\t\t\t\t  \"World|Egocentered|LeftFootcentered|Waistcentered\")));\n\n      addCommand(\"getTimeStep\",\n\t\t makeDirectGetter(*this,&m_TimeStep,docDirectGetter(\"timestep\",\"double\")));\n      addCommand(\"setTimeStep\",\n\t\t makeDirectSetter(*this,&m_TimeStep,docDirectSetter(\"timestep\",\"double\")));\n\n      addCommand(\"getInitByRealState\",\n\t\t makeDirectGetter(*this,&m_InitPositionByRealState,\n\t\t\t\t  docDirectGetter(\"initByRealState\",\"bool\")));\n      addCommand(\"setInitByRealState\",\n\t\t makeDirectSetter(*this,&m_InitPositionByRealState,\n\t\t\t\t  docDirectSetter(\"initByRealState\",\"bool\")));\n\n      addCommand(\"addOnLineStep\",\n       \t\t makeCommandVoid3(*this,&PatternGenerator::addOnLineStep,\n\t\t\t\t  docCommandVoid3(\"Add a step on line.\",\n\t\t\t\t\t\t  \"double (x)\",\"double (y)\",\"double (theta)\")));\n      addCommand(\"addStep\",\n       \t\t makeCommandVoid3(*this,&PatternGenerator::addOnLineStep,\n\t\t\t\t  docCommandVoid3(\"Add a step in the stack.\",\n\t\t\t\t\t\t  \"double (x)\",\"double (y)\",\"double (theta)\")));\n      addCommand(\"parseCmd\",\n       \t\t makeCommandVoid1(*this,&PatternGenerator::pgCommandLine,\n\t\t\t\t  docCommandVoid1(\"Send the command line to the internal pg object.\",\n\t\t\t\t\t\t  \"string (command line)\")));\n\n      addCommand(\"feedBackControl\",\n             makeCommandVoid1(*this,&PatternGenerator::useFeedBackSignals,\n                  docCommandVoid1(\"Enable or disable the use of the CoMfullState Signal inside the pg.\",\n                          \"string (true or false)\")));\n\n      addCommand(\"dynamicFilter\",\n             makeCommandVoid1(*this,&PatternGenerator::useDynamicFilter,\n                  docCommandVoid1(\"Enable or disable the use of the CoMfullState Signal inside the pg.\",\n                          \"string (true or false)\")));\n\n      // Change next step : todo (deal with FootAbsolutePosition...).\n\n     addCommand(\"debug\",\n       \t\t makeCommandVoid0(*this,\n\t\t\t\t  (void (PatternGenerator::*) (void))&PatternGenerator::debug,\n\t\t\t\t  docCommandVoid0(\"Launch a debug command.\")));\n\n    }\n\n    void PatternGenerator::debug(void)\n    {\n      std::cout << \"t = \" << dataInProcessSOUT.getTime() << std::endl;\n      std::cout << \"deptype = \" << dataInProcessSOUT.dependencyType << std::endl;\n      std::cout << \"child = \" << dataInProcessSOUT.updateFromAllChildren << std::endl;\n      std::cout << \"last = \" << dataInProcessSOUT.lastAskForUpdate << std::endl;\n\n      std::cout << \"inprocess = \" << dataInProcessSOUT.needUpdate(40) << std::endl;\n      std::cout << \"onestep = \" << OneStepOfControlS.needUpdate(40) << std::endl;\n\n      dataInProcessSOUT.Signal<unsigned int,int>::access(1);\n    }\n\n\n    void PatternGenerator::addOnLineStep( const double & x, const double & y, const double & th)\n    {\n      assert( m_PGI!=0 );\n      m_PGI->AddOnLineStep(x,y,th);\n    }\n    void PatternGenerator::addStep( const double & x, const double & y, const double & th)\n    {\n      assert( m_PGI!=0 );\n      m_PGI->AddStepInStack(x,y,th);\n    }\n    void PatternGenerator::pgCommandLine( const std::string & cmdline )\n    {\n      assert( m_PGI!=0 );\n      std::istringstream cmdArgs( cmdline );\n      m_PGI->ParseCmd(cmdArgs);\n    }\n\n    void PatternGenerator::useFeedBackSignals( const bool & feedBack )\n    {\n      m_feedBackControl = feedBack ;\n      string cmdBool = feedBack?\"true\":\"false\" ;\n      assert( m_PGI!=0 );\n      std::istringstream cmdArgs( \":feedBackControl \" + cmdBool );\n      m_PGI->ParseCmd(cmdArgs);\n    }\n\n    void PatternGenerator::useDynamicFilter(const bool & dynamicFilter )\n    {\n      m_feedBackControl = dynamicFilter ;\n      string cmdBool = dynamicFilter?\"true\":\"false\" ;\n      assert( m_PGI!=0 );\n      std::istringstream cmdArgs( \":useDynamicFilter \" + cmdBool );\n      m_PGI->ParseCmd(cmdArgs);\n    }\n\n    int PatternGenerator::\n    stringToReferenceEnum( const std::string & FrameReference )\n    {\n      if (FrameReference==\"World\") return WORLD_FRAME;\n      else if (FrameReference==\"Egocentered\") return EGOCENTERED_FRAME;\n      else if (FrameReference==\"LeftFootcentered\")return LEFT_FOOT_CENTERED_FRAME;\n      else if (FrameReference==\"Waistcentered\")return WAIST_CENTERED_FRAME;\n      assert( false && \"String name should be in the list \"\n\t      \"World|Egocentered|LeftFootcentered|Waistcentered\" );\n      return 0;\n    }\n\n    void PatternGenerator::\n    setReferenceFromString( const std::string & str )\n    {\n      m_ReferenceFrame = stringToReferenceEnum( str );\n    }\n\n    Vector & PatternGenerator::getjointWalkingErrorPosition(Vector &res,int time)\n    {\n      sotDEBUGIN(5);\n\n      OneStepOfControlS(time);\n\n      res=m_JointErrorValuesForWalking;\n\n      sotDEBUGOUT(5);\n\n      return res;\n    }\n\n    unsigned int & PatternGenerator::\n    getSupportFoot(unsigned int &res, int /*time*/)\n    {\n      res = m_SupportFoot;\n      return res;\n    }\n\n    VectorRollPitchYaw & PatternGenerator::\n    getWaistAttitude( VectorRollPitchYaw&res, int time)\n    {\n      sotDEBUGIN(5);\n      OneStepOfControlS(time);\n      for( unsigned int i=0;i<3;++i ) { res(i) = m_WaistAttitude(i); }\n      sotDEBUG(5) << \"WaistAttitude: \" << m_WaistAttitude << endl;\n      sotDEBUGOUT(5);\n      return res;\n    }\n\n    dynamicgraph::Vector & PatternGenerator::\n    getdComAttitude( dynamicgraph::Vector& res, int time)\n    {\n      sotDEBUGIN(5);\n      OneStepOfControlS(time);\n      res.resize(3);\n      for( unsigned int i=0;i<3;++i ) { res(i) = m_dComAttitude(i); }\n      sotDEBUG(5) << \"ComAttitude: \" << m_dComAttitude << endl;\n      sotDEBUGOUT(5);\n      return res;\n    }\n\n\n    dynamicgraph::Vector& PatternGenerator::\n    getComAttitude( dynamicgraph::Vector& res, int time)\n    {\n      sotDEBUGIN(5);\n      OneStepOfControlS(time);\n      res.resize(3);\n      for( unsigned int i=0;i<3;++i ) { res(i) = m_ComAttitude(i); }\n      sotDEBUG(5) << \"ComAttitude: \" << m_ComAttitude << endl;\n      sotDEBUGOUT(5);\n      return res;\n    }\n\n    VectorRollPitchYaw & PatternGenerator::getWaistAttitudeAbsolute(VectorRollPitchYaw &res, int time)\n    {\n      sotDEBUGIN(5);\n      OneStepOfControlS(time);\n      sotDEBUG(15) << \"I survived one step of control\" << std::endl;\n      for( unsigned int i=0;i<3;++i ) { res(i) = m_WaistAttitudeAbsolute(i); }\n      sotDEBUG(5) << \"WaistAttitude: \" << m_WaistAttitudeAbsolute << endl;\n      sotDEBUGOUT(5);\n      return res;\n    }\n\n    Vector & PatternGenerator::\n    getWaistPosition(Vector &res, int time)\n    {\n      sotDEBUGIN(5);\n      OneStepOfControlS(time);\n      res = m_WaistPosition;\n      sotDEBUG(5) << \"WaistPosition: \" << m_WaistPosition << endl;\n      sotDEBUGOUT(5);\n      return res;\n    }\n    Vector & PatternGenerator::\n    getWaistPositionAbsolute(Vector &res, int time)\n    {\n      sotDEBUGIN(5);\n      OneStepOfControlS(time);\n      res = m_WaistPositionAbsolute;\n      /* ARGH ! ->  res(2) =0*/\n      sotDEBUG(5) << \"WaistPosition: \" << m_WaistPositionAbsolute << endl;\n      sotDEBUGOUT(5);\n      return res;\n    }\n\n    unsigned & PatternGenerator::\n    getDataInProcess(unsigned &res, int time)\n    {\n      sotDEBUGIN(5);\n      OneStepOfControlS(time);\n      res = m_dataInProcess;\n      sotDEBUG(5) << \"DataInProcess: \" << m_dataInProcess << endl;\n      sotDEBUGOUT(5);\n      return res;\n    }\n\n    void PatternGenerator::\n    setSoleParameters(const double& inSoleLength, const double& inSoleWidth)\n    {\n      m_soleLength = inSoleLength;\n      m_soleWidth  = inSoleWidth;\n    }\n  } // namespace dg\n} // namespace sot\n", "meta": {"hexsha": "c53c7d112f3bd55055ec06219a35ab5e4cf736c3", "size": 58439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pg.cpp", "max_stars_repo_name": "olivier-stasse/sot-pattern-generator", "max_stars_repo_head_hexsha": "f4c07418ae26b7085b5fe2b0c8cbb3a61cbb611b", "max_stars_repo_licenses": ["0BSD"], "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/pg.cpp", "max_issues_repo_name": "olivier-stasse/sot-pattern-generator", "max_issues_repo_head_hexsha": "f4c07418ae26b7085b5fe2b0c8cbb3a61cbb611b", "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": "src/pg.cpp", "max_forks_repo_name": "olivier-stasse/sot-pattern-generator", "max_forks_repo_head_hexsha": "f4c07418ae26b7085b5fe2b0c8cbb3a61cbb611b", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-26T07:09:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-26T07:09:30.000Z", "avg_line_length": 34.4366529169, "max_line_length": 125, "alphanum_fraction": 0.616061192, "num_tokens": 16097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19119740314960554}}
{"text": "#include \"kick.hh\"\n\n#include \"../MotionScript/motionscript.hh\"\n#include \"../util/log.hh\"\n\n#include <Eigen/Core>\n\nusing namespace bold;\nusing namespace Eigen;\nusing namespace std;\n\nstd::vector<std::shared_ptr<Kick const>> Kick::d_allKicks;\n\nvoid Kick::loadAll()\n{\n  // TODO load from config\n  // TODO produce kick params experimentally using kick-learner role\n\n  d_allKicks.push_back(make_shared<Kick const>(\n    \"forward-right\",\n    \"./motionscripts/kick-right.json\",\n    Bounds2d(Vector2d(0, 0), Vector2d(0.1, 0.2)),\n    Vector2d(0.0, 1.853),\n    Vector2d(0.065, 0.106)\n  ));\n\n  d_allKicks.push_back(make_shared<Kick const>(\n    \"forward-left\",\n    \"./motionscripts/kick-left.json\",\n    Bounds2d(Vector2d(-0.1, 0), Vector2d(0, 0.2)),\n    Vector2d(0.0, 1.853),\n    Vector2d(-0.065, 0.106)\n  ));\n\n  d_allKicks.push_back(make_shared<Kick const>(\n    \"cross-left\",\n    \"./motionscripts/kick-cross-left.json\",\n    Bounds2d(Vector2d(-0.1, 0), Vector2d(0.02, 0.16)),\n    Vector2d(1.002, 1.152),\n    Vector2d(-0.006, 0.105)\n  ));\n\n  d_allKicks.push_back(make_shared<Kick const>(\n    \"cross-right\",\n    \"./motionscripts/kick-cross-right.json\",\n    Bounds2d(Vector2d(-0.02, 0), Vector2d(0.1, 0.16)),\n    Vector2d(-1.002, 1.152),\n    Vector2d(0.006, 0.105)\n  ));\n\n  d_allKicks.push_back(make_shared<Kick const>(\n    \"cross-left-80\",\n    \"./motionscripts/kick-cross-left-80.json\",\n    Bounds2d(Vector2d(-0.1, 0), Vector2d(0.02, 0.2)),\n    Vector2d(1.0, 0.1),\n    Vector2d(-0.006, 0.105)\n  ));\n\n  d_allKicks.push_back(make_shared<Kick const>(\n    \"cross-right-80\",\n    \"./motionscripts/kick-cross-right-80.json\",\n    Bounds2d(Vector2d(-0.02, 0), Vector2d(0.1, 0.2)),\n    Vector2d(-1.0, 0.1),\n    Vector2d(0.006, 0.105)\n  ));\n}\n\nshared_ptr<Kick const> Kick::getById(string id)\n{\n  auto it = std::find_if(\n    d_allKicks.begin(),\n    d_allKicks.end(),\n    [id](shared_ptr<Kick const> const& kick) { return kick->getId() == id; });\n\n  if (it == d_allKicks.end())\n  {\n    log::error(\"Kick::getById\") << \"Requested kick with unknown id: \" << id;\n    throw runtime_error(\"Requested kick with unknown id\");\n  }\n\n  return *it;\n}\n\nKick::Kick(string id, string scriptPath, Bounds2d ballBounds, Vector2d endPos, Vector2d idealBallPos)\n: d_id(id),\n  d_motionScript(MotionScript::fromFile(scriptPath)),\n  d_ballBounds(ballBounds),\n  d_endPos(endPos),\n  d_idealBallPos(idealBallPos)\n{}\n\nMaybe<Vector2d> Kick::estimateEndPos(Vector2d const& ballPos) const\n{\n  // TODO end pos depends upon start pos -- need means of modelling this\n  // TODO model probabilistically, not absolutely, to allow learning risk/reward\n\n  if (!d_ballBounds.contains(ballPos))\n    return Maybe<Vector2d>::empty();\n\n  return Maybe<Vector2d>(d_endPos);\n}\n", "meta": {"hexsha": "f693ca4b56a0a1e4d47650b02cb1a106ed8320a8", "size": 2701, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Kick/kick.cc", "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": "Kick/kick.cc", "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": "Kick/kick.cc", "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": 26.4803921569, "max_line_length": 101, "alphanum_fraction": 0.6682710107, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.19093870227005427}}
{"text": "#include \"srs.h\"\n#include \"ChiSquared.h\"\n#include \"binheap.h\"\n#include \"gendef.h\"\n#include \"rand.h\"\n#include <cmath>\n#include <string.h>\n\n//#include <boost/math/distributions/chi_squared.hpp>\n\n// to handle large files\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#define _FILE_OFFSET_BITS 64\n#define O_LARGEFILE 0\n\nSRS::SRS() {\n  d = -1;\n  n = -1;\n  L = -1;\n  B = -1;\n  m = -1;\n  numUsedTrees = -1;\n  trees = NULL;\n  a_array = NULL;\n}\n\nSRS::~SRS() {\n  if (a_array) {\n    delete[] a_array;\n    a_array = NULL;\n  }\n\n  int l = L;\n  if (numUsedTrees != -1) {\n    l = numUsedTrees;\n  }\n\n  if (trees) {\n    for (int i = 0; i < l; i++) {\n      trees[i]->close();\n      delete trees[i];\n      trees[i] = NULL;\n    }\n\n    delete[] trees;\n    trees = NULL;\n  }\n}\n\nvoid SRS::init(int _d, int _n, int _B, int _L, int _m) {\n  d = _d;\n  n = _n;\n  B = _B;\n  L = _L;\n  m = _m;\n\n  gen_vectors();\n}\n\nvoid SRS::gen_vectors() {\n  int i = -1;\n\n  a_array = new float[m * L * d];\n  for (i = 0; i < m * L * d; i++)\n    a_array[i] = gaussian(0, 1);\n}\n\n/*****************************************************************\nbuilds SRS tree(s) from a dataset. data format:\nid coordinate_1 _2 ... _dim\n\n-para-\ndsPath\t\t\tthe dataset path\nindexPath\t  the folder containing the trees\n\n-return-\n0\t\t\t\tsuccess\n1\t\t\t\tfailure\n\n-prior-\nall tree parameters properly set.\n*****************************************************************/\n\nint SRS::buildFromFile(char *_dsPath, char *_indexPath) {\n  int ret = 0;\n\n  char fname[100];\n  int cnt = -1;\n  int i = -1;\n  int *key = NULL;\n  int son = -1;\n  FILE *fp = NULL;\n\n  fp = fopen64(_dsPath, \"r\");\n  BlockFile *d_blockFile = NULL;\n  char *blk = NULL;\n  int blk_pos = -1;\n\n  if (!fp) {\n    printf(\"Could not open the source file.\\n\");\n    ret = 1;\n\n    goto recycle;\n  }\n\n  fclose(fp);\n\n  strcpy(dsPath, _dsPath);\n  getFNameFromPath(dsPath, dsName);\n\n  strcpy(indexPath, _indexPath);\n  if (indexPath[strlen(indexPath) - 1] != '/')\n    strcat(indexPath, \"/\");\n\n  strcpy(dName, indexPath);\n  strcat(dName, \"data\");\n\n  strcpy(fname, indexPath);\n  strcat(fname, \"para\");\n\n  if (writeParaFile(fname)) {\n    ret = 1;\n    goto recycle;\n  }\n\n  key = new int[d];\n  trees = new RtreePtr[L];\n\n  for (i = 0; i < L; i++) {\n    printf(\"Tree %d (out of %d)\\n\", i + 1, L);\n\n    trees[i] = new ptRTree();\n\n    getTreeFname(i, fname);\n    trees[i]->init(fname, 4 * B, NULL, m);\n\n    cnt = 0;\n    // if (isBinary)\n    //   fp = fopen64(dsPath, \"rb\");\n    // else\n    fp = fopen64(dsPath, \"r\");\n\n    while (!feof(fp) && cnt < n) {\n      freadNextEntry(fp, &son, key);\n      if (son <= 0) {\n        printf(\"Sorry no negative id please.\\n\");\n\n        ret = 1;\n        goto recycle;\n      }\n      insert(i, son, key);\n      cnt++;\n\n      // if (cnt % 1000 == 0) {\n      //   printf(\"\\tInserted %d (%d%%)\\n\", cnt, cnt * 100 / n);\n      // }\n    }\n\n    if (cnt == n && !feof(fp)) {\n      printf(\"The dataset is larger than you said. Giving up...\\n\", n);\n      fclose(fp);\n      break;\n    }\n    fclose(fp);\n  }\n\n  for (i = 0; i < L; i++) {\n    trees[i]->close();\n    delete trees[i];\n    trees[i] = NULL;\n  }\n\n  delete[] trees;\n  trees = NULL;\n\nrecycle:\n  delete d_blockFile;\n  delete[] blk;\n  delete[] key;\n\n  return ret;\n}\n\n/*****************************************************************\nBuild a binary file for a dataset. data format:\nid coordinate_1 _2 ... _dim\n\n-para-\ndsPath      the dataset path\nindexPath  the folder containing the binary file (same as the one containing the\ntrees)\n\n-return-\n0       success\n1       failure\n*****************************************************************/\n\nint SRS::buildBinFromFile(char *_dsPath, char *_indexPath) {\n  int ret = 0;\n  char fname[100];\n  int cnt = -1;\n  int i = -1;\n  int *key = NULL;\n  int son = -1;\n  FILE *fp = NULL;\n\n  fp = fopen64(_dsPath, \"r\");\n  BlockFile *d_blockFile = NULL;\n  char *blk = NULL;\n  int blk_pos = -1;\n\n  if (!fp) {\n    printf(\"Could not open the source file.\\n\");\n    ret = 1;\n\n    goto recycle;\n  }\n\n  fclose(fp);\n\n  strcpy(dsPath, _dsPath);\n  getFNameFromPath(dsPath, dsName);\n\n  strcpy(indexPath, _indexPath);\n  if (indexPath[strlen(indexPath) - 1] != '/')\n    strcat(indexPath, \"/\");\n\n  strcpy(dName, indexPath);\n  strcat(dName, \"data\");\n\n  d_blockFile = new BlockFile(dName, 4 * B);\n  blk = new char[d_blockFile->blocklength];\n  blk_pos = 0;\n\n  strcpy(fname, indexPath);\n  strcat(fname, \"para\");\n\n  key = new int[d];\n  cnt = 0;\n  fp = fopen64(dsPath, \"r\");\n\n  while (!feof(fp) && cnt < n) {\n    freadNextEntry(fp, &son, key);\n    for (int j = 0; j < d; ++j) {\n      memcpy(&blk[blk_pos], &key[j], sizeof(int));\n      blk_pos += sizeof(int);\n      if (blk_pos == d_blockFile->blocklength) {\n        blk_pos = 0;\n        d_blockFile->append_block(blk);\n      }\n    }\n\n    if (son <= 0) {\n      printf(\"Sorry no negative id please.\\n\");\n\n      ret = 1;\n      goto recycle;\n    }\n    cnt++;\n  }\n  if (blk_pos != 0) {\n    d_blockFile->append_block(blk); // Thus the last block is not clear!!!\n  }\n\n  if (cnt == n && !feof(fp)) {\n    printf(\"The dataset is larger than you said. Giving up...\\n\", n);\n\n    ret = 1;\n    goto recycle;\n  }\n\n  fclose(fp);\n\nrecycle:\n  delete d_blockFile;\n  delete[] blk;\n\n  return ret;\n}\n\n/*****************************************************************\ncontinue builds SRS tree(s) from a dataset. data format:\nid coordinate_1 _2 ... _dim\n\n-para-\ndsPath      the dataset path\nindexPath   the folder containing the trees\n\n-return-\n0       success\n1       failure\n\n-prior-\nall tree parameters properly set\n*****************************************************************/\n\nint SRS::ctBuildFromFile(char *_dsPath, char *_indexPath) {\n  int ret = 0;\n\n  char fname[100];\n  int cnt = -1;\n  int i = -1;\n  int *key = NULL;\n  // float key = -0.0;\n  int son = -1;\n  FILE *fp = NULL;\n\n  fp = fopen64(_dsPath, \"r\");\n  BlockFile *d_blockFile = NULL;\n  char *blk = NULL;\n\n  if (!fp) {\n    printf(\"Could not open the source file.\\n\");\n\n    ret = 1;\n\n    goto recycle;\n  }\n\n  fclose(fp);\n\n  strcpy(dsPath, _dsPath);\n  getFNameFromPath(dsPath, dsName);\n\n  strcpy(indexPath, _indexPath);\n  if (indexPath[strlen(indexPath) - 1] != '/')\n    strcat(indexPath, \"/\");\n\n  strcpy(dName, indexPath);\n  strcat(dName, \"data\");\n\n  strcpy(fname, indexPath);\n  strcat(fname, \"para\");\n\n  key = new int[d];\n  trees = new RtreePtr[L];\n\n  for (i = 0; i < L; i++) {\n    printf(\"Tree %d (out of %d)\\n\", i + 1, L);\n\n    trees[i] = new ptRTree();\n\n    getTreeFname(i, fname);\n    trees[i]->init(fname, NULL);\n\n    cnt = 0;\n    fp = fopen64(dsPath, \"r\");\n\n    while (!feof(fp) && cnt < n) {\n      freadNextEntry(fp, &son, key);\n\n      if (son <= 0) {\n        printf(\"Sorry no negative id please.\\n\");\n\n        ret = 1;\n        goto recycle;\n      }\n      insert(i, son, key);\n      cnt++;\n\n      if (cnt % 1000 == 0) {\n        printf(\"\\tInserted %d (%d%%)\\n\", cnt, cnt * 100 / n);\n      }\n    }\n\n    if (cnt == n && !feof(fp)) {\n      printf(\"The dataset is larger than you said. Giving up...\\n\", n);\n\n      ret = 1;\n      goto recycle;\n    }\n\n    fclose(fp);\n  }\n\n  for (i = 0; i < L; i++) {\n    trees[i]->close();\n    delete trees[i];\n    trees[i] = NULL;\n  }\n\n  delete[] trees;\n  trees = NULL;\n\nrecycle:\n  delete d_blockFile;\n  delete[] blk;\n\n  return ret;\n}\n\n/*****************************************************************\nwrite the para file to the disk\n\n-para-\nfname\t\tpath of the file\n\n-return-\n0\t\t\tsuccess\n1\t\t\tfailure\n*****************************************************************/\n\nint SRS::writeParaFile(char *_fname) {\n  int ret = 0;\n\n  int i = -1;\n  int u = -1;\n  FILE *fp = NULL;\n  float *aVector = NULL;\n\n  fp = fopen64(_fname, \"r\");\n\n  if (fp) {\n    printf(\"index exists. \");\n\n    ret = 1;\n\n    goto recycle;\n  }\n\n  fp = fopen64(_fname, \"w\");\n  if (!fp) {\n    printf(\"I could not create %s.\\n\", _fname);\n    printf(\"Perhaps no such folder %s?\\n\", indexPath);\n\n    ret = 1;\n\n    goto recycle;\n  }\n\n  fprintf(fp, \"%s\\n\", dsPath);\n  fprintf(fp, \"B = %d\\n\", B);\n  fprintf(fp, \"n = %d\\n\", n);\n  fprintf(fp, \"d = %d\\n\", d);\n  fprintf(fp, \"l = %d\\n\", L);\n  fprintf(fp, \"m = %d\\n\", m);\n\n  for (i = 0; i < m * L; i++) {\n    getHashPara(i, &aVector);\n    fprintf(fp, \"%f\", aVector[0]);\n    for (u = 1; u < d; u++) {\n      fprintf(fp, \" %f\", aVector[u]);\n    }\n    fprintf(fp, \"\\n\");\n  }\n\nrecycle:\n  if (fp)\n    fclose(fp);\n\n  return ret;\n}\n\n/*****************************************************************\nget the file name of a srs-tree\n\n-para-\ni\t\t  which tree it is, from 0 to L- 1\nfname\t(out) the file name\n*****************************************************************/\n\nvoid SRS::getTreeFname(int _i, char *_fname) {\n  char c[100];\n\n  strcpy(_fname, indexPath);\n  sprintf(c, \"%d\", _i); // modified by Yifang\n  strcat(_fname, c);\n}\n\n/*****************************************************************\ninsert a point into the srs-trees.\n\n-para-\ntreeID\tinto which tree are we inserting (from 0 to L-1)\nson\t\t  the object's id\nkey\t\t  its coordinates\n\n -return-\n0\t\tsuccess\n1\t\tfailure\n*****************************************************************/\n\nint SRS::insert(int _treeID, int _son, int *_key) {\n  int ret = 0;\n  Entry *e = NULL;\n\n  e = new ptEntry();\n  e->init(trees[_treeID]);\n  e->level = 0;\n  e->son = _son;\n\n  for (int i = 0; i < m; ++i) {\n    e->bounces[2 * i] = e->bounces[2 * i + 1] =\n        getHashValue(_treeID * m + i, _key);\n  }\n  trees[_treeID]->insert(e);\n\n  return ret;\n}\n\n/*****************************************************************\nreturns the u-th random projection vector.\n\n-para-\nu\t\t\t    see above\na_vector\t(out) starting address of the a-vector, which is an array of\nsize d.\n*****************************************************************/\n\nvoid SRS::getHashPara(int _u, float **_a_vector) {\n  (*_a_vector) = &(a_array[_u * d]);\n}\n\n/*****************************************************************\ngets the inner product of key and the u-th random vector.\n\n-para-\nu\t\t  see above\nkey\t\traw coordinates\n\n-return-\nsee above\n*****************************************************************/\n\nfloat SRS::getHashValue(int _u, int *_key) {\n  float ret = 0;\n  float *a_vector = NULL;\n\n  getHashPara(_u, &a_vector);\n\n  for (int i = 0; i < d; i++) {\n    ret += a_vector[i] * _key[i];\n  }\n  return ret;\n}\n\n/*****************************************************************\nload an existing srs index.\n\n-para-\nparaPath\t\t    The full path of the parameter file\nstart_tree_ID   the first tree that we are going to use (default: 0)\nnumTrees        the number of trees that we are going to use (default: 1)\n\n-return-\n0\t\tsuccess\n1\t\tfailure\n*****************************************************************/\n\nint SRS::restore(char *_paraPath, int _start_tree_ID, int _numTrees) {\n  int ret = 0;\n\n  char fname[100];\n  int i = -1;\n  int len = -1;\n  numUsedTrees = _numTrees;\n\n  strcpy(indexPath, _paraPath);\n\n  len = strlen(indexPath);\n  if (indexPath[len - 1] != '/' && indexPath[len - 1] != '\\\\')\n    strcat(indexPath, \"/\");\n\n  strcpy(dName, indexPath);\n  strcat(dName, \"data\");\n\n  strcpy(fname, indexPath);\n  strcat(fname, \"para\");\n\n  if (readParaFile(fname)) {\n    ret = 1;\n    goto recycle;\n  }\n\n  if (_start_tree_ID + _numTrees > L) {\n    ret = 1;\n    goto recycle;\n  }\n\n  trees = new RtreePtr[_numTrees];\n\n  for (i = 0; i < _numTrees; i++) {\n    getTreeFname(_start_tree_ID + i, fname);\n\n    trees[i] = new ptRTree();\n    trees[i]->init(fname, NULL);\n  }\n\nrecycle:\n  return ret;\n}\n\n/*****************************************************************\nread the parameter file.\n\n-para-\nfname\t\tfull path of the para file\n\n-return-\n0\t\tsuccess\n1\t\tfailure\n*****************************************************************/\n\nint SRS::readParaFile(char *_fname) {\n  int ret = 0;\n\n  FILE *fp = NULL;\n  int cnt = 0;\n  int i = -1;\n  int j = -1;\n  int k = -1;\n\n  fp = fopen64(_fname, \"r\");\n\n  if (!fp) {\n    printf(\"Could not open %s.\\n\", _fname);\n\n    ret = 1;\n    goto recycle;\n  }\n\n  fscanf(fp, \"%s\\n\", dsPath);\n  getFNameFromPath(dsPath, dsName);\n\n  fscanf(fp, \"B = %d\\n\", &B);\n  fscanf(fp, \"n = %d\\n\", &n);\n  fscanf(fp, \"d = %d\\n\", &d);\n  // fscanf(fp, \"t = %d\\n\", &t);\n  fscanf(fp, \"l = %d\\n\", &L);\n  fscanf(fp, \"m = %d\\n\", &m);\n\n  a_array = new float[m * L * d];\n\n  cnt = 0;\n\n  for (i = 0; i < L * m; i++) {\n    for (k = 0; k < d; k++) {\n      fscanf(fp, \"%f\", &a_array[cnt]);\n      cnt++;\n    }\n    fscanf(fp, \"\\n\");\n  }\n\nrecycle:\n\n  if (fp)\n    fclose(fp);\n\n  return ret;\n}\n\n/*****************************************************************\nreads the next pt from the original data file.\n\n-para-\nfp\t\thandle of the file\nson\t\t(out) pt id\nkey\t\tpt coordinates\n*****************************************************************/\n\nvoid SRS::freadNextEntry(FILE *_fp, int *_son, int *_key) {\n  int i;\n  fscanf(_fp, \"%d\", _son);\n  for (i = 0; i < d; i++) {\n    fscanf(_fp, \" %d\", &(_key[i]));\n  }\n\n  fscanf(_fp, \"\\n\");\n}\n\n/*****************************************************************\nreads the pt with given id from the binary data file.\n\n-para-\npt    (out) pt coordinates\nbf   block file\nid   pt id\n\n-return-\nnumber of I/O that cost in this step\n*****************************************************************/\n\nint SRS::readData(int *_pt, BlockFile *_bf, int _id) {\n  int ret = 0;\n  int blk_pos = ((long long)d * sizeof(int) * (_id - 1)) % _bf->blocklength;\n  int blk_id = (long long)d * sizeof(int) * (_id - 1) / _bf->blocklength;\n  char *blk = new char[_bf->blocklength];\n  // printf(\"%d %d\\n\",blk_pos,blk_id);\n\n  _bf->read_block(blk, blk_id);\n  ret++;\n  for (int i = 0; i < d; ++i) {\n    if (blk_pos == _bf->blocklength) {\n      blk_id++;\n      _bf->read_block(blk, blk_id);\n      ret++;\n      blk_pos = 0;\n    }\n    memcpy(&_pt[i], &blk[blk_pos], sizeof(int));\n    blk_pos += sizeof(int);\n  }\n\n  delete[] blk;\n  return ret;\n}\n\n/*----------------------------------------------------------------\n  auxiliary function called by SRS:knn.\n  ----------------------------------------------------------------*/\n\nint SRS_hcomp(const void *_e1, const void *_e2) {\n  SRS_Hentry *e1 = (SRS_Hentry *)_e1;\n  SRS_Hentry *e2 = (SRS_Hentry *)_e2;\n\n  int ret = 0;\n\n  if (e1->gap < e2->gap)\n    ret = -1;\n  else if (e1->gap > e2->gap)\n    ret = 1;\n\n  return ret;\n}\n\n/*----------------------------------------------------------------\n  auxiliary function called by SRS:knn.\n  ----------------------------------------------------------------*/\n\nvoid SRS_hdestroy(const void *_e) {\n  SRS_Hentry *e = (SRS_Hentry *)_e;\n\n  delete e;\n  e = NULL;\n}\n\n/*----------------------------------------------------------------\n  auxiliary function called by SRS:knn.\n  ----------------------------------------------------------------*/\n\nfloat SRS::updateknn(SRS_Hentry *_rslt, SRS_Hentry *_he, int _k) {\n  float ret = -1;\n\n  int i = -1;\n  int pos = -1;\n  bool alreadyIn = false;\n\n  for (i = 0; i < _k; i++) {\n    if (_he->id == _rslt[i].id) {\n      alreadyIn = true;\n      break;\n    } else if (compfloats(_he->dist, _rslt[i].dist) == -1) {\n      break;\n    }\n  }\n\n  pos = i;\n\n  if (!alreadyIn && pos < _k) {\n    for (i = _k - 1; i > pos; i--)\n      _rslt[i].setto(&(_rslt[i - 1]));\n\n    _rslt[pos].setto(_he);\n  }\n  ret = _rslt[_k - 1].dist;\n\n  return ret;\n}\n\n/*****************************************************************\nfinds the top-k c-approximate nearest neighbors.\n\n-para-\nq             query\nk             k of top-k\nrslt          (out) top-k cANN\nnumTrees      number of trees that used (default 1) (only report the case of\n\"numTrees = 1\" in the paper) start_tree_id id of the first tree (default 0) c\napproximation ratio that will be used in the early termination condition tau\nthreshold in Algorithm 2 in the paper t             maximum proportion of points\nthat will be verified (i.e., T/n) early_stop    whether the early termination\ncondition is applied or not\n\n-return-\nnumber of I/O\n*****************************************************************/\nint SRS::knn(int *_q, int _k, SRS_Hentry *_rslt, int _start_tree_ID,\n             int _numTrees, float _c, float _tau, float _t, bool early_stop) {\n  int ret = 0; // total I/O\n  int cnt = 0;\n  int treeId = 0;\n  int son = 0;\n  bool again = true;\n  float *qk = NULL;\n  BinHeap *hp = NULL;\n  BinHeapEntry *bhe = NULL;\n  BinHeapEntry *bhe_top = NULL;\n  SRS_Hentry *he = NULL;\n  BlockFile *d_blockFile = NULL;\n  float knnDist = -1;\n  // boost::math::chi_squared chi(m);\n  float *d_array = NULL;\n  int limit = -1;\n\n  SRS_Hentry *inner_rslt = new SRS_Hentry[_k];\n  for (int i = 0; i < _k; i++) {\n    inner_rslt[i].d = d;\n  }\n\n  // inner_rslt is the top-k NN found through R-tree; rslt also consider the\n  // points that in the same page when reading a point from the binary file\n  for (int i = 0; i < _k; i++) {\n    _rslt[i].id = -1;\n    _rslt[i].dist = (float)MAXREAL;\n    inner_rslt[i].id = -1;\n    inner_rslt[i].dist = (float)MAXREAL;\n  }\n\n  hp = new BinHeap();\n  hp->compare_func = &SRS_hcomp;\n  hp->destroy_data = &SRS_hdestroy;\n\n  d_blockFile = new BlockFile(dName, 4 * B);\n  knnDist = (float)MAXREAL;\n\n  limit = (int)ceil(_t * n) + _k - 1;\n  if (limit > n)\n    limit = n;\n\n  qk = new float[m * _numTrees];\n\n  // d_array records all the read points, so if the r-tree returns a point that\n  // is already read, we can save a I/O\n  d_array = new float[n + 1];\n  for (int i = 0; i <= n; ++i) {\n    d_array[i] = -1.0;\n  }\n\n  for (int i = 0; i < _numTrees; ++i) {\n    he = new SRS_Hentry();\n    he->id = trees[i]->root;\n    he->gap = 0;\n    he->level = 1;\n    he->d = d;\n    he->treeId = i;\n    he->dist = -1;\n\n    bhe = new BinHeapEntry();\n    bhe->data = he;\n    hp->insert(bhe);\n\n    for (int j = 0; j < m; ++j) {\n      qk[i * m + j] = getHashValue((_start_tree_ID + i) * m + j, _q);\n#ifdef DEBUG\n      printf(\"%.6f \", qk[i * m + j]);\n#endif\n    }\n#ifdef DEBUG\n    printf(\"\\n\");\n#endif\n  }\n\n  while (again) {\n    bhe_top = hp->remove();\n    if (!bhe_top) {\n      again = false;\n    } else {\n      he = (SRS_Hentry *)bhe_top->data;\n      treeId = he->treeId;\n      son = he->id;\n\n      if (he->level == 0) {\n        cnt++;\n\n        if (d_array[son] < 0) {\n          int *pt = new int[d];\n          int ret_temp = 0;\n          // locate the page that contains point son\n          int blk_pos = ((long long)d * sizeof(int) * (son - 1)) %\n                        d_blockFile->blocklength;\n          int blk_id =\n              (long long)d * sizeof(int) * (son - 1) / d_blockFile->blocklength;\n          char *blk = new char[d_blockFile->blocklength];\n\n          d_blockFile->read_block(blk, blk_id);\n          ret++;\n\n          // read points in the page before son\n          for (int i = 1;; i++) {\n            int tmp_pos = blk_pos - d * sizeof(int) * i;\n            if (tmp_pos < 0 || son - i < 1) {\n              break;\n            }\n\n            for (int j = 0; j < d; ++j) {\n              memcpy(&pt[j], &blk[tmp_pos], sizeof(int));\n              tmp_pos += sizeof(int);\n            }\n            d_array[son - i] = l2_dist_int(pt, _q, d);\n\n#ifndef DEBUG\n            /* We comment out this block for debugging purpose. As the size of\n               each point is different in compact mode and un-compact mode, the\n               results for them under the same t is different (more data points\n               would be checked under compact mode==>compact mode would be\n               better). To make sure they will produce the same result when\n               using the same parameter, we comment out this block. */\n            SRS_Hentry *tmp_e = new SRS_Hentry();\n            tmp_e->id = son - i;\n            tmp_e->dist = d_array[son - i];\n            updateknn(_rslt, tmp_e, _k);\n            delete tmp_e;\n#endif\n          }\n\n          // read point son\n          for (int i = 0; i < d; ++i) {\n            if (blk_pos == d_blockFile->blocklength) {\n              blk_id++;\n              d_blockFile->read_block(blk, blk_id);\n              ret++;\n              blk_pos = 0;\n            }\n            memcpy(&pt[i], &blk[blk_pos], sizeof(int));\n            blk_pos += sizeof(int);\n          }\n          d_array[son] = l2_dist_int(pt, _q, d);\n\n          // read point in the page after son\n          for (int i = 1;; ++i) {\n            int tmp_pos = blk_pos + d * sizeof(int) * (i - 1);\n            if ((tmp_pos + d * sizeof(int)) > d_blockFile->blocklength ||\n                son + i > n) {\n              break;\n            }\n\n            for (int j = 0; j < d; ++j) {\n              memcpy(&pt[j], &blk[tmp_pos], sizeof(int));\n              tmp_pos += sizeof(int);\n            }\n            d_array[son + i] = l2_dist_int(pt, _q, d);\n            if (son + i > n) {\n              printf(\"%d %d\\n\", son, i);\n            }\n\n#ifndef DEBUG\n            /* We comment out this block for debugging purpose. As the size of\n               each point is different in compact mode and un-compact mode, the\n               results for them under the same t is different (more data points\n               would be checked under compact mode==>compact mode would be\n               better). To make sure they will produce the same result when\n               using the same parameter, we comment out this block. */\n            SRS_Hentry *tmp_e = new SRS_Hentry();\n            tmp_e->id = son + i;\n            tmp_e->dist = d_array[son + i];\n            updateknn(_rslt, tmp_e, _k);\n            delete tmp_e;\n#endif\n          }\n          delete[] pt;\n          delete[] blk;\n        }\n\n        he->dist = d_array[son];\n        updateknn(_rslt, he, _k);\n        knnDist = updateknn(inner_rslt, he, _k);\n\n        // early termination condition\n        //        if (early_stop && (compfloats(knnDist, 0.0) == 0 || 1 - pow(1\n        //        - boost::math::cdf(chi, _c * _c * he->gap / knnDist /\n        //        knnDist), (double) _numTrees) >= _tau)) {\n        if (early_stop &&\n            (compfloats(knnDist, 0.0) == 0 ||\n             (knnDist * knnDist) > (he->gap * chi2inv(_tau, m) / _c / _c))) {\n          again = false;\n        }\n\n      } else {\n        ret++;\n        RTNode *child = new ptRTNode();\n        child->init(trees[treeId], son);\n        for (int i = 0; i < child->num_entries; i++) {\n          he = new SRS_Hentry();\n          he->id = child->entries[i]->son;\n          he->level = child->level;\n          he->gap = MINDIST(qk, child->entries[i]->bounces, m, treeId);\n          he->treeId = treeId;\n          he->d = d;\n\n          bhe = new BinHeapEntry();\n          bhe->data = he;\n          hp->insert(bhe);\n        }\n        delete child;\n      }\n      // normal termination condition (i.e., verified T points)\n      if (cnt >= limit) {\n        again = false;\n      }\n    }\n  }\n\nrecycle:\n  if (d_blockFile) {\n    delete d_blockFile;\n  }\n\n  if (qk) {\n    delete[] qk;\n  }\n\n  if (d_array) {\n    delete[] d_array;\n  }\n\n  delete[] inner_rslt;\n\n  if (hp->root)\n    hp->root->recursive_data_wipeout(hp->destroy_data);\n  delete hp;\n\n  return ret;\n}\n", "meta": {"hexsha": "ca62e27c4f181794215893eb9e5765882f0326ee", "size": 22787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external-memory/iDEC/src/srs.cpp", "max_stars_repo_name": "Why1221/iDEC", "max_stars_repo_head_hexsha": "a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-15T14:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T17:17:57.000Z", "max_issues_repo_path": "external-memory/iDEC/src/srs.cpp", "max_issues_repo_name": "Why1221/iDEC", "max_issues_repo_head_hexsha": "a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb", "max_issues_repo_licenses": ["MIT"], "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-memory/iDEC/src/srs.cpp", "max_forks_repo_name": "Why1221/iDEC", "max_forks_repo_head_hexsha": "a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb", "max_forks_repo_licenses": ["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.2529296875, "max_line_length": 80, "alphanum_fraction": 0.496467284, "num_tokens": 6629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.19093869759126986}}
{"text": "// Copyright (c) 2009-2010 Satoshi Nakamoto\n// Copyright (c) 2009-2014 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or https://www.opensource.org/licenses/mit-license.php .\n\n#include \"miner.h\"\n#ifdef ENABLE_MINING\n#include \"pow/tromp/equi_miner.h\"\n#endif\n\n#include \"amount.h\"\n#include \"chainparams.h\"\n#include \"cc/StakeGuard.h\"\n#include \"importcoin.h\"\n#include \"consensus/consensus.h\"\n#include \"consensus/upgrades.h\"\n#include \"consensus/validation.h\"\n#ifdef ENABLE_MINING\n#include \"crypto/equihash.h\"\n#include \"crypto/verus_hash.h\"\n#endif\n#include \"hash.h\"\n#include \"key_io.h\"\n#include \"main.h\"\n#include \"metrics.h\"\n#include \"net.h\"\n#include \"pow.h\"\n#include \"primitives/transaction.h\"\n#include \"random.h\"\n#include \"timedata.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#include \"utilmoneystr.h\"\n#include \"validationinterface.h\"\n\n#include \"zcash/Address.hpp\"\n#include \"transaction_builder.h\"\n\n#include \"sodium.h\"\n\n#include <boost/thread.hpp>\n#include <boost/tuple/tuple.hpp>\n#ifdef ENABLE_MINING\n#include <functional>\n#endif\n#include <mutex>\n\n#include \"pbaas/pbaas.h\"\n#include \"pbaas/notarization.h\"\n#include \"pbaas/identity.h\"\n#include \"rpc/pbaasrpc.h\"\n#include \"transaction_builder.h\"\n\nusing namespace std;\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// BitcoinMiner\n//\n\n//\n// Unconfirmed transactions in the memory pool often depend on other\n// transactions in the memory pool. When we select transactions from the\n// pool, we select by highest priority or fee rate, so we might consider\n// transactions that depend on transactions that aren't yet in the block.\n// The COrphan class keeps track of these 'temporary orphans' while\n// CreateBlock is figuring out which transactions to include.\n//\nclass COrphan\n{\npublic:\n    const CTransaction* ptx;\n    set<uint256> setDependsOn;\n    CFeeRate feeRate;\n    double dPriority;\n    \n    COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)\n    {\n    }\n};\n\nuint64_t nLastBlockTx = 0;\nuint64_t nLastBlockSize = 0;\n\n// We want to sort transactions by priority and fee rate, so:\ntypedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;\nclass TxPriorityCompare\n{\n    bool byFee;\n    \npublic:\n    TxPriorityCompare(bool _byFee) : byFee(_byFee) { }\n    \n    bool operator()(const TxPriority& a, const TxPriority& b)\n    {\n        if (byFee)\n        {\n            if (a.get<1>() == b.get<1>())\n                return a.get<0>() < b.get<0>();\n            return a.get<1>() < b.get<1>();\n        }\n        else\n        {\n            if (a.get<0>() == b.get<0>())\n                return a.get<1>() < b.get<1>();\n            return a.get<0>() < b.get<0>();\n        }\n    }\n};\n\nvoid UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)\n{\n    pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());\n\n    // Updating time can change work required on testnet:\n    if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) {\n        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);\n    }\n}\n\n#include \"komodo_defs.h\"\n\nextern CCriticalSection cs_metrics;\nextern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;\nextern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;\nextern bool VERUS_MINTBLOCKS;\nextern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];\nextern const char *ASSETCHAINS_ALGORITHMS[];\nextern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];\nextern uint32_t ASSETCHAINS_ALGO;\nextern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];\nextern uint160 ASSETCHAINS_CHAINID;\nextern uint160 VERUS_CHAINID;\nextern std::string VERUS_CHAINNAME;\nextern int32_t PBAAS_STARTBLOCK, PBAAS_ENDBLOCK;\nextern string PBAAS_HOST, PBAAS_USERPASS, ASSETCHAINS_RPCHOST, ASSETCHAINS_RPCCREDENTIALS;;\nextern int32_t PBAAS_PORT;\nextern uint16_t ASSETCHAINS_RPCPORT;\nextern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;\nvoid vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);\n\nextern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];\nuint32_t Mining_start, Mining_height;\nint32_t My_notaryid = -1;\nint32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);\nint32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);\nint32_t komodo_baseid(char *origbase);\nint32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);\nint64_t komodo_block_unlocktime(uint32_t nHeight);\nuint64_t komodo_commission(const CBlock *block);\nint32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);\nint32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, std::vector<unsigned char> &utxosig, CTxDestination &rewardDest);\nint32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);\n\nvoid IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int &nExtraNonce, bool buildMerkle, uint32_t *pSaveBits)\n{\n    // Update nExtraNonce\n    static uint256 hashPrevBlock;\n    if (hashPrevBlock != pblock->hashPrevBlock)\n    {\n        nExtraNonce = 0;\n        hashPrevBlock = pblock->hashPrevBlock;\n    }\n    ++nExtraNonce;\n\n    if (pSaveBits)\n    {\n        *pSaveBits = pblock->nBits;\n    }\n\n    int32_t nHeight = pindexPrev->GetHeight() + 1;\n\n    int solutionVersion = CConstVerusSolutionVector::activationHeight.ActiveVersion(nHeight);\n\n    if (solutionVersion >= CConstVerusSolutionVector::activationHeight.ACTIVATE_PBAAS_HEADER)\n    {\n        // coinbase should already be finalized in the new version\n        if (buildMerkle)\n        {\n            pblock->hashMerkleRoot = pblock->BuildMerkleTree();\n            pblock->SetPrevMMRRoot(ChainMerkleMountainView(chainActive.GetMMR(), pindexPrev->GetHeight()).GetRoot());\n            BlockMMRange mmRange(pblock->BuildBlockMMRTree());\n            BlockMMView mmView(mmRange);\n            pblock->SetBlockMMRRoot(mmView.GetRoot());\n            pblock->AddUpdatePBaaSHeader();\n        }\n\n        UpdateTime(pblock, Params().GetConsensus(), pindexPrev);\n\n        // POS blocks have already had their solution space filled, and there is no actual extra nonce, extradata is used\n        // for POS proof, so don't modify it\n        if (solutionVersion >= CConstVerusSolutionVector::activationHeight.ACTIVATE_PBAAS && !pblock->IsVerusPOSBlock())\n        {\n            pblock->AddUpdatePBaaSHeader();\n\n            uint8_t dummy;\n            // clear extra data to allow adding more PBaaS headers\n            pblock->SetExtraData(&dummy, 0);\n\n            // combine blocks and set compact difficulty if necessary\n            uint32_t savebits;\n            if ((savebits = ConnectedChains.CombineBlocks(*pblock)) && pSaveBits)\n            {\n                arith_uint256 ours, merged;\n                ours.SetCompact(pblock->nBits);\n                merged.SetCompact(savebits);\n                if (merged > ours)\n                {\n                    *pSaveBits = savebits;\n                }\n            }\n\n            // extra nonce is kept in the header, not in the coinbase any longer\n            // this allows instant spend transactions to use coinbase funds for\n            // inputs by ensuring that once final, the coinbase transaction hash\n            // will not continue to change\n            CDataStream s(SER_NETWORK, PROTOCOL_VERSION);\n            s << nExtraNonce;\n            std::vector<unsigned char> vENonce(s.begin(), s.end());\n\n            assert(pblock->ExtraDataLen() >= vENonce.size());\n            pblock->SetExtraData(vENonce.data(), vENonce.size());\n        }\n    }\n    else\n    {\n        // finalize input of coinbase\n        CMutableTransaction txcb(pblock->vtx[0]);\n        txcb.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;\n        assert(txcb.vin[0].scriptSig.size() <= 100);\n        pblock->vtx[0] = txcb;\n        if (buildMerkle)\n        {\n            pblock->hashMerkleRoot = pblock->BuildMerkleTree();\n        }\n\n        UpdateTime(pblock, Params().GetConsensus(), pindexPrev);\n    }\n}\n\nextern CWallet *pwalletMain;\n\nCPubKey GetSolutionPubKey(const std::vector<std::vector<unsigned char>> &vSolutions, txnouttype txType)\n{\n    CPubKey pk;\n\n    if (txType == TX_PUBKEY)\n    {\n        pk = CPubKey(vSolutions[0]);\n    }\n    else if(txType == TX_PUBKEYHASH)\n    {\n        // we need to have this in our wallet to get the public key\n        LOCK(pwalletMain->cs_wallet);\n        pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk);\n    }\n    else if (txType == TX_CRYPTOCONDITION)\n    {\n        if (vSolutions[0].size() == 33)\n        {\n            pk = CPubKey(vSolutions[0]);\n        }\n        else if (vSolutions[0].size() == 34 && vSolutions[0][0] == COptCCParams::ADDRTYPE_PK)\n        {\n            pk = CPubKey(std::vector<unsigned char>(vSolutions[0].begin() + 1, vSolutions[0].end()));\n        }\n        else if (vSolutions[0].size() == 20)\n        {\n            LOCK(pwalletMain->cs_wallet);\n            pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk);\n        }\n        else if (vSolutions[0].size() == 21 && vSolutions[0][0] == COptCCParams::ADDRTYPE_ID)\n        {\n            // destination is an identity, see if we can get its first public key\n            std::pair<CIdentityMapKey, CIdentityMapValue> identity;\n\n            if (pwalletMain->GetIdentity(CIdentityID(uint160(std::vector<unsigned char>(vSolutions[0].begin() + 1, vSolutions[0].end()))), identity) && \n                identity.second.IsValidUnrevoked() && \n                identity.second.primaryAddresses.size())\n            {\n                CPubKey pkTmp = boost::apply_visitor<GetPubKeyForPubKey>(GetPubKeyForPubKey(), identity.second.primaryAddresses[0]);\n                if (pkTmp.IsValid())\n                {\n                    pk = pkTmp;\n                }\n                else\n                {\n                    LOCK(pwalletMain->cs_wallet);\n                    pwalletMain->GetPubKey(CKeyID(GetDestinationID(identity.second.primaryAddresses[0])), pk);\n                }\n            }\n        }\n    }\n    return pk;\n}\n\nCPubKey GetScriptPublicKey(const CScript &scriptPubKey)\n{\n    txnouttype typeRet;\n    std::vector<std::vector<unsigned char>> vSolutions;\n    if (Solver(scriptPubKey, typeRet, vSolutions))\n    {\n        return GetSolutionPubKey(vSolutions, typeRet);\n    }\n    return CPubKey();\n}\n\n// call a chain that we consider a notary chain, meaning we call its daemon, not the other way around,\n// retrieve new exports that we have not imported, and process them. Also, send any exports that are now\n// provable with the available notarization on the specified chain.\nvoid ProcessNewImports(const uint160 &sourceChainID, CPBaaSNotarization &lastConfirmed, CUTXORef &lastConfirmedUTXO, uint32_t nHeight)\n{\n    if (CConstVerusSolutionVector::GetVersionByHeight(nHeight) < CActivationHeight::ACTIVATE_PBAAS || \n        CConstVerusSolutionVector::activationHeight.IsActivationHeight(CActivationHeight::ACTIVATE_PBAAS, nHeight))\n    {\n        return;\n    }\n\n    uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());\n\n    // get any pending imports from the source chain. if the source chain is this chain, we don't need notarization\n    CCurrencyDefinition thisChain = ConnectedChains.ThisChain();\n    uint160 thisChainID = thisChain.GetID();\n    CCurrencyDefinition sourceChain = ConnectedChains.GetCachedCurrency(sourceChainID);\n    if (!sourceChain.IsValid())\n    {\n        printf(\"Unrecognized source chain %s\\n\", EncodeDestination(CIdentityID(sourceChainID)).c_str());\n        return;\n    }\n\n    // printf(\"%s: processing imports for %s\\n\", __func__, sourceChain.name.c_str());\n\n    bool isSameChain = thisChain.GetID() == sourceChainID;\n\n    CChainNotarizationData cnd;\n    if (!(GetNotarizationData(sourceChainID, cnd) && cnd.IsConfirmed()))\n    {\n        printf(\"Cannot get notarization data for currency %s\\n\", sourceChain.name.c_str());\n        return;\n    }\n\n    lastConfirmedUTXO = cnd.vtx[cnd.lastConfirmed].first;\n    lastConfirmed = cnd.vtx[cnd.lastConfirmed].second;\n\n    CTransaction lastImportTx;\n\n    // we need to find the last unspent import transaction\n    std::vector<CAddressUnspentDbEntry> unspentOutputs;\n\n    bool found = false;\n    CAddressUnspentDbEntry foundEntry;\n    CCrossChainImport lastCCI;\n    std::vector<std::pair<std::pair<CInputDescriptor, CPartialTransactionProof>, std::vector<CReserveTransfer>>> exports;\n\n    {\n        LOCK(cs_main);\n\n        if (!isSameChain &&\n            lastConfirmed.proofRoots.count(sourceChainID) &&\n            GetAddressUnspent(CKeyID(CCrossChainRPCData::GetConditionID(sourceChainID, CCrossChainImport::CurrencySystemImportKey())), CScript::P2IDX, unspentOutputs))\n        {\n            // if one spends the prior one, get the one that is not spent\n            for (auto &txidx : unspentOutputs)\n            {\n                COptCCParams p;\n                if (txidx.second.script.IsPayToCryptoCondition(p) &&\n                    p.IsValid() &&\n                    p.evalCode == EVAL_CROSSCHAIN_IMPORT &&\n                    p.vData.size() &&\n                    (lastCCI = CCrossChainImport(p.vData[0])).IsValid())\n                {\n                    found = true;\n                    foundEntry = txidx;\n                    break;\n                }\n            }\n\n            if (found && \n                lastCCI.sourceSystemHeight < lastConfirmed.notarizationHeight)\n            {\n                UniValue params(UniValue::VARR);\n\n                params.push_back(EncodeDestination(CIdentityID(thisChainID)));\n                params.push_back((int64_t)lastCCI.sourceSystemHeight);\n                params.push_back((int64_t)lastConfirmed.proofRoots[sourceChainID].rootHeight);\n\n                UniValue result = NullUniValue;\n                try\n                {\n                    if (sourceChainID == thisChain.GetID())\n                    {\n                        UniValue getexports(const UniValue& params, bool fHelp);\n                        result = getexports(params, false);\n                    }\n                    else\n                    {\n                        result = find_value(RPCCallRoot(\"getexports\", params), \"result\");\n                    }\n                } catch (exception e)\n                {\n                    printf(\"Could not get latest export from external chain %s for %s\\n\", EncodeDestination(CIdentityID(sourceChainID)).c_str(), uni_get_str(params[0]).c_str());\n                    return;\n                }\n\n                // now, we should have a list of exports to import in order\n                if (!result.isArray() || !result.size())\n                {\n                    return;\n                }\n                bool foundCurrent = false;\n                for (int i = 0; i < result.size(); i++)\n                {\n                    uint256 exportTxId = uint256S(uni_get_str(find_value(result[i], \"txid\")));\n                    if (!foundCurrent && !lastCCI.exportTxId.IsNull())\n                    {\n                        // when we find our export, take the next\n                        if (exportTxId == lastCCI.exportTxId)\n                        {\n                            foundCurrent = true;\n                        }\n                        continue;\n                    }\n\n                    // create one import at a time\n                    uint32_t notarizationHeight = uni_get_int64(find_value(result[i], \"height\"));\n                    int32_t exportTxOutNum = uni_get_int(find_value(result[i], \"txoutnum\"));\n                    CPartialTransactionProof txProof = CPartialTransactionProof(find_value(result[i], \"partialtransactionproof\"));\n                    UniValue transferArrUni = find_value(result[i], \"transfers\");\n                    if (!notarizationHeight || \n                        exportTxId.IsNull() || \n                        exportTxOutNum == -1 ||\n                        !transferArrUni.isArray())\n                    {\n                        printf(\"Invalid export from %s\\n\", uni_get_str(params[0]).c_str());\n                        return;\n                    }\n\n                    CTransaction exportTx;\n                    uint256 blkHash;\n                    auto proofRootIt = lastConfirmed.proofRoots.find(sourceChainID);\n                    if (!isSameChain &&\n                        !(txProof.IsValid() &&\n                          !txProof.GetPartialTransaction(exportTx).IsNull() &&\n                          txProof.TransactionHash() == exportTxId &&\n                          proofRootIt != lastConfirmed.proofRoots.end() &&\n                          proofRootIt->second.stateRoot == txProof.CheckPartialTransaction(exportTx) &&\n                          exportTx.vout.size() > exportTxOutNum))\n                    {\n                        /* printf(\"%s: proofRoot: %s, checkPartialRoot: %s, proofheight: %u, ischainproof: %s, blockhash: %s\\n\", \n                            __func__,\n                            proofRootIt->second.ToUniValue().write(1,2).c_str(),\n                            txProof.CheckPartialTransaction(exportTx).GetHex().c_str(),\n                            txProof.GetProofHeight(),\n                            txProof.IsChainProof() ? \"true\" : \"false\",\n                            txProof.GetBlockHash().GetHex().c_str()); */\n                        printf(\"Invalid export for %s\\n\", uni_get_str(params[0]).c_str());\n                        return;\n                    }\n                    else if (isSameChain &&\n                            !(myGetTransaction(exportTxId, exportTx, blkHash) &&\n                            exportTx.vout.size() > exportTxOutNum))\n                    {\n                        printf(\"Invalid export msg2 from %s\\n\", uni_get_str(params[0]).c_str());\n                        return;\n                    }\n                    if (!foundCurrent)\n                    {\n                        CCrossChainExport ccx(exportTx.vout[exportTxOutNum].scriptPubKey);\n                        if (!ccx.IsValid())\n                        {\n                            printf(\"Invalid export msg3 from %s\\n\", uni_get_str(params[0]).c_str());\n                            return;\n                        }\n                        if (ccx.IsChainDefinition())\n                        {\n                            continue;\n                        }\n                    }\n                    std::pair<std::pair<CInputDescriptor, CPartialTransactionProof>, std::vector<CReserveTransfer>> oneExport =\n                        std::make_pair(std::make_pair(CInputDescriptor(exportTx.vout[exportTxOutNum].scriptPubKey, \n                                                        exportTx.vout[exportTxOutNum].nValue, \n                                                        CTxIn(exportTxId, exportTxOutNum)),\n                                                        txProof),\n                                        std::vector<CReserveTransfer>());\n                    for (int j = 0; j < transferArrUni.size(); j++)\n                    {\n                        //printf(\"%s: onetransfer: %s\\n\", __func__, transferArrUni[j].write(1,2).c_str());\n                        oneExport.second.push_back(CReserveTransfer(transferArrUni[j]));\n                        if (!oneExport.second.back().IsValid())\n                        {\n                            printf(\"Invalid reserve transfers in export from %s\\n\", sourceChain.name.c_str());\n                            return;\n                        }\n                    }\n                    exports.push_back(oneExport);\n                }\n            }\n            std::map<uint160, std::vector<std::pair<int, CTransaction>>> newImports;\n            ConnectedChains.CreateLatestImports(sourceChain, lastConfirmedUTXO, exports, newImports);\n        }\n        else if (isSameChain)\n        {\n            ConnectedChains.ProcessLocalImports();\n            return;\n        }\n        else\n        {\n            LogPrint(\"crosschain\", \"Could not get prior import for currency %s\\n\", sourceChain.name.c_str());\n            return;\n        }\n    }\n}\n\nbool CheckNotaryConnection(const CRPCChainData &notarySystem)\n{\n    // ensure we have connection parameters, or we fail\n    if (notarySystem.rpcHost == \"\" || notarySystem.rpcUserPass == \"\" || !notarySystem.rpcPort)\n    {\n        return false;\n    }\n    return true;\n}\n\nbool CallNotary(const CRPCChainData &notarySystem, std::string command, const UniValue &params, UniValue &result, UniValue &error)\n{\n    // ensure we have connection parameters, or we fail\n    if (!CheckNotaryConnection(notarySystem))\n    {\n        return false;\n    }\n\n    try\n    {\n        UniValue rpcResult = RPCCall(command, params, notarySystem.rpcUserPass, notarySystem.rpcPort, notarySystem.rpcHost);\n        result = find_value(rpcResult, \"result\");\n        error = find_value(rpcResult, \"error\");\n    } catch (std::exception e)\n    {\n        error = strprintf(\"Failed to connect to %s chain, error: %s\\n\", notarySystem.chainDefinition.name.c_str(), e.what());\n    }\n    return error.isNull();\n}\n\n// get initial currency state from the notary system specified\nbool GetBlockOneLaunchNotarization(const CRPCChainData &notarySystem, \n                                   const uint160 &currencyID,\n                                   CCurrencyDefinition &curDef,\n                                   CPBaaSNotarization &launchNotarization,\n                                   CPBaaSNotarization &notaryNotarization,\n                                   std::pair<CUTXORef, CPartialTransactionProof> &notarizationOutputProof,\n                                   std::pair<CUTXORef, CPartialTransactionProof> &exportOutputProof,\n                                   std::vector<CReserveTransfer> &exportTransfers)\n{\n    UniValue result, error;\n    bool retVal = false;\n\n    UniValue params(UniValue::VARR);\n    params.push_back(EncodeDestination(CIdentityID(currencyID)));\n\n    // VRSC and VRSCTEST do not start with a notary chain\n    if (!IsVerusActive() && ConnectedChains.IsNotaryAvailable())\n    {\n        // we are starting a PBaaS chain. We only assume that our chain definition and the first notary chain, if there is one, are setup\n        // in ConnectedChains. All other currencies and identities necessary to start have not been populated and must be in block 1 by\n        // getting the information from the notary chain.\n        if (CallNotary(notarySystem, \"getlaunchinfo\", params, result, error))\n        {\n            CCurrencyDefinition currency(find_value(result, \"currencydefinition\"));\n            CPBaaSNotarization notarization(find_value(result, \"launchnotarization\"));\n            notaryNotarization = CPBaaSNotarization(find_value(result, \"notarynotarization\"));\n            CPartialTransactionProof notarizationProof(find_value(result, \"notarizationproof\"));\n            CUTXORef notarizationUtxo(uint256S(uni_get_str(find_value(result, \"notarizationtxid\"))), uni_get_int(find_value(result, \"notarizationvoutnum\")));\n\n            CPartialTransactionProof exportProof(find_value(result, \"exportproof\"));\n            UniValue exportTransfersUni = find_value(result, \"exportransfers\");\n\n            bool reject = false;\n            if (exportTransfersUni.isArray() && exportTransfersUni.size())\n            {\n                for (int i = 0; i < exportTransfersUni.size(); i++)\n                {\n                    CReserveTransfer oneTransfer(exportTransfersUni[i]);\n                    if (!oneTransfer.IsValid())\n                    {\n                        reject = true;\n                    }\n                    else\n                    {\n                        exportTransfers.push_back(oneTransfer);\n                    }\n                }\n            }\n            CUTXORef exportUtxo(uint256S(uni_get_str(find_value(result, \"exporttxid\"))), uni_get_int(find_value(result, \"exportvoutnum\")));\n\n            if (reject ||\n                !currency.IsValid() ||\n                !notarization.IsValid() ||\n                !notarizationProof.IsValid() ||\n                !notaryNotarization.IsValid())\n            {\n                LogPrintf(\"%s: invalid launch notarization for currency %s\\n\", __func__, EncodeDestination(CIdentityID(currencyID)).c_str());\n                printf(\"%s: invalid launch notarization for currency %s\\ncurrencydefinition: %s\\nnotarization: %s\\ntransactionproof: %s\\n\", \n                    __func__, \n                    EncodeDestination(CIdentityID(currencyID)).c_str(),\n                    currency.ToUniValue().write(1,2).c_str(),\n                    notarization.ToUniValue().write(1,2).c_str(),\n                    notarizationProof.ToUniValue().write(1,2).c_str());\n            }\n            else\n            {\n                //printf(\"%s: proofroot: %s\\n\", __func__, latestProofRoot.ToUniValue().write(1,2).c_str());\n                curDef = currency;\n                launchNotarization = notarization;\n                launchNotarization.proofRoots = notaryNotarization.proofRoots;\n                notaryNotarization.proofRoots[ASSETCHAINS_CHAINID] = CProofRoot::GetProofRoot(0);\n                notaryNotarization.currencyStates[ASSETCHAINS_CHAINID] = launchNotarization.currencyState;\n                notarizationOutputProof = std::make_pair(notarizationUtxo, notarizationProof);\n                exportOutputProof = std::make_pair(exportUtxo, exportProof);\n                retVal = true;\n            }\n        }\n        else\n        {\n            LogPrintf(\"%s: error calling notary chain %s\\n\", __func__, error.write(1,2).c_str());\n            printf(\"%s: error calling notary chain %s\\n\", __func__, error.write(1,2).c_str());\n        }\n    }\n    return retVal;\n}\n\nbool DecodeOneExport(const UniValue obj, CCrossChainExport &ccx,\n                     std::pair<std::pair<CInputDescriptor, CPartialTransactionProof>, std::vector<CReserveTransfer>> &oneExport)\n{\n    uint32_t exportHeight = uni_get_int64(find_value(obj, \"height\"));\n    uint256 txId = uint256S(uni_get_str(find_value(obj, \"txid\")));\n    uint32_t outNum = uni_get_int(find_value(obj, \"txoutnum\"));\n    ccx = CCrossChainExport(find_value(obj, \"exportinfo\"));\n    if (!ccx.IsValid())\n    {\n        LogPrintf(\"%s: invalid launch export from notary chain\\n\", __func__);\n        printf(\"%s: invalid launch export from notary chain\\n\", __func__);\n        return false;\n    }\n    CPartialTransactionProof partialTxProof(find_value(obj, \"partialtransactionproof\"));\n    CTransaction exportTx;\n    COptCCParams p;\n    CScript outputScript;\n    CAmount outputValue;\n\n    if (!partialTxProof.IsValid() ||\n        partialTxProof.GetPartialTransaction(exportTx).IsNull() ||\n        partialTxProof.TransactionHash() != txId ||\n        exportTx.vout.size() <= outNum ||\n        !exportTx.vout[outNum].scriptPubKey.IsPayToCryptoCondition(p) ||\n        !p.IsValid() ||\n        !p.evalCode == EVAL_CROSSCHAIN_EXPORT ||\n        (outputValue = exportTx.vout[outNum].nValue) == -1)\n    {\n        //UniValue jsonTxOut(UniValue::VOBJ);\n        //TxToUniv(exportTx, uint256(), jsonTxOut);\n        //printf(\"%s: proofTxRoot:%s\\npartialTx: %s\\n\", __func__, \n        //                                            partialTxProof.GetPartialTransaction(exportTx).GetHex().c_str(),\n        //                                            jsonTxOut.write(1,2).c_str());\n        LogPrintf(\"%s: invalid partial transaction proof from notary chain\\n\", __func__);\n        printf(\"%s: invalid partial transaction proof from notary chain\\n\", __func__);\n        return false;\n    }\n\n    UniValue transfers = find_value(obj, \"transfers\");\n    std::vector<CReserveTransfer> reserveTransfers;\n    if (transfers.isArray() && transfers.size())\n    {\n        for (int i = 0; i < transfers.size(); i++)\n        {\n            CReserveTransfer rt(transfers[i]);\n            if (rt.IsValid())\n            {\n                reserveTransfers.push_back(rt);\n            }\n        }\n    }\n\n    oneExport.first.first = CInputDescriptor(outputScript, outputValue, CTxIn(txId, outNum));\n    oneExport.first.second = partialTxProof;\n    oneExport.second = reserveTransfers;\n    return true;\n}\n\n// get initial currency state from the notary system specified\nbool GetBlockOneImports(const CRPCChainData &notarySystem, const CPBaaSNotarization &launchNotarization, std::map<uint160, std::vector<std::pair<std::pair<CInputDescriptor, CPartialTransactionProof>, std::vector<CReserveTransfer>>>> &exports)\n{\n    UniValue result, error;\n\n    UniValue params(UniValue::VARR);\n    params.push_back(EncodeDestination(CIdentityID(ASSETCHAINS_CHAINID)));\n    params.push_back((int)0);\n    if (launchNotarization.proofRoots.count(ConnectedChains.ThisChain().launchSystemID))\n    {\n        params.push_back((int64_t)launchNotarization.proofRoots.find(ConnectedChains.ThisChain().launchSystemID)->second.rootHeight);\n    }\n\n    // VRSC and VRSCTEST do not start with a notary chain\n    if (!IsVerusActive() && ConnectedChains.IsNotaryAvailable())\n    {\n        // we are starting a PBaaS chain. We only assume that our chain definition and the first notary chain, if there is one, are setup\n        // in ConnectedChains. All other currencies and identities necessary to start have not been populated and must be in block 1 by\n        // getting the information from the notary chain.\n        if (CallNotary(notarySystem, \"getexports\", params, result, error) &&\n            result.isArray() &&\n            result.size())\n        {\n            // we now have an array of exports that we should import into this system\n            // load up to the last launch export on each currency\n            for (int i = 0; i < result.size(); i++)\n            {\n                CCrossChainExport ccx;\n                std::pair<std::pair<CInputDescriptor, CPartialTransactionProof>, std::vector<CReserveTransfer>> oneExport;\n                if (DecodeOneExport(result[i], ccx, oneExport))\n                {\n                    exports[ccx.destCurrencyID].push_back(oneExport);\n                }\n                else\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n        return false;\n    }\n    return false;\n}\n\n// This is called with either the initial currency, or the gateway converter currency\n// to setup an import/export thread, transfer the initial issuance of native currency\n// into the converter, and notarize the state of each currency.\n// All outputs to do those things are added to the outputs vector.\nbool AddOneCurrencyImport(const CCurrencyDefinition &newCurrency, \n                          const CPBaaSNotarization &lastNotarization,\n                          const std::pair<CUTXORef, CPartialTransactionProof> *pLaunchProof,\n                          const std::pair<CUTXORef, CPartialTransactionProof> *pFirstExport,\n                          const std::vector<CReserveTransfer> &_exportTransfers,\n                          CCurrencyValueMap &gatewayDeposits,\n                          std::vector<CTxOut> &outputs,\n                          CCurrencyValueMap &additionalFees)\n{\n    uint160 newCurID = newCurrency.GetID();\n    CPBaaSNotarization newNotarization = lastNotarization;\n    newNotarization.prevNotarization = CUTXORef();\n    newNotarization.SetBlockOneNotarization();\n\n    // each currency will get:\n    // * one currency definition output\n    // * notarization of latest currency state\n\n    CCcontract_info CC;\n    CCcontract_info *cp;\n\n    // make a currency definition\n    cp = CCinit(&CC, EVAL_CURRENCY_DEFINITION);\n    std::vector<CTxDestination> dests({CPubKey(ParseHex(CC.CChexstr))});\n    outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CCurrencyDefinition>(EVAL_CURRENCY_DEFINITION, dests, 1, &newCurrency))));\n\n    // import / export capable currencies include the main currency, fractional currencies on any system, \n    // gateway currencies. the launch system, and non-token currencies. they also get an import / export thread\n    if (ConnectedChains.ThisChain().launchSystemID == newCurID ||\n        (newCurrency.systemID == ASSETCHAINS_CHAINID &&\n        (newCurrency.IsFractional() ||\n        newCurrency.systemID == newCurID ||\n        (newCurrency.IsGateway() && newCurrency.GetID() == newCurrency.gatewayID))))\n    {\n        uint160 firstNotaryID = ConnectedChains.FirstNotaryChain().chainDefinition.GetID();\n\n        // first, put evidence of the notarization pre-import\n        int notarizationIdx = -1;\n        if (pLaunchProof)\n        {\n            // add notarization before other outputs\n            cp = CCinit(&CC, EVAL_NOTARY_EVIDENCE);\n            dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});\n            // now, we need to put the launch notarization evidence, followed by the import outputs\n            CNotaryEvidence evidence = CNotaryEvidence(ConnectedChains.FirstNotaryChain().chainDefinition.GetID(),\n                                                       pLaunchProof->first,\n                                                       true,\n                                                       std::map<CIdentityID, CIdentitySignature>(),\n                                                       std::vector<CPartialTransactionProof>({pLaunchProof->second}),\n                                                       CNotaryEvidence::TYPE_PARTIAL_TXPROOF);\n            notarizationIdx = outputs.size();\n            outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CNotaryEvidence>(EVAL_NOTARY_EVIDENCE, dests, 1, &evidence))));\n        }\n\n        // create the import thread output\n        cp = CCinit(&CC, EVAL_CROSSCHAIN_IMPORT);\n        if (newCurrency.proofProtocol == newCurrency.PROOF_CHAINID)\n        {\n            dests = std::vector<CTxDestination>({CIdentityID(newCurID)});\n        }\n        else\n        {\n            dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});\n        }\n\n        if ((newCurrency.systemID == ASSETCHAINS_CHAINID) && firstNotaryID == newCurrency.launchSystemID)\n        {\n            uint256 transferHash;\n            std::vector<CTxOut> importOutputs;\n            CCurrencyValueMap importedCurrency, gatewayDepositsUsed, spentCurrencyOut;\n\n            CPBaaSNotarization tempLastNotarization = lastNotarization;\n            tempLastNotarization.currencyState.SetLaunchCompleteMarker(false);\n\n            std::vector<CReserveTransfer> exportTransfers(_exportTransfers);\n            if (!tempLastNotarization.NextNotarizationInfo(ConnectedChains.FirstNotaryChain().chainDefinition,\n                                                           newCurrency,\n                                                           0,\n                                                           1,\n                                                           exportTransfers,\n                                                           transferHash,\n                                                           newNotarization,\n                                                           importOutputs,\n                                                           importedCurrency,\n                                                           gatewayDepositsUsed,\n                                                           spentCurrencyOut))\n            {\n                LogPrintf(\"%s: invalid import for currency %s on system %s\\n\", __func__,\n                                                                            newCurrency.name.c_str(), \n                                                                            EncodeDestination(CIdentityID(ASSETCHAINS_CHAINID)).c_str());\n                return false;\n            }\n\n            // if fees are not converted, we will pay out original fees,\n            // less liquidity fees, which go into the currency reserves\n            bool feesConverted;\n            CCurrencyValueMap liquidityFees;\n            CCurrencyValueMap originalFees = \n                newNotarization.currencyState.CalculateConvertedFees(\n                    newNotarization.currencyState.viaConversionPrice,\n                    newNotarization.currencyState.viaConversionPrice,\n                    ASSETCHAINS_CHAINID,\n                    feesConverted,\n                    liquidityFees,\n                    additionalFees);\n            \n            if (!feesConverted)\n            {\n                additionalFees += (originalFees - liquidityFees);\n            }\n\n            newNotarization.SetBlockOneNotarization();\n\n            // display import outputs\n            CMutableTransaction debugTxOut;\n            debugTxOut.vout = outputs;\n            debugTxOut.vout.insert(debugTxOut.vout.end(), importOutputs.begin(), importOutputs.end());\n            UniValue jsonTxOut(UniValue::VOBJ);\n            TxToUniv(debugTxOut, uint256(), jsonTxOut);\n            printf(\"%s: launch outputs: %s\\nlast notarization: %s\\nnew notarization: %s\\n\", __func__, \n                                                                                            jsonTxOut.write(1,2).c_str(),\n                                                                                            lastNotarization.ToUniValue().write(1,2).c_str(),\n                                                                                            newNotarization.ToUniValue().write(1,2).c_str());\n\n            newNotarization.prevNotarization = CUTXORef();\n            newNotarization.prevHeight = 0;\n\n            // get the first export for launch from the notary chain\n            CTransaction firstExportTx;\n            if (!pFirstExport || !(pFirstExport->second.IsValid() && !pFirstExport->second.GetPartialTransaction(firstExportTx).IsNull()))\n            {\n                LogPrintf(\"%s: invalid first export for PBaaS or converter launch\\n\");\n                return false;\n            }\n\n            // get the export for this import\n            CCrossChainExport ccx(firstExportTx.vout[pFirstExport->first.n].scriptPubKey);\n            if (!ccx.IsValid())\n            {\n                LogPrintf(\"%s: invalid export output for PBaaS or converter launch\\n\");\n                return false;\n            }\n\n            // create an import based on launch conditions that covers all pre-allocations and uses the initial notarization.\n            // generate outputs, then fill in numOutputs\n            CCrossChainImport cci = CCrossChainImport(newCurrency.launchSystemID,\n                                                      newNotarization.notarizationHeight,\n                                                      newCurID,\n                                                      ccx.totalAmounts,\n                                                      CCurrencyValueMap(),\n                                                      0,\n                                                      ccx.hashReserveTransfers,\n                                                      pFirstExport->first.hash,\n                                                      pFirstExport->first.n);\n            cci.SetSameChain(newCurrency.launchSystemID == ASSETCHAINS_CHAINID);\n            cci.SetPostLaunch();\n            cci.SetInitialLaunchImport();\n\n            // anything we had before plus anything imported and minus all spent currency out should\n            // be all reserve deposits remaining under control of this currency\n\n            /* printf(\"%s: ccx.totalAmounts: %s\\ngatewayDepositsUsed: %s\\nadditionalFees: %s\\noriginalFees: %s\\n\",\n                __func__,\n                ccx.totalAmounts.ToUniValue().write(1,2).c_str(),\n                gatewayDepositsUsed.ToUniValue().write(1,2).c_str(),\n                additionalFees.ToUniValue().write(1,2).c_str(),\n                originalFees.ToUniValue().write(1,2).c_str()); */\n\n            // to determine left over reserves for deposit, consider imported and emitted as the same\n            gatewayDeposits = CCurrencyValueMap(lastNotarization.currencyState.currencies, lastNotarization.currencyState.reserveIn);\n            if (!newCurrency.IsFractional())\n            {\n                gatewayDeposits += originalFees;\n            }\n\n            gatewayDeposits.valueMap[newCurID] += gatewayDepositsUsed.valueMap[newCurID] + newNotarization.currencyState.primaryCurrencyOut;\n\n            printf(\"importedcurrency %s\\nspentcurrencyout %s\\ngatewaydeposits %s\\n\", \n                importedCurrency.ToUniValue().write(1,2).c_str(),\n                spentCurrencyOut.ToUniValue().write(1,2).c_str(),\n                gatewayDeposits.ToUniValue().write(1,2).c_str());\n\n            gatewayDeposits = (gatewayDeposits - spentCurrencyOut).CanonicalMap();\n\n            printf(\"newNotarization.currencyState %s\\nnewgatewaydeposits %s\\n\", \n                newNotarization.currencyState.ToUniValue().write(1,2).c_str(),\n                gatewayDeposits.ToUniValue().write(1,2).c_str());\n\n            // add the reserve deposit output with all deposits for this currency for the new chain\n            if (gatewayDeposits.valueMap.size())\n            {\n                CCcontract_info *depositCp;\n                CCcontract_info depositCC;\n\n                // create the import thread output\n                depositCp = CCinit(&depositCC, EVAL_RESERVE_DEPOSIT);\n                std::vector<CTxDestination> depositDests({CPubKey(ParseHex(depositCC.CChexstr))});\n                // put deposits under control of the launch system, where the imports using them will be coming from\n                CReserveDeposit rd(newCurrency.IsPBaaSChain() ? newCurrency.launchSystemID : newCurID, gatewayDeposits);\n                CAmount nativeOut = gatewayDeposits.valueMap.count(ASSETCHAINS_CHAINID) ? gatewayDeposits.valueMap[ASSETCHAINS_CHAINID] : 0;\n                outputs.push_back(CTxOut(nativeOut, MakeMofNCCScript(CConditionObj<CReserveDeposit>(EVAL_RESERVE_DEPOSIT, depositDests, 1, &rd))));\n            }\n\n            if (newCurrency.notaries.size())\n            {\n                // notaries all get an even share of 10% of the launch fee in the launch currency to use for notarizing\n                // they may also get pre-allocations\n                uint160 notaryNativeID = ConnectedChains.FirstNotaryChain().chainDefinition.GetID();\n                CAmount notaryFeeShare = ConnectedChains.FirstNotaryChain().chainDefinition.currencyRegistrationFee / 10;\n                additionalFees -= CCurrencyValueMap(std::vector<uint160>({notaryNativeID}), std::vector<int64_t>({notaryFeeShare}));\n                CAmount oneNotaryShare = notaryFeeShare / newCurrency.notaries.size();\n                CAmount notaryModExtra = notaryFeeShare % newCurrency.notaries.size();\n                for (auto &oneNotary : newCurrency.notaries)\n                {\n                    CTokenOutput to(notaryNativeID, oneNotaryShare);\n                    if (notaryModExtra)\n                    {\n                        to.reserveValues.valueMap[notaryNativeID]++;\n                        notaryModExtra--;\n                    }\n                    outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CTokenOutput>(EVAL_RESERVE_OUTPUT, \n                                                    std::vector<CTxDestination>({CIdentityID(oneNotary)}), \n                                                    1, \n                                                    &to))));\n                }\n            }\n\n            cci.numOutputs = importOutputs.size();\n\n            // now add the import itself\n            outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CCrossChainImport>(EVAL_CROSSCHAIN_IMPORT, dests, 1, &cci))));\n\n            // add notarization before other outputs\n            cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION);\n            if (newCurID == ASSETCHAINS_CHAINID &&\n                newCurrency.notarizationProtocol == newCurrency.NOTARIZATION_NOTARY_CHAINID)\n            {\n                dests = std::vector<CTxDestination>({CIdentityID(newCurID)});\n            }\n            else\n            {\n                dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});\n            }\n            outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CPBaaSNotarization>(EVAL_EARNEDNOTARIZATION, dests, 1, &newNotarization))));\n\n            // add export before other outputs\n            cp = CCinit(&CC, EVAL_NOTARY_EVIDENCE);\n            dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});\n            // now, we need to put the export evidence, followed by the import outputs\n            CNotaryEvidence evidence = CNotaryEvidence(cci.sourceSystemID,\n                                                       CUTXORef(uint256(), notarizationIdx),\n                                                       true,\n                                                       std::map<CIdentityID, CIdentitySignature>(),\n                                                       std::vector<CPartialTransactionProof>({pFirstExport->second}),\n                                                       CNotaryEvidence::TYPE_PARTIAL_TXPROOF);\n            outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CNotaryEvidence>(EVAL_NOTARY_EVIDENCE, dests, 1, &evidence))));\n\n            outputs.insert(outputs.end(), importOutputs.begin(), importOutputs.end());\n        }\n        else\n        {\n            // begin with an empty import for this currency\n            // create an import based on launch conditions that covers all pre-allocations and uses the initial notarization\n\n            // if the currency is new and owned by this chain, its registration requires the fee, paid in its launch chain currency\n            // otherwise, it is being imported from another chain and requires an import fee\n            CCurrencyValueMap registrationFees;\n            CAmount registrationAmount = 0;\n            if (newCurrency.systemID == ASSETCHAINS_CHAINID)\n            {\n                if (newCurrency.launchSystemID != ASSETCHAINS_CHAINID)\n                {\n                    registrationFees = CCurrencyValueMap(std::vector<uint160>({newCurrency.launchSystemID}),\n                                        std::vector<int64_t>({ConnectedChains.FirstNotaryChain().chainDefinition.currencyRegistrationFee}));\n                }\n                else\n                {\n                    registrationAmount = ConnectedChains.ThisChain().currencyRegistrationFee;\n                }\n            }\n            else\n            {\n                registrationAmount = 0;\n            }\n\n            CCrossChainImport cci = CCrossChainImport(ConnectedChains.ThisChain().launchSystemID,\n                                                      1,\n                                                      newCurID,\n                                                      CCurrencyValueMap());\n            cci.SetDefinitionImport(true);\n            outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CCrossChainImport>(EVAL_CROSSCHAIN_IMPORT, dests, 1, &cci))));\n\n            // add notarization before other outputs\n            cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION);\n            if (newCurID == ASSETCHAINS_CHAINID &&\n                newCurrency.notarizationProtocol == newCurrency.NOTARIZATION_NOTARY_CHAINID)\n            {\n                dests = std::vector<CTxDestination>({CIdentityID(newCurID)});\n            }\n            else\n            {\n                dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});\n            }\n            // this currency is not launching now\n            newNotarization.SetLaunchConfirmed();\n            newNotarization.SetLaunchComplete();\n            outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CPBaaSNotarization>(EVAL_EARNEDNOTARIZATION, dests, 1, &newNotarization))));\n\n            CReserveTransactionDescriptor rtxd;\n            CCoinbaseCurrencyState importState = newNotarization.currencyState;\n            importState.RevertReservesAndSupply();\n            CCurrencyValueMap importedCurrency;\n            CCurrencyValueMap gatewayDepositsIn;\n            CCurrencyValueMap spentCurrencyOut;\n            CCoinbaseCurrencyState newCurrencyState;\n            if (!rtxd.AddReserveTransferImportOutputs(ConnectedChains.FirstNotaryChain().chainDefinition,\n                                                      ConnectedChains.ThisChain(),\n                                                      newCurrency,\n                                                      importState,\n                                                      std::vector<CReserveTransfer>(),\n                                                      1,\n                                                      outputs,\n                                                      importedCurrency,\n                                                      gatewayDepositsIn,\n                                                      spentCurrencyOut,\n                                                      &newCurrencyState))\n            {\n                LogPrintf(\"Invalid starting currency import for %s\\n\", ConnectedChains.ThisChain().name.c_str());\n                printf(\"Invalid starting currency import for %s\\n\", ConnectedChains.ThisChain().name.c_str());\n                return false;\n            }\n        }\n        // export thread\n        cp = CCinit(&CC, EVAL_CROSSCHAIN_EXPORT);\n        dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});\n        CCrossChainExport ccx;\n\n        ccx = CCrossChainExport(ASSETCHAINS_CHAINID, 1, 1, newCurrency.systemID, newCurID, 0, CCurrencyValueMap(), CCurrencyValueMap(), uint256());\n        outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CCrossChainExport>(EVAL_CROSSCHAIN_EXPORT, dests, 1, &ccx))));\n    }\n    else\n    {\n        cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION);\n        if (newCurID == ASSETCHAINS_CHAINID &&\n            newCurrency.notarizationProtocol == newCurrency.NOTARIZATION_NOTARY_CHAINID)\n        {\n            dests = std::vector<CTxDestination>({CIdentityID(newCurID)});\n        }\n        else\n        {\n            dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});\n        }\n        // we notarize our notary chain here, not ourselves\n        if (newNotarization.currencyID == ASSETCHAINS_CHAINID)\n        {\n            if (!newNotarization.SetMirror())\n            {\n                LogPrintf(\"Cannot mirror our notarization from notary chain\\n\");\n                printf(\"Cannot mirror our notarization from notary chain\\n\");\n                return false;\n            }\n        }\n        newNotarization.SetBlockOneNotarization();\n        outputs.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CPBaaSNotarization>(EVAL_EARNEDNOTARIZATION, dests, 1, &newNotarization))));\n    }\n    return true;\n}\n\n// create all special PBaaS outputs for block 1\nbool MakeBlockOneCoinbaseOutputs(std::vector<CTxOut> &outputs,\n                                 CPBaaSNotarization &launchNotarization,\n                                 CCurrencyValueMap &additionalFees,\n                                 const Consensus::Params &consensusParams)\n{\n    uint160 thisChainID = ConnectedChains.ThisChain().GetID();\n    CCurrencyDefinition &thisChain = ConnectedChains.ThisChain();\n    CCoinbaseCurrencyState currencyState;\n    std::map<uint160, std::vector<std::pair<std::pair<CInputDescriptor, CPartialTransactionProof>, std::vector<CReserveTransfer>>>> blockOneExportImports;\n\n    std::pair<CUTXORef, CPartialTransactionProof> launchNotarizationProof;\n    std::pair<CUTXORef, CPartialTransactionProof> launchExportProof;\n    std::vector<CReserveTransfer> launchExportTransfers;\n    CPBaaSNotarization notaryNotarization, notaryConverterNotarization;\n\n    if (!GetBlockOneLaunchNotarization(ConnectedChains.FirstNotaryChain(), \n                                       thisChainID, \n                                       thisChain, \n                                       launchNotarization,\n                                       notaryNotarization,\n                                       launchNotarizationProof,\n                                       launchExportProof,\n                                       launchExportTransfers))\n    {\n        // cannot make block 1 unless we can get the initial currency state from the first notary system\n        LogPrintf(\"Cannot find chain on notary system\\n\");\n        printf(\"Cannot find chain on notary system\\n\");\n        return false;\n    }\n\n    // we need to have a launch decision to be able to mine any blocks, prior to launch being clear,\n    // it is not an error. we are just not ready.\n    if (!launchNotarization.IsLaunchCleared())\n    {\n        return false;\n    }\n\n    if (!launchNotarization.IsLaunchConfirmed())\n    {\n        // we must reach minimums in all currencies to launch\n        LogPrintf(\"This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\\n\");\n        printf(\"This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\\n\");\n        return false;\n    }\n\n    // get initial imports\n    if (!GetBlockOneImports(ConnectedChains.FirstNotaryChain(), launchNotarization, blockOneExportImports))\n    {\n        // we must reach minimums in all currencies to launch\n        LogPrintf(\"Cannot retrieve initial export imports from notary system\\n\");\n        printf(\"Cannot retrieve initial export imports from notary system\\n\");\n        return false;\n    }\n\n    // get all currencies/IDs that we will need to retrieve from our notary chain\n    std::set<uint160> blockOneCurrencies;\n    std::set<uint160> blockOneIDs = {ASSETCHAINS_CHAINID};\n    std::set<uint160> convertersToCreate;\n\n    CPBaaSNotarization converterNotarization;\n    std::pair<CUTXORef, CPartialTransactionProof> converterNotarizationProof;\n    std::pair<CUTXORef, CPartialTransactionProof> converterExportProof;\n    std::vector<CReserveTransfer> converterExportTransfers;\n    uint160 converterCurrencyID = thisChain.GatewayConverterID();\n    CCurrencyDefinition converterCurDef;\n\n    // if we have a converter currency, ensure that it also meets requirements for currency launch\n    if (!thisChain.gatewayConverterName.empty())\n    {\n        if (!GetBlockOneLaunchNotarization(ConnectedChains.FirstNotaryChain(), \n                                           converterCurrencyID,\n                                           converterCurDef,\n                                           converterNotarization,\n                                           notaryConverterNotarization,\n                                           converterNotarizationProof,\n                                           converterExportProof,\n                                           converterExportTransfers))\n        {\n            LogPrintf(\"Unable to get gateway converter initial state\\n\");\n            printf(\"Unable to get gateway converter initial state\\n\");\n            return false;\n        }\n\n        notaryConverterNotarization.currencyStates[converterCurrencyID] = converterNotarization.currencyState;\n\n        // both currency and primary gateway must have their pre-launch phase complete before we can make a decision\n        // about launching\n        if (!converterNotarization.IsLaunchCleared())\n        {\n            return false;\n        }\n\n        // we need to have a cleared launch to be able to launch\n        if (!converterNotarization.IsLaunchConfirmed())\n        {\n            LogPrintf(\"Primary currency met requirements for launch, but gateway currency converter did not\\n\");\n            printf(\"Primary currency met requirements for launch, but gateway currency converter did not\\n\");\n            return false;\n        }\n\n        convertersToCreate.insert(converterCurrencyID);\n\n        for (auto &oneCurrency : converterCurDef.currencies)\n        {\n            blockOneCurrencies.insert(oneCurrency);\n        }\n    }\n\n    // Now, add block 1 imports, which provide a foundation of all IDs and currencies needed to launch the\n    // new system, including ID and currency outputs for notary chain, all currencies we accept for pre-conversion,\n    // native currency of system launching the chain.\n    for (auto &oneNotary : ConnectedChains.notarySystems)\n    {\n        // first, we need to have the native notary currency itself and its notaries, if it has them\n        blockOneCurrencies.insert(oneNotary.first);\n        blockOneIDs.insert(oneNotary.second.notaryChain.chainDefinition.notaries.begin(), oneNotary.second.notaryChain.chainDefinition.notaries.end());\n    }\n\n    for (auto &oneCurrency : thisChain.currencies)\n    {\n        blockOneCurrencies.insert(oneCurrency);\n    }\n\n    for (auto &onePrealloc : thisChain.preAllocation)\n    {\n        blockOneIDs.insert(onePrealloc.first);\n    }\n\n    // get this chain's notaries\n    auto &notaryIDs = ConnectedChains.ThisChain().notaries;\n    blockOneIDs.insert(notaryIDs.begin(), notaryIDs.end());\n\n    // now retrieve IDs and currencies\n    std::map<uint160, std::pair<CCurrencyDefinition,CPBaaSNotarization>> currencyImports;\n    std::map<uint160, CIdentity> identityImports;\n    if (!ConnectedChains.GetNotaryCurrencies(ConnectedChains.FirstNotaryChain(), blockOneCurrencies, currencyImports) ||\n        !ConnectedChains.GetNotaryIDs(ConnectedChains.FirstNotaryChain(), blockOneIDs, identityImports))\n    {\n        // we must reach minimums in all currencies to launch\n        LogPrintf(\"Cannot retrieve identity and currency definitions needed to create block 1\\n\");\n        printf(\"Cannot retrieve identity and currency definitions needed to create block 1\\n\");\n        return false;\n    }\n\n    if (currencyImports.count(notaryNotarization.currencyID))\n    {\n        currencyImports[notaryNotarization.currencyID].second = notaryNotarization;\n    }\n\n    // add all imported currency and identity outputs, identity revocaton and recovery IDs must be explicitly imported if needed\n    for (auto &oneIdentity : identityImports)\n    {\n        outputs.push_back(CTxOut(0, oneIdentity.second.IdentityUpdateOutputScript(1)));\n    }\n\n    // calculate all issued currency on this chain for both the native and converter currencies,\n    // which is the only currency that can be considered a gateway deposit at launch. this can\n    // be used for native currency fee conversions\n    CCurrencyValueMap gatewayDeposits;\n    launchNotarization.proofRoots[ASSETCHAINS_CHAINID] = notaryNotarization.proofRoots[ASSETCHAINS_CHAINID];\n    bool success = AddOneCurrencyImport(thisChain, \n                                        launchNotarization,\n                                        &launchNotarizationProof,\n                                        &launchExportProof,\n                                        launchExportTransfers,\n                                        gatewayDeposits,\n                                        outputs,\n                                        additionalFees);\n\n    // now, the converter\n    if (success && converterCurDef.IsValid())\n    {\n        // TODO: add a new ID for the converter currency, controlled by the same primary addresses as the\n        // ID for this chain\n        CCurrencyValueMap converterDeposits;\n        converterNotarization.proofRoots[ASSETCHAINS_CHAINID] = notaryConverterNotarization.proofRoots[ASSETCHAINS_CHAINID];\n        success = AddOneCurrencyImport(converterCurDef, \n                                       converterNotarization,\n                                       &converterNotarizationProof,\n                                       &converterExportProof,\n                                       converterExportTransfers,\n                                       converterDeposits,\n                                       outputs,\n                                       additionalFees);\n    }\n\n    if (success)\n    {\n        currencyImports.erase(ASSETCHAINS_CHAINID);\n        currencyImports.erase(converterCurrencyID);\n        // now, add the rest of necessary currencies\n        for (auto &oneCurrency : currencyImports)\n        {\n            success = AddOneCurrencyImport(oneCurrency.second.first, \n                                           oneCurrency.second.second,\n                                           nullptr,\n                                           nullptr,\n                                           std::vector<CReserveTransfer>(),\n                                           gatewayDeposits,\n                                           outputs,\n                                           additionalFees);\n            if (!success)\n            {\n                break;\n            }\n        }\n    }\n    return success;\n}\n\nCBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const std::vector<CTxOut> &minerOutputs, bool isStake)\n{\n    // instead of one scriptPubKeyIn, we take a vector of them along with relative weight. each is assigned a percentage of the block subsidy and\n    // mining reward based on its weight relative to the total\n    if (!(minerOutputs.size() && ConnectedChains.SetLatestMiningOutputs(minerOutputs) || isStake))\n    {\n        fprintf(stderr,\"%s: Must have valid miner outputs, including script with valid PK, PKH, or Verus ID destination.\\n\", __func__);\n        return NULL;\n    }\n\n    CTxDestination firstDestination;\n\n    if (minerOutputs.size())\n    {\n        int64_t shareCheck = 0;\n        CTxDestination checkDest;\n        for (auto &output : minerOutputs)\n        {\n            shareCheck += output.nValue;\n            if (shareCheck < 0 || \n                shareCheck > INT_MAX || \n                !ExtractDestination(output.scriptPubKey, checkDest) || \n                (checkDest.which() == COptCCParams::ADDRTYPE_INVALID))\n            {\n                fprintf(stderr,\"Invalid miner outputs share specifications\\n\");\n                return NULL;\n            }\n        }\n        ExtractDestination(minerOutputs[0].scriptPubKey, firstDestination);\n    }\n\n    uint32_t blocktime;\n    //fprintf(stderr,\"create new block\\n\");\n    // Create new block\n    std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());\n    if(!pblocktemplate.get())\n    {\n        fprintf(stderr,\"pblocktemplate.get() failure\\n\");\n        return NULL;\n    }\n    CBlock *pblock = &pblocktemplate->block; // pointer for convenience\n\n    pblock->nSolution.resize(Eh200_9.SolutionWidth);\n\n    pblock->SetVersionByHeight(chainActive.LastTip()->GetHeight() + 1);\n\n    // -regtest only: allow overriding block.nVersion with\n    // -blockversion=N to test forking scenarios\n    if (chainparams.MineBlocksOnDemand())\n        pblock->nVersion = GetArg(\"-blockversion\", pblock->nVersion);\n    \n    // Add dummy coinbase tx placeholder as first transaction\n    pblock->vtx.push_back(CTransaction());\n\n    pblocktemplate->vTxFees.push_back(-1); // updated at end\n    pblocktemplate->vTxSigOps.push_back(-1); // updated at end\n    \n    // Largest block you're willing to create:\n    unsigned int nBlockMaxSize = GetArg(\"-blockmaxsize\", DEFAULT_BLOCK_MAX_SIZE);\n\n    // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:\n    nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));\n\n    unsigned int nMaxIDSize = nBlockMaxSize / 2;\n    unsigned int nCurrentIDSize = 0;\n    \n    // How much of the block should be dedicated to high-priority transactions,\n    // included regardless of the fees they pay\n    unsigned int nBlockPrioritySize = GetArg(\"-blockprioritysize\", DEFAULT_BLOCK_PRIORITY_SIZE);\n    nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);\n    \n    // Minimum block size you want to create; block will be filled with free transactions\n    // until there are no more or the block reaches this size:\n    unsigned int nBlockMinSize = GetArg(\"-blockminsize\", DEFAULT_BLOCK_MIN_SIZE);\n    nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);\n    \n    // Collect memory pool transactions into the block\n    CAmount nFees = 0;\n    CAmount takenFees = 0;\n\n    bool isVerusActive = IsVerusActive();\n    CCurrencyDefinition &thisChain = ConnectedChains.ThisChain();\n\n    std::vector<CAmount> exchangeRate(thisChain.currencies.size());\n\n    // we will attempt to spend any cheats we see\n    CTransaction cheatTx;\n    boost::optional<CTransaction> cheatSpend;\n    uint256 cbHash;\n\n    CBlockIndex* pindexPrev = 0;\n    bool loop = true;\n    while (loop)\n    {\n        loop = false;\n        int nHeight;\n        const Consensus::Params &consensusParams = chainparams.GetConsensus();\n        uint32_t consensusBranchId;\n        int64_t nMedianTimePast = 0;\n        uint32_t proposedTime = 0;\n\n        {\n            while (proposedTime == nMedianTimePast)\n            {\n                if (proposedTime)\n                {\n                    MilliSleep(20);\n                }\n                LOCK(cs_main);\n                pindexPrev = chainActive.LastTip();\n                nHeight = pindexPrev->GetHeight() + 1;\n                consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams);\n                nMedianTimePast = pindexPrev->GetMedianTimePast();\n                proposedTime = GetAdjustedTime();\n\n                if (proposedTime == nMedianTimePast)\n                {\n                    boost::this_thread::interruption_point();\n                }\n            }\n        }\n\n        CCoinbaseCurrencyState currencyState;\n        CCoinsViewCache view(pcoinsTip);\n        uint32_t expired; uint64_t commission;\n        \n        SaplingMerkleTree sapling_tree;\n\n        {\n            LOCK2(cs_main, mempool.cs);\n            if (pindexPrev != chainActive.LastTip())\n            {\n                // try again\n                loop = true;\n                continue;\n            }\n            pblock->nTime = GetAdjustedTime();\n\n            currencyState = ConnectedChains.GetCurrencyState(nHeight);\n\n            if (!(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree)))\n            {\n                LogPrintf(\"%s: failed to get Sapling anchor\\n\", __func__);\n                assert(false);\n            }\n        }\n\n        // Priority order to process transactions\n        list<COrphan> vOrphan; // list memory doesn't move\n        map<uint256, vector<COrphan*> > mapDependers;\n        bool fPrintPriority = GetBoolArg(\"-printpriority\", false);\n        \n        // This vector will be sorted into a priority queue:\n        vector<TxPriority> vecPriority;\n        vecPriority.reserve(mempool.mapTx.size() + 1);\n\n        {\n            LOCK(cs_main);\n\n            // check if we should add cheat transaction\n            CBlockIndex *ppast;\n            CTransaction cb;\n            int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY;\n            if (defaultSaplingDest &&\n                chainActive.Height() > 100 && \n                (ppast = chainActive[cheatHeight]) && \n                ppast->IsVerusPOSBlock() && \n                cheatList.IsHeightOrGreaterInList(cheatHeight))\n            {\n                // get the block and see if there is a cheat candidate for the stake tx\n                CBlock b;\n                if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, chainparams.GetConsensus(), 1))\n                {\n                    CTransaction &stakeTx = b.vtx[b.vtx.size() - 1];\n\n                    if (cheatList.IsCheatInList(stakeTx, &cheatTx))\n                    {\n                        // make and sign the cheat transaction to spend the coinbase to our address\n                        CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);\n\n                        uint32_t voutNum;\n                        // get the first vout with value\n                        for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++)\n                        {\n                            if (b.vtx[0].vout[voutNum].nValue > 0)\n                                break;\n                        }\n\n                        // send to the same pub key as the destination of this block reward\n                        if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx))\n                        {\n                            LOCK(pwalletMain->cs_wallet);\n                            TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight);\n                            cb = b.vtx[0];\n                            cbHash = cb.GetHash();\n\n                            bool hasInput = false;\n                            for (uint32_t i = 0; i < cb.vout.size(); i++)\n                            {\n                                // add the spends with the cheat\n                                if (cb.vout[i].nValue > 0)\n                                {\n                                    tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue);\n                                    hasInput = true;\n                                }\n                            }\n\n                            if (hasInput)\n                            {\n                                // this is a send from a t-address to a sapling address, which we don't have an ovk for.\n                                // Instead, generate a common one from the HD seed. This ensures the data is\n                                // recoverable, at least for us, while keeping it logically separate from the ZIP 32\n                                // Sapling key hierarchy, which the user might not be using.\n                                uint256 ovk;\n                                HDSeed seed;\n                                if (pwalletMain->GetHDSeed(seed)) {\n                                    ovk = ovkForShieldingFromTaddr(seed);\n\n                                    // send everything to Sapling address\n                                    tb.SendChangeTo(defaultSaplingDest.value(), ovk);\n\n                                    tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey);\n\n                                    TransactionBuilderResult buildResult(tb.Build());\n                                    if (!buildResult.IsError() && buildResult.IsTx())\n                                    {\n                                        cheatSpend = buildResult.GetTxOrThrow();\n                                    }\n                                    else\n                                    {\n                                        LogPrintf(\"Error building cheat catcher transaction: %s\\n\", buildResult.GetError().c_str());\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            if (cheatSpend)\n            {\n                LOCK(mempool.cs);\n\n                cheatTx = cheatSpend.value();\n                std::list<CTransaction> removed;\n                mempool.removeConflicts(cheatTx, removed);\n                printf(\"Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\\n%s\\n\",\n                    (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str());\n\n                // add to mem pool and relay\n                if (myAddtomempool(cheatTx))\n                {\n                    RelayTransaction(cheatTx);\n                }\n            }\n        }\n\n        //\n        // Now start solving the block\n        //\n\n        uint64_t nBlockSize = 1000;             // initial size\n        uint64_t nBlockTx = 1;                  // number of transactions - always have a coinbase\n        uint32_t autoTxSize = 0;                // extra transaction overhead that we will add while creating the block\n        int nBlockSigOps = 100;\n\n        // VerusPoP staking transaction data\n        CMutableTransaction txStaked;           // if this is a stake operation, the staking transaction that goes at the end\n        uint32_t nStakeTxSize = 0;              // serialized size of the stake transaction\n\n        // if this is not for mining, first determine if we have a right to make a block\n        if (isStake)\n        {\n            uint64_t txfees, utxovalue;\n            uint32_t txtime;\n            uint256 utxotxid;\n            int32_t i, siglen, numsigs, utxovout;\n            std::vector<unsigned char> utxosig;\n\n            txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight);\n\n            if (ASSETCHAINS_LWMAPOS != 0)\n            {\n                uint32_t nBitsPOS;\n                arith_uint256 posHash;\n\n                siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, firstDestination);\n                blocktime = GetAdjustedTime();\n            }\n\n            if (siglen <= 0)\n            {\n                return NULL;\n            }\n\n            pblock->nTime = blocktime;\n            nStakeTxSize = GetSerializeSize(txStaked, SER_NETWORK, PROTOCOL_VERSION);\n            nBlockSize += nStakeTxSize;\n        }\n\n        ConnectedChains.AggregateChainTransfers(firstDestination, nHeight);\n\n        // Now the coinbase -\n        // A PBaaS coinbase must have some additional outputs to enable certain chain state and functions to be properly\n        // validated. All but currency state and the first chain definition are either optional or not valid on non-fractional reserve PBaaS blockchains\n        // All of these are instant spend outputs that have no maturity wait time and may be spent in the same block.\n        //\n        // 1. (required) currency state - current state of currency supply and optionally reserve, premine, etc. This is primarily a data output to provide\n        //    cross check for coin minting and burning operations, making it efficient to determine up-to-date supply, reserves, and conversions. To provide\n        //    an extra level of supply cross-checking and fast data retrieval, this is part of all PBaaS chains' protocol, not just reserves.\n        //    This output also includes reserve and native amounts for total conversions, less fees, of any conversions between Verus reserve and the\n        //    native currency.\n        //\n        // 2. (block 1 required) chain definition - in order to confirm the amount of coins converted and issued within the possible range, before chain start,\n        //    new PBaaS chains have a zero-amount, unspendable chain definition output.\n        //\n        // 3. (block 1 optional) initial import utxo - for any chain with conversion or pre-conversion, the first coinbase must include an initial import utxo. \n        //    Pre-conversions are handled on the launch chain before the PBaaS chain starts, so they are an additional output, which begins\n        //    as a fixed amount and is spent with as many outputs as necessary to the recipients of the pre-conversion transactions when those pre-conversions\n        //    are imported. All pre-converted outputs get their source currency from a thread that starts with this output in block 1.\n        //\n        // 4. (block 1 optional) initial export utxo - reserve chains, or any chain that will use exports to another chain must have an initial export utxo, any chain\n        //    may have one, but currently, they can only be spent with valid exports, which only occur on reserve chains\n        //\n        // 5. (optional) notarization output - in order to ensure that notarization can occur independent of the availability of fungible\n        //    coins on the network, and also that the notarization can provide a spendable finalization output and possible reward\n        //\n        // In addition, each PBaaS block can be mined with optional, fee-generating transactions. Inporting transactions from the reserve chain or sending\n        // exported transactions to the reserve chain are optional fee-generating steps that would be easy to do when running multiple daemons.\n        // The types of transactions miners/stakers may facilitate or create for fees are as follows:\n        //\n        // 1. Earned notarization of Verus chain - spends the notarization instant out. must be present and spend the notarization output if there is a notarization output\n        //\n        // 2. Imported transactions from the export thread for this PBaaS chain on the Verus blockchain - imported transactions must spend the import utxo\n        //    thread, represent the export from the alternate chain which spends the export output from the prior import transaction, carry a notary proof, and\n        //    include outputs that map to each of its inputs on the source chain. Outputs can include unconverted reserve outputs only on fractional\n        //    reserve chains, pre-converted outputs for any chain with launch conversion, and post launch outputs to be converted on fractional reserve\n        //    chains. Each are handled in the following way:\n        //      a. Unconverted outputs are left as outputs to the intended destination of Verus reserve token and do not pass through the coinbase\n        //      b. Pre-converted outputs require that the import transaction spend the last pre-conversion output starting at block 1 as the source for\n        //         pre-converted currency.\n        //\n        // 3. Zero or more aggregated exports that combine individual cross-chain transactions and reserve transfer outputs for export to the Verus chain. \n        //\n        // 4. Conversion distribution transactions for all native and reserve currency conversions, including reserve transfer outputs without conversion as\n        //    a second step for reserve transfers that have conversion included. Any remaining pre-converted reserve must always remain in a change output\n        //    until it is exhausted\n        CTxOut premineOut;\n\n        // size of conversion tx\n        std::vector<CInputDescriptor> conversionInputs;\n\n        // if we are a PBaaS chain, first make sure we don't start prematurely, and if\n        // we should make an earned notarization, make it and set index to non-zero value\n        int32_t notarizationTxIndex = 0;                            // index of notarization if it is added\n        int32_t conversionTxIndex = 0;                              // index of conversion transaction if it is added\n\n        // export transactions can be created here by aggregating all pending transfer requests and either getting 10 or more together, or\n        // waiting n (10) blocks since the last one. each export must spend the output of the one before it\n        std::vector<CMutableTransaction> exportTransactions;\n\n        // all transaction outputs requesting conversion to another currency (PBaaS fractional reserve only)\n        // these will be used to calculate conversion price, fees, and generate coinbase conversion output as well as the\n        // conversion output transaction\n        std::vector<CTxOut> reserveConversionTo;\n        std::vector<CTxOut> reserveConversionFrom;\n\n        int64_t pbaasTransparentIn = 0;\n        int64_t pbaasTransparentOut = 0;\n        //extern int64_t ASSETCHAINS_SUPPLY;\n        //printf(\"%lu premine\\n\", ASSETCHAINS_SUPPLY);\n        int64_t blockSubsidy = GetBlockSubsidy(nHeight, consensusParams);\n\n        uint160 thisChainID = ConnectedChains.ThisChain().GetID();\n\n        uint256 mmrRoot;\n        vector<CInputDescriptor> notarizationInputs;\n\n        // used as scratch for making CCs, should be reinitialized each time\n        CCcontract_info CC;\n        CCcontract_info *cp;\n        std::vector<CTxDestination> dests;\n        CPubKey pkCC;\n\n        // Create coinbase tx and set up the null input with height\n        CMutableTransaction coinbaseTx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);\n        coinbaseTx.vin.push_back(CTxIn(uint256(), (uint32_t)-1, CScript() << nHeight << OP_0));\n\n        // we will update amounts and fees later, but convert the guarded output now for validity checking and size estimate\n        if (isStake)\n        {\n            // if there is a specific destination, use it\n            CTransaction stakeTx(txStaked);\n            CStakeParams p;\n            if (ValidateStakeTransaction(stakeTx, p, false))\n            {\n                if (p.Version() < p.VERSION_EXTENDED_STAKE && !p.pk.IsValid())\n                {\n                    LogPrintf(\"CreateNewBlock: invalid public key\\n\");\n                    fprintf(stderr,\"CreateNewBlock: invalid public key\\n\");\n                    return NULL;\n                }\n                CTxDestination guardedOutputDest = (p.Version() < p.VERSION_EXTENDED_STAKE) ? p.pk : p.delegate;\n                coinbaseTx.vout.push_back(CTxOut(1, CScript()));\n                if (!MakeGuardedOutput(1, guardedOutputDest, stakeTx, coinbaseTx.vout.back()))\n                {\n                    LogPrintf(\"CreateNewBlock: failed to make GuardedOutput on staking coinbase\\n\");\n                    fprintf(stderr,\"CreateNewBlock: failed to make GuardedOutput on staking coinbase\\n\");\n                    return NULL;\n                }\n                COptCCParams optP;\n                if (!coinbaseTx.vout.back().scriptPubKey.IsPayToCryptoCondition(optP) || !optP.IsValid())\n                {\n                    MakeGuardedOutput(1, guardedOutputDest, stakeTx, coinbaseTx.vout.back());\n                    LogPrintf(\"%s: created invalid staking coinbase\\n\", __func__);\n                    fprintf(stderr,\"%s: created invalid staking coinbase\\n\", __func__);\n                    return NULL;\n                }\n            }\n            else\n            {\n                LogPrintf(\"CreateNewBlock: invalid stake transaction\\n\");\n                fprintf(stderr,\"CreateNewBlock: invalid stake transaction\\n\");\n                return NULL;\n            }\n        }\n        else\n        {\n            // default outputs for mining and before stake guard or fee calculation\n            // store the relative weight in the amount output to convert later to a relative portion\n            // of the reward + fees\n            coinbaseTx.vout.insert(coinbaseTx.vout.end(), minerOutputs.begin(), minerOutputs.end());\n        }\n\n        CAmount totalEmission = blockSubsidy;\n        CCurrencyValueMap additionalFees;\n\n        // if we don't have a connected root PBaaS chain, we can't properly check\n        // and notarize the start block, so we have to pass the notarization and cross chain steps\n        bool notaryConnected = ConnectedChains.IsNotaryAvailable();\n        uint32_t solutionVersion = CConstVerusSolutionVector::GetVersionByHeight(nHeight);\n\n        if (isVerusActive &&\n            solutionVersion >= CActivationHeight::ACTIVATE_PBAAS &&\n            !notaryConnected)\n        {\n            // until we have connected to the ETH bridge, after PBaaS has launched, we check each block to see if there is now an\n            // ETH bridge defined\n            if (ConnectedChains.FirstNotaryChain().IsValid())\n            {\n                // once PBaaS is active, we attempt to connect to the Ethereum bridge, in case it is active\n                notaryConnected = ConnectedChains.IsNotaryAvailable(true);\n            }\n            else\n            {\n                notaryConnected = ConnectedChains.ConfigureEthBridge();\n            }\n        }\n\n        // at block 1 for a PBaaS chain, we validate launch conditions\n        if (!isVerusActive && nHeight == 1)\n        {\n            CPBaaSNotarization launchNotarization;\n            if (!ConnectedChains.readyToStart &&\n                !ConnectedChains.CheckVerusPBaaSAvailable() &&\n                !ConnectedChains.readyToStart)\n            {\n                return NULL;\n            }\n            if (!MakeBlockOneCoinbaseOutputs(coinbaseTx.vout, launchNotarization, additionalFees, Params().GetConsensus()))\n            {\n                // can't mine block 1 if we are not connected to a notary\n                printf(\"%s: cannot create block one coinbase outputs\\n\", __func__);\n                LogPrintf(\"%s: cannot create block one coinbase outputs\\n\", __func__);\n                return NULL;\n            }\n            currencyState = launchNotarization.currencyState;\n        }\n\n        // if we are a notary, notarize\n        if (nHeight > CPBaaSNotarization::MIN_BLOCKS_BEFORE_NOTARY_FINALIZED && !VERUS_NOTARYID.IsNull())\n        {\n            CValidationState state;\n            TransactionBuilder notarizationBuilder = TransactionBuilder(consensusParams, nHeight, pwalletMain);\n            bool finalized;\n            CTransaction notarizationTx;\n            const CRPCChainData &notaryChain = ConnectedChains.FirstNotaryChain();\n            if (notaryChain.IsValid() &&\n                CPBaaSNotarization::ConfirmOrRejectNotarizations(pwalletMain, ConnectedChains.FirstNotaryChain(), state, notarizationBuilder, finalized))\n            {\n                if (!notarizationBuilder.mtx.vin.size())\n                {\n                    bool success = false;\n                    CCurrencyValueMap reserveValueOut;\n                    CAmount nativeValueOut;\n                    // get a native currency input capable of paying a fee, and make our notary ID the change address\n                    std::set<std::pair<const CWalletTx *, unsigned int>> setCoinsRet;\n                    {\n                        LOCK2(cs_main, pwalletMain->cs_wallet);\n                        std::vector<COutput> vCoins;\n                        if (IsVerusActive())\n                        {\n                            pwalletMain->AvailableCoins(vCoins,\n                                                        false,\n                                                        nullptr,\n                                                        false,\n                                                        true,\n                                                        true,\n                                                        false,\n                                                        false);\n                            success = pwalletMain->SelectCoinsMinConf(CPBaaSNotarization::DEFAULT_NOTARIZATION_FEE, 0, 0, vCoins, setCoinsRet, nativeValueOut);\n                            notarizationBuilder.SetFee(CPBaaSNotarization::DEFAULT_NOTARIZATION_FEE);\n                        }\n                        else\n                        {\n                            CCurrencyValueMap totalTxFees;\n                            totalTxFees.valueMap[ConnectedChains.FirstNotaryChain().chainDefinition.GetID()] = CPBaaSNotarization::DEFAULT_NOTARIZATION_FEE;\n                            notarizationBuilder.SetReserveFee(totalTxFees);\n                            notarizationBuilder.SetFee(0);\n                            pwalletMain->AvailableReserveCoins(vCoins,\n                                                               false,\n                                                               nullptr,\n                                                               true,\n                                                               true,\n                                                               nullptr,\n                                                               &totalTxFees, \n                                                               false);\n\n                            success = pwalletMain->SelectReserveCoinsMinConf(totalTxFees,\n                                                                            0,\n                                                                            0,\n                                                                            1,\n                                                                            vCoins,\n                                                                            setCoinsRet,\n                                                                            reserveValueOut,\n                                                                            nativeValueOut);\n                        }\n                    }\n                    for (auto &oneInput : setCoinsRet)\n                    {\n                        notarizationBuilder.AddTransparentInput(COutPoint(oneInput.first->GetHash(), oneInput.second), \n                                                                oneInput.first->vout[oneInput.second].scriptPubKey,\n                                                                oneInput.first->vout[oneInput.second].nValue);\n                    }\n                    notarizationBuilder.SendChangeTo(CTxDestination(VERUS_NOTARYID));\n                }\n                else\n                {\n                    notarizationBuilder.SetFee(0);\n                }\n\n                if (notarizationBuilder.mtx.vin.size())\n                {\n                    LOCK2(cs_main, mempool.cs);\n                    TransactionBuilderResult buildResult = notarizationBuilder.Build();\n                    if (buildResult.IsTx())\n                    {\n                        notarizationTx = buildResult.GetTxOrThrow();\n\n                        UniValue jsonNotaryConfirmations(UniValue::VOBJ);\n                        TxToUniv(notarizationTx, uint256(), jsonNotaryConfirmations);\n                        //printf(\"%s: (PII) Submitting notarization confirmations:\\n%s\\n\", __func__, jsonNotaryConfirmations.write(1,2).c_str());\n                        LogPrintf(\"%s: (PII) Submitting notarization confirmations:\\n%s\\n\", __func__, jsonNotaryConfirmations.write(1,2).c_str());\n\n                        // add to mem pool and relay\n                        if (myAddtomempool(notarizationTx))\n                        {\n                            RelayTransaction(notarizationTx);\n                        }\n                    }\n                    else\n                    {\n                        printf(\"%s: (PII) error adding notary evidence: %s\\n\", __func__, buildResult.GetError().c_str());\n                        LogPrintf(\"%s: (PII) error adding notary evidence: %s\\n\", __func__, buildResult.GetError().c_str());\n                    }\n                }\n            }\n        }\n\n        if (notaryConnected)\n        {\n            // if we should make an earned notarization, do so\n            if (nHeight != 1 && !(VERUS_NOTARYID.IsNull() && VERUS_DEFAULTID.IsNull() && VERUS_NODEID.IsNull()))\n            {\n                CIdentityID proposer = VERUS_NOTARYID.IsNull() ? (VERUS_DEFAULTID.IsNull() ? VERUS_NODEID : VERUS_DEFAULTID) : VERUS_NOTARYID;\n\n                // if we have access to our notary daemon\n                // create a notarization if we would qualify to do so. add it to the mempool and next block\n                ChainMerkleMountainView mmv = chainActive.GetMMV();\n                mmrRoot = mmv.GetRoot();\n                int32_t confirmedInput = -1;\n                CTxDestination confirmedDest;\n                CValidationState state;\n                CPBaaSNotarization earnedNotarization;\n\n                if (CPBaaSNotarization::CreateEarnedNotarization(ConnectedChains.FirstNotaryChain(),\n                                                                 DestinationToTransferDestination(proposer),\n                                                                 state,\n                                                                 coinbaseTx.vout,\n                                                                 earnedNotarization))\n                {\n                }\n                CPBaaSNotarization lastImportNotarization;\n                CUTXORef lastImportNotarizationUTXO;\n\n                CPBaaSNotarization::SubmitFinalizedNotarizations(ConnectedChains.FirstNotaryChain(), state);\n                ProcessNewImports(ConnectedChains.FirstNotaryChain().chainDefinition.GetID(), lastImportNotarization, lastImportNotarizationUTXO, nHeight);\n            }\n        }\n\n        // done calling out, take locks for the rest\n        LOCK2(cs_main, mempool.cs);\n\n        totalEmission = GetBlockSubsidy(nHeight, consensusParams);\n        blockSubsidy = totalEmission;\n\n        // PBaaS chain's block 1 currency state is done by the time we get here,\n        // including pre-allocations, etc.\n        if (isVerusActive || nHeight != 1)\n        {\n            currencyState.UpdateWithEmission(totalEmission);\n        }\n\n        // process any imports from the current chain to itself\n        ConnectedChains.ProcessLocalImports();\n\n        CFeePool feePool;\n        if (!CFeePool::GetCoinbaseFeePool(feePool, nHeight - 1) ||\n            (!feePool.IsValid() && CConstVerusSolutionVector::GetVersionByHeight(nHeight - 1) >= CActivationHeight::ACTIVATE_PBAAS))\n        {\n            // we should be able to get a valid currency state, if not, fail\n            LogPrintf(\"Failure to get fee pool information for blockchain height #%d\\n\", nHeight - 1);\n            printf(\"Failure to get fee pool information for blockchain height #%d\\n\", nHeight - 1);\n            return NULL;\n        }\n\n        if (solutionVersion >= CActivationHeight::ACTIVATE_PBAAS && !feePool.IsValid())\n        {\n            // first block with a fee pool, so make it valid and empty\n            feePool = CFeePool();\n        }\n\n        // coinbase should have all necessary outputs\n        uint32_t nCoinbaseSize = GetSerializeSize(coinbaseTx, SER_NETWORK, PROTOCOL_VERSION);\n        nBlockSize += nCoinbaseSize;\n\n        // now create the priority array, including market order reserve transactions, since they can always execute, leave limits for later\n        bool haveReserveTransactions = false;\n        uint32_t reserveExchangeLimitSize = 0;\n        std::vector<CReserveTransactionDescriptor> limitOrders;\n\n        // now add transactions from the mem pool to the priority heap\n        for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();\n             mi != mempool.mapTx.end(); ++mi)\n        {\n            const CTransaction& tx = mi->GetTx();\n            uint256 hash = tx.GetHash();\n            \n            int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)\n            ? nMedianTimePast\n            : pblock->GetBlockTime();\n\n            if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))\n            {\n                //fprintf(stderr,\"coinbase.%d finaltx.%d expired.%d\\n\",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));\n                continue;\n            }\n\n            if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )\n            {\n                //fprintf(stderr,\"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\\n\",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);\n                continue;\n            }\n\n            COrphan* porphan = NULL;\n            double dPriority = 0;\n            CAmount nTotalIn = 0;\n            CCurrencyValueMap totalReserveIn;\n            bool fMissingInputs = false;\n            CReserveTransactionDescriptor rtxd;\n            bool isReserve = mempool.IsKnownReserveTransaction(hash, rtxd);\n\n            if (tx.IsCoinImport())\n            {\n                CAmount nValueIn = GetCoinImportValue(tx);\n                nTotalIn += nValueIn;\n                dPriority += (double)nValueIn * 1000;  // flat multiplier\n            } else {\n                if (isReserve)\n                {\n                    nTotalIn += rtxd.nativeIn;\n                    totalReserveIn = rtxd.ReserveInputMap();\n                    assert(!totalReserveIn.valueMap.count(ASSETCHAINS_CHAINID));\n                    if (rtxd.IsIdentity() && CNameReservation(tx).IsValid())\n                    {\n                        nCurrentIDSize += GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n                        if (nCurrentIDSize > nMaxIDSize)\n                        {\n                            continue;\n                        }\n                    }\n                }\n                BOOST_FOREACH(const CTxIn& txin, tx.vin)\n                {\n                    CAmount nValueIn = 0;\n                    CCurrencyValueMap reserveValueIn;\n\n                    // Read prev transaction\n                    if (!view.HaveCoins(txin.prevout.hash))\n                    {\n                        // This should never happen; all transactions in the memory\n                        // pool should connect to either transactions in the chain\n                        // or other transactions in the memory pool.\n                        if (!mempool.mapTx.count(txin.prevout.hash))\n                        {\n                            LogPrintf(\"ERROR: mempool transaction missing input\\n\");\n                            if (fDebug) assert(\"mempool transaction missing input\" == 0);\n                            fMissingInputs = true;\n                            if (porphan)\n                                vOrphan.pop_back();\n                            break;\n                        }\n\n                        // Has to wait for dependencies\n                        if (!porphan)\n                        {\n                            // Use list for automatic deletion\n                            vOrphan.push_back(COrphan(&tx));\n                            porphan = &vOrphan.back();\n                        }\n                        mapDependers[txin.prevout.hash].push_back(porphan);\n                        porphan->setDependsOn.insert(txin.prevout.hash);\n\n                        const CTransaction &otx = mempool.mapTx.find(txin.prevout.hash)->GetTx();\n                        // consider reserve outputs and set priority according to their value here as well\n                        if (isReserve)\n                        {\n                            totalReserveIn += otx.vout[txin.prevout.n].ReserveOutValue();\n                        }\n                        nTotalIn += otx.vout[txin.prevout.n].nValue;\n                        continue;\n                    }\n                    const CCoins* coins = view.AccessCoins(txin.prevout.hash);\n                    assert(coins);\n\n                    if (isReserve)\n                    {\n                        reserveValueIn = coins->vout[txin.prevout.n].ReserveOutValue();\n                    }\n\n                    nValueIn = coins->vout[txin.prevout.n].nValue;\n                    int nConf = nHeight - coins->nHeight;\n\n                    dPriority += ((double)((reserveValueIn.valueMap.size() ? currencyState.ReserveToNative(reserveValueIn) : 0) + nValueIn)) * nConf;\n\n                    if (!isReserve)\n                    {\n                        nTotalIn += nValueIn;\n                        totalReserveIn += reserveValueIn;\n                    }\n                }\n                nTotalIn += tx.GetShieldedValueIn();\n            }\n\n            if (fMissingInputs) continue;\n            \n            // Priority is sum(valuein * age) / modified_txsize\n            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n            dPriority = tx.ComputePriority(dPriority, nTxSize);\n            \n            CAmount nDeltaValueIn = nTotalIn + (totalReserveIn.valueMap.size() ? currencyState.ReserveToNative(totalReserveIn) : 0);\n            CAmount nFeeValueIn = nDeltaValueIn;\n            mempool.ApplyDeltas(hash, dPriority, nDeltaValueIn);\n\n            CAmount nativeEquivalentOut = 0;\n\n            // if there is reserve in, or this is a reserveexchange transaction, calculate fee properly\n            if (isReserve && rtxd.ReserveOutputMap().valueMap.size())\n            {\n                // if this has reserve currency out, convert it to native currency for fee calculation\n                nativeEquivalentOut = currencyState.ReserveToNative(rtxd.ReserveOutputMap());\n            }\n\n            CFeeRate feeRate(isReserve ? rtxd.AllFeesAsNative(currencyState) + currencyState.ReserveToNative(rtxd.ReserveConversionFeesMap()) + rtxd.nativeConversionFees : \n                                         nFeeValueIn - (tx.GetValueOut() + nativeEquivalentOut), nTxSize);\n\n            if (porphan)\n            {\n                porphan->dPriority = dPriority;\n                porphan->feeRate = feeRate;\n            }\n            else\n                vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));\n        }\n\n        //\n        // NOW -- REALLY START TO FILL THE BLOCK\n        //\n        // estimate number of conversions, staking transaction size, and additional coinbase outputs that will be required\n\n        int32_t maxPreLimitOrderBlockSize = nBlockMaxSize - std::min(nBlockMaxSize >> 2, reserveExchangeLimitSize);\n\n        int64_t interest;\n        bool fSortedByFee = (nBlockPrioritySize <= 0);\n\n        TxPriorityCompare comparer(fSortedByFee);\n        std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);\n\n        std::vector<int> reservePositions;\n\n        // now loop and fill the block, leaving space for reserve exchange limit transactions\n        while (!vecPriority.empty())\n        {\n            // Take highest priority transaction off the priority queue:\n            double dPriority = vecPriority.front().get<0>();\n            CFeeRate feeRate = vecPriority.front().get<1>();\n            const CTransaction& tx = *(vecPriority.front().get<2>());\n            \n            std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);\n            vecPriority.pop_back();\n            \n            // Size limits\n            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n            if (nBlockSize + nTxSize >= maxPreLimitOrderBlockSize - autoTxSize) // room for extra autotx\n            {\n                //fprintf(stderr,\"nBlockSize %d + %d nTxSize >= %d maxPreLimitOrderBlockSize\\n\",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)maxPreLimitOrderBlockSize);\n                continue;\n            }\n            \n            // Legacy limits on sigOps:\n            unsigned int nTxSigOps = GetLegacySigOpCount(tx);\n            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)\n            {\n                //fprintf(stderr,\"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\\n\",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);\n                continue;\n            }\n            // Skip free transactions if we're past the minimum block size:\n            const uint256& hash = tx.GetHash();\n            double dPriorityDelta = 0;\n            CAmount nFeeDelta = 0;\n            mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);\n            if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))\n            {\n                //fprintf(stderr,\"fee rate skip\\n\");\n                continue;\n            }\n\n            // Prioritise by fee once past the priority size or we run out of high-priority\n            // transactions:\n            if (!fSortedByFee &&\n                ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))\n            {\n                fSortedByFee = true;\n                comparer = TxPriorityCompare(fSortedByFee);\n                std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);\n            }\n            \n            if (!view.HaveInputs(tx))\n            {\n                //fprintf(stderr,\"dont have inputs\\n\");\n                continue;\n            }\n            CAmount nTxFees;\n            CReserveTransactionDescriptor txDesc;\n            bool isReserve = mempool.IsKnownReserveTransaction(hash, txDesc);\n\n            nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime) - tx.GetValueOut();\n            \n            nTxSigOps += GetP2SHSigOpCount(tx, view);\n            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)\n            {\n                //fprintf(stderr,\"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\\n\",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);\n                continue;\n            }\n\n            // Note that flags: we don't want to set mempool/IsStandard()\n            // policy here, but we still have to ensure that the block we\n            // create only contains transactions that are valid in new blocks.\n            CValidationState state;\n            PrecomputedTransactionData txdata(tx);\n            if (!ContextualCheckInputs(tx, state, view, nHeight, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))\n            {\n                //fprintf(stderr,\"context failure\\n\");\n                continue;\n            }\n\n            UpdateCoins(tx, view, nHeight);\n\n            if (isReserve)\n            {\n                reservePositions.push_back(nBlockTx);\n                haveReserveTransactions = true;\n                additionalFees += txDesc.ReserveFees();\n            }\n\n            BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {\n                sapling_tree.append(outDescription.cm);\n            }\n\n            // Added\n            pblock->vtx.push_back(tx);\n            pblocktemplate->vTxFees.push_back(nTxFees);\n            pblocktemplate->vTxSigOps.push_back(nTxSigOps);\n            nBlockSize += nTxSize;\n            ++nBlockTx;\n            nBlockSigOps += nTxSigOps;\n            nFees += nTxFees;\n            if (fPrintPriority)\n            {\n                LogPrintf(\"priority %.1f fee %s txid %s\\n\",dPriority, feeRate.ToString(), tx.GetHash().ToString());\n            }\n            \n            // Add transactions that depend on this one to the priority queue\n            if (mapDependers.count(hash))\n            {\n                BOOST_FOREACH(COrphan* porphan, mapDependers[hash])\n                {\n                    if (!porphan->setDependsOn.empty())\n                    {\n                        porphan->setDependsOn.erase(hash);\n                        if (porphan->setDependsOn.empty())\n                        {\n                            vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));\n                            std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);\n                        }\n                    }\n                }\n            }\n        }\n\n        // first calculate and distribute block rewards, including fees in the minerOutputs vector\n        CAmount rewardTotalShareAmount = 0;\n        CAmount rewardFees = nFees;\n        if (additionalFees.valueMap.count(thisChainID))\n        {\n            rewardFees += additionalFees.valueMap[thisChainID];\n            additionalFees.valueMap.erase(thisChainID);\n        }\n\n        CAmount verusFees = 0;\n        if (VERUS_CHAINID != ASSETCHAINS_CHAINID && additionalFees.valueMap.count(VERUS_CHAINID))\n        {\n            verusFees += additionalFees.valueMap[VERUS_CHAINID];\n            additionalFees.valueMap.erase(VERUS_CHAINID);\n        }\n\n        if (additionalFees.valueMap.size())\n        {\n            printf(\"%s: burning reserve currency: %s\\n\", __func__, additionalFees.ToUniValue().write(1,2).c_str());\n        }\n\n        if (feePool.IsValid())\n        {\n            // we support only the current native currency or VRSC on PBaaS chains in the fee pool for now\n            feePool.reserveValues.valueMap[thisChainID] += rewardFees;\n            if (verusFees)\n            {\n                feePool.reserveValues.valueMap[VERUS_CHAINID] += verusFees;\n            }\n            CFeePool oneFeeShare = feePool.OneFeeShare();\n            rewardFees = oneFeeShare.reserveValues.valueMap[thisChainID];\n            feePool.reserveValues.valueMap[thisChainID] -= rewardFees;\n\n            if (VERUS_CHAINID != ASSETCHAINS_CHAINID && oneFeeShare.reserveValues.valueMap.count(VERUS_CHAINID))\n            {\n                verusFees = oneFeeShare.reserveValues.valueMap[VERUS_CHAINID];\n                feePool.reserveValues.valueMap[VERUS_CHAINID] -= verusFees;\n            }\n\n            cp = CCinit(&CC, EVAL_FEE_POOL);\n            pkCC = CPubKey(ParseHex(CC.CChexstr));\n            coinbaseTx.vout.push_back(CTxOut(0,MakeMofNCCScript(CConditionObj<CFeePool>(EVAL_FEE_POOL,{pkCC.GetID()},1,&feePool))));\n        }\n\n        // printf(\"%s: rewardfees: %ld, verusfees: %ld\\n\", __func__, rewardFees, verusFees);\n\n        CAmount rewardTotal = blockSubsidy + rewardFees;\n\n        // now that we have the total reward, update the coinbase outputs\n        if (isStake)\n        {\n            // TODO: need to add reserve output to stake coinbase to prevent burning of VRSC\n            coinbaseTx.vout[0].nValue = rewardTotal;\n        }\n        else\n        {\n            for (auto &outputShare : minerOutputs)\n            {\n                rewardTotalShareAmount += outputShare.nValue;\n            }\n\n            int cbOutIdx;\n            CAmount rewardLeft = rewardTotal;\n            CAmount verusFeeLeft = verusFees;\n            for (cbOutIdx = 0; cbOutIdx < minerOutputs.size(); cbOutIdx++)\n            {\n                CAmount amount = (arith_uint256(rewardTotal) * arith_uint256(minerOutputs[cbOutIdx].nValue) / arith_uint256(rewardTotalShareAmount)).GetLow64();\n                if (rewardLeft <= amount || (cbOutIdx + 1) == minerOutputs.size())\n                {\n                    amount = rewardLeft;\n                }\n                rewardLeft -= amount;\n\n                // now make outputs for non-native, VRSC fees\n                if (verusFeeLeft)\n                {\n                    CAmount verusFee = (arith_uint256(verusFees) * arith_uint256(minerOutputs[cbOutIdx].nValue) / arith_uint256(rewardTotalShareAmount)).GetLow64();\n                    if (verusFeeLeft <= verusFee || (cbOutIdx + 1) == minerOutputs.size())\n                    {\n                        verusFee = verusFeeLeft;\n                    }\n                    CTxDestination minerDestination;\n                    if (verusFee >= CFeePool::MIN_SHARE_SIZE && ExtractDestination(coinbaseTx.vout[cbOutIdx].scriptPubKey, minerDestination))\n                    {\n                        CTokenOutput to = CTokenOutput(VERUS_CHAINID, verusFee);\n                        coinbaseTx.vout[cbOutIdx].scriptPubKey = MakeMofNCCScript(CConditionObj<CTokenOutput>(EVAL_RESERVE_OUTPUT, \n                                                                                  std::vector<CTxDestination>({minerDestination}),\n                                                                                  1,\n                                                                                  &to));\n                    }\n                    verusFeeLeft -= verusFee;\n                }\n\n                // we had to wait to update this here to ensure it represented a correct distribution ratio\n                coinbaseTx.vout[cbOutIdx].nValue = amount;\n            }\n        }\n\n        nLastBlockTx = nBlockTx;\n        nLastBlockSize = nBlockSize;\n\n        blocktime = std::max(pindexPrev->GetMedianTimePast(), GetAdjustedTime());\n\n        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());\n\n        coinbaseTx.nExpiryHeight = 0;\n        coinbaseTx.nLockTime = blocktime;\n\n        // finalize input of coinbase\n        coinbaseTx.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(0)) + COINBASE_FLAGS;\n        assert(coinbaseTx.vin[0].scriptSig.size() <= 100);\n\n        // coinbase is done\n        pblock->vtx[0] = coinbaseTx;\n        uint256 cbHash = coinbaseTx.GetHash();\n\n        // display it at block 1 for PBaaS debugging\n        /* if (nHeight == 1)\n        {\n            UniValue jsonTxOut(UniValue::VOBJ);\n            TxToUniv(coinbaseTx, uint256(), jsonTxOut);\n            printf(\"%s: new coinbase transaction: %s\\n\", __func__, jsonTxOut.write(1,2).c_str());\n        } */\n\n        // if there is a stake transaction, add it to the very end\n        if (isStake)\n        {\n            UpdateCoins(txStaked, view, nHeight);\n            pblock->vtx.push_back(txStaked);\n            pblocktemplate->vTxFees.push_back(0);\n            int txSigOps = GetLegacySigOpCount(txStaked);\n            pblocktemplate->vTxSigOps.push_back(txSigOps);\n            // already added to the block size above\n            ++nBlockTx;\n            nBlockSigOps += txSigOps;\n        }\n\n        extern CWallet *pwalletMain;\n\n        pblock->vtx[0] = coinbaseTx;\n        pblocktemplate->vTxFees[0] = -nFees;\n        pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);\n\n        // if not Verus stake, setup nonce, otherwise, leave it alone\n        if (!isStake || ASSETCHAINS_LWMAPOS == 0)\n        {\n            // Randomize nonce\n            arith_uint256 nonce = UintToArith256(GetRandHash());\n\n            // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)\n            nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];\n            nonce >>= 16;\n            pblock->nNonce = ArithToUint256(nonce);\n        }\n        \n        // Fill in header\n        pblock->hashPrevBlock  = pindexPrev->GetBlockHash();\n        pblock->hashFinalSaplingRoot   = sapling_tree.root();\n\n        // all Verus PoS chains need this data in the block at all times\n        if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 )\n        {\n            UpdateTime(pblock, Params().GetConsensus(), pindexPrev);\n            pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());\n        }\n\n        if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )\n        {\n            uint32_t r;\n            CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);\n            if ( pblock->nTime < pindexPrev->nTime+60 )\n                pblock->nTime = pindexPrev->nTime + 60;\n\n            if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )\n            {\n                CAmount txfees = 5000;\n                pblock->vtx.push_back(txNotary);\n                pblocktemplate->vTxFees.push_back(txfees);\n                pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));\n                nFees += txfees;\n                pblocktemplate->vTxFees[0] = -nFees;\n                //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;\n                //fprintf(stderr,\"added notaryvin\\n\");\n            }\n            else\n            {\n                fprintf(stderr,\"error adding notaryvin, need to create 0.0001 utxos\\n\");\n                return(0);\n            }\n        }\n        else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )\n        {\n            CValidationState state;\n            //fprintf(stderr,\"check validity\\n\");\n            if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) // invokes CC checks\n            {\n                throw std::runtime_error(\"CreateNewBlock(): TestBlockValidity failed\");\n            }\n            //fprintf(stderr,\"valid\\n\");\n        }\n    }\n    //fprintf(stderr,\"done new block\\n\");\n\n    // setup the header and buid the Merkle tree\n    unsigned int extraNonce;\n    IncrementExtraNonce(pblock, pindexPrev, extraNonce, true);\n\n    return pblocktemplate.release();\n}\n\nCBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const CScript& _scriptPubKeyIn, bool isStake)\n{\n    std::vector<CTxOut> minerOutputs = _scriptPubKeyIn.size() ? std::vector<CTxOut>({CTxOut(1, _scriptPubKeyIn)}) : std::vector<CTxOut>();\n    return CreateNewBlock(chainparams, minerOutputs, isStake);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Internal miner\n//\n\n#ifdef ENABLE_MINING\n\nclass MinerAddressScript : public CReserveScript\n{\n    // CReserveScript requires implementing this function, so that if an\n    // internal (not-visible) wallet address is used, the wallet can mark it as\n    // important when a block is mined (so it then appears to the user).\n    // If -mineraddress is set, the user already knows about and is managing the\n    // address, so we don't need to do anything here.\n    void KeepScript() {}\n};\n\nvoid GetScriptForMinerAddress(boost::shared_ptr<CReserveScript> &script)\n{\n    CTxDestination addr = DecodeDestination(GetArg(\"-mineraddress\", \"\"));\n    if (!IsValidDestination(addr)) {\n        return;\n    }\n\n    boost::shared_ptr<MinerAddressScript> mAddr(new MinerAddressScript());\n    script = mAddr;\n    script->reserveScript = GetScriptForDestination(addr);\n}\n\n#ifdef ENABLE_WALLET\n//////////////////////////////////////////////////////////////////////////////\n//\n// Internal miner\n//\n\nCBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, bool isStake)\n{\n    CPubKey pubkey; \n    CScript scriptPubKey; \n    uint8_t *ptr; \n    int32_t i;\n    boost::shared_ptr<CReserveScript> coinbaseScript;\n \n    if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )\n    {\n        scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;\n    }\n    else if ( USE_EXTERNAL_PUBKEY != 0 )\n    {\n        //fprintf(stderr,\"use notary pubkey\\n\");\n        scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;\n    }\n    else if (GetArg(\"-mineraddress\", \"\").empty() || !(GetScriptForMinerAddress(coinbaseScript), (scriptPubKey = coinbaseScript->reserveScript).size()))\n    {\n        if (!isStake)\n        {\n            if (!reservekey.GetReservedKey(pubkey))\n            {\n                return NULL;\n            }\n            scriptPubKey = GetScriptForDestination(pubkey);\n        }\n    }\n    return CreateNewBlock(Params(), scriptPubKey, isStake);\n}\n\nvoid komodo_broadcast(const CBlock *pblock,int32_t limit)\n{\n    int32_t n = 1;\n    //fprintf(stderr,\"broadcast new block t.%u\\n\",(uint32_t)time(NULL));\n    {\n        LOCK(cs_vNodes);\n        BOOST_FOREACH(CNode* pnode, vNodes)\n        {\n            if ( pnode->hSocket == INVALID_SOCKET )\n                continue;\n            if ( (rand() % n) == 0 )\n            {\n                pnode->PushMessage(\"block\", *pblock);\n                if ( n++ > limit )\n                    break;\n            }\n        }\n    }\n    //fprintf(stderr,\"finished broadcast new block t.%u\\n\",(uint32_t)time(NULL));\n}\n\nstatic bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)\n#else\nstatic bool ProcessBlockFound(CBlock* pblock)\n#endif // ENABLE_WALLET\n{\n    int32_t height = chainActive.LastTip()->GetHeight()+1;\n    //LogPrintf(\"%s\\n\", pblock->ToString());\n    LogPrintf(\"generated %s height.%d\\n\", FormatMoney(pblock->vtx[0].vout[0].nValue), height);\n\n    // Found a solution\n    {\n        if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())\n        {\n            uint256 hash; int32_t i;\n            hash = pblock->hashPrevBlock;\n            for (i=31; i>=0; i--)\n                fprintf(stderr,\"%02x\",((uint8_t *)&hash)[i]);\n            fprintf(stderr,\" <- prev (stale)\\n\");\n            hash = chainActive.LastTip()->GetBlockHash();\n            for (i=31; i>=0; i--)\n                fprintf(stderr,\"%02x\",((uint8_t *)&hash)[i]);\n            fprintf(stderr,\" <- chainTip (stale)\\n\");\n            \n            return error(\"VerusMiner: generated block is stale\");\n        }\n    }\n    \n#ifdef ENABLE_WALLET\n    // Remove key from key pool\n    if ( IS_KOMODO_NOTARY == 0 )\n    {\n        if (GetArg(\"-mineraddress\", \"\").empty()) {\n            // Remove key from key pool\n            reservekey.KeepKey();\n        }\n    }\n    // Track how many getdata requests this block gets\n    //if ( 0 )\n    {\n        //fprintf(stderr,\"lock cs_wallet\\n\");\n        LOCK(wallet.cs_wallet);\n        wallet.mapRequestCount[pblock->GetHash()] = 0;\n    }\n#endif\n    //fprintf(stderr,\"process new block\\n\");\n\n    // Process this block (almost) the same as if we had received it from another node\n    CValidationState state;\n    if (!ProcessNewBlock(1, chainActive.LastTip()->GetHeight()+1, state, Params(), NULL, pblock, true, NULL))\n        return error(\"VerusMiner: ProcessNewBlock, block not accepted\");\n    \n    TrackMinedBlock(pblock->GetHash());\n    komodo_broadcast(pblock,16);\n    return true;\n}\n\nint32_t komodo_baseid(char *origbase);\nint32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);\narith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);\nint32_t FOUND_BLOCK,KOMODO_MAYBEMINED;\nextern int32_t KOMODO_LASTMINED,KOMODO_INSYNC;\nint32_t roundrobin_delay;\narith_uint256 HASHTarget,HASHTarget_POW;\nint32_t komodo_longestchain();\n\n// wait for peers to connect\nvoid waitForPeers(const CChainParams &chainparams)\n{\n    if (chainparams.MiningRequiresPeers())\n    {\n        bool fvNodesEmpty;\n        {\n            boost::this_thread::interruption_point();\n            LOCK(cs_vNodes);\n            fvNodesEmpty = vNodes.empty();\n        }\n        int longestchain = komodo_longestchain();\n        int lastlongest = 0;\n        if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight()))\n        {\n            int loops = 0, blockDiff = 0, newDiff = 0;\n            \n            do {\n                if (fvNodesEmpty)\n                {\n                    MilliSleep(1000 + rand() % 4000);\n                    boost::this_thread::interruption_point();\n                    LOCK(cs_vNodes);\n                    fvNodesEmpty = vNodes.empty();\n                    loops = 0;\n                    blockDiff = 0;\n                    lastlongest = 0;\n                }\n                else if ((newDiff = IsNotInSync()) > 0)\n                {\n                    if (blockDiff != newDiff)\n                    {\n                        blockDiff = newDiff;\n                    }\n                    else\n                    {\n                        if (++loops <= 5)\n                        {\n                            MilliSleep(1000);\n                        }\n                        else break;\n                    }\n                    lastlongest = 0;\n                }\n                else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight())\n                {\n                    // the only thing may be that we are seeing a long chain that we'll never get\n                    // don't wait forever\n                    if (lastlongest == 0)\n                    {\n                        MilliSleep(3000);\n                        lastlongest = longestchain;\n                    }\n                }\n            } while (fvNodesEmpty || IsNotInSync());\n            MilliSleep(500 + rand() % 1000);\n        }\n    }\n}\n\n#ifdef ENABLE_WALLET\nCBlockIndex *get_chainactive(int32_t height)\n{\n    if ( chainActive.LastTip() != 0 )\n    {\n        if ( height <= chainActive.LastTip()->GetHeight() )\n        {\n            LOCK(cs_main);\n            return(chainActive[height]);\n        }\n        // else fprintf(stderr,\"get_chainactive height %d > active.%d\\n\",height,chainActive.Tip()->GetHeight());\n    }\n    //fprintf(stderr,\"get_chainactive null chainActive.Tip() height %d\\n\",height);\n    return(0);\n}\n\n/*\n * A separate thread to stake, while the miner threads mine.\n */\nvoid static VerusStaker(CWallet *pwallet)\n{\n    LogPrintf(\"Verus staker thread started\\n\");\n    RenameThread(\"verus-staker\");\n\n    const CChainParams& chainparams = Params();\n    auto consensusParams = chainparams.GetConsensus();\n    bool isNotaryConnected = ConnectedChains.CheckVerusPBaaSAvailable();\n\n    // Each thread has its own key\n    CReserveKey reservekey(pwallet);\n\n    // Each thread has its own counter\n    unsigned int nExtraNonce = 0;\n\n    uint8_t *script; uint64_t total,checktoshis; int32_t i,j;\n\n    while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&\n    {\n        sleep(1);\n        if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )\n            break;\n    }\n\n    // try a nice clean peer connection to start\n    CBlockIndex *pindexPrev, *pindexCur;\n    do {\n        pindexPrev = chainActive.LastTip();\n        MilliSleep(5000 + rand() % 5000);\n        waitForPeers(chainparams);\n        pindexCur = chainActive.LastTip();\n    } while (pindexPrev != pindexCur);\n\n    try {\n        static int32_t lastStakingHeight = 0;\n\n        while (true)\n        {\n            waitForPeers(chainparams);\n            CBlockIndex* pindexPrev = chainActive.LastTip();\n\n            // Create new block\n            unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();\n\n            if ( Mining_height != pindexPrev->GetHeight()+1 )\n            {\n                Mining_height = pindexPrev->GetHeight()+1;\n                Mining_start = (uint32_t)time(NULL);\n            }\n\n            // Check for stop or if block needs to be rebuilt\n            boost::this_thread::interruption_point();\n\n            // try to stake a block\n            CBlockTemplate *ptr = NULL;\n\n            // get height locally for consistent reporting\n            int32_t newHeight = Mining_height;\n\n            if (newHeight > VERUS_MIN_STAKEAGE)\n                ptr = CreateNewBlockWithKey(reservekey, newHeight, true);\n\n            // TODO - putting this output here tends to help mitigate announcing a staking height earlier than\n            // announcing the last block win when we start staking before a block's acceptance has been\n            // acknowledged by the mining thread - a better solution may be to put the output on the submission\n            // thread.\n            if ( ptr == 0 && newHeight != lastStakingHeight )\n            {\n                printf(\"Staking height %d for %s\\n\", newHeight, ASSETCHAINS_SYMBOL);\n            }\n            lastStakingHeight = newHeight;\n\n            if ( ptr == 0 )\n            {\n                if (newHeight == 1 && (isNotaryConnected = ConnectedChains.IsNotaryAvailable()))\n                {\n                    static int outputCounter;\n                    if (outputCounter++ % 60 == 0)\n                    {\n                        printf(\"%s: waiting for confirmation of launch at or after block %u on %s before mining block 1\\n\", __func__, \n                                                                                        (uint32_t)ConnectedChains.ThisChain().startBlock, \n                                                                                        ConnectedChains.FirstNotaryChain().chainDefinition.name.c_str());\n                        sleep(1);\n                    }\n                }\n                // wait to try another staking block until after the tip moves again\n                while ( chainActive.LastTip() == pindexPrev )\n                    MilliSleep(250);\n                if (newHeight == 1)\n                {\n                    sleep(10);\n                }\n                continue;\n            }\n\n            unique_ptr<CBlockTemplate> pblocktemplate(ptr);\n            if (!pblocktemplate.get())\n            {\n                if (GetArg(\"-mineraddress\", \"\").empty()) {\n                    LogPrintf(\"Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\\n\",\n                              ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n                } else {\n                    // Should never reach here, because -mineraddress validity is checked in init.cpp\n                    LogPrintf(\"Error in %s staker: Invalid %s -mineraddress\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);\n                }\n                return;\n            }\n\n            CBlock *pblock = &pblocktemplate->block;\n            LogPrintf(\"Staking with %u transactions in block (%u bytes)\\n\", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));\n            //\n            // Search\n            //\n            int64_t nStart = GetTime();\n\n            if (vNodes.empty() && chainparams.MiningRequiresPeers())\n            {\n                if ( Mining_height > ASSETCHAINS_MINHEIGHT )\n                {\n                    fprintf(stderr,\"no nodes, attempting reconnect\\n\");\n                    continue;\n                }\n            }\n\n            if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)\n            {\n                fprintf(stderr,\"timeout, retrying\\n\");\n                continue;\n            }\n\n            if ( pindexPrev != chainActive.LastTip() )\n            {\n                printf(\"Block %d added to chain\\n\", chainActive.LastTip()->GetHeight());\n                MilliSleep(250);\n                continue;\n            }\n\n            int32_t unlockTime = komodo_block_unlocktime(Mining_height);\n            int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);\n\n            uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));\n\n            pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);\n\n            UpdateTime(pblock, consensusParams, pindexPrev);\n\n            if (ProcessBlockFound(pblock, *pwallet, reservekey))\n            {\n                LogPrintf(\"Using %s algorithm:\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n                LogPrintf(\"Staked block found  \\n  hash: %s  \\ntarget: %s\\n\", pblock->GetHash().GetHex(), hashTarget.GetHex());\n                printf(\"Found block %d \\n\", newHeight);\n                printf(\"staking reward %.8f %s!\\n\", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);\n                arith_uint256 post;\n                post.SetCompact(pblock->GetVerusPOSTarget());\n\n                CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1];\n                printf(\"POS hash: %s  \\ntarget:   %s\\n\", \n                    CTransaction::_GetVerusPOSHash(&(pblock->nNonce), \n                                                     sTx.vin[0].prevout.hash, \n                                                     sTx.vin[0].prevout.n, \n                                                     newHeight, \n                                                     chainActive.GetVerusEntropyHash(newHeight), \n                                                     sTx.vout[0].nValue).GetHex().c_str(), \n                                                     ArithToUint256(post).GetHex().c_str());\n                if (unlockTime > newHeight && subsidy >= ASSETCHAINS_TIMELOCKGTE)\n                    printf(\"- timelocked until block %i\\n\", unlockTime);\n                else\n                    printf(\"\\n\");\n            }\n            else\n            {\n                LogPrintf(\"Found block rejected at staking height: %d\\n\", Mining_height);\n                printf(\"Found block rejected at staking height: %d\\n\", Mining_height);\n            }\n\n            // Check for stop or if block needs to be rebuilt\n            boost::this_thread::interruption_point();\n\n            sleep(3);\n\n            // In regression test mode, stop mining after a block is found.\n            if (chainparams.MineBlocksOnDemand()) {\n                throw boost::thread_interrupted();\n            }\n        }\n    }\n    catch (const boost::thread_interrupted&)\n    {\n        LogPrintf(\"VerusStaker terminated\\n\");\n        throw;\n    }\n    catch (const std::runtime_error &e)\n    {\n        LogPrintf(\"VerusStaker runtime error: %s\\n\", e.what());\n        return;\n    }\n}\n\ntypedef bool (*minefunction)(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);\nbool mine_verus_v2(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);\nbool mine_verus_v2_port(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);\n\nvoid static BitcoinMiner_noeq(CWallet *pwallet)\n#else\nvoid static BitcoinMiner_noeq()\n#endif\n{\n    LogPrintf(\"%s miner started\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n    RenameThread(\"verushash-miner\");\n\n#ifdef ENABLE_WALLET\n    // Each thread has its own key\n    CReserveKey reservekey(pwallet);\n#endif\n\n    miningTimer.clear();\n\n    const CChainParams& chainparams = Params();\n    // Each thread has its own counter\n    unsigned int nExtraNonce = 0;\n\n    uint8_t *script; uint64_t total,checktoshis; int32_t i,j;\n\n    while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&\n    {\n        sleep(1);\n        if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )\n            break;\n    }\n\n    SetThreadPriority(THREAD_PRIORITY_LOWEST);\n\n    // try a nice clean peer connection to start\n    CBlockIndex *pindexPrev, *pindexCur;\n    do {\n        pindexPrev = chainActive.LastTip();\n        MilliSleep(5000 + rand() % 5000);\n        waitForPeers(chainparams);\n        pindexCur = chainActive.LastTip();\n    } while (pindexPrev != pindexCur);\n\n    // make sure that we have checked for PBaaS availability\n    ConnectedChains.CheckVerusPBaaSAvailable();\n\n    // this will not stop printing more than once in all cases, but it will allow us to print in all cases\n    // and print duplicates rarely without having to synchronize\n    static CBlockIndex *lastChainTipPrinted;\n    static int32_t lastMiningHeight = 0;\n\n    miningTimer.start();\n\n    try {\n        printf(\"Mining %s with %s\\n\", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n\n        while (true)\n        {\n            miningTimer.stop();\n            waitForPeers(chainparams);\n\n            pindexPrev = chainActive.LastTip();\n\n            // prevent forking on startup before the diff algorithm kicks in,\n            // but only for a startup Verus test chain. PBaaS chains have the difficulty inherited from\n            // their parent\n            if (chainparams.MiningRequiresPeers() && ((IsVerusActive() && pindexPrev->GetHeight() < 50) || pindexPrev != chainActive.LastTip()))\n            {\n                do {\n                    pindexPrev = chainActive.LastTip();\n                    MilliSleep(2000 + rand() % 2000);\n                } while (pindexPrev != chainActive.LastTip());\n            }\n\n            // Create new block\n            unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();\n            if ( Mining_height != pindexPrev->GetHeight()+1 )\n            {\n                Mining_height = pindexPrev->GetHeight()+1;\n                if (lastMiningHeight != Mining_height)\n                {\n                    lastMiningHeight = Mining_height;\n                    printf(\"Mining %s at height %d\\n\", ASSETCHAINS_SYMBOL, Mining_height);\n                }\n                Mining_start = (uint32_t)time(NULL);\n            }\n\n            miningTimer.start();\n\n#ifdef ENABLE_WALLET\n            CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height);\n#else\n            CBlockTemplate *ptr = CreateNewBlockWithKey();\n#endif\n            if ( ptr == 0 )\n            {\n                static uint32_t counter;\n                if ( counter++ % 40 == 0 )\n                {\n                    if (!IsVerusActive() &&\n                        ConnectedChains.IsNotaryAvailable() &&\n                        !ConnectedChains.readyToStart)\n                    {\n                        fprintf(stderr,\"waiting for confirmation of launch at or after block %u on %s chain to start\\n\", (uint32_t)ConnectedChains.ThisChain().startBlock,\n                                                                                        ConnectedChains.FirstNotaryChain().chainDefinition.name.c_str());\n                    }\n                    else\n                    {\n                        fprintf(stderr,\"Unable to create valid block... will continue to try\\n\");\n                    }\n                }\n                MilliSleep(2000);\n                continue;\n            }\n\n            unique_ptr<CBlockTemplate> pblocktemplate(ptr);\n            if (!pblocktemplate.get())\n            {\n                if (GetArg(\"-mineraddress\", \"\").empty()) {\n                    LogPrintf(\"Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\\n\",\n                              ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n                } else {\n                    // Should never reach here, because -mineraddress validity is checked in init.cpp\n                    LogPrintf(\"Error in %s miner: Invalid %s -mineraddress\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);\n                }\n                miningTimer.stop();\n                miningTimer.clear();\n                return;\n            }\n            CBlock *pblock = &pblocktemplate->block;\n\n            uint32_t savebits;\n            bool mergeMining = false;\n            savebits = pblock->nBits;\n\n            uint32_t solutionVersion = CConstVerusSolutionVector::Version(pblock->nSolution);\n            if (pblock->nVersion != CBlockHeader::VERUS_V2)\n            {\n                // must not be in sync\n                printf(\"Mining on incorrect block version.\\n\");\n                sleep(2);\n                continue;\n            }\n            bool verusSolutionPBaaS = solutionVersion >= CActivationHeight::ACTIVATE_PBAAS;\n\n            // v2 hash writer with adjustments for the current height\n            CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION, solutionVersion);\n\n            if ( ASSETCHAINS_SYMBOL[0] != 0 )\n            {\n                if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )\n                {\n                    if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )\n                    {\n                        static uint32_t counter;\n                        if ( counter++ < 10 )\n                            fprintf(stderr,\"skip generating %s on-demand block, no tx avail\\n\",ASSETCHAINS_SYMBOL);\n                        sleep(10);\n                        continue;\n                    } else fprintf(stderr,\"%s vouts.%d mining.%d vs %d\\n\",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);\n                }\n            }\n\n            // set our easiest target, if V3+, no need to rebuild the merkle tree\n            IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, verusSolutionPBaaS ? false : true, &savebits);\n\n            // update PBaaS header\n            if (verusSolutionPBaaS)\n            {\n                if (!IsVerusActive() && ConnectedChains.IsVerusPBaaSAvailable())\n                {\n\n                    UniValue params(UniValue::VARR);\n                    UniValue error(UniValue::VARR);\n                    params.push_back(EncodeHexBlk(*pblock));\n                    params.push_back(ASSETCHAINS_SYMBOL);\n                    params.push_back(ASSETCHAINS_RPCHOST);\n                    params.push_back(ASSETCHAINS_RPCPORT);\n                    params.push_back(ASSETCHAINS_RPCCREDENTIALS);\n                    try\n                    {\n                        ConnectedChains.lastSubmissionFailed = false;\n                        params = RPCCallRoot(\"addmergedblock\", params);\n                        params = find_value(params, \"result\");\n                        error = find_value(params, \"error\");\n                    } catch (std::exception e)\n                    {\n                        printf(\"Failed to connect to %s chain\\n\", ConnectedChains.FirstNotaryChain().chainDefinition.name.c_str());\n                        params = UniValue(e.what());\n                    }\n                    if (mergeMining = (params.isNull() && error.isNull()))\n                    {\n                        printf(\"Merge mining %s with %s as the hashing chain\\n\", ASSETCHAINS_SYMBOL, ConnectedChains.FirstNotaryChain().chainDefinition.name.c_str());\n                        LogPrintf(\"Merge mining with %s as the hashing chain\\n\", ConnectedChains.FirstNotaryChain().chainDefinition.name.c_str());\n                    }\n                }\n            }\n\n            LogPrintf(\"Running %s miner with %u transactions in block (%u bytes)\\n\",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],\n                       pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));\n            //\n            // Search\n            //\n            int64_t nStart = GetTime();\n\n            arith_uint256 hashTarget = arith_uint256().SetCompact(savebits);\n            uint256 uintTarget = ArithToUint256(hashTarget);\n            arith_uint256 ourTarget;\n            ourTarget.SetCompact(pblock->nBits);\n\n            Mining_start = 0;\n\n            if ( pindexPrev != chainActive.LastTip() )\n            {\n                if (lastChainTipPrinted != chainActive.LastTip())\n                {\n                    lastChainTipPrinted = chainActive.LastTip();\n                    printf(\"Block %d added to chain\\n\", lastChainTipPrinted->GetHeight());\n                }\n                MilliSleep(100);\n                continue;\n            }\n\n            uint64_t count;\n            uint64_t hashesToGo = 0;\n            uint64_t totalDone = 0;\n\n            int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);\n            count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];\n            CVerusHashV2 *vh2 = &ss2.GetState();\n            u128 *hashKey;\n            verusclhasher &vclh = vh2->vclh;\n            minefunction mine_verus;\n            mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port;\n\n            while (true)\n            {\n                uint256 hashResult = uint256();\n\n                unsigned char *curBuf;\n\n                if (mergeMining)\n                {\n                    // loop for a few minutes before refreshing the block\n                    while (true)\n                    {\n                        uint256 ourMerkle = pblock->hashMerkleRoot;\n                        if ( pindexPrev != chainActive.LastTip() )\n                        {\n                            if (lastChainTipPrinted != chainActive.LastTip())\n                            {\n                                lastChainTipPrinted = chainActive.LastTip();\n                                printf(\"Block %d added to chain\\n\\n\", lastChainTipPrinted->GetHeight());\n                                arith_uint256 target;\n                                target.SetCompact(lastChainTipPrinted->nBits);\n                                if (ourMerkle == lastChainTipPrinted->hashMerkleRoot)\n                                {\n                                    LogPrintf(\"proof-of-work found  \\n  hash: %s  \\ntarget: %s\\n\", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str());\n                                    printf(\"Found block %d \\n\", lastChainTipPrinted->GetHeight());\n                                    printf(\"mining reward %.8f %s!\\n\", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);\n                                    printf(\"  hash: %s\\ntarget: %s\\n\", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str());\n                                }\n                            }\n                            break;\n                        }\n\n                        // if PBaaS is no longer available, we can't count on merge mining\n                        if (!ConnectedChains.IsVerusPBaaSAvailable())\n                        {\n                            break;\n                        }\n\n                        if (vNodes.empty() && chainparams.MiningRequiresPeers())\n                        {\n                            if ( Mining_height > ASSETCHAINS_MINHEIGHT )\n                            {\n                                fprintf(stderr,\"no nodes, attempting reconnect\\n\");\n                                break;\n                            }\n                        }\n\n                        // update every few minutes, regardless\n                        int64_t elapsed = GetTime() - nStart;\n\n                        if ((mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && elapsed > 60) || elapsed > 60 || ConnectedChains.lastSubmissionFailed)\n                        {\n                            break;\n                        }\n\n                        boost::this_thread::interruption_point();\n                        MilliSleep(500);\n                    }\n                    break;\n                }\n                else\n                {\n                    // check NONCEMASK at a time\n                    for (uint64_t i = 0; i < count; i++)\n                    {\n                        // this is the actual mining loop, which enables us to drop out and queue a header anytime we earn a block that is good enough for a\n                        // merge mined block, but not our own\n                        bool blockFound;\n                        arith_uint256 arithHash;\n                        totalDone = 0;\n                        do\n                        {\n                            // pickup/remove any new/deleted headers\n                            if (ConnectedChains.dirty || (pblock->NumPBaaSHeaders() < ConnectedChains.mergeMinedChains.size() + 1))\n                            {\n                                IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, verusSolutionPBaaS ? false : true, &savebits);\n\n                                hashTarget.SetCompact(savebits);\n                                uintTarget = ArithToUint256(hashTarget);\n                            }\n\n                            // hashesToGo gets updated with actual number run for metrics\n                            hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];\n                            uint64_t start = i * hashesToGo + totalDone;\n                            hashesToGo -= totalDone;\n\n                            if (verusSolutionPBaaS)\n                            {\n                                // mine on canonical header for merge mining\n                                CPBaaSPreHeader savedHeader(*pblock);\n\n                                pblock->ClearNonCanonicalData();\n                                blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);\n                                savedHeader.SetBlockData(*pblock);\n                            }\n                            else\n                            {\n                                blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);\n                            }\n\n                            arithHash = UintToArith256(hashResult);\n                            totalDone += hashesToGo + 1;\n                            if (blockFound && IsVerusActive())\n                            {\n                                ConnectedChains.QueueNewBlockHeader(*pblock);\n                                if (arithHash > ourTarget)\n                                {\n                                    // all blocks qualified with this hash will be submitted\n                                    // until we redo the block, we might as well not try again with anything over this hash\n                                    hashTarget = arithHash;\n                                    uintTarget = ArithToUint256(hashTarget);\n                                }\n                            }\n                        } while (blockFound && arithHash > ourTarget);\n\n                        if (!blockFound || arithHash > ourTarget)\n                        {\n                            // Check for stop or if block needs to be rebuilt\n                            boost::this_thread::interruption_point();\n                            if ( pindexPrev != chainActive.LastTip() )\n                            {\n                                if (lastChainTipPrinted != chainActive.LastTip())\n                                {\n                                    lastChainTipPrinted = chainActive.LastTip();\n                                    printf(\"Block %d added to chain\\n\", lastChainTipPrinted->GetHeight());\n                                }\n                                break;\n                            }\n                            else if ((i + 1) < count)\n                            {\n                                // if we'll not drop through, update hashcount\n                                {\n                                    miningTimer += totalDone;\n                                    totalDone = 0;\n                                }\n                            }\n                        }\n                        else\n                        {\n                            // Check for stop or if block needs to be rebuilt\n                            boost::this_thread::interruption_point();\n\n                            if (pblock->nSolution.size() != 1344)\n                            {\n                                LogPrintf(\"ERROR: Block solution is not 1344 bytes as it should be\");\n                                break;\n                            }\n\n                            SetThreadPriority(THREAD_PRIORITY_NORMAL);\n\n                            int32_t unlockTime = komodo_block_unlocktime(Mining_height);\n\n#ifdef VERUSHASHDEBUG\n                            std::string validateStr = hashResult.GetHex();\n                            std::string hashStr = pblock->GetHash().GetHex();\n                            uint256 *bhalf1 = (uint256 *)vh2->CurBuffer();\n                            uint256 *bhalf2 = bhalf1 + 1;\n#else\n                            std::string hashStr = hashResult.GetHex();\n#endif\n\n                            LogPrintf(\"Using %s algorithm:\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n                            LogPrintf(\"proof-of-work found  \\n  hash: %s  \\ntarget: %s\\n\", hashStr, ArithToUint256(ourTarget).GetHex());\n                            printf(\"Found block %d \\n\", Mining_height );\n                            printf(\"mining reward %.8f %s!\\n\", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);\n#ifdef VERUSHASHDEBUG\n                            printf(\"  hash: %s\\n   val: %s  \\ntarget: %s\\n\\n\", hashStr.c_str(), validateStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());\n                            printf(\"intermediate %lx\\n\", intermediate);\n                            printf(\"Curbuf: %s%s\\n\", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());\n                            bhalf1 = (uint256 *)verusclhasher_key.get();\n                            bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5);\n                            printf(\"   Key: %s%s\\n\", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());\n#else\n                            printf(\"  hash: %s\\ntarget: %s\", hashStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());\n#endif\n                            if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)\n                                printf(\" - timelocked until block %i\\n\", unlockTime);\n                            else\n                                printf(\"\\n\");\n#ifdef ENABLE_WALLET\n                            ProcessBlockFound(pblock, *pwallet, reservekey);\n#else\n                            ProcessBlockFound(pblock);\n#endif\n                            SetThreadPriority(THREAD_PRIORITY_LOWEST);\n                            break;\n                        }\n                    }\n\n                    {\n                        miningTimer += totalDone;\n                    }\n                }\n                \n\n                // Check for stop or if block needs to be rebuilt\n                boost::this_thread::interruption_point();\n\n                if (vNodes.empty() && chainparams.MiningRequiresPeers())\n                {\n                    if ( Mining_height > ASSETCHAINS_MINHEIGHT )\n                    {\n                        fprintf(stderr,\"no nodes, attempting reconnect\\n\");\n                        break;\n                    }\n                }\n\n                if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)\n                {\n                    fprintf(stderr,\"timeout, retrying\\n\");\n                    break;\n                }\n\n                if ( pindexPrev != chainActive.LastTip() )\n                {\n                    if (lastChainTipPrinted != chainActive.LastTip())\n                    {\n                        lastChainTipPrinted = chainActive.LastTip();\n                        printf(\"Block %d added to chain\\n\\n\", lastChainTipPrinted->GetHeight());\n                    }\n                    break;\n                }\n\n                // totalDone now has the number of hashes actually done since starting on one nonce mask worth\n                uint64_t hashesPerNonceMask = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3;\n                if (!(totalDone < hashesPerNonceMask))\n                {\n#ifdef _WIN32\n                    printf(\"%llu mega hashes complete - working\\n\", (hashesPerNonceMask + 1) / 1048576);\n#else\n                    printf(\"%lu mega hashes complete - working\\n\", (hashesPerNonceMask + 1) / 1048576);\n#endif\n                }\n                break;\n\n            }\n        }\n    }\n    catch (const boost::thread_interrupted&)\n    {\n        miningTimer.stop();\n        miningTimer.clear();\n        LogPrintf(\"%s miner terminated\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n        throw;\n    }\n    catch (const std::runtime_error &e)\n    {\n        miningTimer.stop();\n        miningTimer.clear();\n        LogPrintf(\"%s miner runtime error: %s\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());\n        return;\n    }\n    miningTimer.stop();\n    miningTimer.clear();\n}\n\n#ifdef ENABLE_WALLET\n    void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)\n#else\n    void GenerateBitcoins(bool fGenerate, int nThreads)\n#endif\n    {\n        static CCriticalSection cs_startmining;\n\n        LOCK(cs_startmining);\n        if (!AreParamsInitialized())\n        {\n            return;\n        }\n\n        VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0);\n\n        if (fGenerate == true || VERUS_MINTBLOCKS)\n        {\n            mapArgs[\"-gen\"] = \"1\";\n\n            if (VERUS_DEFAULT_ZADDR.size() > 0)\n            {\n                if (defaultSaplingDest == boost::none)\n                {\n                    LogPrintf(\"ERROR: -defaultzaddr parameter is invalid Sapling payment address\\n\");\n                    fprintf(stderr, \"-defaultzaddr parameter is invalid Sapling payment address\\n\");\n                }\n                else\n                {\n                    LogPrintf(\"StakeGuard searching for double stakes on %s\\n\", VERUS_DEFAULT_ZADDR.c_str());\n                    fprintf(stderr, \"StakeGuard searching for double stakes on %s\\n\", VERUS_DEFAULT_ZADDR.c_str());\n                }\n            }\n        }\n\n        static boost::thread_group* minerThreads = NULL;\n\n        if (nThreads < 0)\n            nThreads = GetNumCores();\n\n        if (minerThreads != NULL)\n        {\n            minerThreads->interrupt_all();\n            minerThreads->join_all();\n            delete minerThreads;\n            minerThreads = NULL;\n        }\n\n        //fprintf(stderr,\"nThreads.%d fGenerate.%d\\n\",(int32_t)nThreads,fGenerate);\n        if ( nThreads == 0 && ASSETCHAINS_STAKED )\n            nThreads = 1;\n\n        if (!fGenerate)\n            return;\n\n        minerThreads = new boost::thread_group();\n\n        // add the PBaaS thread when mining or staking\n        minerThreads->create_thread(boost::bind(&CConnectedChains::SubmissionThreadStub));\n\n#ifdef ENABLE_WALLET\n        if (VERUS_MINTBLOCKS && pwallet != NULL)\n        {\n            minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));\n        }\n#endif\n\n        for (int i = 0; i < nThreads; i++) {\n#ifdef ENABLE_WALLET\n            minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));\n#else\n            minerThreads->create_thread(&BitcoinMiner_noeq);\n#endif\n        }\n    }\n    \n#endif // ENABLE_MINING\n", "meta": {"hexsha": "336986eab548fa8d24270916c01e1f76aabe261e", "size": 156471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/miner.cpp", "max_stars_repo_name": "VerusCoin/VerusCoin", "max_stars_repo_head_hexsha": "4864da842b7ed1fe57e95966b34f80c9188756b5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2018-05-21T15:30:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T00:36:46.000Z", "max_issues_repo_path": "src/miner.cpp", "max_issues_repo_name": "jonathandata1/VerusCoin", "max_issues_repo_head_hexsha": "4864da842b7ed1fe57e95966b34f80c9188756b5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-05-20T23:30:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T22:07:09.000Z", "max_forks_repo_path": "src/miner.cpp", "max_forks_repo_name": "jonathandata1/VerusCoin", "max_forks_repo_head_hexsha": "4864da842b7ed1fe57e95966b34f80c9188756b5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2018-05-06T03:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T20:54:16.000Z", "avg_line_length": 45.2359063313, "max_line_length": 242, "alphanum_fraction": 0.5554447789, "num_tokens": 33568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.190897609652894}}
{"text": "#include \"TilePartitionerNoise.h\"\n#include \"logging/Logging.h\"\n#include \"noise/RasterValues.h\"\n#include \"noise/module/Pow.h\"\n#include \"tilegen/alpha/CalculatorMax.h\"\n#include \"tilegen/alpha/CalculatorLinear.h\"\n#include \"tilegen/alpha/CalculatorTopTwo.h\"\n#include \"tilegen/alpha/CalculatorDither.h\"\n#include \"noise/RasterImage.h\"\n#include \"noise/ModuleGroup.h\"\n#include <boost/filesystem.hpp>\n\n#include <iostream>\n\nnamespace tilegen\n{\nnamespace partition\n{\n\nnoise::module::ModulePtr TilePartitionerNoise::makeCornerModule(const Corners& corners,\n                                                                bool left, bool top)\n{\n    TerrainID corner_id = corners[ (left ? 0 : 2) +  (top ? 0 : 1)];\n    TerrainID corner_h =  corners[(!left ? 0 : 2) +  (top ? 0 : 1)];\n    TerrainID corner_v =  corners[ (left ? 0 : 2) + (!top ? 0 : 1)];\n\n    noise::ModuleGroup& combiner = mNoiseModuleManager.getCombiner();\n    noise::ModuleGroup& central = mNoiseModuleManager.getCentral(corner_id);\n    noise::ModuleGroup& border_h = \n        left\n        ? mNoiseModuleManager.getLeftBorder(left ? corner_id : corner_h,\n                                            left ? corner_h : corner_id)\n        : mNoiseModuleManager.getBottomRightBorder();\n    noise::ModuleGroup& border_v =\n        top\n        ? mNoiseModuleManager.getTopBorder(top ? corner_id : corner_v,\n                                           top ? corner_v : corner_id)\n        : mNoiseModuleManager.getBottomRightBorder();\n    central.setQuadrant(left, top, false);\n    border_h.setQuadrant(left, top, false);\n    border_v.setQuadrant(left, top, false);\n    combiner.setQuadrant(left, top, false);\n\n    combiner.setInputModuleSource(0, border_h.getOutputModule());\n    combiner.setInputModuleSource(1, border_v.getOutputModule());\n    combiner.setInputModuleSource(2, central.getOutputModule());\n    if (mDebugOutput)\n    {\n        writeDebugGroup(combiner, Combiner, top, left);\n        writeDebugGroup(border_h, HorizontalBorder, top, left);\n        writeDebugGroup(border_v, VerticalBorder, top, left);\n        writeDebugGroup(central, Central, top, left);\n    }\n    return combiner.getOutputModule();\n}\n\nvoid TilePartitionerNoise::noiseToAlpha(std::vector<noise::RasterValues<double>>& noise_values,\n                                        std::vector<sf::Image>& outputs,\n                                        sf::Vector2u resolution) const\n{\n    std::vector<double> weights((int)CORNERS);\n    std::unique_ptr<alpha::CalculatorBase> ac;\n    switch (mOptions.calculatorMode)\n    {\n    case alpha::CalculatorMode::Max:\n        ac = std::make_unique<alpha::CalculatorMax>();\n        break;\n    case alpha::CalculatorMode::Linear:\n        ac = std::make_unique<alpha::CalculatorLinear>();\n        break;\n    case alpha::CalculatorMode::TopTwo:\n    {\n        auto ac_top_two = std::make_unique<alpha::CalculatorTopTwo>();\n        if (mOptions.alphaCalculatorTopTwoPower)\n            ac_top_two->power = mOptions.alphaCalculatorTopTwoPower.get();\n        ac = std::move(ac_top_two);\n        break;\n    }\n    case alpha::CalculatorMode::Dither:\n    {\n        auto ac_dither = std::make_unique<alpha::CalculatorDither>();\n        if (mOptions.alphaCalculatorTopTwoPower)\n            ac_dither->power = mOptions.alphaCalculatorTopTwoPower.get();\n        ac = std::move(ac_dither);\n        break;\n    }\n    default:\n        throw std::runtime_error(\"Invalid CalculatorMode\");\n    }\n    for (size_t x = 0; x < resolution.x; x++)\n    {\n        for (size_t y = 0; y < resolution.y; y++)\n        {\n            for (int i = 0; i < (int)CORNERS; i++)\n            {\n                weights[i] = noise_values[i].get(x, y);\n            }\n\n            ac->updateAlphas(weights);\n            const auto& alphas = ac->getAlphas();\n            for (int i = 0; i < (int)CORNERS; i++)\n            {\n                outputs[i].setPixel(x, y, sf::Color(255, 255, 255, alphas[i]));\n            }\n        }\n    }\n}\n\nvoid TilePartitionerNoise::writeDebugGroup(const noise::ModuleGroup& module_group, tilegen::ModuleGroupRole module_group_role, bool top, bool left)\n{\n    if (!mDebugModuleWriter)\n    {\n        logError() << \"Requested debug data but didn't provide a debug module writer function!\\n\";\n        throw std::runtime_error(\"Unable to write debug data\");\n    }\n    for (auto it : module_group.getModules())\n    {\n        mDebugModuleWriter(tilegen::DebugTilesetID(module_group_role, it.first, top, left), it.second);\n    }\n}\n\nvoid TilePartitionerNoise::makePartition(TilePartition & regions, const Corners& corners)\n{\n    // Prepare noise value storage\n    std::vector<noise::RasterValues<double>> noise_values;\n    for (int i = 0; i < (int)CORNERS; i++)\n    {\n        noise_values.emplace_back(mOptions.tileFormat.resolution.x,\n                          mOptions.tileFormat.resolution.y,\n                          sf::Rect<double>{0, 0, 1, 1});\n    }\n    // Construct noise modules and render them.\n    // Construction and rendering must be done in the same step,\n    // because module seeds will be overwritten.\n    noise::module::ModulePtr corner_module;\n    for (int i = 0; i < 2; i++)\n        for (int j = 0; j < 2; j++)\n        {\n            corner_module = makeCornerModule(corners, i == 0, j == 0);\n            int k = (2 * i) + j;\n            noise_values[k].build(corner_module->getModule());\n        }\n    // Prepare output storage\n    std::vector<sf::Image> outputs((int)CORNERS);\n    for (int i = 0; i < (int)CORNERS; i++)\n        outputs[i].create(mOptions.tileFormat.resolution.x, mOptions.tileFormat.resolution.y);\n    // Convert noise values to alpha values\n    noiseToAlpha(noise_values, outputs, mOptions.tileFormat.resolution);\n    // Convert output images to required format\n    for (int i = 0; i < (int)CORNERS; i++)\n    {\n        sf::Texture t;\n        t.loadFromImage(outputs[i]);\n        regions.push_back({t, corners[i]});\n    }\n}\n\nTilePartitionerNoise::TilePartitionerNoise(const Options & options) :\n    TilePartitionerBase(options),\n    mNoiseModuleManager(options),\n    mDebugOutput(options.debugOutput)\n{\n}\n\n} // namespace partition\n} // namespace tilegen\n", "meta": {"hexsha": "cbed1af8212d3d5ca96a784d48d0223234aaaca8", "size": 6130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wangscape/tilegen/partition/TilePartitionerNoise.cpp", "max_stars_repo_name": "cheukyin699/Wangscape", "max_stars_repo_head_hexsha": "b01cb310f97e33394c1c0fac23a7f40c34f632cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2016-12-30T03:18:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T21:43:59.000Z", "max_issues_repo_path": "Wangscape/tilegen/partition/TilePartitionerNoise.cpp", "max_issues_repo_name": "cheukyin699/Wangscape", "max_issues_repo_head_hexsha": "b01cb310f97e33394c1c0fac23a7f40c34f632cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 149.0, "max_issues_repo_issues_event_min_datetime": "2016-12-29T19:38:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-29T18:19:51.000Z", "max_forks_repo_path": "Wangscape/tilegen/partition/TilePartitionerNoise.cpp", "max_forks_repo_name": "cheukyin699/Wangscape", "max_forks_repo_head_hexsha": "b01cb310f97e33394c1c0fac23a7f40c34f632cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-12-31T06:09:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T05:34:51.000Z", "avg_line_length": 36.7065868263, "max_line_length": 147, "alphanum_fraction": 0.6244698206, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.1908976060081937}}
{"text": "#include \"wer.h\"\n\n#include <cstdio>\n#include <cassert>\n#include <iostream>\n#include <limits>\n#include <sstream>\n#ifndef HAVE_OLD_CPP\n# include <unordered_map>\n#else\n# include <tr1/unordered_map>\nnamespace std { using std::tr1::unordered_map; }\n#endif\n#include <set>\n#include <valarray>\n#include <boost/functional/hash.hpp>\n#include <stdexcept>\n#include \"tdict.h\"\n#include \"levenshtein.h\"\n\nusing namespace std;\n\nclass WERScore : public ScoreBase<WERScore> {\n  friend class WERScorer;\n\n public:\n  static const unsigned kEDITDISTANCE = 0;\n  static const unsigned kCHARCOUNT = 1;\n  static const unsigned kDUMMY_LAST_ENTRY = 2;\n\n WERScore() : stats(0,kDUMMY_LAST_ENTRY) {}\n  float ComputePartialScore() const { return 0.0;}\n  float ComputeScore() const {\n    return static_cast<float>(stats[kEDITDISTANCE]) / static_cast<float>(stats[kCHARCOUNT]);\n  }\n  void ScoreDetails(string* details) const;\n  void PlusPartialEquals(const Score& rhs, int oracle_e_cover, int oracle_f_cover, int src_len){}\n  void PlusEquals(const Score& delta, const float scale) {\n    if (scale==1)\n      stats += static_cast<const WERScore&>(delta).stats;\n    if (scale==-1)\n      stats -= static_cast<const WERScore&>(delta).stats;\n    throw std::runtime_error(\"WERScore::PlusEquals with scale != +-1\");\n }\n  void PlusEquals(const Score& delta) {\n    stats += static_cast<const WERScore&>(delta).stats;\n  }\n\n  ScoreP GetZero() const {\n    return ScoreP(new WERScore);\n  }\n  ScoreP GetOne() const {\n    return ScoreP(new WERScore);\n  }\n  void Subtract(const Score& rhs, Score* res) const {\n    static_cast<WERScore*>(res)->stats = stats - static_cast<const WERScore&>(rhs).stats;\n  }\n  void Encode(std::string* out) const {\n    ostringstream os;\n    os << stats[kEDITDISTANCE] << ' '\n       << stats[kCHARCOUNT];\n    *out = os.str();\n  }\n  bool IsAdditiveIdentity() const {\n    for (int i = 0; i < kDUMMY_LAST_ENTRY; ++i)\n      if (stats[i] != 0) return false;\n    return true;\n  }\n private:\n  valarray<int> stats;\n};\n\nScoreP WERScorer::ScoreFromString(const std::string& data) {\n  istringstream is(data);\n  WERScore* r = new WERScore;\n  is >> r->stats[WERScore::kEDITDISTANCE]\n     >> r->stats[WERScore::kCHARCOUNT];\n  return ScoreP(r);\n}\n\nvoid WERScore::ScoreDetails(std::string* details) const {\n  char buf[200];\n  sprintf(buf, \"WER = %.2f, edits=%d, len=%d\",\n     ComputeScore() * 100.0f,\n     stats[kEDITDISTANCE],\n     stats[kCHARCOUNT]);\n  *details = buf;\n}\n\nWERScorer::~WERScorer() {}\nWERScorer::WERScorer(const vector<vector<WordID> >& refs) {}\n\nScoreP WERScorer::ScoreCCandidate(const vector<WordID>& hyp) const {\n  return ScoreP();\n}\n\nfloat WERScorer::Calculate(const std::vector<WordID>& hyp, const Sentence& ref, int& edits, int& char_count) const {\n  edits = cdec::LevenshteinDistance(hyp, ref);\n  char_count = ref.size();\n  return static_cast<float>(edits) / static_cast<float>(char_count);\n}\n\nScoreP WERScorer::ScoreCandidate(const std::vector<WordID>& hyp) const {\n  float best_score = numeric_limits<float>::max();\n  WERScore* res = new WERScore;\n  for (int i = 0; i < refs.size(); ++i) {\n    int edits, char_count;\n    const vector<WordID>& ref = refs[i];\n    float score = Calculate(hyp, ref, edits, char_count);\n    if (score < best_score) {\n      res->stats[WERScore::kEDITDISTANCE] = edits;\n      res->stats[WERScore::kCHARCOUNT] = char_count;\n      best_score = score;\n    }\n  }\n  return ScoreP(res);\n}\n", "meta": {"hexsha": "c806b3be5adde8201682c42a87770ad741f251f9", "size": 3395, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mteval/wer.cc", "max_stars_repo_name": "juliakreutzer/bandit-cdec", "max_stars_repo_head_hexsha": "4765a6eb5c15be9d6157327000765f38973fe941", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-18T04:48:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-18T04:48:24.000Z", "max_issues_repo_path": "mteval/wer.cc", "max_issues_repo_name": "juliakreutzer/bandit-cdec", "max_issues_repo_head_hexsha": "4765a6eb5c15be9d6157327000765f38973fe941", "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": "mteval/wer.cc", "max_forks_repo_name": "juliakreutzer/bandit-cdec", "max_forks_repo_head_hexsha": "4765a6eb5c15be9d6157327000765f38973fe941", "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.7711864407, "max_line_length": 116, "alphanum_fraction": 0.6830633284, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.19089760600819367}}
{"text": "#include \"colibri_ca.h\"\r\n#include \"colibri_local_nav.h\"\r\n#include \"colibri_action.h\"\r\n#include \"PID_controller.h\"\r\n#include \"global_planner.h\"\r\n\r\n#include <boost/bind.hpp>\r\n\r\nvoid PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag);\r\n\r\nint main(int argc, char* argv[])\r\n{\t\r\n\tros::init(argc, argv, \"Follow_path_node\");\r\n\t\r\n\tscan_ca scan4caObj;\t\r\n\tlocal_nav local4navObj;\r\n\tnav_action actionObj;\r\n\tplanner plannerObj;\r\n\t\t\r\n\tros::Rate loop_rate(10);\r\n\r\n\tROS_INFO(\"Start to Follow a path ... \");\r\n\r\n\tunsigned int delay_cnt = 0;\r\n\t\r\n\tint range_num = 0;\r\n\tfloat tmp_theta_laseray = 0.0;\t//obstacle 's theta angle\r\n\t\r\n\r\n\tfloat tmp_delta_dis = 0.0;\r\n\tfloat tmp_robot2goal_yaw = 0.0;\r\n\tfloat tmp_laser2goal_yaw = 0.0;\r\n\tbool goal_inlaser_flag = true;\r\n\tfloat dir_goal_in_laser = 0.0;\r\n\tfloat self_rotation_angle = 0.0;\r\n\r\n\tunsigned int turn_adj_flag = 1;\r\n\r\n\tfloat tmp_action_cmd_t[2] = {0.0, 0.0};\r\n\tfloat* ptr_action_cmd_t = tmp_action_cmd_t;\r\n\tfloat newyaw = 145.0;\r\n\tunsigned int micro_adj_flag = 0;\r\n\r\n\tunsigned int adj_flag = 0;\r\n\t\r\n\tbool obtain_flag = false;\r\n\tunsigned int search_start = 0;\r\n\t\r\n\tros::NodeHandle nh_fp;\r\n\tros::Timer planner_timer;\r\n\tbool finish_plan = false;\r\n\r\n\tbool tmp_timer_finish =false;\r\n\tbool *timer_finish = &tmp_timer_finish;\r\n\r\n\tstatic unsigned int index4gravaton = 0; \r\n\r\n\tfloat delta_robot2gravaton = 0.0;\r\n\tbool at_gravaton_flag = false;\r\n\tbool exist_gravaton_flag = false;\r\n\tbool replan_flag = false;\r\n\r\n\tfloat rt_r2g_dis = 100.0;\r\n\r\n\twhile (!ros::service::waitForService(plannerObj.srv4make_plan, ros::Duration(0.2)))\r\n\t{\r\n\t\tROS_INFO(\"Waiting for service move_base/make_plan to become available\");\r\n\t}\r\n\t\r\n\tROS_INFO(\"Service move_base/make_plan prepared OK...\");\r\n\r\n\tfinish_plan = plannerObj.ExecMonoPlanAndGravaton(plannerObj,&local4navObj.cur_robot_state[0],&local4navObj.goal_state[0], search_start,index4gravaton);\r\n\t\r\n\tplanner_timer = nh_fp.createTimer(ros::Duration(PLAN_INTERVAL), boost::bind(&PlannerCallback, &plannerObj, &local4navObj.cur_robot_state[0],&local4navObj.goal_state[0], timer_finish));\r\n\r\n\twhile (ros::ok())\r\n\t{\t\r\n\t\t\t\r\n\t\tif(delay_cnt < DELAY_CNT_MAX)\r\n\t\t{\r\n\t\t\tdelay_cnt++;\r\n\t\t\tros::spinOnce();\r\n\t\t\tloop_rate.sleep();\r\n\t\t}\r\n\t\t\r\n\t\tif(delay_cnt >= DELAY_CNT_MAX)\r\n\t\t{\r\n\t\t\tROS_INFO(\"------ start ------\");\r\n\t\t\tif(*timer_finish == true)\r\n\t\t\t{\r\n\t\t\t\t*timer_finish = false;\r\n\t\t\t\tindex4gravaton = 0;\r\n\t\t\t\treplan_flag = true;\r\n\r\n\t\t\t}else\r\n\t\t\t{\r\n\t\t\t\t\t\t\r\n\t\t\t\tif((at_gravaton_flag == true && local4navObj.approaching_flag == false)||(replan_flag == true))\r\n\t\t\t\t{\r\n\t\t\t\t\tplannerObj.CalcPath2RobotDeltaDis(plannerObj.path_array, local4navObj.cur_robot_state);\r\n\t\t\t\t\tindex4gravaton = plannerObj.CalcGravatonFromPath(plannerObj.path_array, plannerObj.path2robot_array, index4gravaton, plannerObj.gravaton,exist_gravaton_flag);\r\n\t\t\t\t\tat_gravaton_flag = false;\r\n\t\t\t\t\t\r\n\t\t\t\t\treplan_flag = false;\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcout<<\" Waiting for next path plan...\"<<endl;\r\n\t\t\t\t\r\n\t\t\t\tcout<<\" plannerObj.gravation.x = \"<<plannerObj.gravaton.x<<endl;\r\n\t\t\t\tcout<<\" plannerObj.gravation.y = \"<<plannerObj.gravaton.y<<endl;\t\t\r\n\t\t\t\t\r\n\t\t\t\tat_gravaton_flag = actionObj.ReachGravatonOK(&local4navObj.cur_robot_state[0],&plannerObj.gravaton.x, delta_robot2gravaton);\r\n\t\t\t\tcout<<\" delta_robot2gravaton = \"<<delta_robot2gravaton<<endl;\r\n\t\t\t\tcout<<\" at_gravaton_flag : \"<<at_gravaton_flag<<endl;\r\n\t\t\t\t\r\n\t\t\t\tif(local4navObj.approaching_flag == true)\r\n\t\t\t\t{\r\n\t\t\t\t\tplannerObj.gravaton.x = local4navObj.goal_state[0];\r\n\t\t\t\t\tplannerObj.gravaton.y = local4navObj.goal_state[1];\r\n\t\t\t\t\tplannerObj.gravaton.yaw = local4navObj.goal_state[2];\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\r\n\t\t\tlocal4navObj.CalcOffsetOfGoalAndRobot(local4navObj.cur_robot_state, &plannerObj.gravaton.x, &tmp_delta_dis, &tmp_robot2goal_yaw, &tmp_laser2goal_yaw);\r\n\r\n\t\t\tgoal_inlaser_flag = local4navObj.CalcGoalDirOfLaserView(&tmp_laser2goal_yaw, &local4navObj.cur_robot_state[2], &dir_goal_in_laser, &self_rotation_angle);\r\n\r\n\t\t\tfor(int i = 0; i < NUM_RAY4CA; i++)\r\n\t\t\t{\r\n\t\t\t\tscan4caObj.delta_phi_vec[i] = asin(D_SF / (*(scan4caObj.ptrScan4ca + i))) * RAD2DEG;\r\n\t\t\t\tscan4caObj.kp_phi_vec[i] = scan4caObj.CalcKpPhi(local4navObj.cur_robot_vel[0], *(scan4caObj.ptrScan4ca + i));\r\n\t\t\t\trange_num = floor(scan4caObj.delta_phi_vec[i] / RAY_RESOL4CA);\r\n\t\t\t\t\r\n\t\t\t\tscan4caObj.CalcPhiRange(i,range_num,&scan4caObj.phi_start_vec[i-1],&scan4caObj.phi_end_vec[i-1]);\r\n\r\n\t\t\t\ttmp_theta_laseray = i; \t\t\t// unit in degree\r\n\t\t\t\tscan4caObj.kaf_vec[i] = cos((tmp_theta_laseray - dir_goal_in_laser) * DEG2RAD);  //dir_goal_in_laser is 0~180 degree from right side\r\n\t\t\t\tscan4caObj.krf_vec[i] = scan4caObj.kp_phi_vec[i];\r\n\t\t\t}\r\n\r\n\t\t\tscan4caObj.CalcKrfTheta(scan4caObj.kp_phi_vec, scan4caObj.phi_start_vec, scan4caObj.phi_end_vec);\r\n\t\t\tscan4caObj.CalcCorrectedKrf();\r\n\t\t\tscan4caObj.CalcPassFcnAndFwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec);\r\n\t\t\tscan4caObj.CalcPassFcnAndBwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec);\r\n\r\n\t\t\tscan4caObj.angle_adj = scan4caObj.CalcAdjDir(scan4caObj.passfcn_vec,scan4caObj.max_passfcn_val, &scan4caObj.maxfcn_fwdbnd,&scan4caObj.maxfcn_bwdbnd);\r\n\t\t\t\t\r\n\t\t\tscan4caObj.CalcAlarmInAPF();\r\n\t\t\t\r\n\t\t\tif(goal_inlaser_flag == true)\r\n\t\t\t{\r\n\t\t\t\tlocal4navObj.apf_ctrl_output[0] = (V_MAX - V_MIN) * (scan4caObj.max_passfcn_val / D_M) + V_MIN;\r\n\t\t\t\tlocal4navObj.apf_ctrl_output[1] = scan4caObj.angle_adj / 200.0;\t\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tlocal4navObj.apf_ctrl_output[0] = 0.0;\r\n\t\t\t\tlocal4navObj.apf_ctrl_output[1] = 0.0;\t\r\n\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\tlocal4navObj.SatuateCmdVel(local4navObj.apf_ctrl_output,local4navObj.apf_ctrl_output+1);\r\n\r\n\t\t\tlocal4navObj.CalcEuclidDistance(local4navObj.cur_robot_state, local4navObj.goal_state, rt_r2g_dis);\r\n\t\t\t\r\n\t\t\tlocal4navObj.approaching_flag = local4navObj.ReachApprochingAreaOK(&rt_r2g_dis);\r\n\t\t\t\r\n\t\t\tif(tmp_delta_dis >= GOAL_NGHBORHD)\r\n\t\t\t{\r\n\t\t\t\tptr_action_cmd_t = actionObj.AdjustMovingDirAction(&local4navObj.cur_robot_state[2], &dir_goal_in_laser, &tmp_robot2goal_yaw, &turn_adj_flag);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\r\n\t\t\t}\r\n\r\n//\t\t\tcout<<\"turn_adj_flag: \" << turn_adj_flag <<endl;\r\n\t\t\t\r\n\t\t\tif(turn_adj_flag == 1)\r\n\t\t\t{\r\n\t\t\t\tif(local4navObj.approaching_flag == false)\r\n\t\t\t\t{\r\n\t\t\t\t\t*ptr_action_cmd_t = local4navObj.apf_ctrl_output[0];\r\n\t\t\t\t\t*(ptr_action_cmd_t + 1) = local4navObj.apf_ctrl_output[1];\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tptr_action_cmd_t = actionObj.ApproachingGoalAction(&local4navObj.cur_robot_state[0],&local4navObj.goal_state[0],&dir_goal_in_laser,&micro_adj_flag);\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tcout<<\"current_robot_state[0]\"<<local4navObj.cur_robot_state[0]<<endl;\r\n\t\t\tcout<<\"current_robot_state[1]\"<<local4navObj.cur_robot_state[1]<<endl;\r\n\t\t\tcout<<\"current_robot_state[2]\"<<local4navObj.cur_robot_state[2]<<endl;\r\n\t\t\t\r\n\t\t\tcout<<\"adj_angle: \"<< scan4caObj.angle_adj <<endl;\r\n\r\n\t\t\tcout<<\"tmp_delta_dis: \"<<tmp_delta_dis<<endl;\r\n\t\t\tcout<<\"tmp_robot2goal_yaw: \"<<tmp_robot2goal_yaw<<endl;\r\n\t\t\tcout<<\"tmp_laser2goal_yaw: \"<<tmp_laser2goal_yaw<<endl;\r\n\t\r\n\t\t\tcout<<\"dir_goal_in_laser: \"<<dir_goal_in_laser<<endl;\r\n\t\t\t\r\n\t\t\t//local4navObj.position_OK_flag = local4navObj.ReachGoalPositionOK(&tmp_delta_dis);\r\n\r\n\t\t\tlocal4navObj.SatuateCmdVel(ptr_action_cmd_t,ptr_action_cmd_t + 1);\r\n\r\n\t\t\tlocal4navObj.apf_cmd_vel.linear.x = *ptr_action_cmd_t;\r\n\t\t\tlocal4navObj.apf_cmd_vel.angular.z = *(ptr_action_cmd_t + 1);\r\n\t\t\t\r\n\t\t\tif(local4navObj.position_OK_flag == true)\r\n\t\t\t{\r\n\t\t\t\tlocal4navObj.apf_cmd_vel.linear.x = 0.0;\r\n\t\t\t\tlocal4navObj.apf_cmd_vel.angular.z = 0.0;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tcout<<\"approaching_flag: \" << local4navObj.approaching_flag <<endl;\r\n\t\t\tcout<<\"position_OK_flag: \" << local4navObj.position_OK_flag <<endl;\r\n\r\n\t\t\tlocal4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel); \r\n\t\t\tcout<<\"pub_linear_x: \" << local4navObj.apf_cmd_vel.linear.x <<endl;\r\n\t\t\tcout<<\"pub_angular_z: \" << local4navObj.apf_cmd_vel.angular.z <<endl;\r\n\r\n\t\t\tscan4caObj.ResetMaxPassValCnt();\r\n\t\t\r\n\t\t\tros::spinOnce();\r\n\t\t\tloop_rate.sleep();\r\n\t\t\tROS_INFO(\"------- end --------\");\r\n\t\t}\r\n\t}\r\n\r\n\tlocal4navObj.apf_cmd_vel.linear.x = 0.0;\r\n\tlocal4navObj.apf_cmd_vel.angular.z = 0.0;\r\n\r\n\tlocal4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel); \r\n\r\n\treturn 0;\t\r\n}\r\n\r\n\r\nvoid PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag)\r\n{\t\t\r\n\tplannerObj->ObtainPathArray(plannerObj->serviceClient, plannerObj->path_srv,start_pos,goal_pos,finish_flag);\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0edb951b0de348301f6389b09fd10fe65e660522", "size": 8339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "colibri_avoidence/src/follow_path_node.cpp", "max_stars_repo_name": "shevchenco123/28-Constellations", "max_stars_repo_head_hexsha": "bb6ba0360e29732cbe0a6b59cccd9d1f53e05309", "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": "colibri_avoidence/src/follow_path_node.cpp", "max_issues_repo_name": "shevchenco123/28-Constellations", "max_issues_repo_head_hexsha": "bb6ba0360e29732cbe0a6b59cccd9d1f53e05309", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-06-05T12:22:42.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-28T06:43:07.000Z", "max_forks_repo_path": "colibri_avoidence/src/follow_path_node.cpp", "max_forks_repo_name": "shevchenco123/28-Mansions", "max_forks_repo_head_hexsha": "bb6ba0360e29732cbe0a6b59cccd9d1f53e05309", "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.2231075697, "max_line_length": 186, "alphanum_fraction": 0.7073989687, "num_tokens": 2562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19089760236349335}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE CTCLossPlanTest\n#include <boost/test/unit_test.hpp>\n\n#include <poplibs_support/TestDevice.hpp>\n#include <popnn/CTCInference.hpp>\n#include <popnn/CTCLoss.hpp>\n\n#include <poputil/exceptions.hpp>\n\n// Common simple plan parameters\nconst poplar::Type inType = poplar::FLOAT;\nconst poplar::Type outType = poplar::FLOAT;\nconstexpr unsigned batchSize = 10;\nconstexpr unsigned maxTime = 40;\nconstexpr unsigned maxLabelLength = 10;\nconstexpr unsigned numClasses = 4;\n\nBOOST_AUTO_TEST_CASE(SimplePlan) {\n  auto device = createTestDeviceFullSize(TEST_TARGET, 1);\n  auto &target = device.getTarget();\n  poplar::Graph graph(target);\n\n  // Finds reasonably sized plan\n  popnn::ctc::plan(graph, inType, outType, batchSize, maxTime, maxLabelLength,\n                   numClasses, {{\"availableMemoryProportion\", \"0.9\"}});\n}\n\nBOOST_AUTO_TEST_CASE(SimplePlanWithMemoryBound) {\n  auto device = createTestDeviceFullSize(TEST_TARGET, 1);\n  auto &target = device.getTarget();\n  poplar::Graph graph(target);\n\n  // Can't find plan when no available memory\n  BOOST_CHECK_THROW(popnn::ctc::plan(graph, inType, outType, batchSize, maxTime,\n                                     maxLabelLength, numClasses,\n                                     {{\"availableMemoryProportion\", \"0.0\"}}),\n                    poputil::poplibs_error);\n}\n\nBOOST_AUTO_TEST_CASE(SimplePlanWithConstrainedVar) {\n  auto device = createTestDeviceFullSize(TEST_TARGET, 1);\n  auto &target = device.getTarget();\n  poplar::Graph graph(target);\n\n  // Finds plan with a resonable constraint\n  popnn::ctc::plan(\n      graph, inType, outType, batchSize, maxTime, maxLabelLength, numClasses,\n      {{\"planConstraints\", R\"delim({\"parallel\": {\"time\": 1}})delim\"}});\n\n  // Can't find plan with un-satisfiable constraint\n  BOOST_CHECK_THROW(\n      popnn::ctc::plan(\n          graph, inType, outType, batchSize, maxTime, maxLabelLength,\n          numClasses,\n          {{\"planConstraints\", R\"delim({\"parallel\": {\"batch\": 0}})delim\"}}),\n      poputil::poplibs_error);\n\n  // Throws on invalid name\n  BOOST_CHECK_THROW(\n      popnn::ctc::plan(\n          graph, inType, outType, batchSize, maxTime, maxLabelLength,\n          numClasses,\n          {{\"planConstraints\", R\"delim({\"parallel\": {\"xyz\": 0}})delim\"}}),\n      poputil::poplibs_error);\n}\n\nBOOST_AUTO_TEST_CASE(WrongPlanType) {\n  auto device = createTestDeviceFullSize(TEST_TARGET, 1);\n  auto &target = device.getTarget();\n  poplar::Graph graph(target);\n\n  // Given an inference plan\n  auto invalidPlan = popnn::ctc_infer::plan(graph, poplar::FLOAT, 1, 10, 5, 5);\n\n  // When we call the CTC Loss API, Then we expect exceptions thrown\n  BOOST_CHECK_THROW(\n      popnn::ctc::createDataInput(graph, poplar::FLOAT, 1, 10, 5, invalidPlan),\n      poputil::poplibs_error);\n  BOOST_CHECK_THROW(\n      popnn::ctc::createLabelsInput(graph, poplar::FLOAT, 1, 10, invalidPlan),\n      poputil::poplibs_error);\n\n  poplar::program::Sequence prog{};\n  BOOST_CHECK_THROW(\n      popnn::ctc::calcLossAndGradientLogProbabilities(\n          graph, poplar::FLOAT, {}, {}, {}, {}, prog, 0, invalidPlan),\n      poputil::poplibs_error);\n  BOOST_CHECK_THROW(popnn::ctc::calcLossAndGradientLogits(graph, poplar::FLOAT,\n                                                          {}, {}, {}, {}, prog,\n                                                          0, invalidPlan),\n                    poputil::poplibs_error);\n}\n", "meta": {"hexsha": "d8879497171639fab595c3e86c10985e8768fe5e", "size": 3457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popnn/CTCLossPlanTest.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": "tests/popnn/CTCLossPlanTest.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": "tests/popnn/CTCLossPlanTest.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": 36.7765957447, "max_line_length": 80, "alphanum_fraction": 0.6598206537, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19089558572865675}}
{"text": "//\n// Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can\n// be found in the LICENSE.txt file.\n//\n\n#include \"HDRImage.h\"\n#include \"DitherMatrix256.h\"    // for dither_matrix256\n#include <ImfArray.h>            // for Array2D\n#include <ImfRgbaFile.h>         // for RgbaInputFile, RgbaOutputFile\n#include <ImathBox.h>            // for Box2i\n#include <ImfTestFile.h>         // for isOpenExrFile\n#include <ImathVec.h>            // for Vec2\n#include <ImfRgba.h>             // for Rgba, RgbaChannels::WRITE_RGBA\n#include <ctype.h>               // for tolower\n#include <half.h>                // for half\n#include <stdlib.h>              // for abs\n#include <algorithm>             // for nth_element, transform\n#include <cmath>                 // for floor, pow, exp, ceil, round, sqrt\n#include <exception>             // for exception\n#include <functional>            // for pointer_to_unary_function, function\n#include <stdexcept>             // for runtime_error, out_of_range\n#include <string>                // for allocator, operator==, basic_string\n#include <vector>                // for vector\n#include \"Common.h\"              // for lerp, mod, clamp, getExtension\n#include \"Colorspace.h\"\n#include \"ParallelFor.h\"\n#include \"Timer.h\"\n#include <Eigen/Dense>\n#include <spdlog/spdlog.h>\n\n// these pragmas ignore warnings about unused static functions\n#if defined(__clang__)\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-function\"\n#elif defined(__GNUC__) || defined(__GNUG__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#elif defined(_MSC_VER)\n#pragma warning (push, 0)\n#endif\n\n// since NanoVG includes an old version of stb_image, we declare it static here\n#define STB_IMAGE_STATIC\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n#undef STB_IMAGE_IMPLEMENTATION\n\n#define TINY_DNG_LOADER_IMPLEMENTATION\n#include \"tiny_dng_loader.h\"\n\n#if defined(__clang__)\n#pragma clang diagnostic pop\n#elif defined(__GNUC__) || defined(__GNUG__)\n#pragma GCC diagnostic pop\n#elif defined(_MSC_VER)\n#pragma warning (pop)\n#endif\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"     // for stbi_write_bmp, stbi_write_hdr, stbi...\n\n#include \"PFM.h\"\n#include \"PPM.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\n// local functions\nnamespace\n{\n\ninline unsigned short endianSwap(unsigned short val);\nvoid decode12BitToFloat(vector<float> &image, unsigned char *data, int width, int height, bool swapEndian);\nvoid decode14BitToFloat(vector<float> &image, unsigned char *data, int width, int height, bool swapEndian);\nvoid decode16BitToFloat(vector<float> &image, unsigned char *data, int width, int height, bool swapEndian);\nvoid printImageInfo(const tinydng::DNGImage & image);\nHDRImage develop(vector<float> & raw,\n                 const tinydng::DNGImage & param1,\n                 const tinydng::DNGImage & param2);\nvoid copyPixelsFromArray(HDRImage & img, float * data, int w, int h, int n, bool convertToLinear)\n{\n\tif (n != 3 && n != 4)\n\t\tthrow runtime_error(\"Only 3- and 4-channel images are supported.\");\n\n\t// for every pixel in the image\n\tparallel_for(0, h, [&img,w,n,data,convertToLinear](int y)\n\t{\n\t\tfor (int x = 0; x < w; ++x)\n\t\t{\n\t\t\tColor4 c(data[n * (x + y * w) + 0],\n\t\t\t         data[n * (x + y * w) + 1],\n\t\t\t         data[n * (x + y * w) + 2],\n\t\t\t         (n == 3) ? 1.f : data[4 * (x + y * w) + 3]);\n\t\t\timg(x, y) = convertToLinear ? SRGBToLinear(c) : c;\n\t\t}\n\t});\n}\n\nbool isSTBImage(const string & filename)\n{\n\tFILE *f = stbi__fopen(filename.c_str(), \"rb\");\n\tif (!f)\n\t\treturn false;\n\n\tstbi__context s;\n\tstbi__start_file(&s,f);\n\n\t// try stb library first\n\tif (stbi__jpeg_test(&s) ||\n\t\tstbi__png_test(&s) ||\n\t\tstbi__bmp_test(&s) ||\n\t\tstbi__gif_test(&s) ||\n\t\tstbi__psd_test(&s) ||\n\t\tstbi__pic_test(&s) ||\n\t\tstbi__pnm_test(&s) ||\n\t\tstbi__hdr_test(&s) ||\n\t\tstbi__tga_test(&s))\n\t{\n\t\tfclose(f);\n\t\treturn true;\n\t}\n\n\tfclose(f);\n\treturn false;\n}\n\n} // namespace\n\n\nbool HDRImage::load(const string & filename)\n{\n\tauto console = spdlog::get(\"console\");\n    string errors;\n\tstring extension = getExtension(filename);\n\ttransform(extension.begin(),\n\t          extension.end(),\n\t          extension.begin(),\n\t          ::tolower);\n\n    int n, w, h;\n\n\t// try stb library first\n\tif (isSTBImage(filename))\n\t{\n\t\t// stbi doesn't do proper srgb, but uses gamma=2.2 instead, so override it.\n\t\t// we'll do our own srgb correction\n\t\tstbi_ldr_to_hdr_scale(1.0f);\n\t\tstbi_ldr_to_hdr_gamma(1.0f);\n\n\t\tfloat * float_data = stbi_loadf(filename.c_str(), &w, &h, &n, 4);\n\t\tif (float_data)\n\t\t{\n\t\t\tresize(w, h);\n\t\t\tbool convertToLinear = !stbi_is_hdr(filename.c_str());\n\t\t\tTimer timer;\n\t\t\tcopyPixelsFromArray(*this, float_data, w, h, 4, convertToLinear);\n\t\t\tconsole->debug(\"Copying image data took: {} seconds.\", (timer.elapsed()/1000.f));\n\n\t\t\tstbi_image_free(float_data);\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\terrors += string(\"\\t\") + stbi_failure_reason() + \"\\n\";\n\t\t}\n\t}\n\n\n    // then try pfm\n\tif (isPFMImage(filename.c_str()))\n    {\n\t    float * float_data = 0;\n\t    try\n\t    {\n\t\t    w = 0;\n\t\t    h = 0;\n\n\t\t    if ((float_data = loadPFMImage(filename.c_str(), &w, &h, &n)))\n\t\t    {\n\t\t\t    if (n == 3)\n\t\t\t    {\n\t\t\t\t    resize(w, h);\n\n\t\t\t\t    Timer timer;\n\t\t\t\t    // convert 3-channel pfm data to 4-channel internal representation\n\t\t\t\t    copyPixelsFromArray(*this, float_data, w, h, 3, false);\n\t\t\t\t    console->debug(\"Copying image data took: {} seconds.\", (timer.elapsed() / 1000.f));\n\n\t\t\t\t    delete [] float_data;\n\t\t\t\t    return true;\n\t\t\t    }\n\t\t\t    else\n\t\t\t\t    throw runtime_error(\"Only 3-channel PFMs are currently supported.\");\n\t\t\t    return true;\n\t\t    }\n\t\t    else\n\t\t\t    throw runtime_error(\"Could not load PFM image.\");\n\t    }\n\t    catch (const exception &e)\n\t    {\n\t\t    delete [] float_data;\n\t\t    resize(0, 0);\n\t\t    errors += string(\"\\t\") + e.what() + \"\\n\";\n\t    }\n    }\n\n    // next try exrs\n\tif (Imf::isOpenExrFile(filename.c_str()))\n    {\n\t    try\n\t    {\n\t\t    // FIXME: the threading below seems to cause issues, but shouldn't.\n\t\t    // turning off for now\n\t\t    Imf::setGlobalThreadCount(thread::hardware_concurrency());\n\t\t    Timer timer;\n\n\t\t    Imf::RgbaInputFile file(filename.c_str());\n\t\t    Imath::Box2i dw = file.dataWindow();\n\n\t\t    w = dw.max.x - dw.min.x + 1;\n\t\t    h = dw.max.y - dw.min.y + 1;\n\n\t\t    Imf::Array2D<Imf::Rgba> pixels(h, w);\n\n\t\t    file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y * w, 1, w);\n\t\t    file.readPixels(dw.min.y, dw.max.y);\n\n\t\t    console->debug(\"Reading EXR image took: {} seconds.\", (timer.lap() / 1000.f));\n\n\t\t    resize(w, h);\n\n\t\t    // copy pixels over to the Image\n\t\t    parallel_for(0, h, [this, w, &pixels](int y)\n\t\t    {\n\t\t\t    for (int x = 0; x < w; ++x)\n\t\t\t    {\n\t\t\t\t    const Imf::Rgba &p = pixels[y][x];\n\t\t\t\t    (*this)(x, y) = Color4(p.r, p.g, p.b, p.a);\n\t\t\t    }\n\t\t    });\n\n\t\t    console->debug(\"Copying EXR image data took: {} seconds.\", (timer.lap() / 1000.f));\n\t\t    return true;\n\t    }\n\t    catch (const exception &e)\n\t    {\n\t\t    resize(0, 0);\n\t\t    errors += string(\"\\t\") + e.what() + \"\\n\";\n\t    }\n    }\n\n\ttry\n\t{\n\t\tvector<tinydng::DNGImage> images;\n\t\t{\n\t\t\tstd::string err;\n\t\t\tvector<tinydng::FieldInfo> customFields;\n\t\t\tbool ret = tinydng::LoadDNG(filename.c_str(), customFields, &images, &err);\n\n\t\t\tif (ret == false)\n\t\t\t\tthrow runtime_error(\"Failed to load DNG. \" + err);\n\t\t}\n\n\t\t// DNG files sometimes only store the orientation in one of the images,\n\t\t// instead of all of them. find any set value and save it\n\t\tint orientation = 0;\n\t\tfor (size_t i = 0; i < images.size(); i++)\n\t\t{\n\t\t\tconsole->debug(\"Image [{}] size = {} x {}.\", i, images[i].width, images[i].height);\n\t\t\tconsole->debug(\"Image [{}] orientation = {}\", i, images[i].orientation);\n\t\t\tif (images[i].orientation != 0)\n\t\t\t\torientation = images[i].orientation;\n\t\t}\n\n\t\t// Find largest image based on width.\n\t\tsize_t imageIndex = size_t(-1);\n\t\t{\n\t\t\tsize_t largest = 0;\n\t\t\tint largestWidth = images[0].width;\n\t\t\tfor (size_t i = 0; i < images.size(); i++)\n\t\t\t{\n\t\t\t\tif (largestWidth < images[i].width)\n\t\t\t\t{\n\t\t\t\t\tlargest = i;\n\t\t\t\t\tlargestWidth = images[i].width;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\timageIndex = largest;\n\t\t}\n\t\ttinydng::DNGImage & image = images[imageIndex];\n\n\n\t\tconsole->debug(\"\\nLargest image within DNG:\");\n\t\tprintImageInfo(image);\n\t\tconsole->debug(\"\\nLast image within DNG:\");\n\t\tprintImageInfo(images.back());\n\n\t\tconsole->debug(\"Loading image [{}].\", imageIndex);\n\n\t\tw = image.width;\n\t\th = image.height;\n\n\t\t// Convert to float.\n\t\tvector<float> hdr;\n\t\tbool endianSwap = false;        // TODO\n\n\t\tint spp = image.samples_per_pixel;\n\t\tif (image.bits_per_sample == 12)\n\t\t\tdecode12BitToFloat(hdr, &(image.data.at(0)), w, h * spp, endianSwap);\n\t\telse if (image.bits_per_sample == 14)\n\t\t\tdecode14BitToFloat(hdr, &(image.data.at(0)), w, h * spp, endianSwap);\n\t\telse if (image.bits_per_sample == 16)\n\t\t\tdecode16BitToFloat(hdr, &(image.data.at(0)), w, h * spp, endianSwap);\n\t\telse\n\t\t\tthrow runtime_error(\"Error loading DNG: Unsupported bits_per_sample : \" + to_string(spp));\n\n\t\tfloat invScale = 1.0f / static_cast<float>((1 << image.bits_per_sample));\n\t\tif (spp == 3)\n\t\t{\n\t\t\tconsole->debug(\"Decoding a 3 sample-per-pixel DNG image.\");\n\t\t\t// normalize\n\t\t\tparallel_for(0, hdr.size(), [&hdr,invScale](int i)\n\t\t\t{\n\t\t\t\thdr[i] *= invScale;\n\t\t\t});\n\n\t\t\t// Create color image & normalize intensity.\n\t\t\tresize(w, h);\n\n\t\t\tTimer timer;\n\t\t\t// normalize\n\t\t\tparallel_for(0, h, [this,w,invScale,&hdr](int y)\n\t\t\t{\n\t\t\t\tfor (int x = 0; x < w; ++x)\n\t\t\t\t{\n\t\t\t\t\tint index = 3 * y * w + x;\n\t\t\t\t\t(*this)(x, y) = Color4(hdr[index] * invScale + 0,\n\t\t\t\t\t                       hdr[index] * invScale + 1,\n\t\t\t\t\t                       hdr[index] * invScale + 2, 1.0f);\n\t\t\t\t}\n\t\t\t});\n\t\t\tconsole->debug(\"Copying image data took: {} seconds.\", (timer.elapsed()/1000.f));\n\t\t}\n\t\telse if (spp == 1)\n\t\t{\n\t\t\t// Create grayscale image & normalize intensity.\n\t\t\tconsole->debug(\"Decoding a 1 sample-per-pixel DNG image.\");\n\t\t\tTimer timer;\n\t\t\t*this = develop(hdr, image, images.back());\n\t\t\tconsole->debug(\"Copying image data took: {} seconds.\", (timer.elapsed()/1000.f));\n\t\t}\n\t\telse\n\t\t\tthrow runtime_error(\"Error loading DNG: Unsupported samples per pixel: \" + to_string(spp));\n\n\n\t\tint startRow = clamp(image.active_area[1], 0, w);\n\t\tint endRow = clamp(image.active_area[3], 0, w);\n\t\tint startCol = clamp(image.active_area[0], 0, h);\n\t\tint endCol = clamp(image.active_area[2], 0, h);\n\n\t\t*this = block(startRow, startCol,\n\t\t              endRow-startRow,\n\t\t              endCol-startCol).eval();\n\n\t\tenum Orientations\n\t\t{\n\t\t\tORIENTATION_TOPLEFT = 1,\n\t\t\tORIENTATION_TOPRIGHT = 2,\n\t\t\tORIENTATION_BOTRIGHT = 3,\n\t\t\tORIENTATION_BOTLEFT = 4,\n\t\t\tORIENTATION_LEFTTOP = 5,\n\t\t\tORIENTATION_RIGHTTOP = 6,\n\t\t\tORIENTATION_RIGHTBOT = 7,\n\t\t\tORIENTATION_LEFTBOT = 8\n\t\t};\n\n\t\t// now rotate image based on stored orientation\n\t\tswitch (orientation)\n\t\t{\n\t\t\tcase ORIENTATION_TOPRIGHT: *this = flippedHorizontal(); break;\n\t\t\tcase ORIENTATION_BOTRIGHT: *this = flippedVertical().flippedHorizontal(); break;\n\t\t\tcase ORIENTATION_BOTLEFT : *this = flippedVertical(); break;\n\t\t\tcase ORIENTATION_LEFTTOP : *this = rotated90CCW().flippedVertical(); break;\n\t\t\tcase ORIENTATION_RIGHTTOP: *this = rotated90CW(); break;\n\t\t\tcase ORIENTATION_RIGHTBOT: *this = rotated90CW().flippedVertical(); break;\n\t\t\tcase ORIENTATION_LEFTBOT : *this = rotated90CCW(); break;\n\t\t\tdefault: break;// none (0), or ORIENTATION_TOPLEFT\n\t\t}\n\n\t\treturn true;\n\t}\n\tcatch (const exception &e)\n\t{\n\t\tresize(0,0);\n\t\t// only report errors to the user if the extension was actually dng\n\t\tif (extension == \"dng\")\n\t\t\terrors += string(\"\\t\") + e.what() + \"\\n\";\n\t}\n\n    console->error(\"ERROR: Unable to read image file \\\"{}\\\":\\n{}\", filename, errors);\n\n    return false;\n}\n\n\nshared_ptr<HDRImage> loadImage(const string & filename)\n{\n\tshared_ptr<HDRImage> ret = make_shared<HDRImage>();\n\tif (ret->load(filename))\n\t\treturn ret;\n\treturn nullptr;\n}\n\n\nbool HDRImage::save(const string & filename,\n                    float gain, float gamma,\n                    bool sRGB, bool dither) const\n{\n\tauto console = spdlog::get(\"console\");\n    string extension = getExtension(filename);\n\n    transform(extension.begin(),\n              extension.end(),\n              extension.begin(),\n              ::tolower);\n\n    auto img = this;\n    HDRImage imgCopy;\n\n    bool hdrFormat = (extension == \"hdr\") || (extension == \"pfm\") || (extension == \"exr\");\n\n    // if we need to tonemap, then modify a copy of the image data\n    if (gain != 1.0f || sRGB || gamma != 1.0f)\n    {\n        Color4 gainC = Color4(gain, gain, gain, 1.0f);\n        Color4 gammaC = Color4(1.0f / gamma, 1.0f / gamma, 1.0f / gamma, 1.0f);\n\n        imgCopy = *this;\n        img = &imgCopy;\n\n        if (gain != 1.0f)\n            imgCopy *= gainC;\n\n        // only do gamma or sRGB tonemapping if we are saving to an LDR format\n        if (!hdrFormat)\n        {\n            if (sRGB)\n                imgCopy = imgCopy.unaryExpr(ptr_fun((Color4 (*)(const Color4 &)) LinearToSRGB));\n            else if (gamma != 1.0f)\n                imgCopy = imgCopy.pow(gammaC);\n        }\n    }\n\n    if (extension == \"hdr\")\n        return stbi_write_hdr(filename.c_str(), width(), height(), 4, (const float *) img->data()) != 0;\n    else if (extension == \"pfm\")\n        return writePFMImage(filename.c_str(), width(), height(), 4, (const float *) img->data()) != 0;\n    else if (extension == \"exr\")\n    {\n        try\n        {\n            Imf::setGlobalThreadCount(thread::hardware_concurrency());\n            Imf::RgbaOutputFile file(filename.c_str(), width(), height(), Imf::WRITE_RGBA);\n            Imf::Array2D<Imf::Rgba> pixels(height(), width());\n\n            Timer timer;\n            // copy image data over to Rgba pixels\n            parallel_for(0, height(), [this,img,&pixels](int y)\n            {\n                for (int x = 0; x < width(); ++x)\n                {\n                    Imf::Rgba &p = pixels[y][x];\n                    Color4 c = (*img)(x, y);\n                    p.r = c[0];\n                    p.g = c[1];\n                    p.b = c[2];\n                    p.a = c[3];\n                }\n            });\n            console->debug(\"Copying pixel data took: {} seconds.\", (timer.lap()/1000.f));\n\n            file.setFrameBuffer(&pixels[0][0], 1, width());\n            file.writePixels(height());\n\n            console->debug(\"Writing EXR image took: {} seconds.\", (timer.lap()/1000.f));\n\t\t\treturn true;\n        }\n        catch (const exception &e)\n        {\n            console->error(\"ERROR: Unable to write image file \\\"{}\\\": {}\", filename, e.what());\n            return false;\n        }\n    }\n    else\n    {\n        // convert floating-point image to 8-bit per channel with dithering\n        vector<unsigned char> data(size()*3, 0);\n\n        Timer timer;\n        // convert 3-channel pfm data to 4-channel internal representation\n        parallel_for(0, height(), [this,img,&data,dither](int y)\n        {\n            for (int x = 0; x < width(); ++x)\n            {\n                Color4 c = (*img)(x, y);\n                if (dither)\n                {\n                    int xmod = x % 256;\n                    int ymod = y % 256;\n                    float ditherValue = (dither_matrix256[xmod + ymod * 256] / 65536.0f - 0.5f) / 255.0f;\n                    c += Color4(Color3(ditherValue), 0.0f);\n                }\n\n                // convert to [0-255] range\n                c = (c * 255.0f).max(0.0f).min(255.0f);\n\n                data[3 * x + 3 * y * width() + 0] = (unsigned char) c[0];\n                data[3 * x + 3 * y * width() + 1] = (unsigned char) c[1];\n                data[3 * x + 3 * y * width() + 2] = (unsigned char) c[2];\n            }\n        });\n        console->debug(\"Tonemapping to 8bit took: {} seconds.\", (timer.elapsed()/1000.f));\n\n        if (extension == \"ppm\")\n            return writePPMImage(filename.c_str(), width(), height(), 3, &data[0]);\n        else if (extension == \"png\")\n            return stbi_write_png(filename.c_str(), width(), height(),\n                                  3, &data[0], sizeof(unsigned char)*width()*3) != 0;\n        else if (extension == \"bmp\")\n            return stbi_write_bmp(filename.c_str(), width(), height(), 3, &data[0]) != 0;\n        else if (extension == \"tga\")\n            return stbi_write_tga(filename.c_str(), width(), height(), 3, &data[0]) != 0;\n        else if (extension == \"jpg\" || extension == \"jpeg\")\n            return stbi_write_jpg(filename.c_str(), width(), height(), 3, &data[0], 100) != 0;\n        else\n            throw invalid_argument(\"Could not determine desired file type from extension.\");\n    }\n}\n\n\n// local functions\nnamespace\n{\n\n\n// Taken from http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html\nconst Matrix3f XYZD65TosRGB(\n\t(Matrix3f() << 3.2406f, -1.5372f, -0.4986f,\n\t\t-0.9689f,  1.8758f,  0.0415f,\n\t\t0.0557f, -0.2040f,  1.0570f).finished());\n\nconst Matrix3f XYZD50ToXYZD65(\n\t(Matrix3f() << 0.9555766f, -0.0230393f, 0.0631636f,\n\t\t-0.0282895f,  1.0099416f, 0.0210077f,\n\t\t0.0122982f, -0.0204830f, 1.3299098f).finished());\n\n// Taken from http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html\nconst Matrix3f XYZD50TosRGB(\n\t(Matrix3f() << 3.2404542f, -1.5371385f, -0.4985314f,\n\t\t-0.9692660f,  1.8760108f,  0.0415560f,\n\t\t0.0556434f, -0.2040259f,  1.0572252).finished());\n\nMatrix3f computeCameraToXYZD50(const tinydng::DNGImage &param)\n{\n\t//\n\t// The full DNG color-correction model is described in the\n\t// \"Mapping Camera Color Space to CIE XYZ Space\" section of the DNG spec.\n\t//\n\t// Let n be the dimensionality of the camera color space (usually 3 or 4).\n\t// Let CM be the n-by-3 matrix interpolated from the ColorMatrix1 and ColorMatrix2 tags.\n\t// Let CC be the n-by-n matrix interpolated from the CameraCalibration1 and CameraCalibration2 tags (or identity matrices, if the signatures don't match).\n\t// Let AB be the n-by-n matrix, which is zero except for the diagonal entries, which are defined by the AnalogBalance tag.\n\t// Let RM be the 3-by-n matrix interpolated from the ReductionMatrix1 and ReductionMatrix2 tags.\n\t// Let FM be the 3-by-n matrix interpolated from the ForwardMatrix1 and ForwardMatrix2 tags.\n\n\t// TODO: the color correction code below is not quite correct\n\n\t// if the ForwardMatrix is included:\n\tif (false)//param.has_forward_matrix2)\n\t{\n\t\tauto FM((Matrix3f() << param.forward_matrix2[0][0], param.forward_matrix2[0][1], param.forward_matrix2[0][2],\n\t\t\t                   param.forward_matrix2[1][0], param.forward_matrix2[1][1], param.forward_matrix2[1][2],\n\t\t\t\t\t\t\t   param.forward_matrix2[2][0], param.forward_matrix2[2][1], param.forward_matrix2[2][2]).finished());\n\t\tauto CC((Matrix3f() << param.camera_calibration2[0][0], param.camera_calibration2[0][1], param.camera_calibration2[0][2],\n\t\t\t\t\t\t\t   param.camera_calibration2[1][0], param.camera_calibration2[1][1], param.camera_calibration2[1][2],\n\t\t\t\t\t\t\t   param.camera_calibration2[2][0], param.camera_calibration2[2][1], param.camera_calibration2[2][2]).finished());\n\t\tauto AB = Vector3f(param.analog_balance[0], param.analog_balance[1], param.analog_balance[2]).asDiagonal();\n\n\t\tVector3f CameraNeutral(param.as_shot_neutral[0],\n\t\t                       param.as_shot_neutral[1],\n\t\t                       param.as_shot_neutral[2]);\n\t\tVector3f ReferenceNeutral = (AB * CC).inverse() * CameraNeutral;\n\t\tauto D = (ReferenceNeutral.asDiagonal()).inverse();\n\t\tauto CameraToXYZ = FM * D * (AB * CC).inverse();\n\n\t\treturn CameraToXYZ;\n\t}\n\telse\n\t{\n\t\tauto CM((Matrix3f() << param.color_matrix2[0][0], param.color_matrix2[0][1], param.color_matrix2[0][2],\n\t\t\t                   param.color_matrix2[1][0], param.color_matrix2[1][1], param.color_matrix2[1][2],\n\t\t\t\t               param.color_matrix2[2][0], param.color_matrix2[2][1], param.color_matrix2[2][2]).finished());\n\n\t\tauto CameraToXYZ = CM.inverse();\n\n\t\treturn CameraToXYZ;\n\n\t}\n}\n\n\nHDRImage develop(vector<float> & raw,\n                 const tinydng::DNGImage & param1,\n                 const tinydng::DNGImage & param2)\n{\n\tTimer timer;\n\n\tint width = param1.width;\n\tint height = param1.height;\n\tint blackLevel = param1.black_level[0];\n\tint whiteLevel = param1.white_level[0];\n\tVector2i redOffset(param1.active_area[1] % 2, param1.active_area[0] % 2);\n\n\tHDRImage developed(width, height);\n\n\tMatrix3f CameraToXYZD50 = computeCameraToXYZD50(param2);\n\tMatrix3f CameraTosRGB = XYZD50TosRGB * CameraToXYZD50;\n\n\t// Chapter 5 of DNG spec\n\t// Map raw values to linear reference values (i.e. adjust for black and white level)\n\t//\n\t// we also apply white balance before demosaicing here because it increases the\n\t// correlation between the color channels and reduces artifacts\n\tVector3f wb(param2.as_shot_neutral[0], param2.as_shot_neutral[1], param2.as_shot_neutral[2]);\n\tconst float invScale = 1.0f / (whiteLevel - blackLevel);\n\tparallel_for(0, developed.height(), [&developed,&raw,blackLevel,invScale,&wb](int y)\n\t{\n\t\tfor (int x = 0; x < developed.width(); x++)\n\t\t{\n\t\t\tfloat v = clamp((raw[y * developed.width() + x] - blackLevel)*invScale, 0.f, 1.f);\n\t\t\tVector3f rgb = Vector3f(v,v,v);\n\t\t\trgb = rgb.cwiseQuotient(wb);\n\t\t\tdeveloped(x,y) = Color4(rgb(0),rgb(1),rgb(2),1.f);\n\t\t}\n\t});\n\n\t// demosaic\n//\tdeveloped.demosaicLinear(redOffset);\n//\tdeveloped.demosaicGreenGuidedLinear(redOffset);\n//\tdeveloped.demosaicMalvar(redOffset);\n\tdeveloped.demosaicAHD(redOffset, XYZD50ToXYZD65 * CameraToXYZD50);\n\n\t// color correction\n\t// also undo the white balance since the color correction matrix already includes it\n\tparallel_for(0, developed.height(), [&developed,&CameraTosRGB,&wb](int y)\n\t{\n\t\tfor (int x = 0; x < developed.width(); x++)\n\t\t{\n\t\t\tVector3f rgb(developed(x,y).r, developed(x,y).g, developed(x,y).b);\n\t\t\trgb = rgb.cwiseProduct(wb);\n\t\t\tVector3f sRGB = CameraTosRGB * rgb;\n\t\t\tdeveloped(x,y) = Color4(sRGB.x(),sRGB.y(),sRGB.z(),1.f);\n\t\t}\n\t});\n\n\tspdlog::get(\"console\")->debug(\"Developing DNG image took {} seconds.\", (timer.elapsed()/1000.f));\n\treturn developed;\n}\n\n\ninline unsigned short endianSwap(unsigned short val)\n{\n\tunsigned short ret;\n\n\tunsigned char *buf = reinterpret_cast<unsigned char *>(&ret);\n\n\tunsigned short x = val;\n\tbuf[1] = static_cast<unsigned char>(x);\n\tbuf[0] = static_cast<unsigned char>(x >> 8);\n\n\treturn ret;\n}\n\n\n// The decode functions below are adapted from syoyo's dng2exr, in the tinydng library within the\n// ext subfolder\n\n//\n// Decode 12bit integer image into floating point HDR image\n//\nvoid decode12BitToFloat(vector<float> &image, unsigned char *data, int width, int height, bool swapEndian)\n{\n\tTimer timer;\n\n\tint offsets[2][2] = {{0, 1}, {1, 2}};\n\tint bitShifts[2] = {4, 0};\n\n\timage.resize(static_cast<size_t>(width * height));\n\n\tparallel_for(0, height, [&image,width,&offsets,&bitShifts,data,swapEndian](int y)\n\t{\n\t\tfor (int x = 0; x < width; x++)\n\t\t{\n\t\t\tunsigned char buf[3];\n\n\t\t\t// Calculate load address for 12bit pixel(three 8 bit pixels)\n\t\t\tint n = int(y * width + x);\n\n\t\t\t// 24 = 12bit * 2 pixel, 8bit * 3 pixel\n\t\t\tint n2 = n % 2;           // used for offset & bitshifts\n\t\t\tint addr3 = (n / 2) * 3;  // 8bit pixel pos\n\t\t\tint odd = (addr3 % 2);\n\n\t\t\tint bit_shift;\n\t\t\tbit_shift = bitShifts[n2];\n\n\t\t\tint offset[2];\n\t\t\toffset[0] = offsets[n2][0];\n\t\t\toffset[1] = offsets[n2][1];\n\n\t\t\tif (swapEndian)\n\t\t\t{\n\t\t\t\t// load with short byte swap\n\t\t\t\tif (odd)\n\t\t\t\t{\n\t\t\t\t\tbuf[0] = data[addr3 - 1];\n\t\t\t\t\tbuf[1] = data[addr3 + 2];\n\t\t\t\t\tbuf[2] = data[addr3 + 1];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbuf[0] = data[addr3 + 1];\n\t\t\t\t\tbuf[1] = data[addr3 + 0];\n\t\t\t\t\tbuf[2] = data[addr3 + 3];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbuf[0] = data[addr3 + 0];\n\t\t\t\tbuf[1] = data[addr3 + 1];\n\t\t\t\tbuf[2] = data[addr3 + 2];\n\t\t\t}\n\t\t\tunsigned int b0 = static_cast<unsigned int>(buf[offset[0]] & 0xff);\n\t\t\tunsigned int b1 = static_cast<unsigned int>(buf[offset[1]] & 0xff);\n\n\t\t\tunsigned int val = (b0 << 8) | b1;\n\t\t\tval = 0xfff & (val >> bit_shift);\n\n\t\t\timage[static_cast<size_t>(y * width + x)] = static_cast<float>(val);\n\t\t}\n\t});\n\n\tspdlog::get(\"console\")->debug(\"decode12BitToFloat took: {} seconds.\", (timer.lap() / 1000.f));\n}\n\n//\n// Decode 14bit integer image into floating point HDR image\n//\nvoid decode14BitToFloat(vector<float> &image, unsigned char *data, int width, int height, bool swapEndian)\n{\n\tTimer timer;\n\n\tint offsets[4][3] = {{0, 0, 1}, {1, 2, 3}, {3, 4, 5}, {5, 5, 6}};\n\tint bitShifts[4] = {2, 4, 6, 0};\n\n\timage.resize(static_cast<size_t>(width * height));\n\n\tparallel_for(0, height, [&image,width,&offsets,&bitShifts,data,swapEndian](int y)\n\t{\n\t\tfor (int x = 0; x < width; x++)\n\t\t{\n\t\t\tunsigned char buf[7];\n\n\t\t\t// Calculate load address for 14bit pixel(three 8 bit pixels)\n\t\t\tint n = int(y * width + x);\n\n\t\t\t// 56 = 14bit * 4 pixel, 8bit * 7 pixel\n\t\t\tint n4 = n % 4;           // used for offset & bitshifts\n\t\t\tint addr7 = (n / 4) * 7;  // 8bit pixel pos\n\t\t\tint odd = (addr7 % 2);\n\n\t\t\tint offset[3];\n\t\t\toffset[0] = offsets[n4][0];\n\t\t\toffset[1] = offsets[n4][1];\n\t\t\toffset[2] = offsets[n4][2];\n\n\t\t\tint bit_shift;\n\t\t\tbit_shift = bitShifts[n4];\n\n\t\t\tif (swapEndian)\n\t\t\t{\n\t\t\t\t// load with short byte swap\n\t\t\t\tif (odd)\n\t\t\t\t{\n\t\t\t\t\tbuf[0] = data[addr7 - 1];\n\t\t\t\t\tbuf[1] = data[addr7 + 2];\n\t\t\t\t\tbuf[2] = data[addr7 + 1];\n\t\t\t\t\tbuf[3] = data[addr7 + 4];\n\t\t\t\t\tbuf[4] = data[addr7 + 3];\n\t\t\t\t\tbuf[5] = data[addr7 + 6];\n\t\t\t\t\tbuf[6] = data[addr7 + 5];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbuf[0] = data[addr7 + 1];\n\t\t\t\t\tbuf[1] = data[addr7 + 0];\n\t\t\t\t\tbuf[2] = data[addr7 + 3];\n\t\t\t\t\tbuf[3] = data[addr7 + 2];\n\t\t\t\t\tbuf[4] = data[addr7 + 5];\n\t\t\t\t\tbuf[5] = data[addr7 + 4];\n\t\t\t\t\tbuf[6] = data[addr7 + 7];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmemcpy(buf, &data[addr7], 7);\n\t\t\t}\n\t\t\tunsigned int b0 = static_cast<unsigned int>(buf[offset[0]] & 0xff);\n\t\t\tunsigned int b1 = static_cast<unsigned int>(buf[offset[1]] & 0xff);\n\t\t\tunsigned int b2 = static_cast<unsigned int>(buf[offset[2]] & 0xff);\n\n\t\t\t// unsigned int val = (b0 << 16) | (b1 << 8) | b2;\n\t\t\t// unsigned int val = (b2 << 16) | (b0 << 8) | b0;\n\t\t\tunsigned int val = (b0 << 16) | (b1 << 8) | b2;\n\t\t\t// unsigned int val = b2;\n\t\t\tval = 0x3fff & (val >> bit_shift);\n\n\t\t\timage[static_cast<size_t>(y * width + x)] = static_cast<float>(val);\n\t\t}\n\t});\n\n\tspdlog::get(\"console\")->debug(\"decode14BitToFloat took: {} seconds.\", (timer.lap() / 1000.f));\n}\n\n//\n// Decode 16bit integer image into floating point HDR image\n//\nvoid decode16BitToFloat(vector<float> &image, unsigned char *data, int width, int height, bool swapEndian)\n{\n\tTimer timer;\n\n\timage.resize(static_cast<size_t>(width * height));\n\tunsigned short *ptr = reinterpret_cast<unsigned short *>(data);\n\n\tparallel_for(0, height, [&image,width,ptr,swapEndian](int y)\n\t{\n\t\tfor (int x = 0; x < width; x++)\n\t\t{\n\t\t\tunsigned short val = ptr[y * width + x];\n\t\t\tif (swapEndian)\n\t\t\t\tval = endianSwap(val);\n\n\t\t\t// range will be [0, 65535]\n\t\t\timage[static_cast<size_t>(y * width + x)] = static_cast<float>(val);\n\t\t}\n\t});\n\n\tspdlog::get(\"console\")->debug(\"decode16BitToFloat took: {} seconds.\", (timer.lap() / 1000.f));\n}\n\nchar get_colorname(int c)\n{\n\tswitch (c)\n\t{\n\t\tcase 0:\n\t\t\treturn 'R';\n\t\tcase 1:\n\t\t\treturn 'G';\n\t\tcase 2:\n\t\t\treturn 'B';\n\t\tcase 3:\n\t\t\treturn 'C';\n\t\tcase 4:\n\t\t\treturn 'M';\n\t\tcase 5:\n\t\t\treturn 'Y';\n\t\tcase 6:\n\t\t\treturn 'W';\n\t\tdefault:\n\t\t\treturn '?';\n\t}\n}\n\nvoid printImageInfo(const tinydng::DNGImage & image)\n{\n\tauto console = spdlog::get(\"console\");\n\tconsole->debug(\"width = {}.\", image.width);\n\tconsole->debug(\"width = {}.\", image.width);\n\tconsole->debug(\"height = {}.\", image.height);\n\tconsole->debug(\"bits per pixel = {}.\", image.bits_per_sample);\n\tconsole->debug(\"bits per pixel(original) = {}\", image.bits_per_sample_original);\n\tconsole->debug(\"samples per pixel = {}\", image.samples_per_pixel);\n\tconsole->debug(\"sample format = {}\", image.sample_format);\n\n\tconsole->debug(\"version = {}\", image.version);\n\n\tfor (int s = 0; s < image.samples_per_pixel; s++)\n\t{\n\t\tconsole->debug(\"white_level[{}] = {}\", s, image.white_level[s]);\n\t\tconsole->debug(\"black_level[{}] = {}\", s, image.black_level[s]);\n\t}\n\n\tconsole->debug(\"tile_width = {}\", image.tile_width);\n\tconsole->debug(\"tile_length = {}\", image.tile_length);\n\tconsole->debug(\"tile_offset = {}\", image.tile_offset);\n\tconsole->debug(\"tile_offset = {}\", image.tile_offset);\n\n\tconsole->debug(\"cfa_layout = {}\", image.cfa_layout);\n\tconsole->debug(\"cfa_plane_color = {}{}{}{}\",\n\t               get_colorname(image.cfa_plane_color[0]),\n\t               get_colorname(image.cfa_plane_color[1]),\n\t               get_colorname(image.cfa_plane_color[2]),\n\t               get_colorname(image.cfa_plane_color[3]));\n\tconsole->debug(\"cfa_pattern[2][2] = \\n {}, {},\\n {}, {}\",\n\t               image.cfa_pattern[0][0],\n\t               image.cfa_pattern[0][1],\n\t               image.cfa_pattern[1][0],\n\t               image.cfa_pattern[1][1]);\n\n\tconsole->debug(\"active_area = \\n {}, {},\\n {}, {}\",\n\t               image.active_area[0],\n\t               image.active_area[1],\n\t               image.active_area[2],\n\t               image.active_area[3]);\n\n\tconsole->debug(\"calibration_illuminant1 = {}\", image.calibration_illuminant1);\n\tconsole->debug(\"calibration_illuminant2 = {}\", image.calibration_illuminant2);\n\n\tconsole->debug(\"color_matrix1 = \");\n\tfor (size_t k = 0; k < 3; k++)\n\t\tconsole->debug(\"{} {} {}\",\n\t\t               image.color_matrix1[k][0],\n\t\t               image.color_matrix1[k][1],\n\t\t               image.color_matrix1[k][2]);\n\n\tconsole->debug(\"color_matrix2 = \");\n\tfor (size_t k = 0; k < 3; k++)\n\t\tconsole->debug(\"{} {} {}\",\n\t\t               image.color_matrix2[k][0],\n\t\t               image.color_matrix2[k][1],\n\t\t               image.color_matrix2[k][2]);\n\n\tif (true)//image.has_forward_matrix2)\n\t{\n\t\tconsole->debug(\"forward_matrix1 found = \");\n\t\tfor (size_t k = 0; k < 3; k++)\n\t\t\tconsole->debug(\"{} {} {}\",\n\t\t\t               image.forward_matrix1[k][0],\n\t\t\t               image.forward_matrix1[k][1],\n\t\t\t               image.forward_matrix1[k][2]);\n\t}\n\telse\n\t\tconsole->debug(\"forward_matrix2 not found!\");\n\n\tif (true)//image.has_forward_matrix2)\n\t{\n\t\tconsole->debug(\"forward_matrix2 found = \");\n\t\tfor (size_t k = 0; k < 3; k++)\n\t\t\tconsole->debug(\"{} {} {}\",\n\t\t\t               image.forward_matrix2[k][0],\n\t\t\t               image.forward_matrix2[k][1],\n\t\t\t               image.forward_matrix2[k][2]);\n\t}\n\telse\n\t\tconsole->debug(\"forward_matrix2 not found!\");\n\n\tconsole->debug(\"camera_calibration1 = \");\n\tfor (size_t k = 0; k < 3; k++)\n\t\tconsole->debug(\"{} {} {}\",\n\t\t               image.camera_calibration1[k][0],\n\t\t               image.camera_calibration1[k][1],\n\t\t               image.camera_calibration1[k][2]);\n\n\tconsole->debug(\"orientation = {}\", image.orientation);\n\n\tconsole->debug(\"camera_calibration2 = \");\n\tfor (size_t k = 0; k < 3; k++)\n\t\tconsole->debug(\"{} {} {}\",\n\t\t               image.camera_calibration2[k][0],\n\t\t               image.camera_calibration2[k][1],\n\t\t               image.camera_calibration2[k][2]);\n\n\tif (image.has_analog_balance)\n\t\tconsole->debug(\"analog_balance = {} , {} , {}\",\n\t\t               image.analog_balance[0],\n\t\t               image.analog_balance[1],\n\t\t               image.analog_balance[2]);\n\telse\n\t\tconsole->debug(\"analog_balance not found!\");\n\n\tif (image.has_as_shot_neutral)\n\t\tconsole->debug(\"as_shot_neutral = {} , {} , {}\",\n\t\t               image.as_shot_neutral[0],\n\t\t               image.as_shot_neutral[1],\n\t\t               image.as_shot_neutral[2]);\n\telse\n\t\tconsole->debug(\"shot_neutral not found!\");\n}\n\n} // namespace", "meta": {"hexsha": "b594dfd4f620cc4c64838a38733eff544df8cb0d", "size": 31250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HDRImageIO.cpp", "max_stars_repo_name": "ikrima/hdrview", "max_stars_repo_head_hexsha": "8436cf9dc8973b13347c187dfa7152d15d5cfc45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-11T01:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-21T02:22:46.000Z", "max_issues_repo_path": "src/HDRImageIO.cpp", "max_issues_repo_name": "ikrima/hdrview", "max_issues_repo_head_hexsha": "8436cf9dc8973b13347c187dfa7152d15d5cfc45", "max_issues_repo_licenses": ["MIT"], "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/HDRImageIO.cpp", "max_forks_repo_name": "ikrima/hdrview", "max_forks_repo_head_hexsha": "8436cf9dc8973b13347c187dfa7152d15d5cfc45", "max_forks_repo_licenses": ["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.1565304088, "max_line_length": 155, "alphanum_fraction": 0.60352, "num_tokens": 9180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1908955857286567}}
{"text": "// Copyright 2018 IOTA Foundation\n\n#include <map>\n#include <mutex>\n#include <random>\n#include <thread>\n#include <vector>\n\n#include <gtest/gtest.h>\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\n#include \"hub/commands/create_user.h\"\n#include \"hub/commands/get_balance.h\"\n#include \"hub/commands/helper.h\"\n#include \"hub/commands/process_transfer_batch.h\"\n#include \"hub/commands/tests/helper.h\"\n\n#include \"runner.h\"\n\nusing namespace hub;\nusing namespace hub::tests;\nusing namespace sqlpp;\n\nnamespace {\nstatic constexpr int64_t USER_BALANCE = 10000;\nstatic constexpr int64_t MAX_TRANSFER_UNIT = 50;\nstatic constexpr uint32_t NUM_USERS = 100;\nstatic constexpr uint32_t NUM_TRANSFERS = 200;\n\nclass ProcessTransferBatchTest : public CommandTest {};\n\nvoid processRandomTransfer(std::map<uint64_t, std::string>& idsToUsers,\n                           std::map<uint64_t, int64_t>& idsToBalances,\n                           std::shared_ptr<common::ClientSession> session,\n                           bool threadSafe = false) {\n  static std::mutex m;\n  std::random_device rd;   // obtain a random number from hardware\n  std::mt19937 eng(rd());  // seed the generator\n  std::uniform_int_distribution<> distr(1,\n                                        MAX_TRANSFER_UNIT);  // define the range\n  std::vector<std::string> users;\n  boost::copy(idsToUsers | boost::adaptors::map_values,\n              std::inserter(users, users.begin()));\n  cmd::ProcessTransferBatch cmd(std::move(session));\n\n  for (uint32_t i = 0; i < NUM_TRANSFERS; ++i) {\n    cmd::ProcessTransferBatchRequest req;\n    cmd::ProcessTransferBatchReply res;\n\n    auto idsToAmounts = createZigZagTransfer(users, req, distr(eng));\n    bool cmdOK = false;\n    try {\n      auto status = cmd.process(&req, &res);\n      cmdOK = (status == common::cmd::OK);\n    } catch (const sqlpp::exception& ex) {\n    }\n\n    if (threadSafe) {\n      if (cmdOK) {\n        std::unique_lock<std::mutex> lock(m);\n        for (auto& kv : idsToBalances) {\n          idsToBalances[kv.first] += idsToAmounts[kv.first];\n        }\n      }\n    } else {\n      if (cmdOK) {\n        for (auto& kv : idsToBalances) {\n          idsToBalances[kv.first] += idsToAmounts[kv.first];\n        }\n      }\n    }\n  }\n}\n\nTEST_F(ProcessTransferBatchTest, FailOnNonExistingUserId) {\n  cmd::ProcessTransferBatchRequest req;\n  cmd::ProcessTransferBatchReply res;\n\n  constexpr static auto userId = \"Imaginary User\";\n\n  req.transfers.emplace_back(\n      cmd::UserTransfer{.userId = userId, .amount = 100});\n  req.transfers.emplace_back(\n      cmd::UserTransfer{.userId = userId, .amount = -100});\n\n  cmd::ProcessTransferBatch command(session());\n\n  auto status = command.process(&req, &res);\n\n  ASSERT_EQ(status, common::cmd::USER_DOES_NOT_EXIST);\n}\n\nTEST_F(ProcessTransferBatchTest, ZeroAmountTransferFails) {\n  cmd::ProcessTransferBatchRequest req;\n  cmd::ProcessTransferBatchReply res;\n\n  auto userId = \"User Id\";\n  auto status = createUser(session(), userId);\n  ASSERT_TRUE(status == common::cmd::OK);\n\n  req.transfers.emplace_back(cmd::UserTransfer{.userId = userId, .amount = 0});\n\n  cmd::ProcessTransferBatch command(session());\n\n  status = command.process(&req, &res);\n  ASSERT_EQ(status, common::cmd::BATCH_INVALID);\n}\n\nTEST_F(ProcessTransferBatchTest, TransfersAreRecorded) {\n  cmd::ProcessTransferBatchRequest req;\n  cmd::ProcessTransferBatchReply res;\n  std::vector<std::string> users;\n  std::vector<uint64_t> userIds;\n  cmd::ProcessTransferBatch command(session());\n  int64_t absAmount = 10;\n\n  for (auto i = 0; i < 10; ++i) {\n    users.push_back(\"User \" + std::to_string(i + 1));\n    userIds.push_back(i + 1);  // incremental keys are predictable\n    auto status = createUser(session(), users[i]);\n    ASSERT_TRUE(status == common::cmd::OK);\n  }\n  createBalanceForUsers(userIds, USER_BALANCE);\n  createZigZagTransfer(users, req, absAmount);\n  auto status = command.process(&req, &res);\n\n  ASSERT_TRUE(status == common::cmd::OK);\n\n  cmd::GetBalance balCmd(session());\n  cmd::GetBalanceRequest getBalReq;\n  cmd::GetBalanceReply getBalRep;\n\n  for (uint32_t i = 0; i < users.size(); ++i) {\n    getBalReq.userId = users[i];\n    int64_t amount = (i % 2) ? absAmount : -absAmount;\n    ASSERT_TRUE(balCmd.process(&getBalReq, &getBalRep) == common::cmd::OK);\n    ASSERT_EQ(USER_BALANCE + amount, getBalRep.available);\n  }\n}\n\nTEST_F(ProcessTransferBatchTest, TransfersAreRecordedGroupingUserBalances) {\n  cmd::ProcessTransferBatchRequest req;\n  cmd::ProcessTransferBatchReply res;\n  std::vector<std::string> users;\n  std::vector<uint64_t> userIds;\n  cmd::ProcessTransferBatch command(session());\n  int64_t absAmount = 50;\n\n  for (auto i = 0; i < 10; ++i) {\n    users.push_back(\"User \" + std::to_string(i + 1));\n    userIds.push_back(i + 1);  // incremental keys are predictable\n    auto status = createUser(session(), users[i]);\n    ASSERT_TRUE(status == common::cmd::OK);\n  }\n  createBalanceForUsers(userIds, USER_BALANCE / 2);\n  createBalanceForUsers(userIds, USER_BALANCE / 2);\n  createZigZagTransfer(users, req, absAmount);\n  auto status = command.process(&req, &res);\n\n  ASSERT_TRUE(status == common::cmd::OK);\n\n  cmd::GetBalance balCmd(session());\n  cmd::GetBalanceRequest getBalReq;\n  cmd::GetBalanceReply getBalRep;\n\n  for (uint32_t i = 0; i < users.size(); ++i) {\n    getBalReq.userId = users[i];\n    int64_t amount = (i % 2) ? absAmount : -absAmount;\n    ASSERT_TRUE(balCmd.process(&getBalReq, &getBalRep) == common::cmd::OK);\n    ASSERT_EQ(USER_BALANCE + amount, getBalRep.available);\n  }\n}\n\nTEST_F(ProcessTransferBatchTest, TransfersMustBeZeroSummed) {\n  cmd::ProcessTransferBatchRequest req;\n  cmd::ProcessTransferBatchReply res;\n  std::vector<std::string> users;\n  std::vector<uint64_t> userIds;\n  cmd::ProcessTransferBatch command(session());\n\n  for (auto i = 0; i < 9; ++i) {\n    users.push_back(\"User \" + std::to_string(i + 1));\n    userIds.push_back(i + 1);  // incremental keys are predictable\n    auto status = createUser(session(), users[i]);\n    ASSERT_TRUE(status == common::cmd::OK);\n  }\n  createBalanceForUsers(userIds, USER_BALANCE);\n  createZigZagTransfer(users, req, USER_BALANCE / 2);\n  auto status = command.process(&req, &res);\n\n  ASSERT_FALSE(status == common::cmd::OK);\n  ASSERT_EQ(status, common::cmd::BATCH_AMOUNT_NOT_ZERO);\n}\n\nTEST_F(ProcessTransferBatchTest, TransferMustHaveSufficientFunds) {\n  cmd::ProcessTransferBatchRequest req;\n  cmd::ProcessTransferBatchReply res;\n  std::vector<std::string> users;\n  std::vector<uint64_t> userIds;\n  cmd::ProcessTransferBatch command(session());\n\n  for (auto i = 0; i < 2; ++i) {\n    users.push_back(\"User \" + std::to_string(i + 1));\n    userIds.push_back(i + 1);  // incremental keys are predictable\n    auto status = createUser(session(), users[i]);\n    ASSERT_TRUE(status == common::cmd::OK);\n  }\n  createBalanceForUsers(userIds, USER_BALANCE);\n  createZigZagTransfer(users, req, USER_BALANCE + 1);\n  auto status = command.process(&req, &res);\n\n  ASSERT_EQ(status, common::cmd::BATCH_INCONSISTENT);\n}\n\nTEST_F(ProcessTransferBatchTest, SequentialTransfersAreConsistent) {\n  std::map<uint64_t, std::string> idsToUsers;\n  std::map<uint64_t, int64_t> idsToBalances;\n\n  for (uint32_t i = 0; i < NUM_USERS; ++i) {\n    idsToUsers[i + 1] = \"User \" + std::to_string(i + 1);\n    auto status = createUser(session(), idsToUsers[i + 1]);\n    ASSERT_EQ(status, common::cmd::OK);\n  }\n\n  std::vector<uint64_t> userIds;\n  boost::copy(idsToUsers | boost::adaptors::map_keys,\n              std::inserter(userIds, userIds.begin()));\n\n  idsToBalances = createBalanceForUsers(userIds, USER_BALANCE);\n\n  for (auto i = 0; i < 10; ++i) {\n    processRandomTransfer(idsToUsers, idsToBalances, session());\n  }\n\n  cmd::GetBalance balCmd(session());\n  cmd::GetBalanceRequest getBalReq;\n  cmd::GetBalanceReply getBalRep;\n\n  for (auto& kv : idsToUsers) {\n    getBalReq.userId = kv.second;\n    ASSERT_EQ(balCmd.process(&getBalReq, &getBalRep), common::cmd::OK);\n    ASSERT_EQ(idsToBalances[kv.first], getBalRep.available);\n  }\n}\n\nTEST_F(ProcessTransferBatchTest, ConcurrentTransfersAreConsistent) {\n  static constexpr uint32_t NUM_THREADS = 20;\n\n  std::vector<std::thread> threads(NUM_THREADS);\n  std::map<uint64_t, std::string> idsToUsers;\n  std::map<uint64_t, int64_t> idsToBalances;\n\n  for (uint32_t i = 0; i < NUM_USERS; ++i) {\n    idsToUsers[i + 1] = \"User \" + std::to_string(i + 1);\n    auto status = createUser(session(), idsToUsers[i + 1]);\n    ASSERT_EQ(status, common::cmd::OK);\n  }\n\n  std::vector<uint64_t> userIds;\n  boost::copy(idsToUsers | boost::adaptors::map_keys,\n              std::inserter(userIds, userIds.begin()));\n  idsToBalances = createBalanceForUsers(userIds, USER_BALANCE);\n\n  for (uint32_t i = 0; i < NUM_THREADS; ++i) {\n    std::thread t(processRandomTransfer, std::ref(idsToUsers),\n                  std::ref(idsToBalances), session(), true);\n    threads[i] = std::move(t);\n  }\n\n  for (auto& t : threads) {\n    t.join();\n  }\n\n  cmd::GetBalance balCmd(session());\n  cmd::GetBalanceRequest getBalReq;\n  cmd::GetBalanceReply getBalRep;\n\n  for (auto& kv : idsToUsers) {\n    getBalReq.userId = kv.second;\n    ASSERT_EQ(balCmd.process(&getBalReq, &getBalRep), common::cmd::OK);\n    ASSERT_EQ(idsToBalances[kv.first], getBalRep.available);\n  }\n}\n\n};  // namespace\n", "meta": {"hexsha": "39d5e2ae7f64536e5276c369ba7b7469b0b9e2be", "size": 9264, "ext": "cc", "lang": "C++", "max_stars_repo_path": "hub/commands/tests/test_process_transfer_batch.cc", "max_stars_repo_name": "Tsangares/rpchub", "max_stars_repo_head_hexsha": "84378884a189f5c52f14e346fdc1071a816d8b56", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-08-04T19:14:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-29T20:29:07.000Z", "max_issues_repo_path": "hub/commands/tests/test_process_transfer_batch.cc", "max_issues_repo_name": "Tsangares/rpchub", "max_issues_repo_head_hexsha": "84378884a189f5c52f14e346fdc1071a816d8b56", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2018-08-08T08:29:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-25T11:09:48.000Z", "max_forks_repo_path": "hub/commands/tests/test_process_transfer_batch.cc", "max_forks_repo_name": "Tsangares/rpchub", "max_forks_repo_head_hexsha": "84378884a189f5c52f14e346fdc1071a816d8b56", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-08-05T13:43:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T02:08:37.000Z", "avg_line_length": 32.1666666667, "max_line_length": 80, "alphanum_fraction": 0.6857728843, "num_tokens": 2548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.1907147315073957}}
{"text": "// Copyright (c) 2014 The ShadowCoin 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/*\nNotes:\n    Running with -debug could leave to and from address hashes and public keys in the log.\n\n\n    parameters:\n        -nosmsg             Disable secure messaging (fNoSmsg)\n        -debugsmsg          Show extra debug messages (fDebugSmsg)\n        -smsgscanchain      Scan the block chain for public key addresses on startup\n\n\n    Wallet Locked\n        A copy of each incoming message is stored in bucket files ending in _wl.dat\n        wl (wallet locked) bucket files are deleted if they expire, like normal buckets\n        When the wallet is unlocked all the messages in wl files are scanned.\n\n\n    Address Whitelist\n        Owned Addresses are stored in smsgAddresses vector\n        Saved to smsg.ini\n        Modify options using the smsglocalkeys rpc command or edit the smsg.ini file (with client closed)\n\n\n*/\n\n#include \"smessage.h\"\n\n#include <stdint.h>\n#include <time.h>\n#include <map>\n#include <stdexcept>\n#include <sstream>\n#include <errno.h>\n\n#include <secp256k1.h>\n#include <openssl/aes.h>\n#include <openssl/evp.h>\n#include \"crypto/sha512.h\"\n#include \"crypto/hmac_sha256.h\"\n\n#include <boost/atomic.hpp>\n#include <boost/thread.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n\n\n#include \"base58.h\"\n#include \"crypter.h\"\n#include \"db.h\"\n#include \"init.h\" // pwalletMain\n#include \"rpcprotocol.h\"\n#include \"txdb-leveldb.h\"\n\n#include \"lz4/lz4.c\"\n#include \"xxhash/xxhash.h\"\n#include \"xxhash/xxhash.c\"\n\n\n//! anonymous namespace\nnamespace {\n\nclass CSecp256k1Init {\npublic:\n    CSecp256k1Init() {\n        secp256k1_start(SECP256K1_START_VERIFY);\n    }\n    ~CSecp256k1Init() {\n        secp256k1_stop();\n    }\n};\nstatic CSecp256k1Init instance_of_csecp256k1;\n}\n\n\nstatic bool DeriveKey(secure_buffer &vchP, const CKey &keyR, const CPubKey &cpkDestK)\n{\n    vchP.assign(cpkDestK.begin(), cpkDestK.end());\n    secure_buffer r(keyR.begin(), keyR.end());\n    return secp256k1_ec_pubkey_tweak_mul(&vchP[0], vchP.size(), &r[0]);\n}\n\n\n// TODO: For buckets older than current, only need to store no. messages and hash in memory\n\nboost::signals2::signal<void (SecMsgStored& inboxHdr)>  NotifySecMsgInboxChanged;\nboost::signals2::signal<void (SecMsgStored& outboxHdr)> NotifySecMsgOutboxChanged;\nboost::signals2::signal<void ()> NotifySecMsgWalletUnlocked;\n\nbool fSecMsgEnabled = false;\nboost::thread secureMsgThread;\n\nstd::map<int64_t, SecMsgBucket> smsgBuckets;\nstd::vector<SecMsgAddress>      smsgAddresses;\nSecMsgOptions                   smsgOptions;\n\nuint32_t nPeerIdCounter = 1;\n\nCCriticalSection cs_smsg;\nCCriticalSection cs_smsgDB;\nCCriticalSection cs_smsgThreads;\n\nleveldb::DB *smsgDB = NULL;\n\n\nnamespace fs = boost::filesystem;\n\n\nvoid SecMsgBucket::hashBucket()\n{\n    if (fDebugSmsg)\n        printf(\"SecMsgBucket::hashBucket()\\n\");\n    \n    timeChanged = GetTime();\n    \n    std::set<SecMsgToken>::iterator it;\n    \n    void* state = XXH32_init(1);\n    \n    for (it = setTokens.begin(); it != setTokens.end(); ++it)\n    {\n        XXH32_update(state, it->sample, 8);\n    }\n    \n    hash = XXH32_digest(state);\n    \n    if (fDebugSmsg)\n        printf(\"Hashed %d messages, hash %u\\n\", (int) setTokens.size(), hash);\n}\n\n\nbool SecMsgDB::Open(const char* pszMode)\n{\n    if (smsgDB)\n    {\n        pdb = smsgDB;\n        return true;\n    }\n\n    bool fCreate = strchr(pszMode, 'c');\n\n    fs::path fullpath = GetDataDir() / \"smsgDB\";\n\n    if (!fCreate\n        && (!fs::exists(fullpath)\n            || !fs::is_directory(fullpath)))\n    {\n        printf(\"SecMsgDB::open() - DB does not exist.\\n\");\n        return false;\n    }\n\n    leveldb::Options options;\n    options.create_if_missing = fCreate;\n    leveldb::Status s = leveldb::DB::Open(options, fullpath.string(), &smsgDB);\n\n    if (!s.ok())\n    {\n        printf(\"SecMsgDB::open() - Error opening db: %s.\\n\", s.ToString().c_str());\n        return false;\n    }\n\n    pdb = smsgDB;\n\n    return true;\n}\n\n\nclass SecMsgBatchScanner : public leveldb::WriteBatch::Handler\n{\npublic:\n    std::string needle;\n    bool* deleted;\n    std::string* foundValue;\n    bool foundEntry;\n\n    SecMsgBatchScanner() : foundEntry(false) {}\n\n    virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value)\n    {\n        if (key.ToString() == needle)\n        {\n            foundEntry = true;\n            *deleted = false;\n            *foundValue = value.ToString();\n        }\n    }\n\n    virtual void Delete(const leveldb::Slice& key)\n    {\n        if (key.ToString() == needle)\n        {\n            foundEntry = true;\n            *deleted = true;\n        }\n    }\n};\n\n// When performing a read, if we have an active batch we need to check it first\n// before reading from the database, as the rest of the code assumes that once\n// a database transaction begins reads are consistent with it. It would be good\n// to change that assumption in future and avoid the performance hit, though in\n// practice it does not appear to be large.\nbool SecMsgDB::ScanBatch(const CDataStream& key, std::string* value, bool* deleted) const\n{\n    if (!activeBatch)\n        return false;\n\n    *deleted = false;\n    SecMsgBatchScanner scanner;\n    scanner.needle = key.str();\n    scanner.deleted = deleted;\n    scanner.foundValue = value;\n    leveldb::Status s = activeBatch->Iterate(&scanner);\n    if (!s.ok())\n    {\n        printf(\"SecMsgDB ScanBatch error: %s\\n\", s.ToString().c_str());\n        return false;\n    }\n\n    return scanner.foundEntry;\n}\n\nbool SecMsgDB::TxnBegin()\n{\n    if (activeBatch)\n        return true;\n    activeBatch = new leveldb::WriteBatch();\n    return true;\n}\n\nbool SecMsgDB::TxnCommit()\n{\n    if (!activeBatch)\n        return false;\n\n    leveldb::WriteOptions writeOptions;\n    writeOptions.sync = true;\n    leveldb::Status status = pdb->Write(writeOptions, activeBatch);\n    delete activeBatch;\n    activeBatch = NULL;\n\n    if (!status.ok())\n    {\n        printf(\"SecMsgDB batch commit failure: %s\\n\", status.ToString().c_str());\n        return false;\n    }\n\n    return true;\n}\n\nbool SecMsgDB::TxnAbort()\n{\n    delete activeBatch;\n    activeBatch = NULL;\n    return true;\n}\n\nbool SecMsgDB::ReadPK(CKeyID& addr, CPubKey& pubkey)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.reserve(sizeof(addr) + 2);\n    ssKey << 'p';\n    ssKey << 'k';\n    ssKey << addr;\n    std::string strValue;\n\n    bool readFromDb = true;\n    if (activeBatch)\n    {\n        // -- check activeBatch first\n        bool deleted = false;\n        readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;\n        if (deleted)\n            return false;\n    }\n\n    if (readFromDb)\n    {\n        leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue);\n        if (!s.ok())\n        {\n            if (s.IsNotFound())\n                return false;\n            printf(\"LevelDB read failure: %s\\n\", s.ToString().c_str());\n            return false;\n        }\n    }\n\n    try {\n        CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);\n        ssValue >> pubkey;\n    } catch (std::exception& e) {\n        printf(\"SecMsgDB::ReadPK() unserialize threw: %s.\\n\", e.what());\n        return false;\n    }\n\n    return true;\n}\n\nbool SecMsgDB::WritePK(CKeyID& addr, CPubKey& pubkey)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.reserve(sizeof(addr) + 2);\n    ssKey << 'p';\n    ssKey << 'k';\n    ssKey << addr;\n    CDataStream ssValue(SER_DISK, CLIENT_VERSION);\n    ssValue.reserve(sizeof(pubkey));\n    ssValue << pubkey;\n\n    if (activeBatch)\n    {\n        activeBatch->Put(ssKey.str(), ssValue.str());\n        return true;\n    }\n\n    leveldb::WriteOptions writeOptions;\n    writeOptions.sync = true;\n    leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str());\n    if (!s.ok())\n    {\n        printf(\"SecMsgDB write failure: %s\\n\", s.ToString().c_str());\n        return false;\n    }\n\n    return true;\n}\n\nbool SecMsgDB::ExistsPK(CKeyID& addr)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.reserve(sizeof(addr)+2);\n    ssKey << 'p';\n    ssKey << 'k';\n    ssKey << addr;\n    std::string unused;\n\n    if (activeBatch)\n    {\n        bool deleted;\n        if (ScanBatch(ssKey, &unused, &deleted) && !deleted)\n        {\n            return true;\n        }\n    }\n\n    leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);\n    return s.IsNotFound() == false;\n}\n\n\nbool SecMsgDB::NextSmesg(leveldb::Iterator* it, std::string& prefix, unsigned char* chKey, SecMsgStored& smsgStored)\n{\n    if (!pdb)\n        return false;\n\n    if (!it->Valid()) // first run\n        it->Seek(prefix);\n    else\n        it->Next();\n\n    if (!(it->Valid()\n        && it->key().size() == 18\n        && memcmp(it->key().data(), prefix.data(), 2) == 0))\n        return false;\n\n    memcpy(chKey, it->key().data(), 18);\n\n    try {\n        CDataStream ssValue(it->value().data(), it->value().data() + it->value().size(), SER_DISK, CLIENT_VERSION);\n        ssValue >> smsgStored;\n    } catch (std::exception& e) {\n        printf(\"SecMsgDB::NextSmesg() unserialize threw: %s.\\n\", e.what());\n        return false;\n    }\n\n    return true;\n}\n\nbool SecMsgDB::NextSmesgKey(leveldb::Iterator* it, std::string& prefix, unsigned char* chKey)\n{\n    if (!pdb)\n        return false;\n\n    if (!it->Valid()) // first run\n        it->Seek(prefix);\n    else\n        it->Next();\n\n    if (!(it->Valid()\n        && it->key().size() == 18\n        && memcmp(it->key().data(), prefix.data(), 2) == 0))\n        return false;\n\n    memcpy(chKey, it->key().data(), 18);\n\n    return true;\n}\n\nbool SecMsgDB::ReadSmesg(unsigned char* chKey, SecMsgStored& smsgStored)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.write((const char*)chKey, 18);\n    std::string strValue;\n\n    bool readFromDb = true;\n    if (activeBatch)\n    {\n        // -- check activeBatch first\n        bool deleted = false;\n        readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;\n        if (deleted)\n            return false;\n    }\n\n    if (readFromDb)\n    {\n        leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue);\n        if (!s.ok())\n        {\n            if (s.IsNotFound())\n                return false;\n            printf(\"LevelDB read failure: %s\\n\", s.ToString().c_str());\n            return false;\n        }\n    }\n\n    try {\n        CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);\n        ssValue >> smsgStored;\n    } catch (std::exception& e) {\n        printf(\"SecMsgDB::ReadSmesg() unserialize threw: %s.\\n\", e.what());\n        return false;\n    }\n\n    return true;\n}\n\nbool SecMsgDB::WriteSmesg(unsigned char* chKey, SecMsgStored& smsgStored)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.write((const char*)chKey, 18);\n    CDataStream ssValue(SER_DISK, CLIENT_VERSION);\n    ssValue << smsgStored;\n\n    if (activeBatch)\n    {\n        activeBatch->Put(ssKey.str(), ssValue.str());\n        return true;\n    }\n\n    leveldb::WriteOptions writeOptions;\n    writeOptions.sync = true;\n    leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str());\n    if (!s.ok())\n    {\n        printf(\"SecMsgDB write failed: %s\\n\", s.ToString().c_str());\n        return false;\n    }\n\n    return true;\n}\n\nbool SecMsgDB::ExistsSmesg(unsigned char* chKey)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.write((const char*)chKey, 18);\n    std::string unused;\n\n    if (activeBatch)\n    {\n        bool deleted;\n        if (ScanBatch(ssKey, &unused, &deleted) && !deleted)\n        {\n            return true;\n        }\n    }\n\n    leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);\n    return s.IsNotFound() == false;\n    return true;\n}\n\nbool SecMsgDB::EraseSmesg(unsigned char* chKey)\n{\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.write((const char*)chKey, 18);\n\n    if (activeBatch)\n    {\n        activeBatch->Delete(ssKey.str());\n        return true;\n    }\n\n    leveldb::WriteOptions writeOptions;\n    writeOptions.sync = true;\n    leveldb::Status s = pdb->Delete(writeOptions, ssKey.str());\n\n    if (s.ok() || s.IsNotFound())\n        return true;\n    printf(\"SecMsgDB erase failed: %s\\n\", s.ToString().c_str());\n    return false;\n}\n\n\nstatic boost::atomic_uint nThreadCount(0);\nvoid ThreadSecureMsg(void* parg)\n{\n    nThreadCount.fetch_add(1, boost::memory_order_relaxed);\n    // -- bucket management thread\n    RenameThread(\"bitcredit-smsg\"); // Make this thread recognisable\n  \n  \n    std::vector<unsigned char> vchKey;\n    SecMsgStored smsgStored;\n\n    std::string sPrefix(\"qm\");\n    unsigned char chKey[18];\n\n\n    while (fSecMsgEnabled) {\n        int64_t now = GetTime();\n\n        int64_t cutoffTime = now - SMSG_RETENTION;\n        {\n            LOCK(cs_smsg);\n\n            for (std::map<int64_t, SecMsgBucket>::iterator it(smsgBuckets.begin()); it != smsgBuckets.end(); it++) {\n                //if (fDebugSmsg)\n                //    printf(\"Checking bucket %\"PRId64\", size %\"PRIszu\" \\n\", it->first, it->second.setTokens.size());\n                if (it->first < cutoffTime) {\n                    if (fDebugSmsg)\n                        printf(\"Removing bucket %d\\n\", (int) it->first);\n\n                    std::string fileName = boost::lexical_cast<std::string>(it->first);\n\n                    fs::path fullPath = GetDataDir() / \"smsgStore\" / (fileName + \"_01.dat\");\n                    if (fs::exists(fullPath)) {\n                        try {\n                            fs::remove(fullPath);\n                        }\n                        catch (const fs::filesystem_error& ex) {\n                            printf(\"Error removing bucket file %s.\\n\", ex.what());\n                        }\n                    }\n                    else {\n                        printf(\"Path %s does not exist\\n\", fullPath.string().c_str());\n                    }\n                    \n                    // -- look for a wl file, it stores incoming messages when wallet is locked\n                    fullPath = GetDataDir() / \"smsgStore\" / (fileName + \"_01_wl.dat\");\n                    if (fs::exists(fullPath)) {\n                        try {\n                            fs::remove(fullPath);\n                        }\n                        catch (const fs::filesystem_error& ex) {\n                            printf(\"Error removing wallet locked file %s.\\n\", ex.what());\n                        }\n                    }\n\n                    smsgBuckets.erase(it);\n                }\n                else if (it->second.nLockCount > 0) { // -- tick down nLockCount, so will eventually expire if peer never sends data\n                    it->second.nLockCount--;\n\n                    if (it->second.nLockCount == 0) {    // lock timed out\n                        uint32_t nPeerId     = it->second.nLockPeerId;\n                        int64_t  ignoreUntil = GetTime() + SMSG_TIME_IGNORE;\n\n                        if (fDebugSmsg)\n                            printf(\"Lock on bucket %d for peer %u timed out.\\n\", (int) it->first, nPeerId);\n\n                        // -- look through the nodes for the peer that locked this bucket\n                        LOCK(cs_vNodes);\n                        BOOST_FOREACH(CNode* pnode, vNodes) {\n                            if (pnode->smsgData.nPeerId != nPeerId)\n                                continue;\n                            pnode->smsgData.ignoreUntil = ignoreUntil;\n\n                            // -- alert peer that they are being ignored\n                            std::vector<unsigned char> vchData;\n                            vchData.resize(8);\n                            memcpy(&vchData[0], &ignoreUntil, 8);\n                            pnode->PushMessage(\"smsgIgnore\", vchData);\n\n                            if (fDebugSmsg)\n                                printf(\"Lock on bucket %d for peer %u timed out.\\n\", (int) it->first, nPeerId);\n                            break;\n                        }\n                        it->second.nLockPeerId = 0;\n                    } // if (it->second.nLockCount == 0)\n                } // ! if (it->first < cutoffTime)\n            }\n        } // LOCK(cs_smsg);\n\n\n        SecMsgDB dbOutbox;\n        leveldb::Iterator* it;\n        {\n            LOCK(cs_smsgDB);\n\n            if (!dbOutbox.Open(\"cr+\"))\n                continue;\n\n            // -- fifo (smallest key first)\n            it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions());\n        }\n        // -- break up lock, SecureMsgSetHash will take long\n\n        for (;;)\n        {\n            {\n                LOCK(cs_smsgDB);\n                if (!dbOutbox.NextSmesg(it, sPrefix, chKey, smsgStored))\n                    break;\n            }\n\n            SecureMessageHeader smsg(&smsgStored.vchMessage[0]);\n            const unsigned char* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];\n\n            // -- message is removed here, no matter what\n            {\n                LOCK(cs_smsgDB);\n                dbOutbox.EraseSmesg(chKey);\n            }\n\n            // -- add to message store\n            {\n                LOCK(cs_smsg);\n                if (SecureMsgStore(smsg, pPayload, true) != 0) {\n                    printf(\"SecMsgPow: Could not place message in buckets, message removed.\\n\");\n                    continue;\n                }\n            }\n\n            // -- test if message was sent to self\n            if (SecureMsgScanMessage(smsg, pPayload, true) != 0) {\n                // message recipient is not this node (or failed)\n            }\n        }\n\n        {\n            LOCK(cs_smsg);\n            delete it;\n        }\n\n\n        try {\n            boost::this_thread::sleep_for(boost::chrono::seconds(SMSG_THREAD_DELAY)); // check every SMSG_THREAD_DELAY seconds\n        }\n        catch(boost::thread_interrupted &e) {\n            break;\n        }\n    }\n\n    printf(\"ThreadSecureMsg exited.\\n\");\n    nThreadCount.fetch_sub(1, boost::memory_order_relaxed);\n}\n\n\nint SecureMsgBuildBucketSet()\n{\n    /*\n        Build the bucket set by scanning the files in the smsgStore dir.\n\n        smsgBuckets should be empty\n    */\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgBuildBucketSet()\\n\");\n\n    int64_t  now            = GetTime();\n    uint32_t nFiles         = 0;\n    uint32_t nMessages      = 0;\n\n    fs::path pathSmsgDir = GetDataDir() / \"smsgStore\";\n    fs::directory_iterator itend;\n\n\n    if (!fs::exists(pathSmsgDir)\n        || !fs::is_directory(pathSmsgDir))\n    {\n        if (!fs::create_directory(pathSmsgDir)) {\n            printf(\"Message store directory does not exist and could not be created.\\n\");\n            return 1;\n        }\n    }\n\n    for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd) {\n        if (!fs::is_regular_file(itd->status()))\n            continue;\n\n        std::string fileType = (*itd).path().extension().string();\n\n        if (fileType.compare(\".dat\") != 0)\n            continue;\n\n        std::string fileName = (*itd).path().filename().string();\n\n\n        if (fDebugSmsg)\n            printf(\"Processing file: %s.\\n\", fileName.c_str());\n\n        nFiles++;\n\n        // TODO files must be split if > 2GB\n        // time_noFile.dat\n        size_t sep = fileName.find_first_of(\"_\");\n        if (sep == std::string::npos)\n            continue;\n\n        std::string stime = fileName.substr(0, sep);\n\n        int64_t fileTime = boost::lexical_cast<int64_t>(stime);\n\n        if (fileTime < now - SMSG_RETENTION) {\n            printf(\"Dropping file %s, expired.\\n\", fileName.c_str());\n            try {\n                fs::remove((*itd).path());\n            }\n            catch (const fs::filesystem_error& ex) {\n                printf(\"Error removing bucket file %s, %s.\\n\", fileName.c_str(), ex.what());\n            }\n            continue;\n        }\n\n        if (boost::algorithm::ends_with(fileName, \"_wl.dat\")) {\n            if (fDebugSmsg)\n                printf(\"Skipping wallet locked file: %s.\\n\", fileName.c_str());\n            continue;\n        }\n\n        SecureMessageHeader smsg;\n        std::set<SecMsgToken>& tokenSet = smsgBuckets[fileTime].setTokens;\n\n        {\n            LOCK(cs_smsg);\n            FILE *fp;\n\n            if (!(fp = fopen((*itd).path().string().c_str(), \"rb\"))) {\n                printf(\"Error opening file: %s (%d)\\n\", strerror(errno), __LINE__);\n                continue;\n            }\n\n            for (;;) {\n                long int ofs = ftell(fp);\n                SecMsgToken token;\n                token.offset = ofs;\n                if (fread(&smsg, sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) {\n                    if (!feof(fp)) {\n                        printf(\"fread header failed\\n\");\n                    }\n                    break;\n                }\n                token.timestamp = smsg.timestamp;\n                if (smsg.nPayload < 8)\n                    continue;\n                \n                if (fread(token.sample, sizeof(unsigned char), 8, fp) != 8) {\n                    printf(\"fread data failed: %s\\n\", strerror(errno));\n                    break;\n                }\n\n                if (fseek(fp, smsg.nPayload-8, SEEK_CUR) != 0) {\n                    printf(\"fseek, strerror: %s.\\n\", strerror(errno));\n                    break;\n                }\n\n                tokenSet.insert(token);\n            }\n\n            fclose(fp);\n        }\n        smsgBuckets[fileTime].hashBucket();\n\n        nMessages += tokenSet.size();\n\n        if (fDebugSmsg)\n            printf(\"Bucket %d contains %d messages.\\n\", (int) fileTime, (int) tokenSet.size());\n    }\n\n    printf(\"Processed %u files, loaded %d buckets containing %u messages.\\n\", nFiles, (int) smsgBuckets.size(), nMessages);\n\n    return 0;\n}\n\nint SecureMsgAddWalletAddresses()\n{\n    if (fDebugSmsg)\n        printf(\"SecureMsgAddWalletAddresses()\\n\");\n\n    std::string sAnonPrefix(\"ao\");\n\n    uint32_t nAdded = 0;\n    BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook)\n    {\n        if (IsMine(*pwalletMain, entry.first) != ISMINE_SPENDABLE)\n            continue;\n\n        // -- skip addresses for anon outputs\n        if (entry.second.purpose.compare(0, sAnonPrefix.length(), sAnonPrefix) == 0)\n            continue;\n\n        // TODO: skip addresses for stealth transactions\n\n        CBitcreditAddress coinAddress(entry.first);\n        if (!coinAddress.IsValid())\n            continue;\n\n        std::string address;\n        std::string strPublicKey;\n        address = coinAddress.ToString();\n\n        bool fExists        = 0;\n        for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)\n        {\n            if (address != it->sAddress)\n                continue;\n            fExists = 1;\n            break;\n        }\n\n        if (fExists)\n            continue;\n\n        bool recvEnabled    = 1;\n        bool recvAnon       = 1;\n\n        smsgAddresses.push_back(SecMsgAddress(address, recvEnabled, recvAnon));\n        nAdded++;\n    }\n\n    if (fDebugSmsg)\n        printf(\"Added %u addresses to whitelist.\\n\", nAdded);\n\n    return 0;\n}\n\n\nint SecureMsgReadIni()\n{\n    if (!fSecMsgEnabled)\n        return false;\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgReadIni()\\n\");\n\n    fs::path fullpath = GetDataDir() / \"smsg.ini\";\n\n\n    FILE *fp;\n    errno = 0;\n    if (!(fp = fopen(fullpath.string().c_str(), \"r\")))\n    {\n        printf(\"Error opening file: %s (%d)\\n\", strerror(errno), __LINE__);\n        return 1;\n    }\n\n    char cLine[512];\n    char *pName, *pValue;\n\n    char cAddress[64];\n    int addrRecv, addrRecvAnon;\n\n    while (fgets(cLine, 512, fp))\n    {\n        cLine[strcspn(cLine, \"\\n\")] = '\\0';\n        cLine[strcspn(cLine, \"\\r\")] = '\\0';\n        cLine[511] = '\\0'; // for safety\n\n        // -- check that line contains a name value pair and is not a comment, or section header\n        if (cLine[0] == '#' || cLine[0] == '[' || strcspn(cLine, \"=\") < 1)\n            continue;\n\n        if (!(pName = strtok(cLine, \"=\"))\n            || !(pValue = strtok(NULL, \"=\")))\n            continue;\n\n        if (strcmp(pName, \"newAddressRecv\") == 0)\n        {\n            smsgOptions.fNewAddressRecv = (strcmp(pValue, \"true\") == 0) ? true : false;\n        } else\n        if (strcmp(pName, \"newAddressAnon\") == 0)\n        {\n            smsgOptions.fNewAddressAnon = (strcmp(pValue, \"true\") == 0) ? true : false;\n        } else\n        if (strcmp(pName, \"key\") == 0)\n        {\n            int rv = sscanf(pValue, \"%64[^|]|%d|%d\", cAddress, &addrRecv, &addrRecvAnon);\n            if (rv == 3)\n            {\n                smsgAddresses.push_back(SecMsgAddress(std::string(cAddress), addrRecv, addrRecvAnon));\n            } else\n            {\n                printf(\"Could not parse key line %s, rv %d.\\n\", pValue, rv);\n            }\n        } else\n        {\n            printf(\"Unknown setting name: '%s'.\", pName);\n        }\n    }\n\n    printf(\"Loaded %d addresses.\\n\", (int) smsgAddresses.size());\n\n    fclose(fp);\n\n    return 0;\n}\n\nint SecureMsgWriteIni()\n{\n    if (!fSecMsgEnabled)\n        return false;\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgWriteIni()\\n\");\n\n    fs::path fullpath = GetDataDir() / \"smsg.ini~\";\n\n    FILE *fp;\n    errno = 0;\n    if (!(fp = fopen(fullpath.string().c_str(), \"w\")))\n    {\n        printf(\"Error opening file: %s (%d)\\n\", strerror(errno), __LINE__);\n        return 1;\n    }\n\n    if (fwrite(\"[Options]\\n\", sizeof(char), 10, fp) != 10)\n    {\n        printf(\"fwrite error: %s\\n\", strerror(errno));\n        fclose(fp);\n        return false;\n    }\n\n    if (fprintf(fp, \"newAddressRecv=%s\\n\", smsgOptions.fNewAddressRecv ? \"true\" : \"false\") < 0\n        || fprintf(fp, \"newAddressAnon=%s\\n\", smsgOptions.fNewAddressAnon ? \"true\" : \"false\") < 0)\n    {\n        printf(\"fprintf error: %s\\n\", strerror(errno));\n        fclose(fp);\n        return false;\n    }\n\n    if (fwrite(\"\\n[Keys]\\n\", sizeof(char), 8, fp) != 8)\n    {\n        printf(\"fwrite error: %s\\n\", strerror(errno));\n        fclose(fp);\n        return false;\n    }\n    for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)\n    {\n        errno = 0;\n        if (fprintf(fp, \"key=%s|%d|%d\\n\", it->sAddress.c_str(), it->fReceiveEnabled, it->fReceiveAnon) < 0)\n        {\n            printf(\"fprintf error: %s\\n\", strerror(errno));\n            continue;\n        }\n    }\n\n\n    fclose(fp);\n\n\n    try {\n        fs::path finalpath = GetDataDir() / \"smsg.ini\";\n        fs::rename(fullpath, finalpath);\n    } catch (const fs::filesystem_error& ex)\n    {\n        printf(\"Error renaming file %s, %s.\\n\", fullpath.string().c_str(), ex.what());\n    }\n    return 0;\n}\n\n\n/** called from AppInit2() in init.cpp */\nbool SecureMsgStart(bool fDontStart, bool fScanChain) {\n    if (fDontStart) {\n        printf(\"Secure messaging not started.\\n\");\n        return false;\n    }\n\n    printf(\"Secure messaging starting.\\n\");\n    SecureMsgEnable();\n\n    if (fScanChain) {\n        SecureMsgScanBlockChain();\n    }\n    \n    return true;\n}\n\n\nbool SecureMsgEnable() {\n    // -- start secure messaging at runtime\n    if (fSecMsgEnabled) {\n        printf(\"SecureMsgEnable: secure messaging is already enabled.\\n\");\n        return false;\n    }\n\n    {\n        LOCK(cs_smsg);\n        fSecMsgEnabled = true;\n\n        smsgAddresses.clear(); // should be empty already\n        if (SecureMsgReadIni() != 0)\n            printf(\"Failed to read smsg.ini\\n\");\n\n        if (smsgAddresses.size() < 1) {\n            printf(\"No address keys loaded.\\n\");\n            if (SecureMsgAddWalletAddresses() != 0)\n                printf(\"Failed to load addresses from wallet.\\n\");\n        }\n\n        smsgBuckets.clear(); // should be empty already\n\n        if (SecureMsgBuildBucketSet() != 0) {\n            printf(\"SecureMsgEnable: could not load bucket sets, secure messaging disabled.\\n\");\n            fSecMsgEnabled = false;\n            return false;\n        }\n    } // LOCK(cs_smsg);\n\n    // -- start threads\n    secureMsgThread = boost::thread(&ThreadSecureMsg, (void*) NULL);\n    if (secureMsgThread.get_id() == boost::this_thread::get_id()) {\n        printf(\"SecureMsgEnable could not start threads, secure messaging disabled.\\n\");\n        fSecMsgEnabled = false;\n        return false;\n    }\n\n    // -- ping each peer, don't know which have messaging enabled\n    {\n        LOCK(cs_vNodes);\n        BOOST_FOREACH(CNode* pnode, vNodes) {\n            pnode->PushMessage(\"smsgPing\");\n            pnode->PushMessage(\"smsgPong\"); // Send pong as have missed initial ping sent by peer when it connected\n        }\n    }\n\n    printf(\"Secure messaging enabled.\\n\");\n    return true;\n}\n\n\nbool SecureMsgDisable() {\n    // -- stop secure messaging at runtime\n    if (!fSecMsgEnabled) {\n        printf(\"SecureMsgDisable: secure messaging is already disabled.\\n\");\n        return false;\n    }\n\n    {\n        LOCK(cs_smsg);\n        fSecMsgEnabled = false;\n\n        // -- clear smsgBuckets\n        std::map<int64_t, SecMsgBucket>::iterator it;\n        it = smsgBuckets.begin();\n        for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it) {\n            it->second.setTokens.clear();\n        }\n        smsgBuckets.clear();\n\n        // -- tell each smsg enabled peer that this node is disabling\n        {\n            LOCK(cs_vNodes);\n            BOOST_FOREACH(CNode* pnode, vNodes) {\n                if (!pnode->smsgData.fEnabled)\n                    continue;\n\n                pnode->PushMessage(\"smsgDisabled\");\n                pnode->smsgData.fEnabled = false;\n            }\n        }\n\n        if (SecureMsgWriteIni() != 0)\n            printf(\"Failed to save smsg.ini\\n\");\n\n        smsgAddresses.clear();\n\n    } // LOCK(cs_smsg);\n\n    secureMsgThread.interrupt();\n    if (secureMsgThread.joinable())\n        secureMsgThread.join();\n\n    if (smsgDB) {\n        LOCK(cs_smsgDB);\n        delete smsgDB;\n        smsgDB = NULL;\n    }\n\n\n    printf(\"Secure messaging disabled.\\n\");\n    return true;\n}\n\n\nbool SecureMsgReceiveData(CNode* pfrom, std::string strCommand, CDataStream& vRecv)\n{\n    /*\n        Called from ProcessMessage\n        Runs in ThreadMessageHandler2\n    */\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgReceiveData() %s %s.\\n\", pfrom->addrName.c_str(), strCommand.c_str());\n\n    {\n    // break up?\n    LOCK(cs_smsg);\n\n    if (strCommand == \"smsgInv\")\n    {\n        std::vector<unsigned char> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 4)\n        {\n            Misbehaving(pfrom->id, 1);\n            return false; // not enough data received to be a valid smsgInv\n        }\n\n        int64_t now = GetTime();\n\n        if (now < pfrom->smsgData.ignoreUntil)\n        {\n            if (fDebugSmsg)\n                printf(\"Node is ignoring peer %u until %d.\\n\", pfrom->smsgData.nPeerId, (int) pfrom->smsgData.ignoreUntil);\n            return false;\n        }\n\n        uint32_t nBuckets       = smsgBuckets.size();\n        uint32_t nLocked        = 0;    // no. of locked buckets on this node\n        uint32_t nInvBuckets;           // no. of bucket headers sent by peer in smsgInv\n        memcpy(&nInvBuckets, &vchData[0], 4);\n        if (fDebugSmsg)\n            printf(\"Remote node sent %d bucket headers, this has %d.\\n\", nInvBuckets, nBuckets);\n\n\n        // -- Check no of buckets:\n        if (nInvBuckets > (SMSG_RETENTION / SMSG_BUCKET_LEN) + 1) // +1 for some leeway\n        {\n            printf(\"Peer sent more bucket headers than possible %u, %u.\\n\", nInvBuckets, (SMSG_RETENTION / SMSG_BUCKET_LEN));\n            Misbehaving(pfrom->id, 1);\n            return false;\n        }\n\n        if (vchData.size() < 4 + nInvBuckets*16)\n        {\n            printf(\"Remote node did not send enough data.\\n\");\n            Misbehaving(pfrom->id, 1);\n            return false;\n        }\n\n        std::vector<unsigned char> vchDataOut;\n        vchDataOut.reserve(4 + 8 * nInvBuckets); // reserve max possible size\n        vchDataOut.resize(4);\n        uint32_t nShowBuckets = 0;\n\n\n        unsigned char *p = &vchData[4];\n        for (uint32_t i = 0; i < nInvBuckets; ++i)\n        {\n            int64_t time;\n            uint32_t ncontent, hash;\n            memcpy(&time, p, 8);\n            memcpy(&ncontent, p+8, 4);\n            memcpy(&hash, p+12, 4);\n\n            p += 16;\n\n            // Check time valid:\n            if (time < now - SMSG_RETENTION)\n            {\n                if (fDebugSmsg)\n                    printf(\"Not interested in peer bucket %d, has expired.\\n\", (int) time);\n\n                if (time < now - SMSG_RETENTION - SMSG_TIME_LEEWAY)\n                    Misbehaving(pfrom->id, 1);\n                continue;\n            }\n            if (time > now + SMSG_TIME_LEEWAY)\n            {\n                if (fDebugSmsg)\n                    printf(\"Not interested in peer bucket %d, in the future.\\n\", (int) time);\n                Misbehaving(pfrom->id, 1);\n                continue;\n            }\n\n            if (ncontent < 1)\n            {\n                if (fDebugSmsg)\n                    printf(\"Peer sent empty bucket, ignore %d %u %u.\\n\", (int32_t) time, ncontent, hash);\n                continue;\n            }\n\n            if (fDebugSmsg)\n            {\n                printf(\"peer bucket %d %u %u.\\n\", (int32_t) time, ncontent, hash);\n                std::cout << \"this bucket \" << time << \", \" << smsgBuckets[time].setTokens.size() << \", \" << smsgBuckets[time].hash << std::endl;\n            }\n\n            if (smsgBuckets[time].nLockCount > 0)\n            {\n                if (fDebugSmsg)\n                    std::cout << \"Bucket is locked \" << smsgBuckets[time].nLockCount << \" waiting for peer \" << smsgBuckets[time].nLockPeerId << \" to send data.\" << std::endl;\n                nLocked++;\n                continue;\n            }\n\n            // -- if this node has more than the peer node, peer node will pull from this\n            //    if then peer node has more this node will pull fom peer\n            if (smsgBuckets[time].setTokens.size() < ncontent\n                || (smsgBuckets[time].setTokens.size() == ncontent\n                    && smsgBuckets[time].hash != hash)) // if same amount in buckets check hash\n            {\n                if (fDebugSmsg)\n                    printf(\"Requesting contents of bucket %d.\\n\", (int32_t) time);\n\n                uint32_t sz = vchDataOut.size();\n                vchDataOut.resize(sz + 8);\n                memcpy(&vchDataOut[sz], &time, 8);\n\n                nShowBuckets++;\n            }\n        }\n\n        // TODO: should include hash?\n        memcpy(&vchDataOut[0], &nShowBuckets, 4);\n        if (vchDataOut.size() > 4)\n        {\n            pfrom->PushMessage(\"smsgShow\", vchDataOut);\n        } else\n        if (nLocked < 1) // Don't report buckets as matched if any are locked\n        {\n            // -- peer has no buckets we want, don't send them again until something changes\n            //    peer will still request buckets from this node if needed (< ncontent)\n            vchDataOut.resize(8);\n            memcpy(&vchDataOut[0], &now, 8);\n            pfrom->PushMessage(\"smsgMatch\", vchDataOut);\n            if (fDebugSmsg)\n                printf(\"Sending smsgMatch, %d.\\n\", (int32_t) now);\n        }\n\n    } else\n    if (strCommand == \"smsgShow\")\n    {\n        std::vector<unsigned char> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 4)\n            return false;\n\n        uint32_t nBuckets;\n        memcpy(&nBuckets, &vchData[0], 4);\n\n        if (vchData.size() < 4 + nBuckets * 8)\n            return false;\n\n        if (fDebugSmsg)\n            printf(\"smsgShow: peer wants to see content of %u buckets.\\n\", nBuckets);\n\n        std::map<int64_t, SecMsgBucket>::iterator itb;\n        std::set<SecMsgToken>::iterator it;\n\n        std::vector<unsigned char> vchDataOut;\n        int64_t time;\n        unsigned char* pIn = &vchData[4];\n        for (uint32_t i = 0; i < nBuckets; ++i, pIn += 8)\n        {\n            memcpy(&time, pIn, 8);\n\n            itb = smsgBuckets.find(time);\n            if (itb == smsgBuckets.end())\n            {\n                if (fDebugSmsg)\n                    printf(\"Don't have bucket %d.\\n\", (int32_t) time);\n                continue;\n            }\n\n            std::set<SecMsgToken>& tokenSet = (*itb).second.setTokens;\n\n            try { vchDataOut.resize(8 + 16 * tokenSet.size()); } catch (std::exception& e)\n            {\n                std::cout << \"vchDataOut.resize \" << (8 + 16 * tokenSet.size()) << \" threw \" << e.what() << std::endl;\n                continue;\n            }\n            memcpy(&vchDataOut[0], &time, 8);\n\n            unsigned char* p = &vchDataOut[8];\n            for (it = tokenSet.begin(); it != tokenSet.end(); ++it)\n            {\n                memcpy(p, &it->timestamp, 8);\n                memcpy(p+8, &it->sample, 8);\n\n                p += 16;\n            }\n            pfrom->PushMessage(\"smsgHave\", vchDataOut);\n        }\n\n\n    } else\n    if (strCommand == \"smsgHave\")\n    {\n        // -- peer has these messages in bucket\n        std::vector<unsigned char> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 8)\n            return false;\n\n        int n = (vchData.size() - 8) / 16;\n\n        int64_t time;\n        memcpy(&time, &vchData[0], 8);\n\n        // -- Check time valid:\n        int64_t now = GetTime();\n        if (time < now - SMSG_RETENTION)\n        {\n            if (fDebugSmsg)\n                printf(\"Not interested in peer bucket %d, has expired.\\n\", (int32_t) time);\n            return false;\n        }\n        if (time > now + SMSG_TIME_LEEWAY)\n        {\n            if (fDebugSmsg)\n                printf(\"Not interested in peer bucket %d, in the future.\\n\", (int32_t) time);\n            Misbehaving(pfrom->id, 1);\n            return false;\n        }\n\n        if (smsgBuckets[time].nLockCount > 0)\n        {\n            if (fDebugSmsg)\n                printf(\"Bucket %d lock count %u, waiting for message data from peer %u.\\n\", (int32_t) time, smsgBuckets[time].nLockCount, smsgBuckets[time].nLockPeerId);\n            return false;\n        }\n\n        if (fDebugSmsg)\n            printf(\"Sifting through bucket %d.\\n\", (int32_t) time);\n\n        std::vector<unsigned char> vchDataOut;\n        vchDataOut.resize(8);\n        memcpy(&vchDataOut[0], &vchData[0], 8);\n\n        std::set<SecMsgToken>& tokenSet = smsgBuckets[time].setTokens;\n        std::set<SecMsgToken>::iterator it;\n        SecMsgToken token;\n        unsigned char* p = &vchData[8];\n\n        for (int i = 0; i < n; ++i)\n        {\n            memcpy(&token.timestamp, p, 8);\n            memcpy(&token.sample, p+8, 8);\n\n            it = tokenSet.find(token);\n            if (it == tokenSet.end())\n            {\n                int nd = vchDataOut.size();\n                try {\n                    vchDataOut.resize(nd + 16);\n                } catch (std::exception& e) {\n                    printf(\"vchDataOut.resize %d threw: %s.\\n\", nd + 16, e.what());\n                    continue;\n                }\n\n                memcpy(&vchDataOut[nd], p, 16);\n            }\n\n            p += 16;\n        }\n\n        if (vchDataOut.size() > 8)\n        {\n            if (fDebugSmsg)\n            {\n                printf(\"Asking peer for  %d messages.\\n\", (int) (vchDataOut.size() - 8) / 16);\n                printf(\"Locking bucket %d for peer %u.\\n\", (int) time, pfrom->smsgData.nPeerId);\n            }\n            smsgBuckets[time].nLockCount   = 3; // lock this bucket for at most 3 * SMSG_THREAD_DELAY seconds, unset when peer sends smsgMsg\n            smsgBuckets[time].nLockPeerId  = pfrom->smsgData.nPeerId;\n            pfrom->PushMessage(\"smsgWant\", vchDataOut);\n        }\n    } else\n    if (strCommand == \"smsgWant\")\n    {\n        std::vector<unsigned char> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 8)\n            return false;\n\n        std::vector<unsigned char> vchOne;\n        std::vector<unsigned char> vchBunch;\n\n        vchBunch.resize(4+8); // nmessages + bucketTime\n\n        int n = (vchData.size() - 8) / 16;\n\n        int64_t time;\n        uint32_t nBunch = 0;\n        memcpy(&time, &vchData[0], 8);\n\n        std::map<int64_t, SecMsgBucket>::iterator itb;\n        itb = smsgBuckets.find(time);\n        if (itb == smsgBuckets.end())\n        {\n            if (fDebugSmsg)\n                printf(\"Don't have bucket %d.\\n\", (int32_t) time);\n            return false;\n        }\n\n        std::set<SecMsgToken>& tokenSet = itb->second.setTokens;\n        std::set<SecMsgToken>::iterator it;\n        SecMsgToken token;\n        unsigned char* p = &vchData[8];\n        for (int i = 0; i < n; ++i)\n        {\n            memcpy(&token.timestamp, p, 8);\n            memcpy(&token.sample, p+8, 8);\n\n            it = tokenSet.find(token);\n            if (it == tokenSet.end())\n            {\n                if (fDebugSmsg)\n                    printf(\"Don't have wanted message %d.\\n\", (int32_t) token.timestamp);\n            } else\n            {\n                //printf(\"Have message at %\"PRId64\".\\n\", it->offset); // DEBUG\n                token.offset = it->offset;\n                //printf(\"winb before SecureMsgRetrieve %\"PRId64\".\\n\", token.timestamp);\n\n                // -- place in vchOne so if SecureMsgRetrieve fails it won't corrupt vchBunch\n                SecureMessage smsg;\n                if (SecureMsgRetrieve(token, smsg) == 0)\n                {\n                    nBunch++;\n                    const size_t size = vchBunch.size();\n                    vchBunch.resize(size + SMSG_HDR_LEN + smsg.nPayload);\n                    memcpy(&vchBunch[size], &smsg, SMSG_HDR_LEN);\n                    memcpy(&vchBunch[size+SMSG_HDR_LEN], &smsg.vchPayload[0], smsg.nPayload);\n                } else\n                {\n                    printf(\"SecureMsgRetrieve failed %d.\\n\", (int32_t) token.timestamp);\n                }\n\n                if (nBunch >= 500\n                    || vchBunch.size() >= 96000)\n                {\n                    if (fDebugSmsg)\n                        printf(\"Break bunch %u, %d.\\n\", nBunch, (int) vchBunch.size());\n                    break; // end here, peer will send more want messages if needed.\n                }\n            }\n            p += 16;\n        }\n\n        if (nBunch > 0)\n        {\n            if (fDebugSmsg)\n                printf(\"Sending block of %u messages for bucket %d.\\n\", nBunch, (int32_t) time);\n\n            memcpy(&vchBunch[0], &nBunch, 4);\n            memcpy(&vchBunch[4], &time, 8);\n            pfrom->PushMessage(\"smsgMsg\", vchBunch);\n        }\n    } else\n    if (strCommand == \"smsgMsg\")\n    {\n        std::vector<unsigned char> vchData;\n        vRecv >> vchData;\n\n        if (fDebugSmsg)\n            printf(\"smsgMsg vchData.size() %d.\\n\", (int) vchData.size());\n\n        SecureMsgReceive(pfrom, vchData);\n    } else\n    if (strCommand == \"smsgMatch\")\n    {\n        std::vector<unsigned char> vchData;\n        vRecv >> vchData;\n\n\n        if (vchData.size() < 8)\n        {\n            printf(\"smsgMatch, not enough data %d.\\n\", (int) vchData.size());\n            Misbehaving(pfrom->id, 1);\n            return false;\n        }\n\n        int64_t time;\n        memcpy(&time, &vchData[0], 8);\n\n        int64_t now = GetTime();\n        if (time > now + SMSG_TIME_LEEWAY)\n        {\n            printf(\"Warning: Peer buckets matched in the future: %d.\\nEither this node or the peer node has the incorrect time set.\\n\", (int32_t) time);\n            if (fDebugSmsg)\n                printf(\"Peer match time set to now.\\n\");\n            time = now;\n        }\n\n        pfrom->smsgData.lastMatched = time;\n\n        if (fDebugSmsg)\n            printf(\"Peer buckets matched at %d.\\n\", (int32_t) time);\n\n    } else\n    if (strCommand == \"smsgPing\")\n    {\n        // -- smsgPing is the initial message, send reply\n        pfrom->PushMessage(\"smsgPong\");\n    } else\n    if (strCommand == \"smsgPong\")\n    {\n        if (fDebugSmsg)\n             printf(\"Peer replied, secure messaging enabled.\\n\");\n\n        pfrom->smsgData.fEnabled = true;\n    } else\n    if (strCommand == \"smsgDisabled\")\n    {\n        // -- peer has disabled secure messaging.\n\n        pfrom->smsgData.fEnabled = false;\n\n        if (fDebugSmsg)\n            printf(\"Peer %u has disabled secure messaging.\\n\", pfrom->smsgData.nPeerId);\n\n    } else\n    if (strCommand == \"smsgIgnore\")\n    {\n        // -- peer is reporting that it will ignore this node until time.\n        //    Ignore peer too\n        std::vector<unsigned char> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 8)\n        {\n            printf(\"smsgIgnore, not enough data %d.\\n\", (int) vchData.size());\n            Misbehaving(pfrom->id, 1);\n            return false;\n        }\n\n        int64_t time;\n        memcpy(&time, &vchData[0], 8);\n\n        pfrom->smsgData.ignoreUntil = time;\n\n        if (fDebugSmsg)\n            printf(\"Peer %u is ignoring this node until %d, ignore peer too.\\n\", pfrom->smsgData.nPeerId, (int) time);\n    } else\n    {\n        // Unknown message\n    }\n\n    } //  LOCK(cs_smsg);\n\n    return true;\n}\n\nbool SecureMsgSendData(CNode* pto, bool fSendTrickle)\n{\n    /*\n        Called from ProcessMessage\n        Runs in ThreadMessageHandler2\n    */\n\n    //printf(\"SecureMsgSendData() %s.\\n\", pto->addrName.c_str());\n\n\n    int64_t now = GetTime();\n\n    if (pto->smsgData.lastSeen == 0)\n    {\n        // -- first contact\n        pto->smsgData.nPeerId = nPeerIdCounter++;\n        if (fDebugSmsg)\n            printf(\"SecureMsgSendData() new node %s, peer id %u.\\n\", pto->addrName.c_str(), pto->smsgData.nPeerId);\n        // -- Send smsgPing once, do nothing until receive 1st smsgPong (then set fEnabled)\n        pto->PushMessage(\"smsgPing\");\n        pto->smsgData.lastSeen = GetTime();\n        return true;\n    } else\n    if (!pto->smsgData.fEnabled\n        || now - pto->smsgData.lastSeen < SMSG_SEND_DELAY\n        || now < pto->smsgData.ignoreUntil)\n    {\n        return true;\n    }\n\n    // -- When nWakeCounter == 0, resend bucket inventory.\n    if (pto->smsgData.nWakeCounter < 1)\n    {\n        pto->smsgData.lastMatched = 0;\n        pto->smsgData.nWakeCounter = 10 + GetRandInt(300);  // set to a random time between [10, 300] * SMSG_SEND_DELAY seconds\n\n        if (fDebugSmsg)\n            printf(\"SecureMsgSendData(): nWakeCounter expired, sending bucket inventory to %s.\\n\"\n            \"Now %d next wake counter %u\\n\", pto->addrName.c_str(), (int32_t) now, pto->smsgData.nWakeCounter);\n    }\n    pto->smsgData.nWakeCounter--;\n\n    {\n        LOCK(cs_smsg);\n        std::map<int64_t, SecMsgBucket>::iterator it;\n\n        uint32_t nBuckets = smsgBuckets.size();\n        if (nBuckets > 0) // no need to send keep alive pkts, coin messages already do that\n        {\n            std::vector<unsigned char> vchData;\n            // should reserve?\n            vchData.reserve(4 + nBuckets*16); // timestamp + size + hash\n\n            uint32_t nBucketsShown = 0;\n            vchData.resize(4);\n\n            unsigned char* p = &vchData[4];\n            for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it)\n            {\n                SecMsgBucket &bkt = it->second;\n\n                uint32_t nMessages = bkt.setTokens.size();\n\n                if (bkt.timeChanged < pto->smsgData.lastMatched     // peer has this bucket\n                    || nMessages < 1)                               // this bucket is empty\n                    continue;\n\n\n                uint32_t hash = bkt.hash;\n\n                try { vchData.resize(vchData.size() + 16); } catch (std::exception& e)\n                {\n                    printf(\"vchData.resize %d threw: %s.\\n\", (int) vchData.size() + 16, e.what());\n                    continue;\n                }\n                memcpy(p, &it->first, 8);\n                memcpy(p+8, &nMessages, 4);\n                memcpy(p+12, &hash, 4);\n\n                p += 16;\n                nBucketsShown++;\n                //if (fDebug)\n                //    printf(\"Sending bucket %\"PRId64\", size %d \\n\", it->first, it->second.size());\n            }\n\n            if (vchData.size() > 4)\n            {\n                memcpy(&vchData[0], &nBucketsShown, 4);\n                if (fDebugSmsg)\n                    printf(\"Sending %d bucket headers.\\n\", nBucketsShown);\n\n                pto->PushMessage(\"smsgInv\", vchData);\n            }\n        }\n    }\n\n    pto->smsgData.lastSeen = GetTime();\n\n    return true;\n}\n\n\nstatic int SecureMsgInsertAddress(CKeyID& hashKey, CPubKey& pubKey, SecMsgDB& addrpkdb)\n{\n    /* insert key hash and public key to addressdb\n\n        should have LOCK(cs_smsg) where db is opened\n\n        returns\n            0 success\n            1 error\n            4 address is already in db\n    */\n\n\n    if (addrpkdb.ExistsPK(hashKey))\n    {\n        //printf(\"DB already contains public key for address.\\n\");\n        CPubKey cpkCheck;\n        if (!addrpkdb.ReadPK(hashKey, cpkCheck))\n        {\n            printf(\"addrpkdb.Read failed.\\n\");\n        } else\n        {\n            if (cpkCheck != pubKey)\n                printf(\"DB already contains existing public key that does not match .\\n\");\n        }\n        return 4;\n    }\n\n    if (!addrpkdb.WritePK(hashKey, pubKey))\n    {\n        printf(\"Write pair failed.\\n\");\n        return 1;\n    }\n    CBitcreditAddress address;\n    address.Set(hashKey);\n\tprintf(\"Add public key of %s to database\\n\", address.ToString().c_str());\n    return 0;\n}\n\nint SecureMsgInsertAddress(CKeyID& hashKey, CPubKey& pubKey)\n{\n    int rv;\n    {\n        LOCK(cs_smsgDB);\n        SecMsgDB addrpkdb;\n\n        if (!addrpkdb.Open(\"cr+\"))\n            return 1;\n\n        rv = SecureMsgInsertAddress(hashKey, pubKey, addrpkdb);\n    }\n    return rv;\n}\n\n\nstatic bool ScanBlock(CBlock& block, SecMsgDB& addrpkdb,\n    uint32_t& nTransactions, uint32_t& nInputs, uint32_t& nPubkeys, uint32_t& nDuplicates)\n{\n    // -- should have LOCK(cs_smsg) where db is opened\n    BOOST_FOREACH(const CTransaction& tx, block.vtx)\n    {\n        if (tx.IsCoinBase())\n            continue; // leave out coinbase\n\n\n        /*\n        Look at the inputs of every tx.\n        If the inputs are standard, get the pubkey from scriptsig and\n        look for the corresponding output (the input(output of other tx) to the input of this tx)\n        get the address from scriptPubKey\n        add to db if address is unique.\n\n        Would make more sense to do this the other way around, get address first for early out.\n\n        */\n\n        for (size_t i = 0; i < tx.vin.size(); i++)\n        {\n/*\n            TODO ???\n            if (tx.nVersion == ANON_TXN_VERSION\n                && tx.vin[i].IsAnonInput())\n                continue; // skip anon inputs\n*/\n            const CScript &script = tx.vin[i].scriptSig;\n\n            opcodetype opcode;\n            std::vector<unsigned char> vch;\n\n            uint256 prevoutHash, blockHash;\n\n            // -- matching address is in scriptPubKey of previous tx output\n            for (CScript::const_iterator pc = script.begin(); script.GetOp(pc, opcode, vch); )\n            {\n                // -- opcode is the length of the following data, compressed public key is always 33\n                if (opcode == 33)\n                {\n                    CPubKey pubKey(vch);\n\n                    if (!pubKey.IsValid())\n                    {\n                        printf(\"Public key is invalid %s.\\n\", HexStr(vch).c_str());\n                        continue;\n                    }\n\n                    prevoutHash = tx.vin[i].prevout.hash;\n                    CTransaction txOfPrevOutput;\n                    \n                    if (!GetTransaction(prevoutHash, txOfPrevOutput, blockHash, true))\n                    {\n                        printf(\"Could not get transaction %s (output %d) referenced by input #%d of transaction %s in block %s\\n\", prevoutHash.ToString().c_str(), tx.vin[i].prevout.n, (int) i, tx.GetHash().ToString().c_str(), block.GetHash().ToString().c_str());\n                        continue;\n                    }\n\n                    unsigned int nOut = tx.vin[i].prevout.n;\n                    if (nOut >= txOfPrevOutput.vout.size())\n                    {\n                        printf(\"Output %u, not in transaction: %s\\n\", nOut, prevoutHash.ToString().c_str());\n                        continue;\n                    }\n\n                    const CTxOut &txOut = txOfPrevOutput.vout[nOut];\n\n                    CTxDestination addressRet;\n                    if (!ExtractDestination(txOut.scriptPubKey, addressRet))\n                    {\n                        printf(\"ExtractDestination failed: %s\\n\", prevoutHash.ToString().c_str());\n                        continue;\n                    }\n\n                    CBitcreditAddress coinAddress(addressRet);\n                    CKeyID hashKey;\n                    if (!coinAddress.GetKeyID(hashKey))\n                    {\n                        printf(\"coinAddress.GetKeyID failed: %s\\n\", coinAddress.ToString().c_str());\n                        continue;\n                    }\n                    \n                    if (hashKey != pubKey.GetID())\n                        continue;\n\n                    int rv = SecureMsgInsertAddress(hashKey, pubKey, addrpkdb);\n                    nPubkeys += (rv == 0);\n                    nDuplicates += (rv == 4);\n                }\n\n                //printf(\"opcode %d, %s, value %s.\\n\", opcode, GetOpName(opcode), HexStr(vch).c_str());\n            }\n            nInputs++;\n        }\n        nTransactions++;\n\n        if (nTransactions % 10000 == 0) // for ScanChainForPublicKeys\n        {\n            printf(\"Scanning transaction no. %u.\\n\", nTransactions);\n        }\n    }\n    return true;\n}\n\n\nbool SecureMsgScanBlock(CBlock& block)\n{\n    /*\n    scan block for public key addresses\n    called from ProcessMessage() in main where strCommand == \"block\"\n    */\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgScanBlock().\\n\");\n\n    uint32_t nTransactions  = 0;\n    uint32_t nInputs        = 0;\n    uint32_t nPubkeys       = 0;\n    uint32_t nDuplicates    = 0;\n\n    {\n        LOCK(cs_smsgDB);\n\n        SecMsgDB addrpkdb;\n        if (!addrpkdb.Open(\"cw\")\n            || !addrpkdb.TxnBegin())\n            return false;\n\n        ScanBlock(block, addrpkdb,\n            nTransactions, nInputs, nPubkeys, nDuplicates);\n\n        addrpkdb.TxnCommit();\n    }\n\n    if (fDebugSmsg)\n        printf(\"Found %u transactions, %u inputs, %u new public keys, %u duplicates.\\n\", nTransactions, nInputs, nPubkeys, nDuplicates);\n\n    return true;\n}\n\nbool ScanChainForPublicKeys(CBlockIndex* pindexStart, size_t n)\n{\n    printf(\"Scanning block chain for public keys.\\n\");\n    int64_t nStart = GetTimeMillis();\n\n    if (fDebugSmsg)\n        printf(\"From height %u.\\n\", pindexStart->nHeight);\n\n    // -- public keys are in txin.scriptSig\n    //    matching addresses are in scriptPubKey of txin's referenced output\n\n    uint32_t nBlocks        = 0;\n    uint32_t nTransactions  = 0;\n    uint32_t nInputs        = 0;\n    uint32_t nPubkeys       = 0;\n    uint32_t nDuplicates    = 0;\n\n    {\n        LOCK(cs_smsgDB);\n\n        SecMsgDB addrpkdb;\n        if (!addrpkdb.Open(\"cw\")\n            || !addrpkdb.TxnBegin())\n            return false;\n\n        CBlockIndex* pindex = pindexStart;\n        for (size_t i = 0; pindex != NULL && i < n; i++, pindex = pindex->pprev)\n        {\n            nBlocks++;\n            CBlock block;\n            ReadBlockFromDisk(block, pindex);\n\n            ScanBlock(block, addrpkdb,\n                nTransactions, nInputs, nPubkeys, nDuplicates);\n        }\n\n        addrpkdb.TxnCommit();\n    }\n\n    printf(\"Scanned %u blocks, %u transactions, %u inputs\\n\", nBlocks, nTransactions, nInputs);\n    printf(\"Found %u public keys, %u duplicates.\\n\", nPubkeys, nDuplicates);\n    printf(\"Took %d ms\\n\", (int32_t)(GetTimeMillis() - nStart));\n\n    return true;\n}\n\nbool SecureMsgScanBlockChain()\n{\n    TRY_LOCK(cs_main, lockMain);\n    if (lockMain)\n    {\n        CBlockIndex *indexScan = chainActive.Tip();\n\n        try { // -- in try to catch errors opening db,\n            if (!ScanChainForPublicKeys(indexScan, indexScan->nHeight))\n                return false;\n        } catch (std::exception& e)\n        {\n            printf(\"ScanChainForPublicKeys() threw: %s.\\n\", e.what());\n            return false;\n        }\n    } else\n    {\n        printf(\"ScanChainForPublicKeys() Could not lock main.\\n\");\n        return false;\n    }\n\n    return true;\n}\n\nint SecureMsgScanBuckets(std::string &error, bool fDecrypt)\n{\n    if (fDebugSmsg)\n        printf(\"SecureMsgScanBuckets()\\n\");\n\n    if (!fSecMsgEnabled) {\n        error = \"Secure messaging is disabled.\";\n        return fDecrypt ? 0 : RPC_METHOD_NOT_FOUND;\n    }\n    if (pwalletMain->IsLocked()) {\n        error = \"Wallet is locked. Secure messaging needs an unlocked wallet.\";\n        return RPC_WALLET_UNLOCK_NEEDED;\n    }\n\n    int64_t  mStart         = GetTimeMillis();\n    int64_t  now            = GetTime();\n    uint32_t nFiles         = 0;\n    uint32_t nMessages      = 0;\n    uint32_t nFoundMessages = 0;\n\n    fs::path pathSmsgDir = GetDataDir() / \"smsgStore\";\n    fs::directory_iterator itend;\n\n    if (!fs::exists(pathSmsgDir) || !fs::is_directory(pathSmsgDir)) {\n        if (!fs::create_directory(pathSmsgDir)) {\n            error = \"Message store directory does not exist and could not be created.\";\n            return 1;\n        }\n    }\n\n    SecureMessage smsg;\n\n    for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd) {\n        if (!fs::is_regular_file(itd->status()))\n            continue;\n\n        std::string fileName = (*itd).path().filename().string();\n\n        if (!boost::algorithm::ends_with(fileName, fDecrypt ? \"_wl.dat\" : \".dat\"))\n            continue;\n\n        if (fDebugSmsg)\n            printf(\"Processing file: %s.\\n\", fileName.c_str());\n\n        nFiles++;\n\n        // TODO files must be split if > 2GB\n        // time_noFile.dat\n        size_t sep = fileName.find_first_of(\"_\");\n        if (sep == std::string::npos)\n            continue;\n\n        std::string stime = fileName.substr(0, sep);\n\n        int64_t fileTime = boost::lexical_cast<int64_t>(stime);\n\n        if (fileTime < now - SMSG_RETENTION) {\n            printf(\"Dropping file %s, expired.\\n\", fileName.c_str());\n            try {\n                fs::remove((*itd).path());\n            }\n            catch (const fs::filesystem_error& ex) {\n                printf(\"Error removing bucket file %s, %s.\\n\", fileName.c_str(), ex.what());\n            }\n            continue;\n        }\n\n        if (!fDecrypt && boost::algorithm::ends_with(fileName, \"_wl.dat\")) {\n            if (fDebugSmsg)\n                printf(\"Skipping wallet locked file: %s.\\n\", fileName.c_str());\n            continue;\n        }\n\n        {\n            LOCK(cs_smsg);\n            FILE *fp;\n            errno = 0;\n            if (!(fp = fopen((*itd).path().string().c_str(), \"rb\"))) {\n                printf(\"Error opening file: %s (%d)\\n\", strerror(errno), __LINE__);\n                continue;\n            }\n\n            for (;;) {\n                errno = 0;\n                if (fread(smsg.Header(), sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) {\n                    if (errno != 0) {\n                        printf(\"fread header failed: %s\\n\", strerror(errno));\n                    }\n                    else {\n                        //printf(\"End of file.\\n\");\n                    }\n                    break;\n                }\n\n                try {\n                    smsg.vchPayload.resize(smsg.nPayload);\n                }\n                catch (std::exception& e) {\n                    printf(\"SecureMsgWalletUnlocked(): Could not resize vchPayload, %u, %s\\n\", smsg.nPayload, e.what());\n                    fclose(fp);\n                    return 1;\n                }\n\n                if (fread(&smsg.vchPayload[0], 1, smsg.nPayload, fp) != smsg.nPayload) {\n                    printf(\"fread data failed: %s\\n\", strerror(errno));\n                    break;\n                }\n\n                // -- don't report to gui,\n                int rv = SecureMsgScanMessage(*smsg.Header(), &smsg.vchPayload[0], false);\n\n                if (rv == 0) {\n                    nFoundMessages++;\n                }\n                else if (rv != 0) {\n                    // SecureMsgScanMessage failed\n                }\n\n                nMessages ++;\n            }\n\n            fclose(fp);\n\n            // -- remove wl file when scanned\n            try {\n                fs::remove((*itd).path());\n            } catch (const boost::filesystem::filesystem_error& ex) {\n                printf(\"Error removing wl file %s - %s\\n\", fileName.c_str(), ex.what());\n                return 1;\n            }\n        }\n    }\n\n    printf(\"Processed %u files, scanned %u messages, received %u messages.\\n\", nFiles, nMessages, nFoundMessages);\n    printf(\"Took %d ms\\n\", (int)(GetTimeMillis() - mStart));\n    \n\t// -- notify gui\n    if (fDecrypt)\n        NotifySecMsgWalletUnlocked();\n    return 0;\n}\n\n\nint SecureMsgWalletKeyChanged(std::string sAddress, std::string sLabel, ChangeType mode)\n{\n    if (!fSecMsgEnabled)\n        return 0;\n\n    printf(\"SecureMsgWalletKeyChanged()\\n\");\n\n    // TODO: default recv and recvAnon\n\n    {\n        LOCK(cs_smsg);\n\n        switch(mode)\n        {\n            case CT_NEW:\n                smsgAddresses.push_back(SecMsgAddress(sAddress, smsgOptions.fNewAddressRecv, smsgOptions.fNewAddressAnon));\n                break;\n            case CT_DELETED:\n                for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)\n                {\n                    if (sAddress != it->sAddress)\n                        continue;\n                    smsgAddresses.erase(it);\n                    break;\n                }\n                break;\n            default:\n                break;\n        }\n\n    } // LOCK(cs_smsg);\n\n\n    return 0;\n}\n\nint SecureMsgScanMessage(const SecureMessageHeader &smsg, const unsigned char *pPayload, bool reportToGui)\n{\n    /*\n    Check if message belongs to this node.\n    If so add to inbox db.\n\n    if !reportToGui don't fire NotifySecMsgInboxChanged\n     - loads messages received when wallet locked in bulk.\n\n    returns\n        0 success,\n        1 error\n        2 no match\n        3 wallet is locked - message stored for scanning later.\n    */\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgScanMessage()\\n\");\n\n    if (pwalletMain->IsLocked())\n    {\n        if (fDebugSmsg)\n            printf(\"ScanMessage: Wallet is locked, storing message to scan later.\\n\");\n\n        int rv;\n        if ((rv = SecureMsgStoreUnscanned(smsg, pPayload)) != 0)\n            return 1;\n\n        return 3;\n    }\n\n    // -- Calculate hash of payload and enable verification of the HMAC\n    SecureMessageHeader header((const unsigned char*) smsg.begin());\n    memcpy(header.hash, Hash(&pPayload[0], &pPayload[smsg.nPayload]).begin(), 32);\n    \n    std::string addressTo;\n    MessageData msg; // placeholder\n    bool fOwnMessage = false;\n\n    for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)\n    {\n        if (!it->fReceiveEnabled)\n            continue;\n\n        CBitcreditAddress coinAddress(it->sAddress);\n        addressTo = coinAddress.ToString();\n\n        if (!it->fReceiveAnon)\n        {\n            // -- have to do full decrypt to see address from\n            if (SecureMsgDecrypt(false, addressTo, header, pPayload, msg) == 0)\n            {\n                if (fDebugSmsg)\n                    printf(\"%d: Decrypted message with %s.\\n\", __LINE__, addressTo.c_str());\n\n                if (msg.sFromAddress.compare(\"anon\") != 0)\n                    fOwnMessage = true;\n                break;\n            }\n        } else\n        {\n\n            if (SecureMsgDecrypt(true, addressTo, header, pPayload, msg) == 0)\n            {\n                if (fDebugSmsg)\n                    printf(\"%d: Decrypted message with %s.\\n\", __LINE__, addressTo.c_str());\n\n                fOwnMessage = true;\n                break;\n            }\n        }\n    }\n\n    if (fOwnMessage)\n    {\n        // -- save to inbox\n        std::string sPrefix(\"im\");\n        unsigned char chKey[18];\n        memcpy(&chKey[0],  sPrefix.data(),  2);\n        memcpy(&chKey[2],  &smsg.timestamp, 8);\n        memcpy(&chKey[10], pPayload,        8);\n\n        SecMsgStored smsgInbox;\n        smsgInbox.timeReceived  = GetTime();\n        smsgInbox.status        = (SMSG_MASK_UNREAD) & 0xFF;\n        smsgInbox.sAddrTo       = addressTo;\n\n        // -- data may not be contiguous\n        try {\n            smsgInbox.vchMessage.resize(SMSG_HDR_LEN + smsg.nPayload);\n        } catch (std::exception& e) {\n            printf(\"SecureMsgScanMessage(): Could not resize vchData, %u, %s\\n\", SMSG_HDR_LEN + smsg.nPayload, e.what());\n            return 1;\n        }\n        memcpy(&smsgInbox.vchMessage[0], smsg.begin(), SMSG_HDR_LEN);\n        memcpy(&smsgInbox.vchMessage[SMSG_HDR_LEN], pPayload, smsg.nPayload);\n\n        {\n            LOCK(cs_smsgDB);\n            SecMsgDB dbInbox;\n\n            if (dbInbox.Open(\"cw\"))\n            {\n                if (dbInbox.ExistsSmesg(chKey))\n                {\n                    if (fDebugSmsg)\n                        printf(\"Message already exists in inbox db.\\n\");\n                } else\n                {\n                    dbInbox.WriteSmesg(chKey, smsgInbox);\n\n                    if (reportToGui)\n                        NotifySecMsgInboxChanged(smsgInbox);\n                    printf(\"SecureMsg saved to inbox, received with %s.\\n\", addressTo.c_str());\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n\nint SecureMsgGetLocalKey(CKeyID& ckid, CPubKey& cpkOut)\n{\n    if (fDebugSmsg)\n        printf(\"SecureMsgGetLocalKey()\\n\");\n\n    CKey key;\n    if (!pwalletMain->GetKey(ckid, key))\n        return 4;\n\n    cpkOut = key.GetPubKey();\n    if (!cpkOut.IsValid()\n        || !cpkOut.IsCompressed())\n    {\n        printf(\"Public key is invalid %s.\\n\", HexStr(std::vector<unsigned char>(cpkOut.begin(), cpkOut.end())).c_str());\n        return 1;\n    }\n\n    return 0;\n}\n\nint SecureMsgGetLocalPublicKey(std::string& strAddress, std::string& strPublicKey)\n{\n    /* returns\n        0 success,\n        1 error\n        2 invalid address\n        3 address does not refer to a key\n        4 address not in wallet\n    */\n\n    CBitcreditAddress address;\n    if (!address.SetString(strAddress))\n        return 2; // Invalid coin address\n\n    CKeyID keyID;\n    if (!address.GetKeyID(keyID))\n        return 3;\n\n    int rv;\n    CPubKey pubKey;\n    if ((rv = SecureMsgGetLocalKey(keyID, pubKey)) != 0)\n        return rv;\n\n    strPublicKey = EncodeBase58(pubKey.begin(), pubKey.end());\n\n    return 0;\n}\n\nint SecureMsgGetStoredKey(CKeyID& ckid, CPubKey& cpkOut)\n{\n    /* returns\n        0 success,\n        1 error\n        2 public key not in database\n    */\n    if (fDebugSmsg)\n        printf(\"SecureMsgGetStoredKey().\\n\");\n\n    {\n        LOCK(cs_smsgDB);\n        SecMsgDB addrpkdb;\n\n        if (!addrpkdb.Open(\"r\")) {\n            printf(\"addrpkdb. Open() failed.\\n\");\n            return 1;\n        }\n\n        if (!addrpkdb.ReadPK(ckid, cpkOut))\n        {\n            CBitcreditAddress coinAddress;\n            coinAddress.Set(ckid);\n            printf(\"addrpkdb.Read failed: %s.\\n\", coinAddress.ToString().c_str());\n            return 2;\n        }\n    }\n    \n    if (fDebugSmsg) {\n        CBitcreditAddress coinAddress;\n        coinAddress.Set(ckid);\n        printf(\"SecureMsgGetStoredKey(): found public key of %s\\n\", coinAddress.ToString().c_str());\n    }\n    return 0;\n}\n\nint SecureMsgAddAddress(std::string& address, std::string& publicKey)\n{\n    /*\n        Add address and matching public key to the database\n        address and publicKey are in base58\n\n        returns\n            0 success\n            1 error\n            2 publicKey is invalid\n            3 publicKey != address\n            4 address is already in db\n            5 address is invalid\n    */\n\n    CBitcreditAddress coinAddress(address);\n\n    if (!coinAddress.IsValid())\n    {\n        printf(\"Address is not valid: %s.\\n\", address.c_str());\n        return 5;\n    }\n\n    CKeyID hashKey;\n\n    if (!coinAddress.GetKeyID(hashKey))\n    {\n        printf(\"coinAddress.GetKeyID failed: %s.\\n\", coinAddress.ToString().c_str());\n        return 5;\n    }\n\n    std::vector<unsigned char> vchTest;\n    DecodeBase58(publicKey, vchTest);\n    CPubKey pubKey(vchTest);\n\n    // -- check that public key matches address hash\n    CKeyID id; \n    CBitcreditAddress(address).GetKeyID(id);\n\n    if (pubKey.GetID() != id)\n    {\n        printf(\"Public key does not hash to address, addressT %s.\\n\", pubKey.GetID().ToString().c_str());\n        return 3;\n    }\n\n    return SecureMsgInsertAddress(hashKey, pubKey);\n}\n\nint SecureMsgRetrieve(SecMsgToken &token, SecureMessage &smsg)\n{\n    if (fDebugSmsg)\n        printf(\"SecureMsgRetrieve() %d.\\n\", (int32_t) token.timestamp);\n\n    // -- has cs_smsg lock from SecureMsgReceiveData\n\n    fs::path pathSmsgDir = GetDataDir() / \"smsgStore\";\n\n    int64_t bucket = token.timestamp - (token.timestamp % SMSG_BUCKET_LEN);\n    std::string fileName = boost::lexical_cast<std::string>(bucket) + \"_01.dat\";\n    fs::path fullpath = pathSmsgDir / fileName;\n\n    //printf(\"bucket %\"PRId64\".\\n\", bucket);\n    //printf(\"bucket lld %lld.\\n\", bucket);\n    //printf(\"fileName %s.\\n\", fileName.c_str());\n\n    FILE *fp;\n    if (!(fp = fopen(fullpath.string().c_str(), \"rb\"))) {\n        printf(\"Error opening file: %s\\nPath %s\\n\", strerror(errno), fullpath.string().c_str());\n        return 1;\n    }\n\n    if (fseek(fp, token.offset, SEEK_SET) != 0) {\n        printf(\"fseek, strerror: %s.\\n\", strerror(errno));\n        fclose(fp);\n        return 1;\n    }\n\n    if (fread(smsg.Header(), sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) {\n        printf(\"fread header failed: %s\\n\", strerror(errno));\n        fclose(fp);\n        return 1;\n    }\n\n    try {\n        smsg.vchPayload.resize(smsg.nPayload);\n    }\n    catch (std::exception& e) {\n        printf(\"SecureMsgRetrieve(): Could not resize vchPayload, %u, %s\\n\", smsg.nPayload, e.what());\n        return 1;\n    }\n\n    if (fread(&smsg.vchPayload[0], sizeof(unsigned char), smsg.nPayload, fp) != smsg.nPayload) {\n        printf(\"fread data failed: %s. Wanted %u bytes.\\n\", strerror(errno), smsg.nPayload);\n        fclose(fp);\n        return 1;\n    }\n\n\n    fclose(fp);\n\n    return 0;\n}\n\nint SecureMsgReceive(CNode* pfrom, std::vector<unsigned char>& vchData)\n{\n    if (fDebugSmsg)\n        printf(\"SecureMsgReceive().\\n\");\n\n    if (vchData.size() < 12) { // nBunch4 + timestamp8\n        printf(\"Error: not enough data.\\n\");\n        return 1;\n    }\n\n    uint32_t nBunch;\n    int64_t bktTime;\n\n    memcpy(&nBunch, &vchData[0], 4);\n    memcpy(&bktTime, &vchData[4], 8);\n\n\n    // -- check bktTime ()\n    //    bucket may not exist yet - will be created when messages are added\n    int64_t now = GetTime();\n    if (bktTime > now + SMSG_TIME_LEEWAY) {\n        if (fDebugSmsg)\n            printf(\"bktTime > now.\\n\");\n        // misbehave?\n        return 1;\n    }\n    else if (bktTime < now - SMSG_RETENTION) {\n        if (fDebugSmsg)\n            printf(\"bktTime < now - SMSG_RETENTION.\\n\");\n        // misbehave?\n        return 1;\n    }\n\n    std::map<int64_t, SecMsgBucket>::iterator itb;\n\n    if (nBunch == 0 || nBunch > 500) {\n        printf(\"Error: Invalid no. messages received in bunch %u, for bucket %d.\\n\", nBunch, (int32_t) bktTime);\n        Misbehaving(pfrom->id, 1);\n\n        // -- release lock on bucket if it exists\n        itb = smsgBuckets.find(bktTime);\n        if (itb != smsgBuckets.end())\n            itb->second.nLockCount = 0;\n        return 1;\n    }\n\n    uint32_t n = 12;\n\n    for (uint32_t i = 0; i < nBunch; ++i) {\n        if (vchData.size() - n < SMSG_HDR_LEN) {\n            printf(\"Error: not enough data sent, n = %u.\\n\", n);\n            break;\n        }\n\n        SecureMessageHeader header(&vchData[n]);\n\n        int rv = SecureMsgValidate(header, vchData.size() - n-SMSG_HDR_LEN);\n        if (rv != 0) {\n            Misbehaving(pfrom->id, 1);\n            continue;\n        }\n\n        // -- store message, but don't hash bucket\n        if (SecureMsgStore(header, &vchData[n + SMSG_HDR_LEN], false) != 0) {\n            // message dropped\n            break; // continue?\n        }\n        \n        if (SecureMsgScanMessage(header, &vchData[n + SMSG_HDR_LEN], true) != 0) {\n            // message recipient is not this node (or failed)\n        }\n\n        n += SMSG_HDR_LEN + header.nPayload;\n    }\n\n    // -- if messages have been added, bucket must exist now\n    itb = smsgBuckets.find(bktTime);\n    if (itb == smsgBuckets.end()) {\n        if (fDebugSmsg)\n            printf(\"Don't have bucket %d.\\n\", (int32_t) bktTime);\n        return 1;\n    }\n\n    itb->second.nLockCount  = 0; // this node has received data from peer, release lock\n    itb->second.nLockPeerId = 0;\n    itb->second.hashBucket();\n\n    return 0;\n}\n\nint SecureMsgStoreUnscanned(const SecureMessageHeader &header, const unsigned char *pPayload)\n{\n    /*\n    When the wallet is locked a copy of each received message is stored to be scanned later if wallet is unlocked\n    */\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgStoreUnscanned()\\n\");\n\n    if (!pPayload) {\n        printf(\"Error: null pointer to payload.\\n\");\n        return 1;\n    }\n\n    fs::path pathSmsgDir;\n    try {\n        pathSmsgDir = GetDataDir() / \"smsgStore\";\n        fs::create_directory(pathSmsgDir);\n    }\n    catch (const boost::filesystem::filesystem_error& ex) {\n        printf(\"Error: Failed to create directory %s - %s\\n\", pathSmsgDir.string().c_str(), ex.what());\n        return 1;\n    }\n\n    int64_t now = GetTime();\n    if (header.timestamp > now + SMSG_TIME_LEEWAY) {\n        printf(\"Message > now.\\n\");\n        return 1;\n    }\n    else if (header.timestamp < now - SMSG_RETENTION) {\n        printf(\"Message < SMSG_RETENTION.\\n\");\n        return 1;\n    }\n\n    int64_t bucket = header.timestamp - (header.timestamp % SMSG_BUCKET_LEN);\n\n    std::string fileName = boost::lexical_cast<std::string>(bucket) + \"_01_wl.dat\";\n    fs::path fullpath = pathSmsgDir / fileName;\n\n    FILE *fp;\n    if (!(fp = fopen(fullpath.string().c_str(), \"ab\"))) {\n        printf(\"Error opening file: %s (%d)\\n\", strerror(errno), __LINE__);\n        return 1;\n    }\n\n    if (fwrite(&header, sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN\n        || fwrite(pPayload, sizeof(unsigned char), header.nPayload, fp) != header.nPayload)\n    {\n        printf(\"fwrite failed: %s\\n\", strerror(errno));\n        fclose(fp);\n        return 1;\n    }\n\n    fclose(fp);\n\n    return 0;\n}\n\n\nint SecureMsgStore(const SecureMessageHeader &smsg, const unsigned char *pPayload, bool fUpdateBucket)\n{\n    if (fDebugSmsg)\n        printf(\"SecureMsgStore()\\n\");\n\n    if (!pPayload) {\n        printf(\"Error: null pointer to payload.\\n\");\n        return 1;\n    }\n\n\n    long int ofs;\n    fs::path pathSmsgDir;\n    try {\n        pathSmsgDir = GetDataDir() / \"smsgStore\";\n        fs::create_directory(pathSmsgDir);\n    }\n    catch (const boost::filesystem::filesystem_error& ex) {\n        printf(\"Error: Failed to create directory %s - %s\\n\", pathSmsgDir.string().c_str(), ex.what());\n        return 1;\n    }\n\n    int64_t now = GetTime();\n    if (smsg.timestamp > now + SMSG_TIME_LEEWAY) {\n        printf(\"Message > now.\\n\");\n        return 1;\n    }\n    else if (smsg.timestamp < now - SMSG_RETENTION) {\n        printf(\"Message < SMSG_RETENTION.\\n\");\n        return 1;\n    }\n\n    int64_t bucket = smsg.timestamp - (smsg.timestamp % SMSG_BUCKET_LEN);\n\n    {\n        // -- must lock cs_smsg before calling\n        //LOCK(cs_smsg);\n\n        SecMsgToken token(smsg.timestamp, pPayload, smsg.nPayload, 0);\n\n        std::set<SecMsgToken>& tokenSet = smsgBuckets[bucket].setTokens;\n        std::set<SecMsgToken>::iterator it;\n        it = tokenSet.find(token);\n        if (it != tokenSet.end())\n        {\n            printf(\"Already have message.\\n\");\n            if (fDebugSmsg)\n            {\n                printf(\"nPayload: %u\\n\", smsg.nPayload);\n                printf(\"bucket: %d\\n\", (int) bucket);\n\n                printf(\"message ts: %d\\n\", (int) token.timestamp);\n                std::vector<unsigned char> vchShow;\n                vchShow.resize(8);\n                memcpy(&vchShow[0], token.sample, 8);\n                printf(\" sample %s\\n\", HexStr(vchShow).c_str());\n                /*\n                printf(\"\\nmessages in bucket:\\n\");\n                for (it = tokenSet.begin(); it != tokenSet.end(); ++it)\n                {\n                    printf(\"message ts: %\"PRId64, (*it).timestamp);\n                    vchShow.resize(8);\n                    memcpy(&vchShow[0], (*it).sample, 8);\n                    printf(\" sample %s\\n\", HexStr(vchShow).c_str());\n                }\n                */\n            }\n            return 1;\n        }\n\n        std::string fileName = boost::lexical_cast<std::string>(bucket) + \"_01.dat\";\n        fs::path fullpath = pathSmsgDir / fileName;\n\n        FILE *fp;\n        if (!(fp = fopen(fullpath.string().c_str(), \"ab\")))\n        {\n            printf(\"Error opening file: %s (%d)\\n\", strerror(errno), __LINE__);\n            return 1;\n        }\n\n        // -- on windows ftell will always return 0 after fopen(ab), call fseek to set.\n        if (fseek(fp, 0, SEEK_END) != 0)\n        {\n            printf(\"Error fseek failed: %s\\n\", strerror(errno));\n            return 1;\n        }\n\n\n        ofs = ftell(fp);\n\n        if (fwrite(&smsg, sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN\n            || fwrite(pPayload, sizeof(unsigned char), smsg.nPayload, fp) != smsg.nPayload)\n        {\n            printf(\"fwrite failed: %s\\n\", strerror(errno));\n            fclose(fp);\n            return 1;\n        }\n\n        fclose(fp);\n\n        token.offset = ofs;\n\n        //printf(\"token.offset: %\"PRId64\"\\n\", token.offset); // DEBUG\n        tokenSet.insert(token);\n\n        if (fUpdateBucket)\n            smsgBuckets[bucket].hashBucket();\n    }\n\n    //if (fDebugSmsg)\n    printf(\"SecureMsg added to bucket %d.\\n\", (int) bucket);\n    return 0;\n}\n\nint SecureMsgStore(const SecureMessage& smsg, bool fUpdateBucket)\n{\n    return SecureMsgStore(smsg, &smsg.vchPayload[0], fUpdateBucket);\n}\n\nint SecureMsgValidate(const SecureMessageHeader &smsg_header, size_t nPayload)\n{\n    /*\n    returns\n        0 success\n        1 error\n        4 invalid version\n        5 payload is too large\n    */\n\n    if (smsg_header.nPayload != nPayload)\n        return 1;\n\n    if (smsg_header.nVersion != 1)\n        return 4;\n\n    if (smsg_header.nPayload > SMSG_MAX_MSG_WORST)\n        return 5;\n\n    return 0;\n}\n\n\nint SecureMsgEncrypt(SecureMessage& smsg, std::string& addressFrom, std::string& addressTo, std::string& message)\n{\n    /* Create a secure message\n\n        Using similar method to bitmessage.\n        If bitmessage is secure this should be too.\n        https://bitmessage.org/wiki/Encryption\n\n        Some differences:\n        bitmessage seems to use curve sect283r1\n        *coin addresses use secp256k1\n\n        returns\n            2       message is too long.\n            3       addressFrom is invalid.\n            4       addressTo is invalid.\n            5       Could not get public key for addressTo.\n            6       ECDH_compute_key failed\n            7       Could not get private key for addressFrom.\n            8       Could not allocate memory.\n            9       Could not compress message data.\n            10      Could not generate MAC.\n            11      Encrypt failed.\n    */\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgEncrypt(%s, %s, ...)\\n\", addressFrom.c_str(), addressTo.c_str());\n\n\n    if (message.size() > SMSG_MAX_MSG_BYTES) {\n        printf(\"Message is too long, %d.\\n\", (int) message.size());\n        return 2;\n    }\n\n    smsg.nVersion = 1;\n    smsg.timestamp = GetTime();\n\n\n    bool fSendAnonymous;\n    CBitcreditAddress coinAddrFrom;\n    CKeyID ckidFrom;\n    CKey keyFrom;\n\n    if (addressFrom.compare(\"anon\") == 0) {\n        fSendAnonymous = true;\n\n    }\n    else {\n        fSendAnonymous = false;\n\n        if (!coinAddrFrom.SetString(addressFrom)) {\n            printf(\"addressFrom is not valid.\\n\");\n            return 3;\n        }\n\n        if (!coinAddrFrom.GetKeyID(ckidFrom)) {\n            printf(\"coinAddrFrom.GetKeyID failed: %s.\\n\", coinAddrFrom.ToString().c_str());\n            return 3;\n        }\n    }\n\n\n    CBitcreditAddress coinAddrDest;\n    CKeyID ckidDest;\n\n    if (!coinAddrDest.SetString(addressTo)) {\n        printf(\"addressTo is not valid.\\n\");\n        return 4;\n    }\n\n    if (!coinAddrDest.GetKeyID(ckidDest)) {\n        printf(\"%d: coinAddrDest.GetKeyID failed: %s.\\n\", __LINE__, coinAddrDest.ToString().c_str());\n        return 4;\n    }\n\n    // -- public key K is the destination address\n    CPubKey cpkDestK;\n    if (SecureMsgGetStoredKey(ckidDest, cpkDestK) != 0\n        && SecureMsgGetLocalKey(ckidDest, cpkDestK) != 0) // maybe it's a local key (outbox?)\n    {\n        printf(\"Could not get public key for destination address.\\n\");\n        return 5;\n    }\n\n    // -- create save hash instances\n    secure_buffer sha_mem(sizeof(CSHA256) + sizeof(CSHA512) + sizeof(CHMAC_SHA256), 0);\n    CSHA256 &sha256 = *new (&sha_mem[0]) CSHA256();\n    CSHA512 &sha512 = *new (&sha256 + 1) CSHA512();\n\n    // -- make a key pair to which the receiver can respond\n    CKey keyS;\n    keyS.MakeNewKey(true); // make compressed key\n    CPubKey pubKeyS = keyS.GetPubKey();\n\n    // -- hash the timestamp and plaintext\n    uint256 msgHash;\n    sha256.Write((const unsigned char*) &smsg.timestamp, sizeof(smsg.timestamp)).\n           Write((const unsigned char*) &*message.begin(), message.size()).\n           Finalize(msgHash.begin());\n\n    // -- hash some entropy\n    secure_buffer vchKey(64+4, 0);\n    GetRandBytes(&vchKey[0], 16);\n    sha256.Write(&vchKey[0], 16);\n    sha256.Write(pubKeyS.begin(), 33);\n    sha256.Finalize(&vchKey[0]); // use this as key for hmac\n\n    // -- derive a new key pair, which is used for the encryption key computation\n    CKey keyR;\n    while (!keyR.IsValid()) {\n        CHMAC_SHA256 &hmac = *new (&sha512 + 1) CHMAC_SHA256(&vchKey[0], 32);\n        hmac.Write(&vchKey[64], 4); // prepend a counter\n        hmac.Write(keyS.begin(), 32);\n        hmac.Finalize(&vchKey[32]);\n        keyR.Set(&vchKey[32], &vchKey[64], true);\n        (*(uint32_t*) &vchKey[64])++;\n    }\n    \n    // -- Compute a shared secret vchP derived from a new private key keyR and the public key of addressTo\n    secure_buffer vchP;\n    memcpy(smsg.cpkR, &keyR.GetPubKey()[0], sizeof(smsg.cpkR)); // copy public key\n    if (!DeriveKey(vchP, keyR, cpkDestK))\n    {\n        printf(\"ECDH key computation failed\\n\");\n        return 6;\n    }   \n \n    // -- Use vchP and calculate the SHA512 hash H.\n    //    The first 32 bytes of H are called key_e (encryption key) and the last 32 bytes are called key_m (key for HMAC).\n    secure_buffer vchHashed(64); // 512 bit\n    sha512.Write(&vchP[0], vchP.size());\n    sha512.Finalize(&vchHashed[0]);\n    \n    \n    secure_buffer vchPayload;\n    secure_buffer vchCompressed;\n    unsigned char* pMsgData;\n    uint32_t lenMsgData;\n\n    uint32_t lenMsg = message.size();\n    if (lenMsg > 128)\n    {\n        // -- only compress if over 128 bytes\n        int worstCase = LZ4_compressBound(message.size());\n        try {\n            vchCompressed.resize(worstCase);\n        } catch (std::exception& e) {\n            printf(\"vchCompressed.resize %u threw: %s.\\n\", worstCase, e.what());\n            return 8;\n        }\n\n        int lenComp = LZ4_compress((char*)message.c_str(), (char*)&vchCompressed[0], lenMsg);\n        if (lenComp < 1)\n        {\n            printf(\"Could not compress message data.\\n\");\n            return 9;\n        }\n\n        pMsgData = &vchCompressed[0];\n        lenMsgData = lenComp;\n\n    } else\n    {\n        // -- no compression\n        pMsgData = (unsigned char*)message.c_str();\n        lenMsgData = lenMsg;\n    }\n\n    const unsigned int size = SMSG_PL_HDR_LEN + lenMsgData;\n    try {\n        vchPayload.resize(size);\n    }\n    catch (std::exception& e) {\n        printf(\"vchPayload.resize %u threw: %s.\\n\", size, e.what());\n        return 8;\n    }\n\n\t// -- create the payload header\n    PayloadHeader &header = *(PayloadHeader*) &vchPayload[0];\n    memcpy(header.lenPlain, &lenMsg, 4);\n    memcpy(&vchPayload[SMSG_PL_HDR_LEN], pMsgData, lenMsgData);\n    memcpy(header.cpkS, pubKeyS.begin(), sizeof(header.cpkS));\n    \n    if (fSendAnonymous) {\n        memset(header.sigKeyVersion, 0, 66);\n    }\n    else {\n        // -- compact signature proves ownership of from address and allows the public key to be recovered, recipient can always reply.\n        if (!pwalletMain->GetKey(ckidFrom, keyFrom))\n        {\n            printf(\"Could not get private key for addressFrom.\\n\");\n            return 7;\n        }\n        printf(\"private key of %s obtained\\n\", CBitcreditAddress(ckidFrom).ToString().c_str());\n\n        // -- sign the the new public key of keyR with the private key of addressFrom\n        std::vector<unsigned char> vchSignature(65);\n        keyFrom.SignCompact(msgHash, vchSignature);\n\n        header.sigKeyVersion[0] = ((CBitcreditAddress_B*) &coinAddrFrom)->getVersion(); // vchPayload[0] = coinAddrDest.nVersion;\n        memcpy(header.signature, &vchSignature[0], vchSignature.size());\n\n        memset(&vchSignature[0], 0, vchSignature.size());\n    }\n\n    // -- use first 16 bytes of hash of cpkR as IV, fill up with zero\n    //    less critical because the key shall be unique and the payload, too\n    std::vector<unsigned char> vchIV(WALLET_CRYPTO_KEY_SIZE, 0);\n    memcpy(&vchIV[0], Hash(smsg.cpkR, smsg.cpkR + sizeof(smsg.cpkR)).begin(), 16);\n\n    // -- Init crypter\n    CCrypter crypter;\n    crypter.SetKey(secure_buffer(vchHashed.begin(), vchHashed.begin()+32), vchIV);\n\n    // -- encrypt the plaintext\n    if (!crypter.Encrypt(vchPayload, smsg.vchPayload)) {\n        printf(\"crypter.Encrypt failed.\\n\");\n        return 11;\n    }\n    smsg.nPayload = smsg.vchPayload.size();\n    \n    // -- calculate hash of encrypted payload\n    memcpy(smsg.hash, Hash(&smsg.vchPayload[0], &smsg.vchPayload[smsg.nPayload]).begin(), 32);\n\n    // -- Calculate a 32 byte MAC with HMACSHA256, using key_m as salt\n    //    Message authentication code of the header\n    CHMAC_SHA256 hmac(&vchHashed[32], 32);\n    memcpy(smsg.mac, smsg.hash, 32);\n    hmac.Write(smsg.begin(), SMSG_HDR_LEN);\n    hmac.Finalize(smsg.mac);\n    \n    //TODO save the private key keyS\n    return 0;\n}\n\nint SecureMsgSend(std::string& addressFrom, std::string& addressTo, std::string& message, std::string& sError)\n{\n    /* Encrypt secure message, and place it on the network\n        Make a copy of the message to sender's first address and place in send queue db\n        proof of work thread will pick up messages from  send queue db\n\n    */\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgSend(%s, %s, ...)\\n\", addressFrom.c_str(), addressTo.c_str());\n\n    if (pwalletMain->IsLocked()) {\n        sError = \"Wallet is locked, wallet must be unlocked to send and receive messages.\";\n        return RPC_WALLET_UNLOCK_NEEDED;\n    }\n\n    SecureMessage smsg;\n    int rv = SecureMsgEncrypt(smsg, addressFrom, addressTo, message);\n\n    if (rv != 0)\n    {\n        printf(\"SecureMsgSend(), encrypt for recipient failed.\\n\");\n        std::ostringstream oss;\n\n        switch(rv)\n        {\n            case 2:\n                oss << \"Message size of \" << message.size() << \" bytes exceeds the maximum message length of \" << SMSG_MAX_MSG_BYTES << \" bytes.\";\n                sError = oss.str();\n                return RPC_INVALID_PARAMS;\n            case 3:\n                sError = \"Invalid addressFrom.\";\n                return RPC_INVALID_ADDRESS_OR_KEY; \n            case 4:\n                sError = \"Invalid addressTo.\";\n                return RPC_INVALID_ADDRESS_OR_KEY;\n            case 5:  sError = \"Could not get public key for addressTo.\";    break;\n            case 6:  sError = \"ECDH key computation failed.\";               break;\n            case 7:  sError = \"Could not get private key for addressFrom.\"; break;\n            case 8:\n                 sError = \"Could not allocate memory.\";\n                 return RPC_OUT_OF_MEMORY;\n            case 9:  sError = \"Could not compress message data.\";           break;\n            case 11: sError = \"Encrypt failed.\";                            break;\n            default: sError = \"Unspecified Error.\";                         break;\n        }\n\n        return rv;\n    }\n\n\n    // -- Place message in send queue, proof of work will happen in a thread.\n    std::string sPrefix(\"qm\");\n    unsigned char chKey[18];\n    memcpy(&chKey[0],  sPrefix.data(),      2);\n    memcpy(&chKey[2],  &smsg.timestamp,     8);\n    memcpy(&chKey[10], &smsg.vchPayload[0], 8);\n\n    SecMsgStored smsgSQ;\n\n    smsgSQ.timeReceived  = GetTime();\n    smsgSQ.sAddrTo       = addressTo;\n\n    try {\n        smsgSQ.vchMessage.resize(SMSG_HDR_LEN + smsg.nPayload);\n    } catch (std::exception& e) {\n        printf(\"smsgSQ.vchMessage.resize %u threw: %s.\\n\", SMSG_HDR_LEN + smsg.nPayload, e.what());\n        sError = \"Could not allocate memory.\";\n        return RPC_OUT_OF_MEMORY;\n    }\n\n    memcpy(&smsgSQ.vchMessage[0], smsg.begin(), SMSG_HDR_LEN);\n    memcpy(&smsgSQ.vchMessage[SMSG_HDR_LEN], &smsg.vchPayload[0], smsg.nPayload);\n\n    {\n        LOCK(cs_smsgDB);\n        SecMsgDB dbSendQueue;\n        if (dbSendQueue.Open(\"cw\"))\n        {\n            dbSendQueue.WriteSmesg(chKey, smsgSQ);\n            //NotifySecMsgSendQueueChanged(smsgOutbox);\n        }\n    }\n\n    //  -- for outbox create a copy encrypted for owned address\n    //     if the wallet is encrypted private key needed to decrypt will be unavailable\n\n    if (fDebugSmsg)\n        printf(\"Encrypting message for outbox.\\n\");\n\n    std::string addressOutbox = \"None\";\n    CBitcreditAddress coinAddrOutbox;\n\n    BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook)\n    {\n        // -- get first owned address\n        if (IsMine(*pwalletMain, entry.first) != ISMINE_SPENDABLE)\n            continue;\n        \n        coinAddrOutbox = entry.first;\n        addressOutbox = coinAddrOutbox.ToString();\n        break;\n    }\n\n    if (addressOutbox == \"None\")\n    {\n        printf(\"Warning: SecureMsgSend() could not find an address to encrypt outbox message with.\\n\");\n    } else\n    {\n        if (fDebugSmsg)\n            printf(\"Encrypting a copy for outbox, using address %s\\n\", addressOutbox.c_str());\n\n        SecureMessage smsgForOutbox;\n        if ((rv = SecureMsgEncrypt(smsgForOutbox, addressFrom, addressOutbox, message)) != 0)\n        {\n            printf(\"SecureMsgSend(), encrypt for outbox failed, %d.\\n\", rv);\n        } else\n        {\n            // -- save sent message to db\n            std::string sPrefix(\"sm\");\n            unsigned char chKey[18];\n            memcpy(&chKey[0],  sPrefix.data(),               2);\n            memcpy(&chKey[2],  &smsgForOutbox.timestamp,     8);\n            memcpy(&chKey[10], &smsgForOutbox.vchPayload[0], 8);   // sample\n\n            SecMsgStored smsgOutbox;\n\n            smsgOutbox.timeReceived  = GetTime();\n            smsgOutbox.sAddrTo       = addressTo;\n            smsgOutbox.sAddrOutbox   = addressOutbox;\n\n            try {\n                smsgOutbox.vchMessage.resize(SMSG_HDR_LEN + smsgForOutbox.nPayload);\n            } catch (std::exception& e) {\n                printf(\"smsgOutbox.vchMessage.resize %u threw: %s.\\n\", SMSG_HDR_LEN + smsgForOutbox.nPayload, e.what());\n                sError = \"Could not allocate memory.\";\n                return RPC_OUT_OF_MEMORY;\n            }\n            memcpy(&smsgOutbox.vchMessage[0], smsgForOutbox.begin(), SMSG_HDR_LEN);\n            memcpy(&smsgOutbox.vchMessage[SMSG_HDR_LEN], &smsgForOutbox.vchPayload[0], smsgForOutbox.nPayload);\n\n\n            {\n                LOCK(cs_smsgDB);\n                SecMsgDB dbSent;\n\n                if (dbSent.Open(\"cw\"))\n                {\n                    dbSent.WriteSmesg(chKey, smsgOutbox);\n                    NotifySecMsgOutboxChanged(smsgOutbox);\n                }\n            }\n        }\n    }\n\n    if (fDebugSmsg)\n        printf(\"Secure message queued for sending to %s.\\n\", addressTo.c_str());\n\n    return 0;\n}\n\n\nint SecureMsgDecrypt(bool fTestOnly, const std::string& address, const SecureMessageHeader &smsg, const unsigned char *pPayload, MessageData& msg) {\n\n    /* Decrypt secure message\n\n        address is the owned address to decrypt with.\n\n        validate first in SecureMsgValidate\n\n        returns\n            1       Error\n            2       Unknown version number\n            3       Decrypt address is not valid.\n            8       Could not allocate memory\n    */\n\n    if (fDebugSmsg)\n        printf(\"SecureMsgDecrypt(), using %s, testonly %d.\\n\", address.c_str(), fTestOnly);\n\n    if (smsg.nVersion != 1) {\n        printf(\"Unknown version number.\\n\");\n        return 2;\n    }\n\n    // -- Fetch private key k, used to decrypt\n    CBitcreditAddress coinAddrDest;\n    CKeyID ckidDest;\n    CKey keyDest;\n    if (!coinAddrDest.SetString(address))\n    {\n        printf(\"Address is not valid.\\n\");\n        return RPC_INVALID_ADDRESS_OR_KEY;\n    }\n    if (!coinAddrDest.GetKeyID(ckidDest)) {\n        printf(\"%d: coinAddrDest.GetKeyID failed: %s, %s.\\n\", __LINE__, coinAddrDest.ToString().c_str(), address.c_str());\n        return RPC_INVALID_ADDRESS_OR_KEY;\n    }\n    if (!pwalletMain->GetKey(ckidDest, keyDest)) {\n        printf(\"Could not get private key for addressDest.\\n\");\n        return 3;\n    }\n\n\n    CPubKey keyR(smsg.cpkR, smsg.cpkR+33);\n    if (!keyR.IsValid()) {\n        printf(\"Could not get compressed public key for key R.\\n\");\n        return 1;\n    }\n\n\n    // -- Do an EC point multiply with private key k and public key R. This gives you public EC key P.\n    secure_buffer vchP;\n    if (!DeriveKey(vchP, keyDest, keyR)) {\n        printf(\"ECDH key derivation failed\\n\");\n        return 1;\n    }\n\n\n    // -- Use public key P to calculate the SHA512 hash H.\n    //    The first 32 bytes of H are called key_e and the last 32 bytes are called key_m.\n    secure_buffer vchHashedDec(64); // 512 bits\n    secure_buffer sha512_mem(sizeof(CSHA512), 0);\n    CSHA512 &sha512 = *new (&sha512_mem[0]) CSHA512();\n    sha512.Write(&vchP[0], vchP.size());\n    sha512.Finalize(&vchHashedDec[0]);\n    sha512.~CSHA512();\n\n    // -- Message authentication code of header\n    SecureMessageHeader smsg_(smsg.begin());\n    memcpy(smsg_.mac, smsg.hash, 32);\n    unsigned char mac[32];\n    CHMAC_SHA256 hmac(&vchHashedDec[32], 32);\n    hmac.Write((const unsigned char*) smsg_.begin(), SMSG_HDR_LEN);\n    hmac.Finalize(mac);\n\n    if (memcmp(mac, smsg.mac, 32) != 0) {\n        if (fDebugSmsg)\n            printf(\"MAC does not match for address %s.\\n\", coinAddrDest.ToString().c_str()); // expected if message is not to address on node\n        return 1;\n    } \n\n    if (fTestOnly)\n        return 0;\n\n    std::vector<unsigned char> vchIV(WALLET_CRYPTO_KEY_SIZE, 0);\n    memcpy(&vchIV[0], Hash(smsg.cpkR, smsg.cpkR + sizeof(smsg.cpkR)).begin(), 16);\n\n    CCrypter crypter;\n    crypter.SetKey(secure_buffer(vchHashedDec.begin(), vchHashedDec.begin()+32), vchIV);\n    secure_buffer vchPayload;\n    if (!crypter.Decrypt(pPayload, smsg.nPayload, vchPayload)) {\n        printf(\"Decrypt failed.\\n\");\n        return 1;\n    }\n\n    PayloadHeader &header = *(PayloadHeader*) &vchPayload[0];\n    bool fFromAnonymous = (header.sigKeyVersion[0] == 0);\n    uint32_t lenData = vchPayload.size() - SMSG_PL_HDR_LEN;\n    uint32_t lenPlain;\n    memcpy(&lenPlain, header.lenPlain, 4);\n    unsigned char* pMsgData = &vchPayload[SMSG_PL_HDR_LEN];\n\n    try {\n        msg.sMessage.reserve(lenPlain + 1);\n        msg.sMessage.resize(lenPlain);\n    }\n    catch (std::exception& e) {\n        printf(\"msg.vchMessage.resize %u threw: %s.\\n\", lenPlain, e.what());\n        return 8;\n    }\n    char *message = &msg.sMessage[0];\n\n    if (lenPlain > 128) {\n        // -- decompress\n        if (LZ4_decompress_safe((char*) pMsgData, message, lenData, lenPlain) != (int) lenPlain) {\n            printf(\"Could not decompress message data.\\n\");\n            return 1;\n        }\n    }\n    else {\n        // -- plaintext\n        memcpy(message, pMsgData, lenPlain);\n    }\n\n    if (fFromAnonymous) {\n        // -- Anonymous sender\n        msg.sFromAddress = \"anon\";\n        printf(\"from anon\\n\");\n    }\n    else {\n        uint256 msgHash;\n        CSHA256().Write((const unsigned char*) &smsg.timestamp, 8).\n                  Write((const unsigned char*) message, lenPlain).\n                  Finalize(msgHash.begin());\n        \n        CPubKey cpkFromSig;\n        std::vector<unsigned char> vchSig(65, 0);\n        memcpy(&vchSig[0], header.signature, vchSig.size());\n        bool valid = cpkFromSig.RecoverCompact(msgHash, vchSig);\n        if (!valid) {\n            printf(\"Signature validation failed.\\n\");\n            return 1;\n        }\n        if (!cpkFromSig.IsCompressed())\n            printf(\"key is not compressed\\n\");\n\n\t\t// TODO check whether the public key is trusted\n        CKeyID ckidFrom(cpkFromSig.GetID());\n        int rv = 5;\n        try {\n            rv = SecureMsgInsertAddress(ckidFrom, cpkFromSig);\n        }\n        catch (std::exception& e) {\n            printf(\"SecureMsgInsertAddress(), exception: %s.\\n\", e.what());\n            //return 1;\n        }\n\n        switch(rv) {\n            case 0:\n                printf(\"Sender public key added to db.\\n\");\n                break;\n            case 4:\n                printf(\"Sender public key already in db.\\n\");\n                break;\n            default:\n                printf(\"Error adding sender public key to db.\\n\");\n                break;\n        }\n        \n        msg.sFromAddress = secure_string(CBitcreditAddress(ckidFrom).ToString().c_str());\n    }\n\n    msg.sToAddress = secure_string(address.c_str());\n    msg.timestamp = smsg.timestamp;\n    // TODO insert new public key and link it with cpkFromSig \n\n    if (fDebugSmsg)\n        printf(\"Decrypted message for %s: %s.\\n\", address.c_str(), msg.sMessage.c_str());\n\n    return 0;\n}\n\nint SecureMsgDecrypt(const SecMsgStored& smsgStored, MessageData &msg, std::string &errorMsg)\n{\n    SecureMessageHeader smsg(&smsgStored.vchMessage[0]);\n    const unsigned char* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];\n    memcpy(smsg.hash, Hash(&pPayload[0], &pPayload[smsg.nPayload]).begin(), 32);\n    int error = SecureMsgDecrypt(false, smsgStored.sAddrTo, smsg, pPayload, msg);\n    errorMsg = \"\";\n    return error;\n}\n", "meta": {"hexsha": "e9c894b4cc2045ee9209316f4b74fcfefd38b27d", "size": 98893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/smessage.cpp", "max_stars_repo_name": "coinkeeper/2015-06-22_19-17_bitcredits", "max_stars_repo_head_hexsha": "d4902d06d956c78bfdb80d0433c9953c206bd12f", "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/smessage.cpp", "max_issues_repo_name": "coinkeeper/2015-06-22_19-17_bitcredits", "max_issues_repo_head_hexsha": "d4902d06d956c78bfdb80d0433c9953c206bd12f", "max_issues_repo_licenses": ["MIT"], "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/smessage.cpp", "max_forks_repo_name": "coinkeeper/2015-06-22_19-17_bitcredits", "max_forks_repo_head_hexsha": "d4902d06d956c78bfdb80d0433c9953c206bd12f", "max_forks_repo_licenses": ["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.7960228985, "max_line_length": 262, "alphanum_fraction": 0.5486131475, "num_tokens": 25586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19071473022896027}}
{"text": "#include \"lwtnn/LightweightGraph.hh\"\n#include \"lwtnn/InputPreprocessor.hh\"\n#include \"lwtnn/Graph.hh\"\n#include <Eigen/Dense>\n\nnamespace {\n  using namespace Eigen;\n  using namespace lwt;\n\n  typedef LightweightGraph::NodeMap NodeMap;\n  typedef InputPreprocessor IP;\n  typedef std::vector<std::pair<std::string, IP*> > Preprocs;\n  typedef LightweightGraph::SeqNodeMap SeqNodeMap;\n  typedef InputVectorPreprocessor IVP;\n  typedef std::vector<std::pair<std::string, IVP*> > VecPreprocs;\n\n  // this is used internally to ensure that we only look up map inputs\n  // when the network asks for them.\n  class LazySource: public ISource\n  {\n  public:\n    LazySource(const NodeMap&, const SeqNodeMap&,\n               const Preprocs&, const VecPreprocs&);\n    virtual VectorXd at(size_t index) const;\n    virtual MatrixXd matrix_at(size_t index) const;\n  private:\n    const NodeMap& m_nodes;\n    const SeqNodeMap& m_seqs;\n    const Preprocs& m_preprocs;\n    const VecPreprocs& m_vec_preprocs;\n  };\n\n  LazySource::LazySource(const NodeMap& n, const SeqNodeMap& s,\n                         const Preprocs& p, const VecPreprocs& v):\n    m_nodes(n), m_seqs(s), m_preprocs(p), m_vec_preprocs(v)\n  {\n  }\n  VectorXd LazySource::at(size_t index) const\n  {\n    const auto& proc = m_preprocs.at(index);\n    if (!m_nodes.count(proc.first)) {\n      throw NNEvaluationException(\"Can't find node \" + proc.first);\n    }\n    const auto& preproc = *proc.second;\n    return preproc(m_nodes.at(proc.first));\n  }\n  MatrixXd LazySource::matrix_at(size_t index) const\n  {\n    const auto& proc = m_vec_preprocs.at(index);\n    if (!m_seqs.count(proc.first)) {\n      throw NNEvaluationException(\"Can't find sequence node \" + proc.first);\n    }\n    const auto& preproc = *proc.second;\n    return preproc(m_seqs.at(proc.first));\n  }\n\n}\nnamespace lwt {\n  // ______________________________________________________________________\n  // Lightweight Graph\n\n  typedef LightweightGraph::NodeMap NodeMap;\n  LightweightGraph::LightweightGraph(const GraphConfig& config,\n                                     std::string default_output):\n    m_graph(new Graph(config.nodes, config.layers))\n  {\n    for (const auto& node: config.inputs) {\n      m_preprocs.emplace_back(\n        node.name, new InputPreprocessor(node.variables));\n    }\n    for (const auto& node: config.input_sequences) {\n      m_vec_preprocs.emplace_back(\n        node.name, new InputVectorPreprocessor(node.variables));\n    }\n    size_t output_n = 0;\n    for (const auto& node: config.outputs) {\n      m_outputs.emplace_back(node.second.node_index, node.second.labels);\n      m_output_indices.emplace(node.first, output_n);\n      output_n++;\n    }\n    if (default_output.size() > 0) {\n      if (!m_output_indices.count(default_output)) {\n        throw NNConfigurationException(\"no output node\" + default_output);\n      }\n      m_default_output = m_output_indices.at(default_output);\n    } else if (output_n == 1) {\n      m_default_output = 0;\n    } else {\n      throw NNConfigurationException(\"you must specify a default output\");\n    }\n  }\n\n  LightweightGraph::~LightweightGraph() {\n    delete m_graph;\n    for (auto& preproc: m_preprocs) {\n      delete preproc.second;\n      preproc.second = 0;\n    }\n    for (auto& preproc: m_vec_preprocs) {\n      delete preproc.second;\n      preproc.second = 0;\n    }\n  }\n\n  ValueMap LightweightGraph::compute(const NodeMap& nodes,\n                                     const SeqNodeMap& seq) const {\n    return compute(nodes, seq, m_default_output);\n  }\n  ValueMap LightweightGraph::compute(const NodeMap& nodes,\n                                     const SeqNodeMap& seq,\n                                     const std::string& output) const {\n    if (!m_output_indices.count(output)) {\n      throw NNEvaluationException(\"no output node \" + output);\n    }\n    return compute(nodes, seq, m_output_indices.at(output));\n  }\n  ValueMap LightweightGraph::compute(const NodeMap& nodes,\n                                     const SeqNodeMap& seq,\n                                     size_t idx) const {\n    LazySource source(nodes, seq, m_preprocs, m_vec_preprocs);\n    VectorXd result = m_graph->compute(source, m_outputs.at(idx).first);\n    const std::vector<std::string>& labels = m_outputs.at(idx).second;\n    std::map<std::string, double> output;\n    for (size_t iii = 0; iii < labels.size(); iii++) {\n      output[labels.at(iii)] = result(iii);\n    }\n    return output;\n  }\n\n  VectorMap LightweightGraph::scan(const NodeMap& nodes,\n                                     const SeqNodeMap& seq) const {\n    return scan(nodes, seq, m_default_output);\n  }\n  VectorMap LightweightGraph::scan(const NodeMap& nodes,\n                                     const SeqNodeMap& seq,\n                                     const std::string& output) const {\n    if (!m_output_indices.count(output)) {\n      throw NNEvaluationException(\"no output node \" + output);\n    }\n    return scan(nodes, seq, m_output_indices.at(output));\n  }\n  VectorMap LightweightGraph::scan(const NodeMap& nodes,\n                                     const SeqNodeMap& seq,\n                                     size_t idx) const {\n    LazySource source(nodes, seq, m_preprocs, m_vec_preprocs);\n    MatrixXd result = m_graph->scan(source, m_outputs.at(idx).first);\n    const std::vector<std::string>& labels = m_outputs.at(idx).second;\n    std::map<std::string, std::vector<double> > output;\n    for (size_t iii = 0; iii < labels.size(); iii++) {\n      VectorXd row = result.row(iii);\n      std::vector<double> out_vector(row.data(), row.data() + row.size());\n      output[labels.at(iii)] = out_vector;\n    }\n    return output;\n  }\n\n}\n", "meta": {"hexsha": "a8adea0d46c3d07da1af2b8c96dafd3eb1a0ff51", "size": 5645, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/LightweightGraph.cxx", "max_stars_repo_name": "VukanJ/lwtnn", "max_stars_repo_head_hexsha": "7519b20994a1b8263612e9fb52f6e23f826412a7", "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/LightweightGraph.cxx", "max_issues_repo_name": "VukanJ/lwtnn", "max_issues_repo_head_hexsha": "7519b20994a1b8263612e9fb52f6e23f826412a7", "max_issues_repo_licenses": ["MIT"], "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/LightweightGraph.cxx", "max_forks_repo_name": "VukanJ/lwtnn", "max_forks_repo_head_hexsha": "7519b20994a1b8263612e9fb52f6e23f826412a7", "max_forks_repo_licenses": ["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.7278481013, "max_line_length": 76, "alphanum_fraction": 0.6389725421, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.1907147289505246}}
{"text": "// Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.\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, version 2.0,\n// as published by the Free Software Foundation.\n//\n// This program is also distributed with certain software (including\n// but not limited to OpenSSL) that is licensed under separate terms,\n// as designated in a particular file or component or in included license\n// documentation.  The authors of MySQL hereby grant you an additional\n// permission to link the program and your derivative works with the\n// separately licensed software that they have included with MySQL.\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, version 2.0, 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA.\n\n/// @file\n///\n/// Implements the distance_sphere functor and function.\n\n#include \"sql/gis/distance_sphere.h\"\n#include \"sql/gis/distance_sphere_functor.h\"\n\n#include <boost/geometry.hpp>\n#include <cmath>      // std::isinf, M_PI\n#include <stdexcept>  // std::overflow_error\n\n#include \"my_dbug.h\"                                // DBUG_ASSERT\n#include \"sql/dd/types/spatial_reference_system.h\"  // dd::Spatial_reference_system\n#include \"sql/gis/functor.h\"     // gis::Functor, gis::not_implemented_exception\n#include \"sql/gis/geometries.h\"  // gis::{Geometry{,_type}, Coordinate_system}\n#include \"sql/gis/geometries_cs.h\"      // gis::{Cartesian_*, Geographic_*}\n#include \"sql/gis/geometries_traits.h\"  // boost::geometry traits for gis types\n#include \"sql/sql_exception_handler.h\"  // handle_gis_exception\n\nnamespace bg = boost::geometry;\n\nnamespace gis {\n\n/// Map Cartesian geometry to geographic, mapping degrees east = x, degrees\n/// north = y. Do not canonicalize coordinates of poles.\n///\n/// Used when a SQL function needs to accept Cartesian coordiates as a shorthand\n/// for geographic with some default SRS.\nstatic Geographic_point reinterpret_as_degrees(const Cartesian_point &g) {\n  double lon_deg = g.x();\n  double lat_deg = g.y();\n\n  if (!(-180.0 < lon_deg && lon_deg <= 180.0))\n    throw longitude_out_of_range_exception(lon_deg, -180.0, 180.0);\n\n  if (!(-90.0 <= lat_deg && lat_deg <= 90.0))\n    throw latitude_out_of_range_exception(lat_deg, -90.0, 90.0);\n\n  return {lon_deg * M_PI / 180.0, lat_deg * M_PI / 180.0};\n}\n\n/// Map Cartesian geometry to geographic, mapping degrees east = x, degrees\n/// north = y. Do not canonicalize coordinates of poles.\n///\n/// Used when a SQL function needs to accept Cartesian coordiates as a shorthand\n/// for geographic with some default SRS.\nstatic Geographic_multipoint reinterpret_as_degrees(\n    const Cartesian_multipoint &g) {\n  Geographic_multipoint dg{};\n  for (auto const &point : g) {\n    dg.push_back(reinterpret_as_degrees(point));\n  }\n  return dg;\n}\n\ndouble Distance_sphere::operator()(const Geometry *g1,\n                                   const Geometry *g2) const {\n  return apply(*this, g1, g2);\n}\n\ndouble Distance_sphere::eval(const Cartesian_point *g1,\n                             const Cartesian_point *g2) const {\n  // The parser interprets SRID 0 coordinates as Cartesian. This is incorrect\n  // for distance_sphere that takes spherical coordinates in degrees.\n  // Convert to internal representation for geographic coordinates.\n  Geographic_point rg1 = reinterpret_as_degrees(*g1);\n  Geographic_point rg2 = reinterpret_as_degrees(*g2);\n  return eval(&rg1, &rg2);\n}\n\ndouble Distance_sphere::eval(const Cartesian_point *g1,\n                             const Cartesian_multipoint *g2) const {\n  // Distance is commutative.\n  return eval(g2, g1);\n}\n\ndouble Distance_sphere::eval(const Cartesian_multipoint *g1,\n                             const Cartesian_point *g2) const {\n  Geographic_multipoint rg1 = reinterpret_as_degrees(*g1);\n  Geographic_point rg2 = reinterpret_as_degrees(*g2);\n  return eval(&rg1, &rg2);\n}\n\ndouble Distance_sphere::eval(const Cartesian_multipoint *g1,\n                             const Cartesian_multipoint *g2) const {\n  Geographic_multipoint rg1 = reinterpret_as_degrees(*g1);\n  Geographic_multipoint rg2 = reinterpret_as_degrees(*g2);\n  return eval(&rg1, &rg2);\n}\n\ndouble Distance_sphere::eval(const Geographic_point *g1,\n                             const Geographic_point *g2) const {\n  return bg::distance(*g1, *g2, m_strategy);\n}\n\ndouble Distance_sphere::eval(const Geographic_point *g1,\n                             const Geographic_multipoint *g2) const {\n  return bg::distance(*g1, *g2, m_strategy);\n}\n\ndouble Distance_sphere::eval(const Geographic_multipoint *g1,\n                             const Geographic_point *g2) const {\n  return bg::distance(*g1, *g2, m_strategy);\n}\n\ndouble Distance_sphere::eval(const Geographic_multipoint *g1,\n                             const Geographic_multipoint *g2) const {\n  // Boost does not yet implement distance between two multipoints. Find\n  // minumum by iterating over multipoint-point distances.\n  double minimum = eval(g1, &(*g2)[0]);\n  for (size_t i = 1; i < g2->size(); i++) {\n    double d = eval(g1, &(*g2)[i]);\n    if (d < minimum) minimum = d;\n  }\n  return minimum;\n}\n\ndouble Distance_sphere::eval(const Geometry *g1, const Geometry *g2) const {\n  throw not_implemented_exception::for_non_projected(*g1, *g2);\n}\n\nbool distance_sphere(const dd::Spatial_reference_system *srs,\n                     const Geometry *g1, const Geometry *g2,\n                     const char *func_name, double sphere_radius,\n                     double *result, bool *result_null) noexcept {\n  try {\n    DBUG_ASSERT(g1->coordinate_system() == g2->coordinate_system());\n    DBUG_ASSERT(!srs || srs->is_cartesian() || srs->is_geographic());\n    DBUG_ASSERT(!srs || srs->is_cartesian() == (g1->coordinate_system() ==\n                                                Coordinate_system::kCartesian));\n    DBUG_ASSERT(!srs ||\n                srs->is_geographic() == (g1->coordinate_system() ==\n                                         Coordinate_system::kGeographic));\n\n    *result_null = false;\n\n    if (srs && srs->is_projected())\n      throw not_implemented_exception::for_projected(*g1, *g2);\n\n    *result = Distance_sphere{sphere_radius}(g1, g2);\n\n    if (std::isinf(*result)) throw std::overflow_error(\"INFINITY\");\n\n    return false;\n  } catch (...) {\n    handle_gis_exception(func_name);\n    return true;\n  }\n}\n\n}  // namespace gis\n", "meta": {"hexsha": "3e7e38a2008cb2b4abf1cf3dceeeeefc12055182", "size": 6745, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mysql-server/sql/gis/distance_sphere.cc", "max_stars_repo_name": "silenc3502/MYSQL-Arch-Doc-Summary", "max_stars_repo_head_hexsha": "fcc6bb65f72a385b9f56debc9b2c00cee5914bae", "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": "mysql-server/sql/gis/distance_sphere.cc", "max_issues_repo_name": "silenc3502/MYSQL-Arch-Doc-Summary", "max_issues_repo_head_hexsha": "fcc6bb65f72a385b9f56debc9b2c00cee5914bae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mysql-server/sql/gis/distance_sphere.cc", "max_forks_repo_name": "silenc3502/MYSQL-Arch-Doc-Summary", "max_forks_repo_head_hexsha": "fcc6bb65f72a385b9f56debc9b2c00cee5914bae", "max_forks_repo_licenses": ["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.7643678161, "max_line_length": 83, "alphanum_fraction": 0.6836174944, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19066667534484835}}
{"text": "#include <stdlib.h>\n#include <iostream>\n#include <boost/optional/optional_io.hpp>\n#include <boost/optional.hpp>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <string>\n\n#include \"snark.hpp\"\n#include \"utils.cpp\"\n\nusing namespace libsnark;\nusing namespace std;\n\nint genProof(r1cs_ppzksnark_proving_key<default_r1cs_ppzksnark_pp> provingKey_in, string proofFileName)\n{\n  int unsigned counter;\n  // Initialize bit_vectors for all of the variables involved.\n  bit_vector h_startBalance_bv;\n  bit_vector h_endBalance_bv;\n  bit_vector h_incoming_bv[noIncomingPayments];\n  bit_vector h_outgoing_bv[noOutgoingPayments];\n  bit_vector r_startBalance_bv;\n  bit_vector r_endBalance_bv;\n  bit_vector r_incoming_bv[noIncomingPayments];\n  bit_vector r_outgoing_bv[noOutgoingPayments];\n\n  vector<vector<unsigned long int>> publicValues = fillValuesFromfile(\"publicInputParameters_multi\");\n  h_startBalance_bv = int_list_to_bits_local(publicValues[0], 8);\n  h_endBalance_bv = int_list_to_bits_local(publicValues[1], 8);\n  for (counter = 0; counter < noIncomingPayments; counter++)\n  {\n    h_incoming_bv[counter] = int_list_to_bits_local(publicValues[counter+2], 8);\n  }\n\n  for (counter = 0; counter < noOutgoingPayments; counter++)\n  {\n    h_outgoing_bv[counter] = int_list_to_bits_local(publicValues[counter+2+noIncomingPayments], 8);\n  }\n\n  vector<vector<unsigned long int>> privateValues = fillValuesFromfile(\"privateInputParameters_multi\");\n  r_startBalance_bv = int_list_to_bits_local(privateValues[0], 8);\n  r_endBalance_bv = int_list_to_bits_local(privateValues[1], 8);\n  for (counter = 0; counter < noIncomingPayments; counter++)\n  {\n    r_incoming_bv[counter] = int_list_to_bits_local(privateValues[counter+2], 8);\n  }\n  for (counter = 0; counter < noOutgoingPayments; counter++)\n  {\n    r_outgoing_bv[counter] = int_list_to_bits_local(privateValues[counter+2+noIncomingPayments], 8);\n  }\n\n  boost::optional<libsnark::r1cs_ppzksnark_proof<libff::alt_bn128_pp>> proof = generate_payment_multi_proof<default_r1cs_ppzksnark_pp>(provingKey_in, h_startBalance_bv, h_endBalance_bv, h_incoming_bv, h_outgoing_bv, r_startBalance_bv, r_endBalance_bv, r_incoming_bv, r_outgoing_bv);\n\n  if(proof == boost::none)\n  {\n    return 1;\n  } else {\n    stringstream proofStream;\n    proofStream << proof;\n\n    ofstream fileOut;\n    fileOut.open(proofFileName);\n\n    fileOut << proofStream.rdbuf();\n    fileOut.close();\n    return 0;\n  }\n}\n\nint getUserInput(r1cs_ppzksnark_proving_key<default_r1cs_ppzksnark_pp> provingKey_in)\n{\n  string inputTemp = \"\";\n  int result=0;\n  cout << \"Press enter paymentId to generate a proof or q to quit\" << endl;\n  cin >> inputTemp;  \n  cout << \"Input from console: \" << inputTemp << endl;\n  if(inputTemp != \"q\")\n  {\n    result = genProof(provingKey_in, \"proof_multi_\" + inputTemp);\n    if(result!=0)\n    {\n      cout << \"There was an error generating the proof\" << endl;\n      return getUserInput(provingKey_in);\n    }\n    else\n    {\n      return getUserInput(provingKey_in);\n    }\n  }\n  else\n  {\n    return 0;\n  }\n}\n\nint main(int argc, char *argv[])\n{\n  string keyFileName = \"provingKey_multi\";\n\n  cout << \"Loading proving key\" << endl;\n\n  // Initialize the curve parameters.\n  default_r1cs_ppzksnark_pp::init_public_params();\n\n  r1cs_ppzksnark_proving_key<default_r1cs_ppzksnark_pp> provingKey_in;\n\n  ifstream fileIn(keyFileName);\n  stringstream provingKeyFromFile;\n  if (fileIn) {\n     provingKeyFromFile << fileIn.rdbuf();\n     fileIn.close();\n  }\n \n  provingKeyFromFile >> provingKey_in;\n\n  cout << \"Proving key loaded into memory\" << endl;\n\n  return getUserInput(provingKey_in);\n \n}\n", "meta": {"hexsha": "2eead2ba4be4c2db37064201805ba43fadceeb6e", "size": 3612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/payment_multi_generate_proof.cpp", "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/payment_multi_generate_proof.cpp", "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/payment_multi_generate_proof.cpp", "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": 29.3658536585, "max_line_length": 282, "alphanum_fraction": 0.7403100775, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.19061760439140193}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2015 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\n#include <boost/config.hpp>\n\n#ifndef BOOST_NO_CXX11_HDR_REGEX\n\n#include \"performance.hpp\"\n#include <regex>\n\nstruct std_regex : public abstract_regex\n{\nprivate:\n   std::regex e;\n   std::cmatch what;\npublic:\n   virtual bool set_expression(const char* pe, bool isperl)\n   {\n      try\n      {\n         e.assign(pe, isperl ? std::regex::ECMAScript : std::regex::extended);\n      }\n      catch(const std::exception&)\n      {\n         return false;\n      }\n      return true;\n   }\n   virtual bool match_test(const char* text);\n   virtual unsigned find_all(const char* text);\n   virtual std::string name();\n\n   struct initializer\n   {\n      initializer()\n      {\n         std_regex::register_instance(boost::shared_ptr<abstract_regex>(new std_regex));\n      }\n      void do_nothing()const {}\n   };\n   static const initializer init;\n};\n\nconst std_regex::initializer std_regex::init;\n\n\nbool std_regex::match_test(const char * text)\n{\n   return regex_match(text, what, e);\n}\n\nunsigned std_regex::find_all(const char * text)\n{\n   std::regex_iterator<const char*> i(text, text + std::strlen(text), e), j;\n   unsigned count = 0;\n   while(i != j)\n   {\n      ++i;\n      ++count;\n   }\n   return count;\n}\n\nstd::string std_regex::name()\n{\n   init.do_nothing();\n   return \"std::regex\";\n}\n\n#endif\n", "meta": {"hexsha": "9294acefb7552c43f0c54bf7b9a9358912dee37d", "size": 1526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/regex/performance/std.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/regex/performance/std.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/regex/performance/std.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": 20.6216216216, "max_line_length": 88, "alphanum_fraction": 0.6186107471, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.19061760439140193}}
{"text": "/********************************************************\n  Stanford Driving Software\n  Copyright (c) 2011 Stanford University\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with \n  or without modification, are permitted provided that the \n  following conditions are met:\n\n* Redistributions of source code must retain the above \n  copyright notice, this list of conditions and the \n  following disclaimer.\n* Redistributions in binary form must reproduce the above\n  copyright notice, this list of conditions and the \n  following disclaimer in the documentation and/or other\n  materials provided with the distribution.\n* The names of the contributors may not be used to endorse\n  or promote products derived from this software\n  without specific prior written permission.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n  CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \n  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \n  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n  DAMAGE.\n ********************************************************/\n\n\n#define DEBUG_LEVEL 0\n\n#include <float.h>\n#include <Eigen/Dense>\n#include <aw_roadNetworkSearch.h>\n#include <aw_lane.h>\n#include <aw_perimeterPoint.h>\n#include <aw_roadNetwork.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace vlr {\n\nnamespace rndf {\n\nRoadNetworkSearch::RoadNetworkSearch(RoadNetwork* rndf) :\n  rndf_(rndf) {\n  lane_tree_ = new LaneQuadTree(rndf, 1.0);\n}\n\nRoadNetworkSearch::~RoadNetworkSearch() {\n  delete lane_tree_;\n}\n\nRoadNetworkSearch::RoadNetworkSearch(const RoadNetworkSearch& rns, RoadNetwork* rndf) {\n  if (!rndf) {\n    rndf_ = rns.rndf_;\n  }\n  else {\n    rndf_ = rndf;\n  }\n\n  lane_tree_ = new LaneQuadTree(*rns.lane_tree_);\n}\n\nrndf::Lane* RoadNetworkSearch::closest_lane(double utm_x, double utm_y) const {\n  Lane* l;\n  double distance = DBL_MAX;\n  closest_lane(utm_x, utm_y, l, distance);\n  return l;\n}\n\nvoid RoadNetworkSearch::closest_lane(double utm_x, double utm_y, Lane*& l, double& distance) const {\n  LaneQuadTree::Element* closest_element = NULL;\n  Vector2d p(utm_x, utm_y);\n  Vector2d closest_point(DBL_MAX, DBL_MAX);\n  distance = DBL_MAX;\n  l = NULL;\n  if (!lane_tree_->search_nearest_neighbor(p, closest_element, distance, closest_point)) if (DEBUG_LEVEL > 0) fprintf(stderr,\n      \"BUG!!! RNDF NN SEARCH RETURNED FALSE!\\n\");\n  if (closest_element != NULL && closest_element->l != NULL) l = closest_element->l;\n  else if (DEBUG_LEVEL > 0) fprintf(stderr, \"BUG!!! CLOSEST ELEMENT / LANE IS NULL!\\n\");\n}\n\nbool RoadNetworkSearch::within_lane(double utm_x, double utm_y) const {\n  Lane* l = NULL;\n  double distance;\n  closest_lane(utm_x, utm_y, l, distance);\n  if (l == NULL) {\n    if (DEBUG_LEVEL > 0) fprintf(stderr, \"BUG!!!! LANE IS NULL!\\n\");\n    return false;\n  }\n  distance = sqrt(distance);\n  if (distance > 0.5 * l->laneWidth() + 0.5) return false;\n  else return true;\n}\n\nWayPoint* RoadNetworkSearch::closest_waypoint(double utm_x, double utm_y) {\n  double min_dist2 = DBL_MAX;\n  WayPoint* w = NULL;\n\n  const TWayPointMap& waypoints = rndf_->wayPoints();\n  TWayPointMap::const_iterator it, it_end;\n\n  for (it = waypoints.begin(), it_end = waypoints.end(); it != it_end; ++it) {\n    double x = utm_x - (*it).second->utmX();\n    double y = utm_y - (*it).second->utmY();\n    double dist2 = x * x + y * y;\n    if (dist2 < min_dist2) {\n      min_dist2 = dist2;\n      w = (*it).second;\n    }\n\n  }\n\n  return w;\n}\n\nPerimeterPoint* RoadNetworkSearch::closest_perimeterpoint(double utm_x, double utm_y) {\n  double min_dist2 = DBL_MAX;\n  PerimeterPoint* p = NULL;\n\n  const TPerimeterPointMap& perimeterpoints = rndf_->perimeterPoints();\n  TPerimeterPointMap::const_iterator it, it_end;\n\n  for (it = perimeterpoints.begin(), it_end = perimeterpoints.end(); it != it_end; ++it) {\n    double x = utm_x - (*it).second->utmX();\n    double y = utm_y - (*it).second->utmY();\n    double dist2 = x * x + y * y;\n    if (dist2 < min_dist2) {\n      min_dist2 = dist2;\n      p = (*it).second;\n    }\n  }\n\n  return p;\n}\n\nTrafficLight* RoadNetworkSearch::closestTrafficLight(double utm_x, double utm_y) {\n  double min_dist2 = DBL_MAX;\n  TrafficLight* tl = NULL;\n\n  const TTrafficLightMap& traffic_lights = rndf_->trafficLights();\n  TTrafficLightMap::const_iterator it, it_end;\n\n  for (it = traffic_lights.begin(), it_end = traffic_lights.end(); it != it_end; ++it) {\n    double x = utm_x - (*it).second->utmX();\n    double y = utm_y - (*it).second->utmY();\n    double dist2 = x * x + y * y;\n    if (dist2 < min_dist2) {\n      min_dist2 = dist2;\n      tl = (*it).second;\n    }\n  }\n\n  return tl;\n}\n\nCrosswalk* RoadNetworkSearch::closestCrosswalk(double utm_x, double utm_y) {\n  double min_dist2 = DBL_MAX;\n  Crosswalk* cw = NULL;\n\n  const TCrosswalkMap& crosswalks = rndf_->crosswalks();\n  TCrosswalkMap::const_iterator it, it_end;\n\n  for (it = crosswalks.begin(), it_end = crosswalks.end(); it != it_end; ++it) {\n    double center_x = 0.5 * ((*it).second->utmX1() + (*it).second->utmX2());\n    double center_y = 0.5 * ((*it).second->utmY1() + (*it).second->utmY2());\n    double x = utm_x - center_x;\n    double y = utm_y - center_y;\n    double dist2 = x * x + y * y;\n    if (dist2 < min_dist2) {\n      min_dist2 = dist2;\n      cw = (*it).second;\n    }\n  }\n\n  return cw;\n}\n} // namespace rndf\n\n} // namespace vlr\n\n", "meta": {"hexsha": "70b2fcd20d3f6026630a7b50df73240e5a0db7e8", "size": 5888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_rndf/src/aw_roadNetworkSearch.cpp", "max_stars_repo_name": "EatAllBugs/autonomous_learning", "max_stars_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T08:49:57.000Z", "max_issues_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_rndf/src/aw_roadNetworkSearch.cpp", "max_issues_repo_name": "yinflight/autonomous_learning", "max_issues_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_rndf/src/aw_roadNetworkSearch.cpp", "max_forks_repo_name": "yinflight/autonomous_learning", "max_forks_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T00:58:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T13:16:09.000Z", "avg_line_length": 30.5077720207, "max_line_length": 125, "alphanum_fraction": 0.6810461957, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34864512179822554, "lm_q1q2_score": 0.19061758959041245}}
{"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// File generated at Sat 27 Aug 2016 12:40:44\n\n/**\n * @file SSM_mass_eigenstates.hpp\n *\n * @brief contains class for model with routines needed to solve boundary\n *        value problem using the two_scale solver by solving EWSB\n *        and determine the pole masses and mixings\n *\n * This file was generated at Sat 27 Aug 2016 12:40:44 with FlexibleSUSY\n * 1.5.1 (git commit: 8356bacd26e8aecc6635607a32835d534ea3cf01) and SARAH 4.9.0 .\n */\n\n#ifndef SSM_MASS_EIGENSTATES_H\n#define SSM_MASS_EIGENSTATES_H\n\n#include \"SSM_two_scale_soft_parameters.hpp\"\n#include \"SSM_physical.hpp\"\n#include \"SSM_info.hpp\"\n#include \"two_loop_corrections.hpp\"\n#include \"problems.hpp\"\n#include \"config.h\"\n\n#include <iosfwd>\n#include <string>\n\n#ifdef ENABLE_THREADS\n#include <mutex>\n#endif\n\n#include <gsl/gsl_vector.h>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\n/**\n * @class SSM_mass_eigenstates\n * @brief model class with routines for determing masses and mixinga and EWSB\n */\nclass SSM_mass_eigenstates : public SSM_soft_parameters {\npublic:\n   explicit SSM_mass_eigenstates(const SSM_input_parameters& input_ = SSM_input_parameters());\n   virtual ~SSM_mass_eigenstates();\n\n   /// number of EWSB equations\n   static const std::size_t number_of_ewsb_equations = 2;\n\n   void calculate_DRbar_masses();\n   void calculate_DRbar_parameters();\n   void calculate_pole_masses();\n   void check_pole_masses_for_tachyons();\n   virtual void clear();\n   void clear_DRbar_parameters();\n   Eigen::ArrayXd get_DRbar_masses() const;\n   void do_calculate_sm_pole_masses(bool);\n   bool do_calculate_sm_pole_masses() const;\n   void do_force_output(bool);\n   bool do_force_output() const;\n   void reorder_DRbar_masses();\n   void reorder_pole_masses();\n   void set_ewsb_iteration_precision(double);\n   void set_ewsb_loop_order(unsigned);\n   void set_two_loop_corrections(const Two_loop_corrections&);\n   const Two_loop_corrections& get_two_loop_corrections() const;\n   void set_DRbar_masses(const Eigen::ArrayXd&);\n   void set_number_of_ewsb_iterations(std::size_t);\n   void set_number_of_mass_iterations(std::size_t);\n   std::size_t get_number_of_ewsb_iterations() const;\n   std::size_t get_number_of_mass_iterations() const;\n   void set_pole_mass_loop_order(unsigned);\n   unsigned get_pole_mass_loop_order() const;\n   void set_physical(const SSM_physical&);\n   double get_ewsb_iteration_precision() const;\n   double get_ewsb_loop_order() const;\n   const SSM_physical& get_physical() const;\n   SSM_physical& get_physical();\n   const Problems<SSM_info::NUMBER_OF_PARTICLES>& get_problems() const;\n   Problems<SSM_info::NUMBER_OF_PARTICLES>& get_problems();\n   int solve_ewsb_tree_level();\n   int solve_ewsb_one_loop();\n   int solve_ewsb();            ///< solve EWSB at ewsb_loop_order level\n\n   void calculate_spectrum();\n   void clear_problems();\n   std::string name() const;\n   void run_to(double scale, double eps = -1.0);\n   void print(std::ostream& out = std::cout) const;\n   void set_precision(double);\n   double get_precision() const;\n\n\n   double get_MVG() const { return MVG; }\n   double get_MHp() const { return MHp; }\n   const Eigen::Array<double,3,1>& get_MFv() const { return MFv; }\n   double get_MFv(int i) const { return MFv(i); }\n   double get_MAh() const { return MAh; }\n   const Eigen::Array<double,2,1>& get_Mhh() const { return Mhh; }\n   double get_Mhh(int i) const { return Mhh(i); }\n   const Eigen::Array<double,3,1>& get_MFd() const { return MFd; }\n   double get_MFd(int i) const { return MFd(i); }\n   const Eigen::Array<double,3,1>& get_MFu() const { return MFu; }\n   double get_MFu(int i) const { return MFu(i); }\n   const Eigen::Array<double,3,1>& get_MFe() const { return MFe; }\n   double get_MFe(int i) const { return MFe(i); }\n   double get_MVWp() const { return MVWp; }\n   double get_MVP() const { return MVP; }\n   double get_MVZ() const { return MVZ; }\n\n   \n\n   \n   const Eigen::Matrix<double,2,2>& get_ZH() const { return ZH; }\n   double get_ZH(int i, int k) const { return ZH(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Vd() const { return Vd; }\n   const std::complex<double>& get_Vd(int i, int k) const { return Vd(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Ud() const { return Ud; }\n   const std::complex<double>& get_Ud(int i, int k) const { return Ud(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Vu() const { return Vu; }\n   const std::complex<double>& get_Vu(int i, int k) const { return Vu(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Uu() const { return Uu; }\n   const std::complex<double>& get_Uu(int i, int k) const { return Uu(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Ve() const { return Ve; }\n   const std::complex<double>& get_Ve(int i, int k) const { return Ve(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Ue() const { return Ue; }\n   const std::complex<double>& get_Ue(int i, int k) const { return Ue(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZZ() const { return ZZ; }\n   double get_ZZ(int i, int k) const { return ZZ(i,k); }\n\n\n   double get_mass_matrix_VG() const;\n   void calculate_MVG();\n   double get_mass_matrix_Hp() const;\n   void calculate_MHp();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fv() const;\n   void calculate_MFv();\n   double get_mass_matrix_Ah() const;\n   void calculate_MAh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_hh() const;\n   void calculate_Mhh();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fd() const;\n   void calculate_MFd();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fu() const;\n   void calculate_MFu();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fe() const;\n   void calculate_MFe();\n   double get_mass_matrix_VWp() const;\n   void calculate_MVWp();\n   Eigen::Matrix<double,2,2> get_mass_matrix_VPVZ() const;\n   void calculate_MVPVZ();\n\n   double get_ewsb_eq_hh_1() const;\n   double get_ewsb_eq_hh_2() const;\n\n   std::complex<double> CpUhhAhAh(unsigned gO2) const;\n   double CpUhhVZVZ(unsigned gO2) const;\n   std::complex<double> CpUhhconjHpHp(unsigned gO2) const;\n   double CpUhhconjVWpVWp(unsigned gO2) const;\n   double CpUhhbargWpgWp(unsigned gO1) const;\n   double CpUhhbargWpCgWpC(unsigned gO1) const;\n   double CpUhhbargZgZ(unsigned gO1) const;\n   std::complex<double> CpUhhUhhAhAh(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhconjHpHp(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhVZAh(unsigned gO2) const;\n   double CpUhhconjVWpHp(unsigned gO2) const;\n   double CpUhhUhhconjVWpVWp(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhhhhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFdFdPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFdFdPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFeFePR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFeFePL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFuFuPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFuFuPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   double CpconjHpVWpVP() const;\n   double CpconjHpVZVWp() const;\n   double CpHpgWpCbargZ() const;\n   double CpconjHpbargWpCgZ() const;\n   double CpHpgZbargWp() const;\n   double CpconjHpbargZgWp() const;\n   double CpHpconjHpAhAh() const;\n   double CpHpconjHpconjHpHp() const;\n   std::complex<double> CpconjHpVWpAh() const;\n   double CpconjHpVPHp() const;\n   double CpconjHpVZHp() const;\n   double CpHpconjHpconjVWpVWp() const;\n   std::complex<double> CpHpconjHpVZVZ() const;\n   std::complex<double> CpHpconjHphhhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjHpbarFdFuPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjHpbarFdFuPL(unsigned gI1, unsigned gI2) const;\n   double CpconjHpbarFeFvPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjHpbarFeFvPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjHpHphh(unsigned gI2) const;\n   std::complex<double> CpconjHpVWphh(unsigned gI2) const;\n   std::complex<double> CpAhbargWpgWp() const;\n   std::complex<double> CpAhbargWpCgWpC() const;\n   double CpAhAhAhAh() const;\n   double CpAhAhconjHpHp() const;\n   std::complex<double> CpAhconjVWpHp() const;\n   double CpAhAhconjVWpVWp() const;\n   std::complex<double> CpAhAhVZVZ() const;\n   std::complex<double> CpAhhhAh(unsigned gI1) const;\n   std::complex<double> CpAhAhhhhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFdFdPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFdFdPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFeFePR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFeFePL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFuFuPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFuFuPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhVZhh(unsigned gI2) const;\n   double CpVZbargWpgWp() const;\n   double CpVZbargWpCgWpC() const;\n   double CpVZconjHpHp() const;\n   double CpVZconjVWpHp() const;\n   std::complex<double> CpVZVZAhAh() const;\n   std::complex<double> CpVZVZconjHpHp() const;\n   double CpVZconjVWpVWp() const;\n   std::complex<double> CpVZhhAh(unsigned gI1) const;\n   std::complex<double> CpVZVZhhhh(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFdFdPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFdFdPR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFeFePL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFeFePR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFuFuPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFuFuPR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFvFvPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFvFvPR(unsigned , unsigned ) const;\n   std::complex<double> CpVZVZhh(unsigned gI2) const;\n   double CpVZVZconjVWpVWp1() const;\n   double CpVZVZconjVWpVWp2() const;\n   double CpVZVZconjVWpVWp3() const;\n   std::complex<double> CpconjVWpHpAh() const;\n   double CpconjVWpVPHp() const;\n   double CpconjVWpVZHp() const;\n   double CpconjVWpbargPgWp() const;\n   double CpconjVWpbargWpCgP() const;\n   double CpconjVWpbargWpCgZ() const;\n   double CpconjVWpbargZgWp() const;\n   double CpVWpconjVWpAhAh() const;\n   double CpVWpconjVWpconjHpHp() const;\n   double CpconjVWpVWpVP() const;\n   double CpconjVWpVZVWp() const;\n   std::complex<double> CpVWpconjVWphhhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWpbarFdFuPL(unsigned gI1, unsigned gI2) const;\n   double CpconjVWpbarFdFuPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjVWpbarFeFvPL(unsigned gI1, unsigned gI2) const;\n   double CpconjVWpbarFeFvPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjVWpHphh(unsigned gI2) const;\n   std::complex<double> CpconjVWpVWphh(unsigned gI2) const;\n   double CpVWpconjVWpVPVP1() const;\n   double CpVWpconjVWpVPVP2() const;\n   double CpVWpconjVWpVPVP3() const;\n   double CpVWpconjVWpVZVZ1() const;\n   double CpVWpconjVWpVZVZ2() const;\n   double CpVWpconjVWpVZVZ3() const;\n   double CpVWpconjVWpconjVWpVWp1() const;\n   double CpVWpconjVWpconjVWpVWp2() const;\n   double CpVWpconjVWpconjVWpVWp3() const;\n   std::complex<double> CpbarUFdhhFdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdhhFdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdFdAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarUFdFdAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarUFdVGFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVGFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdVPFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVPFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdVZFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVZFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdconjHpFuPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdconjHpFuPR(unsigned gO1, unsigned gI2) const;\n   double CpbarUFdconjVWpFuPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarUFdconjVWpFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuhhFuPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuhhFuPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuFuAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarUFuFuAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarUFuHpFdPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuHpFdPR(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuVGFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVGFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuVPFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVPFuPL(unsigned gO1, unsigned gI2) const;\n   double CpbarUFuVWpFdPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarUFuVWpFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuVZFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVZFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFehhFePL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFehhFePR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFeFeAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarUFeFeAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarUFeVPFePR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFeVPFePL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFeVZFePR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFeVZFePL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFeconjHpFvPL(unsigned gO2, unsigned gI2) const;\n   double CpbarUFeconjHpFvPR(unsigned , unsigned ) const;\n   double CpbarUFeconjVWpFvPR(unsigned , unsigned ) const;\n   double CpbarUFeconjVWpFvPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFdhhFdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdhhFdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdFdAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarFdFdAhPR(unsigned gO1, unsigned gI1) const;\n   double CpbarFdVZFdPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFdVZFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFdconjHpFuPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarFdconjHpFuPR(unsigned gO1, unsigned gI2) const;\n   double CpbarFdconjVWpFuPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFdconjVWpFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFehhFePL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFehhFePR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFeFeAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarFeFeAhPR(unsigned gO1, unsigned gI1) const;\n   double CpbarFeVZFePR(unsigned gO2, unsigned gI2) const;\n   double CpbarFeVZFePL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFeconjHpFvPL(unsigned gO2, unsigned gI2) const;\n   double CpbarFeconjHpFvPR(unsigned , unsigned ) const;\n   double CpbarFeconjVWpFvPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFeconjVWpFvPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFuhhFuPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuhhFuPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuFuAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarFuFuAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarFuHpFdPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarFuHpFdPR(unsigned gO1, unsigned gI2) const;\n   double CpbarFuVPFuPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFuVPFuPL(unsigned gO1, unsigned gI2) const;\n   double CpbarFuVWpFdPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFuVWpFdPL(unsigned gO1, unsigned gI2) const;\n   double CpbarFuVZFuPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFuVZFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> self_energy_hh(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Hp(double p ) const;\n   std::complex<double> self_energy_Ah(double p ) const;\n   std::complex<double> self_energy_VZ(double p ) const;\n   std::complex<double> self_energy_VWp(double p ) const;\n   std::complex<double> self_energy_Fd_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_VZ_heavy(double p ) const;\n   std::complex<double> self_energy_VWp_heavy(double p ) const;\n   std::complex<double> self_energy_Fd_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> tadpole_hh(unsigned gO1) const;\n\n\n   /// calculates the tadpoles at current loop order\n   void tadpole_equations(double[number_of_ewsb_equations]) const;\n\n\n\n\n\n   void calculate_MVG_pole();\n   void calculate_MFv_pole();\n   void calculate_MVP_pole();\n   void calculate_MVZ_pole();\n   void calculate_Mhh_pole();\n   void calculate_MFd_pole();\n   void calculate_MFu_pole();\n   void calculate_MFe_pole();\n   void calculate_MVWp_pole();\n   double calculate_MVWp_pole(double);\n   double calculate_MVZ_pole(double);\n\n   double calculate_MFv_DRbar(double, int) const;\n   double calculate_MFe_DRbar(double, int) const;\n   double calculate_MFu_DRbar(double, int) const;\n   double calculate_MFd_DRbar(double, int) const;\n   double calculate_MVP_DRbar(double);\n   double calculate_MVZ_DRbar(double);\n   double calculate_MVWp_DRbar(double);\n\n   double Alpha() const;\n   double ThetaW() const;\n\n\nprivate:\n   struct EWSB_args {\n      SSM_mass_eigenstates* model;\n      unsigned ewsb_loop_order;\n   };\n\n#ifdef ENABLE_THREADS\n   struct Thread {\n      typedef void(SSM_mass_eigenstates::*Memfun_t)();\n      SSM_mass_eigenstates* model;\n      Memfun_t fun;\n\n      Thread(SSM_mass_eigenstates* model_, Memfun_t fun_)\n         : model(model_), fun(fun_) {}\n      void operator()() {\n         try {\n            (model->*fun)();\n         } catch (...) {\n            model->thread_exception = std::current_exception();\n         }\n      }\n   };\n#endif\n\n   std::size_t number_of_ewsb_iterations;\n   std::size_t number_of_mass_iterations;\n   unsigned ewsb_loop_order;\n   unsigned pole_mass_loop_order;\n   bool calculate_sm_pole_masses; ///< switch to calculate the pole masses of the Standard Model particles\n   bool force_output;             ///< switch to force output of pole masses\n   double precision;              ///< RG running precision\n   double ewsb_iteration_precision;\n   SSM_physical physical; ///< contains the pole masses and mixings\n   Problems<SSM_info::NUMBER_OF_PARTICLES> problems;\n   Two_loop_corrections two_loop_corrections; ///< used 2-loop corrections\n#ifdef ENABLE_THREADS\n   std::exception_ptr thread_exception;\n   static std::mutex mtx_fortran; /// locks fortran functions\n#endif\n\n   int solve_ewsb_iteratively();\n   int solve_ewsb_iteratively(unsigned);\n   int solve_ewsb_iteratively_with(EWSB_solver*, const double[number_of_ewsb_equations]);\n   int solve_ewsb_tree_level_custom();\n   void ewsb_initial_guess(double[number_of_ewsb_equations]);\n   int ewsb_step(double[number_of_ewsb_equations]) const;\n   static int ewsb_step(const gsl_vector*, void*, gsl_vector*);\n   static int tadpole_equations(const gsl_vector*, void*, gsl_vector*);\n   void copy_DRbar_masses_to_pole_masses();\n\n   // Passarino-Veltman loop functions\n   double A0(double) const;\n   double B0(double, double, double) const;\n   double B1(double, double, double) const;\n   double B00(double, double, double) const;\n   double B22(double, double, double) const;\n   double H0(double, double, double) const;\n   double F0(double, double, double) const;\n   double G0(double, double, double) const;\n\n   // DR-bar masses\n   double MVG;\n   double MHp;\n   Eigen::Array<double,3,1> MFv;\n   double MAh;\n   Eigen::Array<double,2,1> Mhh;\n   Eigen::Array<double,3,1> MFd;\n   Eigen::Array<double,3,1> MFu;\n   Eigen::Array<double,3,1> MFe;\n   double MVWp;\n   double MVP;\n   double MVZ;\n\n   // DR-bar mixing matrices\n   Eigen::Matrix<double,2,2> ZH;\n   Eigen::Matrix<std::complex<double>,3,3> Vd;\n   Eigen::Matrix<std::complex<double>,3,3> Ud;\n   Eigen::Matrix<std::complex<double>,3,3> Vu;\n   Eigen::Matrix<std::complex<double>,3,3> Uu;\n   Eigen::Matrix<std::complex<double>,3,3> Ve;\n   Eigen::Matrix<std::complex<double>,3,3> Ue;\n   Eigen::Matrix<double,2,2> ZZ;\n\n   // phases\n\n};\n\nstd::ostream& operator<<(std::ostream&, const SSM_mass_eigenstates&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "fa342c0aeaa42e5529665a994f8ce8dbdef1760a", "size": 23811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/SSM/SSM_mass_eigenstates.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/models/SSM/SSM_mass_eigenstates.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/models/SSM/SSM_mass_eigenstates.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": 47.244047619, "max_line_length": 106, "alphanum_fraction": 0.7397841334, "num_tokens": 7402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1906175844405901}}
{"text": "#ifndef HERMIT_SPIRIT_QI_IPV4_HPP\n#define HERMIT_SPIRIT_QI_IPV4_HPP\n\n#include <cstdint>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/fusion/adapted/std_pair.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\n#include <hermit/ip.hpp>\n\nnamespace hermit {\n  namespace spirit {\n    namespace qi {\n      template< typename Iterator >\n        class ipv4 : public boost::spirit::qi::grammar<\n          Iterator,\n          hermit::ipv4()\n        > {\n          public:\n            ipv4() : ipv4::base_type( root ) {\n              namespace qi = boost::spirit::qi;\n              namespace phx = boost::phoenix;\n              root = ( dec3_p >> '.' >> dec3_p >> '.' >> dec3_p >> '.' >> dec3_p )[\n                qi::_val =\n                  phx::static_cast_< uint32_t >( qi::_1 ) << 24|\n                  phx::static_cast_< uint32_t >( qi::_2 ) << 16|\n                  phx::static_cast_< uint32_t >( qi::_3 ) << 8|\n                  phx::static_cast_< uint32_t >( qi::_4 )\n                ];\n            }\n          private:\n            boost::spirit::qi::uint_parser<uint8_t, 10, 1, 3> dec3_p; \n            boost::spirit::qi::rule< Iterator, hermit::ipv4() > root;\n        };\n\n      template< typename Iterator >\n        class ipv4segment : public boost::spirit::qi::grammar<\n          Iterator,\n          std::pair< hermit::ipv4, hermit::ipv4 >()\n        > {\n          public:\n            ipv4segment() : ipv4segment::base_type( root ) {\n              namespace qi = boost::spirit::qi;\n              namespace phx = boost::phoenix;\n              root = ( ipv4address >> '/' >> dec2_p )[\n                phx::if_( qi::_2 <= 32 && qi::_2 > 0 )[\n                  phx::at_c< 1 >( qi::_val ) = 0xFFFFFFFFul ^ ( ( 1 << ( 32 - qi::_2 ) ) - 1 ),\n                  phx::if_( ( phx::at_c< 1 >( qi::_val ) & qi::_1 ) == qi::_1 )[\n                    phx::at_c< 0 >( qi::_val ) = qi::_1,\n                    qi::_pass = true\n                  ].else_[\n                    qi::_pass = false\n                  ]\n                ].else_[\n                  qi::_pass = false\n                ]\n              ];\n            }\n          private:\n            boost::spirit::qi::uint_parser<uint8_t, 10, 1, 2> dec2_p; \n            ipv4< Iterator > ipv4address;\n            boost::spirit::qi::rule< Iterator, std::pair< hermit::ipv4, hermit::ipv4 >() > root;\n        };\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "f818f84003de8cdfe1dcd91264930db0b9ed0e8e", "size": 2416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hermit/spirit/qi/ipv4.hpp", "max_stars_repo_name": "Fadis/hermit", "max_stars_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T05:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-09T05:54:01.000Z", "max_issues_repo_path": "include/hermit/spirit/qi/ipv4.hpp", "max_issues_repo_name": "Fadis/hermit", "max_issues_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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/hermit/spirit/qi/ipv4.hpp", "max_forks_repo_name": "Fadis/hermit", "max_forks_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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": 34.5142857143, "max_line_length": 96, "alphanum_fraction": 0.4730960265, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1906175844405901}}
{"text": "#include \"generator/affiliation.hpp\"\n\n#include \"platform/platform.hpp\"\n\n#include \"geometry/mercator.hpp\"\n\n#include \"base/thread_pool_computational.hpp\"\n\n#include <cmath>\n#include <functional>\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/register/ring.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n\nBOOST_GEOMETRY_REGISTER_POINT_2D(m2::PointD, double, boost::geometry::cs::cartesian, x, y);\nBOOST_GEOMETRY_REGISTER_RING(std::vector<m2::PointD>);\n\nnamespace feature\n{\nnamespace affiliation\n{\ntemplate <typename T>\nstruct RemoveCvref\n{\n  typedef std::remove_cv_t<std::remove_reference_t<T>> type;\n};\n\ntemplate <typename T>\nusing RemoveCvrefT = typename RemoveCvref<T>::type;\n\ntemplate <typename T>\nm2::RectD GetLimitRect(T && t)\n{\n  using Type = RemoveCvrefT<T>;\n  if constexpr(std::is_same_v<Type, FeatureBuilder>)\n    return t.GetLimitRect();\n  if constexpr(std::is_same_v<Type, m2::PointD>)\n    return m2::RectD(t, t);\n\n  UNREACHABLE();\n}\n\ntemplate <typename T, typename F>\nbool ForAnyPoint(T && t, F && f)\n{\n  using Type = RemoveCvrefT<T>;\n  if constexpr(std::is_same_v<Type, FeatureBuilder>)\n    return t.ForAnyPoint(std::forward<F>(f));\n  if constexpr(std::is_same_v<Type, m2::PointD>)\n    return f(std::forward<T>(t));\n\n  UNREACHABLE();\n}\n\ntemplate <typename T, typename F>\nvoid ForEachPoint(T && t, F && f)\n{\n  using Type = RemoveCvrefT<T>;\n  if constexpr(std::is_same_v<Type, FeatureBuilder>)\n    t.ForEachPoint(std::forward<F>(f));\n  else if constexpr(std::is_same_v<Type, m2::PointD>)\n    f(std::forward<T>(t));\n  else\n    UNREACHABLE();\n}\n\n// An implementation for CountriesFilesAffiliation class.\ntemplate <typename T>\nstd::vector<std::string> GetAffiliations(T const & t,\n                                         borders::CountryPolygonsCollection const & countryPolygonsTree,\n                                         bool haveBordersForWholeWorld)\n{\n  std::vector<std::string> countries;\n  std::vector<std::reference_wrapper<borders::CountryPolygons const>> countriesContainer;\n  countryPolygonsTree.ForEachCountryInRect(GetLimitRect(t), [&](auto const & countryPolygons) {\n    countriesContainer.emplace_back(countryPolygons);\n  });\n\n  // todo(m.andrianov): We need to explore this optimization better. There is a hypothesis: some\n  // elements belong to a rectangle, but do not belong to the exact boundary.\n  if (haveBordersForWholeWorld && countriesContainer.size() == 1)\n  {\n    borders::CountryPolygons const & countryPolygons = countriesContainer.front();\n    countries.emplace_back(countryPolygons.GetName());\n    return countries;\n  }\n\n  for (borders::CountryPolygons const & countryPolygons : countriesContainer)\n  {\n    auto const need = ForAnyPoint(t, [&](auto const & point) {\n      return countryPolygons.Contains(point);\n    });\n\n    if (need)\n      countries.emplace_back(countryPolygons.GetName());\n  }\n\n  return countries;\n}\n\n// An implementation for CountriesFilesIndexAffiliation class.\nusing IndexSharedPtr = std::shared_ptr<CountriesFilesIndexAffiliation::Tree>;\n\nCountriesFilesIndexAffiliation::Box MakeBox(m2::RectD const & rect)\n{\n  return {rect.LeftBottom(), rect.RightTop()};\n}\n\nstd::optional<std::string> IsOneCountryForLimitRect(m2::RectD const & limitRect,\n                                                    IndexSharedPtr const & index)\n{\n  borders::CountryPolygons const * country = nullptr;\n  std::vector<CountriesFilesIndexAffiliation::Value> values;\n  auto const bbox = MakeBox(limitRect);\n  boost::geometry::index::query(*index, boost::geometry::index::covers(bbox),\n                                std::back_inserter(values));\n  for (auto const & v : values)\n  {\n    for (borders::CountryPolygons const & c : v.second)\n    {\n      if (!country)\n        country = &c;\n      else if (country != &c)\n        return {};\n    }\n  }\n  return country ? country->GetName() : std::optional<std::string>{};\n}\n\ntemplate <typename T>\nstd::vector<std::string> GetHonestAffiliations(T && t, IndexSharedPtr const & index)\n{\n  std::vector<std::string> affiliations;\n  std::unordered_set<borders::CountryPolygons const *> countires;\n  ForEachPoint(t, [&](auto const & point) {\n    std::vector<CountriesFilesIndexAffiliation::Value> values;\n    boost::geometry::index::query(*index, boost::geometry::index::covers(point),\n                                  std::back_inserter(values));\n    for (auto const & v : values)\n    {\n      if (v.second.size() == 1)\n      {\n        borders::CountryPolygons const & cp = v.second.front();\n        if (countires.insert(&cp).second)\n          affiliations.emplace_back(cp.GetName());\n      }\n      else\n      {\n        for (borders::CountryPolygons const & cp : v.second)\n        {\n          if (cp.Contains(point) && countires.insert(&cp).second)\n            affiliations.emplace_back(cp.GetName());\n        }\n      }\n    }\n  });\n\n  return affiliations;\n}\n\ntemplate <typename T>\nstd::vector<std::string> GetAffiliations(T && t, IndexSharedPtr const & index)\n{\n  auto const oneCountry = IsOneCountryForLimitRect(GetLimitRect(t), index);\n  return oneCountry ? std::vector<std::string>{*oneCountry} : GetHonestAffiliations(t, index);\n}\n}  // namespace affiliation\n\nCountriesFilesAffiliation::CountriesFilesAffiliation(std::string const & borderPath, bool haveBordersForWholeWorld)\n  : m_countryPolygonsTree(borders::GetOrCreateCountryPolygonsTree(borderPath))\n  , m_haveBordersForWholeWorld(haveBordersForWholeWorld)\n{\n}\n\nstd::vector<std::string> CountriesFilesAffiliation::GetAffiliations(FeatureBuilder const & fb) const\n{\n  return affiliation::GetAffiliations(fb, m_countryPolygonsTree, m_haveBordersForWholeWorld);\n}\n\nstd::vector<std::string>\nCountriesFilesAffiliation::GetAffiliations(m2::PointD const & point) const\n{\n  return affiliation::GetAffiliations(point, m_countryPolygonsTree, m_haveBordersForWholeWorld);\n}\n\nbool CountriesFilesAffiliation::HasCountryByName(std::string const & name) const\n{\n  return m_countryPolygonsTree.HasRegionByName(name);\n}\n\nCountriesFilesIndexAffiliation::CountriesFilesIndexAffiliation(std::string const & borderPath,\n                                                               bool haveBordersForWholeWorld)\n  : CountriesFilesAffiliation(borderPath, haveBordersForWholeWorld)\n{\n  static std::mutex cacheMutex;\n  static std::unordered_map<std::string, std::shared_ptr<Tree>> cache;\n  auto const key = borderPath + std::to_string(haveBordersForWholeWorld);\n\n  std::lock_guard<std::mutex> lock(cacheMutex);\n\n  auto const it = cache.find(key);\n  if (it != std::cend(cache))\n  {\n    m_index = it->second;\n    return;\n  }\n\n  auto const net = generator::cells_merger::MakeNet(0.2 /* step */,\n                                                    mercator::Bounds::kMinX, mercator::Bounds::kMinY,\n                                                    mercator::Bounds::kMaxX, mercator::Bounds::kMaxY);\n  auto const index = BuildIndex(net);\n  m_index = index;\n  cache.emplace(key, index);\n}\n\nstd::vector<std::string> CountriesFilesIndexAffiliation::GetAffiliations(FeatureBuilder const & fb) const\n{\n  return affiliation::GetAffiliations(fb, m_index);\n}\n\nstd::vector<std::string> CountriesFilesIndexAffiliation::GetAffiliations(m2::PointD const & point) const\n{\n  return affiliation::GetAffiliations(point, m_index);\n}\n\nstd::shared_ptr<CountriesFilesIndexAffiliation::Tree>\nCountriesFilesIndexAffiliation::BuildIndex(const std::vector<m2::RectD> & net)\n{\n  std::unordered_map<borders::CountryPolygons const *, std::vector<m2::RectD>> countriesRects;\n  std::mutex countriesRectsMutex;\n  std::vector<Value> treeCells;\n  std::mutex treeCellsMutex;\n  auto const numThreads = GetPlatform().CpuCores();\n  {\n    base::thread_pool::computational::ThreadPool pool(numThreads);\n    for (auto const & rect : net)\n    {\n      pool.SubmitWork([&, rect]() {\n        std::vector<std::reference_wrapper<borders::CountryPolygons const>> countries;\n        m_countryPolygonsTree.ForEachCountryInRect(rect, [&](auto const & country) {\n          countries.emplace_back(country);\n        });\n        if (m_haveBordersForWholeWorld && countries.size() == 1)\n        {\n          borders::CountryPolygons const & country = countries.front();\n          std::lock_guard<std::mutex> lock(countriesRectsMutex);\n          countriesRects[&country].emplace_back(rect);\n        }\n        else\n        {\n          auto const box = affiliation::MakeBox(rect);\n          std::vector<std::reference_wrapper<borders::CountryPolygons const>> interCountries;\n          for (borders::CountryPolygons const & cp : countries)\n          {\n            cp.ForAnyPolygon([&](auto const & polygon) {\n              if (!boost::geometry::intersects(polygon.Data(), box))\n                return false;\n              interCountries.emplace_back(cp);\n              return true;\n            });\n          }\n          if (interCountries.empty())\n            return;\n          if (interCountries.size() == 1)\n          {\n            borders::CountryPolygons const & country = interCountries.front();\n            std::lock_guard<std::mutex> lock(countriesRectsMutex);\n            countriesRects[&country].emplace_back(rect);\n          }\n          else\n          {\n            std::lock_guard<std::mutex> lock(treeCellsMutex);\n            treeCells.emplace_back(box, std::move(interCountries));\n          }\n        }\n      });\n    }\n  }\n  {\n    base::thread_pool::computational::ThreadPool pool(numThreads);\n    for (auto & pair : countriesRects)\n    {\n      pool.SubmitWork([&, countryPtr{pair.first}, rects{std::move(pair.second)}]() mutable {\n        generator::cells_merger::CellsMerger merger(std::move(rects));\n        auto const merged = merger.Merge();\n        for (auto const & rect : merged)\n        {\n          std::vector<std::reference_wrapper<borders::CountryPolygons const>> interCountries{*countryPtr};\n          std::lock_guard<std::mutex> lock(treeCellsMutex);\n          treeCells.emplace_back(affiliation::MakeBox(rect), std::move(interCountries));\n        }\n      });\n    }\n  }\n  return std::make_shared<Tree>(treeCells);\n}\n\nSingleAffiliation::SingleAffiliation(std::string const & filename)\n  : m_filename(filename)\n{\n}\n\nstd::vector<std::string> SingleAffiliation::GetAffiliations(FeatureBuilder const &) const\n{\n  return {m_filename};\n}\n\nbool SingleAffiliation::HasCountryByName(std::string const & name) const\n{\n  return name == m_filename;\n}\n\nstd::vector<std::string>\nSingleAffiliation::GetAffiliations(m2::PointD const &) const\n{\n  return {m_filename};\n}\n}  // namespace feature\n", "meta": {"hexsha": "f638b6ad78f7d1f8cd61a9962146c79fd10f5d51", "size": 10585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generator/affiliation.cpp", "max_stars_repo_name": "dualword/organicmaps", "max_stars_repo_head_hexsha": "c0a73aea4835517edef3b5a7d68a3a50d55a4471", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-18T17:26:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:26:50.000Z", "max_issues_repo_path": "generator/affiliation.cpp", "max_issues_repo_name": "dualword/organicmaps", "max_issues_repo_head_hexsha": "c0a73aea4835517edef3b5a7d68a3a50d55a4471", "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": "generator/affiliation.cpp", "max_forks_repo_name": "dualword/organicmaps", "max_forks_repo_head_hexsha": "c0a73aea4835517edef3b5a7d68a3a50d55a4471", "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.7708978328, "max_line_length": 115, "alphanum_fraction": 0.674350496, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.19056991096979806}}
{"text": "// Copyright (C) 2011-2012 by the Bem++ 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 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#ifndef fiber_default_local_assembler_for_integral_operators_on_surfaces_hpp\n#define fiber_default_local_assembler_for_integral_operators_on_surfaces_hpp\n\n#include \"../common/common.hpp\"\n\n#include \"local_assembler_for_integral_operators.hpp\"\n\n#include \"_2d_array.hpp\"\n#include \"accuracy_options.hpp\"\n#include \"default_local_assembler_for_operators_on_surfaces_utilities.hpp\"\n#include \"element_pair_topology.hpp\"\n#include \"numerical_quadrature.hpp\"\n#include \"parallelization_options.hpp\"\n#include \"shared_ptr.hpp\"\n#include \"test_kernel_trial_integrator.hpp\"\n#include \"verbosity_level.hpp\"\n\n#include <boost/static_assert.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <tbb/concurrent_unordered_map.h>\n#include <tbb/mutex.h>\n#include <cstring>\n#include <climits>\n#include <set>\n#include <utility>\n#include <vector>\n\nnamespace Fiber {\n\n/** \\cond FORWARD_DECL */\nclass OpenClHandler;\ntemplate <typename CoordinateType> class CollectionOfShapesetTransformations;\ntemplate <typename ValueType> class CollectionOfKernels;\ntemplate <typename BasisFunctionType, typename KernelType, typename ResultType>\nclass TestKernelTrialIntegral;\n\ntemplate <typename CoordinateType> class RawGridGeometry;\n\ntemplate <typename CoordinateType>\nclass QuadratureDescriptorSelectorForIntegralOperators;\ntemplate <typename CoordinateType> class DoubleQuadratureRuleFamily;\n/** \\endcond */\n\ntemplate <typename BasisFunctionType, typename KernelType, typename ResultType,\n          typename GeometryFactory>\nclass DefaultLocalAssemblerForIntegralOperatorsOnSurfaces\n    : public LocalAssemblerForIntegralOperators<ResultType> {\npublic:\n  typedef typename ScalarTraits<ResultType>::RealType CoordinateType;\n\n  DefaultLocalAssemblerForIntegralOperatorsOnSurfaces(\n      const shared_ptr<const GeometryFactory> &testGeometryFactory,\n      const shared_ptr<const GeometryFactory> &trialGeometryFactory,\n      const shared_ptr<const RawGridGeometry<CoordinateType>> &testRawGeometry,\n      const shared_ptr<const RawGridGeometry<CoordinateType>> &trialRawGeometry,\n      const shared_ptr<const std::vector<const Shapeset<BasisFunctionType> *>> &\n          testShapesets,\n      const shared_ptr<const std::vector<const Shapeset<BasisFunctionType> *>> &\n          trialShapesets,\n      const shared_ptr<const CollectionOfShapesetTransformations<\n          CoordinateType>> &testTransformations,\n      const shared_ptr<const CollectionOfKernels<KernelType>> &kernel,\n      const shared_ptr<const CollectionOfShapesetTransformations<\n          CoordinateType>> &trialTransformations,\n      const shared_ptr<const TestKernelTrialIntegral<\n          BasisFunctionType, KernelType, ResultType>> &integral,\n      const shared_ptr<const OpenClHandler> &openClHandler,\n      const ParallelizationOptions &parallelizationOptions,\n      VerbosityLevel::Level verbosityLevel, bool cacheSingularIntegrals,\n      const shared_ptr<const QuadratureDescriptorSelectorForIntegralOperators<\n          CoordinateType>> &quadDescSelector,\n      const shared_ptr<const DoubleQuadratureRuleFamily<CoordinateType>> &\n          quadRuleFamily);\n  virtual ~DefaultLocalAssemblerForIntegralOperatorsOnSurfaces();\n\npublic:\n  virtual void\n  evaluateLocalWeakForms(CallVariant callVariant,\n                         const std::vector<int> &elementIndicesA,\n                         int elementIndexB, LocalDofIndex localDofIndexB,\n                         std::vector<arma::Mat<ResultType>> &result,\n                         CoordinateType nominalDistance = -1.);\n\n  virtual void\n  evaluateLocalWeakForms(const std::vector<int> &testElementIndices,\n                         const std::vector<int> &trialElementIndices,\n                         Fiber::_2dArray<arma::Mat<ResultType>> &result,\n                         CoordinateType nominalDistance = -1.);\n\n  virtual CoordinateType estimateRelativeScale(CoordinateType minDist) const;\n\nprivate:\n  /** \\cond PRIVATE */\n  typedef TestKernelTrialIntegrator<BasisFunctionType, KernelType, ResultType>\n  Integrator;\n  typedef typename Integrator::ElementIndexPair ElementIndexPair;\n  typedef DefaultLocalAssemblerForOperatorsOnSurfacesUtilities<\n      BasisFunctionType> Utilities;\n\n  /** \\brief Alternative comparison functor for pairs.\n   *\n   *  This functor can be used to sort pairs according to the second member\n   *  and then, in case of equality, according to the first member. */\n  template <typename T1, typename T2> struct alternative_less {\n    bool operator()(const std::pair<T1, T2> &a,\n                    const std::pair<T1, T2> &b) const {\n      return a.second < b.second ||\n             (!(b.second < a.second) && a.first < b.first);\n    }\n  };\n\n  /** \\brief Comparison functor for element-index pairs.\n   *\n   *  This functor sorts element index pairs first after the trial element\n   *  index (second member) and then, in case of equality, after the test\n   *  element index (first member) */\n  typedef alternative_less<typename ElementIndexPair::first_type,\n                           typename ElementIndexPair::second_type>\n  ElementIndexPairCompare;\n\n  /** \\brief Set of element index pairs.\n   *\n   *  The alternative sorting (first after the trial element index) is used\n   *  because profiling has shown that evaluateLocalWeakForms is called more\n   *  often in the TEST_TRIAL mode (with a single trial element index) than\n   *  in the TRIAL_TEST mode. Therefore the singular integral cache is\n   *  indexed with trial element index, and this sorting mode makes it easier\n   *  to construct such cache. */\n  typedef std::set<ElementIndexPair, ElementIndexPairCompare>\n  ElementIndexPairSet;\n\n  bool testAndTrialGridsAreIdentical() const;\n\n  void cacheSingularLocalWeakForms();\n  void findPairsOfAdjacentElements(ElementIndexPairSet &pairs) const;\n  void cacheLocalWeakForms(const ElementIndexPairSet &elementIndexPairs);\n\n  const Integrator &selectIntegrator(int testElementIndex,\n                                     int trialElementIndex,\n                                     CoordinateType nominalDistance = -1.);\n\n  const Integrator &getIntegrator(const DoubleQuadratureDescriptor &index);\n\nprivate:\n  shared_ptr<const GeometryFactory> m_testGeometryFactory;\n  shared_ptr<const GeometryFactory> m_trialGeometryFactory;\n  shared_ptr<const RawGridGeometry<CoordinateType>> m_testRawGeometry;\n  shared_ptr<const RawGridGeometry<CoordinateType>> m_trialRawGeometry;\n  shared_ptr<const std::vector<const Shapeset<BasisFunctionType> *>>\n  m_testShapesets;\n  shared_ptr<const std::vector<const Shapeset<BasisFunctionType> *>>\n  m_trialShapesets;\n  shared_ptr<const CollectionOfShapesetTransformations<CoordinateType>>\n  m_testTransformations;\n  shared_ptr<const CollectionOfKernels<KernelType>> m_kernels;\n  shared_ptr<const CollectionOfShapesetTransformations<CoordinateType>>\n  m_trialTransformations;\n  shared_ptr<const TestKernelTrialIntegral<BasisFunctionType, KernelType,\n                                           ResultType>> m_integral;\n  shared_ptr<const OpenClHandler> m_openClHandler;\n  ParallelizationOptions m_parallelizationOptions;\n  VerbosityLevel::Level m_verbosityLevel;\n  shared_ptr<const QuadratureDescriptorSelectorForIntegralOperators<\n      CoordinateType>> m_quadDescSelector;\n  shared_ptr<const DoubleQuadratureRuleFamily<CoordinateType>> m_quadRuleFamily;\n\n  typedef tbb::concurrent_unordered_map<DoubleQuadratureDescriptor,\n                                        Integrator *> IntegratorMap;\n  IntegratorMap m_testKernelTrialIntegrators;\n  mutable tbb::mutex m_integratorCreationMutex;\n\n  enum {\n    INVALID_INDEX = INT_MAX\n  };\n  typedef _2dArray<std::pair<int, arma::Mat<ResultType>>> Cache;\n  /** \\brief Singular integral cache.\n   *\n   *  This cache stores the preevaluated local weak forms expressed by\n   *  singular integrals. A particular item it stored in r'th row and c'th\n   *  column stores, in its second member, the local weak form calculated for\n   *  the test element with index it.first and the trial element with index\n   *  c. In each column, the items are sorted after increasing test element\n   *  index. At the end of each column there can be unused items with test\n   *  element index set to INVALID_INDEX (= INT_MAX, so that the sorting is\n   *  preserved). */\n  Cache m_cache;\n  /** \\endcond */\n};\n\n} // namespace Fiber\n\n#include \"default_local_assembler_for_integral_operators_on_surfaces_imp.hpp\"\n\n#endif\n", "meta": {"hexsha": "52b0c22d749e8da8ec40bd01f7d2004bc99b7e02", "size": 9499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/fiber/default_local_assembler_for_integral_operators_on_surfaces.hpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/fiber/default_local_assembler_for_integral_operators_on_surfaces.hpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/fiber/default_local_assembler_for_integral_operators_on_surfaces.hpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": 44.1813953488, "max_line_length": 80, "alphanum_fraction": 0.7553426676, "num_tokens": 2029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.19056991096979806}}
{"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// File generated at Sat 27 Aug 2016 12:50:26\n\n#ifndef CMSSMNoFV_EFFECTIVE_COUPLINGS_H\n#define CMSSMNoFV_EFFECTIVE_COUPLINGS_H\n\n#include \"CMSSMNoFV_mass_eigenstates.hpp\"\n#include \"lowe.h\"\n#include \"physical_input.hpp\"\n\n#include <complex>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nnamespace standard_model {\nclass Standard_model;\n}\n\nclass CMSSMNoFV_effective_couplings {\npublic:\n   CMSSMNoFV_effective_couplings(const CMSSMNoFV_mass_eigenstates&,\n                                   const softsusy::QedQcd&,\n                                   const Physical_input&);\n   ~CMSSMNoFV_effective_couplings();\n\n   void do_run_couplings(bool flag) { rg_improve = flag; }\n   bool do_run_couplings() const { return rg_improve; }\n   void do_include_qcd_corrections(bool flag) { include_qcd_corrections = flag; }\n   bool do_include_qcd_corrections() const { return include_qcd_corrections; }\n   void set_physical_inputs(const Physical_input& inputs_) { physical_input = inputs_; }\n   void set_low_energy_data(const softsusy::QedQcd& qedqcd_) { qedqcd = qedqcd_; }\n   void set_model(const CMSSMNoFV_mass_eigenstates& model_);\n\n   double get_hhVPVP_partial_width(unsigned gO1) const;\n   double get_hhVGVG_partial_width(unsigned gO1) const;\n   double get_AhVPVP_partial_width(unsigned gO1) const;\n   double get_AhVGVG_partial_width(unsigned gO1) const;\n   std::complex<double> get_eff_CphhVPVP(unsigned gO1) const { return eff_CphhVPVP(gO1); }\n   std::complex<double> get_eff_CphhVGVG(unsigned gO1) const { return eff_CphhVGVG(gO1); }\n   std::complex<double> get_eff_CpAhVPVP(unsigned gO1) const { return eff_CpAhVPVP(gO1); }\n   std::complex<double> get_eff_CpAhVGVG(unsigned gO1) const { return eff_CpAhVGVG(gO1); }\n\n   void calculate_effective_couplings();\n\n   std::complex<double> CpFdhhbarFdPL(unsigned gt2) const;\n   std::complex<double> CpFshhbarFsPL(unsigned gt2) const;\n   std::complex<double> CpFbhhbarFbPL(unsigned gt2) const;\n   std::complex<double> CpFuhhbarFuPL(unsigned gt2) const;\n   std::complex<double> CpFchhbarFcPL(unsigned gt2) const;\n   std::complex<double> CpFthhbarFtPL(unsigned gt2) const;\n   std::complex<double> CpFehhbarFePL(unsigned gt2) const;\n   std::complex<double> CpFmhhbarFmPL(unsigned gt2) const;\n   std::complex<double> CpFtauhhbarFtauPL(unsigned gt2) const;\n   std::complex<double> CphhSdconjSd(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhSuconjSu(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhSeconjSe(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhSmconjSm(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhStauconjStau(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhSsconjSs(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhScconjSc(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhSbconjSb(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhStconjSt(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhHpmconjHpm(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpChahhbarChaPL(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CphhVWmconjVWm(unsigned gt1) const;\n   std::complex<double> CpAhFdbarFdPL(unsigned gt1) const;\n   std::complex<double> CpAhFsbarFsPL(unsigned gt1) const;\n   std::complex<double> CpAhFbbarFbPL(unsigned gt1) const;\n   std::complex<double> CpAhFubarFuPL(unsigned gt1) const;\n   std::complex<double> CpAhFcbarFcPL(unsigned gt1) const;\n   std::complex<double> CpAhFtbarFtPL(unsigned gt1) const;\n   std::complex<double> CpAhFebarFePL(unsigned gt1) const;\n   std::complex<double> CpAhFmbarFmPL(unsigned gt1) const;\n   std::complex<double> CpAhFtaubarFtauPL(unsigned gt1) const;\n   std::complex<double> CpAhSdconjSd(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhSuconjSu(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhSeconjSe(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhSmconjSm(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhStauconjStau(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhSsconjSs(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhScconjSc(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhSbconjSb(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhStconjSt(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhHpmconjHpm(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   std::complex<double> CpAhChabarChaPL(unsigned gt1, unsigned gt2, unsigned gt3) const;\n   void calculate_eff_CphhVPVP(unsigned gO1);\n   void calculate_eff_CphhVGVG(unsigned gO1);\n   void calculate_eff_CpAhVPVP(unsigned gO1);\n   void calculate_eff_CpAhVGVG(unsigned gO1);\n\nprivate:\n   CMSSMNoFV_mass_eigenstates model;\n   softsusy::QedQcd qedqcd;\n   Physical_input physical_input;\n   bool rg_improve;\n   bool include_qcd_corrections;\n\n   void copy_mixing_matrices_from_model();\n\n   void run_SM_strong_coupling_to(double m);\n\n   // higher order corrections to the amplitudes for\n   // effective coupling to photons\n   std::complex<double> scalar_scalar_qcd_factor(double, double) const;\n   std::complex<double> scalar_fermion_qcd_factor(double, double) const;\n   std::complex<double> pseudoscalar_fermion_qcd_factor(double, double) const;\n\n   // higher order corrections to the leading order\n   // effective couplings to gluons\n   double number_of_active_flavours(double) const;\n   double scalar_scaling_factor(double) const;\n   double pseudoscalar_scaling_factor(double) const;\n\n   Eigen::Matrix<double,2,2> ZD;\n   Eigen::Matrix<double,2,2> ZU;\n   Eigen::Matrix<double,2,2> ZE;\n   Eigen::Matrix<double,2,2> ZM;\n   Eigen::Matrix<double,2,2> ZTau;\n   Eigen::Matrix<double,2,2> ZS;\n   Eigen::Matrix<double,2,2> ZC;\n   Eigen::Matrix<double,2,2> ZB;\n   Eigen::Matrix<double,2,2> ZT;\n   Eigen::Matrix<double,2,2> ZH;\n   Eigen::Matrix<double,2,2> ZA;\n   Eigen::Matrix<double,2,2> ZP;\n   Eigen::Matrix<std::complex<double>,4,4> ZN;\n   Eigen::Matrix<std::complex<double>,2,2> UM;\n   Eigen::Matrix<std::complex<double>,2,2> UP;\n   Eigen::Matrix<double,2,2> ZZ;\n\n   Eigen::Array<std::complex<double>,2,1> eff_CphhVPVP;\n   Eigen::Array<std::complex<double>,2,1> eff_CphhVGVG;\n   Eigen::Array<std::complex<double>,2,1> eff_CpAhVPVP;\n   Eigen::Array<std::complex<double>,2,1> eff_CpAhVGVG;\n\n};\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "055d114b603fff92329f81642fa781ba911db13d", "size": 7455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/CMSSMNoFV/CMSSMNoFV_effective_couplings.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/models/CMSSMNoFV/CMSSMNoFV_effective_couplings.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/models/CMSSMNoFV/CMSSMNoFV_effective_couplings.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": 46.8867924528, "max_line_length": 90, "alphanum_fraction": 0.7392354125, "num_tokens": 2186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1904953404269261}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <stdio.h>\n#include <math.h>\n#include <vector>\n#include <numeric>\n#include <strings.h>\n#include <assert.h>\n\n#include <dirent.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\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/geometries/adapted/c_array.hpp>\n\n#include \"mail.h\"\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\n\ntypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > Polygon;\n\n\nusing namespace std;\n\n/*=======================================================================\nSTATIC EVALUATION PARAMETERS\n=======================================================================*/\n\n// holds the number of test images on the server\nconst int32_t N_TESTIMAGES = 7518;\n\n// easy, moderate and hard evaluation level\nenum DIFFICULTY{EASY=0, MODERATE=1, HARD=2};\n\n// evaluation metrics: image, ground or 3D\nenum METRIC{IMAGE=0, GROUND=1, BOX3D=2};\n\n// evaluation parameter\nconst int32_t MIN_HEIGHT[3]     = {40, 25, 25};     // minimum height for evaluated groundtruth/detections\nconst int32_t MAX_OCCLUSION[3]  = {0, 1, 2};        // maximum occlusion level of the groundtruth used for evaluation\nconst double  MAX_TRUNCATION[3] = {0.15, 0.3, 0.5}; // maximum truncation level of the groundtruth used for evaluation\n\n// evaluated object classes\nenum CLASSES{CAR=0, PEDESTRIAN=1, CYCLIST=2};\nconst int NUM_CLASS = 3;\n\n// parameters varying per class\nvector<string> CLASS_NAMES;\n// the minimum overlap required for 2D evaluation on the image/ground plane and 3D evaluation\nconst double MIN_OVERLAP[3][3] = {{0.7, 0.5, 0.5}, {0.5, 0.25, 0.25}, {0.5, 0.25, 0.25}};\n\n// no. of recall steps that should be evaluated (discretized)\nconst double N_SAMPLE_PTS = 41;\n\n\n// initialize class names\nvoid initGlobals () {\n  CLASS_NAMES.push_back(\"car\");\n  CLASS_NAMES.push_back(\"pedestrian\");\n  CLASS_NAMES.push_back(\"cyclist\");\n}\n\n/*=======================================================================\nDATA TYPES FOR EVALUATION\n=======================================================================*/\n\n// holding data needed for precision-recall and precision-aos\nstruct tPrData {\n  vector<double> v;           // detection score for computing score thresholds\n  double         similarity;  // orientation similarity\n  int32_t        tp;          // true positives\n  int32_t        fp;          // false positives\n  int32_t        fn;          // false negatives\n  tPrData () :\n    similarity(0), tp(0), fp(0), fn(0) {}\n};\n\n// holding bounding boxes for ground truth and detections\nstruct tBox {\n  string  type;     // object type as car, pedestrian or cyclist,...\n  double   x1;      // left corner\n  double   y1;      // top corner\n  double   x2;      // right corner\n  double   y2;      // bottom corner\n  double   alpha;   // image orientation\n  tBox (string type, double x1,double y1,double x2,double y2,double alpha) :\n    type(type),x1(x1),y1(y1),x2(x2),y2(y2),alpha(alpha) {}\n};\n\n// holding ground truth data\nstruct tGroundtruth {\n  tBox    box;        // object type, box, orientation\n  double  truncation; // truncation 0..1\n  int32_t occlusion;  // occlusion 0,1,2 (non, partly, fully)\n  double ry;\n  double  t1, t2, t3;\n  double h, w, l;\n  tGroundtruth () :\n    box(tBox(\"invalild\",-1,-1,-1,-1,-10)),truncation(-1),occlusion(-1) {}\n  tGroundtruth (tBox box,double truncation,int32_t occlusion) :\n    box(box),truncation(truncation),occlusion(occlusion) {}\n  tGroundtruth (string type,double x1,double y1,double x2,double y2,double alpha,double truncation,int32_t occlusion) :\n    box(tBox(type,x1,y1,x2,y2,alpha)),truncation(truncation),occlusion(occlusion) {}\n};\n\n// holding detection data\nstruct tDetection {\n  tBox    box;    // object type, box, orientation\n  double  thresh; // detection score\n  double  ry;\n  double  t1, t2, t3;\n  double  h, w, l;\n  tDetection ():\n    box(tBox(\"invalid\",-1,-1,-1,-1,-10)),thresh(-1000) {}\n  tDetection (tBox box,double thresh) :\n    box(box),thresh(thresh) {}\n  tDetection (string type,double x1,double y1,double x2,double y2,double alpha,double thresh) :\n    box(tBox(type,x1,y1,x2,y2,alpha)),thresh(thresh) {}\n};\n\n\n/*=======================================================================\nFUNCTIONS TO LOAD DETECTION AND GROUND TRUTH DATA ONCE, SAVE RESULTS\n=======================================================================*/\nvector<int32_t> indices;\n\nvector<tDetection> loadDetections(string file_name, bool &compute_aos,\n        vector<bool> &eval_image, vector<bool> &eval_ground,\n        vector<bool> &eval_3d, bool &success) {\n\n  // holds all detections (ignored detections are indicated by an index vector\n  vector<tDetection> detections;\n  FILE *fp = fopen(file_name.c_str(),\"r\");\n  if (!fp) {\n    success = false;\n    return detections;\n  }\n  while (!feof(fp)) {\n    tDetection d;\n    double trash;\n    char str[255];\n    if (fscanf(fp, \"%s %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n                   str, &trash, &trash, &d.box.alpha, &d.box.x1, &d.box.y1,\n                   &d.box.x2, &d.box.y2, &d.h, &d.w, &d.l, &d.t1, &d.t2, &d.t3,\n                   &d.ry, &d.thresh)==16) {\n\n        // d.thresh = 1;\n      d.box.type = str;\n      detections.push_back(d);\n\n      // orientation=-10 is invalid, AOS is not evaluated if at least one orientation is invalid\n      if(d.box.alpha == -10)\n        compute_aos = false;\n\n      // a class is only evaluated if it is detected at least once\n      for (int c = 0; c < NUM_CLASS; c++) {\n        if (!strcasecmp(d.box.type.c_str(), CLASS_NAMES[c].c_str())) {\n          if (!eval_image[c] && d.box.x1 >= 0)\n            eval_image[c] = true;\n          if (!eval_ground[c] && d.t1 != -1000)\n            eval_ground[c] = true;\n          if (!eval_3d[c] && d.t2 != -1000)\n            eval_3d[c] = true;\n          break;\n        }\n      }\n    }\n  }\n  fclose(fp);\n  success = true;\n  return detections;\n}\n\nvector<tGroundtruth> loadGroundtruth(string file_name,bool &success) {\n\n  // holds all ground truth (ignored ground truth is indicated by an index vector\n  vector<tGroundtruth> groundtruth;\n  FILE *fp = fopen(file_name.c_str(),\"r\");\n  if (!fp) {\n    success = false;\n    return groundtruth;\n  }\n  while (!feof(fp)) {\n    tGroundtruth g;\n    char str[255];\n    if (fscanf(fp, \"%s %lf %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n                   str, &g.truncation, &g.occlusion, &g.box.alpha,\n                   &g.box.x1,   &g.box.y1,     &g.box.x2,    &g.box.y2,\n                   &g.h,      &g.w,        &g.l,       &g.t1,\n                   &g.t2,      &g.t3,        &g.ry )==15) {\n      g.box.type = str;\n      groundtruth.push_back(g);\n    }\n  }\n  fclose(fp);\n  success = true;\n  return groundtruth;\n}\n\nvoid saveStats (const vector<double> &precision, const vector<double> &aos, FILE *fp_det, FILE *fp_ori) {\n\n  // save precision to file\n  if(precision.empty())\n    return;\n  for (int32_t i=0; i<precision.size(); i++)\n    fprintf(fp_det,\"%f \",precision[i]);\n  fprintf(fp_det,\"\\n\");\n\n  // save orientation similarity, only if there were no invalid orientation entries in submission (alpha=-10)\n  if(aos.empty())\n    return;\n  for (int32_t i=0; i<aos.size(); i++)\n    fprintf(fp_ori,\"%f \",aos[i]);\n  fprintf(fp_ori,\"\\n\");\n}\n\n/*=======================================================================\nEVALUATION HELPER FUNCTIONS\n=======================================================================*/\n\n// criterion defines whether the overlap is computed with respect to both areas (ground truth and detection)\n// or with respect to box a or b (detection and \"dontcare\" areas)\ninline double imageBoxOverlap(tBox a, tBox b, int32_t criterion=-1){\n\n  // overlap is invalid in the beginning\n  double o = -1;\n\n  // get overlapping area\n  double x1 = max(a.x1, b.x1);\n  double y1 = max(a.y1, b.y1);\n  double x2 = min(a.x2, b.x2);\n  double y2 = min(a.y2, b.y2);\n\n  // compute width and height of overlapping area\n  double w = x2-x1;\n  double h = y2-y1;\n\n  // set invalid entries to 0 overlap\n  if(w<=0 || h<=0)\n    return 0;\n\n  // get overlapping areas\n  double inter = w*h;\n  double a_area = (a.x2-a.x1) * (a.y2-a.y1);\n  double b_area = (b.x2-b.x1) * (b.y2-b.y1);\n\n  // intersection over union overlap depending on users choice\n  if(criterion==-1)     // union\n    o = inter / (a_area+b_area-inter);\n  else if(criterion==0) // bbox_a\n    o = inter / a_area;\n  else if(criterion==1) // bbox_b\n    o = inter / b_area;\n\n  // overlap\n  return o;\n}\n\ninline double imageBoxOverlap(tDetection a, tGroundtruth b, int32_t criterion=-1){\n  return imageBoxOverlap(a.box, b.box, criterion);\n}\n\n// compute polygon of an oriented bounding box\ntemplate <typename T>\nPolygon toPolygon(const T& g) {\n    using namespace boost::numeric::ublas;\n    using namespace boost::geometry;\n    matrix<double> mref(2, 2);\n    mref(0, 0) = cos(g.ry); mref(0, 1) = sin(g.ry);\n    mref(1, 0) = -sin(g.ry); mref(1, 1) = cos(g.ry);\n\n    static int count = 0;\n    matrix<double> corners(2, 4);\n    double data[] = {g.l / 2, g.l / 2, -g.l / 2, -g.l / 2,\n                     g.w / 2, -g.w / 2, -g.w / 2, g.w / 2};\n    std::copy(data, data + 8, corners.data().begin());\n    matrix<double> gc = prod(mref, corners);\n    for (int i = 0; i < 4; ++i) {\n        gc(0, i) += g.t1;\n        gc(1, i) += g.t3;\n    }\n\n    double points[][2] = {{gc(0, 0), gc(1, 0)},{gc(0, 1), gc(1, 1)},{gc(0, 2), gc(1, 2)},{gc(0, 3), gc(1, 3)},{gc(0, 0), gc(1, 0)}};\n    Polygon poly;\n    append(poly, points);\n    return poly;\n}\n\n// measure overlap between bird's eye view bounding boxes, parametrized by (ry, l, w, tx, tz)\ninline double groundBoxOverlap(tDetection d, tGroundtruth g, int32_t criterion = -1) {\n    using namespace boost::geometry;\n    Polygon gp = toPolygon(g);\n    Polygon dp = toPolygon(d);\n\n    std::vector<Polygon> in, un;\n    intersection(gp, dp, in);\n    union_(gp, dp, un);\n\n    double inter_area = in.empty() ? 0 : area(in.front());\n    double union_area = area(un.front());\n    double o;\n    if(criterion==-1)     // union\n        o = inter_area / union_area;\n    else if(criterion==0) // bbox_a\n        o = inter_area / area(dp);\n    else if(criterion==1) // bbox_b\n        o = inter_area / area(gp);\n\n    return o;\n}\n\n// measure overlap between 3D bounding boxes, parametrized by (ry, h, w, l, tx, ty, tz)\ninline double box3DOverlap(tDetection d, tGroundtruth g, int32_t criterion = -1) {\n    using namespace boost::geometry;\n    Polygon gp = toPolygon(g);\n    Polygon dp = toPolygon(d);\n\n    std::vector<Polygon> in, un;\n    intersection(gp, dp, in);\n    union_(gp, dp, un);\n\n    double ymax = min(d.t2, g.t2);\n    double ymin = max(d.t2 - d.h, g.t2 - g.h);\n\n    double inter_area = in.empty() ? 0 : area(in.front());\n    double inter_vol = inter_area * max(0.0, ymax - ymin);\n\n    double det_vol = d.h * d.l * d.w;\n    double gt_vol = g.h * g.l * g.w;\n\n    double o;\n    if(criterion==-1)     // union\n        o = inter_vol / (det_vol + gt_vol - inter_vol);\n    else if(criterion==0) // bbox_a\n        o = inter_vol / det_vol;\n    else if(criterion==1) // bbox_b\n        o = inter_vol / gt_vol;\n\n    return o;\n}\n\nvector<double> getThresholds(vector<double> &v, double n_groundtruth){\n\n  // holds scores needed to compute N_SAMPLE_PTS recall values\n  vector<double> t;\n\n  // sort scores in descending order\n  // (highest score is assumed to give best/most confident detections)\n  sort(v.begin(), v.end(), greater<double>());\n\n  // get scores for linearly spaced recall\n  double current_recall = 0;\n  for(int32_t i=0; i<v.size(); i++){\n\n    // check if right-hand-side recall with respect to current recall is close than left-hand-side one\n    // in this case, skip the current detection score\n    double l_recall, r_recall, recall;\n    l_recall = (double)(i+1)/n_groundtruth;\n    if(i<(v.size()-1))\n      r_recall = (double)(i+2)/n_groundtruth;\n    else\n      r_recall = l_recall;\n\n    if( (r_recall-current_recall) < (current_recall-l_recall) && i<(v.size()-1))\n      continue;\n\n    // left recall is the best approximation, so use this and goto next recall step for approximation\n    recall = l_recall;\n\n    // the next recall step was reached\n    t.push_back(v[i]);\n    current_recall += 1.0/(N_SAMPLE_PTS-1.0);\n  }\n  return t;\n}\n\nvoid cleanData(CLASSES current_class, const vector<tGroundtruth> &gt, const vector<tDetection> &det, vector<int32_t> &ignored_gt, vector<tGroundtruth> &dc, vector<int32_t> &ignored_det, int32_t &n_gt, DIFFICULTY difficulty){\n\n  // extract ground truth bounding boxes for current evaluation class\n  for(int32_t i=0;i<gt.size(); i++){\n\n    // only bounding boxes with a minimum height are used for evaluation\n    double height = gt[i].box.y2 - gt[i].box.y1;\n\n    // neighboring classes are ignored (\"van\" for \"car\" and \"person_sitting\" for \"pedestrian\")\n    // (lower/upper cases are ignored)\n    int32_t valid_class;\n\n    // all classes without a neighboring class\n    if(!strcasecmp(gt[i].box.type.c_str(), CLASS_NAMES[current_class].c_str()))\n      valid_class = 1;\n\n    // classes with a neighboring class\n    else if(!strcasecmp(CLASS_NAMES[current_class].c_str(), \"Pedestrian\") && !strcasecmp(\"Person_sitting\", gt[i].box.type.c_str()))\n      valid_class = 0;\n    else if(!strcasecmp(CLASS_NAMES[current_class].c_str(), \"Car\") && !strcasecmp(\"Van\", gt[i].box.type.c_str()))\n      valid_class = 0;\n\n    // classes not used for evaluation\n    else\n      valid_class = -1;\n\n    // ground truth is ignored, if occlusion, truncation exceeds the difficulty or ground truth is too small\n    // (doesn't count as FN nor TP, although detections may be assigned)\n    bool ignore = false;\n    if(gt[i].occlusion>MAX_OCCLUSION[difficulty] || gt[i].truncation>MAX_TRUNCATION[difficulty] || height<MIN_HEIGHT[difficulty])\n      ignore = true;\n\n    // set ignored vector for ground truth\n    // current class and not ignored (total no. of ground truth is detected for recall denominator)\n    if(valid_class==1 && !ignore){\n      ignored_gt.push_back(0);\n      n_gt++;\n    }\n\n    // neighboring class, or current class but ignored\n    else if(valid_class==0 || (ignore && valid_class==1))\n      ignored_gt.push_back(1);\n\n    // all other classes which are FN in the evaluation\n    else\n      ignored_gt.push_back(-1);\n  }\n\n  // extract dontcare areas\n  for(int32_t i=0;i<gt.size(); i++)\n    if(!strcasecmp(\"DontCare\", gt[i].box.type.c_str()))\n      dc.push_back(gt[i]);\n\n  // extract detections bounding boxes of the current class\n  for(int32_t i=0;i<det.size(); i++){\n\n    // neighboring classes are not evaluated\n    int32_t valid_class;\n    if(!strcasecmp(det[i].box.type.c_str(), CLASS_NAMES[current_class].c_str()))\n      valid_class = 1;\n    else\n      valid_class = -1;\n\n    int32_t height = fabs(det[i].box.y1 - det[i].box.y2);\n    // set ignored vector for detections\n    if(height<MIN_HEIGHT[difficulty])\n      ignored_det.push_back(1);\n    else if(valid_class==1)\n      ignored_det.push_back(0);\n    else\n      ignored_det.push_back(-1);\n  }\n}\n\ntPrData computeStatistics(CLASSES current_class, const vector<tGroundtruth> &gt,\n        const vector<tDetection> &det, const vector<tGroundtruth> &dc,\n        const vector<int32_t> &ignored_gt, const vector<int32_t>  &ignored_det,\n        bool compute_fp, double (*boxoverlap)(tDetection, tGroundtruth, int32_t),\n        METRIC metric, bool compute_aos=false, double thresh=0, bool debug=false){\n\n  tPrData stat = tPrData();\n  const double NO_DETECTION = -10000000;\n  vector<double> delta;            // holds angular difference for TPs (needed for AOS evaluation)\n  vector<bool> assigned_detection; // holds wether a detection was assigned to a valid or ignored ground truth\n  assigned_detection.assign(det.size(), false);\n  vector<bool> ignored_threshold;\n  ignored_threshold.assign(det.size(), false); // holds detections with a threshold lower than thresh if FP are computed\n\n  // detections with a low score are ignored for computing precision (needs FP)\n  if(compute_fp)\n    for(int32_t i=0; i<det.size(); i++)\n      if(det[i].thresh<thresh)\n        ignored_threshold[i] = true;\n\n  // evaluate all ground truth boxes\n  for(int32_t i=0; i<gt.size(); i++){\n\n    // this ground truth is not of the current or a neighboring class and therefore ignored\n    if(ignored_gt[i]==-1)\n      continue;\n\n    /*=======================================================================\n    find candidates (overlap with ground truth > 0.5) (logical len(det))\n    =======================================================================*/\n    int32_t det_idx          = -1;\n    double valid_detection = NO_DETECTION;\n    double max_overlap     = 0;\n\n    // search for a possible detection\n    bool assigned_ignored_det = false;\n    for(int32_t j=0; j<det.size(); j++){\n\n      // detections not of the current class, already assigned or with a low threshold are ignored\n      if(ignored_det[j]==-1)\n        continue;\n      if(assigned_detection[j])\n        continue;\n      if(ignored_threshold[j])\n        continue;\n\n      // find the maximum score for the candidates and get idx of respective detection\n      double overlap = boxoverlap(det[j], gt[i], -1);\n\n      // for computing recall thresholds, the candidate with highest score is considered\n      if(!compute_fp && overlap>MIN_OVERLAP[metric][current_class] && det[j].thresh>valid_detection){\n        det_idx         = j;\n        valid_detection = det[j].thresh;\n      }\n\n      // for computing pr curve values, the candidate with the greatest overlap is considered\n      // if the greatest overlap is an ignored detection (min_height), the overlapping detection is used\n      else if(compute_fp && overlap>MIN_OVERLAP[metric][current_class] && (overlap>max_overlap || assigned_ignored_det) && ignored_det[j]==0){\n        max_overlap     = overlap;\n        det_idx         = j;\n        valid_detection = 1;\n        assigned_ignored_det = false;\n      }\n      else if(compute_fp && overlap>MIN_OVERLAP[metric][current_class] && valid_detection==NO_DETECTION && ignored_det[j]==1){\n        det_idx              = j;\n        valid_detection      = 1;\n        assigned_ignored_det = true;\n      }\n    }\n\n    /*=======================================================================\n    compute TP, FP and FN\n    =======================================================================*/\n\n    // nothing was assigned to this valid ground truth\n    if(valid_detection==NO_DETECTION && ignored_gt[i]==0) {\n      stat.fn++;\n    }\n\n    // only evaluate valid ground truth <=> detection assignments (considering difficulty level)\n    else if(valid_detection!=NO_DETECTION && (ignored_gt[i]==1 || ignored_det[det_idx]==1))\n      assigned_detection[det_idx] = true;\n\n    // found a valid true positive\n    else if(valid_detection!=NO_DETECTION){\n\n      // write highest score to threshold vector\n      stat.tp++;\n      stat.v.push_back(det[det_idx].thresh);\n\n      // compute angular difference of detection and ground truth if valid detection orientation was provided\n      if(compute_aos)\n        delta.push_back(gt[i].box.alpha - det[det_idx].box.alpha);\n\n      // clean up\n      assigned_detection[det_idx] = true;\n    }\n  }\n\n  // if FP are requested, consider stuff area\n  if(compute_fp){\n\n    // count fp\n    for(int32_t i=0; i<det.size(); i++){\n\n      // count false positives if required (height smaller than required is ignored (ignored_det==1)\n      if(!(assigned_detection[i] || ignored_det[i]==-1 || ignored_det[i]==1 || ignored_threshold[i]))\n        stat.fp++;\n    }\n\n    // do not consider detections overlapping with stuff area\n    int32_t nstuff = 0;\n    for(int32_t i=0; i<dc.size(); i++){\n      for(int32_t j=0; j<det.size(); j++){\n\n        // detections not of the current class, already assigned, with a low threshold or a low minimum height are ignored\n        if(assigned_detection[j])\n          continue;\n        if(ignored_det[j]==-1 || ignored_det[j]==1)\n          continue;\n        if(ignored_threshold[j])\n          continue;\n\n        // compute overlap and assign to stuff area, if overlap exceeds class specific value\n        double overlap = boxoverlap(det[j], dc[i], 0);\n        if(overlap>MIN_OVERLAP[metric][current_class]){\n          assigned_detection[j] = true;\n          nstuff++;\n        }\n      }\n    }\n\n    // FP = no. of all not to ground truth assigned detections - detections assigned to stuff areas\n    stat.fp -= nstuff;\n\n    // if all orientation values are valid, the AOS is computed\n    if(compute_aos){\n      vector<double> tmp;\n\n      // FP have a similarity of 0, for all TP compute AOS\n      tmp.assign(stat.fp, 0);\n      for(int32_t i=0; i<delta.size(); i++)\n        tmp.push_back((1.0+cos(delta[i]))/2.0);\n\n      // be sure, that all orientation deltas are computed\n      assert(tmp.size()==stat.fp+stat.tp);\n      assert(delta.size()==stat.tp);\n\n      // get the mean orientation similarity for this image\n      if(stat.tp>0 || stat.fp>0)\n        stat.similarity = accumulate(tmp.begin(), tmp.end(), 0.0);\n\n      // there was neither a FP nor a TP, so the similarity is ignored in the evaluation\n      else\n        stat.similarity = -1;\n    }\n  }\n  return stat;\n}\n\n/*=======================================================================\nEVALUATE CLASS-WISE\n=======================================================================*/\n\nbool eval_class (FILE *fp_det, FILE *fp_ori, CLASSES current_class,\n        const vector< vector<tGroundtruth> > &groundtruth,\n        const vector< vector<tDetection> > &detections, bool compute_aos,\n        double (*boxoverlap)(tDetection, tGroundtruth, int32_t),\n        vector<double> &precision, vector<double> &aos,\n        DIFFICULTY difficulty, METRIC metric) {\n    assert(groundtruth.size() == detections.size());\n\n  // init\n  int32_t n_gt=0;                                     // total no. of gt (denominator of recall)\n  vector<double> v, thresholds;                       // detection scores, evaluated for recall discretization\n  vector< vector<int32_t> > ignored_gt, ignored_det;  // index of ignored gt detection for current class/difficulty\n  vector< vector<tGroundtruth> > dontcare;            // index of dontcare areas, included in ground truth\n\n  // for all test images do\n  for (int32_t i=0; i<groundtruth.size(); i++){\n\n    // holds ignored ground truth, ignored detections and dontcare areas for current frame\n    vector<int32_t> i_gt, i_det;\n    vector<tGroundtruth> dc;\n\n    // only evaluate objects of current class and ignore occluded, truncated objects\n    cleanData(current_class, groundtruth[i], detections[i], i_gt, dc, i_det, n_gt, difficulty);\n    ignored_gt.push_back(i_gt);\n    ignored_det.push_back(i_det);\n    dontcare.push_back(dc);\n\n    // compute statistics to get recall values\n    tPrData pr_tmp = tPrData();\n    pr_tmp = computeStatistics(current_class, groundtruth[i], detections[i], dc, i_gt, i_det, false, boxoverlap, metric);\n\n    // add detection scores to vector over all images\n    for(int32_t j=0; j<pr_tmp.v.size(); j++)\n      v.push_back(pr_tmp.v[j]);\n  }\n\n  // get scores that must be evaluated for recall discretization\n  thresholds = getThresholds(v, n_gt);\n\n  // compute TP,FP,FN for relevant scores\n  vector<tPrData> pr;\n  pr.assign(thresholds.size(),tPrData());\n  for (int32_t i=0; i<groundtruth.size(); i++){\n\n    // for all scores/recall thresholds do:\n    for(int32_t t=0; t<thresholds.size(); t++){\n      tPrData tmp = tPrData();\n      tmp = computeStatistics(current_class, groundtruth[i], detections[i], dontcare[i],\n                              ignored_gt[i], ignored_det[i], true, boxoverlap, metric,\n                              compute_aos, thresholds[t], t==38);\n\n      // add no. of TP, FP, FN, AOS for current frame to total evaluation for current threshold\n      pr[t].tp += tmp.tp;\n      pr[t].fp += tmp.fp;\n      pr[t].fn += tmp.fn;\n      if(tmp.similarity!=-1)\n        pr[t].similarity += tmp.similarity;\n    }\n  }\n\n  // compute recall, precision and AOS\n  vector<double> recall;\n  precision.assign(N_SAMPLE_PTS, 0);\n  if(compute_aos)\n    aos.assign(N_SAMPLE_PTS, 0);\n  double r=0;\n  for (int32_t i=0; i<thresholds.size(); i++){\n    r = pr[i].tp/(double)(pr[i].tp + pr[i].fn);\n    recall.push_back(r);\n    precision[i] = pr[i].tp/(double)(pr[i].tp + pr[i].fp);\n    if(compute_aos)\n      aos[i] = pr[i].similarity/(double)(pr[i].tp + pr[i].fp);\n  }\n\n  // filter precision and AOS using max_{i..end}(precision)\n  for (int32_t i=0; i<thresholds.size(); i++){\n    precision[i] = *max_element(precision.begin()+i, precision.end());\n    if(compute_aos)\n      aos[i] = *max_element(aos.begin()+i, aos.end());\n  }\n\n  // save statisics and finish with success\n  saveStats(precision, aos, fp_det, fp_ori);\n    return true;\n}\n\nvoid saveAndPlotPlots(string dir_name,string file_name,string obj_type,vector<double> vals[],bool is_aos){\n\n  char command[1024];\n\n  // save plot data to file\n  FILE *fp = fopen((dir_name + \"/\" + file_name + \".txt\").c_str(),\"w\");\n  printf(\"save %s\\n\", (dir_name + \"/\" + file_name + \".txt\").c_str());\n  for (int32_t i=0; i<(int)N_SAMPLE_PTS; i++)\n    fprintf(fp,\"%f %f %f %f\\n\",(double)i/(N_SAMPLE_PTS-1.0),vals[0][i],vals[1][i],vals[2][i]);\n  fclose(fp);\n\n  // create png + eps\n  for (int32_t j=0; j<2; j++) {\n\n    // open file\n    FILE *fp = fopen((dir_name + \"/\" + file_name + \".gp\").c_str(),\"w\");\n\n    // save gnuplot instructions\n    if (j==0) {\n      fprintf(fp,\"set term png size 450,315 font \\\"Helvetica\\\" 11\\n\");\n      fprintf(fp,\"set output \\\"%s.png\\\"\\n\",file_name.c_str());\n    } else {\n      fprintf(fp,\"set term postscript eps enhanced color font \\\"Helvetica\\\" 20\\n\");\n      fprintf(fp,\"set output \\\"%s.eps\\\"\\n\",file_name.c_str());\n    }\n\n    // set labels and ranges\n    fprintf(fp,\"set size ratio 0.7\\n\");\n    fprintf(fp,\"set xrange [0:1]\\n\");\n    fprintf(fp,\"set yrange [0:1]\\n\");\n    fprintf(fp,\"set xlabel \\\"Recall\\\"\\n\");\n    if (!is_aos) fprintf(fp,\"set ylabel \\\"Precision\\\"\\n\");\n    else         fprintf(fp,\"set ylabel \\\"Orientation Similarity\\\"\\n\");\n    obj_type[0] = toupper(obj_type[0]);\n    fprintf(fp,\"set title \\\"%s\\\"\\n\",obj_type.c_str());\n\n    // line width\n    int32_t   lw = 5;\n    if (j==0) lw = 3;\n\n    // plot error curve\n    fprintf(fp,\"plot \");\n    fprintf(fp,\"\\\"%s.txt\\\" using 1:2 title 'Easy' with lines ls 1 lw %d,\",file_name.c_str(),lw);\n    fprintf(fp,\"\\\"%s.txt\\\" using 1:3 title 'Moderate' with lines ls 2 lw %d,\",file_name.c_str(),lw);\n    fprintf(fp,\"\\\"%s.txt\\\" using 1:4 title 'Hard' with lines ls 3 lw %d\",file_name.c_str(),lw);\n\n    // close file\n    fclose(fp);\n\n    // run gnuplot => create png + eps\n    sprintf(command,\"cd %s; gnuplot %s\",dir_name.c_str(),(file_name + \".gp\").c_str());\n    system(command);\n  }\n\n  // create pdf and crop\n  sprintf(command,\"cd %s; ps2pdf %s.eps %s_large.pdf\",dir_name.c_str(),file_name.c_str(),file_name.c_str());\n  system(command);\n  sprintf(command,\"cd %s; pdfcrop %s_large.pdf %s.pdf\",dir_name.c_str(),file_name.c_str(),file_name.c_str());\n  system(command);\n  sprintf(command,\"cd %s; rm %s_large.pdf\",dir_name.c_str(),file_name.c_str());\n  system(command);\n}\n\nbool eval(string result_sha,Mail* mail){\n\n  // set some global parameters\n  initGlobals();\n\n  // ground truth and result directories\n  string gt_dir         = \"data/object/label_2\";\n  string result_dir     = \"results/\" + result_sha;\n  string plot_dir       = result_dir + \"/plot\";\n\n  // create output directories\n  system((\"mkdir \" + plot_dir).c_str());\n\n  // hold detections and ground truth in memory\n  vector< vector<tGroundtruth> > groundtruth;\n  vector< vector<tDetection> >   detections;\n\n  // holds wether orientation similarity shall be computed (might be set to false while loading detections)\n  // and which labels where provided by this submission\n  bool compute_aos=true;\n  vector<bool> eval_image(NUM_CLASS, false);\n  vector<bool> eval_ground(NUM_CLASS, false);\n  vector<bool> eval_3d(NUM_CLASS, false);\n\n  // for all images read groundtruth and detections\n  mail->msg(\"Loading detections...\");\n  for (int32_t i=0; i<N_TESTIMAGES; i++) {\n\n    // file name\n    char file_name[256];\n    sprintf(file_name,\"%06d.txt\",indices.at(i));\n\n    // read ground truth and result poses\n    bool gt_success,det_success;\n    vector<tGroundtruth> gt   = loadGroundtruth(gt_dir + \"/\" + file_name,gt_success);\n    vector<tDetection>   det  = loadDetections(result_dir + \"/data/\" + file_name,\n            compute_aos, eval_image, eval_ground, eval_3d, det_success);\n    groundtruth.push_back(gt);\n    detections.push_back(det);\n\n    // check for errors\n    if (!gt_success) {\n      mail->msg(\"ERROR: Couldn't read: %s of ground truth. Please write me an email!\", file_name);\n      return false;\n    }\n    if (!det_success) {\n      mail->msg(\"ERROR: Couldn't read: %s\", file_name);\n      return false;\n    }\n  }\n  mail->msg(\"  done.\");\n\n  // holds pointers for result files\n  FILE *fp_det=0, *fp_ori=0;\n\n  // eval image 2D bounding boxes\n  for (int c = 0; c < NUM_CLASS; c++) {\n    CLASSES cls = (CLASSES)c;\n    if (eval_image[c]) {\n      fp_det = fopen((result_dir + \"/stats_\" + CLASS_NAMES[c] + \"_detection.txt\").c_str(), \"w\");\n      if(compute_aos)\n        fp_ori = fopen((result_dir + \"/stats_\" + CLASS_NAMES[c] + \"_orientation.txt\").c_str(),\"w\");\n      vector<double> precision[3], aos[3];\n      if(   !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, imageBoxOverlap, precision[0], aos[0], EASY, IMAGE)\n         || !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, imageBoxOverlap, precision[1], aos[1], MODERATE, IMAGE)\n         || !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, imageBoxOverlap, precision[2], aos[2], HARD, IMAGE)) {\n        mail->msg(\"%s evaluation failed.\", CLASS_NAMES[c].c_str());\n        return false;\n      }\n      fclose(fp_det);\n      saveAndPlotPlots(plot_dir, CLASS_NAMES[c] + \"_detection\", CLASS_NAMES[c], precision, 0);\n      if(compute_aos){\n        saveAndPlotPlots(plot_dir, CLASS_NAMES[c] + \"_orientation\", CLASS_NAMES[c], aos, 1);\n        fclose(fp_ori);\n      }\n    }\n  }\n\n  // don't evaluate AOS for birdview boxes and 3D boxes\n  compute_aos = false;\n\n  // eval bird's eye view bounding boxes\n  for (int c = 0; c < NUM_CLASS; c++) {\n    CLASSES cls = (CLASSES)c;\n    if (eval_ground[c]) {\n      fp_det = fopen((result_dir + \"/stats_\" + CLASS_NAMES[c] + \"_detection_ground.txt\").c_str(), \"w\");\n      vector<double> precision[3], aos[3];\n      if(   !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, groundBoxOverlap, precision[0], aos[0], EASY, GROUND)\n         || !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, groundBoxOverlap, precision[1], aos[1], MODERATE, GROUND)\n         || !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, groundBoxOverlap, precision[2], aos[2], HARD, GROUND)) {\n        mail->msg(\"%s evaluation failed.\", CLASS_NAMES[c].c_str());\n        return false;\n      }\n      fclose(fp_det);\n      saveAndPlotPlots(plot_dir, CLASS_NAMES[c] + \"_detection_ground\", CLASS_NAMES[c], precision, 0);\n    }\n  }\n\n  // eval 3D bounding boxes\n  for (int c = 0; c < NUM_CLASS; c++) {\n    CLASSES cls = (CLASSES)c;\n    if (eval_3d[c]) {\n      fp_det = fopen((result_dir + \"/stats_\" + CLASS_NAMES[c] + \"_detection_3d.txt\").c_str(), \"w\");\n      vector<double> precision[3], aos[3];\n      if(   !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, box3DOverlap, precision[0], aos[0], EASY, BOX3D)\n         || !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, box3DOverlap, precision[1], aos[1], MODERATE, BOX3D)\n         || !eval_class(fp_det, fp_ori, cls, groundtruth, detections, compute_aos, box3DOverlap, precision[2], aos[2], HARD, BOX3D)) {\n        mail->msg(\"%s evaluation failed.\", CLASS_NAMES[c].c_str());\n        return false;\n      }\n      fclose(fp_det);\n      saveAndPlotPlots(plot_dir, CLASS_NAMES[c] + \"_detection_3d\", CLASS_NAMES[c], precision, 0);\n    }\n  }\n\n  // success\n  return true;\n}\n\nint32_t main (int32_t argc,char *argv[]) {\n\n  // we need 2 or 4 arguments!\n  if (argc!=2 && argc!=4) {\n    cout << \"Usage: ./eval_detection result_sha [user_sha email]\" << endl;\n    return 1;\n  }\n\n  // read arguments\n  string result_sha = argv[1];\n\n  // init notification mail\n  Mail *mail;\n  if (argc==4) mail = new Mail(argv[3]);\n  else         mail = new Mail();\n  mail->msg(\"Thank you for participating in our evaluation!\");\n\n  // run evaluation\n  if (eval(result_sha,mail)) {\n    mail->msg(\"Your evaluation results are available at:\");\n    mail->msg(\"http://www.cvlibs.net/datasets/kitti/user_submit_check_login.php?benchmark=object&user=%s&result=%s\",argv[2], result_sha.c_str());\n  } else {\n    system((\"rm -r results/\" + result_sha).c_str());\n    mail->msg(\"An error occured while processing your results.\");\n    mail->msg(\"Please make sure that the data in your zip archive has the right format!\");\n  }\n\n  // send mail and exit\n  delete mail;\n\n  return 0;\n}\n\n\n", "meta": {"hexsha": "c8051bbb6d943ab827f4359c524ce384ccd6b0d2", "size": 33046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eval/KITTI/evaluate_object_3d.cpp", "max_stars_repo_name": "biancaAlexandru/VoxelNet_PyTorch", "max_stars_repo_head_hexsha": "75f7945c698f01f2b4858259b541ee6ffec20d2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 489.0, "max_stars_repo_stars_event_min_datetime": "2017-09-12T08:05:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:34:37.000Z", "max_issues_repo_path": "eval/KITTI/evaluate_object_3d.cpp", "max_issues_repo_name": "biancaAlexandru/VoxelNet_PyTorch", "max_issues_repo_head_hexsha": "75f7945c698f01f2b4858259b541ee6ffec20d2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2017-10-17T09:59:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T10:58:04.000Z", "max_forks_repo_path": "eval/KITTI/evaluate_object_3d.cpp", "max_forks_repo_name": "biancaAlexandru/VoxelNet_PyTorch", "max_forks_repo_head_hexsha": "75f7945c698f01f2b4858259b541ee6ffec20d2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 168.0, "max_forks_repo_forks_event_min_datetime": "2017-09-25T16:45:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T09:05:28.000Z", "avg_line_length": 35.8805646037, "max_line_length": 224, "alphanum_fraction": 0.6208315681, "num_tokens": 8967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1904953404269261}}
{"text": "#ifndef __wrapper_MSSMNoFV_onshell_def_gm2calc_1_2_0_hpp__\n#define __wrapper_MSSMNoFV_onshell_def_gm2calc_1_2_0_hpp__\n\n#include <Eigen/Core>\n#include \"wrapper_MSSMNoFV_onshell_mass_eigenstates_decl.hpp\"\n\n#include \"identification.hpp\"\n\nnamespace CAT_3(BACKENDNAME,_,SAFE_VERSION)\n{\n   \n   namespace gm2calc\n   {\n      \n      // Member functions: \n      inline void MSSMNoFV_onshell::set_verbose_output(bool flag)\n      {\n         get_BEptr()->set_verbose_output(flag);\n      }\n      \n      inline bool MSSMNoFV_onshell::do_verbose_output() const\n      {\n         return get_BEptr()->do_verbose_output();\n      }\n      \n      inline void MSSMNoFV_onshell::set_alpha_MZ(double arg_1)\n      {\n         get_BEptr()->set_alpha_MZ(arg_1);\n      }\n      \n      inline void MSSMNoFV_onshell::set_alpha_thompson(double arg_1)\n      {\n         get_BEptr()->set_alpha_thompson(arg_1);\n      }\n      \n      inline void MSSMNoFV_onshell::set_Ae(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& A)\n      {\n         get_BEptr()->set_Ae(A);\n      }\n      \n      inline void MSSMNoFV_onshell::set_Au(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& A)\n      {\n         get_BEptr()->set_Au(A);\n      }\n      \n      inline void MSSMNoFV_onshell::set_Ad(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& A)\n      {\n         get_BEptr()->set_Ad(A);\n      }\n      \n      inline void MSSMNoFV_onshell::set_Ae(unsigned int i, unsigned int k, double a)\n      {\n         get_BEptr()->set_Ae(i, k, a);\n      }\n      \n      inline void MSSMNoFV_onshell::set_Au(unsigned int i, unsigned int k, double a)\n      {\n         get_BEptr()->set_Au(i, k, a);\n      }\n      \n      inline void MSSMNoFV_onshell::set_Ad(unsigned int i, unsigned int k, double a)\n      {\n         get_BEptr()->set_Ad(i, k, a);\n      }\n      \n      inline void MSSMNoFV_onshell::set_MA0(double m)\n      {\n         get_BEptr()->set_MA0(m);\n      }\n      \n      inline void MSSMNoFV_onshell::set_TB(double arg_1)\n      {\n         get_BEptr()->set_TB(arg_1);\n      }\n      \n      inline double MSSMNoFV_onshell::get_EL() const\n      {\n         return get_BEptr()->get_EL();\n      }\n      \n      inline double MSSMNoFV_onshell::get_EL0() const\n      {\n         return get_BEptr()->get_EL0();\n      }\n      \n      inline double MSSMNoFV_onshell::get_gY() const\n      {\n         return get_BEptr()->get_gY();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MUDIM() const\n      {\n         return get_BEptr()->get_MUDIM();\n      }\n      \n      inline double MSSMNoFV_onshell::get_TB() const\n      {\n         return get_BEptr()->get_TB();\n      }\n      \n      inline double MSSMNoFV_onshell::get_vev() const\n      {\n         return get_BEptr()->get_vev();\n      }\n      \n      inline const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& MSSMNoFV_onshell::get_Ae() const\n      {\n         return get_BEptr()->get_Ae();\n      }\n      \n      inline const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& MSSMNoFV_onshell::get_Au() const\n      {\n         return get_BEptr()->get_Au();\n      }\n      \n      inline const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& MSSMNoFV_onshell::get_Ad() const\n      {\n         return get_BEptr()->get_Ad();\n      }\n      \n      inline double MSSMNoFV_onshell::get_Ae(unsigned int i, unsigned int k) const\n      {\n         return get_BEptr()->get_Ae(i, k);\n      }\n      \n      inline double MSSMNoFV_onshell::get_Au(unsigned int i, unsigned int k) const\n      {\n         return get_BEptr()->get_Au(i, k);\n      }\n      \n      inline double MSSMNoFV_onshell::get_Ad(unsigned int i, unsigned int k) const\n      {\n         return get_BEptr()->get_Ad(i, k);\n      }\n      \n      inline double MSSMNoFV_onshell::get_MW() const\n      {\n         return get_BEptr()->get_MW();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MZ() const\n      {\n         return get_BEptr()->get_MZ();\n      }\n      \n      inline double MSSMNoFV_onshell::get_ME() const\n      {\n         return get_BEptr()->get_ME();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MM() const\n      {\n         return get_BEptr()->get_MM();\n      }\n      \n      inline double MSSMNoFV_onshell::get_ML() const\n      {\n         return get_BEptr()->get_ML();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MU() const\n      {\n         return get_BEptr()->get_MU();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MC() const\n      {\n         return get_BEptr()->get_MC();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MT() const\n      {\n         return get_BEptr()->get_MT();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MD() const\n      {\n         return get_BEptr()->get_MD();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MS() const\n      {\n         return get_BEptr()->get_MS();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MBMB() const\n      {\n         return get_BEptr()->get_MBMB();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MB() const\n      {\n         return get_BEptr()->get_MB();\n      }\n      \n      inline double MSSMNoFV_onshell::get_MA0() const\n      {\n         return get_BEptr()->get_MA0();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_USe() const\n      {\n         return get_BEptr()->get_USe();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_USm() const\n      {\n         return get_BEptr()->get_USm();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_UStau() const\n      {\n         return get_BEptr()->get_UStau();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_USu() const\n      {\n         return get_BEptr()->get_USu();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_USd() const\n      {\n         return get_BEptr()->get_USd();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_USc() const\n      {\n         return get_BEptr()->get_USc();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_USs() const\n      {\n         return get_BEptr()->get_USs();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_USb() const\n      {\n         return get_BEptr()->get_USb();\n      }\n      \n      inline const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& MSSMNoFV_onshell::get_USt() const\n      {\n         return get_BEptr()->get_USt();\n      }\n      \n      inline void MSSMNoFV_onshell::convert_to_onshell(double precision, unsigned int max_iterations)\n      {\n         get_BEptr()->convert_to_onshell(precision, max_iterations);\n      }\n      \n      inline void MSSMNoFV_onshell::convert_to_onshell(double precision)\n      {\n         get_BEptr()->convert_to_onshell__BOSS(precision);\n      }\n      \n      inline void MSSMNoFV_onshell::convert_to_onshell()\n      {\n         get_BEptr()->convert_to_onshell__BOSS();\n      }\n      \n      inline void MSSMNoFV_onshell::calculate_masses()\n      {\n         get_BEptr()->calculate_masses();\n      }\n      \n      inline void MSSMNoFV_onshell::check_problems() const\n      {\n         get_BEptr()->check_problems();\n      }\n      \n      inline void MSSMNoFV_onshell::convert_yukawa_couplings_treelevel()\n      {\n         get_BEptr()->convert_yukawa_couplings_treelevel();\n      }\n      \n      \n      // Wrappers for original constructors: \n      inline MSSMNoFV_onshell::MSSMNoFV_onshell() :\n         MSSMNoFV_onshell_mass_eigenstates(__factory0())\n      {\n         get_BEptr()->set_wptr(this);\n         get_BEptr()->set_delete_wrapper(false);\n      }\n      \n      inline MSSMNoFV_onshell::MSSMNoFV_onshell(const gm2calc::MSSMNoFV_onshell_mass_eigenstates& arg_1) :\n         MSSMNoFV_onshell_mass_eigenstates(__factory1(arg_1))\n      {\n         get_BEptr()->set_wptr(this);\n         get_BEptr()->set_delete_wrapper(false);\n      }\n      \n      // Special pointer-based constructor: \n      inline MSSMNoFV_onshell::MSSMNoFV_onshell(Abstract_MSSMNoFV_onshell* in) :\n         MSSMNoFV_onshell_mass_eigenstates(in)\n      {\n         get_BEptr()->set_wptr(this);\n         get_BEptr()->set_delete_wrapper(false);\n      }\n      \n      // Copy constructor: \n      inline MSSMNoFV_onshell::MSSMNoFV_onshell(const MSSMNoFV_onshell& in) :\n         MSSMNoFV_onshell_mass_eigenstates(in.get_BEptr()->pointer_copy__BOSS())\n      {\n         get_BEptr()->set_wptr(this);\n         get_BEptr()->set_delete_wrapper(false);\n      }\n      \n      // Assignment operator: \n      inline MSSMNoFV_onshell& MSSMNoFV_onshell::operator=(const MSSMNoFV_onshell& in)\n      {\n         if (this != &in)\n         {\n            get_BEptr()->pointer_assign__BOSS(in.get_BEptr());\n         }\n         return *this;\n      }\n      \n      \n      // Destructor: \n      inline MSSMNoFV_onshell::~MSSMNoFV_onshell()\n      {\n         if (get_BEptr() != 0)\n         {\n            get_BEptr()->set_delete_wrapper(false);\n            if (can_delete_BEptr())\n            {\n               delete BEptr;\n               BEptr = 0;\n            }\n         }\n         set_delete_BEptr(false);\n      }\n      \n      // Returns correctly casted pointer to Abstract class: \n      inline Abstract_MSSMNoFV_onshell* gm2calc::MSSMNoFV_onshell::get_BEptr() const\n      {\n         return dynamic_cast<Abstract_MSSMNoFV_onshell*>(BEptr);\n      }\n   }\n   \n}\n\n\n#include \"gambit/Backends/backend_undefs.hpp\"\n\n#endif /* __wrapper_MSSMNoFV_onshell_def_gm2calc_1_2_0_hpp__ */\n", "meta": {"hexsha": "a78932984b7c716c8e8960641499294970a964a1", "size": 9515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/wrapper_MSSMNoFV_onshell_def.hpp", "max_stars_repo_name": "GambitBSM/gambit_2.0", "max_stars_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T22:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T22:53:26.000Z", "max_issues_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/wrapper_MSSMNoFV_onshell_def.hpp", "max_issues_repo_name": "GambitBSM/gambit_2.0", "max_issues_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T11:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T17:24:41.000Z", "max_forks_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/wrapper_MSSMNoFV_onshell_def.hpp", "max_forks_repo_name": "GambitBSM/gambit_2.0", "max_forks_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:31:41.000Z", "avg_line_length": 27.4207492795, "max_line_length": 106, "alphanum_fraction": 0.570152391, "num_tokens": 2750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.1904745969102407}}
{"text": "/***************************************************************************\n * Copyright 1998-2018 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 <boost/format.hpp>\n\n#include \"slg/engines/bidirvmcpu/bidirvmcpu.h\"\n\nusing namespace std;\nusing namespace luxrays;\nusing namespace slg;\n\nvoid HashGrid::Build(vector<vector<PathVertexVM> > &pathsVertices, const float radius) {\n\t// Reset statistic counters\n\t//mergeHitsV2V = 0;\n\t//mergeHitsV2S = 0;\n\t//mergeHitsS2S = 0;\n\n\tradius2 = radius * radius;\n\n\t// Build the vertices bounding box\n\tvertexCount = 0;\n\tvertexBBox = BBox();\n\tfor (u_int i = 0; i < pathsVertices.size(); ++i) {\n\t\tvertexCount += pathsVertices[i].size();\n\n\t\tfor (u_int j = 0; j < pathsVertices[i].size(); ++j)\n\t\t\tvertexBBox = Union(vertexBBox, pathsVertices[i][j].bsdf.hitPoint.p);\n\t}\n\n\tif (vertexCount <= 0)\n\t\treturn;\n\n\tvertexBBox.Expand(radius + DEFAULT_EPSILON_STATIC);\n\n\t// Calculate the size of the grid cell\n\tconst float cellSize = radius * 2.f;\n\tinvCellSize = 1.f / cellSize;\n\n\tgridSize = vertexCount;\t\n\tcellEnds.resize(gridSize);\n\tfill(cellEnds.begin(), cellEnds.end(), 0);\n\tlightVertices.resize(gridSize, NULL);\n\n\tfor (u_int i = 0, k = 0; i < pathsVertices.size(); ++i) {\n\t\tfor (u_int j = 0; j < pathsVertices[i].size(); ++j, ++k) {\n\t\t\tconst PathVertexVM *vertex = &pathsVertices[i][j];\n\n\t\t\tcellEnds[Hash(vertex->bsdf.hitPoint.p)]++;\n\t\t}\n\t}\n\n\tint sum = 0;\n\tfor (u_int i = 0; i < cellEnds.size(); ++i) {\n\t\tint temp = cellEnds[i];\n\t\tcellEnds[i] = sum;\n\t\tsum += temp;\n\t}\n\t\n\tfor (u_int i = 0; i < pathsVertices.size(); ++i) {\n\t\tfor (u_int j = 0; j < pathsVertices[i].size(); ++j) {\n\t\t\tconst PathVertexVM *vertex = &pathsVertices[i][j];\n\n\t\t\tconst int targetIdx = cellEnds[Hash(vertex->bsdf.hitPoint.p)]++;\n            lightVertices[targetIdx] = vertex;\n\t\t}\n\t}\n}\n\nvoid HashGrid::Process(const BiDirVMCPURenderThread *thread,\n\t\tconst PathVertexVM &eyeVertex, Spectrum *radiance) const {\n\tif ((vertexCount <= 0) ||\n\t\t\t!vertexBBox.Inside(eyeVertex.bsdf.hitPoint.p))\n\t\treturn;\n\n\tconst Vector distMin = eyeVertex.bsdf.hitPoint.p - vertexBBox.pMin;\n\tconst Vector cellPoint = invCellSize * distMin;\n\tconst Vector coordFloor(floorf(cellPoint.x), floorf(cellPoint.y), floorf(cellPoint.z));\n\n\tconst int px = int(coordFloor.x);\n\tconst int py = int(coordFloor.y);\n\tconst int pz = int(coordFloor.z);\n\n\tconst Vector fractCoord = cellPoint - coordFloor;\n\n\tconst int pxo = px + ((fractCoord.x < .5f) ? -1 : +1);\n\tconst int pyo = py + ((fractCoord.y < .5f) ? -1 : +1);\n\tconst int pzo = pz + ((fractCoord.z < .5f) ? -1 : +1);\n\n\tint i0, i1;\n\tHashRange(Hash(px, py, pz), &i0, &i1);\n\tProcess(thread, eyeVertex, i0, i1, radiance);\n\tHashRange(Hash(px, py, pzo), &i0, &i1);\n\tProcess(thread, eyeVertex, i0, i1, radiance);\n\tHashRange(Hash(px, pyo, pz), &i0, &i1);\n\tProcess(thread, eyeVertex, i0, i1, radiance);\n\tHashRange(Hash(px, pyo, pzo), &i0, &i1);\n\tProcess(thread, eyeVertex, i0, i1, radiance);\n\tHashRange(Hash(pxo, py, pz), &i0, &i1);\n\tProcess(thread, eyeVertex, i0, i1, radiance);\n\tHashRange(Hash(pxo, py, pzo), &i0, &i1);\n\tProcess(thread, eyeVertex, i0, i1, radiance);\n\tHashRange(Hash(pxo, pyo, pz), &i0, &i1);\n\tProcess(thread, eyeVertex, i0, i1, radiance);\n\tHashRange(Hash(pxo, pyo, pzo), &i0, &i1);\n\tProcess(thread, eyeVertex, i0, i1, radiance);\n}\n\nvoid HashGrid::Process(const BiDirVMCPURenderThread *thread,\n\t\tconst PathVertexVM &eyeVertex, const int i0, const int i1,\n\t\tSpectrum *radiance) const {\n\tfor (int i = i0; i < i1; ++i) {\n\t\tconst PathVertexVM *lightVertex = lightVertices[i];\n\t\tProcess(thread, eyeVertex, lightVertex, radiance);\n\t}\n}\n\nvoid HashGrid::Process(const BiDirVMCPURenderThread *thread,\n\t\tconst PathVertexVM &eyeVertex, const PathVertexVM *lightVertex,\n\t\tSpectrum *radiance) const {\n\tconst float distance2 = (lightVertex->bsdf.hitPoint.p - eyeVertex.bsdf.hitPoint.p).LengthSquared();\n\n\tif (distance2 <= radius2) {\n\t\tfloat eyeBsdfPdfW, eyeBsdfRevPdfW;\n\t\tBSDFEvent eyeEvent;\n\t\t// I need to remove the dotN term from the result (see below)\n\t\tSpectrum eyeBsdfEval = eyeVertex.bsdf.Evaluate(lightVertex->bsdf.hitPoint.fixedDir,\n\t\t\t\t&eyeEvent, &eyeBsdfPdfW, &eyeBsdfRevPdfW);\n\t\tif(eyeBsdfEval.Black())\n\t\t\treturn;\n\t\t\n\t\t// Volume BSDF doesn't multiply BSDF::Evaluate() by dotN so I need\n\t\t// to remove the term only if it isn't a Volume\n\t\tif (!eyeVertex.bsdf.IsVolume())\n\t\t\teyeBsdfEval /= AbsDot(lightVertex->bsdf.hitPoint.fixedDir, eyeVertex.bsdf.hitPoint.geometryN);\n\n\t\tBiDirVMCPURenderEngine *engine = (BiDirVMCPURenderEngine *)thread->renderEngine;\n\t\tif (eyeVertex.depth >= engine->rrDepth) {\n\t\t\t// Russian Roulette\n\t\t\tconst float prob = RenderEngine::RussianRouletteProb(eyeBsdfEval, engine->rrImportanceCap);\n\t\t\teyeBsdfPdfW *= prob;\n\t\t\teyeBsdfRevPdfW *= prob; // Note: SmallVCM uses light prob here\n\t\t}\n\n\t\t// MIS weights\n\t\tconst float weightLight = lightVertex->dVCM * thread->misVcWeightFactor +\n\t\t\tlightVertex->dVM * BiDirVMCPURenderThread::MIS(eyeBsdfPdfW);\n\t\tconst float weightCamera = eyeVertex.dVCM * thread->misVcWeightFactor +\n\t\t\teyeVertex.dVM * BiDirVMCPURenderThread::MIS(eyeBsdfRevPdfW);\n\t\tconst float misWeight = 1.f / (weightLight + 1.f + weightCamera);\n\n\t\tradiance[lightVertex->lightID] += (thread->vmNormalization * misWeight) *\n\t\t\t\teyeVertex.throughput * eyeBsdfEval * lightVertex->throughput;\n\n\t\t// Statistics\n\t\t/*if (eyeVertex.bsdf.IsVolume()) {\n\t\t\tif (lightVertex->bsdf.IsVolume())\n\t\t\t\t++mergeHitsV2V;\n\t\t\telse\n\t\t\t\t++mergeHitsV2S;\n\t\t} else {\n\t\t\tif (lightVertex->bsdf.IsVolume())\n\t\t\t\t++mergeHitsV2S;\n\t\t\telse\n\t\t\t\t++mergeHitsS2S;\t\t\t\n\t\t}*/\n\t}\n}\n\n/*void HashGrid::PrintStatistics() const {\n\tconst double mergeTotal = mergeHitsV2V + mergeHitsV2S + mergeHitsS2S;\n\n\tif (mergeTotal == 0.f)\n\t\tcout << \"Volume2Volume = 0  Volume2Surface = 0  Volume2Volume = 0\\n\";\n\telse\n\t\tcout << boost::format(\"Volume2Volume = %d (%.2f%%)  Volume2Surface = %d (%.2f%%)  Surface2Surface = %d (%.2f%%)\") %\n\t\t\t\tmergeHitsV2V % (100.0 * mergeHitsV2V / mergeTotal) %\n\t\t\t\tmergeHitsV2S % (100.0 * mergeHitsV2S / mergeTotal) %\n\t\t\t\tmergeHitsS2S % (100.0 * mergeHitsS2S / mergeTotal) << \"\\n\";\n}*/\n", "meta": {"hexsha": "8183fab8f52825f77e8970e688f600dc481809e3", "size": 7165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/slg/engines/bidirvmcpu/hashgrid.cpp", "max_stars_repo_name": "aedancullen/LuxCore", "max_stars_repo_head_hexsha": "2b2289ce985ddc1ba1a44f932e1f76ee9a1c3e3a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-19T22:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T22:00:26.000Z", "max_issues_repo_path": "src/slg/engines/bidirvmcpu/hashgrid.cpp", "max_issues_repo_name": "aedancullen/LuxCore", "max_issues_repo_head_hexsha": "2b2289ce985ddc1ba1a44f932e1f76ee9a1c3e3a", "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/engines/bidirvmcpu/hashgrid.cpp", "max_forks_repo_name": "aedancullen/LuxCore", "max_forks_repo_head_hexsha": "2b2289ce985ddc1ba1a44f932e1f76ee9a1c3e3a", "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.7435897436, "max_line_length": 117, "alphanum_fraction": 0.6273551989, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.19047459597325161}}
{"text": "#ifndef CRC_HPP\n#define CRC_HPP\n\n/**\n * @Author Pawel Ptasznik\n *\n * @Copyright Terabee 2020\n *\n */\n\n#include <boost/crc.hpp>\n\nnamespace terabee\n{\nnamespace internal\n{\nnamespace crc\n{\n\ninline uint8_t calcCrc8(const uint8_t* data, int numBytes)\n{\n  boost::crc_optimal<8, 0x7, 0, 0> crc;\n  crc.process_bytes(data, numBytes);\n  return crc.checksum();\n}\n\ninline uint32_t calcCrc32(const uint8_t* data, int numBytes)\n{\n  boost::crc_optimal<32, 0x4C11DB7, 0xFFFFFFFF, 0> crc;\n  crc.process_bytes(data, numBytes);\n  return crc.checksum();\n}\n\n}  // namespace crc\n}  // namespace internal\n}  // namespace terabee\n\n#endif  // CRC_HPP\n", "meta": {"hexsha": "2249e79d78fa947cf3f32a7c7437881024fd2e0d", "size": 624, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/terabee/internal/crc/crc.hpp", "max_stars_repo_name": "Terabee/terabee_api", "max_stars_repo_head_hexsha": "87ed2f00b8a807e28fa1117923736db611a1945d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-06-09T07:56:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T08:20:01.000Z", "max_issues_repo_path": "include/terabee/internal/crc/crc.hpp", "max_issues_repo_name": "Terabee/terabee_api", "max_issues_repo_head_hexsha": "87ed2f00b8a807e28fa1117923736db611a1945d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-26T01:24:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-21T07:55:54.000Z", "max_forks_repo_path": "include/terabee/internal/crc/crc.hpp", "max_forks_repo_name": "Terabee/terabee_api", "max_forks_repo_head_hexsha": "87ed2f00b8a807e28fa1117923736db611a1945d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-22T16:48:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-22T16:48:05.000Z", "avg_line_length": 16.0, "max_line_length": 60, "alphanum_fraction": 0.703525641, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.19047459597325161}}
{"text": "/*****************************************\n *** Model of a single LIF/MAT2 neuron ***\n *****************************************/\n\n/*** Copyright 2017-2021 Jannik Luboeinski ***\n *** licensed under Apache-2.0 (http://www.apache.org/licenses/LICENSE-2.0) ***\n\n *** Uses the library boost/archive - ***\n *** Copyright 2002 Robert Ramey ***\n *** licensed under the Boost Software License v1.0 (http://www.boost.org/LICENSE_1_0.txt) ***\n\n *** Uses the library boost/serialization -  ***\n *** Copyright 2002 Robert Ramey, 2005 Matthias Troyer ***\n *** licensed under the Boost Software License v1.0 (http://www.boost.org/LICENSE_1_0.txt) ***/\n\n#include <random>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/vector.hpp>\n#include \"Stimulus.cpp\"\n\nusing namespace std;\n\n/*** Neuron class ***\n * Represents one neuron */\nclass Neuron {\t\n\nfriend class boost::serialization::access;\n\nprivate:\n\n/*** Computational parameters ***/\ndouble dt; // s, one timestep for numerical simulation\n\n/*** State variables ***/\ndouble V; // mV, the current membrane potential at the soma\n#if DENDR_SPIKES == ON\ndouble I_dendr; // nA, the current evoked by dendritic spikes\ndouble I_dendr_A; // nA, first contribution to the current evoked by dendritic spikes\ndouble I_dendr_B; // nA, second contribution to the current evoked by dendritic spikes\ndouble I_dendr_C; // nA, third contribution to the current evoked by dendritic spikes\ndouble dendr_inp_integral; // nC, the integral over the charge deposited in the dendrite in the last 2 ms (or conductivity \n                           // in case of conductance-based synapses)\nvector<double> dendr_inp_history; // nC, vector containing the PSC amplitudes of the last 2 ms\ndouble dendr_int_window; // s, dendritic integration window\ndouble refractory_dendr; // s, time span until refractory period for dendritic spikes is over\ndouble t_ref_dendr; // s, absolute refractory period for dendritic spikes - has to be at least one timestep!\ndouble dendr_spike_threshold; // nC, threshold that dendr_inp_integral has to cross for a dendritic spike to be evoked\ndouble I_dendr_A_amp; // nC, amplitude of first current component of dendritic spikes\ndouble I_dendr_B_amp; // nC, amplitude of second current component of dendritic spikes\ndouble I_dendr_C_amp; // nC, amplitude of third current component of dendritic spikes\ndouble tau_dendr_A; // s, decay time constant of first current component of dendritic spikes\ndouble tau_dendr_B; // s, decay time constant of first current component of dendritic spikes\ndouble tau_dendr_C; // s, decay time constant of first current component of dendritic spikes\n#endif\n#if NEURON_MODEL == MAT2\ndouble ad_th; // mV, the adaptive voltage threshold\ndouble exp1; // mV, the fast component of the adaptive voltage threshold\ndouble exp2; // mV, the slow component of the adaptive voltage threshold\n#endif\ndouble p_P; // the protein amount for LTP in this neuron\ndouble p_C; // the common protein amount for LTP and LTP in this neuron\ndouble p_D; // the protein amount for LTD in this neuron\ndouble I_stim; // nA, the externally applied stimulus current\ndouble I_bg; // nA, the external background noise current (computed using Gaussian noise or an OU process with mean 0)\n#if COND_BASED_SYN == ON\ndouble I_int_exc; // nA, the synaptic input from excitatory network neurons affecting this neuron\ndouble I_int_inh; // nA, the synaptic input from inhibitory network neurons affecting this neuron\ndouble V_exc_syn_rev; // mV, the reversal potential for conductance-based, excitatory synapses\ndouble V_inh_syn_rev; // mV, the reversal potential for conductance-based, inhibitory synapses\n#endif\ndouble I_int; // nA, the synaptic input from other network neurons affecting this neuron\ndouble refractory; // s, time span until absolute refractory period is over\nbool active; // specifies if neuron is currently spiking\nint spike_count; // the total number of spikes that occurred since the last reset\nvector<int> spike_history; // vector of all spike times (in units of timesteps) in the process since the last reset\nint spike_history_reserve; // the maximum number of spikes\nint inh_incoming; // number of incoming inhibitory connections in a network\nint exc_incoming; // number of incoming excitatory connections in a network\nint inh_outgoing; // number of outgoing connections to inhibitory neurons in a network\nint exc_outgoing; // number of outgoing connections to excitatory neurons in a network\nvector<int> outgoing; // vector of all outgoing connections to neurons in a network\nStimulus cst; // current stimulus for this neuron\nminstd_rand0 rg; // default uniform generator for random numbers (seed is chosen in constructor)\nnormal_distribution<double> norm_dist; // normal distribution to obtain Gaussian white noise, constructed in Neuron class constructor\n#ifdef TWO_NEURONS_ONE_SYNAPSE\nbool poisson_neuron; // indicates if the neuron solely serves as Poisson spike generator\n#endif\n\nprotected:\n\n/*** Physical parameters ***/\ndouble tau_mem; // s, the membrane time constant\ndouble R_mem; // M\u03a9, resistance of the cell membrane\ndouble V_rev; // mV, the reversal potential of the neuron\ndouble V_reset; // mV, the reset potential of the neuron\ndouble t_ref; // s, absolute refractory period - has to be at least one timestep!\n#if NEURON_MODEL == LIF\ndouble V_th; // mV, the threshold potential of the neuron\ndouble V_spike; // mV, the height of an action potential\n#elif NEURON_MODEL == MAT2\ndouble ad_th_limit; // mV, the limit of the adaptive voltage threshold for time toward infinity\n#endif\ndouble tau_OU; // s, correlation time of the Ornstein-Uhlenbeck process\ndouble sigma_WN; // nA s^1/2, standard deviation of the Gaussian white noise driving the OU process\n#if SYNAPSE_MODEL == MONOEXP\ndouble sigma_OU; // nA, standard deviation of the OU process\n#endif\ndouble I_0; // nA, the mean of the external synaptic inputs (i.e., of the OU process)\nint type; // the type of this neuron (inhibitory/excitatory - TYPE_INH/TYPE_EXC)\n\n/*** normalRandomNumber ***\n * Returns a random number drawn from a normal distribution with standard deviation 1 and mean 0 *\n * - return: the random number of type double (technically in units of sqrt(s)) */\ninline double normalRandomNumber()\n{\n\tdouble nd = norm_dist(rg);\n\n\t/* Check for mean and standard deviation *\n\tstatic int i = 0;\n\tstatic double mean =0.0;\n\tstatic double var =0.0;\n\tconst int av_steps = 1000000;\n\ti++;\n\tmean += nd;\n\tvar += pow2(nd); // compute variance based on an assumed mean of 0.0\n\tif (i == av_steps)\n\t{\n\t\tcout << endl << \"mean: \" << mean / double(av_steps) << endl;\n\t\tcout << \"stddev: \" << sqrt(var / double(av_steps)) << endl;\n\t\tmean = 0.0;\n\t\tvar = 0.0;\n\t\ti=0;\n\t} */\n\treturn nd;\n}\n\npublic:\n\n/*** saveNeuronParams ***\n * Saves all the neuron parameters to a given file */\nvoid saveNeuronParams(ofstream *f) const\n{\n\t*f << endl;\n\t*f << \"Neuron parameters:\" << endl;\n\t*f << \"tau_mem = \" << tau_mem << \" s\" << endl;\n\t*f << \"R_mem = \" << R_mem << \" M\u03a9\" << endl;\n\t*f << \"V_rev = \" << V_rev << \" mV\" << endl;\n\t*f << \"t_ref = \" << t_ref << \" s\" << endl;\n#if NEURON_MODEL == LIF\n\t*f << \"V_reset = \" << V_reset << \" mV\" << endl;\n\t*f << \"V_th = \" << V_th << \" mV\" << endl;\n\t*f << \"V_spike = \" << V_spike << \" mV\" << endl;\n#endif\n#if COND_BASED_SYN == ON\n\t*f << \"V_exc_syn_rev = \" << V_exc_syn_rev << \" mV\" << endl;\n\t*f << \"V_inh_syn_rev = \" << V_inh_syn_rev << \" mV\" << endl;\n#endif\n\t*f << \"tau_OU = \" << tau_OU << \" s\" << endl;\n\t*f << \"sigma_WN = \" << sigma_WN << \" nA s^1/2\" << endl;\n\t*f << \"I_0 = \" << I_0 << \" nA\" << endl;\n#if COND_BASED_SYN == ON\n\t\n#endif\n#if DENDR_SPIKES == ON\n\t*f << \"t_ref_dendr = \" << t_ref_dendr << \" s\" << endl;\n\t*f << \"dendr_spike_threshold = \" << dendr_spike_threshold << \" nC\" << endl;\n\t*f << \"dendr_int_window = \" << dendr_int_window << \" s\" << endl;\n\t*f << \"I_dendr_A_amp = \" << I_dendr_A_amp << \" nA\" << endl;\n\t*f << \"I_dendr_B_amp = \" << I_dendr_B_amp << \" nA\" << endl;\n\t*f << \"I_dendr_C_amp = \" << I_dendr_C_amp << \" nA\" << endl;\n\t*f << \"tau_dendr_A = \" << tau_dendr_A << \" s\" << endl;\n\t*f << \"tau_dendr_B = \" << tau_dendr_B << \" s\" << endl;\n\t*f << \"tau_dendr_C = \" << tau_dendr_C << \" s\" << endl;\n#endif\n}\n\n/*** serialize ***\n * Saves all state variables to a file using serialization from boost *\n * - ar: the archive stream *\n * - version: the archive version */\ntemplate<class Archive> void serialize(Archive &ar, const unsigned int version)\n{\n\tar & V;\n#if DENDR_SPIKES == ON\n\tar & I_dendr;\n\tar & I_dendr_A;\n\tar & I_dendr_B;\n\tar & I_dendr_C;\n\tar & dendr_inp_integral;\n\tar & dendr_inp_history;\n\tar & refractory_dendr;\n#endif\n#if NEURON_MODEL == MAT2\n\tar & ad_th;\n\tar & exp1;\n\tar & exp2;\n#endif\n\tar & p_P;\n\tar & p_C;\n\tar & p_D;\n\tar & I_stim;\n\tar & I_bg;\n#if COND_BASED_SYN == ON\n\tar & I_int_exc;\n\tar & I_int_inh;\n\tar & V_exc_syn_rev;\n\tar & V_inh_syn_rev;\n#endif\n\tar & I_int;\n\tar & refractory;\n\tar & active;\n\tar & spike_count;\n\tar & spike_history;\n}\n\n/*** getNumberIncoming ***\n * Returns the number of either inhibitory or excitatory incoming connections to this neuron *\n * from other neurons in a network *\n * - int type: the type of incoming connections (inh./exc.)\n * - return: the number of incoming connections */\nint getNumberIncoming(int type) const\n{\n\tif (type == TYPE_INH)\n\t\treturn inh_incoming;\n\telse if (type == TYPE_EXC)\n\t\treturn exc_incoming;\n\telse\n\t\tthrow invalid_argument(\"Invalid neuron type.\");\n}\n\n/*** getNumberOutgoing ***\n * Returns the number of connections outgoing from this neuron to other *\n * neurons (of a specific type) *\n * - int type [optional]: the type of the postsynaptic neuron (inh./exc.)\n * - return: the number of outgoing connections */\nint getNumberOutgoing(int type) const\n{\n\tif (type == TYPE_INH)\n\t\treturn inh_outgoing;\n\telse if (type == TYPE_EXC)\n\t\treturn exc_outgoing;\n\telse\n\t\tthrow invalid_argument(\"Invalid neuron type.\");\n}\nint getNumberOutgoing() const\n{\n\treturn outgoing.size();\n}\n\n/*** incNumberIncoming ***\n * Increases the number of incoming connections to this neuron (only to be used while *\n * a network is being built) *\n * - int type: the type of the presynaptic neuron (inh./exc.) */\nvoid incNumberIncoming(int type)\n{\n\tif (type == TYPE_INH)\n\t\tinh_incoming++;\n\telse if (type == TYPE_EXC)\n\t\texc_incoming++;\n}\n\n/*** addOutgoingConnection ***\n * Adds an outgoing connection from this neuron to another one (only to be used while a network is being built) *\n * - index: the index of the neuron that receives the connection *\n * - int type: the type of the receiving neuron (inh./exc.) */\nvoid addOutgoingConnection(int index, int type)\n{\n\toutgoing.push_back(index);\n\n\tif (type == TYPE_INH)\n\t\tinh_outgoing++;\n\telse if (type == TYPE_EXC)\n\t\texc_outgoing++;\n}\n\n/*** getOutgoingConnection ***\n * Returns the index of a neuron receiving an outgoing connection *\n * - arr_index: the index of the connection in the array *\n * - return: the index of the neuron that receives the connection */\nint getOutgoingConnection(int arr_index) const\n{\n\treturn outgoing[arr_index];\n}\n\n/*** getVoltage ***\n * Returns the membrane potential of the neuron *\n * - return: the membrane potential in mV */\ndouble getVoltage() const\n{\n\treturn V;\n}\n\n/*** getThreshold ***\n * Returns the value of the (possibly) dynamic membrane threshold of the neuron *\n * - return: the membrane threshold in mV */\ndouble getThreshold() const\n{\n#if NEURON_MODEL == LIF\n\treturn V_th;\n#elif NEURON_MODEL == MAT2\n\treturn ad_th;\n#endif\n}\n\n/*** getCurrent ***\n * Returns total current affecting the neuron *\n * - return: the instantaneous current in nA */\ndouble getCurrent() const\n{\n\treturn I_stim+I_bg+I_int;\n}\n\n/*** getStimulusCurrent ***\n * Returns current evoked by external stimulation *\n * - return: the instantaneous current stimulus in nA */\ndouble getStimulusCurrent() const\n{\n\treturn I_stim;\n}\n\n/*** getBGCurrent ***\n * Returns current external background current accounting for external inputs *\n * - return: the instantaneous external background current in nA */\ndouble getBGCurrent() const\n{\n\treturn I_bg;\n}\n\n/*** getConstCurrent ***\n * Returns the mean of the external current *\n * - return: the constant current in nA */\ndouble getConstCurrent() const\n{\n\treturn I_0;\n}\n\n/*** getSigma ***\n * Returns the standard deviation of the white noise entering the external current *\n * - return: the standard deviation in nA s^(1/2) */\ndouble getSigma() const\n{\n\treturn sigma_WN;\n}\n\n/*** getSynapticCurrent ***\n * Returns the internal synaptic current that arrived in the previous timestep *\n * - return: the synaptic current in nA */\ndouble getSynapticCurrent() const\n{\n\treturn I_int;\n}\n\n/*** setSynapticCurrent ***\n * Sets the synaptic input current from other neurons within the network to this neuron *\n * - _I_int: the synaptic current in nA */\nvoid setSynapticCurrent(const double _I_int)\n{\n\tI_int = _I_int;\n}\n\n#if COND_BASED_SYN == ON\n/*** getExcSynapticCurrent ***\n * Returns the internal excitatory synaptic conductance of the previous timestep *\n * - return: the excitatory synaptic conductance in nS */\ndouble getExcSynapticCurrent() const\n{\n\treturn I_int_exc;\n}\n\n/*** getInhSynapticCurrent ***\n * Returns the internal inhibitory synaptic conductance of the previous timestep *\n * - return: the inhibitory synaptic conductance in nS */\ndouble getInhSynapticCurrent() const\n{\n\treturn I_int_inh;\n}\n\n\n/*** setExcSynapticCurrent ***\n * Sets the synaptic input current from excitatory neurons within the network to this neuron *\n * - _I_int_exc: the synaptic current/conductance in nA/nS */\nvoid setExcSynapticCurrent(const double _I_int_exc)\n{\n\tI_int_exc = _I_int_exc;\n}\n\n/*** setInhSynapticCurrent ***\n * Sets the synaptic input current from inhibitory neurons within the network to this neuron *\n * - _I_int_inh: the synaptic current/conductance in nA/nS */\nvoid setInhSynapticCurrent(const double _I_int_inh)\n{\n\tI_int_inh = _I_int_inh;\n}\n#endif\n\n/*** increaseExcSynapticCurrent ***\n * Adds a specified contribution to the excitatory synaptic input current/conductance *\n * - contr: the contribution to be added to the synaptic current/conductance in nA/nS */\nvoid increaseExcSynapticCurrent(const double contr)\n{\n#if COND_BASED_SYN == ON\n\tI_int_exc += contr;\n#else\n\tI_int += contr;\n#endif\n}\n\n/*** increaseInhSynapticCurrent ***\n * Adds a specified contribution to the inhibitory synaptic input current/conductance *\n * - contr: the contribution to be added to the synaptic current/conductance in nA/nS */\nvoid increaseInhSynapticCurrent(const double contr)\n{\n#if COND_BASED_SYN == ON\n\tI_int_inh += contr;\n#else\n\tI_int -= contr;\n#endif\n}\n\n#if DENDR_SPIKES == ON\n/*** updateDendriteInput ***\n * Adds the the amplitude of a PSC current to the history and to the integral of the deposited charge *\n * - psc_amplitude: the PSC amplitde in nA/nS/nC */\nvoid updateDendriteInput(const double psc_amplitude)\n{\n\tdendr_inp_history[dendr_inp_history.size()-1] += psc_amplitude;\n\tdendr_inp_integral += psc_amplitude;\n}\n\n/*** getDendriticCurrent ***\n * Returns the current that dendritic spiking caused in the previous timestep *\n * - return: the synaptic current in nA */\ndouble getDendriticCurrent() const\n{\n\treturn I_dendr;\n}\n\n/*** compDendriticCurrent ***\n * Computes the dendritic current at time t as in Jahnke et al., 2015 *\n * - t: the time counted from the beginning of a dendritic spike *\nvoid compDendriticCurrent(double t)\n{    \n    I_dendr = -55.*exp(-t/0.0002) + 64.*exp(-t/0.0003) - 9.*exp(-t/0.0007);\n}*/\n#endif\n\n/*** getActivity ***\n * Returns true if the neuron is spiking in this instant of duration dt *\n * ATTENTION: can cause complications when used in a population for it does *\n * not include information about the exact spike time *\n * - return: whether neuron is firing or not */\nbool getActivity() const\n{\n\tif (active)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\n/*** getSpikeTime ***\n * Returns the spike time for a given spike number (ATTENTION: argument n should not exceed the result of getSpikeHistorySize() -\n * this is not checked here for performance reasons) *\n * - int n: the number of the spike (in temporal order, starting with 1)\n * - return: the spike time in units of time bins for the n-th spike (or -1 if it does not exist) */\nint getSpikeTime(int n) const\n{\n\treturn spike_history[n-1];\n}\n\n/*** spikeAt ***\n * Returns whether or not a spike has occurred at a given timestep, begins searching *\n * from latest spike *\n * - int t_step: the time bin at which the spike should have occurred\n * - return: true if a spike occurred, false if not */\nbool spikeAt(int t_step) const\n{\n\tfor(int i=spike_history.size()-1; i>=0; i--)\n\t{\n\t\tif (spike_history[i] == t_step) // value that is looked for\n\t\t\treturn true;\n\t\telse if (spike_history[i] < t_step) // already below value that is looked for\n\t\t\treturn false;\n\t}\n\treturn false;\n}\n\n/*** spikesInInterval ***\n * Counts the number of spikes in a given interval *\n * - int tb_start: the time bin at which the interval begins *\n * - int tb_end: one time bin after the interval ends *\n * - return: the number of spikes in the given interval */\nint spikesInInterval(int tb_start, int tb_end) const\n{\n\tint count = 0;\n\n\tfor(int i=spike_history.size()-1; i>=0; i--)\n\t{\n\t\tif (spike_history[i] >= tb_start && spike_history[i] < tb_end)\n\t\t\tcount++;\n\t}\n\n\treturn count;\n}\n\n/*** hideSpikeTime ***\n * \"Hides\" the spike time for a given spike number, which means that *\n * it will be stored as a negative number, such that it will not anymore *\n * be taken into consideration for synaptic transmission *\n * (WAS ONLY NECESSARY FOR AN APPROXIMATION THAT IS NOT USED ANYMORE) *\n * - int n: the number of the spike (in temporal order, starting with 1)\n * - return: the spike time for the n-th spike (or -1.0 if it does not exist) */\nvoid hideSpikeTime(int n)\n{\n\tif (n <= spike_history.size() && n >= 1)\n\t\tspike_history[n-1] *= -1;\n}\n\n/*** removeSpikes ***\n * Removes a specified set of spikes from history, to save memory *\n * - int start: the number of the spike to start with (in temporal order, starting with 1)\n * - int end: the number of the spike to end with (in temporal order, starting with 1) */\nvoid removeSpikes(int start, int end)\n{\n\tspike_history.erase(spike_history.begin()+start-1,spike_history.begin()+end);\n}\n\n/*** getSpikeCount ***\n * Returns the number of spikes that have occurred since the last reset (including those that have been removed) *\n * - return: the number of spikes */\nint getSpikeCount() const\n{\n\treturn spike_count;\n}\n\n/*** getSpikeHistorySize ***\n * Returns the current size of the spike history vector *\n * - return: the size of the spike history vector */\nint getSpikeHistorySize() const\n{\n\treturn spike_history.size();\n}\n\n/*** processTimeStep ***\n * Processes one timestep (of duration delta_t) for the neuron * \n * - int tb_step: timestep at which to evaluate stimulus (< 0 before stimulus onset) *\n * - int tb_init: initial timestep for simple decay process (should be positive only in decaying state!) */\nvoid processTimeStep(int tb_step, int tb_init)\n{\n\tdouble delta_t; // duration of the timestep in seconds, either dt or tb_step-tb_init\n\n\tif (tb_init < 0)\n\t\tdelta_t = dt;\n\telse\n\t\tdelta_t = (tb_step - tb_init) * dt;\n\n#if SYNAPSE_MODEL == DELTA\n\tI_bg = normalRandomNumber() * sqrt(1/delta_t) * sigma_WN + I_0;\n#elif SYNAPSE_MODEL == MONOEXP\n\tI_bg = (I_bg-I_0) * exp(-delta_t/tau_OU) + normalRandomNumber() * sqrt(1. - exp(-2.*delta_t/tau_OU)) * sigma_OU + I_0; // compute external synaptic input in nA\n#endif\n\n#if COND_BASED_SYN == ON\n\t//I_int = (I_int_exc * V_exc_syn_rev + I_int_inh * V_inh_syn_rev - (I_int_exc + I_int_inh) * V) / 1000.; // divide by 1000 to get from nS*mV=pA to nA\n\tI_int = (I_int_exc * (V_exc_syn_rev - V) + I_int_inh * (V_inh_syn_rev - V)) / 1000.; // divide by 1000 to get from nS*mV=pA to nA\n#endif\n\n#ifdef TWO_NEURONS_ONE_SYNAPSE\n\tif (poisson_neuron == false)\n\t{\n#endif\n\n#if NEURON_MODEL == MAT2\n\n\t\t// MAT(2) neuron\n\t\tV = V * exp(-delta_t/tau_mem) + R_mem*(I_int + I_bg) * (1. - exp(-delta_t/tau_mem)); // compute mem. pot. in mV (analytical solution)\n\n\t\texp1 = exp1 * exp(-delta_t/0.01); // fast threshold relaxation\n\t\texp2 = exp2 * exp(-delta_t/0.2); // slow threshold relaxation\n\n\t\tif (active)\n\t\t{\n\n\t\t\texp1 = exp1 + 0.015; // add new spike with full contribution alpha_1\n\t\t\texp2 = exp2 + 0.003; // add new spike with full contribution alpha_2\n\t\t\t\n\t\t\tactive = false;\n\t\t}\n\t\t\n\t\tad_th = ad_th_limit + exp1 + exp2; // update adaptive threshold\n\n#elif NEURON_MODEL == LIF\n\n#if DENDR_SPIKES == ON\n\n\t\t// exponential decay of dendritic spikes\n\t\tI_dendr_A *= exp(- delta_t / tau_dendr_A);\n\t\tI_dendr_B *= exp(- delta_t / tau_dendr_B);\n\t\tI_dendr_C *= exp(- delta_t / tau_dendr_C);\n\n\t\tif (refractory_dendr > EPSILON) // if in refractory period for dendritic spikes\n\t\t{\n\t\t\trefractory_dendr -= delta_t;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (dendr_inp_integral > dendr_spike_threshold) // threshold has been crossed\n\t\t\t{\n\t\t\t\t// dendrite spike contributions do not have to be added up because possible remaining contributions should have decayed to zero\n\t\t\t\tI_dendr_A = -55.; //I_dendr_A -= 55.;\n\t\t\t\tI_dendr_B = 64.; //I_dendr_B += 64.;\n\t\t\t\tI_dendr_C = -9.; //I_dendr_C -= 9.;\n\n\t\t\t\trefractory_dendr = t_ref_dendr;\n\t\t\t}\n\t\t}\n\n\t\t//compDendriticCurrent(tb_step*delta_t - I_dendr_A);\n\t\tI_dendr = I_dendr_A + I_dendr_B + I_dendr_C;\n\t\t\t\n\t\tdendr_inp_integral -= dendr_inp_history[0]; // remove oldest contributions from integral\n\t\tdendr_inp_history.erase(dendr_inp_history.begin()); // remove oldest contributions from history\n\t\tdendr_inp_history.push_back(0.); // add slot for new contributions\n\n#endif\n\n\t\t// LIF\n\t\t//V += delta_t/tau_mem * (- V + V_rev + R_mem*(I_bg + I_int)); // compute mem. pot. in mV (Euler method)\n\t\tV = V * exp(-delta_t/tau_mem) + (V_rev + R_mem*(  I_bg \n\t\t\t                                        + I_int\n#if DENDR_SPIKES == ON\n\t\t                                                + I_dendr\n#endif\n\t\t                                                         )) * (1. - exp(-delta_t/tau_mem)); // compute mem. pot. in mV (analytical solution)\n\n\n\n#endif\n\n#ifdef TWO_NEURONS_ONE_SYNAPSE\n\t} // poisson_neuron == false\n\n\telse\n\t{\n\t\tactive = false;\n\t\tV = V_reset;\n\t} // poisson_neuron == true\n#endif\n\tif (cst.isSet() && tb_init < 0 && abs(I_stim = cst.get(tb_step)) > EPSILON) // stimulation; get stimulus current in nA\n\t{\n#if STIM_TYPE == POISSON_STIMULATION\n\t\tV += R_mem * I_stim;\n#else\n\t\tV += R_mem * I_stim * (1. - exp(-delta_t/tau_mem));\n#endif\n\n#ifdef TWO_NEURONS_ONE_SYNAPSE\n\t#if NEURON_MODEL == MAT2\n\t\tV = ad_th; // definite spiking (the magnitude of I_stim is not important as long as it is finite)\n\t#elif NEURON_MODEL == LIF\n\t\tV = V_th;\n\t#endif\n#endif\n\t}\n\n\tif (refractory > EPSILON // if in refractory period\n#ifdef TWO_NEURONS_ONE_SYNAPSE\n\t   && poisson_neuron == false\n#endif\n\t   )\n\t{\n#if NEURON_MODEL == LIF\n\t\tactive = false;\n\t\t\n\t\tV = V_reset;\n#endif\n\t\trefractory -= delta_t;\n\t}\n\telse\n\t{\n#if NEURON_MODEL == LIF\n\t\tif (V >= V_th) // threshold crossing\n\t\t{\n\t\t\tV = V_reset;\n#elif NEURON_MODEL == MAT2\n\t\tif (V >= ad_th) // threshold crossing\n\t\t{\n#endif\n\t\t\trefractory = t_ref;\n\t\t\tif (tb_step >= 0) // count only those spikes that occur after the stimulus onset\n\t\t\t\tspike_history.push_back(tb_step);\n\n\t\t\tactive = true;\n\t\t\tspike_count++;\n\t\t}\n\t}\n\n}\n\n/*** setProteinAmounts ***\n * Sets the protein amounts in the neuron *\n * - double _p_P: momentary protein amount for potentiation *\n * - double _p_C: momentary common protein amount *\n * - double _p_D: momentary protein amount for depression */\nvoid setProteinAmounts(const double _p_P, const double _p_C, const double _p_D)\n{\n\tp_P = _p_P;\n\tp_C = _p_C;\n\tp_D = _p_D;\n}\n\n/*** getPProteinAmount ***\n * Returns the protein amount for potentiation in the neuron *\n * - return: momentary protein amount */\ndouble getPProteinAmount() const\n{\n\treturn p_P;\n}\n\n/*** getCProteinAmount ***\n * Returns the common protein amount in the neuron *\n * - return: momentary protein amount */\ndouble getCProteinAmount() const\n{\n\treturn p_C;\n}\n\n/*** getDProteinAmount ***\n * Returns the protein amount for depression in the neuron *\n * - return: momentary protein amount */\ndouble getDProteinAmount() const\n{\n\treturn p_D;\n}\n\n/*** setCurrentStimulus ***\n * Sets a current stimulus for the neuron *\n * - Stimulus& _cst: shape of one stimulus period */\nvoid setCurrentStimulus(const Stimulus& _cst)\n{\n\tcst = _cst;\n}\n\n/*** isStimulusSet ***\n * Returns true if a stimulus has been set *\n * - return: the value of isSet() in Stimulus class */\nbool isStimulusSet() const\n{\n\treturn cst.isSet();\n}\n\n/*** multiplyCurrentStimulus ***\n * Multiplies the set current stimulus by a real number *\n * - double r: number to multiply */\nvoid multiplyCurrentStimulus(double r)\n{\n\tcst.multiplyBy(r);\n}\n\n/*** setConstCurrent ***\n * Sets the constant current (mean of Gaussian white noise or OU process) to a newly defined value *\n * - double _I_0: constant current in nA */\nvoid setConstCurrent(double _I_0)\n{\n\tI_0 = _I_0;\n}\n\n/*** setSigma ***\n * Sets the standard deviation of the external input current (i.e., Gaussian white noise or the OU process)*\n * - double _sigma: standard deviation in nA s^1/2 */\nvoid setSigma(double _sigma)\n{\n\tsigma_WN = _sigma;\n\n#if SYNAPSE_MODEL == MONOEXP\n\tsigma_OU = sigma_WN / sqrt(2.*tau_OU); // sigma of the OU process; required unit for tau_OU is [s]\n#endif\n}\n\n/*** setTauOU ***\n * Sets the time constant of the Ornstein-Uhlenbeck process *\n * (synaptic time constant of assumed input synapses) *\n * - double _tau_OU: the synaptic time constant in s*/\nvoid setTauOU(double _tau_OU)\n{\n\ttau_OU = _tau_OU;\n}\n\n/*** setType ***\n * Sets the type of this neuron (inhibitory/excitatory) *\n * - int _type: the neuron type */\nvoid setType(int _type)\n{\n\ttype = _type;\n}\n\n/*** setSpikeHistoryMemory ***\n * Sets the RAM size that shall be reserved for the spike history *\n * - int storage_steps: the size of the storage timespan in timesteps *\n * - return: the reserved size of the spike history vector */\nint setSpikeHistoryMemory(int storage_steps)\n{\n\tspike_history_reserve = int(round(storage_steps*(dt/t_ref)));\n}\n\n/*** getType ***\n * Returns the type of this neuron (inhbitory/excitatory) *\n * - return: the neuron type */\nint getType() const\n{\n\treturn type;\n}\n\n#ifdef TWO_NEURONS_ONE_SYNAPSE\n/*** setPoisson ***\n * Allows for making this neuron a Poisson neuron (used to generate Poissonian spikes only, without own voltage dynamics) *\n * - bool _poisson_neuron: indicates if the neuron shall be Poissonian */\nvoid setPoisson(bool _poisson_neuron)\n{\n\tpoisson_neuron = _poisson_neuron;\n}\n#endif\n\n/*** resetConnections ***\n * Resets the connections *\n * - only_exc: if true, only counters for excitatory connections are reset */\nvoid resetConnections(bool only_exc = false)\n{\n\texc_outgoing = 0;\n\texc_incoming = 0;\n\n\tif (!only_exc)\n\t{\n\t\tinh_outgoing = 0;\n\t\tinh_incoming = 0;\n\t}\n\n\tvector<int>().swap(outgoing);\n}\n\n/*** reset ***\n * Resets neuron to initial state */\nvoid reset()\n{\n\tvector<int>().swap(spike_history); // additionally to clearing the vector, reallocates it\n\tspike_history.reserve(spike_history_reserve); // pre-allocates space for the maximum number of spikes\n\n\tV = V_rev;\n\n#if DENDR_SPIKES == ON\n\tI_dendr = 0.;\n\tI_dendr_A = 0.;//-1000.;\n\tI_dendr_B = 0.;\n\tI_dendr_C = 0.;\n\tdendr_inp_history.assign(int(round(dendr_int_window/dt)), 0.);\n\tdendr_inp_integral = 0.;\n\trefractory_dendr = 0.;\n#endif\n#if NEURON_MODEL == MAT2\n\tad_th = ad_th_limit;\n\texp1 = 0.0;\n\texp2 = 0.0;\n#endif\n\trefractory = 0.0; // neuron ready to fire\n\tp_P = 0.0;\n\tp_C = 0.0;\n\tp_D = 0.0;\n\tI_stim = 0.0;\n\tI_bg = 0.0;\n#if COND_BASED_SYN == ON\n\tI_int_exc = 0.0;\n\tI_int_inh = 0.0;\n#endif\n\tI_int = 0.0;\n\n\tactive = false;\n\tspike_count = 0;\n\t\n\trg.seed(getClockSeed()); // set new seed by clock's epoch\n\tnorm_dist.reset(); // reset the normal distribution for random numbers\n}\n\n\n/*** Constructor ***\n * Sets all parameters on experimentally determined values *\n * _dt: size of a timestep in seconds */\nNeuron(const double _dt) : \n\tdt(_dt), rg(getClockSeed()), norm_dist(0.0,1.0)\n{\n\ttau_mem = 0.010; // from Yamauchi et al., 2011\n\n#if NEURON_MODEL == MAT2\n\n\tt_ref = 0.002; // from Kobayashi et al., 2009\n\n#ifdef TWO_NEURONS_ONE_SYNAPSE_ALT\n\tR_mem = 0.01;\n#elif defined TWO_NEURONS_ONE_SYNAPSE\n\tR_mem = 0.0001; // from Li et al., 2016 (mind that the quantity R here is a different one than there!)\n#else\n\tR_mem = 0.01;\n\t//R_mem = 50.0; // from Kobayashi et al., 2009 / Yamauchi et al., 2009\n#endif\n\n\tV_rev = 0.0;\n\tV_reset = 0.0; // estimated to model afterhypolarization in combination with t_ref (see also Dayan & Abbott, p. 4)\n\tad_th_limit = 0.005; // from Li et al., 2016\n\n#elif NEURON_MODEL == LIF\n\n\tt_ref = 0.002; // estimated to model afterhypolarization in combination with V_reset\n\tR_mem = 10.0; // from Dayan & Abbott, fig. 5.\n\tV_th = -55.0; // from Dayan & Abbott, p. 162\n\tV_spike = 35.0; // estimated from sketch in Bachelor's thesis\n\tV_rev = -65.0; // from Dayan & Abbott, fig. 5.\n\tV_reset = -70.0; // estimated to model afterhypolarization in combination with t_ref (see also Dayan & Abbott, p. 4)\n\n#endif\n\tsigma_WN = 0.;\n#if SYNAPSE_MODEL == MONOEXP\n\tsigma_OU = 0.;\n#endif\n\tI_0 = 0.;\n\ttau_OU = 0.005; // estimated\n\n#ifdef TWO_NEURONS_ONE_SYNAPSE\n\tpoisson_neuron = false;\n#endif\n\n#if COND_BASED_SYN == ON\n\tV_exc_syn_rev = 0.; // Moritz' Master's thesis\n\tV_inh_syn_rev = -70.; // Moritz' Master's thesis\n#endif\n#if DENDR_SPIKES == ON\n\tdendr_spike_threshold = 6.5; // estimated (Jahnke et al., 2015: 8.65)\n\tdendr_int_window = 0.002;\n\tt_ref_dendr = 0.005;\n\tI_dendr_A_amp = -55.;\n\tI_dendr_B_amp = 64.; \n\tI_dendr_C_amp = -9.;\n\ttau_dendr_A = 0.0002;\n\ttau_dendr_B = 0.0003;\n\ttau_dendr_C = 0.0007;\n#endif\n\n\treset();\n\tresetConnections();\n}\n\n/*** Destructor ***\n * Frees the allocated memory */\n~Neuron()\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": "56ae26d9454efa0d9152a15e516f9e98bc7f0637", "size": 29661, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation-code/Neuron.cpp", "max_stars_repo_name": "jlubo/memory-consolidation-stc", "max_stars_repo_head_hexsha": "f9934760e12de324360297d7fc7902623169cb4d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-02T21:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T03:12:07.000Z", "max_issues_repo_path": "simulation-code/Neuron.cpp", "max_issues_repo_name": "jlubo/memory-consolidation-stc", "max_issues_repo_head_hexsha": "f9934760e12de324360297d7fc7902623169cb4d", "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": "simulation-code/Neuron.cpp", "max_forks_repo_name": "jlubo/memory-consolidation-stc", "max_forks_repo_head_hexsha": "f9934760e12de324360297d7fc7902623169cb4d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-22T12:56:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T07:42:36.000Z", "avg_line_length": 30.3592630502, "max_line_length": 160, "alphanum_fraction": 0.6993021139, "num_tokens": 8251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.19047458834015515}}
{"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#include <votca/tools/tokenizer.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/atomcontainer.h\"\n#include \"votca/xtp/classicalsegment.h\"\n\nnamespace votca {\nnamespace xtp {\n\n// MPS files have a weird format positions can be in bohr or angstroem,\n// multipoles are in q*bohr^k, with k rank of multipole and polarisabilities are\n// in angstroem^3\ntemplate <class T>\nvoid ClassicalSegment<T>::LoadFromFile(std::string filename) {\n\n  std::string line;\n  std::ifstream intt;\n  intt.open(filename);\n  double unit_conversion = tools::conv::ang2bohr;\n\n  Index readinmultipoles = 0;\n  Index numberofmultipoles = 0;\n  Vector9d multipoles = Vector9d::Zero();\n  Index rank = 0;\n\n  if (!intt.is_open()) {\n    throw std::runtime_error(\"File:\" + filename + \" could not be opened\");\n  }\n  while (intt.good()) {\n\n    std::getline(intt, line);\n    tools::Tokenizer toker(line, \" \\t\");\n    std::vector<std::string> split = toker.ToVector();\n\n    if (!split.size() || split[0] == \"!\" || split[0].substr(0, 1) == \"!\") {\n      continue;\n    }\n\n    // ! Interesting information here, e.g.\n    // ! DCV2T opt\n    // ! SP        RB3LYP          6-311+G(d,p)\n    // Units bohr\n    //\n    // C          -4.2414603400   -3.8124751600    0.0017575736    Rank  2\n    //  -0.3853409355\n    //  -0.0002321905   0.2401559510   0.6602334308\n    //  -0.7220625314   0.0004894995  -0.0003833545   0.4526409813  -0.50937399\n    //  P 1.75\n\n    // Units used\n    if (split[0] == \"Units\") {\n      std::string units = split[1];\n      if (units != \"bohr\" && units != \"angstrom\") {\n        throw std::runtime_error(\"Unit \" + units + \" in file \" + filename +\n                                 \" not supported.\");\n      }\n      if (units == \"bohr\") {\n        unit_conversion = 1.0;\n      }\n    } else if (split.size() == 6) {\n      // element,  position,  rank limit convert to bohr\n      std::string name = split[0];\n      Eigen::Vector3d pos;\n      Index id = Index(this->_atomlist.size());\n      pos[0] = boost::lexical_cast<double>(split[1]);\n      pos[1] = boost::lexical_cast<double>(split[2]);\n      pos[2] = boost::lexical_cast<double>(split[3]);\n      rank = boost::lexical_cast<Index>(split[5]);\n      numberofmultipoles = (rank + 1) * (rank + 1);\n      multipoles = Vector9d::Zero();\n      pos *= unit_conversion;\n      this->_atomlist.push_back(T(id, name, pos));\n    }\n    // 'P', dipole polarizability\n    else if (split[0] == \"P\") {\n      Eigen::Matrix3d p1;\n      if (split.size() == 7) {\n        double pxx = boost::lexical_cast<double>(split[1]);\n        double pxy = boost::lexical_cast<double>(split[2]);\n        double pxz = boost::lexical_cast<double>(split[3]);\n        double pyy = boost::lexical_cast<double>(split[4]);\n        double pyz = boost::lexical_cast<double>(split[5]);\n        double pzz = boost::lexical_cast<double>(split[6]);\n        p1 << pxx, pxy, pxz, pxy, pyy, pyz, pxz, pyz, pzz;\n      } else if (split.size() == 2) {\n        double pxx = boost::lexical_cast<double>(split[1]);\n        p1 = pxx * Eigen::Matrix3d::Identity();\n      } else {\n        throw std::runtime_error(\"Invalid line in \" + filename + \": \" + line);\n      }\n      double unit_conversion_3 = std::pow(tools::conv::ang2bohr, 3);\n      p1 = p1 * unit_conversion_3;\n      this->_atomlist.back().setpolarization(p1);\n    }\n    // Multipole lines\n    else {\n      // stay in bohr\n      for (const std::string& entry : split) {\n        double qXYZ = boost::lexical_cast<double>(entry);\n        if (multipoles.size() < readinmultipoles) {\n          throw std::runtime_error(\"ReadMpsFile: File\" + filename +\n                                   \"is not properly formatted\");\n        }\n        multipoles(readinmultipoles) = qXYZ;\n        readinmultipoles++;\n      }\n      if (readinmultipoles == numberofmultipoles) {\n        Eigen::Vector3d temp_dipoles = multipoles.segment<3>(1);\n        // mps format for dipoles is z x y\n        // we need x y z\n        multipoles(1) = temp_dipoles(1);\n        multipoles(2) = temp_dipoles(2);\n        multipoles(3) = temp_dipoles(0);\n        this->_atomlist.back().setMultipole(multipoles, rank);\n        readinmultipoles = 0;\n      }\n    }\n  }\n  this->calcPos();\n}\n\ntemplate <class T>\ndouble ClassicalSegment<T>::CalcTotalQ() const {\n  double Q = 0;\n  for (const T& site : this->_atomlist) {\n    Q += site.getCharge();\n  }\n  return Q;\n}\n\ntemplate <class T>\nEigen::Vector3d ClassicalSegment<T>::CalcDipole() const {\n  Eigen::Vector3d dipole = Eigen::Vector3d::Zero();\n\n  Eigen::Vector3d CoM = this->getPos();\n  for (const T& site : this->_atomlist) {\n    dipole += (site.getPos() - CoM) * site.getCharge();\n    dipole += site.getDipole();\n  }\n  return dipole;\n}\n\ntemplate <class T>\nvoid ClassicalSegment<T>::WriteMPS(std::string filename,\n                                   std::string header) const {\n\n  std::ofstream ofs;\n  ofs.open(filename, std::ofstream::out);\n  if (!ofs.is_open()) {\n    throw std::runtime_error(\"Bad file handle: \" + filename);\n  }\n\n  ofs << (boost::format(\"! GENERATED BY VOTCA::XTP::%1$s\\n\") % header);\n  ofs << (boost::format(\"! N=%2$d Q[e]=%1$+1.7f\\n\") % CalcTotalQ() %\n          this->size());\n  ofs << boost::format(\"Units angstrom\\n\");\n\n  for (const T& site : this->_atomlist) {\n    ofs << site.WriteMpsLine(\"angstrom\");\n  }\n  ofs.close();\n}\n\ntemplate <class T>\nstd::string ClassicalSegment<T>::identify() const {\n  return \"\";\n}\n\ntemplate <>\nstd::string ClassicalSegment<PolarSite>::identify() const {\n  return \"PolarSegment\";\n}\ntemplate <>\nstd::string ClassicalSegment<StaticSite>::identify() const {\n  return \"StaticSegment\";\n}\n\ntemplate class ClassicalSegment<PolarSite>;\ntemplate class ClassicalSegment<StaticSite>;\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "0097f66eb541a67ab353fce4e16b6da85d76ce8c", "size": 6490, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/classicalsegment.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/classicalsegment.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/classicalsegment.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": 31.3526570048, "max_line_length": 80, "alphanum_fraction": 0.6090909091, "num_tokens": 1866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.19045119161848864}}
{"text": "/**\n * @file ompl_default_plan_profile.cpp\n * @brief\n *\n * @author Levi Armstrong\n * @date June 18, 2020\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2020, Southwest Research Institute\n *\n * @par License\n * Software License Agreement (Apache License)\n * @par\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 * @par\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 <tesseract_common/macros.h>\nTESSERACT_COMMON_IGNORE_WARNINGS_PUSH\n#include <ompl/geometric/SimpleSetup.h>\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n#include <ompl/tools/multiplan/ParallelPlan.h>\n#include <ompl/base/objectives/PathLengthOptimizationObjective.h>\n#include <ompl/base/goals/GoalStates.h>\n#include <boost/algorithm/string.hpp>\nTESSERACT_COMMON_IGNORE_WARNINGS_POP\n\n#include <tesseract_command_language/instruction_type.h>\n#include <tesseract_command_language/move_instruction.h>\n#include <tesseract_command_language/plan_instruction.h>\n\n#include <tesseract_motion_planners/ompl/profile/ompl_default_plan_profile.h>\n#include <tesseract_motion_planners/ompl/utils.h>\n\n#include <tesseract_motion_planners/ompl/continuous_motion_validator.h>\n#include <tesseract_motion_planners/ompl/discrete_motion_validator.h>\n#include <tesseract_motion_planners/ompl/state_collision_validator.h>\n#include <tesseract_motion_planners/ompl/compound_state_validator.h>\n\n#include <tesseract_kinematics/core/utils.h>\n\nnamespace tesseract_planning\n{\nOMPLDefaultPlanProfile::OMPLDefaultPlanProfile(const tinyxml2::XMLElement& xml_element)\n{\n  const tinyxml2::XMLElement* state_space_element = xml_element.FirstChildElement(\"StateSpace\");\n  const tinyxml2::XMLElement* planning_time_element = xml_element.FirstChildElement(\"PlanningTime\");\n  const tinyxml2::XMLElement* max_solutions_element = xml_element.FirstChildElement(\"MaxSolutions\");\n  const tinyxml2::XMLElement* simplify_element = xml_element.FirstChildElement(\"Simplify\");\n  const tinyxml2::XMLElement* optimize_element = xml_element.FirstChildElement(\"Optimize\");\n  const tinyxml2::XMLElement* planners_element = xml_element.FirstChildElement(\"Planners\");\n  //  const tinyxml2::XMLElement* collision_check_element = xml_element.FirstChildElement(\"CollisionCheck\");\n  //  const tinyxml2::XMLElement* collision_continuous_element = xml_element.FirstChildElement(\"CollisionContinuous\");\n  //  const tinyxml2::XMLElement* collision_safety_margin_element =\n  //  xml_element.FirstChildElement(\"CollisionSafetyMargin\");\n  //  const tinyxml2::XMLElement* longest_valid_segment_fraction_element =\n  //  xml_element.FirstChildElement(\"LongestValidSegme\"\n  //                                                                                                     \"ntFraction\");\n  //  const tinyxml2::XMLElement* longest_valid_segment_length_element =\n  //  xml_element.FirstChildElement(\"LongestValidSegment\"\n  //                                                                                                   \"Length\");\n\n  tinyxml2::XMLError status{ tinyxml2::XMLError::XML_SUCCESS };\n\n  if (state_space_element != nullptr)\n  {\n    auto type = static_cast<int>(OMPLProblemStateSpace::REAL_STATE_SPACE);\n    status = state_space_element->QueryIntAttribute(\"type\", &type);\n    if (status != tinyxml2::XML_SUCCESS)\n      throw std::runtime_error(\"OMPLPlanProfile: Error parsing StateSpace type attribute.\");\n\n    state_space = static_cast<OMPLProblemStateSpace>(type);\n  }\n\n  if (planning_time_element != nullptr)\n  {\n    std::string planning_time_string;\n    status = tesseract_common::QueryStringText(planning_time_element, planning_time_string);\n    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n      throw std::runtime_error(\"OMPLPlanProfile: Error parsing PlanningTime string\");\n\n    if (!tesseract_common::isNumeric(planning_time_string))\n      throw std::runtime_error(\"OMPLPlanProfile: PlanningTime is not a numeric values.\");\n\n    tesseract_common::toNumeric<double>(planning_time_string, planning_time);\n  }\n\n  if (max_solutions_element != nullptr)\n  {\n    std::string max_solutions_string;\n    status = tesseract_common::QueryStringText(max_solutions_element, max_solutions_string);\n    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n      throw std::runtime_error(\"OMPLPlanProfile: Error parsing MaxSolutions string\");\n\n    if (!tesseract_common::isNumeric(max_solutions_string))\n      throw std::runtime_error(\"OMPLPlanProfile: MaxSolutions is not a numeric values.\");\n\n    tesseract_common::toNumeric<int>(max_solutions_string, max_solutions);\n  }\n\n  if (simplify_element != nullptr)\n  {\n    status = simplify_element->QueryBoolText(&simplify);\n    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n      throw std::runtime_error(\"OMPLPlanProfile: Error parsing Simplify string\");\n  }\n\n  if (optimize_element != nullptr)\n  {\n    status = optimize_element->QueryBoolText(&optimize);\n    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n      throw std::runtime_error(\"OMPLPlanProfile: Error parsing Optimize string\");\n  }\n\n  if (planners_element != nullptr)\n  {\n    planners.clear();\n    for (const tinyxml2::XMLElement* e = planners_element->FirstChildElement(\"Planner\"); e != nullptr;\n         e = e->NextSiblingElement(\"Planner\"))\n    {\n      int type{ 0 };\n      status = e->QueryIntAttribute(\"type\", &type);\n      if (status != tinyxml2::XML_SUCCESS)\n        throw std::runtime_error(\"OMPLPlanProfile: Error parsing Planner type attribute.\");\n\n      switch (type)\n      {\n        case static_cast<int>(OMPLPlannerType::SBL):\n        {\n          SBLConfigurator::ConstPtr ompl_planner = std::make_shared<const SBLConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::EST):\n        {\n          ESTConfigurator::ConstPtr ompl_planner = std::make_shared<const ESTConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::LBKPIECE1):\n        {\n          LBKPIECE1Configurator::ConstPtr ompl_planner = std::make_shared<const LBKPIECE1Configurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::BKPIECE1):\n        {\n          BKPIECE1Configurator::ConstPtr ompl_planner = std::make_shared<const BKPIECE1Configurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::KPIECE1):\n        {\n          KPIECE1Configurator::ConstPtr ompl_planner = std::make_shared<const KPIECE1Configurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::BiTRRT):\n        {\n          BiTRRTConfigurator::ConstPtr ompl_planner = std::make_shared<const BiTRRTConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::RRT):\n        {\n          RRTConfigurator::ConstPtr ompl_planner = std::make_shared<const RRTConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::RRTConnect):\n        {\n          RRTConnectConfigurator::ConstPtr ompl_planner = std::make_shared<const RRTConnectConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::RRTstar):\n        {\n          RRTstarConfigurator::ConstPtr ompl_planner = std::make_shared<const RRTstarConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::TRRT):\n        {\n          TRRTConfigurator::ConstPtr ompl_planner = std::make_shared<const TRRTConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::PRM):\n        {\n          PRMConfigurator::ConstPtr ompl_planner = std::make_shared<const PRMConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::PRMstar):\n        {\n          PRMstarConfigurator::ConstPtr ompl_planner = std::make_shared<const PRMstarConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::LazyPRMstar):\n        {\n          LazyPRMstarConfigurator::ConstPtr ompl_planner = std::make_shared<const LazyPRMstarConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        case static_cast<int>(OMPLPlannerType::SPARS):\n        {\n          SPARSConfigurator::ConstPtr ompl_planner = std::make_shared<const SPARSConfigurator>(*e);\n          planners.push_back(ompl_planner);\n          break;\n        }\n        default:\n        {\n          throw std::runtime_error(\"Unsupported OMPL Planner type\");\n        }\n      }\n    }\n  }\n\n  /// @todo Update XML\n  //  if (collision_check_element)\n  //  {\n  //    status = collision_check_element->QueryBoolText(&collision_check);\n  //    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n  //      throw std::runtime_error(\"OMPLPlanProfile: Error parsing CollisionCheck string\");\n  //  }\n\n  //  if (collision_continuous_element)\n  //  {\n  //    status = collision_continuous_element->QueryBoolText(&collision_continuous);\n  //    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n  //      throw std::runtime_error(\"OMPLPlanProfile: Error parsing CollisionContinuous string\");\n  //  }\n\n  /// @todo Update XML\n  //  if (collision_safety_margin_element)\n  //  {\n  //    std::string collision_safety_margin_string;\n  //    status = tesseract_common::QueryStringText(collision_safety_margin_element, collision_safety_margin_string);\n  //    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n  //      throw std::runtime_error(\"OMPLPlanProfile: Error parsing CollisionSafetyMargin string\");\n\n  //    if (!tesseract_common::isNumeric(collision_safety_margin_string))\n  //      throw std::runtime_error(\"OMPLPlanProfile: CollisionSafetyMargin is not a numeric values.\");\n\n  //    tesseract_common::toNumeric<double>(collision_safety_margin_string, collision_safety_margin);\n  //  }\n\n  //  if (longest_valid_segment_fraction_element)\n  //  {\n  //    std::string longest_valid_segment_fraction_string;\n  //    status = tesseract_common::QueryStringText(longest_valid_segment_fraction_element,\n  //                                               longest_valid_segment_fraction_string);\n  //    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n  //      throw std::runtime_error(\"OMPLPlanProfile: Error parsing LongestValidSegmentFraction string\");\n\n  //    if (!tesseract_common::isNumeric(longest_valid_segment_fraction_string))\n  //      throw std::runtime_error(\"OMPLPlanProfile: LongestValidSegmentFraction is not a numeric values.\");\n\n  //    tesseract_common::toNumeric<double>(longest_valid_segment_fraction_string, longest_valid_segment_fraction);\n  //  }\n\n  //  if (longest_valid_segment_length_element)\n  //  {\n  //    std::string longest_valid_segment_length_string;\n  //    status =\n  //        tesseract_common::QueryStringText(longest_valid_segment_length_element,\n  //        longest_valid_segment_length_string);\n  //    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n  //      throw std::runtime_error(\"OMPLPlanProfile: Error parsing LongestValidSegmentLength string\");\n\n  //    if (!tesseract_common::isNumeric(longest_valid_segment_length_string))\n  //      throw std::runtime_error(\"OMPLPlanProfile: LongestValidSegmentLength is not a numeric values.\");\n\n  //    tesseract_common::toNumeric<double>(longest_valid_segment_length_string, longest_valid_segment_length);\n  //  }\n}\n\nvoid OMPLDefaultPlanProfile::setup(OMPLProblem& prob) const\n{\n  prob.planners = planners;\n  prob.planning_time = planning_time;\n  prob.max_solutions = max_solutions;\n  prob.simplify = simplify;\n  prob.optimize = optimize;\n\n  prob.contact_checker->applyContactManagerConfig(collision_check_config.contact_manager_config);\n\n  std::vector<std::string> joint_names = prob.manip->getJointNames();\n  auto dof = static_cast<unsigned>(prob.manip->numJoints());\n  auto limits = prob.manip->getLimits().joint_limits;\n\n  if (state_space == OMPLProblemStateSpace::REAL_STATE_SPACE)\n    prob.extractor = [dof](const ompl::base::State* state) -> Eigen::Map<Eigen::VectorXd> {\n      return tesseract_planning::RealVectorStateSpaceExtractor(state, dof);\n    };\n\n#ifndef OMPL_LESS_1_4_0\n  else if (state_space == OMPLProblemStateSpace::REAL_CONSTRAINTED_STATE_SPACE)\n    prob.extractor = tesseract_planning::ConstrainedStateSpaceExtractor;\n#endif\n  else\n    throw std::runtime_error(\"OMPLMotionPlannerDefaultConfig: Unsupported configuration!\");\n\n  if (prob.state_space == OMPLProblemStateSpace::REAL_STATE_SPACE)\n  {\n    // Construct the OMPL state space for this manipulator\n    ompl::base::StateSpacePtr state_space_ptr;\n\n    auto rss = std::make_shared<ompl::base::RealVectorStateSpace>();\n    for (unsigned i = 0; i < dof; ++i)\n      rss->addDimension(joint_names[i], limits(i, 0), limits(i, 1));\n\n    if (state_sampler_allocator)\n    {\n      rss->setStateSamplerAllocator(\n          [=](const ompl::base::StateSpace* space) { return state_sampler_allocator(space, prob); });\n    }\n    else\n    {\n      Eigen::VectorXd weights = Eigen::VectorXd::Ones(dof);\n      rss->setStateSamplerAllocator(\n          [weights, limits](const ompl::base::StateSpace* state_space) -> ompl::base::StateSamplerPtr {\n            return allocWeightedRealVectorStateSampler(state_space, weights, limits);\n          });\n    }\n\n    state_space_ptr = rss;\n\n    // Setup Longest Valid Segment\n    processLongestValidSegment(state_space_ptr, collision_check_config);\n\n    // Create Simple Setup from state space\n    prob.simple_setup = std::make_shared<ompl::geometric::SimpleSetup>(state_space_ptr);\n\n    // Setup state checking functionality\n    ompl::base::StateValidityCheckerPtr svc_without_collision = processStateValidator(prob);\n\n    // Setup motion validation (i.e. collision checking)\n    processMotionValidator(prob, svc_without_collision);\n\n    // make sure the planners run until the time limit, and get the best possible solution\n    processOptimizationObjective(prob);\n  }\n}\n\nvoid OMPLDefaultPlanProfile::applyGoalStates(OMPLProblem& prob,\n                                             const Eigen::Isometry3d& cartesian_waypoint,\n                                             const Instruction& parent_instruction,\n                                             const ManipulatorInfo& manip_info,\n                                             const std::vector<std::string>& /*active_links*/,\n                                             int /*index*/) const\n{\n  const auto dof = prob.manip->numJoints();\n  tesseract_common::KinematicLimits limits = prob.manip->getLimits();\n\n  assert(isPlanInstruction(parent_instruction));\n  const auto& base_instruction = parent_instruction.as<PlanInstruction>();\n  assert(!(manip_info.empty() && base_instruction.getManipulatorInfo().empty()));\n  ManipulatorInfo mi = manip_info.getCombined(base_instruction.getManipulatorInfo());\n\n  if (mi.manipulator.empty())\n    throw std::runtime_error(\"OMPL, manipulator is empty!\");\n\n  if (mi.tcp_frame.empty())\n    throw std::runtime_error(\"OMPL, tcp_frame is empty!\");\n\n  if (mi.working_frame.empty())\n    throw std::runtime_error(\"OMPL, working_frame is empty!\");\n\n  Eigen::Isometry3d tcp_offset = prob.env->findTCPOffset(mi);\n\n  Eigen::Isometry3d tcp_frame_cwp = cartesian_waypoint * tcp_offset.inverse();\n\n  if (prob.state_space == OMPLProblemStateSpace::REAL_STATE_SPACE)\n  {\n    /** @todo Need to add Descartes pose sample to ompl profile */\n    tesseract_kinematics::KinGroupIKInput ik_input(tcp_frame_cwp, mi.working_frame, mi.tcp_frame);\n    tesseract_kinematics::IKSolutions joint_solutions =\n        std::dynamic_pointer_cast<const tesseract_kinematics::KinematicGroup>(prob.manip)\n            ->calcInvKin({ ik_input }, Eigen::VectorXd::Zero(dof));\n    auto goal_states = std::make_shared<ompl::base::GoalStates>(prob.simple_setup->getSpaceInformation());\n    std::vector<tesseract_collision::ContactResultMap> contact_map_vec(\n        static_cast<std::size_t>(joint_solutions.size()));\n\n    for (std::size_t i = 0; i < joint_solutions.size(); ++i)\n    {\n      Eigen::VectorXd& solution = joint_solutions[i];\n\n      // Check limits\n      if (tesseract_common::satisfiesPositionLimits(solution, limits.joint_limits))\n      {\n        tesseract_common::enforcePositionLimits(solution, limits.joint_limits);\n      }\n      else\n      {\n        CONSOLE_BRIDGE_logDebug(\"In OMPLDefaultPlanProfile: Goal state has invalid bounds\");\n      }\n\n      // Get discrete contact manager for testing provided start and end position\n      // This is required because collision checking happens in motion validators now\n      // instead of the isValid function to avoid unnecessary collision checks.\n      if (!checkStateInCollision(prob, solution, contact_map_vec[i]))\n      {\n        {\n          ompl::base::ScopedState<> goal_state(prob.simple_setup->getStateSpace());\n          for (unsigned j = 0; j < dof; ++j)\n            goal_state[j] = solution[static_cast<Eigen::Index>(j)];\n\n          goal_states->addState(goal_state);\n        }\n\n        auto redundant_solutions = tesseract_kinematics::getRedundantSolutions<double>(\n            solution, limits.joint_limits, prob.manip->getRedundancyCapableJointIndices());\n        for (const auto& rs : redundant_solutions)\n        {\n          ompl::base::ScopedState<> goal_state(prob.simple_setup->getStateSpace());\n          for (unsigned j = 0; j < dof; ++j)\n            goal_state[j] = rs[static_cast<Eigen::Index>(j)];\n\n          goal_states->addState(goal_state);\n        }\n      }\n    }\n\n    if (!goal_states->hasStates())\n    {\n      for (std::size_t i = 0; i < contact_map_vec.size(); i++)\n        for (const auto& contact_vec : contact_map_vec[i])\n          for (const auto& contact : contact_vec.second)\n            CONSOLE_BRIDGE_logError((\"Solution: \" + std::to_string(i) + \"  Links: \" + contact.link_names[0] + \", \" +\n                                     contact.link_names[1] + \"  Distance: \" + std::to_string(contact.distance))\n                                        .c_str());\n      throw std::runtime_error(\"In OMPLDefaultPlanProfile: All goal states are either in collision or outside limits\");\n    }\n    prob.simple_setup->setGoal(goal_states);\n  }\n}\n\nvoid OMPLDefaultPlanProfile::applyGoalStates(OMPLProblem& prob,\n                                             const Eigen::VectorXd& joint_waypoint,\n                                             const Instruction& /*parent_instruction*/,\n                                             const ManipulatorInfo& /*manip_info*/,\n                                             const std::vector<std::string>& /*active_links*/,\n                                             int /*index*/) const\n{\n  const auto dof = prob.manip->numJoints();\n  tesseract_common::KinematicLimits limits = prob.manip->getLimits();\n  if (prob.state_space == OMPLProblemStateSpace::REAL_STATE_SPACE)\n  {\n    // Check limits\n    Eigen::VectorXd solution = joint_waypoint;\n    if (tesseract_common::satisfiesPositionLimits(solution, limits.joint_limits))\n    {\n      tesseract_common::enforcePositionLimits(solution, limits.joint_limits);\n    }\n    else\n    {\n      CONSOLE_BRIDGE_logDebug(\"In OMPLDefaultPlanProfile: Goal state has invalid bounds\");\n    }\n\n    // Get discrete contact manager for testing provided start and end position\n    // This is required because collision checking happens in motion validators now\n    // instead of the isValid function to avoid unnecessary collision checks.\n    tesseract_collision::ContactResultMap contact_map;\n    if (checkStateInCollision(prob, solution, contact_map))\n    {\n      CONSOLE_BRIDGE_logError(\"In OMPLDefaultPlanProfile: Goal state is in collision\");\n      for (const auto& contact_vec : contact_map)\n        for (const auto& contact : contact_vec.second)\n          CONSOLE_BRIDGE_logError((\"Links: \" + contact.link_names[0] + \", \" + contact.link_names[1] +\n                                   \"  Distance: \" + std::to_string(contact.distance))\n                                      .c_str());\n    }\n\n    ompl::base::ScopedState<> goal_state(prob.simple_setup->getStateSpace());\n    for (unsigned i = 0; i < dof; ++i)\n      goal_state[i] = joint_waypoint[i];\n\n    prob.simple_setup->setGoalState(goal_state);\n  }\n}\n\nvoid OMPLDefaultPlanProfile::applyStartStates(OMPLProblem& prob,\n                                              const Eigen::Isometry3d& cartesian_waypoint,\n                                              const Instruction& parent_instruction,\n                                              const ManipulatorInfo& manip_info,\n                                              const std::vector<std::string>& /*active_links*/,\n                                              int /*index*/) const\n{\n  const auto dof = prob.manip->numJoints();\n  tesseract_common::KinematicLimits limits = prob.manip->getLimits();\n\n  assert(isPlanInstruction(parent_instruction));\n  const auto& base_instruction = parent_instruction.as<PlanInstruction>();\n  assert(!(manip_info.empty() && base_instruction.getManipulatorInfo().empty()));\n  ManipulatorInfo mi = manip_info.getCombined(base_instruction.getManipulatorInfo());\n\n  if (mi.manipulator.empty())\n    throw std::runtime_error(\"OMPL, manipulator is empty!\");\n\n  if (mi.tcp_frame.empty())\n    throw std::runtime_error(\"OMPL, tcp_frame is empty!\");\n\n  if (mi.working_frame.empty())\n    throw std::runtime_error(\"OMPL, working_frame is empty!\");\n\n  Eigen::Isometry3d tcp = prob.env->findTCPOffset(mi);\n\n  Eigen::Isometry3d tcp_frame_cwp = cartesian_waypoint * tcp.inverse();\n\n  if (prob.state_space == OMPLProblemStateSpace::REAL_STATE_SPACE)\n  {\n    /** @todo Need to add Descartes pose sampler to ompl profile */\n    /** @todo Need to also provide the seed instruction to use here */\n    tesseract_kinematics::KinGroupIKInput ik_input(tcp_frame_cwp, mi.working_frame, mi.tcp_frame);\n    tesseract_kinematics::IKSolutions joint_solutions =\n        std::dynamic_pointer_cast<const tesseract_kinematics::KinematicGroup>(prob.manip)\n            ->calcInvKin({ ik_input }, Eigen::VectorXd::Zero(dof));\n    bool found_start_state = false;\n    std::vector<tesseract_collision::ContactResultMap> contact_map_vec(joint_solutions.size());\n\n    for (std::size_t i = 0; i < joint_solutions.size(); ++i)\n    {\n      Eigen::VectorXd& solution = joint_solutions[i];\n\n      // Check limits\n      if (tesseract_common::satisfiesPositionLimits(solution, limits.joint_limits))\n      {\n        tesseract_common::enforcePositionLimits(solution, limits.joint_limits);\n      }\n      else\n      {\n        CONSOLE_BRIDGE_logDebug(\"In OMPLDefaultPlanProfile: Start state has invalid bounds\");\n      }\n\n      // Get discrete contact manager for testing provided start and end position\n      // This is required because collision checking happens in motion validators now\n      // instead of the isValid function to avoid unnecessary collision checks.\n      if (!checkStateInCollision(prob, solution, contact_map_vec[i]))\n      {\n        found_start_state = true;\n        {\n          ompl::base::ScopedState<> start_state(prob.simple_setup->getStateSpace());\n          for (unsigned j = 0; j < dof; ++j)\n            start_state[j] = solution[static_cast<Eigen::Index>(j)];\n\n          prob.simple_setup->addStartState(start_state);\n        }\n\n        auto redundant_solutions = tesseract_kinematics::getRedundantSolutions<double>(\n            solution, limits.joint_limits, prob.manip->getRedundancyCapableJointIndices());\n        for (const auto& rs : redundant_solutions)\n        {\n          ompl::base::ScopedState<> start_state(prob.simple_setup->getStateSpace());\n          for (unsigned j = 0; j < dof; ++j)\n            start_state[j] = rs[static_cast<Eigen::Index>(j)];\n\n          prob.simple_setup->addStartState(start_state);\n        }\n      }\n    }\n\n    if (!found_start_state)\n    {\n      for (std::size_t i = 0; i < contact_map_vec.size(); i++)\n        for (const auto& contact_vec : contact_map_vec[i])\n          for (const auto& contact : contact_vec.second)\n            CONSOLE_BRIDGE_logError((\"Solution: \" + std::to_string(i) + \"  Links: \" + contact.link_names[0] + \", \" +\n                                     contact.link_names[1] + \"  Distance: \" + std::to_string(contact.distance))\n                                        .c_str());\n      throw std::runtime_error(\"In OMPLPlannerFreespaceConfig: All start states are either in collision or outside \"\n                               \"limits\");\n    }\n  }\n}\n\nvoid OMPLDefaultPlanProfile::applyStartStates(OMPLProblem& prob,\n                                              const Eigen::VectorXd& joint_waypoint,\n                                              const Instruction& /*parent_instruction*/,\n                                              const ManipulatorInfo& /*manip_info*/,\n                                              const std::vector<std::string>& /*active_links*/,\n                                              int /*index*/) const\n{\n  const auto dof = prob.manip->numJoints();\n  tesseract_common::KinematicLimits limits = prob.manip->getLimits();\n\n  if (prob.state_space == OMPLProblemStateSpace::REAL_STATE_SPACE)\n  {\n    Eigen::VectorXd solution = joint_waypoint;\n\n    if (tesseract_common::satisfiesPositionLimits(solution, limits.joint_limits))\n    {\n      tesseract_common::enforcePositionLimits(solution, limits.joint_limits);\n    }\n    else\n    {\n      CONSOLE_BRIDGE_logDebug(\"In OMPLDefaultPlanProfile: Start state is outside limits\");\n    }\n\n    // Get discrete contact manager for testing provided start and end position\n    // This is required because collision checking happens in motion validators now\n    // instead of the isValid function to avoid unnecessary collision checks.\n    tesseract_collision::ContactResultMap contact_map;\n    if (checkStateInCollision(prob, joint_waypoint, contact_map))\n    {\n      CONSOLE_BRIDGE_logError(\"In OMPLPlannerFreespaceConfig: Start state is in collision\");\n      for (const auto& contact_vec : contact_map)\n        for (const auto& contact : contact_vec.second)\n          CONSOLE_BRIDGE_logError((\"Links: \" + contact.link_names[0] + \", \" + contact.link_names[1] +\n                                   \"  Distance: \" + std::to_string(contact.distance))\n                                      .c_str());\n    }\n\n    ompl::base::ScopedState<> start_state(prob.simple_setup->getStateSpace());\n    for (unsigned i = 0; i < dof; ++i)\n      start_state[i] = joint_waypoint[i];\n\n    prob.simple_setup->addStartState(start_state);\n  }\n}\n\ntinyxml2::XMLElement* OMPLDefaultPlanProfile::toXML(tinyxml2::XMLDocument& doc) const\n{\n  Eigen::IOFormat eigen_format(Eigen::StreamPrecision, Eigen::DontAlignCols, \" \", \" \");\n\n  tinyxml2::XMLElement* xml_planner = doc.NewElement(\"Planner\");\n  xml_planner->SetAttribute(\"type\", std::to_string(2).c_str());\n\n  tinyxml2::XMLElement* xml_ompl = doc.NewElement(\"OMPLPlanProfile\");\n\n  tinyxml2::XMLElement* xml_ompl_planners = doc.NewElement(\"Planners\");\n\n  for (const auto& planner : planners)\n  {\n    tinyxml2::XMLElement* xml_ompl_planner = doc.NewElement(\"Planner\");\n    xml_ompl_planner->SetAttribute(\"type\", std::to_string(static_cast<int>(planner->getType())).c_str());\n    tinyxml2::XMLElement* xml_planner = planner->toXML(doc);\n    xml_ompl_planner->InsertEndChild(xml_planner);\n    xml_ompl_planners->InsertEndChild(xml_ompl_planner);\n  }\n\n  xml_ompl->InsertEndChild(xml_ompl_planners);\n\n  tinyxml2::XMLElement* xml_state_space = doc.NewElement(\"StateSpace\");\n  xml_state_space->SetAttribute(\"type\", std::to_string(static_cast<int>(state_space)).c_str());\n  xml_ompl->InsertEndChild(xml_state_space);\n\n  tinyxml2::XMLElement* xml_planning_time = doc.NewElement(\"PlanningTime\");\n  xml_planning_time->SetText(planning_time);\n  xml_ompl->InsertEndChild(xml_planning_time);\n\n  tinyxml2::XMLElement* xml_max_solutions = doc.NewElement(\"MaxSolutions\");\n  xml_max_solutions->SetText(max_solutions);\n  xml_ompl->InsertEndChild(xml_max_solutions);\n\n  tinyxml2::XMLElement* xml_simplify = doc.NewElement(\"Simplify\");\n  xml_simplify->SetText(simplify);\n  xml_ompl->InsertEndChild(xml_simplify);\n\n  tinyxml2::XMLElement* xml_optimize = doc.NewElement(\"Optimize\");\n  xml_optimize->SetText(optimize);\n  xml_ompl->InsertEndChild(xml_optimize);\n\n  /// @todo Update XML\n  //  tinyxml2::XMLElement* xml_collision_check = doc.NewElement(\"CollisionCheck\");\n  //  xml_collision_check->SetText(collision_check);\n  //  xml_ompl->InsertEndChild(xml_collision_check);\n\n  //  tinyxml2::XMLElement* xml_collision_continuous = doc.NewElement(\"CollisionContinuous\");\n  //  xml_collision_continuous->SetText(collision_continuous);\n  //  xml_ompl->InsertEndChild(xml_collision_continuous);\n\n  //  tinyxml2::XMLElement* xml_collision_safety_margin = doc.NewElement(\"CollisionSafetyMargin\");\n  //  xml_collision_safety_margin->SetText(collision_safety_margin);\n  //  xml_ompl->InsertEndChild(xml_collision_safety_margin);\n\n  //  tinyxml2::XMLElement* xml_long_valid_seg_frac = doc.NewElement(\"LongestValidSegmentFraction\");\n  //  xml_long_valid_seg_frac->SetText(longest_valid_segment_fraction);\n  //  xml_ompl->InsertEndChild(xml_long_valid_seg_frac);\n\n  //  tinyxml2::XMLElement* xml_long_valid_seg_len = doc.NewElement(\"LongestValidSegmentLength\");\n  //  xml_long_valid_seg_len->SetText(longest_valid_segment_length);\n  //  xml_ompl->InsertEndChild(xml_long_valid_seg_len);\n\n  // TODO: Add plugins for state_sampler_allocator, optimization_objective_allocator, svc_allocator,\n  // mv_allocator\n\n  xml_planner->InsertEndChild(xml_ompl);\n\n  return xml_planner;\n}\n\nompl::base::StateValidityCheckerPtr OMPLDefaultPlanProfile::processStateValidator(OMPLProblem& prob) const\n{\n  ompl::base::StateValidityCheckerPtr svc_without_collision;\n  auto csvc = std::make_shared<CompoundStateValidator>();\n  if (svc_allocator != nullptr)\n  {\n    svc_without_collision = svc_allocator(prob.simple_setup->getSpaceInformation(), prob);\n    csvc->addStateValidator(svc_without_collision);\n  }\n\n  if (collision_check_config.type == tesseract_collision::CollisionEvaluatorType::DISCRETE ||\n      collision_check_config.type == tesseract_collision::CollisionEvaluatorType::LVS_DISCRETE)\n  {\n    auto svc = std::make_shared<StateCollisionValidator>(\n        prob.simple_setup->getSpaceInformation(), *prob.env, prob.manip, collision_check_config, prob.extractor);\n    csvc->addStateValidator(svc);\n  }\n  prob.simple_setup->setStateValidityChecker(csvc);\n\n  return svc_without_collision;\n}\n\nvoid OMPLDefaultPlanProfile::processMotionValidator(\n    OMPLProblem& prob,\n    const ompl::base::StateValidityCheckerPtr& svc_without_collision) const\n{\n  if (mv_allocator != nullptr)\n  {\n    auto mv = mv_allocator(prob.simple_setup->getSpaceInformation(), prob);\n    prob.simple_setup->getSpaceInformation()->setMotionValidator(mv);\n  }\n  else\n  {\n    if (collision_check_config.type != tesseract_collision::CollisionEvaluatorType::NONE)\n    {\n      ompl::base::MotionValidatorPtr mv;\n      if (collision_check_config.type == tesseract_collision::CollisionEvaluatorType::CONTINUOUS ||\n          collision_check_config.type == tesseract_collision::CollisionEvaluatorType::LVS_CONTINUOUS)\n      {\n        mv = std::make_shared<ContinuousMotionValidator>(prob.simple_setup->getSpaceInformation(),\n                                                         svc_without_collision,\n                                                         *prob.env,\n                                                         prob.manip,\n                                                         collision_check_config,\n                                                         prob.extractor);\n      }\n      else\n      {\n        // Collision checking is preformed using the state validator which this calls.\n        mv = std::make_shared<DiscreteMotionValidator>(prob.simple_setup->getSpaceInformation());\n      }\n      prob.simple_setup->getSpaceInformation()->setMotionValidator(mv);\n    }\n  }\n}\n\nvoid OMPLDefaultPlanProfile::processOptimizationObjective(OMPLProblem& prob) const\n{\n  if (optimization_objective_allocator)\n  {\n    prob.simple_setup->getProblemDefinition()->setOptimizationObjective(\n        optimization_objective_allocator(prob.simple_setup->getSpaceInformation(), prob));\n  }\n  else if (prob.optimize)\n  {\n    // Add default optimization function to minimize path length\n    prob.simple_setup->getProblemDefinition()->setOptimizationObjective(\n        std::make_shared<ompl::base::PathLengthOptimizationObjective>(prob.simple_setup->getSpaceInformation()));\n  }\n}\n\n}  // namespace tesseract_planning\n", "meta": {"hexsha": "24d5696b8bfc368b77411f0feba9d96ce11437cb", "size": 33511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tesseract_motion_planners/ompl/src/profile/ompl_default_plan_profile.cpp", "max_stars_repo_name": "ros-industrial-consortium/tesseract_planning", "max_stars_repo_head_hexsha": "c32cdabcabc4c67fda5f222177ba0396e2fa2560", "max_stars_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-01-08T16:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T05:30:29.000Z", "max_issues_repo_path": "tesseract_motion_planners/ompl/src/profile/ompl_default_plan_profile.cpp", "max_issues_repo_name": "ros-industrial-consortium/tesseract_planning", "max_issues_repo_head_hexsha": "c32cdabcabc4c67fda5f222177ba0396e2fa2560", "max_issues_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "Apache-2.0"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2021-01-10T23:17:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-24T13:39:28.000Z", "max_forks_repo_path": "tesseract_motion_planners/ompl/src/profile/ompl_default_plan_profile.cpp", "max_forks_repo_name": "ros-industrial-consortium/tesseract_planning", "max_forks_repo_head_hexsha": "c32cdabcabc4c67fda5f222177ba0396e2fa2560", "max_forks_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-01-10T17:55:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T05:39:33.000Z", "avg_line_length": 43.2958656331, "max_line_length": 119, "alphanum_fraction": 0.6833875444, "num_tokens": 7660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.1904511916184886}}
{"text": "/* \n * Author: Johannes M Dieterich\n */\n\n#ifndef FOURIERKEDF_HPP\n#define\tFOURIERKEDF_HPP\n\n#include <armadillo>\n#include <memory>\n#include <string>\n#include \"FourierGrid.hpp\"\n#include \"Grid.hpp\"\n#include \"StressTensor.hpp\"\nusing namespace std;\n\nclass FourierKEDF {\npublic:\n    virtual ~FourierKEDF(){};\n    virtual string getMethodDescription() const = 0;\n    virtual vector<string> getCitations() const = 0;\n    virtual vector<string> getWorkingEquations() const = 0;\n    virtual double calcEnergy(const FourierGrid& grid) const = 0;\n    virtual double calcPotential(const FourierGrid& grid, FourierGrid& potential) const = 0;\n    virtual unique_ptr<StressTensor> calcStress(const FourierGrid& grid) const = 0;\nprivate:\n};\n\n#endif\t/* FOURIERKEDF_HPP */\n\n", "meta": {"hexsha": "28d082d94f35fba9d931d90774aacf57f0244340", "size": 754, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/FourierKEDF.hpp", "max_stars_repo_name": "EACcodes/libKEDF", "max_stars_repo_head_hexsha": "3dff53318ce7be52be5f45242ea8daf08a032866", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T12:13:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-29T01:13:25.000Z", "max_issues_repo_path": "include/FourierKEDF.hpp", "max_issues_repo_name": "EACcodes/libKEDF", "max_issues_repo_head_hexsha": "3dff53318ce7be52be5f45242ea8daf08a032866", "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/FourierKEDF.hpp", "max_forks_repo_name": "EACcodes/libKEDF", "max_forks_repo_head_hexsha": "3dff53318ce7be52be5f45242ea8daf08a032866", "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.1333333333, "max_line_length": 92, "alphanum_fraction": 0.7360742706, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.1904511808329922}}
{"text": "#include \"eigen-delegate.hpp\"\n#include <memory>\n\n#include <Eigen/Core>\n#include <tensorflow/lite/c/builtin_op_data.h>\n\n#define DEBUG\n\nusing namespace tflite::tools;\n\nnamespace tflite\n{\n\nEigenDelegate::EigenDelegate(\n    const SimpleDelegateInterface::Options &options\n) : options(options)\n{}\n\nbool EigenDelegate::IsNodeSupportedByDelegate(\n        const TfLiteRegistration *registration,\n        const TfLiteNode *node,\n        TfLiteContext *context) const\n{\n    switch (registration->builtin_code)\n    {\n        // TODO uncomment\n        // case kTfLiteBuiltinAdd:\n        case kTfLiteBuiltinFullyConnected:\n            break;\n        default:\n            printf(\"Skipped builtin code %d\\n\", registration->builtin_code);\n            return false;\n    }\n    // Only support float32\n    for (int i = 0; i < node->inputs->size; i++)\n    {\n        auto &tensor = context->tensors[node->inputs->data[i]];\n        if (tensor.type != kTfLiteFloat32)\n        {\n            printf(\"Skipped tensor type %d for %d (%s,%d)\\n\",\n                tensor.type,\n                i,\n                registration->custom_name == NULL ? \"\" : registration->custom_name,\n                registration->builtin_code\n            );\n            return false;\n        }\n    }\n    return true;\n}\n\nTfLiteStatus EigenDelegate::Initialize(TfLiteContext *context)\n{\n    return kTfLiteOk;\n}\n\nconst char *EigenDelegate::Name() const\n{\n    static constexpr char kName[] = \"EigenDelegate\";\n    return kName;\n}\n\nstd::unique_ptr<SimpleDelegateKernelInterface> EigenDelegate::CreateDelegateKernelInterface()\n{\n    return std::make_unique<EigenDelegateKernel>();\n}\n\nTfLiteStatus EigenDelegateKernel::Init(TfLiteContext* context, const TfLiteDelegateParams* params)\n{\n    // Save index to all nodes which are part of this delegate.\n    inputs_.resize(params->nodes_to_replace->size);\n    outputs_.resize(params->nodes_to_replace->size);\n    builtin_code_.resize(params->nodes_to_replace->size);\n    nodes_.resize(params->nodes_to_replace->size);\n    for (int i = 0; i < params->nodes_to_replace->size; i++)\n    {\n        const int node_index = params->nodes_to_replace->data[i];\n        // Get this node information.\n        TfLiteNode* delegated_node = nullptr;\n        TfLiteRegistration* delegated_node_registration = nullptr;\n        TF_LITE_ENSURE_EQ(\n            context,\n            context->GetNodeAndRegistration(\n                context,\n                node_index,\n                &delegated_node,\n                &delegated_node_registration\n            ),\n            kTfLiteOk\n        );\n        for (int j = 0; j < delegated_node->inputs->size; j++)\n        {\n            inputs_[i].push_back(delegated_node->inputs->data[j]);\n        }\n        for (int j = 0; j < delegated_node->outputs->size; j++)\n        {\n            outputs_[i].push_back(delegated_node->outputs->data[j]);\n        }\n        builtin_code_[i] = delegated_node_registration->builtin_code;\n        nodes_[i] = delegated_node;\n    }\n    return kTfLiteOk;\n}\n\nTfLiteStatus EigenDelegateKernel::Prepare(TfLiteContext* context, TfLiteNode* node)\n{\n    intermediatedata.clear();\n#ifdef DEBUG\n    printf(\"BEFORE ALLOCATION (tensor id, data address, dims address)\\n\");\n    for (int i = 0; i < context->tensors_size; i++)\n    {\n        printf(\"tensor %d:  %x %x\\n\",\n            i,\n            context->tensors[i].data,\n            context->tensors[i].dims\n        );\n    }\n#endif // DEBUG\n    for (auto &out : outputs_)\n    {\n        for (auto &outid : out)\n        {\n            if (GetTensorData<float *>(&context->tensors[outid]) == NULL)\n            {\n                intermediatedata.push_back(\n                    std::make_unique<std::vector<float>>(\n                        NumElements(&context->tensors[outid])\n                    )\n                );\n                context->tensors[outid].data.f = intermediatedata.back()->data();\n            }\n        }\n    }\n#ifdef DEBUG\n    printf(\"AFTER ALLOCATION (tensor id, data address, dims address)\\n\");\n    for (int i = 0; i < context->tensors_size; i++)\n    {\n        printf(\"tensor %d:  %x %x\\n\",\n            i,\n            context->tensors[i].data,\n            context->tensors[i].dims\n        );\n    }\n#endif // DEBUG\n    return kTfLiteOk;\n}\n\nTfLiteStatus EigenDelegateKernel::Eval(TfLiteContext* context, TfLiteNode* node)\n{\n    TfLiteStatus ret = kTfLiteOk;\n    for (int i = 0; i < inputs_.size(); i++)\n    {\n        switch (builtin_code_[i])\n        {\n            // TODO uncomment\n            // case kTfLiteBuiltinAdd:\n            //     ret = add(context, i);\n            //     break;\n            case kTfLiteBuiltinFullyConnected:\n                ret = fullyConnected(context, i);\n                break;\n            default:\n                ret = kTfLiteDelegateError;\n        }\n        if (ret != kTfLiteOk)\n        {\n            break;\n        }\n    }\n    return ret;\n}\n\nTfLiteStatus EigenDelegateKernel::add(TfLiteContext *context, int nodeid)\n{\n    // TODO implement using Eigen routines\n    return kTfLiteOk;\n}\n\nTfLiteStatus EigenDelegateKernel::fullyConnected(TfLiteContext *context, int nodeid)\n{\n    auto &tfinput = context->tensors[inputs_[nodeid][0]];\n    auto &tfweights = context->tensors[inputs_[nodeid][1]];\n    auto &tfbias = context->tensors[inputs_[nodeid][2]];\n    auto &tfoutput = context->tensors[outputs_[nodeid][0]];\n\n    auto ws = GetTensorShape(&tfweights);\n\n    Eigen::Map<Eigen::VectorXf> input(\n        GetTensorData<float>(&tfinput), NumElements(&tfinput)\n    );\n\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> weights(\n        GetTensorData<float>(&tfweights),\n        ws.Dims(0),\n        ws.Dims(1)\n    );\n\n    Eigen::Map<Eigen::VectorXf> bias(\n        GetTensorData<float>(&tfbias),\n        NumElements(&tfbias)\n    );\n\n    Eigen::Map<Eigen::VectorXf> output(\n        GetTensorData<float>(&tfoutput),\n        NumElements(&tfoutput)\n    );\n\n    output = weights * input + bias;\n\n    TfLiteFullyConnectedParams *params = static_cast<TfLiteFullyConnectedParams *>(\n        nodes_[nodeid]->builtin_data\n    );\n\n    switch (params->activation)\n    {\n        case TfLiteFusedActivation::kTfLiteActNone:\n            break;\n        case TfLiteFusedActivation::kTfLiteActRelu:\n            output = output.cwiseMax(0);\n            break;\n        default:\n            return kTfLiteDelegateError;\n    }\n    return kTfLiteOk;\n}\n\n} // namespace tflite\n\ntflite::SimpleDelegateInterface::Options TfLiteEigenDelegateOptionsDefault() {\n    tflite::SimpleDelegateInterface::Options options = {0};\n    return options;\n}\n\nTfLiteDelegate *TfLiteEigenDelegateCreate(const tflite::SimpleDelegateInterface::Options* options) {\n    std::unique_ptr<tflite::EigenDelegate> custom(\n        new tflite::EigenDelegate(\n            options ? *options : TfLiteEigenDelegateOptionsDefault()\n        )\n    );\n    return tflite::TfLiteDelegateFactory::CreateSimpleDelegate(std::move(custom));\n}\n\nvoid TfLiteEigenDelegateDelete(TfLiteDelegate* delegate) {\n    tflite::TfLiteDelegateFactory::DeleteSimpleDelegate(delegate);\n}\n\nTfLiteDelegate *CreateEigenDelegateFromOptions(char **options_keys, char **options_values, size_t num_options)\n{\n    return TfLiteEigenDelegateCreate(NULL);\n}\n\nTfLiteDelegate *tflite_plugin_create_delegate(char** options_keys, char** options_values, size_t num_options, void (*report_error)(const char*))\n{\n\treturn CreateEigenDelegateFromOptions(options_keys, options_values, num_options);\n}\n\nvoid tflite_plugin_destroy_delegate(TfLiteDelegate *delegate)\n{\n\tTfLiteEigenDelegateDelete(delegate);\n}\n", "meta": {"hexsha": "14d9fbfdc4478fefdd20dd9f103f9b33db8be300", "size": 7561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "delegate-example/src/eigen-delegate.cpp", "max_stars_repo_name": "antmicro/dl-in-iot-course", "max_stars_repo_head_hexsha": "2072b88c97c8f643de6055ee7e3b1506303dab98", "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": "delegate-example/src/eigen-delegate.cpp", "max_issues_repo_name": "antmicro/dl-in-iot-course", "max_issues_repo_head_hexsha": "2072b88c97c8f643de6055ee7e3b1506303dab98", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-09T08:47:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T08:47:50.000Z", "max_forks_repo_path": "delegate-example/src/eigen-delegate.cpp", "max_forks_repo_name": "antmicro/dl-in-iot-course", "max_forks_repo_head_hexsha": "2072b88c97c8f643de6055ee7e3b1506303dab98", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-04T19:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T18:58:44.000Z", "avg_line_length": 28.969348659, "max_line_length": 144, "alphanum_fraction": 0.6224044439, "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1904511789738717}}
{"text": "// Copyright (c) 2016 The UUV Simulator Authors.\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, 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 <uuv_sensor_plugins/UnderwaterCameraPlugin.hh>\n\n#include <chrono>\n#include <cmath>\n#include <iostream>\n#include <stdio.h>\n#include <string>\n\n#include <boost/bind.hpp>\n\n#include \"Common.hh\"\n\nnamespace gazebo {\n\nUnderwaterCameraPlugin::UnderwaterCameraPlugin()\n    : DepthCameraPlugin(),\n      lastImage(nullptr)\n{\n}\n\nUnderwaterCameraPlugin::~UnderwaterCameraPlugin()\n{\n    if (lastImage)\n        delete [] lastImage;\n\n    if (depth2rangeLUT)\n        delete [] depth2rangeLUT;\n}\n\n\nvoid UnderwaterCameraPlugin::Load(sensors::SensorPtr _sensor,\n                                  sdf::ElementPtr _sdf)\n{\n    DepthCameraPlugin::Load(_sensor, _sdf);\n\n    lastImage = new unsigned char[this->width*this->height*this->depth];\n\n    // Only need to load settings specific to this sensor.\n    getSdfParam<float>(_sdf, \"attenuationR\", attenuation[0], 1.f/30.f);\n    getSdfParam<float>(_sdf, \"attenuationG\", attenuation[1], 1.f/30.f);\n    getSdfParam<float>(_sdf, \"attenuationB\", attenuation[2], 1.f/30.f);\n\n    getSdfParam<unsigned char>(_sdf, \"backgroundR\", background[0], 0);\n    getSdfParam<unsigned char>(_sdf, \"backgroundG\", background[1], 0);\n    getSdfParam<unsigned char>(_sdf, \"backgroundB\", background[2], 0);\n\n    // Compute camera intrinsics fx, fy from FOVs:\n#if GAZEBO_MAJOR_VERSION >= 7\n    math::Angle hfov = math::Angle(this->depthCamera->HFOV().Radian());\n    math::Angle vfov = math::Angle(this->depthCamera->VFOV().Radian());\n#else\n    math::Angle hfov = this->depthCamera->GetHFOV();\n    math::Angle vfov = this->depthCamera->GetVFOV();\n#endif\n\n    double fx = (0.5*this->width)/tan(0.5*hfov.Radian());\n    double fy = (0.5*this->height)/tan(0.5*vfov.Radian());\n\n    // Assume the camera's principal point to be at the sensor's center:\n    double cx = 0.5*this->width;\n    double cy = 0.5*this->height;\n\n    // Create and fill depth2range LUT\n    this->depth2rangeLUT = new float[this->width*this->height];\n    float* lutPtr = this->depth2rangeLUT;\n    for (int v = 0; v < this->height; v++)\n    {\n        double y_z = (v - cy)/fy;\n        for (int u = 0; u < this->width; u++)\n        {\n            double x_z = (u - cx)/fx;\n            // Precompute the per-pixel factor in the following formula:\n            // range = || (x, y, z) ||_2\n            // range = || z * (x/z, y/z, 1.0) ||_2\n            // range = z * || (x/z, y/z, 1.0) ||_2\n            *(lutPtr++) = sqrt(1.0 + x_z*x_z + y_z*y_z);\n        }\n    }\n\n    // TODO: Advertise a gazebo topic?\n    //    publisher_ = node_handle_->Advertise<sensor_msgs::msgs::Camera>(\n    //                sensor_topic_, 10);\n}\n\nvoid UnderwaterCameraPlugin::OnNewDepthFrame(const float *_image,\n                                             unsigned int _width,\n                                             unsigned int _height,\n                                             unsigned int _depth,\n                                             const std::string &_format)\n{\n    // TODO: Can we assume this pointer to always remain valid?\n    lastDepth = _image;\n}\n\n\nvoid UnderwaterCameraPlugin::OnNewRGBPointCloud(const float *_pcd,\n                                                unsigned int _width,\n                                                unsigned int _height,\n                                                unsigned int _depth,\n                                                const std::string &_format)\n{\n}\n\nvoid UnderwaterCameraPlugin::OnNewImageFrame(const unsigned char *_image,\n                                             unsigned int _width,\n                                             unsigned int _height,\n                                             unsigned int _depth,\n                                             const std::string &_format)\n{\n    // Only create cv::Mat wrappers around existing memory\n    // (neither allocates nor copies any images).\n    const cv::Mat input(_height, _width, CV_8UC3,\n                        const_cast<unsigned char*>(_image));\n    const cv::Mat depth(_height, _width, CV_32FC1,\n                        const_cast<float*>(lastDepth));\n\n    cv::Mat output(_height, _width, CV_8UC3, lastImage);\n\n    SimulateUnderwater(input, depth, output);\n\n    // TODO: Publish Gazebo topic\n}\n\nvoid UnderwaterCameraPlugin::SimulateUnderwater(const cv::Mat& _inputImage,\n                                                const cv::Mat& _inputDepth,\n                                                cv::Mat& _outputImage)\n{\n    const float* lutPtr = this->depth2rangeLUT;\n    for (unsigned int row = 0; row < this->height; row++)\n    {\n        const cv::Vec3b* inrow = _inputImage.ptr<cv::Vec3b>(row);\n        const float* depthrow = _inputDepth.ptr<float>(row);\n        cv::Vec3b* outrow = _outputImage.ptr<cv::Vec3b>(row);\n\n        for (int col = 0; col < this->width; col++)\n        {\n            // Convert depth to range using the depth2range LUT\n            float r = *(lutPtr++)*depthrow[col];\n            const cv::Vec3b& in = inrow[col];\n            cv::Vec3b& out = outrow[col];\n\n            if (r < 1e-3)\n            {\n              r = 1e10;\n            }\n\n            for (int c = 0; c < 3; c++)\n            {\n                // Simplifying assumption: intensity ~ irradiance.\n                // This is not really the case but a good enough approximation\n                // for now (it would be better to use a proper Radiometric\n                // Response Function).\n                float e = std::exp(-r*attenuation[c]);\n                out[c] = e*in[c] + (1.0f-e)*background[c];\n            }\n        }\n    }\n}\nGZ_REGISTER_SENSOR_PLUGIN(UnderwaterCameraPlugin);\n}\n", "meta": {"hexsha": "c43bd76e327ff4a30911bb994cf1736473e15619", "size": 6213, "ext": "cc", "lang": "C++", "max_stars_repo_path": "uuv_sensor_plugins/uuv_sensor_plugins/src/UnderwaterCameraPlugin.cc", "max_stars_repo_name": "ignaciotb/uuv_simulator", "max_stars_repo_head_hexsha": "b3c46ef713dbcca615627d9f537c88edc8ad8f95", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T08:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T08:59:19.000Z", "max_issues_repo_path": "uuv_sensor_plugins/uuv_sensor_plugins/src/UnderwaterCameraPlugin.cc", "max_issues_repo_name": "ignaciotb/uuv_simulator", "max_issues_repo_head_hexsha": "b3c46ef713dbcca615627d9f537c88edc8ad8f95", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-13T10:58:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T14:09:05.000Z", "max_forks_repo_path": "uuv_sensor_plugins/uuv_sensor_plugins/src/UnderwaterCameraPlugin.cc", "max_forks_repo_name": "ignaciotb/uuv_simulator", "max_forks_repo_head_hexsha": "b3c46ef713dbcca615627d9f537c88edc8ad8f95", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T15:02:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-02T15:14:58.000Z", "avg_line_length": 35.3011363636, "max_line_length": 78, "alphanum_fraction": 0.5649444713, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19037459377410101}}
{"text": "#include \"../base/oz.h\"\n#include \"ozShapeDetector.h\"\n\n#include \"../base/ozAlarmFrame.h\"\n#include <dlib/svm_threaded.h>\n#include <dlib/image_processing.h>\n#include <dlib/data_io.h>\n#include <iostream>\n#include <vector>\n\n/**\n* @brief\n*\n* @param name\n*/\nShapeDetector::ShapeDetector( const std::string &name, const std::string &objectData, ShapeMarkup shapeMarkup ) :\n    VideoProvider( cClass(), name ),\n    Thread( identity() ),\n    mObjectData( objectData ),\n    mShapeMarkup( shapeMarkup )\n{\n}\n\n/**\n* @brief\n*\n* @param markup\n* @param provider\n* @param link\n*/\nShapeDetector::ShapeDetector( const std::string &objectData, ShapeMarkup shapeMarkup, VideoProvider &provider, const FeedLink &link ) :\n    VideoConsumer( cClass(), provider, link ),\n    VideoProvider( cClass(), provider.name() ),\n    Thread( identity() ),\n    mObjectData( objectData ),\n    mShapeMarkup( shapeMarkup )\n{\n}\n\n/**\n* @brief\n*/\nShapeDetector::~ShapeDetector()\n{\n}\n\n/**\n* @brief\n*\n* @return\n*/\nint ShapeDetector::run()\n{\n    config.dir_events = \"/transfer\";\n    config.record_diag_images = true;\n\n    // Wait for encoder to be ready\n    if ( waitForProviders() )\n    {\n        AVPixelFormat pixelFormat = videoProvider()->pixelFormat();\n        int16_t width = videoProvider()->width();\n        int16_t height = videoProvider()->height();\n        Debug( 1,\"pf:%d, %dx%d\", pixelFormat, width, height );\n\n        typedef dlib::scan_fhog_pyramid<dlib::pyramid_down<6> > image_scanner_type;\n\n        dlib::object_detector<image_scanner_type> detector;\n        dlib::deserialize( mObjectData.c_str() ) >> detector;\n\n        setReady();\n        while ( !mStop )\n        {\n            if ( mStop )\n               break;\n            mQueueMutex.lock();\n            if ( !mFrameQueue.empty() )\n            {\n                Debug( 3, \"Got %zd frames on queue\", mFrameQueue.size() );\n                for ( FrameQueue::iterator iter = mFrameQueue.begin(); iter != mFrameQueue.end(); iter++ )\n                {\n                    // Only operate on video frames\n                    const VideoFrame *frame = dynamic_cast<const VideoFrame *>(iter->get());\n                    if ( frame )\n                    {\n                        Image image( pixelFormat, width, height, frame->buffer().data() );\n                        Image convImage( Image::FMT_RGB, image );\n                        dlib::array2d<dlib::rgb_pixel> img( height, width );\n                        memcpy( image_data( img ), convImage.buffer().data(), convImage.buffer().size() );\n                        //assign_image( img, frame->buffer().data() );\n\n                        //Info( \"B4: %d x %d\", num_rows(img), num_columns(img) );\n                        //dlib::pyramid_up(img);\n                        //Info( \"AFT: %d x %d\", num_rows(img), num_columns(img) );\n                        std::vector<dlib::rectangle> dets = detector(img);\n\n                       \tDebug( (dets.size() > 0) ? 1:2,\"%jd @ %ju: Got %jd shapes\", frame->id(), frame->timestamp(), dets.size() );\n                        if ( dets.size() > 0 && mShapeMarkup != OZ_SHAPE_MARKUP_NONE )\n                        {\n                            // Now we will go ask the shape_predictor to tell us the pose of\n                            // each shape we detected.\n                            std::vector<dlib::full_object_detection> shapes;\n                            typedef std::pair<dlib::point,dlib::point> line_t;\n                            std::vector<line_t> lines;\n                            for ( unsigned int i = 0; i < dets.size(); i++ )\n                            {\n                                if ( mShapeMarkup & OZ_SHAPE_MARKUP_OUTLINE )\n                                    draw_rectangle( img, dets[i], dlib::rgb_pixel( 255, 0, 0 ), 1 );\n                            }\n\n                            //dlib::save_png( img, \"/transfer/image.png\" );\n                            //Info( \"%d x %d = %d\", num_rows(img), num_columns(img), 3*num_rows(img)*num_columns(img) );\n                        }\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n                        \tDebug( 2,\"%jd @ %ju: Got %jd shapes\", frame->id(), frame->timestamp(), dets.size() );\n\t\t\t\t\t\t}\n                        // Move inside preceding 'if' to only output 'shape' frames\n                        AlarmFrame *alarmFrame = new AlarmFrame( this, *iter, frame->id(), frame->timestamp(), (uint8_t *)image_data(img), 3*num_rows(img)*num_columns(img), dets.size()>0 );\n\n                        distributeFrame( FramePtr( alarmFrame ) );\n                        mFrameCount++;\n                    }\n                }\n                mFrameQueue.clear();\n            }\n            mQueueMutex.unlock();\n            checkProviders();\n            // Quite short so we can always keep up with the required packet rate for 25/30 fps\n            usleep( INTERFRAME_TIMEOUT );\n        }\n    }\n    FeedProvider::cleanup();\n    FeedConsumer::cleanup();\n    return( !ended() );\n}\n", "meta": {"hexsha": "8adbc2b23fba29d7e047cfebf7911ae8a8da05c6", "size": 4932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "server/src/processors/ozShapeDetector.cpp", "max_stars_repo_name": "dstarikov/ozonebase", "max_stars_repo_head_hexsha": "fd942c6816f0ecb03548bad93219eab5044d6aea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 98.0, "max_stars_repo_stars_event_min_datetime": "2016-06-09T00:10:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T05:10:55.000Z", "max_issues_repo_path": "server/src/processors/ozShapeDetector.cpp", "max_issues_repo_name": "redheavendogg/ozonebase", "max_issues_repo_head_hexsha": "e675f2353b3264dc563d287117e7bfb2c68a54dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 65.0, "max_issues_repo_issues_event_min_datetime": "2016-05-26T14:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-07T05:02:36.000Z", "max_forks_repo_path": "server/src/processors/ozShapeDetector.cpp", "max_forks_repo_name": "redheavendogg/ozonebase", "max_forks_repo_head_hexsha": "e675f2353b3264dc563d287117e7bfb2c68a54dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2016-06-10T20:35:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T05:29:34.000Z", "avg_line_length": 36.2647058824, "max_line_length": 189, "alphanum_fraction": 0.5150040552, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19037458646394362}}
{"text": "// Copyright 2019 Apex.AI, Inc.\n// Co-developed by Tier IV, Inc. and Apex.AI, 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//  \u00a0 \u00a0http://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 <lidar_utils/point_cloud_utils.hpp>\n#include <ndt/visibility_control.hpp>\n#include <sensor_msgs/msg/point_cloud2.hpp>\n#include <geometry_msgs/msg/transform.hpp>\n#include <geometry_msgs/msg/vector3.hpp>\n#include <vector>\n#include <Eigen/src/Core/Matrix.h>\n\nnamespace autoware{\nnamespace localization{\nnamespace ndt{\n\nclass NdtNormal\n{\n\n  using Point = Eigen::Vector3d;\n  using Covariance = Eigen::Matrix3d;\n\n  // getters, setters\n  Point centroid;\n  Covariance covariance;\n};\n\n\n//CRTP base class for NDT maps\ntemplate<typename Derived, typename NdtUnit = NdtNormal>\nclass NdtMapBase\n{\n    // neighbourhood search\n  const std::vector<NdtUnit> & cells(double x, double y, double z);\n};\n\n\n//CRTP base class for NDT scans.\ntemplate<typename Derived, typename NdtUnit = common::lidar_utils::PointXYZIF>\nclass NdtScanBase{\npublic:\n  using Point = NdtUnit;\n  using IterT = typename std::vector<NdtUnit>::iterator;\n  //get the point for a given index.\n  NdtUnit & get(size_t index);\n\n  IterT begin();\n\n  IterT end();\n\nprivate:\n  const Derived & impl() const\n  {\n    return *static_cast<const Derived *>(this);\n  }\n};\n\nclass NDTMap : public NdtMapBase<NDTMap, NdtNormal>{\n    // Use voxelgrid or spatial hash directly etc. instead\n    using MapContainer = std::vector<NdtNormal>;\nprivate:\n    MapContainer m_cells;\n};\n\nclass P2DNDTScan : public NdtScanBase<P2DNDTScan, common::lidar_utils::PointXYZIF>{\n  using PointT = common::lidar_utils::PointXYZIF;\n  const std::vector<PointT> & cells(double x, double y, double z);\n\n  void advance(size_t advancement);\n  PointT next();\n  PointT prev();\n  PointT front();\n  PointT back();\n  void transform(const geometry_msgs::msg::Transform &);\nprivate:\n sensor_msgs::msg::PointCloud2 m_cloud;\n};\n\n}\n}\n}\n", "meta": {"hexsha": "34f36a14a0bab26e5a5bc2e0cb734016147e79fa", "size": 2383, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/localization/ndt/include/ndt/ndt_representations.hpp", "max_stars_repo_name": "jimaldon/AutowareAuto", "max_stars_repo_head_hexsha": "2b639aa06f67e41222c89f3885c0472483ac6b38", "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/localization/ndt/include/ndt/ndt_representations.hpp", "max_issues_repo_name": "jimaldon/AutowareAuto", "max_issues_repo_head_hexsha": "2b639aa06f67e41222c89f3885c0472483ac6b38", "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/ndt_representations.hpp", "max_forks_repo_name": "jimaldon/AutowareAuto", "max_forks_repo_head_hexsha": "2b639aa06f67e41222c89f3885c0472483ac6b38", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-21T04:17:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T04:17:33.000Z", "avg_line_length": 25.623655914, "max_line_length": 83, "alphanum_fraction": 0.7310113303, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.1903745791537864}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <iostream>\n\n#include <boost/math/quaternion.hpp>\n\nextern \"C\" void externalForceG(double t, double* f, unsigned int size_z, double *z){\n  // std::cout << \"externalForceG at time \"<< t << std::endl;\n  f[0]=0;\n  f[1]=0;\n  f[2]=0;\n  \n  if (t > 0.04){\n    f[2] = +1000.0;\n  }\n}\nextern \"C\" void externalMomentumY(double t,double *m, unsigned int size_z, double *z){\n  // std::cout << \"externalMomentumY\"<<std::endl;\n  m[0]=5000;\n  m[1]=0;\n  m[2]=0;\n}\n", "meta": {"hexsha": "c851fbd43cced43d1cc58675fc479063c0c19996", "size": 491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Mechanics/Mechanisms/ShaftTube/TubePlugin/TubePlugin.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/Mechanisms/ShaftTube/TubePlugin/TubePlugin.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/Mechanisms/ShaftTube/TubePlugin/TubePlugin.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": 21.347826087, "max_line_length": 86, "alphanum_fraction": 0.6069246436, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19037457387845103}}
{"text": "#ifndef GIFS_SH_BOMD_CORE_H\n#define GIFS_SH_BOMD_CORE_H\n\n\n#include <armadillo>\n#include \"qm_interface.hpp\"\n#include \"configreader.hpp\"\n\n\nclass BOMD\n{\npublic:\n  explicit BOMD(arma::mat& qm_grd, arma::mat& mm_grd);\n  virtual ~BOMD() {delete qm;}\n  \n  virtual double update_gradient(void);\n  virtual bool rescale_velocities(arma::mat &velocities, arma::vec &masses, arma::mat &total_gradient, double total_energy);\n  // setup from user input\n  void setup(FileHandle& fh,\n             const arma::uvec& atomicnumbers,\n\t         arma::mat& qm_crd,\n\t         arma::mat& mm_crd,\n\t         arma::vec& mm_chg\n          );\n  //\nprotected:\n  inline arma::uword NQM(void) const { return qm_grd.n_cols; }\n  inline arma::uword NMM(void) const { return mm_grd.n_cols; }\n  inline int call_idx() const noexcept { return md_call_idx; };\n\n  /* Config for keys common to all dynamics classes */\n  void add_common_keys(ConfigBlockReader& reader);\n  \n  /* Child classes will override these methods for own setup */\n  virtual ConfigBlockReader setup_reader(void);\n  virtual void get_reader_data(ConfigBlockReader& reader);\n  \n  QMInterface* qm{nullptr};\n  // fixed size\n  arma::mat& qm_grd;\n  // flexible size\n  arma::mat& mm_grd;\n  arma::vec energy{};\n\n  // On which surface are we running?\n  size_t active_state;\n\n  // To track energy drift from GMX\n  double elast = 0, edrift = 0;\n  \nprivate:\n  int md_call_idx = 0; // tracks each call to rescale_velocities();\n};\n\nclass PrintBomd:\n    public BOMD \n{\npublic:\n  virtual ~PrintBomd() {};\n  explicit PrintBomd(arma::mat& qm_grd,\n                     arma::mat& mm_grd) : BOMD(qm_grd, mm_grd) {}\n  \n  double update_gradient(void) {\n    double e = BOMD::update_gradient();\n    qm->crd_qm.t().print(\"qm_crd: \");\n    qm->crd_mm.t().print(\"mm_crd: \");\n    qm_grd.t().print(\"qm_grd\");\n    mm_grd.t().print(\"mm_grd\");\n    return e;\n  }\n\n  bool rescale_velocities(arma::mat &velocities, arma::vec &masses, arma::mat &total_gradient, double total_energy) {\n    BOMD::rescale_velocities(velocities, masses, total_gradient, total_energy);\n    velocities.t().print(\"Velocities:\");\n    masses.t().print(\"Masses:\");\n    total_gradient.t().print(\"Total Gradient\");\n    return true;\n  }\n};\n\n\n#endif\n", "meta": {"hexsha": "36df0b38c2fa9bbbc499f41c3758c4aca333f819", "size": 2210, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bomd.hpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T19:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T19:48:20.000Z", "max_issues_repo_path": "include/bomd.hpp", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "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/bomd.hpp", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 26.6265060241, "max_line_length": 124, "alphanum_fraction": 0.6737556561, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1902450726330614}}
{"text": "// Copyright 2016-2021 Doug Moen\n// Licensed under the Apache License, version 2.0\n// See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0\n\n#include <libcurv/builtin.h>\n\n#include <libcurv/analyser.h>\n#include <libcurv/bool.h>\n#include <libcurv/die.h>\n#include <libcurv/dir_record.h>\n#include <libcurv/exception.h>\n#include <libcurv/function.h>\n#include <libcurv/import.h>\n#include <libcurv/tree.h>\n#include <libcurv/num.h>\n#include <libcurv/pattern.h>\n#include <libcurv/picker.h>\n#include <libcurv/prim_expr.h>\n#include <libcurv/program.h>\n#include <libcurv/sc_compiler.h>\n#include <libcurv/sc_context.h>\n#include <libcurv/source.h>\n#include <libcurv/system.h>\n#include <libcurv/types.h>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cassert>\n#include <climits>\n#include <cmath>\n#include <cstdlib>\n#include <filesystem>\n#include <string>\n\nusing namespace std;\nusing namespace boost::math::double_constants;\n\nnamespace curv {\n\nShared<Meaning>\nBuiltin_Value::to_meaning(const Identifier& id) const\n{\n    return make<Constant>(share(id), value_);\n}\n\n//----------------------------------------------//\n// Templates for constructing builtin functions //\n//----------------------------------------------//\n\ntemplate <class Prim>\nstruct Unary_Array_Func : public Function\n{\n    using Function::Function;\n    using Op = Unary_Array_Op<Prim>;\n    Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        return Op::call(fl, At_Arg(*this, fm), arg);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase> ph, SC_Frame& fm)\n    const override\n    {\n        return Op::sc_op(At_SC_Arg_Expr(*this, ph, fm), argx, fm);\n    }\n};\n\ntemplate <class Prim>\nstruct Binary_Array_Func : public Tuple_Function\n{\n    Binary_Array_Func(const char* nm) : Tuple_Function(2,nm) {}\n    using Op = Binary_Array_Op<Prim>;\n    Value tuple_call(Fail fl, Frame& args) const override\n    {\n        return Op::call(fl, At_Arg(*this, args), args[0], args[1]);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase> ph, SC_Frame& fm)\n    const override\n    {\n        return Op::sc_op(At_SC_Arg_Expr(*this, ph, fm), argx, fm);\n    }\n};\n\ntemplate <class Prim>\nstruct Monoid_Func final : public Function\n{\n    using Function::Function;\n    using Op = Binary_Array_Op<Prim>;\n    Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        return Op::reduce(fl, At_Arg(*this, fm), Prim::zero(), arg);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase> ph, SC_Frame& fm)\n    const override\n    {\n        return Op::sc_reduce(At_SC_Arg_Expr(*this, ph, fm),\n            Prim::zero(), argx, fm);\n    }\n};\n\n//-------------------//\n// Builtin Functions //\n//-------------------//\n\nstruct F_as : public Curried_Function\n{\n    F_as(const char* nm) : Curried_Function(2,nm) {}\n    virtual Value ccall(const Function& self, Fail fl, Frame& args)\n    const override {\n        At_Arg cx(*this, args);\n        auto type = CType::from_value(args[0], Fail::hard, cx);\n        if (type->contains(args[1], cx))\n            return args[1];\n        if (fl == Fail::soft)\n            return missing;\n        throw Exception(At_Arg(self, args),\n            stringify(args[1],\" is not a \",*type));\n    }\n    virtual bool validate_arg(unsigned i, Value a, Fail fl, const At_Syntax& cx)\n    const override {\n        return CType::from_value(a, fl, cx).has_value();\n    }\n};\nstruct F_is : public Curried_Function\n{\n    F_is(const char* nm) : Curried_Function(2,nm) {}\n    virtual Value ccall(const Function& self, Fail, Frame& args)\n    const override {\n        At_Arg cx(*this, args);\n        auto type = CType::from_value(args[0], Fail::hard, cx);\n        return type->contains(args[1], cx);\n    }\n    virtual bool validate_arg(unsigned i, Value a, Fail fl, const At_Syntax& cx)\n    const override {\n        return CType::from_value(a, fl, cx).has_value();\n    }\n};\nstruct F_Tuple : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        std::vector<CType> types;\n        TRY_DEF(list, arg.to<const List>(fl, At_Arg(*this, fm)));\n        for (auto e : *list) {\n            TRY_DEF(type, CType::from_value(e, fl, At_Arg(*this, fm)));\n            types.push_back(type);\n        }\n        if (types.size() > 0) {\n            // Tuple[T]=>Array[1]T, Tuple[T,T]=>Array[2]T, ...\n            bool uniform = true;\n            for (unsigned i = 1; i < types.size(); ++i) {\n                if (types[0] != types[i]) {\n                    uniform = false;\n                    break;\n                }\n            }\n            if (uniform)\n                return {make<Array_Type>(types.size(), types[0])};\n        }\n        return {make<Tuple_Type>(std::move(types))};\n    }\n};\nstruct F_List : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        TRY_DEF(type, CType::from_value(arg, fl, At_Arg(*this, fm)));\n        return {make<List_Type>(type)};\n    }\n};\nstruct F_Array : public Curried_Function\n{\n    static CType make_array_type(\n        unsigned i,\n        const std::vector<int>& axes,\n        CType etype)\n    {\n        if (i == axes.size()) return etype;\n        /* otherwise i < axes.size() */\n        if (axes[i] == 0)\n            return {make<Tuple_Type>(std::vector<CType>{})};\n        etype = make_array_type(i+1, axes, etype);\n        return {make<Array_Type>(axes[i], etype)};\n    }\n    F_Array(const char* nm) : Curried_Function(2,nm) {}\n    virtual Value ccall(const Function& self, Fail fl, Frame& args) const\n    {\n        At_Arg cx(*this, args);\n        TRY_DEF(xlist, args[0].to<const List>(fl, cx));\n        TRY_DEF(etype, CType::from_value(args[1], fl, cx));\n        std::vector<int> axes;\n        for (auto e : *xlist) {\n            if (!e.is_num()) {\n                FAIL(fl, false, cx, stringify(e,\" is not a number\"));\n            }\n            int i;\n            if (!num_to_int(e.to_num_unsafe(), i, 0, INT_MAX, fl, cx))\n                return missing;\n            axes.push_back(i);\n        }\n        return make_array_type(0, axes, etype).to_value();\n    }\n    virtual bool validate_arg(unsigned i, Value a, Fail fl, const At_Syntax& cx)\n    const override {\n        auto xlist = a.to<const List>(fl, cx);\n        if (xlist == nullptr) return false;\n        for (auto e : *xlist) {\n            if (!e.is_num()) {\n                FAIL(fl, false, cx, stringify(e,\" is not a number\"));\n            }\n            int i;\n            if (!num_to_int(e.to_num_unsafe(), i, 0, INT_MAX, fl, cx))\n                return false;\n        }\n        return true;\n    }\n};\nstruct F_Struct : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        Symbol_Map<CType> fields;\n        At_Arg cx(*this, fm);\n        TRY_DEF(rec, arg.to<const Record>(fl, cx));\n        for (auto pf = rec->iter(); !pf->empty(); pf->next()) {\n            TRY_DEF(type, CType::from_value(pf->value(cx), fl, cx));\n            fields[pf->key()] = type;\n        }\n        return {make<Struct_Type>(std::move(fields))};\n    }\n};\nstruct F_Record : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        Symbol_Map<CType> fields;\n        At_Arg cx(*this, fm);\n        TRY_DEF(rec, arg.to<const Record>(fl, cx));\n        for (auto pf = rec->iter(); !pf->empty(); pf->next()) {\n            TRY_DEF(type, CType::from_value(pf->value(cx), fl, cx));\n            fields[pf->key()] = type;\n        }\n        return {make<Record_Type>(std::move(fields))};\n    }\n};\nstruct F_is_bool : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame&) const override\n    {\n        return {is_bool(arg)};\n    }\n};\nstruct F_is_char : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame&) const override\n    {\n        return {arg.is_char()};\n    }\n};\nstruct F_is_symbol : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame&) const override\n    {\n        return {is_symbol(arg)};\n    }\n};\nstruct F_is_num : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame&) const override\n    {\n        return {is_num(arg)};\n    }\n};\nstruct F_is_string : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame&) const override\n    {\n        return {is_string(arg)};\n    }\n};\nstruct F_is_list : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame& fm) const override\n    {\n        Generic_List glist(arg);\n        return {glist.is_list()};\n    }\n};\nstruct F_is_record : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame&) const override\n    {\n        return {arg.maybe<Record>() != nullptr};\n    }\n};\nstruct F_is_primitive_func : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame&) const override\n    {\n        return {arg.maybe<Function>() != nullptr};\n    }\n};\nstruct F_is_func : public Function\n{\n    using Function::Function;\n    Value call(Value arg, Fail, Frame& fm) const override\n    {\n        return {maybe_function(arg, At_Arg(*this, fm)) != nullptr};\n    }\n};\n\nstruct Bit_Prim : public Unary_Bool_To_Num_Prim\n{\n    static const char* name() { return \"bit\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value call(bool b, const Context&) { return {double(b)}; }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value arg)\n    {\n        auto result = fm.sc_.newvalue(SC_Type::Num(arg.type.count()));\n        fm.sc_.out() << \"  \" << result.type << \" \" << result << \" = \"\n            << result.type << \"(\" << arg << \");\\n\";\n        return result;\n    }\n};\nusing F_bit = Unary_Array_Func<Bit_Prim>;\n\n#define UNARY_NUMERIC_FUNCTION(Func_Name,curv_name,c_name,glsl_name) \\\nstruct Func_Name##Prim : public Unary_Num_SCVec_Prim \\\n{ \\\n    static const char* name() { return #curv_name; } \\\n    static constexpr Prec prec = Prec::postfix; \\\n    static Value call(double x, const Context&) { return {c_name(x)}; } \\\n    static SC_Value sc_call(SC_Frame& fm, SC_Value arg) \\\n        { return sc_unary_call(fm, arg.type, #glsl_name, arg); } \\\n}; \\\nusing Func_Name = Unary_Array_Func<Func_Name##Prim>; \\\n\nUNARY_NUMERIC_FUNCTION(F_sqrt, sqrt, sqrt, sqrt)\nUNARY_NUMERIC_FUNCTION(F_log, log, log, log)\nUNARY_NUMERIC_FUNCTION(F_abs, abs, abs, abs)\nUNARY_NUMERIC_FUNCTION(F_floor, floor, floor, floor)\nUNARY_NUMERIC_FUNCTION(F_ceil, ceil, ceil, ceil)\nUNARY_NUMERIC_FUNCTION(F_trunc, trunc, trunc, trunc)\nUNARY_NUMERIC_FUNCTION(F_round, round, rint, roundEven)\n\ninline double frac(double n) { return n - floor(n); }\nUNARY_NUMERIC_FUNCTION(F_frac, frac, frac, fract)\n\ninline double sign(double n) { return copysign(double(n!=0),n); }\nUNARY_NUMERIC_FUNCTION(F_sign, sign, sign, sign)\n\nUNARY_NUMERIC_FUNCTION(F_sin, sin, sin, sin)\nUNARY_NUMERIC_FUNCTION(F_cos, cos, cos, cos)\nUNARY_NUMERIC_FUNCTION(F_tan, tan, tan, tan)\nUNARY_NUMERIC_FUNCTION(F_acos, acos, acos, acos)\nUNARY_NUMERIC_FUNCTION(F_asin, asin, asin, asin)\nUNARY_NUMERIC_FUNCTION(F_atan, atan, atan, atan)\n\nUNARY_NUMERIC_FUNCTION(F_sinh, sinh, sinh, sinh)\nUNARY_NUMERIC_FUNCTION(F_cosh, cosh, cosh, cosh)\nUNARY_NUMERIC_FUNCTION(F_tanh, tanh, tanh, tanh)\nUNARY_NUMERIC_FUNCTION(F_acosh, acosh, acosh, acosh)\nUNARY_NUMERIC_FUNCTION(F_asinh, asinh, asinh, asinh)\nUNARY_NUMERIC_FUNCTION(F_atanh, atanh, atanh, atanh)\n\nstruct Phase_Prim : public Unary_Vec2_To_Num_Prim\n{\n    static const char* name() { return \"phase\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value call(Vec2 v, const Context&) { return {atan2(v.y,v.x)}; }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value arg) {\n        auto result = fm.sc_.newvalue(SC_Type::Num());\n        fm.sc_.out() << \"  \" << result.type << \" \" << result << \" = \"\n            << \"atan(\" << arg << \".y,\" << arg << \".x);\\n\";\n        return result;\n    }\n};\nusing F_phase = Unary_Array_Func<Phase_Prim>;\n\nstruct Max_Prim : public Binary_Num_SCVec_Prim\n{\n    static const char* name() { return \"max\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value zero() { return {-INFINITY}; }\n    static Value call(double x, double y, const Context&)\n        { return {std::max(x,y)}; }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x, SC_Value y)\n        { return sc_bincall(fm, x.type, \"max\", x, y); }\n};\nusing F_max = Monoid_Func<Max_Prim>;\n\nstruct Min_Prim : public Binary_Num_SCVec_Prim\n{\n    static const char* name() { return \"min\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value zero() { return {INFINITY}; }\n    static Value call(double x, double y, const Context&)\n        { return {std::min(x,y)}; }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x, SC_Value y)\n        { return sc_bincall(fm, x.type, \"min\", x, y); }\n};\nusing F_min = Monoid_Func<Min_Prim>;\n\nusing F_sum = Monoid_Func<Add_Prim>;\n\nusing F_not = Unary_Array_Func<Not_Prim>;\n\n#define BOOL_OP(CppName,Name,Zero,LogOp,BitOp)\\\nstruct CppName##_Prim : public Binary_Bool_Prim\\\n{\\\n    static const char* name() { return Name; } \\\n    static constexpr Prec prec = Prec::postfix; \\\n    static Value zero() { return {Zero}; }\\\n    static Value call(bool x, bool y, const Context&) { return {x LogOp y}; }\\\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x, SC_Value y)\\\n    {\\\n        auto result = fm.sc_.newvalue(x.type);\\\n        fm.sc_.out() << \"  \" << x.type << \" \" << result << \" = \";\\\n        if (x.type.is_bool())\\\n            fm.sc_.out() << x << #LogOp << y << \";\\n\";\\\n        else if (x.type.is_bool_or_vec()) {\\\n            /* In GLSL 4.6, I *think* you can use '&' and '|' instead. */ \\\n            /* TODO: SubCurv: more efficient and|or in bvec case */ \\\n            bool first = true;\\\n            fm.sc_.out() << x.type << \"(\";\\\n            for (unsigned i = 0; i < x.type.count(); ++i) {\\\n                if (!first) fm.sc_.out() << \",\";\\\n                first = false;\\\n                fm.sc_.out() << x << \"[\" << i << \"]\"\\\n                    << #LogOp << y << \"[\" << i << \"]\";\\\n            }\\\n            fm.sc_.out() << \")\";\\\n        }\\\n        else\\\n            fm.sc_.out() << x << #BitOp << y << \";\\n\";\\\n        fm.sc_.out() << \";\\n\";\\\n        return result;\\\n    }\\\n};\\\nusing F_##CppName = Monoid_Func<CppName##_Prim>;\\\n\nBOOL_OP(and,\"and\",true,&&,&)\nBOOL_OP(or,\"or\",false,||,|)\n\nstruct Xor_Prim : public Binary_Bool_Prim\n{\n    static const char* name() { return \"xor\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value zero() { return {false}; }\n    static Value call(bool x, bool y, const Context&) { return {x != y}; }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x, SC_Value y)\n    {\n        auto result = fm.sc_.newvalue(x.type);\n        fm.sc_.out() << \"  \" << result.type << \" \" << result << \" = \";\n        if (x.type.is_bool())\n            fm.sc_.out() << x << \"!=\" << y;\n        else if (x.type.is_bool_or_vec())\n            fm.sc_.out() << \"notEqual(\" << x << \",\" << y << \")\";\n        else // bool32 or vector of bool32\n            fm.sc_.out() << x << \"^\" << y;\n        fm.sc_.out() << \";\\n\";\n        return result;\n    }\n};\nusing F_xor = Monoid_Func<Xor_Prim>;\n\nstruct Lshift_Prim : public Shift_Prim\n{\n    static const char* name() { return \"lshift\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value call(Shared<const List> a, double b, const Context &cx)\n    {\n        At_Index acx(0, cx);\n        At_Index bcx(1, cx);\n        unsigned n = (unsigned) num_to_int(b, 0, a->size()-1, bcx);\n        Shared<List> result = make_tail_array<List>(a->size());\n        for (unsigned i = 0; i < n; ++i)\n            result->at(i) = {false};\n        for (unsigned i = n; i < a->size(); ++i)\n            result->at(i) = {a->at(i-n).to_bool(acx)};\n        return {result};\n    }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x, SC_Value y)\n    {\n        auto result = fm.sc_.newvalue(x.type);\n        fm.sc_.out() << \"  \" << x.type << \" \" << result << \" = \"\n            << x << \" << int(\" << y << \");\\n\";\n        return result;\n    }\n};\nusing F_lshift = Binary_Array_Func<Lshift_Prim>;\n\nstruct Rshift_Prim : public Shift_Prim\n{\n    static const char* name() { return \"rshift\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value call(Shared<const List> a, double b, const Context &cx)\n    {\n        At_Index acx(0, cx);\n        At_Index bcx(1, cx);\n        unsigned n = (unsigned) num_to_int(b, 0, a->size()-1, bcx);\n        Shared<List> result = make_tail_array<List>(a->size());\n        for (unsigned i = a->size()-n; i < a->size(); ++i)\n            result->at(i) = {false};\n        for (unsigned i = 0; i < a->size()-n; ++i)\n            result->at(i) = {a->at(i+n).to_bool(acx)};\n        return {result};\n    }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x, SC_Value y)\n    {\n        auto result = fm.sc_.newvalue(x.type);\n        fm.sc_.out() << \"  \" << x.type << \" \" << result << \" = \"\n            << x << \" >> int(\" << y << \");\\n\";\n        return result;\n    }\n};\nusing F_rshift = Binary_Array_Func<Rshift_Prim>;\n\nstruct Bool32_Sum_Prim : public Binary_Bool32_Prim\n{\n    static const char* name() { return \"bool32_sum\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value zero()\n    {\n        static Value z = {nat_to_bool32(0)};\n        return z;\n    }\n    static Value call(unsigned a, unsigned b, const Context&)\n    {\n        return {nat_to_bool32(a + b)};\n    }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x, SC_Value y)\n    {\n        auto result = fm.sc_.newvalue(x.type);\n        fm.sc_.out() << \"  \" << x.type << \" \" << result << \" = \"\n            << x << \" + \" << y << \";\\n\";\n        return result;\n    }\n};\nusing F_bool32_sum = Monoid_Func<Bool32_Sum_Prim>;\n\nstruct Bool32_Product_Prim : public Binary_Bool32_Prim\n{\n    static const char* name() { return \"bool32_product\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value zero()\n    {\n        static Value z = {nat_to_bool32(1)};\n        return z;\n    }\n    static Value call(unsigned a, unsigned b, const Context&)\n    {\n        return {nat_to_bool32(a * b)};\n    }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x, SC_Value y)\n    {\n        auto result = fm.sc_.newvalue(x.type);\n        fm.sc_.out() << \"  \" << x.type << \" \" << result << \" = \"\n            << x << \" * \" << y << \";\\n\";\n        return result;\n    }\n};\nusing F_bool32_product = Monoid_Func<Bool32_Product_Prim>;\n\nstruct F_bool32_to_nat : public Function\n{\n    using Function::Function;\n    struct Prim : public Unary_Bool32_To_Num_Prim\n    {\n        static const char* name() { return \"bool32_to_nat\"; }\n        static constexpr Prec prec = Prec::postfix;\n        static Value call(unsigned n, const Context&)\n        {\n            return {double(n)};\n        }\n        // No SubCurv support because a Num (32 bit float)\n        // cannot hold a Nat (32 bit natural).\n        static SC_Type sc_result_type(SC_Type) { return {}; }\n        static SC_Value sc_call(SC_Frame& fm, SC_Value x)\n        {\n            throw Exception(At_SC_Frame(fm),\n                \"bool32_to_nat is not supported by SubCurv\");\n        }\n    };\n    static Unary_Array_Op<Prim> array_op;\n    Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        return array_op.call(fl, At_Arg(*this, fm), arg);\n    }\n};\n\nstruct F_nat_to_bool32 : public Function\n{\n    using Function::Function;\n    struct Prim : public Unary_Num_To_Bool32_Prim\n    {\n        static const char* name() { return \"nat_to_bool32\"; }\n        static constexpr Prec prec = Prec::postfix;\n        static Value call(double n, const Context& cx)\n        {\n            return {nat_to_bool32(num_to_nat(n, cx))};\n        }\n        static SC_Value sc_call(SC_Frame& fm, SC_Value x)\n        {\n            throw Exception(At_SC_Frame(fm),\n                \"nat_to_bool32 can't be called in this context: \"\n                \"argument must be a constant\");\n        }\n    };\n    static Unary_Array_Op<Prim> array_op;\n    Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        return array_op.call(fl, At_Arg(*this, fm), arg);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase> ph, SC_Frame& fm)\n    const override\n    {\n        At_SC_Arg_Expr cx(*this, ph, fm);\n        if (auto k = dynamic_cast<const Constant*>(&argx)) {\n            unsigned n = num_to_nat(k->value_.to_num(cx), cx);\n            auto type = SC_Type::Bool32();\n            auto result = fm.sc_.newvalue(type);\n            fm.sc_.out() << \"  \" << type << \" \" << result << \" = \"\n                << n << \"u;\\n\";\n            return result;\n        }\n        else {\n            throw Exception(cx, \"argument must be a constant\");\n        }\n    }\n};\n\nstruct Bool32_To_Float_Prim : public Unary_Bool32_To_Num_Prim\n{\n    static const char* name() { return \"bool32_to_float\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value call(unsigned n, const Context&)\n    {\n        return {bitcast_nat_to_float(n)};\n    }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x)\n    {\n        unsigned count = x.type.is_bool32() ? 1 : x.type.count();\n        auto result = fm.sc_.newvalue(SC_Type::Num(count));\n        fm.sc_.out() << \"  \" << result.type << \" \" << result\n            << \" = uintBitsToFloat(\" << x << \");\\n\";\n        return result;\n    }\n};\nusing F_bool32_to_float = Unary_Array_Func<Bool32_To_Float_Prim>;\n\nstruct Float_To_Bool32_Prim : public Unary_Num_To_Bool32_Prim\n{\n    static const char* name() { return \"bool32_to_float\"; }\n    static constexpr Prec prec = Prec::postfix;\n    static Value call(double n, const Context&)\n    {\n        return {nat_to_bool32(bitcast_float_to_nat(n))};\n    }\n    static SC_Value sc_call(SC_Frame& fm, SC_Value x)\n    {\n        auto result = fm.sc_.newvalue(SC_Type::Bool32(x.type.count()));\n        fm.sc_.out() << \"  \" << result.type << \" \" << result\n            << \" = floatBitsToUint(\" << x << \");\\n\";\n        return result;\n    }\n};\nusing F_float_to_bool32 = Unary_Array_Func<Float_To_Bool32_Prim>;\n\nValue\nselect(Value a, Value b, Value c, Fail fl, const Context& cx)\n{\n    if (a.is_bool())\n        return a.to_bool_unsafe() ? b : c;\n    if (auto alist = a.maybe<List>()) {\n        auto blist = b.maybe<Abstract_List>();\n        if (blist) {\n            ASSERT_SIZE(fl,missing,blist,alist->size(),At_Index(1, cx));\n        }\n        auto clist = c.maybe<Abstract_List>();\n        if (clist) {\n            ASSERT_SIZE(fl,missing,clist,alist->size(),At_Index(2, cx));\n        }\n        List_Builder lb;\n        for (unsigned i = 0; i < alist->size(); ++i) {\n            TRY_DEF(v, select(alist->at(i),\n                              blist ? blist->val_at(i) : b,\n                              clist ? clist->val_at(i) : c,\n                              fl, cx));\n            lb.push_back(v);\n        }\n        return lb.get_value();\n    }\n    FAIL(fl, missing, At_Index(0, cx),\n        stringify(a, \" is not a Bool or a List\"));\n}\n\n// `select[a,b,c]` is a vectorized version of `if` in which the condition is\n// an array of booleans.\n// * If `a` is boolean, then the result is `if (a) b else c`.\n// * If `a` is an array of booleans, then the result is an array with the same\n//   shape as `a`. The elements of the result are selected from the arrays `b`\n//   and `c` based on whether the corresponding element of `a` is true or false.\n//   For example, `select[[false,true], [1,2], [10,20]] == [10,2]`.\n// * Broadcasting is supported between `a` and `b` and between `a` and `c`,\n//   so for example, `select[[false,true], 1, 0] == [0,1]`.\n// * Broadcasting is not supported between `b` and `c`, so for example,\n//   `select[true, 1, [1,2,3]]` yields `1`, and not `[1,1,1]`.\n// The SubCurv version of `select` restricts the arguments `b` and `c`\n// to have the same type.\n//\n// `select` has a different name from `if` because it violates some of the\n// laws of `if`: it always evaluates all 3 arguments, and it can't be involved\n// in tail recursion optimization.\n//\n// Similar to: numpy.where, R `ifelse`\nstruct F_select : public Tuple_Function\n{\n    F_select(const char* nm) : Tuple_Function(3,nm) {}\n    Value tuple_call(Fail fl, Frame& args) const override\n    {\n        return select(args[0], args[1], args[2], fl, At_Arg(*this, args));\n    }\n    SC_Value sc_tuple_call(SC_Frame& fm) const override\n    {\n        auto cond = fm[0];\n        auto consequent = fm[1];\n        auto alternate = fm[2];\n        if (!cond.type.is_bool_or_vec()) {\n            throw Exception(At_SC_Tuple_Arg(0,fm), stringify(\n                \"argument is not bool or bool vector; it has type \",\n                cond.type));\n        }\n        if (consequent.type != alternate.type) {\n            throw Exception(At_SC_Tuple_Arg(1,fm), stringify(\n                \"2nd and 3rd argument of 'select' have different types: \",\n                consequent.type, \" and \", alternate.type));\n        }\n        SC_Value result;\n        if (cond.type.is_bool()) {\n            result = fm.sc_.newvalue(consequent.type);\n            fm.sc_.out() << \"  \" << result.type << \" \" << result << \" = \";\n            fm.sc_.out() << cond << \"?\" << consequent << \":\" << alternate;\n        } else {\n            // 'cond' is a boolean vector.\n            if (consequent.type.count() == 1) {\n                // Consequent & alternate are scalars. Convert them to vectors.\n                auto T = SC_Type::Array(consequent.type, cond.type.count());\n                sc_try_extend(fm, consequent, T);\n                sc_try_extend(fm, alternate, T);\n            }\n            else if (!consequent.type.is_vec()) {\n                throw Exception(At_SC_Tuple_Arg(1,fm), stringify(\n                    \"Must be a scalar or vector to match condition argument.\"\n                    \" Instead, type is \", consequent.type));\n            }\n            else if (cond.type.count() != consequent.type.count()) {\n                throw Exception(At_SC_Tuple_Arg(1,fm), stringify(\n                    \"Vector length \",consequent.type.count(),\" does not match\"\n                    \" length of condition vector (\", cond.type.count(),\")\"));\n            }\n            result = fm.sc_.newvalue(consequent.type);\n            fm.sc_.out() << \"  \" << result.type << \" \" << result << \" = \";\n            // In GLSL 4.5, this is `mix(alt,cons,cond)` (all args are vectors).\n            // Right now, we are locked to GLSL 3.3, so we can't use this.\n            // TODO: SubCurv: more efficient `select` for vector case\n            if (result.type.is_num_vec()) {\n                // This version of 'mix' is linear interpolation: it works by\n                // multiplication and addition of all 3 arguments. Which is\n                // different from the boolean vector 'mix' in GLSL 4.5 (which\n                // produces exact results even when linear interpolation would\n                // fail due to floating point approximation). But I saw IQ use\n                // linear interpolation of vectors to implement a 'select' in\n                // WebGL, so maybe this is efficient code.\n                fm.sc_.out() << \"mix(\" << alternate << \",\" << consequent\n                    << \",vec\" << cond.type.count() << \"(\" << cond << \"))\";\n            } else {\n                fm.sc_.out() << result.type << \"(\";\n                bool atfirst = true;\n                for (unsigned i = 0; i < result.type.count(); ++i) {\n                    if (!atfirst) fm.sc_.out() << \",\";\n                    atfirst = false;\n                    fm.sc_.out() << cond << \"[\" << i << \"] ? \"\n                                << consequent << \"[\" << i << \"] : \"\n                                << alternate << \"[\" << i << \"]\";\n                }\n                fm.sc_.out() << \")\";\n            }\n        }\n        fm.sc_.out() << \";\\n\";\n        return result;\n    }\n};\n\nSC_Value Equal_Expr::sc_eval(SC_Frame& fm) const\n{\n    auto a = sc_eval_op(fm, *arg1_);\n    auto b = sc_eval_op(fm, *arg2_);\n    if (a.type != b.type || a.type.plex_array_rank() > 0) {\n        throw Exception(At_SC_Phrase(syntax_, fm),\n            stringify(\"domain error: \",a.type,\" == \",b.type));\n    }\n    SC_Value result = fm.sc_.newvalue(SC_Type::Bool());\n    fm.sc_.out() <<\"  bool \"<<result<<\" =(\"<<a<<\" == \"<<b<<\");\\n\";\n    return result;\n}\nSC_Value Not_Equal_Expr::sc_eval(SC_Frame& fm) const\n{\n    auto a = sc_eval_op(fm, *arg1_);\n    auto b = sc_eval_op(fm, *arg2_);\n    if (a.type != b.type || a.type.plex_array_rank() > 0) {\n        throw Exception(At_SC_Phrase(syntax_, fm),\n            stringify(\"domain error: \",a.type,\" != \",b.type));\n    }\n    SC_Value result = fm.sc_.newvalue(SC_Type::Bool());\n    fm.sc_.out() <<\"  bool \"<<result<<\" =(\"<<a<<\" != \"<<b<<\");\\n\";\n    return result;\n}\n\n// Generalized dot product that includes vector dot product and matrix product.\n// Same as Mathematica Dot[A,B]. Like APL A+.\u00d7B, Python numpy.dot(A,B)\n//  dot(a,b) =\n//    if (count a > 0 && is_list(a[0]))\n//      [for (row in a) dot(row,b)]  // matrix*...\n//    else\n//      sum(a*b)                     // vector*...\nstruct F_dot : public Tuple_Function\n{\n    F_dot(const char* nm) : Tuple_Function(2,nm) {}\n    Value dot(Value a, Value b, Fail, const At_Arg& cx) const;\n    Value tuple_call(Fail fl, Frame& args) const override\n    {\n        return dot(args[0], args[1], fl, At_Arg(*this, args));\n    }\n    SC_Value sc_tuple_call(SC_Frame& fm) const override\n    {\n        auto a = fm[0];\n        auto b = fm[1];\n        if (a.type.is_num_vec() && a.type == b.type)\n            return sc_bincall(fm, SC_Type::Num(), \"dot\", a, b);\n        if (a.type.is_num_vec() && b.type.is_mat()\n            && a.type.count() == b.type.count())\n        {\n            return sc_binop(fm, a.type, b, \"*\", a);\n        }\n        if (a.type.is_mat() && b.type.is_num_vec()\n            && a.type.count() == b.type.count())\n        {\n            return sc_binop(fm, b.type, b, \"*\", a);\n        }\n        if (a.type.is_mat() && b.type.is_mat()\n            && a.type.count() == b.type.count())\n        {\n            return sc_binop(fm, a.type, b, \"*\", a);\n        }\n        throw Exception(At_SC_Frame(fm), stringify(\n            \"dot: invalid argument type [\",a.type,\",\",b.type,\"]\"));\n    }\n};\nValue F_dot::dot(Value a, Value b, Fail fl, const At_Arg& cx) const\n{\n    auto av = a.maybe<List>();\n    auto bv = b.maybe<List>();\n    if (av && bv) {\n        if (av->size() > 0 && av->at(0).maybe<List>()) {\n            Shared<List> result = make_tail_array<List>(av->size());\n            for (size_t i = 0; i < av->size(); ++i) {\n                TRY_DEF(v, dot(av->at(i), b, fl, cx));\n                result->at(i) = v;\n            }\n            return {result};\n        } else {\n            if (av->size() != bv->size())\n                throw Exception(cx, stringify(\"list of size \",av->size(),\n                    \" can't be multiplied by list of size \",bv->size()));\n            Value result = {0.0};\n            for (size_t i = 0; i < av->size(); ++i) {\n                TRY_DEF(prod, Multiply_Op::call(fl, cx, av->at(i), bv->at(i)));\n                TRY_DEF(sum, Add_Op::call(fl, cx, result, prod));\n                result = sum;\n            }\n            return result;\n        }\n    }\n    // Handle the case where a or b is a reactive list,\n    // and return a reactive result.\n    //   This is copied and modified from F_dot::sc_tuple_call.\n    //   The code ought to be identical in both cases.\n    //   The reactive result should contain SubCurv IR code,\n    //   which is simultaneously code that can be evaluated by the interpreter.\n    auto aty = sc_type_of(a);\n    auto bty = sc_type_of(b);\n    SC_Type rty;\n    if (aty.is_num_vec() && aty == bty)\n        rty = SC_Type::Num();\n    else if (aty.is_num_vec() && bty.is_mat() && aty.count() == bty.count())\n        rty = bty;\n    else if (aty.is_mat() && bty.is_num_vec() && aty.count() == bty.count())\n        rty = aty;\n    else if (aty.is_mat() && bty.is_mat() && aty.count() == bty.count())\n        rty = aty;\n    else\n        throw Exception(cx, stringify(\"dot[\",a,\",\",b,\"]: invalid arguments\"));\n    Shared<List_Expr> args = make_tail_array<List_Expr>(\n        {to_expr(a, cx.syntax()), to_expr(b, cx.syntax())},\n        share(cx.syntax()));\n    args->init();\n    return {make<Reactive_Expression>(\n        rty,\n        make<Call_Expr>(\n            cx.call_frame_.call_phrase_,\n            make<Constant>(\n                func_part(cx.call_frame_.call_phrase_),\n                Value{share(*this)}),\n            args),\n        cx)};\n}\n\nstruct F_mag : public Tuple_Function\n{\n    F_mag(const char* nm) : Tuple_Function(1,nm) {}\n    Value tuple_call(Fail fl, Frame& args) const override\n    {\n        // Use hypot() or BLAS DNRM2 or Eigen stableNorm/blueNorm?\n        // Avoids overflow/underflow due to squaring of large/small values.\n        // Slower.  https://forum.kde.org/viewtopic.php?f=74&t=62402\n\n        // Fast path: assume we have a list of numbers, compute a result.\n        if (auto list = args[0].maybe<List>()) {\n            double sum = 0.0;\n            for (auto val : *list) {\n                double x = val.to_num_or_nan();\n                sum += x * x;\n            }\n            if (sum == sum)\n                return {sqrt(sum)};\n        }\n\n        // Slow path, return a reactive value or abort.\n        Shared<Operation> arg_op = nullptr;\n        if (auto rx = args[0].maybe<Reactive_Value>()) {\n            if (rx->sctype_.is_num_vec())\n                arg_op = rx->expr();\n        } else {\n            TRY_DEF(list, args[0].to<List>(fl, At_Arg(*this, args)));\n            Shared<List_Expr> rlist = make_tail_array<List_Expr>\n                (list->size(),arg_part(args.call_phrase_));\n            arg_op = rlist;\n            for (unsigned i = 0; i < list->size(); ++i) {\n                Value val = list->at(i);\n                if (val.is_num()) {\n                    rlist->at(i) =\n                        make<Constant>(arg_part(args.call_phrase_), val);\n                    continue;\n                }\n                auto r = val.maybe<Reactive_Value>();\n                if (r && r->sctype_.is_num()) {\n                    rlist->at(i) = r->expr();\n                    continue;\n                }\n                arg_op = nullptr;\n                break;\n            }\n            if (arg_op) rlist->init();\n        }\n        if (arg_op) {\n            return {make<Reactive_Expression>(\n                SC_Type::Num(),\n                make<Call_Expr>(\n                    args.call_phrase_,\n                    make<Constant>(\n                        func_part(args.call_phrase_),\n                        Value{share(*this)}),\n                    arg_op),\n                At_Arg(*this, args))};\n        }\n        FAIL(fl, missing, At_Arg(*this, args),\n            stringify(args[0],\": domain error\"));\n    }\n    SC_Value sc_tuple_call(SC_Frame& fm) const override\n    {\n        auto arg = fm[0];\n        if (!arg.type.is_num_vec())\n            throw Exception(At_SC_Tuple_Arg(0, fm), stringify(\n                \"mag: argument is not a vector (type \", arg.type, \")\"));\n        auto result = fm.sc_.newvalue(SC_Type::Num());\n        fm.sc_.out() << \"  float \"<<result<<\" = length(\"<<arg<<\");\\n\";\n        return result;\n    }\n};\n\nstruct F_count : public Tuple_Function\n{\n    F_count(const char* nm) : Tuple_Function(1,nm) {}\n    Value tuple_call(Fail fl, Frame& args) const override\n    {\n        if (auto list = args[0].maybe<const Abstract_List>())\n            return {double(list->size())};\n        if (auto re = args[0].maybe<const Reactive_Value>()) {\n            if (re->sctype_.is_array())\n                return {double(re->sctype_.count())};\n        }\n        FAIL(fl, missing, At_Arg(*this, args), \"not a list or string\");\n    }\n    SC_Value sc_tuple_call(SC_Frame& fm) const override\n    {\n        auto arg = fm[0];\n        if (!arg.type.is_array())\n            throw Exception(At_SC_Tuple_Arg(0, fm), stringify(\n                \"count: argument is not a list (type \",arg.type,\")\"));\n        auto result = fm.sc_.newvalue(SC_Type::Num());\n        fm.sc_.out() << \"  float \"<<result<<\" = \"<<arg.type.count()<<\";\\n\";\n        return result;\n    }\n};\nstruct F_fields : public Tuple_Function\n{\n    F_fields(const char* nm) : Tuple_Function(1,nm) {}\n    static Value fields(Value arg, Fail fl, const Context& cx)\n    {\n        if (auto record = arg.maybe<const Record>())\n            return {record->fields()};\n      #if 0\n        else if (auto list = arg.maybe<List>()) {\n            Shared<List> result = make_tail_array<List>(list->size());\n            for (unsigned i = 0; i < list->size(); ++i)\n                result->at(i) = fields(list->at(i), cx);\n            return {result};\n        }\n      #endif\n        else\n            FAIL(fl, missing, cx, stringify(arg, \" is not a record\"));\n    }\n    Value tuple_call(Fail fl, Frame& args) const override\n    {\n        return fields(args[0], fl, At_Arg(*this, args));\n    }\n};\n\n// Construct a character from an integer or a string of length 1.\n// Vectorized.\nValue to_char(Value arg, Fail fl, const Context& cx)\n{\n    if (arg.is_num()) {\n        int code;\n        if (!num_to_int(arg.to_num_unsafe(), code, 1, 127, fl, cx))\n            return missing;\n        return Value{char(code)};\n    }\n    else if (auto list = arg.maybe<List>()) {\n        if (list->empty()) return arg;\n        Shared<String> s = make_uninitialized_string(list->size());\n        for (unsigned i = 0; i < list->size(); ++i) {\n            TRY_DEF(val, to_char(list->at(i), fl, cx));\n            if (val.is_char())\n                s->at(i) = val.to_char_unsafe();\n            else {\n                Shared<List> result = make_tail_array<List>(list->size());\n                for (unsigned j = 0; j < i; ++j)\n                    result->at(j) = Value(s->at(j));\n                result->at(i) = val;\n                for (unsigned k = i+1; k < list->size(); ++k)\n                    result->at(i) = to_char(list->at(i), fl, cx);\n                return {result};\n            }\n        }\n        return {s};\n    }\n    else {\n        FAIL(fl, missing, cx,\n            stringify(arg, \" is not an integer, or a list or tree of integers\"));\n    }\n}\nstruct F_char : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        return to_char(arg, fl, At_Arg(*this, fm));\n    }\n};\nValue ucode(Value arg, Fail fl, const Context& cx)\n{\n    if (arg.is_char())\n        return {(double)(unsigned)arg.to_char_unsafe()};\n    if (auto str = arg.maybe<const String>()) {\n        List_Builder lb;\n        for (size_t i = 0; i < str->size(); ++i)\n            lb.push_back({(double)(unsigned)str->at(i)});\n        return lb.get_value();\n    }\n    if (auto list = arg.maybe<const List>()) {\n        List_Builder lb;\n        for (Value e : *list) {\n            TRY_DEF(r, ucode(e, fl, cx));\n            lb.push_back(r);\n        }\n        return lb.get_value();\n    }\n    FAIL(fl, missing, cx,\n        stringify(arg, \" is not a character or list of characters\"));\n}\nstruct F_ucode : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        return ucode(arg, fl, At_Arg(*this, fm));\n    }\n};\nstruct F_symbol : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        At_Arg cx(*this, fm);\n        TRY_DEF(string, value_to_string(arg, fl, cx));\n        for (auto c : *string) {\n            if (c <= ' ' || c >= '~') {\n                FAIL(fl,missing,cx, stringify(\n                    \"string \",arg,\" contains \",illegal_character_message(c)));\n            }\n        }\n        auto symbol = make_symbol(string->data(), string->size());\n        return symbol.to_value();\n    }\n};\nstruct F_string : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        String_Builder sb;\n        arg.print_string(sb);\n        return sb.get_value();\n    }\n};\nstruct F_repr : public Tuple_Function\n{\n    F_repr(const char* nm) : Tuple_Function(1,nm) {}\n    Value tuple_call(Fail, Frame& args) const override\n    {\n        String_Builder sb;\n        sb << args[0];\n        return sb.get_value();\n    }\n};\n\nstruct F_match : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        At_Arg ctx0(*this, fm);\n        TRY_DEF(list, arg.to<List>(fl, ctx0));\n        std::vector<Shared<const Function>> cases;\n        for (size_t i = 0; i < list->size(); ++i) {\n            TRY_DEF(fn, value_to_function(list->at(i), fl, At_Index(i,ctx0)));\n            cases.push_back(fn);\n        }\n        auto mf = make<Piecewise_Function>(cases);\n        mf->fname_.name_ = fname_.name_;\n        mf->fname_.argpos_ = 1;\n        return {mf};\n    }\n};\n\nstruct F_compose : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        At_Arg ctx0(*this, fm);\n        TRY_DEF(list, arg.to<List>(fl, ctx0));\n        std::vector<Shared<const Function>> cases;\n        for (size_t i = 0; i < list->size(); ++i) {\n            TRY_DEF(fn, value_to_function(list->at(i), fl, At_Index(i,ctx0)));\n            cases.push_back(fn);\n        }\n        auto mf = make<Composite_Function>(cases);\n        mf->fname_.name_ = fname_.name_;\n        mf->fname_.argpos_ = 1;\n        return {mf};\n    }\n};\n\nstruct F_tslice : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        At_Arg cx(*this, fm);\n        TRY_DEF(list, arg.to<List>(fl, cx));\n        return make_tslice(list->begin(), list->end());\n    }\n};\nstruct F_tpath : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        At_Arg cx(*this, fm);\n        TRY_DEF(list, arg.to<List>(fl, cx));\n        return make_tpath(list->begin(), list->end());\n    }\n};\nstruct F_amend : public Curried_Function\n{\n    F_amend(const char* nm) : Curried_Function(3,nm) {}\n    virtual Value ccall(const Function& self, Fail, Frame& args) const\n    {\n        return tree_amend(args[2], args[0], args[1], At_Arg(*this, args));\n    }\n};\n\n// The filename argument to \"file\", if it is a relative filename,\n// is interpreted relative to the parent directory of the source file from\n// which \"file\" is called.\n//\n// Because \"file\" has this hidden parameter (the name of the source file from\n// which it is called), it is not a pure function. For this reason, it isn't\n// a function value at all, it's a metafunction.\nstruct File_Expr : public Just_Expression\n{\n    Shared<Operation> arg_;\n    File_Expr(Shared<const Call_Phrase> src, Shared<Operation> arg)\n    :\n        Just_Expression(move(src)),\n        arg_(move(arg))\n    {}\n    virtual Value eval(Frame& fm) const override\n    {\n        // Each call to `file pathname` has its own stack frame,\n        // which permits calls to `file pathname` to appear in stack traces.\n        auto& callphrase = dynamic_cast<const Call_Phrase&>(*syntax_);\n        std::unique_ptr<Frame> f2 = make_tail_array<Frame>(0,\n            fm.sstate_, &fm, fm.func_, &callphrase);\n        At_Metacall_With_Call_Frame cx(\"file\", 0, *f2);\n\n        // construct file pathname from argument\n        Value arg = arg_->eval(fm);\n        auto argstr = value_to_string(arg, Fail::hard, cx);\n        namespace fs = std::filesystem;\n        fs::path filepath;\n        auto caller_filename = syntax_->location().source().name_;\n        if (caller_filename->empty()) {\n            filepath = fs::path(argstr->c_str());\n        } else {\n            filepath = fs::path(caller_filename->c_str()).parent_path()\n                / fs::path(argstr->c_str());\n        }\n\n        return import_value(import, filepath, cx);\n    }\n};\nstruct File_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<File_Expr>(share(ph), analyse_op(*ph.arg_, env));\n    }\n    virtual void print_help(std::ostream& out) const override\n    {\n        out <<\n            \"file <filename>\\n\"\n            \"  Evaluate the program stored in the file named <filename>, and return the resulting value.\\n\"\n            \"  <filename> is a string.\\n\";\n    }\n};\n\n/// The meaning of a call to `print`, such as `print \"foo\"`.\nstruct Print_Action : public Just_Action\n{\n    Shared<Operation> arg_;\n    Print_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Just_Action(move(syntax)),\n        arg_(move(arg))\n    {}\n    virtual void exec(Frame& fm, Executor&) const override\n    {\n        Value arg = arg_->eval(fm);\n        auto str = to_print_string(arg);\n        fm.sstate_.system_.print(str->c_str());\n    }\n};\n/// The meaning of the phrase `print` in isolation.\nstruct Print_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Print_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n    virtual void print_help(std::ostream& out) const override\n    {\n        out <<\n            \"print <message>\\n\"\n            \"  Print a message string on the debug console, followed by newline. If <message> is not a string,\\n\"\n            \"  it is converted to a string using the 'string' function.\\n\";\n    }\n};\n\nstruct Warning_Action : public Just_Action\n{\n    Shared<Operation> arg_;\n    Warning_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Just_Action(move(syntax)),\n        arg_(move(arg))\n    {}\n    virtual void exec(Frame& fm, Executor&) const override\n    {\n        Value arg = arg_->eval(fm);\n        auto msg = to_print_string(arg);\n        Exception exc{At_Phrase(*syntax_, fm), msg};\n        fm.sstate_.system_.warning(exc);\n    }\n};\n/// The meaning of the phrase `warning` in isolation.\nstruct Warning_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Warning_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n    virtual void print_help(std::ostream& out) const override\n    {\n        out <<\n            \"warning <message>\\n\"\n            \"  Print a message string on the debug console, preceded by 'WARNING: ',\\n\"\n            \"  followed by newline and then a stack trace. If <message> is not a string,\\n\"\n            \"  it is converted to a string using the 'string' function.\\n\";\n    }\n};\n\nstruct Error_Function : public Function\n{\n    using Function::Function;\n    virtual Value call(Value arg, Fail fl, Frame& fm) const override\n    {\n        FAIL(fl, missing, At_Frame(fm), to_print_string(arg));\n    }\n};\n/// The meaning of a call to `error`, such as `error(\"foo\")`.\nstruct Error_Operation : public Just_Action\n{\n    Shared<Operation> arg_;\n    Error_Operation(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Just_Action(move(syntax)),\n        arg_(move(arg))\n    {}\n    [[noreturn]] void run(Frame& fm) const\n    {\n        Value val = arg_->eval(fm);\n        auto msg = to_print_string(val);\n        throw Exception{At_Phrase(*syntax_, fm), msg};\n    }\n    virtual void exec(Frame& fm, Executor&) const override\n    {\n        run(fm);\n    }\n    virtual Value eval(Frame& fm) const override\n    {\n        run(fm);\n    }\n};\n/// The meaning of the phrase `error` in isolation.\nstruct Error_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Error_Operation>(share(ph), analyse_op(*ph.arg_, env));\n    }\n    virtual Shared<Operation> to_operation(Source_State&) override\n    {\n        return make<Constant>(syntax_, Value{make<Error_Function>(\"error\")});\n    }\n    virtual void print_help(std::ostream& out) const override\n    {\n        out <<\n            \"error <message>\\n\"\n            \"  On the debug console, print 'ERROR: ', then the message string, then newline and a stack trace.\\n\"\n            \"  Then terminate the program. If <message> is not a string,\\n\"\n            \"  convert it to a string using the 'string' function.\\n\";\n    }\n};\n\n// exec(expr) -- a debug action that evaluates expr, then discards the result.\n// It is used to call functions or source files for their side effects.\nstruct Exec_Action : public Just_Action\n{\n    Shared<Operation> arg_;\n    Exec_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Just_Action(move(syntax)),\n        arg_(move(arg))\n    {}\n    virtual void exec(Frame& fm, Executor&) const override\n    {\n        arg_->eval(fm);\n    }\n};\nstruct Exec_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Exec_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n    virtual void print_help(std::ostream& out) const override\n    {\n        out <<\n            \"exec <expression>\\n\"\n            \"  Evaluate the expression and then ignore the result. This is used for calling a function whose only\\n\"\n            \"  purpose is to have a side effect (by executing debug statements) and you don't care about the result.\\n\";\n    }\n};\n\nstruct Assert_Action : public Just_Action\n{\n    Shared<Operation> arg_;\n    Assert_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Just_Action(move(syntax)),\n        arg_(move(arg))\n    {}\n    virtual void exec(Frame& fm, Executor&) const override\n    {\n        At_Metacall cx{\"assert\", 0, *arg_->syntax_, fm};\n        bool b = arg_->eval(fm).to_bool(cx);\n        if (!b)\n            throw Exception(At_Phrase(*syntax_, fm), \"assertion failed\");\n    }\n};\nstruct Assert_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        auto arg = analyse_op(*ph.arg_, env);\n        return make<Assert_Action>(share(ph), arg);\n    }\n    virtual void print_help(std::ostream& out) const override\n    {\n        out <<\n            \"assert <condition>\\n\"\n            \"  Evaluate the condition, which must be true or false. If it is true, then nothing happens.\\n\"\n            \"  If it is false, then an assertion failure error message is produced, followed by a stack trace,\\n\"\n            \"  and the program is terminated.\\n\";\n    }\n};\n\nstruct Assert_Error_Action : public Just_Action\n{\n    Shared<Operation> expected_message_;\n    Shared<const String> actual_message_;\n    Shared<Operation> expr_;\n\n    Assert_Error_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> expected_message,\n        Shared<const String> actual_message,\n        Shared<Operation> expr)\n    :\n        Just_Action(move(syntax)),\n        expected_message_(move(expected_message)),\n        actual_message_(move(actual_message)),\n        expr_(move(expr))\n    {}\n\n    virtual void exec(Frame& fm, Executor&) const override\n    {\n        Value expected_msg_val = expected_message_->eval(fm);\n        auto expected_msg_str =\n            value_to_string(expected_msg_val, Fail::hard,\n                At_Phrase(*expected_message_->syntax_, fm));\n\n        if (actual_message_ != nullptr) {\n            if (*actual_message_ != *expected_msg_str)\n                throw Exception(At_Phrase(*syntax_, fm),\n                    stringify(\"assertion failed: expected error \\\"\",\n                        expected_msg_str,\n                        \"\\\", actual error \\\"\",\n                        actual_message_,\n                        \"\\\"\"));\n            return;\n        }\n\n        Value result;\n        try {\n            result = expr_->eval(fm);\n        } catch (Exception& e) {\n            if (*e.shared_what() != *expected_msg_str) {\n                throw Exception(At_Phrase(*syntax_, fm),\n                    stringify(\"assertion failed: expected error \\\"\",\n                        expected_msg_str,\n                        \"\\\", actual error \\\"\",\n                        e.shared_what(),\n                        \"\\\"\"));\n            }\n            return;\n        }\n        throw Exception(At_Phrase(*syntax_, fm),\n            stringify(\"assertion failed: expected error \\\"\",\n                expected_msg_str,\n                \"\\\", got value \", result));\n    }\n};\nstruct Assert_Error_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        Shared<const Comma_Phrase> commas = nullptr;\n        if (auto parens = cast<Paren_Phrase>(ph.arg_)) {\n            commas = cast<Comma_Phrase>(parens->body_);\n        }\n        else if (auto brackets = cast<Bracket_Phrase>(ph.arg_)) {\n            commas = cast<Comma_Phrase>(brackets->body_);\n        }\n        if (commas && commas->args_.size() == 2) {\n            auto msg = analyse_op(*commas->args_[0].expr_, env);\n            Shared<Operation> expr = nullptr;\n            Shared<const String> actual_msg = nullptr;\n            try {\n                expr = analyse_op(*commas->args_[1].expr_, env);\n            } catch (Exception& e) {\n                actual_msg = e.shared_what();\n            }\n            return make<Assert_Error_Action>(share(ph), msg, actual_msg, expr);\n        } else {\n            throw Exception(At_Phrase(ph, env),\n                \"assert_error: expecting 2 arguments\");\n        }\n    }\n    virtual void print_help(std::ostream& out) const override\n    {\n        out <<\n            \"assert_error [error_message_string, expression]\\n\"\n            \"  Evaluate the expression argument. Assert that the expression evaluation terminates with an error,\\n\"\n            \"  and that the resulting error message is equal to error_message_string. Used for unit testing.\\n\";\n    }\n};\n\nstruct Defined_Expression : public Just_Expression\n{\n    Shared<const Operation> expr_;\n    Symbol_Expr selector_;\n\n    Defined_Expression(\n        Shared<const Phrase> syntax,\n        Shared<const Operation> expr,\n        Symbol_Expr selector)\n    :\n        Just_Expression(move(syntax)),\n        expr_(move(expr)),\n        selector_(move(selector))\n    {\n    }\n\n    static Value defined_at(Value val, Symbol_Ref id)\n    {\n        if (auto rec = val.maybe<Record>())\n            return {rec->hasfield(id)};\n      #if 0\n        else if (auto list = val.maybe<List>()) {\n            Shared<List> result = make_tail_array<List>(list->size());\n            for (unsigned i = 0; i < list->size(); ++i)\n                result->at(i) = defined_at(list->at(i), id);\n            return {result};\n        }\n      #endif\n        else\n            return {false};\n    }\n    virtual Value eval(Frame& fm) const override\n    {\n        auto val = expr_->eval(fm);\n        auto id = selector_.eval(fm);\n        return defined_at(val, id);\n    }\n};\nstruct Defined_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        auto argph = strip_parens(ph.arg_);\n        if (auto dot = cast<const Dot_Phrase>(argph)) {\n            if (auto brackets = cast<const Bracket_Phrase>(dot->right_)) {\n                return make<Defined_Expression>(\n                    share(ph),\n                    analyse_op(*dot->left_, env),\n                    Symbol_Expr(analyse_op(*brackets->body_, env)));\n            }\n            if (auto string = cast<const String_Phrase>(dot->right_)) {\n                env.sstate_.deprecate(\n                    &Source_State::dot_string_deprecated_, 1,\n                    At_Phrase(*argph, env),\n                    Source_State::dot_string_deprecated_msg);\n            }\n        }\n        auto arg = analyse_op(*argph, env);\n        if (auto dot = cast<Dot_Expr>(arg)) {\n            return make<Defined_Expression>(\n                share(ph), dot->base_, dot->selector_);\n        }\n        if (auto slice = cast<Index_Expr>(arg)) {\n            return make<Defined_Expression>(\n                share(ph), slice->arg1_, Symbol_Expr(slice->arg2_));\n        }\n        throw Exception(At_Phrase(*argph, env),\n            \"defined: argument must be `expression.identifier`\"\n                \" or `expression.[expression]`\"\n                \" or `expression@expression`\");\n    }\n    virtual void print_help(std::ostream& out) const override\n    {\n        out <<\n            \"defined (record . identifier)\\n\"\n            \"  True if a field named identifier is defined by record, otherwise false.\\n\"\n            \"  For example, given 'R={a:1}', then 'defined(R.a)' is true and 'defined(R.foo)' is false.\\n\"\n            \"\\n\"\n            \"defined (record .[ symbolExpr ])\\n\"\n            \"  Test the field named by the symbol after evaluating symbolExpr. If the field exists,\\n\"\n            \"  return true, otherwise false. This allows the field name to be computed at run time.\\n\"\n            \"  For example, 'defined(R.[#a])' is true and 'defined(R.[#foo])' is false.\\n\";\n    }\n};\n\nstruct Builtin_Time : public Builtin\n{\n    virtual Shared<Meaning> to_meaning(const Identifier& id) const\n    {\n        return make<Constant>(share(id), Value{make<Uniform_Variable>(\n            make_symbol(\"time\"),\n            std::string(\"u_time\"),\n            SC_Type::Num(),\n            share(id))});\n    }\n};\n\nstruct Builtin_Resolution : public Builtin\n{\n    virtual Shared<Meaning> to_meaning(const Identifier& id) const\n    {\n        return make<Constant>(share(id), Value{make<Uniform_Variable>(\n            make_symbol(\"resolution\"),\n            std::string(\"u_resolution\"),\n            SC_Type::Array(SC_Type::Num(), 2),\n            share(id))});\n    }\n};\n\nconst Namespace&\nbuiltin_namespace()\n{\n    #define FUNCTION(nm,f) \\\n        {make_symbol(nm), make<Builtin_Value>(Value{make<f>(nm)})}\n\n    static const Namespace names = {\n    {make_symbol(\"pi\"), make<Builtin_Value>(pi)},\n    {make_symbol(\"tau\"), make<Builtin_Value>(two_pi)},\n    {make_symbol(\"inf\"), make<Builtin_Value>(INFINITY)},\n    {make_symbol(\"false\"), make<Builtin_Value>(Value(false))},\n    {make_symbol(\"true\"), make<Builtin_Value>(Value(true))},\n    {make_symbol(\"Any\"), make<Builtin_Value>(Value(make<Any_Type>()))},\n    {make_symbol(\"Bool\"), make<Builtin_Value>(Value(make<Bool_Type>()))},\n    {make_symbol(\"Char\"), make<Builtin_Value>(Value(make<Char_Type>()))},\n    {make_symbol(\"Func\"), make<Builtin_Value>(Value(make<Func_Type>()))},\n    {make_symbol(\"Num\"), make<Builtin_Value>(Value(make<Num_Type>()))},\n    {make_symbol(\"Symbol\"), make<Builtin_Value>(Value(make<Symbol_Type>()))},\n    {make_symbol(\"Type\"), make<Builtin_Value>(Value(make<Type_Type>()))},\n    {make_symbol(\"time\"), make<Builtin_Time>()},\n    {make_symbol(\"resolution\"), make<Builtin_Resolution>()},\n\n    FUNCTION(\"as\", F_as),\n    FUNCTION(\"is\", F_is),\n    FUNCTION(\"Tuple\", F_Tuple),\n    FUNCTION(\"List\", F_List),\n    FUNCTION(\"Array\", F_Array),\n    FUNCTION(\"Struct\", F_Struct),\n    FUNCTION(\"Record\", F_Record),\n    FUNCTION(\"is_bool\", F_is_bool),\n    FUNCTION(\"is_char\", F_is_char),\n    FUNCTION(\"is_symbol\", F_is_symbol),\n    FUNCTION(\"is_num\", F_is_num),\n    FUNCTION(\"is_string\", F_is_string),\n    FUNCTION(\"is_list\", F_is_list),\n    FUNCTION(\"is_record\", F_is_record),\n    FUNCTION(\"is_primitive_func\", F_is_primitive_func),\n    FUNCTION(\"is_func\", F_is_func),\n    FUNCTION(\"bit\", F_bit),\n    FUNCTION(\"sqrt\", F_sqrt),\n    FUNCTION(\"log\", F_log),\n    FUNCTION(\"abs\", F_abs),\n    FUNCTION(\"floor\", F_floor),\n    FUNCTION(\"ceil\", F_ceil),\n    FUNCTION(\"trunc\", F_trunc),\n    FUNCTION(\"round\", F_round),\n    FUNCTION(\"frac\", F_frac),\n    FUNCTION(\"sign\", F_sign),\n    FUNCTION(\"sin\", F_sin),\n    FUNCTION(\"cos\", F_cos),\n    FUNCTION(\"tan\", F_tan),\n    FUNCTION(\"asin\", F_asin),\n    FUNCTION(\"acos\", F_acos),\n    FUNCTION(\"atan\", F_atan),\n    FUNCTION(\"phase\", F_phase),\n    FUNCTION(\"sinh\", F_sinh),\n    FUNCTION(\"cosh\", F_cosh),\n    FUNCTION(\"tanh\", F_tanh),\n    FUNCTION(\"asinh\", F_asinh),\n    FUNCTION(\"acosh\", F_acosh),\n    FUNCTION(\"atanh\", F_atanh),\n    FUNCTION(\"max\", F_max),\n    FUNCTION(\"min\", F_min),\n    FUNCTION(\"sum\", F_sum),\n    FUNCTION(\"not\", F_not),\n    FUNCTION(\"and\", F_and),\n    FUNCTION(\"or\", F_or),\n    FUNCTION(\"xor\", F_xor),\n    FUNCTION(\"lshift\", F_lshift),\n    FUNCTION(\"rshift\", F_rshift),\n    FUNCTION(\"bool32_sum\", F_bool32_sum),\n    FUNCTION(\"bool32_product\", F_bool32_product),\n    FUNCTION(\"bool32_to_nat\", F_bool32_to_nat),\n    FUNCTION(\"nat_to_bool32\", F_nat_to_bool32),\n    FUNCTION(\"bool32_to_float\", F_bool32_to_float),\n    FUNCTION(\"float_to_bool32\", F_float_to_bool32),\n    FUNCTION(\"select\", F_select),\n    FUNCTION(\"dot\", F_dot),\n    FUNCTION(\"mag\", F_mag),\n    FUNCTION(\"count\", F_count),\n    FUNCTION(\"fields\", F_fields),\n    FUNCTION(\"char\", F_char),\n    FUNCTION(\"ucode\", F_ucode),\n    FUNCTION(\"symbol\", F_symbol),\n    FUNCTION(\"string\", F_string),\n    FUNCTION(\"repr\", F_repr),\n    FUNCTION(\"match\", F_match),\n    FUNCTION(\"compose\", F_compose),\n\n    // top secret index API (aka lenses)\n    {make_symbol(\"this\"), make<Builtin_Value>(Value{make<This>()})},\n    FUNCTION(\"tslice\", F_tslice),\n    FUNCTION(\"tpath\", F_tpath),\n    FUNCTION(\"amend\", F_amend),\n\n    {make_symbol(\"file\"), make<Builtin_Meaning<File_Metafunction>>()},\n    {make_symbol(\"print\"), make<Builtin_Meaning<Print_Metafunction>>()},\n    {make_symbol(\"warning\"), make<Builtin_Meaning<Warning_Metafunction>>()},\n    {make_symbol(\"error\"), make<Builtin_Meaning<Error_Metafunction>>()},\n    {make_symbol(\"assert\"), make<Builtin_Meaning<Assert_Metafunction>>()},\n    {make_symbol(\"assert_error\"), make<Builtin_Meaning<Assert_Error_Metafunction>>()},\n    {make_symbol(\"exec\"), make<Builtin_Meaning<Exec_Metafunction>>()},\n    {make_symbol(\"defined\"), make<Builtin_Meaning<Defined_Metafunction>>()},\n    };\n    return names;\n}\n\n} // namespace curv\n", "meta": {"hexsha": "cc3f14cd4346502881b75cf2331dae58fac00020", "size": 62142, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libcurv/builtin.cc", "max_stars_repo_name": "curv3d/curv", "max_stars_repo_head_hexsha": "f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 921.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T18:47:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:36:18.000Z", "max_issues_repo_path": "libcurv/builtin.cc", "max_issues_repo_name": "curv3d/curv", "max_issues_repo_head_hexsha": "f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 93.0, "max_issues_repo_issues_event_min_datetime": "2019-01-11T15:35:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T17:42:05.000Z", "max_forks_repo_path": "libcurv/builtin.cc", "max_forks_repo_name": "curv3d/curv", "max_forks_repo_head_hexsha": "f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2019-01-20T09:37:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T15:12:10.000Z", "avg_line_length": 34.755033557, "max_line_length": 120, "alphanum_fraction": 0.574796434, "num_tokens": 15877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19024507263306137}}
{"text": "//---------------------------------------------------------------------------------------------------------------------\n//  AR MICO plugin\n//---------------------------------------------------------------------------------------------------------------------\n//  Copyright 2020 Pablo Ramon Soria (a.k.a. Bardo91) pabramsor@gmail.com\n//---------------------------------------------------------------------------------------------------------------------\n//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n//  and associated documentation files (the \"Software\"), to deal in the Software without restriction,\n//  including without limitation the rights to use, copy, modify, merge, publish, distribute,\n//  sublicense, and/or 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 all copies or substantial\n//  portions of the Software.\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n//  BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES\n//  OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//---------------------------------------------------------------------------------------------------------------------\n\n\n#include <mico/ar/flow/BlockArucoCoordinates.h>\n#include <flow/Outpipe.h>\n#include <flow/Policy.h>\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Eigen>\n\n#include <opencv2/aruco.hpp>\n\nnamespace mico{\n    namespace ar {\n        BlockArucoCoordinates::BlockArucoCoordinates(){\n            dictionary_ = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);;\n\n            createPipe<Eigen::Matrix4f>(\"coordinates\");\n            createPipe<std::map<int, Eigen::Matrix4f>>(\"all_coordinates\");\n            createPipe<cv::Mat>(\"output_image\");\n\n            createPolicy({  flow::makeInput<cv::Mat>(\"image\") });\n\n            registerCallback({\"image\"}, \n                [&](flow::DataFlow _data){\n                    if(!idle_) return;\n                    idle_ = false;\n                    auto image = _data.get<cv::Mat>(\"image\").clone();\n                    if(!image.rows){\n                        idle_ = true;\n                        return ;\n                    } \n\n                    cv::rotate(image, image, cv::ROTATE_180);\n\n\n                    std::vector<int> ids;\n                    std::vector<std::vector<cv::Point2f>> corners;\n                    cv::aruco::detectMarkers(image, dictionary_, corners, ids);\n                    // if at least one marker detected\n                    if (ids.size() > 0) {\n                        cv::aruco::drawDetectedMarkers(image, corners, ids);\n\n                        if (isCalibrated_) {\n                            std::vector<cv::Vec3d> rvecs, tvecs;\n                            cv::aruco::estimatePoseSingleMarkers(corners, 0.05, cameraMatrix_, distCoeffs_, rvecs, tvecs);\n\n\n                            if (id_ == 0 && getPipe(\"all_coordinates\")->registrations()) {\n                                std::map<int, Eigen::Matrix4f> all;\n                                // draw axis for each marker\n                                for (int id = 0; id < ids.size(); id++) {\n                                    cv::Mat R;\n                                    cv::Rodrigues(rvecs[id], R);\n\n                                    Eigen::Matrix4f coordinates = Eigen::Matrix4f::Identity();\n                                    for (unsigned i = 0; i < 3; i++) {\n                                        for (unsigned j = 0; j < 3; j++) {\n                                            coordinates(i, j) = R.at<double>(i, j);\n                                        }\n                                        coordinates(i, 3) = tvecs[id](i);\n                                    }\n                                    all[ids[id]] = coordinates;\n                                }\n                                getPipe(\"all_coordinates\")->flush(all);\n                            }\n                            else {\n                                // draw axis for each marker\n                                for (int id = 0; id < ids.size(); id++) {\n                                    //cv::aruco::drawAxis(image, cameraMatrix_, distCoeffs_, rvecs[id], tvecs[id], 0.1);\n                                    if (ids[id] == id_) { // use as coordinate system\n                                        cv::Mat R;\n                                        cv::Rodrigues(rvecs[id],R);\n\n                                        Eigen::Matrix4f coordinates = Eigen::Matrix4f::Identity();\n                                        for (unsigned i = 0; i < 3; i++) {\n                                            for (unsigned j = 0; j < 3; j++) {\n                                                coordinates(i, j) = R.at<double>(i, j);\n                                            }\n                                            coordinates(i, 3) = tvecs[id](i);\n                                        }\n                                        if (getPipe(\"coordinates\")->registrations()) {\n                                            getPipe(\"coordinates\")->flush(coordinates);\n                                        }\n                                    }\n                                }\n                            }\n\n                        }\n                    }\n\n                    \n                    if (getPipe(\"output_image\")->registrations()) {\n                        getPipe(\"output_image\")->flush(image);\n                    }\n\n                    idle_ = true;\n                }\n            );\n\n        }\n\n        bool BlockArucoCoordinates::configure(std::vector<flow::ConfigParameterDef> _params) {\n            if (auto param = getParamByName(_params, \"id\"); param) {\n                id_ = param.value().asInteger();\n            }\n\n            if (auto param = getParamByName(_params, \"calibration_file\"); param) {\n                std::string paramFile = param.value().asPath().string();\n                \n                cv::FileStorage fs;\n                try {\n                    fs.open(paramFile, cv::FileStorage::READ);\n                }\n                catch (cv::Exception& e) {\n                    return false;\n                }\n                \n                if (fs.isOpened()) {\n                    fs[\"Matrix\"] >> cameraMatrix_;\n                    fs[\"DistCoeffs\"] >> distCoeffs_;\n                \n                    isCalibrated_ = true;\n                }\n                else {\n                    isCalibrated_ = false;\n                }\n            }\n\n            return isCalibrated_;\n        }\n        \n        std::vector<flow::ConfigParameterDef> BlockArucoCoordinates::parameters(){\n            return {\n                {\"id\", flow::ConfigParameterDef::eParameterType::INTEGER, 1},\n                {\"calibration_file\", flow::ConfigParameterDef::eParameterType::PATH, fs::path(\"\")}\n            };\n        }\n    }\n\n}", "meta": {"hexsha": "06e19272cd497a0e9bddaf34bed0d426316ce7cd", "size": 7334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mplugins/ar_mplugin/src/ar/flow/BlockArucoCoordinates.cpp", "max_stars_repo_name": "mico-corp/mico", "max_stars_repo_head_hexsha": "45febf13da8c919eea77af9fa3b91afeb324f81b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T19:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:13:29.000Z", "max_issues_repo_path": "mplugins/ar_mplugin/src/ar/flow/BlockArucoCoordinates.cpp", "max_issues_repo_name": "mico-corp/mico", "max_issues_repo_head_hexsha": "45febf13da8c919eea77af9fa3b91afeb324f81b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T21:27:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T17:03:02.000Z", "max_forks_repo_path": "mplugins/ar_mplugin/src/ar/flow/BlockArucoCoordinates.cpp", "max_forks_repo_name": "mico-corp/mico", "max_forks_repo_head_hexsha": "45febf13da8c919eea77af9fa3b91afeb324f81b", "max_forks_repo_licenses": ["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.8375, "max_line_length": 122, "alphanum_fraction": 0.4168257431, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19024507263306137}}
{"text": "#include \"../agg.hpp\"\n#include <boost/accumulators/statistics/max.hpp>\n\nARRAY_AGGREGATE_FNC(amax, tag::max);\nSQL_AGGREGATE_FNC(v_max, tag::max);\n", "meta": {"hexsha": "6e6cfd0ceb2704310a6a6c4623dec5ca09cc9030", "size": 145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/aggregate/max.cpp", "max_stars_repo_name": "tarkmeper/numpgsql", "max_stars_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T15:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-07T16:31:55.000Z", "max_issues_repo_path": "src/math/aggregate/max.cpp", "max_issues_repo_name": "tarkmeper/numpgsql", "max_issues_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_issues_repo_licenses": ["MIT"], "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/aggregate/max.cpp", "max_forks_repo_name": "tarkmeper/numpgsql", "max_forks_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_forks_repo_licenses": ["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.1666666667, "max_line_length": 48, "alphanum_fraction": 0.7586206897, "num_tokens": 44, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.19024506910387573}}
{"text": "#ifndef MANIFOLDS_FUNCTIONS_FACTOR_EXPRESSIONS_HH\n#define MANIFOLDS_FUNCTIONS_FACTOR_EXPRESSIONS_HH\n\n#include \"variables.hh\"\n#include \"concepts.hh\"\n#include <boost/mpl/map.hpp>\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/insert.hpp>\n#include <boost/mpl/contains.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/erase_key.hpp>\n#include <boost/mpl/sort.hpp>\n#include <boost/mpl/unique.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/less.hpp>\n#include <boost/mpl/front.hpp>\n#include <boost/mpl/set.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/mpl/zip_view.hpp>\n#include <utility>\n\nnamespace boost {\nnamespace mpl {\ntemplate <class T, T t>\nstruct less_tag<std::integral_constant<T, t> > : less_tag<integral_c<T, t> > {};\n}\n}\n\nnamespace manifolds {\n\ntemplate <class A, class B, bool = (A::value < B::value)> struct max_t : B {};\n\ntemplate <class A, class B> struct max_t<A, B, false> : A {};\n\ntemplate <class F, class = void>\nstruct HighestVariable : std::integral_constant<int, -1> {};\n\ntemplate <class F, class... Fs>\nstruct HighestVariable<\n    std::tuple<F, Fs...> > : max_t<HighestVariable<F>,\n                                   HighestVariable<std::tuple<Fs...> > > {};\n\ntemplate <>\nstruct HighestVariable<std::tuple<> > : std::integral_constant<int, -1> {};\n\ntemplate <int i, bool a, bool c>\nstruct HighestVariable<Variable<i, a, c> > : std::integral_constant<int, i> {};\n\ntemplate <class F>\nstruct HighestVariable<F, IsFunctionContainer<F> > : HighestVariable<decltype(\n                                                         std::declval<F>()\n                                                             .GetFunctions())> {\n};\n\ntemplate <class F, class = void> struct Factors {\n  typedef typename std::conditional<\n      F::stateless, boost::mpl::map<boost::mpl::pair<F, int_<1> > >,\n      boost::mpl::map<> >::type type;\n};\n\ntemplate <class Map, class Key,\n          bool = boost::mpl::has_key<Map, Key>::type::value,\n          bool = is_stateless<Key>::value>\nstruct InsertOrIncrement {\n  typedef typename boost::mpl::insert<\n      typename boost::mpl::erase_key<Map, Key>::type,\n      boost::mpl::pair<\n          Key, int_<boost::mpl::at<Map, Key>::type::value + 1> > >::type type;\n};\n\ntemplate <class Map, class Key, bool stateless>\nstruct InsertOrIncrement<Map, Key, false, stateless> {\n  typedef typename std::conditional<\n      stateless, boost::mpl::insert<Map, boost::mpl::pair<Key, int_<1> > >,\n      boost::mpl::map<> >::type::type type;\n};\n\ntemplate <class, class, int> struct PowerSetIndicesImpl;\n\ntemplate <class... Sequences, std::size_t... indices, int count>\nstruct PowerSetIndicesImpl<std::tuple<Sequences...>,\n                           std::integer_sequence<std::size_t, indices...>,\n                           count> {\n  template <class, std::size_t> struct Add;\n\n  template <std::size_t... is, std::size_t i>\n  struct Add<std::integer_sequence<std::size_t, is...>, i> {\n    typedef std::integer_sequence<std::size_t, i, is...> type;\n  };\n\n  template <class Sequence, std::size_t... is> struct AddAll {\n    typedef std::tuple<typename Add<Sequence, is>::type...> type;\n  };\n\n  typedef decltype(std::tuple_cat(\n      typename AddAll<Sequences, indices...>::type()...,\n      std::tuple<std::integer_sequence<std::size_t, indices>...>())) NextIter;\n  typedef typename PowerSetIndicesImpl<\n      NextIter, std::integer_sequence<std::size_t, indices...>, count - 1>::type\n  type;\n  typedef typename PowerSetIndicesImpl<\n      NextIter, std::integer_sequence<std::size_t, indices...>,\n      count - 1>::type_old type_old;\n};\n\ntemplate <class Vector, class Obj, class... Objs> struct CreateVector {\n  typedef typename boost::mpl::push_back<\n      typename CreateVector<Vector, Objs...>::type, Obj>::type type;\n};\n\ntemplate <class Vector, class Obj> struct CreateVector<Vector, Obj> {\n  typedef boost::mpl::vector<Obj> type;\n};\n\ntemplate <class Container, class Tuple> struct TupleToContainer;\n\ntemplate <class Container, class... Ts>\nstruct TupleToContainer<Container, std::tuple<Ts...> > : CreateVector<Container,\n                                                                      Ts...> {};\n\ntemplate <class... Sets, std::size_t... indices>\nstruct PowerSetIndicesImpl<std::tuple<Sets...>,\n                           std::integer_sequence<std::size_t, indices...>, 0> {\n  template <class> struct Sort;\n\n  struct Samer {\n    template <class A, class B> using apply = std::is_same<A, B>;\n  };\n\n  template <class... Objects> struct Sort<std::tuple<Objects...> > {\n    struct VecComp {\n\n      template <class Left, class Right, class = void> struct apply {\n        static const bool fronts_same = (boost::mpl::front<Left>::type::value ==\n                                         boost::mpl::front<Right>::type::value);\n        typedef typename eval_if_t<\n            fronts_same, apply<typename boost::mpl::pop_front<Left>::type,\n                               typename boost::mpl::pop_front<Right>::type>,\n            bool_<(boost::mpl::front<Left>::type::value <\n                   boost::mpl::front<Right>::type::value)> >::type type;\n      };\n\n      template <class Left, class Right>\n      struct apply<Left, Right,\n                   typename std::enable_if<\n                       !boost::mpl::size<Left>::type::value ||\n                       !boost::mpl::size<Right>::type::value>::type> {\n        typedef bool_<(boost::mpl::size<Left>::type::value <\n                       boost::mpl::size<Right>::type::value)> type;\n      };\n    };\n\n    typedef typename boost::mpl::sort<\n        typename CreateVector<boost::mpl::vector<>, Objects...>::type,\n        VecComp>::type Sorted;\n    typedef typename boost::mpl::unique<Sorted, Samer>::type type;\n  };\n\n  template <std::size_t... is>\n  struct Sort<std::integer_sequence<std::size_t, is...> > {\n    typedef typename CreateVector<\n        boost::mpl::vector<>, std::integral_constant<std::size_t, is>...>::type\n    Vector;\n    typedef typename boost::mpl::sort<Vector>::type Sorted;\n    typedef typename boost::mpl::unique<Sorted, Samer>::type type;\n  };\n\n  struct AppendSeq {\n    template <class, class> struct apply;\n\n    template <std::size_t... is, class Next>\n    struct apply<std::integer_sequence<std::size_t, is...>, Next> {\n      typedef std::integer_sequence<std::size_t, is..., Next::value> type;\n    };\n  };\n\n  template <class Set>\n  using Transfer = typename boost::mpl::fold<\n      Set, std::integer_sequence<std::size_t>, AppendSeq>::type;\n\n  typedef std::tuple<Transfer<typename Sort<Sets>::type>...> type_old;\n\n  typedef typename Sort<std::tuple<typename Sort<Sets>::type...> >::type\n  SortedVector;\n\n  struct AppendTuple {\n    template <class, class> struct apply;\n    template <class... Objects, class Next>\n    struct apply<std::tuple<Objects...>, Next> {\n      typedef std::tuple<Objects..., Transfer<Next> > type;\n    };\n  };\n\n  typedef typename boost::mpl::fold<SortedVector, std::tuple<>,\n                                    AppendTuple>::type type;\n};\n\ntemplate <int N> struct PowerSetIndices {\n  typedef typename PowerSetIndicesImpl<\n      std::tuple<>, std::make_index_sequence<N>, N>::type type;\n  typedef typename PowerSetIndicesImpl<\n      std::tuple<>, std::make_index_sequence<N>, N>::type_old type_old;\n};\n\ntemplate <template <class...> class Container, class... Funcs>\nstruct Factors<Container<Funcs...>,\n               IsReorderableFunctionContainer<Container<Funcs...> > > {\n  template <class> struct SubFactors;\n\n  template <class... Fs> struct SubFactors<std::tuple<Fs...> > {\n    typedef boost::mpl::vector<typename Factors<Fs>::type...> type;\n  };\n\n  struct Merger2 {\n    template <class Map, class Next> struct apply {\n      typedef typename InsertOrIncrement<Map, typename Next::first>::type type;\n    };\n  };\n\n  struct Merger1 {\n    template <class OverallMap, class CurrentMap> struct apply {\n      typedef typename boost::mpl::fold<CurrentMap, OverallMap, Merger2>::type\n      type;\n    };\n  };\n\n  typedef typename boost::mpl::fold<\n      typename SubFactors<\n          decltype(std::declval<Container<Funcs...> >().GetFunctions())>::type,\n      boost::mpl::map<>, Merger1>::type Individuals;\n\n  typedef typename PowerSetIndices<sizeof...(Funcs)>::type power_set_indices;\n\n  struct AddCombo {\n    template <class Map, class Next> struct apply {};\n\n    template <class Map, std::size_t... indices>\n    struct apply<Map, std::integer_sequence<std::size_t, indices...> > {\n      struct Adder {\n        template <class M, class N> struct apply {\n          typedef typename InsertOrIncrement<\n              M, typename nth<N::value, Funcs...>::type>::type type;\n        };\n      };\n      typedef InsertOrIncrement<\n          Map, Container<typename nth<indices, Funcs...>::type...> > Inserted;\n      typedef typename eval_if_t<(sizeof...(indices) > 1), Inserted, Map>::type\n      type;\n    };\n  };\n\n  typedef typename boost::mpl::fold<\n      typename TupleToContainer<boost::mpl::vector<>, power_set_indices>::type,\n      Individuals, AddCombo>::type type;\n};\n\ntemplate <class... Fs> struct Factors<Composition<Fs...> > {\n  template <class> struct SubFactors;\n\n  template <class F, class... F2s> struct SubFactors<Composition<F, F2s...> > {\n    typedef typename SubFactors<Composition<F2s...> >::type SubType;\n    typedef InsertOrIncrement<SubType, Composition<F, F2s...> > InsertExpr;\n    typedef typename std::conditional<\n        is_stateless<Composition<F, F2s...> >::value, InsertExpr,\n        SubType>::type::type type;\n  };\n\n  template <class F> struct SubFactors<Composition<F> > {\n    typedef typename std::conditional<\n        is_variable<F>::value, boost::mpl::map<>,\n        boost::mpl::map<boost::mpl::pair<F, int_<1> > > >::type type;\n  };\n\n  typedef typename SubFactors<Composition<Fs...> >::type type;\n};\n\ntemplate <class F> struct Factors<F, Variable_c<F> > {\n  typedef boost::mpl::map<> type;\n};\n\ntemplate <class FactorsMap> struct Filter1OffFactors {\n  struct Adder {\n    template <class Map, class Next> struct apply {\n      typedef typename eval_if_t<(Next::second::value > 1),\n                                 boost::mpl::insert<Map, typename Next::first>,\n                                 Map>::type type;\n    };\n  };\n\n  typedef typename boost::mpl::fold<FactorsMap, boost::mpl::set<>, Adder>::type\n  type;\n};\n\ntemplate <class F> struct AssignVariables {\n  static const std::size_t nHighestVarIndex = HighestVariable<F>::type::value;\n\n  typedef typename Factors<F>::type AllFactors;\n  typedef typename Filter1OffFactors<AllFactors>::type Factors;\n\n  typedef boost::mpl::range_c<std::size_t, nHighestVarIndex + 1,\n                              nHighestVarIndex + 1 +\n                                  boost::mpl::size<Factors>::type::value>\n  NewVarIndices;\n\n  struct Add {\n    template <class Map, class T> struct apply {\n      typedef typename boost::mpl::insert<\n          Map, boost::mpl::pair<\n                   typename boost::mpl::at_c<T, 0>::type,\n                   Variable<boost::mpl::at_c<T, 1>::type::value> > >::type type;\n    };\n  };\n\n  typedef typename boost::mpl::fold<\n      boost::mpl::zip_view<boost::mpl::vector<Factors, NewVarIndices> >,\n      boost::mpl::map<>, Add>::type type;\n};\n\ntemplate <class ExprToVarMap, class F>\nauto FactorSingle(F f, boost::mpl::false_) {\n  return f;\n}\n\ntemplate <class ExprToVarMap, class F>\nauto FactorSingle(F f, boost::mpl::true_) {\n  return typename boost::mpl::at<ExprToVarMap, F>::type{};\n}\n\ntemplate <class ExprToVarMap, class F> auto FactorSingle(F f) {\n  FactorSingle(f, typename boost::mpl::has_key<ExprToVarMap, F>::type());\n}\n\ntemplate <class ExprToVarMap, class F> auto ApplyFactoring(F f) {\n  return FactorSingle(f);\n}\n\ntemplate <template <class...> class Container, class ExprToVarMap>\nstruct GetContainerContents {\n  struct AddTo {\n    template <class Vector, class Next> struct apply {\n      typedef Vector type;\n    };\n\n    template <class Vector, class... Funcs>\n    struct apply<Vector, Container<Funcs...> > {\n      typedef typename boost::mpl::push_back<\n          Vector, boost::mpl::vector<Funcs...> >::type type;\n    };\n  };\n};\n\ntemplate <class ExprToVarMap, template <class...> class Container, class... Fs,\n          class = IsReorderableFunctionContainer<Container<Fs...> > >\nauto ApplyFactoring(Container<Fs...> c) {}\n}\n\n#endif\n", "meta": {"hexsha": "cd23e648ff8752d6b4797d301cf9b572d6aeec38", "size": 12274, "ext": "hh", "lang": "C++", "max_stars_repo_path": "functions/factor.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/factor.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/factor.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": 34.2849162011, "max_line_length": 80, "alphanum_fraction": 0.633126935, "num_tokens": 3041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3775406547908327, "lm_q1q2_score": 0.19024506557469006}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright Jens Maurer 2006-1011\n//  Copyright Steven Watanabe 2011\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_RANDOM_HPP\n#define BOOST_MP_RANDOM_HPP\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4127)\n#endif\n\n#include <boost/multiprecision/number.hpp>\n\nnamespace boost{ namespace random{ namespace detail{\n//\n// This is a horrible hack: this declaration has to appear before the definition of\n// uniform_int_distribution, otherwise it won't be used...\n// Need to find a better solution, like make Boost.Random safe to use with\n// UDT's and depricate/remove this header altogether.\n//\ntemplate<class Engine, class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>\nboost::multiprecision::number<Backend, ExpressionTemplates> \n   generate_uniform_int(Engine& eng, const boost::multiprecision::number<Backend, ExpressionTemplates>& min_value, const boost::multiprecision::number<Backend, ExpressionTemplates>& max_value);\n\n}}}\n\n#include <boost/random.hpp>\n#include <boost/mpl/eval_if.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace detail{\n\ntemplate<class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>\nstruct subtract<boost::multiprecision::number<Backend, ExpressionTemplates>, true> \n{ \n  typedef boost::multiprecision::number<Backend, ExpressionTemplates> result_type;\n  result_type operator()(result_type const& x, result_type const& y) { return x - y; }\n};\n\n}\n\ntemplate<class Engine, std::size_t w, class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>\nclass independent_bits_engine<Engine, w, boost::multiprecision::number<Backend, ExpressionTemplates> >\n{\npublic:\n    typedef Engine base_type;\n    typedef boost::multiprecision::number<Backend, ExpressionTemplates> result_type;\n\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return 0; }\n    // This is the only function we modify compared to the primary template:\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    {\n       // This expression allows for the possibility that w == std::numeric_limits<result_type>::digits:\n       return (((result_type(1) << (w - 1)) - 1) << 1) + 1; \n    }\n\n    independent_bits_engine() { }\n\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(independent_bits_engine,\n        result_type, seed_arg)\n    {\n        _base.seed(seed_arg);\n    }\n\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(independent_bits_engine,\n        SeedSeq, seq)\n    { _base.seed(seq); }\n\n    independent_bits_engine(const base_type& base_arg) : _base(base_arg) {}\n\n    template<class It>\n    independent_bits_engine(It& first, It last) : _base(first, last) { }\n\n    void seed() { _base.seed(); }\n\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(independent_bits_engine,\n        result_type, seed_arg)\n    { _base.seed(seed_arg); }\n\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(independent_bits_engine,\n        SeedSeq, seq)\n    { _base.seed(seq); }\n\n    template<class It> void seed(It& first, It last)\n    { _base.seed(first, last); }\n\n    result_type operator()()\n    {\n        // While it may seem wasteful to recalculate this\n        // every time, both msvc and gcc can propagate\n        // constants, resolving this at compile time.\n        base_unsigned range =\n            detail::subtract<base_result>()((_base.max)(), (_base.min)());\n        std::size_t m =\n            (range == (std::numeric_limits<base_unsigned>::max)()) ?\n                std::numeric_limits<base_unsigned>::digits :\n                detail::integer_log2(range + 1);\n        std::size_t n = (w + m - 1) / m;\n        std::size_t w0, n0;\n        base_unsigned y0, y1;\n        base_unsigned y0_mask, y1_mask;\n        calc_params(n, range, w0, n0, y0, y1, y0_mask, y1_mask);\n        if(base_unsigned(range - y0 + 1) > y0 / n) {\n            // increment n and try again.\n            ++n;\n            calc_params(n, range, w0, n0, y0, y1, y0_mask, y1_mask);\n        }\n\n        BOOST_ASSERT(n0*w0 + (n - n0)*(w0 + 1) == w);\n\n        result_type S = 0;\n        for(std::size_t k = 0; k < n0; ++k) {\n            base_unsigned u;\n            do {\n                u = detail::subtract<base_result>()(_base(), (_base.min)());\n            } while(u > base_unsigned(y0 - 1));\n            S = (S << w0) + (u & y0_mask);\n        }\n        for(std::size_t k = 0; k < (n - n0); ++k) {\n            base_unsigned u;\n            do {\n                u = detail::subtract<base_result>()(_base(), (_base.min)());\n            } while(u > base_unsigned(y1 - 1));\n            S = (S << (w0 + 1)) + (u & y1_mask);\n        }\n        return S;\n    }\n  \n    /** Fills a range with random values */\n    template<class Iter>\n    void generate(Iter first, Iter last)\n    { detail::generate_from_int(*this, first, last); }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(boost::uintmax_t z)\n    {\n        for(boost::uintmax_t i = 0; i < z; ++i) {\n            (*this)();\n        }\n    }\n\n    const base_type& base() const { return _base; }\n\n    /**\n     * Writes the textual representation if the generator to a @c std::ostream.\n     * The textual representation of the engine is the textual representation\n     * of the base engine.\n     */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, independent_bits_engine, r)\n    {\n        os << r._base;\n        return os;\n    }\n\n    /**\n     * Reads the state of an @c independent_bits_engine from a\n     * @c std::istream.\n     */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, independent_bits_engine, r)\n    {\n        is >> r._base;\n        return is;\n    }\n\n    /**\n     * Returns: true iff the two @c independent_bits_engines will\n     * produce the same sequence of values.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(independent_bits_engine, x, y)\n    { return x._base == y._base; }\n    /**\n     * Returns: true iff the two @c independent_bits_engines will\n     * produce different sequences of values.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(independent_bits_engine)\n\nprivate:\n\n    /// \\cond show_private\n    typedef typename base_type::result_type base_result;\n    typedef typename make_unsigned<base_result>::type base_unsigned;\n\n    void calc_params(\n        std::size_t n, base_unsigned range,\n        std::size_t& w0, std::size_t& n0,\n        base_unsigned& y0, base_unsigned& y1,\n        base_unsigned& y0_mask, base_unsigned& y1_mask)\n    {\n        BOOST_ASSERT(w >= n);\n        w0 = w/n;\n        n0 = n - w % n;\n        y0_mask = (base_unsigned(2) << (w0 - 1)) - 1;\n        y1_mask = (y0_mask << 1) | 1;\n        y0 = (range + 1) & ~y0_mask;\n        y1 = (range + 1) & ~y1_mask;\n        BOOST_ASSERT(y0 != 0 || base_unsigned(range + 1) == 0);\n    }\n    /// \\endcond\n\n    Engine _base;\n};\n\ntemplate<class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>\nclass uniform_smallint<boost::multiprecision::number<Backend, ExpressionTemplates> >\n{\npublic:\n    typedef boost::multiprecision::number<Backend, ExpressionTemplates> input_type;\n    typedef boost::multiprecision::number<Backend, ExpressionTemplates> result_type;\n\n    class param_type\n    {\n    public:\n\n        typedef uniform_smallint distribution_type;\n\n        /** constructs the parameters of a @c uniform_smallint distribution. */\n        param_type(result_type const& min_arg = 0, result_type const& max_arg = 9)\n          : _min(min_arg), _max(max_arg)\n        {\n            BOOST_ASSERT(_min <= _max);\n        }\n\n        /** Returns the minimum value. */\n        result_type a() const { return _min; }\n        /** Returns the maximum value. */\n        result_type b() const { return _max; }\n        \n\n        /** Writes the parameters to a @c std::ostream. */\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\n        {\n            os << parm._min << \" \" << parm._max;\n            return os;\n        }\n    \n        /** Reads the parameters from a @c std::istream. */\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\n        {\n            is >> parm._min >> std::ws >> parm._max;\n            return is;\n        }\n\n        /** Returns true if the two sets of parameters are equal. */\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\n        { return lhs._min == rhs._min && lhs._max == rhs._max; }\n\n        /** Returns true if the two sets of parameters are different. */\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\n\n    private:\n        result_type _min;\n        result_type _max;\n    };\n\n    /**\n     * Constructs a @c uniform_smallint. @c min and @c max are the\n     * lower and upper bounds of the output range, respectively.\n     */\n    explicit uniform_smallint(result_type const& min_arg = 0, result_type const& max_arg = 9)\n      : _min(min_arg), _max(max_arg) {}\n\n    /**\n     * Constructs a @c uniform_smallint from its parameters.\n     */\n    explicit uniform_smallint(const param_type& parm)\n      : _min(parm.a()), _max(parm.b()) {}\n\n    /** Returns the minimum value of the distribution. */\n    result_type a() const { return _min; }\n    /** Returns the maximum value of the distribution. */\n    result_type b() const { return _max; }\n    /** Returns the minimum value of the distribution. */\n    result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _min; }\n    /** Returns the maximum value of the distribution. */\n    result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _max; }\n\n    /** Returns the parameters of the distribution. */\n    param_type param() const { return param_type(_min, _max); }\n    /** Sets the parameters of the distribution. */\n    void param(const param_type& parm)\n    {\n        _min = parm.a();\n        _max = 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    /** Returns a value uniformly distributed in the range [min(), max()]. */\n    template<class Engine>\n    result_type operator()(Engine& eng) const\n    {\n        typedef typename Engine::result_type base_result;\n        return generate(eng, boost::is_integral<base_result>());\n    }\n\n    /** Returns a value uniformly distributed in the range [param.a(), param.b()]. */\n    template<class Engine>\n    result_type operator()(Engine& eng, const param_type& parm) const\n    { return uniform_smallint(parm)(eng); }\n\n    /** Writes the distribution to a @c std::ostream. */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, uniform_smallint, ud)\n    {\n        os << ud._min << \" \" << ud._max;\n        return os;\n    }\n    \n    /** Reads the distribution from a @c std::istream. */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, uniform_smallint, ud)\n    {\n        is >> ud._min >> std::ws >> ud._max;\n        return is;\n    }\n\n    /**\n     * Returns true if the two distributions will produce identical\n     * sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(uniform_smallint, lhs, rhs)\n    { return lhs._min == rhs._min && lhs._max == rhs._max; }\n    \n    /**\n     * Returns true if the two distributions may produce different\n     * sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(uniform_smallint)\n\nprivate:\n    \n    // \\cond show_private\n    template<class Engine>\n    result_type generate(Engine& eng, boost::mpl::true_) const\n    {\n        // equivalent to (eng() - eng.min()) % (_max - _min + 1) + _min,\n        // but guarantees no overflow.\n        typedef typename Engine::result_type base_result;\n        typedef typename boost::make_unsigned<base_result>::type base_unsigned;\n        typedef result_type  range_type;\n        range_type range = random::detail::subtract<result_type>()(_max, _min);\n        base_unsigned base_range =\n            random::detail::subtract<result_type>()((eng.max)(), (eng.min)());\n        base_unsigned val =\n            random::detail::subtract<base_result>()(eng(), (eng.min)());\n        if(range >= base_range) {\n            return boost::random::detail::add<range_type, result_type>()(\n                static_cast<range_type>(val), _min);\n        } else {\n            base_unsigned modulus = static_cast<base_unsigned>(range) + 1;\n            return boost::random::detail::add<range_type, result_type>()(\n                static_cast<range_type>(val % modulus), _min);\n        }\n    }\n    \n    template<class Engine>\n    result_type generate(Engine& eng, boost::mpl::false_) const\n    {\n        typedef typename Engine::result_type base_result;\n        typedef result_type                  range_type;\n        range_type range = random::detail::subtract<result_type>()(_max, _min);\n        base_result val = boost::uniform_01<base_result>()(eng);\n        // what is the worst that can possibly happen here?\n        // base_result may not be able to represent all the values in [0, range]\n        // exactly.  If this happens, it will cause round off error and we\n        // won't be able to produce all the values in the range.  We don't\n        // care about this because the user has already told us not to by\n        // using uniform_smallint.  However, we do need to be careful\n        // to clamp the result, or floating point rounding can produce\n        // an out of range result.\n        range_type offset = static_cast<range_type>(val * (range + 1));\n        if(offset > range) return _max;\n        return boost::random::detail::add<range_type, result_type>()(offset , _min);\n    }\n    // \\endcond\n\n    result_type _min;\n    result_type _max;\n};\n\n\nnamespace detail{\n\ntemplate<class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>\nstruct select_uniform_01<boost::multiprecision::number<Backend, ExpressionTemplates> >\n{\n  template<class RealType>\n  struct apply\n  {\n    typedef new_uniform_01<boost::multiprecision::number<Backend, ExpressionTemplates> > type;\n  };\n};\n\ntemplate<class Engine, class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>\nboost::multiprecision::number<Backend, ExpressionTemplates> \n   generate_uniform_int(\n    Engine& eng, const boost::multiprecision::number<Backend, ExpressionTemplates>& min_value, const boost::multiprecision::number<Backend, ExpressionTemplates>& max_value,\n    boost::mpl::true_ /** is_integral<Engine::result_type> */)\n{\n    typedef boost::multiprecision::number<Backend, ExpressionTemplates> result_type;\n    // Since we're using big-numbers, use the result type for all internal calculations:\n    typedef result_type range_type;\n    typedef result_type base_result;\n    typedef result_type base_unsigned;\n    const range_type range = random::detail::subtract<result_type>()(max_value, min_value);\n    const base_result bmin = (eng.min)();\n    const base_unsigned brange =\n      random::detail::subtract<base_result>()((eng.max)(), (eng.min)());\n\n    if(range == 0) {\n      return min_value;    \n    } else if(brange == range) {\n      // this will probably never happen in real life\n      // basically nothing to do; just take care we don't overflow / underflow\n      base_unsigned v = random::detail::subtract<base_result>()(eng(), bmin);\n      return random::detail::add<base_unsigned, result_type>()(v, min_value);\n    } else if(brange < range) {\n      // use rejection method to handle things like 0..3 --> 0..4\n      for(;;) {\n        // concatenate several invocations of the base RNG\n        // take extra care to avoid overflows\n\n        //  limit == floor((range+1)/(brange+1))\n        //  Therefore limit*(brange+1) <= range+1\n        range_type limit;\n        if(std::numeric_limits<range_type>::is_bounded && (range == (std::numeric_limits<range_type>::max)())) {\n          limit = range/(range_type(brange)+1);\n          if(range % (range_type(brange)+1) == range_type(brange))\n            ++limit;\n        } else {\n          limit = (range+1)/(range_type(brange)+1);\n        }\n\n        // We consider \"result\" as expressed to base (brange+1):\n        // For every power of (brange+1), we determine a random factor\n        range_type result = range_type(0);\n        range_type mult = range_type(1);\n\n        // loop invariants:\n        //  result < mult\n        //  mult <= range\n        while(mult <= limit) {\n          // Postcondition: result <= range, thus no overflow\n          //\n          // limit*(brange+1)<=range+1                   def. of limit       (1)\n          // eng()-bmin<=brange                          eng() post.         (2)\n          // and mult<=limit.                            loop condition      (3)\n          // Therefore mult*(eng()-bmin+1)<=range+1      by (1),(2),(3)      (4)\n          // Therefore mult*(eng()-bmin)+mult<=range+1   rearranging (4)     (5)\n          // result<mult                                 loop invariant      (6)\n          // Therefore result+mult*(eng()-bmin)<range+1  by (5), (6)         (7)\n          //\n          // Postcondition: result < mult*(brange+1)\n          //\n          // result<mult                                 loop invariant      (1)\n          // eng()-bmin<=brange                          eng() post.         (2)\n          // Therefore result+mult*(eng()-bmin) <\n          //           mult+mult*(eng()-bmin)            by (1)              (3)\n          // Therefore result+(eng()-bmin)*mult <\n          //           mult+mult*brange                  by (2), (3)         (4)\n          // Therefore result+(eng()-bmin)*mult <\n          //           mult*(brange+1)                   by (4)\n          result += static_cast<range_type>(random::detail::subtract<base_result>()(eng(), bmin) * mult);\n\n          // equivalent to (mult * (brange+1)) == range+1, but avoids overflow.\n          if(mult * range_type(brange) == range - mult + 1) {\n              // The destination range is an integer power of\n              // the generator's range.\n              return(result);\n          }\n\n          // Postcondition: mult <= range\n          // \n          // limit*(brange+1)<=range+1                   def. of limit       (1)\n          // mult<=limit                                 loop condition      (2)\n          // Therefore mult*(brange+1)<=range+1          by (1), (2)         (3)\n          // mult*(brange+1)!=range+1                    preceding if        (4)\n          // Therefore mult*(brange+1)<range+1           by (3), (4)         (5)\n          // \n          // Postcondition: result < mult\n          //\n          // See the second postcondition on the change to result. \n          mult *= range_type(brange)+range_type(1);\n        }\n        // loop postcondition: range/mult < brange+1\n        //\n        // mult > limit                                  loop condition      (1)\n        // Suppose range/mult >= brange+1                Assumption          (2)\n        // range >= mult*(brange+1)                      by (2)              (3)\n        // range+1 > mult*(brange+1)                     by (3)              (4)\n        // range+1 > (limit+1)*(brange+1)                by (1), (4)         (5)\n        // (range+1)/(brange+1) > limit+1                by (5)              (6)\n        // limit < floor((range+1)/(brange+1))           by (6)              (7)\n        // limit==floor((range+1)/(brange+1))            def. of limit       (8)\n        // not (2)                                       reductio            (9)\n        //\n        // loop postcondition: (range/mult)*mult+(mult-1) >= range\n        //\n        // (range/mult)*mult + range%mult == range       identity            (1)\n        // range%mult < mult                             def. of %           (2)\n        // (range/mult)*mult+mult > range                by (1), (2)         (3)\n        // (range/mult)*mult+(mult-1) >= range           by (3)              (4)\n        //\n        // Note that the maximum value of result at this point is (mult-1),\n        // so after this final step, we generate numbers that can be\n        // at least as large as range.  We have to really careful to avoid\n        // overflow in this final addition and in the rejection.  Anything\n        // that overflows is larger than range and can thus be rejected.\n\n        // range/mult < brange+1  -> no endless loop\n        range_type result_increment =\n            generate_uniform_int(\n                eng,\n                static_cast<range_type>(0),\n                static_cast<range_type>(range/mult),\n                boost::mpl::true_());\n        if(std::numeric_limits<range_type>::is_bounded && ((std::numeric_limits<range_type>::max)() / mult < result_increment)) {\n          // The multiplication would overflow.  Reject immediately.\n          continue;\n        }\n        result_increment *= mult;\n        // unsigned integers are guaranteed to wrap on overflow.\n        result += result_increment;\n        if(result < result_increment) {\n          // The addition overflowed.  Reject.\n          continue;\n        }\n        if(result > range) {\n          // Too big.  Reject.\n          continue;\n        }\n        return random::detail::add<range_type, result_type>()(result, min_value);\n      }\n    } else {                   // brange > range\n      range_type bucket_size;\n      // it's safe to add 1 to range, as long as we cast it first,\n      // because we know that it is less than brange.  However,\n      // we do need to be careful not to cause overflow by adding 1\n      // to brange.\n      if(std::numeric_limits<base_unsigned>::is_bounded && (brange == (std::numeric_limits<base_unsigned>::max)())) {\n        bucket_size = brange / (range+1);\n        if(brange % (range+1) == range) {\n          ++bucket_size;\n        }\n      } else {\n        bucket_size = (brange+1) / (range+1);\n      }\n      for(;;) {\n        range_type result =\n          random::detail::subtract<base_result>()(eng(), bmin);\n        result /= bucket_size;\n        // result and range are non-negative, and result is possibly larger\n        // than range, so the cast is safe\n        if(result <= range)\n          return result + min_value;\n      }\n    }\n}\n\ntemplate<class Engine, class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>\ninline boost::multiprecision::number<Backend, ExpressionTemplates> \n   generate_uniform_int(Engine& eng, const boost::multiprecision::number<Backend, ExpressionTemplates>& min_value, const boost::multiprecision::number<Backend, ExpressionTemplates>& max_value)\n{\n    typedef typename Engine::result_type base_result;\n    typedef typename mpl::or_<boost::is_integral<base_result>, mpl::bool_<boost::multiprecision::number_category<Backend>::value == boost::multiprecision::number_kind_integer> >::type tag_type;\n    return generate_uniform_int(eng, min_value, max_value,\n        tag_type());\n}\n\n} // detail\n\n\n}} // namespaces\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n#endif\n", "meta": {"hexsha": "eebf1fbee5767ac9d59bfed6b244131b51bd7232", "size": 23043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/multiprecision/random.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "3party/boost/boost/multiprecision/random.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/multiprecision/random.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 39.1887755102, "max_line_length": 193, "alphanum_fraction": 0.5994011196, "num_tokens": 5499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836384, "lm_q2_score": 0.30735801052067535, "lm_q1q2_score": 0.19018711874311164}}
{"text": "// ----------------- BEGIN LICENSE BLOCK ---------------------------------\n//\n// Copyright (C) 2018-2019 Intel Corporation\n//\n// SPDX-License-Identifier: MIT\n//\n// ----------------- END LICENSE BLOCK -----------------------------------\n\n#include \"ad/map/maker/map_data/Lane.hpp\"\n#include <ad/map/maker/geometry/Point2d.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <unordered_set>\n#include \"ad/map/maker/map_data/MapDataStore.hpp\"\n#include \"ad/map/maker/map_data/PolyLineConversion.hpp\"\n\nnamespace ad {\nnamespace map {\nnamespace maker {\nnamespace map_data {\n\ntypedef ::boost::geometry::model::d2::point_xy<double> Boost2dPoint;\ntypedef ::boost::geometry::model::polygon<Boost2dPoint> BoostPolygon;\n\nBoostPolygon fromLane(MapDataStore const &store, Lane const &lane)\n{\n  auto const &leftBorder = store.polyLine(lane.leftBorder).mNodes;\n  auto const &rightBorder = store.polyLine(lane.rightBorder).mNodes;\n  // at first shot, we assume that both borders have the same order of points, e.g. from left to right\n  std::vector<Boost2dPoint> points;\n  for (auto const id : leftBorder)\n  {\n    auto const &p = store.point(id);\n    points.push_back({p.x, p.y});\n  }\n  for (auto it = rightBorder.rbegin(); it != rightBorder.rend(); ++it)\n  {\n    auto const &p = store.point(*it);\n    points.push_back({p.x, p.y});\n  }\n  // close polygon\n  points.push_back(points.front());\n  BoostPolygon result;\n  ::boost::geometry::assign_points(result, points);\n  // ensure that all polygons have the same orientation\n  ::boost::geometry::correct(result);\n  return result;\n}\n\nbool Lane::overlapsWithLane(MapDataStore const &store, Lane const &other) const\n{\n  if (&other == this)\n  {\n    return true;\n  }\n  auto thisP = fromLane(store, *this);\n  auto thatP = fromLane(store, other);\n  std::deque<BoostPolygon> output;\n  (void)::boost::geometry::intersection(thisP, thatP, output);\n  return (!output.empty());\n}\n\nContact Lane::checkLeftRightContact(MapDataStore const &store, Lane const &other) const\n{\n  if (&other == this)\n  {\n    return Contact::Overlap;\n  }\n\n  // check forward contact\n  auto const &thisLeftBorder = store.polyLine(leftBorder).mNodes;\n  auto const &thisRightBorder = store.polyLine(rightBorder).mNodes;\n\n  auto const &otherLeftBorder = store.polyLine(other.leftBorder).mNodes;\n  auto const &otherRightBorder = store.polyLine(other.rightBorder).mNodes;\n\n  auto const thisLeftStart = thisLeftBorder.front();\n  auto const thisRightStart = thisRightBorder.front();\n  auto const otherLeftStart = otherLeftBorder.front();\n  auto const otherRightStart = otherRightBorder.front();\n\n  auto const thisLeftEnd = thisLeftBorder.back();\n  auto const thisRightEnd = thisRightBorder.back();\n  auto const otherLeftEnd = otherLeftBorder.back();\n  auto const otherRightEnd = otherRightBorder.back();\n\n  std::unordered_set<MapDataId> startPoints;\n  std::unordered_set<MapDataId> endPoints;\n\n  startPoints.insert(thisLeftStart);\n  startPoints.insert(thisRightStart);\n  startPoints.insert(otherLeftStart);\n  startPoints.insert(otherRightStart);\n\n  endPoints.insert(thisLeftEnd);\n  endPoints.insert(thisRightEnd);\n  endPoints.insert(otherLeftEnd);\n  endPoints.insert(otherRightEnd);\n\n  // No contact means that all id points are unique and therefore we would have 4 points on each set.\n  if ((startPoints.size() < 4) && (endPoints.size() < 4))\n  {\n    if ((thisLeftStart == otherRightStart) || (thisLeftEnd == otherRightEnd))\n    {\n      return Contact::Left;\n    }\n\n    if ((thisRightStart == otherLeftStart) || (thisRightEnd == otherLeftEnd))\n    {\n      return Contact::Right;\n    }\n  }\n\n  // @TODO handle reverse contact. i.e. when there is contact with the inverted(other lane).\n\n  return Contact::None;\n}\n\nbool Lane::hasLeftContactWithLane(MapDataStore const &store, Lane const &other) const\n{\n  if (checkLeftRightContact(store, other) == Contact::Left)\n  {\n    return true;\n  }\n  return false;\n}\n\nbool Lane::hasRightContactWithLane(MapDataStore const &store, Lane const &other) const\n{\n  if (checkLeftRightContact(store, other) == Contact::Right)\n  {\n    return true;\n  }\n  return false;\n}\n\nvoid Lane::invertLaneDirection(MapDataStore &store, bool invertBorderPolylines)\n{\n  if (invertBorderPolylines)\n  {\n    auto &leftBorderPolyLine = store.polyLine(leftBorder);\n    auto &rightBorderPolyLine = store.polyLine(rightBorder);\n    std::reverse(leftBorderPolyLine.mNodes.begin(), leftBorderPolyLine.mNodes.end());\n    std::reverse(rightBorderPolyLine.mNodes.begin(), rightBorderPolyLine.mNodes.end());\n  }\n\n  if (drivingDirection == DrivingDirection::Forward)\n  {\n    drivingDirection = DrivingDirection::Backward;\n  }\n  else if (drivingDirection == DrivingDirection::Backward)\n  {\n    drivingDirection = DrivingDirection::Forward;\n  }\n\n  std::swap(leftBorder, rightBorder);\n  std::swap(leftNeighbor, rightNeighbor);\n  std::swap(predecessors, successors);\n}\n\ngeometry::Point2d Lane::findNearestPoint(MapDataStore const &store, geometry::Point2d const &point) const\n{\n  if (leftBorder == InvalidId || rightBorder == InvalidId)\n  {\n    return geometry::Point2d{0.0, 0.0};\n  }\n  auto leftPoint = findNearestPointOnLeftBorder(store, point);\n  auto rightPoint = findNearestPointOnRightBorder(store, point);\n  double leftDistance = leftPoint.squaredDistance(point);\n  double rightDistance = rightPoint.squaredDistance(point);\n\n  if (leftDistance < rightDistance)\n  {\n    return leftPoint;\n  }\n  else\n  {\n    return rightPoint;\n  }\n}\n\ngeometry::Point2d Lane::findNearestPointOnLeftBorder(MapDataStore const &store, geometry::Point2d const &point) const\n{\n  if (!store.hasPolyLine(leftBorder))\n  {\n    return geometry::Point2d{0.0, 0.0};\n  }\n  auto borderPolyLine = store.polyLine(leftBorder);\n  auto geometry = polylineToGeometry(store, borderPolyLine);\n  return geometry.findNearestPoint(point);\n}\n\ngeometry::Point2d Lane::findNearestPointOnRightBorder(MapDataStore const &store, geometry::Point2d const &point) const\n{\n  if (!store.hasPolyLine(rightBorder))\n  {\n    return geometry::Point2d{0.0, 0.0};\n  }\n  auto borderPolyLine = store.polyLine(rightBorder);\n  auto geometry = polylineToGeometry(store, borderPolyLine);\n  return geometry.findNearestPoint(point);\n}\n\n} // namespace map_data\n} // namespace maker\n} // namespace map\n} // namespace ad\n", "meta": {"hexsha": "5e6b58ebd655e12205f8d5d19115c0fc1009d373", "size": 6270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/map_maker/map_data/src/Lane.cpp", "max_stars_repo_name": "seowwj/map", "max_stars_repo_head_hexsha": "2afacd50e1b732395c64b1884ccfaeeca0040ee7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2019-12-19T20:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:20:51.000Z", "max_issues_repo_path": "tools/map_maker/map_data/src/Lane.cpp", "max_issues_repo_name": "seowwj/map", "max_issues_repo_head_hexsha": "2afacd50e1b732395c64b1884ccfaeeca0040ee7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54.0, "max_issues_repo_issues_event_min_datetime": "2020-04-05T05:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T18:42:33.000Z", "max_forks_repo_path": "tools/map_maker/map_data/src/Lane.cpp", "max_forks_repo_name": "seowwj/map", "max_forks_repo_head_hexsha": "2afacd50e1b732395c64b1884ccfaeeca0040ee7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2019-12-20T07:37:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:06:16.000Z", "avg_line_length": 30.1442307692, "max_line_length": 118, "alphanum_fraction": 0.7172248804, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.19014007724985102}}
{"text": "#include <Eigen/Dense>\n#include <VirtualRobot/MathTools.h>\n#include <VirtualRobot/Nodes/ForceTorqueSensor.h>\n#include <SimDynamics/SimDynamics.h>\n\n#include <boost/assert.hpp>\n#include <boost/make_shared.hpp>\n\n#include <unordered_map>\n\n#include \"kajita/FootForceController.h\"\n#include \"kajita/FootTorqueController.h\"\n#include \"kajita/ZMPTrackingController.h\"\n\n#include \"stabilizer/kajita/ZMPDistributor.h\"\n#include \"stabilizer/KajitaStabilizer.h\"\n\n#include \"controller/PostureController.h\"\n\nnamespace Bipedal\n{\n\n/*\n * These controller needs a trajectory with the following control features:\n *\n * Poses:\n *  - chest pose\n *  - pelvis pose\n *  - left foot pose\n *  - right foot pose\n *\n * Values:\n *  - support phase\n *\n * Points:\n *  - Reference ZMP\n */\nKajitaStabilizer::KajitaStabilizer(const VirtualRobot::RobotPtr& robot,\n                                   const VirtualRobot::RobotNodePtr& chest,\n                                   const VirtualRobot::RobotNodePtr& leftFoot,\n                                   const VirtualRobot::RobotNodePtr& rightFoot,\n                                   const VirtualRobot::RobotNodePtr& leftFootBody,\n                                   const VirtualRobot::RobotNodePtr& rightFootBody,\n                                   const VirtualRobot::RobotNodePtr& leftAnkleBody,\n                                   const VirtualRobot::RobotNodePtr& rightAnkleBody,\n                                   const VirtualRobot::RobotNodePtr& pelvis,\n                                   const VirtualRobot::ForceTorqueSensorPtr& leftAnkleSensorX,\n                                   const VirtualRobot::ForceTorqueSensorPtr& rightAnkleSensorX,\n                                   const VirtualRobot::ForceTorqueSensorPtr& leftAnkleSensorY,\n                                   const VirtualRobot::ForceTorqueSensorPtr& rightAnkleSensorY)\n/* Nodes */\n: chest(chest)\n, leftFoot(leftFoot)\n, rightFoot(rightFoot)\n, leftFootBody(leftFootBody)\n, rightFootBody(rightFootBody)\n, pelvis(pelvis)\n, leftAnkleSensorX(leftAnkleSensorX)\n, rightAnkleSensorX(rightAnkleSensorX)\n, leftAnkleSensorY(leftAnkleSensorY)\n, rightAnkleSensorY(rightAnkleSensorY)\n/* Controllers */\n, chestPostureController(new TwoDOFPostureController(40, 5, 80, 5))\n, forceDistributor(new ZMPDistributor(robot->getMass(),\n                                        Eigen::Vector3f(0.0, 0.0, -9.81),\n                                        leftFootBody, rightFootBody, leftFoot, rightFoot))\n, footTorqueController(new FootTorqueController())\n// gains calculated with utils/zmp_gains.ipynote\n, zmpTrackingController(new ZMPTrackingController(Eigen::Vector3f(-0.09150757, -0.02709391, -0.33112892)))\n/* Adapted frames */\n, chestPose(Eigen::Matrix4f::Identity())\n, pelvisPose(Eigen::Matrix4f::Identity())\n, leftFootPose(Eigen::Matrix4f::Identity())\n, rightFootPose(Eigen::Matrix4f::Identity())\n, zmpPosition(Eigen::Vector3f::Zero())\n, comPosition(Eigen::Vector3f::Zero())\n, comPositionRef(Eigen::Vector3f::Zero())\n, zmpPositionRef(Eigen::Vector3f::Zero())\n, ft({Eigen::Vector3f::Zero(), Eigen::Vector3f::Zero(), Eigen::Vector3f::Zero(), Eigen::Vector3f::Zero()})\n{\n    BOOST_ASSERT(robot);\n    BOOST_ASSERT(chest);\n    BOOST_ASSERT(leftFoot);\n    BOOST_ASSERT(rightFoot);\n    BOOST_ASSERT(leftFootBody);\n    BOOST_ASSERT(rightFootBody);\n    BOOST_ASSERT(leftAnkleBody);\n    BOOST_ASSERT(rightAnkleBody);\n    BOOST_ASSERT(pelvis);\n    BOOST_ASSERT(leftAnkleSensorX);\n    BOOST_ASSERT(rightAnkleSensorX);\n    BOOST_ASSERT(leftAnkleSensorY);\n    BOOST_ASSERT(rightAnkleSensorY);\n\n    // FIXME Make node name configurable\n    Eigen::Vector3f leftHipPos  = robot->getRobotNode(\"LeftLeg_Joint2\")->getGlobalPose().block(0, 3, 3, 1);\n    Eigen::Vector3f rightHipPos = robot->getRobotNode(\"RightLeg_Joint2\")->getGlobalPose().block(0, 3, 3, 1);\n    double hipJointDistance = (leftHipPos - rightHipPos).norm();\n    footForceController = FootForceControllerPtr(new FootForceController(hipJointDistance));\n\n    leftAnkleOffset = (leftFoot->getGlobalPose().inverse() * leftAnkleBody->getGlobalPose()).block(0,3,3,1);\n    // project to foot sole\n    leftAnkleOffset.z() = 0;\n    rightAnkleOffset = (rightFoot->getGlobalPose().inverse() * rightAnkleBody->getGlobalPose()).block(0,3,3,1);\n    // project to foot sole\n    rightAnkleOffset.z() = 0;\n}\n\nvoid KajitaStabilizer::update(float dt,\n                              const Eigen::Vector3f& comActualWorld,\n                              const Eigen::Vector3f& comVelocityActualWorld,\n                              const Eigen::Vector3f& zmpActualWorld,\n                              Bipedal::SupportPhase phase,\n                              const Eigen::Matrix4f& chestPoseRefWorld,\n                              const Eigen::Matrix4f& pelvisPoseRefWorld,\n                              const Eigen::Matrix4f& leftFootPoseRefWorld,\n                              const Eigen::Matrix4f& rightFootPoseRefWorld,\n                              const Eigen::Vector3f& comRefGroundFrame,\n                              const Eigen::Vector3f& comVelocityRefGroundFrame,\n                              const Eigen::Vector3f& zmpRefGroundFrame)\n{\n    Eigen::Matrix4f leftToWorld  = leftFoot->getGlobalPose();\n    Eigen::Matrix4f rightToWorld = rightFoot->getGlobalPose();\n    auto groundFrame = Bipedal::computeGroundFrame(leftToWorld, rightToWorld, phase);\n    auto worldToGroundFrame = groundFrame.inverse();\n\n    // Apply step adation frame to reference values\n    chestPoseRef     = chestPoseRefWorld;\n    pelvisPoseRef    = pelvisPoseRefWorld;\n    leftFootPoseRef  = leftFootPoseRefWorld;\n    rightFootPoseRef = rightFootPoseRefWorld;\n    comPositionRef   = comRefGroundFrame;\n    zmpPositionRef   = zmpRefGroundFrame;\n\n    // We never change the reference\n    comPosition = comPositionRef;\n\n    // convert actual values to ground frame\n    Eigen::Vector3f zmpActualGroundFrame = VirtualRobot::MathTools::transformPosition(zmpActualWorld, worldToGroundFrame);\n    Eigen::Vector3f comActualGroundFrame = VirtualRobot::MathTools::transformPosition(comActualWorld, worldToGroundFrame);\n    Eigen::Vector3f comVelocityActualGroundFrame = worldToGroundFrame.block(0,0,3,3) * comVelocityActualWorld;\n\n    // Adapt the reference ZMP to stabilize\n    zmpPosition = Eigen::Vector3f::Zero();\n    zmpPosition.head(2) = zmpTrackingController->computeAdaptedZMP(zmpRefGroundFrame.head(2),\n                                                                   comRefGroundFrame.head(2),\n                                                                   comVelocityRefGroundFrame.head(2),\n                                                                   zmpActualGroundFrame.head(2),\n                                                                   comActualGroundFrame.head(2),\n                                                                   comVelocityActualGroundFrame.head(2));\n\n    // Distribute adapted ZMP to yielf reference force/torques\n    ft = forceDistributor->distributeZMP(\n        leftAnkleOffset,\n        rightAnkleOffset,\n        leftToWorld,\n        rightToWorld,\n        zmpPosition,\n        phase\n    );\n\n    Eigen::Matrix3f worldToLeft  = leftToWorld.block(0, 0, 3, 3).inverse();\n    Eigen::Matrix3f worldToRight = rightToWorld.block(0, 0, 3, 3).inverse();\n    Eigen::Vector3f leftTorqueLocal  = worldToLeft * (leftAnkleSensorX->getAxisTorque()  + leftAnkleSensorY->getAxisTorque());\n    Eigen::Vector3f rightTorqueLocal = worldToRight * (rightAnkleSensorX->getAxisTorque() + rightAnkleSensorY->getAxisTorque());\n\n    leftFootPose  = Eigen::Matrix4f::Identity();\n    rightFootPose = Eigen::Matrix4f::Identity();\n    footTorqueController->correctFootOrientation(\n        leftFootPoseRef,\n        rightFootPoseRef,\n        ft.leftTorque,\n        ft.rightTorque,\n        leftTorqueLocal,\n        rightTorqueLocal,\n        leftFootPose,\n        rightFootPose\n    );\n\n/* FIXME RobotConfig needs a flag for deciding what to use\n    pelvisPose = footForceController->correctPelvisOrientation(\n        pelvisPoseRef,\n        ft.leftForce,\n        ft.rightForce,\n        -leftAnkleSensorX->getForce(),\n        rightAnkleSensorX->getForce()\n    );\n*/\n    pelvisPose = pelvisPoseRef;\n    footForceController->correctFootHeight(\n        ft.leftForce,\n        ft.rightForce,\n        -leftAnkleSensorX->getForce(),\n        rightAnkleSensorX->getForce(),\n        leftFootPose,\n        rightFootPose\n    );\n\n    chestPose = chestPoseRef * chestPostureController->correctPosture(\n        chestPoseRef,\n        chest->getGlobalPose()\n    );\n}\n\nstd::unordered_map<std::string, DampeningController*> KajitaStabilizer::getControllers()\n{\n    std::unordered_map<std::string, DampeningController*> controllers;\n\n    controllers[\"LeftAnkle_TorqueX\"]  = &footTorqueController->leftPhiDC;\n    controllers[\"LeftAnkle_TorqueY\"]  = &footTorqueController->leftThetaDC;\n    controllers[\"RightAnkle_TorqueX\"] = &footTorqueController->rightPhiDC;\n    controllers[\"RightAnkle_TorqueY\"] = &footTorqueController->rightThetaDC;\n    controllers[\"Chest_Roll\"]         = &chestPostureController->phiDC;\n    controllers[\"Chest_Pitch\"]        = &chestPostureController->thetaDC;\n    controllers[\"Pelvis_Pitch\"]       = &footForceController->zCtrlDC;\n\n    return controllers;\n}\n\n}\n\n", "meta": {"hexsha": "618275ba97ffad32032053d00b31ab7d5130c39e", "size": 9245, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stabilizer/KajitaStabilizer.cpp", "max_stars_repo_name": "TheMarex/libbipedal", "max_stars_repo_head_hexsha": "803f505425fd0bf94620f7efe7ceaa39f4fc8201", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-06-10T22:02:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T19:16:16.000Z", "max_issues_repo_path": "src/stabilizer/KajitaStabilizer.cpp", "max_issues_repo_name": "TheMarex/libbipedal", "max_issues_repo_head_hexsha": "803f505425fd0bf94620f7efe7ceaa39f4fc8201", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-09-29T01:31:56.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-22T02:01:08.000Z", "max_forks_repo_path": "src/stabilizer/KajitaStabilizer.cpp", "max_forks_repo_name": "TheMarex/libbipedal", "max_forks_repo_head_hexsha": "803f505425fd0bf94620f7efe7ceaa39f4fc8201", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-09-29T09:03:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T22:33:12.000Z", "avg_line_length": 41.6441441441, "max_line_length": 128, "alphanum_fraction": 0.6524607896, "num_tokens": 2236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.19005902714255096}}
{"text": "/**\n * @project identt\n * @file src/store/StoreBase.cc\n * @author  S Roychowdhury <sroycode AT gmail DOT com>\n * @version 1.0.0\n *\n * @section LICENSE\n *\n * Copyright (c) 2017 S Roychowdhury.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * 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, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n *  StoreBase.cc : Store Base Implementation\n *\n */\n#include <iomanip>\n#include <sstream>\n#include <cmath>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <store/StoreBase.hpp>\n\n#define IDENTT_MACRO_HEX(A)       std::setbase(16) << std::setfill ('0') << std::setw ( A )\n#define IDENTT_MACRO_STR(A)       std::setfill (' ') << std::setw ( A )\n\n#define IDENTT_FMT_ID_KEY(A)      IDENTT_MACRO_HEX(IDENTT_KEYID_LEN) << A\n\n#ifdef IDENTT_USE_BASE80_KEYS\n#define IDENTT_FMT_NODE_ONLY(A)   IDENTT_MACRO_STR(IDENTT_NODE_LEN) << Base80String<uint64_t,IDENTT_NODE_LEN>(A)\n#else\n#define IDENTT_FMT_NODE_ONLY(A)   IDENTT_MACRO_HEX(IDENTT_NODE_LEN) << A\n#endif\n\n#define IDENTT_FMT_NODE_KEY(A,B)  IDENTT_FMT_ID_KEY(A) << IDENTT_FMT_NODE_ONLY(B)\n\n// #define IDENTT_FMT_SEP \"\\x1E\"\n#define IDENTT_FMT_SEP \":\"\n/* UINT is defined here so can be changed independent of node if needed */\n#define IDENTT_FMT_UINT_ONLY(A)    IDENTT_FMT_NODE_ONLY(A)\n/* STR is defined here so can be changed to hash in future if needed */\n#define IDENTT_FMT_STRN_ONLY(A)    A\n/* SINT is defined here so can be changed independent of node if needed */\n#define IDENTT_FMT_SINT_ONLY(A)   IDENTT_MACRO_HEX(IDENTT_NODE_LEN) << A\n\n#define IDENTT_FMT_UINT_KEY(A,B)   IDENTT_FMT_ID_KEY(A) << IDENTT_FMT_UINT_ONLY(B)\n#define IDENTT_FMT_STRN_KEY(A,B)   IDENTT_FMT_ID_KEY(A) << IDENTT_FMT_STRN_ONLY(B)\n\n\n/**\n* Base80String : Get limited char string\n*  : someone needs to get a faster way for this to be usable\n*  refer http://www.hackersdelight.org/divcMore.pdf\n*\n*/\ntemplate<typename T, size_t N>\ninline std::string Base80String(T dividend)\n{\n\tconst static char usechars[] = \"()+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz\";\n\tT modulo=0;\n\tstd::string out(N,' '); // N  (char 32 space)\n\tsize_t c=N;\n\twhile (dividend > 0 && c>0) {\n\t\tmodulo = (dividend - 1) % 80;\n\t\tdividend = (T)((dividend - modulo) / 80);\n\t\tout[--c] = usechars[modulo];\n\t}\n\treturn out;\n}\n\n/**\n* Str2Uint64 : Convert the first 8 characters of a string to 64 bit\n*\n* @param str\n*   std::string& string to change\n*\n* @return\n*   uint64_t hash\n*/\ninline uint64_t Str2Uint64 (std::string str)\n{\n\tboost::algorithm::to_upper(str);\n\tuint64_t t=0;\n\tsize_t counter=8;\n\tfor (char& i : str) {\n\t\tt+= std::pow(i,counter);\n\t\tif (--counter==0) break;\n\t}\n\treturn t;\n}\n\n/**\n* EncodeKeyType : make prefix key with keytype\n*\n*/\nstd::string identt::store::StoreBase::EncodeKeyType(identt::store::KeyTypeE keytype)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_ID_KEY( (unsigned short)keytype );\n\treturn ss.str();\n}\n\n/**\n* EncodePrimaryKey : make primary key with id only\n*\n*/\nstd::string identt::store::StoreBase::EncodePrimaryKey(identt::store::KeyTypeE keytype, ::google::protobuf::uint64 id)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_NODE_KEY( (unsigned short)keytype, id );\n\treturn ss.str();\n}\n\n/**\n* DecodePrimaryKey : get keytype and id from primary key\n*\n*/\nstd::pair<identt::store::KeyTypeE,uint64_t> identt::store::StoreBase::DecodePrimaryKey (std::string& key)\n{\n\n\tif (key.length() < ( IDENTT_KEYID_LEN + IDENTT_NODE_LEN ))\n\t\tthrow identt::BadDataException(\"Invalid Key probed\");\n\tidentt::store::KeyTypeE x = (identt::store::KeyTypeE) std::stoull(key.substr(0,IDENTT_KEYID_LEN),0,16);\n\tuint64_t y = std::stoull(key.substr(IDENTT_KEYID_LEN,IDENTT_NODE_LEN),0,16);\n\treturn std::make_pair(x,y);\n}\n\nnamespace identt {\nnamespace store {\n\n/** 1 value */\n\n/**\n* EncodeSecondaryKey : make secondary key with uint64_t\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, uint64_t key)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_UINT_KEY( (unsigned short)keytype, key );\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with std::string\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, std::string key)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_STRN_KEY( (unsigned short)keytype, key );\n\treturn ss.str();\n}\n\n/** 2 value */\n\n/**\n* EncodeSecondaryKey : make secondary key with two keys uint64_t , uint64_t\n*  : u-u unique , u non unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, uint64_t key1, uint64_t key2)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_UINT_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key2);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with two keys uint64_t , std::string\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, uint64_t key1, std::string key2)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_UINT_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key2);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with two keys std::string , uint64_t\n*  : always unique\n*  : s-u unique , s non unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, std::string key1, uint64_t key2)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_STRN_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key2);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with two keys std::string , std::string\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, std::string key1, std::string key2)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_STRN_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key2);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with two keys uint64_t, int32_t\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, uint64_t key1, int32_t key2)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_UINT_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_SINT_ONLY(key2);\n\treturn ss.str();\n}\n\n/** 3 value */\n\n/**\n* EncodeSecondaryKey : make secondary key with three keys uint64_t , uint64_t , uint64_t\n*  : u-u-u unique , u-u non unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, uint64_t key1, uint64_t key2, uint64_t key3)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_UINT_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key2)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key3);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with three keys uint64_t , uint64_t , std::string\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, uint64_t key1, uint64_t key2, std::string key3)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_UINT_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key2)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key3);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with three keys uint64_t , std::string , uint64_t\n*  : always unique\n*  : u-s-u unique , u-s non unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, uint64_t key1, std::string key2, uint64_t key3)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_UINT_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key2)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key3);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with three keys uint64_t , std::string , std::string\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, uint64_t key1, std::string key2, std::string key3)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_UINT_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key2)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key3);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with three keys std::string , uint64_t , uint64_t\n*  : s-u-u unique , s-u non unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, std::string key1, uint64_t key2, uint64_t key3)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_STRN_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key2)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key3);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with three keys std::string , uint64_t , std::string\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, std::string key1, uint64_t key2, std::string key3)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_STRN_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key2)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key3);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with three keys std::string , std::string , uint64_t\n*  : s-s-u unique , s-s non unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, std::string key1, std::string key2, uint64_t key3)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_STRN_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key2)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_UINT_ONLY(key3);\n\treturn ss.str();\n}\n\n/**\n* EncodeSecondaryKey : make secondary key with three keys std::string , std::string , std::string\n*  : always unique\n*\n*/\ntemplate<> std::string StoreBase::EncodeSecondaryKey (KeyTypeE keytype, std::string key1, std::string key2, std::string key3)\n{\n\tstd::stringstream ss;\n\tss << IDENTT_FMT_STRN_KEY( (unsigned short)keytype, key1)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key2)\n\t   << IDENTT_FMT_SEP << IDENTT_FMT_STRN_ONLY(key3);\n\treturn ss.str();\n}\n\n\n} // namespace store\n} // namespace identt\n", "meta": {"hexsha": "71d21671a6a296021b44fd41d7e8b3588f10e528", "size": 10937, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/store/StoreBase.cc", "max_stars_repo_name": "sroycode/identt", "max_stars_repo_head_hexsha": "40bffa3d8db69c810c4d6707b9eb32f983539c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-20T09:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-04T09:43:00.000Z", "max_issues_repo_path": "src/store/StoreBase.cc", "max_issues_repo_name": "sroycode/identt", "max_issues_repo_head_hexsha": "40bffa3d8db69c810c4d6707b9eb32f983539c99", "max_issues_repo_licenses": ["MIT"], "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/store/StoreBase.cc", "max_forks_repo_name": "sroycode/identt", "max_forks_repo_head_hexsha": "40bffa3d8db69c810c4d6707b9eb32f983539c99", "max_forks_repo_licenses": ["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.3805555556, "max_line_length": 125, "alphanum_fraction": 0.7225016001, "num_tokens": 3027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.33807713748839197, "lm_q1q2_score": 0.19005901722287113}}
{"text": "/**\n * Copyright Soramitsu Co., Ltd. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n#ifndef KAGOME_RUNTIME_BINARYEN_WASM_MEMORY_IMPL_HPP\n#define KAGOME_RUNTIME_BINARYEN_WASM_MEMORY_IMPL_HPP\n\n#include <binaryen/shell-interface.h>\n\n#include <array>\n#include <cstring>  // for std::memset in gcc\n#include <memory>\n#include <unordered_map>\n\n#include <boost/optional.hpp>\n\n#include \"common/literals.hpp\"\n#include \"log/logger.hpp\"\n#include \"primitives/math.hpp\"\n#include \"runtime/wasm_memory.hpp\"\n\nnamespace kagome::runtime::binaryen {\n\n  using namespace kagome::common::literals;\n\n  // Alignment for pointers, same with substrate:\n  // https://github.com/paritytech/substrate/blob/743981a083f244a090b40ccfb5ce902199b55334/primitives/allocator/src/freeing_bump.rs#L56\n  inline const uint8_t kAlignment = sizeof(size_t);\n  inline const size_t kInitialMemorySize = 2_MB;  // 2Mb\n  inline const size_t kDefaultHeapBase = 1_MB;    // 1Mb\n\n  /**\n   * Obtain closest multiple of kAllignment that is greater or equal to given\n   * number\n   * @tparam T T type of number\n   * @param t given number\n   * @return closest multiple\n   */\n  template <typename T>\n  inline constexpr T roundUpAlign(T t) {\n    return math::roundUp<kAlignment>(t);\n  }\n\n  static_assert(roundUpAlign(kDefaultHeapBase) == kDefaultHeapBase,\n                \"Heap base must be aligned\");\n  static_assert(kDefaultHeapBase < kInitialMemorySize,\n                \"Heap base must be in border of memory\");\n\n  /**\n   * Memory implementation for wasm environment\n   * Most code is taken from Binaryen's implementation here:\n   * https://github.com/WebAssembly/binaryen/blob/master/src/shell-interface.h#L37\n   * @note Memory size of this implementation is at least of the size of one\n   * wasm page (4096 bytes)\n   */\n  class WasmMemoryImpl final : public WasmMemory {\n   public:\n    explicit WasmMemoryImpl(wasm::ShellExternalInterface::Memory *memory);\n    WasmMemoryImpl(const WasmMemoryImpl &copy) = delete;\n    WasmMemoryImpl &operator=(const WasmMemoryImpl &copy) = delete;\n    WasmMemoryImpl(WasmMemoryImpl &&move) = delete;\n    WasmMemoryImpl &operator=(WasmMemoryImpl &&move) = delete;\n    ~WasmMemoryImpl() override = default;\n\n    void setHeapBase(WasmSize initial_offset) override;\n\n    void reset() override;\n\n    WasmSize size() const override;\n    void resize(WasmSize newSize) override;\n\n    WasmPointer allocate(WasmSize size) override;\n    boost::optional<WasmSize> deallocate(WasmPointer ptr) override;\n\n    int8_t load8s(WasmPointer addr) const override;\n    uint8_t load8u(WasmPointer addr) const override;\n    int16_t load16s(WasmPointer addr) const override;\n    uint16_t load16u(WasmPointer addr) const override;\n    int32_t load32s(WasmPointer addr) const override;\n    uint32_t load32u(WasmPointer addr) const override;\n    int64_t load64s(WasmPointer addr) const override;\n    uint64_t load64u(WasmPointer addr) const override;\n    std::array<uint8_t, 16> load128(WasmPointer addr) const override;\n    common::Buffer loadN(kagome::runtime::WasmPointer addr,\n                         kagome::runtime::WasmSize n) const override;\n    std::string loadStr(kagome::runtime::WasmPointer addr,\n                        kagome::runtime::WasmSize length) const override;\n\n    void store8(WasmPointer addr, int8_t value) override;\n    void store16(WasmPointer addr, int16_t value) override;\n    void store32(WasmPointer addr, int32_t value) override;\n    void store64(WasmPointer addr, int64_t value) override;\n    void store128(WasmPointer addr,\n                  const std::array<uint8_t, 16> &value) override;\n    void storeBuffer(kagome::runtime::WasmPointer addr,\n                     gsl::span<const uint8_t> value) override;\n\n    WasmSpan storeBuffer(gsl::span<const uint8_t> value) override;\n\n    /// following methods are needed mostly for testing purposes\n    boost::optional<WasmSize> getDeallocatedChunkSize(WasmPointer ptr) const;\n    boost::optional<WasmSize> getAllocatedChunkSize(WasmPointer ptr) const;\n    size_t getAllocatedChunksNum() const;\n    size_t getDeallocatedChunksNum() const;\n\n   private:\n    wasm::ShellExternalInterface::Memory *memory_;\n    WasmSize size_;\n\n    // Heap base. Offset is reset to it on reset()\n    WasmPointer heap_base_;\n\n    // Offset on the tail of the last allocated MemoryImpl chunk\n    WasmPointer offset_;\n\n    log::Logger logger_;\n\n    // map containing addresses of allocated MemoryImpl chunks\n    std::unordered_map<WasmPointer, WasmSize> allocated_;\n\n    // map containing addresses to the deallocated MemoryImpl chunks\n    std::map<WasmPointer, WasmSize> deallocated_;\n\n    template <typename T>\n    static bool aligned(const char *address) {\n      static_assert(!(sizeof(T) & (sizeof(T) - 1)), \"must be a power of 2\");\n      // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)\n      return 0 == (reinterpret_cast<uintptr_t>(address) & (sizeof(T) - 1));\n    }\n\n    /**\n     * Finds memory segment of given size among deallocated pieces of memory\n     * and allocates a memory there\n     * @param size of target memory\n     * @return address of memory of given size, or -1 if it is impossible to\n     * allocate this amount of memory\n     */\n    WasmPointer freealloc(WasmSize size);\n\n    /**\n     * Resize memory and allocate memory segment of given size\n     * @param size memory size to be allocated\n     * @return pointer to the allocated memory @or 0 if it is impossible to\n     * allocate this amount of memory\n     */\n    WasmPointer growAlloc(WasmSize size);\n  };\n}  // namespace kagome::runtime::binaryen\n\n#endif  // KAGOME_RUNTIME_BINARYEN_WASM_MEMORY_IMPL_HPP\n", "meta": {"hexsha": "b89bfd4c1351ae260075a4285574c8a346592971", "size": 5625, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/runtime/binaryen/wasm_memory_impl.hpp", "max_stars_repo_name": "igor-egorov/kagome", "max_stars_repo_head_hexsha": "b2a77061791aa7c1eea174246ddc02ef5be1b605", "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": "core/runtime/binaryen/wasm_memory_impl.hpp", "max_issues_repo_name": "igor-egorov/kagome", "max_issues_repo_head_hexsha": "b2a77061791aa7c1eea174246ddc02ef5be1b605", "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": "core/runtime/binaryen/wasm_memory_impl.hpp", "max_forks_repo_name": "igor-egorov/kagome", "max_forks_repo_head_hexsha": "b2a77061791aa7c1eea174246ddc02ef5be1b605", "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.0065789474, "max_line_length": 135, "alphanum_fraction": 0.7207111111, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.19005901468418382}}
{"text": "// Boost.Geometry Index\n//\n// R-tree inserting visitor implementation\n//\n// Copyright (c) 2011-2015 Adam Wulkiewicz, Lodz, Poland.\n//\n// This file was modified by Oracle on 2019-2020.\n// Modifications copyright (c) 2019-2020 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_INDEX_DETAIL_RTREE_VISITORS_INSERT_HPP\n#define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_INSERT_HPP\n\n#ifdef BOOST_GEOMETRY_INDEX_EXPERIMENTAL_ENLARGE_BY_EPSILON\n#include <type_traits>\n#endif\n\n#include <boost/geometry/algorithms/detail/expand_by_epsilon.hpp>\n#include <boost/geometry/core/static_assert.hpp>\n#include <boost/geometry/util/condition.hpp>\n\n#include <boost/geometry/index/detail/algorithms/bounds.hpp>\n#include <boost/geometry/index/detail/algorithms/content.hpp>\n\n#include <boost/geometry/index/detail/rtree/node/subtree_destroyer.hpp>\n\nnamespace boost { namespace geometry { namespace index {\n\nnamespace detail { namespace rtree {\n\n// Default choose_next_node\ntemplate\n<\n    typename MembersHolder,\n    typename ChooseNextNodeTag = typename MembersHolder::options_type::choose_next_node_tag\n>\nclass choose_next_node;\n\ntemplate <typename MembersHolder>\nclass choose_next_node<MembersHolder, choose_by_content_diff_tag>\n{\npublic:\n    typedef typename MembersHolder::box_type box_type;\n    typedef typename MembersHolder::parameters_type parameters_type;\n\n    typedef typename MembersHolder::node node;\n    typedef typename MembersHolder::internal_node internal_node;\n    typedef typename MembersHolder::leaf leaf;\n\n    typedef typename rtree::elements_type<internal_node>::type children_type;\n\n    typedef typename index::detail::default_content_result<box_type>::type content_type;\n\n    template <typename Indexable>\n    static inline size_t apply(internal_node & n,\n                               Indexable const& indexable,\n                               parameters_type const& parameters,\n                               size_t /*node_relative_level*/)\n    {\n        children_type & children = rtree::elements(n);\n\n        BOOST_GEOMETRY_INDEX_ASSERT(!children.empty(), \"can't choose the next node if children are empty\");\n\n        size_t children_count = children.size();\n\n        // choose index with smallest content change or smallest content\n        size_t choosen_index = 0;\n        content_type smallest_content_diff = (std::numeric_limits<content_type>::max)();\n        content_type smallest_content = (std::numeric_limits<content_type>::max)();\n\n        // caculate areas and areas of all nodes' boxes\n        for ( size_t i = 0 ; i < children_count ; ++i )\n        {\n            typedef typename children_type::value_type child_type;\n            child_type const& ch_i = children[i];\n\n            // expanded child node's box\n            box_type box_exp(ch_i.first);\n            index::detail::expand(box_exp, indexable,\n                                  index::detail::get_strategy(parameters));\n\n            // areas difference\n            content_type content = index::detail::content(box_exp);\n            content_type content_diff = content - index::detail::content(ch_i.first);\n\n            // update the result\n            if ( content_diff < smallest_content_diff ||\n                ( content_diff == smallest_content_diff && content < smallest_content ) )\n            {\n                smallest_content_diff = content_diff;\n                smallest_content = content;\n                choosen_index = i;\n            }\n        }\n\n        return choosen_index;\n    }\n};\n\n// ----------------------------------------------------------------------- //\n\n// Not implemented here\ntemplate\n<\n    typename MembersHolder,\n    typename RedistributeTag = typename MembersHolder::options_type::redistribute_tag\n>\nstruct redistribute_elements\n{\n    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\n        \"Not implemented for this RedistributeTag type.\",\n        MembersHolder, RedistributeTag);\n};\n\n// ----------------------------------------------------------------------- //\n\n// Split algorithm\ntemplate\n<\n    typename MembersHolder,\n    typename SplitTag = typename MembersHolder::options_type::split_tag\n>\nclass split\n{\n    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\n        \"Not implemented for this SplitTag type.\",\n        MembersHolder, SplitTag);\n};\n\n// Default split algorithm\ntemplate <typename MembersHolder>\nclass split<MembersHolder, split_default_tag>\n{\nprotected:\n    typedef typename MembersHolder::parameters_type parameters_type;\n    typedef typename MembersHolder::box_type box_type;\n    typedef typename MembersHolder::translator_type translator_type;\n    typedef typename MembersHolder::allocators_type allocators_type;\n    typedef typename MembersHolder::size_type size_type;\n\n    typedef typename MembersHolder::node node;\n    typedef typename MembersHolder::internal_node internal_node;\n    typedef typename MembersHolder::leaf leaf;\n\n    typedef typename MembersHolder::node_pointer node_pointer;\n\npublic:\n    typedef index::detail::varray<\n        typename rtree::elements_type<internal_node>::type::value_type,\n        1\n    > nodes_container_type;\n\n    template <typename Node>\n    static inline void apply(nodes_container_type & additional_nodes,\n                             Node & n,\n                             box_type & n_box,\n                             parameters_type const& parameters,\n                             translator_type const& translator,\n                             allocators_type & allocators)\n    {\n        // TODO - consider creating nodes always with sufficient memory allocated\n\n        // create additional node, use auto destroyer for automatic destruction on exception\n        node_pointer n2_ptr = rtree::create_node<allocators_type, Node>::apply(allocators);                  // MAY THROW, STRONG (N: alloc)\n        // create reference to the newly created node\n        Node & n2 = rtree::get<Node>(*n2_ptr);\n\n        BOOST_TRY\n        {\n            // NOTE: thread-safety\n            // After throwing an exception by redistribute_elements the original node may be not changed or\n            // both nodes may be empty. In both cases the tree won't be valid r-tree.\n            // The alternative is to create 2 (or more) additional nodes here and store backup info\n            // in the original node, then, if exception was thrown, the node would always have more than max\n            // elements.\n            // The alternative is to use moving semantics in the implementations of redistribute_elements,\n            // it will be possible to throw from boost::move() in the case of e.g. static size nodes.\n\n            // redistribute elements\n            box_type box2;\n            redistribute_elements<MembersHolder>\n                ::apply(n, n2, n_box, box2, parameters, translator, allocators);                                   // MAY THROW (V, E: alloc, copy, copy)\n\n            // check numbers of elements\n            BOOST_GEOMETRY_INDEX_ASSERT(parameters.get_min_elements() <= rtree::elements(n).size() &&\n                rtree::elements(n).size() <= parameters.get_max_elements(),\n                \"unexpected number of elements\");\n            BOOST_GEOMETRY_INDEX_ASSERT(parameters.get_min_elements() <= rtree::elements(n2).size() &&\n                rtree::elements(n2).size() <= parameters.get_max_elements(),\n                \"unexpected number of elements\");\n\n            // return the list of newly created nodes (this algorithm returns one)\n            additional_nodes.push_back(rtree::make_ptr_pair(box2, n2_ptr));                                  // MAY THROW, STRONG (alloc, copy)\n        }\n        BOOST_CATCH(...)\n        {\n            // NOTE: This code is here to prevent leaving the rtree in a state\n            //  after an exception is thrown in which pushing new element could\n            //  result in assert or putting it outside the memory of node elements.\n            typename rtree::elements_type<Node>::type & elements = rtree::elements(n);\n            size_type const max_size = parameters.get_max_elements();\n            if (elements.size() > max_size)\n            {\n                rtree::destroy_element<MembersHolder>::apply(elements[max_size], allocators);\n                elements.pop_back();\n            }\n\n            rtree::visitors::destroy<MembersHolder>::apply(n2_ptr, allocators);\n\n            BOOST_RETHROW\n        }\n        BOOST_CATCH_END\n    }\n};\n\n// ----------------------------------------------------------------------- //\n\nnamespace visitors { namespace detail {\n\ntemplate <typename InternalNode, typename InternalNodePtr, typename SizeType>\nstruct insert_traverse_data\n{\n    typedef typename rtree::elements_type<InternalNode>::type elements_type;\n    typedef typename elements_type::value_type element_type;\n    typedef typename elements_type::size_type elements_size_type;\n    typedef SizeType size_type;\n\n    insert_traverse_data()\n        : parent(0), current_child_index(0), current_level(0)\n    {}\n\n    void move_to_next_level(InternalNodePtr new_parent,\n                            elements_size_type new_child_index)\n    {\n        parent = new_parent;\n        current_child_index = new_child_index;\n        ++current_level;\n    }\n\n    bool current_is_root() const\n    {\n        return 0 == parent;\n    }\n\n    elements_type & parent_elements() const\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(parent, \"null pointer\");\n        return rtree::elements(*parent);\n    }\n\n    element_type & current_element() const\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(parent, \"null pointer\");\n        return rtree::elements(*parent)[current_child_index];\n    }\n\n    InternalNodePtr parent;\n    elements_size_type current_child_index;\n    size_type current_level;\n};\n\n// Default insert visitor\ntemplate <typename Element, typename MembersHolder>\nclass insert\n    : public MembersHolder::visitor\n{\nprotected:\n    typedef typename MembersHolder::box_type box_type;\n    typedef typename MembersHolder::value_type value_type;\n    typedef typename MembersHolder::parameters_type parameters_type;\n    typedef typename MembersHolder::translator_type translator_type;\n    typedef typename MembersHolder::allocators_type allocators_type;\n\n    typedef typename MembersHolder::node node;\n    typedef typename MembersHolder::internal_node internal_node;\n    typedef typename MembersHolder::leaf leaf;\n\n    typedef rtree::subtree_destroyer<MembersHolder> subtree_destroyer;\n    typedef typename allocators_type::node_pointer node_pointer;\n    typedef typename allocators_type::size_type size_type;\n\n    //typedef typename allocators_type::internal_node_pointer internal_node_pointer;\n    typedef internal_node * internal_node_pointer;\n\n    inline insert(node_pointer & root,\n                  size_type & leafs_level,\n                  Element const& element,\n                  parameters_type const& parameters,\n                  translator_type const& translator,\n                  allocators_type & allocators,\n                  size_type relative_level = 0\n    )\n        : m_element(element)\n        , m_parameters(parameters)\n        , m_translator(translator)\n        , m_relative_level(relative_level)\n        , m_level(leafs_level - relative_level)\n        , m_root_node(root)\n        , m_leafs_level(leafs_level)\n        , m_traverse_data()\n        , m_allocators(allocators)\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(m_relative_level <= leafs_level, \"unexpected level value\");\n        BOOST_GEOMETRY_INDEX_ASSERT(m_level <= m_leafs_level, \"unexpected level value\");\n        BOOST_GEOMETRY_INDEX_ASSERT(0 != m_root_node, \"there is no root node\");\n        // TODO\n        // assert - check if Box is correct\n\n        // When a value is inserted, during the tree traversal bounds of nodes\n        // on a path from the root to a leaf must be expanded. So prepare\n        // a bounding object at the beginning to not do it later for each node.\n        // NOTE: This is actually only needed because conditionally the bounding\n        //       object may be expanded below. Otherwise the indexable could be\n        //       directly used instead\n        index::detail::bounds(rtree::element_indexable(m_element, m_translator),\n                              m_element_bounds,\n                              index::detail::get_strategy(m_parameters));\n\n#ifdef BOOST_GEOMETRY_INDEX_EXPERIMENTAL_ENLARGE_BY_EPSILON\n        // Enlarge it in case if it's not bounding geometry type.\n        // It's because Points and Segments are compared WRT machine epsilon\n        // This ensures that leafs bounds correspond to the stored elements\n        if (BOOST_GEOMETRY_CONDITION((\n                std::is_same<Element, value_type>::value\n             && ! index::detail::is_bounding_geometry\n                    <\n                        typename indexable_type<translator_type>::type\n                    >::value )) )\n        {\n            geometry::detail::expand_by_epsilon(m_element_bounds);\n        }\n#endif\n    }\n\n    template <typename Visitor>\n    inline void traverse(Visitor & visitor, internal_node & n)\n    {\n        // choose next node\n        size_t choosen_node_index = rtree::choose_next_node<MembersHolder>\n            ::apply(n, rtree::element_indexable(m_element, m_translator),\n                    m_parameters,\n                    m_leafs_level - m_traverse_data.current_level);\n\n        // expand the node to contain value\n        index::detail::expand(\n            rtree::elements(n)[choosen_node_index].first,\n            m_element_bounds,\n            index::detail::get_strategy(m_parameters));\n\n        // next traversing step\n        traverse_apply_visitor(visitor, n, choosen_node_index);                                                 // MAY THROW (V, E: alloc, copy, N:alloc)\n    }\n\n    // TODO: awulkiew - change post_traverse name to handle_overflow or overflow_treatment?\n\n    template <typename Node>\n    inline void post_traverse(Node &n)\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(m_traverse_data.current_is_root() ||\n                                    &n == &rtree::get<Node>(*m_traverse_data.current_element().second),\n                                    \"if node isn't the root current_child_index should be valid\");\n\n        // handle overflow\n        if ( m_parameters.get_max_elements() < rtree::elements(n).size() )\n        {\n            // NOTE: If the exception is thrown current node may contain more than MAX elements or be empty.\n            // Furthermore it may be empty root - internal node.\n            split(n);                                                                                           // MAY THROW (V, E: alloc, copy, N:alloc)\n        }\n    }\n\n    template <typename Visitor>\n    inline void traverse_apply_visitor(Visitor & visitor, internal_node &n, size_t choosen_node_index)\n    {\n        // save previous traverse inputs and set new ones\n        insert_traverse_data<internal_node, internal_node_pointer, size_type>\n            backup_traverse_data = m_traverse_data;\n\n        // calculate new traverse inputs\n        m_traverse_data.move_to_next_level(&n, choosen_node_index);\n\n        // next traversing step\n        rtree::apply_visitor(visitor, *rtree::elements(n)[choosen_node_index].second);                          // MAY THROW (V, E: alloc, copy, N:alloc)\n\n        // restore previous traverse inputs\n        m_traverse_data = backup_traverse_data;\n    }\n\n    // TODO: consider - split result returned as OutIter is faster than reference to the container. Why?\n\n    template <typename Node>\n    inline void split(Node & n) const\n    {\n        typedef rtree::split<MembersHolder> split_algo;\n\n        typename split_algo::nodes_container_type additional_nodes;\n        box_type n_box;\n\n        split_algo::apply(additional_nodes, n, n_box, m_parameters, m_translator, m_allocators);                // MAY THROW (V, E: alloc, copy, N:alloc)\n\n        BOOST_GEOMETRY_INDEX_ASSERT(additional_nodes.size() == 1, \"unexpected number of additional nodes\");\n\n        // TODO add all additional nodes\n        // For kmeans algorithm:\n        // elements number may be greater than node max elements count\n        // split and reinsert must take node with some elements count\n        // and container of additional elements (std::pair<Box, node*>s or Values)\n        // and translator + allocators\n        // where node_elements_count + additional_elements > node_max_elements_count\n        // What with elements other than std::pair<Box, node*> ?\n        // Implement template <node_tag> struct node_element_type or something like that\n\n        // for exception safety\n        subtree_destroyer additional_node_ptr(additional_nodes[0].second, m_allocators);\n\n#ifdef BOOST_GEOMETRY_INDEX_EXPERIMENTAL_ENLARGE_BY_EPSILON\n        // Enlarge bounds of a leaf node.\n        // It's because Points and Segments are compared WRT machine epsilon\n        // This ensures that leafs' bounds correspond to the stored elements.\n        if (BOOST_GEOMETRY_CONDITION((\n                std::is_same<Node, leaf>::value\n             && ! index::detail::is_bounding_geometry\n                    <\n                        typename indexable_type<translator_type>::type\n                    >::value )))\n        {\n            geometry::detail::expand_by_epsilon(n_box);\n            geometry::detail::expand_by_epsilon(additional_nodes[0].first);\n        }\n#endif\n\n        // node is not the root - just add the new node\n        if ( !m_traverse_data.current_is_root() )\n        {\n            // update old node's box\n            m_traverse_data.current_element().first = n_box;\n            // add new node to parent's children\n            m_traverse_data.parent_elements().push_back(additional_nodes[0]);                                     // MAY THROW, STRONG (V, E: alloc, copy)\n        }\n        // node is the root - add level\n        else\n        {\n            BOOST_GEOMETRY_INDEX_ASSERT(&n == &rtree::get<Node>(*m_root_node), \"node should be the root\");\n\n            // create new root and add nodes\n            subtree_destroyer new_root(rtree::create_node<allocators_type, internal_node>::apply(m_allocators), m_allocators); // MAY THROW, STRONG (N:alloc)\n\n            BOOST_TRY\n            {\n                rtree::elements(rtree::get<internal_node>(*new_root)).push_back(rtree::make_ptr_pair(n_box, m_root_node));  // MAY THROW, STRONG (E:alloc, copy)\n                rtree::elements(rtree::get<internal_node>(*new_root)).push_back(additional_nodes[0]);                 // MAY THROW, STRONG (E:alloc, copy)\n            }\n            BOOST_CATCH(...)\n            {\n                // clear new root to not delete in the ~subtree_destroyer() potentially stored old root node\n                rtree::elements(rtree::get<internal_node>(*new_root)).clear();\n                BOOST_RETHROW                                                                                           // RETHROW\n            }\n            BOOST_CATCH_END\n\n            m_root_node = new_root.get();\n            ++m_leafs_level;\n\n            new_root.release();\n        }\n\n        additional_node_ptr.release();\n    }\n\n    // TODO: awulkiew - implement dispatchable split::apply to enable additional nodes creation\n\n    Element const& m_element;\n    box_type m_element_bounds;\n    parameters_type const& m_parameters;\n    translator_type const& m_translator;\n    size_type const m_relative_level;\n    size_type const m_level;\n\n    node_pointer & m_root_node;\n    size_type & m_leafs_level;\n\n    // traversing input parameters\n    insert_traverse_data<internal_node, internal_node_pointer, size_type> m_traverse_data;\n\n    allocators_type & m_allocators;\n};\n\n} // namespace detail\n\n// Insert visitor forward declaration\ntemplate\n<\n    typename Element,\n    typename MembersHolder,\n    typename InsertTag = typename MembersHolder::options_type::insert_tag\n>\nclass insert;\n\n// Default insert visitor used for nodes elements\n// After passing the Element to insert visitor the Element is managed by the tree\n// I.e. one should not delete the node passed to the insert visitor after exception is thrown\n// because this visitor may delete it\ntemplate <typename Element, typename MembersHolder>\nclass insert<Element, MembersHolder, insert_default_tag>\n    : public detail::insert<Element, MembersHolder>\n{\npublic:\n    typedef detail::insert<Element, MembersHolder> base;\n\n    typedef typename base::parameters_type parameters_type;\n    typedef typename base::translator_type translator_type;\n    typedef typename base::allocators_type allocators_type;\n\n    typedef typename base::node node;\n    typedef typename base::internal_node internal_node;\n    typedef typename base::leaf leaf;\n\n    typedef typename base::node_pointer node_pointer;\n    typedef typename base::size_type size_type;\n\n    inline insert(node_pointer & root,\n                  size_type & leafs_level,\n                  Element const& element,\n                  parameters_type const& parameters,\n                  translator_type const& translator,\n                  allocators_type & allocators,\n                  size_type relative_level = 0\n    )\n        : base(root, leafs_level, element, parameters, translator, allocators, relative_level)\n    {}\n\n    inline void operator()(internal_node & n)\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(base::m_traverse_data.current_level < base::m_leafs_level, \"unexpected level\");\n\n        if ( base::m_traverse_data.current_level < base::m_level )\n        {\n            // next traversing step\n            base::traverse(*this, n);                                                                           // MAY THROW (E: alloc, copy, N: alloc)\n        }\n        else\n        {\n            BOOST_GEOMETRY_INDEX_ASSERT(base::m_level == base::m_traverse_data.current_level, \"unexpected level\");\n\n            BOOST_TRY\n            {\n                // push new child node\n                rtree::elements(n).push_back(base::m_element);                                                  // MAY THROW, STRONG (E: alloc, copy)\n            }\n            BOOST_CATCH(...)\n            {\n                // if the insert fails above, the element won't be stored in the tree\n\n                rtree::visitors::destroy<MembersHolder>::apply(base::m_element.second, base::m_allocators);\n\n                BOOST_RETHROW                                                                                     // RETHROW\n            }\n            BOOST_CATCH_END\n        }\n\n        base::post_traverse(n);                                                                                 // MAY THROW (E: alloc, copy, N: alloc)\n    }\n\n    inline void operator()(leaf &)\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(false, \"this visitor can't be used for a leaf\");\n    }\n};\n\n// Default insert visitor specialized for Values elements\ntemplate <typename MembersHolder>\nclass insert<typename MembersHolder::value_type, MembersHolder, insert_default_tag>\n    : public detail::insert<typename MembersHolder::value_type, MembersHolder>\n{\npublic:\n    typedef detail::insert<typename MembersHolder::value_type, MembersHolder> base;\n\n    typedef typename base::value_type value_type;\n    typedef typename base::parameters_type parameters_type;\n    typedef typename base::translator_type translator_type;\n    typedef typename base::allocators_type allocators_type;\n\n    typedef typename base::node node;\n    typedef typename base::internal_node internal_node;\n    typedef typename base::leaf leaf;\n\n    typedef typename base::node_pointer node_pointer;\n    typedef typename base::size_type size_type;\n\n    inline insert(node_pointer & root,\n                  size_type & leafs_level,\n                  value_type const& value,\n                  parameters_type const& parameters,\n                  translator_type const& translator,\n                  allocators_type & allocators,\n                  size_type relative_level = 0\n    )\n        : base(root, leafs_level, value, parameters, translator, allocators, relative_level)\n    {}\n\n    inline void operator()(internal_node & n)\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(base::m_traverse_data.current_level < base::m_leafs_level, \"unexpected level\");\n        BOOST_GEOMETRY_INDEX_ASSERT(base::m_traverse_data.current_level < base::m_level, \"unexpected level\");\n\n        // next traversing step\n        base::traverse(*this, n);                                                                                   // MAY THROW (V, E: alloc, copy, N: alloc)\n\n        base::post_traverse(n);                                                                                     // MAY THROW (E: alloc, copy, N: alloc)\n    }\n\n    inline void operator()(leaf & n)\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(base::m_traverse_data.current_level == base::m_leafs_level, \"unexpected level\");\n        BOOST_GEOMETRY_INDEX_ASSERT(base::m_level == base::m_traverse_data.current_level ||\n                                    base::m_level == (std::numeric_limits<size_t>::max)(), \"unexpected level\");\n        \n        rtree::elements(n).push_back(base::m_element);                                                              // MAY THROW, STRONG (V: alloc, copy)\n\n        base::post_traverse(n);                                                                                     // MAY THROW (V: alloc, copy, N: alloc)\n    }\n};\n\n}}} // namespace detail::rtree::visitors\n\n}}} // namespace boost::geometry::index\n\n#endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_INSERT_HPP\n", "meta": {"hexsha": "8b32c81763128ed72c2ce0cac31f71113856d237", "size": 25643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/index/detail/rtree/visitors/insert.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/index/detail/rtree/visitors/insert.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/index/detail/rtree/visitors/insert.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": 40.5102685624, "max_line_length": 160, "alphanum_fraction": 0.6320633311, "num_tokens": 5112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.33807712415000574, "lm_q1q2_score": 0.190059009724344}}
{"text": "/******************************************************************************\n * Copyright 2018 The Apollo 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 \"modules/perception/camera/common/undistortion_handler.h\"\n\n#include <npp.h>\n\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"cyber/common/log.h\"\n#include \"modules/perception/common/sensor_manager/sensor_manager.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace camera {\n\nbool UndistortionHandler::set_device(int device) {\n  device_ = device;\n  auto code = cudaSetDevice(device_);\n  if (code != cudaSuccess) {\n    AERROR << \"cudaSetDevice failed: \" << cudaGetErrorString(code);\n    return false;\n  }\n  return true;\n}\n/* Initialization of the GPU routines for camera data preprocessing\n *\n * Return: 0 - success; other - failure\n * Params: device - dev number of the GPU device\n * Note: returns OK if already been inited.\n */\nbool UndistortionHandler::Init(const std::string &sensor_name, int device) {\n  if (inited_) {\n    return true;\n  }\n\n  std::vector<double> D;\n  std::vector<double> K;\n\n  common::SensorManager *sensor_manager = common::SensorManager::Instance();\n  if (!sensor_manager->IsSensorExist(sensor_name)) {\n    AERROR << \"Sensor '\" << sensor_name << \"' not exists!\";\n    return false;\n  }\n\n  if (!set_device(device)) {\n    return false;\n  }\n\n  base::BrownCameraDistortionModelPtr distort_model =\n      std::dynamic_pointer_cast<base::BrownCameraDistortionModel>(\n          sensor_manager->GetDistortCameraModel(sensor_name));\n\n  height_ = static_cast<int>(distort_model->get_height());\n  width_ = static_cast<int>(distort_model->get_width());\n  d_mapx_.Reshape({height_, width_});\n  d_mapy_.Reshape({height_, width_});\n\n  Eigen::Matrix3f I;\n  I << 1.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 1.f;\n\n  InitUndistortRectifyMap(distort_model->get_intrinsic_params(),\n                          distort_model->get_distort_params(), I,\n                          distort_model->get_intrinsic_params(), width_,\n                          height_, &d_mapx_, &d_mapy_);\n\n  inited_ = true;\n  return true;\n}\n\nbool UndistortionHandler::Handle(const base::Image8U &src_img,\n                                 base::Image8U *dst_img) {\n  if (!inited_) {\n    return false;\n  }\n\n  if (!set_device(device_)) {\n    return false;\n  }\n\n  NppiInterpolationMode remap_mode = NPPI_INTER_LINEAR;\n  NppiSize image_size;\n  image_size.width = width_;\n  image_size.height = height_;\n  NppiRect remap_roi = {0, 0, width_, height_};\n\n  NppStatus status;\n  int d_map_step = static_cast<int>(d_mapx_.shape(1) * sizeof(float));\n  switch (src_img.channels()) {\n    case 1:\n      status = nppiRemap_8u_C1R(\n          src_img.gpu_data(), image_size, src_img.width_step(), remap_roi,\n          d_mapx_.gpu_data(), d_map_step, d_mapy_.gpu_data(), d_map_step,\n          dst_img->mutable_gpu_data(), dst_img->width_step(), image_size,\n          remap_mode);\n      break;\n    case 3:\n      status = nppiRemap_8u_C3R(\n          src_img.gpu_data(), image_size, src_img.width_step(), remap_roi,\n          d_mapx_.gpu_data(), d_map_step, d_mapy_.gpu_data(), d_map_step,\n          dst_img->mutable_gpu_data(), dst_img->width_step(), image_size,\n          remap_mode);\n      break;\n    default:\n      AERROR << \"Invalid number of channels: \" << src_img.channels();\n      return false;\n  }\n\n  if (status != NPP_SUCCESS) {\n    AERROR << \"NPP_CHECK_NPP - status = \" << status;\n    return false;\n  }\n\n  return true;\n}\n\nbool UndistortionHandler::Release(void) {\n  inited_ = false;\n  return true;\n}\n\nvoid UndistortionHandler::InitUndistortRectifyMap(\n    const Eigen::Matrix3f &camera_model,\n    const Eigen::Matrix<float, 5, 1> distortion, const Eigen::Matrix3f &R,\n    const Eigen::Matrix3f &new_camera_model, int width, int height,\n    base::Blob<float> *d_mapx, base::Blob<float> *d_mapy) {\n  float fx = camera_model(0, 0);\n  float fy = camera_model(1, 1);\n  float cx = camera_model(0, 2);\n  float cy = camera_model(1, 2);\n  float nfx = new_camera_model(0, 0);\n  float nfy = new_camera_model(1, 1);\n  float ncx = new_camera_model(0, 2);\n  float ncy = new_camera_model(1, 2);\n  float k1 = distortion(0, 0);\n  float k2 = distortion(1, 0);\n  float p1 = distortion(2, 0);\n  float p2 = distortion(3, 0);\n  float k3 = distortion(4, 0);\n  Eigen::Matrix3f Rinv = R.inverse();\n\n  for (int v = 0; v < height_; ++v) {\n    float *x_ptr = d_mapx->mutable_cpu_data() + d_mapx->offset(v);\n    float *y_ptr = d_mapy->mutable_cpu_data() + d_mapy->offset(v);\n    for (int u = 0; u < width_; ++u) {\n      Eigen::Matrix<float, 3, 1> xy1;\n      xy1 << (static_cast<float>(u) - ncx) / nfx,\n          (static_cast<float>(v) - ncy) / nfy, 1;\n      auto XYW = Rinv * xy1;\n      double nx = XYW(0, 0) / XYW(2, 0);\n      double ny = XYW(1, 0) / XYW(2, 0);\n      double r_square = nx * nx + ny * ny;\n      double scale = (1 + r_square * (k1 + r_square * (k2 + r_square * k3)));\n      double nnx =\n          nx * scale + 2 * p1 * nx * ny + p2 * (r_square + 2 * nx * nx);\n      double nny =\n          ny * scale + p1 * (r_square + 2 * ny * ny) + 2 * p2 * nx * ny;\n      x_ptr[u] = static_cast<float>(nnx * fx + cx);\n      y_ptr[u] = static_cast<float>(nny * fy + cy);\n    }\n  }\n}\n\n}  // namespace camera\n}  // namespace perception\n}  // namespace apollo\n", "meta": {"hexsha": "05c73c145026ca92efd86c936453bed4ab279800", "size": 5868, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/perception/camera/common/undistortion_handler.cc", "max_stars_repo_name": "seeclong/apollo", "max_stars_repo_head_hexsha": "99c8afb5ebcae2a3c9359a156a957ff03944b27b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2019-04-06T02:27:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T13:47:06.000Z", "max_issues_repo_path": "modules/perception/camera/common/undistortion_handler.cc", "max_issues_repo_name": "seeclong/apollo", "max_issues_repo_head_hexsha": "99c8afb5ebcae2a3c9359a156a957ff03944b27b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-10-06T22:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T14:04:05.000Z", "max_forks_repo_path": "modules/perception/camera/common/undistortion_handler.cc", "max_forks_repo_name": "seeclong/apollo", "max_forks_repo_head_hexsha": "99c8afb5ebcae2a3c9359a156a957ff03944b27b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2019-04-15T10:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T08:52:39.000Z", "avg_line_length": 32.6, "max_line_length": 79, "alphanum_fraction": 0.6336059986, "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.19001750916422705}}
{"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_PPC_VMX_SIMD_FUNCTION_TOUINT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_PPC_VMX_SIMD_FUNCTION_TOUINT_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.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\n   BOOST_DISPATCH_OVERLOAD( touint_\n                          , (typename A0)\n                          , bs::vmx_\n                          , bs::saturated_tag\n                          , bs::pack_< bd::single_<A0>, bs::vmx_>\n                          )\n   {\n      BOOST_FORCEINLINE  bd::as_integer_t<A0, unsigned>\n      operator()(bs::saturated_tag const&, const A0& a0) const BOOST_NOEXCEPT\n      {\n        return vec_ctu(a0.storage(),0);\n      }\n   };\n} } }\n\n#endif\n", "meta": {"hexsha": "29ace286effaf22cd6b922dad203d95ddd33db65", "size": 1204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/ppc/vmx/simd/function/touint.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/ppc/vmx/simd/function/touint.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/ppc/vmx/simd/function/touint.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": 33.4444444444, "max_line_length": 100, "alphanum_fraction": 0.5257475083, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.19001750036579487}}
{"text": "//   GAMBIT: Global and Modular BSM Inference Tool\n//   *********************************************\n///  \\file\n///\n///  Type definition and function declaration header for decay chain setup.\n///\n///\n///  *********************************************\n///\n///  Authors (add name and date if you modify):\n///\n///  \\author Lars A. Dal\n///          (l.a.dal@fys.uio.no)\n///  \\date 2014 Oct, Nov, Dec\n///  \\date 2015 Jan\n///  *********************************************\n\n#ifndef __decay_chain_hpp__\n#define __decay_chain_hpp__\n\n#include <vector>\n#include <unordered_map>\n#include <string>\n#include <set>\n#include <boost/shared_ptr.hpp>\n#include \"gambit/Utils/threadsafe_rng.hpp\"\n\nnamespace Gambit\n{\n    namespace DarkBit\n    {\n        struct TH_Channel;\n        class TH_ProcessCatalog;\n        class SimYieldTable;\n        namespace DecayChain\n        {\n            using std::vector;\n            using std::ofstream;\n            using std::ostream;\n            using std::string;\n            using boost::shared_ptr;\n            using std::unordered_map;\n            using std::set;\n\n            //  *********************************************\n            //  Generic 3-vector class\n            //  *********************************************\n            class vec3\n            {\n                public:\n                    double vals[3];\n                    // Constructors\n                    vec3(){}\n                    vec3(double v0, double v1, double v2) {vals[0]=v0;vals[1]=v1;vals[2]=v2;}\n                    vec3(double v0){vals[0]=v0;vals[1]=v0;vals[2]=v0;}\n                    // Get the length of the vector\n                    double length() const;\n                    // Normalize vector to unit length\n                    void normalize();\n                    // Normalize vector to length len\n                    void normalize(const double len);\n                    // Operators\n                    double& operator[](int i){ return vals[i];}\n                    double operator[](int i)const{ return vals[i];}\n                    vec3 operator-()const{return vec3(-vals[0],-vals[1],-vals[2]);\t}\n            };\n            vec3 operator* (double x, const vec3 &y);\n            vec3 operator* (const vec3 &y, double x);\n            vec3 operator/ (const vec3 &y, double x);\n            ostream& operator<<(ostream& os, const vec3& v);\n            double dot(const vec3 &a, const vec3 &b);\n\n\n            //  *********************************************\n            //  Generic 4-vector class\n            //  *********************************************\n            class vec4\n            {\n                public:\n                    double vals[4];\n                    // Constructors\n                    vec4(){}\n                    vec4(double v0, double v1, double v2, double v3){vals[0]=v0;vals[1]=v1;vals[2]=v2;vals[3]=v3;}\n                    vec4(double v0){vals[0]=v0;vals[1]=v0;vals[2]=v0;vals[3]=v0;}\n                    vec4(double v0, vec3 v){vals[0]=v0;vals[1]=v[0];vals[2]=v[1];vals[3]=v[2];}\n                    // Returns vec3 containting elements 1,2,3\n                    vec3 xyz() const{return vec3(vals[1],vals[2],vals[3]);}\n                    // Operators\n                    double& operator[](int i){ return vals[i];}\n                    double operator[](int i)const{ return vals[i];}\n                    vec4 operator-(){return vec4(-vals[0],-vals[1],-vals[2],-vals[3]);}\n            };\n            vec4 operator* (double x, const vec4 &y);\n            vec4 operator* (const vec4 &y, double x);\n            vec4 operator+ (const vec4 &x, const vec4 &y);\n            vec4 operator- (const vec4 &x, const vec4 &y);\n            ostream& operator<<(ostream& os, const vec4& v);\n            double dot(const vec4 &a, const vec4 &b);\n            // Construct an energy-momentum 4-vector from the given 3-momentum and mass\n            vec4 Ep4vec(const vec3 p, double m);\n\n\n            //  *********************************************\n            //  Generic 4x4 class\n            //  *********************************************\n            class mat4\n            {\n                public:\n                    double vals[4][4];\n                    mat4(){};\n                    mat4(   double v00, double v01, double v02, double v03,\n                            double v10, double v11, double v12, double v13,\n                            double v20, double v21, double v22, double v23,\n                            double v30, double v31, double v32, double v33);\n                    mat4(double v);\n                    // Identity matrix\n                    static mat4 identity();\n            };\n            vec4 operator* (const mat4 &m, const vec4 &v);\n            mat4 operator* (const mat4 &m1, const mat4 &m2);\n            ostream& operator<<(ostream& os, const mat4& m);\n\n\n            //  *********************************************\n            //  Utility functions\n            //  *********************************************\n            // Generate a random number between -1 and 1\n            double rand_m1_1();\n            // Generate a random number between 0 and 1\n            inline double rand_0_1(){return Random::draw();}\n            // Generate a 3-vector to a random point on the unit sphere\n            vec3 randOnSphere();\n            // Calculate Lorentz boost matrix corresponding to beta_xyz.\n            // Always calculate gamma=E/m and use the second version when possible, as this is far more numerically stable.\n            void lorentzMatrix(const vec3 &beta_xyz, mat4 &mat);\n            void lorentzMatrix(const vec3 &beta_xyz, mat4 &mat, double gamma);\n            // Boost inVec according to beta_xyz.\n            vec4 lorentzBoost(const vec4 &inVec, const vec3 &beta_xyz);\n            // Boost inVec to the frame where a particle at rest (in this frame) would have 4-momentum p_parent\n            vec4 p_parentFrame(const vec4 &inVec, const vec4 &p_parent);\n            // Get Lorentz matrix for boosting to parent frame\n            void boostMatrixParentFrame(mat4 &mat, vec4 &p_parent);\n            // Calculate the invariant mass of the given 4-vector pair\n            double invariantMass(const vec4 &a, const vec4 &b);\n\n\n            //  *********************************************\n            //  Class containing all the allowed decay channels of a single particle,\n            //  as well as the particle mass.\n            //  Contains functonality for picking random decays according to their decay widths\n            //  *********************************************\n            class DecayTableEntry\n            {\n                friend class DecayTable;\n                public:\n                    // Particle mass\n                    const double m;\n                    // Is the particle stable in the context of the decay chain?\n                    bool stable;\n                    // Flags indicating whether or not the various decay states are endpoints\n                    unordered_map<const TH_Channel*, bool> endpointFlags;\n                    // Constructor\n                    DecayTableEntry(string pID, double m, bool stable) :\n                        m(m), stable(stable), enabledWidth(0),\n                        totalWidth(0), invisibleWidth(0), useForcedTotalWidth(false), forcedTotalWidth(0), pID(pID), randInit(false){}\n                    // Dummy constructor (for the DecayTable map)\n                    DecayTableEntry() :\n                        m(0), stable(false), enabledWidth(0),\n                        totalWidth(0), invisibleWidth(0), useForcedTotalWidth(false), forcedTotalWidth(0), pID(\"\"),  randInit(false){}\n                    // Pick a random decay channel\n                    bool randomDecay(const TH_Channel* &decay) const;\n                    // Update decay widths and if necessary Monte Carlo table\n                    void update();\n                    // Functions for checking if a decay exists in the decay tables\n                    bool isEnabled(const TH_Channel *in) const;\n                    bool isDisabled(const TH_Channel *in) const;\n                    bool isRegistered(const TH_Channel *in) const;\n                    // Add decay channel as enabled or disabled\n                    void addChannel(const TH_Channel *in);\n                    void addDisabled(const TH_Channel *in);\n                    void setInvisibleWidth(double width);\n                    // Functions for enabling/disabling (registered) decays.\n                    // Returns false if decay is in the list of disabled/enabled decays\n                    bool enableDecay(const TH_Channel *in);\n                    bool disableDecay(const TH_Channel *in);\n                    // Get branching ratio of enabled decays\n                    double getEnabledBranching() const;\n                    // Set total decay width to a fixed value\n                    void forceTotalWidth(bool enabled, double width);\n                    // Get total decay width\n                    double getTotalWidth() const;\n                    bool hasEnabledDecays() const;\n                private:\n                    // Lists of decays\n                    vector<const TH_Channel*> enabledDecays;\n                    vector<const TH_Channel*> disabledDecays;\n                    // Table used for picking random decays\n                    mutable vector<double> randLims;\n                    // Decay widths of enabled channels and all channels\n                    double enabledWidth;\n                    double totalWidth;\n                    double invisibleWidth;\n                    bool useForcedTotalWidth;\n                    double forcedTotalWidth;\n                    // String particle identifier\n                    string pID;\n                    // Initialization status of Monte Carlo table\n                    mutable bool randInit;\n                    // Function used in picking a random decay\n                    int findChannelIdx(double pick) const;\n                    // Generate table for picking a random decay in Monte Carlo decay chains\n                    void generateRandTable() const;\n            };\n\n            //  *********************************************\n            //  Table of all particles and their decay channels.\n            //  Uses particle PID as array index\n            //  *********************************************\n            class DecayTable\n            {\n                public:\n                    DecayTable(const TH_ProcessCatalog &cat, const SimYieldTable &tab, set<string> disabledList);\n                    DecayTable(){};\n                    bool hasEntry(string) const;\n                    // Add particle to decay table, specifying particle ID, mass and whether or not it should be decayed in decay chains\n                    void addEntry(string pID, double m, bool stable);\n                    void addEntry(string pID, DecayTableEntry entry);\n                    bool randomDecay(string pID, const TH_Channel* &decay) const;\n                    const DecayTableEntry& operator[](string i) const;\n                    // Retrieve width of decay channel\n                    static double getWidth(const TH_Channel *ch);\n                    // Print the decay table (to cout)\n                    void printTable() const;\n                private:\n                    unordered_map<string,DecayTableEntry> table;\n            };\n\n\n            //  *********************************************\n            //  The main decay chain class.\n            //  Each link (particle) in the decay chain is an instance of this class,\n            //  with pointers to its parent and child links.\n            //  *********************************************\n            class ChainParticle\n            {\n                public:\n                    // Invariant (rest) mass\n                    const double m;\n                    // Constructor for the base node (top particle in the decay chain).\n                    ChainParticle(vec3 ipLab, const DecayTable *dc, string pID);\n                    // Iteratively add random links to the decay chain by Monte Carlo to a maximum length of maxSteps or minimum energy of Emin.\n                    // Use negative numbers to turn off limits\n                    void generateDecayChainMC(int maxSteps, double Emin);\n                    // Draw new angles for the decay products in this and all subsequent links of the decay chain\n                    void reDrawAngles();\n                    // Remove all subsequent links in the decay chain\n                    void cutChain();\n                    // Boost a given 4-momentum from this frame to the lab frame.\n                    vec4 p_to_Lab(const vec4 &p) const;\n                    // Calculate 4-momentum of this particle in the lab frame.\n                    vec4 p_Lab() const;\n                    // Calculate the energy of this particle in the lab frame. Faster than calculating the full 4-momentum.\n                    double E_Lab() const;\n                    // Iteratively collect decay chain endpoint states. Optional argument to only collect particles of certain types.\n                    // Note that this function will not collect decay products of endpoint states. These must be extracted manually.\n                    void collectEndpointStates(vector<const ChainParticle*> &endpointStates, bool includeAborted, string ipID=\"\") const;\n                    // Get number of child particles\n                    int getnChildren() const {return nChildren;}\n                    // Get child particle\n                    const ChainParticle* operator[](int i) const;\n                    // Get parent particle\n                    const ChainParticle* getParent() const;\n                    // Get energy in parent frame\n                    double E_parentFrame() const;\n                    // Get particle ID\n                    string getpID() const {return pID;}\n                    // Print the decay chain (to cout)\n                    void printChain() const;\n                    // Get weight factor (see description of the weight variable)\n                    double getWeight() const {return weight;}\n                    // Get boost between lab frame and CoM frame of this particle\n                    void getBoost(double& gamma, double& beta) const;\n                    // Get pointer to decay table\n                    const DecayTable* getDecayTable() const {return decayTable;}\n                    // Destructor\n                    ~ChainParticle();\n                private:\n                    // Helper function for printChain()\n                    bool printChain(int generation, vector<int> ancestry) const;\n                    // How much the decay chain (to this point) should be weighted down due to\n                    // missing/disabled decay channels. Only relevant for Monte Carlo generated chains.\n                    double weight;\n                    // Pointer to decay table\n                    const DecayTable *decayTable;\n                    // Lorentz matrices\n                    mat4 boostToParentFrame;\n                    mat4 boostToLabFrame;\n                    // 4-momentum in parent's rest frame\n                    vec4 p_parent;\n                    // Particle identifier\n                    string pID;\n                    // How many ancestors do I have?\n                    int chainGeneration;\n                    // Has this particle been kept from decaying by an energy or chain length cut?\n                    bool abortedDecay;\n                    // Is this particle stable, or has it decayed to a final state consisting entirely of stable particles?\n                    // If so, this particle is considered a final state, and any children must be extracted manually after collecting the final states.\n                    // This is to avoid having final states that can't be treated as free particles (such as quarks).\n                    bool isEndpoint;\n                    // Number of child particles\n                    int nChildren;\n                    // Pointers to parent and child particles\n                    ChainParticle *parent;\n                    vector<ChainParticle*> children;\n                    // Function for updating the Lorentz boost matrices according to a new 4-momentum.\n                    void update(vec4 &ip_parent);\n                    // Constructor used by member functions during chain generation.\n                    ChainParticle(const vec4 &pp, double m, double weight, const DecayTable *dc, ChainParticle *parent, int chainGeneration, string pID);\n                    // Disable copy constructor and assignment operator. These would cause mayhem.\n                    ChainParticle(const ChainParticle&);\n                    ChainParticle & operator=(const ChainParticle&);\n            };\n            typedef std::vector<const Gambit::DarkBit::DecayChain::ChainParticle*> ChainParticleVector;\n\n            // Container for passing around ChainParticle objects.\n            struct ChainContainer\n            {\n                ChainContainer(){}\n                ChainContainer(shared_ptr<ChainParticle> ch) : chain(ch) {}\n                shared_ptr<const ChainParticle> chain;\n            };\n\n        }\n    }\n}\n\n#endif // defined __decay_chain_hpp__\n", "meta": {"hexsha": "99c3f28c1359777189397a248fa90ffb580284ae", "size": 17313, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "DarkBit/include/gambit/DarkBit/decay_chain.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-21T19:59:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-21T19:59:18.000Z", "max_issues_repo_path": "DarkBit/include/gambit/DarkBit/decay_chain.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-10-06T14:03:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T11:53:54.000Z", "max_forks_repo_path": "DarkBit/include/gambit/DarkBit/decay_chain.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": 51.2218934911, "max_line_length": 153, "alphanum_fraction": 0.5027436031, "num_tokens": 3287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.1900174966571504}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2016-2019.\n// Modifications copyright (c) 2016-2019 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_DETAIL_BUFFER_BUFFERED_PIECE_COLLECTION_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFERED_PIECE_COLLECTION_HPP\n\n#include <algorithm>\n#include <cstddef>\n#include <set>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/range.hpp>\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/point_type.hpp>\n\n#include <boost/geometry/algorithms/covered_by.hpp>\n#include <boost/geometry/algorithms/envelope.hpp>\n\n#include <boost/geometry/strategies/buffer.hpp>\n\n#include <boost/geometry/geometries/ring.hpp>\n\n#include <boost/geometry/algorithms/detail/buffer/buffered_ring.hpp>\n#include <boost/geometry/algorithms/detail/buffer/buffer_policies.hpp>\n#include <boost/geometry/algorithms/detail/overlay/cluster_info.hpp>\n#include <boost/geometry/algorithms/detail/buffer/get_piece_turns.hpp>\n#include <boost/geometry/algorithms/detail/buffer/piece_border.hpp>\n#include <boost/geometry/algorithms/detail/buffer/turn_in_piece_visitor.hpp>\n#include <boost/geometry/algorithms/detail/buffer/turn_in_original_visitor.hpp>\n\n#include <boost/geometry/algorithms/detail/disjoint/point_box.hpp>\n#include <boost/geometry/algorithms/detail/overlay/add_rings.hpp>\n#include <boost/geometry/algorithms/detail/overlay/assign_parents.hpp>\n#include <boost/geometry/algorithms/detail/overlay/enrichment_info.hpp>\n#include <boost/geometry/algorithms/detail/overlay/enrich_intersection_points.hpp>\n#include <boost/geometry/algorithms/detail/overlay/ring_properties.hpp>\n#include <boost/geometry/algorithms/detail/overlay/select_rings.hpp>\n#include <boost/geometry/algorithms/detail/overlay/traversal_info.hpp>\n#include <boost/geometry/algorithms/detail/overlay/traverse.hpp>\n#include <boost/geometry/algorithms/detail/overlay/turn_info.hpp>\n#include <boost/geometry/algorithms/detail/partition.hpp>\n#include <boost/geometry/algorithms/detail/sections/sectionalize.hpp>\n#include <boost/geometry/algorithms/detail/sections/section_box_policies.hpp>\n\n#include <boost/geometry/views/detail/normalized_view.hpp>\n#include <boost/geometry/util/range.hpp>\n\n// TODO remove this\n#include <boost/geometry/algorithms/detail/overlay/debug_turn_info.hpp>\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace buffer\n{\n\n\n/*\n *  Terminology\n *\n *  Suppose we make a buffer (using blocked corners) of this rectangle:\n *\n *         +-------+\n *         |       |\n *         |  rect |\n *         |       |\n *         +-------+\n *\n * For the sides we get these four buffered side-pieces (marked with s)\n * and four buffered corner pieces (marked with c)\n *\n *     c---+---s---+---c\n *     |   | piece |   |     <- see below for details of the middle top-side-piece\n *     +---+-------+---+\n *     |   |       |   |\n *     s   |  rect |   s     <- two side pieces left/right of rect\n *     |   |       |   |\n *     +---+-------+---+\n *     |   | piece |   |     <- one side-piece below, and two corner pieces\n *     c---+---s---+---c\n *\n *  The outer part of the picture above, using all pieces,\n *    form together the offsetted ring (marked with o below)\n *  The 8 pieces are part of the piece collection and use for inside-checks\n *  The inner parts form (using 1 or 2 points per piece, often co-located)\n *    form together the robust_polygons (marked with r below)\n *  The remaining piece-segments are helper-segments (marked with h)\n *\n *     ooooooooooooooooo\n *     o   h       h   o\n *     ohhhrrrrrrrrrhhho\n *     o   r       r   o\n *     o   r       r   o\n *     o   r       r   o\n *     ohhhrrrrrrrrrhhho\n *     o   h       h   o\n *     ooooooooooooooooo\n *\n */\n\ntemplate\n<\n    typename Ring,\n    typename IntersectionStrategy,\n    typename DistanceStrategy,\n    typename RobustPolicy\n>\nstruct buffered_piece_collection\n{\n    typedef typename geometry::point_type<Ring>::type point_type;\n    typedef typename geometry::coordinate_type<Ring>::type coordinate_type;\n\n    // Robust ring/polygon type, always clockwise\n    typedef geometry::model::ring<point_type> clockwise_ring_type;\n\n    typedef geometry::model::box<point_type> box_type;\n\n    typedef typename IntersectionStrategy::side_strategy_type side_strategy_type;\n    typedef typename IntersectionStrategy::envelope_strategy_type envelope_strategy_type;\n    typedef typename IntersectionStrategy::expand_strategy_type expand_strategy_type;\n\n    typedef typename IntersectionStrategy::template area_strategy\n        <\n            point_type\n        >::type area_strategy_type;\n\n    typedef typename area_strategy_type::template result_type\n        <\n            point_type\n        >::type area_result_type;\n\n    typedef typename IntersectionStrategy::template point_in_geometry_strategy\n        <\n            point_type,\n            clockwise_ring_type\n        >::type point_in_geometry_strategy_type;\n\n\n    typedef buffer_turn_info\n    <\n        point_type,\n        typename segment_ratio_type<point_type, RobustPolicy>::type\n    > buffer_turn_info_type;\n\n    typedef buffer_turn_operation\n    <\n        point_type,\n        typename segment_ratio_type<point_type, RobustPolicy>::type\n    > buffer_turn_operation_type;\n\n    typedef std::vector<buffer_turn_info_type> turn_vector_type;\n\n    typedef piece_border<Ring, point_type> piece_border_type;\n\n    struct piece\n    {\n        strategy::buffer::piece_type type;\n        signed_size_type index;\n\n        signed_size_type left_index; // points to previous piece of same ring\n        signed_size_type right_index; // points to next piece of same ring\n\n        // The next two members (1, 2) form together a complete clockwise ring\n        // for each piece (with one dupped point)\n        // The complete clockwise ring is also included as a robust ring (3)\n\n        // 1: half, part of offsetted_rings\n\n        // Segment identifier of this piece, including its start index\n        segment_identifier first_seg_id;\n\n        // One-beyond index of this piece, to iterate over a ring\n        // from:                ring.begin() + pc.first_seg_id.segment_index;\n        // to (not including):  ring.begin() + pc.beyond_last_segment_index;\n        // Its ring_id etc are shared with first_seg_id\n        signed_size_type beyond_last_segment_index;\n\n        // part in offsetted ring which is part of offsetted ring\n        signed_size_type offsetted_count;\n\n        bool is_flat_start;\n        bool is_flat_end;\n\n        bool is_deflated;\n\n        // Ring (parts) of this piece, always clockwise\n        piece_border_type m_piece_border;\n\n        point_type m_label_point;\n\n        // For a point buffer\n        point_type m_center;\n\n        piece()\n            : type(strategy::buffer::piece_type_unknown)\n            , index(-1)\n            , left_index(-1)\n            , right_index(-1)\n            , beyond_last_segment_index(-1)\n            , offsetted_count(-1)\n            , is_flat_start(false)\n            , is_flat_end(false)\n            , is_deflated(false)\n        {\n        }\n    };\n\n    struct original_ring\n    {\n        typedef geometry::sections<box_type, 1> sections_type;\n\n        // Creates an empty instance\n        inline original_ring()\n            : m_is_interior(false)\n            , m_has_interiors(false)\n        {}\n\n        inline original_ring(clockwise_ring_type const& ring,\n                bool is_interior, bool has_interiors,\n                envelope_strategy_type const& envelope_strategy,\n                expand_strategy_type const& expand_strategy)\n            : m_ring(ring)\n            , m_is_interior(is_interior)\n            , m_has_interiors(has_interiors)\n        {\n            geometry::envelope(m_ring, m_box, envelope_strategy);\n\n            // create monotonic sections in x-dimension\n            // The dimension is critical because the direction is later used\n            // in the optimization for within checks using winding strategy\n            // and this strategy is scanning in x direction.\n            typedef boost::mpl::vector_c<std::size_t, 0> dimensions;\n            geometry::sectionalize<false, dimensions>(m_ring,\n                    detail::no_rescale_policy(), m_sections,\n                    envelope_strategy, expand_strategy);\n        }\n\n        clockwise_ring_type m_ring;\n        box_type m_box;\n        sections_type m_sections;\n\n        bool m_is_interior;\n        bool m_has_interiors;\n    };\n\n    typedef std::vector<piece> piece_vector_type;\n\n    piece_vector_type m_pieces;\n    turn_vector_type m_turns;\n    signed_size_type m_first_piece_index;\n    bool m_deflate;\n    bool m_has_deflated;\n\n    // Offsetted rings, and representations of original ring(s)\n    // both indexed by multi_index\n    buffered_ring_collection<buffered_ring<Ring> > offsetted_rings;\n    std::vector<original_ring> original_rings;\n    std::vector<point_type> m_linear_end_points;\n\n    buffered_ring_collection<Ring> traversed_rings;\n    segment_identifier current_segment_id;\n\n    // Specificly for offsetted rings around points\n    // but also for large joins with many points\n    typedef geometry::sections<box_type, 2> sections_type;\n    sections_type monotonic_sections;\n\n    // Define the clusters, mapping cluster_id -> turns\n    typedef std::map\n        <\n            signed_size_type,\n            detail::overlay::cluster_info\n        > cluster_type;\n\n    cluster_type m_clusters;\n\n    IntersectionStrategy m_intersection_strategy;\n    DistanceStrategy m_distance_strategy;\n    side_strategy_type m_side_strategy;\n    area_strategy_type m_area_strategy;\n    envelope_strategy_type m_envelope_strategy;\n    expand_strategy_type m_expand_strategy;\n    point_in_geometry_strategy_type m_point_in_geometry_strategy;\n\n    RobustPolicy const& m_robust_policy;\n\n    buffered_piece_collection(IntersectionStrategy const& intersection_strategy,\n                              DistanceStrategy const& distance_strategy,\n                              RobustPolicy const& robust_policy)\n        : m_first_piece_index(-1)\n        , m_deflate(false)\n        , m_has_deflated(false)\n        , m_intersection_strategy(intersection_strategy)\n        , m_distance_strategy(distance_strategy)\n        , m_side_strategy(intersection_strategy.get_side_strategy())\n        , m_area_strategy(intersection_strategy\n            .template get_area_strategy<point_type>())\n        , m_envelope_strategy(intersection_strategy.get_envelope_strategy())\n        , m_expand_strategy(intersection_strategy.get_expand_strategy())\n        , m_point_in_geometry_strategy(intersection_strategy\n            .template get_point_in_geometry_strategy<point_type, clockwise_ring_type>())\n        , m_robust_policy(robust_policy)\n    {}\n\n    inline bool is_following(buffer_turn_info_type const& turn,\n                             buffer_turn_operation_type const& op)\n    {\n        return turn.operations[0].seg_id.segment_index == op.seg_id.segment_index\n            || turn.operations[1].seg_id.segment_index == op.seg_id.segment_index;\n    }\n\n    // Verify if turns which are classified as OK (outside or on border of\n    // offsetted ring) do not traverse through other turns which are classified\n    // as WITHIN (inside a piece). This can happen if turns are nearly colocated\n    // and due to floating point precision just classified as within, while\n    // they should not be within.\n    // In those cases the turns are fine to travel through (and should),\n    // but they are not made startable.\n    template <typename Vector>\n    inline void pretraverse(Vector const& indexed_operations)\n    {\n        // Verify if the turns which are OK don't skip segments\n        typedef typename boost::range_value<Vector>::type indexed_type;\n        buffer_turn_operation_type last_traversable_operation;\n        buffer_turn_info_type last_traversable_turn;\n        bool first = true;\n        for (std::size_t i = 0; i < indexed_operations.size(); i++)\n        {\n            indexed_type const & itop = indexed_operations[i];\n            buffer_turn_info_type const& turn = m_turns[itop.turn_index];\n\n            if (turn.is_turn_traversable && ! first)\n            {\n               // Check previous and next turns. The first is handled\n               BOOST_GEOMETRY_ASSERT(i > 0);\n               indexed_type const& previous_itop = indexed_operations[i - 1];\n               std::size_t const next_index = i + 1 < indexed_operations.size() ? i + 1 : 0;\n               indexed_type const& next_itop = indexed_operations[next_index];\n\n               buffer_turn_info_type& previous_turn = m_turns[previous_itop.turn_index];\n               buffer_turn_info_type& next_turn = m_turns[next_itop.turn_index];\n\n               if (previous_turn.close_to_offset\n                   && is_following(previous_turn, last_traversable_operation))\n               {\n                   previous_turn.is_turn_traversable = true;\n               }\n               else if (next_turn.close_to_offset\n                        && is_following(next_turn, last_traversable_operation))\n               {\n                   next_turn.is_turn_traversable = true;\n               }\n            }\n\n            if (turn.is_turn_traversable)\n            {\n                first = false;\n                last_traversable_operation = *itop.subject;\n                last_traversable_turn = turn;\n            }\n        }\n    }\n\n    inline void check_linear_endpoints(buffer_turn_info_type& turn) const\n    {\n        // TODO this is quadratic. But the #endpoints, expected, is low,\n        // and only applicable for linear features\n        // (in a multi linestring with many short lines, the #endpoints can be\n        // much higher)\n        for (typename boost::range_iterator<std::vector<point_type> const>::type it\n             = boost::begin(m_linear_end_points);\n             it != boost::end(m_linear_end_points);\n             ++it)\n        {\n            if (detail::equals::equals_point_point(turn.point, *it,\n                            m_intersection_strategy.get_equals_point_point_strategy()))\n            {\n                turn.is_linear_end_point = true;\n            }\n        }\n    }\n\n    inline void verify_turns()\n    {\n        typedef detail::overlay::indexed_turn_operation\n            <\n                buffer_turn_operation_type\n            > indexed_turn_operation;\n        typedef std::map\n            <\n                ring_identifier,\n                std::vector<indexed_turn_operation>\n            > mapped_vector_type;\n        mapped_vector_type mapped_vector;\n\n        detail::overlay::create_map(m_turns, mapped_vector,\n                                    enriched_map_buffer_include_policy());\n\n        // Sort turns over offsetted ring(s)\n        for (typename mapped_vector_type::iterator mit\n            = mapped_vector.begin();\n            mit != mapped_vector.end();\n            ++mit)\n        {\n            std::sort(mit->second.begin(), mit->second.end(), buffer_less());\n        }\n\n        for (typename mapped_vector_type::iterator mit\n            = mapped_vector.begin();\n            mit != mapped_vector.end();\n            ++mit)\n        {\n            pretraverse(mit->second);\n        }\n    }\n\n    inline void deflate_check_turns()\n    {\n        if (! m_has_deflated)\n        {\n            return;\n        }\n\n        // Deflated rings may not travel to themselves, there should at least\n        // be three turns (which cannot be checked here - TODO: add to traverse)\n        for (typename boost::range_iterator<turn_vector_type>::type it =\n            boost::begin(m_turns); it != boost::end(m_turns); ++it)\n        {\n            buffer_turn_info_type& turn = *it;\n            if (! turn.is_turn_traversable)\n            {\n                continue;\n            }\n            for (int i = 0; i < 2; i++)\n            {\n                buffer_turn_operation_type& op = turn.operations[i];\n                if (op.enriched.get_next_turn_index() == static_cast<signed_size_type>(turn.turn_index)\n                    && m_pieces[op.seg_id.piece_index].is_deflated)\n                {\n                    // Keep traversable, but don't start here\n                    op.enriched.startable = false;\n                }\n            }\n        }\n    }\n\n    // Check if a turn is inside any of the originals\n    inline void check_turn_in_original()\n    {\n        typedef turn_in_original_ovelaps_box\n            <\n                typename IntersectionStrategy::disjoint_point_box_strategy_type\n            > turn_in_original_ovelaps_box_type;\n        typedef original_ovelaps_box\n            <\n                typename IntersectionStrategy::disjoint_box_box_strategy_type\n            > original_ovelaps_box_type;\n\n        turn_in_original_visitor\n            <\n                turn_vector_type,\n                point_in_geometry_strategy_type\n            > visitor(m_turns, m_point_in_geometry_strategy);\n\n        geometry::partition\n            <\n                box_type,\n                include_turn_policy,\n                detail::partition::include_all_policy\n            >::apply(m_turns, original_rings, visitor,\n                     turn_get_box(), turn_in_original_ovelaps_box_type(),\n                     original_get_box(), original_ovelaps_box_type());\n\n        bool const deflate = m_distance_strategy.negative();\n\n        for (typename boost::range_iterator<turn_vector_type>::type it =\n            boost::begin(m_turns); it != boost::end(m_turns); ++it)\n        {\n            buffer_turn_info_type& turn = *it;\n            if (turn.is_turn_traversable)\n            {\n                if (deflate && turn.count_in_original <= 0)\n                {\n                    // For deflate/negative buffers:\n                    // it is not in the original, so don't use it\n                    turn.is_turn_traversable = false;\n                }\n                else if (! deflate && turn.count_in_original > 0)\n                {\n                    // For inflate: it is in original, so don't use it\n                    turn.is_turn_traversable = false;\n                }\n            }\n        }\n    }\n\n    inline void update_turn_administration()\n    {\n        std::size_t index = 0;\n        for (typename boost::range_iterator<turn_vector_type>::type it =\n            boost::begin(m_turns); it != boost::end(m_turns); ++it, ++index)\n        {\n            buffer_turn_info_type& turn = *it;\n\n            // Update member used\n            turn.turn_index = index;\n\n            // Verify if a turn is a linear endpoint\n            if (! turn.is_linear_end_point)\n            {\n                check_linear_endpoints(turn);\n            }\n        }\n    }\n\n    // Calculate properties of piece borders which are not influenced\n    // by turns themselves:\n    // - envelopes (essential for partitioning during calc turns)\n    // - convexity\n    // - monotonicity\n    // - min/max radius of point buffers\n    // - (if pieces are reversed)\n    inline void update_piece_administration()\n    {\n        for (typename piece_vector_type::iterator it = boost::begin(m_pieces);\n            it != boost::end(m_pieces);\n            ++it)\n        {\n            piece& pc = *it;\n            piece_border_type& border = pc.m_piece_border;\n            buffered_ring<Ring> const& ring = offsetted_rings[pc.first_seg_id.multi_index];\n\n            if (pc.offsetted_count > 0)\n            {\n                if (pc.type != strategy::buffer::buffered_concave)\n                {\n                    border.set_offsetted(ring, pc.first_seg_id.segment_index,\n                                       pc.beyond_last_segment_index);\n                }\n\n                // Calculate envelopes for piece borders\n                border.get_properties_of_border(pc.type == geometry::strategy::buffer::buffered_point, pc.m_center);\n                if (! pc.is_flat_end && ! pc.is_flat_start)\n                {\n                    border.get_properties_of_offsetted_ring_part(m_side_strategy);\n                }\n            }\n        }\n    }\n\n    inline void get_turns()\n    {\n        update_piece_administration();\n\n        {\n            // Calculate the turns\n            piece_turn_visitor\n                <\n                    piece_vector_type,\n                    buffered_ring_collection<buffered_ring<Ring> >,\n                    turn_vector_type,\n                    IntersectionStrategy,\n                    RobustPolicy\n                > visitor(m_pieces, offsetted_rings, m_turns,\n                          m_intersection_strategy, m_robust_policy);\n\n            typedef detail::section::get_section_box\n                <\n                    typename IntersectionStrategy::expand_box_strategy_type\n                > get_section_box_type;\n            typedef detail::section::overlaps_section_box\n                <\n                    typename IntersectionStrategy::disjoint_box_box_strategy_type\n                > overlaps_section_box_type;\n\n            detail::sectionalize::enlarge_sections(monotonic_sections,\n                                                   m_envelope_strategy);\n            geometry::partition\n                <\n                    box_type\n                >::apply(monotonic_sections, visitor,\n                         get_section_box_type(),\n                         overlaps_section_box_type());\n        }\n\n        update_turn_administration();\n\n        {\n            // Check if turns are inside pieces\n            turn_in_piece_visitor\n                <\n                    typename geometry::cs_tag<point_type>::type,\n                    turn_vector_type, piece_vector_type, DistanceStrategy\n                > visitor(m_turns, m_pieces, m_distance_strategy);\n\n            typedef turn_ovelaps_box\n                <\n                    typename IntersectionStrategy::disjoint_point_box_strategy_type\n                > turn_ovelaps_box_type;\n            typedef piece_ovelaps_box\n                <\n                    typename IntersectionStrategy::disjoint_box_box_strategy_type\n                > piece_ovelaps_box_type;\n\n            geometry::partition\n                <\n                    box_type\n                >::apply(m_turns, m_pieces, visitor,\n                         turn_get_box(), turn_ovelaps_box_type(),\n                         piece_get_box(), piece_ovelaps_box_type());\n        }\n    }\n\n    inline void start_new_ring(bool deflate)\n    {\n        std::size_t const n = offsetted_rings.size();\n        current_segment_id.source_index = 0;\n        current_segment_id.multi_index = static_cast<signed_size_type>(n);\n        current_segment_id.ring_index = -1;\n        current_segment_id.segment_index = 0;\n\n        offsetted_rings.resize(n + 1);\n        original_rings.resize(n + 1);\n\n        m_first_piece_index = static_cast<signed_size_type>(boost::size(m_pieces));\n        m_deflate = deflate;\n        if (deflate)\n        {\n            // Pieces contain either deflated exterior rings, or inflated\n            // interior rings which are effectively deflated too\n            m_has_deflated = true;\n        }\n    }\n\n    inline void abort_ring()\n    {\n        // Remove all created pieces for this ring, sections, last offsetted\n        while (! m_pieces.empty()\n               && m_pieces.back().first_seg_id.multi_index\n               == current_segment_id.multi_index)\n        {\n            m_pieces.pop_back();\n        }\n\n        offsetted_rings.pop_back();\n        original_rings.pop_back();\n\n        m_first_piece_index = -1;\n    }\n\n    inline void update_last_point(point_type const& p,\n            buffered_ring<Ring>& ring)\n    {\n        // For the first point of a new piece, and there were already\n        // points in the offsetted ring, for some piece types the first point\n        // is a duplicate of the last point of the previous piece.\n\n        // TODO: disable that, that point should not be added\n\n        // For now, it is made equal because due to numerical instability,\n        // it can be a tiny bit off, possibly causing a self-intersection\n\n        BOOST_GEOMETRY_ASSERT(boost::size(m_pieces) > 0);\n        if (! ring.empty()\n            && current_segment_id.segment_index\n                == m_pieces.back().first_seg_id.segment_index)\n        {\n            ring.back() = p;\n        }\n    }\n\n    inline void set_piece_center(point_type const& center)\n    {\n        BOOST_GEOMETRY_ASSERT(! m_pieces.empty());\n        m_pieces.back().m_center = center;\n    }\n\n    inline bool finish_ring(strategy::buffer::result_code code)\n    {\n        if (code == strategy::buffer::result_error_numerical)\n        {\n            abort_ring();\n            return false;\n        }\n\n        if (m_first_piece_index == -1)\n        {\n            return false;\n        }\n\n        // Casted version\n        std::size_t const first_piece_index\n                = static_cast<std::size_t>(m_first_piece_index);\n        signed_size_type const last_piece_index\n                = static_cast<signed_size_type>(boost::size(m_pieces)) - 1;\n\n        if (first_piece_index < boost::size(m_pieces))\n        {\n            // If pieces were added,\n            // reassign left-of-first and right-of-last\n            geometry::range::at(m_pieces, first_piece_index).left_index\n                    = last_piece_index;\n            geometry::range::back(m_pieces).right_index = m_first_piece_index;\n        }\n\n        buffered_ring<Ring>& added = offsetted_rings.back();\n        if (! boost::empty(added))\n        {\n            // Make sure the closing point is identical (they are calculated\n            // separately by different pieces)\n            range::back(added) = range::front(added);\n        }\n\n        for (std::size_t i = first_piece_index; i < boost::size(m_pieces); i++)\n        {\n            sectionalize(m_pieces[i], added);\n        }\n\n        m_first_piece_index = -1;\n        return true;\n    }\n\n    template <typename InputRing>\n    inline void finish_ring(strategy::buffer::result_code code,\n                            InputRing const& input_ring,\n                            bool is_interior, bool has_interiors)\n    {\n        if (! finish_ring(code))\n        {\n            return;\n        }\n\n        if (! input_ring.empty())\n        {\n            // Assign the ring to the original_ring collection\n            // For rescaling, it is recalculated. Without rescaling, it\n            // is just assigning (note that this Ring type is the\n            // GeometryOut type, which might differ from the input ring type)\n            clockwise_ring_type clockwise_ring;\n\n            typedef detail::normalized_view<InputRing const> view_type;\n            view_type const view(input_ring);\n\n            for (typename boost::range_iterator<view_type const>::type it =\n                boost::begin(view); it != boost::end(view); ++it)\n            {\n                clockwise_ring.push_back(*it);\n            }\n\n            original_rings.back()\n                = original_ring(clockwise_ring,\n                    is_interior, has_interiors,\n                    m_envelope_strategy, m_expand_strategy);\n        }\n    }\n\n    inline void set_current_ring_concave()\n    {\n        BOOST_GEOMETRY_ASSERT(boost::size(offsetted_rings) > 0);\n        offsetted_rings.back().has_concave = true;\n    }\n\n    inline signed_size_type add_point(point_type const& p)\n    {\n        BOOST_GEOMETRY_ASSERT(boost::size(offsetted_rings) > 0);\n\n        buffered_ring<Ring>& current_ring = offsetted_rings.back();\n        update_last_point(p, current_ring);\n\n        current_segment_id.segment_index++;\n        current_ring.push_back(p);\n        return static_cast<signed_size_type>(current_ring.size());\n    }\n\n    //-------------------------------------------------------------------------\n\n    inline piece& create_piece(strategy::buffer::piece_type type,\n            bool decrease_segment_index_by_one)\n    {\n        if (type == strategy::buffer::buffered_concave)\n        {\n            offsetted_rings.back().has_concave = true;\n        }\n\n        piece pc;\n        pc.type = type;\n        pc.index = static_cast<signed_size_type>(boost::size(m_pieces));\n        pc.is_deflated = m_deflate;\n\n        current_segment_id.piece_index = pc.index;\n\n        pc.first_seg_id = current_segment_id;\n\n        // Assign left/right (for first/last piece per ring they will be re-assigned later)\n        pc.left_index = pc.index - 1;\n        pc.right_index = pc.index + 1;\n\n        std::size_t const n = boost::size(offsetted_rings.back());\n        pc.first_seg_id.segment_index = decrease_segment_index_by_one ? n - 1 : n;\n        pc.beyond_last_segment_index = pc.first_seg_id.segment_index;\n\n        m_pieces.push_back(pc);\n        return m_pieces.back();\n    }\n\n    inline void init_rescale_piece(piece& pc)\n    {\n        if (pc.first_seg_id.segment_index < 0)\n        {\n            // This indicates an error situation: an earlier piece was empty\n            // It currently does not happen\n            pc.offsetted_count = 0;\n            return;\n        }\n\n        BOOST_GEOMETRY_ASSERT(pc.first_seg_id.multi_index >= 0);\n        BOOST_GEOMETRY_ASSERT(pc.beyond_last_segment_index >= 0);\n\n        pc.offsetted_count = pc.beyond_last_segment_index - pc.first_seg_id.segment_index;\n        BOOST_GEOMETRY_ASSERT(pc.offsetted_count >= 0);\n    }\n\n    inline void add_piece_point(piece& pc, const point_type& point, bool add_to_original)\n    {\n        if (add_to_original && pc.type != strategy::buffer::buffered_concave)\n        {\n            pc.m_piece_border.add_original_point(point);\n        }\n        else\n        {\n            pc.m_label_point = point;\n        }\n    }\n\n    inline void sectionalize(piece const& pc, buffered_ring<Ring> const& ring)\n    {\n        typedef geometry::detail::sectionalize::sectionalize_part\n        <\n            point_type,\n            boost::mpl::vector_c<std::size_t, 0, 1> // x,y dimension\n        > sectionalizer;\n\n        // Create a ring-identifier. The source-index is the piece index\n        // The multi_index is as in this collection (the ring), but not used here\n        // The ring_index is not used\n        ring_identifier const ring_id(pc.index, pc.first_seg_id.multi_index, -1);\n\n        sectionalizer::apply(monotonic_sections,\n            boost::begin(ring) + pc.first_seg_id.segment_index,\n            boost::begin(ring) + pc.beyond_last_segment_index,\n            m_robust_policy,\n            ring_id, 10);\n    }\n\n    inline void finish_piece(piece& pc)\n    {\n        init_rescale_piece(pc);\n    }\n\n    inline void finish_piece(piece& pc,\n                    point_type const& point1,\n                    point_type const& point2,\n                    point_type const& point3)\n    {\n        init_rescale_piece(pc);\n        if (pc.offsetted_count == 0)\n        {\n            return;\n        }\n\n        add_piece_point(pc, point1, false);\n        add_piece_point(pc, point2, true);\n        add_piece_point(pc, point3, false);\n    }\n\n    inline void finish_piece(piece& pc,\n                    point_type const& point1,\n                    point_type const& point2,\n                    point_type const& point3,\n                    point_type const& point4)\n    {\n        init_rescale_piece(pc);\n\n        // Add the four points. Note that points 2 and 3 are the originals,\n        // and that they are already passed in reverse order\n        // (because the offsetted ring is in clockwise order)\n        add_piece_point(pc, point1, false);\n        add_piece_point(pc, point2, true);\n        add_piece_point(pc, point3, true);\n        add_piece_point(pc, point4, false);\n    }\n\n    template <typename Range>\n    inline void add_range_to_piece(piece& pc, Range const& range, bool add_front)\n    {\n        BOOST_GEOMETRY_ASSERT(boost::size(range) != 0u);\n\n        typename Range::const_iterator it = boost::begin(range);\n\n        // If it follows a non-join (so basically the same piece-type) point b1 should be added.\n        // There should be two intersections later and it should be discarded.\n        // But for now we need it to calculate intersections\n        if (add_front)\n        {\n            add_point(*it);\n        }\n\n        for (++it; it != boost::end(range); ++it)\n        {\n            pc.beyond_last_segment_index = add_point(*it);\n        }\n    }\n\n    inline void add_piece(strategy::buffer::piece_type type, point_type const& p,\n            point_type const& b1, point_type const& b2)\n    {\n        piece& pc = create_piece(type, false);\n        add_point(b1);\n        pc.beyond_last_segment_index = add_point(b2);\n        finish_piece(pc, b2, p, b1);\n    }\n\n    template <typename Range>\n    inline void add_piece(strategy::buffer::piece_type type, Range const& range,\n            bool decrease_segment_index_by_one)\n    {\n        piece& pc = create_piece(type, decrease_segment_index_by_one);\n\n        if (boost::size(range) > 0u)\n        {\n            add_range_to_piece(pc, range, offsetted_rings.back().empty());\n        }\n        finish_piece(pc);\n    }\n\n    template <typename Range>\n    inline void add_piece(strategy::buffer::piece_type type,\n            point_type const& p, Range const& range)\n    {\n        piece& pc = create_piece(type, true);\n\n        if (boost::size(range) > 0u)\n        {\n            add_range_to_piece(pc, range, offsetted_rings.back().empty());\n            finish_piece(pc, range.back(), p, range.front());\n        }\n        else\n        {\n            finish_piece(pc);\n        }\n    }\n\n    template <typename Range>\n    inline void add_side_piece(point_type const& original_point1,\n            point_type const& original_point2,\n            Range const& range, bool first)\n    {\n        BOOST_GEOMETRY_ASSERT(boost::size(range) >= 2u);\n\n        piece& pc = create_piece(strategy::buffer::buffered_segment, ! first);\n        add_range_to_piece(pc, range, first);\n\n        // Add the four points of the side, starting with the last point of the\n        // range, and reversing the order of the originals to keep it clockwise\n        finish_piece(pc, range.back(), original_point2, original_point1, range.front());\n    }\n\n    template <typename EndcapStrategy, typename Range>\n    inline void add_endcap(EndcapStrategy const& strategy, Range const& range,\n            point_type const& end_point)\n    {\n        boost::ignore_unused(strategy);\n\n        if (range.empty())\n        {\n            return;\n        }\n        strategy::buffer::piece_type pt = strategy.get_piece_type();\n        if (pt == strategy::buffer::buffered_flat_end)\n        {\n            // It is flat, should just be added, without helper segments\n            add_piece(pt, range, true);\n        }\n        else\n        {\n            // Normal case, it has an \"inside\", helper segments should be added\n            add_piece(pt, end_point, range);\n        }\n    }\n\n    inline void mark_flat_start(point_type const& point)\n    {\n        if (! m_pieces.empty())\n        {\n            piece& back = m_pieces.back();\n            back.is_flat_start = true;\n\n            // This happens to linear buffers, and it will be the very\n            // first or last point. If that coincides with a turn,\n            // and the turn was marked as ON_BORDER\n            // the turn should NOT be within (even though it can be marked\n            // as such)\n            m_linear_end_points.push_back(point);\n        }\n    }\n\n    inline void mark_flat_end(point_type const& point)\n    {\n        if (! m_pieces.empty())\n        {\n            piece& back = m_pieces.back();\n            back.is_flat_end = true;\n            m_linear_end_points.push_back(point);\n        }\n    }\n\n    //-------------------------------------------------------------------------\n\n    inline void enrich()\n    {\n        enrich_intersection_points<false, false, overlay_buffer>(m_turns,\n            m_clusters, offsetted_rings, offsetted_rings,\n            m_robust_policy,\n            m_intersection_strategy);\n    }\n\n    // Discards all rings which do have not-OK intersection points only.\n    // Those can never be traversed and should not be part of the output.\n    inline void discard_rings()\n    {\n        for (typename boost::range_iterator<turn_vector_type const>::type it =\n            boost::begin(m_turns); it != boost::end(m_turns); ++it)\n        {\n            if (it->is_turn_traversable)\n            {\n                offsetted_rings[it->operations[0].seg_id.multi_index].has_accepted_intersections = true;\n                offsetted_rings[it->operations[1].seg_id.multi_index].has_accepted_intersections = true;\n            }\n            else\n            {\n                offsetted_rings[it->operations[0].seg_id.multi_index].has_discarded_intersections = true;\n                offsetted_rings[it->operations[1].seg_id.multi_index].has_discarded_intersections = true;\n            }\n        }\n    }\n\n    inline bool point_coveredby_original(point_type const& point)\n    {\n        typedef typename IntersectionStrategy::disjoint_point_box_strategy_type d_pb_strategy_type;\n\n        signed_size_type count_in_original = 0;\n\n        // Check of the robust point of this outputted ring is in\n        // any of the robust original rings\n        // This can go quadratic if the input has many rings, and there\n        // are many untouched deflated rings around\n        for (typename std::vector<original_ring>::const_iterator it\n            = original_rings.begin();\n            it != original_rings.end();\n            ++it)\n        {\n            original_ring const& original = *it;\n            if (original.m_ring.empty())\n            {\n                continue;\n            }\n            if (detail::disjoint::disjoint_point_box(point,\n                                                     original.m_box,\n                                                     d_pb_strategy_type()))\n            {\n                continue;\n            }\n\n            int const geometry_code\n                = detail::within::point_in_geometry(point,\n                    original.m_ring, m_point_in_geometry_strategy);\n\n            if (geometry_code == -1)\n            {\n                // Outside, continue\n                continue;\n            }\n\n            // Apply for possibly nested interior rings\n            if (original.m_is_interior)\n            {\n                count_in_original--;\n            }\n            else if (original.m_has_interiors)\n            {\n                count_in_original++;\n            }\n            else\n            {\n                // Exterior ring without interior rings\n                return true;\n            }\n        }\n        return count_in_original > 0;\n    }\n\n    // For a deflate, all rings around inner rings which are untouched\n    // (no intersections/turns) and which are OUTSIDE the original should\n    // be discarded\n    inline void discard_nonintersecting_deflated_rings()\n    {\n        for(typename buffered_ring_collection<buffered_ring<Ring> >::iterator it\n            = boost::begin(offsetted_rings);\n            it != boost::end(offsetted_rings);\n            ++it)\n        {\n            buffered_ring<Ring>& ring = *it;\n            if (! ring.has_intersections()\n                && boost::size(ring) > 0u\n                && geometry::area(ring, m_area_strategy) < 0)\n            {\n                if (! point_coveredby_original(geometry::range::front(ring)))\n                {\n                    ring.is_untouched_outside_original = true;\n                }\n            }\n        }\n    }\n\n    inline void block_turns()\n    {\n        for (typename boost::range_iterator<turn_vector_type>::type it =\n            boost::begin(m_turns); it != boost::end(m_turns); ++it)\n        {\n            buffer_turn_info_type& turn = *it;\n            if (! turn.is_turn_traversable)\n            {\n                // Discard this turn (don't set it to blocked to avoid colocated\n                // clusters being discarded afterwards\n                turn.discarded = true;\n            }\n        }\n    }\n\n    inline void traverse()\n    {\n        typedef detail::overlay::traverse\n            <\n                false, false,\n                buffered_ring_collection<buffered_ring<Ring> >,\n                buffered_ring_collection<buffered_ring<Ring > >,\n                overlay_buffer,\n                backtrack_for_buffer\n            > traverser;\n        std::map<ring_identifier, overlay::ring_turn_info> turn_info_per_ring;\n\n        traversed_rings.clear();\n        buffer_overlay_visitor visitor;\n        traverser::apply(offsetted_rings, offsetted_rings,\n                        m_intersection_strategy, m_robust_policy,\n                        m_turns, traversed_rings,\n                        turn_info_per_ring,\n                        m_clusters, visitor);\n    }\n\n    inline void reverse()\n    {\n        for(typename buffered_ring_collection<buffered_ring<Ring> >::iterator it = boost::begin(offsetted_rings);\n            it != boost::end(offsetted_rings);\n            ++it)\n        {\n            if (! it->has_intersections())\n            {\n                std::reverse(it->begin(), it->end());\n            }\n        }\n        for (typename boost::range_iterator<buffered_ring_collection<Ring> >::type\n                it = boost::begin(traversed_rings);\n                it != boost::end(traversed_rings);\n                ++it)\n        {\n            std::reverse(it->begin(), it->end());\n        }\n    }\n\n    template <typename GeometryOutput, typename OutputIterator>\n    inline OutputIterator assign(OutputIterator out) const\n    {\n        typedef detail::overlay::ring_properties<point_type, area_result_type> properties;\n\n        std::map<ring_identifier, properties> selected;\n\n        // Select all rings which do not have any self-intersection\n        // Inner rings, for deflate, which do not have intersections, and\n        // which are outside originals, are skipped\n        // (other ones should be traversed)\n        signed_size_type index = 0;\n        for(typename buffered_ring_collection<buffered_ring<Ring> >::const_iterator it = boost::begin(offsetted_rings);\n            it != boost::end(offsetted_rings);\n            ++it, ++index)\n        {\n            if (! it->has_intersections()\n                && ! it->is_untouched_outside_original)\n            {\n                properties p = properties(*it, m_area_strategy);\n                if (p.valid)\n                {\n                    ring_identifier id(0, index, -1);\n                    selected[id] = p;\n                }\n            }\n        }\n\n        // Select all created rings\n        index = 0;\n        for (typename boost::range_iterator<buffered_ring_collection<Ring> const>::type\n                it = boost::begin(traversed_rings);\n                it != boost::end(traversed_rings);\n                ++it, ++index)\n        {\n            properties p = properties(*it, m_area_strategy);\n            if (p.valid)\n            {\n                ring_identifier id(2, index, -1);\n                selected[id] = p;\n            }\n        }\n\n        detail::overlay::assign_parents<overlay_buffer>(offsetted_rings, traversed_rings,\n                selected, m_intersection_strategy);\n        return detail::overlay::add_rings<GeometryOutput>(selected, offsetted_rings, traversed_rings, out,\n                                                          m_area_strategy);\n    }\n\n};\n\n\n}} // namespace detail::buffer\n#endif // DOXYGEN_NO_DETAIL\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFERED_PIECE_COLLECTION_HPP\n", "meta": {"hexsha": "438921be528d3e90c9075fef6efa2c1b8465a264", "size": 43881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/geometry/algorithms/detail/buffer/buffered_piece_collection.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/geometry/algorithms/detail/buffer/buffered_piece_collection.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/geometry/algorithms/detail/buffer/buffered_piece_collection.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": 34.9928229665, "max_line_length": 119, "alphanum_fraction": 0.5981860031, "num_tokens": 9183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.18998547181309172}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\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_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP\r\n#define BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP\r\n\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/select_calculation_type.hpp>\r\n\r\n#include <boost/geometry/strategies/side.hpp>\r\n#include <boost/geometry/strategies/within.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace within\r\n{\r\n\r\n/*!\r\n\\brief Within detection using winding rule\r\n\\ingroup strategies\r\n\\tparam Point \\tparam_point\r\n\\tparam PointOfSegment \\tparam_segment_point\r\n\\tparam CalculationType \\tparam_calculation\r\n\\author Barend Gehrels\r\n\\note The implementation is inspired by terralib http://www.terralib.org (LGPL)\r\n\\note but totally revised afterwards, especially for cases on segments\r\n\\note Only dependant on \"side\", -> agnostic, suitable for spherical/latlong\r\n\r\n\\qbk{\r\n[heading See also]\r\n[link geometry.reference.algorithms.within.within_3_with_strategy within (with strategy)]\r\n}\r\n */\r\ntemplate\r\n<\r\n    typename Point,\r\n    typename PointOfSegment = Point,\r\n    typename CalculationType = void\r\n>\r\nclass winding\r\n{\r\n    typedef typename select_calculation_type\r\n        <\r\n            Point,\r\n            PointOfSegment,\r\n            CalculationType\r\n        >::type calculation_type;\r\n\r\n\r\n    typedef typename strategy::side::services::default_strategy\r\n        <\r\n            typename cs_tag<Point>::type\r\n        >::type strategy_side_type;\r\n\r\n\r\n    /*! subclass to keep state */\r\n    class counter\r\n    {\r\n        int m_count;\r\n        bool m_touches;\r\n\r\n        inline int code() const\r\n        {\r\n            return m_touches ? 0 : m_count == 0 ? -1 : 1;\r\n        }\r\n\r\n    public :\r\n        friend class winding;\r\n\r\n        inline counter()\r\n            : m_count(0)\r\n            , m_touches(false)\r\n        {}\r\n\r\n    };\r\n\r\n\r\n    template <size_t D>\r\n    static inline int check_touch(Point const& point,\r\n                PointOfSegment const& seg1, PointOfSegment const& seg2,\r\n                counter& state)\r\n    {\r\n        calculation_type const p = get<D>(point);\r\n        calculation_type const s1 = get<D>(seg1);\r\n        calculation_type const s2 = get<D>(seg2);\r\n        if ((s1 <= p && s2 >= p) || (s2 <= p && s1 >= p))\r\n        {\r\n            state.m_touches = true;\r\n        }\r\n        return 0;\r\n    }\r\n\r\n\r\n    template <size_t D>\r\n    static inline int check_segment(Point const& point,\r\n                PointOfSegment const& seg1, PointOfSegment const& seg2,\r\n                counter& state)\r\n    {\r\n        calculation_type const p = get<D>(point);\r\n        calculation_type const s1 = get<D>(seg1);\r\n        calculation_type const s2 = get<D>(seg2);\r\n\r\n        // Check if one of segment endpoints is at same level of point\r\n        bool eq1 = math::equals(s1, p);\r\n        bool eq2 = math::equals(s2, p);\r\n\r\n        if (eq1 && eq2)\r\n        {\r\n            // Both equal p -> segment is horizontal (or vertical for D=0)\r\n            // The only thing which has to be done is check if point is ON segment\r\n            return check_touch<1 - D>(point, seg1, seg2,state);\r\n        }\r\n\r\n        return\r\n              eq1 ? (s2 > p ?  1 : -1)  // Point on level s1, UP/DOWN depending on s2\r\n            : eq2 ? (s1 > p ? -1 :  1)  // idem\r\n            : s1 < p && s2 > p ?  2     // Point between s1 -> s2 --> UP\r\n            : s2 < p && s1 > p ? -2     // Point between s2 -> s1 --> DOWN\r\n            : 0;\r\n    }\r\n\r\n\r\n\r\n\r\npublic :\r\n\r\n    // Typedefs and static methods to fulfill the concept\r\n    typedef Point point_type;\r\n    typedef PointOfSegment segment_point_type;\r\n    typedef counter state_type;\r\n\r\n    static inline bool apply(Point const& point,\r\n                PointOfSegment const& s1, PointOfSegment const& s2,\r\n                counter& state)\r\n    {\r\n        int count = check_segment<1>(point, s1, s2, state);\r\n        if (count != 0)\r\n        {\r\n            int side = strategy_side_type::apply(s1, s2, point);\r\n            if (side == 0)\r\n            {\r\n                // Point is lying on segment\r\n                state.m_touches = true;\r\n                state.m_count = 0;\r\n                return false;\r\n            }\r\n\r\n            // Side is NEG for right, POS for left.\r\n            // The count is -2 for down, 2 for up (or -1/1)\r\n            // Side positive thus means UP and LEFTSIDE or DOWN and RIGHTSIDE\r\n            // See accompagnying figure (TODO)\r\n            if (side * count > 0)\r\n            {\r\n                state.m_count += count;\r\n            }\r\n        }\r\n        return ! state.m_touches;\r\n    }\r\n\r\n    static inline int result(counter const& state)\r\n    {\r\n        return state.code();\r\n    }\r\n};\r\n\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\nnamespace services\r\n{\r\n\r\n// Register using \"areal_tag\" for ring, polygon, multi-polygon\r\ntemplate <typename Point, typename PointOfSegment>\r\nstruct default_strategy<point_tag, areal_tag, cartesian_tag, cartesian_tag, Point, PointOfSegment>\r\n{\r\n    typedef winding<Point, PointOfSegment> type;\r\n};\r\n\r\ntemplate <typename Point, typename PointOfSegment>\r\nstruct default_strategy<point_tag, areal_tag, spherical_polar_tag, spherical_polar_tag, Point, PointOfSegment>\r\n{\r\n    typedef winding<Point, PointOfSegment> type;\r\n};\r\n\r\ntemplate <typename Point, typename PointOfSegment>\r\nstruct default_strategy<point_tag, areal_tag, spherical_equatorial_tag, spherical_equatorial_tag, Point, PointOfSegment>\r\n{\r\n    typedef winding<Point, PointOfSegment> type;\r\n};\r\n\r\n} // namespace services\r\n\r\n#endif\r\n\r\n\r\n}} // namespace strategy::within\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP\r\n", "meta": {"hexsha": "a3645c9f3f77413d556739032caf51dd6ded1ada", "size": 6150, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependencies/boost_geometry/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_stars_repo_name": "bobzabcik/OpenStudio", "max_stars_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_stars_repo_licenses": ["blessing"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dependencies/boost_geometry/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_issues_repo_name": "bobzabcik/OpenStudio", "max_issues_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "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": "dependencies/boost_geometry/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_forks_repo_name": "bobzabcik/OpenStudio", "max_forks_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.738317757, "max_line_length": 121, "alphanum_fraction": 0.6108943089, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.18998546820621817}}
{"text": "#include <jni.h>\n\n#include <atomic>\n#include <cassert>\n#include <memory>\n\n#include <fstream>\n#include <Eigen/Dense>\n#include \"logging.hpp\"\n#include <nlohmann/json.hpp>\n#include \"algorithm_module.hpp\"\n#include \"jniutil.hpp\"\n\nusing nlohmann::json;\n\nnamespace {\n    bool recordExternalPoses = false;\n    int frameStride = 1;\n    int frameNumber = 0;\n\n    json settingsJson;\n    std::shared_ptr<AlgorithmModule> algorithmPtr;\n\n    class Clock {\n    public:\n        double convert(int64_t tNanos) const {\n            return (tNanos - t0) * 1e-9 + MARGIN;\n        }\n\n        Clock(int64_t t = 0) : t0(t) {}\n\n    private:\n        /**\n         * Time in seconds to add to the beginning to avoid negative timestamps\n         * caused by possible unordered samples in the beginning\n         */\n        static constexpr double MARGIN = 0.01;\n        const int64_t t0;\n    };\n\n    std::unique_ptr<Clock> doubleClock;\n}\n\nextern \"C\" {\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_nativeStop(JNIEnv *, jobject) {\n    log_debug(\"nativeStop\");\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) {\n        log_warn(\"Expected algorithm to exist at this point\");\n        return;\n    }\n    std::atomic_store(&algorithmPtr, std::shared_ptr<AlgorithmModule>(nullptr));\n    // dtor may be called here\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_configureVisualization(\n        JNIEnv *, jobject,\n        jint visuWidth, jint visuHeight) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) {\n        // happens on external AR. TODO: hacky\n        log_warn(\"no algorithm, ignoring configureVisualization\");\n        return;\n    }\n    log_debug(\"configureVisualization(%d, %d)\", visuWidth, visuHeight);\n    algorithm->setupRendering(visuWidth, visuHeight);\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_configure(\n        JNIEnv *env, jobject,\n        jlong timeNanos,\n        jint width,\n        jint height,\n        jint textureId,\n        jint frameStrideJint,\n        jboolean recordExternalPosesJboolean,\n        jstring moduleNameJava,\n        jstring moduleSettingsJson) {\n\n    std::atomic_store(&algorithmPtr, std::shared_ptr<AlgorithmModule>(nullptr));\n    doubleClock = std::make_unique<Clock>(timeNanos);\n\n    frameNumber = 0;\n    frameStride = static_cast<int>(frameStrideJint);\n    recordExternalPoses = recordExternalPosesJboolean;\n\n    assert(width >= height);\n\n    const std::string moduleName = getStringOrEmpty(env, moduleNameJava);\n    log_info(\"initializing %s\", moduleName.c_str());\n    json *settingsJsonPtr = nullptr;\n    const std::string settingsString = getStringOrEmpty(env, moduleSettingsJson);\n    if (!settingsString.empty()) {\n        settingsJson = json::parse(settingsString);\n        log_debug(\"json settings\\n%s\", settingsJson.dump(2).c_str());\n        settingsJsonPtr = &settingsJson;\n    }\n\n    auto ptr = AlgorithmModule::build(textureId, width, height, moduleName, settingsJsonPtr);\n    std::atomic_store(&algorithmPtr, std::shared_ptr<AlgorithmModule>(std::move(ptr)));\n}\n\nJNIEXPORT jboolean JNICALL Java_org_example_viotester_AlgorithmWorker_processFrame(\n        JNIEnv *, jobject,\n        jlong timeNanos,\n        jint cameraInd,\n        jfloat fx,\n        jfloat fy,\n        jfloat px,\n        jfloat py) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return false;\n\n    if ((frameNumber++ % frameStride) != 0) return false;\n\n    AlgorithmModule::CameraIntrinsics cam {\n        .cameraIndex = cameraInd,\n        .focalLengthX = fx,\n        .focalLengthY = fy,\n        .principalPointX = px,\n        .principalPointY = py\n    };\n    algorithm->addFrame(doubleClock->convert(timeNanos), cam);\n    return true;\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_processGyroSample(\n        JNIEnv*, jobject,\n        jlong timeNanos, jfloat x, jfloat y, jfloat z) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return;\n\n    algorithm->addGyro(doubleClock->convert(timeNanos), { x, y, z });\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_processAccSample(\n        JNIEnv*, jobject,\n        jlong timeNanos, jfloat x, jfloat y, jfloat z) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return;\n    algorithm->addAcc(doubleClock->convert(timeNanos), { x, y, z });\n}\n\nJNIEXPORT jstring JNICALL Java_org_example_viotester_AlgorithmWorker_getStatsString(\n        JNIEnv *env, jobject) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (algorithm) return env->NewStringUTF(algorithm->status().c_str());\n    return nullptr;\n}\n\nJNIEXPORT jint JNICALL Java_org_example_viotester_AlgorithmWorker_getTrackingStatus(\n        JNIEnv *, jobject) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (algorithm) return algorithm->trackingStatus();\n    return -1;\n}\n\nJNIEXPORT jdoubleArray JNICALL Java_org_example_viotester_AlgorithmWorker_getPose(\n        JNIEnv *env, jobject) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (algorithm) {\n        recorder::Pose pose;\n        bool hasPose = algorithm->pose(pose);\n        if (!hasPose) {\n            return NULL;\n        }\n        jdoubleArray result = env->NewDoubleArray(8);\n        jdouble buf[8];\n        buf[0] = pose.time;\n        buf[1] = pose.position.x;\n        buf[2] = pose.position.y;\n        buf[3] = pose.position.z;\n        buf[4] = pose.orientation.x;\n        buf[5] = pose.orientation.y;\n        buf[6] = pose.orientation.z;\n        buf[7] = pose.orientation.w;\n        env->SetDoubleArrayRegion(result, 0, 8, buf);\n        return result;\n    }\n    return NULL;\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_drawVisualization(JNIEnv *, jobject, jlong timeNanos) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return;\n    algorithm->render(doubleClock->convert(timeNanos));\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_processGpsLocation(JNIEnv *, jobject, jlong timeNanos, jdouble lat, jdouble lon, jdouble alt, jfloat acc) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return;\n    algorithm->addGps(doubleClock->convert(timeNanos), AlgorithmModule::Gps {\n            .latitude = lat,\n            .longitude = lon,\n            .altitude = alt,\n            .accuracy = acc\n    });\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_processGpsTime(JNIEnv *, jobject, jlong timeNanos, jdouble gpsTimeUtcSeconds) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return;\n    const double t = doubleClock->convert(timeNanos);\n    algorithm->addJsonData(\n            AlgorithmModule::json {\n                    { \"time\", t },\n                    { \"gpsTime\",\n                              {\n                                      { \"utcSeconds\", gpsTimeUtcSeconds }\n                              }\n                    }\n            });\n}\n\nJNIEXPORT jdouble JNICALL Java_org_example_viotester_AlgorithmWorker_convertTime(JNIEnv *, jobject, jlong timeNanos) {\n    return doubleClock->convert(timeNanos);\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_writeInfoFile(\n        JNIEnv* env, jobject,\n        jstring mode, jstring device) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return;\n\n    std::string infoFile = !settingsJson.at(\"infoFileName\").is_null() ? settingsJson.at(\"infoFileName\") : \"\";\n    if (infoFile.empty())\n        return;\n    json infoJson = R\"(\n            {\n                \"camera mode\": \"\",\n                \"device\": \"\",\n                \"tags\": [\n                    \"android\"\n                ]\n            }\n        )\"_json;\n    infoJson[\"camera mode\"] = getStringOrEmpty(env, mode);\n    infoJson[\"device\"] = getStringOrEmpty(env, device);\n    std::ofstream fileOutput(infoFile);\n    fileOutput << infoJson.dump() << std::endl;\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_writeParamsFile(\n        JNIEnv*, jobject) {\n    std::string paramsFile = !settingsJson.at(\"parametersFileName\").is_null() ? settingsJson.at(\"parametersFileName\") : \"\";\n    if (paramsFile.empty())\n        return;\n    std::ofstream fileOutput(paramsFile);\n    fileOutput << \"imuToCameraMatrix -0,-1,0,-1,0,0,0,0,-1;\" << std::endl;\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_processExternalImage(JNIEnv *, jobject,\n        jlong timeNs, jlong frameNumber, jint cameraInd, jfloat fx, jfloat fy, jfloat ppx, jfloat ppy) {\n    (void)frameNumber;\n    AlgorithmModule::CameraIntrinsics cam {\n            .cameraIndex = cameraInd,\n            .focalLengthX = fx,\n            .focalLengthY = fy,\n            .principalPointX = ppx,\n            .principalPointY = ppy\n    };\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return;\n    algorithm->addFrame(doubleClock->convert(timeNs), cam);\n}\n\nJNIEXPORT void JNICALL Java_org_example_viotester_AlgorithmWorker_recordPoseMatrix(JNIEnv *env, jobject, jlong timeNs, jfloatArray pose, jstring tag) {\n    auto algorithm = std::atomic_load(&algorithmPtr);\n    if (!algorithm) return;\n    if (!recordExternalPoses) return;\n\n    auto *poseArr = env->GetFloatArrayElements(pose, nullptr);\n    Eigen::Matrix4f viewMatrix = Eigen::Map<Eigen::Matrix4f>(poseArr);\n    env->ReleaseFloatArrayElements(pose, poseArr, JNI_ABORT);\n\n    const double t = doubleClock->convert(timeNs);\n\n    const Eigen::Matrix3f R = viewMatrix.block<3, 3>(0, 0);\n    const Eigen::Vector3f p = -R.transpose() * viewMatrix.block<3, 1>(0, 3);\n    const Eigen::Quaternionf q(R);\n\n    algorithm->addJsonData(\n            AlgorithmModule::json {\n                    // Android Studio thinks this indentation is pretty and refuses to change\n                    // so let's keep it that way\n                    { \"time\", t },\n                    { getStringOrEmpty(env, tag).c_str(),\n                              {\n                                      { \"position\",\n                                              {\n                                                      { \"x\", p.x() },\n                                                      { \"y\", p.y() },\n                                                      { \"z\", p.z() }\n                                              }\n                                      },\n                                      { \"orientation\",\n                                              {\n                                                      { \"w\", q.w() },\n                                                      { \"x\", q.x() },\n                                                      { \"y\", q.y() },\n                                                      { \"z\", q.z() }\n                                              }\n                                      }\n                              }\n                    }\n            });\n}\n}\n", "meta": {"hexsha": "ca86d4a73efadd06619c45d96f02c5317f841e4d", "size": 10964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/src/main/jni/algorithm_worker.cpp", "max_stars_repo_name": "AaltoML/android-viotester", "max_stars_repo_head_hexsha": "055ef11e2ac9b070bb9230c6eadd99cc991b318d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-09-13T02:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:54:28.000Z", "max_issues_repo_path": "app/src/main/jni/algorithm_worker.cpp", "max_issues_repo_name": "AaltoML/android-viotester", "max_issues_repo_head_hexsha": "055ef11e2ac9b070bb9230c6eadd99cc991b318d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-06-16T07:49:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-11T12:54:23.000Z", "max_forks_repo_path": "app/src/main/jni/algorithm_worker.cpp", "max_forks_repo_name": "AaltoML/android-viotester", "max_forks_repo_head_hexsha": "055ef11e2ac9b070bb9230c6eadd99cc991b318d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-08T09:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:54:14.000Z", "avg_line_length": 35.3677419355, "max_line_length": 173, "alphanum_fraction": 0.6025173294, "num_tokens": 2446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18998546820621814}}
{"text": "#include <GL/glew.h>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include <gflags/gflags.h>\n#include <vector>\n#include <array>\n#include <json/json.h>\n#include <simple.h>\n#include \"totalmodel.h\"\n#include <FitToBody.h>\n#include <VisualizedData.h>\n#include <Renderer.h>\n#include <KinematicModel.h>\n#include <cassert>\n#include <opencv2/highgui/highgui.hpp>\n#include <GL/freeglut.h>\n#include <pose_to_transforms.h>\n#include \"meshTrackingProj.h\"\n#include \"SGSmooth.hpp\"\n#include \"ModelFitter.h\"\n#include \"utils.h\"\n#include <thread>\n#include <boost/filesystem.hpp>\n#include <BVHWriter.h>\n\n#define ROWS 1080\n#define COLS 1920\n#define FACE_VERIFY_THRESH 0.05\n#define PI 3.14159265359\n\nTotalModel g_total_model;\n\nint main()\n{\n\t// initialize total model\n    LoadTotalModelFromObj(g_total_model, std::string(\"model/mesh_nofeet.obj\"));\n    LoadModelColorFromObj(g_total_model, std::string(\"model/nofeetmesh_byTomas_bottom.obj\"));  // contain the color information\n    LoadTotalDataFromJson(g_total_model, std::string(\"model/adam_v1_plus2.json\"), std::string(\"model/adam_blendshapes_348_delta_norm.json\"), std::string(\"model/correspondences_nofeet.txt\"));\n    LoadCocoplusRegressor(g_total_model, std::string(\"model/regressor_0n1_root.json\"));\n\n    // use the skeleton of the first frame\n\tconst std::string param_filename = \"/home/evonneng/Documents/research/ssp/tools/bvh-parser/output/body_3d_frontal/0001.txt\";\n\tsmpl::SMPLParams frame_params;\n\treadFrameParam(param_filename, frame_params);\n\tEigen::VectorXd J_vec = g_total_model.J_mu_ + g_total_model.dJdc_ * frame_params.m_adam_coeffs;\n\tconst Eigen::Matrix<double, 3 * TotalModel::NUM_JOINTS, 1> J0 = J_vec;\n\n\t// assume we already have the estimation result of the first 10 frames of the dancing sequence\n\tstd::vector<Eigen::Matrix<double, 3, 1>> t;\n\tstd::vector<Eigen::Matrix<double, TotalModel::NUM_JOINTS, 3, Eigen::RowMajor>> pose;\n\tfor (auto i = 1; i <= 800; i++)\n\t{\n\t\tchar frame_param_name[200];\n\t\tsprintf(frame_param_name, \"/home/evonneng/Documents/research/ssp/tools/bvh-parser/output/body_3d_frontal/%04d.txt\", i);\n\t\treadFrameParam(frame_param_name, frame_params);\n\t\tt.push_back(frame_params.m_adam_t);\n\t\tpose.push_back(frame_params.m_adam_pose);\n\t}\n\n\tBVHWriter bvh(g_total_model.m_parent);\n\tbvh.parseInput(J0, t, pose);\n\tbvh.writeBVH(\"output.bvh\", 1.0 / 30);\n\n\treturn 0;\n}", "meta": {"hexsha": "888e7f87c2aeb33a5da8c57b2b063d457d2a65da", "size": 2335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visualization/FitAdam/bvh.cpp", "max_stars_repo_name": "alvaro-budria/body2hands", "max_stars_repo_head_hexsha": "0eba438b4343604548120bdb03c7e1cb2b08bcd6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2021-05-14T02:55:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T01:51:12.000Z", "max_issues_repo_path": "visualization/FitAdam/bvh.cpp", "max_issues_repo_name": "human2b/body2hands", "max_issues_repo_head_hexsha": "8ab4b206dc397c3b326f2b4ec9448c84ee8801fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-06-24T09:59:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T08:15:20.000Z", "max_forks_repo_path": "visualization/FitAdam/bvh.cpp", "max_forks_repo_name": "human2b/body2hands", "max_forks_repo_head_hexsha": "8ab4b206dc397c3b326f2b4ec9448c84ee8801fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T03:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T02:30:44.000Z", "avg_line_length": 35.3787878788, "max_line_length": 190, "alphanum_fraction": 0.7614561028, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.1899854645993446}}
{"text": "#include <ceres/ceres.h>\n#include <iostream>\n#include <sophus/se3.hpp>\n#include <time.h>\n\n#include \"local_parameterization_se3.hpp\"\n\n#include \"glog/logging.h\"\n#include <vector>\n#include <fstream>\n#include <Eigen/Core>\n\n#include <iomanip> \n#include <algorithm> \n\n#define SIGMA 0.5\n#define SIGMA_two_EM 0.2\n#define NUM_ITERATION_EM 1000\n#define PI 3.1415926535897\n#define Median_inlier_loss   3                //\u8c03\u8282\u516c\u5f0f(13)\u4e2d\u7684\u5706\u7b26\u53f7         change round signal \n\n#define PARETO_ALPHA 1\n\n#define ZIQUAN true\n#define NUM_FEATURE_MATCHES_PER_CONSTRAINT 200\n#define TRUST_ODOMETRY 0.9\n\ntypedef Eigen::Matrix< double, 6, 6, Eigen::RowMajor > InformationMatrix;\ntypedef Eigen::Matrix< double, 6, 1> Vector6d;\ntypedef Eigen::Matrix< int, Eigen::Dynamic, 3, Eigen::RowMajor > Semantic_lable_read;   //\u5143\u7d20\u4e3a:\u8bed\u4e49\u4e00\u81f4\u7684\u6807\u7b7e\u4f4d\u3001\u8bed\u4e49\u6807\u7b7e1\u3001\u8bed\u4e49\u6807\u7b7e2     the flag if semantic labels are the same  label_1  and label_2\ntypedef Eigen::Matrix< double, Eigen::Dynamic, 6, Eigen::RowMajor > PairMatrix;\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\nusing ceres::Solve;\n\n/*\n  ZHOU's convension\n*/\nstd::vector<std::vector<double>>  semantic_p;    //\u4fdd\u5b58\u8bed\u4e49\u6df7\u6dc6\u77e9\u9635     save  semantic matrix\n\n  void LoadFromFile_semantic_p(const char*  filename ) {          //load  semantic matrix\n    semantic_p.clear();\n    semantic_p.resize(24);\n    for(int i=0;i<24;i++)\n    {\n      semantic_p[i].resize(24);\n    }\n    FILE * f = fopen( filename, \"r\" );\n    int i=0;\n    if ( f != NULL ) {\n      char buffer[1024];\n      while ( fgets( buffer, 1024, f ) != NULL &&i<24) \n      {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) \n        {\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",  \\\n           &semantic_p[i][0],&semantic_p[i][1],&semantic_p[i][2], &semantic_p[i][3], &semantic_p[i][4], &semantic_p[i][5],\\\n          &semantic_p[i][6],&semantic_p[i][7],&semantic_p[i][8], &semantic_p[i][9], &semantic_p[i][10], &semantic_p[i][11],\\\n          &semantic_p[i][12],&semantic_p[i][13],&semantic_p[i][14], &semantic_p[i][15], &semantic_p[i][16], &semantic_p[i][17],\\\n          &semantic_p[i][18],&semantic_p[i][19],&semantic_p[i][20], &semantic_p[i][21], &semantic_p[i][22], &semantic_p[i][23]);\n        }\n        i++;\n      }\n      fclose( f );\n    }\n  }\n\nstruct FramedMatches {\n  int id1_;\n  int id2_;\n  int frame_;\n  int old_correspondence_num_;\n  int new_correspondence_num_;\n  float ratio_;\n  Eigen::Matrix4d transformation_;\n  std::vector< std::pair<Eigen::Vector3d, Eigen::Vector3d> > pairs_;\n  std::vector<int> semantic_label;          //\u5b58\u50a8\u6bcf\u4e2a\u70b9\u5bf9 \u8bed\u4e49\u662f\u5426\u5bf9\u5e94\u7684\u6807\u5fd7\u4f4d    save the flag if semantic labels are the same for each point pair\n  std::vector<int> label_one_;         //\u6bcf\u5bf9\u5bf9\u5e94\u70b9\u7b2c\u4e00\u4e2a\u70b9\u7684\u8bed\u4e49\u6807\u7b7e\u503c     the semantic label of the first point for each point pair\n  std::vector<int> label_two_;        //\u6bcf\u5bf9\u5bf9\u5e94\u70b9\u7b2c\u4e8c\u4e2a\u70b9\u7684\u8bed\u4e49\u6807\u7b7e\u503c     the semantic label of the second point for each point pair\n  FramedMatches( int id1, int id2, int f, int old_cor,int new_cor,float ratio,Eigen::Matrix4d trans, PairMatrix pairs,Semantic_lable_read sem)\n  : id1_(id1), id2_(id2), frame_(f), old_correspondence_num_(old_cor),new_correspondence_num_(new_cor),ratio_(ratio),transformation_(trans)\n  {\n    int num_pairs = pairs.rows();\n    pairs_.resize(num_pairs);\n    semantic_label.resize(num_pairs);\n    label_one_.resize(num_pairs);\n    label_two_.resize(num_pairs);\n    for (int i = 0; i < num_pairs;  i++) {\n      pairs_[i] = std::make_pair(Eigen::Vector3d(pairs(i,0), pairs(i,1), pairs(i,2)), \n                                 Eigen::Vector3d(pairs(i,3), pairs(i,4), pairs(i,5)));\n      semantic_label[i]=sem(i,0);\n      label_one_[i]=sem(i,1);\n      label_two_[i]=sem(i,2);\n    }\n  }\n};\n\nstruct PCLMatches {\n  std::vector< FramedMatches > data_;\n\n  void LoadFromFile(const char* filename) {// load files of odometry and loop constraints\n    data_.clear();\n    int id1, id2, frames=22, old_correspondence_num, new_correspondence_num;\n    float ratio;\n    Eigen::Matrix4d trans;\n    PairMatrix pairs;\n    Semantic_lable_read sem;\n    FILE * f = fopen( filename, \"r\" );\n    if ( f != NULL ) {\n      char buffer[1024];\n      // int counter = 0;\n      // while ( (num < 0 || counter <= num) && fgets( buffer, 1024, f ) != NULL ) {\n      while ( fgets( buffer, 1024, f ) != NULL ) {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) {\n            sscanf( buffer, \"%d %d %d %d %f\", &id1, &id2, &old_correspondence_num, &new_correspondence_num, &ratio);\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(0,0), &trans(0,1), &trans(0,2), &trans(0,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(1,0), &trans(1,1), &trans(1,2), &trans(1,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(2,0), &trans(2,1), &trans(2,2), &trans(2,3) );\n          trans(3,0) = 0; trans(3,1) = 0; trans(3,2) = 0; trans(3,3) = 1;\n          pairs.resize(old_correspondence_num, 6);\n          sem.resize(old_correspondence_num, 3);\n          for (int i = 0; i < old_correspondence_num; i++) {\n            fgets( buffer, 1024, f );\n            sscanf( buffer, \"%lf %lf %lf %lf %lf %lf %d %d %d\", &pairs(i,0), &pairs(i,1), &pairs(i,2), &pairs(i,3), \\\n                                                           &pairs(i,4), &pairs(i,5), &sem(i,0),&sem(i,1),&sem(i,2));\n          }\n            data_.push_back( FramedMatches( id1, id2, frames, old_correspondence_num,new_correspondence_num,ratio,trans, pairs,sem) );\n          std::cout << id1 << \" and \" << id2  << std::endl;\n        }\n      }\n      fclose( f );\n    }\n  }\n};\n\nstruct FramedTransformation {\n  int id1_;\n  int id2_;\n  int frame_;\n  Eigen::Matrix4d transformation_;      // pose\n  Sophus::SE3d transformation_se3_;     // useful for both pose and link\n  // std::vector< std::pair<Eigen::Vector3d, Eigen::Vector3d> > pairs_;\n\n  FramedTransformation( int id1, int id2, int f, Eigen::Matrix4d t)\n    : id1_( id1 ), id2_( id2 ), frame_( f ), transformation_( t ) \n  {\n    Eigen::Quaterniond q;\n    q = t.block<3,3>(0,0);\n    transformation_se3_ = Sophus::SE3d(q, Sophus::SE3d::Point(t(0,3), t(1,3), t(2,3)));\n  }\n\n  // only use this constructer to check for convergence\n  FramedTransformation(int id1, int id2, int f, Sophus::SE3d t)\n    : id1_( id1 ), id2_( id2 ), frame_( f ), transformation_se3_( t ) \n    {\n      transformation_ = t.matrix();\n    }\n};\n\nstruct PCLTrajectory {\n  std::vector< FramedTransformation > data_;\n  int index_;\n\n  void LoadFromFile(const char* filename ) {      // load init poses file\n    data_.clear();\n    index_ = 0;\n    int id1, id2, frame;\n    Eigen::Matrix4d trans;\n    FILE * f = fopen( filename, \"r\" );\n    if ( f != NULL ) {\n      char buffer[1024];\n      while ( fgets( buffer, 1024, f ) != NULL ) {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) {\n          sscanf( buffer, \"%d %d %d\", &id1, &id2, &frame);\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(0,0), &trans(0,1), &trans(0,2), &trans(0,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(1,0), &trans(1,1), &trans(1,2), &trans(1,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(2,0), &trans(2,1), &trans(2,2), &trans(2,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(3,0), &trans(3,1), &trans(3,2), &trans(3,3) );\n          data_.push_back( FramedTransformation( id1, id2, frame, trans ) );\n        }\n      }\n      std::cout << \"pose num is:\"<<data_.size()  << std::endl;\n      fclose( f );\n    }\n  }\n\n  void SaveToFile(const char* filename ) {               // save output poses files\n    FILE * f = fopen( filename, \"w\" );\n    for ( int i = 0; i < ( int )data_.size(); i++ ) {\n      Sophus::SE3d trans_se3 = data_[ i ].transformation_se3_;\n      Eigen::Matrix4d trans = trans_se3.matrix();\n      fprintf( f, \"%d\\t%d\\t%d\\n\", data_[ i ].id1_, data_[ i ].id2_, data_[ i ].frame_ );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n    }\n    fclose( f );\n  }\n\n};\n\nstruct FramedInformation {\n  int id1_;\n  int id2_;\n  int frame_;\n  InformationMatrix information_;\n  FramedInformation( int id1, int id2, int f, InformationMatrix t )\n    : id1_( id1 ), id2_( id2 ), frame_( f ), information_( t ) \n  {}\n};\n\nstruct PCLInformation {        // load information matrix files ,not used in cauchy \n  std::vector< FramedInformation > data_;\n\n  void LoadFromFile(const char*  filename ) {\n    data_.clear();\n    int id1, id2, frame;\n    InformationMatrix info;\n    FILE * f = fopen( filename, \"r\" );\n    if ( f != NULL ) {\n      char buffer[1024];\n      while ( fgets( buffer, 1024, f ) != NULL ) {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) {\n          sscanf( buffer, \"%d %d %d\", &id1, &id2, &frame);\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(0,0), &info(0,1), &info(0,2), &info(0,3), &info(0,4), &info(0,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(1,0), &info(1,1), &info(1,2), &info(1,3), &info(1,4), &info(1,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(2,0), &info(2,1), &info(2,2), &info(2,3), &info(2,4), &info(2,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(3,0), &info(3,1), &info(3,2), &info(3,3), &info(3,4), &info(3,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(4,0), &info(4,1), &info(4,2), &info(4,3), &info(4,4), &info(4,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(5,0), &info(5,1), &info(5,2), &info(5,3), &info(5,4), &info(5,5) );\n          data_.push_back( FramedInformation( id1, id2, frame, info ) );\n          // std::cout << id1 << \"\\t\" << id2  << std::endl;\n        }\n      }\n      fclose( f );\n    }\n  }\n};\n\n\n// Eigen's ostream operator is not compatible with ceres::Jet types.\n// In particular, Eigen assumes that the scalar type (here Jet<T,N>) can be\n// casted to an arithmetic type, which is not true for ceres::Jet.\n// Unfortunatly, the ceres::Jet class does not define a conversion\n// operator (http://en.cppreference.com/w/cpp/language/cast_operator).\n//\n// This workaround creates a template specilization for Eigen's cast_impl,\n// when casting from a ceres::Jet type. It relies on Eigen's internal API and\n// might break with future versions of Eigen.\nnamespace Eigen {\nnamespace internal {\n\ntemplate <class T, int N, typename NewType>\nstruct cast_impl<ceres::Jet<T, N>, NewType> {\n  EIGEN_DEVICE_FUNC\n  static inline NewType run(ceres::Jet<T, N> const& x) {\n    return static_cast<NewType>(x.a);\n  }\n};\n\n}  // namespace internal\n}  // namespace Eigen\n\n\n// test examples of Eigen\nstruct TestSE3CostFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  TestSE3CostFunctor(Sophus::SE3d T_aw) : T_aw(T_aw) {}\n\n  template <class T>\n  bool operator()(T const* const sT_wa, T* sResiduals) const {\n    Eigen::Map<Sophus::SE3<T> const> const T_wa(sT_wa);\n    Eigen::Map<Eigen::Matrix<T, 6, 1> > residuals(sResiduals);\n\n    // We are able to mix Sophus types with doubles and Jet types withou needing\n    // to cast to T.\n    residuals = (T_aw * T_wa).log();\n    // std::cout << residuals << std::endl;\n\n    // Reverse order of multiplication. This forces the compiler to verify that\n    // (Jet, double) and (double, Jet) SE3 multiplication work correctly.\n    // residuals = (T_wa * T_aw).log();\n\n    // Finally, ensure that Jet-to-Jet multiplication works.\n    // residuals = (T_wa * T_aw.cast<T>()).log();\n    return true;\n  }\n\n  Sophus::SE3d T_aw;\n};\n\nstruct TestPointCostFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  TestPointCostFunctor(Sophus::SE3d T_aw, Eigen::Vector3d point_a)\n      : T_aw(T_aw), point_a(point_a) {}\n\n  template <class T>\n  bool operator()(T const* const sT_wa, T const* const spoint_b,\n                  T* sResiduals) const {\n    using Vector3T = Eigen::Matrix<T, 3, 1>;\n    Eigen::Map<Sophus::SE3<T> const> const T_wa(sT_wa);\n    Eigen::Map<Vector3T const> point_b(spoint_b);\n    Eigen::Map<Vector3T> residuals(sResiduals);\n\n    // Multiply SE3d by Jet Vector3.\n    Vector3T point_b_prime = T_aw * point_b;\n    // Ensure Jet SE3 multiplication with Jet Vector3.\n    // point_b_prime = T_aw.cast<T>() * point_b;\n\n    // Multiply Jet SE3 with Vector3d.\n    Vector3T point_a_prime = T_wa * point_a;\n    // Ensure Jet SE3 multiplication with Jet Vector3.\n    // point_a_prime = T_wa * point_a.cast<T>();\n\n    residuals = point_b_prime - point_a_prime;\n    return true;\n  }\n\n  Sophus::SE3d T_aw;\n  Eigen::Vector3d point_a;\n};\n\n//  GaussianFunctor is not used in this work.\nstruct GaussianFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  GaussianFunctor(Sophus::SE3d trans_next_to_current, InformationMatrix info, int id1, int id2) \n  : trans_next_to_current_(trans_next_to_current), info_(info), id1_(id1), id2_(id2) {}\n\n  template <typename T> \n  bool operator()(T const* const sT_current, T const* const sT_next, \n                  T* residual) const {\n    // using Vector3T = Eigen::Matrix<T, 3, 1>;\n    Eigen::Map<Sophus::SE3<T> const> const T_current(sT_current);\n    Eigen::Map<Sophus::SE3<T> const> const T_next(sT_next);\n    // Eigen::Map<Vector3T> residuals(sResiduals);\n\n    // Eigen::Matrix<T,4,4> M_xi = (trans_next_to_current_ * T_next.inverse() * T_current).matrix();\n    Sophus::SE3<T> xi_7T = trans_next_to_current_ \n                          * T_next.inverse() \n                          * T_current;\n\n    Eigen::Matrix<T,6,1> xi;\n    // xi << M_xi(0,3), M_xi(1,3), M_xi(2,3), q.x(), q.y(), q.z();\n    xi << xi_7T.data()[4], xi_7T.data()[5], xi_7T.data()[6], xi_7T.data()[0], xi_7T.data()[1], xi_7T.data()[2];\n\n    Eigen::Matrix<T,1,1> sq_error = xi.transpose() * info_ * xi;\n    // double sq_error = (xi.transpose() * info_ * xi)[0];\n    \n    residual[0] = T( sqrt(sq_error(0,0)) );\n    // residual[0] = T( sqrt(sq_error(0,0) / T(2.)) / T(SIGMA) );\n\n    // std::cout << id1_ << \", \" << id2_ << \" : \" << residual[0] << std::endl;\n    return true;\n  }\n\nprivate:\n  const Sophus::SE3d trans_next_to_current_;\n  const InformationMatrix info_;\n  const int id1_, id2_;\n};\n\n// define CauchyFunctor \nstruct CauchyFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  CauchyFunctor(Eigen::Vector3d point_p, Eigen::Vector3d point_q, \n                int id1, int id2) \n  : point_p_(point_p), point_q_(point_q),\n    id1_(id1), id2_(id2) {}\n\n  template <typename T> \n  bool operator()(T const* const sT_current, T const* const sT_next, \n                  T* sResiduals) const {\n    // using Vector3T = Eigen::Matrix<T, 3, 1>;\n    Eigen::Map<Sophus::SE3<T> const> const T_current(sT_current);\n    Eigen::Map<Sophus::SE3<T> const> const T_next(sT_next);\n    Eigen::Map<Eigen::Matrix<T, 3, 1> > residuals(sResiduals);\n\n    residuals = (T_current * point_p_ - T_next * point_q_);\n\n    return true;\n  }\n\nprivate:\n  const Eigen::Vector3d point_p_, point_q_;\n  const int id1_, id2_;\n};\n\n\nclass R2EM_CauchyUniform {\npublic:\n  // lambda  : converge for first EM\n  double lambda_;\n  //  lambda_second_ : converge for second EM\n  double  lambda_second_;\n  double U;\n  Eigen::Matrix<double, 6, 6> covarance_;\n\n  // read from file\n  PCLMatches odometry_txt_;\n  PCLMatches loop_txt_;\n\n  // blocks for ceres\n  PCLTrajectory camera_poses_;\n  std::vector< std::vector<double> > L_;     //\u5355\u4e2aloop\u6b63\u786e\u7684\u6982\u7387\u503c(\u8bed\u4e49)      correct probability of a loop constraint\n  double sum_L_;   //\u7528\u4e8e\u68c0\u6d4b first EM \u6536\u655b\u6027      for test convergence of first EM\n  std::vector< std::vector<double> > L_P_;    //\u6240\u6709odometry\u3001loop\u4e2d\u6bcf\u4e2a\u70b9\u5bf9\u6b63\u786e\u7684\u6982\u7387      correct probability of a point pair in a constraint\n  double sum_L_P_;   //\u7528\u4e8e\u68c0\u6d4b second EM\u6536\u655b\u6027    for test convergence of second EM\n  std::vector< std::vector<int> > L_vector;     //\u5355\u4e2aloop\u662f\u5426\u6b63\u786e(\u6839\u636e\u76f8\u540c\u5411\u91cf\u5bf9\u7684\u4e2a\u6570): 0\u8868\u793a\u4e0d\u6b63\u786e, 1: \u8868\u793a\u6682\u65f6\u6b63\u786e    judge whether a loop is correct from vector filter model\n  std::vector< std::vector<int> > vector_true;         //\u6839\u636e\u5411\u91cf\u5bf9\u662f\u5426\u76f8\u540c\uff1a\u6240\u6709odometry\u3001loop\u4e2d\u6bcf\u4e2a\u70b9\u5bf9\u662f\u5426\u6b63\u786e: 0\u8868\u793a\u4e0d\u6b63\u786e\uff0c1\u8868\u793a\u6b63\u786e  judge whether a point pair in a loop is correct from vector filter model\n\n\n  // convergence condition  for first EM\n  double last_lambda_;\n  PCLTrajectory last_camera_poses_;\n  Eigen::Matrix<double, 6, 6> last_covarance_;\n  // convergence condition  for second EM\n  double last_lambda_second_;\n\n  R2EM_CauchyUniform(double lambda)\n  : lambda_(lambda){\n    last_lambda_ = -1.;\n    lambda_second_=0.99;\n    last_lambda_second_ = -1.;\n  }\n  ~R2EM_CauchyUniform() {}\n\n  void LoadOdometryTxt(const char* filename) {\n    odometry_txt_.LoadFromFile(filename);//, -1);\n  }\n\n  void LoadLoopTxt(const char* filename) {\n    loop_txt_.LoadFromFile(filename);//, -1);\n  }\n\n  void InitCameraPosesWithZhou(const char* filename) {\n    camera_poses_.LoadFromFile(filename);\n    L_.resize(NumPoses());\n    for (int i = 0; i < NumPoses(); i++) {\n      L_[i].resize(NumPoses());\n    }\n  }\n\n  void InitCameraPoses() {          // init poses of submaps\n    camera_poses_.data_.clear();\n    camera_poses_.index_ = 0;\n    Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();\n    camera_poses_.data_.push_back( FramedTransformation( 0, 0, 1, pose ) );\n\n    for( std::vector< FramedMatches >::iterator it = odometry_txt_.data_.begin();\n      it != odometry_txt_.data_.end(); it ++)\n    {      \n      pose = pose * it->transformation_; \n      camera_poses_.data_.push_back( FramedTransformation( it->id2_, it->id2_, it->id2_ + 1, pose ) );\n    }\n\n    L_.resize(NumPoses());\n    for (int i = 0; i < NumPoses(); i++) {\n      L_[i].resize(NumPoses());\n    }\n\n  }; \n\n  void SaveCameraPoses(const char* filename) {\n    camera_poses_.SaveToFile(filename);\n  }\n\n  void EstimateLAMBDA() {              //estimate  cauchy loss for odometry and loop constraints\n\n    std::cout << \"In EstimateLAMBDA : \" << NumOdometryConstraints() << std::endl;\n    std::vector<double> average_loss(NumOdometryConstraints());\n    std::vector<double> total_loss(NumOdometryConstraints());\n    for (int i = 0; i < NumOdometryConstraints(); i ++) {\n\n      FramedMatches match = odometry_txt_.data_[i];\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n\n      std::cout << \"In EstimateLAMBDA : \" << i << \"th OdometryConstraint \" << id1 << \" with \" << id2 << std::endl;\n\n      Eigen::Quaterniond q;\n      q = match.transformation_.block<3,3>(0,0);\n      Sophus::SE3d transformation_se3_ = Sophus::SE3d(q, Sophus::SE3d::Point(match.transformation_(0,3), match.transformation_(1,3), match.transformation_(2,3)));\n      \n      // compute the sum of cauchy loss\n      double sum_cauchy_loss = 0.;\n      for (std::size_t j = 0; j < match.pairs_.size(); j++) {\n        Eigen::Vector3d vec_d = camera_poses_.data_[id1].transformation_se3_ * match.pairs_[j].first \n                              - camera_poses_.data_[id2].transformation_se3_ * match.pairs_[j].second;\n        sum_cauchy_loss += log (1. + vec_d.squaredNorm() / (SIGMA * SIGMA));\n      }\n      assert(match.pairs_.size() > 0);\n      average_loss[i] = sum_cauchy_loss / match.pairs_.size();\n      total_loss[i] = sum_cauchy_loss;\n    }\n\n    for (int i = 0; i < NumOdometryConstraints(); i ++) {\n      FramedMatches match = odometry_txt_.data_[i];\n      // FramedInformation info = odometry_info_.data_[i];\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n\n      // double expterm = exp( - log(U) + (1. + PARETO_ALPHA) * log(average_loss[i]));\n      double expterm = exp( - log(U) + (1. + PARETO_ALPHA) * (average_loss[i]));\n      // L_[id1][id2] = 1./ (1. + expterm);\n      std::cout << \"(\" << std::setw(3) << id1 << \",\" << std::setw(3) << id2 << \") : \" \n                << std::setw(15) << average_loss[i] << \"(\" <<  total_loss[i] << \")\"\n                << std::setw(15) << average_loss[i] * average_loss[i]\n                << std::setw(15) << expterm <<  \" --> \"\n                << std::setw(15) << 1./ (1. + expterm)\n                << std::setw(15) << match.pairs_.size()\n                // << std::setw(15) << U_big\n                << std::endl;\n    }\n    std::nth_element(average_loss.begin(), average_loss.begin() + average_loss.size()/2, average_loss.end());\n    std::nth_element(total_loss.begin(), total_loss.begin() + total_loss.size()/2, total_loss.end());\n    // double median_inlier_loss = average_loss[average_loss.size()/2];\n    \n    double median_inlier_loss = exp(2 * average_loss[average_loss.size()/2]);\n    std::cout << \"average_loss[average_loss.size()/2] \" << average_loss[average_loss.size()/2] << '\\n';\n\n    // double median_total_loss = total_loss[average_loss.size()/2];\n    std::cout << \"The median is \" << median_inlier_loss << '\\n';\n    // U =  TRUST_ODOMETRY / (1-TRUST_ODOMETRY) * median_inlier_loss * median_inlier_loss;\n    U =  TRUST_ODOMETRY / (1-TRUST_ODOMETRY) * median_inlier_loss;\n    // double U_big =  TRUST_ODOMETRY / (1-TRUST_ODOMETRY) * median_total_loss * median_total_loss;\n\n  }\n\n  void SaveLinks(const char* filename) {       //save correct constraints\n    FILE * f = fopen( filename, \"w\" );\n\n    for ( int i = 0; i < NumOdometryConstraints(); i++ ) {\n      Eigen::Matrix4d trans = odometry_txt_.data_[ i ].transformation_;\n      // Eigen::Matrix4d trans = trans_se3.matrix();\n      fprintf( f, \"%d\\t%d\\t%d\\n\", odometry_txt_.data_[ i ].id1_, odometry_txt_.data_[ i ].id2_, odometry_txt_.data_[ i ].frame_ );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n    }\n\n    for (int i = 0; i < NumLoopClosureConstraints(); i++ ) {\n      Eigen::Matrix4d trans = loop_txt_.data_[ i ].transformation_;\n      int id1 = loop_txt_.data_[ i ].id1_;\n      int id2 = loop_txt_.data_[ i ].id2_;\n      assert(id1 < id2);\n      if (id1 != id2 - 1 && L_[id1][id2] > 0.8 * TRUST_ODOMETRY) {\n        fprintf( f, \"%d\\t%d\\t%d\\n\", loop_txt_.data_[ i ].id1_, loop_txt_.data_[ i ].id2_, loop_txt_.data_[ i ].frame_ );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n      }\n    }\n    fclose( f );\n  }\n\n  // first Expectation step\n  void Expectation(int iteration_num) \n  {\n    //\u8ba1\u7b97odometry\u6bcf\u4e2a\u70b9\u6b63\u786e\u7684\u6982\u7387    calculate correct probabilities of point pairs in each odometry constraint     \n    // for (int i = 0; i < NumOdometryConstraints(); i++) \n    // {\n    //   std::cout << \"num of correct odometry:  \" << i<< std::endl;\n\n    //   FramedMatches match = odometry_txt_.data_[i];\n      \n    //   assert(match.id1_ < match.id2_);\n    //   int id1 = match.id1_;\n    //   int id2 = match.id2_;\n    //     if(id1 !=60)         //\n    //     {\n    //       for (std::size_t j = 0; j < match.pairs_.size() && j<200; j++) \n    //       {\n              \n    //           Eigen::Vector3d vec_d = camera_poses_.data_[id1].transformation_se3_ * match.pairs_[j].first \n    //                                 -camera_poses_.data_[id2].transformation_se3_ * match.pairs_[j].second;\n\n    //           L_P_[i+NumLoopClosureConstraints()][j]= U / (U + exp(2 * log (1. + vec_d.squaredNorm() / (SIGMA_two_EM * SIGMA_two_EM))));          \n              \n    //           if(iteration_num==0)   L_P_[i+NumLoopClosureConstraints()][j]=1;\n    //       }\n    //     }\n\n    // }\n    sum_L_ = 0.;\n    std::vector<int> healthy_counter(20);\n    for (int ii = 0; ii < 20; ii ++) {\n      healthy_counter[ii] = 0;\n    }\n\n    int maxnum_loop_corres=0;\n    for (int i = 0; i < NumLoopClosureConstraints(); i ++) {\n\n      FramedMatches match = loop_txt_.data_[i];\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n\n      if(L_vector[id1][id2]==0) continue;   //\u6839\u636e\u5411\u91cf\u5bf9\u4e00\u81f4\u7684\u6570\u91cf\u5224\u65ad \u4e00\u4e2aloop\u662f\u5426\u4e3a\u6b63\u786e\u7684loop  \u4e0d\u6b63\u786e\u7684loop\u4e0d\u53c2\u4e0e\u4f18\u5316  judge if a loop is correct by vector filter model\n      // std::cout << id1 << \" ? \" << id2 <<std::endl;\n\n      // compute the sum of cauchy loss\n      double sum_cauchy_loss = 0.;\n      for (std::size_t j = 0; j < match.pairs_.size(); j++) {\n        \n          if(vector_true[i][j]==0 ) continue;     //\u5411\u91cf\u5bf9\u4e0d\u4e00\u81f4\u7684\u5339\u914d\u5bf9 \u76f4\u63a5\u4e0d\u53c2\u4e0e \u6b63\u786e\u6982\u7387\u8ba1\u7b97 \u548c \u4f18\u5316     if a point pair  is false by vector filter model , continue\n\n        Eigen::Vector3d vec_d = camera_poses_.data_[id1].transformation_se3_ * match.pairs_[j].first \n                              -camera_poses_.data_[id2].transformation_se3_ * match.pairs_[j].second;\n        if(1)\n        {\n          sum_cauchy_loss += log (1. + vec_d.squaredNorm() / (SIGMA * SIGMA));\n        }\n        else\n        {\n           sum_cauchy_loss+=0;\n        }\n      }\n      if (match.pairs_.size() > 0) {\n        sum_cauchy_loss /= match.pairs_.size();\n      }\n\n      L_[id1][id2] = U / (U + exp(2 * sum_cauchy_loss));\n\n\n        std::cout << id1 <<\" \" << id2 << std::endl;\n        std::cout << log (1. + (camera_poses_.data_[id1].transformation_se3_ * match.pairs_[0].first \n                              -camera_poses_.data_[id2].transformation_se3_ * match.pairs_[0].second).squaredNorm() / (SIGMA * SIGMA))*L_[id1][id2] << std::endl;\n      \n      //\u5bf9\u4e8e\u4e24\u5e45\u5730\u56fe\u7684\u914d\u51c6\uff0c\u5728\u7b2c\u4e00\u6b21EM\u8fed\u4ee3\u65f6\uff0c\u6240\u6709loop-closure\u7684\u6982\u7387\u90fd\u8bbe\u4e3a1\u3002\u7b2c\u4e00\u6b21\u8fed\u4ee3\u4ecd\u7136\u8003\u8651\u8bed\u4e49\u6b63\u786e\u70b9\u5bf9\u5360\u6bd4\u7684\u56e0\u7d20\u3002  correct P of loops =1  for the first E step,and consider semantic ratio\n       if(iteration_num ==0) \n       {\n        L_[id1][id2]=1;\n        L_[id1][id2]=L_[id1][id2]*exp(-(match.ratio_-1)*(match.ratio_-1)/(2*0.1));\n       }                                                                                                        \n\n      std::cout << \"(\" << std::setw(3) << id1 << \",\" << std::setw(3) << id2 << \") : \" \n                << std::setw(15) << sum_cauchy_loss\n                << std::setw(15) << sum_cauchy_loss * sum_cauchy_loss\n                << std::setw(15) << exp(2 * sum_cauchy_loss / match.pairs_.size()) <<  \" --> \"\n                << std::setw(15) <<  L_[id1][id2]\n                << std::endl;\n\n      for (int ii = 0; ii < 20; ii ++) {\n        if (L_[id1][id2] > 0.05 * ii && L_[id1][id2] <= 0.05 * (ii+1)){\n          healthy_counter[ii] ++;\n        } \n      }\n      \n      sum_L_ += L_[id1][id2];\n   }\n\n    std::cout << \"\\t\\tsum_L_ is \" << sum_L_ << std::endl;\n    std::cout << \"\\t\\tHealthy is \";\n    for (int ii = 0; ii < 20; ii ++) {\n       std::cout << \"\\t(\" << (0.05 * ii) << \")\\t\" << healthy_counter[ii] ;\n    }\n    std::cout << \"\\t(1.0)\\t\" << std::endl;\n    std::cout << \"\\t\\tTotal is \" << NumLoopClosureConstraints() << std::endl;\n    std::cout << \"\\t\\testimated LAMBDA is \" << U << std::endl;\n  }\n\n  //first Maximization step\n  void Maximization() {\n    last_lambda_ = lambda_;\n    last_camera_poses_.index_ = camera_poses_.index_;\n    last_camera_poses_.data_.clear();\n    for (int i = 0; i < NumPoses(); i++) {\n      last_camera_poses_.data_.push_back( \n        FramedTransformation (camera_poses_.data_[i].id1_, \n                              camera_poses_.data_[i].id2_, \n                              camera_poses_.data_[i].frame_,\n                              camera_poses_.data_[i].transformation_se3_));\n    }\n    camera_poses_.index_ ++;\n\n    // Maximize lambda\n    lambda_ = sum_L_ / NumLoopClosureConstraints();\n\n    // Maximize pose\n    // Build the problem.\n    ceres::Problem problem;\n\n    // Specify local update rule for our parameter\n    for (std::vector< FramedTransformation >::iterator it = camera_poses_.data_.begin(); \n         it != camera_poses_.data_.end(); it++ ) {\n      problem.AddParameterBlock(it->transformation_se3_.data(), Sophus::SE3d::num_parameters,\n                                new Sophus::test::LocalParameterizationSE3);\n    }\n\n    // Create and add cost functions. Derivatives will be evaluated via\n    // automatic differentiation                                \n    int  diuqi=0 ;\n    // odometry cases\n    for (int i = 0; i < NumOdometryConstraints(); i++) \n    {\n      FramedMatches match = odometry_txt_.data_[i];\n      \n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_; \n      int id2 = match.id2_;\n        if(1)         //\n        { \n          diuqi=0 ;        // output numbers of filtered point pairs in each odometry\n          for (std::size_t j = 0; j < match.pairs_.size() && j<200; j++) \n          {\n            // std::cout << \"label is \"<<  match.semantic_label[j] << \" match.vector_true[j] \" << vector_true[i+NumLoopClosureConstraints()][j]<< std::endl;\n            \n            if(vector_true[i+NumLoopClosureConstraints()][j]==0)          //\n            {\n              // std::cout << \"\u4e22\u5f03\uff1a\" <<match.pairs_[j].first[0] << \"  \" << match.pairs_[j].first[1] << \"  \" <<match.pairs_[j].first[2] << \" second: \" <<\n              //  match.pairs_[j].second[0] << \"  \" << match.pairs_[j].second[1] << \"  \" <<match.pairs_[j].second[2] << std::endl;\n              diuqi++ ;\n           \n            }\n\n            if(vector_true[i+NumLoopClosureConstraints()][j]==1)          //\n            {\n              // std::cout << match.pairs_[j].first[0] << \"  \" << match.pairs_[j].first[1] << \"  \" <<match.pairs_[j].first[2] << \" second: \" <<\n              //  match.pairs_[j].second[0] << \"  \" << match.pairs_[j].second[1] << \"  \" <<match.pairs_[j].second[2] << std::endl;\n            ceres::CostFunction* cost_odometry =\n                new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                    new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                      id1, id2));\n            problem.AddResidualBlock(cost_odometry, \n                                    new ceres::CauchyLoss(SIGMA),\n                                    camera_poses_.data_[id1].transformation_se3_.data(), \n                                    camera_poses_.data_[id2].transformation_se3_.data());                        \n            }\n          }\n          std::cout << id1 <<\"is: \"<<diuqi <<std::endl;\n        }\n\n    }\n\n    for (int i = 0; i < NumLoopClosureConstraints(); i++) \n    {\n      FramedMatches match = loop_txt_.data_[i];\n      \n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n       \n        if(L_vector[id1][id2]==0) continue; //\u6839\u636e\u5411\u91cf\u5bf9\u4e00\u81f4\u7684\u6570\u91cf\u5224\u65ad \u4e00\u4e2aloop\u662f\u5426\u4e3a\u6b63\u786e\u7684loop  \u4e0d\u6b63\u786e\u7684loop\u4e0d\u53c2\u4e0e\u4f18\u5316      for filtered loops by vector filter model ,continue\n\n        for (std::size_t j = 0; j < match.pairs_.size() ; j++) \n        {\n          if(match.semantic_label[j]==1 && vector_true[i][j]==1)\n          {\n          // {\n          ceres::CostFunction* cost_loop =\n              new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                  new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                    id1, id2));\n          //  if (L_[id1][id2] >= TRUST_ODOMETRY * 0.5) {\n            //\u76ee\u6807\u51fd\u6570\uff0c\u6bcf\u4e2aodometry\u548cloop\u5e94\u8be5\u9664\u4ee5 \u5404\u81ea\u7279\u5f81\u70b9\u5bf9\u7684\u6570\u91cf\u3002(cauchy\u6e90\u4ee3\u7801\u53ef\u80fd\u56e0\u4e3a\u7279\u5f81\u70b9\u6570\u91cf\u76f8\u540c\u6ca1\u6709\u9664)\n            problem.AddResidualBlock(cost_loop, \n                                  new ceres::ScaledLoss(new ceres::CauchyLoss(SIGMA), L_[id1][id2], ceres::TAKE_OWNERSHIP),\n                                  camera_poses_.data_[id1].transformation_se3_.data(), \n                                  camera_poses_.data_[id2].transformation_se3_.data());\n          }\n\n          if(match.semantic_label[j]==0 && vector_true[i][j]==1)\n          {\n            int label_one=match.label_one_[j];\n            int label_two=match.label_two_[j];\n          ceres::CostFunction* cost_loop =\n              new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                  new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                    id1, id2));\n          //  if (L_[id1][id2] >= TRUST_ODOMETRY * 0.5) {\n           if (label_one!=100&&label_two!=100) {\n            problem.AddResidualBlock(cost_loop, \n                                  new ceres::ScaledLoss(new ceres::CauchyLoss(SIGMA), L_[id1][id2]*semantic_p[label_one][label_two], ceres::TAKE_OWNERSHIP),\n                                  camera_poses_.data_[id1].transformation_se3_.data(), \n                                  camera_poses_.data_[id2].transformation_se3_.data());\n           }\n          }\n\n        }\n    }\n    \n\n    // Set solver options (precision / method)\n    ceres::Solver::Options options;\n    // options.max_num_iterations = 1000;\n    options.gradient_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    options.function_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    // options.linear_solver_type = ceres::DENSE_QR;\n    options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n  \n    // Solve\n    std::cout << \"--------------SOLVING----------------ITERATION \" << camera_poses_.index_ << std::endl;\n    ceres::Solver::Summary summary;\n    Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n    std::cout << \"--------------  DONE ----------------ITERATION \" << camera_poses_.index_ << std::endl;\n  }\n\nvoid Vector()       //\u8ba1\u7b97\u4e00\u4e2aloop\u4e2d\u6b63\u786e\u5411\u91cf\u7684\u4e2a\u6570   vector filter model\n  {            \n      int l_odometry_ave=0;\n    for (int i = 0; i < NumOdometryConstraints(); i++) \n    {\n      int l=0;\n      // std::cout << \"num of correct odometry:  \" << i<< std::endl;\n\n      FramedMatches match = odometry_txt_.data_[i];\n      \n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n      std::cout << id1 << \"   \" << id2 <<std::endl;\n\n       int  num_vector[match.pairs_.size()]={0}; \n\n        if(1)         // judge for a point pair in each odometry\n        {\n          for (std::size_t j = 0; j < match.pairs_.size()-1 && j<200; j++) \n          for (std::size_t k = j+1; k < match.pairs_.size() && k<200; k++) \n          {\n              \n              Eigen::Vector3d vec_d_1 = (match.pairs_[k].first - match.pairs_[j].first);\n              Eigen::Vector3d vec_d_2 = (match.pairs_[k].second - match.pairs_[j].second);\n\n              float sqrt_1=sqrt(vec_d_1[0]*vec_d_1[0]+vec_d_1[1]*vec_d_1[1]+vec_d_1[2]*vec_d_1[2]);\n              float sqrt_2=sqrt(vec_d_2[0]*vec_d_2[0]+vec_d_2[1]*vec_d_2[1]+vec_d_2[2]*vec_d_2[2]);\n\n              if(abs(sqrt_1-sqrt_2)<0.2)    \n              {\n                // l++;\n                num_vector[j]++;\n                num_vector[k]++;\n                // vector_true[i+NumLoopClosureConstraints()][j]=1;\n                // vector_true[i+NumLoopClosureConstraints()][k]=1;\n              }      \n          }\n          // judge for a odometry constraint\n          for(int m=0;m<match.pairs_.size();m++)\n          {\n            // std::cout << num_vector[m] << std::endl;\n            if(num_vector[m]>match.pairs_.size()/4)\n            {\n              vector_true[i+NumLoopClosureConstraints()][m]=1;\n              l++;\n            }\n          }\n\n        }\n        l_odometry_ave+=l;\n        // std:: cout << l << std::endl;\n    }\n    l_odometry_ave=l_odometry_ave/NumOdometryConstraints();      //\u6240\u6709odometry\u4e2d\u76f8\u540c\u5411\u91cf\u5bf9\u6570\u91cf\u7684\u5e73\u5747\u6570\n    // std:: cout << \"l_odometry_ave \"<<l_odometry_ave << std::endl;\n    for (int i = 0; i < NumLoopClosureConstraints(); i++) \n    {\n      int l=0;\n      FramedMatches match = loop_txt_.data_[i];\n       \n      int  num_vector[match.pairs_.size()]={0};\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n      // std::cout << id1 << \"   \" << id2 <<std::endl;\n\n      //judge for a point pair in a loop\n          for (std::size_t j = 0; j < match.pairs_.size()-1 && j<200; j++) \n          for (std::size_t k = j+1; k < match.pairs_.size() && k<200; k++) \n          {\n              \n              Eigen::Vector3d vec_d_1 = (match.pairs_[k].first - match.pairs_[j].first);\n              Eigen::Vector3d vec_d_2 = (match.pairs_[k].second - match.pairs_[j].second);\n\n              float sqrt_1=sqrt(vec_d_1[0]*vec_d_1[0]+vec_d_1[1]*vec_d_1[1]+vec_d_1[2]*vec_d_1[2]);\n              float sqrt_2=sqrt(vec_d_2[0]*vec_d_2[0]+vec_d_2[1]*vec_d_2[1]+vec_d_2[2]*vec_d_2[2]);\n\n              if(abs(sqrt_1-sqrt_2)<0.1)    \n              {\n                // l++;\n                num_vector[j]++;\n                num_vector[k]++;\n              }\n\n          }\n          // judge for a loop\n          for(int m=0;m<match.pairs_.size();m++)\n          {\n            if(num_vector[m]>match.pairs_.size()/4)\n            {\n                          // std::cout << num_vector[m] << std::endl;\n              vector_true[i][m]=1;\n              l++;\n            }\n          }\n        // std:: cout << l << std::endl;\n        if (l<l_odometry_ave*0.2) \n        {\n          // std:: cout << \"outlier loop\" << std::endl;\n          L_vector[id1][id2]=0;\n        }\n        else    L_vector[id1][id2]=1;\n        // std:: cout << \" \" << std::endl;\n    }\n  }\n\n  // second E step  filter false point pairs in correct constraints\n  void Expectation_point(int iteration_num)       //\u518d\u6b21\u4f7f\u7528EM\u7b97\u6cd5\uff0c\u7b5b\u9664\u6b63\u786eloop \u548c odometry\u4e2d\u7684\u9519\u8bef\u70b9\u5bf9\n  {            \n    sum_L_P_=0. ;\n    for (int i = 0; i < NumOdometryConstraints(); i++) \n    {\n      // std::cout << \"num of correct odometry:  \" << i<< std::endl;\n\n      FramedMatches match = odometry_txt_.data_[i];\n      \n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n      // std::cout << id1 << \"   \" << id2 <<std::endl;\n        if(1)         \n        {\n          // odometry cases\n          for (std::size_t j = 0; j < match.pairs_.size() && j<200; j++) \n          {\n              if(vector_true[i+NumLoopClosureConstraints()][j]==0)  continue;\n\n              Eigen::Vector3d vec_d = camera_poses_.data_[id1].transformation_se3_ * match.pairs_[j].first \n                                    -camera_poses_.data_[id2].transformation_se3_ * match.pairs_[j].second;\n\n              L_P_[i+NumLoopClosureConstraints()][j]= U / (U + exp(2 * log (1. + vec_d.squaredNorm() / (SIGMA_two_EM * SIGMA_two_EM))));          \n              \n              //if(iteration_num==0)   L_P_[i+NumLoopClosureConstraints()][j]=1;\n\n              sum_L_P_ +=L_P_[i+NumLoopClosureConstraints()][j] ;\n          }\n        }\n\n    }\n    // loop cases\n    for (int i = 0; i < NumLoopClosureConstraints(); i ++) \n    {\n      FramedMatches match = loop_txt_.data_[i];\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n       \n\n      if(L_vector[id1][id2]==0)  continue;       //\u6839\u636e\u5411\u91cf \u53bb\u9664\u9519\u8befloop\n      if(L_[id1][id2] < TRUST_ODOMETRY*0.2 )  continue;           //\u53ea\u8003\u8651\u6b63\u786eloop\u4e2d\u9519\u8bef\u70b9\u5bf9\u7684\u7b5b\u9664\n\n      for (std::size_t j = 0; j < match.pairs_.size(); j++) \n      {\n        if(vector_true[i][j]==0)  continue;\n\n        Eigen::Vector3d vec_d = camera_poses_.data_[id1].transformation_se3_ * match.pairs_[j].first \n                              -camera_poses_.data_[id2].transformation_se3_ * match.pairs_[j].second;\n\n        L_P_[i][j]= U / (U + exp(2 * log (1. + vec_d.squaredNorm() / (SIGMA_two_EM * SIGMA_two_EM))));          \n        // if(iteration_num==0)   L_P_[i][j]=1;\n        // std::cout << \"U:  \" << U<< std::endl;\n        sum_L_P_ +=L_P_[i][j] ;\n        // std::cout << \"num of correct loop:  \" << i<< std::endl;\n        // std::cout << \"correct probability of point \"<<j <<\" is: \"<< L_P_[i][j]<< std::endl;\n        // std::cout << \"point first is :\" << match.pairs_[j].first << \"point second is :\" << match.pairs_[j].second <<std::endl;\n      }                                                                                        \n      \n    }\n  }\n\n// second M step filter false point pairs in correct constraints\nvoid Maximization_point() {\n    last_lambda_second_ = lambda_second_;\n    last_camera_poses_.index_ = camera_poses_.index_;\n    last_camera_poses_.data_.clear();\n    for (int i = 0; i < NumPoses(); i++) {\n      last_camera_poses_.data_.push_back( \n        FramedTransformation (camera_poses_.data_[i].id1_, \n                              camera_poses_.data_[i].id2_, \n                              camera_poses_.data_[i].frame_,\n                              camera_poses_.data_[i].transformation_se3_));\n    }\n    camera_poses_.index_ ++;\n\n    // Maximize lambda\n    lambda_second_ = sum_L_P_ / 50;\n\n    // Maximize pose\n    // Build the problem.\n    ceres::Problem problem;\n\n    // Specify local update rule for our parameter\n    for (std::vector< FramedTransformation >::iterator it = camera_poses_.data_.begin(); \n         it != camera_poses_.data_.end(); it++ ) {\n      problem.AddParameterBlock(it->transformation_se3_.data(), Sophus::SE3d::num_parameters,\n                                new Sophus::test::LocalParameterizationSE3);\n    }\n\n    //dometry cases\n    for (int i = 0; i < NumOdometryConstraints(); i++) \n    {\n\n      FramedMatches match = odometry_txt_.data_[i];\n      \n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n        if(1)         ///////////////////////////////////////////////////////////\n        {\n          for (std::size_t j = 0; j < match.pairs_.size() && j<200; j++) \n          {\n            \n            if(L_P_[i+NumLoopClosureConstraints()][j]<0.8) continue;\n            else L_P_[i+NumLoopClosureConstraints()][j]=1;\n\n            if(match.semantic_label[j]==1 && vector_true[i+NumLoopClosureConstraints()][j]==1)         \n            {\n            ceres::CostFunction* cost_odometry =\n                new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                    new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                      id1, id2));\n            problem.AddResidualBlock(cost_odometry, \n                                  new ceres::ScaledLoss(new ceres::CauchyLoss(SIGMA_two_EM), L_P_[i+NumLoopClosureConstraints()][j], ceres::TAKE_OWNERSHIP),\n                                  camera_poses_.data_[id1].transformation_se3_.data(), \n                                  camera_poses_.data_[id2].transformation_se3_.data());                         \n            }\n          }\n        }\n\n    }\n\n    // loop cases\n    for (int i = 0; i < NumLoopClosureConstraints(); i++) \n    {\n        \n      FramedMatches match = loop_txt_.data_[i];\n      \n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n\n       if(L_[id1][id2] < TRUST_ODOMETRY*0.2)  continue;          //\u4e0d\u8fdb\u884coutlier loop\u7684\u4f18\u5316\n       if(L_vector[id1][id2]==0) continue;    //\u5411\u91cf\u5224\u65ad   \u9519\u8befloop\u76f4\u63a5\u4e0d\u53c2\u4e0e\u4f18\u5316\n\n        for (std::size_t j = 0; j < match.pairs_.size(); j++) \n        {\n          if(L_[id1][id2] >= TRUST_ODOMETRY*0.2)\n          {\n              if(L_P_[i][j]<0.8) continue;\n               else L_P_[i][j]=1;\n          }\n          if(match.semantic_label[j]==1 && vector_true[i][j]==1)   //\u8bed\u4e49+\u5411\u91cf  semantic information and vector consistency\n          {\n          // {\n          ceres::CostFunction* cost_loop =\n              new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                  new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                    id1, id2));\n            problem.AddResidualBlock(cost_loop, \n                                  new ceres::ScaledLoss(new ceres::CauchyLoss(SIGMA_two_EM), L_P_[i][j], ceres::TAKE_OWNERSHIP),\n                                  camera_poses_.data_[id1].transformation_se3_.data(), \n                                  camera_poses_.data_[id2].transformation_se3_.data());\n          }\n\n          if(match.semantic_label[j]==0 && vector_true[i][j]==1)          //\u8bed\u4e49+\u5411\u91cf\n          {\n            int label_one=match.label_one_[j];\n            int label_two=match.label_two_[j];\n          ceres::CostFunction* cost_loop =\n              new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                  new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                    id1, id2));\n          //  if (L_[id1][id2] >= TRUST_ODOMETRY * 0.5) {\n            if(label_one!=100 && label_two!=100){\n            problem.AddResidualBlock(cost_loop, \n                                  new ceres::ScaledLoss(new ceres::CauchyLoss(SIGMA_two_EM), L_P_[i][j]*semantic_p[label_one][label_two], ceres::TAKE_OWNERSHIP),\n                                  camera_poses_.data_[id1].transformation_se3_.data(), \n                                  camera_poses_.data_[id2].transformation_se3_.data());\n            }\n          }\n\n        }\n    }\n    \n\n    // Set solver options (precision / method)\n    ceres::Solver::Options options;\n    // options.max_num_iterations = 1000;\n    options.gradient_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    options.function_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    // options.linear_solver_type = ceres::DENSE_QR;\n    options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n  \n    // Solve\n    std::cout << \"--------------SOLVING----------------ITERATION \" << camera_poses_.index_ << std::endl;\n    ceres::Solver::Summary summary;\n    Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n    std::cout << \"--------------  DONE ----------------ITERATION \" << camera_poses_.index_ << std::endl;\n  }\n  int NumPoses() {\n    return camera_poses_.data_.size();\n  }\n\n  int NumOdometryConstraints() {\n    return odometry_txt_.data_.size();\n  }\n\n  int NumLoopClosureConstraints() {\n    return loop_txt_.data_.size();\n  }\n\n  bool IsConverged_first() {\n    if (last_lambda_ < 0) {\n      // not started yet\n      return false;\n    }\n\n    std::cout << \"new lambda : \"<< lambda_ << std::endl;\n    if (fabs(lambda_ - last_lambda_) > 0.001) {\n      std::cout << \"lambda was updated\" << std::endl;\n      return false;\n    }\n\n    for (int i = 0; i < NumPoses(); i++)\n    {\n      // std::cout << \"checking converging pose : \";\n      Sophus::SE3d last_pose = last_camera_poses_.data_[i].transformation_se3_;\n      Sophus::SE3d current_pose = camera_poses_.data_[i].transformation_se3_;\n\n      double const mse = (last_pose.inverse() * current_pose).log().squaredNorm();\n      bool const converged = mse < 10. * Sophus::Constants<double>::epsilon();\n\n      std::cout << i << \"(\" << mse << \", \" << converged << \",\" << last_camera_poses_.index_ << \"),\";\n      if (!converged) {\n        std::cout << std::endl;\n        return false;\n      }\n    }\n\n    std::cout << std::endl;\n    return true;\n  }\n\n  bool IsConverged_second() {\n    if (last_lambda_second_ < 0) {\n      // not started yet\n      return false;\n    }\n\n    std::cout << \"new lambda_second : \"<< lambda_second_ << std::endl;\n    if (fabs(lambda_second_ - last_lambda_second_) > 0.01) {\n      std::cout << \"lambda was updated\" << std::endl;\n      return false;\n    }\n\n    for (int i = 0; i < NumPoses(); i++)\n    {\n      // std::cout << \"checking converging pose : \";\n      Sophus::SE3d last_pose = last_camera_poses_.data_[i].transformation_se3_;\n      Sophus::SE3d current_pose = camera_poses_.data_[i].transformation_se3_;\n\n      double const mse = (last_pose.inverse() * current_pose).log().squaredNorm();\n      bool const converged = mse < 10. * Sophus::Constants<double>::epsilon();\n\n      std::cout << i << \"(\" << mse << \", \" << converged << \",\" << last_camera_poses_.index_ << \"),\";\n      if (!converged) {\n        std::cout << std::endl;\n        return false;\n      }\n    }\n    std::cout << std::endl;\n    return true;\n  }\n};\n\n\n\nbool test(Sophus::SE3d const& T_w_targ, Sophus::SE3d const& T_w_init,\n          Sophus::SE3d::Point const& point_a_init,\n          Sophus::SE3d::Point const& point_b) {\n  static constexpr int kNumPointParameters = 3;\n\n  // Optimisation parameters.\n  Sophus::SE3d T_wr = T_w_init;\n  Sophus::SE3d::Point point_a = point_a_init;\n\n  // Build the problem.\n  ceres::Problem problem;\n\n  // Specify local update rule for our parameter\n  problem.AddParameterBlock(T_wr.data(), Sophus::SE3d::num_parameters,\n                            new Sophus::test::LocalParameterizationSE3);\n\n  // Create and add cost functions. Derivatives will be evaluated via\n  // automatic differentiation\n  ceres::CostFunction* cost_function1 =\n      new ceres::AutoDiffCostFunction<TestSE3CostFunctor, Sophus::SE3d::DoF,\n                                      Sophus::SE3d::num_parameters>(\n          new TestSE3CostFunctor(T_w_targ.inverse()));\n  problem.AddResidualBlock(cost_function1, NULL, T_wr.data());\n\n  ceres::CostFunction* cost_function2 =\n      new ceres::AutoDiffCostFunction<TestPointCostFunctor, kNumPointParameters,\n                                      Sophus::SE3d::num_parameters,\n                                      kNumPointParameters>(\n          new TestPointCostFunctor(T_w_targ.inverse(), point_b));\n  problem.AddResidualBlock(cost_function2, NULL, T_wr.data(), point_a.data());\n\n  // Set solver options (precision / method)\n  ceres::Solver::Options options;\n  options.gradient_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n  options.function_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n  options.linear_solver_type = ceres::DENSE_QR;\n\n  // Solve\n  ceres::Solver::Summary summary;\n  Solve(options, &problem, &summary);\n  std::cout << summary.BriefReport() << std::endl;\n\n  // Difference between target and parameter\n  double const mse = (T_w_targ.inverse() * T_wr).log().squaredNorm();\n  bool const passed = mse < 10. * Sophus::Constants<double>::epsilon();\n  return passed;\n}\n\ntemplate <typename Scalar>\nbool CreateSE3FromMatrix(Eigen::Matrix<Scalar, 4, 4> mat) {\n  auto se3 = Sophus::SE3<Scalar>(mat);\n  se3 = se3;\n  return true;\n}\n\nint main(int argc, char** argv) {\n\n  std::cout << \"cauchy_em started\" << std::endl;\n  clock_t start = clock() ; \n\n  if (argc == 7)\n  {\n\n    // converge  detect for EM first and second initial\n    double lambda = 0.99;\n    R2EM_CauchyUniform r2em_c(lambda);\n\n    std::cout << \"LoadOdometryTxt\" << std::endl;\n    r2em_c.LoadOdometryTxt(argv[1]);\n\n    std::cout << \"LoadLoopTxt\" << std::endl;\n    r2em_c.LoadLoopTxt(argv[2]);\n\n    std::cout << \"InitCameraPosesWithZhou\" << std::endl;\n    r2em_c.InitCameraPosesWithZhou(argv[3]);\n\n    //\u521d\u59cb\u5316\n  r2em_c.L_P_.resize(r2em_c.NumLoopClosureConstraints()+r2em_c.NumOdometryConstraints());\n    for (int i = 0; i < r2em_c.NumLoopClosureConstraints()+r2em_c.NumOdometryConstraints(); i++) {\n      r2em_c.L_P_[i].resize(200);                    \n    }\n\n  r2em_c.L_vector.resize(r2em_c.NumPoses());\n    for (int i = 0; i < r2em_c.NumPoses(); i++) {\n      r2em_c.L_vector[i].resize(r2em_c.NumPoses());\n    }\n\n  r2em_c.vector_true.resize(r2em_c.NumLoopClosureConstraints()+r2em_c.NumOdometryConstraints());\n    for (int i = 0; i < r2em_c.NumLoopClosureConstraints()+r2em_c.NumOdometryConstraints(); i++) {\n      r2em_c.vector_true[i].resize(200);       \n    }\n\n    std::cout << \"EstimateLAMBDA\" << std::endl;\n    r2em_c.EstimateLAMBDA();\n\n    LoadFromFile_semantic_p(argv[4]);\n  std::cout << \"semantic probability matrix\" << std::endl;\n    r2em_c.Vector();\n    std::cout << \"START EM\" << std::endl;\n\n    //\u7b2c\u4e00\u6b21EM\u8fed\u4ee3\uff0c\u7528\u4e8e\u7b5b\u9664\u9519\u8bef\u7684loop    first EM iteration\n    for (int i = 0 ; i < NUM_ITERATION_EM; i ++) {\n      r2em_c.Expectation(i);\n      r2em_c.Maximization();\n\n      std::cout << \"check 1 \" << std::endl;\n      \n\n      std::cout << \"check EM converges in iteration \" << i << std::endl;\n      if (r2em_c.IsConverged_first()) {\n        std::cout << \"EM converges! \" << std::endl;\n        break;\n      }\n    }\n    clock_t finish_1 = clock() ; \n\n    r2em_c.SaveCameraPoses(\"/home/tang/undergraduate/RobustPCLReconstruction-cauchy_em/data/cauchy/poses_first_EM.txt\");\n    //\u7b2c\u4e8c\u6b21EM\u8fed\u4ee3\uff0c\u7528\u4e8e\u7b5b\u9664\u6b63\u786eloop\u4e2d\u7684\u9519\u8bef\u70b9\u5bf9\n    //second EM iteration\n    for (int i = 0 ; i < NUM_ITERATION_EM; i ++) {\n      r2em_c.Expectation_point(i); \n      r2em_c.Maximization_point();\n\nstd::string iteration_pose=\"/home/tang/undergraduate/RobustPCLReconstruction-cauchy_em/data/cauchy/\u591a\u673a/07-10%\u6b63\u786e-\u5404\u4ee3\u4f4d\u59ff/pose_second\"+std::to_string(i)+\".txt\";\n  r2em_c.SaveCameraPoses(iteration_pose.c_str());\n\n      std::cout << \"check 1 \" << std::endl;\n\n      std::cout << \"check EM converges in iteration \" << i << std::endl;\n      if (r2em_c.IsConverged_second()) {\n        std::cout << \"EM second converges! \" << std::endl;\n        break;\n      }\n    }\n    clock_t finish_2 = clock() ; \n\n      r2em_c.SaveCameraPoses(argv[5]);\n      std::cout << \"final poses are saved to \" << argv[5] << std::endl;\n\n\n      r2em_c.SaveLinks(argv[6]);\n      std::cout << \"links are saved to \" << argv[6] << std::endl;\n\n    std::cout << \"there are \" << r2em_c.NumPoses() << \" poses\" << std::endl;\n    std::cout << \"there are \" << r2em_c.NumLoopClosureConstraints() << \" loops\" << std::endl;\n\n    // efficiency\n    std::cout << \"first EM time is : \" << double((finish_1-start)/1000) << \"ms\" << std::endl;\n    std::cout << \"second EM time is : \" << double((finish_2-finish_1)/1000) << \"ms\" << std::endl;\n    // std::cout << start << std::endl;\n    // std::cout << finish_1 << std::endl;\n    // std::cout << finish_2 << std::endl;\n    //  std::cout << CLOCKS_PER_SEC << std::endl;\n  \n  } else {\n    std::cout << \"input format is : odom.txt loop.txt init.txt final.txt link.txt\" << std::endl;\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "99842ce76b091137a016fc624a4239039f80e465", "size": 54412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ceres/cauchy_em_two_EM.cpp", "max_stars_repo_name": "BIT-TYJ/EO-RCL", "max_stars_repo_head_hexsha": "ea41ab441fa43753a6d7ecb1bddf96814add3d8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T15:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T15:01:35.000Z", "max_issues_repo_path": "test/ceres/cauchy_em_two_EM.cpp", "max_issues_repo_name": "BIT-TYJ/EO-RCL", "max_issues_repo_head_hexsha": "ea41ab441fa43753a6d7ecb1bddf96814add3d8e", "max_issues_repo_licenses": ["MIT"], "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/ceres/cauchy_em_two_EM.cpp", "max_forks_repo_name": "BIT-TYJ/EO-RCL", "max_forks_repo_head_hexsha": "ea41ab441fa43753a6d7ecb1bddf96814add3d8e", "max_forks_repo_licenses": ["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.5723636364, "max_line_length": 181, "alphanum_fraction": 0.5674851136, "num_tokens": 16416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18998546280942236}}
{"text": "#ifndef STAN_MATH_TORSTEN_PKMODELTWOCPT2_HPP\n#define STAN_MATH_TORSTEN_PKMODELTWOCPT2_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/prim/scal/err/check_greater_or_equal.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/torsten/event_solver.hpp>\n#include <stan/math/torsten/events_manager.hpp>\n#include <stan/math/torsten/PKModel/PKModel.hpp>\n#include <stan/math/torsten/PKModel/Pred/Pred1_twoCpt.hpp>\n#include <stan/math/torsten/PKModel/Pred/PredSS_twoCpt.hpp>\n#include <stan/math/torsten/pmx_twocpt_model.hpp>\n#include <stan/math/torsten/pmx_population_check.hpp>\n#include <stan/math/torsten/return_type.hpp>\n#include <string>\n#include <vector>\n\nnamespace torsten {\n\n/**\n * Computes the predicted amounts in each compartment at each event\n * for a two compartment model with first oder absorption.\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 scalars for the model parameters.\n * @tparam T5 type of scalars for the \n * @param[in] pMatrix parameters at each event\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 * @return a matrix with predicted amount in each compartment\n *         at each event.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          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_twocpt(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<std::vector<T4> >& pMatrix,\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 stan::math::check_positive_finite;\n  using refactor::PKRec;\n\n  int nCmt = refactor::PMXTwoCptModel<double, double, double, double>::Ncmt;\n  int nParms = refactor::PMXTwoCptModel<double, double, double, double>::Npar;\n  static const char* function(\"pmx_solve_twocpt\");\n\n  // Check arguments\n  torsten::pmx_check(time, amt, rate, ii, evid, cmt, addl, ss,\n                pMatrix, biovar, tlag, function);\n  for (size_t i = 0; i < pMatrix.size(); i++) {\n    check_positive_finite(function, \"PK parameter CL\", pMatrix[i][0]);\n    check_positive_finite(function, \"PK parameter Q\", pMatrix[i][1]);\n    check_positive_finite(function, \"PK parameter V2\", pMatrix[i][2]);\n    check_positive_finite(function, \"PK parameter V3\", pMatrix[i][3]);\n  }\n  std::string message4 = \", but must equal the number of parameters in the model: \" // NOLINT\n    + boost::lexical_cast<std::string>(nParms) + \"!\";\n  const char* length_error4 = message4.c_str();\n  if (!(pMatrix[0].size() == (size_t) nParms))\n    stan::math::invalid_argument(function,\n    \"The number of parameters per event (length of a vector in the first argument) is\", // NOLINT\n    pMatrix[0].size(), \"\", length_error4);\n\n  // FIX ME - we want to check every array of pMatrix, not\n  // just the first one (at index 0)\n  std::string message5 = \", but must equal the number of parameters in the model: \" // NOLINT\n  + boost::lexical_cast<std::string>(nParms) + \"!\";\n  const char* length_error5 = message5.c_str();\n  if (!(pMatrix[0].size() == (size_t) nParms))\n    stan::math::invalid_argument(function,\n    \"The number of parameters per event (length of a vector in the ninth argument) is\", // NOLINT\n    pMatrix[0].size(), \"\", length_error5);\n\n  std::string message6 = \", but must equal the number of compartments in the model: \" // NOLINT\n  + boost::lexical_cast<std::string>(nCmt) + \"!\";\n  const char* length_error6 = message6.c_str();\n  if (!(biovar[0].size() == (size_t) nCmt))\n    stan::math::invalid_argument(function,\n    \"The number of biovariability parameters per event (length of a vector in the tenth argument) is\", // NOLINT\n    biovar[0].size(), \"\", length_error6);\n\n  if (!(tlag[0].size() == (size_t) nCmt))\n    stan::math::invalid_argument(function,\n    \"The number of lag times parameters per event (length of a vector in the eleventh argument) is\", // NOLINT\n    tlag[0].size(), \"\", length_error5);\n\n  // Construct dummy matrix for last argument of pred\n  Matrix<T4, Dynamic, Dynamic> dummy_system;\n  vector<Matrix<T4, Dynamic, Dynamic> >\n    dummy_systems(1, dummy_system);\n\n#ifdef OLD_TORSTEN\n  return Pred(time, amt, rate, ii, evid, cmt, addl, ss,\n              pMatrix, biovar, tlag,\n              nCmt, dummy_systems,\n              Pred1_twoCpt(), PredSS_twoCpt());\n#else\n  using ER = NONMENEventsRecord<T0, T1, T2, T3, std::vector<T4>, T5, T6>;\n  using EM = EventsManager<ER>;\n  const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, 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::PMXTwoCptModel<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 an std::vector for \n * pMatrix/bioavailability/tlag\n */\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T_par, typename T_biovar, typename T_tlag,\n               typename\n            std::enable_if_t<\n              !(torsten::is_std_vector<T_par>::value && 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,\n                                            typename torsten::value_type<T_par>::type,\n                                            typename torsten::value_type<T_biovar>::type,\n                                            typename torsten::value_type<T_tlag>::type>::type,\n                 Eigen::Dynamic, Eigen::Dynamic>\n  pmx_solve_twocpt(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<T_par>& pMatrix,\n                   const std::vector<T_biovar>& biovar,\n                   const std::vector<T_tlag>& tlag) {\n    auto param_ = torsten::to_array_2d(pMatrix);\n    auto biovar_ = torsten::to_array_2d(biovar);\n    auto tlag_ = torsten::to_array_2d(tlag);\n\n    return pmx_solve_twocpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                            param_, biovar_, tlag_);\n  }\n\n  // old version\n  template <typename T0, typename T1, typename T2, typename T3, typename T4,\n            typename T5, typename T6>\n  Eigen::Matrix <typename torsten::return_t<T0, T1, T2, T3, T4, T5, T6>::type,\n                 Eigen::Dynamic, Eigen::Dynamic>\n  PKModelTwoCpt(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<std::vector<T4> >& pMatrix,\n                const std::vector<std::vector<T5> >& biovar,\n                const std::vector<std::vector<T6> >& tlag) {\n    auto x = pmx_solve_twocpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                              pMatrix, biovar, tlag);\n    return x.transpose();\n  }\n\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T_par, typename T_biovar, typename T_tlag,\n               typename\n            std::enable_if_t<\n              !(torsten::is_std_vector<T_par>::value && 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,\n                                            typename torsten::value_type<T_par>::type,\n                                            typename torsten::value_type<T_biovar>::type,\n                                            typename torsten::value_type<T_tlag>::type>::type,\n                 Eigen::Dynamic, Eigen::Dynamic>\n  PKModelTwoCpt(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<T_par>& pMatrix,\n                   const std::vector<T_biovar>& biovar,\n                   const std::vector<T_tlag>& tlag) {\n    auto x = pmx_solve_twocpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                            pMatrix, biovar, tlag);\n    return x.transpose();\n  }\n\n  /* \n   * For population models, we follow the call signature\n   * but add the arrays of the length of each individual's data. \n   * The size of that vector is the size of\n   * the population.\n   */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix<typename EventsManager<NONMENEventsRecord<T0, T1, T2, T3, std::vector<T4>, T5, T6> >::T_scalar, // NOLINT\n              Eigen::Dynamic, Eigen::Dynamic>\npmx_solve_group_twocpt(const std::vector<int>& len,\n                       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<std::vector<T4> >& pMatrix,\n                       const std::vector<std::vector<T5> >& biovar,\n                       const std::vector<std::vector<T6> >& tlag) {\n  using ER = NONMENEventsRecord<T0, T1, T2, T3, std::vector<T4>, T5, T6>;\n  using EM = EventsManager<ER>;\n\n  int nCmt = refactor::PMXTwoCptModel<double, double, double, double>::Ncmt;\n  ER events_rec(nCmt, len, time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, biovar, tlag);\n\n  static const char* caller(\"pmx_solve_group_twocpt\");\n  torsten::pmx_population_check(len, time, amt, rate, ii, evid, cmt, addl, ss,\n                                pMatrix, biovar, tlag, caller);\n\n  using model_type = refactor::PMXTwoCptModel<typename EM::T_time, typename EM::T_scalar, typename EM::T_rate, typename EM::T_par>;\n  EventSolver<model_type> pr;\n\n  Eigen::Matrix<typename EM::T_scalar, -1, -1> pred(events_rec.total_num_event_times, nCmt);\n\n  pr.pred(events_rec, pred);\n\n  return pred;\n}\n\n}\n#endif\n", "meta": {"hexsha": "17913ec804dfe874a821c7cfeb4f39b71576ea93", "size": 11999, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/pmx_solve_twocpt.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_twocpt.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_twocpt.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": 45.6235741445, "max_line_length": 159, "alphanum_fraction": 0.6118009834, "num_tokens": 3179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.18995623629289654}}
{"text": "#pragma once\n#include <fc/crypto/elliptic.hpp>\n#include <boost/config.hpp>\n\n#ifdef _MSC_VER\nextern \"C\"{\n    struct ECDSA_SIG_st {\n        BIGNUM *r;\n        BIGNUM *s;\n    };\n}\n#endif\n\n/* public_key_impl implementation based on openssl\n * used by mixed + openssl\n */\n\nnamespace fc { namespace ecc { namespace detail {\n\nvoid _init_lib();\n\nclass public_key_impl\n{\n    public:\n        public_key_impl() BOOST_NOEXCEPT;\n        public_key_impl( const public_key_impl& cpy ) BOOST_NOEXCEPT;\n        public_key_impl( public_key_impl&& cpy ) BOOST_NOEXCEPT;\n        ~public_key_impl() BOOST_NOEXCEPT;\n\n        public_key_impl& operator=( const public_key_impl& pk ) BOOST_NOEXCEPT;\n\n        public_key_impl& operator=( public_key_impl&& pk ) BOOST_NOEXCEPT;\n\n        static int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check);\n\n        EC_KEY* _key = nullptr;\n\n    private:\n        void free_key() BOOST_NOEXCEPT;\n};\n\n}}}\n", "meta": {"hexsha": "0e7b47c4fdf0fca1bacc81257939e382dc7ac037", "size": 986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/crypto/_elliptic_impl_pub.hpp", "max_stars_repo_name": "Jack-Cheung/fc", "max_stars_repo_head_hexsha": "48092ac0c65036c3972229d45bff54c2f07e6449", "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/crypto/_elliptic_impl_pub.hpp", "max_issues_repo_name": "Jack-Cheung/fc", "max_issues_repo_head_hexsha": "48092ac0c65036c3972229d45bff54c2f07e6449", "max_issues_repo_licenses": ["MIT"], "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/crypto/_elliptic_impl_pub.hpp", "max_forks_repo_name": "Jack-Cheung/fc", "max_forks_repo_head_hexsha": "48092ac0c65036c3972229d45bff54c2f07e6449", "max_forks_repo_licenses": ["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.9302325581, "max_line_length": 138, "alphanum_fraction": 0.6855983773, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.18995294900330906}}
{"text": "#include <ros/ros.h>\n#include <boost/thread.hpp>\n#include <armadillo>\n#include <geometry_msgs/Twist.h>\n#include <string>\n\n//Includes specific to this package\n#include <jog_controller/twist_to_jog_frame.h>\n#include \"jog_msgs/JogFrame.h\"\n#include \"jog_msgs/ControllerStatus.h\"\n#include \"jog_msgs/GetTargetList.h\"\n#include \"jog_msgs/SetTarget.h\"\n#include \"jog_msgs/SetCollisionAvoidance.h\"\n\nnamespace jog_controller\n{\n\nTwistToJogFrame::TwistToJogFrame()\n{\n  ros::NodeHandle nh, pnh(\"~\");\n  jog_frame_pub_ = nh.advertise<jog_msgs::JogFrame>(\"jog_frame\", 1);\n  get_target_frame_list_srv_ = nh.advertiseService(\"/twist_to_jog_frame/get_target_frame_list\", &TwistToJogFrame::getTargetFrameList, this);\n  set_controller_status_srv_ = nh.advertiseService(\"/twist_to_jog_frame/set_controller_status\", &TwistToJogFrame::setControllerStatus, this);\n  set_target_frame_srv_ = nh.advertiseService(\"/twist_to_jog_frame/set_target_frame\", &TwistToJogFrame::setTargetFrame, this);\n  set_target_link_srv_ = nh.advertiseService(\"/twist_to_jog_frame/set_target_link\", &TwistToJogFrame::setTargetLink, this);\n  pnh.getParam(\"/jog_frame_node/group_names\", group_names_);\n  pnh.getParam(\"/jog_frame_node/link_names\", link_names_);\n  pnh.getParam(\"group_name\", group_name_);\n  pnh.getParam(\"link_name\", link_name_);\n  pnh.getParam(\"frame_id\", frame_id_);\n  pnh.getParam(\"rotate_axes\", rotate_axes_);\n  std::string str_rotation_matrix_;\n  pnh.getParam(\"rotation_matrix\", str_rotation_matrix_); \n  rotation_matrix_ = arma::mat(str_rotation_matrix_);\n  pnh.getParam(\"dominant_axis_mode\", dominant_axis_mode_);\n  pnh.getParam(\"scale_linear\", scale_linear_);\n  pnh.getParam(\"scale_angular\", scale_angular_);\n  pnh.getParam(\"sub_topic\", sub_topic_);\n  pnh.param(\"avoid_collisions\", avoid_collisions_, true);\n  pnh.getParam(\"controller_enabled\", controller_enabled_);\n  twist_sub_ = nh.subscribe(sub_topic_, 10, &TwistToJogFrame::twistCallback, this);\n  ros::topic::waitForMessage<geometry_msgs::Twist>(sub_topic_);\n}\n\nvoid TwistToJogFrame::keepOnlyDominantAxis(arma::vec6 &twist_p)\n{\n  double min = twist_p.min();\n  double max = twist_p.max();\n  double min_max = max + min;\n  if(min_max > 0){\n    arma::uword i = twist_p.index_max();\n    twist_p.zeros();\n    twist_p.at(i) = max;\n  } else {\n    arma::uword i = twist_p.index_min();\n    twist_p.zeros();\n    twist_p.at(i) = min;\n  }\n}\n\nvoid TwistToJogFrame::rotateAxes(arma::vec6 &twist_p)\n{\n  arma::vec linear = arma::vec3({twist_p.at(0), twist_p.at(1), twist_p.at(2)});\n  arma::vec angular = arma::vec3({twist_p.at(3), twist_p.at(4), twist_p.at(5)});\n\n  linear = rotation_matrix_ * linear;\n  angular = rotation_matrix_ * angular;\n\n  //Write in original vector\n  for(arma::uword i = 0; i < 3; i++){ \n    twist_p[i] = linear[i];\n    twist_p[i+3] = angular[i];\n  }\n}\n\nbool TwistToJogFrame::hasDuplicate(const arma::vec6 &twist_p)\n{\n  arma::vec nz_tmp = arma::nonzeros(twist_p);\n  arma::vec unique_tmp = arma::unique(nz_tmp);\n  return size(unique_tmp) != size(nz_tmp);\n}\n\nvoid TwistToJogFrame::scaleCommand(arma::vec6 &twist_p)\n{\n  for(arma::uword i = 0; i < 3; i++)\n  {\n    // x,y,z\n    twist_p.at(i) = twist_p.at(i) * scale_linear_; \n    // rx,ry,rz\n    twist_p.at(i+3) = twist_p.at(i+3) * scale_angular_;\n  }\n}\n\nvoid TwistToJogFrame::twistCallback(const geometry_msgs::TwistConstPtr &twist)\n{\n  boost::mutex::scoped_lock lock(mutex_);\n\n  // publish\n  jog_msgs::JogFrame msg;\n  msg.header.stamp = ros::Time::now();\n  msg.header.frame_id = frame_id_;\n  msg.group_name = group_name_;\n  msg.link_name = link_name_;\n\n  arma::vec6 v_twist = arma::vec6({twist->linear.x, twist->linear.y, twist->linear.z, twist->angular.x, twist->angular.y, twist->angular.z});\n\n  if(rotate_axes_)\n  {\n    rotateAxes(v_twist);\n  }\n\n  scaleCommand(v_twist);\n\n  if(dominant_axis_mode_)\n  {\n    if(hasDuplicate(v_twist))\n    {\n      v_twist.zeros(); //handling the edge case\n    } else {\n      keepOnlyDominantAxis(v_twist);\n    }\n  }\n\n  msg.avoid_collisions = avoid_collisions_;\n\n  // Publish if the button is enabled and if at least one of the commands is different from zero.\n  if(controller_enabled_ && arma::any(v_twist))\n  {\n    //Adding linear and angular values to the msg.\n    msg.linear_delta.x = v_twist.at(0);\n    msg.linear_delta.y = v_twist.at(1);\n    msg.linear_delta.z = v_twist.at(2);\n    msg.angular_delta.x = v_twist.at(3);\n    msg.angular_delta.y = v_twist.at(4);\n    msg.angular_delta.z = v_twist.at(5);\n\n    jog_frame_pub_.publish(msg);\n  }  \n}  \n\nbool TwistToJogFrame::getTargetFrameList(jog_msgs::GetTargetListRequest &req, jog_msgs::GetTargetListResponse &res)\n{\n  res.target = link_names_;\n  return true;\n}\n\n//callback for controller_enable service\nbool TwistToJogFrame::setControllerStatus(jog_msgs::ControllerStatusRequest &req, jog_msgs::ControllerStatusResponse &res)\n{\n  controller_enabled_ = req.status;\n  return true;\n}\n\nbool TwistToJogFrame::setTargetFrame(jog_msgs::SetTargetRequest &target_frame, jog_msgs::SetTargetResponse &res)\n{\n  frame_id_ = target_frame.name;\n  return true;\n}\n\nbool TwistToJogFrame::setTargetLink(jog_msgs::SetTargetRequest &target_link, jog_msgs::SetTargetResponse &res)\n{\n  link_name_ = target_link.name;\n  return true;\n}\n\nbool TwistToJogFrame::setCollisionAvoidance(jog_msgs::SetCollisionAvoidanceRequest &req, jog_msgs::SetCollisionAvoidanceResponse &res)\n{\n  avoid_collisions_ = req.status;\n  return true;\n}\n\n}  // namespace jog_controller\n\n/**\n * @brief Main function of the node\n */\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"twist_to_jog_frame\");\n  jog_controller::TwistToJogFrame node;\n\n  ros::Rate loop_rate(10);\n  while ( ros::ok() )\n  {\n    ros::spinOnce();\n    loop_rate.sleep();\n  }\n  return 0;\n}", "meta": {"hexsha": "4d643b39d3022a8ebad8148cc442b791074c2607", "size": 5678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jog_controller/src/twist_to_jog_frame.cpp", "max_stars_repo_name": "clubcapra/jog_control", "max_stars_repo_head_hexsha": "708409bfa3bd2956375b54d7b0bb7b1a5a815c6d", "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": "jog_controller/src/twist_to_jog_frame.cpp", "max_issues_repo_name": "clubcapra/jog_control", "max_issues_repo_head_hexsha": "708409bfa3bd2956375b54d7b0bb7b1a5a815c6d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-08-30T17:32:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-15T17:13:17.000Z", "max_forks_repo_path": "jog_controller/src/twist_to_jog_frame.cpp", "max_forks_repo_name": "clubcapra/jog_control", "max_forks_repo_head_hexsha": "708409bfa3bd2956375b54d7b0bb7b1a5a815c6d", "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.0423280423, "max_line_length": 141, "alphanum_fraction": 0.7263120817, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.18985858565612165}}
{"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_DSL_FUNCTIONS_PACK_TERMINAL_HPP_INCLUDED\n#define BOOST_SIMD_DSL_FUNCTIONS_PACK_TERMINAL_HPP_INCLUDED\n\n#include <boost/simd/dsl/functions/terminal.hpp>\n#include <boost/simd/sdk/functor/preprocessor/call.hpp>\n#include <boost/proto/traits.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION_TPL( boost::simd::tag::terminal_,tag::cpu_\n                                , (class Value)(class State)\n                                  (class Data)(std::size_t N)\n                                , ((array_<scalar_< arithmetic_<Value > >,N>))\n                                  ((target_<array_<scalar_< arithmetic_<State> >,N> >))\n                                  (scalar_< integer_<Data> >)\n                                )\n{\n    typedef typename Value::value_type result_type;\n\n    BOOST_DISPATCH_FORCE_INLINE result_type\n    operator()( Value const& v, State const&, Data const& p ) const\n    {\n      return v[p];\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "9e8399422f2d51362df2eea4d30507c2e7d223fa", "size": 1502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/dsl/functions/pack/terminal.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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/sdk/include/boost/simd/dsl/functions/pack/terminal.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/boost/simd/sdk/include/boost/simd/dsl/functions/pack/terminal.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": 40.5945945946, "max_line_length": 87, "alphanum_fraction": 0.5299600533, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.18985858565612163}}
{"text": "// All content Copyright (C) 2018 Genomics plc\n#include \"variant/type/variant.hpp\"\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <string>\n\nusing wecall::utils::ReferenceSequence;\nusing wecall::caller::Region;\n\nBOOST_AUTO_TEST_CASE( mnp )\n{\n    using namespace wecall::variant;\n\n    std::string contig = \"1\";\n    const std::string removed( \"ABCD\" );\n    const std::string added( \"HELL\" );\n\n    const auto referenceSequence =\n        std::make_shared< ReferenceSequence >( Region( contig, 1000000, 1000000 + removed.size() ), removed );\n    varPtr_t theMNP = std::make_shared< Variant >( referenceSequence, referenceSequence->region(), added );\n\n    BOOST_CHECK_EQUAL( theMNP->sequence(), added );\n    BOOST_CHECK_EQUAL( theMNP->refSequence().sequence(), removed );\n\n    BOOST_CHECK_EQUAL( theMNP->start(), 1000000 );\n    BOOST_CHECK_EQUAL( theMNP->end(), 1000004 );\n\n    auto nDiffs = 4;\n    auto expectedPrior = 5e-5 * pow( 0.1, nDiffs - 1 ) * ( 1.0 - 0.1 );\n\n    wecall::variant::setDefaultPriors( {theMNP} );\n    BOOST_CHECK_CLOSE( theMNP->prior(), expectedPrior, 1e-5 );\n}\n\nBOOST_AUTO_TEST_CASE( testMnpLeftAlignDoesntChangePosition )\n{\n    using namespace wecall::variant;\n\n    std::string contig = \"1\";\n    const std::string seq = \"TT\";\n\n    const auto referenceSequence = std::make_shared< ReferenceSequence >( Region( contig, 0, 10 ), \"ATATATATAA\" );\n\n    varPtr_t theMnp = std::make_shared< Variant >( referenceSequence, Region( contig, 8, 10 ), seq );\n\n    theMnp->getLeftAligned( 0 );\n\n    BOOST_CHECK_EQUAL( theMnp->start(), 8 );\n}\n", "meta": {"hexsha": "297b4c04c2b00ae7dac0407e411198041cf08524", "size": 1571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/test/unittest/variant/testMnp.cpp", "max_stars_repo_name": "dylex/wecall", "max_stars_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T15:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:13:05.000Z", "max_issues_repo_path": "cpp/test/unittest/variant/testMnp.cpp", "max_issues_repo_name": "dylex/wecall", "max_issues_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T12:32:56.000Z", "max_forks_repo_path": "cpp/test/unittest/variant/testMnp.cpp", "max_forks_repo_name": "dylex/wecall", "max_forks_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:28:33.000Z", "avg_line_length": 30.8039215686, "max_line_length": 114, "alphanum_fraction": 0.6868236792, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.18985858565612163}}
{"text": "// Boost.Geometry Index\r\n//\r\n// boxes union/intersection area/volume\r\n//\r\n// Copyright (c) 2011-2014 Adam Wulkiewicz, Lodz, Poland.\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_INDEX_DETAIL_ALGORITHMS_INTERSECTION_CONTENT_HPP\r\n#define BOOST_GEOMETRY_INDEX_DETAIL_ALGORITHMS_INTERSECTION_CONTENT_HPP\r\n\r\n#include <boost/geometry/algorithms/intersection.hpp>\r\n#include <boost/geometry/strategies/intersection.hpp>\r\n#include <boost/geometry/index/detail/algorithms/content.hpp>\r\n\r\nnamespace boost { namespace geometry { namespace index { namespace detail {\r\n\r\n/**\r\n * \\brief Compute the area of the intersection of b1 and b2\r\n */\r\ntemplate <typename Box>\r\ninline typename default_content_result<Box>::type intersection_content(Box const& box1, Box const& box2)\r\n{\r\n    if ( geometry::intersects(box1, box2) )\r\n    {\r\n        Box box_intersection;\r\n        if ( geometry::intersection(box1, box2, box_intersection) )\r\n            return detail::content(box_intersection);\r\n    }\r\n    return 0;\r\n}\r\n\r\n}}}} // namespace boost::geometry::index::detail\r\n\r\n#endif // BOOST_GEOMETRY_INDEX_DETAIL_ALGORITHMS_INTERSECTION_CONTENT_HPP\r\n", "meta": {"hexsha": "7399af0855da593ec6e859ceb46c9bf2e54f2280", "size": 1297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/index/detail/algorithms/intersection_content.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/index/detail/algorithms/intersection_content.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/index/detail/algorithms/intersection_content.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 34.1315789474, "max_line_length": 105, "alphanum_fraction": 0.7409406322, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.18985858211336915}}
{"text": "#include <boost/hana.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <string>\n#include <iostream>\n\nstruct person {\n    BOOST_HANA_DEFINE_STRUCT(person,\n        (std::string, name),\n        (int, age)\n    );\n};\n\ntemplate <class T>\ntypename boost::disable_if<boost::hana::Foldable<T>>::type serialize(T t) { std::cout << t << '\\n'; }\n\ntemplate <class T>\ntypename boost::enable_if<boost::hana::Foldable<T>>::type serialize(T t) { boost::hana::for_each(t, [](auto pair){ std::cout << boost::hana::second(pair) << '\\n'; }); }\n\nint main()\n{\n    person tom{ \"Tom\", 35 };\n    serialize(tom);\n\n    std::string s{\"String\"};\n    serialize(s);\n\n    int i{1};\n    serialize(i);\n}\n", "meta": {"hexsha": "0028038734a6b0dfa456ee0c867c75855aee0be7", "size": 672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "27_boost_hana_serialize_boost_enable_if/27_boost_hana_serialize_boost_enable_if.cpp", "max_stars_repo_name": "BorisSchaeling/boost-meta-programming", "max_stars_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "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": "27_boost_hana_serialize_boost_enable_if/27_boost_hana_serialize_boost_enable_if.cpp", "max_issues_repo_name": "BorisSchaeling/boost-meta-programming", "max_issues_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "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": "27_boost_hana_serialize_boost_enable_if/27_boost_hana_serialize_boost_enable_if.cpp", "max_forks_repo_name": "BorisSchaeling/boost-meta-programming", "max_forks_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-03T08:29:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-29T08:42:49.000Z", "avg_line_length": 22.4, "max_line_length": 168, "alphanum_fraction": 0.6160714286, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1898585785706167}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include <boost/preprocessor/control/if.hpp>\n\n#include \"DataStructures/DataBox/PrefixHelpers.hpp\"\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Actions/VolumeTermsImpl.tpp\"\n#include \"Evolution/Systems/NewtonianEuler/System.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/TimeDerivativeTerms.hpp\"\n#include \"PointwiseFunctions/AnalyticData/NewtonianEuler/KhInstability.hpp\"\n#include \"PointwiseFunctions/AnalyticSolutions/NewtonianEuler/IsentropicVortex.hpp\"\n#include \"PointwiseFunctions/AnalyticSolutions/NewtonianEuler/LaneEmdenStar.hpp\"\n#include \"PointwiseFunctions/AnalyticSolutions/NewtonianEuler/RiemannProblem.hpp\"\n#include \"PointwiseFunctions/AnalyticSolutions/NewtonianEuler/SmoothFlow.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n\nnamespace evolution::dg::Actions::detail {\n#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)\n#define INITIAL_DATA_TYPE(data) BOOST_PP_TUPLE_ELEM(1, data)<DIM(data)>\n#define SYSTEM(data) \\\n  ::NewtonianEuler::System<DIM(data), INITIAL_DATA_TYPE(data)>\n\n#define INSTANTIATION(r, data)                                                \\\n  template void volume_terms<::NewtonianEuler::TimeDerivativeTerms<           \\\n      DIM(data), INITIAL_DATA_TYPE(data)>>(                                   \\\n      const gsl::not_null<Variables<db::wrap_tags_in<                         \\\n          ::Tags::dt, typename SYSTEM(data)::variables_tag::tags_list>>*>     \\\n          dt_vars_ptr,                                                        \\\n      const gsl::not_null<Variables<db::wrap_tags_in<                         \\\n          ::Tags::Flux, typename SYSTEM(data)::flux_variables,                \\\n          tmpl::size_t<DIM(data)>, Frame::Inertial>>*>                        \\\n          volume_fluxes,                                                      \\\n      const gsl::not_null<Variables<db::wrap_tags_in<                         \\\n          ::Tags::deriv, typename SYSTEM(data)::gradient_variables,           \\\n          tmpl::size_t<DIM(data)>, Frame::Inertial>>*>                        \\\n          partial_derivs,                                                     \\\n      const gsl::not_null<Variables<typename SYSTEM(                          \\\n          data)::compute_volume_time_derivative_terms::temporary_tags>*>      \\\n          temporaries,                                                        \\\n      const Variables<typename SYSTEM(data)::variables_tag::tags_list>&       \\\n          evolved_vars,                                                       \\\n      const ::dg::Formulation dg_formulation, const Mesh<DIM(data)>& mesh,    \\\n      [[maybe_unused]] const tnsr::I<DataVector, DIM(data), Frame::Inertial>& \\\n          inertial_coordinates,                                               \\\n      const InverseJacobian<DataVector, DIM(data), Frame::ElementLogical,     \\\n                            Frame::Inertial>&                                 \\\n          logical_to_inertial_inverse_jacobian,                               \\\n      [[maybe_unused]] const Scalar<DataVector>* const det_inverse_jacobian,  \\\n      const std::optional<tnsr::I<DataVector, DIM(data), Frame::Inertial>>&   \\\n          mesh_velocity,                                                      \\\n      const std::optional<Scalar<DataVector>>& div_mesh_velocity,             \\\n      const tnsr::I<DataVector, DIM(data)>& momentum_density,                 \\\n      const Scalar<DataVector>& energy_density,                               \\\n      const tnsr::I<DataVector, DIM(data)>& velocity,                         \\\n      const Scalar<DataVector>& pressure);\n\nGENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2, 3),\n                        (::NewtonianEuler::Solutions::RiemannProblem,\n                         ::NewtonianEuler::Solutions::SmoothFlow))\n\nGENERATE_INSTANTIATIONS(INSTANTIATION, (2, 3),\n                        (::NewtonianEuler::AnalyticData::KhInstability))\n\nGENERATE_INSTANTIATIONS(INSTANTIATION, (2),\n                        (::NewtonianEuler::Solutions::IsentropicVortex))\n\n#undef INSTANTIATION\n#undef SYSTEM\n#undef INITIAL_DATA_TYPE\n#undef DIM\n\nusing isentropic_vortex_3d_system = ::NewtonianEuler::System<\n    3, ::NewtonianEuler::Solutions::IsentropicVortex<3>>;\n\ntemplate void volume_terms<::NewtonianEuler::TimeDerivativeTerms<\n    3, ::NewtonianEuler::Solutions::IsentropicVortex<3>>>(\n    const gsl::not_null<Variables<db::wrap_tags_in<\n        ::Tags::dt, isentropic_vortex_3d_system::variables_tag::tags_list>>*>\n        dt_vars_ptr,\n    const gsl::not_null<Variables<db::wrap_tags_in<\n        ::Tags::Flux, isentropic_vortex_3d_system::flux_variables,\n        tmpl::size_t<3>, Frame::Inertial>>*>\n        volume_fluxes,\n    const gsl::not_null<Variables<db::wrap_tags_in<\n        ::Tags::deriv, isentropic_vortex_3d_system::gradient_variables,\n        tmpl::size_t<3>, Frame::Inertial>>*>\n        partial_derivs,\n    const gsl::not_null<\n        Variables<isentropic_vortex_3d_system::\n                      compute_volume_time_derivative_terms::temporary_tags>*>\n        temporaries,\n    const Variables<isentropic_vortex_3d_system::variables_tag::tags_list>&\n        evolved_vars,\n    const ::dg::Formulation dg_formulation, const Mesh<3>& mesh,\n    [[maybe_unused]] const tnsr::I<DataVector, 3, Frame::Inertial>&\n        inertial_coordinates,\n    const InverseJacobian<DataVector, 3, Frame::ElementLogical,\n                          Frame::Inertial>&\n        logical_to_inertial_inverse_jacobian,\n    [[maybe_unused]] const Scalar<DataVector>* const det_inverse_jacobian,\n    const std::optional<tnsr::I<DataVector, 3, Frame::Inertial>>& mesh_velocity,\n    const std::optional<Scalar<DataVector>>& div_mesh_velocity,\n    const tnsr::I<DataVector, 3>& momentum_density,\n    const Scalar<DataVector>& energy_density,\n    const tnsr::I<DataVector, 3>& velocity, const Scalar<DataVector>& pressure,\n    const NewtonianEuler::Sources::VortexPerturbation& source,\n    const NewtonianEuler::Solutions::IsentropicVortex<3>& vortex,\n    const tnsr::I<DataVector, 3>& x, const double& time);\n\nusing lane_emden_star_system =\n    ::NewtonianEuler::System<3, ::NewtonianEuler::Solutions::LaneEmdenStar>;\n\ntemplate void volume_terms<::NewtonianEuler::TimeDerivativeTerms<\n    3, ::NewtonianEuler::Solutions::LaneEmdenStar>>(\n    const gsl::not_null<Variables<db::wrap_tags_in<\n        ::Tags::dt,\n        typename lane_emden_star_system::variables_tag::tags_list>>*>\n        dt_vars_ptr,\n    const gsl::not_null<Variables<db::wrap_tags_in<\n        ::Tags::Flux, typename lane_emden_star_system::flux_variables,\n        tmpl::size_t<3>, Frame::Inertial>>*>\n        volume_fluxes,\n    const gsl::not_null<Variables<db::wrap_tags_in<\n        ::Tags::deriv, typename lane_emden_star_system::gradient_variables,\n        tmpl::size_t<3>, Frame::Inertial>>*>\n        partial_derivs,\n    const gsl::not_null<\n        Variables<typename lane_emden_star_system::\n                      compute_volume_time_derivative_terms::temporary_tags>*>\n        temporaries,\n    const Variables<typename lane_emden_star_system::variables_tag::tags_list>&\n        evolved_vars,\n    const ::dg::Formulation dg_formulation, const Mesh<3>& mesh,\n    [[maybe_unused]] const tnsr::I<DataVector, 3, Frame::Inertial>&\n        inertial_coordinates,\n    const InverseJacobian<DataVector, 3, Frame::ElementLogical,\n                          Frame::Inertial>&\n        logical_to_inertial_inverse_jacobian,\n    [[maybe_unused]] const Scalar<DataVector>* const det_inverse_jacobian,\n    const std::optional<tnsr::I<DataVector, 3, Frame::Inertial>>& mesh_velocity,\n    const std::optional<Scalar<DataVector>>& div_mesh_velocity,\n    const tnsr::I<DataVector, 3>& momentum_density,\n    const Scalar<DataVector>& energy_density,\n    const tnsr::I<DataVector, 3>& velocity, const Scalar<DataVector>& pressure,\n    const NewtonianEuler::Sources::LaneEmdenGravitationalField& source,\n    const Scalar<DataVector>& mass_density_cons_for_source,\n    const tnsr::I<DataVector, 3>& momentum_density_for_source,\n    const NewtonianEuler::Solutions::LaneEmdenStar& star,\n    const tnsr::I<DataVector, 3>& x);\n}  // namespace evolution::dg::Actions::detail\n", "meta": {"hexsha": "53567fa25b083f4b1bbaa9fcee9880a6335b62a3", "size": 8272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Executables/NewtonianEuler/VolumeTermsInstantiation.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/Evolution/Executables/NewtonianEuler/VolumeTermsInstantiation.cpp", "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/Evolution/Executables/NewtonianEuler/VolumeTermsInstantiation.cpp", "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": 54.4210526316, "max_line_length": 83, "alphanum_fraction": 0.6410783366, "num_tokens": 1941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1898585785706167}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/xray/sampling_base.h>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/python/return_internal_reference.hpp>\n\nnamespace cctbx { namespace xray { namespace boost_python {\n\nnamespace {\n\n  struct sampling_base_wrappers\n  {\n    typedef sampling_base<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      typedef return_value_policy<copy_const_reference> ccr;\n      typedef return_internal_reference<> rir;\n      class_<w_t>(\"sampling_base\", no_init)\n        .def(\"unit_cell\", &w_t::unit_cell, rir())\n        .def(\"u_base\", &w_t::u_base)\n        .def(\"u_extra\", &w_t::u_extra)\n        .def(\"u_min\", &w_t::u_min)\n        .def(\"wing_cutoff\", &w_t::wing_cutoff)\n        .def(\"exp_table_one_over_step_size\",\n          &w_t::exp_table_one_over_step_size)\n        .def(\"tolerance_positive_definite\",\n          &w_t::tolerance_positive_definite)\n        .def(\"n_scatterers_passed\", &w_t::n_scatterers_passed)\n        .def(\"n_contributing_scatterers\", &w_t::n_contributing_scatterers)\n        .def(\"n_anomalous_scatterers\", &w_t::n_anomalous_scatterers)\n        .def(\"anomalous_flag\", &w_t::anomalous_flag)\n        .def(\"exp_table_size\", &w_t::exp_table_size)\n        .def(\"max_sampling_box_n_points\", &w_t::max_sampling_box_n_points)\n        .def(\"sum_sampling_box_n_points\", &w_t::sum_sampling_box_n_points)\n        .def(\"ave_sampling_box_n_points\", &w_t::ave_sampling_box_n_points)\n        .def(\"max_sampling_box_edges\", &w_t::max_sampling_box_edges, ccr())\n        .def(\"max_sampling_box_edges_frac\", &w_t::max_sampling_box_edges_frac)\n        .def(\"excessive_sampling_radius_i_seqs\",\n          &w_t::excessive_sampling_radius_i_seqs, ccr())\n      ;\n    }\n  };\n\n} // namespace <anoymous>\n\n  void wrap_sampling_base()\n  {\n    using namespace boost::python;\n\n    def(\"calc_u_base\", calc_u_base, (\n      arg(\"d_min\"),\n      arg(\"grid_resolution_factor\"),\n      arg(\"quality_factor\")=100,\n      arg(\"max_u_base\")=adptbx::b_as_u(1000)));\n\n    def(\"apply_u_extra\",\n      (void(*)(\n        uctbx::unit_cell const&,\n        double const&,\n        af::const_ref<miller::index<> > const&,\n        af::ref<std::complex<double> > const&,\n        double const&)) apply_u_extra, (\n          arg(\"unit_cell\"),\n          arg(\"u_extra\"),\n          arg(\"miller_indices\"),\n          arg(\"structure_factors\"),\n          arg(\"multiplier\")=1));\n\n    sampling_base_wrappers::wrap();\n  }\n\n}}} // namespace cctbx::xray::boost_python\n", "meta": {"hexsha": "eae61280587c668d4d47c05aa7c22a1af60c3dd8", "size": 2650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/xray/boost_python/sampling_base.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": "cctbx/xray/boost_python/sampling_base.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": "cctbx/xray/boost_python/sampling_base.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": 33.125, "max_line_length": 78, "alphanum_fraction": 0.6622641509, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1898585785706167}}
{"text": "//\n// Created by Macx on 2018/10/6.\n//\n\n#include <vector>\n#include <cmath>\n#include <cstdlib>\n#include <cstddef>\n#include <limits>\n#include <algorithm>\n#include <time.h>\n//#include <Eigen/Dense>\n//#include <Eigen/Geometry>\n#include <iostream>\n#include \"Model.h\"\n#include <ofxProfiler.h>\n#include <GL/glcorearb.h>\n#include \"Math.hpp\"\n#include \"Constants.hpp\"\n#include \"tiny_obj_loader.h\"\n\n#if defined __linux__ || defined __APPLE__\n// \"Compiled for Linux\n#else\n// Windows doesn't define these values by default, Linux does\n#define M_PI 3.141592653589793f\n#define INFINITY 1e8\n#endif\n\n#if defined __linux__ || defined __APPLE__\n#include <SDL.h>\n#include <zconf.h>\n#else\n#include \"SDL.h\"\n#undef min\n#undef max\n#endif\n\n#define WITH_TEXTURE 1\n\nconst S32 width = 800;\nconst S32 height = 800;\nconst S32 depth = 255;\n\n//using Eigen::Vec3f;\n//using Eigen::Mat4f;\nusing namespace FW;\n\nSDL_PixelFormat *pixFormat = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888);\n\nU32 WHITE = SDL_MapRGBA(pixFormat, 255, 255, 255, 255);\nU32 BLACK = SDL_MapRGBA(pixFormat, 0, 0, 0, 255);\nU32 RED = SDL_MapRGBA(pixFormat, 255, 0, 0, 255);\nU32 GREEN = SDL_MapRGBA(pixFormat, 0, 255, 0, 255);\nU32 BLUE = SDL_MapRGBA(pixFormat, 0, 0, 255, 255);\n\nVec3f light_dir(1, -1, 1);\nVec3f eye(1, 1, 3);\nVec3f center(0, 0, 0);\n\nModel *model = NULL;\nSDL_Window *gWindow = NULL;\nSDL_Renderer *gRender = NULL;\nSDL_Texture *gTexture = NULL;\n\nvoid init() {\n  SDL_Init(SDL_INIT_VIDEO);\n  gWindow =\n      SDL_CreateWindow(\"SDL\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n                       width, height, SDL_WINDOW_SHOWN);\n\n  gRender = SDL_CreateRenderer(\n      gWindow, -1, SDL_RENDERER_SOFTWARE | SDL_RENDERER_TARGETTEXTURE);\n\n  gTexture = SDL_CreateTexture(gRender, SDL_PIXELFORMAT_RGBA8888,\n                               SDL_TEXTUREACCESS_STREAMING, width, height);\n}\n\nvoid close() {\n  SDL_DestroyRenderer(gRender);\n  SDL_DestroyTexture(gTexture);\n  SDL_DestroyWindow(gWindow);\n  SDL_Quit();\n}\n\nvoid Clear(U32 *pix, U32 color) {\n  for (S32 i = 0; i < height; ++i) {\n    for (S32 j = 0; j < width; ++j) {\n      pix[i * width + j] = color;\n    }\n  }\n}\n\nvoid put_pixel(U32 *pix, U32 color, S32 x, S32 y) {\n  pix[(height - y - 1) * width + x] = color;\n}\n\nvoid Line(S32 x0, S32 y0, S32 x1, S32 y1, U32 *pix, U32 color) {\n  bool steep = false;\n  if (FW::abs(x0 - x1) < FW::abs(y0 - y1)) {\n    FW::swap(x0, y0);\n    FW::swap(x1, y1);\n    steep = true;\n  }\n  if (x0 > x1) {\n    FW::swap(x0, x1);\n    FW::swap(y0, y1);\n  }\n\n  for (S32 x = x0; x <= x1; x++) {\n    F32 t = (x - x0) / (F32) (x1 - x0);\n    S32 y = y0 * (1.f - t) + y1 * t;\n    if (steep) {\n      put_pixel(pix, color, y, x);\n    } else {\n      put_pixel(pix, color, x, y);\n    }\n  }\n}\n\nvoid Triangle(Vec2i t0, Vec2i t1, Vec2i t2, U32 *pix, U32 color) {\n  if (t0.y == t1.y && t0.y == t2.y) return; // i dont care about degenerate triangles\n  if (t0.y > t1.y) FW::swap(t0, t1);\n  if (t0.y > t2.y) FW::swap(t0, t2);\n  if (t1.y > t2.y) FW::swap(t1, t2);\n  S32 total_height = t2.y - t0.y;\n  for (S32 i = 0; i < total_height; i++) {\n    bool second_half = i > t1.y - t0.y || t1.y == t0.y;\n    S32 segment_height = second_half ? t2.y - t1.y : t1.y - t0.y;\n    F32 alpha = (F32) i / total_height;\n    F32 beta = (F32) (i - (second_half ? t1.y - t0.y : 0))\n        / segment_height; // be careful: with above conditions no division by zero here\n    Vec2i A = t0 + ((t2 - t0) * alpha);\n    Vec2i B = second_half ? t1 + ((t2 - t1) * beta) : t0 + ((t1 - t0) *\n        beta);\n    if (A.x > B.x) FW::swap(A, B);\n    for (S32 j = A.x; j <= B.x; j++) {\n      put_pixel(pix, color, j, t0.y + i); // attention, due to S32 casts t0.y+i != A.y\n    }\n  }\n}\n\nVec3f barycentric(Vec3i A, Vec3i B, Vec3i C, Vec3i P) {\n  Vec3i s[2];\n  for (S32 i = 2; i--;) {\n    s[i][0] = C[i] - A[i];\n    s[i][1] = B[i] - A[i];\n    s[i][2] = A[i] - P[i];\n  }\n  Vec3f u = FW::cross((Vec3f)s[0], (Vec3f)s[1]);\n  if (FW::abs(u[2]) != 0) // dont forget that u[2] is integer. If it is zero then triangle ABC is degenerate\n  {\n    return Vec3f(1.f - (u.x + u.y) / u.z, u.y / u.z, u.x / u.z);\n  }\n  return Vec3f(-1, 1, 1); // in this case generate negative coordinates, it will be thrown away by the rasterizator\n}\n\nF32 Det(Vec3f A, Vec3f B, Vec3f C) {\n  return (B.x - A.x) * (C.y - A.y) - (B.y - A.y) * (C.x - A.x);\n}\n\nvoid TriangleFast2(Vec3f *pts, S32 *zbuffer, U32 *pix, U32 *colors) {\n  Vec2i bboxmin(FW_S32_MAX, FW_S32_MAX);\n  Vec2i bboxmax(FW_S32_MIN, FW_S32_MIN);\n  Vec2i clamp(width - 1, height - 1);\n\n  for (S32 i = 0; i < 3; i++) {\n    for (S32 j = 0; j < 2; j++) {\n      bboxmin[j] = FW::max(0, FW::min(bboxmin[j], (S32) (pts[i][j] + 0.5)));\n      bboxmax[j] = FW::min(clamp[j], FW::max(bboxmax[j], (S32) (pts[i][j] + 0.5)));\n    }\n  }\n\n  U8 r[3], g[3], b[3], a[3];\n  for (S32 i = 0; i < 3; i++) {\n    SDL_GetRGBA(colors[i], pixFormat, &r[i], &g[i], &b[i], &a[i]);\n  }\n\n  F32 z_inv_0 = 1.0f / pts[0][2];\n  F32 z_inv_1 = 1.0f / pts[1][2];\n  F32 z_inv_2 = 1.0f / pts[2][2];\n\n  F32 y_0 = pts[0][1];\n  F32 y_1 = pts[1][1];\n  F32 y_2 = pts[2][1];\n\n  F32 x_0 = pts[0][0];\n  F32 x_1 = pts[1][0];\n  F32 x_2 = pts[2][0];\n\n  Vec2f n_pq(pts[0].y - pts[1].y, pts[1].x - pts[0].x);\n  Vec2f n_qr(pts[1].y - pts[2].y, pts[2].x - pts[1].x);\n  Vec2f n_rp(pts[2].y - pts[0].y, pts[0].x - pts[2].x);\n  Vec2f v_p = pts[0].getXY();\n  Vec2f v_q = pts[1].getXY();\n  Vec2f v_r = pts[2].getXY();\n\n  F32 c_pq = -1.f * (n_pq.dot(v_p));\n  F32 c_qr = -1.f * (n_qr.dot(v_q));\n  F32 c_rp = -1.f * (n_rp.dot(v_r));\n\n  F32 Den = Det(pts[0], pts[1], pts[2]);\n\n  F32 D_Zpinv_x = ((y_2 - y_0) * (z_inv_1 - z_inv_0) + (y_0 - y_1) * (z_inv_2 - z_inv_0)) / Den;\n  F32 D_Zpinv_y = ((x_0 - x_2) * (z_inv_1 - z_inv_0) + (x_1 - x_0) * (z_inv_2 - z_inv_0)) / Den;\n\n  F32 D_Zpinv_x_r =\n      ((y_2 - y_0) * (z_inv_1 * r[1] - z_inv_0 * r[0]) + (y_0 - y_1) * (z_inv_2 * r[2] - z_inv_0 * r[0])) / Den;\n  F32 D_Zpinv_y_r =\n      ((x_0 - x_2) * (z_inv_1 * r[1] - z_inv_0 * r[0]) + (x_1 - x_0) * (z_inv_2 * r[2] - z_inv_0 * r[0])) / Den;\n\n  F32 D_Zpinv_x_g =\n      ((y_2 - y_0) * (z_inv_1 * g[1] - z_inv_0 * g[0]) + (y_0 - y_1) * (z_inv_2 * g[2] - z_inv_0 * g[0])) / Den;\n  F32 D_Zpinv_y_g =\n      ((x_0 - x_2) * (z_inv_1 * g[1] - z_inv_0 * g[0]) + (x_1 - x_0) * (z_inv_2 * g[2] - z_inv_0 * g[0])) / Den;\n\n  F32 D_Zpinv_x_b =\n      ((y_2 - y_0) * (z_inv_1 * b[1] - z_inv_0 * b[0]) + (y_0 - y_1) * (z_inv_2 * b[2] - z_inv_0 * b[0])) / Den;\n  F32 D_Zpinv_y_b =\n      ((x_0 - x_2) * (z_inv_1 * b[1] - z_inv_0 * b[0]) + (x_1 - x_0) * (z_inv_2 * b[2] - z_inv_0 * b[0])) / Den;\n\n  F32 z_p;\n  F32 z_inv_p;\n\n  z_inv_p = z_inv_0 + (bboxmin.x - x_0) * D_Zpinv_x + (bboxmin.y - y_0) * D_Zpinv_y;\n  z_p = 1.0f / z_inv_p;\n  F32 r_i_p = (r[0] * z_inv_0 + (bboxmin.x - x_0) * D_Zpinv_x_r + (bboxmin.y - y_0) * D_Zpinv_y_r);\n  F32 g_i_p = (g[0] * z_inv_0 + (bboxmin.x - x_0) * D_Zpinv_x_g + (bboxmin.y - y_0) * D_Zpinv_y_g);\n  F32 b_i_p = (b[0] * z_inv_0 + (bboxmin.x - x_0) * D_Zpinv_x_b + (bboxmin.y - y_0) * D_Zpinv_y_b);\n\n  Vec3i P;\n  for (P.x = bboxmin.x; P.x <= bboxmax.x; P.x++) {\n    F32 z_inv_p_base = z_inv_p;\n    F32 r_i_p_base = r_i_p;\n    F32 g_i_p_base = g_i_p;\n    F32 b_i_p_base = b_i_p;\n    z_inv_p += D_Zpinv_x;\n    r_i_p += D_Zpinv_x_r;\n    g_i_p += D_Zpinv_x_g;\n    b_i_p += D_Zpinv_x_b;\n    for (P.y = bboxmin.y; P.y <= bboxmax.y; P.y++) {\n      P.z = 0;\n\n      z_p = 1.0f / z_inv_p_base;\n      P.z = z_p;\n      U32 color = SDL_MapRGBA(pixFormat, r_i_p_base * z_p, g_i_p_base * z_p, b_i_p_base * z_p, 255);\n\n      z_inv_p_base += D_Zpinv_y;\n      r_i_p_base += D_Zpinv_y_r;\n      g_i_p_base += D_Zpinv_y_g;\n      b_i_p_base += D_Zpinv_y_b;\n\n      Vec2f s = P.getXY();\n      F32 e_pq_s = n_pq.dot(s) + c_pq;\n      if (e_pq_s >= 0) {\n        F32 e_qr_s = n_qr.dot(s) + c_qr;\n        if (e_qr_s >= 0) {\n          F32 e_rp_s = n_rp.dot(s) + c_rp;\n          if (e_rp_s < 0)\n            continue;\n        } else continue;\n      } else continue;\n\n      S32 idx = P.x + P.y * width;\n      if (zbuffer[idx] < P.z) {\n        zbuffer[idx] = P.z;\n        put_pixel(pix, color, P.x, P.y);\n      }\n    }\n  }\n}\n#if 0\nvoid Triangle(Vec3i *pts, S32 *zbuffer, U32 *pix, U32 *colors) {\n  Vec2i bboxmin(FW::numeric_limits<S32>::max, FW::numeric_limits<S32>::max);\n  Vec2i bboxmax(-FW::numeric_limits<S32>::max, -FW::numeric_limits<S32>::max);\n  Vec2i clamp(width - 1, height - 1);\n  for (S32 i = 0; i < 3; i++) {\n    for (S32 j = 0; j < 2; j++) {\n      bboxmin[j] = FW::max(0, FW::min(bboxmin[j], pts[i][j]));\n      bboxmax[j] = FW::min(clamp[j], FW::max(bboxmax[j], pts[i][j]));\n    }\n  }\n  Vec3i P;\n  F32 z_inv;\n  for (P.x = bboxmin.x; P.x <= bboxmax.x; P.x++) {\n    for (P.y = bboxmin.y; P.y <= bboxmax.y; P.y++) {\n      Vec3f bc_screen = barycentric(pts[0], pts[1], pts[2], P);\n      if (bc_screen.x < 0 || bc_screen.y < 0 || bc_screen.z < 0) continue;\n      P.z = 0;\n      z_inv = 0;\n      for (S32 i = 0; i < 3; i++) z_inv += 1.0 / pts[i][2] * bc_screen[i];\n      U8 r_add = 0, g_add = 0, b_add = 0, a_add = 0;\n      {\n        U8 r, g, b, a;\n        for (S32 i = 0; i < 3; i++) {\n          SDL_GetRGBA(colors[i], pixFormat, &r, &g, &b, &a);\n          F32 pfx = bc_screen[i] / pts[i][2] / z_inv;\n          r_add += r * pfx;\n          g_add += g * pfx;\n          b_add += b * pfx;\n          a_add += a * pfx;\n        }\n      }\n      P.z = 1.0 / z_inv;\n      U32 color = SDL_MapRGBA(pixFormat, r_add, g_add, b_add, a_add);\n      S32 idx = P.x + P.y * width;\n      if (zbuffer[idx] < P.z) {\n        zbuffer[idx] = P.z;\n        put_pixel(pix, color, P.x, P.y);\n      }\n    }\n  }\n}\n#endif // 0\n\n//template<class A, class B>\n//inline A lerp(const A &a, const A &b, const B &t) { return (A) (a * ((B) 1 - t) + b * t); }\n\nVec3i setupPleq(const Vec3f& values, const Vec2i& v0, const Vec2i& d1, const Vec2i& d2, S32 area, int samplesLog2)\n{\n  F64 t0 = (F64)values.x;\n  F64 t1 = (F64)values.y - t0;\n  F64 t2 = (F64)values.z - t0;\n  F64 xc = (t1 * (F64)d2.y - t2 * (F64)d1.y) / (F64)area;\n  F64 yc = (t2 * (F64)d1.x - t1 * (F64)d2.x) / (F64)area;\n\n  Vec2i center = (v0 * 2 + min(d1.x, d2.x, 0) + max(d1.x, d2.x, 0)) >> (CR_SUBPIXEL_LOG2 - samplesLog2 + 1);\n  Vec2i vc = v0 - (center << (CR_SUBPIXEL_LOG2 - samplesLog2));\n\n  Vec3i pleq;\n  pleq.x = (U32)(S64)FW::floor(xc * exp2(CR_SUBPIXEL_LOG2 - samplesLog2) + 0.5);\n  pleq.y = (U32)(S64)FW::floor(yc * exp2(CR_SUBPIXEL_LOG2 - samplesLog2) + 0.5);\n  pleq.z = (U32)(S64)FW::floor(t0 - xc * (F64)vc.x - yc * (F64)vc.y + 0.5);\n  pleq.z -= pleq.x * center.x + pleq.y * center.y;\n  return pleq;\n}\n\nbool setupTriangle(Vec3f *pts) {\n\n  Vec3f v0 = pts[0];\n  Vec3f v1 = pts[1];\n  Vec3f v2 = pts[2];\n\n  Vec2i p0 = Vec2i(v0.x, v0.y);\n  Vec2i p1 = Vec2i(v1.x, v1.y);\n  Vec2i p2 = Vec2i(v2.x, v2.y);\n  Vec2i d1 = p1 - p0;\n  Vec2i d2 = p2 - p0;\n\n  S32 area = d1.x * d2.y - d1.y * d2.x;\n\n  if (area <= 0)\n    return false;\n\n  Vec3f zvert = FW::lerp(Vec3f(CR_DEPTH_MIN), Vec3f(CR_DEPTH_MIN), Vec3f(v0.z, v1.z, v2.z)* 0.5f + 0.5f);\n//  zvert.print();\n  return true;\n}\n\nvoid TriangleFast3(Vec3f *pts, S32 *zbuffer, U32 *pix, U32 *colors) {\n  Vec2i bboxmin(FW_S32_MAX, FW_S32_MAX);\n  Vec2i bboxmax(FW_S32_MIN, FW_S32_MIN);\n  Vec2i clamp(width - 1, height - 1);\n\n  for (S32 i = 0; i < 3; i++) {\n    for (S32 j = 0; j < 2; j++) {\n      bboxmin[j] = FW::max(0, FW::min(bboxmin[j], (S32) (pts[i][j] + 0.5)));\n      bboxmax[j] = FW::min(clamp[j], FW::max(bboxmax[j], (S32) (pts[i][j] + 0.5)));\n    }\n  }\n\n  U8 r[3], g[3], b[3], a[3];\n  for (S32 i = 0; i < 3; i++) {\n    SDL_GetRGBA(colors[i], pixFormat, &r[i], &g[i], &b[i], &a[i]);\n  }\n\n  F32 z_inv_0 = 1.0f / pts[0][2];\n  F32 z_inv_1 = 1.0f / pts[1][2];\n  F32 z_inv_2 = 1.0f / pts[2][2];\n\n  F32 y_0 = pts[0][1];\n  F32 y_1 = pts[1][1];\n  F32 y_2 = pts[2][1];\n\n  F32 x_0 = pts[0][0];\n  F32 x_1 = pts[1][0];\n  F32 x_2 = pts[2][0];\n\n  Vec2f n_pq(pts[0].y - pts[1].y, pts[1].x - pts[0].x);\n  Vec2f n_qr(pts[1].y - pts[2].y, pts[2].x - pts[1].x);\n  Vec2f n_rp(pts[2].y - pts[0].y, pts[0].x - pts[2].x);\n  Vec2f v_p = pts[0].getXY();\n  Vec2f v_q = pts[1].getXY();\n  Vec2f v_r = pts[2].getXY();\n\n  F32 c_pq = -1.f * (n_pq.dot(v_p));\n  F32 c_qr = -1.f * (n_qr.dot(v_q));\n  F32 c_rp = -1.f * (n_rp.dot(v_r));\n  setupTriangle(pts);\n  F32 Den = Det(pts[0], pts[1], pts[2]);\n  F32 Den_1 = 1.0f / Den;\n\n  F32 D_Zpinv_x = ((y_2 - y_0) * (z_inv_1 - z_inv_0) + (y_0 - y_1) * (z_inv_2 - z_inv_0)) * Den_1;\n  F32 D_Zpinv_y = ((x_0 - x_2) * (z_inv_1 - z_inv_0) + (x_1 - x_0) * (z_inv_2 - z_inv_0)) * Den_1;\n\n  F32 D_Zpinv_x_r =\n      ((y_2 - y_0) * (z_inv_1 * r[1] - z_inv_0 * r[0]) + (y_0 - y_1) * (z_inv_2 * r[2] - z_inv_0 * r[0])) * Den_1;\n  F32 D_Zpinv_y_r =\n      ((x_0 - x_2) * (z_inv_1 * r[1] - z_inv_0 * r[0]) + (x_1 - x_0) * (z_inv_2 * r[2] - z_inv_0 * r[0])) * Den_1;\n\n  F32 D_Zpinv_x_g =\n      ((y_2 - y_0) * (z_inv_1 * g[1] - z_inv_0 * g[0]) + (y_0 - y_1) * (z_inv_2 * g[2] - z_inv_0 * g[0])) * Den_1;\n  F32 D_Zpinv_y_g =\n      ((x_0 - x_2) * (z_inv_1 * g[1] - z_inv_0 * g[0]) + (x_1 - x_0) * (z_inv_2 * g[2] - z_inv_0 * g[0])) * Den_1;\n\n  F32 D_Zpinv_x_b =\n      ((y_2 - y_0) * (z_inv_1 * b[1] - z_inv_0 * b[0]) + (y_0 - y_1) * (z_inv_2 * b[2] - z_inv_0 * b[0])) * Den_1;\n  F32 D_Zpinv_y_b =\n      ((x_0 - x_2) * (z_inv_1 * b[1] - z_inv_0 * b[0]) + (x_1 - x_0) * (z_inv_2 * b[2] - z_inv_0 * b[0])) * Den_1;\n\n  F32 z_p;\n  F32 z_inv_p;\n\n  z_inv_p = z_inv_0 + (bboxmin.x - x_0) * D_Zpinv_x + (bboxmin.y - y_0) * D_Zpinv_y;\n  z_p = 1.0 / z_inv_p;\n  F32 r_i_p = (r[0] * z_inv_0 + (bboxmin.x - x_0) * D_Zpinv_x_r + (bboxmin.y - y_0) * D_Zpinv_y_r);\n  F32 g_i_p = (g[0] * z_inv_0 + (bboxmin.x - x_0) * D_Zpinv_x_g + (bboxmin.y - y_0) * D_Zpinv_y_g);\n  F32 b_i_p = (b[0] * z_inv_0 + (bboxmin.x - x_0) * D_Zpinv_x_b + (bboxmin.y - y_0) * D_Zpinv_y_b);\n\n  Vec3i P;\n  for (P.x = bboxmin.x; P.x <= bboxmax.x; P.x++) {\n    F32 z_inv_p_base = z_inv_p;\n    F32 r_i_p_base = r_i_p;\n    F32 g_i_p_base = g_i_p;\n    F32 b_i_p_base = b_i_p;\n\n    z_inv_p += D_Zpinv_x;\n    r_i_p += D_Zpinv_x_r;\n    g_i_p += D_Zpinv_x_g;\n    b_i_p += D_Zpinv_x_b;\n\n    for (P.y = bboxmin.y; P.y <= bboxmax.y; P.y++) {\n      P.z = 0;\n\n      z_p = 1.0 / z_inv_p_base;\n      P.z = z_p;\n      U32 color = SDL_MapRGBA(pixFormat, r_i_p_base * z_p, g_i_p_base * z_p, b_i_p_base * z_p, 255);\n\n      z_inv_p_base += D_Zpinv_y;\n      r_i_p_base += D_Zpinv_y_r;\n      g_i_p_base += D_Zpinv_y_g;\n      b_i_p_base += D_Zpinv_y_b;\n\n      Vec2f s = P.getXY();\n      F32 e_pq_s = n_pq.dot(s) + c_pq;\n      if (e_pq_s >= 0) {\n        F32 e_qr_s = n_qr.dot(s) + c_qr;\n        if (e_qr_s >= 0) {\n          F32 e_rp_s = n_rp.dot(s) + c_rp;\n          if (e_rp_s < 0)\n            continue;\n        } else continue;\n      } else continue;\n\n      S32 idx = P.x + P.y * width;\n      if (zbuffer[idx] < P.z) {\n        zbuffer[idx] = P.z;\n        put_pixel(pix, color, P.x, P.y);\n      }\n    }\n  }\n}\n\ntemplate<typename T>\nclass Device {\n public:\n  void sr_glViewport(GLint x,\n                     GLint y,\n                     GLsizei width,\n                     GLsizei height) {\n    viewPort.m_x = x;\n    viewPort.m_y = y;\n    viewPort.m_width = width;\n    viewPort.m_height = height;\n  }\n\n  void sr_glDepthRange(T nearVal,\n                       T farVal) {\n    viewPort.m_nearVal = nearVal;\n    viewPort.m_farVal = farVal;\n  }\n private:\n  struct ViewPort {\n    GLint m_x = 0;\n    GLint m_y = 0;\n    GLsizei m_width = 1;\n    GLsizei m_height = 1;\n    T m_nearVal = 0.0;\n    T m_farVal = 1.0;\n  };\n protected:\n  ViewPort viewPort;\n};\n\nMat4f viewport(S32 x, S32 y, S32 w, S32 h) {\n  Mat4f m;\n  m.setIdentity();\n  m(0, 3) = x + w / 2.f;\n  m(1, 3) = y + h / 2.f;\n  m(2, 3) = depth / 2.f;\n\n  m(0, 0) = w / 2.f;\n  m(1, 1) = h / 2.f;\n  m(2, 2) = depth / 2.f;\n  return m;\n}\n\nVec3f world2screen(Vec3f v) {\n  return Vec3f(S32((v.x + 1.f) * width / 2.f + .5f), S32((v.y + 1.f) * height / 2.f + .5f), v.z);\n}\n\nMat4f lookat(Vec3f eye, Vec3f center, Vec3f up) {\n  Vec3f z = (eye - center).normalized();\n  z.normalize();\n  Vec3f x = cross(up,z);\n  x.normalize();\n  Vec3f y = z.cross(x);\n  y.normalize();\n  Mat4f res;\n  res.setIdentity();\n  for (S32 i = 0; i < 3; i++) {\n    res(0, i) = x[i];\n    res(1, i) = y[i];\n    res(2, i) = z[i];\n    res(i, 3) = -center[i];\n  }\n  return res;\n}\n\nS32 main(S32 argc, char **argv) {\n  if (2 == argc) {\n    model = new Model(argv[1]);\n  } else {\n#if defined __linux__ || defined __APPLE__\n    model = new Model(\"../../obj/african_head.obj\");\n#else\n    model = new Model(\"../obj/african_head.obj\");\n#endif\n  }\n\n//add device\n  Device<GLfloat> m_device;\n  m_device.sr_glViewport(0, 0, 800, 800);\n  m_device.sr_glDepthRange(0, 1);\n\n  S32 *zbuffer = new S32[width * height];\n  light_dir.normalize();\n  void *pix;\n  S32 pitch;\n\n  init();\n\n  S32 x_current(0);\n  S32 y_current(0);\n\n  // Main loop flag\n  bool quit = false;\n\n  // Event handler\n  SDL_Event e;\n\n  F32 deltaX(1), deltaY(1), deltaZ(3);\n\n  eye = Vec3f( deltaX, deltaY, deltaZ);\n\n  // timer\n  clock_t start(0), finish(0);\n  double duration;\n  S32 frame_count(0);\n  // While application is running\n  while (!quit) {\n    PROFILE_START_FRAME;\n    PROFILE_BEGIN(\"FRAME\");\n    PROFILE_BEGIN(\"Prepare\");\n    frame_count++;\n    if (frame_count == 60) {\n      finish = clock();\n      duration = (finish - start) / CLOCKS_PER_SEC;\n      FW::printf(\"%f  FPS\\n\", 60 / duration);\n      start = clock();\n      frame_count = 0;\n    }\n    // Handle events on queue\n    while (SDL_PollEvent(&e) != 0) {\n      // User requests quit\n      if (e.type == SDL_QUIT || e.key.keysym.sym == SDLK_ESCAPE) {\n        quit = true;\n      }\n      if (e.key.keysym.sym == SDLK_UP) {\n        deltaY += 0.2f;\n        break;\n      }\n      if (e.key.keysym.sym == SDLK_DOWN) {\n        deltaY -= 0.2f;\n        break;\n      }\n      if (e.key.keysym.sym == SDLK_RIGHT) {\n        deltaX += 0.2f;\n        break;\n      }\n      if (e.key.keysym.sym == SDLK_LEFT) {\n        deltaX -= 0.2f;\n        break;\n      }\n      if (e.key.keysym.sym == SDLK_w) {\n        deltaZ -= 0.2f;\n        break;\n      }\n      if (e.key.keysym.sym == SDLK_s) {\n        deltaZ += 0.2f;\n        break;\n      }\n      if (e.type == SDL_MOUSEMOTION || e.button.button == SDL_BUTTON_LEFT) {\n        x_current = e.motion.x;\n        y_current = e.motion.y;\n      }\n    }\n\n    SDL_LockTexture(gTexture, NULL, &pix, &pitch);\n    // Render begin\n\n    // Clear color\n    Clear((U32 *) pix, BLACK);\n\n    // Eye and center position\n    eye = Vec3f(deltaX, deltaY, deltaZ);\n\n    Mat4f ModelView = lookat(eye, center, Vec3f(0, 1, 0));\n    Mat4f Projection;\n    Projection.setIdentity();\n    Mat4f ViewPort = viewport(width / 8, height / 8, width * 3 / 4, height * 3 / 4);\n    Projection(3, 2) = -1.f / (eye - center).length();\n    Mat4f z = ViewPort * Projection * ModelView;\n\n    for (S32 i = 0; i < width * height; i++) {\n      zbuffer[i] = std::numeric_limits<S32>::min();\n    }\n    PROFILE_END();\n    PROFILE_BEGIN(\"Render face\");\n    // Loop over shapes\n\n    for (S32 i = 0; i < model->nfaces(); i++) {\n      std::vector<tinyobj::index_t> face = model->m_faces[i];\n      Vec3f screen_coords[3];\n      Vec3f world_coords[3];\n      U32 colors[3];\n      Vec3f n_v[3];\n      F32 intensity[3];\n\n      // load texture data\n      for (S32 j = 0; j < 3; ++j) {\n        tinyobj::index_t _idx = face[j];\n        Vec3f v = model->vert(_idx);\n        n_v[j] = model->normal(_idx);\n\n        Vec4f v_(v,1);\n//        v_ << v, 1;\n        Vec4f v_temp;\n        v_temp = ViewPort * Projection * ModelView * v_;\n        v_temp = v_temp / v_temp.w;\n        screen_coords[j] = (v_temp).getXYZ();\n\n        world_coords[j] = v;\n        intensity[j] = fabs(n_v[j].dot(light_dir));\n\n    // Render face\n//    for (S32 i = 0; i < model->nfaces(); i++) {\n//      std::vector<S32> face = model->face(i);\n//      Vec3f screen_coords[3];\n//      Vec3f world_coords[3];\n//      U32 colors[3];\n//      Vec3f n_v[3];\n//      F32 intensity[3];\n//\n//      // load texture data\n//      for (S32 j = 0; j < 3; ++j) {\n//        Vec3f v = model->vert(face[j]);\n//        n_v[j] = model->normal(i, j);\n//\n//        Vec4f v_(v,1);\n////        v_ << v, 1;\n//        Vec4f v_temp;\n//        v_temp = ViewPort * Projection * ModelView * v_;\n//        v_temp = v_temp / v_temp.w;\n//        screen_coords[j] = (v_temp).getXYZ();\n//\n//        world_coords[j] = v;\n//        intensity[j] = fabs(n_v[j].dot(light_dir));\n\n#if  defined(WITH_TEXTURE)\n        if (intensity[j] > 0) {\n          colors[j] = SDL_MapRGBA(pixFormat,\n                                  static_cast<U8>(model->diffuse(model->uv(_idx))[2] * intensity[j]),\n                                  static_cast<U8>(model->diffuse(model->uv(_idx))[1] * intensity[j]),\n                                  static_cast<U8>(model->diffuse(model->uv(_idx))[0] * intensity[j]),\n                                  model->diffuse(model->uv(_idx))[3]);\n        } else {\n          colors[j] = SDL_MapRGBA(pixFormat,\n                                  model->diffuse(model->uv(_idx))[2],\n                                  model->diffuse(model->uv(_idx))[1],\n                                  model->diffuse(model->uv(_idx))[0],\n                                  model->diffuse(model->uv(_idx))[3]);\n        }\n#else\n\t\tif (intensity[j] > 0) {\n\t\t\tcolors[j] = SDL_MapRGBA(pixFormat,\n\t\t\t\tstatic_cast<U8>(255.0 * intensity[j]),\n\t\t\t\tstatic_cast<U8>(255.0 * intensity[j]),\n\t\t\t\tstatic_cast<U8>(255.0 * intensity[j]),\n\t\t\t\t255);\n\t\t}\n#endif\n\n      }\n\n\n      // back face culling\n      Vec3f AB = screen_coords[0] - screen_coords[1];\n      Vec3f AC = screen_coords[0] - screen_coords[2];\n      Vec3f N = AC.cross(AB);\n      if (N.z > 0) {\n        continue;\n      }\n\n      // tessellation\n//      Vec3i screen_coords_i[3];\n//      screen_coords_i[0] = screen_coords[0];\n//      screen_coords_i[1] = screen_coords[1];\n//      screen_coords_i[2] = screen_coords[2];\n      TriangleFast3(screen_coords, zbuffer, (U32 *) pix, colors);\n    }\n    PROFILE_END();\n//    Vec3f world_coords[3];\n//    world_coords[0] << 0, 0, 0.99;\n//    world_coords[1] << 1, 0.5, 0.99;\n//    world_coords[2] << 0.5, 1, -0.99;\n//\n//    Vec3f screen_coords[3];\n//\n//    U32 colors[3];\n//    colors[0] = RED;\n//    colors[1] = GREEN;\n//    colors[2] = BLUE;\n//    for (S32 j = 0; j < 3; ++j) {\n//      Vec4f v_;\n//      v_ << world_coords[j], 1;\n//      Vec4f v_temp;\n//      v_temp = ViewPort * Projection * ModelView * v_;\n//      v_temp = v_temp / v_temp.w;\n//      screen_coords[j] = v_temp.block(0, 0, 3, 1);\n//    }\n\n    // tessellation\n//    TriangleFast2(screen_coords, zbuffer, (U32 *) pix, colors);\n    PROFILE_BEGIN(\"Render present\");\n    // Render end\n    SDL_UnlockTexture(gTexture);\n    SDL_RenderCopy(gRender, gTexture, NULL, NULL);\n    SDL_RenderPresent(gRender);\n    PROFILE_END();\n    PROFILE_END();\n    cout << ofxProfiler::getResults();\n\n#if defined __linux__ || defined __APPLE__\n    usleep(10);\n#else\n    Sleep(1);\n#endif //\n\n  }\n\n  { // dump z-buffer (debugging purposes only)\n    TGAImage zbimage(width, height, TGAImage::GRAYSCALE);\n    for (S32 i = 0; i < width; i++) {\n      for (S32 j = 0; j < height; j++) {\n        unsigned char zzzz = zbuffer[i + j * width];\n        zbimage.set(i, j, TGAColor(&zzzz, 1));\n      }\n    }\n    zbimage.flip_vertically(); // i want to have the origin at the left bottom corner of the image\n    zbimage.write_tga_file(\"zbuffer.tga\");\n  }\n\n  close();\n  return 0;\n}\n", "meta": {"hexsha": "051f5d46b5bf594bb22c9f65f66f84e93db7d6bb", "size": 23189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "JustJokerX/softrender", "max_stars_repo_head_hexsha": "a556e90455c74fcbb94ad53c11e2f46e5d82a898", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-06-07T05:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T13:24:42.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "JustJokerX/softrender", "max_issues_repo_head_hexsha": "a556e90455c74fcbb94ad53c11e2f46e5d82a898", "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": "JustJokerX/softrender", "max_forks_repo_head_hexsha": "a556e90455c74fcbb94ad53c11e2f46e5d82a898", "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.095357591, "max_line_length": 115, "alphanum_fraction": 0.5439648109, "num_tokens": 9122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1898585785706167}}
{"text": "// Copyright (c) 2017 Graphcore Ltd. All rights reserved.\n#include \"popnnCycleEstimators.hpp\"\n\n#include \"PerformanceEstimation.hpp\"\n#include \"PoolingDefUtil.hpp\"\n#include \"poplibs_support/FlopEstimation.hpp\"\n#include \"popnn/NonLinearity.hpp\"\n#include \"popnn/NonLinearityDefUtil.hpp\"\n#include \"popnn/PoolingDef.hpp\"\n#include <poplibs_support/Algorithm.hpp>\n\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/max_element.hpp>\n#include <boost/range/irange.hpp>\n#include <cassert>\n#include <cmath>\n\nusing namespace poplar;\nusing namespace poplibs_support;\n\n// Macro to create entries in cycle estimator table\n#define INSTANTIATE_NL_CYCLE_ESTIMATOR(v)                                      \\\n  CYCLE_ESTIMATOR_ENTRY(popnn, v, FLOAT, popnn::NonLinearityType::GELU),       \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, HALF, popnn::NonLinearityType::GELU),    \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, FLOAT, popnn::NonLinearityType::SWISH),  \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, HALF, popnn::NonLinearityType::SWISH)\n\n#define INSTANTIATE_NL_GRAD_CYCLE_ESTIMATOR(v)                                 \\\n  CYCLE_ESTIMATOR_ENTRY(popnn, v, FLOAT, popnn::NonLinearityType::SIGMOID),    \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, HALF, popnn::NonLinearityType::SIGMOID), \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, FLOAT, popnn::NonLinearityType::RELU),   \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, HALF, popnn::NonLinearityType::RELU),    \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, FLOAT, popnn::NonLinearityType::TANH),   \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, HALF, popnn::NonLinearityType::TANH),    \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, FLOAT, popnn::NonLinearityType::GELU),   \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, HALF, popnn::NonLinearityType::GELU),    \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, FLOAT, popnn::NonLinearityType::SWISH),  \\\n      CYCLE_ESTIMATOR_ENTRY(popnn, v, HALF, popnn::NonLinearityType::SWISH)\n\nnamespace popnn {\n\nstatic std::uint64_t nonlinearityFlops(const NonLinearityType &nlType) {\n  // assume single flop for all non-linearities other than GELU\n  if (nlType == NonLinearityType::GELU) {\n    return 8;\n  } else if (nlType == NonLinearityType::SWISH) {\n    return 2;\n  }\n  return 1;\n}\n\nstatic std::uint64_t nonlinearityGradFlops(const NonLinearityType &nlType) {\n  switch (nlType) {\n  case NonLinearityType::GELU:\n    return 15;\n  case NonLinearityType::SWISH:\n    return 5;\n  case NonLinearityType::RELU:\n    return 1;\n  case NonLinearityType::SIGMOID:\n    return 2;\n  case NonLinearityType::TANH:\n    return 2;\n  default:\n    throw poputil::poplibs_error(\"Unhandled non-linearity type\");\n  }\n}\n\nVertexPerfEstimate\nnonLinearity1DCycleEstimator(const VertexIntrospector &vertex,\n                             const Target &target, const Type &type,\n                             const NonLinearityType &nlType, bool inPlace) {\n  bool isNonInPlaceSwish = nlType == NonLinearityType::SWISH && inPlace;\n  bool isFloat = type == FLOAT;\n  CODELET_FIELD(data);\n  const auto numWorkers = target.getNumWorkerContexts();\n  const auto vectorWidth = target.getVectorWidth(type);\n  const auto n = data.size();\n\n  const auto numVectors = n / vectorWidth;\n  const auto remainder = n % vectorWidth;\n\n  // If any worker handles an extra vector due to the remainder\n  // we take the longest worker hence rounded up.\n  const auto vectorsPerWorker = (numVectors + numWorkers - 1) / numWorkers;\n\n  const auto opCycles = getNonLinearityOpCycles(nlType, isFloat, false);\n  const auto vectorLoopCycles = getNonLinearityOpCycles(nlType, isFloat, true);\n\n  // These cycle estimates follow the aligned path. Slightly optimistic.\n  // The cost of misalignment is ~9 cycles for half, less for float.\n  std::uint64_t cycles = 9; // Supervisor vertex overhead\n  std::uint64_t workerCycles =\n      3 + // Load input pointer, output pointer and size\n              isNonInPlaceSwish\n          ? 1\n          : 0 +     // Branch into shared code\n                5 + // Divide & Remainder to split work between workers\n                2 + // Get worker ID\n                2 + // Check 64-bit aligned and branch\n                5 + // Setup remainders and size for worker\n                3 + // Offset worker's pointers and branch if done\n                (vectorsPerWorker ? 1 : 0) *\n                    (2 + opCycles + // Warm up pipeline, rpt\n                     (vectorsPerWorker - 1) * vectorLoopCycles + 1 +\n                     opCycles); // Handle remaining element from pipeline\n\n  // possibly unpack pointers\n  workerCycles +=\n      poputil::internal::getUnpackCost(data.getProfilerVectorLayout(0));\n\n  // Add remainder handling cycles. This handling could be slightly overlapped\n  // with other workers if the worker doing the remainder had less vector\n  // work than the others. Some of these transcendental ops may take\n  // less time anyway so we'll just stick with the simpler estimation.\n  if (isFloat) {\n    workerCycles +=\n        3 + // Test worker ID to handle remainder, test remainder, branch\n        ((remainder & 1) ? 1 : 0) * (2 + opCycles); // Handle 32-bit remainder\n  } else {\n    workerCycles +=\n        2 + // Test worker ID to handle remainder with\n        1 + // branch for 32-bit remainder\n        ((remainder & 2) ? 1 : 0) * (2 + opCycles) + // Handle 32-bit remainder\n        1 + // branch for 16-bit remainder\n        ((remainder & 1) ? 1 : 0) * (3 + opCycles); // Handle 16-bit remainder\n  }\n\n  std::uint64_t flops = n * nonlinearityFlops(nlType);\n\n  return {cycles + (workerCycles * numWorkers),\n          convertToTypeFlops(flops, type)};\n}\n\nVertexPerfEstimate\nMAKE_PERF_ESTIMATOR_NAME(NonLinearity1D)(const VertexIntrospector &vertex,\n                                         const Target &target, const Type &type,\n                                         const NonLinearityType &nlType) {\n  return nonLinearity1DCycleEstimator(vertex, target, type, nlType, false);\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(NonLinearity1DInPlace)(\n    const VertexIntrospector &vertex, const Target &target, const Type &type,\n    const NonLinearityType &nlType) {\n  return nonLinearity1DCycleEstimator(vertex, target, type, nlType, true);\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(NonLinearityGrad1D)(\n    const VertexIntrospector &vertex, const Target &target, const Type &type,\n    const NonLinearityType &nlType) {\n  bool isFloat = type == FLOAT;\n  const auto vectorWidth = target.getVectorWidth(type);\n  const auto numWorkers = target.getNumWorkerContexts();\n  CODELET_FIELD(inGrad);\n  CODELET_FIELD(outGrad);\n  CODELET_FIELD(out);\n  const auto n = inGrad.size();\n  assert(outGrad.size() == n);\n  assert(out.size() == n);\n\n  const auto inGradLayout = inGrad.getProfilerVectorLayout(0);\n  assert(inGradLayout == outGrad.getProfilerVectorLayout(0) &&\n         inGradLayout == out.getProfilerVectorLayout(0));\n\n  const auto numVectors = n / vectorWidth;\n  const auto remainder = n % vectorWidth;\n  const auto vectorsPerWorker = (numVectors + numWorkers - 1) / numWorkers;\n  const auto opCycles = getNonLinearityGradOpCycles(nlType, isFloat, false);\n  const auto vectorCycles = getNonLinearityGradOpCycles(nlType, isFloat, true);\n\n  std::uint64_t cycles = 9; // Supervisor vertex overhead\n  std::uint64_t workerCycles =\n      3 + // Load vertex state\n      5 + // Split work between workers\n      2 + // Get worker ID\n      3 + // Add remaining vectors to relevant workers\n      3 + // Offset pointers to data\n      3 + // Pre-load inputs, and generate ones if needed\n      1 + // Branch if no vectors\n      (vectorsPerWorker ? 1 : 0) * (4 + // Warm up the pipeline\n                                    (vectorsPerWorker - 1) * vectorCycles +\n                                    1); // Store remaining element\n\n  // get real pointers from scaled pointers\n  if (inGradLayout == layout::Vector::ScaledPtr64) {\n    workerCycles += poputil::internal::getUnpackCost(inGradLayout) + 2;\n  }\n\n  if (isFloat) {\n    workerCycles += 2 + // Pick a worker to handle the remainder, branch\n                    2 + // Check for remainder\n                    (remainder ? 1 : 0) * (opCycles + 1);\n  } else {\n    workerCycles += 2 + // Pick a worker to handle remainders, branch\n                    2 + // Check for 32-bit remainder\n                    ((remainder & 2) ? 1 : 0) * (opCycles + 2) +\n                    2 + // Check for 16-bit remainder\n                    ((remainder & 1) ? 1 : 0) * (opCycles + 4);\n  }\n\n  return {cycles + (workerCycles * numWorkers),\n          convertToTypeFlops(n * nonlinearityGradFlops(nlType), type)};\n}\n\nVertexPerfEstimate\nnonLinearity2DCycleEstimator(const VertexIntrospector &vertex,\n                             const Target &target, const Type &type,\n                             const NonLinearityType &nlType, bool inPlace) {\n  bool isNonInPlaceSwish = nlType == NonLinearityType::SWISH && inPlace;\n  bool isFloat = type == FLOAT;\n  const auto vectorWidth = target.getVectorWidth(type);\n  CODELET_FIELD(data);\n  const auto n0 = data.size();\n  assert(n0 > 0);\n\n  std::uint64_t cycles = 5; // Vertex overhead\n\n  const auto opCycles = getNonLinearityOpCycles(nlType, isFloat, false);\n  const auto vectorLoopCycles = getNonLinearityOpCycles(nlType, isFloat, true);\n\n  cycles += isNonInPlaceSwish\n                ? 1\n                : 0 +     // Load out pointer\n                      2 + // Load base pointer, DeltaN pointer\n                      5 + // Unpack base pointer, n0, DeltaN pointer\n                      2;  // Set mask for inner loop, sub for brnzdec\n\n  // Following 64-bit aligned path\n  unsigned totalElements = 0;\n  const std::uint64_t flopsPerElement = nonlinearityFlops(nlType);\n  for (std::size_t i = 0; i < n0; ++i) {\n    const auto n1 = data[i].size();\n    const auto numVectors = n1 / vectorWidth;\n    const auto remainder = n1 % vectorWidth;\n\n    cycles += 4 +                 // Load DeltaN, calculate inner pointer and n1\n              1 +                 // Load next out ptr or copy data ptr\n              (isFloat ? 0 : 2) + // Test 32-bit aligned\n              (isFloat ? 2 : 3) + // Test 64-bit aligned\n              2 +                 // Shift to get num vectors, branch if 0\n              (numVectors ? 1 : 0) * (2 + opCycles + // Warm up pipeline\n                                      (numVectors - 1) * vectorLoopCycles + 1 +\n                                      opCycles); // Handle last element\n\n    if (isFloat) {\n      cycles += 2 + // Check for remainder, branch\n                (remainder ? 1 : 0) * (2 + opCycles);\n    } else {\n      cycles += 2 + // Check for 32-bit remainder, branch\n                ((remainder & 2) ? 1 : 0) * (2 + opCycles) +\n                2 + // Check for 16-bit remainder, branch\n                ((remainder & 1) ? 1 : 0) * (3 + opCycles);\n    }\n\n    cycles += 1; // brnzdec\n\n    // assume one flop per element regardless of non-linearity type\n    totalElements += n1;\n  }\n\n  return {cycles, convertToTypeFlops(totalElements * flopsPerElement, type)};\n}\nVertexPerfEstimate\nMAKE_PERF_ESTIMATOR_NAME(NonLinearity2D)(const VertexIntrospector &vertex,\n                                         const Target &target, const Type &type,\n                                         const NonLinearityType &nlType) {\n  return nonLinearity2DCycleEstimator(vertex, target, type, nlType, false);\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(NonLinearity2DInPlace)(\n    const VertexIntrospector &vertex, const Target &target, const Type &type,\n    const NonLinearityType &nlType) {\n  return nonLinearity2DCycleEstimator(vertex, target, type, nlType, true);\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(NonLinearityGrad2D)(\n    const VertexIntrospector &vertex, const Target &target, const Type &type,\n    const NonLinearityType &nlType) {\n  bool isFloat = type == FLOAT;\n  const auto vectorWidth = target.getVectorWidth(type);\n  CODELET_FIELD(inGrad);\n  CODELET_FIELD(outGrad);\n  CODELET_FIELD(out);\n  const auto n0 = inGrad.size();\n  assert(outGrad.size() == n0);\n  assert(out.size() == n0);\n  assert(n0 > 0);\n\n  std::uint64_t cycles = 5; // Vertex overhead\n\n  cycles += 4 + // Load vertex state\n            3 + // Load DeltaN base/n0, generate ones if needed\n            3 + // Calculate DeltaN pointer\n            2;  // Set mask for inner loop, sub for brnzdec\n\n  const auto opCycles = getNonLinearityGradOpCycles(nlType, isFloat, false);\n  const auto vectorCycles = getNonLinearityGradOpCycles(nlType, isFloat, true);\n\n  unsigned totalElements = 0;\n  for (std::size_t i = 0; i < n0; ++i) {\n    const auto n1 = inGrad[i].size();\n    assert(outGrad[i].size() == n1);\n    assert(out[i].size() == n1);\n    const auto numVectors = n1 / vectorWidth;\n    const auto remainder = n1 % vectorWidth;\n\n    cycles += 6 + // Load DeltaN, calculate inner pointer/n1, shift for n1 vecs\n              3 + // Pre-load inputs for pipeline, branch if 0\n              (numVectors ? 1 : 0) * (4 + // Warm up pipeline\n                                          // Store last element\n                                      (numVectors - 1) * vectorCycles + 1);\n\n    if (isFloat) {\n      cycles += 2 + // Check for remainder\n                (remainder ? 1 : 0) * (1 + opCycles);\n    } else {\n      cycles += 2 + // Check for 32-bit remainder\n                ((remainder & 2) ? 1 : 0) * (2 + opCycles) +\n                2 + // Check for 16-bit remainder\n                ((remainder & 1) ? 1 : 0) * (4 + opCycles);\n    }\n    totalElements += n1;\n    cycles += 1; // brnzdec\n  }\n\n  return {cycles, convertToTypeFlops(\n                      totalElements * nonlinearityGradFlops(nlType), type)};\n}\n\nVertexPerfEstimate\npoolingCycleEstimator(const VertexIntrospector &vertex, const Target &target,\n                      const Type &dataType, const PoolingType &pType,\n                      bool isBwdPass, bool isGradientScale = false) {\n  CODELET_SCALAR_VAL(initInfo, unsigned short);\n  CODELET_SCALAR_VAL(chansPerGroupDM1, unsigned short);\n  CODELET_SCALAR_VAL(numChanGroupsM1, unsigned short);\n  CODELET_VECTOR_VALS(startPos, unsigned short);\n  CODELET_VECTOR_2D_VALS(workList, unsigned short);\n  CODELET_FIELD(out);\n  CODELET_FIELD(in);\n\n  const auto numWorkers = target.getNumWorkerContexts();\n\n  const auto startPosLayout =\n      vertex.getFieldInfo(\"startPos\").getProfilerVectorLayout(0);\n  const auto workListLayout =\n      vertex.getFieldInfo(\"workList\").getProfilerVectorListLayout();\n\n  UnpackCosts unpackCosts;\n  unpackCosts.outLayout =\n      poputil::internal::getUnpackCost(out.getProfilerVectorLayout(0));\n\n  unpackCosts.inLayout =\n      poputil::internal::getUnpackCost(in.getProfilerVectorLayout(0));\n  unpackCosts.fwdOutLayout = unpackCosts.outLayout;\n  unpackCosts.fwdInLayout = unpackCosts.inLayout;\n\n  unpackCosts.startPosLayout = poputil::internal::getUnpackCost(startPosLayout);\n  unpackCosts.workListLayout = poputil::internal::getUnpackCost(workListLayout);\n\n  auto cycles = getPoolingCycles(\n      initInfo, chansPerGroupDM1 + 1, numChanGroupsM1, startPos, workList,\n      unpackCosts, pType == PoolingType::MAX, isBwdPass, numWorkers);\n\n  // compute flops\n  unsigned totalWorkItems = 0;\n  for (unsigned wId = 0; wId < numWorkers; ++wId) {\n    const unsigned numRows =\n        wId == 0 ? startPos[0] : startPos[wId] - startPos[wId - 1];\n    for (unsigned row = 0; row < numRows; ++row) {\n      const unsigned sPos = wId == 0 ? 0 : startPos[wId - 1];\n      for (unsigned w = 0; w != workList[sPos + row].size(); w += 3) {\n        totalWorkItems += workList[sPos + row][w + 2];\n      }\n    }\n  }\n  std::uint64_t numChanGroups = numChanGroupsM1 + 1;\n  const auto scaleFactor = dataType == poplar::HALF ? 4 : 2;\n  const auto chansPerGroup = (chansPerGroupDM1 + 1) * scaleFactor;\n  std::uint64_t flops = 0;\n\n  if (dataType == FLOAT || dataType == HALF) {\n    flops += numChanGroups * totalWorkItems * chansPerGroup;\n\n    if (pType == PoolingType::AVG || pType == PoolingType::SUM ||\n        isGradientScale) {\n      // additional flops for division/scale\n      flops += numChanGroups * chansPerGroup * initInfo;\n    }\n  }\n  return {cycles, convertToTypeFlops(flops, dataType)};\n}\n\nVertexPerfEstimate\nMAKE_PERF_ESTIMATOR_NAME(MaxPooling)(const VertexIntrospector &vertex,\n                                     const Target &target, const Type &type) {\n  return poolingCycleEstimator(vertex, target, type, PoolingType::MAX, false);\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(MaxPoolingGradientScale)(\n    const VertexIntrospector &vertex, const Target &target, const Type &type) {\n  return poolingCycleEstimator(vertex, target, type, PoolingType::MAX, false,\n                               true);\n}\n\nVertexPerfEstimate\nMAKE_PERF_ESTIMATOR_NAME(SumPooling)(const VertexIntrospector &vertex,\n                                     const Target &target, const Type &type) {\n  return poolingCycleEstimator(vertex, target, type, PoolingType::SUM, false);\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(SelectiveScaling)(\n    const VertexIntrospector &vertex, const Target &target, const Type &type) {\n  // TODO: T5436 Improve this estimate.\n  return 10;\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(MaxPoolingGrad)(\n    const VertexIntrospector &vertex, const Target &target, const Type &type) {\n  (void)type;\n  return poolingCycleEstimator(vertex, target, type, PoolingType::MAX, true);\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(LossSumSquaredTransform)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &fpType) {\n  const bool isFloat = fpType == FLOAT;\n  const auto size = vertex.getFieldInfo(\"probs\").size();\n  const auto isSoftmax = false;\n  std::uint64_t flops = static_cast<std::uint64_t>(size) * 3;\n  auto cycles = getLossTransformCycles(isFloat, isSoftmax, size);\n  return {cycles, convertToTypeFlops(flops, fpType)};\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(LossCrossEntropyTransform)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &fpType) {\n  const bool isFloat = fpType == FLOAT;\n  const auto size = vertex.getFieldInfo(\"probs\").size();\n  const auto isSoftmax = true;\n  std::uint64_t flops = static_cast<std::uint64_t>(size) * 6 + 2;\n  auto cycles = getLossTransformCycles(isFloat, isSoftmax, size);\n  return {cycles, convertToTypeFlops(flops, fpType)};\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(ReduceMaxClassGather)(\n    const VertexIntrospector &vertex, const Target &target, const Type &inType,\n    const Type &labelType) {\n  std::uint64_t supervisorCycles = 5 + // Vertex overhead\n                                   4;  // Supervisor call + sync\n  CODELET_FIELD(activations);\n  CODELET_SCALAR_VAL(size, unsigned);\n  CODELET_SCALAR_VAL(workerSize, unsigned);\n  const auto numWorkers = target.getNumWorkerContexts();\n  // Check the divisor chosen is large enough to process all inputs\n  // with the target number of workers and the grain size.\n  assert(workerSize * numWorkers >= size);\n  std::uint64_t cycles;\n  if (inType == FLOAT || inType == HALF) {\n    // Assembly, supervisor implementation\n    // Size is the size of the whole tensor, divisor indicates the region an\n    // individual worker operates on.  So each worker does divisor inner loop\n    // passes unless size is small, in which case one worker does size inner\n    // loop passes, and all the others do nothing.\n    cycles = 3 + // Load acts pointer, size, divisor\n             2 + // Get worker ID\n             4 + // Calculate the worker's region\n             3 + // Calculate N, sub 1 for first element, branch if no work.\n             1 + // Offset pointer for worker\n             3 + // Load first element as max, setup pointers\n             1 + // rpt\n             std::min(workerSize - 1, size - 1) * 3 +\n             3 + // Handle remaining element from loop\n             6 + // Calculate max index from max act pointer\n             4;  // Load maxValue/maxIndex pointers, store (+f16->f32 for half)\n  } else {\n    // Compiled, 1 worker (pseudo supervisor) version for other types\n    const auto nOutputs = (size + workerSize - 1) / workerSize;\n    cycles = 22 +                                // Net overhead\n             nOutputs * ((workerSize * 6) + 25); // Inner, outer loop overhead\n  }\n  return {cycles * numWorkers + supervisorCycles,\n          convertToTypeFlops(size, inType)};\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(ReduceMaxNClassGather)(\n    const VertexIntrospector &vertex, const Target &target, const Type &fpType,\n    const bool sorted) {\n  CODELET_FIELD(activations);\n  CODELET_SCALAR_VAL(divisorLog2, unsigned short);\n  CODELET_SCALAR_VAL(numK, unsigned short);\n\n#ifndef NDEBUG\n  const auto numWorkers = target.getNumWorkerContexts();\n#endif\n  const auto divisor = (1u << divisorLog2);\n  // Check the divisor chosen is large enough to process all inputs\n  // with the target number of workers and the grain size.\n  assert(divisor * numWorkers >= activations.size());\n\n  const auto nOutputs = (activations.size() + divisor - 1) / divisor;\n\n  std::uint64_t cycles = 10 + // Initial set up.\n                         2;   // Enter nOutputsloop.\n\n  // Gather is assumed to have (roughly) the same cycles as sparse but in a\n  // loop. It also doesn't benefit from compile time optimizations.\n  for (unsigned i = 0; i < nOutputs; ++i) {\n    cycles += 23; // Rough estimate for the first add.\n\n    // For the first K we have a guaranteed push op.\n    for (unsigned i = 1; i < numK; ++i) {\n      cycles += 13 +              // Setup\n                std::log(i) * 20; // log(i) loop.\n    }\n\n    // Assumes the worst case. This would be the case of activations being\n    // sorted in assending order.\n    cycles += (activations.size() - numK) * (13 + std::log(numK) * 20);\n\n    // As we are working on the indices we do a bit at the end to store the\n    // actual values as well and transform the indices.\n    cycles += 8 * numK;\n\n    if (sorted) {\n      for (int i = numK; i >= 1; --i) {\n        cycles += 10;               // Setup.\n        cycles += 20 * std::log(i); // log(k-1) pop operation.\n      }\n    }\n  }\n\n  return cycles;\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(ReduceMaxNClassSparse)(\n    const VertexIntrospector &vertex, const Target &target, const Type &type,\n    const bool sorted) {\n  CODELET_SCALAR_VAL(numK, unsigned short);\n  CODELET_FIELD(activations);\n\n  std::uint64_t cycles = 10 + // Initial set up.\n                         2;   // Enter N loop.\n\n  cycles += 23; // Rough estimate for the first add.\n\n  // For the first K we have a guaranteed push op.\n  for (int i = 1; i < numK; ++i) {\n    cycles += 13 +              // Setup\n              std::log(i) * 20; // log(i) loop.\n  }\n\n  // Assumes the worst case. This would be the case of activations being\n  // sorted in assending order.\n  cycles += (activations.size() - numK) * (13 + std::log(numK) * 20);\n\n  // As we are working on the indices we do a bit at the end to store the actual\n  // values as well and transform the indices.\n  cycles += 8 * numK;\n\n  // Sorting is very expensive but even if requested by the user it will ony be\n  // performed on the very last reduction.\n  if (sorted) {\n    for (int i = numK; i >= 1; --i) {\n      cycles += 10;               // Setup.\n      cycles += 20 * std::log(i); // log(k-1) pop operation.\n    }\n  }\n  return cycles;\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(ReduceMaxClassSparse)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &inOutType, const Type &labelType) {\n  std::uint64_t cycles = 5; // Vertex overhead\n  CODELET_FIELD(activations);\n  CODELET_FIELD(labels);\n  const auto numActs = activations.size();\n  assert(numActs == labels.size());\n  if (inOutType == HALF || inOutType == FLOAT) {\n    // Assembly implementation\n    cycles += 2 + // Load acts start/end pointer\n              3 + // Calculate N, sub 1 for first element\n              3 + // Load first element as max, setup pointers\n              1 + // rpt\n              (numActs - 1) * 3 + 3 + // Handle remaining element from loop\n              6 + // Calculate max index from max act pointer\n              4;  // Load maxValue/maxIndex pointers, store\n  } else {\n    // Compiled versions for other types\n    cycles += 18 +         // Net overhead\n              numActs * 6; // Loop cycles\n  }\n  return cycles;\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(ReduceMinClassGather)(\n    const VertexIntrospector &vertex, const Target &target, const Type &inType,\n    const Type &labelType) {\n  std::uint64_t supervisorCycles = 5 + // Vertex overhead\n                                   4;  // Supervisor call + sync\n  CODELET_FIELD(activations);\n  CODELET_SCALAR_VAL(size, unsigned);\n  CODELET_SCALAR_VAL(workerSize, unsigned);\n  const auto numWorkers = target.getNumWorkerContexts();\n  // Check the divisor chosen is large enough to process all inputs\n  // with the target number of workers and the grain size.\n  assert(workerSize * numWorkers >= size);\n  std::uint64_t cycles;\n  if (inType == FLOAT || inType == HALF) {\n    // Assembly, supervisor implementation\n    // Size is the size of the whole tensor, divisor indicates the region an\n    // individual worker operates on.  So each worker does divisor inner loop\n    // passes unless size is small, in which case one worker does size inner\n    // loop passes, and all the others do nothing.\n    cycles = 3 + // Load acts pointer, size, divisor\n             2 + // Get worker ID\n             4 + // Calculate the worker's region\n             3 + // Calculate N, sub 1 for first element, branch if no work.\n             1 + // Offset pointer for worker\n             3 + // Load first element as max, setup pointers\n             1 + // rpt\n             std::min(workerSize - 1, size - 1) * 3 +\n             3 + // Handle remaining element from loop\n             6 + // Calculate min index from min act pointer\n             4;  // Load minValue/minIndex pointers, store (+f16->f32 for half)\n  } else {\n    // Compiled, 1 worker (pseudo supervisor) version for other types\n    const auto nOutputs = (size + workerSize - 1) / workerSize;\n    cycles = 22 +                                // Net overhead\n             nOutputs * ((workerSize * 6) + 25); // Inner, outer loop overhead\n  }\n  return {cycles * numWorkers + supervisorCycles,\n          convertToTypeFlops(size, inType)};\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(ReduceMinClassSparse)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &inOutType, const Type &labelType) {\n  std::uint64_t cycles = 5; // Vertex overhead\n  CODELET_FIELD(activations);\n  CODELET_FIELD(labels);\n  const auto numActs = activations.size();\n  assert(numActs == labels.size());\n  if (inOutType == HALF || inOutType == FLOAT) {\n    // Assembly implementation\n    cycles += 2 + // Load acts start/end pointer\n              3 + // Calculate N, sub 1 for first element\n              3 + // Load first element as max, setup pointers\n              1 + // rpt\n              (numActs - 1) * 3 + 3 + // Handle remaining element from loop\n              6 + // Calculate min index from min act pointer\n              4;  // Load minValue/minIndex pointers, store\n  } else {\n    // Compiled version for other types\n    cycles += 18 +         // Total overhead\n              numActs * 6; // Loop cycles\n  }\n  return {cycles, convertToTypeFlops(numActs, inOutType)};\n}\n\nVertexPerfEstimate\nMAKE_PERF_ESTIMATOR_NAME(CalcAccuracy)(const VertexIntrospector &vertex,\n                                       const Target &target,\n                                       const Type &labelType) {\n  std::uint64_t cycles = 5; // Vertex overhead\n  CODELET_FIELD(maxPerBatch);\n  CODELET_FIELD(expected);\n  const auto batchSize = maxPerBatch.size();\n  assert(batchSize == expected.size());\n\n  cycles += 4 + // Load maxPerBatch start/end, sub, shift for num elements\n            2 + // Load expected and numCorrect pointer\n            1 + // Load initial numCorrect value\n            1;  // rpt\n\n  cycles += batchSize * (2 + // Load maxPerBatch/expected\n                         1 + // cmpeq\n                         1); // add\n\n  cycles += 1; // Store final numCorrect\n\n  // calc accuracy does no FP operations\n  return cycles;\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCAlpha)(\n    const VertexIntrospector &vertex, const Target &target, const Type &inType,\n    const Type &outType, const Type symbolType, const bool isLastLabel) {\n  CODELET_FIELD(label);\n  // Label contains the previous symbol as a dependency, not an extra result\n  return {alphaCycles(1, label.size() - 1, false),\n          alphaFlops(1, label.size() - 1, outType, false)};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCBeta)(\n    const VertexIntrospector &vertex, const Target &target, const Type &inType,\n    const Type &outType, const Type symbolType, const bool isFirstLabel) {\n  CODELET_FIELD(label);\n  // Label contains the previous symbol as a dependency, not an extra result\n  return {betaCycles(1, label.size() - 1, false),\n          betaFlops(1, label.size() - 1, outType, false)};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCGradGivenAlpha)(\n    const VertexIntrospector &vertex, const Target &target, const Type &inType,\n    const Type &outType, const Type symbolType, const bool isFirstLabel) {\n  CODELET_FIELD(label);\n  // Label contains the previous symbol as a dependency, not an extra result\n  return {gradGivenAlphaCycles(1, label.size() - 1, false),\n          gradGivenAlphaFlops(1, label.size() - 1, outType, false)};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCGradGivenBeta)(\n    const VertexIntrospector &vertex, const Target &target, const Type &inType,\n    const Type &outType, const Type symbolType, const bool isLastLabel) {\n  CODELET_FIELD(label);\n  // Label contains the previous symbol as a dependency, not an extra result\n  return {gradGivenBetaCycles(1, label.size() - 1, false),\n          gradGivenBetaFlops(1, label.size() - 1, outType, false)};\n}\n\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCGenerateCopyCandidates)(\n    const VertexIntrospector &vertex, const Target &target, const Type &inType,\n    const Type &partialsType, const Type symbolType) {\n  // TODO: cycle estimator\n  return {0, 0};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCGenerateExtendCandidates)(\n    const VertexIntrospector &vertex, const Target &target, const Type &inType,\n    const Type &partialsType, const Type symbolType) {\n  // TODO: cycle estimator\n  return {0, 0};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCMergeCandidates)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &partialsType, const Type symbolType) {\n  // TODO: cycle estimator\n  return {0, 0};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCSelectCopyCandidates)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &partialsType, const Type symbolType) {\n  // TODO: cycle estimator\n  return {0, 0};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCSelectExtendCandidates)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &partialsType, const Type symbolType) {\n  // TODO: cycle estimator\n  return {0, 0};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCRankCandidates)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &partialsType, const Type symbolType) {\n  CODELET_SCALAR_VAL(totalCandidates, unsigned);\n  CODELET_SCALAR_VAL(firstCandidateToRank, unsigned);\n  CODELET_SCALAR_VAL(lastCandidateToRank, unsigned);\n  CODELET_SCALAR_VAL(beamwidth, unsigned);\n\n  const std::size_t supervisorCycles =\n      14 +                  // Vertex state load\n      (5 + 6) * beamwidth + // Initialise to zero loop\n      8;                    // runall, exit if complete\n\n  const auto numToRank = lastCandidateToRank - firstCandidateToRank;\n  const auto numWorkers = target.getNumWorkerContexts();\n  const auto maxToRankPerWorker =\n      poplibs_support::ceildiv(numToRank, numWorkers);\n\n  std::size_t workerCycles = 13;           // Non loop\n  workerCycles += maxToRankPerWorker * 28; // Outer loop body, including odd one\n  workerCycles +=\n      maxToRankPerWorker * 3 * ((totalCandidates - 1) / 2); // rpt loop content\n\n  workerCycles += 15; // Assume each worker will copy only once\n\n  std::size_t flops = totalCandidates * numToRank * 2;\n  return {supervisorCycles + workerCycles * numWorkers, flops};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCReduceCandidates)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &partialsType, const Type symbolType) {\n  CODELET_SCALAR_VAL(totalCandidates, unsigned);\n\n  const std::size_t supervisorCycles = 24 + // Exit if complete\n                                       12;  // runall, exit\n\n  std::size_t workerCycles = 13 + // Pre loop, processing 1\n                             (totalCandidates - 1) / 2 + // Actual loop\n                             6;                          // Post loop\n\n  const auto numWorkers = target.getNumWorkerContexts();\n  const unsigned numItemsToReduce = 5;\n  return {supervisorCycles + workerCycles * numWorkers,\n          totalCandidates * numItemsToReduce};\n}\nVertexPerfEstimate MAKE_PERF_ESTIMATOR_NAME(CTCUpdate)(\n    const VertexIntrospector &vertex, const Target &target,\n    const Type &partialsType, const Type symbolType) {\n\n  CODELET_SCALAR_VAL(beamwidth, unsigned);\n\n  const std::size_t supervisorCycles = 12 + // Load pointers, vertex state\n                                       16;  // Exit branch and function calls\n  // Slowest worker path\n  const std::size_t workerCycles = 16 +            // Pre loop\n                                   beamwidth * 7 + // Loop body\n                                   1;              // Post loop\n\n  const auto numWorkers = target.getNumWorkerContexts();\n  return {supervisorCycles + numWorkers * workerCycles, 0};\n}\nVertexPerfEstimate\nMAKE_PERF_ESTIMATOR_NAME(CTCGenerateOutput)(const VertexIntrospector &vertex,\n                                            const Target &target,\n                                            const Type symbolType) {\n  // TODO: cycle estimator\n  return {0, 0};\n}\n\npoputil::internal::PerfEstimatorTable makePerfFunctionTable() {\n  return {\n      CYCLE_ESTIMATOR_ENTRY(popnn, LossSumSquaredTransform, FLOAT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, LossSumSquaredTransform, HALF),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, LossCrossEntropyTransform, FLOAT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, LossCrossEntropyTransform, HALF),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassGather, FLOAT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassGather, HALF, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassGather, INT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassGather, UNSIGNED_INT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassGather, FLOAT, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassGather, HALF, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassGather, INT, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassGather, UNSIGNED_INT, INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassSparse, FLOAT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassSparse, UNSIGNED_INT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassSparse, UNSIGNED_INT, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassSparse, FLOAT, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassSparse, INT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxClassSparse, INT, INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassGather, FLOAT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassGather, FLOAT, true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassGather, HALF, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassGather, HALF, true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassGather, INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassGather, INT, true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassGather, UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassGather, UNSIGNED_INT, true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassSparse, FLOAT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassSparse, FLOAT, true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassSparse, HALF, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassSparse, HALF, true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassSparse, INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassSparse, INT, true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassSparse, UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMaxNClassSparse, UNSIGNED_INT, true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassGather, FLOAT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassGather, HALF, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassGather, INT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassGather, UNSIGNED_INT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassGather, FLOAT, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassGather, HALF, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassGather, INT, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassGather, UNSIGNED_INT, INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassSparse, FLOAT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassSparse, INT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassSparse, UNSIGNED_INT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassSparse, FLOAT, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassSparse, UNSIGNED_INT, INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, ReduceMinClassSparse, INT, INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, CalcAccuracy, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CalcAccuracy, INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, MaxPoolingGrad, FLOAT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, MaxPoolingGrad, HALF),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, SumPooling, FLOAT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, SumPooling, HALF),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, MaxPooling, FLOAT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, MaxPooling, HALF),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, MaxPoolingGradientScale, FLOAT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, MaxPoolingGradientScale, HALF),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, SelectiveScaling, FLOAT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, SelectiveScaling, HALF),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCAlpha, FLOAT, FLOAT, UNSIGNED_INT, true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCAlpha, HALF, HALF, UNSIGNED_INT, true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCAlpha, HALF, FLOAT, UNSIGNED_INT, true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCBeta, FLOAT, FLOAT, UNSIGNED_INT, true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCBeta, HALF, HALF, UNSIGNED_INT, true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCBeta, HALF, FLOAT, UNSIGNED_INT, true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenAlpha, FLOAT, FLOAT,\n                            UNSIGNED_INT, true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenAlpha, HALF, HALF, UNSIGNED_INT,\n                            true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenAlpha, HALF, FLOAT, UNSIGNED_INT,\n                            true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenBeta, FLOAT, FLOAT, UNSIGNED_INT,\n                            true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenBeta, HALF, HALF, UNSIGNED_INT,\n                            true),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenBeta, HALF, FLOAT, UNSIGNED_INT,\n                            true),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCAlpha, FLOAT, FLOAT, UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCAlpha, HALF, HALF, UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCAlpha, HALF, FLOAT, UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCBeta, FLOAT, FLOAT, UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCBeta, HALF, HALF, UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCBeta, HALF, FLOAT, UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenAlpha, FLOAT, FLOAT,\n                            UNSIGNED_INT, false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenAlpha, HALF, HALF, UNSIGNED_INT,\n                            false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenAlpha, HALF, FLOAT, UNSIGNED_INT,\n                            false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenBeta, FLOAT, FLOAT, UNSIGNED_INT,\n                            false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenBeta, HALF, HALF, UNSIGNED_INT,\n                            false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGradGivenBeta, HALF, FLOAT, UNSIGNED_INT,\n                            false),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGenerateCopyCandidates, FLOAT, FLOAT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGenerateCopyCandidates, HALF, FLOAT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGenerateCopyCandidates, HALF, HALF,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGenerateExtendCandidates, FLOAT, FLOAT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGenerateExtendCandidates, HALF, FLOAT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGenerateExtendCandidates, HALF, HALF,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCMergeCandidates, FLOAT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCMergeCandidates, HALF, UNSIGNED_INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCSelectCopyCandidates, FLOAT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCSelectCopyCandidates, HALF, UNSIGNED_INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCSelectExtendCandidates, FLOAT,\n                            UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCSelectExtendCandidates, HALF,\n                            UNSIGNED_INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCRankCandidates, FLOAT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCRankCandidates, HALF, UNSIGNED_INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCReduceCandidates, FLOAT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCReduceCandidates, HALF, UNSIGNED_INT),\n\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCUpdate, HALF, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCUpdate, FLOAT, UNSIGNED_INT),\n      CYCLE_ESTIMATOR_ENTRY(popnn, CTCGenerateOutput, UNSIGNED_INT),\n\n      INSTANTIATE_NL_GRAD_CYCLE_ESTIMATOR(NonLinearityGrad1D),\n      INSTANTIATE_NL_CYCLE_ESTIMATOR(NonLinearity1DInPlace),\n      CYCLE_ESTIMATOR_ENTRY(popnn, NonLinearity1D, FLOAT,\n                            popnn::NonLinearityType::SWISH),\n      CYCLE_ESTIMATOR_ENTRY(popnn, NonLinearity1D, HALF,\n                            popnn::NonLinearityType::SWISH),\n\n      INSTANTIATE_NL_GRAD_CYCLE_ESTIMATOR(NonLinearityGrad2D),\n      INSTANTIATE_NL_CYCLE_ESTIMATOR(NonLinearity2DInPlace),\n      CYCLE_ESTIMATOR_ENTRY(popnn, NonLinearity2D, FLOAT,\n                            popnn::NonLinearityType::SWISH),\n      CYCLE_ESTIMATOR_ENTRY(popnn, NonLinearity2D, HALF,\n                            popnn::NonLinearityType::SWISH)};\n}\n\n} // end namespace popnn\n", "meta": {"hexsha": "ae8b889ff1224d98cfdae1d1ad5a68b57e720846", "size": 43399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/popnn/popnnCycleEstimators.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/popnn/popnnCycleEstimators.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/popnn/popnnCycleEstimators.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": 43.8816986855, "max_line_length": 80, "alphanum_fraction": 0.6659370032, "num_tokens": 11392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1898585785706167}}
{"text": "//--- aims -------------------------------------------------------------------\n#include <aims/bucket/bucketMap.h>                                // BucketMap\n#include <aims/data/data_g.h>                                      // AimsData\n#include <aims/getopt/getopt2.h>                            // AimsApplication\n#include <aims/getopt/getoptProcess.h>        // AimsApplication: ProcessInput\n#include <aims/io/datatypecode.h>                           // DataTypeCode<T>\n#include <aims/io/io_g.h>                          // Reader - Writer - Finder\n#include <aims/mesh/surfaceOperation.h>            // SurfaceManip::meshVolume\n#include <aims/graph/graphmanip.h>                           // storeTalairach\n#include <aims/transformation/affinetransformation3d.h> // AffineTransformation3d\n#include <aims/transformation/transformation_chain.h> // TransformationChain3d\n#include <aims/transform/transform_objects.h>\n#include <aims/resampling/linearresampler.h>                // LinearResampler\n#include <aims/resampling/cubicresampler.h>                  // CubicResampler\n#include <aims/resampling/resamplerfactory.h>\n#include <aims/resampling/standardreferentials.h>\n#include <aims/registration/ffd.h>                        // FfdTransformation\n//--- carto ------------------------------------------------------------------\n#include <cartobase/smart/rcptr.h>                                   // rc_ptr\n#include <cartobase/object/object.h>                                 // Object\n#include <cartobase/stream/fileutil.h>\n#include <cartobase/exception/errno.h>\n//--- soma -------------------------------------------------------------------\n#include <soma-io/allocator/allocator.h>\n//--- std --------------------------------------------------------------------\n#include <algorithm>\n#include <iostream>\n#include <exception>\n#include <sstream>\n//--- boost ------------------------------------------------------------------\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/lexical_cast.hpp>\n//----------------------------------------------------------------------------\n\nusing namespace aims;\nusing namespace std;\nusing namespace carto;\nusing namespace soma;\n\nnamespace {\n\nstatic const int EXIT_USAGE_ERROR = 2;\n\nstruct ApplyTransformProc;\n\nstruct FatalError : public runtime_error {\n  explicit FatalError(const string& msg) : runtime_error(msg) {}\n};\n\ntemplate <class T, class C>\nbool doVolume(Process &, const string &, Finder &);\ntemplate <int D>\nbool doMesh(Process &, const string &, Finder &);\nbool doBucket(Process &, const string &, Finder &);\nbool doBundles(Process &, const string &, Finder &);\nbool doGraph(Process &, const string &, Finder &);\n\n\nstruct ApplyTransformProc : public Process\n{\npublic:\n  ApplyTransformProc();\n\n  string  output;\n  vector<string> direct_transform_list;\n  vector<string> inverse_transform_list;\n  string  input_coords;\n  bool    points_mode;\n  string  interp_type;\n  string  background_value;\n  bool    keep_transforms;\n  bool    ignore_reference_transforms;\n  string  reference;\n  int32_t dx;\n  int32_t dy;\n  int32_t dz;\n  double  sx;\n  double  sy;\n  double  sz;\n  string  vfinterp;\n  bool    mmap_fields;\n  string  progress_file;\n};\n\n\nApplyTransformProc::ApplyTransformProc()\n  : Process(),\n    input_coords(\"AIMS\"),\n    points_mode(false),\n    interp_type(\"linear\"),\n    background_value(\"0\"),\n    keep_transforms(false),\n    ignore_reference_transforms(false),\n    dx(0), dy(0), dz(0),\n    sx(0.), sy(0.), sz(0.),\n    vfinterp(\"linear\"),\n    mmap_fields(false)\n{\n  registerProcessType(\"Volume\", \"S8\",      &doVolume<int8_t, int8_t>);\n  registerProcessType(\"Volume\", \"U8\",      &doVolume<uint8_t, uint8_t>);\n  registerProcessType(\"Volume\", \"S16\",     &doVolume<int16_t, int16_t>);\n  registerProcessType(\"Volume\", \"U16\",     &doVolume<uint16_t, uint16_t>);\n  registerProcessType(\"Volume\", \"S32\",     &doVolume<int32_t, int32_t>);\n  registerProcessType(\"Volume\", \"U32\",     &doVolume<uint32_t, uint32_t>);\n  registerProcessType(\"Volume\", \"FLOAT\",   &doVolume<float, float>);\n  registerProcessType(\"Volume\", \"DOUBLE\",  &doVolume<double, double>);\n  registerProcessType(\"Volume\", \"RGB\",     &doVolume<AimsRGB, AimsRGB::ChannelType>);\n  registerProcessType(\"Volume\", \"RGBA\",    &doVolume<AimsRGBA, AimsRGBA::ChannelType>);\n  registerProcessType(\"Volume\", \"POINT3DF\", &doVolume<Point3df, float>);\n  registerProcessType(\"Mesh\",   \"VOID\",    &doMesh<3>);\n  registerProcessType(\"Mesh4\",  \"VOID\",    &doMesh<4>);\n  registerProcessType(\"Segments\", \"VOID\",  &doMesh<2>);\n  registerProcessType(\"Bucket\", \"VOID\",    &doBucket);\n  registerProcessType(\"Graph\",  \"VOID\",    &doGraph);\n\n  // just for doc (bundles are handled by a special case in doGraph)\n  registerProcessType(\"BundleMap\", \"VOID\", &doBundles);\n}\n\n\ntemplate<class T>\nunique_ptr<Resampler<T> >\nget_resampler(const std::string& interp_type)\n{\n  map<string, int> resamplers;\n  resamplers[ \"n\" ] = 0;\n  resamplers[ \"nearest\" ] = 0;\n  resamplers[ \"0\" ] = 0;\n  resamplers[ \"l\" ] = 1;\n  resamplers[ \"linear\" ] = 1;\n  resamplers[ \"1\" ] = 1;\n  resamplers[ \"q\" ] = 2;\n  resamplers[ \"quadratic\" ] = 2;\n  resamplers[ \"2\" ] = 2;\n  resamplers[ \"c\" ] = 3;\n  resamplers[ \"cubic\" ] = 3;\n  resamplers[ \"3\" ] = 3;\n  resamplers[ \"quadric\" ] = 4;\n  resamplers[ \"4\" ] = 4;\n  resamplers[ \"quintic\" ] = 5;\n  resamplers[ \"5\" ] = 5;\n  resamplers[ \"six\" ] = 6;\n  resamplers[ \"sixthorder\" ] = 6;\n  resamplers[ \"6\" ] = 6;\n  resamplers[ \"seven\" ] = 7;\n  resamplers[ \"seventhorder\" ] = 7;\n  resamplers[ \"7\" ] = 7;\n  resamplers[ \"maj\" ] = 101;\n  resamplers[ \"majority\" ] = 101;\n  resamplers[ \"mef\" ] = 201;\n  resamplers[ \"median\" ] = 201;\n  int order = 0;\n\n  typename map<string, int>::iterator\ti = resamplers.find( interp_type );\n  if( i != resamplers.end() )\n    order = i->second;\n  else\n  {\n    // try another numeric value\n    stringstream s( interp_type );\n    try\n    {\n      s >> order;\n    }\n    catch( ... )\n    {\n      throw invalid_argument( \"invalid resampler type: \" + interp_type );\n    }\n    if( order == 0 )\n      throw invalid_argument( \"invalid resampler type: \" + interp_type );\n  }\n  return ResamplerFactory<T>::getResampler( order );\n}\n\n\nvoid set_geometry_from_header(ApplyTransformProc& proc,\n                              const DictionaryInterface &header,\n                              bool dimension_ok,\n                              bool voxel_size_ok)\n{\n  if(!voxel_size_ok) {\n    Object voxel_size = header.getProperty(\"voxel_size\");\n    if(!(proc.sx > 0))\n      proc.sx = voxel_size->getArrayItem(0)->getScalar();\n    if(!(proc.sy > 0))\n      proc.sy = voxel_size->getArrayItem(1)->getScalar();\n    if(!(proc.sz > 0))\n      proc.sz = voxel_size->getArrayItem(2)->getScalar();\n  }\n  if(!dimension_ok) {\n    Object volume_dimension = header.getProperty(\"volume_dimension\");\n    if(!(proc.dx > 0))\n      proc.dx = volume_dimension->getArrayItem(0)->getScalar();\n    if(!(proc.dy > 0))\n      proc.dy = volume_dimension->getArrayItem(1)->getScalar();\n    if(!(proc.dz > 0))\n      proc.dz = volume_dimension->getArrayItem(2)->getScalar();\n  }\n}\n\n\n// Return the header of the reference object, or a null reference if there is\n// no reference object.\ncarto::Object read_reference_header(const std::string reference_filename)\n{\n  carto::Object reference_header;\n  if(!reference_filename.empty()) {\n    Finder finder;\n    if(!finder.check(reference_filename)) {\n      throw FatalError(\"failed to read the header of the reference object \"\n                       + reference_filename);\n    }\n    reference_header = finder.headerObject();\n  }\n  return reference_header;\n}\n\n\n// Set dimensions and voxel size of the resampled object: in decreasing order\n// of priority, use commandline flags, else the reference object, else the\n// input object passed as fallback_header.\nvoid set_geometry(ApplyTransformProc& proc,\n                  const carto::Object& reference_header,\n                  const DictionaryInterface& fallback_header,\n                  bool set_dimensions)\n{\n  bool dimension_ok = !set_dimensions || (proc.dx > 0 && proc.dy > 0 && proc.dz > 0);\n  bool voxel_size_ok = proc.sx > 0 && proc.sy > 0 && proc.sz > 0;\n  if(dimension_ok && voxel_size_ok)\n    return;\n\n  // Reference volume\n  if(!reference_header.isNull()) {\n    try {\n      set_geometry_from_header(proc, *reference_header, dimension_ok,\n                               voxel_size_ok);\n    } catch(...) {\n      throw FatalError(\"Failed to retrieve volume_dimension and voxel_size \"\n                       \"from the reference object (\" + proc.reference + \")\");\n    }\n  }\n\n  dimension_ok = !set_dimensions || (proc.dx > 0 && proc.dy > 0 && proc.dz > 0);\n  voxel_size_ok = proc.sx > 0 && proc.sy > 0 && proc.sz > 0;\n  if(dimension_ok && voxel_size_ok)\n    return;\n\n  try {\n    set_geometry_from_header(proc, fallback_header, dimension_ok,\n                             voxel_size_ok);\n  } catch(...) {\n    throw FatalError(\"Failed to retrieve volume_dimension and voxel_size \"\n                     \"from the fallback object\");\n  }\n}\n\nvoid copy_referentials_and_transformations(const carto::Object& referentials,\n                                           const carto::Object& transformations,\n                                           carto::Object& referentials2,\n                                           carto::Object& transformations2)\n{\n  // Initialize new objects with empty vectors that they own\n  transformations2 = carto::Object::value<std::vector<std::vector<float> > >();\n  referentials2 = carto::Object::value<std::vector<std::string> >();\n\n  // Obtain a reference to the new vectors owned by the objects\n  std::vector<std::vector<float> > & t2\n    = transformations2->value<std::vector<std::vector<float> > >();\n  std::vector<std::string> & r2\n    = referentials2->value<std::vector<std::string> >();\n\n  // Copy the elements one by one\n  size_t nt = std::min(referentials->size(), transformations->size());\n  r2.reserve(nt);\n  t2.reserve(nt);\n  for( size_t i=0; i<nt; ++i ) {\n    AffineTransformation3d mat(transformations->getArrayItem(i));\n    t2.push_back(mat.toVector());\n    r2.push_back(referentials->getArrayItem(i)->getString());\n  }\n}\n\nvoid\ninsert_transformation_to_old_referential(DictionaryInterface& header,\n                                         const AffineTransformation3d& inverse_transform,\n                                         std::string old_referential_id)\n{\n  if(old_referential_id.empty()) {\n    old_referential_id = \"Coordinates aligned to another file or to \"\n      \"anatomical truth\";\n  }\n\n  typedef std::vector<std::string> ReferentialVectorType;\n  typedef std::vector<std::vector<float> > TransformVectorType;\n  carto::Object new_referentials_obj\n    = carto::Object::value<ReferentialVectorType>();\n  carto::Object new_transforms_obj\n    = carto::Object::value<TransformVectorType>();\n  ReferentialVectorType& new_referentials\n    = new_referentials_obj->value<ReferentialVectorType>();\n  TransformVectorType& new_transforms\n    = new_transforms_obj->value<TransformVectorType>();\n\n  // Copy the existing referentials and transformations\n  try {\n    carto::Object old_referentials, old_transforms;\n    old_referentials = header.getProperty(\"referentials\");\n    old_transforms = header.getProperty(\"transformations\");\n    new_referentials.reserve(old_referentials->size() + 1);\n    new_transforms.reserve(old_transforms->size() + 1);\n\n    for( carto::Object tit = old_transforms->objectIterator(),\n           rit = old_referentials->objectIterator();\n         tit->isValid() && rit->isValid();\n         tit->next(), rit->next() ) {\n      new_referentials.push_back(rit->currentValue()->getString());\n      AffineTransformation3d transform(tit->currentValue());\n      new_transforms.push_back(transform.toVector());\n    }\n  } catch(...) {\n    // An error occured while reading the existing transformations, discard\n    // what has been read until now.\n    new_referentials.clear();\n    new_transforms.clear();\n  }\n\n  // Insert a transformation to the old referential at the end\n  new_referentials.push_back(old_referential_id);\n  new_transforms.push_back(inverse_transform.toVector());\n  header.setProperty(\"referentials\", new_referentials_obj);\n  header.setProperty(\"transformations\", new_transforms_obj);\n}\n\n\nvoid adjust_header_transforms(const ApplyTransformProc& proc,\n                              DictionaryInterface& header,\n                              const Transformation3d * inverse_transform,\n                              const carto::Object reference_header)\n{\n  if(proc.keep_transforms) {\n    // Case 1: the user explicitly requests to keep the input header transforms\n    return;\n  }\n  if(inverse_transform && inverse_transform->isIdentity())\n    return;  // the transformations remain valid\n\n  std::string old_referential;\n  try {\n    old_referential = header.getProperty(\"referential\")->getString();\n  } catch(...) {}\n  // The referential UUID used by Axon is no longer valid\n  try {\n    header.removeProperty(\"referential\");\n  } catch(...) {}\n\n  const AffineTransformation3d * affine_inverse_transform\n    = dynamic_cast<const AffineTransformation3d*>(inverse_transform);\n\n  if(!proc.ignore_reference_transforms && !reference_header.isNull()) {\n    // Case 2: copy the referential and transformations from the reference\n    // object if enabled and available.\n\n    // TODO: specify the behaviour w.r.t. on-disk data orientation (i.e.\n    // storage_to_memory header field). We should probably copy it from the\n    // reference header, but only for Volumes (it is not used for other data\n    // types). Also, we should specify the behaviour w.r.t. preservation of the\n    // anatomical orientation (i.e. the allow_orientation_change flag of the\n    // somanifti writer).\n\n    // Copy the referential uuid from the reference header if present\n    std::string reference_referential;\n    try {\n      reference_referential =\n        reference_header->getProperty(\"referential\")->getString();\n    } catch(...) {\n    }\n    if(!reference_referential.empty()) {\n      header.setProperty(\"referential\",\n                         carto::Object::value(reference_referential));\n    }\n\n    // Copy the list of referentials and transformations from the reference\n    carto::Object new_referentials_obj, new_transforms_obj;\n    try {\n      copy_referentials_and_transformations(\n        reference_header->getProperty(\"referentials\"),\n        reference_header->getProperty(\"transformations\"),\n        new_referentials_obj,\n        new_transforms_obj\n      );\n    } catch(...) {\n      new_referentials_obj.reset();\n      new_transforms_obj.reset();\n    }\n    if(!new_referentials_obj.isNull()) {\n      header.setProperty(\"referentials\", new_referentials_obj);\n      header.setProperty(\"transformations\", new_transforms_obj);\n\n      if(affine_inverse_transform) {\n        insert_transformation_to_old_referential(header,\n                                                 *affine_inverse_transform,\n                                                 old_referential);\n      }\n      return; // success\n    }\n    // in case of failure, fall through to reach case 4\n  }\n\n  if(affine_inverse_transform) {\n    // Case 3: reuse the  referential and transformations from the input object\n    // and compose them with the inverse affine transformation\n    try {\n      carto::Object old_transforms = header.getProperty(\"transformations\");\n\n      typedef std::vector<std::vector<float> > TransformVectorType;\n      carto::Object new_transforms_obj\n        = carto::Object::value<TransformVectorType>();\n      TransformVectorType& new_transforms\n        = new_transforms_obj->value<TransformVectorType>();\n      new_transforms.reserve(old_transforms->size());\n\n      for( carto::Object it = old_transforms->objectIterator();\n           it->isValid();\n           it->next() ) {\n        carto::Object old_transform_obj = it->currentValue();\n        AffineTransformation3d transform(old_transform_obj);\n        transform *= *affine_inverse_transform;\n        new_transforms.push_back(transform.toVector());\n      }\n\n      header.setProperty(\"transformations\", new_transforms_obj);\n\n      insert_transformation_to_old_referential(header,\n                                               *affine_inverse_transform,\n                                               old_referential);\n      return; // success\n    } catch( ... ) {\n      // remove all transformations by falling through to reach case 4\n    }\n  }\n\n  // Case 4: if neither case 1 nor case 2 applies, or if an error occurs while\n  // updating the transformations, we fail gracefully by removing all\n  // pre-existing transformations from the input object.\n  try {\n    header.removeProperty(\"transformations\");\n  } catch(...) {}\n  try {\n    header.removeProperty(\"referentials\");\n  } catch(...) {}\n\n  if(affine_inverse_transform) {\n    insert_transformation_to_old_referential(header, *affine_inverse_transform,\n                                             old_referential);\n  }\n}\n\n\n// Throws FatalError in case of failure\nrc_ptr<FfdTransformation>\nload_ffd_deformation(const string &filename,\n                     const ApplyTransformProc &proc)\n{\n  rc_ptr<FfdTransformation> deformation;\n\n  // Maybe find a better way of choosing the vector field interpolation for\n  // each transformation (URL parameter?)\n  if(proc.vfinterp == \"cubic\" || proc.vfinterp == \"c\")\n    deformation.reset(new SplineFfd);\n  else if(proc.vfinterp == \"linear\" || proc.vfinterp == \"l\")\n    deformation.reset(new TrilinearFfd);\n  else\n    throw invalid_argument(\"invalid vector field interpolation type: \"\n                           + proc.vfinterp + \", aborting.\");\n\n  AllocatorContext requested_allocator(AllocatorStrategy::ReadOnly);\n  if(proc.mmap_fields) {\n    // The \"use factor\" is used calculate a threshold size above which\n    // memory-mapping is attempted, based on the currently available memory. By\n    // setting it to zero, we can force memory-mapping to be always attempted.\n    requested_allocator.setUseFactor(0.f);\n  }\n\n  aims::Reader<FfdTransformation> rdef(filename);\n  rdef.setAllocatorContext(requested_allocator);\n  bool read_success = rdef.read(*deformation);\n  if(!read_success) {\n    ostringstream s;\n    s << \"Failed to load a deformation field from \"\n      << filename << \", aborting.\";\n    throw FatalError(s.str());\n  }\n\n  const AllocatorContext & actual_allocator =\n    static_cast<const VolumeRef<Point3df> & >(\n      *deformation.get()).allocatorContext();\n  if(proc.mmap_fields\n     && actual_allocator.allocatorType() != AllocatorStrategy::ReadOnlyMap)\n  {\n    std::clog << \"Warning: memory-mapping was requested but could not be used\"\n              << std::endl;\n  }\n\n  return deformation;\n}\n\n\nrc_ptr<Transformation3d>\nload_transformation(const string &filename_arg,\n                    const ApplyTransformProc &proc)\n{\n  bool invert;\n  string filename;\n\n  if(filename_arg.substr(0, 4) == \"inv:\") {\n    filename = filename_arg.substr(4, std::string::npos);\n    invert = true;\n  } else {\n    filename = filename_arg;\n    invert = false;\n  }\n\n  Finder finder;\n  if(!finder.check(filename)) {\n    ostringstream s;\n    s << \"Failed to check the transformation file \" << filename;\n    throw FatalError(s.str());\n  }\n\n  if(finder.objectType() == \"Volume\" && finder.dataType() == \"POINT3DF\")\n  {\n    if(invert) {\n      ostringstream s;\n      s << \"Cannot invert a deformation field)\"\n        << filename_arg << \"), aborting.\";\n      throw FatalError(s.str());\n    }\n    rc_ptr<FfdTransformation> deformation = load_ffd_deformation(\n      filename, proc\n     );\n    return rc_ptr<Transformation3d>(deformation.release());\n  }\n  else if(finder.objectType() == \"AffineTransformation3d\")\n  {\n    rc_ptr<AffineTransformation3d> affine(new AffineTransformation3d);\n    aims::Reader<AffineTransformation3d> reader(filename);\n    bool read_success = reader.read(*affine);\n    if(!read_success) {\n      ostringstream s;\n      s << \"Failed to load affine transformation from \"\n        << filename << \", aborting.\";\n      throw FatalError(s.str());\n    }\n    if(invert) {\n      *affine = affine->inverse();\n    }\n    return rc_ptr<Transformation3d>(affine.release());\n  }\n\n  ostringstream s;\n  s << \"Unsupported object type \" << finder.objectType()\n    << \"(of \" << finder.dataType() << \") passed in \" << filename;\n  throw FatalError(s.str());\n}\n\n\n// FatalError is thrown if the transformations cannot be loaded properly.\nstd::pair<const_ref<Transformation3d>, const_ref<Transformation3d> >\nload_transformations(const ApplyTransformProc& proc,\n                     const DictionaryInterface* input_header = nullptr)\n{\n  std::pair<const_ref<Transformation3d>, const_ref<Transformation3d> > ret;\n  rc_ptr<AffineTransformation3d> aims_to_input_space_transform; // null\n\n  // boost::iequals is used for case-insensitive comparison\n  using boost::iequals;\n  string effective_input_coords = boost::trim_copy(proc.input_coords);\n  if(proc.points_mode) {\n    if(iequals(effective_input_coords, \"auto\"))\n      effective_input_coords = \"AIMS\";\n    else if(!iequals(effective_input_coords, \"AIMS\"))\n      throw FatalError(\"--input-coords cannot be used in points mode\");\n  }\n\n  if(!iequals(effective_input_coords, \"AIMS\")) {\n    if(!input_header || !input_header->isDictionary()) {\n      throw FatalError(\"--input-coords cannot be used, because no header \"\n                       \"could be read for the input data\");\n    }\n\n    carto::Object referentials;\n    carto::Object transformations;\n    try\n    {\n      referentials = input_header->getProperty( \"referentials\" );\n      transformations = input_header->getProperty( \"transformations\" );\n    }\n    catch( ... )\n    {\n      throw FatalError(\"--input-coords cannot be used, because no \"\n                       \"transformations could be read in the input header\");\n    }\n    if(referentials.isNull() || transformations.isNull()) {\n      throw FatalError(\"--input-coords cannot be used, because no \"\n                       \"transformations could be read in the input header\");\n    }\n\n    // Valid values are >= 0\n    int transform_position = -1;\n    // Detect special values\n    if(iequals(effective_input_coords, \"first\")) {\n      transform_position = 0;\n    } else if(iequals(effective_input_coords, \"last\")\n              || iequals(effective_input_coords, \"auto\")) {\n      transform_position = std::min(referentials->size(),\n                                    transformations->size()) - 1;\n    } else if(iequals(effective_input_coords, \"qform\")\n       || iequals(effective_input_coords, \"ITK\")\n       || iequals(effective_input_coords, \"ANTS\")) {\n      // TODO determine transform_position\n      throw FatalError(\"--input-coords qform not implemented yet\");\n    } else if(iequals(effective_input_coords, \"sform\")) {\n      // TODO determine transform_position\n      throw FatalError(\"--input-coords sform not implemented yet\");\n    } else {\n      try {\n        transform_position = boost::lexical_cast<int>(effective_input_coords);\n      } catch(const boost::bad_lexical_cast &) {}\n    }\n\n    if(transform_position < 0) {\n      string referential_name, referential_id;\n\n      if(iequals(effective_input_coords, \"mni\")\n         || iequals(effective_input_coords, \"mni152\")\n         || iequals(effective_input_coords, \"NIFTI_XFORM_MNI_152\")) {\n        referential_name = StandardReferentials::mniTemplateReferential();\n        referential_id = StandardReferentials::mniTemplateReferentialID();\n      } else if(iequals(effective_input_coords, \"scanner\")\n                || iequals(effective_input_coords, \"NIFTI_XFORM_SCANNER_ANAT\")) {\n        referential_name = StandardReferentials::commonScannerBasedReferential();\n        referential_id = StandardReferentials::commonScannerBasedReferentialID();\n      } else if(iequals(effective_input_coords, \"acpc\")) {\n        referential_name = StandardReferentials::acPcReferential();\n        referential_id = StandardReferentials::acPcReferentialID();\n      } else if(iequals(effective_input_coords, \"talairach\")\n                || iequals(effective_input_coords, \"NIFTI_XFORM_TALAIRACH\")) {\n        referential_name = StandardReferentials::talairachReferential();\n      } else if(iequals(effective_input_coords, \"aligned\")\n                || iequals(effective_input_coords, \"NIFTI_XFORM_ALIGNED_ANAT\")) {\n        referential_name = \"Coordinates aligned to another file or to anatomical truth\";\n      } else if(iequals(effective_input_coords, \"NIFTI_XFORM_TEMPLATE_OTHER\")) {\n        referential_name = \"Other template\";\n      } else {\n        referential_name = proc.input_coords;\n      }\n\n      // Look for the target referential or id in header['referentials']\n      size_t i = 0;\n      for( carto::Object it = referentials->objectIterator();\n           it->isValid();\n           it->next(), ++i ) {\n        const carto::Object referential_obj = it->currentValue();\n        if(!referential_obj.isNone() && referential_obj->isString()) {\n          const string current_ref_name = referential_obj->getString();\n          if(current_ref_name == referential_name\n             || (!referential_id.empty()\n                 && current_ref_name == referential_id)) {\n            transform_position = i;\n            if(carto::verbose)\n            break;\n          }\n        }\n      }\n    }\n\n    if(transform_position >= 0) {\n      carto::Object transformation_object;\n      if(!transformations->isArray())\n        throw FatalError(\"--input-coords cannot find a valid 'transformations'\"\n                         \"header field\");\n      if(!(transform_position < transformations->size())) {\n        stringstream error_message;\n        error_message << \"--input-coords cannot use transform in position \"\n                      << transform_position\n                      << \" (0-based), the header contains only \"\n                      << transformations->size() << \" transformations.\";\n        throw FatalError(error_message.str());\n      }\n      transformation_object = transformations->getArrayItem(transform_position);\n      if(!transformation_object.isNull()) {\n        aims_to_input_space_transform.reset(\n          new AffineTransformation3d(transformation_object));\n        if(carto::verbose) {\n          std::cout << \"--input-coords will use the referential in position \"\n                    << transform_position\n                    << \" (0-based) which is named '\"\n                    << referentials->getArrayItem(transform_position)->getString()\n                    << \"'\\n\";\n          std::cout << \"--input-coords transformation:\\n\"\n                    << *aims_to_input_space_transform\n                    << \"\\n\";\n        }\n      } else {\n        throw FatalError(\"Error in the input header, --input-coords failed\");\n      }\n    } else if(iequals(effective_input_coords, \"auto\")) {\n      // Do nothing: fall back to AIMS coordinates\n      // (aims_to_input_space_transform is a null pointer)\n    } else {\n      throw FatalError(\"Cannot find the header transformation corresponding \"\n                       \"to --input-coords '\" + proc.input_coords + \"'\");\n    }\n  }\n\n  if(!proc.direct_transform_list.empty()) {\n    TransformationChain3d direct_chain;\n    if(!aims_to_input_space_transform.isNull())\n      direct_chain.push_back(aims_to_input_space_transform);\n\n    for(vector<string>::const_iterator filename_it = proc.direct_transform_list.begin();\n        filename_it != proc.direct_transform_list.end();\n        ++filename_it)\n    {\n      rc_ptr<Transformation3d> transform\n        = load_transformation(*filename_it, proc);\n      direct_chain.push_back(transform);\n    }\n    ret.first = direct_chain.simplify();\n  }\n\n  if(!proc.inverse_transform_list.empty()) {\n    TransformationChain3d inverse_chain;\n\n    for(vector<string>::const_iterator filename_it = proc.inverse_transform_list.begin();\n        filename_it != proc.inverse_transform_list.end();\n        ++filename_it)\n    {\n      rc_ptr<Transformation3d> transform\n        = load_transformation(*filename_it, proc);\n      inverse_chain.push_back(transform);\n    }\n    if(!aims_to_input_space_transform.isNull()) {\n      if(!aims_to_input_space_transform->invertible()) {\n        throw FatalError(\"Error using --input-coords: the transformation \"\n                         \"is not invertible\");\n      }\n      inverse_chain.push_back(aims_to_input_space_transform->getInverse());\n    }\n    ret.second = inverse_chain.simplify();\n  }\n\n  if(ret.first.isNull() && ret.second.isNull()) {\n    if(aims_to_input_space_transform.isNull()) {\n      clog << \"No transformation provided, identity will be used.\" << endl;\n      ret.first = const_ref<Transformation3d>(new TransformationChain3d);\n      ret.second = const_ref<Transformation3d>(new TransformationChain3d);\n    } else {\n      TransformationChain3d direct_chain;\n      direct_chain.push_back(aims_to_input_space_transform);\n      ret.first = direct_chain.simplify();\n    }\n  }\n\n  if(ret.first.isNull() && ret.second->invertible()) {\n    ret.first = const_ref<Transformation3d>(ret.second->getInverse());\n  }\n\n  if(ret.second.isNull() && ret.first->invertible()) {\n    ret.second = const_ref<Transformation3d>(ret.first->getInverse());\n  }\n\n  return ret;\n}\n\n\ntemplate <class T, class C>\nbool doVolume(Process & process, const string & fileref, Finder &)\n{\n  ApplyTransformProc & proc = (ApplyTransformProc &) process;\n\n  // Read the input image\n  aims::Reader<Volume<T> > input_reader(fileref);\n  input_reader.setAllocatorContext(AllocatorStrategy::ReadOnly);\n  Volume<T> input_image;\n  input_reader.read(input_image);\n\n  // Parse the background value to the data type\n  T background_value;\n  stringTo(proc.background_value, background_value);\n\n  // Load the transformation\n  const_ref<Transformation3d> inverse_transform;\n  {\n    std::pair<const_ref<Transformation3d>, const_ref<Transformation3d> > transforms\n      = load_transformations(proc, &input_image.header());\n    inverse_transform = transforms.second;\n    if(inverse_transform.isNull()) {\n      clog << \"Error: no inverse transform provided\" << endl;\n      return false;\n    }\n  }\n\n  // Compute dimensions of the output volume\n  const carto::Object reference_header = read_reference_header(proc.reference);\n  set_geometry(proc, reference_header, input_image.header(), true);\n\n  cout << \"Output dimensions: \"\n       << proc.dx << \", \" << proc.dy << \", \" << proc.dz << endl;\n  cout << \"Output voxel size: \"\n       << proc.sx << \", \" << proc.sy << \", \" << proc.sz << \" mm\" << endl;\n\n  // Prepare the output resampled volume\n  Volume<T> out(proc.dx, proc.dy, proc.dz, input_image.getSizeT());\n  out.copyHeaderFrom(input_image.header());\n  vector<float> vs(4);\n  vs[0] = proc.sx;\n  vs[1] = proc.sy;\n  vs[2] = proc.sz;\n  vs[3] = input_image.getVoxelSize()[3];\n  out.header().setProperty(\"voxel_size\", vs);\n\n  // Prepare the resampler\n  unique_ptr<aims::Resampler<T> > resampler\n    = get_resampler<T>(proc.interp_type);\n\n  unique_ptr<ostream> progress_stream;\n  if( !proc.progress_file.empty() )\n  {\n    progress_stream.reset( new ofstream( proc.progress_file.c_str(),\n                                         ios::app ) );\n    resampler->setVerboseStream( *progress_stream );\n  }\n\n  adjust_header_transforms(proc, out.header(), inverse_transform.pointer(),\n                           reference_header);\n  // The UUID should NOT be preserved, because the output is a different file\n  // from the input. Keeping it triggers the infamous \"duplicate UUID\" problem\n  // in BrainVISA/Axon...\n  try {\n    out.header().removeProperty(\"uuid\");\n  } catch(...) {}\n\n  // Perform resampling\n  cout << \"Resampling \" << DataTypeCode<Volume<T> >::name() << \"... \";\n  resampler->resample_inv(input_image, *inverse_transform,\n                          background_value, out, true);\n  cout << endl;\n\n  // Write the resampled volume. The allow_orientation_change instructs the\n  // NIfTI writer to avoid writing dummy transformations to the header of the\n  // output image.\n  Writer<Volume<T> > output_writer(\n    proc.output,\n    carto::Object::value(std::map<std::string, bool>{\n      {\"allow_orientation_change\", true} })\n  );\n  bool success = output_writer.write(out);\n\n  return success;\n}\n\n\ntemplate <int D>\nbool doMesh(Process & process, const string & fileref, Finder &)\n{\n  ApplyTransformProc & proc = (ApplyTransformProc &) process;\n  typedef AimsTimeSurface<D, Void> MeshType;\n\n  // Read the input mesh\n  aims::Reader<MeshType> input_reader(fileref);\n  input_reader.setAllocatorContext(AllocatorStrategy::InternalModif);\n  AimsTimeSurface<D, Void> mesh;\n  input_reader.read(mesh);\n\n  // Load the transformation\n  const_ref<Transformation3d> direct_transform, inverse_transform;\n  {\n    std::pair<const_ref<Transformation3d>, const_ref<Transformation3d> > transforms\n      = load_transformations(proc, &mesh.header());\n    direct_transform = transforms.first;\n    inverse_transform = transforms.second; // allowed to be null\n    if(direct_transform.isNull()) {\n      clog << \"Error: no direct transform provided\" << endl;\n      return false;\n    }\n  }\n\n  const carto::Object reference_header = read_reference_header(proc.reference);\n  adjust_header_transforms(proc, mesh.header(), inverse_transform.pointer(),\n                           reference_header);\n  // The UUID should NOT be preserved, because the output is a different file\n  // from the input. Keeping it triggers the infamous \"duplicate UUID\" problem\n  // in BrainVISA/Axon...\n  try {\n    mesh.header().removeProperty(\"uuid\");\n  } catch(...) {}\n\n\n  // Perform the transformation\n  cout << \"Transforming \" << DataTypeCode<MeshType>::name() << \"... \";\n  transformMesh(mesh, *direct_transform);\n  cout << endl;\n\n  // Write the transformed mesh\n  Writer<AimsTimeSurface<D, Void> > w3(proc.output);\n  bool success = w3.write(mesh);\n\n  return success;\n}\n\n\nbool doBucket(Process & process, const string & fileref, Finder &)\n{\n  ApplyTransformProc & proc = (ApplyTransformProc &) process;\n\n  typedef BucketMap<Void> BucketType;\n\n  aims::Reader<BucketType> input_reader(fileref);\n  input_reader.setAllocatorContext(AllocatorStrategy::ReadOnly);\n  BucketType input_bucket;\n  input_reader.read(input_bucket);\n\n  // Prepare the output dimensions\n  const carto::Object reference_header = read_reference_header(proc.reference);\n  set_geometry(proc, reference_header, input_bucket.header(), false);\n  cout << \"Output voxel size: \"\n       << proc.sx << \", \" << proc.sy << \", \" << proc.sz << \" mm\" << endl;\n\n  // Load the transformation\n  const_ref<Transformation3d> direct_transform, inverse_transform;\n  {\n    std::pair<const_ref<Transformation3d>, const_ref<Transformation3d> > transforms\n      = load_transformations(proc, &input_bucket.header());\n    direct_transform = transforms.first;\n    inverse_transform = transforms.second; // allowed to be null\n    if(direct_transform.isNull()) {\n      clog << \"Error: no direct transform provided\" << endl;\n      return false;\n    }\n  }\n\n  // Perform the transformation\n  // TODO: add an option to use pushforward, pullback, or both\n  rc_ptr<BucketMap<Void> > out;\n\n  if(!inverse_transform.isNull()) {\n    cout << \"Resampling \" << DataTypeCode<BucketType>::name()\n         << \" with the combined pushforward and pullback methods... \";\n    out = resampleBucket(input_bucket, *direct_transform, *inverse_transform,\n                         Point3df(proc.sx, proc.sy, proc.sz));\n  } else {\n    cout << \"Transforming \" << DataTypeCode<BucketType>::name()\n         << \" with the low-quality pushforward method... \";\n    out = transformBucketDirect(input_bucket, *direct_transform,\n                                Point3df(proc.sx, proc.sy, proc.sz));\n  }\n  cout << endl;\n\n  out->setHeader(input_bucket.header());\n  // The UUID should NOT be preserved, because the output is a different file\n  // from the input. Keeping it triggers the infamous \"duplicate UUID\" problem\n  // in BrainVISA/Axon...\n  try {\n    out->header().removeProperty(\"uuid\");\n  } catch(...) {}\n\n  adjust_header_transforms(proc, out->header(), inverse_transform.pointer(),\n                           reference_header);\n\n  // Write the resampled volume\n  Writer<BucketMap<Void> > w3(proc.output);\n  bool success = w3.write(*out);\n\n  return success;\n}\n\n\nbool doBundles(Process & process, const string & fileref, Finder &)\n{\n  ApplyTransformProc & proc = (ApplyTransformProc &) process;\n\n  // Prepare the Bundle reader\n  aims::BundleReader bundle_reader(fileref);\n\n  // Load the transformation\n  const_ref<Transformation3d> direct_transform, inverse_transform;\n  {\n    std::pair<const_ref<Transformation3d>, const_ref<Transformation3d> > transforms\n      = load_transformations(proc, bundle_reader.readHeader().get());\n    direct_transform = transforms.first;\n    inverse_transform = transforms.second; // allowed to be null\n    if(direct_transform.isNull()) {\n      clog << \"Error: no direct transform provided\" << endl;\n      return false;\n    }\n  }\n\n  // FIXME: there is no API to set the output header, so the transformations\n  // will just be ignored for Bundles.\n  //\n  // carto::Object header = bundle_reader.readHeader();\n  // const carto::Object reference_header\n  //   = read_reference_header(proc.reference);\n  // adjust_header_transforms(proc, header, inverse_transform.pointer(),\n  //                          reference_header);\n\n  // Prepare the Bundles processing chain\n  BundleTransformer transformer(direct_transform);\n  bundle_reader.addBundleListener(transformer);\n  BundleWriter bundle_writer;\n  bundle_writer.setFileString(proc.output);\n  transformer.addBundleListener(bundle_writer);\n\n  cout << \"Transforming Bundles... \";\n  bundle_reader.read();\n  cout << endl;\n\n  return true;\n}\n\n\nbool doGraph(Process & process, const string & fileref, Finder & f)\n{\n  // check bundles objects, which are reported as graphs by Finder\n  // (since they can be read as graphs, which is the only data structure to\n  // represent them internally)\n  const PythonHeader *ph = dynamic_cast<const PythonHeader *>(f.header());\n  if(ph\n     && ph->hasProperty(\"format\")\n     && ph->getProperty(\"format\")->isString()\n     && ph->getProperty(\"format\")->getString().substr(0, 8) == \"bundles_\")\n    return doBundles(process, fileref, f);\n\n  // other cases are \"real\" graphs\n\n  ApplyTransformProc & proc = (ApplyTransformProc &) process;\n\n  // Read the input Graph\n  aims::Reader<Graph> input_reader(fileref);\n  input_reader.setAllocatorContext(AllocatorStrategy::InternalModif);\n  unique_ptr<Graph> graph(input_reader.read());\n\n  // Deduce the voxel size of the output Graph\n  const carto::Object reference_header = read_reference_header(proc.reference);\n  set_geometry(proc, reference_header, *graph, false);\n  cout << \"Output voxel size: \"\n       << proc.sx << \", \" << proc.sy << \", \" << proc.sz << \" mm\" << endl;\n\n  // Load the transformation\n  // TODO: add an option to use pushforward, pullback, or both for Buckets\n  const_ref<Transformation3d> direct_transform, inverse_transform;\n  {\n    std::pair<const_ref<Transformation3d>, const_ref<Transformation3d> > transforms\n      = load_transformations(proc, graph.get());\n    direct_transform = transforms.first;\n    inverse_transform = transforms.second; // allowed to be null\n    if(direct_transform.isNull()) {\n      clog << \"Error: no direct transform provided\" << endl;\n      return false;\n    }\n  }\n\n  adjust_header_transforms(proc, *graph,\n                           inverse_transform.pointer(),\n                           reference_header);\n  // Update the transformation to Talairach stored in the old attributes\n  // (Talairach_rotation, Talairach_translation, and Talairach_scale) to\n  // reflect the updated transformations.\n  GraphManip::storeTalairach(*graph, GraphManip::talairach(*graph));\n\n  // The UUID should NOT be preserved, because the output is a different file\n  // from the input. Keeping it triggers the infamous \"duplicate UUID\" problem\n  // in BrainVISA/Axon...\n  try {\n    graph->removeProperty(\"uuid\");\n  } catch(...) {}\n  try {\n    graph->getProperty(\"header\")->removeProperty(\"uuid\");\n  } catch(...) {}\n\n  // Perform the graph transformation\n  cout << \"Resampling Graph... \";\n  transformGraph(*graph, *direct_transform, inverse_transform.pointer(),\n                 Point3df(proc.sx, proc.sy, proc.sz));\n  cout << endl;\n\n  // Write the output Graph\n  Writer<Graph> output_writer(proc.output);\n  graph->setProperty(\"filename_base\", \"*\");\n  bool success = output_writer.write(*graph);\n\n  return success;\n}\n\n\nbool doPoints(ApplyTransformProc & proc, const string & filename)\n{\n  // Open the input stream\n  istream *input_stream = 0;\n  ifstream input_file_stream;\n  stringstream input_string_stream;\n  if(filename == \"-\")\n  {\n    input_stream = &std::cin;  // standard input stream\n  }\n  else if(FileUtil::fileStat(filename).find('+') != string::npos)\n  {\n    input_file_stream.open(filename.c_str());\n    if(!input_file_stream)\n      throw errno_error();\n    input_stream = &input_file_stream;\n  }\n  else\n  {\n    input_string_stream.str(filename);\n    input_stream = &input_string_stream;\n  }\n\n  // Open the output stream\n  const bool print_on_stdout = proc.output.empty() || proc.output == \"-\";\n  ostream * output_stream;\n  ofstream output_file_stream;\n  if(print_on_stdout)\n  {\n    output_stream = &std::cout;\n  }\n  else\n  {\n    output_file_stream.open(proc.output.c_str());\n    if(!output_file_stream)\n      throw errno_error();\n    output_stream = &output_file_stream;\n  }\n\n  // Load the transformation\n  const_ref<Transformation3d> direct_transform;\n  {\n    std::pair<const_ref<Transformation3d>, const_ref<Transformation3d> > transforms\n      = load_transformations(proc);\n    direct_transform = transforms.first;\n    if(direct_transform.isNull()) {\n      clog << \"Error: no direct transform provided\" << endl;\n      return false;\n    }\n  }\n\n  // Transform all points in the input stream and write to the output stream\n  while(input_stream->good())\n  {\n    Point3df p(1e38, 1e38, 1e38), q;\n    *input_stream >> p;\n    if(p == Point3df(1e38, 1e38, 1e38))\n      break;\n    q = direct_transform->transform(p);\n    if(proc.output.empty())\n      *output_stream << \"p : \" << p << \" -> \";\n    *output_stream << q << \"\\n\";\n    if(output_stream->fail()) {\n      std::clog << \"Error writing to the output stream\" << std::endl;\n      return false;\n    }\n  }\n  if(input_stream->bad()) {\n    // We should check for fail(), but it is also set when everything goes\n    // well...\n    std::clog << \"Error reading the input stream of points\" << std::endl;\n    return false;\n  }\n\n  return true;\n}\n\n} // end of anonymous namespace\n\n\nint main(int argc, const char **argv)\n{\n  int result = EXIT_SUCCESS;\n\n  try {\n    ApplyTransformProc proc;\n    ProcessInput  proc_input(proc);\n\n    //\n    // Collect arguments.\n    //\n    AimsApplication app(\n      argc, argv,\n      \"Apply a spatial transformation on an image, a mesh, a 'bucket'\\n\"\n      \"(voxels list file), fiber tracts, a graph, or to points.\\n\"\n      \"\\n\"\n      \"Depending on the type of input, the direct transformation and/or the\\n\"\n      \"inverse transformation are needed:\\n\"\n      \"- Images need the inverse transformation, because they are resampled\\n\"\n      \"  using pullback interpolation;\\n\"\n      \"- Meshes and Bundles need the direct transformation only;\\n\"\n      \"- Buckets and Graphs need the direct transformation (pushforward), but\\n\"\n      \"  a better interpolation method will be used for Buckets if the\\n\"\n      \"  inverse transformation is also available (combined pullback and\\n\"\n      \"  pushforward).\\n\"\n      \"\\n\"\n      \"These rules apply for passing the transformations:\\n\"\n      \"- An arbitrary number of transformations can be specified, they will\\n\"\n      \"  be composed in the order that they appear on the command line\\n\"\n      \"  (e.g. for flags '-m A.trm -m B.trm', A will be applied before B,\\n\"\n      \"  in other words, the matrix product BA will be used);\\n\"\n      \"- Each transformation can be an affine transform (in .trm format) or\\n\"\n      \"  a displacement field (in .ima/.dim GIS format, a.k.a. \\\"FFD\\\" for\\n\"\n      \"  Free-Form Deformation);\\n\"\n      \"- Direct transformations must be given with --direct-transform/-d/-m,\\n\"\n      \"  ordered from the input space to the target space;\\n\"\n      \"- Inverse transformations must be given with --inverse-transform/-I/-M,\\n\"\n      \"  ordered from the target space to the input space;\\n\"\n      \"- If only one transformation is specified (direct or inverse), the\\n\"\n      \"  other will be computed automatically if the full transformation\\n\"\n      \"  chain can be inverted. Otherwise, both transformation chains must\\n\"\n      \"  be specified completely.\\n\"\n      \"\\n\"\n      \"The meaning of coordinates in the input image can be specified with \\n\"\n      \"the --input-coords option. This option specifies how to interpret the\\n\"\n      \"transformations contained in the image header. --input-coords can\\n\"\n      \"take the following values:\\n\"\n      \"- 'AIMS' (default): internal coordinate system of the AIMS library.\\n\"\n      \"  For images, this is defined as 'physical' coordinates in\\n\"\n      \"  millimetres, starting from zero at the centre of the rightmost,\\n\"\n      \"  most anterior, most superior voxel in the image. Note that AIMS\\n\"\n      \"  determines the anatomical orientation based on the header in a\\n\"\n      \"  format-dependent manner. For NIfTI it uses first qform then sform\\n\"\n      \"  if they point to a referential of known orientation, and falls back\\n\"\n      \"  to assuming a RAS+ on-disk orientation.\\n\"\n      \"- 'auto': use the last transformation defined in the AIMS metadata\\n\"\n      \"  (i.e. the last or qform or sform to be defined) or fallback to\\n\"\n      \"  AIMS coordinates if no transformation is found.\\n\"\n      \"- 'first': use the first transformation defined in the AIMS metadata,\\n\"\n      \"  i.e. the first or qform or sform to be defined.\\n\"\n      \"- 'last': use the last transformation defined in the AIMS metadata,\\n\"\n      \"  i.e. the last or qform or sform to be defined.\\n\"\n      \"- '0', '1'... or any non-negative integer: use the transformation\\n\"\n      \"  in that position (0-based) in the AIMS metadata field\\n\"\n      \"  'transformations' (0 is a synonym of 'first').\\n\"\n      /* These options are not implemented yet. TODO(ylep)\n      \"- 'qform', 'ITK', or 'ANTS': use the target space of the qform stored\\n\"\n      \"  in a NIfTI file. This corresponds to the physical space used in\\n\"\n      \"  tools based on the ITK library, such as ANTS.\\n\"\n      \"- sform: use the target space of the sform stored in a NIfTI file.\\n\"\n      // TODO: do some tools use sform?\n      */\n      \"- a referential name or UUID: use that referential from the\\n\"\n      \"  'referentials' field of the AIMS image header, which is read from\\n\"\n      \"  the image header or the sidecar .minf file (the .minf takes\\n\"\n      \"  precedence). There are shortcuts for common cases:\\n\"\n      \"  - 'mni', or 'mni152': use MNI coordinates, which correspond to the\\n\"\n      \"    NIFTI_XFORM_MNI_152 intent, a.k.a. 'Talairach-MNI template-SPM',\\n\"\n      \"    in AIMS.\\n\"\n      \"  - 'scanner': use 'Scanner-based anatomical coordinates', which\\n\"\n      \"    correspond to the NIFTI_XFORM_SCANNER_ANAT intent.\\n\"\n      \"  - 'acpc': use the 'Talairach-AC/PC-Anatomist' referential.\\n\"\n      \"  - 'aligned': use the referential that corresponds to\\n\"\n      \"    the NIFTI_XFORM_ALIGNED_ANAT intent, a.k.a. 'Coordinates aligned\\n\"\n      \"    to another file or to anatomical truth' in AIMS.\\n\"\n      \"  - 'talairach': use the referential that corresponds to the\\n\"\n      \"    NIFTI_XFORM_TALAIRACH intent.\\n\"\n      \"  - 'NIFTI_XFORM_TEMPLATE_OTHER': use the referential that\\n\"\n      \"    corresponds to this intent ('Other template' in AIMS).\\n\"\n      \"\\n\"\n      \"The header transformations of the output are set according to the\\n\"\n      \"first rule that applies:\\n\"\n      \"1. If --keep-transforms is passed, or if the applied transformation\\n\"\n      \"   is identity, the header transformations of the input object are\\n\"\n      \"   copied verbatim to the output. This mode should be used when\\n\"\n      \"   applying a corrective transformation.\\n\"\n      \"2. If --reference is given and unless --ignore-reference-transform is\\n\"\n      \"   passed, the transformations of the reference object are copied to\\n\"\n      \"   the output.\\n\"\n      \"3. If the applied transformation is affine, the output transformations\\n\"\n      \"   are set to the header transforms of the input, composed with the\\n\"\n      \"   applied transformation.\\n\"\n      \"4. If none of the rules above apply, no transformations are set in\\n\"\n      \"   the output header.\\n\"\n      \"\\n\"\n      \"Points mode is activated by passing the --points option.\\n\"\n      \"In this mode, the --input option either specifies an ASCII file\\n\"\n      \"containing point coordinates, or is directly one or several points\\n\"\n      \"coordinates on the command-line. Points should be formatted as\\n\"\n      \"\\\"(x, y, z)\\\", with parentheses and commas. Points will be written\\n\"\n      \"to the output stream in the same format, one point per line.\\n\"\n      \"The input or output file names can also be -, which means standard\\n\"\n      \"input and standard output, respectively. If --output is omitted,\\n\"\n      \"the points are written on standard output in a user-friendly format.\\n\"\n      \"\\n\"\n      \"Note also that for meshes or points, the dimensions, voxel sizes,\\n\"\n      \"reference, and resampling options are not needed and are ignored.\"\n   );\n    app.addOption(proc_input, \"--input\", \"Input image\");\n    app.addOption(proc.output, \"--output\", \"Output image\", true);\n    app.addOptionSeries(proc.direct_transform_list,\n                        \"--direct-transform\",\n                        \"direct transformation (from input space to \"\n                        \"output space). Multiple transformations will \"\n                        \"be composed in the order that they are \"\n                        \"passed on the command-line. The file name may be \"\n                        \"prefixed with 'inv:', in which case the inverse of \"\n                        \"the transformation is used.\");\n    app.addOptionSeries(proc.inverse_transform_list,\n                        \"--inverse-transform\",\n                        \"inverse transformation (from output space to \"\n                        \"input space). Multiple transformations will \"\n                        \"be composed in the order that they are \"\n                        \"passed on the command-line. The file name may be \"\n                        \"prefixed with 'inv:', in which case the inverse of \"\n                        \"the transformation is used.\");\n    app.addOption(proc.input_coords, \"--input-coords\",\n                  \"How to interpret coordinates in the input image w.r.t. \"\n                  \"the transformations written in the image header. See above.\"\n                  \" [default: AIMS]\", true);\n    app.addOption(proc.points_mode, \"--points\",\n                  \"Points mode: transform point coordinates (see above).\", true);\n    app.addOption(proc.interp_type, \"--interp\",\n                  \"Type of interpolation used for Volumes: n[earest], \"\n                  \"l[inear], q[uadratic], c[cubic], quartic, quintic, \"\n                  \"six[thorder], seven[thorder], maj[ority], med[ian] \"\n                  \"[default=linear]. Modes may \"\n                  \"also be specified as order number: 0=nearest, 1=linear... \"\n                  \"Additional values: 101=majority, 201=median\",\n                  true);\n    app.addOption(proc.background_value, \"--background\",\n                  \"Value used for the background of Volumes\", true);\n    app.addOption(proc.dx, \"--dx\",\n                  \"Output X dimension [default: same as input]\", true);\n    app.addOption(proc.dy, \"--dy\",\n                  \"Output Y dimension [default: same as input]\", true);\n    app.addOption(proc.dz, \"--dz\",\n                  \"Output Z dimension [default: same as input]\", true);\n    app.addOption(proc.sx, \"--sx\",\n                  \"Output X voxel size [default: same as input]\", true);\n    app.addOption(proc.sy, \"--sy\",\n                  \"Output Y voxel size [default: same as input]\", true);\n    app.addOption(proc.sz, \"--sz\",\n                  \"Output Z voxel size [default: same as input]\", true);\n    app.addOption(proc.reference, \"--reference\",\n                  \"Volume used to define output voxel size and volume \"\n                  \"dimension (values are overridden by --dx, --dy, \"\n                  \"--dz, --sx, --sy and --sz)\", true);\n    app.addOption(proc.keep_transforms, \"--keep-transforms\",\n                  \"Preserve the transformations of the input image\", true);\n    app.addOption(proc.ignore_reference_transforms,\n                  \"--ignore-reference-transforms\",\n                  \"Do not try to copy the transformations from the reference \"\n                  \"image\", true);\n    app.addOption(proc.vfinterp, \"--vectorinterpolation\",\n                  \"Interpolation used for vector field transformations \"\n                  \"(a.k.a. FFD): l[inear], c[ubic] [default = linear]\", true);\n    app.addOption(proc.mmap_fields, \"--mmap-fields\",\n                  \"Try to memory-map the deformation fields instead of\"\n                  \"loading them entirely in memory. This may improve the \"\n                  \"performance for transforming sparse point sets.\", true);\n    app.addOption(proc.progress_file, \"--progress\",\n                  \"write progress info in this file. The file is opened in \"\n                  \"append mode, so that it can be an existing file, \"\n                  \"already opened by a monitoring application.\", true );\n    app.alias(\"-i\",             \"--input\");\n    app.alias(\"-m\",             \"--direct-transform\");\n    app.alias(\"--motion\",       \"--direct-transform\");\n    app.alias(\"-d\",             \"--direct-transform\");\n    app.alias(\"-I\",             \"--inverse-transform\");\n    app.alias(\"-M\",             \"--inverse-transform\");\n    app.alias(\"--type\",         \"--interp\");\n    app.alias(\"-t\",             \"--interp\");\n    app.alias(\"--bg\",           \"--background\");\n    app.alias(\"-bv\",            \"--background\");\n    app.alias(\"--defaultvalue\", \"--background\");\n    app.alias(\"-r\",             \"--reference\");\n    app.alias(\"-o\",             \"--output\");\n    app.alias(\"--vi\",           \"--vectorinterpolation\");\n    try\n    {\n      app.initialize();\n    }\n    catch(const carto::user_interruption &)\n    {\n      // Exit after printing e.g. help\n      return EXIT_SUCCESS;\n    }\n    catch(const std::runtime_error &e)\n    {\n      clog << argv[0] << \": error processing command-line options: \"\n           << e.what() << endl;\n      return EXIT_USAGE_ERROR;\n    }\n\n\n    bool ok = false;\n    if(proc.points_mode)\n    {\n      ok = doPoints(proc, proc_input.filename);\n    }\n    else\n    {\n      if(proc.output.empty()) {\n        std::clog << argv[0] << \": error: --output must be provided\" << std::endl;\n        return EXIT_USAGE_ERROR;\n      }\n      ok = proc.execute(proc_input.filename);\n    }\n    if(!ok)\n      result = EXIT_FAILURE;\n\n  }\n  catch(std::exception &e) {\n    cerr << argv[ 0 ] << \": \" << e.what() << endl;\n    result = EXIT_FAILURE;\n  }\n  return result;\n}\n", "meta": {"hexsha": "c41e619fd853dbc74d6c8e6937f17bf03dbc43e6", "size": 55083, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aimsalgo/src/AimsApplyTransform/AimsApplyTransform.cc", "max_stars_repo_name": "brainvisa/aims-free", "max_stars_repo_head_hexsha": "5852c1164292cadefc97cecace022d14ab362dc4", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-09T05:34:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T00:03:15.000Z", "max_issues_repo_path": "aimsalgo/src/AimsApplyTransform/AimsApplyTransform.cc", "max_issues_repo_name": "brainvisa/aims-free", "max_issues_repo_head_hexsha": "5852c1164292cadefc97cecace022d14ab362dc4", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 72.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T14:52:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T11:22:51.000Z", "max_forks_repo_path": "aimsalgo/src/AimsApplyTransform/AimsApplyTransform.cc", "max_forks_repo_name": "brainvisa/aims-free", "max_forks_repo_head_hexsha": "5852c1164292cadefc97cecace022d14ab362dc4", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8729710656, "max_line_length": 89, "alphanum_fraction": 0.6439554854, "num_tokens": 12739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.18985857148511187}}
{"text": "/*\nCopyright (C) 2015-present The DotCpp Authors.\n\nThis file is part of .C++, a native C++ implementation of\npopular .NET class library APIs developed to facilitate\ncode reuse between C# and C++.\n\n    http://github.com/dotcpp/dotcpp (source)\n    http://dotcpp.org (documentation)\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#pragma once\n\n#include <dot/declare.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\nnamespace dot\n{\n    class String;\n    class Period;\n    class LocalTime;\n    class LocalDateTime;\n    class Object;\n\n    /// LocalDate is an immutable struct representing a date within the calendar,\n    /// with no reference to a particular time zone or time of day.\n    class DOT_CLASS LocalDate : public boost::gregorian::date\n    {\n        typedef LocalDate self;\n\n    public: // CONSTRUCTORS\n\n        /// In C\\# local date is a struct, and as all structs it has default constructor\n        /// that initializes all backing variables to 0. This means that default\n        /// constructed value corresponds to 0001-01-01. As Boost date_time library\n        /// does not accept the date 0001-01-01, we will instead use the Unix epoch\n        /// 1970-01-01 as default constructed value.\n        LocalDate();\n\n        /// Constructs an instance for the given year, month and day in the ISO calendar.\n        LocalDate(int year, int month, int day);\n\n        /// Create from Boost gregorian date.\n        LocalDate(boost::gregorian::date date);\n\n        /// Copy constructor.\n        LocalDate(const LocalDate& other);\n\n        /// Create from Object.\n        LocalDate(Object const& rhs);\n\n    public:\n        /// Adds the specified Period to the date. Friendly alternative to operator+().\n        static LocalDate add(const LocalDate& date, const Period& period);\n\n        /// Combines this LocalDate with the given LocalTime into a single LocalDateTime. Fluent alternative to operator+().\n        LocalDateTime at(const LocalTime& time) const;\n\n        /// Gets a LocalDateTime at midnight on the date represented by this local date.\n        LocalDateTime at_midnight() const;\n\n        /// Indicates whether this date is earlier, later or the same as another one.\n        int compare_to(const LocalDate& other) const;\n\n        /// Compares two LocalDate values for equality. This requires that the dates be the same, within the same calendar.\n        bool equals(const LocalDate& other) const;\n\n        /// String that represents the current Object.\n        String to_string() const;\n\n        /// Subtracts the specified date from this date, returning the result as a Period with units of years, months and days. Fluent alternative to operator-().\n        Period minus(const LocalDate& date) const;\n\n        /// Subtracts the specified Period from this date. Fluent alternative to operator-().\n        LocalDate minus(const Period& period) const;\n\n        /// Returns the next LocalDate falling on the specified iso_day_of_week.\n        /// This is a strict \"next\" - if this date on already falls on the target day of the week,\n        /// the returned value will be a week later.\n        LocalDate next(int target_day_of_week) const;\n\n        /// Adds the specified Period to this date. Fluent alternative to operator+().\n        LocalDate plus(const Period& period) const;\n\n        /// Returns a new LocalDate representing the current value with the given number of days added.\n        LocalDate plus_days(int days) const;\n\n        /// Returns a new LocalDate representing the current value with the given number of months added.\n        LocalDate plus_months(int months) const;\n\n        /// Returns a new LocalDate representing the current value with the given number of weeks added.\n        LocalDate plus_weeks(int weeks) const;\n\n        /// Returns a new LocalDate representing the current value with the given number of years added.\n        LocalDate plus_years(int years) const;\n\n        /// Returns the previous LocalDate falling on the specified iso_day_of_week.\n        /// This is a strict \"previous\" - if this date on already falls on the\n        /// target day of the week, the returned value will be a week earlier.\n        LocalDate previous(int target_day_of_week) const;\n\n        /// Subtracts one date from another, returning the result as a Period with units of years, months and days.\n        static Period subtract(const LocalDate& lhs, const LocalDate& rhs);\n\n        /// Subtracts the specified Period from the date. Friendly alternative to operator-().\n        static LocalDate subtract(const LocalDate& date, const Period& period);\n\n    public:\n        /// Combines the given LocalDate and LocalTime components into a single LocalDateTime.\n        LocalDateTime operator+(const LocalTime& time) const;\n\n        /// Adds the specified Period to the date.\n        LocalDate operator+(const Period& period) const;\n\n        /// Compares two LocalDate values for equality. This requires that the dates be the same, within the same calendar.\n        bool operator==(const LocalDate& other) const;\n\n        /// Compares two LocalDate values for inequality.\n        bool operator!=(const LocalDate& other) const;\n\n        /// Compares two dates to see if the left one is strictly later than the right one.\n        bool operator>(const LocalDate& other) const;\n\n        /// Compares two dates to see if the left one is later than or equal to the right one.\n        bool operator>=(const LocalDate& other) const;\n\n        /// Compares two dates to see if the left one is strictly earlier than the right one.\n        bool operator<(const LocalDate& other) const;\n\n        /// Compares two dates to see if the left one is earlier than or equal to the right one.\n        bool operator<=(const LocalDate& other) const;\n\n        /// Subtracts one date from another, returning the result as a Period with units of years, months and days.\n        Period operator-(const LocalDate& other) const;\n\n        /// Subtracts the specified Period from the date. This is a convenience operator over the minus(Period) method.\n        LocalDate operator-(const Period& period) const;\n    };\n}\n", "meta": {"hexsha": "fdd0044a1e49cd4a5a4b5f2b3f3ea3634f18b5cf", "size": 6647, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/src/dotcpp/dot/noda_time/local_date.hpp", "max_stars_repo_name": "datacentricorg/datacentric-cpp", "max_stars_repo_head_hexsha": "252f642b1a81c2475050d48e9564eec0a561907e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-08T01:29:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-18T19:19:00.000Z", "max_issues_repo_path": "cpp/src/dotcpp/dot/noda_time/local_date.hpp", "max_issues_repo_name": "datacentricorg/datacentric-cpp", "max_issues_repo_head_hexsha": "252f642b1a81c2475050d48e9564eec0a561907e", "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/src/dotcpp/dot/noda_time/local_date.hpp", "max_forks_repo_name": "datacentricorg/datacentric-cpp", "max_forks_repo_head_hexsha": "252f642b1a81c2475050d48e9564eec0a561907e", "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.4444444444, "max_line_length": 162, "alphanum_fraction": 0.6958026177, "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.18985857148511184}}
{"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_tool.hh\"\n#include \"random.hh\"\n\n#include <boost/python.hpp>\n\n#include \"../blockmodel/graph_blockmodel.hh\"\n#define BASE_STATE_params BLOCK_STATE_params\n#include \"graph_blockmodel_measured.hh\"\n#include \"graph_blockmodel_uncertain_mcmc.hh\"\n#include \"../support/graph_state.hh\"\n#include \"../loops/mcmc_loop.hh\"\n\nusing namespace boost;\nusing namespace graph_tool;\n\nGEN_DISPATCH(block_state, BlockState, BLOCK_STATE_params)\n\ntemplate <class BaseState>\nGEN_DISPATCH(measured_state, Measured<BaseState>::template MeasuredState,\n             MEASURED_STATE_params)\n\ntemplate <class State>\nGEN_DISPATCH(mcmc_uncertain_state, MCMC<State>::template MCMCUncertainState,\n             MCMC_UNCERTAIN_STATE_params(State))\n\npython::object mcmc_measured_sweep(python::object omcmc_state,\n                                   python::object omeasured_state,\n                                   rng_t& rng)\n{\n    python::object ret;\n    auto dispatch = [&](auto* block_state)\n    {\n        typedef typename std::remove_pointer<decltype(block_state)>::type\n            state_t;\n\n        measured_state<state_t>::dispatch\n            (omeasured_state,\n             [&](auto& ls)\n             {\n                 typedef typename std::remove_reference<decltype(ls)>::type\n                     measured_state_t;\n\n                 mcmc_uncertain_state<measured_state_t>::make_dispatch\n                     (omcmc_state,\n                      [&](auto& s)\n                      {\n                          auto ret_ = mcmc_sweep(s, rng);\n                          ret = tuple_apply([&](auto&... args){ return python::make_tuple(args...); }, ret_);\n                      });\n             },\n             false);\n    };\n    block_state::dispatch(dispatch);\n    return ret;\n}\n\nvoid export_measured_mcmc()\n{\n    using namespace boost::python;\n    def(\"mcmc_measured_sweep\", &mcmc_measured_sweep);\n}\n", "meta": {"hexsha": "f6a3b10ba9af4940cf00f151815e62875c896b59", "size": 2670, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/inference/uncertain/graph_blockmodel_measured_mcmc.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/inference/uncertain/graph_blockmodel_measured_mcmc.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/inference/uncertain/graph_blockmodel_measured_mcmc.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": 33.7974683544, "max_line_length": 109, "alphanum_fraction": 0.6520599251, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.18983085814982095}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\nnamespace bold\n{\n  class BulkReadTable;\n\n  // http://support.robotis.com/en/product/darwin-op/references/reference/hardware_specifications/electronics/sub_controller_(cm-730).htm\n\n  // TODO rename as CM730State\n\n  class CM730Snapshot\n  {\n  public:\n    bool isPowered;\n    /// Red LED\n    bool isLed2On;\n    /// Blue LED\n    bool isLed3On;\n    /// Green LED\n    bool isLed4On;\n    Eigen::Vector3d eyeColor;\n    Eigen::Vector3d foreheadColor;\n    bool isModeButtonPressed;\n    bool isStartButtonPressed;\n    /// The converted gyroscope output, in degrees per second.\n    Eigen::Vector3d gyro;\n    /// The converted accelerometer output, in gs.\n    Eigen::Vector3d acc;\n    float voltage;\n    /// Raw raw value of the gyroscope, in range [0,1023] corresponding to [-1600,1600] degrees per second.\n    Eigen::Vector3i gyroRaw;\n    /// Raw raw value of the accelerometer, in range [0,1023] corresponding to [-4,4] g.\n    Eigen::Vector3i accRaw;\n\n    CM730Snapshot() = default;\n\n    CM730Snapshot(BulkReadTable const& data);\n\n    /** Returns the gyroscope value, in hardware units, but balanced around the midpoint.\n     *\n     * Values may be positive or negative.\n     */\n    Eigen::Vector3i getBalancedGyroValue() const\n    {\n      return this->gyroRaw - Eigen::Vector3i(512, 512, 512);\n    }\n  };\n\n  class StaticCM730State\n  {\n  public:\n    unsigned short modelNumber;\n    unsigned char firmwareVersion;\n    unsigned char dynamixelId;\n    unsigned int baudBPS;\n    unsigned int returnDelayTimeMicroSeconds;\n\n    /** Controls when a status packet is returned in response to an instruction.\n    *\n    * 0 - only for PING command\n    * 1 - only for READ command\n    * 2 - for all commands\n    *\n    * Note that a status packet is never returned for broadcast instructions.\n    */\n    unsigned char statusRetLevel;\n\n    // skip dynamic addresses in the table -- they are captured in CM730Snapshot\n\n    StaticCM730State() = default;\n\n    StaticCM730State(BulkReadTable const& data);\n  };\n}\n", "meta": {"hexsha": "2ae269c86b8cee1001c7210a1ddfe3e54d903a09", "size": 2020, "ext": "hh", "lang": "C++", "max_stars_repo_path": "CM730Snapshot/cm730snapshot.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": "CM730Snapshot/cm730snapshot.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": "CM730Snapshot/cm730snapshot.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": 26.2337662338, "max_line_length": 137, "alphanum_fraction": 0.6856435644, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.35220178884745906, "lm_q1q2_score": 0.18983085448496712}}
{"text": "#include <cnoid/SimpleController>\n#include <cnoid/SharedJoystick>\n#include <boost/format.hpp>\n\nusing namespace std;\nusing namespace cnoid;\nusing boost::format;\n\nnamespace {\n\nconst double STICK_THRESH = 0.1;\n\n}\n\nclass AizuSpiderController : public SimpleController\n{\n    Body* body;\n    double dt;\n\n    Link::ActuationMode mainActuationMode;\n\n    vector<Link*> tracks;\n    Link::ActuationMode trackActuationMode;\n    double trackVelocityRatio;\n    double kd_mainTrack;\n    double kd_subTrack;\n    vector<double> qprev_track;\n\n    enum { L_TRACK, R_TRACK, FL_SUB_TRACK, FR_SUB_TRACK, BL_SUB_TRACK, BR_SUB_TRACK, NUM_TRACKS };\n\n    struct JointInfo {\n        Link* joint;\n        double qref;\n        double qold;\n        double kp;\n        double kd;\n    };\n    \n    vector<JointInfo> jointInfos;\n\n    struct JointSpec {\n        string name;\n        double kp_torque;\n        double kd_torque;\n        double kp_velocity;\n    };\n\n    enum { FR_FLIPPER, FL_FLIPPER, BR_FLIPPER, BL_FLIPPER, NUM_FLIPPERS };\n\n    SharedJoystickPtr joystick;\n    int targetMode;\n\npublic:\n    virtual bool initialize(SimpleControllerIO* io) override;\n    bool initializeTracks(SimpleControllerIO* io);\n    bool initializeTracks(SimpleControllerIO* io, vector<string>& names);\n    bool initializeFlipperJoints(SimpleControllerIO* io);\n    bool initializeJoints(SimpleControllerIO* io, vector<JointSpec>& specs);\n    virtual bool control() override;\n    void controlTracks();\n    void setTrackTorque(int id, double dq_target, double kd);\n    void updateFlipperTargetPositions();\n    void controlJointsWithTorque();\n    void controlJointsWithVelocity();\n    void controlJointsWithPosition();\n};\n\n\nbool AizuSpiderController::initialize(SimpleControllerIO* io)\n{\n    body = io->body();\n    dt = io->timeStep();\n\n    io->os() << \"The actuation mode of \" << io->controllerName() << \" is \";\n    string option = io->optionString();\n    if(option == \"velocity\"){\n        mainActuationMode = Link::ActuationMode::JOINT_VELOCITY;\n        io->os() << \"JOINT_VELOCITY\";\n    } else if(option  == \"position\"){\n        mainActuationMode = Link::ActuationMode::JOINT_DISPLACEMENT;\n        io->os() << \"JOINT_DISPLACEMENT\";\n    } else {\n        mainActuationMode = Link::ActuationMode::JOINT_EFFORT;\n        io->os() << \"JOINT_EFFORT\";\n    }\n    io->os() << \".\" << endl;\n\n    if(!initializeTracks(io)){\n        return false;\n    }\n\n    if(!initializeFlipperJoints(io)){\n        return false;\n    }\n\n    joystick = io->getOrCreateSharedObject<SharedJoystick>(\"joystick\");\n    targetMode = joystick->addMode();\n\n    return true;\n}\n\n\nbool AizuSpiderController::initializeTracks(SimpleControllerIO* io)\n{\n    tracks.clear();\n    qprev_track.clear();\n    \n    vector<string> trackNames = {\n        \"L_TRACK\", \"R_TRACK\", \"FL_SUB_TRACK\", \"FR_SUB_TRACK\", \"BL_SUB_TRACK\", \"BR_SUB_TRACK\" };\n\n    vector<string> wheelNames = {\n        \"L_TRACK_WHEEL1\", \"R_TRACK_WHEEL1\",\n        \"FL_SUB_TRACK_WHEEL1\", \"FR_SUB_TRACK_WHEEL1\", \"BL_SUB_TRACK_WHEEL1\", \"BR_SUB_TRACK_WHEEL1\" };\n    \n    bool result;\n    \n    if(body->link(wheelNames[0])){\n        if(mainActuationMode == Link::JOINT_TORQUE){\n            trackActuationMode = Link::JOINT_TORQUE;\n            trackVelocityRatio = 0.5;\n            kd_mainTrack = 8.0;\n            kd_subTrack = 1.5;\n        } else {\n            trackActuationMode = Link::JOINT_VELOCITY;\n            trackVelocityRatio = 4.0;\n        }\n        result = initializeTracks(io, wheelNames);\n    } else {\n        trackActuationMode = Link::JOINT_SURFACE_VELOCITY;\n        trackVelocityRatio = 0.5;\n        result = initializeTracks(io, trackNames);\n    }\n\n    return result;\n}\n\n\nbool AizuSpiderController::initializeTracks(SimpleControllerIO* io, vector<string>& names)\n{\n    for(auto& name : names){\n        auto link = body->link(name);\n        if(!link){\n            io->os() << format(\"%1% of %2% is not found\") % name % body->name() << endl;\n            return false;\n        }\n        link->setActuationMode(trackActuationMode);\n        io->enableOutput(link);\n        tracks.push_back(link);\n        qprev_track.push_back(link->q());\n    }\n    return true;\n}\n\n\nbool AizuSpiderController::initializeFlipperJoints(SimpleControllerIO* io)\n{\n    jointInfos.clear();\n    \n    vector<JointSpec> specs(NUM_FLIPPERS);\n\n    const double FLIPPER_P_GAIN_TORQUE = 800.0;\n    const double FLIPPER_D_GAIN_TORQUE = 20.0;\n    const double FLIPPER_P_GAIN_VELOCITY = 0.5;\n    \n    specs[FR_FLIPPER] = { \"FR_FLIPPER\", FLIPPER_P_GAIN_TORQUE, FLIPPER_D_GAIN_TORQUE, FLIPPER_P_GAIN_VELOCITY };\n    specs[FL_FLIPPER] = { \"FL_FLIPPER\", FLIPPER_P_GAIN_TORQUE, FLIPPER_D_GAIN_TORQUE, FLIPPER_P_GAIN_VELOCITY };\n    specs[BR_FLIPPER] = { \"BR_FLIPPER\", FLIPPER_P_GAIN_TORQUE, FLIPPER_D_GAIN_TORQUE, FLIPPER_P_GAIN_VELOCITY };\n    specs[BL_FLIPPER] = { \"BL_FLIPPER\", FLIPPER_P_GAIN_TORQUE, FLIPPER_D_GAIN_TORQUE, FLIPPER_P_GAIN_VELOCITY };\n\n    return initializeJoints(io, specs);\n}\n\n\nbool AizuSpiderController::initializeJoints(SimpleControllerIO* io, vector<JointSpec>& specs)\n{\n    for(auto& spec : specs){\n        auto joint = body->link(spec.name);\n        if(!joint){\n            io->os() << format(\"%1% of %2% is not found\") % spec.name % body->name() << endl;\n            return false;\n        }\n        joint->setActuationMode(mainActuationMode);\n        io->enableIO(joint);\n\n        JointInfo info;\n        info.joint = joint;\n        info.qref = info.qold = joint->q();\n\n        if(mainActuationMode == Link::JOINT_VELOCITY){\n            info.kp = spec.kp_velocity;\n        } else if(mainActuationMode == Link::JOINT_TORQUE){\n            info.kp = spec.kp_torque;\n            info.kd = spec.kd_torque;\n        }\n        \n        jointInfos.push_back(info);\n    }\n\n    return true;\n}\n\n\nbool AizuSpiderController::control()\n{\n    joystick->updateState(targetMode);\n\n    controlTracks();\n\n    updateFlipperTargetPositions();\n\n    switch(mainActuationMode){\n    case Link::JOINT_TORQUE:\n        controlJointsWithTorque();\n        break;\n    case Link::JOINT_VELOCITY:\n        controlJointsWithVelocity();\n        break;\n    case Link::JOINT_ANGLE:\n        controlJointsWithPosition();\n        break;\n    default:\n        break;\n    }\n\n    return true;\n}\n\n\nvoid AizuSpiderController::controlTracks()\n{\n    double hpos =\n        joystick->getPosition(targetMode, Joystick::L_STICK_H_AXIS, STICK_THRESH) +\n        0.8 * joystick->getPosition(Joystick::DIRECTIONAL_PAD_H_AXIS);\n\n    double vpos = -(\n        joystick->getPosition(targetMode, Joystick::L_STICK_V_AXIS, STICK_THRESH) +\n        0.8 * joystick->getPosition(Joystick::DIRECTIONAL_PAD_V_AXIS));\n    \n    double dq_L = trackVelocityRatio * (vpos + 0.4 * hpos);\n    double dq_R = trackVelocityRatio * (vpos - 0.4 * hpos);\n\n    switch(trackActuationMode){\n\n    case Link::JOINT_VELOCITY:\n    case Link::JOINT_SURFACE_VELOCITY:\n        for(int i=0; i < 3; ++i){\n            tracks[i*2  ]->dq_target() = dq_L;\n            tracks[i*2+1]->dq_target() = dq_R;\n        }\n        break;\n\n    case Link::JOINT_TORQUE:\n        setTrackTorque(L_TRACK, dq_L, kd_mainTrack);\n        setTrackTorque(R_TRACK, dq_R, kd_mainTrack);\n        setTrackTorque(FL_SUB_TRACK, dq_L, kd_subTrack);\n        setTrackTorque(FR_SUB_TRACK, dq_R, kd_subTrack);\n        setTrackTorque(BL_SUB_TRACK, dq_L, kd_subTrack);\n        setTrackTorque(BR_SUB_TRACK, dq_R, kd_subTrack);\n        break;\n\n    default:\n        break;\n    }\n}\n\n\nvoid AizuSpiderController::setTrackTorque(int id, double dq_target, double kd)\n{\n    Link* axis = tracks[id];\n    double dq_current = (axis->q() - qprev_track[id]) / dt;\n    axis->u() = kd * (dq_target - dq_current);\n    qprev_track[id] = axis->q();\n}\n\n\nvoid AizuSpiderController::updateFlipperTargetPositions()\n{\n    static const double FLIPPER_GAIN = 0.5;\n\n    // Arrange all the flippers to the same position\n    if(joystick->getButtonState(targetMode, Joystick::R_STICK_BUTTON)){\n        double qa = 0.0;\n        for(int i=0; i < NUM_FLIPPERS; ++i){\n            qa += jointInfos[i].qref;\n        }\n        qa /= NUM_FLIPPERS;\n        double dqmax = dt * 0.5;\n        for(int i=0; i < NUM_FLIPPERS; ++i){\n            double dq = qa - jointInfos[i].qref;\n            if(dq > dqmax){\n                dq = dqmax;\n            } else if(dq < -dqmax){\n                dq = -dqmax;\n            }\n            jointInfos[i].qref += dq;\n        }\n    } else {\n        double pos = joystick->getPosition(targetMode, Joystick::R_STICK_V_AXIS, STICK_THRESH);\n        double dq = dt * FLIPPER_GAIN * pos;\n        bool FL = joystick->getPosition(targetMode, Joystick::L_TRIGGER_AXIS, STICK_THRESH) > 0.0;\n        bool FR = joystick->getPosition(targetMode, Joystick::R_TRIGGER_AXIS, STICK_THRESH) > 0.0;\n        bool BL = joystick->getButtonState(targetMode, Joystick::L_BUTTON);\n        bool BR = joystick->getButtonState(targetMode, Joystick::R_BUTTON);\n        \n        if(!FL && !FR && !BL && !BR){\n            // Synchronize mode\n            jointInfos[FR_FLIPPER].qref += dq;\n            jointInfos[FL_FLIPPER].qref += dq;\n            jointInfos[BR_FLIPPER].qref += dq;\n            jointInfos[BL_FLIPPER].qref += dq;\n        } else {\n            if(FL){\n                jointInfos[FL_FLIPPER].qref += dq;\n            }\n            if(FR){\n                jointInfos[FR_FLIPPER].qref += dq;\n            }\n            if(BL){\n                jointInfos[BL_FLIPPER].qref += dq;\n            }\n            if(BR){\n                jointInfos[BR_FLIPPER].qref += dq;\n            }\n        }\n    }\n}\n\n\nvoid AizuSpiderController::controlJointsWithTorque()\n{\n    for(auto& info : jointInfos){\n        auto joint = info.joint;\n        double q = joint->q();\n        double dq = (q - info.qold) / dt;\n        joint->u() = info.kp * (info.qref - q) + info.kd * (0.0 - dq);\n        info.qold = q;\n    }\n}\n\n\nvoid AizuSpiderController::controlJointsWithVelocity()\n{\n    for(auto& info : jointInfos){\n        auto joint = info.joint;\n        joint->dq_target() = info.kp * (info.qref - joint->q()) / dt;\n    }\n}\n\n\nvoid AizuSpiderController::controlJointsWithPosition()\n{\n    for(auto& info : jointInfos){\n        info.joint->q_target() = info.qref;\n    }\n}\n\n\nCNOID_IMPLEMENT_SIMPLE_CONTROLLER_FACTORY(AizuSpiderController)\n", "meta": {"hexsha": "8c00092045dbaba6eb2f3a6805dcbefc5e1dee12", "size": 10205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sample/SimpleController/AizuSpiderController.cpp", "max_stars_repo_name": "jun0/choreonoid", "max_stars_repo_head_hexsha": "37167e52bfa054088272e1924d2062604104ac08", "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": "sample/SimpleController/AizuSpiderController.cpp", "max_issues_repo_name": "jun0/choreonoid", "max_issues_repo_head_hexsha": "37167e52bfa054088272e1924d2062604104ac08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample/SimpleController/AizuSpiderController.cpp", "max_forks_repo_name": "jun0/choreonoid", "max_forks_repo_head_hexsha": "37167e52bfa054088272e1924d2062604104ac08", "max_forks_repo_licenses": ["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.426183844, "max_line_length": 112, "alphanum_fraction": 0.6226359628, "num_tokens": 2731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18983085082011333}}
{"text": "/*\n * Copyright 2020 California  Institute  of Technology (\u201cCaltech\u201d)\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 <x/vio/range_update.h>\n#include <x/vio/tools.h>\n#include <x/ekf/state.h>\n#include <boost/math/distributions.hpp>\n\nusing namespace x;\nusing namespace Eigen;\n\nRangeUpdate::RangeUpdate(const x::RangeMeasurement& range_meas,\n                         const std::vector<int>& tr_feat_ids,\n                         const x::AttitudeList& quats,\n                         const x::TranslationList& poss,\n                         const MatrixXd& feature_states,\n                         const std::vector<int>& anchor_idxs,\n                         const MatrixXd& cov_s,\n                         const int n_poses_max,\n                         const double sigma_range)\n{\n  // Initialize Kalman update matrices\n  const size_t cols = cov_s.cols();\n  jac_ = MatrixXd::Zero(1, cols);\n  cov_m_diag_ = VectorXd::Ones(1);\n  res_ = MatrixXd::Zero(1, 1);\n  \n  // Compute residual, Jacobian and covariance block\n  processRangedFacet(range_meas,\n                     tr_feat_ids,\n                     quats,\n                     poss,\n                     feature_states,\n                     anchor_idxs,\n                     cov_s,\n                     n_poses_max,\n                     sigma_range);\n  /*processRangedFeature(range_meas,\n                         quats,\n                         poss,\n                         feature_states,\n                         P,\n                         n_poses_max,\n                         sigma_range,\n                         0);*/\n}\n\nvoid RangeUpdate::processRangedFacet(const x::RangeMeasurement& range_meas,\n                                     const std::vector<int>& tr_feat_ids,\n                                     const x::AttitudeList& C_q_G,\n                                     const x::TranslationList& G_p_C,\n                                     const MatrixXd& feature_states,\n                                     const std::vector<int>& anchor_idxs,\n                                     const MatrixXd& P,\n                                     const int n_poses_max,\n                                     const double sigma_range)\n{\n  /********************************************************\n   * Cartesian world coordinates of the triangle features *\n   ********************************************************/\n \n  // Array storing the  of the three features\n  std::array<Vector3d, 3> G_p_fj; // world position\n  std::array<Vector3d, 3> G_p_Ca; // anchor position\n  std::array<x::Quaternion, 3> Ca_q_G; // anchor quaternion\n  std::array<int, 3> anchor_idx; // anchor quaternion\n  std::array<double, 3> alpha; // Normalized undistored image coordinates X\n  std::array<double, 3> beta; // Normalized undistored image coordinates Y\n  std::array<double, 3> rho; // Inverse depth\n\n  for(unsigned int j=0; j<3; j++)\n  {\n    // Inverse-depth parameters in last observation frame\n    alpha[j] = feature_states(tr_feat_ids[j] * 3, 0);\n    beta[j] = feature_states(tr_feat_ids[j] * 3 + 1, 0);\n    rho[j] = feature_states(tr_feat_ids[j] * 3 + 2, 0);\n\n    // Anchor pose\n    anchor_idx[j] = anchor_idxs[tr_feat_ids[j]];\n    Ca_q_G[j].x() = C_q_G[anchor_idx[j]].ax;\n    Ca_q_G[j].y() = C_q_G[anchor_idx[j]].ay;\n    Ca_q_G[j].z() = C_q_G[anchor_idx[j]].az;\n    Ca_q_G[j].w() = C_q_G[anchor_idx[j]].aw;\n\n    const Vector3d anchor_pos(G_p_C[anchor_idx[j]].tx, G_p_C[anchor_idx[j]].ty, G_p_C[anchor_idx[j]].tz);\n    G_p_Ca[j] = anchor_pos;\n\n    // Coordinate of feature in global frame\n    G_p_fj[j] = 1 / (rho[j])*Ca_q_G[j].normalized().toRotationMatrix() * Vector3d(alpha[j], beta[j], 1) + G_p_Ca[j];\n  }\n\n  /***********************\n   * Current camera pose *\n   ***********************/\n  \n  // Orientation\n  x::Attitude Cn_q_G(C_q_G.back());\n  x::Quatern attitude_to_quaternion;\n  x::Quaternion Ci_q_G  = attitude_to_quaternion(Cn_q_G);\n\n  // Position\n  x::Translation G_p_Cn(G_p_C.back());\n  Vector3d G_p_Ci(G_p_Cn.tx, G_p_Cn.ty, G_p_Cn.tz);\n\n  /************\n   * Residual *\n   ************/\n  \n  // Compute normal vector to the triangle plane in world coordinates\n  const Vector3d G_n = (G_p_fj[0] - G_p_fj[1]).cross(G_p_fj[2] - G_p_fj[1]);\n\n  // Undistorted normalized homogeneous 2D coordinates of the LRF impact point on the ground\n  const Vector3d lrf_img_pt_nh(range_meas.img_pt_n.getX(), range_meas.img_pt_n.getY(), 1.0);\n\n  // Measurement prediction\n  const double a = (G_p_fj[1] - G_p_Ci).dot(G_n);\n  const double b = lrf_img_pt_nh.dot(Ci_q_G.normalized().toRotationMatrix().transpose() * G_n);\n  double range_hat = a/b;\n\n  // Measurement\n  const double range(range_meas.range);\n\n  // Actual residual\n  MatrixXd res_j(MatrixXd::Zero(1, 1));\n  res_j(0, 0) = range - range_hat;\n\n  /*******************************\n   * Measurement Jacobian matrix *\n   *******************************/\n\n  const size_t cols = P.cols();\n  MatrixXd h_j(MatrixXd::Zero(1, cols));\n  \n  // Camera Position\n  const RangeJacobian J_pc = - 1.0 / b * G_n.transpose();\n\n  // Camera attitude\n  const RangeJacobian J_qc = a / std::pow(b, 2.0)\n    * G_n.transpose() * Ci_q_G.normalized().toRotationMatrix() \n    * x::Skew(lrf_img_pt_nh(0), lrf_img_pt_nh(1), lrf_img_pt_nh(2)).matrix;\n  \n  // Position of the LRF target point in world frame\n  const Vector3d G_p_r = a / b * Ci_q_G.normalized().toRotationMatrix() * lrf_img_pt_nh + G_p_Ci;\n \n  // Barycenter\n  const Vector3d G_p_bary = 1.0/3.0 * (G_p_fj[0]+G_p_fj[1]+G_p_fj[2]);\n  /* Triangle feature 1 */\n  // Jacobian wrt cartesian feature coordinates\n  const RangeJacobian J_f0 = 1.0 / b * (1.0/3.0 * G_n + (G_p_fj[2] - G_p_fj[1]).cross(G_p_bary - G_p_r)).transpose();\n  // Anchor position\n  const RangeJacobian J_pc0 = J_f0;\n  // Anchor attitude \n  const RangeJacobian J_qc0 = - 1.0 / rho[0] * J_f0 * Ca_q_G[0].normalized().toRotationMatrix()\n    * x::Skew(alpha[0], beta[0], 1.0).matrix;\n  // Inverse-depth feature coordinates\n  MatrixXd mat(MatrixXd::Identity(3, 3));\n  mat(0, 2) = - alpha[0] / rho[0];\n  mat(1, 2) = - beta[0] / rho[0];\n  mat(2, 2) =  - 1 / rho[0];\n  RangeJacobian J_fi0 = 1 / rho[0] * J_f0 * Ca_q_G[0].normalized().toRotationMatrix() * mat;\n\n  /* Triangle feature 2 */\n  // Jacobian wrt cartesian feature coordinates\n  const RangeJacobian J_f1 = 1.0 / b * (1.0/3.0 * G_n + (G_p_fj[0] - G_p_fj[2]).cross(G_p_bary - G_p_r)).transpose();\n  // Anchor position\n  const RangeJacobian J_pc1 = J_f1;\n  // Anchor attitude \n  const RangeJacobian J_qc1 = - 1.0 / rho[1] * J_f1 * Ca_q_G[1].normalized().toRotationMatrix()\n    * x::Skew(alpha[1], beta[1], 1.0).matrix;\n  // Inverse-depth feature coordinates\n  mat = MatrixXd::Identity(3, 3);\n  mat(0, 2) = - alpha[1] / rho[1];\n  mat(1, 2) = - beta[1] / rho[1];\n  mat(2, 2) = - 1 / rho[1];\n  RangeJacobian J_fi1 = 1 / rho[1] * J_f1 * Ca_q_G[1].normalized().toRotationMatrix() * mat;\n\n  // Triangle feature 3\n  // Jacobian wrt cartesian feature coordinates\n  const RangeJacobian J_f2 = 1.0 / b * (1.0/3.0 * G_n + (G_p_fj[1] - G_p_fj[0]).cross(G_p_bary - G_p_r)).transpose();\n  // Anchor position\n  const RangeJacobian J_pc2 = J_f2;\n  // Anchor attitude \n  const RangeJacobian J_qc2 = - 1.0 / rho[2] * J_f2 * Ca_q_G[2].normalized().toRotationMatrix()\n    * x::Skew(alpha[2], beta[2], 1.0).matrix;\n  // Inverse-depth feature coordinates\n  mat = MatrixXd::Identity(3, 3);\n  mat(0, 2) = - alpha[2] / rho[2];\n  mat(1, 2) = - beta[2] / rho[2];\n  mat(2, 2) = - 1 / rho[2];\n  RangeJacobian J_fi2 = 1 / rho[2] * J_f2 * Ca_q_G[2].normalized().toRotationMatrix() * mat;\n\n  // Update stacked Jacobian matrices associated to the current feature\n  const unsigned int row = 0;\n  const unsigned int pos = C_q_G.size()- 1;\n  unsigned int col = pos * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_pc;\n\n  col += n_poses_max * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_qc;\n\n  col = anchor_idx[0] * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) =\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) + J_pc0;\n  col += n_poses_max * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = \n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) + J_qc0;\n  col = (n_poses_max * 2 + tr_feat_ids[0]) * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_fi0;\n \n  col = anchor_idx[1] * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) =\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) + J_pc1; \n  col += n_poses_max * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = \n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) + J_qc1;\n  col = (n_poses_max * 2 + tr_feat_ids[1]) * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_fi1;\n\n  col = anchor_idx[2] * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) =\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) + J_pc2;\n  col += n_poses_max * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = \n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) + J_qc2;\n  col = (n_poses_max * 2 + tr_feat_ids[2]) * kJacCols;\n  h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_fi2;\n\n  //==========================================================================\n  // Outlier rejection\n  //==========================================================================\n  VectorXd r_j(1);\n  const double var_range = sigma_range * sigma_range;\n  r_j << var_range;\n  MatrixXd S_inv = (h_j * P * h_j.transpose() + r_j).inverse();\n  MatrixXd gamma = res_j.transpose() * S_inv * res_j;\n  boost::math::chi_squared_distribution<> my_chisqr(1);\n  double chi = quantile(my_chisqr, 0.9);  // 95-th percentile\n\n  if (gamma(0, 0) < chi)  // Inlier\n  {\n    jac_.block(0,               // startRow\n             0,               // startCol\n             1,               // numRows\n             cols) = h_j;  // numCols\n\n    // Residual vector\n    res_.block(0, 0, 1, 1) = res_j;\n\n    // Measurement covariance matrix\n    cov_m_diag_ = r_j;\n  }\n}\n\nvoid RangeUpdate::processRangedFeature(const x::RangeMeasurement& range_meas,\n                                       const x::AttitudeList& C_q_G,\n                                       const x::TranslationList& G_p_C,\n                                       const MatrixXd& feature_states,\n                                       const std::vector<int>& anchor_idxs,\n                                       const MatrixXd& P,\n                                       const int n_poses_max,\n                                       const double sigma_range,\n                                       const size_t& j)\n{\n  const size_t cols = P.cols();\n  MatrixXd h_j(MatrixXd::Zero(1, cols));\n  MatrixXd res_j(MatrixXd::Zero(1, 1));\n\n  //==========================================================================\n  // Feature information\n  //==========================================================================\n  // A-priori inverse-depth parameters in last observation frame\n  double alpha = feature_states(j * 3, 0);\n  double beta = feature_states(j * 3 + 1, 0);\n  double rho = feature_states(j * 3 + 2, 0);\n  \n  // Anchor pose\n  unsigned int anchor_idx = anchor_idxs[j];\n  x::Quaternion Ca_q_G;\n  Ca_q_G.x() = C_q_G[anchor_idx].ax;\n  Ca_q_G.y() = C_q_G[anchor_idx].ay;\n  Ca_q_G.z() = C_q_G[anchor_idx].az;\n  Ca_q_G.w() = C_q_G[anchor_idx].aw;\n\n  Vector3d G_p_Ca(G_p_C[anchor_idx].tx, G_p_C[anchor_idx].ty, G_p_C[anchor_idx].tz);\n\n  // Coordinate of feature in global frame\n  Vector3d G_p_fj = 1 / (rho)*Ca_q_G.normalized().toRotationMatrix() * Vector3d(alpha, beta, 1) + G_p_Ca;\n\n  // FOR LAST FEATURE OBSERVATION\n  x::Translation G_p_Cn(G_p_C.back());\n  x::Attitude Cn_q_G(C_q_G.back());\n\n  x::Quatern attitude_to_quaternion;\n  Quaterniond Ci_q_G_ = attitude_to_quaternion(Cn_q_G);\n  Vector3d G_p_Ci_(G_p_Cn.tx, G_p_Cn.ty, G_p_Cn.tz);\n\n  // Feature position expressed in camera frame.\n  Vector3d Ci_p_fj;\n  Ci_p_fj << Ci_q_G_.normalized().toRotationMatrix().transpose() * (G_p_fj - G_p_Ci_);\n\n  //==========\n  // Residual\n  //==========\n  double range(range_meas.range);\n  double range_hat(Ci_p_fj(2));\n  res_j(0, 0) = range - range_hat;\n\n  //============================\n  // Measurement Jacobian matrix\n  //============================\n  const unsigned int pos = C_q_G.size() - 1;\n  if (anchor_idx == pos)  // Handle special case\n  {\n    // Inverse-depth feature coordinates jacobian\n    RangeJacobian mat(MatrixXd::Zero(1, 3));\n    mat(0, 2) = -1 / std::pow(rho, 2);\n\n    // Update stacked Jacobian matrices associated to the current feature\n    unsigned int row = 0;\n    unsigned int col = (n_poses_max * 2 + j) * kJacCols;\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = mat;\n  }\n  else\n  {\n    // Set Jacobian of pose for i'th measurement of feature j (eq.22, 23)\n    RangeJacobian J_i(MatrixXd::Zero(1, 3));\n    J_i(0, 2) = 1.0;\n\n    // Attitude\n    Vector3d skew_vector = Ci_q_G_.normalized().toRotationMatrix().transpose() * (G_p_fj - G_p_Ci_);\n    RangeJacobian J_attitude = J_i * x::Skew(skew_vector(0), skew_vector(1), skew_vector(2)).matrix;\n\n    // Position\n    RangeJacobian J_position = -J_i * Ci_q_G_.normalized().toRotationMatrix().transpose();\n\n    // Anchor attitude\n    RangeJacobian J_anchor_att = -1 / rho * J_i * Ci_q_G_.normalized().toRotationMatrix().transpose() *\n                                         Ca_q_G.normalized().toRotationMatrix() * x::Skew(alpha, beta, 1).matrix;\n\n    // Anchor position\n    RangeJacobian J_anchor_pos = -J_position;\n\n    // Inverse-depth feature coordinates\n    MatrixXd mat(MatrixXd::Identity(3, 3));\n    mat(0, 2) = -alpha / rho;\n    mat(1, 2) = -beta / rho;\n    mat(2, 2) = -1 / rho;\n    RangeJacobian Hf_j1 = 1 / rho * J_i * Ci_q_G_.normalized().toRotationMatrix().transpose() *\n                                  Ca_q_G.normalized().toRotationMatrix() * mat;\n\n    // Update stacked Jacobian matrices associated to the current feature\n    unsigned int row = 0;\n    const unsigned int pos = C_q_G.size() - 1;\n    unsigned int col = pos * kJacCols;\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_position;\n\n    col += n_poses_max * kJacCols;\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_attitude;\n\n    col = anchor_idx * kJacCols;\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_anchor_pos;\n\n    col += n_poses_max * kJacCols;\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = J_anchor_att;\n\n    col = (n_poses_max * 2 + j) * kJacCols;\n    h_j.block<1, kJacCols>(row, kSizeCoreErr + col) = Hf_j1;\n  }\n\n  //==========================================================================\n  // Outlier rejection\n  //==========================================================================\n  VectorXd r_j(1);\n  const double var_range = sigma_range * sigma_range;\n  r_j << var_range;\n  // MatrixXd S_inv = (h_j * P * h_j.transpose() + R_j).inverse();\n  // MatrixXd gamma = res_j.transpose() * S_inv * res_j;\n  // chi_squared_distribution<> my_chisqr(2 * features[j].size());\n  // double chi = quantile(my_chisqr, 0.9);  // 95-th percentile\n\n  if (true)  // gamma(0, 0) < chi)  // Inlier\n  {\n    jac_.block(0,               // startRow\n             0,               // startCol\n             1,               // numRows\n             cols) = h_j;  // numCols\n\n    // Residual vector\n    res_.block(0, 0, 1, 1) = res_j;\n\n    // Measurement covariance matrix\n    cov_m_diag_ = r_j;\n  }\n}\n", "meta": {"hexsha": "48560c05803e9c0bc23800fac592943fc52645bc", "size": 15798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/x/vio/range_update.cpp", "max_stars_repo_name": "jpl-x/x_events", "max_stars_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T18:01:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:44:43.000Z", "max_issues_repo_path": "src/x/vio/range_update.cpp", "max_issues_repo_name": "jpl-x/x_events", "max_issues_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-11T15:53:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T15:53:17.000Z", "max_forks_repo_path": "src/x/vio/range_update.cpp", "max_forks_repo_name": "jpl-x/x_events", "max_forks_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T00:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:44:45.000Z", "avg_line_length": 38.7205882353, "max_line_length": 117, "alphanum_fraction": 0.5809596151, "num_tokens": 4674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18983084715525958}}
{"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#ifndef METRO_LIKELIHOOD_SMOOTH_FUNCTION_HPP\n#define METRO_LIKELIHOOD_SMOOTH_FUNCTION_HPP\n\n#include <memory>\n#include <boost/noncopyable.hpp>\n#include <Eigen/Core>\n#include \"metro/DataSubset.hpp\"\n\nnamespace metro {\n\t// This class represents a smooth function, i.e. a function that is\n\t// twice differentiable.\n\t// SmoothFunctions are intended to be stateful - they are properly thought\n\t// of as a function evaluated at a specific point.  This design choice\n\t// was made because it is typically the case that a large amount of computation can be\n\t// shared between derivatives.\n\t\n\t// a great deal of comp\n\t// The intentino \n\t// This choice means that the accessor functions, named \"get_value[...]\",\n\t// are const and return references, while the \n\tstruct SmoothFunction: public boost::noncopyable {\n\tpublic:\n\t\ttypedef std::unique_ptr< SmoothFunction > UniquePtr ;\n\t\ttypedef double Scalar ;\n\t\ttypedef Eigen::VectorXd Vector ;\n\t\ttypedef Eigen::MatrixXd Matrix ;\n\tpublic:\n\t\tvirtual ~SmoothFunction() {}\n\t\tvirtual int number_of_parameters() const = 0 ;\n\t\tvirtual Vector const& parameters() const = 0 ;\n\n\t\t// Evaluate the function at a given parameter value\n\t\tvirtual void evaluate_at( Vector const& parameters, int const numberOfDerivatives = 2 ) = 0 ;\n\t\t// Re-evaluate the function at a previously set parameter value, previously\n\t\t// set by a call to evaluate_at().\n\t\t// This allows to evaluate a specified number of derivatives.\n\t\tvirtual void evaluate( int const numberOfDerivatives = 2 ) = 0 ;\n\t\t\n\t\tvirtual Scalar get_value_of_function() const = 0 ;\n\t\tvirtual Vector get_value_of_first_derivative() const = 0 ;\n\t\tvirtual Matrix get_value_of_second_derivative() const = 0 ;\n\t\tvirtual std::string get_summary() const = 0 ;\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "479b3a9914a2a2e1f37959b805a5874019953bb8", "size": 1953, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/SmoothFunction.hpp", "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/include/metro/SmoothFunction.hpp", "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/include/metro/SmoothFunction.hpp", "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": 36.8490566038, "max_line_length": 95, "alphanum_fraction": 0.7383512545, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18983083827409314}}
{"text": "/*\n * Copyright (c) 2018 Peerplays Blockchain Standards Association, and contributors.\n *\n * The 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\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#define DEFAULT_LOGGER \"betting\"\n#include <graphene/chain/betting_market_object.hpp>\n#include <graphene/chain/database.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n\n#include <boost/msm/back/state_machine.hpp>\n#include <boost/msm/front/state_machine_def.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/msm/back/tools.hpp>\n\nnamespace graphene { namespace chain {\n   enum class betting_market_state {\n      unresolved,\n      frozen,\n      closed,\n      graded,\n      canceled,\n      settled\n   };\n} }\nFC_REFLECT_ENUM(graphene::chain::betting_market_state, \n                (unresolved)\n                (frozen)\n                (closed)\n                (graded)\n                (canceled)\n                (settled))\n\n\nnamespace graphene { namespace chain {\n\nnamespace msm = boost::msm;\nnamespace mpl = boost::mpl;\n\n/* static */ share_type bet_object::get_approximate_matching_amount(share_type bet_amount, bet_multiplier_type backer_multiplier, bet_type back_or_lay, bool round_up /* = false */)\n{\n   fc::uint128_t amount_to_match_128 = bet_amount.value;\n\n   if (back_or_lay == bet_type::back)\n   {\n       amount_to_match_128 *= backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION;\n       if (round_up)\n         amount_to_match_128 += GRAPHENE_BETTING_ODDS_PRECISION - 1;\n       amount_to_match_128 /= GRAPHENE_BETTING_ODDS_PRECISION;\n   }\n   else\n   {\n       amount_to_match_128 *= GRAPHENE_BETTING_ODDS_PRECISION;\n       if (round_up)\n         amount_to_match_128 += backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION - 1;\n       amount_to_match_128 /= backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION;\n   }\n   return amount_to_match_128.to_uint64();\n}\n\nshare_type bet_object::get_approximate_matching_amount(bool round_up /* = false */) const\n{\n   return get_approximate_matching_amount(amount_to_bet.amount, backer_multiplier, back_or_lay, round_up);\n}\n\n/* static */ share_type bet_object::get_exact_matching_amount(share_type bet_amount, bet_multiplier_type backer_multiplier, bet_type back_or_lay)\n{\n   share_type back_ratio;\n   share_type lay_ratio;\n   std::tie(back_ratio, lay_ratio) = get_ratio(backer_multiplier);\n   if (back_or_lay == bet_type::back)\n      return bet_amount / back_ratio * lay_ratio;\n   else\n      return bet_amount / lay_ratio * back_ratio;\n}\n\nshare_type bet_object::get_exact_matching_amount() const\n{\n   return get_exact_matching_amount(amount_to_bet.amount, backer_multiplier, back_or_lay);\n}\n\n/* static */ std::pair<share_type, share_type> bet_object::get_ratio(bet_multiplier_type backer_multiplier)\n{\n   share_type gcd = boost::integer::gcd(GRAPHENE_BETTING_ODDS_PRECISION, static_cast<int32_t>(backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION));\n   return std::make_pair(GRAPHENE_BETTING_ODDS_PRECISION / gcd, (backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION) / gcd);\n}\n\nstd::pair<share_type, share_type> bet_object::get_ratio() const\n{\n   return get_ratio(backer_multiplier);\n}\n\nshare_type bet_object::get_minimum_matchable_amount() const\n{\n   share_type gcd = boost::integer::gcd(GRAPHENE_BETTING_ODDS_PRECISION, static_cast<int32_t>(backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION));\n   return (back_or_lay == bet_type::back ? GRAPHENE_BETTING_ODDS_PRECISION : backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION) / gcd;\n}\n\nshare_type bet_object::get_minimum_matching_amount() const\n{\n   share_type gcd = boost::integer::gcd(GRAPHENE_BETTING_ODDS_PRECISION, static_cast<int32_t>(backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION));\n   return (back_or_lay == bet_type::lay ? GRAPHENE_BETTING_ODDS_PRECISION : backer_multiplier - GRAPHENE_BETTING_ODDS_PRECISION) / gcd;\n}\n\n\nshare_type betting_market_position_object::reduce()\n{\n   share_type additional_not_cancel_balance = std::min(pay_if_payout_condition, pay_if_not_payout_condition);\n   if (additional_not_cancel_balance == 0)\n      return 0;\n   pay_if_payout_condition -= additional_not_cancel_balance;\n   pay_if_not_payout_condition -= additional_not_cancel_balance;\n   pay_if_not_canceled += additional_not_cancel_balance;\n   \n   share_type immediate_winnings = std::min(pay_if_canceled, pay_if_not_canceled);\n   if (immediate_winnings == 0)\n      return 0;\n   pay_if_canceled -= immediate_winnings;\n   pay_if_not_canceled -= immediate_winnings;\n   return immediate_winnings;\n}\n\n// betting market object implementation\nnamespace \n{\n   // Events -- most events happen when the witnesses publish an update operation with a new\n   // status, so if they publish an event with the status set to `frozen`, we'll generate a `frozen_event`\n   struct unresolved_event \n   {\n      database& db;\n      unresolved_event(database& db) : db(db) {}\n   };\n   struct frozen_event \n   {\n      database& db;\n      frozen_event(database& db) : db(db) {}\n   };\n   struct closed_event \n   {\n      database& db;\n      closed_event(database& db) : db(db) {}\n   };\n   struct graded_event\n   {\n      database& db;\n      betting_market_resolution_type new_grading;\n      graded_event(database& db, betting_market_resolution_type new_grading) : db(db), new_grading(new_grading) {}\n   };\n   struct settled_event\n   {\n      database& db;\n      settled_event(database& db) : db(db) {}\n   };\n   struct canceled_event\n   {\n      database& db;\n      canceled_event(database& db) : db(db) {}\n   };\n\n   // Events\n   struct betting_market_state_machine_ : public msm::front::state_machine_def<betting_market_state_machine_>\n   {\n      // disable a few state machine features we don't use for performance\n      typedef int no_exception_thrown;\n      typedef int no_message_queue;\n\n      // States\n      struct unresolved : public msm::front::state<>{\n         template <class Event>\n         void on_entry(const Event& event, betting_market_state_machine_& fsm) {\n            dlog(\"betting market ${id} -> unresolved\", (\"id\", fsm.betting_market_obj->id));\n         }\n      };\n      struct frozen : public msm::front::state<>{\n         template <class Event>\n         void on_entry(const Event& event, betting_market_state_machine_& fsm) {\n            dlog(\"betting market ${id} -> frozen\", (\"id\", fsm.betting_market_obj->id));\n         }\n      };\n      struct closed : public msm::front::state<>{\n         template <class Event>\n         void on_entry(const Event& event, betting_market_state_machine_& fsm) {\n            dlog(\"betting market ${id} -> closed\", (\"id\", fsm.betting_market_obj->id));\n         }\n      };\n      struct graded : public msm::front::state<>{\n         void on_entry(const graded_event& event, betting_market_state_machine_& fsm) {\n            dlog(\"betting market ${id} -> graded\", (\"id\", fsm.betting_market_obj->id));\n            fsm.betting_market_obj->resolution = event.new_grading;\n         }\n      };\n      struct settled : public msm::front::state<>{\n         template <class Event>\n         void on_entry(const Event& event, betting_market_state_machine_& fsm) {\n            dlog(\"betting market ${id} -> settled\", (\"id\", fsm.betting_market_obj->id));\n         }\n      };\n      struct canceled : public msm::front::state<>{\n         void on_entry(const canceled_event& event, betting_market_state_machine_& fsm) {\n            dlog(\"betting market ${id} -> canceled\", (\"id\", fsm.betting_market_obj->id));\n            fsm.betting_market_obj->resolution = betting_market_resolution_type::cancel;\n            fsm.betting_market_obj->cancel_all_bets(event.db);\n         }\n      };\n\n      typedef unresolved initial_state;\n      typedef betting_market_state_machine_ x; // makes transition table cleaner\n\n\n      // Transition table for betting market\n      struct transition_table : mpl::vector<\n      //    Start                       Event                         Next                       Action               Guard\n      //  +---------------------------+-----------------------------+----------------------------+---------------------+----------------------+\n      _row < unresolved,               frozen_event,                 frozen >,\n      _row < unresolved,               closed_event,                 closed >,\n      _row < unresolved,               canceled_event,               canceled >,\n      //  +---------------------------+-----------------------------+----------------------------+---------------------+----------------------+\n      _row < frozen,                   unresolved_event,             unresolved >,\n      _row < frozen,                   closed_event,                 closed >,\n      _row < frozen,                   canceled_event,               canceled >,\n      //  +---------------------------+-----------------------------+----------------------------+---------------------+----------------------+\n      _row < closed,                   graded_event,                 graded >,\n      _row < closed,                   canceled_event,               canceled >,\n      //  +---------------------------+-----------------------------+----------------------------+---------------------+----------------------+\n      _row < graded,                   settled_event,                settled >,\n      _row < graded,                   canceled_event,               canceled >\n      //  +---------------------------+-----------------------------+----------------------------+---------------------+----------------------+\n      > {};\n\n      template <class Fsm, class Event>\n      void no_transition(Event const& e, Fsm& ,int state)\n      {\n         FC_THROW_EXCEPTION(graphene::chain::no_transition, \"No transition\");\n      }\n       \n      template <class Fsm>\n      void no_transition(canceled_event const& e, Fsm&, int state)\n      {\n         //ignore transitions from settled to canceled state\n         //and from canceled to canceled state\n      }\n\n      betting_market_object* betting_market_obj;\n      betting_market_state_machine_(betting_market_object* betting_market_obj) : betting_market_obj(betting_market_obj) {}\n   };\n   typedef msm::back::state_machine<betting_market_state_machine_> betting_market_state_machine;\n\n} // end anonymous namespace\n\nclass betting_market_object::impl {\npublic:\n   betting_market_state_machine state_machine;\n\n   impl(betting_market_object* self) : state_machine(self) {}\n};\n\nbetting_market_object::betting_market_object() :\n   my(new impl(this))\n{\n}\n\nbetting_market_object::betting_market_object(const betting_market_object& rhs) : \n   graphene::db::abstract_object<betting_market_object>(rhs),\n   group_id(rhs.group_id),\n   description(rhs.description),\n   payout_condition(rhs.payout_condition),\n   resolution(rhs.resolution),\n   my(new impl(this))\n{\n   my->state_machine = rhs.my->state_machine;\n   my->state_machine.betting_market_obj = this;\n}\n\nbetting_market_object& betting_market_object::operator=(const betting_market_object& rhs)\n{\n   //graphene::db::abstract_object<betting_market_object>::operator=(rhs);\n   id = rhs.id;\n   group_id = rhs.group_id;\n   description = rhs.description;\n   payout_condition = rhs.payout_condition;\n   resolution = rhs.resolution;\n\n   my->state_machine = rhs.my->state_machine;\n   my->state_machine.betting_market_obj = this;\n\n   return *this;\n}\n\nbetting_market_object::~betting_market_object()\n{\n}\n\nnamespace {\n\n\n   bool verify_betting_market_status_constants()\n   {\n      unsigned error_count = 0;\n      typedef msm::back::generate_state_set<betting_market_state_machine::stt>::type all_states;\n      static char const* filled_state_names[mpl::size<all_states>::value];\n      mpl::for_each<all_states,boost::msm::wrap<mpl::placeholders::_1> >\n         (msm::back::fill_state_names<betting_market_state_machine::stt>(filled_state_names));\n      for (unsigned i = 0; i < mpl::size<all_states>::value; ++i)\n      {\n         try\n         {\n            // this is an approximate test, the state name provided by typeinfo will be mangled, but should\n            // at least contain the string we're looking for\n            const char* fc_reflected_value_name = fc::reflector<betting_market_state>::to_string((betting_market_state)i);\n            if (!strstr(filled_state_names[i], fc_reflected_value_name))\n            {\n               fc_elog(fc::logger::get(\"default\"),\n                       \"Error, state string mismatch between fc and boost::msm for int value ${int_value}: \"\n                       \"boost::msm -> ${boost_string}, fc::reflect -> ${fc_string}\",\n                       (\"int_value\", i)(\"boost_string\", filled_state_names[i])(\"fc_string\", fc_reflected_value_name));\n               ++error_count;\n            }\n         }\n         catch (const fc::bad_cast_exception&)\n         {\n            fc_elog(fc::logger::get(\"default\"), \n                    \"Error, no reflection for value ${int_value} in enum betting_market_status\",\n                    (\"int_value\", i));\n            ++error_count;\n         }\n      }\n      if (error_count == 0)\n         dlog(\"Betting market status constants are correct\");\n      else\n         wlog(\"There were ${count} errors in the betting market status constants\", (\"count\", error_count));\n\n      return error_count == 0;\n   }\n} // end anonymous namespace\n\n\nbetting_market_status betting_market_object::get_status() const\n{\n   static bool state_constants_are_correct = verify_betting_market_status_constants();\n   (void)&state_constants_are_correct;\n   betting_market_state state = (betting_market_state)my->state_machine.current_state()[0];\n   \n   edump((state));\n\n   switch (state)\n   {\n      case betting_market_state::unresolved:\n         return betting_market_status::unresolved;\n      case betting_market_state::frozen:\n         return betting_market_status::frozen;\n      case betting_market_state::closed:\n         return betting_market_status::unresolved;\n      case betting_market_state::canceled:\n         return betting_market_status::canceled;\n      case betting_market_state::graded:\n         return betting_market_status::graded;\n      case betting_market_state::settled:\n         return betting_market_status::settled;\n      default:\n         FC_THROW(\"Unexpected betting market state\");\n   };\n}\n\nvoid betting_market_object::cancel_all_unmatched_bets(database& db) const\n{\n   const auto& bet_odds_idx = db.get_index_type<bet_object_index>().indices().get<by_odds>();\n\n   // first, cancel all bets on the active books\n   auto book_itr = bet_odds_idx.lower_bound(std::make_tuple(id));\n   auto book_end = bet_odds_idx.upper_bound(std::make_tuple(id));\n   while (book_itr != book_end)\n   {\n      auto old_book_itr = book_itr;\n      ++book_itr;\n      db.cancel_bet(*old_book_itr, true);\n   }\n\n   // then, cancel any delayed bets on that market.  We don't have an index for\n   // that, so walk through all delayed bets\n   book_itr = bet_odds_idx.begin();\n   while (book_itr != bet_odds_idx.end() &&\n          book_itr->end_of_delay)\n   {\n      auto old_book_itr = book_itr;\n      ++book_itr;\n      if (old_book_itr->betting_market_id == id)\n         db.cancel_bet(*old_book_itr, true);\n   }\n}\n    \nvoid betting_market_object::cancel_all_bets(database& db) const\n{\n    const auto& bets_by_market_id = db.get_index_type<bet_object_index>().indices().get<by_betting_market_id>();\n    \n    auto bet_it = bets_by_market_id.lower_bound(id);\n    auto bet_it_end = bets_by_market_id.upper_bound(id);\n    while (bet_it != bet_it_end)\n    {\n        auto old_bet_it = bet_it;\n        ++bet_it;\n        db.cancel_bet(*old_bet_it, true);\n    }\n}\n\nvoid betting_market_object::pack_impl(std::ostream& stream) const\n{\n   boost::archive::binary_oarchive oa(stream, boost::archive::no_header|boost::archive::no_codecvt|boost::archive::no_xml_tag_checking);\n   oa << my->state_machine;\n}\n\nvoid betting_market_object::unpack_impl(std::istream& stream)\n{\n   boost::archive::binary_iarchive ia(stream, boost::archive::no_header|boost::archive::no_codecvt|boost::archive::no_xml_tag_checking);\n   ia >> my->state_machine;\n}\n\nvoid betting_market_object::on_unresolved_event(database& db)\n{\n   my->state_machine.process_event(unresolved_event(db));\n}\n\nvoid betting_market_object::on_frozen_event(database& db)\n{\n   my->state_machine.process_event(frozen_event(db));\n}\n\nvoid betting_market_object::on_closed_event(database& db)\n{\n   my->state_machine.process_event(closed_event(db));\n}\n\nvoid betting_market_object::on_graded_event(database& db, betting_market_resolution_type new_grading)\n{\n   my->state_machine.process_event(graded_event(db, new_grading));\n}\n\nvoid betting_market_object::on_settled_event(database& db)\n{\n   my->state_machine.process_event(settled_event(db));\n}\n\nvoid betting_market_object::on_canceled_event(database& db)\n{\n   my->state_machine.process_event(canceled_event(db));\n}\n\n} } // graphene::chain\n\nnamespace fc { \n   // Manually reflect betting_market_object to variant to properly reflect \"state\"\n   void to_variant(const graphene::chain::betting_market_object& event_obj, fc::variant& v)\n   {\n      fc::mutable_variant_object o;\n      o(\"id\", event_obj.id)\n       (\"group_id\", event_obj.group_id)\n       (\"description\", event_obj.description)\n       (\"payout_condition\", event_obj.payout_condition)\n       (\"resolution\", event_obj.resolution)\n       (\"status\", event_obj.get_status());\n\n      v = o;\n   }\n\n   // Manually reflect betting_market_object to variant to properly reflect \"state\"\n   void from_variant(const fc::variant& v, graphene::chain::betting_market_object& event_obj)\n   {\n      event_obj.id = v[\"id\"].as<graphene::chain::betting_market_id_type>();\n      event_obj.group_id = v[\"name\"].as<graphene::chain::betting_market_group_id_type>();\n      event_obj.description = v[\"description\"].as<graphene::chain::internationalized_string_type>();\n      event_obj.payout_condition = v[\"payout_condition\"].as<graphene::chain::internationalized_string_type>();\n      event_obj.resolution = v[\"resolution\"].as<fc::optional<graphene::chain::betting_market_resolution_type>>();\n      graphene::chain::betting_market_status status = v[\"status\"].as<graphene::chain::betting_market_status>();\n      const_cast<int*>(event_obj.my->state_machine.current_state())[0] = (int)status;\n   }\n} //end namespace fc\n\n", "meta": {"hexsha": "cb0e006e4d24313f31218b0283706f58198faf1d", "size": 19220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/betting_market_object.cpp", "max_stars_repo_name": "sierra19XX/peerplays", "max_stars_repo_head_hexsha": "a0f793951c4aced5e6be945865e8f63124cc7949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-24T08:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T08:58:42.000Z", "max_issues_repo_path": "libraries/chain/betting_market_object.cpp", "max_issues_repo_name": "sierra19XX/peerplays", "max_issues_repo_head_hexsha": "a0f793951c4aced5e6be945865e8f63124cc7949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/betting_market_object.cpp", "max_forks_repo_name": "sierra19XX/peerplays", "max_forks_repo_head_hexsha": "a0f793951c4aced5e6be945865e8f63124cc7949", "max_forks_repo_licenses": ["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.6720321932, "max_line_length": 180, "alphanum_fraction": 0.6639438085, "num_tokens": 4345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.18971050617730043}}
{"text": "//\n// Created by erik on 1/2/17.\n//\n\n#include \"Spawn.h\"\n#include \"game/State.h\"\n#include \"game/entity/entity.h\"\n#include \"physics/PhysicsWorld.h\"\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n\nusing namespace spatacs;\nusing namespace game;\nusing namespace events;\n\n\nSpawn::Spawn(const length_vec& pos, const velocity_vec& vel) : mPosition(pos), mVelocity(vel)\n{\n\n}\n\nGameEntityHandle Spawn::spawn(EventContext& context) const\n{\n    return context.state.entity_manager().create();\n}\n\n\nSpawnProjectile::SpawnProjectile(GameEntityID shooter, length_vec pos, velocity_vec vel, mass_t mass, length_t rad,\n                                 game::Damage dmg) :\n        Spawn(pos, vel),\n        mShooter(shooter),\n        mMass(mass),\n        mRadius(rad),\n        mDamage(dmg)\n{\n\n}\n\nvoid SpawnProjectile::apply(EventContext& context) const\n{\n    GameEntityHandle entity = spawn(context);\n    entity.add<components::Timer>(10.0_s);\n    entity.add<components::Parent>(mShooter);\n    entity.add<components::Warhead>(mDamage);\n    entity.add_tag<components::TimedDespawn>();\n\n    physics::Object obj(mPosition, mVelocity, mMass, entity.id().getID());\n    obj.addFixture( mRadius );\n    auto pid = context.world.spawn(obj);\n\n    entity.add<components::PhysicsData>(pid, mMass, mPosition, mVelocity);\n}\n\nSpawnShip::SpawnShip(std::uint64_t team, std::string name, std::string type, const length_vec& position) :\n        Spawn(position, velocity_vec{0,0,0}),\n        mTeam(team),\n        mName(std::move(name)),\n        mType(std::move(type))\n{\n\n}\n/*\nnamespace\n{\n    game::AmmoData getAmmoData(const std::string& type)\n    {\n        boost::property_tree::ptree tree;\n        boost::property_tree::xml_parser::read_xml(\"data/ammunition.xml\", tree);\n        auto& source = tree.get_child(\"ammunition.\" + type);\n\n        game::AmmoData data;\n        data.mass   = source.get<mass_t>(\"mass\");\n        data.charge = source.get<energy_t>(\"energy\");\n        data.name   = type;\n        data.damage.armour_pierce   = source.get<double>(\"AP\", 0.0);\n        data.damage.high_explosive  = source.get<double>(\"HE\", 0.0);\n        data.damage.shield_overload = source.get<double>(\"SO\", 0.0);\n        return data;\n    }\n}\n*/\nvoid SpawnShip::apply(EventContext& context) const\n{\n    boost::property_tree::ptree tree;\n    boost::property_tree::xml_parser::read_xml(\"data/\"+mType+\".xml\", tree);\n    auto data = tree.get_child(\"ship\");\n    auto mass = data.get<mass_t>(\"mass\");\n\n\n    GameEntityHandle entity = spawn(context);\n    entity.add<components::Name>(mName);\n    entity.add<components::Affiliation>(mTeam);\n\n    physics::Object obj(mPosition, velocity_vec{0, 0, 0}, mass, entity.id().getID());\n    /*obj.addFixture( ship->radius() ).setUserdata(0); // ship\n    obj.addFixture( ship->radius() + 25.0_m ).setUserdata(1); // shield\n     */\n    auto pid = context.world.spawn(obj);\n\n    entity.add<components::PhysicsData>(pid, mass, mPosition, mVelocity);\n\n\n    /*\n    // now add the ammo\n    for(auto& ammo : mAmmo)\n    {\n        ship->components().apply( game::systems::AddAmmunition(getAmmoData(ammo.type), ammo.amount) );\n    }\n\n    mass_t rest = game::systems::fill_fuel(ship->components(), mFuel);\n    if( rest > 0.0_kg )\n        std::cerr << \"Could not fit total fuel into tank!\" << std::endl;\n     */\n}\n\nvoid SpawnShip::addAmmunition(std::string name, std::size_t amount)\n{\n    mAmmo.emplace_back( std::move(name), amount);\n}\n\nvoid SpawnShip::setFuel(mass_t f)\n{\n    mFuel = f;\n}\n\nSpawnShip::AmmoData::AmmoData(const std::string& type, size_t amount) : type(type), amount(amount)\n{}\n", "meta": {"hexsha": "53cdad0fe01a90fe59a503222b314100dc555452", "size": 3601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "game/events/Spawn.cpp", "max_stars_repo_name": "ngc92/SpaTacS", "max_stars_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "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": "game/events/Spawn.cpp", "max_issues_repo_name": "ngc92/SpaTacS", "max_issues_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "game/events/Spawn.cpp", "max_forks_repo_name": "ngc92/SpaTacS", "max_forks_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_forks_repo_licenses": ["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.1328125, "max_line_length": 115, "alphanum_fraction": 0.6562066093, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1897105023566533}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// Copyright 2019 FZI Research Center for Information Technology\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\n//-----------------------------------------------------------------------------\n/*!\\file    JacobianTransposeSolver.cpp\n *\n * \\author  Stefan Scherzinger <scherzin@fzi.de>\n * \\date    2020/03/26\n *\n */\n//-----------------------------------------------------------------------------\n\n// this package\n#include <cartesian_controller_base/JacobianTransposeSolver.h>\n\n// Pluginlib\n#include <pluginlib/class_list_macros.h>\n\n// other\n#include <boost/algorithm/clamp.hpp>\n\n/**\n * \\class cartesian_controller_base::JacobianTransposeSolver \n *\n * Users may explicitly specify this solver with \\a \"jacobian_transpose\" as \\a\n * ik_solver in their controllers.yaml configuration file for each controller:\n *\n * \\code{.yaml}\n * <name_of_your_controller>:\n *     type: \"<type_of_your_controller>\"\n *     ik_solver: \"jacobian_transpose\"\n *     ...\n * \\endcode\n *\n */\nPLUGINLIB_EXPORT_CLASS(cartesian_controller_base::JacobianTransposeSolver, cartesian_controller_base::IKSolver)\n\n\n\n\n\nnamespace cartesian_controller_base{\n\n  JacobianTransposeSolver::JacobianTransposeSolver()\n  {\n  }\n\n  JacobianTransposeSolver::~JacobianTransposeSolver(){}\n\n  trajectory_msgs::JointTrajectoryPoint JacobianTransposeSolver::getJointControlCmds(\n        ros::Duration period,\n        const ctrl::Vector6D& net_force)\n  {\n    // Compute joint jacobian\n    m_jnt_jacobian_solver->JntToJac(m_current_positions,m_jnt_jacobian);\n\n    // Compute joint accelerations according to: \\f$ \\ddot{q} = H^{-1} ( J^T f) \\f$\n    m_current_accelerations.data = m_jnt_jacobian.data.transpose() * net_force;\n\n    // Integrate once, starting with zero motion\n    m_current_velocities.data = 0.5 * m_current_accelerations.data * period.toSec();\n\n    // Integrate twice, starting with zero motion\n    m_current_positions.data = m_last_positions.data + 0.5 * m_current_velocities.data * period.toSec();\n\n    // Make sure positions stay in allowed margins\n    applyJointLimits();\n\n    // Apply results\n    trajectory_msgs::JointTrajectoryPoint control_cmd;\n    for (int i = 0; i < m_number_joints; ++i)\n    {\n      control_cmd.positions.push_back(m_current_positions(i));\n      control_cmd.velocities.push_back(m_current_velocities(i));\n\n      // Accelerations should be left empty. Those values will be interpreted\n      // by most hardware joint drivers as max. tolerated values. As a\n      // consequence, the robot will move very slowly.\n    }\n    control_cmd.time_from_start = period; // valid for this duration\n\n    return control_cmd;\n  }\n\n  bool JacobianTransposeSolver::init(ros::NodeHandle& nh,\n                                     const KDL::Chain& chain,\n                                     const KDL::JntArray& upper_pos_limits,\n                                     const KDL::JntArray& lower_pos_limits)\n  {\n    IKSolver::init(nh, chain, upper_pos_limits, lower_pos_limits);\n\n    m_jnt_jacobian_solver.reset(new KDL::ChainJntToJacSolver(m_chain));\n    m_jnt_jacobian.resize(m_number_joints);\n\n    return true;\n  }\n} // namespace\n", "meta": {"hexsha": "62bf21ebca59f8ba0d0246a8d8741ea9418c6870", "size": 4715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cartesian_controller_base/src/JacobianTransposeSolver.cpp", "max_stars_repo_name": "graziegrazie/cartesian_controllers", "max_stars_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2019-11-01T07:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T08:14:52.000Z", "max_issues_repo_path": "cartesian_controller_base/src/JacobianTransposeSolver.cpp", "max_issues_repo_name": "graziegrazie/cartesian_controllers", "max_issues_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T20:40:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:17:50.000Z", "max_forks_repo_path": "cartesian_controller_base/src/JacobianTransposeSolver.cpp", "max_forks_repo_name": "graziegrazie/cartesian_controllers", "max_forks_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2019-11-01T07:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T08:26:35.000Z", "avg_line_length": 37.72, "max_line_length": 111, "alphanum_fraction": 0.6816542948, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.18971049853600624}}
{"text": "#include \"dense-reconstruction/pmvs-common.h\"\n\n#include <map>\n#include <stdlib.h>\n\n#include <Eigen/Core>\n#include <aslam/cameras/camera-factory.h>\n#include <aslam/cameras/camera-pinhole.h>\n#include <aslam/cameras/camera-unified-projection.h>\n#include <aslam/cameras/camera.h>\n#include <aslam/common/timer.h>\n#include <aslam/common/undistort-helpers.h>\n#include <aslam/frames/visual-frame.h>\n#include <aslam/frames/visual-nframe.h>\n#include <glog/logging.h>\n#include <landmark-triangulation/pose-interpolator.h>\n#include <maplab-common/accessors.h>\n#include <maplab-common/file-system-tools.h>\n#include <maplab-common/vector-window-operations.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/imgproc/types_c.h>\n#include <vi-map/unique-id.h>\n\nnamespace dense_reconstruction {\nObserverCamera::ObserverCamera(\n    const vi_map::VIMap& vi_map, const PmvsConfig& config,\n    const vi_map::MissionId& _mission_id, const aslam::CameraId& _camera_id,\n    const unsigned int _frame_idx, const bool _is_optional_camera)\n    : mission_id(_mission_id),\n      camera_id(_camera_id),\n      frame_idx(_frame_idx),\n      is_optional_camera(_is_optional_camera) {\n  VLOG(2) << \"Create ObserverCamera from camera \" << camera_id;\n  const aslam::Camera* camera = nullptr;\n  if (is_optional_camera) {\n    const backend::CameraWithExtrinsics& cam_with_extrinsics =\n        vi_map.getMission(mission_id)\n            .getOptionalCameraWithExtrinsics(camera_id);\n    camera = cam_with_extrinsics.second.get();\n    T_B_C = cam_with_extrinsics.first.inverse();\n    VLOG(2) << \"  -> is optional camera.\";\n  } else {\n    const aslam::NCamera& n_camera =\n        vi_map.getSensorManager().getNCameraForMission(mission_id);\n    camera = &(n_camera.getCamera(frame_idx));\n    T_B_C = n_camera.get_T_C_B(frame_idx).inverse();\n    VLOG(2) << \"  -> is nframe camera.\";\n  }\n\n  const aslam::Camera::Type camera_type = camera->getType();\n  aslam::Camera::Ptr original_camera;\n  switch (camera_type) {\n    case aslam::Camera::Type::kPinhole:\n      VLOG(2) << \"  -> is pinhole camera.\";\n      if (camera->getDistortion().getType() !=\n          aslam::Distortion::Type::kNoDistortion) {\n        undistorter = aslam::createMappedUndistorter(\n            *camera, config.pmvs_undistortion_alpha,\n            config.pmvs_undistortion_scale,\n            config.kUndistortionInterpolationMethod);\n\n        camera_matrix_undistorted = static_cast<const aslam::PinholeCamera&>(\n                                        undistorter->getOutputCamera())\n                                        .getCameraMatrix();\n\n        VLOG(2)\n            << \"  -> is distorted, initializing pinhole mapped undistorter!\";\n        CHECK(undistorter != nullptr);\n      } else {\n        camera_matrix_undistorted =\n            static_cast<const aslam::PinholeCamera*>(camera)->getCameraMatrix();\n        VLOG(2) << \"  -> is already undistorted!\";\n      }\n      break;\n    case aslam::Camera::Type::kUnifiedProjection:\n      VLOG(2) << \"  -> is unified projection camera.\";\n      if (camera->getDistortion().getType() !=\n          aslam::Distortion::Type::kNoDistortion) {\n        undistorter = aslam::createMappedUndistorterToPinhole(\n            *static_cast<const aslam::UnifiedProjectionCamera*>(camera),\n            config.pmvs_undistortion_alpha, config.pmvs_undistortion_scale,\n            config.kUndistortionInterpolationMethod);\n\n        camera_matrix_undistorted =\n            static_cast<const aslam::UnifiedProjectionCamera&>(\n                undistorter->getOutputCamera())\n                .getCameraMatrix();\n        VLOG(2) << \"  -> is distorted, initializing unified projection mapped \"\n                   \"undistorter!\";\n        CHECK(undistorter != nullptr);\n      } else {\n        camera_matrix_undistorted =\n            static_cast<const aslam::UnifiedProjectionCamera*>(camera)\n                ->getCameraMatrix();\n        VLOG(2) << \"  -> is already undistorted!\";\n      }\n\n      break;\n    default:\n      LOG(FATAL) << \"Unsupported camera type: \" << camera_type;\n  }\n}\n\nObserverCamera::ObserverCamera(\n    const vi_map::VIMap& vi_map, const PmvsConfig& config,\n    const vi_map::MissionId& _mission_id, const aslam::CameraId& _camera_id)\n    : ObserverCamera(vi_map, config, _mission_id, _camera_id, 0u, true) {}\n\nvoid ObserverCamera::undistortImage(\n    const cv::Mat& image, cv::Mat* undistorted_image) const {\n  CHECK(!image.empty());\n  CHECK_NOTNULL(undistorted_image);\n  CHECK(undistorter != nullptr);\n  undistorter->processImage(image, undistorted_image);\n}\n\nObserverPose::ObserverPose(\n    const vi_map::VIMap& vi_map, const size_t _camera_number,\n    const vi_map::MissionId& _mission_id,\n    const pose_graph::VertexId& _vertex_id, const int64_t _timestamp_ns,\n    const ObserverCamera& observer_camera,\n    const backend::ResourceType& _image_type)\n    : camera_number(_camera_number),\n      mission_id(_mission_id),\n      vertex_id(_vertex_id),\n      timestamp_ns(_timestamp_ns),\n      camera_id(observer_camera.camera_id),\n      is_optional_camera_image(observer_camera.is_optional_camera),\n      image_type(_image_type),\n      frame_idx(observer_camera.frame_idx) {\n  aslam::Transformation T_M_I;\n  if (needsInterpolation(vi_map)) {\n    Eigen::Matrix<int64_t, 1, Eigen::Dynamic> pose_timestamps;\n    pose_timestamps.resize(1);\n    pose_timestamps(0, 0) = timestamp_ns;\n    aslam::TransformationVector poses_M_I;\n    landmark_triangulation::PoseInterpolator pose_interpolator;\n    pose_interpolator.getPosesAtTime(\n        vi_map, mission_id, pose_timestamps, &poses_M_I);\n    T_M_I = poses_M_I.at(0u);\n  } else {\n    T_M_I = vi_map.getVertex(vertex_id).get_T_M_I();\n  }\n\n  const aslam::Transformation& T_G_M =\n      vi_map.getMissionBaseFrameForMission(mission_id).get_T_G_M();\n\n  T_G_C = T_G_M * T_M_I * observer_camera.T_B_C;\n  p_G = T_G_C.getPosition();\n\n  const Eigen::Matrix<double, 3, 4> T_GC =\n      T_G_C.inverse().getTransformationMatrix().template topLeftCorner<3, 4>();\n\n  P_undistorted = observer_camera.camera_matrix_undistorted * T_GC;\n}\n\nvoid ObserverPose::loadImage(\n    const vi_map::VIMap& vi_map, cv::Mat* image) const {\n  CHECK_NOTNULL(image);\n  if (is_optional_camera_image) {\n    CHECK(\n        vi_map.getOptionalCameraResource(\n            vi_map.getMission(mission_id), image_type, camera_id, timestamp_ns,\n            image));\n  } else {\n    const vi_map::Vertex& vertex = vi_map.getVertex(vertex_id);\n    CHECK(vi_map.getFrameResource(vertex, frame_idx, image_type, image));\n  }\n}\n\nbool ObserverPose::needsUndistortion() const {\n  return (image_type == backend::ResourceType::kRawImage) ||\n         (image_type == backend::ResourceType::kRawColorImage);\n}\n\nbool ObserverPose::needsInterpolation(const vi_map::VIMap& vi_map) const {\n  return vi_map.getVertex(vertex_id).getMinTimestampNanoseconds() !=\n         timestamp_ns;\n}\n\n}  // namespace dense_reconstruction\n", "meta": {"hexsha": "8e71ec2b7c5f642982878916c69d005f18f5abb8", "size": 6940, "ext": "cc", "lang": "C++", "max_stars_repo_path": "interfaces/pmvs_interface/src/pmvs-common.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": "interfaces/pmvs_interface/src/pmvs-common.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": "interfaces/pmvs_interface/src/pmvs-common.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": 37.7173913043, "max_line_length": 80, "alphanum_fraction": 0.6930835735, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3140505449918075, "lm_q1q2_score": 0.18966512151953888}}
{"text": "//-------------------------------------------------------------------------//\n//\n// Copyright 2017 Sascha Kaden\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#ifndef COLLISIONDETECTIONSPHERE_HPP\n#define COLLISIONDETECTIONSPHERE_HPP\n\n#include <Eigen/Geometry>\n\n#include <ippp/environment/cad/CadProcessing.h>\n#include <ippp/modules/collisionDetection/CollisionDetection.hpp>\n\nnamespace ippp {\n\n/*!\n* \\brief   Class for AABB collision detection with the Eigen AABB structure, which is saved in the Mesh container.\n* \\author  Sascha Kaden\n* \\date    2017-02-19\n*/\ntemplate <unsigned int dim>\nclass CollisionDetectionSphere : public CollisionDetection<dim> {\n  public:\n    CollisionDetectionSphere(const std::shared_ptr<Environment> &environment,\n                             const CollisionRequest &request = CollisionRequest());\n    bool checkConfig(const Vector<dim> &config, CollisionRequest *request = nullptr, CollisionResult *result = nullptr);\n    bool checkTrajectory(std::vector<Vector<dim>> &configs) override;\n\n  private:\n    bool checkObstacles(const AABB &robotAABB, CollisionResult *result);\n    bool checkRobots(const std::vector<AABB> &robotAABB, CollisionResult *result);\n    double checkSphere(const AABB &a, const AABB &b);\n\n    bool m_multiRobot = false;\n    std::vector<AABB> m_robotAABBs;\n    std::vector<AABB> m_obstacleAABBs;\n    std::vector<std::shared_ptr<RobotBase>> m_robots;\n\n    using CollisionDetection<dim>::m_environment;\n};\n\n/*!\n*  \\brief      Constructor of the class CollisionDetectionAABB\n*  \\author     Sascha Kaden\n*  \\param[in]  Environment\n*  \\date       2017-02-19\n*/\ntemplate <unsigned int dim>\nCollisionDetectionSphere<dim>::CollisionDetectionSphere(const std::shared_ptr<Environment> &environment,\n                                                        const CollisionRequest &request)\n    : CollisionDetection<dim>(\"CollisionDetectionSphere\", environment, request) {\n    if (environment->numRobots() > 1)\n        m_multiRobot = true;\n\n    m_robots = m_environment->getRobots();\n\n    for (auto robot : environment->getRobots())\n        m_robotAABBs.push_back(robot->getBaseModel()->getAABB());\n\n    for (auto obstacle : environment->getObstacles())\n        m_obstacleAABBs.push_back(obstacle->getAABB());\n}\n\n/*!\n*  \\brief      Check for collision\n*  \\author     Sascha Kaden\n*  \\param[in]  configuration\n*  \\param[out] binary result of collision (true if in collision or config is empty)\n*  \\date       2016-05-25\n*/\ntemplate <unsigned int dim>\nbool CollisionDetectionSphere<dim>::checkConfig(const Vector<dim> &config, CollisionRequest *request, CollisionResult *result) {\n    CollisionRequest collisionRequest;\n    if (request)\n        collisionRequest = *request;\n    else\n        collisionRequest = this->m_request;\n\n    if (m_multiRobot && collisionRequest.checkInterRobot) {\n        // compute the new AABBs of the robots with the configuration\n        std::vector<VectorX> singleConfigs = util::splitVec<dim>(config, m_environment->getRobotDimSizes());\n        std::vector<AABB> robotAABBs;\n        for (unsigned int i = 0; i < m_robots.size(); ++i) {\n            auto trafo = m_robots[i]->getTransformation(singleConfigs[i]);\n            robotAABBs.push_back(util::translateAABB(m_robotAABBs[i], trafo));\n        }\n        // check collisions\n        if (checkRobots(robotAABBs, result))\n            return true;\n        for (auto &robotAABB : robotAABBs)\n            if (checkObstacles(robotAABB, result))\n                return true;\n    } \n    if (collisionRequest.checkObstacle) {\n        auto trafo = m_robots[0]->getTransformation(config);\n        AABB robotAABB = util::translateAABB(m_robotAABBs[0], trafo);\n        return checkObstacles(robotAABB, result);\n    }\n\n    return false;\n}\n\n/*!\n*  \\brief      Check collision of a trajectory of configurations\n*  \\author     Sascha Kaden\n*  \\param[in]  vector of configurations\n*  \\param[out] binary result of collision (true if in collision)\n*  \\date       2016-05-25\n*/\ntemplate <unsigned int dim>\nbool CollisionDetectionSphere<dim>::checkTrajectory(std::vector<Vector<dim>> &configs) {\n    if (configs.empty())\n        return false;\n\n    for (auto &config : configs)\n        if (checkConfig(config))\n            return true;\n\n    return false;\n}\n\ntemplate <unsigned int dim>\nbool CollisionDetectionSphere<dim>::checkRobots(const std::vector<AABB> &robots, CollisionResult *result) {\n    if (result) {\n        double dist;\n        for (auto a = robots.begin(); a != robots.end() - 1; ++a) {\n            for (auto b = robots.begin() + 1; b != robots.end(); ++b) {\n                dist = checkSphere(*a, *b);\n                if (dist < result->minDist)\n                    result->minDist = dist;\n                if (dist < result->minRobotDist)\n                    result->minRobotDist = dist;\n                if (dist == 0) {\n                    result->collision = true;\n                    return true;\n                }\n            }\n        }\n    } else {\n        for (auto a = robots.begin(); a != robots.end() - 1; ++a)\n            for (auto b = robots.begin() + 1; b != robots.end(); ++b)\n                if (checkSphere(*a, *b) < 0)\n                    return true;\n    }\n\n    return false;\n}\n\ntemplate <unsigned int dim>\nbool CollisionDetectionSphere<dim>::checkObstacles(const AABB &robotAABB, CollisionResult *result) {\n    if (result) {\n        double dist;\n        for (auto &obstacle : m_obstacleAABBs) {\n            dist = checkSphere(robotAABB, obstacle);\n            if (dist < result->minDist)\n                result->minDist = dist;\n            if (dist < result->minObstacleDist)\n                result->minObstacleDist = dist;\n            if (dist == 0) {\n                result->collision = true;\n                return true;\n            }\n        }\n    } else {\n        for (auto &obstacle : m_obstacleAABBs)\n            if (checkSphere(robotAABB, obstacle) < 0)\n                return true;\n    }\n\n    return false;\n}\n\ntemplate <unsigned int dim>\ndouble CollisionDetectionSphere<dim>::checkSphere(const AABB &a, const AABB &b) {\n    // Book: Real-Time Collision Detection page 88\n    Vector3 d = a.center() - b.center();\n    double dist2 = d.dot(d);\n    // Spheres intersect if squared distance is less than squared sum of radii\n    double radiusSum = a.diagonal().norm() + b.diagonal().norm();\n    return dist2 - (radiusSum * radiusSum);\n}\n\n} /* namespace ippp */\n\n#endif /* COLLISIONDETECTIONAABB_HPP */\n", "meta": {"hexsha": "4ba16af775dbdd4584af889a7db4eea3d967298d", "size": 7029, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ippp/modules/collisionDetection/CollisionDetectionSphere.hpp", "max_stars_repo_name": "tobiaskohlbau/IPPP", "max_stars_repo_head_hexsha": "91432f00b49ea5a83648e3294ad5b4b661dcd284", "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/ippp/modules/collisionDetection/CollisionDetectionSphere.hpp", "max_issues_repo_name": "tobiaskohlbau/IPPP", "max_issues_repo_head_hexsha": "91432f00b49ea5a83648e3294ad5b4b661dcd284", "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/ippp/modules/collisionDetection/CollisionDetectionSphere.hpp", "max_forks_repo_name": "tobiaskohlbau/IPPP", "max_forks_repo_head_hexsha": "91432f00b49ea5a83648e3294ad5b4b661dcd284", "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.3216080402, "max_line_length": 128, "alphanum_fraction": 0.625266752, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18949865699205484}}
{"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_SIMD_FUNCTION_DEINTERLEAVE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_DEINTERLEAVE_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/function/deinterleave_first.hpp>\n#include <boost/simd/function/deinterleave_second.hpp>\n#include <array>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( deinterleave_\n                          , (typename T, typename X)\n                          , bd::cpu_\n                          , bs::pack_< bd::unspecified_<T>, X >\n                          , bs::pack_< bd::unspecified_<T>, X >\n                          )\n  {\n    static_assert ( T::static_size >= 2\n                  , \"deinterleave_first requires at least two elements\"\n                  );\n\n    BOOST_FORCEINLINE std::array<T,2> operator()(T const& x, T const& y) const BOOST_NOEXCEPT\n    {\n      return { deinterleave_first(x,y), deinterleave_second(x,y) };\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "b884d6abddfc920452fabe0274a2178e14f21781", "size": 1430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/deinterleave.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/deinterleave.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/deinterleave.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": 34.8780487805, "max_line_length": 100, "alphanum_fraction": 0.548951049, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.18949865165309504}}
{"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_BLOCKMODEL_MULTICANONICAL_HH\n#define GRAPH_BLOCKMODEL_MULTICANONICAL_HH\n\n#include \"config.h\"\n\n#include <vector>\n\n#include \"graph_tool.hh\"\n#include \"../support/graph_state.hh\"\n#include \"graph_blockmodel_util.hh\"\n#include <boost/mpl/vector.hpp>\n\nnamespace graph_tool\n{\nusing namespace boost;\nusing namespace std;\n\n#define MULTICANONICAL_BLOCK_STATE_params(State)                               \\\n    ((__class__,&, mpl::vector<python::object>, 1))                            \\\n    ((state, &, State&, 0))                                                    \\\n    ((hist, &, std::vector<size_t>&, 0))                                       \\\n    ((dens, &, std::vector<double>&, 0))                                       \\\n    ((S_min, , double, 0))                                                     \\\n    ((S_max, , double, 0))                                                     \\\n    ((f, , double, 0))                                                         \\\n    ((S, , double, 0))                                                         \\\n    ((E,, size_t, 0))                                                          \\\n    ((verbose,, bool, 0))\n\n\ntemplate <class State>\nstruct Multicanonical\n{\n    GEN_STATE_BASE(MulticanonicalBlockStateBase,\n                   MULTICANONICAL_BLOCK_STATE_params(State))\n\n    template <class... Ts>\n    class MulticanonicalBlockState\n        : public MulticanonicalBlockStateBase<Ts...>\n    {\n    public:\n        GET_PARAMS_USING(MulticanonicalBlockStateBase<Ts...>,\n                         MULTICANONICAL_BLOCK_STATE_params(State))\n        GET_PARAMS_TYPEDEF(Ts, MULTICANONICAL_BLOCK_STATE_params(State))\n\n        template <class... ATs,\n                  typename std::enable_if_t<sizeof...(ATs) ==\n                                            sizeof...(Ts)>* = nullptr>\n        MulticanonicalBlockState(ATs&&... as)\n           : MulticanonicalBlockStateBase<Ts...>(as...),\n            _i(get_bin(_S))\n        {\n        }\n\n        int _i;\n        double _dS;\n        size_t _null_move = null_group;\n\n        int get_bin(double S)\n        {\n            return std::floor((_hist.size() - 1) *\n                              ((S - _S_min) / (_S_max - _S_min)));\n        };\n\n        bool skip_node(size_t v)\n        {\n            return _state.skip_node(v);\n        }\n\n        size_t node_state(size_t v)\n        {\n            return _state.node_state(v);\n        }\n\n        size_t node_weight(size_t v)\n        {\n            return _state.node_weight(v);\n        }\n\n        template <class RNG>\n        size_t move_proposal(size_t v, RNG& rng)\n        {\n            return _state.move_proposal(v, rng);\n        }\n\n        auto virtual_move_dS(size_t v, size_t nr)\n        {\n            auto dS = _state.virtual_move_dS(v, nr);\n            double nS = _S + get<0>(dS);\n            if (nS < _S_min || nS >= _S_max)\n            {\n                get<0>(dS) = numeric_limits<double>::infinity();\n            }\n            else\n            {\n                int j = get_bin(nS);\n                get<1>(dS) += _dens[_i] - _dens[j];\n            }\n            _dS = get<0>(dS);\n            return dS;\n        }\n\n        void perform_move(size_t v, size_t nr)\n        {\n            _state.perform_move(v, nr);\n            _S += _dS;\n            _i = get_bin(_S);\n        }\n\n        bool is_deterministic()\n        {\n            return _state.is_deterministic();\n        }\n\n        bool is_sequential()\n        {\n            return _state.is_sequential();\n        }\n\n        auto& get_vlist()\n        {\n            return _state.get_vlist();\n        }\n\n        double get_beta()\n        {\n            return 1;\n        }\n\n        size_t get_niter()\n        {\n            return _state.get_niter();\n        }\n\n        void step(size_t, size_t)\n        {\n            _hist[_i]++;\n            _dens[_i] += _f;\n        }\n    };\n};\n\n\n} // graph_tool namespace\n\n#endif //GRAPH_BLOCKMODEL_MULTICANONICAL_HH\n", "meta": {"hexsha": "98cbef157f7b9febd97a115e8372a423758409d7", "size": 4728, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/inference/blockmodel/graph_blockmodel_multicanonical.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/inference/blockmodel/graph_blockmodel_multicanonical.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/inference/blockmodel/graph_blockmodel_multicanonical.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.8292682927, "max_line_length": 80, "alphanum_fraction": 0.4991539763, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18949864975607283}}
{"text": "#include \"extractor/intersection/intersection_analysis.hpp\"\n#include \"extractor/intersection/coordinate_extractor.hpp\"\n\n#include \"util/assert.hpp\"\n#include \"util/bearing.hpp\"\n#include \"util/coordinate_calculation.hpp\"\n\n#include <boost/optional/optional_io.hpp>\n\nnamespace osrm\n{\nnamespace extractor\n{\nnamespace intersection\n{\n\nIntersectionEdges getIncomingEdges(const util::NodeBasedDynamicGraph &graph,\n                                   const NodeID intersection_node)\n{\n    IntersectionEdges result;\n\n    for (const auto outgoing_edge : graph.GetAdjacentEdgeRange(intersection_node))\n    {\n        const auto from_node = graph.GetTarget(outgoing_edge);\n        const auto incoming_edge = graph.FindEdge(from_node, intersection_node);\n\n        if (!graph.GetEdgeData(incoming_edge).reversed)\n        {\n            result.push_back({from_node, incoming_edge});\n        }\n    }\n\n    // Enforce ordering of incoming edges\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nIntersectionEdges getOutgoingEdges(const util::NodeBasedDynamicGraph &graph,\n                                   const NodeID intersection_node)\n{\n    IntersectionEdges result;\n\n    for (const auto outgoing_edge : graph.GetAdjacentEdgeRange(intersection_node))\n    {\n        result.push_back({intersection_node, outgoing_edge});\n    }\n\n    BOOST_ASSERT(std::is_sorted(result.begin(), result.end()));\n    return result;\n}\n\nstd::vector<util::Coordinate>\ngetEdgeCoordinates(const extractor::CompressedEdgeContainer &compressed_geometries,\n                   const std::vector<util::Coordinate> &node_coordinates,\n                   const NodeID from_node,\n                   const EdgeID edge,\n                   const NodeID to_node)\n{\n    if (!compressed_geometries.HasEntryForID(edge))\n        return {node_coordinates[from_node], node_coordinates[to_node]};\n\n    BOOST_ASSERT(from_node < node_coordinates.size());\n    BOOST_ASSERT(to_node < node_coordinates.size());\n\n    // extracts the geometry in coordinates from the compressed edge container\n    std::vector<util::Coordinate> result;\n    const auto &geometry = compressed_geometries.GetBucketReference(edge);\n    result.reserve(geometry.size() + 1);\n\n    result.push_back(node_coordinates[from_node]);\n    std::transform(geometry.begin(),\n                   geometry.end(),\n                   std::back_inserter(result),\n                   [&node_coordinates](const auto &compressed_edge) {\n                       return node_coordinates[compressed_edge.node_id];\n                   });\n\n    // filter duplicated coordinates\n    result.erase(std::unique(result.begin(), result.end()), result.end());\n    return result;\n}\n\nnamespace\n{\ndouble findAngleBisector(double alpha, double beta)\n{\n    alpha *= M_PI / 180.;\n    beta *= M_PI / 180.;\n    const auto average =\n        180. * std::atan2(std::sin(alpha) + std::sin(beta), std::cos(alpha) + std::cos(beta)) /\n        M_PI;\n    return std::fmod(average + 360., 360.);\n}\n\ndouble findClosestOppositeBearing(const IntersectionEdgeGeometries &edge_geometries,\n                                  const double bearing)\n{\n    BOOST_ASSERT(!edge_geometries.empty());\n    const auto min = std::min_element(\n        edge_geometries.begin(),\n        edge_geometries.end(),\n        [bearing = util::bearing::reverse(bearing)](const auto &lhs, const auto &rhs) {\n            return util::angularDeviation(lhs.perceived_bearing, bearing) <\n                   util::angularDeviation(rhs.perceived_bearing, bearing);\n        });\n    return util::bearing::reverse(min->perceived_bearing);\n}\n\nstd::pair<bool, double> findMergedBearing(const util::NodeBasedDynamicGraph &graph,\n                                          const IntersectionEdgeGeometries &edge_geometries,\n                                          std::size_t lhs_index,\n                                          std::size_t rhs_index,\n                                          bool neighbor_intersection)\n{\n    // Function returns a pair with a flag and a value of bearing for merged roads\n    // If the flag is false the bearing must not be used as a merged value at neighbor intersections\n\n    using util::angularDeviation;\n    using util::bearing::angleBetween;\n\n    const auto &lhs = edge_geometries[lhs_index];\n    const auto &rhs = edge_geometries[rhs_index];\n    BOOST_ASSERT(graph.GetEdgeData(lhs.edge).reversed != graph.GetEdgeData(rhs.edge).reversed);\n\n    const auto &entry = graph.GetEdgeData(lhs.edge).reversed ? rhs : lhs;\n    const auto opposite_bearing =\n        findClosestOppositeBearing(edge_geometries, entry.perceived_bearing);\n    const auto merged_bearing = findAngleBisector(rhs.perceived_bearing, lhs.perceived_bearing);\n\n    if (angularDeviation(angleBetween(opposite_bearing, entry.perceived_bearing), STRAIGHT_ANGLE) <\n        MAXIMAL_ALLOWED_NO_TURN_DEVIATION)\n    {\n        // In some intersections, turning roads can introduce artificial turns if we merge here.\n        // Consider a scenario like:\n        //\u00a0\n        //  a     .  g - f\n        //  |   .\n        //  | .\n        //  |.\n        // d-b--------e\n        //  |\n        //  c\n        //\u00a0\n        // Merging `bgf` and `be` would introduce an angle, even though d-b-e is perfectly straight\n        // We don't change the angle, if such an opposite road exists\n        return {false, entry.perceived_bearing};\n    }\n\n    if (neighbor_intersection)\n    {\n        // Check that the merged bearing makes both turns closer to straight line\n        const auto turn_angle_lhs = angleBetween(opposite_bearing, lhs.perceived_bearing);\n        const auto turn_angle_rhs = angleBetween(opposite_bearing, rhs.perceived_bearing);\n        const auto turn_angle_new = angleBetween(opposite_bearing, merged_bearing);\n\n        if (util::angularDeviation(turn_angle_lhs, STRAIGHT_ANGLE) <\n                util::angularDeviation(turn_angle_new, STRAIGHT_ANGLE) ||\n            util::angularDeviation(turn_angle_rhs, STRAIGHT_ANGLE) <\n                util::angularDeviation(turn_angle_new, STRAIGHT_ANGLE))\n            return {false, opposite_bearing};\n    }\n\n    return {true, merged_bearing};\n}\n\nbool isRoadsPairMergeable(const MergableRoadDetector &detector,\n                          const IntersectionEdgeGeometries &edge_geometries,\n                          const NodeID intersection_node,\n                          const std::size_t index)\n{\n    const auto size = edge_geometries.size();\n    BOOST_ASSERT(index < size);\n\n    const auto &llhs = edge_geometries[(index + size - 1) % size];\n    const auto &lhs = edge_geometries[index];\n    const auto &rhs = edge_geometries[(index + 1) % size];\n    const auto &rrhs = edge_geometries[(index + 2) % size];\n\n    // TODO: check IsDistinctFrom - it is an angle and name-only check\n    // also check CanMergeRoad for all merging scenarios\n    return detector.IsDistinctFrom({llhs.edge, llhs.perceived_bearing, llhs.length},\n                                   {lhs.edge, lhs.perceived_bearing, lhs.length}) &&\n           detector.CanMergeRoad(intersection_node,\n                                 {lhs.edge, lhs.perceived_bearing, lhs.length},\n                                 {rhs.edge, rhs.perceived_bearing, rhs.length}) &&\n           detector.IsDistinctFrom({rhs.edge, rhs.perceived_bearing, rhs.length},\n                                   {rrhs.edge, rrhs.perceived_bearing, rrhs.length});\n}\n\nauto getIntersectionLanes(const util::NodeBasedDynamicGraph &graph, const NodeID intersection_node)\n{\n    std::uint8_t max_lanes_intersection = 0;\n    for (auto outgoing_edge : graph.GetAdjacentEdgeRange(intersection_node))\n    {\n        max_lanes_intersection =\n            std::max(max_lanes_intersection,\n                     graph.GetEdgeData(outgoing_edge).flags.road_classification.GetNumberOfLanes());\n    }\n    return max_lanes_intersection;\n}\n\ntemplate <bool USE_CLOSE_COORDINATE>\nIntersectionEdgeGeometries\ngetIntersectionOutgoingGeometries(const util::NodeBasedDynamicGraph &graph,\n                                  const extractor::CompressedEdgeContainer &compressed_geometries,\n                                  const std::vector<util::Coordinate> &node_coordinates,\n                                  const NodeID intersection_node)\n{\n    IntersectionEdgeGeometries edge_geometries;\n\n    // TODO: keep CoordinateExtractor to reproduce bearings, simplify later\n    const CoordinateExtractor coordinate_extractor(graph, compressed_geometries, node_coordinates);\n\n    const auto max_lanes_intersection = getIntersectionLanes(graph, intersection_node);\n\n    // Collect outgoing edges\n    for (const auto outgoing_edge : graph.GetAdjacentEdgeRange(intersection_node))\n    {\n        const auto remote_node = graph.GetTarget(outgoing_edge);\n\n        const auto &geometry = getEdgeCoordinates(\n            compressed_geometries, node_coordinates, intersection_node, outgoing_edge, remote_node);\n\n        // OSRM_ASSERT(geometry.size() >= 2, node_coordinates[intersection_node]);\n\n        const auto close_coordinate =\n            coordinate_extractor.ExtractCoordinateAtLength(2. /*m*/, geometry);\n        const auto initial_bearing =\n            util::coordinate_calculation::bearing(geometry[0], close_coordinate);\n\n        const auto representative_coordinate =\n            USE_CLOSE_COORDINATE || graph.GetOutDegree(intersection_node) <= 2\n                ? coordinate_extractor.GetCoordinateCloseToTurn(\n                      intersection_node, outgoing_edge, false, remote_node)\n                : coordinate_extractor.ExtractRepresentativeCoordinate(intersection_node,\n                                                                       outgoing_edge,\n                                                                       false,\n                                                                       remote_node,\n                                                                       max_lanes_intersection,\n                                                                       geometry);\n        const auto perceived_bearing =\n            util::coordinate_calculation::bearing(geometry[0], representative_coordinate);\n\n        const auto edge_length = util::coordinate_calculation::getLength(\n            geometry.begin(), geometry.end(), util::coordinate_calculation::haversineDistance);\n\n        edge_geometries.push_back({outgoing_edge, initial_bearing, perceived_bearing, edge_length});\n    }\n\n    // Sort edges in the clockwise bearings order\n    std::sort(edge_geometries.begin(), edge_geometries.end(), [](const auto &lhs, const auto &rhs) {\n        return lhs.perceived_bearing < rhs.perceived_bearing;\n    });\n    return edge_geometries;\n}\n}\n\nstd::pair<IntersectionEdgeGeometries, std::unordered_set<EdgeID>>\ngetIntersectionGeometries(const util::NodeBasedDynamicGraph &graph,\n                          const extractor::CompressedEdgeContainer &compressed_geometries,\n                          const std::vector<util::Coordinate> &node_coordinates,\n                          const MergableRoadDetector &detector,\n                          const NodeID intersection_node)\n{\n    IntersectionEdgeGeometries edge_geometries = getIntersectionOutgoingGeometries<false>(\n        graph, compressed_geometries, node_coordinates, intersection_node);\n\n    const auto edges_number = edge_geometries.size();\n\n    std::vector<bool> merged_edges(edges_number, false);\n\n    // TODO: intersection views do not contain merged and not allowed edges\n    // but contain other restricted edges that are used in TurnAnalysis,\n    // to be deleted after TurnAnalysis refactoring\n    std::unordered_set<EdgeID> merged_edge_ids;\n\n    if (edges_number >= 3)\n    { // Adjust bearings of mergeable roads\n        for (std::size_t index = 0; index < edges_number; ++index)\n        {\n            if (isRoadsPairMergeable(detector, edge_geometries, intersection_node, index))\n            { // Merge bearings of roads left & right\n                const auto next = (index + 1) % edges_number;\n                auto &lhs = edge_geometries[index];\n                auto &rhs = edge_geometries[next];\n                merged_edges[index] = true;\n                merged_edges[next] = true;\n\n                const auto merge = findMergedBearing(graph, edge_geometries, index, next, false);\n\n                lhs.perceived_bearing = lhs.initial_bearing = merge.second;\n                rhs.perceived_bearing = rhs.initial_bearing = merge.second;\n\n                // Only one of the edges must be reversed, mark it as merged to remove from\n                // intersection view\n                BOOST_ASSERT(graph.GetEdgeData(lhs.edge).reversed ^\n                             graph.GetEdgeData(rhs.edge).reversed);\n                merged_edge_ids.insert(graph.GetEdgeData(lhs.edge).reversed ? lhs.edge : rhs.edge);\n            }\n        }\n    }\n\n    if (edges_number >= 2)\n    { // Adjust bearings of roads that will be merged at the neighbor intersections\n        const double constexpr PRUNING_DISTANCE = 30.;\n\n        for (std::size_t index = 0; index < edges_number; ++index)\n        {\n            auto &edge_geometry = edge_geometries[index];\n\n            // Don't adjust bearings of roads that were merged at the current intersection\n            // or have neighbor intersection farer than the pruning distance\n            if (merged_edges[index] || edge_geometry.length > PRUNING_DISTANCE)\n                continue;\n\n            const auto neighbor_intersection_node = graph.GetTarget(edge_geometry.edge);\n\n            const auto neighbor_geometries = getIntersectionOutgoingGeometries<false>(\n                graph, compressed_geometries, node_coordinates, neighbor_intersection_node);\n\n            const auto neighbor_edges = neighbor_geometries.size();\n            if (neighbor_edges <= 1)\n                continue;\n\n            const auto neighbor_curr = std::distance(\n                neighbor_geometries.begin(),\n                std::find_if(neighbor_geometries.begin(),\n                             neighbor_geometries.end(),\n                             [&graph, &intersection_node](const auto &road) {\n                                 return graph.GetTarget(road.edge) == intersection_node;\n                             }));\n            BOOST_ASSERT(static_cast<std::size_t>(neighbor_curr) != neighbor_geometries.size());\n            const auto neighbor_prev = (neighbor_curr + neighbor_edges - 1) % neighbor_edges;\n            const auto neighbor_next = (neighbor_curr + 1) % neighbor_edges;\n\n            if (isRoadsPairMergeable(\n                    detector, neighbor_geometries, neighbor_intersection_node, neighbor_prev))\n            { // Neighbor intersection has mergable neighbor_prev and neighbor_curr roads\n                BOOST_ASSERT(!isRoadsPairMergeable(\n                    detector, neighbor_geometries, neighbor_intersection_node, neighbor_curr));\n\n                // TODO: merge with an angle bisector, but not a reversed closed turn, to be\n                // checked as a difference with the previous implementation\n                const auto merge = findMergedBearing(\n                    graph, neighbor_geometries, neighbor_prev, neighbor_curr, true);\n\n                if (merge.first)\n                {\n                    const auto offset = util::angularDeviation(\n                        merge.second, neighbor_geometries[neighbor_curr].perceived_bearing);\n\n                    // Adjust bearing of AB at the node A if at the node B roads BA (neighbor_curr)\n                    // and BC (neighbor_prev) will be merged and will have merged bearing Bb.\n                    // The adjustment value is \u2220bBA with negative sign (counter-clockwise) to Aa\n                    //     A ~~~ a\n                    //       \\\u00a0\n                    //  b --- B ---\n                    //       /\n                    //     C\n                    edge_geometry.perceived_bearing = edge_geometry.initial_bearing =\n                        std::fmod(edge_geometry.perceived_bearing + 360. - offset, 360.);\n                }\n            }\n            else if (isRoadsPairMergeable(\n                         detector, neighbor_geometries, neighbor_intersection_node, neighbor_curr))\n            { // Neighbor intersection has mergable neighbor_curr and neighbor_next roads\n                BOOST_ASSERT(!isRoadsPairMergeable(\n                    detector, neighbor_geometries, neighbor_intersection_node, neighbor_prev));\n\n                // TODO: merge with an angle bisector, but not a reversed closed turn, to be\n                // checked as a difference with the previous implementation\n                const auto merge = findMergedBearing(\n                    graph, neighbor_geometries, neighbor_curr, neighbor_next, true);\n                if (merge.first)\n                {\n                    const auto offset = util::angularDeviation(\n                        merge.second, neighbor_geometries[neighbor_curr].perceived_bearing);\n\n                    // Adjust bearing of AB at the node A if at the node B roads BA (neighbor_curr)\n                    // and BC (neighbor_next) will be merged and will have merged bearing Bb.\n                    // The adjustment value is \u2220bBA with positive sign (clockwise) to Aa\n                    //     a ~~~ A\n                    //         /\n                    //    --- B --- b\n                    //         \\\u00a0\n                    //          C\n                    edge_geometry.perceived_bearing = edge_geometry.initial_bearing =\n                        std::fmod(edge_geometry.perceived_bearing + offset, 360.);\n                }\n            }\n        }\n    }\n\n    // Add incoming edges with reversed bearings\n    edge_geometries.resize(2 * edges_number);\n    for (std::size_t index = 0; index < edges_number; ++index)\n    {\n        const auto &geometry = edge_geometries[index];\n        const auto remote_node = graph.GetTarget(geometry.edge);\n        const auto incoming_edge = graph.FindEdge(remote_node, intersection_node);\n        edge_geometries[edges_number + index] = {incoming_edge,\n                                                 util::bearing::reverse(geometry.initial_bearing),\n                                                 util::bearing::reverse(geometry.perceived_bearing),\n                                                 geometry.length};\n    }\n\n    // Enforce ordering of edges by IDs\n    std::sort(edge_geometries.begin(), edge_geometries.end());\n\n    return std::make_pair(edge_geometries, merged_edge_ids);\n}\n\ninline auto findEdge(const IntersectionEdgeGeometries &geometries, const EdgeID &edge)\n{\n    const auto it = std::lower_bound(\n        geometries.begin(), geometries.end(), edge, [](const auto &geometry, const auto edge) {\n            return geometry.edge < edge;\n        });\n    BOOST_ASSERT(it != geometries.end() && it->edge == edge);\n    return it;\n}\n\ndouble findEdgeBearing(const IntersectionEdgeGeometries &geometries, const EdgeID &edge)\n{\n    return findEdge(geometries, edge)->perceived_bearing;\n}\n\ndouble findEdgeLength(const IntersectionEdgeGeometries &geometries, const EdgeID &edge)\n{\n    return findEdge(geometries, edge)->length;\n}\n\ntemplate <typename RestrictionsRange>\nbool isTurnRestricted(const RestrictionsRange &restrictions, const NodeID to)\n{\n    // Check turn restrictions to find a node that is the only allowed target when coming from a\n    // node to an intersection\n    //     d\n    //     |\n    // a - b - c  and `only_straight_on ab | bc would return `c` for `a,b`\n    const auto is_only = std::find_if(restrictions.first,\n                                      restrictions.second,\n                                      [](const auto &pair) { return pair.second->is_only; });\n    if (is_only != restrictions.second)\n        return is_only->second->AsNodeRestriction().to != to;\n\n    // Check if explicitly forbidden\n    const auto no_turn =\n        std::find_if(restrictions.first, restrictions.second, [&to](const auto &restriction) {\n            return restriction.second->AsNodeRestriction().to == to;\n        });\n\n    return no_turn != restrictions.second;\n}\n\nbool isTurnAllowed(const util::NodeBasedDynamicGraph &graph,\n                   const EdgeBasedNodeDataContainer &node_data_container,\n                   const RestrictionMap &restriction_map,\n                   const std::unordered_set<NodeID> &barrier_nodes,\n                   const IntersectionEdgeGeometries &geometries,\n                   const TurnLanesIndexedArray &turn_lanes_data,\n                   const IntersectionEdge &from,\n                   const IntersectionEdge &to)\n{\n    BOOST_ASSERT(graph.GetTarget(from.edge) == to.node);\n\n    // TODO: to use TurnAnalysis all outgoing edges are required, to be removed later\n    if (graph.GetEdgeData(from.edge).reversed || graph.GetEdgeData(to.edge).reversed)\n        return false;\n\n    const auto intersection_node = to.node;\n    const auto destination_node = graph.GetTarget(to.edge);\n    auto const &restrictions = restriction_map.Restrictions(from.node, intersection_node);\n\n    // Check if turn is explicitly restricted by a turn restriction\n    if (isTurnRestricted(restrictions, destination_node))\n        return false;\n\n    // Precompute reversed bearing of the `from` edge\n    const auto from_edge_reversed_bearing =\n        util::bearing::reverse(findEdgeBearing(geometries, from.edge));\n\n    // Collect some information about the intersection\n    // 1) number of allowed exits and adjacent bidirectional edges\n    std::uint32_t allowed_exits = 0, bidirectional_edges = 0;\n    // 2) edge IDs of roundabouts edges\n    EdgeID roundabout_from = SPECIAL_EDGEID, roundabout_to = SPECIAL_EDGEID;\n    double roundabout_from_angle = 0., roundabout_to_angle = 0.;\n\n    for (const auto eid : graph.GetAdjacentEdgeRange(intersection_node))\n    {\n        const auto &edge_data = graph.GetEdgeData(eid);\n        const auto &edge_class = edge_data.flags;\n        const auto to_node = graph.GetTarget(eid);\n        const auto reverse_edge = graph.FindEdge(to_node, intersection_node);\n        BOOST_ASSERT(reverse_edge != SPECIAL_EDGEID);\n\n        const auto is_exit_edge = !edge_data.reversed && !isTurnRestricted(restrictions, to_node);\n        const auto is_bidirectional = !graph.GetEdgeData(reverse_edge).reversed;\n        allowed_exits += is_exit_edge;\n        bidirectional_edges += is_bidirectional;\n\n        if (edge_class.roundabout || edge_class.circular)\n        {\n            if (edge_data.reversed)\n            {\n                // \"Linked Roundabouts\" is an example of tie between two linked roundabouts\n                // A tie breaker for that maximizes \u2220(roundabout_from_bearing, \u00acfrom_edge_bearing)\n                const auto angle = util::bearing::angleBetween(\n                    findEdgeBearing(geometries, reverse_edge), from_edge_reversed_bearing);\n                if (angle > roundabout_from_angle)\n                {\n                    roundabout_from = reverse_edge;\n                    roundabout_from_angle = angle;\n                }\n            }\n            else\n            {\n                // a tie breaker that maximizes \u2220(\u00acfrom_edge_bearing, roundabout_to_bearing)\n                const auto angle = util::bearing::angleBetween(from_edge_reversed_bearing,\n                                                               findEdgeBearing(geometries, eid));\n                if (angle > roundabout_to_angle)\n                {\n                    roundabout_to = eid;\n                    roundabout_to_angle = angle;\n                }\n            }\n        }\n    }\n\n    // 3) if the intersection has a barrier\n    const bool is_barrier_node = barrier_nodes.find(intersection_node) != barrier_nodes.end();\n\n    // Check a U-turn\n    if (from.node == destination_node)\n    {\n        // Allow U-turns before barrier nodes\n        if (is_barrier_node)\n            return true;\n\n        // Allow U-turns at dead-ends\n        if (graph.GetAdjacentEdgeRange(intersection_node).size() == 1)\n            return true;\n\n        // Allow U-turns at dead-ends if there is at most one bidirectional road at the intersection\n        // The condition allows U-turns d\u2192a\u2192d and c\u2192b\u2192c (\"Bike - Around the Block\" test)\n        //   a\u2192b\n        //   \u2195 \u2195\n        //   d\u2194c\n        if (allowed_exits == 1 || bidirectional_edges <= 1)\n            return true;\n\n        // Allow U-turn if the incoming edge has a U-turn lane\n        // TODO: revisit the use-case, related PR #2753\n        const auto &incoming_edge_annotation_id = graph.GetEdgeData(from.edge).annotation_data;\n        const auto lane_description_id = static_cast<std::size_t>(\n            node_data_container.GetAnnotation(incoming_edge_annotation_id).lane_description_id);\n        if (lane_description_id != INVALID_LANE_DESCRIPTIONID)\n        {\n            const auto &turn_lane_offsets = std::get<0>(turn_lanes_data);\n            const auto &turn_lanes = std::get<1>(turn_lanes_data);\n            BOOST_ASSERT(lane_description_id + 1 < turn_lane_offsets.size());\n\n            if (std::any_of(turn_lanes.begin() + turn_lane_offsets[lane_description_id],\n                            turn_lanes.begin() + turn_lane_offsets[lane_description_id + 1],\n                            [](const auto &lane) { return lane & TurnLaneType::uturn; }))\n                return true;\n        }\n\n        // Don't allow U-turns on usual intersections\n        return false;\n    }\n\n    // Don't allow turns via barriers for not U-turn maneuvers\n    if (is_barrier_node)\n        return false;\n\n    // Check for roundabouts exits in the opposite direction of roundabout flow\n    if (roundabout_from != SPECIAL_EDGEID && roundabout_to != SPECIAL_EDGEID)\n    {\n        // Get bearings of edges\n        const auto roundabout_from_bearing = findEdgeBearing(geometries, roundabout_from);\n        const auto roundabout_to_bearing = findEdgeBearing(geometries, roundabout_to);\n        const auto to_edge_bearing = findEdgeBearing(geometries, to.edge);\n\n        // Get angles from the roundabout edge to three other edges\n        const auto roundabout_angle =\n            util::bearing::angleBetween(roundabout_from_bearing, roundabout_to_bearing);\n        const auto roundabout_from_angle =\n            util::bearing::angleBetween(roundabout_from_bearing, from_edge_reversed_bearing);\n        const auto roundabout_to_angle =\n            util::bearing::angleBetween(roundabout_from_bearing, to_edge_bearing);\n\n        // Restrict turning over a roundabout if `roundabout_to_angle` is in\n        // a sector between `roundabout_from_bearing` to `from_bearing` (shaded area)\n        //\n        //    roundabout_angle = 270\u00b0         roundabout_angle = 90\u00b0\n        //  roundabout_from_angle = 150\u00b0    roundabout_from_angle = 150\u00b0\n        //   roundabout_to_angle = 90\u00b0       roundabout_to_angle = 270\u00b0\n        //\n        //             150\u00b0                            150\u00b0\n        //              v\u2591\u2591\u2591\u2591\u2591\u2591                \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591v\n        //             v\u2591\u2591\u2591\u2591\u2591\u2591\u2591                \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591v\n        // 270\u00b0 <-ooo- v -ttt-> 90\u00b0       270\u00b0 <-ttt- v -ooo-> 90\u00b0\n        //             ^\u2591\u2591\u2591\u2591\u2591\u2591\u2591                \u2591\u2591\u2591\u2591\u2591\u2591\u2591^\n        //             r\u2591\u2591\u2591\u2591\u2591\u2591\u2591                \u2591\u2591\u2591\u2591\u2591\u2591\u2591r\n        //             r\u2591\u2591\u2591\u2591\u2591\u2591\u2591                \u2591\u2591\u2591\u2591\u2591\u2591\u2591r\n        if ((roundabout_from_angle < roundabout_angle &&\n             roundabout_to_angle < roundabout_from_angle) ||\n            (roundabout_from_angle > roundabout_angle &&\n             roundabout_to_angle > roundabout_from_angle))\n            return false;\n    }\n\n    return true;\n}\n\n// The function adapts intersection geometry data to TurnAnalysis\nIntersectionView convertToIntersectionView(const util::NodeBasedDynamicGraph &graph,\n                                           const EdgeBasedNodeDataContainer &node_data_container,\n                                           const RestrictionMap &restriction_map,\n                                           const std::unordered_set<NodeID> &barrier_nodes,\n                                           const IntersectionEdgeGeometries &edge_geometries,\n                                           const TurnLanesIndexedArray &turn_lanes_data,\n                                           const IntersectionEdge &incoming_edge,\n                                           const IntersectionEdges &outgoing_edges,\n                                           const std::unordered_set<EdgeID> &merged_edges)\n{\n    using util::bearing::angleBetween;\n\n    const auto edge_it = findEdge(edge_geometries, incoming_edge.edge);\n    const auto incoming_bearing = edge_it->perceived_bearing;\n    const auto initial_incoming_bearing = edge_it->initial_bearing;\n\n    using IntersectionViewDataWithAngle = std::pair<IntersectionViewData, double>;\n    std::vector<IntersectionViewDataWithAngle> pre_intersection_view;\n    IntersectionViewData uturn{{SPECIAL_EDGEID, 0., 0.}, false, 0.};\n    std::size_t allowed_uturns_number = 0;\n    for (const auto &outgoing_edge : outgoing_edges)\n    {\n        const auto is_uturn = [](const auto angle) {\n            return std::fabs(angle) < std::numeric_limits<double>::epsilon();\n        };\n\n        const auto edge_it = findEdge(edge_geometries, outgoing_edge.edge);\n        const auto segment_length = edge_it->length;\n        const auto is_merged = merged_edges.count(outgoing_edge.edge) != 0;\n        const auto is_turn_allowed = intersection::isTurnAllowed(graph,\n                                                                 node_data_container,\n                                                                 restriction_map,\n                                                                 barrier_nodes,\n                                                                 edge_geometries,\n                                                                 turn_lanes_data,\n                                                                 incoming_edge,\n                                                                 outgoing_edge);\n\n        // Compute angles\n        const auto outgoing_bearing = edge_it->perceived_bearing;\n        const auto initial_outgoing_bearing = edge_it->initial_bearing;\n        auto turn_angle = std::fmod(\n            std::round(angleBetween(incoming_bearing, outgoing_bearing) * 1e8) / 1e8, 360.);\n        auto initial_angle = angleBetween(initial_incoming_bearing, initial_outgoing_bearing);\n\n        // If angle of the allowed turn is in a neighborhood of 0\u00b0 (\u00b115\u00b0) but the initial OSM angle\n        // is in the opposite semi-plane then assume explicitly a U-turn to avoid incorrect\n        // adjustments due to numerical noise in selection of representative_coordinate\n        if (is_turn_allowed &&\n            ((turn_angle < 15 && initial_angle > 180) || (turn_angle > 345 && initial_angle < 180)))\n        {\n            turn_angle = 0;\n            initial_angle = 0;\n        }\n\n        const auto is_uturn_angle = is_uturn(turn_angle);\n\n        IntersectionViewData road{\n            {outgoing_edge.edge, outgoing_bearing, segment_length}, is_turn_allowed, turn_angle};\n\n        if (graph.GetTarget(outgoing_edge.edge) == incoming_edge.node)\n        { // Save the true U-turn road to add later if no allowed U-turns will be added\n            uturn = road;\n        }\n        else if (is_turn_allowed || (!is_merged && !is_uturn_angle))\n        { // Add roads that have allowed entry or not U-turns and not merged\n            allowed_uturns_number += is_uturn_angle;\n\n            // Adjust computed initial turn angle for non-U-turn road edge cases:\n            // 1) use 0\u00b0 or 360\u00b0 if the road has 0\u00b0 initial angle\n            // 2) use turn angle if the smallest arc between turn and initial angles passes 0\u00b0\n            const auto use_turn_angle = (turn_angle > 270 && initial_angle < 90) ||\n                                        (turn_angle < 90 && initial_angle > 270);\n            const auto adjusted_angle = is_uturn(initial_angle)\n                                            ? (turn_angle > 180. ? 360. : 0.)\n                                            : use_turn_angle ? turn_angle : initial_angle;\n            pre_intersection_view.push_back({road, adjusted_angle});\n        }\n    }\n\n    BOOST_ASSERT(uturn.eid != SPECIAL_EDGEID);\n    if (uturn.entry_allowed || allowed_uturns_number == 0)\n    { // Add the true U-turn if it is allowed or no other U-turns found\n        pre_intersection_view.insert(pre_intersection_view.begin(), {uturn, 0});\n    }\n\n    // Order roads in counter-clockwise order starting from the U-turn edge in the OSM order\n    std::stable_sort(pre_intersection_view.begin(),\n                     pre_intersection_view.end(),\n                     [](const auto &lhs, const auto &rhs) {\n                         return std::tie(lhs.second, lhs.first.angle) <\n                                std::tie(rhs.second, rhs.first.angle);\n                     });\n\n    // Adjust perceived bearings to keep the initial OSM order with respect to the first edge\n    for (auto curr = pre_intersection_view.begin(), next = std::next(curr);\n         next != pre_intersection_view.end();\n         ++curr, ++next)\n    {\n        // Check that the perceived angles order is the same as the initial OSM one\n        if (next->first.angle < curr->first.angle)\n        { // If the true bearing is out of the initial order (next before current) then\n            // adjust the next road angle to keep the order. The adjustment angle is at most\n            // 0.5\u00b0 or a half-angle between the current angle and 360\u00b0 to prevent overlapping\n            const auto angle_adjustment =\n                std::min(.5, util::restrictAngleToValidRange(360. - curr->first.angle) / 2.);\n            next->first.angle =\n                util::restrictAngleToValidRange(curr->first.angle + angle_adjustment);\n        }\n    }\n\n    // Copy intersection view data\n    IntersectionView intersection_view;\n    intersection_view.reserve(pre_intersection_view.size());\n    std::transform(pre_intersection_view.begin(),\n                   pre_intersection_view.end(),\n                   std::back_inserter(intersection_view),\n                   [](const auto &road) { return road.first; });\n\n    return intersection_view;\n}\n\n//                                               a\n//                                               |\n//                                               |\n//                                               v\n// For an intersection from_node --via_eid--> turn_node ----> c\n//                                               ^\n//                                               |\n//                                               |\n//                                               b\n// This functions returns _all_ turns as if the graph was undirected.\n// That means we not only get (from_node, turn_node, c) in the above example\n// but also (from_node, turn_node, a), (from_node, turn_node, b). These turns are\n// marked as invalid and only needed for intersection classification.\ntemplate <bool USE_CLOSE_COORDINATE>\nIntersectionView getConnectedRoads(const util::NodeBasedDynamicGraph &graph,\n                                   const EdgeBasedNodeDataContainer &node_data_container,\n                                   const std::vector<util::Coordinate> &node_coordinates,\n                                   const extractor::CompressedEdgeContainer &compressed_geometries,\n                                   const RestrictionMap &node_restriction_map,\n                                   const std::unordered_set<NodeID> &barrier_nodes,\n                                   const TurnLanesIndexedArray &turn_lanes_data,\n                                   const IntersectionEdge &incoming_edge)\n{\n    const auto intersection_node = graph.GetTarget(incoming_edge.edge);\n    const auto &outgoing_edges = intersection::getOutgoingEdges(graph, intersection_node);\n    auto edge_geometries = getIntersectionOutgoingGeometries<USE_CLOSE_COORDINATE>(\n        graph, compressed_geometries, node_coordinates, intersection_node);\n\n    // Add incoming edges with reversed bearings\n    const auto edges_number = edge_geometries.size();\n    edge_geometries.resize(2 * edges_number);\n    for (std::size_t index = 0; index < edges_number; ++index)\n    {\n        const auto &geometry = edge_geometries[index];\n        const auto remote_node = graph.GetTarget(geometry.edge);\n        const auto incoming_edge = graph.FindEdge(remote_node, intersection_node);\n        edge_geometries[edges_number + index] = {incoming_edge,\n                                                 util::bearing::reverse(geometry.initial_bearing),\n                                                 util::bearing::reverse(geometry.perceived_bearing),\n                                                 geometry.length};\n    }\n\n    // Enforce ordering of edges by IDs\n    std::sort(edge_geometries.begin(), edge_geometries.end());\n\n    return convertToIntersectionView(graph,\n                                     node_data_container,\n                                     node_restriction_map,\n                                     barrier_nodes,\n                                     edge_geometries,\n                                     turn_lanes_data,\n                                     incoming_edge,\n                                     outgoing_edges,\n                                     std::unordered_set<EdgeID>());\n}\n\ntemplate IntersectionView\ngetConnectedRoads<false>(const util::NodeBasedDynamicGraph &graph,\n                         const EdgeBasedNodeDataContainer &node_data_container,\n                         const std::vector<util::Coordinate> &node_coordinates,\n                         const extractor::CompressedEdgeContainer &compressed_geometries,\n                         const RestrictionMap &node_restriction_map,\n                         const std::unordered_set<NodeID> &barrier_nodes,\n                         const TurnLanesIndexedArray &turn_lanes_data,\n                         const IntersectionEdge &incoming_edge);\n\ntemplate IntersectionView\ngetConnectedRoads<true>(const util::NodeBasedDynamicGraph &graph,\n                        const EdgeBasedNodeDataContainer &node_data_container,\n                        const std::vector<util::Coordinate> &node_coordinates,\n                        const extractor::CompressedEdgeContainer &compressed_geometries,\n                        const RestrictionMap &node_restriction_map,\n                        const std::unordered_set<NodeID> &barrier_nodes,\n                        const TurnLanesIndexedArray &turn_lanes_data,\n                        const IntersectionEdge &incoming_edge);\n\nIntersectionEdge skipDegreeTwoNodes(const util::NodeBasedDynamicGraph &graph, IntersectionEdge road)\n{\n    std::unordered_set<NodeID> visited_nodes;\n    (void)visited_nodes;\n\n    // Skip trivial nodes without generating the intersection in between, stop at the very first\n    // intersection of degree > 2\n    const auto starting_node = road.node;\n    auto next_node = graph.GetTarget(road.edge);\n    while (graph.GetOutDegree(next_node) == 2 && next_node != starting_node)\n    {\n        BOOST_ASSERT(visited_nodes.insert(next_node).second);\n        const auto next_edge = graph.BeginEdges(next_node);\n        road.edge = graph.GetTarget(next_edge) == road.node ? next_edge + 1 : next_edge;\n        road.node = next_node;\n        next_node = graph.GetTarget(road.edge);\n    }\n\n    return road;\n}\n}\n}\n}\n", "meta": {"hexsha": "a8e7692530507a76c58b307706c4c1ac14424eb4", "size": 39284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extractor/intersection/intersection_analysis.cpp", "max_stars_repo_name": "aweatherlycap1/osrm-backend", "max_stars_repo_head_hexsha": "31d6d74f90fa760aa8d1f312c2593dabcbc9a69b", "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/extractor/intersection/intersection_analysis.cpp", "max_issues_repo_name": "aweatherlycap1/osrm-backend", "max_issues_repo_head_hexsha": "31d6d74f90fa760aa8d1f312c2593dabcbc9a69b", "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/extractor/intersection/intersection_analysis.cpp", "max_forks_repo_name": "aweatherlycap1/osrm-backend", "max_forks_repo_head_hexsha": "31d6d74f90fa760aa8d1f312c2593dabcbc9a69b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-23T22:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T22:49:07.000Z", "avg_line_length": 46.7666666667, "max_line_length": 100, "alphanum_fraction": 0.6043681906, "num_tokens": 7921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18949864441711325}}
{"text": "#include \"pcl_ros/point_cloud.h\"\n#include <Eigen/Dense>\n#include <dynamic_reconfigure/server.h>\n#include <laser_geometry/laser_geometry.h>\n#include <laserscan_merger/laserscan_mergerConfig.h>\n#include <pcl/conversions.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl_ros/transforms.h>\n#include <ros/ros.h>\n#include <sensor_msgs/LaserScan.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/point_cloud_conversion.h>\n#include <string.h>\n#include <tf/transform_listener.h>\n#include <tf2_ros/buffer.h>\n#include <tf2_ros/transform_listener.h>\n\nusing namespace std;\nusing namespace pcl;\nusing namespace laserscan_merger;\n\nclass LaserscanMerger {\npublic:\n  LaserscanMerger(ros::NodeHandle &n, tf2_ros::Buffer *tf);\n  void scanCallback(const sensor_msgs::LaserScan::ConstPtr &scan,\n                    std::string topic);\n  void pointcloud_to_laserscan(Eigen::MatrixXf points,\n                               pcl::PCLPointCloud2 *merged_cloud);\n  void reconfigureCallback(laserscan_mergerConfig &config, uint32_t level);\n\nprivate:\n  ros::NodeHandle node_;\n  laser_geometry::LaserProjection projector_;\n  tf2_ros::Buffer *tf_buffer_;\n  // tf::TransformListener tf_listener_;\n\n  ros::Publisher point_cloud_publisher_;\n  ros::Publisher laser_scan_publisher_;\n  vector<ros::Subscriber> scan_subscribers_;\n  vector<bool> clouds_modified_;\n\n  vector<pcl::PCLPointCloud2> clouds_;\n  vector<string> input_topics_;\n\n  void laserscan_topic_parser();\n\n  double angle_min_;\n  double angle_max_;\n  double angle_increment_;\n  double time_increment_;\n  double scan_time_;\n  double range_min_;\n  double range_max_;\n\n  string destination_frame_;\n  string cloud_destination_topic_;\n  string scan_destination_topic_;\n  string laserscan_topics_;\n};\n\nvoid LaserscanMerger::reconfigureCallback(laserscan_mergerConfig &config,\n                                          uint32_t level) {\n  this->angle_min_ = config.angle_min;\n  this->angle_max_ = config.angle_max;\n  this->angle_increment_ = config.angle_increment;\n  this->time_increment_ = config.time_increment;\n  this->scan_time_ = config.scan_time;\n  this->range_min_ = config.range_min;\n  this->range_max_ = config.range_max;\n}\n\nLaserscanMerger::LaserscanMerger(ros::NodeHandle &n, tf2_ros::Buffer *tf) {\n  ros::NodeHandle nh(\"~\");\n  node_ = n;\n  tf_buffer_ = tf;\n  // tf2_ros::TransformListener tf_listener(tf_buffer_);\n\n  nh.param<std::string>(\"destination_frame\", destination_frame_, \"cart_frame\");\n  nh.param<std::string>(\"cloud_destination_topic\", cloud_destination_topic_,\n                        \"/merged_cloud\");\n  nh.param<std::string>(\"scan_destination_topic\", scan_destination_topic_,\n                        \"/scan_multi\");\n  nh.param<std::string>(\"laserscan_topics\", laserscan_topics_, \"\");\n  nh.param(\"angle_min\", angle_min_, -2.36);\n  nh.param(\"angle_max\", angle_max_, 2.36);\n  nh.param(\"angle_increment\", angle_increment_, 0.0058);\n  nh.param(\"scan_time\", scan_time_, 0.0333333);\n  nh.param(\"range_min\", range_min_, 0.45);\n  nh.param(\"range_max\", range_max_, 25.0);\n\n  this->laserscan_topic_parser();\n\n  point_cloud_publisher_ = node_.advertise<sensor_msgs::PointCloud2>(\n      cloud_destination_topic_.c_str(), 1, false);\n  laser_scan_publisher_ = node_.advertise<sensor_msgs::LaserScan>(\n      scan_destination_topic_.c_str(), 1, false);\n}\n\nvoid LaserscanMerger::laserscan_topic_parser() {\n  // LaserScan topics to subscribe\n  ros::master::V_TopicInfo topics;\n  ros::master::getTopics(topics);\n\n  istringstream iss(laserscan_topics_);\n  vector<string> tokens;\n  copy(istream_iterator<string>(iss), istream_iterator<string>(),\n       back_inserter<vector<string>>(tokens));\n  vector<string> tmp_input_topics;\n  for (int i = 0; i < tokens.size(); ++i) {\n    for (int j = 0; j < topics.size(); ++j) {\n      if ((tokens[i].compare(topics[j].name) == 0) &&\n          (topics[j].datatype.compare(\"sensor_msgs/LaserScan\") == 0)) {\n        tmp_input_topics.push_back(topics[j].name);\n      }\n    }\n  }\n\n  sort(tmp_input_topics.begin(), tmp_input_topics.end());\n  std::vector<string>::iterator last =\n      std::unique(tmp_input_topics.begin(), tmp_input_topics.end());\n  tmp_input_topics.erase(last, tmp_input_topics.end());\n\n  // Do not re-subscribe if the topics are the same\n  if ((tmp_input_topics.size() != input_topics_.size()) ||\n      !equal(tmp_input_topics.begin(), tmp_input_topics.end(),\n             input_topics_.begin())) {\n\n    // Unsubscribe from previous topics\n    for (int i = 0; i < scan_subscribers_.size(); ++i)\n      scan_subscribers_[i].shutdown();\n\n    input_topics_ = tmp_input_topics;\n    if (input_topics_.size() > 0) {\n      scan_subscribers_.resize(input_topics_.size());\n      clouds_modified_.resize(input_topics_.size());\n      clouds_.resize(input_topics_.size());\n      ROS_INFO(\"Subscribing to topics\\t%ld\", scan_subscribers_.size());\n      for (int i = 0; i < input_topics_.size(); ++i) {\n        scan_subscribers_[i] = node_.subscribe<sensor_msgs::LaserScan>(\n            input_topics_[i].c_str(), 1,\n            boost::bind(&LaserscanMerger::scanCallback, this, _1,\n                        input_topics_[i]));\n        clouds_modified_[i] = false;\n        cout << input_topics_[i] << \" \";\n      }\n    } else\n      ROS_INFO(\"Not subscribed to any topic.\");\n  }\n}\n\nvoid LaserscanMerger::scanCallback(const sensor_msgs::LaserScan::ConstPtr &scan,\n                                   std::string topic) {\n\n  // Verify that TF knows how to transform from the received scan to the\n  // destination scan frame\n  /*tfListener_.waitForTransform(scan->header.frame_id.c_str(),\n                               destination_frame_.c_str(), scan->header.stamp,\n                               ros::Duration(1));\n  projector_.transformLaserScanToPointCloud(\n      scan->header.frame_id, *scan, tmpCloud1, tfListener_,\n      laser_geometry::channel_option::Distance);\n  try {\n    tfListener_.transformPointCloud(destination_frame_.c_str(), tmpCloud1,\n                                    tmpCloud2);\n  } catch (tf::TransformException ex) {\n    ROS_ERROR(\"%s\", ex.what());\n    return;\n  }*/\n\n  // Verify that TF knows how to transform from the received scan to the\n  // destination scan frame\n  // tf_buffer_.waitForTransform(destination_frame_.c_str(),\n  // scan->header.frame_id.c_str(), scan->header.stamp, ros::Duration(1));\n  // printf(\"Received topic %s in the frame %s\\n\", topic.c_str(),\n  //       scan->header.frame_id.c_str());\n  bool ok = true;\n  try {\n    bool ok = tf_buffer_->canTransform(\n        destination_frame_.c_str(), scan->header.frame_id.c_str(),\n        scan->header.stamp +\n            ros::Duration().fromSec(scan->ranges.size() * scan->time_increment),\n        ros::Duration(1.0));\n  } catch (tf2::TransformException &ex) {\n    ROS_ERROR(\"tranformException. Could NOT transform from %s to %s: %s\",\n              scan->header.frame_id.c_str(), destination_frame_.c_str(),\n              ex.what());\n    return;\n  } catch (tf2::LookupException &ex) {\n    ROS_ERROR(\"LookupException. Could NOT transform from %s to %s: %s\",\n              scan->header.frame_id.c_str(), destination_frame_.c_str(),\n              ex.what());\n  }\n  if (!ok) {\n    ROS_ERROR(\"Could NOT transform from %s to %s.\",\n              scan->header.frame_id.c_str(), destination_frame_.c_str());\n    return;\n  }\n\n  // The concatenation of pointclouds (pcl::concatena) is giving me problems\n  // because of different fiels in the pointclouds. And using the\n  // channel_options in the transformLaserScanToPointCloud is not working\n  // properly. So, I'm filling the intensity field in all the scans.\n  sensor_msgs::LaserScan laser = *scan;\n  if (scan->intensities.empty())\n    laser.intensities.resize(scan->ranges.size(), 0.0);\n\n  sensor_msgs::PointCloud2 cloud;\n  // sensor_msgs::PointCloud cloud;\n  if (scan->header.frame_id != destination_frame_) {\n    try {\n      projector_.transformLaserScanToPointCloud(\n          destination_frame_, laser, cloud,\n          *tf_buffer_); // laser_geometry::channel_option::Distance\n      // | None | Intensity\n      // projector_.transformLaserScanToPointCloud(destination_frame_, laser,\n      //                                          cloud, tf_listener_);\n    } catch (const std::exception &ex) {\n      ROS_ERROR(\"[%s] Topic: %s. Error transforming laser to point cloud in \"\n                \"other frame: %s\",\n                topic.c_str(), ros::this_node::getName().c_str(), ex.what());\n      return;\n    }\n  } else {\n    try {\n      projector_.projectLaser(laser, cloud);\n    } catch (const std::exception &ex) {\n      ROS_ERROR(\"[%s] Error projecting laser to point cloud: %s\",\n                ros::this_node::getName().c_str(), ex.what());\n      return;\n    }\n  }\n\n  for (int i = 0; i < input_topics_.size(); ++i) {\n    if (topic.compare(input_topics_[i]) == 0) {\n      // sensor_msgs::convertPointCloudToPointCloud2(tmpCloud2, tmpCloud3);\n      pcl_conversions::toPCL(cloud, clouds_[i]);\n      clouds_modified_[i] = true;\n    }\n  }\n\n  // Count how many scans we have\n  int totalClouds = 0;\n  for (int i = 0; i < clouds_modified_.size(); ++i)\n    if (clouds_modified_[i])\n      ++totalClouds;\n\n  // Go ahead only if all subscribed scans have arrived\n  if (totalClouds == clouds_modified_.size()) {\n    pcl::PCLPointCloud2 merged_cloud = clouds_[0];\n    clouds_modified_[0] = false;\n\n    for (int i = 1; i < clouds_modified_.size(); ++i) {\n      pcl::concatenatePointCloud(merged_cloud, clouds_[i],\n                                 merged_cloud); // Deprecated\n\n      // if (!pcl::concatenate(merged_cloud, clouds[i],\n      // merged_cloud))\n      //  ROS_ERROR(\"[%s] Concatenate pointclouds failed!\",\n      //            ros::this_node::getName().c_str());\n      // merged_cloud += clouds_[i];\n      clouds_modified_[i] = false;\n    }\n\n    point_cloud_publisher_.publish(merged_cloud);\n\n    Eigen::MatrixXf points;\n    getPointCloudAsEigen(merged_cloud, points);\n\n    pointcloud_to_laserscan(points, &merged_cloud);\n  }\n}\n\nvoid LaserscanMerger::pointcloud_to_laserscan(\n    Eigen::MatrixXf points, pcl::PCLPointCloud2 *merged_cloud) {\n  sensor_msgs::LaserScanPtr output(new sensor_msgs::LaserScan());\n  output->header = pcl_conversions::fromPCL(merged_cloud->header);\n  output->header.frame_id = destination_frame_.c_str();\n  output->header.stamp = ros::Time::now(); // fixes #265\n  output->angle_min = this->angle_min_;\n  output->angle_max = this->angle_max_;\n  output->angle_increment = this->angle_increment_;\n  output->time_increment = this->time_increment_;\n  output->scan_time = this->scan_time_;\n  output->range_min = this->range_min_;\n  output->range_max = this->range_max_;\n\n  uint32_t ranges_size = std::ceil((output->angle_max - output->angle_min) /\n                                   output->angle_increment);\n  output->ranges.assign(ranges_size, output->range_max + 1.0);\n\n  for (int i = 0; i < points.cols(); i++) {\n    const float &x = points(0, i);\n    const float &y = points(1, i);\n    const float &z = points(2, i);\n\n    if (std::isnan(x) || std::isnan(y) || std::isnan(z)) {\n      ROS_DEBUG(\"rejected for nan in point(%f, %f, %f)\\n\", x, y, z);\n      continue;\n    }\n\n    double range_sq = y * y + x * x;\n    double range_min_sq_ = output->range_min * output->range_min;\n    if (range_sq < range_min_sq_) {\n      ROS_DEBUG(\n          \"rejected for range %f below minimum value %f. Point: (%f, %f, %f)\",\n          range_sq, range_min_sq_, x, y, z);\n      continue;\n    }\n\n    double angle = atan2(y, x);\n    if (angle < output->angle_min || angle > output->angle_max) {\n      ROS_DEBUG(\"rejected for angle %f not in range (%f, %f)\\n\", angle,\n                output->angle_min, output->angle_max);\n      continue;\n    }\n    int index = (angle - output->angle_min) / output->angle_increment;\n\n    if (output->ranges[index] * output->ranges[index] > range_sq)\n      output->ranges[index] = sqrt(range_sq);\n  }\n\n  laser_scan_publisher_.publish(output);\n}\n\nint main(int argc, char **argv) {\n  ros::init(argc, argv, \"laser_multi_merger\");\n\n  ros::NodeHandle nh;\n\n  tf2_ros::Buffer tf_buffer;\n  tf2_ros::TransformListener tf_listener(tf_buffer);\n\n  LaserscanMerger _laser_merger(nh, &tf_buffer);\n\n  dynamic_reconfigure::Server<laserscan_mergerConfig> server;\n  dynamic_reconfigure::Server<laserscan_mergerConfig>::CallbackType f;\n\n  f = boost::bind(&LaserscanMerger::reconfigureCallback, &_laser_merger, _1,\n                  _2);\n  server.setCallback(f);\n\n  ros::spin();\n\n  return 0;\n}\n", "meta": {"hexsha": "7d8778616cb7b11e9e1b8bbadb134e743cb92356", "size": 12457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/laserscan_merger.cpp", "max_stars_repo_name": "robotics-upo/laserscan_merger", "max_stars_repo_head_hexsha": "065900e808d0dfe1131e1bf9f22ab70e99ce6573", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T15:28:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T15:28:16.000Z", "max_issues_repo_path": "src/laserscan_merger.cpp", "max_issues_repo_name": "robotics-upo/laserscan_merger", "max_issues_repo_head_hexsha": "065900e808d0dfe1131e1bf9f22ab70e99ce6573", "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/laserscan_merger.cpp", "max_forks_repo_name": "robotics-upo/laserscan_merger", "max_forks_repo_head_hexsha": "065900e808d0dfe1131e1bf9f22ab70e99ce6573", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-31T02:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T02:12:02.000Z", "avg_line_length": 35.7959770115, "max_line_length": 80, "alphanum_fraction": 0.6645259693, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18949864441711325}}
{"text": "// 2019 Team AobaZero\n// This is a work derived from Leela Zero (May 1, 2019).\n/*\n    This file is part of Leela Zero.\n    Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors\n\n    Leela Zero 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    Leela Zero 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 Leela Zero.  If not, see <http://www.gnu.org/licenses/>.\n\n    Additional permission under GNU GPL version 3 section 7\n\n    If you modify this Program, or any covered work, by linking or\n    combining it with NVIDIA Corporation's libraries from the\n    NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural\n    Network library and/or the NVIDIA TensorRT inference library\n    (or a modified version of those libraries), containing parts covered\n    by the terms of the respective license agreement, the licensors of\n    this Program grant you additional permission to convey the resulting\n    work.\n*/\n\n#include \"config.h\"\n\n#ifdef USE_OPENCL\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <map>\n#include <random>\n#include <cmath>\n#include <fstream>\n#ifndef USE_BLAS\n#include <Eigen/Dense>\n#endif\n\n#include \"GTP.h\"\n#include \"OpenCL.h\"\n#include \"Tuner.h\"\n#include \"Utils.h\"\n#include \"Random.h\"\n\n//const auto TUNER_FILE_LOCAL = std::string(\"leelaz_opencl_tuning\");\nconst auto TUNER_FILE_LOCAL = std::string(\"aobaz_opencl_tuning\");\n\ntemplate <typename net_t>\nstd::vector<std::string> Tuner<net_t>::tuned_devices;\n\n#ifndef USE_BLAS\n// Eigen helpers\ntemplate <typename T>\nusing EigenMatrixMap =\n    Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>;\ntemplate <typename T>\nusing ConstEigenMatrixMap =\n    Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>;\n#endif\n\ntemplate <typename net_t> static std::string getTunerKernel();\ntemplate <typename net_t> static float getTunerMaxError();\n\ntemplate <> std::string getTunerKernel<float>() {\n    return std::string(\"XgemmBatched\");\n}\n\ntemplate <> float getTunerMaxError<float>() {\n    return 1e-4f;\n}\n\n#ifdef USE_HALF\ntemplate <> std::string getTunerKernel<half_float::half>() {\n    return std::string(\"XgemmBatchedHalf\");\n}\n\ntemplate <> float getTunerMaxError<half_float::half>() {\n    return 1e-1f;\n}\n#endif\n\nusing namespace Utils;\n\ntemplate <typename net_t>\nstatic void sgemmBatched_ref(const std::vector<net_t>& a,\n                             const std::vector<net_t>& b,\n                             std::vector<net_t>& c,\n                             const int m, const int n, const int k,\n                             const int batch_size) {\n    std::vector<float> ar(a.size());\n    std::vector<float> br(b.size());\n    std::vector<float> cr(c.size());\n\n    std::copy(begin(a), end(a), begin(ar));\n    std::copy(begin(b), end(b), begin(br));\n\n    for (auto batch = 0; batch < batch_size; batch++) {\n        auto offset_u = batch * m * k;\n        auto offset_v = batch * n * k;\n        auto offset_m = batch * m * n;\n#ifdef USE_BLAS\n        // Calculates C = transpose(tranpose(A) * B) in row major, or\n        // C = A * transpose(B) in column major.\n        for (auto i = 0; i < m; i++) {\n            for (auto j = 0; j < n; j++) {\n                auto acc = 0.0f;\n                for (auto l = 0; l < k; l++) {\n                    acc += ar[l * m + i + offset_u] * br[l * n + j + offset_v];\n                }\n                cr[j * m + i + offset_m] = acc;\n            }\n        }\n#else\n        auto C = EigenMatrixMap<float>(cr.data() + offset_m, m, n);\n        auto A = ConstEigenMatrixMap<float>(ar.data() + offset_u, m, k);\n        auto B = ConstEigenMatrixMap<float>(br.data() + offset_v, n, k);\n        C.noalias() = (A * B.transpose());\n#endif\n    }\n\n    std::copy(begin(cr), end(cr), begin(c));\n}\n\n\nstatic bool IsMultiple(const size_t a, const size_t b) {\n    return (a % b == 0);\n}\n\ntemplate <typename net_t>\nbool Tuner<net_t>::valid_config_sgemm(Parameters p, bool exhaustive) {\n    if (p[\"TCE\"] == 0) {\n        if (!IsMultiple(p[\"MWG\"], p[\"MDIMC\"]*p[\"VWM\"])) {\n            return false;\n        }\n        if (!IsMultiple(p[\"NWG\"], p[\"NDIMC\"]*p[\"VWN\"])) {\n            return false;\n        }\n        if (!IsMultiple(p[\"MWG\"], p[\"MDIMA\"]*p[\"VWM\"])) {\n            return false;\n        }\n        if (!IsMultiple(p[\"NWG\"], p[\"NDIMB\"]*p[\"VWN\"])) {\n            return false;\n        }\n        if (!IsMultiple(p[\"KWG\"], p[\"MDIMC\"]*p[\"NDIMC\"]/p[\"MDIMA\"])) {\n            return false;\n        }\n        if (!IsMultiple(p[\"KWG\"], p[\"MDIMC\"]*p[\"NDIMC\"]/p[\"NDIMB\"])) {\n            return false;\n        }\n        // Extra restrictions for a fast tuning run\n        if (!exhaustive) {\n            if (p[\"MDIMC\"] != p[\"MDIMA\"]) {\n                return false;\n            }\n            if (p[\"NDIMC\"] != p[\"NDIMB\"]) {\n                return false;\n            }\n            if (p[\"SA\"] != p[\"SB\"]) {\n                return false;\n            }\n        }\n    } else {\n        if (!m_use_tensorcore) {\n            return false;\n        }\n\n        // In Tensor Core implementations, MDIMA and NDIMB represents the\n        // wmmv multiplication dimensions, that is,\n        // m16n16k16 / m32n8k16 / m8n32k16.  Thus m * n is fixed to 256.\n        if (p[\"MDIMA\"] * p[\"NDIMB\"] != 256) {\n            return false;\n        }\n        if (p[\"MWG\"] < p[\"MDIMC\"]) {\n            return false;\n        }\n        if (p[\"NWG\"] < p[\"NDIMC\"]) {\n            return false;\n        }\n        if (p[\"MDIMC\"] < p[\"MDIMA\"]) {\n            return false;\n        }\n        if (p[\"NDIMC\"] < p[\"NDIMB\"]) {\n            return false;\n        }\n        // VWM / VWN has no meaning if we don't do SA / SB.\n        // Only test VWM / VWN == 2\n        if (p[\"SA\"] == 0 && p[\"VWM\"] != 2) {\n            return false;\n        }\n        if (p[\"SB\"] == 0 && p[\"VWN\"] != 2) {\n            return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename net_t>\nParameters Tuner<net_t>::get_parameters_by_int(\n    const std::vector<Configurations>& opts, const int n) {\n\n    Parameters param;\n    std::vector<size_t> choices(opts.size());\n\n    auto cfgs = 1;\n    for (auto c = size_t{0}; c < opts.size(); c++) {\n        choices[c] = opts[c].second.size();\n        cfgs *= choices[c];\n    }\n    auto j = n;\n\n    for (auto c = size_t{0}; c < opts.size(); c++) {\n        auto o = opts[c];\n        auto s = o.first;\n        auto v = o.second[j % choices[c]];\n        j /= choices[c];\n        param[s] = v;\n    }\n\n    return param;\n}\n\ntemplate <typename net_t>\nstd::string Tuner<net_t>::parameters_to_defines(const Parameters& p) {\n    std::string s;\n    for (auto const& x : p) {\n        s += \" -D\" + x.first + \"=\" + std::to_string(x.second);\n    }\n    return s;\n}\n\ntemplate <typename net_t>\nstd::string Tuner<net_t>::parameters_to_string(const Parameters& p) {\n    std::string s;\n    for (auto const& x : p) {\n        s += x.first + \"=\" + std::to_string(x.second) + \" \";\n    }\n    if (s.size() > 0) {\n        s.resize(s.size() - 1);\n    }\n    return s;\n}\n\nstatic size_t next_power_of_two(const size_t x) {\n    return 2 << size_t(std::ceil(std::log2(x)) - 1);\n}\n\ntemplate <typename net_t>\nstatic void sgemm_generate_data(std::vector<net_t> &x,\n                                const int m, const int n,\n                                const int batch_size,\n                                const int m_ceil, const int n_ceil) {\n    for (auto batch = 0; batch < batch_size; batch++) {\n        for (auto i = 0; i < n_ceil; i++) {\n            if (i < n) {\n                for (auto j = 0; j < m; j++) {\n                    x[batch*n_ceil*m_ceil + i*m_ceil + j] =\n                        (( (i ^ j) + batch - 128) % 256) / 256.0f;\n                }\n                for (auto j = m; j < m_ceil; j++) {\n                    x[batch*n_ceil*m_ceil + i*m_ceil + j] = 0.0f;\n                }\n            } else {\n                for (auto j = 0; j < m_ceil; j++) {\n                    x[batch*n_ceil*m_ceil + i*m_ceil + j] = 0.0f;\n                }\n            }\n        }\n    }\n}\n\ntemplate <typename net_t>\nstatic float compare_ref(std::vector<net_t> &x, std::vector<net_t> &ref,\n                         const int m, const int n, const int batch_size,\n                         const int m_ceil, const int n_ceil) {\n    auto sum = 0.0f;\n    for (auto batch = 0; batch < batch_size; batch++) {\n        for (auto j = 0; j < m; j++) {\n            for (auto i = 0; i < n; i++) {\n                auto r = ref[batch*n*m + j*n + i];\n                auto y = x[batch*n_ceil*m_ceil + j*n_ceil + i];\n\n                sum += (r - y) * (r - y);\n            }\n        }\n    }\n    return sum / (m * n * batch_size);\n}\n\ntemplate <typename net_t>\nstd::vector<Parameters> Tuner<net_t>::build_valid_params() {\n    auto opts = std::vector<Configurations>();\n    if (cfg_sgemm_exhaustive) {\n        opts = {\n            {\"MWG\", {16, 32, 64}},\n            {\"NWG\", {16, 32, 64}},\n            {\"KWG\", {16, 32}},\n            {\"MDIMC\", {8, 16, 32}},\n            {\"NDIMC\", {8, 16, 32}},\n            {\"MDIMA\", {8, 16, 32}},\n            {\"NDIMB\", {8, 16, 32}},\n            {\"KWI\", {2, 8}},\n            {\"VWM\", {1, 2, 4, 8}},\n            {\"VWN\", {1, 2, 4, 8}},\n            {\"STRM\", {0, 1}},\n            {\"STRN\", {0, 1}},\n            {\"SA\", {0, 1}},\n            {\"SB\", {0, 1}},\n        };\n    } else {\n        opts = {\n            {\"MWG\", {16, 32, 64}},\n            {\"NWG\", {16, 32, 64}},\n            {\"KWG\", {16, 32}},\n            {\"MDIMC\", {8, 16, 32}},\n            {\"NDIMC\", {8, 16, 32}},\n            {\"MDIMA\", {8, 16, 32}},\n            {\"NDIMB\", {8, 16, 32}},\n            {\"KWI\", {2, 8}},\n            {\"VWM\", {2, 4}},\n            {\"VWN\", {2, 4}},\n            {\"STRM\", {0}},\n            {\"STRN\", {0}},\n            {\"SA\", {1}},\n            {\"SB\", {1}},\n        };\n    }\n    // Tensor Core options\n    auto topts = std::vector<Configurations>();\n    if (cfg_sgemm_exhaustive) {\n        topts = {\n            {\"MWG\", {32, 64, 128, 256}},\n            {\"NWG\", {8, 16, 32, 64}},\n            {\"KWG\", {16, 32, 64}},\n            {\"MDIMC\", {8, 16, 32, 64}},\n            {\"NDIMC\", {8, 16, 32, 64}},\n            {\"MDIMA\", {8, 16, 32}},\n            {\"NDIMB\", {8, 16, 32}},\n            {\"KWI\", {2}},\n            {\"VWM\", {2, 4, 8}},\n            {\"VWN\", {2, 4, 8}},\n            {\"STRM\", {0}},\n            {\"STRN\", {0}},\n            {\"SA\", {0, 1}},\n            {\"SB\", {0, 1}},\n        };\n    } else {\n        topts = {\n            {\"MWG\", {32, 64, 128}},\n            {\"NWG\", {8, 16, 32}},\n            {\"KWG\", {16, 32}},\n            {\"MDIMC\", {8, 16, 32}},\n            {\"NDIMC\", {8, 16, 32}},\n            {\"MDIMA\", {8, 16, 32}},\n            {\"NDIMB\", {8, 16, 32}},\n            {\"KWI\", {2}},\n            {\"VWM\", {2}},\n            {\"VWN\", {2}},\n            {\"STRM\", {0}},\n            {\"STRN\", {0}},\n            {\"SA\", {0}},\n            {\"SB\", {0}},\n        };\n    }\n\n    auto valid_params = std::vector<Parameters>{};\n    auto build_from = [this, &valid_params](std::vector<Configurations> & opts, int tce) {\n        auto cfgs = 1;\n        for (auto c = size_t{0}; c < opts.size(); c++) {\n            cfgs *= opts[c].second.size();\n        }\n        for (auto i = 0; i < cfgs; i++) {\n            Parameters param = get_parameters_by_int(opts, i);\n            param[\"TCE\"] = tce;\n            if (valid_config_sgemm(param, cfg_sgemm_exhaustive)) {\n                valid_params.push_back(param);\n            }\n        }\n    };\n    build_from(opts, 0);\n    build_from(topts, 1);\n\n    // Don't use thread RNG or determinism will depend on whether tuner ran.\n    auto rng = Random{0};\n    std::shuffle(begin(valid_params), end(valid_params), rng);\n\n    if (cfg_sgemm_exhaustive) {\n        // Likely too many valid params, cut out some of them\n        valid_params.resize(valid_params.size() / 16);\n    }\n\n    return valid_params;\n}\n\ntemplate <typename net_t>\nstd::string Tuner<net_t>::tune_sgemm(const int m, const int n, const int k,\n                              const int batch_size, const int runs) {\n    // This needs to be at minimum the maximum (MNK/WG) values above.\n    auto m_max = std::max(64, m);\n    auto n_max = std::max(64, n);\n    auto k_max = std::max(32, k);\n\n    auto at_size = batch_size\n        * next_power_of_two(k_max) * next_power_of_two(m_max);\n    auto b_size = batch_size\n        * next_power_of_two(k_max) * next_power_of_two(n_max);\n    auto c_size = batch_size\n        * next_power_of_two(m_max) * next_power_of_two(n_max);\n\n    auto total_flops = batch_size * 2.0 * m * n * k;\n\n    auto at = std::vector<net_t>(at_size);\n    auto b = std::vector<net_t>(b_size);\n    auto c = std::vector<net_t>(c_size);\n    auto c_ref = std::vector<net_t>(c_size);\n\n    sgemm_generate_data(at, k, m, batch_size, k, m);\n    sgemm_generate_data(b, n, k, batch_size, n, k);\n\n    sgemmBatched_ref(at, b, c_ref, m, n, k, batch_size);\n\n    auto aBuffer = cl::Buffer(\n        m_context,\n        CL_MEM_READ_WRITE, sizeof(net_t) * at_size, nullptr, nullptr);\n    auto bBuffer = cl::Buffer(\n        m_context,\n        CL_MEM_READ_WRITE, sizeof(net_t) * b_size, nullptr, nullptr);\n    auto cBuffer = cl::Buffer(\n        m_context,\n        CL_MEM_READ_WRITE, sizeof(net_t) * c_size, nullptr, nullptr);\n\n    myprintf(\"\\nStarted OpenCL SGEMM tuner.\\n\");\n\n    auto valid_params = build_valid_params();\n\n    myprintf(\"Will try %zu valid configurations.\\n\", valid_params.size());\n\n    std::string best_params;\n    auto best_time = unsigned{0};\n\n    auto queue = cl::CommandQueue(m_context,\n                                  m_device,\n                                  CL_QUEUE_PROFILING_ENABLE);\n    auto event = cl::Event();\n    auto program = cl::Program(m_context, sourceCode_common + sourceCode_sgemm);\n\n    auto m_ceil_prev = 0;\n    auto n_ceil_prev = 0;\n    auto k_ceil_prev = 0;\n    auto param_counter = size_t{0};\n    auto min_error = 100.0f;\n    auto failed_compile = 0;\n    auto failed_enqueue = 0;\n    auto failed_error = 0;\n\n    for (auto & p : valid_params) {\n        param_counter++;\n\n        auto defines = parameters_to_defines(p);\n\n        try {\n            auto args = m_opencl.m_cl_args + \" \" + defines;\n            program.build(args.c_str());\n        } catch (const cl::Error&) {\n            // Failed to compile, get next parameter\n            failed_compile++;\n            continue;\n        }\n\n        auto sgemm_kernel = cl::Kernel(program, \"XgemmBatched\");\n\n        auto m_ceil = int(ceilMultiple(ceilMultiple(m, p[\"MWG\"]), p[\"VWM\"]));\n        auto n_ceil = int(ceilMultiple(ceilMultiple(n, p[\"NWG\"]), p[\"VWN\"]));\n        auto k_ceil = int(ceilMultiple(ceilMultiple(k, p[\"KWG\"]), p[\"VWM\"]));\n\n        if (m_ceil != m_ceil_prev\n            || n_ceil != n_ceil_prev\n            || k_ceil != k_ceil_prev) {\n            m_ceil_prev = m_ceil;\n            n_ceil_prev = n_ceil;\n            k_ceil_prev = k_ceil;\n\n            sgemm_generate_data(at, k, m, batch_size, k_ceil, m_ceil);\n            sgemm_generate_data(b, n, k, batch_size, n_ceil, k_ceil);\n\n            queue.enqueueWriteBuffer(aBuffer, CL_FALSE, 0,\n                                     at_size * sizeof(net_t), at.data());\n            queue.enqueueWriteBuffer(bBuffer, CL_FALSE, 0,\n                                     b_size * sizeof(net_t), b.data());\n            queue.finish();\n        }\n\n        sgemm_kernel.setArg(0, m_ceil);\n        sgemm_kernel.setArg(1, n_ceil);\n        sgemm_kernel.setArg(2, k_ceil);\n        sgemm_kernel.setArg(3, aBuffer);\n        sgemm_kernel.setArg(4, bBuffer);\n        sgemm_kernel.setArg(5, cBuffer);\n\n        cl::NDRange local_sgemm = {p[\"MDIMC\"], p[\"NDIMC\"], 1};\n\n\n        cl::NDRange size_sgemm = {(m_ceil * p[\"MDIMC\"]) / p[\"MWG\"],\n                                  (n_ceil * p[\"NDIMC\"]) / p[\"NWG\"],\n                                  size_t(batch_size)};\n        // Tensor Core implementation uses a different dimension.\n        if (p[\"TCE\"]) {\n            local_sgemm = {32 * p[\"MDIMC\"] / p[\"MDIMA\"], p[\"NDIMC\"] / p[\"NDIMB\"], 1};\n            size_sgemm = {32 * m_ceil / p[\"MDIMA\"] * p[\"MDIMC\"] / p[\"MWG\"],\n                          n_ceil / p[\"NDIMB\"] * p[\"NDIMC\"] / p[\"NWG\"],\n                          size_t(batch_size)};\n        }\n\n        auto sum = 0.0f;\n        auto error = 0.0f;\n\n        for (auto r = 0; r < runs; r++) {\n            try {\n                queue.enqueueNDRangeKernel(sgemm_kernel, cl::NullRange,\n                                           size_sgemm, local_sgemm,\n                                           nullptr, &event);\n                queue.finish();\n                event.wait();\n\n                queue.enqueueReadBuffer(cBuffer, CL_FALSE, 0,\n                                        c_size * sizeof(net_t), c.data());\n                queue.finish();\n\n                auto this_error = compare_ref(c, c_ref, n, m, batch_size,\n                                              n_ceil, m_ceil);\n                error = std::max(error, this_error);\n\n                auto elapsed =\n                    event.getProfilingInfo<CL_PROFILING_COMMAND_END>() -\n                    event.getProfilingInfo<CL_PROFILING_COMMAND_START>();\n\n                sum += elapsed;\n            } catch (const cl::Error&) {\n                // Failed to enqueue kernel. Set error to some big number.\n                failed_enqueue++;\n                error = std::numeric_limits<float>::max();\n                // This failure will be counted to be failed due to error,\n                // so preemptively subtract one from that count.\n                failed_error--;\n                break;\n            }\n        }\n\n        min_error = std::min(min_error, error);\n\n        if (error >= getTunerMaxError<net_t>()) {\n            failed_error++;\n        }\n\n        if (error < getTunerMaxError<net_t>() && (best_time == 0 || sum < best_time)) {\n            auto param_str = parameters_to_string(p);\n            auto kernel_ms = 1e-6f * (sum / runs);\n            // Timing is in nanoseconds (10^-9), Giga = 10^9, so this works out\n            auto kernel_gflops = total_flops / (sum / runs);\n            myprintf(\"(%u/%u) %s %.4f ms (%.1f GFLOPS)\\n\",\n               param_counter, valid_params.size(), param_str.c_str(),\n               kernel_ms, kernel_gflops);\n            best_time = sum;\n            best_params = defines;\n        }\n    }\n    if (best_time == 0) {\n        if (failed_compile > 0) {\n            myprintf_error(\"Failed to compile: %d kernels.\\n\", failed_compile);\n        }\n        if (failed_enqueue > 0) {\n            myprintf_error(\"Failed to enqueue: %d kernels\\n\", failed_enqueue);\n        }\n        if (failed_error > 0) {\n            myprintf_error(\"Too high error: %d kernels\\n\", failed_error);\n        }\n        myprintf_error(\"Failed to find a working configuration.\\nCheck your OpenCL drivers.\\n\");\n        myprintf_error(\"Minimum error: %f. Error bound: %f\\n\", min_error, getTunerMaxError<net_t>());\n        throw std::runtime_error(\"Tuner failed to find working configuration.\");\n    }\n    return best_params;\n}\n\ntemplate <typename net_t>\nvoid Tuner<net_t>::store_sgemm_tuners(const int m, const int n, const int k,\n                               const int batch_size, std::string tuners) {\n    auto tuner_file = leelaz_file(TUNER_FILE_LOCAL);\n    auto file_contents = std::vector<std::string>();\n    {\n        // Read the previous contents to string\n        auto file = std::ifstream{tuner_file};\n        if (file.good()) {\n            auto line = std::string{};\n            while (std::getline(file, line)) {\n                file_contents.emplace_back(line);\n            }\n        }\n    }\n    auto file = std::ofstream{tuner_file};\n\n    auto device_name = m_opencl.get_device_name();\n    auto tuning_params = std::stringstream{};\n    tuning_params << m << \";\" << n << \";\" << k << \";\" << batch_size;\n\n    auto tuning_line_prefix = std::to_string(TUNER_VERSION) + \";\"\n        + getTunerKernel<net_t>() + \";\" + tuning_params.str() + \";\";\n    auto tuning_line = tuning_line_prefix + tuners + \";\" + device_name;\n\n    // Write back previous data as long as it's not the device and\n    // tuning we just tuned\n    for (const auto& line : file_contents) {\n        if (line.find(tuning_line_prefix) == std::string::npos\n            || line.find(device_name) == std::string::npos) {\n            file << line << std::endl;\n        }\n    }\n\n    // Write new tuning\n    file << tuning_line << std::endl;\n\n    if (file.fail()) {\n        myprintf(\"Could not save the tuning result.\\n\");\n        myprintf(\"Do I have write permissions on %s?\\n\",\n            tuner_file.c_str());\n    }\n}\n\ntemplate <typename net_t>\nstd::string Tuner<net_t>::sgemm_tuners_from_line(std::string line,\n                                          const int m, const int n, const int k,\n                                          const int batch_size) {\n    auto s = std::vector<std::string>{};\n    auto ss = std::stringstream{line};\n    auto item = std::string{};\n\n    while (std::getline(ss, item, ';')) {\n        s.emplace_back(item);\n    }\n\n    if (s.size() != 8) {\n        return \"\";\n    }\n\n    if (s[0] != std::to_string(TUNER_VERSION)) {\n        return \"\";\n    }\n\n    if (s[1] != getTunerKernel<net_t>()) {\n        return \"\";\n    }\n\n    if (s[2] != std::to_string(m)) {\n        return \"\";\n    }\n\n    if (s[3] != std::to_string(n)) {\n        return \"\";\n    }\n\n    if (s[4] != std::to_string(k)) {\n        return \"\";\n    }\n\n    if (s[5] != std::to_string(batch_size)) {\n        return \"\";\n    }\n\n    if (s[7] != m_opencl.get_device_name()) {\n        return \"\";\n    }\n\n    return s[6];\n}\n\ntemplate <typename net_t>\nstd::string Tuner<net_t>::load_sgemm_tuners(const int m, const int n, const int k,\n                                     const int batch_size) {\n    auto tuner_file = leelaz_file(TUNER_FILE_LOCAL);\n    auto file = std::ifstream{tuner_file};\n\n    auto try_prior_tuning = file.good();\n\n    // If we want full tuning, don't reuse previously tuned results\n    // except if the tuning was created from this run from a different\n    // GPU instance with the same name.  This prevents the tuner running\n    // for multiple times if the system has multiple same GPUs.\n    if (try_prior_tuning && cfg_sgemm_exhaustive) {\n        auto dev = m_opencl.get_device_name();\n        try_prior_tuning = std::any_of(\n            begin(tuned_devices),\n            end(tuned_devices),\n            [&dev](const std::string & x) { return dev == x; }\n        );\n    }\n    tuned_devices.emplace_back(m_opencl.get_device_name());\n\n    if (try_prior_tuning) {\n        auto line = std::string{};\n        while (std::getline(file, line)) {\n            auto tuners = sgemm_tuners_from_line(line, m, n, k, batch_size);\n            if (tuners.size() != 0) {\n                myprintf(\"Loaded existing SGEMM tuning.\\n\");\n                return tuners;\n            }\n        }\n    }\n    auto tuners = tune_sgemm(m, n, k, batch_size);\n    store_sgemm_tuners(m, n, k, batch_size, tuners);\n    return tuners;\n}\n\ntemplate <typename net_t>\nvoid Tuner<net_t>::enable_tensorcore() {}\n#ifdef USE_HALF\ntemplate <>\nvoid Tuner<half_float::half>::enable_tensorcore() {\n    m_use_tensorcore = true;\n}\n#endif\n\ntemplate class Tuner<float>;\n#ifdef USE_HALF\ntemplate class Tuner<half_float::half>;\n#endif\n\n#endif\n", "meta": {"hexsha": "6ae231e5e1cddef4779264029b9c10216be8f100", "size": 23602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/usi-engine/Tuner.cpp", "max_stars_repo_name": "bleu48/aobazero", "max_stars_repo_head_hexsha": "c805b80d9ed8d27ce507fc2b74fb7609d75b2426", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T05:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T02:46:00.000Z", "max_issues_repo_path": "src/usi-engine/Tuner.cpp", "max_issues_repo_name": "bleu48/aobazero", "max_issues_repo_head_hexsha": "c805b80d9ed8d27ce507fc2b74fb7609d75b2426", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2019-05-07T15:22:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T04:34:39.000Z", "max_forks_repo_path": "src/usi-engine/Tuner.cpp", "max_forks_repo_name": "kobanium/aoba-zero", "max_forks_repo_head_hexsha": "dd6eb185e22c57b72663859e678fff79f7f425a5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-05-10T02:11:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T12:28:03.000Z", "avg_line_length": 32.0679347826, "max_line_length": 101, "alphanum_fraction": 0.5227523091, "num_tokens": 6440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18949863907815367}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ 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 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 \"bempp/common/config_ahmed.hpp\"\n#include \"bempp/common/config_trilinos.hpp\"\n\n#include \"aca_global_assembler.hpp\"\n\n#include \"assembly_options.hpp\"\n#include \"cluster_construction_helper.hpp\"\n#include \"index_permutation.hpp\"\n#include \"discrete_boundary_operator_composition.hpp\"\n#include \"discrete_sparse_boundary_operator.hpp\"\n\n#include \"../common/armadillo_fwd.hpp\"\n#include \"../common/auto_timer.hpp\"\n#include \"../common/boost_shared_array_fwd.hpp\"\n#include \"../common/chunk_statistics.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../fiber/local_assembler_for_operators.hpp\"\n#include \"../fiber/serial_blas_region.hpp\"\n#include \"../fiber/scalar_traits.hpp\"\n#include \"../space/space.hpp\"\n\n#include <stdexcept>\n#include <iostream>\n\n#include <boost/type_traits/is_complex.hpp>\n\n#include <tbb/atomic.h>\n#include <tbb/parallel_for.h>\n#include <tbb/task_scheduler_init.h>\n#include <tbb/concurrent_queue.h>\n\n#ifdef WITH_AHMED\n#include \"ahmed_aux.hpp\"\n#include \"discrete_aca_boundary_operator.hpp\"\n#include \"scattered_range.hpp\"\n#include \"weak_form_aca_assembly_helper.hpp\"\n#endif\n\nnamespace Bempp\n{\n\n// Body of parallel loop\nnamespace\n{\n\n#ifdef WITH_AHMED\ntemplate <typename BasisFunctionType, typename ResultType>\nclass AcaWeakFormAssemblerLoopBody\n{\n    typedef typename Fiber::ScalarTraits<ResultType>::RealType CoordinateType;\n    typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n    typedef bemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n    typedef mblock<typename AhmedTypeTraits<ResultType>::Type> AhmedMblock;\npublic:\n    typedef tbb::concurrent_queue<size_t> LeafClusterIndexQueue;\n\n    AcaWeakFormAssemblerLoopBody(\n            WeakFormAcaAssemblyHelper<BasisFunctionType, ResultType>& helper,\n            AhmedLeafClusterArray& leafClusters,\n            boost::shared_array<AhmedMblock*> blocks,\n            const AcaOptions& options,\n            tbb::atomic<size_t>& done,\n            bool verbose,\n            LeafClusterIndexQueue& leafClusterIndexQueue,\n            bool symmetric,\n            std::vector<ChunkStatistics>& stats) :\n        m_helper(helper),\n        m_leafClusters(leafClusters), m_blocks(blocks),\n        m_options(options), m_done(done), m_verbose(verbose),\n        m_leafClusterIndexQueue(leafClusterIndexQueue),\n        m_symmetric(symmetric),\n        m_stats(stats)\n    {\n    }\n\n    template <typename Range>\n    void operator() (const Range& r) const {\n        const char* TEXT = \"Approximating ... \";\n        for (typename Range::const_iterator i = r.begin(); i != r.end(); ++i) {\n            size_t leafClusterIndex = 0;\n            if (!m_leafClusterIndexQueue.try_pop(leafClusterIndex)) {\n                std::cerr << \"AcaWeakFormAssemblerLoopBody::operator(): \"\n                             \"Warning: try_pop failed; this shouldn't happen!\"\n                          << std::endl;\n                continue;\n            }\n            m_stats[leafClusterIndex].valid = true;\n            m_stats[leafClusterIndex].chunkStart = r.begin();\n            m_stats[leafClusterIndex].chunkSize = r.size();\n            m_stats[leafClusterIndex].startTime = tbb::tick_count::now();\n\n            AhmedBemBlcluster* cluster =\n                    dynamic_cast<AhmedBemBlcluster*>(m_leafClusters[leafClusterIndex]);\n            if (m_symmetric)\n                apprx_sym(m_helper, m_blocks[cluster->getidx()],\n                          cluster, m_options.eps, m_options.maximumRank,\n                          true /* complex_sym */);\n            else\n                apprx_unsym(m_helper, m_blocks[cluster->getidx()],\n                            cluster, m_options.eps, m_options.maximumRank);\n            m_stats[leafClusterIndex].endTime = tbb::tick_count::now();\n            // TODO: recompress\n            const int HASH_COUNT = 20;\n            if (m_verbose)\n                progressbar(std::cout, TEXT, (++m_done) - 1,\n                            m_leafClusters.size(), HASH_COUNT, true);\n        }\n\n    }\n\nprivate:\n    WeakFormAcaAssemblyHelper<BasisFunctionType, ResultType>& m_helper;\n    AhmedLeafClusterArray& m_leafClusters;\n    boost::shared_array<AhmedMblock*> m_blocks;\n    const AcaOptions& m_options;\n    tbb::atomic<size_t>& m_done;\n    bool m_verbose;\n    LeafClusterIndexQueue& m_leafClusterIndexQueue;\n    bool m_symmetric;\n    std::vector<ChunkStatistics>& m_stats;\n};\n\nvoid reallyGetClusterIds(const cluster& clusterTree,\n                         const std::vector<unsigned int>& p2oDofs,\n                         std::vector<unsigned int>& clusterIds,\n                         unsigned int& id)\n{\n    if (clusterTree.isleaf())\n        for (unsigned int nDof = clusterTree.getnbeg(); nDof < clusterTree.getnend(); ++nDof)\n            clusterIds[p2oDofs[nDof]] = id;\n    else\n        for (unsigned int nSon = 0; nSon < clusterTree.getns(); ++nSon)\n            reallyGetClusterIds(*clusterTree.getson(nSon), p2oDofs, clusterIds, ++id);\n}\n\nvoid getClusterIds(const cluster& clusterTree,\n                   const std::vector<unsigned int>& p2oDofs,\n                   std::vector<unsigned int>& clusterIds)\n{\n    clusterIds.resize(p2oDofs.size());\n    unsigned int id = 0;\n    reallyGetClusterIds(clusterTree, p2oDofs, clusterIds, id);\n}\n#endif\n\n} // namespace\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteBoundaryOperator<ResultType> >\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assembleDetachedWeakForm(\n        const Space<BasisFunctionType>& testSpace,\n        const Space<BasisFunctionType>& trialSpace,\n        const std::vector<LocalAssembler*>& localAssemblers,\n        const std::vector<const DiscreteBndOp*>& sparseTermsToAdd,\n        const std::vector<ResultType>& denseTermsMultipliers,\n        const std::vector<ResultType>& sparseTermsMultipliers,\n        const AssemblyOptions& options,\n        int symmetry)\n{\n#ifdef WITH_AHMED\n    typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n    typedef ExtendedBemCluster<AhmedDofType> AhmedBemCluster;\n    typedef bemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n    typedef DiscreteAcaBoundaryOperator<ResultType> DiscreteAcaLinOp;\n\n    const AcaOptions& acaOptions = options.acaOptions();\n    const bool indexWithGlobalDofs = acaOptions.globalAssemblyBeforeCompression;\n    const bool verbosityAtLeastDefault =\n            (options.verbosityLevel() >= VerbosityLevel::DEFAULT);\n    const bool verbosityAtLeastHigh =\n            (options.verbosityLevel() >= VerbosityLevel::HIGH);\n\n    // Currently we don't support Hermitian ACA operators. This is because we\n    // don't have the means to really test them -- we would need complex-valued\n    // basis functions for that. (Assembly of such a matrix would be very easy\n    // -- just change complex_sym from true to false in the call to apprx_sym()\n    // in AcaWeakFormAssemblerLoopBody::operator() -- but operations on\n    // symmetric/Hermitian matrices are not always trivial and we do need to be\n    // able to test them properly.)\n    bool symmetric = symmetry & SYMMETRIC;\n    if (symmetry & HERMITIAN && !(symmetry & SYMMETRIC) &&\n            verbosityAtLeastDefault)\n        std::cout << \"Warning: assembly of non-symmetric Hermitian H-matrices \"\n                     \"is not supported yet. A general H-matrix will be assembled\"\n                  << std::endl;\n\n#ifndef WITH_TRILINOS\n    if (!indexWithGlobalDofs)\n        throw std::runtime_error(\"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n                                 \"ACA assembly with globalAssemblyBeforeCompression \"\n                                 \"set to false requires BEM++ to be linked with \"\n                                 \"Trilinos\");\n#endif // WITH_TRILINOS\n\n    const size_t testDofCount = indexWithGlobalDofs ?\n                testSpace.globalDofCount() : testSpace.flatLocalDofCount();\n    const size_t trialDofCount = indexWithGlobalDofs ?\n                trialSpace.globalDofCount() : trialSpace.flatLocalDofCount();\n\n    if (symmetric && testDofCount != trialDofCount)\n        throw std::invalid_argument(\"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n                                    \"you cannot generate a symmetric weak form \"\n                                    \"using test and trial spaces with different \"\n                                    \"numbers of DOFs\");\n\n    // o2p: map of original indices to permuted indices\n    // p2o: map of permuted indices to original indices\n    typedef ClusterConstructionHelper<BasisFunctionType> CCH;\n    shared_ptr<AhmedBemCluster> testClusterTree;\n    shared_ptr<IndexPermutation> test_o2pPermutation, test_p2oPermutation;\n    CCH::constructBemCluster(testSpace, indexWithGlobalDofs, acaOptions,\n                             testClusterTree,\n                             test_o2pPermutation, test_p2oPermutation);\n    shared_ptr<AhmedBemCluster> trialClusterTree;\n    shared_ptr<IndexPermutation> trial_o2pPermutation, trial_p2oPermutation;\n    if (symmetric || &testSpace == &trialSpace) {\n        trialClusterTree = testClusterTree;\n        trial_o2pPermutation = test_o2pPermutation;\n        trial_p2oPermutation = test_p2oPermutation;\n    } else\n        CCH::constructBemCluster(trialSpace, indexWithGlobalDofs, acaOptions,\n                                 trialClusterTree,\n                                 trial_o2pPermutation, trial_p2oPermutation);\n\n//    // Export VTK plots showing the disctribution of leaf cluster ids\n//    std::vector<unsigned int> testClusterIds;\n//    getClusterIds(*testClusterTree, test_p2oPermutation->permutedIndices(), testClusterIds);\n//    testSpace.dumpClusterIds(\"testClusterIds\", testClusterIds,\n//                             indexWithGlobalDofs ? GLOBAL_DOFS : FLAT_LOCAL_DOFS);\n//    std::vector<unsigned int> trialClusterIds;\n//    getClusterIds(*trialClusterTree, trial_p2oPermutation->permutedIndices(), trialClusterIds);\n//    trialSpace.dumpClusterIds(\"trialClusterIds\", trialClusterIds,\n//                              indexWithGlobalDofs ? GLOBAL_DOFS : FLAT_LOCAL_DOFS);\n\n    if (verbosityAtLeastHigh)\n        std::cout << \"Test cluster count: \" << testClusterTree->getncl()\n                  << \"\\nTrial cluster count: \" << trialClusterTree->getncl()\n                  << std::endl;\n\n    unsigned int blockCount = 0;\n    shared_ptr<AhmedBemBlcluster> bemBlclusterTree(\n                CCH::constructBemBlockCluster(acaOptions, symmetric,\n                                              *testClusterTree, *trialClusterTree,\n                                              blockCount).release());\n\n    if (verbosityAtLeastHigh)\n        std::cout << \"Mblock count: \" << blockCount << std::endl;\n\n    std::vector<unsigned int> p2oTestDofs =\n        test_p2oPermutation->permutedIndices();\n    std::vector<unsigned int> p2oTrialDofs =\n        trial_p2oPermutation->permutedIndices();\n    WeakFormAcaAssemblyHelper<BasisFunctionType, ResultType>\n        helper(testSpace, trialSpace, p2oTestDofs, p2oTrialDofs,\n               localAssemblers, sparseTermsToAdd,\n               denseTermsMultipliers, sparseTermsMultipliers, options);\n\n    typedef mblock<typename AhmedTypeTraits<ResultType>::Type> AhmedMblock;\n    boost::shared_array<AhmedMblock*> blocks =\n            allocateAhmedMblockArray<ResultType>(bemBlclusterTree.get());\n\n    // matgen_sqntl(helper, AhmedBemBlclusterTree.get(), AhmedBemBlclusterTree.get(),\n    //              acaOptions.recompress, acaOptions.eps,\n    //              acaOptions.maximumRank, blocks.get());\n\n    // matgen_omp(helper, blockCount, AhmedBemBlclusterTree.get(),\n    //            acaOptions.eps, acaOptions.maximumRank, blocks.get());\n\n    // // Dump mblocks\n    // const int mblockCount = AhmedBemBlclusterTree->nleaves();\n    // for (int i = 0; i < mblockCount; ++i)\n    //     if (blocks[i]->isdns())\n    //     {\n    //         char  buffer[1024];\n    //         sprintf(buffer, \"mblock-dns-%d-%d.txt\",\n    //                 blocks[i]->getn1(), blocks[i]->getn2());\n    //         arma::Col<ResultType> block((ResultType*)blocks[i]->getdata(),\n    //                                     blocks[i]->nvals());\n    //         arma::diskio::save_raw_ascii(block, buffer);\n    //     }\n    //     else\n    //     {\n    //         char buffer[1024];\n    //         sprintf(buffer, \"mblock-lwr-%d-%d.txt\",\n    //                 blocks[i]->getn1(), blocks[i]->getn2());\n    //         arma::Col<ResultType> block((ResultType*)blocks[i]->getdata(),\n    //                                     blocks[i]->nvals());\n    //         arma::diskio::save_raw_ascii(block, buffer);\n    //     }\n\n    AhmedLeafClusterArray leafClusters(bemBlclusterTree.get());\n    leafClusters.sortAccordingToClusterSize();\n    const size_t leafClusterCount = leafClusters.size();\n\n    const ParallelizationOptions& parallelOptions =\n            options.parallelizationOptions();\n    int maxThreadCount = 1;\n    if (!parallelOptions.isOpenClEnabled())\n    {\n        if (parallelOptions.maxThreadCount() == ParallelizationOptions::AUTO)\n            maxThreadCount = tbb::task_scheduler_init::automatic;\n        else\n            maxThreadCount = parallelOptions.maxThreadCount();\n    }\n    tbb::task_scheduler_init scheduler(maxThreadCount);\n    tbb::atomic<size_t> done;\n    done = 0;\n\n    std::vector<ChunkStatistics> chunkStats(leafClusterCount);\n\n    //    typedef AcaWeakFormAssemblerLoopBody<BasisFunctionType, ResultType> Body;\n    //    // std::cout << \"Loop start\" << std::endl;\n    //    tbb::tick_count loopStart = tbb::tick_count::now();\n    // //    tbb::parallel_for(tbb::blocked_range<size_t>(0, leafClusterCount),\n    // //                      Body(helper, leafClusters, blocks, acaOptions, done\n    // //                           , chunkStats));\n    //    tbb::parallel_for(ScatteredRange(0, leafClusterCount),\n    //                      Body(helper, leafClusters, blocks, acaOptions, done\n    //                           , chunkStats));\n    //    tbb::tick_count loopEnd = tbb::tick_count::now();\n    //    // std::cout << \"Loop end\" << std::endl;\n\n    typedef AcaWeakFormAssemblerLoopBody<BasisFunctionType, ResultType> Body;\n    typename Body::LeafClusterIndexQueue leafClusterIndexQueue;\n    for (size_t i = 0; i < leafClusterCount; ++i)\n        leafClusterIndexQueue.push(i);\n\n    if (verbosityAtLeastDefault)\n        std::cout << \"About to start the ACA assembly loop\" << std::endl;\n    tbb::tick_count loopStart = tbb::tick_count::now();\n    {\n        Fiber::SerialBlasRegion region; // if possible, ensure that BLAS is single-threaded\n        tbb::parallel_for(tbb::blocked_range<size_t>(0, leafClusterCount),\n                          Body(helper, leafClusters, blocks, acaOptions, done,\n                               verbosityAtLeastDefault,\n                               leafClusterIndexQueue, symmetric, chunkStats));\n    }\n    tbb::tick_count loopEnd = tbb::tick_count::now();\n    if (verbosityAtLeastDefault) {\n        std::cout << \"\\n\"; // the progress bar doesn't print the final \\n\n        std::cout << \"ACA loop took \" << (loopEnd - loopStart).seconds() << \" s\"\n                  << std::endl;\n    }\n\n    // TODO: parallelise!\n    if (acaOptions.recompress) {\n        if (verbosityAtLeastDefault)\n            std::cout << \"About to start ACA agglomeration\" << std::endl;\n        agglH(bemBlclusterTree.get(), blocks.get(),\n              acaOptions.eps, acaOptions.maximumRank);\n        if (verbosityAtLeastDefault)\n            std::cout << \"Agglomeration finished\" << std::endl;\n    }\n\n    // // Dump timing data of individual chunks\n    //    std::cout << \"\\nChunks:\\n\";\n    //    for (int i = 0; i < leafClusterCount; ++i)\n    //        if (chunkStats[i].valid) {\n    //            int blockIndex = leafClusters[i]->getidx();\n    //            std::cout << chunkStats[i].chunkStart << \"\\t\"\n    //                      << chunkStats[i].chunkSize << \"\\t\"\n    //                      << (chunkStats[i].startTime - loopStart).seconds() << \"\\t\"\n    //                      << (chunkStats[i].endTime - loopStart).seconds() << \"\\t\"\n    //                      << (chunkStats[i].endTime - chunkStats[i].startTime).seconds() << \"\\t\"\n    //                      << blocks[blockIndex]->getn1() << \"\\t\"\n    //                      << blocks[blockIndex]->getn2() << \"\\t\"\n    //                      << blocks[blockIndex]->islwr() << \"\\t\"\n    //                      << (blocks[blockIndex]->islwr() ? blocks[blockIndex]->rank() : 0) << \"\\n\";\n    //        }\n\n    {\n        size_t origMemory = sizeof(ResultType) * testDofCount * trialDofCount;\n        size_t ahmedMemory = sizeH(bemBlclusterTree.get(), blocks.get());\n        int maximumRank = Hmax_rank(bemBlclusterTree.get(), blocks.get());\n        if (verbosityAtLeastDefault)\n            std::cout << \"\\nNeeded storage: \"\n                      << ahmedMemory / 1024. / 1024. << \" MB.\\n\"\n                      << \"Without approximation: \"\n                      << origMemory / 1024. / 1024. << \" MB.\\n\"\n                      << \"Compressed to \"\n                      << (100. * ahmedMemory) / origMemory << \"%.\\n\"\n                      << \"Maximum rank: \" << maximumRank << \".\\n\"\n                      << std::endl;\n\n        if (acaOptions.outputPostscript) {\n            if (verbosityAtLeastDefault)\n                std::cout << \"Writing matrix partition ...\" << std::flush;\n            std::ofstream os(acaOptions.outputFname.c_str());\n            if (symmetric) // seems valid also for Hermitian matrices\n                psoutputHeH(os, bemBlclusterTree.get(), testDofCount, blocks.get());\n            else\n                psoutputGeH(os, bemBlclusterTree.get(), testDofCount, blocks.get());\n            os.close();\n            if (verbosityAtLeastDefault)\n                std::cout << \" done.\" << std::endl;\n        }\n    }\n\n    int outSymmetry = NO_SYMMETRY;\n    if (symmetric) {\n        outSymmetry = SYMMETRIC;\n        if (!boost::is_complex<ResultType>())\n            outSymmetry |= HERMITIAN;\n    }\n    std::auto_ptr<DiscreteAcaLinOp> acaOp(\n                new DiscreteAcaLinOp(testDofCount, trialDofCount,\n                                     acaOptions.eps,\n                                     acaOptions.maximumRank,\n                                     outSymmetry,\n                                     bemBlclusterTree, blocks,\n                                     *trial_o2pPermutation,\n                                     *test_o2pPermutation,\n                                     parallelOptions));\n\n    std::auto_ptr<DiscreteBndOp> result;\n    if (indexWithGlobalDofs)\n        result = acaOp;\n    else {\n#ifdef WITH_TRILINOS\n        // without Trilinos, this code will never be reached -- an exception\n        // will be thrown earlier in this function\n        typedef DiscreteBoundaryOperatorComposition<ResultType> DiscreteBndOpComp;\n        shared_ptr<DiscreteBndOp> acaOpShared(acaOp.release());\n        shared_ptr<DiscreteBndOp> trialGlobalToLocal =\n                constructOperatorMappingGlobalToFlatLocalDofs<\n                BasisFunctionType, ResultType>(trialSpace);\n        shared_ptr<DiscreteBndOp> testLocalToGlobal =\n                constructOperatorMappingFlatLocalToGlobalDofs<\n                BasisFunctionType, ResultType>(testSpace);\n        shared_ptr<DiscreteBndOp> tmp(\n                    new DiscreteBndOpComp(acaOpShared, trialGlobalToLocal));\n        result.reset(new DiscreteBndOpComp(testLocalToGlobal, tmp));\n#endif // WITH_TRILINOS\n    }\n    return result;\n\n#else // without Ahmed\n    throw std::runtime_error(\"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n                             \"To enable assembly in ACA mode, recompile BEM++ \"\n                             \"with the symbol WITH_AHMED defined.\");\n#endif // WITH_AHMED\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteBoundaryOperator<ResultType> >\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assembleDetachedWeakForm(\n        const Space<BasisFunctionType>& testSpace,\n        const Space<BasisFunctionType>& trialSpace,\n        LocalAssembler& localAssembler,\n        const AssemblyOptions& options,\n        int symmetry)\n{\n    std::vector<LocalAssembler*> localAssemblers(1, &localAssembler);\n    std::vector<const DiscreteBndOp*> sparseTermsToAdd;\n    std::vector<ResultType> denseTermsMultipliers(1, 1.0);\n    std::vector<ResultType> sparseTermsMultipliers;\n\n    return assembleDetachedWeakForm(testSpace, trialSpace, localAssemblers,\n                            sparseTermsToAdd,\n                            denseTermsMultipliers,\n                            sparseTermsMultipliers,\n                            options, symmetry);\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(AcaGlobalAssembler);\n\n} // namespace Bempp\n", "meta": {"hexsha": "31b89cb22acf7eea174301dba7f54b0301491f91", "size": 21849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/aca_global_assembler.cpp", "max_stars_repo_name": "nicolas-chaulet/bempp", "max_stars_repo_head_hexsha": "0f5cc72e0e542437e787db5704978456b0ad9e35", "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": "lib/assembly/aca_global_assembler.cpp", "max_issues_repo_name": "nicolas-chaulet/bempp", "max_issues_repo_head_hexsha": "0f5cc72e0e542437e787db5704978456b0ad9e35", "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": "lib/assembly/aca_global_assembler.cpp", "max_forks_repo_name": "nicolas-chaulet/bempp", "max_forks_repo_head_hexsha": "0f5cc72e0e542437e787db5704978456b0ad9e35", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T09:46:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T09:46:44.000Z", "avg_line_length": 44.7725409836, "max_line_length": 102, "alphanum_fraction": 0.628541352, "num_tokens": 5073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.18945048087428024}}
{"text": "/**\n\nCopyright (c) 2016, Borella Jocelyn, Hanselmann Fabian, Heller Florian, Heizmann Heinrich, K\u00fcbler Marcel, Mehlhaus Jonas, Mei\u00dfner Pascal, Qattan Mohamad, Reckling Reno, Stroh Daniel\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#include <ros/ros.h>\n#include <dynamic_reconfigure/server.h>\n#include <std_msgs/Float64MultiArray.h>\n#include <std_msgs/Empty.h>\n#include <std_msgs/UInt32.h>\n#include <std_msgs/UInt32MultiArray.h>\n#include <std_msgs/String.h>\n\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\n#include <ISM/common_type/Point.hpp>\n#include <ISM/common_type/Track.hpp>\n#include <ISM/common_type/Tracks.hpp>\n#include <ISM/common_type/Object.hpp>\n#include \"ISM/recognizer/VotingSpace.hpp\"\n#include \"ISM/recorder/Recorder.hpp\"\n#include <ISM/utility/TableHelper.hpp>\n#include <ISM/utility/MathHelper.hpp>\n\n#include <asr_ism/recordGenConfig.h>\n\n#include <asr_ism_visualizations/ObjectModelVisualizerRVIZ.hpp>\n#include \"asr_ism_visualizations/VizHelperRVIZ.hpp\"\n\n#include <boost/filesystem/path.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/algorithm/string.hpp>\n\n//#include <eigen3/Eigen/Geometry.hpp>\n#include <eigen3/unsupported/Eigen/Splines>\n#include <Eigen/Geometry>\n\n//#include \"visStuff.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/random.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <random>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <math.h>\n#include <stdint.h>\n#include <tuple>\n\n\nusing visualization_msgs::MarkerArray;\nusing namespace VIZ;\n\ndouble frand(double min, double max) {\n\tdouble f = (double) rand() / RAND_MAX;\n\treturn min + f * (max - min);\n}\n\nenum class RecGenPointType\n{\n\tFix = 0,\n\tMidSpline = 1,\n\tMidSplineAlt = 2,\n\tUndefined = 3\n};\n\nnamespace H\n{\n    template<class C, class T>\n    auto contains(const C& v, const T& x)\n    -> decltype(end(v), true)\n    {\n\treturn end(v) != std::find(begin(v), end(v), x);\n    }\n}\n\nRecGenPointType recGenPointTypeFromString(const std::string& s)\n{\n\tif(s == \"Fix\")\n\t{\n\t\treturn RecGenPointType::Fix;\n\t} else if(s == \"MidSpline\")\n\t{\n\t\treturn RecGenPointType::MidSpline;\n\t} else if(s == \"MidSplineAlt\")\n\t{\n\t\treturn RecGenPointType::MidSplineAlt;\n\t}\n\n\treturn RecGenPointType::Undefined;\n}\n\nenum class OrientCalcType\n{\n\tFix = 0,\n    Random = 1,\n    Linear = 2,\n    Undefined = 3\n};\n\nOrientCalcType orientCalcTypeFromString(const std::string& s)\n{\n\tif(s == \"Fix\")\n\t{\n\t\treturn OrientCalcType::Fix;\n\t} else if (s == \"Random\")\n\t{\n\t\treturn OrientCalcType::Random;\n\t} else if (s == \"Linear\")\n\t{\n\t\treturn OrientCalcType::Linear;\n\t}\n\treturn OrientCalcType::Undefined;\n}\n\nclass RecordGenPoint\n{\npublic:\n\tRecordGenPoint(std::string name, int32_t id, RecGenPointType type, double posX, double posY,\n\t\t\tdouble posZ, double orientW, double orientX, double orientY, double orientZ,\n\t\t\tOrientCalcType orientCalcType, double posErr, double orientDerivation, unsigned int from,\n\t\t\tunsigned int to, double linearDegX, double linearDegY, double linearDegZ):\n\t\tmTimestep(0),\n\t\tmCurrentApplied(false),\n\t\tmName(name),\n\t\tmId(id),\n\t\tmType(type),\n\t\tmCurrentPosX(posX),\n\t\tmCurrentPosY(posY),\n\t\tmCurrentPosZ(posZ),\n\t\tmCurrentOrientW(orientW),\n\t\tmCurrentOrientX(orientX),\n\t\tmCurrentOrientY(orientY),\n\t\tmCurrentOrientZ(orientZ),\n\t    mInitOrientW(orientW),\n\t    mInitOrientX(orientX),\n\t    mInitOrientY(orientY),\n\t    mInitOrientZ(orientZ),\n\t\tmOrientCalcType(orientCalcType),\n\t\tmPosErr(posErr),\n\t\tmOrientDer(orientDerivation),\n\t\tmFrom(from),\n\t\tmTo(to),\n\t\tmLinearDegX(linearDegX),\n\t\tmLinearDegY(linearDegY),\n\t\tmLinearDegZ(linearDegZ),\n\t\tmUniform(-1,1),\n\t\tmNormal(0, mOrientDer)\n\n\t{\n\t\tif(mOrientCalcType == OrientCalcType::Undefined)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Type of OrientCalc is undefined\");\n\t\t}\n\t\tif(mType == RecGenPointType::Undefined)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Type of RecGenPoint is undefined\");\n\t\t}\n        mTrack.reset(new ISM::Track(name, boost::lexical_cast<std::string>(id)));\n\t\tstd::random_device rd;\n\t\tmRandomGen.seed(rd());\n\t\tmRandomGenOrient.seed(rd());\n\t\tmVariantGen = new boost::variate_generator<boost::mt19937, boost::uniform_real<>>\n\t\t\t\t(mRandomGen, mUniform);\n\t\tmVarGenOrient = new boost::variate_generator<boost::mt19937, boost::normal_distribution<>>\n\t\t\t\t(mRandomGenOrient, mNormal);\n\t}\n\tvirtual ~RecordGenPoint()\n\t{\n\t}\n\tvirtual bool isVisible() = 0;\n\tvirtual void calcCurrObPos() = 0;\n\tvirtual void calcCurrObOrient()\n\t{\n\t\tISM::PointPtr currPos;\n        if(mCurrentO && mCurrentO->pose)\n\t\t{\n            currPos = mCurrentO->pose->point;\n\t\t}\n\n\t\tswitch(mOrientCalcType)\n\t\t{\n\t\tcase OrientCalcType::Fix:\n\t\t{\n            mCurrentO.reset(new ISM::Object(mName,\n                            new ISM::Pose(currPos,\n                                    new ISM::Quaternion(mCurrentOrientW, mCurrentOrientX,\n                                    \t\tmCurrentOrientY, mCurrentOrientZ)),\n                                    \t\tboost::lexical_cast<std::string>(mId)));\n\n\t\t\tbreak;\n\t\t}\n\t\tcase OrientCalcType::Random:\n\t\t{\n\t\t\tmCurrentOrientW = (*mVariantGen)();\n\t\t\tmCurrentOrientX = (*mVariantGen)();\n\t\t\tmCurrentOrientY = (*mVariantGen)();\n\t\t\tmCurrentOrientZ = (*mVariantGen)();\n\n            mCurrentO.reset(new ISM::Object(mName,\n                            new ISM::Pose(mCurrentO->pose->point,\n                                    new ISM::Quaternion(mCurrentOrientW, mCurrentOrientX,\n                                    \t\tmCurrentOrientY, mCurrentOrientZ)),\n                                    \t\tboost::lexical_cast<std::string>(mId)));\n\t\t\tbreak;\n\t\t}\n\t\tcase OrientCalcType::Linear:\n\t\t{\n\t\t\tif(mTimestep > 0 && mFrom < mTo)\n\t\t\t{\n\t\t\t    const double pi = boost::math::constants::pi<double>();\n\t\t\t\tdouble totSpan = mTo - mFrom;\n\t\t\t\tdouble currentLinEulX = mLinearDegX * ((double) mTimestep) / totSpan\n\t\t\t\t\t\t*pi / 180.0;\n\t\t\t\tdouble currentLinEulY = mLinearDegY * ((double) mTimestep) / totSpan\n\t\t\t\t\t\t*pi / 180.0;\n\t\t\t\tdouble currentLinEulZ = mLinearDegZ * ((double) mTimestep) / totSpan\n\t\t\t\t\t\t*pi / 180.0;\n\n\t\t\t    Eigen::Quaterniond linQ = Eigen::AngleAxisd(currentLinEulX, Eigen::Vector3d::UnitX())\n\t\t\t     * Eigen::AngleAxisd(currentLinEulY, Eigen::Vector3d::UnitY())\n\t\t\t     * Eigen::AngleAxisd(currentLinEulZ, Eigen::Vector3d::UnitZ());\n\t\t\t    Eigen::Quaterniond q(mInitOrientW, mInitOrientX, mInitOrientY, mInitOrientZ);\n\t\t\t    Eigen::Quaterniond totalQ = q * linQ;\n\n\t\t\t    mCurrentOrientW = totalQ.w();\n\t\t\t    mCurrentOrientX = totalQ.x();\n\t\t\t    mCurrentOrientY = totalQ.y();\n\t\t\t    mCurrentOrientZ = totalQ.z();\n\t\t\t}\n\t\t\tmCurrentO.reset(new ISM::Object(mName,\n                    new ISM::Pose(mCurrentO->pose->point,\n\t\t\t\t\t\tnew ISM::Quaternion(mCurrentOrientW, mCurrentOrientX,\n\t\t\t\t\t\t\t\tmCurrentOrientY, mCurrentOrientZ)),\n\t\t\t\t\t\t\t\tboost::lexical_cast<std::string>(mId)));\n\t\t\tbreak;\n\t\t}\n\t\tcase OrientCalcType::Undefined:\n\t\t{\n\t\t\tthrow std::runtime_error(\"OrientCalcType is Undefined\");\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t}\n\tvirtual void forceInvisible(bool) = 0;\n\tvirtual void apply()\n\t{\n        if(!mCurrentO || !mCurrentO->pose->point ||\n                !mCurrentO->pose->quat)\n\t\t\tthrow \"RecordGenPoint: Current Object must always be initialized\";\n\t\tif(!mCurrentApplied)\n\t\t{\n            auto point = mCurrentO->pose->point;\n            auto quat = mCurrentO->pose->quat;\n            point->eigen.x() = point->eigen.x() + (*mVariantGen)() * mPosErr;\n            point->eigen.y() = point->eigen.y() + (*mVariantGen)() * mPosErr;\n            point->eigen.z() = point->eigen.z() + (*mVariantGen)() * mPosErr;\n            if(point->eigen.x() < -1.0 || point->eigen.x() > 1.0\n                    || point->eigen.y() < -1.0 || point->eigen.y() > 1.0\n                    ||point->eigen.z() < -1.0 || point->eigen.z() > 1.0 )\n\t\t\t{\n\t\t\t\tstd::cerr << \"Warning Point does not lie in range: \" << point << std::endl\n\t\t\t\t\t\t<< \"type: \" << mName << \" id: \" << mId << std::endl\n\t\t\t\t\t\t<< \"at timestep: \" << mTimestep << std::endl;\n\t\t\t\tstd::cin.ignore();\n\t\t\t}\n\t\t\tconst double pi = boost::math::constants::pi<double>();\n\n\t\t\tEigen::Matrix3d m;\n\t\t\tm = Eigen::AngleAxisd(pi * (*mVarGenOrient)(), Eigen::Vector3d::UnitX())\n\t\t\t * Eigen::AngleAxisd(pi * (*mVarGenOrient)(), Eigen::Vector3d::UnitY())\n\t\t\t * Eigen::AngleAxisd(pi * (*mVarGenOrient)(), Eigen::Vector3d::UnitZ());\n\n\t\t\tEigen::Quaterniond errorQ(m);\n\t\t\tEigen::Quaterniond q(quat->eigen.w(), quat->eigen.x(), quat->eigen.y(), quat->eigen.z());\n\t    Eigen::Quaterniond totalQ = q * errorQ;\n\n\t    quat->eigen.w() = totalQ.w();\n            quat->eigen.x() = totalQ.x();\n            quat->eigen.y() = totalQ.y();\n            quat->eigen.z() = totalQ.z();\n\t\t\t/*\n            quat->setW(quat->w);\n            quat->setX(quat->x);\n            quat->setY(quat->y);\n            quat->setZ(quat->z);\n\t\t\t*/\n\n            if(isVisible())\n            {\n\t\t//TODO not in current ws\n            \t//mCurrentO->mTimestep = mTimestep;\n                mTrack->objects.push_back(mCurrentO);\n            }\n            else\n            {\n                mTrack->objects.push_back(ISM::ObjectPtr());\n                std::cout << mName << \" is not visible\" << std::endl;\n            }\n\n            mCurrentApplied = true;\n\t\t}\n\t}\n\tvirtual void applyAndGotoNextTimestep()\n\t{\n\t\tapply();\n\t\t++mTimestep;\n\t\tmCurrentApplied = false;\n\t\tcalcCurrObPos();\n\t\tcalcCurrObOrient();\n\t}\n\n\tunsigned int mTimestep;\n\tbool mCurrentApplied;\n\tstd::string mName;\n\tint32_t mId;\n\tISM::TrackPtr mTrack;\n    ISM::ObjectPtr mCurrentO;\n    RecGenPointType mType;\n\tdouble mCurrentPosX;\n\tdouble mCurrentPosY;\n\tdouble mCurrentPosZ;\n\tdouble mCurrentOrientW;\n\tdouble mCurrentOrientX;\n\tdouble mCurrentOrientY;\n\tdouble mCurrentOrientZ;\n\tdouble mInitOrientW;\n\tdouble mInitOrientX;\n\tdouble mInitOrientY;\n\tdouble mInitOrientZ;\n\tOrientCalcType mOrientCalcType;\n\tdouble mPosErr;\n\tdouble mOrientDer;\n\tunsigned int mFrom;\n\tunsigned int mTo;\n\tdouble mLinearDegX;\n\tdouble mLinearDegY;\n\tdouble mLinearDegZ;\n\tboost::mt19937 mRandomGen;\n\tboost::mt19937 mRandomGenOrient;\n\tboost::uniform_real<> mUniform;\n\tboost::normal_distribution<> mNormal;\n    boost::variate_generator<boost::mt19937, boost::uniform_real<>>* mVariantGen;\n    boost::variate_generator<boost::mt19937, boost::normal_distribution<>>* mVarGenOrient;\n    //ISM::PosePtr mCurrentPose;\n};\n\nclass MidSplinePoint : public RecordGenPoint\n{\nprivate:\n\tvoid setCol(Eigen::MatrixXd &m, int col, Eigen::Vector3d &v, double time)\n\t{\n\t\tm(0, col) = time;\n\t\tm(1, col) = v.x();\n\t\tm(2, col) = v.y();\n\t\tm(3, col) = v.z();\n\t}\npublic:\n\tvoid calcSpline()\n\t{\n\t\tEigen::Vector3d s = Eigen::Vector3d(mXs, mYs , mZs);\n\t\tEigen::Vector3d e = Eigen::Vector3d(mXe, mYe , mZe);\n\t\tEigen::Vector3d sToe = e - s;\n        Eigen::Vector3d m = s + sToe/2;\n        Eigen::Vector3d temp = sToe;\n        temp.normalize();\n        temp = temp * 2;\n        Eigen::Vector3d orthSToe = temp.unitOrthogonal();\n        orthSToe.normalize();\n        orthSToe *= (sToe.norm()/2) * tan(mDegree * (boost::math::constants::pi<double>() / 180.0));\n        Eigen::Vector3d p3 = m + orthSToe;\n\n        //dimension, num points\n        int numPoints = 3;\n        double timeToNextPoint = mTimeSpan / (double) numPoints;\n        Eigen::MatrixXd points(4, numPoints);\n        setCol(points, 0, s, 0);\n        setCol(points, 1, p3, timeToNextPoint);\n        setCol(points, 2, e, mTimeSpan);\n        mSpline = Eigen::SplineFitting<Eigen::Spline<double, 4>>::Interpolate(points, numPoints - 1);\n\t}\n\tMidSplinePoint(std::string name, int32_t id, double xs, double ys, double zs,\n\t\t\tdouble xe, double ye, double ze, double degree, double timeSpan,\n\t\t\tdouble orientW, double orientX, double orientY, double orientZ,\n\t\t\tOrientCalcType orientCalcType, double posErr, double orientErr,\n\t\t\tunsigned int from, unsigned int to,\n\t\t\t double linearDegX, double linearDegY, double linearDegZ) :\n\t\t\t\tRecordGenPoint(name, id, RecGenPointType::MidSpline, xs, ys, zs, orientW,\n\t\t\t\t\t\torientX, orientY, orientZ, orientCalcType, posErr,\n\t\t\t\t\t\torientErr, from, to,\n\t\t\t\t\t\tlinearDegX, linearDegY, linearDegZ),\n\t\t\t\t\t\tmIsInvisible(false),\n                mXs(xs), mYs(ys), mZs(zs), mXe(xe), mYe(ye), mZe(ze), mDegree(degree), mTimeSpan(timeSpan)\n\t{\n\t\tcalcSpline();\n\t\tcalcCurrObPos();\n\t\tcalcCurrObOrient();\n\t}\n\n\tvoid setNewParams(double xs, double ys, double zs,\n\t\t\tdouble xe, double ye, double ze, double degree, double timeSpan)\n\t{\n\t\tmXs = xs;\n\t\tmYs = ys;\n\t\tmZs = zs;\n\n\t\tmXe = xe;\n\t\tmYe = ye;\n\t\tmZe = ze;\n\n\t\tmDegree = degree;\n\t\tmTimeSpan = timeSpan;\n\t\tcalcSpline();\n\t\tcalcCurrObPos();\n\t}\n\n\tvirtual ~MidSplinePoint()\n\t{\n\t}\n\n\tvirtual bool isVisible()\n\t{\n\t\treturn !mIsInvisible;\n\t}\n\n\tvirtual void forceInvisible(bool b)\n\t{\n\t\tmIsInvisible = b;\n\t}\n\n\tvirtual void calcCurrObPos()\n\t{\n\t\tISM::QuaternionPtr currOrient;\n        if(mCurrentO && mCurrentO->pose)\n\t\t{\n            currOrient = mCurrentO->pose->quat;\n\t\t}\n\n        Eigen::Vector4d values;\n\t\tif(mTimestep > mTimeSpan)\n          values = mSpline(1);\n\t\telse\n          values = mSpline(mTimestep/mTimeSpan);\n\n\t\tmCurrentPosX = values(1);\n\t\tmCurrentPosY = values(2);\n\t\tmCurrentPosZ = values(3);\n        mCurrentO.reset(new ISM::Object(mName,\n                        new ISM::Pose(new ISM::Point(mCurrentPosX, mCurrentPosY, mCurrentPosZ),\n                                currOrient), boost::lexical_cast<std::string>(mId)));\n\n\t}\n\tbool mIsInvisible;\n\tdouble mXs;\n\tdouble mYs;\n\tdouble mZs;\n\tdouble mXe;\n\tdouble mYe;\n\tdouble mZe;\n\tEigen::Spline<double, 4> mSpline;\n\tdouble mDegree;\n\tdouble mTimeSpan;\n};\n\nclass MidSplinePointAlt : public MidSplinePoint\n{\npublic:\n\tMidSplinePointAlt(std::string name, int32_t id, double xs, double ys, double zs,\n\t\t\tdouble xe, double ye, double ze, double degree, double timeSpan,\n\t\t\tdouble orientW, double orientX, double orientY, double orientZ,\n\t\t\tOrientCalcType orientCalcType, double posErr, double orientErr,\n\t\t\tunsigned int from, unsigned int to , double linearDegX, double linearDegY, double linearDegZ) :\n          MidSplinePoint(name, id, xs, ys, zs,\n                          xe, ye, ze, degree, timeSpan, orientW, orientX, orientY, orientZ,\n                          orientCalcType, posErr, orientErr, from, to, linearDegX, linearDegY, linearDegZ)\n    {\n\n    }\n\tvirtual void calcCurrObPos()\n\t{\n\t\tISM::QuaternionPtr currOrient;\n        if(mCurrentO && mCurrentO->pose)\n\t\t{\n            currOrient = mCurrentO->pose->quat;\n\t\t}\n\n        Eigen::Vector4d values;\n        int timesTimeSpan = mTimestep / mTimeSpan;\n\t\tif((timesTimeSpan % 2) == 0)\n          values = mSpline((mTimestep - (timesTimeSpan * mTimeSpan)) / mTimeSpan);\n\t\telse\n          values = mSpline(1 - (mTimestep - (timesTimeSpan * mTimeSpan)) / mTimeSpan);\n\n\t\tmCurrentPosX = values(1);\n\t\tmCurrentPosY = values(2);\n\t\tmCurrentPosZ = values(3);\n        mCurrentO.reset(new ISM::Object(mName,\n                        new ISM::Pose(new ISM::Point(mCurrentPosX, mCurrentPosY, mCurrentPosZ),\n                                currOrient), boost::lexical_cast<std::string>(mId)));\n\n\t}\n};\nclass FixRecordGenPoint : public RecordGenPoint\n{\npublic:\n\tFixRecordGenPoint(std::string name, int32_t id, double x, double y, double z,\n\t\t\tdouble orientW, double orientX, double orientY, double orientZ,\n\t\t\tOrientCalcType orientCalcType, double posErr, double orientErr,\n\t\t\tunsigned int from, unsigned int to, double linearDegX, double linearDegY, double linearDegZ):\n\t\tRecordGenPoint(name, id, RecGenPointType::Fix, x, y, z, orientW, orientX, orientY, orientZ,\n\t\t\t\torientCalcType, posErr, orientErr, from, to, linearDegX, linearDegY, linearDegZ),\n\t\tmIsInvisible(false)\n\t{\n\t\tcalcCurrObPos();\n\t\tcalcCurrObOrient();\n#if 0\n        if(mTimestep > 0)\n        {\n        \tunsigned int desTs = mTimestep;\n        \tmTimestep = 0;\n        \tforceInvisible(true);\n            for(unsigned int i = 0; i < desTs; ++i)\n            {\n            \tapplyAndGotoNextTimestep();\n            }\n            forceInvisible(false);\n        }\n#endif\n\t}\n\n\tvirtual ~FixRecordGenPoint()\n\t{\n\t}\n\n\tvoid setNewParams(double x, double y, double z)\n\t{\n\t\tmCurrentPosX = x;\n\t\tmCurrentPosY = y;\n\t\tmCurrentPosZ = z;\n\t\tcalcCurrObPos();\n\t}\n\n\tvirtual bool isVisible()\n\t{\n\t\treturn !mIsInvisible;\n\t}\n\n\tvirtual void forceInvisible(bool b)\n\t{\n\t\tmIsInvisible = b;\n\t}\n\n\tvirtual void calcCurrObPos()\n\t{\n\t\tISM::QuaternionPtr currOrient;\n        if(mCurrentO && mCurrentO->pose)\n\t\t{\n            currOrient = mCurrentO->pose->quat;\n\t\t}\n        mCurrentO.reset(new ISM::Object(mName,\n                        new ISM::Pose(new ISM::Point(mCurrentPosX, mCurrentPosY, mCurrentPosZ),\n                                        currOrient), boost::lexical_cast<std::string>(mId)));\n\n\t}\n\n\tbool mIsInvisible;\n};\n\nusing boost::filesystem::path;\ntypedef boost::shared_ptr<RecordGenPoint> RecordGenPointPtr;\ntypedef std::tuple<uint32_t,uint32_t,RecordGenPointPtr> FromToPointTuple;\nnamespace pt = boost::property_tree;\n\nstruct cmpFromToPointTuple {\n    bool operator()(const FromToPointTuple& a, const FromToPointTuple& b) const {\n    \tif(std::get<2>(a)->mName == std::get<2>(b)->mName &&\n    \t\t\tstd::get<2>(a)->mId == std::get<2>(b)->mId)\n    \t{\n    \t\treturn std::get<1>(a) < std::get<0>(b);\n    \t} else\n    \t{\n    \t\treturn (uintptr_t)(std::get<2>(a).get()) < (uintptr_t)(std::get<2>(b).get());\n    \t}\n    }\n};\n\nclass RecordGenerator\n{\npublic:\n\tvoid parseXml(path xmlFile)\n\t{\n\t\tpt::ptree tree;\n\n\t\tpt::read_xml(xmlFile.string(), tree);\n\n\t\tfor(auto& fstLvlNode : tree)\n\t\t{\n\t\t\tif(fstLvlNode.first == \"object\")\n\t\t\t{\n\t\t\t\tstd::string name = fstLvlNode.second.get<std::string>(\"<xmlattr>.name\");\n\t\t\t\tint32_t id = fstLvlNode.second.get<int32_t>(\"<xmlattr>.id\");\n                ISM::TrackPtr sharedTrack = ISM::TrackPtr(new ISM::Track(name,\n                \t\tboost::lexical_cast<std::string>(id)));\n                mTracks.push_back(sharedTrack);\n\t\t\t\tfor(auto& pointNode : fstLvlNode.second)\n\t\t\t\t{\n                    if(pointNode.first == \"point\")\n                    {\n                        auto& pointAttrs = pointNode.second;\n\n                        RecGenPointType pointType = recGenPointTypeFromString\n                                        (pointAttrs.get<std::string>(\"<xmlattr>.type\", \"\"));\n                        int from = pointAttrs.get<uint32_t>(\"from\");\n                        int to = pointAttrs.get<uint32_t>(\"to\");\n                        if(from > to)\n                        {\n                        \tstd::stringstream ss;\n                        \tss << \"At: \" << name << \",\" << id << \" from must be less than to\";\n                        \tthrow std::runtime_error(ss.str());\n                        }\n                        double posX = pointAttrs.get<double>(\"posX\", 0.0);\n                        double posY = pointAttrs.get<double>(\"posY\", 0.0);\n                        double posZ = pointAttrs.get<double>(\"posZ\", 0.0);\n                        double orientW = pointAttrs.get<double>(\"orientW\", 0.0);\n                        double orientX = pointAttrs.get<double>(\"orientX\", 0.0);\n                        double orientY = pointAttrs.get<double>(\"orientY\", 0.0);\n                        double orientZ = pointAttrs.get<double>(\"orientZ\", 0.0);\n                        double xs = pointAttrs.get<double>(\"xs\", 0.0);\n                        double ys = pointAttrs.get<double>(\"ys\", 0.0);\n                        double zs = pointAttrs.get<double>(\"zs\", 0.0);\n                        double xe = pointAttrs.get<double>(\"xe\", 0.0);\n                        double ye = pointAttrs.get<double>(\"ye\", 0.0);\n                        double ze = pointAttrs.get<double>(\"ze\", 0.0);\n                        double degree = pointAttrs.get<double>(\"degree\", 0.0);\n                        double timeSpan = pointAttrs.get<double>(\"timeSpan\", 0.0);\n                        double posErr = pointAttrs.get<double>(\"posErr\", 0.0);\n                        double orientErr = pointAttrs.get<double>(\"orientErr\", 0.0);\n                        double linearDegX = pointAttrs.get<double>(\"linearDegX\", 0.0);\n                        double linearDegY = pointAttrs.get<double>(\"linearDegY\", 0.0);\n                        double linearDegZ = pointAttrs.get<double>(\"linearDegZ\", 0.0);\n                        OrientCalcType oCT = orientCalcTypeFromString(pointAttrs.get<std::string>(\"orientCalcType\", \"\"));\n                        std::vector<unsigned int> timestampVisible;\n                        for(auto& pointAttr : pointAttrs)\n                        {\n                                if(pointAttr.first == \"visible\")\n                                {\n                                        std::string rangeString = pointAttr.second.get_value(\"\");\n                                        std::vector<std::string> range;\n                                        boost::split(range, rangeString, boost::is_any_of(\"-\"));\n                                        if(range.size() == 2)\n                                        {\n                                                for(unsigned int i = boost::lexical_cast<unsigned int>(range[0]);\n                                                                i <= boost::lexical_cast<unsigned int>(range[1]); ++i)\n                                                {\n                                                        timestampVisible.push_back(i);\n                                                }\n                                        } else\n                                        {\n                                                timestampVisible.push_back(boost::lexical_cast<unsigned int>(range[0]));\n                                        }\n                                }\n                        }\n                        RecordGenPointPtr p;\n                        switch(pointType)\n                        {\n                        case RecGenPointType::Fix:\n                        {\n                                p = RecordGenPointPtr(new FixRecordGenPoint(name, id, posX, posY, posZ, orientW,\n                                                orientX, orientY, orientZ, oCT, posErr, orientErr, from, to\n                                                ,linearDegX, linearDegY, linearDegZ));\n                                break;\n                        }\n                        case RecGenPointType::MidSpline:\n                        {\n                                p = RecordGenPointPtr(new MidSplinePoint(name, id, xs, ys, zs, xe, ye, ze, degree,\n                                                timeSpan, orientW, orientX, orientY, orientZ, oCT, posErr, orientErr, from, to,\n                                                 linearDegX, linearDegY, linearDegZ));\n                                break;\n                        }\n                        case RecGenPointType::MidSplineAlt:\n                        {\n                                p = RecordGenPointPtr(new MidSplinePointAlt(name, id, xs, ys, zs, xe, ye, ze, degree,\n                                        timeSpan, orientW, orientX, orientY, orientZ, oCT, posErr, orientErr, from, to,\n                                         linearDegX, linearDegY, linearDegZ));\n                                break;\n                        }\n\n                        default:\n                                throw std::runtime_error(\"Error in parsing xml: RecGenPointType not valid\");\n                                break;\n                        }\n                        mTimestampVisibleXmlPoints[p] = timestampVisible;\n                        p->mTrack = sharedTrack;\n                        auto itToSucceed = mPoints.insert(std::make_tuple(from,to,p));\n                        if(!itToSucceed.second)\n                        {\n\t\t\t\t\t\t\tstd::stringstream ss;\n                        \tss << \"At: \" << name << \",\" << id << \" point intervals overlapping\";\n                        \tthrow std::runtime_error(ss.str());\n                        }\n                    }\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n    void dynamicReconfCallback(asr_ism::recordGenConfig &config, uint32_t level)\n    {\n    \tmShowFrom = config.from;\n    \tmShowTo = config.to;\n    }\n\n\tRecordGenerator(std::string dbFile,\n\t\t\tstd::string patternName = \"pattern0\", bool doPublish = false):\n\t\tmNextId(0),\n\t\tmTimestep(0),\n\t\tmDbFile(dbFile),\n\t\tmFilterViaVgOut(false),\n\t\tmPatternName(patternName),\n\t\tmShowCurrent(false),\n\t\tmDoPublish(doPublish),\n\t\tmShowFrom(0),\n\t\tmShowTo(0)\n\t{\n            dynamic_reconfigure::Server<asr_ism::recordGenConfig>::CallbackType f = boost::bind(&RecordGenerator::dynamicReconfCallback, this, _1, _2);\n\t    mDynReconfServer.setCallback(f);\n\t\trec.reset(new ISM::Recorder(mDbFile));\n\t\t//TODO drop tables?\n        //rec->dropTables();\n\t}\n\n\tvoid filterViaVgOut(boost::filesystem::path vgOutFile)\n\t{\n\t\tmFilterViaVgOut = true;\n\t\tstd::ifstream is(vgOutFile.string());\n\t\tstd::string line;\n\t\tstd::string type;\n\t\tstd::string pattern;\n\t\tbool foundRep = true;\n\t\twhile(std::getline(is, line))\n\t\t{\n\t\t\tif(line.find(\"Ref is:\") != std::string::npos)\n\t\t\t{\n\t\t\t\tline.erase(line.begin(), line.begin() + line.find_first_of(\":\") + 1);\n\t\t\t\tmPatternToRef[pattern] = line;\n\t\t\t}\n\t\t\tif(line.find(\"Id for pattern:\") != std::string::npos)\n\t\t\t{\n\t\t\t\tline.erase(line.begin(), line.begin() + line.find_first_of(\":\") + 1);\n\t\t\t\tpattern = line;\n\t\t\t} else if(line.find(\"Id for type:\") != std::string::npos)\n\t\t\t{\n\t\t\t\tline.erase(line.begin(), line.begin() + line.find_first_of(\":\") + 1);\n\t\t\t\ttype = line;\n\t\t\t} else if(line.find(\"These trackIds are in the same Orient Grid:\") != std::string::npos)\n\t\t\t{\n\t\t\t\tfoundRep = false;\n\t\t\t} else if(!foundRep)\n\t\t\t{\n\t\t\t\tuint32_t rep = 0;\n\t\t\t\ttry\n\t\t\t\t{\n                    rep = boost::lexical_cast<uint32_t>(line);\n\t\t\t\t} catch(boost::bad_lexical_cast& e)\n                {\n\t\t\t\t\tcontinue;\n                }\n\t\t\t\tmPatternTypeToVoxelReps[std::make_pair(pattern,type)].insert(rep);\n\t\t\t\tfoundRep = true;\n\t\t\t}\n\t\t}\n\t\tfor(auto& patternTypeToVoxelReps : mPatternTypeToVoxelReps)\n\t\t{\n\t\t\tstd::string pattern = patternTypeToVoxelReps.first.first;\n\t\t\tstd::string type = patternTypeToVoxelReps.first.second;\n\t\t\tfor(uint32_t rep : patternTypeToVoxelReps.second)\n\t\t\t{\n\t\t\t    std::cout << \"Rep for p: \" << pattern << \" t: \" << type << \" is: \" << rep << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid applyAndGotoNextTimestep()\n\t{\n        for(auto& fromToPoint : mPoints)\n        {\n\t\t    if(std::get<0>(fromToPoint) <= mTimestep &&\n\t\t\t    std::get<1>(fromToPoint) >= mTimestep)\n\t\t    {\n\t\t\t    auto& p = std::get<2>(fromToPoint);\n\t\t\t    std::vector<unsigned int>& visTs = mTimestampVisibleXmlPoints[p];\n\n\t\t\t    if(std::find(visTs.begin(), visTs.end(), mTimestep) != visTs.end())\n\t\t\t    {\n\t\t\t\t    p->forceInvisible(false);\n\t\t\t    } else\n\t\t\t    {\n\t\t\t\t    p->forceInvisible(true);\n\t\t\t    }\n\t\t\t    p->applyAndGotoNextTimestep();\n\t\t    }\n        }\n\t    mTimestep++;\n\t}\n\n\tvoid apply()\n\t{\n        for(auto& fromToPoint : mPoints)\n        {\n\t\t    if(std::get<0>(fromToPoint) <= mTimestep &&\n\t\t\t    std::get<1>(fromToPoint) >= mTimestep)\n\t\t    {\n\t\t\t    auto& p = std::get<2>(fromToPoint);\n\t\t\t    std::vector<unsigned int>& visTs = mTimestampVisibleXmlPoints[p];\n\n\t\t\t    if(std::find(visTs.begin(), visTs.end(), mTimestep) != visTs.end())\n\t\t\t    {\n\t\t\t\t    p->forceInvisible(false);\n\t\t\t    } else\n\t\t\t    {\n\t\t\t\t    p->forceInvisible(true);\n\t\t\t    }\n\t\t\t    p->apply();\n\t\t    }\n        }\n\t}\n\n\tvoid applyAndGotoNextTimestep(const uint32_t n)\n\t{\n\t\tfor(unsigned int i = 0; i < n; ++i)\n\t\t{\n\t\t\tapplyAndGotoNextTimestep();\n\t\t}\n\t}\n\n\tstd::vector<ISM::ObjectPtr> getCurrentVisibleObjects()\n    {\n\t\tstd::vector<ISM::ObjectPtr> result;\n\t\tfor(auto& fromToPoint : mPoints)\n\t\t{\n\t\t    if(std::get<0>(fromToPoint) <= mTimestep &&\n\t\t\t    std::get<1>(fromToPoint) >= mTimestep)\n\t\t    {\n\t\t\t    auto& p = std::get<2>(fromToPoint);\n\t\t\t    if(p->isVisible())\n\t\t\t    {\n\t\t\t\t    result.push_back(p->mCurrentO);\n\t\t\t    }\n\t\t    }\n\t\t}\n\t\treturn result;\n    }\n\n\tstd::vector<ISM::ObjectPtr> getCurrentInvisibleObjects()\n    {\n\t\tstd::vector<ISM::ObjectPtr> result;\n\t\tfor(auto& fromToPoint : mPoints)\n\t\t{\n\t\t    if(std::get<0>(fromToPoint) <= mTimestep &&\n\t\t\t    std::get<1>(fromToPoint) >= mTimestep)\n\t\t    {\n\t\t\t    auto& p = std::get<2>(fromToPoint);\n\t\t\t    if(!p->isVisible())\n\t\t\t    {\n\t\t\t\t    result.push_back(p->mCurrentO);\n\t\t\t    }\n\t\t    }\n\t\t}\n\t\treturn result;\n    }\n\n\t//void showFromTo(std_msgs::UInt32MultiArray::ConstPtr& msg)\n\tvoid showFromTo(const std_msgs::Float64MultiArray::ConstPtr& msg)\n\t{\n\t    mShowFrom = *msg->data.begin();\n\t    mShowTo = *(msg->data.begin() + 1);\n\t    mShowCurrent = false;\n\t}\n\n    std::vector<ISM::ObjectPtr> getObjects(unsigned int from, unsigned int to)\n    {\n\tstd::vector<ISM::ObjectPtr> result;\n    \tstatic unsigned int oldTo = to;\n    \tif(!mDoPublish)\n    \t{\n            if(to == oldTo)\n            {\n                    return result;\n            } else\n            {\n                    oldTo = to;\n            }\n            ROS_INFO_STREAM(\"from is \" << from << \" << to: \" <<to );\n    \t}\n    \tif(mTimestep < to)\n    \t{\n    \t\t//TODO\n    \t\tapplyAndGotoNextTimestep(to - mTimestep);\n    \t}\n\n    \tif(mTimestep == to)\n    \t{\n\t\t    apply();\n    \t}\n\t\tif(from <= to)\n\t\t{\n\t\t\tfor(auto& t : mTracks)\n\t\t\t{\n\t\t\t\tbool isRef = false;\n                if(mFilterViaVgOut)\n                {\n                \tstd::vector<std::string> isRefInPatterns;\n                \tfor(auto& patternToRef : mPatternToRef)\n                \t{\n                \t\tif(patternToRef.second == t->type)\n                \t\t{\n                \t\t\tisRefInPatterns.push_back(patternToRef.first);\n                \t\t}\n                \t}\n                \tif(isRefInPatterns.size() > 0)\n                \t{\n                \t\tisRef = true;\n                \t\tfor(auto& patternTypeToReps : mPatternTypeToVoxelReps)\n                \t\t{\n                \t\t\tif(patternTypeToReps.first.second != t->type\n                \t\t\t\t\t&& H::contains(isRefInPatterns, patternTypeToReps.first.first))\n                \t\t\t{\n                \t\t\t\tfor(uint32_t repTs : patternTypeToReps.second)\n                \t\t\t\t{\n\t\t\t\t\t\t\t\t    if(from <= repTs && repTs <= to && !H::contains(result,\n\t\t\t\t\t\t\t\t    \t\tt->objects[repTs]))\n\t\t\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t\t    \tresult.push_back(t->objects[repTs]);\n\t\t\t\t\t\t\t\t    }\n                \t\t\t\t}\n                \t\t\t}\n                \t\t}\n                \t}\n                }\n                if((!isRef && mFilterViaVgOut) || !mFilterViaVgOut)\n                {\n\t\t\t\t    if(t->objects.size() > to)\n\t\t\t\t    {\n\t\t\t\t\t    {\n\t\t\t\t\t\t\t//TODO why did i do this?\n\t\t\t\t\t\t    result.insert(result.end(), t->objects.begin() + from, t->objects.begin() + to + 1);\n\t\t\t\t\t    }\n\t\t\t\t    } else if(t->objects.size() > from)\n\t\t\t\t    {\n\t\t\t\t\t    result.insert(result.end(), t->objects.begin() + from, t->objects.end());\n\t\t\t\t    }\n                }\n\t\t\t}\n\t\t}\n\t\t/*\n\t\tROS_INFO_STREAM(\"-------\");\n\t\tfor(auto& o : result)\n\t\t{\n\t\t\tif(o)\n\t\t\t{\n\t\t\t\tROS_INFO_STREAM(o);\n\t\t\t}\n\t\t}\n\t\tROS_INFO_STREAM(\"-------\");\n\t\t*/\n\t\treturn result;\n    }\n\n\tstd::vector<ISM::ObjectPtr> getOldObjects()\n    {\n\t\tif(mTimestep == 0)\n\t\t{\n\t\t\treturn std::vector<ISM::ObjectPtr>();\n\t\t}\n\t\treturn getObjects(0, mTimestep -1);\n    }\n\n\tvoid writeToDb()\n\t{\n\t\tuint32_t maxTimestep = std::get<1>(*mPoints.rbegin());\n\t\tif(maxTimestep > mTimestep)\n\t\t{\n\t\t\tapplyAndGotoNextTimestep(maxTimestep - mTimestep);\n\t\t\tapply();\n\t\t}\n        ROS_INFO_STREAM(\"Writing to database\");\n\t\tapply();\n        ISM::TracksPtr tracks(new ISM::Tracks(mTracks));\n        auto objectSets = tracks->toObjectSetVector();\n        for (auto objectSet : objectSets) {\n            rec->insert(objectSet, mPatternName);\n        }\n        ROS_INFO_STREAM(\"Finished\");\n\t}\n\n\tvoid writeToDb(const std_msgs::Empty)\n\t{\n\t\twriteToDb();\n\t}\n\nprivate:\n    int32_t mNextId;\n    std::vector<int32_t> mIdXmlPoints;\n    std::map<RecordGenPointPtr, std::vector<unsigned int> > mTimestampVisibleXmlPoints;\n    dynamic_reconfigure::Server<asr_ism::recordGenConfig> mDynReconfServer;\n\npublic:\n\tunsigned int mTimestep;\n\tstd::string mDbFile;\n\tbool mFilterViaVgOut;\n\tstd::map<std::pair<std::string, std::string>, std::set<uint32_t>> mPatternTypeToVoxelReps;\n\tstd::map<std::string, std::string> mPatternToRef;\n\tstd::string mPatternName;\n\n\tstd::set<std::tuple<uint32_t,uint32_t,RecordGenPointPtr>, cmpFromToPointTuple> mPoints;\n\tstd::vector<ISM::TrackPtr> mTracks;\n\tISM::RecorderPtr rec;\n\tbool mShowCurrent;\n\tbool mDoPublish;\n\tuint32_t mShowFrom;\n\tuint32_t mShowTo;\n};\n\nstd_msgs::ColorRGBA getColorForTypeId(std::map<std::pair<std::string,std::string>, std_msgs::ColorRGBA >&\n    typeIdToColor, std::vector<std_msgs::ColorRGBA>& allColors, uint32_t& availColorIndex,\n    std::string& type, std::string& id)\n{\n\tstd_msgs::ColorRGBA result;\n\tif(typeIdToColor.find(std::make_pair(type,id)) != typeIdToColor.end())\n\t{\n\t\tresult = typeIdToColor[std::make_pair(type,id)];\n\t} else\n\t{\n\t\tif(allColors.size() < availColorIndex + 1)\n\t\t{\n\t\t\tstd::uniform_real_distribution<float> urd;\n\t\t\tstd::default_random_engine re;\n\t\t\tresult = VIZ::VizHelperRVIZ::createColorRGBA(urd(re), urd(re), urd(re), 1);\n\t\t\tallColors.push_back(result);\n\t\t} else\n\t\t{\n\t\t\tresult = allColors[availColorIndex];\n\t\t}\n\t\ttypeIdToColor[std::make_pair(type, id)] = result;\n\t\t++availColorIndex;\n\t}\n\treturn result;\n}\n\nint main(int argc, char** argv) {\n\tros::init(argc, argv, \"recordGen\");\n\tros::NodeHandle n(\"~\");\n\tros::Rate r(1);\n\tstd::string baseFrame = \"/camera_left_frame\";\n\tstd::string visualizationTopic = \"/visualization_marker\";\n\tstd::string dbFile;//(\"/media/share/data/own/gen1.sqlite\");\n    double bin_size = 0.03;\n\tdouble maxAngleDeviation = 10;\n\tbool useXml = false;\n\tbool useVgOut = false;\n\tboost::filesystem::path xmlFile;\n\tboost::filesystem::path vgOutFile;\n    bool detailedBinNS;\n\tbool doPublish;\n\n    if (!n.getParam(\"dbfilename\", dbFile)) {\n    \tthrow std::runtime_error(\"dbfilename not set\");\n    }\n    ROS_INFO_STREAM(\"dbfilename: \" << dbFile);\n\n    std::string temp;\n    if (n.getParam(\"xml\", temp)) {\n    \tuseXml = true;\n    \txmlFile = temp;\n    }\n    xmlFile = temp;\n    ROS_INFO_STREAM(\"xml: \" << temp);\n\n    if (n.getParam(\"vgOut\", temp)) {\n    \tvgOutFile = temp;\n    \tif(boost::filesystem::is_regular_file(vgOutFile))\n    \t{\n\t\t    useVgOut = true;\n    \t} else\n    \t{\n    \t\tuseVgOut = false;\n    \t}\n    }\n    vgOutFile = temp;\n    if(useVgOut)\n    {\n\t    ROS_INFO_STREAM(\"vgOut: \" << vgOutFile);\n    }\n\n    if (!n.getParam(\"detailedBinNS\", detailedBinNS)) {\n        detailedBinNS = false;\n    }\n    ROS_INFO_STREAM(\"detailedBinNS: \" << detailedBinNS);\n\n    if (!n.getParam(\"doPublish\", doPublish)) {\n    \tdoPublish = false;\n    }\n    ROS_INFO_STREAM(\"doPublish: \" << doPublish);\n\n    if (!n.getParam(\"bin_size\", bin_size)) {\n        bin_size = 0.03;\n    }\n    ROS_INFO_STREAM(\"bin_size: \" << bin_size);\n\n    RecordGenerator rg(dbFile, \"pattern0\", doPublish);\n    if(useXml)\n    {\n    \trg.parseXml(xmlFile);\n    }\n    if(useVgOut)\n    {\n    \trg.filterViaVgOut(vgOutFile);\n    }\n\n\tros::Publisher visPub = n.advertise<visualization_msgs::MarkerArray>(visualizationTopic, 100);\n\n\n    ISM::VotingSpace vs = ISM::VotingSpace(bin_size, maxAngleDeviation);\n    //std_msgs::ColorRGBA  regularBinColor = VizHelperRVIZ::createColorRGBA(0.0, 1.0, 0.0, 1.0);\n    //std_msgs::ColorRGBA  regularObjectColor = VizHelperRVIZ::createColorRGBA(0.0, 1.0, 0.0, 1.0);\n    //const double sphereRadius = 0.005;\n    //const double markerLifetime = ros::Duration().toSec();\n\n    /*\n    ros::Subscriber s0 = n.subscribe<std_msgs::Float64MultiArray>(\"addPoint\", 1000, &RecordGenerator::addPoint, &rg);\n    ros::Subscriber s1 = n.subscribe<std_msgs::UInt32>(\"applyAndGotoNextTimestep2\", 1000, &RecordGenerator::applyAndGotoNextTimestep, &rg);\n    ros::Subscriber s3 = n.subscribe<std_msgs::Float64MultiArray>(\"changeParameter\", 1000, &RecordGenerator::changeParameter, &rg);\n    ros::Subscriber s4 = n.subscribe<std_msgs::String>(\"toogleInvis\", 1000, &RecordGenerator::toogleInvisible, &rg);\n    */\n    ros::Subscriber s1 = n.subscribe<std_msgs::Float64MultiArray>(\"showFromTo\", 1000, &RecordGenerator::showFromTo, &rg);\n    //ros::Subscriber s1 = n.subscribe<std_msgs::UInt32MultiArray>(\"showFromTo\", 1000, &RecordGenerator::showFromTo, &rg);\n    ros::Subscriber s2 = n.subscribe<std_msgs::Empty>(\"writeToDb\", 1000, &RecordGenerator::writeToDb, &rg);\n\n    std::vector<std_msgs::ColorRGBA> allColors;\n    allColors.push_back(VIZ::VizHelperRVIZ::createColorRGBA(0.0,0.0,0.0,1.0));\n    allColors.push_back(VIZ::VizHelperRVIZ::createColorRGBA(1.0,0.0,0.0,1.0));\n    allColors.push_back(VIZ::VizHelperRVIZ::createColorRGBA(0.0,1.0,0.0,1.0));\n    allColors.push_back(VIZ::VizHelperRVIZ::createColorRGBA(0.0,0.0,1.0,1.0));\n    allColors.push_back(VIZ::VizHelperRVIZ::createColorRGBA(0.5,0.2,0.9,1.0));\n    allColors.push_back(VIZ::VizHelperRVIZ::createColorRGBA(0.3,0.8,0.8,1.0));\n    allColors.push_back(VIZ::VizHelperRVIZ::createColorRGBA(0.3,0.5,0.5,1.0));\n    allColors.push_back(VIZ::VizHelperRVIZ::createColorRGBA(0.5,0.3,0.1,1.0));\n\n    std::map<std::pair<std::string,std::string>, std_msgs::ColorRGBA > typeIdToColor;\n    //uint32_t availColorIndex = 0;\n\n    /*\n    boost::function< geometry_msgs::Point (int,int,int) > pointF = boost::bind(genCuboidPoint, _1, _2, _3, x, y, z, xwitdh, ywidth, zwidth);\nstd_msgs::ColorRGBA getColor(std::map<std::pair<std::string,std::string>, std_msgs::ColorRGBA >&\n    typeIdToColor, std::vector<std_msgs::ColorRGBA>& allColors, uint32_t& availColorIndex,\n    const std::string& type, const std::string& id)\n    */\n\n /*   boost::function < std_msgs::ColorRGBA (const std::string,const std::string) > getColor =\n                boost::bind(getColorForTypeId, boost::ref(typeIdToColor), boost::ref(allColors),\n                                boost::ref(availColorIndex), _1, _2);\n*/\n    while (ros::ok()) {\n\n        ///deleted for visualization refectoring. Bins now drawn at ism_voting_visualizer\n    /*    std::map<std::tuple<int,int,int>,bool> binDrawn;\n\n    \tMarkerArray oBs;\n    \tMarkerArray bins;\n        ros::spinOnce();\n        //TODO\n        if(rg.mShowCurrent)\n        {\n\t\t\tfor(ISM::ObjectPtr& o : rg.getCurrentVisibleObjects())\n\t\t\t{\n                ISM::PointPtr point = o->pose->point;\n\t\t\t\tstd::stringstream ss;\n                ss << o->getType() << \" With X:\" << point->eigen.x() << \"Y:\" << point->eigen.y() << \"Z:\" << point->eigen.z();\n\t\t\t\toBs.markers.push_back(VIZ::VizHelperRVIZ::createSphereMarker(point, baseFrame, ss.str(),\n\t\t\t\t\t\tboost::lexical_cast<int32_t>(o->getId()), sphereRadius, regularObjectColor, markerLifetime));\n                //TODO: look for better solution than hard-code binSize; Problem introduced because of deletion of calcBinNum in VotingSpace\n                int x = vs.discretizeToBins(point->eigen.x(), 0.1);\n                int y = vs.discretizeToBins(point->eigen.y(), 0.1);\n                int z = vs.discretizeToBins(point->eigen.z(), 0.1);\n\t\t\t    std::tuple<int,int,int> t = std::make_tuple(x, y, z);\n\t\t\t    if(binDrawn[t] == false)\n\t\t\t    {\n\t\t\t\t    std::stringstream ss;\n\t\t\t\t    ss << \"\\nObject\" << o->getId() << \"Is in Bin: \"<< \"X:\" << x << \" Y:\" << y << \" Z:\" << z;\n\t\t\t\t    bins.markers.push_back(VIZ::VizHelperRVIZ::getBinMarker(x, y, z, bin_size, ss.str(), 0, baseFrame,\n\t\t\t\t\t\t    regularBinColor));\n\t\t\t\t    binDrawn[t] = true;\n\t\t\t    }\n\t\t\t}\n\t\t\tfor(ISM::ObjectPtr& o : rg.getCurrentInvisibleObjects())\n\t\t\t{\n                ISM::PointPtr point = o->pose->point;\n\t\t\t\tstd::stringstream ss;\n                ss << \"Invis: \" <<  o->getType() << \" With X:\" << point->eigen.x() << \"Y:\" << point->eigen.y() << \"Z:\" << point->eigen.z();\n\t\t\t\tvisualization_msgs::Marker s = VizHelperRVIZ::createSphereMarker(point, baseFrame, ss.str(),\n\t\t\t\t\t\tboost::lexical_cast<int32_t>(o->getId()), sphereRadius, regularObjectColor, markerLifetime);\n\t\t\t\ts.color.g = 0.0f;\n\t\t\t\ts.color.b = 1.0f;\n\t\t\t\toBs.markers.push_back(s);\n                //TODO: look for better solution than hard-code binSize; Problem introduced because of deletion of calcBinNum in VotingSpace\n                int x = vs.discretizeToBins(point->eigen.x(), 0.1);\n                int y = vs.discretizeToBins(point->eigen.y(), 0.1);\n                int z = vs.discretizeToBins(point->eigen.z(), 0.1);\n\t\t\t    std::tuple<int,int,int> t = std::make_tuple(x, y, z);\n\t\t\t    if(binDrawn[t] == false)\n\t\t\t    {\n\t\t\t\t    std::stringstream ss;\n\t\t\t\t    ss << \"\\nObject\" << o->getId() << \"Is in Bin: \"<< \"X:\" << x << \" Y:\" << y << \" Z:\" << z;\n\t\t\t\t    bins.markers.push_back(VizHelperRVIZ::getBinMarker(x,y,z,bin_size,ss.str(), 0, baseFrame,\n\t\t\t\t\t\t    regularBinColor));\n\t\t\t\t    binDrawn[t] = true;\n\t\t\t    }\n\t\t\t}\n\t\t\tint id = 0;\n\t\t\tfor(ISM::ObjectPtr& o : rg.getOldObjects())\n\t\t\t{\n\t\t\t\tif(!o)\n\t\t\t\t\tcontinue;\n                ISM::PointPtr point = o->pose->point;\n\t\t\t\tstd::stringstream ss;\n                //ss << \"Old \" << o->getType() << \" With X:\" << point->eigen.x() << \"Y:\" << point->eigen.y() << \"Z:\" << point->eigen.z();\n\t\t\t\tss << \"Old \" << o->getType();\n\t\t\t\t//visualization_msgs::Marker m = objectToSphere(o, baseFrame, ss.str(), boost::lexical_cast<int32_t>(o->getId()));\n\t\t\t\tvisualization_msgs::Marker m = VizHelperRVIZ::createSphereMarker(point, baseFrame, ss.str(),\n\t\t\t\t\t\tboost::lexical_cast<int32_t>(id++), sphereRadius, regularObjectColor, markerLifetime);\n\t\t\t\tm.color.r = 1.0f;\n\t\t\t\toBs.markers.push_back(m);\n                //TODO: look for better solution than hard-code binSize; Problem introduced because of deletion of calcBinNum in VotingSpace\n                int x = vs.discretizeToBins(point->eigen.x(), 0.1);\n                int y = vs.discretizeToBins(point->eigen.y(), 0.1);\n                int z = vs.discretizeToBins(point->eigen.z(), 0.1);\n\t\t\t    std::tuple<int,int,int> t = std::make_tuple(x, y, z);\n\t\t\t    if(binDrawn[t] == false)\n\t\t\t    {\n\t\t\t\t    std::stringstream ss;\n\t\t\t\t    ss << \"\\nObject\" << o->getId() << \"Is in Bin: \"<< \"X:\" << x << \" Y:\" << y << \" Z:\" << z;\n\t\t\t\t    bins.markers.push_back(VizHelperRVIZ::getBinMarker(x,y,z,bin_size,ss.str(),0,baseFrame,\n\t\t\t\t\t\t    regularBinColor));\n\t\t\t\t    binDrawn[t] = true;\n\t\t\t    }\n\t\t\t}\n        } else\n        {\n\t\t\tint objectMarkerId = 0;\n\t\t\tint binMarkerId = 0;\n\n\t\t\tfor(ISM::ObjectPtr& o : rg.getObjects(rg.mShowFrom, rg.mShowTo))\n\t\t\t{\n\t\t\t\tif(!rg.mDoPublish)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(!o)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n                ISM::PointPtr point = o->pose->point;\n\t\t\t\tstd::stringstream ss;\n                //ss << o->getType() << \" With X:\" << point->eigen.x() << \"Y:\" << point->eigen.y() << \"Z:\" << point->eigen.z();\n\t\t\t\tss << o->getType() << \" \" << o->getId();\n\t\t\t\tauto sphereWithOrient = VIZ::VizHelperRVIZ::createSphereMarkerWithOrientation(\n                        o->pose, baseFrame, ss.str(), objectMarkerId + 1, sphereRadius,\n\t\t\t\t\t\tgetColor(o->getType(), o->getId()), markerLifetime, objectMarkerId + 2);\n\t\t\t\tobjectMarkerId += 4;\n\t\t\t\toBs.markers.insert(oBs.markers.end(), sphereWithOrient.markers.begin(),\n\t\t\t\t\t\tsphereWithOrient.markers.end());\n                //TODO: look for better solution than hard-code binSize; Problem introduced because of deletion of calcBinNum in VotingSpace\n                int x = vs.discretizeToBins(point->eigen.x(), 0.1);\n                int y = vs.discretizeToBins(point->eigen.y(), 0.1);\n                int z = vs.discretizeToBins(point->eigen.z(), 0.1);\n\t\t\t    std::tuple<int,int,int> t = std::make_tuple(x, y, z);\n\t\t\t    if(binDrawn[t] == false)\n\t\t\t    {\n\t\t\t\t    std::stringstream ss;\n\t\t\t\t    //ss << \"\\nObject\" << o->getId() << \"Is in Bin: \"<< \"X:\" << x << \" Y:\" << y << \" Z:\" << z;\n\t\t\t\t    if(detailedBinNS)\n\t\t\t\t    {\n                        ss << \"Bin: \"<< \"X:\" << x << \" Y:\" << y << \" Z:\" << z;\n\t\t\t\t    } else\n\t\t\t\t    {\n                        ss << \"Bins\";\n\t\t\t\t    }\n\t\t\t\t    bins.markers.push_back(VIZ::VizHelperRVIZ::getBinMarker(x, y, z, bucketSize, ss.str(),\n\t\t\t\t    \t\tbinMarkerId++, baseFrame, regularBinColor));\n\t\t\t\t    binDrawn[t] = true;\n\t\t\t    }\n\t\t\t}\n\n        }\n        visPub.publish(oBs);\n        visPub.publish(bins);*/\n\n        r.sleep();\n    }\n\n}\n", "meta": {"hexsha": "6e610341f02f26ea1b1b6b1cf26e43159fa7d17d", "size": 44990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/recordGen.cpp", "max_stars_repo_name": "Tobi2001/asr_ism", "max_stars_repo_head_hexsha": "a2e6afcad22133ce42bfff810186069c3d5a487c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T13:37:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-29T13:37:24.000Z", "max_issues_repo_path": "src/recordGen.cpp", "max_issues_repo_name": "Tobi2001/asr_ism", "max_issues_repo_head_hexsha": "a2e6afcad22133ce42bfff810186069c3d5a487c", "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/recordGen.cpp", "max_forks_repo_name": "Tobi2001/asr_ism", "max_forks_repo_head_hexsha": "a2e6afcad22133ce42bfff810186069c3d5a487c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-03T13:55:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-03T13:55:48.000Z", "avg_line_length": 34.0833333333, "max_line_length": 755, "alphanum_fraction": 0.5903311847, "num_tokens": 12258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1894504808742802}}
{"text": "/**************************************************************************\\\n|\n|    Copyright (C) 2009 Marc Stevens\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 <stdexcept>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n\n#include <boost/program_options.hpp>\n\n#include \"main.hpp\"\n\n#include <hashclash/md5detail.hpp>\n#include <hashclash/timer.hpp>\n\nusing namespace hashclash;\nusing namespace std;\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nstd::string workdir;\n\nint main(int argc, char** argv) \n{\n\tint result = 0;\n\ttimer runtime(true);\n\n\tcout <<\n\t\t\"Birthday search for MD5 chosen-prefix collisions\\n\"\n\t\t\"Copyright (C) 2009 Marc Stevens\\n\"\n\t\t\"http://homepages.cwi.nl/~stevens/\\n\"\n\t\t<< endl;\n\n\ttry {\n\t\tbirthday_parameters parameters;\n\n\t\t// Define program options\n\t\tpo::options_description \n\t\t\tdesc(\"Allowed options\"), \t\t\t\n\t\t\tall(\"Allowed options\");\n\n\t\tdesc.add_options()\n\t\t\t(\"help,h\", \"Show options.\")\n\t\t\t(\"mod,m\"\n\t\t\t\t, po::value<unsigned>(&parameters.modn)->default_value(1)\n\t\t\t\t, \"Do only 1/m of all work.\")\n\n\t\t\t(\"index,i\"\n\t\t\t\t, po::value<unsigned>(&parameters.modi)->default_value(0)\n\t\t\t\t, \"Do i-th part of all work (i=0,...,m-1).\")\n\n\t\t\t(\"workdir,w\"\n\t\t\t\t, po::value<string>(&workdir)->default_value(\"./data\")\n\t\t\t\t, \"Set working directory.\")\n\n\t\t\t(\"inputfile1\"\n\t\t\t\t, po::value<string>(&parameters.inputfile1)\n\t\t\t\t, \"Use specified inputfile as first message.\")\n\n\t\t\t(\"inputfile2\"\n\t\t\t\t, po::value<string>(&parameters.inputfile2)\n\t\t\t\t, \"Use specified inputfile as second message.\")\n\n\t\t\t(\"outputfile1\"\n\t\t\t\t, po::value<string>(&parameters.outputfile1)->default_value(\"file1.bin\")\n\t\t\t\t, \"Use specified outputfile for first message.\")\n\n\t\t\t(\"outputfile2\"\n\t\t\t\t, po::value<string>(&parameters.outputfile2)->default_value(\"file2.bin\")\n\t\t\t\t, \"Use specified outputfile for second message.\")\n\n\t\t\t(\"distribution\"\n\t\t\t\t, po::bool_switch(&parameters.distribution)\n\t\t\t\t, \"Show workdistribution.\\nDepends on hybridbits and pathtyperange.\")\n\n\t\t\t(\"hybridbits\"\n\t\t\t\t, po::value<unsigned>(&parameters.hybridbits)->default_value(0)\n\t\t\t\t, \"Set 0 for 64-bit, 32 for 96-bit birthdaying.\")\n\n\t\t\t(\"pathtyperange\"\n\t\t\t\t, po::value<unsigned>(&parameters.pathtyperange)->default_value(2)\n\t\t\t\t, \"Increases potential # diffs eliminated per n.c.\")\n\n\t\t\t(\"maxblocks\"\n\t\t\t\t, po::value<unsigned>(&parameters.maxblocks)->default_value(9)\n\t\t\t\t, \"Upperbound on the amount of near-collisions.\")\n\n\t\t\t(\"logtraillength\"\n\t\t\t\t, po::value<int>(&parameters.logpathlength)->default_value(-1)\n\t\t\t\t, \"Specify avg. trail length in bits.\")\n\n\t\t\t(\"maxmemory\"\n\t\t\t\t, po::value<unsigned>(&parameters.maxmemory)->default_value(100)\n\t\t\t\t, \"Max. memory in MB used for storing trails.\")\n\n\t\t\t(\"memhardlimit\"\n\t\t\t\t, po::bool_switch(&parameters.memhardlimit)\n\t\t\t\t, \"Hard limit max. memory instead of average.\")\n\t\t\t(\"threads\"\n\t\t\t\t, po::value<unsigned>(&parameters.threads)->default_value(0)\n\t\t\t\t, \"Number of computing threads to start.\")\n\t\t\t;\n\n#ifdef HAVE_CUDA\n\t\tdesc.add_options()\n\t\t\t(\"cuda_dev_query\", \"Query CUDA devices\")\n\t\t\t(\"cuda_enable\", po::bool_switch(&parameters.cuda_enabled), \"Enable CUDA\")\n\t\t\t;\n#else\n\t\tall.add_options()\t\t\t\n\t\t\t(\"cuda_dev_query\", \"Query CUDA devices\")\n\t\t\t(\"cuda_enable\", po::bool_switch(&parameters.cuda_enabled), \"Enable CUDA\")\n\t\t\t;\n#endif\n\n\t\tall.add(desc);\n\t\n\t\t// Parse program options\n\t\tpo::variables_map vm;\n\t\tpo::store(po::parse_command_line(argc, argv, all), vm);\n\t\t{\n\t\t\tstd::ifstream ifs(\"md5birthdaysearch.cfg\");\n\t\t\tif (ifs) po::store(po::parse_config_file(ifs, all), vm);\n\t\t}\n\t\tpo::notify(vm);\n\n\t\t// Process program options\n\t\tif (vm.count(\"help\")) {\n\t\t\tcout << desc << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tif (parameters.distribution) {\n\t\t\tdetermine_nrblocks_distribution(parameters);\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (parameters.modi >= parameters.modn) {\n\t\t\tcerr << \"Error: i must be strictly less than m!\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (parameters.modn != 1)\n\t\t\tcout << \"System \" << parameters.modi << \" of \" << parameters.modn << endl;\n\t\tif (parameters.inputfile1.size() == 0)\n\t\t{\n\t\t\tcerr << \"Error: inputfile1 must be given!\" << endl;\n\t\t\treturn 2;\n\t\t}\n\t\tif (parameters.inputfile2.size() == 0)\n\t\t{\n\t\t\tcerr << \"Error: inputfile2 must be given!\" << endl;\n\t\t\treturn 2;\n\t\t}\n\t\tif (parameters.logpathlength < 0 && parameters.maxmemory == 0)\n\t\t{\n\t\t\tcerr << \"Cannot determine logtraillength when maxmemory is unspecified!\" << endl;\n\t\t\treturn 3;\n\t\t}\n\t\tif (parameters.modi == 0)\n\t\t{\n\t\t\tif (parameters.outputfile1.size() == 0)\n\t\t\t{\n\t\t\t\tcerr << \"Error: outputfile1 must be given!\" << endl;\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\tif (parameters.outputfile2.size() == 0)\n\t\t\t{\n\t\t\t\tcerr << \"Error: outputfile2 must be given!\" << endl;\n\t\t\t\treturn 2;\n\t\t\t}\t\t\t\n\t\t}\n#ifdef HAVE_CUDA\n\t\tif (vm.count(\"cuda_dev_query\")) {\n\t\t\tcuda_device_query();\n\t\t\treturn 0;\n\t\t}\n#endif // CUDA\n\t\tresult = dostep(parameters);\n\t} catch (exception& e) {\n\t\tcout << \"Runtime: \" << runtime.time() << endl;\n\t\tcerr << \"Caught exception!!:\" << endl << e.what() << endl;\n\t\tthrow;\n\t} catch (...) {\n\t\tcout << \"Runtime: \" << runtime.time() << endl;\n\t\tcerr << \"Unknown exception caught!!\" << endl;\n\t\tthrow;\n\t}\n\tcout << \"Runtime: \" << runtime.time() << endl;\n\treturn result;\n}\n", "meta": {"hexsha": "ce98e3c280b054955485b4646f27ff18c129d579", "size": 5817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/md5birthdaysearch/main.cpp", "max_stars_repo_name": "killua4564/hashclash", "max_stars_repo_head_hexsha": "f780f17ef579e4bb246f5c47f31765f665dab74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 398.0, "max_stars_repo_stars_event_min_datetime": "2017-10-16T19:46:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T23:45:05.000Z", "max_issues_repo_path": "src/md5birthdaysearch/main.cpp", "max_issues_repo_name": "killua4564/hashclash", "max_issues_repo_head_hexsha": "f780f17ef579e4bb246f5c47f31765f665dab74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T08:14:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T09:33:44.000Z", "max_forks_repo_path": "src/md5birthdaysearch/main.cpp", "max_forks_repo_name": "killua4564/hashclash", "max_forks_repo_head_hexsha": "f780f17ef579e4bb246f5c47f31765f665dab74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 72.0, "max_forks_repo_forks_event_min_datetime": "2017-10-18T14:44:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T18:07:19.000Z", "avg_line_length": 28.1014492754, "max_line_length": 84, "alphanum_fraction": 0.6389891697, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111865, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.18945047536052126}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"EnumAsFlagsMacro.h\"\n\nenum class TestFlags : uint64_t {\n    none = 0,\n    flag0 = 1 << 0,\n    flag1 = 1 << 1,\n    flag2 = 1 << 2,\n    flag3 = 1 << 3,\n    flag4 = 1 << 4,\n    flag5 = 1 << 5,\n    flag6 = 1 << 6,\n    flag7 = 1 << 7,\n    flag8 = 1 << 8,\n    flag9 = 1 << 9,\n    flag10 = 1 << 10\n};\nMAKE_ENUM_SUPPORT_FLAG_OPERATORS(TestFlags);\nMAKE_ENUM_SUPPORT_OSTREAM_OPERATOR(TestFlags);\n\nBOOST_AUTO_TEST_CASE(EnumAsFlagsMacroTestCase)\n{\n    BOOST_REQUIRE_EQUAL(sizeof(std::underlying_type<TestFlags>::type), 8);\n        \n    TestFlags f = TestFlags::none;\n    BOOST_REQUIRE_EQUAL(f, TestFlags::none);\n    BOOST_REQUIRE_NE(f, TestFlags::flag0);\n    BOOST_REQUIRE_EQUAL(f | TestFlags::flag0, TestFlags::flag0);\n    f |= TestFlags::flag10;\n    BOOST_REQUIRE_NE(f, TestFlags::none);\n    BOOST_REQUIRE_EQUAL(f, TestFlags::flag10);\n    BOOST_REQUIRE_EQUAL(f | TestFlags::flag0, TestFlags::flag10 | TestFlags::flag0);\n    f |= TestFlags::flag0;\n    f |= TestFlags::flag1;\n    f |= TestFlags::flag2;\n    BOOST_REQUIRE_EQUAL(f, TestFlags::flag0 | TestFlags::flag1 | TestFlags::flag2 | TestFlags::flag10);\n    f &= TestFlags::flag1 | TestFlags::flag2 | TestFlags::flag3;\n    BOOST_REQUIRE_EQUAL(f, TestFlags::flag1 | TestFlags::flag2);\n    f = f | TestFlags::flag0;\n    f = f | TestFlags::flag10;\n    BOOST_REQUIRE_EQUAL(f, TestFlags::flag0 | TestFlags::flag1 | TestFlags::flag2 | TestFlags::flag10);\n    f &= ~TestFlags::flag10;\n    BOOST_REQUIRE_EQUAL(f, TestFlags::flag0 | TestFlags::flag1 | TestFlags::flag2);\n    f ^= TestFlags::flag10;\n    BOOST_REQUIRE_EQUAL(f, TestFlags::flag0 | TestFlags::flag1 | TestFlags::flag2 | TestFlags::flag10);\n    f ^= TestFlags::flag10;\n    BOOST_REQUIRE_EQUAL(f, TestFlags::flag0 | TestFlags::flag1 | TestFlags::flag2);\n    BOOST_REQUIRE_EQUAL(TestFlags::flag0 & TestFlags::flag0, TestFlags::flag0);\n    BOOST_REQUIRE_EQUAL(TestFlags::flag0 & TestFlags::flag1, TestFlags::none);\n    BOOST_REQUIRE_EQUAL(TestFlags::flag0 ^ TestFlags::flag0, TestFlags::none);\n    BOOST_REQUIRE_EQUAL(TestFlags::flag0 ^ TestFlags::flag0 ^ TestFlags::flag0, TestFlags::flag0);\n    BOOST_REQUIRE_EQUAL(TestFlags::flag0 ^ TestFlags::flag1, TestFlags::flag0 | TestFlags::flag1);\n}\n\n", "meta": {"hexsha": "489d3a1d70c124af34f9fcbab504117711c80a2a", "size": 2231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/util/test/TestEnumAsFlagsMacro.cpp", "max_stars_repo_name": "ewb4/HDTN", "max_stars_repo_head_hexsha": "a0e577351bd28c3aeb7e656e03a2d93cf84712a0", "max_stars_repo_licenses": ["NASA-1.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": "common/util/test/TestEnumAsFlagsMacro.cpp", "max_issues_repo_name": "ewb4/HDTN", "max_issues_repo_head_hexsha": "a0e577351bd28c3aeb7e656e03a2d93cf84712a0", "max_issues_repo_licenses": ["NASA-1.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": "common/util/test/TestEnumAsFlagsMacro.cpp", "max_forks_repo_name": "ewb4/HDTN", "max_forks_repo_head_hexsha": "a0e577351bd28c3aeb7e656e03a2d93cf84712a0", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5636363636, "max_line_length": 103, "alphanum_fraction": 0.6853428956, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.1893974035694824}}
{"text": "/*\n The MIT License (MIT)\n\n Copyright (c) [2016] [BTC.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,\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#include \"CommonGrin.h\"\n\n#include \"cuckoo/cuckaroo.h\"\n#include \"cuckoo/cuckarood.h\"\n#include \"cuckoo/cuckaroom.h\"\n#include \"cuckoo/cuckatoo.h\"\n#include \"cuckoo/siphash.h\"\n#include \"libblake2/blake2.h\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <limits>\n#include <Utils.h>\n\nstatic const uint8_t BASE_EDGE_BITS = 24;\nstatic const uint8_t DEFAULT_MIN_EDGE_BITS = 31;\nstatic const uint8_t SECOND_POW_EDGE_BITS = 29;\n\nstatic const uint64_t MAX_DIFFICUTY = std::numeric_limits<uint64_t>::max();\n\nstatic const uint64_t BLOCK_TIME_SEC = 60;\nstatic const uint64_t HOUR_HEIGHT = 3600 / BLOCK_TIME_SEC;\nstatic const uint64_t DAY_HEIGHT = 24 * HOUR_HEIGHT;\nstatic const uint64_t WEEK_HEIGHT = 7 * DAY_HEIGHT;\nstatic const uint64_t YEAR_HEIGHT = 52 * WEEK_HEIGHT;\n\nstatic const uint64_t GRIN_BASE = 1000000000;\nstatic const uint64_t REWARD = BLOCK_TIME_SEC * GRIN_BASE;\n\nstatic uint64_t\nPowDifficultyGrinScaled(uint64_t hash, uint32_t secondaryScaling) {\n  boost::multiprecision::uint128_t x = secondaryScaling;\n  x <<= 64;\n  x /= hash;\n  return x > MAX_DIFFICUTY ? MAX_DIFFICUTY : static_cast<uint64_t>(x);\n}\n\n// verify that edges are ascending and form a cycle in header-generated graph\nbool VerifyPowGrinPrimary(\n    const std::vector<uint64_t> &edges, siphash_keys &keys, uint32_t edgeBits) {\n  return verify_cuckatoo(edges, keys, edgeBits);\n}\n\n// verify that edges are ascending and form a cycle in header-generated graph\nbool VerifyPowGrinSecondary(\n    const std::vector<uint64_t> &edges,\n    siphash_keys &keys,\n    uint32_t edgeBits,\n    uint16_t version) {\n  switch (version) {\n  case 3:\n    return verify_cuckaroom(edges, keys, edgeBits);\n  case 2:\n    return verify_cuckarood(edges, keys, edgeBits);\n  default:\n    return verify_cuckaroo(edges, keys, edgeBits);\n  }\n}\n\nbool VerifyPowGrin(\n    const PreProofGrin &preProof,\n    uint32_t edgeBits,\n    const std::vector<uint64_t> &proofs) {\n  if (edgeBits != SECOND_POW_EDGE_BITS && edgeBits < DEFAULT_MIN_EDGE_BITS)\n    return false;\n\n  siphash_keys siphashKeys;\n  char preProofKeys[32];\n  blake2b(\n      preProofKeys, sizeof(preProofKeys), &preProof, sizeof(preProof), 0, 0);\n  siphashKeys.setkeys(preProofKeys);\n  return edgeBits == SECOND_POW_EDGE_BITS\n      ? VerifyPowGrinSecondary(\n            proofs, siphashKeys, edgeBits, preProof.prePow.version.value())\n      : VerifyPowGrinPrimary(proofs, siphashKeys, edgeBits);\n}\n\nuint256 PowHashGrin(uint32_t edgeBits, const std::vector<uint64_t> &proofs) {\n  // Compress the proofs to a bit vector\n  std::vector<uint8_t> proofBits((proofs.size() * edgeBits + 7) / 8, 0);\n  uint64_t edgeMask = (static_cast<uint64_t>(1) << edgeBits) - 1;\n  size_t i = 0;\n  for (uint64_t proof : proofs) {\n    proof &= edgeMask;\n    for (uint32_t j = 0; j < edgeBits; ++j) {\n      if (0x1 & (proof >> j)) {\n        uint32_t position = i * edgeBits + j;\n        proofBits[position / 8] |= (1 << (position % 8));\n      }\n    }\n    ++i;\n  }\n\n  // Generate the blake2b hash\n  uint256 hash;\n  blake2b(hash.begin(), sizeof(hash), proofBits.data(), proofBits.size(), 0, 0);\n  return hash;\n}\n\nuint32_t GraphWeightGrin(uint64_t height, uint32_t edgeBits) {\n  uint64_t xprEdgeBits = edgeBits;\n\n  auto bitsOverMin =\n      edgeBits <= DEFAULT_MIN_EDGE_BITS ? 0 : edgeBits - DEFAULT_MIN_EDGE_BITS;\n  auto expiryHeight = (1 << bitsOverMin) * YEAR_HEIGHT;\n  if (edgeBits < 32 && height >= expiryHeight) {\n    auto weeks = 1 + (height - expiryHeight) / WEEK_HEIGHT;\n    xprEdgeBits = xprEdgeBits > weeks ? xprEdgeBits - weeks : 0;\n  }\n\n  return ((2 << (edgeBits - BASE_EDGE_BITS)) * xprEdgeBits);\n}\n\nuint32_t\nPowScalingGrin(uint64_t height, uint32_t edgeBits, uint32_t secondaryScaling) {\n  return edgeBits == SECOND_POW_EDGE_BITS ? secondaryScaling\n                                          : GraphWeightGrin(height, edgeBits);\n}\n\nuint64_t PowDifficultyGrin(\n    uint64_t height,\n    uint32_t edgeBits,\n    uint32_t secondaryScaling,\n    const std::vector<uint64_t> &proofs) {\n  // Compress the proofs to a bit vector\n  std::vector<uint8_t> proofBits((proofs.size() * edgeBits + 7) / 8, 0);\n  uint64_t edgeMask = (static_cast<uint64_t>(1) << edgeBits) - 1;\n  size_t i = 0;\n  for (uint64_t proof : proofs) {\n    proof &= edgeMask;\n    for (uint32_t j = 0; j < edgeBits; ++j) {\n      if (0x1 & (proof >> j)) {\n        uint32_t position = i * edgeBits + j;\n        proofBits[position / 8] |= (1 << (position % 8));\n      }\n    }\n    ++i;\n  }\n\n  // Generate the blake2b hash\n  boost::endian::big_uint64_buf_t hash[4];\n  blake2b(hash, sizeof(hash), proofBits.data(), proofBits.size(), 0, 0);\n\n  // Scale the difficulty\n  return PowDifficultyGrinScaled(\n      hash[0].value(), PowScalingGrin(height, edgeBits, secondaryScaling));\n}\n\nuint64_t GetBlockRewardGrin(uint64_t height) {\n  return REWARD;\n}", "meta": {"hexsha": "1da274dff69789834dc0d773bd2b2bf74920fbd2", "size": 5868, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/grin/CommonGrin.cc", "max_stars_repo_name": "jheleniak/btcpool", "max_stars_repo_head_hexsha": "28ad61f60d529c203db2b58379d851ba20697eae", "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/grin/CommonGrin.cc", "max_issues_repo_name": "jheleniak/btcpool", "max_issues_repo_head_hexsha": "28ad61f60d529c203db2b58379d851ba20697eae", "max_issues_repo_licenses": ["MIT"], "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/grin/CommonGrin.cc", "max_forks_repo_name": "jheleniak/btcpool", "max_forks_repo_head_hexsha": "28ad61f60d529c203db2b58379d851ba20697eae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-25T13:53:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T13:53:33.000Z", "avg_line_length": 33.724137931, "max_line_length": 80, "alphanum_fraction": 0.7128493524, "num_tokens": 1639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.18939740225634105}}
{"text": "#include \"config.h\"\n\n#include <boost/container/flat_map.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"filelib.h\"\n#include \"stringlib.h\"\n#include \"weights.h\"\n#include \"sparse_vector.h\"\n#include \"candidate_set.h\"\n#include \"sentence_metadata.h\"\n#include \"ns.h\"\n#include \"ns_docscorer.h\"\n#include \"verbose.h\"\n#include \"hg.h\"\n#include \"ff_register.h\"\n#include \"decoder.h\"\n#include \"fdict.h\"\n#include \"sampler.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nboost::shared_ptr<MT19937> rng;\nvector<training::CandidateSet> kbests;\nSparseVector<weight_t> G, u, lambdas;\ndouble pseudo_doc_decay = 0.9;\n\nbool InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n    (\"decoder_config,c\",po::value<string>(),\"[REQ] Decoder configuration file\")\n    (\"devset,d\",po::value<string>(),\"[REQ] Source/reference development set\")\n    (\"weights,w\",po::value<string>(),\"Initial feature weights file\")\n    (\"mt_metric,m\",po::value<string>()->default_value(\"ibm_bleu\"), \"Scoring metric (ibm_bleu, nist_bleu, koehn_bleu, ter, combi)\")\n    (\"size\",po::value<unsigned>()->default_value(0), \"Process rank (for multiprocess mode)\")\n    (\"rank\",po::value<unsigned>()->default_value(1), \"Number of processes (for multiprocess mode)\")\n    (\"optimizer,o\",po::value<unsigned>()->default_value(1), \"Optimizer (Adaptive MIRA=1)\")\n    (\"fear,f\",po::value<unsigned>()->default_value(1), \"Fear selection (model-cost=1, maxcost=2, maxscore=3)\")\n    (\"hope,h\",po::value<unsigned>()->default_value(1), \"Hope selection (model+cost=1, mincost=2)\")\n    (\"eta0\", po::value<double>()->default_value(0.1), \"Initial step size\")\n    (\"random_seed,S\", po::value<uint32_t>(), \"Random seed (if not specified, /dev/random will be used)\")\n    (\"mt_metric_scale,s\", po::value<double>()->default_value(1.0), \"Scale MT loss function by this amount\")\n    (\"pseudo_doc,e\", \"Use pseudo-documents for approximate scoring\")\n    (\"k_best_size,k\", po::value<unsigned>()->default_value(500), \"Size of hypothesis list to search for oracles\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n    (\"config\", po::value<string>(), \"Configuration file\")\n    (\"help,H\", \"Print this help message and exit\");\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(opts).add(clo);\n  \n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"config\")) {\n    ifstream config((*conf)[\"config\"].as<string>().c_str());\n    po::store(po::parse_config_file(config, dconfig_options), *conf);\n  }\n  po::notify(*conf);\n\n  if (conf->count(\"help\")\n          || !conf->count(\"decoder_config\")\n          || !conf->count(\"devset\")) {\n    cerr << dcmdline_options << endl;\n    return false;\n  }\n  return true;\n}\n\nstruct TrainingObserver : public DecoderObserver {\n  explicit TrainingObserver(const EvaluationMetric& m, const int k) : metric(m), kbest_size(k), cur_eval() {}\n\n  const EvaluationMetric& metric;\n  const int kbest_size;\n  const SegmentEvaluator* cur_eval;\n  SufficientStats pdoc;\n  unsigned hi, vi, fi;  // hope, viterbi, fear\n\n  void SetSegmentEvaluator(const SegmentEvaluator* eval) {\n    cur_eval = eval;\n  }\n\n  virtual void NotifySourceParseFailure(const SentenceMetadata& smeta) {\n    cerr << \"Failed to translate sentence with ID = \" << smeta.GetSentenceID() << endl;\n    abort();\n  }\n\n  unsigned CostAugmentedDecode(const training::CandidateSet& cs,\n                               const SparseVector<double>& w,\n                               double alpha = 0) {\n    unsigned best_i = 0;\n    double best = -numeric_limits<double>::infinity();\n    for (unsigned i = 0; i < cs.size(); ++i) {\n      double s = cs[i].fmap.dot(w);\n      if (alpha)\n        s += alpha * metric.ComputeScore(cs[i].eval_feats + pdoc);\n      if (s > best) {\n        best = s;\n        best_i = i;\n      }\n    }\n    return best_i;\n  }\n\n  virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) {\n    pdoc *= pseudo_doc_decay;\n    const unsigned sent_id = smeta.GetSentenceID();\n    kbests[sent_id].AddUniqueKBestCandidates(*hg, kbest_size, cur_eval);\n    vi = CostAugmentedDecode(kbests[sent_id], lambdas);\n    hi = CostAugmentedDecode(kbests[sent_id], lambdas, 1.0);\n    fi = CostAugmentedDecode(kbests[sent_id], lambdas, -1.0);\n    cerr << sent_id << \" ||| \" << TD::GetString(kbests[sent_id][vi].ewords) << \" ||| \" << metric.ComputeScore(kbests[sent_id][vi].eval_feats + pdoc) << endl;\n    pdoc += kbests[sent_id][vi].eval_feats;  // update pseudodoc stats\n  }\n};\n\nint main(int argc, char** argv) {\n  SetSilent(true);  // turn off verbose decoder output\n  register_feature_functions();\n\n  po::variables_map conf;\n  if (!InitCommandLine(argc, argv, &conf)) return 1;\n\n  if (conf.count(\"random_seed\"))\n    rng.reset(new MT19937(conf[\"random_seed\"].as<uint32_t>()));\n  else\n    rng.reset(new MT19937);\n  \n  string metric_name = UppercaseString(conf[\"mt_metric\"].as<string>());\n  if (metric_name == \"COMBI\") {\n    cerr << \"WARNING: 'combi' metric is no longer supported, switching to 'COMB:TER=-0.5;IBM_BLEU=0.5'\\n\";\n    metric_name = \"COMB:TER=-0.5;IBM_BLEU=0.5\";\n  } else if (metric_name == \"BLEU\") {\n    cerr << \"WARNING: 'BLEU' is ambiguous, assuming 'IBM_BLEU'\\n\";\n    metric_name = \"IBM_BLEU\";\n  }\n  EvaluationMetric* metric = EvaluationMetric::Instance(metric_name);\n  DocumentScorer ds(metric, conf[\"devset\"].as<string>());\n  cerr << \"Loaded \" << ds.size() << \" references for scoring with \" << metric_name << endl;\n  kbests.resize(ds.size());\n  double eta = 0.001;\n\n  ReadFile ini_rf(conf[\"decoder_config\"].as<string>());\n  Decoder decoder(ini_rf.stream());\n\n  vector<weight_t>& dense_weights = decoder.CurrentWeightVector();\n  if (conf.count(\"weights\")) {\n    Weights::InitFromFile(conf[\"weights\"].as<string>(), &dense_weights);\n    Weights::InitSparseVector(dense_weights, &lambdas);\n  }\n\n  TrainingObserver observer(*metric, conf[\"k_best_size\"].as<unsigned>());\n\n  unsigned num = 200;\n  for (unsigned iter = 1; iter < num; ++iter) {\n    lambdas.init_vector(&dense_weights);\n    unsigned sent_id = rng->next() * ds.size();\n    cerr << \"Learning from sentence id: \" << sent_id << endl;\n    observer.SetSegmentEvaluator(ds[sent_id]);\n    decoder.SetId(sent_id);\n    decoder.Decode(ds[sent_id]->src, &observer);\n    if (observer.vi != observer.hi) {  // viterbi != hope\n      SparseVector<double> grad = kbests[sent_id][observer.fi].fmap;\n      grad -= kbests[sent_id][observer.hi].fmap;\n      cerr << \"GRAD: \" << grad << endl;\n      const SparseVector<double>& g = grad;\n#if HAVE_CXX11 && (__GNUC_MINOR__ > 4 || __GNUC__ > 4)\n      for (auto& gi : g) {\n#else\n      for (SparseVector<double>::const_iterator it = g.begin(); it != g.end(); ++it) {\n        const pair<unsigned,double>& gi = *it;\n#endif\n        if (gi.second) {\n          u[gi.first] += gi.second;\n          G[gi.first] += gi.second * gi.second;\n          lambdas.set_value(gi.first, 1.0);  // this is a dummy value to trigger recomputation\n        }\n      }\n      for (SparseVector<double>::iterator it = lambdas.begin(); it != lambdas.end(); ++it) {\n        const pair<unsigned,double>& xi = *it;\n        double z = fabs(u[xi.first] / iter) - 0.0;\n        double s = 1;\n        if (u[xi.first] > 0) s = -1;\n        if (z > 0 && G[xi.first]) {\n          lambdas.set_value(xi.first, eta * s * z * iter / sqrt(G[xi.first]));\n        } else {\n          lambdas.set_value(xi.first, 0.0);\n        }\n      }\n    }\n  }\n  cerr << \"Optimization complete.\\n\";\n  Weights::WriteToFile(\"-\", dense_weights, true);\n  return 0;\n}\n\n", "meta": {"hexsha": "18ddbf8f18c1fd2e1232b40e88aba9fd1b37f1a5", "size": 7728, "ext": "cc", "lang": "C++", "max_stars_repo_path": "training/mira/ada_opt_sm.cc", "max_stars_repo_name": "wilkeraziz/cdec", "max_stars_repo_head_hexsha": "ecb852fb890aeb805686c852904186bba7bb6fd6", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "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": "training/mira/ada_opt_sm.cc", "max_issues_repo_name": "wilkeraziz/cdec", "max_issues_repo_head_hexsha": "ecb852fb890aeb805686c852904186bba7bb6fd6", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "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": "training/mira/ada_opt_sm.cc", "max_forks_repo_name": "wilkeraziz/cdec", "max_forks_repo_head_hexsha": "ecb852fb890aeb805686c852904186bba7bb6fd6", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "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.8341708543, "max_line_length": 157, "alphanum_fraction": 0.6539855072, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18939739985305637}}
{"text": "\n\n#include <functional>\n#include <utility>\n#include <list>\n\nusing std::list;\nusing std::pair;\n\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/normal.hpp>\n\n#include \"eigenIncluder.hpp\"\n#include \"algebraTrace.hpp\"\n#include \"streamTrace.hpp\"\n#include \"mongoWrite.hpp\"\n#include \"instrument.hpp\"\n#include \"acsConfig.hpp\"\n#include \"algebra.hpp\"\n#include \"common.hpp\"\n#include \"mongo.hpp\"\n\n// #pragma GCC optimize (\"O0\")\n\n/** \\file\n* This software uses specialised kalman filter classes to perform filtering.\n* Using a classes such as KFState, KFMeas, etc, prevents duplication of code, and ensures that many edge cases are taken care of\n* without the need for the developer to consider them explicitly.\n*\n* The basic workflow for using the filter is:\n* create filter object,\n* initialise the state transition matrix at the beginning of each epoch\n* create a list of measurements (only adding entries for required states, using KFKeys to reference the state element)\n* combining measurements that were in a list into a single matrix corresponding to the new state,\n* and filtering - filtering internally saves the states for RTS code, using a single sequential file that has some headers added so that it can be traversed backwards\n*\n* The filter has some pre/post fit checks that remove measurements that are out of expected ranges,\n* and there are functions provided for setting, resetting, and getting values, noises, and covariance values.\n*\n* KFKeys are used to identify states. They may have a type, SatStat value, string, and number associated with them, and can be set and read from filter objects as required.\n*\n* KFMeasEntrys are used for an individual measurement, before being combined into KFMeas objects that contain all of the measurements for a filter iteration.\n*\n* Internally, the data is stored in maps and Eigen matrices/vectors, but the accessors should be used rather than the vectors themselves to ensure that states have been initialised and are in the expected order.\n*/\n\n\nbool KFKey::operator ==(const KFKey& b) const\n{\n\tif (str.compare(b.str)\t!= 0)\t\treturn false;\n\tif (Sat\t\t\t\t\t!= b.Sat)\treturn false;\n\tif (type\t\t\t\t!= b.type)\treturn false;\n\tif (num\t\t\t\t\t!= b.num)\treturn false;\n\telse\t\t\t\t\t\t\t\treturn true;\n}\n\nbool KFKey::operator <(const KFKey& b) const\n{\n\tint strCompare = str.compare(b.str);\n\n\tif (strCompare < 0)\t\treturn true;\n\tif (strCompare > 0)\t\treturn false;\n\t\n\tif (type < b.type)\t\treturn true;\n\tif (type > b.type)\t\treturn false;\n\n\tif (Sat < b.Sat)\t\treturn true;\n\tif (Sat > b.Sat)\t\treturn false;\n\n\tif (num < b.num)\t\treturn true;\n\telse\t\t\t\t\treturn false;\n}\n\n\n/** Clears and initialises the state transition matrix to identity at the beginning of an epoch.\n* Also clears any noise that was being added for the initialisation of a new state.\n*/\nvoid KFState::initFilterEpoch()\n{\n\tZAdditionMap.\t\tclear();\n\tinitNoiseMap.\t\tclear();\n\n\tKFKey oneKey;\n\toneKey.type = KF::ONE;\n\t\n\tfor (auto& [key1, mapp]\t: stateTransitionMap)\n\t{\n\t\tif (key1 == oneKey)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t//remove initialisation elements for subsequent epochs\n\t\tmapp.erase(oneKey);\n\t}\n\t\n\tstateTransitionMap\t[oneKey][oneKey]\t= {1, 0};\n}\n\n/** Finds the position in the KF state vector of particular states.\n*/\nint KFState::getKFIndex(\n\tKFKey\t\tkey)\t\t///< [in]\tKey to search for in state\n{\n\tauto index = kfIndexMap.find(key);\n\tif (index == kfIndexMap.end())\n\t{\n\t\treturn -1;\n\t}\n\treturn index->second;\n}\n\n/** Returns the value and variance of a state within the kalman filter object\n*/\nbool KFState::getKFValue(\n\tKFKey\t\tkey,\t\t\t///< [in]\tKey to search for in state\n\tdouble&\t\tvalue,\t\t\t///< [out]\tOutput value\n\tdouble*\t\tvariance)\t\t///< [out]\tOutput variance\n{\n\tauto a = kfIndexMap.find(key);\n\tif (a == kfIndexMap.end())\n\t{\n//\t\tstd::cout << std::endl << \"Warning: State not found in filter: \" << key << std::endl;\n\t\treturn false;\n\t}\n\tint index = a->second;\n\tif (index >= x.size())\n\t{\n\t\treturn false;\n\t}\n\tvalue = x(index);\n\n\tif (variance)\n\t{\n\t\t*variance = P(index,index);\n\t}\n\n\treturn true;\n}\n\n/** Returns the standard deviation of a state within the kalman filter object\n*/\nbool KFState::getKFSigma(\n\tKFKey\t\tkey,\t\t///< [in]\tKey to search for in state\n\tdouble&\t\tsigma)\t\t///< [out]\tOutput value\n{\n\tauto a = kfIndexMap.find(key);\n\tif (a == kfIndexMap.end())\n\t{\n\t\treturn false;\n\t}\n\tint index = a->second;\n\tif (index >= x.size())\n\t{\n\t\treturn false;\n\t}\n\n\tsigma = sqrt(P(index,index));\n\treturn true;\n}\n\n/** Sets the value of a state within the kalman filter object\n*/\nbool KFState::setKFValue(\n\tKFKey\t\tkey,\t\t///< [in]\tKey to search for in state\n\tdouble\t\tvalue)\t\t///< [in]\tInput value\n{\n\tauto a = kfIndexMap.find(key);\n\tif (a == kfIndexMap.end())\n\t{\n\t\treturn false;\n\t}\n\n\tint index = a->second;\n\tif (index >= x.size())\n\t{\n\t\treturn false;\n\t}\n\n\tx(index) = value;\n\n\treturn true;\n}\n\n/** Sets the process noise of a state within the kalman filter object\n*/\nbool KFState::setKFNoise(\n\tKFKey\t\tkfKey,\t\t///< [in]\tKey to search for in state\n\tdouble\t\tvalue)\t\t///< [in]\tInput value\n{\n\tprocNoiseMap[kfKey] = value;\n\n\treturn true;\n}\n\n\n/** Adds dynamics to a filter state by inserting off-diagonal, time dependent elements to transition matrix\n*/\nvoid KFState::setKFTransRate(\n\tKFKey\t\t\tdest,\t\t\t///< [in]\tKey to search for in state to change in transition\n\tKFKey\t\t\tsource,\t\t\t///< [in]\tKey to search for in state as source\n\tdouble\t\t\tvalue,\t\t\t///< [in]\tInput value\n\tInitialState\tinitialState)\t///< [in]\tInitial state for rate state.\n{\n\taddKFState(source, initialState);\n\n\tstateTransitionMap[dest][source] = {value, 1};\n}\n\n/** Adds dynamics to a filter state by inserting off-diagonal, non-time dependent elements to transition matrix\n*/\nvoid KFState::setKFTrans(\n\tKFKey\t\t\tdest,\t\t\t///< [in]\tKey to search for in state to change in transition\n\tKFKey\t\t\tsource,\t\t\t///< [in]\tKey to search for in state as source\n\tdouble\t\t\tvalue,\t\t\t///< [in]\tInput value\n\tInitialState\tinitialState)\t///< [in]\tInitial state for rate state.\n{\n\taddKFState(dest, initialState);\n\n\tauto& [oldValue, rate] = stateTransitionMap[dest][source];\n\t\n\tif (rate != 0)\n\t{\n\t\tstd::cout << \"ERROR: BAD TRANS SUM\" << std::endl;\n\t\treturn;\n\t}\n\t\n\tvalue += oldValue;\n\t\n\tstateTransitionMap[dest][source] = {value, 0};\n}\n\n/** Remove a state from a kalman filter object.\n*/\nvoid KFState::removeState(\n\tKFKey\t\t\tkfKey)\t\t\t\t///< [in]\tKey to search for in state\n{\n\tZTransitionMap.\t\t\terase(kfKey);\n\tstateTransitionMap.\t\terase(kfKey);\n\tprocNoiseMap.\t\t\terase(kfKey);\n\tgaussMarkovTauMap.\t\terase(kfKey);\n\tgaussMarkovMuMap.\t\terase(kfKey);\n}\n\n/** Tries to add a state to the filter object.\n*  If it does not exist, it adds it to a list of states to be added.\n*  Call consolidateKFState() to apply the list to the filter object\n*/\nvoid KFState::addKFState(\n\tKFKey\t\t\tkfKey,\t\t\t///< [in]\tThe key to add to the state\n\tInitialState\tinitialState)\t///< [in]\tThe initial conditions to add to the state\n{\n\tauto iter = stateTransitionMap.find(kfKey);\n\tif (iter != stateTransitionMap.end())\n\t{\n\t\t//is an existing state, just update values\n\t\tif (initialState.Q\t\t!= 0)\t\t{\tprocNoiseMap\t\t[kfKey]\t= initialState.Q;\t\t}\t\n\t\tif (initialState.mu\t\t!= 0)\t\t{\tgaussMarkovMuMap\t[kfKey]\t= initialState.mu;\t\t}\t\n\t\tif (initialState.tau\t!= 0)\t\t{\tgaussMarkovTauMap\t[kfKey] = initialState.tau;\t\t}\n\n\t\treturn;\n\t}\n\n\t//this is a new state, add to the state transition matrix to create a new state.\n\n\tKFKey ONE = {KF::ONE};\n\tZAdditionMap\t\t[kfKey]\t\t\t=  1;\n\tZTransitionMap\t\t[kfKey][kfKey]\t=  1;\n\tstateTransitionMap\t[kfKey][kfKey]\t= {1,\t\t\t\t0};\n\tstateTransitionMap\t[kfKey][ONE]\t= {initialState.x,\t0};\n\tinitNoiseMap\t\t[kfKey]\t\t\t=  initialState.P;\t\t//todo aaron, check if these can be neglected for zero entries\n\tprocNoiseMap\t\t[kfKey]\t\t\t=  initialState.Q;\n\tgaussMarkovTauMap\t[kfKey]\t\t\t=  initialState.tau;\n\tgaussMarkovMuMap\t[kfKey]\t\t\t=  initialState.mu;\n\n\tif (initialState.P == 0)\n\t{\n\t\t//will be an uninitialised variable, do a least squares solution\n\t\tlsqRequired = true;\n\t}\n}\n\n\n/** Tries to add a noise element.\n*  If it does not exist, it adds it to a list of states to be added.\n*  Call consolidateKFState() to apply the list to the filter object\n*/\nvoid KFState::addNoiseElement(\n\tObsKey\t\t\tobsKey,\n\tdouble\t\t\tvariance)\n{\n\tnoiseElementMap[obsKey]\t= variance;\n}\n\n/** Add process noise and dynamics to filter object according to time gap.\n * This will also sort states according to their kfKey as a result of the way the state transition matrix is generated.\n */\nvoid KFState::stateTransition(\n\tTrace&\t\ttrace,\t\t///< [out]\tTrace file for output\n\tGTime\t\tnewTime)\t///< [in]\tTime of update for process noise and dynamics (s)\n{\n\tKFState& kfState = *this;\n\t\n\tdouble tgap = 0;\n\tif\t( newTime\t!= GTime::noTime()\n\t\t&&time\t\t!= GTime::noTime())\n\t{\n\t\ttgap = newTime.time - time.time;\n\t}\n\t\n\tif\t( newTime\t!= GTime::noTime())\n\t{\n\t\ttime = newTime;\n\t}\n\t\n//\tTestStack ts(__FUNCTION__);\n\n\tint newStateCount = stateTransitionMap.size();\n\tif (newStateCount == 0)\n\t{\n\t\tstd::cout << \"THIS IS WEIRD\" << std::endl;\n\t\treturn;\n\t}\n\n\t//Initialise and populate a state transition and Z transition matrix\n\tSparseMatrix<double>\tF_z\t\t= SparseMatrix<double>\t(newStateCount, x.rows());\n\tSparseMatrix<double>\tF\t\t= SparseMatrix<double>\t(newStateCount, x.rows());\n// \tMatrixXd\t\t\tF\t\t= MatrixXd::Zero(newStateCount, x.rows());\n\tVectorXd\t\t\tZ_plus\t= VectorXd::Zero(newStateCount);\n\t\n\t//add transitions for any states (usually close to identity)\n\tint row = 0;\n\tmap<KFKey, short int> newKFIndexMap;\n\tfor (auto& [newStateKey, newStateMap] : stateTransitionMap)\n\t{\n\t\tnewKFIndexMap[newStateKey] = row;\n\n\t\tfor (auto& [sourceStateKey, values] : newStateMap)\n\t\t{\n\t\t\tint sourceIndex\t= getKFIndex(sourceStateKey);\n\n\t\t\tif\t( (sourceIndex < 0)\n\t\t\t\t||(sourceIndex >= F.cols()))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tauto& [value, tExp] = values;\n\n\t\t\tdouble tau = -1;\n\t\t\t\n\t\t\tauto gmIter = gaussMarkovTauMap.find(sourceStateKey);\n\t\t\tif (gmIter != gaussMarkovTauMap.end())\n\t\t\t{\n\t\t\t\tauto& [dummy, sourceTau] = *gmIter;\n\t\t\t\n\t\t\t\ttau = sourceTau;\n\t\t\t}\n\n\t\t\tdouble scalar = 1;\t\t\t\n\t\t\t\n\t\t\tif (tau < 0)\n\t\t\t{\n\t\t\t\t//Random Walk model (special case for First Order Gauss Markov model when tau == inf)\n\t\t\t\n\t\t\t\tfor (int i = 0; i < tExp; i++)\n\t\t\t\t{\n\t\t\t\t\tscalar *= tgap / (i+1);\n\t\t\t\t}\n\t\t\t\t\n// \t\t\t\tF(row, sourceIndex) = value * scalar;\n\t\t\t\tF.insert(row, sourceIndex) = value * scalar;\n\t\t\t\t\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t//First Order Gauss Markov model, Ref: Carpenter and Lee (2008) - A Stable Clock Error Model Using Coupled First- and Second-Order Gauss-Markov Processes - https://ntrs.nasa.gov/api/citations/20080044877/downloads/20080044877.pdf\n\t\t\n\t\t\tdouble tempTerm = 1;\n\t\t\tscalar = exp(-tgap/tau);\n\t\t\t\n\t\t\tfor (int i = 0; i < tExp; i++)\n\t\t\t{\n\t\t\t\tscalar = tau * (tempTerm - scalar);\t//recursive formula derived according to Ref: Carpenter and Lee (2008)\n\t\t\t\ttempTerm *= tgap / (i+1);\n\t\t\t}\n\t\t\t\n\t\t\tdouble transition = value * scalar;\n\t\t\t\n// \t\t\tF(row, sourceIndex) = transition;\n\t\t\tF.insert(row, sourceIndex) = transition;\n\t\t\t\n\t\t\t\n\t\t\t//Add state transitions to ONE element, to allow for tiedown to average value mu\n\t\t\t//derived from integrating and distributing terms for v = (v0 - mu) * exp(-t/tau) + mu;\n\t\t\t//tempTerm calculated above appears to be same as required for these terms too, (at least for tExp = 0,1)\n\t\t\t\n\t\t\tauto muIter = gaussMarkovMuMap.find(sourceStateKey);\n\t\t\tif (muIter != gaussMarkovMuMap.end())\n\t\t\t{\n\t\t\t\tauto& [dummy2, mu] = *muIter;\n\t\t\t\t\n// \t\t\t\tF(row, 0) = mu * (tempTerm - transition);\n\t\t\t\tF.insert(row, 0) = mu * (tempTerm - transition);\n\t\t\t}\n\t\t}\n\t\t\n\t\trow++;\n\t}\n\t\n\tfor (auto& [kfKey1, map] : ZTransitionMap)\n\tfor (auto& [kfKey2, value] : map)\n\t{\n\t\tint index2\t= getKFIndex(kfKey2);\n\n\t\tif\t( (index2 < 0)\n\t\t\t||(index2 >= F.cols()))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tauto it = newKFIndexMap.find(kfKey1);\t//todo aaron, this shold be ensured true elsewhere\n\t\tif (it == newKFIndexMap.end())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tauto& [dummy, row] = *it;\n\t\t\n// \t\tF_z(row, index2) = value;\n\t\tF_z.insert(row, index2) = value;\n\t}\n\t\n\t\n\tfor (auto& [kfKey, value] : ZAdditionMap)\n\t{\n\t\tint row = newKFIndexMap[kfKey];\n\t\t\n\t\tZ_plus(row) = value;\n\t}\n\n\t//scale and add process noise\n\tMatrixXd Q0 = MatrixXd::Zero(newStateCount, newStateCount);\n\ttgap = fabs(tgap);\n\n\t//add noise as 'process noise' as the method of initialising a state's variance\n\tfor (auto& [kfKey, value]\t: initNoiseMap)\n\t{\n\t\tauto iter = newKFIndexMap.find(kfKey);\n\t\tif (iter == newKFIndexMap.end())\n\t\t{\n\t\t\tstd::cout << kfKey << \" broke\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tint index\t= iter->second;\n\n\t\tif\t( (index < 0)\n\t\t\t||(index >= Q0.rows()))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tQ0(index, index) = value;\n\t}\n\n\t//add time dependent process noise\n\tif (tgap)\n\tfor (auto& [dest,\tmap]\t: stateTransitionMap)\n\tfor (auto& [source,\tvals]\t: map)\n\t{\n\t\tauto& [val, tExp] = vals;\n\t\n\t\tauto initIter = initNoiseMap.find(dest);\n\t\tif (initIter != initNoiseMap.end())\n\t\t{\n\t\t\t//this was initialised this epoch\n\t\t\tdouble init = initIter->second;\n\n\t\t\tif (init == 0)\n\t\t\t{\n\t\t\t\t//this was initialised with no noise, do lsq, dont add process noise\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tauto destIter = newKFIndexMap.find(dest);\n\t\tif (destIter == newKFIndexMap.end())\n\t\t{\n\t\t\tstd::cout << dest << \" broke\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tint destIndex\t= destIter->second;\n\n\t\tif\t( (destIndex < 0)\n\t\t\t||(destIndex >= Q0.rows()))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tauto sourceIter = newKFIndexMap.find(source);\n\t\tif (sourceIter == newKFIndexMap.end())\n\t\t{\n\t\t\tstd::cout << dest << \" broKe\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tint sourceIndex\t= sourceIter->second;\n\n\t\tif\t( (sourceIndex < 0)\n\t\t\t||(sourceIndex >= Q0.rows()))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tauto iter2 = procNoiseMap.find(source);\n\t\tif (iter2 == procNoiseMap.end())\n\t\t{\n// \t\t\tstd::cout << dest << \" brOke\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tauto [dummy, sourceProcessNoise] = *iter2;\n\t\t\n\t\tauto gmIter = gaussMarkovTauMap.find(source);\n\t\tif (gmIter != gaussMarkovTauMap.end())\n\t\t{\n\t\t\tauto& [dummy, tau] = *gmIter;\n\n\t\t\tif (tau < 0)\n\t\t\t{\n\t\t\t\t//Random Walk model (special case for First Order Gauss Markov model when tau == inf)\n\t\t\t\t\n\t\t\t\tif\t\t(tExp == 0)\t{\tQ0(destIndex,\tdestIndex) += sourceProcessNoise / 1\t* tgap;}\n\t\t\t\telse if\t(tExp == 1)\t{\tQ0(destIndex,\tdestIndex) += sourceProcessNoise / 3\t* tgap * tgap * tgap;\t\n\t\t// \t\t\t\t\t\t\t\tQ0(sourceIndex, destIndex) += sourceProcessNoise / 2\t* tgap * tgap;\t\n\t\t// \t\t\t\t\t\t\t\tQ0(destIndex, sourceIndex) += sourceProcessNoise / 2\t* tgap * tgap; \n\t\t\t\t\t\t\t\t\t}\n\t\t\t\telse if (tExp == 2)\t{\tQ0(destIndex,\tdestIndex) += sourceProcessNoise / 20\t* tgap * tgap * tgap * tgap * tgap;}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//First Order Gauss Markov model, Ref: Carpenter and Lee (2008) - A Stable Clock Error Model Using Coupled First- and Second-Order Gauss-Markov Processes - https://ntrs.nasa.gov/api/citations/20080044877/downloads/20080044877.pdf\n\t\t\t\n\t\t\t\tif\t\t(tExp == 0)\t{\tQ0(destIndex,\tdestIndex) += sourceProcessNoise / 2\t* tau * (1 - exp(-2*tgap/tau));\t\t}\n\t\t\t\telse if\t(tExp == 1)\t{\tQ0(destIndex,\tdestIndex) += sourceProcessNoise / 2\t* tau * tau * (\t+ 2 * tgap \t\t\t\t\t\t\t\t//one tau from front tau3 distributed to prevent divide by zero\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t- 4 * tau * (1 - exp(-1*tgap/tau)) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ 1 * tau * (1 - exp(-2*tgap/tau)));\t//correct formula re-derived according to Ref: Carpenter and Lee (2008)\n\t\t// \t\t\t\t\t\t\t\tQ0(sourceIndex, destIndex) += sourceProcessNoise / 2\t* tau * tau * (1-exp(-tgap/tau)) * (1-exp(-tgap/tau));\n\t\t// \t\t\t\t\t\t\t\tQ0(destIndex, sourceIndex) += sourceProcessNoise / 2\t* tau * tau * (1-exp(-tgap/tau)) * (1-exp(-tgap/tau));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\telse if (tExp == 2)\t{\tstd::cout << \"FOGM model is not applied to acceleration term at the moment\" << std::endl;\t}\t//todo Eugene: add process noise for acceleration term\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"Tau value not found in filter: \" << source << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\t//output the state transition matrix to a trace file (used by RTS smoother)\n\tif (rts_filename.empty() == false)\n\t{\n\t\tTransitionMatrixObject transitionMatrixObject;\n\t\ttransitionMatrixObject.rows = F.rows();\n\t\ttransitionMatrixObject.cols = F.cols();\n\n\t\tfor (int k = 0; k < F.outerSize(); ++k)\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(F, k); it; ++it)\n\t\t{\n\t\t\tdouble transition = it.value();\n\t\t\t\n\t\t\tif (transition == 0)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\ttransitionMatrixObject.forwardTransitionMap[{it.row(), it.col()}] = transition;\n\t\t}\n\t\t\n\t\tspitFilterToFile(transitionMatrixObject,\tE_SerialObject::TRANSITION_MATRIX,\trts_forward_filename);\n\t}\n\t\n\t//compute the updated states and permutation and covariance matrices\n\tif (F.rows() == F.cols())\n\t{\n// \t\tInstrument\tinstrument(\"PPPalgebra0\");\n\t\tdx = (F * x) - x;\n\t}\n\t\n\t{\n// \t\tInstrument\tinstrument(\"PPPalgebra1\");\n\t\tZ = (F_z\t* Z\t* F_z.transpose()\t\t\t).eval();\n\t}\n\t{\n// \t\tInstrument\tinstrument(\"PPPalgebra2\");\n\t\tx = (F\t\t* x\t\t\t\t\t\t\t\t).eval();\n\t}\n\t{\n// \t\tInstrument\tinstrument(\"PPPalgebra3\");\n\t\tP = (F\t\t* P * F.transpose()\t\t+ Q0\t).eval();\n\t}\n\t{\n// \t\tInstrument\tinstrument(\"PPPalgebra4\");\n\t\tZ += Z_plus.asDiagonal();\n\t}\n// \tstd::cout << \"F_z\" << std::endl << F_z << std::endl;\n// \tstd::cout << \"F\" << std::endl << F << std::endl;\n// \tstd::cout << \"Z\" << std::endl << Z << std::endl;\n\n\t//replace the index map with the updated version that corresponds to the updated state\n\tkfIndexMap = std::move(newKFIndexMap);\n\t\n\tinitFilterEpoch();\n}\n\n/** Compare variances of measurements and pre-filtered states to detect unreasonable values\n* Ref: Wang et al. (1997) - On Quality Control in Hydrographic GPS Surveying\n* &  Wieser et al. (2004) - Failure Scenarios to be Considered with Kinematic High Precision Relative GNSS Positioning - http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.573.9628&rep=rep1&type=pdf\n*/\nvoid KFState::preFitSigmaCheck(\n\tTrace&\t\ttrace,\t\t\t///< Trace to output to\n\tKFMeas&\t\tkfMeas,\t\t\t///< Measurements, noise, and design matrix\n\tKFKey&\t\tbadStateKey,\t///< Key to the state that has worst ratio (only if worse than badMeasIndex)\n\tint&\t\tbadMeasIndex,\t///< Index of the measurement that has the worst ratio\n\tdouble&\t\tsumOfSqTestStat,\t///< Sum of squared test statistics\n\tint\t\t\tbegX,\t\t\t///< Index of first state element to process\n\tint\t\t\tnumX,\t\t\t///< Number of states elements to process\n\tint\t\t\tbegH,\t\t\t///< Index of first measurement to process\n\tint\t\t\tnumH)\t\t\t///< Number of measurements to process\n{\n\tauto\t\tv = kfMeas.V.segment(begH, numH);\n\tauto\t\tR = kfMeas.R.block(begH, begH, numH, numH);\n\tauto\t\tH = kfMeas.A.block(begH, begX, numH, numX);\n\tauto\t\tP = this-> P.block(begX, begX, numX, numX);\n\n\tArrayXd\t\tmeasRatios\t= ArrayXd::Zero(numH);\n\tArrayXd\t\tstateRatios\t= ArrayXd::Zero(numX);\n\n\tif (sigma_check)\n\t{\n\t\t//use 'array' for component-wise calculations\n\t\tauto\t\tmeasVariations\t= v.array().square();\t//delta squared\n\t\tauto\t\tmeasVariances\t= (R.diagonal() + (H * P * H.transpose()).diagonal()).array();\n\t\n\t\tmeasRatios\t= measVariations\t/ measVariances;\n\n\t\ttrace << std::endl << \"DOING PRE SIGMA CHECK: \";\n\t}\n\telse if (w_test)\n\t{\n\t\tMatrixXd\tQinv\t= (R + H * P * H.transpose()).inverse();\n\t\tMatrixXd\tH_Qinv\t= H.transpose() * Qinv;\n\n\t\t//use 'array' for component-wise calculations\n\t\tauto\t\tmeasVariations\t= (Qinv * v)\t.array().square();\n\t\tauto\t\tstateVariations\t= (H_Qinv * v)\t.array().square();\n\n\t\tauto\t\tmeasVariances\t=  Qinv\t\t\t.diagonal().array();\n\t\tauto\t\tstateVariances\t= (H_Qinv * H)\t.diagonal().array();\n\t\n\t\tmeasRatios\t= measVariations\t/ measVariances;\n\t\tstateRatios\t= stateVariations\t/ stateVariances;\n\t\tstateRatios\t= stateRatios.isFinite().select(stateRatios, 0);\t//set ratio to 0 if corresponding variance is 0, e.g. ONE state, clk rate states\n\n\t\ttrace << std::endl << \"DOING W-TEST: \";\n\t}\n\n\tsumOfSqTestStat\t= measRatios.sum() + stateRatios.sum();\n\n\t//if any are outside the expected value, flag an error\n\n\tEigen::ArrayXd::Index stateIndex;\n\tEigen::ArrayXd::Index measIndex;\n\t\n\tdouble maxStateRatio\t= stateRatios\t.maxCoeff(&stateIndex);\n\tdouble maxMeasRatio\t\t= measRatios\t.maxCoeff(&measIndex);\n\t\n\t//if any are outside the expected values, flag an error\n\tif\t( maxStateRatio > maxMeasRatio\n\t\t&&maxStateRatio > SQR(sigma_threshold))\n\t{\n\t\tint chunkIndex = stateIndex + begX;\n\t\t\n\t\tauto it = kfIndexMap.begin();\n\t\tstd::advance(it, stateIndex);\n\t\t\n\t\tauto& [key, dummy] = *it;\n\t\t\n\t\ttrace << std::endl << \"LARGE STATE ERROR OF \" << maxStateRatio\t<< \" AT \" << chunkIndex << \" : \" << key;\n\t\t\n\t\tbadStateKey = key;\n\t}\n\t\n\tif\t(maxMeasRatio > SQR(sigma_threshold))\n\t{\n\t\tint chunkIndex = measIndex + begH;\n\t\t\n\t\ttrace << std::endl << \"LARGE MEAS  ERROR OF \" << maxMeasRatio\t<< \" AT \" << chunkIndex << \" : \" << kfMeas.obsKeys[chunkIndex];\n\t\t\n\t\tbadMeasIndex = measIndex + begH;\n\t}\n}\n\n/** Compare variances of measurements and filtered states to detect unreasonable values\n*/\nvoid KFState::postFitSigmaChecks(\n\tTrace&\t\ttrace,      \t///< Trace file to output to\n\tKFMeas&\t\tkfMeas,\t\t\t///< Measurements, noise, and design matrix\n\tVectorXd&\txp,         \t///< The post-filter state vector to compare with measurements\n\tVectorXd&\tdx,\t\t\t\t///< The innovations from filtering to recalculate the deltas.\n\tint\t\t\titeration,\t\t///< Number of iterations prior to this check\n\tKFKey&\t\tbadStateKey,\t///< Key to the state that has worst ratio (only if worse than badMeasIndex)\n\tint&\t\tbadMeasIndex,\t///< Index of the measurement that has the worst ratio\n\tdouble&\t\tsumOfSqTestStat,\t///< Sum of squared test statistics\n\tint\t\t\tbegX,\t\t\t///< Index of first state element to process\n\tint\t\t\tnumX,\t\t\t///< Number of state elements to process\n\tint\t\t\tbegH,\t\t\t///< Index of first measurement to process\n\tint\t\t\tnumH)\t\t\t///< Number of measurements to process\n{\n\tauto\t\tH = kfMeas.A.block(begH, begX, numH, numX);\n\tVectorXd\tvv = kfMeas.V.segment(begH, numH) - H * dx.segment(begX, numX);\n\n\t//use 'array' for component-wise calculations\n\tauto\t\tmeasVariations\t\t= vv\t\t\t\t\t.array().square();\t//delta squared\n\tauto\t\tstateVariations\t\t= dx.segment(begX, numX).array().square();\n\t\n\tauto\t\tmeasVariances\t\t= kfMeas.\tR.block(begH, begH, numH, numH).diagonal().array();\n\tauto\t\tstateVariances\t\t= \t\t\tP.block(begX, begX, numX, numX).diagonal().array();\n\t\n\tauto\t\tmeasRatios\t\t\t= measVariations\t/ measVariances;\n\tArrayXd\t\tstateRatios\t\t\t= stateVariations\t/ stateVariances;\n\t\t\t\tstateRatios\t\t\t= stateRatios.isFinite().select(stateRatios, 0);\t\n\t\n\tif (output_residuals)\n\t{\n\t\ttrace << std::endl << \"+ Residuals\" << std::endl;\n\t\ttracepdeex(2, trace, \"#\\t%2s\\t%19s\\t%8s\\t%3s\\t%7s\\t%13s\\t%13s\\t%16s\\n\", \"It\", \"Time\", \"Str\", \"Sat\", \"Type\", \"Prefit Res\", \"Postfit Res\", \"Meas Variance\");\n\n\t\tfor (int i = begH; i < begH + numH; i++)\n\t\t{\n\t\t\ttracepdeex(2, trace, \"%%\\t%2d\\t%19s\\t%20s\\t%13.4f\\t%13.4f\\t%16.9f\\n\", iteration, time.to_string(0).c_str(), ((string)kfMeas.obsKeys[i]).c_str(), kfMeas.V(i), vv(i - begH), kfMeas.R(i,i));\n\t\t}\n\t\ttrace << \"- Residuals\" << std::endl;\n\t}\n\t\n#\tifdef ENABLE_MONGODB\n\tif (acsConfig.output_mongo_measurements)\n\t{\n\t\tmongoMeasResiduals(kfMeas.obsKeys, kfMeas.V, vv, kfMeas.R, begH, numH);\n\t}\n#\tendif\n\n\ttrace << std::endl << \"DOING SIGMACHECK: \";\n\t\n\n\tsumOfSqTestStat\t= measRatios.sum() + stateRatios.sum();\n\n\t//if any are outside the expected values, flag an error\n\t\n\tEigen::ArrayXd::Index stateIndex;\n\tEigen::ArrayXd::Index measIndex;\n\t\n\tdouble maxStateRatio\t= stateRatios\t.maxCoeff(&stateIndex);\n\tdouble maxMeasRatio\t\t= measRatios\t.maxCoeff(&measIndex);\n\t\n\t//if any are outside the expected values, flag an error\n\tif\t( maxStateRatio > maxMeasRatio\n\t\t&&maxStateRatio > SQR(sigma_threshold))\n\t{\n\t\tint chunkIndex = stateIndex + begX;\n\t\t\n\t\tauto it = kfIndexMap.begin();\n\t\tstd::advance(it, stateIndex);\n\t\t\n\t\tauto& [key, dummy] = *it;\n\t\t\n\t\ttrace << std::endl << \"LARGE STATE ERROR OF \" << maxStateRatio\t<< \" AT \" << chunkIndex << \" : \" << key;\n\t\t\n\t\tbadStateKey = key;\n\t}\n\t\n\tif\t(maxMeasRatio > SQR(sigma_threshold))\n\t{\n\t\tint chunkIndex = measIndex + begH;\n\t\t\n\t\ttrace << std::endl << \"LARGE MEAS  ERROR OF \" << maxMeasRatio\t<< \" AT \" << chunkIndex << \" : \" << kfMeas.obsKeys[chunkIndex];\n\t\t\n\t\tbadMeasIndex = measIndex + begH;\n\t}\n}\n\n/** Compute Chi-square increment based on the change of fitting solution\n*/\ndouble KFState::stateChiSquare(\n\tTrace&\t\ttrace,      ///< Trace file to output to\n\tMatrixXd&\tPp,   \t\t///< Post-update covariance of states\n\tVectorXd&\tdx,\t\t\t///< The innovations from filtering to recalculate the deltas.\n\tint\t\t\tbegX,\t\t///< Index of first state element to process\n\tint\t\t\tnumX,\t\t///< Number of states elements to process\n\tint\t\t\tbegH,\t\t///< Index of first measurement to process\n\tint\t\t\tnumH)\t\t///< Number of measurements to process\n{\n\tif (begX == 0)\t//exclude the One state\n\t{\n\t\tbegX  = 1;\n\t\tnumX -= 1;\n\t}\n\t\n\tauto\t\tw  = dx.segment(begX, numX);\n\tMatrixXd\tP  = this->P.block(begX, begX, numX, numX);\n\t// MatrixXd\tdP = this->P.block(begX, begX, numX, numX) - Pp.block(begX, begX, numX, numX);\t//Ref: Li et al. (2020) - Robust Kalman Filtering Based on Chi-square Increment and Its Application - https://www.mdpi.com/2072-4292/12/4/732/pdf\n\n\tdouble\t\tchiSq = w.transpose() * P.inverse() * w;\n\t// double\t\tchiSq = w.transpose() * dP.inverse() * w;\t//Ref: Li et al. (2020) - Robust Kalman Filtering Based on Chi-square Increment and Its Application - https://www.mdpi.com/2072-4292/12/4/732/pdf\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//numerical instability problem exists for dP.inverse()\n\n\ttrace << std::endl << \"DOING STATE CHI-SQUARE TEST:\";\n\t// for (int i = 0; i < numX; i++)\ttrace << \"dx: \" \t<< w(i) << \"\\tdP: \"\t<< dP(i, i) << std::endl;\n\t\n\treturn chiSq;\n}\n\n/** Compute Chi-square increment based on post-fit residuals\n*/\ndouble KFState::measChiSquare(\n\tTrace&\t\ttrace,      ///< Trace file to output to\n\tKFMeas&\t\tkfMeas,\t\t///< Measurements, noise, and design matrix\n\tVectorXd&\tdx,\t\t\t///< The innovations from filtering to recalculate the deltas.\n\tint\t\t\tbegX,\t\t///< Index of first state element to process\n\tint\t\t\tnumX,\t\t///< Number of states elements to process\n\tint\t\t\tbegH,\t\t///< Index of first measurement to process\n\tint\t\t\tnumH)\t\t///< Number of measurements to process\n{\n\tauto\t\tw = dx.segment(begX, numX);\n\tauto\t\tH = kfMeas.A.block(begH, begX, numH, numX);\n\tVectorXd\tv = kfMeas.V.segment(begH, numH) - H * w;\n\tauto\t\tR = kfMeas.R.block(begH, begH, numH, numH);\n\n\tdouble\t\tchiSq = (v.array().square() / R.diagonal().array()).sum();\n\n\ttrace << std::endl << \"DOING MEASUREMENT CHI-SQUARE TEST:\";\n\t// for (int i = 0; i < numH; i++)\ttrace << \"v(+): \"\t<< v(i) << \"\\tR: \"\t\t<< R(i, i) << std::endl;\n\t\n\treturn chiSq;\n}\n\n/** Compute Chi-square increment based on pre-fit residuals (innovations)\n*/\ndouble KFState::innovChiSquare(\n\tTrace&\t\ttrace,\t\t///< Trace to output to\n\tKFMeas&\t\tkfMeas,\t\t///< Measurements, noise, and design matrix\n\tint\t\t\tbegX,\t\t///< Index of first state element to process\n\tint\t\t\tnumX,\t\t///< Number of states elements to process\n\tint\t\t\tbegH,\t\t///< Index of first measurement to process\n\tint\t\t\tnumH)\t\t///< Number of measurements to process\n{\n\tauto\t\tH = kfMeas.A.block(begH, begX, numH, numX);\n\tauto\t\tv = kfMeas.V.segment(begH, numH);\n\tauto\t\tR = kfMeas.R.block(begH, begH, numH, numH);\n\tauto\t\tP = this->P.block(begX, begX, numX, numX);\n\tMatrixXd\tQ = R + H * P * H.transpose();\n\t\n\tdouble\t\tchiSq = v.transpose() * Q.inverse() * v;\n\t\n\ttrace << std::endl << \"DOING INNOVATION CHI-SQUARE TEST:\";\n\t// for (int i = 0; i < numH; i++)\ttrace << \"v(-): \"\t<< v(i) << \"\\tS: \"\t\t<< Q(i, i) << std::endl;\n\t\n\treturn chiSq;\n}\n\n/** Kalman filter.\n*/\nint KFState::kFilter(\n\tTrace&\t\t\ttrace,\t\t///< Trace to output to\n\tKFMeas&\t\t\tkfMeas,\t\t///< Measurements, noise, and design matrices\n\tVectorXd&\t\txp,   \t\t///< Post-update state vector\n\tMatrixXd&\t\tPp,   \t\t///< Post-update covariance of states\n\tVectorXd&\t\tdx,\t\t\t///< Post-update state innovation\n\tint\t\t\t\tbegX,\t\t///< Index of first state element to process\n\tint\t\t\t\tnumX,\t\t///< Number of state elements to process\n\tint\t\t\t\tbegH,\t\t///< Index of first measurement to process\n\tint\t\t\t\tnumH)\t\t///< Number of measurements to process\n{\n\tauto& H = kfMeas.A;\n\tauto& R = kfMeas.R;\n\tauto& v = kfMeas.V;\n\n\tauto subH = H.block(begH, begX, numH, numX);\n\t\n\tMatrixXd HP\t= subH\t* P.block(begX, begX, numX, numX);\n\tMatrixXd Q\t= HP\t* subH.transpose();\n\n\tQ += R.block(begH, begH, numH, numH);\n\t\n\tMatrixXd K;\n\n\tbool repeat = true;\n\twhile (repeat)\n\t{\n\t\tswitch (inverter)\n\t\t{\n\t\t\tdefault:\n\t\t\tcase E_Inverter::LDLT:\n\t\t\t{\n\t\t\t\tauto QQ = Q.triangularView<Eigen::Upper>().adjoint();\n\t\t\t\tLDLT<MatrixXd> solver;\n\t\t\t\tsolver.compute(QQ);\n\t\t\t\tif (solver.info() != Eigen::ComputationInfo::Success)\n\t\t\t\t{\n\t\t\t\t\txp = x;\n\t\t\t\t\tPp = P;\n\t\t\t\t\tdx = VectorXd::Zero(xp.rows());\n\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\tauto Kt = solver.solve(HP);\n\t\t\t\tif (solver.info() != Eigen::ComputationInfo::Success)\n\t\t\t\t{\n\t\t\t\t\ttracepdeex(1, trace, \"Warning: kalman filter error2\\n\");\n\t\t\t\t\txp = x;\n\t\t\t\t\tPp = P;\n\t\t\t\t\tdx = VectorXd::Zero(xp.rows());\n\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\tK = Kt.transpose();\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase E_Inverter::LLT:\n\t\t\t{\n\t\t\t\tauto QQ = Q.triangularView<Eigen::Upper>().adjoint();\n\t\t\t\tLLT<MatrixXd> solver;\n\t\t\t\tsolver.compute(QQ);\n\t\t\t\tif (solver.info() != Eigen::ComputationInfo::Success)\n\t\t\t\t{\n\t\t\t\t\tinverter = E_Inverter::LDLT;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tauto Kt = solver.solve(HP);\n\t\t\t\tif (solver.info() != Eigen::ComputationInfo::Success)\n\t\t\t\t{\n\t\t\t\t\tinverter = E_Inverter::LDLT;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tK = Kt.transpose();\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase E_Inverter::INV:\n\t\t\t{\n\t\t\t\tMatrixXd Qinv = Q.inverse();\n\t\t\t\tK = P * H.transpose() * Qinv;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\trepeat = false;\n\t}\n\n\n\tdx.segment(begX, numX)\t= K * v.segment(begH, numH);\n\txp.segment(begX, numX)\t= x. segment(begX, numX)\n\t\t\t\t\t\t\t+ dx.segment(begX, numX);\n\n// \ttrace << std::endl << \"h \"\t<< std::endl << subH;\n// \ttrace << std::endl << \"hp \"\t<< std::endl << HP;\n// \ttrace << std::endl << \"Q \"\t<< std::endl << Q;\n// \ttrace << std::endl << \"K \"\t<< std::endl << K;\n// \ttrace << std::endl << \"X \"\t<< std::endl << x. segment(begX, numX);\n// \ttrace << std::endl << \"DX\"\t<< std::endl << dx.segment(begX, numX);\n// \ttrace << std::endl << \"xp\"\t<< std::endl << xp.segment(begX, numX);\n\t\n// \tif (acsConfig.joseph_stabilisation)\n// \t{\n// \t\tMatrixXd IKH = MatrixXd::Identity(P.rows(), P.cols()) - K * H;\n// \t\tPp = IKH * P * IKH.transpose() + K * R * K.transpose();\n// \t}\n// \telse\n\t{\n\t\tPp.block(begX, begX, numX, numX) = P.block(begX, begX, numX, numX) - K * HP;\n\t\t\n\t\tPp.block(begX, begX, numX, numX) = (\t  Pp.block(begX, begX, numX, numX) \n\t\t\t\t\t\t\t\t\t\t\t\t+ Pp.block(begX, begX, numX, numX).transpose()\t).eval() / 2;\n\t}\n\n\n\tbool error = xp.segment(begX, numX).array().isNaN().any();\n\tif (error)\n\t{\n\t\tstd::cout << std::endl << \"xp:\" << std::endl << xp << std::endl;\n\t\tstd::cout << std::endl << \"R :\" << std::endl << R << std::endl;\n\t\tstd::cout << std::endl << \"v :\" << std::endl << v << std::endl;\n\t\tstd::cout << std::endl << \"K :\" << std::endl << K << std::endl;\n\t\tstd::cout << std::endl << \"P :\" << std::endl << P << std::endl;\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"NAN found. Exiting...\";\n\t\tstd::cout << std::endl;\n\n\t\texit(0);\n\t}\n\n\tbool pass = true;\n\treturn pass;\n}\n\n/** Perform chi squared quality control.\n*/\nbool KFState::chiQC(\n\tTrace&\t\ttrace,      ///< Trace to output to\n\tKFMeas&\t\tkfMeas,\t\t///< Measurements, noise, and design matrix\n\tVectorXd&\txp)         ///< Post filtered state vector\n{\n\tauto& H = kfMeas.A;\n\tauto W = kfMeas.W(all, 0);\n\n\tVectorXd&\ty\t\t= kfMeas.Y;\n\tVectorXd\tv\t\t= y - H * xp;\n\tdouble\t\tv_Wv\t= v.transpose() * W.asDiagonal() * v;\n\n\t//trace << std::endl << \"chiqcV\" << v.rows() << std::endl;\ttracematpde(5, trace, v, 15, 5);\n\n\tint obsNumber = v.rows() - x.rows() + 1;\n\tdouble val = v_Wv / (obsNumber);\n\n\tdouble thres;\n\tif (obsNumber <= 100) \tthres = chisqr_arr[obsNumber - 1] / (obsNumber);\n\telse\t\t\t\t\tthres = 3;\n\n\t/* chi-square validation */\n\tif (val > thres)\n\t{\n\t\ttracepdeex(6, trace, \" ChiSquare error detected\");\n\n// \t\tauto variations\t= v.array().square();\n// \t\tEigen::MatrixXf::Index index;\n// \t\ttrace << \" -> LARGEe ERROR OF \" << sqrt(variations.maxCoeff(&index)) << \" AT \" << index;\n\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n/** Combine a list of KFMeasEntrys into a single KFMeas object for used in the filter\n*/\nKFMeas KFState::combineKFMeasList(\n\tKFMeasEntryList&\tkfEntryList,\t///< List of input measurements as lists of entries\n\tGTime\t\t\t\tmeasTime)\t\t///< Time to use for measurements and hence state transitions\n{\n\tint numMeas = kfEntryList.size();\n\n\tKFMeas kfMeas;\n\n\tkfMeas.time = measTime;\n\t\n\tkfMeas.V.resize(numMeas);\n\tkfMeas.Y.resize(numMeas);\n\n\tkfMeas.R = MatrixXd::Zero(numMeas, numMeas);\n\tkfMeas.A = MatrixXd::Zero(numMeas, x.rows());\n\n\tkfMeas.obsKeys\t\t.resize(numMeas);\n\tkfMeas.metaDataMaps\t.resize(numMeas);\n\n\tint meas = 0;\n\tfor (auto& entry: kfEntryList)\n\t{\n\t\tkfMeas.R(meas, meas)\t= entry.noise;\n\t\tkfMeas.Y(meas)\t\t\t= entry.value;\n\t\tkfMeas.V(meas)\t\t\t= entry.innov;\n\n\t\tfor (auto& [kfKey, value] : entry.designEntryMap)\n\t\t{\n\t\t\tint index = getKFIndex(kfKey);\n\t\t\tif (index < 0)\n\t\t\t{\n\t\t\t\tstd::cout << \"hhuh?\" << kfKey << std::endl;\n\t\t\t\treturn KFMeas();\n\t\t\t}\n\t\t\tkfMeas.A(meas, index) = value;\n\t\t}\n\n\t\tkfMeas.obsKeys\t\t[meas] = std::move(entry.obsKey);\n\t\tkfMeas.metaDataMaps\t[meas] = std::move(entry.metaDataMap);\n\t\tmeas++;\n\t}\n\t\n\tif (noiseElementMap.empty() == false)\n\t{\n\t\tVectorXd uncorrelatedNoise = VectorXd::Zero(noiseElementMap.size());\n\t\t\n\t\tmap<ObsKey, int>\tnoiseIndexMap;\n\t\tint noises = 0;\n\t\tfor (auto& [obsKey, variance] : noiseElementMap)\n\t\t{\n\t\t\tuncorrelatedNoise(noises) = variance;\n\t\t\t\n\t\t\tnoiseIndexMap[obsKey] = noises;\n\t\t\tnoises++;\n\t\t}\n\t\t\n\t\tSparseMatrix<double> R_A = SparseMatrix<double>(numMeas, noiseElementMap.size());\n\t\t\n\t\tmeas = 0;\n\t\tfor (auto& entry: kfEntryList)\n\t\t{\n\t\t\tfor (auto& [obsKey, value] : entry.noiseEntryMap)\n\t\t\t{\n\t\t\t\tint noiseIndex = noiseIndexMap[obsKey];\n\t\t\t\t\n\t\t\t\tR_A.insert(meas, noiseIndex) = value;\n\t\t\t}\n\t\t\t\n\t\t\tmeas++;\n\t\t}\n\t\t\n\t\tInstrument instrument(\"PPPnoisELment\");\n// \t\tstd::cout << R_A << std::endl;\n\t\tkfMeas.R = R_A * uncorrelatedNoise.asDiagonal() * R_A.transpose();\n\t\t\n// \t\tstd::cout << std::setprecision(5);\n// \t\tstd::cout << \"R\" << std::endl << kfMeas.R << std::endl;\n\t}\n\n\treturn kfMeas;\n}\n\nbool KFState::doStateRejectCallbacks(\n\tTrace&\t\ttrace,\t\t\t\t///< Trace file for output\n\tKFMeas&\t\tkfMeas,\t\t\t\t///< Measurements that were passed to the filter\n\tKFKey&\t\tbadKey)\t\t\t\t///< Index in measurement list that was unsatisfactory\n{\n\tfor (auto& callback : stateRejectCallbacks)\n\t{\n\t\tbool keepGoing = callback(trace, *this, kfMeas, badKey);\n\n\t\tif (keepGoing == false)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\nbool KFState::doMeasRejectCallbacks(\n\tTrace&\t\ttrace,\t\t\t\t///< Trace file for output\n\tKFMeas&\t\tkfMeas,\t\t\t\t///< Measurements that were passed to the filter\n\tint\t\t\tbadIndex)\t\t\t///< Index in measurement list that was unsatisfactory\n{\n\tfor (auto& callback : measRejectCallbacks)\n\t{\n\t\tbool keepGoing = callback(trace, *this, kfMeas, badIndex);\n\n\t\tif (keepGoing == false)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\nbool ObsKey::operator ==(const ObsKey& b) const\n{\n\tif (str.compare(b.str)\t!= 0)\t\treturn false;\n\tif (Sat\t\t\t\t\t!= b.Sat)\treturn false;\n\tif (type.compare(b.type)!= 0)\t\treturn false;\n\tif (num\t\t\t\t\t!= b.num)\treturn false;\n\telse\t\t\t\t\t\t\t\treturn true;\n}\n\nbool ObsKey::operator <(const ObsKey& b) const\n{\n\tint typeCompare = type.compare(b.type);\n\tif (typeCompare < 0)\t\treturn true;\n\tif (typeCompare > 0)\t\treturn false;\n\n\tint strCompare = str.compare(b.str);\n\tif (strCompare < 0)\t\treturn true;\n\tif (strCompare > 0)\t\treturn false;\n\n\tif (Sat < b.Sat)\t\treturn true;\n\tif (Sat > b.Sat)\t\treturn false;\n\n\tif (num < b.num)\t\treturn true;\n\tif (num > b.num)\t\treturn false;\n\n\telse\t\t\t\t\treturn false;\n}\n\n\n/** Kalman filter operation\n*/\nint KFState::filterKalman(\n\tTrace&\t\t\t\ttrace,\t\t\t\t\t///< Trace file for output\n\tKFMeas&\t\t\t\tkfMeas,\t\t\t\t\t///< Measurement object\n\tbool\t\t\t\tinnovReady,\t\t\t\t///< Innovation already constructed\n\tlist<FilterChunk>*\tfilterChunkList_ptr)\t///< Optional ist of chunks for parallel processing of sub filters\n{\n\tKFState& kfState = *this;\n\n\tif (kfMeas.time != GTime::noTime())\n\t{\n\t\tkfState.time = kfMeas.time;\n\t}\n\n\tif (kfState.rts_filename.empty() == false)\n\t{\n\t\tspitFilterToFile(kfState, E_SerialObject::FILTER_MINUS, kfState.rts_forward_filename);\n\t}\n\n\tif (kfMeas.A.rows() == 0)\n\t{\n\t\t//nothing to be done, clean up and return early\n\n\t\tif (kfState.rts_filename.empty() == false)\n\t\t{\n\t\t\tspitFilterToFile(kfState, E_SerialObject::FILTER_PLUS, kfState.rts_forward_filename);\n\t\t}\n\t\treturn 1;\n\t}\n\n\t/* kalman filter measurement update */\n\tif (innovReady == false)\n\t{\n\t\tkfMeas.V = kfMeas.Y - kfMeas.A * kfState.x;\n\t}\n\n\tlist<FilterChunk> dummyFilterChunkList;\n\tif (filterChunkList_ptr == nullptr)\n\t{\n\t\tfilterChunkList_ptr = &dummyFilterChunkList;\n\t}\n\t\n\tauto& filterChunkList = *filterChunkList_ptr;\n\t\n\tif (filterChunkList.empty())\n\t{\n\t\tFilterChunk filterChunk;\n\t\tfilterChunk.trace_ptr = &trace;\n\t\t\n\t\tfilterChunkList.push_back(filterChunk);\n\t}\n\t\n\tdouble\tprefitSumOfSqTestStat\t= 0;\n\tfor (auto& filterChunk : filterChunkList)\n\t{\n\t\tif (filterChunk.numX < 0)\tfilterChunk.numX = x.rows();\n\t\tif (filterChunk.numH < 0)\tfilterChunk.numH = kfMeas.A.rows();\n\t\t\n\t\tdouble\tchunkSumOfSqTestStat\t= 0;\n\t\tfor (int i = 0; i < max_prefit_remv; i++)\n\t\t{\n\t\t\tauto& chunkTrace = *filterChunk.trace_ptr;\n\n\t\t\tif\t(  sigma_check\t== false\n\t\t\t\t&& w_test\t\t== false)\t\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tKFKey\tbadState;\n\t\t\tint\t\tbadMeasIndex = -1;\n\n\t\t\tkfState.preFitSigmaCheck(chunkTrace, kfMeas, badState, badMeasIndex, chunkSumOfSqTestStat, filterChunk.begX, filterChunk.numX, filterChunk.begH, filterChunk.numH);\n\t\t\t\n\t\t\tif (badState.type)\t\t{\tchunkTrace << std::endl << \"Prefit check failed state test\";\t\tbool keepGoing = doStateRejectCallbacks\t(chunkTrace, kfMeas, badState);\t\t\t/*continue;*/\t}\t//always fallthrough\n\t\t\tif (badMeasIndex >= 0)\t{\tchunkTrace << std::endl << \"Prefit check failed measurement test\";\tbool keepGoing = doMeasRejectCallbacks\t(chunkTrace, kfMeas, badMeasIndex);\t\tcontinue;\t\t}\t//retry next iteration\t\n\t\t\telse\t\t\t\t\t{\tchunkTrace << std::endl << \"Prefit check passed\";\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\t\t\t}\n\t\t}\n\n\t\tprefitSumOfSqTestStat\t+= chunkSumOfSqTestStat;\n\t}\n\n\tif\t(  sigma_check \n\t\t|| w_test)\n\t{\n\t\ttrace << std::endl << \"Sum-of-squared test statistics (prefit): \"\t<< prefitSumOfSqTestStat\t<< std::endl;\n\t}\n\t\n\tMatrixXd Pp = P;\n\tVectorXd xp = x;\n\t\t\t dx = VectorXd::Zero(x.rows());\n\t\n\tdouble postfitSumOfSqTestStat = 0;\n\tfor (auto& filterChunk : filterChunkList)\n\t{\n\t\tdouble chunkSumOfSqTestStat = 0;\n\t\tfor (int i = 0; i < max_filter_iter; i++)\n\t\t{\n\t\t\tauto& chunkTrace = *filterChunk.trace_ptr;\n\t\t\t\n\t\t\tbool pass = kfState.kFilter(chunkTrace, kfMeas, xp, Pp, dx, filterChunk.begX, filterChunk.numX, filterChunk.begH, filterChunk.numH);\n\n\t\t\tif (pass == false)\n\t\t\t{\n\t\t\t\tchunkTrace << \"FILTER FAILED\" << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n// \t\t\tchunkTrace << \"\\nFrom \" << filterChunk.begH << \" for \" << filterChunk.numH;\n// \t\t\tchunkTrace << \"\\nStat \" << filterChunk.begX << \" for \" << filterChunk.numX;\n\t// \t\toutputStates(chunkTrace);\n\n\t\t\tif (sigma_check == false)\t\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tKFKey\tbadState;\n\t\t\tint\t\tbadMeasIndex = -1;\n\t\t\t\n\t\t\tkfState.postFitSigmaChecks(chunkTrace, kfMeas, xp, dx, i, badState, badMeasIndex, chunkSumOfSqTestStat, filterChunk.begX, filterChunk.numX, filterChunk.begH, filterChunk.numH);\n\t\t\t\n\t\t\tif (badState.type)\t\t{\tchunkTrace << std::endl << \"Postfit check failed state test\";\t\tbool keepGoing = doStateRejectCallbacks\t(chunkTrace, kfMeas, badState);\t\t\t/*continue;*/\t}\t//always fallthrough\n\t\t\tif (badMeasIndex >= 0)\t{\tchunkTrace << std::endl << \"Postfit check failed measurement test\";\tbool keepGoing = doMeasRejectCallbacks\t(chunkTrace, kfMeas, badMeasIndex);\t\tcontinue;\t\t}\t//retry next iteration\t\n\t\t\telse\t\t\t\t\t{\tchunkTrace << std::endl << \"Postfit check passed\";\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\t\t\t}\t//all ok, finish\n\t\t}\n\n\t\tpostfitSumOfSqTestStat += chunkSumOfSqTestStat;\n\t}\n\n\tif (sigma_check)\t\n\t\ttrace << std::endl << \"Sum-of-squared test statistics (postfit): \" << postfitSumOfSqTestStat << std::endl;\n\n\tdouble\tchiSq\t\t= 0;\n\tdouble\tdof\t\t\t= 0;\n\tdouble\tchiSqPerDof\t= 0;\n\tdouble\tqc\t\t\t= 0;\n\tif (chi_square_test)\n\t{\n\t\tfor (auto& filterChunk : filterChunkList)\n\t\t{\n\t\t\tauto& chunkTrace = *filterChunk.trace_ptr;\n\n\t\t\tswitch (chi_square_mode)\n\t\t\t{\n\t\t\t\tcase E_ChiSqMode::INNOVATION:\t{\tchiSq += kfState.innovChiSquare(chunkTrace, kfMeas,     filterChunk.begX, filterChunk.numX, filterChunk.begH, filterChunk.numH);\tbreak;\t}\n\t\t\t\tcase E_ChiSqMode::MEASUREMENT:\t{\tchiSq += kfState.measChiSquare( chunkTrace, kfMeas, dx, filterChunk.begX, filterChunk.numX, filterChunk.begH, filterChunk.numH);\tbreak;\t}\n\t\t\t\tcase E_ChiSqMode::STATE:\t\t{\tchiSq += kfState.stateChiSquare(chunkTrace, Pp,     dx, filterChunk.begX, filterChunk.numX, filterChunk.begH, filterChunk.numH);\tbreak;\t}\n\t\t\t\tdefault:\t\t\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttrace << std::endl << \"Number of measurements:\" << kfMeas.A.rows() << \"\\tNumber of states:\" << kfState.x.rows() - 1;\n\n\t\tif (chi_square_mode == +E_ChiSqMode::STATE)\tdof\t= kfState.x.rows() - 1;\n\t\telse\t\t\t\t\t\t\t\t\t\tdof\t= kfMeas. A.rows();\n\n\t\tchiSqPerDof\t= chiSq / dof;\n\n\t\t// check against threshold\n\t\tboost::math::normal normDist;\n\t\tdouble\talpha = cdf(complement(normDist, sigma_threshold)) * 2;\t//two-tailed\n\n\t\tboost::math::chi_squared chiSqDist(dof);\n\t\tqc = quantile(complement(chiSqDist, alpha));\n\t\tif (chiSq <= qc)\ttrace << std::endl << \"Chi-square test passed\";\n\t\telse\t\t\t\ttrace << std::endl << \"Chi-square test failed\";\n\n\t\ttrace << std::endl << \"Chi-square increment: \" << chiSq << \"\\tThreshold: \" << qc << \"\\tDegree of freedom: \" << dof << \"\\tChi-square per DOF: \" << chiSqPerDof << std::endl;\n\t}\n\n#\tifdef ENABLE_MONGODB\n\tif (acsConfig.output_mongo_test_stats)\n\t{\n\t\tmongoTestStat(kfState, prefitSumOfSqTestStat, postfitSumOfSqTestStat, chiSq, qc, dof, chiSqPerDof);\n\t}\n#\tendif\n\n// \tif (pass)\n\t{\n\t\tkfState.x = std::move(xp);\n\t\tkfState.P = std::move(Pp);\n\t}\n\n\tif (kfState.rts_filename.empty() == false)\n\t{\n\t\tspitFilterToFile(kfState, E_SerialObject::FILTER_PLUS, kfState.rts_forward_filename);\n\t}\n\t\n\tinitFilterEpoch();\n\treturn 1;\n}\n\n/** Perform least squares using the measurements in the KFMeas object\n*/\nint KFState::filterLeastSquares(\n\tTrace&\t\t\ttrace,\t\t///< [in]\t\tTrace to output to\n\tKFMeas&\t\t\tkfMeas)\t\t///< [in]\t\tMeasurements, noise, and design matrix\n{\n\tKFState& kfState = *this;\n\n\ttrace << std::endl << \" -------STARTING LS --------\" << std::endl;\n\n\t//invert measurement noise matrix to get a weight matrix\n\tkfMeas.W = (1 / kfMeas.R.diagonal().array()).matrix();\t\t//todo, aaron straight inversion?\n\n\tif (kfMeas.R.rows() < kfState.x.rows())\n\t{\n\t\ttrace << std::endl << \"INSUFFICIENT MEASUREMENTS FOR LEAST SQUARES \" << kfMeas.R.rows() <<  \" \" << kfState.x.rows();\n\t\treturn 0;\n\t}\n\n\tauto& H = kfMeas.A;\n\tauto& W = kfMeas.W;\n\tauto& Y = kfMeas.Y;\n\n\t//calculate least squares solution\n\tMatrixXd H_W\t= H.transpose() * W.asDiagonal();\n\tMatrixXd Q\t\t= H_W * H;\n\n\ttrace << std::endl << \" -------DOING LS --------\"<< std::endl;\n\n\tMatrixXd Qinv = Q.inverse();\n\tVectorXd x1 = Qinv * H_W * Y;\n\n\tbool error = x1.array().isNaN().any();\n\tif (error)\n\t{\n\t\tstd::cout << \"NAN found. Exiting...\";\n\t\tstd::cout\t<< std::endl\n\t\t<< x1\t\t<< std::endl\n\t\t<< Qinv\t\t<< std::endl\n\t\t<< Q\t\t<< std::endl;\n\n\t\texit(0);\n\t}\n\n// \tstd::cout << std::endl << \"postLSQ\" << std::endl;\n\n\tchiQCPass = kfState.chiQC(trace, kfMeas, x1);\n\tif (chiQCPass == false)\n\t{\n// \t\treturn 0;\t//todo aaron\n\t}\n\n\t//copy results to outputs\n\tfor (int i = 0; i < kfState.x.rows(); i++)\n\t{\n\t\tif (kfState.P(i,i) == 0)\n\t\t{\n\t\t\tkfState.P(i,i)\t= Qinv(i,i);\n\t\t\tkfState.x(i)\t= x1(i);\n\t\t}\n\t}\n\n\ttrace << std::endl << \" -------STOPPING LS --------\"<< std::endl;\n\treturn 1;\n}\n\n//todo aaron, remove tgap, add time to filter\n\n/** Least squares estimator for new kalman filter states.\n* If new states have been added that do not contain variance values, the filter will assume that these states values and covariances should be\n* estimated using least squares.\n*\n* This function will extract the minimum required states from the existing state vector,\n* and the minimum required measurements in order to perform least squares for the uninitialised states.\n*/\nvoid KFState::leastSquareInitStates(\n\tTrace&\t\t\ttrace,\t\t\t\t///< [in]\t\tTrace file for output\n\tKFMeas&\t\t\tkfMeas,\t\t\t\t///< [in]\t\tMeasurement object\n\tbool\t\t\tinitCovars,\t\t\t///< [in]\t\tOption to also initialise off-diagonal covariance values\n\tVectorXd*\t\tdx,\t\t\t\t\t///< [out]\t\tOptional output of state deltas\n\tbool\t\t\tinnovReady)\t\t\t///< [in]\t\tPerform conversion between V & Y\t\t\n{\n\tchiQCPass = false;\n\n\tif (innovReady)\n\t{\n\t\tkfMeas.Y = kfMeas.V;\n\t}\n\t\n\tvector<int> newStateIndicies;\n\n\t//find all the states that aren't initialised, they need least squaring.\n\tfor (auto& [key, i] : kfIndexMap)\n\t{\n\t\tif\t( (key.type != KF::ONE)\n\t\t\t&&(P(i,i) == 0))\n\t\t{\n\t\t\t//this is a new state and needs to be evaluated using least squares\n\t\t\tnewStateIndicies.push_back(i);\n\t\t}\n\t}\n\n\t//get the subset of the measurement matrix that applies to the uninitialised states\n\tauto subsetA = kfMeas.A(all, newStateIndicies);\n\n\t//find the subset of measurements that are required for the initialisation\n\tauto usedMeas = subsetA.rowwise().any();\n\n\tmap<int, bool> pseudoMeasStates;\n\tvector<int> leastSquareMeasIndicies;\n\n\tfor (int meas = 0; meas < usedMeas.rows(); meas++)\n\t{\n\t\t//if not used, dont worry about it\n\t\tif (usedMeas(meas) == 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t//this measurement is used to calculate a new state.\n\t\t//copy it to a new design matrix\n\t\tleastSquareMeasIndicies.push_back(meas);\n\n\t\t//remember make a pseudo measurement of anything it references that is already set\n\t\tfor (int state = 0; state < kfMeas.A.cols(); state++)\n\t\t{\n\t\t\tif\t( (kfMeas.A(meas, state)\t!= 0)\n\t\t\t\t&&(P(state,state)\t\t\t!= 0))\n\t\t\t{\n\t\t\t\tpseudoMeasStates[state] = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tint newMeasCount = leastSquareMeasIndicies.size() + pseudoMeasStates.size();\n\n\t//Create new measurement objects with larger size, (using all states for now)\n\tKFMeas\tleastSquareMeas;\n\n\tleastSquareMeas.Y = VectorXd::Zero(newMeasCount);\n\tleastSquareMeas.R = MatrixXd::Zero(newMeasCount, newMeasCount);\n\tleastSquareMeas.A = MatrixXd::Zero(newMeasCount, kfMeas.A.cols());\n\n\tint measCount = leastSquareMeasIndicies.size();\n\n\t//copy in the required measurements from the old set\n\tleastSquareMeas.Y.head\t\t(measCount)\t\t= kfMeas.Y(leastSquareMeasIndicies);\n\tleastSquareMeas.R.topLeftCorner\t(measCount, measCount)\t= kfMeas.R(leastSquareMeasIndicies, leastSquareMeasIndicies);\n\tleastSquareMeas.A.topRows\t(measCount)\t\t= kfMeas.A(leastSquareMeasIndicies, all);\n\n\t//append any new pseudo measurements to the end\n\tfor (auto& [state, boool] : pseudoMeasStates)\n\t{\n\t\tleastSquareMeas.Y(measCount)\t\t\t\t= x(state);\n\t\tleastSquareMeas.R(measCount, measCount)\t\t= P(state, state);\n\t\tleastSquareMeas.A(measCount, state)\t\t\t= 1;\n\t\tmeasCount++;\n\t}\n\n\t//find the subset of states required for these measurements\n\tvector<int> usedCols;\n\tauto usedStates = leastSquareMeas.A.colwise().any();\n\tfor (int i = 0; i < usedStates.cols(); i++)\n\t{\n\t\tif (usedStates(i) != 0)\n\t\t{\n\t\t\tusedCols.push_back(i);\n\t\t}\n\t}\n\n\t//create a new meaurement object using only the required states.\n\tKFMeas\tleastSquareMeasSubs;\n\tleastSquareMeasSubs.Y = leastSquareMeas.Y;\n\tleastSquareMeasSubs.R = leastSquareMeas.R;\n\tleastSquareMeasSubs.A = leastSquareMeas.A(all, usedCols);\n\n\t//invert measurement noise matrix to get a weight matrix\n\tleastSquareMeasSubs.W = (1 / leastSquareMeasSubs.R.diagonal().array()).matrix();//todo aaron straight inversion?\n\n\tVectorXd w = (1 / leastSquareMeasSubs.R.diagonal().array()).matrix().col(0);\t//todo aaron straight inversion?\n\n\tfor (int i = 0; i < w.rows(); i++)\n\t{\n\t\tif (std::isinf(w(i)))\n\t\t{\n\t\t\tw(i) = 0;\n\t\t}\n\t}\n\n\tif\t( leastSquareMeasSubs.A.cols() == 0\n\t\t||leastSquareMeasSubs.A.rows() == 0)\n\t{\n\t\ttrace << std::endl << \"EMPTY DESIGN MATRIX DURING LEAST SQUARES\";\n\t\treturn;\n\t}\n\n\tif (leastSquareMeasSubs.R.rows() < leastSquareMeasSubs.A.cols())\n\t{\n\t\ttrace << std::endl << \"INSUFFICIENT MEASUREMENTS FOR LEAST SQUARES \" << leastSquareMeasSubs.R.rows() <<  \" \" << x.rows();\n\t\treturn;\n\t}\n\tauto& H = leastSquareMeasSubs.A;\n\tauto& Y = leastSquareMeasSubs.Y;\n\n\t//calculate least squares solution\n\tMatrixXd W\t\t= w.asDiagonal();\n\tMatrixXd H_W\t= H.transpose() * W;\n\tMatrixXd Q\t\t= H_W * H;\n\n\tMatrixXd Qinv\t= Q.inverse();\n\tVectorXd x1\t\t= Qinv * H_W * Y;\n\n// \tstd::cout << \"Q : \" << std::endl << Q;\n\tbool error = x1.array().isNaN().any();\n\tif (error)\n\t{\n\t\tstd::cout << std::endl << \"x1:\" << std::endl << x1 << std::endl;\n\t\tstd::cout << std::endl << \"w :\" << std::endl << w << std::endl;\n\t\tstd::cout << std::endl << \"H :\" << std::endl << H << std::endl;\n\t\tstd::cout << std::endl << \"P :\" << std::endl << P << std::endl;\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"NAN found. Exiting....\";\n\t\tstd::cout\t<< std::endl;\n\n\t\texit(-1);\n\t}\n\n// \tstd::cout << std::endl << \"postLSQ\" << std::endl;\n\tchiQCPass = chiQC(trace, leastSquareMeasSubs, x1);\n\tif (chiQCPass == false)\n\t{\n// \t\treturn 1;\t//todo aaron\n\t}\n\n\tif (dx)\n\t{\n\t\t(*dx) = x1;\n\t}\n\n\tfor (int i = 0; i < usedCols.size(); i++)\n\t{\n\t\tint stateRowIndex = usedCols[i];\n\n\t\tif (P(stateRowIndex, stateRowIndex) != 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble newStateVal = x1(i);\n\t\tdouble newStateCov = Qinv(i,i);\n\n\t\tif (dx)\n\t\t{\n\t\t\tx(stateRowIndex)\t\t\t\t+=\tnewStateVal;\n\t\t\tP(stateRowIndex,stateRowIndex)\t=\tnewStateCov;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tx(stateRowIndex)\t\t\t\t= newStateVal;\n\t\t\tP(stateRowIndex,stateRowIndex)\t= newStateCov;\n\t\t}\n\n\n\t\tif (initCovars)\n\t\t{\n\t\t\tfor (int j = 0; j < i; j++)\n\t\t\t{\n\t\t\t\tint stateColIndex = usedCols[j];\n\n\t\t\t\tnewStateCov = Qinv(i,j);\n\n\t\t\t\tP(stateRowIndex,stateColIndex)\t= newStateCov;\n\t\t\t\tP(stateColIndex,stateRowIndex)\t= newStateCov;\n\t\t\t}\n\t\t}\n\t}\n}\nvoid KFState::leastSquareInitStatesA(\n\tTrace&\t\t\ttrace,\t\t\t\t///< [in]\t\tTrace file for output\n\tKFMeas&\t\t\tkfMeas,\t\t\t\t///< [in]\t\tMeasurement object\n\tbool\t\t\tinitCovars,\t\t\t///< [in]\t\tOption to also initialise off-diagonal covariance values\n\tVectorXd*\t\tdx,\t\t\t\t\t///< [out]\t\tOptional output of state deltas\n\tbool\t\t\tinnovReady)\t\t\t///< [in]\t\tPerform conversion between V & Y\t\t\n{\n\tchiQCPass = false;\n\n\tif (innovReady)\n\t{\n\t\tkfMeas.Y = kfMeas.V;\n\t}\n\t\n\tvector<int> newStateIndicies;\n\n\t//find all the states that aren't initialised, they need least squaring.\n\tfor (auto& [key, i] : kfIndexMap)\n\t{\n\t\tif\t( (key.type != KF::ONE)\n\t\t\t&&(P(i,i) == 0))\n\t\t{\n\t\t\t//this is a new state and needs to be evaluated using least squares\n\t\t\tnewStateIndicies.push_back(i);\n\t\t}\n\t}\n\n\t//get the subset of the measurement matrix that applies to the uninitialised states\n\tauto subsetA = kfMeas.A(all, newStateIndicies);\n\n\t//find the subset of measurements that are required for the initialisation\n\tauto usedMeas = subsetA.rowwise().any();\n\n\tmap<int, bool> pseudoMeasStates;\n\tvector<int> leastSquareMeasIndicies;\n\n\tfor (int meas = 0; meas < usedMeas.rows(); meas++)\n\t{\n\t\t//if not used, dont worry about it\n\t\tif (usedMeas(meas) == 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t//this measurement is used to calculate a new state.\n\t\t//copy it to a new design matrix\n\t\tleastSquareMeasIndicies.push_back(meas);\n\t}\n\n\t//Create new measurement objects with larger size, (using all states for now)\n\t//copy in the required measurements from the old set\n\tKFMeas\tleastSquareMeas;\n\tleastSquareMeas.Y\t= kfMeas.Y(leastSquareMeasIndicies);\n\tleastSquareMeas.V\t= kfMeas.V(leastSquareMeasIndicies);\n\tleastSquareMeas.R\t= kfMeas.R(leastSquareMeasIndicies, leastSquareMeasIndicies);\n\tleastSquareMeas.A\t= kfMeas.A(leastSquareMeasIndicies, all);\n\n\t//invert measurement noise matrix to get a weight matrix\n\tleastSquareMeas.W = (1 / leastSquareMeas.R.diagonal().array()).matrix();\t\t//todo aaron straight inversion?\n\n\tVectorXd w = (1 / leastSquareMeas.R.diagonal().array()).matrix().col(0);\t//todo aaron straight inversion?\n\n\tfor (int i = 0; i < w.rows(); i++)\n\t{\n\t\tif (std::isinf(w(i)))\n\t\t{\n\t\t\tw(i) = 0;\n\t\t}\n\t}\n\n\tif (leastSquareMeas.R.rows() < leastSquareMeas.A.cols())\n\t{\n\t\ttrace << std::endl << \"INSUFFICIENT MEASUREMENTS FOR LEAST SQUARES \" << leastSquareMeas.R.rows() <<  \" \" << x.rows();\n\t\ttrace << std::endl << \"Setting variances to large initial values \";;\n\t\tfor (int i = 0; i < newStateIndicies.size(); i++)\n\t\t{\n\t\t\tint index = newStateIndicies[i];\n\n\t\t\tP(index, index) = SQR(10000);\n\t\t}\n\t\t\t\n\t\treturn;\n\t}\n\tauto& H = leastSquareMeas.A;\n\tauto& Y = leastSquareMeas.Y;\n\n\t//calculate least squares solution\n\tMatrixXd W\t\t= w.asDiagonal();\n\tMatrixXd H_W\t= H.transpose() * W;\n\tMatrixXd Q\t\t= H_W * H;\n\n\tMatrixXd Qinv\t= Q.inverse();\n\tVectorXd x1\t\t= Qinv * H_W * Y;\n\n// \tstd::cout << \"Q : \" << std::endl << Q;\n\tbool error = x1.array().isNaN().any();\n\tif (error)\n\t{\n\t\tstd::cout << std::endl << \"x1:\" << std::endl << x1 << std::endl;\n\t\tstd::cout << std::endl << \"w :\" << std::endl << w << std::endl;\n\t\tstd::cout << std::endl << \"H :\" << std::endl << H << std::endl;\n\t\tstd::cout << std::endl << \"P :\" << std::endl << P << std::endl;\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"NAN found. Exiting....\";\n\t\tstd::cout\t<< std::endl;\n\n\t\texit(-1);\n\t}\n\n// \tstd::cout << std::endl << \"postLSQ\" << std::endl;\n\tchiQCPass = chiQC(trace, leastSquareMeas, x1);\n\tif (chiQCPass == false)\n\t{\n// \t\treturn 1;\t//todo aaron\n\t}\n\n\tif (dx)\n\t{\n\t\t(*dx) = x1;\n\t}\n\n\tfor (int i = 0; i < newStateIndicies.size(); i++)\n\t{\n\t\tint stateRowIndex = newStateIndicies[i];\n\n\t\tif (P(stateRowIndex, stateRowIndex) != 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble newStateVal = x1(i);\n\t\tdouble newStateCov = Qinv(i,i);\n\n\t\tif (dx)\n\t\t{\n\t\t\tx(stateRowIndex)\t\t\t\t+=\tnewStateVal;\n\t\t\tP(stateRowIndex,stateRowIndex)\t=\tnewStateCov;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tx(stateRowIndex)\t\t\t\t= newStateVal;\n\t\t\tP(stateRowIndex,stateRowIndex)\t= newStateCov;\n\t\t}\n\n\t\tif (initCovars)\n\t\t{\n\t\t\tfor (int j = 0; j < i; j++)\n\t\t\t{\n\t\t\t\tint stateColIndex = newStateIndicies[j];\n\n\t\t\t\tnewStateCov = Qinv(i,j);\n\n\t\t\t\tP(stateRowIndex,stateColIndex)\t= newStateCov;\n\t\t\t\tP(stateColIndex,stateRowIndex)\t= newStateCov;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Get a portion of the state vector by passing a list of keys\n*/\nVectorXd KFState::getSubState(\n\tmap<KFKey, int>&\tkfKeyMap,\t///< List of keys to return within substate\n\tMatrixXd*\t\t\tcovarMat)\t///< Optional pointer to a matrix for output of covariance submatrix\n{\n\tvector<int> indices;\n\tindices.resize(kfKeyMap.size());\n\n\tfor (auto& [kfKey, mapIndex] : kfKeyMap)\n\t{\n\t\tint stateIndex = getKFIndex(kfKey);\n\t\tif (stateIndex >= 0)\n\t\t{\n\t\t\tindices[mapIndex] = stateIndex;\n\t\t}\n\t}\n\n\tVectorXd subState = x(indices);\n\tif (covarMat)\n\t{\n\t\t*covarMat = P(indices, indices);\n\t}\n\treturn subState;\n}\n\n/** Output keys and states in human readable format\n*/\nvoid KFState::outputStates(\n\t\tTrace&\t\ttrace,\t///< Trace to output to\n\t\tint\t\t\tbegX,\t///< Index of first state element to process\n\t\tint\t\t\tnumX)   ///< Number of state elements to process\n{\n\ttracepdeex(2, trace, \"\\n\\n\");\n\n\ttrace << std::endl << \"+ States\" << std::endl;\n\t\n\ttracepdeex(2, trace, \"#\\t%19s\\t%20s\\t%5s\\t%3s\\t%3s\\t%13s\\t%16s\\t%10s\\n\", \"Time\", \"Type\", \"Str\", \"Sat\", \"Num\", \"State\", \"Variance\", \"Adjust\");\n\n\tint endX;\n\tif (numX < 0)\tendX = x.rows();\n\telse\t\t\tendX = begX + numX;\n\t\n\tfor (auto& [key, index] : kfIndexMap)\n\t{\n\t\tif (index >= x.rows())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif\t( index <  begX\n\t\t\t||index >= endX)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble _x\t= x(index);\n\t\tdouble _dx = 0;\n\t\tif (index < dx.rows())\n\t\t\t_dx = dx(index);\n\t\tdouble _p\t= P(index, index);\n\t\tstring type\t= KF::_from_integral(key.type)._to_string();\n\n\t\ttracepdeex(2, trace, \"*\\t%19s\\t%20s\\t%5s\\t%3s\\t%3d\\t%13.4f\\t%16.9f\\t%10.3f\\n\", time.to_string(0).c_str(), type.c_str(), key.str.c_str(), key.Sat.id().c_str(), key.num, _x, _p, _dx);\n\t}\n\ttrace << \"- States\" << std::endl;\n}\n\nvoid KFState::outputCorrelations(\n\t\t\tTrace&\t\ttrace)\n{\n\ttracepdeex(2, trace, \"\\n\\n\");\n\n\ttrace << std::endl << \"+ Correlations\" << std::endl;\n\t\n\tint skip = 0;\n\tfor (auto& [key, index] : kfIndexMap)\n\t{\n\t\tif (key.type == KF::ONE)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\ttracepdeex(2, trace, \"\\n%28s\", \"\");\n\t\tfor (int i = 0; i < skip; i++)\n\t\t{\n\t\t\ttracepdeex(2, trace, \"|    \");\n\t\t}\n\t\t\n\t\ttrace << \"> \" << key;\n\t\t\n\t\tskip++;  \n\t}\n\t\n\tfor (auto& [key, index] : kfIndexMap)\n\t{\n\t\tif (key.type == KF::ONE)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\ttrace << std::endl << key << \"  \";\n\n\t\tfor (auto& [key2, index2] : kfIndexMap)\n\t\t{\n\t\t\tif (key2.type == KF::ONE)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tdouble v1\t= P(index,\tindex);\n\t\t\tdouble v2\t= P(index2, index2);\n\t\t\tdouble v12\t= P(index,\tindex2); \n\t\t\t\n\t\t\tdouble correlation = v12 / sqrt(v1 * v2) * 100;\n\t\t\t\n\t\t\tif (index == index2)\ttracepdeex(2, trace, \"%4.0s \", \"\");\n\t\t\telse\t\t\t\t\ttracepdeex(2, trace, \"%4.0f \", correlation);\n\t\t\n\t\t}\n\t}\n\ttrace << std::endl << \"- Correlations\" << std::endl;\n}\n\nInitialState initialStateFromConfig(\n\tKalmanModel&\tkalmanModel,\n\tint\t\t\t\tindex)\n{\n\tInitialState init = {};\n\n\tif (index < kalmanModel.apriori_val\t.size())\t\tinit.x\t\t= \t\tkalmanModel.apriori_val\t[index];\n\telse\t\t\t\t\t\t\t\t\t\t\t\tinit.x\t\t= \t\tkalmanModel.apriori_val\t.back();\n\tif (index < kalmanModel.sigma\t\t.size())\t\tinit.P\t\t= SQR(\tkalmanModel.sigma\t\t[index]);\n\telse\t\t\t\t\t\t\t\t\t\t\t\tinit.P\t\t= SQR(\tkalmanModel.sigma\t\t.back());\n\tif (index < kalmanModel.proc_noise\t.size())\t\tinit.Q\t\t= SQR(\tkalmanModel.proc_noise\t[index]);\n\telse\t\t\t\t\t\t\t\t\t\t\t\tinit.Q\t\t= SQR(\tkalmanModel.proc_noise\t.back());\n\tif (index < kalmanModel.tau\t\t\t.size())\t\tinit.tau\t= \t\tkalmanModel.tau\t\t\t[index];\n\telse\t\t\t\t\t\t\t\t\t\t\t\tinit.tau\t= \t\tkalmanModel.tau\t\t\t.back();\n\tif (index < kalmanModel.mu\t\t\t.size())\t\tinit.mu\t\t= \t\tkalmanModel.mu\t\t\t[index];\n\telse\t\t\t\t\t\t\t\t\t\t\t\tinit.mu\t\t= \t\tkalmanModel.mu\t\t\t.back();\n\n\treturn init;\n}\n\nKFState mergeFilters(\n\tlist<KFState*>& kfStatePointerList,\n\tbool\t\t\tincludeTrop)\n{\n\tmap<KFKey, double>\t\t\t\tstateValueMap;\n\tmap<KFKey, map<KFKey, double>>\tstateCovarMap;\n\n\tfor (auto& statePointer : kfStatePointerList)\n\t{\n\t\tKFState& kfState = *statePointer;\n\n\t\tfor (auto& [key1, index1] : kfState.kfIndexMap)\n\t\t{\n\t\t\tif\t( key1.type != KF::REC_POS\n\t\t\t\t&&key1.type != KF::ONE\n\t\t\t\t&&key1.type != KF::TROP\n\t\t\t\t&&key1.type != KF::TROP_GM)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif\t(  includeTrop == false\n\t\t\t\t&&(key1.type == KF::TROP\n\t\t\t\t|| key1.type == KF::TROP_GM))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstateValueMap[key1] = kfState.x(index1);\n\n\t\t\tfor (auto& [key2, index2] : kfState.kfIndexMap)\n\t\t\t{\n\t\t\t\tif\t( key2.type != KF::REC_POS\n\t\t\t\t\t&&key2.type != KF::TROP\n\t\t\t\t\t&&key2.type != KF::TROP_GM)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif\t(  includeTrop == false\n\t\t\t\t\t&&(key2.type == KF::TROP\n\t\t\t\t\t|| key2.type == KF::TROP_GM))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (kfState.P(index1, index2) != 0)\n\t\t\t\t{\n\t\t\t\t\tstateCovarMap[key1][key2] = kfState.P(index1, index2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tKFState mergedKFState;\n\n\tmergedKFState.x\t\t= VectorXd::Zero(stateValueMap.size());\n\tmergedKFState.dx\t= VectorXd::Zero(stateValueMap.size());\n\tmergedKFState.P\t\t= MatrixXd::Zero(stateValueMap.size(), stateValueMap.size());\n\n\tint i = 0;\n\tfor (auto& [key, value] : stateValueMap)\n\t{\n\t\tmergedKFState.kfIndexMap[key]\t= i;\n\t\tmergedKFState.x(i)\t\t\t\t= value;\n\n\t\ti++;\n\t}\n\n\tfor (auto& [key1, map2]\t\t: stateCovarMap)\n\tfor (auto& [key2, value]\t: map2)\n\t{\n\t\tint index1 = mergedKFState.kfIndexMap[key1];\n\t\tint index2 = mergedKFState.kfIndexMap[key2];\n\n\t\tmergedKFState.P(index1, index2) = value;\n\t}\n\n\treturn mergedKFState;\n}\n\n/** Calculates prefit residual, returning results as a KFMeasEntryList\n* KFMeasEntryMap[ObsKey].value = prefit residual value\n* KFMeasEntryMap[ObsKey].noise = prefit residual uncertainty\n* KFMeasEntryMap[ObsKey].innov = kfMeas.V(i)\n*/\nKFMeasEntryList KFState::calcPrefitResids(\n\tTrace&\t\t\ttrace,\t\t\t\t///< [out]\tTrace file for output\n\tKFMeas&\t\t\tkfMeas)\t\t\t\t///< [in]\tMeasurement object\n{\n\tKFState& kfState = *this;\n\n\t// Calculate prefit resid & uncertainty S\n\tEigen::VectorXd PrefitResid = kfMeas.Y - kfMeas.A * kfState.x;\n\tEigen::MatrixXd S = kfMeas.A * kfState.P * kfMeas.A.transpose() + Eigen::MatrixXd(kfMeas.R.asDiagonal());\n\tint numMeas = PrefitResid.size();\n\t//assert(kfMeas.R.size() == numMeas);\n\tassert(S.rows() == numMeas);\n\tassert(S.cols() == numMeas);\n\tassert(kfMeas.V.size() == numMeas);\n\n\t// Return result within a KFMeasEntryList\n\tKFMeasEntryList kfMeasEntryList;\n\tfor (int meas=0; meas<numMeas; ++meas)\n\t{\n\t\tKFMeasEntry entry;\n\t\tentry.value = PrefitResid(meas);\n\t\t//entry.noise = kfMeas.R(meas);\n\t\tentry.noise = S(meas,meas);\n\t\tentry.innov = kfMeas.V(meas);\n\t\tentry.obsKey = kfMeas.obsKeys.at(meas);\n\t\tkfMeasEntryList.push_back(entry);\n\t}\n\treturn kfMeasEntryList;\n}\n", "meta": {"hexsha": "ecf3fd968cfb3e091a4bec365ae8304dccd83468", "size": 59347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/common/algebra.cpp", "max_stars_repo_name": "GnssTao/ginan", "max_stars_repo_head_hexsha": "b69593b584f75e03238c1c667796e2030391fbed", "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/common/algebra.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/common/algebra.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": 28.4637889688, "max_line_length": 237, "alphanum_fraction": 0.6465364719, "num_tokens": 19137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18939739985305637}}
{"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#define BOOST_TEST_MODULE pubkey_elgamal_verifiable_test\n\n#undef NDEBUG\n\n#include <string>\n#include <type_traits>\n#include <functional>\n\n#include <boost/filesystem.hpp>\n#include <filesystem>\n#include <fstream>\n#include <sstream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include <nil/crypto3/pubkey/algorithm/generate_keypair.hpp>\n#include <nil/crypto3/pubkey/algorithm/encrypt.hpp>\n#include <nil/crypto3/pubkey/algorithm/decrypt.hpp>\n#include <nil/crypto3/pubkey/algorithm/verify_encryption.hpp>\n#include <nil/crypto3/pubkey/algorithm/verify_decryption.hpp>\n#include <nil/crypto3/pubkey/algorithm/rerandomize.hpp>\n\n#include <nil/crypto3/pubkey/modes/verifiable_encryption.hpp>\n\n#include <nil/crypto3/pubkey/elgamal_verifiable.hpp>\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/curves/jubjub.hpp>\n#include <nil/crypto3/algebra/pairing/bls12.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/bls12.hpp>\n\n#include <nil/crypto3/random/algebraic_random_device.hpp>\n#include <nil/crypto3/random/algebraic_engine.hpp>\n\n#include <nil/crypto3/zk/algorithms/generate.hpp>\n\n#include <nil/crypto3/zk/snark/systems/ppzksnark/r1cs_gg_ppzksnark.hpp>\n\n#include <nil/crypto3/zk/components/voting/encrypted_input_voting.hpp>\n\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/primary_input.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/proof.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/verification_key.hpp>\n#include <nil/crypto3/marshalling/pubkey/types/elgamal_verifiable.hpp>\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::algebra;\nusing namespace nil::crypto3::zk;\nusing namespace nil::crypto3::pubkey;\nusing namespace nil::crypto3::random;\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp<FieldParams> &e) {\n    std::cout << e.data << std::endl;\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp2<FieldParams> &e) {\n    std::cout << e.data[0].data << \", \" << e.data[1].data << std::endl;\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp3<FieldParams> &e) {\n    std::cout << e.data[0].data << \", \" << e.data[1].data << \", \" << e.data[2].data << std::endl;\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const fields::detail::element_fp12_2over3over2<FieldParams> &e) {\n    os << \"[[[\" << e.data[0].data[0].data[0].data << \",\" << e.data[0].data[0].data[1].data << \"],[\"\n       << e.data[0].data[1].data[0].data << \",\" << e.data[0].data[1].data[1].data << \"],[\"\n       << e.data[0].data[2].data[0].data << \",\" << e.data[0].data[2].data[1].data << \"]],\"\n       << \"[[\" << e.data[1].data[0].data[0].data << \",\" << e.data[1].data[0].data[1].data << \"],[\"\n       << e.data[1].data[1].data[0].data << \",\" << e.data[1].data[1].data[1].data << \"],[\"\n       << e.data[1].data[2].data[0].data << \",\" << e.data[1].data[2].data[1].data << \"]]]\" << std::endl;\n}\n\ntemplate<typename CurveParams, typename Form>\nvoid print_curve_point(std::ostream &os,\n                       const curves::detail::curve_element<CurveParams, Form, curves::coordinates::affine> &p) {\n    os << \"( X: [\";\n    print_field_element(os, p.X);\n    os << \"], Y: [\";\n    print_field_element(os, p.Y);\n    os << \"] )\" << std::endl;\n}\n\ntemplate<typename CurveParams, typename Form>\nvoid print_curve_point(\n    std::ostream &os,\n    const curves::detail::curve_element<CurveParams, Form, curves::coordinates::jacobian_with_a4_0> &p) {\n    os << \"( X: [\";\n    print_field_element(os, p.X);\n    os << \"], Y: [\";\n    print_field_element(os, p.Y);\n    os << \"], Z: [\";\n    print_field_element(os, p.Z);\n    os << \"] )\" << std::endl;\n}\n\ntemplate<typename CurveParams, typename Form, typename Coordinates>\ntypename std::enable_if<std::is_same<Coordinates, curves::coordinates::projective>::value ||\n                        std::is_same<Coordinates, curves::coordinates::jacobian_with_a4_0>::value>::type\n    print_curve_point(std::ostream &os, const curves::detail::curve_element<CurveParams, Form, Coordinates> &p) {\n    os << \"( X: [\";\n    print_field_element(os, p.X);\n    os << \"], Y: [\";\n    print_field_element(os, p.Y);\n    os << \"], Z:[\";\n    print_field_element(os, p.Z);\n    os << \"] )\" << std::endl;\n}\n\nnamespace boost {\n    namespace test_tools {\n        namespace tt_detail {\n            template<typename CurveParams, typename Form, typename Coordinates>\n            struct print_log_value<curves::detail::curve_element<CurveParams, Form, Coordinates>> {\n                void operator()(std::ostream &os,\n                                curves::detail::curve_element<CurveParams, Form, Coordinates> const &p) {\n                    print_curve_point(os, p);\n                }\n            };\n\n            template<typename FieldParams>\n            struct print_log_value<typename fields::detail::element_fp<FieldParams>> {\n                void operator()(std::ostream &os, typename fields::detail::element_fp<FieldParams> const &e) {\n                    print_field_element(os, e);\n                }\n            };\n\n            template<typename FieldParams>\n            struct print_log_value<typename fields::detail::element_fp2<FieldParams>> {\n                void operator()(std::ostream &os, typename fields::detail::element_fp2<FieldParams> const &e) {\n                    print_field_element(os, e);\n                }\n            };\n\n            template<typename FieldParams>\n            struct print_log_value<typename fields::detail::element_fp12_2over3over2<FieldParams>> {\n                void operator()(std::ostream &os,\n                                typename fields::detail::element_fp12_2over3over2<FieldParams> const &e) {\n                    print_field_element(os, e);\n                }\n            };\n\n            template<template<typename, typename> class P, typename K, typename V>\n            struct print_log_value<P<K, V>> {\n                void operator()(std::ostream &, P<K, V> const &) {\n                }\n            };\n        }    // namespace tt_detail\n    }        // namespace test_tools\n}    // namespace boost\n\ntemplate<typename ValueType, std::size_t N>\ntypename std::enable_if<std::is_unsigned<ValueType>::value, std::vector<std::array<ValueType, N>>>::type\n    generate_random_data(std::size_t leaf_number) {\n    std::vector<std::array<ValueType, N>> v;\n    for (std::size_t i = 0; i < leaf_number; ++i) {\n        std::array<ValueType, N> leaf;\n        std::generate(std::begin(leaf), std::end(leaf),\n                      [&]() { return std::rand() % (std::numeric_limits<ValueType>::max() + 1); });\n        v.emplace_back(leaf);\n    }\n    return v;\n}\n\ntemplate<typename VerificationKey, typename PublicKey, typename Proof, typename PInput, typename CipherText>\nstruct marshalling_verification_data_groth16_encrypted_input {\n    using endianness = nil::marshalling::option::big_endian;\n    using proof_marshalling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_proof<nil::marshalling::field_type<endianness>, Proof>;\n    using verification_key_marshalling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_extended_verification_key<\n            nil::marshalling::field_type<endianness>, VerificationKey>;\n    using public_key_marshalling_type =\n        nil::crypto3::marshalling::types::elgamal_verifiable_public_key<nil::marshalling::field_type<endianness>,\n                                                                        PublicKey>;\n    using ct_marshalling_type = nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_encrypted_primary_input<\n        nil::marshalling::field_type<endianness>, CipherText>;\n    using pinput_marshalling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_primary_input<nil::marshalling::field_type<endianness>,\n                                                                          PInput>;\n\n    static inline std::string proof_path_str = \"proof.bin\";\n    static inline std::string vk_path_str = \"vkey.bin\";\n    static inline std::string pubkey_path_str = \"pubkey.bin\";\n    static inline std::string ct_path_str = \"ct.bin\";\n    static inline std::string unenc_pi_path_str = \"unenc_pi.bin\";\n    static inline std::string full_output_path_str = \"data_encrypted_input.bin\";\n    static inline std::string full_output_wrong_ct_path_str = \"data_encrypted_input_wrong_ct.bin\";\n\n    static inline auto proof_path = std::filesystem::path(proof_path_str);\n    static inline auto vk_path = std::filesystem::path(vk_path_str);\n    static inline auto pubkey_path = std::filesystem::path(pubkey_path_str);\n    static inline auto ct_path = std::filesystem::path(ct_path_str);\n    static inline auto unenc_pi_path = std::filesystem::path(unenc_pi_path_str);\n    static inline auto full_output_path = std::filesystem::path(full_output_path_str);\n    static inline auto full_output_wrong_ct_path = std::filesystem::path(full_output_wrong_ct_path_str);\n\n    template<typename MarshallingType, typename InputObj, typename F>\n    static std::vector<std::uint8_t> serialize_obj(const InputObj &in_obj, const std::function<F> &f) {\n        MarshallingType filled_val = f(in_obj);\n        std::vector<std::uint8_t> blob(filled_val.length());\n        auto it = std::begin(blob);\n        nil::marshalling::status_type status = filled_val.write(it, blob.size());\n        return blob;\n    }\n\n    template<typename Path, typename Blob>\n    static void write_obj(const Path &path, std::initializer_list<Blob> blobs) {\n        std::ofstream out(path, std::ios_base::binary);\n        for (const auto &blob : blobs) {\n            for (const auto b : blob) {\n                out << b;\n            }\n        }\n        out.close();\n    }\n\n    static void write_data(const VerificationKey &vk, const PublicKey &pubkey, const Proof &proof, const PInput &pinput,\n                           const CipherText &ct) {\n        auto proof_blob = serialize_obj<proof_marshalling_type>(\n            proof, std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_proof<Proof, endianness>));\n        write_obj(proof_path, {proof_blob});\n\n        auto vk_blob = serialize_obj<verification_key_marshalling_type>(\n            vk, std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_verification_key<VerificationKey,\n                                                                                                        endianness>));\n        write_obj(vk_path, {vk_blob});\n\n        auto pubkey_blob = serialize_obj<public_key_marshalling_type>(\n            pubkey, std::function(nil::crypto3::marshalling::types::fill_public_key<PublicKey, endianness>));\n        write_obj(pubkey_path, {pubkey_blob});\n\n        auto pinput_blob = serialize_obj<pinput_marshalling_type>(\n            pinput,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<PInput, endianness>));\n        write_obj(unenc_pi_path, {pinput_blob});\n\n        auto ct_blob = serialize_obj<ct_marshalling_type>(\n            ct,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_encrypted_primary_input<CipherText,\n                                                                                                 endianness>));\n        write_obj(ct_path, {ct_blob});\n\n        nil::crypto3::random::algebraic_random_device<\n            typename std::iterator_traits<typename CipherText::iterator>::value_type::group_type>\n            d;\n        auto ct_wrong = ct;\n        ct_wrong[std::rand() % ct.size()] = d();\n        auto ct_wrong_blob = serialize_obj<ct_marshalling_type>(\n            ct_wrong,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_encrypted_primary_input<CipherText,\n                                                                                                 endianness>));\n\n        write_obj(full_output_path, {proof_blob, vk_blob, pubkey_blob, ct_blob, pinput_blob});\n        write_obj(full_output_wrong_ct_path, {proof_blob, vk_blob, pubkey_blob, ct_wrong_blob, pinput_blob});\n    }\n\n    template<typename ReturnType, typename MarshallingType, typename Path, typename F>\n    static ReturnType read_obj(const Path &path, const std::function<F> &f) {\n        std::ifstream in(path, std::ios_base::binary);\n        std::stringstream buffer;\n        buffer << in.rdbuf();\n        auto blob_str = buffer.str();\n        std::vector<std::uint8_t> blob(std::cbegin(blob_str), std::cend(blob_str));\n\n        MarshallingType marshalling_obj;\n        auto it = std::cbegin(blob);\n        nil::marshalling::status_type status = marshalling_obj.read(it, blob.size());\n        return f(marshalling_obj);\n    }\n\n    static std::tuple<Proof, VerificationKey, PublicKey, PInput, CipherText> read_data() {\n        Proof proof = read_obj<Proof, proof_marshalling_type>(\n            proof_path,\n            std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_proof<Proof, endianness>));\n        VerificationKey vk = read_obj<VerificationKey, verification_key_marshalling_type>(\n            vk_path,\n            std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_verification_key<VerificationKey,\n                                                                                                    endianness>));\n        PublicKey pubkey = read_obj<PublicKey, public_key_marshalling_type>(\n            pubkey_path, std::function(nil::crypto3::marshalling::types::make_public_key<PublicKey, endianness>));\n        PInput pinput = read_obj<PInput, pinput_marshalling_type>(\n            unenc_pi_path,\n            std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_primary_input<PInput, endianness>));\n        CipherText ct = read_obj<CipherText, ct_marshalling_type>(\n            ct_path,\n            std::function(\n                nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_encrypted_primary_input<CipherText,\n                                                                                                 endianness>));\n\n        return std::tuple {proof, vk, pubkey, pinput, ct};\n    }\n};\n\nstruct test_policy {\n    using pairing_curve_type = curves::bls12_381;\n    using curve_type = curves::jubjub;\n    using base_points_generator_hash_type = hashes::sha2<256>;\n    using hash_params = hashes::find_group_hash_default_params;\n    using hash_component = components::pedersen<curve_type, base_points_generator_hash_type, hash_params>;\n    using hash_type = typename hash_component::hash_type;\n    using merkle_hash_component = hash_component;\n    using merkle_hash_type = typename merkle_hash_component::hash_type;\n    using field_type = typename hash_component::field_type;\n    static constexpr std::size_t arity = 2;\n    static constexpr std::size_t tree_depth = 1;\n    using voting_component =\n        components::encrypted_input_voting<arity, hash_component, merkle_hash_component, field_type>;\n    using merkle_proof_component = typename voting_component::merkle_proof_component;\n    using encryption_scheme = elgamal_verifiable<pairing_curve_type>;\n    using proof_system = typename encryption_scheme::proof_system_type;\n    using marshalling_data_type = marshalling_verification_data_groth16_encrypted_input<\n        typename proof_system::verification_key_type, typename encryption_scheme::public_key_type,\n        typename proof_system::proof_type, typename proof_system::primary_input_type,\n        typename encryption_scheme::cipher_type::first_type>;\n};\n\nBOOST_AUTO_TEST_SUITE(pubkey_elgamal_verifiable_test_suite)\n\nBOOST_AUTO_TEST_CASE(elgamal_verifiable_auto_test) {\n    /* prepare test */\n    constexpr std::size_t participants_number = 1 << test_policy::tree_depth;\n    auto secret_keys = generate_random_data<bool, test_policy::hash_type::digest_bits>(participants_number);\n    std::vector<std::array<bool, test_policy::hash_type::digest_bits>> public_keys;\n    for (const auto &sk : secret_keys) {\n        std::array<bool, test_policy::hash_type::digest_bits> pk {};\n        hash<test_policy::merkle_hash_type>(sk, std::begin(pk));\n        public_keys.emplace_back(pk);\n    }\n    containers::merkle_tree<test_policy::merkle_hash_type, test_policy::arity> tree(public_keys.begin(),\n                                                                                    public_keys.end());\n    std::size_t proof_idx = std::rand() % participants_number;\n    containers::merkle_proof<test_policy::merkle_hash_type, test_policy::arity> proof(tree, proof_idx);\n    auto tree_pk_leaf = tree[proof_idx];\n\n    std::vector<bool> m = {0, 1, 0, 0, 0, 0, 0};\n    std::vector<typename test_policy::pairing_curve_type::scalar_field_type::value_type> m_field;\n    for (const auto m_i : m) {\n        m_field.emplace_back(std::size_t(m_i));\n    }\n\n    const std::size_t eid_size = 64;\n    std::vector<bool> eid(eid_size);\n    std::generate(eid.begin(), eid.end(), [&]() { return std::rand() % 2; });\n\n    std::vector<bool> eid_sk;\n    std::copy(std::cbegin(eid), std::cend(eid), std::back_inserter(eid_sk));\n    std::copy(std::cbegin(secret_keys[proof_idx]), std::cend(secret_keys[proof_idx]), std::back_inserter(eid_sk));\n    std::vector<bool> sn = hash<test_policy::hash_type>(eid_sk);\n\n    components::blueprint<test_policy::field_type> bp;\n    components::block_variable<test_policy::field_type> m_block(bp, m.size());\n    components::block_variable<test_policy::field_type> eid_block(bp, eid.size());\n    components::digest_variable<test_policy::field_type> sn_digest(bp, test_policy::hash_component::digest_bits);\n    components::digest_variable<test_policy::field_type> root_digest(bp,\n                                                                     test_policy::merkle_hash_component::digest_bits);\n    components::blueprint_variable_vector<test_policy::field_type> address_bits_va;\n    address_bits_va.allocate(bp, test_policy::tree_depth);\n    test_policy::merkle_proof_component path_var(bp, test_policy::tree_depth);\n    components::block_variable<test_policy::field_type> sk_block(bp, secret_keys[proof_idx].size());\n    test_policy::voting_component vote_var(bp, m_block, eid_block, sn_digest, root_digest, address_bits_va, path_var,\n                                           sk_block, components::blueprint_variable<test_policy::field_type>(0));\n\n    path_var.generate_r1cs_constraints();\n    vote_var.generate_r1cs_constraints();\n\n    BOOST_CHECK(!bp.is_satisfied());\n    path_var.generate_r1cs_witness(proof);\n    BOOST_CHECK(!bp.is_satisfied());\n    address_bits_va.fill_with_bits_of_ulong(bp, path_var.address);\n    BOOST_CHECK(!bp.is_satisfied());\n    auto address = path_var.address;\n    BOOST_CHECK(address_bits_va.get_field_element_from_bits(bp) == path_var.address);\n    m_block.generate_r1cs_witness(m);\n    BOOST_CHECK(!bp.is_satisfied());\n    eid_block.generate_r1cs_witness(eid);\n    BOOST_CHECK(!bp.is_satisfied());\n    sk_block.generate_r1cs_witness(secret_keys[proof_idx]);\n    BOOST_CHECK(!bp.is_satisfied());\n    vote_var.generate_r1cs_witness(tree.root(), sn);\n    BOOST_CHECK(bp.is_satisfied());\n\n    std::cout << \"Constraints number: \" << bp.num_constraints() << std::endl;\n\n    bp.set_input_sizes(vote_var.get_input_size());\n\n    typename test_policy::proof_system::keypair_type gg_keypair =\n        generate<test_policy::proof_system>(bp.get_constraint_system());\n\n    algebraic_random_device<typename test_policy::pairing_curve_type::scalar_field_type> d;\n    std::vector<typename test_policy::pairing_curve_type::scalar_field_type::value_type> rnd;\n    for (std::size_t i = 0; i < m.size() * 3 + 2; ++i) {\n        rnd.emplace_back(d());\n    }\n    typename test_policy::encryption_scheme::keypair_type keypair =\n        generate_keypair<test_policy::encryption_scheme, modes::verifiable_encryption<test_policy::encryption_scheme>>(\n            rnd, {gg_keypair, m.size()});\n\n    typename test_policy::encryption_scheme::cipher_type cipher_text =\n        encrypt<test_policy::encryption_scheme, modes::verifiable_encryption<test_policy::encryption_scheme>>(\n            m_field, {d(), std::get<0>(keypair), gg_keypair, bp.primary_input(), bp.auxiliary_input()});\n\n    typename test_policy::proof_system::primary_input_type pinput = bp.primary_input();\n    test_policy::marshalling_data_type::write_data(\n        gg_keypair.second, std::get<0>(keypair), cipher_text.second,\n        typename test_policy::proof_system::primary_input_type {std::cbegin(pinput) + m.size(), std::cend(pinput)},\n        cipher_text.first);\n\n    typename test_policy::encryption_scheme::decipher_type decipher_text =\n        decrypt<test_policy::encryption_scheme, modes::verifiable_encryption<test_policy::encryption_scheme>>(\n            cipher_text.first, {std::get<1>(keypair), std::get<2>(keypair), gg_keypair});\n    BOOST_CHECK(decipher_text.first.size() == m_field.size());\n    for (std::size_t i = 0; i < m_field.size(); ++i) {\n        BOOST_CHECK(decipher_text.first[i] == m_field[i]);\n    }\n\n    bool enc_verification_ans = verify_encryption<test_policy::encryption_scheme>(\n        cipher_text.first,\n        {std::get<0>(keypair), gg_keypair.second, cipher_text.second,\n         typename test_policy::proof_system::primary_input_type {std::cbegin(pinput) + m.size(), std::cend(pinput)}});\n    BOOST_CHECK(enc_verification_ans);\n\n    bool dec_verification_ans = verify_decryption<test_policy::encryption_scheme>(\n        cipher_text.first, decipher_text.first, {std::get<2>(keypair), gg_keypair, decipher_text.second});\n    BOOST_CHECK(dec_verification_ans);\n\n    /// Rerandomized cipher text\n    std::vector<typename test_policy::pairing_curve_type::scalar_field_type::value_type> rnd_rerandomization;\n    for (std::size_t i = 0; i < 3; ++i) {\n        rnd_rerandomization.emplace_back(d());\n    }\n    typename test_policy::encryption_scheme::cipher_type rerand_cipher_text =\n        rerandomize<test_policy::encryption_scheme>(rnd_rerandomization, cipher_text.first,\n                                                    {std::get<0>(keypair), gg_keypair, cipher_text.second});\n\n    /// Decryption of the rerandomized cipher text\n    typename test_policy::encryption_scheme::decipher_type decipher_rerand_text =\n        decrypt<test_policy::encryption_scheme, modes::verifiable_encryption<test_policy::encryption_scheme>>(\n            rerand_cipher_text.first, {std::get<1>(keypair), std::get<2>(keypair), gg_keypair});\n    BOOST_CHECK(decipher_rerand_text.first.size() == m_field.size());\n    for (std::size_t i = 0; i < m_field.size(); ++i) {\n        BOOST_CHECK(decipher_rerand_text.first[i] == m_field[i]);\n    }\n\n    /// Encryption verification of the rerandomized cipher text\n    enc_verification_ans = verify_encryption<test_policy::encryption_scheme>(\n        rerand_cipher_text.first,\n        {std::get<0>(keypair), gg_keypair.second, rerand_cipher_text.second,\n         typename test_policy::proof_system::primary_input_type {std::cbegin(pinput) + m.size(), std::cend(pinput)}});\n    BOOST_CHECK(enc_verification_ans);\n\n    /// Decryption verification of the rerandomized cipher text\n    dec_verification_ans = verify_decryption<test_policy::encryption_scheme>(\n        rerand_cipher_text.first, decipher_rerand_text.first,\n        {std::get<2>(keypair), gg_keypair, decipher_rerand_text.second});\n    BOOST_CHECK(dec_verification_ans);\n\n    // TODO: add status return\n    // /// False-positive tests\n    // auto cipher_text_wrong = cipher_text.first;\n    // for (auto & c: cipher_text_wrong) {\n    //     c = c + std::iterator_traits<typename decltype(cipher_text.first)::iterator>::value_type::one();\n    // }\n    // typename encryption_scheme::decipher_type decipher_text_wrong =\n    //     decrypt<encryption_scheme, modes::verifiable_encryption<encryption_scheme>>(\n    //         cipher_text_wrong, {std::get<1>(keypair), std::get<2>(keypair), gg_keypair});\n    // BOOST_CHECK(decipher_text.first.size() == m_field.size());\n    // bool wrong_decryption_ans = true;\n    // for (std::size_t i = 0; i < m_field.size(); ++i) {\n    //     wrong_decryption_ans &= (decipher_text.first[i] == m_field[i]);\n    // }\n    // BOOST_CHECK(!wrong_decryption_ans);\n}\n\nBOOST_AUTO_TEST_CASE(elgamal_verifiable_restored_test) {\n    auto [proof, vk, pubkey, pinput, ct] = test_policy::marshalling_data_type::read_data();\n\n    bool enc_verification_ans = verify_encryption<test_policy::encryption_scheme>(ct, {pubkey, vk, proof, pinput});\n    BOOST_CHECK(enc_verification_ans);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "518aa63cc11912b9345917a54ada72643b11a2c7", "size": 26153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/elgamal_verifiable.cpp", "max_stars_repo_name": "NilFoundation/pubkey", "max_stars_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "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/elgamal_verifiable.cpp", "max_issues_repo_name": "NilFoundation/pubkey", "max_issues_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_issues_repo_licenses": ["MIT"], "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/elgamal_verifiable.cpp", "max_forks_repo_name": "NilFoundation/pubkey", "max_forks_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.6841085271, "max_line_length": 120, "alphanum_fraction": 0.674989485, "num_tokens": 6209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18939739482348916}}
{"text": "// This file automatically generated by create_export_module.py\n#define NO_IMPORT_ARRAY \n\n#include <NumpyEigenConverter.hpp>\n\n#include <boost/cstdint.hpp>\n\n\nvoid import_D_D_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, Eigen::Dynamic, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_D_1_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, Eigen::Dynamic, 1 > >::register_converter();\n}\n\nvoid import_D_2_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, Eigen::Dynamic, 2 > >::register_converter();\n}\n\nvoid import_D_3_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, Eigen::Dynamic, 3 > >::register_converter();\n}\n\nvoid import_D_4_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, Eigen::Dynamic, 4 > >::register_converter();\n}\n\nvoid import_D_5_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, Eigen::Dynamic, 5 > >::register_converter();\n}\n\nvoid import_D_6_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, Eigen::Dynamic, 6 > >::register_converter();\n}\n\nvoid import_1_D_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 1, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_1_1_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 1, 1 > >::register_converter();\n}\n\nvoid import_1_2_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 1, 2 > >::register_converter();\n}\n\nvoid import_1_3_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 1, 3 > >::register_converter();\n}\n\nvoid import_1_4_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 1, 4 > >::register_converter();\n}\n\nvoid import_1_5_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 1, 5 > >::register_converter();\n}\n\nvoid import_1_6_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 1, 6 > >::register_converter();\n}\n\nvoid import_2_D_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 2, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_2_1_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 2, 1 > >::register_converter();\n}\n\nvoid import_2_2_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 2, 2 > >::register_converter();\n}\n\nvoid import_2_3_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 2, 3 > >::register_converter();\n}\n\nvoid import_2_4_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 2, 4 > >::register_converter();\n}\n\nvoid import_2_5_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 2, 5 > >::register_converter();\n}\n\nvoid import_2_6_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 2, 6 > >::register_converter();\n}\n\nvoid import_3_D_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 3, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_3_1_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 3, 1 > >::register_converter();\n}\n\nvoid import_3_2_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 3, 2 > >::register_converter();\n}\n\nvoid import_3_3_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 3, 3 > >::register_converter();\n}\n\nvoid import_3_4_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 3, 4 > >::register_converter();\n}\n\nvoid import_3_5_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 3, 5 > >::register_converter();\n}\n\nvoid import_3_6_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 3, 6 > >::register_converter();\n}\n\nvoid import_4_D_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 4, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_4_1_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 4, 1 > >::register_converter();\n}\n\nvoid import_4_2_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 4, 2 > >::register_converter();\n}\n\nvoid import_4_3_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 4, 3 > >::register_converter();\n}\n\nvoid import_4_4_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 4, 4 > >::register_converter();\n}\n\nvoid import_4_5_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 4, 5 > >::register_converter();\n}\n\nvoid import_4_6_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 4, 6 > >::register_converter();\n}\n\nvoid import_5_D_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 5, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_5_1_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 5, 1 > >::register_converter();\n}\n\nvoid import_5_2_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 5, 2 > >::register_converter();\n}\n\nvoid import_5_3_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 5, 3 > >::register_converter();\n}\n\nvoid import_5_4_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 5, 4 > >::register_converter();\n}\n\nvoid import_5_5_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 5, 5 > >::register_converter();\n}\n\nvoid import_5_6_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 5, 6 > >::register_converter();\n}\n\nvoid import_6_D_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 6, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_6_1_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 6, 1 > >::register_converter();\n}\n\nvoid import_6_2_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 6, 2 > >::register_converter();\n}\n\nvoid import_6_3_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 6, 3 > >::register_converter();\n}\n\nvoid import_6_4_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 6, 4 > >::register_converter();\n}\n\nvoid import_6_5_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 6, 5 > >::register_converter();\n}\n\nvoid import_6_6_int()\n{\n\tNumpyEigenConverter<Eigen::Matrix< int, 6, 6 > >::register_converter();\n}\n\n", "meta": {"hexsha": "98c7cbde4d75f279287e7b3b7d9d7aed761fb4ea", "size": 5239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "numpy_eigen/src/autogen_module/import_int.cpp", "max_stars_repo_name": "565353780/pytorch-voxblox-plus-plus", "max_stars_repo_head_hexsha": "fd319495b36651cf8c0c9244e0f664fac1afd5ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-24T11:16:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T05:14:44.000Z", "max_issues_repo_path": "numpy_eigen/src/autogen_module/import_int.cpp", "max_issues_repo_name": "565353780/pytorch-voxblox-plus-plus", "max_issues_repo_head_hexsha": "fd319495b36651cf8c0c9244e0f664fac1afd5ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-19T14:31:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T02:55:39.000Z", "max_forks_repo_path": "numpy_eigen/src/autogen_module/import_int.cpp", "max_forks_repo_name": "565353780/pytorch-voxblox-plus-plus", "max_forks_repo_head_hexsha": "fd319495b36651cf8c0c9244e0f664fac1afd5ca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-24T08:34:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T07:17:54.000Z", "avg_line_length": 20.625984252, "max_line_length": 98, "alphanum_fraction": 0.7175033403, "num_tokens": 1550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.1893838179189525}}
{"text": "#include \"VideoFaceDetector.h\"\n#include <dlib/dnn.h>\n#include <dlib/image_io.h>\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <dlib/opencv.h>\n#include <dlib/string.h>\n#include <iostream>\n//#include <nlohmann/json.hpp>\n#include <opencv2/imgproc.hpp>\n\n// using json = nlohmann::json;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\n// The next bit of code defines a ResNet network.  It's basically copied\n// and pasted from the dnn_imagenet_ex.cpp example, except we replaced the loss\n// layer with loss_metric and made the network somewhat smaller.  Go read the\n// introductory dlib DNN examples to learn what all this stuff means.\n//\n// Also, the dnn_metric_learning_on_images_ex.cpp example shows how to train\n// this network. The dlib_face_recognition_resnet_model_v1 model used by this\n// example was trained using essentially the code shown in\n// dnn_metric_learning_on_images_ex.cpp except the mini-batches were made larger\n// (35x15 instead of 5x5), the iterations without progress was set to 10000, and\n// the training dataset consisted of about 3 million images instead of\n// 55.  Also, the input layer was locked to images of size 150.\ntemplate <template <int, template <typename> class, int, typename> class block,\n          int N, template <typename> class BN, typename SUBNET>\nusing residual = add_prev1<block<N, BN, 1, tag1<SUBNET>>>;\n\ntemplate <template <int, template <typename> class, int, typename> class block,\n          int N, template <typename> class BN, typename SUBNET>\nusing residual_down =\n    add_prev2<avg_pool<2, 2, 2, 2, skip1<tag2<block<N, BN, 2, tag1<SUBNET>>>>>>;\n\ntemplate <int N, template <typename> class BN, int stride, typename SUBNET>\nusing block =\n    BN<con<N, 3, 3, 1, 1, relu<BN<con<N, 3, 3, stride, stride, SUBNET>>>>>;\n\ntemplate <int N, typename SUBNET>\nusing ares = relu<residual<block, N, affine, SUBNET>>;\ntemplate <int N, typename SUBNET>\nusing ares_down = relu<residual_down<block, N, affine, SUBNET>>;\n\ntemplate <typename SUBNET> using alevel0 = ares_down<256, SUBNET>;\ntemplate <typename SUBNET>\nusing alevel1 = ares<256, ares<256, ares_down<256, SUBNET>>>;\ntemplate <typename SUBNET>\nusing alevel2 = ares<128, ares<128, ares_down<128, SUBNET>>>;\ntemplate <typename SUBNET>\nusing alevel3 = ares<64, ares<64, ares<64, ares_down<64, SUBNET>>>>;\ntemplate <typename SUBNET> using alevel4 = ares<32, ares<32, ares<32, SUBNET>>>;\n\nusing anet_type = loss_metric<fc_no_bias<\n    128, avg_pool_everything<alevel0<alevel1<alevel2<alevel3<alevel4<max_pool<\n             3, 3, 2, 2,\n             relu<affine<con<32, 7, 7, 2, 2, input_rgb_image_sized<150>\n                             //                              input_rgb_image\n                             >>>>>>>>>>>>;\n\nstatic anet_type net;\nstatic bool initialized = false;\n\nconst double VideoFaceDetector::TICK_FREQUENCY = cv::getTickFrequency();\n\nvoid VideoFaceDetector::add_faces(const std::string &folder) {\n\n  for (auto file_name : directory(folder).get_files()) {\n    auto pos = file_name.name().find(\".jpg\");\n    if (pos == std::string::npos)\n      continue;\n    matrix<rgb_pixel> face_chip;\n    dlib::load_jpeg(face_chip, file_name);\n    auto &face_descriptor = net(face_chip);\n    if (face_descriptor.size() == face_dim) {\n      nb++;\n      copy(face_descriptor.begin(), face_descriptor.end(), back_inserter(xb));\n      std::cout << \"data\" << nb << std::endl;\n    }\n  }\n\n  // reindex\n  reindex();\n}\n\nVideoFaceDetector::VideoFaceDetector(const std::string cascadeFilePath,\n                                     cv::VideoCapture &videoCapture,\n                                     const std::string name, bool learn) {\n\n  if (!initialized) {\n    deserialize(\"dlib_face_recognition_resnet_model_v1.dat\") >> net;\n    initialized = true;\n  }\n\n  setFaceCascade(cascadeFilePath);\n  setVideoCapture(videoCapture);\n\n  m_name = name;\n\n  //  m_cli = new httplib::SSLClient(\"localhost\", 5000);\n\n  if (learn)\n    add_faces(name);\n  m_learn = learn;\n}\n\nvoid VideoFaceDetector::setVideoCapture(cv::VideoCapture &videoCapture) {\n  m_videoCapture = &videoCapture;\n}\n\ncv::VideoCapture *VideoFaceDetector::videoCapture() const {\n  return m_videoCapture;\n}\n\nvoid VideoFaceDetector::setFaceCascade(const std::string cascadeFilePath) {\n  if (m_faceCascade == nullptr) {\n    m_faceCascade = new cv::CascadeClassifier(cascadeFilePath);\n  } else {\n    m_faceCascade->load(cascadeFilePath);\n  }\n\n  if (m_faceCascade->empty()) {\n    std::cerr << \"Error creating cascade classifier. Make sure the file\"\n              << std::endl\n              << cascadeFilePath << \" exists.\" << std::endl;\n  }\n}\n\ncv::CascadeClassifier *VideoFaceDetector::faceCascade() const {\n  return m_faceCascade;\n}\n\nvoid VideoFaceDetector::setResizedWidth(const int width) {\n  m_resizedWidth = std::max(width, 1);\n}\n\nint VideoFaceDetector::resizedWidth() const { return m_resizedWidth; }\n\nbool VideoFaceDetector::isFaceFound() const { return m_foundFace; }\n\ncv::Rect VideoFaceDetector::face() const {\n  cv::Rect faceRect = m_trackedFace;\n  faceRect.x = static_cast<int>(faceRect.x / m_scale);\n  faceRect.y = static_cast<int>(faceRect.y / m_scale);\n  faceRect.width = static_cast<int>(faceRect.width / m_scale);\n  faceRect.height = static_cast<int>(faceRect.height / m_scale);\n  return faceRect;\n}\n\nstd::string VideoFaceDetector::name() const { return m_name; }\n\ncv::Point VideoFaceDetector::facePosition() const {\n  cv::Point facePos;\n  facePos.x = static_cast<int>(m_facePosition.x / m_scale);\n  facePos.y = static_cast<int>(m_facePosition.y / m_scale);\n  return facePos;\n}\n\nvoid VideoFaceDetector::setTemplateMatchingMaxDuration(const double s) {\n  m_templateMatchingMaxDuration = s;\n}\n\ndouble VideoFaceDetector::templateMatchingMaxDuration() const {\n  return m_templateMatchingMaxDuration;\n}\n\nVideoFaceDetector::~VideoFaceDetector() {\n  if (m_faceCascade != nullptr)\n    delete m_faceCascade;\n\n  //  if (m_cli != nullptr)\n  //    delete m_cli;\n\n  delete faiss_index;\n  delete quantizer;\n}\n\ncv::Rect VideoFaceDetector::doubleRectSize(const cv::Rect &inputRect,\n                                           const cv::Rect &frameSize) const {\n  cv::Rect outputRect;\n  // Double rect size\n  outputRect.width = inputRect.width * 2;\n  outputRect.height = inputRect.height * 2;\n\n  // Center rect around original center\n  outputRect.x = inputRect.x - inputRect.width / 2;\n  outputRect.y = inputRect.y - inputRect.height / 2;\n\n  // Handle edge cases\n  if (outputRect.x < frameSize.x) {\n    outputRect.width += outputRect.x;\n    outputRect.x = frameSize.x;\n  }\n  if (outputRect.y < frameSize.y) {\n    outputRect.height += outputRect.y;\n    outputRect.y = frameSize.y;\n  }\n\n  if (outputRect.x + outputRect.width > frameSize.width) {\n    outputRect.width = frameSize.width - outputRect.x;\n  }\n  if (outputRect.y + outputRect.height > frameSize.height) {\n    outputRect.height = frameSize.height - outputRect.y;\n  }\n\n  return outputRect;\n}\n\ncv::Point VideoFaceDetector::centerOfRect(const cv::Rect &rect) const {\n  return cv::Point(rect.x + rect.width / 2, rect.y + rect.height / 2);\n}\n\ncv::Rect VideoFaceDetector::biggestFace(std::vector<cv::Rect> &faces) const {\n  assert(!faces.empty());\n\n  cv::Rect *biggest = &faces[0];\n  for (auto &face : faces) {\n    if (face.area() < biggest->area())\n      biggest = &face;\n  }\n  return *biggest;\n}\n\n/*\n * Face template is small patch in the middle of detected face.\n */\ncv::Mat VideoFaceDetector::getFaceTemplate(const cv::Mat &frame,\n                                           cv::Rect face) {\n  face.x += face.width / 4;\n  face.y += face.height / 4;\n  face.width /= 2;\n  face.height /= 2;\n\n  cv::Mat faceTemplate = frame(face).clone();\n  return faceTemplate;\n}\n\nvoid VideoFaceDetector::limitRect(const cv::Mat &frame, cv::Rect &rect) {\n  if (rect.x < 0)\n    rect.x = 0;\n  if (rect.y < 0)\n    rect.y = 0;\n  if (rect.x + rect.width > frame.cols)\n    rect.width = frame.cols - rect.x;\n  if (rect.y + rect.height > frame.rows)\n    rect.height = frame.rows - rect.y;\n}\n\nfloat VideoFaceDetector::search_face_local(const std::vector<float> &xq) {\n\n  auto *I = new long[1];\n  auto *D = new float[1];\n\n  //  std::cout << \"before search\" << std::endl;\n\n  faiss_index->search(1, xq.data(), 1, D, I);\n\n  return D[0];\n}\n\nvoid VideoFaceDetector::reindex() {\n\n  if (nb < 1)\n    return;\n  if (faiss_index != nullptr) {\n    delete faiss_index;\n    delete quantizer;\n  }\n\n  quantizer = new faiss::IndexFlatL2(face_dim);\n  faiss_index = new faiss::IndexIVFFlat(quantizer, face_dim, 1);\n  faiss_index->nprobe = 1;\n\n  auto data = xb.data();\n\n  // here we specify METRIC_L2, by default it performs inner-product search\n  faiss_index->train(nb, data);\n  faiss_index->add(nb, data);\n}\n\nvoid VideoFaceDetector::searchFaceChip(const cv::Mat &chip_frame) {\n  static std::vector<float> xq(face_dim);\n\n  if (chip_frame.empty())\n    return;\n\n  //  std::cout << \"chip_frame\" << chip_frame.cols << std::endl;\n\n  //  cv::imshow(\"test\", chip_frame);\n\n  // later will be multiple face_chips as well\n  matrix<rgb_pixel> face_chip;\n  assign_image(face_chip, cv_image<bgr_pixel>(chip_frame));\n  auto &face_descriptor = net(face_chip);\n\n  if (xb.empty()) {\n    copy(face_descriptor.begin(), face_descriptor.end(), back_inserter(xb));\n    nb = 1;\n    cv::imwrite(m_name + \"/1.jpg\", chip_frame);\n    reindex();\n  } else {\n    //  json data = net(face_chip);\n\n    xq.assign(face_descriptor.begin(), face_descriptor.end());\n\n    auto conf = search_face_local(xq);\n    if (conf > 0.2f) {\n      nb++;\n      cv::imshow(\"test\", chip_frame);\n      std::cout << \"num points: \" << nb << \" confidence \" << conf << std::endl;\n      copy(face_descriptor.begin(), face_descriptor.end(), back_inserter(xb));\n      cv::imwrite(m_name + \"/\" + std::to_string(nb) + \".jpg\", chip_frame);\n      reindex();\n    }\n  }\n\n  //  auto res = m_cli->Post(\"/search_face\", data.dump(), \"application/json\");\n  //  if (res && res->status == 200) {\n  //    data = json::parse(res->body);\n  //    auto first = data[0];\n  //    if (first[\"confidence\"] > 0.8f) {\n  //      return first[\"name\"];\n  //    }\n  //  }\n\n  //  return \"unknow\";\n}\n\nvoid VideoFaceDetector::detectFaceAllSizes(const cv::Mat &frame) {\n  // Minimum face size is 1/5th of screen height\n  // Maximum face size is 2/3rds of screen height\n  m_faceCascade->detectMultiScale(\n      frame, m_allFaces, 1.1, 3, 0, cv::Size(frame.rows / 5, frame.rows / 5),\n      cv::Size(frame.rows * 2 / 3, frame.rows * 2 / 3));\n\n  if (m_allFaces.empty())\n    return;\n\n  m_foundFace = true;\n\n  // Locate biggest face\n  m_trackedFace = biggestFace(m_allFaces);\n\n  // Copy face template\n  m_faceTemplate = getFaceTemplate(frame, m_trackedFace);\n\n  // Calculate roi\n  m_faceRoi =\n      doubleRectSize(m_trackedFace, cv::Rect(0, 0, frame.cols, frame.rows));\n\n  // Update face position\n  m_facePosition = centerOfRect(m_trackedFace);\n}\n\nvoid VideoFaceDetector::detectFaceAroundRoi(const cv::Mat &frame) {\n  // Detect faces sized +/-20% off biggest face in previous search\n  m_faceCascade->detectMultiScale(\n      frame(m_faceRoi), m_allFaces, 1.1, 3, 0,\n      cv::Size(m_trackedFace.width * 8 / 10, m_trackedFace.height * 8 / 10),\n      cv::Size(m_trackedFace.width * 12 / 10, m_trackedFace.width * 12 / 10));\n\n  if (m_allFaces.empty()) {\n    // Activate template matching if not already started and start timer\n    m_templateMatchingRunning = true;\n    if (m_templateMatchingStartTime == 0)\n      m_templateMatchingStartTime = cv::getTickCount();\n    return;\n  }\n\n  // Turn off template matching if running and reset timer\n  m_templateMatchingRunning = false;\n  m_templateMatchingCurrentTime = m_templateMatchingStartTime = 0;\n\n  // Get detected face\n  m_trackedFace = biggestFace(m_allFaces);\n\n  // Add roi offset to face\n  m_trackedFace.x += m_faceRoi.x;\n  m_trackedFace.y += m_faceRoi.y;\n\n  // Get face template\n  m_faceTemplate = getFaceTemplate(frame, m_trackedFace);\n\n  // Calculate roi\n  m_faceRoi =\n      doubleRectSize(m_trackedFace, cv::Rect(0, 0, frame.cols, frame.rows));\n\n  // Update face position\n  m_facePosition = centerOfRect(m_trackedFace);\n}\n\nvoid VideoFaceDetector::detectFacesTemplateMatching(const cv::Mat &frame) {\n  // Calculate duration of template matching\n  m_templateMatchingCurrentTime = cv::getTickCount();\n  double duration = static_cast<double>(m_templateMatchingCurrentTime -\n                                        m_templateMatchingStartTime) /\n                    TICK_FREQUENCY;\n\n  // If template matching lasts for more than 2 seconds face is possibly lost\n  // so disable it and redetect using cascades\n  if (duration > m_templateMatchingMaxDuration) {\n    m_foundFace = false;\n    m_templateMatchingRunning = false;\n    m_templateMatchingStartTime = m_templateMatchingCurrentTime = 0;\n    m_facePosition.x = m_facePosition.y = 0;\n    m_trackedFace.x = m_trackedFace.y = m_trackedFace.width =\n        m_trackedFace.height = 0;\n    return;\n  }\n\n  // Edge case when face exits frame while\n  if (m_faceTemplate.rows * m_faceTemplate.cols == 0 ||\n      m_faceTemplate.rows <= 1 || m_faceTemplate.cols <= 1) {\n    m_foundFace = false;\n    m_templateMatchingRunning = false;\n    m_templateMatchingStartTime = m_templateMatchingCurrentTime = 0;\n    m_facePosition.x = m_facePosition.y = 0;\n    m_trackedFace.x = m_trackedFace.y = m_trackedFace.width =\n        m_trackedFace.height = 0;\n    return;\n  }\n\n  // Template matching with last known face\n  // cv::matchTemplate(frame(m_faceRoi), m_faceTemplate, m_matchingResult,\n  // CV_TM_CCOEFF);\n  cv::matchTemplate(frame(m_faceRoi), m_faceTemplate, m_matchingResult,\n                    cv::TM_SQDIFF_NORMED);\n  cv::normalize(m_matchingResult, m_matchingResult, 0, 1, cv::NORM_MINMAX, -1,\n                cv::Mat());\n  double min, max;\n  cv::Point minLoc, maxLoc;\n  cv::minMaxLoc(m_matchingResult, &min, &max, &minLoc, &maxLoc);\n\n  // Add roi offset to face position\n  minLoc.x += m_faceRoi.x;\n  minLoc.y += m_faceRoi.y;\n\n  // Get detected face\n  // m_trackedFace = cv::Rect(maxLoc.x, maxLoc.y, m_trackedFace.width,\n  // m_trackedFace.height);\n  m_trackedFace =\n      cv::Rect(minLoc.x, minLoc.y, m_faceTemplate.cols, m_faceTemplate.rows);\n  m_trackedFace =\n      doubleRectSize(m_trackedFace, cv::Rect(0, 0, frame.cols, frame.rows));\n\n  // Get new face template\n  m_faceTemplate = getFaceTemplate(frame, m_trackedFace);\n\n  // Calculate face roi\n  m_faceRoi =\n      doubleRectSize(m_trackedFace, cv::Rect(0, 0, frame.cols, frame.rows));\n\n  // Update face position\n  m_facePosition = centerOfRect(m_trackedFace);\n}\n\ncv::Point VideoFaceDetector::getFrameAndDetect(cv::Mat &frame) {\n  *m_videoCapture >> frame;\n\n  // Downscale frame to m_resizedWidth width - keep aspect ratio\n  m_scale =\n      static_cast<double>(std::min(m_resizedWidth, frame.cols)) / frame.cols;\n  cv::Size resizedFrameSize = cv::Size(static_cast<int>(m_scale * frame.cols),\n                                       static_cast<int>(m_scale * frame.rows));\n\n  if (frame.empty() || resizedFrameSize.empty())\n    return cv::Point(0, 0);\n\n  cv::Mat resizedFrame;\n  cv::resize(frame, resizedFrame, resizedFrameSize);\n\n  if (!m_foundFace) {\n    detectFaceAllSizes(resizedFrame); // Detect using cascades over whole image\n  } else {\n    detectFaceAroundRoi(resizedFrame); // Detect using cascades only in ROI\n    if (m_templateMatchingRunning) {\n      detectFacesTemplateMatching(\n          resizedFrame); // Detect using template matching\n    }\n  }\n\n  if (m_learn) {\n\n    // search face chip with this face to update label\n    auto trackedFace =\n        cv::Rect(static_cast<int>(m_trackedFace.x / m_scale),\n                 static_cast<int>(m_trackedFace.y / m_scale),\n                 static_cast<int>(m_trackedFace.width / m_scale),\n                 static_cast<int>(m_trackedFace.height / m_scale));\n    limitRect(frame, trackedFace);\n    if (trackedFace.empty())\n      return cv::Point(0, 0);\n\n    cv::Mat chip_frame;\n    cv::resize(frame(trackedFace), chip_frame, cv::Size(150, 150));\n    searchFaceChip(chip_frame);\n  }\n\n  return m_facePosition;\n}\n\ncv::Point VideoFaceDetector::operator>>(cv::Mat &frame) {\n  return this->getFrameAndDetect(frame);\n}\n", "meta": {"hexsha": "e5594ca3bc742c3fa4dc041db231240e70a82a1c", "size": 16132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VideoFaceDetector.cpp", "max_stars_repo_name": "agiletechvn/realtime-tracking", "max_stars_repo_head_hexsha": "fb2bd3d4ec48cedddbe6e77a7afd4c4db7ecd34b", "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": "VideoFaceDetector.cpp", "max_issues_repo_name": "agiletechvn/realtime-tracking", "max_issues_repo_head_hexsha": "fb2bd3d4ec48cedddbe6e77a7afd4c4db7ecd34b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VideoFaceDetector.cpp", "max_forks_repo_name": "agiletechvn/realtime-tracking", "max_forks_repo_head_hexsha": "fb2bd3d4ec48cedddbe6e77a7afd4c4db7ecd34b", "max_forks_repo_licenses": ["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.8814229249, "max_line_length": 91, "alphanum_fraction": 0.6738780064, "num_tokens": 4365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.2845760163515857, "lm_q1q2_score": 0.1893598860464511}}
{"text": "//  Copyright (c) 2021 DNV AS\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#include <jsScript/jsQuantity.h>\n#include <jsScript/jsUnitValue.h>\n#include <jsScript/jsUnit.h>\n#include <jsScript/jsClass.h>\n\n#include <sstream>\n#include <limits>\n#include \"Units/Runtime/DynamicQuantity.h\"\n#include \"Units/Runtime/UnitParser.h\"\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 \"Reflection/Classes/Class.h\"\n#include \"Units/Formatting/IUnitFormatterService.h\"\n#include \"Units/Formatting/DimensionFormatter.h\"\n#include \"Services/ServiceProvider.h\"\n\njsQuantity::formatFlags jsQuantity::m_string_operator_format = includeUnitString;\nusing namespace DNVS::MoFa::Units::Runtime;\nusing namespace DNVS::MoFa::Units;\n\n//////////////////////////////////////////////////////////////////////\n// Construction/Destruction\n//////////////////////////////////////////////////////////////////////\n\njsBoundDouble jsBoundDouble::operator-()\n{\n    return jsBoundDouble(-m_value, m_inclusive);\n}\n\njsBoundDouble& jsBoundDouble::operator+()\n{\n    return *this;\n}\n\njsBoundDouble jsBoundDouble::infinity()\n{\n    return jsBoundDouble(std::numeric_limits<double>::infinity());\n}\n\nstd::mutex jsQuantity::m_mutex;\n\nstd::mutex& jsQuantity::GetMutex()\n{\n    return m_mutex;\n}\n\njsQuantity::jsQuantity(const jsQuantity& quantity)\n    : m_quantity(quantity.m_quantity)\n    , m_phenomenon(quantity.m_phenomenon)\n{\n}\n\njsQuantity::jsQuantity(const DNVS::MoFa::Units::Runtime::DynamicPhenomenon& phenomenon, double value, const std::string& unitName)\n    : m_phenomenon(phenomenon)\n    , m_quantity(value, unitName)\n{\n    ThrowIfQuantityAndPhenomenonAreIncompatible();\n}\n\njsQuantity::jsQuantity(const DNVS::MoFa::Units::Runtime::DynamicPhenomenon& phenomenon)\n    : m_phenomenon(phenomenon)\n{\n}\n\njsQuantity::jsQuantity(const DNVS::MoFa::Units::Runtime::DynamicPhenomenon& phenomenon, const std::string& quantity)\n    : m_phenomenon(phenomenon)\n{\n    std::lock_guard<std::mutex> guard(GetMutex());\n    ///We are using boost::spirit for parsing the quantity here for performance reasons. It is faster than std::stringstream.\n    ///It also handles NaN and Infinity correctly.\n    using boost::spirit::qi::double_;\n    using boost::spirit::qi::char_;\n    using boost::spirit::qi::phrase_parse;\n    using boost::spirit::qi::_1;\n    using boost::spirit::qi::space;\n\n    double value;\n    std::vector<char> unitVect;\n    if (phrase_parse(quantity.begin(), quantity.end(), double_[boost::phoenix::ref(value) = _1] >> (*char_)[boost::phoenix::ref(unitVect) = _1], space))\n    {\n        if (unitVect.empty())\n            m_quantity = DynamicQuantity(value, GetInputUnitSystem().GetUnit(m_phenomenon));\n        else\n        {\n            std::string unit(&unitVect.front(), unitVect.size());\n            m_quantity = DynamicQuantity(value, unit);\n            ThrowIfQuantityAndPhenomenonAreIncompatible();\n        }\n    }\n    else\n        throw bad_type_conversion(quantity, phenomenon.GetName());\n}\n\njsQuantity::jsQuantity(const DynamicPhenomenon& phenomenon, const DynamicQuantity& quantity)\n    : m_phenomenon(phenomenon)\n    , m_quantity(quantity)\n{\n    m_quantity.TryChangeUnit(GetDatabaseUnitSystem().GetUnit(phenomenon));\n}\n\njsQuantity& jsQuantity::operator=(const jsQuantity& quantity)\n{\n    m_phenomenon = quantity.m_phenomenon;\n    m_quantity = quantity.m_quantity;\n    return *this;\n}\n\njsQuantity::jsQuantity(double value)\n    : m_quantity(value)\n{\n}\n\njsQuantity::jsQuantity(const DNVS::MoFa::Units::Runtime::DynamicPhenomenon& phenomenon, double value, bool databaseUnits)\n    : m_phenomenon(phenomenon)\n{    \n    if (databaseUnits)\n    {\n        m_quantity = DynamicQuantity(value, SimplifiedUnit(1.0, phenomenon.GetDimension()));\n    }\n    else\n    {\n        UnitSystem unitSystem = GetInputUnitSystem();\n        Unit unit = unitSystem.GetUnit(m_phenomenon);\n        m_quantity = DynamicQuantity(value, unit);\n    }\n}\n\njsQuantity::jsQuantity(double value, const std::string& unit)\n    : m_quantity(value, unit)\n{\n    auto phenomenons = DynamicPhenomenon::GetCompatiblePhenomenons(m_quantity.GetSimplifiedUnit().GetDimension());\n    if (phenomenons.size() == 1)\n        m_phenomenon = phenomenons.front();\n    else\n        throw std::runtime_error(\"Unknown phenomenon for \" + unit);\n}\n\njsQuantity::jsQuantity(const DNVS::MoFa::Units::Runtime::DynamicPhenomenon& phenomenon, const jsUnitValue& value)\n    : m_phenomenon(phenomenon)\n    , m_quantity(value)\n{\n    ThrowIfQuantityAndPhenomenonAreIncompatible();\n}\n\njsQuantity::~jsQuantity()\n{\n\n}\n\nvoid jsQuantity::init(jsTypeLibrary& typeLibrary)\n{\n    jsTClass<jsQuantity> cls(typeLibrary, \"Quantity\");\n    if (cls.reinit()) return;\n    cls.Function(\"toString\", &jsQuantity::operator std::string);\n    cls.Function(\"signature\", &jsQuantity::signature);\n    cls.Function(\"toDouble\", &jsQuantity::toDouble);\n    cls.ImplicitConversion(&jsQuantity::operator std::string);\n    cls.ImplicitConversion(&jsQuantity::operator const DynamicQuantity&);\n\n    using namespace DNVS::MoFa::Reflection::Classes;\n    Class<jsQuantity> cls2(jsStack::stack()->GetTypeLibrary(), \"\");\n    cls2.Function(\"toString\", &jsQuantity::operator std::string);\n}\n\njsQuantity::operator const DynamicQuantity&() const\n{\n    if (!m_quantity.GetSimplifiedUnit().HasUnitName())\n    {\n        Unit unit = GetDatabaseUnit();\n        const_cast<jsQuantity*>(this)->m_quantity = DynamicQuantity(m_quantity.GetNeutralValue(), unit);\n    }\n    return m_quantity;\n}\n\nstd::string jsQuantity::signature() const\n{\n    return Formatting::DimensionFormatter().FormatAsHtml(m_phenomenon.GetDimension());\n}\n\njsQuantity::operator double() const\n{\n    return m_quantity.GetNeutralValue();\n}\n\nUnit jsQuantity::GetInputUnit() const\n{\n    return GetInputUnitSystem().GetUnit(m_phenomenon);\n}\n\nUnit jsQuantity::GetDatabaseUnit() const\n{\n    return GetDatabaseUnitSystem().GetUnit(m_phenomenon);\n}\n\njsQuantity::operator std::string() const\n{\n    return format(10, std::ios_base::floatfield, m_string_operator_format);\n}\n\nconst DynamicQuantity& jsQuantity::GetQuantity() const\n{\n    return m_quantity;\n}\n\nconst DynamicPhenomenon& jsQuantity::GetPhenomenon() const\n{\n    return m_phenomenon;\n}\n\njsValue* jsQuantity::operator-()\n{\n    return new jsUnitValue(-m_quantity);\n}\n\njsValue* jsQuantity::operator==(jsValue* op2)\n{\n    double compatibleNumber = 0;\n    if (!getCompatibleNumber(op2, compatibleNumber)) return jsScriptable::operator==(op2);\n    if (_isnan(*this) || _isnan(compatibleNumber)) return toJScript(false);\n    bool result = jsQuantity::compareTolerant(*this, compatibleNumber) == 0;\n    return toJScript(result);\n}\n\njsValue* jsQuantity::operator!=(jsValue* op2)\n{\n    double compatibleNumber = 0;\n    if (!getCompatibleNumber(op2, compatibleNumber)) return jsScriptable::operator==(op2);\n    if (_isnan(*this) || _isnan(compatibleNumber)) return toJScript(true);\n    bool result = jsQuantity::compareTolerant(*this, compatibleNumber) != 0;\n    return toJScript(result);\n}\n\njsValue* jsQuantity::operator<=(jsValue* op2)\n{\n    double compatibleNumber = 0;\n    if (!getCompatibleNumber(op2, compatibleNumber)) return jsScriptable::operator==(op2);\n    bool result = jsQuantity::compareTolerant(*this, compatibleNumber) <= 0;\n    return toJScript(result);\n}\n\njsValue* jsQuantity::operator>=(jsValue* op2)\n{\n    double compatibleNumber = 0;\n    if (!getCompatibleNumber(op2, compatibleNumber)) return jsScriptable::operator==(op2);\n    bool result = jsQuantity::compareTolerant(*this, compatibleNumber) >= 0;\n    return toJScript(result);\n}\n\njsValue* jsQuantity::operator<(jsValue* op2) {\n    double compatibleNumber = 0;\n    if (!getCompatibleNumber(op2, compatibleNumber)) return jsScriptable::operator==(op2);\n    bool result = jsQuantity::compareTolerant(*this, compatibleNumber) < 0;\n    return toJScript(result);\n}\n\njsValue* jsQuantity::operator>(jsValue* op2)\n{\n    double compatibleNumber = 0;\n    if (!getCompatibleNumber(op2, compatibleNumber)) return jsScriptable::operator==(op2);\n    bool result = jsQuantity::compareTolerant(*this, compatibleNumber) > 0;\n    return toJScript(result);\n}\n\nbool jsQuantity::getCompatibleNumber(jsValue* op2, double& number)\n{\n    try {\n        DynamicQuantity otherQuantity = fromJScript(op2, jsType<DynamicQuantity>());\n        DynamicQuantity thisQuantity = *this;\n        otherQuantity.ChangeUnit(thisQuantity.GetSimplifiedUnit());\n        number = otherQuantity.GetValue();\n        return true;\n    }\n    catch(...)\n    { \n        return false;\n    }\n}\n\nvoid jsQuantity::ThrowIfQuantityAndPhenomenonAreIncompatible()\n{\n    if (!m_quantity.IsCompatible(m_phenomenon))\n        throw std::runtime_error(\"Invalid unit: '\" + m_quantity.GetSimplifiedUnit().GetUnitName() + \"' is not a valid \" + m_phenomenon.GetName() + \" unit\");\n}\n\njsValue* jsQuantity::operator+(jsValue* op2)\n{\n    try {\n        DynamicQuantity otherQuantity = fromJScript(op2, jsType<DynamicQuantity>());\n        DynamicQuantity thisQuantity = *this;\n        return new jsUnitValue(thisQuantity + otherQuantity);\n    }\n    catch(...) {}\n    return jsValue::operator+(op2);\n}\n\njsValue* jsQuantity::operator-(jsValue* op2)\n{\n    try {\n        DynamicQuantity otherQuantity = fromJScript(op2, jsType<DynamicQuantity>());\n        DynamicQuantity thisQuantity = *this;\n        return new jsUnitValue(thisQuantity - otherQuantity);\n    }\n    catch (...) {}\n    return jsValue::operator-(op2);\n}\n\njsValue* jsQuantity::operator*(jsValue* op2)\n{\n    try {\n        DynamicQuantity otherQuantity = fromJScript(op2, jsType<DynamicQuantity>());\n        DynamicQuantity thisQuantity = *this;\n        DynamicQuantity result = thisQuantity * otherQuantity;\n        if (result.RemoveUnitIfDimensionLess())\n            return toJScript(result.GetValue());\n        else\n            return new jsUnitValue(result);\n    }\n    catch (...) {}\n    try {\n        double value = fromJScript(op2, jsType<double>());\n        DynamicQuantity thisQuantity = *this;\n        return new jsUnitValue(thisQuantity * value);\n    }\n    catch (...) {}\n    return jsValue::operator*(op2);\n}\n\n\njsValue* jsQuantity::InverseDivide(jsValue* op2)\n{\n    try {\n        double value = fromJScript(op2, jsType<double>());\n        DynamicQuantity thisQuantity = *this;\n        return new jsUnitValue(value / thisQuantity);\n    }\n    catch (...) {}\n    return jsValue::InverseDivide(op2);\n}\n\njsValue* jsQuantity::operator/(jsValue* op2)\n{\n    try {\n        DynamicQuantity otherQuantity = fromJScript(op2, jsType<DynamicQuantity>());\n        DynamicQuantity thisQuantity = *this;\n        DynamicQuantity result = thisQuantity / otherQuantity;\n        if (result.RemoveUnitIfDimensionLess())\n            return toJScript(result.GetValue());\n        else\n            return new jsUnitValue(result);\n    }\n    catch (...) {}\n    try {\n        double value = fromJScript(op2, jsType<double>());\n        DynamicQuantity thisQuantity = *this;\n        return new jsUnitValue(thisQuantity / value);\n    }\n    catch (...) {}\n    return jsValue::operator/(op2);\n}\n\n\nstd::string jsQuantity::format(formatFlags format, unitType unitTypeFlag) const\n{\n    int precision = 10;\n    std::ios::fmtflags floatFlag = std::ios_base::floatfield;\n    auto service = DNVS::MoFa::Services::ServiceProvider::Instance().TryGetService<Formatting::IUnitFormatterService>();\n    if (service)\n    {\n        precision = service->GetPrecision(m_phenomenon);\n        floatFlag = service->GetFloatFlags(m_phenomenon);\n    }\n    return this->format(precision, floatFlag, format, unitTypeFlag);\n}\n\nstd::string FormatUsingStream(std::ios_base::fmtflags flags, size_t precision, double number)\n{\n    std::stringstream stream;\n    stream.precision(precision);\n    if ((flags&std::ios_base::floatfield) == std::ios_base::floatfield)\n        flags = (flags)&~std::ios_base::floatfield;\n    stream.setf(flags);\n    stream << number;\n    return stream.str();\n}\n\nstd::string FormatUsingSprintF(std::ios_base::fmtflags flags, size_t precision, double number)\n{\n    std::string format = \"%.*\";\n    switch (flags&std::ios_base::floatfield)\n    {\n    case std::ios_base::floatfield:\n        format += \"g\";\n        break;\n    case std::ios_base::fixed:\n        format += \"f\";\n        break;\n    case std::ios_base::scientific:\n        format += \"e\";\n        break;\n    }\n    char numberAsString[200];\n    sprintf_s(numberAsString, 200, format.c_str(), int(precision), number);\n    return numberAsString;\n}\n\nstd::string jsQuantity::format(int precision, std::ios_base::fmtflags flags, formatFlags format, unitType unitTypeFlag) const\n{\n    double number = value(unitTypeFlag);\n    if (_isnan(number)) return \"NaN\";\n    if (!_finite(number)) {\n        if (number > 0) return \"+Infinity\";\n        else return \"-Infinity\";\n    }\n    if (fabs(m_quantity.GetNeutralValue()) < 1e-15)\n        number = 0;\n    std::string formattedNumber = FormatUsingSprintF(flags, precision, number);\n    if (format == includeUnitString) {\n        formattedNumber += \" \" + unitString(unitTypeFlag);\n    }\n    return formattedNumber;\n}\n\ndouble jsQuantity::value(unitType unitTypeFlag) const\n{\n    if (unitTypeFlag == databaseUnit) return m_quantity.GetNeutralValue();\n    else return GetInputUnitSystem().Convert(m_phenomenon, m_quantity);\n}\n\nstd::string jsQuantity::unitString(unitType unitTypeFlag) const\n{\n    if (unitTypeFlag == databaseUnit) {\n        return GetDatabaseUnitSystem().GetUnit(m_phenomenon).GetUnitName();\n    }\n    else {\n        return GetInputUnitSystem().GetUnit(m_phenomenon).GetUnitName();\n    }\n}\n\nDynamicDimension jsQuantity::GetDimension() const\n{\n    return m_phenomenon.GetDimension();\n}\n\ndouble jsQuantity::toDouble() const\n{\n    return value();\n}\n\nvoid jsQuantity::checkRange(const jsBoundDouble& lower_bound, const jsBoundDouble& upper_bound)\n{\n    if ((lower_bound.inclusive() && double(*this) < double(lower_bound)) ||\n        (double(*this) <= double(lower_bound)) ||\n        (upper_bound.inclusive() && double(*this) > double(upper_bound)) ||\n        (double(*this) >= double(upper_bound)))\n    {\n        std::string error = m_phenomenon.GetName() + \" value: \" + format() + \" out of range \";\n        if (lower_bound.inclusive()) error += \"[\";\n        else error += \"<\";\n        error += mofa::lexical_cast<std::string>(double(lower_bound));\n        error += \",\";\n        error += mofa::lexical_cast<std::string>(double(upper_bound));\n        if (upper_bound.inclusive()) error += \"]\";\n        else error += \">\";\n        throw std::range_error(error.c_str());\n    }\n}\n\ndouble jsQuantity::convert(const std::string& unitName) const\n{\n    DynamicQuantity q(m_quantity);\n    q.ChangeUnit(unitName);\n    return q.GetValue();\n}\n\njsQuantity::formatFlags jsQuantity::stringOperatorFormat(formatFlags operator_format)\n{\n    // Return value is previous operator format\n    formatFlags result = m_string_operator_format;\n    m_string_operator_format = operator_format;\n    return result;\n}\n\nbool jsQuantity::compatible(const jsQuantity& quantity)\n{\n    if (!m_phenomenon.IsValid()) return false;\n    if (!quantity.m_phenomenon.IsValid()) return false;\n    return m_quantity.IsCompatible(quantity.m_quantity);\n}\n\nint jsQuantity::compareTolerant(const double& a1, const double& a2)\n{\n    if (a1 == 0.0 && a2 == 0.0) return 0;\n\n    if (fabs(a1) == std::numeric_limits<double>::infinity() || fabs(a2) == std::numeric_limits<double>::infinity()) {\n        if (a1 == a2) {\n            return 0;\n        }\n        else if (a1 == -std::numeric_limits<double>::infinity() || a2 == std::numeric_limits<double>::infinity()) {\n            return -1;\n        }\n        else {\n            return 1;\n        }\n    }\n\n    double maximum = (std::max)(fabs(a1), fabs(a2));\n    double normalised_a1 = a1 / maximum;\n    double normalised_a2 = a2 / maximum;\n\n    if (fabs(normalised_a1 - normalised_a2) < 1e-10) return 0;\n    else if (normalised_a1 < normalised_a2) return -1;\n    else return 1;\n}\n", "meta": {"hexsha": "8462dec65603e372717fb266a4e31fef7e0a5708", "size": 16063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jsScript/jsQuantity.cpp", "max_stars_repo_name": "dnv-opensource/Reflection", "max_stars_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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": "jsScript/jsQuantity.cpp", "max_issues_repo_name": "dnv-opensource/Reflection", "max_issues_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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": "jsScript/jsQuantity.cpp", "max_forks_repo_name": "dnv-opensource/Reflection", "max_forks_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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.8310940499, "max_line_length": 156, "alphanum_fraction": 0.6818153521, "num_tokens": 3964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.18932355399403436}}
{"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/**\n * @file rkf_integrator.cpp\n * @brief Implementation of the RKF_integrator class\n */\n\n#include \"rkf_integrator.hpp\"\n#include \"logger.hpp\"\n#include \"wrappers.hpp\"\n\n#include \"config.h\"\n\n#ifdef ENABLE_ODEINT\n\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\n#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_algebra_dispatcher.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_resize.hpp>\n#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n#include <boost/numeric/odeint/stepper/generation.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_fehlberg78.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\ntemplate <typename Scalar, int R, int C, int O, int MR, int MC>\nstruct vector_space_norm_inf<Eigen::Array<Scalar,R,C,O,MR,MC> > {\n   using result_type = typename Eigen::NumTraits<Scalar>::Real;\n   result_type operator()(const Eigen::Array<Scalar,R,C,O,MR,MC>& x) const\n      {\n         return x.cwiseAbs().maxCoeff();\n      }\n};\n\n} // namespace odeint\n} // namespace numeric\n} // namespace boost\n\nnamespace flexiblesusy {\n\nnamespace runge_kutta {\n\n/**\n * The vector of the initial values of the parameters is\n * updated so that after calling this function, this vector contains\n * the updated values of the parameters at the end-point of the\n * integration.\n *\n * @param[in] start initial value of the independent variable\n * @param[in] end final value of the independent variable\n * @param[inout] pars initial values of the parameters\n * @param[in] derivs function calculating the derivatives\n * @param[in] tol desired accuracy to use in integration step\n */\nvoid RKF_integrator::operator()(double start, double end,\n                                Eigen::ArrayXd& pars, const Derivs& derivs,\n                                double tol) const\n{\n   using state_type = Eigen::ArrayXd;\n   using stepper_type = boost::numeric::odeint::runge_kutta_fehlberg78<\n      state_type, double, state_type, double,\n      boost::numeric::odeint::vector_space_algebra\n      >;\n\n   const double guess = (end - start) * 0.1; // first step size\n   const auto derivatives = [derivs] (const state_type& y, state_type& dydt, double t) -> void {\n      dydt = derivs(t, y);\n   };\n\n   const auto stepper = boost::numeric::odeint::make_controlled(tol, tol, stepper_type());\n   boost::numeric::odeint::integrate_adaptive(\n      stepper, derivatives, pars, start, end, guess, RKF_observer());\n}\n\nvoid RKF_integrator::RKF_observer::operator()(const Eigen::ArrayXd& state, double t) const\n{\n   if (!IsFinite(state)) {\n      int max_step_dir = 0;\n      for (int i = 0; i < state.size(); ++i) {\n         if (!IsFinite(state(i))) {\n            max_step_dir = i;\n            break;\n         }\n      }\n#ifdef ENABLE_VERBOSE\n      ERROR(\"RKF_integrator: non-perturbative running at Q = \"\n            << std::exp(t) << \" GeV of parameter y(\" << max_step_dir\n            << \") = \" << state(max_step_dir));\n#endif\n      throw NonPerturbativeRunningError(std::exp(t), max_step_dir, state(max_step_dir));\n   }\n}\n\n} // namespace runge_kutta\n\n} // namespace flexiblesusy\n\n#else\n\nnamespace flexiblesusy {\n\nnamespace runge_kutta {\n\n/**\n * The vector of the initial values of the parameters is\n * updated so that after calling this function, this vector contains\n * the updated values of the parameters at the end-point of the\n * integration.\n *\n * @param[in] start initial value of the independent variable\n * @param[in] end final value of the independent variable\n * @param[inout] pars initial values of the parameters\n * @param[in] derivs function calculating the derivatives\n * @param[in] tol desired accuracy to use in integration step\n */\nvoid RKF_integrator::operator()(double, double, Eigen::ArrayXd&, const Derivs&,\n                                double) const\n{\n   throw DisabledOdeintError(\"Cannot call operator(), because odeint support is disabled.\");\n}\n\n} // namespace runge_kutta\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "0cde71c5b91f24238d4da8e7efb900889c05b69f", "size": 4847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/rkf_integrator.cpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/src/rkf_integrator.cpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/src/rkf_integrator.cpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 33.4275862069, "max_line_length": 96, "alphanum_fraction": 0.6826903239, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.18932355084556354}}
{"text": "#include <booster/booster.h>\n#include <booster/helper.h>\n\n#include \"utils.h\"\n// #define TEST_SGECONV\nint test_general_conv_kernels(int output_channels, int input_channels, int input_h, int input_w, int kernel_h, int kernel_w, int stride, int pad)\n{\n    booster::ConvParam conv_param;\n    // conv_param\n    conv_param.output_channels = output_channels;\n    conv_param.input_channels = input_channels;\n    conv_param.input_h = input_h;\n    conv_param.input_w = input_w;\n    conv_param.kernel_h = kernel_h;\n    conv_param.kernel_w = kernel_w;\n    conv_param.stride_h = stride;\n    conv_param.stride_w = stride;\n    conv_param.pad_left = pad;\n    conv_param.pad_bottom = pad;\n    conv_param.pad_right = pad;\n    conv_param.pad_top = pad;\n    conv_param.group = 1;\n    conv_param.bias_term = true;\n    conv_param.AssignOutputDim();\n    conv_param.activation = booster::None;\n    conv_param.LogParams(\"TEST\");\n\n    float* kernel_data = (float*) malloc(sizeof(float) * conv_param.kernel_h * conv_param.kernel_w * conv_param.input_channels * conv_param.output_channels);\n    rand_fill<float>(kernel_data, conv_param.kernel_h * conv_param.kernel_w * conv_param.input_channels * conv_param.output_channels);\n    // float* naive_processed_kernel = (float*) malloc(sizeof(float) * conv_param.kernel_h * conv_param.kernel_w * conv_param.input_channels * conv_param.output_channels);\n    // float* im2col_processed_kernel = (float*) malloc(sizeof(float) * conv_param.kernel_h * conv_param.kernel_w * conv_param.input_channels * conv_param.output_channels);\n    \n    float* input_data = (float*) malloc(sizeof(float) * conv_param.input_channels * conv_param.input_h * conv_param.input_w);\n    rand_fill<float>(input_data, conv_param.input_channels * conv_param.input_h * conv_param.input_w);\n    float* output_data_1 = (float*) malloc(sizeof(float) * conv_param.output_channels * conv_param.output_h * conv_param.output_w);\n    float* output_data_2 = (float*) malloc(sizeof(float) * conv_param.output_channels * conv_param.output_h * conv_param.output_w);\n    float* output_data_3 = (float*) malloc(sizeof(float) * conv_param.output_channels * conv_param.output_h * conv_param.output_w);\n\n    float* bias_data = (float*) malloc(sizeof(float) * conv_param.output_channels);\n\n    rand_fill<float>(bias_data, conv_param.output_channels);\n    //Initialize\n    printf(\"Initializing naive...\\n\");\n    booster::ConvBooster naive_booster;\n    naive_booster.ForceSelectAlgo(booster::NAIVE);\n    int buffer_size = 0;\n    int processed_kernel_size = 0;\n    naive_booster.GetBufferSize(&conv_param, &buffer_size, &processed_kernel_size);\n    float* naive_processed_kernel = (float*) malloc(sizeof(float) * processed_kernel_size);\n    float* naive_buffer = (float*) malloc(sizeof(float) * buffer_size);\n    naive_booster.Init(&conv_param, naive_processed_kernel, kernel_data);\n    \n    printf(\"Initializing im2col...\\n\");\n    booster::ConvBooster im2col_booster;\n    im2col_booster.ForceSelectAlgo(booster::IM2COL);\n    im2col_booster.GetBufferSize(&conv_param, &buffer_size, &processed_kernel_size);\n    float* im2col_processed_kernel = (float*) malloc(sizeof(float) * processed_kernel_size);\n    float* im2col_buffer = (float*) malloc(sizeof(float) * buffer_size);\n    im2col_booster.Init(&conv_param, im2col_processed_kernel, kernel_data);\n\n    \n#ifdef TEST_SGECONV\n    printf(\"Initializing sgeconv...\\n\");\n    booster::ConvBooster sgeconv_booster;\n    sgeconv_booster.ForceSelectAlgo(booster::SGECONV);\n    sgeconv_booster.GetBufferSize(&conv_param, &buffer_size, &processed_kernel_size);\n    float* sgeconv_processed_kernel = (float*) malloc(sizeof(float) * processed_kernel_size);\n    float* sgeconv_buffer = (float*) malloc(sizeof(float) * buffer_size);\n    sgeconv_booster.Init(&conv_param, sgeconv_processed_kernel, kernel_data);\n#endif\n    \n    //Forward\n    printf(\"Forward naive...\\n\");\n    naive_booster.Forward(&conv_param, output_data_1, input_data, naive_processed_kernel, naive_buffer, bias_data);\n    printf(\"Forward im2col...\\n\");\n    im2col_booster.Forward(&conv_param, output_data_2, input_data, im2col_processed_kernel, im2col_buffer, bias_data); \n\n#ifdef TEST_SGECONV\n    printf(\"Forward sgeconv...\\n\");\n    sgeconv_booster.Forward(&conv_param, output_data_3, input_data, sgeconv_processed_kernel, sgeconv_buffer, bias_data); \n#endif\n\n    //Check results\n    diff(output_data_1, output_data_2, conv_param.output_channels * conv_param.output_w * conv_param.output_h);\n#ifdef TEST_SGECONV\n    diff(output_data_1, output_data_3, conv_param.output_channels * conv_param.output_w * conv_param.output_h);\n#endif\n    //Cleanup\n    free(naive_processed_kernel);\n    free(naive_buffer);\n    free(im2col_processed_kernel);\n    free(im2col_buffer);\n#ifdef TEST_SGECONV\n    free(sgeconv_processed_kernel);\n    free(sgeconv_buffer);\n#endif\n    free(kernel_data);\n    free(input_data);\n    free(output_data_1);\n    free(output_data_2);\n    free(output_data_3);\n    free(bias_data);\n    \n    return 0;\n}\n\nint main()\n{\n    test_general_conv_kernels(64, 32, 224, 224, 5, 5, 4, 1);\n    return 0;\n}\n", "meta": {"hexsha": "ac8bc4f3e640e959d1b37e799d474a29029bb2f0", "size": 5075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/booster/conv_test.cpp", "max_stars_repo_name": "nihui/FeatherCNN", "max_stars_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-14T09:00:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:11:54.000Z", "max_issues_repo_path": "test/booster/conv_test.cpp", "max_issues_repo_name": "nihui/FeatherCNN", "max_issues_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "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/booster/conv_test.cpp", "max_forks_repo_name": "nihui/FeatherCNN", "max_forks_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "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.3125, "max_line_length": 172, "alphanum_fraction": 0.7477832512, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18932354558868558}}
{"text": "#ifndef RAI_QUADRUPEDCONTROLLER_HPP\n#define RAI_QUADRUPEDCONTROLLER_HPP\n\n#include <Eigen/Core>\n#include \"string\"\n#include \"SimpleMLPLayer.hpp\"\n#include <cerberus_anymal_control/utils/IK.hpp>\n#include <cerberus_anymal_control/utils/GraphLoader.hpp>\n# define M_PI       3.14159265358979323846    /* pi */\n# define M_PI_2        1.57079632679489661923    /* pi/2 */\n\nnamespace RAI {\n\nclass QuadrupedController {\n  static constexpr int EstimationDim = 4;\n  static constexpr int ObservationDim = 60;\n  static constexpr int ObservationStride = 4;\n  static constexpr int HistoryLength = 128;\n  static constexpr int jointHistoryLength = 20;\n  static constexpr unsigned int actionDimension = 16;\n  static constexpr int stateDimension = 133;\n  static constexpr unsigned int nStack = 40;\n\n  typedef typename Eigen::Matrix<double, 3, 1> AngularVelocity;\n  typedef typename Eigen::Matrix<double, 3, 1> LinearVelocity;\n  typedef typename Eigen::Matrix<double, 4, 1> Quaternion;\n  typedef typename Eigen::Matrix<double, 3, 3> RotationMatrix;\n  typedef typename Eigen::Matrix<double, 4, 1> Vector4d;\n  typedef typename Eigen::Matrix<double, stateDimension, 1> State;\n  typedef typename Eigen::Matrix<double, actionDimension, 1> Action;\n  typedef typename Eigen::Matrix<double, ObservationDim, 1> Observation;\n  using Dtype = double;\n  using JointSpaceVector = Eigen::Matrix<double, 12, 1>;\n\n  typedef typename Eigen::VectorXd VectorXd;\n\n public:\n  QuadrupedController();\n\n  ~QuadrupedController();\n\n  void reset(GraphLoader<float> *graph);\n\n  void updateAction(Action action_in);\n\n  void getDesJointPos(Eigen::Matrix<double, 12, 1> &output,\n                      const Eigen::Matrix<double, 19, 1> &generalizedCoordinates,\n                      const Eigen::Matrix<double, 18, 1> &generalizedVelocities,\n                      double headingVel, double lateralVel, double yawrate);\n\n  void updateHistory(const VectorXd &q,\n                     const VectorXd &u);\n\n  static void QuattoEuler(const Quaternion &q, double &roll, double &pitch, double &yaw);\n\n private:\n  double anglediff(double target, double source);\n\n  double anglemod(double a);\n\n  double wrapAngle(double a);\n\n  int fastfloor(double a);\n\n  void conversion_GeneralizedState2LearningState(State &state,\n                                                        const VectorXd &q,\n                                                        const VectorXd &u);\n\n  RotationMatrix quatToRotMat(Quaternion &q);\n\n  State state_;\n  Action action_;\n  JointSpaceVector jointNominalConfig;\n  State state_unscaled_; /// just memory slot for computation\n  State stateOffset_;\n  State stateScale_;\n  Action actionOffset_;\n  Action actionScale_;\n  Action scaledAction_;\n  Eigen::Matrix<Dtype, 3, 1> e_g;\n  Eigen::Matrix<Dtype, 3, 1> x_, y_;\n  Eigen::Matrix<Dtype, 3, 1> command_;\n  Eigen::Matrix<Dtype, 12 * jointHistoryLength, 1> jointVelHist_, jointPosHist_, tempHist_;\n  Eigen::Matrix<float, ObservationDim, nStack> historyBuffer_;\n  Observation observationScale_;\n  Observation observationOffset_;\n  std::vector<Eigen::Matrix<double, 3, 1>> footPos_Target;\n  std::vector<Eigen::Matrix<double, 3, 1>> prevfootPos_Target;\n  std::vector<Eigen::Matrix<double, 3, 1>> prevfootPos_Target2;\n  Eigen::Matrix<Dtype, 12, 1> footPositionOffset_;\n\n  double h0_ = -0.5;\n  double clearance_[4];\n\n  double freqScale_ = 0.0025 * 2.0 * M_PI;\n  double baseFreq_ = 0.0;\n\n  unsigned long int controlCounter = 0;\n  unsigned long int stopCounter = 0;\n  unsigned long int historyUpdateCounter = 0;\n  unsigned long int decimation = 8;\n\n  InverseKinematics IK_;\n  tensorflow::TensorShape state_dims_inv;\n  tensorflow::Tensor state_tf_tensor;\n\n  tensorflow::TensorShape history_dims_inv;\n  tensorflow::Tensor history_tf_tensor;\n  GraphLoader<float> *graph_;\n\n public:\n  double pi_[4];\n  double piD_[4];\n  JointSpaceVector jointPositionTarget_;\n\n};\n\n}\n\n#endif //RAI_QUADRUPEDCONTROLLER_HPP\n", "meta": {"hexsha": "c1d6f4eaf5001123dc2c6427d331a579d89a4067", "size": 3897, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cerberus_anymal_control/include/cerberus_anymal_control/controllers/cpgController_200205.hpp", "max_stars_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_stars_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "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": "cerberus_anymal_control/include/cerberus_anymal_control/controllers/cpgController_200205.hpp", "max_issues_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_issues_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "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": "cerberus_anymal_control/include/cerberus_anymal_control/controllers/cpgController_200205.hpp", "max_forks_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_forks_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "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.2066115702, "max_line_length": 91, "alphanum_fraction": 0.7169617655, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.1893235385889421}}
{"text": "#include <utility>\n\n#include <sstream>\n\n#include <gurobi_c++.h>\n\n#include <boost/exception/diagnostic_information.hpp>\n\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n\n#include <boost/config.hpp>\n#include <boost/format.hpp>\n#include <boost/optional.hpp>\n\n#include <ortools/constraint_solver/routing.h>\n#include <ortools/constraint_solver/routing_parameters.pb.h>\n#include <ortools/constraint_solver/routing_parameters.h>\n\n#include \"util/input.h\"\n#include \"util/logging.h\"\n#include \"util/validation.h\"\n\n#include \"location_container.h\"\n#include \"solver_wrapper.h\"\n#include \"estimate_solver.h\"\n#include \"break.h\"\n#include \"second_step_solver.h\"\n#include \"gexf_writer.h\"\n\nDEFINE_string(problem,\n              \"../problem.json\", \"a file path to the problem instance\");\nDEFINE_validator(problem, &util::file::Exists\n);\n\nDEFINE_string(human_planners_solution,\n              \"\", \"a file path to the solution file for warm start\");\nDEFINE_validator(human_planners_solution, &util::file::Exists\n);\n\nDEFINE_string(solution,\n              \"\", \"a file path to the solution file for warm start\");\nDEFINE_validator(solution, &util::file::IsNullOrExists\n);\n\nDEFINE_string(maps,\n              \"../data/scotland-latest.osrm\", \"a file path to the map\");\nDEFINE_validator(maps, &util::file::Exists\n);\n\nDEFINE_string(output,\n              \"output.gexf\", \"an output file\");\n\nstatic const auto DEFAULT_TIME_LIMIT_TEXT = \"00:03:00\";\nstatic const auto DEFAULT_TIME_LIMIT = boost::posix_time::duration_from_string(DEFAULT_TIME_LIMIT_TEXT);\nDEFINE_string(time_limit, DEFAULT_TIME_LIMIT_TEXT,\n              \"time limit for proving the optimality\");\n\nDEFINE_double(gap_limit,\n              0.001, \"gap limit for proving the optimality\");\n\nDEFINE_string(break_time_window,\n              \"00:120:00\",\n              \"Time window for breaks\");\nDEFINE_validator(break_time_window, &util::time_duration::IsNullOrPositive\n);\n\nDEFINE_string(visit_time_window,\n              \"00:120:00\", \"Time window for visits\");\nDEFINE_validator(visit_time_window, &util::time_duration::IsNullOrPositive\n);\n\nDEFINE_string(begin_end_shift_time_extension,\n              \"00:15:00\",\n              \"Extra time added to the shift before and after working day\");\nDEFINE_validator(begin_end_shift_time_extension, &util::time_duration::IsNullOrPositive\n);\n\nvoid ParseArgs(int argc, char *argv[]) {\n    gflags::SetVersionString(\"0.0.1\");\n    gflags::SetUsageMessage(\"Robust Optimization for Workforce Scheduling\\n\"\n                            \"Example: rows-mip\"\n                            \" --problem=problem.json\"\n                            \" --maps=./data/scotland-latest.osrm\");\n\n    static const auto REMOVE_FLAGS = false;\n    gflags::ParseCommandLineFlags(&argc, &argv, REMOVE_FLAGS);\n\n    VLOG(1) << boost::format(\"Launched with the arguments:\\n\"\n                             \"problem: %1%\\n\"\n                             \"maps: %2%\\n\") % FLAGS_problem % FLAGS_maps;\n}\n\nint main(int argc, char *argv[]) {\n    util::SetupLogging(argv[0]);\n    ParseArgs(argc, argv);\n\n    const auto human_planner_schedule = util::LoadHumanPlannerSchedule(FLAGS_human_planners_solution);\n\n    auto cancel_token = std::make_shared<std::atomic<bool> >(false);\n    std::shared_ptr<rows::Printer> printer = util::CreatePrinter(\"log\");\n    const auto all_problem = util::LoadProblem(FLAGS_problem, printer);\n    const auto problem = all_problem.Trim(boost::posix_time::ptime{human_planner_schedule.date()}, boost::posix_time::hours(24));\n\n    const auto engine_config = util::CreateEngineConfig(FLAGS_maps);\n    const auto visit_time_window = util::GetTimeDurationOrDefault(FLAGS_visit_time_window, boost::posix_time::not_a_date_time);\n    const auto break_time_window = util::GetTimeDurationOrDefault(FLAGS_break_time_window, boost::posix_time::not_a_date_time);\n    const auto begin_end_shift_time_extension\n            = util::GetTimeDurationOrDefault(FLAGS_begin_end_shift_time_extension, boost::posix_time::not_a_date_time);\n\n    operations_research::RoutingSearchParameters search_params = operations_research::DefaultRoutingSearchParameters();\n//    search_params.set_first_solution_strategy(operations_research::FirstSolutionStrategy::ALL_UNPERFORMED);\n//    search_params.mutable_local_search_operators()->set_use_exchange_subtrip(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_relocate_expensive_chain(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_light_relocate_pair(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_relocate(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_exchange(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_exchange_pair(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_extended_swap_active(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_swap_active(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_node_pair_swap_active(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_cross_exchange(operations_research::OptionalBoolean::BOOL_TRUE);\n//    search_params.mutable_local_search_operators()->set_use_relocate_neighbors(operations_research::OptionalBoolean::BOOL_TRUE);\n\n//    search_params.set_local_search_metaheuristic(operations_research::LocalSearchMetaheuristic_Value_GUIDED_LOCAL_SEARCH);\n//    search_params.set_guided_local_search_lambda_coefficient(1.0);\n\n    auto problem_data_factory_ptr = std::make_shared<rows::RealProblemDataFactory>(engine_config);\n    const auto problem_data = problem_data_factory_ptr->makeProblem(problem);\n    rows::EstimateSolver solver{*problem_data,\n                                human_planner_schedule,\n                                search_params,\n                                util::GetTimeDurationOrDefault(FLAGS_visit_time_window, boost::posix_time::not_a_date_time),\n                                util::GetTimeDurationOrDefault(FLAGS_break_time_window, boost::posix_time::not_a_date_time),\n                                util::GetTimeDurationOrDefault(FLAGS_begin_end_shift_time_extension, boost::posix_time::not_a_date_time),\n                                boost::posix_time::seconds(30)};\n\n    operations_research::RoutingModel model{solver.index_manager()};\n//    second_stage_model->solver()->set_fail_intercept(&FailureInterceptor);\n    solver.ConfigureModel(model, printer, cancel_token, 1.0);\n\n    printer->operator<<(rows::TracingEvent(rows::TracingEventType::Started, \"Stage1\"));\n    const auto solution_assignment = model.SolveWithParameters(search_params);\n    printer->operator<<(rows::TracingEvent(rows::TracingEventType::Finished, \"Stage1\"));\n\n    if (solution_assignment == nullptr) {\n        throw util::ApplicationError(\"No second stage solution found.\", util::ErrorCode::ERROR);\n    }\n\n    // TODO: save solution\n\n    return EXIT_SUCCESS;\n}", "meta": {"hexsha": "cded30f4fbe03762dcfc5e47501fd04a6c80ca82", "size": 7249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/rows-estimate.cpp", "max_stars_repo_name": "pmateusz/cordia", "max_stars_repo_head_hexsha": "f911f4b140e416097342a7261b73e8e39dbe7589", "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/rows-estimate.cpp", "max_issues_repo_name": "pmateusz/cordia", "max_issues_repo_head_hexsha": "f911f4b140e416097342a7261b73e8e39dbe7589", "max_issues_repo_licenses": ["MIT"], "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/rows-estimate.cpp", "max_forks_repo_name": "pmateusz/cordia", "max_forks_repo_head_hexsha": "f911f4b140e416097342a7261b73e8e39dbe7589", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T17:54:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T02:28:33.000Z", "avg_line_length": 47.3790849673, "max_line_length": 137, "alphanum_fraction": 0.7394123327, "num_tokens": 1537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.18926665533459153}}
{"text": "//==================================================================\n// Author       : Pointner Sebastian\n// Company      : Johannes Kepler University\n// Name         : SMT Macro Placer\n// Workfile     : terminal.hpp\n//\n// Date         : 22. December 2019\n// Compiler     : gcc version 9.2.0 (GCC) \n// Copyright    : Johannes Kepler University\n// Description  : SoC Terminal Component\n//==================================================================\n#ifndef TERMINAL_HPP\n#define TERMINAL_HPP\n\n#include <iostream>\n#include <string>\n#include <algorithm>\n\n#include <pin.hpp>\n#include <object.hpp>\n#include <logger.hpp>\n#include <encoding_utils.hpp>\n\n#include <boost/algorithm/string.hpp>\n\nnamespace Placer {\n\nenum eTerminalType {\n    ePowerTerminal,\n    eSignalTerminal,\n    eUnknownTerminal};\n\n/**\n * @class Terminal\n * @brief Soc Terminal Pin\n */\nclass Terminal: public virtual Object {\npublic:\n    \n    Terminal(std::string const & name,\n             e_pin_direction const direction);\n\n    Terminal(std::string const & name,\n             size_t const pos_x,\n             size_t const pos_y,\n             e_pin_direction const direction,\n             eOrientation const orientation);\n\n    virtual ~Terminal();\n\n    bool operator== (Terminal const & t);\n\n    bool is_free();\n\n    void set_direction(e_pin_direction const direction);\n    e_pin_direction get_direction() const;\n\n    z3::expr& get_pos_x();\n    z3::expr& get_pos_y();\n\n    size_t get_pox_x_numerical();\n    size_t get_pos_y_numerical();\n\n    void add_solution_pos_x(size_t const val);\n    void add_solution_pos_y(size_t const val);\n\n    size_t get_solution_pos_x(size_t const sol);\n    size_t get_solution_pos_y(size_t const sol);\n\n    std::string get_name();\n    std::string get_id();\n    size_t get_key();\n    bool has_solution(size_t const solution);\n\n    bool is_input();\n    bool is_output();\n    bool is_bidirectional();\n\n    bool is_power_terminal();\n    bool is_signal_terminal();\n\n    void set_bitwidth(size_t const width);\n    size_t get_bitwidth () const;\n    bool has_bitwidth();\n\n    void set_frequency(size_t const frequency);\n    size_t get_frequency() const;\n    bool has_frequency();\n\n    virtual void dump(std::ostream & stream = std::cout);\n\nprivate:\n    Utils::Logger* m_logger;\n    EncodingUtils* m_encode;\n    std::string m_name;\n    bool m_free;\n    size_t m_key;\n    e_pin_direction m_direction;\n    eTerminalType m_terminal_type;\n\n    size_t m_bitwidth;\n    size_t m_frequency;\n\n    z3::expr m_pos_x;\n    z3::expr m_pos_y;\n    eOrientation m_orientation;\n\n    std::vector<size_t> m_solutions_x;\n    std::vector<size_t> m_solutions_y;\n\n    void resolve_terminal_type();\n    static std::vector<std::string> m_terminal_keywords;\n};\n\n} /* namespace Placer */\n\n#endif /* TERMINAL_HPP */\n", "meta": {"hexsha": "a49b5c839c10e078e4407d5d774e99197697caa9", "size": 2772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "01_src/compontents/terminal.hpp", "max_stars_repo_name": "gledr/SMT_MacroPlacer", "max_stars_repo_head_hexsha": "b5b25f0ce9094553167ffd4985721f86414ceddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T15:33:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T07:34:15.000Z", "max_issues_repo_path": "01_src/compontents/terminal.hpp", "max_issues_repo_name": "gledr/SMT_MacroPlacer", "max_issues_repo_head_hexsha": "b5b25f0ce9094553167ffd4985721f86414ceddc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01_src/compontents/terminal.hpp", "max_forks_repo_name": "gledr/SMT_MacroPlacer", "max_forks_repo_head_hexsha": "b5b25f0ce9094553167ffd4985721f86414ceddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-03T07:34:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T07:34:17.000Z", "avg_line_length": 23.4915254237, "max_line_length": 68, "alphanum_fraction": 0.6435786436, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.18926665017755387}}
{"text": "#include \"robotiq_epick_interface/epick_gripper_interface.h\"\n\n#include <ros/spinner.h>\n#include <ros/callback_queue.h>\n#include <algorithm>    // std::min std::max\n\n#include <boost/bind.hpp>\n\nnamespace epick_interface\n{\n  inline float clip(float value, const float min, const float max){\n    value = std::min(value, max);\n    return std::max(value, min);\n  }\n\n  inline uint8_t toUint8(float value){\n    return static_cast<uint8_t>(clip(round(value), 0., 255.));\n  }\n\n  inline uint8_t kpaToUint8(const float& relative_KPa){\n    return toUint8(relative_KPa + 100.);\n  }\n\n  inline float uintToKpa(const uint8_t gP){\n    return static_cast<float>(gP - 100); // KPa\n  }\n\n  inline uint8_t secToUint8(const float& rdel_sec){\n    return toUint8(rdel_sec*10);\n  }\n\n  EpickGripper::EpickGripper(ros::NodeHandle& nh): nh_(nh)\n  {\n    loadParams();\n    initPublishers();\n    initSubscribers();\n  }\n\n  bool EpickGripper::waitForConnection(const ros::Duration& timeout)\n  {\n    ros::Duration(0.1).sleep();\n    ros::Rate r(30);\n    const ros::Time start_time = ros::Time::now();\n    while(ros::ok()){\n      if(ros::Time::now() - start_time > timeout){\n        return false;\n      }else{\n        return true;\n      }\n      r.sleep();\n    }\n    return false;\n  }\n\n  bool EpickGripper::isReady()\n  {\n    return cur_status_.gSTA == 3 && cur_status_.gACT == 1;\n  }\n\n  bool EpickGripper::isReset()\n  {\n    return  cur_status_.gSTA == 0 || cur_status_.gACT == 0;\n  }\n\n  bool EpickGripper::isMoving()\n  {\n    return cur_status_.gGTO == 1 && cur_status_.gOBJ == 0;\n  }\n\n  bool EpickGripper::isStopped()\n  {\n    return cur_status_.gOBJ != 0;\n  }\n\n  bool EpickGripper::objectDetected()\n  {\n    return cur_status_.gOBJ == 1 || cur_status_.gOBJ == 2;\n  }\n\n  EpickGripper::FaultStatus EpickGripper::getFaultStatus()\n  {\n    return static_cast<EpickGripper::FaultStatus>(cur_status_.gFLT);\n  }\n\n  EpickGripper::ActuatorStatus EpickGripper::getActuatorStatus()\n  {\n    return static_cast<EpickGripper::ActuatorStatus>(cur_status_.gVAS);\n  }\n\n  float EpickGripper::getPressure()\n  {\n    return uintToKpa(cur_status_.gPO);\n  }\n\n  float EpickGripper::getRequestedPressure()\n  {\n    return uintToKpa(cur_status_.gPR);\n  }\n\n  bool EpickGripper::isClosed()\n  {\n    return cur_status_.gPO >= 230;\n  }\n\n  bool EpickGripper::isOpened()\n  {\n    return cur_status_.gPO <= 13;\n  }\n\n  bool EpickGripper::waitUntilStopped(const ros::Duration& timeout)\n  {\n    ros::Rate r(30);\n    const ros::Time start_time = ros::Time::now();\n    while(ros::ok()){\n      if(ros::Time::now() - start_time > timeout){\n        return false;\n      }\n\n      if(isStopped()){\n        return true;\n      }\n    }\n    return false;\n  }\n\n bool EpickGripper::waitUntilMoving(const ros::Duration& timeout)\n  {\n    ros::Rate r(30);\n    const ros::Time start_time = ros::Time::now();\n    while(ros::ok()){\n      if(ros::Time::now() - start_time > timeout){\n        return false;\n      }\n\n      if(isStopped()){\n        return true;\n      }\n    }\n    return false;\n  }\n\n  void EpickGripper::reset()\n  {\n    GripperOutput cmd;\n    cmd.rACT = 0;\n    cmd.rGTO = 0;\n    cmd_pub_.publish(cmd);\n    return;\n  }\n\n  bool EpickGripper::activate(const ros::Duration& timeout)\n  {\n    GripperOutput cmd;\n    cmd.rACT = 1;\n    cmd.rMOD = 0;\n    cmd.rGTO = 0;\n    cmd.rPR = 0;\n    cmd.rSP = 0;\n    cmd.rFR = 0;\n    cmd_pub_.publish(cmd);\n    ros::Rate r(30);\n    ros::Time start_time = ros::Time::now();\n    while(ros::ok()){\n      if(ros::Time::now() - start_time > timeout){\n        return false;\n      }\n\n      if(isReady()){\n        return true;\n      }\n      ros::spinOnce();\n      r.sleep();\n    }\n    return false;\n  }\n\n  void EpickGripper::loadParams()\n  {\n\n    cmd_pub_topic_name_   = \"output\";\n    state_sub_topic_name_ = \"input\";\n    return;\n  }\n\n  void EpickGripper::initSubscribers()\n  {\n    state_sub_ = nh_.subscribe(state_sub_topic_name_, 1,\n                               &EpickGripper::statusCb, this);\n  }\n\n  void EpickGripper::initPublishers()\n  {\n    cmd_pub_ = nh_.advertise<GripperOutput>(cmd_pub_topic_name_, 1);\n  }\n\n  void EpickGripper::statusCb(GripperInput msg)\n  {\n    cur_status_ = msg;\n  }\n\n  void EpickGripper::autoRelease()\n  {\n    GripperOutput cmd;\n    cmd.rACT = 1;\n    cmd.rATR = 1;\n    cmd_pub_.publish(cmd);\n  }\n\n  bool EpickGripper::goTo(const float& max_press_kpa, const float& action_timeout_sec,\n                  const float& min_press_kpa, const bool block, const ros::Duration& timeout\n                   ){\n    // REGULATE VACUUM PRESSURE REQUEST\n    const float staurated_min = std::min(min_press_kpa, 0.f);\n    GripperOutput cmd;\n    cmd.rACT = 1;\n    cmd.rMOD = 1;\n    cmd.rGTO = 1;\n    cmd.rPR = kpaToUint8(max_press_kpa);\n    cmd.rSP = secToUint8(action_timeout_sec);\n    cmd.rFR = kpaToUint8(staurated_min);\n    //cmd.rATR = open_valve_;\n    cmd_pub_.publish(cmd);\n\n    ROS_WARN_STREAM(\"GRIP pressure uint  \" << static_cast<int>(cmd.rPR));\n    ros::Duration(0.1).sleep();\n\n    if(block){\n      if(!waitUntilMoving(timeout)){\n          return false;\n      }\n      return waitUntilStopped(timeout);\n    }\n    return true;\n  }\n\n  bool EpickGripper::stop(bool block, const ros::Duration& timeout)\n  {\n    GripperOutput cmd;\n    cmd.rACT = 1;\n    cmd.rGTO = 0;\n    cmd_pub_.publish(cmd);\n    ros::Duration(0.1).sleep();\n    if(block)\n      return waitUntilStopped(timeout);\n    return true;\n  }\n\n  bool EpickGripper::drop(const float& max_press_kpa, const float& action_timeout_sec,\n                  const float& min_press_kpa, const bool block, const ros::Duration& timeout)\n  {\n    if(!isReady()){\n      ROS_WARN(\"Impossible to actuate epick while it is not in ready state!\");\n      return false;\n    }\n    if(isOpened())\n      return true;\n    float gripping_press = std::max(0.f, max_press_kpa); // we need positive pressure to release\n    return goTo(gripping_press, action_timeout_sec, min_press_kpa, block, timeout);\n  }\n\n  bool EpickGripper::grasp(const float& max_press_kpa, const float& action_timeout_sec,\n                  const float& min_press_kpa, const bool block, const ros::Duration& timeout)\n  {\n    if(!isReady()){\n     ROS_WARN(\"Impossible to actuate epick while it is not in ready state!\");\n      return false;\n    }\n    if(isClosed())\n      return true;\n    ROS_WARN_STREAM(\"GRIP pressure  \" << max_press_kpa);\n    float gripping_press = std::min(-10.f, max_press_kpa); // we need negative pressure to grasp\n    return goTo(gripping_press, action_timeout_sec, min_press_kpa, block, timeout);\n  }\n\n}\n", "meta": {"hexsha": "489681e18c5bf79d05fed2fac0b5520daa95b987", "size": 6483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robotiq_epick_control/src/robotiq_epick_interface/epick_gripper_interface.cpp", "max_stars_repo_name": "ValerioMa/robotiq_tcp", "max_stars_repo_head_hexsha": "45891abd454c3e5bc1bf75ebf151256d5a283d5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-27T08:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T19:59:20.000Z", "max_issues_repo_path": "robotiq_epick_control/src/robotiq_epick_interface/epick_gripper_interface.cpp", "max_issues_repo_name": "ValerioMa/robotiq_tcp", "max_issues_repo_head_hexsha": "45891abd454c3e5bc1bf75ebf151256d5a283d5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-19T13:16:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-20T21:43:36.000Z", "max_forks_repo_path": "robotiq_epick_control/src/robotiq_epick_interface/epick_gripper_interface.cpp", "max_forks_repo_name": "ValerioMa/robotiq_tcp", "max_forks_repo_head_hexsha": "45891abd454c3e5bc1bf75ebf151256d5a283d5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-18T05:49:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-18T05:49:43.000Z", "avg_line_length": 23.4891304348, "max_line_length": 96, "alphanum_fraction": 0.6308807651, "num_tokens": 1861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.18926664650353106}}
{"text": "#include <unistd.h>\n#include <atomic>\n#include <cmath>\n#include <csignal>\n#include <cstdlib>\n\n// How to include Eigen\n// https://stackoverflow.com/questions/56172620/how-to-build-a-simple-c-demo-using-eigen-with-bazel\n#include <Eigen/Eigen>\n#include <Eigen/Core>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <thread>\n#include <vector>\n\n\n#include \"os1.h\"\n#include \"os1_packet.h\"\n#include \"os1_util.h\"\n#include \"lidar_scan.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/types.h\"\n#include \"tensorflow/core/framework/tensor_types.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n// #include \"ouster/os1.h\"\n// #include \"ouster/os1_packet.h\"\n// #include \"ouster/os1_util.h\"\n// #include \"ouster/lidar_scan.h\"\n// #include \"ouster/viz.h\"\nnamespace tf = ::tensorflow;\nnamespace OS1 = ouster::OS1;\n// namespace viz = ouster::viz;\n#include <chrono>  \n\n// https://stackoverflow.com/questions/50799510/how-to-run-custom-gpu-tensorflowop-from-c-code\n\n\n/**\n * Print usage\n */\nvoid print_help() {\n    std::cout\n        << \"Usage: viz [options] [hostname] [udp_destination]\\n\"\n        << \"Options:\\n\"\n        << \"  -m <512x10 | 512x20 | 1024x10 | 1024x20 | 2048x10> : lidar mode, \"\n           \"default 1024x10\\n\"\n        << \"  -f <path> : use provided metadata file; do not configure via TCP\"\n        << std::endl;\n}\n\nstd::string read_metadata(const std::string& meta_file) {\n    std::stringstream buf{};\n    std::ifstream ifs{};\n    ifs.open(meta_file);\n    buf << ifs.rdbuf();\n    ifs.close();\n\n    if (!ifs) {\n        std::cerr << \"Failed to read \" << meta_file\n                  << \"; check that the path is valid\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    }\n\n    return buf.str();\n}\n\nint main(int argc, char** argv) {\n    int W = 1024;\n    int H = OS1::pixels_per_column;\n    OS1::lidar_mode mode = OS1::MODE_1024x10;\n    bool do_config = true;  // send tcp commands to configure sensor\n    std::string metadata{};\n    tf::Tensor tf_tensor(tf::DT_FLOAT, tf::TensorShape({1, 65536, 3}));\n    tf::TTypes<float, 3>::Tensor map_tensor = tf_tensor.tensor<float, 3>();\n    try {\n        int c = 0;\n        while ((c = getopt(argc, argv, \"hm:f:\")) != -1) {\n            switch (c) {\n                case 'h':\n                    print_help();\n                    return 1;\n                    break;\n                case 'm':\n                    mode = OS1::lidar_mode_of_string(optarg);\n                    if (mode) {\n                        W = OS1::n_cols_of_lidar_mode(mode);\n                    } else {\n                        std::cout << \"Lidar Mode must be 512x10, 512x20, \"\n                                     \"1024x10, 1024x20, or 2048x10\"\n                                  << std::endl;\n                        print_help();\n                        std::exit(EXIT_FAILURE);\n                    }\n                    break;\n                case 'f':\n                    do_config = false;\n                    metadata = read_metadata(optarg);\n                    break;\n                case '?':\n                    std::cout << \"Invalid Argument Format\" << std::endl;\n                    print_help();\n                    std::exit(EXIT_FAILURE);\n                    break;\n            }\n        }\n    } catch (const std::exception& ex) {\n        std::cout << \"Invalid Argument Format: \" << ex.what() << std::endl;\n        print_help();\n        std::exit(EXIT_FAILURE);\n    }\n\n    if (do_config && argc != optind + 2) {\n        std::cerr << \"Expected 2 arguments after options\" << std::endl;\n        print_help();\n        std::exit(EXIT_FAILURE);\n    }\n\n    std::shared_ptr<OS1::client> cli;\n    if (do_config) {\n        std::cout << \"Configuring sensor: \" << argv[optind]\n                  << \" UDP Destination:\" << argv[optind + 1] << std::endl;\n        cli = OS1::init_client(argv[optind], argv[optind + 1], mode);\n    } else {\n        std::cout << \"Listening for sensor data\" << std::endl;\n        cli = OS1::init_client();\n    }\n\n    if (!cli) {\n        std::cerr << \"Failed to initialize client\" << std::endl;\n        print_help();\n        std::exit(EXIT_FAILURE);\n    }\n\n    uint8_t lidar_buf[OS1::lidar_packet_bytes + 1];\n    uint8_t imu_buf[OS1::imu_packet_bytes + 1];\n\n    auto ls = std::unique_ptr<ouster::LidarScan>(new ouster::LidarScan(W, H));\n\n    // auto vh = viz::init_viz(W, H);\n\n    if (do_config) metadata = OS1::get_metadata(*cli);\n\n    auto info = OS1::parse_metadata(metadata);\n\n    auto xyz_lut = OS1::make_xyz_lut(W, H, info.beam_azimuth_angles,\n                                     info.beam_altitude_angles);\n\n    // Use to signal termination\n    std::atomic_bool end_program{false};\n\n    // auto it = std::back_inserter(*ls);\n    auto it = ls->begin();\n\n    // callback that calls update with filled lidar scan\n    auto batch_and_update = OS1::batch_to_iter<ouster::LidarScan::iterator>(\n        xyz_lut, W, H, ouster::LidarScan::Point::Zero(),\n        &ouster::LidarScan::make_val, [&](uint64_t) {\n            // swap lidar scan and point it to new buffer\n            // viz::update(*vh, ls);\n            it = ls->begin();\n            // std::cout << \"Not Initialized with the first frame\" << std::endl;\n        });\n\n    int count = 0;\n    int batch = 0;\n    bool complete = false;\n    auto start = std::chrono::high_resolution_clock::now(); \n    // Start poll thread\n    std::thread poll([&] {\n        while (!end_program) {\n            if (count > 1){\n                // std::cout << \"Next Batch count \" << batch << std::endl;\n                batch += 1;\n                count = 0;\n            }\n\n            // Poll the client for data and add to our lidar scan\n            OS1::client_state st = OS1::poll_client(*cli);\n            if (st & OS1::client_state::ERROR) {\n                std::cerr << \"Client returned error state\" << std::endl;\n                std::exit(EXIT_FAILURE);\n            }\n            if (st & OS1::client_state::LIDAR_DATA) {\n                if (OS1::read_lidar_packet(*cli, lidar_buf)){\n\n                    // Get starting timepoint \n                    // auto start = std::chrono::high_resolution_clock::now(); \n                \n                    // Call the function, here sort() \n                    batch_and_update(lidar_buf, it , map_tensor, complete);\n                    // Get ending timepoint \n                    // auto stop = std::chrono::high_resolution_clock::now(); \n                \n                    // // Get duration. Substart timepoints to  \n                    // // get durarion. To cast it to proper unit \n                    // // use duration cast method \n                    // auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); \n                \n                    // std::cout << \"Time taken by function: \"\n                    //     << duration.count() << \" microseconds\" << std::endl; \n                    // tf::TTypes<float, 3>::Tensor map_tensor_2 = tf_tensor.tensor<float, 3>();\n                    // for(int k = 0; k < 65536; k ++){\n                    //     std::cout << map_tensor_2(0,k,0) << \" \" <<  map_tensor_2(0,k,1) << \" \"   <<  map_tensor_2(0,k,2) << std::endl;\n                    \n                    // }\n                    // std::cout << tf_tensor.shape() << std::endl;\n                    // std::cout << map_tensor_2.setZero() << std::endl;\n                    if(complete){\n                        auto stop = std::chrono::high_resolution_clock::now(); \n                        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); \n                        std::cout << \"Time taken by function: \"\n                            << duration.count() << \" microseconds\" << std::endl; \n                        count += 1;\n                        map_tensor.setZero();\n                        start = std::chrono::high_resolution_clock::now(); \n                    }\n\n                    // if (batch > 0){\n                    //     end_program = true;\n                    // }\n                }\n            }\n            if (st & OS1::client_state::IMU_DATA) {\n                OS1::read_imu_packet(*cli, imu_buf);\n            }\n        }\n    });\n\n    // print the content of the point cloud\n    // while(batch < 1){}\n    // if (batch == 1){\n    //     auto it2 = ls->data_;\n    //     int npoints = 0;\n    //     for (;npoints < H * W ; npoints++)\n    //     {\n    //         std::cout << it2[npoints] << std::endl;\n    //     }\n    // }\n    while(true){}\n    // clean up\n    poll.join();\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "622f1dbb0166b7fd59f75d72780975b43d482cde", "size": 8620, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mediapipe/calculators/ouster/ouster_lidar_packet_generator_test.cc", "max_stars_repo_name": "tjtanaa/mediapipe_bazel_1.2.0", "max_stars_repo_head_hexsha": "8fc404be47a0e0ed49bd076541ae899f1c9ce221", "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": "mediapipe/calculators/ouster/ouster_lidar_packet_generator_test.cc", "max_issues_repo_name": "tjtanaa/mediapipe_bazel_1.2.0", "max_issues_repo_head_hexsha": "8fc404be47a0e0ed49bd076541ae899f1c9ce221", "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": "mediapipe/calculators/ouster/ouster_lidar_packet_generator_test.cc", "max_forks_repo_name": "tjtanaa/mediapipe_bazel_1.2.0", "max_forks_repo_head_hexsha": "8fc404be47a0e0ed49bd076541ae899f1c9ce221", "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.7580645161, "max_line_length": 137, "alphanum_fraction": 0.5042923434, "num_tokens": 2104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1892666428295082}}
{"text": "#include <iostream>\n\n#include <boost/numeric/linear_algebra/operators.hpp>\n#include <boost/numeric/linear_algebra/concepts.hpp>\n\n#include <libs/numeric/linear_algebra/test/algebraic_functions.hpp>\n\nint main(int, char* []) \n{\n    using namespace mtl;\n\n    math::add<int>     int_add;\n\n    std::cout << \"equal_results(2,5,  3,4, int_add) \" \n         << equal_results(2,5,  3,4, int_add)  << std::endl;\n    std::cout << \"equal_results(2,4,  3,4, int_add) \" \n         << equal_results(2,4,  3,4, int_add)  << std::endl;\n\n    std::cout << \"identity_pair(2,4, int_add) \" \n         << identity_pair(2,4, int_add)  << std::endl;\n    std::cout << \"identity_pair(0,0, int_add) \" \n         << identity_pair(0,0, int_add)  << std::endl << std::endl;\n\n    std::cout << \"ordered_algebraic_division(3,2, int_add) \" \n         << ordered_algebraic_division(3,2, int_add)  << std::endl;\n    std::cout << \"ordered_algebraic_division(4,2, int_add) \" \n         << ordered_algebraic_division(4,2, int_add)  << std::endl;\n    std::cout << \"ordered_algebraic_division(-6,2, int_add) \" \n         << ordered_algebraic_division(-6,2, int_add)  << std::endl;\n\n    return 0;\n}\n \n", "meta": {"hexsha": "41dc961b6120425e73af45955e2b3f9bf726d9b9", "size": 1150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/linear_algebra/test/int_example.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/int_example.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/int_example.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": 33.8235294118, "max_line_length": 68, "alphanum_fraction": 0.6226086957, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.18926664063849993}}
{"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 <algorithm>\n#include <boost/algorithm/string/join.hpp>\n#include <boost/range/adaptor/indexed.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <ored/marketdata/equityvolcurve.hpp>\n#include <ored/marketdata/marketdatumparser.hpp>\n#include <ored/utilities/currencycheck.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ored/utilities/to_string.hpp>\n#include <ored/utilities/wildcard.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/termstructures/volatility/equityfx/blackconstantvol.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvariancecurve.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <qle/models/carrmadanarbitragecheck.hpp>\n#include <qle/termstructures/blackdeltautilities.hpp>\n#include <qle/termstructures/blackvariancesurfacemoneyness.hpp>\n#include <qle/termstructures/blackvariancesurfacesparse.hpp>\n#include <qle/termstructures/blackvolsurfacedelta.hpp>\n#include <qle/termstructures/eqcommoptionsurfacestripper.hpp>\n#include <qle/termstructures/equityblackvolsurfaceproxy.hpp>\n#include <qle/termstructures/optionpricesurface.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace std;\n\nnamespace ore {\nnamespace data {\n\nEquityVolCurve::EquityVolCurve(Date asof, EquityVolatilityCurveSpec spec, const Loader& loader,\n                               const CurveConfigurations& curveConfigs, const Handle<EquityIndex>& eqIndex,\n                               const map<string, boost::shared_ptr<EquityCurve>>& requiredEquityCurves,\n                               const map<string, boost::shared_ptr<EquityVolCurve>>& requiredEquityVolCurves) {\n\n    try {\n        LOG(\"EquityVolCurve: start building equity volatility structure with ID \" << spec.curveConfigID());\n\n        auto config = *curveConfigs.equityVolCurveConfig(spec.curveConfigID());\n\n        calendar_ = parseCalendar(config.calendar());\n        // if calendar is null use currency\n        if (calendar_ == NullCalendar())\n            calendar_ = parseCalendar(config.ccy());\n        dayCounter_ = parseDayCounter(config.dayCounter());\n\n        if (config.isProxySurface()) {\n            buildVolatility(asof, spec, curveConfigs, requiredEquityCurves, requiredEquityVolCurves);\n        } else {\n            QL_REQUIRE(config.quoteType() == MarketDatum::QuoteType::PRICE ||\n                           config.quoteType() == MarketDatum::QuoteType::RATE_LNVOL,\n                       \"EquityVolCurve: Only lognormal volatilities and option premiums supported for equity \"\n                       \"volatility surfaces.\");\n\n            // Do different things depending on the type of volatility configured\n            boost::shared_ptr<VolatilityConfig> vc = config.volatilityConfig();\n            if (auto cvc = boost::dynamic_pointer_cast<ConstantVolatilityConfig>(vc)) {\n                buildVolatility(asof, config, *cvc, loader);\n            } else if (auto vcc = boost::dynamic_pointer_cast<VolatilityCurveConfig>(vc)) {\n                buildVolatility(asof, config, *vcc, loader);\n            } else if (auto vssc = boost::dynamic_pointer_cast<VolatilityStrikeSurfaceConfig>(vc)) {\n                buildVolatility(asof, config, *vssc, loader, eqIndex);\n            } else if (auto vmsc = boost::dynamic_pointer_cast<VolatilityMoneynessSurfaceConfig>(vc)) {\n                buildVolatility(asof, config, *vmsc, loader, eqIndex);\n            } else if (auto vdsc = boost::dynamic_pointer_cast<VolatilityDeltaSurfaceConfig>(vc)) {\n                buildVolatility(asof, config, *vdsc, loader, eqIndex);\n            } else {\n                QL_FAIL(\"Unexpected VolatilityConfig in EquityVolatilityConfig\");\n            }\n        }\n        DLOG(\"EquityVolCurve: finished building equity volatility structure with ID \" << spec.curveConfigID());\n\n        buildCalibrationInfo(asof, curveConfigs, config, eqIndex);\n\n    } catch (exception& e) {\n        QL_FAIL(\"Equity volatility curve building failed : \" << e.what());\n    } catch (...) {\n        QL_FAIL(\"Equity volatility curve building failed: unknown error\");\n    }\n}\n\nvoid EquityVolCurve::buildVolatility(const Date& asof, const EquityVolatilityCurveConfig& vc,\n                                     const ConstantVolatilityConfig& cvc, const Loader& loader) {\n    LOG(\"EquityVolCurve: start building constant volatility structure\");\n\n    QL_REQUIRE(cvc.quoteType() == MarketDatum::QuoteType::RATE_LNVOL ||\n                   cvc.quoteType() == MarketDatum::QuoteType::RATE_SLNVOL ||\n                   cvc.quoteType() == MarketDatum::QuoteType::RATE_NVOL,\n               \"Quote for Equity Constant Volatility Config must be a Volatility\");\n\n    // Loop over all market datums and find the single quote\n    // Return error if there are duplicates (this is why we do not use loader.get() method)\n    Real quoteValue = Null<Real>();\n    for (const boost::shared_ptr<MarketDatum>& md : loader.loadQuotes(asof)) {\n        if (md->asofDate() == asof && md->instrumentType() == MarketDatum::InstrumentType::EQUITY_OPTION) {\n\n            boost::shared_ptr<EquityOptionQuote> q = boost::dynamic_pointer_cast<EquityOptionQuote>(md);\n\n            if (q->name() == cvc.quote()) {\n                TLOG(\"Found the constant volatility quote \" << q->name());\n                QL_REQUIRE(quoteValue == Null<Real>(), \"Duplicate quote found for quote with id \" << cvc.quote());\n                // convert quote from minor to major currency if needed\n                quoteValue = convertMinorToMajorCurrency(q->ccy(), q->quote()->value());\n            }\n        }\n    }\n    QL_REQUIRE(quoteValue != Null<Real>(), \"Quote not found for id \" << cvc.quote());\n\n    DLOG(\"Creating BlackConstantVol structure\");\n    vol_ = boost::make_shared<BlackConstantVol>(asof, calendar_, quoteValue, dayCounter_);\n\n    LOG(\"EquityVolCurve: finished building constant volatility structure\");\n}\n\nvoid EquityVolCurve::buildVolatility(const Date& asof, const EquityVolatilityCurveConfig& vc,\n                                     const VolatilityCurveConfig& vcc, const Loader& loader) {\n\n    LOG(\"EquityVolCurve: start building 1-D volatility curve\");\n\n    QL_REQUIRE(vcc.quoteType() == MarketDatum::QuoteType::RATE_LNVOL ||\n                   vcc.quoteType() == MarketDatum::QuoteType::RATE_SLNVOL ||\n                   vcc.quoteType() == MarketDatum::QuoteType::RATE_NVOL,\n               \"Quote for Equity Constant Volatility Config must be a Volatility\");\n\n    // Must have at least one quote\n    QL_REQUIRE(vcc.quotes().size() > 0, \"No quotes specified in config \" << vc.curveID());\n\n    // Check if we are using a regular expression to select the quotes for the curve. If we are, the quotes should\n    // contain exactly one element.\n    auto wildcard = getUniqueWildcard(vcc.quotes());\n\n    // curveData will be populated with the expiry dates and volatility values.\n    map<Date, Real> curveData;\n\n    // Different approaches depending on whether we are using a regex or searching for a list of explicit quotes.\n    if (wildcard) {\n        DLOG(\"Have single quote with pattern \" << (*wildcard).regex());\n\n        // Loop over quotes and process commodity option quotes matching pattern on asof\n        for (const boost::shared_ptr<MarketDatum>& md : loader.loadQuotes(asof)) {\n\n            // Go to next quote if the market data point's date does not equal our asof\n            if (md->asofDate() != asof)\n                continue;\n\n            auto q = boost::dynamic_pointer_cast<EquityOptionQuote>(md);\n            if (q && (*wildcard).matches(q->name()) && q->quoteType() == vc.quoteType()) {\n\n                TLOG(\"The quote \" << q->name() << \" matched the pattern\");\n\n                Date expiryDate = getDateFromDateOrPeriod(q->expiry(), asof, calendar_);\n                if (expiryDate > asof) {\n                    // Add the quote to the curve data\n                    QL_REQUIRE(curveData.count(expiryDate) == 0, \"Duplicate quote for the expiry date \"\n                                                                     << io::iso_date(expiryDate)\n                                                                     << \" provided by equity volatility config \"\n                                                                     << vc.curveID());\n                    // convert quote from minor to major currency if needed\n                    curveData[expiryDate] = convertMinorToMajorCurrency(q->ccy(), q->quote()->value());\n\n                    TLOG(\"Added quote \" << q->name() << \": (\" << io::iso_date(expiryDate) << \",\" << fixed\n                                        << setprecision(9) << q->quote()->value() << \")\");\n                }\n            }\n        }\n        // Check that we have quotes in the end\n        QL_REQUIRE(curveData.size() > 0, \"No quotes found matching regular expression \" << vcc.quotes()[0]);\n\n    } else {\n\n        DLOG(\"Have \" << vcc.quotes().size() << \" explicit quotes\");\n\n        // Loop over quotes and process commodity option quotes that are explicitly specified in the config\n        for (const boost::shared_ptr<MarketDatum>& md : loader.loadQuotes(asof)) {\n            // Go to next quote if the market data point's date does not equal our asof\n            if (md->asofDate() != asof)\n                continue;\n\n            if (auto q = boost::dynamic_pointer_cast<EquityOptionQuote>(md)) {\n\n                // Find quote name in configured quotes.\n                auto it = find(vcc.quotes().begin(), vcc.quotes().end(), q->name());\n\n                if (it != vcc.quotes().end()) {\n                    TLOG(\"Found the configured quote \" << q->name());\n\n                    Date expiryDate = getDateFromDateOrPeriod(q->expiry(), asof, calendar_);\n                    QL_REQUIRE(expiryDate > asof, \"Equity volatility quote '\" << q->name()\n                                                                              << \"' has expiry in the past (\"\n                                                                              << io::iso_date(expiryDate) << \")\");\n                    QL_REQUIRE(curveData.count(expiryDate) == 0, \"Duplicate quote for the date \"\n                                                                     << io::iso_date(expiryDate)\n                                                                     << \" provided by equity volatility config \"\n                                                                     << vc.curveID());\n\n                    // convert quote from minor to major currency if needed\n                    curveData[expiryDate] = convertMinorToMajorCurrency(q->ccy(), q->quote()->value());\n\n                    TLOG(\"Added quote \" << q->name() << \": (\" << io::iso_date(expiryDate) << \",\" << fixed\n                                        << setprecision(9) << q->quote()->value() << \")\");\n                }\n            }\n        }\n\n        // Check that we have found all of the explicitly configured quotes\n        QL_REQUIRE(curveData.size() == vcc.quotes().size(), \"Found \" << curveData.size() << \" quotes, but \"\n                                                                     << vcc.quotes().size()\n                                                                     << \" quotes were given in config.\");\n    }\n\n    // Create the dates and volatility vector\n    vector<Date> dates;\n    vector<Volatility> volatilities;\n    for (const auto& datum : curveData) {\n        dates.push_back(datum.first);\n        volatilities.push_back(datum.second);\n        TLOG(\"Added data point (\" << io::iso_date(dates.back()) << \",\" << fixed << setprecision(9)\n                                  << volatilities.back() << \")\");\n    }\n\n    DLOG(\"Creating BlackVarianceCurve object.\");\n    auto tmp = boost::make_shared<BlackVarianceCurve>(asof, dates, volatilities, dayCounter_);\n\n    // set max expiry date (used in buildCalibrationInfo())\n    if (!dates.empty())\n        maxExpiry_ = dates.back();\n\n    // Set the interpolation.\n    if (vcc.interpolation() == \"Linear\") {\n        DLOG(\"Interpolation set to Linear.\");\n    } else if (vcc.interpolation() == \"Cubic\") {\n        DLOG(\"Setting interpolation to Cubic.\");\n        tmp->setInterpolation<Cubic>();\n    } else if (vcc.interpolation() == \"LogLinear\") {\n        DLOG(\"Setting interpolation to LogLinear.\");\n        tmp->setInterpolation<LogLinear>();\n    } else {\n        DLOG(\"Interpolation \" << vcc.interpolation() << \" not recognised so leaving it Linear.\");\n    }\n\n    // Set the volatility_ member after we have possibly updated the interpolation.\n    vol_ = tmp;\n\n    // Set the extrapolation\n    if (parseExtrapolation(vcc.extrapolation()) == Extrapolation::Flat) {\n        DLOG(\"Enabling BlackVarianceCurve flat volatility extrapolation.\");\n        vol_->enableExtrapolation();\n    } else if (parseExtrapolation(vcc.extrapolation()) == Extrapolation::None) {\n        DLOG(\"Disabling BlackVarianceCurve extrapolation.\");\n        vol_->disableExtrapolation();\n    } else if (parseExtrapolation(vcc.extrapolation()) == Extrapolation::UseInterpolator) {\n        DLOG(\"BlackVarianceCurve does not support using interpolator for extrapolation \"\n             << \"so default to flat volatility extrapolation.\");\n        vol_->enableExtrapolation();\n    } else {\n        DLOG(\"Unexpected extrapolation so default to flat volatility extrapolation.\");\n        vol_->enableExtrapolation();\n    }\n\n    LOG(\"EquityVolCurve: finished building 1-D volatility curve\");\n}\n\nvoid EquityVolCurve::buildVolatility(const Date& asof, EquityVolatilityCurveConfig& vc,\n                                     const VolatilityStrikeSurfaceConfig& vssc, const Loader& loader,\n                                     const QuantLib::Handle<EquityIndex>& eqIndex) {\n    try {\n\n        QL_REQUIRE(vssc.expiries().size() > 0, \"No expiries defined\");\n        QL_REQUIRE(vssc.strikes().size() > 0, \"No strikes defined\");\n\n        // check for wild cards\n        bool expiriesWc = find(vssc.expiries().begin(), vssc.expiries().end(), \"*\") != vssc.expiries().end();\n        bool strikesWc = find(vssc.strikes().begin(), vssc.strikes().end(), \"*\") != vssc.strikes().end();\n        if (expiriesWc) {\n            QL_REQUIRE(vssc.expiries().size() == 1, \"Wild card expiriy specified but more expiries also specified.\");\n        }\n        if (strikesWc) {\n            QL_REQUIRE(vssc.strikes().size() == 1, \"Wild card strike specified but more strikes also specified.\");\n        }\n        bool wildcard = strikesWc || expiriesWc;\n\n        vector<Real> callStrikes, putStrikes;\n        vector<Real> callData, putData;\n        vector<Date> callExpiries, putExpiries;\n\n        // In case of wild card we need the following granularity within the mkt data loop\n        bool strikeRelevant = strikesWc;\n        bool expiryRelevant = expiriesWc;\n        bool quoteRelevant = true;\n\n        // We loop over all market data, looking for quotes that match the configuration\n        Size callQuotesAdded = 0;\n        Size putQuotesAdded = 0;\n        for (auto& md : loader.loadQuotes(asof)) {\n            // skip irrelevant data\n            if (md->asofDate() == asof && md->instrumentType() == MarketDatum::InstrumentType::EQUITY_OPTION &&\n                md->quoteType() == vc.quoteType()) {\n                boost::shared_ptr<EquityOptionQuote> q = boost::dynamic_pointer_cast<EquityOptionQuote>(md);\n                // todo - for now we will ignore ATM, ATMF quotes both for explicit strikes and in case of strike wild\n                // card. ----\n                auto absoluteStrike = boost::dynamic_pointer_cast<AbsoluteStrike>(q->strike());\n                if (absoluteStrike && (q->eqName() == vc.curveID() && q->ccy() == vc.ccy())) {\n                    if (!expiriesWc) {\n                        auto j = std::find(vssc.expiries().begin(), vssc.expiries().end(), q->expiry());\n                        expiryRelevant = j != vssc.expiries().end();\n                    }\n                    if (!strikesWc) {\n                        auto i = std::find_if(vssc.strikes().begin(), vssc.strikes().end(),\n                                              [&absoluteStrike](const std::string& x) {\n                                                  return close_enough(parseReal(x), absoluteStrike->strike());\n                                              });\n                        strikeRelevant = i != vssc.strikes().end();\n                    }\n                    quoteRelevant = strikeRelevant && expiryRelevant;\n\n                    // add quote to vectors, if relevant\n                    // If a quote doesn't include a call/put flag (an Implied Vol for example), it\n                    // defaults to a call. For an explicit surface we expect either a call and put\n                    // for every point, or just a vol at every point\n                    if (quoteRelevant) {\n                        Date tmpDate = getDateFromDateOrPeriod(q->expiry(), asof, calendar_);\n                        QL_REQUIRE(tmpDate >= asof,\n                                   \"Option quote for a past date (\" << ore::data::to_string(tmpDate) << \")\");\n                        if (tmpDate == asof) {\n                            DLOG(\"Option quote for as of date (\" << ore::data::to_string(tmpDate) << \") ignored.\");\n                            continue;\n                        }\n                        // get values and strikes, convert from minor to major currency if needed\n                        Real quoteValue = q->quote()->value();\n                        if (vc.quoteType() == MarketDatum::QuoteType::PRICE)\n                            quoteValue = convertMinorToMajorCurrency(q->ccy(), quoteValue);\n                        Real strikeValue = convertMinorToMajorCurrency(q->ccy(), absoluteStrike->strike());\n\n                        if (q->isCall()) {\n                            callStrikes.push_back(strikeValue);\n                            callData.push_back(quoteValue);\n                            callExpiries.push_back(tmpDate);\n                            callQuotesAdded++;\n                        } else {\n                            putStrikes.push_back(strikeValue);\n                            putData.push_back(quoteValue);\n                            putExpiries.push_back(tmpDate);\n                            putQuotesAdded++;\n                        }\n                    }\n                }\n            }\n        }\n\n        QL_REQUIRE(callQuotesAdded > 0, \"No valid equity volatility quotes provided\");\n        bool callSurfaceOnly = false;\n        if (callQuotesAdded > 0 && putQuotesAdded == 0) {\n            QL_REQUIRE(vc.quoteType() != MarketDatum::QuoteType::PRICE,\n                       \"For Premium quotes, call and put quotes must be supplied.\");\n            DLOG(\"EquityVolatilityCurve \" << vc.curveID() << \": Only one set of quotes, can build surface directly\");\n            callSurfaceOnly = true;\n        }\n        // Check loaded quotes\n        if (!wildcard) {\n            Size explicitGridSize = vssc.expiries().size() * vssc.strikes().size();\n            QL_REQUIRE(callQuotesAdded == explicitGridSize,\n                       \"EquityVolatilityCurve \" << vc.curveID() << \": \" << callQuotesAdded << \" quotes provided but \"\n                                                << explicitGridSize << \" expected.\");\n            if (!callSurfaceOnly) {\n                QL_REQUIRE(callQuotesAdded == putQuotesAdded,\n                           \"Call and Put quotes must match for explicitly defined surface, \"\n                               << callQuotesAdded << \" call quotes, and \" << putQuotesAdded << \" put quotes\");\n                DLOG(\"EquityVolatilityCurve \" << vc.curveID() << \": Complete set of \" << callQuotesAdded\n                                              << \", call and put quotes found.\");\n            }\n        }\n\n        QL_REQUIRE(callStrikes.size() == callData.size() && callData.size() == callExpiries.size(),\n                   \"Quotes loaded don't produce strike,vol,expiry vectors of equal length.\");\n        QL_REQUIRE(putStrikes.size() == putData.size() && putData.size() == putExpiries.size(),\n                   \"Quotes loaded don't produce strike,vol,expiry vectors of equal length.\");\n        DLOG(\"EquityVolatilityCurve \" << vc.curveID() << \": Found \" << callQuotesAdded << \", call quotes and \"\n                                      << putQuotesAdded << \" put quotes using wildcard.\");\n\n        // Set the strike extrapolation which only matters if extrapolation is turned on for the whole surface.\n        bool flatStrikeExtrap = true;\n        bool flatTimeExtrap = true;\n        if (vssc.extrapolation()) {\n\n            auto strikeExtrapType = parseExtrapolation(vssc.strikeExtrapolation());\n            if (strikeExtrapType == Extrapolation::UseInterpolator) {\n                DLOG(\"Strike extrapolation switched to using interpolator.\");\n                flatStrikeExtrap = false;\n            } else if (strikeExtrapType == Extrapolation::None) {\n                DLOG(\"Strike extrapolation cannot be turned off on its own so defaulting to flat.\");\n            } else if (strikeExtrapType == Extrapolation::Flat) {\n                DLOG(\"Strike extrapolation has been set to flat.\");\n            } else {\n                DLOG(\"Strike extrapolation \" << strikeExtrapType << \" not expected so default to flat.\");\n            }\n\n            auto timeExtrapType = parseExtrapolation(vssc.timeExtrapolation());\n            if (timeExtrapType == Extrapolation::UseInterpolator) {\n                DLOG(\"Time extrapolation switched to using interpolator.\");\n                flatTimeExtrap = false;\n            } else if (timeExtrapType == Extrapolation::None) {\n                DLOG(\"Time extrapolation cannot be turned off on its own so defaulting to flat.\");\n            } else if (timeExtrapType == Extrapolation::Flat) {\n                DLOG(\"Time extrapolation has been set to flat.\");\n            } else {\n                DLOG(\"Time extrapolation \" << timeExtrapType << \" not expected so default to flat.\");\n            }\n\n        } else {\n            DLOG(\"Extrapolation is turned off for the whole surface so the time and\"\n                 << \" strike extrapolation settings are ignored\");\n        }\n\n        // set max expiry date (used in buildCalibrationInfo())\n        maxExpiry_ = Date::minDate();\n        for (auto const& d : callExpiries)\n            maxExpiry_ = std::max(maxExpiry_, d);\n        for (auto const& d : putExpiries)\n            maxExpiry_ = std::max(maxExpiry_, d);\n        if (maxExpiry_ == Date::minDate())\n            maxExpiry_ = Date();\n\n        bool preferOutOfTheMoney = vc.preferOutOfTheMoney() && *vc.preferOutOfTheMoney();\n\n        if (vc.quoteType() == MarketDatum::QuoteType::PRICE) {\n\n            // Create the 1D solver options used in the price stripping.\n            Solver1DOptions solverOptions = vc.solverConfig();\n\n            DLOG(\"Building a option price surface for calls and puts\");\n            boost::shared_ptr<OptionPriceSurface> callSurface =\n                boost::make_shared<OptionPriceSurface>(asof, callExpiries, callStrikes, callData, dayCounter_);\n            boost::shared_ptr<OptionPriceSurface> putSurface =\n                boost::make_shared<OptionPriceSurface>(asof, putExpiries, putStrikes, putData, dayCounter_);\n\n            DLOG(\"CallSurface contains \" << callSurface->expiries().size() << \" expiries.\");\n\n            DLOG(\"Stripping equity volatility surface from the option premium surfaces\");\n            boost::shared_ptr<EquityOptionSurfaceStripper> eoss = boost::make_shared<EquityOptionSurfaceStripper>(\n                eqIndex, callSurface, putSurface, calendar_, dayCounter_, vc.exerciseType(), flatStrikeExtrap,\n                flatStrikeExtrap, flatTimeExtrap, preferOutOfTheMoney, solverOptions);\n            vol_ = eoss->volSurface();\n\n        } else if (vc.quoteType() == MarketDatum::QuoteType::RATE_LNVOL) {\n\n            if (callExpiries.size() == 1 && callStrikes.size() == 1) {\n                LOG(\"EquityVolCurve: Building BlackConstantVol\");\n                vol_ = boost::shared_ptr<BlackVolTermStructure>(\n                    new BlackConstantVol(asof, Calendar(), callData[0], dayCounter_));\n            } else {\n                // create a vol surface from the calls\n                boost::shared_ptr<BlackVarianceSurfaceSparse> callSurface =\n                    boost::make_shared<BlackVarianceSurfaceSparse>(asof, calendar_, callExpiries, callStrikes, callData,\n                                                                   dayCounter_, flatStrikeExtrap, flatStrikeExtrap,\n                                                                   flatTimeExtrap);\n\n                if (callSurfaceOnly) {\n                    // if only a call surface provided use that\n                    vol_ = callSurface;\n                } else {\n                    // otherwise create a vol surface from puts and strip for a final surface\n                    boost::shared_ptr<BlackVarianceSurfaceSparse> putSurface =\n                        boost::make_shared<BlackVarianceSurfaceSparse>(asof, calendar_, putExpiries, putStrikes,\n                                                                       putData, dayCounter_, flatStrikeExtrap,\n                                                                       flatStrikeExtrap, flatTimeExtrap);\n\n                    boost::shared_ptr<EquityOptionSurfaceStripper> eoss =\n                        boost::make_shared<EquityOptionSurfaceStripper>(\n                            eqIndex, callSurface, putSurface, calendar_, dayCounter_, Exercise::European,\n                            flatStrikeExtrap, flatStrikeExtrap, flatTimeExtrap, preferOutOfTheMoney);\n                    vol_ = eoss->volSurface();\n                }\n            }\n        } else {\n            QL_FAIL(\"EquityVolatility: Invalid quote type provided.\");\n        }\n        DLOG(\"Setting BlackVarianceSurfaceSparse extrapolation to \" << to_string(vssc.extrapolation()));\n        vol_->enableExtrapolation(vssc.extrapolation());\n\n    } catch (std::exception& e) {\n        QL_FAIL(\"equity vol curve building failed :\" << e.what());\n    } catch (...) {\n        QL_FAIL(\"equity vol curve building failed: unknown error\");\n    }\n}\n\nnamespace {\nvector<Real> checkMoneyness(const vector<string>& strMoneynessLevels) {\n\n    using boost::adaptors::transformed;\n    using boost::algorithm::join;\n\n    vector<Real> moneynessLevels = parseVectorOfValues<Real>(strMoneynessLevels, &parseReal);\n    sort(moneynessLevels.begin(), moneynessLevels.end(), [](Real x, Real y) { return !close(x, y) && x < y; });\n    QL_REQUIRE(adjacent_find(moneynessLevels.begin(), moneynessLevels.end(),\n                             [](Real x, Real y) { return close(x, y); }) == moneynessLevels.end(),\n               \"The configured moneyness levels contain duplicates\");\n    DLOG(\"Parsed \" << moneynessLevels.size() << \" unique configured moneyness levels.\");\n    DLOG(\"The moneyness levels are: \" << join(\n             moneynessLevels | transformed([](Real d) { return ore::data::to_string(d); }), \",\"));\n\n    return moneynessLevels;\n}\n} // namespace\n\nvoid EquityVolCurve::buildVolatility(const Date& asof, EquityVolatilityCurveConfig& vc,\n                                     const VolatilityMoneynessSurfaceConfig& vmsc, const Loader& loader,\n                                     const QuantLib::Handle<EquityIndex>& eqIndex) {\n\n    using boost::adaptors::transformed;\n    using boost::algorithm::join;\n\n    // Check that the quote type is volatility, we do not support price\n    QL_REQUIRE(vc.quoteType() == MarketDatum::QuoteType::RATE_LNVOL,\n               \"Equity Moneyness Surface supports lognormal volatility quotes only\");\n\n    // Parse, sort and check the vector of configured moneyness levels\n    vector<Real> moneynessLevels = checkMoneyness(vmsc.moneynessLevels());\n\n    // Expiries may be configured with a wildcard or given explicitly\n    bool expWc = false;\n    if (find(vmsc.expiries().begin(), vmsc.expiries().end(), \"*\") != vmsc.expiries().end()) {\n        expWc = true;\n        QL_REQUIRE(vmsc.expiries().size() == 1, \"Wild card expiry specified but more expiries also specified.\");\n        DLOG(\"Have expiry wildcard pattern \" << vmsc.expiries()[0]);\n    }\n\n    // Map to hold the rows of the volatility matrix. The keys are the expiry dates and the values are the\n    // vectors of volatilities, one for each configured moneyness.\n    map<Date, vector<Real>> surfaceData;\n\n    // Count the number of quotes added. We check at the end that we have added all configured quotes.\n    Size quotesAdded = 0;\n\n    // Configured moneyness type.\n    MoneynessStrike::Type moneynessType = parseMoneynessType(vmsc.moneynessType());\n\n    // Populate the configured strikes.\n    vector<boost::shared_ptr<BaseStrike>> strikes;\n    for (const auto& moneynessLevel : moneynessLevels) {\n        strikes.push_back(boost::make_shared<MoneynessStrike>(moneynessType, moneynessLevel));\n    }\n\n    // Read the quotes to fill the expiry dates and vols matrix.\n    for (const boost::shared_ptr<MarketDatum>& md : loader.loadQuotes(asof)) {\n\n        // Go to next quote if the market data point's date does not equal our asof.\n        if (md->asofDate() != asof)\n            continue;\n\n        // Go to next quote if not a commodity option quote.\n        auto q = boost::dynamic_pointer_cast<EquityOptionQuote>(md);\n        if (!q)\n            continue;\n\n        // Go to next quote if eq name or currency do not match config.\n        if (vc.curveID() != q->eqName() || vc.ccy() != q->ccy())\n            continue;\n\n        // Go to next quote if quote type does not match config\n        if (vc.quoteType() != q->quoteType())\n            continue;\n\n        // Iterator to one of the configured strikes.\n        vector<boost::shared_ptr<BaseStrike>>::iterator strikeIt;\n\n        if (!expWc) {\n\n            // If we have explicitly configured expiries and the quote is not in the configured quotes continue.\n            auto it = find(vc.quotes().begin(), vc.quotes().end(), q->name());\n            if (it == vc.quotes().end())\n                continue;\n\n            // Check if quote's strike is in the configured strikes, continue if no.\n            strikeIt = find_if(strikes.begin(), strikes.end(),\n                               [&q](boost::shared_ptr<BaseStrike> s) { return *s == *q->strike(); });\n            if (strikeIt == strikes.end())\n                continue;\n\n        } else {\n\n            // Check if quote's strike is in the configured strikes and continue if it is not.\n            strikeIt = find_if(strikes.begin(), strikes.end(),\n                               [&q](boost::shared_ptr<BaseStrike> s) { return *s == *q->strike(); });\n            if (strikeIt == strikes.end())\n                continue;\n        }\n\n        // Position of quote in vector of strikes\n        Size pos = std::distance(strikes.begin(), strikeIt);\n\n        // Process the quote\n        Date eDate = getDateFromDateOrPeriod(q->expiry(), asof, calendar_);\n\n        // Add quote to surface\n        if (surfaceData.count(eDate) == 0)\n            surfaceData[eDate] = vector<Real>(moneynessLevels.size(), Null<Real>());\n\n        QL_REQUIRE(surfaceData[eDate][pos] == Null<Real>(),\n                   \"Quote \" << q->name() << \" provides a duplicate quote for the date \" << io::iso_date(eDate)\n                            << \" and strike \" << *q->strike());\n        surfaceData[eDate][pos] = q->quote()->value();\n        quotesAdded++;\n\n        TLOG(\"Added quote \" << q->name() << \": (\" << io::iso_date(eDate) << \",\" << *q->strike() << \",\" << fixed\n                            << setprecision(9) << \",\" << q->quote()->value() << \")\");\n    }\n\n    LOG(\"EquityVolCurve: added \" << quotesAdded << \" quotes in building moneyness strike surface.\");\n\n    // Check the data gathered.\n    if (!expWc) {\n        // If expiries were configured explicitly, the number of configured quotes should equal the\n        // number of quotes added.\n        QL_REQUIRE(vc.quotes().size() == quotesAdded,\n                   \"Found \" << quotesAdded << \" quotes, but \" << vc.quotes().size() << \" quotes required by config.\");\n    } else {\n        // check we have non-empty surface data\n        QL_REQUIRE(!surfaceData.empty(), \"Moneyness Surface Data is empty\");\n        // If the expiries were configured via a wildcard, check that no surfaceData element has a Null<Real>().\n        for (const auto& kv : surfaceData) {\n            for (Size j = 0; j < moneynessLevels.size(); j++) {\n                QL_REQUIRE(kv.second[j] != Null<Real>(), \"Volatility for expiry date \"\n                                                             << io::iso_date(kv.first) << \" and strike \" << *strikes[j]\n                                                             << \" not found. Cannot proceed with a sparse matrix.\");\n            }\n        }\n    }\n\n    // Populate the volatility quotes and the expiry times.\n    // Rows are moneyness levels and columns are expiry times - this is what the ctor needs below.\n    vector<Date> expiryDates(surfaceData.size());\n    vector<Time> expiryTimes(surfaceData.size());\n    vector<vector<Handle<Quote>>> vols(moneynessLevels.size());\n    for (const auto row : surfaceData | boost::adaptors::indexed(0)) {\n        expiryDates[row.index()] = row.value().first;\n        expiryTimes[row.index()] = dayCounter_.yearFraction(asof, row.value().first);\n        for (Size i = 0; i < row.value().second.size(); i++) {\n            vols[i].push_back(Handle<Quote>(boost::make_shared<SimpleQuote>(row.value().second[i])));\n        }\n    }\n\n    // set max expiry date (used in buildCalibrationInfo())\n    if (!expiryDates.empty())\n        maxExpiry_ = expiryDates.back();\n\n    // Set the strike extrapolation which only matters if extrapolation is turned on for the whole surface.\n    // BlackVarianceSurfaceMoneyness time extrapolation is hard-coded to constant in volatility.\n    bool flatExtrapolation = true;\n    if (vmsc.extrapolation()) {\n\n        auto strikeExtrapType = parseExtrapolation(vmsc.strikeExtrapolation());\n        if (strikeExtrapType == Extrapolation::UseInterpolator) {\n            DLOG(\"Strike extrapolation switched to using interpolator.\");\n            flatExtrapolation = false;\n        } else if (strikeExtrapType == Extrapolation::None) {\n            DLOG(\"Strike extrapolation cannot be turned off on its own so defaulting to flat.\");\n        } else if (strikeExtrapType == Extrapolation::Flat) {\n            DLOG(\"Strike extrapolation has been set to flat.\");\n        } else {\n            DLOG(\"Strike extrapolation \" << strikeExtrapType << \" not expected so default to flat.\");\n        }\n\n        auto timeExtrapType = parseExtrapolation(vmsc.timeExtrapolation());\n        if (timeExtrapType != Extrapolation::Flat) {\n            DLOG(\"BlackVarianceSurfaceMoneyness only supports flat volatility extrapolation in the time direction\");\n        }\n    } else {\n        DLOG(\"Extrapolation is turned off for the whole surface so the time and\"\n             << \" strike extrapolation settings are ignored\");\n    }\n\n    // Time interpolation\n    if (vmsc.timeInterpolation() != \"Linear\") {\n        DLOG(\"BlackVarianceSurfaceMoneyness only supports linear time interpolation in variance.\");\n    }\n\n    // Strike interpolation\n    if (vmsc.strikeInterpolation() != \"Linear\") {\n        DLOG(\"BlackVarianceSurfaceMoneyness only supports linear strike interpolation in variance.\");\n    }\n\n    // Both moneyness surfaces need a spot quote.\n\n    // The choice of false here is important for forward moneyness. It means that we use the cpts and yts in the\n    // BlackVarianceSurfaceMoneynessForward to get the forward value at all times and in particular at times that\n    // are after the last expiry time. If we set it to true, BlackVarianceSurfaceMoneynessForward uses a linear\n    // interpolated forward curve on the expiry times internally which is poor.\n    bool stickyStrike = false;\n\n    if (moneynessType == MoneynessStrike::Type::Forward) {\n\n        DLOG(\"Creating BlackVarianceSurfaceMoneynessForward object\");\n        vol_ = boost::make_shared<BlackVarianceSurfaceMoneynessForward>(\n            calendar_, eqIndex->equitySpot(), expiryTimes, moneynessLevels, vols, dayCounter_,\n            eqIndex->equityDividendCurve(), eqIndex->equityForecastCurve(), stickyStrike, flatExtrapolation);\n\n    } else {\n\n        DLOG(\"Creating BlackVarianceSurfaceMoneynessSpot object\");\n        vol_ = boost::make_shared<BlackVarianceSurfaceMoneynessSpot>(calendar_, eqIndex->equitySpot(), expiryTimes,\n                                                                     moneynessLevels, vols, dayCounter_, stickyStrike,\n                                                                     flatExtrapolation);\n    }\n\n    DLOG(\"Setting BlackVarianceSurfaceMoneyness extrapolation to \" << to_string(vmsc.extrapolation()));\n    vol_->enableExtrapolation(vmsc.extrapolation());\n\n    LOG(\"EquityVolCurve: finished building 2-D volatility moneyness strike surface\");\n}\n\nvoid EquityVolCurve::buildVolatility(const QuantLib::Date& asof, EquityVolatilityCurveConfig& vc,\n                                     const VolatilityDeltaSurfaceConfig& vdsc, const Loader& loader,\n                                     const QuantLib::Handle<QuantExt::EquityIndex>& eqIndex) {\n\n    using boost::adaptors::transformed;\n    using boost::algorithm::join;\n\n    LOG(\"EquityVolCurve: start building 2-D volatility delta strike surface\");\n\n    QL_REQUIRE(vc.quoteType() == MarketDatum::QuoteType::RATE_LNVOL,\n               \"EquityVolCurve: only quote type\"\n                   << \" RATE_LNVOL is currently supported for a 2-D volatility delta strike surface.\");\n\n    // Parse, sort and check the vector of configured put deltas\n    vector<Real> putDeltas = parseVectorOfValues<Real>(vdsc.putDeltas(), &parseReal);\n    sort(putDeltas.begin(), putDeltas.end(), [](Real x, Real y) { return !close(x, y) && x < y; });\n    QL_REQUIRE(adjacent_find(putDeltas.begin(), putDeltas.end(), [](Real x, Real y) { return close(x, y); }) ==\n                   putDeltas.end(),\n               \"The configured put deltas contain duplicates\");\n    DLOG(\"Parsed \" << putDeltas.size() << \" unique configured put deltas\");\n    DLOG(\"Put deltas are: \" << join(putDeltas | transformed([](Real d) { return ore::data::to_string(d); }), \",\"));\n\n    // Parse, sort descending and check the vector of configured call deltas\n    vector<Real> callDeltas = parseVectorOfValues<Real>(vdsc.callDeltas(), &parseReal);\n    sort(callDeltas.begin(), callDeltas.end(), [](Real x, Real y) { return !close(x, y) && x > y; });\n    QL_REQUIRE(adjacent_find(callDeltas.begin(), callDeltas.end(), [](Real x, Real y) { return close(x, y); }) ==\n                   callDeltas.end(),\n               \"The configured call deltas contain duplicates\");\n    DLOG(\"Parsed \" << callDeltas.size() << \" unique configured call deltas\");\n    DLOG(\"Call deltas are: \" << join(callDeltas | transformed([](Real d) { return ore::data::to_string(d); }), \",\"));\n\n    // Expiries may be configured with a wildcard or given explicitly\n    bool expWc = false;\n    if (find(vdsc.expiries().begin(), vdsc.expiries().end(), \"*\") != vdsc.expiries().end()) {\n        expWc = true;\n        QL_REQUIRE(vdsc.expiries().size() == 1, \"Wild card expiry specified but more expiries also specified.\");\n        DLOG(\"Have expiry wildcard pattern \" << vdsc.expiries()[0]);\n    }\n\n    // Map to hold the rows of the equity volatility matrix. The keys are the expiry dates and the values are the\n    // vectors of volatilities, one for each configured delta.\n    map<Date, vector<Real>> surfaceData;\n\n    // Number of strikes = number of put deltas + ATM + number of call deltas\n    Size numStrikes = putDeltas.size() + 1 + callDeltas.size();\n\n    // Count the number of quotes added. We check at the end that we have added all configured quotes.\n    Size quotesAdded = 0;\n\n    // Configured delta and Atm types.\n    DeltaVolQuote::DeltaType deltaType = parseDeltaType(vdsc.deltaType());\n    DeltaVolQuote::AtmType atmType = parseAtmType(vdsc.atmType());\n    boost::optional<DeltaVolQuote::DeltaType> atmDeltaType;\n    if (!vdsc.atmDeltaType().empty()) {\n        atmDeltaType = parseDeltaType(vdsc.atmDeltaType());\n    }\n\n    // Populate the configured strikes.\n    vector<boost::shared_ptr<BaseStrike>> strikes;\n    for (const auto& pd : putDeltas) {\n        strikes.push_back(boost::make_shared<DeltaStrike>(deltaType, Option::Put, pd));\n    }\n    strikes.push_back(boost::make_shared<AtmStrike>(atmType, atmDeltaType));\n    for (const auto& cd : callDeltas) {\n        strikes.push_back(boost::make_shared<DeltaStrike>(deltaType, Option::Call, cd));\n    }\n\n    // Read the quotes to fill the expiry dates and vols matrix.\n    for (const boost::shared_ptr<MarketDatum>& md : loader.loadQuotes(asof)) {\n\n        // Go to next quote if the market data point's date does not equal our asof.\n        if (md->asofDate() != asof)\n            continue;\n\n        // Go to next quote if not a commodity option quote.\n        auto q = boost::dynamic_pointer_cast<EquityOptionQuote>(md);\n        if (!q)\n            continue;\n\n        // Go to next quote if not a equity name or currency do not match config.\n        if (vc.curveID() != q->eqName() || vc.ccy() != q->ccy())\n            continue;\n\n        // Iterator to one of the configured strikes.\n        vector<boost::shared_ptr<BaseStrike>>::iterator strikeIt;\n\n        if (!expWc) {\n\n            // If we have explicitly configured expiries and the quote is not in the configured quotes continue.\n            auto it = find(vc.quotes().begin(), vc.quotes().end(), q->name());\n            if (it == vc.quotes().end())\n                continue;\n\n            // Check if quote's strike is in the configured strikes.\n            // It should be as we have selected from the explicitly configured quotes in the last step.\n            strikeIt = find_if(strikes.begin(), strikes.end(),\n                               [&q](boost::shared_ptr<BaseStrike> s) { return *s == *q->strike(); });\n            QL_REQUIRE(strikeIt != strikes.end(),\n                       \"The quote '\"\n                           << q->name()\n                           << \"' is in the list of configured quotes but does not match any of the configured strikes\");\n\n        } else {\n\n            // Check if quote's strike is in the configured strikes and continue if it is not.\n            strikeIt = find_if(strikes.begin(), strikes.end(),\n                               [&q](boost::shared_ptr<BaseStrike> s) { return *s == *q->strike(); });\n            if (strikeIt == strikes.end())\n                continue;\n        }\n\n        // Position of quote in vector of strikes\n        Size pos = std::distance(strikes.begin(), strikeIt);\n\n        // Process the quote\n        Date eDate;\n        boost::shared_ptr<Expiry> expiry = parseExpiry(q->expiry());\n        if (auto expiryDate = boost::dynamic_pointer_cast<ExpiryDate>(expiry)) {\n            eDate = expiryDate->expiryDate();\n        } else if (auto expiryPeriod = boost::dynamic_pointer_cast<ExpiryPeriod>(expiry)) {\n            // We may need more conventions here eventually.\n            eDate = calendar_.adjust(asof + expiryPeriod->expiryPeriod());\n        }\n\n        // Add quote to surface\n        if (surfaceData.count(eDate) == 0)\n            surfaceData[eDate] = vector<Real>(numStrikes, Null<Real>());\n\n        QL_REQUIRE(surfaceData[eDate][pos] == Null<Real>(),\n                   \"Quote \" << q->name() << \" provides a duplicate quote for the date \" << io::iso_date(eDate)\n                            << \" and strike \" << *q->strike());\n        surfaceData[eDate][pos] = q->quote()->value();\n        quotesAdded++;\n\n        TLOG(\"Added quote \" << q->name() << \": (\" << io::iso_date(eDate) << \",\" << *q->strike() << \",\" << fixed\n                            << setprecision(9) << \",\" << q->quote()->value() << \")\");\n    }\n\n    LOG(\"EquityVolCurve: added \" << quotesAdded << \" quotes in building delta strike surface.\");\n\n    // Check the data gathered.\n    if (!expWc) {\n        // If expiries were configured explicitly, the number of configured quotes should equal the\n        // number of quotes added.\n        QL_REQUIRE(vc.quotes().size() == quotesAdded,\n                   \"Found \" << quotesAdded << \" quotes, but \" << vc.quotes().size() << \" quotes required by config.\");\n    } else {\n        // If the expiries were configured via a wildcard, check that no surfaceData element has a Null<Real>().\n        for (const auto& kv : surfaceData) {\n            for (Size j = 0; j < numStrikes; j++) {\n                QL_REQUIRE(kv.second[j] != Null<Real>(), \"Volatility for expiry date \"\n                                                             << io::iso_date(kv.first) << \" and strike \" << *strikes[j]\n                                                             << \" not found. Cannot proceed with a sparse matrix.\");\n            }\n        }\n    }\n\n    // Populate the matrix of volatilities and the expiry dates.\n    vector<Date> expiryDates;\n    Matrix vols(surfaceData.size(), numStrikes);\n    for (const auto row : surfaceData | boost::adaptors::indexed(0)) {\n        expiryDates.push_back(row.value().first);\n        copy(row.value().second.begin(), row.value().second.end(), vols.row_begin(row.index()));\n    }\n\n    // Need to multiply each put delta value by -1 before passing it to the BlackVolatilitySurfaceDelta ctor\n    // i.e. a put delta of 0.25 that is passed in to the config must be -0.25 when passed to the ctor.\n    transform(putDeltas.begin(), putDeltas.end(), putDeltas.begin(), [](Real pd) { return -1.0 * pd; });\n    DLOG(\"Multiply put deltas by -1.0 before creating BlackVolatilitySurfaceDelta object.\");\n    DLOG(\"Put deltas are: \" << join(putDeltas | transformed([](Real d) { return ore::data::to_string(d); }), \",\"));\n\n    // Set the strike extrapolation which only matters if extrapolation is turned on for the whole surface.\n    // BlackVolatilitySurfaceDelta time extrapolation is hard-coded to constant in volatility.\n    bool flatExtrapolation = true;\n    if (vdsc.extrapolation()) {\n\n        auto strikeExtrapType = parseExtrapolation(vdsc.strikeExtrapolation());\n        if (strikeExtrapType == Extrapolation::UseInterpolator) {\n            DLOG(\"Strike extrapolation switched to using interpolator.\");\n            flatExtrapolation = false;\n        } else if (strikeExtrapType == Extrapolation::None) {\n            DLOG(\"Strike extrapolation cannot be turned off on its own so defaulting to flat.\");\n        } else if (strikeExtrapType == Extrapolation::Flat) {\n            DLOG(\"Strike extrapolation has been set to flat.\");\n        } else {\n            DLOG(\"Strike extrapolation \" << strikeExtrapType << \" not expected so default to flat.\");\n        }\n\n        auto timeExtrapType = parseExtrapolation(vdsc.timeExtrapolation());\n        if (timeExtrapType != Extrapolation::Flat) {\n            DLOG(\"BlackVolatilitySurfaceDelta only supports flat volatility extrapolation in the time direction\");\n        }\n    } else {\n        DLOG(\"Extrapolation is turned off for the whole surface so the time and\"\n             << \" strike extrapolation settings are ignored\");\n    }\n\n    // Time interpolation\n    if (vdsc.timeInterpolation() != \"Linear\") {\n        DLOG(\"BlackVolatilitySurfaceDelta only supports linear time interpolation.\");\n    }\n\n    // Strike interpolation\n    InterpolatedSmileSection::InterpolationMethod im;\n    if (vdsc.strikeInterpolation() == \"Linear\") {\n        im = InterpolatedSmileSection::InterpolationMethod::Linear;\n    } else if (vdsc.strikeInterpolation() == \"NaturalCubic\") {\n        im = InterpolatedSmileSection::InterpolationMethod::NaturalCubic;\n    } else if (vdsc.strikeInterpolation() == \"FinancialCubic\") {\n        im = InterpolatedSmileSection::InterpolationMethod::FinancialCubic;\n    } else {\n        im = InterpolatedSmileSection::InterpolationMethod::Linear;\n        DLOG(\"BlackVolatilitySurfaceDelta does not support strike interpolation '\" << vdsc.strikeInterpolation()\n                                                                                   << \"' so setting it to linear.\");\n    }\n\n    // set max expiry date (used in buildCalibrationInfo())\n    if (!expiryDates.empty())\n        maxExpiry_ = expiryDates.back();\n\n    DLOG(\"Creating BlackVolatilitySurfaceDelta object\");\n    bool hasAtm = true;\n    vol_ = boost::make_shared<BlackVolatilitySurfaceDelta>(\n        asof, expiryDates, putDeltas, callDeltas, hasAtm, vols, dayCounter_, calendar_, eqIndex->equitySpot(),\n        eqIndex->equityForecastCurve(), eqIndex->equityDividendCurve(), deltaType, atmType, atmDeltaType, 0 * Days,\n        deltaType, atmType, atmDeltaType, im, flatExtrapolation);\n\n    DLOG(\"Setting BlackVolatilitySurfaceDelta extrapolation to \" << to_string(vdsc.extrapolation()));\n    vol_->enableExtrapolation(vdsc.extrapolation());\n\n    LOG(\"EquityVolCurve: finished building 2-D volatility delta strike surface\");\n}\n\nvoid EquityVolCurve::buildVolatility(const QuantLib::Date& asof, const EquityVolatilityCurveSpec& spec,\n                                     const CurveConfigurations& curveConfigs,\n                                     const map<string, boost::shared_ptr<EquityCurve>>& eqCurves,\n                                     const map<string, boost::shared_ptr<EquityVolCurve>>& eqVolCurves) {\n\n    // get all the configurations and the curve needed for proxying\n    auto config = *curveConfigs.equityVolCurveConfig(spec.curveConfigID());\n\n    auto proxy = config.proxySurface();\n    auto eqConfig = *curveConfigs.equityCurveConfig(spec.curveConfigID());\n    auto proxyConfig = *curveConfigs.equityCurveConfig(proxy);\n    auto proxyVolConfig = *curveConfigs.equityVolCurveConfig(proxy);\n\n    // create dummy specs to look up the required curves\n    EquityCurveSpec eqSpec(eqConfig.currency(), spec.curveConfigID());\n    EquityCurveSpec proxySpec(proxyConfig.currency(), proxy);\n    EquityVolatilityCurveSpec proxyVolSpec(proxyVolConfig.ccy(), proxy);\n\n    // Get all necessary curves\n    auto curve = eqCurves.find(eqSpec.name());\n    QL_REQUIRE(curve != eqCurves.end(), \"Failed to find equity curve, when building equity vol curve \" << spec.name());\n    auto proxyCurve = eqCurves.find(proxySpec.name());\n    QL_REQUIRE(proxyCurve != eqCurves.end(), \"Failed to find equity curve for proxy \"\n                                                 << proxySpec.name() << \", when building equity vol curve \"\n                                                 << spec.name());\n    auto proxyVolCurve = eqVolCurves.find(proxyVolSpec.name());\n    QL_REQUIRE(proxyVolCurve != eqVolCurves.end(), \"Failed to find equity vol curve for proxy \"\n                                                       << proxyVolSpec.name() << \", when building equity vol curve \"\n                                                       << spec.name());\n\n    vol_ = boost::make_shared<EquityBlackVolatilitySurfaceProxy>(\n        proxyVolCurve->second->volTermStructure(), curve->second->equityIndex(), proxyCurve->second->equityIndex());\n}\n\nvoid EquityVolCurve::buildCalibrationInfo(const QuantLib::Date& asof, const CurveConfigurations& curveConfigs,\n                                          const EquityVolatilityCurveConfig& config,\n                                          const Handle<EquityIndex>& eqIndex) {\n\n    DLOG(\"Building calibration info for eq vol surface\");\n\n    try {\n\n        ReportConfig rc = effectiveReportConfig(curveConfigs.reportConfigEqVols(), config.reportConfig());\n\n        bool reportOnDeltaGrid = *rc.reportOnDeltaGrid();\n        bool reportOnMoneynessGrid = *rc.reportOnMoneynessGrid();\n        std::vector<Real> moneyness = *rc.moneyness();\n        std::vector<std::string> deltas = *rc.deltas();\n        std::vector<Period> expiries = *rc.expiries();\n\n        calibrationInfo_ = boost::make_shared<FxEqVolCalibrationInfo>();\n\n        DeltaVolQuote::AtmType atmType = DeltaVolQuote::AtmType::AtmDeltaNeutral;\n        DeltaVolQuote::DeltaType deltaType = DeltaVolQuote::DeltaType::Fwd;\n\n        if (auto vdsc = boost::dynamic_pointer_cast<VolatilityDeltaSurfaceConfig>(config.volatilityConfig())) {\n            atmType = parseAtmType(vdsc->atmType());\n            deltaType = parseDeltaType(vdsc->deltaType());\n        }\n\n        calibrationInfo_->dayCounter = config.dayCounter().empty() ? \"na\" : config.dayCounter();\n        calibrationInfo_->calendar = config.calendar().empty() ? \"na\" : config.calendar();\n        calibrationInfo_->atmType = ore::data::to_string(atmType);\n        calibrationInfo_->deltaType = ore::data::to_string(deltaType);\n        calibrationInfo_->longTermAtmType = ore::data::to_string(atmType);\n        calibrationInfo_->longTermDeltaType = ore::data::to_string(deltaType);\n        calibrationInfo_->switchTenor = \"na\";\n        calibrationInfo_->riskReversalInFavorOf = \"na\";\n        calibrationInfo_->butterflyStyle = \"na\";\n\n        std::vector<Real> times, forwards, rfDisc, divDisc;\n        for (auto const& p : expiries) {\n            Date d = vol_->optionDateFromTenor(p);\n            calibrationInfo_->expiryDates.push_back(d);\n            times.push_back(vol_->dayCounter().empty() ? Actual365Fixed().yearFraction(asof, d)\n                                                       : vol_->timeFromReference(d));\n            forwards.push_back(eqIndex->fixing(d));\n            rfDisc.push_back(eqIndex->equityForecastCurve()->discount(d));\n            divDisc.push_back(eqIndex->equityDividendCurve()->discount(d));\n        }\n\n        calibrationInfo_->times = times;\n        calibrationInfo_->forwards = forwards;\n\n        std::vector<std::vector<Real>> callPricesDelta(times.size(), std::vector<Real>(deltas.size(), 0.0));\n        std::vector<std::vector<Real>> callPricesMoneyness(times.size(), std::vector<Real>(moneyness.size(), 0.0));\n\n        calibrationInfo_->isArbitrageFree = true;\n\n        if (reportOnDeltaGrid) {\n            calibrationInfo_->deltas = deltas;\n            calibrationInfo_->deltaGridStrikes =\n                std::vector<std::vector<Real>>(times.size(), std::vector<Real>(deltas.size(), 0.0));\n            calibrationInfo_->deltaGridProb =\n                std::vector<std::vector<Real>>(times.size(), std::vector<Real>(deltas.size(), 0.0));\n            calibrationInfo_->deltaGridImpliedVolatility =\n                std::vector<std::vector<Real>>(times.size(), std::vector<Real>(deltas.size(), 0.0));\n            calibrationInfo_->deltaGridCallSpreadArbitrage =\n                std::vector<std::vector<bool>>(times.size(), std::vector<bool>(deltas.size(), true));\n            calibrationInfo_->deltaGridButterflyArbitrage =\n                std::vector<std::vector<bool>>(times.size(), std::vector<bool>(deltas.size(), true));\n            TLOG(\"Delta surface arbitrage analysis result (no calendar spread arbitrage included):\");\n            Real maxTime = QL_MAX_REAL;\n            if (maxExpiry_ != Date()) {\n                if (vol_->dayCounter().empty())\n                    maxTime = Actual365Fixed().yearFraction(asof, maxExpiry_);\n                else\n                    maxTime = vol_->timeFromReference(maxExpiry_);\n            }\n            DeltaVolQuote::AtmType at;\n            DeltaVolQuote::DeltaType dt;\n            for (Size i = 0; i < times.size(); ++i) {\n                Real t = times[i];\n                at = atmType;\n                dt = deltaType;\n                // for times after the last quoted expiry we use artificial conventions to avoid problems with strike\n                // from delta conversions: we use fwd delta always and ATM DNS\n                if (t > maxTime) {\n                    at = DeltaVolQuote::AtmDeltaNeutral;\n                    dt = DeltaVolQuote::Fwd;\n                }\n                bool validSlice = true;\n                for (Size j = 0; j < deltas.size(); ++j) {\n                    DeltaString d(deltas[j]);\n                    try {\n                        Real strike;\n                        if (d.isAtm()) {\n                            strike = QuantExt::getAtmStrike(dt, at, eqIndex->equitySpot()->value(), rfDisc[i],\n                                                            divDisc[i], vol_, t);\n                        } else if (d.isCall()) {\n                            strike = QuantExt::getStrikeFromDelta(Option::Call, d.delta(), dt,\n                                                                  eqIndex->equitySpot()->value(), rfDisc[i], divDisc[i],\n                                                                  vol_, t);\n                        } else {\n                            strike =\n                                QuantExt::getStrikeFromDelta(Option::Put, d.delta(), dt, eqIndex->equitySpot()->value(),\n                                                             rfDisc[i], divDisc[i], vol_, t);\n                        }\n                        Real stddev = std::sqrt(vol_->blackVariance(t, strike));\n                        callPricesDelta[i][j] = blackFormula(Option::Call, strike, forwards[i], stddev);\n                        calibrationInfo_->deltaGridStrikes[i][j] = strike;\n                        calibrationInfo_->deltaGridImpliedVolatility[i][j] = stddev / std::sqrt(t);\n                    } catch (const std::exception& e) {\n                        validSlice = false;\n                        TLOG(\"error for time \" << t << \" delta \" << deltas[j] << \": \" << e.what());\n                    }\n                }\n                if (validSlice) {\n                    try {\n                        QuantExt::CarrMadanMarginalProbability cm(calibrationInfo_->deltaGridStrikes[i], forwards[i],\n                                                                  callPricesDelta[i]);\n                        calibrationInfo_->deltaGridCallSpreadArbitrage[i] = cm.callSpreadArbitrage();\n                        calibrationInfo_->deltaGridButterflyArbitrage[i] = cm.butterflyArbitrage();\n                        if (!cm.arbitrageFree())\n                            calibrationInfo_->isArbitrageFree = false;\n                        calibrationInfo_->deltaGridProb[i] = cm.density();\n                        TLOGGERSTREAM << arbitrageAsString(cm);\n                    } catch (const std::exception& e) {\n                        TLOG(\"error for time \" << t << \": \" << e.what());\n                        calibrationInfo_->isArbitrageFree = false;\n                        TLOGGERSTREAM << \"..(invalid slice)..\";\n                    }\n                } else {\n                    calibrationInfo_->isArbitrageFree = false;\n                    TLOGGERSTREAM << \"..(invalid slice)..\";\n                }\n            }\n            TLOG(\"Delta surface arbitrage analysis completed.\");\n        }\n\n        if (reportOnMoneynessGrid) {\n            calibrationInfo_->moneyness = moneyness;\n            calibrationInfo_->moneynessGridStrikes =\n                std::vector<std::vector<Real>>(times.size(), std::vector<Real>(moneyness.size(), 0.0));\n            calibrationInfo_->moneynessGridProb =\n                std::vector<std::vector<Real>>(times.size(), std::vector<Real>(moneyness.size(), 0.0));\n            calibrationInfo_->moneynessGridImpliedVolatility =\n                std::vector<std::vector<Real>>(times.size(), std::vector<Real>(moneyness.size(), 0.0));\n            calibrationInfo_->moneynessGridCallSpreadArbitrage =\n                std::vector<std::vector<bool>>(times.size(), std::vector<bool>(moneyness.size(), true));\n            calibrationInfo_->moneynessGridButterflyArbitrage =\n                std::vector<std::vector<bool>>(times.size(), std::vector<bool>(moneyness.size(), true));\n            calibrationInfo_->moneynessGridCalendarArbitrage =\n                std::vector<std::vector<bool>>(times.size(), std::vector<bool>(moneyness.size(), true));\n            for (Size i = 0; i < times.size(); ++i) {\n                Real t = times[i];\n                for (Size j = 0; j < moneyness.size(); ++j) {\n                    try {\n                        Real strike = moneyness[j] * forwards[i];\n                        calibrationInfo_->moneynessGridStrikes[i][j] = strike;\n                        Real stddev = std::sqrt(vol_->blackVariance(t, strike));\n                        callPricesMoneyness[i][j] = blackFormula(Option::Call, strike, forwards[i], stddev);\n                        calibrationInfo_->moneynessGridImpliedVolatility[i][j] = stddev / std::sqrt(t);\n                    } catch (const std::exception& e) {\n                        TLOG(\"error for time \" << t << \" moneyness \" << moneyness[j] << \": \" << e.what());\n                    }\n                }\n            }\n            if (!times.empty() && !moneyness.empty()) {\n                try {\n                    QuantExt::CarrMadanSurface cm(times, moneyness, eqIndex->equitySpot()->value(), forwards,\n                                                  callPricesMoneyness);\n                    for (Size i = 0; i < times.size(); ++i) {\n                        calibrationInfo_->moneynessGridProb[i] = cm.timeSlices()[i].density();\n                    }\n                    calibrationInfo_->moneynessGridCallSpreadArbitrage = cm.callSpreadArbitrage();\n                    calibrationInfo_->moneynessGridButterflyArbitrage = cm.butterflyArbitrage();\n                    calibrationInfo_->moneynessGridCalendarArbitrage = cm.calendarArbitrage();\n                    if (!cm.arbitrageFree())\n                        calibrationInfo_->isArbitrageFree = false;\n                    TLOG(\"Moneyness surface Arbitrage analysis result:\");\n                    TLOGGERSTREAM << arbitrageAsString(cm);\n                } catch (const std::exception& e) {\n                    TLOG(\"error: \" << e.what());\n                    calibrationInfo_->isArbitrageFree = false;\n                }\n                TLOG(\"Moneyness surface Arbitrage analysis completed:\");\n            }\n        }\n\n        DLOG(\"Building calibration info for eq vol surface completed.\");\n\n    } catch (std::exception& e) {\n        QL_FAIL(\"eq vol curve calibration info building failed: \" << e.what());\n    } catch (...) {\n        QL_FAIL(\"eq vol curve calibration info building failed: unknown error\");\n    }\n}\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "ca34f9c13a6f1de65db26d399e2bdadcb93a9211", "size": 63143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/marketdata/equityvolcurve.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": "OREData/ored/marketdata/equityvolcurve.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": "OREData/ored/marketdata/equityvolcurve.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": 52.6630525438, "max_line_length": 120, "alphanum_fraction": 0.5895190282, "num_tokens": 14062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.18926663399844798}}
{"text": "// Copyright (c) 2021, The Monero Project\n//\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//\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n//\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\n//    materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    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\n// EXPRESS 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\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// 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\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"multisig_account.h\"\n\n#include \"crypto/crypto.h\"\n#include \"cryptonote_config.h\"\n#include \"include_base_utils.h\"\n#include \"multisig.h\"\n#include \"multisig_kex_msg.h\"\n#include \"ringct/rctOps.h\"\n\n#include <boost/math/special_functions/binomial.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <limits>\n#include <memory>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n\n#undef MONERO_DEFAULT_LOG_CATEGORY\n#define MONERO_DEFAULT_LOG_CATEGORY \"multisig\"\n\nnamespace multisig\n{\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  * \n  * brief: calculate_multisig_keypair_from_derivation - wrapper on calculate_multisig_keypair() for an input public key\n  *    Converts an input public key into a crypto private key (type cast, does not change serialization),\n  *    then passes it to get_multisig_blinded_secret_key().\n  * \n  *    Result:\n  *      - privkey = H(derivation)\n  *      - pubkey = privkey * G\n  * param: derivation - a curve point\n  * outparam: derived_pubkey_out - public key of the resulting privkey\n  * return: multisig private key\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static crypto::secret_key calculate_multisig_keypair_from_derivation(const crypto::public_key_memsafe &derivation,\n    crypto::public_key &derived_pubkey_out)\n  {\n    crypto::secret_key blinded_skey = get_multisig_blinded_secret_key(rct::rct2sk(rct::pk2rct(derivation)));\n    CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(blinded_skey, derived_pubkey_out), \"Failed to derive public key\");\n\n    return blinded_skey;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: make_multisig_common_privkey - Create the 'common' multisig privkey, owned by all multisig participants.\n  *    - common privkey = H(sorted base common privkeys)\n  * param: participant_base_common_privkeys - Base common privkeys contributed by multisig participants.\n  * outparam: common_privkey_out - result\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static void make_multisig_common_privkey(std::vector<crypto::secret_key> participant_base_common_privkeys,\n    crypto::secret_key &common_privkey_out)\n  {\n    // sort the privkeys for consistency\n    //TODO: need a constant-time operator< for sorting secret keys\n    std::sort(participant_base_common_privkeys.begin(), participant_base_common_privkeys.end(),\n        [](const crypto::secret_key &key1, const crypto::secret_key &key2) -> bool\n        {\n          return memcmp(&key1, &key2, sizeof(crypto::secret_key)) < 0;\n        }\n      );\n\n    // privkey = H(sorted ancillary base privkeys)\n    crypto::hash_to_scalar(participant_base_common_privkeys.data(),\n      participant_base_common_privkeys.size()*sizeof(crypto::secret_key),\n      common_privkey_out);\n\n    CHECK_AND_ASSERT_THROW_MES(common_privkey_out != crypto::null_skey, \"Unexpected null secret key (danger!).\");\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  * \n  * brief: compute_multisig_aggregation_coefficient - creates aggregation coefficient for a specific public key in a set\n  *    of public keys\n  *    \n  *    WARNING: The coefficient will only be deterministic if...\n  *      1) input keys are pre-sorted\n  *         - tested here\n  *      2) input keys are in canonical form (compressed points in the prime-order subgroup of Ed25519)\n  *         - untested here for performance\n  * param: sorted_keys - set of component public keys that will be merged into a multisig public spend key\n  * param: aggregation_key - one of the component public keys\n  * return: aggregation coefficient\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static rct::key compute_multisig_aggregation_coefficient(const std::vector<crypto::public_key> &sorted_keys,\n    const crypto::public_key &aggregation_key)\n  {\n    CHECK_AND_ASSERT_THROW_MES(std::is_sorted(sorted_keys.begin(), sorted_keys.end()),\n      \"Keys for aggregation coefficient aren't sorted.\");\n\n    // aggregation key must be in sorted_keys\n    CHECK_AND_ASSERT_THROW_MES(std::find(sorted_keys.begin(), sorted_keys.end(), aggregation_key) != sorted_keys.end(),\n      \"Aggregation key expected to be in input keyset.\");\n\n    // aggregation coefficient salt\n    rct::key salt = rct::zero();\n    static_assert(sizeof(rct::key) >= sizeof(config::HASH_KEY_MULTISIG_KEY_AGGREGATION), \"Hash domain separator is too big.\");\n    memcpy(salt.bytes, config::HASH_KEY_MULTISIG_KEY_AGGREGATION, sizeof(config::HASH_KEY_MULTISIG_KEY_AGGREGATION));\n\n    // coeff = H(aggregation_key, sorted_keys, domain-sep)\n    rct::keyV data;\n    data.reserve(sorted_keys.size() + 2);\n    data.push_back(rct::pk2rct(aggregation_key));\n    for (const auto &key : sorted_keys)\n      data.push_back(rct::pk2rct(key));\n    data.push_back(salt);\n\n    // note: coefficient is considered public knowledge, no need to memwipe data\n    return rct::hash_to_scalar(data);\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  * \n  * brief: generate_multisig_aggregate_key - generates a multisig public spend key via key aggregation\n  *    Key aggregation via aggregation coefficients prevents key cancellation attacks.\n  *    See: https://www.getmonero.org/resources/research-lab/pubs/MRL-0009.pdf\n  * param: final_keys - address components (public keys) obtained from other participants (not shared with local)\n  * param: privkeys_inout - private keys of address components known by local; each key will be multiplied by an aggregation coefficient (return by reference)\n  * return: final multisig public spend key for the account\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static crypto::public_key generate_multisig_aggregate_key(std::vector<crypto::public_key> final_keys,\n    std::vector<crypto::secret_key> &privkeys_inout)\n  {\n    // collect all public keys that will go into the spend key (these don't need to be memsafe)\n    final_keys.reserve(final_keys.size() + privkeys_inout.size());\n\n    // 1. convert local multisig private keys to pub keys\n    // 2. insert to final keyset if not there yet\n    // 3. save the corresponding index of input priv key set for later reference\n    std::unordered_map<crypto::public_key, std::size_t> own_keys_mapping;\n\n    for (std::size_t multisig_keys_index{0}; multisig_keys_index < privkeys_inout.size(); ++multisig_keys_index)\n    {\n      crypto::public_key pubkey;\n      CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(privkeys_inout[multisig_keys_index], pubkey), \"Failed to derive public key\");\n\n      own_keys_mapping[pubkey] = multisig_keys_index;\n\n      final_keys.push_back(pubkey);\n    }\n\n    // sort input final keys for computing aggregation coefficients (lowest to highest)\n    // note: input should be sanitized (no duplicates)\n    std::sort(final_keys.begin(), final_keys.end());\n    CHECK_AND_ASSERT_THROW_MES(std::adjacent_find(final_keys.begin(), final_keys.end()) == final_keys.end(),\n        \"Unexpected duplicate found in input list.\");\n\n    // key aggregation\n    rct::key aggregate_key = rct::identity();\n\n    for (const crypto::public_key &key : final_keys)\n    {\n      // get aggregation coefficient\n      rct::key coeff = compute_multisig_aggregation_coefficient(final_keys, key);\n\n      // convert private key if possible\n      // note: retain original priv key index in input list, in case order matters upstream\n      auto found_key = own_keys_mapping.find(key);\n      if (found_key != own_keys_mapping.end())\n      {\n        // k_agg = coeff*k_base\n        sc_mul((unsigned char*)&(privkeys_inout[found_key->second]),\n          coeff.bytes,\n          (const unsigned char*)&(privkeys_inout[found_key->second]));\n\n        CHECK_AND_ASSERT_THROW_MES(privkeys_inout[found_key->second] != crypto::null_skey,\n          \"Multisig privkey with aggregation coefficient unexpectedly null.\");\n      }\n\n      // convert public key (pre-merge operation)\n      // K_agg = coeff*K_base\n      rct::key converted_pubkey = rct::scalarmultKey(rct::pk2rct(key), coeff);\n\n      // build aggregate key (merge operation)\n      rct::addKeys(aggregate_key, aggregate_key, converted_pubkey);\n    }\n\n    return rct::rct2pk(aggregate_key);\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: multisig_kex_make_next_msg - Construct a kex msg for any round > 1 of multisig key construction.\n  *    - Involves DH exchanges with pubkeys provided by other participants.\n  *    - Conserves mapping [pubkey -> DH derivation] : [origin keys of participants that share this secret with you].\n  * param: base_privkey - account's base private key, for performing DH exchanges and signing messages\n  * param: round - the round of the message that should be produced\n  * param: threshold - threshold for multisig (M in M-of-N)\n  * param: num_signers - number of participants in multisig (N)\n  * param: pubkey_origins_map - map between pubkeys to produce DH derivations with and identity keys of\n  *    participants who will share each derivation with you\n  * outparam: derivation_origins_map_out - map between DH derivations (shared secrets) and identity keys\n  *        - If msg is not for the last round, then these derivations are also stored in the output message\n  *          so they can be sent to other participants, who will make more DH derivations for the next kex round.\n  *        - If msg is for the last round, then these derivations won't be sent to other participants.\n  *          Instead, they are converted to share secrets (i.e. s = H(derivation)) and multiplied by G.\n  *          The keys s*G are sent to other participants in the message, so they can be used to produce the final\n  *          multisig key via generate_multisig_spend_public_key().\n  *            - The values s are the local account's shares of the final multisig key's private key. The caller can\n  *              compute those values with calculate_multisig_keypair_from_derivation() (or compute them directly).\n  * return: multisig kex message for the specified round\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static multisig_kex_msg multisig_kex_make_next_msg(const crypto::secret_key &base_privkey,\n    const std::uint32_t round,\n    const std::uint32_t threshold,\n    const std::uint32_t num_signers,\n    const std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> &pubkey_origins_map,\n    std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> &derivation_origins_map_out)\n  {\n    CHECK_AND_ASSERT_THROW_MES(num_signers > 1, \"Must be at least one other multisig signer.\");\n    CHECK_AND_ASSERT_THROW_MES(num_signers <= config::MULTISIG_MAX_SIGNERS,\n      \"Too many multisig signers specified (limit = 16 to prevent dangerous combinatorial explosion during key exchange).\");\n    CHECK_AND_ASSERT_THROW_MES(num_signers >= threshold,\n      \"Multisig threshold may not be larger than number of signers.\");\n    CHECK_AND_ASSERT_THROW_MES(threshold > 0, \"Multisig threshold must be > 0.\");\n    CHECK_AND_ASSERT_THROW_MES(round > 1, \"Round for next msg must be > 1.\");\n    CHECK_AND_ASSERT_THROW_MES(round <= multisig_kex_rounds_required(num_signers, threshold),\n      \"Trying to make key exchange message for an invalid round.\");\n\n    // make shared secrets with input pubkeys\n    std::vector<crypto::public_key> msg_pubkeys;\n    msg_pubkeys.reserve(pubkey_origins_map.size());\n    derivation_origins_map_out.clear();\n\n    for (const auto &pubkey_and_origins : pubkey_origins_map)\n    {\n      // D = 8 * k_base * K_pubkey\n      // note: must be mul8 (cofactor), otherwise it is possible to leak to a malicious participant if the local\n      //       base_privkey is a multiple of 8 or not\n      // note2: avoid making temporaries that won't be memwiped\n      rct::key derivation_rct;\n      auto a_wiper = epee::misc_utils::create_scope_leave_handler([&]{\n        memwipe(&derivation_rct, sizeof(rct::key));\n      });\n\n      rct::scalarmultKey(derivation_rct, rct::pk2rct(pubkey_and_origins.first), rct::sk2rct(base_privkey));\n      rct::scalarmultKey(derivation_rct, derivation_rct, rct::EIGHT);\n\n      crypto::public_key_memsafe derivation{rct::rct2pk(derivation_rct)};\n\n      // retain mapping between pubkey's origins and the DH derivation\n      // note: if msg for last round, then caller must know how to handle these derivations properly\n      derivation_origins_map_out[derivation] = pubkey_and_origins.second;\n\n      // if the last round, convert derivations to public keys for the output message\n      if (round == multisig_kex_rounds_required(num_signers, threshold))\n      {\n        // derived_pubkey = H(derivation)*G\n        crypto::public_key derived_pubkey;\n        calculate_multisig_keypair_from_derivation(derivation, derived_pubkey);\n        msg_pubkeys.push_back(derived_pubkey);\n      }\n      // otherwise, put derivations in message directly, so other signers can in turn create derivations (shared secrets)\n      //  with them for the next round\n      else\n        msg_pubkeys.push_back(derivation);\n    }\n\n    return multisig_kex_msg{round, base_privkey, std::move(msg_pubkeys)};\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: multisig_kex_msgs_sanitize_pubkeys - Sanitize multisig kex messages.\n  *    - Removes duplicates from msg pubkeys, ignores pubkeys equal to the local account's signing key,\n  *      ignores messages signed by the local account, ignores keys found in input 'exclusion set',\n  *      constructs map of pubkey:origins.\n  *    - Requires that all input msgs have the same round number.\n  *\n  *    origins = all the signing pubkeys that recommended a given pubkey found in input msgs\n  *\n  *    - If the messages' round numbers are all '1', then only the message signing pubkey is considered\n  *      'recommended'. Furthermore, the 'exclusion set' is ignored.\n  * param: own_pubkey - local account's signing key (key used to sign multisig messages)\n  * param: expanded_msgs - set of multisig kex messages to process\n  * param: exclude_pubkeys - pubkeys to exclude from output set\n  * outparam: sanitized_pubkeys_out - processed pubkeys obtained from msgs, mapped to their origins\n  * return: round number shared by all input msgs\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static std::uint32_t multisig_kex_msgs_sanitize_pubkeys(const crypto::public_key &own_pubkey,\n    const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::vector<crypto::public_key> &exclude_pubkeys,\n    std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> &sanitized_pubkeys_out)\n  {\n    CHECK_AND_ASSERT_THROW_MES(expanded_msgs.size() > 0, \"At least one input message expected.\");\n\n    std::uint32_t round = expanded_msgs[0].get_round();\n    sanitized_pubkeys_out.clear();\n\n    // get all pubkeys from input messages, add them to pubkey:origins map\n    // - origins = all the signing pubkeys that recommended a given msg pubkey\n    for (const auto &expanded_msg : expanded_msgs)\n    {\n      CHECK_AND_ASSERT_THROW_MES(expanded_msg.get_round() == round, \"All messages must have the same kex round number.\");\n\n      // ignore messages from self\n      if (expanded_msg.get_signing_pubkey() == own_pubkey)\n        continue;\n\n      // in round 1, only the signing pubkey is treated as a msg pubkey\n      if (round == 1)\n      {\n        // note: ignores duplicates\n        sanitized_pubkeys_out[expanded_msg.get_signing_pubkey()].insert(expanded_msg.get_signing_pubkey());\n      }\n      // in other rounds, only the msg pubkeys are treated as msg pubkeys\n      else\n      {\n        // copy all pubkeys from message into list\n        for (const auto &pubkey : expanded_msg.get_msg_pubkeys())\n        {\n          // ignore own pubkey\n          if (pubkey == own_pubkey)\n            continue;\n\n          // ignore pubkeys in 'ignore' set\n          if (std::find(exclude_pubkeys.begin(), exclude_pubkeys.end(), pubkey) != exclude_pubkeys.end())\n            continue;\n\n          // note: ignores duplicates\n          sanitized_pubkeys_out[pubkey].insert(expanded_msg.get_signing_pubkey());\n        }\n      }\n    }\n\n    return round;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: evaluate_multisig_kex_round_msgs - Evaluate pubkeys from a kex round in order to prepare for the next round.\n  *    - Sanitizes input msgs.\n  *    - Require uniqueness in: 'signers', 'exclude_pubkeys'.\n  *    - Requires each input pubkey be recommended by 'num_recommendations = expected_round' msg signers.\n  *      - For a final multisig key to be truly 'M-of-N', each of the the private key's components must be\n  *        shared by (N - M + 1) signers.\n  *    - Requires that msgs are signed by only keys in 'signers'.\n  *    - Requires that each key in 'signers' recommends [num_signers - 2 CHOOSE (expected_round - 1)] pubkeys.\n  *      - These should be derivations each signer recommends for round 'expected_round', excluding derivations shared\n  *        with the local account.\n  *    - Requires that 'exclude_pubkeys' has [num_signers - 1 CHOOSE (expected_round - 1)] pubkeys.\n  *      - These should be derivations the local account has corresponding to round 'expected_round'.\n  * param: base_privkey - multisig account's base private key\n  * param: expected_round - expected kex round of input messages\n  * param: threshold - threshold for multisig (M in M-of-N)\n  * param: signers - expected participants in multisig kex\n  * param: expanded_msgs - set of multisig kex messages to process\n  * param: exclude_pubkeys - derivations held by the local account corresponding to round 'expected_round'\n  * return: fully sanitized and validated pubkey:origins map for building the account's next kex round message\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> evaluate_multisig_kex_round_msgs(\n    const crypto::public_key &base_pubkey,\n    const std::uint32_t expected_round,\n    const std::uint32_t threshold,\n    const std::vector<crypto::public_key> &signers,\n    const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::vector<crypto::public_key> &exclude_pubkeys)\n  {\n    CHECK_AND_ASSERT_THROW_MES(signers.size() > 1, \"Must be at least one other multisig signer.\");\n    CHECK_AND_ASSERT_THROW_MES(signers.size() <= config::MULTISIG_MAX_SIGNERS,\n      \"Too many multisig signers specified (limit = 16 to prevent dangerous combinatorial explosion during key exchange).\");\n    CHECK_AND_ASSERT_THROW_MES(signers.size() >= threshold, \"Multisig threshold may not be larger than number of signers.\");\n    CHECK_AND_ASSERT_THROW_MES(threshold > 0, \"Multisig threshold must be > 0.\");\n    CHECK_AND_ASSERT_THROW_MES(expected_round > 0, \"Expected round must be > 0.\");\n    CHECK_AND_ASSERT_THROW_MES(expected_round <= multisig_kex_rounds_required(signers.size(), threshold),\n      \"Expecting key exchange messages for an invalid round.\");\n\n    std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> pubkey_origins_map;\n\n    // leave early in the last round of 1-of-N, where all signers share a key so the local signer doesn't care about\n    // recommendations from other signers\n    if (threshold == 1 && expected_round == multisig_kex_rounds_required(signers.size(), threshold))\n      return pubkey_origins_map;\n\n    // exclude_pubkeys should all be unique\n    for (auto it = exclude_pubkeys.begin(); it != exclude_pubkeys.end(); ++it)\n    {\n      CHECK_AND_ASSERT_THROW_MES(std::find(exclude_pubkeys.begin(), it, *it) == it,\n        \"Found duplicate pubkeys for exclusion unexpectedly.\");\n    }\n\n    // sanitize input messages\n    std::uint32_t round = multisig_kex_msgs_sanitize_pubkeys(base_pubkey, expanded_msgs, exclude_pubkeys, pubkey_origins_map);\n    CHECK_AND_ASSERT_THROW_MES(round == expected_round,\n      \"Kex messages were for round [\" << round << \"], but expected round is [\" << expected_round << \"]\");\n\n    // evaluate pubkeys collected\n    std::unordered_map<crypto::public_key, std::unordered_set<crypto::public_key>> origin_pubkeys_map;\n\n    // 1. each pubkey should be recommended by a precise number of signers\n    for (const auto &pubkey_and_origins : pubkey_origins_map)\n    {\n      // expected amount = round_num\n      // With each successive round, pubkeys are shared by incrementally larger groups,\n      //  starting at 1 in round 1 (i.e. the local multisig key to start kex with).\n      CHECK_AND_ASSERT_THROW_MES(pubkey_and_origins.second.size() == round,\n        \"A pubkey recommended by multisig kex messages had an unexpected number of recommendations.\");\n\n      // map (sanitized) pubkeys back to origins\n      for (const auto &origin : pubkey_and_origins.second)\n        origin_pubkeys_map[origin].insert(pubkey_and_origins.first);\n    }\n\n    // 2. the number of unique signers recommending pubkeys should equal the number of signers passed in (minus the local signer)\n    CHECK_AND_ASSERT_THROW_MES(origin_pubkeys_map.size() == signers.size() - 1,\n      \"Number of unique other signers does not equal number of other signers that recommended pubkeys.\");\n\n    // 3. each origin should recommend a precise number of pubkeys\n\n    // TODO: move to a 'math' library, with unit tests\n    auto n_choose_k_f =\n      [](const std::uint32_t n, const std::uint32_t k) -> std::uint32_t\n      {\n        static_assert(std::numeric_limits<std::int32_t>::digits <= std::numeric_limits<double>::digits,\n          \"n_choose_k requires no rounding issues when converting between int32 <-> double.\");\n\n        if (n < k)\n          return 0;\n\n        double fp_result = boost::math::binomial_coefficient<double>(n, k);\n\n        if (fp_result < 0)\n          return 0;\n\n        if (fp_result > std::numeric_limits<std::int32_t>::max())  // note: std::round() returns std::int32_t\n          return 0;\n\n        return static_cast<std::uint32_t>(std::round(fp_result));\n      };\n\n    // other signers: (N - 2) choose (msg_round_num - 1)\n      // - Each signer recommends keys they share with other signers.\n      // - In each round, a signer shares a key with 'round num - 1' other signers.\n      // - Since 'origins pubkey map' excludes keys shared with the local account,\n      //   only keys shared with participants 'other than local and self' will be in the map (e.g. N - 2 signers).\n      // - So other signers will recommend (N - 2) choose (msg_round_num - 1) pubkeys (after removing keys shared with local).\n      // - Each origin should have a shared key with each group of size 'round - 1'.\n      // Note: Keys shared with local are ignored to facilitate kex round boosting, where one or more signers may\n      //       have boosted the local signer (implying they didn't have access to the local signer's previous round msg).\n    std::uint32_t expected_recommendations_others = n_choose_k_f(signers.size() - 2, round - 1);\n\n    // local: (N - 1) choose (msg_round_num - 1)\n    std::uint32_t expected_recommendations_self = n_choose_k_f(signers.size() - 1, round - 1);\n\n    // note: expected_recommendations_others would be 0 in the last round of 1-of-N, but we return early for that case\n    CHECK_AND_ASSERT_THROW_MES(expected_recommendations_self > 0 && expected_recommendations_others > 0,\n      \"Bad num signers or round num (possibly numerical limits exceeded).\");\n\n    // check that local account recommends expected number of keys\n    CHECK_AND_ASSERT_THROW_MES(exclude_pubkeys.size() == expected_recommendations_self,\n      \"Local account did not recommend expected number of multisig keys.\");\n\n    // check that other signers recommend expected number of keys\n    for (const auto &origin_and_pubkeys : origin_pubkeys_map)\n    {\n      CHECK_AND_ASSERT_THROW_MES(origin_and_pubkeys.second.size() == expected_recommendations_others,\n        \"A pubkey recommended by multisig kex messages had an unexpected number of recommendations.\");\n\n      // 2 (continued). only expected signers should be recommending keys\n      CHECK_AND_ASSERT_THROW_MES(std::find(signers.begin(), signers.end(), origin_and_pubkeys.first) != signers.end(),\n        \"Multisig kex message with unexpected signer encountered.\");\n    }\n\n    // note: above tests implicitly detect if the total number of recommended keys is correct or not\n    return pubkey_origins_map;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: multisig_kex_process_round - Process kex messages for the active kex round.\n  *    - A wrapper around evaluate_multisig_kex_round_msgs() -> multisig_kex_make_next_msg().\n  *      - In other words, evaluate the input messages and try to make a message for the next round.\n  *    - Note: Must be called on the final round's msgs to evaluate the final key components\n  *            recommended by other participants.\n  * param: base_privkey - multisig account's base private key\n  * param: current_round - round of kex the input messages should be designed for\n  * param: threshold - threshold for multisig (M in M-of-N)\n  * param: signers - expected participants in multisig kex\n  * param: expanded_msgs - set of multisig kex messages to process\n  * param: exclude_pubkeys - keys held by the local account corresponding to round 'current_round'\n  *    - If 'current_round' is the final round, these are the local account's shares of the final aggregate key.\n  * outparam: keys_to_origins_map_out - map between round keys and identity keys\n  *    - If in the final round, these are key shares recommended by other signers for the final aggregate key.\n  *    - Otherwise, these are the local account's DH derivations for the next round.\n  *      - See multisig_kex_make_next_msg() for an explanation.\n  * return: multisig kex message for next round, or empty message if 'current_round' is the final round\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static multisig_kex_msg multisig_kex_process_round(const crypto::secret_key &base_privkey,\n    const crypto::public_key &base_pubkey,\n    const std::uint32_t current_round,\n    const std::uint32_t threshold,\n    const std::vector<crypto::public_key> &signers,\n    const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::vector<crypto::public_key> &exclude_pubkeys,\n    std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> &keys_to_origins_map_out)\n  {\n    // evaluate messages\n    std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> evaluated_pubkeys =\n      evaluate_multisig_kex_round_msgs(base_pubkey, current_round, threshold, signers, expanded_msgs, exclude_pubkeys);\n\n    // produce message for next round (if there is one)\n    if (current_round < multisig_kex_rounds_required(signers.size(), threshold))\n    {\n      return multisig_kex_make_next_msg(base_privkey,\n        current_round + 1,\n        threshold,\n        signers.size(),\n        evaluated_pubkeys,\n        keys_to_origins_map_out);\n    }\n    else\n    {\n      // no more rounds, so collect the key shares recommended by other signers for the final aggregate key\n      keys_to_origins_map_out.clear();\n      keys_to_origins_map_out = std::move(evaluated_pubkeys);\n\n      return multisig_kex_msg{};\n    }\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_account: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  void multisig_account::initialize_kex_update(const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::uint32_t rounds_required,\n    std::vector<crypto::public_key> &exclude_pubkeys_out)\n  {\n    if (m_kex_rounds_complete == 0)\n    {\n      // the first round of kex msgs will contain each participant's base pubkeys and ancillary privkeys\n\n      // collect participants' base common privkey shares\n      // note: duplicate privkeys are acceptable, and duplicates due to duplicate signers\n      //       will be blocked by duplicate-signer errors after this function is called\n      std::vector<crypto::secret_key> participant_base_common_privkeys;\n      participant_base_common_privkeys.reserve(expanded_msgs.size() + 1);\n\n      // add local ancillary base privkey\n      participant_base_common_privkeys.emplace_back(m_base_common_privkey);\n\n      // add other signers' base common privkeys\n      for (const auto &expanded_msg : expanded_msgs)\n      {\n        if (expanded_msg.get_signing_pubkey() != m_base_pubkey)\n        {\n          participant_base_common_privkeys.emplace_back(expanded_msg.get_msg_privkey());\n        }\n      }\n\n      // make common privkey\n      make_multisig_common_privkey(std::move(participant_base_common_privkeys), m_common_privkey);\n\n      // set common pubkey\n      CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(m_common_privkey, m_common_pubkey),\n        \"Failed to derive public key\");\n\n      // if N-of-N, then the base privkey will be used directly to make the account's share of the final key\n      if (rounds_required == 1)\n      {\n        m_multisig_privkeys.clear();\n        m_multisig_privkeys.emplace_back(m_base_privkey);\n      }\n\n      // exclude all keys the local account recommends\n      // - in the first round, only the local pubkey is recommended by the local signer\n      exclude_pubkeys_out.emplace_back(m_base_pubkey);\n    }\n    else\n    {\n      // in other rounds, kex msgs will contain participants' shared keys\n\n      // ignore shared keys the account helped create for this round\n      for (const auto &shared_key_with_origins : m_kex_keys_to_origins_map)\n      {\n        exclude_pubkeys_out.emplace_back(shared_key_with_origins.first);\n      }\n    }\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_account: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  void multisig_account::finalize_kex_update(const std::uint32_t rounds_required,\n    std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> result_keys_to_origins_map)\n  {\n    // prepare for next round (or complete the multisig account fully)\n    if (rounds_required == m_kex_rounds_complete + 1)\n    {\n      // finished (have set of msgs to complete address)\n\n      // when 'completing the final round', result keys are other signers' shares of the final key\n      std::vector<crypto::public_key> result_keys;\n      result_keys.reserve(result_keys_to_origins_map.size());\n\n      for (const auto &result_key_and_origins : result_keys_to_origins_map)\n      {\n        result_keys.emplace_back(result_key_and_origins.first);\n      }\n\n      // compute final aggregate key, update local multisig privkeys with aggregation coefficients applied\n      m_multisig_pubkey = generate_multisig_aggregate_key(std::move(result_keys), m_multisig_privkeys);\n\n      // no longer need the account's pubkeys saved for this round (they were only used to build exclude_pubkeys)\n      // TODO: record [pre-aggregation pubkeys : origins] map for aggregation-style signing\n      m_kex_keys_to_origins_map.clear();\n    }\n    else if (rounds_required == m_kex_rounds_complete + 2)\n    {\n      // one more round (must send/receive one more set of kex msgs)\n      // - at this point, have local signer's pre-aggregation private key shares of the final address\n\n      // result keys are the local signer's DH derivations for the next round\n\n      // derivations are shared secrets between each group of N - M + 1 signers of which the local account is a member\n      // - convert them to private keys: multisig_key = H(derivation)\n      // - note: shared key = multisig_key[i]*G is recorded in the kex msg for sending to other participants\n      //   instead of the original 'derivation' value (which MUST be kept secret!)\n      m_multisig_privkeys.clear();\n      m_multisig_privkeys.reserve(result_keys_to_origins_map.size());\n\n      m_kex_keys_to_origins_map.clear();\n\n      for (const auto &derivation_and_origins : result_keys_to_origins_map)\n      {\n        // multisig_privkey = H(derivation)\n        // derived pubkey = multisig_key * G\n        crypto::public_key_memsafe derived_pubkey;\n        m_multisig_privkeys.push_back(\n          calculate_multisig_keypair_from_derivation(derivation_and_origins.first, derived_pubkey));\n\n        // save the account's kex key mappings for this round [derived pubkey : other signers who will have the same key]\n        m_kex_keys_to_origins_map[derived_pubkey] = std::move(derivation_and_origins.second);\n      }\n    }\n    else\n    {\n      // next round is an 'intermediate' key exchange round, so there is nothing special to do here\n\n      // save the account's kex keys for this round [DH derivation : other signers who will have the same derivation]\n      m_kex_keys_to_origins_map = std::move(result_keys_to_origins_map);\n    }\n\n    // a full set of msgs has been collected and processed, so the 'round is complete'\n    ++m_kex_rounds_complete;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_account: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  void multisig_account::kex_update_impl(const std::vector<multisig_kex_msg> &expanded_msgs)\n  {\n    CHECK_AND_ASSERT_THROW_MES(expanded_msgs.size() > 0, \"No key exchange messages passed in.\");\n\n    const std::uint32_t rounds_required = multisig_kex_rounds_required(m_signers.size(), m_threshold);\n    CHECK_AND_ASSERT_THROW_MES(rounds_required > 0, \"Multisig kex rounds required unexpectedly 0.\");\n\n    // initialize account update\n    std::vector<crypto::public_key> exclude_pubkeys;\n    initialize_kex_update(expanded_msgs, rounds_required, exclude_pubkeys);\n\n    // evaluate messages and get this account's kex msg for the next round\n    std::unordered_map<crypto::public_key_memsafe, std::unordered_set<crypto::public_key>> result_keys_to_origins_map;\n\n    m_next_round_kex_message = multisig_kex_process_round(\n      m_base_privkey,\n      m_base_pubkey,\n      m_kex_rounds_complete + 1,\n      m_threshold,\n      m_signers,\n      expanded_msgs,\n      exclude_pubkeys,\n      result_keys_to_origins_map).get_msg();\n\n    // finish account update\n    finalize_kex_update(rounds_required, std::move(result_keys_to_origins_map));\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n} //namespace multisig\n", "meta": {"hexsha": "0a0ca7bdc9aa622b4e3b29e44c222fc5919f3e68", "size": 37524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multisig/multisig_account_kex_impl.cpp", "max_stars_repo_name": "bojanskr/monero", "max_stars_repo_head_hexsha": "67e5ca9ad6f1c861ad315476a88f9d36c38a0abb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T04:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T04:57:34.000Z", "max_issues_repo_path": "src/multisig/multisig_account_kex_impl.cpp", "max_issues_repo_name": "bojanskr/monero", "max_issues_repo_head_hexsha": "67e5ca9ad6f1c861ad315476a88f9d36c38a0abb", "max_issues_repo_licenses": ["MIT"], "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/multisig/multisig_account_kex_impl.cpp", "max_forks_repo_name": "bojanskr/monero", "max_forks_repo_head_hexsha": "67e5ca9ad6f1c861ad315476a88f9d36c38a0abb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.6148555708, "max_line_length": 158, "alphanum_fraction": 0.6686387379, "num_tokens": 8463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.18905217566436747}}
{"text": "#include \"nmos/capabilities.h\"\n\n#include <boost/range/adaptor/transformed.hpp>\n#include \"nmos/json_fields.h\"\n\nnamespace nmos\n{\n    web::json::value make_caps_string_constraint(const std::vector<utility::string_t>& enum_values)\n    {\n        using web::json::value_of;\n        using web::json::value_from_elements;\n        return value_of({\n            { !enum_values.empty() ? nmos::fields::constraint_enum.key : U(\"\"), value_from_elements(enum_values) }\n        });\n    }\n\n    web::json::value make_caps_integer_constraint(const std::vector<int64_t>& enum_values, int64_t minimum, int64_t maximum)\n    {\n        using web::json::value_of;\n        using web::json::value_from_elements;\n        return value_of({\n            { !enum_values.empty() ? nmos::fields::constraint_enum.key : U(\"\"), value_from_elements(enum_values) },\n            { minimum != no_minimum<int64_t>() ? nmos::fields::constraint_minimum.key : U(\"\"), minimum },\n            { maximum != no_maximum<int64_t>() ? nmos::fields::constraint_maximum.key : U(\"\"), maximum }\n        });\n    }\n\n    web::json::value make_caps_number_constraint(const std::vector<double>& enum_values, double minimum, double maximum)\n    {\n        using web::json::value_of;\n        using web::json::value_from_elements;\n        return value_of({\n            { !enum_values.empty() ? nmos::fields::constraint_enum.key : U(\"\"), value_from_elements(enum_values) },\n            { minimum != no_minimum<double>() ? nmos::fields::constraint_minimum.key : U(\"\"), minimum },\n            { maximum != no_maximum<double>() ? nmos::fields::constraint_maximum.key : U(\"\"), maximum }\n        });\n    }\n\n    web::json::value make_caps_boolean_constraint(const std::vector<bool>& enum_values)\n    {\n        using web::json::value_of;\n        using web::json::value_from_elements;\n        return value_of({\n            { !enum_values.empty() ? nmos::fields::constraint_enum.key : U(\"\"), value_from_elements(enum_values) }\n        });\n    }\n\n    web::json::value make_caps_rational_constraint(const std::vector<nmos::rational>& enum_values, const nmos::rational& minimum, const nmos::rational& maximum)\n    {\n        using web::json::value_of;\n        using web::json::value_from_elements;\n        return value_of({\n            { !enum_values.empty() ? nmos::fields::constraint_enum.key : U(\"\"), value_from_elements(enum_values | boost::adaptors::transformed([](const nmos::rational& r) { return make_rational(r); })) },\n            { minimum != no_minimum<nmos::rational>() ? nmos::fields::constraint_minimum.key : U(\"\"), make_rational(minimum) },\n            { maximum != no_maximum<nmos::rational>() ? nmos::fields::constraint_maximum.key : U(\"\"), make_rational(maximum) }\n        });\n    }\n\n    namespace details\n    {\n        // cf. nmos::details::make_constraints_schema in nmos/connection_api.cpp \n        template <typename T, typename Parse>\n        bool match_constraint(const T& value, const web::json::value& constraint, Parse parse)\n        {\n            if (constraint.has_field(nmos::fields::constraint_enum))\n            {\n                const auto& enum_values = nmos::fields::constraint_enum(constraint).as_array();\n                if (enum_values.end() == std::find_if(enum_values.begin(), enum_values.end(), [&parse, &value](const web::json::value& enum_value)\n                {\n                    return parse(enum_value) == value;\n                }))\n                {\n                    return false;\n                }\n            }\n            if (constraint.has_field(nmos::fields::constraint_minimum))\n            {\n                const auto& minimum = nmos::fields::constraint_minimum(constraint);\n                if (parse(minimum) > value)\n                {\n                    return false;\n                }\n            }\n            if (constraint.has_field(nmos::fields::constraint_maximum))\n            {\n                const auto& maximum = nmos::fields::constraint_maximum(constraint);\n                if (parse(maximum) < value)\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n    }\n\n    bool match_string_constraint(const utility::string_t& value, const web::json::value& constraint)\n    {\n        return details::match_constraint(value, constraint, [](const web::json::value& enum_value)\n        {\n            return enum_value.as_string();\n        });\n    }\n\n    bool match_integer_constraint(int64_t value, const web::json::value& constraint)\n    {\n        return details::match_constraint(value, constraint, [&value](const web::json::value& enum_value)\n        {\n            return enum_value.as_integer();\n        });\n    }\n\n    bool match_number_constraint(double value, const web::json::value& constraint)\n    {\n        return details::match_constraint(value, constraint, [&value](const web::json::value& enum_value)\n        {\n            return enum_value.as_double();\n        });\n    }\n\n    bool match_boolean_constraint(bool value, const web::json::value& constraint)\n    {\n        return details::match_constraint(value, constraint, [&value](const web::json::value& enum_value)\n        {\n            return enum_value.as_bool();\n        });\n    }\n\n    bool match_rational_constraint(const nmos::rational& value, const web::json::value& constraint)\n    {\n        return details::match_constraint(value, constraint, [&value](const web::json::value& enum_value)\n        {\n            return nmos::parse_rational(enum_value);\n        });\n    }\n}\n", "meta": {"hexsha": "4ba723e2c17d66a35f0c15e54096450bc9404c49", "size": 5496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Development/nmos/capabilities.cpp", "max_stars_repo_name": "rayli-hlit/nmos-cpp", "max_stars_repo_head_hexsha": "c3f0cf7b31fca669e3523251d1ec39c6b2ac7acb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2017-09-19T06:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:40:42.000Z", "max_issues_repo_path": "Development/nmos/capabilities.cpp", "max_issues_repo_name": "rayli-hlit/nmos-cpp", "max_issues_repo_head_hexsha": "c3f0cf7b31fca669e3523251d1ec39c6b2ac7acb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 200.0, "max_issues_repo_issues_event_min_datetime": "2018-02-22T17:40:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T18:53:21.000Z", "max_forks_repo_path": "Development/nmos/capabilities.cpp", "max_forks_repo_name": "alanb-sony/nmos-cpp", "max_forks_repo_head_hexsha": "677fd9ddf6a11cf1fb53eddf9375e8b56d1eb83f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2017-09-20T08:13:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:27:08.000Z", "avg_line_length": 40.4117647059, "max_line_length": 204, "alphanum_fraction": 0.5987991266, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.18902097608368892}}
{"text": "//\n// ini_settings.cpp - ini settings implementation\n//\n// leccore library, part of the liblec library\n// Copyright (c) 2019 Alec Musasa (alecmus at live dot com)\n//\n// Released under the MIT license. For full details see the\n// file LICENSE.txt\n//\n\n#include \"../settings.h\"\n#include \"../leccore_common.h\"\n#include \"../app_version_info.h\"\n#include \"../encode.h\"\n#include \"../hash.h\"\n#include \"../encrypt.h\"\n#include \"../encode.h\"\n\n#include <filesystem>\n\n#include <Windows.h>\n#include <ShlObj.h>\t// for SHGetFolderPathA\n#include <comdef.h>\t// for _com_error\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n\nusing namespace liblec::leccore;\n\nclass ini_settings::impl {\npublic:\n\tconst std::string _default_file_name = \"config.ini\";\n\tconst std::string _file_name;\n\tconst std::string _key;\n\tconst std::string _iv;\n\tconst bool _encrypted;\n\tconst int _salt_length = 4;\n\tstd::string _ini_path;\n\tbool _ini_path_set;\n\n\timpl(const std::string& file_name,\n\t\tconst std::string& key,\n\t\tconst std::string& iv) :\n\t\t_file_name(file_name.empty() ? _default_file_name : file_name),\n\t\t_key(key),\n\t\t_iv(iv),\n\t\t_encrypted(!_key.empty() && !_iv.empty()),\n\t\t_ini_path_set(false) {}\n\t~impl() {}\n\n\tbool encrypt_string(const std::string& plain,\n\t\tstd::string& encrypted,\n\t\tstd::string& error) {\n\t\terror.clear();\n\t\tencrypted.clear();\n\t\t// make random salt (makes the encoded and encrypted results different for the same input)\n\t\tconst std::string salt = hash_string::random_string(_salt_length);\n\n\t\t// encode the salt and plain text to base64\n\t\tstd::string encoded = base64::encode(salt + plain);\n\n\t\t// encrypt the encoded text\n\t\taes enc(_key, _iv);\n\t\treturn enc.encrypt(encoded, encrypted, error);\n\t}\n\n\tbool decrypt_string(const std::string& encrypted,\n\t\tstd::string& decrypted,\n\t\tstd::string& error) {\n\t\terror.clear();\n\t\tdecrypted.clear();\n\t\t// decrypt the text\n\t\tstd::string encoded;\n\t\taes enc(_key, _iv);\n\t\tif (!enc.decrypt(encrypted, encoded, error))\n\t\t\treturn false;\n\n\t\t// decode the decrypted text\n\t\tbase64 base64_encoder;\n\t\tdecrypted = base64_encoder.decode(encoded);\n\n\t\t// step over the salt\n\t\tdecrypted = decrypted.substr(_salt_length);\n\t\treturn true;\n\t}\n\n\tstatic bool erase_path(boost::property_tree::ptree& pt,\n\t\tconst boost::property_tree::ptree::key_type& key_path,\n\t\tsize_t& erased_subkeys,\n\t\tstd::string& error) {\n\t\terror.clear();\n\t\ttry {\n\t\t\tboost::property_tree::ptree* p_sub_tree = &pt;\n\t\t\tboost::property_tree::ptree::path_type path(key_path);\n\t\t\tboost::property_tree::ptree::key_type parent_path;\n\t\t\tboost::property_tree::ptree::key_type sub_key;\n\n\t\t\twhile (!path.single()) {\n\t\t\t\tsub_key = path.reduce();\n\t\t\t\tparent_path = parent_path.empty() ? sub_key :\n\t\t\t\t\tparent_path + path.separator() + sub_key;\n\t\t\t\tp_sub_tree = &(p_sub_tree->get_child(sub_key));\n\t\t\t}\n\n\t\t\tsub_key = path.reduce();\n\t\t\tconst auto _count = p_sub_tree->erase(sub_key);\n\t\t\terased_subkeys += _count;\n\t\t\tif (_count == 0)\n\t\t\t\treturn true;\n\t\t\t\n\t\t\tif (p_sub_tree->empty() && !parent_path.empty())\n\t\t\t\treturn erase_path(pt, parent_path, erased_subkeys, error);\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\tcatch (const std::exception& e) {\n\t\t\terror = e.what();\n\t\t\treturn false;\n\t\t}\n\t}\n};\n\nini_settings::ini_settings(const std::string& file_name) : ini_settings(file_name, \"\", \"\") {}\nini_settings::ini_settings(const std::string& file_name, const std::string& key,\n\tconst std::string& iv) : _d(*new impl(file_name, key, iv)) {}\nini_settings::~ini_settings() { delete& _d; }\n\nbool ini_settings::get_ini_path(std::string& ini_path, std::string& error) {\n\terror.clear();\n\tini_path.clear();\n\tif (!_d._ini_path_set && _d._ini_path.empty()) {\n\t\tapp_version_info ver_info;\n\n\t\tstd::string company_name, app_name;\n\t\tif (!ver_info.get_company_name(company_name, error))\n\t\t\treturn false;\n\n\t\tif (!ver_info.get_app_name(app_name, error))\n\t\t\treturn false;\n\n\t\tauto get_app_data = [](std::string& app_data_folder, std::string& error)->bool {\n\t\t\tapp_data_folder.clear();\n\t\t\tCHAR szPath[MAX_PATH];\n\t\t\tHRESULT result = SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, szPath);\n\t\t\t\n\t\t\tif (FAILED(result)) {\n\t\t\t\terror = convert_string(_com_error(result).ErrorMessage());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tapp_data_folder = szPath;\n\t\t\treturn true;\n\t\t};\n\n\t\t// get appdata folder\n\t\tstd::string app_data_folder;\n\t\tif (!get_app_data(app_data_folder, error))\n\t\t\treturn false;\n\n\t\t_d._ini_path = app_data_folder + \"\\\\\" +\n\t\t\tcompany_name + \"\\\\\" +\n\t\t\tapp_name;\n\t}\n\tini_path = _d._ini_path;\n\treturn true;\n}\n\nvoid ini_settings::set_ini_path(const std::string& ini_path) {\n\t_d._ini_path = ini_path;\n\t_d._ini_path_set = true;\n}\n\nbool ini_settings::write_value(const std::string& branch,\n\tconst std::string& value_name, const std::string& value, std::string& error) {\n\terror.clear();\n\tstd::string ini_path;\n\tif (!get_ini_path(ini_path, error))\n\t\treturn false;\n\n\tconst std::string full_ini_file_path = ini_path.empty() ?\n\t\t_d._file_name : ini_path + \"\\\\\" + _d._file_name;\n\n\tstd::string _path = value_name;\n\n\tif (!branch.empty())\n\t\t_path = branch + \".\" + _path;\n\n\ttry {\n\t\tif (!ini_path.empty()) {\n\t\t\tstd::filesystem::path path(ini_path);\n\t\t\tstd::filesystem::create_directories(path);\n\t\t}\n\n\t\tboost::property_tree::ptree pt;\n\n\t\tstd::filesystem::path file(full_ini_file_path);\n\t\tif (std::filesystem::is_regular_file(file))\n\t\t\tboost::property_tree::ini_parser::read_ini(full_ini_file_path, pt);\n\n\t\tif (_d._encrypted) {\n\t\t\tstd::string data_encrypted;\n\t\t\tif (!_d.encrypt_string(value, data_encrypted, error))\n\t\t\t\treturn false;\n\n\t\t\tstd::string encoded = base32::encode(data_encrypted);\n\t\t\tpt.put(_path, encoded);\n\t\t\tboost::property_tree::write_ini(full_ini_file_path, pt);\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\tpt.put(_path, value);\n\t\t\tboost::property_tree::write_ini(full_ini_file_path, pt);\n\t\t\treturn true;\n\t\t}\n\t}\n\tcatch (const std::exception& e) {\n\t\terror = e.what();\n\t\treturn false;\n\t}\n}\n\nbool ini_settings::read_value(const std::string& branch,\n\tconst std::string& value_name, std::string& value, std::string& error) {\n\terror.clear();\n\tvalue.clear();\n\tstd::string ini_path;\n\tif (!get_ini_path(ini_path, error))\n\t\treturn false;\n\n\tconst std::string full_ini_file_path = ini_path.empty() ?\n\t\t_d._file_name : ini_path + \"\\\\\" + _d._file_name;\n\n\tstd::string _path = value_name;\n\n\tif (!branch.empty())\n\t\t_path = branch + \".\" + _path;\n\n\ttry {\n\t\tstd::filesystem::path path(full_ini_file_path);\n\t\tif (!std::filesystem::exists(path))\n\t\t\treturn true;\n\n\t\tboost::property_tree::ptree pt;\n\t\tboost::property_tree::ini_parser::read_ini(full_ini_file_path, pt);\n\n\t\tif (_d._encrypted) {\n\t\t\tstd::string encoded;\n\t\t\ttry { encoded = pt.get<std::string>(_path); }\n\t\t\tcatch (const std::exception&) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tstd::string data_encrypted = base32::decode(encoded);\n\t\t\treturn _d.decrypt_string(data_encrypted, value, error);\n\t\t}\n\t\telse {\n\t\t\ttry {\n\t\t\t\tvalue = pt.get<std::string>(_path);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcatch (const std::exception&) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\tcatch (const std::exception& e) {\n\t\terror = e.what();\n\t\treturn false;\n\t}\n}\n\nbool liblec::leccore::ini_settings::delete_value(const std::string& branch,\n\tconst std::string& value_name, std::string& error) {\n\terror.clear();\n\tif (value_name.empty()) {\n\t\terror = \"Value name not specified\";\n\t\treturn false;\n\t}\n\n\tstd::string ini_path;\n\tif (!get_ini_path(ini_path, error))\n\t\treturn false;\n\n\tconst std::string full_ini_file_path = ini_path.empty() ?\n\t\t_d._file_name : ini_path + \"\\\\\" + _d._file_name;\n\n\tstd::string _path = value_name;\n\n\tif (!branch.empty())\n\t\t_path = branch + \".\" + _path;\n\n\ttry {\n\t\tboost::property_tree::ptree pt;\n\t\tboost::property_tree::ini_parser::read_ini(full_ini_file_path, pt);\n\t\tsize_t erased_subkeys = 0;\n\t\tif (!impl::erase_path(pt, _path, erased_subkeys, error))\n\t\t\treturn false;\n\n\t\tif (erased_subkeys > 0)\n\t\t\tboost::property_tree::write_ini(full_ini_file_path, pt);\n\n\t\treturn true;\n\t}\n\tcatch (const std::exception& e) {\n\t\terror = e.what();\n\t\treturn false;\n\t}\n}\n\nbool ini_settings::delete_recursive(const std::string& branch,\n\tstd::string& error) {\n\terror.clear();\n\tstd::string ini_path;\n\tif (!get_ini_path(ini_path, error))\n\t\treturn false;\n\n\tconst std::string full_ini_file_path = ini_path.empty() ?\n\t\t_d._file_name : ini_path + \"\\\\\" + _d._file_name;\n\n\tstd::string _path = branch;\n\n\ttry {\n\t\tboost::property_tree::ptree pt;\n\n\t\tsize_t erased_subkeys = 0;\n\t\tif (!_path.empty()) {\n\t\t\tboost::property_tree::ini_parser::read_ini(full_ini_file_path, pt);\n\t\t\tif (!impl::erase_path(pt, _path, erased_subkeys, error))\n\t\t\t\treturn false;\n\t\t}\n\n\t\tif (erased_subkeys > 0)\n\t\t\tboost::property_tree::write_ini(full_ini_file_path, pt);\n\n\t\treturn true;\n\t}\n\tcatch (const std::exception& e) {\n\t\terror = e.what();\n\t\treturn false;\n\t}\n}\n", "meta": {"hexsha": "0d2c5c9f7c181c6bd97919bf6087719f5570b995", "size": 8626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "settings/ini_settings.cpp", "max_stars_repo_name": "alecmus/leccore", "max_stars_repo_head_hexsha": "42d81fbf513e069396c372367161e341d66ba5f3", "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": "settings/ini_settings.cpp", "max_issues_repo_name": "alecmus/leccore", "max_issues_repo_head_hexsha": "42d81fbf513e069396c372367161e341d66ba5f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-08T20:43:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T20:49:48.000Z", "max_forks_repo_path": "settings/ini_settings.cpp", "max_forks_repo_name": "alecmus/leccore", "max_forks_repo_head_hexsha": "42d81fbf513e069396c372367161e341d66ba5f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-13T20:02:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T20:02:10.000Z", "avg_line_length": 25.2222222222, "max_line_length": 93, "alphanum_fraction": 0.6883839555, "num_tokens": 2357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.18902096894735462}}
{"text": "//\n// Created by Hamza El-Kebir on 6/17/21.\n//\n\n#ifndef LODESTAR_FASTFOURIERTRANSFORM_HPP\n#define LODESTAR_FASTFOURIERTRANSFORM_HPP\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/FFT>\n\nnamespace ls {\n    namespace data {\n        class FastFourierTransform {\n\n        };\n    }\n}\n\n#endif //LODESTAR_FASTFOURIERTRANSFORM_HPP\n", "meta": {"hexsha": "c5a463415ce81613d79d2f96c0bcf543c88ada08", "size": 327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/data/FastFourierTransform.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/data/FastFourierTransform.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/data/FastFourierTransform.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": 16.35, "max_line_length": 42, "alphanum_fraction": 0.7217125382, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1890209689473546}}
{"text": "#ifndef CLASSIFIER_HPP\n#define CLASSIFIER_HPP\n\n#include <caffe/caffe.hpp>\n\n#include <opencv/cv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\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/opencv/to_open_cv.h>\n\n#include <memory>\n#include <string>\n\nusing namespace caffe;\n\nclass Classifier {\npublic:\n    Classifier(const std::string& model_file, const std::string& trained_file, const std::string& mean_file, int cpu_only);\n    Classifier(const std::string& model_file, const std::string& trained_file, int cpu_only);\n    ~Classifier();\n    std::vector<float> GetFeature(const cv::Mat& img);\n    std::vector<float> GetFeature(const std::string& image_name);\n    void SetMean(const std::string& mean_file);\n    dlib::frontal_face_detector detector;\n    dlib::shape_predictor sp;\nprivate:\n\n    void WrapInputLayer(std::vector<cv::Mat>* input_channels);\n    void Preprocess(const cv::Mat& img, std::vector<cv::Mat>* input_channels);\n\nprivate:\n    std::shared_ptr<Net<float> > _net;\n    cv::Size _input_geometry;\n    int _num_channels;\n    cv::Mat _mean;\n    bool _flag_sub_mean = false;\n    int scale_ = 1;\n};\n\nClassifier::~Classifier() {\n\n}\n\nClassifier::Classifier(const std::string& model_file,\n                       const std::string& trained_file,\n                       const std::string& mean_file, int cpu_only) {\n    _flag_sub_mean = true;\n    if (cpu_only == 1) {\n        Caffe::set_mode(Caffe::CPU);\n    }\n    else {\n        Caffe::set_mode(Caffe::GPU);\n    }\n\n    /* Load the network. */\n    _net.reset(new Net<float>(model_file, TEST));\n    _net->CopyTrainedLayersFrom(trained_file);\n\n    CHECK_EQ(_net->num_inputs(), 1) << \"Network should have exactly one input.\";\n    CHECK_EQ(_net->num_outputs(), 1) << \"Network should have exactly one output.\";\n\n    Blob<float>* input_layer = _net->input_blobs()[0];\n    _num_channels = input_layer->channels();\n    CHECK(_num_channels == 3 || _num_channels == 1)\n        << \"Input layer should have 1 or 3 channels.\";\n\n    _input_geometry = cv::Size(input_layer->width(), input_layer->height());\n    SetMean(mean_file);\n    Blob<float>* output_layer = _net->output_blobs()[0];\n    detector = dlib::get_frontal_face_detector();\n    dlib::deserialize(\"shape_predictor_68_face_landmarks.dat\") >> sp;\n}\n\nClassifier::Classifier(const std::string& model_file, const std::string& trained_file, int cpu_only) {\n    _flag_sub_mean = false;\n    if (cpu_only == 1) {\n        Caffe::set_mode(Caffe::CPU);\n    }\n    else {\n        Caffe::set_mode(Caffe::GPU);\n    }\n    _net.reset(new Net<float>(model_file, TEST));\n    _net->CopyTrainedLayersFrom(trained_file);\n    CHECK_EQ(_net->num_inputs(), 1) << \"Network should have exactly one input.\";\n    CHECK_EQ(_net->num_outputs(), 1) << \"Network should have exactly one output.\";\n\n    //get the address of Point\n    Blob<float>* input_layer = _net->input_blobs()[0];\n    _num_channels = input_layer->channels();\n    CHECK(_num_channels == 3 || _num_channels == 1) << \"Input layer should have 1 or 3 channels.\";\n\n    //get size\n    _input_geometry = cv::Size(input_layer->width(), input_layer->height());\n    Blob<float>* output_layer = _net->output_blobs()[0];\n    detector = dlib::get_frontal_face_detector();\n    dlib::deserialize(\"./resource/shape_predictor_68_face_landmarks.dat\") >> sp;\n\n}\n\nvoid Classifier::SetMean(const string& mean_file) {\n    BlobProto blob_proto;\n    ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);\n    Blob<float> mean_blob;\n    mean_blob.FromProto(blob_proto);\n    CHECK_EQ(mean_blob.channels(), _num_channels) << \"Number of channels of mean file doesn't match input layer.\";\n    std::vector<cv::Mat> channels;\n    float* data = mean_blob.mutable_cpu_data();\n    for (int i = 0; i < _num_channels; ++i) {\n        cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);\n        channels.push_back(channel);\n        data += mean_blob.height() * mean_blob.width();\n    }\n    cv::Mat mean;\n    cv::merge(channels, mean);\n    cv::Scalar channel_mean = cv::mean(mean);\n    _mean = cv::Mat(_input_geometry, mean.type(), channel_mean);\n}\n\nstd::vector<float> Classifier::GetFeature(const cv::Mat& img) {\n    double time1;\n    Blob<float>* input_layer = _net->input_blobs()[0];\n\n    input_layer->Reshape(1, _num_channels,\n        _input_geometry.height, _input_geometry.width);\n    _net->Reshape();\n\n    std::vector<cv::Mat> input_channels;\n\n    WrapInputLayer(&input_channels);\n\n    Preprocess(img, &input_channels);\n    _net->Forward();\n\n    Blob<float>* output_layer = _net->output_blobs()[0];\n    const float* begin = output_layer->cpu_data();\n    const float* end = begin + output_layer->channels();\n\n    return std::vector<float>(begin, end);\n}\n\nstd::vector<float> Classifier::GetFeature(const string& image_name) {\n    double time1;\n    cv::Mat img = cv::imread(image_name, -1);\n    Blob<float>* input_layer = _net->input_blobs()[0];\n    input_layer->Reshape(1, _num_channels, _input_geometry.height, _input_geometry.width);\n    _net->Reshape();\n\n    std::vector<cv::Mat> input_channels;\n    WrapInputLayer(&input_channels);\n    Preprocess(img, &input_channels);\n    _net->Forward();\n\n    Blob<float>* output_layer = _net->output_blobs()[0];\n    const float* begin = output_layer->cpu_data();\n    const float* end = begin + output_layer->channels();\n    return std::vector<float>(begin, end);\n}\n\nvoid Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) {\n    Blob<float>* input_layer = _net->input_blobs()[0];\n    int width = input_layer->width();\n    int height = input_layer->height();\n    float* input_data = input_layer->mutable_cpu_data();\n    for (int i = 0; i < input_layer->channels(); ++i) {\n        cv::Mat channel(height, width, CV_32FC1, input_data);\n        input_channels->push_back(channel);\n        input_data += width * height;\n    }\n}\n\n\nvoid Classifier::Preprocess(const cv::Mat& img, std::vector<cv::Mat>* input_channels) {\n    cv::Mat sample;\n    if (img.channels() == 3 && _num_channels == 1)\n        cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);\n    else if (img.channels() == 4 && _num_channels == 1)\n        cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);\n    else if (img.channels() == 4 && _num_channels == 3)\n        cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);\n    else if (img.channels() == 1 && _num_channels == 3)\n        cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);\n    else\n        sample = img;\n\n    cv::Mat sample_resized;\n    if (sample.size() != _input_geometry)\n        cv::resize(sample, sample_resized, _input_geometry);\n    else\n        sample_resized = sample;\n\n    cv::Mat sample_float;\n    if (_num_channels == 3)\n        sample_resized.convertTo(sample_float, CV_32FC3);\n    else\n        sample_resized.convertTo(sample_float, CV_32FC1);\n\n    cv::Mat sample_normalized;\n    if (_flag_sub_mean == true) {\n        cv::subtract(sample_float, _mean, sample_normalized);\n        cv::split(sample_normalized, *input_channels);\n    }\n    else {\n        cv::split(sample_float, *input_channels);\n    }\n\n    CHECK(reinterpret_cast<float*>(input_channels->at(0).data) == _net->input_blobs()[0]->cpu_data())\n        << \"Input channels are not wrapping the input layer of the network.\";\n}\n\n#endif // CLASSIFIER_HPP\n", "meta": {"hexsha": "fd3e550743d32eda38856196a014d7358491a30a", "size": 7449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Classifier.hpp", "max_stars_repo_name": "jjzhang166/libFace3", "max_stars_repo_head_hexsha": "c8c27131b88003922b05fbe6151df9f8092b0947", "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/Classifier.hpp", "max_issues_repo_name": "jjzhang166/libFace3", "max_issues_repo_head_hexsha": "c8c27131b88003922b05fbe6151df9f8092b0947", "max_issues_repo_licenses": ["MIT"], "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/Classifier.hpp", "max_forks_repo_name": "jjzhang166/libFace3", "max_forks_repo_head_hexsha": "c8c27131b88003922b05fbe6151df9f8092b0947", "max_forks_repo_licenses": ["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.1697247706, "max_line_length": 123, "alphanum_fraction": 0.6717680226, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18902096894735457}}
{"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#include \"SimpleMatrix.hpp\"\n\n#include <assert.h>                                             // for assert\n#include <memory>                                               // for __sha...\n#include <iostream>                                             // for ostream\n#include <boost/numeric/ublas/io.hpp>                           // for opera...\n#include <boost/numeric/ublas/matrix_proxy.hpp>                 // for matri...\n#include <boost/numeric/bindings/blas.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include \"SimpleMatrixFriends.hpp\"                              // for subprod\n#include \"SiconosAlgebra.hpp\"    // for symmetric, triangular ...\n#include \"BlockMatrix.hpp\"                                      // for Block...\n#include \"BlockMatrixIterators.hpp\"                             // for Const...\n#include \"SiconosException.hpp\"                           // for Sicon...\n#include \"ioMatrix.hpp\"                                         // for read\n#include \"Tools.hpp\"                                            // for toString\n#include \"bindings_utils.hpp\"                                   // for fill\n#include \"NumericsMatrix.h\"\n\n#include \"NumericsSparseMatrix.h\"\n#include \"CSparseMatrix.h\"\n\n//#define DEBUG_MESSAGES\n#include \"siconos_debug.h\"\n\n#ifdef DEBUG_MESSAGES\n#include \"NumericsVector.h\"\n#include <cs.h>\n#endif\n\n\n\n\n\nusing namespace Siconos;\nnamespace siconosBindings = boost::numeric::bindings::blas;\nusing std::cout;\nusing std::endl;\n\n\n// =================================================\n//                CONSTRUCTORS\n// =================================================\n\nSimpleMatrix::SimpleMatrix():\n  SiconosMatrix(Siconos::DENSE)\n{\n  mat.Dense = new DenseMat(ublas::zero_matrix<double>());\n}\n\n// parameters: dimensions and type.\nSimpleMatrix::SimpleMatrix(unsigned int row,\n                           unsigned int col,\n                           UBLAS_TYPE typ,\n                           unsigned int upper,\n                           unsigned int lower):\n  SiconosMatrix(Siconos::DENSE)\n{\n  if(typ == DENSE)\n  {\n    mat.Dense = new DenseMat(ublas::zero_matrix<double>(row, col));\n    // _num = 1; default value\n  }\n  else if(typ == TRIANGULAR)\n  {\n    mat.Triang = new TriangMat(ublas::zero_matrix<double>(row, col));\n    _num = TRIANGULAR;\n  }\n  else if(typ == SYMMETRIC)\n  {\n    mat.Sym = new SymMat(ublas::zero_matrix<double>(row, col));\n    _num = SYMMETRIC;\n  }\n  else if(typ == SPARSE)\n  {\n    mat.Sparse = new SparseMat(row, col, upper);\n    _num = SPARSE;\n    zero();\n  }\n  else if(typ == SPARSE_COORDINATE)\n  {\n    mat.SparseCoordinate = new SparseCoordinateMat(row, col, upper);\n    _num = SPARSE_COORDINATE;\n    zero();\n  }\n  else if(typ == BANDED)\n  {\n    mat.Banded = new BandedMat(row, col, upper, lower);\n    _num = BANDED;\n    zero();\n  }\n  else if(typ == ZERO)\n  {\n    mat.Zero = new ZeroMat(row, col);\n    _num = ZERO;\n  }\n  else if(typ == IDENTITY)\n  {\n    mat.Identity = new IdentityMat(row, col);\n    _num = IDENTITY;\n  }\n  else THROW_EXCEPTION(\"invalid type.\");\n}\n\n// parameters: dimensions, input value and type\nSimpleMatrix::SimpleMatrix(unsigned int row, unsigned int col, double inputValue, UBLAS_TYPE typ, unsigned int upper, unsigned int lower):\n  SiconosMatrix(typ)\n{\n  // This constructor has sense only for dense matrices ...\n  if(typ == DENSE)\n  {\n    mat.Dense = new DenseMat(ublas::scalar_matrix<double>(row, col, inputValue));\n    // _num = Siconos::DENSE; default value\n  }\n  else\n     THROW_EXCEPTION(\"invalid type.\");\n}\n\n// // parameters: a vector (stl) of double and the type.\n// SimpleMatrix::SimpleMatrix(const std::vector<double>& v, unsigned int row, unsigned int col, UBLAS_TYPE typ, unsigned int lower, unsigned int upper):\n//   SiconosMatrix(1, row, col), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false), _isCholeskyFactorized(false), _isCholeskyFactorizedInPlace(false)\n// {\n//   if( (  (v.size() != row*col) && (typ != SYMMETRIC && typ != BANDED) )\n//       || (v.size() != row*row && typ == SYMMETRIC)\n//       || (typ == BANDED && ( (v.size()) != (unsigned int)(std::max)(row, col)*(lower+1+upper) ) ))\n//      THROW_EXCEPTION(\"invalid vector size\");\n\n//   if(typ == DENSE)\n//     {\n//       mat.Dense = new DenseMat(row,col);\n//       // _num = Siconos::DENSE; default value\n//     }\n//   else if(typ == TRIANGULAR)\n//     {\n//       mat.Triang = new TriangMat(row,col);\n//       _num = Siconos::TRIANGULAR;\n//     }\n//   else if(typ == SYMMETRIC)\n//     {\n//       mat.Sym = new SymMat(row);\n//       _num = Siconos::SYMMETRIC;\n//     }\n//   else if(typ == SPARSE)\n//     {\n//        THROW_EXCEPTION(\"warning -- use constructor(const SparseMat &m) or constructor(UBLAS_TYPE, int row, int col) with UBLAS_TYPE = SPARSE\");\n\n//     }\n//   else if(typ == BANDED)\n//     {\n//       mat.Banded = new BandedMat(row, col, lower, upper);\n//       _num = Siconos::BANDED;\n//     }\n//   else\n//      THROW_EXCEPTION(\"invalid type of matrix given\");\n\n//   std::copy(v.begin(), v.end(), (vect.Dense)->begin());\n\n\n// }\n\n// Copy constructors\nSimpleMatrix::SimpleMatrix(const SimpleMatrix &m):\n  SiconosMatrix(m.num())\n{\n\n  _isSymmetric = m.isSymmetric();\n  _isPositiveDefinite = m.isPositiveDefinite();\n\n  _isPLUFactorized= m.isPLUFactorized();\n  _isPLUFactorizedInPlace= m.isPLUFactorizedInPlace();\n  _isPLUInversed= m.isPLUInversed();\n\n  if(_num == Siconos::DENSE)\n  {\n    mat.Dense = new DenseMat(m.size(0), m.size(1));\n    noalias(*mat.Dense) = (*m.dense());\n  }\n  //   mat.Dense = new DenseMat(*m.dense());\n\n  else if(_num == Siconos::TRIANGULAR)\n    mat.Triang = new TriangMat(*m.triang());\n\n  else if(_num == Siconos::SYMMETRIC)\n\n    mat.Sym = new SymMat(*m.sym());\n\n  else if(_num == Siconos::SPARSE)\n    mat.Sparse = new SparseMat(*m.sparse());\n\n  else if(_num == Siconos::SPARSE_COORDINATE)\n    mat.SparseCoordinate = new SparseCoordinateMat(*m.sparseCoordinate());\n\n  else if(_num == Siconos::BANDED)\n    mat.Banded = new BandedMat(*m.banded());\n\n  else if(_num == Siconos::ZERO)\n    mat.Zero = new ZeroMat(m.size(0), m.size(1));\n\n  else// if(_num == Siconos::IDENTITY)\n    mat.Identity = new IdentityMat(m.size(0), m.size(1));\n}\n\n/** copy constructor of a block given by the coord = [r0A r1A c0A c1A]\n *  \\param A the matrix for extracting the block\n */\nSimpleMatrix::SimpleMatrix(const SimpleMatrix& A, const Index& coord):\n  SiconosMatrix(A.num())\n{\n  if(coord[0]>=coord[1])\n     THROW_EXCEPTION(\"Empty row range coord[0]>= coord[1]\");\n  if(coord[2]>=coord[3])\n     THROW_EXCEPTION(\"Empty column range coord[2]>= coord[3]\");\n  if(coord[1] > A.size(0))\n     THROW_EXCEPTION(\"row index too large.\");\n  if(coord[3] > A.size(1))\n     THROW_EXCEPTION(\"column index too large.\");\n\n  if(_num == Siconos::DENSE)\n  {\n    ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Dense=new DenseMat(subA);\n  }\n  else if(_num == Siconos::TRIANGULAR)\n  {\n    ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Triang=new TriangMat(subA);\n  }\n  else if(_num == Siconos::SYMMETRIC)\n  {\n    ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Sym=new SymMat(subA);\n  }\n  else if(_num == Siconos::SPARSE)\n  {\n    ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Sparse=new SparseMat(subA);\n  }\n  else if(_num == Siconos::SPARSE_COORDINATE)\n  {\n    ublas::matrix_range<SparseCoordinateMat> subA(*A.sparseCoordinate(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.SparseCoordinate=new SparseCoordinateMat(subA);\n  }\n  else if(_num == Siconos::BANDED)\n  {\n    ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Banded=new BandedMat(subA);\n  }\n  else if(_num == Siconos::ZERO)\n  {\n    mat.Zero = new ZeroMat(coord[1]-coord[0], coord[3]-coord[2]);\n  }\n  else// if(_num == Siconos::IDENTITY)\n    mat.Identity = new IdentityMat(coord[1]-coord[0], coord[3]-coord[2]);\n}\n\n\n\n\nSimpleMatrix::SimpleMatrix(const SiconosMatrix &m):\n  SiconosMatrix(m.num())\n{\n  // _num is set in SiconosMatrix constructor with m.num() ... must be changed if m is Block\n  Siconos::UBLAS_TYPE numM = m.num();\n\n  _isSymmetric = m.isSymmetric();\n  _isPositiveDefinite = m.isPositiveDefinite();\n\n  _isPLUFactorized= m.isPLUFactorized();\n  _isPLUFactorizedInPlace= m.isPLUFactorizedInPlace();\n  _isPLUInversed= m.isPLUInversed();\n\n\n  if(m.ipiv())\n    _ipiv.reset(new VInt(*(m.ipiv())));\n\n  if(numM == 0)  // ie if m is Block, this matrix is set to a dense.\n  {\n    const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n    _num = Siconos::DENSE;\n    // get number of blocks in a row/col of m.\n    mat.Dense = new DenseMat(m.size(0), m.size(1));\n    ConstBlocksIterator1 it;\n    ConstBlocksIterator2 it2;\n    unsigned int posRow = 0;\n    unsigned int posCol = 0;\n\n    for(it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for(it2 = it.begin(); it2 != it.end(); ++it2)\n      {\n        setBlock(posRow, posCol, **it2);\n        posCol += (*it2)->size(1);\n      }\n      posRow += (*it)->size(0);\n      posCol = 0;\n    }\n  }\n  else if(_num == Siconos::DENSE)\n  {\n    mat.Dense = new DenseMat(m.size(0), m.size(1));\n    noalias(*mat.Dense) = (*m.dense());\n  }\n\n  else if(_num == Siconos::TRIANGULAR)\n    mat.Triang = new TriangMat(*m.triang());\n\n  else if(_num == Siconos::SYMMETRIC)\n    mat.Sym = new SymMat(*m.sym());\n\n  else if(_num == Siconos::SPARSE)\n    mat.Sparse = new SparseMat(*m.sparse());\n\n  else if(_num == Siconos::SPARSE_COORDINATE)\n    mat.SparseCoordinate = new SparseCoordinateMat(*m.sparseCoordinate());\n\n  else if(_num == Siconos::BANDED)\n    mat.Banded = new BandedMat(*m.banded());\n\n  else if(_num == Siconos::ZERO)\n    mat.Zero = new ZeroMat(m.size(0), m.size(1));\n\n  else // if(_num == Siconos::IDENTITY)\n    mat.Identity = new IdentityMat(m.size(0), m.size(1));\n}\n\nSimpleMatrix::SimpleMatrix(const DenseMat& m):\n  SiconosMatrix(Siconos::DENSE)\n{\n  mat.Dense = new DenseMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const TriangMat& m):\n  SiconosMatrix(Siconos::TRIANGULAR)\n{\n  mat.Triang = new TriangMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const SymMat& m):\n  SiconosMatrix(Siconos::SYMMETRIC)\n{\n  mat.Sym = new SymMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const SparseMat& m):\n  SiconosMatrix(Siconos::SPARSE)\n{\n  mat.Sparse = new SparseMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const SparseCoordinateMat& m):\n  SiconosMatrix(SPARSE_COORDINATE)\n{\n  mat.SparseCoordinate = new SparseCoordinateMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const BandedMat& m):\n  SiconosMatrix(Siconos::BANDED)\n{\n  mat.Banded = new BandedMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const ZeroMat& m):\n  SiconosMatrix(Siconos::ZERO)\n{\n  mat.Zero = new ZeroMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const IdentityMat& m):\n  SiconosMatrix(Siconos::IDENTITY)\n{\n  mat.Identity = new IdentityMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const std::string &file, bool ascii):\n  SiconosMatrix(Siconos::DENSE)\n{\n  mat.Dense = new DenseMat();\n  if(ascii)\n  {\n    ioMatrix::read(file, \"ascii\", *this);\n  }\n  else\n  {\n    ioMatrix::read(file, \"binary\", *this);\n  }\n}\n\nSimpleMatrix::~SimpleMatrix()\n{\n  if(_num == Siconos::DENSE)\n  {\n    delete(mat.Dense);\n    if (_numericsMatrix)\n    {\n      // _numericsMatrix->matrix0 points to the array contained in the ublas matrix\n      // To avoid double free on this pointer, we set it to NULL before deletion\n      if (_numericsMatrix->matrix0)\n        _numericsMatrix->matrix0 =nullptr;\n    }\n  }\n  else if(_num == Siconos::TRIANGULAR)\n    delete(mat.Triang);\n  else if(_num == Siconos::SYMMETRIC)\n    delete(mat.Sym);\n  else if(_num == Siconos::SPARSE_COORDINATE)\n    delete(mat.SparseCoordinate);\n  else if(_num == Siconos::SPARSE)\n    delete(mat.Sparse);\n  else if(_num == Siconos::BANDED)\n    delete(mat.Banded);\n  else if(_num == Siconos::ZERO)\n    delete(mat.Zero);\n  else if(_num == Siconos::IDENTITY)\n    delete(mat.Identity);\n}\n\n\nvoid SimpleMatrix::updateNumericsMatrix()\n{\n  /* set the numericsMatrix */\n  NumericsMatrix * NM;\n  if(_num == DENSE)\n  {\n    _numericsMatrix.reset(NM_new(),NM_free_not_dense); // When we reset, we do not free the matrix0\n                                                        //that is linked to the array of the boost container\n    NM = _numericsMatrix.get();\n    double * data = (double*)(getArray());\n    DEBUG_EXPR(NV_display(data,size(0)*size(1)););\n    NM_fill(NM, NM_DENSE, size(0), size(1), data ); // Pointer link\n  }\n  else\n  {\n    // For all the other cases, we build a sparse matrix and we call numerics for the factorization of a sparse matrix.\n    _numericsMatrix.reset(NM_create(NM_SPARSE, size(0), size(1)),NM_free);\n    NM = _numericsMatrix.get();\n    _numericsMatrix->matrix2->origin = NSM_CSC;\n    NM_csc_alloc(NM, nnz());\n    fillCSC(numericsSparseMatrix(NM)->csc, std::numeric_limits<double>::epsilon());\n    DEBUG_EXPR(cs_print(numericsSparseMatrix(NM)->csc, 0););\n  }\n}\n\n\n\nbool SimpleMatrix::checkSymmetry(double tol) const\n{\n  SP::SimpleMatrix  m_trans(new SimpleMatrix(*this));\n  m_trans->trans();\n  double err = (*this-*m_trans).normInf();\n  if((*m_trans).normInf() > 0.0)\n  {\n    err /= (*m_trans).normInf();\n  }\n  // std::cout << \"err_rel  =\"<< err <<std::endl;\n  return (err < tol);\n}\n//======================================\n// get Ublas component (dense, sym ...)\n//======================================\n\nconst DenseMat SimpleMatrix::getDense(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::DENSE)\n     THROW_EXCEPTION(\" the current matrix is not a Dense matrix\");\n\n  return *mat.Dense;\n}\n\nconst TriangMat SimpleMatrix::getTriang(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::TRIANGULAR)\n     THROW_EXCEPTION(\"the current matrix is not a Triangular matrix\");\n\n  return *mat.Triang;\n}\n\nconst SymMat SimpleMatrix::getSym(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::SYMMETRIC)\n     THROW_EXCEPTION(\"he current matrix is not a Symmetric matrix\");\n\n  return *mat.Sym;\n}\n\nconst SparseMat SimpleMatrix::getSparse(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::SPARSE)\n     THROW_EXCEPTION(\"the current matrix is not a Sparse matrix\");\n\n  return *mat.Sparse;\n}\n\nconst SparseCoordinateMat SimpleMatrix::getSparseCoordinate(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::SPARSE_COORDINATE)\n     THROW_EXCEPTION(\"the current matrix is not a Sparse Coordinate matrix\");\n\n  return *mat.SparseCoordinate;\n}\nconst BandedMat SimpleMatrix::getBanded(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::BANDED)\n     THROW_EXCEPTION(\"the current matrix is not a Banded matrix\");\n\n  return *mat.Banded;\n}\n\nconst ZeroMat SimpleMatrix::getZero(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::ZERO)\n     THROW_EXCEPTION(\"the current matrix is not a Zero matrix\");\n\n  return *mat.Zero;\n}\n\nconst IdentityMat SimpleMatrix::getIdentity(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::IDENTITY)\n     THROW_EXCEPTION(\"the current matrix is not a Identity matrix\");\n\n  return *mat.Identity;\n}\n\nDenseMat* SimpleMatrix::dense(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::DENSE)\n     THROW_EXCEPTION(\"the current matrix is not a Dense matrix\");\n\n  return mat.Dense;\n}\n\nTriangMat* SimpleMatrix::triang(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::TRIANGULAR)\n     THROW_EXCEPTION(\"the current matrix is not a Triangular matrix\");\n\n  return mat.Triang;\n}\n\nSymMat* SimpleMatrix::sym(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::SYMMETRIC)\n     THROW_EXCEPTION(\"the current matrix is not a Symmetric matrix\");\n\n  return mat.Sym;\n}\n\nSparseMat* SimpleMatrix::sparse(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::SPARSE)\n     THROW_EXCEPTION(\"the current matrix is not a Sparse matrix\");\n\n  return mat.Sparse;\n}\n\nSparseCoordinateMat* SimpleMatrix::sparseCoordinate(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::SPARSE_COORDINATE)\n     THROW_EXCEPTION(\"the current matrix is not a Sparse matrix\");\n\n  return mat.SparseCoordinate;\n}\n\nBandedMat* SimpleMatrix::banded(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::BANDED)\n     THROW_EXCEPTION(\"the current matrix is not a Banded matrix\");\n\n  return mat.Banded;\n}\n\nZeroMat* SimpleMatrix::zero_mat(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::ZERO)\n     THROW_EXCEPTION(\"the current matrix is not a Zero matrix\");\n\n  return mat.Zero;\n}\n\nIdentityMat* SimpleMatrix::identity(unsigned int, unsigned int) const\n{\n  if(_num != Siconos::IDENTITY)\n     THROW_EXCEPTION(\"the current matrix is not a Identity matrix\");\n\n  return mat.Identity;\n}\n\ndouble* SimpleMatrix::getArray(unsigned int, unsigned int) const\n{\n  if(_num == Siconos::SPARSE)\n     THROW_EXCEPTION(\"not yet implemented for sparse matrix.\");\n\n  if(_num == Siconos::DENSE)\n    return (((*mat.Dense).data()).data());\n  else if(_num == Siconos::TRIANGULAR)\n    return &(((*mat.Triang).data())[0]);\n  else if(_num == Siconos::SYMMETRIC)\n    return &(((*mat.Sym).data())[0]);\n  else if(_num == Siconos::ZERO)\n  {\n    ZeroMat::iterator1 it = (*mat.Zero).begin1();\n    return const_cast<double*>(&(*it));\n  }\n  else if(_num == Siconos::IDENTITY)\n  {\n    IdentityMat::iterator1 it = (*mat.Identity).begin1();\n    return const_cast<double*>(&(*it));\n  }\n  else\n    return &(((*mat.Banded).data())[0]);\n}\n\n// ===========================\n//       fill matrix\n// ===========================\n\nvoid SimpleMatrix::zero()\n{\n  unsigned int size1 = size(0);\n  unsigned int size2 = size(1);\n  if(_num == Siconos::DENSE)\n    *mat.Dense = ublas::zero_matrix<double>(size1, size2);\n  else if(_num == Siconos::TRIANGULAR)\n    *mat.Triang = ublas::zero_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::SYMMETRIC)\n    *mat.Sym = ublas::zero_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::SPARSE)\n    *mat.Sparse = ublas::zero_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::SPARSE_COORDINATE)\n    *mat.SparseCoordinate = ublas::zero_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::BANDED)\n    *mat.Banded = ublas::zero_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::IDENTITY)\n     THROW_EXCEPTION(\"you can not set to zero a matrix of type Identity!.\");\n  resetFactorizationFlags();\n  // if _num == Siconos::ZERO: nothing\n}\n\nvoid SimpleMatrix::randomize()\n{\n  if(_num == Siconos::DENSE)\n    Siconos::algebra::fill(*mat.Dense);\n  else\n     THROW_EXCEPTION(\"only implemented for dense matrices.\");\n  resetFactorizationFlags();\n}\n\nvoid SimpleMatrix::randomize_sym()\n{\n  if(_num == Siconos::DENSE)\n    Siconos::algebra::fill_sym(*mat.Dense);\n  else\n     THROW_EXCEPTION(\"only implemented for dense matrices.\");\n  resetFactorizationFlags();\n}\n\nvoid SimpleMatrix::eye()\n{\n  unsigned int size1 = size(0);\n  unsigned int size2 = size(1);\n  if(_num == Siconos::DENSE)\n    *mat.Dense = ublas::identity_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::TRIANGULAR)\n    *mat.Triang = ublas::identity_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::SYMMETRIC)\n    *mat.Sym = ublas::identity_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::SPARSE)\n    *mat.Sparse = ublas::identity_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::BANDED)\n    *mat.Banded = ublas::identity_matrix<double>(size1, size2);\n\n  else if(_num == Siconos::ZERO)\n     THROW_EXCEPTION(\"you can not set to identity a matrix of type Zero!.\");\n  resetFactorizationFlags();\n}\n\n\n\nunsigned int SimpleMatrix::size(unsigned int index) const\n{\n  if(_num == Siconos::DENSE)\n  {\n    if(index == 0) return (*mat.Dense).size1();\n    else  return (*mat.Dense).size2();\n  }\n  else if(_num == Siconos::TRIANGULAR)\n  {\n    if(index == 0) return (*mat.Triang).size1();\n    else return (*mat.Triang).size2();\n  }\n  else if(_num == Siconos::SYMMETRIC)\n  {\n    if(index == 0) return (*mat.Sym).size1();\n    else  return (*mat.Sym).size2();\n  }\n  else if(_num == Siconos::SPARSE)\n  {\n    if(index == 0) return (*mat.Sparse).size1();\n    else return (*mat.Sparse).size2();\n  }\n  else if(_num == Siconos::SPARSE_COORDINATE)\n  {\n    if(index == 0) return (*mat.SparseCoordinate).size1();\n    else return (*mat.SparseCoordinate).size2();\n  }\n  else if(_num == Siconos::BANDED)\n  {\n    if(index == 0) return (*mat.Banded).size1();\n    else  return (*mat.Banded).size2();\n  }\n  else if(_num == Siconos::ZERO)\n  {\n    if(index == 0) return (*mat.Zero).size1();\n    else  return (*mat.Zero).size2();\n  }\n  else if(_num == Siconos::IDENTITY)\n  {\n    if(index == 0) return (*mat.Identity).size1();\n    else  return (*mat.Identity).size2();\n  }\n  else return 0;\n\n\n};\n\n\n//=======================\n// set matrix dimension\n//=======================\n\nvoid SimpleMatrix::resize(unsigned int row, unsigned int col, unsigned int lower, unsigned int upper, bool preserve)\n{\n\n  if(_num == Siconos::DENSE)\n  {\n    (*mat.Dense).resize(row, col, preserve);\n  }\n  else if(_num == Siconos::TRIANGULAR)\n  {\n    (*mat.Triang).resize(row, col, preserve);\n  }\n  else if(_num == Siconos::SYMMETRIC)\n  {\n    (*mat.Sym).resize(row, col, preserve);\n  }\n  else if(_num == Siconos::SPARSE)\n  {\n    (*mat.Sparse).resize(row, col, preserve);\n  }\n  else if(_num == Siconos::SPARSE_COORDINATE)\n  {\n    (*mat.SparseCoordinate).resize(row, col, preserve);\n  }\n  else if(_num == Siconos::BANDED)\n  {\n    (*mat.Banded).resize(row, col, lower, upper, preserve);\n  }\n  else if(_num == Siconos::ZERO)\n  {\n    (*mat.Zero).resize(row, col, preserve);\n  }\n  else if(_num == Siconos::IDENTITY)\n  {\n    (*mat.Identity).resize(row, col, preserve);\n  }\n  resetFactorizationFlags();\n}\n\n\n//=====================\n// screen display\n//=====================\n\nvoid SimpleMatrix::display() const\n{\n  std::cout.setf(std::ios::scientific);\n  std::cout.precision(6);\n\n  if(size(0) == 0 || size(1) ==0)\n  {\n    std::cout << \"SimpleMatrix::display(): empty matrix\" << std::endl;\n  }\n  std::cout << \"SimpleMatrix storage type - num = \" << _num << \"\\n\";\n  if(_num == Siconos::DENSE)\n  {\n    Siconos::algebra::print_m(*mat.Dense);\n    //std::cout << *mat.Dense << std::endl;\n  }\n  else if(_num == Siconos::TRIANGULAR)\n    std::cout << *mat.Triang << std::endl;\n  else if(_num == Siconos::SYMMETRIC)\n    std::cout << *mat.Sym << std::endl;\n  else if(_num == Siconos::SPARSE)\n  {\n    std::cout << \"non zero element (nnz) = \" <<  mat.Sparse->nnz() << std::endl;\n\n    std::cout << *mat.Sparse << std::endl;\n  }\n  else if(_num == Siconos::SPARSE_COORDINATE)\n  {\n    std::cout << *mat.SparseCoordinate << std::endl;\n  }\n  else if(_num == Siconos::BANDED)\n    std::cout << *mat.Banded << std::endl;\n  else if(_num == Siconos::ZERO)\n    std::cout << *mat.Zero << std::endl;\n  else if(_num == Siconos::IDENTITY)\n    std::cout << *mat.Identity << std::endl;\n}\nvoid SimpleMatrix::displayExpert(bool brief) const\n{\n  std::cout.setf(std::ios::scientific);\n  std::cout.precision(6);\n\n  if(size(0) == 0 || size(1) ==0)\n  {\n    std::cout << \"SimpleMatrix::display(): empty matrix\" << std::endl;\n  }\n  std::cout << \"SimpleMatrix storage type - num = \" << _num << \"\\n\";\n  if(_num == Siconos::DENSE)\n  {\n    Siconos::algebra::print_m(*mat.Dense);\n    //std::cout << *mat.Dense << std::endl;\n  }\n  else if(_num == Siconos::TRIANGULAR)\n    std::cout << *mat.Triang << std::endl;\n  else if(_num == Siconos::SYMMETRIC)\n    std::cout << *mat.Sym << std::endl;\n  else if(_num == Siconos::SPARSE)\n  {\n    std::cout << \"non zero element (nnz) = \" <<  mat.Sparse->nnz() << std::endl;\n    std::cout << \"non zero element (nnz_capacity) = \" <<  mat.Sparse->nnz_capacity() << std::endl;\n    std::cout << \"filled1 = \" <<  mat.Sparse->filled1() << std::endl;\n    std::cout << \"filled2 = \" <<  mat.Sparse->filled2() << std::endl;\n\n    std::cout << \"index_data1 = [ \" ;\n    size_t i=0;\n    for(i = 0; i < mat.Sparse->filled1()-1 ; i++)\n    {\n      std::cout << mat.Sparse->index1_data()[i] << \", \" ;\n    }\n    std::cout << mat.Sparse->index1_data()[i] << \"]\" <<  std::endl;\n\n    std::cout << \"index_data2 = [\" ;\n    for(i = 0; i < mat.Sparse->filled2()-1 ; i++)\n    {\n      std::cout << mat.Sparse->index2_data()[i] << \", \" ;\n    }\n    std::cout << mat.Sparse->index2_data()[i] << \"]\" << std::endl;\n\n    std::cout << \"value_data = [\" ;\n    for(i = 0; i < mat.Sparse->filled2()-1 ; i++)\n    {\n      std::cout << mat.Sparse->value_data()[i] << \", \" ;\n    }\n    std::cout << mat.Sparse->value_data()[i] << \"]\" << std::endl;\n\n    std::cout << *mat.Sparse << std::endl;\n  }\n  else if(_num == Siconos::SPARSE_COORDINATE)\n  {\n    std::cout << \"non zero element (nnz) = \" <<  mat.SparseCoordinate->nnz() << std::endl;\n\n\n\n    for(size_t i = 0; i < mat.SparseCoordinate->nnz(); ++i)\n    {\n      //std::cout << i << std::endl;\n      std::cout << \"M(\" << mat.SparseCoordinate->index1_data()[i] << \", \" ;\n      std::cout << mat.SparseCoordinate->index2_data()[i] << \") =  \" ;\n      std::cout << mat.SparseCoordinate->value_data()[i] << std::endl;\n    }\n  }\n  else if(_num == Siconos::BANDED)\n    std::cout << *mat.Banded << std::endl;\n  else if(_num == Siconos::ZERO)\n    std::cout << *mat.Zero << std::endl;\n  else if(_num == Siconos::IDENTITY)\n    std::cout << *mat.Identity << std::endl;\n}\n\n\n\n//=====================\n// convert to a string\n//=====================\n\nstd::string SimpleMatrix::toString() const\n{\n  return ::toString(*this);\n}\n\n//=====================\n// convert to an ostream\n//=====================\n\nstd::ostream& operator<<(std::ostream& os, const SimpleMatrix& sm)\n{\n  if(sm._num == Siconos::DENSE)\n    os << *sm.mat.Dense;\n  else if(sm._num == Siconos::TRIANGULAR)\n    os << *sm.mat.Triang;\n  else if(sm._num == Siconos::SYMMETRIC)\n    os << *sm.mat.Sym;\n  else if(sm._num == Siconos::SPARSE)\n    os << *sm.mat.Sparse;\n  else if(sm._num == Siconos::BANDED)\n    os << *sm.mat.Banded;\n  else if(sm._num == Siconos::ZERO)\n    os << *sm.mat.Zero;\n  else if(sm._num == Siconos::IDENTITY)\n    os << *sm.mat.Identity;\n  return os;\n}\n\n\nvoid SimpleMatrix::assign(const SimpleMatrix &smat)\n{\n\n  switch(_num)\n  {\n  case Siconos::SPARSE:\n  {\n\n\n    switch(smat.num())\n    {\n    case Siconos::SPARSE:\n    {\n      mat.Sparse->assign(smat.getSparse());\n      break;\n    }\n    default:\n    {\n    }\n\n    }\n  }\n  default:\n  {\n     THROW_EXCEPTION(\"do not know how to assign for the given storage type \");\n  }\n  }\n}\n\n// void prod(const SiconosMatrix& A, const BlockVector& x, SiconosVector& y, bool init)\n// {\n//   assert(!(A.isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n//   if(init)\n//     y.zero();\n//   unsigned int startRow = 0;\n//   unsigned int startCol = 0;\n//   // In private_addprod, the sum of all blocks of x, x[i], is computed: y = Sum_i (subA x[i]), with subA a submatrix of A,\n//   // starting from position startRow in rows and startCol in columns.\n//   // private_prod takes also into account the fact that each block of x can also be a block.\n//   VectorOfVectors::const_iterator it;\n//   for(it = x.begin(); it != x.end(); ++it)\n//   {\n//     private_addprod(A, startRow, startCol, **it, y);\n//     startCol += (*it)->size();\n//   }\n// }\n\n\n\n// void private_addprod(const SiconosMatrix& A, unsigned int startRow, unsigned int startCol, const BlockVector& x, SiconosVector& y)\n// {\n//   assert(!(A.isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n//   assert(!A.isBlock() && \"private_addprod(A,start,x,y) error: not yet implemented for block matrix.\");\n//   VectorOfVectors::const_iterator it;\n//   unsigned int startColBis = startCol;\n//   for(it = x.begin(); it != x.end(); ++it)\n//   {\n//     private_addprod(A, startRow, startColBis, **it, y);\n//     startColBis += (*it)->size();\n//   }\n\n// }\n\n// // x block, y siconos\n// void private_prod(const SiconosMatrix& A, unsigned int startRow, const BlockVector& x, SiconosVector& y, bool init)\n// {\n//   assert(!(A.isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n//   // Computes y = subA *x (or += if init = false), subA being a sub-matrix of A, between el. of index (row) startRow and startRow + sizeY\n//   if(init)  // y = subA * x , else y += subA * x\n//     y.zero();\n//   private_addprod(A, startRow, 0, x, y);\n// }\n\n// // x and y blocks\n// void private_prod(SPC::SiconosMatrix A, const unsigned int startRow, SPC::BlockVector x, SP::BlockVector y, bool init)\n// {\n//   assert(!(A->isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n\n//   unsigned int row = startRow;\n//   VectorOfVectors::const_iterator it;\n//   for(it = y->begin(); it != y->end(); ++it)\n//   {\n//     private_prod(*A, row, *x, **it, init);\n//     row += (*it)->size();\n//   }\n// }\n\n// // x and y blocks\n// void private_prod(SPC::SiconosMatrix A, const unsigned int startRow, SPC::SiconosVector x, SP::BlockVector y, bool init)\n// {\n//   assert(!(A->isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n\n//   unsigned int row = startRow;\n//   VectorOfVectors::const_iterator it;\n//   for(it = y->begin(); it != y->end(); ++it)\n//   {\n//     private_prod(*A, row, *x, **it, init);\n//     row += (*it)->size();\n//   }\n// }\n\n// void private_addprod(SPC::BlockVector x, SPC::SiconosMatrix A, unsigned int startRow, unsigned int startCol, SP::SiconosVector y)\n// {\n//   assert(!(A->isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n//   VectorOfVectors::const_iterator it;\n//   unsigned int startColBis = startCol;\n//   for(it = x->begin(); it != x->end(); ++it)\n//   {\n//     private_addprod((*it), A, startRow, startColBis, y);\n//     startColBis += (*it)->size();\n//   }\n\n// }\n\n// void private_prod(SPC::SiconosVector x, SPC::SiconosMatrix A, unsigned int startCol, SP::BlockVector  y, bool init)\n// {\n//   assert(!(A->isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n\n//   unsigned int col = startCol;\n//   VectorOfVectors::const_iterator it;\n//   for(it = y->begin(); it != y->end(); ++it)\n//   {\n//     private_prod(x, A, col, *it, init);\n//     col += (*it)->size();\n//   }\n// }\n\n// void private_prod(SPC::BlockVector x, SPC::SiconosMatrix A, unsigned int startCol, SP::SiconosVector  y, bool init)\n// {\n//   assert(!(A->isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n\n//   // Computes y = subA *x (or += if init = false), subA being a sub-matrix of trans(A), between el. of A of index (col) startCol and startCol + sizeY\n//   if(init)  // y = subA * x , else y += subA * x\n//     y->zero();\n//   private_addprod(x, A, startCol, 0, y);\n\n// }\n\n// void private_prod(SPC::BlockVector x, SPC::SiconosMatrix A, unsigned int startCol, SP::BlockVector  y, bool init)\n// {\n//   assert(!(A->isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n\n//   unsigned int col = startCol;\n//   VectorOfVectors::const_iterator it;\n//   for(it = y->begin(); it != y->end(); ++it)\n//   {\n//     private_prod(x, A, col, *it, init);\n//     col += (*it)->size();\n//   }\n// }\n\n// void private_addprod(double a, SPC::SiconosMatrix A, unsigned int startRow, unsigned int startCol, SPC::SiconosVector x, SP::SiconosVector y)\n// {\n//   assert(!(A->isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n\n//   if(A->isBlock())\n//      THROW_EXCEPTION(\"not yet implemented for block matrix.\");\n\n//   // we take a submatrix subA of A, starting from row startRow to row (startRow+sizeY) and between columns startCol and (startCol+sizeX).\n//   // Then computation of y = subA*x + y.\n//   Siconos::UBLAS_TYPE numA = A->num();\n//   Siconos::UBLAS_TYPE numY = y->num();\n//   Siconos::UBLAS_TYPE numX = x->num();\n//   unsigned int sizeX = x->size();\n//   unsigned int sizeY = y->size();\n\n//   if(numX != numY)\n//      THROW_EXCEPTION(\"not yet implemented for x and y of different types.\");\n\n//   if(numY == 1 && numX == 1)\n//   {\n\n//     assert(y->dense() != x->dense());\n\n//     if(numA == 1)\n//       noalias(*y->dense()) += a * prod(ublas::subrange(*A->dense(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n//     else if(numA == 2)\n//       noalias(*y->dense()) += a * prod(ublas::subrange(*A->triang(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n//     else if(numA == 3)\n//       noalias(*y->dense()) += a * prod(ublas::subrange(*A->sym(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n//     else if(numA == 4)\n//       noalias(*y->dense()) += a * prod(ublas::subrange(*A->sparse(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n//     else //if(numA==5)\n//       noalias(*y->dense()) += a * prod(ublas::subrange(*A->banded(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n//   }\n//   else // x and y sparse\n//   {\n//     if(numA == 4)\n//       *y->sparse() += a * prod(ublas::subrange(*A->sparse(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->sparse());\n//     else\n//        THROW_EXCEPTION(\"not yet implemented for x, y  sparse and A not sparse.\");\n//   }\n\n// }\n\n// void private_prod(double a, SPC::SiconosMatrix A, unsigned int startRow, SPC::SiconosVector x, SP::SiconosVector  y, bool init)\n// {\n//   assert(!(A->isPLUFactorizedInPlace()) && \"A is PLUFactorizedInPlace in prod !!\");\n\n\n//   // Computes y = subA *x (or += if init = false), subA being a sub-matrix of A, between el. of index (row) startRow and startRow + sizeY\n\n//   if(init)  // y = subA * x , else y += subA * x\n//     y->zero();\n//   private_addprod(a, A, startRow, 0, x, y);\n\n// }\n\nunsigned SimpleMatrix::copyData(double* data) const\n{\n  assert((_num == Siconos::DENSE) && \"SiconosMatrix::copyData : forbidden: the current matrix is not dense.\");\n\n  unsigned size = mat.Dense->size1() * mat.Dense->size2();\n  siconosBindings::detail::copy(size, getArray(), 1, data, 1);\n  return size;\n}\n", "meta": {"hexsha": "aaf01a2be5bae31d4cb2f07fcfcba24edd2f2a12", "size": 34467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrix.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/SimpleMatrix.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/SimpleMatrix.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": 29.7385677308, "max_line_length": 170, "alphanum_fraction": 0.6207096643, "num_tokens": 10240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18902096894735457}}
{"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_BOOLEAN_FUNCTIONS_SIMD_COMMON_SELSUB_HPP_INCLUDED\n#define BOOST_SIMD_BOOLEAN_FUNCTIONS_SIMD_COMMON_SELSUB_HPP_INCLUDED\n\n#include <boost/simd/boolean/functions/selsub.hpp>\n#include <boost/simd/include/functions/simd/if_else_zero.hpp>\n#include <boost/simd/include/functions/simd/minus.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/negate.hpp>\n#include <boost/simd/sdk/meta/cardinal_of.hpp>\n#include <boost/mpl/equal_to.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION_IF ( boost::simd::tag::selsub_, tag::cpu_, (A0)(A1)(X)\n                                , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                                        , boost::simd::meta::cardinal_of<A1>\n                                                        >\n                                  )\n                                , ((simd_<unspecified_<A0>,X>))\n                                  ((simd_<unspecified_<A1>,X>))\n                                  ((simd_<unspecified_<A1>,X>))\n                                )\n  {\n    typedef A1 result_type;\n    inline result_type operator()(A0 const& a0, A1 const& a1, A1 const& a2) const\n    {\n     return a1 - if_else_zero(a0, a2);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION_IF ( boost::simd::tag::selsub_, tag::cpu_, (A0)(A1)(X)\n                                , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                                        , boost::simd::meta::cardinal_of<A1>\n                                                        >\n                                  )\n                                , ((simd_<unspecified_<A0>,X>))\n                                  ((simd_<floating_<A1>,X>))\n                                  ((simd_<floating_<A1>,X>))\n                                )\n  {\n    typedef A1 result_type;\n    inline result_type operator()(A0 const& a0, A1 const& a1, A1 const& a2) const\n    {\n      // this is a workaround for a gcc (at least 4.6) over-optimization in case or a1 and a2 are\n      // equal (constant?) and invalid (inf -inf or nan) in which case the general impl sometimes\n      // return 0 in place of nan in float cases.\n     return a1 + if_else_zero(a0, -a2);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "a0ce95b7a9e220ee1dd584b936cd2fda95b188e4", "size": 2844, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/boolean/include/boost/simd/boolean/functions/simd/common/selsub.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/boost/simd/boolean/include/boost/simd/boolean/functions/simd/common/selsub.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/boost/simd/boolean/include/boost/simd/boolean/functions/simd/common/selsub.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": 46.6229508197, "max_line_length": 97, "alphanum_fraction": 0.5, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.18902096537918742}}
{"text": "#include \"wheelcontroller.h\"\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n#include <thread>\n\n#define deg150 (150.0 * PI / 180.0)\n#define deg30 (30.0 * PI / 180.0)\n#define deg270 (270.0 * PI / 180.0)\n//#define LIMIT_ACCELERATION\n\nWheelController::WheelController() : ThreadedClass(\"WheelController\")\n{\n\tw_left = NULL;\n\tw_right = NULL;\n\tw_back = NULL;\n\ttargetSpeed = { 0, 0, 0 };\n};\n\nvoid WheelController::InitWheels(boost::asio::io_service &io, bool useDummyPorts/* = false*/)\n{\n\tusing boost::property_tree::ptree;\n\tptree pt;\n\tif (useDummyPorts) {\n\t\tw_left = new SoftwareWheel(\"left\");\n\t\tw_right = new SoftwareWheel(\"right\");\n\t\tw_back = new SoftwareWheel(\"back\");\n\n\t}\n\telse {\n\t\tread_ini(\"conf/ports.ini\", pt);\n\n\t\tstd::cout << \"left wheel \" << std::to_string(ID_WHEEL_LEFT) << \" \" << pt.get<std::string>(std::to_string(ID_WHEEL_LEFT)) << std::endl;\n\t\tw_left = new SerialWheel(io, pt.get<std::string>(std::to_string(ID_WHEEL_LEFT)), 115200, \"left\");\n\n\n\t\tstd::cout << \"right wheel \" << std::to_string(ID_WHEEL_RIGHT) << \" \" << pt.get<std::string>(std::to_string(ID_WHEEL_RIGHT)) << std::endl;\n\t\tw_right = new SerialWheel(io, pt.get<std::string>(std::to_string(ID_WHEEL_RIGHT)), 115200, \"right\");\n\n\n\t\tstd::cout << \"back wheel \" << std::to_string(ID_WHEEL_BACK) << \" \" << pt.get<std::string>(std::to_string(ID_WHEEL_BACK)) << std::endl;\n\t\tw_back = new SerialWheel(io, pt.get<std::string>(std::to_string(ID_WHEEL_BACK)), 115200, \"back\");\n\t\tstd::cout << \"wheels done\" << std::endl;\n\n\t}\n\tw_left->Start();\n\tw_right->Start();\n\tw_back->Start();\n\tStart();\n\n}\n\nvoid WheelController::DestroyWheels()\n{\n\tif (w_left != NULL) {\n\t\tdelete w_left;\n\t\tw_left = NULL;\n\t}\n\tif (w_right != NULL) {\n\t\tdelete w_right;\n\t\tw_right = NULL;\n\t}\n\tif (w_back != NULL) {\n\t\tdelete w_back;\n\t\tw_back = NULL;\n\n\t}\n};\nWheelController::~WheelController()\n{\n\tStop();\n\tWaitForStop();\n\tDestroyWheels();\n}\nvoid WheelController::Forward(int speed) {\n\n\tDriveRotate(speed * 1.1547, 0, 0);\n\n}\nvoid WheelController::Rotate(bool direction, double speed)\n{\n\tDriveRotate(0,0, direction ? speed : -speed);\n}\nvoid WheelController::Drive(double velocity, double direction)\n{\n\tDriveRotate(velocity, direction, 0);\n}\n\nvoid WheelController::DriveRotate(double velocity, double direction, double rotate)\n{\n\t//std::cout << \"DriveRotate: \" << velocity << std::endl;\n\n\tif (abs(velocity) > 190){\n\t\tif (velocity > 0){\n\t\t\tvelocity = 190;\n\t\t}\n\t\telse{\n\t\t\tvelocity = -190;\n\t\t}\n\t}\n\n\n\tif ((abs(rotate) + velocity) > 190){\n\t\tif (rotate > 0){\n\t\t\tvelocity = velocity - rotate;\n\t\t}\n\t\telse{\n\t\t\tvelocity = velocity + rotate;\n\t\t}\n\t\t\t\n\t}\n\t//double sign = (velocity > 0) - (velocity < 0);\n\t//velocity = sign*std::min(190.0, abs(velocity + rotate)) - rotate;\n\n\ttargetSpeed.velocity = velocity; // sin(direction* PI / 180.0)* velocity + rotate;\n\ttargetSpeed.heading = direction; //cos(direction* PI / 180.0)* velocity + rotate,\n\ttargetSpeed.rotation = rotate;\n#ifndef LIMIT_ACCELERATION\n\t\tauto speeds = CalculateWheelSpeeds(targetSpeed.velocity, targetSpeed.heading, targetSpeed.rotation);\n\tif (w_left != NULL) w_left->SetSpeed(speeds.x);\n\tif (w_right != NULL) w_right->SetSpeed(speeds.y);\n\tif (w_back != NULL) w_back->SetSpeed(speeds.z);\n#endif\n\tdirectControl = false;\n\tupdateSpeed = true;\n\tlastUpdate = boost::posix_time::microsec_clock::local_time();\n\n\t\n}\ncv::Point3d WheelController::CalculateWheelSpeeds(double velocity, double direction, double rotate)\n{\n\treturn cv::Point3d(\n\t\t(velocity*cos((150 - direction) * PI / 180.0)) + rotate,\n\t\t((velocity*cos((30 - direction)  * PI / 180.0)) + rotate),\n\t\t(velocity*cos((270 - direction)  * PI / 180.0)) + rotate\n\t);\n}\nvoid WheelController::Stop()\n{\n\tDrive(0,0);\n}\n\nbool WheelController::IsStalled()\n{\n\tif (directControl) return false;\n\n\tif (targetSpeed.velocity < 0.01 || actualSpeed.velocity > 90){\n\t\tstallTime = boost::posix_time::microsec_clock::local_time();\n\t\treturn false;\n\t}\n\tboost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();\n\tboost::posix_time::time_duration::tick_type stallDuration = (time - stallTime).total_milliseconds();\n\t//std::cout << \"stall? \" << velocity << \", \" << velocity2 << \"t: \" << stallDuration << std::endl;\n\n\t\t\n\tif (abs(actualSpeed.velocity - targetSpeed.velocity) < 10) {\n\t\t// reset timer\n\t\tstallTime = boost::posix_time::microsec_clock::local_time();\n\t}else {\n\t\t//std::cout << \"stall? \" << velocity << \", \" << velocity2 << \"t: \" << stallDuration << std::endl;\n\t\treturn stallDuration > 600;\n\t\n\t}\n\treturn false;\n\n\t//return w_left->IsStalled() || w_right->IsStalled() || w_back->IsStalled();\n}\nbool WheelController::HasError()\n{\n\treturn w_left->HasError() || w_right->HasError() || w_back->HasError();\n}\n\ncv::Point3d WheelController::GetWheelSpeeds()\n{\n\treturn cv::Point3d(w_left->GetSpeed(), w_right->GetSpeed(), w_back->GetSpeed());\n}\n\nvoid WheelController::CalculateRobotSpeed()\n{\n\tlastSpeed = actualSpeed;\n\tcv::Point3d speeds = GetWheelSpeeds();\n\tdouble a, b, c, u, v, w;\n\t/*\n\ta = x *[cos(u) * cos(y) + sin(u) * sin(y)] + z\n\tb = x *[cos(v) * cos(y) + sin(v) * sin(y)] + z\n\tc = x *[cos(w) * cos(y) + sin(w) * sin(y)] + z\n\t*/\n\tif (abs(speeds.z - speeds.x) > 0.0000001) { // c - a == 0\n\t\ta = speeds.x; b = speeds.y; c = speeds.z;\n\t\tu = deg150; v = deg30; w = deg270;\n\t}\n\telse if (abs(speeds.x - speeds.y) > 0.0000001) {\n\t\ta = speeds.y; b = speeds.z; c = speeds.x;\n\t\tu = deg30; v = deg270; w = deg30;\n\t}\n\telse if (abs(speeds.z - speeds.y) > 0.0000001) {\n\t\ta = speeds.z; b = speeds.x; c = speeds.y;\n\t\tu = deg270; v = deg30; w = deg150;\n\t}\n\telse {\n\t\t// all equal, rotation only\n\t\tactualSpeed.velocity = 0;\n\t\tactualSpeed.heading = 0;\n\t\tactualSpeed.rotation = speeds.x;\n\t\treturn;\n\n\t}\n\tdouble s = (b - a) / (c - a);\n\tdouble directionInRad = atan(((cos(v) - cos(u)) - s * (cos(w) - cos(u))) / (s * (sin(w) - sin(u)) - (sin(v) - sin(u))));\n\t//if (directionInRad < 0) directionInRad += 2 * PI;\n\tactualSpeed.heading = directionInRad / PI * 180;\n\tactualSpeed.velocity = (a - c) / ((cos(u) - cos(w)) * cos(directionInRad) + (sin(u) - sin(w)) * sin(directionInRad));\n\tactualSpeed.rotation = c - (actualSpeed.velocity  * cos(w - directionInRad));\n\n}\n\nconst Speed &  WheelController::GetTargetSpeed()\n{\n\treturn targetSpeed;\n}\n\nconst Speed &  WheelController::GetActualSpeed()\n{\n\treturn actualSpeed;\n}\n\nstd::string WheelController::GetDebugInfo(){\n\n\tstd::ostringstream oss;\n\toss.precision(4);\n\toss << \"[WheelController] target: \" << \"velocity: \" << targetSpeed.velocity << \", heading: \" << targetSpeed.heading << \", rotate: \" << targetSpeed.rotation << \"|\";\n\toss << \"[WheelController] actual: \" << \"velocity: \" << actualSpeed.velocity << \", heading: \" << actualSpeed.heading << \", rotate: \" << actualSpeed.rotation << \"|\";\n\tcv::Point3d speeds = GetWheelSpeeds();\n\tauto speeds2 = CalculateWheelSpeeds(targetSpeed.velocity, targetSpeed.heading, targetSpeed.rotation);\n\toss << \"[Wheels] target: \" << \"left  : \" << speeds2.x << \", right: \" << speeds2.y << \", back: \" << speeds2.z << \"|\";\n\toss << \"[Wheels] actual: \" << \"left  : \" << speeds.x << \", right: \" << speeds.y << \", back: \" << speeds.x << \"|\";\n\t//oss << \"[WheelController] pos: \" << \"x: \" << robotPos.x << \", y: \" << robotPos.y << \", r: \" << robotPos.z;\n\treturn oss.str();\n}\n\n\nvoid WheelController::Run()\n{\n\twhile (!stop_thread) {\n\t\tCalculateRobotSpeed();\n#ifdef LIMIT_ACCELERATION\n\t\tboost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();\n\t\tif (!updateSpeed && (now - lastUpdate).total_milliseconds() > 500) {\n\t\t\ttargetSpeed = {0,0,0};\n\t\t}\n\t\tupdateSpeed = false;\n\t\tSpeed speed = targetSpeed;\n\t\tdouble dt = (double)(now - lastStep).total_milliseconds() / 1000.0;\n\t\tif (dt < 0.0000001) continue;\n\n\t\tif (abs(actualSpeed.velocity) > 1000) {\n\t\t\tstd::cout << \"to big actual velocity: \" << actualSpeed.velocity << \"wheel speeds: \" << GetWheelSpeeds() << std::endl;\n\t\t\tactualSpeed.velocity = 0;\n\n\t\t}\n\t\tdouble dv = targetSpeed.velocity - actualSpeed.velocity;\n\t\tdouble sign = (dv > 0) - (dv < 0);\n\t\tdouble acc = dv / dt;\n\n\t\tacc = sign * std::min(fabs(acc), 500.0);\n\t\tspeed.velocity = acc*dt + actualSpeed.velocity;\n\n\t\tauto speeds = CalculateWheelSpeeds(speed.velocity, speed.heading, speed.rotation);\n\t\t//std::cout << \"wheel speeds, left: \" << speeds.x << \", right: \" << speeds.y << \", back: \" << speeds.z << std::endl;\n\t\tw_left->SetSpeed(speeds.x);\n\t\tw_right->SetSpeed(speeds.y);\n\t\tw_back->SetSpeed(speeds.z);\n\t\tlastStep = now;\n#endif\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(10)); // do not poll serial to fast\n\t}\n\tstd::cout << \"WheelController stoping\" << std::endl;\n\t\n}\n", "meta": {"hexsha": "54b70199273ed9e290bb93dd8efe1544a71edca6", "size": 8507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wheelcontroller.cpp", "max_stars_repo_name": "andresviikmaa/Robotiina", "max_stars_repo_head_hexsha": "985de6e2afa159d7420b8a5f94d87d3a66fb3c17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-03-18T08:19:38.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-18T08:19:38.000Z", "max_issues_repo_path": "wheelcontroller.cpp", "max_issues_repo_name": "andresviikmaa/Robotiina", "max_issues_repo_head_hexsha": "985de6e2afa159d7420b8a5f94d87d3a66fb3c17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wheelcontroller.cpp", "max_forks_repo_name": "andresviikmaa/Robotiina", "max_forks_repo_head_hexsha": "985de6e2afa159d7420b8a5f94d87d3a66fb3c17", "max_forks_repo_licenses": ["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.4910394265, "max_line_length": 164, "alphanum_fraction": 0.6485247443, "num_tokens": 2549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.18902096181102038}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"util.h\"\n#include \"scrypt.h\"\n#include \"main.h\"\n\nBOOST_AUTO_TEST_SUITE(scrypt_tests)\n\nBOOST_AUTO_TEST_CASE(scrypt_hashtest)\n{\n    // Test Scrypt hash with known inputs against expected outputs for all \n    // supported Nfactors, only goes up to N = 1048576 due to current 32 bit\n    // limit on nTime. Blocktime is packed in the pseudoheaders in inputhex\n    #define HASHCOUNT 50\n    const char* inputhex[HASHCOUNT] = {\n        \"\"\n    }; \n    const char* expected[HASHCOUNT] = { \n        \"\"\n    };\n    uint256 scrypthash;\n    std::vector<unsigned char> inputbytes;\n    \n    for (int i = 0; i < HASHCOUNT; i++) {\n        inputbytes = ParseHex(inputhex[i]);\n        unsigned int blocktime = *(unsigned int*)(&inputbytes[68]);\n        printf(\"%i\\n\", blocktime);\n        unsigned char Nfactor = GetNfactor(blocktime);\n        unsigned int scratchpad_size = 128 * (1 << (Nfactor+1)) + 512;\n        std::vector<char> scratchpad = std::vector<char>(scratchpad_size);\n#if defined(USE_SSE2)\n        // Test SSE2 scrypt\n        scrypt_N_1_1_256_sp_sse2((const char*)&inputbytes[0], \n                                BEGIN(scrypthash), &scratchpad[0], \n                                Nfactor);\n#endif\n        // Test generic scrypt\n        scrypt_N_1_1_256_sp_generic((const char*)&inputbytes[0], \n                                    BEGIN(scrypthash), &scratchpad[0], \n                                    Nfactor);\n        BOOST_CHECK_EQUAL(scrypthash.ToString().c_str(), expected[i]);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d1be1f2d98093b31a2b4da6c67a2115041f8d067", "size": 1558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/scrypt_tests.cpp", "max_stars_repo_name": "damarkanginan/Speedcoin", "max_stars_repo_head_hexsha": "69d802b6ef6589c80341fa5cf9bf10238d1e3e3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-17T11:48:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T00:59:20.000Z", "max_issues_repo_path": "src/test/scrypt_tests.cpp", "max_issues_repo_name": "damarkanginan/Speedcoin", "max_issues_repo_head_hexsha": "69d802b6ef6589c80341fa5cf9bf10238d1e3e3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-01T21:11:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-04T11:37:03.000Z", "max_forks_repo_path": "src/test/scrypt_tests.cpp", "max_forks_repo_name": "damarkanginan/Speedcoin", "max_forks_repo_head_hexsha": "69d802b6ef6589c80341fa5cf9bf10238d1e3e3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T05:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-19T13:26:48.000Z", "avg_line_length": 33.8695652174, "max_line_length": 76, "alphanum_fraction": 0.6026957638, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.18899096550251815}}
{"text": "// Copyright (c) 2017, Adam Allevato\n// Copyright (c) 2017, The University of Texas at Austin\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\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 \"AS\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"orp/core/nn_classifier.h\"\n\n#include <boost/filesystem.hpp>\n#include <boost/regex.hpp>\n\nNNClassifier::NNClassifier() :\n  Classifier3D()\n{\n  srand (static_cast <unsigned> (time(0)));\n\n  node_private_.param<std::string>(\"data_folder\", dataFolder, \"/\");\n  node_private_.param<std::string>(\"file_extension\", fileExtension, \"/\");\n  node_private_.param<float>(\"threshold\", threshold, 10000.0f);\n}\n\nvoid NNClassifier::init() {\n  //parse the params on the parameter server\n  loadTypeList();\n  if(!ros::isShuttingDown()) {\n\n    loadModelsRecursive(dataFolder, fileExtension, loadedModels);\n    ROS_INFO(\"Loaded %d models.\\n\", (int)loadedModels.size());\n\n    if(loadedModels.size() < 1)\n    {\n      ROS_WARN (\"No models loaded from %s.\", dataFolder.c_str());\n    } else {\n      subModels = loadedModels;\n\n      // Convert data into FLANN format\n      kData = new flann::Matrix<float>(\n        new float[subModels.size() * subModels[0].second.size()],\n        subModels.size(),\n        subModels[0].second.size());\n\n      ROS_INFO_STREAM(\"data size: [\" << kData->rows <<\n                      \" , \" << kData->cols << \"]\");\n      for(size_t i = 0; i < kData->rows; ++i)\n      {\n        for(size_t j = 0; j < kData->cols; ++j)\n        {\n          *(kData->ptr()+(i*kData->cols + j)) = subModels[i].second[j];\n        }\n      }\n\n      kIndex = new flann::Index<flann::ChiSquareDistance<float> >(\n          *kData, flann::LinearIndexParams ());\n      kIndex->buildIndex();\n    }\n    ROS_INFO(\"Training data loaded.\");\n  }\n  Classifier::init();\n}\n\nvoid NNClassifier::loadTypeList() {\n  XmlRpc::XmlRpcValue paramMap;\n  std::vector<WorldObjectType> objects;\n  while(!node_.getParam(\"items\", paramMap)) {\n    ROS_INFO_DELAYED_THROTTLE(5.0,\n                      \"Waiting for object type list on parameter server...\");\n    ros::Duration(1.0).sleep();\n  }\n  for(XmlRpc::XmlRpcValue::iterator it = paramMap.begin();\n      it != paramMap.end(); ++it) {\n    fullTypeList.push_back(it->first);\n  }\n}\n\nNNClassifier::~NNClassifier() {\n  delete[] kData->ptr();\n  delete kIndex;\n}\n\nint NNClassifier::nearestKSearch(\n  flann::Index<flann::ChiSquareDistance<float> > &index,\n  const FeatureVector &homeFeature,\n  int k,\n  flann::Matrix<int> &indices,\n  flann::Matrix<float> &distances)\n{\n  int rows = 1;\n  // Query point\n  //flann::Matrix<float> home =\n  //  flann::Matrix<float>(\n  //    const_cast<float*>(&(homeFeature.second[0])),\n  //                       home.rows,\n  //                       homeFeature.second.size ());\n  flann::Matrix<float> home =\n      flann::Matrix<float>(\n        new float[homeFeature.second.size()],\n        rows,\n        homeFeature.second.size());\n  memcpy(&home.ptr ()[0],\n         &homeFeature.second.at(0),\n         home.cols * home.rows * sizeof (int));\n\n  indices =\n      flann::Matrix<int>(new int[home.rows*k], home.rows, k);\n  distances =\n      flann::Matrix<float>(new float[home.rows*k], home.rows, k);\n  int foundCount =\n      index.knnSearch (home, indices, distances, k, flann::SearchParams (128));\n\n  return foundCount;\n}\n\nvoid NNClassifier::loadModelsRecursive(\n  const boost::filesystem::path &base_dir,\n  const std::string &extension,\n  FeatureVectorVector &loadedModels)\n{\n  ROS_INFO(\"loading files from %s\", base_dir.string().c_str());\n  if(!boost::filesystem::is_directory (base_dir)) {\n    ROS_FATAL(\"target path %s is not a directory!\", base_dir.string().c_str());\n    return;\n  }\n  if(!boost::filesystem::exists (base_dir)) {\n    ROS_FATAL(\"target folder %s does not exist\", base_dir.string().c_str());\n    return;\n  }\n\n  for(boost::filesystem::directory_iterator it (base_dir);\n      it != boost::filesystem::directory_iterator (); ++it) {\n    if(boost::filesystem::is_directory(it->status ())) {\n      std::stringstream ss;\n      ss << it->path();\n      ROS_INFO(\"NOT traversing into directory %s.\", ss.str().c_str());\n    }\n    if(boost::filesystem::is_regular_file(it->status()) &&\n       boost::filesystem::extension(it->path()) == extension) {\n      FeatureVector m;\n      boost::regex pattern(\"\");\n      boost::cmatch what;\n      for(std::vector<std::string>::iterator types = fullTypeList.begin();\n          types != fullTypeList.end(); ++types) {\n        //match just the filename against the regex\n        pattern = boost::regex(\"(\" + *types + \")(.*)\");\n        if(boost::regex_match(\n           it->path().filename().string().c_str(), what, pattern))\n        {\n          if(loadHist(it->path(), m))\n          {\n            loadedModels.push_back(m);\n            ROS_INFO(\"Loading file %s\",\n                      it->path().filename().string().c_str());\n          } else\n          {\n            ROS_INFO_STREAM(\"histogram loader rejected file \" <<\n                            it->path().filename().string().c_str());\n          }\n        }\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "c59f6bf5554022d47b698c3f3be42f021e5fd75f", "size": 6441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nn_classifier.cpp", "max_stars_repo_name": "Kukanani/orp", "max_stars_repo_head_hexsha": "ff8eff74e1776691dfa7474bbd1e6a3d0d015a91", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-04T22:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-18T02:30:38.000Z", "max_issues_repo_path": "src/nn_classifier.cpp", "max_issues_repo_name": "Kukanani/orp", "max_issues_repo_head_hexsha": "ff8eff74e1776691dfa7474bbd1e6a3d0d015a91", "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/nn_classifier.cpp", "max_forks_repo_name": "Kukanani/orp", "max_forks_repo_head_hexsha": "ff8eff74e1776691dfa7474bbd1e6a3d0d015a91", "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.6290322581, "max_line_length": 79, "alphanum_fraction": 0.6402732495, "num_tokens": 1544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18899095824549045}}
{"text": "#define BOOST_TEST_MODULE pcraster model_engine dynamicwave\n#include <boost/test/unit_test.hpp>\n\n#include \"calc_globallibdefs.h\"\n#include \"geo_filecreatetester.h\"\n#include \"com_csfcell.h\"\n#include \"com_directory.h\"\n#include \"com_file.h\"\n#include \"calc_field.h\"\n#include \"calc_p5stack.h\"\n\n\n// NOTE use string failureExpected in files expected to fail, see style guide\n\nstruct Fixture\n{\n\n    Fixture()\n    {\n        calc::globalInit();\n    }\n\n\n    ~Fixture()\n    {\n        calc::globalEnd();\n    }\n\n};\n\n\n\nBOOST_FIXTURE_TEST_SUITE(dynamicwave, Fixture)\n\n\nBOOST_AUTO_TEST_CASE(testSimpleInput)\n{\n  using namespace calc;\n\n  // pcrcalc507 basic dynamicwave\n  // profileId=0,H=1,A=2,P=3\n  com::write(\"1 0 0 1\\n1 1 2000 2000\",\"tmp507.tbl\");\n\n  // first run no tests\n  execTest(\"pcrcalc507\");\n/*\n  // next some alterations:\n  const char* pcrcalc507a=\" \\\n      report tmp.state,tmp.flux=\\n \\\n      dynwavestate,dynwaveflux( \\n \\\n      tmp507.tbl,                  \\n \\\n      inp1n.map,  # profile id  \\n \\\n      inpldd.map,               \\n \\\n      %1%, # oldState            \\n \\\n      0, # inflow               \\n \\\n      0, # bottomLevel          \\n \\\n      1, # roughness            \\n \\\n      1, # segmentLength        \\n \\\n      10, # nrTimeSlices        \\n \\\n      1, # timestepInSecs       \\n \\\n      0  # constantState        \\n \\\n      );                        \\n \\\n      report p = lookuppotential(tmp507.tbl,inp1n.map,0,1,tmp.state); \\n \\\n      report s = lookupstate(tmp507.tbl,inp1n.map,0,1,p); \\n \\\n      report tmp.res = (tmp.state==s) && %2%;     \\n\";\n\n\n  { // state == 5 everywhere\n    geo::FileCreateTester state(\"tmp.state\");\n    geo::FileCreateTester  flux(\"tmp.flux\");\n    std::string testCmd((boost::format(pcrcalc507a)\n          % \"5\" % \"1==1\").str());\n    execTest(testCmd);\n\n    BOOST_CHECK(flux.equalTo(\"inp0s.map\",false));\n    BOOST_CHECK(state.equalTo(\"inp5s.map\",false));\n  }\n  { // state == distance ==> drop in the network\n    geo::FileCreateTester  res(\"tmp.res\");\n    std::string testCmd((boost::format(pcrcalc507a) %\n          \"ldddist(inpldd.map,inpldd.map==5,1)\" %\n          \"tmp.state >= 0 && tmp.flux >= 0\"\n          ).str());\n    execTest(testCmd);\n\n    BOOST_CHECK(res.equalTo(\"inp1b.map\",false));\n  }\n  { // state == 300-distance ==> only uphill\n    geo::FileCreateTester  res(\"tmp.res\");\n    std::string testCmd((boost::format(pcrcalc507a) %\n     \"300-ldddist(inpldd.map,inpldd.map==5,1)\" %\n     \"tmp.flux == 0 && tmp.state==(300-ldddist(inpldd.map,inpldd.map==5,1))\"\n     ).str());\n    execTest(testCmd);\n\n    BOOST_CHECK(res.equalTo(\"inp1b.map\",false));\n  }\n\n  { // state == 100000, to generate DomainError\n    geo::FileCreateTester state(\"tmp.state\");\n    geo::FileCreateTester  flux(\"tmp.flux\");\n    std::string testCmd((boost::format(pcrcalc507a)\n          % \"100000\" % \"1==1\").str());\n    TRY_TEST_MSG {\n      execTest(testCmd);\n    } CATCH_TEST_MSG(\"pcrcalc508\");\n    BOOST_CHECK(catched);\n  }\n*/\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "cdb938bb4038e3953f9372f4cbf2c42535ad6edd", "size": 2969, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_dynamicwavetest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "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": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_dynamicwavetest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_dynamicwavetest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.2743362832, "max_line_length": 77, "alphanum_fraction": 0.5870663523, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.18899095098846283}}
{"text": "#include \"stdafx.h\"\n#include \"hmac_sha_base64.h\"\n#include \"openssl/sha.h\"\n\n#include <boost/archive/iterators/binary_from_base64.hpp>\n#include <boost/archive/iterators/base64_from_binary.hpp>\n#include <boost/archive/iterators/transform_width.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing namespace core;\nusing namespace tools;\n\nuint8_t *coding=(uint8_t*)\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";                   //52...63\n\nenum\n{\n    UNABLE_TO_OPEN_INPUT_FILE,\n    UNABLE_TO_OPEN_OUTPUT_FILE,\n    UNABLE_TO_CREATE_OUTPUTBUFFER\n};\n\nuint8_t base64::lobyte(uint16_t w)\n{\n    return ((uint8_t)(((uint32_t)(w)) & 0xff));\n}\n\nuint8_t base64::hibyte(uint16_t w)\n{\n    return ((uint8_t)((((uint32_t)(w)) >> 8) & 0xff));\n}\n\nuint16_t base64::loword(uint32_t l)\n{\n    return ((uint16_t)(((uint32_t)(l)) & 0xffff));\n}\n\nuint16_t base64::hiword(uint32_t l)\n{\n    return ((uint16_t)((((uint32_t)(l)) >> 16) & 0xffff));\n}\n\nint32_t fchr(uint8_t c)\n{\n    int32_t i=0;\n    for (i=0;i < 64;i++) if (coding[i]==c) return (i);\n    return (-1);\n}\n\nint32_t base64::base64_decode(uint8_t *source,int32_t length, uint8_t *dst)\n{\n    int32_t temp =0;\n    int32_t i=0;\n    int32_t size =0;\n    int32_t cursor = 0;\n\n    for (;i<length/4;)\n    {\n        int32_t zeroes;\n        int32_t j;\n        cursor = 0;\n        zeroes = 0;\n\n        *((uint8_t*)&cursor+3) = source[i*4];\n        *((uint8_t*)&cursor+2) = source[i*4+1];\n        *((uint8_t*)&cursor+1) = source[i*4+2];\n        *((uint8_t*)&cursor) = source[i*4+3];\n        for (j =0 ;j <4; j++)\n        {\n            if (*((uint8_t*)&cursor +j) == '=')\n            {\n                *((uint8_t*)&cursor +j) =0;\n                zeroes++;\n                continue;\n            }\n            temp  = fchr( *((uint8_t*)&cursor +j) );\n            temp <<=6*j;\n            cursor &= ~(0xFF << j*8);\n            cursor ^= temp;\n        }\n        for (j = 0; j<3; j++)\n        {\n            dst[i*3+j] = *((uint8_t*)&cursor+2);\n            cursor <<=8;\n            size++;\n        }\n        i++;\n        size-=zeroes;\n    }\n    return size;\n}\n\nint32_t base64::base64_encode(uint8_t* source, int32_t length, uint8_t* dst)\n{\n    uint32_t cursor =0x0;\n    int32_t i=0,size =0, j =0,ostatok = (length%3);\n\n    for (;i<length - (length%3);)\n    {\n        *((uint8_t*)&cursor) = source[i+2];\n        *((uint8_t*)&cursor+1) = source[i+1];\n        *((uint8_t*)&cursor+2) = source[i];\n        i+=3;\n\n        //shift\n        for (j =0; j<4; j++ )\n        {\n            uint8_t zna4; // delete after debug\n            cursor <<=6;\n            zna4 = core::tools::base64::hibyte(core::tools::base64::hiword(cursor));\n            dst[size+j] = coding[zna4];\n            cursor &= 0x0FFFFFF;\n        }\n        size +=j;\n    }\n    if (ostatok)\n    {\n        cursor =0;\n        if (ostatok>1)\n        {\n            *((uint8_t*)&cursor) = source[i+1];\n            *((uint8_t*)&cursor+1) = source[i];\n        }\n        else\n            *((uint8_t*)&cursor) = source[i];\n\n        for (i = 0; i<ostatok+1; i++)\n        {\n            cursor<<=6;\n            if (ostatok == 1)\n            {\n                dst[size+i] = coding[core::tools::base64::hibyte(core::tools::base64::loword(cursor))];\n                cursor &= 0xFF;\n            }\n            else\n            {\n                dst[size+i] = coding[core::tools::base64::lobyte(core::tools::base64::hiword(cursor))];\n                cursor &= 0xFFFF;\n            }\n\n        }\n        size +=i;\n        for (j=0; j < 4 - i;j++)\n        {\n            dst[size] = '=';\n            size++;\n        }\n    }\n    return (size);\n}\n\n\nstd::string base64::hmac_base64(std::vector<uint8_t>& data, std::vector<uint8_t>& secret)\n{\n    const unsigned SHA_BLOCKSIZE = 64;\n\n    uint8_t* text = &data[0];\n    uint32_t textlen = (uint32_t)data.size();\n    uint8_t* key = &secret[0];\n    uint32_t keylen = (uint32_t)secret.size();\n\n#define MIR_SHA256_HASH_SIZE 32\n\n    unsigned char mdkey[MIR_SHA256_HASH_SIZE];\n    unsigned char k_ipad[SHA_BLOCKSIZE], k_opad[SHA_BLOCKSIZE];\n\n    SHA256_CTX ctx;\n\n    uint8_t res[MIR_SHA256_HASH_SIZE];\n\n    if ( keylen > SHA_BLOCKSIZE )\n    {\n        SHA256_Init( &ctx );\n        SHA256_Update( &ctx, key, keylen );\n        SHA256_Final( mdkey, &ctx );\n\n        keylen = 32;\n        key = mdkey;\n    }\n\n    memcpy( k_ipad, key, keylen );\n    memcpy( k_opad, key, keylen );\n    memset( k_ipad+keylen, 0x36, SHA_BLOCKSIZE - keylen );\n    memset( k_opad+keylen, 0x5c, SHA_BLOCKSIZE - keylen );\n\n    for ( uint32_t i = 0; i < keylen; i++ )\n    {\n        k_ipad[i] ^= 0x36;\n        k_opad[i] ^= 0x5c;\n    }\n\n    SHA256_Init( &ctx );\n    SHA256_Update( &ctx, k_ipad, SHA_BLOCKSIZE );\n    SHA256_Update( &ctx, text, (int32_t) textlen );\n    SHA256_Final( res, &ctx );\n\n    SHA256_Init( &ctx );\n    SHA256_Update( &ctx, k_opad,SHA_BLOCKSIZE );\n    SHA256_Update( &ctx, res, (int32_t)MIR_SHA256_HASH_SIZE );\n    SHA256_Final( res, &ctx );\n\n    std::vector<uint8_t> temp_buffer(MIR_SHA256_HASH_SIZE*2);\n    int32_t encoded = core::tools::base64::base64_encode((uint8_t*) res, MIR_SHA256_HASH_SIZE, &temp_buffer[0]);\n\n    return std::string((char*) &temp_buffer[0], encoded);\n}\n\nusing namespace boost::archive::iterators;\n\nstd::string base64::decode64(const std::string& val)\n{\n    typedef transform_width<binary_from_base64<std::string::const_iterator>, 8, 6> it;\n    return boost::algorithm::trim_right_copy_if(std::string(it(std::begin(val)), it(std::end(val))), [](char c) {\n        return c == '\\0';\n    });\n}\n\nstd::string base64::encode64(const std::string& val)\n{\n    typedef base64_from_binary<transform_width<std::string::const_iterator, 6, 8>> it;\n    auto tmp = std::string(it(std::begin(val)), it(std::end(val)));\n    return tmp.append((3 - val.size() % 3) % 3, '=');\n}\n\nvoid core::tools::sha256(std::string_view _string, char _sha[65])\n{\n    unsigned char hash[SHA256_DIGEST_LENGTH];\n\n    SHA256_CTX sha256;\n    SHA256_Init(&sha256);\n    SHA256_Update(&sha256, _string.data(), _string.size());\n    SHA256_Final(hash, &sha256);\n\n    for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i)\n    {\n        sprintf(_sha + (i * 2), \"%02x\", hash[i]);\n    }\n\n    _sha[64] = 0;\n}\n", "meta": {"hexsha": "3b7216b5d23554ffb98cbdf1d0b6af0328981f5d", "size": 6161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/tools/hmac_sha_base64.cpp", "max_stars_repo_name": "Qt-Widgets/im-desktop-imported", "max_stars_repo_head_hexsha": "85fed419229597bc10de59de268f5d898f853405", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-24T02:53:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T02:53:50.000Z", "max_issues_repo_path": "core/tools/hmac_sha_base64.cpp", "max_issues_repo_name": "Qt-Widgets/im-desktop-imported-widgets-collection", "max_issues_repo_head_hexsha": "85fed419229597bc10de59de268f5d898f853405", "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": "core/tools/hmac_sha_base64.cpp", "max_forks_repo_name": "Qt-Widgets/im-desktop-imported-widgets-collection", "max_forks_repo_head_hexsha": "85fed419229597bc10de59de268f5d898f853405", "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.6708333333, "max_line_length": 121, "alphanum_fraction": 0.5526700211, "num_tokens": 1879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.18899095098846283}}
{"text": "#ifdef USE_DARKNET\n\n#include <boost/filesystem.hpp>\n#include <fstream>\n#include <glog/logging.h>\n#include <opencv2/opencv.hpp>\n#include <sstream>\n#include <unordered_set>\n\n#include \"nexus/backend/darknet_model.h\"\n#include \"nexus/backend/slice.h\"\n#include \"nexus/backend/utils.h\"\n#include \"nexus/common/image.h\"\n#include \"nexus/proto/control.pb.h\"\n\nnamespace fs = boost::filesystem;\n\nnamespace nexus {\nnamespace backend {\n\nnamespace {\n\nimage cvmat_to_image(const cv::Mat& cv_img_rgb) {\n  int c = cv_img_rgb.channels();\n  int h = cv_img_rgb.rows;\n  int w = cv_img_rgb.cols;\n  image img = make_image(w, h, c);\n  int count = 0;\n  for (int k = 0; k < c; ++k) {\n    for (int i = 0; i < h; ++i) {\n      for (int j = 0; j < w; ++j) {\n        cv::Vec3b pixel = cv_img_rgb.at<cv::Vec3b>(i, j);\n        img.data[count++] = pixel.val[k] / 255.;\n      }\n    }\n  }\n  return img;\n}\n\n}\n\nDarknetModel::DarknetModel(int gpu_id, const ModelInstanceConfig& config) :\n    ModelInstance(gpu_id, config),\n    first_input_array_(true) {\n  // load darknet model\n  CHECK(model_info_[\"cfg_file\"]) << \"Missing cfg_file in the model info\";\n  CHECK(model_info_[\"weight_file\"]) << \"Missing weight_file in the model info\";\n  fs::path model_dir = fs::path(model_info_[\"model_dir\"].as<std::string>());\n  fs::path cfg_path = model_dir / model_info_[\"cfg_file\"].as<std::string>();\n  fs::path weight_path = model_dir / model_info_[\"weight_file\"].\n                         as<std::string>();\n  CHECK(fs::exists(cfg_path)) << \"Config file \" << cfg_path <<\n      \" doesn't exist\";\n  CHECK(fs::exists(weight_path)) << \"Weight file \" << weight_path <<\n      \" doesn't exist\";\n  image_height_ = 0;\n  image_width_ = 0;\n  if (model_session_.image_height() > 0) {\n    CHECK_GT(model_session_.image_width(), 0) << \"image_height and \" <<\n        \"image_width must be set at same time\";\n    image_height_ = model_session_.image_height();\n    image_width_ = model_session_.image_width();\n  }\n\n  // switch the current directory to the model directory as required\n  // for loading a model in the darknet\n  fs::path curr_dir = fs::current_path();\n  fs::current_path(weight_path.parent_path());\n  net_ = parse_network_cfg_spec(const_cast<char*>(cfg_path.string().c_str()),\n                                gpu_id, max_batch_, image_width_,\n                                image_height_);\n  load_weights(net_, const_cast<char*>(weight_path.string().c_str()));\n  fs::current_path(curr_dir);\n\n  // Get input and output's shape and size\n  auto input_layer = net_->layers[0];\n  input_shape_.set_dims({max_batch_, input_layer.c, input_layer.h,\n          input_layer.w});\n  input_size_ = input_shape_.NumElements(1);\n  auto output_layer = get_network_output_layer(net_);\n  output_shape_.set_dims({max_batch_, output_layer.out_c, output_layer.out_h,\n          output_layer.out_w});\n  output_size_ = output_shape_.NumElements(1);\n  LOG(INFO) << \"Model \" << model_session_id_ << \": input shape \" <<\n      input_shape_ << \" (\" << input_size_ << \"), output shape \" <<\n      output_shape_ << \" (\" << output_size_ << \")\";\n  // find the output layer id\n  for (int i = net_->n - 1; i > 0; --i) {\n    if (net_->layers[i].type != COST) {\n      output_layer_id_ = i;\n      break;\n    }\n  }\n  // Darknet doesn't have name for layers, so hardcode name as \"output\"\n  output_name_ = \"output\"; \n  // load classnames\n  if (model_info_[\"class_names\"]) {\n    fs::path cns_path = model_dir / model_info_[\"class_names\"].\n                        as<std::string>();\n    LoadClassnames(cns_path.string(), &classnames_);\n  }\n}\n\nDarknetModel::~DarknetModel() {\n  free_network(net_);\n}\n\nShape DarknetModel::InputShape() {\n  return input_shape_;\n}\n\nstd::unordered_map<std::string, Shape> DarknetModel::OutputShapes() {\n  return {{ output_name_, output_shape_ }};\n}\n\nArrayPtr DarknetModel::CreateInputGpuArray() {\n  std::shared_ptr<Array> arr;\n  if (first_input_array_) {\n    auto buf = std::make_shared<Buffer>(\n        net_->input_gpu, max_batch_ * input_size_ * sizeof(float),\n        gpu_device_);\n    arr = std::make_shared<Array>(DT_FLOAT, max_batch_ * input_size_, buf);\n    first_input_array_ = false;\n  } else {\n    arr = std::make_shared<Array>(DT_FLOAT, max_batch_ * input_size_,\n                                  gpu_device_);\n  }\n  return arr;\n}\n\nstd::unordered_map<std::string, ArrayPtr> DarknetModel::GetOutputGpuArrays() {\n  auto buf = std::make_shared<Buffer>(net_->layers[output_layer_id_].output_gpu,\n                                      max_batch_ * output_size_ * sizeof(float),\n                                      gpu_device_);\n  auto arr = std::make_shared<Array>(DT_FLOAT, max_batch_ * output_size_, buf);\n  return {{ output_name_, arr }};\n}\n\nvoid DarknetModel::Preprocess(std::shared_ptr<Task> task) {\n  auto prepare_image = [&](cv::Mat& cv_img) {\n#if 0\n    image img = cvmat_to_image(cv_img);\n    //image resized = resize_image(img, net_->w, net_->h);\n    image resized = letterbox_image(img, net_->w, net_->h);\n    size_t nfloats = net_->w * net_->h * 3;\n    auto buf = std::make_shared<Buffer>(\n        resized.data, nfloats * sizeof(float), cpu_device_, true);\n    free_image(img);\n#else\n    cv::Mat resized_image;\n    cv::resize(cv_img, resized_image, cv::Size(net_->w, net_->h));\n    image input = cvmat_to_image(resized_image);\n    size_t nfloats = net_->w * net_->h * 3;\n    auto buf = std::make_shared<Buffer>(\n        input.data, nfloats * sizeof(float), cpu_device_, true);\n#endif\n    auto in_arr = std::make_shared<Array>(DT_FLOAT, nfloats, buf);\n    task->AppendInput(in_arr);\n  };\n\n  const auto& query = task->query;\n  const auto& input_data = query.input();\n  switch (input_data.data_type()) {\n    case DT_IMAGE: {\n      cv::Mat cv_img_rgb = DecodeImage(input_data.image(), CO_RGB);\n      task->attrs[\"im_height\"] = cv_img_rgb.rows;\n      task->attrs[\"im_width\"] = cv_img_rgb.cols;\n      if (query.window_size() > 0) {\n        for (int i = 0; i < query.window_size(); ++i) {\n          auto rect = query.window(i);\n          cv::Mat crop_img = cv_img_rgb(cv::Rect(\n              rect.left(), rect.top(), rect.right() - rect.left(),\n              rect.bottom() - rect.top()));\n          prepare_image(crop_img);\n        }\n      } else {\n        prepare_image(cv_img_rgb);\n      }\n      break;\n    }\n    default:\n      task->result.set_status(INPUT_TYPE_INCORRECT);\n      task->result.set_error_message(\"Input type incorrect: \" +\n                                     DataType_Name(input_data.data_type()));\n      break;\n  }\n}\n\nvoid DarknetModel::Forward(std::shared_ptr<BatchTask> batch_task) {\n  size_t batch_size = batch_task->batch_size();\n  net_->input_gpu = batch_task->GetInputArray()->Data<float>();\n  set_batch_network_lightweight(net_, batch_size);\n  network_predict_gpu_nocopy(net_);\n  layer l = net_->layers[output_layer_id_];\n  auto out_arr = batch_task->GetOutputArray(output_name_);\n  Memcpy(out_arr->Data<void>(), cpu_device_, l.output_gpu, gpu_device_,\n         batch_size * output_size_ * sizeof(float));\n  batch_task->SliceOutputBatch({{\n        output_name_, Slice(batch_size, output_size_) }});\n}\n\nvoid DarknetModel::Postprocess(std::shared_ptr<Task> task) {\n  const auto& query = task->query;\n  auto* result = &task->result;\n  result->set_status(CTRL_OK);\n  for (auto& output : task->outputs) {\n    auto out_arr = output->arrays.at(output_name_);\n    float* out_data = out_arr->Data<float>();\n    // TODO: check predicates in the query\n    if (type() == \"detection\") {\n      layer l = net_->layers[net_->n - 1];\n      size_t nboxes = l.w * l.h * l.n;\n      size_t nprobs = nboxes * (l.classes + 1);\n      int* boxes = new int[nboxes * 4];\n      float* probs = new float[nprobs];\n      int only_objectness = 0;\n      float tree_threshold = 0.5;\n      int relative = 1;\n      float nms = 0.3;\n      float threshold = 0.24;\n      int im_height = task->attrs[\"im_height\"].as<int>();\n      int im_width = task->attrs[\"im_width\"].as<int>();\n      output_detection_results(\n          out_data, l, im_width, im_height, net_->w, net_->h, threshold, probs,\n          nprobs, boxes, nboxes * 4, only_objectness, nullptr, tree_threshold,\n          relative, nms);\n      MarshalDetectionResult(query, probs, nprobs, boxes, nboxes, result);\n      delete[] boxes;\n      delete[] probs;\n    } else if (type() == \"classification\") {\n      if (classnames_.empty()) {\n        PostprocessClassification(query, out_data, output_size_, result);\n      } else {\n        PostprocessClassification(query, out_data, output_size_, result,\n                                  &classnames_);\n      }\n    } else {\n      std::ostringstream oss;\n      oss << \"Unsupported model type \" << type() << \" for \" << framework();\n      result->set_status(MODEL_TYPE_NOT_SUPPORT);\n      result->set_error_message(oss.str());\n      break;\n    }\n  }\n}\n\nvoid DarknetModel::MarshalDetectionResult(\n    const QueryProto& query, const float* probs, size_t nprobs,\n    const int* boxes, size_t nboxes, QueryResultProto* result) {\n  std::vector<std::string> output_fields(query.output_field().begin(),\n                                         query.output_field().end());\n  if (output_fields.size() == 0) {\n    output_fields.push_back(\"rect\");\n    output_fields.push_back(\"class_name\");\n  }\n  size_t nclasses_plus_1 = nprobs / nboxes;\n  for (size_t i = 0; i < nboxes; ++i) {\n    const float* ps = &probs[i * nclasses_plus_1];\n    const int* bs = &boxes[i * 4];\n    bool allzero = true;\n    for (size_t j = 0; j < 4; ++j) {\n      if (bs[j] != 0) {\n        allzero = false;\n        break;\n      }\n    }\n    if (allzero) {\n      continue;\n    }\n    float max_prob = 0.;\n    int max_idx = -1;\n    for (size_t j = 0; j < nclasses_plus_1 - 1; ++j) {\n      float p = float(ps[j]);\n      if (p > 0) {\n        if (p > max_prob) {\n          max_prob = p;\n          max_idx = j;\n        }\n      }\n    }\n    // fill in detection result\n    auto record = result->add_output();\n    for (auto field : output_fields) {\n      if (field == \"rect\") {\n        auto value = record->add_named_value();\n        value->set_name(\"rect\");\n        value->set_data_type(DT_RECT);\n        auto rect = value->mutable_rect();\n        rect->set_left(bs[0]);\n        rect->set_right(bs[1]);\n        rect->set_top(bs[2]);\n        rect->set_bottom(bs[3]);\n      } else if (field == \"objectness\") {\n        auto value = record->add_named_value();\n        value->set_name(\"objectness\");\n        value->set_data_type(DT_FLOAT);\n        value->set_f(ps[nclasses_plus_1 - 1]);\n      } else if (field == \"class_id\") {\n        auto value = record->add_named_value();\n        value->set_name(\"class_id\");\n        value->set_data_type(DT_INT32);\n        value->set_i(max_idx);\n      } else if (field == \"class_prob\") {\n        auto value = record->add_named_value();\n        value->set_name(\"class_prob\");\n        value->set_data_type(DT_FLOAT);\n        value->set_f(max_prob);\n      } else if (field == \"class_name\") {\n        auto value = record->add_named_value();\n        value->set_name(\"class_name\");\n        value->set_data_type(DT_STRING);\n        if (classnames_.size() > max_idx) {\n          value->set_s(classnames_.at(max_idx));\n        }\n      }\n    }\n  }\n}\n\n} // namespace backend\n} // namespace nexus\n\n#endif // USE_DARKNET\n", "meta": {"hexsha": "99e36770cf9dbf01b0c749d17f6b26e9bf0ee78b", "size": 11212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nexus/backend/darknet_model.cpp", "max_stars_repo_name": "levulinh/NCL-nexus", "max_stars_repo_head_hexsha": "bffb80c00cd57a66ce4bbb47d7b60cce1d49fdb4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2018-09-27T23:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T03:55:38.000Z", "max_issues_repo_path": "src/nexus/backend/darknet_model.cpp", "max_issues_repo_name": "levulinh/NCL-nexus", "max_issues_repo_head_hexsha": "bffb80c00cd57a66ce4bbb47d7b60cce1d49fdb4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-02-10T21:33:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T04:25:45.000Z", "max_forks_repo_path": "src/nexus/backend/darknet_model.cpp", "max_forks_repo_name": "levulinh/NCL-nexus", "max_forks_repo_head_hexsha": "bffb80c00cd57a66ce4bbb47d7b60cce1d49fdb4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T21:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T03:55:24.000Z", "avg_line_length": 34.6049382716, "max_line_length": 80, "alphanum_fraction": 0.6185337139, "num_tokens": 2954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.320821307318384, "lm_q1q2_score": 0.18892818079852264}}
{"text": "/*-\n * SPDX-License-Identifier: BSD-2-Clause\n * \n * Copyright (c) 2021 NKI/AVL, Netherlands Cancer Institute\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\n#include <fstream>\n#include <iomanip>\n\n#include <cif++/CifUtils.hpp>\n#include <cif++/Structure.hpp>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/date_time.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/program_options.hpp>\n\n#include <zeep/json/element.hpp>\n\n#include \"blast.hpp\"\n#include \"queue.hpp\"\n#include \"revision.hpp\"\n\nnamespace po = boost::program_options;\nnamespace fs = std::filesystem;\nnamespace io = boost::iostreams;\nnamespace ba = boost::algorithm;\n\nusing json = zeep::json::element;\n\n// --------------------------------------------------------------------\n\nusing mmcif::Point;\n\nstruct CAtom\n{\n\tCAtom(const CAtom &) = default;\n\tCAtom(CAtom &&) = default;\n\n\tCAtom(mmcif::AtomType type, Point pt, int charge)\n\t\t: type(type), pt(pt)\n\t{\n\t\tradius = charge == 0 ?\n\t\t\tmmcif::AtomTypeTraits(type).radius(mmcif::RadiusType::VanderWaals) : \n\t\t\tmmcif::AtomTypeTraits(type).effective_ionic_radius(charge);\n\n\t\tif (std::isnan(radius))\n\t\t\tthrow std::runtime_error(\"Unknown radius for atom \" + mmcif::AtomTypeTraits(type).symbol() + \" with charge \" + std::to_string(charge));\n\t}\n\n\tCAtom(const mmcif::Atom &atom)\n\t\t: CAtom(atom.type(), atom.location(), atom.charge())\n\t{\n\t}\n\n\tmmcif::AtomType type;\n\tPoint pt;\n\tfloat radius;\n};\n\n// --------------------------------------------------------------------\n\njson CalculateClashScore(const std::vector<CAtom> &polyAtoms, const std::vector<CAtom> &resAtoms, float maxDistance)\n{\n\tauto maxDistanceSq = maxDistance * maxDistance;\n\n\tjson result;\n\n\tauto &dp = result[\"distance\"];\n\n\tint n = 0, o = 0;\n\tdouble sumOverlapSq = 0;\n\n\tfor (auto &pa : polyAtoms)\n\t{\n\t\tbool near = false;\n\n\t\tfor (auto &ra : resAtoms)\n\t\t{\n\t\t\tauto d = DistanceSquared(pa.pt, ra.pt);\n\n\t\t\tif (d >= maxDistanceSq)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tnear = true;\n\n\t\t\td = std::sqrt(d);\n\n\t\t\tauto overlap = pa.radius + ra.radius - d;\n\t\t\tif (overlap < 0)\n\t\t\t\toverlap = 0;\n\t\t\t\n\t\t\tif (overlap > 0)\n\t\t\t{\n\t\t\t\t++n;\n\t\t\t\tsumOverlapSq += overlap * overlap;\n\t\t\t}\n\t\t\t\n\t\t\tjson d_pair;\n\t\t\td_pair.push_back(d);\n\t\t\td_pair.push_back(overlap);\n\n\t\t\tdp.push_back(std::move(d_pair));\n\t\t}\n\n\t\tif (near)\n\t\t\t++o;\n\t}\n\n\tresult[\"score\"] = o ? sumOverlapSq / o : 0;\n\tresult[\"clash_count\"] = n;\n\tresult[\"poly_atom_count\"] = o;\n\tresult[\"ligand_atom_count\"] = resAtoms.size();\n\n\treturn result;\n}\n\n// --------------------------------------------------------------------\n\nint a_main(int argc, const char *argv[])\n{\n\tusing namespace std::literals;\n\tusing namespace cif::literals;\n\n\tpo::options_description visible_options(argv[0] + \" [options] input-file [output-file]\"s);\n\n\tvisible_options.add_options()\n\t\t(\"distance-cutoff\", po::value<float>()->default_value(4), \"The max distance between polymer atoms and ligand atoms used in calculating clash scores\")\n\t\t(\"config\", po::value<std::string>(), \"Config file\")\n\t\t(\"help,h\", \"Display help message\")\n\t\t(\"version\", \"Print version\")\n\t\t(\"verbose,v\", \"Verbose output\")\n\t\t(\"quiet\", \"Do not produce warnings\");\n\n\tpo::options_description hidden_options(\"hidden options\");\n\thidden_options.add_options()\n\t\t(\"xyzin,i\", po::value<std::string>(), \"coordinates file\")\n\t\t(\"output,o\", po::value<std::string>(), \"Output to this file\")\n\t\t(\"debug,d\", po::value<int>(), \"Debug level (for even more verbose output)\");\n\n\tpo::options_description cmdline_options;\n\tcmdline_options.add(visible_options).add(hidden_options);\n\n\tpo::positional_options_description p;\n\tp.add(\"xyzin\", 1);\n\tp.add(\"output\", 1);\n\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n\n\tfs::path configFile = \"alphafill.conf\";\n\tif (vm.count(\"config\"))\n\t\tconfigFile = vm[\"config\"].as<std::string>();\n\n\tif (not fs::exists(configFile) and getenv(\"HOME\") != nullptr)\n\t\tconfigFile = fs::path(getenv(\"HOME\")) / \".config\" / configFile;\n\n\tif (fs::exists(configFile))\n\t{\n\t\tstd::ifstream cfgFile(configFile);\n\t\tif (cfgFile.is_open())\n\t\t\tpo::store(po::parse_config_file(cfgFile, visible_options, true), vm);\n\t}\n\n\tpo::notify(vm);\n\n\t// --------------------------------------------------------------------\n\n\tif (vm.count(\"version\"))\n\t{\n\t\twrite_version_string(std::cout, vm.count(\"verbose\"));\n\t\texit(0);\n\t}\n\n\tif (vm.count(\"help\") or vm.count(\"xyzin\") == 0)\n\t{\n\t\tstd::cout << visible_options << std::endl;\n\t\texit(vm.count(\"help\") ? 0 : 1);\n\t}\n\n\tif (vm.count(\"quiet\"))\n\t\tcif::VERBOSE = -1;\n\n\tif (vm.count(\"verbose\"))\n\t\tcif::VERBOSE = 1;\n\n\tif (vm.count(\"debug\"))\n\t\tcif::VERBOSE = vm[\"debug\"].as<int>();\n\n\tfloat maxDistance = vm[\"distance-cutoff\"].as<float>();\n\n\t// --------------------------------------------------------------------\n\t\n\tfs::path xyzin = vm[\"xyzin\"].as<std::string>();\n\tmmcif::File f(xyzin);\n\tmmcif::Structure structure(f, 1, mmcif::StructureOpenOptions::SkipHydrogen);\n\t\n\tauto &db = f.data();\n\n\tauto &polies = structure.polymers();\n\tif (polies.size() != 1)\n\t\tthrow std::runtime_error(\"Number of polymers in this file is not exactly 1\");\n\n\tauto &poly = polies.front();\n\n\tstd::vector<CAtom> polyAtoms;\n\n\tfor (auto &res : poly)\n\t{\n\t\tfor (auto &atom : res.atoms())\n\t\t\tpolyAtoms.emplace_back(atom);\n\t}\n\n\tstd::vector<std::string> ligandIDs;\n\tfor (auto &&[id] : db[\"struct_asym\"].rows<std::string>(\"id\"))\n\t{\n\t\tif (id == poly.asymID())\n\t\t\tcontinue;\n\t\tligandIDs.emplace_back(id);\n\t}\n\n\tfor (auto &asymID : ligandIDs)\n\t{\n\t\tstd::vector<CAtom> resAtoms;\n\n\t\t// auto &res = structure.getResidue(asymID);\n\n\t\t// for (auto &atom : res.atoms())\n\t\t// \tresAtoms.emplace_back(atom);\n\n\t\t// assert(not resAtoms.empty());\n\n\t\tfor (const auto &[type_symbol, x, y, z, charge, comp_id] :\n\t\t\tdb[\"atom_site\"].find<std::string,float,float,float,std::optional<int>,std::string>(\n\t\t\t\t\"label_asym_id\"_key == asymID,\n\t\t\t\t\"type_symbol\", \"Cartn_x\", \"Cartn_y\", \"Cartn_z\", \"pdbx_formal_charge\", \"label_comp_id\"))\n\t\t{\n\t\t\tmmcif::AtomTypeTraits att(type_symbol);\n\n\t\t\tint formal_charge = charge.value_or(0);\n\n\t\t\tif (not charge.has_value() and att.isMetal())\n\t\t\t{\n\t\t\t\tauto compound = mmcif::CompoundFactory::instance().create(comp_id);\n\t\t\t\tif (compound)\n\t\t\t\t\tformal_charge = compound->formalCharge();\n\t\t\t}\n\n\t\t\tresAtoms.emplace_back(att.type(), Point{ x, y, z }, formal_charge);\n\t\t}\n\n\t\tjson clash{\n\t\t\t{ \"asym_id\", asymID },\n\t\t\t{ \"clash\", CalculateClashScore(polyAtoms, resAtoms, maxDistance) }\n\t\t};\n\n\t\tstd::cout << clash << std::endl;\n\t}\n\n\treturn 0;\n}\n\n// --------------------------------------------------------------------\n\n// recursively print exception whats:\nvoid print_what(const std::exception &e)\n{\n\tstd::cerr << e.what() << std::endl;\n\ttry\n\t{\n\t\tstd::rethrow_if_nested(e);\n\t}\n\tcatch (const std::exception &nested)\n\t{\n\t\tstd::cerr << \" >> \";\n\t\tprint_what(nested);\n\t}\n}\n\n// --------------------------------------------------------------------\n\nint main(int argc, const char *argv[])\n{\n\tint result = 0;\n\n\ttry\n\t{\n#if defined(DATA_DIR)\n\t\tcif::addDataDirectory(DATA_DIR);\n#endif\n\t\tresult = a_main(argc, argv);\n\t}\n\tcatch (const std::exception &ex)\n\t{\n\t\tprint_what(ex);\n\t\texit(1);\n\t}\n\n\treturn result;\n}\n", "meta": {"hexsha": "c2fa884a3af7ee40f8817902f7361bf1c25e876c", "size": 8320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/clash-score.cpp", "max_stars_repo_name": "PDB-REDO/alphafill", "max_stars_repo_head_hexsha": "6c74e0939108af8769ac0013e7af7691591d5745", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2021-11-28T13:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T21:37:16.000Z", "max_issues_repo_path": "src/clash-score.cpp", "max_issues_repo_name": "PDB-REDO/alphafill", "max_issues_repo_head_hexsha": "6c74e0939108af8769ac0013e7af7691591d5745", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-19T18:22:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T07:54:11.000Z", "max_forks_repo_path": "src/clash-score.cpp", "max_forks_repo_name": "PDB-REDO/alphafill", "max_forks_repo_head_hexsha": "6c74e0939108af8769ac0013e7af7691591d5745", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-11-28T13:03:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T05:34:51.000Z", "avg_line_length": 25.9190031153, "max_line_length": 151, "alphanum_fraction": 0.6378605769, "num_tokens": 2166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.18879753763188145}}
{"text": "#include \"OwnedItems.hpp\"\n#include \"SerializeUtility.hpp\"\n#include <boost/test/auto_unit_test.hpp>\n#include <iostream>\n\n\n\n \nvoid OwnedItemsDataLibrary()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(DATA_LIBRARY);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 1 );\n  BOOST_CHECK ( oi.GetCostSum() == 15 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 10 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 10 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(DATA_LIBRARY);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(DATA_LIBRARY);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 2 );\n  BOOST_CHECK ( oi.GetCostSum() == 30 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 20 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 20 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(DATA_LIBRARY);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\n\nvoid OwnedItemsWarehouse()\n{\n  OwnedItems oi;\n  std::vector<ItemType> it;\n  FactoryType fac;\n\n  fac = oi.AddItem(WAREHOUSE);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 1 );\n  BOOST_CHECK ( oi.GetCostSum() == 25 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 3 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(WAREHOUSE);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(WAREHOUSE);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 2 );\n  BOOST_CHECK ( oi.GetCostSum() == 50 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 6 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(WAREHOUSE);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nvoid OwnedItemsHeavyEquipment()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(HEAVY_EQUIPMENT);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 1 );\n  BOOST_CHECK ( oi.GetCostSum() == 30 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 5 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 5 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 10 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == true );\n\n  it.push_back(HEAVY_EQUIPMENT);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(HEAVY_EQUIPMENT);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 2 );\n  BOOST_CHECK ( oi.GetCostSum() == 60 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 10 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 10 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 20 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == true );\n\n  it.push_back(HEAVY_EQUIPMENT);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nvoid OwnedItemsNodule()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(NODULE);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 2 );\n  BOOST_CHECK ( oi.GetCostSum() == 25 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 3 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(NODULE);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(NODULE);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 4 );\n  BOOST_CHECK ( oi.GetCostSum() == 50 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 6 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(NODULE);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nvoid OwnedItemsScientists()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(SCIENTISTS);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 2 );\n  BOOST_CHECK ( oi.GetCostSum() == 40 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 1 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(SCIENTISTS);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(SCIENTISTS);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 4 );\n  BOOST_CHECK ( oi.GetCostSum() == 80 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 2 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(SCIENTISTS);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nvoid OwnedItemsOrbitalLab()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(ORBITAL_LAB);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 3 );\n  BOOST_CHECK ( oi.GetCostSum() == 50 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 1 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(ORBITAL_LAB);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(ORBITAL_LAB);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 6 );\n  BOOST_CHECK ( oi.GetCostSum() == 100 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 2 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(ORBITAL_LAB);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nvoid OwnedItemsRobots()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(ROBOTS);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 3 );\n  BOOST_CHECK ( oi.GetCostSum() == 50 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == UNLIMITED_ROBOTS );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 1 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 1 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(ROBOTS);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(ROBOTS);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 6 );\n  BOOST_CHECK ( oi.GetCostSum() == 100 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == UNLIMITED_ROBOTS );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == UNLIMITED_ROBOTS );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 2 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(ROBOTS);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\n\nvoid OwnedItemsLaboratory()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(LABORATORY);\n  \n  BOOST_CHECK ( fac == RESEARCH_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 5 );\n  BOOST_CHECK ( oi.GetCostSum() == 100 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == true );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(LABORATORY);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(LABORATORY);\n  \n  BOOST_CHECK ( fac == RESEARCH_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 10 );\n  BOOST_CHECK ( oi.GetCostSum() == 200 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == true );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(LABORATORY);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nvoid OwnedItemsEcoplants()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(ECOPLANTS);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 5 );\n  BOOST_CHECK ( oi.GetCostSum() == 50 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 10 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 5 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(ECOPLANTS);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(ECOPLANTS);\n  \n  BOOST_CHECK ( fac == NO_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 10 );\n  BOOST_CHECK ( oi.GetCostSum() == 100 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 20 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 5 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(ECOPLANTS);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nvoid OwnedItemsOutpost()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(OUTPOST);\n  \n  BOOST_CHECK ( fac == TITANIUM_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 5 );\n  BOOST_CHECK ( oi.GetCostSum() == 100 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 3 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 5 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(OUTPOST);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(OUTPOST);\n  \n  BOOST_CHECK ( fac == TITANIUM_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 10 );\n  BOOST_CHECK ( oi.GetCostSum() == 200 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 6 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 10 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(OUTPOST);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nvoid OwnedItemsSpaceStation()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(SPACE_STATION);\n  \n  BOOST_CHECK ( fac == SPACE_STATION_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 0 );\n  BOOST_CHECK ( oi.GetCostSum() == 120 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(SPACE_STATION);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(SPACE_STATION);\n  \n  BOOST_CHECK ( fac == SPACE_STATION_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 0 );\n  BOOST_CHECK ( oi.GetCostSum() == 240 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(SPACE_STATION);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\n\nvoid OwnedItemsPlanetaryCruiser()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(PLANETARY_CRUISER);\n  \n  BOOST_CHECK ( fac == PLANETARY_CRUISER_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 0 );\n  BOOST_CHECK ( oi.GetCostSum() == 160 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(PLANETARY_CRUISER);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(PLANETARY_CRUISER);\n  \n  BOOST_CHECK ( fac == PLANETARY_CRUISER_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 0 );\n  BOOST_CHECK ( oi.GetCostSum() == 320 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(PLANETARY_CRUISER);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\n\nvoid OwnedItemsMoonBase()\n{\n  OwnedItems oi;\n  FactoryType fac;\n  std::vector<ItemType> it;\n\n  fac = oi.AddItem(MOON_BASE);\n  \n  BOOST_CHECK ( fac == MOON_BASE_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 0 );\n  BOOST_CHECK ( oi.GetCostSum() == 200 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(MOON_BASE);\n  BOOST_CHECK ( oi.GetItemList() == it);\n\n  fac = oi.AddItem(MOON_BASE);\n  \n  BOOST_CHECK ( fac == MOON_BASE_FACTORY );\n  BOOST_CHECK ( oi.GetItemVPs() == 0 );\n  BOOST_CHECK ( oi.GetCostSum() == 400 );\n\n  BOOST_CHECK ( oi.GetDiscount(DATA_LIBRARY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(WAREHOUSE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(HEAVY_EQUIPMENT) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(NODULE) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SCIENTISTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ORBITAL_LAB) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ROBOTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(LABORATORY) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(ECOPLANTS) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(OUTPOST) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(SPACE_STATION) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(PLANETARY_CRUISER) == 0 ); \n  BOOST_CHECK ( oi.GetDiscount(MOON_BASE) == 0 ); \n\n  BOOST_CHECK ( oi.GetHandIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleIncrease() == 0 );\n  BOOST_CHECK ( oi.GetPeopleCost() == 10 );\n  BOOST_CHECK ( oi.GetResearchProduction() == 0 );\n  BOOST_CHECK ( oi.GetMicrobioticProduction() == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( FIRST_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( SECOND_UNLIMITED ) == 0 );\n  BOOST_CHECK ( oi.GetNumRobotsPerPerson( ALWAYS_MULTIPLICATIVE ) == 0 );\n  BOOST_CHECK ( oi.CanBuildResearch() == false );\n  BOOST_CHECK ( oi.CanBuildTitanium() == false );\n\n  it.push_back(MOON_BASE);\n  BOOST_CHECK ( oi.GetItemList() == it);\n}\n\nBOOST_AUTO_TEST_CASE( OwnedItemsConstructor )\n{\n  OwnedItemsDataLibrary();\n  OwnedItemsWarehouse();\n  OwnedItemsHeavyEquipment();\n  OwnedItemsNodule();\n  OwnedItemsScientists();\n  OwnedItemsOrbitalLab();\n  OwnedItemsRobots();\n  OwnedItemsLaboratory();\n  OwnedItemsEcoplants();\n  OwnedItemsOutpost();\n  OwnedItemsSpaceStation();\n  OwnedItemsPlanetaryCruiser();\n  OwnedItemsMoonBase();\n\n  OwnedItems oi;\n  std::vector<ItemType> it;\n  oi.AddItem(LABORATORY);      it.push_back(LABORATORY);\n  oi.AddItem(HEAVY_EQUIPMENT); it.push_back(HEAVY_EQUIPMENT);\n  oi.AddItem(ROBOTS);          it.push_back(ROBOTS);\n  oi.AddItem(ROBOTS);          it.push_back(ROBOTS);\n\n  BOOST_CHECK( oi.GetItemList() == it);\n\n  OwnedItems noi;\n  SerialTransfer(oi,noi);\n\n  BOOST_CHECK( noi.GetItemList() == it);\n}\n", "meta": {"hexsha": "d6c7640db1515362e00578edfdd53d14ed78169d", "size": 40252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Outpost/tests/OwnedItemsTest.cpp", "max_stars_repo_name": "chiendarrendor/AlbertsGameMachine", "max_stars_repo_head_hexsha": "29855669056bf23666791960dc2e79eab47f6a0b", "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": "Outpost/tests/OwnedItemsTest.cpp", "max_issues_repo_name": "chiendarrendor/AlbertsGameMachine", "max_issues_repo_head_hexsha": "29855669056bf23666791960dc2e79eab47f6a0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Outpost/tests/OwnedItemsTest.cpp", "max_forks_repo_name": "chiendarrendor/AlbertsGameMachine", "max_forks_repo_head_hexsha": "29855669056bf23666791960dc2e79eab47f6a0b", "max_forks_repo_licenses": ["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.5402750491, "max_line_length": 83, "alphanum_fraction": 0.6805127696, "num_tokens": 12158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.18875759202740097}}
{"text": "#pragma once\n//===----------------------------------------------------------------------===//\n#include <dtl/bitmap/util/plain_bitmap.hpp>\n#include <dtl/bitmap/util/plain_bitmap_iter.hpp>\n#include <dtl/dtl.hpp>\n\n#include <boost/dynamic_bitset.hpp>\n\n#include <cstddef>\n#include <type_traits>\n#include <vector>\n//===----------------------------------------------------------------------===//\nnamespace dtl {\n//===----------------------------------------------------------------------===//\n/// Un-Aligned Hybrid: An RLE compressed representation of a bitmap of length N.\n/// Unlike WAH or BBC, the encoding is not word or byte aligned.\ntemplate<typename _word_type = u32>\nclass uah {\n\nprotected:\n  using word_type = typename std::remove_cv<_word_type>::type;\n  static_assert(std::is_integral<word_type>::value,\n      \"The word type must be an integral type.\");\n  static_assert(!std::is_same<word_type, bool>::value,\n      \"The word type must not be a boolean.\");\n  \n  static constexpr std::size_t word_bitlength = sizeof(word_type) * 8;\n  static constexpr std::size_t max_fill_length = (1ull << (word_bitlength - 2)) - 1;\n  /// The number of bits that can be stored in a literal word.\n  static constexpr std::size_t payload_bit_cnt = word_bitlength - 1;\n  static constexpr word_type all_ones = word_type(~word_type(0));\n\n  /// The encoded bitmap.\n  std::vector<word_type> data_;\n  /// The length of the encoded bitmap.\n  std::size_t encoded_bitmap_length_ = 0;\n\n  std::size_t remaining_bit_cnt_in_last_literal_word_ = 0;\n\n  /// Returns true if the given word is a literal word.\n  static inline constexpr u1\n  is_literal_word(const word_type w) noexcept {\n    return (w & word_type(1)) == 0;\n  }\n\n  /// Returns true if the given word is a fill word.\n  static inline constexpr u1\n  is_fill_word(const word_type w) noexcept {\n    return (w & word_type(1)) == 1;\n  }\n\n  /// Extract the fill value from a fill word.\n  static inline constexpr u1\n  extract_fill_value(const word_type w) noexcept {\n    assert(is_fill_word(w));\n    return (w & word_type(2)) != 0;\n  }\n\n  /// Extract the fill length from a fill word.\n  static inline constexpr std::size_t\n  extract_fill_length(const word_type w) noexcept {\n    assert(is_fill_word(w));\n    return w >> 2;\n  }\n\n  /// Creates a fill word.\n  static inline constexpr word_type\n  make_fill_word(u1 val, const std::size_t len) noexcept {\n    assert(len <= max_fill_length);\n    word_type w = val ? word_type(3) : word_type(1);\n    w |= len << 2;\n    return w;\n  }\n\n  /// Initialize the compressed bitmap with a 0- or 1-run of length 0.\n  inline void\n  init(u1 val) noexcept {\n    assert(data_.size() == 0);\n    data_.push_back(make_fill_word(val, 0));\n  }\n\n  /// Append a 0- or 1-run of the given length to the compressed bitmap.\n  inline void\n  append_run(u1 val, std::size_t len) {\n    assert(data_.size() > 0);\n    auto& w = data_.back();\n    if (is_fill_word(w)) {\n      const auto last_fill_len = extract_fill_length(w);\n      const auto last_fill_val = extract_fill_value(w);\n      if (last_fill_val == val) {\n        //===--------------------------------------------------------------===//\n        // The run that is to be appended is of a SAME KIND as the\n        // previous one.\n        //===--------------------------------------------------------------===//\n\n        // Extend the previous fill word.\n        auto extend_by = std::min(max_fill_length - last_fill_len, len);\n        w = make_fill_word(val, last_fill_len + extend_by);\n        encoded_bitmap_length_ += extend_by;\n        if (extend_by == len) {\n          return; // Done.\n        }\n        // The previous fill word exceeded its max length. Thus, we have to\n        // append a new fill word.\n        len -= extend_by;\n      }\n      else {\n        //===--------------------------------------------------------------===//\n        // The run that is to be appended is of a DIFFERENT KIND than the\n        // previous one.\n        //===--------------------------------------------------------------===//\n\n        // Try to save space by converting the last word into a literal word.\n        if (last_fill_len < payload_bit_cnt) {\n          // Convert the last word into a literal word.\n          auto literal_word = last_fill_val\n              ? (all_ones >> (word_bitlength - last_fill_len)) << 1\n              : word_type(0);\n          auto remaining_bits = payload_bit_cnt - last_fill_len;\n          // Append the current run value.\n          auto extend_by = std::min(remaining_bits, len);\n          auto bits_to_append = val\n              ? all_ones >> (word_bitlength - extend_by)\n              : word_type(0);\n          literal_word |=\n              bits_to_append << (1 + payload_bit_cnt - remaining_bits);\n          w = literal_word;\n          encoded_bitmap_length_ += extend_by;\n          remaining_bit_cnt_in_last_literal_word_ = remaining_bits - extend_by;\n          if (extend_by == len) {\n            return; // Done.\n          }\n          // The previous fill word exceeded its max length. Thus, we have to\n          // append a new fill word.\n          len -= extend_by;\n        }\n      }\n    }\n    else {\n      // Append to the last literal word.\n      if (remaining_bit_cnt_in_last_literal_word_ > 0) {\n        auto extend_by = std::min(remaining_bit_cnt_in_last_literal_word_, len);\n        if (val == true) {\n          auto bits_to_append = all_ones >> (word_bitlength - extend_by);\n          w |= bits_to_append\n              << (word_bitlength - remaining_bit_cnt_in_last_literal_word_);\n        }\n        remaining_bit_cnt_in_last_literal_word_ -= extend_by;\n        encoded_bitmap_length_ += extend_by;\n        if (extend_by == len) {\n          return; // Done.\n        }\n        len -= extend_by;\n        // Could not fit the entire run into the last literal word.\n      }\n    }\n\n    // Append remaining bits of the current run as a fill word.\n    while (len > 0) {\n      const auto fill_len = std::min(std::size_t(max_fill_length), len);\n      data_.emplace_back(make_fill_word(val, fill_len));\n      encoded_bitmap_length_ += fill_len;\n      len -= fill_len;\n    }\n    remaining_bit_cnt_in_last_literal_word_ = 0;\n  }\n\n  /// Append a 0-run of the given length to the compressed bitmap.\n  inline void\n  append_zero_run(std::size_t len) {\n    append_run(false, len);\n  }\n\n  /// Append a 1-run of the given length to the compressed bitmap.\n  inline void\n  append_one_run(const std::size_t len) {\n    append_run(true, len);\n  }\n\npublic:\n  uah() = default;\n\n  explicit uah(const boost::dynamic_bitset<$u32>& in) {\n    // Obtain a 1-run iterator for the input bitmap.\n    dtl::plain_bitmap_iter<boost::dynamic_bitset<$u32>> it(in);\n    // Append runs to the compressed bitmap.\n    std::size_t i = 0;\n    if (it.pos() > 0) {\n      // The bitmap starts with a 0-run.\n      init(false);\n      auto len = it.pos() - i;\n      append_zero_run(len);\n      i += len;\n    }\n    else {\n      // The bitmap starts with a 0-run.\n      init(true);\n    }\n    while (!it.end()) {\n      auto len = it.length();\n      append_one_run(len);\n      i += len;\n      it.next();\n      if (!it.end()) {\n        len = it.pos() - i;\n        append_zero_run(len);\n        i += len;\n      }\n    }\n    if (i < in.size()) {\n      append_zero_run(in.size() - i);\n    }\n    // Try to reduce the memory consumption.\n    shrink();\n  }\n\n  ~uah() = default;\n  uah(const uah& other) = default;\n  uah(uah&& other) noexcept = default;\n  uah& operator=(const uah& other) = default;\n  uah& operator=(uah&& other) noexcept = default;\n\n  /// Return the size in bytes.\n  std::size_t __forceinline__\n  size_in_bytes() const {\n    return data_.size() * sizeof(word_type) /* size of the compressed bitmap */\n        + sizeof(encoded_bitmap_length_); /* bit-length of the original bitmap */\n  }\n\n  /// Returns the size of the bitmap.\n  std::size_t __forceinline__\n  size() const {\n    return encoded_bitmap_length_;\n  }\n\n  /// Conversion to an plain bitmap. // TODO remove\n  dtl::plain_bitmap<$u64>\n  to_plain_bitmap() {\n    dtl::plain_bitmap<$u64> ret(encoded_bitmap_length_, false);\n    std::size_t i = 0;\n    for (std::size_t word_idx = 0; word_idx < data_.size(); ++word_idx) {\n      auto& w = data_[word_idx];\n      if (is_fill_word(w)) {\n        auto val = extract_fill_value(w);\n        auto len = extract_fill_length(w);\n        ret.set(i, i + len, val);\n        i += len;\n      }\n      else {\n        const std::size_t cnt = word_idx == data_.size() - 1\n            ? payload_bit_cnt - remaining_bit_cnt_in_last_literal_word_\n            : payload_bit_cnt;\n        for (std::size_t k = 0; k < cnt; ++k) {\n          ret.set(i + k, dtl::bits::bit_test(w, k + 1));\n        }\n        i += cnt;\n      }\n    }\n    if (i < encoded_bitmap_length_) {\n      ret.clear(i, encoded_bitmap_length_);\n    }\n    return std::move(ret);\n  }\n\n  static std::string\n  name() {\n    return \"uah\" + std::to_string(word_bitlength);\n  }\n\n  /// Returns the value of the bit at the position pos.\n  u1 __forceinline__\n  test(const std::size_t pos) const {\n    std::size_t i = 0;\n    std::size_t word_idx = 0;\n    // Find the corresponding word.\n    for (; word_idx < data_.size(); ++word_idx) {\n      auto& w = data_[word_idx];\n      if (is_literal_word(w)) {\n        if (pos >= i + payload_bit_cnt) {\n          i += payload_bit_cnt;\n          continue;\n        }\n        else {\n          return dtl::bits::bit_test(w, pos - i + 1); // TODO optimize\n        }\n      }\n      else {\n        auto fill_len = extract_fill_length(w);\n        if (pos >= i + fill_len) {\n          i += fill_len;\n          continue;\n        }\n        else {\n          return extract_fill_value(w);\n        }\n      }\n    }\n    return false;\n  }\n\n  /// Try to reduce the memory consumption. This function is supposed to be\n  /// called after the bitmap has been modified.\n  __forceinline__ void\n  shrink() {\n    data_.shrink_to_fit();\n  }\n\n  //===--------------------------------------------------------------------===//\n  /// 1-run iterator\n  class iter {\n    const uah& outer_;\n\n    std::size_t word_idx_;\n    std::size_t in_word_idx_;\n\n    //===------------------------------------------------------------------===//\n    // Iterator state\n    //===------------------------------------------------------------------===//\n    /// Points to the beginning of a 1-run.\n    $u64 pos_;\n    /// The length of the current 1-run.\n    $u64 length_;\n    //===------------------------------------------------------------------===//\n\n  public:\n    explicit __forceinline__\n    iter(const uah& outer)\n        : outer_(outer),\n          word_idx_(0),\n          in_word_idx_(0),\n          pos_(0), length_(0) {\n      const auto word_cnt = outer_.data_.size();\n      word_type w;\n      while (word_idx_ < word_cnt) {\n        w = outer_.data_[word_idx_];\n        if (is_fill_word(w)) {\n          if (extract_fill_value(w) == false) {\n            pos_ += extract_fill_length(w);\n          }\n          else {\n            length_ = extract_fill_length(w);\n            in_word_idx_ = 0;\n            break;\n          }\n        }\n        else {\n          const word_type payload = w >> 1;\n          if (payload == 0) {\n            pos_ += payload_bit_cnt;\n          }\n          else {\n            const std::size_t b = dtl::bits::tz_count(payload);\n            std::size_t e = b + 1;\n            for (; e < payload_bit_cnt; ++e) {\n              u1 is_set = dtl::bits::bit_test(payload, e);\n              if (!is_set) break;\n            }\n            pos_ += b;\n            length_ = e - b;\n            in_word_idx_ = e;\n            break;\n          }\n        }\n        ++word_idx_;\n      }\n      if (word_idx_ == word_cnt) {\n        pos_ = outer_.encoded_bitmap_length_;\n        length_ = 0;\n      }\n      else {\n        if (is_fill_word(w)) {\n          ++word_idx_;\n          in_word_idx_ = 0;\n        }\n      }\n    }\n\n    /// Forward the iterator to the next 1-run.\n    void __forceinline__\n    next() {\n      pos_ += length_;\n      length_ = 0;\n      const auto word_cnt = outer_.data_.size();\n      word_type w;\n      while (word_idx_ < word_cnt) {\n        w = outer_.data_[word_idx_];\n        if (is_fill_word(w)) {\n          if (extract_fill_value(w) == false) {\n            pos_ += extract_fill_length(w);\n          }\n          else {\n            length_ = extract_fill_length(w);\n            break;\n          }\n        }\n        else {\n          if (in_word_idx_ < payload_bit_cnt) { // TODO decode the entire literal word at once.\n            const word_type payload = w >> (1 + in_word_idx_);\n            if (payload == 0) {\n              pos_ += payload_bit_cnt - in_word_idx_;\n            }\n            else {\n              const std::size_t b = dtl::bits::tz_count(payload);\n              std::size_t e = b + 1;\n              for (; e < (payload_bit_cnt - in_word_idx_); ++e) {\n                u1 is_set = dtl::bits::bit_test(payload, e);\n                if (!is_set) break;\n              }\n              pos_ += b;\n              length_ = e - b;\n              in_word_idx_ += e;\n              break;\n            }\n          }\n        }\n        ++word_idx_;\n        in_word_idx_ = 0;\n      }\n      if (word_idx_ == word_cnt) {\n        pos_ = outer_.encoded_bitmap_length_;\n        length_ = 0;\n      }\n      else {\n        if (is_fill_word(w)) {\n          ++word_idx_;\n          in_word_idx_ = 0;\n        }\n      }\n    }\n\n    /// Forward the iterator to the desired position.\n    void __forceinline__\n    skip_to(const std::size_t to_pos) {\n      assert(pos_ <= to_pos);\n      if (to_pos >= outer_.encoded_bitmap_length_) {\n        pos_ = outer_.encoded_bitmap_length_;\n        length_ = 0;\n        return;\n      }\n      // Call next until the desired position has been reached.\n      while (!end() && pos() + length() <= to_pos) {\n        next();\n      }\n      // Adjust the current position and run length.\n      if (!end() && pos() < to_pos) {\n        length_ -= to_pos - pos_;\n        pos_ = to_pos;\n      }\n    }\n\n    u1 __forceinline__\n    end() const noexcept {\n      return length_ == 0;\n    }\n\n    u64 __forceinline__\n    pos() const noexcept {\n      return pos_;\n    }\n\n    u64 __forceinline__\n    length() const noexcept {\n      return length_;\n    }\n  };\n  //===--------------------------------------------------------------------===//\n\n  using skip_iter_type = iter;\n  using scan_iter_type = iter;\n\n  /// Returns a 1-run iterator.\n  skip_iter_type __forceinline__\n  it() const {\n    return skip_iter_type(*this);\n  }\n\n  /// Returns a 1-run iterator.\n  scan_iter_type __forceinline__\n  scan_it() const {\n    return scan_iter_type(*this);\n  }\n\n  /// Returns the name of the instance including the most important parameters\n  /// in JSON.\n  std::string\n  info() const {\n    return \"{\\\"name\\\":\\\"\" + name() + \"\\\"\"\n        + \",\\\"n\\\":\" + std::to_string(encoded_bitmap_length_)\n        + \",\\\"size\\\":\" + std::to_string(size_in_bytes())\n        + \",\\\"word_size\\\":\" + std::to_string(sizeof(word_type))\n        + \"}\";\n  }\n\n  // For debugging purposes.\n  void\n  print(std::ostream& os) const {\n    os << \"word idx | word type | content\" << std::endl;\n    for (std::size_t i = 0; i < data_.size(); ++i) {\n      os << std::setw(8) << i << \" | \";\n      auto& w = data_[i];\n      if (is_fill_word(w)) {\n        os << \"fill      | \";\n        os << extract_fill_length(w) << \" x \";\n        os << (extract_fill_value(w) ? \"'1'\" : \"'0'\");\n        os << std::endl;\n      }\n      else {\n        os << \"literal   | '\";\n        for (std::size_t k = 1; k < word_bitlength; ++k) {\n          os << (dtl::bits::bit_test(w, k) ? \"1\" : \"0\");\n        }\n        os << \"'\";\n        os << std::endl;\n      }\n    }\n  }\n};\n//===----------------------------------------------------------------------===//\n/// UAH compressed representation of a bitmap of length N using 8-bit words.\nusing uah8 = uah<u8>;\n/// UAH compressed representation of a bitmap of length N using 16-bit words.\nusing uah16 = uah<u16>;\n/// UAH compressed representation of a bitmap of length N using 32-bit words.\nusing uah32 = uah<u32>;\n/// UAH compressed representation of a bitmap of length N using 64-bit words.\nusing uah64 = uah<u64>;\n//===----------------------------------------------------------------------===//\n} // namespace dtl\n", "meta": {"hexsha": "0fac81314fe2a84adc0062355c1540e055b4b4a7", "size": 16210, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dtl/bitmap/uah.hpp", "max_stars_repo_name": "harald-lang/tree-encoded-bitmaps", "max_stars_repo_head_hexsha": "a4ab056f2cefa7843b27c736833b08977b56649c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T12:51:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T07:38:24.000Z", "max_issues_repo_path": "src/dtl/bitmap/uah.hpp", "max_issues_repo_name": "marcellus-saputra/Thuja", "max_issues_repo_head_hexsha": "8443320a6d0e9a20bb6b665f0befc6988978cafd", "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/dtl/bitmap/uah.hpp", "max_forks_repo_name": "marcellus-saputra/Thuja", "max_forks_repo_head_hexsha": "8443320a6d0e9a20bb6b665f0befc6988978cafd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-07T13:43:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T04:49:39.000Z", "avg_line_length": 30.6427221172, "max_line_length": 95, "alphanum_fraction": 0.5333127699, "num_tokens": 3997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.18875757961103262}}
{"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\n#include <boost/lexical_cast.hpp>\n#include <boost/timer.hpp>\n#include <orea/cube/inmemorycube.hpp>\n#include <orea/engine/stresstest.hpp>\n#include <orea/engine/valuationengine.hpp>\n#include <orea/scenario/clonescenariofactory.hpp>\n#include <ored/utilities/log.hpp>\n#include <ql/errors.hpp>\n#include <ql/instruments/forwardrateagreement.hpp>\n#include <ql/instruments/makeois.hpp>\n#include <ql/instruments/makevanillaswap.hpp>\n#include <ql/math/solvers1d/newtonsafe.hpp>\n#include <ql/pricingengines/capfloor/bacheliercapfloorengine.hpp>\n#include <ql/pricingengines/capfloor/blackcapfloorengine.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <ql/termstructures/yield/oisratehelper.hpp>\n#include <qle/instruments/crossccybasisswap.hpp>\n#include <qle/instruments/deposit.hpp>\n#include <qle/instruments/fxforward.hpp>\n#include <qle/pricingengines/crossccyswapengine.hpp>\n#include <qle/pricingengines/depositengine.hpp>\n#include <qle/pricingengines/discountingfxforwardengine.hpp>\n\n#include <iomanip>\n#include <iostream>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace std;\nusing namespace ore::data;\n\nnamespace ore {\nnamespace analytics {\n\nStressTest::StressTest(const boost::shared_ptr<ore::data::Portfolio>& portfolio,\n                       boost::shared_ptr<ore::data::Market>& market, const string& marketConfiguration,\n                       const boost::shared_ptr<ore::data::EngineData>& engineData,\n                       boost::shared_ptr<ScenarioSimMarketParameters>& simMarketData,\n                       const boost::shared_ptr<StressTestScenarioData>& stressData, const Conventions& conventions,\n                       boost::shared_ptr<ScenarioFactory> scenarioFactory, bool continueOnError) {\n\n    LOG(\"Build Simulation Market\");\n    boost::shared_ptr<ScenarioSimMarket> simMarket =\n        boost::make_shared<ScenarioSimMarket>(market, simMarketData, conventions, marketConfiguration, continueOnError);\n\n    LOG(\"Build Stress Scenario Generator\");\n    Date asof = market->asofDate();\n    boost::shared_ptr<Scenario> baseScenario = simMarket->baseScenario();\n    scenarioFactory = scenarioFactory ? scenarioFactory : boost::make_shared<CloneScenarioFactory>(baseScenario);\n    boost::shared_ptr<StressScenarioGenerator> scenarioGenerator =\n        boost::make_shared<StressScenarioGenerator>(stressData, baseScenario, simMarketData, scenarioFactory);\n    simMarket->scenarioGenerator() = scenarioGenerator;\n\n    LOG(\"Build Engine Factory\");\n    map<MarketContext, string> configurations;\n    configurations[MarketContext::pricing] = marketConfiguration;\n    boost::shared_ptr<EngineFactory> factory = boost::make_shared<EngineFactory>(engineData, simMarket, configurations);\n\n    LOG(\"Reset and Build Portfolio\");\n    portfolio->reset();\n    portfolio->build(factory);\n\n    LOG(\"Build the cube object to store sensitivities\");\n    boost::shared_ptr<NPVCube> cube = boost::make_shared<DoublePrecisionInMemoryCube>(\n        asof, portfolio->ids(), vector<Date>(1, asof), scenarioGenerator->samples());\n\n    boost::shared_ptr<DateGrid> dg = boost::make_shared<DateGrid>(\n        \"1,0W\"); // TODO - extend the DateGrid interface so that it can actually take a vector of dates as input\n    vector<boost::shared_ptr<ValuationCalculator>> calculators;\n    calculators.push_back(boost::make_shared<NPVCalculator>(simMarketData->baseCcy()));\n    ValuationEngine engine(asof, dg, simMarket);\n    LOG(\"Run Stress Scenarios\");\n    /*ostringstream o;\n    o.str(\"\");\n    o << \"Stress scenarios \" << portfolio->size() << \" x \" << dg->size() << \" x \" << scenarioGenerator->samples() <<\n    \"... \";\n    auto progressBar = boost::make_shared<SimpleProgressBar>(o.str());\n    auto progressLog = boost::make_shared<ProgressLog>(\"Building scenarios...\");\n    engine.registerProgressIndicator(progressBar);\n    engine.registerProgressIndicator(progressLog);*/\n    engine.buildCube(portfolio, cube, calculators);\n\n    /*****************\n     * Collect results\n     */\n    baseNPV_.clear();\n    shiftedNPV_.clear();\n    delta_.clear();\n    labels_.clear();\n    for (Size i = 0; i < portfolio->size(); ++i) {\n        Real npv0 = cube->getT0(i, 0);\n        string id = portfolio->trades()[i]->id();\n        trades_.insert(id);\n        baseNPV_[id] = npv0;\n        for (Size j = 0; j < scenarioGenerator->samples(); ++j) {\n            string label = scenarioGenerator->scenarios()[j]->label();\n            Real npv = cube->get(i, 0, j, 0);\n            pair<string, string> p(id, label);\n            shiftedNPV_[p] = npv;\n            delta_[p] = npv - npv0;\n            labels_.insert(label);\n        }\n    }\n    LOG(\"Stress testing done\");\n}\n\nvoid StressTest::writeReport(const boost::shared_ptr<ore::data::Report>& report, Real outputThreshold) {\n\n    report->addColumn(\"TradeId\", string());\n    report->addColumn(\"ScenarioLabel\", string());\n    report->addColumn(\"Base NPV\", double(), 2);\n    report->addColumn(\"Scenario NPV\", double(), 2);\n    report->addColumn(\"Sensitivity\", double(), 2);\n\n    for (auto data : shiftedNPV_) {\n        string id = data.first.first;\n        string factor = data.first.second;\n        Real npv = data.second;\n        Real base = baseNPV_[id];\n        Real sensi = npv - base;\n        if (fabs(sensi) > outputThreshold) {\n            report->next();\n            report->add(id);\n            report->add(factor);\n            report->add(base);\n            report->add(npv);\n            report->add(sensi);\n        }\n    }\n\n    report->end();\n}\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "a1c6f63cc5db73904e628b9404695f3c3aeb9a2a", "size": 6301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/engine/stresstest.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": "OREAnalytics/orea/engine/stresstest.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": "OREAnalytics/orea/engine/stresstest.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": 41.1830065359, "max_line_length": 120, "alphanum_fraction": 0.6951277575, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.18868946156314614}}
{"text": "#ifndef MESH_H\n#define MESH_H\n\n#include \"array\"\n#include \"vector\"\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#pragma clang diagnostic ignored \"-Wunused-parameter\"\n#pragma clang diagnostic ignored \"-Wmissing-braces\"\n#include \"dccrg.hpp\"\n#include \"dccrg_cartesian_geometry.hpp\"\n#pragma clang diagnostic pop\n\n#include \"cell.hpp\"\n#include \"parameters.hpp\"\n#include \"common.h\"\n\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace dccrg;\nusing namespace Eigen;\n\ntypedef Array<double, 4, 1> vec4;\n\n\n// class to handle neighborhood cells\nclass Neighborhood_Cube\n{\npublic:\n\n    std::array<vec4, 27> fields;\n\n    vec4& operator [](const std::size_t i){return this->fields[i];}\n    const vec4& operator [](const std::size_t i) const {return this->fields[i];}\n\n    void init_currents() \n    {\n        for(int ijk=0; ijk<27; ijk++) {\n            fields[ijk] = vec4::Zero();\n        }\n        return;\n    };\n\n\n    int index(int i, int j, int k) {\n        return (i+1) + (j+1)*3 + (k+1)*3*3;\n    };\n\n    void add_J(int i, int j, int k, vec4 dJ)\n    {\n        int ijk = this->index(i,j,k);\n\n        #ifdef DEBUG\n        cout << \"  addJ: \" << i << j << k << \" -> \" << ijk \n        << \" A\" << dJ << \" B \" << fields[ijk] << endl;\n        #endif\n\n        fields[ijk] += dJ;\n    };\n\n    vec4 J(int i, int j, int k) {\n        return this->fields[index(i,j,k)];\n    };\n\n\n\tvoid distribute(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid, uint64_t cell);\n};\n\n\n\nclass Mesh\n{\npublic:\n\n    // MPI parameters\n    int \n        rank = 0;\n\n    // Deposit currents into the mesh\n\tvoid sort_particles_into_cells(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid);\n\n    // Deposit currents into the mesh\n\tvoid deposit_currents(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid);\n\n    // Collect and compute staggered Yee currents\n\tvoid yee_currents(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid);\n\n    /* Shift fields from staggered Yee to nodal lattice\n       in practice we interpolate linearly between neighboring Yee values\n       TODO FIXME\n    */\n\tvoid nodal_fields(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid);\n\n};\n\n\n\n#endif\n", "meta": {"hexsha": "e5019a13f41715d8132f35433240e6240a72a5de", "size": 2169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "prototypes/cpp-pic/mesh.hpp", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-10-26T07:08:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T06:47:37.000Z", "max_issues_repo_path": "prototypes/cpp-pic/mesh.hpp", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T08:50:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T20:11:12.000Z", "max_forks_repo_path": "prototypes/cpp-pic/mesh.hpp", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["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.4752475248, "max_line_length": 85, "alphanum_fraction": 0.6371599816, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.18868945780177546}}
{"text": "/********************************************************\n  Stanford Driving Software\n  Copyright (c) 2011 Stanford University\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with \n  or without modification, are permitted provided that the \n  following conditions are met:\n\n* Redistributions of source code must retain the above \n  copyright notice, this list of conditions and the \n  following disclaimer.\n* Redistributions in binary form must reproduce the above\n  copyright notice, this list of conditions and the \n  following disclaimer in the documentation and/or other\n  materials provided with the distribution.\n* The names of the contributors may not be used to endorse\n  or promote products derived from this software\n  without specific prior written permission.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n  CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \n  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \n  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n  DAMAGE.\n ********************************************************/\n\n\n#include <pluginlib/class_list_macros.h>\n#include <Project3D.h>\n#include <velodyne/Packet.h>\n#include <velodyne/Projected.h>\n#include <boost/thread.hpp>\n#include <velodyne.h>\n#include <global.h>\n#include <pcl/point_types.h>\n#include <pcl_ros/point_cloud.h>\n\nusing namespace std;\n\nnamespace velodyne\n{\n\n  PLUGINLIB_DECLARE_CLASS(velodyne, Project3D, velodyne::Project3D, nodelet::Nodelet);\n\n  Project3D::Project3D()\n  {\n\n  }\n\n  Project3D::~Project3D()\n  {\n  }\n\n  void Project3D::onInit()\n  {\n    string cal_file, int_file;\n    ros::NodeHandle& private_nh = getPrivateNodeHandle();\n    private_nh.getParam(\"/driving/velodyne/cal_file\", cal_file);\n    private_nh.getParam(\"/driving/velodyne/int_file\", int_file);\n    readCalibration(cal_file, int_file);\n    projected_pub_ = private_nh.advertise<velodyne::Projected>\n        (\"/driving/velodyne/projected\", 4096);\n    points_pub_ = private_nh.advertise<pcl::PointCloud<pcl::PointXYZI> >\n        (\"/driving/velodyne/rawpoints\", 4096);\n    packet_sub_ = private_nh.subscribe(\"/driving/velodyne/packet\", 4096, \n        &Project3D::projectPacket, this);\n    NODELET_INFO(\"Ready to project points\");\n  }\n\n  void Project3D::readCalibration(string cal_file, string int_file)\n  {\n    if(!config_.readCalibration(cal_file))\n    {\n      NODELET_ERROR_STREAM(\"Could not open calibration file \" << \n          cal_file << string(\".\"));\n      throw VLRException(\"Could not open calibration file \" +\n          cal_file + string(\".\"));\n    }\n\n    if(!config_.readIntensity(int_file))\n    {\n      NODELET_ERROR_STREAM(\"Could not open intensity file \" << \n          int_file << string(\".\"));\n      throw VLRException(\"Could not open intensity file \" +\n          int_file + string(\".\"));\n    }\n  }\n\n  void Project3D::projectPacket(const velodyne::PacketPtr& packet)\n  {\n    double x, y, z;\n    double distance, distance1, cosVertAngle, sinVertAngle, cosRotAngle, sinRotAngle, hOffsetCorr, vOffsetCorr;\n    double xyDistance; //, distanceCorr, shortOffset, longOffset;\n\n    velodyne::Projected projected;\n    pcl::PointCloud<pcl::PointXYZI> cloud;\n    for (int b = 0; b < velodyne::Packet::NUM_BLOCKS; b++)\n    {\n      for (int l = 0; l < velodyne::Block::NUM_BEAMS; l++)\n      {\n        // laser is global laser id, 0-64\n        // l is block laser id, 0-32\n        int laser = l + velodyne::Block::NUM_BEAMS * packet->block[b].block;\n        if ((packet->block[b].laser[l].distance == 0 || \n              packet->block[b].laser[l].distance * VELODYNE_TICKS_TO_METER > 110 || \n              isnan(config_.sin_rot_angle[packet->block[b].encoder][laser]))) \n        {\n          projected.block[b].point[l].x = 0;\n          projected.block[b].point[l].y = 0;\n          projected.block[b].point[l].z = 0;\n          projected.block[b].laser[l].distance = 0;\n        }\n        else \n        {\n          distance1 = packet->block[b].laser[l].distance * VELODYNE_TICKS_TO_METER;\n          distance = config_.range_offsetX[laser] * distance1 + config_.range_offset[laser];\n\n          cosVertAngle = config_.cos_vert_angle[laser];\n          sinVertAngle = config_.sin_vert_angle[laser];\n          cosRotAngle = config_.cos_rot_angle[packet->block[b].encoder][laser];\n          sinRotAngle = config_.sin_rot_angle[packet->block[b].encoder][laser];\n          hOffsetCorr = config_.h_offset[laser];\n          vOffsetCorr = config_.v_offset[laser];\n\n          xyDistance = distance * cosVertAngle;\n\n          x = xyDistance * cosRotAngle - hOffsetCorr * sinRotAngle;\n          y = xyDistance * sinRotAngle + hOffsetCorr * cosRotAngle;\n          z = (xyDistance / cosVertAngle) * sinVertAngle + vOffsetCorr;\n\n          projected.block[b].point[l].x = x;\n          projected.block[b].point[l].y = y;\n          projected.block[b].point[l].z = z;\n          projected.block[b].laser[l].distance = (uint16_t) (xyDistance * 100);\n          projected.block[b].laser[l].intensity = config_.intensity_map[config_.inv_beam_order[laser]][packet->block[b].laser[l].intensity];\n          pcl::PointXYZI point;\n          point.x = x;\n          point.y = y;\n          point.z = z;\n          point.intensity = projected.block[b].laser[l].intensity;\n          cloud.push_back(point);\n        }\n      }\n      projected.block[b].block = packet->block[b].block;\n      projected.block[b].encoder = packet->block[b].encoder;\n    }\n    projected.spin_count = packet->spin_count;\n    projected.header.stamp = packet->header.stamp;\n    projected.header.frame_id = \"Velodyne\";\n    cloud.header.frame_id = \"Velodyne\";\n    cloud.header.stamp = ros::Time::now();\n    points_pub_.publish(cloud); \n    projected_pub_.publish(projected);\n  }\n} // namespace velodyne\n\n\n", "meta": {"hexsha": "fcb9e85569e2fad21cb056815a44a9eff405c25f", "size": 6302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "11_learning_materials/stanford_self_driving_car/perception/velodyne/src/Project3D.cpp", "max_stars_repo_name": "EatAllBugs/autonomous_learning", "max_stars_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T08:49:57.000Z", "max_issues_repo_path": "11_learning_materials/stanford_self_driving_car/perception/velodyne/src/Project3D.cpp", "max_issues_repo_name": "yinflight/autonomous_learning", "max_issues_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11_learning_materials/stanford_self_driving_car/perception/velodyne/src/Project3D.cpp", "max_forks_repo_name": "yinflight/autonomous_learning", "max_forks_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T00:58:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T13:16:09.000Z", "avg_line_length": 37.2899408284, "max_line_length": 140, "alphanum_fraction": 0.6650269756, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.1886894492026375}}
{"text": "//#include <ndt_registration/ndt_matcher_p2d.h>\n//#include <ndt_registration/ndt_matcher_d2d_2d.h>\n#include <ndt_registration/ndt_matcher_d2d.h>\n#include <ndt_map/ndt_map.h>\n#include <ndt_map/pointcloud_utils.h>\n\n#include \"pcl/point_cloud.h\"\n#include \"pcl/io/pcd_io.h\"\n#include <cstdio>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nint\nmain (int argc, char** argv)\n{\n    if(argc!=9) {\n\tstd::cout<<\"usage \"<<argv[0]<<\" x y z r p t cloud1.wrl cloud2.wrl\\n\";\n\treturn -1;\n    }\n\n    istringstream roll_c(argv[4]),pitch_c(argv[5]),yaw_c(argv[6]),xoffset_c(argv[1]),yoffset_c(argv[2]),zoffset_c(argv[3]);\n    double roll,pitch,yaw,xoffset,yoffset,zoffset;\n    roll_c >> roll;\n    pitch_c >> pitch;\n    yaw_c >> yaw;\n    xoffset_c >> xoffset;\n    yoffset_c >> yoffset;\n    zoffset_c >> zoffset;\n\n    printf(\"X %f Y %f Z %f Roll %f Pitch %f Yaw %f \\n\",xoffset,yoffset,zoffset,roll,pitch,yaw);\t\n    pcl::PointCloud<pcl::PointXYZ> cloud, cloud_offset, cloud_trans;\n    char fname[50];\n    FILE *fout;\n    double __res[] = {0.5, 1, 2, 4};\n    std::vector<double> resolutions (__res, __res+sizeof(__res)/sizeof(double));\n\n    struct timeval tv_start,tv_end,tv_reg_start,tv_reg_end;\n\n    Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> Tout;\n    Tout.setIdentity();\n    //printf(\"Working\");\t\n    if(argc == 9)\n    {\n\n        gettimeofday(&tv_start,NULL);\n        //we do a single scan to scan registration\n        //TODO fix these to load pcd files\n\tif (pcl::io::loadPCDFile<pcl::PointXYZ> (argv[7], cloud) == -1) //* load the file\n\t{\n\t    std::cerr<<\"Couldn't read file\\n\";\n\t    return (-1);\n\t}\n\tif (pcl::io::loadPCDFile<pcl::PointXYZ> (argv[8], cloud_offset) == -1) //* load the file\n\t{\n\t    std::cerr<<\"Couldn't read file\\n\";\n\t    return (-1);\n\t}\n        \n        Tout =  Eigen::Translation<double,3>(xoffset,yoffset,zoffset)*\n            Eigen::AngleAxis<double>(roll,Eigen::Vector3d::UnitX()) *\n            Eigen::AngleAxis<double>(pitch,Eigen::Vector3d::UnitY()) *\n            Eigen::AngleAxis<double>(yaw,Eigen::Vector3d::UnitZ()) ;\n        \n\t//lslgeneric::NDTMatcherD2D_2D<pcl::PointXYZ,pcl::PointXYZ> matcherD2D(false, false, resolutions);\n\tperception_oru::NDTMatcherD2D matcherD2D(false, false, resolutions);\n\tcloud_trans = cloud_offset;\n        bool ret = matcherD2D.match(cloud,cloud_offset,Tout,true);\n\n\tstd::cout<<\"Transform: \\n\"<<Tout.matrix()<<std::endl;\n\n\tperception_oru::transformPointCloudInPlace(Tout,cloud_trans);\n\tpcl::PointCloud<pcl::PointXYZRGB> cloud_comb;\n\tpcl::PointXYZRGB red(255,0,0);\n\tfor(int i=0; i<cloud.points.size(); ++i ) {\n\t    red.x = cloud.points[i].x;\n\t    red.y = cloud.points[i].y;\n\t    red.z = cloud.points[i].z;\n\t    cloud_comb.points.push_back(red);\n\t}\n\tpcl::PointXYZRGB green(0,200,0);\n\tfor(int i=0; i<cloud_offset.points.size(); ++i ) {\n\t    green.x = cloud_offset.points[i].x;\n\t    green.y = cloud_offset.points[i].y;\n\t    green.z = cloud_offset.points[i].z;\n\t    cloud_comb.points.push_back(green);\n\t}\n\tpcl::PointXYZRGB blue(10,20,200);\n\tfor(int i=0; i<cloud_trans.points.size(); ++i ) {\n\t    blue.x = cloud_trans.points[i].x;\n\t    blue.y = cloud_trans.points[i].y;\n\t    blue.z = cloud_trans.points[i].z;\n\t    cloud_comb.points.push_back(blue);\n\t}\n\tcloud_comb.width=1;\n\tcloud_comb.height=cloud_comb.points.size();\n\tcloud_comb.is_dense = false;\n\tpcl::io::savePCDFileBinary (\"test_pcd.pcd\", cloud_comb);\n\n    }\n}\n", "meta": {"hexsha": "6e4e0195e856fc89701deb368f2b1f850d30a1ca", "size": 3422, "ext": "cc", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_registration/test/simple.cc", "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_registration/test/simple.cc", "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_registration/test/simple.cc", "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": 32.2830188679, "max_line_length": 123, "alphanum_fraction": 0.6595558153, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.18868222176623992}}
{"text": "//\n//  astar.hpp\n//  indigo-bondorder\n//\n//  Created by Welsh, Ivan on 30/10/17.\n//  Copyright \u00a9 2017 Allison Group. All rights reserved.\n//\n\n#ifndef ASTAR_HPP\n#define ASTAR_HPP\n\n#include <map>\n#include <queue>\n#include <deque>\n#include <vector>\n\n#include <boost/dynamic_bitset.hpp>\n\n\n#include \"electron_optimisation_algorithm.hpp\"\n\nnamespace indigo_bondorder {\n  namespace algorithm {\n    \n    typedef boost::dynamic_bitset<> VertMask;\n    \n    struct AStarQueueItem {\n      ElnDist distribution;\n      VertMask unchangeable, calculable, new_calculable;\n      Score path_cost, heuristic_cost, parent_path_cost;\n      uint16_t nbr_start_idx;\n      uint8_t nbr_count;\n    };\n    \n    typedef std::shared_ptr<AStarQueueItem> p_AStarQueueItem;\n    \n    class ItemCompare {\n    public:\n      bool operator()(const p_AStarQueueItem a, const p_AStarQueueItem b);\n    };\n    \n    \n    class PriorityQueue :\n    public std::priority_queue<p_AStarQueueItem, std::vector<p_AStarQueueItem>,\n    ItemCompare > {\n    public:\n      void reserve(size_t sz) { this->c.reserve(sz); }\n      size_t max_size() const { return this->c.max_size(); }\n      void clear() { this->c.clear(); }\n    };\n    \n    class AStarOptimisation : public ElectronOptimisationAlgorithm {\n    private:\n      PriorityQueue queue_;\n      \n      std::vector<ElnVertex> pos2vert_;\n      std::map<ElnVertex, size_t>  vert2pos_;\n      \n      std::vector<uint8_t> uniqueIDs_;\n      std::vector<VertMask> requiredUnchangeables_;\n      std::map<MolVertPair, ElnVertex> idsToVertex_;\n      std::map<ElnVertex, ElnVertProp*> vertexProperties_;\n      size_t vertMaskSize_;\n      size_t maximumQueueSize_ = 0;\n      size_t sizePerItem_;\n      \n    private:\n      AStarOptimisation() = default;\n      \n    public:\n      AStarOptimisation(ElectronOpt* parent);\n      \n    public:\n      void Run() override;\n      size_t GetMaximumQueueSize() { return maximumQueueSize_; }\n      size_t GetSizePerQueueItem() { return sizePerItem_; }\n      \n    private:\n      void PopulateUniqueIDs();\n      void PopulateUnchangeables();\n      void PopulateInitialDistribution(p_AStarQueueItem d);\n      void PopulateNeighbourDistribution(p_AStarQueueItem parent, p_AStarQueueItem child);\n      void Initalise();\n      void DetermineCalculable(p_AStarQueueItem d);\n      void CalculatePathEnergy(p_AStarQueueItem d);\n      void CalculateHeuristicEnergy(p_AStarQueueItem d);\n      void PromiscuousHeuristic(p_AStarQueueItem d);\n      void AbstemiousHeuristic(p_AStarQueueItem d);\n      void GenerateNeighbourDistributions(p_AStarQueueItem d, std::vector<ElnDist>* out_nbrs);\n      \n    };\n  }\n}\n\n#endif /* ASTAR_HPP */\n", "meta": {"hexsha": "171fb85f8ac6b2a360bfbf3dbc4de497c5d4a36d", "size": 2645, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/indigo-bondorder/algorithm/formalbonds/astar.hpp", "max_stars_repo_name": "Cuboxylate/indigo-bondorder", "max_stars_repo_head_hexsha": "a7d4543b4245c5b987c45c1440cc5764f862fce5", "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/indigo-bondorder/algorithm/formalbonds/astar.hpp", "max_issues_repo_name": "Cuboxylate/indigo-bondorder", "max_issues_repo_head_hexsha": "a7d4543b4245c5b987c45c1440cc5764f862fce5", "max_issues_repo_licenses": ["MIT"], "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/indigo-bondorder/algorithm/formalbonds/astar.hpp", "max_forks_repo_name": "Cuboxylate/indigo-bondorder", "max_forks_repo_head_hexsha": "a7d4543b4245c5b987c45c1440cc5764f862fce5", "max_forks_repo_licenses": ["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.5520833333, "max_line_length": 94, "alphanum_fraction": 0.6846880907, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.1886822203512877}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <stdexcept>\n#include <functional>\n#include <random>\n#include <Eigen/Geometry>\n#include <visualization_msgs/Marker.h>\n#include \"arc_utilities/eigen_helpers.hpp\"\n#include \"arc_utilities/eigen_helpers_conversions.hpp\"\n#include \"arc_utilities/pretty_print.hpp\"\n#include \"arc_utilities/voxel_grid.hpp\"\n#include \"arc_utilities/simple_rrt_planner.hpp\"\n#include \"uncertainty_planning_core/simple_pid_controller.hpp\"\n#include \"uncertainty_planning_core/simple_uncertainty_models.hpp\"\n#include \"uncertainty_planning_core/uncertainty_contact_planning.hpp\"\n#include \"uncertainty_planning_core/simple_robot_models.hpp\"\n#include \"uncertainty_planning_core/simple_samplers.hpp\"\n#include \"uncertainty_planning_core/uncertainty_planning_core.hpp\"\n#include \"fast_kinematic_simulator/fast_kinematic_simulator.hpp\"\n#include \"fast_kinematic_simulator/simulator_environment_builder.hpp\"\n#include \"uncertainty_planning_examples/config_common.hpp\"\n\n#ifndef UR5_LINKED_COMMON_CONFIG_HPP\n#define UR5_LINKED_COMMON_CONFIG_HPP\n\n#ifdef LIMIT_UR5_JOINT_LIMITS\n    #define UR5_JOINT_LIMITS M_PI\n#else\n    #define UR5_JOINT_LIMITS (M_PI * 2.0)\n#endif\n\n#ifndef OVERRIDE_FIXED_RESOLUTION\n    #define RESOLUTION 0.03125\n#endif\n\nnamespace ur5_linked_common_config\n{\n    typedef simple_robot_models::SimpleJointModel SJM;\n    typedef simple_robot_models::SimpleLinkedConfiguration SLC;\n\n    inline uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS GetDefaultOptions()\n    {\n        uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS options;\n        options.clustering_type = uncertainty_contact_planning::CONVEX_REGION_SIGNATURE;\n        options.planner_time_limit = 120.0;\n        options.goal_bias = 0.1;\n        options.step_size = M_PI;\n        options.step_duration = 10.0;\n        options.goal_probability_threshold = 0.51;\n        options.goal_distance_threshold = M_PI_4;\n        options.connect_after_first_solution = 0.0;\n        options.signature_matching_threshold = 0.99;\n        options.distance_clustering_threshold = M_PI_2;\n        options.feasibility_alpha = 0.75;\n        options.variance_alpha = 0.75;\n        options.edge_attempt_count = 50u;\n        options.num_particles = 24u;\n        options.use_contact = true;\n        options.use_reverse = true;\n        options.use_spur_actions = true;\n        options.max_exec_actions = 1000u;\n        options.max_policy_exec_time = 0.0;\n        options.num_policy_simulations = 1u;\n        options.num_policy_executions = 1u;\n        options.policy_action_attempt_count = 100u;\n        options.debug_level = 0;\n        options.planner_log_file = \"/tmp/ur5_planner_log.txt\";\n        options.policy_log_file = \"/tmp/ur5_policy_log.txt\";\n        options.planned_policy_file = \"/tmp/ur5_planned_policy.policy\";\n        options.executed_policy_file = \"/dev/null\";\n        return options;\n    }\n\n    inline uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS GetOptions()\n    {\n        return uncertainty_planning_core::GetOptions(GetDefaultOptions());\n    }\n\n    inline config_common::TASK_CONFIG_PARAMS GetDefaultExtraOptions()\n    {\n        return config_common::TASK_CONFIG_PARAMS(0.03125, 25.0, 0.0, 0.0, \"baxter_blocked_test_mod_env\");\n    }\n\n    inline config_common::TASK_CONFIG_PARAMS GetExtraOptions()\n    {\n        return config_common::GetOptions(GetDefaultExtraOptions());\n    }\n\n    inline simple_robot_models::LINKED_ROBOT_CONFIG GetDefaultRobotConfig(const config_common::TASK_CONFIG_PARAMS& options)\n    {\n        const double env_resolution = options.environment_resolution;\n        const double kp = 1.0;\n        const double ki = 0.0;\n        const double kd = 0.1;\n        const double i_clamp = 0.0;\n        const double velocity_limit = env_resolution * 2.0;\n        const double max_sensor_noise = options.sensor_error;\n        const double max_actuator_noise = options.actuator_error;\n        const simple_robot_models::LINKED_ROBOT_CONFIG robot_config(kp, ki, kd, i_clamp, velocity_limit, max_sensor_noise, max_actuator_noise);\n        return robot_config;\n    }\n\n    inline Eigen::Isometry3d GetBaseTransform()\n    {\n        const Eigen::Isometry3d base_transform = Eigen::Translation3d(0.0, 0.0, 0.0) * Eigen::Quaterniond(Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitZ()));\n        return base_transform;\n    }\n\n    inline SLC MakeUR5ArmConfiguration(const std::vector<double>& joint_values)\n    {\n        assert(joint_values.size() == 6);\n        SLC arm_configuration(6);\n        const double shoulder_pan_joint = joint_values[0];\n        arm_configuration[0] = SJM(std::pair<double, double>(-UR5_JOINT_LIMITS, UR5_JOINT_LIMITS), shoulder_pan_joint, SJM::REVOLUTE); // shoulder_pan_joint\n        const double shoulder_lift_joint = joint_values[1];\n        arm_configuration[1] = SJM(std::pair<double, double>(-UR5_JOINT_LIMITS, UR5_JOINT_LIMITS), shoulder_lift_joint, SJM::REVOLUTE); // shoulder_lift_joint\n        const double elbow_joint = joint_values[2];\n        arm_configuration[2] = SJM(std::pair<double, double>(-UR5_JOINT_LIMITS, UR5_JOINT_LIMITS), elbow_joint, SJM::REVOLUTE); // elbow_joint\n        const double wrist_1_joint = joint_values[3];\n        arm_configuration[3] = SJM(std::pair<double, double>(-UR5_JOINT_LIMITS, UR5_JOINT_LIMITS), wrist_1_joint, SJM::REVOLUTE); // wrist_1_joint\n        const double wrist_2_joint = joint_values[4];\n        arm_configuration[4] = SJM(std::pair<double, double>(-UR5_JOINT_LIMITS, UR5_JOINT_LIMITS), wrist_2_joint, SJM::REVOLUTE); // wrist_2_joint\n        const double wrist_3_joint = joint_values[5];\n        arm_configuration[5] = SJM(std::pair<double, double>(-UR5_JOINT_LIMITS, UR5_JOINT_LIMITS), wrist_3_joint, SJM::REVOLUTE); // wrist_3_joint\n        return arm_configuration;\n    }\n\n    inline std::pair<SLC, SLC> GetStartAndGoal()\n    {\n        // Define the goals of the plan\n        const SLC goal = MakeUR5ArmConfiguration(std::vector<double>{0.0, 0.0, 0.0, 0.0, 0.0, 0.0});\n        const SLC start = MakeUR5ArmConfiguration(std::vector<double>{0.0, 0.0, 0.0, 0.0, 0.0, 0.0});\n        return std::make_pair(start, goal);\n    }\n\n    inline SLC GetReferenceConfiguration()\n    {\n        const SLC reference_configuration = MakeUR5ArmConfiguration(std::vector<double>{0.0, 0.0, 0.0, 0.0, 0.0, 0.0});\n        return reference_configuration;\n    }\n\n    inline std::vector<double> GetJointUncertaintyParams(const config_common::TASK_CONFIG_PARAMS& options)\n    {\n        std::vector<double> uncertainty_params(6, options.actuator_error);\n        return uncertainty_params;\n    }\n\n    inline std::vector<double> GetJointDistanceWeights()\n    {\n        const std::vector<double> max_velocities = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};\n        std::vector<double> distance_weights(max_velocities.size(), 0.0);\n        for (size_t idx = 0; idx < max_velocities.size(); idx++)\n        {\n            distance_weights[idx] = 1.0 / max_velocities[idx];\n        }\n        return distance_weights;\n    }\n\n    inline void MakeCylinderPoints(const double radius, const double length, const double resolution, const Eigen::Vector3d& axis, const std::shared_ptr<EigenHelpers::VectorVector4d>& points)\n    {\n        UNUSED(radius);\n        UNUSED(length);\n        UNUSED(axis);\n        points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));\n        points->push_back(Eigen::Vector4d(resolution, 0.0, 0.0, 1.0));\n        points->push_back(Eigen::Vector4d(0.0, resolution, 0.0, 1.0));\n        points->push_back(Eigen::Vector4d(0.0, resolution * 2.0, 0.0, 1.0));\n        points->push_back(Eigen::Vector4d(0.0, 0.0, resolution, 1.0));\n        points->push_back(Eigen::Vector4d(0.0, 0.0, resolution * 2.0, 1.0));\n        points->push_back(Eigen::Vector4d(0.0, 0.0, resolution * 3.0, 1.0));\n    }\n\n    inline std::shared_ptr<EigenHelpers::VectorVector4d> GetLinkPoints(const std::string& link_name)\n    {\n        if (link_name == \"base_link\")\n        {\n            std::shared_ptr<EigenHelpers::VectorVector4d> link_points(new EigenHelpers::VectorVector4d());\n            MakeCylinderPoints(0.06, 0.05, RESOLUTION, Eigen::Vector3d::UnitZ(), link_points);\n            return link_points;\n        }\n        else if (link_name == \"shoulder_link\")\n        {\n            std::shared_ptr<EigenHelpers::VectorVector4d> link_points(new EigenHelpers::VectorVector4d());\n            MakeCylinderPoints(0.06, 0.05, RESOLUTION, Eigen::Vector3d::UnitZ(), link_points);\n            return link_points;\n        }\n        else if (link_name == \"upper_arm_link\")\n        {\n            std::shared_ptr<EigenHelpers::VectorVector4d> link_points(new EigenHelpers::VectorVector4d());\n            MakeCylinderPoints(0.06, 0.05, RESOLUTION, Eigen::Vector3d::UnitZ(), link_points);\n            return link_points;\n        }\n        else if (link_name == \"forearm_link\")\n        {\n            std::shared_ptr<EigenHelpers::VectorVector4d> link_points(new EigenHelpers::VectorVector4d());\n            MakeCylinderPoints(0.06, 0.05, RESOLUTION, Eigen::Vector3d::UnitZ(), link_points);\n            return link_points;\n        }\n        else if (link_name == \"wrist_1_link\")\n        {\n            std::shared_ptr<EigenHelpers::VectorVector4d> link_points(new EigenHelpers::VectorVector4d());\n            MakeCylinderPoints(0.6, 0.12, RESOLUTION, Eigen::Vector3d::UnitY(), link_points);\n            return link_points;\n        }\n        else if (link_name == \"wrist_2_link\")\n        {\n            std::shared_ptr<EigenHelpers::VectorVector4d> link_points(new EigenHelpers::VectorVector4d());\n            MakeCylinderPoints(0.6, 0.12, RESOLUTION, Eigen::Vector3d::UnitZ(), link_points);\n            return link_points;\n        }\n        else if (link_name == \"wrist_3_link\")\n        {\n            std::shared_ptr<EigenHelpers::VectorVector4d> link_points(new EigenHelpers::VectorVector4d());\n            MakeCylinderPoints(0.05, 0.0823, RESOLUTION, Eigen::Vector3d::UnitY(), link_points);\n            return link_points;\n        }\n        else if (link_name == \"ee_link\")\n        {\n            std::shared_ptr<EigenHelpers::VectorVector4d> link_points(new EigenHelpers::VectorVector4d());\n            MakeCylinderPoints(RESOLUTION * 0.5, RESOLUTION * 0.5, RESOLUTION, Eigen::Vector3d::UnitX(), link_points);\n            return link_points;\n        }\n        else\n        {\n            throw std::invalid_argument(\"Invalid link name\");\n        }\n    }\n\n    typedef uncertainty_planning_core::LinkedActuatorModel UR5JointActuatorModel;\n\n    inline simple_robot_models::SimpleLinkedRobot<UR5JointActuatorModel> GetRobot(const Eigen::Isometry3d& base_transform, const simple_robot_models::LINKED_ROBOT_CONFIG& joint_config, const std::vector<double>& joint_uncertainty_params, const std::vector<double>& joint_distance_weights)\n    {\n        const double shoulder_pan_joint_noise = joint_uncertainty_params[0];\n        const double shoulder_lift_joint_noise = joint_uncertainty_params[1];\n        const double elbow_joint_noise = joint_uncertainty_params[2];\n        const double wrist_1_joint_noise = joint_uncertainty_params[3];\n        const double wrist_2_joint_noise = joint_uncertainty_params[4];\n        const double wrist_3_joint_noise = joint_uncertainty_params[5];\n        // Make the robot model\n        simple_robot_models::RobotLink base_link(GetLinkPoints(\"base_link\"), \"base_link\");\n        simple_robot_models::RobotLink shoulder_link(GetLinkPoints(\"shoulder_link\"), \"shoulder_link\");\n        simple_robot_models::RobotLink upper_arm_link(GetLinkPoints(\"upper_arm_link\"), \"upper_arm_link\");\n        simple_robot_models::RobotLink forearm_link(GetLinkPoints(\"forearm_link\"), \"forearm_link\");\n        simple_robot_models::RobotLink wrist_1_link(GetLinkPoints(\"wrist_1_link\"), \"wrist_1_link\");\n        simple_robot_models::RobotLink wrist_2_link(GetLinkPoints(\"wrist_2_link\"), \"wrist_2_link\");\n        simple_robot_models::RobotLink wrist_3_link(GetLinkPoints(\"wrist_3_link\"), \"wrist_3_link\");\n        simple_robot_models::RobotLink ee_link(GetLinkPoints(\"ee_link\"), \"ee_link\");\n        // Collect the links\n        const std::vector<simple_robot_models::RobotLink> links = {base_link, shoulder_link, upper_arm_link, forearm_link, wrist_1_link, wrist_2_link, wrist_3_link, ee_link};\n        // Set allowed self-collisions (i.e. collisions that actually can't happen, so if they occur, they are numerical issues)\n        const std::vector<std::pair<size_t, size_t>> allowed_self_collisions = {std::pair<size_t, size_t>(0, 1), std::pair<size_t, size_t>(1, 2), std::pair<size_t, size_t>(2, 3), std::pair<size_t, size_t>(3, 4), std::pair<size_t, size_t>(4, 5), std::pair<size_t, size_t>(5, 6), std::pair<size_t, size_t>(6, 7)};\n        // Make the reference configuration\n        const SLC reference_configuration = GetReferenceConfiguration();\n        // Make the joints\n        // Shoulder pan\n        simple_robot_models::RobotJoint<UR5JointActuatorModel> shoulder_pan_joint;\n        shoulder_pan_joint.name = \"shoulder_pan_joint\";\n        shoulder_pan_joint.parent_link_index = 0;\n        shoulder_pan_joint.child_link_index = 1;\n        shoulder_pan_joint.joint_axis = Eigen::Vector3d::UnitZ();\n        shoulder_pan_joint.joint_transform = Eigen::Translation3d(0.0, 0.0, 0.089159) * EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, 0.0);\n        shoulder_pan_joint.joint_model = reference_configuration[0];\n        simple_robot_models::LINKED_ROBOT_CONFIG shoulder_pan_joint_config = joint_config;\n        shoulder_pan_joint_config.velocity_limit = 3.15;\n        const UR5JointActuatorModel shoulder_pan_joint_model(std::abs(shoulder_pan_joint_noise), shoulder_pan_joint_config.velocity_limit);\n        shoulder_pan_joint.joint_controller = simple_robot_models::JointControllerGroup<UR5JointActuatorModel>(shoulder_pan_joint_config, shoulder_pan_joint_model);\n        // Shoulder lift\n        simple_robot_models::RobotJoint<UR5JointActuatorModel> shoulder_lift_joint;\n        shoulder_lift_joint.name = \"shoulder_lift_joint\";\n        shoulder_lift_joint.parent_link_index = 1;\n        shoulder_lift_joint.child_link_index = 2;\n        shoulder_lift_joint.joint_axis = Eigen::Vector3d::UnitY();\n        shoulder_lift_joint.joint_transform = Eigen::Translation3d(0.0, 0.13585, 0.0) * EigenHelpers::QuaternionFromUrdfRPY(0.0, M_PI_2, 0.0);\n        shoulder_lift_joint.joint_model = reference_configuration[1];\n        simple_robot_models::LINKED_ROBOT_CONFIG shoulder_lift_joint_config = joint_config;\n        shoulder_lift_joint_config.velocity_limit = 3.15;\n        const UR5JointActuatorModel shoulder_lift_joint_model(std::abs(shoulder_lift_joint_noise), shoulder_lift_joint_config.velocity_limit);\n        shoulder_lift_joint.joint_controller = simple_robot_models::JointControllerGroup<UR5JointActuatorModel>(shoulder_lift_joint_config, shoulder_lift_joint_model);\n        // Elbow\n        simple_robot_models::RobotJoint<UR5JointActuatorModel> elbow_joint;\n        elbow_joint.name = \"elbow_joint\";\n        elbow_joint.parent_link_index = 2;\n        elbow_joint.child_link_index = 3;\n        elbow_joint.joint_axis = Eigen::Vector3d::UnitY();\n        elbow_joint.joint_transform = Eigen::Translation3d(0.0, -0.1197, 0.42500) * EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, 0.0);\n        elbow_joint.joint_model = reference_configuration[2];\n        simple_robot_models::LINKED_ROBOT_CONFIG elbow_joint_config = joint_config;\n        elbow_joint_config.velocity_limit = 3.15;\n        const UR5JointActuatorModel elbow_joint_model(std::abs(elbow_joint_noise), elbow_joint_config.velocity_limit);\n        elbow_joint.joint_controller = simple_robot_models::JointControllerGroup<UR5JointActuatorModel>(elbow_joint_config, elbow_joint_model);\n        // Wrist 1\n        simple_robot_models::RobotJoint<UR5JointActuatorModel> wrist_1_joint;\n        wrist_1_joint.name = \"wrist_1_joint\";\n        wrist_1_joint.parent_link_index = 3;\n        wrist_1_joint.child_link_index = 4;\n        wrist_1_joint.joint_axis = Eigen::Vector3d::UnitY();\n        wrist_1_joint.joint_transform = Eigen::Translation3d(0.0, 0.0, 0.39225) * EigenHelpers::QuaternionFromUrdfRPY(0.0, M_PI_2, 0.0);\n        wrist_1_joint.joint_model = reference_configuration[3];\n        simple_robot_models::LINKED_ROBOT_CONFIG wrist_1_joint_config = joint_config;\n        wrist_1_joint_config.velocity_limit = 3.2;\n        const UR5JointActuatorModel wrist_1_joint_model(std::abs(wrist_1_joint_noise), wrist_1_joint_config.velocity_limit);\n        wrist_1_joint.joint_controller = simple_robot_models::JointControllerGroup<UR5JointActuatorModel>(wrist_1_joint_config, wrist_1_joint_model);\n        // Wrist 2\n        simple_robot_models::RobotJoint<UR5JointActuatorModel> wrist_2_joint;\n        wrist_2_joint.name = \"wrist_2_joint\";\n        wrist_2_joint.parent_link_index = 4;\n        wrist_2_joint.child_link_index = 5;\n        wrist_2_joint.joint_axis = Eigen::Vector3d::UnitZ();\n        wrist_2_joint.joint_transform = Eigen::Translation3d(0.0, 0.093, 0.0) * EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, 0.0);\n        wrist_2_joint.joint_model = reference_configuration[4];\n        simple_robot_models::LINKED_ROBOT_CONFIG wrist_2_joint_config = joint_config;\n        wrist_2_joint_config.velocity_limit = 3.2;\n        const UR5JointActuatorModel wrist_2_joint_model(std::abs(wrist_2_joint_noise), wrist_2_joint_config.velocity_limit);\n        wrist_2_joint.joint_controller = simple_robot_models::JointControllerGroup<UR5JointActuatorModel>(wrist_2_joint_config, wrist_2_joint_model);\n        // Wrist 3\n        simple_robot_models::RobotJoint<UR5JointActuatorModel> wrist_3_joint;\n        wrist_3_joint.name = \"wrist_3_joint\";\n        wrist_3_joint.parent_link_index = 5;\n        wrist_3_joint.child_link_index = 6;\n        wrist_3_joint.joint_axis = Eigen::Vector3d::UnitY();\n        wrist_3_joint.joint_transform = Eigen::Translation3d(0.0, 0.0, 0.09465) * EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, 0.0);\n        wrist_3_joint.joint_model = reference_configuration[5];\n        simple_robot_models::LINKED_ROBOT_CONFIG wrist_3_joint_config = joint_config;\n        wrist_3_joint_config.velocity_limit = 3.2;\n        const UR5JointActuatorModel wrist_3_joint_model(std::abs(wrist_3_joint_noise), wrist_3_joint_config.velocity_limit);\n        wrist_3_joint.joint_controller = simple_robot_models::JointControllerGroup<UR5JointActuatorModel>(wrist_3_joint_config, wrist_3_joint_model);\n        // Fixed wrist->EE joint\n        simple_robot_models::RobotJoint<UR5JointActuatorModel> ee_fixed_joint;\n        ee_fixed_joint.name = \"ee_fixed_joint\";\n        ee_fixed_joint.parent_link_index = 6;\n        ee_fixed_joint.child_link_index = 7;\n        ee_fixed_joint.joint_axis = Eigen::Vector3d::UnitZ();\n        ee_fixed_joint.joint_transform = Eigen::Translation3d(0.0, 0.0823, 0.0) * EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, M_PI_2);\n        ee_fixed_joint.joint_model = SJM(std::make_pair(0.0, 0.0), 0.0, SJM::FIXED);\n        // We don't need an uncertainty model for a fixed joint\n        ee_fixed_joint.joint_controller = simple_robot_models::JointControllerGroup<UR5JointActuatorModel>(joint_config);\n        // Collect the joints\n        const std::vector<simple_robot_models::RobotJoint<UR5JointActuatorModel>> joints = {shoulder_pan_joint, shoulder_lift_joint, elbow_joint, wrist_1_joint, wrist_2_joint, wrist_3_joint, ee_fixed_joint};\n        const simple_robot_models::SimpleLinkedRobot<UR5JointActuatorModel> robot(base_transform, links, joints, allowed_self_collisions, reference_configuration, joint_distance_weights);\n        return robot;\n    }\n\n    inline uncertainty_planning_core::LinkedSamplerPtr GetSampler()\n    {\n        // Make the sampler\n        const SLC reference_configuration = GetReferenceConfiguration();\n        return uncertainty_planning_core::LinkedSamplerPtr(new simple_samplers::SimpleLinkedBaseSampler<uncertainty_planning_core::PRNG>(reference_configuration));\n    }\n\n    inline uncertainty_planning_core::LinkedSimulatorPtr GetSimulator(const config_common::TASK_CONFIG_PARAMS& options, const int32_t debug_level)\n    {\n        const simulator_environment_builder::EnvironmentComponents environment_components = simulator_environment_builder::BuildCompleteEnvironment(options.environment_id, options.environment_resolution);\n        const fast_kinematic_simulator::SolverParameters solver_params = fast_kinematic_simulator::GetDefaultSolverParameters();\n        return fast_kinematic_simulator::MakeLinkedSimulator(environment_components.GetEnvironment(), environment_components.GetEnvironmentSDF(), environment_components.GetSurfaceNormalsGrid(), solver_params, options.simulation_controller_frequency, debug_level);\n    }\n}\n\n#endif // UR5_LINKED_COMMON_CONFIG_HPP\n", "meta": {"hexsha": "43003afb364af503e8662b0d73ba06f1f21be058", "size": 20816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uncertainty_planning_examples/ur5_common_config.hpp", "max_stars_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_stars_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T05:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T02:12:02.000Z", "max_issues_repo_path": "include/uncertainty_planning_examples/ur5_common_config.hpp", "max_issues_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_issues_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "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/uncertainty_planning_examples/ur5_common_config.hpp", "max_forks_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_forks_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-04-17T03:08:47.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-04T13:08:59.000Z", "avg_line_length": 57.0301369863, "max_line_length": 311, "alphanum_fraction": 0.7268447348, "num_tokens": 5308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18868221808365662}}
{"text": "/********************************************************\n  Stanford Driving Software\n  Copyright (c) 2011 Stanford University\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with \n  or without modification, are permitted provided that the \n  following conditions are met:\n\n* Redistributions of source code must retain the above \n  copyright notice, this list of conditions and the \n  following disclaimer.\n* Redistributions in binary form must reproduce the above\n  copyright notice, this list of conditions and the \n  following disclaimer in the documentation and/or other\n  materials provided with the distribution.\n* The names of the contributors may not be used to endorse\n  or promote products derived from this software\n  without specific prior written permission.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n  CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \n  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \n  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n  DAMAGE.\n ********************************************************/\n\n\n#include <track_manager.h>\n#include <boost/filesystem.hpp>\n#include \"multibooster_support2.h\"\n\nusing namespace std;\nusing boost::shared_ptr;\nusing namespace track_manager;\nusing namespace pipeline;\nusing namespace Eigen;\n\n\n\n// Object* buildObject(const vector< shared_ptr<DescriptorNode> >& dns, int label) {\n//   Object* obj = new Object;\n//   obj->label_ = label;\n//   obj->descriptors_ = vector<descriptor>(dns.size());\n  \n//   for(size_t i = 0; i < dns.size(); ++i) {\n//     descriptor& desc = obj->descriptors_[i];\n//     if(dns[i]->getDescriptor()) {\n//       desc.vector = new VectorXf(); \n//       *desc.vector = *dns[i]->getDescriptor(); //TODO: Make multibooster take a shared_ptr.\n//       desc.length_squared = desc.vector->dot(*desc.vector);\n//     }\n//     else { \n//       desc.vector = NULL;\n//       desc.length_squared = -1;\n//     }\n//   }\n  \n//   return obj;\n//}\n\n\n\n// Object* getDescriptorsForCloud2(DescriptorPipeline& dp, const sensor_msgs::PointCloud& roscloud, bool debug = false, bool timing = false) {\n//   shared_ptr<MatrixXf> cloud((MatrixXf*)NULL);\n//   shared_ptr<VectorXf> intensity((VectorXf*)NULL);\n//   rosToEigen(roscloud, &cloud, &intensity);\n//   dp.setInput(cloud, intensity);\n\n//   timeval start, end;\n//   gettimeofday(&start, NULL);\n  \n//   dp.compute();\n//   vector< shared_ptr<DescriptorNode> > dns = dp.getOutputDescriptorNodes(0);\n\n//   Object* obj = new Object;\n//   obj->descriptors_ = vector<descriptor>(dns.size());\n//   for(size_t i = 0; i < dns.size(); ++i) {\n//     descriptor& desc = obj->descriptors_[i];\n//     if(dns[i]->getDescriptor()) {\n//       desc.vector = new VectorXf(); \n//       *desc.vector = *dns[i]->getDescriptor(); //TODO: Make multibooster take a shared_ptr.\n//       desc.length_squared = desc.vector->dot(*desc.vector);\n//     }\n//     else { \n//       desc.vector = NULL;\n//       desc.length_squared = -1;\n//     }\n//   }\n//   dp.flush();\n  \n//   gettimeofday(&end, NULL);\n//   if(timing)\n//     cout << (end.tv_sec - start.tv_sec) * 1000. + (end.tv_usec - start.tv_usec) / 1000. << \" ms to compute descriptors and copy into object.\" << endl;\n//   return obj;\n// }\n\n\nvoid accumulateStats(MultiBooster* mb, const TrackManager& tm, PerfStats* stats, vector< shared_ptr<Track> >* misclassified) {\n  size_t max_num_clouds = 0;\n  for(size_t i = 0; i < tm.tracks_.size(); ++i) {\n    if(tm.tracks_[i]->clouds_.size() > max_num_clouds)\n      max_num_clouds = tm.tracks_[i]->clouds_.size();\n  }\n  cout << \"Building pipeline...\"; cout.flush();\n  int num_threads = 1;\n  ClassifierPipeline cp(mb, num_threads);\n  cout << \" done.\" << endl;\n\n  timeval start, end;\n  gettimeofday(&start, NULL);\n  int num_clouds = 0;\n  for(size_t i = 0; i < tm.tracks_.size(); ++i) {\n    if(i % 100 == 0) {\n      cout << \".\"; cout.flush();\n    }\n    //cout << \"Working on track \" << i << \" / \" << tm.tracks_.size() << endl;\n    Track& tr = *tm.tracks_[i];\n\n    int label;\n    if(tr.label_.compare(\"unlabeled\") == 0)\n      continue;\n    if(tr.label_.compare(\"background\") == 0)\n      label = -1;\n    else\n      label = mb->class_map_.toId(tr.label_);\n\n    \n    vector< shared_ptr<MatrixXf> > clouds(tr.clouds_.size());\n    vector< shared_ptr<VectorXf> > intensities(tr.clouds_.size());\n    for(size_t j = 0; j < tr.clouds_.size(); ++j) {\n      ++num_clouds;\n      shared_ptr<MatrixXf> cloud((MatrixXf*)NULL);\n      shared_ptr<VectorXf> intensity((VectorXf*)NULL);\n      rosToEigen(*tr.clouds_[j], &cloud, &intensity);\n      clouds[j] = cloud;\n      intensities[j] = intensity;\n    }\n\n    timeval start2, end2;\n    gettimeofday(&start2, NULL);\n    vector<VectorXf> responses = cp.classify(clouds, intensities);\n    gettimeofday(&end2, NULL);\n    cout << ((end2.tv_sec - start2.tv_sec) * 1000. + (end2.tv_usec - start2.tv_usec) / 1000.) / (float)clouds.size() << \" ms per object.\" << endl;\n\n    // -- Get the prediction and increment statistics.\n    VectorXf track_prediction = mb->prior_;\n    assert(responses.size() == tr.clouds_.size());\n    for(size_t j = 0; j < responses.size(); ++j) {\n      track_prediction += 2*responses[j] - mb->prior_;\n    }\n    cout << track_prediction.transpose() << endl;\n    stats->incrementStats(label, track_prediction);\n\n    // -- If we were wrong, set the track aside to be saved.\n    int prediction = 0;\n    float val = track_prediction.maxCoeff(&prediction);\n    if(val < 0)\n      prediction = -1;\n    if(label != prediction)\n      misclassified->push_back(tm.tracks_[i]);\n  }\n  gettimeofday(&end, NULL);\n  cout << \"Descriptor computation and classification of \" << num_clouds << \" clouds took \"\n       << end.tv_sec - start.tv_sec << \" seconds, mean time per cloud is \" << (double)(end.tv_sec - start.tv_sec) / (double)num_clouds << endl;\n}\n\nint main(int argc, char** argv) {\n\n  if(argc < 3) {\n    cout << \"Usage: \" << argv[0] << \" CLASSIFIER TRACK_MANAGER [TRACK_MANAGER ...]\" << endl;\n    return 1;\n  }\n  \n  cout << \"Loading multibooster \" << argv[1] << endl;\n  MultiBooster* mb = new MultiBooster(argv[1]);\n  if(getenv(\"WC_LIMIT\"))\n    mb->wc_limiter_ = atoi(getenv(\"WC_LIMIT\"));\n\n  mb->applyNewMappings(mb->class_map_, getDescriptorNames());\n  cout << mb->status(false) << endl;\n\n  PerfStats stats(mb->class_map_);\n  for(int i = 2; i < argc; ++i) { \n    cout << \"Loading track manager \" << argv[i] << endl;\n    cerr << \"Loading track manager \" << argv[i] << endl;\n    TrackManager tm(argv[i]);\n    cout << \"Loaded \" << tm.tracks_.size() << \" tracks.\" << endl;\n    if(tm.tracks_.size() == 0) {\n      cerr << \"0 tracks.  Skipping.\" << endl;\n      continue;\n    }\n    vector< shared_ptr<Track> > misclassified;\n    accumulateStats(mb, tm, &stats, &misclassified);\n\n\n    boost::filesystem::path path(argv[i]);\n    string stem = path.filename().substr(0, path.filename().size() - 3);\n    string savename = \"misclassified/\" + stem + \".tm\";\n    cout << misclassified.size() << \" misclassified tracks.  Saving to \" << savename << endl;\n    TrackManager mc(misclassified);\n    int foo = system(\"mkdir -p misclassified\");     --foo; // This is to avoid a warning.\n    mc.save(savename);\n  }\n\n  cout << stats.statString() << endl;\n  delete mb;\n  return 0;\n}\n", "meta": {"hexsha": "f65299db57be450e2412c4f17e4da4945e18767a", "size": 7785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "11_learning_materials/stanford_self_driving_car/perception/perception/src/track_classifier.cpp", "max_stars_repo_name": "EatAllBugs/autonomous_learning", "max_stars_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T08:49:57.000Z", "max_issues_repo_path": "11_learning_materials/stanford_self_driving_car/perception/perception/src/track_classifier.cpp", "max_issues_repo_name": "yinflight/autonomous_learning", "max_issues_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11_learning_materials/stanford_self_driving_car/perception/perception/src/track_classifier.cpp", "max_forks_repo_name": "yinflight/autonomous_learning", "max_forks_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T00:58:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T13:16:09.000Z", "avg_line_length": 35.3863636364, "max_line_length": 153, "alphanum_fraction": 0.6394348105, "num_tokens": 2043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.1886822180836566}}
{"text": "// Copyright 2021 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#ifndef SCENE_MODULE__OCCLUSION_SPOT__GRID_UTILS_HPP_\n#define SCENE_MODULE__OCCLUSION_SPOT__GRID_UTILS_HPP_\n\n#include <grid_map_core/GridMap.hpp>\n#include <grid_map_core/iterators/LineIterator.hpp>\n#include <grid_map_core/iterators/PolygonIterator.hpp>\n#include <opencv2/opencv.hpp>\n#include <scene_module/occlusion_spot/geometry.hpp>\n\n#include <nav_msgs/msg/occupancy_grid.hpp>\n\n#include <boost/geometry.hpp>\n\n#include <lanelet2_core/geometry/Lanelet.h>\n#include <lanelet2_core/primitives/Lanelet.h>\n\n#include <vector>\n\nnamespace behavior_velocity_planner\n{\nnamespace grid_utils\n{\nnamespace occlusion_cost_value\n{\nstatic constexpr int NO_INFORMATION = -1;\nstatic constexpr int FREE_SPACE = 0;\nstatic constexpr int UNKNOWN = 50;\nstatic constexpr int OCCUPIED = 100;\n}  // namespace occlusion_cost_value\n\nstruct GridParam\n{\n  int free_space_max;  // maximum value of a freespace cell in the occupancy grid\n  int occupied_min;    // minimum value of an occupied cell in the occupancy grid\n};\nstruct OcclusionSpotSquare\n{\n  grid_map::Index index;        // index of the anchor\n  grid_map::Position position;  // position of the anchor\n  int side_size;                // number of cells for each side of the square\n};\n// @brief structure representing a OcclusionSpot on the OccupancyGrid\nstruct OcclusionSpot\n{\n  double distance_along_lanelet;\n  lanelet::ConstLanelet lanelet;\n  lanelet::BasicPoint2d position;\n};\n//!< @brief Return true\n// if the given cell is a occlusion_spot square of size min_size*min_size in the given grid\nbool isOcclusionSpotSquare(\n  OcclusionSpotSquare & occlusion_spot, const grid_map::Matrix & grid_data,\n  const grid_map::Index & cell, const int side_size, const grid_map::Size & grid_size);\n//!< @brief Find all occlusion spots inside the given lanelet\nvoid findOcclusionSpots(\n  std::vector<grid_map::Position> & occlusion_spot_positions, const grid_map::GridMap & grid,\n  const lanelet::BasicPolygon2d & polygon, const double min_size);\n//!< @brief Return true if the path between the two given points is free of occupied cells\nbool isCollisionFree(\n  const grid_map::GridMap & grid, const grid_map::Position & p1, const grid_map::Position & p2);\n//!< @brief get the corner positions of the square described by the given anchor\nvoid getCornerPositions(\n  std::vector<grid_map::Position> & corner_positions, const grid_map::GridMap & grid,\n  const OcclusionSpotSquare & occlusion_spot_square);\nvoid imageToOccupancyGrid(const cv::Mat & cv_image, nav_msgs::msg::OccupancyGrid * occupancy_grid);\nvoid toQuantizedImage(\n  const nav_msgs::msg::OccupancyGrid & occupancy_grid, cv::Mat * cv_image, const GridParam & param);\nvoid denoiseOccupancyGridCV(\n  nav_msgs::msg::OccupancyGrid & occupancy_grid, grid_map::GridMap & grid_map,\n  const GridParam & param);\n}  // namespace grid_utils\n}  // namespace behavior_velocity_planner\n\n#endif  // SCENE_MODULE__OCCLUSION_SPOT__GRID_UTILS_HPP_\n", "meta": {"hexsha": "1601d49b5806dad9349e2840b51a1e3ba8e73f3a", "size": 3500, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/scene_module/occlusion_spot/grid_utils.hpp", "max_stars_repo_name": "loop-perception/AutowareArchitectureProposal.iv", "max_stars_repo_head_hexsha": "5d8dff0db51634f0c42d2a3e87ca423fbee84348", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-09-25T08:52:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T02:39:31.000Z", "max_issues_repo_path": "planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/scene_module/occlusion_spot/grid_utils.hpp", "max_issues_repo_name": "loop-perception/AutowareArchitectureProposal.iv", "max_issues_repo_head_hexsha": "5d8dff0db51634f0c42d2a3e87ca423fbee84348", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T04:28:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T13:53:15.000Z", "max_forks_repo_path": "planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/scene_module/occlusion_spot/grid_utils.hpp", "max_forks_repo_name": "taikitanaka3/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "0d47ea532118c98458516a8c83fbdab3d27c6231", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T05:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T03:14:25.000Z", "avg_line_length": 39.3258426966, "max_line_length": 100, "alphanum_fraction": 0.7762857143, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18857024147945223}}
{"text": "#include <exe/inputParser.h>\n\n#include <base/cgal_typedefs.h>\n#include <IO/fileIO.h>\n#include <IO/ttIO.h>\n#include <IO/ethIO.h>\n#ifdef COLMAP\n#include <IO/colmapIO.h>\n#endif\n#include <util/helper.h>\n#include <util/geometricOperations.h>\n\n#include <processing/meshProcessing.h>\n#include <processing/edgeManifoldness.h>\n#include <processing/graphCut.h>\n\n#include <processing/pointSetProcessing.h>\n#include <processing/normalAndSensorProcessing.h>\n#include <processing/evaluation.h>\n#include <processing/rayTracingFacet.h>\n\n#include <learning/learning.h>\n#include <learning/learningMath.h>\n#include <learning/learningRayTracing.h>\n#include <learning/learningRayTracingGroundTruth.h>\n#include <learning/learningIO_bin.h>\n\n\n#include <CGAL/optimal_bounding_box.h>\n#include <boost/filesystem.hpp>\nusing namespace boost::filesystem;\n\n\n/////////////////////////////////////////////////////////////////////\n///////////////////////// CONTROL FUNCTIONS /////////////////////////\n/////////////////////////////////////////////////////////////////////\nint extractFeatures(dirHolder& dir, dataHolder& data, runningOptions& options, exportOptions& exportO){\n\n\n    ///////////////////////////////\n    ///////// FILE NAMING /////////\n    ///////////////////////////////\n    options.scoring=\"_\"+options.scoring;\n    if(dir.read_file.empty())\n        dir.read_file = dir.write_file;\n    if(dir.write_file.empty())\n        dir.write_file = dir.read_file;\n\n    ///////////////////////////////\n    ///////// IMPORT SCAN /////////\n    ///////////////////////////////\n    // sampling input\n    if(options.data_source == \"ply\"){\n        importPLYPoints(dir, data);\n    }\n    else if(options.data_source == \"npz\"){\n        importNPZ(dir, data);\n    }\n//    #ifdef COLMAP\n//    else if(options.data_source == \"colmap\"){\n//        readColmapFiles(dir, data);\n//    }\n//    #endif\n    #ifdef OpenMVS\n    else if(options.data_source == \"omvs\"){\n        if(importOMVSScene(dir, data))\n            return 1;\n    }\n    #endif\n    else{\n        cout << \"ERROR: not a valid reconstruction input\" << endl;\n        return 1;\n    }\n\n\n    // ground truth\n    if(!dir.gt_poly_file.empty()){\n        if(dir.gt_poly_file.substr(dir.gt_poly_file.length() - 3 ) == \"off\"){\n            if(importOFFMesh(dir.path+dir.gt_poly_file, data.gt_poly))\n                return 1;\n//            CGAL::Polygon_mesh_processing::keep_largest_connected_components(data.gt_poly, 1);\n        }\n        #ifdef RECONBENCH\n        else if(dir.gt_poly_file.substr(dir.gt_poly_file.length() - 3 ) == \"mpu\"){\n            if(importImplicit(dir, data))\n                return 1;\n        }\n        #endif\n        else{\n            cerr << \"\\nnot a valid ending for a ground truth file. choose either .mpu or .off\" << endl;\n            return 1;\n        }\n        assert(data.gt_poly.size_of_vertices() > 0);\n        options.ground_truth = 1;\n    }\n\n    ///////////////////////////////////\n    ///////// PREPROCESS DATA /////////\n    ///////////////////////////////////\n    if(!dir.transformation_file.empty()){\n        // import translation matrix\n//        if(importTransformationMatrix(dir,data))\n//            return 1;\n        if(applyTransformationMatrix(data))\n            return 1;\n    }\n    // calc gt obb\n    if(!options.gt_isclosed){\n        cout << \"\\nMake bounding box of open GT for cropping input...\" << endl;\n        assert(options.ground_truth);\n        // get centroid of ground truth\n        getOrientedBoundingBox(data.gt_poly,data.bb_array,data.bb_surface_mesh);\n        data.gt_centroid = getBoundingBoxCentroid(data.bb_array,1000.0);\n        cout << \"\\t-ground truth centroid for ray tracing: \" << data.gt_centroid << \"-1000\" << endl;\n        clipWithBoundingBox(data.points,data.infos,data.bb_surface_mesh);\n\n    }\n\n    if(options.scale > 0.0)\n        standardizePointSet(dir, data, options.scale);\n\n//    if(options.scoring == \"_rt\")\n//        orderSensors(data);\n//    else\n//        cout << \"\\nSensors not ordered for ray-tracing\" << endl;\n\n    if(exportO.cameras){\n        dir.suffix = \"_cameras\";\n        exportCameraCenter(dir, data);\n    }\n    // export the scanned points\n    if(exportO.toply){\n        exportO.color = data.has_color;\n        exportO.normals = data.has_normal;\n        exportPLY(dir, data.points, data.infos, exportO);\n    }\n\n    if(exportO.tonpz){\n        toXTensor(data);\n        exportNPZ(dir,data);\n    }\n\n    //////////////////////////////////////\n    /////// DELAUNAY TRIANGULATION ///////\n    //////////////////////////////////////\n    if(options.Dt_epsilon > 0.0)\n        makeAdaptiveDelaunayWithInfo(data, options.Dt_epsilon);\n    else\n        makeDelaunayWithInfo(data);\n\n//    cout << \"Mean edge length after scaling: \" << calcMeanEdgeLength(data) << endl;\n\n\n    ///////////////////////////////////\n    /////// TETRAHEDRON SCORING ///////\n    ///////////////////////////////////\n    // make an index, necessary for graphExport e.g.\n    options.make_global_cell_idx=1;\n    indexDelaunay(data, options);\n\n    if(!options.ground_truth){\n        // this constructs the features which are exported to the cell ray graph,\n        // important to note the difference between score, and features, where score is not used in any way in the learning.\n        if(options.scale == 0.0)\n            cout << \"\\nConsider turning on scaling with --sn, if your learning data is not yet scaled to a unit cube!\" << endl;\n        assert(data.has_sensor);\n        learning::rayTracing(data.Dt, options);\n        // this is only for making a reconstruction of a lrt, but has no influence on the features or the learning\n//        learning::aggregateScoreAndLabel(data.Dt);\n    }\n    else{\n        assert(data.has_sensor);\n        learning::rayTracing(data.Dt, options);\n        if(dir.gt_poly_file.substr(dir.gt_poly_file.length() - 3 ) == \"off\"){\n            if(options.gt_isclosed){\n                if(labelObjectWithClosedGroundTruth(dir,data, options.number_of_points_per_cell))\n                    return 1;\n            }\n            else{\n                if(labelObjectWithOpenGroundTruth(dir,data, options.number_of_points_per_cell))\n                    return 1;\n            }\n        }\n        #ifdef RECONBENCH\n        if(dir.gt_poly_file.substr(dir.gt_poly_file.length() - 3 ) == \"mpu\"){\n            labelObjectWithImplicit(data, options.number_of_points_per_cell);\n        }\n        #endif\n\n    }\n\n    // get tet index per eval point\n    if(!dir.occ_file.empty()){\n        if(importOccPoints(dir,data))\n            return 1;\n        point2TetraIndex(data);\n    }\n\n\n\n    ////////////////////////////\n    ////////// EXPORT //////////\n    ////////////////////////////\n    // export _eval.npz file, with eval points, occupancy and point2tetIndex\n    if(!dir.occ_file.empty())\n        exportOccPoints(dir,data);\n\n    //// export features and labels\n    // check if labels directory exists, if not create it\n    path lpath(dir.path);\n    lpath /= string(\"dgnn\");\n    if(!is_directory(lpath))\n        create_directory(lpath);\n    // export the features and labels\n    auto ge = graphExporter(dir, data.Dt, options);\n    ge.run(true);\n\n\n    ///// export the 3DT as npz\n    options.make_global_cell_idx=1;\n    options.make_global_vertex_idx=1;\n    options.make_finite_cell_idx=0;\n    options.make_finite_vertex_idx=0;\n    indexDelaunay(data, options);\n    export3DT(dir,data);\n\n    if(exportO.interface){\n        for(auto cit = data.Dt.all_cells_begin(); cit != data.Dt.all_cells_end(); cit++){\n            if(data.Dt.is_infinite(cit)){\n                cit->info().gc_label = 1;\n                continue;\n            }\n            // this means untraversed cells and 50/50 cells will be labelled as inside\n            cit->info().gc_label = cit->info().outside_score > cit->info().inside_score ? 1 : 0;\n        }\n        exportInterface(dir, data, options, exportO);\n    }\n\n    return 0;\n}\n\n\n\nint main(int argc, char const *argv[]){\n\n\n    cliParser ip(\"feat\");\n    if(ip.parse(argc, argv))\n        return 1;\n    if(ip.getInput())\n        return 1;\n    if(ip.getOutput())\n        return 1;\n    if(ip.getFeat())\n        return 1;\n\n    auto start = std::chrono::high_resolution_clock::now();\n    cout << \"\\n-----FEATURE EXTRACTION-----\" << endl;\n    cout << \"\\nWorking dir set to:\\n\\t-\" << ip.dh.path << endl;\n\n    dataHolder data;\n    if(extractFeatures(ip.dh, data, ip.ro, ip.eo))\n        return 1;\n\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);\n    cout << \"\\n-----FEATURE EXTRACTION FINISHED in \"<< duration.count() << \"s -----\\n\" << endl;\n\n    return 0;\n\n}\n\n\n\n", "meta": {"hexsha": "ab6aa930b85d1fa29bae966da0df3d28c9428898", "size": 8627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/exe/feat.cpp", "max_stars_repo_name": "raphaelsulzer/mesh-tools", "max_stars_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-24T03:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T03:39:05.000Z", "max_issues_repo_path": "src/exe/feat.cpp", "max_issues_repo_name": "raphaelsulzer/mesh-tools", "max_issues_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-24T06:59:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T01:25:09.000Z", "max_forks_repo_path": "src/exe/feat.cpp", "max_forks_repo_name": "raphaelsulzer/mesh-tools", "max_forks_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_forks_repo_licenses": ["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.3709090909, "max_line_length": 127, "alphanum_fraction": 0.5697229628, "num_tokens": 2002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3629691917376782, "lm_q1q2_score": 0.1885702343194413}}
{"text": "/**\n * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * This program is free software: you can redistribute it and/or modify\n * it 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 * 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 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 this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n#include <bitcoin/bitcoin/wallet/stealth_address.hpp>\n\n#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <bitcoin/bitcoin/formats/base_58.hpp>\n#include <bitcoin/bitcoin/math/checksum.hpp>\n#include <bitcoin/bitcoin/math/elliptic_curve.hpp>\n#include <bitcoin/bitcoin/math/hash.hpp>\n#include <bitcoin/bitcoin/math/stealth.hpp>\n#include <bitcoin/bitcoin/utility/assert.hpp>\n#include <bitcoin/bitcoin/utility/binary.hpp>\n#include <bitcoin/bitcoin/utility/data.hpp>\n\nnamespace libbitcoin {\nnamespace wallet {\n\nusing namespace bc::chain;\n\nstatic constexpr uint8_t version_size = sizeof(uint8_t);\nstatic constexpr uint8_t options_size = sizeof(uint8_t);\nstatic constexpr uint8_t number_keys_size = sizeof(uint8_t);\nstatic constexpr uint8_t number_sigs_size = sizeof(uint8_t);\nstatic constexpr uint8_t filter_length_size = sizeof(uint8_t);\nstatic constexpr uint8_t max_spend_key_count = max_uint8;\n\n// wiki.unsystem.net/index.php/DarkWallet/Stealth#Address_format\n// [version:1=0x2a][options:1][scan_pubkey:33][N:1][spend_pubkey_1:33]..\n// [spend_pubkey_N:33][number_signatures:1][prefix_number_bits:1]\n// [filter:prefix_number_bits / 8, round up][checksum:4]\n// Estimate assumes N = 0 and prefix_length = 0:\nconstexpr size_t min_address_size = version_size + options_size +\n    ec_compressed_size + number_keys_size + number_sigs_size +\n    filter_length_size + checksum_size;\n\n// Document the assumption that the prefix is defined with an 8 bit block size.\nstatic_assert(binary::bits_per_block == byte_bits,\n    \"The stealth prefix must use an 8 bit block size.\");\n\nconst uint8_t stealth_address::mainnet_p2kh = 0x2a;\nconst uint8_t stealth_address::reuse_key_flag = 1 << 0;\nconst size_t stealth_address::min_filter_bits = 1 * byte_bits;\nconst size_t stealth_address::max_filter_bits = sizeof(uint32_t) * byte_bits;\n\nstealth_address::stealth_address()\n  : valid_(false), version_(0), scan_key_(null_compressed_point),\n    spend_keys_(), signatures_(0), filter_()\n{\n}\n\nstealth_address::stealth_address(const stealth_address& other)\n  : valid_(other.valid_), version_(other.version_), scan_key_(other.scan_key_),\n    spend_keys_(other.spend_keys_), signatures_(other.signatures_),\n    filter_(other.filter_)\n{\n}\n\nstealth_address::stealth_address(const std::string& encoded)\n  : stealth_address(from_string(encoded))\n{\n}\n\nstealth_address::stealth_address(const data_chunk& decoded)\n  : stealth_address(from_stealth(decoded))\n{\n}\n\nstealth_address::stealth_address(const binary& filter,\n    const ec_compressed& scan_key, const point_list& spend_keys,\n    uint8_t signatures, uint8_t version)\n  : stealth_address(from_stealth(filter, scan_key, spend_keys, signatures,\n        version))\n{\n}\n\nstealth_address::stealth_address(uint8_t version, const binary& filter,\n    const ec_compressed& scan_key, const point_list& spend_keys,\n    uint8_t signatures)\n  : valid_(true), filter_(filter), scan_key_(scan_key),\n    spend_keys_(spend_keys), signatures_(signatures), version_(version)\n{\n}\n\n// Factories.\n// ----------------------------------------------------------------------------\n\nstealth_address stealth_address::from_string(const std::string& encoded)\n{\n    data_chunk decoded;\n    return decode_base58(decoded, encoded) ? stealth_address(decoded) :\n        stealth_address();\n}\n\n// This is the stealth address parser.\nstealth_address stealth_address::from_stealth(const data_chunk& decoded)\n{\n    // Size is guarded until we get to N.\n    auto required_size = min_address_size;\n    if (decoded.size() < required_size || !verify_checksum(decoded))\n        return{};\n\n    // [version:1 = 0x2a]\n    auto iterator = decoded.begin();\n    const auto version = *iterator;\n\n    // [options:1]\n    ++iterator;\n    const auto options = *iterator;\n    if (options > reuse_key_flag)\n        return{};\n\n    // [scan_pubkey:33]\n    ++iterator;\n    auto scan_key_begin = iterator;\n    iterator += ec_compressed_size;\n    ec_compressed scan_key;\n    std::copy_n(scan_key_begin, ec_compressed_size, scan_key.begin());\n\n    // [N:1]\n    auto number_spend_pubkeys = *iterator;\n    ++iterator;\n\n    // Adjust and retest required size. for pubkey list.\n    required_size += number_spend_pubkeys * ec_compressed_size;\n    if (decoded.size() < required_size)\n        return{};\n\n    // We don't explicitly save 'reuse', instead we add to spend_keys_.\n    point_list spend_keys;\n    if (options == reuse_key_flag)\n        spend_keys.push_back(scan_key);\n\n    // [spend_pubkey_1:33]..[spend_pubkey_N:33]\n    ec_compressed point;\n    for (auto key = 0; key < number_spend_pubkeys; ++key)\n    {\n        auto spend_key_begin = iterator;\n        iterator += ec_compressed_size;\n        std::copy_n(spend_key_begin, ec_compressed_size, point.begin());\n        spend_keys.push_back(point);\n    }\n\n    // [number_signatures:1]\n    const auto signatures = *iterator;\n    ++iterator;\n\n    // [prefix_number_bits:1]\n    const auto filter_bits = *iterator;\n    if (filter_bits > max_filter_bits)\n        return{};\n\n    // [prefix:prefix_number_bits / 8, round up]\n    ++iterator;\n    const auto filter_bytes = (filter_bits + (byte_bits - 1)) / byte_bits;\n\n    // Adjust and retest required size.\n    required_size += filter_bytes;\n    if (decoded.size() != required_size)\n        return{};\n\n    // Deserialize the filter bytes/blocks.\n    const data_chunk raw_filter(iterator, iterator + filter_bytes);\n    const binary filter(filter_bits, raw_filter);\n    return{ filter, scan_key, spend_keys, signatures, version };\n}\n\n// This corrects signature and spend_keys.\nstealth_address stealth_address::from_stealth(const binary& filter,\n    const ec_compressed& scan_key, const point_list& spend_keys,\n    uint8_t signatures, uint8_t version)\n{\n    // Ensure there is at least one spend key.\n    auto spenders = spend_keys;\n    if (spenders.empty())\n        spenders.push_back(scan_key);\n\n    // Guard against too many keys.\n    const auto spend_keys_size = spenders.size();\n    if (spend_keys_size > max_spend_key_count)\n        return{};\n\n    // Guard against prefix too long.\n    auto prefix_number_bits = filter.size();\n    if (prefix_number_bits > max_filter_bits)\n        return{};\n\n    // Coerce signatures to a valid range.\n    const auto maximum = signatures == 0 || signatures > spend_keys_size;\n    const auto coerced = maximum ? static_cast<uint8_t>(spend_keys_size) :\n        signatures;\n\n    // Parameter order is used to change the constructor signature.\n    return{ version, filter, scan_key, spenders, coerced };\n}\n\n// Cast operators.\n// ----------------------------------------------------------------------------\n\nstealth_address::operator const bool() const\n{\n    return valid_;\n}\n\nstealth_address::operator const data_chunk() const\n{\n    return to_chunk();\n}\n\n// Serializer.\n// ----------------------------------------------------------------------------\n\nstd::string stealth_address::encoded() const\n{\n    return encode_base58(to_chunk());\n}\n\nuint8_t stealth_address::version() const\n{\n    return version_;\n}\n\n// Accessors.\n// ----------------------------------------------------------------------------\n\nconst binary& stealth_address::filter() const\n{\n    return filter_;\n}\n\nconst ec_compressed& stealth_address::scan_key() const\n{\n    return scan_key_;\n}\n\nuint8_t stealth_address::signatures() const\n{\n    return signatures_;\n}\n\nconst point_list& stealth_address::spend_keys() const\n{\n    return spend_keys_;\n}\n\n// Methods.\n// ----------------------------------------------------------------------------\n\ndata_chunk stealth_address::to_chunk() const\n{\n    data_chunk address;\n    address.push_back(version());\n    address.push_back(options());\n    extend_data(address, scan_key_);\n\n    // Spend_pubkeys must have been guarded against a max size of 255.\n    auto number_spend_pubkeys = static_cast<uint8_t>(spend_keys_.size());\n\n    // Adjust for key reuse.\n    if (reuse_key())\n        --number_spend_pubkeys;\n\n    address.push_back(number_spend_pubkeys);\n\n    // Serialize the spend keys, excluding any that match the scan key.\n    for (const auto& key : spend_keys_)\n        if (key != scan_key_)\n            extend_data(address, key);\n\n    address.push_back(signatures_);\n\n    // The prefix must be guarded against a size greater than 32\n    // so that the bitfield can convert into uint32_t and sized by uint8_t.\n    const auto prefix_number_bits = static_cast<uint8_t>(filter_.size());\n\n    // Serialize the prefix bytes/blocks.\n    address.push_back(prefix_number_bits);\n    extend_data(address, filter_.blocks());\n\n    append_checksum(address);\n    return address;\n}\n\n\n// Helpers.\n// ----------------------------------------------------------------------------\n\nbool stealth_address::reuse_key() const\n{\n    // If the spend_keys_ contains the scan_key_ then the key is reused.\n    return std::find(spend_keys_.begin(), spend_keys_.end(), scan_key_) !=\n        spend_keys_.end();\n}\n\nuint8_t stealth_address::options() const\n{\n    // There is currently only one option.\n    return reuse_key() ? reuse_key_flag : 0x00;\n}\n\n// Operators.\n// ----------------------------------------------------------------------------\n\nstealth_address& stealth_address::operator=(const stealth_address& other)\n{\n    valid_ = other.valid_;\n    version_ = other.version_;\n    scan_key_ = other.scan_key_;\n    spend_keys_ = other.spend_keys_;\n    signatures_ = other.signatures_;\n    filter_ = other.filter_;\n    return *this;\n}\n\nbool stealth_address::operator<(const stealth_address& other) const\n{\n    return encoded() < other.encoded();\n}\n\nbool stealth_address::operator==(const stealth_address& other) const\n{\n    return valid_ == other.valid_ && version_ == other.version_ &&\n        scan_key_ == other.scan_key_&& spend_keys_ == other.spend_keys_ &&\n        signatures_ == other.signatures_ && filter_ == other.filter_;\n}\n\nbool stealth_address::operator!=(const stealth_address& other) const\n{\n    return !(*this == other);\n}\n\nstd::istream& operator>>(std::istream& in, stealth_address& to)\n{\n    std::string value;\n    in >> value;\n    to = stealth_address(value);\n\n    if (!to)\n    {\n        using namespace boost::program_options;\n        BOOST_THROW_EXCEPTION(invalid_option_value(value));\n    }\n\n    return in;\n}\n\nstd::ostream& operator<<(std::ostream& out, const stealth_address& of)\n{\n    out << of.encoded();\n    return out;\n}\n\n} // namespace wallet\n} // namespace libbitcoin\n", "meta": {"hexsha": "70b0331564d571a437710b57833a467230997ae5", "size": 11179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/libbitcoin/src/wallet/stealth_address.cpp", "max_stars_repo_name": "anatolse/beam", "max_stars_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 631.0, "max_stars_repo_stars_event_min_datetime": "2018-11-10T05:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:21:00.000Z", "max_issues_repo_path": "3rdparty/libbitcoin/src/wallet/stealth_address.cpp", "max_issues_repo_name": "anatolse/beam", "max_issues_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1824.0, "max_issues_repo_issues_event_min_datetime": "2018-11-08T11:32:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T12:33:03.000Z", "max_forks_repo_path": "3rdparty/libbitcoin/src/wallet/stealth_address.cpp", "max_forks_repo_name": "anatolse/beam", "max_forks_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 216.0, "max_forks_repo_forks_event_min_datetime": "2018-11-12T08:07:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T20:50:19.000Z", "avg_line_length": 29.9705093834, "max_line_length": 79, "alphanum_fraction": 0.6816352089, "num_tokens": 2555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.1884894736168679}}
{"text": "#include \"CalibTracker/SiStripLorentzAngle/interface/LA_Filler_Fitter.h\"\n#include \"CalibTracker/SiStripCommon/interface/TTREE_FOREACH_ENTRY.hh\"\n#include \"DataFormats/SiStripDetId/interface/StripSubdetector.h\"\n\n#include <cmath>\n#include <boost/lexical_cast.hpp>\n\nvoid LA_Filler_Fitter::fill(TTree* tree, Book& book) const {\n  TTREE_FOREACH_ENTRY(tree) {\n    TFE_MAX(maxEvents_);\n    TFE_PRINTSTATUS;\n    std::vector<unsigned> PLEAF(tsostrackmulti, tree);\n    std::vector<unsigned> PLEAF(clusterdetid, tree);\n    std::vector<unsigned> PLEAF(clusterwidth, tree);\n    std::vector<float> PLEAF(clustervariance, tree);\n    std::vector<float> PLEAF(tsosdriftx, tree);\n    std::vector<float> PLEAF(tsosdriftz, tree);\n    std::vector<float> PLEAF(tsoslocaltheta, tree);\n    std::vector<float> PLEAF(tsoslocalphi, tree);\n    std::vector<float> PLEAF(tsosglobalZofunitlocalY, tree);\n\n    const unsigned N(clusterdetid.size());\n    std::vector<float> BdotY(N, 0);\n    if (!ensembleBins_) {\n      std::vector<float> PLEAF(tsosBdotY, tree);\n      swap(BdotY, tsosBdotY);\n    }\n    std::vector<float> localy(N, 0);\n    if (localYbin_) {\n      std::vector<float> PLEAF(tsoslocaly, tree);\n      swap(localy, tsoslocaly);\n    }\n    std::vector<unsigned> seedstrip(N, 0);\n    if (stripsPerBin_) {\n      std::vector<unsigned> PLEAF(clusterseedstrip, tree);\n      swap(seedstrip, clusterseedstrip);\n    }\n\n    for (unsigned i = 0; i < N; i++) {\n      const SiStripDetId detid(clusterdetid[i]);\n      if (tsostrackmulti[i] != 1 ||\n          (detid.subDetector() != SiStripDetId::TIB && detid.subDetector() != SiStripDetId::TOB))\n        continue;\n\n      const int sign = tsosglobalZofunitlocalY[i] < 0 ? -1 : 1;\n      const float tthetaL = sign * tsosdriftx[i] / tsosdriftz[i];\n      const float tthetaT = sign * tan(tsoslocaltheta[i]) * cos(tsoslocalphi[i]);\n\n      fill_one_cluster(book,\n                       granularity(detid, tthetaL, TFE_index, localy[i], seedstrip[i] % 128),\n                       clusterwidth[i],\n                       clustervariance[i],\n                       tthetaL,\n                       tthetaT,\n                       fabs(BdotY[i]));\n    }\n  }\n}\n\nvoid LA_Filler_Fitter::fill_one_cluster(Book& book,\n                                        const poly<std::string>& gran,\n                                        const unsigned width,\n                                        const float variance,\n                                        const float tthetaL,\n                                        const float tthetaT,\n                                        const float BdotY) const {\n  book.fill(tthetaL, gran + \"_reconstruction\", 360, -1.0, 1.0);\n  book.fill(tthetaT - tthetaL, gran + allAndOne(width), 360, -1.0, 1.0);\n  book.fill(tthetaT - tthetaL, variance, gran + varWidth(width), 360, -1.0, 1.0);\n  if (methods_ & WIDTH)\n    book.fill(tthetaT, width, gran + method(WIDTH), 81, -0.6, 0.6);\n  if (!ensembleBins_) {\n    book.fill(BdotY, gran + \"_field\", 101, 1, 5);\n    book.fill(width, gran + \"_width\", 10, 0, 10);\n  }\n}\n\npoly<std::string> LA_Filler_Fitter::allAndOne(const unsigned width) const {\n  poly<std::string> a1(\"_all\");\n  if (width == 1)\n    a1 *= \"_w1\";\n  return a1;\n}\n\npoly<std::string> LA_Filler_Fitter::varWidth(const unsigned width) const {\n  poly<std::string> vw;\n  vw++;\n  if (width == 2 && methods_ & (AVGV2 | RMSV2))\n    vw *= method(AVGV2, false);\n  if (width == 3 && methods_ & (AVGV3 | RMSV3))\n    vw *= method(AVGV3, false);\n  return vw;\n}\n\npoly<std::string> LA_Filler_Fitter::granularity(const SiStripDetId detid,\n                                                const float tthetaL,\n                                                const Long64_t TFE_index,\n                                                const float localy,\n                                                const unsigned apvstrip) const {\n  poly<std::string> gran;\n  gran += subdetLabel(detid);\n  if (byLayer_)\n    gran *= layerLabel(detid);\n  if (byModule_)\n    gran *= moduleLabel(detid);\n  if (localYbin_)\n    gran += (localy < 0 ? \"_yM\" : \"_yP\") + std::to_string(abs((int)(localy / localYbin_ + (localy < 0 ? -1 : 0))));\n  if (stripsPerBin_)\n    gran += \"_strip\" +\n            std::to_string(\n                (unsigned)((0.5 + ((apvstrip / 64) ? (127 - apvstrip) : apvstrip) / stripsPerBin_) * stripsPerBin_));\n  if (ensembleBins_) {\n    gran +=\n        \"_ensembleBin\" + std::to_string((int)(ensembleBins_ * (tthetaL - ensembleLow_) / (ensembleUp_ - ensembleLow_)));\n    gran += \"\";\n    if (ensembleSize_)\n      gran *= \"_sample\" + std::to_string(TFE_index % ensembleSize_);\n  }\n  return gran;\n}\n\nstd::string LA_Filler_Fitter::subdetLabel(const SiStripDetId detid) {\n  return detid.subDetector() == SiStripDetId::TOB ? \"TOB\" : \"TIB\";\n}\nstd::string LA_Filler_Fitter::moduleLabel(const SiStripDetId detid) {\n  return subdetLabel(detid) + \"_module\" + std::to_string(detid());\n}\nstd::string LA_Filler_Fitter::layerLabel(const SiStripDetId detid) const {\n  const bool isTIB = detid.subdetId() == StripSubdetector::TIB;\n  unsigned layer = isTIB ? tTopo_->tibLayer(detid) : tTopo_->tobLayer(detid);\n  bool stereo = isTIB ? tTopo_->tibStereo(detid) : tTopo_->tobStereo(detid);\n\n  return subdetLabel(detid) + \"_layer\" + std::to_string(layer) + (stereo ? \"s\" : \"a\");\n}\n", "meta": {"hexsha": "3df58ebbbd3d3dd00bbdfb164c9d339c564fb69e", "size": 5272, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CalibTracker/SiStripLorentzAngle/src/LA_Filler.cc", "max_stars_repo_name": "NTrevisani/cmssw", "max_stars_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-29T13:32:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-31T00:40:58.000Z", "max_issues_repo_path": "CalibTracker/SiStripLorentzAngle/src/LA_Filler.cc", "max_issues_repo_name": "NTrevisani/cmssw", "max_issues_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 26.0, "max_issues_repo_issues_event_min_datetime": "2018-10-30T12:47:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:39:00.000Z", "max_forks_repo_path": "CalibTracker/SiStripLorentzAngle/src/LA_Filler.cc", "max_forks_repo_name": "NTrevisani/cmssw", "max_forks_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-06-07T15:22:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-28T20:48:30.000Z", "avg_line_length": 39.0518518519, "max_line_length": 120, "alphanum_fraction": 0.596168437, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35220178884745906, "lm_q1q2_score": 0.18846262377175696}}
{"text": "#ifndef OSRM_OPENING_HOURS_HPP\n#define OSRM_OPENING_HOURS_HPP\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/spirit/include/qi.hpp>\n\n#include <boost/io/ios_state.hpp>\n\n#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iterator>\n#include <limits>\n#include <string>\n\nnamespace osrm\n{\nnamespace util\n{\n\n// Helper classes for \"opening hours\" format http://wiki.openstreetmap.org/wiki/Key:opening_hours\n// Supported simplified features in CheckOpeningHours:\n// - Year/Month/Day ranges\n// - Weekday ranges\n// - Time ranges\n// Not supported:\n// - Week numbers\n// - Holidays, events, variables dates\n// - Day offsets and periodic ranges\nstruct OpeningHours\n{\n    enum Modifier\n    {\n        unknown,\n        open,\n        closed,\n        off,\n        is24_7\n    };\n\n    struct Time\n    {\n        enum Event : unsigned char\n        {\n            invalid,\n            none,\n            dawn,\n            sunrise,\n            sunset,\n            dusk\n        };\n\n        Event event;\n        std::int32_t minutes;\n\n        Time() : event(invalid), minutes(0) {}\n        Time(Event event) : event(event), minutes(0) {}\n        Time(char hour, char min) : event(none), minutes(hour * 60 + min) {}\n        Time(Event event, bool positive, const Time &offset)\n            : event(event), minutes(positive ? offset.minutes : -offset.minutes)\n        {\n        }\n    };\n\n    struct TimeSpan\n    {\n        Time from, to;\n        TimeSpan() = default;\n        TimeSpan(const Time &from_, const Time &to_) : from(from_), to(to_)\n        {\n            if (to.minutes < from.minutes)\n                to.minutes += 24 * 60;\n        }\n\n        bool IsInRange(const struct tm &time, bool &use_curr_day, bool &use_next_day) const\n        {\n            // TODO: events are not handled\n            if (from.event != OpeningHours::Time::none || to.event != OpeningHours::Time::none)\n                return false;\n\n            const auto minutes = time.tm_hour * 60 + time.tm_min;\n            if (to.minutes > 24 * 60)\n            {\n                use_curr_day = (from.minutes <= minutes); // in range [from, 24:00) current day\n                use_next_day = (minutes < to.minutes - 24 * 60); // in range [00:00, to) next day\n            }\n            else\n            {\n                use_curr_day =\n                    (from.minutes <= minutes && minutes < to.minutes); // in range [from, to)\n                use_next_day = false;                                  // do not use the next day\n            }\n\n            return use_curr_day || use_next_day;\n        }\n    };\n\n    struct WeekdayRange\n    {\n        int weekdays, overnight_weekdays;\n        WeekdayRange() = default;\n        WeekdayRange(unsigned char from, unsigned char to)\n        {\n            // weekdays mask for [from, to], e.g [2, 5] -> 0111100, [5, 2] -> 1100111,\n            //  [3, 3] -> 0001000, [0,6] -> 1111111, [6,0] -> 1000001, [4, 3] -> 1111111\n            weekdays = (from <= to) ? ((1 << (to - from + 1)) - 1) << from\n                                    : ~(((1 << (from - to - 1)) - 1) << (to + 1));\n            weekdays &= 0x7f;\n            overnight_weekdays = (weekdays << 1) | (weekdays & 0x40 ? 1 : 0);\n        }\n\n        bool IsInRange(const struct tm &time, bool use_curr_day, bool use_next_day) const\n        {\n            return (use_curr_day && weekdays & (1 << time.tm_wday)) ||\n                   (use_next_day && overnight_weekdays & (1 << time.tm_wday));\n        }\n    };\n\n    struct Monthday\n    {\n        int year;\n        char month;\n        char day;\n        Monthday() = default;\n        Monthday(int year) : year(year), month(0), day(0) {}\n        Monthday(int year, char month, char day) : year(year), month(month), day(day) {}\n\n        bool IsValid() const { return year > 0 || month != 0 || day != 0; }\n        bool operator==(const Monthday &rhs) const\n        {\n            return std::tie(year, month, day) == std::tie(rhs.year, rhs.month, rhs.day);\n        }\n    };\n\n    struct MonthdayRange\n    {\n        Monthday from, to;\n        MonthdayRange() : from(0, 0, 0), to(0, 0, 0) {}\n        MonthdayRange(const Monthday &from, const Monthday &to) : from(from), to(to) {}\n\n        bool IsInRange(const struct tm &time, bool use_curr_day, bool use_next_day) const\n        {\n            using boost::gregorian::date;\n            using boost::gregorian::date_duration;\n\n            const auto year = time.tm_year + 1900;\n            const auto month = time.tm_mon + 1;\n\n            date date_current(year, month, time.tm_mday);\n            date date_from(boost::gregorian::min_date_time);\n            date date_to(boost::gregorian::max_date_time);\n\n            if (from.IsValid())\n            {\n                date_from = (from.day == 0) ? date(from.year == 0 ? year : from.year,\n                                                   from.month == 0 ? month : from.month,\n                                                   1)\n                                            : date(from.year == 0 ? year : from.year,\n                                                   from.month == 0 ? month : from.month,\n                                                   from.day);\n            }\n            if (to.IsValid())\n            {\n                date_to = date(to.year == 0 ? (from.year == 0 ? year : from.year) : to.year,\n                               to.month == 0 ? (from.month == 0 ? month : from.month) : to.month,\n                               1);\n                date_to = (to.day == 0) ? date_to.end_of_month()\n                                        : date(date_to.year(), date_to.month(), to.day);\n            }\n            else if (to == Monthday())\n            {\n                date_to = date_from;\n            }\n\n            if (!use_curr_day)\n                date_from += date_duration(1);\n            if (use_next_day && date_to != date(boost::gregorian::max_date_time))\n                date_to += date_duration(1);\n\n            return date_from <= date_current && date_current <= date_to;\n        }\n    };\n\n    OpeningHours() : modifier(open) {}\n\n    bool IsInRange(const struct tm &time) const\n    {\n        bool use_curr_day = true;  // the first matching time uses the current day\n        bool use_next_day = false; // the first matching time uses the next day\n        return\n            // the value is in range if time is not specified or is in any time range\n            // (also modifies use_curr_day and use_next_day flags to handle overnight day ranges,\n            // e.g. for 22:00-03:00 and 2am -> use_curr_day = false and use_next_day = true)\n            (times.empty() || std::any_of(times.begin(),\n                                          times.end(),\n                                          [&time, &use_curr_day, &use_next_day](const auto &x) {\n                                              return x.IsInRange(time, use_curr_day, use_next_day);\n                                          }))\n            // .. and if weekdays are not specified or matches weekdays range\n            && (weekdays.empty() ||\n                std::any_of(weekdays.begin(),\n                            weekdays.end(),\n                            [&time, use_curr_day, use_next_day](const auto &x) {\n                                return x.IsInRange(time, use_curr_day, use_next_day);\n                            }))\n            // .. and if month-day ranges are not specified or is in any month-day range\n            && (monthdays.empty() ||\n                std::any_of(monthdays.begin(),\n                            monthdays.end(),\n                            [&time, use_curr_day, use_next_day](const auto &x) {\n                                return x.IsInRange(time, use_curr_day, use_next_day);\n                            }));\n    }\n\n    std::vector<TimeSpan> times;\n    std::vector<WeekdayRange> weekdays;\n    std::vector<MonthdayRange> monthdays;\n    Modifier modifier;\n};\n\n#ifndef NDEBUG\n// Debug output stream operators for use with BOOST_SPIRIT_DEBUG\ninline std::ostream &operator<<(std::ostream &stream, const OpeningHours::Modifier value)\n{\n    switch (value)\n    {\n    case OpeningHours::unknown:\n        return stream << \"unknown\";\n    case OpeningHours::open:\n        return stream << \"open\";\n    case OpeningHours::closed:\n        return stream << \"closed\";\n    case OpeningHours::off:\n        return stream << \"off\";\n    case OpeningHours::is24_7:\n        return stream << \"24/7\";\n    }\n    return stream;\n}\n\ninline std::ostream &operator<<(std::ostream &stream, const OpeningHours::Time::Event value)\n{\n    switch (value)\n    {\n    case OpeningHours::Time::dawn:\n        return stream << \"dawn\";\n    case OpeningHours::Time::sunrise:\n        return stream << \"sunrise\";\n    case OpeningHours::Time::sunset:\n        return stream << \"sunset\";\n    case OpeningHours::Time::dusk:\n        return stream << \"dusk\";\n    default:\n        break;\n    }\n    return stream;\n}\n\ninline std::ostream &operator<<(std::ostream &stream, const OpeningHours::Time &value)\n{\n    boost::io::ios_flags_saver ifs(stream);\n    if (value.event == OpeningHours::Time::invalid)\n        return stream << \"???\";\n    if (value.event == OpeningHours::Time::none)\n        return stream << std::setfill('0') << std::setw(2) << value.minutes / 60 << \":\"\n                      << std::setfill('0') << std::setw(2) << value.minutes % 60;\n    stream << value.event;\n    if (value.minutes != 0)\n        stream << value.minutes;\n    return stream;\n}\n\ninline std::ostream &operator<<(std::ostream &stream, const OpeningHours::TimeSpan &value)\n{\n    return stream << value.from << \"-\" << value.to;\n}\n\ninline std::ostream &operator<<(std::ostream &stream, const OpeningHours::Monthday &value)\n{\n    bool empty = true;\n    if (value.year != 0)\n    {\n        stream << (int)value.year;\n        empty = false;\n    };\n    if (value.month != 0)\n    {\n        stream << (empty ? \"\" : \"/\") << (int)value.month;\n        empty = false;\n    };\n    if (value.day != 0)\n    {\n        stream << (empty ? \"\" : \"/\") << (int)value.day;\n    };\n    return stream;\n}\n\ninline std::ostream &operator<<(std::ostream &stream, const OpeningHours::WeekdayRange &value)\n{\n    boost::io::ios_flags_saver ifs(stream);\n    return stream << std::hex << std::setfill('0') << std::setw(2) << value.weekdays;\n}\n\ninline std::ostream &operator<<(std::ostream &stream, const OpeningHours::MonthdayRange &value)\n{\n    return stream << value.from << \"-\" << value.to;\n}\n\ninline std::ostream &operator<<(std::ostream &stream, const OpeningHours &value)\n{\n    if (value.modifier == OpeningHours::is24_7)\n        return stream << OpeningHours::is24_7;\n\n    for (auto x : value.monthdays)\n        stream << x << \", \";\n    for (auto x : value.weekdays)\n        stream << x << \", \";\n    for (auto x : value.times)\n        stream << x << \", \";\n    return stream << \" |\" << value.modifier << \"|\";\n}\n#endif\n\nnamespace detail\n{\n\nnamespace\n{\nnamespace ph = boost::phoenix;\nnamespace qi = boost::spirit::qi;\n}\n\ntemplate <typename Iterator, typename Skipper = qi::blank_type>\nstruct opening_hours_grammar : qi::grammar<Iterator, Skipper, std::vector<OpeningHours>()>\n{\n    // http://wiki.openstreetmap.org/wiki/Key:opening_hours/specification\n    opening_hours_grammar() : opening_hours_grammar::base_type(time_domain)\n    {\n        using qi::_1;\n        using qi::_a;\n        using qi::_b;\n        using qi::_c;\n        using qi::_r1;\n        using qi::_pass;\n        using qi::_val;\n        using qi::eoi;\n        using qi::lit;\n        using qi::char_;\n        using qi::uint_;\n        using oh = osrm::util::OpeningHours;\n\n        // clang-format off\n\n        // General syntax\n        time_domain = rule_sequence[ph::push_back(_val, _1)] % any_rule_separator;\n\n        rule_sequence\n            = lit(\"24/7\")[ph::bind(&oh::modifier, _val) = oh::is24_7]\n            | (selector_sequence[_val = _1] >> -rule_modifier[ph::bind(&oh::modifier, _val) = _1] >> -comment)\n            | comment\n            ;\n\n        any_rule_separator = char_(';') | lit(\"||\") | additional_rule_separator;\n\n        additional_rule_separator = char_(',');\n\n        // Rule modifiers\n        rule_modifier.add\n            (\"unknown\", oh::unknown)\n            (\"open\", oh::open)\n            (\"closed\", oh::closed)\n            (\"off\", oh::off)\n            ;\n\n        // Selectors\n        selector_sequence = (wide_range_selectors(_a) >> small_range_selectors(_a))[_val = _a];\n\n        wide_range_selectors\n            = (-monthday_selector(_r1)\n               >> -year_selector(_r1)\n               >> -week_selector(_r1) // TODO week_selector\n              ) >> -lit(':')\n            ;\n\n        small_range_selectors = -(weekday_selector(_r1) >> (&~lit(',') | eoi)) >> -time_selector(_r1);\n\n        // Time selector\n        time_selector = (timespan % ',')[ph::bind(&OpeningHours::times, _r1) = _1];\n\n        timespan\n            = (time[_a = _1]\n               >> -(lit('+')[_b = ph::construct<OpeningHours::Time>(24, 0)]\n                    | ('-' >> extended_time[_b = _1]\n                       >> -('+' | '/' >> (minute | hour_minutes))))\n               )[_val = ph::construct<OpeningHours::TimeSpan>(_a, _b)]\n            ;\n\n        time = hour_minutes | variable_time;\n\n        extended_time = extended_hour_minutes | variable_time;\n\n        variable_time\n            = event[_val = ph::construct<OpeningHours::Time>(_1)]\n            | ('(' >> event[_a = _1] >> plus_or_minus[_b = _1] >> hour_minutes[_c = _1] >> ')')\n            [_val = ph::construct<OpeningHours::Time>(_a, _b, _c)]\n            ;\n\n        event.add\n            (\"dawn\", OpeningHours::Time::dawn)\n            (\"sunrise\", OpeningHours::Time::sunrise)\n            (\"sunset\", OpeningHours::Time::sunset)\n            (\"dusk\", OpeningHours::Time::dusk)\n            ;\n\n        // Weekday selector\n        weekday_selector\n            = (holiday_sequence(_r1) >> -(char_(\", \") >> weekday_sequence(_r1)))\n            | (weekday_sequence(_r1) >> -(char_(\", \") >> holiday_sequence(_r1)))\n            ;\n\n        weekday_sequence = (weekday_range % ',')[ph::bind(&OpeningHours::weekdays, _r1) = _1];\n\n        weekday_range\n            = wday[_a = _1, _b = _1]\n            >> -(('-' >> wday[_b = _1])\n                 | ('[' >> (nth_entry % ',') >> ']' >> -day_offset))\n            [_val = ph::construct<OpeningHours::WeekdayRange>(_a, _b)]\n            ;\n\n        holiday_sequence = (lit(\"SH\") >> -day_offset) | lit(\"PH\");\n\n        nth_entry = nth | nth >> '-' >> nth | '-' >> nth;\n\n        nth = char_(\"12345\");\n\n        day_offset = plus_or_minus >> uint_ >> lit(\"days\");\n\n        // Week selector\n        week_selector = (lit(\"week \") >> week) % ',';\n\n        week = weeknum >> -('-' >> weeknum >> -('/' >> uint_));\n\n        // Month selector\n        monthday_selector = (monthday_range % ',')[ph::bind(&OpeningHours::monthdays, _r1) = _1];\n\n        monthday_range\n            = (date_from[ph::bind(&OpeningHours::MonthdayRange::from, _val) = _1]\n               >> -date_offset\n               >> '-'\n               >> date_to[ph::bind(&OpeningHours::MonthdayRange::to, _val) = _1]\n               >> -date_offset)\n            | (date_from[ph::bind(&OpeningHours::MonthdayRange::from, _val) = _1]\n               >> -(date_offset\n                    >> -lit('+')[ph::bind(&OpeningHours::MonthdayRange::from, _val) = ph::construct<OpeningHours::Monthday>(-1)]\n                    ))\n            ;\n\n        date_offset = (plus_or_minus >> wday) | day_offset;\n\n        date_from\n            = ((-year[_a = _1] >> ((month[_b = _1] >> -daynum[_c = _1]) | daynum[_c = _1]))\n               | variable_date)\n            [_val = ph::construct<OpeningHours::Monthday>(_a, _b, _c)]\n            ;\n\n        date_to\n            = date_from[_val = _1]\n            | daynum[_val = ph::construct<OpeningHours::Monthday>(0, 0, _1)]\n            ;\n\n        variable_date = lit(\"easter\");\n\n        // Year selector\n        year_selector = (year_range % ',')[ph::bind(&OpeningHours::monthdays, _r1) = _1];\n\n        year_range\n            = year[ph::bind(&OpeningHours::MonthdayRange::from, _val) = ph::construct<OpeningHours::Monthday>(_1)]\n            >> -(('-' >> year[ph::bind(&OpeningHours::MonthdayRange::to, _val) = ph::construct<OpeningHours::Monthday>(_1)]\n                  >> -('/' >> uint_))\n                 | lit('+')[ph::bind(&OpeningHours::MonthdayRange::to, _val) = ph::construct<OpeningHours::Monthday>(-1)]);\n\n        // Basic elements\n        plus_or_minus = lit('+')[_val = true] | lit('-')[_val = false];\n\n        hour = uint2_p[_pass = bind([](unsigned x) { return x <= 24; }, _1), _val = _1];\n\n        extended_hour = uint2_p[_pass = bind([](unsigned x) { return x <= 48; }, _1), _val = _1];\n\n        minute = uint2_p[_pass = bind([](unsigned x) { return x < 60; }, _1), _val = _1];\n\n        hour_minutes =\n            hour[_a = _1] >> ':' >> minute[_val = ph::construct<OpeningHours::Time>(_a, _1)];\n\n        extended_hour_minutes = extended_hour[_a = _1] >> ':' >>\n                                minute[_val = ph::construct<OpeningHours::Time>(_a, _1)];\n\n        wday.add\n            (\"Su\", 0)\n            (\"Mo\", 1)\n            (\"Tu\", 2)\n            (\"We\", 3)\n            (\"Th\", 4)\n            (\"Fr\", 5)\n            (\"Sa\", 6)\n            ;\n\n        daynum\n            = uint2_p[_pass = bind([](unsigned x) { return 01 <= x && x <= 31; }, _1), _val = _1]\n            >> (&~lit(':') | eoi)\n            ;\n\n        weeknum = uint2_p[_pass = bind([](unsigned x) { return 01 <= x && x <= 53; }, _1), _val = _1];\n\n        month.add\n            (\"Jan\", 1)\n            (\"Feb\", 2)\n            (\"Mar\", 3)\n            (\"Apr\", 4)\n            (\"May\", 5)\n            (\"Jun\", 6)\n            (\"Jul\", 7)\n            (\"Aug\", 8)\n            (\"Sep\", 9)\n            (\"Oct\", 10)\n            (\"Nov\", 11)\n            (\"Dec\", 12)\n            ;\n\n        year = uint4_p[_pass = bind([](unsigned x) { return x > 1900; }, _1), _val = _1];\n\n        comment = lit('\"') >> *(~qi::char_('\"')) >> lit('\"');\n\n        // clang-format on\n\n        BOOST_SPIRIT_DEBUG_NODES((time_domain)(rule_sequence)(any_rule_separator)(\n            selector_sequence)(wide_range_selectors)(small_range_selectors)(time_selector)(\n            timespan)(time)(extended_time)(variable_time)(weekday_selector)(weekday_sequence)(\n            weekday_range)(holiday_sequence)(nth_entry)(nth)(day_offset)(week_selector)(week)(\n            monthday_selector)(monthday_range)(date_offset)(date_from)(date_to)(variable_date)(\n            year_selector)(year_range)(plus_or_minus)(hour_minutes)(extended_hour_minutes)(comment)(\n            hour)(extended_hour)(minute)(daynum)(weeknum)(year));\n    }\n\n    qi::rule<Iterator, Skipper, std::vector<OpeningHours>()> time_domain;\n    qi::rule<Iterator, Skipper, OpeningHours()> rule_sequence;\n    qi::rule<Iterator, Skipper, void()> any_rule_separator, additional_rule_separator;\n    qi::rule<Iterator, Skipper, OpeningHours(), qi::locals<OpeningHours>> selector_sequence;\n    qi::symbols<char const, OpeningHours::Modifier> rule_modifier;\n    qi::rule<Iterator, Skipper, void(OpeningHours &)> wide_range_selectors, small_range_selectors,\n        time_selector, weekday_selector, year_selector, monthday_selector, week_selector;\n\n    // Time rules\n    qi::rule<Iterator,\n             Skipper,\n             OpeningHours::TimeSpan(),\n             qi::locals<OpeningHours::Time, OpeningHours::Time>>\n        timespan;\n\n    qi::rule<Iterator, Skipper, OpeningHours::Time()> time, extended_time;\n\n    qi::rule<Iterator,\n             Skipper,\n             OpeningHours::Time(),\n             qi::locals<OpeningHours::Time::Event, bool, OpeningHours::Time>>\n        variable_time;\n\n    qi::rule<Iterator, Skipper, OpeningHours::Time(), qi::locals<unsigned>> hour_minutes,\n        extended_hour_minutes;\n\n    qi::symbols<char const, OpeningHours::Time::Event> event;\n\n    qi::rule<Iterator, Skipper, bool()> plus_or_minus;\n\n    // Weekday rules\n    qi::rule<Iterator, Skipper, void(OpeningHours &)> weekday_sequence, holiday_sequence;\n\n    qi::rule<Iterator,\n             Skipper,\n             OpeningHours::WeekdayRange(),\n             qi::locals<unsigned char, unsigned char>>\n        weekday_range;\n\n    // Monthday rules\n    qi::rule<Iterator, Skipper, OpeningHours::MonthdayRange()> monthday_range;\n\n    qi::rule<Iterator, Skipper, OpeningHours::Monthday(), qi::locals<unsigned, unsigned, unsigned>>\n        date_from;\n\n    qi::rule<Iterator, Skipper, OpeningHours::Monthday()> date_to;\n\n    // Year rules\n    qi::rule<Iterator, Skipper, OpeningHours::MonthdayRange()> year_range;\n\n    // Unused rules\n    qi::rule<Iterator, Skipper, void()> nth_entry, nth, day_offset, week, date_offset,\n        variable_date, comment;\n\n    // Basic rules and parsers\n    qi::rule<Iterator, Skipper, unsigned()> hour, extended_hour, minute, daynum, weeknum, year;\n    qi::symbols<char const, unsigned char> wday, month;\n    qi::uint_parser<unsigned, 10, 2, 2> uint2_p;\n    qi::uint_parser<unsigned, 10, 4, 4> uint4_p;\n};\n}\n\ninline std::vector<OpeningHours> ParseOpeningHours(const std::string &str)\n{\n    auto it(str.begin()), end(str.end());\n    const detail::opening_hours_grammar<decltype(it)> static grammar;\n\n    std::vector<OpeningHours> result;\n    bool ok = boost::spirit::qi::phrase_parse(it, end, grammar, boost::spirit::qi::blank, result);\n\n    if (!ok || it != end)\n        return std::vector<OpeningHours>();\n\n    return result;\n}\n\ninline bool CheckOpeningHours(const std::vector<OpeningHours> &input, const struct tm &time)\n{\n    bool is_open = false;\n    for (auto &opening_hours : input)\n    {\n        if (opening_hours.modifier == OpeningHours::is24_7)\n            return true;\n\n        if (opening_hours.IsInRange(time))\n        {\n            is_open = opening_hours.modifier == OpeningHours::open;\n        }\n    }\n\n    return is_open;\n}\n\n} // util\n} // osrm\n\n#endif // OSRM_OPENING_HOURS_HPP\n", "meta": {"hexsha": "618dc73635d7d2016f98c6e9cc977ea4dc2608c9", "size": 21906, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/deps/osrm/include/util/opening_hours.hpp", "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/deps/osrm/include/util/opening_hours.hpp", "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/deps/osrm/include/util/opening_hours.hpp", "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": 34.1214953271, "max_line_length": 128, "alphanum_fraction": 0.5385739067, "num_tokens": 5474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.18846262218784124}}
{"text": "//   Copyright 2015 Patrick Putnam\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 CLOTHO_COMMON_CROSSOVER_HPP_\n#define CLOTHO_COMMON_CROSSOVER_HPP_\n\n#include \"clotho/data_spaces/population_space/population_space_row.hpp\"\n#include <boost/random/bernoulli_distribution.hpp>\n#include \"clotho/data_spaces/crossover/position_classifier.hpp\"\n#include \"clotho/data_spaces/generators/position_distribution_helper.hpp\"\n#include \"clotho/data_spaces/generators/crossover_event_distribution_helper.hpp\"\n\n#include \"clotho/data_spaces/crossover/block_crossover_method.hpp\"\n\nnamespace clotho {\nnamespace genetics {\n\ntemplate < class RNG, class PopulationType, class AlleleType >\nclass common_crossover;\n\ntemplate < class RNG, class BlockType, class WeightType, class AlleleType >\nclass common_crossover< RNG, population_space_row< BlockType, WeightType >, AlleleType >  {\npublic:\n    typedef RNG random_engine_type;\n\n    typedef population_space_row< BlockType, WeightType >       space_type;\n    typedef typename space_type::genome_pointer                 genome_pointer;\n    typedef AlleleType allele_type;\n\n    typedef PositionClassifier< typename allele_type::position_vector > classifier_type;\n    typedef typename classifier_type::event_type                        event_type;\n\n    typedef block_crossover_method< classifier_type, BlockType >     method_type;\n\n    typedef typename position_distribution_helper< typename allele_type::position_type >::type  position_distribution_type;\n    typedef typename crossover_event_distribution_helper< double >::type                    event_distribution_type;\n\n    common_crossover( random_engine_type * rng, allele_type * alleles, double recomb_rate, double bias_rate ) : \n        m_rng( rng )\n        , m_alleles( alleles )\n        , m_event_dist(recomb_rate)\n        , m_bias_dist( bias_rate )\n    { }\n\n    void operator()( genome_pointer p0_start, genome_pointer p0_end, genome_pointer p1_start, genome_pointer p1_end, genome_pointer offspring, genome_pointer offspring_end ) {\n        event_type evts;\n        fill_events( evts, m_event_dist(*m_rng));\n        classifier_type cfier0( &m_alleles->getPositions(), evts );\n\n        run_crossover_task( cfier0, p0_start, p0_end, p1_start, p1_end, offspring, offspring_end, m_bias_dist(*m_rng));\n    }\n\n    virtual ~common_crossover() {}\n\nprotected:\n\n    void fill_events( event_type & evt, unsigned int N ) {\n        while( N-- ) {\n            evt.push_back( m_pos_dist( *m_rng ) );\n        }\n    }\n\n    void run_crossover_task( const classifier_type & cls, genome_pointer p0_start, genome_pointer p0_end, genome_pointer p1_start, genome_pointer p1_end, genome_pointer offspring, genome_pointer offspring_end, bool should_swap_strands ) {\n        if( cls.event_count() == 0 ) {\n            genome_pointer first = p0_start, last = p0_end;\n            if( should_swap_strands ) {\n                first = p1_start;\n                last = p1_end;\n            }\n\n            while( first != last ) {\n                *offspring++ = *first++;\n            }\n\n            while( offspring != offspring_end ) {\n                *offspring++ = method_type::bit_helper_type::ALL_UNSET;\n            }\n        } else if( should_swap_strands ) {\n            method_type met(cls);\n            met( p1_start, p1_end, p0_start, p0_end, offspring, offspring_end);\n        } else {\n            method_type met(cls);\n            met( p0_start, p0_end, p1_start, p1_end, offspring, offspring_end);\n        }   \n    }\n\n    random_engine_type          * m_rng;\n    allele_type                 * m_alleles;\n    event_distribution_type     m_event_dist;\n    boost::random::bernoulli_distribution< double > m_bias_dist;\n    position_distribution_type m_pos_dist;\n};\n\n}   // namespace genetics\n}   // namespace clotho\n\n#endif  // CLOTHO_COMMON_CROSSOVER_HPP_\n", "meta": {"hexsha": "ecc796bf63e19deb811cf43b41e0053199cf371e", "size": 4351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clotho/data_spaces/crossover/common_crossover_row_block.hpp", "max_stars_repo_name": "putnampp/clotho", "max_stars_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T21:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:26:54.000Z", "max_issues_repo_path": "include/clotho/data_spaces/crossover/common_crossover_row_block.hpp", "max_issues_repo_name": "putnampp/clotho", "max_issues_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T21:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-23T12:41:00.000Z", "max_forks_repo_path": "include/clotho/data_spaces/crossover/common_crossover_row_block.hpp", "max_forks_repo_name": "putnampp/clotho", "max_forks_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "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": 40.287037037, "max_line_length": 238, "alphanum_fraction": 0.6970811308, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18846261807879464}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.\n// Copyright (c) 2013-2014 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2013-2020.\n// Modifications copyright (c) 2013-2020, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\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_ALGORITHMS_DETAIL_DISJOINT_AREAL_AREAL_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISJOINT_AREAL_AREAL_HPP\n\n#include <boost/geometry/core/point_type.hpp>\n\n#include <boost/geometry/algorithms/covered_by.hpp>\n#include <boost/geometry/algorithms/detail/for_each_range.hpp>\n#include <boost/geometry/algorithms/detail/point_on_border.hpp>\n\n#include <boost/geometry/algorithms/detail/disjoint/linear_linear.hpp>\n#include <boost/geometry/algorithms/detail/disjoint/segment_box.hpp>\n\n#include <boost/geometry/algorithms/for_each.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace disjoint\n{\n\ntemplate <typename Geometry1, typename Geometry2, typename Strategy>\ninline bool point_on_border_covered_by(Geometry1 const& geometry1,\n                                       Geometry2 const& geometry2,\n                                       Strategy const& strategy)\n{\n    typename geometry::point_type<Geometry1>::type pt;\n    return geometry::point_on_border(pt, geometry1)\n        && geometry::covered_by(pt, geometry2, strategy);\n}\n\n\n/*!\n\\tparam Strategy point_in_geometry strategy\n*/\ntemplate <typename Geometry1, typename Geometry2, typename Strategy>\ninline bool rings_containing(Geometry1 const& geometry1,\n                             Geometry2 const& geometry2,\n                             Strategy const& strategy)\n{\n    return geometry::detail::any_range_of(geometry2, [&](auto const& range)\n    {\n        return point_on_border_covered_by(range, geometry1, strategy);\n    });\n}\n\n\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct areal_areal\n{\n    /*!\n    \\tparam Strategy relate (segments intersection) strategy\n    */\n    template <typename Strategy>\n    static inline bool apply(Geometry1 const& geometry1,\n                             Geometry2 const& geometry2,\n                             Strategy const& strategy)\n    {\n        if ( ! disjoint_linear<Geometry1, Geometry2>::apply(geometry1, geometry2, strategy) )\n        {\n            return false;\n        }\n\n        // If there is no intersection of segments, they might located\n        // inside each other\n\n        // We check that using a point on the border (external boundary),\n        // and see if that is contained in the other geometry. And vice versa.\n\n        if ( rings_containing(geometry1, geometry2, strategy)\n          || rings_containing(geometry2, geometry1, strategy) )\n        {\n            return false;\n        }\n\n        return true;\n    }\n};\n\n\ntemplate <typename Areal, typename Box>\nstruct areal_box\n{\n    /*!\n    \\tparam Strategy relate (segments intersection) strategy\n    */\n    template <typename Strategy>\n    static inline bool apply(Areal const& areal,\n                             Box const& box,\n                             Strategy const& strategy)\n    {\n        if (! geometry::all_segments_of(areal, [&](auto const& s)\n              {\n                  return disjoint_segment_box::apply(s, box, strategy);\n              }) )\n        {\n            return false;\n        }\n\n        // If there is no intersection of any segment and box,\n        // the box might be located inside areal geometry\n\n        if ( point_on_border_covered_by(box, areal, strategy) )\n        {\n            return false;\n        }\n\n        return true;\n    }\n};\n\n\n}} // namespace detail::disjoint\n#endif // DOXYGEN_NO_DETAIL\n\n\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\ntemplate <typename Areal1, typename Areal2>\nstruct disjoint<Areal1, Areal2, 2, areal_tag, areal_tag, false>\n    : detail::disjoint::areal_areal<Areal1, Areal2>\n{};\n\n\ntemplate <typename Areal, typename Box>\nstruct disjoint<Areal, Box, 2, areal_tag, box_tag, false>\n    : detail::disjoint::areal_box<Areal, Box>\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISJOINT_AREAL_AREAL_HPP\n", "meta": {"hexsha": "934f90c87500fca2ac182b37c01004ef6802c27c", "size": 4818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/disjoint/areal_areal.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/disjoint/areal_areal.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/disjoint/areal_areal.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": 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.8502994012, "max_line_length": 93, "alphanum_fraction": 0.6760066418, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18846261491096364}}
{"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     gateway_utils.cpp\n * \\author   Collin Johnson\n *\n * Definition of utility functions for constructing gateways:\n *\n *   - are_gateways_intersecting\n *   - are_gatway_angle_close\n *   - is_gateway_untraversable\n *   - select_straightest_gateway_boundary\n */\n\n#include \"hssh/local_topological/area_detection/gateways/gateway_utils.h\"\n#include \"hssh/local_topological/area_detection/gateways/endpoint_validator.h\"\n#include \"hssh/local_topological/area_detection/local_topo_isovist_field.h\"\n#include \"hssh/local_topological/area_detection/voronoi/voronoi_utils.h\"\n#include \"hssh/local_topological/gateway.h\"\n#include \"hssh/local_topological/voronoi_skeleton_grid.h\"\n#include \"utils/algorithm_ext.h\"\n#include \"utils/ray_tracing.h\"\n#include <array>\n#include <boost/range/iterator_range.hpp>\n\nnamespace vulcan\n{\nnamespace hssh\n{\n\nconst uint8_t kValidEndpointMask = SKELETON_CELL_OCCUPIED | SKELETON_CELL_FRONTIER;\nconst uint8_t kValidCenterMask = SKELETON_CELL_REDUCED_SKELETON;\n\n\ncell_t skeleton_cell_between_endpoints(const Line<int>& cellBoundary, const VoronoiSkeletonGrid& grid);\ncell_t nearest_valid_location(cell_t start, int searchRadius, uint8_t validMask, const VoronoiSkeletonGrid& grid);\n\n\nbool are_gateways_intersecting(const Gateway& lhs, const Gateway& rhs)\n{\n    Point<int> intersection;\n\n    return lhs.intersectsWithCellBoundary(rhs.cellBoundary(), intersection);\n}\n\n\nbool are_gateway_angles_close(const Gateway& lhs,\n                              const Gateway& rhs,\n                              double closeAngleThreshold,\n                              double endpointDistanceThreshold)\n{\n    // Arrange the gateways so their closest endpoints are in the 0 index of an array, which allows the calculated angle\n    // for each to show if they are really pointing the same direction or not.\n    auto lhsBoundary = lhs.boundary();\n    auto rhsBoundary = rhs.boundary();\n\n    std::array<Point<double>, 2> lhsEnds = {{lhsBoundary.a, lhsBoundary.b}};\n    std::array<Point<double>, 2> rhsEnds = {{rhsBoundary.a, rhsBoundary.b}};\n\n    int closestLhsIndex = 0;\n    int closestRhsIndex = 0;\n    float minDistance = 10000000000.0f;\n\n    for (int n = 0; n < 2; ++n) {\n        for (int i = 0; i < 2; ++i) {\n            float endpointDistance = distance_between_points(lhsEnds[n], rhsEnds[i]);\n            if (endpointDistance < minDistance) {\n                minDistance = endpointDistance;\n                closestLhsIndex = n;\n                closestRhsIndex = i;\n            }\n        }\n    }\n\n    if (closestLhsIndex != 0) {\n        std::swap(lhsEnds[0], lhsEnds[1]);\n    }\n\n    if (closestRhsIndex != 0) {\n        std::swap(rhsEnds[0], rhsEnds[1]);\n    }\n\n    bool areAnglesClose =\n      std::abs(angle_diff(angle_to_point(lhsEnds[0], lhsEnds[1]), angle_to_point(rhsEnds[0], rhsEnds[1])))\n      < closeAngleThreshold;\n    bool areEndpointsClose = minDistance < endpointDistanceThreshold;\n\n    return areAnglesClose && areEndpointsClose;\n}\n\n\nbool is_gateway_traversable(const Gateway& gateway, double robotLength, const VoronoiSkeletonGrid& skeleton)\n{\n    // Trace through the skeleton from the gateway cell. Go up to lengthInCells, as anything over that length isn't\n    // needed. Go through as many branches as needed -- can't go through more than lengthInCells, so that's sufficient\n    // Need to follow the full skeleton because a dead end might not cram in the back of a partially seen office\n    std::size_t lengthInCells = robotLength * skeleton.cellsPerMeter();\n    auto traces = trace_voronoi_graph(gateway.skeletonCell(), skeleton, lengthInCells, lengthInCells, false);\n\n    // Find the longest trace for each side of the gateway\n    CellToTypeMap<std::size_t> cellToMaxLength;\n    for (auto& t : traces.traces) {\n        if (t.points.size() > 1) {\n            if (cellToMaxLength.find(t.points[1]) != cellToMaxLength.end()) {\n                cellToMaxLength[t.points[1]] = std::max(cellToMaxLength[t.points[1]], t.points.size());\n            } else {\n                cellToMaxLength[t.points[1]] = t.points.size();\n            }\n        }\n    }\n\n    // See how many lengths along the reduced skeleton are long enough. Gateways can't exist at reduced junctions, but\n    // can be at full skeleton junctions, so only check the reduced skeleton branches to see if they are long enough.\n    int numLongEnough = 0;\n    for (auto lengths : cellToMaxLength) {\n        if ((skeleton.getClassification(lengths.first.x, lengths.first.y) & SKELETON_CELL_REDUCED_SKELETON)\n            && (lengths.second == lengthInCells)) {\n            ++numLongEnough;\n        }\n    }\n\n    // Both branches of the reduced skeleton need to be long enough\n    return numLongEnough == 2;\n}\n\n\nvoid gateway_boundary_cells(const Gateway& gateway, const VoronoiSkeletonGrid& grid, CellVector& boundaryCells)\n{\n    auto center = gateway.skeletonCell();\n    auto boundary = gateway.cellBoundary();\n    auto deltaA = boundary.a - center;\n    auto deltaB = boundary.b - center;\n\n    // Start all endpoints slightly inside the associated cell, which helps keep truncation\n    // errors in the ray trace from causing the gateway to fall in the wrong cell\n    Point<double> adjustedCenter(center.x + 0.01, center.y + 0.01);\n\n    auto boundaryA =\n      Line<double>(adjustedCenter, Point<double>(adjustedCenter.x + deltaA.x, adjustedCenter.y + deltaA.y));\n    auto boundaryB =\n      Line<double>(adjustedCenter, Point<double>(adjustedCenter.x + deltaB.x, adjustedCenter.y + deltaB.y));\n\n    // Trace along the gateway boundary to get all cells it passes through\n    utils::find_cells_along_line(boundaryA, grid, std::back_inserter(boundaryCells));\n    utils::find_cells_along_line(boundaryB, grid, std::back_inserter(boundaryCells));\n\n    utils::erase_unique(boundaryCells);\n}\n\n\nfloat gateway_cell_perimeter(const Gateway& gateway, float metersPerCell)\n{\n    // Iterate along the boundary. If a cell is four-way connected, then it adds 1 to perim. If 8-way connected,\n    // it adds 2\n\n    if (gateway.sizeCells() == 1) {\n        return metersPerCell;\n    }\n\n    return cell_vector_perimeter(gateway.beginCells(), gateway.endCells(), metersPerCell);\n}\n\n\ndouble gateway_normal_from_source_cells(cell_t cell, const VoronoiSkeletonGrid& skeleton)\n{\n    double maxAngle = 0.0;\n    double maxNormal = 0.0;\n\n    auto sources = skeleton.getSourceCells(cell.x, cell.y);\n\n    for (std::size_t n = 0; n < sources.size(); ++n) {\n        for (std::size_t m = n + 1; m < sources.size(); ++m) {\n            // Angular separation is relative to the skeleton cell\n            double angleBetweenSources = std::abs(angle_between_points(sources[n], sources[m], cell));\n            if (angleBetweenSources > maxAngle) {\n                maxAngle = angleBetweenSources;\n                maxNormal = angle_sum(angle_to_point(sources[n], sources[m]), M_PI_2);\n            }\n        }\n    }\n\n    return maxNormal;\n}\n\n\nboost::optional<Gateway> create_gateway_at_cell(cell_t cell,\n                                                double normal,\n                                                int32_t id,\n                                                const VoronoiSkeletonGrid& skeleton,\n                                                double maxExtraLength)\n{\n    auto cellBoundary = gateway_boundary_line_at_cell(cell, normal, skeleton, maxExtraLength);\n\n    if (!cellBoundary) {\n        return boost::none;\n    }\n\n    // If the cell isn't on the reduced skeleton, then find it\n    if (~skeleton.getClassification(cell.x, cell.y) & SKELETON_CELL_REDUCED_SKELETON) {\n        cell = skeleton_cell_between_endpoints(*cellBoundary, skeleton);\n\n        if (!skeleton.isCellInGrid(cell)) {\n            return boost::none;\n        }\n    }\n\n    // Return a valid gateway that satisfies the post-condition\n    Gateway gateway(skeleton.getTimestamp(), id, *cellBoundary, cell, skeleton);\n\n    //     bool foundSkeleton = false;\n    //     for(auto& cell : boost::make_iterator_range(gateway.beginCells(), gateway.endCells()))\n    //     {\n    //         if(skeleton.getClassification(cell.x, cell.y) & SKELETON_CELL_REDUCED_SKELETON)\n    //         {\n    //             if(foundSkeleton)\n    //             {\n    //                 std::cout << \"Filtering gateway at \" << gateway.skeletonCell() << \" Double-crosser!\";\n    //                 return boost::none;\n    //             }\n    //\n    //             foundSkeleton = true;\n    //         }\n    //     }\n\n    return gateway;\n}\n\n\nboost::optional<Line<int>>\n  gateway_boundary_line_at_cell(cell_t cell, double normal, const VoronoiSkeletonGrid& skeleton, double maxExtraLength)\n{\n    // The endpoints of the gateway are in the +/- pi/2 directions. Trace to the nearest obstacle.\n    const double kGatewayLengthAddition = maxExtraLength;\n    Line<int> cellBoundary;\n\n    cellBoundary.a =\n      utils::trace_ray_until_condition(cell,\n                                       normal + M_PI_2,\n                                       skeleton.getMetricDistance(cell.x, cell.y) + kGatewayLengthAddition,\n                                       skeleton,\n                                       VoronoiSkeletonTerminationFunc(kValidEndpointMask));\n    cellBoundary.b =\n      utils::trace_ray_until_condition(cell,\n                                       normal - M_PI_2,\n                                       skeleton.getMetricDistance(cell.x, cell.y) + kGatewayLengthAddition,\n                                       skeleton,\n                                       VoronoiSkeletonTerminationFunc(kValidEndpointMask));\n\n    // If either cell boundary isn't on an unknown or occupied cell, then the ray trace failed to satisfy the condition\n    // so no valid gateway exists.\n    // If both ends are the same, it also can't be a valid gateway.\n    if (!(skeleton.getClassification(cellBoundary.a.x, cellBoundary.a.y) & kValidEndpointMask)\n        || !(skeleton.getClassification(cellBoundary.b.x, cellBoundary.b.y) & kValidEndpointMask)\n        || (cellBoundary.a == cellBoundary.b)) {\n        return boost::none;\n    }\n\n    return cellBoundary;\n}\n\n\nboost::optional<Gateway> create_gateway_between_sources(const CellVector& sources,\n                                                        cell_t skeletonCell,\n                                                        int32_t id,\n                                                        const VoronoiSkeletonGrid& skeleton,\n                                                        const VoronoiIsovistField& isovists)\n{\n    // Weird situation can result in a single source cell, for which there is obviously no\n    if (sources.size() < 2) {\n        return boost::none;\n    }\n\n    // Find the boundary amongst the gateways that is closest to the expected length, given the location of the\n    // skeleton cell\n    double optimalLength = 2.0 * skeleton.getMetricDistance(skeletonCell.x, skeletonCell.y) * skeleton.cellsPerMeter();\n    Line<int> boundary(sources[0], sources[1]);\n    for (std::size_t n = 0; n < sources.size(); ++n) {\n        for (std::size_t m = n + 1; m < sources.size(); ++m) {\n            double len = distance_between_points(sources[n], sources[m]);\n            if (std::abs(len - optimalLength) < std::abs(length(boundary) - optimalLength)) {\n                boundary.a = sources[n];\n                boundary.b = sources[m];\n            }\n        }\n    }\n\n    // Construct a gateway from this boundary\n    auto gatewaySkeleton = skeleton_cell_between_endpoints(boundary, skeleton);\n    // If a valid cell was found, then create the gateway\n    if ((gatewaySkeleton.x >= 0) && (gatewaySkeleton.y >= 0)) {\n        assert(skeleton.getClassification(gatewaySkeleton.x, gatewaySkeleton.y) & kValidCenterMask);\n        return Gateway(skeleton.getTimestamp(), id, boundary, gatewaySkeleton, isovists, skeleton);\n    }\n    // Otherwise no gateway exists\n    else {\n        return boost::none;\n    }\n}\n\n\nboost::optional<Gateway>\n  adjust_gateway_for_new_skeleton(const Gateway& gateway, const VoronoiSkeletonGrid& skeleton, int maxSearchRadius)\n{\n    Line<int> newBoundary;\n    newBoundary.a = nearest_valid_location(utils::global_point_to_grid_cell_round(gateway.boundary().a, skeleton),\n                                           maxSearchRadius,\n                                           kValidEndpointMask,\n                                           skeleton);\n    newBoundary.b = nearest_valid_location(utils::global_point_to_grid_cell_round(gateway.boundary().b, skeleton),\n                                           maxSearchRadius,\n                                           kValidEndpointMask,\n                                           skeleton);\n\n    if (!skeleton.isCellInGrid(newBoundary.a) || !skeleton.isCellInGrid(newBoundary.b)) {\n        std::cout << \"FAILED TO ADJUST BOUNDARY: Old:\" << gateway.cellBoundary() << \" New:\" << newBoundary << '\\n';\n        return boost::none;\n    }\n\n    cell_t skeletonCell = skeleton_cell_between_endpoints(newBoundary, skeleton);\n\n    if (!skeleton.isCellInGrid(skeletonCell)) {\n        std::cout << \"FAILED TO ADJUST SKELETON: Old:\" << gateway.skeletonCell() << \" New boundary:\" << newBoundary\n                  << \" New skeleton: \" << skeletonCell << '\\n';\n        return boost::none;\n    }\n\n    return Gateway(skeleton.getTimestamp(), gateway.id(), newBoundary, skeletonCell, skeleton);\n}\n\n// Return a cell along the boundary that is reduced skeleton, or a cell not in the map\ncell_t skeleton_cell_between_endpoints(const Line<int>& cellBoundary, const VoronoiSkeletonGrid& grid)\n{\n    // Find all cells along the boundary\n    CellVector boundaryCells;\n    utils::find_cells_along_line(cellBoundary, grid, std::back_inserter(boundaryCells));\n\n    // See if any cells are skeleton cells on the boundary\n    auto skeletonIt = std::find_if(boundaryCells.begin(), boundaryCells.end(), [&grid](cell_t c) {\n        return grid.getClassification(c.x, c.y) & SKELETON_CELL_REDUCED_SKELETON;\n    });\n\n    // If didn't find a skeleton cell, then check for a four-way connected cell adjacent to the boundary. Due to\n    // discretization, it is possible to step by the desired skeleton cell\n    if (skeletonIt == boundaryCells.end()) {\n        // If one of the skeleton cells has a neighbor cell with the desired label, then use it.\n        NeighborArray neighbors;\n        for (auto cell : boundaryCells) {\n            int num = neighbor_cells_with_classification(cell, kValidCenterMask, grid, EIGHT_WAY, neighbors);\n\n            if (num > 0) {\n                return neighbors[0];\n            }\n        }\n\n        std::cout << \"Failed to find a reduced skeleton cell along cells: \";\n        std::copy(boundaryCells.begin(), boundaryCells.end(), std::ostream_iterator<cell_t>(std::cout, \" \"));\n        std::cout << '\\n';\n        return cell_t(-1, -1);\n    }\n    // Otherwise, assign the cell to be the skeleton cell that was found\n    else {\n        return *skeletonIt;\n    }\n}\n\n// Return a cell not in the grid if no valid location is within the search radius\ncell_t nearest_valid_location(cell_t start, int searchRadius, uint8_t validMask, const VoronoiSkeletonGrid& grid)\n{\n    // If the start cell is valid, then we're done!\n    if (grid.getClassification(start) & kValidEndpointMask) {\n        return start;\n    }\n\n    // Otherwise run a search through all the cells within the search radius. Check the cells in order of increasing\n    // radius away from the starting cell (approximately) by searching rectangles of cells with increasing perimeter\n    // centered at the start cell\n    std::vector<int> indices;\n    indices.push_back(0);\n    for (int n = 1; n <= searchRadius; ++n) {\n        indices.push_back(n);\n        indices.push_back(-n);\n    }\n\n    for (int y : indices) {\n        for (int x = -std::abs(y), xEnd = std::abs(y); x <= xEnd; ++x) {\n            cell_t newCell(start.x + x, start.y + y);\n            if (grid.getClassification(newCell.x, newCell.y) & kValidEndpointMask) {\n                return newCell;\n            }\n        }\n\n        // The above loop won't check cells along the line y = 0. Do that check separately right here.\n        cell_t newCell(start.x + y, start.y);\n        if (grid.getClassification(newCell.x, newCell.y) & kValidEndpointMask) {\n            return newCell;\n        }\n    }\n\n    return cell_t(-1, -1);\n}\n\n}   // namespace hssh\n}   // namespace vulcan\n", "meta": {"hexsha": "1dcda7fae4f241bd2ab7607cfb3b0b3ac0eaef56", "size": 16673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hssh/local_topological/area_detection/gateways/gateway_utils.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/hssh/local_topological/area_detection/gateways/gateway_utils.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/hssh/local_topological/area_detection/gateways/gateway_utils.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": 40.5669099757, "max_line_length": 120, "alphanum_fraction": 0.638697295, "num_tokens": 3803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37387583672470853, "lm_q1q2_score": 0.18839834113730364}}
{"text": "//==================================================================\n// Author       : Pointner Sebastian\n// Company      : Johannes Kepler University\n// Name         : SMT Macro Placer\n// Workfile     : macrocircuit.hpp\n//\n// Date         : 22. December 2019\n// Compiler     : gcc version 9.2.0 (GCC) \n// Copyright    : Johannes Kepler University\n// Description  : SoC Macro Circuit\n//==================================================================\n#ifndef MACROCIRCUIT_HPP\n#define MACROCIRCUIT_HPP\n\n#include <vector>\n#include <string>\n#include <fstream>\n#include <cstdio>\n#include <map>\n#include <unordered_map>\n#include <thread>\n#include <chrono>\n#include <mutex>\n#include <cmath>\n\n#include <z3++.h>\n\n#include <boost/filesystem.hpp>\n\n#include <object.hpp>\n#include <components.hpp>\n#include <lefdefIO.h>\n#include <tree.hpp>\n#include <evaluate.hpp>\n#include <logger.hpp>\n#include <timer.hpp>\n#include <supplement.hpp>\n#include <bookshelf.hpp>\n#include <layout.hpp>\n#include <partitioning.hpp>\n#include <parquet.hpp>\n#include <encoding_utils.hpp>\n#include <utils.hpp>\n#include <def_utils.hpp>\n#include <database.hpp>\n#include <plotter.hpp>\n#include <hlclient.hpp>\n\nnamespace Placer {\n\nclass Evaluate;\nclass Partitioning;\nclass ParquetFrontend;\n\n/**\n * @class MacroCircuit\n * @brief Top Class for MacroCircuit Placement\n */\nclass MacroCircuit: public virtual Object {\npublic:\n\n    MacroCircuit();\n\n    virtual ~MacroCircuit();\n\n    void build_circuit();\n    void partitioning();\n    void encode();\n    void place();\n\n    void dump_all();\n    void dump_best();\n\n    void save_all();\n    void save_best();\n\n    void results_to_db();\n\n    void create_statistics();\n\n    void dump(std::ostream & stream = std::cout);\n\nprivate:\n    friend class Evaluate;\n\n    // Microsoft Z3\n    z3::optimize* m_z3_opt;\n\n    Circuit::Circuit* m_circuit;\n    std::vector<Macro*> m_macros;\n    std::vector<MacroDefinition> m_macro_definitions;\n\n    std::vector<Cell*> m_cells;\n\n    std::vector<Terminal*> m_terminals;\n\n    std::vector<Partition*> m_partitons;\n\n    std::vector<Component*> m_components;\n    Tree* m_tree;\n    Evaluate* m_eval;\n    Utils::Logger* m_logger;\n    Utils::Timer* m_timer;\n    Utils::Database* m_db;\n    Utils::DefUtils* m_def_utils;\n    Supplement* m_supplement;\n    Bookshelf* m_bookshelf;\n    Partitioning* m_partitioning;\n    ParquetFrontend* m_parquet;\n    EncodingUtils* m_encode;\n    Plotter* m_plotter;\n    HLClient* m_hl_client;\n\n    std::map<std::string, Macro*> m_id2macro;\n    std::map<std::string, Terminal*> m_id2terminal;\n    std::map<std::string, Cell*> m_id2cell;\n    size_t m_solutions;\n    size_t m_estimated_area;\n\n    Layout* m_layout;\n\n    double m_standard_cell_height;\n\n    void build_circuit_lefdef();\n    void build_circuit_bookshelf();\n\n    bool is_macro(LefDefParser::defiComponent const & macro);\n    bool is_standard_cell(LefDefParser::defiComponent const & cell);\n\n    /**\n     * Thread Functions\n     */\n    void add_terminals();\n    void add_macros();\n    void add_cells();\n    void area_estimator();\n\n    void add_cell(LefDefParser::defiComponent const & cmp);\n\n    void build_tree_from_lefdef();\n    void init_tree(eInputFormat const type);\n\n    void create_macro_definitions();\n\n    void write_def(std::string const & name, size_t const solution);\n    void write_lef(std::string const & name);\n\n    Tree* get_tree();\n    Layout* get_layout();\n    size_t get_solutions();\n\n    /**\n     * SMT Encoding\n     */\n    void encode_smt();\n    void encode_parquet();\n\n    void config_z3();\n    void run_encoding();\n\n    void encode_components_inside_die(eRotation const type);\n    void encode_components_non_overlapping(eRotation const type);\n    void encode_terminals_on_frontier();\n    void encode_terminals_non_overlapping();\n    void encode_terminals_center_edge();\n    void encode_hpwl_length();\n    void encode_layout_on_grid();\n    void encode_components_on_grid();\n    void encode_terminals_on_grid();\n\n    z3::expr m_components_non_overlapping;\n    z3::expr m_components_inside_die;\n    z3::expr m_terminals_on_frontier;\n    z3::expr m_terminals_non_overlapping;\n    z3::expr m_terminals_center_edge;\n    z3::expr m_hpwl_cost_function;\n    z3::expr m_layout_on_grid;\n    z3::expr m_terminals_on_grid;\n    z3::expr m_components_on_grid;\n    z3::expr_vector m_hpwl_edges;\n\n    z3::expr manhattan_distance(z3::expr const & from_x,\n                                z3::expr const & from_y,\n                                z3::expr const & to_x,\n                                z3::expr const & to_y);\n\n    /**\n     * SMT Solving\n     */ \n    void solve_z3_api();\n    void solve_z3_no_api();\n    void solve_optimathsat_no_api();\n    void process_results(z3::model const & m);\n    void dump_smt_instance();\n    void process_key_value_results(std::map<std::string, std::vector<size_t>> & solution, size_t const id);\n\n};\n\n} /* namespace Placer */\n\n#endif /* MACROCIRCUIT_HPP */\n", "meta": {"hexsha": "af18f758cd1674204f3077b1f281e669ca83b8f4", "size": 4911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "01_src/macrocircuit/macrocircuit.hpp", "max_stars_repo_name": "gledr/SMT_MacroPlacer", "max_stars_repo_head_hexsha": "b5b25f0ce9094553167ffd4985721f86414ceddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T15:33:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T07:34:15.000Z", "max_issues_repo_path": "01_src/macrocircuit/macrocircuit.hpp", "max_issues_repo_name": "gledr/SMT_MacroPlacer", "max_issues_repo_head_hexsha": "b5b25f0ce9094553167ffd4985721f86414ceddc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01_src/macrocircuit/macrocircuit.hpp", "max_forks_repo_name": "gledr/SMT_MacroPlacer", "max_forks_repo_head_hexsha": "b5b25f0ce9094553167ffd4985721f86414ceddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-03T07:34:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T07:34:17.000Z", "avg_line_length": 24.3118811881, "max_line_length": 107, "alphanum_fraction": 0.6605579312, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.18839834113730364}}
{"text": "// ======================================================================\n// \\title  FixedAxisSe3AdapterImpl.cpp\n// \\author gene\n// \\brief  cpp file for FixedAxisSe3Adapter component implementation class\n//\n// \\copyright\n// Copyright 2009-2015, by the California Institute of Technology.\n// ALL RIGHTS RESERVED.  United States Government Sponsorship\n// acknowledged. Any commercial use must be negotiated with the Office\n// of Technology Transfer at the California Institute of Technology.\n//\n// This software may be subject to U.S. export control laws and\n// regulations.  By accepting this document, the user agrees to comply\n// with all U.S. export laws and regulations.  User has the\n// responsibility to obtain export licenses, or other export authority\n// as may be required before exporting such information to foreign\n// countries or providing access to foreign persons.\n// ======================================================================\n\n\n#include <Gnc/Utils/FixedAxisSe3Adapter/FixedAxisSe3AdapterComponentImpl.hpp>\n#include \"Fw/Types/BasicTypes.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace Gnc {\n\n  // ----------------------------------------------------------------------\n  // Construction, initialization, and destruction\n  // ----------------------------------------------------------------------\n\n  FixedAxisSe3AdapterComponentImpl ::\n#if FW_OBJECT_NAMES == 1\n    FixedAxisSe3AdapterComponentImpl(\n        const char *const compName\n    ) :\n      FixedAxisSe3AdapterComponentBase(compName)\n#else\n    FixedAxisSe3AdapterImpl(void)\n#endif\n  {\n\n  }\n\n  void FixedAxisSe3AdapterComponentImpl ::\n    init(\n        const NATIVE_INT_TYPE instance\n    )\n  {\n    FixedAxisSe3AdapterComponentBase::init(instance);\n  }\n\n  FixedAxisSe3AdapterComponentImpl ::\n    ~FixedAxisSe3AdapterComponentImpl(void)\n  {\n\n  }\n\n  // ----------------------------------------------------------------------\n  // Handler implementations for user-defined typed input ports\n  // ----------------------------------------------------------------------\n\n  void FixedAxisSe3AdapterComponentImpl ::\n    flatOutput_handler(\n        const NATIVE_INT_TYPE portNum,\n        ROS::mav_msgs::FlatOutput &FlatOutput\n    )\n  {\n      using namespace ROS::geometry_msgs;\n      using namespace ROS::mav_msgs;\n\n      Eigen::Quaterniond yawQ;\n      yawQ = Eigen::AngleAxisd(FlatOutput.getyaw(),\n            Eigen::Vector3d::UnitZ());\n      Se3FeedForward se3ff(FlatOutput.getheader(),\n                           FlatOutput.getposition(),\n                           FlatOutput.getvelocity(),\n                           FlatOutput.getacceleration(),\n                           Quaternion(yawQ.x(),\n                                      yawQ.y(),\n                                      yawQ.z(),\n                                      yawQ.w()),\n                           Vector3(0.0, 0.0, 0.0),\n                           Vector3(0.0, 0.0, 0.0));\n      this->se3Cmd_out(0, se3ff);\n  }\n\n  // ----------------------------------------------------------------------\n  // Command handler implementations\n  // ----------------------------------------------------------------------\n\n  void FixedAxisSe3AdapterComponentImpl ::\n    AXSE3ADAP_InitParams_cmdHandler(\n        const FwOpcodeType opCode,\n        const U32 cmdSeq\n    )\n  {\n    // TODO\n    this->cmdResponse_out(opCode, cmdSeq, Fw::COMMAND_OK);\n  }\n\n} // end namespace Gnc\n", "meta": {"hexsha": "007f409d7b0904d0e7cc1d673bfad0e6286c3ddc", "size": 3389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gnc/Utils/FixedAxisSe3Adapter/FixedAxisSe3AdapterComponentImpl.cpp", "max_stars_repo_name": "genemerewether/fprime", "max_stars_repo_head_hexsha": "fcdd071b5ddffe54ade098ca5d451903daba9eed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-22T03:41:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T12:48:31.000Z", "max_issues_repo_path": "Gnc/Utils/FixedAxisSe3Adapter/FixedAxisSe3AdapterComponentImpl.cpp", "max_issues_repo_name": "genemerewether/fprime", "max_issues_repo_head_hexsha": "fcdd071b5ddffe54ade098ca5d451903daba9eed", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-02-07T17:58:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-13T00:46:24.000Z", "max_forks_repo_path": "Gnc/Utils/FixedAxisSe3Adapter/FixedAxisSe3AdapterComponentImpl.cpp", "max_forks_repo_name": "genemerewether/fprime", "max_forks_repo_head_hexsha": "fcdd071b5ddffe54ade098ca5d451903daba9eed", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-01T18:44:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-01T01:19:39.000Z", "avg_line_length": 32.9029126214, "max_line_length": 77, "alphanum_fraction": 0.5379167896, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.1883983411373036}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_MULTINOMIAL_LOG_HPP\n#define STAN_MATH_PRIM_MAT_PROB_MULTINOMIAL_LOG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/prob/multinomial_lpmf.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/** \\ingroup multivar_dists\n * @deprecated use <code>multinomial_lpmf</code>\n */\ntemplate <bool propto, typename T_prob>\nreturn_type_t<T_prob> multinomial_log(\n    const std::vector<int>& ns,\n    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {\n  return multinomial_lpmf<propto, T_prob>(ns, theta);\n}\n\n/** \\ingroup multivar_dists\n * @deprecated use <code>multinomial_lpmf</code>\n */\ntemplate <typename T_prob>\nreturn_type_t<T_prob> multinomial_log(\n    const std::vector<int>& ns,\n    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {\n  return multinomial_lpmf<false>(ns, theta);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "3e5f6d190bdc00d43d35e2b40fbac72d9608af31", "size": 983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/prob/multinomial_log.hpp", "max_stars_repo_name": "martinmodrak/math", "max_stars_repo_head_hexsha": "89e8ed81eb9fb7362a10648d1dece263def2ea64", "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/mat/prob/multinomial_log.hpp", "max_issues_repo_name": "martinmodrak/math", "max_issues_repo_head_hexsha": "89e8ed81eb9fb7362a10648d1dece263def2ea64", "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/mat/prob/multinomial_log.hpp", "max_forks_repo_name": "martinmodrak/math", "max_forks_repo_head_hexsha": "89e8ed81eb9fb7362a10648d1dece263def2ea64", "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.3055555556, "max_line_length": 60, "alphanum_fraction": 0.7487283825, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.18839834113730358}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <memory>\n#include <utility>\n\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"DataStructures/VariablesTag.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Evolution/DgSubcell/Tags/Mesh.hpp\"\n#include \"Evolution/DgSubcell/Tags/NeighborData.hpp\"\n#include \"Evolution/Systems/ScalarAdvection/FiniteDifference/Reconstructor.hpp\"\n#include \"Evolution/Systems/ScalarAdvection/Tags.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// \\cond\ntemplate <size_t Dim>\nclass Direction;\ntemplate <size_t Dim>\nclass Element;\ntemplate <size_t Dim>\nclass ElementId;\ntemplate <size_t Dim>\nclass Mesh;\ntemplate <typename TagsList>\nclass Variables;\nnamespace evolution::dg::subcell {\nclass NeighborData;\n}  // namespace evolution::dg::subcell\nnamespace gsl {\ntemplate <typename>\nclass not_null;\n}  // namespace gsl\nnamespace PUP {\nclass er;\n}  // namespace PUP\n/// \\endcond\n\nnamespace ScalarAdvection::fd {\n/*!\n * \\brief Monotised central reconstruction. See\n * ::fd::reconstruction::monotised_central() for details.\n */\ntemplate <size_t Dim>\nclass MonotisedCentral : public Reconstructor<Dim> {\n private:\n  using face_vars_tags =\n      tmpl::list<Tags::U,\n                 ::Tags::Flux<Tags::U, tmpl::size_t<Dim>, Frame::Inertial>>;\n  using volume_vars_tags = tmpl::list<Tags::U>;\n\n public:\n  using options = tmpl::list<>;\n  static constexpr Options::String help{\n      \"Monotised central reconstruction scheme.\"};\n\n  MonotisedCentral() = default;\n  MonotisedCentral(MonotisedCentral&&) = default;\n  MonotisedCentral& operator=(MonotisedCentral&&) = default;\n  MonotisedCentral(const MonotisedCentral&) = default;\n  MonotisedCentral& operator=(const MonotisedCentral&) = default;\n  ~MonotisedCentral() override = default;\n\n  void pup(PUP::er& p) override;\n\n  /// \\cond\n  explicit MonotisedCentral(CkMigrateMessage* msg);\n  WRAPPED_PUPable_decl_base_template(Reconstructor<Dim>, MonotisedCentral);\n  /// \\endcond\n\n  auto get_clone() const -> std::unique_ptr<Reconstructor<Dim>> override;\n\n  size_t ghost_zone_size() const override { return 2; }\n\n  using reconstruction_argument_tags = tmpl::list<\n      ::Tags::Variables<volume_vars_tags>, domain::Tags::Element<Dim>,\n      evolution::dg::subcell::Tags::NeighborDataForReconstructionAndRdmpTci<\n          Dim>,\n      evolution::dg::subcell::Tags::Mesh<Dim>>;\n\n  template <typename TagsList>\n  void reconstruct(\n      gsl::not_null<std::array<Variables<TagsList>, Dim>*> vars_on_lower_face,\n      gsl::not_null<std::array<Variables<TagsList>, Dim>*> vars_on_upper_face,\n      const Variables<tmpl::list<Tags::U>>& volume_vars,\n      const Element<Dim>& element,\n      const FixedHashMap<\n          maximum_number_of_neighbors(Dim) + 1,\n          std::pair<Direction<Dim>, ElementId<Dim>>,\n          evolution::dg::subcell::NeighborData,\n          boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>&\n          neighbor_data,\n      const Mesh<Dim>& subcell_mesh) const;\n\n  template <typename TagsList>\n  void reconstruct_fd_neighbor(\n      gsl::not_null<Variables<TagsList>*> vars_on_face,\n      const Variables<tmpl::list<Tags::U>>& volume_vars,\n      const Element<Dim>& element,\n      const FixedHashMap<\n          maximum_number_of_neighbors(Dim) + 1,\n          std::pair<Direction<Dim>, ElementId<Dim>>,\n          evolution::dg::subcell::NeighborData,\n          boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>&\n          neighbor_data,\n      const Mesh<Dim>& subcell_mesh,\n      const Direction<Dim> direction_to_reconstruct) const;\n};\n\ntemplate <size_t Dim>\nbool operator==(const MonotisedCentral<Dim>& /*lhs*/,\n                const MonotisedCentral<Dim>& /*rhs*/);\n\ntemplate <size_t Dim>\nbool operator!=(const MonotisedCentral<Dim>& lhs,\n                const MonotisedCentral<Dim>& rhs);\n}  // namespace ScalarAdvection::fd\n", "meta": {"hexsha": "fa97cfde3a8a9cb80c15edf19225f6bfb6a21b66", "size": 4141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/ScalarAdvection/FiniteDifference/MonotisedCentral.hpp", "max_stars_repo_name": "kidder/spectre", "max_stars_repo_head_hexsha": "97ae95f72320f9f67895d3303824e64de6fd9077", "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/Evolution/Systems/ScalarAdvection/FiniteDifference/MonotisedCentral.hpp", "max_issues_repo_name": "kidder/spectre", "max_issues_repo_head_hexsha": "97ae95f72320f9f67895d3303824e64de6fd9077", "max_issues_repo_licenses": ["MIT"], "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/Evolution/Systems/ScalarAdvection/FiniteDifference/MonotisedCentral.hpp", "max_forks_repo_name": "kidder/spectre", "max_forks_repo_head_hexsha": "97ae95f72320f9f67895d3303824e64de6fd9077", "max_forks_repo_licenses": ["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.3515625, "max_line_length": 79, "alphanum_fraction": 0.7157691379, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.18839833410629483}}
{"text": "/*\n * Copyright (c) 2019, 2020, 2021 SiKol Ltd.\n *\n * Boost Software License - Version 1.0 - August 17th, 2003\n *\n * Permission is hereby granted, free of charge, to any person or organization\n * obtaining a copy of the software and accompanying documentation covered by\n * this license (the \"Software\") to use, reproduce, display, distribute,\n * execute, and transmit the Software, and to prepare derivative works of the\n * Software, and to permit third-parties to whom the Software is furnished to\n * do so, all subject to the following:\n *\n * The copyright notices in the Software and this entire statement, including\n * the above license grant, this restriction and the following disclaimer,\n * must be included in all copies of the Software, in whole or in part, and\n * all derivative works of the Software, unless such copies or derivative\n * works are solely in the form of machine-executable object code generated by\n * a source language processor.\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, TITLE AND NON-INFRINGEMENT. IN NO EVENT\n * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\n * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef SK_CONFIG_PARSER_NUMERIC_HXX_INCLUDED\n#define SK_CONFIG_PARSER_NUMERIC_HXX_INCLUDED\n\n#include <concepts>\n\n#include <boost/spirit/home/x3/numeric/int.hpp>\n#include <boost/spirit/home/x3/numeric/real.hpp>\n#include <boost/spirit/home/x3/numeric/uint.hpp>\n\n#include <sk/config/detail/parser/bool.hxx>\n#include <sk/config/parser_for.hxx>\n\nnamespace sk::config {\n\n    /*\n     * bool is here because it's an std::unsigned_integral, so if we\n     * put it in its own header, anyone including numeric.hxx but not\n     * the bool header would incorrectly parse bool instead of creating\n     * a compile-time error.\n     */\n    template <> struct parser_for<bool> {\n        using parser_type = detail::parser::bool_parser;\n        using rule_type = bool;\n        static constexpr char const name[] = \"a boolean\";\n    };\n\n    void propagate_value(auto & /*ctx*/, bool &to, bool from) {\n        to = from;\n    }\n\n    // signed_integral\n    template <std::signed_integral T> struct parser_for<T> {\n        using parser_type = boost::spirit::x3::int_parser<T>;\n        using rule_type = T;\n        static constexpr char const name[] = \"an integer\";\n    };\n\n    template <std::signed_integral T>\n    void propagate_value(auto & /*ctx*/, T &to, T from) {\n        to = from;\n    }\n\n    // unsigned_integral\n    template <std::unsigned_integral T> struct parser_for<T> {\n        using parser_type = boost::spirit::x3::uint_parser<T>;\n        using rule_type = T;\n        static constexpr char const name[] = \"a positive integer\";\n    };\n\n    template <std::unsigned_integral T>\n    void propagate_value(auto & /*ctx*/, T &to, T from) {\n        to = from;\n    }\n\n    // floating_point\n    template <typename T>\n    struct config_real_policies : boost::spirit::x3::real_policies<T> {};\n\n    template <std::floating_point T> struct parser_for<T> {\n        using parser_type =\n            boost::spirit::x3::real_parser<float, config_real_policies<float>>;\n        using rule_type = T;\n        static constexpr char const name[] = \"a decimal number\";\n    };\n\n    template <std::floating_point T>\n    void propagate_value(auto & /*ctx*/, T &to, T from) {\n        to = from;\n    }\n\n}; // namespace sk::config\n\n#endif // SK_CONFIG_PARSER_NUMERIC_HXX_INCLUDED\n", "meta": {"hexsha": "ca6429d034bd5753fce97b164a4dd234f6b88cb8", "size": 3701, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/sk/config/parser/numeric.hxx", "max_stars_repo_name": "sikol/sk-config", "max_stars_repo_head_hexsha": "ada0c72ac5703763b1f1d9aadc2cc3850bf11acc", "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/sk/config/parser/numeric.hxx", "max_issues_repo_name": "sikol/sk-config", "max_issues_repo_head_hexsha": "ada0c72ac5703763b1f1d9aadc2cc3850bf11acc", "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/sk/config/parser/numeric.hxx", "max_forks_repo_name": "sikol/sk-config", "max_forks_repo_head_hexsha": "ada0c72ac5703763b1f1d9aadc2cc3850bf11acc", "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.2843137255, "max_line_length": 79, "alphanum_fraction": 0.694406917, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.18839833410629483}}
{"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_INTERLEAVE_EVEN_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_INTERLEAVE_EVEN_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <boost/simd/meta/is_bitwise_logical.hpp>\n#include <boost/simd/function/simd/bitwise_cast.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD(interleave_even_\n                          , (typename A0, typename A1, typename X)\n                          , bd::cpu_\n                          , bs::pack_<bd::unspecified_<A0>, X>\n                          , bs::pack_<bd::unspecified_<A1>, X>\n                          )\n   {\n     A0 operator()(A0 const& a0, A1 const& a1) const\n      {\n        A0 that;\n        const std::size_t n = bs::cardinal_of<A0>::value;\n        for(std::size_t i=0;i<n;i+= 2)\n        {\n          that[i]   = a0[i];\n          that[i+1] = a1[i];\n        }\n        return that;\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD(interleave_even_\n                             , (typename A0, typename X)\n                             , bd::cpu_\n                             , bs::pack_<bs::logical_<A0>, X>\n                             , bs::pack_<bs::logical_<A0>, X>\n                             )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n      {\n        using type = A0; //meta::as_arithmetic<A0>;\n        return bitwise_cast<A0>(\n          interleave_even( bitwise_cast<type>(a0), bitwise_cast<type>(a1) )\n        );\n      }\n   };\n\n\n//   #define M_IEVEN(z,n,t) (n%2 ? (t+n-1) : n)\n//   BOOST_SIMD_DEFINE_SHUFFLE2(  interleave_even_, M_IEVEN, type32_ )\n//   BOOST_SIMD_DEFINE_SHUFFLE2(  interleave_even_, M_IEVEN, type16_ )\n//   BOOST_SIMD_DEFINE_SHUFFLE2(  interleave_even_, M_IEVEN, type8_  )\n//   #undef M_IEVEN\n\n} } }\n\n#endif\n\n", "meta": {"hexsha": "67b34495314f33c82be1a50af8ca45c3e9b0314e", "size": 2403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/interleave_even.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/interleave_even.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/interleave_even.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.375, "max_line_length": 100, "alphanum_fraction": 0.5364128173, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.18839833410629483}}
{"text": "#include \"formats/cube.hpp\"\n#include \"formats/gnuplot.hpp\"\n#include \"formats/stm.hpp\"\n#include \"atomistic/fundamental.hpp\"\n#include \"types.hpp\"\n#include \"wrappers/lapack.hpp\"\n#include \"io.hpp\"\n#include <cmath>\n\n#include <ctime>\n\n#include <boost/format.hpp>\n#include <boost/spirit/include/qi_core.hpp>\n#include <boost/spirit/include/qi_eol.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <blitz/array.h>\n\n#include <fftw3.h>\n\nnamespace formats {\nnamespace stm {\n\nusing namespace types;\nusing namespace wrappers::lapack;\n\nbool StsCube::initialize(){\n    if(levels.size() == 0){\n        std::cout \n            << \"No states for given energy window. STS will not be performed.\";\n        return false;\n    }\n\n    // Steal from first cube file\n    std::list< formats::WfnCube >::const_iterator\n        cubeIt = levels.begin();\n    \n    // Get atoms and proper grid\n    this->fileName = cubeIt->fileName;\n    this->readCubeFile();\n    \n    this->title  = \"STS data (z = energy)\";\n    this->description  = str(boost::format(\n                \"Range [%1.3d V,%1.3d V], delta %1.4d V, sigma %1.4d V\")\n            % eMin % eMax % deltaE % sigma);\n    \n    if(modeFlag == CONSTANT_Z){\n        Real height = boost::lexical_cast<Real>(modeParameter);\n    \n        // Get z index of STS plane\n        std::vector<types::Real> tempvector;\n        tempvector.push_back(0);\n        tempvector.push_back(0);\n        tempvector.push_back(this->topZCoordinate() + height);\n        std::vector<types::Uint> indices;\n        this->grid.getNearestIndices(tempvector, indices);\n        this-> zIndex = indices[2];\n        std::cout << \"STS will be performed at z-index \" \n            << zIndex << \"\\n\";\n        this->title += str(boost::format(\" at z-plane %3d\") % zIndex);\n    }\n    else if (modeFlag == PROFILE){\n        stm = stm::StmCube();\n        std::cout << \"Reading z profile from \" \n            << modeParameter << \"\\n\";\n        stm.readIgorFile(modeParameter);\n        this->title += \" on z profile read from \";\n        this->title += modeParameter;\n    }\n\n    // Adjust z dimension for energy\n    Uint newIncrementCount =(unsigned int) ((eMax - eMin)/deltaE) + 1;\n\n    if(this->cubeZ == 0){\n        // Per default we simply keep the old z extent\n        this->grid.directions[2].scaleVector(\n                Real(grid.directions[2].getNElements())/\n                Real(newIncrementCount));\n        this->grid.directions[2] = \n            la::Direction(grid.directions[2].getIncrementVector(),\n                    newIncrementCount);\n    }\n    else{\n        // Else the new extent is cubeZ atomic units\n        Real newDZ = this->cubeZ / newIncrementCount;\n        std::vector<Real> v; v.push_back(0); v.push_back(0); v.push_back(newDZ);\n        this->grid.directions[2] = la::Direction(v, newIncrementCount);\n        this->grid.originVector[2] = \n            eMin / (eMax - eMin) * cubeZ;\n    }\n    grid.data = std::vector<Real>(grid.countPoints(), 0.0);\n\n    return true;\n}\n\n\nbool StsCube::calculate(){\n\n    if( ! this->initialize() ) return false;\n\n    std::list< formats::WfnCube >::const_iterator\n        cubeIt = levels.begin(),\n    cubeEnd = levels.end();\n\n    // Get all necessary planes\n    formats::WfnCube tempCube;\n    while(cubeIt != cubeEnd){\n        std::cout<< \"Processing \" << cubeIt->fileName << \"\\n\";\n        tempCube = *cubeIt;\n        tempCube.readCubeFile();\n        if(!this->psiSquared) tempCube.squareValues();\n        std::vector<Real> tempPlane;\n\n        if(modeFlag == CONSTANT_Z){       \n           tempCube.getZPlane(zIndex, tempPlane);\n        }\n        else if(modeFlag == PROFILE){\n            this->interpolateOnZProfile(tempCube.grid, tempPlane);\n        }\n        \n        addLevel(tempPlane, cubeIt->energy); \n        ++cubeIt;\n    }\n        \n    std::cout<< \"Done processing cube files...\\n\\n\";\n\n    // Normalize sum, s.th. values are, on average, 1\n    //grid *= Real(grid.countPoints()) / grid.sum();\n\n    return true;\n}\n\nvoid StsCube::interpolateOnZProfile(\n        const formats::CubeGrid &grid,\n        std::vector<Real> &result) const { \n    Uint nX = grid.directions[0].getNElements();\n    Uint nY = grid.directions[1].getNElements();\n    result.reserve(nX * nY);\n\n    Real dZ = grid.directions[2].getIncrementVector()[2];\n    std::vector<Real>::const_iterator zIt = this->stm.stm.begin();\n    Real valLow, valHigh, deltaLow;\n    Uint zLow;\n    for(Uint x = 0; x < nX; ++x){\n        for(Uint y = 0; y < nY; ++y){\n            zLow = Uint(*zIt / dZ);\n            deltaLow = (*zIt - zLow * dZ) / dZ; // Between 0 and 1\n            valLow = grid.getDataPoint(x, y, zLow);\n            valHigh = grid.getDataPoint(x, y, zLow + 1);\n\n            result.push_back(valLow * (1.0 - deltaLow) + valHigh * deltaLow);\n\n            ++zIt;\n        }\n    }\n}\n\n\nvoid StsCube::addLevel(const std::vector<types::Real> &plane,\n               types::Real energy){\n    \n    Uint nEnergies = grid.directions[2].getNElements();\n\n    // Gaussian stuff\n    // \\$ \\frac{1}{\\sigma \\sqrt{2\\pi} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}} \\$\n    // = a e^{c(x-b)^2}\n    types::Real a = 1.0/(sigma * std::sqrt(2 * M_PI));\n    types::Real c = -1.0/(2 * sigma * sigma);\n   \n     std::vector<Real>::const_iterator \n         planeIt = plane.begin(),\n         planeEnd = plane.end();\n     std::vector<Real>::iterator \n         dataIt = grid.data.begin();\n     while(planeIt != planeEnd){\n         for(Uint z = 0; z < nEnergies; ++z){\n             Real e = eMin + deltaE * z; \n             *dataIt += *planeIt * a * std::exp(c * (energy - e)*(energy - e));\n             ++dataIt;\n         }\n         ++planeIt;\n     }\n\n\n}\n\nvoid StmCube::setIsoValue(types::Real isoValue){\n    this->setValue = isoValue;\n    this->mode = CONSTANT_CURRENT;\n    this->stm.clear();\n    getZIsoSurface(isoValue, this->stm);\n}\n\nvoid StmCube::setZValue(types::Real zValue){\n    this->setValue = zValue;\n    this->mode = CONSTANT_HEIGHT;\n    this->stm.clear();\n\n    // Find largest z coordinate of atoms\n    std::vector<types::Real> tempvector;\n    tempvector.push_back(0);\n    tempvector.push_back(0);\n    tempvector.push_back(this->topZCoordinate() + zValue);\n    std::vector<types::Uint> indices;\n    this->grid.getNearestIndices(tempvector, indices);\n    Uint zIndex = indices[2];\n    std::cout << \"STM will be performed at z-index \" \n        << zIndex << \"\\n\";\n    this->getZPlane(zIndex, this->stm);\n    std::cout << \"STM will be performed at z-index \" \n        << zIndex << \"\\n\";\n}\n\nbool StmCube::writeIgorFile(String fileName) const {\n    Uint nX = grid.directions[0].getNElements();\n    Uint nY = grid.directions[1].getNElements();\n    std::vector<Real>::const_iterator stmIt = stm.begin();\n\n    Stream result = \"\";\n    for(Uint x = 0; x<nX; ++x){\n        for(Uint y=0; y<nY; ++y){\n            result += str(boost::format(\"%12.6e\") % *stmIt);\n            result += \" \";\n            ++stmIt;\n        }\n        result += \"\\n\";\n    }\n\n    return io::writeStream(fileName, result);\n}\n\n\nbool StmCube::readIgorFile(String fileName) {\n    String content;\n    io::readFile(fileName, content);\n    \n    std::string::const_iterator it = content.begin(),\n        end = content.end();\n\n    using boost::spirit::double_;\n    using boost::spirit::qi::eol;\n    using boost::spirit::qi::parse;\n    using boost::spirit::ascii::space;\n    if (! parse(\n        it,\n        end,\n        double_ % space,\n        stm\n        )) throw types::parseError() << types::errinfo_parse(\"title or description\");\n\n   return true;\n} \n\nWfnExtrapolation::WfnExtrapolation(\n        std::vector<String> fileNames,\n        const cp2k::Spectrum& spectrum,\n        Cube&   hartree ,\n        Mode          mode    ,\n        types::Real   var1    ,\n        types::Real   zWidth  ,\n        types::Real   approachFrom,\n        types::Real   kPlaneMax,\n        types::Uint   nLayers\n        ){\n    \n    for(std::vector<String>::const_iterator it = fileNames.begin();\n                        it != fileNames.end(); ++it){\n        WfnCube tmp;\n        tmp.setFileName(*it);\n        wfns.push_back(tmp);\n    }\n        \n\n    this->spectrum = spectrum;\n    this->hartree = hartree;\n    this->mode    = mode;\n    if      ( mode == plane )       this->zStart     = var1;\n    else if ( mode == rollingBall ) this->ballRadius = var1;\n    else if ( mode == isoSurface )  this->isoValue   = var1;\n    this->zWidth  = zWidth;\n    this->approachFrom = approachFrom;\n    this->kPlaneMax = kPlaneMax;\n    this->nLayers     = nLayers;\n\n}\n\nvoid WfnExtrapolation::execute(){\n    using namespace blitz;\n    time_t t;\n\n    this->determineRange();\n    \n    \n    // Need some info on the grid\n    // SI units energy: 2 m E/hbar^2 a0 = 2 E/Ha\n    Uint nX = hartree.nX(), nY = hartree.nY(), nZ = zEndIndex + 1;\n    Real dX = hartree.dX(), dY = hartree.dY(), dZ = hartree.dZ();\n    \n    std::cout << \"Original wave vector grid: kx,ky = \" \n        << nX << \",\" << nY << \"\\n\";\n    int nKX = nX, nKY = nY, nK = nKX * nKY;\n    if (mode == isoSurface || mode == rollingBall){ \n        // May choose to reduce Fourier components\n        // limiting oscillation frequency/a.u. to kMax\n        Real dKX = 2 * M_PI / (dX * Real(nX));\n        Real dKY = 2 * M_PI / (dY * Real(nY));\n\n        Real kXMax = nKX/2.0 * dKX;\n        Real kYMax = nKY/2.0 * dKY;\n        Real scale = this->kPlaneMax / sqrt(kXMax * kXMax + kYMax * kYMax);\n        if( scale < 1.0 ){\n            nKX = int( scale * nX);\n            nKY = int( scale * nY);\n            std::cout << \"Reduced wave vector grid: kx,ky = \" << nKX << \",\" << nKY << \"\\n\";\n        }\n\n    }\n    \n    for(std::vector<WfnCube>::iterator wfn = wfns.begin();\n            wfn != wfns.end(); ++wfn){\n\n        t = clock();\n        std::cout << \"--------\\n Processing  \" << wfn->getFileName() << \"\\n\";\n        wfn->readCubeFile(); \n        std::cout << \"Time to read cube : \" << (clock() -t)/1000.0 << \" ms\\n\";\n        \n        wfn->grid.resize(nX, nY, nZ);\n        Array<types::Real,3> dataArray(\n                &(wfn->grid.data[0]),\n                shape(nX, nY, nZ),\n                neverDeleteData);\n        Real E =  spectrum.getLevel(wfn->getSpin(), wfn->getLevel());\n        E -= this->surfacePotential;\n        wfn->setEnergy(E);\n        std::cout << \"Energy level \" << wfn->getEnergy() << \" Ha\\n\";\n\n        // Produce z profile\n        std::string zProfile = io::getFileName(wfn->getFileName());\n        WfnCube tmp = WfnCube(*wfn);\n        tmp.squareValues();\n        zProfile += \".zprofile\";\n        std::cout << \"Writing Z profile to \" << zProfile << std::endl;\n        tmp.writeZProfile(zProfile, \"Z profile of sqared wave function\\n\");\n           \n\n        // Get values on extrapolation surface\n        wfn->grid.zSurface(this->zIndices, this->surface);\n        types::String s = formats::gnuplot::writeMatrix<Real>(this->surface, nX, nY);\n        String sFile = io::getFileName(wfn->getFileName()) + \".exsurf\";\n        io::writeStream(sFile, s);\n\n        std::cout << \"Starting extrapolation ... \" << std::endl;\n        if ( mode == plane ) \n            this->onPlane(*wfn);\n        \n        else if ( mode == isoSurface || mode == rollingBall )  \n            this->onSurface(*wfn, nKX, nKY);\n            \n        std::cout << \"Time to extrapolate : \" << (clock() -t)/1000.0 << \" ms\\n\";\n\n        types::String outCubeFile = \"extrapolated.\";\n        outCubeFile += io::getFileName(wfn->getFileName());\n        t = clock();\n        std::cout << \"Writing extrapolated cube file to \" << outCubeFile << std::endl;\n        wfn->writeCubeFile(outCubeFile);\n        std::cout << \"Time to write cube : \" << (clock() -t)/1000.0 << \" ms\\n\";\n\n        // Produce z profile\n        tmp = *wfn;\n        tmp.grid.squareValues();\n        std::string outZProfile = outCubeFile;\n        outZProfile += \".zprofile\";\n        std::cout << \"Writing Z profile of extrapolated cube file to \" << outZProfile << std::endl;\n        tmp.writeZProfile(outZProfile, \"Z profile of squared extrapolated wave function\\n\");\n\n        wfn->grid.data.clear();\n    }\n}\n\nvoid WfnExtrapolation::determineRange(){\n    using namespace blitz;\n\n    Cube tmp(hartree);\n\n    // Some preparations...\n    if( mode == plane || mode == rollingBall) {\n        // Find highest z-coordinate\n        // Note: The slowest index in cube file format is x, so in terms of storage\n        //       modifying the number of x-coordinates would be the easiest.\n        std::vector< atomistic::Atom >::const_iterator it = hartree.atoms.begin(),\n            end = hartree.atoms.end();\n        types::Real zTop = it->coordinates[2];\n        ++it;\n        while(it != end) {\n            if( it->coordinates[2] > zTop ) {\n                zTop = it->coordinates[2];\n            }\n            ++it;\n        }\n    \n        // Define region of interpolation\n        std::vector<types::Real> tempvector;\n        tempvector.push_back(0);\n        tempvector.push_back(0);\n        tempvector.push_back(zTop + zStart);\n        std::vector<types::Uint> indices;\n        hartree.grid.getNearestIndices(tempvector, indices);\n        this->zStartIndex = indices[2];\n        this->zSurfEndIndex = indices[2];\n        \n        tempvector[2] += zWidth;\n        hartree.grid.getNearestIndices(tempvector, indices);\n        this->zEndIndex = indices[2];\n    }\n\n\n    // Define the z indices\n    if (mode == plane){\n        std::cout << \"Fourier transform will be performed at z-index \" \n            << zStartIndex << \"\\n\";\n    \n        this->zIndices = std::vector<Uint> (hartree.nX() * hartree.nY(), zStartIndex);\n        \n    }\n\n    else if ( mode == isoSurface ) {\n        if (approachFrom < 0) hartree.grid.zIsoSurfaceOnGrid(isoValue, this->zIndices);\n        else                  hartree.grid.zIsoSurfaceOnGrid(isoValue, this->zIndices, approachFrom);\n        \n        Array<types::Uint,2> zIndicesBlitz(\n                &zIndices[0],\n                shape(hartree.nX(), hartree.nY()),\n                neverDeleteData);\n        \n        // Write some info about plane \n        zStartIndex = min(zIndicesBlitz);\n        Real dZ = hartree.grid.directions[2].getIncrementVector()[2];\n        zSurfEndIndex = max(zIndicesBlitz);\n        zEndIndex = zSurfEndIndex + Uint(zWidth / dZ);\n\n        std::cout << \"Isosurface ranges over \" << (zSurfEndIndex-zStartIndex)*dZ\n                  << \" from z = \" << zStartIndex * dZ \n                  << \" to \" << max(zIndicesBlitz) * dZ << \" [a.u.].\\n\";\n        std::cout << \"Extrapolation will be extended to \"\n                  << zEndIndex * dZ << \" [a.u.]\\n\";\n    }\n\n    else if (mode == rollingBall){\n        Uint nX = hartree.nX(), nY = hartree.nY(), nZ = zEndIndex + 1;\n        Real dX = hartree.dX(), dY = hartree.dY(), dZ = hartree.dZ();\n\n        // TODO if (approachFrom > 0) zMax  = approachFrom;\n\n\n        std::vector<bool> boolGrid(nX*nY*nZ, false);\n        std::vector<atomistic::Atom>::const_iterator \n            it  = hartree.atoms.begin(),\n            end = hartree.atoms.end();\n        int rI = int(ballRadius / dX) + 1;\n        int rJ = int(ballRadius / dY) + 1;\n        \n        Real x,y,z;\n        int iX, iY, iZ;\n        Real r2 = ballRadius * ballRadius;\n\n        // Build the boolean Grid\n        std::vector<types::Uint> indices;\n        std::vector<Real> coords;\n        while(it != end){\n            indices.clear();\n            coords = it->getCoordinates();\n            hartree.grid.getNearestIndices(coords, indices);\n\n            for(int i = -rI; i <= rI; ++i)\n                for(int j = -rJ; j <= rJ; ++j){\n                    x = i * dX;\n                    y = j * dY;\n                    z = r2 - x*x - y*y;\n\n                    if (z > 0){\n                        iX = (indices[0] + i) % nX;\n                        iY = (indices[1] + j) % nY;\n                        iZ = int(indices[2]) + int(sqrt(z) / dZ);\n                        if (iZ > zEndIndex) iZ = zEndIndex;\n\n                        boolGrid[iX*nY*nZ + iY*nZ + iZ] = true;\n                    }\n                }\n\n            ++it;\n        }\n\n               \n\n        // Find the topmost 'true' surface\n        zIndices = std::vector<Uint>(nX*nY);\n        for(int i = 0; i < nX; ++i)\n            for(int j = 0; j < nY; ++j){\n                int k = nZ;\n                while(k > 0){\n                    --k;\n                    if (boolGrid[i*nY*nZ + j*nZ + k] == true){\n                        zIndices[i*nY + j] = k;\n                        break;\n                    }\n                }\n                if (k == 0){\n                    std::cout << \"Warning: Ball rolled to bottom of cube file without finding an atom.\\n\";\n                    zIndices[i*nY + j] = 0;\n                }\n            }\n\n        \n//        Old, much too slow way of doing things\n//        std::vector<Real> tmp;\n//        for(Uint x = 0; x < nX; ++x){\n//            std::cout << \"Here\\n\";\n//            for(Uint y = 0; y < nY; ++y)\n//                for(Uint z = zMax; z > 0; --z){\n//                    tmp.push_back(x*hartree.dX());\n//                    tmp.push_back(y*hartree.dY());\n//                    tmp.push_back(z*hartree.dZ());\n//                    if(hartree.distance(tmp) < ballRadius){\n//                        zIndices[y*nX+x] = z-1;\n//                        break;\n//                    }\n//                }\n//        }\n        \n        Array<types::Uint,2> zIndicesBlitz(\n                &zIndices[0],\n                shape(hartree.nX(), hartree.nY()),\n                neverDeleteData);\n        \n        // Write some info about plane \n        zStartIndex = min(zIndicesBlitz);\n        zSurfEndIndex = max(zIndicesBlitz);\n        //Real dZ = hartree.dZ();\n        zEndIndex = zSurfEndIndex + Uint(zWidth / dZ);\n\n        std::cout << \"Rolling-ball surface ranges over \" << (zSurfEndIndex-zStartIndex)*dZ\n                  << \" from z = \" << zStartIndex * dZ \n                  << \" to \" << zSurfEndIndex * dZ << \" [a.u.].\\n\";\n        std::cout << \"Extrapolation will be extended to \"\n                  << zEndIndex * dZ << \" [a.u.]\\n\";\n\n    }\n   \n    // Write extrapolation z indices \n    String s = formats::gnuplot::writeMatrix<Uint>(this->zIndices, hartree.nX(), hartree.nY());\n    String sFile = io::getFileName(hartree.getFileName()) + \".zindices\";\n    io::writeStream(sFile, s);\n\n    this->setSurfacePotential();\n    \n\n}\n   \nvoid WfnExtrapolation::setSurfacePotential(){\n    using namespace blitz;\n   \n\n    std::vector<Real> hartreeVector;\n    hartree.grid.zSurface(zIndices, hartreeVector);\n    Array<Real, 2> hartreeSurface (\n            &hartreeVector[0],\n            shape(hartree.nX(), hartree.nY()),\n            neverDeleteData);\n    this->surfacePotential = mean(hartreeSurface);\n    Array<Real, 3> hartreeGrid (\n            &(hartree.grid.data[0]),\n            shape(hartree.nX(), hartree.nY(), hartree.nZ()),\n            neverDeleteData);\n    Real vacuumPotential = max(hartreeGrid);\n\n    std::cout << \"Average Hartree potential on extrapolation surface is \" \n              << surfacePotential << \" Ha\\n\";\n    std::cout << \"This is \" << vacuumPotential - surfacePotential \n              << \" Ha below the maximum Hartree potential.\\n\";\n\n    // Print hartree potential for gnuplot\n    types::String s = formats::gnuplot::writeMatrix(hartreeVector, hartree.nX(), hartree.nY());\n    String surfaceFile = io::getFileName(hartree.getFileName()) + \".exsurf\";\n    io::writeStream(surfaceFile, s);\n\n}\n\n\nvoid WfnExtrapolation::onPlane(WfnCube& wfn){\n    using namespace blitz;\n    time_t t;\n        \n    // Need some info on the grid\n    // SI units energy: 2 m E/hbar^2 a0 = 2 E/Ha\n    Uint nX = wfn.nX(), nY = wfn.nY(), nZ = wfn.nZ();\n    Real dX = hartree.dX(), dY = hartree.dY(), dZ = hartree.dZ();\n    Real dKX = 2 * M_PI * dZ / (dX * Real(nX));\n    Real dKY = 2 * M_PI * dZ / (dY * Real(nY));\n    \n    Real E = wfn.getEnergy() * dZ * dZ;\n    Array<types::Real,3> dataArray(\n            &(wfn.grid.data[0]),\n            shape(nX, nY, nZ),\n            neverDeleteData);\n\n    // Do a real 2 complex fft\n    // Since a(-k)=a(k)^* (or in terms of indices: a[n-k]=a[k]^*)\n    // only a[k], k=0...n/2+1 (division rounded down) are retained\n    types::Uint nXF = nX, nYF = nY/2 + 1;\n    fftw_complex *out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * nXF * nYF);\n\n    Array<types::Real,2> planeDirect(\n            &surface[0], \n            shape(nX, nY), \n            neverDeleteData);\n\n    fftw_plan plan_forward = fftw_plan_dft_r2c_2d(nX, nY, planeDirect.data(), out, FFTW_ESTIMATE);\n    fftw_execute(plan_forward);\n\n\n    Array<types::Complex,2> planeFourier(\n            reinterpret_cast<types::Complex *>(out),\n            shape(nXF, nYF),\n            neverDeleteData);\n    \n    std::vector<Real> fourierReal(nXF*nYF);\n    for(int i =0;i<nXF;++i)\n        for(int j =0;j<nYF;++j)\n            fourierReal[i*nYF+j] = abs(planeFourier(i,j));\n\n    // Plotting the coefficients of the Fourier\n    String s = formats::gnuplot::writeMatrix<Real>(fourierReal, nXF, nYF);\n    String hartleyFile = io::getFileName(wfn.getFileName()) + \".fourier\";\n    io::writeStream(hartleyFile, s);\n\n\n    // Calculate the exponential prefactors.\n    // Multiplication of Fourier coefficients with these prefactors\n    // propagates them to next z plane.\n    // The prefectors would only need dimensions (nX/2 +1, nY/2 +1)\n    // since they are the same for G and -G. However for the sake of\n    // simplicity of calculation, we prepare them here for (nX, nY/2+1) = (nXF,nYF).\n    t = clock();\n    Array<types::Real,2> prefactors(nXF, nYF);\n\n    // Notice that the order of storage is 0...G -G...-1 for uneven nX\n    // and 0...G-1 G -(G-1)...-1 for even NX\n    prefactors( Range(0, nXF/2), Range::all())= exp(- sqrt(tensor::i * dKX * tensor::i * dKX + tensor::j *dKY * tensor::j * dKY - 2 * E) );\n    // tensor::i always starts from 0, i.e. it ranges from 0...nXF/2-1 (nX even) or 0...nXF/2 (nX uneven)\n    if(nX % 2 == 1)\n        prefactors( Range(nXF/2 + 1, nXF - 1), Range::all())= exp(- sqrt( (nXF/2 - tensor::i) * dKX * (nXF/2 - tensor::i) * dKX + tensor::j *dKY * tensor::j * dKY - 2 * E) );\n    else\n        prefactors( Range(nXF/2 + 1, nXF - 1), Range::all())= exp(- sqrt( (nXF/2 -1 - tensor::i) * dKX * (nXF/2 - 1 - tensor::i) * dKX + tensor::j *dKY * tensor::j * dKY - 2 * E) );\n\n    // Sequentially update the cube file\n    Array<types::Real,2> tempDirect(nX, nY);\n    Array<types::Complex,2> tempFourier(nXF, nYF);\n    fftw_plan plan_backward;\n    for(int zIndex = zStartIndex + 1; zIndex < nZ; ++zIndex) {\n        // Propagate fourier coefficients\n        planeFourier = prefactors(tensor::i, tensor::j) * planeFourier(tensor::i, tensor::j);\n\n        // The c2r transform destroys its input\n        tempFourier = planeFourier;\n        plan_backward = fftw_plan_dft_c2r_2d(nX, nY, (fftw_complex*) tempFourier.data(), tempDirect.data(), FFTW_ESTIMATE);\n\n\n        // Do Fourier-back transform\n        fftw_execute(plan_backward); /* repeat as needed */\n        tempDirect /= nX * nY;\n\n        // Copy data\n        dataArray(Range::all(), Range::all(), zIndex) = tempDirect(Range::all(), Range::all());\n    }\n\n    fftw_destroy_plan(plan_forward);\n    fftw_destroy_plan(plan_backward);\n    fftw_free(out);\n}\n\nvoid WfnExtrapolation::onSurface(WfnCube& wfn, Uint nKX, Uint nKY){\n    using namespace blitz;\n    time_t t;\n    \n    // Need some info on the grid\n    // SI units energy: 2 m E/hbar^2 a0 = 2 E/Ha\n    Uint nX = hartree.nX(), nY = hartree.nY(), nZ = zEndIndex + 1;\n    Real dX = hartree.dX(), dY = hartree.dY(), dZ = hartree.dZ();\n    Real dKX = 2 * M_PI * dZ / (dX * Real(nX));\n    Real dKY = 2 * M_PI * dZ / (dY * Real(nY));\n    \n    Array<types::Real,3> dataArray(\n            &(wfn.grid.data[0]),\n            shape(nX, nY, nZ),\n            neverDeleteData);\n    Real E = wfn.getEnergy() * dZ * dZ;\n\n    int nK = nKX * nKY;\n   \n    // Instead of a wave-number based criterion that is the\n    // same for all wave functions, we may also choose some adaptive\n    // criterion such as the one below (upper limit for z-decay of\n    // involved basis functions.\n//    // May choose to reduce k-grid \n//    Real kXMax = nKX/2.0 * dKX;\n//    Real kYMax = nKY/2.0 * dKY;\n//    // Take only low-freq. Fourier components such that no basis function\n//    // decays faster than f(z) \\propto 10^{-minExpGoal * z}\n//    Uint zSpan = zSurfEndIndex - zStartIndex;\n//\n//    // Translate decayCutoff to minimum exponent per z-index\n//    Real minExpGoal = this->decayCutoff * dZ * log(10.0);   \n//    Real scaling = sqrt( (minExpGoal * minExpGoal + 2*E)\n//            / (kXMax * kXMax + kYMax * kYMax) );\n//    if(scaling < 1.0){\n//        nKX = int( scaling * nX); kXMax = nKX/2.0 * dKX;\n//        nKY = int( scaling * nY); kYMax = nKY/2.0 * dKY;\n//        std::cout << \"Reduced wave vector grid: kx,ky = \" << nKX << \",\" << nKY << \"\\n\";\n//    }\n//    Real minExp = - sqrt( -2.0 * E + kXMax * kXMax + kYMax * kYMax);\n//    std::cout << \"Strongest considered decay: x \" << exp(minExp/dZ) << \" per a.u.\\n\";\n//    minExp *= Real(zSurfEndIndex) - Real(zStartIndex);\n//    std::cout << \"Smallest exponential term in matrix: \" << exp(minExp) << \"\\n\";\n        \n    \n\n    // Build matrix for modified discrete Hartley transform\n    Uint n = nX * nY;\n    std::cout << \"Matrix dimension is \" << n << \"x\" << nK \n        << \", i.e. \" << Real(nLayers*n*nK*8)  / (1024.0 * 1024.0) << \" MBytes per matrix\\n\";\n    //exit(0); \n    //        // Test: Extrapolation on plane\n    //        for(int i = 0; i < zIndices.size();++i){\n    //            zIndices[i] = 128;\n    //        }\n    //        this->zSurfEndIndex = 128;\n    //        this->zStartIndex = 128;\n    //        E = -0.160023 * dZ * dZ;\n\n    std::vector<Real> A(n*nK*nLayers);\n    int iX, iY, jX, jY;\n    Real kX, kY, kZ;\n    Real arg;\n    t = clock();\n\n\n    for(Uint j = 0; j < nK; ++j){\n        jX = j / nKY; jX = (2* jX < nKX) ? jX : jX - nKX;\n        jY = j % nKY; jY = (2* jY < nKY) ? jY : jY - nKY;\n\n        kX = jX * dKX;\n        kY = jY * dKY;\n        kZ = sqrt( -2.0 * E + kX * kX+ kY * kY);\n\n        for(Uint i = 0; i < n; ++i){\n            iX = i / nY; iY = i % nY;\n            arg = 2.0 * M_PI * ( Real(iX * jX) / Real(nX)  + Real(iY * jY) / Real(nY) );\n\n            for(Uint l = 0; l < nLayers; ++l){\n                // Need transposed matrix for Fortran\n                A[l*n+i + j*n*nLayers] = (sin(arg) + cos(arg)) *\n                    exp(- kZ * (int(zIndices[i]) - int(l) - int(zStartIndex) ) );\n            }\n        }\n    }\n    std::cout << \"Matrix created in : \" << (clock() -t)/1000.0 << \" ms\\n\";\n\n\n    // Prepare wave function values\n    int iZ;\n    std::vector<Real> hartley(n*nLayers);\n    for(Uint l = 0; l < nLayers; ++l){\n        for(Uint i = 0; i < n; ++i){\n            iX = i/nY;\n            iY = i%nY;\n            iZ = int(zIndices[i]) - int(l);\n            hartley[l*n + i] = wfn.grid.data[iX*nY*nZ+ iY*nZ + iZ];\n        }\n    }\n\n\n    // Solve the linear system\n    char TRANS_ = 'N';\n    int  M_     = n*nLayers;\n    int  N_     = nK;\n    int  NRHS_  = 1;\n    std::vector<Real> S(N_);\n    Real RCOND_ = 1e-5;\n    int  RANK_;\n    std::vector<Real> WORK(1);\n    int  LWORK_ = -1;\n    std::vector<int> IWORK(1);\n    int  ILWORK_ = -1;\n    int  INFO_  = 0;\n    // Writes correct WORK dimensions to WORK[0], IWORK[0]\n    // SUBROUTINE DGELSD( M, N, NRHS, A, LDA, B, LDB, S, RCOND, RANK,\n    //                   WORK, LWORK, IWORK, INFO )\n    dgelsd_(&M_, &N_, &NRHS_, \n            &*A.begin(), &M_, \n            &*hartley.begin(), &M_, \n            &*S.begin(), &RCOND_, &RANK_,\n            &*WORK.begin(), &LWORK_, &*IWORK.begin(),\n            &INFO_);\n    LWORK_ = int(abs(WORK[0])); \n    WORK =  std::vector<Real>(LWORK_);\n    ILWORK_ = int(abs(IWORK[0])); \n    IWORK =  std::vector<int>(ILWORK_);\n\n    // Now solve this little puzzle\n    std::cout << \"Starting optimization of overdetermined system\\n\"; \n    t = clock();\n\n    dgelsd_(&M_, &N_, &NRHS_, \n            &*A.begin(), &M_, \n            &*hartley.begin(), &M_, \n            &*S.begin(), &RCOND_, &RANK_,\n            &*WORK.begin(), &LWORK_, &*IWORK.begin(),\n            &INFO_);\n    //        dgels_(&TRANS_, &M_, &N_, &NRHS_, \n    //                &*A.begin(), &M_, \n    //                &*hartley.begin(), &M_, \n    //                &*WORK.begin(), &LWORK_,\n    //                &INFO_);\n    if( INFO_ != 0 ){\n        throw types::runtimeError() \n            << types::errinfo_runtime(\"LAPACK Error: Problem with solution of least-squares problem.\");\n    }\n    std::cout << \"Found solution in : \" << (clock() -t)/1000.0 << \" ms\\n\";\n\n    // Print condition number of problem\n    std::cout << \"Condition number: \" << S[0] / S[nK -1] << \"\\n\";\n\n    //        // Plotting the coefficients of the hartley transform\n    //        types::String s = formats::gnuplot::writeMatrix<Real>(hartley, nKX, nKY);\n    //        String hartleyFile = io::getFileName(wfn->getFileName()) + \".hartley\";\n    //        io::writeStream(hartleyFile, s);\n\n    // Re-layout hartley components to nX-nY\n    std::vector<Real> tmp = hartley;\n    hartley = std::vector<Real>(nX*nY, 0.0);\n    Real i2, j2;\n    for(int i = 0; i < nKX; ++i){\n        i2 = (2 * i < nKX) ? i :  int(nX) + i - nKX ;\n        for(int j = 0; j < nKY; ++j){\n            j2 = (2 * j < nKY) ? j : int(nY) + j - nKY;\n            hartley[i2 * nY + j2] = tmp[i* nKY + j];\n        }\n    }\n\n    //        // Plotting the coefficients of the reformed hartley transform\n    //        s = formats::gnuplot::writeMatrix<Real>(hartley, nX, nY);\n    //        hartleyFile = io::getFileName(wfn->getFileName()) + \".hartley2\";\n    //        io::writeStream(hartleyFile, s);\n\n    // Producing Fourier transform\n    int nXF = nX; int nYF = nY/2 +1;\n    std::vector<Complex> fourier(nXF*nYF);\n    int iT,jT;\n    for(int i = 0; i < nXF; ++i){\n        for(int j = 0; j < nYF; ++j){\n            iT = (int(nX) - i) % nX;\n            jT = (int(nY) - j) % nY;\n\n            fourier[i*nYF+j] = \n                1/2.0 * (               hartley[i*nY+j] + hartley[iT*nY+jT]  \n                        - Complex(0,1.0)*( hartley[i*nY+j] - hartley[iT*nY+jT]) );\n        }\n    }\n\n    \n    // Plotting the coefficients of the Fourier transform\n    std::vector<Real> fourierReal(fourier.size());\n    for(int i =0;i<fourierReal.size();++i)\n        fourierReal[i] = abs(fourier[i]);\n    String s = formats::gnuplot::writeMatrix<Real>(fourierReal, nXF, nYF);\n    String fileName = io::getFileName(wfn.getFileName()) + \".fourier\";\n    io::writeStream(fileName, s);\n\n\n    // Calculating the exponential prefactors to propagate coefficients to\n    // next z plane\n    t = clock();\n    std::vector<Real> pref(nXF*nYF);    \n    for(int i = 0; i < nXF; ++i){\n        kX = (2*i < nX) ? i : i - int(nX) ;\n        kX *= dKX;\n        for(int j = 0; j < nYF; ++j){\n            kY = (2*j < nY) ? j : j - int(nY);\n            kY *= dKY;\n            kZ = sqrt( -2.0 * E + kX * kX+ kY * kY);\n            pref[i*nYF + j] = exp(- kZ );\n        }\n    }\n\n\n    Array<types::Real,2> prefactors(\n            &pref[0],\n            shape(nXF, nYF),\n            neverDeleteData);\n\n    Array<types::Complex,2> planeFourier(\n            &fourier[0],\n            shape(nXF, nYF),\n            neverDeleteData);\n\n    Array<types::Complex,2> tempFourier(nXF, nYF);\n    Array<types::Real,2> tempDirect(nX, nY);\n    fftw_plan plan_backward;\n\n    for(int zIndex = zStartIndex+1; zIndex < nZ; ++zIndex) {\n        // Propagate hartley coefficients (could use matmul here)\n        planeFourier = prefactors(tensor::i, tensor::j) * planeFourier(tensor::i, tensor::j);\n\n        // The c2r transform destroys its input\n        tempFourier = planeFourier;\n        plan_backward = fftw_plan_dft_c2r_2d(\n                nX, nY, \n                (fftw_complex*) tempFourier.data(), \n                tempDirect.data(), \n                FFTW_ESTIMATE);\n\n        // Perform Fourier transform backwards\n        fftw_execute(plan_backward);\n\n        // Copy data\n        if (zIndex > zSurfEndIndex) \n            dataArray(Range::all(), Range::all(), zIndex) = tempDirect(Range::all(), Range::all());\n        else {\n            for(int x = 0; x < nX; ++x){\n                for(int y = 0; y < nY; ++y){\n                    if (zIndex > zIndices[x*nY + y]) {\n                        dataArray(x, y, zIndex) = tempDirect(x, y);\n                    }\n                }\n            }\n        }\n\n    }\n    fftw_destroy_plan(plan_backward);\n\n}\n\n}\n}\n", "meta": {"hexsha": "677083e21d77b3f0375a0b39db1ee4ce798b3b2d", "size": 32334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/formats/stm.cpp", "max_stars_repo_name": "ltalirz/util-programs", "max_stars_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "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": "lib/formats/stm.cpp", "max_issues_repo_name": "ltalirz/util-programs", "max_issues_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_issues_repo_licenses": ["MIT"], "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/formats/stm.cpp", "max_forks_repo_name": "ltalirz/util-programs", "max_forks_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_forks_repo_licenses": ["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.2158730159, "max_line_length": 181, "alphanum_fraction": 0.5315766685, "num_tokens": 9555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.18839832707528617}}
{"text": "/*\r\n* Botan 2.4.0 Amalgamation\r\n* (C) 1999-2018 The Botan Authors\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n#include \"stdafx.h\"\r\n#include <lax/util/botan/botan_all.h>\r\n#include <lax/util/botan/botan_all_internal.h>\r\n\r\n/*\r\n* AES\r\n* (C) 1999-2010,2015,2017 Jack Lloyd\r\n*\r\n* Based on the public domain reference implementation by Paulo Baretto\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n/*\r\n* This implementation is based on table lookups which are known to be\r\n* vulnerable to timing and cache based side channel attacks. Some\r\n* countermeasures are used which may be helpful in some situations:\r\n*\r\n* - Only a single 256-word T-table is used, with rotations applied.\r\n*   Most implementations use 4 T-tables which leaks much more\r\n*   information via cache usage.\r\n*\r\n* - The TE and TD tables are computed at runtime to avoid flush+reload\r\n*   attacks using clflush. As different processes will not share the\r\n*   same underlying table data, an attacker can't manipulate another\r\n*   processes cache lines via their shared reference to the library\r\n*   read only segment.\r\n*\r\n* - Each cache line of the lookup tables is accessed at the beginning\r\n*   of each call to encrypt or decrypt. (See the Z variable below)\r\n*\r\n* If available SSSE3 or AES-NI are used instead of this version, as both\r\n* are faster and immune to side channel attacks.\r\n*\r\n* Some AES cache timing papers for reference:\r\n*\r\n* \"Software mitigations to hedge AES against cache-based software side\r\n* channel vulnerabilities\" https://eprint.iacr.org/2006/052.pdf\r\n*\r\n* \"Cache Games - Bringing Access-Based Cache Attacks on AES to Practice\"\r\n* http://www.ieee-security.org/TC/SP2011/PAPERS/2011/paper031.pdf\r\n*\r\n* \"Cache-Collision Timing Attacks Against AES\" Bonneau, Mironov\r\n* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.88.4753\r\n*/\r\n\r\nnamespace Botan {\r\n\r\nnamespace {\r\n\r\nBOTAN_ALIGNAS(64)\r\nconst uint8_t SE[256] = {\r\n   0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B,\r\n   0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,\r\n   0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26,\r\n   0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\r\n   0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2,\r\n   0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,\r\n   0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED,\r\n   0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\r\n   0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F,\r\n   0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,\r\n   0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC,\r\n   0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\r\n   0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14,\r\n   0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,\r\n   0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D,\r\n   0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\r\n   0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F,\r\n   0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,\r\n   0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11,\r\n   0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\r\n   0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F,\r\n   0xB0, 0x54, 0xBB, 0x16 };\r\n\r\nBOTAN_ALIGNAS(64)\r\nconst uint8_t SD[256] = {\r\n   0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E,\r\n   0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87,\r\n   0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32,\r\n   0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,\r\n   0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49,\r\n   0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16,\r\n   0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50,\r\n   0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,\r\n   0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05,\r\n   0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02,\r\n   0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41,\r\n   0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,\r\n   0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8,\r\n   0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89,\r\n   0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B,\r\n   0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,\r\n   0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59,\r\n   0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D,\r\n   0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D,\r\n   0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,\r\n   0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63,\r\n   0x55, 0x21, 0x0C, 0x7D };\r\n\r\ninline uint8_t xtime(uint8_t s) { return static_cast<uint8_t>(s << 1) ^ ((s >> 7) * 0x1B); }\r\ninline uint8_t xtime4(uint8_t s) { return xtime(xtime(s)); }\r\ninline uint8_t xtime8(uint8_t s) { return xtime(xtime(xtime(s))); }\r\n\r\ninline uint8_t xtime3(uint8_t s) { return xtime(s) ^ s; }\r\ninline uint8_t xtime9(uint8_t s) { return xtime8(s) ^ s; }\r\ninline uint8_t xtime11(uint8_t s) { return xtime8(s) ^ xtime(s) ^ s; }\r\ninline uint8_t xtime13(uint8_t s) { return xtime8(s) ^ xtime4(s) ^ s; }\r\ninline uint8_t xtime14(uint8_t s) { return xtime8(s) ^ xtime4(s) ^ xtime(s); }\r\n\r\ninline uint32_t SE_word(uint32_t x)\r\n   {\r\n   return make_uint32(SE[get_byte(0, x)],\r\n                      SE[get_byte(1, x)],\r\n                      SE[get_byte(2, x)],\r\n                      SE[get_byte(3, x)]);\r\n   }\r\n\r\nconst uint32_t* AES_TE()\r\n   {\r\n   class TE_Table final\r\n      {\r\n      public:\r\n         TE_Table()\r\n            {\r\n            uint32_t* p = reinterpret_cast<uint32_t*>(&data);\r\n            for(size_t i = 0; i != 256; ++i)\r\n               {\r\n               const uint8_t s = SE[i];\r\n               p[i] = make_uint32(xtime(s), s, s, xtime3(s));\r\n               }\r\n            }\r\n\r\n         const uint32_t* ptr() const\r\n            {\r\n            return reinterpret_cast<const uint32_t*>(&data);\r\n            }\r\n      private:\r\n         std::aligned_storage<256*sizeof(uint32_t), 64>::type data;\r\n      };\r\n\r\n   static TE_Table table;\r\n   return table.ptr();\r\n   }\r\n\r\nconst uint32_t* AES_TD()\r\n   {\r\n   class TD_Table final\r\n      {\r\n      public:\r\n         TD_Table()\r\n            {\r\n            uint32_t* p = reinterpret_cast<uint32_t*>(&data);\r\n            for(size_t i = 0; i != 256; ++i)\r\n               {\r\n               const uint8_t s = SD[i];\r\n               p[i] = make_uint32(xtime14(s), xtime9(s), xtime13(s), xtime11(s));\r\n               }\r\n            }\r\n\r\n         const uint32_t* ptr() const\r\n            {\r\n            return reinterpret_cast<const uint32_t*>(&data);\r\n            }\r\n      private:\r\n         std::aligned_storage<256*sizeof(uint32_t), 64>::type data;\r\n      };\r\n\r\n   static TD_Table table;\r\n   return table.ptr();\r\n   }\r\n\r\n#define AES_T(T, K, V0, V1, V2, V3)                                     \\\r\n   (K ^ T[get_byte(0, V0)] ^                                            \\\r\n    rotr< 8>(T[get_byte(1, V1)]) ^                                      \\\r\n    rotr<16>(T[get_byte(2, V2)]) ^                                      \\\r\n    rotr<24>(T[get_byte(3, V3)]))\r\n\r\n/*\r\n* AES Encryption\r\n*/\r\nvoid aes_encrypt_n(const uint8_t in[], uint8_t out[],\r\n                   size_t blocks,\r\n                   const secure_vector<uint32_t>& EK,\r\n                   const secure_vector<uint8_t>& ME)\r\n   {\r\n   BOTAN_ASSERT(EK.size() && ME.size() == 16, \"Key was set\");\r\n\r\n   const size_t cache_line_size = CPUID::cache_line_size();\r\n\r\n   const uint32_t* TE = AES_TE();\r\n\r\n   // Hit every cache line of TE\r\n   volatile uint32_t Z = 0;\r\n   for(size_t i = 0; i < 256; i += cache_line_size / sizeof(uint32_t))\r\n      {\r\n      Z |= TE[i];\r\n      }\r\n   Z &= TE[82]; // this is zero, which hopefully the compiler cannot deduce\r\n\r\n   for(size_t i = 0; i < blocks; ++i)\r\n      {\r\n      uint32_t T0, T1, T2, T3;\r\n      load_be(in + 16*i, T0, T1, T2, T3);\r\n\r\n      T0 ^= EK[0];\r\n      T1 ^= EK[1];\r\n      T2 ^= EK[2];\r\n      T3 ^= EK[3];\r\n\r\n      T0 ^= Z;\r\n\r\n      uint32_t B0 = AES_T(TE, EK[4], T0, T1, T2, T3);\r\n      uint32_t B1 = AES_T(TE, EK[5], T1, T2, T3, T0);\r\n      uint32_t B2 = AES_T(TE, EK[6], T2, T3, T0, T1);\r\n      uint32_t B3 = AES_T(TE, EK[7], T3, T0, T1, T2);\r\n\r\n      for(size_t r = 2*4; r < EK.size(); r += 2*4)\r\n         {\r\n         T0 = AES_T(TE, EK[r  ], B0, B1, B2, B3);\r\n         T1 = AES_T(TE, EK[r+1], B1, B2, B3, B0);\r\n         T2 = AES_T(TE, EK[r+2], B2, B3, B0, B1);\r\n         T3 = AES_T(TE, EK[r+3], B3, B0, B1, B2);\r\n\r\n         B0 = AES_T(TE, EK[r+4], T0, T1, T2, T3);\r\n         B1 = AES_T(TE, EK[r+5], T1, T2, T3, T0);\r\n         B2 = AES_T(TE, EK[r+6], T2, T3, T0, T1);\r\n         B3 = AES_T(TE, EK[r+7], T3, T0, T1, T2);\r\n         }\r\n\r\n      /*\r\n      * Use TE[x] >> 8 instead of SE[] so encryption only references a single\r\n      * lookup table.\r\n      */\r\n      out[16*i+ 0] = static_cast<uint8_t>(TE[get_byte(0, B0)] >> 8) ^ ME[0];\r\n      out[16*i+ 1] = static_cast<uint8_t>(TE[get_byte(1, B1)] >> 8) ^ ME[1];\r\n      out[16*i+ 2] = static_cast<uint8_t>(TE[get_byte(2, B2)] >> 8) ^ ME[2];\r\n      out[16*i+ 3] = static_cast<uint8_t>(TE[get_byte(3, B3)] >> 8) ^ ME[3];\r\n      out[16*i+ 4] = static_cast<uint8_t>(TE[get_byte(0, B1)] >> 8) ^ ME[4];\r\n      out[16*i+ 5] = static_cast<uint8_t>(TE[get_byte(1, B2)] >> 8) ^ ME[5];\r\n      out[16*i+ 6] = static_cast<uint8_t>(TE[get_byte(2, B3)] >> 8) ^ ME[6];\r\n      out[16*i+ 7] = static_cast<uint8_t>(TE[get_byte(3, B0)] >> 8) ^ ME[7];\r\n      out[16*i+ 8] = static_cast<uint8_t>(TE[get_byte(0, B2)] >> 8) ^ ME[8];\r\n      out[16*i+ 9] = static_cast<uint8_t>(TE[get_byte(1, B3)] >> 8) ^ ME[9];\r\n      out[16*i+10] = static_cast<uint8_t>(TE[get_byte(2, B0)] >> 8) ^ ME[10];\r\n      out[16*i+11] = static_cast<uint8_t>(TE[get_byte(3, B1)] >> 8) ^ ME[11];\r\n      out[16*i+12] = static_cast<uint8_t>(TE[get_byte(0, B3)] >> 8) ^ ME[12];\r\n      out[16*i+13] = static_cast<uint8_t>(TE[get_byte(1, B0)] >> 8) ^ ME[13];\r\n      out[16*i+14] = static_cast<uint8_t>(TE[get_byte(2, B1)] >> 8) ^ ME[14];\r\n      out[16*i+15] = static_cast<uint8_t>(TE[get_byte(3, B2)] >> 8) ^ ME[15];\r\n      }\r\n   }\r\n\r\n/*\r\n* AES Decryption\r\n*/\r\nvoid aes_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks,\r\n                   const secure_vector<uint32_t>& DK,\r\n                   const secure_vector<uint8_t>& MD)\r\n   {\r\n   BOTAN_ASSERT(DK.size() && MD.size() == 16, \"Key was set\");\r\n\r\n   const size_t cache_line_size = CPUID::cache_line_size();\r\n   const uint32_t* TD = AES_TD();\r\n\r\n   volatile uint32_t Z = 0;\r\n   for(size_t i = 0; i < 256; i += cache_line_size / sizeof(uint32_t))\r\n      {\r\n      Z |= TD[i];\r\n      }\r\n   Z &= TD[99]; // this is zero, which hopefully the compiler cannot deduce\r\n\r\n   for(size_t i = 0; i != blocks; ++i)\r\n      {\r\n      uint32_t T0 = load_be<uint32_t>(in, 0) ^ DK[0];\r\n      uint32_t T1 = load_be<uint32_t>(in, 1) ^ DK[1];\r\n      uint32_t T2 = load_be<uint32_t>(in, 2) ^ DK[2];\r\n      uint32_t T3 = load_be<uint32_t>(in, 3) ^ DK[3];\r\n\r\n      T0 ^= Z;\r\n\r\n      uint32_t B0 = AES_T(TD, DK[4], T0, T3, T2, T1);\r\n      uint32_t B1 = AES_T(TD, DK[5], T1, T0, T3, T2);\r\n      uint32_t B2 = AES_T(TD, DK[6], T2, T1, T0, T3);\r\n      uint32_t B3 = AES_T(TD, DK[7], T3, T2, T1, T0);\r\n\r\n      for(size_t r = 2*4; r < DK.size(); r += 2*4)\r\n         {\r\n         T0 = AES_T(TD, DK[r  ], B0, B3, B2, B1);\r\n         T1 = AES_T(TD, DK[r+1], B1, B0, B3, B2);\r\n         T2 = AES_T(TD, DK[r+2], B2, B1, B0, B3);\r\n         T3 = AES_T(TD, DK[r+3], B3, B2, B1, B0);\r\n\r\n         B0 = AES_T(TD, DK[r+4], T0, T3, T2, T1);\r\n         B1 = AES_T(TD, DK[r+5], T1, T0, T3, T2);\r\n         B2 = AES_T(TD, DK[r+6], T2, T1, T0, T3);\r\n         B3 = AES_T(TD, DK[r+7], T3, T2, T1, T0);\r\n         }\r\n\r\n      out[ 0] = SD[get_byte(0, B0)] ^ MD[0];\r\n      out[ 1] = SD[get_byte(1, B3)] ^ MD[1];\r\n      out[ 2] = SD[get_byte(2, B2)] ^ MD[2];\r\n      out[ 3] = SD[get_byte(3, B1)] ^ MD[3];\r\n      out[ 4] = SD[get_byte(0, B1)] ^ MD[4];\r\n      out[ 5] = SD[get_byte(1, B0)] ^ MD[5];\r\n      out[ 6] = SD[get_byte(2, B3)] ^ MD[6];\r\n      out[ 7] = SD[get_byte(3, B2)] ^ MD[7];\r\n      out[ 8] = SD[get_byte(0, B2)] ^ MD[8];\r\n      out[ 9] = SD[get_byte(1, B1)] ^ MD[9];\r\n      out[10] = SD[get_byte(2, B0)] ^ MD[10];\r\n      out[11] = SD[get_byte(3, B3)] ^ MD[11];\r\n      out[12] = SD[get_byte(0, B3)] ^ MD[12];\r\n      out[13] = SD[get_byte(1, B2)] ^ MD[13];\r\n      out[14] = SD[get_byte(2, B1)] ^ MD[14];\r\n      out[15] = SD[get_byte(3, B0)] ^ MD[15];\r\n\r\n      in += 16;\r\n      out += 16;\r\n      }\r\n   }\r\n\r\nvoid aes_key_schedule(const uint8_t key[], size_t length,\r\n                      secure_vector<uint32_t>& EK,\r\n                      secure_vector<uint32_t>& DK,\r\n                      secure_vector<uint8_t>& ME,\r\n                      secure_vector<uint8_t>& MD)\r\n   {\r\n   static const uint32_t RC[10] = {\r\n      0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,\r\n      0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000 };\r\n\r\n   const size_t rounds = (length / 4) + 6;\r\n\r\n   secure_vector<uint32_t> XEK(length + 32), XDK(length + 32);\r\n\r\n   const size_t X = length / 4;\r\n\r\n   // Can't happen, but make static analyzers happy\r\n   if(X != 4 && X != 6 && X != 8)\r\n      throw Invalid_Argument(\"Invalid AES key size\");\r\n\r\n   for(size_t i = 0; i != X; ++i)\r\n      XEK[i] = load_be<uint32_t>(key, i);\r\n\r\n   for(size_t i = X; i < 4*(rounds+1); i += X)\r\n      {\r\n      XEK[i] = XEK[i-X] ^ RC[(i-X)/X] ^ SE_word(rotl<8>(XEK[i-1]));\r\n\r\n      for(size_t j = 1; j != X; ++j)\r\n         {\r\n         XEK[i+j] = XEK[i+j-X];\r\n\r\n         if(X == 8 && j == 4)\r\n            XEK[i+j] ^= SE_word(XEK[i+j-1]);\r\n         else\r\n            XEK[i+j] ^= XEK[i+j-1];\r\n         }\r\n      }\r\n\r\n   for(size_t i = 0; i != 4*(rounds+1); i += 4)\r\n      {\r\n      XDK[i  ] = XEK[4*rounds-i  ];\r\n      XDK[i+1] = XEK[4*rounds-i+1];\r\n      XDK[i+2] = XEK[4*rounds-i+2];\r\n      XDK[i+3] = XEK[4*rounds-i+3];\r\n      }\r\n\r\n   for(size_t i = 4; i != length + 24; ++i)\r\n      {\r\n      XDK[i] = SE_word(XDK[i]);\r\n      XDK[i] = AES_T(AES_TD(), 0, XDK[i], XDK[i], XDK[i], XDK[i]);\r\n      }\r\n\r\n   ME.resize(16);\r\n   MD.resize(16);\r\n\r\n   for(size_t i = 0; i != 4; ++i)\r\n      {\r\n      store_be(XEK[i+4*rounds], &ME[4*i]);\r\n      store_be(XEK[i], &MD[4*i]);\r\n      }\r\n\r\n   EK.resize(length + 24);\r\n   DK.resize(length + 24);\r\n   copy_mem(EK.data(), XEK.data(), EK.size());\r\n   copy_mem(DK.data(), XDK.data(), DK.size());\r\n\r\n#if defined(BOTAN_HAS_AES_ARMV8)\r\n   if(CPUID::has_arm_aes())\r\n      {\r\n      // ARM needs the subkeys to be byte reversed\r\n\r\n      for(size_t i = 0; i != EK.size(); ++i)\r\n         EK[i] = reverse_bytes(EK[i]);\r\n      for(size_t i = 0; i != DK.size(); ++i)\r\n         DK[i] = reverse_bytes(DK[i]);\r\n      }\r\n#endif\r\n\r\n   }\r\n\r\n#undef AES_T\r\n\r\nsize_t aes_parallelism()\r\n   {\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return 4;\r\n      }\r\n#endif\r\n\r\n   return 1;\r\n   }\r\n\r\nconst char* aes_provider()\r\n   {\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return \"aesni\";\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return \"ssse3\";\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_ARMV8)\r\n   if(CPUID::has_arm_aes())\r\n      {\r\n      return \"armv8\";\r\n      }\r\n#endif\r\n\r\n   return \"base\";\r\n   }\r\n\r\n}\r\n\r\nstd::string AES_128::provider() const { return aes_provider(); }\r\nstd::string AES_192::provider() const { return aes_provider(); }\r\nstd::string AES_256::provider() const { return aes_provider(); }\r\n\r\nsize_t AES_128::parallelism() const { return aes_parallelism(); }\r\nsize_t AES_192::parallelism() const { return aes_parallelism(); }\r\nsize_t AES_256::parallelism() const { return aes_parallelism(); }\r\n\r\nvoid AES_128::encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const\r\n   {\r\n   verify_key_set(m_EK.empty() == false);\r\n\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_ARMV8)\r\n   if(CPUID::has_arm_aes())\r\n      {\r\n      return armv8_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n   aes_encrypt_n(in, out, blocks, m_EK, m_ME);\r\n   }\r\n\r\nvoid AES_128::decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const\r\n   {\r\n   verify_key_set(m_DK.empty() == false);\r\n\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_ARMV8)\r\n   if(CPUID::has_arm_aes())\r\n      {\r\n      return armv8_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n   aes_decrypt_n(in, out, blocks, m_DK, m_MD);\r\n   }\r\n\r\nvoid AES_128::key_schedule(const uint8_t key[], size_t length)\r\n   {\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_key_schedule(key, length);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_key_schedule(key, length);\r\n      }\r\n#endif\r\n\r\n   aes_key_schedule(key, length, m_EK, m_DK, m_ME, m_MD);\r\n   }\r\n\r\nvoid AES_128::clear()\r\n   {\r\n   zap(m_EK);\r\n   zap(m_DK);\r\n   zap(m_ME);\r\n   zap(m_MD);\r\n   }\r\n\r\nvoid AES_192::encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const\r\n   {\r\n   verify_key_set(m_EK.empty() == false);\r\n\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_ARMV8)\r\n   if(CPUID::has_arm_aes())\r\n      {\r\n      return armv8_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n   aes_encrypt_n(in, out, blocks, m_EK, m_ME);\r\n   }\r\n\r\nvoid AES_192::decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const\r\n   {\r\n   verify_key_set(m_DK.empty() == false);\r\n\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_ARMV8)\r\n   if(CPUID::has_arm_aes())\r\n      {\r\n      return armv8_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n   aes_decrypt_n(in, out, blocks, m_DK, m_MD);\r\n   }\r\n\r\nvoid AES_192::key_schedule(const uint8_t key[], size_t length)\r\n   {\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_key_schedule(key, length);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_key_schedule(key, length);\r\n      }\r\n#endif\r\n\r\n   aes_key_schedule(key, length, m_EK, m_DK, m_ME, m_MD);\r\n   }\r\n\r\nvoid AES_192::clear()\r\n   {\r\n   zap(m_EK);\r\n   zap(m_DK);\r\n   zap(m_ME);\r\n   zap(m_MD);\r\n   }\r\n\r\nvoid AES_256::encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const\r\n   {\r\n   verify_key_set(m_EK.empty() == false);\r\n\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_ARMV8)\r\n   if(CPUID::has_arm_aes())\r\n      {\r\n      return armv8_encrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n   aes_encrypt_n(in, out, blocks, m_EK, m_ME);\r\n   }\r\n\r\nvoid AES_256::decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const\r\n   {\r\n   verify_key_set(m_DK.empty() == false);\r\n\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_ARMV8)\r\n   if(CPUID::has_arm_aes())\r\n      {\r\n      return armv8_decrypt_n(in, out, blocks);\r\n      }\r\n#endif\r\n\r\n   aes_decrypt_n(in, out, blocks, m_DK, m_MD);\r\n   }\r\n\r\nvoid AES_256::key_schedule(const uint8_t key[], size_t length)\r\n   {\r\n#if defined(BOTAN_HAS_AES_NI)\r\n   if(CPUID::has_aes_ni())\r\n      {\r\n      return aesni_key_schedule(key, length);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AES_SSSE3)\r\n   if(CPUID::has_ssse3())\r\n      {\r\n      return ssse3_key_schedule(key, length);\r\n      }\r\n#endif\r\n\r\n   aes_key_schedule(key, length, m_EK, m_DK, m_ME, m_MD);\r\n   }\r\n\r\nvoid AES_256::clear()\r\n   {\r\n   zap(m_EK);\r\n   zap(m_DK);\r\n   zap(m_ME);\r\n   zap(m_MD);\r\n   }\r\n\r\n}\r\n/*\r\n* SCAN Name Abstraction\r\n* (C) 2008-2009,2015 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\nnamespace {\r\n\r\nstd::string make_arg(\r\n   const std::vector<std::pair<size_t, std::string> >& name, size_t start)\r\n   {\r\n   std::string output = name[start].second;\r\n   size_t level = name[start].first;\r\n\r\n   size_t paren_depth = 0;\r\n\r\n   for(size_t i = start + 1; i != name.size(); ++i)\r\n      {\r\n      if(name[i].first <= name[start].first)\r\n         break;\r\n\r\n      if(name[i].first > level)\r\n         {\r\n         output += \"(\" + name[i].second;\r\n         ++paren_depth;\r\n         }\r\n      else if(name[i].first < level)\r\n         {\r\n         output += \"),\" + name[i].second;\r\n         --paren_depth;\r\n         }\r\n      else\r\n         {\r\n         if(output[output.size() - 1] != '(')\r\n            output += \",\";\r\n         output += name[i].second;\r\n         }\r\n\r\n      level = name[i].first;\r\n      }\r\n\r\n   for(size_t i = 0; i != paren_depth; ++i)\r\n      output += \")\";\r\n\r\n   return output;\r\n   }\r\n\r\n}\r\n\r\nSCAN_Name::SCAN_Name(const char* algo_spec) : SCAN_Name(std::string(algo_spec))\r\n   {\r\n   }\r\n\r\nSCAN_Name::SCAN_Name(std::string algo_spec) : m_orig_algo_spec(algo_spec), m_alg_name(), m_args(), m_mode_info()\r\n   {\r\n   std::vector<std::pair<size_t, std::string> > name;\r\n   size_t level = 0;\r\n   std::pair<size_t, std::string> accum = std::make_pair(level, \"\");\r\n\r\n   const std::string decoding_error = \"Bad SCAN name '\" + algo_spec + \"': \";\r\n\r\n   for(size_t i = 0; i != algo_spec.size(); ++i)\r\n      {\r\n      char c = algo_spec[i];\r\n\r\n      if(c == '/' || c == ',' || c == '(' || c == ')')\r\n         {\r\n         if(c == '(')\r\n            ++level;\r\n         else if(c == ')')\r\n            {\r\n            if(level == 0)\r\n               throw Decoding_Error(decoding_error + \"Mismatched parens\");\r\n            --level;\r\n            }\r\n\r\n         if(c == '/' && level > 0)\r\n            accum.second.push_back(c);\r\n         else\r\n            {\r\n            if(accum.second != \"\")\r\n               name.push_back(accum);\r\n            accum = std::make_pair(level, \"\");\r\n            }\r\n         }\r\n      else\r\n         accum.second.push_back(c);\r\n      }\r\n\r\n   if(accum.second != \"\")\r\n      name.push_back(accum);\r\n\r\n   if(level != 0)\r\n      throw Decoding_Error(decoding_error + \"Missing close paren\");\r\n\r\n   if(name.size() == 0)\r\n      throw Decoding_Error(decoding_error + \"Empty name\");\r\n\r\n   m_alg_name = name[0].second;\r\n\r\n   bool in_modes = false;\r\n\r\n   for(size_t i = 1; i != name.size(); ++i)\r\n      {\r\n      if(name[i].first == 0)\r\n         {\r\n         m_mode_info.push_back(make_arg(name, i));\r\n         in_modes = true;\r\n         }\r\n      else if(name[i].first == 1 && !in_modes)\r\n         m_args.push_back(make_arg(name, i));\r\n      }\r\n   }\r\n\r\nstd::string SCAN_Name::arg(size_t i) const\r\n   {\r\n   if(i >= arg_count())\r\n      throw Invalid_Argument(\"SCAN_Name::arg \" + std::to_string(i) +\r\n                             \" out of range for '\" + as_string() + \"'\");\r\n   return m_args[i];\r\n   }\r\n\r\nstd::string SCAN_Name::arg(size_t i, const std::string& def_value) const\r\n   {\r\n   if(i >= arg_count())\r\n      return def_value;\r\n   return m_args[i];\r\n   }\r\n\r\nsize_t SCAN_Name::arg_as_integer(size_t i, size_t def_value) const\r\n   {\r\n   if(i >= arg_count())\r\n      return def_value;\r\n   return to_u32bit(m_args[i]);\r\n   }\r\n\r\n}\r\n/*\r\n* OctetString\r\n* (C) 1999-2007 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\n/*\r\n* Create an OctetString from RNG output\r\n*/\r\nOctetString::OctetString(RandomNumberGenerator& rng,\r\n                         size_t len)\r\n   {\r\n   m_data = rng.random_vec(len);\r\n   }\r\n\r\n/*\r\n* Create an OctetString from a hex string\r\n*/\r\nOctetString::OctetString(const std::string& hex_string)\r\n   {\r\n   m_data.resize(1 + hex_string.length() / 2);\r\n   m_data.resize(hex_decode(m_data.data(), hex_string));\r\n   }\r\n\r\n/*\r\n* Create an OctetString from a byte string\r\n*/\r\nOctetString::OctetString(const uint8_t in[], size_t n)\r\n   {\r\n   m_data.assign(in, in + n);\r\n   }\r\n\r\n/*\r\n* Set the parity of each key byte to odd\r\n*/\r\nvoid OctetString::set_odd_parity()\r\n   {\r\n   const uint8_t ODD_PARITY[256] = {\r\n      0x01, 0x01, 0x02, 0x02, 0x04, 0x04, 0x07, 0x07, 0x08, 0x08, 0x0B, 0x0B,\r\n      0x0D, 0x0D, 0x0E, 0x0E, 0x10, 0x10, 0x13, 0x13, 0x15, 0x15, 0x16, 0x16,\r\n      0x19, 0x19, 0x1A, 0x1A, 0x1C, 0x1C, 0x1F, 0x1F, 0x20, 0x20, 0x23, 0x23,\r\n      0x25, 0x25, 0x26, 0x26, 0x29, 0x29, 0x2A, 0x2A, 0x2C, 0x2C, 0x2F, 0x2F,\r\n      0x31, 0x31, 0x32, 0x32, 0x34, 0x34, 0x37, 0x37, 0x38, 0x38, 0x3B, 0x3B,\r\n      0x3D, 0x3D, 0x3E, 0x3E, 0x40, 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46,\r\n      0x49, 0x49, 0x4A, 0x4A, 0x4C, 0x4C, 0x4F, 0x4F, 0x51, 0x51, 0x52, 0x52,\r\n      0x54, 0x54, 0x57, 0x57, 0x58, 0x58, 0x5B, 0x5B, 0x5D, 0x5D, 0x5E, 0x5E,\r\n      0x61, 0x61, 0x62, 0x62, 0x64, 0x64, 0x67, 0x67, 0x68, 0x68, 0x6B, 0x6B,\r\n      0x6D, 0x6D, 0x6E, 0x6E, 0x70, 0x70, 0x73, 0x73, 0x75, 0x75, 0x76, 0x76,\r\n      0x79, 0x79, 0x7A, 0x7A, 0x7C, 0x7C, 0x7F, 0x7F, 0x80, 0x80, 0x83, 0x83,\r\n      0x85, 0x85, 0x86, 0x86, 0x89, 0x89, 0x8A, 0x8A, 0x8C, 0x8C, 0x8F, 0x8F,\r\n      0x91, 0x91, 0x92, 0x92, 0x94, 0x94, 0x97, 0x97, 0x98, 0x98, 0x9B, 0x9B,\r\n      0x9D, 0x9D, 0x9E, 0x9E, 0xA1, 0xA1, 0xA2, 0xA2, 0xA4, 0xA4, 0xA7, 0xA7,\r\n      0xA8, 0xA8, 0xAB, 0xAB, 0xAD, 0xAD, 0xAE, 0xAE, 0xB0, 0xB0, 0xB3, 0xB3,\r\n      0xB5, 0xB5, 0xB6, 0xB6, 0xB9, 0xB9, 0xBA, 0xBA, 0xBC, 0xBC, 0xBF, 0xBF,\r\n      0xC1, 0xC1, 0xC2, 0xC2, 0xC4, 0xC4, 0xC7, 0xC7, 0xC8, 0xC8, 0xCB, 0xCB,\r\n      0xCD, 0xCD, 0xCE, 0xCE, 0xD0, 0xD0, 0xD3, 0xD3, 0xD5, 0xD5, 0xD6, 0xD6,\r\n      0xD9, 0xD9, 0xDA, 0xDA, 0xDC, 0xDC, 0xDF, 0xDF, 0xE0, 0xE0, 0xE3, 0xE3,\r\n      0xE5, 0xE5, 0xE6, 0xE6, 0xE9, 0xE9, 0xEA, 0xEA, 0xEC, 0xEC, 0xEF, 0xEF,\r\n      0xF1, 0xF1, 0xF2, 0xF2, 0xF4, 0xF4, 0xF7, 0xF7, 0xF8, 0xF8, 0xFB, 0xFB,\r\n      0xFD, 0xFD, 0xFE, 0xFE };\r\n\r\n   for(size_t j = 0; j != m_data.size(); ++j)\r\n      m_data[j] = ODD_PARITY[m_data[j]];\r\n   }\r\n\r\n/*\r\n* Hex encode an OctetString\r\n*/\r\nstd::string OctetString::as_string() const\r\n   {\r\n   return hex_encode(m_data.data(), m_data.size());\r\n   }\r\n\r\n/*\r\n* XOR Operation for OctetStrings\r\n*/\r\nOctetString& OctetString::operator^=(const OctetString& k)\r\n   {\r\n   if(&k == this) { zeroise(m_data); return (*this); }\r\n   xor_buf(m_data.data(), k.begin(), std::min(length(), k.length()));\r\n   return (*this);\r\n   }\r\n\r\n/*\r\n* Equality Operation for OctetStrings\r\n*/\r\nbool operator==(const OctetString& s1, const OctetString& s2)\r\n   {\r\n   return (s1.bits_of() == s2.bits_of());\r\n   }\r\n\r\n/*\r\n* Unequality Operation for OctetStrings\r\n*/\r\nbool operator!=(const OctetString& s1, const OctetString& s2)\r\n   {\r\n   return !(s1 == s2);\r\n   }\r\n\r\n/*\r\n* Append Operation for OctetStrings\r\n*/\r\nOctetString operator+(const OctetString& k1, const OctetString& k2)\r\n   {\r\n   secure_vector<uint8_t> out;\r\n   out += k1.bits_of();\r\n   out += k2.bits_of();\r\n   return OctetString(out);\r\n   }\r\n\r\n/*\r\n* XOR Operation for OctetStrings\r\n*/\r\nOctetString operator^(const OctetString& k1, const OctetString& k2)\r\n   {\r\n   secure_vector<uint8_t> out(std::max(k1.length(), k2.length()));\r\n\r\n   copy_mem(out.data(), k1.begin(), k1.length());\r\n   xor_buf(out.data(), k2.begin(), k2.length());\r\n   return OctetString(out);\r\n   }\r\n\r\n}\r\n/*\r\n* Block Ciphers\r\n* (C) 2015 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_HAS_AES)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ARIA)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_BLOWFISH)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CAMELLIA)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CAST_128)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CAST_256)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CASCADE)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_DES)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_GOST_28147_89)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_IDEA)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_KASUMI)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_LION)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MISTY1)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_NOEKEON)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SEED)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SERPENT)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHACAL2)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SM4)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_TWOFISH)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_THREEFISH_512)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_XTEA)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_OPENSSL)\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\nstd::unique_ptr<BlockCipher>\r\nBlockCipher::create(const std::string& algo,\r\n                    const std::string& provider)\r\n   {\r\n#if defined(BOTAN_HAS_OPENSSL)\r\n   if(provider.empty() || provider == \"openssl\")\r\n      {\r\n      if(auto bc = make_openssl_block_cipher(algo))\r\n         return bc;\r\n\r\n      if(!provider.empty())\r\n         return nullptr;\r\n      }\r\n#endif\r\n\r\n   // TODO: CommonCrypto\r\n   // TODO: CryptoAPI\r\n   // TODO: /dev/crypto\r\n\r\n   // Only base providers from here on out\r\n   if(provider.empty() == false && provider != \"base\")\r\n      return nullptr;\r\n\r\n#if defined(BOTAN_HAS_AES)\r\n   if(algo == \"AES-128\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new AES_128);\r\n      }\r\n\r\n   if(algo == \"AES-192\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new AES_192);\r\n      }\r\n\r\n   if(algo == \"AES-256\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new AES_256);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ARIA)\r\n   if(algo == \"ARIA-128\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new ARIA_128);\r\n      }\r\n\r\n   if(algo == \"ARIA-192\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new ARIA_192);\r\n      }\r\n\r\n   if(algo == \"ARIA-256\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new ARIA_256);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SERPENT)\r\n   if(algo == \"Serpent\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new Serpent);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHACAL2)\r\n   if(algo == \"SHACAL2\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new SHACAL2);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_TWOFISH)\r\n   if(algo == \"Twofish\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new Twofish);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_THREEFISH_512)\r\n   if(algo == \"Threefish-512\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new Threefish_512);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_BLOWFISH)\r\n   if(algo == \"Blowfish\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new Blowfish);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CAMELLIA)\r\n   if(algo == \"Camellia-128\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new Camellia_128);\r\n      }\r\n\r\n   if(algo == \"Camellia-192\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new Camellia_192);\r\n      }\r\n\r\n   if(algo == \"Camellia-256\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new Camellia_256);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_DES)\r\n   if(algo == \"DES\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new DES);\r\n      }\r\n\r\n   if(algo == \"DESX\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new DESX);\r\n      }\r\n\r\n   if(algo == \"TripleDES\" || algo == \"3DES\" || algo == \"DES-EDE\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new TripleDES);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_NOEKEON)\r\n   if(algo == \"Noekeon\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new Noekeon);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CAST_128)\r\n   if(algo == \"CAST-128\" || algo == \"CAST5\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new CAST_128);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CAST_256)\r\n   if(algo == \"CAST-256\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new CAST_256);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_IDEA)\r\n   if(algo == \"IDEA\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new IDEA);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_KASUMI)\r\n   if(algo == \"KASUMI\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new KASUMI);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MISTY1)\r\n   if(algo == \"MISTY1\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new MISTY1);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SEED)\r\n   if(algo == \"SEED\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new SEED);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SM4)\r\n   if(algo == \"SM4\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new SM4);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_XTEA)\r\n   if(algo == \"XTEA\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new XTEA);\r\n      }\r\n#endif\r\n\r\n   const SCAN_Name req(algo);\r\n\r\n#if defined(BOTAN_HAS_GOST_28147_89)\r\n   if(req.algo_name() == \"GOST-28147-89\")\r\n      {\r\n      return std::unique_ptr<BlockCipher>(new GOST_28147_89(req.arg(0, \"R3411_94_TestParam\")));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CASCADE)\r\n   if(req.algo_name() == \"Cascade\" && req.arg_count() == 2)\r\n      {\r\n      std::unique_ptr<BlockCipher> c1(BlockCipher::create(req.arg(0)));\r\n      std::unique_ptr<BlockCipher> c2(BlockCipher::create(req.arg(1)));\r\n\r\n      if(c1 && c2)\r\n         return std::unique_ptr<BlockCipher>(new Cascade_Cipher(c1.release(), c2.release()));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_LION)\r\n   if(req.algo_name() == \"Lion\" && req.arg_count_between(2, 3))\r\n      {\r\n      std::unique_ptr<HashFunction> hash(HashFunction::create(req.arg(0)));\r\n      std::unique_ptr<StreamCipher> stream(StreamCipher::create(req.arg(1)));\r\n\r\n      if(hash && stream)\r\n         {\r\n         const size_t block_size = req.arg_as_integer(2, 1024);\r\n         return std::unique_ptr<BlockCipher>(new Lion(hash.release(), stream.release(), block_size));\r\n         }\r\n      }\r\n#endif\r\n\r\n   BOTAN_UNUSED(req);\r\n   BOTAN_UNUSED(provider);\r\n\r\n   return nullptr;\r\n   }\r\n\r\n//static\r\nstd::unique_ptr<BlockCipher>\r\nBlockCipher::create_or_throw(const std::string& algo,\r\n                             const std::string& provider)\r\n   {\r\n   if(auto bc = BlockCipher::create(algo, provider))\r\n      {\r\n      return bc;\r\n      }\r\n   throw Lookup_Error(\"Block cipher\", algo, provider);\r\n   }\r\n\r\nstd::vector<std::string> BlockCipher::providers(const std::string& algo)\r\n   {\r\n   return probe_providers_of<BlockCipher>(algo, { \"base\", \"openssl\" });\r\n   }\r\n\r\n}\r\n/*\r\n* CBC Mode\r\n* (C) 1999-2007,2013,2017 Jack Lloyd\r\n* (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\nCBC_Mode::CBC_Mode(BlockCipher* cipher, BlockCipherModePaddingMethod* padding) :\r\n   m_cipher(cipher),\r\n   m_padding(padding),\r\n   m_state(m_cipher->block_size())\r\n   {\r\n   if(m_padding && !m_padding->valid_blocksize(cipher->block_size()))\r\n      throw Invalid_Argument(\"Padding \" + m_padding->name() +\r\n                             \" cannot be used with \" +\r\n                             cipher->name() + \"/CBC\");\r\n   }\r\n\r\nvoid CBC_Mode::clear()\r\n   {\r\n   m_cipher->clear();\r\n   reset();\r\n   }\r\n\r\nvoid CBC_Mode::reset()\r\n   {\r\n   zeroise(m_state);\r\n   }\r\n\r\nstd::string CBC_Mode::name() const\r\n   {\r\n   if(m_padding)\r\n      return cipher().name() + \"/CBC/\" + padding().name();\r\n   else\r\n      return cipher().name() + \"/CBC/CTS\";\r\n   }\r\n\r\nsize_t CBC_Mode::update_granularity() const\r\n   {\r\n   return cipher().parallel_bytes();\r\n   }\r\n\r\nKey_Length_Specification CBC_Mode::key_spec() const\r\n   {\r\n   return cipher().key_spec();\r\n   }\r\n\r\nsize_t CBC_Mode::default_nonce_length() const\r\n   {\r\n   return block_size();\r\n   }\r\n\r\nbool CBC_Mode::valid_nonce_length(size_t n) const\r\n   {\r\n   return (n == 0 || n == block_size());\r\n   }\r\n\r\nvoid CBC_Mode::key_schedule(const uint8_t key[], size_t length)\r\n   {\r\n   m_cipher->set_key(key, length);\r\n   }\r\n\r\nvoid CBC_Mode::start_msg(const uint8_t nonce[], size_t nonce_len)\r\n   {\r\n   if(!valid_nonce_length(nonce_len))\r\n      throw Invalid_IV_Length(name(), nonce_len);\r\n\r\n   /*\r\n   * A nonce of zero length means carry the last ciphertext value over\r\n   * as the new IV, as unfortunately some protocols require this. If\r\n   * this is the first message then we use an IV of all zeros.\r\n   */\r\n   if(nonce_len)\r\n      m_state.assign(nonce, nonce + nonce_len);\r\n   }\r\n\r\nsize_t CBC_Encryption::minimum_final_size() const\r\n   {\r\n   return 0;\r\n   }\r\n\r\nsize_t CBC_Encryption::output_length(size_t input_length) const\r\n   {\r\n   if(input_length == 0)\r\n      return block_size();\r\n   else\r\n      return round_up(input_length, block_size());\r\n   }\r\n\r\nsize_t CBC_Encryption::process(uint8_t buf[], size_t sz)\r\n   {\r\n   const size_t BS = block_size();\r\n\r\n   BOTAN_ASSERT(sz % BS == 0, \"CBC input is full blocks\");\r\n   const size_t blocks = sz / BS;\r\n\r\n   if(blocks > 0)\r\n      {\r\n      xor_buf(&buf[0], state_ptr(), BS);\r\n      cipher().encrypt(&buf[0]);\r\n\r\n      for(size_t i = 1; i != blocks; ++i)\r\n         {\r\n         xor_buf(&buf[BS*i], &buf[BS*(i-1)], BS);\r\n         cipher().encrypt(&buf[BS*i]);\r\n         }\r\n\r\n      state().assign(&buf[BS*(blocks-1)], &buf[BS*blocks]);\r\n      }\r\n\r\n   return sz;\r\n   }\r\n\r\nvoid CBC_Encryption::finish(secure_vector<uint8_t>& buffer, size_t offset)\r\n   {\r\n   BOTAN_ASSERT(buffer.size() >= offset, \"Offset is sane\");\r\n\r\n   const size_t BS = block_size();\r\n\r\n   const size_t bytes_in_final_block = (buffer.size()-offset) % BS;\r\n\r\n   padding().add_padding(buffer, bytes_in_final_block, BS);\r\n\r\n   if((buffer.size()-offset) % BS)\r\n      throw Exception(\"Did not pad to full block size in \" + name());\r\n\r\n   update(buffer, offset);\r\n   }\r\n\r\nbool CTS_Encryption::valid_nonce_length(size_t n) const\r\n   {\r\n   return (n == block_size());\r\n   }\r\n\r\nsize_t CTS_Encryption::minimum_final_size() const\r\n   {\r\n   return block_size() + 1;\r\n   }\r\n\r\nsize_t CTS_Encryption::output_length(size_t input_length) const\r\n   {\r\n   return input_length; // no ciphertext expansion in CTS\r\n   }\r\n\r\nvoid CTS_Encryption::finish(secure_vector<uint8_t>& buffer, size_t offset)\r\n   {\r\n   BOTAN_ASSERT(buffer.size() >= offset, \"Offset is sane\");\r\n   uint8_t* buf = buffer.data() + offset;\r\n   const size_t sz = buffer.size() - offset;\r\n\r\n   const size_t BS = block_size();\r\n\r\n   if(sz < BS + 1)\r\n      throw Encoding_Error(name() + \": insufficient data to encrypt\");\r\n\r\n   if(sz % BS == 0)\r\n      {\r\n      update(buffer, offset);\r\n\r\n      // swap last two blocks\r\n      for(size_t i = 0; i != BS; ++i)\r\n         std::swap(buffer[buffer.size()-BS+i], buffer[buffer.size()-2*BS+i]);\r\n      }\r\n   else\r\n      {\r\n      const size_t full_blocks = ((sz / BS) - 1) * BS;\r\n      const size_t final_bytes = sz - full_blocks;\r\n      BOTAN_ASSERT(final_bytes > BS && final_bytes < 2*BS, \"Left over size in expected range\");\r\n\r\n      secure_vector<uint8_t> last(buf + full_blocks, buf + full_blocks + final_bytes);\r\n      buffer.resize(full_blocks + offset);\r\n      update(buffer, offset);\r\n\r\n      xor_buf(last.data(), state_ptr(), BS);\r\n      cipher().encrypt(last.data());\r\n\r\n      for(size_t i = 0; i != final_bytes - BS; ++i)\r\n         {\r\n         last[i] ^= last[i + BS];\r\n         last[i + BS] ^= last[i];\r\n         }\r\n\r\n      cipher().encrypt(last.data());\r\n\r\n      buffer += last;\r\n      }\r\n   }\r\n\r\nsize_t CBC_Decryption::output_length(size_t input_length) const\r\n   {\r\n   return input_length; // precise for CTS, worst case otherwise\r\n   }\r\n\r\nsize_t CBC_Decryption::minimum_final_size() const\r\n   {\r\n   return block_size();\r\n   }\r\n\r\nsize_t CBC_Decryption::process(uint8_t buf[], size_t sz)\r\n   {\r\n   const size_t BS = block_size();\r\n\r\n   BOTAN_ASSERT(sz % BS == 0, \"Input is full blocks\");\r\n   size_t blocks = sz / BS;\r\n\r\n   while(blocks)\r\n      {\r\n      const size_t to_proc = std::min(BS * blocks, m_tempbuf.size());\r\n\r\n      cipher().decrypt_n(buf, m_tempbuf.data(), to_proc / BS);\r\n\r\n      xor_buf(m_tempbuf.data(), state_ptr(), BS);\r\n      xor_buf(&m_tempbuf[BS], buf, to_proc - BS);\r\n      copy_mem(state_ptr(), buf + (to_proc - BS), BS);\r\n\r\n      copy_mem(buf, m_tempbuf.data(), to_proc);\r\n\r\n      buf += to_proc;\r\n      blocks -= to_proc / BS;\r\n      }\r\n\r\n   return sz;\r\n   }\r\n\r\nvoid CBC_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset)\r\n   {\r\n   BOTAN_ASSERT(buffer.size() >= offset, \"Offset is sane\");\r\n   const size_t sz = buffer.size() - offset;\r\n\r\n   const size_t BS = block_size();\r\n\r\n   if(sz == 0 || sz % BS)\r\n      throw Decoding_Error(name() + \": Ciphertext not a multiple of block size\");\r\n\r\n   update(buffer, offset);\r\n\r\n   const size_t pad_bytes = BS - padding().unpad(&buffer[buffer.size()-BS], BS);\r\n   buffer.resize(buffer.size() - pad_bytes); // remove padding\r\n   if(pad_bytes == 0 && padding().name() != \"NoPadding\")\r\n      {\r\n      throw Decoding_Error(name());\r\n      }\r\n   }\r\n\r\nvoid CBC_Decryption::reset()\r\n   {\r\n   zeroise(state());\r\n   zeroise(m_tempbuf);\r\n   }\r\n\r\nbool CTS_Decryption::valid_nonce_length(size_t n) const\r\n   {\r\n   return (n == block_size());\r\n   }\r\n\r\nsize_t CTS_Decryption::minimum_final_size() const\r\n   {\r\n   return block_size() + 1;\r\n   }\r\n\r\nvoid CTS_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset)\r\n   {\r\n   BOTAN_ASSERT(buffer.size() >= offset, \"Offset is sane\");\r\n   const size_t sz = buffer.size() - offset;\r\n   uint8_t* buf = buffer.data() + offset;\r\n\r\n   const size_t BS = block_size();\r\n\r\n   if(sz < BS + 1)\r\n      throw Encoding_Error(name() + \": insufficient data to decrypt\");\r\n\r\n   if(sz % BS == 0)\r\n      {\r\n      // swap last two blocks\r\n\r\n      for(size_t i = 0; i != BS; ++i)\r\n         std::swap(buffer[buffer.size()-BS+i], buffer[buffer.size()-2*BS+i]);\r\n\r\n      update(buffer, offset);\r\n      }\r\n   else\r\n      {\r\n      const size_t full_blocks = ((sz / BS) - 1) * BS;\r\n      const size_t final_bytes = sz - full_blocks;\r\n      BOTAN_ASSERT(final_bytes > BS && final_bytes < 2*BS, \"Left over size in expected range\");\r\n\r\n      secure_vector<uint8_t> last(buf + full_blocks, buf + full_blocks + final_bytes);\r\n      buffer.resize(full_blocks + offset);\r\n      update(buffer, offset);\r\n\r\n      cipher().decrypt(last.data());\r\n\r\n      xor_buf(last.data(), &last[BS], final_bytes - BS);\r\n\r\n      for(size_t i = 0; i != final_bytes - BS; ++i)\r\n         std::swap(last[i], last[i + BS]);\r\n\r\n      cipher().decrypt(last.data());\r\n      xor_buf(last.data(), state_ptr(), BS);\r\n\r\n      buffer += last;\r\n      }\r\n   }\r\n\r\n}\r\n/*\r\n* Runtime CPU detection\r\n* (C) 2009,2010,2013,2017 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n#include <ostream>\r\n\r\nnamespace Botan {\r\n\r\nuint64_t CPUID::g_processor_features = 0;\r\nsize_t CPUID::g_cache_line_size = BOTAN_TARGET_CPU_DEFAULT_CACHE_LINE_SIZE;\r\nCPUID::Endian_status CPUID::g_endian_status = ENDIAN_UNKNOWN;\r\n\r\nbool CPUID::has_simd_32()\r\n   {\r\n#if defined(BOTAN_TARGET_SUPPORTS_SSE2)\r\n   return CPUID::has_sse2();\r\n#elif defined(BOTAN_TARGET_SUPPORTS_ALTIVEC)\r\n   return CPUID::has_altivec();\r\n#elif defined(BOTAN_TARGET_SUPPORTS_NEON)\r\n   return CPUID::has_neon();\r\n#else\r\n   return true;\r\n#endif\r\n   }\r\n\r\n//static\r\nstd::string CPUID::to_string()\r\n   {\r\n   std::vector<std::string> flags;\r\n\r\n#define CPUID_PRINT(flag) do { if(has_##flag()) { flags.push_back(#flag); } } while(0)\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)\r\n   CPUID_PRINT(sse2);\r\n   CPUID_PRINT(ssse3);\r\n   CPUID_PRINT(sse41);\r\n   CPUID_PRINT(sse42);\r\n   CPUID_PRINT(avx2);\r\n   CPUID_PRINT(avx512f);\r\n\r\n   CPUID_PRINT(rdtsc);\r\n   CPUID_PRINT(bmi2);\r\n   CPUID_PRINT(adx);\r\n\r\n   CPUID_PRINT(aes_ni);\r\n   CPUID_PRINT(clmul);\r\n   CPUID_PRINT(rdrand);\r\n   CPUID_PRINT(rdseed);\r\n   CPUID_PRINT(intel_sha);\r\n#endif\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)\r\n   CPUID_PRINT(altivec);\r\n#endif\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)\r\n   CPUID_PRINT(neon);\r\n   CPUID_PRINT(arm_sha1);\r\n   CPUID_PRINT(arm_sha2);\r\n   CPUID_PRINT(arm_aes);\r\n   CPUID_PRINT(arm_pmull);\r\n#endif\r\n\r\n#undef CPUID_PRINT\r\n\r\n   return string_join(flags, ' ');\r\n   }\r\n\r\n//static\r\nvoid CPUID::print(std::ostream& o)\r\n   {\r\n   o << \"CPUID flags: \" << CPUID::to_string() << \"\\n\";\r\n   }\r\n\r\n//static\r\nvoid CPUID::initialize()\r\n   {\r\n   g_processor_features = 0;\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) || \\\r\n    defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) || \\\r\n    defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)\r\n\r\n   g_processor_features = CPUID::detect_cpu_features(&g_cache_line_size);\r\n\r\n#endif\r\n\r\n   g_processor_features |= CPUID::CPUID_INITIALIZED_BIT;\r\n   }\r\n\r\n//static\r\nCPUID::Endian_status CPUID::runtime_check_endian()\r\n   {\r\n   // Check runtime endian\r\n   const uint32_t endian32 = 0x01234567;\r\n   const uint8_t* e8 = reinterpret_cast<const uint8_t*>(&endian32);\r\n\r\n   Endian_status endian = ENDIAN_UNKNOWN;\r\n\r\n   if(e8[0] == 0x01 && e8[1] == 0x23 && e8[2] == 0x45 && e8[3] == 0x67)\r\n      {\r\n      endian = ENDIAN_BIG;\r\n      }\r\n   else if(e8[0] == 0x67 && e8[1] == 0x45 && e8[2] == 0x23 && e8[3] == 0x01)\r\n      {\r\n      endian = ENDIAN_LITTLE;\r\n      }\r\n   else\r\n      {\r\n      throw Internal_Error(\"Unexpected endian at runtime, neither big nor little\");\r\n      }\r\n\r\n   // If we were compiled with a known endian, verify it matches at runtime\r\n#if defined(BOTAN_TARGET_CPU_IS_LITTLE_ENDIAN)\r\n   BOTAN_ASSERT(endian == ENDIAN_LITTLE, \"Build and runtime endian match\");\r\n#elif defined(BOTAN_TARGET_CPU_IS_BIG_ENDIAN)\r\n   BOTAN_ASSERT(endian == ENDIAN_BIG, \"Build and runtime endian match\");\r\n#endif\r\n\r\n   return endian;\r\n   }\r\n\r\nstd::vector<Botan::CPUID::CPUID_bits>\r\nCPUID::bit_from_string(const std::string& tok)\r\n   {\r\n#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)\r\n   if(tok == \"sse2\" || tok == \"simd\")\r\n      return {Botan::CPUID::CPUID_SSE2_BIT};\r\n   if(tok == \"ssse3\")\r\n      return {Botan::CPUID::CPUID_SSSE3_BIT};\r\n   if(tok == \"aesni\")\r\n      return {Botan::CPUID::CPUID_AESNI_BIT};\r\n   if(tok == \"clmul\")\r\n      return {Botan::CPUID::CPUID_CLMUL_BIT};\r\n   if(tok == \"avx2\")\r\n      return {Botan::CPUID::CPUID_AVX2_BIT};\r\n   if(tok == \"sha\")\r\n      return {Botan::CPUID::CPUID_SHA_BIT};\r\n\r\n#elif defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)\r\n   if(tok == \"altivec\" || tok == \"simd\")\r\n      return {Botan::CPUID::CPUID_ALTIVEC_BIT};\r\n\r\n#elif defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)\r\n   if(tok == \"neon\" || tok == \"simd\")\r\n      return {Botan::CPUID::CPUID_ARM_NEON_BIT};\r\n   if(tok == \"armv8sha1\")\r\n      return {Botan::CPUID::CPUID_ARM_SHA1_BIT};\r\n   if(tok == \"armv8sha2\")\r\n      return {Botan::CPUID::CPUID_ARM_SHA2_BIT};\r\n   if(tok == \"armv8aes\")\r\n      return {Botan::CPUID::CPUID_ARM_AES_BIT};\r\n   if(tok == \"armv8pmull\")\r\n      return {Botan::CPUID::CPUID_ARM_PMULL_BIT};\r\n\r\n#else\r\n   BOTAN_UNUSED(tok);\r\n#endif\r\n\r\n   return {};\r\n   }\r\n\r\n}\r\n/*\r\n* Runtime CPU detection for ARM\r\n* (C) 2009,2010,2013,2017 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)\r\n  #include <sys/auxv.h>\r\n\r\n#elif defined(BOTAN_TARGET_OS_IS_IOS)\r\n  #include <sys/types.h>\r\n  #include <sys/sysctl.h>\r\n\r\n#else\r\n\r\n#endif\r\n\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)\r\n\r\n#if defined(BOTAN_TARGET_OS_IS_IOS)\r\n\r\nnamespace {\r\n\r\nuint64_t flags_by_ios_machine_type(const std::string& machine)\r\n   {\r\n   /*\r\n   * This relies on a map of known machine names to features. This\r\n   * will quickly grow out of date as new products are introduced, but\r\n   * is apparently the best we can do for iOS.\r\n   */\r\n\r\n   struct version_info {\r\n      std::string name;\r\n      size_t min_version_neon;\r\n      size_t min_version_armv8;\r\n      };\r\n\r\n   static const version_info min_versions[] = {\r\n      { \"iPhone\", 2, 6 },\r\n      { \"iPad\", 1, 4 },\r\n      { \"iPod\", 4, 7 },\r\n      { \"AppleTV\", 2, 5 },\r\n   };\r\n\r\n   if(machine.size() < 3)\r\n      return 0;\r\n\r\n   auto comma = machine.find(',');\r\n\r\n   // Simulator, or something we don't know about\r\n   if(comma == std::string::npos)\r\n      return 0;\r\n\r\n   std::string product = machine.substr(0, comma);\r\n\r\n   size_t version = 0;\r\n   size_t place = 1;\r\n   while(product.size() > 1 && ::isdigit(product.back()))\r\n      {\r\n      const size_t digit = product.back() - '0';\r\n      version += digit * place;\r\n      place *= 10;\r\n      product.pop_back();\r\n      }\r\n\r\n   if(version == 0)\r\n      return 0;\r\n\r\n   for(const version_info& info : min_versions)\r\n      {\r\n      if(info.name != product)\r\n         continue;\r\n\r\n      if(version >= info.min_version_armv8)\r\n         {\r\n         return CPUID::CPUID_ARM_AES_BIT |\r\n                CPUID::CPUID_ARM_PMULL_BIT |\r\n                CPUID::CPUID_ARM_SHA1_BIT |\r\n                CPUID::CPUID_ARM_SHA2_BIT |\r\n                CPUID::CPUID_ARM_NEON_BIT;\r\n         }\r\n\r\n      if(version >= info.min_version_neon)\r\n         return CPUID::CPUID_ARM_NEON_BIT;\r\n      }\r\n\r\n   // Some other product we don't know about\r\n   return 0;\r\n   }\r\n\r\n}\r\n\r\n#endif\r\n\r\nuint64_t CPUID::detect_cpu_features(size_t* cache_line_size)\r\n   {\r\n   uint64_t detected_features = 0;\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)\r\n   /*\r\n   * On systems with getauxval these bits should normally be defined\r\n   * in bits/auxv.h but some buggy? glibc installs seem to miss them.\r\n   * These following values are all fixed, for the Linux ELF format,\r\n   * so we just hardcode them in ARM_hwcap_bit enum.\r\n   */\r\n\r\n   enum ARM_hwcap_bit {\r\n#if defined(BOTAN_TARGET_ARCH_IS_ARM32)\r\n      NEON_bit  = (1 << 12),\r\n      AES_bit   = (1 << 0),\r\n      PMULL_bit = (1 << 1),\r\n      SHA1_bit  = (1 << 2),\r\n      SHA2_bit  = (1 << 3),\r\n\r\n      ARCH_hwcap_neon   = 16, // AT_HWCAP\r\n      ARCH_hwcap_crypto = 26, // AT_HWCAP2\r\n#elif defined(BOTAN_TARGET_ARCH_IS_ARM64)\r\n      NEON_bit  = (1 << 1),\r\n      AES_bit   = (1 << 3),\r\n      PMULL_bit = (1 << 4),\r\n      SHA1_bit  = (1 << 5),\r\n      SHA2_bit  = (1 << 6),\r\n\r\n      ARCH_hwcap_neon   = 16, // AT_HWCAP\r\n      ARCH_hwcap_crypto = 16, // AT_HWCAP\r\n#endif\r\n   };\r\n\r\n#if defined(AT_DCACHEBSIZE)\r\n   const unsigned long dcache_line = ::getauxval(AT_DCACHEBSIZE);\r\n\r\n   // plausibility check\r\n   if(dcache_line == 32 || dcache_line == 64 || dcache_line == 128)\r\n      *cache_line_size = static_cast<size_t>(dcache_line);\r\n#endif\r\n\r\n   const unsigned long hwcap_neon = ::getauxval(ARM_hwcap_bit::ARCH_hwcap_neon);\r\n   if(hwcap_neon & ARM_hwcap_bit::NEON_bit)\r\n      detected_features |= CPUID::CPUID_ARM_NEON_BIT;\r\n\r\n   /*\r\n   On aarch64 this ends up calling getauxval twice with AT_HWCAP\r\n   It doesn't seem worth optimizing this out, since getauxval is\r\n   just reading a field in the ELF header.\r\n   */\r\n   const unsigned long hwcap_crypto = ::getauxval(ARM_hwcap_bit::ARCH_hwcap_crypto);\r\n   if(hwcap_crypto & ARM_hwcap_bit::AES_bit)\r\n      detected_features |= CPUID::CPUID_ARM_AES_BIT;\r\n   if(hwcap_crypto & ARM_hwcap_bit::PMULL_bit)\r\n      detected_features |= CPUID::CPUID_ARM_PMULL_BIT;\r\n   if(hwcap_crypto & ARM_hwcap_bit::SHA1_bit)\r\n      detected_features |= CPUID::CPUID_ARM_SHA1_BIT;\r\n   if(hwcap_crypto & ARM_hwcap_bit::SHA2_bit)\r\n      detected_features |= CPUID::CPUID_ARM_SHA2_BIT;\r\n\r\n#elif defined(BOTAN_TARGET_OS_IS_IOS)\r\n\r\n   char machine[64] = { 0 };\r\n   size_t size = sizeof(machine) - 1;\r\n   ::sysctlbyname(\"hw.machine\", machine, &size, nullptr, 0);\r\n\r\n   detected_features = flags_by_ios_machine_type(machine);\r\n\r\n#elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_ARCH_IS_ARM64)\r\n\r\n   /*\r\n   No getauxval API available, fall back on probe functions. We only\r\n   bother with Aarch64 here to simplify the code and because going to\r\n   extreme contortions to support detect NEON on devices that probably\r\n   don't support it doesn't seem worthwhile.\r\n\r\n   NEON registers v0-v7 are caller saved in Aarch64\r\n   */\r\n\r\n   auto neon_probe  = []() -> int { asm(\"and v0.16b, v0.16b, v0.16b\"); return 1; };\r\n   auto aes_probe   = []() -> int { asm(\".word 0x4e284800\"); return 1; };\r\n   auto pmull_probe = []() -> int { asm(\".word 0x0ee0e000\"); return 1; };\r\n   auto sha1_probe  = []() -> int { asm(\".word 0x5e280800\"); return 1; };\r\n   auto sha2_probe  = []() -> int { asm(\".word 0x5e282800\"); return 1; };\r\n\r\n   // Only bother running the crypto detection if we found NEON\r\n\r\n   if(OS::run_cpu_instruction_probe(neon_probe) == 1)\r\n      {\r\n      detected_features |= CPUID::CPUID_ARM_NEON_BIT;\r\n\r\n      if(OS::run_cpu_instruction_probe(aes_probe) == 1)\r\n         detected_features |= CPUID::CPUID_ARM_AES_BIT;\r\n      if(OS::run_cpu_instruction_probe(pmull_probe) == 1)\r\n         detected_features |= CPUID::CPUID_ARM_PMULL_BIT;\r\n      if(OS::run_cpu_instruction_probe(sha1_probe) == 1)\r\n         detected_features |= CPUID::CPUID_ARM_SHA1_BIT;\r\n      if(OS::run_cpu_instruction_probe(sha2_probe) == 1)\r\n         detected_features |= CPUID::CPUID_ARM_SHA2_BIT;\r\n      }\r\n\r\n#endif\r\n\r\n   return detected_features;\r\n   }\r\n\r\n#endif\r\n\r\n}\r\n/*\r\n* Runtime CPU detection for POWER/PowerPC\r\n* (C) 2009,2010,2013,2017 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)\r\n\r\n/*\r\n* On Darwin and OpenBSD ppc, use sysctl to detect AltiVec\r\n*/\r\n#if defined(BOTAN_TARGET_OS_IS_DARWIN)\r\n  #include <sys/sysctl.h>\r\n#elif defined(BOTAN_TARGET_OS_IS_OPENBSD)\r\n  #include <sys/param.h>\r\n  #include <sys/sysctl.h>\r\n  #include <machine/cpu.h>\r\n#endif\r\n\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)\r\n\r\n/*\r\n* PowerPC specific block: check for AltiVec using either\r\n* sysctl or by reading processor version number register.\r\n*/\r\nuint64_t CPUID::detect_cpu_features(size_t* cache_line_size)\r\n   {\r\n#if defined(BOTAN_TARGET_OS_IS_DARWIN) || defined(BOTAN_TARGET_OS_IS_OPENBSD)\r\n   // On Darwin/OS X and OpenBSD, use sysctl\r\n\r\n   int sels[2] = {\r\n#if defined(BOTAN_TARGET_OS_IS_OPENBSD)\r\n      CTL_MACHDEP, CPU_ALTIVEC\r\n#else\r\n      CTL_HW, HW_VECTORUNIT\r\n#endif\r\n   };\r\n\r\n   int vector_type = 0;\r\n   size_t length = sizeof(vector_type);\r\n   int error = ::sysctl(sels, 2, &vector_type, &length, NULL, 0);\r\n\r\n   if(error == 0 && vector_type > 0)\r\n      return CPUID::CPUID_ALTIVEC_BIT;\r\n\r\n#else\r\n\r\n   /*\r\n   On PowerPC, MSR 287 is PVR, the Processor Version Number\r\n   Normally it is only accessible to ring 0, but Linux and NetBSD\r\n   (others, too, maybe?) will trap and emulate it for us.\r\n   */\r\n\r\n   int pvr = OS::run_cpu_instruction_probe([]() -> int {\r\n      uint32_t pvr = 0;\r\n      asm volatile(\"mfspr %0, 287\" : \"=r\" (pvr));\r\n      // Top 16 bits suffice to identify the model\r\n      return static_cast<int>(pvr >> 16);\r\n      });\r\n\r\n   if(pvr > 0)\r\n      {\r\n      const uint16_t ALTIVEC_PVR[] = {\r\n         0x003E, // IBM POWER6\r\n         0x003F, // IBM POWER7\r\n         0x004A, // IBM POWER7p\r\n         0x004D, // IBM POWER8\r\n         0x004B, // IBM POWER8E\r\n         0x000C, // G4-7400\r\n         0x0039, // G5 970\r\n         0x003C, // G5 970FX\r\n         0x0044, // G5 970MP\r\n         0x0070, // Cell PPU\r\n         0, // end\r\n      };\r\n\r\n      for(size_t i = 0; ALTIVEC_PVR[i]; ++i)\r\n         {\r\n         if(pvr == ALTIVEC_PVR[i])\r\n            return CPUID::CPUID_ALTIVEC_BIT;\r\n         }\r\n\r\n      return 0;\r\n      }\r\n\r\n   // TODO try direct instruction probing\r\n\r\n#endif\r\n\r\n   return 0;\r\n   }\r\n\r\n#endif\r\n\r\n}\r\n/*\r\n* Runtime CPU detection for x86\r\n* (C) 2009,2010,2013,2017 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)\r\n\r\n#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)\r\n  #include <intrin.h>\r\n#elif defined(BOTAN_BUILD_COMPILER_IS_INTEL)\r\n  #include <ia32intrin.h>\r\n#elif defined(BOTAN_BUILD_COMPILER_IS_GCC) || defined(BOTAN_BUILD_COMPILER_IS_CLANG)\r\n  #include <cpuid.h>\r\n#endif\r\n\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)\r\n\r\nuint64_t CPUID::detect_cpu_features(size_t* cache_line_size)\r\n   {\r\n#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)\r\n  #define X86_CPUID(type, out) do { __cpuid((int*)out, type); } while(0)\r\n  #define X86_CPUID_SUBLEVEL(type, level, out) do { __cpuidex((int*)out, type, level); } while(0)\r\n\r\n#elif defined(BOTAN_BUILD_COMPILER_IS_INTEL)\r\n  #define X86_CPUID(type, out) do { __cpuid(out, type); } while(0)\r\n  #define X86_CPUID_SUBLEVEL(type, level, out) do { __cpuidex((int*)out, type, level); } while(0)\r\n\r\n#elif defined(BOTAN_TARGET_ARCH_IS_X86_64) && defined(BOTAN_USE_GCC_INLINE_ASM)\r\n  #define X86_CPUID(type, out)                                                    \\\r\n     asm(\"cpuid\\n\\t\" : \"=a\" (out[0]), \"=b\" (out[1]), \"=c\" (out[2]), \"=d\" (out[3]) \\\r\n         : \"0\" (type))\r\n\r\n  #define X86_CPUID_SUBLEVEL(type, level, out)                                    \\\r\n     asm(\"cpuid\\n\\t\" : \"=a\" (out[0]), \"=b\" (out[1]), \"=c\" (out[2]), \"=d\" (out[3]) \\\r\n         : \"0\" (type), \"2\" (level))\r\n\r\n#elif defined(BOTAN_BUILD_COMPILER_IS_GCC) || defined(BOTAN_BUILD_COMPILER_IS_CLANG)\r\n  #define X86_CPUID(type, out) do { __get_cpuid(type, out, out+1, out+2, out+3); } while(0)\r\n\r\n  #define X86_CPUID_SUBLEVEL(type, level, out) \\\r\n     do { __cpuid_count(type, level, out[0], out[1], out[2], out[3]); } while(0)\r\n#else\r\n  #warning \"No way of calling x86 cpuid instruction for this compiler\"\r\n  #define X86_CPUID(type, out) do { clear_mem(out, 4); } while(0)\r\n  #define X86_CPUID_SUBLEVEL(type, level, out) do { clear_mem(out, 4); } while(0)\r\n#endif\r\n\r\n   uint64_t features_detected = 0;\r\n   uint32_t cpuid[4] = { 0 };\r\n\r\n   // CPUID 0: vendor identification, max sublevel\r\n   X86_CPUID(0, cpuid);\r\n\r\n   const uint32_t max_supported_sublevel = cpuid[0];\r\n\r\n   const uint32_t INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };\r\n   const uint32_t AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };\r\n   const bool is_intel = same_mem(cpuid + 1, INTEL_CPUID, 3);\r\n   const bool is_amd = same_mem(cpuid + 1, AMD_CPUID, 3);\r\n\r\n   if(max_supported_sublevel >= 1)\r\n      {\r\n      // CPUID 1: feature bits\r\n      X86_CPUID(1, cpuid);\r\n      const uint64_t flags0 = (static_cast<uint64_t>(cpuid[2]) << 32) | cpuid[3];\r\n\r\n      enum x86_CPUID_1_bits : uint64_t {\r\n         RDTSC = (1ULL << 4),\r\n         SSE2 = (1ULL << 26),\r\n         CLMUL = (1ULL << 33),\r\n         SSSE3 = (1ULL << 41),\r\n         SSE41 = (1ULL << 51),\r\n         SSE42 = (1ULL << 52),\r\n         AESNI = (1ULL << 57),\r\n         RDRAND = (1ULL << 62)\r\n      };\r\n\r\n      if(flags0 & x86_CPUID_1_bits::RDTSC)\r\n         features_detected |= CPUID::CPUID_RDTSC_BIT;\r\n      if(flags0 & x86_CPUID_1_bits::SSE2)\r\n         features_detected |= CPUID::CPUID_SSE2_BIT;\r\n      if(flags0 & x86_CPUID_1_bits::CLMUL)\r\n         features_detected |= CPUID::CPUID_CLMUL_BIT;\r\n      if(flags0 & x86_CPUID_1_bits::SSSE3)\r\n         features_detected |= CPUID::CPUID_SSSE3_BIT;\r\n      if(flags0 & x86_CPUID_1_bits::SSE41)\r\n         features_detected |= CPUID::CPUID_SSE41_BIT;\r\n      if(flags0 & x86_CPUID_1_bits::SSE42)\r\n         features_detected |= CPUID::CPUID_SSE42_BIT;\r\n      if(flags0 & x86_CPUID_1_bits::AESNI)\r\n         features_detected |= CPUID::CPUID_AESNI_BIT;\r\n      if(flags0 & x86_CPUID_1_bits::RDRAND)\r\n         features_detected |= CPUID::CPUID_RDRAND_BIT;\r\n      }\r\n\r\n   if(is_intel)\r\n      {\r\n      // Intel cache line size is in cpuid(1) output\r\n      *cache_line_size = 8 * get_byte(2, cpuid[1]);\r\n      }\r\n   else if(is_amd)\r\n      {\r\n      // AMD puts it in vendor zone\r\n      X86_CPUID(0x80000005, cpuid);\r\n      *cache_line_size = get_byte(3, cpuid[2]);\r\n      }\r\n\r\n   if(max_supported_sublevel >= 7)\r\n      {\r\n      clear_mem(cpuid, 4);\r\n      X86_CPUID_SUBLEVEL(7, 0, cpuid);\r\n\r\n      enum x86_CPUID_7_bits : uint64_t {\r\n         AVX2 = (1ULL << 5),\r\n         BMI2 = (1ULL << 8),\r\n         AVX512F = (1ULL << 16),\r\n         RDSEED = (1ULL << 18),\r\n         ADX = (1ULL << 19),\r\n         SHA = (1ULL << 29),\r\n      };\r\n      uint64_t flags7 = (static_cast<uint64_t>(cpuid[2]) << 32) | cpuid[1];\r\n\r\n      if(flags7 & x86_CPUID_7_bits::AVX2)\r\n         features_detected |= CPUID::CPUID_AVX2_BIT;\r\n      if(flags7 & x86_CPUID_7_bits::BMI2)\r\n         features_detected |= CPUID::CPUID_BMI2_BIT;\r\n      if(flags7 & x86_CPUID_7_bits::AVX512F)\r\n         features_detected |= CPUID::CPUID_AVX512F_BIT;\r\n      if(flags7 & x86_CPUID_7_bits::RDSEED)\r\n         features_detected |= CPUID::CPUID_RDSEED_BIT;\r\n      if(flags7 & x86_CPUID_7_bits::ADX)\r\n         features_detected |= CPUID::CPUID_ADX_BIT;\r\n      if(flags7 & x86_CPUID_7_bits::SHA)\r\n         features_detected |= CPUID::CPUID_SHA_BIT;\r\n      }\r\n\r\n#undef X86_CPUID\r\n#undef X86_CPUID_SUBLEVEL\r\n\r\n   /*\r\n   * If we don't have access to CPUID, we can still safely assume that\r\n   * any x86-64 processor has SSE2 and RDTSC\r\n   */\r\n#if defined(BOTAN_TARGET_ARCH_IS_X86_64)\r\n   if(features_detected == 0)\r\n      {\r\n      features_detected |= CPUID::CPUID_SSE2_BIT;\r\n      features_detected |= CPUID::CPUID_RDTSC_BIT;\r\n      }\r\n#endif\r\n\r\n   return features_detected;\r\n   }\r\n\r\n#endif\r\n\r\n}\r\n/*\r\n* CRC32\r\n* (C) 1999-2007 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\nstd::unique_ptr<HashFunction> CRC32::copy_state() const\r\n   {\r\n   return std::unique_ptr<HashFunction>(new CRC32(*this));\r\n   }\r\n\r\n/*\r\n* Update a CRC32 Checksum\r\n*/\r\nvoid CRC32::add_data(const uint8_t input[], size_t length)\r\n   {\r\n   const uint32_t TABLE[256] = {\r\n      0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,\r\n      0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,\r\n      0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,\r\n      0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,\r\n      0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,\r\n      0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,\r\n      0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,\r\n      0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,\r\n      0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,\r\n      0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,\r\n      0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106,\r\n      0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,\r\n      0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,\r\n      0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,\r\n      0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,\r\n      0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,\r\n      0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,\r\n      0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,\r\n      0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA,\r\n      0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,\r\n      0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,\r\n      0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,\r\n      0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84,\r\n      0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,\r\n      0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,\r\n      0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,\r\n      0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,\r\n      0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,\r\n      0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,\r\n      0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,\r\n      0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28,\r\n      0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,\r\n      0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,\r\n      0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,\r\n      0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,\r\n      0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,\r\n      0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,\r\n      0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,\r\n      0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,\r\n      0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,\r\n      0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,\r\n      0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,\r\n      0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D };\r\n\r\n   uint32_t tmp = m_crc;\r\n   while(length >= 16)\r\n      {\r\n      tmp = TABLE[(tmp ^ input[ 0]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 1]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 2]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 3]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 4]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 5]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 6]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 7]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 8]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[ 9]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[10]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[11]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[12]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[13]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[14]) & 0xFF] ^ (tmp >> 8);\r\n      tmp = TABLE[(tmp ^ input[15]) & 0xFF] ^ (tmp >> 8);\r\n      input += 16;\r\n      length -= 16;\r\n      }\r\n\r\n   for(size_t i = 0; i != length; ++i)\r\n      tmp = TABLE[(tmp ^ input[i]) & 0xFF] ^ (tmp >> 8);\r\n\r\n   m_crc = tmp;\r\n   }\r\n\r\n/*\r\n* Finalize a CRC32 Checksum\r\n*/\r\nvoid CRC32::final_result(uint8_t output[])\r\n   {\r\n   m_crc ^= 0xFFFFFFFF;\r\n   store_be(m_crc, output);\r\n   clear();\r\n   }\r\n\r\n}\r\n/*\r\n* Entropy Source Polling\r\n* (C) 2008-2010,2015 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_HAS_SYSTEM_RNG)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_RDRAND)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_RDSEED)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_WIN32)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_PROC_WALKER)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_DARWIN_SECRANDOM)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_GETENTROPY)\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\n#if defined(BOTAN_HAS_SYSTEM_RNG)\r\n\r\nnamespace {\r\n\r\nclass System_RNG_EntropySource final : public Entropy_Source\r\n   {\r\n   public:\r\n      size_t poll(RandomNumberGenerator& rng) override\r\n         {\r\n         const size_t poll_bits = BOTAN_RNG_RESEED_POLL_BITS;\r\n         rng.reseed_from_rng(system_rng(), poll_bits);\r\n         return poll_bits;\r\n         }\r\n\r\n      std::string name() const override { return \"system_rng\"; }\r\n   };\r\n\r\n}\r\n\r\n#endif\r\n\r\nstd::unique_ptr<Entropy_Source> Entropy_Source::create(const std::string& name)\r\n   {\r\n#if defined(BOTAN_HAS_SYSTEM_RNG)\r\n   if(name == \"system_rng\" || name == \"win32_cryptoapi\")\r\n      {\r\n      return std::unique_ptr<Entropy_Source>(new System_RNG_EntropySource);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_RDRAND)\r\n   if(name == \"rdrand\")\r\n      {\r\n      return std::unique_ptr<Entropy_Source>(new Intel_Rdrand);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_RDSEED)\r\n   if(name == \"rdseed\")\r\n      {\r\n      return std::unique_ptr<Entropy_Source>(new Intel_Rdseed);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_DARWIN_SECRANDOM)\r\n   if(name == \"darwin_secrandom\")\r\n      {\r\n      return std::unique_ptr<Entropy_Source>(new Darwin_SecRandom);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_GETENTROPY)\r\n   if(name == \"getentropy\")\r\n      {\r\n      return std::unique_ptr<Entropy_Source>(new Getentropy);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM)\r\n   if(name == \"dev_random\")\r\n      {\r\n      return std::unique_ptr<Entropy_Source>(new Device_EntropySource(BOTAN_SYSTEM_RNG_POLL_DEVICES));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_PROC_WALKER)\r\n   if(name == \"proc_walk\")\r\n      {\r\n      const std::string root_dir = BOTAN_ENTROPY_PROC_FS_PATH;\r\n      if(!root_dir.empty())\r\n         return std::unique_ptr<Entropy_Source>(new ProcWalking_EntropySource(root_dir));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ENTROPY_SRC_WIN32)\r\n   if(name == \"system_stats\")\r\n      {\r\n      return std::unique_ptr<Entropy_Source>(new Win32_EntropySource);\r\n      }\r\n#endif\r\n\r\n   BOTAN_UNUSED(name);\r\n   return std::unique_ptr<Entropy_Source>();\r\n   }\r\n\r\nvoid Entropy_Sources::add_source(std::unique_ptr<Entropy_Source> src)\r\n   {\r\n   if(src.get())\r\n      {\r\n      m_srcs.push_back(std::move(src));\r\n      }\r\n   }\r\n\r\nstd::vector<std::string> Entropy_Sources::enabled_sources() const\r\n   {\r\n   std::vector<std::string> sources;\r\n   for(size_t i = 0; i != m_srcs.size(); ++i)\r\n      {\r\n      sources.push_back(m_srcs[i]->name());\r\n      }\r\n   return sources;\r\n   }\r\n\r\nsize_t Entropy_Sources::poll(RandomNumberGenerator& rng,\r\n                             size_t poll_bits,\r\n                             std::chrono::milliseconds timeout)\r\n   {\r\n   typedef std::chrono::system_clock clock;\r\n\r\n   auto deadline = clock::now() + timeout;\r\n\r\n   size_t bits_collected = 0;\r\n\r\n   for(size_t i = 0; i != m_srcs.size(); ++i)\r\n      {\r\n      bits_collected += m_srcs[i]->poll(rng);\r\n\r\n      if (bits_collected >= poll_bits || clock::now() > deadline)\r\n         break;\r\n      }\r\n\r\n   return bits_collected;\r\n   }\r\n\r\nsize_t Entropy_Sources::poll_just(RandomNumberGenerator& rng, const std::string& the_src)\r\n   {\r\n   for(size_t i = 0; i != m_srcs.size(); ++i)\r\n      {\r\n      if(m_srcs[i]->name() == the_src)\r\n         {\r\n         return m_srcs[i]->poll(rng);\r\n         }\r\n      }\r\n\r\n   return 0;\r\n   }\r\n\r\nEntropy_Sources::Entropy_Sources(const std::vector<std::string>& sources)\r\n   {\r\n   for(auto&& src_name : sources)\r\n      {\r\n      add_source(Entropy_Source::create(src_name));\r\n      }\r\n   }\r\n\r\nEntropy_Sources& Entropy_Sources::global_sources()\r\n   {\r\n   static Entropy_Sources global_entropy_sources(BOTAN_ENTROPY_DEFAULT_SOURCES);\r\n\r\n   return global_entropy_sources;\r\n   }\r\n\r\n}\r\n\r\n/*\r\n* Hash Functions\r\n* (C) 2015 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_HAS_ADLER32)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CRC24)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CRC32)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_GOST_34_11)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_KECCAK)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MD4)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MD5)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_RIPEMD_160)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA1)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA2_32)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA2_64)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA3)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHAKE)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SKEIN_512)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_STREEBOG)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SM3)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_TIGER)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_WHIRLPOOL)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_PARALLEL_HASH)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_COMB4P)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_BLAKE2B)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_BEARSSL)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_OPENSSL)\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\nstd::unique_ptr<HashFunction> HashFunction::create(const std::string& algo_spec,\r\n                                                   const std::string& provider)\r\n   {\r\n#if defined(BOTAN_HAS_OPENSSL)\r\n   if(provider.empty() || provider == \"openssl\")\r\n      {\r\n      if(auto hash = make_openssl_hash(algo_spec))\r\n         return hash;\r\n\r\n      if(!provider.empty())\r\n         return nullptr;\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_BEARSSL)\r\n   if(provider.empty() || provider == \"bearssl\")\r\n      {\r\n      if(auto hash = make_bearssl_hash(algo_spec))\r\n         return hash;\r\n\r\n      if(!provider.empty())\r\n         return nullptr;\r\n      }\r\n#endif\r\n\r\n   // TODO: CommonCrypto hashes\r\n\r\n   if(provider.empty() == false && provider != \"base\")\r\n      return nullptr; // unknown provider\r\n\r\n#if defined(BOTAN_HAS_SHA1)\r\n   if(algo_spec == \"SHA-160\" ||\r\n      algo_spec == \"SHA-1\" ||\r\n      algo_spec == \"SHA1\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SHA_160);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA2_32)\r\n   if(algo_spec == \"SHA-224\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SHA_224);\r\n      }\r\n\r\n   if(algo_spec == \"SHA-256\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SHA_256);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA2_64)\r\n   if(algo_spec == \"SHA-384\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SHA_384);\r\n      }\r\n\r\n   if(algo_spec == \"SHA-512\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SHA_512);\r\n      }\r\n\r\n   if(algo_spec == \"SHA-512-256\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SHA_512_256);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_RIPEMD_160)\r\n   if(algo_spec == \"RIPEMD-160\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new RIPEMD_160);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_WHIRLPOOL)\r\n   if(algo_spec == \"Whirlpool\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new Whirlpool);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MD5)\r\n   if(algo_spec == \"MD5\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new MD5);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MD4)\r\n   if(algo_spec == \"MD4\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new MD4);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_GOST_34_11)\r\n   if(algo_spec == \"GOST-R-34.11-94\" || algo_spec == \"GOST-34.11\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new GOST_34_11);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ADLER32)\r\n   if(algo_spec == \"Adler32\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new Adler32);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CRC24)\r\n   if(algo_spec == \"CRC24\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new CRC24);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CRC32)\r\n   if(algo_spec == \"CRC32\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new CRC32);\r\n      }\r\n#endif\r\n\r\n   const SCAN_Name req(algo_spec);\r\n\r\n#if defined(BOTAN_HAS_TIGER)\r\n   if(req.algo_name() == \"Tiger\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(\r\n         new Tiger(req.arg_as_integer(0, 24),\r\n                   req.arg_as_integer(1, 3)));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SKEIN_512)\r\n   if(req.algo_name() == \"Skein-512\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(\r\n         new Skein_512(req.arg_as_integer(0, 512), req.arg(1, \"\")));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_BLAKE2B)\r\n   if(req.algo_name() == \"Blake2b\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(\r\n         new Blake2b(req.arg_as_integer(0, 512)));\r\n   }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_KECCAK)\r\n   if(req.algo_name() == \"Keccak-1600\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(\r\n         new Keccak_1600(req.arg_as_integer(0, 512)));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA3)\r\n   if(req.algo_name() == \"SHA-3\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(\r\n         new SHA_3(req.arg_as_integer(0, 512)));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHAKE)\r\n   if(req.algo_name() == \"SHAKE-128\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SHAKE_128(req.arg_as_integer(0, 128)));\r\n      }\r\n   if(req.algo_name() == \"SHAKE-256\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SHAKE_256(req.arg_as_integer(0, 256)));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_STREEBOG)\r\n   if(algo_spec == \"Streebog-256\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new Streebog_256);\r\n      }\r\n   if(algo_spec == \"Streebog-512\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new Streebog_512);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SM3)\r\n   if(algo_spec == \"SM3\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new SM3);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_WHIRLPOOL)\r\n   if(req.algo_name() == \"Whirlpool\")\r\n      {\r\n      return std::unique_ptr<HashFunction>(new Whirlpool);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_PARALLEL_HASH)\r\n   if(req.algo_name() == \"Parallel\")\r\n      {\r\n      std::vector<std::unique_ptr<HashFunction>> hashes;\r\n\r\n      for(size_t i = 0; i != req.arg_count(); ++i)\r\n         {\r\n         auto h = HashFunction::create(req.arg(i));\r\n         if(!h)\r\n            {\r\n            return nullptr;\r\n            }\r\n         hashes.push_back(std::move(h));\r\n         }\r\n\r\n      return std::unique_ptr<HashFunction>(new Parallel(hashes));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_COMB4P)\r\n   if(req.algo_name() == \"Comb4P\" && req.arg_count() == 2)\r\n      {\r\n      std::unique_ptr<HashFunction> h1(HashFunction::create(req.arg(0)));\r\n      std::unique_ptr<HashFunction> h2(HashFunction::create(req.arg(1)));\r\n\r\n      if(h1 && h2)\r\n         return std::unique_ptr<HashFunction>(new Comb4P(h1.release(), h2.release()));\r\n      }\r\n#endif\r\n\r\n\r\n   return nullptr;\r\n   }\r\n\r\n//static\r\nstd::unique_ptr<HashFunction>\r\nHashFunction::create_or_throw(const std::string& algo,\r\n                              const std::string& provider)\r\n   {\r\n   if(auto hash = HashFunction::create(algo, provider))\r\n      {\r\n      return hash;\r\n      }\r\n   throw Lookup_Error(\"Hash\", algo, provider);\r\n   }\r\n\r\nstd::vector<std::string> HashFunction::providers(const std::string& algo_spec)\r\n   {\r\n   return probe_providers_of<HashFunction>(algo_spec, {\"base\", \"bearssl\", \"openssl\"});\r\n   }\r\n\r\n}\r\n\r\n/*\r\n* Hex Encoding and Decoding\r\n* (C) 2010 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\nvoid hex_encode(char output[],\r\n                const uint8_t input[],\r\n                size_t input_length,\r\n                bool uppercase)\r\n   {\r\n   static const uint8_t BIN_TO_HEX_UPPER[16] = {\r\n      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n      'A', 'B', 'C', 'D', 'E', 'F' };\r\n\r\n   static const uint8_t BIN_TO_HEX_LOWER[16] = {\r\n      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n      'a', 'b', 'c', 'd', 'e', 'f' };\r\n\r\n   const uint8_t* tbl = uppercase ? BIN_TO_HEX_UPPER : BIN_TO_HEX_LOWER;\r\n\r\n   for(size_t i = 0; i != input_length; ++i)\r\n      {\r\n      uint8_t x = input[i];\r\n      output[2*i  ] = tbl[(x >> 4) & 0x0F];\r\n      output[2*i+1] = tbl[(x     ) & 0x0F];\r\n      }\r\n   }\r\n\r\nstd::string hex_encode(const uint8_t input[],\r\n                       size_t input_length,\r\n                       bool uppercase)\r\n   {\r\n   std::string output(2 * input_length, 0);\r\n\r\n   if(input_length)\r\n      hex_encode(&output.front(), input, input_length, uppercase);\r\n\r\n   return output;\r\n   }\r\n\r\nsize_t hex_decode(uint8_t output[],\r\n                  const char input[],\r\n                  size_t input_length,\r\n                  size_t& input_consumed,\r\n                  bool ignore_ws)\r\n   {\r\n   /*\r\n   * Mapping of hex characters to either their binary equivalent\r\n   * or to an error code.\r\n   *  If valid hex (0-9 A-F a-f), the value.\r\n   *  If whitespace, then 0x80\r\n   *  Otherwise 0xFF\r\n   * Warning: this table assumes ASCII character encodings\r\n   */\r\n\r\n   static const uint8_t HEX_TO_BIN[256] = {\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80,\r\n      0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01,\r\n      0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,\r\n      0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C,\r\n      0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\r\n      0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };\r\n\r\n   uint8_t* out_ptr = output;\r\n   bool top_nibble = true;\r\n\r\n   clear_mem(output, input_length / 2);\r\n\r\n   for(size_t i = 0; i != input_length; ++i)\r\n      {\r\n      const uint8_t bin = HEX_TO_BIN[static_cast<uint8_t>(input[i])];\r\n\r\n      if(bin >= 0x10)\r\n         {\r\n         if(bin == 0x80 && ignore_ws)\r\n            continue;\r\n\r\n         std::string bad_char(1, input[i]);\r\n         if(bad_char == \"\\t\")\r\n           bad_char = \"\\\\t\";\r\n         else if(bad_char == \"\\n\")\r\n           bad_char = \"\\\\n\";\r\n\r\n         throw Invalid_Argument(\r\n           std::string(\"hex_decode: invalid hex character '\") +\r\n           bad_char + \"'\");\r\n         }\r\n\r\n      if(top_nibble)\r\n         *out_ptr |= bin << 4;\r\n      else\r\n         *out_ptr |= bin;\r\n\r\n      top_nibble = !top_nibble;\r\n      if(top_nibble)\r\n         ++out_ptr;\r\n      }\r\n\r\n   input_consumed = input_length;\r\n   size_t written = (out_ptr - output);\r\n\r\n   /*\r\n   * We only got half of a uint8_t at the end; zap the half-written\r\n   * output and mark it as unread\r\n   */\r\n   if(!top_nibble)\r\n      {\r\n      *out_ptr = 0;\r\n      input_consumed -= 1;\r\n      }\r\n\r\n   return written;\r\n   }\r\n\r\nsize_t hex_decode(uint8_t output[],\r\n                  const char input[],\r\n                  size_t input_length,\r\n                  bool ignore_ws)\r\n   {\r\n   size_t consumed = 0;\r\n   size_t written = hex_decode(output, input, input_length,\r\n                               consumed, ignore_ws);\r\n\r\n   if(consumed != input_length)\r\n      throw Invalid_Argument(\"hex_decode: input did not have full bytes\");\r\n\r\n   return written;\r\n   }\r\n\r\nsize_t hex_decode(uint8_t output[],\r\n                  const std::string& input,\r\n                  bool ignore_ws)\r\n   {\r\n   return hex_decode(output, input.data(), input.length(), ignore_ws);\r\n   }\r\n\r\nsecure_vector<uint8_t> hex_decode_locked(const char input[],\r\n                                      size_t input_length,\r\n                                      bool ignore_ws)\r\n   {\r\n   secure_vector<uint8_t> bin(1 + input_length / 2);\r\n\r\n   size_t written = hex_decode(bin.data(),\r\n                               input,\r\n                               input_length,\r\n                               ignore_ws);\r\n\r\n   bin.resize(written);\r\n   return bin;\r\n   }\r\n\r\nsecure_vector<uint8_t> hex_decode_locked(const std::string& input,\r\n                                      bool ignore_ws)\r\n   {\r\n   return hex_decode_locked(input.data(), input.size(), ignore_ws);\r\n   }\r\n\r\nstd::vector<uint8_t> hex_decode(const char input[],\r\n                             size_t input_length,\r\n                             bool ignore_ws)\r\n   {\r\n   std::vector<uint8_t> bin(1 + input_length / 2);\r\n\r\n   size_t written = hex_decode(bin.data(),\r\n                               input,\r\n                               input_length,\r\n                               ignore_ws);\r\n\r\n   bin.resize(written);\r\n   return bin;\r\n   }\r\n\r\nstd::vector<uint8_t> hex_decode(const std::string& input,\r\n                             bool ignore_ws)\r\n   {\r\n   return hex_decode(input.data(), input.size(), ignore_ws);\r\n   }\r\n\r\n}\r\n/*\r\n* Message Authentication Code base class\r\n* (C) 1999-2008 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_HAS_CBC_MAC)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CMAC)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_GMAC)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_HMAC)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_POLY1305)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SIPHASH)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ANSI_X919_MAC)\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\nstd::unique_ptr<MessageAuthenticationCode>\r\nMessageAuthenticationCode::create(const std::string& algo_spec,\r\n                                  const std::string& provider)\r\n   {\r\n   const SCAN_Name req(algo_spec);\r\n\r\n#if defined(BOTAN_HAS_GMAC)\r\n   if(req.algo_name() == \"GMAC\" && req.arg_count() == 1)\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         if(auto bc = BlockCipher::create(req.arg(0)))\r\n            return std::unique_ptr<MessageAuthenticationCode>(new GMAC(bc.release()));\r\n         }\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_HMAC)\r\n   if(req.algo_name() == \"HMAC\" && req.arg_count() == 1)\r\n      {\r\n      // TODO OpenSSL\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         if(auto h = HashFunction::create(req.arg(0)))\r\n            return std::unique_ptr<MessageAuthenticationCode>(new HMAC(h.release()));\r\n         }\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_POLY1305)\r\n   if(req.algo_name() == \"Poly1305\" && req.arg_count() == 0)\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         return std::unique_ptr<MessageAuthenticationCode>(new Poly1305);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SIPHASH)\r\n   if(req.algo_name() == \"SipHash\")\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         return std::unique_ptr<MessageAuthenticationCode>(\r\n            new SipHash(req.arg_as_integer(0, 2), req.arg_as_integer(1, 4)));\r\n         }\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CMAC)\r\n   if((req.algo_name() == \"CMAC\" || req.algo_name() == \"OMAC\") && req.arg_count() == 1)\r\n      {\r\n      // TODO: OpenSSL CMAC\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         if(auto bc = BlockCipher::create(req.arg(0)))\r\n            return std::unique_ptr<MessageAuthenticationCode>(new CMAC(bc.release()));\r\n         }\r\n      }\r\n#endif\r\n\r\n\r\n#if defined(BOTAN_HAS_CBC_MAC)\r\n   if(req.algo_name() == \"CBC-MAC\" && req.arg_count() == 1)\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         if(auto bc = BlockCipher::create(req.arg(0)))\r\n            return std::unique_ptr<MessageAuthenticationCode>(new CBC_MAC(bc.release()));\r\n         }\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_ANSI_X919_MAC)\r\n   if(req.algo_name() == \"X9.19-MAC\")\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         return std::unique_ptr<MessageAuthenticationCode>(new ANSI_X919_MAC);\r\n         }\r\n      }\r\n#endif\r\n\r\n   BOTAN_UNUSED(req);\r\n   BOTAN_UNUSED(provider);\r\n\r\n   return nullptr;\r\n   }\r\n\r\nstd::vector<std::string>\r\nMessageAuthenticationCode::providers(const std::string& algo_spec)\r\n   {\r\n   return probe_providers_of<MessageAuthenticationCode>(algo_spec, {\"base\", \"openssl\"});\r\n   }\r\n\r\n//static\r\nstd::unique_ptr<MessageAuthenticationCode>\r\nMessageAuthenticationCode::create_or_throw(const std::string& algo,\r\n                                           const std::string& provider)\r\n   {\r\n   if(auto mac = MessageAuthenticationCode::create(algo, provider))\r\n      {\r\n      return mac;\r\n      }\r\n   throw Lookup_Error(\"MAC\", algo, provider);\r\n   }\r\n\r\n/*\r\n* Default (deterministic) MAC verification operation\r\n*/\r\nbool MessageAuthenticationCode::verify_mac(const uint8_t mac[], size_t length)\r\n   {\r\n   secure_vector<uint8_t> our_mac = final();\r\n\r\n   if(our_mac.size() != length)\r\n      return false;\r\n\r\n   return constant_time_compare(our_mac.data(), mac, length);\r\n   }\r\n\r\n}\r\n/*\r\n* Merkle-Damgard Hash Function\r\n* (C) 1999-2008 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\n/*\r\n* MDx_HashFunction Constructor\r\n*/\r\nMDx_HashFunction::MDx_HashFunction(size_t block_len,\r\n                                   bool byte_end,\r\n                                   bool bit_end,\r\n                                   size_t cnt_size) :\r\n   m_buffer(block_len),\r\n   m_count(0),\r\n   m_position(0),\r\n   BIG_BYTE_ENDIAN(byte_end),\r\n   BIG_BIT_ENDIAN(bit_end),\r\n   COUNT_SIZE(cnt_size)\r\n   {\r\n   }\r\n\r\n/*\r\n* Clear memory of sensitive data\r\n*/\r\nvoid MDx_HashFunction::clear()\r\n   {\r\n   zeroise(m_buffer);\r\n   m_count = m_position = 0;\r\n   }\r\n\r\n/*\r\n* Update the hash\r\n*/\r\nvoid MDx_HashFunction::add_data(const uint8_t input[], size_t length)\r\n   {\r\n   m_count += length;\r\n\r\n   if(m_position)\r\n      {\r\n      buffer_insert(m_buffer, m_position, input, length);\r\n\r\n      if(m_position + length >= m_buffer.size())\r\n         {\r\n         compress_n(m_buffer.data(), 1);\r\n         input += (m_buffer.size() - m_position);\r\n         length -= (m_buffer.size() - m_position);\r\n         m_position = 0;\r\n         }\r\n      }\r\n\r\n   const size_t full_blocks = length / m_buffer.size();\r\n   const size_t remaining   = length % m_buffer.size();\r\n\r\n   if(full_blocks)\r\n      compress_n(input, full_blocks);\r\n\r\n   buffer_insert(m_buffer, m_position, input + full_blocks * m_buffer.size(), remaining);\r\n   m_position += remaining;\r\n   }\r\n\r\n/*\r\n* Finalize a hash\r\n*/\r\nvoid MDx_HashFunction::final_result(uint8_t output[])\r\n   {\r\n   m_buffer[m_position] = (BIG_BIT_ENDIAN ? 0x80 : 0x01);\r\n   for(size_t i = m_position+1; i != m_buffer.size(); ++i)\r\n      m_buffer[i] = 0;\r\n\r\n   if(m_position >= m_buffer.size() - COUNT_SIZE)\r\n      {\r\n      compress_n(m_buffer.data(), 1);\r\n      zeroise(m_buffer);\r\n      }\r\n\r\n   write_count(&m_buffer[m_buffer.size() - COUNT_SIZE]);\r\n\r\n   compress_n(m_buffer.data(), 1);\r\n   copy_out(output);\r\n   clear();\r\n   }\r\n\r\n/*\r\n* Write the count bits to the buffer\r\n*/\r\nvoid MDx_HashFunction::write_count(uint8_t out[])\r\n   {\r\n   if(COUNT_SIZE < 8)\r\n      throw Invalid_State(\"MDx_HashFunction::write_count: COUNT_SIZE < 8\");\r\n   if(COUNT_SIZE >= output_length() || COUNT_SIZE >= hash_block_size())\r\n      throw Invalid_Argument(\"MDx_HashFunction: COUNT_SIZE is too big\");\r\n\r\n   const uint64_t bit_count = m_count * 8;\r\n\r\n   if(BIG_BYTE_ENDIAN)\r\n      store_be(bit_count, out + COUNT_SIZE - 8);\r\n   else\r\n      store_le(bit_count, out + COUNT_SIZE - 8);\r\n   }\r\n\r\n}\r\n/*\r\n* CBC Padding Methods\r\n* (C) 1999-2007,2013 Jack Lloyd\r\n* (C) 2016 Ren\u00e9 Korthaus, Rohde & Schwarz Cybersecurity\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\n/**\r\n* Get a block cipher padding method by name\r\n*/\r\nBlockCipherModePaddingMethod* get_bc_pad(const std::string& algo_spec)\r\n   {\r\n   if(algo_spec == \"NoPadding\")\r\n      return new Null_Padding;\r\n\r\n   if(algo_spec == \"PKCS7\")\r\n      return new PKCS7_Padding;\r\n\r\n   if(algo_spec == \"OneAndZeros\")\r\n      return new OneAndZeros_Padding;\r\n\r\n   if(algo_spec == \"X9.23\")\r\n      return new ANSI_X923_Padding;\r\n\r\n   if(algo_spec == \"ESP\")\r\n      return new ESP_Padding;\r\n\r\n   return nullptr;\r\n   }\r\n\r\n/*\r\n* Pad with PKCS #7 Method\r\n*/\r\nvoid PKCS7_Padding::add_padding(secure_vector<uint8_t>& buffer,\r\n                                size_t last_byte_pos,\r\n                                size_t block_size) const\r\n   {\r\n   const uint8_t pad_value = static_cast<uint8_t>(block_size - last_byte_pos);\r\n\r\n   for(size_t i = 0; i != pad_value; ++i)\r\n      buffer.push_back(pad_value);\r\n   }\r\n\r\n/*\r\n* Unpad with PKCS #7 Method\r\n*/\r\nsize_t PKCS7_Padding::unpad(const uint8_t block[], size_t size) const\r\n   {\r\n   CT::poison(block,size);\r\n   size_t bad_input = 0;\r\n   const uint8_t last_byte = block[size-1];\r\n\r\n   bad_input |= CT::expand_mask<size_t>(last_byte > size);\r\n\r\n   size_t pad_pos = size - last_byte;\r\n   size_t i = size - 2;\r\n   while(i)\r\n      {\r\n      bad_input |= (~CT::is_equal(block[i],last_byte)) & CT::expand_mask<uint8_t>(i >= pad_pos);\r\n      --i;\r\n      }\r\n\r\n   CT::conditional_copy_mem(bad_input,&pad_pos,&size,&pad_pos,1);\r\n   CT::unpoison(block,size);\r\n   CT::unpoison(pad_pos);\r\n   return pad_pos;\r\n   }\r\n\r\n/*\r\n* Pad with ANSI X9.23 Method\r\n*/\r\nvoid ANSI_X923_Padding::add_padding(secure_vector<uint8_t>& buffer,\r\n                                    size_t last_byte_pos,\r\n                                    size_t block_size) const\r\n   {\r\n   const uint8_t pad_value = static_cast<uint8_t>(block_size - last_byte_pos);\r\n\r\n   for(size_t i = last_byte_pos; i < block_size-1; ++i)\r\n      {\r\n      buffer.push_back(0);\r\n      }\r\n   buffer.push_back(pad_value);\r\n   }\r\n\r\n/*\r\n* Unpad with ANSI X9.23 Method\r\n*/\r\nsize_t ANSI_X923_Padding::unpad(const uint8_t block[], size_t size) const\r\n   {\r\n   CT::poison(block,size);\r\n   size_t bad_input = 0;\r\n   const size_t last_byte = block[size-1];\r\n\r\n   bad_input |= CT::expand_mask<size_t>(last_byte > size);\r\n\r\n   size_t pad_pos = size - last_byte;\r\n   size_t i = size - 2;\r\n   while(i)\r\n      {\r\n      bad_input |= (~CT::is_zero(block[i])) & CT::expand_mask<uint8_t>(i >= pad_pos);\r\n      --i;\r\n      }\r\n   CT::conditional_copy_mem(bad_input,&pad_pos,&size,&pad_pos,1);\r\n   CT::unpoison(block,size);\r\n   CT::unpoison(pad_pos);\r\n   return pad_pos;\r\n   }\r\n\r\n/*\r\n* Pad with One and Zeros Method\r\n*/\r\nvoid OneAndZeros_Padding::add_padding(secure_vector<uint8_t>& buffer,\r\n                                      size_t last_byte_pos,\r\n                                      size_t block_size) const\r\n   {\r\n   buffer.push_back(0x80);\r\n\r\n   for(size_t i = last_byte_pos + 1; i % block_size; ++i)\r\n      buffer.push_back(0x00);\r\n   }\r\n\r\n/*\r\n* Unpad with One and Zeros Method\r\n*/\r\nsize_t OneAndZeros_Padding::unpad(const uint8_t block[], size_t size) const\r\n   {\r\n   CT::poison(block, size);\r\n   uint8_t bad_input = 0;\r\n   uint8_t seen_one = 0;\r\n   size_t pad_pos = size - 1;\r\n   size_t i = size;\r\n\r\n   while(i)\r\n      {\r\n      seen_one |= CT::is_equal<uint8_t>(block[i-1],0x80);\r\n      pad_pos -= CT::select<uint8_t>(~seen_one, 1, 0);\r\n      bad_input |= ~CT::is_zero<uint8_t>(block[i-1]) & ~seen_one;\r\n      i--;\r\n      }\r\n   bad_input |= ~seen_one;\r\n\r\n   CT::conditional_copy_mem(size_t(bad_input),&pad_pos,&size,&pad_pos,1);\r\n   CT::unpoison(block, size);\r\n   CT::unpoison(pad_pos);\r\n\r\n   return pad_pos;\r\n   }\r\n\r\n/*\r\n* Pad with ESP Padding Method\r\n*/\r\nvoid ESP_Padding::add_padding(secure_vector<uint8_t>& buffer,\r\n                              size_t last_byte_pos,\r\n                              size_t block_size) const\r\n   {\r\n   uint8_t pad_value = 0x01;\r\n\r\n   for(size_t i = last_byte_pos; i < block_size; ++i)\r\n      {\r\n      buffer.push_back(pad_value++);\r\n      }\r\n   }\r\n\r\n/*\r\n* Unpad with ESP Padding Method\r\n*/\r\nsize_t ESP_Padding::unpad(const uint8_t block[], size_t size) const\r\n   {\r\n   CT::poison(block,size);\r\n\r\n   const size_t last_byte = block[size-1];\r\n   size_t bad_input = 0;\r\n   bad_input |= CT::expand_mask<size_t>(last_byte > size);\r\n\r\n   size_t pad_pos = size - last_byte;\r\n   size_t i = size - 1;\r\n   while(i)\r\n      {\r\n      bad_input |= ~CT::is_equal<uint8_t>(size_t(block[i-1]),size_t(block[i])-1) & CT::expand_mask<uint8_t>(i > pad_pos);\r\n      --i;\r\n      }\r\n   CT::conditional_copy_mem(bad_input,&pad_pos,&size,&pad_pos,1);\r\n   CT::unpoison(block, size);\r\n   CT::unpoison(pad_pos);\r\n   return pad_pos;\r\n   }\r\n\r\n\r\n}\r\n/*\r\n* Cipher Modes\r\n* (C) 2015 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n#include <sstream>\r\n\r\n#if defined(BOTAN_HAS_BLOCK_CIPHER)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_AEAD_MODES)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MODE_CBC)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MODE_CFB)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MODE_XTS)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_OPENSSL)\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\nCipher_Mode* get_cipher_mode(const std::string& algo, Cipher_Dir direction,\r\n                             const std::string& provider)\r\n   {\r\n#if defined(BOTAN_HAS_OPENSSL)\r\n   if(provider.empty() || provider == \"openssl\")\r\n      {\r\n      if(Cipher_Mode* bc = make_openssl_cipher_mode(algo, direction))\r\n         return bc;\r\n\r\n      if(!provider.empty())\r\n         return nullptr;\r\n      }\r\n#endif\r\n\r\n   if(auto sc = StreamCipher::create(algo))\r\n      {\r\n      return new Stream_Cipher_Mode(sc.release());\r\n      }\r\n\r\n#if defined(BOTAN_HAS_AEAD_MODES)\r\n   if(auto aead = get_aead(algo, direction))\r\n      {\r\n      return aead;\r\n      }\r\n#endif\r\n\r\n   if(algo.find('/') != std::string::npos)\r\n      {\r\n      const std::vector<std::string> algo_parts = split_on(algo, '/');\r\n      const std::string cipher_name = algo_parts[0];\r\n      const std::vector<std::string> mode_info = parse_algorithm_name(algo_parts[1]);\r\n\r\n      if(mode_info.empty())\r\n         return nullptr;\r\n\r\n      std::ostringstream alg_args;\r\n\r\n      alg_args << '(' << cipher_name;\r\n      for(size_t i = 1; i < mode_info.size(); ++i)\r\n         alg_args << ',' << mode_info[i];\r\n      for(size_t i = 2; i < algo_parts.size(); ++i)\r\n         alg_args << ',' << algo_parts[i];\r\n      alg_args << ')';\r\n\r\n      const std::string mode_name = mode_info[0] + alg_args.str();\r\n      return get_cipher_mode(mode_name, direction, provider);\r\n      }\r\n\r\n#if defined(BOTAN_HAS_BLOCK_CIPHER)\r\n\r\n   SCAN_Name spec(algo);\r\n\r\n   if(spec.arg_count() == 0)\r\n      {\r\n      return nullptr;\r\n      }\r\n\r\n   std::unique_ptr<BlockCipher> bc(BlockCipher::create(spec.arg(0), provider));\r\n\r\n   if(!bc)\r\n      {\r\n      return nullptr;\r\n      }\r\n\r\n#if defined(BOTAN_HAS_MODE_CBC)\r\n   if(spec.algo_name() == \"CBC\")\r\n      {\r\n      const std::string padding = spec.arg(1, \"PKCS7\");\r\n\r\n      if(padding == \"CTS\")\r\n         {\r\n         if(direction == ENCRYPTION)\r\n            return new CTS_Encryption(bc.release());\r\n         else\r\n            return new CTS_Decryption(bc.release());\r\n         }\r\n      else\r\n         {\r\n         std::unique_ptr<BlockCipherModePaddingMethod> pad(get_bc_pad(padding));\r\n\r\n         if(pad)\r\n            {\r\n            if(direction == ENCRYPTION)\r\n               return new CBC_Encryption(bc.release(), pad.release());\r\n            else\r\n               return new CBC_Decryption(bc.release(), pad.release());\r\n            }\r\n         }\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MODE_XTS)\r\n   if(spec.algo_name() == \"XTS\")\r\n      {\r\n      if(direction == ENCRYPTION)\r\n         return new XTS_Encryption(bc.release());\r\n      else\r\n         return new XTS_Decryption(bc.release());\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_MODE_CFB)\r\n   if(spec.algo_name() == \"CFB\")\r\n      {\r\n      const size_t feedback_bits = spec.arg_as_integer(1, 8*bc->block_size());\r\n      if(direction == ENCRYPTION)\r\n         return new CFB_Encryption(bc.release(), feedback_bits);\r\n      else\r\n         return new CFB_Decryption(bc.release(), feedback_bits);\r\n      }\r\n#endif\r\n\r\n#endif\r\n\r\n   return nullptr;\r\n   }\r\n\r\n//static\r\nstd::vector<std::string> Cipher_Mode::providers(const std::string& algo_spec)\r\n   {\r\n   const std::vector<std::string>& possible = { \"base\", \"openssl\" };\r\n   std::vector<std::string> providers;\r\n   for(auto&& prov : possible)\r\n      {\r\n      std::unique_ptr<Cipher_Mode> mode(get_cipher_mode(algo_spec, ENCRYPTION, prov));\r\n      if(mode)\r\n         {\r\n         providers.push_back(prov); // available\r\n         }\r\n      }\r\n   return providers;\r\n   }\r\n\r\n}\r\n/*\r\n* (C) 2016 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_HAS_AUTO_SEEDING_RNG)\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\nvoid RandomNumberGenerator::randomize_with_ts_input(uint8_t output[], size_t output_len)\r\n   {\r\n   /*\r\n   Form additional input which is provided to the PRNG implementation\r\n   to paramaterize the KDF output.\r\n   */\r\n   uint8_t additional_input[16] = { 0 };\r\n   store_le(OS::get_system_timestamp_ns(), additional_input);\r\n   store_le(OS::get_high_resolution_clock(), additional_input + 8);\r\n\r\n   randomize_with_input(output, output_len, additional_input, sizeof(additional_input));\r\n   }\r\n\r\nvoid RandomNumberGenerator::randomize_with_input(uint8_t output[], size_t output_len,\r\n                                                 const uint8_t input[], size_t input_len)\r\n   {\r\n   this->add_entropy(input, input_len);\r\n   this->randomize(output, output_len);\r\n   }\r\n\r\nsize_t RandomNumberGenerator::reseed(Entropy_Sources& srcs,\r\n                                     size_t poll_bits,\r\n                                     std::chrono::milliseconds poll_timeout)\r\n   {\r\n   return srcs.poll(*this, poll_bits, poll_timeout);\r\n   }\r\n\r\nvoid RandomNumberGenerator::reseed_from_rng(RandomNumberGenerator& rng, size_t poll_bits)\r\n   {\r\n   secure_vector<uint8_t> buf(poll_bits / 8);\r\n   rng.randomize(buf.data(), buf.size());\r\n   this->add_entropy(buf.data(), buf.size());\r\n   }\r\n\r\nRandomNumberGenerator* RandomNumberGenerator::make_rng()\r\n   {\r\n#if defined(BOTAN_HAS_AUTO_SEEDING_RNG)\r\n   return new AutoSeeded_RNG;\r\n#else\r\n   throw Exception(\"make_rng failed, no AutoSeeded_RNG in this build\");\r\n#endif\r\n   }\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_THREADS)\r\n\r\n#if defined(BOTAN_HAS_AUTO_SEEDING_RNG)\r\nSerialized_RNG::Serialized_RNG() : m_rng(new AutoSeeded_RNG) {}\r\n#else\r\nSerialized_RNG::Serialized_RNG()\r\n   {\r\n   throw Exception(\"Serialized_RNG default constructor failed: AutoSeeded_RNG disabled in build\");\r\n   }\r\n#endif\r\n\r\n#endif\r\n\r\n}\r\n/*\r\n* SHA-160\r\n* (C) 1999-2008,2011 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\nstd::unique_ptr<HashFunction> SHA_160::copy_state() const\r\n   {\r\n   return std::unique_ptr<HashFunction>(new SHA_160(*this));\r\n   }\r\n\r\nnamespace SHA1_F {\r\n\r\nnamespace {\r\n\r\n/*\r\n* SHA-160 F1 Function\r\n*/\r\ninline void F1(uint32_t A, uint32_t& B, uint32_t C, uint32_t D, uint32_t& E, uint32_t msg)\r\n   {\r\n   E += (D ^ (B & (C ^ D))) + msg + 0x5A827999 + rotl<5>(A);\r\n   B  = rotl<30>(B);\r\n   }\r\n\r\n/*\r\n* SHA-160 F2 Function\r\n*/\r\ninline void F2(uint32_t A, uint32_t& B, uint32_t C, uint32_t D, uint32_t& E, uint32_t msg)\r\n   {\r\n   E += (B ^ C ^ D) + msg + 0x6ED9EBA1 + rotl<5>(A);\r\n   B  = rotl<30>(B);\r\n   }\r\n\r\n/*\r\n* SHA-160 F3 Function\r\n*/\r\ninline void F3(uint32_t A, uint32_t& B, uint32_t C, uint32_t D, uint32_t& E, uint32_t msg)\r\n   {\r\n   E += ((B & C) | ((B | C) & D)) + msg + 0x8F1BBCDC + rotl<5>(A);\r\n   B  = rotl<30>(B);\r\n   }\r\n\r\n/*\r\n* SHA-160 F4 Function\r\n*/\r\ninline void F4(uint32_t A, uint32_t& B, uint32_t C, uint32_t D, uint32_t& E, uint32_t msg)\r\n   {\r\n   E += (B ^ C ^ D) + msg + 0xCA62C1D6 + rotl<5>(A);\r\n   B  = rotl<30>(B);\r\n   }\r\n\r\n}\r\n\r\n}\r\n\r\n/*\r\n* SHA-160 Compression Function\r\n*/\r\nvoid SHA_160::compress_n(const uint8_t input[], size_t blocks)\r\n   {\r\n   using namespace SHA1_F;\r\n\r\n#if defined(BOTAN_HAS_SHA1_X86_SHA_NI)\r\n   if(CPUID::has_intel_sha())\r\n      {\r\n      return sha1_compress_x86(m_digest, input, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA1_ARMV8)\r\n   if(CPUID::has_arm_sha1())\r\n      {\r\n      return sha1_armv8_compress_n(m_digest, input, blocks);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHA1_SSE2)\r\n   if(CPUID::has_sse2())\r\n      {\r\n      return sse2_compress_n(m_digest, input, blocks);\r\n      }\r\n\r\n#endif\r\n\r\n   uint32_t A = m_digest[0], B = m_digest[1], C = m_digest[2],\r\n          D = m_digest[3], E = m_digest[4];\r\n\r\n   m_W.resize(80);\r\n\r\n   for(size_t i = 0; i != blocks; ++i)\r\n      {\r\n      load_be(m_W.data(), input, 16);\r\n\r\n      for(size_t j = 16; j != 80; j += 8)\r\n         {\r\n         m_W[j  ] = rotl<1>(m_W[j-3] ^ m_W[j-8] ^ m_W[j-14] ^ m_W[j-16]);\r\n         m_W[j+1] = rotl<1>(m_W[j-2] ^ m_W[j-7] ^ m_W[j-13] ^ m_W[j-15]);\r\n         m_W[j+2] = rotl<1>(m_W[j-1] ^ m_W[j-6] ^ m_W[j-12] ^ m_W[j-14]);\r\n         m_W[j+3] = rotl<1>(m_W[j  ] ^ m_W[j-5] ^ m_W[j-11] ^ m_W[j-13]);\r\n         m_W[j+4] = rotl<1>(m_W[j+1] ^ m_W[j-4] ^ m_W[j-10] ^ m_W[j-12]);\r\n         m_W[j+5] = rotl<1>(m_W[j+2] ^ m_W[j-3] ^ m_W[j- 9] ^ m_W[j-11]);\r\n         m_W[j+6] = rotl<1>(m_W[j+3] ^ m_W[j-2] ^ m_W[j- 8] ^ m_W[j-10]);\r\n         m_W[j+7] = rotl<1>(m_W[j+4] ^ m_W[j-1] ^ m_W[j- 7] ^ m_W[j- 9]);\r\n         }\r\n\r\n      F1(A, B, C, D, E, m_W[ 0]);   F1(E, A, B, C, D, m_W[ 1]);\r\n      F1(D, E, A, B, C, m_W[ 2]);   F1(C, D, E, A, B, m_W[ 3]);\r\n      F1(B, C, D, E, A, m_W[ 4]);   F1(A, B, C, D, E, m_W[ 5]);\r\n      F1(E, A, B, C, D, m_W[ 6]);   F1(D, E, A, B, C, m_W[ 7]);\r\n      F1(C, D, E, A, B, m_W[ 8]);   F1(B, C, D, E, A, m_W[ 9]);\r\n      F1(A, B, C, D, E, m_W[10]);   F1(E, A, B, C, D, m_W[11]);\r\n      F1(D, E, A, B, C, m_W[12]);   F1(C, D, E, A, B, m_W[13]);\r\n      F1(B, C, D, E, A, m_W[14]);   F1(A, B, C, D, E, m_W[15]);\r\n      F1(E, A, B, C, D, m_W[16]);   F1(D, E, A, B, C, m_W[17]);\r\n      F1(C, D, E, A, B, m_W[18]);   F1(B, C, D, E, A, m_W[19]);\r\n\r\n      F2(A, B, C, D, E, m_W[20]);   F2(E, A, B, C, D, m_W[21]);\r\n      F2(D, E, A, B, C, m_W[22]);   F2(C, D, E, A, B, m_W[23]);\r\n      F2(B, C, D, E, A, m_W[24]);   F2(A, B, C, D, E, m_W[25]);\r\n      F2(E, A, B, C, D, m_W[26]);   F2(D, E, A, B, C, m_W[27]);\r\n      F2(C, D, E, A, B, m_W[28]);   F2(B, C, D, E, A, m_W[29]);\r\n      F2(A, B, C, D, E, m_W[30]);   F2(E, A, B, C, D, m_W[31]);\r\n      F2(D, E, A, B, C, m_W[32]);   F2(C, D, E, A, B, m_W[33]);\r\n      F2(B, C, D, E, A, m_W[34]);   F2(A, B, C, D, E, m_W[35]);\r\n      F2(E, A, B, C, D, m_W[36]);   F2(D, E, A, B, C, m_W[37]);\r\n      F2(C, D, E, A, B, m_W[38]);   F2(B, C, D, E, A, m_W[39]);\r\n\r\n      F3(A, B, C, D, E, m_W[40]);   F3(E, A, B, C, D, m_W[41]);\r\n      F3(D, E, A, B, C, m_W[42]);   F3(C, D, E, A, B, m_W[43]);\r\n      F3(B, C, D, E, A, m_W[44]);   F3(A, B, C, D, E, m_W[45]);\r\n      F3(E, A, B, C, D, m_W[46]);   F3(D, E, A, B, C, m_W[47]);\r\n      F3(C, D, E, A, B, m_W[48]);   F3(B, C, D, E, A, m_W[49]);\r\n      F3(A, B, C, D, E, m_W[50]);   F3(E, A, B, C, D, m_W[51]);\r\n      F3(D, E, A, B, C, m_W[52]);   F3(C, D, E, A, B, m_W[53]);\r\n      F3(B, C, D, E, A, m_W[54]);   F3(A, B, C, D, E, m_W[55]);\r\n      F3(E, A, B, C, D, m_W[56]);   F3(D, E, A, B, C, m_W[57]);\r\n      F3(C, D, E, A, B, m_W[58]);   F3(B, C, D, E, A, m_W[59]);\r\n\r\n      F4(A, B, C, D, E, m_W[60]);   F4(E, A, B, C, D, m_W[61]);\r\n      F4(D, E, A, B, C, m_W[62]);   F4(C, D, E, A, B, m_W[63]);\r\n      F4(B, C, D, E, A, m_W[64]);   F4(A, B, C, D, E, m_W[65]);\r\n      F4(E, A, B, C, D, m_W[66]);   F4(D, E, A, B, C, m_W[67]);\r\n      F4(C, D, E, A, B, m_W[68]);   F4(B, C, D, E, A, m_W[69]);\r\n      F4(A, B, C, D, E, m_W[70]);   F4(E, A, B, C, D, m_W[71]);\r\n      F4(D, E, A, B, C, m_W[72]);   F4(C, D, E, A, B, m_W[73]);\r\n      F4(B, C, D, E, A, m_W[74]);   F4(A, B, C, D, E, m_W[75]);\r\n      F4(E, A, B, C, D, m_W[76]);   F4(D, E, A, B, C, m_W[77]);\r\n      F4(C, D, E, A, B, m_W[78]);   F4(B, C, D, E, A, m_W[79]);\r\n\r\n      A = (m_digest[0] += A);\r\n      B = (m_digest[1] += B);\r\n      C = (m_digest[2] += C);\r\n      D = (m_digest[3] += D);\r\n      E = (m_digest[4] += E);\r\n\r\n      input += hash_block_size();\r\n      }\r\n   }\r\n\r\n/*\r\n* Copy out the digest\r\n*/\r\nvoid SHA_160::copy_out(uint8_t output[])\r\n   {\r\n   copy_out_vec_be(output, output_length(), m_digest);\r\n   }\r\n\r\n/*\r\n* Clear memory of sensitive data\r\n*/\r\nvoid SHA_160::clear()\r\n   {\r\n   MDx_HashFunction::clear();\r\n   zeroise(m_W);\r\n   m_digest[0] = 0x67452301;\r\n   m_digest[1] = 0xEFCDAB89;\r\n   m_digest[2] = 0x98BADCFE;\r\n   m_digest[3] = 0x10325476;\r\n   m_digest[4] = 0xC3D2E1F0;\r\n   }\r\n\r\n}\r\n/*\r\n* Stream Ciphers\r\n* (C) 2015,2016 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_HAS_CHACHA)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SALSA20)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHAKE_CIPHER)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CTR_BE)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_OFB)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_RC4)\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_OPENSSL)\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\nstd::unique_ptr<StreamCipher> StreamCipher::create(const std::string& algo_spec,\r\n                                                   const std::string& provider)\r\n   {\r\n   const SCAN_Name req(algo_spec);\r\n\r\n#if defined(BOTAN_HAS_CTR_BE)\r\n   if((req.algo_name() == \"CTR-BE\" || req.algo_name() == \"CTR\") && req.arg_count_between(1,2))\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         auto cipher = BlockCipher::create(req.arg(0));\r\n         if(cipher)\r\n            {\r\n            size_t ctr_size = req.arg_as_integer(1, cipher->block_size());\r\n            return std::unique_ptr<StreamCipher>(new CTR_BE(cipher.release(), ctr_size));\r\n            }\r\n         }\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_CHACHA)\r\n   if(req.algo_name() == \"ChaCha\")\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         return std::unique_ptr<StreamCipher>(new ChaCha(req.arg_as_integer(0, 20)));\r\n      }\r\n\r\n   if(req.algo_name() == \"ChaCha20\")\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         return std::unique_ptr<StreamCipher>(new ChaCha(20));\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SALSA20)\r\n   if(req.algo_name() == \"Salsa20\")\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         return std::unique_ptr<StreamCipher>(new Salsa20);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_SHAKE_CIPHER)\r\n   if(req.algo_name() == \"SHAKE-128\")\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         return std::unique_ptr<StreamCipher>(new SHAKE_128_Cipher);\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_OFB)\r\n   if(req.algo_name() == \"OFB\" && req.arg_count() == 1)\r\n      {\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         if(auto c = BlockCipher::create(req.arg(0)))\r\n            return std::unique_ptr<StreamCipher>(new OFB(c.release()));\r\n         }\r\n      }\r\n#endif\r\n\r\n#if defined(BOTAN_HAS_RC4)\r\n\r\n   if(req.algo_name() == \"RC4\" ||\r\n      req.algo_name() == \"ARC4\" ||\r\n      req.algo_name() == \"MARK-4\")\r\n      {\r\n      const size_t skip = (req.algo_name() == \"MARK-4\") ? 256 : req.arg_as_integer(0, 0);\r\n\r\n#if defined(BOTAN_HAS_OPENSSL)\r\n      if(provider.empty() || provider == \"openssl\")\r\n         {\r\n         return std::unique_ptr<StreamCipher>(make_openssl_rc4(skip));\r\n         }\r\n#endif\r\n\r\n      if(provider.empty() || provider == \"base\")\r\n         {\r\n         return std::unique_ptr<StreamCipher>(new RC4(skip));\r\n         }\r\n      }\r\n\r\n#endif\r\n\r\n   BOTAN_UNUSED(req);\r\n   BOTAN_UNUSED(provider);\r\n\r\n   return nullptr;\r\n   }\r\n\r\n//static\r\nstd::unique_ptr<StreamCipher>\r\nStreamCipher::create_or_throw(const std::string& algo,\r\n                             const std::string& provider)\r\n   {\r\n   if(auto sc = StreamCipher::create(algo, provider))\r\n      {\r\n      return sc;\r\n      }\r\n   throw Lookup_Error(\"Stream cipher\", algo, provider);\r\n   }\r\n\r\nstd::vector<std::string> StreamCipher::providers(const std::string& algo_spec)\r\n   {\r\n   return probe_providers_of<StreamCipher>(algo_spec, {\"base\", \"openssl\"});\r\n   }\r\n\r\n}\r\n/*\r\n* Runtime assertion checking\r\n* (C) 2010,2012 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\nvoid assertion_failure(const char* expr_str,\r\n                       const char* assertion_made,\r\n                       const char* func,\r\n                       const char* file,\r\n                       int line)\r\n   {\r\n   std::ostringstream format;\r\n\r\n   format << \"False assertion \";\r\n\r\n   if(assertion_made && assertion_made[0] != 0)\r\n      format << \"'\" << assertion_made << \"' (expression \" << expr_str << \") \";\r\n   else\r\n      format << expr_str << \" \";\r\n\r\n   if(func)\r\n      format << \"in \" << func << \" \";\r\n\r\n   format << \"@\" << file << \":\" << line;\r\n\r\n   throw Exception(format.str());\r\n   }\r\n\r\n}\r\n/*\r\n* Barrier\r\n* (C) 2016 Joel Low\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_THREADS)\r\n\r\nnamespace Botan {\r\n\r\nvoid Barrier::wait(size_t delta)\r\n    {\r\n    lock_guard_type<mutex_type> lock(m_mutex);\r\n    m_value += static_cast<int>(delta);\r\n    }\r\n\r\nvoid Barrier::sync()\r\n    {\r\n    std::unique_lock<mutex_type> lock(m_mutex);\r\n    \r\n    if(m_value > 1)\r\n        {\r\n        --m_value;\r\n        const size_t current_syncs = m_syncs;\r\n        m_cond.wait(lock, [this, &current_syncs] { return m_syncs != current_syncs; });\r\n        }\r\n    else\r\n        {\r\n        m_value = 0;\r\n        ++m_syncs;\r\n        m_cond.notify_all();\r\n        }\r\n    }\r\n\r\n}\r\n\r\n#endif\r\n/*\r\n* Calendar Functions\r\n* (C) 1999-2010,2017 Jack Lloyd\r\n* (C) 2015 Simon Warta (Kullo GmbH)\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n#include <ctime>\r\n#include <iomanip>\r\n#include <stdlib.h>\r\n\r\nnamespace Botan {\r\n\r\nnamespace {\r\n\r\nstd::tm do_gmtime(std::time_t time_val)\r\n   {\r\n   std::tm tm;\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_GMTIME_S)\r\n   ::gmtime_s(&tm, &time_val); // Windows\r\n#elif defined(BOTAN_TARGET_OS_HAS_GMTIME_R)\r\n   ::gmtime_r(&time_val, &tm); // Unix/SUSv2\r\n#else\r\n   std::tm* tm_p = std::gmtime(&time_val);\r\n   if (tm_p == nullptr)\r\n      throw Encoding_Error(\"time_t_to_tm could not convert\");\r\n   tm = *tm_p;\r\n#endif\r\n\r\n   return tm;\r\n   }\r\n\r\n/*\r\nPortable replacement for timegm, _mkgmtime, etc\r\n\r\nAlgorithm due to Howard Hinnant\r\n\r\nSee https://howardhinnant.github.io/date_algorithms.html#days_from_civil\r\nfor details and explaination. The code is slightly simplified by our assumption\r\nthat the date is at least 1970, which is sufficient for our purposes.\r\n*/\r\nsize_t days_since_epoch(uint32_t year, uint32_t month, uint32_t day)\r\n   {\r\n   if(month <= 2)\r\n      year -= 1;\r\n   const uint32_t era = year / 400;\r\n   const uint32_t yoe = year - era * 400;      // [0, 399]\r\n   const uint32_t doy = (153*(month + (month > 2 ? -3 : 9)) + 2)/5 + day-1;  // [0, 365]\r\n   const uint32_t doe = yoe * 365 + yoe/4 - yoe/100 + doy;         // [0, 146096]\r\n   return era * 146097 + doe - 719468;\r\n   }\r\n\r\n}\r\n\r\nstd::chrono::system_clock::time_point calendar_point::to_std_timepoint() const\r\n   {\r\n   if(get_year() < 1970)\r\n      throw Invalid_Argument(\"calendar_point::to_std_timepoint() does not support years before 1970\");\r\n\r\n   // 32 bit time_t ends at January 19, 2038\r\n   // https://msdn.microsoft.com/en-us/library/2093ets1.aspx\r\n   // Throw after 2037 if 32 bit time_t is used\r\n   if(get_year() > 2037 && sizeof(std::time_t) == 4)\r\n      {\r\n      throw Invalid_Argument(\"calendar_point::to_std_timepoint() does not support years after 2037 on this system\");\r\n      }\r\n   else if(get_year() >= 2400)\r\n      {\r\n      // This upper bound is somewhat arbitrary\r\n      throw Invalid_Argument(\"calendar_point::to_std_timepoint() does not support years after 2400\");\r\n      }\r\n\r\n   const uint64_t seconds_64 = (days_since_epoch(get_year(), get_month(), get_day()) * 86400) +\r\n                                (get_hour() * 60 * 60) + (get_minutes() * 60) + get_seconds();\r\n\r\n   const time_t seconds_time_t = static_cast<time_t>(seconds_64);\r\n\r\n   if(seconds_64 - seconds_time_t != 0)\r\n      {\r\n      throw Invalid_Argument(\"calendar_point::to_std_timepoint time_t overflow\");\r\n      }\r\n\r\n   return std::chrono::system_clock::from_time_t(seconds_time_t);\r\n   }\r\n\r\nstd::string calendar_point::to_string() const\r\n   {\r\n   // desired format: <YYYY>-<MM>-<dd>T<HH>:<mm>:<ss>\r\n   std::stringstream output;\r\n   output << std::setfill('0')\r\n          << std::setw(4) << get_year() << \"-\"\r\n          << std::setw(2) << get_month() << \"-\"\r\n          << std::setw(2) << get_day() << \"T\"\r\n          << std::setw(2) << get_hour() << \":\"\r\n          << std::setw(2) << get_minutes() << \":\"\r\n          << std::setw(2) << get_seconds();\r\n   return output.str();\r\n   }\r\n\r\n\r\ncalendar_point calendar_value(\r\n   const std::chrono::system_clock::time_point& time_point)\r\n   {\r\n   std::tm tm = do_gmtime(std::chrono::system_clock::to_time_t(time_point));\r\n\r\n   return calendar_point(tm.tm_year + 1900,\r\n                         tm.tm_mon + 1,\r\n                         tm.tm_mday,\r\n                         tm.tm_hour,\r\n                         tm.tm_min,\r\n                         tm.tm_sec);\r\n   }\r\n\r\n}\r\n/*\r\n* Character Set Handling\r\n* (C) 1999-2007 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n#include <cctype>\r\n\r\nnamespace Botan {\r\n\r\nnamespace {\r\n\r\nvoid append_utf8_for(std::string& s, uint32_t c)\r\n   {\r\n   if(c >= 0xD800 && c < 0xE000)\r\n      throw Decoding_Error(\"Invalid Unicode character\");\r\n\r\n   if(c <= 0x7F)\r\n      {\r\n      const uint8_t b0 = static_cast<uint8_t>(c);\r\n      s.push_back(static_cast<char>(b0));\r\n      }\r\n   else if(c <= 0x7FF)\r\n      {\r\n      const uint8_t b0 = 0xC0 | static_cast<uint8_t>(c >> 6);\r\n      const uint8_t b1 = 0x80 | static_cast<uint8_t>(c & 0x3F);\r\n      s.push_back(static_cast<char>(b0));\r\n      s.push_back(static_cast<char>(b1));\r\n      }\r\n   else if(c <= 0xFFFF)\r\n      {\r\n      const uint8_t b0 = 0xE0 | static_cast<uint8_t>(c >> 12);\r\n      const uint8_t b1 = 0x80 | static_cast<uint8_t>((c >> 6) & 0x3F);\r\n      const uint8_t b2 = 0x80 | static_cast<uint8_t>(c & 0x3F);\r\n      s.push_back(static_cast<char>(b0));\r\n      s.push_back(static_cast<char>(b1));\r\n      s.push_back(static_cast<char>(b2));\r\n      }\r\n   else if(c <= 0x10FFFF)\r\n      {\r\n      const uint8_t b0 = 0xF0 | static_cast<uint8_t>(c >> 18);\r\n      const uint8_t b1 = 0x80 | static_cast<uint8_t>((c >> 12) & 0x3F);\r\n      const uint8_t b2 = 0x80 | static_cast<uint8_t>((c >> 6) & 0x3F);\r\n      const uint8_t b3 = 0x80 | static_cast<uint8_t>(c & 0x3F);\r\n      s.push_back(static_cast<char>(b0));\r\n      s.push_back(static_cast<char>(b1));\r\n      s.push_back(static_cast<char>(b2));\r\n      s.push_back(static_cast<char>(b3));\r\n      }\r\n   else\r\n      throw Decoding_Error(\"Invalid Unicode character\");\r\n\r\n   }\r\n\r\n}\r\n\r\nstd::string ucs2_to_utf8(const uint8_t ucs2[], size_t len)\r\n   {\r\n   if(len % 2 != 0)\r\n      throw Decoding_Error(\"Invalid length for UCS-2 string\");\r\n\r\n   const size_t chars = len / 2;\r\n\r\n   std::string s;\r\n   for(size_t i = 0; i != chars; ++i)\r\n      {\r\n      const uint16_t c = load_be<uint16_t>(ucs2, i);\r\n      append_utf8_for(s, c);\r\n      }\r\n\r\n   return s;\r\n   }\r\n\r\nstd::string ucs4_to_utf8(const uint8_t ucs4[], size_t len)\r\n   {\r\n   if(len % 4 != 0)\r\n      throw Decoding_Error(\"Invalid length for UCS-4 string\");\r\n\r\n   const size_t chars = len / 4;\r\n\r\n   std::string s;\r\n   for(size_t i = 0; i != chars; ++i)\r\n      {\r\n      const uint32_t c = load_be<uint32_t>(ucs4, i);\r\n      append_utf8_for(s, c);\r\n      }\r\n\r\n   return s;\r\n   }\r\n\r\n/*\r\n* Convert from UTF-8 to ISO 8859-1\r\n*/\r\nstd::string utf8_to_latin1(const std::string& utf8)\r\n   {\r\n   std::string iso8859;\r\n\r\n   size_t position = 0;\r\n   while(position != utf8.size())\r\n      {\r\n      const uint8_t c1 = static_cast<uint8_t>(utf8[position++]);\r\n\r\n      if(c1 <= 0x7F)\r\n         {\r\n         iso8859 += static_cast<char>(c1);\r\n         }\r\n      else if(c1 >= 0xC0 && c1 <= 0xC7)\r\n         {\r\n         if(position == utf8.size())\r\n            throw Decoding_Error(\"UTF-8: sequence truncated\");\r\n\r\n         const uint8_t c2 = static_cast<uint8_t>(utf8[position++]);\r\n         const uint8_t iso_char = ((c1 & 0x07) << 6) | (c2 & 0x3F);\r\n\r\n         if(iso_char <= 0x7F)\r\n            throw Decoding_Error(\"UTF-8: sequence longer than needed\");\r\n\r\n         iso8859 += static_cast<char>(iso_char);\r\n         }\r\n      else\r\n         throw Decoding_Error(\"UTF-8: Unicode chars not in Latin1 used\");\r\n      }\r\n\r\n   return iso8859;\r\n   }\r\n\r\nnamespace Charset {\r\n\r\nnamespace {\r\n\r\n/*\r\n* Convert from UCS-2 to ISO 8859-1\r\n*/\r\nstd::string ucs2_to_latin1(const std::string& ucs2)\r\n   {\r\n   if(ucs2.size() % 2 == 1)\r\n      throw Decoding_Error(\"UCS-2 string has an odd number of bytes\");\r\n\r\n   std::string latin1;\r\n\r\n   for(size_t i = 0; i != ucs2.size(); i += 2)\r\n      {\r\n      const uint8_t c1 = ucs2[i];\r\n      const uint8_t c2 = ucs2[i+1];\r\n\r\n      if(c1 != 0)\r\n         throw Decoding_Error(\"UCS-2 has non-Latin1 characters\");\r\n\r\n      latin1 += static_cast<char>(c2);\r\n      }\r\n\r\n   return latin1;\r\n   }\r\n\r\n/*\r\n* Convert from ISO 8859-1 to UTF-8\r\n*/\r\nstd::string latin1_to_utf8(const std::string& iso8859)\r\n   {\r\n   std::string utf8;\r\n   for(size_t i = 0; i != iso8859.size(); ++i)\r\n      {\r\n      const uint8_t c = static_cast<uint8_t>(iso8859[i]);\r\n\r\n      if(c <= 0x7F)\r\n         utf8 += static_cast<char>(c);\r\n      else\r\n         {\r\n         utf8 += static_cast<char>((0xC0 | (c >> 6)));\r\n         utf8 += static_cast<char>((0x80 | (c & 0x3F)));\r\n         }\r\n      }\r\n   return utf8;\r\n   }\r\n\r\n}\r\n\r\n/*\r\n* Perform character set transcoding\r\n*/\r\nstd::string transcode(const std::string& str,\r\n                      Character_Set to, Character_Set from)\r\n   {\r\n   if(to == LOCAL_CHARSET)\r\n      to = LATIN1_CHARSET;\r\n   if(from == LOCAL_CHARSET)\r\n      from = LATIN1_CHARSET;\r\n\r\n   if(to == from)\r\n      return str;\r\n\r\n   if(from == LATIN1_CHARSET && to == UTF8_CHARSET)\r\n      return latin1_to_utf8(str);\r\n   if(from == UTF8_CHARSET && to == LATIN1_CHARSET)\r\n      return utf8_to_latin1(str);\r\n   if(from == UCS2_CHARSET && to == LATIN1_CHARSET)\r\n      return ucs2_to_latin1(str);\r\n\r\n   throw Invalid_Argument(\"Unknown transcoding operation from \" +\r\n                          std::to_string(from) + \" to \" + std::to_string(to));\r\n   }\r\n\r\n/*\r\n* Check if a character represents a digit\r\n*/\r\nbool is_digit(char c)\r\n   {\r\n   if(c == '0' || c == '1' || c == '2' || c == '3' || c == '4' ||\r\n      c == '5' || c == '6' || c == '7' || c == '8' || c == '9')\r\n      return true;\r\n   return false;\r\n   }\r\n\r\n/*\r\n* Check if a character represents whitespace\r\n*/\r\nbool is_space(char c)\r\n   {\r\n   if(c == ' ' || c == '\\t' || c == '\\n' || c == '\\r')\r\n      return true;\r\n   return false;\r\n   }\r\n\r\n/*\r\n* Convert a character to a digit\r\n*/\r\nuint8_t char2digit(char c)\r\n   {\r\n   switch(c)\r\n      {\r\n      case '0': return 0;\r\n      case '1': return 1;\r\n      case '2': return 2;\r\n      case '3': return 3;\r\n      case '4': return 4;\r\n      case '5': return 5;\r\n      case '6': return 6;\r\n      case '7': return 7;\r\n      case '8': return 8;\r\n      case '9': return 9;\r\n      }\r\n\r\n   throw Invalid_Argument(\"char2digit: Input is not a digit character\");\r\n   }\r\n\r\n/*\r\n* Convert a digit to a character\r\n*/\r\nchar digit2char(uint8_t b)\r\n   {\r\n   switch(b)\r\n      {\r\n      case 0: return '0';\r\n      case 1: return '1';\r\n      case 2: return '2';\r\n      case 3: return '3';\r\n      case 4: return '4';\r\n      case 5: return '5';\r\n      case 6: return '6';\r\n      case 7: return '7';\r\n      case 8: return '8';\r\n      case 9: return '9';\r\n      }\r\n\r\n   throw Invalid_Argument(\"digit2char: Input is not a digit\");\r\n   }\r\n\r\n/*\r\n* Case-insensitive character comparison\r\n*/\r\nbool caseless_cmp(char a, char b)\r\n   {\r\n   return (std::tolower(static_cast<unsigned char>(a)) ==\r\n           std::tolower(static_cast<unsigned char>(b)));\r\n   }\r\n\r\n}\r\n\r\n}\r\n/*\r\n* DataSource\r\n* (C) 1999-2007 Jack Lloyd\r\n*     2005 Matthew Gregan\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)\r\n  #include <fstream>\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\n/*\r\n* Read a single byte from the DataSource\r\n*/\r\nsize_t DataSource::read_byte(uint8_t& out)\r\n   {\r\n   return read(&out, 1);\r\n   }\r\n\r\n/*\r\n* Peek a single byte from the DataSource\r\n*/\r\nsize_t DataSource::peek_byte(uint8_t& out) const\r\n   {\r\n   return peek(&out, 1, 0);\r\n   }\r\n\r\n/*\r\n* Discard the next N bytes of the data\r\n*/\r\nsize_t DataSource::discard_next(size_t n)\r\n   {\r\n   uint8_t buf[64] = { 0 };\r\n   size_t discarded = 0;\r\n\r\n   while(n)\r\n      {\r\n      const size_t got = this->read(buf, std::min(n, sizeof(buf)));\r\n      discarded += got;\r\n      n -= got;\r\n\r\n      if(got == 0)\r\n         break;\r\n      }\r\n\r\n   return discarded;\r\n   }\r\n\r\n/*\r\n* Read from a memory buffer\r\n*/\r\nsize_t DataSource_Memory::read(uint8_t out[], size_t length)\r\n   {\r\n   size_t got = std::min<size_t>(m_source.size() - m_offset, length);\r\n   copy_mem(out, m_source.data() + m_offset, got);\r\n   m_offset += got;\r\n   return got;\r\n   }\r\n\r\nbool DataSource_Memory::check_available(size_t n)\r\n   {\r\n   return (n <= (m_source.size() - m_offset));\r\n   }\r\n\r\n/*\r\n* Peek into a memory buffer\r\n*/\r\nsize_t DataSource_Memory::peek(uint8_t out[], size_t length,\r\n                               size_t peek_offset) const\r\n   {\r\n   const size_t bytes_left = m_source.size() - m_offset;\r\n   if(peek_offset >= bytes_left) return 0;\r\n\r\n   size_t got = std::min(bytes_left - peek_offset, length);\r\n   copy_mem(out, &m_source[m_offset + peek_offset], got);\r\n   return got;\r\n   }\r\n\r\n/*\r\n* Check if the memory buffer is empty\r\n*/\r\nbool DataSource_Memory::end_of_data() const\r\n   {\r\n   return (m_offset == m_source.size());\r\n   }\r\n\r\n/*\r\n* DataSource_Memory Constructor\r\n*/\r\nDataSource_Memory::DataSource_Memory(const std::string& in) :\r\n   m_source(cast_char_ptr_to_uint8(in.data()),\r\n            cast_char_ptr_to_uint8(in.data()) + in.length()),\r\n   m_offset(0)\r\n   {\r\n   }\r\n\r\n/*\r\n* Read from a stream\r\n*/\r\nsize_t DataSource_Stream::read(uint8_t out[], size_t length)\r\n   {\r\n   m_source.read(cast_uint8_ptr_to_char(out), length);\r\n   if(m_source.bad())\r\n      throw Stream_IO_Error(\"DataSource_Stream::read: Source failure\");\r\n\r\n   const size_t got = static_cast<size_t>(m_source.gcount());\r\n   m_total_read += got;\r\n   return got;\r\n   }\r\n\r\nbool DataSource_Stream::check_available(size_t n)\r\n   {\r\n   const std::streampos orig_pos = m_source.tellg();\r\n   m_source.seekg(0, std::ios::end);\r\n   const size_t avail = static_cast<size_t>(m_source.tellg() - orig_pos);\r\n   m_source.seekg(orig_pos);\r\n   return (avail >= n);\r\n   }\r\n\r\n/*\r\n* Peek into a stream\r\n*/\r\nsize_t DataSource_Stream::peek(uint8_t out[], size_t length, size_t offset) const\r\n   {\r\n   if(end_of_data())\r\n      throw Invalid_State(\"DataSource_Stream: Cannot peek when out of data\");\r\n\r\n   size_t got = 0;\r\n\r\n   if(offset)\r\n      {\r\n      secure_vector<uint8_t> buf(offset);\r\n      m_source.read(cast_uint8_ptr_to_char(buf.data()), buf.size());\r\n      if(m_source.bad())\r\n         throw Stream_IO_Error(\"DataSource_Stream::peek: Source failure\");\r\n      got = static_cast<size_t>(m_source.gcount());\r\n      }\r\n\r\n   if(got == offset)\r\n      {\r\n      m_source.read(cast_uint8_ptr_to_char(out), length);\r\n      if(m_source.bad())\r\n         throw Stream_IO_Error(\"DataSource_Stream::peek: Source failure\");\r\n      got = static_cast<size_t>(m_source.gcount());\r\n      }\r\n\r\n   if(m_source.eof())\r\n      m_source.clear();\r\n   m_source.seekg(m_total_read, std::ios::beg);\r\n\r\n   return got;\r\n   }\r\n\r\n/*\r\n* Check if the stream is empty or in error\r\n*/\r\nbool DataSource_Stream::end_of_data() const\r\n   {\r\n   return (!m_source.good());\r\n   }\r\n\r\n/*\r\n* Return a human-readable ID for this stream\r\n*/\r\nstd::string DataSource_Stream::id() const\r\n   {\r\n   return m_identifier;\r\n   }\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)\r\n\r\n/*\r\n* DataSource_Stream Constructor\r\n*/\r\nDataSource_Stream::DataSource_Stream(const std::string& path,\r\n                                     bool use_binary) :\r\n   m_identifier(path),\r\n   m_source_memory(new std::ifstream(path, use_binary ? std::ios::binary : std::ios::in)),\r\n   m_source(*m_source_memory),\r\n   m_total_read(0)\r\n   {\r\n   if(!m_source.good())\r\n      {\r\n      throw Stream_IO_Error(\"DataSource: Failure opening file \" + path);\r\n      }\r\n   }\r\n\r\n#endif\r\n\r\n/*\r\n* DataSource_Stream Constructor\r\n*/\r\nDataSource_Stream::DataSource_Stream(std::istream& in,\r\n                                     const std::string& name) :\r\n   m_identifier(name),\r\n   m_source(in),\r\n   m_total_read(0)\r\n   {\r\n   }\r\n\r\nDataSource_Stream::~DataSource_Stream()\r\n   {\r\n   // for ~unique_ptr\r\n   }\r\n\r\n}\r\n/*\r\n* (C) 2017 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\nException::Exception(const std::string& msg) : m_msg(msg)\r\n   {}\r\n\r\nException::Exception(const char* prefix, const std::string& msg) :\r\n   m_msg(std::string(prefix) + \" \" + msg)\r\n   {}\r\n\r\nInvalid_Argument::Invalid_Argument(const std::string& msg) :\r\n   Exception(\"Invalid argument\", msg)\r\n   {}\r\n\r\nInvalid_Argument::Invalid_Argument(const std::string& msg, const std::string& where) :\r\n   Exception(\"Invalid argument\", msg + \" in \" + where)\r\n   {}\r\n\r\nLookup_Error::Lookup_Error(const std::string& type,\r\n                           const std::string& algo,\r\n                           const std::string& provider) :\r\n   Exception(\"Unavailable \" + type + \" \" + algo +\r\n             (provider.empty() ? std::string(\"\") : (\" for provider \" + provider)))\r\n   {}\r\n\r\nInternal_Error::Internal_Error(const std::string& err) :\r\n   Exception(\"Internal error: \" + err)\r\n   {}\r\n\r\nInvalid_Key_Length::Invalid_Key_Length(const std::string& name, size_t length) :\r\n   Invalid_Argument(name + \" cannot accept a key of length \" +\r\n                    std::to_string(length))\r\n   {}\r\n\r\nInvalid_IV_Length::Invalid_IV_Length(const std::string& mode, size_t bad_len) :\r\n   Invalid_Argument(\"IV length \" + std::to_string(bad_len) +\r\n                    \" is invalid for \" + mode)\r\n   {}\r\n\r\nKey_Not_Set::Key_Not_Set(const std::string& algo) :\r\n   Invalid_State(\"Key not set in \" + algo)\r\n   {}\r\n\r\nPolicy_Violation::Policy_Violation(const std::string& err) :\r\n   Invalid_State(\"Policy violation: \" + err) {}\r\n\r\nPRNG_Unseeded::PRNG_Unseeded(const std::string& algo) :\r\n   Invalid_State(\"PRNG not seeded: \" + algo)\r\n   {}\r\n\r\nAlgorithm_Not_Found::Algorithm_Not_Found(const std::string& name) :\r\n   Lookup_Error(\"Could not find any algorithm named \\\"\" + name + \"\\\"\")\r\n   {}\r\n\r\nNo_Provider_Found::No_Provider_Found(const std::string& name) :\r\n   Exception(\"Could not find any provider for algorithm named \\\"\" + name + \"\\\"\")\r\n   {}\r\n\r\nProvider_Not_Found::Provider_Not_Found(const std::string& algo, const std::string& provider) :\r\n   Lookup_Error(\"Could not find provider '\" + provider + \"' for \" + algo)\r\n   {}\r\n\r\nInvalid_Algorithm_Name::Invalid_Algorithm_Name(const std::string& name):\r\n   Invalid_Argument(\"Invalid algorithm name: \" + name)\r\n   {}\r\n\r\nEncoding_Error::Encoding_Error(const std::string& name) :\r\n   Invalid_Argument(\"Encoding error: \" + name)\r\n   {}\r\n\r\nDecoding_Error::Decoding_Error(const std::string& name) :\r\n   Invalid_Argument(\"Decoding error: \" + name)\r\n   {}\r\n\r\nDecoding_Error::Decoding_Error(const std::string& name, const char* exception_message) :\r\n   Invalid_Argument(\"Decoding error: \" + name + \" failed with exception \" + exception_message) {}\r\n\r\nIntegrity_Failure::Integrity_Failure(const std::string& msg) :\r\n   Exception(\"Integrity failure: \" + msg)\r\n   {}\r\n\r\nInvalid_OID::Invalid_OID(const std::string& oid) :\r\n   Decoding_Error(\"Invalid ASN.1 OID: \" + oid)\r\n   {}\r\n\r\nStream_IO_Error::Stream_IO_Error(const std::string& err) :\r\n   Exception(\"I/O error: \" + err)\r\n   {}\r\n\r\nSelf_Test_Failure::Self_Test_Failure(const std::string& err) :\r\n   Internal_Error(\"Self test failed: \" + err)\r\n   {}\r\n\r\nNot_Implemented::Not_Implemented(const std::string& err) :\r\n   Exception(\"Not implemented\", err)\r\n   {}\r\n\r\n}\r\n/*\r\n* (C) 2015,2017 Jack Lloyd\r\n* (C) 2015 Simon Warta (Kullo GmbH)\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)\r\n  #include <filesystem>\r\n#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)\r\n  #include <boost/filesystem.hpp>\r\n#elif defined(BOTAN_TARGET_OS_HAS_READDIR)\r\n  #include <sys/types.h>\r\n  #include <sys/stat.h>\r\n  #include <dirent.h>\r\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\r\n  #define NOMINMAX 1\r\n  #define _WINSOCKAPI_ // stop windows.h including winsock.h\r\n  #include <windows.h>\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\nnamespace {\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)\r\nstd::vector<std::string> impl_stl_filesystem(const std::string& dir)\r\n   {\r\n\tusing namespace std::experimental::filesystem;\r\n\r\n   std::vector<std::string> out;\r\n\r\n   path p(dir);\r\n\r\n   if (is_directory(p))\r\n      {\r\n      for (recursive_directory_iterator itr(p), end; itr != end; ++itr)\r\n         {\r\n         if (is_regular_file(itr->path()))\r\n            {\r\n            out.push_back(itr->path().string());\r\n            }\r\n         }\r\n      }\r\n\r\n   return out;\r\n   }\r\n\r\n#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)\r\n\r\nstd::vector<std::string> impl_boost_filesystem(const std::string& dir_path)\r\n{\r\n   namespace fs = boost::filesystem;\r\n\r\n   std::vector<std::string> out;\r\n\r\n   for(fs::recursive_directory_iterator dir(dir_path), end; dir != end; ++dir)\r\n      {\r\n      if(fs::is_regular_file(dir->path()))\r\n         {\r\n         out.push_back(dir->path().string());\r\n         }\r\n      }\r\n\r\n   return out;\r\n}\r\n\r\n#elif defined(BOTAN_TARGET_OS_HAS_READDIR)\r\nstd::vector<std::string> impl_readdir(const std::string& dir_path)\r\n   {\r\n   std::vector<std::string> out;\r\n   std::deque<std::string> dir_list;\r\n   dir_list.push_back(dir_path);\r\n\r\n   while(!dir_list.empty())\r\n      {\r\n      const std::string cur_path = dir_list[0];\r\n      dir_list.pop_front();\r\n\r\n      std::unique_ptr<DIR, std::function<int (DIR*)>> dir(::opendir(cur_path.c_str()), ::closedir);\r\n\r\n      if(dir)\r\n         {\r\n         while(struct dirent* dirent = ::readdir(dir.get()))\r\n            {\r\n            const std::string filename = dirent->d_name;\r\n            if(filename == \".\" || filename == \"..\")\r\n               continue;\r\n            const std::string full_path = cur_path + \"/\" + filename;\r\n\r\n            struct stat stat_buf;\r\n\r\n            if(::stat(full_path.c_str(), &stat_buf) == -1)\r\n               continue;\r\n\r\n            if(S_ISDIR(stat_buf.st_mode))\r\n               dir_list.push_back(full_path);\r\n            else if(S_ISREG(stat_buf.st_mode))\r\n               out.push_back(full_path);\r\n            }\r\n         }\r\n      }\r\n\r\n   return out;\r\n   }\r\n\r\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\r\n\r\nstd::vector<std::string> impl_win32(const std::string& dir_path)\r\n   {\r\n   std::vector<std::string> out;\r\n   std::deque<std::string> dir_list;\r\n   dir_list.push_back(dir_path);\r\n\r\n   while(!dir_list.empty())\r\n      {\r\n      const std::string cur_path = dir_list[0];\r\n      dir_list.pop_front();\r\n\r\n      WIN32_FIND_DATA find_data;\r\n      HANDLE dir = ::FindFirstFile((cur_path + \"/*\").c_str(), &find_data);\r\n\r\n      if(dir != INVALID_HANDLE_VALUE)\r\n         {\r\n         do\r\n            {\r\n            const std::string filename = find_data.cFileName;\r\n            if(filename == \".\" || filename == \"..\")\r\n               continue;\r\n            const std::string full_path = cur_path + \"/\" + filename;\r\n\r\n            if(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)\r\n               {\r\n               dir_list.push_back(full_path);\r\n               }\r\n            else\r\n               {\r\n               out.push_back(full_path);\r\n               }\r\n            }\r\n         while(::FindNextFile(dir, &find_data));\r\n         }\r\n\r\n      ::FindClose(dir);\r\n      }\r\n\r\n   return out;\r\n}\r\n#endif\r\n\r\n}\r\n\r\nstd::vector<std::string> get_files_recursive(const std::string& dir)\r\n   {\r\n   std::vector<std::string> files;\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)\r\n   files = impl_stl_filesystem(dir);\r\n#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)\r\n   files = impl_boost_filesystem(dir);\r\n#elif defined(BOTAN_TARGET_OS_HAS_READDIR)\r\n   files = impl_readdir(dir);\r\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\r\n   files = impl_win32(dir);\r\n#else\r\n   BOTAN_UNUSED(dir);\r\n   throw No_Filesystem_Access();\r\n#endif\r\n\r\n   std::sort(files.begin(), files.end());\r\n\r\n   return files;\r\n   }\r\n\r\n}\r\n/*\r\n* (C) 2017 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n#include <cstdlib>\r\n\r\n#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\nBOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size)\r\n   {\r\n#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)\r\n   if(void* p = mlock_allocator::instance().allocate(elems, elem_size))\r\n      return p;\r\n#endif\r\n\r\n   void* ptr = std::calloc(elems, elem_size);\r\n   if(!ptr)\r\n      throw std::bad_alloc();\r\n   return ptr;\r\n   }\r\n\r\nvoid deallocate_memory(void* p, size_t elems, size_t elem_size)\r\n   {\r\n   if(p == nullptr)\r\n      return;\r\n\r\n   secure_scrub_memory(p, elems * elem_size);\r\n\r\n#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)\r\n   if(mlock_allocator::instance().deallocate(p, elems, elem_size))\r\n      return;\r\n#endif\r\n\r\n   std::free(p);\r\n   }\r\n\r\nbool constant_time_compare(const uint8_t x[],\r\n                           const uint8_t y[],\r\n                           size_t len)\r\n   {\r\n   volatile uint8_t difference = 0;\r\n\r\n   for(size_t i = 0; i != len; ++i)\r\n      difference |= (x[i] ^ y[i]);\r\n\r\n   return difference == 0;\r\n   }\r\n\r\n}\r\n/*\r\n* OS and machine specific utility functions\r\n* (C) 2015,2016,2017 Jack Lloyd\r\n* (C) 2016 Daniel Neus\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)\r\n  #include <string.h>\r\n#endif\r\n\r\n#if defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\r\n  #include <sys/types.h>\r\n  #include <sys/resource.h>\r\n  #include <sys/mman.h>\r\n  #include <signal.h>\r\n  #include <setjmp.h>\r\n  #include <unistd.h>\r\n  #include <errno.h>\r\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\r\n  #define NOMINMAX 1\r\n  #include <windows.h>\r\n#endif\r\n\r\nnamespace Botan {\r\n\r\n// Not defined in OS namespace for historical reasons\r\nvoid secure_scrub_memory(void* ptr, size_t n)\r\n   {\r\n#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)\r\n   ::RtlSecureZeroMemory(ptr, n);\r\n\r\n#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)\r\n   ::explicit_bzero(ptr, n);\r\n\r\n#elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1)\r\n   /*\r\n   Call memset through a static volatile pointer, which the compiler\r\n   should not elide. This construct should be safe in conforming\r\n   compilers, but who knows. I did confirm that on x86-64 GCC 6.1 and\r\n   Clang 3.8 both create code that saves the memset address in the\r\n   data segment and uncondtionally loads and jumps to that address.\r\n   */\r\n   static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset;\r\n   (memset_ptr)(ptr, 0, n);\r\n#else\r\n\r\n   volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr);\r\n\r\n   for(size_t i = 0; i != n; ++i)\r\n      p[i] = 0;\r\n#endif\r\n   }\r\n\r\nuint32_t OS::get_process_id()\r\n   {\r\n#if defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\r\n   return ::getpid();\r\n#elif defined(BOTAN_TARGET_OS_IS_WINDOWS) || defined(BOTAN_TARGET_OS_IS_MINGW)\r\n   return ::GetCurrentProcessId();\r\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIKERNEL) || defined(BOTAN_TARGET_OS_IS_LLVM)\r\n   return 0; // truly no meaningful value\r\n#else\r\n   #error \"Missing get_process_id\"\r\n#endif\r\n   }\r\n\r\nuint64_t OS::get_processor_timestamp()\r\n   {\r\n   uint64_t rtc = 0;\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_QUERY_PERF_COUNTER)\r\n   LARGE_INTEGER tv;\r\n   ::QueryPerformanceCounter(&tv);\r\n   rtc = tv.QuadPart;\r\n\r\n#elif defined(BOTAN_USE_GCC_INLINE_ASM)\r\n\r\n#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)\r\n\r\n   if(CPUID::has_rdtsc())\r\n      {\r\n      uint32_t rtc_low = 0, rtc_high = 0;\r\n      asm volatile(\"rdtsc\" : \"=d\" (rtc_high), \"=a\" (rtc_low));\r\n      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;\r\n      }\r\n\r\n#elif defined(BOTAN_TARGET_ARCH_IS_PPC64)\r\n   uint32_t rtc_low = 0, rtc_high = 0;\r\n   asm volatile(\"mftbu %0; mftb %1\" : \"=r\" (rtc_high), \"=r\" (rtc_low));\r\n\r\n   /*\r\n   qemu-ppc seems to not support mftb instr, it always returns zero.\r\n   If both time bases are 0, assume broken and return another clock.\r\n   */\r\n   if(rtc_high > 0 || rtc_low > 0)\r\n      {\r\n      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;\r\n      }\r\n\r\n#elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)\r\n   asm volatile(\"rpcc %0\" : \"=r\" (rtc));\r\n\r\n   // OpenBSD does not trap access to the %tick register\r\n#elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)\r\n   asm volatile(\"rd %%tick, %0\" : \"=r\" (rtc));\r\n\r\n#elif defined(BOTAN_TARGET_ARCH_IS_IA64)\r\n   asm volatile(\"mov %0=ar.itc\" : \"=r\" (rtc));\r\n\r\n#elif defined(BOTAN_TARGET_ARCH_IS_S390X)\r\n   asm volatile(\"stck 0(%0)\" : : \"a\" (&rtc) : \"memory\", \"cc\");\r\n\r\n#elif defined(BOTAN_TARGET_ARCH_IS_HPPA)\r\n   asm volatile(\"mfctl 16,%0\" : \"=r\" (rtc)); // 64-bit only?\r\n\r\n#else\r\n   //#warning \"OS::get_processor_timestamp not implemented\"\r\n#endif\r\n\r\n#endif\r\n\r\n   return rtc;\r\n   }\r\n\r\nuint64_t OS::get_high_resolution_clock()\r\n   {\r\n   if(uint64_t cpu_clock = OS::get_processor_timestamp())\r\n      return cpu_clock;\r\n\r\n   /*\r\n   If we got here either we either don't have an asm instruction\r\n   above, or (for x86) RDTSC is not available at runtime. Try some\r\n   clock_gettimes and return the first one that works, or otherwise\r\n   fall back to std::chrono.\r\n   */\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)\r\n\r\n   // The ordering here is somewhat arbitrary...\r\n   const clockid_t clock_types[] = {\r\n#if defined(CLOCK_MONOTONIC_HR)\r\n      CLOCK_MONOTONIC_HR,\r\n#endif\r\n#if defined(CLOCK_MONOTONIC_RAW)\r\n      CLOCK_MONOTONIC_RAW,\r\n#endif\r\n#if defined(CLOCK_MONOTONIC)\r\n      CLOCK_MONOTONIC,\r\n#endif\r\n#if defined(CLOCK_PROCESS_CPUTIME_ID)\r\n      CLOCK_PROCESS_CPUTIME_ID,\r\n#endif\r\n#if defined(CLOCK_THREAD_CPUTIME_ID)\r\n      CLOCK_THREAD_CPUTIME_ID,\r\n#endif\r\n   };\r\n\r\n   for(clockid_t clock : clock_types)\r\n      {\r\n      struct timespec ts;\r\n      if(::clock_gettime(clock, &ts) == 0)\r\n         {\r\n         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);\r\n         }\r\n      }\r\n#endif\r\n\r\n   // Plain C++11 fallback\r\n   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();\r\n   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();\r\n   }\r\n\r\nuint64_t OS::get_system_timestamp_ns()\r\n   {\r\n#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)\r\n   struct timespec ts;\r\n   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0)\r\n      {\r\n      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);\r\n      }\r\n#endif\r\n\r\n   auto now = std::chrono::system_clock::now().time_since_epoch();\r\n   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();\r\n   }\r\n\r\nsize_t OS::get_memory_locking_limit()\r\n   {\r\n#if defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)\r\n   /*\r\n   * Linux defaults to only 64 KiB of mlockable memory per process\r\n   * (too small) but BSDs offer a small fraction of total RAM (more\r\n   * than we need). Bound the total mlock size to 512 KiB which is\r\n   * enough to run the entire test suite without spilling to non-mlock\r\n   * memory (and thus presumably also enough for many useful\r\n   * programs), but small enough that we should not cause problems\r\n   * even if many processes are mlocking on the same machine.\r\n   */\r\n   size_t mlock_requested = BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB;\r\n\r\n   /*\r\n   * Allow override via env variable\r\n   */\r\n   if(const char* env = std::getenv(\"BOTAN_MLOCK_POOL_SIZE\"))\r\n      {\r\n      try\r\n         {\r\n         const size_t user_req = std::stoul(env, nullptr);\r\n         mlock_requested = std::min(user_req, mlock_requested);\r\n         }\r\n      catch(std::exception&) { /* ignore it */ }\r\n      }\r\n\r\n#if defined(RLIMIT_MEMLOCK)\r\n   if(mlock_requested > 0)\r\n      {\r\n      struct ::rlimit limits;\r\n\r\n      ::getrlimit(RLIMIT_MEMLOCK, &limits);\r\n\r\n      if(limits.rlim_cur < limits.rlim_max)\r\n         {\r\n         limits.rlim_cur = limits.rlim_max;\r\n         ::setrlimit(RLIMIT_MEMLOCK, &limits);\r\n         ::getrlimit(RLIMIT_MEMLOCK, &limits);\r\n         }\r\n\r\n      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);\r\n      }\r\n#else\r\n   /*\r\n   * If RLIMIT_MEMLOCK is not defined, likely the OS does not support\r\n   * unprivileged mlock calls.\r\n   */\r\n   return 0;\r\n#endif\r\n\r\n#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)\r\n   SIZE_T working_min = 0, working_max = 0;\r\n   DWORD working_flags = 0;\r\n   if(!::GetProcessWorkingSetSizeEx(::GetCurrentProcess(), &working_min, &working_max, &working_flags))\r\n      {\r\n      return 0;\r\n      }\r\n\r\n   SYSTEM_INFO sSysInfo;\r\n   ::GetSystemInfo(&sSysInfo);\r\n\r\n   // According to Microsoft MSDN:\r\n   // The maximum number of pages that a process can lock is equal to the number of pages in its minimum working set minus a small overhead\r\n   // In the book \"Windows Internals Part 2\": the maximum lockable pages are minimum working set size - 8 pages \r\n   // But the information in the book seems to be inaccurate/outdated\r\n   // I've tested this on Windows 8.1 x64, Windows 10 x64 and Windows 7 x86\r\n   // On all three OS the value is 11 instead of 8\r\n   size_t overhead = sSysInfo.dwPageSize * 11ULL;\r\n   if(working_min > overhead)\r\n      {\r\n      size_t lockable_bytes = working_min - overhead;\r\n      if(lockable_bytes < (BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB * 1024ULL))\r\n         {\r\n         return lockable_bytes;\r\n         }\r\n      else\r\n         {\r\n         return BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB * 1024ULL;\r\n         }\r\n      }\r\n#endif\r\n\r\n   return 0;\r\n   }\r\n\r\nvoid* OS::allocate_locked_pages(size_t length)\r\n   {\r\n#if defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)\r\n\r\n#if !defined(MAP_NOCORE)\r\n   #define MAP_NOCORE 0\r\n#endif\r\n\r\n#if !defined(MAP_ANONYMOUS)\r\n   #define MAP_ANONYMOUS MAP_ANON\r\n#endif\r\n\r\n   void* ptr = ::mmap(nullptr,\r\n                      length,\r\n                      PROT_READ | PROT_WRITE,\r\n                      MAP_ANONYMOUS | MAP_SHARED | MAP_NOCORE,\r\n                      /*fd*/-1,\r\n                      /*offset*/0);\r\n\r\n   if(ptr == MAP_FAILED)\r\n      {\r\n      return nullptr;\r\n      }\r\n\r\n#if defined(MADV_DONTDUMP)\r\n   ::madvise(ptr, length, MADV_DONTDUMP);\r\n#endif\r\n\r\n   if(::mlock(ptr, length) != 0)\r\n      {\r\n      ::munmap(ptr, length);\r\n      return nullptr; // failed to lock\r\n      }\r\n\r\n   ::memset(ptr, 0, length);\r\n\r\n   return ptr;\r\n#elif defined BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK\r\n   LPVOID ptr = ::VirtualAlloc(nullptr, length, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);\r\n   if(!ptr)\r\n      {\r\n      return nullptr;\r\n      }\r\n\r\n   if(::VirtualLock(ptr, length) == 0)\r\n      {\r\n      ::VirtualFree(ptr, 0, MEM_RELEASE);\r\n      return nullptr; // failed to lock\r\n      }\r\n\r\n   return ptr;\r\n#else\r\n   BOTAN_UNUSED(length);\r\n   return nullptr; /* not implemented */\r\n#endif\r\n   }\r\n\r\nvoid OS::free_locked_pages(void* ptr, size_t length)\r\n   {\r\n   if(ptr == nullptr || length == 0)\r\n      return;\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)\r\n   secure_scrub_memory(ptr, length);\r\n   ::munlock(ptr, length);\r\n   ::munmap(ptr, length);\r\n#elif defined BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK\r\n   secure_scrub_memory(ptr, length);\r\n   ::VirtualUnlock(ptr, length);\r\n   ::VirtualFree(ptr, 0, MEM_RELEASE);\r\n#else\r\n   // Invalid argument because no way this pointer was allocated by us\r\n   throw Invalid_Argument(\"Invalid ptr to free_locked_pages\");\r\n#endif\r\n   }\r\n\r\n#if defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\r\nnamespace {\r\n\r\nstatic ::sigjmp_buf g_sigill_jmp_buf;\r\n\r\nvoid botan_sigill_handler(int)\r\n   {\r\n   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/1);\r\n   }\r\n\r\n}\r\n#endif\r\n\r\nint OS::run_cpu_instruction_probe(std::function<int ()> probe_fn)\r\n   {\r\n   volatile int probe_result = -3;\r\n\r\n#if defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\r\n   struct sigaction old_sigaction;\r\n   struct sigaction sigaction;\r\n\r\n   sigaction.sa_handler = botan_sigill_handler;\r\n   sigemptyset(&sigaction.sa_mask);\r\n   sigaction.sa_flags = 0;\r\n\r\n   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);\r\n\r\n   if(rc != 0)\r\n      throw Exception(\"run_cpu_instruction_probe sigaction failed\");\r\n\r\n   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/1);\r\n\r\n   if(rc == 0)\r\n      {\r\n      // first call to sigsetjmp\r\n      probe_result = probe_fn();\r\n      }\r\n   else if(rc == 1)\r\n      {\r\n      // non-local return from siglongjmp in signal handler: return error\r\n      probe_result = -1;\r\n      }\r\n\r\n   // Restore old SIGILL handler, if any\r\n   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);\r\n   if(rc != 0)\r\n      throw Exception(\"run_cpu_instruction_probe sigaction restore failed\");\r\n\r\n#elif defined(BOTAN_TARGET_OS_IS_WINDOWS) && defined(BOTAN_TARGET_COMPILER_IS_MSVC)\r\n\r\n   // Windows SEH\r\n   __try\r\n      {\r\n      probe_result = probe_fn();\r\n      }\r\n   __except(::GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION ?\r\n            EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)\r\n      {\r\n      probe_result = -1;\r\n      }\r\n\r\n#endif\r\n\r\n   return probe_result;\r\n   }\r\n\r\n}\r\n/*\r\n* Various string utils and parsing functions\r\n* (C) 1999-2007,2013,2014,2015 Jack Lloyd\r\n* (C) 2015 Simon Warta (Kullo GmbH)\r\n* (C) 2017 Ren\u00e9 Korthaus, Rohde & Schwarz Cybersecurity\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n#include <limits>\r\n\r\nnamespace Botan {\r\n\r\nuint16_t to_uint16(const std::string& str)\r\n   {\r\n   const uint32_t x = to_u32bit(str);\r\n\r\n   if(x >> 16)\r\n      throw Invalid_Argument(\"Integer value exceeds 16 bit range\");\r\n\r\n   return static_cast<uint16_t>(x);\r\n   }\r\n\r\nuint32_t to_u32bit(const std::string& str)\r\n   {\r\n   // std::stoul is not strict enough. Ensure that str is digit only [0-9]*\r\n   for(const char chr : str)\r\n      {\r\n      if(chr < '0' || chr > '9')\r\n         {\r\n         std::string chrAsString(1, chr);\r\n         throw Invalid_Argument(\"String contains non-digit char: \" + chrAsString);\r\n         }\r\n      }\r\n\r\n   const unsigned long int x = std::stoul(str);\r\n\r\n   constexpr bool cond = sizeof(unsigned long int) > 4;\r\n\r\n   if (cond)\r\n      {\r\n      // x might be uint64\r\n      if (x > std::numeric_limits<uint32_t>::max())\r\n         {\r\n         throw Invalid_Argument(\"Integer value of \" + str + \" exceeds 32 bit range\");\r\n         }\r\n      }\r\n\r\n   return static_cast<uint32_t>(x);\r\n   }\r\n\r\n/*\r\n* Convert a string into a time duration\r\n*/\r\nuint32_t timespec_to_u32bit(const std::string& timespec)\r\n   {\r\n   if(timespec.empty())\r\n      return 0;\r\n\r\n   const char suffix = timespec[timespec.size()-1];\r\n   std::string value = timespec.substr(0, timespec.size()-1);\r\n\r\n   uint32_t scale = 1;\r\n\r\n   if(Charset::is_digit(suffix))\r\n      value += suffix;\r\n   else if(suffix == 's')\r\n      scale = 1;\r\n   else if(suffix == 'm')\r\n      scale = 60;\r\n   else if(suffix == 'h')\r\n      scale = 60 * 60;\r\n   else if(suffix == 'd')\r\n      scale = 24 * 60 * 60;\r\n   else if(suffix == 'y')\r\n      scale = 365 * 24 * 60 * 60;\r\n   else\r\n      throw Decoding_Error(\"timespec_to_u32bit: Bad input \" + timespec);\r\n\r\n   return scale * to_u32bit(value);\r\n   }\r\n\r\n/*\r\n* Parse a SCAN-style algorithm name\r\n*/\r\nstd::vector<std::string> parse_algorithm_name(const std::string& namex)\r\n   {\r\n   if(namex.find('(') == std::string::npos &&\r\n      namex.find(')') == std::string::npos)\r\n      return std::vector<std::string>(1, namex);\r\n\r\n   std::string name = namex, substring;\r\n   std::vector<std::string> elems;\r\n   size_t level = 0;\r\n\r\n   elems.push_back(name.substr(0, name.find('(')));\r\n   name = name.substr(name.find('('));\r\n\r\n   for(auto i = name.begin(); i != name.end(); ++i)\r\n      {\r\n      char c = *i;\r\n\r\n      if(c == '(')\r\n         ++level;\r\n      if(c == ')')\r\n         {\r\n         if(level == 1 && i == name.end() - 1)\r\n            {\r\n            if(elems.size() == 1)\r\n               elems.push_back(substring.substr(1));\r\n            else\r\n               elems.push_back(substring);\r\n            return elems;\r\n            }\r\n\r\n         if(level == 0 || (level == 1 && i != name.end() - 1))\r\n            throw Invalid_Algorithm_Name(namex);\r\n         --level;\r\n         }\r\n\r\n      if(c == ',' && level == 1)\r\n         {\r\n         if(elems.size() == 1)\r\n            elems.push_back(substring.substr(1));\r\n         else\r\n            elems.push_back(substring);\r\n         substring.clear();\r\n         }\r\n      else\r\n         substring += c;\r\n      }\r\n\r\n   if(!substring.empty())\r\n      throw Invalid_Algorithm_Name(namex);\r\n\r\n   return elems;\r\n   }\r\n\r\nstd::vector<std::string> split_on(const std::string& str, char delim)\r\n   {\r\n   return split_on_pred(str, [delim](char c) { return c == delim; });\r\n   }\r\n\r\nstd::vector<std::string> split_on_pred(const std::string& str,\r\n                                       std::function<bool (char)> pred)\r\n   {\r\n   std::vector<std::string> elems;\r\n   if(str.empty()) return elems;\r\n\r\n   std::string substr;\r\n   for(auto i = str.begin(); i != str.end(); ++i)\r\n      {\r\n      if(pred(*i))\r\n         {\r\n         if(!substr.empty())\r\n            elems.push_back(substr);\r\n         substr.clear();\r\n         }\r\n      else\r\n         substr += *i;\r\n      }\r\n\r\n   if(substr.empty())\r\n      throw Invalid_Argument(\"Unable to split string: \" + str);\r\n   elems.push_back(substr);\r\n\r\n   return elems;\r\n   }\r\n\r\n/*\r\n* Join a string\r\n*/\r\nstd::string string_join(const std::vector<std::string>& strs, char delim)\r\n   {\r\n   std::string out = \"\";\r\n\r\n   for(size_t i = 0; i != strs.size(); ++i)\r\n      {\r\n      if(i != 0)\r\n         out += delim;\r\n      out += strs[i];\r\n      }\r\n\r\n   return out;\r\n   }\r\n\r\n/*\r\n* Parse an ASN.1 OID string\r\n*/\r\nstd::vector<uint32_t> parse_asn1_oid(const std::string& oid)\r\n   {\r\n   std::string substring;\r\n   std::vector<uint32_t> oid_elems;\r\n\r\n   for(auto i = oid.begin(); i != oid.end(); ++i)\r\n      {\r\n      char c = *i;\r\n\r\n      if(c == '.')\r\n         {\r\n         if(substring.empty())\r\n            throw Invalid_OID(oid);\r\n         oid_elems.push_back(to_u32bit(substring));\r\n         substring.clear();\r\n         }\r\n      else\r\n         substring += c;\r\n      }\r\n\r\n   if(substring.empty())\r\n      throw Invalid_OID(oid);\r\n   oid_elems.push_back(to_u32bit(substring));\r\n\r\n   if(oid_elems.size() < 2)\r\n      throw Invalid_OID(oid);\r\n\r\n   return oid_elems;\r\n   }\r\n\r\n/*\r\n* X.500 String Comparison\r\n*/\r\nbool x500_name_cmp(const std::string& name1, const std::string& name2)\r\n   {\r\n   auto p1 = name1.begin();\r\n   auto p2 = name2.begin();\r\n\r\n   while((p1 != name1.end()) && Charset::is_space(*p1)) ++p1;\r\n   while((p2 != name2.end()) && Charset::is_space(*p2)) ++p2;\r\n\r\n   while(p1 != name1.end() && p2 != name2.end())\r\n      {\r\n      if(Charset::is_space(*p1))\r\n         {\r\n         if(!Charset::is_space(*p2))\r\n            return false;\r\n\r\n         while((p1 != name1.end()) && Charset::is_space(*p1)) ++p1;\r\n         while((p2 != name2.end()) && Charset::is_space(*p2)) ++p2;\r\n\r\n         if(p1 == name1.end() && p2 == name2.end())\r\n            return true;\r\n         if(p1 == name1.end() || p2 == name2.end())\r\n            return false;\r\n         }\r\n\r\n      if(!Charset::caseless_cmp(*p1, *p2))\r\n         return false;\r\n      ++p1;\r\n      ++p2;\r\n      }\r\n\r\n   while((p1 != name1.end()) && Charset::is_space(*p1)) ++p1;\r\n   while((p2 != name2.end()) && Charset::is_space(*p2)) ++p2;\r\n\r\n   if((p1 != name1.end()) || (p2 != name2.end()))\r\n      return false;\r\n   return true;\r\n   }\r\n\r\n/*\r\n* Convert a decimal-dotted string to binary IP\r\n*/\r\nuint32_t string_to_ipv4(const std::string& str)\r\n   {\r\n   std::vector<std::string> parts = split_on(str, '.');\r\n\r\n   if(parts.size() != 4)\r\n      throw Decoding_Error(\"Invalid IP string \" + str);\r\n\r\n   uint32_t ip = 0;\r\n\r\n   for(auto part = parts.begin(); part != parts.end(); ++part)\r\n      {\r\n      uint32_t octet = to_u32bit(*part);\r\n\r\n      if(octet > 255)\r\n         throw Decoding_Error(\"Invalid IP string \" + str);\r\n\r\n      ip = (ip << 8) | (octet & 0xFF);\r\n      }\r\n\r\n   return ip;\r\n   }\r\n\r\n/*\r\n* Convert an IP address to decimal-dotted string\r\n*/\r\nstd::string ipv4_to_string(uint32_t ip)\r\n   {\r\n   std::string str;\r\n\r\n   for(size_t i = 0; i != sizeof(ip); ++i)\r\n      {\r\n      if(i)\r\n         str += \".\";\r\n      str += std::to_string(get_byte(i, ip));\r\n      }\r\n\r\n   return str;\r\n   }\r\n\r\nstd::string erase_chars(const std::string& str, const std::set<char>& chars)\r\n   {\r\n   std::string out;\r\n\r\n   for(auto c: str)\r\n      if(chars.count(c) == 0)\r\n         out += c;\r\n\r\n   return out;\r\n   }\r\n\r\nstd::string replace_chars(const std::string& str,\r\n                          const std::set<char>& chars,\r\n                          char to_char)\r\n   {\r\n   std::string out = str;\r\n\r\n   for(size_t i = 0; i != out.size(); ++i)\r\n      if(chars.count(out[i]))\r\n         out[i] = to_char;\r\n\r\n   return out;\r\n   }\r\n\r\nstd::string replace_char(const std::string& str, char from_char, char to_char)\r\n   {\r\n   std::string out = str;\r\n\r\n   for(size_t i = 0; i != out.size(); ++i)\r\n      if(out[i] == from_char)\r\n         out[i] = to_char;\r\n\r\n   return out;\r\n   }\r\n\r\nbool host_wildcard_match(const std::string& issued, const std::string& host)\r\n   {\r\n   if(issued == host)\r\n      {\r\n      return true;\r\n      }\r\n\r\n   size_t stars = 0;\r\n   for(char c : issued)\r\n      {\r\n      if(c == '*')\r\n         stars += 1;\r\n      }\r\n\r\n   if(stars > 1)\r\n      {\r\n      return false;\r\n      }\r\n\r\n   // first try to match the base, then the left-most label\r\n   // which can contain exactly one wildcard at any position\r\n   if(issued.size() > 2)\r\n      {\r\n      size_t host_i = host.find('.');\r\n      if(host_i == std::string::npos || host_i == host.size() - 1)\r\n         {\r\n         return false;\r\n         }\r\n\r\n      size_t issued_i = issued.find('.');\r\n      if(issued_i == std::string::npos || issued_i == issued.size() - 1)\r\n         {\r\n         return false;\r\n         }\r\n\r\n      const std::string host_base = host.substr(host_i + 1);\r\n      const std::string issued_base = issued.substr(issued_i + 1);\r\n\r\n      // if anything but the left-most label doesn't equal,\r\n      // we are already out here\r\n      if(host_base != issued_base)\r\n         {\r\n         return false;\r\n         }\r\n\r\n      // compare the left-most labels\r\n      std::string host_prefix = host.substr(0, host_i);\r\n\r\n      if(host_prefix.empty())\r\n         {\r\n         return false;\r\n         }\r\n\r\n      const std::string issued_prefix = issued.substr(0, issued_i);\r\n\r\n      // if split_on would work on strings with less than 2 items,\r\n      // the if/else block would not be necessary\r\n      if(issued_prefix == \"*\")\r\n         {\r\n         return true;\r\n         }\r\n\r\n      std::vector<std::string> p;\r\n\r\n      if(issued_prefix[0] == '*')\r\n         {\r\n         p = std::vector<std::string>{\"\", issued_prefix.substr(1, issued_prefix.size())};\r\n         }\r\n      else if(issued_prefix[issued_prefix.size()-1] == '*')\r\n         {\r\n         p = std::vector<std::string>{issued_prefix.substr(0, issued_prefix.size() - 1), \"\"};\r\n         }\r\n      else\r\n         {\r\n         p = split_on(issued_prefix, '*');\r\n         }\r\n\r\n      if(p.size() != 2)\r\n         {\r\n         return false;\r\n         }\r\n\r\n      // match anything before and after the wildcard character\r\n      const std::string first = p[0];\r\n      const std::string last = p[1];\r\n\r\n      if(host_prefix.substr(0, first.size()) == first)\r\n         {\r\n         host_prefix.erase(0, first.size());\r\n         }\r\n\r\n      // nothing to match anymore\r\n      if(last.empty())\r\n         {\r\n         return true;\r\n         }\r\n\r\n      if(host_prefix.size() >= last.size() &&\r\n            host_prefix.substr(host_prefix.size() - last.size(), last.size()) == last)\r\n         {\r\n         return true;\r\n         }\r\n      }\r\n\r\n   return false;\r\n   }\r\n}\r\n/*\r\n* Simple config/test file reader\r\n* (C) 2013,2014,2015 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\nstd::string clean_ws(const std::string& s)\r\n   {\r\n   const char* ws = \" \\t\\n\";\r\n   auto start = s.find_first_not_of(ws);\r\n   auto end = s.find_last_not_of(ws);\r\n\r\n   if(start == std::string::npos)\r\n      return \"\";\r\n\r\n   if(end == std::string::npos)\r\n      return s.substr(start, end);\r\n   else\r\n      return s.substr(start, start + end + 1);\r\n   }\r\n\r\nstd::map<std::string, std::string> read_cfg(std::istream& is)\r\n   {\r\n   std::map<std::string, std::string> kv;\r\n   size_t line = 0;\r\n\r\n   while(is.good())\r\n      {\r\n      std::string s;\r\n\r\n      std::getline(is, s);\r\n\r\n      ++line;\r\n\r\n      if(s.empty() || s[0] == '#')\r\n         continue;\r\n\r\n      s = clean_ws(s.substr(0, s.find('#')));\r\n\r\n      if(s.empty())\r\n         continue;\r\n\r\n      auto eq = s.find(\"=\");\r\n\r\n      if(eq == std::string::npos || eq == 0 || eq == s.size() - 1)\r\n         throw Exception(\"Bad read_cfg input '\" + s + \"' on line \" + std::to_string(line));\r\n\r\n      const std::string key = clean_ws(s.substr(0, eq));\r\n      const std::string val = clean_ws(s.substr(eq + 1, std::string::npos));\r\n\r\n      kv[key] = val;\r\n      }\r\n\r\n   return kv;\r\n   }\r\n\r\n}\r\n/*\r\n* Semaphore\r\n* (C) 2013 Joel Low\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\n#if defined(BOTAN_TARGET_OS_HAS_THREADS)\r\n\r\n// Based on code by Pierre Gaston (http://p9as.blogspot.com/2012/06/c11-semaphores.html)\r\n\r\nnamespace Botan {\r\n\r\nvoid Semaphore::release(size_t n)\r\n   {\r\n   for(size_t i = 0; i != n; ++i)\r\n      {\r\n      lock_guard_type<mutex_type> lock(m_mutex);\r\n\r\n      if(m_value++ < 0)\r\n         {\r\n         ++m_wakeups;\r\n         m_cond.notify_one();\r\n         }\r\n      }\r\n   }\r\n\r\nvoid Semaphore::acquire()\r\n   {\r\n   std::unique_lock<mutex_type> lock(m_mutex);\r\n   if(m_value-- <= 0)\r\n       {\r\n       m_cond.wait(lock, [this] { return m_wakeups > 0; });\r\n       --m_wakeups;\r\n       }\r\n   }\r\n\r\n}\r\n\r\n#endif\r\n/*\r\n* Version Information\r\n* (C) 1999-2013,2015 Jack Lloyd\r\n*\r\n* Botan is released under the Simplified BSD License (see license.txt)\r\n*/\r\n\r\n\r\nnamespace Botan {\r\n\r\n/*\r\n  These are intentionally compiled rather than inlined, so an\r\n  application running against a shared library can test the true\r\n  version they are running against.\r\n*/\r\n\r\n#define QUOTE(name) #name\r\n#define STR(macro) QUOTE(macro)\r\n\r\nconst char* short_version_cstr()\r\n   {\r\n   return STR(BOTAN_VERSION_MAJOR) \".\"\r\n          STR(BOTAN_VERSION_MINOR) \".\"\r\n          STR(BOTAN_VERSION_PATCH);\r\n   }\r\n\r\nconst char* version_cstr()\r\n   {\r\n\r\n   /*\r\n   It is intentional that this string is a compile-time constant;\r\n   it makes it much easier to find in binaries.\r\n   */\r\n\r\n   return \"Botan \" STR(BOTAN_VERSION_MAJOR) \".\"\r\n                   STR(BOTAN_VERSION_MINOR) \".\"\r\n                   STR(BOTAN_VERSION_PATCH) \" (\"\r\n#if defined(BOTAN_UNSAFE_FUZZER_MODE)\r\n                   \"UNSAFE FUZZER MODE BUILD \"\r\n#endif\r\n                   BOTAN_VERSION_RELEASE_TYPE\r\n#if (BOTAN_VERSION_DATESTAMP != 0)\r\n                   \", dated \" STR(BOTAN_VERSION_DATESTAMP)\r\n#endif\r\n                   \", revision \" BOTAN_VERSION_VC_REVISION\r\n                   \", distribution \" BOTAN_DISTRIBUTION_INFO \")\";\r\n   }\r\n\r\n#undef STR\r\n#undef QUOTE\r\n\r\n/*\r\n* Return the version as a string\r\n*/\r\nstd::string version_string()\r\n   {\r\n   return std::string(version_cstr());\r\n   }\r\n\r\nstd::string short_version_string()\r\n   {\r\n   return std::string(short_version_cstr());\r\n   }\r\n\r\nuint32_t version_datestamp() { return BOTAN_VERSION_DATESTAMP; }\r\n\r\n/*\r\n* Return parts of the version as integers\r\n*/\r\nuint32_t version_major() { return BOTAN_VERSION_MAJOR; }\r\nuint32_t version_minor() { return BOTAN_VERSION_MINOR; }\r\nuint32_t version_patch() { return BOTAN_VERSION_PATCH; }\r\n\r\nstd::string runtime_version_check(uint32_t major,\r\n                                  uint32_t minor,\r\n                                  uint32_t patch)\r\n   {\r\n   std::ostringstream oss;\r\n\r\n   if(major != version_major() || minor != version_minor() || patch != version_patch())\r\n      {\r\n      oss << \"Warning: linked version (\" << short_version_string() << \")\"\r\n          << \" does not match version built against \"\r\n          << \"(\" << major << '.' << minor << '.' << patch << \")\\n\";\r\n      }\r\n\r\n   return oss.str();\r\n   }\r\n\r\n}\r\n", "meta": {"hexsha": "fc46d34eb23de6d4f2ae6e3985e4ce0cf32175f0", "size": 164418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/botan/botan_all.cpp", "max_stars_repo_name": "laxtools/lax", "max_stars_repo_head_hexsha": "4b6ac5e042787f1c66e6f4771ec9aafe6b2df26b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-27T11:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-28T10:41:59.000Z", "max_issues_repo_path": "src/util/botan/botan_all.cpp", "max_issues_repo_name": "laxtools/lax", "max_issues_repo_head_hexsha": "4b6ac5e042787f1c66e6f4771ec9aafe6b2df26b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-28T07:39:31.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-26T05:03:29.000Z", "max_forks_repo_path": "src/util/botan/botan_all.cpp", "max_forks_repo_name": "laxtools/lax", "max_forks_repo_head_hexsha": "4b6ac5e042787f1c66e6f4771ec9aafe6b2df26b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-27T11:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-27T11:45:26.000Z", "avg_line_length": 26.6912337662, "max_line_length": 140, "alphanum_fraction": 0.5862557628, "num_tokens": 50699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.1881350434141486}}
{"text": "//\n//map_alignment.launch \u3092\u3064\u304b\u3063\u3066\u30d1\u30e9\u30e1\u30fc\u30bf\u8abf\u6574\u3059\u308b\n//\n//\n\n#include <ros/ros.h>\n#include <tf/transform_broadcaster.h>\n\n#include <std_msgs/String.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <nav_msgs/Odometry.h>\n#include <iostream>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\n#include <pcl/registration/ndt.h>\n#include <pcl/filters/approximate_voxel_grid.h>\n\n#include <pcl/ros/conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <boost/thread/thread.hpp>\n\n#include \"std_msgs/Int32.h\"\n#include \"std_msgs/Float64.h\"\n\n#include <math.h>\n\n#include <local_tool/filters.hpp>\n#include <local_tool/mathematics.hpp>\n#include <local_tool/registration.hpp>\n\n\ntypedef pcl::PointXYZINormal PointN;\ntypedef pcl::PointXYZ PointX;\ntypedef pcl::PointCloud<PointN>::Ptr CloudNPtr;\ntypedef pcl::PointCloud<PointX>::Ptr CloudXPtr;\n\nusing namespace std;\nusing namespace Eigen;\n\nCloudXPtr input_cloud (new pcl::PointCloud<PointX>);\nCloudXPtr limit_lidar (new pcl::PointCloud<PointX>);\nCloudXPtr limit_input_cloud (new pcl::PointCloud<PointX>);\nCloudXPtr filtered_laser_cloud (new pcl::PointCloud<PointX>);\nCloudXPtr before_laser_cloud (new pcl::PointCloud<PointX>);\nCloudXPtr local_map_cloud (new pcl::PointCloud<PointX>);\nCloudXPtr target_map_cloud (new pcl::PointCloud<PointX>);\nCloudXPtr filtered_map_cloud (new pcl::PointCloud<PointX>);\nCloudXPtr output_cloud (new pcl::PointCloud<PointX>);\n\n\nclass Align{\n\tprivate:\n\t\tros::NodeHandle n;\n\t\tros::Rate r;\n\t\tros::Subscriber velo_sub;\n\t\tros::Subscriber odom_sub;\n\t\tros::Publisher ndt_pub;\n\t\tros::Publisher vis_voxel_pub;\n\t\tros::Publisher vis_map_pub;\n\n\t\tsensor_msgs::PointCloud2 vis_laser_voxel;\n\t\tsensor_msgs::PointCloud2 vis_map;\t\n\t\tnav_msgs::Odometry odo;\n\t\tnav_msgs::Odometry odo_pub;\n\n\t\tfloat x_now,y_now,yaw_now;\n\t\tfloat z_now;\n\n\t\tfloat map_limit,laser_limit;//map\u30fblaser\u306e\u8ddd\u96e2\n\t\tstring map_file;\n\n\t\tfloat laser_size,map_size;//voxel\n\t\tbool flag;//lidar\n\t\tbool flag_laser;//lidar\n\t\tdouble l_roll, l_pitch, l_yaw;//\u89d2\u5ea6etc\n\n\n\t\tstring LIDAR_TOPIC;\n\t\tstring ODOM_TOPIC;\n\t\tstring NDT_TOPIC;\n\n\tpublic:\n\t\tAlign(ros::NodeHandle& n);\n\t\tvoid first_laser();//map\u306e\u70b9\u7fa4\u3092\u6271\u3046\n\t\tvoid maptolidar();//\u4f4d\u7f6e\u5408\u308f\u305b\u3092\u884c\u3046\n\n\n\t\tvoid odomCallback(const nav_msgs::Odometry::Ptr msg);\n\t\tvoid velodyneCallback(const sensor_msgs::PointCloud2ConstPtr input);//velodyne\u306e\u70b9\u7fa4\u3092\u6271\u3046\n\t\tbool spin()\n\t\t{\n\t\t\tros::Rate loop_rate(r);\n\n\t\t\twhile(ros::ok()){\n\t\t\t\tif(flag_laser)first_laser();\n\t\t\t\tif(flag)maptolidar();\n\t\t\t\tros::spinOnce();\n\t\t\t\tloop_rate.sleep();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n};\n\nAlign::Align(ros::NodeHandle& n) :\n\tr(10),\n\tflag(false),\n\tflag_laser(true)\n{\n\n    n.param(\"laser_voxel_size\",laser_size, 0.0f);\n    n.param(\"map_voxel_size\",map_size, 0.0f);\n    n.param(\"map_limit\",map_limit, 0.0f);\n    n.param(\"laser_limit\",laser_limit, 0.0f);\n    n.param(\"init_x\",x_now, 0.0f);\n    n.param(\"init_y\",y_now, 0.0f);\n    n.param(\"init_z\",z_now, 0.0f);\n    n.param(\"init_yaw\",yaw_now, 0.0f);\n    n.param(\"lidar_topic\",LIDAR_TOPIC, {0});\n    n.param(\"odom_topic\",ODOM_TOPIC, {0});\n    n.param(\"ndt_topic\",NDT_TOPIC, {0});\n    // n.getParam(\"ndt_topic\",NDT_TOPIC);\n\tn.getParam(\"map/d_kan_around\",map_file);\n\t// n.getParam(\"map/d_kan_indoor\",map_file);\n\t\n\t\n\tvelo_sub = n.subscribe(LIDAR_TOPIC, 1000, &Align::velodyneCallback, this);\n\todom_sub = n.subscribe(ODOM_TOPIC, 1000, &Align::odomCallback, this);\n\n\tndt_pub = n.advertise<nav_msgs::Odometry>(NDT_TOPIC, 1000);\n\tvis_voxel_pub = n.advertise<sensor_msgs::PointCloud2>(\"/ndt_result\", 1000);\n\tvis_map_pub = n.advertise<sensor_msgs::PointCloud2>(\"/vis_map\", 1000);\n\n\n\n\t// cout << \"-------PARAMETARS----------\" << endl;\n\tcout << \"map_name\uff1a\" << map_file << endl;\n\n\tl_roll = l_pitch = l_yaw = 0;\n\n}\n\n//\u73fe\u5728\u5730\u3092\u77e5\u308b\nvoid \nAlign::odomCallback(const nav_msgs::Odometry::Ptr msg){\n\n    odo.pose = msg->pose;\n\n\tx_now = msg->pose.pose.position.x;\n\ty_now = msg->pose.pose.position.y;\n\tz_now = 0;\n\n\tyaw_now = msg->pose.pose.orientation.z;\n}\n\n//lidar\u60c5\u5831\nvoid \nAlign::velodyneCallback(const sensor_msgs::PointCloud2ConstPtr input){\n\n\tflag = true;\n\tfloat d = 0;\n\n\tpcl::fromROSMsg(*input,*input_cloud);\n\n\tlimit_input_cloud->points.clear();\n\t\n    size_t velodyne_size = input_cloud->points.size();\n\tfor(size_t i = 0; i < velodyne_size; i++){\n\t\tpcl::PointXYZ temp_point;\n\t\ttemp_point.x = input_cloud->points[i].x; \n\t\ttemp_point.y = input_cloud->points[i].y;\n\t\ttemp_point.z = input_cloud->points[i].z + z_now;\n\t\t\n        d = distance(temp_point.x , temp_point.y);\n        \n        if(1.5 <= d &&d <= laser_limit){//\u3064\u304f\u3070\n\n\t\t\tlimit_input_cloud->points.push_back(temp_point);\n\t\n\t\t}\n\t\n\t}\n\n\tvoxel_grid(laser_size,limit_input_cloud,filtered_laser_cloud);\n\n}\n\n\n//\u53c2\u7167\u30c7\u30fc\u30bf\u306e\u8aad\u307f\u8fbc\u307f\nvoid \nAlign::first_laser()\n{\n\tbefore_laser_cloud = filtered_laser_cloud;\n\n\tflag_laser = false; \n}\n\n\n\n///\u30e1\u30a4\u30f3\u51e6\u7406\nvoid \nAlign::maptolidar()\n{\n\tcout << \"\u30ec\u30fc\u30b6\u304b\u3089\u5f97\u305f Filtered cloud contains \" << filtered_laser_cloud->size ()<< endl;\n\n\n\tMatrix4f a;\n\t// a = (local_map_cloud,filtered_laser_cloud,output_cloud,odo);\n\ta = registration_icp(before_laser_cloud,filtered_laser_cloud);\n\n\tcalc_rpy(a,l_roll,l_pitch,l_yaw);\n\n\todo_pub.pose.pose.position.x = x_now + a(0, 3); \n\todo_pub.pose.pose.position.y = y_now + a(1, 3); \n\todo_pub.pose.pose.orientation.z = l_yaw;  \n\n\tndt_pub.publish(odo_pub);               \n\n\tpcl::toROSMsg(*output_cloud , vis_laser_voxel);           \n\tpcl::toROSMsg(*local_map_cloud , vis_map);           \n\n\n    vis_laser_voxel.header.frame_id = \"/map\"; //laser\u306eframe_id\n\tvis_map.header.frame_id = \"/map\"; //laser\u306eframe_id\n\n\tvis_laser_voxel.header.stamp = ros::Time::now(); //laser\u306eframe_id\n\tvis_map.header.stamp = ros::Time::now(); //laser\u306eframe_id\n\n\n\tvis_voxel_pub.publish(vis_laser_voxel);\n\tvis_map_pub.publish(vis_map);\n\n\tbefore_laser_cloud = filtered_laser_cloud;\n}\n\n\n\n\n\n\nint main(int argc, char** argv){\n\tros::init(argc,argv,\"map_alignment\");\n\tros::NodeHandle n;\n\n\n\tcout<<\"-----alignment start-------\"<<endl;\n\n\tAlign align(n);\n\n\talign.spin();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "fae8cb8f7de5c124d78a3295e2cf03e2bc397a46", "size": 5954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kari_localization/src/slam2.cpp", "max_stars_repo_name": "karrykarry/kari_localization", "max_stars_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "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": "kari_localization/src/slam2.cpp", "max_issues_repo_name": "karrykarry/kari_localization", "max_issues_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kari_localization/src/slam2.cpp", "max_forks_repo_name": "karrykarry/kari_localization", "max_forks_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "max_forks_repo_licenses": ["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.0775193798, "max_line_length": 86, "alphanum_fraction": 0.7096069869, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.1880985098461631}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  Defines the as_simd metafunction for SSE2 like extensions\n\n  @copyright 2012 - 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_ARCH_X86_SSE2_AS_SIMD_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE2_AS_SIMD_HPP_INCLUDED\n\n#include <boost/simd/arch/x86/sse1/as_simd.hpp>\n#include <boost/dispatch/meta/is_natural.hpp>\n\nnamespace boost { namespace simd\n{\n  template<typename T> struct logical;\n\n  namespace ext\n  {\n    template<> struct as_simd<double, boost::simd::sse_>\n    {\n      using type = __m128d;\n    };\n\n    template<typename T>\n    struct as_simd< T, boost::simd::sse_\n                  , typename std::enable_if<boost::dispatch::is_natural<T>::value>::type\n                  >\n    {\n      using type = __m128i;\n    };\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "412298c889165ce6424d948ff81140dac074afc9", "size": 1092, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/x86/sse2/as_simd.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/x86/sse2/as_simd.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/x86/sse2/as_simd.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": 26.0, "max_line_length": 100, "alphanum_fraction": 0.5595238095, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18809850625490437}}
{"text": "/*\n * Copyright 2009-2020 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 *\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/test/tools/old/interface.hpp>\n#include <ostream>\n#include <sstream>\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE statetracker_test\n\n// Standard includes\n#include <fstream>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// VOTCA includes\n#include <votca/tools/eigenio_matrixmarket.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/statetracker.h\"\n#include <libint2/initialize.h>\nusing namespace votca::xtp;\nusing namespace std;\nBOOST_AUTO_TEST_SUITE(statetracker_test)\nBOOST_AUTO_TEST_CASE(osc) {\n  libint2::initialize();\n  Orbitals orb;\n  orb.QMAtoms().LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +\n                             \"/statetracker/molecule.xyz\");\n  orb.setDFTbasisName(std::string(XTP_TEST_DATA_FOLDER) +\n                      \"/statetracker/3-21G.xml\");\n  Logger log;\n  orb.setBasisSetSize(17);\n  orb.setNumberOfOccupiedLevels(4);\n  orb.setBSEindices(0, 16);\n  orb.setTDAApprox(true);\n\n  Eigen::MatrixXd& MOs = orb.MOs().eigenvectors();\n\n  orb.MOs().eigenvalues() = Eigen::VectorXd::Ones(17);\n  MOs = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/statetracker/MOs.mm\");\n\n  Eigen::VectorXd se_ref = Eigen::VectorXd::Zero(3);\n  se_ref << 0.107455, 0.107455, 0.107455;\n  orb.BSESinglets().eigenvalues() = se_ref;\n\n  // reference coefficients\n  Eigen::MatrixXd spsi_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/statetracker/spsi_ref.mm\");\n\n  orb.BSESinglets().eigenvectors() = spsi_ref;\n  orb.CalcCoupledTransition_Dipoles();\n\n  {\n    votca::tools::Property prop;\n    prop.LoadFromXML(std::string(XTP_TEST_DATA_FOLDER) +\n                     \"/statetracker/statetracker.xml\");\n    StateTracker tracker;\n    tracker.setLogger(&log);\n    QMState s(\"s1\");\n    tracker.setInitialState(s);\n    tracker.Initialize(prop.get(\"statetracker\"));\n    QMState newstate = tracker.CalcState(orb);\n    BOOST_CHECK_EQUAL(newstate.Type().ToString(), \"s\");\n    BOOST_CHECK_EQUAL(newstate.StateIdx(), 1);\n  }\n  libint2::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(readwrite_hdf5) {\n  votca::tools::Property prop;\n  prop.LoadFromXML(std::string(XTP_TEST_DATA_FOLDER) +\n                   \"/statetracker/statetracker2.xml\");\n\n  Logger log;\n  StateTracker tracker;\n  tracker.setLogger(&log);\n  QMState s(\"s1\");\n  tracker.setInitialState(s);\n  tracker.Initialize(prop.get(\"statetracker\"));\n  tracker.PrintInfo();\n  std::stringstream ss;\n  ss << log << std::flush;\n\n  std::string output1 = ss.str();\n\n  {\n    CheckpointFile f(\"statetracker_test.hdf5\");\n    CheckpointWriter w = f.getWriter();\n    tracker.WriteToCpt(w);\n  }\n  StateTracker tracker2;\n  CheckpointFile f(\"statetracker_test.hdf5\");\n  CheckpointReader r = f.getReader();\n  tracker2.ReadFromCpt(r);\n  tracker2.setLogger(&log);\n  tracker2.PrintInfo();\n  std::stringstream ss2;\n  ss2 << log << std::flush;\n  BOOST_CHECK_EQUAL(tracker.InitialState().ToString(),\n                    tracker2.InitialState().ToString());\n\n  BOOST_CHECK_EQUAL(output1, ss2.str());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ca4b0a5866b2750495795d5ad50369188c56ce91", "size": 3661, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_statetracker.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/tests/test_statetracker.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/tests/test_statetracker.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": 30.2561983471, "max_line_length": 76, "alphanum_fraction": 0.7080032778, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.18809850266364564}}
{"text": "//          Copyright Rein Halbersma 2010-2021.\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 <core/board/sequence.hpp>\n#include <dctl/core/action.hpp>\n#include <dctl/core/board.hpp>          // international\n#include <dctl/core/rules.hpp>\n#include <dctl/core/state.hpp>\n#include <boost/mpl/vector.hpp>         // vector\n#include <boost/test/unit_test.hpp>     // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_SUITE_END, BOOST_AUTO_TEST_CASE_TEMPLATE\n#include <iostream>\n\nusing namespace dctl::core;\n\nBOOST_AUTO_TEST_SUITE(SetupLayout)\n\nusing RSequence = boost::mpl::vector\n<\n        checkers,\n        czech,\n        frisian,\n        international,\n        italian,\n        pool,\n        russian,\n        spanish,\n        thai\n>;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(initial, T, BoardSequence)\n{\n        auto const s = basic_state<international, T>::initial();\n        std::cout << diag << s;\n        std::cout << \"W = \" << T::width << \", H = \" << T::height << \", P = \" << T::coloring << \", bits = \" << T::bits() << \"\\n\\n\";\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(ActionSize, T, RSequence)\n{\n        using A = basic_action<T, basic_board<international>>;\n        std::cout << \"sizeof(Action) = \" << sizeof(A) << \"\\n\";\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(StateSize, T, RSequence)\n{\n        using state = basic_state<T, basic_board<international>>;\n        std::cout << \"sizeof(state) = \" << sizeof(state) << \"(\" << sizeof(square_t<basic_mask<board_t<state>>>) << \")\" << \"\\n\";\n}\n\nBOOST_AUTO_TEST_CASE(Grid)\n{\n        auto const d = detail::dimensions{1,1,0};\n        auto const i = detail::InnerGrid{d};\n        auto const o = detail::bit_layout{i, 2};\n        std::cout << \"W = \" << i.width() << \", H = \" << i.height() << \", P = \" << i.coloring() << \", bits = \" << i.size() << \"\\n\\n\";\n        std::cout << \"W = \" << o.width() << \", H = \" << o.height() << \", P = \" << o.coloring() << \", bits = \" << o.size() << \"\\n\\n\";\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "05af97ed740c0703af8f61fd64b04768bc636e81", "size": 2057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/core/ui/layout.cpp", "max_stars_repo_name": "rhalbersma/dctl", "max_stars_repo_head_hexsha": "c38097f41ed74f172b486582b435954ceede67b6", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-11-22T10:01:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T07:22:12.000Z", "max_issues_repo_path": "test/src/core/ui/layout.cpp", "max_issues_repo_name": "rhalbersma/dctl", "max_issues_repo_head_hexsha": "c38097f41ed74f172b486582b435954ceede67b6", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2016-11-21T08:56:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T19:40:51.000Z", "max_forks_repo_path": "test/src/core/ui/layout.cpp", "max_forks_repo_name": "rhalbersma/dctl", "max_forks_repo_head_hexsha": "c38097f41ed74f172b486582b435954ceede67b6", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-06-20T08:30:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-29T21:30:37.000Z", "avg_line_length": 33.7213114754, "max_line_length": 132, "alphanum_fraction": 0.5916383082, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18809849907238693}}
{"text": "// -*- mode: c++; indent-tabs-mode: t; tab-width: 4; c-basic-offset: 4; -*-\n/**\n   c) Tokuo Tsuji (Kyushu univ./AIST) and Kensuke Harada (AIST)\n*/\n\n#include <fstream>\n#include <string>\n#include <iostream>\n\n#include <math.h>\n\n#include <algorithm>\n#include <time.h>\n#ifndef WIN32\n#include <sys/resource.h>\n#endif\n\n#include <boost/filesystem.hpp>\n\n#include <cnoid/JointPath>\t/* modified by qtconv.rb 0th rule*/\n#include <cnoid/MessageView>\t/* modified by qtconv.rb 0th rule*/\n#include <cnoid/ExecutablePath>\n\n//#define DEBUG_MODE\n//#define SET_TOLERANCE_MODE\n\n#include \"GraspController.h\"\n#include \"PlaceController.h\"\n#include \"readtext.h\"\n#include \"VectorMath.h\"\n#include \"ForceClosureTest.h\"\n\n#include \"GraspPluginManager.h\"\n\n//#define BOOST_PYTHON_STATIC_LIB\n//#ifndef NDEBUG\n//#define BOOST_DEBUG_PYTHON\n//#endif\n#include <boost/python.hpp>\n#include <boost/make_shared.hpp>\n\n#define deg2Rad(x)   ((x)*(3.141596)/(180.0))\n#define m_pi    (3.141596)\n\n\n\nnamespace grasp{\n\n\nvoid _initrand(){\n#ifdef WIN32\n\t  srand((unsigned)time(NULL));\n#else\n\t  srand48(time(0));\n#endif\n\t}\n\n#ifdef WIN32\ndouble getrusage_sec() {\n\treturn clock();\n}\n#else\ndouble getrusage_sec() {\n\tstruct rusage t;\n\tstruct timeval tv;\n\tgetrusage(RUSAGE_SELF, &t);\n\ttv = t.ru_utime;\n\treturn tv.tv_sec + (double)tv.tv_usec*1e-6;\n}\n#endif\n\nclass PythonConverter{\n\tpublic:\n\t\tstatic PythonConverter* instance(){\n\t\t\tstatic PythonConverter* instance = new PythonConverter;\n\t\t\treturn instance;\n\t\t}\n\t\tstatic cnoid::Vector3 setVector3(double a, double b, double c){\n\t\t\treturn cnoid::Vector3(a,b,c);\n\t\t}\n};\n\n}\n\nBOOST_PYTHON_MODULE( grasp )\n{\nusing namespace boost::python;\n //   class_<grasp::GraspController, boost::noncopyable>(\"GraspController\", no_init)\n //       .def(\"instance\", &grasp::GraspController::instance, return_value_policy<reference_existing_object>()).staticmethod(\"instance\")\n //   ;\n    class_<grasp::PlanBase, boost::noncopyable>(\"PlanBase\", no_init)\n        .def(\"instance\", &grasp::PlanBase::instance, return_value_policy<reference_existing_object>()).staticmethod(\"instance\")\n        .def(\"initial\", &grasp::PlanBase::initial)\n//        .def(\"doGraspPlanning\", &grasp::PlanBase::doGraspPlanning)\n //       .def(\"doPlacePlanning\", &grasp::PlanBase::doPlacePlanning)\n  //      .def(\"doPickAndPlacePlanning\", &grasp::PlanBase::doPickAndPlacePlanning)\n\t\t.add_property(\"stopFlag\", &grasp::PlanBase::stopFlag) //test\n    ;\n\tclass_<cnoid::BodyItemPtr>(\"BodyItemPtr\")\n\t;\n\tclass_<cnoid::Vector3>(\"Vector3\")\n\t;\n    class_<grasp::PythonConverter>(\"PythonConverter\")\n\t\t.def(\"Vector3\", &grasp::PythonConverter::setVector3).staticmethod(\"Vector3\")\n\t;\n}\n\nusing namespace std;\nusing namespace cnoid;\nusing namespace grasp;\nusing namespace boost;\n\nMotionState PlanBase::getMotionState(double time){\n\tMotionState ret;\n\n\tret.jointSeq = VectorXd(body()->numJoints());\n\tfor(int i=0;i<body()->numJoints();i++)\n        ret.jointSeq[i] = body()->joint(i)->q();\n\n    ret.pos = body()->link(0)->p();\n    ret.rpy = rpyFromRot(body()->link(0)->R());\n\n\tret.graspingState = getGraspingState();\n\tret.graspingState2 = getGraspingState2();\n\tif( getGraspingState()==GRASPING ){\n\t\tret.objectPalmPos = targetArmFinger->objectPalmPos;\n\t\tret.objectPalmRot = targetArmFinger->objectPalmRot;\n\t}\n\tret.objectContactState = getObjectContactState();\n\tret.pathPlanDOF = pathPlanDOF;\n\tret.tolerance = tolerance;\n\tret.time = time;\n\tret.id = motionId;\n\treturn ret;\n}\n\nvoid PlanBase::setMotionState(MotionState gm){\n\tfor(int i=0;i<body()->numJoints();i++){\n        body()->joint(i)->q() = gm.jointSeq[i];\n\t}\n    body()->link(0)->p() = gm.pos;\n    body()->link(0)->R() = rotFromRpy(gm.rpy);\n\n\tsetGraspingState(gm.graspingState);\n\tsetGraspingState2(gm.graspingState2);\n\tif( getGraspingState()==GRASPING ){\n\t\ttargetArmFinger->objectPalmPos = gm.objectPalmPos;\n\t\ttargetArmFinger->objectPalmRot = gm.objectPalmRot;\n\t}\n\tsetObjectContactState(gm.objectContactState);\n\tpathPlanDOF = gm.pathPlanDOF;\n\tsetTolerance(gm.tolerance);\n\tcalcForwardKinematics();\n\tmotionId = gm.id;\n}\n\nPlanBase::PlanBase()  : \tos (MessageView::mainInstance()->cout() )\n{\n//\tbodyItemRobot = NULL;\n//\tbodyItemGRC = NULL;\n\ttargetObject = NULL;\n\ttargetArmFinger=NULL;\n\tstopFlag = false;\n//\trefSize = refCsSize = 0;\n//\tarm = NULL;\n//\tfingers = NULL;\n\tgraspingState = NOT_GRASPING;\n\tgraspingState2 = NOT_GRASPING;\n\ttolerance = 0.0;\n\tulimitMap=Vector3(1,1,1);\n\tllimitMap = Vector3(-1,-1,-1);\n\tdoInitialCollision=true;\n\tuseObjectSafeBoundingBox = false;\n\tuseRobotSafeBoundingBox = false;\n\tboundingBoxSafetySize = Vector3(0.005,0.005,0.005);\n\tmotionId = -1;\n\n    if ( PyImport_AppendInittab( (char *)\"grasp\", initgrasp ) == -1 ) {\n        MessageView::mainInstance()->put(\"faild init Grasp Module\");\n//        return;\n    }\n}\n\nPlanBase::~PlanBase() {\n\tRemoveAllPointCloudEnvironment();\n}\n\nPlanBase* PlanBase::instance(PlanBase *gc) {\n\tstatic PlanBase* instance = (gc) ? gc : new PlanBase();\n\tif(gc) instance = gc;\n\treturn instance;\n}\n\nTargetObject::TargetObject(cnoid::BodyItemPtr bodyItem){\n\tbodyItemObject = bodyItem;\n\tobject = bodyItemObject->body()->link(0);\n    objVisPos = object->p();\n    objVisRot = object->R();\n    objMass = object->m();\n\toffsetApplied = false;\n}\n\n\nvoid PlanBase::SetGraspedObject(cnoid::BodyItemPtr bodyItem){\n\n\ttargetObject = new TargetObject(bodyItem); //shoud be chaged;\n\n\tBox& OCP = targetObject->OCP;\n\tcalcBoundingBox(object()->coldetModel(), OCP.edge, OCP.p, targetObject->objCoM_, OCP.R);\n\tif(targetArmFinger){\n\t\tfor(int i=0;i<nFing();i++) fingers(i)->coldetLinkPair(targetObject->bodyItemObject);\n#ifdef  CNOID_10_11_12_13\n\t\tarm()->palmObjPair = new ColdetLinkPair(palm(),object() );\n#else\n\t\tarm()->palmObjPair = make_shared<ColdetLinkPair>(body(), palm(), bodyItem->body(), object() );\n#endif\n\t}\n\tstring tagId = bodyItem->name();\n\tif(objTag2Item.find(tagId) == objTag2Item.end()){\n\t\tobjTag2Item.insert( pair <string,BodyItemPtr>(tagId, bodyItem) );\n\t}\n\tsetObjectContactState(ON_ENVIRONMENT) ;\n\n\ttargetObject->safeBoundingBox = ColdetPairData::getSafeBoundingBox(object()->coldetModel(), boundingBoxSafetySize);\n\n\tinitialCollision();\n}\n\nArmFingers::ArmFingers(cnoid::BodyItemPtr bodyItem, const YamlMapping& gSettings) :  os (MessageView::mainInstance()->cout() )\n{\n\tbodyItemRobot = bodyItem;\n\n#ifdef CNOID_10_11\n\tboost::filesystem::path robotfullpath( bodyItemRobot->modelFilePath() );\n#else\n\tboost::filesystem::path robotfullpath( bodyItemRobot->lastAccessedFilePath() );\n#endif\n\n\tcout << robotfullpath.string() << endl;\n\tbodyItemRobotPath = boost::filesystem::path (robotfullpath.branch_path()).string();\n\tdataFilePath = bodyItemRobotPath + \"/data/\";\n\n\t//READ YAML setting\n\n\tpalm = bodyItemRobot->body()->link(gSettings[\"palm\"].toString());\n\tbase = bodyItemRobot->body()->link(gSettings[\"base\"].toString());\n\n\tconst YamlSequence& tips = *gSettings[\"fingerEnds\"].toSequence();\n\n\tnFing = tips.size();\n\tfingers = new FingerPtr[nFing];\n\n\tarm=NULL;\n\tfor (int i = 0;i < tips.size();i++) {\n\t\tfingers[i]=NULL;\n\t}\n\n\tif( gSettings.find(\"GrasplotPluginDir\")->type() == YAML_SCALAR ){\n#ifdef WIN32\n\t\tstring pluginPath =  cnoid::executableTopDirectory() + string(\"\\\\bin\\\\\") + bodyItemRobot->name() + string(\"\\\\\");\n#else\n\t\tstring pluginPath = bodyItemRobotPath + \"/\" + gSettings[\"GrasplotPluginDir\"].toString();\n#endif\n\t\tos << \"Grasplot Plugin Path \" << pluginPath << endl;\n\t\tgPluginManager.scanPluginFiles(pluginPath);\n\n\t\tarm = (Arm *)gPluginManager.loadGrasplotPlugin(bodyItemRobot->body(),base,palm, \"Arm\");\n\n\t\tfor (int i = 0;i < tips.size();i++) {\n\t\t\tif(!fingers[i]) fingers[i] = (Finger *)gPluginManager.loadGrasplotPlugin\n\t\t\t\t\t(bodyItemRobot->body(), palm, bodyItemRobot->body()->link(tips[i].toString()), \"Finger\");\n\t\t}\n\t}\n\tif(!arm){\n\t\tarm = new Arm(bodyItemRobot->body(),base, palm);\n\t}\n\tfor (int i = 0;i < tips.size();i++) {\n\t\tif(!fingers[i]) fingers[i] = new Finger(bodyItemRobot->body(), palm, bodyItemRobot->body()->link(tips[i].toString()) );\n\t\tfingers[i]->number = i;\n\t}\n\n\tif( gSettings.find(\"dataFilePath\")->type() == YAML_SCALAR ){\n\t\tdataFilePath = bodyItemRobotPath + \"/\" + gSettings[\"dataFilePath\"].toString() +\"/\";\n\t}\n\n\tif( gSettings.find(\"armStandardPose\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"armStandardPose\"].toSequence();\n\t\tfor(int i=0;i<list.size();i++){\n\t\t\tarm->armStandardPose.push_back(list[i].toDouble());\n\t\t}\n\t}\n\n\tif( gSettings.find(\"armFinalPose\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"armFinalPose\"].toSequence();\n\t\tfor(int i=0;i<list.size();i++){\n\t\t\tarm->armFinalPose.push_back(list[i].toDouble());\n\t\t}\n\t}\n\n\tif( gSettings.find(\"fingerOpenPose\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"fingerOpenPose\"].toSequence();\n\t\tint j=0;\n\t\tint k=0;\n\t\tfor(int i=0;i<list.size();i++){\n\t\t\tif(i>=k+fingers[j]->fing_path->numJoints()){\n\t\t\t\tk += fingers[j]->fing_path->numJoints();\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tfingers[j]->fingerOpenPose.push_back(list[i].toDouble());\n\t\t}\n\t}\n\n\tif( gSettings.find(\"fingerOpenPoseOffset\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"fingerOpenPoseOffset\"].toSequence();\n\t\tint j=0;\n\t\tint k=0;\n\t\tfor(int i=0;i<list.size();i++){\n\t\t\tif(i>=k+fingers[j]->fing_path->numJoints()){\n\t\t\t\tk += fingers[j]->fing_path->numJoints();\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tfingers[j]->fingerOpenPoseOffset.push_back(list[i].toDouble());\n\t\t}\n\t}\n\n\tif( gSettings.find(\"fingerCloseOffset\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"fingerCloseOffset\"].toSequence();\n\t\tint j=0;\n\t\tint k=0;\n\t\tfor(int i=0;i<list.size();i++){\n\t\t\tif(i>=k+fingers[j]->fing_path->numJoints()){\n\t\t\t\tk += fingers[j]->fing_path->numJoints();\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tfingers[j]->fingerCloseOffset.push_back(list[i].toDouble());\n\t\t}\n\t}\n\n\tif( gSettings.find(\"fingerOffset\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"fingerOffset\"].toSequence();\n\t\tfor(int j=0; j<nFing; j++)\n\t\t\tfingers[j]->offset = list[0].toDouble();\n\t}\n\n\tif( gSettings.find(\"pythonInterface\")->type() == YAML_SCALAR ){\n\t\tpythonInterface = bodyItemRobotPath + \"/\" + gSettings[\"pythonInterface\"].toString();\n\t}else{\n\t\tpythonInterface = \"/NULL\";\n\t}\n\n\tvector <InterLink> & interLinkList = PlanBase::instance()->interLinkList;\n\tif( gSettings.find(\"interlink\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"interlink\"].toSequence();\n\t\tfor(int i=0;i<list.size();i++){\n\t\t\tconst YamlSequence& ilist = *list[i].toSequence();\n\t\t\tLink* master = bodyItemRobot->body()->link(ilist[0].toString());\n\t\t\tdouble baseratio = ilist[1].toDouble();\n\t\t\tfor(int j=1;j<ilist.size()/2;j++){\n\t\t\t\tInterLink temp;\n\t\t\t\ttemp.master = master;\n\t\t\t\ttemp.slave = bodyItemRobot->body()->link(ilist[2*j].toString());\n\t\t\t\ttemp.ratio = ilist[2*j+1].toDouble()/baseratio;\n\t\t\t\tinterLinkList.push_back(temp);\n\t\t\t}\n\n\t\t}\n\t}\n\tif( gSettings.find(\"approachOffset\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"approachOffset\"].toSequence();\n\t\tfor(int i=0;i<list.size();i++){\n\t\t\tarm->approachOffset[i] = list[i].toDouble();\n\t\t}\n\t}\n\n\tif( gSettings.find(\"selfContactPair\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"selfContactPair\"].toSequence();\n\t\tif(list[0].type() == YAML_SCALAR){\n\t\t\tfor(int i=0;i<list.size()/2;i++){\n\t\t\t\tcontactLinks.insert ( make_pair ( list[i*2].toString(), list[i*2+1].toString() ) );\n\t\t\t}\n\t\t}\n\t\tif(list[0].type() == YAML_SEQUENCE){\n\t\t\tfor(int i=0;i<list.size();i++){\n\t\t\t\tconst YamlSequence& plist = *list[i].toSequence();\n\t\t\t\tfor(int j=0;j<plist.size();j++){\n\t\t\t\t\tfor(int k=j+1;k<plist.size();k++){\n\t\t\t\t\t\tcontactLinks.insert ( make_pair (plist[j].toString(), plist[k].toString() )  );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t}\n\t}\n\tif( gSettings.find(\"movableArea\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"movableArea\"].toSequence();\n\t\tconst YamlSequence& ilist = *list[0].toSequence();\n\t\tPlanBase::instance()->llimitMap = Vector3 ( ilist[0].toDouble(),ilist[1].toDouble(),ilist[2].toDouble() );\n\t\tconst YamlSequence& ilist1 = *list[1].toSequence();\n\t\tPlanBase::instance()->ulimitMap = Vector3 ( ilist1[0].toDouble(),ilist1[1].toDouble(),ilist1[2].toDouble() );\n\t}\n\n\tcout << \"llimit\" << PlanBase::instance()->llimitMap.transpose() << \" \";\n\tcout << \"ulimit\" << PlanBase::instance()->ulimitMap.transpose() << endl;\n\n\tif( gSettings.find(\"InterObject\")->type() == YAML_SEQUENCE ){\n\t\tconst YamlSequence& list = *gSettings[\"InterObject\"].toSequence();\n\t\tfor(int i=0;i<list.size();i++){\n\t\t\tInterObject tempo;\n\t\t\tconst YamlSequence& ilist = *list[i].toSequence();\n\t\t\ttempo.master  = bodyItemRobot->body()->link(ilist[0].toString());\n\n\t\t\tBodyItemPtr temp = new BodyItem();\n\t\t\tif( !temp->loadModelFile(dataFilePath +ilist[1].toString()) ){\n\t\t\t\tos << \"modelLoadError: \" << dataFilePath +ilist[1].toString() << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttemp->setName(ilist[1].toString());\n\t\t\tbodyItemRobot->addChildItem (temp);\n\t\t\ttempo.slaveItem = temp;\n\t\t\tconst YamlSequence& vlist = *ilist[2].toSequence();\n\t\t\ttempo.relativePos = Vector3 ( vlist[0].toDouble(),vlist[1].toDouble(),vlist[2].toDouble() );\n\t\t\tconst YamlSequence& vlist2 = *ilist[3].toSequence();\n\t\t\ttempo.relativeRot << vlist2[0].toDouble(), vlist2[1].toDouble(), vlist2[2].toDouble(), vlist2[3].toDouble(), vlist2[4].toDouble(), vlist2[5].toDouble(), vlist2[6].toDouble(), vlist2[7].toDouble(), vlist2[8].toDouble();\n\t\t\ttempo.setInterObject();\n\t\t\ttempo.type = InterObject::ROBOT;\n\t\t\tPlanBase::instance()->interObjectList.push_back(tempo);\n\t\t}\n\t}\n\n\tif( gSettings.find(\"mu\")->type() == YAML_SCALAR){\n\t\tmu = gSettings[\"mu\"].toDouble();\n\t}else{\n\t\tmu = 0.5;\n\t}\n\n\tif( gSettings.find(\"fmax\")->type() == YAML_SCALAR){\n\t\tfmax = gSettings[\"fmax\"].toDouble();\n\t}else{\n\t\tfmax = 10;\n\t}\n\n\tif( gSettings.find(\"hmax\")->type() == YAML_SCALAR){\n\t\thmax = gSettings[\"hmax\"].toDouble();\n\t}else{\n\t\thmax = 0.005;\n\t}\n\n\thandJoint = new LinkTraverse(palm);\n\tnHandLink = handJoint->numLinks();\n\n\tif (gSettings.find(\"name\")->type() == YAML_SCALAR ){\n\t\tname = gSettings[\"name\"].toString();\n\t}else{\n\t\tstatic int i=0;\n\t\tstringstream namenum;\n\t\tnamenum << arm << i;\n\t\tname = namenum.str();\n\t}\n\n}\n\nbool PlanBase::SetGraspingRobot(cnoid::BodyItemPtr bodyItem_){\n\t//setting robot\n\n\tarmsList.clear(); //Temoporary;  will delete menbers\n\tinterLinkList.clear();\n\ttargetArmFinger = NULL;\n\n\t//READ YAML setting\n\tif( bodyItem_->body()->info()->find(\"graspPluginSetting\")->type() == YAML_SEQUENCE){ // multi arm\n\t\tconst YamlSequence& glist = *(*bodyItem_->body()->info())[\"graspPluginSetting\"].toSequence();\n\t\tfor(int i=0;i<glist.size();i++){\n\t\t\tconst YamlMapping& gSettings = *glist[i].toMapping();\n\t\t\tif ( gSettings.isValid() && !gSettings.empty()) {\n\t\t\t\ttargetArmFinger = new ArmFingers(bodyItem_, gSettings);\n\t\t\t\tarmsList.push_back(targetArmFinger);\n\t\t\t}\n\t\t}\n\t}\n\telse{ // single arm\n\t\tconst YamlMapping& gSettings = *bodyItem_->body()->info()->findMapping(\"graspPluginSetting\");\n\t\tif ( gSettings.isValid() && !gSettings.empty()) {\n\t\t\ttargetArmFinger = new ArmFingers(bodyItem_, gSettings);\n\t\t\tarmsList.push_back(targetArmFinger);\n\t\t}\n\t}\n\n\ttargetArmFinger = armsList[0];\n\n\tif(targetArmFinger == NULL){\n\t\tos << \"ERROR graspPluginSetting is not found in yaml\" << endl;\n\t\treturn false;\n\t}\n\n\trobTag2Arm.clear();\n\tfor(int i=0;i<armsList.size();i++){\n\t\tarmsList[i]->id = i;\n\t\tstring tagId = armsList[i]->name;\n\t\tif(robTag2Arm.find(tagId) != robTag2Arm.end()){\n\t\t\tos << \"Error: the tagId is already recorded \" << tagId << endl;\n\t\t\tcontinue;\n\t\t}else{\n\t\t\trobTag2Arm.insert( pair <string,ArmFingers*>(tagId, armsList[i]));\n\t\t}\n\t}\n\n\tos  << bodyItem_->name() << \" has \" <<armsList.size() << \" arm(s) \"<< endl;\n\n\tif(targetObject){\n\t\tfor(int i=0;i<nFing();i++) fingers(i)->coldetLinkPair(targetObject->bodyItemObject);\n#ifdef  CNOID_10_11_12_13\n\t\tarm()->palmObjPair = new ColdetLinkPair(palm(),object() );\n#else\n\t\tarm()->palmObjPair = make_shared<ColdetLinkPair>(body(), palm(), targetObject->bodyItemObject->body(), object() );\n#endif\n\t}\n\n\tbodyItemRobot()->body()->calcForwardKinematics();\n\n\tgraspMotionSeq.clear();\n\tsetGraspingState(NOT_GRASPING);\n\tsetGraspingState2(NOT_GRASPING);\n\n\trobotSelfPairs.clear();\n\tfor(unsigned int i=0;i<bodyItemRobot()->body()->numLinks();i++){ // If initial position is not collided, it is stored as\n\t\tfor(unsigned int j=i+1;j<bodyItemRobot()->body()->numLinks();j++){\n\t\t\tbool pass = false;\n\t\t\tpair<multimap<string, string>::iterator, multimap<string, string>::iterator> ppp;\n\t\t\tppp = targetArmFinger->contactLinks.equal_range(bodyItemRobot()->body()->link(i)->name() );\n\t\t\tfor (multimap<string, string>::iterator it2 = ppp.first; it2 != ppp.second; ++it2){\n\t\t\t\tif(it2->second == bodyItemRobot()->body()->link(j)->name()) pass = true;\n\t\t\t}\n\t\t\tppp = targetArmFinger->contactLinks.equal_range(bodyItemRobot()->body()->link(j)->name() );\n\t\t\tfor (multimap<string, string>::iterator it2 = ppp.first; it2 != ppp.second; ++it2){\n\t\t\t\tif(it2->second == bodyItemRobot()->body()->link(i)->name()) pass = true;\n\t\t\t}\n\t\t\tif(pass) continue;\n#ifdef  CNOID_10_11_12_13\n\t\t\tColdetLinkPairPtr temp= new ColdetLinkPair(bodyItemRobot()->body()->link(i),bodyItemRobot()->body()->link(j));\n#else\n\t\t\tColdetLinkPairPtr temp = make_shared<ColdetLinkPair>(bodyItemRobot()->body(), bodyItemRobot()->body()->link(i), bodyItemRobot()->body(), bodyItemRobot()->body()->link(j) );\n#endif\n\t\t\ttemp->updatePositions();\n\t\t\tint t1,t2;\n\t\t\tdouble p1[3],p2[3];\n\t\t\tdouble distance = temp->computeDistance(t1,p1,t2,p2);\n\t\t\tif(distance>1.0e-04)\trobotSelfPairs.push_back(temp);\n#ifdef DEBUG_MODE\n\t\t\telse os <<\"collide on initial condition at robotSelfPair\"  <<distance <<\" \"<< temp->model(0)->name() <<\" \" << temp->model(1)->name()  << endl;\n#endif\n\t\t}\n\t}\n/*\tfor(unsigned int i=0; i<arm()->arm_path->numJoints(); i++){\n\t\tfor(unsigned int j=i+2; j<arm()->arm_path->numJoints(); j++){\n\t\t\trobotSelfPairs.push_back(new ColdetLinkPair(arm()->arm_path->joint(i), arm()->arm_path->joint(j)) );\n\t\t}\n\t}\n\n*/\n\tinitialCollision();\n\treturn true;\n}\n\n\nbool PlanBase::flush(){\n\tstatic int cnt=0;\n\tcnt++;\n\n\tif(stopFlag){\n\t\tstopFlag=false;\n\t\tthrow(cnt);\n\t}\n/* it will be GraspController\n\tif(bodyItemGRC){\n\t\tbodyItemGRC->body()->link(0)->R = palm()->R*(GRCmax.R);\n\t\tbodyItemGRC->body()->link(0)->p = palm()->p+palm()->R*GRCmax.p;\n\t\tbodyItemGRC->notifyKinematicStateChange();\n\t}\n*/\n//\tbodyItemRobot()->body()->calcForwardKinematics();\n\tif(targetArmFinger) bodyItemRobot()->notifyKinematicStateChange();\n\tif(targetObject) targetObject->bodyItemObject->notifyKinematicStateChange();\n\tMessageView::mainInstance()->flush();\n\n#ifdef  DEBUG_MODE\n\tusleep(100000);\n#endif\n\treturn true;\n\n}\n\nvoid PlanBase::calcForwardKinematics(){\n\n\tsetInterLink();\n\n\tbodyItemRobot()->body()->calcForwardKinematics();\n\n\tif(graspingState==GRASPING) {\n\t\tif(nFing()>0){\n            object()->R() = fingers(0)->tip->R()*(targetArmFinger->objectPalmRot);\n            object()->p() = fingers(0)->tip->p()+fingers(0)->tip->R()*targetArmFinger->objectPalmPos;\n\t\t}else{\n\t\t\tobject()->R() = palm()->R()*(targetArmFinger->objectPalmRot);\n\t\t\tobject()->p() = palm()->p()+palm()->R()*targetArmFinger->objectPalmPos;\n\t\t}\n\t}\n\telse if(graspingState2==GRASPING) {\n\t\tif(nFing(1)>0) {\n            object()->R() = fingers(1,0)->tip->R()*(armsList[1]->objectPalmRot);\n\t\t\tobject()->p() = fingers(1,0)->tip->p()+fingers(1,0)->tip->R()*armsList[1]->objectPalmPos;\n\t\t} else {\n\t\t\tobject()->R() = palm(1)->R()*(armsList[1]->objectPalmRot);\n\t\t\tobject()->p() = palm(1)->p()+palm(1)->R()*armsList[1]->objectPalmPos;\n\t\t}\n\t}\n\tfor(int i=0;i<interObjectList.size();i++){\n//\t\tif(interObjectList[i].type == InterObject::GRASPED_OBJECT){\n\t\t\tinterObjectList[i].setInterObject();\n//\t\t}\n\t}\n\t//cout << \"pos y \"<< bodyItemRobot()->body()->link(0)->p.transpose() <<  rpyFromRot(bodyItemRobot()->body()->link(0)->R)[2] << endl;\n}\n\nbool PlanBase::isColliding(){\n//\tcnoid::ColdetLinkPairPtr* robotSelfPairs, robotEnvPairs, robotObjPairs, objEnvPairs;\n\tfor(int i=0;i<robotSelfPairs.size();i++){\n\t\tColdetLinkPairPtr testPair = robotSelfPairs[i];\n\t\ttestPair->updatePositions();\n\t\tbool coll = testPair->checkCollision();\n\t\tif(coll){\n\t\t\tcolPairName[0] = testPair->model(0)->name();\n\t\t\tcolPairName[1] = testPair->model(1)->name();\n#ifdef DEBUG_MODE\n\t\t\tcout <<\"self collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\treturn true;\n\t\t}\n\t}\n\tint sizeRobotEnv = robotEnvPairs.size();\n\tif(useRobotSafeBoundingBox) sizeRobotEnv = safeRobotEnvPairs.size();\n\tfor(int i=0;i<sizeRobotEnv;i++){\n\t\tColdetLinkPairPtr testPair;\n\t\tif(useRobotSafeBoundingBox) testPair= safeRobotEnvPairs[i];\n\t\telse testPair= robotEnvPairs[i];\n\n\t\ttestPair->updatePositions();\n\t\tbool coll = testPair->checkCollision();\n\t\tif(coll){\n\t\t\tcolPairName[0] = testPair->model(0)->name();\n\t\t\tcolPairName[1] = testPair->model(1)->name();\n#ifdef DEBUG_MODE\n\t\t\tcout <<\"robot env collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\treturn true;\n\t\t}\n\t}\n\tfor(int i=0;i<robotPointCloudPairs.size();i++){\n\t\tbool coll = isCollidingPointCloud(robotPointCloudPairs[i].second,robotPointCloudPairs[i].first);\n\t\tif(coll){\n#ifdef DEBUG_MODE\n\t\t\tcout << \"robot pointcloud collide\" << endl;\n#endif\n\t\t\treturn true;\n\t\t}\n\t}\n\tif(checkAllGraspingState()==NOT_GRASPING){\n\t\tfor(int i=0;i<robotObjPairs.size();i++){\n\t\t\tColdetLinkPairPtr testPair = robotObjPairs[i];\n\t\t\ttestPair->updatePositions();\n\t\t\tbool coll = testPair->checkCollision();\n\t\t\tif(coll){\n\t\t\t\tcolPairName[0] = testPair->model(0)->name();\n\t\t\t\tcolPairName[1] = testPair->model(1)->name();\n#ifdef DEBUG_MODE\n\t\t\t\tcout <<\"robot obj collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\tif(getObjectContactState()==OFF_ENVIRONMENT){\n\t\tfor(int i=0;i<objEnvPairs.size();i++){\n\t\t\tColdetLinkPairPtr testPair = objEnvPairs[i];\n\t\t\ttestPair->updatePositions();\n\t\t\tbool coll = testPair->checkCollision();\n\t\t\tif(coll){\n\t\t\t\tcolPairName[0] = testPair->model(0)->name();\n\t\t\t\tcolPairName[1] = testPair->model(1)->name();\n#ifdef DEBUG_MODE\n\t\t\t\tcout <<\"obj env collide \" << i  << \" \"<<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tfor(int i=0;i<objPointCloudPairs.size();i++){\n\t\t\tbool coll = isCollidingPointCloud(objPointCloudPairs[i].second ,objPointCloudPairs[i].first);\n\t\t\tif(coll){\n#ifdef DEBUG_MODE\n\t\t\t\tcout << \"obj pointcloud collide\" << endl;\n#endif\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(int i=0;i<interObjectList.size();i++){\n\t\tif( interObjectList[i].isColliding() ) return true;\n\t}\n\n\treturn false;\n}\n\nbool PlanBase::isCollidingPointCloud(PointCloudEnv* pc_env, BodyItemPtr item, double tol){\n\tfor(int i=0; i<item->body()->numLinks(); i++) {\n\t\tColdetModelPtr c = item->body()->link(i)->coldetModel();\n\t\tvector<Vector3> bbdata;\n\t\tc->getBoundingBoxData(0, bbdata);\n\t\tvector<Vector3> v(8);\n\t\tv[0] = bbdata[0] + Vector3( bbdata[1](0),  bbdata[1](1),  bbdata[1](2));\n\t\tv[1] = bbdata[0] + Vector3( bbdata[1](0),  bbdata[1](1), -bbdata[1](2));\n\t\tv[2] = bbdata[0] + Vector3( bbdata[1](0), -bbdata[1](1),  bbdata[1](2));\n\t\tv[3] = bbdata[0] + Vector3( bbdata[1](0), -bbdata[1](1), -bbdata[1](2));\n\t\tv[4] = bbdata[0] + Vector3(-bbdata[1](0),  bbdata[1](1),  bbdata[1](2));\n\t\tv[5] = bbdata[0] + Vector3(-bbdata[1](0),  bbdata[1](1), -bbdata[1](2));\n\t\tv[6] = bbdata[0] + Vector3(-bbdata[1](0), -bbdata[1](1),  bbdata[1](2));\n\t\tv[7] = bbdata[0] + Vector3(-bbdata[1](0), -bbdata[1](1), -bbdata[1](2));\n\n\t\tdouble max_x, max_y, max_z, min_x, min_y, min_z;\n\t\tmax_x = max_y = max_z = -DBL_MAX;\n\t\tmin_x = min_y = min_z = DBL_MAX;\n\t\tfor (int j = 0; j < 8; j++) {\n\t\t\tVector3 rv;\n            rv = item->body()->link(i)->R() * v[j] + item->body()->link(i)->p();\n\t\t\tmax_x = std::max(max_x, rv(0));\n\t\t\tmin_x = std::min(min_x, rv(0));\n\t\t\tmax_y = std::max(max_y, rv(1));\n\t\t\tmin_y = std::min(min_y, rv(1));\n\t\t\tmax_z = std::max(max_z, rv(2));\n\t\t\tmin_z = std::min(min_z, rv(2));\n\t\t}\n\n\t\tmax_x += tol; max_y += tol; max_z += tol;\n\t\tmin_x -= tol; min_y -= tol; min_z -= tol;\n\n\t\tif(max_x < pc_env->min_x || min_x > pc_env->max_x ||\n\t\t\tmax_y < pc_env->min_y || min_y > pc_env->max_y ||\n\t\t\tmax_z < pc_env->min_z || min_z > pc_env->max_z) {\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tvector<Vector3> target_p;\n\t\tfor(int j=0;j<pc_env->p().size();j++){\n\t\t\tif(pc_env->p()[j](0) < max_x && pc_env->p()[j](0) > min_x &&\n\t\t\t\tpc_env->p()[j](1) < max_y && pc_env->p()[j](1) > min_y &&\n\t\t\t\tpc_env->p()[j](2) < max_z && pc_env->p()[j](2) > min_z){\n\t\t\t\t\ttarget_p.push_back(pc_env->p()[j]);\n\t\t\t}\n\t\t}\n\n\t\tif(target_p.empty()) continue;\n\n\t\tif(item->body()->link(i)->coldetModel()->checkCollisionWithPointCloud(target_p, tol)){\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n/* //\u30aa\u30ea\u30b8\u30ca\u30eb\nbool PlanBase::isCollidingPointCloud(const vector<Vector3>& p, BodyItemPtr item, double tol){\n\tfor(int i=0; i<item->body()->numLinks(); i++){\n\t\t\tif(item->body()->link(i)->coldetModel()->checkCollisionWithPointCloud(p, tol)){\n\t\t\t\t\treturn true;\n\t\t\t}\n\t}\n\treturn false;\n}\n*/\n//\u2460\u4e00\u70b9Ver\nint PlanBase::isCollidingPointCloud(const vector<Vector3>& p, BodyItemPtr item, double tol){\n  //sleep(2); //test\n  for(int i=0; i<item->body()->numLinks(); i++){\n    int judge = item->body()->link(i)->coldetModel()->checkCollisionWithPointCloud(p, tol);\n    if(judge) {\n        return judge;\n    }\n  }\n  return 0;\n}\n//\u5165\u529b\u30d9\u30af\u30bfp\u306e\u5e72\u6e09\u70b9\u3092col_result\u306b\u8a70\u3081\u308b\nvoid PlanBase::isCollidingPointCloud2(const vector<cnoid::Vector3>& p, cnoid::BodyItemPtr item, vector<cnoid::Vector3>& col_result, double tol){\n  for(int i=0; i<item->body()->numLinks(); i++){\n    item->body()->link(i)->coldetModel()->checkCollisionWithPointCloud2(p, tol, col_result);\n  }\n}\n//2\u306e\u91cd\u8907\u3092\u6d88\u3057\u305f\u3082\u306e\nvoid PlanBase::isCollidingPointCloud3(const vector<cnoid::Vector3>& p, cnoid::BodyItemPtr item, vector<cnoid::Vector3>& col_result, double tol){\n  vector<int> judge;\n  for(int i=0; i<p.size(); i++){\n    judge.push_back(0);\n  }\n  //for(int i=0; i<item->body()->numLinks(); i++){\n  for(int i=3; i<11; i++){ //for pal Right Arm\n    item->body()->link(i)->coldetModel()->checkCollisionWithPointCloud3(p, tol, judge);\n  }\n  for(int i=0; i<p.size(); i++){\n    if(judge[i]){\n      col_result.push_back(p[i]);\n    }\n  }\n}\n\n//\u5165\u529b\u30d9\u30af\u30bfp\u304b\u3089\u5e72\u6e09\u70b9\u3092\u524a\u9664\u3059\u308b\nvoid PlanBase::removeCollidingPointCloud(vector<cnoid::Vector3>& p, cnoid::BodyItemPtr item, double tol){\n  for(int i=0; i<item->body()->numLinks(); i++){\n    item->body()->link(i)->coldetModel()->removeCollisionWithPointCloud(p, tol);\n  }\n}\nvoid PlanBase::removeCollidingPointCloud2(const vector<cnoid::Vector3>& p, cnoid::BodyItemPtr item, vector<cnoid::Vector3>& col_result, double tol){\n  vector<int> judge;\n  for(int i=0; i<p.size(); i++){\n    judge.push_back(0);\n  }\n  for(int i=0; i<item->body()->numLinks(); i++){\n    item->body()->link(i)->coldetModel()->removeCollisionWithPointCloud2(p, tol, judge);\n  }\n  for(int i=0; i<p.size(); i++){\n    if(!judge[i]){\n      col_result.push_back(p[i]);\n    }\n  }\n}\n\nbool PlanBase::isCollidingPointCloudFinger(const vector<Vector3>& p, double tol){\n\n\tfor(int i=0; i<nFing(); i++)\n\t\tfor(int j=0; j<fingers(i)->fing_path->numJoints(); j++){\n\t\t\tif(fingers(i)->fing_path->joint(j)->coldetModel()->checkCollisionWithPointCloud(p, tol))\n\t\t\t\t\treturn true;\n\t\t}\n\treturn false;\n}\n\ndouble PlanBase::clearance(){\n\n//\tdouble start = getrusage_sec();\n\n\tdouble min_sep=1.e10;\n\n\tfor(int i=0;i<robotSelfPairs.size();i++){\n\t\tColdetLinkPairPtr testPair = robotSelfPairs[i];\n\t\ttestPair->updatePositions();\n\t\tbool coll = testPair->checkCollision();\n\t\tif(coll){\n\t\t\tcolPairName[0] = testPair->model(0)->name();\n\t\t\tcolPairName[1] = testPair->model(1)->name();\n#ifdef DEBUG_MODE\n\t\t\tcout <<\"self collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\treturn 0;\n\t\t}\n\t}\n\tif(checkAllGraspingState()==NOT_GRASPING){\n\t\tfor(int i=0;i<robotObjPairs.size();i++){\n\t\t\tColdetLinkPairPtr testPair = robotObjPairs[i];\n\t\t\ttestPair->updatePositions();\n\t\t\tbool coll = testPair->checkCollision();\n\t\t\tif(coll){\n\t\t\t\tcolPairName[0] = testPair->model(0)->name();\n\t\t\t\tcolPairName[1] = testPair->model(1)->name();\n#ifdef DEBUG_MODE\n\t\t\t\tcout <<\"robot obj collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(int i=0;i<robotPointCloudPairs.size();i++){\n\t\tbool coll = isCollidingPointCloud(robotPointCloudPairs[i].second,robotPointCloudPairs[i].first);\n\t\tif(coll){\n#ifdef DEBUG_MODE\n\t\t\tcout << \"robot pointcloud collide\" << endl;\n#endif\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tfor(int i=0;i<robotEnvPairs.size();i++){\n\t\tColdetLinkPairPtr testPair = robotEnvPairs[i];\n\t\ttestPair->updatePositions();\n\n\t\ttestPair->setTolerance(tolerance);\n\t\tif( testPair->detectIntersection() ){\n#ifdef DEBUG_MODE\n\t\t\tos <<\"rob-env tolerance collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\treturn 0;\n\t\t}\n\t\tcontinue;\n\n\t\tint t1,t2;\n\t\tdouble p1[3],p2[3];\n\t\tdouble distance = testPair->computeDistance(t1,p1,t2,p2);\n\t\tif(distance <=tolerance){\n#ifdef DEBUG_MODE\n\t\t\tos <<\"rob-env tolerance collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\treturn distance;\n\t\t}\n\t\telse {\n\t\t\tos << distance << endl;\n\t\t}\n\t\tif(distance < min_sep){\n\t\t\tmin_sep = distance;\n\t\t}\n\t}\n\n\n\tif(getObjectContactState()==OFF_ENVIRONMENT){\n\t\tfor(int i=0;i<objEnvPairs.size();i++){\n\t\t\tColdetLinkPairPtr testPair = objEnvPairs[i];\n\t\t\ttestPair->updatePositions();\n\n\t\t\ttestPair->setTolerance(tolerance);\n\t\t\tif( testPair->detectIntersection() ){\n#ifdef DEBUG_MODE\n\t\t\t\tos <<\"rob-env tolerance collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcontinue;\n\n\t\t\tint t1,t2;\n\t\t\tdouble p1[3],p2[3];\n\t\t\tdouble distance = testPair->computeDistance(t1,p1,t2,p2);\n\t\t\tif(distance <=tolerance){\n#ifdef DEBUG_MODE\n\t\t\t\tos <<\"obj-env tolerance collide \" <<testPair->model(0)->name() <<\" \"<<testPair->model(1)->name()<< endl;\n#endif\n\t\t\t\treturn distance;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tos << distance << endl;\n\t\t\t}\n\t\t\tif(distance < min_sep){\n\t\t\t\tmin_sep = distance;\n\t\t\t}\n\t\t}\n\n\t\tfor(int i=0;i<objPointCloudPairs.size();i++){\n\t\t\tbool coll = isCollidingPointCloud(objPointCloudPairs[i].second, objPointCloudPairs[i].first);\n\t\t\tif(coll){\n\t#ifdef DEBUG_MODE\n\t\t\t\tcout << \"obj pointcloud collide\" << endl;\n\t#endif\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n//\tdouble end = getrusage_sec();\n//\tcout << \"time clearance\" << objEnvPairs.size() << \" \"<< end - start << endl;\n\n\n\treturn min_sep;\n}\n\n\nvoid PlanBase::setGraspingState(int state){\n\tif(state==GRASPING){\n\t\tif(nFing() > 0){\n\t\t\ttargetArmFinger->objectPalmPos = trans(Matrix3(fingers(0)->tip->R()))*(object()->p() - fingers(0)->tip->p());\n\t\t\ttargetArmFinger->objectPalmRot = trans(Matrix3(fingers(0)->tip->R()))*object()->R();\n\t\t}else{\n\t\t\ttargetArmFinger->objectPalmPos = trans(Matrix3(palm()->R()))*(object()->p() - palm()->p());\n\t\t\ttargetArmFinger->objectPalmRot = trans(Matrix3(palm()->R()))*object()->R() ;\n\t\t}\n\t}\n\tgraspingState = state;\n}\n\nvoid PlanBase::setGraspingState2(int state){\n\tif(armsList.size() >1 && state==GRASPING){\n\t\tif(nFing(1)>0) {\n\t\t\tarmsList[1]->objectPalmPos = trans(Matrix3(fingers(1,0)->tip->R()))*(object()->p() - fingers(1,0)->tip->p());\n\t\t\tarmsList[1]->objectPalmRot = trans(Matrix3(fingers(1,0)->tip->R()))*object()->R();\n\t\t}else {\n\t\t\tarmsList[1]->objectPalmPos = trans(Matrix3(palm(1)->R()))*(object()->p() - palm(1)->p());\n\t\t\tarmsList[1]->objectPalmRot = trans(Matrix3(palm(1)->R()))*object()->R() ;\n\t\t}\n\t}\n\tgraspingState2 = state;\n}\n\nvoid PlanBase::setTrajectoryPlanDOF(){\n\n\tpathPlanDOF.clear();\n\n\tfor(int i=0; i<arm()->nJoints; i++)\n        pathPlanDOF.push_back(arm()->arm_path->joint(i)->jointId());\n\tfor(int i=0; i<nFing(); i++)\n\t\tfor(int j=0; j<fingers(i)->nJoints; j++)\n            pathPlanDOF.push_back(fingers(i)->fing_path->joint(j)->jointId());\n\n#ifdef DEBUG_MODE\n\tcout << \"Plan DOF= \";\n\tfor (unsigned int i=0; i<pathPlanDOF.size(); i++)\n\t\tcout << pathPlanDOF[i] << \" \";\tcout << endl;\n#endif\n}\n\nvoid PlanBase::setTrajectoryPlanDOF(int k){\n\n\tpathPlanDOF.clear();\n\n\tfor(int i=0; i<arm(k)->nJoints; i++)\n        pathPlanDOF.push_back(arm(k)->arm_path->joint(i)->jointId());\n\tfor(int i=0; i<nFing(k); i++)\n\t\tfor(int j=0; j<fingers(k,i)->nJoints; j++)\n            pathPlanDOF.push_back(fingers(k,i)->fing_path->joint(j)->jointId());\n\n#ifdef DEBUG_MODE\n\tcout << \"Plan DOF= \";\n\tfor (unsigned int i=0; i<pathPlanDOF.size(); i++)\n\t\tcout << pathPlanDOF[i] << \" \";\tcout << endl;\n#endif\n}\n\nvoid PlanBase::setTrajectoryPlanMapDOF(){\n\n\tpathPlanDOF.clear();\n\n\tint top = body()->numJoints();\n\tpathPlanDOF.push_back(top); //position x\n\tpathPlanDOF.push_back(top+1); //position y;\n\tpathPlanDOF.push_back(top+5); //yaw;\n\n\t//ulimitMap = Vector3(3.0,3.0,3.0);\n\t//llimitMap = Vector3(-3.0,-3.0,-3.0);\n\n#ifdef DEBUG_MODE\n\tcout << \"Plan Map DOF= \";\n\tfor (unsigned int i=0; i<pathPlanDOF.size(); i++)\n\t\tcout << pathPlanDOF[i] << \" \";\tcout << endl;\n#endif\n}\n\n\ndouble PlanBase::calcContactPoint(ColdetLinkPairPtr cPair, Vector3 &Po, Vector3 &Pf, Vector3 &objN, Vector3 &fingerN) {\n\n//\tint Ik = t;\n\n\tdouble p1[3] = {0}, p2[3] = {0};\n\tint tid1, tid2;\n\n//\tColdetLinkPairPtr cPair = linkObjPair[Ik];\n//\tColdetModelPtr model = cPair->model(0);\n\n    cPair->model(0)->setPosition(cPair->link(0)->R(), cPair->link(0)->p());\n    cPair->model(1)->setPosition(cPair->link(1)->R(), cPair->link(1)->p());\n//\tcout << cPair->link(0)->p << cPair->link(1)->p << endl;\n\n\tdouble dsn = cPair->computeDistance(tid1, &p1[0], tid2, &p2[0]);\n\n\n\tLink* links[2];\n\tlinks[0] = cPair->link(0);\n\tlinks[1] = cPair->link(1);\n\n\tint v[2][3];\n\tlinks[0]->coldetModel()->getTriangle(tid1, v[0][0], v[0][1], v[0][2]);\n\tlinks[1]->coldetModel()->getTriangle(tid2, v[1][0], v[1][1], v[1][2]);\n\n\tfloat p[3];\n\tVector3 n[3];\n\n\tfor (int i = 1; i < 2;i++) {\n\t\tfor (int j = 0; j < 3;j++) {\n\t\t\tlinks[i]->coldetModel()->getVertex(v[i][j], p[0], p[1], p[2]);\n\t\t\tn[j] = Vector3 (p[0], p[1], p[2]);\n\t\t}\n\t}\n\n\tPf = Vector3(p1[0], p1[1], p1[2]);\n\tPo = Vector3(p2[0], p2[1], p2[2]);\n//\tcout << Po << Pf << endl;\n\n\t//Po = trans(cPair->link(1)->R) * Po - cPair->link(1)->p; //bug? ochi\n    Po = trans(Matrix3(cPair->link(1)->R())) * (Po - cPair->link(1)->p());\n//\talias(Pf) = trans(cPair->link(0)->R) * Pf - cPair->link(0)->p;\n\n\n\tVector3 objN2 = cross(Vector3(n[1] - n[0]), Vector3(n[2] - n[0]));\n\tobjN = objN2 / norm2(objN2);\n\n\tfor (int j = 0; j < 3;j++) {\n\t\tlinks[0]->coldetModel()->getVertex(v[0][j], p[0], p[1], p[2]);\n\t\tn[j] = Vector3 (p[0], p[1], p[2]);\n\t}\n\n\tobjN2 = cross(Vector3(n[1] - n[0]), Vector3(n[2] - n[0]));\n\t//normal vector of finger in the object local corrdinate\n    fingerN = trans(Matrix3(cPair->link(1)->R())) * (cPair->link(0)->R()) * (objN2 / norm2(objN2));\n\n\treturn dsn;\n\n}\n\nMatrix3 makeOrthogonal(const MatrixXd A, const VectorXd b)\n{\n\tvector<double> c;\n\tfor(size_t i=0; i<b.size(); i++)\n\t\t\tc.push_back(fabs(b(i)));\n\n\tMatrix3 A_ = d2v(A);\n\tint j=argmax(c);\n\tVector3 v0 = A_.col(j);\n\tVector3 v1 = A_.col((j+1)%3);\n\n\tdouble r=dot(v0,v1);\n\tv1 = (-r*v0 + v1)/sqrt(1-r*r);\n\tVector3 v2 = cross(v0,v1);\n\n\tfor(int i=0; i<3; i++){\n\t\tA_(i, (j+1)%3) = v1(i);\n\t\tA_(i, (j+2)%3) = v2(i);\n\t}\n\n\treturn A_;\n}\n\nvoid PlanBase::calcBoundingBox(ColdetModelPtr model, Vector3 &edge, Vector3& center, Vector3& com, Matrix3& Rot) {\n\t//objVis and objPos shoulde be defined in advance.\n\n\tclass Triangle{\n\tpublic:\n\t\tcnoid::Vector3 ver[3];\n\t\tfloat area;\n\t};\n\n\t// convert coldetmodel to objectshape\n\tfloat out_x, out_y, out_z;\n\tint v0,v1,v2;\n\n\tint nVerticies = model->getNumVertices();\n\tint nTriangles = model->getNumTriangles();\n\n\tVector3* verticies = new Vector3[nVerticies];\n\tTriangle* triangles = new Triangle[nTriangles];\n\n\tfor(int i=0;i<nVerticies;i++){\n        model->getVertex(i, out_x, out_y, out_z);\n\t\tverticies[i][0] = out_x;\n\t\tverticies[i][1] = out_y;\n\t\tverticies[i][2] = out_z;\n\t}\n\n\tfor(int i=0;i<nTriangles;i++){\n        model->getTriangle(i, v0,v1,v2);\n\t\ttriangles[i].ver[0] = verticies[v0];\n\t\ttriangles[i].ver[1] = verticies[v1];\n\t\ttriangles[i].ver[2] = verticies[v2];\n\t}\n\n\t// calc distribution\n\tVector3 pt;\n\tMatrixXd distribute = MatrixXd::Zero(3, 3);\n\tVector3 average(0, 0, 0);\n\n\tfor(int i=0;i<nTriangles;i++){\n\t\tVector3 e1 (triangles[i].ver[1] - triangles[i].ver[0]);\n\t\tVector3 e2 (triangles[i].ver[2] - triangles[i].ver[0]);\n\t\ttriangles[i].area = norm2 ( cross(e1,e2) ) /2.0;\n\t}\n\n\tMatrix3 aq,aq_n_sum,aq_p_sum;\n\tstd::vector<double>* aq_p[3][3];\n\tstd::vector<double>* aq_n[3][3];\n\tVector3 sumCenter(0,0,0);\n\tdouble sumArea=0;\n\tfor(int i=0;i<3;i++) for(int j=0;j<3;j++) {\n\t\taq(i,j)=0;\n\t\taq_p_sum(i,j)=0;\n\t\taq_n_sum(i,j)=0;\n\t\taq_p[i][j] = new std::vector<double>();\n\t\taq_n[i][j] = new std::vector<double>();\n\t}\n\n\tfor(int l=0;l<nTriangles;l++){\n\t\tTriangle& t = triangles[l];\n\t\tfor(int i=0;i<3;i++){\n\t\t\tfor(int j=0;j<3;j++){\n\t\t\t\tfor(int k=0;k<3;k++){\n\t\t\t\t\tdouble tmp_aq;\n\t\t\t\t\ttmp_aq = t.area*(t.ver[i][j] * t.ver[i][k])/6.0;\n\t\t\t\t\ttmp_aq > 0 ? aq_p[j][k]->push_back(tmp_aq) : aq_n[j][k]->push_back(tmp_aq);\n\t\t\t\t\ttmp_aq = t.area*(t.ver[i][j] * t.ver[(i+1)%3][k])/12.0;\n\t\t\t\t\ttmp_aq > 0 ? aq_p[j][k]->push_back(tmp_aq) : aq_n[j][k]->push_back(tmp_aq);\n\t\t\t\t\ttmp_aq = t.area*(t.ver[(i+1)%3][j] * t.ver[i][k])/12.0;\n\t\t\t\t\ttmp_aq > 0 ? aq_p[j][k]->push_back(tmp_aq) : aq_n[j][k]->push_back(tmp_aq);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsumArea +=t.area;\n\t\tsumCenter  =  sumCenter + t.area/3.0* Vector3 ( t.ver[0] + t.ver[1] + t.ver[2]);\n\t}\n\tfor(int i=0;i<3;i++) for(int j=0;j<3;j++) {\n\t\tstd::sort(aq_p[i][j]->begin(),aq_p[i][j]->end(),LessAbs());\n\t\tfor(int n=0;n<aq_p[i][j]->size();n++){\n\t\t\taq_p_sum(i,j) += aq_p[i][j]->at(n);\n\t\t}\n\t\tstd::sort(aq_n[i][j]->begin(),aq_n[i][j]->end(),LessAbs());\n\t\tfor(int n=0;n<aq_n[i][j]->size();n++){\n\t\t\taq_n_sum(i,j) += aq_n[i][j]->at(n);\n\t\t}\n\t\tdelete aq_p[i][j];\n\t\tdelete aq_n[i][j];\n\t}\n\tfor(int i=0;i<3;i++) for(int j=0;j<3;j++) {aq(i,j) = aq_p_sum(i,j) + aq_n_sum(i,j);}\n\taverage = com = sumCenter/sumArea;\n\tfor(int j=0;j<3;j++){\n\t\tfor(int k=0;k<3;k++){\n\t\t\tdistribute(j,k) = aq(j,k) - com[j] * com[k] * sumArea;\n\t\t}\n\t}\n\tMatrixXd evec(3, 3);\n\tVectorXd eval(3);\n\tint info;\n\tEigen::EigenSolver<MatrixXd> es(distribute);\n\teval = es.eigenvalues().real();\n\tevec = es.eigenvectors().real();\n\n\tRot = makeOrthogonal(evec, eval);\n\t//Rot =  (d2v(evec));\n\n\tVector3 e[3];\n\tfor (int i = 0; i < 3; i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\te[j][i] = Rot(i, j);\n\n\tVector3 pt_max(0, 0, 0), pt_min(0, 0, 0);\n\n\tfor(int l=0;l<nVerticies;l++){\n\t\tVector3 pt = verticies[l];\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tdouble tmp = dot(e[j], Vector3(pt - average));\n\t\t\tif (tmp > pt_max[j]) pt_max[j] = tmp;\n\t\t\tif (tmp < pt_min[j]) pt_min[j] = tmp;\n\t\t}\n\t}\n\n\t//Rot =  (d2v(evec));\n\n\tedge =  (pt_max - pt_min);\n\tcenter =  average + 0.5 * Rot * (pt_max + pt_min);\n//\tcom = average;\n\n//\talias(Rot)  = objVisRot() * Rot;\n//\talias(center) = objVisRot() * center + objVisPos();\n//\talias(com)    = objVisRot() * com   + objVisPos();\n#ifdef DEBUG_MODE\n\tcout << \"bouding box size\"<< edge.transpose() << endl<< Rot  <<endl;\n#endif\n\n\tdelete []\tverticies;\n\tdelete []  triangles;\n\n\n\treturn;\n}\n\n\n\n\n//Including Enveloping grasp\n//bool PlanBase::sampleFinalPos2(mpkRobotCollection* robots, vector<mpkCollPair> *test_pairs, int iterate)\nbool PlanBase::initial() {\n\tif ( !targetObject || !targetArmFinger) {\n\t\tos << \"Please select Grasped Object and Grasping Robot\" << endl;\n\t\treturn false;\n\t}\n\n\tRemoveEnvironment(targetObject->bodyItemObject);\n\n    targetObject->objVisPos = object()->p();\n    targetObject->objVisRot = object()->R();\n\n\tsetGraspingState(NOT_GRASPING);\n\tsetGraspingState2(NOT_GRASPING);\n\tgraspMotionSeq.push_back ( getMotionState() );\n\n\tinitialCollision();\n\n\t_initrand();\n\treturn true;\n}\n\nvoid PlanBase::initialCollision(){\n\n\t/////////////////////////////////////////////////////////// temporal change\n\tinitialCollisionWithMemory();\n\treturn;\n\t///////////////////////////////////////////////////////////\n\n\tif(!doInitialCollision) return;\n\n\trobotEnvPairs.clear();\n\trobotObjPairs.clear();\n\tobjEnvPairs.clear();\n\trobotPointCloudPairs.clear();\n\tobjPointCloudPairs.clear();\n\n\tif(targetArmFinger==NULL) {\n\t\treturn;\n\t}\n\tfor(unsigned int j=0;j<bodyItemRobot()->body()->numLinks();j++){\n\t\tfor( list<BodyItemPtr>::iterator it = bodyItemEnv.begin(); it !=bodyItemEnv.end(); it++){\n\t\t\tfor(unsigned int i=0;i<(*it)->body()->numLinks();i++){\n#ifdef  CNOID_10_11_12_13\n\t\t\t\tColdetLinkPairPtr temp= new ColdetLinkPair(bodyItemRobot()->body()->link(j), (*it)->body()->link(i));\n#else\n\t\t\t\tColdetLinkPairPtr temp = make_shared<ColdetLinkPair>(bodyItemRobot()->body(),bodyItemRobot()->body()->link(j), (*it)->body(), (*it)->body()->link(i) );\n#endif\n\t\t\t\ttemp->updatePositions();\n\t\t\t\tint t1,t2;\n\t\t\t\tdouble p1[3],p2[3];\n\t\t\t\tdouble distance = temp->computeDistance(t1,p1,t2,p2);\n\t\t\t\tif(distance>1.0e-04)\trobotEnvPairs.push_back(temp);\n#ifdef DEBUG_MODE\n\t\t\t\telse os <<\"collide on initial condition robot and env\"  <<distance <<\" \"<< temp->model(0)->name() <<\" \" << (*it)->body()->name() << endl;\n#endif\n\t\t\t}\n\t\t}\n\t}\n/*\tfor(unsigned int j=0;j<arm()->arm_path->numJoints();j++){\n\t\tfor( list<BodyItemPtr>::iterator it = bodyItemEnv.begin(); it !=bodyItemEnv.end(); it++){\n\t\t\tColdetLinkPairPtr temp= new ColdetLinkPair(arm()->arm_path->joint(j), (*it)->body()->link(0));\n\t\t\ttemp->model(0)->setPosition(temp->link(0)->R, temp->link(0)->p);\n\t\t\ttemp->model(1)->setPosition(temp->link(1)->R, temp->link(1)->p);\n\t\t\tint t1,t2;\n\t\t\tdouble p1[3],p2[3];\n\t\t\tdouble distance = temp->computeDistance(t1,p1,t2,p2);\n\t\t\tif(distance>1.0e-03)\tarmEnvPairs.push_back(temp);\n#ifdef DEBUG_MODE\n\t\t\telse os <<\"tollerance collide on initial condition\"  <<distance <<\" \"<< temp->model(0)->name() <<\" \" << temp->model(1)->name()  << endl;\n#endif\n\t\t\tos <<\"tollerance collide on initial condition\"  <<distance <<\" \"<< temp->model(0)->name() <<\" \" << temp->model(1)->name()  << endl;\n\t\t}\n\t}\n*/\tif(targetObject){\n\t\tfor(unsigned int j=0;j<bodyItemRobot()->body()->numLinks();j++){\n#ifdef  CNOID_10_11_12_13\n\t\t\t\trobotObjPairs.push_back(new ColdetLinkPair(bodyItemRobot()->body()->link(j), object() ));\n#else\n\t\t\t\trobotObjPairs.push_back(make_shared<ColdetLinkPair>(bodyItemRobot()->body(),bodyItemRobot()->body()->link(j),targetObject->bodyItemObject->body(),object()));\n#endif\n\n\n\t\t\t}\n\t\tColdetModelPtr backup = object()->coldetModel();\n\t\tif(useObjectSafeBoundingBox){\n\t\t\tobject()->setColdetModel(targetObject->safeBoundingBox);\n\t\t}\n\t\tfor(list<cnoid::BodyItemPtr>::iterator it = bodyItemEnv.begin(); it !=bodyItemEnv.end();it++){\n\t\t\tfor(unsigned int i=0;i<(*it)->body()->numLinks();i++){\n#ifdef  CNOID_10_11_12_13\n\t\t\t\tobjEnvPairs.push_back(new ColdetLinkPair(object(), (*it)->body()->link(i)));\n#else\n\t\t\t\tobjEnvPairs.push_back( make_shared<ColdetLinkPair>(targetObject->bodyItemObject->body(), object(), (*it)->body(), (*it)->body()->link(i)));\n#endif\n\t\t\t}\n        }\n        object()->setColdetModel(backup);\n\t}\n\n\n\tfor(list<PointCloudEnv*>::iterator it = pointCloudEnv.begin(); it != pointCloudEnv.end(); ++it){\n\t\tpair<BodyItemPtr, PointCloudEnv*> robo_pointcloud(bodyItemRobot(), *it);\n\t\trobotPointCloudPairs.push_back(robo_pointcloud);\n\t\tif(targetObject){\n\t\t\tpair<BodyItemPtr, PointCloudEnv*> obj_pointcloud(targetObject->bodyItemObject, *it);\n\t\t\tobjPointCloudPairs.push_back(obj_pointcloud);\n\t\t}\n\t}\n\n\tfor(int i=0;i<interObjectList.size();i++) interObjectList[i].initialCollision();\n}\n\nvoid PlanBase::initialCollisionWithMemory(){\n\n//\tstatic vector<ColdetPairData*> coldetPairData;\n\n\trobotEnvPairs.clear();\n\tsafeRobotEnvPairs.clear();\n\trobotObjPairs.clear();\n\tobjEnvPairs.clear();\n\trobotPointCloudPairs.clear();\n\tobjPointCloudPairs.clear();\n\n\tif(targetArmFinger) {\n\t\tfor( list<BodyItemPtr>::iterator it = bodyItemEnv.begin(); it !=bodyItemEnv.end(); it++){\n\t\t\tBodyItemPtr bodyItem1= bodyItemRobot();\n\t\t\tBodyItemPtr bodyItem2= *it;\n\t\t\tbool find=false;\n\t\t\tfor(int k=0;k<coldetPairData.size();k++){\n\t\t\t\tif( ( (coldetPairData[k]->bodyItem1== bodyItem1) && (coldetPairData[k]->bodyItem2== bodyItem2) ) ||\n\t\t\t\t       ((coldetPairData[k]->bodyItem2== bodyItem2) && (coldetPairData[k]->bodyItem1== bodyItem1) ) ){\n\t\t\t\t\tfind=true;\n\t\t\t\t\trobotEnvPairs.insert( robotEnvPairs.end(),  coldetPairData[k]->coldetLinkPairs.begin(), coldetPairData[k]->coldetLinkPairs.end() );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif(find) continue;\n\t\t\tColdetPairData * temp = new ColdetPairData(bodyItem1, bodyItem2);\n\t\t\tcoldetPairData.push_back(temp);\n\t\t\trobotEnvPairs.insert( robotEnvPairs.end(),  temp->coldetLinkPairs.begin(), temp->coldetLinkPairs.end() );\n\t\t}\n\n\t\tfor( list<BodyItemPtr>::iterator it = bodyItemEnv.begin(); it !=bodyItemEnv.end(); it++){\n\t\t\tBodyItemPtr bodyItem1= bodyItemRobot();\n\t\t\tBodyItemPtr bodyItem2= *it;\n\t\t\tbool find=false;\n\t\t\tfor(int k=0;k<safeColdetPairData.size();k++){\n\t\t\t\tif( ( (safeColdetPairData[k]->bodyItem1== bodyItem1) && (safeColdetPairData[k]->bodyItem2== bodyItem2) ) ||\n\t\t\t\t       ((safeColdetPairData[k]->bodyItem2== bodyItem2) && (safeColdetPairData[k]->bodyItem1== bodyItem1) ) ){\n\t\t\t\t\tfind=true;\n\t\t\t\t\tsafeRobotEnvPairs.insert( safeRobotEnvPairs.end(),  safeColdetPairData[k]->coldetLinkPairs.begin(), safeColdetPairData[k]->coldetLinkPairs.end() );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif(find) continue;\n\t\t\tColdetPairData * temp = new ColdetPairData(bodyItem1, bodyItem2, false, true);\n\t\t\tsafeColdetPairData.push_back(temp);\n\t\t\tsafeRobotEnvPairs.insert( safeRobotEnvPairs.end(),  temp->coldetLinkPairs.begin(), temp->coldetLinkPairs.end() );\n\t\t}\n\n\t}\n\n\tif(targetObject){\n\t\tif(targetArmFinger) {\n\t\t\tBodyItemPtr bodyItem1= bodyItemRobot();\n\t\t\tBodyItemPtr bodyItem2= targetObject->bodyItemObject;\n\t\t\tbool find=false;\n\t\t\tfor(int k=0;k<coldetPairData.size();k++){\n\t\t\t\tif( ( (coldetPairData[k]->bodyItem1== bodyItem1) && (coldetPairData[k]->bodyItem2== bodyItem2) ) ||\n\t\t\t\t       ((coldetPairData[k]->bodyItem2== bodyItem2) && (coldetPairData[k]->bodyItem1== bodyItem1) ) ){\n\t\t\t\t\tfind=true;\n\t\t\t\t\trobotObjPairs.insert( robotObjPairs.end(),  coldetPairData[k]->coldetLinkPairs.begin(), coldetPairData[k]->coldetLinkPairs.end() );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif(!find){\n\t\t\t\tColdetPairData * temp = new ColdetPairData(bodyItem1, bodyItem2);\n\t\t\t\tcoldetPairData.push_back(temp);\n\t\t\t\trobotObjPairs.insert( robotObjPairs.end(),  temp->coldetLinkPairs.begin(), temp->coldetLinkPairs.end() );\n\t\t\t}\n\t\t}\n\n\t\tfor(list<cnoid::BodyItemPtr>::iterator it = bodyItemEnv.begin(); it !=bodyItemEnv.end();it++){\n\t\t\tBodyItemPtr bodyItem1= targetObject->bodyItemObject;\n\t\t\tBodyItemPtr bodyItem2= *it;\n\t\t\tbool find=false;\n\t\t\tfor(int k=0;k<coldetPairData.size();k++){\n\t\t\t\tif( ( (coldetPairData[k]->bodyItem1== bodyItem1) && (coldetPairData[k]->bodyItem2== bodyItem2) ) ||\n\t\t\t\t       ((coldetPairData[k]->bodyItem2== bodyItem2) && (coldetPairData[k]->bodyItem1== bodyItem1) ) ){\n\t\t\t\t\tfind=true;\n\t\t\t\t\tobjEnvPairs.insert( objEnvPairs.end(),  coldetPairData[k]->coldetLinkPairs.begin(), coldetPairData[k]->coldetLinkPairs.end() );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(find) continue;\n\t\t\tColdetPairData * temp = new ColdetPairData(bodyItem1, bodyItem2);\n\t\t\tcoldetPairData.push_back(temp);\n\t\t\tobjEnvPairs.insert( objEnvPairs.end(),  temp->coldetLinkPairs.begin(), temp->coldetLinkPairs.end() );\n\t\t}\n\t\tif(useObjectSafeBoundingBox){\n\t\t\tobjEnvPairs.clear();\n            ColdetModelPtr backup = object()->coldetModel();\n            object()->setColdetModel(targetObject->safeBoundingBox);\n\t\t\tfor(list<cnoid::BodyItemPtr>::iterator it = bodyItemEnv.begin(); it !=bodyItemEnv.end();it++){\n\t\t\t\tfor(unsigned int i=0;i<(*it)->body()->numLinks();i++){\n#ifdef  CNOID_10_11_12_13\n\t\t\t\t\tobjEnvPairs.push_back(new ColdetLinkPair(object(), (*it)->body()->link(i)));\n#else\n\t\t\t\t\tobjEnvPairs.push_back( make_shared<ColdetLinkPair>(targetObject->bodyItemObject->body(), object(), (*it)->body(), (*it)->body()->link(i)));\n#endif\n\t\t\t\t}\n\t\t\t}\n//\t\t\tobject()->coldetModel() = backup;\n\t\t\tobject()->setColdetModel(backup);\n\t\t}\n\t}\n\tfor(list<PointCloudEnv*>::iterator it = pointCloudEnv.begin(); it != pointCloudEnv.end(); ++it){\n\t\tif (targetArmFinger) {\n\t\t\tpair<BodyItemPtr, PointCloudEnv*> robo_pointcloud(bodyItemRobot(), *it);\n\t\t\trobotPointCloudPairs.push_back(robo_pointcloud);\n\t\t}\n\t\tif (targetObject) {\n\t\t\tpair<BodyItemPtr, PointCloudEnv*> obj_pointcloud(targetObject->bodyItemObject, *it);\n\t\t\tobjPointCloudPairs.push_back(obj_pointcloud);\n\t\t}\n\t}\n\tfor(int i=0;i<interObjectList.size();i++) interObjectList[i].initialCollision();\n\n\tos << \"coldetPairData size\" << coldetPairData.size() << endl;\n}\n\n\n\nvoid PlanBase::setObjPos(const cnoid::Vector3& P, const cnoid::Matrix3 R){\n\n\ttargetObject->objVisPos = P;\n\ttargetObject->objVisRot = R;\n    object()->p()=P;\n\tobject()->R()=R;\n\n\ttargetObject->offsetApplied = false;\n\n\treturn;\n\n}\n\nvoid PlanBase::setVisOffset(const cnoid::Vector3& P)\n{\n\tif(!targetObject->offsetApplied){\n\t\ttargetObject->objVisPos += P;\n        object()->p() += P;\n\t\ttargetObject->offsetApplied = true;\n\t}\n}\n\nvoid PlanBase::setVisOffsetR()\n{\n\tVector3 y = rpyFromRot(targetObject->objVisRot);\n\tif( fabs(y(0))<0.1 ) y(0)=0;\n\telse if(fabs(y(0)-1.5708)<0.1 ) y(0) =  1.5708;\n\telse if(fabs(y(0)+1.5708)<0.1 ) y(0) = -1.5708;\n\telse if(fabs(y(0)-3.1415)<0.1 ) y(0) =  3.1415;\n\telse if(fabs(y(0)+3.1415)<0.1 ) y(0) = -3.1415;\n\n\tif( fabs(y(1))<0.1 ) y(1)=0;\n\telse if(fabs(y(1)-1.5708)<0.1 ) y(1) =  1.5708;\n\telse if(fabs(y(1)+1.5708)<0.1 ) y(1) = -1.5708;\n\telse if(fabs(y(1)-3.1415)<0.1 ) y(1) =  3.1415;\n\telse if(fabs(y(1)+3.1415)<0.1 ) y(1) = -3.1415;\n\n\ttargetObject->objVisRot = rotFromRpy(y);\n    object()->R() = rotFromRpy(y);\n}\n\nvoid PlanBase::removeVisOffset(const cnoid::Vector3& P)\n{\n\tif(targetObject->offsetApplied){\n\t\ttargetObject->objVisPos -= P;\n        object()->p() -= P;\n\t\ttargetObject->offsetApplied = false;\n\t}\n}\n\nvoid PlanBase::setInterLink(){\n\tif(interLinkList.empty()) return;\n\tfor(int i=0; i<interLinkList.size();i++){\n        interLinkList[i].slave->q() = interLinkList[i].master->q() *interLinkList[i].ratio;\n        if( interLinkList[i].slave->q() < interLinkList[i].slave->q_lower()) interLinkList[i].slave->q() = interLinkList[i].slave->q_lower();\n        if( interLinkList[i].slave->q() > interLinkList[i].slave->q_upper()) interLinkList[i].slave->q() = interLinkList[i].slave->q_upper();\n\t}\n}\n", "meta": {"hexsha": "50aba911c3b2a398699073a9a93756c1247fa2b7", "size": 49560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modified  source/Choreonoid/PlanBase.cpp", "max_stars_repo_name": "irvs/avoidance-behavior", "max_stars_repo_head_hexsha": "ad921202199c9630c946ea8a99bb190c4d5cdcb2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-04-15T08:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-15T08:33:37.000Z", "max_issues_repo_path": "modified  source/Choreonoid/PlanBase.cpp", "max_issues_repo_name": "irvs/avoidance-behavior", "max_issues_repo_head_hexsha": "ad921202199c9630c946ea8a99bb190c4d5cdcb2", "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": "modified  source/Choreonoid/PlanBase.cpp", "max_forks_repo_name": "irvs/avoidance-behavior", "max_forks_repo_head_hexsha": "ad921202199c9630c946ea8a99bb190c4d5cdcb2", "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.546785487, "max_line_length": 221, "alphanum_fraction": 0.6509079903, "num_tokens": 15751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.18809832877732338}}
{"text": "#include <trajopt_utils/macros.h>\nTRAJOPT_IGNORE_WARNINGS_PUSH\n#include <boost/functional/hash.hpp>\n#include <moveit/planning_scene/planning_scene.h>\n#include <moveit/collision_detection_fcl/collision_env_fcl.h>\nTRAJOPT_IGNORE_WARNINGS_POP\n\n#include <trajopt/collision_terms.h>\n#include <trajopt/utils.hpp>\n#include <trajopt_sco/expr_ops.hpp>\n#include <trajopt_sco/expr_vec_ops.hpp>\n#include <trajopt_sco/modeling_utils.hpp>\n#include <trajopt_sco/sco_common.hpp>\n#include <trajopt_utils/eigen_conversions.hpp>\n#include <trajopt_utils/logging.hpp>\n#include <trajopt_utils/stl_to_string.hpp>\n\nnamespace trajopt\n{\nvoid CollisionsToDistances(const collision_detection::DistanceMap& distance_results, sco::DblVec& dists)\n{\n  dists.clear();\n  dists.reserve(distance_results.size());\n  for (const auto& d : distance_results)\n  {\n    dists.push_back(d.second[0].distance);\n  }\n}\n\nvoid CollisionsToDistanceExpressions(const collision_detection::DistanceMap& distance_results,\n                                     planning_scene::PlanningSceneConstPtr env,\n                                     const robot_state::JointModelGroup* joint_model_group,\n                                     const sco::VarVector& vars, \n                                     const sco::DblVec& dofvals, \n                                     sco::AffExprVector& exprs,\n                                     bool isTimestep1)\n{\n  exprs.clear();\n  exprs.reserve(distance_results.size());\n  moveit::core::RobotState robot_state(env->getRobotModel());\n  robot_state.setVariablePositions(joint_model_group->getActiveJointModelNames(), dofvals);\n  robot_state.update();\n  for (const auto& d : distance_results)\n  {\n    sco::AffExpr dist(d.second[0].distance);\n    Eigen::MatrixXd jacobian;\n    bool robot_link1 = false, robot_link2 = false;\n    if (robot_state.getJacobian(joint_model_group,\n                                env->getRobotModel()->getLinkModel(d.second[0].link_names[0]),\n                                d.second[0].nearest_points[0], jacobian))\n    {\n      Eigen::VectorXd dist_grad = -d.second[0].normal.transpose()*jacobian.topRows(3);\n      sco::exprInc(dist, sco::varDot(dist_grad, vars));\n      sco::exprInc(dist, -dist_grad.dot(util::toVectorXd(dofvals)));\n      robot_link1 = true;\n    } \n    if (robot_state.getJacobian(joint_model_group,\n                                env->getRobotModel()->getLinkModel(d.second[0].link_names[1]),\n                                d.second[0].nearest_points[1], jacobian))\n    {\n      Eigen::VectorXd dist_grad = d.second[0].normal.transpose()*jacobian.topRows(3);\n      sco::exprInc(dist, sco::varDot(dist_grad, vars));\n      sco::exprInc(dist, -dist_grad.dot(util::toVectorXd(dofvals)));\n      robot_link2 = true;\n    }\n    if (robot_link1 || robot_link2) \n    {\n      exprs.push_back(dist);\n    }\n  }\n\n  LOG_DEBUG(\"%ld distance expressions\\n\", exprs.size());\n}\n\ninline size_t hash(const sco::DblVec& x){ return boost::hash_range(x.begin(), x.end()); }\n\nvoid CollisionEvaluator::GetCollisionsCached(const sco::DblVec& x, collision_detection::DistanceMap& distance_results) \n{\n  size_t key = hash(sco::getDblVec(x, GetVars()));\n  collision_detection::DistanceMap* it = m_cache.get(key);\n  if (it != nullptr) {\n    LOG_DEBUG(\"using cached collision check\\n\");\n    distance_results = *it;\n  }\n  else {\n    LOG_DEBUG(\"not using cached collision check\\n\");\n    CalcCollisions(x, distance_results);\n    m_cache.put(key, distance_results);\n  }\n}\n\nSingleTimestepCollisionEvaluator::SingleTimestepCollisionEvaluator(planning_scene::PlanningSceneConstPtr env,\n                                                                   const robot_state::JointModelGroup* joint_model_group,\n                                                                   const sco::VarVector& vars)\n  : CollisionEvaluator(env, joint_model_group), m_vars(vars)\n{\n}\n\nvoid SingleTimestepCollisionEvaluator::CalcCollisions(const sco::DblVec& x, collision_detection::DistanceMap& distance_results)\n{\n  sco::DblVec dofvals = getDblVec(x, m_vars);\n\n  auto diff = env->diff();\n  const collision_detection::WorldPtr world_ptr = diff->getWorldNonConst();\n  const robot_model::RobotModelConstPtr robot_model_ptr = diff->getRobotModel();\n  moveit::core::RobotState robot_state(robot_model_ptr);\n  robot_state.setVariablePositions(joint_model_group->getActiveJointModelNames(), dofvals);\n  robot_state.update();\n\n  auto dreq = collision_detection::DistanceRequest();\n  auto dres = collision_detection::DistanceResult();\n  dreq.group_name = joint_model_group->getName();\n  dreq.enable_signed_distance = true;\n  dreq.enable_nearest_points = true;\n  dreq.acm = &diff->getAllowedCollisionMatrix();\n  dreq.type = collision_detection::DistanceRequestType::SINGLE;\n  collision_detection::CollisionEnvFCL cenv(robot_model_ptr, world_ptr);\n\n  cenv.distanceRobot(dreq, dres, robot_state);\n  distance_results.insert(dres.distances.begin(), dres.distances.end());\n  cenv.distanceSelf(dreq, dres, robot_state);\n  distance_results.insert(dres.distances.begin(), dres.distances.end());\n}\n\nvoid SingleTimestepCollisionEvaluator::CalcDists(const sco::DblVec& x, sco::DblVec& dists) \n{\n  collision_detection::DistanceMap distance_results;\n  GetCollisionsCached(x, distance_results);\n  CollisionsToDistances(distance_results, dists);\n}\n\nvoid SingleTimestepCollisionEvaluator::CalcDistExpressions(const sco::DblVec& x, sco::AffExprVector& exprs)\n{\n  collision_detection::DistanceMap distance_results;\n  GetCollisionsCached(x, distance_results);\n  sco::DblVec dofvals = sco::getDblVec(x, m_vars);\n  CollisionsToDistanceExpressions(distance_results, env, joint_model_group, m_vars, dofvals, exprs, false);\n}\n\n//////////////////////////////////////////\n\nCollisionCost::CollisionCost(planning_scene::PlanningSceneConstPtr env, \n                             const robot_state::JointModelGroup* joint_model_group,\n                             double dist_pen, double coeff, const sco::VarVector& vars)\n  : Cost(\"collision\"), m_calc(new SingleTimestepCollisionEvaluator(env, joint_model_group, vars)), m_dist_pen(dist_pen), m_coeff(coeff)\n{\n}\n\nsco::ConvexObjectivePtr CollisionCost::convex(const sco::DblVec& x, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  sco::AffExprVector exprs;\n  m_calc->CalcDistExpressions(x, exprs);\n  for (std::size_t i=0; i < exprs.size(); ++i)\n  {\n    sco::AffExpr viol = sco::exprSub(sco::AffExpr(m_dist_pen), exprs[i]);\n    out->addHinge(viol, m_coeff);\n  }\n  return out;\n}\n\ndouble CollisionCost::value(const sco::DblVec& x)\n{\n  sco::DblVec dists;\n  m_calc->CalcDists(x, dists);\n  double out = 0;\n  for (std::size_t i=0; i < dists.size(); ++i) {\n    out += sco::pospart(m_dist_pen - dists[i]) * m_coeff;\n  }\n  return out;\n}\n\n// ALMOST EXACTLY COPIED FROM CollisionCost\n\nCollisionConstraint::CollisionConstraint(planning_scene::PlanningSceneConstPtr env,\n                                         const robot_state::JointModelGroup* joint_model_group,\n                                         double dist_pen, double coeff, const sco::VarVector& vars)\n  : m_calc(new SingleTimestepCollisionEvaluator(env, joint_model_group, vars)), m_dist_pen(dist_pen), m_coeff(coeff)\n{\n  name_ = \"collision\";\n}\n\nsco::ConvexConstraintsPtr CollisionConstraint::convex(const sco::DblVec& x, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  sco::AffExprVector exprs;\n  m_calc->CalcDistExpressions(x, exprs);\n  for (std::size_t i = 0; i < exprs.size(); ++i)\n  {\n    sco::AffExpr viol = sco::exprSub(sco::AffExpr(m_dist_pen), exprs[i]);\n    out->addIneqCnt(sco::exprMult(viol, m_coeff));\n  }\n  return out;\n}\n\nsco::DblVec CollisionConstraint::value(const sco::DblVec& x) {\n  sco::DblVec dists;\n  m_calc->CalcDists(x, dists);\n  sco::DblVec out(dists.size());\n  for (std::size_t i=0; i < dists.size(); ++i) {\n    out[i] = sco::pospart(m_dist_pen - dists[i]) * m_coeff;\n  }\n  return out;\n}\n\n}  // namespace trajopt", "meta": {"hexsha": "d98c7fb6f6bbbc6657c8d9e5571a1403a8cec792", "size": 7948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moveit_planners/trajopt/trajopt/src/collision_terms.cpp", "max_stars_repo_name": "adam-vonderviszt/moveit", "max_stars_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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": "moveit_planners/trajopt/trajopt/src/collision_terms.cpp", "max_issues_repo_name": "adam-vonderviszt/moveit", "max_issues_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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": "moveit_planners/trajopt/trajopt/src/collision_terms.cpp", "max_forks_repo_name": "adam-vonderviszt/moveit", "max_forks_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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.5825242718, "max_line_length": 135, "alphanum_fraction": 0.6863361852, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.188098317586914}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n// TestCorrelator.h\n#include <gtest/gtest.h>\n\n#include <vw/Image/UtilityViews.h>\n#include <vw/Stereo/CorrelatorView.h>\n#include <vw/Image/Transform.h>\n\n#include <boost/random/linear_congruential.hpp>\n\nusing namespace vw;\nusing namespace vw::stereo;\n\nclass BasicCorrelationTest : public ::testing::Test {\nprotected:\n  BasicCorrelationTest() {}\n\n  virtual void SetUp() {\n    boost::rand48 gen(10);\n    image1 = 255*uniform_noise_view( gen, 50, 50 );\n    image2 = transform(image1, TranslateTransform(3,3),\n                       ZeroEdgeExtension(), NearestPixelInterpolation());\n    mask.set_size(50,50);\n    fill(mask,PixelMask<uint8>(255));\n  }\n\n  template <class ViewT, class MViewT, class PreProcT>\n  CorrelatorView<typename ViewT::pixel_type,\n                 typename MViewT::pixel_type,\n                 PreProcT>\n  correlate( ImageViewBase<ViewT> const& input1,\n             ImageViewBase<ViewT> const& input2,\n             ImageViewBase<MViewT> const& mask,\n             PreProcT const& proc,\n             stereo::CorrelatorType type = stereo::ABS_DIFF_CORRELATOR ) {\n    typedef typename ViewT::pixel_type pixel_type;\n    typedef typename MViewT::pixel_type mask_type;\n    CorrelatorView<pixel_type,mask_type,PreProcT> corr( input1, input2, mask, mask, proc, false );\n    corr.set_search_range( BBox2i(0,0,6,6) );\n    corr.set_kernel_size(  Vector2i(7,7)   );\n    corr.set_correlator_options( 1, type );\n    return corr;\n  }\n\n  template <class ViewT>\n  void check_error( ImageViewBase<ViewT> const& input,\n                    float success = 0.9 ) {\n    ViewT const& disparity_map = input.impl();\n    int count_correct = 0;\n    int count_valid = 0;\n    for (int j = 0; j < disparity_map.rows(); ++j)\n      for (int i = 0; i < disparity_map.cols(); ++i)\n        if ( is_valid( disparity_map(i,j) ) ) {\n          count_valid++;\n          if ( disparity_map(i,j).child() == Vector2f(3,3) )\n            count_correct++;\n        }\n    EXPECT_GT( float(count_correct)/float(count_valid), success );\n  }\n\n  ImageView<uint8> image1, image2;\n  ImageView<PixelMask<uint8> > mask;\n};\n\nTEST_F( BasicCorrelationTest, NullPreprocess ) {\n  typedef NullStereoPreprocessingFilter FilterT;\n\n  ImageView<PixelMask<Vector2f> > disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::ABS_DIFF_CORRELATOR );\n  check_error( disparity_map, 0.95 );\n\n  disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::SQR_DIFF_CORRELATOR );\n  check_error( disparity_map, 0.93 );\n\n  disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::NORM_XCORR_CORRELATOR );\n  check_error( disparity_map, 0.95 );\n}\n\nTEST_F( BasicCorrelationTest, SlogPreprocess ) {\n  typedef SlogStereoPreprocessingFilter FilterT;\n\n  ImageView<PixelMask<Vector2f> > disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::ABS_DIFF_CORRELATOR );\n  check_error( disparity_map, 0.84 );\n\n  disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::SQR_DIFF_CORRELATOR );\n  check_error( disparity_map, 0.84 );\n\n  disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::NORM_XCORR_CORRELATOR );\n  check_error( disparity_map, 0.915 );\n}\n\nTEST_F( BasicCorrelationTest, LogPreprocess ) {\n  typedef LogStereoPreprocessingFilter FilterT;\n\n  ImageView<PixelMask<Vector2f> > disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::ABS_DIFF_CORRELATOR );\n  check_error( disparity_map, 0.85 );\n\n  disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::SQR_DIFF_CORRELATOR );\n  check_error( disparity_map, 0.81 );\n\n  disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::NORM_XCORR_CORRELATOR );\n  check_error( disparity_map, 0.89 );\n}\n\nTEST_F( BasicCorrelationTest, BlurPreprocess ) {\n  typedef BlurStereoPreprocessingFilter FilterT;\n\n  ImageView<PixelMask<Vector2f> > disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::ABS_DIFF_CORRELATOR );\n  check_error( disparity_map, 0.79 );\n\n  disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::SQR_DIFF_CORRELATOR );\n  check_error( disparity_map, 0.75 );\n\n  disparity_map =\n    correlate( image1, image2, mask, FilterT(),\n               stereo::NORM_XCORR_CORRELATOR );\n  check_error( disparity_map, 0.79 );\n}\n", "meta": {"hexsha": "5029e1884754a0a8b953e2bc8000108ddf65f5ad", "size": 4644, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/vw/Stereo/tests/TestCorrelator.cxx", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/Stereo/tests/TestCorrelator.cxx", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.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": "src/vw/Stereo/tests/TestCorrelator.cxx", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 31.8082191781, "max_line_length": 98, "alphanum_fraction": 0.6737726098, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.188098317586914}}
{"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 - 2013 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_OPERATOR_FUNCTIONS_SIMD_VMX_QPX_PLUS_HPP_INCLUDED\n#define BOOST_SIMD_OPERATOR_FUNCTIONS_SIMD_VMX_QPX_PLUS_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_QPX_SUPPORT\n\n#include <boost/simd/operator/functions/plus.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT         ( plus_, boost::simd::tag::qpx_\n                                   , (A0)\n                                   , ((simd_<double_<A0>, boost::simd::tag::qpx_>))\n                                     ((simd_<double_<A0>, boost::simd::tag::qpx_>))\n                                   )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return vec_add(a0(), a1());\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "f8490dc8b544b6f16671f037eaed45691b957634", "size": 1283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/operator/functions/simd/vmx/qpx/plus.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/operator/functions/simd/vmx/qpx/plus.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/operator/functions/simd/vmx/qpx/plus.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": 36.6571428571, "max_line_length": 83, "alphanum_fraction": 0.5167575994, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.188098317586914}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\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_1F0_HPP\r\n#define BOOST_MATH_HYPERGEOMETRIC_1F0_HPP\r\n\r\n#include <boost/math/policies/policy.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n\r\n\r\nnamespace boost { namespace math { namespace detail {\r\n\r\ntemplate <class T, class Policy>\r\ninline T hypergeometric_1F0_imp(const T& a, const T& z, const Policy& pol)\r\n{\r\n   static const char* function = \"boost::math::hypergeometric_1F0<%1%,%1%>(%1%, %1%)\";\r\n   BOOST_MATH_STD_USING // pow\r\n\r\n   if (z == 1)\r\n      return policies::raise_pole_error<T>(\r\n         function,\r\n         \"Evaluation of 1F0 with z = %1%.\",\r\n         z,\r\n         pol);\r\n   if (1 - z < 0)\r\n   {\r\n      if (floor(a) != a)\r\n         return policies::raise_domain_error<T>(function,\r\n            \"Result is complex when a is non-integral and z > 1, but got z = %1%\", z, pol);\r\n   }\r\n   // more naive and convergent method than series\r\n   return pow(T(1 - z), T(-a));\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_1F0(T1 a, T2 z, const Policy&)\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_1F0_imp<value_type>(\r\n         static_cast<value_type>(a),\r\n         static_cast<value_type>(z),\r\n         forwarding_policy()),\r\n      \"boost::math::hypergeometric_1F0<%1%>(%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline typename tools::promote_args<T1, T2>::type hypergeometric_1F0(T1 a, T2 z)\r\n{\r\n   return hypergeometric_1F0(a, z, policies::policy<>());\r\n}\r\n\r\n\r\n  } } // namespace boost::math\r\n\r\n#endif // BOOST_MATH_HYPERGEOMETRIC_1F0_HPP\r\n", "meta": {"hexsha": "f1e670ed017c0d767a968a416721c03e635f3685", "size": 2456, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/special_functions/hypergeometric_1F0.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_1F0.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_1F0.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.1891891892, "max_line_length": 96, "alphanum_fraction": 0.6469869707, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.18807784381920756}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2012 Mateusz Loskot, London, UK.\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_MULTI_ALGORITHMS_DISJOINT_HPP\r\n#define BOOST_GEOMETRY_MULTI_ALGORITHMS_DISJOINT_HPP\r\n\r\n\r\n#include <boost/geometry/algorithms/disjoint.hpp>\r\n#include <boost/geometry/multi/algorithms/covered_by.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\n#ifndef DOXYGEN_NO_DISPATCH\r\nnamespace dispatch\r\n{\r\n\r\ntemplate <typename Point, typename MultiPolygon>\r\nstruct disjoint<Point, MultiPolygon, 2, point_tag, multi_polygon_tag, false>\r\n    : detail::disjoint::reverse_covered_by<Point, MultiPolygon>\r\n{};\r\n\r\n} // namespace dispatch\r\n\r\n\r\n#endif // DOXYGEN_NO_DISPATCH\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_MULTI_ALGORITHMS_DISJOINT_HPP\r\n", "meta": {"hexsha": "a8175d3a4ffbfb20d219fe4b204d222570321909", "size": 1104, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "_thirdPartyLibs/include/boost/geometry/multi/algorithms/disjoint.hpp", "max_stars_repo_name": "kamarianakis/glGA-edu", "max_stars_repo_head_hexsha": "17f0b33c3ea8efcfa8be01d41343862ea4e6fae0", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "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": "_thirdPartyLibs/include/boost/geometry/multi/algorithms/disjoint.hpp", "max_issues_repo_name": "kamarianakis/glGA-edu", "max_issues_repo_head_hexsha": "17f0b33c3ea8efcfa8be01d41343862ea4e6fae0", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "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": "_thirdPartyLibs/include/boost/geometry/multi/algorithms/disjoint.hpp", "max_forks_repo_name": "kamarianakis/glGA-edu", "max_forks_repo_head_hexsha": "17f0b33c3ea8efcfa8be01d41343862ea4e6fae0", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "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": 26.2857142857, "max_line_length": 80, "alphanum_fraction": 0.7545289855, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352405, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.1880778401286745}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cstring>\n#include <limits>\n#include <mpi.h>\n//#include <Eigen/Eigenvalues>\n\nenum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};\n\n#include \"particle_simulator.hpp\"\n#include \"hdr_time.hpp\"\n#include \"hdr_run.hpp\"\n#ifdef USE_INTRINSICS\n#include \"vector_x86.hpp\"\n#endif\n#include \"hdr_dimension.hpp\"\n#include \"hdr_kernel.hpp\"\n#include \"hdr_sph.hpp\"\n#include \"hdr_hgas.hpp\"\n#include \"hdr_bhns.hpp\"\n\nclass SPHAnalysis : public HelmholtzGas {\npublic:\n    SPHAnalysis() {\n        this->id    = 0;\n        this->istar = 0;\n        this->mass  = 0.;\n        this->pos   = 0.;\n        this->vel   = 0.;\n        this->uene  = 0.;\n        this->alph  = 0.;\n        this->alphu = 0.;\n        this->ksr   = 0.;\n        for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->cmps[k] = 0.;\n        }        \n    }\n\n    void readAscii(FILE * fp) {\n        fscanf(fp, \"%lld%lld%lf\", &this->id, &this->istar, &this->mass);      //  3\n        fscanf(fp, \"%lf%lf%lf\", &this->pos[0], &this->pos[1], &this->pos[2]); //  6\n        fscanf(fp, \"%lf%lf%lf\", &this->vel[0], &this->vel[1], &this->vel[2]); //  9\n        fscanf(fp, \"%lf%lf%lf\", &this->acc[0], &this->acc[1], &this->acc[2]); // 12\n        fscanf(fp, \"%lf%lf%lf\", &this->uene, &this->alph, &this->alphu);      // 15\n        fscanf(fp, \"%lf%lf%6d\", &this->dens, &this->ksr,  &this->np);         // 18\n        fscanf(fp, \"%lf%lf%lf\", &this->vsnd, &this->pres, &this->temp);       // 21\n        fscanf(fp, \"%lf%lf%lf\", &this->divv, &this->rotv, &this->bswt);       // 24\n        fscanf(fp, \"%lf%lf%lf\", &this->pot,  &this->abar, &this->zbar);       // 27\n        fscanf(fp, \"%lf\",       &this->enuc);                                 // 28\n        fscanf(fp, \"%lf%lf%lf\", &this->vsmx, &this->udot, &this->dnuc);       // 31\n        for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) {       // 32 -- 44\n            fscanf(fp, \"%lf\", &this->cmps[k]);\n        }\n        fscanf(fp, \"%lf\", &this->pot3);\n        fscanf(fp, \"%lf%lf%lf\", &this->tempmax[0], &this->tempmax[1], &this->tempmax[2]);\n        fscanf(fp, \"%lf\", &this->entr);\n    }\n\n    void writeAscii(FILE *fp) const {\n        fprintf(fp, \"%6d %2d %+e\", this->id, this->istar, this->mass);         //  3\n        fprintf(fp, \" %+e %+e %+e\", this->pos[0], this->pos[1], this->pos[2]); //  6\n        fprintf(fp, \" %+e %+e %+e\", this->vel[0], this->vel[1], this->vel[2]); //  9\n        fprintf(fp, \" %+e %+e %+e\", this->acc[0], this->acc[1], this->acc[2]); // 12\n        fprintf(fp, \" %+e %+e %+e\", this->uene, this->alph, this->alphu);      // 15\n        fprintf(fp, \" %+e %+e %6d\", this->dens, this->ksr,  this->np);         // 18\n        fprintf(fp, \" %+e %+e %+e\", this->vsnd, this->pres, this->temp);       // 21\n        fprintf(fp, \" %+e %+e %+e\", this->divv, this->rotv, this->bswt);       // 24\n        fprintf(fp, \" %+e %+e %+e\", this->pot, this->abar, this->zbar);        // 27\n        fprintf(fp, \" %+e\",         this->enuc);                               // 28\n        fprintf(fp, \" %+e %+e %+e\", this->vsmx, this->udot, this->dnuc);       // 31\n        for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) {        // 32 -- 44\n            fprintf(fp, \" %+.3e\", this->cmps[k]);\n        }\n        if(RP::FlagDamping == 2) {\n            PS::F64vec omg = RP::RotationalVelocity;\n            PS::F64vec vec = omg ^ pos;\n            fprintf(fp, \" %+e\", this->pot - 0.5 * (vec * vec));                // 45\n        }\n        fprintf(fp, \" %+e\", this->pot3);                                       // 45\n        fprintf(fp, \" %+e %+e %+e\", this->tempmax[0], this->tempmax[1],\n                this->tempmax[2]);                                             // 46 -- 48\n        fprintf(fp, \" %+e\", this->entr);                                       // 49\n        fprintf(fp, \"\\n\");\n    }\n\n};\n\ntemplate <class Tsph>\nvoid calcPositionAndVelocityOfDensityCenter(Tsph & sph,\n                                            PS::F64vec & xcglb,\n                                            PS::F64vec & vcglb) {\n    PS::F64    dnloc = 0.;\n    PS::F64vec xcloc = 0.;\n    PS::F64vec vcloc = 0.;\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        dnloc += sph[i].dens;\n        xcloc += sph[i].dens * sph[i].pos;\n        vcloc += sph[i].dens * sph[i].vel;\n    }\n    PS::F64 dnglb;\n    dnglb = PS::Comm::getSum(dnloc);\n    xcglb = PS::Comm::getSum(xcloc);\n    vcglb = PS::Comm::getSum(vcloc);\n    xcglb /= dnglb;\n    vcglb /= dnglb;\n}\n\ntemplate <class Tsph>\nvoid findBoundParticle(char * hfile,\n                       char * ofile,\n                       PS::S64 itime,\n                       PS::S64 searchmode,\n                       PS::S64 printmode,\n                       PS::S64 excludedID,\n                       Tsph & sph) {\n    PS::F64vec xc, vc;\n    calcPositionAndVelocityOfDensityCenter(sph, xc, vc);\n\n    NR::Nucleon mxloc;\n    FILE * fp = NULL;\n    if(printmode == 0) {\n        fp = fopen(ofile, \"w\");\n    }\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        PS::F64vec dx = sph[i].pos - xc;\n        PS::F64vec dv = sph[i].vel - vc;\n        PS::F64    eb = 0.5 * (dv * dv) + sph[i].pot;\n        eb = (searchmode == 0) ? eb : (- eb);\n        //if(eb < 0.) {\n        if(eb < 0. && !(sph[i].istar == excludedID)) {\n            if(printmode == 0) {\n                sph[i].writeAscii(fp);\n            }\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                mxloc[k] += sph[i].mass * sph[i].cmps[k];\n            }\n        }\n    }\n    if(printmode == 0) {\n        fclose(fp);\n    }\n    NR::Nucleon mxglb;\n    for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n        mxglb[k]  = PS::Comm::getSum(mxloc[k]);\n        mxglb[k] /= CodeUnit::SolarMass;\n    }\n\n    if(PS::Comm::getRank() == 0) {\n        FILE * fp = fopen(hfile, \"a\");\n        fprintf(fp, \"%8d\", itime);                                         // 1\n        fprintf(fp, \" %+e %+e %+e\", xc[0], xc[1], xc[2]);                  // 4\n        fprintf(fp, \" %+e %+e %+e\", vc[0], vc[1], vc[2]);                  // 7\n        fprintf(fp, \" %+.3e %+.3e %+.3e\", mxglb[0], mxglb[1],  mxglb[2]);  // 10\n        fprintf(fp, \" %+.3e %+.3e %+.3e\", mxglb[3], mxglb[4],  mxglb[5]);  // 13\n        fprintf(fp, \" %+.3e %+.3e %+.3e\", mxglb[6], mxglb[7],  mxglb[8]);  // 16\n        fprintf(fp, \" %+.3e %+.3e %+.3e\", mxglb[9], mxglb[10], mxglb[11]); // 19\n        fprintf(fp, \" %+.3e\", mxglb[12]);                                  // 20\n        fprintf(fp, \"\\n\");\n        fclose(fp);\n    }\n\n}\n\nint main(int argc, char ** argv) {\n    PS::Initialize(argc, argv);\n\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n\n    char idir[1024], odir[1024];\n    PS::S64 ibgn, iend;\n    PS::S64 searchmode;\n    PS::S64 printmode;\n    PS::S64 excludedID;\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", idir);\n    fscanf(fp, \"%s\", odir);\n    fscanf(fp, \"%lld%lld\", &ibgn, &iend);\n    fscanf(fp, \"%lld\", &searchmode);\n    fscanf(fp, \"%lld\", &printmode);\n    fscanf(fp, \"%lld\", &excludedID);\n    fclose(fp);\n\n    char hfile[1024];\n    sprintf(hfile, \"%s/summary.log\", odir);\n    for(PS::S64 itime = ibgn; itime <= iend; itime++) {        \n        char tfile[1024];\n        FILE *fp = NULL;\n        PS::S64 tdir = 0;\n        for(PS::S64 iidir = 0; iidir < 100; iidir++) {\n            sprintf(tfile, \"%s/t%02d/sph_t%04d_p%06d_i%06d.dat\", idir, iidir, itime,\n                    PS::Comm::getNumberOfProc(), 0);\n            fp = fopen(tfile, \"r\");\n            if(fp != NULL) {\n                tdir = iidir;\n                break;\n            }\n        }\n        if(fp == NULL) {\n            continue;\n        }\n        fclose(fp);\n\n        char sfile[1024];\n        sprintf(sfile, \"%s/t%02d/sph_t%04d\", idir, tdir, itime);\n        sph.readParticleAscii(sfile, \"%s_p%06d_i%06d.dat\");\n\n        char ofile[1024];\n        //sprintf(ofile, \"%s/sph_t%04d_p%06d_i%06d.dat.bound\",\n        sprintf(ofile, \"%s/sph_t%04d_p%06d_i%06d.dat\",\n                odir, itime, PS::Comm::getNumberOfProc(), PS::Comm::getRank());\n        findBoundParticle(hfile, ofile, itime, searchmode, printmode, excludedID, sph);\n\n    }\n\n    PS::Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "402896408b4ca2533627283fbd890771228d7d61", "size": 8308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.hgas/findBound/main.cpp", "max_stars_repo_name": "atrtnkw/sph", "max_stars_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-11T00:43:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T13:41:50.000Z", "max_issues_repo_path": "tool.hgas/findBound/main.cpp", "max_issues_repo_name": "atrtnkw/sph", "max_issues_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_issues_repo_licenses": ["MIT"], "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.hgas/findBound/main.cpp", "max_forks_repo_name": "atrtnkw/sph", "max_forks_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-06T14:22:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T14:22:25.000Z", "avg_line_length": 37.2556053812, "max_line_length": 90, "alphanum_fraction": 0.4625662013, "num_tokens": 2769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18807784012867446}}
{"text": "#ifndef SAST_SAST_HPP\n#define SAST_SAST_HPP\n\n#include <stack>\n#include <stdexcept>\n#include <boost/iterator/iterator_facade.hpp>\n#include <boost/range/adaptor/sliced.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/iterator.hpp>\n#include <boost/range/size.hpp>\n#include <boost/range/sub_range.hpp>\n#include \"esa.hxx\"\n\n\nnamespace sast {\n\ntemplate <class RandomAccessRange, class Index>\nstruct positional_finder;\n\ntemplate <class RandomAccessRange, class Index>\nstruct sast;\n\ntemplate <class RandomAccessRange, class Index>\npositional_finder<RandomAccessRange, Index> make_positional_finder(const sast<RandomAccessRange, Index>&);\n\n\ntemplate <class RandomAccessRange, class Index>\nstruct sast {\n    using range_type = RandomAccessRange;\n    using char_type = typename boost::range_value<RandomAccessRange>::type;\n    using index_type = Index;\n\n    struct substr {\n        using iterator       = typename boost::range_iterator<RandomAccessRange>::type;\n        using const_iterator = typename boost::range_const_iterator<RandomAccessRange>::type;\n\n        index_type pos()       const { return parent_->sa_[parent_->l_[i_]]; }\n        boost::sub_range<const std::vector<index_type>> allpos() const { return boost::adaptors::slice(parent_->sa_, parent_->l_[i_], parent_->r_[i_]); }\n        index_type length()    const { return parent_->d_[i_]; }\n        index_type frequency() const { return parent_->r_[i_] - parent_->l_[i_]; }\n\n        iterator begin() { return boost::begin(parent_->input_) + pos(); }\n        iterator end()   { return boost::begin(parent_->input_) + pos() + length(); }\n        const_iterator begin() const { return boost::const_begin(parent_->input_) + pos(); }\n        const_iterator end()   const { return boost::const_begin(parent_->input_) + pos() + length(); }\n\n        substr(const sast* parent, int i)\n            : parent_(parent), i_(i)\n        {}\n\n    private:\n        const sast* parent_;\n        int i_;\n    };\n\nprivate:\n    template <class> struct node_iterator;\n\npublic:\n    using iterator       = node_iterator<substr>;\n    using const_iterator = node_iterator<const substr>;\n\n    sast(const RandomAccessRange& input, const size_t alphabet_size)\n        : input_(input),\n          sa_(boost::size(input)),\n          l_(boost::size(input)),\n          r_(boost::size(input)),\n          d_(boost::size(input)),\n          node_to_parent_node_()\n    {\n        // suffix array\n        int err = esaxx(boost::const_begin(input_),\n                        sa_.begin(),\n                        l_.begin(), r_.begin(), d_.begin(),\n                        static_cast<index_type>(boost::size(input_)),\n                        static_cast<index_type>(alphabet_size),\n                        num_nodes_);\n        if (err) throw std::runtime_error(\"saisxx failed to construct a suffix array.\");\n\n        // Dummy node\n        // These values are designed so that they can be used as well as those\n        // of the other nodes.\n        l_[num_nodes_] = 0;\n        r_[num_nodes_] = 0;\n        d_[num_nodes_] = 0;\n\n        // node_to_parent_node[i]: \u30ce\u30fc\u30c9i\u306e\u89aa\u30ce\u30fc\u30c9\u306e\u756a\u53f7\uff08post-order\uff09\u3002\n        // suffix_to_parent_node[k]: \u63a5\u5c3e\u8f9einput[k..$]\u306b\u5bfe\u5fdc\u3059\u308b\u8449\u30ce\u30fc\u30c9\u306e\u3001\u89aa\u30ce\u30fc\u30c9\u306epost-order\u9806\u306e\u756a\u53f7\u3002\n        node_to_parent_node_.resize(num_nodes_);\n        std::vector<index_type> suffix_to_parent_node(boost::size(input) + 1);\n        suffix_to_parent_node[boost::size(input)] = num_nodes_ - 1;  // \u63a5\u5c3e\u8f9einput[$..$]\n        {\n            std::stack<index_type> stk;  // the top of the stack is a current parent node\n            stk.push(num_nodes_);  // put the dummy node, which will be the parent of the root node\n            index_type next_node = num_nodes_ - 1;  // a node to consider next\n            index_type i = boost::size(input) - 1;  // a current suffix, the i-th suffix in the suffix array\n            // narrow the range [l, r) to find the immediate parent of the i-th node\n            while (next_node >= 0 && l_[next_node] <= i && i < r_[next_node]) {\n                node_to_parent_node_[next_node] = stk.top();\n                stk.push(next_node);\n                --next_node;\n            }\n            while (i >= 0) {\n                // widen the range [l, r) to find the lowest ancestor of the i-th node\n                while (!(l_[stk.top()] <= i && i < r_[stk.top()])) {\n                    stk.pop();\n                }\n                // narrow the range [l, r) to find the immediate parent of the i-th node\n                while (next_node >= 0 && l_[next_node] <= i && i < r_[next_node]) {\n                    node_to_parent_node_[next_node] = stk.top();\n                    stk.push(next_node);\n                    --next_node;\n                }\n                suffix_to_parent_node[sa_[i]] = stk.top();\n                --i;\n            }\n        }\n\n        // suffix_link_\n        suffix_link_.resize(num_nodes_);\n        suffix_link_[num_nodes_ - 1] = num_nodes_;  // transfers to the dummy node.\n        for (int i = 0; i < num_nodes_ - 1; ++i) {\n            // \u3053\u3053\u3067\u306f\u30ce\u30fc\u30c9i\uff08i\u306fpost-order\u3067\u306e\u756a\u53f7\uff09\u306b\u5bfe\u5fdc\u3059\u308b\u90e8\u5206\u6587\u5b57\u5217substr\u3092\u6271\u3046\u3002\n            const auto len_substr  = d_[i];\n            const auto pos_substr  = sa_[l_[i]];\n            // substr\u306e\u5148\u982d\u30921\u6587\u5b57\u524a\u3063\u305fsub-substr\u3092\u8003\u3048\u308b\u3002\n            const auto len_subsubstr = len_substr - 1;\n            // sub-substr\u306b\u5bfe\u5fdc\u3059\u308b\u30ce\u30fc\u30c9\u3092\u898b\u3064\u3051\u308b\u3002\n            // {\u5185\u90e8,\u8449}\u30ce\u30fc\u30c9\u306b\u5bfe\u5fdc\u3059\u308b\u90e8\u5206\u6587\u5b57\u5217\u304b\u3089\u5148\u982d\u306e1\u6587\u5b57\u3092\u524a\u3063\u3066\u5f97\u3089\u308c\n            // \u308b\u6587\u5b57\u5217\u306b\u306f\u3001\u5fc5\u305a\u5bfe\u5fdc\u3059\u308b{\u5185\u90e8,\u8449}\u30ce\u30fc\u30c9\u304c\u5b58\u5728\u3059\u308b\u3002\n            auto j = suffix_to_parent_node[pos_substr + 1];  // \u63a5\u5c3e\u8f9einput[(pos_substr + j)..$]\u306b\u5bfe\u5fdc\u3059\u308b\u8449\u30ce\u30fc\u30c9\u306e\u89aa\u30ce\u30fc\u30c9\n            while (d_[j] > len_subsubstr) j = node_to_parent_node_[j];  // d[j] == len_subsubstr \u306a\u3089\u3070\u3001\u30ce\u30fc\u30c9j\u306fsub-substr\u306b\u5bfe\u5fdc\u3059\u308b\u30ce\u30fc\u30c9\u3002\n            suffix_link_[i] = j;\n        }\n    }\n\n    iterator begin() { return iterator(this, 0); }\n    iterator end()   { return iterator(this, num_nodes_); }\n    const_iterator begin() const { return const_iterator(this, 0); }\n    const_iterator end()   const { return const_iterator(this, num_nodes_); }\n\n    index_type size() const { return num_nodes_; }\n\n    const RandomAccessRange& input() const {\n        return input_;\n    }\n\n    friend positional_finder<RandomAccessRange, index_type> make_positional_finder<>(const sast&);\n\nprivate:\n    template <class Value>\n    struct node_iterator\n        : public boost::iterator_facade<\n            node_iterator<Value>,\n            Value,\n            boost::random_access_traversal_tag,\n            Value,\n            int>\n    {\n        node_iterator()\n            : parent_(0), i_(-1)\n        {}\n\n        node_iterator(const sast* parent, int i)\n            : parent_(parent), i_(i)\n        {}\n\n        template <class OtherValue>\n        node_iterator(node_iterator<OtherValue> const& other)\n            : parent_(other.parent_), i_(other.i_)\n        {}\n\n        node_iterator<Value> parent() {\n            return node_iterator(parent_, parent_->node_to_parent_node_[i_]);\n        }\n\n        node_iterator<Value> suffix() {\n            return node_iterator(parent_, parent_->suffix_link_[i_]);\n        }\n\n    private:\n        friend class boost::iterator_core_access;\n        template <class> friend struct node_iterator;\n\n        void increment() { ++i_; }\n        void decrement() { --i_; }\n        void advance(int n) { i_ += n; }\n        int distance_to(const node_iterator<Value>& other) const { return other.i_ - this->i_; }\n\n        template <class OtherValue>\n        bool equal(const node_iterator<OtherValue>& other) const {\n            return this->parent_ == other.parent_ && this->i_ == other.i_;\n        }\n\n        Value dereference() const {\n            return substr(parent_, i_);\n        }\n\n        const sast* parent_;\n        int i_;\n    };\n\n    const RandomAccessRange& input_;\n    std::vector<index_type> sa_;\n    std::vector<index_type>  l_;\n    std::vector<index_type>  r_;\n    std::vector<index_type>  d_;\n    index_type  num_nodes_;\n    std::vector<index_type> node_to_parent_node_;\n    std::vector<index_type> suffix_link_;\n};\n\n\ntemplate <class RandomAccessRange, class Index>\nstruct positional_finder {\n    using range_type = RandomAccessRange;\n    using char_type = typename boost::range_value<RandomAccessRange>::type;\n    using index_type = Index;\n\nprivate:\n    using sast_type = sast<RandomAccessRange, Index>;\n\npublic:\n    template <class Vector>\n    positional_finder(const sast_type& sast, Vector&& suffix_to_parent_node)\n        : sast_(sast), suffix_to_parent_node_(std::forward<Vector>(suffix_to_parent_node))\n    {}\n\n    typename sast_type::iterator find(const int i, const int j) const {\n        const auto len_substr = j - i;\n        const auto pos_substr = i;\n        // substr\u306b\u5bfe\u5fdc\u3059\u308b\u5185\u90e8\u30ce\u30fc\u30c9\u3092\u898b\u3064\u3051\u308b\u3002\n        auto n = sast_.begin() + suffix_to_parent_node_[pos_substr];  // \u63a5\u5c3e\u8f9einput[pos_substr..$]\u306b\u5bfe\u5fdc\u3059\u308b\u8449\u30ce\u30fc\u30c9\u306e\u89aa\u30ce\u30fc\u30c9\n        if (n->length() >= len_substr) {\n            // substr\u306f2\u56de\u4ee5\u4e0a\u51fa\u73fe\u3057\u3066\u304a\u308a\u3001\u5bfe\u5fdc\u3059\u308b\u5185\u90e8\u30ce\u30fc\u30c9\u304c\u5b58\u5728\u3059\u308b\u3002\n            // d[node_to_parent_node[k]] < len_substr <= d[k] \u3092\u6e80\u305f\u3059 k \u3092\n            // \u898b\u3064\u3051\u308b\u3002\n            while (n.parent()->length() >= len_substr) {\n                n = n.parent();\n            }\n            // const auto kk = n->length() - len_substr;  // \u30ce\u30fc\u30c9k\u3067\u306fkk\u6587\u5b57\u524a\u3063\u305f\u3053\u3068\u306b\u76f8\u5f53\u3059\u308b\u3002\n\n            return n;\n        }\n        else {\n            // substr\u306f1\u56de\u3057\u304b\u51fa\u73fe\u3057\u3066\u304a\u3089\u305a\u3001\u5bfe\u5fdc\u3059\u308b\u5185\u90e8\u30ce\u30fc\u30c9\u304c\u5b58\u5728\u3057\u306a\u3044\u3002\n            return n;\n        }\n    }\n\nprivate:\n    const sast_type& sast_;\n    const std::vector<Index> suffix_to_parent_node_;\n};\n\n\ntemplate <class RandomAccessRange, class Index>\npositional_finder<RandomAccessRange, Index> make_positional_finder(const sast<RandomAccessRange, Index>& sast) {\n    const auto& input = sast.input_;\n    const auto& sa_ = sast.sa_;\n    const auto& l_ = sast.l_;\n    const auto& r_ = sast.r_;\n    const auto& num_nodes_ = sast.num_nodes_;\n\n    // suffix_to_parent_node[k]: \u63a5\u5c3e\u8f9einput[k..$]\u306b\u5bfe\u5fdc\u3059\u308b\u8449\u30ce\u30fc\u30c9\u306e\u3001\u89aa\u30ce\u30fc\u30c9\u306epost-order\u9806\u306e\u756a\u53f7\u3002\n    std::vector<Index> suffix_to_parent_node(boost::size(input) + 1);\n    suffix_to_parent_node[boost::size(input)] = num_nodes_ - 1;  // \u63a5\u5c3e\u8f9einput[$..$]\n    {\n        std::stack<Index> stk;  // the top of the stack is a current parent node\n        stk.push(num_nodes_);  // put the dummy node, which will be the parent of the root node\n        Index next_node = num_nodes_ - 1;  // a node to consider next\n        Index i = boost::size(input) - 1;  // a current suffix, the i-th suffix in the suffix array\n        // narrow the range [l, r) to find the immediate parent of the i-th node\n        while (next_node >= 0 && l_[next_node] <= i && i < r_[next_node]) {\n            stk.push(next_node);\n            --next_node;\n        }\n        while (i >= 0) {\n            // widen the range [l, r) to find the lowest ancestor of the i-th node\n            while (!(l_[stk.top()] <= i && i < r_[stk.top()])) {\n                stk.pop();\n            }\n            // narrow the range [l, r) to find the immediate parent of the i-th node\n            while (next_node >= 0 && l_[next_node] <= i && i < r_[next_node]) {\n                stk.push(next_node);\n                --next_node;\n            }\n            suffix_to_parent_node[sa_[i]] = stk.top();\n            --i;\n        }\n    }\n\n    return positional_finder<RandomAccessRange, Index>(sast, std::move(suffix_to_parent_node));\n}\n\n}  // namespace sast\n\n\n#endif  /* SAST_SAST_HPP */\n", "meta": {"hexsha": "56004274d7213322bb6f7d75343f7202536cde22", "size": 11136, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sast/sast.hpp", "max_stars_repo_name": "yuttie/atm", "max_stars_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "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/sast/sast.hpp", "max_issues_repo_name": "yuttie/atm", "max_issues_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_issues_repo_licenses": ["MIT"], "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/sast/sast.hpp", "max_forks_repo_name": "yuttie/atm", "max_forks_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_forks_repo_licenses": ["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.12, "max_line_length": 153, "alphanum_fraction": 0.6003053161, "num_tokens": 2980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18807784012867443}}
{"text": "#ifndef OSMIUM_BG_FACTORY_HPP\n#define OSMIUM_BG_FACTORY_HPP\n\n/*\n\nThis file is part of Osmium (https://osmcode.org/libosmium).\n\nCopyright 2013-2021 Jochen Topf <jochen@topf.org> and others (see README).\n\nBoost Software License - Version 1.0 - August 17th, 2003\n\nPermission is hereby granted, free of charge, to any person or organization\nobtaining a copy of the software and accompanying documentation covered by\nthis license (the \"Software\") to use, reproduce, display, distribute,\nexecute, and transmit the Software, and to prepare derivative works of the\nSoftware, and to permit third-parties to whom the Software is furnished to\ndo so, all subject to the following:\n\nThe copyright notices in the Software and this entire statement, including\nthe above license grant, this restriction and the following disclaimer,\nmust be included in all copies of the Software, in whole or in part, and\nall derivative works of the Software, unless such copies or derivative\nworks are solely in the form of machine-executable object code generated by\na source language processor.\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, TITLE AND NON-INFRINGEMENT. IN NO EVENT\nSHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\nFOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\n*/\n\n#include <osmium/geom/coordinates.hpp>\n#include <osmium/memory/collection.hpp>\n#include <osmium/memory/item.hpp>\n#include <osmium/osm/area.hpp>\n#include <osmium/osm/item_type.hpp>\n#include <osmium/osm/location.hpp>\n#include <osmium/osm/node.hpp>\n#include <osmium/osm/node_ref.hpp>\n#include <osmium/osm/node_ref_list.hpp>\n#include <osmium/osm/types.hpp>\n#include <osmium/osm/way.hpp>\n\n#include <cstddef>\n#include <stdexcept>\n#include <string>\n#include <utility>\n\n#include <osmium/geom/factory.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\nnamespace osmium {\n    namespace geom {\n        /**\n         * Boost Geometry factory.\n         */\n        class BGFactory {\n\n        public:\n            using point_type        = boost::geometry::model::d2::point_xy<double, boost::geometry::cs::geographic<boost::geometry::degree>>;\n            using box_type          = boost::geometry::model::box<point_type>;\n            using linestring_type   = boost::geometry::model::linestring<point_type>;\n            using polygon_type      = boost::geometry::model::polygon<point_type>;\n            using multipolygon_type = boost::geometry::model::multi_polygon<polygon_type>;\n            using ring_type         = boost::geometry::model::ring<point_type>;\n\n        public:\n            BGFactory() { }\n            BGFactory(const BGFactory &) = default;\n            BGFactory(BGFactory&&) = default;\n            ~BGFactory() = default;\n            BGFactory& operator=(const BGFactory &) = default;\n            BGFactory& operator=(BGFactory&&) = default;\n\n            int epsg() const noexcept { return 4326; }\n            std::string proj_string() const { return \"+proj=longlat +datum=WGS84 +no_defs\"; }\n\n            /* Point */\n\n            point_type create_point(const osmium::Location& location) const {\n                return point_type(location.lon(), location.lat());\n            }\n\n            point_type create_point(const osmium::Node& node) const {\n                try {\n                    return create_point(node.location());\n                } catch (osmium::geometry_error& e) {\n                    e.set_id(\"node\", node.id());\n                    throw;\n                }\n            }\n\n            point_type create_point(const osmium::NodeRef& node_ref) const {\n                try {\n                    return create_point(node_ref.location());\n                } catch (osmium::geometry_error& e) {\n                    e.set_id(\"node\", node_ref.ref());\n                    throw;\n                }\n            }\n\n            /* LineString */\n\n            linestring_type create_linestring(const osmium::WayNodeList& wnl, use_nodes un = use_nodes::unique, direction dir = direction::forward) const {\n                linestring_type l;\n\n                l.resize(wnl.size());\n                if(dir == direction::forward)\n                    std::transform(wnl.cbegin(), wnl.cend(), l.begin(), [&](const osmium::NodeRef& n){ return create_point(n); });\n                else\n                    std::transform(wnl.crbegin(), wnl.crend(), l.begin(), [&](const osmium::NodeRef& n){ return create_point(n); });\n                \n                if(un == use_nodes::unique)\n                    boost::geometry::unique(l);\n\n                if(l.size() < 2)\n                    throw osmium::geometry_error{\"need at least two points for linestring\"};\n\n                if(! boost::geometry::is_valid(l)) {\n                    std::string m;\n                    boost::geometry::is_valid(l, m);\n                    throw osmium::geometry_error{m};\n                }\n\n                return l;\n            }\n\n            linestring_type create_linestring(const osmium::Way& way, use_nodes un = use_nodes::unique, direction dir = direction::forward) const {\n                try {\n                    return create_linestring(way.nodes(), un, dir);\n                } catch (osmium::geometry_error& e) {\n                    e.set_id(\"way\", way.id());\n                    throw;\n                }\n            }\n\n            /* Polygon */\n\n            polygon_type create_polygon(const osmium::WayNodeList& wnl, use_nodes un = use_nodes::unique, direction dir = direction::forward) const {\n                polygon_type p;\n\n                p.outer().resize(wnl.size());\n                if(dir == direction::forward)\n                    std::transform(wnl.cbegin(), wnl.cend(), p.outer().begin(), [&](const osmium::NodeRef& n){ return create_point(n); });\n                else\n                    std::transform(wnl.crbegin(), wnl.crend(), p.outer().begin(), [&](const osmium::NodeRef& n){ return create_point(n); });\n                \n                if (un == use_nodes::unique)\n                    boost::geometry::unique(p);\n\n                if (p.outer().size() < 4)\n                    throw osmium::geometry_error{\"need at least four points for polygon\"};\n\n                if (! boost::geometry::is_valid(p)) {\n                    std::string m;\n                    boost::geometry::is_valid(p, m);\n                    throw osmium::geometry_error{m};\n                }\n                \n                return p;\n            }\n\n            polygon_type create_polygon(const osmium::Way& way, use_nodes un = use_nodes::unique, direction dir = direction::forward) const {\n                try {\n                    return create_polygon(way.nodes(), un, dir);\n                } catch (osmium::geometry_error& e) {\n                    e.set_id(\"way\", way.id());\n                    throw;\n                }\n            }\n\n            /* MultiPolygon */\n\n            multipolygon_type create_multipolygon(const osmium::Area& area) const {\n                try {\n                    multipolygon_type mp;\n                    polygon_type * current_polygon = nullptr;\n                    for (const auto& item : area) {\n                        if (item.type() == osmium::item_type::outer_ring) {\n                            const auto& ring = static_cast<const osmium::OuterRing&>(item);\n                            current_polygon = &mp.emplace_back();\n                            current_polygon->outer().resize(ring.size());\n                            std::transform(ring.crbegin(), ring.crend(), current_polygon->outer().begin(), \n                                    [&](const osmium::NodeRef& n){ return create_point(n); });\n                        } else if (item.type() == osmium::item_type::inner_ring) {\n                            const auto& ring = static_cast<const osmium::InnerRing&>(item);\n                            ring_type & current_ring = current_polygon->inners().emplace_back();\n                            current_ring.resize(ring.size());\n                            std::transform(ring.crbegin(), ring.crend(), current_ring.begin(), \n                                    [&](const osmium::NodeRef& n){ return create_point(n); });\n                        }\n                    }\n\n                    if(mp.empty())\n                        throw osmium::geometry_error{\"invalid area\"};\n\n                    if(!boost::geometry::is_valid(mp)) {\n                        std::string m;\n                        boost::geometry::is_valid(mp, m);\n                        throw osmium::geometry_error{m};\n                    }\n\n                    return mp;\n                } catch (osmium::geometry_error& e) {\n                    e.set_id(\"area\", area.id());\n                    throw;\n                }\n            }\n\n            template<class T>\n            box_type envelope(T&& elem) {\n                const osmium::Box box = elem.envelope();\n                return box_type(create_point(box.bottom_left()), create_point(box.top_right()));\n            }\n        }; // class BGFactory\n    } // namespace geom\n} // namespace osmium\n\n#endif // OSMIUM_GEOM_FACTORY_HPP\n", "meta": {"hexsha": "a3bb8262023ca09a006bc671d8e89fac636b8b04", "size": 9515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/osmium_utils/bg_factory.hpp", "max_stars_repo_name": "fhamonic/osm2sorted_geojson", "max_stars_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T11:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:56:01.000Z", "max_issues_repo_path": "include/osmium_utils/bg_factory.hpp", "max_issues_repo_name": "fhamonic/osm2geojson", "max_issues_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "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/osmium_utils/bg_factory.hpp", "max_forks_repo_name": "fhamonic/osm2geojson", "max_forks_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "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.5502183406, "max_line_length": 155, "alphanum_fraction": 0.557435628, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.18807783643814138}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  Aggregate SIMD numerical and type limits for ARM NEON\n\n  @copyright 2012 - 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_ARCH_ARM_NEON_LIMITS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_ARM_NEON_LIMITS_HPP_INCLUDED\n\n#include <boost/simd/arch/arm/tags.hpp>\n#include <boost/simd/arch/common/limits.hpp>\n#include <boost/dispatch/meta/make_integer.hpp>\n\nnamespace boost { namespace simd\n{\n  template<> struct limits<boost::simd::neon_>\n  {\n    using parent = boost::simd::neon64_;\n\n    struct largest_integer\n    {\n      template<typename Sign> struct apply : boost::dispatch::make_integer<8,Sign> {};\n    };\n\n    struct smallest_integer\n    {\n      template<typename Sign> struct apply : boost::dispatch::make_integer<1,Sign> {};\n    };\n\n#ifdef __aarch64__\n    using largest_real   = double;\n#else\n    using largest_real   = float;\n#endif\n    using smallest_real  = float;\n\n    enum { bits = 128, bytes = 16 };\n  };\n\n  template<> struct limits<boost::simd::neon64_> : limits<boost::simd::neon_>\n  {\n    using parent = boost::simd::simd_;\n  };\n} }\n\n#endif\n\n", "meta": {"hexsha": "6e31426416d711923cf1cd64710757ffc659a192", "size": 1402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/arm/neon/limits.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/arm/neon/limits.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/arm/neon/limits.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": 25.4909090909, "max_line_length": 100, "alphanum_fraction": 0.5998573466, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.18807783274760834}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <random>\n#include <chrono>\n#include <functional>\n#include <cctype>\n#include <locale>\n#include <algorithm>\n#include <regex>\n#include <iterator>\n#include <vector>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include \"perceptron.h\"\n#include \"segmentor.h\"\n#include \"featurizer.h\"\n#include \"naivebayes.h\"\n#include \"util.h\"\n\nusing namespace std;\n\n\nint main() {\n    int THRESHOLD = 6;\n\n    NBUnigramBOW* nb = new NBUnigramBOW();\n\n    ifstream is(\"naivebayes.dat\", ios::binary);\n    boost::archive::binary_iarchive nb_ar(is);\n    nb_ar >> nb;\n\n    AveragedPerceptron* perceptron = new AveragedPerceptron();\n    Featurizer* feat = new Featurizer();\n    map<string, int> index_table;\n    feat->index_table = index_table;\n\n    ifstream feature_is(\"feature_index.dat\", ios::binary);\n    boost::archive::binary_iarchive feature_ar(feature_is);\n    feature_ar >> feat;\n\n    ifstream perceptron_is(\"perceptron.dat\", ios::binary);\n    boost::archive::binary_iarchive perceptron_ar(perceptron_is);\n    perceptron_ar >> perceptron;\n\n    Segmentor* seg = new Segmentor(perceptron, feat);\n\n    ifstream test_query (\"../data/test1.qry\");\n\n    vector<string> test_texts;\n\n    string line;\n    if (test_query.is_open()) {\n        while (getline(test_query, line)) {\n            transform(line.begin(), line.end(), line.begin(), ::tolower);\n            line = trim(line);\n\n            if (line.empty()) {\n                continue;\n            }\n\n            test_texts.push_back(line);\n        }\n    }\n\n    ofstream prediction_file (\"../prediction/nb_ap_ensemble.txt\");\n\n    for (auto x: test_texts) {\n        vector<string> prediction = nb->predict(x);\n        double loglikelihood = nb->fitness(prediction);\n\n        // bigram correction\n        vector<string> correction;\n        for (auto word: prediction) {\n            vector<vector<string>> splits = nb->split_pairs(word);\n\n            bool corrected = false;\n            for (auto pair: splits) {\n                vector<string> ngram;\n                ngram.push_back(pair[0]);\n                ngram.push_back(pair[1]);\n\n                // this will not search the entire space\n                // will pick bi-gram greedily\n                auto it = nb->bigram.find(ngram);\n                if (it != nb->bigram.end()) {\n                    if (it->second > THRESHOLD) {\n                        // this bigram has to show up plenty of times\n                        if ((pair[1].size() != 1) && (pair[1].size() != 2)) {\n                            // will ignore single/double characters since they are usually a word\n                            // segmented because they contain apostrophes\n                            correction.push_back(pair[0]);\n                            correction.push_back(pair[1]);\n                            corrected = true;\n                            break;\n                        }\n                    }\n                }\n            }\n            if (not corrected) {\n                correction.push_back(word);\n            }\n        }\n\n        // Averaged Perceptron to the rescue!\n        // It's better off to resort to averaged perceptron when dealing with non-words\n        bool is_equal = false;\n        if (prediction.size() < correction.size()) {\n            is_equal = std::equal ( prediction.begin(), prediction.end(), correction.begin() );\n        }\n        else {\n            is_equal = std::equal ( correction.begin(), correction.end(), prediction.begin() );\n        }\n\n        if (is_equal) {\n            // reaching here means no correction was made\n            if (prediction.size() == 2 && loglikelihood < -10.0) {\n                // if the final prediction was a single word\n                // it is quite likely that this word a english non-word\n                // but it might still be segmented\n                // fallback to averaged perceptron\n                correction.clear();\n                vector<int> ap_prediction = seg->predict(prediction[0]);\n                stringstream ss;\n                for (int i = 0; i < ap_prediction.size(); ++i) {\n                    ss << prediction[0][i];\n                    if (ap_prediction[i] == 1) {\n                        correction.push_back(ss.str());\n                        ss.str(\"\");\n                        ss.clear();\n                    }\n                }\n                if (not ss.str().empty()) {\n                    correction.push_back(ss.str());\n                    ss.str(\"\");\n                    ss.clear();\n                }\n            }\n\n        }\n\n        bool anomaly_detected = false;\n        for (auto word: prediction) {\n            // handle single character anomalies\n            // only single character that appears many times\n            // so that it will affect the result is 'a'\n            if (word.size() == 1 && word[0] != 'a') {\n                anomaly_detected = true;\n            }\n        }\n\n        if (anomaly_detected) {\n            // fallback to averaged perceptron\n            correction.clear();\n\n            vector<int> ap_prediction = seg->predict(x);\n            stringstream ss;\n            for (int i = 0; i < ap_prediction.size(); ++i) {\n                ss << x[i];\n                if (ap_prediction[i] == 1) {\n                    correction.push_back(ss.str());\n                    ss.str(\"\");\n                    ss.clear();\n                }\n            }\n            if (not ss.str().empty()) {\n                correction.push_back(ss.str());\n                ss.str(\"\");\n                ss.clear();\n            }\n        }\n\n        // if (prediction.size() > 5 && loglikelihood < -50.0) {\n        //     for (auto w: prediction) {\n        //         cout << w << \" \";\n        //     }\n        //     cout << loglikelihood << endl;\n        //     // correction.clear();\n        //     // vector<int> ap_prediction = seg->predict(x);\n        //     // stringstream ss;\n        //     // for (int i = 0; i < ap_prediction.size(); ++i) {\n        //     //     ss << x[i];\n        //     //     if (ap_prediction[i] == 1) {\n        //     //         correction.push_back(ss.str());\n        //     //         ss.str(\"\");\n        //     //         ss.clear();\n        //     //     }\n        //     // }\n        //     // if (not ss.str().empty()) {\n        //     //     correction.push_back(ss.str());\n        //     //     ss.str(\"\");\n        //     //     ss.clear();\n        //     // }\n        // }\n\n\n\n\n\n\n        stringstream ss;\n        for (auto word: correction) {\n            ss << word << \" \";\n        }\n        string result = ss.str();\n\n        prediction_file << trim(result) << endl;\n        ss.str(\"\");\n        ss.clear();\n    }\n\n    return 0;\n};\n", "meta": {"hexsha": "80b7f935b49b7a31d24cbd6209dd1085ff7aea3e", "size": 6867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test.cpp", "max_stars_repo_name": "shurain/codesprint2014r1", "max_stars_repo_head_hexsha": "980b0191e9e90adc54778bdc5dbfbb41538e96f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-12-07T08:13:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-07T08:13:37.000Z", "max_issues_repo_path": "src/test.cpp", "max_issues_repo_name": "shurain/codesprint2014r1", "max_issues_repo_head_hexsha": "980b0191e9e90adc54778bdc5dbfbb41538e96f1", "max_issues_repo_licenses": ["MIT"], "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": "shurain/codesprint2014r1", "max_forks_repo_head_hexsha": "980b0191e9e90adc54778bdc5dbfbb41538e96f1", "max_forks_repo_licenses": ["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.6451612903, "max_line_length": 97, "alphanum_fraction": 0.4831804281, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702254064929194, "lm_q1q2_score": 0.18800485387469568}}
{"text": "// Copyright (c) 2010 Satoshi Nakamoto\n// Copyright (c) 2009-2013 The Bitcoin 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 \"base58.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"net.h\"\n#include \"netbase.h\"\n#include \"rpcserver.h\"\n#include \"txdb.h\"\n#include \"timedata.h\"\n#include \"util.h\"\n#ifdef ENABLE_WALLET\n#include \"wallet.h\"\n#include \"walletdb.h\"\n#endif\n\n#include <stdint.h>\n\n#include <boost/assign/list_of.hpp>\n#include \"json/json_spirit_utils.h\"\n#include \"json/json_spirit_value.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace json_spirit;\n\nValue getinfo(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 0)\n        throw runtime_error(\n            \"getinfo\\n\"\n            \"Returns an object containing various state info.\");\n\n    proxyType proxy;\n    GetProxy(NET_IPV4, proxy);\n\n    Object obj, diff;\n    obj.push_back(Pair(\"version\",       FormatFullVersion()));\n    obj.push_back(Pair(\"protocolversion\",(int)PROTOCOL_VERSION));\n#ifdef ENABLE_WALLET\n    if (pwalletMain) {\n        obj.push_back(Pair(\"walletversion\", pwalletMain->GetVersion()));\n        obj.push_back(Pair(\"balance\",       ValueFromAmount(pwalletMain->GetBalance())));\n        obj.push_back(Pair(\"newmint\",       ValueFromAmount(pwalletMain->GetNewMint())));\n        obj.push_back(Pair(\"stake\",         ValueFromAmount(pwalletMain->GetStake())));\n    }\n#endif\n    obj.push_back(Pair(\"blocks\",        (int)nBestHeight));\n    obj.push_back(Pair(\"timeoffset\",    (int64_t)GetTimeOffset()));\n    obj.push_back(Pair(\"moneysupply\",   ValueFromAmount(pindexBest->nMoneySupply)));\n    obj.push_back(Pair(\"digsupply\",     ValueFromAmount(pindexBest->nDigsupply)));\n    obj.push_back(Pair(\"stakesupply\",   ValueFromAmount(pindexBest->nStakeSupply)));\n    obj.push_back(Pair(\"activesupply\",  ValueFromAmount(pindexBest->nDigsupply + pindexBest->nStakeSupply)));\n    obj.push_back(Pair(\"connections\",   (int)vNodes.size()));\n    obj.push_back(Pair(\"proxy\",         (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));\n    obj.push_back(Pair(\"ip\",            GetLocalAddress(NULL).ToStringIP()));\n\n    diff.push_back(Pair(\"proof-of-stake\", GetDifficulty(GetLastBlockIndex(pindexBest, true))));\n    obj.push_back(Pair(\"difficulty\",    diff));\n\n    obj.push_back(Pair(\"testnet\",       TestNet()));\n#ifdef ENABLE_WALLET\n    if (pwalletMain) {\n        obj.push_back(Pair(\"keypoololdest\", (int64_t)pwalletMain->GetOldestKeyPoolTime()));\n        obj.push_back(Pair(\"keypoolsize\",   (int)pwalletMain->GetKeyPoolSize()));\n    }\n    obj.push_back(Pair(\"paytxfee\",      ValueFromAmount(nTransactionFee)));\n    obj.push_back(Pair(\"mininput\",      ValueFromAmount(nMinimumInputValue)));\n    if (pwalletMain && pwalletMain->IsCrypted())\n        obj.push_back(Pair(\"unlocked_until\", (int64_t)nWalletUnlockTime));\n#endif\n    obj.push_back(Pair(\"errors\",        GetWarnings(\"statusbar\")));\n    return obj;\n}\n\n#ifdef ENABLE_WALLET\nclass DescribeAddressVisitor : public boost::static_visitor<Object>\n{\npublic:\n    Object operator()(const CNoDestination &dest) const { return Object(); }\n\n    Object operator()(const CKeyID &keyID) const {\n        Object obj;\n        CPubKey vchPubKey;\n        pwalletMain->GetPubKey(keyID, vchPubKey);\n        obj.push_back(Pair(\"isscript\", false));\n        obj.push_back(Pair(\"pubkey\", HexStr(vchPubKey)));\n        obj.push_back(Pair(\"iscompressed\", vchPubKey.IsCompressed()));\n        return obj;\n    }\n\n    Object operator()(const CScriptID &scriptID) const {\n        Object obj;\n        obj.push_back(Pair(\"isscript\", true));\n        CScript subscript;\n        pwalletMain->GetCScript(scriptID, subscript);\n        std::vector<CTxDestination> addresses;\n        txnouttype whichType;\n        int nRequired;\n        ExtractDestinations(subscript, whichType, addresses, nRequired);\n        obj.push_back(Pair(\"script\", GetTxnOutputType(whichType)));\n        obj.push_back(Pair(\"hex\", HexStr(subscript.begin(), subscript.end())));\n        Array a;\n        BOOST_FOREACH(const CTxDestination& addr, addresses)\n            a.push_back(CBitcoinAddress(addr).ToString());\n        obj.push_back(Pair(\"addresses\", a));\n        if (whichType == TX_MULTISIG)\n            obj.push_back(Pair(\"sigsrequired\", nRequired));\n        return obj;\n    }\n};\n#endif\n\nValue validateaddress(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"validateaddress <Clamaddress>\\n\"\n            \"Return information about <Clamaddress>.\");\n\n    CBitcoinAddress address(params[0].get_str());\n    bool isValid = address.IsValid();\n\n    Object ret;\n    ret.push_back(Pair(\"isvalid\", isValid));\n    if (isValid)\n    {\n        CTxDestination dest = address.Get();\n        string currentAddress = address.ToString();\n        ret.push_back(Pair(\"address\", currentAddress));\n#ifdef ENABLE_WALLET\n        bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;\n        ret.push_back(Pair(\"ismine\", fMine));\n        if (fMine) {\n            Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);\n            ret.insert(ret.end(), detail.begin(), detail.end());\n        }\n        if (pwalletMain && pwalletMain->mapAddressBook.count(dest))\n            ret.push_back(Pair(\"account\", pwalletMain->mapAddressBook[dest]));\n#endif\n    }\n    return ret;\n}\n\n\nstatic void validateoutputs_check_unconfirmed_spend(COutPoint& outpoint, CTransaction& tx, Object& entry)\n{\n    // check whether unconfirmed output is already spent\n    LOCK(mempool.cs); // protect mempool.mapNextTx\n    if (mempool.mapNextTx.count(outpoint)) {\n        // pull details from mempool\n        CInPoint in = mempool.mapNextTx[outpoint];\n        Object details;\n        entry.push_back(Pair(\"status\", \"spent\"));\n        details.push_back(Pair(\"txid\", in.ptx->GetHash().GetHex()));\n        details.push_back(Pair(\"vin\", int(in.n)));\n        details.push_back(Pair(\"confirmations\", 0));\n        entry.push_back(Pair(\"spent\", details));\n    } else {\n        entry.push_back(Pair(\"status\", \"unspent\"));\n\n        const CScript& pk = tx.vout[outpoint.n].scriptPubKey;\n        entry.push_back(Pair(\"scriptPubKey\", HexStr(pk.begin(), pk.end())));\n    }\n}\n\nValue validateoutputs(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"validateoutputs [{\\\"txid\\\":txid,\\\"vout\\\":n},...]\\n\"\n            \"Return information about outputs (whether they exist, and whether they have been spent).\");\n\n    Array inputs = params[0].get_array();\n\n    CTxDB txdb(\"r\");\n    CTxIndex txindex;\n    Array ret;\n\n    BOOST_FOREACH(Value& input, inputs)\n    {\n        const Object& o = input.get_obj();\n\n        const Value& txid_v = find_value(o, \"txid\");\n        if (txid_v.type() != str_type)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, missing txid key\");\n        string txid = txid_v.get_str();\n        if (!IsHex(txid))\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, expected hex txid\");\n\n        const Value& vout_v = find_value(o, \"vout\");\n        if (vout_v.type() != int_type)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, missing vout key\");\n        int nOutput = vout_v.get_int();\n        if (nOutput < 0)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, vout must be positive\");\n\n        Object entry;\n        entry.push_back(Pair(\"txid\", txid));\n        entry.push_back(Pair(\"vout\", nOutput));\n\n        CTransaction tx;\n        uint256 hashBlock = 0;\n        CTxIndex txindex;\n        COutPoint outpoint(uint256(txid), nOutput);\n\n        // find the output\n        if (!GetTransaction(uint256(txid), tx, hashBlock, txindex)) {\n            entry.push_back(Pair(\"status\", \"txid not found\"));\n            ret.push_back(entry);\n            continue;\n        }\n\n        // check that the output number is in range\n        if ((unsigned)nOutput >= tx.vout.size()) {\n            entry.push_back(Pair(\"status\", \"vout too high\"));\n            entry.push_back(Pair(\"outputs\", (int)tx.vout.size()));\n            ret.push_back(entry);\n            continue;\n        }\n\n        entry.push_back(Pair(\"amount\", ValueFromAmount(tx.vout[nOutput].nValue)));\n\n        // get the address and account\n        CTxDestination address;\n        if (ExtractDestination(tx.vout[nOutput].scriptPubKey, address))\n        {\n            entry.push_back(Pair(\"address\", CBitcoinAddress(address).ToString()));\n            if (pwalletMain->mapAddressBook.count(address))\n                entry.push_back(Pair(\"account\", pwalletMain->mapAddressBook[address]));\n        }\n\n        // is the output confirmed?\n        if (hashBlock == 0) {\n            entry.push_back(Pair(\"confirmations\", 0));\n            validateoutputs_check_unconfirmed_spend(outpoint, tx, entry);\n            ret.push_back(entry);\n            continue;\n        }\n\n        // find the block containing the output\n        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);\n        if (mi != mapBlockIndex.end() && (*mi).second)\n        {\n            CBlockIndex* pindex = (*mi).second;\n            if (pindex->IsInMainChain()) {\n                entry.push_back(Pair(\"height\", pindex->nHeight));\n                entry.push_back(Pair(\"confirmations\", 1 + nBestHeight - pindex->nHeight));\n            } else {\n                LogPrintf(\"can't find block with hash %s\\n\", hashBlock.GetHex().c_str());\n                entry.push_back(Pair(\"confirmations\", 0));\n            }\n        }\n\n        // check whether any confirmed transaction spends this output\n        if (txindex.vSpent[nOutput].IsNull()) {\n            // if not, check for an unconfirmed spend\n            validateoutputs_check_unconfirmed_spend(outpoint, tx, entry);\n            ret.push_back(entry);\n            continue;\n        }\n\n        entry.push_back(Pair(\"status\", \"spent\"));\n\n        Object details;\n        CTransaction spending_tx;\n\n        // load the transaction that spends this output\n        spending_tx.ReadFromDisk(txindex.vSpent[nOutput]);\n\n        details.push_back(Pair(\"txid\", spending_tx.GetHash().GetHex()));\n\n        // find this output's input number in the spending transaction\n        int n = 0;\n        BOOST_FOREACH(CTxIn input, spending_tx.vin) {\n            if (input.prevout == outpoint) {\n                details.push_back(Pair(\"vin\", n));\n                break;\n            }\n            n++;\n        }\n\n        // get the spending transaction\n        if (GetTransaction(uint256(spending_tx.GetHash()), tx, hashBlock, txindex) && hashBlock != 0) {\n            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);\n            if (mi != mapBlockIndex.end() && (*mi).second)\n            {\n                CBlockIndex* pindex = (*mi).second;\n                if (pindex->IsInMainChain()) {\n                    details.push_back(Pair(\"height\", pindex->nHeight));\n                    details.push_back(Pair(\"confirmations\", 1 + nBestHeight - pindex->nHeight));\n                } else {\n                    LogPrintf(\"can't find block with hash %s\\n\", hashBlock.GetHex().c_str());\n                    details.push_back(Pair(\"confirmations\", 0));\n                }\n            }\n        }\n\n        entry.push_back(Pair(\"spent\", details));\n        ret.push_back(entry);\n    }\n\n    return ret;\n}\n\n\nValue validatepubkey(const Array& params, bool fHelp)\n{\n    if (fHelp || !params.size() || params.size() > 2)\n        throw runtime_error(\n            \"validatepubkey <Clampubkey>\\n\"\n            \"Return information about <Clampubkey>.\");\n\n    std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());\n    CPubKey pubKey(vchPubKey);\n\n    bool isValid = pubKey.IsValid();\n    bool isCompressed = pubKey.IsCompressed();\n    CKeyID keyID = pubKey.GetID();\n\n    CBitcoinAddress address;\n    address.Set(keyID);\n\n    Object ret;\n    ret.push_back(Pair(\"isvalid\", isValid));\n    if (isValid)\n    {\n        CTxDestination dest = address.Get();\n        string currentAddress = address.ToString();\n        ret.push_back(Pair(\"address\", currentAddress));\n        ret.push_back(Pair(\"iscompressed\", isCompressed));\n#ifdef ENABLE_WALLET\n        bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;\n        ret.push_back(Pair(\"ismine\", fMine));\n        if (fMine) {\n            Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);\n            ret.insert(ret.end(), detail.begin(), detail.end());\n        }\n        if (pwalletMain && pwalletMain->mapAddressBook.count(dest))\n            ret.push_back(Pair(\"account\", pwalletMain->mapAddressBook[dest]));\n#endif\n    }\n    return ret;\n}\n\nValue verifymessage(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 3)\n        throw runtime_error(\n            \"verifymessage <Clamaddress> <signature> <message>\\n\"\n            \"Verify a signed message\");\n\n    string strAddress  = params[0].get_str();\n    string strSign     = params[1].get_str();\n    string strMessage  = params[2].get_str();\n\n    CBitcoinAddress addr(strAddress);\n    if (!addr.IsValid())\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid address\");\n\n    CKeyID keyID;\n    if (!addr.GetKeyID(keyID))\n        throw JSONRPCError(RPC_TYPE_ERROR, \"Address does not refer to key\");\n\n    bool fInvalid = false;\n    vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);\n\n    if (fInvalid)\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Malformed base64 encoding\");\n\n    CHashWriter ss(SER_GETHASH, 0);\n    ss << strMessageMagic;\n    ss << strMessage;\n\n    CPubKey pubkey;\n    if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))\n        return false;\n\n    return (pubkey.GetID() == keyID);\n}\n\nValue setspeech(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"setspeech <text>\\n\"\n            \"Sets the text to be used as the transaction comment when staking or making other transactions.\");\n\n    strDefaultSpeech = params[0].get_str();\n\n    LogPrint(\"speech\", \"set default speech to \\\"%s\\\"\\n\", strDefaultSpeech);\n\n    return Value::null;\n}\n", "meta": {"hexsha": "d9ecc7b3e38e852467d72c669880cec6773ee484", "size": 14271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rpcmisc.cpp", "max_stars_repo_name": "coinkeeper/2015-06-22_18-55_clams", "max_stars_repo_head_hexsha": "f5575011523bf710d73f748d43f07a4214005374", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-06T22:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-06T22:33:13.000Z", "max_issues_repo_path": "src/rpcmisc.cpp", "max_issues_repo_name": "coinkeeper/2015-06-22_18-55_clams", "max_issues_repo_head_hexsha": "f5575011523bf710d73f748d43f07a4214005374", "max_issues_repo_licenses": ["MIT"], "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/rpcmisc.cpp", "max_forks_repo_name": "coinkeeper/2015-06-22_18-55_clams", "max_forks_repo_head_hexsha": "f5575011523bf710d73f748d43f07a4214005374", "max_forks_repo_licenses": ["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.7669172932, "max_line_length": 110, "alphanum_fraction": 0.6259547334, "num_tokens": 3461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.18800485387469565}}
{"text": "// -*- C++ -*-\n//\n// Copyright Sylvain Bougerel 2009 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file COPYING or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_DYN_LINK\n#define SPATIAL_ENABLE_ASSERT // detect interal issues that should not occur\n\n#include <boost/test/unit_test.hpp>\n#include <utility> // std::make_pair\n#include \"../../src/idle_point_multimap.hpp\"\n#include \"spatial_test_types.hpp\"\n\nusing namespace spatial;\n\nBOOST_AUTO_TEST_CASE( test_idle_point_map_constructors )\n{\n  idle_point_multimap<2, int2, int> idle_points;\n  idle_point_multimap<0, int2, int> runtime_idle_points;\n}\n\nBOOST_AUTO_TEST_CASE( test_idle_point_map_copy_assignment )\n{\n  idle_point_multimap<2, int2, int> idle_points;\n  idle_points.insert(std::make_pair(zeros, 0));\n  idle_points.insert(std::make_pair(ones, 1));\n  idle_points.insert(std::make_pair(twos, 2));\n  idle_point_multimap<2, int2, int> copy(idle_points);\n  BOOST_CHECK_EQUAL(idle_points.size(), copy.size());\n  BOOST_CHECK(*idle_points.begin() == *copy.begin());\n  idle_points = copy;\n  BOOST_CHECK_EQUAL(idle_points.size(), copy.size());\n  BOOST_CHECK(*idle_points.begin() == *copy.begin());\n}\n\nBOOST_AUTO_TEST_CASE( test_zero_idle_point_map_copy_assignment )\n{\n  idle_point_multimap<0, int2, int> idle_points;\n  idle_points.insert(std::make_pair(zeros, 0));\n  idle_points.insert(std::make_pair(ones, 1));\n  idle_points.insert(std::make_pair(twos, 2));\n  idle_point_multimap<0, int2, int> copy(idle_points);\n  BOOST_CHECK_EQUAL(idle_points.size(), copy.size());\n  BOOST_CHECK(*idle_points.begin() == *copy.begin());\n  idle_points = copy;\n  BOOST_CHECK_EQUAL(idle_points.size(), copy.size());\n  BOOST_CHECK(*idle_points.begin() == *copy.begin());\n}\n", "meta": {"hexsha": "c05ae73b78b75fabdad6cda8d088f36392050587", "size": 1765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/verify/verify_idle_point_multimap.cpp", "max_stars_repo_name": "Roboauto/spatial", "max_stars_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-12-07T02:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T05:39:05.000Z", "max_issues_repo_path": "tests/verify/verify_idle_point_multimap.cpp", "max_issues_repo_name": "Roboauto/spatial", "max_issues_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-28T15:07:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T15:07:42.000Z", "max_forks_repo_path": "tests/verify/verify_idle_point_multimap.cpp", "max_forks_repo_name": "Roboauto/spatial", "max_forks_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T13:30:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:22:03.000Z", "avg_line_length": 34.6078431373, "max_line_length": 76, "alphanum_fraction": 0.7473087819, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.18800485387469562}}
{"text": "#ifndef DQN_HPP_\n#define DQN_HPP_\n\n#include <memory>\n#include <random>\n#include <tuple>\n#include <unordered_map>\n#include <vector>\n#include <HFO.hpp>\n#include <caffe/caffe.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/optional.hpp>\n#include <mutex>\n#include \"hfo_game.hpp\"\n\nnamespace dqn {\n\nconstexpr auto kStateInputCount = 1;\nconstexpr auto kMinibatchSize = 32;\nconstexpr auto kActionSize = 4;\nconstexpr auto kActionParamSize = 6;\n\nconstexpr auto kActionInputDataSize = kMinibatchSize * kActionSize;\nconstexpr auto kActionParamsInputDataSize = kMinibatchSize * kActionParamSize;\nconstexpr auto kTargetInputDataSize = kMinibatchSize * kActionSize;\nconstexpr auto kFilterInputDataSize = kMinibatchSize * kActionSize;\n\nusing ActorOutput = std::array<float, kActionSize + kActionParamSize>;\nusing StateData   = std::vector<float>;\nusing StateDataSp = std::shared_ptr<StateData>;\nusing InputStates = std::array<StateDataSp, kStateInputCount>;\nusing Transition  = std::tuple<InputStates, ActorOutput, float,\n                               float, boost::optional<StateDataSp>>;\nusing SolverSp    = std::shared_ptr<caffe::Solver<float>>;\nusing NetSp       = boost::shared_ptr<caffe::Net<float>>;\n\n// Layer Names\nconstexpr auto state_input_layer_name         = \"state_input_layer\";\nconstexpr auto action_input_layer_name        = \"action_input_layer\";\nconstexpr auto action_params_input_layer_name = \"action_params_input_layer\";\nconstexpr auto target_input_layer_name        = \"target_input_layer\";\nconstexpr auto filter_input_layer_name        = \"filter_input_layer\";\nconstexpr auto q_values_layer_name            = \"q_values_layer\";\n// Blob names\nconstexpr auto states_blob_name        = \"states\";\nconstexpr auto actions_blob_name       = \"actions\";\nconstexpr auto action_params_blob_name = \"action_params\";\nconstexpr auto targets_blob_name       = \"target\";\nconstexpr auto filter_blob_name        = \"filter\";\nconstexpr auto q_values_blob_name      = \"q_values\";\nconstexpr auto loss_blob_name          = \"loss\";\n\n/**\n * Deep Q-Network\n */\nclass DQN {\npublic:\n  DQN(caffe::SolverParameter& actor_solver_param,\n      caffe::SolverParameter& critic_solver_param,\n      std::string save_path, int state_size, int tid);\n  ~DQN();\n\n  // Benchmark the speed of updates\n  void Benchmark(int iterations=1000);\n\n  // Loading methods\n  void RestoreActorSolver(const std::string& actor_solver);\n  void RestoreCriticSolver(const std::string& critic_solver);\n  void LoadActorWeights(const std::string& actor_model_file);\n  void LoadCriticWeights(const std::string& critic_weights);\n  void LoadReplayMemory(const std::string& filename);\n\n  // Snapshot the model/solver/replay memory. Produces files:\n  // snapshot_prefix_iter_N.[caffemodel|solverstate|replaymem]. Optionally\n  // removes snapshots with same prefix but lower iteration.\n  void Snapshot();\n  void Snapshot(const std::string& snapshot_prefix, bool remove_old=false,\n                bool snapshot_memory=true);\n\n  ActorOutput GetRandomActorOutput();\n\n  // Select an action using epsilon-greedy action selection.\n  ActorOutput SelectAction(const InputStates& input_states, double epsilon);\n\n  // Select a batch of actions using epsilon-greedy action selection.\n  std::vector<ActorOutput> SelectActions(const std::vector<InputStates>& states_batch,\n                                         double epsilon);\n\n  // Converts an ActorOutput into an action by samping over discrete actions\n  Action SampleAction(const ActorOutput& actor_output);\n\n  // Evaluate a state-action, returning the q-value.\n  float EvaluateAction(const InputStates& input_states, const ActorOutput& action);\n\n  // Add a transition to replay memory\n  void AddTransition(const Transition& transition);\n  void AddTransitions(const std::vector<Transition>& transitions);\n\n  // Computes a tabular Q-Value for each transition\n  void LabelTransitions(std::vector<Transition>& transitions);\n\n  // Update the model(s)\n  void Update();\n\n  // Clear the replay memory\n  void ClearReplayMemory() { replay_memory_->clear(); }\n\n  // Save the replay memory to a gzipped compressed file\n  void SnapshotReplayMemory(const std::string& filename);\n\n  // Get the current size of the replay memory\n  int memory_size() const { return replay_memory_->size(); }\n\n  // Share the parameters in a layer. Owner keeps the params, slave loses them\n  void ShareLayer(caffe::Layer<float>& param_owner,\n                  caffe::Layer<float>& param_slave);\n\n  // Share parameters between DQNs\n  void ShareParameters(DQN& other,\n                       int num_actor_layers_to_share,\n                       int num_critic_layers_to_share);\n\n  // Free's the replay memory of other, which now points to our own replay mem\n  void ShareReplayMemory(DQN& other);\n\n  // Return the current iteration of the solvers\n  int min_iter() const { return std::min(actor_iter(), critic_iter()); }\n  int max_iter() const { return std::max(actor_iter(), critic_iter()); }\n  int critic_iter() const { return critic_solver_->iter(); }\n  int actor_iter() const { return actor_solver_->iter(); }\n  int state_size() const { return state_size_; }\n  const std::string& save_path() const { return save_path_; }\n  int unum() const { return unum_; }\n  void set_unum(int unum) { unum_ = unum; }\n\nprotected:\n  // Initialize DQN. Called by the constructor\n  void Initialize();\n\n  // Update both the actor and critic.\n  std::pair<float, float> UpdateActorCritic();\n\n  // Randomly sample the replay memory n-times, returning transition indexes\n  std::vector<int> SampleTransitionsFromMemory(int n);\n  // Randomly sample the replay memory n-times returning input_states\n  std::vector<InputStates> SampleStatesFromMemory(int n);\n\n  // Clone the network and store the result in clone_net_\n  void CloneNet(NetSp& net_from, NetSp& net_to);\n  // Update the parameters of net_to towards net_from.\n  // net_to = tau * net_from + (1 - tau) * net_to\n  void SoftUpdateNet(NetSp& net_from, NetSp& net_to, float tau);\n\n  // Given input states, use the actor network to select an action.\n  ActorOutput SelectActionGreedily(caffe::Net<float>& actor,\n                                   const InputStates& last_states);\n\n  // Given a batch of input states, return a batch of selected actions.\n  std::vector<ActorOutput> SelectActionGreedily(\n      caffe::Net<float>& actor,\n      const std::vector<InputStates>& states_batch);\n\n  // Runs forward on critic to produce q-values. Actions inferred by actor.\n  std::vector<float> CriticForwardThroughActor(\n      caffe::Net<float>& critic, caffe::Net<float>& actor,\n      const std::vector<InputStates>& states_batch);\n\n  // Runs forward on critic to produce q-values.\n  std::vector<float> CriticForward(caffe::Net<float>& critic,\n                                   const std::vector<InputStates>& states_batch,\n                                   const std::vector<ActorOutput>& action_batch);\n\n  // Input data into the State/Target/Filter layers of the given\n  // net. This must be done before forward is called.\n  void InputDataIntoLayers(caffe::Net<float>& net,\n                           float* states_input,\n                           float* actions_input,\n                           float* action_params_input,\n                           float* target_input,\n                           float* filter_input);\n\nprotected:\n  caffe::SolverParameter actor_solver_param_;\n  caffe::SolverParameter critic_solver_param_;\n  const int replay_memory_capacity_;\n  const double gamma_;\n  std::shared_ptr<std::deque<Transition> > replay_memory_;\n  SolverSp actor_solver_;\n  NetSp actor_net_; // The actor network used for continuous action evaluation.\n  SolverSp critic_solver_;\n  NetSp critic_net_;  // The critic network used for giving q-value of a continuous action;\n  NetSp critic_target_net_; // Clone of critic net. Used to generate targets.\n  NetSp actor_target_net_; // Clone of the actor net. Used to generate targets.\n  std::mt19937 random_engine;\n  float smoothed_critic_loss_, smoothed_actor_loss_;\n  int last_snapshot_iter_;\n  std::string save_path_;\n  const int state_size_; // Number of state features\n  const int state_input_data_size_;\n  int tid_;\n  int unum_;\n};\n\ncaffe::NetParameter CreateActorNet(int state_size);\ncaffe::NetParameter CreateCriticNet(int state_size);\n\n/**\n * Converts an ActorOutput into an action by maxing over discrete actions\n */\nAction GetAction(const ActorOutput& actor_output);\n\n/**\n * Returns a vector of filenames matching a given regular expression.\n */\nstd::vector<std::string> FilesMatchingRegexp(const std::string& regexp);\n\n// Removes all files matching a given regular expression\nvoid RemoveFilesMatchingRegexp(const std::string& regexp);\n\n/**\n * Removes snapshots matching regexp that have an iteration less than\n * min_iter.\n */\nvoid RemoveSnapshots(const std::string& regexp, int min_iter);\n\n/**\n * Look for the latest snapshot to resume from. Returns a string\n * containing the path to the .solverstate. Returns empty string if\n * none is found. Will only return if the snapshot contains all of:\n * .solverstate,.caffemodel,.replaymemory\n */\nvoid FindLatestSnapshot(const std::string& snapshot_prefix,\n                        std::string& actor_snapshot,\n                        std::string& critic_snapshot,\n                        std::string& memory_snapshot);\n\n/**\n * Look for the best HiScore matching the given snapshot prefix\n */\nint FindHiScore(const std::string& snapshot_prefix);\n\nstd::string PrintActorOutput(const ActorOutput& actor_output);\n\n} // namespace dqn\n\n#endif /* DQN_HPP_ */\n", "meta": {"hexsha": "7d85496425b0ed962616be0acfd545248cacc2ee", "size": 9527, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dqn.hpp", "max_stars_repo_name": "naderzare/dqn-hfo", "max_stars_repo_head_hexsha": "c7b0a73de07078e248015d44573d8dcadd6fb8d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-10-14T23:17:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T11:55:43.000Z", "max_issues_repo_path": "src/dqn.hpp", "max_issues_repo_name": "naderzare/dqn-hfo", "max_issues_repo_head_hexsha": "c7b0a73de07078e248015d44573d8dcadd6fb8d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2015-04-29T15:39:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-03T09:21:51.000Z", "max_forks_repo_path": "src/dqn.hpp", "max_forks_repo_name": "naderzare/dqn-hfo", "max_forks_repo_head_hexsha": "c7b0a73de07078e248015d44573d8dcadd6fb8d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-04-23T15:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T01:45:19.000Z", "avg_line_length": 38.5708502024, "max_line_length": 91, "alphanum_fraction": 0.7207935342, "num_tokens": 2113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.18800485387469562}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Timo Sachsenberg $\n// $Authors: Timo Sachsenberg $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/KERNEL/StandardTypes.h>\n#include <OpenMS/FORMAT/MzMLFile.h>\n#include <OpenMS/CONCEPT/Constants.h>\n#include <OpenMS/APPLICATIONS/TOPPBase.h>\n#include <OpenMS/CHEMISTRY/ModificationsDB.h>\n#include <OpenMS/DATASTRUCTURES/Param.h>\n#include <OpenMS/FORMAT/FeatureXMLFile.h>\n#include <OpenMS/FORMAT/FASTAFile.h>\n#include <OpenMS/CHEMISTRY/Element.h>\n#include <OpenMS/CHEMISTRY/ElementDB.h>\n#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>\n#include <OpenMS/MATH/MISC/BilinearInterpolation.h>\n#include <OpenMS/TRANSFORMATIONS/RAW2PEAK/PeakPickerHiRes.h>\n#include <OpenMS/MATH/MISC/NonNegativeLeastSquaresSolver.h>\n#include <OpenMS/FORMAT/SVOutStream.h>\n#include <OpenMS/FORMAT/TextFile.h>\n#include <OpenMS/FILTERING/TRANSFORMERS/Normalizer.h>\n#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/GaussModel.h>\n#include <OpenMS/COMPARISON/SPECTRA/SpectrumAlignment.h>\n#include <OpenMS/FILTERING/TRANSFORMERS/ThresholdMower.h>\n#include <OpenMS/MATH/MISC/CubicSpline2d.h>\n#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/MassDecomposition.h>\n#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/MassDecompositionAlgorithm.h>\n\n#include <boost/math/distributions/normal.hpp>\n\n#include <QtCore/QStringList>\n#include <QtCore/QFile>\n#include <QtCore/QDir>\n#include <QtCore/QFileInfo>\n#include <QtCore/QProcess>\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <map>\n\n#include <math.h>\n\nusing namespace OpenMS;\nusing namespace std;\nusing boost::math::normal;\n\ntypedef map<double, double> MapRateToScoreType;\ntypedef pair<double, vector<double> > IsotopePattern;\ntypedef vector<IsotopePattern> IsotopePatterns;\n\nstruct RateScorePair\n{\n  double rate;\n  double score;\n};\n\n/// datastructure for reporting an incorporation event\nstruct SIPIncorporation\n{\n  double rate; ///< rate\n\n  double correlation; ///< correlation coefficient\n\n  double abundance; ///< abundance of isotopologue\n\n  PeakSpectrum theoretical; ///< peak spectrum as generated from the theoretical isotopic distribution\n};\n\n/// datastructure for reporting a peptide with one or more incorporation rates\nstruct SIPPeptide\n{\n  AASequence sequence; ///< sequence of the peptide\n\n  vector<String> accessions; ///< protein accessions of the peptide\n\n  bool unique; ///< if the peptide is unique and therefor identifies the protein umambigously\n\n  double mz_theo; ///< theoretical mz\n\n  double mass_theo; ///< uncharged theoretical mass\n\n  double score; ///< search engine score or q-value if fdr filtering is applied\n\n  double feature_rt; ///< measurement time of feature apex [s]\n\n  double feature_mz; ///< mz of feature apex [s]\n\n  //Size feature_scan_number; ///< scan number\n\n  Int charge; ///< charge of the peptide feature\n\n  double mass_diff; // 13C or 15N mass difference\n\n  double global_LR; ///< labeling ratio for the whole spectrum used to detect global drifts. 13C/(12C+13C) intensities. (15N analogous)\n\n  vector<RateScorePair> correlation_maxima;\n\n  MapRateToScoreType decomposition_map; // all rate to decomposition scores for the peptide\n\n  MapRateToScoreType correlation_map; // all rate to correlation scores for the peptide\n\n  double RR; ///< R squared of NNLS fit\n\n  double explained_TIC_fraction; ///< fraction of the MS2 TIC that is explained by the maximum correlating decomposition weights\n\n  String feature_type; ///< used to distinguish features from FeatureFinder, or synthetised from ids or averagine ids in reporting\n\n  Size non_zero_decomposition_coefficients; ///< decomposition coefficients significantly larger than 0\n\n  PeakSpectrum reconstruction; ///< signal reconstruction (debugging)\n\n  vector<double> reconstruction_monoistopic; ///< signal reconstruction of natural peptide (at mono-isotopic peak)\n\n  PeakSpectrum accumulated;\n\n  vector<SIPIncorporation> incorporations;\n\n  IsotopePatterns patterns;\n\n  vector<PeakSpectrum> pattern_spectra;\n};\n\n///< comparator for vectors of SIPPeptides based on their size. Used to sort by group size.\nstruct SizeLess :\n  public std::binary_function<vector<SIPPeptide>, vector<SIPPeptide>, bool>\n{\n  inline bool operator()(const vector<SIPPeptide>& a, const vector<SIPPeptide>& b) const\n  {\n    return a.size() < b.size();\n  }\n\n};\n\nstruct SequenceLess :\n  public std::binary_function<pair<SIPPeptide, Size>, pair<SIPPeptide, Size>, bool>\n{\n  inline bool operator()(const pair<SIPPeptide, Size>& a, const pair<SIPPeptide, Size>& b) const\n  {\n    return a.first.sequence.toString() < b.first.sequence.toString();\n  }\n\n};\n\nstruct RIALess :\n  public std::binary_function<SIPIncorporation, SIPIncorporation, bool>\n{\n  inline bool operator()(const SIPIncorporation& a, const SIPIncorporation& b) const\n  {\n    return a.rate < b.rate;\n  }\n\n};\n\nclass MetaProSIPInterpolation\n{\npublic:\n  ///< Determine score maxima from rate to score distribution using derivatives from spline interpolation\n  static vector<RateScorePair> getHighPoints(double threshold, const MapRateToScoreType& rate2score, bool debug = false)\n  {\n    vector<RateScorePair> high_points;\n    vector<double> x, y;\n\n    // set proper boundaries (uniform spacing)\n    x.push_back(-100.0 / (double)rate2score.size());\n    y.push_back(0);\n\n    // copy data\n    for (MapRateToScoreType::const_iterator it = rate2score.begin(); it != rate2score.end(); ++it)\n    {\n      x.push_back(it->first);\n      y.push_back(it->second);\n    }\n\n    if (rate2score.find(100.0) == rate2score.end() && x[x.size() - 1] < 100.0)\n    {\n      x.push_back(100.0);\n      y.push_back(0);\n    }\n\n    const size_t n = x.size();\n\n    //Wm5::IntpAkimaNonuniform1<double> spline(x.size(), &x.front(), &y.front());\n    CubicSpline2d spline(x, y);\n\n    if (debug)\n    {\n      LOG_DEBUG << x[0] << \" \" << x[n - 1] << \" \" << n << endl;\n    }\n\n    double last_dxdy = 0;\n    for (double xi = x[0]; xi < x[n - 1]; xi += 0.01)\n    {\n      double dxdy = spline.derivatives(xi, 1);\n      double yi = spline.eval(xi);\n\n      if (debug)\n      {\n        cout << x[0] << \" \" << x[n - 1] << \" \" << xi << \" \" << yi << endl;\n      }\n\n      if (last_dxdy > 0.0 && dxdy <= 0 && yi > threshold)\n      {\n        RateScorePair rsp;\n        rsp.rate = xi;\n        rsp.score = yi;\n        high_points.push_back(rsp);\n      }\n      last_dxdy = dxdy;\n    }\n\n    if (debug)\n    {\n      LOG_DEBUG << \"Found: \" << high_points.size() << \" local maxima.\" << endl;\n      for (Size i = 0; i != high_points.size(); ++i)\n      {\n        LOG_DEBUG << high_points[i].rate << \" \" << high_points[i].score << endl;\n      }\n    }\n\n    return high_points;\n  }\n\n};\n\nclass MetaProSIPClustering\n{\npublic:\n  static vector<double> getRIAClusterCenter(const vector<SIPPeptide>& sip_peptides)\n  {\n    vector<double> cluster;\n    MapRateToScoreType hist;\n\n    for (vector<SIPPeptide>::const_iterator cit = sip_peptides.begin(); cit != sip_peptides.end(); ++cit)\n    {\n      // build histogram of rates\n      for (vector<SIPIncorporation>::const_iterator iit = cit->incorporations.begin(); iit != cit->incorporations.end(); ++iit)\n      {\n        if (hist.find(iit->rate) == hist.end())\n        {\n          hist[iit->rate] = 1.0;\n        }\n        else\n        {\n          hist[iit->rate] += 1.0;\n        }\n      }\n    }\n\n    // kernel density estimation, TODO: binary search for 5 sigma boundaries\n    vector<double> density(101, 0);\n    for (Size i = 0; i != density.size(); ++i)\n    {\n      double sum = 0;\n      for (MapRateToScoreType::const_iterator mit = hist.begin(); mit != hist.end(); ++mit)\n      {\n        normal s(mit->first, 2.0);\n        sum += mit->second * pdf(s, (double)i);\n      }\n      density[i] = sum;\n    }\n\n    MapRateToScoreType ria_density;\n\n    for (Size i = 0; i != density.size(); ++i)\n    {\n      ria_density[i] = density[i];\n    }\n\n    /*\n    TextFile t;\n    for (MapRateToScoreType::const_iterator mit = ria_density.begin(); mit != ria_density.end(); ++mit)\n    {\n      t.addLine(String(mit->second));\n    }\n    t.store(\"/abi-data/sachsenb/OpenMS_IDE/dump.txt\");\n    */\n\n    vector<RateScorePair> cluster_center = MetaProSIPInterpolation::getHighPoints(0.5, ria_density, true);\n\n    // return cluster centers\n    for (vector<RateScorePair>::const_iterator cit = cluster_center.begin(); cit != cluster_center.end(); ++cit)\n    {\n      cluster.push_back(cit->rate);\n    }\n    return cluster;\n  }\n\n  //@Note sip peptides get reordered in same order as clusters\n  static vector<vector<SIPPeptide> > clusterSIPPeptides(const vector<double>& centers, vector<SIPPeptide>& sip_peptides)\n  {\n    // one cluster for each cluster center\n    vector<vector<SIPPeptide> > clusters(centers.size(), vector<SIPPeptide>());\n\n    // assign sip peptide to cluster center with largest RIA\n    for (vector<SIPPeptide>::const_iterator sit = sip_peptides.begin(); sit != sip_peptides.end(); ++sit)\n    {\n      const vector<SIPIncorporation>& incs = sit->incorporations;\n      if (!incs.empty())\n      {\n        double largest_ria = incs[incs.size() - 1].rate;\n        Size closest_cluster_idx = 0;\n        double closest_cluster_dist = std::numeric_limits<double>::max();\n        for (Size i = 0; i != centers.size(); ++i)\n        {\n          double dist = std::fabs(centers[i] - largest_ria);\n          if (dist < closest_cluster_dist)\n          {\n            closest_cluster_dist = dist;\n            closest_cluster_idx = i;\n          }\n        }\n\n        // add SIP peptide to closest cluster\n        clusters[closest_cluster_idx].push_back(*sit);\n      }\n    }\n\n    // rearrange SIP peptides to reflect new order\n    sip_peptides.clear();\n    for (vector<vector<SIPPeptide> >::const_iterator sit = clusters.begin(); sit != clusters.end(); ++sit)\n    {\n      sip_peptides.insert(sip_peptides.end(), sit->begin(), sit->end());\n    }\n\n    return clusters;\n  }\n\n};\n\nclass MetaProSIPReporting\n{\npublic:\n  static void plotHeatMap(const String& output_dir, const String& tmp_path, const String& file_suffix, const String& file_extension, const vector<vector<double> >& binned_ria, vector<String> class_labels, Size debug_level = 0)\n  {\n    String filename = String(\"heatmap\") + file_suffix + \".\" + file_extension;\n    String script_filename = String(\"heatmap\") + file_suffix + String(\".R\");\n\n    TextFile current_script;\n    StringList ria_list, col_labels;\n\n    for (Size i = 0; i != binned_ria[0].size(); ++i)\n    {\n      String label = String(i * (100 / binned_ria[0].size())) + \"%-\" + String((i + 1) * (100 / binned_ria[0].size())) + \"%\";\n      col_labels.push_back(label);\n    }\n\n    for (vector<vector<double> >::const_iterator pit = binned_ria.begin(); pit != binned_ria.end(); ++pit)\n    {\n      for (vector<double>::const_iterator rit = pit->begin(); rit != pit->end(); ++rit)\n      {\n        ria_list.push_back(String(*rit));\n      }\n    }\n\n    // row labels\n    StringList row_labels;\n    if (!class_labels.empty())\n    {\n      for (Size i = 0; i != class_labels.size(); ++i)\n      {\n        row_labels.push_back(class_labels[i]);\n      }\n    }\n\n    // plot heatmap\n    current_script.addLine(\"library(gplots)\");\n    String ria_list_string;\n    ria_list_string.concatenate(ria_list.begin(), ria_list.end(), \",\");\n    current_script.addLine(\"mdat <- matrix(c(\" + ria_list_string + \"), ncol=\" + String(binned_ria[0].size()) + \", byrow=TRUE)\");\n\n    if (file_extension == \"png\")\n    {\n      current_script.addLine(\"png('\" + tmp_path + \"/\" + filename + \"', width=1000, height=\" + String(10 * binned_ria.size()) + \")\");\n    }\n    else if (file_extension == \"svg\")\n    {\n      current_script.addLine(\"svg('\" + tmp_path + \"/\" + filename + \"', width=8, height=4.5)\");\n    }\n    else if (file_extension == \"pdf\")\n    {\n      current_script.addLine(\"pdf('\" + tmp_path + \"/\" + filename + \"', width=8, height=4.5)\");\n    }\n\n    String labRowString;\n    if (row_labels.empty())\n    {\n      labRowString = \"FALSE\";\n    }\n    else\n    {\n      String row_labels_string;\n      row_labels_string.concatenate(row_labels.begin(), row_labels.end(), \"\\\",\\\"\");\n      labRowString = String(\"c(\\\"\") + row_labels_string + \"\\\")\";\n    }\n\n    String col_labels_string;\n    col_labels_string.concatenate(col_labels.begin(), col_labels.end(), \"\\\",\\\"\");\n\n    current_script.addLine(\"heatmap.2(mdat, dendrogram=\\\"none\\\", col=colorRampPalette(c(\\\"black\\\",\\\"red\\\")), Rowv=FALSE, Colv=FALSE, key=FALSE, labRow=\" + labRowString + \",labCol=c(\\\"\" + col_labels_string + \"\\\"),trace=\\\"none\\\", density.info=\\\"none\\\")\");\n\n    current_script.addLine(\"tmp<-dev.off()\");\n    current_script.store(tmp_path + \"/\" + script_filename);\n\n    QProcess p;\n    QStringList env = QProcess::systemEnvironment();\n    env << QString(\"R_LIBS=\") + tmp_path.toQString();\n    p.setEnvironment(env);\n\n    QStringList qparam;\n    qparam << \"--vanilla\";\n    if (debug_level < 1)\n    {\n      qparam << \"--quiet\";\n    }\n    qparam << \"--slave\" << \"--file=\" + QString(tmp_path.toQString() + \"/\" + script_filename.toQString());\n    p.start(\"R\", qparam);\n    p.waitForFinished(-1);\n    int status = p.exitCode();\n\n    // cleanup\n    if (status != 0)\n    {\n      std::cerr << \"Error: Process returned with non 0 status.\" << std::endl;\n    }\n    else\n    {\n      QFile(QString(tmp_path.toQString() + \"/\" + filename.toQString())).copy(output_dir.toQString() + \"/heatmap\" + file_suffix.toQString() + \".\" + file_extension.toQString());\n      if (debug_level < 1)\n      {\n        QFile(QString(tmp_path.toQString() + \"/\" + script_filename.toQString())).remove();\n        QFile(QString(tmp_path.toQString() + \"/\" + filename.toQString())).remove();\n      }\n    }\n  }\n\n  static void plotFilteredSpectra(const String& output_dir, const String& tmp_path, const String& file_suffix, const String& file_extension, const vector<SIPPeptide>& sip_peptides, Size debug_level = 0)\n  {\n    String filename = String(\"spectrum_plot\") + file_suffix + \".\" + file_extension;\n    String script_filename = String(\"spectrum_plot\") + file_suffix + String(\".R\");\n\n    for (Size i = 0; i != sip_peptides.size(); ++i)\n    {\n      TextFile current_script;\n      StringList mz_list;\n      StringList intensity_list;\n\n      for (Size j = 0; j != sip_peptides[i].accumulated.size(); ++j)\n      {\n        const Peak1D& peak = sip_peptides[i].accumulated[j];\n        mz_list.push_back(String(peak.getMZ()));\n        intensity_list.push_back(String(peak.getIntensity()));\n      }\n\n      String mz_list_string;\n      mz_list_string.concatenate(mz_list.begin(), mz_list.end(), \",\");\n\n      String intensity_list_string;\n      intensity_list_string.concatenate(intensity_list.begin(), intensity_list.end(), \",\");\n\n      current_script.addLine(\"mz<-c(\" + mz_list_string + \")\");\n      current_script.addLine(\"int<-c(\" + intensity_list_string + \")\");\n      current_script.addLine(\"x0=mz; x1=mz; y0=rep(0, length(x0)); y1=int\");\n\n      if (file_extension == \"png\")\n      {\n        current_script.addLine(\"png('\" + tmp_path + \"/\" + filename + \"')\");\n      }\n      else if (file_extension == \"svg\")\n      {\n        current_script.addLine(\"svg('\" + tmp_path + \"/\" + filename + \"', width=8, height=4.5)\");\n      }\n      else if (file_extension == \"pdf\")\n      {\n        current_script.addLine(\"pdf('\" + tmp_path + \"/\" + filename + \"', width=8, height=4.5)\");\n      }\n\n      current_script.addLine(\"plot.new()\");\n      current_script.addLine(\"plot.window(xlim=c(min(mz),max(mz)), ylim=c(0,max(int)))\");\n      current_script.addLine(\"axis(1); axis(2)\");\n      current_script.addLine(\"title(xlab=\\\"m/z\\\")\");\n      current_script.addLine(\"title(ylab=\\\"intensity\\\")\");\n      current_script.addLine(\"box()\");\n      current_script.addLine(\"segments(x0,y0,x1,y1)\");\n      current_script.addLine(\"tmp<-dev.off()\");\n      current_script.store(tmp_path + \"/\" + script_filename);\n\n      QProcess p;\n      QStringList env = QProcess::systemEnvironment();\n      env << QString(\"R_LIBS=\") + tmp_path.toQString();\n      p.setEnvironment(env);\n\n      QStringList qparam;\n      qparam << \"--vanilla\" << \"--quiet\" << \"--slave\" << \"--file=\" + QString(tmp_path.toQString() + \"/\" + script_filename.toQString());\n      p.start(\"R\", qparam);\n      p.waitForFinished(-1);\n      int status = p.exitCode();\n\n      if (status != 0)\n      {\n        std::cerr << \"Error: Process returned with non 0 status.\" << std::endl;\n      }\n      else\n      {\n        QFile(QString(tmp_path.toQString() + \"/\" + filename.toQString())).copy(output_dir.toQString() + \"/spectrum\" + file_suffix.toQString() + \"_rt_\" + String(sip_peptides[i].feature_rt).toQString() + \".\" + file_extension.toQString());\n        if (debug_level < 1)\n        {\n          QFile(QString(tmp_path.toQString() + \"/\" + script_filename.toQString())).remove();\n          QFile(QString(tmp_path.toQString() + \"/\" + filename.toQString())).remove();\n        }\n      }\n    }\n  }\n\n  static void writeHTML(const String& qc_output_directory, const String& file_suffix, const String& file_extension, const vector<SIPPeptide>& sip_peptides)\n  {\n    TextFile current_script;\n\n    // html header\n    current_script.addLine(\"<!DOCTYPE html>\\n<html>\\n<body>\\n\");\n\n    // peptide heat map plot\n    current_script.addLine(String(\"<h1>\") + \"peptide heat map</h1>\");\n    String peptide_heatmap_plot_filename = String(\"heatmap_peptide\") + file_suffix + String(\".\") + file_extension;\n    current_script.addLine(\"<p> <img src=\\\"\" + peptide_heatmap_plot_filename + \"\\\" alt=\\\"graphic\\\"></p>\");\n\n    for (Size i = 0; i != sip_peptides.size(); ++i)\n    {\n      // heading\n      current_script.addLine(String(\"<h1>\") + \"RT: \" + String(sip_peptides[i].feature_rt) + \"</h1>\");\n\n      current_script.addLine(\"<table border=\\\"1\\\">\");\n      // sequence table row\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>sequence</td>\");\n      current_script.addLine(String(\"<td>\") + sip_peptides[i].sequence.toString() + \"</td>\");\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>rt (min.)</td>\");\n      current_script.addLine(String(\"<td>\" + String::number(sip_peptides[i].feature_rt / 60.0, 2) + \"</td>\"));\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>rt (sec.)</td>\");\n      current_script.addLine(String(\"<td>\" + String::number(sip_peptides[i].feature_rt, 2) + \"</td>\"));\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>mz</td>\");\n      current_script.addLine(String(\"<td>\" + String::number(sip_peptides[i].feature_mz, 4) + \"</td>\"));\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>theo. mz</td>\");\n      current_script.addLine(String(\"<td>\" + String::number(sip_peptides[i].mz_theo, 4) + \"</td>\"));\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>charge</td>\");\n      current_script.addLine(String(\"<td>\" + String(sip_peptides[i].charge) + \"</td>\"));\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>feature type</td>\");\n      current_script.addLine(String(\"<td>\" + String(sip_peptides[i].feature_type) + \"</td>\"));\n      current_script.addLine(\"</tr>\");\n\n      if (!sip_peptides[i].accessions.empty())\n      {\n        current_script.addLine(String(\"<tr>\"));\n        current_script.addLine(\"<td>accessions</td>\");\n        current_script.addLine(String(\"<td>\" + *sip_peptides[i].accessions.begin() + \"</td>\"));\n        current_script.addLine(String(\"</tr>\"));\n\n        current_script.addLine(String(\"<tr>\"));\n        current_script.addLine(\"<td>unique</td>\");\n        current_script.addLine(String(\"<td>\" + String(sip_peptides[i].unique) + \"</td>\"));\n        current_script.addLine(String(\"</tr>\"));\n      }\n\n      current_script.addLine(String(\"<tr>\"));\n      current_script.addLine(\"<td>search score</td>\");\n      current_script.addLine(String(\"<td>\") + String(sip_peptides[i].score) + \"</td>\");\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>global labeling ratio</td>\");\n      current_script.addLine(String(\"<td>\") + String::number(sip_peptides[i].global_LR, 2) + \"</td>\");\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"<tr>\");\n      current_script.addLine(\"<td>R squared</td>\");\n      current_script.addLine(String(\"<td>\") + String::number(sip_peptides[i].RR, 2) + \"</td>\");\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"</table>\");\n\n      // table header of incorporations\n      current_script.addLine(\"<p>\");\n      current_script.addLine(\"<table border=\\\"1\\\">\");\n      current_script.addLine(\"<tr>\");\n      for (Size k = 0; k != sip_peptides[i].incorporations.size(); ++k)\n      {\n        current_script.addLine(String(\"<td>RIA\") + String(k + 1) + \"</td>\");\n        current_script.addLine(String(\"<td>CORR.\") + String(k + 1) + \"</td>\");\n        current_script.addLine(String(\"<td>INT\") + String(k + 1) + \"</td>\");\n      }\n      current_script.addLine(\"</tr>\");\n\n      // table of incorporations\n      current_script.addLine(\"<tr>\");\n      for (Size k = 0; k != sip_peptides[i].incorporations.size(); ++k)\n      {\n        SIPIncorporation p = sip_peptides[i].incorporations[k];\n        current_script.addLine(String(\"<td>\") + String::number(p.rate, 2) + \"</td>\");\n        current_script.addLine(String(\"<td>\") + String::number(p.correlation, 2) + \"</td>\");\n        current_script.addLine(String(\"<td>\") + String::number(p.abundance, 0) + \"</td>\");\n      }\n      current_script.addLine(\"</tr>\");\n\n      current_script.addLine(\"</table>\");\n\n      // spectrum plot\n      String spectrum_filename = String(\"spectrum\") + file_suffix + \"_rt_\" + String(sip_peptides[i].feature_rt) + \".\" + file_extension;\n      current_script.addLine(\"<p> <img src=\\\"\" + spectrum_filename + \"\\\" alt=\\\"graphic\\\"></p>\");\n\n      // score plot\n      String score_filename = String(\"scores\") + file_suffix + \"_rt_\" + String(sip_peptides[i].feature_rt) + \".\" + file_extension;\n      current_script.addLine(\"<p> <img src=\\\"\" + score_filename + \"\\\" alt=\\\"graphic\\\"></p>\");\n    }\n    current_script.addLine(\"\\n</body>\\n</html>\");\n    current_script.store(qc_output_directory.toQString() + \"/index\" + file_suffix.toQString() + \".html\");\n  }\n\n  static void plotScoresAndWeights(const String& output_dir, const String& tmp_path, const String& file_suffix, const String& file_extension, const vector<SIPPeptide>& sip_peptides, double score_plot_yaxis_min, Size debug_level = 0)\n  {\n    String score_filename = String(\"score_plot\") + file_suffix + file_extension;\n    String script_filename = String(\"score_plot\") + file_suffix + String(\".R\");\n\n    for (Size i = 0; i != sip_peptides.size(); ++i)\n    {\n      TextFile current_script;\n      StringList rate_dec_list;\n      StringList rate_corr_list;\n      StringList weights_list;\n      StringList corr_list;\n\n      for (MapRateToScoreType::const_iterator mit = sip_peptides[i].decomposition_map.begin(); mit != sip_peptides[i].decomposition_map.end(); ++mit)\n      {\n        rate_dec_list.push_back(String(mit->first));\n        weights_list.push_back(String(mit->second));\n      }\n\n      for (MapRateToScoreType::const_iterator mit = sip_peptides[i].correlation_map.begin(); mit != sip_peptides[i].correlation_map.end(); ++mit)\n      {\n        rate_corr_list.push_back(String(mit->first));\n        corr_list.push_back(String(mit->second));\n      }\n\n      String rate_dec_list_string;\n      rate_dec_list_string.concatenate(rate_dec_list.begin(), rate_dec_list.end(), \",\");\n\n      String weights_list_string;\n      weights_list_string.concatenate(weights_list.begin(), weights_list.end(), \",\");\n\n      String rate_corr_list_string;\n      rate_corr_list_string.concatenate(rate_corr_list.begin(), rate_corr_list.end(), \",\");\n\n      String corr_list_string;\n      corr_list_string.concatenate(corr_list.begin(), corr_list.end(), \",\");\n\n      current_script.addLine(\"rate_dec<-c(\" + rate_dec_list_string + \")\");\n      current_script.addLine(\"dec<-c(\" + weights_list_string + \")\");\n      current_script.addLine(\"if (max(dec)!=0) {dec<-dec/max(dec)}\");\n      current_script.addLine(\"rate_corr<-c(\" + rate_corr_list_string + \")\");\n      current_script.addLine(\"corr<-c(\" + corr_list_string + \")\");\n\n      if (score_plot_yaxis_min >= 0)\n      {\n        current_script.addLine(\"corr[corr<0]=0\"); // truncate at 0 for better drawing\n      }\n\n      current_script.addLine(\"x0=rate_dec; x1=rate_dec; y0=rep(0, length(x0)); y1=dec\"); // create R segments for decomposition score (vertical bars)\n      if (file_extension == \"png\")\n      {\n        current_script.addLine(\"png('\" + tmp_path + \"/\" + score_filename + \"')\");\n      }\n      else if (file_extension == \"svg\")\n      {\n        current_script.addLine(\"svg('\" + tmp_path + \"/\" + score_filename + \"', width=8, height=4.5)\");\n      }\n      else if (file_extension == \"pdf\")\n      {\n        current_script.addLine(\"pdf('\" + tmp_path + \"/\" + score_filename + \"', width=8, height=4.5)\");\n      }\n      current_script.addLine(\"plot.new()\");\n      current_script.addLine(\"plot.window(xlim=c(0,100), ylim=c(\" + String(score_plot_yaxis_min) + \",1))\");\n      current_script.addLine(\"axis(1); axis(2)\");\n      current_script.addLine(\"title(xlab=\\\"RIA\\\")\");\n      current_script.addLine(\"title(ylab=\\\"normalized weight / corr.\\\")\");\n      current_script.addLine(\"box()\");\n      current_script.addLine(\"segments(x0,y0,x1,y1, col='red')\");\n      current_script.addLine(\"lines(x=rate_corr, y=corr, col='blue')\");\n      current_script.addLine(\"legend('bottomright', horiz=FALSE, xpd=TRUE, col=c('red', 'blue'), lwd=2, c('weights', 'correlation'))\");\n      current_script.addLine(\"tmp<-dev.off()\");\n      current_script.store(tmp_path + \"/\" + script_filename);\n\n      QProcess p;\n      QStringList env = QProcess::systemEnvironment();\n      env << QString(\"R_LIBS=\") + tmp_path.toQString();\n      p.setEnvironment(env);\n\n      QStringList qparam;\n      qparam << \"--vanilla\" << \"--quiet\" << \"--slave\" << \"--file=\" + QString(tmp_path.toQString() + \"/\" + script_filename.toQString());\n      p.start(\"R\", qparam);\n      p.waitForFinished(-1);\n      int status = p.exitCode();\n\n      if (status != 0)\n      {\n        std::cerr << \"Error: Process returned with non 0 status.\" << std::endl;\n      }\n      else\n      {\n        QFile(QString(tmp_path.toQString() + \"/\" + score_filename.toQString())).copy(output_dir.toQString() + \"/scores\" + file_suffix.toQString() + \"_rt_\" + String(sip_peptides[i].feature_rt).toQString() + \".\" + file_extension.toQString());\n        if (debug_level < 1)\n        {\n          QFile(QString(tmp_path.toQString() + \"/\" + script_filename.toQString())).remove();\n          QFile(QString(tmp_path.toQString() + \"/\" + score_filename.toQString())).remove();\n        }\n      }\n    }\n  }\n\n  static void createQualityReport(String tmp_path, String qc_output_directory, String file_suffix, const String& file_extension, const vector<vector<SIPPeptide> >& sip_peptide_cluster, Size n_heatmap_bins, double score_plot_y_axis_min, bool report_natural_peptides)\n  {\n    vector<SIPPeptide> sip_peptides;\n    for (vector<vector<SIPPeptide> >::const_iterator cit = sip_peptide_cluster.begin(); cit != sip_peptide_cluster.end(); ++cit)\n    {\n      for (vector<SIPPeptide>::const_iterator sit = cit->begin(); sit != cit->end(); ++sit)\n      {\n        // skip non natural peptides for repoting if flag is set\n        if (!report_natural_peptides && sit->incorporations.size() == 1 && sit->incorporations[0].rate < 5.0)\n        {\n          continue;\n        }\n        sip_peptides.push_back(*sit);\n      }\n    }\n\n    // heat map based on peptide RIAs\n    LOG_INFO << \"Plotting peptide heat map of \" << sip_peptides.size() << endl;\n    vector<vector<double> > binned_peptide_ria;\n    vector<String> class_labels;\n    createBinnedPeptideRIAData_(n_heatmap_bins, sip_peptide_cluster, binned_peptide_ria, class_labels);\n    plotHeatMap(qc_output_directory, tmp_path, \"_peptide\" + file_suffix, file_extension, binned_peptide_ria, class_labels);\n\n    LOG_INFO << \"Plotting filtered spectra for quality report\" << endl;\n    plotFilteredSpectra(qc_output_directory, tmp_path, file_suffix, file_extension, sip_peptides);\n\n    LOG_INFO << \"Plotting correlation score and weight distribution\" << endl;\n    plotScoresAndWeights(qc_output_directory, tmp_path, file_suffix, file_extension, sip_peptides, score_plot_y_axis_min);\n\n    if (file_extension != \"pdf\") // html doesn't support pdf as image\n    {\n      writeHTML(qc_output_directory, file_suffix, file_extension, sip_peptides);\n    }\n  }\n\n  static void createCSVReport(vector<vector<SIPPeptide> >& sippeptide_cluster, ofstream& os, map<String, String>& proteinid_to_description)\n  {\n    SVOutStream out_csv_stream(os, \"\\t\", \"_\", String::NONE);\n    // sort clusters by non increasing size\n    sort(sippeptide_cluster.rbegin(), sippeptide_cluster.rend(), SizeLess());\n\n    for (Size i = 0; i != sippeptide_cluster.size(); ++i)\n    {\n      const vector<SIPPeptide>& current_cluster = sippeptide_cluster[i];\n\n      // Group\n      map<String, vector<SIPPeptide> > all_peptides; // map sequence to SIPPeptide\n      map<String, vector<SIPPeptide> > ambigous_peptides; // map sequence to SIPPeptide\n      map<String, map<String, vector<SIPPeptide> > > unambigous_proteins; // map Accession to unmodified String to SIPPeptides\n\n      for (Size k = 0; k != current_cluster.size(); ++k)\n      {\n        const SIPPeptide& current_SIPpeptide = current_cluster[k];\n        String seq = current_SIPpeptide.sequence.toUnmodifiedString();\n        if (current_SIPpeptide.unique)\n        {\n          String first_accession = *current_SIPpeptide.accessions.begin();\n          unambigous_proteins[first_accession][seq].push_back(current_SIPpeptide);\n        }\n        else\n        {\n          ambigous_peptides[current_SIPpeptide.sequence.toUnmodifiedString()].push_back(current_SIPpeptide);\n        }\n        all_peptides[seq].push_back(current_SIPpeptide);\n      }\n\n      Size n_all_peptides = all_peptides.size(); // # of different (on sequence level) unique and non-unique peptides\n      //Size n_ambigous_peptides = ambigous_peptides.size();\n      Size n_unambigous_proteins = unambigous_proteins.size();\n\n      // determine median global LR of whole group\n      vector<double> group_global_LRs;\n      vector<double> group_number_RIAs;\n      for (map<String, vector<SIPPeptide> >::const_iterator all_it = all_peptides.begin(); all_it != all_peptides.end(); ++all_it)\n      {\n        for (vector<SIPPeptide>::const_iterator v_it = all_it->second.begin(); v_it != all_it->second.end(); ++v_it)\n        {\n          group_global_LRs.push_back(v_it->global_LR);\n          group_number_RIAs.push_back(v_it->incorporations.size());\n        }\n      }\n      double group_global_LR = Math::median(group_global_LRs.begin(), group_global_LRs.end(), false);\n\n      Size group_number_RIA = (Size)(Math::median(group_number_RIAs.begin(), group_number_RIAs.end(), false) + 0.5); // median number of RIAs\n      // Group header\n      // Distinct peptides := different (on sequence level) unique and non-unique peptides\n      out_csv_stream << String(\"Group \") + String(i + 1) << \"# Distinct Peptides\" << \"# Unambigous Proteins\" << \"Median Global LR\";\n      for (Size i = 0; i != group_number_RIA; ++i)\n      {\n        out_csv_stream << \"median RIA \" + String(i + 1);\n      }\n      out_csv_stream << endl;\n\n      out_csv_stream << \"\" << n_all_peptides << n_unambigous_proteins << group_global_LR;\n\n      // collect 1th, 2nd, ... RIA of the group based on the peptide RIAs\n      vector<vector<double> > group_RIAs(group_number_RIA, vector<double>());\n      vector<double> group_RIA_medians(group_number_RIA, 0);\n\n      for (map<String, vector<SIPPeptide> >::const_iterator all_it = all_peptides.begin(); all_it != all_peptides.end(); ++all_it)\n      {\n        for (vector<SIPPeptide>::const_iterator v_it = all_it->second.begin(); v_it != all_it->second.end(); ++v_it)\n        {\n          for (Size i = 0; i != group_number_RIA; ++i)\n          {\n            if (i == v_it->incorporations.size())\n            {\n              break;\n            }\n            group_RIAs[i].push_back(v_it->incorporations[i].rate);\n          }\n        }\n      }\n\n      for (Size i = 0; i != group_number_RIA; ++i)\n      {\n        group_RIA_medians[i] = Math::median(group_RIAs[i].begin(), group_RIAs[i].end(), false);\n      }\n\n      for (Size i = 0; i != group_number_RIA; ++i)\n      {\n        out_csv_stream << String(group_RIA_medians[i]);\n      }\n      out_csv_stream << endl;\n\n      // unambiguous protein level\n      for (map<String, map<String, vector<SIPPeptide> > >::const_iterator prot_it = unambigous_proteins.begin(); prot_it != unambigous_proteins.end(); ++prot_it)\n      {\n        // determine median global LR of protein\n        vector<double> protein_global_LRs;\n        vector<double> protein_number_RIAs;\n        for (map<String, vector<SIPPeptide> >::const_iterator pept_it = prot_it->second.begin(); pept_it != prot_it->second.end(); ++pept_it)\n        {\n          for (vector<SIPPeptide>::const_iterator v_it = pept_it->second.begin(); v_it != pept_it->second.end(); ++v_it)\n          {\n            protein_global_LRs.push_back(v_it->global_LR);\n            protein_number_RIAs.push_back(v_it->incorporations.size());\n          }\n        }\n        double protein_global_LR = Math::median(protein_global_LRs.begin(), protein_global_LRs.end(), false);\n        Size protein_number_RIA = (Size)(Math::median(protein_number_RIAs.begin(), protein_number_RIAs.end(), false) + 0.5); // median number of RIAs\n\n        out_csv_stream << \"\" << \"Protein Accession\" << \"Description\" << \"# Unique Peptides\" << \"Median Global LR\";\n        for (Size i = 0; i != protein_number_RIA; ++i)\n        {\n          out_csv_stream << \"median RIA \" + String(i + 1);\n        }\n        out_csv_stream << endl;\n\n        String protein_accession = prot_it->first;\n        String protein_description = \"none\";\n        if (proteinid_to_description.find(protein_accession.trim().toUpper()) != proteinid_to_description.end())\n        {\n          protein_description = proteinid_to_description.at(protein_accession.trim().toUpper());\n        }\n\n        out_csv_stream << \"\" << protein_accession << protein_description << prot_it->second.size() << protein_global_LR;\n\n        vector<vector<double> > protein_RIAs(protein_number_RIA, vector<double>());\n        vector<double> protein_RIA_medians(protein_number_RIA, 0);\n\n        // ratio to natural decomposition\n        vector<vector<double> > protein_ratio(protein_number_RIA, vector<double>());\n        vector<double> protein_ratio_medians(protein_number_RIA, 0);\n\n        // collect 1th, 2nd, ... RIA of the protein based on the peptide RIAs\n        for (map<String, vector<SIPPeptide> >::const_iterator pept_it = prot_it->second.begin(); pept_it != prot_it->second.end(); ++pept_it)\n        {\n          for (vector<SIPPeptide>::const_iterator v_it = pept_it->second.begin(); v_it != pept_it->second.end(); ++v_it)\n          {\n            for (Size i = 0; i != protein_number_RIA; ++i)\n            {\n              if (i == v_it->incorporations.size())\n              {\n                break;\n              }\n              protein_RIAs[i].push_back(v_it->incorporations[i].rate);\n              protein_ratio[i].push_back(v_it->incorporations[i].abundance);\n            }\n          }\n        }\n\n        for (Size i = 0; i != protein_number_RIA; ++i)\n        {\n          protein_RIA_medians[i] = Math::median(protein_RIAs[i].begin(), protein_RIAs[i].end(), false);\n          protein_ratio_medians[i] = Math::median(protein_ratio[i].begin(), protein_ratio[i].end(), false);\n        }\n\n        for (Size i = 0; i != protein_number_RIA; ++i)\n        {\n          out_csv_stream << String(protein_RIA_medians[i]);\n        }\n\n        out_csv_stream << endl;\n\n        // print header of unique peptides\n        out_csv_stream << \"\" << \"\" << \"Peptide Sequence\" << \"RT\" << \"Exp. m/z\" << \"Theo. m/z\" << \"Charge\" << \"Score\" << \"TIC fraction\" << \"#non-natural weights\" << \"\";\n        Size max_incorporations = 0;\n        for (map<String, vector<SIPPeptide> >::const_iterator pept_it = prot_it->second.begin(); pept_it != prot_it->second.end(); ++pept_it)\n        {\n          for (vector<SIPPeptide>::const_iterator v_it = pept_it->second.begin(); v_it != pept_it->second.end(); ++v_it)\n          {\n            max_incorporations = std::max(v_it->incorporations.size(), max_incorporations);\n          }\n        }\n\n        for (Size i = 0; i != max_incorporations; ++i)\n        {\n          out_csv_stream << \"RIA \" + String(i + 1) << \"INT \" + String(i + 1) << \"Cor. \" + String(i + 1);\n        }\n        out_csv_stream << \"Peak intensities\" << \"Global LR\" << endl;\n\n        // print data of unique peptides\n        for (map<String, vector<SIPPeptide> >::const_iterator pept_it = prot_it->second.begin(); pept_it != prot_it->second.end(); ++pept_it)\n        {\n          for (vector<SIPPeptide>::const_iterator v_it = pept_it->second.begin(); v_it != pept_it->second.end(); ++v_it)\n          {\n            out_csv_stream << \"\" << \"\" << v_it->sequence.toString() << String::number(v_it->feature_rt / 60.0, 2) << String::number(v_it->feature_mz, 4) << v_it->mz_theo << v_it->charge << v_it->score << v_it->explained_TIC_fraction << v_it->non_zero_decomposition_coefficients << \"\";\n            for (vector<SIPIncorporation>::const_iterator incorps = v_it->incorporations.begin(); incorps != v_it->incorporations.end(); ++incorps)\n            {\n              out_csv_stream << String::number(incorps->rate, 1) << String::number(incorps->abundance, 0) << String::number(incorps->correlation, 2);\n            }\n\n            // blank entries for nicer formatting\n            for (Int q = 0; q < (Int)max_incorporations - (Int)v_it->incorporations.size(); ++q)\n            {\n              out_csv_stream << \"\" << \"\" << \"\";\n            }\n\n            // output peak intensities\n            String peak_intensities;\n            for (PeakSpectrum::const_iterator p = v_it->accumulated.begin(); p != v_it->accumulated.end(); ++p)\n            {\n              peak_intensities += String::number(p->getIntensity(), 0) + \" \";\n            }\n            out_csv_stream << peak_intensities;\n            out_csv_stream << v_it->global_LR;\n\n            out_csv_stream << endl;\n          }\n        }\n      }\n\n      // print header of non-unique peptides below the protein section\n      Size max_incorporations = 0;\n      for (map<String, vector<SIPPeptide> >::const_iterator pept_it = ambigous_peptides.begin(); pept_it != ambigous_peptides.end(); ++pept_it)\n      {\n        for (vector<SIPPeptide>::const_iterator v_it = pept_it->second.begin(); v_it != pept_it->second.end(); ++v_it)\n        {\n          max_incorporations = std::max(v_it->incorporations.size(), max_incorporations);\n        }\n      }\n\n      out_csv_stream << \"Non-Unique Peptides\" << \"Accessions\" << \"Peptide Sequence\" << \"Descriptions\" << \"Score\" << \"RT\" << \"Exp. m/z\" << \"Theo. m/z\" << \"Charge\" << \"#non-natural weights\" << \"\";\n\n      for (Size i = 0; i != max_incorporations; ++i)\n      {\n        out_csv_stream << \"RIA \" + String(i + 1) << \"INT \" + String(i + 1) << \"Cor. \" + String(i + 1);\n      }\n      out_csv_stream << \"Peak intensities\" << \"Global LR\" << endl;\n\n      // print data of non-unique peptides below the protein section\n      for (map<String, vector<SIPPeptide> >::const_iterator pept_it = ambigous_peptides.begin(); pept_it != ambigous_peptides.end(); ++pept_it)\n      {\n        // build up the protein accession string for non-unique peptides. Only the first 3 accessions are added.\n        for (vector<SIPPeptide>::const_iterator v_it = pept_it->second.begin(); v_it != pept_it->second.end(); ++v_it)\n        {\n          String accessions_string;\n          String description_string = \"none\";\n\n          for (Size ac = 0; ac != v_it->accessions.size(); ++ac)\n          {\n            if (ac >= 3) // only print at most 3 accessions as these can be quite numorous\n            {\n              accessions_string += \"...\";\n              break;\n            }\n            String protein_accession = v_it->accessions[ac];\n            accessions_string += protein_accession;\n\n            if (proteinid_to_description.find(protein_accession.trim().toUpper()) != proteinid_to_description.end())\n            {\n              if (description_string == \"none\")\n              {\n                description_string = \"\";\n              }\n              description_string += proteinid_to_description.at(protein_accession.trim().toUpper());\n            }\n\n            if (ac < v_it->accessions.size() - 1)\n            {\n              accessions_string += \", \";\n              if (description_string != \"none\")\n              {\n                description_string += \", \";\n              }\n            }\n          }\n\n          out_csv_stream << \"\" << accessions_string << v_it->sequence.toString() << description_string << v_it->score << String::number(v_it->feature_rt / 60.0, 2) << String::number(v_it->feature_mz, 4) << v_it->mz_theo << v_it->charge << v_it->non_zero_decomposition_coefficients << \"\";\n\n          // output variable sized RIA part\n          for (vector<SIPIncorporation>::const_iterator incorps = v_it->incorporations.begin(); incorps != v_it->incorporations.end(); ++incorps)\n          {\n            out_csv_stream << String::number(incorps->rate, 1) << String::number(incorps->abundance, 0) << String::number(incorps->correlation, 2);\n          }\n\n          // blank entries for nicer formatting\n          for (Int q = 0; q < (Int)max_incorporations - (Int)v_it->incorporations.size(); ++q)\n          {\n            out_csv_stream << \"\" << \"\" << \"\";\n          }\n\n          // output peak intensities\n          String peak_intensities;\n          for (PeakSpectrum::const_iterator p = v_it->accumulated.begin(); p != v_it->accumulated.end(); ++p)\n          {\n            peak_intensities += String::number(p->getIntensity(), 0) + \" \";\n          }\n          out_csv_stream << peak_intensities;\n          out_csv_stream << v_it->global_LR;\n          out_csv_stream << endl;\n        }\n      }\n    }\n    os.close();\n  }\n\n  static void createPeptideCentricCSVReport(const String in_mzML, const String& file_extension, vector<vector<SIPPeptide> >& sippeptide_cluster, ofstream& os, map<String, String>& proteinid_to_description, String qc_output_directory, String file_suffix, bool report_natural_peptides)\n  {\n    SVOutStream out_csv_stream(os, \"\\t\", \"_\", String::NONE);\n\n    // sort clusters by non increasing size\n    sort(sippeptide_cluster.rbegin(), sippeptide_cluster.rend(), SizeLess());\n\n    // store SIP peptide with cluster index for peptide centric view on data\n    vector<pair<SIPPeptide, Size> > peptide_to_cluster_index;\n    for (Size i = 0; i != sippeptide_cluster.size(); ++i)\n    {\n      const vector<SIPPeptide>& current_cluster = sippeptide_cluster[i];\n      for (Size k = 0; k != current_cluster.size(); ++k)\n      {\n        peptide_to_cluster_index.push_back(make_pair(current_cluster[k], i));\n      }\n    }\n\n    LOG_INFO << \"Writing \" << peptide_to_cluster_index.size() << \" peptides to peptide centric csv.\" << endl;\n\n    // sort by sequence\n    sort(peptide_to_cluster_index.begin(), peptide_to_cluster_index.end(), SequenceLess());\n\n    out_csv_stream << \"Peptide Sequence\" << \"Feature\" << \"Quality Report Spectrum\" << \"Quality report scores\" << \"Sample Name\" << \"Protein Accessions\" << \"Description\" << \"Unique\" << \"#Ambiguity members\"\n                   << \"Score\" << \"RT\" << \"Exp. m/z\" << \"Theo. m/z\" << \"Charge\" << \"TIC fraction\" << \"#non-natural weights\" << \"Peak intensities\" << \"Group\" << \"Global Peptide LR\";\n\n    for (Size i = 1; i <= 10; ++i)\n    {\n      out_csv_stream << \"RIA \" + String(i) << \"LR of RIA \" + String(i) << \"INT \" + String(i) << \"Cor. \" + String(i);\n    }\n    out_csv_stream << std::endl;\n\n    for (Size i = 0; i != peptide_to_cluster_index.size(); ++i)\n    {\n      const SIPPeptide& current_SIPpeptide = peptide_to_cluster_index[i].first;\n\n      // skip non natural peptides for repoting if flag is set\n      if (!report_natural_peptides && current_SIPpeptide.incorporations.size() == 1 && current_SIPpeptide.incorporations[0].rate < 5.0)\n      {\n        continue;\n      }\n\n      const Size& current_cluster_index = peptide_to_cluster_index[i].second;\n\n      // output peptide sequence\n      out_csv_stream << current_SIPpeptide.sequence.toString() << current_SIPpeptide.feature_type;\n\n      // output quality report links if available\n      if (qc_output_directory.empty() || file_suffix.empty()) // if no qc plots have been generated or no unique file_suffix has been provided we can't generate links to spectra and scores\n      {\n        out_csv_stream << \"\" << \"\" << in_mzML;\n      }\n      else\n      {\n        String qr_spectrum_filename = String(\"file://\") + qc_output_directory + \"/\" + String(\"spectrum\") + file_suffix + \"_rt_\" + String(current_SIPpeptide.feature_rt) + \".\" + file_extension;\n        String qr_scores_filename = String(\"file://\") + qc_output_directory + \"/\" + String(\"scores\") + file_suffix + \"_rt_\" + String(current_SIPpeptide.feature_rt) + \".\" + file_extension;\n        out_csv_stream << qr_spectrum_filename << qr_scores_filename << in_mzML;\n      }\n\n      // output protein accessions and descriptions\n      String accession_string;\n      String protein_descriptions = \"none\";\n      for (Size j = 0; j != current_SIPpeptide.accessions.size(); ++j)\n      {\n        String current_accession = current_SIPpeptide.accessions[j];\n        current_accession.trim().toUpper();\n        accession_string += current_accession;\n\n        if (proteinid_to_description.find(current_accession) != proteinid_to_description.end())\n        {\n          if (protein_descriptions == \"none\")\n          {\n            protein_descriptions = proteinid_to_description.at(current_accession);\n          }\n          else\n          {\n            protein_descriptions += proteinid_to_description.at(current_accession);\n          }\n        }\n\n        // add \",\" between accessions\n        if (j != current_SIPpeptide.accessions.size() - 1)\n        {\n          accession_string += \",\";\n          protein_descriptions += \",\";\n        }\n      }\n\n      out_csv_stream << accession_string << protein_descriptions << current_SIPpeptide.unique << current_SIPpeptide.accessions.size() << current_SIPpeptide.score << String::number(current_SIPpeptide.feature_rt / 60.0, 2)\n                     << String::number(current_SIPpeptide.feature_mz, 4) << String::number(current_SIPpeptide.mz_theo, 4) << current_SIPpeptide.charge << current_SIPpeptide.explained_TIC_fraction << current_SIPpeptide.non_zero_decomposition_coefficients;\n\n      // output peak intensities\n      String peak_intensities;\n      for (PeakSpectrum::const_iterator p = current_SIPpeptide.accumulated.begin(); p != current_SIPpeptide.accumulated.end(); ++p)\n      {\n        peak_intensities += String::number(p->getIntensity(), 0) + \" \";\n      }\n      out_csv_stream << peak_intensities;\n\n      out_csv_stream << current_cluster_index << current_SIPpeptide.global_LR;\n\n      for (Size j = 0; j != current_SIPpeptide.incorporations.size(); ++j)\n      {\n        const double ria = current_SIPpeptide.incorporations[j].rate;\n        const double abundance = current_SIPpeptide.incorporations[j].abundance;\n        const double corr = current_SIPpeptide.incorporations[j].correlation;\n\n        double LR_of_RIA = 0;\n        if (ria < 1.5) // first RIA hast natural abundance\n        {\n          LR_of_RIA = abundance / current_SIPpeptide.incorporations[0].abundance;\n        }\n        out_csv_stream << String::number(ria, 1) << String::number(LR_of_RIA, 1) << String::number(abundance, 1) << String::number(corr, 1);\n      }\n      out_csv_stream << endl;\n    }\n\n    out_csv_stream << endl;\n    os.close();\n  }\n\nprotected:\n  static void createBinnedPeptideRIAData_(const Size n_heatmap_bins, const vector<vector<SIPPeptide> >& sip_clusters, vector<vector<double> >& binned_peptide_ria, vector<String>& cluster_labels)\n  {\n    cluster_labels.clear();\n    binned_peptide_ria.clear();\n\n    for (vector<vector<SIPPeptide> >::const_iterator cit = sip_clusters.begin(); cit != sip_clusters.end(); ++cit)\n    {\n      const vector<SIPPeptide>& sip_peptides = *cit;\n      for (vector<SIPPeptide>::const_iterator pit = sip_peptides.begin(); pit != sip_peptides.end(); ++pit)\n      {\n        vector<double> binned(n_heatmap_bins, 0.0);\n        for (vector<SIPIncorporation>::const_iterator iit = pit->incorporations.begin(); iit != pit->incorporations.end(); ++iit)\n        {\n          Int bin = iit->rate / 100.0 * n_heatmap_bins;\n          bin = bin > (Int)binned.size() - 1 ? (Int)binned.size() - 1 : bin;\n          bin = bin < 0 ? 0 : bin;\n          binned[bin] = log(1.0 + iit->abundance);\n        }\n        binned_peptide_ria.push_back(binned);\n        cluster_labels.push_back((String)(cit - sip_clusters.begin()));\n      }\n    }\n  }\n\n};\n\nclass MetaProSIPDecomposition\n{\npublic:\n  ///> Perform the decomposition\n  static Int calculateDecompositionWeightsIsotopicPatterns(Size n_bins, const vector<double>& isotopic_intensities, const IsotopePatterns& patterns, MapRateToScoreType& map_rate_to_decomposition_weight, SIPPeptide& sip_peptide)\n  {\n    Matrix<double> beta(n_bins, 1);\n    Matrix<double> intensity_vector(isotopic_intensities.size(), 1);\n\n    for (Size p = 0; p != isotopic_intensities.size(); ++p)\n    {\n      intensity_vector(p, 0) = isotopic_intensities[p];\n    }\n\n    Matrix<double> basis_matrix(isotopic_intensities.size(), n_bins);\n\n    for (Size row = 0; row != isotopic_intensities.size(); ++row)\n    {\n      for (Size col = 0; col != n_bins; ++col)\n      {\n        const vector<double>& pattern = patterns[col].second;\n        if (row <= n_bins)\n        {\n          basis_matrix(row, col) = pattern[row];\n        }\n        else\n        {\n          basis_matrix(row, col) = 0;\n        }\n      }\n    }\n\n    Int result = NonNegativeLeastSquaresSolver::solve(basis_matrix, intensity_vector, beta);\n\n    for (Size p = 0; p != n_bins; ++p)\n    {\n      map_rate_to_decomposition_weight[(double)p / n_bins * 100.0] = beta(p, 0);\n    }\n\n    // calculate R squared\n    double S_tot = 0;\n    double mean = accumulate(isotopic_intensities.begin(), isotopic_intensities.end(), 0) / isotopic_intensities.size();\n    for (Size row = 0; row != isotopic_intensities.size(); ++row)\n    {\n      S_tot += pow(isotopic_intensities[row] - mean, 2);\n    }\n\n    double S_err = 0;\n    PeakSpectrum reconstructed;\n\n    for (Size row = 0; row != isotopic_intensities.size(); ++row)\n    {\n      double predicted = 0;\n      for (Size col = 0; col != n_bins; ++col)\n      {\n        predicted += basis_matrix(row, col) * beta(col, 0);\n      }\n      Peak1D peak;\n      peak.setIntensity(predicted);\n      peak.setMZ(sip_peptide.mz_theo + sip_peptide.mass_diff / sip_peptide.charge * row);\n      reconstructed.push_back(peak);\n      S_err += pow(isotopic_intensities[row] - predicted, 2);\n    }\n\n    for (Size row = 0; row != 5; ++row)\n    {\n      double predicted = 0;\n      for (Size col = 0; col != 3; ++col)\n      {\n        predicted += basis_matrix(row, col) * beta(col, 0);\n      }\n      sip_peptide.reconstruction_monoistopic.push_back(predicted);\n    }\n\n    sip_peptide.RR = 1.0 - (S_err / S_tot);\n    sip_peptide.reconstruction = reconstructed;\n\n    return result;\n  }\n\n  // Template calculations for base matrix\n\n  ///> Given a peptide sequence calculate the theoretical isotopic patterns given all incorporations rate (13C Version)\n  ///> extend isotopic patterns by additional_isotopes to collect other element higher isotopes at 100% incorporation\n  static IsotopePatterns calculateIsotopePatternsFor13CRange(const AASequence& peptide, Size additional_isotopes = 5)\n  {\n    IsotopePatterns ret;\n\n    const Element* e1 = ElementDB::getInstance()->getElement(\"Carbon\");\n    Element* e2 = const_cast<Element*>(e1);\n\n    EmpiricalFormula peptide_ef = peptide.getFormula();\n    Size MAXISOTOPES = (Size)peptide_ef.getNumberOf(e1);\n\n    // calculate empirical formula of modifications - these can not be labeled via substrate feeding and must be taken care of in pattern calculation\n    AASequence unmodified_peptide = AASequence::fromString(peptide.toUnmodifiedString());\n    EmpiricalFormula unmodified_peptide_ef = unmodified_peptide.getFormula();\n    UInt max_labeling_carbon = (UInt)unmodified_peptide_ef.getNumberOf(e1); // max. number of atoms that can be labeled\n    EmpiricalFormula modifications_ef = peptide_ef - unmodified_peptide_ef; // difference formula for modifications (note that it can contain positive/negative numbers)\n\n    if (modifications_ef.getNumberOf(e1) > 0) // modification adds additional (unlabeled) carbon atoms\n    {\n      IsotopeDistribution modification_dist = modifications_ef.getIsotopeDistribution(max_labeling_carbon + additional_isotopes);\n      for (double abundance = 0.0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)max_labeling_carbon)\n      {\n        double a = abundance / 100.0;\n        IsotopeDistribution isotopes;\n        std::vector<std::pair<Size, double> > container;\n        container.push_back(make_pair(12, 1.0 - a));\n        container.push_back(make_pair(13, a));\n        isotopes.set(container);\n        e2->setIsotopeDistribution(isotopes);\n        IsotopeDistribution dist = unmodified_peptide_ef.getIsotopeDistribution(max_labeling_carbon + additional_isotopes);\n        dist += modification_dist; // convole with modification distribution (which follows the natural distribution)\n        container = dist.getContainer();\n        vector<double> intensities;\n        for (Size i = 0; i != container.size(); ++i)\n        {\n          intensities.push_back(container[i].second);\n        }\n        ret.push_back(make_pair(abundance, intensities));\n      }\n    }\n    else\n    {\n      // calculate isotope distribution for a given peptide and varying incoperation rates\n      // modification of isotope distribution in static ElementDB\n      for (double abundance = 0.0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)MAXISOTOPES)\n      {\n        double a = abundance / 100.0;\n        IsotopeDistribution isotopes;\n        std::vector<std::pair<Size, double> > container;\n        container.push_back(make_pair(12, 1.0 - a));\n        container.push_back(make_pair(13, a));\n        isotopes.set(container);\n        e2->setIsotopeDistribution(isotopes);\n        IsotopeDistribution dist = peptide_ef.getIsotopeDistribution(MAXISOTOPES + additional_isotopes);\n        container = dist.getContainer();\n        vector<double> intensities;\n        for (Size i = 0; i != container.size(); ++i)\n        {\n          intensities.push_back(container[i].second);\n        }\n        ret.push_back(make_pair(abundance, intensities));\n      }\n    }\n\n    // reset to natural occurance\n    IsotopeDistribution isotopes;\n    std::vector<std::pair<Size, double> > container;\n    container.push_back(make_pair(12, 0.9893));\n    container.push_back(make_pair(13, 0.0107));\n    isotopes.set(container);\n    e2->setIsotopeDistribution(isotopes);\n    return ret;\n  }\n\n  static Size getNumberOfLabelingElements(String labeling_element, const AASequence& peptide)\n  {\n    AASequence unmodified_peptide = AASequence::fromString(peptide.toUnmodifiedString());\n    EmpiricalFormula unmodified_peptide_ef = unmodified_peptide.getFormula();\n\n    if (labeling_element == \"N\")\n    {\n      const Element* e = ElementDB::getInstance()->getElement(\"Nitrogen\");\n      return (Size)unmodified_peptide_ef.getNumberOf(e);\n    }\n    else if (labeling_element == \"C\")\n    {\n      const Element* e = ElementDB::getInstance()->getElement(\"Carbon\");\n      return (Size)unmodified_peptide_ef.getNumberOf(e);\n    } else if (labeling_element == \"H\")\n    {\n      const Element* e = ElementDB::getInstance()->getElement(\"Hydrogen\");\n      return (Size)unmodified_peptide_ef.getNumberOf(e);\n    }\n    return 0;\n  }\n\n  ///> Given a peptide sequence calculate the theoretical isotopic patterns given all incorporations rate (15C Version)\n  ///> extend isotopic patterns by additional_isotopes to collect other element higher isotopes at 100% incorporation\n  static IsotopePatterns calculateIsotopePatternsFor15NRange(const AASequence& peptide, Size additional_isotopes = 5)\n  {\n    IsotopePatterns ret;\n\n    const Element* e1 = ElementDB::getInstance()->getElement(\"Nitrogen\");\n    Element* e2 = const_cast<Element*>(e1);\n\n    EmpiricalFormula peptide_ef = peptide.getFormula();\n    UInt MAXISOTOPES = (UInt)peptide_ef.getNumberOf(e1);\n\n    // calculate empirical formula of modifications - these can not be labeled via substrate feeding and must be taken care of in pattern calculation\n    AASequence unmodified_peptide = AASequence::fromString(peptide.toUnmodifiedString());\n    EmpiricalFormula unmodified_peptide_ef = unmodified_peptide.getFormula();\n    UInt max_labeling_nitrogens = (UInt)unmodified_peptide_ef.getNumberOf(e1); // max. number of nitrogen atoms that can be labeled\n    EmpiricalFormula modifications_ef = peptide_ef - unmodified_peptide_ef; // difference formula for modifications (note that it can contain positive/negative numbers)\n\n    if (modifications_ef.getNumberOf(e1) > 0) // modification adds additional (unlabeled) nitrogen atoms\n    {\n      IsotopeDistribution modification_dist = modifications_ef.getIsotopeDistribution(max_labeling_nitrogens + additional_isotopes);\n      for (double abundance = 0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)max_labeling_nitrogens)\n      {\n        double a = abundance / 100.0;\n        IsotopeDistribution isotopes;\n        std::vector<std::pair<Size, double> > container;\n        container.push_back(make_pair(14, 1.0 - a));\n        container.push_back(make_pair(15, a));\n        isotopes.set(container);\n        e2->setIsotopeDistribution(isotopes);\n        IsotopeDistribution dist = unmodified_peptide_ef.getIsotopeDistribution(max_labeling_nitrogens + additional_isotopes);\n        dist += modification_dist; // calculate convolution with isotope distribution of modification(s)\n        container = dist.getContainer();\n        vector<double> intensities;\n        for (Size i = 0; i != container.size(); ++i)\n        {\n          intensities.push_back(container[i].second);\n        }\n        ret.push_back(make_pair(abundance, intensities));\n      }\n    }\n    else\n    {\n      // calculate isotope distribution for a given peptide and varying incoperation rates\n      // modification of isotope distribution in static ElementDB\n      for (double abundance = 0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)MAXISOTOPES)\n      {\n        double a = abundance / 100.0;\n        IsotopeDistribution isotopes;\n        std::vector<std::pair<Size, double> > container;\n        container.push_back(make_pair(14, 1.0 - a));\n        container.push_back(make_pair(15, a));\n        isotopes.set(container);\n        e2->setIsotopeDistribution(isotopes);\n        IsotopeDistribution dist = peptide_ef.getIsotopeDistribution(MAXISOTOPES + additional_isotopes);\n        container = dist.getContainer();\n        vector<double> intensities;\n        for (Size i = 0; i != container.size(); ++i)\n        {\n          intensities.push_back(container[i].second);\n        }\n        ret.push_back(make_pair(abundance, intensities));\n      }\n    }\n    // reset to natural occurance\n    IsotopeDistribution isotopes;\n    std::vector<std::pair<Size, double> > container;\n    container.push_back(make_pair(14, 0.99632));\n    container.push_back(make_pair(15, 0.368));\n    isotopes.set(container);\n    e2->setIsotopeDistribution(isotopes);\n    return ret;\n  }\n\n  static IsotopePatterns calculateIsotopePatternsFor2HRange(const AASequence& peptide, Size additional_isotopes = 5)\n  {\n    IsotopePatterns ret;\n\n    const Element* e1 = ElementDB::getInstance()->getElement(\"Hydrogen\");\n    Element* e2 = const_cast<Element*>(e1);\n\n    EmpiricalFormula peptide_ef = peptide.getFormula();\n    Size MAXISOTOPES = (Size)peptide_ef.getNumberOf(e1);\n\n    // calculate empirical formula of modifications - these can not be labeled via substrate feeding and must be taken care of in pattern calculation\n    AASequence unmodified_peptide = AASequence::fromString(peptide.toUnmodifiedString());\n    EmpiricalFormula unmodified_peptide_ef = unmodified_peptide.getFormula();\n    UInt max_labeling_element = (UInt)unmodified_peptide_ef.getNumberOf(e1); // max. number of atoms that can be labeled\n    EmpiricalFormula modifications_ef = peptide_ef - unmodified_peptide_ef; // difference formula for modifications (note that it can contain positive/negative numbers)\n\n    if (modifications_ef.getNumberOf(e1) > 0) // modification adds additional (unlabeled) atoms\n    {\n      IsotopeDistribution modification_dist = modifications_ef.getIsotopeDistribution(max_labeling_element + additional_isotopes);\n      for (double abundance = 0.0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)max_labeling_element)\n      {\n        double a = abundance / 100.0;\n        IsotopeDistribution isotopes;\n        std::vector<std::pair<Size, double> > container;\n        container.push_back(make_pair(1, 1.0 - a));\n        container.push_back(make_pair(2, a));\n        isotopes.set(container);\n        e2->setIsotopeDistribution(isotopes);\n        IsotopeDistribution dist = unmodified_peptide_ef.getIsotopeDistribution(max_labeling_element + additional_isotopes);\n        dist += modification_dist; // convole with modification distribution (which follows the natural distribution)\n        container = dist.getContainer();\n        vector<double> intensities;\n        for (Size i = 0; i != container.size(); ++i)\n        {\n          intensities.push_back(container[i].second);\n        }\n        ret.push_back(make_pair(abundance, intensities));\n      }\n    }\n    else\n    {\n      // calculate isotope distribution for a given peptide and varying incoperation rates\n      // modification of isotope distribution in static ElementDB\n      for (double abundance = 0.0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)MAXISOTOPES)\n      {\n        double a = abundance / 100.0;\n        IsotopeDistribution isotopes;\n        std::vector<std::pair<Size, double> > container;\n        container.push_back(make_pair(1, 1.0 - a));\n        container.push_back(make_pair(2, a));\n        isotopes.set(container);\n        e2->setIsotopeDistribution(isotopes);\n        IsotopeDistribution dist = peptide_ef.getIsotopeDistribution(MAXISOTOPES + additional_isotopes);\n        container = dist.getContainer();\n        vector<double> intensities;\n        for (Size i = 0; i != container.size(); ++i)\n        {\n          intensities.push_back(container[i].second);\n        }\n        ret.push_back(make_pair(abundance, intensities));\n      }\n    }\n\n    // reset to natural occurance\n    IsotopeDistribution isotopes;\n    std::vector<std::pair<Size, double> > container;\n    container.push_back(make_pair(1, 0.999885));\n    container.push_back(make_pair(2, 0.000115));\n    isotopes.set(container);\n    e2->setIsotopeDistribution(isotopes);\n    return ret;\n  }\n\n  static IsotopePatterns calculateIsotopePatternsFor15NRangeOfAveraginePeptide(double mass)\n  {\n    IsotopePatterns ret;\n    const Element* e1 = ElementDB::getInstance()->getElement(\"Nitrogen\");\n    Element* e2 = const_cast<Element*>(e1);\n\n    // calculate number of expected labeling elements using averagine model\n    Size element_count = mass * 0.0122177302837372;\n\n    // calculate isotope distribution for a given peptide and varying incoperation rates\n    // modification of isotope distribution in static ElementDB\n    for (double abundance = 0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)element_count)\n    {\n      double a = abundance / 100.0;\n      IsotopeDistribution isotopes;\n      std::vector<std::pair<Size, double> > container;\n      container.push_back(make_pair(14, 1.0 - a));\n      container.push_back(make_pair(15, a));\n      isotopes.set(container);\n      e2->setIsotopeDistribution(isotopes);\n      IsotopeDistribution dist(element_count);\n      dist.estimateFromPeptideWeight(mass);\n      container = dist.getContainer();\n      vector<double> intensities;\n      for (Size i = 0; i != container.size(); ++i)\n      {\n        intensities.push_back(container[i].second);\n      }\n      ret.push_back(make_pair(abundance, intensities));\n    }\n\n    // reset to natural occurance\n    IsotopeDistribution isotopes;\n    std::vector<std::pair<Size, double> > container;\n    container.push_back(make_pair(14, 0.99632));\n    container.push_back(make_pair(15, 0.368));\n    isotopes.set(container);\n    e2->setIsotopeDistribution(isotopes);\n    return ret;\n  }\n\n  static IsotopePatterns calculateIsotopePatternsFor13CRangeOfAveraginePeptide(double mass)\n  {\n    IsotopePatterns ret;\n\n    const Element* e1 = ElementDB::getInstance()->getElement(\"Carbon\");\n    Element* e2 = const_cast<Element*>(e1);\n    Size element_count = mass * 0.0444398894906044;\n\n    // calculate isotope distribution for a given peptide and varying incoperation rates\n    // modification of isotope distribution in static ElementDB\n    for (double abundance = 0.0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)element_count)\n    {\n      double a = abundance / 100.0;\n      IsotopeDistribution isotopes;\n      std::vector<std::pair<Size, double> > container;\n      container.push_back(make_pair(12, 1.0 - a));\n      container.push_back(make_pair(13, a));\n      isotopes.set(container);\n      e2->setIsotopeDistribution(isotopes);\n      IsotopeDistribution dist(element_count);\n      dist.estimateFromPeptideWeight(mass);\n      container = dist.getContainer();\n      vector<double> intensities;\n      for (Size i = 0; i != container.size(); ++i)\n      {\n        intensities.push_back(container[i].second);\n      }\n      ret.push_back(make_pair(abundance, intensities));\n    }\n\n    // reset to natural occurance\n    IsotopeDistribution isotopes;\n    std::vector<std::pair<Size, double> > container;\n    container.push_back(make_pair(12, 0.9893));\n    container.push_back(make_pair(13, 0.0107));\n    isotopes.set(container);\n    e2->setIsotopeDistribution(isotopes);\n    return ret;\n  }\n\n  static IsotopePatterns calculateIsotopePatternsFor2HRangeOfAveraginePeptide(double mass)\n  {\n    IsotopePatterns ret;\n\n    const Element* e1 = ElementDB::getInstance()->getElement(\"Hydrogen\");\n    Element* e2 = const_cast<Element*>(e1);\n    Size element_count = mass * 0.06981572169;\n\n    // calculate isotope distribution for a given peptide and varying incoperation rates\n    // modification of isotope distribution in static ElementDB\n    for (double abundance = 0.0; abundance < 100.0 - 1e-8; abundance += 100.0 / (double)element_count)\n    {\n      double a = abundance / 100.0;\n      IsotopeDistribution isotopes;\n      std::vector<std::pair<Size, double> > container;\n      container.push_back(make_pair(1, 1.0 - a));\n      container.push_back(make_pair(2, a));\n      isotopes.set(container);\n      e2->setIsotopeDistribution(isotopes);\n      IsotopeDistribution dist(element_count);\n      dist.estimateFromPeptideWeight(mass);\n      container = dist.getContainer();\n      vector<double> intensities;\n      for (Size i = 0; i != container.size(); ++i)\n      {\n        intensities.push_back(container[i].second);\n      }\n      ret.push_back(make_pair(abundance, intensities));\n    }\n\n    // reset to natural occurance\n    IsotopeDistribution isotopes;\n    std::vector<std::pair<Size, double> > container;\n    container.push_back(make_pair(1, 0.999885));\n    container.push_back(make_pair(2, 0.000115));\n    isotopes.set(container);\n    e2->setIsotopeDistribution(isotopes);\n    return ret;\n  }\n};\n\nclass MetaProSIPXICExtraction\n{\npublic:\n  static vector<vector<double> > extractXICs(double seed_rt, vector<double> xic_mzs, double mz_toelrance_ppm, double rt_tolerance_s, const MSExperiment<Peak1D>& peak_map)\n  {\n    // point on first spectrum in tolerance window\n    MSExperiment<>::ConstIterator rt_begin = peak_map.RTBegin(seed_rt - rt_tolerance_s);\n\n    // point on after last spectrum in tolerance window\n    MSExperiment<>::ConstIterator rt_end = peak_map.RTBegin(seed_rt + rt_tolerance_s);\n\n    // create set containing all rts of spectra in tolerance window\n    set<double> all_rts;\n    for (MSExperiment<>::ConstIterator rt_it = rt_begin; rt_it != rt_end; ++rt_it)\n    {\n      all_rts.insert(rt_it->getRT());\n    }\n\n    vector<vector<double> > xics(xic_mzs.size(), vector<double>());\n\n    for (Size i = 0; i < xic_mzs.size(); ++i)\n    {\n      // create and initialize xic to contain values for all rts\n      map<double, double> xic; // rt to summed intensity\n      for (set<double>::const_iterator sit = all_rts.begin(); sit != all_rts.end(); ++sit)\n      {\n        xic[*sit] = 0;\n      }\n\n      double mz_da = mz_toelrance_ppm * xic_mzs[i] * 1e-6; // mz tolerance in Dalton\n      MSExperiment<>::ConstAreaIterator it = peak_map.areaBeginConst(seed_rt - rt_tolerance_s, seed_rt + rt_tolerance_s, xic_mzs[i] - mz_da, xic_mzs[i] + mz_da);\n\n      for (; it != peak_map.areaEndConst(); ++it)\n      {\n        double rt = it.getRT();\n        if (xic.find(rt) != xic.end())\n        {\n          xic[rt] += it->getIntensity();\n        }\n        else\n        {\n          LOG_WARN << \"RT: \" << rt << \" not contained in rt set.\" << endl;\n        }\n      }\n\n      // copy map to vector for easier processing\n      vector<double> v;\n      for (map<double, double>::const_iterator it = xic.begin(); it != xic.end(); ++it)\n      {\n        v.push_back(it->second);\n      }\n\n      xics[i] = v;\n    }\n    return xics;\n  }\n\n  static vector<double> correlateXICsToMono(const vector<vector<double> >& xics)\n  {\n    vector<double> rrs(xics.size(), 0); // correlation of isotopic xics to monoisotopic xic\n\n    rrs[0] = 1.0; // perfect correlation of monoisotopic trace to itself\n\n    for (Size i = 1; i < xics.size(); ++i)\n    {\n      rrs[i] = Math::pearsonCorrelationCoefficient(xics[0].begin(), xics[0].end(), xics[i].begin(), xics[i].end());\n    }\n    return rrs;\n  }\n\n  static vector<double> extractXICsOfIsotopeTraces(Size element_count, double mass_diff, double mz_tolerance_ppm, double rt_tolerance_s, double seed_rt, double seed_mz, double seed_charge, const MSExperiment<Peak1D>& peak_map, const double min_corr_mono = -1.0)\n  {\n    vector<double> xic_mzs;\n\n    // calculate centers of XICs to be extracted\n    for (Size k = 0; k != element_count; ++k)\n    {\n      double mz = seed_mz + k * mass_diff / seed_charge;\n      xic_mzs.push_back(mz);\n    }\n\n    // extract xics\n    vector<vector<double> > xics = extractXICs(seed_rt, xic_mzs, mz_tolerance_ppm, rt_tolerance_s, peak_map);\n\n    vector<double> xic_intensities(xics.size(), 0.0);\n    if (min_corr_mono > 0)\n    {\n      // calculate correlation to mono-isotopic peak\n      vector<double> RRs = correlateXICsToMono(xics);\n\n      // sum over XICs to yield one intensity value for each XIC. If correlation to mono-isotopic is lower then threshold, delete intensity.\n      for (Size i = 0; i != xic_intensities.size(); ++i)\n      {\n        double v = std::accumulate(xics[i].begin(), xics[i].end(), 0.0);\n        xic_intensities[i] = RRs[i] > min_corr_mono ? v : 0.0;\n      }\n    }\n    else // correlation disabled so just take the XIC intensities\n    {\n      for (Size i = 0; i != xic_intensities.size(); ++i)\n      {\n        xic_intensities[i] = std::accumulate(xics[i].begin(), xics[i].end(), 0.0);\n      }\n    }\n\n    return xic_intensities;\n  }\n\n};\n\nclass RIntegration\n{\npublic:\n  // Perform a simple check if R and all R dependencies are thereget\n  static bool checkRDependencies(String tmp_path, StringList package_names)\n  {\n    String random_name = String::random(8);\n    String script_filename = tmp_path + String(\"/\") + random_name + String(\".R\");\n\n    // check if R in path and can be executed\n    TextFile checkRInPath;\n    checkRInPath.addLine(\"q()\");\n    checkRInPath.store(script_filename);\n\n    LOG_INFO << \"Checking R...\";\n    {\n      QProcess p;\n      p.setProcessChannelMode(QProcess::MergedChannels);\n      QStringList env = QProcess::systemEnvironment();\n      env << QString(\"R_LIBS=\") + tmp_path.toQString();\n      p.setEnvironment(env);\n\n      QStringList checkRinPathQParam;\n      checkRinPathQParam << \"--vanilla\" << \"--quiet\" << \"--slave\" << \"--file=\" + script_filename.toQString();\n      p.start(\"R\", checkRinPathQParam);\n      p.waitForFinished(-1);\n\n      if (p.error() == QProcess::FailedToStart || p.exitStatus() == QProcess::CrashExit || p.exitCode() != 0)\n      {\n        LOG_INFO << \" failed\" << std::endl;\n        LOG_ERROR << \"Can't execute R. Do you have R installed? Check if the path to R is in your system path variable.\" << std::endl;\n        return false;\n      }\n      LOG_INFO << \" success\" << std::endl;\n    }\n    // check dependencies\n    LOG_INFO << \"Checking R dependencies. If package is not found we will try to install it in your temp directory...\";\n    TextFile current_script;\n    current_script.addLine(\"LoadOrInstallPackage <-function(x)\");\n    current_script.addLine(\"{\");\n    current_script.addLine(\"  x <-as.character(substitute(x))\");\n    current_script.addLine(\"  if (isTRUE(x %in%.packages(all.available = TRUE)))\");\n    current_script.addLine(\"  {\");\n    current_script.addLine(\"    eval(parse(text = paste(\\\"library(\\\", x, \\\")\\\", sep = \\\"\\\")))\");\n    current_script.addLine(\"  }\");\n    current_script.addLine(\"  else\");\n    current_script.addLine(\"  {\");\n    current_script.addLine(\"    options(repos = structure(c(CRAN = \\\"http://cran.rstudio.com/\\\")))\");\n    current_script.addLine(\"    update.packages()\");\n    current_script.addLine(\"    eval(parse(text = paste(\\\"install.packages('\\\", x, \\\"')\\\", sep = \\\"\\\")))\");\n    current_script.addLine(\"    eval(parse(text = paste(\\\"library(\\\", x, \\\")\\\", sep = \\\"\\\")))\");\n    current_script.addLine(\"  }\");\n    current_script.addLine(\"}\");\n    for (StringList::const_iterator it = package_names.begin(); it != package_names.end(); ++it)\n    {\n      current_script.addLine(\"LoadOrInstallPackage(\" + *it + \")\");\n    }\n\n    current_script.store(script_filename);\n\n    QProcess p;\n    p.setProcessChannelMode(QProcess::MergedChannels);\n    QStringList env = QProcess::systemEnvironment();\n    env << QString(\"R_LIBS=\") + tmp_path.toQString();\n    p.setEnvironment(env);\n\n    QStringList qparam;\n    qparam << \"--vanilla\" << \"--quiet\" << \"--slave\" << \"--file=\" + script_filename.toQString();\n    p.start(\"R\", qparam);\n    p.waitForFinished(-1);\n    int status = p.exitCode();\n\n    if (status != 0)\n    {\n      LOG_ERROR << \"\\nProblem finding all R dependencies. Check if R and following libraries are installed:\" << std::endl;\n      for (TextFile::ConstIterator line_it = current_script.begin(); line_it != current_script.end(); ++line_it)\n      {\n        LOG_ERROR << *line_it  << std::endl;\n      }\n      QString s = p.readAllStandardOutput();\n      LOG_ERROR << s.toStdString() << std::endl;\n      return false;\n    }\n    LOG_INFO << \" success\" << std::endl;\n    return true;\n  }\n\n};\n\nclass TOPPMetaProSIP :\n  public TOPPBase\n{\npublic:\n  TOPPMetaProSIP()\n    : TOPPBase(\"MetaProSIP\", \"Performs proteinSIP on peptide features for elemental flux analysis.\", false),\n    ADDITIONAL_ISOTOPES(5),\n    FEATURE_STRING(\"feature\"),\n    UNASSIGNED_ID_STRING(\"id\"),\n    UNIDENTIFIED_STRING(\"unidentified\")\n  {\n  }\n\nprotected:\n  Size ADDITIONAL_ISOTOPES;\n  std::string FEATURE_STRING;\n  std::string UNASSIGNED_ID_STRING;\n  std::string UNIDENTIFIED_STRING;\n  void registerOptionsAndFlags_()\n  {\n    registerInputFile_(\"in_mzML\", \"<file>\", \"\", \"Centroided MS1 data\");\n    setValidFormats_(\"in_mzML\", ListUtils::create<String>(\"mzML\"));\n\n    registerInputFile_(\"in_fasta\", \"<file>\", \"\", \"Protein sequence database\");\n    setValidFormats_(\"in_fasta\", ListUtils::create<String>(\"fasta\"));\n\n    registerOutputFile_(\"out_csv\", \"<file>\", \"\", \"Column separated file with feature fitting result.\");\n    setValidFormats_(\"out_csv\", ListUtils::create<String>(\"csv\"));\n\n    registerOutputFile_(\"out_peptide_centric_csv\", \"<file>\", \"\", \"Column separated file with peptide centric result.\");\n    setValidFormats_(\"out_peptide_centric_csv\", ListUtils::create<String>(\"csv\"));\n\n    registerInputFile_(\"in_featureXML\", \"<file>\", \"\", \"Feature data annotated with identifications (IDMapper)\");\n    setValidFormats_(\"in_featureXML\", ListUtils::create<String>(\"featureXML\"));\n\n    registerDoubleOption_(\"mz_tolerance_ppm\", \"<tol>\", 10.0, \"Tolerance in ppm\", false);\n\n    registerDoubleOption_(\"rt_tolerance_s\", \"<tol>\", 30.0, \"Rolerance window around feature rt for XIC extraction\", false);\n\n    registerDoubleOption_(\"intensity_threshold\", \"<tol>\", 10.0, \"Intensity threshold to collect peaks in the MS1 spectrum.\", false);\n\n    registerDoubleOption_(\"correlation_threshold\", \"<tol>\", 0.7, \"Correlation threshold for reporting a RIA\", false);\n\n    registerDoubleOption_(\"xic_threshold\", \"<tol>\", 0.7, \"Minimum correlation to mono-isotopic peak for retaining a higher isotopic peak. If featureXML from reference file is used it should be disabled (set to -1) as no mono-isotopic peak is expected to be present.\", false);\n\n    registerDoubleOption_(\"decomposition_threshold\", \"<tol>\", 0.7, \"Minimum R\u00b2 of decomposition that must be achieved for a peptide to be reported.\", false);\n\n    registerDoubleOption_(\"weight_merge_window\", \"<tol>\", 5.0, \"Decomposition coefficients within +- this rate window will be combined\", false);\n\n    registerDoubleOption_(\"min_correlation_distance_to_averagine\", \"<tol>\", -1.0, \"Minimum difference in correlation between incorporation pattern and averagine pattern. Positive values filter all RIAs passing the correlation threshold but that also show a better correlation to an averagine peptide. Disabled for values <= -1\", false, true);\n\n    registerDoubleOption_(\"pattern_15N_TIC_threshold\", \"<threshold>\", 0.95, \"The most intense peaks of the theoretical pattern contributing to at least this TIC fraction are taken into account.\", false, true);\n    registerDoubleOption_(\"pattern_13C_TIC_threshold\", \"<threshold>\", 0.95, \"The most intense peaks of the theoretical pattern contributing to at least this TIC fraction are taken into account.\", false, true);\n    registerDoubleOption_(\"pattern_2H_TIC_threshold\", \"<threshold>\", 0.95, \"The most intense peaks of the theoretical pattern contributing to at least this TIC fraction are taken into account.\", false, true);\n    registerIntOption_(\"heatmap_bins\", \"<threshold>\", 20, \"Number of RIA bins for heat map generation.\", false, true);\n\n    registerStringOption_(\"plot_extension\", \"<extension>\", \"png\", \"Extension used for plots (png|svg|pdf).\", false);\n    StringList valid_extensions;\n    valid_extensions.push_back(\"png\");\n    valid_extensions.push_back(\"svg\");\n    valid_extensions.push_back(\"pdf\");\n    setValidStrings_(\"plot_extension\", valid_extensions);\n\n    registerStringOption_(\"qc_output_directory\", \"<directory>\", \"\", \"Output directory for the quality report\", false);\n\n    registerStringOption_(\"labeling_element\", \"<parameter>\", \"C\", \"Which element (single letter code) is labeled.\", false);\n    StringList valid_element;\n    valid_element.push_back(\"C\");\n    valid_element.push_back(\"N\");\n    valid_element.push_back(\"H\");\n    setValidStrings_(\"labeling_element\", valid_element);\n\n    registerFlag_(\"use_unassigned_ids\", \"Include identifications not assigned to a feature in pattern detection.\", false);\n\n    registerFlag_(\"use_averagine_ids\", \"Use averagine peptides as model to perform pattern detection on unidentified peptides.\", false);\n\n    registerFlag_(\"report_natural_peptides\", \"Whether purely natural peptides are reported in the quality report.\", false);\n\n    registerFlag_(\"filter_monoisotopic\", \"Try to filter out mono-isotopic patterns to improve detection of low RIA patterns\", false);\n\n    registerFlag_(\"cluster\", \"Perform grouping\", false);\n\n    registerDoubleOption_(\"observed_peak_fraction\", \"<threshold>\", 0.5, \"Fraction of observed/expected peaks.\", false, true);\n\n    registerIntOption_(\"min_consecutive_isotopes\", \"<threshold>\", 2, \"Minimum number of consecutive isotopic intensities needed.\", false, true);\n\n    registerDoubleOption_(\"score_plot_yaxis_min\", \"<threshold>\", 0.0, \"The minimum value of the score axis. Values smaller than zero usually only make sense if the observed peak fraction is set to 0.\", false, true);\n\n    registerStringOption_(\"collect_method\", \"<method>\", \"correlation_maximum\", \"How RIAs are collected.\", false, true);\n    StringList valid_collect_method;\n    valid_collect_method.push_back(\"correlation_maximum\");\n    valid_collect_method.push_back(\"decomposition_maximum\");\n    setValidStrings_(\"collect_method\", valid_collect_method);\n\n    registerDoubleOption_(\"lowRIA_correlation_threshold\", \"<tol>\", -1, \"Correlation threshold for reporting low RIA patterns. Disable and take correlation_threshold value for negative values.\", false, true);\n  }\n\n  ///> filter intensity to remove noise or additional incorporation peaks that otherwise might interfere with correlation calculation\n  void filterIsotopicIntensities(vector<double>::const_iterator& pattern_begin, vector<double>::const_iterator& pattern_end,\n                                 vector<double>::const_iterator& intensities_begin, vector<double>::const_iterator& intensities_end, double TIC_threshold = 0.99)\n  {\n    if (std::distance(pattern_begin, pattern_end) != std::distance(intensities_begin, intensities_end))\n    {\n      LOG_ERROR << \"Error: size of pattern and collected intensities don't match!: (pattern \" << std::distance(pattern_begin, pattern_end) << \") (intensities \" << std::distance(intensities_begin, intensities_end) << \")\" << endl;\n    }\n\n    if (pattern_begin == pattern_end)\n    {\n      return;\n    }\n\n    // determine order of peaks based on intensities\n    vector<double>::const_iterator b_it = pattern_begin;\n    vector<double>::const_iterator e_it = pattern_end;\n    // create intensity to offset map for sorting\n    vector<std::pair<double, Int> > intensity_to_offset;\n    for (; b_it != e_it; ++b_it)\n    {\n      std::pair<double, Int> intensity_offset_pair = make_pair(*b_it, std::distance(pattern_begin, b_it));\n      intensity_to_offset.push_back(intensity_offset_pair); // pair: intensity, offset to pattern_begin iterator\n    }\n    // sort by intensity (highest first)\n    std::sort(intensity_to_offset.begin(), intensity_to_offset.end(), std::greater<pair<double, Int> >());\n\n    // determine sequence of (neighbouring) peaks needed to achieve threshold * 100 % TIC in the patterns\n    double TIC = 0.0;\n    Int min_offset = std::distance(pattern_begin, pattern_end);\n    Int max_offset = 0;\n\n    for (vector<std::pair<double, Int> >::const_iterator it = intensity_to_offset.begin(); it != intensity_to_offset.end(); ++it)\n    {\n      TIC += it->first;\n      if (it->second < min_offset)\n      {\n        min_offset = it->second;\n      }\n\n      if (it->second > max_offset)\n      {\n        max_offset = it->second;\n      }\n\n      if (TIC > TIC_threshold)\n      {\n        break;\n      }\n    }\n\n    vector<double>::const_iterator tmp_pattern_it(pattern_begin);\n    vector<double>::const_iterator tmp_intensity_it(intensities_begin);\n\n    std::advance(pattern_begin, min_offset);\n    std::advance(intensities_begin, min_offset);\n    std::advance(tmp_pattern_it, max_offset + 1);\n    std::advance(tmp_intensity_it, max_offset + 1);\n\n    pattern_end = tmp_pattern_it;\n    intensities_end = tmp_intensity_it;\n\n    //cout << \"after: \" << std::distance(pattern_begin, pattern_end) << \" \" << min_offset << \" \" << max_offset << endl;\n  }\n\n  ///< Calculates the correlation between measured isotopic_intensities and the theoretical isotopic patterns for all incorporation rates\n  void calculateCorrelation(Size n_element, const vector<double>& isotopic_intensities, IsotopePatterns patterns,\n                            MapRateToScoreType& map_rate_to_correlation_score, String labeling_element, double mass, double min_correlation_distance_to_averagine)\n  {\n    double min_observed_peak_fraction = getDoubleOption_(\"observed_peak_fraction\");\n\n    LOG_INFO << \"Calculating \" << patterns.size() << \" isotope patterns with \" << ADDITIONAL_ISOTOPES << \" additional isotopes.\" << endl;\n\n    double TIC_threshold(0.0);\n    \n    // N15 has smaller RIA resolution and multiple RIA peaks tend to overlap more in correlation. This reduces the width of the pattern leading to better distinction\n    if (labeling_element == \"N\")\n    {\n      TIC_threshold = getDoubleOption_(\"pattern_15N_TIC_threshold\");\n    } else if (labeling_element == \"C\")\n    {\n      TIC_threshold = getDoubleOption_(\"pattern_13C_TIC_threshold\");\n    } else if (labeling_element == \"H\")\n    {\n      TIC_threshold = getDoubleOption_(\"pattern_2H_TIC_threshold\");\n    }\n\n    double max_incorporation_rate = 100.0;\n    double incorporation_step = max_incorporation_rate / (double)n_element;\n\n    // calculate correlation with a natural averagine peptide (used to filter out coeluting peptides)\n    double peptide_weight = mass;\n\n    const Size AVERAGINE_CORR_OFFSET = 3;\n\n    // calculate correlation for averagine peptides\n    std::vector<double> averagine_correlation(isotopic_intensities.size(), 0.0);\n\n    // extended by zeros on both sides to simplify correlation\n    vector<double> ext_isotopic_intensities(AVERAGINE_CORR_OFFSET, 0.0);\n    ext_isotopic_intensities.insert(ext_isotopic_intensities.end(), isotopic_intensities.begin(), isotopic_intensities.end());\n    for (Size i = 0; i != AVERAGINE_CORR_OFFSET; ++i)\n    {\n      ext_isotopic_intensities.push_back(0.0);\n    }\n\n    for (Size ii = 0; ii < isotopic_intensities.size(); ++ii)\n    {\n      // calculate isotope distribution of averagine peptide as this will be used to detect spurious correlations with coeluting peptides\n      // Note: actually it would be more accurate to use 15N-14N or 13C-12C distances. This doesn't affect averagine distribution much so this approximation is sufficient. (see TODO)\n      double current_weight = peptide_weight + ii * 1.0; // TODO: use 13C-12C or 15N-14N instead of 1.0 as mass distance to be super accurate\n      IsotopeDistribution averagine = IsotopeDistribution(10);\n      averagine.estimateFromPeptideWeight(current_weight);\n\n      std::vector<std::pair<Size, double> > averagine_intensities_pairs = averagine.getContainer();\n\n      // zeros to the left for sliding window correlation\n      std::vector<double> averagine_intensities(AVERAGINE_CORR_OFFSET, 0.0); // add 0 intensity bins left to actual averagine pattern\n\n      for (Size i = 0; i != averagine_intensities_pairs.size(); ++i)\n      {\n        averagine_intensities.push_back(averagine_intensities_pairs[i].second);\n      }\n\n      // zeros to the right\n      for (Size i = 0; i != AVERAGINE_CORR_OFFSET; ++i)\n      {\n        averagine_intensities.push_back(0.0);\n      }\n\n      // number of bins that can be correlated\n      Int max_correlated_values = std::min((int)ext_isotopic_intensities.size() - ii, averagine_intensities.size());\n\n      double corr_with_averagine = Math::pearsonCorrelationCoefficient(averagine_intensities.begin(), averagine_intensities.begin() + max_correlated_values,\n                                                                       ext_isotopic_intensities.begin() + ii, ext_isotopic_intensities.begin() + ii + max_correlated_values);\n      averagine_correlation[ii] = corr_with_averagine;\n    }\n\n    // calculate correlation of RIA peptide with measured data\n    for (Size ii = 0; ii != patterns.size(); ++ii)\n    {\n      double rate = (double)ii * incorporation_step;\n\n      vector<double>::const_iterator pattern_begin = patterns[ii].second.begin();\n      vector<double>::const_iterator pattern_end = patterns[ii].second.end();\n      vector<double>::const_iterator intensities_begin = isotopic_intensities.begin();\n      vector<double>::const_iterator intensities_end = isotopic_intensities.end();\n\n      filterIsotopicIntensities(pattern_begin, pattern_end, intensities_begin, intensities_end, TIC_threshold);\n      Size zeros = 0;\n      for (vector<double>::const_iterator it = intensities_begin; it != intensities_end; ++it)\n      {\n        if (*it < 1e-8)\n        {\n          zeros++;\n        }\n      }\n\n      // remove correlations with only very few peaks\n      if ((double)zeros / (double)std::distance(intensities_begin, intensities_end) > min_observed_peak_fraction)\n      {\n        map_rate_to_correlation_score[rate] = 0;\n        continue;\n      }\n\n      double correlation_score = Math::pearsonCorrelationCoefficient(pattern_begin, pattern_end, intensities_begin, intensities_end);\n\n      // remove correlations that show higher similarity to an averagine peptide\n      if (rate > 5.0 && correlation_score < averagine_correlation[ii] + min_correlation_distance_to_averagine)\n      {\n        map_rate_to_correlation_score[rate] = 0;\n        continue;\n      }\n\n      // cout << ii << \"\\t\" << std::distance(intensities_end, intensities_begin) << \"\\t\" << std::distance(intensities_begin, isotopic_intensities.begin()) << \"\\t\" << std::distance(intensities_end, isotopic_intensities.begin()) << endl;\n      if (boost::math::isnan(correlation_score))\n      {\n        correlation_score = 0.0;\n      }\n      map_rate_to_correlation_score[rate] = correlation_score;\n    }\n  }\n\n  ///< Returns highest scoring rate and score pair in the map\n  void getBestRateScorePair(const MapRateToScoreType& map_rate_to_score, double& best_rate, double& best_score)\n  {\n    best_score = -1;\n    for (MapRateToScoreType::const_iterator mit = map_rate_to_score.begin(); mit != map_rate_to_score.end(); ++mit)\n    {\n      if (mit->second > best_score)\n      {\n        best_score = mit->second;\n        best_rate = mit->first;\n      }\n    }\n  }\n\n  PeakSpectrum extractPeakSpectrum(Size element_count, double mass_diff, double rt, double feature_hit_theoretical_mz, Int feature_hit_charge, const MSExperiment<>& peak_map)\n  {\n    PeakSpectrum spec = *peak_map.RTBegin(rt - 1e-8);\n    PeakSpectrum::ConstIterator begin_it = spec.MZBegin(feature_hit_theoretical_mz - 1e-8);\n    PeakSpectrum::ConstIterator end_it = spec.MZEnd(feature_hit_theoretical_mz + element_count * mass_diff / feature_hit_charge + 1e-8);\n\n    PeakSpectrum ret;\n    for (; begin_it != end_it; ++begin_it)\n    {\n      if (begin_it->getIntensity() > 1e-8)\n      {\n        ret.push_back(*begin_it);\n      }\n    }\n    return ret;\n  }\n\n  // collects intensities starting at seed_mz/_rt, if no peak is found at the expected position a 0 is added\n  vector<double> extractIsotopicIntensities(Size element_count, double mass_diff, double mz_tolerance_ppm,\n                                            double seed_rt, double seed_mz, double seed_charge,\n                                            const MSExperiment<Peak1D>& peak_map)\n  {\n    vector<double> isotopic_intensities;\n    for (Size k = 0; k != element_count; ++k)\n    {\n      double min_rt = seed_rt - 0.01; // feature rt\n      double max_rt = seed_rt + 0.01;\n      double mz = seed_mz + k * mass_diff / seed_charge;\n\n      double min_mz;\n      double max_mz;\n\n      if (k <= 5)\n      {\n        double ppm = std::max(10.0, mz_tolerance_ppm); // restrict ppm to 10 for low intensity peaks\n        min_mz = mz - mz * ppm * 1e-6;\n        max_mz = mz + mz * ppm * 1e-6;\n      }\n      else\n      {\n        min_mz = mz - mz * mz_tolerance_ppm * 1e-6;\n        max_mz = mz + mz * mz_tolerance_ppm * 1e-6;\n      }\n\n      double found_peak_int = 0;\n\n      MSExperiment<Peak1D>::ConstAreaIterator aait = peak_map.areaBeginConst(min_rt, max_rt, min_mz, max_mz);\n\n      // find 13C/15N peak in window around theoretical predicted position\n      vector<double> found_peaks;\n      for (; aait != peak_map.areaEndConst(); ++aait)\n      {\n        double peak_int = aait->getIntensity();\n        if (peak_int > 1) // we found a valid 13C/15N peak\n        {\n          found_peaks.push_back(peak_int);\n        }\n      }\n\n      found_peak_int = std::accumulate(found_peaks.begin(), found_peaks.end(), 0);\n\n      // assign peak intensity to first peak in small area around theoretical predicted position (should be usually only be 1)\n      isotopic_intensities.push_back(found_peak_int);\n    }\n    return isotopic_intensities;\n  }\n\n  void writePeakIntensities_(SVOutStream& out_stream, vector<double> isotopic_intensities, bool write_13Cpeaks)\n  {\n    double intensities_sum_12C = 0.0;\n    // calculate 12C summed intensity\n    for (Size k = 0; k != 5; ++k)\n    {\n      if (k >= isotopic_intensities.size())\n      {\n        break;\n      }\n      intensities_sum_12C += isotopic_intensities[k];\n    }\n\n    // determine 13C peaks and summed intensity\n    double intensities_sum_13C = 0;\n    for (Size u = 5; u < isotopic_intensities.size(); ++u)\n    {\n      intensities_sum_13C += isotopic_intensities[u];\n    }\n\n    String int_string;\n    // print 12C peaks\n    for (Size u = 0; u != 5; ++u)\n    {\n      if (u == isotopic_intensities.size())\n      {\n        break;\n      }\n      int_string += String::number(isotopic_intensities[u], 0);\n      int_string += \" \";\n    }\n    int_string += \", \";\n\n    if (write_13Cpeaks)\n    {\n      // print 13C peaks\n      for (Size u = 5; u < isotopic_intensities.size(); ++u)\n      {\n        int_string += String::number(isotopic_intensities[u], 0);\n        if (u < isotopic_intensities.size() - 1)\n        {\n          int_string += \" \";\n        }\n      }\n      out_stream << int_string;\n\n      double ratio = 0.0;\n      if (intensities_sum_12C + intensities_sum_13C > 0.0000001)\n      {\n        ratio = intensities_sum_13C / (intensities_sum_12C + intensities_sum_13C);\n      }\n      out_stream << ratio; // << skewness(intensities_13C.begin(), intensities_13C.end());\n\n    }\n    else // bad correlation, no need to print intensities, ratio etc.\n    {\n      String int_string;\n\n      int_string += \"\\t\";\n      int_string += \"\\t\";\n      out_stream << int_string;\n    }\n  }\n\n  // scores smaller than 0 will be paddde to 0\n  MapRateToScoreType normalizeToMax(const MapRateToScoreType& map_rate_to_decomposition_weight)\n  {\n    // extract heightest weight (best score) and rate\n    double best_rate, best_score;\n    getBestRateScorePair(map_rate_to_decomposition_weight, best_rate, best_score);\n\n    if (debug_level_ >= 10)\n    {\n      LOG_DEBUG << \"best rate + score: \" << best_rate << \" \" << best_score << endl;\n    }\n\n    // normalize weights to max(weights)=1\n    MapRateToScoreType map_weights_norm(map_rate_to_decomposition_weight);\n    for (MapRateToScoreType::iterator mit = map_weights_norm.begin(); mit != map_weights_norm.end(); ++mit)\n    {\n      if (best_score > 0)\n      {\n        mit->second /= best_score;\n      }\n      else\n      {\n        mit->second = 0;\n      }\n    }\n\n    return map_weights_norm;\n  }\n\n  // Extract the mono-isotopic trace and reports the rt of the maximum intensity\n  // Used to compensate for slight RT shifts (e.g. important if features of a different map are used)\n  // n_scans corresponds to the number of neighboring scan rts that should be extracted\n  // n_scan = 2 -> vector size = 1 + 2 + 2\n  vector<double> findApexRT(const FeatureMap::iterator feature_it, double hit_rt, const MSExperiment<Peak1D>& peak_map, Size n_scans)\n  {\n    vector<double> seeds_rt;\n    vector<Peak2D> mono_trace;\n\n    if (!feature_it->getConvexHulls().empty())\n    {\n      // extract elution profile of 12C containing mass trace using a bounding box\n      // first convex hull contains the monoisotopic 12C trace\n      const DBoundingBox<2>& mono_bb = feature_it->getConvexHulls()[0].getBoundingBox();\n\n      //(min_rt, max_rt, min_mz, max_mz)\n      MSExperiment<Peak1D>::ConstAreaIterator ait = peak_map.areaBeginConst(mono_bb.minPosition()[0], mono_bb.maxPosition()[0], mono_bb.minPosition()[1], mono_bb.maxPosition()[1]);\n      for (; ait != peak_map.areaEndConst(); ++ait)\n      {\n        Peak2D p2d;\n        p2d.setRT(ait.getRT()); // get rt of scan\n        p2d.setMZ(ait->getMZ()); // get peak 1D mz\n        p2d.setIntensity(ait->getIntensity());\n        mono_trace.push_back(p2d);\n      }\n    }\n\n    // if there is no 12C mono trace generate a valid starting point\n    if (mono_trace.empty())\n    {\n      Peak2D p2d;\n      double next_valid_scan_rt = peak_map.RTBegin(hit_rt - 0.001)->getRT();\n      p2d.setRT(next_valid_scan_rt);\n      p2d.setMZ(0); // actually not needed\n      p2d.setIntensity(0);\n      mono_trace.push_back(p2d);\n    }\n\n    // determine trace peak with highest intensity\n    double max_trace_int = -1e16;\n    double max_trace_int_idx = 0;\n\n    for (Size j = 0; j != mono_trace.size(); ++j)\n    {\n      if (mono_trace[j].getIntensity() > max_trace_int)\n      {\n        max_trace_int = mono_trace[j].getIntensity();\n        max_trace_int_idx = j;\n      }\n    }\n    double max_trace_int_rt = mono_trace[max_trace_int_idx].getRT();\n    seeds_rt.push_back(max_trace_int_rt);\n\n    for (Size i = 1; i <= n_scans; ++i)\n    {\n      double rt_after = max_trace_int_rt;\n      if (max_trace_int_idx < (Int)mono_trace.size() - (Int)i)\n      {\n        rt_after = mono_trace[max_trace_int_idx + i].getRT();\n      }\n\n      double rt_before = max_trace_int_rt;\n      if (max_trace_int_idx >= i)\n      {\n        rt_before = mono_trace[max_trace_int_idx - i].getRT();\n      }\n\n      if (fabs(max_trace_int_rt - rt_after) < 10.0)\n      {\n        seeds_rt.push_back(rt_after);\n      }\n\n      if (fabs(max_trace_int_rt - rt_before) < 10.0)\n      {\n        seeds_rt.push_back(rt_before);\n      }\n    }\n    //cout << \"Seeds size:\" << seeds_rt.size() << endl;\n    return seeds_rt;\n  }\n\n  PeakSpectrum mergeSpectra(const MSExperiment<>& to_merge)\n  {\n    PeakSpectrum merged;\n    for (Size i = 0; i != to_merge.size(); ++i)\n    {\n      std::copy(to_merge[i].begin(), to_merge[i].end(), std::back_inserter(merged));\n    }\n    merged.sortByPosition();\n\n    return merged;\n  }\n\n  ///> converts a vector of isotopic intensities to a peak spectrum starting at mz=mz_start with mass_diff/charge step size\n  PeakSpectrum isotopicIntensitiesToSpectrum(double mz_start, double mass_diff, Int charge, vector<double> isotopic_intensities)\n  {\n    PeakSpectrum ps;\n    for (Size i = 0; i != isotopic_intensities.size(); ++i)\n    {\n      Peak1D peak;\n      peak.setMZ(mz_start + i * mass_diff / (double)charge);\n      peak.setIntensity(isotopic_intensities[i]);\n      ps.push_back(peak);\n    }\n    return ps;\n  }\n\n  ///> Collect decomposition coefficients in the merge window around the correlation maximum.\n  ///> Final list of RIAs is constructed for the peptide.\n  void extractIncorporationsAtCorrelationMaxima(SIPPeptide& sip_peptide,\n                                                const IsotopePatterns& patterns,\n                                                double weight_merge_window = 5.0,\n                                                double min_corr_threshold = 0.5,\n                                                double min_decomposition_weight = 10.0)\n  {\n    const MapRateToScoreType& map_rate_to_decomposition_weight = sip_peptide.decomposition_map;\n    const MapRateToScoreType& map_rate_to_correlation_score = sip_peptide.correlation_map;\n    vector<SIPIncorporation> sip_incorporations;\n    const vector<RateScorePair>& corr_maxima = sip_peptide.correlation_maxima;\n\n    double explained_TIC_fraction = 0;\n    double TIC = 0;\n    Size non_zero_decomposition_coefficients = 0;\n\n    double max_corr_TIC = 0;\n\n    for (Size k = 0; k < corr_maxima.size(); ++k)\n    {\n      const double rate = corr_maxima[k].rate;\n      const double corr = corr_maxima[k].score;\n\n      if (corr > min_corr_threshold)\n      {\n        SIPIncorporation sip_incorporation;\n        sip_incorporation.rate = rate;\n\n        // sum up decomposition intensities for quantification in merge window\n        double int_sum = 0;\n        MapRateToScoreType::const_iterator low = map_rate_to_decomposition_weight.lower_bound(rate - weight_merge_window - 1e-4);\n        MapRateToScoreType::const_iterator high = map_rate_to_decomposition_weight.lower_bound(rate + weight_merge_window + 1e-4);\n        for (; low != high; ++low)\n        {\n          int_sum += low->second;\n        }\n\n        if (low != map_rate_to_decomposition_weight.end())\n        {\n          int_sum += low->second;\n        }\n\n        sip_incorporation.abundance = int_sum; // calculate abundance as sum of all decompositions\n        sip_incorporation.correlation = min(corr, 1.0);\n\n        max_corr_TIC += int_sum;\n\n        // find closest idx (could be more efficient using binary search)\n        Size closest_idx = 0;\n        for (Size i = 0; i != patterns.size(); ++i)\n        {\n          if (fabs(patterns[i].first - rate) < fabs(patterns[closest_idx].first - rate))\n          {\n            closest_idx = i;\n          }\n        }\n        sip_incorporation.theoretical = isotopicIntensitiesToSpectrum(sip_peptide.mz_theo, sip_peptide.mass_diff, sip_peptide.charge, patterns[closest_idx].second);\n\n        if (int_sum > 1e-4)\n        {\n          sip_incorporations.push_back(sip_incorporation);\n        }\n        else\n        {\n          if (debug_level_ > 1)\n          {\n            LOG_WARN << \"warning: prevented adding of 0 abundance decomposition at rate \" << rate << endl;\n            LOG_WARN << \"decomposition: \" << endl;\n            for (MapRateToScoreType::const_iterator it = map_rate_to_decomposition_weight.begin(); it != map_rate_to_decomposition_weight.end(); ++it)\n            {\n              LOG_WARN << it->first << \" \" << it->second << endl;\n            }\n            LOG_WARN << \"correlation: \" << endl;\n            for (MapRateToScoreType::const_iterator it = map_rate_to_correlation_score.begin(); it != map_rate_to_correlation_score.end(); ++it)\n            {\n              LOG_WARN << it->first << \" \" << it->second << endl;\n            }\n          }\n\n        }\n      }\n    }\n\n    // find highest non-natural incorporation\n    double highest_non_natural_abundance = 0;\n    double highest_non_natural_rate = 0;\n    for (vector<SIPIncorporation>::const_iterator it = sip_incorporations.begin(); it != sip_incorporations.end(); ++it)\n    {\n      if (it->rate < 5.0) // skip natural\n      {\n        continue;\n      }\n\n      if (it->abundance > highest_non_natural_abundance)\n      {\n        highest_non_natural_rate = it->rate;\n        highest_non_natural_abundance = it->abundance;\n      }\n    }\n\n    bool non_natural = false;\n    if (highest_non_natural_rate > 5.0 && highest_non_natural_abundance > min_decomposition_weight)\n    {\n      non_natural = true;\n    }\n\n    // used for non-gaussian shape detection\n    for (MapRateToScoreType::const_iterator mit = map_rate_to_decomposition_weight.begin(); mit != map_rate_to_decomposition_weight.end(); ++mit)\n    {\n      double decomposition_rate = mit->first;\n      double decomposition_weight = mit->second;\n      TIC += decomposition_weight;\n\n      if (non_natural && decomposition_weight > 0.05 * highest_non_natural_abundance && decomposition_rate > 5.0)\n      {\n        ++non_zero_decomposition_coefficients;\n      }\n    }\n\n    if (TIC > 1e-5)\n    {\n      explained_TIC_fraction = max_corr_TIC / TIC;\n    }\n    else\n    {\n      explained_TIC_fraction = 0;\n    }\n\n    // set results\n    sip_peptide.incorporations = sip_incorporations;\n    sip_peptide.explained_TIC_fraction = explained_TIC_fraction;\n    sip_peptide.non_zero_decomposition_coefficients = non_zero_decomposition_coefficients;\n  }\n\n  ///> Collect decomposition coefficients. Starting at the largest decomposition weights merge smaller weights in the merge window.\n  void extractIncorporationsAtHeighestDecompositionWeights(SIPPeptide& sip_peptide,\n                                                           const IsotopePatterns& patterns,\n                                                           double weight_merge_window = 5.0,\n                                                           double min_corr_threshold = 0.5,\n                                                           double min_low_RIA_threshold = -1,\n                                                           double min_decomposition_weight = 10.0)\n  {\n    if (min_low_RIA_threshold < 0)\n    {\n      min_low_RIA_threshold = min_corr_threshold;\n    }\n\n    const MapRateToScoreType& map_rate_to_decomposition_weight = sip_peptide.decomposition_map;\n    const MapRateToScoreType& map_rate_to_correlation_score = sip_peptide.correlation_map;\n\n    double explained_TIC_fraction = 0;\n    double TIC = 0;\n    Size non_zero_decomposition_coefficients = 0;\n    double max_corr_TIC = 0;\n    vector<SIPIncorporation> sip_incorporations;\n\n    // find decomposition weights with correlation larger than threshold (seeds)\n    MapRateToScoreType::const_iterator md_it = map_rate_to_decomposition_weight.begin();\n    MapRateToScoreType::const_iterator mc_it = map_rate_to_correlation_score.begin();\n\n    set<pair<double, double> > seeds_weight_rate_pair;\n    for (; md_it != map_rate_to_decomposition_weight.end(); ++md_it, ++mc_it)\n    {\n      if (mc_it->first < 10.0) // lowRIA region\n      {\n        if (mc_it->second >= min_low_RIA_threshold && md_it->second >= min_decomposition_weight)\n        {\n          seeds_weight_rate_pair.insert(make_pair(md_it->second, md_it->first));\n        }\n      }\n      else // non-low RIA region\n      {\n        if (mc_it->second >= min_corr_threshold && md_it->second >= min_decomposition_weight)\n        {\n          seeds_weight_rate_pair.insert(make_pair(md_it->second, md_it->first));\n          //cout << \"Seeds insert: \" << md_it->second << \" \" << md_it->first << endl;\n        }\n      }\n    }\n\n    // cout << \"Seeds: \" << seeds_weight_rate_pair.size() << endl;\n\n    // seeds_weight_rate_pair contains the seeds ordered by their decomposition weight\n    while (!seeds_weight_rate_pair.empty())\n    {\n      // pop last element from set\n      set<pair<double, double> >::iterator last_element = --seeds_weight_rate_pair.end();\n      pair<double, double> current_seed = *last_element;\n\n      //cout << current_seed.first << \" \" << current_seed.second << endl;\n\n      // find weights in window to merge, remove from seed map. maybe also remove from original map depending on whether we want to quantify the weight only 1 time\n      const double rate = current_seed.second;\n\n      SIPIncorporation sip_incorporation;\n      sip_incorporation.rate = rate;\n\n      MapRateToScoreType::const_iterator low = map_rate_to_decomposition_weight.lower_bound(rate - weight_merge_window - 1e-4);\n      MapRateToScoreType::const_iterator high = map_rate_to_decomposition_weight.lower_bound(rate + weight_merge_window + 1e-4);\n\n      // cout << \"Distance: \" << std::distance(low, high) << endl;;\n\n      MapRateToScoreType::const_iterator l1 = low;\n      MapRateToScoreType::const_iterator h1 = high;\n\n      // iterate over peaks in merge window\n      for (; l1 != h1; ++l1)\n      {\n        // remove from seed map\n        seeds_weight_rate_pair.erase(make_pair(l1->second, l1->first));\n      }\n\n      // Sum up decomposition intensities for quantification in merge window\n      double int_sum = 0;\n      for (; low != high; ++low)\n      {\n        int_sum += low->second;\n      }\n\n      if (low != map_rate_to_decomposition_weight.end())\n      {\n        int_sum += low->second;\n      }\n\n      sip_incorporation.abundance = int_sum;\n      MapRateToScoreType::const_iterator corr_it = map_rate_to_correlation_score.lower_bound(rate - 1e-6);\n      sip_incorporation.correlation = min(corr_it->second, 1.0);\n\n      max_corr_TIC += int_sum;\n\n      PeakSpectrum theoretical_spectrum;\n\n      // find closest idx (could be more efficient using binary search)\n      Size closest_idx = 0;\n      for (Size i = 0; i != patterns.size(); ++i)\n      {\n        if (fabs(patterns[i].first - rate) < fabs(patterns[closest_idx].first - rate))\n        {\n          closest_idx = i;\n        }\n      }\n      sip_incorporation.theoretical = isotopicIntensitiesToSpectrum(sip_peptide.mz_theo, sip_peptide.mass_diff, sip_peptide.charge, patterns[closest_idx].second);\n\n      sip_incorporations.push_back(sip_incorporation);\n    }\n\n    // find highest non-natural incorporation\n    double highest_non_natural_abundance = 0;\n    double highest_non_natural_rate = 0;\n    for (vector<SIPIncorporation>::const_iterator it = sip_incorporations.begin(); it != sip_incorporations.end(); ++it)\n    {\n      if (it->rate < 5.0) // skip natural\n      {\n        continue;\n      }\n\n      if (it->abundance > highest_non_natural_abundance)\n      {\n        highest_non_natural_rate = it->rate;\n        highest_non_natural_abundance = it->abundance;\n      }\n    }\n\n    bool non_natural = false;\n    if (highest_non_natural_rate > 5.0)\n    {\n      non_natural = true;\n    }\n\n    // used for non-gaussian shape detection\n    for (MapRateToScoreType::const_iterator mit = map_rate_to_decomposition_weight.begin(); mit != map_rate_to_decomposition_weight.end(); ++mit)\n    {\n      double decomposition_rate = mit->first;\n      double decomposition_weight = mit->second;\n      TIC += decomposition_weight;\n\n      if (non_natural && decomposition_weight > 0.05 * highest_non_natural_abundance && decomposition_rate > 5.0)\n      {\n        ++non_zero_decomposition_coefficients;\n      }\n    }\n\n    if (TIC > 1e-5)\n    {\n      explained_TIC_fraction = max_corr_TIC / TIC;\n    }\n    else\n    {\n      explained_TIC_fraction = 0;\n    }\n\n    // set results\n    std::sort(sip_incorporations.begin(), sip_incorporations.end(), RIALess());\n    sip_peptide.incorporations = sip_incorporations;\n    sip_peptide.explained_TIC_fraction = explained_TIC_fraction;\n    sip_peptide.non_zero_decomposition_coefficients = non_zero_decomposition_coefficients;\n  }\n\n  ///> calculate the global labeling ration based on all but the first 4 peaks\n  double calculateGlobalLR(const vector<double>& isotopic_intensities)\n  {\n    if (isotopic_intensities.size() < 5)\n    {\n      return 0.0;\n    }\n\n    double sum = accumulate(isotopic_intensities.begin(), isotopic_intensities.end(), 0);\n    double sum_incorporated = accumulate(isotopic_intensities.begin() + 4, isotopic_intensities.end(), 0);\n\n    if (sum < 1e-4)\n    {\n      return 0.0;\n    }\n\n    return sum_incorporated / sum;\n  }\n\n  ExitCodes main_(int, const char**)\n  {\n    String file_extension_ = getStringOption_(\"plot_extension\");\n    Int debug_level = getIntOption_(\"debug\");\n    String in_mzml = getStringOption_(\"in_mzML\");\n    String in_features = getStringOption_(\"in_featureXML\");\n    double mz_tolerance_ppm_ = getDoubleOption_(\"mz_tolerance_ppm\");\n    double rt_tolerance_s = getDoubleOption_(\"rt_tolerance_s\");\n\n    double weight_merge_window_ = getDoubleOption_(\"weight_merge_window\");\n    double intensity_threshold_ = getDoubleOption_(\"intensity_threshold\");\n    double decomposition_threshold = getDoubleOption_(\"decomposition_threshold\");\n\n    Size min_consecutive_isotopes = (Size)getIntOption_(\"min_consecutive_isotopes\");\n    String qc_output_directory = getStringOption_(\"qc_output_directory\");\n    Size n_heatmap_bins = getIntOption_(\"heatmap_bins\");\n    double score_plot_y_axis_min = getDoubleOption_(\"score_plot_yaxis_min\");\n\n    QDir qc_dir(qc_output_directory.toQString());\n\n    // convert relative paths into absolute path\n    qc_output_directory = String(qc_dir.absolutePath());\n\n    // trying to create qc_output_directory if not present\n    if (!qc_dir.exists())\n    {\n      qc_dir.mkpath(qc_output_directory.toQString());\n    }\n\n    String out_csv = getStringOption_(\"out_csv\");\n    ofstream out_csv_stream(out_csv.c_str());\n    out_csv_stream << fixed << setprecision(4);\n\n    String out_peptide_centric_csv = getStringOption_(\"out_peptide_centric_csv\");\n    ofstream out_peptide_csv_stream(out_peptide_centric_csv.c_str());\n    out_peptide_csv_stream << fixed << setprecision(4);\n\n    String labeling_element = getStringOption_(\"labeling_element\");\n\n    //bool plot_merged = getFlag_(\"plot_merged\");\n    bool report_natural_peptides = getFlag_(\"report_natural_peptides\");\n    bool use_unassigned_ids = getFlag_(\"use_unassigned_ids\");\n    bool use_averagine_ids = getFlag_(\"use_averagine_ids\");\n\n    //String debug_patterns_name = getStringOption_(\"debug_patterns_name\");\n\n    double correlation_threshold = getDoubleOption_(\"correlation_threshold\");\n\n    double xic_threshold = getDoubleOption_(\"xic_threshold\");\n\n    double min_correlation_distance_to_averagine = getDoubleOption_(\"min_correlation_distance_to_averagine\");\n\n    String tmp_path = File::getTempDirectory();\n    tmp_path.substitute('\\\\', '/');\n\n    // check if R and dependencies are installed\n    StringList package_names;\n    package_names.push_back(\"gplots\");\n    bool R_is_working = RIntegration::checkRDependencies(tmp_path, package_names);\n    if (!R_is_working)\n    {\n      LOG_INFO << \"There was a problem detecting R and/or of one of the required libraries. Make sure you have the directory of your R executable in your system path variable.\" << endl;\n      return EXTERNAL_PROGRAM_ERROR;\n    }\n\n    bool cluster_flag = getFlag_(\"cluster\");\n\n    // read descriptions from FASTA and create map for fast annotation\n    LOG_INFO << \"loading sequences...\" << endl;\n    String in_fasta = getStringOption_(\"in_fasta\");\n    vector<FASTAFile::FASTAEntry> fasta_entries;\n    FASTAFile().load(in_fasta, fasta_entries);\n    map<String, String> proteinid_to_description;\n    for (vector<FASTAFile::FASTAEntry>::const_iterator it = fasta_entries.begin(); it != fasta_entries.end(); ++it)\n    {\n      if (!it->identifier.empty() && !it->description.empty())\n      {\n        String s = it->identifier;\n        proteinid_to_description[s.trim().toUpper()] = it->description;\n      }\n    }\n\n    LOG_INFO << \"loading feature map...\" << endl;\n    FeatureXMLFile fh;\n    FeatureMap feature_map;\n    fh.load(in_features, feature_map);\n\n    // annotate as features found using feature finding (to distinguish them from averagine features oder id based features ... see below)\n    for (FeatureMap::iterator feature_it = feature_map.begin(); feature_it != feature_map.end(); ++feature_it)\n    {\n      feature_it->setMetaValue(\"feature_type\", FEATURE_STRING);\n    }\n\n    // if also unassigned ids are used create a pseudo feature\n    if (use_unassigned_ids)\n    {\n      const vector<PeptideIdentification> unassigned_ids = feature_map.getUnassignedPeptideIdentifications();\n      Size unassigned_id_features = 0;\n      for (vector<PeptideIdentification>::const_iterator it = unassigned_ids.begin(); it != unassigned_ids.end(); ++it)\n      {\n        vector<PeptideHit> hits = it->getHits();\n        if (!hits.empty())\n        {\n          Feature f;\n          f.setMetaValue(\"feature_type\", UNASSIGNED_ID_STRING);\n          f.setRT(it->getRT());\n          // take sequence of first hit to calculate ground truth mz\n          double charge = hits[0].getCharge();\n          if (charge == 0)\n          {\n            continue;\n          }\n          double charged_weight = hits[0].getSequence().getMonoWeight(Residue::Full, charge);\n          double mz = charged_weight / charge;\n          f.setMZ(mz);\n          // add id to pseudo feature\n          vector<PeptideIdentification> id;\n          id.push_back(*it);\n          f.setPeptideIdentifications(id);\n          feature_map.push_back(f);\n          unassigned_id_features++;\n        }\n      }\n      feature_map.updateRanges();\n      LOG_INFO << \"Evaluating \" << unassigned_id_features << \" unassigned identifications.\" << endl;\n    }\n\n    // determine all spectra that have not been identified and assign an averagine peptide to it\n    if (use_averagine_ids)\n    {\n      // load only MS2 spectra with precursor information\n      MSExperiment<Peak1D> peak_map;\n      MzMLFile mh;\n      std::vector<Int> ms_level(1, 2);\n      mh.getOptions().setMSLevels(ms_level);\n      mh.load(in_mzml, peak_map);\n      peak_map.sortSpectra();\n      peak_map.updateRanges();\n\n      // extract rt and mz of all identified precursors and store them in blacklist\n      vector<Peak2D> blacklisted_precursors;\n      // in features\n      for (FeatureMap::iterator feature_it = feature_map.begin(); feature_it != feature_map.end(); ++feature_it) // for each peptide feature\n      {\n        const vector<PeptideIdentification>& f_ids = feature_it->getPeptideIdentifications();\n        for (vector<PeptideIdentification>::const_iterator id_it = f_ids.begin(); id_it != f_ids.end(); ++id_it)\n        {\n          if (!id_it->getHits().empty())\n          {\n            // Feature with id found so we don't need to generate averagine id. Find MS2 in experiment and blacklist it.\n            Peak2D p;\n            p.setRT(id_it->getRT());\n            p.setMZ(id_it->getMZ());\n            blacklisted_precursors.push_back(p);\n          }\n        }\n      }\n\n      // and in unassigned ids\n      const vector<PeptideIdentification> unassigned_ids = feature_map.getUnassignedPeptideIdentifications();\n      for (vector<PeptideIdentification>::const_iterator it = unassigned_ids.begin(); it != unassigned_ids.end(); ++it)\n      {\n        const vector<PeptideHit> hits = it->getHits();\n        if (!hits.empty())\n        {\n          Peak2D p;\n          p.setRT(it->getRT());\n          p.setMZ(it->getMZ());\n          blacklisted_precursors.push_back(p);\n        }\n      }\n\n      // find index of all precursors that have been blacklisted\n      vector<Size> blacklist_idx;\n      for (vector<Peak2D>::const_iterator it = blacklisted_precursors.begin(); it != blacklisted_precursors.end(); ++it)\n      {\n        MSExperiment<>::const_iterator map_rt_begin = peak_map.RTBegin(-std::numeric_limits<double>::max());\n        MSExperiment<>::const_iterator rt_begin = peak_map.RTBegin(it->getRT() - 1e-5);\n        Size index = std::distance(map_rt_begin, rt_begin);\n        //cout << \"Blacklist Index: \" << index << endl;\n        blacklist_idx.push_back(index);\n      }\n\n      for (Size i = 0; i != peak_map.size(); ++i)\n      {\n        // precursor not blacklisted?\n        if (find(blacklist_idx.begin(), blacklist_idx.end(), i) == blacklist_idx.end() && !peak_map[i].getPrecursors().empty())\n        {\n          // store feature with id generated from averagine peptide (pseudo id)\n          Feature f;\n\n          double precursor_mz = peak_map[i].getPrecursors()[0].getMZ();\n          int precursor_charge = peak_map[i].getPrecursors()[0].getCharge();\n          //double precursor_mass = (double)precursor_charge * precursor_mz - (double)precursor_charge * Constants::PROTON_MASS_U;\n\n          // add averagine id to pseudo feature\n          PeptideHit pseudo_hit;\n\n          // set peptide with lowest deviation from averagine\n          pseudo_hit.setSequence(AASequence()); // set empty sequence\n          pseudo_hit.setCharge(precursor_charge);\n          PeptideIdentification pseudo_id;\n          vector<PeptideHit> pseudo_hits;\n          pseudo_hits.push_back(pseudo_hit);\n          pseudo_id.setHits(pseudo_hits);\n          vector<PeptideIdentification> id;\n          id.push_back(pseudo_id);\n          f.setPeptideIdentifications(id);\n          f.setRT(peak_map[i].getRT());\n          f.setMZ(precursor_mz);\n          f.setMetaValue(\"feature_type\", UNIDENTIFIED_STRING);\n          feature_map.push_back(f);\n        }\n      }\n      feature_map.updateRanges();\n    }\n\n    LOG_INFO << \"loading experiment...\" << endl;\n    MSExperiment<Peak1D> peak_map;\n    MzMLFile mh;\n    std::vector<Int> ms_level(1, 1);\n    mh.getOptions().setMSLevels(ms_level);\n    mh.load(in_mzml, peak_map);\n    peak_map.updateRanges();\n    ThresholdMower tm;\n    Param tm_parameters;\n    tm_parameters.setValue(\"threshold\", intensity_threshold_);\n    tm.setParameters(tm_parameters);\n    tm.filterPeakMap(peak_map);\n    peak_map.sortSpectra();\n\n    // used to generate plots\n    vector<String> titles;\n    vector<MapRateToScoreType> weight_maps;\n    vector<MapRateToScoreType> normalized_weight_maps;\n    vector<MapRateToScoreType> correlation_maps;\n\n    String file_suffix = \"_\" + String(QFileInfo(in_mzml.toQString()).baseName()) + \"_\" + String::random(4);\n\n    vector<SIPPeptide> sip_peptides;\n\n    Size nPSMs = 0; ///< number of PSMs. If 0 IDMapper has not been called.\n    Size spectrum_with_no_isotopic_peaks(0);\n    Size spectrum_with_isotopic_peaks(0);\n\n    for (FeatureMap::iterator feature_it = feature_map.begin(); feature_it != feature_map.end(); ++feature_it) // for each peptide feature\n    {\n      const double feature_hit_center_rt = feature_it->getRT();\n\n      // check if out of experiment bounds\n      if (feature_hit_center_rt > peak_map.getMaxRT() || feature_hit_center_rt < peak_map.getMinRT())\n      {\n        continue;\n      }\n\n      // Extract 1 or more MS/MS with identifications assigned to the feature by IDMapper\n      vector<PeptideIdentification> pep_ids = feature_it->getPeptideIdentifications();\n\n      nPSMs += pep_ids.size();\n\n      // Skip features without peptide identifications\n      if (pep_ids.empty())\n      {\n        continue;\n      }\n\n      // add best scoring PeptideHit of all PeptideIdentifications mapping to the current feature to tmp_pepid\n      PeptideIdentification tmp_pepid;\n      tmp_pepid.setHigherScoreBetter(pep_ids[0].isHigherScoreBetter());\n      for (Size i = 0; i != pep_ids.size(); ++i)\n      {\n        pep_ids[i].assignRanks();\n        const vector<PeptideHit>& hits = pep_ids[i].getHits();\n        if (!hits.empty())\n        {\n          tmp_pepid.insertHit(hits[0]);\n        }\n        else\n        {\n          LOG_WARN << \"Empty peptide hit encountered on feature. Ignoring.\" << endl;\n        }\n      }\n\n      tmp_pepid.assignRanks();\n\n      SIPPeptide sip_peptide;\n      sip_peptide.feature_type = feature_it->getMetaValue(\"feature_type\"); // used to annotate feature type in reporting\n\n      // retrieve identification information\n      const PeptideHit& feature_hit = tmp_pepid.getHits()[0];\n      const double feature_hit_score = feature_hit.getScore();\n      const double feature_hit_center_mz = feature_it->getMZ();\n      const double feature_hit_charge = feature_hit.getCharge();\n\n      String feature_hit_seq = \"\";\n      double feature_hit_theoretical_mz = 0;\n      AASequence feature_hit_aaseq;\n      // set theoretical mz of peptide hit to:\n      //   mz of sequence if we have a sequence identified\n      // otherwise:\n      //   mz of precursor (stored in feature mz) if no sequence identified\n      if (sip_peptide.feature_type == FEATURE_STRING || sip_peptide.feature_type == UNASSIGNED_ID_STRING)\n      {\n        feature_hit_aaseq = feature_hit.getSequence();\n        feature_hit_seq = feature_hit_aaseq.toString();\n        feature_hit_theoretical_mz = feature_hit_aaseq.getMonoWeight(Residue::Full, feature_hit.getCharge()) / feature_hit.getCharge();\n      }\n      else if (sip_peptide.feature_type == UNIDENTIFIED_STRING)\n      {\n        feature_hit_aaseq = AASequence();\n        feature_hit_seq = String(\"\");\n        feature_hit_theoretical_mz = feature_hit_center_mz;\n      }\n\n      if (debug_level_ > 1)\n      {\n        LOG_DEBUG << \"Feature type: (\" << sip_peptide.feature_type << \") Seq.: \" << feature_hit_seq << \" m/z: \" << feature_hit_theoretical_mz << endl;\n      }\n\n      const set<String> protein_accessions = feature_hit.extractProteinAccessions();\n      sip_peptide.accessions = vector<String>(protein_accessions.begin(), protein_accessions.end());\n      sip_peptide.sequence = feature_hit_aaseq;\n      sip_peptide.mz_theo = feature_hit_theoretical_mz;\n      sip_peptide.mass_theo = feature_hit_theoretical_mz * feature_hit_charge - feature_hit_charge * Constants::PROTON_MASS_U;\n      sip_peptide.charge = feature_hit_charge;\n      sip_peptide.score = feature_hit_score;\n      sip_peptide.feature_rt = feature_hit_center_rt;\n      sip_peptide.feature_mz = feature_hit_center_mz;\n      sip_peptide.unique = sip_peptide.accessions.size() == 1 ? true : false;\n\n      // determine retention time of scans next to the central scan\n      vector<double> seeds_rt = findApexRT(feature_it, feature_hit_center_rt, peak_map, 2); // 1 scan at maximum, 2+2 above and below\n      double max_trace_int_rt = seeds_rt[0];\n\n      // determine maximum number of peaks and mass difference\n      EmpiricalFormula e = feature_hit_aaseq.getFormula();\n\n      // assign mass difference between labeling element isotopes\n      if (labeling_element == \"C\")\n      {\n        sip_peptide.mass_diff = 1.003354837810;\n      } else if (labeling_element == \"N\")\n      {\n        sip_peptide.mass_diff = 0.9970349;\n      } else if (labeling_element == \"H\")\n      {\n        sip_peptide.mass_diff = 1.00627675;\n      }\n\n      Size element_count(0);\n      if (sip_peptide.feature_type == FEATURE_STRING || sip_peptide.feature_type == UNASSIGNED_ID_STRING)\n      {\n        element_count = MetaProSIPDecomposition::getNumberOfLabelingElements(labeling_element, feature_hit_aaseq);\n      }\n      else // if (sip_peptide.feature_type == UNIDENTIFIED_STRING)\n      {\n        // calculate number of expected labeling elements using averagine model C:4.9384 H:7.7583 N:1.3577 O:1.4773 S:0.0417 divided by average weight 111.1254\n        if (labeling_element == \"C\")\n        {\n          element_count = sip_peptide.mass_theo * 0.0444398894906044;\n        } else if (labeling_element == \"N\")\n        {\n          element_count = sip_peptide.mass_theo * 0.0122177302837372;\n        } else if (labeling_element == \"H\")\n        {\n          element_count = sip_peptide.mass_theo * 0.06981572169;\n        }\n      }\n\n      // collect 13C / 15N peaks\n      if (debug_level_ >= 10)\n      {\n        LOG_DEBUG << \"Extract XICs\" << endl;\n      }\n\n      vector<double> isotopic_intensities = MetaProSIPXICExtraction::extractXICsOfIsotopeTraces(element_count + ADDITIONAL_ISOTOPES, sip_peptide.mass_diff, mz_tolerance_ppm_, rt_tolerance_s, max_trace_int_rt, feature_hit_theoretical_mz, feature_hit_charge, peak_map, xic_threshold);\n\n      // set intensity to zero if not enough neighboring isotopic peaks are present\n      for (Size i = 0; i != isotopic_intensities.size(); ++i)\n      {\n        if (isotopic_intensities[i] < 1e-4) continue;\n        Size consecutive_isotopes = 0;\n        Int j = i;\n\n        while (j >= 0)\n        {\n          if (isotopic_intensities[j] > 1e-4)\n          {\n            ++consecutive_isotopes;\n            --j;\n          }\n          else\n          {\n            break;\n          }\n        }\n        j = i + 1;\n\n        while ((Size)j < isotopic_intensities.size())\n        {\n          if (isotopic_intensities[j] > 1e-4)\n          {\n            ++consecutive_isotopes;\n            ++j;\n          }\n          else\n          {\n            break;\n          }\n        }\n\n        if (consecutive_isotopes < min_consecutive_isotopes)\n        {\n          isotopic_intensities[i] = 0;\n        }\n      }\n\n      double TIC = accumulate(isotopic_intensities.begin(), isotopic_intensities.end(), 0.0);\n\n      // collect 13C / 15N peaks\n      if (debug_level_ >= 10)\n      {\n        LOG_DEBUG << \"TIC of XICs: \" << TIC << endl;\n        for (Size i = 0; i != isotopic_intensities.size(); ++i)\n        {\n          cout << isotopic_intensities[i] << endl;\n        }\n      }\n\n      // no Peaks collected\n      if (TIC < 1e-4)\n      {\n        ++spectrum_with_no_isotopic_peaks;\n        if (debug_level > 0)\n        {\n          LOG_INFO << \"no isotopic peaks in spectrum\" << endl;\n        }\n        continue;\n      }\n      else\n      {\n        ++spectrum_with_isotopic_peaks;\n      }\n\n      // store accumulated intensities at theoretical positions\n      sip_peptide.accumulated = isotopicIntensitiesToSpectrum(feature_hit_theoretical_mz, sip_peptide.mass_diff, feature_hit_charge, isotopic_intensities);\n\n      sip_peptide.global_LR = calculateGlobalLR(isotopic_intensities);\n\n      Size non_zero_isotopic_intensities(0);\n      for (Size i = 0; i != isotopic_intensities.size(); ++i)\n      {\n        if (isotopic_intensities[i] > 0.1)\n        {\n          ++non_zero_isotopic_intensities;\n        }\n      }\n      cout << \"isotopic intensities missing / total: \" << isotopic_intensities.size() - non_zero_isotopic_intensities << \"/\" << isotopic_intensities.size() << endl;\n\n      LOG_INFO << feature_hit.getSequence().toString() << \"\\trt: \" << max_trace_int_rt << endl;\n\n      // correlation filtering\n      MapRateToScoreType map_rate_to_correlation_score;\n\n      IsotopePatterns patterns;\n\n      // calculate isotopic patterns for the given sequence, incoroporation interval/steps\n      if (sip_peptide.feature_type == FEATURE_STRING || sip_peptide.feature_type == UNASSIGNED_ID_STRING)\n      {\n       if (labeling_element == \"N\")\n       {\n         patterns = MetaProSIPDecomposition::calculateIsotopePatternsFor15NRange(AASequence::fromString(feature_hit_seq));\n       } else if (labeling_element == \"C\")\n       {\n         patterns = MetaProSIPDecomposition::calculateIsotopePatternsFor13CRange(AASequence::fromString(feature_hit_seq));\n       } else if (labeling_element == \"H\")\n       {\n         patterns = MetaProSIPDecomposition::calculateIsotopePatternsFor2HRange(AASequence::fromString(feature_hit_seq));\n       }\n      }\n      else if (sip_peptide.feature_type == UNIDENTIFIED_STRING)\n      {\n       if (labeling_element == \"N\")\n       {\n         patterns = MetaProSIPDecomposition::calculateIsotopePatternsFor15NRangeOfAveraginePeptide(sip_peptide.mass_theo);\n       } else if (labeling_element == \"C\")\n       {\n         patterns = MetaProSIPDecomposition::calculateIsotopePatternsFor13CRangeOfAveraginePeptide(sip_peptide.mass_theo);\n       } else if (labeling_element == \"H\")\n       {\n         patterns = MetaProSIPDecomposition::calculateIsotopePatternsFor2HRangeOfAveraginePeptide(sip_peptide.mass_theo);\n       }\n      }\n\n      // store theoretical patterns for visualization\n      sip_peptide.patterns = patterns;\n      for (IsotopePatterns::const_iterator pit = sip_peptide.patterns.begin(); pit != sip_peptide.patterns.end(); ++pit)\n      {\n        PeakSpectrum p = isotopicIntensitiesToSpectrum(feature_hit_theoretical_mz, sip_peptide.mass_diff, feature_hit_charge, pit->second);\n        p.setMetaValue(\"rate\", (double)pit->first);\n        p.setMSLevel(2);\n        sip_peptide.pattern_spectra.push_back(p);\n      }\n\n      // calculate decomposition into isotopic patterns\n      MapRateToScoreType map_rate_to_decomposition_weight;\n      MetaProSIPDecomposition::calculateDecompositionWeightsIsotopicPatterns(element_count, isotopic_intensities, patterns, map_rate_to_decomposition_weight, sip_peptide);\n\n      // set first intensity to zero and remove first 2 possible RIAs (0% and e.g. 1.07% for carbon)\n      MapRateToScoreType tmp_map_rate_to_correlation_score;\n      if (getFlag_(\"filter_monoisotopic\"))\n      {\n        // calculate correlation of natural RIAs (for later reporting) before we subtract the intensities. This is somewhat redundant but no speed bottleneck.\n        calculateCorrelation(element_count, isotopic_intensities, patterns, tmp_map_rate_to_correlation_score, labeling_element, sip_peptide.mass_theo, -1.0);\n        for (Size i = 0; i != sip_peptide.reconstruction_monoistopic.size(); ++i)\n        {\n          if (i == 0)\n          {\n            isotopic_intensities[0] = 0;\n          }\n\n          isotopic_intensities[i] -= sip_peptide.reconstruction_monoistopic[i];\n          if (isotopic_intensities[i] < 0)\n          {\n            isotopic_intensities[i] = 0;\n          }\n        }\n      }\n\n      sip_peptide.decomposition_map = map_rate_to_decomposition_weight;\n\n      // calculate Pearson correlation coefficients\n      calculateCorrelation(element_count, isotopic_intensities, patterns, map_rate_to_correlation_score, labeling_element, sip_peptide.mass_theo, min_correlation_distance_to_averagine);\n\n      // restore original correlation of natural RIAs (take maximum of observed correlations)\n      if (getFlag_(\"filter_monoisotopic\"))\n      {\n        MapRateToScoreType::iterator dc_it = map_rate_to_correlation_score.begin();\n        MapRateToScoreType::const_iterator tmp_dc_it = tmp_map_rate_to_correlation_score.begin();\n        dc_it->second = max(tmp_dc_it->second, dc_it->second);\n        ++dc_it;\n        ++tmp_dc_it;\n        dc_it->second = max(tmp_dc_it->second, dc_it->second);\n      }\n\n      sip_peptide.correlation_map = map_rate_to_correlation_score;\n\n      // determine maximum correlations\n      sip_peptide.correlation_maxima = MetaProSIPInterpolation::getHighPoints(correlation_threshold, map_rate_to_correlation_score);\n\n      // FOR REPORTING: store incorporation information like e.g. theoretical spectrum for best correlations\n      if (getStringOption_(\"collect_method\") == \"correlation_maximum\")\n      {\n        extractIncorporationsAtCorrelationMaxima(sip_peptide, patterns, weight_merge_window_, correlation_threshold);\n      }\n      else if (getStringOption_(\"collect_method\") == \"decomposition_maximum\")\n      {\n        extractIncorporationsAtHeighestDecompositionWeights(sip_peptide, patterns, weight_merge_window_, correlation_threshold, getDoubleOption_(\"lowRIA_correlation_threshold\"));\n      }\n\n      // store sip peptide\n      if (sip_peptide.incorporations.size() != 0 && sip_peptide.RR > decomposition_threshold)\n      {\n        if (debug_level > 0)\n        {\n          LOG_INFO << \"SIP peptides: \" << sip_peptide.incorporations.size() << endl;\n        }\n        sip_peptides.push_back(sip_peptide);\n      }\n\n      MapRateToScoreType map_rate_to_normalized_weight = normalizeToMax(map_rate_to_decomposition_weight);\n\n      // store for plotting\n      titles.push_back(feature_hit_seq + \" \" + String(feature_hit_center_rt));\n      weight_maps.push_back(map_rate_to_decomposition_weight);\n      normalized_weight_maps.push_back(map_rate_to_normalized_weight);\n      correlation_maps.push_back(map_rate_to_correlation_score);\n    }\n\n    LOG_INFO << \"Spectra with / without isotopic peaks \" << spectrum_with_isotopic_peaks << \"/\" << spectrum_with_no_isotopic_peaks << endl;\n\n    if (nPSMs == 0)\n    {\n      LOG_ERROR << \"No assigned identifications found in featureXML. Did you forget to run IDMapper?\" << endl;\n      return INCOMPATIBLE_INPUT_DATA;\n    }\n\n    if (sip_peptides.size() == 0)\n    {\n      LOG_ERROR << \"No peptides passing the incorporation threshold found.\" << endl;\n      return INCOMPATIBLE_INPUT_DATA;\n    }\n\n    // copy meta information\n    MSExperiment<Peak1D> debug_exp = peak_map;\n    debug_exp.clear(false);\n\n    vector<vector<SIPPeptide> > sippeptide_clusters; // vector of cluster\n\n    if (cluster_flag)\n    {\n      if (debug_level > 0)\n      {\n        LOG_INFO << \"Determine cluster center of RIAs: \" << endl;\n      }\n      vector<double> cluster_center(MetaProSIPClustering::getRIAClusterCenter(sip_peptides));\n      if (debug_level > 0)\n      {\n        LOG_INFO << \"Assigning peptides to cluster: \" << endl;\n      }\n      sippeptide_clusters = MetaProSIPClustering::clusterSIPPeptides(cluster_center, sip_peptides);\n\n      // remove cluster with no assigned SIP peptide (spurious highpoints giving rise to cluster may happen because of small bumps caused by interpolation)\n      vector<vector<SIPPeptide> >::iterator scit = sippeptide_clusters.begin();\n      vector<double>::iterator ccit = cluster_center.begin();\n      while (scit != sippeptide_clusters.end() && ccit != cluster_center.end())\n      {\n        if (scit->empty())\n        {\n          scit = sippeptide_clusters.erase(scit); // remove cluster of SIP peptides\n          ccit = cluster_center.erase(ccit); // remove cluster center\n        }\n        else\n        {\n          ++scit;\n          ++ccit;\n        }\n      }\n\n      if (debug_level > 0)\n      {\n        for (Size i = 0; i != sippeptide_clusters.size(); ++i)\n        {\n          LOG_INFO << \"Cluster: \" << (i + 1) << \" contains \" << sippeptide_clusters[i].size() << \" peptides.\" << endl;\n        }\n      }\n    }\n    else // data hasn't been clustered so just add all SIP peptides as cluster zero\n    {\n      sippeptide_clusters.push_back(sip_peptides);\n    }\n\n    // create group/cluster centric report\n    if (!out_csv.empty())\n    {\n      LOG_INFO << \"Create CSV report.\" << endl;\n      MetaProSIPReporting::createCSVReport(sippeptide_clusters, out_csv_stream, proteinid_to_description);\n    }\n\n    // create peptide centric report\n    if (!out_peptide_centric_csv.empty())\n    {\n      LOG_INFO << \"Creating peptide centric report: \" << out_peptide_centric_csv << std::endl;\n      MetaProSIPReporting::createPeptideCentricCSVReport(in_mzml, file_extension_, sippeptide_clusters, out_peptide_csv_stream, proteinid_to_description, qc_output_directory, file_suffix, report_natural_peptides);\n    }\n\n    // plot debug spectra\n    /*\n    if (!debug_patterns_name.empty())\n    {\n      MzMLFile mtest;\n      mtest.store(debug_patterns_name, debug_exp);\n    }\n    */\n\n    // quality report\n    if (!qc_output_directory.empty() && R_is_working)\n    {\n      // TODO plot merged is now passed as false\n      MetaProSIPReporting::createQualityReport(tmp_path, qc_output_directory, file_suffix, file_extension_, sippeptide_clusters, n_heatmap_bins, score_plot_y_axis_min, report_natural_peptides);\n    }\n\n    return EXECUTION_OK;\n  }\n\n};\n\nint main(int argc, const char** argv)\n{\n  TOPPMetaProSIP tool;\n  return tool.main(argc, argv);\n}\n", "meta": {"hexsha": "cb8c082c01074971d469e70ea5b7ad52fad57d3e", "size": 139137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/MetaProSIP.cpp", "max_stars_repo_name": "tomas-pluskal/openms", "max_stars_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_stars_repo_licenses": ["Zlib", "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/MetaProSIP.cpp", "max_issues_repo_name": "tomas-pluskal/openms", "max_issues_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_issues_repo_licenses": ["Zlib", "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/MetaProSIP.cpp", "max_forks_repo_name": "tomas-pluskal/openms", "max_forks_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_forks_repo_licenses": ["Zlib", "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.3178788757, "max_line_length": 342, "alphanum_fraction": 0.6561302889, "num_tokens": 34601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767283, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.18800485233290684}}
{"text": "// Copyright 2020 Erik Teichmann <kontakt.teichmann@gmail.com>\n\n#ifndef INCLUDE_SAM_SYSTEM_RK4_NETWORK_HPP_\n#define INCLUDE_SAM_SYSTEM_RK4_NETWORK_HPP_\n\n#include <vector>\n\n#include <boost/numeric/odeint/integrate/check_adapter.hpp>\n#include <boost/numeric/odeint/integrate/integrate_n_steps.hpp>\n#include <boost/numeric/odeint/integrate/null_observer.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n\n#include \"./generic_network.hpp\"\n\nnamespace sam {\n\n/*! \\brief A network that is integrated with a 4th order Runge-Kutta method.\n *\n * A network that is integrated with a Runge-Kutta method of 4th order. The\n * integrator is implemented by the odeint library in boost\n * (https://www.boost.org/doc/libs/1_72_0/libs/numeric/odeint/doc/html/index.html).\n */\ntemplate<typename ODE, typename data_type = double>\nclass RK4Network: public GenericNetwork<ODE, data_type> {\n public:\n  using typename GenericNetwork<ODE, data_type>::node_size_type;\n  using typename GenericNetwork<ODE, data_type>::state_type;\n  using typename GenericNetwork<ODE, data_type>::matrix_type;\n\n  template<typename... Ts>\n  explicit RK4Network(node_size_type node_sizes, 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  boost::numeric::odeint::runge_kutta4<state_type> stepper_;\n};\n\n// Implementation\n\ntemplate<typename ODE, typename data_type>\ntemplate<typename... Ts>\nRK4Network<ODE, data_type>::RK4Network(node_size_type node_sizes,\n                                      unsigned int dimension,\n                                      Ts... parameters)\n    : GenericNetwork<ODE, data_type>(node_sizes, dimension, parameters...) {}\n\ntemplate<typename ODE, typename data_type>\ntemplate<typename observer_type>\nvoid RK4Network<ODE, data_type>::Integrate(double dt, unsigned int number_steps,\n                                           observer_type observer) {\n      this->t_ = boost::numeric::odeint::integrate_n_steps(\n          stepper_, *(this->ode_), this->x_, this->t_, dt, number_steps,\n          observer);\n}\n\n}  // namespace sam\n\n#endif  // INCLUDE_SAM_SYSTEM_RK4_NETWORK_HPP_\n", "meta": {"hexsha": "ca022221adb2c2a11d57fea4f203fd1e64c6b322", "size": 2330, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sam/system/rk4_network.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/rk4_network.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/rk4_network.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.40625, "max_line_length": 83, "alphanum_fraction": 0.7145922747, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.18800485034608042}}
{"text": "#include \"RevoluteJoint.h\"\n#include <Eigen/Geometry>\n\n#include \"RigidBodyManipulator.h\" // todo: remove this when I remove setupOldKinematicTree\n\nusing namespace Eigen;\n\nRevoluteJoint::RevoluteJoint(const std::string& name, const Isometry3d& transform_to_parent_body, const Vector3d& rotation_axis) :\n    FixedAxisOneDoFJoint(name, transform_to_parent_body, spatialJointAxis(rotation_axis)), rotation_axis(rotation_axis)\n{\n  assert(abs(rotation_axis.norm()-1)<1e-10);\n}\n\nRevoluteJoint::~RevoluteJoint()\n{\n  // empty\n}\n\nIsometry3d RevoluteJoint::jointTransform(const Eigen::Ref<const VectorXd>& q) const\n{\n  Isometry3d ret(AngleAxisd(q[0], rotation_axis));\n  ret.makeAffine();\n  return ret;\n}\n\nMatrix<double, TWIST_SIZE, 1> RevoluteJoint::spatialJointAxis(const Vector3d& rotation_axis)\n{\n  Matrix<double, TWIST_SIZE, 1> ret;\n  ret.topRows<3>() = rotation_axis;\n  ret.bottomRows<3>() = Vector3d::Zero();\n  return ret;\n}\n\nvoid RevoluteJoint::setupOldKinematicTree(RigidBodyManipulator* model, int body_ind, int position_num_start, int velocity_num_start) const\n{\n  FixedAxisOneDoFJoint::setupOldKinematicTree(model,body_ind,position_num_start,velocity_num_start);\n  model->bodies[body_ind]->pitch = 0.0;\n\n  Vector3d z_axis(0.0,0.0,1.0);\n  if (rotation_axis.dot(z_axis)<1-1e-4) {\n//    std::cout << \"T_body_to_joint (before) = \" << std::endl << model->bodies[body_ind]->T_body_to_joint << std::endl;\n    Vector4d a;\n    a << rotation_axis.cross(z_axis), acos(rotation_axis.dot(z_axis));\n    if ((std::abs(a(0))<1e-4) && (std::abs(a(1))<1e-4) && (std::abs(a(2))<1e-4))\n      a.head(3) << 0.0, 1.0, 0.0;\n//    std::cout << \"axis_angle = \" << a.transpose() << std::endl;\n    model->bodies[body_ind]->T_body_to_joint.topLeftCorner(3,3) = axis2rotmat(a);\n//    std::cout << \"T_body_to_joint (after) = \" << std::endl << model->bodies[body_ind]->T_body_to_joint << std::endl;\n  }\n}\n\n", "meta": {"hexsha": "a390ce6fed787fa07bacc431ce1d281a6e31cc25", "size": 1873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "systems/plants/joints/RevoluteJoint.cpp", "max_stars_repo_name": "peteflorence/drake", "max_stars_repo_head_hexsha": "42bc694cd2371c73f79967a6a653be769935b33f", "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": "systems/plants/joints/RevoluteJoint.cpp", "max_issues_repo_name": "peteflorence/drake", "max_issues_repo_head_hexsha": "42bc694cd2371c73f79967a6a653be769935b33f", "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/plants/joints/RevoluteJoint.cpp", "max_forks_repo_name": "peteflorence/drake", "max_forks_repo_head_hexsha": "42bc694cd2371c73f79967a6a653be769935b33f", "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": 36.0192307692, "max_line_length": 138, "alphanum_fraction": 0.7143619861, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1880048468174652}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Geometry_AdvancedModel.hpp\n//! \\author Alex Robinson\n//! \\brief  The advanced geometry model base class declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef GEOMETRY_ADVANCED_MODEL_HPP\n#define GEOMETRY_ADVANCED_MODEL_HPP\n\n// Boost Includes\n#include <boost/units/systems/cgs/area.hpp>\n\n// FRENSIE Includes\n#include \"Geometry_Model.hpp\"\n\nnamespace Geometry{\n\n//! The advanced model base class\nclass AdvancedModel : public Model\n{\n\npublic:\n\n  //! The surface id set type\n  typedef std::set<EntityId> SurfaceIdSet;\n\n  //! The surface id array type\n  typedef std::vector<EntityId> SurfaceIdArray;\n\n  //! The surface estimator data type\n  typedef std::tuple<EstimatorType,ParticleType,SurfaceIdArray> SurfaceEstimatorData;\n\n  //! surface estimator id data map type\n  typedef std::map<EstimatorId,SurfaceEstimatorData> SurfaceEstimatorIdDataMap;\n\n  //! The area unit\n  typedef boost::units::cgs::area AreaUnit;\n\n  //! The area quantity\n  typedef boost::units::quantity<AreaUnit> Area;\n\n  //! Constructor\n  AdvancedModel()\n  { /* ... */ }\n\n  //! Destructor\n  virtual ~AdvancedModel()\n  { /* ... */ }\n\n  //! Check if this is an advanced model\n  bool isAdvanced() const override\n  { return true; }\n\n  //! Check if the model has surface estimator data\n  virtual bool hasSurfaceEstimatorData() const = 0;\n\n  //! Get the surfaces\n  virtual void getSurfaces( SurfaceIdSet& surfaces ) const = 0;\n\n  //! Get the surface estimator data\n  virtual void getSurfaceEstimatorData( SurfaceEstimatorIdDataMap& surface_estimator_id_data_map ) const = 0;\n\n  //! Check if a surface exists\n  virtual bool doesSurfaceExist(\n                            const EntityId surface_id ) const = 0;\n\n  //! Get the surface area\n  virtual Area getSurfaceArea(\n                            const EntityId surface_id ) const = 0;\n\n  //! Check if the surface is a reflecting surface\n  virtual bool isReflectingSurface(\n                            const EntityId surface_id ) const = 0;\n\nprivate:\n\n  // Save the model to an archive\n  template<typename Archive>\n  void save( Archive& ar, const unsigned version ) const\n  { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( Model ); }\n\n  // Load the model from an archive\n  template<typename Archive>\n  void load( Archive& ar, const unsigned version )\n  { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( Model ); }\n\n  BOOST_SERIALIZATION_SPLIT_MEMBER();\n\n  // Declare the boost serialization access object as a friend\n  friend class boost::serialization::access;\n};\n\n} // end Geometry namespace\n\nBOOST_SERIALIZATION_ASSUME_ABSTRACT_CLASS( AdvancedModel, Geometry );\nBOOST_SERIALIZATION_CLASS_VERSION( AdvancedModel, Geometry, 0 );\n\n#endif // end GEOMETRY_ADVANCED_MODEL_HPP\n\n//---------------------------------------------------------------------------//\n// end Geometry_AdvancedModel.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "9e6227cbdc160876ab4d5e86628b27cb4f0f2dfb", "size": 3007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/geometry/core/src/Geometry_AdvancedModel.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/geometry/core/src/Geometry_AdvancedModel.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/geometry/core/src/Geometry_AdvancedModel.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": 28.6380952381, "max_line_length": 109, "alphanum_fraction": 0.6428333888, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.18800484681746518}}
{"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_REDUCTION_FUNCTIONS_SIMD_SSE_SSE2_ALL_HPP_INCLUDED\n#define BOOST_SIMD_REDUCTION_FUNCTIONS_SIMD_SSE_SSE2_ALL_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n\n#include <boost/simd/reduction/functions/all.hpp>\n#include <boost/simd/include/functions/simd/genmask.hpp>\n#include <boost/simd/sdk/simd/logical.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::all_, boost::simd::tag::sse2_,\n                              (A0),\n                              ((simd_<type16_<A0>,boost::simd::tag::sse_>))\n                            )\n  {\n    typedef typename meta::scalar_of<A0>::type sA0;\n    typedef typename meta::as_logical<sA0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return result_type(_mm_movemask_epi8(genmask(a0)) == 0xFFFF);\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "2fef3afdb5fa3ae20e6a7692576958ea2ea6b67b", "size": 1364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/reduction/include/boost/simd/reduction/functions/simd/sse/sse2/all.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/boost/simd/reduction/include/boost/simd/reduction/functions/simd/sse/sse2/all.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/boost/simd/reduction/include/boost/simd/reduction/functions/simd/sse/sse2/all.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.9714285714, "max_line_length": 84, "alphanum_fraction": 0.5835777126, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.1879138815671467}}
{"text": "#include <voxelized_geometry_tools/device_pointcloud_voxelization.hpp>\n\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\n#include <algorithm>\n#include <atomic>\n#include <cmath>\n#include <cstdint>\n#include <fstream>\n#include <memory>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <voxelized_geometry_tools/collision_map.hpp>\n#include <voxelized_geometry_tools/cuda_voxelization_helpers.h>\n#include <voxelized_geometry_tools/opencl_voxelization_helpers.h>\n#include <voxelized_geometry_tools/pointcloud_voxelization_interface.hpp>\n\nnamespace voxelized_geometry_tools\n{\nnamespace pointcloud_voxelization\n{\nVoxelizerRuntime DevicePointCloudVoxelizer::DoVoxelizePointClouds(\n    const CollisionMap& static_environment, const double step_size_multiplier,\n    const PointCloudVoxelizationFilterOptions& filter_options,\n    const std::vector<PointCloudWrapperSharedPtr>& pointclouds,\n    CollisionMap& output_environment) const\n{\n  EnforceAvailable();\n\n  const std::chrono::time_point<std::chrono::steady_clock> start_time =\n      std::chrono::steady_clock::now();\n\n  // Allocate device-side memory for tracking grids. Note that at least one grid\n  // is always allocated so that filtering is consistent, even if no points are\n  // raycast.\n  const size_t num_tracking_grids =\n      std::max(pointclouds.size(), static_cast<size_t>(1));\n\n  std::unique_ptr<TrackingGridsHandle> tracking_grids =\n      helper_interface_->PrepareTrackingGrids(\n          static_environment.GetTotalCells(),\n          static_cast<int32_t>(num_tracking_grids));\n  if (tracking_grids->GetNumTrackingGrids() != num_tracking_grids)\n  {\n    throw std::runtime_error(\"Failed to allocate device tracking grid\");\n  }\n\n  // Get X_GW, the transform from grid origin to world\n  const Eigen::Isometry3d& X_GW =\n      static_environment.GetInverseOriginTransform();\n\n  // Prepare grid data\n  const float inverse_step_size =\n      static_cast<float>(1.0 /\n          (static_environment.GetResolution() * step_size_multiplier));\n  const float inverse_cell_size =\n      static_cast<float>(static_environment.GetGridSizes().InvCellXSize());\n  const int32_t num_x_cells =\n      static_cast<int32_t>(static_environment.GetNumXCells());\n  const int32_t num_y_cells =\n      static_cast<int32_t>(static_environment.GetNumYCells());\n  const int32_t num_z_cells =\n      static_cast<int32_t>(static_environment.GetNumZCells());\n\n  // Do raycasting of the pointclouds\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n  for (size_t idx = 0; idx < pointclouds.size(); idx++)\n  {\n    const PointCloudWrapperSharedPtr& pointcloud = pointclouds.at(idx);\n\n    // Only do work if the pointcloud is non-empty, to avoid passing empty\n    // arrays into the device interface.\n    if (pointcloud->Size() > 0)\n    {\n      // Get X_WC, the transform from world to the origin of the pointcloud\n      const Eigen::Isometry3d& X_WC =\n          pointcloud->GetPointCloudOriginTransform();\n      // X_GC, transform from grid origin to the origin of the pointcloud\n      const Eigen::Isometry3f grid_pointcloud_transform_float =\n          (X_GW * X_WC).cast<float>();\n\n      const float max_range = static_cast<float>(pointcloud->MaxRange());\n\n      // Copy pointcloud\n      std::vector<float> raw_points(pointcloud->Size() * 3, 0.0);\n      for (int64_t point = 0; point < pointcloud->Size(); point++)\n      {\n        pointcloud->CopyPointLocationIntoVectorFloat(\n            point, raw_points, point * 3);\n      }\n\n      // Raycast\n      helper_interface_->RaycastPoints(\n          raw_points, max_range, grid_pointcloud_transform_float.data(),\n          inverse_step_size, inverse_cell_size, num_x_cells, num_y_cells,\n          num_z_cells, *tracking_grids, idx);\n    }\n  }\n\n  const std::chrono::time_point<std::chrono::steady_clock> raycasted_time =\n      std::chrono::steady_clock::now();\n\n  // Filter\n  const float percent_seen_free =\n      static_cast<float>(filter_options.PercentSeenFree());\n  const int32_t outlier_points_threshold =\n      filter_options.OutlierPointsThreshold();\n  const int32_t num_cameras_seen_free =\n      filter_options.NumCamerasSeenFree();\n\n  std::unique_ptr<FilterGridHandle> filter_grid =\n      helper_interface_->PrepareFilterGrid(\n          static_environment.GetTotalCells(),\n          static_environment.GetImmutableRawData().data());\n\n  helper_interface_->FilterTrackingGrids(\n      *tracking_grids, percent_seen_free, outlier_points_threshold,\n      num_cameras_seen_free, *filter_grid);\n\n  // Retrieve & return\n  helper_interface_->RetrieveFilteredGrid(\n      *filter_grid, output_environment.GetMutableRawData().data());\n\n  const std::chrono::time_point<std::chrono::steady_clock> done_time =\n      std::chrono::steady_clock::now();\n\n  return VoxelizerRuntime(\n      std::chrono::duration<double>(raycasted_time - start_time).count(),\n      std::chrono::duration<double>(done_time - raycasted_time).count());\n}\n\nCudaPointCloudVoxelizer::CudaPointCloudVoxelizer(\n    const std::map<std::string, int32_t>& options)\n{\n  device_name_ = \"CudaPointCloudVoxelizer\";\n  helper_interface_ = std::unique_ptr<DeviceVoxelizationHelperInterface>(\n      cuda_helpers::MakeCudaVoxelizationHelper(options));\n  EnforceAvailable();\n}\n\nOpenCLPointCloudVoxelizer::OpenCLPointCloudVoxelizer(\n    const std::map<std::string, int32_t>& options)\n{\n  device_name_ = \"OpenCLPointCloudVoxelizer\";\n  helper_interface_ = std::unique_ptr<DeviceVoxelizationHelperInterface>(\n      opencl_helpers::MakeOpenCLVoxelizationHelper(options));\n  EnforceAvailable();\n}\n}  // namespace pointcloud_voxelization\n}  // namespace voxelized_geometry_tools\n", "meta": {"hexsha": "c130120ef37d7121cce6e34af5f7771d10799456", "size": 5608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/voxelized_geometry_tools/device_pointcloud_voxelization.cpp", "max_stars_repo_name": "ToyotaResearchInstitute/voxelized_geometry_tools", "max_stars_repo_head_hexsha": "3928899e8493b9a812bb7b0998fd5fe9a5c98b8f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T20:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-09T02:16:33.000Z", "max_issues_repo_path": "src/voxelized_geometry_tools/device_pointcloud_voxelization.cpp", "max_issues_repo_name": "ToyotaResearchInstitute/voxelized_geometry_tools", "max_issues_repo_head_hexsha": "3928899e8493b9a812bb7b0998fd5fe9a5c98b8f", "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/voxelized_geometry_tools/device_pointcloud_voxelization.cpp", "max_forks_repo_name": "ToyotaResearchInstitute/voxelized_geometry_tools", "max_forks_repo_head_hexsha": "3928899e8493b9a812bb7b0998fd5fe9a5c98b8f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-16T08:24:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T08:24:54.000Z", "avg_line_length": 35.7197452229, "max_line_length": 80, "alphanum_fraction": 0.7423323823, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.18791387062385745}}
{"text": "#include \"generator/streets/street_geometry.hpp\"\n\n#include \"generator/boost_helpers.hpp\"\n\n#include \"indexer/feature_algo.hpp\"\n\n#include \"geometry/mercator.hpp\"\n\n#include \"base/exception.hpp\"\n\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\n#include <boost/geometry.hpp>\n\nnamespace generator\n{\nnamespace streets\n{\nPin StreetGeometry::GetOrChoosePin() const\n{\n  if (m_pin)\n    return *m_pin;\n\n  if (m_highwayGeometry)\n    return m_highwayGeometry->ChoosePin();\n\n  if (m_bindingsGeometry)\n    return m_bindingsGeometry->GetCentralBinding();\n\n  UNREACHABLE();\n}\n\nm2::RectD StreetGeometry::GetBbox() const\n{\n  if (m_highwayGeometry)\n    return m_highwayGeometry->GetBbox();\n\n  if (m_bindingsGeometry)\n    return m_bindingsGeometry->GetBbox();\n\n  if (m_pin)\n    return {m_pin->m_position, m_pin->m_position};\n\n  UNREACHABLE();\n}\n\nvoid StreetGeometry::SetPin(Pin && pin)\n{\n  m_pin = std::move(pin);\n}\n\nvoid StreetGeometry::AddHighwayLine(base::GeoObjectId const & osmId, std::vector<m2::PointD> const & line)\n{\n  if (!m_highwayGeometry)\n    m_highwayGeometry = std::make_unique<HighwayGeometry>();\n\n  m_highwayGeometry->AddLine(osmId, line);\n}\n\nvoid StreetGeometry::AddHighwayArea(base::GeoObjectId const osmId, std::vector<m2::PointD> const & border)\n{\n  if (!m_highwayGeometry)\n    m_highwayGeometry = std::make_unique<HighwayGeometry>();\n\n  m_highwayGeometry->AddArea(osmId, border);\n}\n\nvoid StreetGeometry::AddBinding(base::GeoObjectId const & osmId, m2::PointD const & point)\n{\n  if (!m_bindingsGeometry)\n    m_bindingsGeometry = std::make_unique<BindingsGeometry>();\n\n  m_bindingsGeometry->Add(osmId, point);\n}\n\n// HighwayGeometry -------------------------------------------------------------------------------------------\n\nPin HighwayGeometry::ChoosePin() const\n{\n  if (!m_areaParts.empty())\n    return ChooseAreaPin();\n\n  return ChooseMultilinePin();\n}\n\nPin HighwayGeometry::ChooseMultilinePin() const\n{\n  auto const & lines = m_multiLine.m_lines;\n  CHECK(!lines.empty(), ());\n  auto longestLine = lines.cbegin();\n  auto longestLineLength = longestLine->CalculateLength();\n  for (auto l = std::next(longestLine), end = lines.cend(); l != end; ++l)\n  {\n    auto const length = l->CalculateLength();\n    if (longestLineLength < length)\n    {\n      longestLine = l;\n      longestLineLength = length;\n    }\n  }\n\n  return ChooseLinePin(*longestLine, longestLineLength / 2);\n}\n\nPin HighwayGeometry::ChooseLinePin(Line const & line, double disposeDistance) const\n{\n  double length = 0.0;\n\n  for (auto const & segment : line.m_segments)\n  {\n    auto const & points = segment.m_points;\n    CHECK_GREATER_OR_EQUAL(points.size(), 2, ());\n    for (auto p = points.cbegin(), end = std::prev(points.cend()); p != end; ++p)\n    {\n      auto const & p1 = *p;\n      auto const & p2 = *std::next(p);\n      length += MercatorBounds::DistanceOnEarth(p1, p2);\n      if (disposeDistance < length)\n        return {p1.Mid(p2), segment.m_osmId};\n    }\n  }\n\n  UNREACHABLE();\n}\n\nPin HighwayGeometry::ChooseAreaPin() const\n{\n  CHECK(!m_areaParts.empty(), ());\n  auto const largestPart = std::max_element(m_areaParts.cbegin(), m_areaParts.cend(),\n                                            base::LessBy(&AreaPart::m_area));\n  return {largestPart->m_center, largestPart->m_osmId};\n}\n\nvoid HighwayGeometry::AddLine(base::GeoObjectId const & osmId, std::vector<m2::PointD> const & line)\n{\n  m_multiLine.Add({osmId, line});\n  ExtendLimitRect(line);\n}\n\nvoid HighwayGeometry::AddArea(base::GeoObjectId const & osmId, std::vector<m2::PointD> const & border)\n{\n  m_areaParts.emplace_back(osmId, border);\n  ExtendLimitRect(border);\n}\n\nm2::RectD const & HighwayGeometry::GetBbox() const\n{\n  return m_limitRect;\n}\n\nvoid HighwayGeometry::ExtendLimitRect(std::vector<m2::PointD> const & points)\n{\n  feature::CalcRect(points, m_limitRect);\n}\n\n// HighwayGeometry::MultiLine --------------------------------------------------------------------------------\n\nvoid HighwayGeometry::MultiLine::Add(LineSegment && segment)\n{\n  for (auto line = m_lines.begin(), end = m_lines.end(); line != end; ++line) \n  {\n    if (line->Add(std::move(segment)))\n    {\n      if (Recombine(std::move(*line)))\n        m_lines.erase(line);\n      return;\n    }\n  }\n\n  m_lines.emplace_back(Line{{std::move(segment)}});\n}\n\nbool HighwayGeometry::MultiLine::Recombine(Line && line)\n{\n  for (auto & l : m_lines)\n  {\n    if (l.Concatenate(std::move(line)))\n      return true;\n  }\n\n  return false;\n}\n\n// HighwayGeometry::Line -------------------------------------------------------------------------------------\n\nbool HighwayGeometry::Line::Concatenate(Line && other)\n{\n  // Ignore self-addition.\n  if (&other == this)\n    return false;\n\n  CHECK(!m_segments.empty(), ());\n  CHECK(!m_segments.front().m_points.empty() && !m_segments.back().m_points.empty(), ());\n  auto const & thisStart = m_segments.front().m_points.front();\n  auto const & thisEnd = m_segments.back().m_points.back();\n\n  CHECK(!other.m_segments.empty(), ());\n  CHECK(!other.m_segments.front().m_points.empty() && !other.m_segments.back().m_points.empty(), ());\n  auto const & otherStart = other.m_segments.front().m_points.front();\n  auto const & otherEnd = other.m_segments.back().m_points.back();\n\n  if (AlmostEqualAbs(thisEnd, otherStart, kCoordEqualityEps))\n  {\n    m_segments.splice(m_segments.end(), std::move(other.m_segments));\n    return true;\n  }\n\n  if (AlmostEqualAbs(thisStart, otherEnd, kCoordEqualityEps))\n  {\n    m_segments.splice(m_segments.begin(), std::move(other.m_segments));\n    return true;\n  }\n\n  if (AlmostEqualAbs(thisStart, otherStart, kCoordEqualityEps))\n  {\n    other.Reverse();\n    m_segments.splice(m_segments.begin(), std::move(other.m_segments));\n    return true;\n  }\n\n  if (AlmostEqualAbs(thisEnd, otherEnd, kCoordEqualityEps))\n  {\n    other.Reverse();\n    m_segments.splice(m_segments.end(), std::move(other.m_segments));\n    return true;\n  }\n\n  return false;\n}\n\nvoid HighwayGeometry::Line::Reverse()\n{\n  for (auto & segment : m_segments)\n    std::reverse(segment.m_points.begin(), segment.m_points.end());\n  std::reverse(m_segments.begin(), m_segments.end());\n}\n\nbool HighwayGeometry::Line::Add(LineSegment && segment)\n{\n  CHECK(!m_segments.empty(), ());\n  auto const & startSegment = m_segments.front();\n  auto const & endSegment = m_segments.back();\n  CHECK(!startSegment.m_points.empty(), ());\n  auto const & lineStart = startSegment.m_points.front();\n  CHECK(!endSegment.m_points.empty(), ());\n  auto const & lineEnd = endSegment.m_points.back();\n\n  // Ignore self-addition.\n  if (startSegment.m_osmId == segment.m_osmId || endSegment.m_osmId == segment.m_osmId)\n    return false;\n\n  CHECK(!segment.m_points.empty(), ());\n  auto const & segmentStart = segment.m_points.front();\n  auto const & segmentEnd = segment.m_points.back();\n\n  if (AlmostEqualAbs(lineEnd, segmentStart, kCoordEqualityEps))\n  {\n    m_segments.push_back(std::move(segment));\n    return true;\n  }\n\n  if (AlmostEqualAbs(lineEnd, segmentEnd, kCoordEqualityEps))\n  {\n    std::reverse(segment.m_points.begin(), segment.m_points.end());\n    m_segments.push_back(std::move(segment));\n    return true;\n  }\n\n  if (AlmostEqualAbs(lineStart, segmentEnd, kCoordEqualityEps))\n  {\n    m_segments.push_front(std::move(segment));\n    return true;\n  }\n\n  if (AlmostEqualAbs(lineStart, segmentStart, kCoordEqualityEps))\n  {\n    std::reverse(segment.m_points.begin(), segment.m_points.end());\n    m_segments.push_front(std::move(segment));\n    return true;\n  }\n\n  return false;\n}\n\ndouble HighwayGeometry::Line::CalculateLength() const noexcept\n{\n  double length = 0.0;\n  for (auto const & segment : m_segments)\n    length += segment.CalculateLength();\n  return length;\n}\n\n// HighwayGeometry::LineSegment ------------------------------------------------------------------------------\n\nHighwayGeometry::LineSegment::LineSegment(base::GeoObjectId const & osmId,\n                                          std::vector<m2::PointD> const & points)\n  : m_osmId{osmId}, m_points{points}\n{\n  CHECK_GREATER_OR_EQUAL(m_points.size(), 2, ());\n}\n\ndouble HighwayGeometry::LineSegment::CalculateLength() const noexcept\n{\n  if (m_points.size() < 2)\n    return 0.0;\n\n  double length = 0.0;\n  for (auto p1 = m_points.cbegin(), p2 = std::next(p1); p2 != m_points.cend(); p1 = p2, ++p2)\n    length += MercatorBounds::DistanceOnEarth(*p1, *p2);\n\n  return length;\n}\n\n// HighwayGeometry::AreaPart ---------------------------------------------------------------------------------\n\nHighwayGeometry::AreaPart::AreaPart(base::GeoObjectId const & osmId, std::vector<m2::PointD> const & polygon)\n  : m_osmId{osmId}\n{\n  CHECK_GREATER_OR_EQUAL(polygon.size(), 3, ());\n\n  auto boostPolygon = boost_helpers::BoostPolygon{};\n  for (auto const & p : polygon)\n    boost::geometry::append(boostPolygon, boost_helpers::BoostPoint{p.x, p.y});\n  boost::geometry::correct(boostPolygon);\n\n  boost_helpers::BoostPoint center{};\n  boost::geometry::centroid(boostPolygon, center);\n  m_center = {center.get<0>(), center.get<1>()};\n\n  m_area = boost::geometry::area(boostPolygon);\n}\n\n// BindingsGeometry ------------------------------------------------------------------------------------------\n\nPin BindingsGeometry::GetCentralBinding() const\n{\n  CHECK(m_centralBinding, (\"no bindings\"));\n  return *m_centralBinding;\n}\n\nm2::RectD const & BindingsGeometry::GetBbox() const\n{\n  CHECK(m_centralBinding, (\"no bindings\"));\n  return m_limitRect;\n}\n\nvoid BindingsGeometry::ExtendLimitRect(m2::PointD const & point)\n{\n  m_limitRect.Add(point);\n}\n\nvoid BindingsGeometry::Add(base::GeoObjectId const & osmId, m2::PointD const & point)\n{\n  ExtendLimitRect(point);\n\n  if (!m_centralBinding)\n  {\n    m_centralBinding = Pin{point, osmId};\n    return;\n  }\n\n  auto const bboxCenter = GetBbox().Center();\n  auto const centralBindingDistance = MercatorBounds::DistanceOnEarth(m_centralBinding->m_position, bboxCenter);\n  auto const pointDistance = MercatorBounds::DistanceOnEarth(point, bboxCenter);\n  if (pointDistance < centralBindingDistance)\n    m_centralBinding = Pin{point, osmId};\n}\n}  // namespace streets\n}  // namespace generator\n", "meta": {"hexsha": "91cfcf18e0dc574a12303f4c1618cf602cbc5549", "size": 10072, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generator/streets/street_geometry.cpp", "max_stars_repo_name": "LaGrunge/omim", "max_stars_repo_head_hexsha": "8ce6d970f8f0eb613531b16edd22ea8ab923e72a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-28T21:14:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-28T21:14:26.000Z", "max_issues_repo_path": "generator/streets/street_geometry.cpp", "max_issues_repo_name": "LaGrunge/omim", "max_issues_repo_head_hexsha": "8ce6d970f8f0eb613531b16edd22ea8ab923e72a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-09-09T10:11:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-02T15:04:21.000Z", "max_forks_repo_path": "generator/streets/street_geometry.cpp", "max_forks_repo_name": "LaGrunge/geocore", "max_forks_repo_head_hexsha": "b599eda29a32a14e5c02f51c66848959b50732f2", "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.0752688172, "max_line_length": 112, "alphanum_fraction": 0.6582605242, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.18791315861679628}}
{"text": "#ifndef HERMIT_SPIRIT_KARMA_IPV6_HPP\n#define HERMIT_SPIRIT_KARMA_IPV6_HPP\n\n#include <cstdint>\n#include <utility>\n#include <boost/spirit/include/karma.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/fusion/adapted/std_pair.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\n#include <hermit/ip.hpp>\n\nnamespace hermit {\n  namespace spirit {\n    namespace karma {\n    template< typename Iterator >\n      class ipv6 : public boost::spirit::karma::grammar<\n        Iterator,\n        hermit::ipv6()\n        > {\n      public:\n        ipv6() : ipv6::base_type( root ) {\n          namespace karma = boost::spirit::karma;\n          namespace phx = boost::phoenix;\n          root = ( hex_p << ':' << hex_p << ':' << hex_p << ':' << hex_p << ':' <<\n                   hex_p << ':' << hex_p << ':' << hex_p << ':' << hex_p )[\n            karma::_1 = phx::static_cast_< uint16_t >( phx::at_c< 0 >( karma::_val ) / 0x1000000000000ull ),\n            karma::_2 = phx::static_cast_< uint16_t >( phx::at_c< 0 >( karma::_val ) / 0x100000000ull ),\n            karma::_3 = phx::static_cast_< uint16_t >( phx::at_c< 0 >( karma::_val ) / 0x10000ull ),\n            karma::_4 = phx::static_cast_< uint16_t >( phx::at_c< 0 >( karma::_val ) ),\n            karma::_5 = phx::static_cast_< uint16_t >( phx::at_c< 1 >( karma::_val ) / 0x1000000000000ull ),\n            karma::_6 = phx::static_cast_< uint16_t >( phx::at_c< 1 >( karma::_val ) / 0x100000000ull ),\n            karma::_7 = phx::static_cast_< uint16_t >( phx::at_c< 1 >( karma::_val ) / 0x10000ull ),\n            karma::_8 = phx::static_cast_< uint16_t >( phx::at_c< 1 >( karma::_val ) )\n          ];\n        }\n      private:\n        boost::spirit::karma::uint_generator<uint16_t, 16> hex_p;\n        boost::spirit::karma::rule< Iterator, hermit::ipv6() > root;\n      };\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "3df7ee491eed8f7ea83f85c51e3a91a6a8fc0ea7", "size": 1837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hermit/spirit/karma/ipv6.hpp", "max_stars_repo_name": "Fadis/hermit", "max_stars_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T05:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-09T05:54:01.000Z", "max_issues_repo_path": "include/hermit/spirit/karma/ipv6.hpp", "max_issues_repo_name": "Fadis/hermit", "max_issues_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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/hermit/spirit/karma/ipv6.hpp", "max_forks_repo_name": "Fadis/hermit", "max_forks_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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.9347826087, "max_line_length": 108, "alphanum_fraction": 0.5781164943, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.18791314697989492}}
{"text": "#include <Eigen/Geometry>\n#include <nav_msgs/Odometry.h>\n#include <nodelet/nodelet.h>\n#include <quadrotor_msgs/SO3Command.h>\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <std_msgs/Float64.h>\n#include <tf/transform_datatypes.h>\n#include \"snav/snapdragon_navigator.h\"\n\nclass SO3CmdToSnav : public nodelet::Nodelet\n{\n public:\n  void onInit(void);\n\n private:\n  void so3_cmd_callback(const quadrotor_msgs::SO3Command::ConstPtr &msg);\n  void odom_callback(const nav_msgs::Odometry::ConstPtr &odom);\n  void imu_callback(const sensor_msgs::Imu::ConstPtr &pose);\n  void so3_cmd_to_qc_interface(const quadrotor_msgs::SO3Command::ConstPtr &msg);\n  void motors_on();\n  void motors_off();\n\n  //controller state\n  SnavCachedData *snav_cached_data_struct;\n\n  bool odom_set_, imu_set_, so3_cmd_set_;\n  Eigen::Quaterniond odom_q_, imu_q_;\n\n  ros::Subscriber so3_cmd_sub_;\n  ros::Subscriber odom_sub_;\n  ros::Subscriber imu_sub_;\n\n  int motor_status_;\n\n  double so3_cmd_timeout_;\n  ros::Time last_so3_cmd_time_;\n  quadrotor_msgs::SO3Command last_so3_cmd_;\n};\n\nvoid SO3CmdToSnav::odom_callback(const nav_msgs::Odometry::ConstPtr &odom)\n{\n  if(!odom_set_)\n    odom_set_ = true;\n\n  odom_q_ = Eigen::Quaterniond(\n      odom->pose.pose.orientation.w, odom->pose.pose.orientation.x,\n      odom->pose.pose.orientation.y, odom->pose.pose.orientation.z);\n    if(so3_cmd_set_ &&\n     ((ros::Time::now() - last_so3_cmd_time_).toSec() >= so3_cmd_timeout_))\n  {\n    ROS_INFO(\"so3_cmd timeout. %f seconds since last command\",\n             (ros::Time::now() - last_so3_cmd_time_).toSec());\n    const auto last_so3_cmd_ptr =\n        boost::make_shared<quadrotor_msgs::SO3Command>(last_so3_cmd_);\n\n    so3_cmd_callback(last_so3_cmd_ptr);\n  }\n}\n\nvoid SO3CmdToSnav::imu_callback(const sensor_msgs::Imu::ConstPtr &pose)\n{\n  if(!imu_set_)\n    imu_set_ = true;\n\n  imu_q_ = Eigen::Quaterniond(pose->orientation.w, pose->orientation.x,\n                              pose->orientation.y, pose->orientation.z);\n\n  if(so3_cmd_set_ &&\n     ((ros::Time::now() - last_so3_cmd_time_).toSec() >= so3_cmd_timeout_))\n  {\n    ROS_INFO(\"so3_cmd timeout. %f seconds since last command\",\n             (ros::Time::now() - last_so3_cmd_time_).toSec());\n    const auto last_so3_cmd_ptr =\n        boost::make_shared<quadrotor_msgs::SO3Command>(last_so3_cmd_);\n\n    so3_cmd_callback(last_so3_cmd_ptr);\n  }\n}\n\nvoid SO3CmdToSnav::motors_on(){\n\n  int ret = sn_spin_props();\n  if(ret == -1)\n    ROS_ERROR(\"INIT: not able to send spinning command\");\n  else\n    motor_status_ = 1;\n\n  if(snav_cached_data_struct->general_status.props_state == SN_PROPS_STATE_SPINNING)\n    ROS_ERROR(\"INIT: all the propellers are spinnig\");\n  else{\n    ROS_ERROR(\"INIT 5: all the propellers are not spinnig\");\n    motor_status_ = 0;\n  }\n\n/*\n    int counter_motors = 0;\n\t\tdo{\n\t\t//call the update 0 success\n\t\tint res_update = sn_update_data();\n\t\tif(res_update ==  -1){\n\t\tROS_ERROR(\"\\nINIT 1: flight software non functional\\n\");\n\t\treturn;\n\t\t}\n\t\t//send minimum thrust and identity attitude\n\t\tsn_send_thrust_att_ang_vel_command (0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);\n\n\t\t//run the props 0 success\n\t\t//int r = sn_spin_props();\n\t\t//if(r == -1)\n\t\t  //ROS_ERROR(\"\\nINIT 2: not able to send spinning command\\n\");\n\n\t\t//controller state\n\t\t//int size_cached_struct;\n\t\tcounter_motors++;\n\n\t\t}\n\t\twhile(counter_motors > 500);//snav_cached_data_struct->general_status.props_state != SN_PROPS_STATE_SPINNING);\n\n\t\t//sn_send_thrust_att_ang_vel_command (0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);\n\t\tfor(int i = 0; i<10; i++){\n\t\tint r = sn_spin_props();\n\t\tif(r == -1)\n\t\t  ROS_ERROR(\"\\nINIT 2: not able to send spinning command\\n\");\n\t\telse\n\t\t\tmotor_status_ = 1;\n\t\t  }\n\t\tif(snav_cached_data_struct->general_status.props_state == SN_PROPS_STATE_SPINNING)\n\t\t  ROS_ERROR(\"\\nINIT 5: all the propellers are spinnig\\n\");\n\t\telse\n\t\t  ROS_ERROR(\"\\nINIT 5: all the propellers are not spinnig\\n\");\n*/\n}\n\n\nvoid SO3CmdToSnav::motors_off(){\n\tdo{\n\t\t//call the update 0 success\n\t\tint res_update = sn_update_data();\n\t  //stop the props 0 success\n\t\tint ret = sn_stop_props();\n\t\tif(ret == -1)\n\t\t  ROS_ERROR(\"Not able to send switch off propellers\");\n\n\t\t//send minimum thrust and identity attitude\n\t\tsn_send_thrust_att_ang_vel_command (0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);\n\t\tmotor_status_ = 0;\n\t}\n\twhile(snav_cached_data_struct->general_status.props_state == SN_PROPS_STATE_SPINNING);\n\n\t//check the propellers status\n\tif(snav_cached_data_struct->general_status.props_state == SN_PROPS_STATE_SPINNING)\n\t  ROS_ERROR(\"All the propellers are still spinnig\");\n\telse\n\t  ROS_ERROR(\"All the propellers are now off\");\n}\n\nvoid SO3CmdToSnav::so3_cmd_to_qc_interface(\n  const quadrotor_msgs::SO3Command::ConstPtr &msg){\n  // grab desired forces and rotation from so3\n  const Eigen::Vector3d f_des(msg->force.x, msg->force.y, msg->force.z);\n\n  const Eigen::Quaterniond q_des(msg->orientation.w, msg->orientation.x,\n                                 msg->orientation.y, msg->orientation.z);\n  const Eigen::Vector3d ang_vel(msg->angular_velocity.x, msg->angular_velocity.y, msg->angular_velocity.z);\n\n  // convert to tf::Quaternion\n  tf::Quaternion imu_tf =\n      tf::Quaternion(imu_q_.x(), imu_q_.y(), imu_q_.z(), imu_q_.w());\n  tf::Quaternion odom_tf =\n      tf::Quaternion(odom_q_.x(), odom_q_.y(), odom_q_.z(), odom_q_.w());\n\n  const Eigen::Matrix3d R_cur(odom_q_);\n\n  //const float Psi =\n  //    0.5f * (3.0f - (R_des(0, 0) * R_cur(0, 0) + R_des(1, 0) * R_cur(1, 0) +\n  //                    R_des(2, 0) * R_cur(2, 0) + R_des(0, 1) * R_cur(0, 1) +\n  //                    R_des(1, 1) * R_cur(1, 1) + R_des(2, 1) * R_cur(2, 1) +\n  //                    R_des(0, 2) * R_cur(0, 2) + R_des(1, 2) * R_cur(1, 2) +\n   //                   R_des(2, 2) * R_cur(2, 2)));\n\n  double throttle = 0.0;\n  //if(Psi < 1.0f) // Position control stability guaranteed only when Psi < 1\n  //{\n  throttle = f_des(0) * R_cur(0, 2) + f_des(1) * R_cur(1, 2) +\n               f_des(2) * R_cur(2, 2);\n\n  //convert throttle in grams\n  throttle = throttle*1000/9.81;\n\n  int res_update = sn_update_data();\n  if(res_update ==  -1){\n    ROS_ERROR(\"\\nTRAJ 1: flight software non functional\\n\");\n    return;\n  }\n\n  int r = sn_send_thrust_att_ang_vel_command (throttle, q_des.w(), q_des.x(), q_des.y(), q_des.z(), ang_vel(0), ang_vel(1), ang_vel(2));\n  if(r == -1)\n    ROS_ERROR(\"\\nTRAJ 2: control command not send\\n\");\n}\n\nvoid SO3CmdToSnav::so3_cmd_callback(\n    const quadrotor_msgs::SO3Command::ConstPtr &msg)\n{\n  if(!so3_cmd_set_)\n    so3_cmd_set_ = true;\n\n  //switch on motors\n  if(msg->aux.enable_motors && !motor_status_)\n  \tmotors_on();\n  else if(!msg->aux.enable_motors)\n  \tmotors_off();\n\n  so3_cmd_to_qc_interface(msg);\n\n  // save last so3_cmd\n  last_so3_cmd_ = *msg;\n  last_so3_cmd_time_ = ros::Time::now();\n}\n\nvoid SO3CmdToSnav::onInit(void)\n{\n  ros::NodeHandle priv_nh(getPrivateNodeHandle());\n\n  // get param for so3 command timeout duration\n  priv_nh.param(\"so3_cmd_timeout\", so3_cmd_timeout_, 0.25);\n\n  odom_set_ = false;\n  imu_set_ = false;\n  so3_cmd_set_ = false;\n  motor_status_ = 0;\n\tsnav_cached_data_struct = NULL;\n  if (sn_get_flight_data_ptr(sizeof(SnavCachedData), &snav_cached_data_struct) != 0)\n  {\n    ROS_ERROR(\"\\nFailed to get flight data pointer!\\n\");\n    return;\n  }\n\n  so3_cmd_sub_ =\n      priv_nh.subscribe(\"so3_cmd\", 10, &SO3CmdToSnav::so3_cmd_callback, this,\n                        ros::TransportHints().tcpNoDelay());\n\n  odom_sub_ = priv_nh.subscribe(\"odom\", 10, &SO3CmdToSnav::odom_callback,\n                                this, ros::TransportHints().tcpNoDelay());\n\n  imu_sub_ = priv_nh.subscribe(\"imu\", 10, &SO3CmdToSnav::imu_callback, this,\n                               ros::TransportHints().tcpNoDelay());\n}\n\n#include <pluginlib/class_list_macros.h>\nPLUGINLIB_EXPORT_CLASS(SO3CmdToSnav, nodelet::Nodelet);", "meta": {"hexsha": "1457acc61e43db1b3837897b84051e84b309ffe2", "size": 7814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/so3cmd_to_snav_nodelet.cpp", "max_stars_repo_name": "tyuezhan/snavquad_interface", "max_stars_repo_head_hexsha": "13103c1e2ed073f1f5e07c2523782dfe6066cbb7", "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/so3cmd_to_snav_nodelet.cpp", "max_issues_repo_name": "tyuezhan/snavquad_interface", "max_issues_repo_head_hexsha": "13103c1e2ed073f1f5e07c2523782dfe6066cbb7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-07-18T21:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T20:27:03.000Z", "max_forks_repo_path": "src/so3cmd_to_snav_nodelet.cpp", "max_forks_repo_name": "tyuezhan/snavquad_interface", "max_forks_repo_head_hexsha": "13103c1e2ed073f1f5e07c2523782dfe6066cbb7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T18:29:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T20:22:16.000Z", "avg_line_length": 31.1314741036, "max_line_length": 136, "alphanum_fraction": 0.6749424111, "num_tokens": 2452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.18771290960594328}}
{"text": "// Copyright (c) 2017-2019 The Multiverse 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 \"crypto.h\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"test_fnfn.h\"\n\nusing namespace multiverse::crypto;\n\nBOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicUtfSetup)\n\nBOOST_AUTO_TEST_CASE(multisign)\n{\n    srand(time(0));\n\n    int64_t keyCount = 0;\n    int64_t signCount = 0, signTime = 0, verifyTime = 0;\n    int count = 100;\n    for (int i = 0; i < count; i++)\n    {\n        uint32_t nKey = CryptoGetRand32() % 16 + 1;\n        uint32_t nPartKey = CryptoGetRand32() % nKey + 1;\n\n        keyCount += nKey;\n\n        CCryptoKey* keys = new CCryptoKey[nKey];\n        std::set<uint256> setPubKey;\n        for (int i = 0; i < nKey; i++)\n        {\n            CryptoMakeNewKey(keys[i]);\n            setPubKey.insert(keys[i].pubkey);\n        }\n\n        uint256 anchor;\n        CryptoGetRand256(anchor);\n        uint256 msg;\n        CryptoGetRand256(msg);\n\n        std::vector<uint8_t> vchSig;\n        for (int i = 0; i < nPartKey; i++)\n        {\n            boost::posix_time::ptime t0 = boost::posix_time::microsec_clock::universal_time();\n            BOOST_CHECK(CryptoMultiSign(setPubKey, keys[i], anchor.begin(), anchor.size(), msg.begin(), msg.size(), vchSig));\n            boost::posix_time::ptime t1 = boost::posix_time::microsec_clock::universal_time();\n            signTime = (t1 - t0).ticks();\n            ++signCount;\n        }\n\n        std::set<uint256> setPartKey;\n        boost::posix_time::ptime t0 = boost::posix_time::microsec_clock::universal_time();\n        BOOST_CHECK(CryptoMultiVerify(setPubKey, anchor.begin(), anchor.size(), msg.begin(), msg.size(), vchSig, setPartKey) && (setPartKey.size() == nPartKey));\n        boost::posix_time::ptime t1 = boost::posix_time::microsec_clock::universal_time();\n        verifyTime += (t1 - t0).ticks();\n    }\n\n    std::cout << \"multisign key count : \" << keyCount << std::endl;\n    std::cout << \"multisign sign count : \" << signCount << \"; average time : \" << signTime / signCount << \"us.\" << std::endl;\n    std::cout << \"multisign verify count : \" << count << \"; time per count : \" << verifyTime / count << \"us.\"\n              << \" time per key count: \" << verifyTime / keyCount << \"us.\" << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "f0fe041787775a4a2b5c8d87e9c94391822a510f", "size": 2389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/crypto_tests.cpp", "max_stars_repo_name": "FissionAndFusion/FnFnMvWallet-Pre", "max_stars_repo_head_hexsha": "80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-08-17T07:05:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-16T09:22:32.000Z", "max_issues_repo_path": "test/crypto_tests.cpp", "max_issues_repo_name": "FissionAndFusion/FnFnMvWallet-Pre", "max_issues_repo_head_hexsha": "80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-08-18T11:09:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-22T10:02:02.000Z", "max_forks_repo_path": "test/crypto_tests.cpp", "max_forks_repo_name": "FissionAndFusion/FnFnMvWallet-Pre", "max_forks_repo_head_hexsha": "80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-08-17T01:12:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-16T09:05:31.000Z", "avg_line_length": 36.7538461538, "max_line_length": 161, "alphanum_fraction": 0.6128087066, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.18760598884090182}}
{"text": "#include \"mtwrap.h\"\n//#include <cstdint>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\nstatic boost::random::mt19937 rng(42u);\nstatic boost::random::uniform_int_distribution<> dist(1, 6);\n\nextern \"C\" {\nint roll_die(void)\n{\n    return dist(rng);\n}\n\nuint32_t mt_rand(void)\n{\n    return rng();\n}\nvoid mt_write_random(uint8_t *bytes, size_t len)\n{\n    while (len >= 4) {\n        uint32_t tmp = mt_rand();\n        memcpy(bytes, &tmp, sizeof(uint32_t));\n        bytes += 4;\n        len -= 4;\n    }\n    if (len) {\n        uint32_t tmp = mt_rand();\n        memcpy(bytes, &tmp, len);\n    }\n}\n\n}\n", "meta": {"hexsha": "4323f3b16dc9112505c70e717c422a811a8760f8", "size": 693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_examples/mtwrap.cpp", "max_stars_repo_name": "btolva/unicorn-hat-hd", "max_stars_repo_head_hexsha": "cc5716e48fc4c9630ced0b7040960fc2fd6787a8", "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_examples/mtwrap.cpp", "max_issues_repo_name": "btolva/unicorn-hat-hd", "max_issues_repo_head_hexsha": "cc5716e48fc4c9630ced0b7040960fc2fd6787a8", "max_issues_repo_licenses": ["MIT"], "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_examples/mtwrap.cpp", "max_forks_repo_name": "btolva/unicorn-hat-hd", "max_forks_repo_head_hexsha": "cc5716e48fc4c9630ced0b7040960fc2fd6787a8", "max_forks_repo_licenses": ["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.8, "max_line_length": 60, "alphanum_fraction": 0.6363636364, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.18760598715718946}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2018.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Timo Sachsenberg $\n// $Authors: David Wojnar $\n// --------------------------------------------------------------------------\n//\n#include <OpenMS/MATH/STATISTICS/PosteriorErrorProbabilityModel.h>\n\n#include <OpenMS/CONCEPT/Constants.h>\n#include <OpenMS/CONCEPT/LogStream.h>\n#include <OpenMS/DATASTRUCTURES/String.h>\n#include <OpenMS/DATASTRUCTURES/ListUtils.h>\n#include <OpenMS/FORMAT/TextFile.h>\n#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>\n#include <OpenMS/METADATA/PeptideIdentification.h>\n#include <OpenMS/METADATA/ProteinIdentification.h>\n#include <OpenMS/METADATA/PeptideHit.h>\n\n#include <QDir>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include <algorithm>\n\n\n\nusing namespace std;\n\nnamespace OpenMS\n{\n  namespace Math\n  {\n    PosteriorErrorProbabilityModel::PosteriorErrorProbabilityModel() :\n      DefaultParamHandler(\"PosteriorErrorProbabilityModel\"),\n      incorrectly_assigned_fit_param_(GaussFitter::GaussFitResult(-1, -1, -1)),\n      correctly_assigned_fit_param_(GaussFitter::GaussFitResult(-1, -1, -1)),\n      negative_prior_(0.5), max_incorrectly_(0), max_correctly_(0), smallest_score_(0)\n    {\n      defaults_.setValue(\"out_plot\", \"\", \"If given, the some output files will be saved in the following manner: <out_plot>_scores.txt for the scores and <out_plot> which contains the fitted values for each step of the EM-algorithm, e.g., out_plot = /usr/home/OMSSA123 leads to /usr/home/OMSSA123_scores.txt, /usr/home/OMSSA123 will be written. If no directory is specified, e.g. instead of '/usr/home/OMSSA123' just OMSSA123, the files will be written into the working directory.\", ListUtils::create<String>(\"advanced,output file\"));\n      defaults_.setValue(\"number_of_bins\", 100, \"Number of bins used for visualization. Only needed if each iteration step of the EM-Algorithm will be visualized\", ListUtils::create<String>(\"advanced\"));\n      defaults_.setValue(\"incorrectly_assigned\", \"Gumbel\", \"for 'Gumbel', the Gumbel distribution is used to plot incorrectly assigned sequences. For 'Gauss', the Gauss distribution is used.\", ListUtils::create<String>(\"advanced\"));\n      defaults_.setValue(\"max_nr_iterations\", 1000, \"Bounds the number of iterations for the EM algorithm when convergence is slow.\", ListUtils::create<String>(\"advanced\"));\n      defaults_.setValidStrings(\"incorrectly_assigned\", ListUtils::create<String>(\"Gumbel,Gauss\"));\n      defaultsToParam_();\n      getNegativeGnuplotFormula_ = &PosteriorErrorProbabilityModel::getGumbelGnuplotFormula;\n      getPositiveGnuplotFormula_ = &PosteriorErrorProbabilityModel::getGaussGnuplotFormula;\n    }\n\n    PosteriorErrorProbabilityModel::~PosteriorErrorProbabilityModel()\n    {\n    }\n\n    bool PosteriorErrorProbabilityModel::fit(std::vector<double>& search_engine_scores)\n    {\n      // nothing to fit?\n      if (search_engine_scores.empty()) { return false; }\n\n      //-------------------------------------------------------------\n      // Initializing Parameters\n      //-------------------------------------------------------------\n      sort(search_engine_scores.begin(), search_engine_scores.end());\n\n      smallest_score_ = search_engine_scores[0];\n\n      vector<double> x_scores{search_engine_scores};\n      for (double & d : x_scores) { d += fabs(smallest_score_) + 0.001; }\n\n      negative_prior_ = 0.7;\n      if (param_.getValue(\"incorrectly_assigned\") == \"Gumbel\")\n      {\n        incorrectly_assigned_fit_param_.x0 = Math::mean(x_scores.begin(), x_scores.begin() + ceil(0.5 * x_scores.size())) + x_scores[0];\n        incorrectly_assigned_fit_param_.sigma = Math::sd(x_scores.begin(), x_scores.end(), incorrectly_assigned_fit_param_.x0);\n        incorrectly_assigned_fit_param_.A = 1   / sqrt(2 * Constants::PI * pow(incorrectly_assigned_fit_param_.sigma, 2));\n        //TODO: Currently, the fit is calculated using the Gauss. \n        getNegativeGnuplotFormula_ = &PosteriorErrorProbabilityModel::getGumbelGnuplotFormula;\n      }\n      else\n      {\n        incorrectly_assigned_fit_param_.x0 = Math::mean(x_scores.begin(), x_scores.begin() + ceil(0.5 * x_scores.size())) + x_scores[0];\n        incorrectly_assigned_fit_param_.sigma = Math::sd(x_scores.begin(), x_scores.end(), incorrectly_assigned_fit_param_.x0);\n        incorrectly_assigned_fit_param_.A = 1   / sqrt(2 * Constants::PI * pow(incorrectly_assigned_fit_param_.sigma, 2));\n        getNegativeGnuplotFormula_ = &PosteriorErrorProbabilityModel::getGaussGnuplotFormula;\n      }\n      getPositiveGnuplotFormula_ = &PosteriorErrorProbabilityModel::getGaussGnuplotFormula;\n\n      Size x_score_start = std::min(x_scores.size() - 1, (Size) ceil(x_scores.size() * 0.7)); // if only one score is present, ceil(...) will yield 1, which is an invalid index\n      correctly_assigned_fit_param_.x0 = Math::mean(x_scores.begin() + x_score_start, x_scores.end()) + x_scores[x_score_start]; //(gauss_scores.begin()->getX() + (gauss_scores.end()-1)->getX())/2;\n      correctly_assigned_fit_param_.sigma = incorrectly_assigned_fit_param_.sigma;\n      correctly_assigned_fit_param_.A = 1.0   / sqrt(2 * Constants::PI * pow(correctly_assigned_fit_param_.sigma, 2));\n\n      vector<double> incorrect_density, correct_density;\n      fillDensities(x_scores, incorrect_density, correct_density);\n\n      double maxlike = computeMaxLikelihood(incorrect_density, correct_density);\n \n      //-------------------------------------------------------------\n      // create files for output\n      //-------------------------------------------------------------\n      bool output_plots  = (param_.getValue(\"out_plot\").toString().trim().length() > 0);\n      TextFile file;\n      if (output_plots)\n      {\n        // create output directory (if not already present)\n        QDir dir(param_.getValue(\"out_plot\").toString().toQString());\n        if (!dir.cdUp())\n        {\n          LOG_ERROR << \"Could not navigate to output directory for plots from '\" << String(dir.dirName()) << \"'.\" << std::endl;\n          return false;\n        }\n        if (!dir.exists() && !dir.mkpath(\".\"))\n        {\n          LOG_ERROR << \"Could not create output directory for plots '\" << String(dir.dirName()) << \"'.\" << std::endl;\n          return false;\n        }\n        //\n        file = initPlots(x_scores);\n      }\n\n      //-------------------------------------------------------------\n      // Estimate Parameters - EM algorithm\n      //-------------------------------------------------------------\n      bool stop_em_init = false;\n      Int max_itns = param_.getValue(\"max_nr_iterations\");\n      int delta = 6;\n      int itns = 0;\n      \n      do\n      {\n        //-------------------------------------------------------------\n        // E-STEP\n        double one_minus_sum_posterior = one_minus_sum_post(incorrect_density, correct_density);\n        double sum_posterior = sum_post(incorrect_density, correct_density);\n\n        // new mean\n        double sum_positive_x0 = sum_pos_x0(x_scores, incorrect_density, correct_density);\n        double sum_negative_x0 = sum_neg_x0(x_scores, incorrect_density, correct_density);\n\n        double positive_mean = sum_positive_x0 / one_minus_sum_posterior;\n        double negative_mean = sum_negative_x0 / sum_posterior;\n\n        //i new standard deviation\n        double sum_positive_sigma = sum_pos_sigma(x_scores, incorrect_density, correct_density, positive_mean);\n        double sum_negative_sigma = sum_neg_sigma(x_scores, incorrect_density, correct_density, negative_mean);\n\n        // update parameters\n        correctly_assigned_fit_param_.x0 = positive_mean;\n        if (sum_positive_sigma  != 0)\n        {\n          correctly_assigned_fit_param_.sigma = sqrt(sum_positive_sigma / one_minus_sum_posterior);\n          correctly_assigned_fit_param_.A = 1 / sqrt(2 * Constants::PI * pow(correctly_assigned_fit_param_.sigma, 2));\n        }\n\n        incorrectly_assigned_fit_param_.x0 = negative_mean;\n        if (sum_negative_sigma  != 0)\n        {\n          incorrectly_assigned_fit_param_.sigma = sqrt(sum_negative_sigma / sum_posterior);\n          incorrectly_assigned_fit_param_.A = 1 / sqrt(2 * Constants::PI * pow(incorrectly_assigned_fit_param_.sigma, 2));\n        }\n\n        // compute new prior probabilities negative peptides\n        fillDensities(x_scores, incorrect_density, correct_density);\n        sum_posterior = sum_post(incorrect_density, correct_density);\n        negative_prior_ = sum_posterior / x_scores.size();\n\n        double new_maxlike(computeMaxLikelihood(incorrect_density, correct_density));\n        if (boost::math::isnan(new_maxlike - maxlike) \n          || new_maxlike < maxlike)\n        {\n          return false;\n        }\n\n        // check termination criterium\n        if ((new_maxlike - maxlike) < pow(10.0, -delta) || itns >= max_itns)\n        {\n          if (itns >= max_itns)\n          {\n            LOG_WARN << \"Number of iterations exceeded. Convergence criterion not met. Last likelihood increase: \" << (new_maxlike - maxlike) << endl;\n            LOG_WARN << \"Algorithm returns probabilites for suboptimal fit. You might want to try raising the max. number of iterations and have a look at the distribution.\" << endl;\n          }\n          stop_em_init = true;\n          sum_posterior = sum_post(incorrect_density, correct_density);\n          negative_prior_ = sum_posterior / x_scores.size();\n\n        }\n\n        if (output_plots)\n        {\n          String formula1, formula2, formula3;\n          formula1 = ((this)->*(getNegativeGnuplotFormula_))(incorrectly_assigned_fit_param_) + \"* \" + String(negative_prior_); //String(incorrectly_assigned_fit_param_.A) +\" * exp(-(x - \" + String(incorrectly_assigned_fit_param_.x0) + \") ** 2 / 2 / (\" + String(incorrectly_assigned_fit_param_.sigma) + \") ** 2)\"+ \"*\" + String(negative_prior_);\n          formula2 = ((this)->*(getPositiveGnuplotFormula_))(correctly_assigned_fit_param_) + \"* (1 - \" + String(negative_prior_) + \")\"; //String(correctly_assigned_fit_param_.A) +\" * exp(-(x - \" + String(correctly_assigned_fit_param_.x0) + \") ** 2 / 2 / (\" + String(correctly_assigned_fit_param_.sigma) + \") ** 2)\"+ \"* (1 - \" + String(negative_prior_) + \")\";\n          formula3 = getBothGnuplotFormula(incorrectly_assigned_fit_param_, correctly_assigned_fit_param_);\n          // important: use single quotes for paths, since otherwise backslashes will not be accepted on Windows!\n          file.addLine(\"plot '\" + (String)param_.getValue(\"out_plot\") + \"_scores.txt' with boxes, \" + formula1 + \" , \" + formula2 + \" , \" + formula3);\n        }\n        //update maximum likelihood\n        maxlike = new_maxlike;\n        ++itns;\n      } while (!stop_em_init);\n\n      //-------------------------------------------------------------\n      // Finished fitting\n      //-------------------------------------------------------------\n      if (param_.getValue(\"incorrectly_assigned\") == \"Gumbel\")\n      {\n        max_incorrectly_ = getGumbel_(incorrectly_assigned_fit_param_.x0, incorrectly_assigned_fit_param_);\n      }\n      else\n      {\n        max_incorrectly_ = incorrectly_assigned_fit_param_.eval(incorrectly_assigned_fit_param_.x0);\n      }\n      max_correctly_ = correctly_assigned_fit_param_.eval(correctly_assigned_fit_param_.x0);\n\n      if (output_plots)\n      {\n        String formula1 = ((this)->*(getNegativeGnuplotFormula_))(incorrectly_assigned_fit_param_) + \"*\" + String(negative_prior_); //String(incorrectly_assigned_fit_param_.A) +\" * exp(-(x - \" + String(incorrectly_assigned_fit_param_.x0) + \") ** 2 / 2 / (\" + String(incorrectly_assigned_fit_param_.sigma) + \") ** 2)\"+ \"*\" + String(negative_prior_);\n        String formula2 = ((this)->*(getPositiveGnuplotFormula_))(correctly_assigned_fit_param_) + \"* (1 - \" + String(negative_prior_) + \")\"; // String(correctly_assigned_fit_param_.A) +\" * exp(-(x - \" + String(correctly_assigned_fit_param_.x0) + \") ** 2 / 2 / (\" + String(correctly_assigned_fit_param_.sigma) + \") ** 2)\"+ \"* (1 - \" + String(negative_prior_) + \")\";\n        String formula3 = getBothGnuplotFormula(incorrectly_assigned_fit_param_, correctly_assigned_fit_param_);\n        // important: use single quotes for paths, since otherwise backslashes will not be accepted on Windows!\n        file.addLine(\"plot '\" + (String)param_.getValue(\"out_plot\") + \"_scores.txt' with boxes, \" + formula1 + \" , \" + formula2 + \" , \" + formula3);\n        file.store((String)param_.getValue(\"out_plot\"));\n        tryGnuplot((String)param_.getValue(\"out_plot\"));\n      }\n      return true;\n    }\n\n    bool PosteriorErrorProbabilityModel::fit(std::vector<double>& search_engine_scores, vector<double>& probabilities)\n    {\n      bool return_value = fit(search_engine_scores);\n\n      if (!return_value) return false;\n\n      probabilities = std::vector<double>(search_engine_scores);\n      for (double & p : probabilities) { p = computeProbability(p); }\n\n      return true;\n    }\n\n    void PosteriorErrorProbabilityModel::fillDensities(vector<double>& x_scores, vector<double>& incorrect_density, vector<double>& correct_density)\n    {\n      if (incorrect_density.size() != x_scores.size())\n      {\n        incorrect_density.resize(x_scores.size());\n        correct_density.resize(x_scores.size());\n      }\n      vector<double>::iterator incorrect(incorrect_density.begin());\n      vector<double>::iterator correct(correct_density.begin());\n      for (double const & score : x_scores)\n      {\n        // TODO: incorrect is currently filled with gauss as fitting gumble is not supported\n        *incorrect = incorrectly_assigned_fit_param_.eval(score);\n        *correct = correctly_assigned_fit_param_.eval(score);\n        ++incorrect;\n        ++correct;\n      }\n    }\n\n    double PosteriorErrorProbabilityModel::computeMaxLikelihood(vector<double>& incorrect_density, vector<double>& correct_density)\n    {\n      double maxlike(0);\n      vector<double>::iterator incorrect = incorrect_density.begin();\n      for (vector<double>::iterator correct = correct_density.begin(); correct < correct_density.end(); ++correct, ++incorrect)\n      {\n        maxlike += log10(negative_prior_ * (*incorrect) + (1 - negative_prior_) * (*correct));\n      }\n      return maxlike;\n    }\n\n    double PosteriorErrorProbabilityModel::one_minus_sum_post(vector<double>& incorrect_density, vector<double>& correct_density)\n    {\n      double one_min(0);\n      vector<double>::iterator incorrect = incorrect_density.begin();\n      for (vector<double>::iterator correct = correct_density.begin(); correct < correct_density.end(); ++correct, ++incorrect)\n      {\n        one_min +=  1  - ((negative_prior_ * (*incorrect)) / ((negative_prior_ * (*incorrect)) + (1 - negative_prior_) * (*correct)));\n      }\n      return one_min;\n    }\n\n    double PosteriorErrorProbabilityModel::sum_post(vector<double>& incorrect_density, vector<double>& correct_density)\n    {\n      double post(0);\n      vector<double>::iterator incorrect = incorrect_density.begin();\n      for (vector<double>::iterator correct = correct_density.begin(); correct < correct_density.end(); ++correct, ++incorrect)\n      {\n        post += ((negative_prior_ * (*incorrect)) / ((negative_prior_ * (*incorrect)) + (1 - negative_prior_) * (*correct)));\n      }\n      return post;\n    }\n\n    double PosteriorErrorProbabilityModel::sum_pos_x0(vector<double>& x_scores, vector<double>& incorrect_density, vector<double>& correct_density)\n    {\n      double pos_x0(0);\n      vector<double>::iterator the_x = x_scores.begin();\n      vector<double>::iterator incorrect = incorrect_density.begin();\n      for (vector<double>::iterator correct = correct_density.begin(); correct < correct_density.end(); ++correct, ++incorrect, ++the_x)\n      {\n        pos_x0 += ((1  - ((negative_prior_ * (*incorrect)) / ((negative_prior_ * (*incorrect)) + (1 - negative_prior_) * (*correct)))) * (*the_x));\n      }\n      return pos_x0;\n    }\n\n    double PosteriorErrorProbabilityModel::sum_neg_x0(vector<double>& x_scores, vector<double>& incorrect_density, vector<double>& correct_density)\n    {\n      double neg_x0(0);\n      vector<double>::iterator the_x = x_scores.begin();\n      vector<double>::iterator correct = correct_density.begin();\n      for (vector<double>::iterator incorrect = incorrect_density.begin(); incorrect < incorrect_density.end(); ++correct, ++incorrect, ++the_x)\n      {\n        neg_x0 += ((((negative_prior_ * (*incorrect)) / ((negative_prior_ * (*incorrect)) + (1 - negative_prior_) * (*correct)))) * (*the_x));\n      }\n      return neg_x0;\n    }\n\n    double PosteriorErrorProbabilityModel::sum_pos_sigma(vector<double>& x_scores, vector<double>& incorrect_density, vector<double>& correct_density, double positive_mean)\n    {\n      double pos_sigma(0);\n      vector<double>::iterator the_x = x_scores.begin();\n      vector<double>::iterator incorrect = incorrect_density.begin();\n      for (vector<double>::iterator correct = correct_density.begin(); correct < correct_density.end(); ++correct, ++incorrect, ++the_x)\n      {\n        pos_sigma += ((1  - ((negative_prior_ * (*incorrect)) / ((negative_prior_ * (*incorrect)) + (1 - negative_prior_) * (*correct)))) * pow((*the_x) - positive_mean, 2));\n      }\n      return pos_sigma;\n    }\n\n    double PosteriorErrorProbabilityModel::sum_neg_sigma(vector<double>& x_scores, vector<double>& incorrect_density, vector<double>& correct_density, double positive_mean)\n    {\n      double neg_sigma(0);\n      vector<double>::iterator the_x = x_scores.begin();\n      vector<double>::iterator incorrect = incorrect_density.begin();\n      for (vector<double>::iterator correct = correct_density.begin(); correct < correct_density.end(); ++correct, ++incorrect, ++the_x)\n      {\n        neg_sigma += ((((negative_prior_ * (*incorrect)) / ((negative_prior_ * (*incorrect)) + (1 - negative_prior_) * (*correct)))) * pow((*the_x) - positive_mean, 2));\n      }\n      return neg_sigma;\n    }\n\n    double PosteriorErrorProbabilityModel::computeProbability(double score) const\n    {\n      score = score + fabs(smallest_score_) + 0.001;\n      double x_neg, x_pos;\n\n      // the score is smaller than the peak of incorrectly assigned sequences. To ensure that the probabilities wont rise again use the incorrectly assigned peak for computation\n      if (score < incorrectly_assigned_fit_param_.x0)\n      {\n        x_neg = max_incorrectly_;\n        x_pos = correctly_assigned_fit_param_.eval(score);\n      }\n      // same as above. However, this time to ensure that probabilities wont drop again.\n      else if (score > correctly_assigned_fit_param_.x0)\n      {\n        x_neg = getGumbel_(score, incorrectly_assigned_fit_param_);\n        x_pos = max_correctly_;\n      }\n      // if its in between use the normal formula\n      else\n      {\n        x_neg = getGumbel_(score, incorrectly_assigned_fit_param_);\n        x_pos = correctly_assigned_fit_param_.eval(score);\n      }\n      return (negative_prior_ * x_neg) / ((negative_prior_ * x_neg) + (1 - negative_prior_) * x_pos);\n    }\n\n    TextFile PosteriorErrorProbabilityModel::initPlots(vector<double>& x_scores)\n    {\n      std::vector<DPosition<2> > points;\n      Int number_of_bins = param_.getValue(\"number_of_bins\");\n      points.resize(number_of_bins);\n      DPosition<2> temp;\n      double dividing_score = (x_scores.back() - x_scores[0]) / number_of_bins;\n\n      temp.setX(dividing_score / 2);\n      temp.setY(0);\n      Int bin = 0;\n      points[bin] = temp;\n      double temp_divider = dividing_score;\n      for (std::vector<double>::iterator it = x_scores.begin(); it < x_scores.end(); ++it)\n      {\n        if (temp_divider - *it >= 0 && bin < number_of_bins - 1)\n        {\n          points[bin].setY(points[bin].getY() + 1);\n        }\n        else if (bin  == number_of_bins - 1)\n        {\n          points[bin].setY(points[bin].getY() + 1);\n        }\n        else\n        {\n          temp.setX((temp_divider + temp_divider + dividing_score) / 2);\n          temp.setY(1);\n          ++bin;\n          points[bin] = temp;\n          temp_divider += dividing_score;\n        }\n      }\n\n      TextFile data_points;\n      for (vector<DPosition<2> >::iterator it = points.begin(); it < points.end(); ++it)\n      {\n        it->setY(it->getY() / (x_scores.size()  * dividing_score));\n        data_points << (String(it->getX()) + \"\\t\" + it->getY());\n      }\n      data_points.store((String)param_.getValue(\"out_plot\") + \"_scores.txt\");\n\n      TextFile file;\n      file << \"set terminal pdf color solid linewidth 2.0 rounded\";\n      //file<<\"set style empty solid 0.5 border -1\";\n      //file<<\"set style function lines\";\n      file << \"set xlabel \\\"discriminant score\\\"\";\n      file << \"set ylabel \\\"density\\\"\";\n      //TODO: file<<\"set title \";\n      file << \"set key off\";\n      // important: use single quotes for paths, since otherwise backslashes will not be accepted on Windows!\n      file <<  \"set output '\" + (String)param_.getValue(\"out_plot\") + \".pdf'\";\n      String formula1 = ((this)->*(getNegativeGnuplotFormula_))(incorrectly_assigned_fit_param_) + \"* \" + String(negative_prior_); //String(incorrectly_assigned_fit_param_.A) +\" * exp(-(x - \" + String(incorrectly_assigned_fit_param_.x0) + \") ** 2 / 2 / (\" + String(incorrectly_assigned_fit_param_.sigma) + \") ** 2)\"+ \"*\" + String(negative_prior_);\n      String formula2 = ((this)->*(getPositiveGnuplotFormula_))(correctly_assigned_fit_param_) + \"* (1 - \" + String(negative_prior_) + \")\"; //String(correctly_assigned_fit_param_.A) +\" * exp(-(x - \" + String(correctly_assigned_fit_param_.x0) + \") ** 2 / 2 / (\" + String(correctly_assigned_fit_param_.sigma) + \") ** 2)\"+ \"* (1 - \" + String(negative_prior_) + \")\";\n      // important: use single quotes for paths, since otherwise backslashes will not be accepted on Windows!\n      file << (\"plot '\" + (String)param_.getValue(\"out_plot\") + \"_scores.txt' with boxes, \" + formula1 + \" , \" + formula2);\n      return file;\n    }\n\n    const String PosteriorErrorProbabilityModel::getGumbelGnuplotFormula(const GaussFitter::GaussFitResult& params) const\n    {\n      // build a formula with the fitted parameters for gnuplot\n      stringstream formula;\n      formula << \"(1/\" << params.sigma << \") * \" << \"exp(( \" << params.x0 << \"- x)/\" << params.sigma << \") * exp(-exp((\" << params.x0 << \" - x)/\" << params.sigma << \"))\";\n      return formula.str();\n    }\n\n    const String PosteriorErrorProbabilityModel::getGaussGnuplotFormula(const GaussFitter::GaussFitResult& params) const\n    {\n      stringstream formula;\n      formula << params.A << \" * exp(-(x - \" << params.x0 << \") ** 2 / 2 / (\" << params.sigma << \") ** 2)\";\n      return formula.str();\n    }\n\n    const String PosteriorErrorProbabilityModel::getBothGnuplotFormula(const GaussFitter::GaussFitResult& incorrect, const GaussFitter::GaussFitResult& correct) const\n    {\n      stringstream formula;\n      formula << negative_prior_ << \"*\" <<  ((this)->*(getNegativeGnuplotFormula_))(incorrect) << \" + (1-\" << negative_prior_ << \")*\" << ((this)->*(getPositiveGnuplotFormula_))(correct);\n      return formula.str();\n    }\n\n    void PosteriorErrorProbabilityModel::plotTargetDecoyEstimation(vector<double>& target, vector<double>& decoy)\n    {\n      if (target.size() == 0 || decoy.size() == 0)\n      {\n        StringList empty;\n        if (target.size() == 0) empty.push_back(\"target\");\n        if (decoy.size() == 0) empty.push_back(\"decoy\");\n        LOG_WARN << \"Target-Decoy plot was called, but '\" << ListUtils::concatenate(empty, \"' and '\") << \"' has no data! Unable to create a target-decoy plot.\" << std::endl;\n        return;\n      }\n      Int number_of_bins = param_.getValue(\"number_of_bins\");\n      std::vector<DPosition<3> > points(number_of_bins);\n      DPosition<3> temp;\n\n      sort(target.begin(), target.end());\n      sort(decoy.begin(), decoy.end());\n\n      double dividing_score = (max(target.back(), decoy.back()) /*scores.back()*/ - min(target[0], decoy[0]) /*scores[0]*/) / number_of_bins;\n\n      temp[0] = (dividing_score / 2);\n      temp[1] = 0;\n      temp[2] = 0;\n      Int bin = 0;\n      points[bin] = temp;\n      double temp_divider = dividing_score;\n      for (std::vector<double>::iterator it = target.begin(); it < target.end(); ++it)\n      {\n        *it = *it + fabs(smallest_score_) + 0.001;\n        if (temp_divider - *it >= 0 && bin < number_of_bins - 1)\n        {\n          points[bin][1] += 1;\n        }\n        else if (bin  == number_of_bins - 1)\n        {\n          points[bin][1] += 1;\n        }\n        else\n        {\n          temp[0] = ((temp_divider + temp_divider + dividing_score) / 2);\n          temp[1] = 1;\n          ++bin;\n          points[bin] = temp;\n          temp_divider += dividing_score;\n        }\n      }\n\n      bin = 0;\n      temp_divider = dividing_score;\n      for (std::vector<double>::iterator it = decoy.begin(); it < decoy.end(); ++it)\n      {\n        *it = *it + fabs(smallest_score_) + 0.001;\n        if (temp_divider - *it >= 0 && bin < number_of_bins - 1)\n        {\n          points[bin][2] += 1;\n        }\n        else if (bin  == number_of_bins - 1)\n        {\n          points[bin][2] += 1;\n        }\n        else\n        {\n          // temp[0] = ((temp_divider + temp_divider + dividing_score)/2);\n          // temp[2] = 1;\n          ++bin;\n          points[bin][2] = 1;\n          temp_divider += dividing_score;\n        }\n      }\n\n      TextFile data_points;\n      for (vector<DPosition<3> >::iterator it = points.begin(); it < points.end(); ++it)\n      {\n        (*it)[1] = ((*it)[1] / ((decoy.size() + target.size())  * dividing_score));\n        (*it)[2] = ((*it)[2] / ((decoy.size() + target.size())  * dividing_score));\n        String temp_ = (*it)[0];\n        temp_ += \"\\t\";\n        temp_ += (*it)[1];\n        temp_ += \"\\t\";\n        temp_ += (*it)[2];\n        data_points << temp_;\n      }\n      data_points.store((String)param_.getValue(\"out_plot\") + \"_target_decoy_scores.txt\");\n      TextFile file;\n      file << \"set terminal pdf color solid linewidth 2.0 rounded\";\n      //file<<\"set style empty solid 0.5 border -1\";\n      //file<<\"set style function lines\";\n      file << \"set xlabel \\\"discriminant score\\\"\";\n      file << \"set ylabel \\\"density\\\"\";\n      //TODO: file<<\"set title \";\n      file << \"set key off\";\n      // important: use single quotes for paths, since otherwise backslashes will not be accepted on Windows!\n      file << String(\"set output '\") +  (String)param_.getValue(\"out_plot\") + \"_target_decoy.pdf'\";\n      String formula1, formula2;\n      formula1 = getGumbelGnuplotFormula(getIncorrectlyAssignedFitResult()) + \"* \" + String(getNegativePrior()); //String(incorrectly_assigned_fit_param_.A) +\" * exp(-(x - \" + String(incorrectly_assigned_fit_param_.x0) + \") ** 2 / 2 / (\" + String(incorrectly_assigned_fit_param_.sigma) + \") ** 2)\"+ \"*\" + String(negative_prior_);\n      formula2 = getGaussGnuplotFormula(getCorrectlyAssignedFitResult()) + \"* (1 - \" + String(getNegativePrior()) + \")\"; //String(correctly_assigned_fit_param_.A) +\" * exp(-(x - \" + String(correctly_assigned_fit_param_.x0) + \") ** 2 / 2 / (\" + String(correctly_assigned_fit_param_.sigma) + \") ** 2)\"+ \"* (1 - \" + String(negative_prior_) + \")\";\n      // important: use single quotes for paths, since otherwise backslashes will not be accepted on Windows!\n      file << (\"plot '\" + (String)param_.getValue(\"out_plot\") + \"_target_decoy_scores.txt'   using 1:3  with boxes fill solid 0.8 noborder, \\\"\" + (String)param_.getValue(\"out_plot\") + \"_target_decoy_scores.txt\\\"  using 1:2  with boxes, \" + formula1 + \" , \" + formula2);\n      file.store((String)param_.getValue(\"out_plot\") + \"_target_decoy\");\n      tryGnuplot((String)param_.getValue(\"out_plot\") + \"_target_decoy\");\n    }\n\n    void PosteriorErrorProbabilityModel::tryGnuplot(const String& gp_file)\n    {\n      LOG_INFO << \"Attempting to call 'gnuplot' ...\";\n      String cmd = String(\"gnuplot \\\"\") + gp_file + \"\\\"\";\n      if (system(cmd.c_str()))  // 0 is success!\n      {\n        LOG_WARN << \"Calling 'gnuplot' on '\" << gp_file << \"' failed. Please create plots manually.\" << std::endl;\n      }\n      else LOG_INFO << \" success!\" << std::endl;\n\n    }\n\n    double PosteriorErrorProbabilityModel::transformScore_(const String & engine, const PeptideHit & hit)\n    {\n      // Set fixed e-value threshold\n      const double smallest_e_value_ = numeric_limits<double>::denorm_min();\n\n      if (engine == \"OMSSA\")\n      {\n        return (-1) * log10(max(hit.getScore(), smallest_e_value_));\n      }\n      else if (engine == \"MYRIMATCH\" ) \n      {\n        return hit.getScore();\n      }\n      else if (engine == \"XTANDEM\")\n      {\n        return (-1) * log10(max((double)hit.getMetaValue(\"E-Value\"), smallest_e_value_));\n      }\n      else if (engine == \"MASCOT\")\n      {\n        // issue #740: unable to fit data with score 0\n        if (hit.getScore() == 0.0) \n        {\n          return numeric_limits<double>::quiet_NaN();\n        }\n        // end issue #740\n        if (hit.metaValueExists(\"EValue\"))\n        {\n          return (-1) * log10(max((double)hit.getMetaValue(\"EValue\"), smallest_e_value_));\n        }\n        if (hit.metaValueExists(\"expect\"))\n        {\n          return (-1) * log10(max((double)hit.getMetaValue(\"expect\"), smallest_e_value_));\n        }\n      }\n      else if (engine == \"SPECTRAST\")\n      {\n        return 100 * hit.getScore(); // f-val\n      }\n      else if (engine == \"SIMTANDEM\")\n      {\n        if (hit.metaValueExists(\"E-Value\"))\n        {\n          return (-1) * log10(max((double)hit.getMetaValue(\"E-Value\"), smallest_e_value_));\n        }\n      }\n      else if ((engine == \"MSGFPLUS\") || (engine == \"MS-GF+\"))\n      {\n        if (hit.metaValueExists(\"MS:1002053\"))  // name: MS-GF:EValue\n        {\n          return (-1) * log10(max((double)hit.getMetaValue(\"MS:1002053\"), smallest_e_value_));\n        }\n        else if (hit.metaValueExists(\"expect\"))\n        {\n          return (-1) * log10(max((double)hit.getMetaValue(\"expect\"), smallest_e_value_));\n        }\n      }\n      else if (engine == \"COMET\")\n      {\n        if (hit.metaValueExists(\"MS:1002257\")) // name: Comet:expectation value\n        {\n          return (-1) * log10(max((double)hit.getMetaValue(\"MS:1002257\"), smallest_e_value_));\n        }\n        else if (hit.metaValueExists(\"expect\"))\n        {\n          return (-1) * log10(max((double)hit.getMetaValue(\"expect\"), smallest_e_value_));\n        }\n      }\n\n      throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"No parameters for chosen search engine\", \"The chosen search engine is currently not supported\");\n    }\n\n    map<String, vector<vector<double>>> PosteriorErrorProbabilityModel::extractAndTransformScores(\n      const vector<ProteinIdentification> & protein_ids,\n      const vector<PeptideIdentification> & peptide_ids,\n      const bool split_charge,\n      const bool top_hits_only,\n      const bool target_decoy_available,\n      const double fdr_for_targets_smaller)\n    {\n      std::set<Int> charges;\n      const StringList search_engines = ListUtils::create<String>(\"XTandem,OMSSA,MASCOT,SpectraST,MyriMatch,SimTandem,MSGFPlus,MS-GF+,Comet\");\n\n      if (split_charge)\n      {  // determine different charges in data\n        for (PeptideIdentification const & pep_id : peptide_ids)\n        {\n          const vector<PeptideHit>& hits = pep_id.getHits();\n          for (PeptideHit const & hit : hits) { charges.insert(hit.getCharge()); }\n        }\n        if (charges.empty())\n        {\n          throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"'split_charge' is set, but the list of charge states is empty\");\n        }\n      }\n\n      set<Int>::iterator charge_it = charges.begin(); // charges can be empty, no problem if split_charge is not set\n      map<String, vector<vector<double> > > all_scores;\n      char splitter = ','; // to split the engine from the charge state later on\n      do\n      {\n        vector<double> scores, decoy, target;\n        for (String supported_engine : search_engines)\n        {\n          supported_engine.toUpper();\n          for (ProteinIdentification const & prot : protein_ids)\n          {\n            String search_engine = prot.getSearchEngine();\n            search_engine.toUpper();\n\n            if (supported_engine == search_engine)\n            {\n              for (PeptideIdentification pep : peptide_ids)\n              {\n                // make sure we are comparing peptide and proteins of the same search run\n                if (prot.getIdentifier() == pep.getIdentifier())\n                {\n                  pep.sort();\n                  vector<PeptideHit>& hits = pep.getHits();\n                  if (top_hits_only)\n                  {\n                    if (!hits.empty() && (!split_charge || hits[0].getCharge() == *charge_it))\n                    {\n                      double score = PosteriorErrorProbabilityModel::transformScore_(supported_engine, hits[0]);\n                      if (!boost::math::isnan(score)) // issue #740: ignore scores with 0 values, otherwise you will get the error \"unable to fit data\"\n                      {\n                        scores.push_back(score);\n\n                        if (target_decoy_available)\n                        {\n                          if (hits[0].getScore() < fdr_for_targets_smaller)\n                          {\n                            target.push_back(score);\n                          }\n                          else\n                          {\n                            decoy.push_back(score);\n                          }\n                        }\n                      }\n                    }\n                  }\n                  else\n                  {\n                    for (PeptideHit const & hit : hits)\n                    {\n                      if (!split_charge || (hit.getCharge() == *charge_it))\n                      {\n                        double score = PosteriorErrorProbabilityModel::transformScore_(supported_engine, hit);\n                        if (!boost::math::isnan(score)) // issue #740: ignore scores with 0 values, otherwise you will get the error \"unable to fit data\"\n                        {\n                          scores.push_back(score);\n                        }\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          }\n\n          if (scores.size() > 2)\n          {\n            vector<vector<double> > tmp;\n            tmp.push_back(scores);\n            tmp.push_back(target);\n            tmp.push_back(decoy);\n\n            if (split_charge)\n            {\n              String engine_with_charge_state = supported_engine + String(splitter) + String(*charge_it);\n              all_scores.insert(make_pair(engine_with_charge_state, tmp));\n            }\n            else\n            {\n              all_scores.insert(make_pair(supported_engine, tmp));\n            }\n          }\n\n          scores.clear();\n          target.clear();\n          decoy.clear();\n        }\n\n        if (split_charge) { ++charge_it; }\n      } while (charge_it != charges.end());\n      return all_scores;\n    }\n\n\n    void PosteriorErrorProbabilityModel::updateScores(\n      const PosteriorErrorProbabilityModel & PEP_model,\n      const String & search_engine,\n      const Int charge,\n      const bool prob_correct,\n      const bool split_charge,\n      vector<ProteinIdentification> & protein_ids,\n      vector<PeptideIdentification> & peptide_ids,\n      bool & unable_to_fit_data,\n      bool & data_might_not_be_well_fit)\n    {\n      String engine(search_engine);\n      unable_to_fit_data = true;\n      data_might_not_be_well_fit = true;\n\n      engine.toUpper();\n      for (ProteinIdentification & prot : protein_ids)\n      {\n        String search_engine = prot.getSearchEngine();\n        search_engine.toUpper();\n\n        if (engine == search_engine)\n        {\n          for (PeptideIdentification & pep : peptide_ids)\n          {\n            if (prot.getIdentifier() == pep.getIdentifier())\n            {\n              String score_type = pep.getScoreType() + \"_score\";\n              vector<PeptideHit> hits = pep.getHits();\n              for (PeptideHit & hit : hits)\n              {\n                if (!split_charge || (hit.getCharge() == charge))\n                {\n                  double score;\n                  hit.setMetaValue(score_type, hit.getScore());\n                  score = PosteriorErrorProbabilityModel::transformScore_(engine, hit);\n\n                  if (boost::math::isnan(score)) // issue #740: ignore scores with 0 values, otherwise you will get the error \"unable to fit data\"\n                  {\n                    score = 1.0;\n                  }\n                  else \n                  { \n                    score = PEP_model.computeProbability(score);\n\n                    // invalid score? invalid fit!\n                    if ((score > 0.0) && (score < 1.0)) unable_to_fit_data = false; \n                    if ((score > 0.2) && (score < 0.8)) data_might_not_be_well_fit = false;\n                  }\n                  hit.setScore(score);\n                  if (prob_correct)\n                  {\n                    hit.setScore(1.0 - score);\n                  }\n                  else\n                  {\n                    hit.setScore(score);\n                  }\n                }\n              }\n              pep.setHits(hits);\n            }\n            if (prob_correct)\n            {\n              pep.setScoreType(\"Posterior Probability\");\n              pep.setHigherScoreBetter(true);\n            }\n            else\n            {\n              pep.setScoreType(\"Posterior Error Probability\");\n              pep.setHigherScoreBetter(false);\n            }\n          }\n        }\n      }\n    }\n  } // namespace Math\n} // namespace OpenMS\n", "meta": {"hexsha": "2fa51a1b1f7f7aebf4ae5835e1a969f05bb6e702", "size": 39642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/MATH/STATISTICS/PosteriorErrorProbabilityModel.cpp", "max_stars_repo_name": "andreott/OpenMS", "max_stars_repo_head_hexsha": "718fa2e8a91280ff65e4cf834a3d825811dce1dc", "max_stars_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T09:15:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T09:15:10.000Z", "max_issues_repo_path": "src/openms/source/MATH/STATISTICS/PosteriorErrorProbabilityModel.cpp", "max_issues_repo_name": "andreott/OpenMS", "max_issues_repo_head_hexsha": "718fa2e8a91280ff65e4cf834a3d825811dce1dc", "max_issues_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-06-19T14:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T14:34:32.000Z", "max_forks_repo_path": "src/openms/source/MATH/STATISTICS/PosteriorErrorProbabilityModel.cpp", "max_forks_repo_name": "andreott/OpenMS", "max_forks_repo_head_hexsha": "718fa2e8a91280ff65e4cf834a3d825811dce1dc", "max_forks_repo_licenses": ["BSL-1.0", "Zlib", "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.5281690141, "max_line_length": 534, "alphanum_fraction": 0.6050148832, "num_tokens": 9167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.18760598715718943}}
{"text": "#include <Rcpp.h>\n#include <array>\n#include <boost/container/flat_map.hpp>\n\n// Was using C++17 for std::map::try_emplace\n// Very much required for boost::container::flat_map - 10x speed gain\n// [[Rcpp::plugins(cpp17)]]\n// \n// Using boost::container::flat_map as it is >3x faster than any of std::*\n// [[Rcpp::depends(BH)]]\n// sparse_map - https://www.codeproject.com/Articles/866996/Fast-Implementations-of-Maps-with-Integer-Keys-in\n// can actually be the fastest map for the task, however I didn't try it yet\n// because it requires me to include non-standard header and change the way I\n// emplace new items.\n\n\n// CX report, vectorised, summarising, context-aware, linearly scalable\n// PRE-SORTED DATASET IS A REQUIREMENT.\n// \n// Parses XM tags and outputs summarised CX report only if most frequent context\n// is observed in more than 50% of reads (not including +-) and is within ctx\n// string parameter.\n// Output report is a data.frame with six columns and rows for every cytosine:\n// rname (factor), strand (factor), pos, ctx (char), meth, unmeth\n// \n// 1) all XM positions counted in int[16]: index is equal to char+2>>2&00001111\n// 2) when gap in reads or another chr - spit map to res, clear map\n// 3) spit if within context and same context in more than 50% of the reads\n// \n// Here's the ctx_to_idx convertion:\n// ctx  bin       +2        >>2&15  idx\n// +    00101011  00101101  1011    11\n// -    00101101  00101111  1011    11\n// .    00101110  00110000  1100    12\n// H    01001000  01001010  0010    2\n// U    01010101  01010111  0101    5\n// X    01011000  01011010  0110    6\n// Z    01011010  01011100  0111    7\n// h    01101000  01101010  1010    10\n// u    01110101  01110111  1101    13\n// x    01111000  01111010  1110    14\n// z    01111010  01111100  1111    15\n// \n// [[Rcpp::export(\"rcpp_cx_report\")]]\nRcpp::DataFrame rcpp_cx_report(Rcpp::DataFrame &df,                             // data frame with BAM data\n                               Rcpp::LogicalVector &pass,                       // does it pass the threshold\n                               std::string ctx)                                 // context string for bases to report\n{\n  // walking trough bunch of reads <- filling the map\n  // pos<<2|strand -> {0: rname,  1: pos,       2: 'H',  3: '',    4: '',   5: 'U',  6: 'X',  7: 'Z',\n  //                   8: strand, 9: coverage, 10: 'h', 11: '+-', 12: '.', 13: 'u', 14: 'x', 15: 'z'}\n  // boost::container::flat_map<uint64_t, std::array<int,16>>\n  \n  Rcpp::IntegerVector rname   = df[\"rname\"];                                    // template rname\n  Rcpp::IntegerVector strand  = df[\"strand\"];                                   // template strand\n  Rcpp::IntegerVector start   = df[\"start\"];                                    // template start\n  Rcpp::IntegerVector templid = df[\"templid\"];                                  // template id, effectively holds indexes of corresponding std::string in std::vector\n  \n  // Rcpp::CharacterVector xm    = df[\"XM\"];                                       // merged refspaced template XMs\n  Rcpp::XPtr<std::vector<std::string>> xm((SEXP)df.attr(\"xm_xptr\"));            // merged refspaced template XMs, as a pointer to std::vector<std::string>\n  \n  // main typedefs\n  typedef uint64_t T_key;                                                       // {62bit:pos, 2bit:strand}\n  typedef std::array<int,16> T_val;                                             // {0:rname, 1:pos, 8:strand, 9:coverage, and 10 more for 11 valid chars}\n  typedef boost::container::flat_map<T_key, T_val> T_cx_fmap;                   // attaboy\n  \n  // macros\n  #define ctx_to_idx(c) ((c+2)>>2) & 15\n  #define spit_results {                                                       \\\n    for (it=cx_map.begin(); it!=cx_map.end(); it++) {                          \\\n      it->second[9] /= 2;                              /* half the coverage */ \\\n      if (it->second[12] > it->second[9])             /* skip if most are . */ \\\n        continue;                                                              \\\n      else if ((it->second[2] + it->second[10]) > it->second[9])               \\\n        max_freq_ctx='H', max_freq_idx=2;                                      \\\n      else if ((it->second[6] + it->second[14]) > it->second[9])               \\\n        max_freq_ctx='X', max_freq_idx=6;                                      \\\n      else if ((it->second[7] + it->second[15]) > it->second[9])               \\\n        max_freq_ctx='Z', max_freq_idx=7;                                      \\\n      else continue;                               /* skip if none is > 50% */ \\\n      if (ctx.find(max_freq_ctx)!=std::string::npos) {     /* if within ctx */ \\\n        res_rname.push_back(it->second[0]);                        /* rname */ \\\n        res_strand.push_back(it->second[8]);                      /* strand */ \\\n        res_pos.push_back(it->second[1]);                            /* pos */ \\\n        res_ctx.push_back(max_freq_idx);                         /* context */ \\\n        res_meth.push_back(it->second[max_freq_idx]);               /* meth */ \\\n        res_unmeth.push_back(it->second[max_freq_idx | 8]);       /* unmeth */ \\\n      }                                                                        \\\n    }                                                                          \\\n    cx_map.clear();                                                            \\\n    hint = cx_map.end();                                                       \\\n  }\n\n  // result\n  // { (rname, strand, pos, ctx, meth, unmeth) * n }\n  std::vector<int> res_rname, res_strand, res_pos, res_ctx, res_meth, res_unmeth;\n  size_t nitems = rname.size()*pow(ctx.size()<<2,2);\n  // reserving space makes it only slow?\n  res_rname.reserve(nitems); res_strand.reserve(nitems);\n  res_pos.reserve(nitems); res_ctx.reserve(nitems);\n  res_meth.reserve(nitems); res_unmeth.reserve(nitems);\n  \n  // iterating over XM vector, saving the results when necessary\n  T_cx_fmap cx_map;\n  T_cx_fmap::iterator it, hint;\n  T_key map_key;\n  T_val map_val = {0};\n  unsigned int idx_to_increase, max_freq_ctx, max_freq_idx, pass_x;\n  \n  cx_map.reserve(100000);                                                       // reserving helps?\n  for (unsigned int x=0; x<rname.size(); x++) {\n    // checking for the interrupt\n    if ((x & 0xFFFF) == 0) Rcpp::checkUserInterrupt();                          // every ~65k reads\n    \n    if ((start[x]>map_val[1]) || (rname[x]!=map_val[0])) {\n      spit_results;\n    }\n    map_val[0] = rname[x];\n    map_val[8] = strand[x];\n    pass_x = (!pass[x])<<3;                                                     // should we lowercase this XM (TRUE==0, FALSE==8)\n    for (unsigned int i=0; i<xm->at(templid[x]).size(); i++) {                  // xm->at(templid[x]) is a reference to a corresponding XM string\n      map_val[1] = start[x]+i;\n      map_key = ((T_key)map_val[1] << 2) | map_val[8];\n      idx_to_increase = ctx_to_idx(xm->at(templid[x])[i]);                      // see the table above\n      if (idx_to_increase==11) continue;                                        // skip +-\n      idx_to_increase |= pass_x;                                                // if not pass - lowercase\n      hint = cx_map.try_emplace(hint, map_key, map_val);\n      hint->second[idx_to_increase]++;\n      hint->second[9]++;                                                        // total coverage\n    }\n  }\n  spit_results;\n  \n  Rcpp::DataFrame res = Rcpp::DataFrame::create(                                // final CX report\n    Rcpp::Named(\"rname\") = res_rname,                                           // numeric ids (factor) for reference names\n    Rcpp::Named(\"strand\") = res_strand,                                         // numeric ids (factor) for reference strands\n    Rcpp::Named(\"pos\") = res_pos,                                               // position of cytosine\n    Rcpp::Named(\"context\") = res_ctx,                                           // cytosine context\n    Rcpp::Named(\"meth\") = res_meth,                                             // number of methylated\n    Rcpp::Named(\"unmeth\") = res_unmeth                                          // number of unmethylated\n  );\n  \n  return res;\n}\n\n\n// test code in R\n//\n\n/*** R\n# microbenchmark::microbenchmark(rcpp_cx_report(rname, strand, start, xm, pass, ctx), times=10)\n*/\n\n// Sourcing:\n// Rcpp::sourceCpp(\"rcpp_cx_report.cpp\")\n\n// #############################################################################\n", "meta": {"hexsha": "682c2cb70449c6df9ada2dd56be61669b8e1ded2", "size": 8528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rcpp_cx_report.cpp", "max_stars_repo_name": "BBCG/epialleleR", "max_stars_repo_head_hexsha": "b0f74fe342161b2945421a551487e8d60f4fd61e", "max_stars_repo_licenses": ["ClArtistic"], "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/rcpp_cx_report.cpp", "max_issues_repo_name": "BBCG/epialleleR", "max_issues_repo_head_hexsha": "b0f74fe342161b2945421a551487e8d60f4fd61e", "max_issues_repo_licenses": ["ClArtistic"], "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/rcpp_cx_report.cpp", "max_forks_repo_name": "BBCG/epialleleR", "max_forks_repo_head_hexsha": "b0f74fe342161b2945421a551487e8d60f4fd61e", "max_forks_repo_licenses": ["ClArtistic"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T12:16:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T12:16:39.000Z", "avg_line_length": 53.9746835443, "max_line_length": 165, "alphanum_fraction": 0.4962476548, "num_tokens": 2190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.18760598355526636}}
{"text": "#ifndef SPHERE_HPP\n#define SPHERE_HPP\n\n#include <algorithm>\n#include <cmath>\n#include <string>\n\n#include <Eigen/Core>\n\n#include \"image.hpp\"\n#include \"surface.hpp\"\n#include \"ray.hpp\"\n\nclass Sphere : public Surface {\n  public:\n    Sphere(double radius, Eigen::Vector4d centerPoint, std::string texture = \"\");\n\n    void setRadius(double radius);\n    double getRadius();\n    void setCenterPoint(Eigen::Vector4d centerPoint);\n    Eigen::Vector4d getCenterPoint();\n    Eigen::Vector2d calculateUVMapping(Eigen::Vector4d intersectionPoint);\n\n    std::string getType();\n    double calculateIntersectionTime(Ray ray);\n    Eigen::Vector4d calculateIntersectionNormal(Eigen::Vector4d intersectionPoint);\n    std::shared_ptr<Color> getTextureColor(Eigen::Vector4d intersectionPoint);\n\n  private:\n    Image texture;\n    double radius;\n    Eigen::Vector4d centerPoint;\n};\n\n#endif // SPHERE_HPP\n", "meta": {"hexsha": "cf2df336f96318df366fc29bd02ab3027539bec9", "size": 880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sphere.hpp", "max_stars_repo_name": "matheusportela/black-hole-ray-tracer", "max_stars_repo_head_hexsha": "3a7f1a32d6d44f74278b721e1f49e11b8a9ad86e", "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/sphere.hpp", "max_issues_repo_name": "matheusportela/black-hole-ray-tracer", "max_issues_repo_head_hexsha": "3a7f1a32d6d44f74278b721e1f49e11b8a9ad86e", "max_issues_repo_licenses": ["MIT"], "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/sphere.hpp", "max_forks_repo_name": "matheusportela/black-hole-ray-tracer", "max_forks_repo_head_hexsha": "3a7f1a32d6d44f74278b721e1f49e11b8a9ad86e", "max_forks_repo_licenses": ["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.4444444444, "max_line_length": 83, "alphanum_fraction": 0.7363636364, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1876059799533433}}
{"text": "#ifndef GRID_SENSOR_HPP_I9SAOOSJ\n#define GRID_SENSOR_HPP_I9SAOOSJ\n\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n#include <ros/ros.h>\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <tf_conversions/tf_eigen.h>\n#include <tf/transform_broadcaster.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl/common/transforms.h>\n#include <pcl_conversions/pcl_conversions.h>\n\n\n#include <gridmapping2/proxy_gridmap.hpp>\n\n#include <scrollgrid/scrollgrid3.hpp>\n#include <scrollgrid/raycasting.hpp>\n#include <scrollgrid/occ_raycasting.hpp>\n#include <scrollgrid/scrolling_strategies.hpp>\n#include <scrollgrid/grid_util.hpp>\n\n#include <opencv/cv.h>\n#include <opencv2/core/core.hpp>\n\n#include <Eigen/Dense>\n\n#include <sensor_msgs/Image.h>\n#include <image_transport/image_transport.h>\n#include <cv_bridge/cv_bridge.h>\n#include <sensor_msgs/image_encodings.h>\n#include <nav_msgs/Odometry.h>\n\n\n#include \"densecrf.h\"\n\n\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXf_row;\n\n\nusing namespace Eigen;\nusing namespace std;\n\nnamespace ca {\n\ntypedef Eigen::Matrix<mem_ix_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXf_men;\n\n\nclass GridSensor {\n public:\n\n  typedef pcl::PointCloud<pcl::PointXYZ> PointCloudXYZ;\n  typedef pcl::PointCloud<pcl::PointXYZRGB> CloudXYZRGB;\n\n  //Parameters specific for rgbd grid  static const uint8_t CA_SG_UNKNOWN;\n  uint8_t CA_SG_UNKNOWN;\n  int32_t CA_SG_COMPLETELY_FREE;\n  int32_t CA_SG_COMPLETELY_OCCUPIED;\n  int32_t CA_SG_BARELY_FREE;\n  int32_t CA_SG_BARELY_OCCUPIED;\n  int32_t CA_SG_BELIEF_UPDATE_POS; // when hit\n  int32_t CA_SG_BELIEF_UPDATE_NEG;\n\n public:\n\n  GridSensor(ros::NodeHandle& n):\n\tinitialized_(false),\n\tcounter(0) {\n\n\tCA_SG_UNKNOWN = 128;  //128   255\n\tCA_SG_COMPLETELY_FREE = 0;\n\tCA_SG_COMPLETELY_OCCUPIED = 255;//255  254\n\tCA_SG_BARELY_FREE = 117;\n\tCA_SG_BARELY_OCCUPIED = 135; //129  128  //change grid_visualization.hpp accordingly\n\tCA_SG_BELIEF_UPDATE_POS = 10; // when hit  20\n\tCA_SG_BELIEF_UPDATE_NEG = 4;  // when pass through  2 (raw)\n\t  \n\tn.param<int>(\"Grid_SG_BARELY_FREE\", CA_SG_BARELY_FREE, CA_SG_BARELY_FREE);\n\tn.param<int>(\"Grid_SG_BARELY_OCCUPIED\", CA_SG_BARELY_OCCUPIED, CA_SG_BARELY_OCCUPIED);\n\tn.param<int>(\"Grid_SG_BELIEF_UPDATE_POS\", CA_SG_BELIEF_UPDATE_POS, CA_SG_BELIEF_UPDATE_POS);\n\tn.param<int>(\"Grid_SG_BELIEF_UPDATE_NEG\", CA_SG_BELIEF_UPDATE_NEG, CA_SG_BELIEF_UPDATE_NEG);\n\t\n        n.param<std::string>(\"/grid_sensor/pointCloudFrame\", point_cloud_frame_, \"/camera_rgb_optical_frame\");\n        n.param<std::string>(\"/grid_sensor/worldFrame\", world_frame_, \"/world_frame\");\n        n.param<std::string>(\"/grid_sensor/sharedGridIdentifer\",shared_grid_identifier_,\"shared_grid_map\");\n\traw_cloud_pub = n.advertise<CloudXYZRGB> (\"/rgbd_grid/raw_stereo_cloud\", 50);\n\traw_img_pub=n.advertise<sensor_msgs::Image>(\"/raw_img\",10);\n\traw_label_img_pub=n.advertise<sensor_msgs::Image>(\"/raw_label_img\",10);\n\traw_superpixel_img_pub = n.advertise<sensor_msgs::Image>(\"/superpixel_img\",10);\n\t\n\todom_pub=n.advertise<nav_msgs::Odometry>( \"/odom_pose\", 10 );\n\n\n\tproxy_=new ca::ProxyGridMap(shared_grid_identifier_);\n        ROS_INFO_STREAM(\"Grid sensor :\"<<point_cloud_frame_<<\" , \"<<world_frame_);\n\t\n\tn.param (\"crf_iterations\", crf_iterations, crf_iterations);\n\tn.param (\"use_high_order\", use_high_order, use_high_order);\n\tn.param (\"use_high_order\", use_hierarchical_inference, use_hierarchical_inference);\n\t\n\tn.param (\"smooth_xy_stddev\", smooth_xy_stddev, smooth_xy_stddev);\n\tn.param (\"smooth_z_stddev\", smooth_z_stddev, smooth_z_stddev);\n\tn.param (\"smooth_weight\", smooth_weight, smooth_weight);\n\tn.param (\"appear_xy_stddev\", appear_xy_stddev, appear_xy_stddev);\n\tn.param (\"appear_z_stddev\", appear_z_stddev, appear_z_stddev);\n\tn.param (\"appear_rgb_stddev\", appear_rgb_stddev, appear_rgb_stddev);\n\tn.param (\"appear_weight\", appear_weight, appear_weight);\n\t\n\tn.param (\"depth_scaling\", depth_scaling, depth_scaling);\n\tn.param (\"depth_ignore_thres\", depth_ignore_thres, depth_ignore_thres);\n      }\n\n\n  virtual ~GridSensor() {\n   delete proxy_;\n  }\n\n public:\n\n  void preprocess_pose(ros::Time timnow,const cv::Mat& rgb_img, const cv::Mat& label_img,const cv::Mat& superpixel_img, \n\t\t       const Eigen::Matrix4f& transToWorld);   \n  void AddDepthImg(const cv::Mat& rgb_img,const cv::Mat& label_rgb_img,const cv::Mat& depth_img, const cv::Mat& superpixel_img, \n\t\t\t  const Eigen::Matrix4f pose,MatrixXf_row& frame_label_prob); // pose is 12*1    possibly add label data here\n  void reproject_to_images(int current_index);\n  \n  MatrixXf_men pixels_to_gridmem;  // store each pixel's correspondence to 3D occupancy grid memory index\n  int crf_iterations=0;\n  bool use_high_order=false;\n  bool use_hierarchical_inference=false;\n  void CRF_optimization(const string superpixel_bin_file);\n  \n  void ScrollGrid();\n  void ClearGrid(const ca::Vec3Ix& start, const ca::Vec3Ix& finish);\n  void Init();\n\n\n  void UpdateProbability(int x,int y,int z, bool endpt){\n    bool isadd=false,isremove=false;\n    if(!grid3_->is_inside_grid(x,y,z))ROS_INFO_STREAM(\"updateprob:isinsideGrid\"<<x<<\" , \"<<y<<\" , \"<<z);\n    mem_ix_t mem_ix = grid3_->grid_to_mem(x, y, z);\n    int32_t old_value = occ_array3_[mem_ix];\n    if(!endpt){\n      int32_t new_value = static_cast<int32_t>(occ_array3_[mem_ix])-CA_SG_BELIEF_UPDATE_NEG;\n      new_value=std::max(CA_SG_COMPLETELY_FREE, new_value);\n      occ_array3_[mem_ix] = static_cast<uint8_t>(new_value);\n      isremove = (old_value>=CA_SG_BARELY_FREE && new_value<=CA_SG_BARELY_FREE); //REMOVE point from list\n    }\n    else{\n      int32_t new_value = static_cast<int32_t>(occ_array3_[mem_ix])+CA_SG_BELIEF_UPDATE_POS;\n      new_value=std::min(CA_SG_COMPLETELY_OCCUPIED, new_value);\n      occ_array3_[mem_ix] = static_cast<uint8_t>(new_value);\n      isadd = (old_value<CA_SG_BARELY_FREE && new_value>=CA_SG_BARELY_OCCUPIED);  //ADD point from list\n    }\n  } \n\n  Eigen::MatrixXi label_to_color_mat;\n  int sky_label=1;\n  \n  // calibration related\n  Eigen::Matrix3f calibration_mat;\n  int im_height, im_width;\n  void set_up_calibration(const Eigen::Matrix3f& calibration_mat_in,const int im_height_in,const int im_width_in);\n\n  // for reprojection evaluation\n  void set_up_reprojections(const int reprojection_frames);\n  std::vector<cv::Mat> reproject_depth_imgs; // depth buffer for images\n  std::vector<cv::Mat> actual_depth_imgs;\n  std::vector<cv::Mat> reproj_label_colors;\n  std::vector<cv::Mat> reproj_label_maps;\n  std::vector<Eigen::Matrix4f> all_WorldToBodys; // all the frame poses need to project\n  std::vector<Eigen::Matrix4f> all_BodyToWorlds; // all the frame poses need to project\n  Eigen::VectorXi reproj_frame_inds;\n  \n private:\n\n  std::string point_cloud_frame_;\n  std::string world_frame_;\n  std::string shared_grid_identifier_;\n\n  ca::ProxyGridMap* proxy_;  //occupancy grids\n  ca::ScrollGrid3f* grid3_;\n  ca::DenseArray3<uint8_t> occ_array3_;  // true data fields of occupancy value\n  ca::DenseArray3<Vector3f> rgb_array3_;  // true data fields of rgb value\n  ca::DenseArray3<Vector_Xxf> label_array3_;  // true data fields of label probability\n  ca::DenseArray3<int> count_array3_;\n  \n  int counter;\n  ca::ScrollGrid3f::Vec3 sensor_pos_;\n\n  ros::Publisher raw_cloud_pub,raw_img_pub, raw_label_img_pub, raw_superpixel_img_pub,odom_pub;\n  \n  \n  //Scrolling\n  ca::ScrollForBaseFrame<float> scroll_strategy_;\n  ca::Vec3Ix scroll_cells_;\n  ca::Vec3Ix clear_i_min, clear_i_max, clear_j_min, clear_j_max, clear_k_min, clear_k_max;\n\n  //Raycasting\n  ca::ScrollGrid3f::Vec3 ray_end_pos_;\n  ca::Vec3Ix sensor_pos_ijk_;\n  ca::Vec3Ix ray_end_pos_ijk_;\n\n  //Input point cloud is provided in local frame and therefore converted to point_cloud_global\n  //If point cloud is global, assign it directly to point_cloud_global //TODO\n  tf::TransformListener tf_listener_;\n  PointCloudXYZ point_cloud_global_;\n  tf::StampedTransform w_to_sensor_transform_;\n\n  bool initialized_; \n    \n  // depth to cloud   \n  cv::Mat_<float> matx_to3d_, maty_to3d_;\n  float depth_scaling=1000;\n  float depth_ignore_thres=20.0;\n\n  \n  // CRF related\n  float smooth_xy_stddev=3;\n  float smooth_z_stddev=3;\n  float smooth_weight=8;\n\n  float appear_xy_stddev=160;\n  float appear_z_stddev=40;\n  float appear_rgb_stddev=4;\n  float appear_weight=10;\n\t \n};\n\n}\n#endif\n", "meta": {"hexsha": "4aba9cc5dfad56bf1a2b025a050552535524db78", "size": 8255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_sensor/include/grid_sensor/grid_sensor.hpp", "max_stars_repo_name": "ganlumomo/semantic_3d_mapping", "max_stars_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2018-03-15T13:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:37:55.000Z", "max_issues_repo_path": "grid_sensor/include/grid_sensor/grid_sensor.hpp", "max_issues_repo_name": "ganlumomo/semantic_3d_mapping", "max_issues_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-04-28T09:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T23:46:00.000Z", "max_forks_repo_path": "grid_sensor/include/grid_sensor/grid_sensor.hpp", "max_forks_repo_name": "ganlumomo/semantic_3d_mapping", "max_forks_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2018-03-21T06:54:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T07:27:42.000Z", "avg_line_length": 35.4291845494, "max_line_length": 128, "alphanum_fraction": 0.7622047244, "num_tokens": 2348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18760597995334327}}
{"text": "#include <iostream>\n#include <signal.h>\n#include <cstdlib>\n#include <boost/program_options.hpp>\n#include <thread>\n#include <atomic>\n#include <experimental/filesystem>\n#include <chrono>\n\n#include <sdm/types.hpp>\n#include <sdm/config.hpp>\n#include <sdm/common.hpp>\n#include <sdm/parser/parser.hpp>\n#include <sdm/public/algorithm.hpp>\n#include <sdm/algorithms.hpp>\n#include <sdm/worlds.hpp>\n#include <sdm/core/state/private_occupancy_state.hpp>\n#include <sdm/utils/value_function/qfunction/pwlc_qvalue_function.hpp>\n\nusing namespace sdm;\nusing namespace std;\nnamespace po = boost::program_options;\n\ndouble MAX_RUNNING_TIME = 1800;\nbool quit_flag = false;\nstd::string name = \"result\";\nstd::shared_ptr<Algorithm> algorithm;\n\nvoid leave()\n{\n    algorithm->logging();\n    std::cout << \"\\n\"\n              << config::LOG_SDMS << \"Exit process\" << std::endl;\n    algorithm = nullptr;\n    exit(0);\n}\n\nvoid handler(int)\n{\n    leave();\n}\n\nint solve(int argv, char **args)\n{\n    // Handle interrupt signal\n    signal(SIGINT, &handler);\n\n    try\n    {\n        std::string world, algo_name, formalism, upper_bound, lower_bound, ub_init, lb_init, type_sampling;\n        int trials, memory;\n        number horizon, seed, batch_size, freq_update_lb, freq_update_ub, state_type;\n        double error, discount, granularity_start, granularity_end, rate_start, rate_end, rate_decay, eps_start, eps_end, eps_decay;\n        double p_b, p_o, p_c;\n        bool store_actions, store_states;\n        unsigned long long num_samples;\n\n        int freq_pruning_v1 = 1, freq_pruning_v2 = 1;\n        std::string type_of_resolution_v1, type_of_resolution_v2, type_of_pruning_v1, type_of_pruning_v2;\n\n        po::options_description options(\"Options\");\n        options.add_options()\n        (\"help\", \"produce help message\")\n        (\"test\", \"test the policy found\")\n        (\"save\", \"save the policy found\");\n\n        po::options_description config(\"Configuration\");\n        config.add_options()\n        (\"algorithm,a\", po::value<string>(&algo_name)->default_value(\"hsvi\"), \"the algorithm to use\")\n        (\"world,w\", po::value<string>(&world)->default_value(\"mabc.dpomdp\"), \"the world to be solved\")\n        (\"formalism,f\", po::value<string>(&formalism)->default_value(\"OccupancyMDP\"), \"the formalism to use\")\n        (\"horizon,h\", po::value<number>(&horizon)->default_value(5), \"the planning horizon\")\n        (\"discount,d\", po::value<double>(&discount)->default_value(1.0), \"the discount factor\")\n        (\"memory,m\", po::value<int>(&memory)->default_value(-1), \"the memory for history\")\n        (\"error,e\", po::value<double>(&error)->default_value(0.001), \"the error\")\n        (\"trials,t\", po::value<int>(&trials)->default_value(100000), \"the maximum number of trials\")\n        (\"seed,s\", po::value<number>(&seed)->default_value(1), \"the seed\")\n        (\"batch_size,b\", po::value<number>(&batch_size)->default_value(0), \"the batch size used in rl\")\n        (\"name,n\", po::value<std::string>(&name)->default_value(\"\"), \"the name of the experiment\")\n        (\"compression\", po::value<number>(&state_type)->default_value(0), \"The type of occupancy state (COMPRESSED, ONE_STEP, UNCOMPRESSED)\")\n        (\"store_states\", po::value<bool>(&store_states)->default_value(true), \"If true, store the macro states.\")\n        (\"store_actions\", po::value<bool>(&store_actions)->default_value(true), \"If true, store the macro actions.\")\n        (\"p_c\", po::value<double>(&p_c)->default_value(config::PRECISION_COMPRESSION), \"The precision of the compression.\")\n        (\"p_b\", po::value<double>(&p_b)->default_value(config::PRECISION_BELIEF), \"The precision of beliefs.\")\n        (\"p_o\", po::value<double>(&p_o)->default_value(config::PRECISION_OCCUPANCY_STATE), \"The precision of occupancy states.\")\n        (\"time_max\", po::value<double>(&MAX_RUNNING_TIME)->default_value(1800), \"The maximum running time.\");\n\n        po::options_description hsvi_config(\"HSVI configuration\");\n        hsvi_config.add_options()\n        (\"lower_bound\", po::value<string>(&lower_bound)->default_value(\"tabular\"), \"the lower bound representation\")\n        (\"upper_bound\", po::value<string>(&upper_bound)->default_value(\"tabular\"), \"the upper bound representation\")\n        (\"lb_init\", po::value<string>(&lb_init)->default_value(\"Min\"), \"the lower bound initialization method\")\n        (\"ub_init\", po::value<string>(&ub_init)->default_value(\"Max\"), \"the upper bound initialization method\")\n        (\"freq_update_lb\", po::value<number>(&freq_update_lb)->default_value(1), \"the update frequency of the lower bound.\")\n        (\"freq_update_ub\", po::value<number>(&freq_update_ub)->default_value(1), \"the update frequency of the upper bound.\")\n        (\"lb_type_of_resolution\", po::value<string>(&type_of_resolution_v1)->default_value(\"IloIfThen\"), \"the type of resolution for the lower bound (ex: 'BigM:100' or 'IloIfThen' for LP)\")\n        (\"ub_type_of_resolution\", po::value<string>(&type_of_resolution_v2)->default_value(\"IloIfThen\"), \"the type of resolution for the upper bound (ex: 'BigM:100' or 'IloIfThen' for LP)\")\n        (\"lb_freq_pruning\", po::value<int>(&freq_pruning_v1)->default_value(1), \"the pruning frequency for the first value function.\")\n        (\"ub_freq_pruning\", po::value<int>(&freq_pruning_v2)->default_value(1), \"the pruning frequency for the second value function .\")\n        (\"lb_type_of_pruning\", po::value<string>(&type_of_pruning_v1)->default_value(\"none\"), \"the pruning type for the lower bound (ex: 'bounded', 'pairwise', 'none'\")\n        (\"ub_type_of_pruning\", po::value<string>(&type_of_pruning_v2)->default_value(\"none\"), \"the pruning type for the upper bound (ex: 'iterative', 'global', 'none'\");\n\n        po::options_description pbvi_config(\"PBVI configuration\");\n        pbvi_config.add_options()\n        (\"num_samples\", po::value<unsigned long long>(&num_samples)->default_value(10), \"the number of sample to generate in the algorithm\")\n        (\"type_sampling\", po::value<string>(&type_sampling)->default_value(\"\"), \"the type of sampling process\")\n        (\"value_function\", po::value<string>(&lower_bound), \"the lower bound representation\")\n        (\"vf_init\", po::value<string>(&lb_init), \"the lower bound initialization method\")\n        (\"freq_update\", po::value<number>(&freq_update_lb), \"the update frequency of the lower bound.\")\n        (\"type_of_resolution\", po::value<string>(&type_of_resolution_v1), \"the type of resolution for the lower bound (ex: 'BigM:100' or 'IloIfThen' for LP)\")\n        (\"freq_pruning\", po::value<int>(&freq_pruning_v1), \"the pruning frequency for the first value function.\")\n        (\"type_of_pruning\", po::value<string>(&type_of_pruning_v1), \"the pruning type for the lower bound (ex: 'bounded', 'pairwise', 'none'\");\n\n        po::options_description qlearning_config(\"Q-learning configuration\");\n        qlearning_config.add_options()\n        (\"qvalue_function\", po::value<string>(&lower_bound), \"the q-value function representation\")\n        (\"eps_start\", po::value<double>(&eps_start)->default_value(1.0), \"the starting epsilon\")\n        (\"eps_end\", po::value<double>(&eps_end)->default_value(0.001), \"the final epsilon\")\n        (\"eps_decay\", po::value<double>(&eps_decay)->default_value(-1), \"the decaying epsilon factor (default to linear)\")\n        (\"rate_start\", po::value<double>(&rate_start)->default_value(1.0), \"the starting learning rate\")\n        (\"rate_end\", po::value<double>(&rate_end)->default_value(0.001), \"the final learning rate\")\n        (\"rate_decay\", po::value<double>(&rate_decay)->default_value(10000), \"the decaying factor\")\n        (\"rate_decay_start_time\", po::value<double>(&QLearning::RATE_DECAY_START_TIME)->default_value(43200), \"the decaying factor\")\n        (\"rate_decay_duration\", po::value<double>(&QLearning::DURATION_RATE_DECAY)->default_value(43200), \"the decaying factor\")\n        (\"q_init\", po::value<string>(&lb_init), \"the q-value function initialization method\")\n        (\"g_start\", po::value<double>(&granularity_start)->default_value(oPWLCQ::GRANULARITY_START), \"The granularity...\")\n        (\"g_end\", po::value<double>(&granularity_end)->default_value(oPWLCQ::GRANULARITY_END), \"The granularity...\")\n        ;\n\n        po::options_description byg_config(\"Bayesian game solver configuration\");\n        byg_config.add_options()\n        (\"player_id\", po::value<number>(&batch_size), \"the identifier of player\");\n\n        po::options_description visible(\"\\nUsage:\\tsdms-solve [CONFIGS]\\n\\tSDMStudio solve [CONFIGS]\\n\\nSolve a problem with specified algorithms and configurations.\");\n        visible.add(options).add(config).add(hsvi_config).add(pbvi_config).add(qlearning_config).add(byg_config);\n\n        po::options_description config_file_options;\n        config_file_options.add(config);\n\n        po::variables_map vm;\n        try\n        {\n            po::store(po::command_line_parser(argv, args).options(visible).run(), vm);\n            po::notify(vm);\n            if (vm.count(\"help\"))\n            {\n                std::cout << visible << std::endl;\n                return sdm::SUCCESS;\n            }\n            if (discount >= 1 && !horizon)\n            {\n                std::cerr << config::LOG_SDMS << \"Invalid hyperparameters (discount must be less than 1. for infinite horizon)\" << std::endl;\n                return sdm::ERROR_IN_COMMAND_LINE;\n            }\n        }\n        catch (po::error &e)\n        {\n            std::cerr << \"ERROR: \" << e.what() << std::endl;\n            std::cerr << visible << std::endl;\n            return sdm::ERROR_IN_COMMAND_LINE;\n        }\n\n        // Set the seed\n        common::global_urng().seed(seed);\n\n        // Set precisions\n        Belief::PRECISION = p_b;\n        OccupancyState::PRECISION = p_o;\n        PrivateOccupancyState::PRECISION_COMPRESSION = p_c;\n        oPWLCQ::GRANULARITY_START = granularity_start;\n        oPWLCQ::GRANULARITY_END = granularity_end;\n\n        common::logo();\n        \n        // Build algorithm\n        algorithm = sdm::algo::make(algo_name,\n                                    world,\n                                    formalism,\n                                    horizon,\n                                    discount,\n                                    error,\n                                    trials,\n                                    MAX_RUNNING_TIME,\n                                    name,\n                                    memory,\n                                    (StateType)state_type,\n                                    store_states,\n                                    store_actions,\n                                    batch_size,\n                                    num_samples,\n                                    type_sampling,\n                                    rate_start,\n                                    rate_end,\n                                    rate_decay,\n                                    eps_start,\n                                    eps_end,\n                                    eps_decay,\n                                    lower_bound,\n                                    lb_init,\n                                    freq_update_lb,\n                                    type_of_resolution_v1,\n                                    freq_pruning_v1,\n                                    type_of_pruning_v1,\n                                    upper_bound,\n                                    ub_init,\n                                    freq_update_ub,\n                                    type_of_resolution_v2,\n                                    freq_pruning_v2,\n                                    type_of_pruning_v2);\n\n        // Initialize algorithm\n        algorithm->initialize();\n\n        // Solve the problem\n        algorithm->solve();\n\n        if (vm.count(\"test\"))\n        {\n            algorithm->test();\n        }\n        if (vm.count(\"save\"))\n        {\n            algorithm->save();\n        }\n    }\n    catch (std::exception &e)\n    {\n        std::cerr << \"Unhandled Exception reached the top of main: \" << e.what() << std::endl;\n        return sdm::ERROR_UNHANDLED_EXCEPTION;\n    }\n\n    return sdm::SUCCESS;\n}\n\n#ifndef __main_program__\n#define __main_program__\nint main(int argv, char **args)\n{\n\n    // return solve(argv, args);\n    return solve(argv, args);\n}\n#endif", "meta": {"hexsha": "f15937c384e31c4bdbcc9debb7b6d7691d6ae906", "size": 12270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/programs/solve.cpp", "max_stars_repo_name": "SDMStudio/sdms", "max_stars_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "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/programs/solve.cpp", "max_issues_repo_name": "SDMStudio/sdms", "max_issues_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "max_issues_repo_licenses": ["MIT"], "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/programs/solve.cpp", "max_forks_repo_name": "SDMStudio/sdms", "max_forks_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4938271605, "max_line_length": 189, "alphanum_fraction": 0.6013039935, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18760597995334327}}
{"text": "// Copyright Oleg Maximenko 2014.\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://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <svgpp/definitions.hpp>\n#include <svgpp/parser/detail/common.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/spirit/include/qi_grammar.hpp>\n\nnamespace svgpp \n{\n\nnamespace qi = boost::spirit::qi;\n\nnamespace detail\n{\n  struct length_units_symbols\n  {\n    enum type {em, ex, px, in, cm, mm, pt, pc};\n\n    length_units_symbols()\n    {\n      symbols_.add(\"em\", em);\n      symbols_.add(\"ex\", ex);\n      symbols_.add(\"px\", px);\n      symbols_.add(\"in\", in);\n      symbols_.add(\"cm\", cm);\n      symbols_.add(\"mm\", mm);\n      symbols_.add(\"pt\", pt);\n      symbols_.add(\"pc\", pc);\n    }\n\n    qi::symbols<char, type> const & symbols() const { return symbols_; }\n\n    template<class LengthFactory, class Value>\n    static typename LengthFactory::length_type create_length(LengthFactory const & length_factory, Value value, type units)\n    {\n      switch (units)\n      {\n      default:\n        BOOST_ASSERT(false);\n      case em:\n        return length_factory.create_length(value, tag::length_units::em());\n      case ex:\n        return length_factory.create_length(value, tag::length_units::ex());\n      case px:\n        return length_factory.create_length(value, tag::length_units::px());\n      case in:\n        return length_factory.create_length(value, tag::length_units::in());\n      case cm:\n        return length_factory.create_length(value, tag::length_units::cm());\n      case mm:\n        return length_factory.create_length(value, tag::length_units::mm());\n      case pt:\n        return length_factory.create_length(value, tag::length_units::pt());\n      case pc:\n        return length_factory.create_length(value, tag::length_units::pc());\n      }\n    }\n\n  private:\n    qi::symbols<char, type> symbols_;\n  };\n\n  template<class LengthFactory, class Value>\n  inline typename LengthFactory::length_type call_make_length_without_units(LengthFactory const & length_factory, Value value)\n  {\n    return length_factory.create_length(value, tag::length_units::none());\n  }\n}\n\ntemplate <\n  class PropertySource, \n  class Iterator, \n  class LengthFactory, \n  class PercentageDirectionTag = tag::length_dimension::not_width_nor_height,\n  class Number = typename LengthFactory::number_type\n>\nclass length_grammar;\n\ntemplate <typename Iterator, class LengthFactory, class PercentageDirectionTag, class Number>\nclass length_grammar<tag::source::attribute, Iterator, LengthFactory, PercentageDirectionTag, Number>:\n  public qi::grammar<Iterator, typename LengthFactory::length_type(LengthFactory const &), qi::locals<Number> >\n{\n  typedef length_grammar<tag::source::attribute, Iterator, LengthFactory, PercentageDirectionTag, Number> this_type;\npublic:\n  typedef typename LengthFactory::length_type length_type; \n\n  length_grammar()\n    : this_type::grammar(rule_)\n  {\n    namespace phx = boost::phoenix;\n    using qi::_1;\n    using qi::_a;\n    using qi::_val;\n    using qi::_r1;\n    rule_ \n        =   number_ [_a = _1] \n            >>  ( units_symbols_.symbols()\n                      [_val = phx::bind(&detail::length_units_symbols::create_length<LengthFactory, Number>, _r1, _a, _1)]\n                | qi::lit(\"%\")\n                      [_val = phx::bind(&length_grammar::call_make_length_percent, _r1, _a)]\n                | qi::eps\n                      [_val = phx::bind(&detail::call_make_length_without_units<LengthFactory, Number>, _r1, _a)]\n                );\n  }\n\nprivate:\n  typename this_type::start_type rule_; \n  qi::real_parser<Number, detail::number_policies<Number, tag::source::attribute> > number_;\n  detail::length_units_symbols units_symbols_;\n\n  static length_type call_make_length_percent(LengthFactory const & length_factory, Number value)\n  {\n    return length_factory.create_length(value, tag::length_units::percent(), PercentageDirectionTag());\n  }\n};\n\ntemplate<\n  class Iterator, \n  class LengthFactory, \n  class PercentageDirectionTag, \n  class Number\n>\nclass length_grammar<tag::source::css, Iterator, LengthFactory, PercentageDirectionTag, Number>:\n  public qi::grammar<Iterator, typename LengthFactory::length_type(LengthFactory const &), qi::locals<Number> >\n{\n  typedef length_grammar<tag::source::css, Iterator, LengthFactory, PercentageDirectionTag, Number> this_type;\npublic:\n  typedef typename LengthFactory::length_type length_type; \n\n  length_grammar()\n    : this_type::grammar(rule_)\n  {\n    namespace phx = boost::phoenix;\n    using qi::_1;\n    using qi::_a;\n    using qi::_val;\n    using qi::_r1;\n    rule_ \n        =   number_ [_a = _1] \n            >>  ( qi::no_case\n                  [\n                    units_symbols_.symbols()\n                        [_val = phx::bind(&detail::length_units_symbols::create_length<LengthFactory, Number>, _r1, _a, _1)]\n                  ]\n                | qi::eps\n                      [_val = phx::bind(&detail::call_make_length_without_units<LengthFactory, Number>, _r1, _a)]\n                );\n  }\n\nprivate:\n  typename this_type::start_type rule_; \n  qi::real_parser<Number, detail::number_policies<Number, tag::source::css> > number_;\n  detail::length_units_symbols units_symbols_;\n};\n\ntemplate <\n  class Iterator, \n  class LengthFactory, \n  class Number = typename LengthFactory::number_type\n>\nclass percentage_or_length_css_grammar:\n  public qi::grammar<Iterator, typename LengthFactory::length_type(LengthFactory const &), qi::locals<Number> >\n{\n  typedef percentage_or_length_css_grammar<Iterator, LengthFactory, Number> this_type;\npublic:\n  typedef typename LengthFactory::length_type length_type; \n\n  percentage_or_length_css_grammar()\n    : this_type::grammar(rule_)\n  {\n    namespace phx = boost::phoenix;\n    using qi::_1;\n    using qi::_a;\n    using qi::_val;\n    using qi::_r1;\n    rule_ \n        =   number_ [_a = _1] \n            >>  ( qi::no_case\n                  [\n                    units_symbols_.symbols()\n                        [_val = phx::bind(&detail::length_units_symbols::create_length<LengthFactory, Number>, _r1, _a, _1)]\n                  ]\n                | qi::lit(\"%\")\n                      [_val = phx::bind(&this_type::call_make_length_percent, _r1, _a)]\n                | qi::eps\n                      [_val = phx::bind(&detail::call_make_length_without_units<LengthFactory, Number>, _r1, _a)]\n                );\n  }\n\nprivate:\n  typename this_type::start_type rule_; \n  qi::real_parser<Number, detail::number_policies<Number, tag::source::css> > number_;\n  detail::length_units_symbols units_symbols_;\n\n  static length_type call_make_length_percent(LengthFactory const & length_factory, Number value)\n  {\n    return length_factory.create_length(value, tag::length_units::percent(), tag::length_dimension::not_width_nor_height());\n  }\n};\n\n}", "meta": {"hexsha": "ef1a3c7f9c5a991a6d2207136ae072204235d3ec", "size": 6981, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/svgpp/parser/grammar/length.hpp", "max_stars_repo_name": "RichardCory/svgpp", "max_stars_repo_head_hexsha": "801e0142c61c88cf2898da157fb96dc04af1b8b0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 428.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:25:47.000Z", "max_issues_repo_path": "include/svgpp/parser/grammar/length.hpp", "max_issues_repo_name": "andrew2015/svgpp", "max_issues_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T14:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T16:55:11.000Z", "max_forks_repo_path": "include/svgpp/parser/grammar/length.hpp", "max_forks_repo_name": "andrew2015/svgpp", "max_forks_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2015-05-19T04:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:42:50.000Z", "avg_line_length": 33.4019138756, "max_line_length": 126, "alphanum_fraction": 0.6680991262, "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18760597274949722}}
{"text": "// (C) Copyright Stephan Dollberg 2013. 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#ifndef MEMCACHED_CONSISTENT_HASHER_HPP\n#define MEMCACHED_CONSISTENT_HASHER_HPP\n\n#include <boost/range/irange.hpp>\n#include <map>\n\nnamespace memcachedcpp { namespace detail {\n\n    template<typename hash>\n    class consistent_hasher {\n    public:\n        template<typename server_iter>\n        consistent_hasher(server_iter begin, server_iter end) {\n            auto current_server_id = 0;\n            for(auto&& server_name : boost::iterator_range<server_iter>(begin, end)) {\n                for(int i : boost::irange(0, 256)) {\n                    consistent_hash[hasher(server_name + std::to_string(i))] = current_server_id; \n                }\n                current_server_id++;\n            }\n        }\n\n        std::size_t get_node_id(const std::string& key) const {\n            auto current_hash = hasher(key);\n            auto begin_iter = consistent_hash.upper_bound(current_hash);\n            return begin_iter != consistent_hash.end() ? begin_iter->second : consistent_hash.begin()->second;\n        }\n\n    private:\n        hash hasher;\n        std::map<std::size_t, std::size_t> consistent_hash;\n    };\n}}\n\n#endif // MEMCACHED_CLIENT_HPP\n", "meta": {"hexsha": "d0a56ea684418bdb813051a4aa420b03d6265203", "size": 1341, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/memcached-cpp/detail/consistent_hasher.hpp", "max_stars_repo_name": "respu/memcached-cpp", "max_stars_repo_head_hexsha": "a729c377f7c2a6306b5411709f445ae1863eac26", "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/memcached-cpp/detail/consistent_hasher.hpp", "max_issues_repo_name": "respu/memcached-cpp", "max_issues_repo_head_hexsha": "a729c377f7c2a6306b5411709f445ae1863eac26", "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/memcached-cpp/detail/consistent_hasher.hpp", "max_forks_repo_name": "respu/memcached-cpp", "max_forks_repo_head_hexsha": "a729c377f7c2a6306b5411709f445ae1863eac26", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-06-07T07:10:53.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-30T09:30:46.000Z", "avg_line_length": 34.3846153846, "max_line_length": 110, "alphanum_fraction": 0.6487695749, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18760597274949722}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/xray/scatterer_utils.h>\n#include <cctbx/crystal/direct_space_asu.h>\n#include <cctbx/eltbx/henke.h>\n#include <cctbx/eltbx/sasaki.h>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/return_by_value.hpp>\n\nnamespace cctbx { namespace xray { namespace boost_python {\n\nnamespace {\n\n  struct scatterer_wrappers\n  {\n    typedef scatterer<> w_t;\n    typedef w_t::float_type flt_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      typedef return_value_policy<return_by_value> rbv;\n      typedef default_call_policies dcp;\n      class_<w_t>(\"scatterer\", no_init)\n        .def(init<w_t const&>(arg(\"other\")))\n        .def(init<std::string const&,\n                  fractional<flt_t> const&,\n                  flt_t const&,\n                  flt_t const&,\n                  std::string const&,\n                  flt_t const&,\n                  flt_t const&>((\n          arg(\"label\"),\n          arg(\"site\"),\n          arg(\"u_iso\"),\n          arg(\"occupancy\"),\n          arg(\"scattering_type\"),\n          arg(\"fp\"),\n          arg(\"fdp\"))))\n        .def(init<std::string const&,\n                  fractional<flt_t> const&,\n                  scitbx::sym_mat3<flt_t> const&,\n                  flt_t const&,\n                  std::string const&,\n                  flt_t const&,\n                  flt_t const&>((\n          arg(\"label\"),\n          arg(\"site\"),\n          arg(\"u_star\"),\n          arg(\"occupancy\"),\n          arg(\"scattering_type\"),\n          arg(\"fp\"),\n          arg(\"fdp\"))))\n        .add_property(\"label\", make_getter(&w_t::label, rbv()),\n                               make_setter(&w_t::label, dcp()))\n        .add_property(\"scattering_type\",\n          make_getter(&w_t::scattering_type, rbv()),\n          make_setter(&w_t::scattering_type, dcp()))\n        .add_property(\"fp\", make_getter(&w_t::fp, rbv()),\n                            make_setter(&w_t::fp, dcp()))\n        .add_property(\"fdp\", make_getter(&w_t::fdp, rbv()),\n                             make_setter(&w_t::fdp, dcp()))\n        .add_property(\"site\", make_getter(&w_t::site, rbv()),\n                              make_setter(&w_t::site, dcp()))\n        .add_property(\"occupancy\", make_getter(&w_t::occupancy, rbv()),\n                                   make_setter(&w_t::occupancy, dcp()))\n        .add_property(\"u_iso\", make_getter(&w_t::u_iso, rbv()),\n                               make_setter(&w_t::u_iso, dcp()))\n        .add_property(\"u_star\", make_getter(&w_t::u_star, rbv()),\n                                make_setter(&w_t::u_star, dcp()))\n        .def_readwrite(\"flags\", &w_t::flags)\n        .def(\"set_use_u\", &w_t::set_use_u, (arg(\"iso\"),arg(\"aniso\")))\n        .def(\"set_use_u_iso_only\", &w_t::set_use_u_iso_only)\n        .def(\"set_use_u_aniso_only\", &w_t::set_use_u_aniso_only)\n        .def(\"convert_to_isotropic\", &w_t::convert_to_isotropic, (\n          arg(\"unit_cell\")))\n        .def(\"convert_to_anisotropic\", &w_t::convert_to_anisotropic, (\n          arg(\"unit_cell\")))\n        .def(\"is_positive_definite_u\",\n          (bool(w_t::*)(uctbx::unit_cell const&) const)\n            &w_t::is_positive_definite_u, (\n          arg(\"unit_cell\")))\n        .def(\"is_positive_definite_u\",\n          (bool(w_t::*)(uctbx::unit_cell const&, double const&) const)\n            &w_t::is_positive_definite_u, (\n          arg(\"unit_cell\"),\n          arg(\"u_cart_tolerance\")))\n        .def(\"u_iso_or_equiv\", &w_t::u_iso_or_equiv, (arg(\"unit_cell\")))\n        .def(\"b_iso\", &w_t::b_iso)\n        .def(\"u_cart_plus_u_iso\", &w_t::u_cart_plus_u_iso, (arg(\"unit_cell\")))\n        .def(\"tidy_u\",\n          (void(w_t::*)(\n            uctbx::unit_cell const&,\n            sgtbx::site_symmetry_ops const&,\n            double const&,\n            double const&,\n            double const&)) &w_t::tidy_u, (\n          arg(\"unit_cell\"),\n          arg(\"site_symmetry_ops\"),\n          arg(\"u_min\"),\n          arg(\"u_max\"),\n          arg(\"anisotropy_min\")))\n        .def(\"shift_u\",\n          (void(w_t::*)(\n            uctbx::unit_cell const&,\n            double const&)) &w_t::shift_u, (\n          arg(\"unit_cell\"),\n          arg(\"u_shift\")))\n        .def(\"shift_occupancy\",\n          (void(w_t::*)(\n            double const&)) &w_t::shift_occupancy, (\n          arg(\"q_shift\")))\n        .def(\"apply_symmetry\",\n          (sgtbx::site_symmetry(w_t::*)(\n            uctbx::unit_cell const&,\n            sgtbx::space_group const&,\n            double const&,\n            double const&,\n            bool)) &w_t::apply_symmetry, (\n              arg(\"unit_cell\"),\n              arg(\"space_group\"),\n              arg(\"min_distance_sym_equiv\")=0.5,\n              arg(\"u_star_tolerance\")=0,\n              arg(\"assert_min_distance_sym_equiv\")=true))\n        .def(\"apply_symmetry\",\n          (void(w_t::*)(\n            sgtbx::site_symmetry_ops const&,\n            double const&)) &w_t::apply_symmetry, (\n              arg(\"site_symmetry_ops\"),\n              arg(\"u_star_tolerance\")=0))\n        .def(\"apply_symmetry_site\", &w_t::apply_symmetry_site, (\n          arg(\"site_symmetry_ops\")))\n        .def(\"apply_symmetry_u_star\", &w_t::apply_symmetry_u_star, (\n          arg(\"site_symmetry_ops\"),\n          arg(\"u_star_tolerance\")=0))\n        .def(\"multiplicity\", &w_t::multiplicity)\n        .def(\"weight_without_occupancy\", &w_t::weight_without_occupancy)\n        .def(\"weight\", &w_t::weight)\n        .def(\"report_details\", &w_t::report_details, (\n          arg(\"unit_cell\"),\n          arg(\"prefix\")))\n      ;\n    }\n  };\n\n} // namespace <anoymous>\n\n  void wrap_scatterer()\n  {\n    using namespace boost::python;\n\n    scatterer_wrappers::wrap();\n\n    def(\"is_positive_definite_u\",\n      (af::shared<bool>(*)(\n        af::const_ref<scatterer<> > const&,\n        uctbx::unit_cell const&)) is_positive_definite_u, (\n          arg(\"scatterers\"),\n          arg(\"unit_cell\")));\n\n    def(\"is_positive_definite_u\",\n      (af::shared<bool>(*)(\n        af::const_ref<scatterer<> > const&,\n        uctbx::unit_cell const&,\n        double)) is_positive_definite_u, (\n          arg(\"scatterers\"),\n          arg(\"unit_cell\"),\n          arg(\"u_cart_tolerance\")));\n\n    def(\"tidy_us\",\n      (void(*)(\n        af::ref<scatterer<> > const&,\n        uctbx::unit_cell const&,\n        sgtbx::site_symmetry_table const&,\n        double u_min,\n        double u_max,\n        double anisotropy_min)) tidy_us, (\n          arg(\"scatterers\"),\n          arg(\"unit_cell\"),\n          arg(\"site_symmetry_table\"),\n          arg(\"u_min\"),\n          arg(\"u_max\"),\n          arg(\"anisotropy_min\")));\n\n    def(\"u_star_plus_u_iso\",\n      (void(*)(\n        af::ref<scatterer<> > const&,\n        uctbx::unit_cell const&)) u_star_plus_u_iso, (\n          arg(\"scatterers\"),\n          arg(\"unit_cell\")));\n\n    def(\"shift_us\",\n      (void(*)(\n        af::ref<scatterer<> > const&,\n        uctbx::unit_cell const&,\n        double u_min)) shift_us, (\n          arg(\"scatterers\"),\n          arg(\"unit_cell\"),\n          arg(\"u_shift\")));\n\n    def(\"shift_us\",\n      (void(*)(\n        af::ref<scatterer<> > const&,\n        uctbx::unit_cell const&,\n        double u_min,\n        af::const_ref<std::size_t> const&)) shift_us, (\n          arg(\"scatterers\"),\n          arg(\"unit_cell\"),\n          arg(\"u_shift\"),\n          arg(\"selection\")));\n\n    def(\"shift_occupancies\",\n      (void(*)(\n        af::ref<scatterer<> > const&,\n        double,\n        af::const_ref<std::size_t> const&)) shift_occupancies, (\n          arg(\"scatterers\"),\n          arg(\"q_shift\"),\n          arg(\"selection\")));\n\n    def(\"shift_occupancies\",\n      (void(*)(\n        af::ref<scatterer<> > const&,\n        double)) shift_occupancies, (\n          arg(\"scatterers\"),\n          arg(\"q_shift\")));\n\n    def(\"apply_symmetry_sites\",\n      (void(*)(\n        sgtbx::site_symmetry_table const&,\n        af::ref<scatterer<> > const&)) apply_symmetry_sites, (\n          arg(\"site_symmetry_table\"),\n          arg(\"scatterers\")));\n\n    def(\"apply_symmetry_u_stars\",\n      (void(*)(\n        sgtbx::site_symmetry_table const&,\n        af::ref<scatterer<> > const&,\n        double)) apply_symmetry_u_stars, (\n          arg(\"site_symmetry_table\"),\n          arg(\"scatterers\"),\n          arg(\"u_star_tolerance\")=0));\n\n    def(\"add_scatterers_ext\",\n      (void(*)(\n        uctbx::unit_cell const&,\n        sgtbx::space_group const&,\n        af::ref<scatterer<> > const&,\n        sgtbx::site_symmetry_table&,\n        sgtbx::site_symmetry_table const&,\n        double,\n        double,\n        bool,\n        bool)) add_scatterers_ext, (\n          arg(\"unit_cell\"),\n          arg(\"space_group\"),\n          arg(\"scatterers\"),\n          arg(\"site_symmetry_table\"),\n          arg(\"site_symmetry_table_for_new\"),\n          arg(\"min_distance_sym_equiv\"),\n          arg(\"u_star_tolerance\"),\n          arg(\"assert_min_distance_sym_equiv\"),\n          arg(\"non_unit_occupancy_implies_min_distance_sym_equiv_zero\")));\n\n    def(\"change_basis\",\n      (af::shared<scatterer<> >(*)(\n        af::const_ref<scatterer<> > const&,\n        sgtbx::change_of_basis_op const&)) change_basis, (\n      arg(\"scatterers\"), arg(\"cb_op\")));\n\n    def(\"expand_to_p1\",\n      (af::shared<scatterer<> >(*)(\n        uctbx::unit_cell const&,\n        sgtbx::space_group const&,\n        af::const_ref<scatterer<> > const&,\n        sgtbx::site_symmetry_table const&,\n        bool)) expand_to_p1, (\n          arg(\"unit_cell\"),\n          arg(\"space_group\"),\n          arg(\"scatterers\"),\n          arg(\"site_symmetry_table\"),\n          arg(\"append_number_to_labels\")));\n\n    def(\"n_undefined_multiplicities\",\n      (std::size_t(*)(\n        af::const_ref<scatterer<> > const&)) n_undefined_multiplicities, (\n      arg(\"scatterers\")));\n\n    def(\"asu_mappings_process\",\n      (void(*)(\n        crystal::direct_space_asu::asu_mappings<>&,\n        af::const_ref<scatterer<> > const&,\n        sgtbx::site_symmetry_table const&)) asu_mappings_process, (\n      arg(\"asu_mappings\"), arg(\"scatterers\"), arg(\"site_symmetry_table\")));\n\n    def(\"rotate\",\n      (af::shared<scatterer<> >(*)(\n        uctbx::unit_cell const&,\n        scitbx::mat3<double> const&,\n        af::const_ref<scatterer<> > const&)) rotate, (\n          arg(\"unit_cell\"),\n          arg(\"rotation_matrix\"),\n          arg(\"scatterers\")));\n\n    typedef return_value_policy<return_by_value> rbv;\n    class_<apply_rigid_body_shift<> >(\"apply_rigid_body_shift\")\n      .def(init<af::shared<scitbx::vec3<double> > const&,\n                af::shared<scitbx::vec3<double> > const&,\n                scitbx::mat3<double> const&,\n                scitbx::vec3<double> const&,\n                af::const_ref<double> const&,\n                uctbx::unit_cell const&,\n                af::const_ref<std::size_t> const& >((arg(\"sites_cart\"),\n                                              arg(\"sites_frac\"),\n                                              arg(\"rot\"),\n                                              arg(\"trans\"),\n                                              arg(\"atomic_weights\"),\n                                              arg(\"unit_cell\"),\n                                              arg(\"selection\"))))\n      .add_property(\"sites_frac\",  make_getter(\n                             &apply_rigid_body_shift<>::sites_frac, rbv()))\n      .add_property(\"sites_cart\",  make_getter(\n                             &apply_rigid_body_shift<>::sites_cart, rbv()))\n      .add_property(\"center_of_mass\",  make_getter(\n                             &apply_rigid_body_shift<>::center_of_mass, rbv()))\n    ;\n\n    def(\"set_inelastic_form_factors_from_henke\",\n      (void(*)(af::ref<scatterer<> > const &,\n               eltbx::wavelengths::characteristic,\n               bool))\n        inelastic_form_factors<eltbx::henke::table>::set,\n        (arg(\"scatterers\"), arg(\"photon\"), arg(\"set_use_fp_fdp\")=true));\n    def(\"set_inelastic_form_factors_from_sasaki\",\n      (void(*)(af::ref<scatterer<> > const &,\n               eltbx::wavelengths::characteristic,\n               bool))\n        inelastic_form_factors<eltbx::sasaki::table>::set,\n        (arg(\"scatterers\"), arg(\"photon\"), arg(\"set_use_fp_fdp\")=true));\n    def(\"set_inelastic_form_factors_from_henke\",\n      (void(*)(af::ref<scatterer<> > const &, float, bool))\n        inelastic_form_factors<eltbx::henke::table>::set,\n        (arg(\"scatterers\"), arg(\"wavelength\"), arg(\"set_use_fp_fdp\")=true));\n    def(\"set_inelastic_form_factors_from_sasaki\",\n      (void(*)(af::ref<scatterer<> > const &, float, bool))\n        inelastic_form_factors<eltbx::sasaki::table>::set,\n        (arg(\"scatterers\"), arg(\"wavelength\"), arg(\"set_use_fp_fdp\")=true));\n  }\n\n}}} // namespace cctbx::xray::boost_python\n", "meta": {"hexsha": "1aeab142d3aa4303146affe604c73e947be939aa", "size": 12776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/xray/boost_python/scatterer.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": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "cctbx/xray/boost_python/scatterer.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cctbx/xray/boost_python/scatterer.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": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T12:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T12:52:30.000Z", "avg_line_length": 35.9887323944, "max_line_length": 79, "alphanum_fraction": 0.5389010645, "num_tokens": 3279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1876059727494972}}
{"text": "#include \"worldengine/images/ancient_map_image.h\"\n#include \"../basic.h\"\n\n#include <random>\n\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n#endif\n\n#include <boost/log/trivial.hpp>\n#include <boost/multiprecision/integer.hpp>\n#include <boost/random.hpp>\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic pop\n#endif\n\n\nnamespace bm = boost::multiprecision;\n\nnamespace WorldEngine\n{\ntypedef std::function<void(\n   boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)>\n   DrawFunction;\n\nstatic const uint32_t NUM_COLOR_CHANNELS = 3;\n\nstatic const boost::gil::rgb8_pixel_t LAND_COLOR =\n   boost::gil::rgb8_pixel_t(181, 166, 127);\n\nstatic void CreateBiomeGroupMasks(\n   const World&                                                 world,\n   std::unordered_map<BiomeGroup, boost::multi_array<bool, 2>>& biomeMasks,\n   uint32_t                                                     scale);\nstatic void CreateMountainMask(const World&                  world,\n                               boost::multi_array<float, 2>& mountainMask,\n                               uint32_t                      scale);\n\nstatic void DrawAMountain(boost::gil::rgb8_image_t::view_t& target,\n                          int32_t                           x,\n                          int32_t                           y,\n                          float                             w,\n                          int32_t                           h);\nstatic void DrawDesertPattern(boost::gil::rgb8_image_t::view_t& target,\n                              int32_t                           x,\n                              int32_t                           y,\n                              boost::gil::rgb8_pixel_t          c);\nstatic void DrawForestPattern1(boost::gil::rgb8_image_t::view_t& target,\n                               int32_t                           x,\n                               int32_t                           y,\n                               boost::gil::rgb8_pixel_t          c1,\n                               boost::gil::rgb8_pixel_t          c2);\nstatic void DrawForestPattern2(boost::gil::rgb8_image_t::view_t& target,\n                               int32_t                           x,\n                               int32_t                           y,\n                               boost::gil::rgb8_pixel_t          c1,\n                               boost::gil::rgb8_pixel_t          c2);\n\nstatic void DrawPixelCheck(boost::gil::rgb8_image_t::view_t& target,\n                           int32_t                           x,\n                           int32_t                           y,\n                           boost::gil::rgb8_pixel_t          c);\nstatic void DrawShadedPixel(boost::gil::rgb8_image_t::view_t& target,\n                            uint32_t                          x,\n                            uint32_t                          y,\n                            uint8_t                           r,\n                            uint8_t                           g,\n                            uint8_t                           b);\nstatic void DrawBorealForest(boost::gil::rgb8_image_t::view_t& target,\n                             uint32_t                          x,\n                             uint32_t                          y);\nstatic void\nDrawChaparral(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y);\nstatic void DrawCoolDesert(boost::gil::rgb8_image_t::view_t& target,\n                           uint32_t                          x,\n                           uint32_t                          y);\nstatic void DrawColdParklands(boost::gil::rgb8_image_t::view_t& target,\n                              uint32_t                          x,\n                              uint32_t                          y);\nstatic void\nDrawGlacier(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y);\nstatic void\nDrawHotDesert(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y);\nstatic void\nDrawJungle(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y);\nstatic void\nDrawSavanna(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y);\nstatic void\nDrawSteppe(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y);\nstatic void DrawTemperateForest1(boost::gil::rgb8_image_t::view_t& target,\n                                 uint32_t                          x,\n                                 uint32_t                          y);\nstatic void DrawTemperateForest2(boost::gil::rgb8_image_t::view_t& target,\n                                 uint32_t                          x,\n                                 uint32_t                          y);\nstatic void DrawTropicalDryForest(boost::gil::rgb8_image_t::view_t& target,\n                                  uint32_t                          x,\n                                  uint32_t                          y);\nstatic void\nDrawTundra(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y);\nstatic void DrawWarmTemperateForest(boost::gil::rgb8_image_t::view_t& target,\n                                    uint32_t                          x,\n                                    uint32_t                          y);\ntemplate<typename T>\nstatic void ScaleArray(const boost::multi_array<T, 2>& input,\n                       boost::multi_array<T, 2>&       output,\n                       uint32_t                        scale);\n\nAncientMapImage::AncientMapImage(const World& world,\n                                 uint32_t     seed,\n                                 uint32_t     scale,\n                                 SeaColor     seaColor,\n                                 bool         drawBiome,\n                                 bool         drawRivers,\n                                 bool         drawMountains,\n                                 bool         drawOuterLandBorder) :\n    Image(world, scale),\n    seed_(seed),\n    seaColor_(seaColor),\n    drawBiome_(drawBiome),\n    drawRivers_(drawRivers),\n    drawMountains_(drawMountains),\n    drawOuterLandBorder_(drawOuterLandBorder)\n{\n}\n\nAncientMapImage::~AncientMapImage() {}\n\nvoid AncientMapImage::DrawImage(boost::gil::rgb8_image_t::view_t& target)\n{\n   BOOST_LOG_TRIVIAL(debug) << \"Ancient map: Initializing\";\n\n   std::mt19937 generator(seed_);\n\n   const int32_t width   = world_.width();\n   const int32_t height  = world_.height();\n   const int32_t sWidth  = width * scale_;\n   const int32_t sHeight = height * scale_;\n\n   const boost::gil::rgb8_pixel_t seaColor =\n      (seaColor_ == SeaColor::Blue) ? boost::gil::rgb8_pixel_t(142, 162, 179) :\n                                      boost::gil::rgb8_pixel_t(212, 198, 169);\n\n   OceanArrayType scaledOcean;\n   ScaleArray(world_.GetOceanData(), scaledOcean, scale_);\n   boost::multi_array<uint32_t, 2> neighbors = CountNeighbors(scaledOcean);\n\n   boost::multi_array<bool, 2> borders(boost::extents[sHeight][sWidth]);\n   std::transform(scaledOcean.data(),\n                  scaledOcean.data() + scaledOcean.num_elements(),\n                  neighbors.data(),\n                  borders.data(),\n                  [](const bool& ocean, const uint32_t& neighbors) -> bool {\n                     return (ocean || neighbors == 0) ? false : true;\n                  });\n\n   // Cache neighbors count at different radii\n   std::unordered_map<int32_t, boost::multi_array<int32_t, 2>> borderNeighbors;\n   borderNeighbors[6].resize(boost::extents[sHeight][sWidth]);\n   borderNeighbors[9].resize(boost::extents[sHeight][sWidth]);\n   borderNeighbors[6] = CountNeighbors(borders, 6);\n   borderNeighbors[9] = CountNeighbors(borders, 9);\n\n   boost::multi_array<bool, 2> outerBorders;\n   if (drawOuterLandBorder_)\n   {\n      outerBorders.resize(boost::extents[sHeight][sWidth]);\n\n      auto GenerateOuterBorders =\n         [&sWidth, &sHeight, &scaledOcean = std::as_const(scaledOcean)](\n            const boost::multi_array<bool, 2>& innerBorders,\n            boost::multi_array<bool, 2>&       outerBorders) {\n            boost::multi_array<uint32_t, 2> neighbors =\n               CountNeighbors(innerBorders);\n\n            for (int32_t y = 0; y < sHeight; y++)\n            {\n               for (int32_t x = 0; x < sWidth; x++)\n               {\n                  outerBorders[y][x] = !innerBorders[y][x] &&\n                                       scaledOcean[y][x] && neighbors[y][x] > 0;\n               }\n            }\n         };\n\n      GenerateOuterBorders(borders, outerBorders);\n      GenerateOuterBorders(outerBorders, outerBorders);\n   }\n\n   boost::multi_array<float, 2> mountainMask;\n   if (drawMountains_)\n   {\n      CreateMountainMask(world_, mountainMask, scale_);\n   }\n\n   std::unordered_map<BiomeGroup, boost::multi_array<bool, 2>> biomeMasks;\n\n   std::function<void(BiomeGroup, DrawFunction, int32_t, DrawFunction)>\n      DrawBiome;\n   if (drawBiome_)\n   {\n      CreateBiomeGroupMasks(world_, biomeMasks, scale_);\n\n      DrawBiome = [this,\n                   &biomeMasks,\n                   &generator,\n                   &target,\n                   &borderNeighbors = std::as_const(borderNeighbors),\n                   &borders = std::as_const(borders)](BiomeGroup   group,\n                                                      DrawFunction Draw,\n                                                      int32_t      r,\n                                                      DrawFunction AltDraw) {\n         BOOST_LOG_TRIVIAL(debug)\n            << \"Ancient map: Drawing biome group \" << group;\n\n         boost::random::uniform_real_distribution<float> random(0.0f, 1.0f);\n\n         const int32_t width   = world_.width();\n         const int32_t height  = world_.height();\n         const int32_t sWidth  = width * scale_;\n         const int32_t sHeight = height * scale_;\n\n         for (int32_t sy = 0; sy < sHeight; sy++)\n         {\n            for (int32_t sx = 0; sx < sWidth; sx++)\n            {\n               if (biomeMasks.at(group)[sy][sx])\n               {\n                  if (group == BiomeGroup::Iceland)\n                  {\n                     if (!borders[sy][sx])\n                     {\n                        Draw(target, sx, sy);\n                     }\n                  }\n                  else\n                  {\n                     if (r == 0 || borderNeighbors.at(r)[sy][sx] <= 2)\n                     {\n                        if (AltDraw != nullptr && random(generator) >= 0.5f)\n                        {\n                           AltDraw(target, sx, sy);\n                        }\n                        else\n                        {\n                           Draw(target, sx, sy);\n                        }\n\n                        for (int32_t dy = -r; dy <= r; dy++)\n                        {\n                           const int32_t yp = sy + dy;\n                           for (int32_t dx = -r; dx <= r; dx++)\n                           {\n                              const int32_t xp = sx + dx;\n                              if (0 <= yp && yp < sHeight && 0 <= xp &&\n                                  xp < sWidth)\n                              {\n                                 biomeMasks.at(group)[yp][xp] = false;\n                              }\n                           }\n                        }\n                     }\n                  }\n               }\n            }\n         }\n      };\n   }\n\n   BOOST_LOG_TRIVIAL(debug) << \"Ancient map: Coloring oceans and borders\";\n\n   static const boost::gil::rgb8_pixel_t borderColor(0, 0, 0);\n   const boost::gil::rgb8_pixel_t        outerBorderColor =\n      Gradient(0.5f, 0.0f, 1.0f, borderColor, seaColor);\n\n   std::vector<boost::multi_array<float, 2>> channels;\n   for (uint32_t c = 0; c < NUM_COLOR_CHANNELS; c++)\n   {\n      channels.push_back(\n         boost::multi_array<float, 2>(boost::extents[sHeight][sWidth]));\n   }\n\n   for (int32_t y = 0; y < sHeight; y++)\n   {\n      for (int32_t x = 0; x < sWidth; x++)\n      {\n         boost::gil::rgb8_pixel_t color;\n\n         if (borders[y][x])\n         {\n            color = borderColor;\n         }\n         else if (drawOuterLandBorder_ && outerBorders[y][x])\n         {\n            color = outerBorderColor;\n         }\n         else if (scaledOcean[y][x])\n         {\n            color = seaColor;\n         }\n         else\n         {\n            color = LAND_COLOR;\n         }\n\n         for (uint32_t c = 0; c < NUM_COLOR_CHANNELS; c++)\n         {\n            channels[c][y][x] = color[c];\n         }\n      }\n   }\n\n   BOOST_LOG_TRIVIAL(debug) << \"Ancient map: Anti-aliasing image\";\n   for (uint32_t c = 0; c < NUM_COLOR_CHANNELS; c++)\n   {\n      AntiAlias(channels[c]);\n   }\n\n   for (int32_t y = 0; y < sHeight; y++)\n   {\n      for (int32_t x = 0; x < sWidth; x++)\n      {\n         target(x, y) =\n            boost::gil::rgb8_pixel_t(static_cast<uint8_t>(channels[0][y][x]),\n                                     static_cast<uint8_t>(channels[1][y][x]),\n                                     static_cast<uint8_t>(channels[2][y][x]));\n      }\n   }\n\n   if (drawBiome_)\n   {\n      DrawBiome(BiomeGroup::Iceland, DrawGlacier, 0, nullptr);\n      DrawBiome(BiomeGroup::Tundra, DrawTundra, 0, nullptr);\n      DrawBiome(BiomeGroup::ColdParklands, DrawColdParklands, 0, nullptr);\n      DrawBiome(BiomeGroup::Steppe, DrawSteppe, 0, nullptr);\n      DrawBiome(BiomeGroup::Chaparral, DrawChaparral, 0, nullptr);\n      DrawBiome(BiomeGroup::Savanna, DrawSavanna, 0, nullptr);\n      DrawBiome(BiomeGroup::CoolDesert, DrawCoolDesert, 9, nullptr);\n      DrawBiome(BiomeGroup::HotDesert, DrawHotDesert, 9, nullptr);\n      DrawBiome(BiomeGroup::BorealForest, DrawBorealForest, 6, nullptr);\n      DrawBiome(BiomeGroup::CoolTemperateForest,\n                DrawTemperateForest1,\n                6,\n                DrawTemperateForest2);\n      DrawBiome(\n         BiomeGroup::WarmTemperateForest, DrawWarmTemperateForest, 6, nullptr);\n      DrawBiome(\n         BiomeGroup::TropicalDryForest, DrawTropicalDryForest, 6, nullptr);\n      DrawBiome(BiomeGroup::Jungle, DrawJungle, 6, nullptr);\n   }\n\n   if (drawRivers_)\n   {\n      BOOST_LOG_TRIVIAL(debug) << \"Ancient map: Drawing rivers\";\n      DrawRivers(target);\n   }\n\n   if (drawMountains_)\n   {\n      BOOST_LOG_TRIVIAL(debug) << \"Ancient map: Drawing mountains\";\n\n      for (int32_t sy = 0; sy < sHeight; sy++)\n      {\n         int32_t y = sy / scale_;\n         for (int32_t sx = 0; sx < sWidth; sx++)\n         {\n            int32_t x = sx / scale_;\n\n            float w = mountainMask[sy][sx];\n            if (w > 0.0f)\n            {\n               int32_t h =\n                  static_cast<int32_t>(3u + world_.GetLevelOfMountain(x, y));\n               int32_t r =\n                  std::max<int32_t>(static_cast<int32_t>(w * 2 / 3), h);\n\n               if (borderNeighbors.find(r) == borderNeighbors.end())\n               {\n                  borderNeighbors[r].resize(boost::extents[sHeight][sWidth]);\n                  borderNeighbors[r] = CountNeighbors(borders, r);\n               }\n\n               if (borderNeighbors[r][sy][sx] <= 2)\n               {\n                  DrawAMountain(target, sx, sy, w, h);\n\n                  for (int32_t dy = -r; dy <= r; dy++)\n                  {\n                     const int32_t yp = sy + dy;\n                     for (int32_t dx = -r; dx <= r; dx++)\n                     {\n                        const int32_t xp = sx + dx;\n                        if (0 <= yp && yp < sHeight && 0 <= xp && xp < sWidth)\n                        {\n                           mountainMask[yp][xp] = 0.0;\n                        }\n                     }\n                  }\n               }\n            }\n         }\n      }\n   }\n\n   BOOST_LOG_TRIVIAL(debug) << \"Ancient map: Complete\";\n}\n\nstatic void CreateBiomeGroupMasks(\n   const World&                                                 world,\n   std::unordered_map<BiomeGroup, boost::multi_array<bool, 2>>& masks,\n   uint32_t                                                     scale)\n{\n   const uint32_t width  = world.width();\n   const uint32_t height = world.height();\n\n   for (BiomeGroup group : BiomeGroupIterator())\n   {\n      boost::multi_array<bool, 2>& mask = masks[group];\n      mask.resize(boost::extents[height][width]);\n      std::fill(mask.data(), mask.data() + mask.num_elements(), false);\n\n      for (uint32_t y = 0; y < height; y++)\n      {\n         for (uint32_t x = 0; x < width; x++)\n         {\n            if (group == world.GetBiomeGroup(x, y))\n            {\n               mask[y][x] = true;\n            }\n         }\n      }\n\n      const boost::multi_array<uint32_t, 2> neighbors = CountNeighbors(mask);\n\n      std::transform(\n         mask.data(),\n         mask.data() + mask.num_elements(),\n         neighbors.data(),\n         mask.data(),\n         [&group = std::as_const(group)](const bool&     mask,\n                                         const uint32_t& neighbors) -> bool {\n            return (mask && (neighbors > 5 || group == BiomeGroup::Iceland));\n         });\n\n      ScaleArray(mask, mask, scale);\n   }\n}\n\nstatic void CreateMountainMask(const World&                  world,\n                               boost::multi_array<float, 2>& mask,\n                               uint32_t                      scale)\n{\n   const uint32_t width  = world.width();\n   const uint32_t height = world.height();\n\n   mask.resize(boost::extents[height][width]);\n   std::fill(mask.data(), mask.data() + mask.num_elements(), 0.0f);\n\n   for (uint32_t y = 0; y < height; y++)\n   {\n      for (uint32_t x = 0; x < width; x++)\n      {\n         if (world.IsMountain(x, y))\n         {\n            mask[y][x] = 1.0f;\n         }\n      }\n   }\n\n   const boost::multi_array<uint32_t, 2> neighbors = CountNeighbors(mask, 3);\n\n   std::transform(mask.data(),\n                  mask.data() + mask.num_elements(),\n                  neighbors.data(),\n                  mask.data(),\n                  [](const float& mask, const uint32_t& neighbors) -> float {\n                     if (mask > 0.0f && neighbors > 32)\n                     {\n                        return neighbors / 4.0f;\n                     }\n                     else\n                     {\n                        return 0.0f;\n                     }\n                  });\n\n   ScaleArray(mask, mask, scale);\n}\n\nstatic void DrawAMountain(boost::gil::rgb8_image_t::view_t& target,\n                          int32_t                           x,\n                          int32_t                           y,\n                          float,\n                          int32_t h)\n{\n   const boost::gil::rgb8_pixel_t mcr(75, 75, 75);\n\n   // Left edge\n   for (int32_t mody = -h; mody <= h; mody++)\n   {\n      const float   bottomness = (mody + h) / 2.0f;\n      const int32_t leftBorder = static_cast<int32_t>(bottomness);\n      const int32_t darkArea   = static_cast<int32_t>(bottomness / 2.0f);\n      const int32_t lightArea  = darkArea;\n\n      for (int32_t itx = darkArea; itx <= leftBorder; itx++)\n      {\n         DrawPixelCheck(target,\n                        x - itx,\n                        y + mody,\n                        Gradient(static_cast<float>(itx),\n                                 static_cast<float>(darkArea),\n                                 static_cast<float>(leftBorder),\n                                 boost::gil::rgb8_pixel_t(0, 0, 0),\n                                 boost::gil::rgb8_pixel_t(64, 64, 64)));\n      }\n      for (int32_t itx = -darkArea; itx <= lightArea; itx++)\n      {\n         DrawPixelCheck(target,\n                        x + itx,\n                        y + mody,\n                        Gradient(static_cast<float>(itx),\n                                 static_cast<float>(-darkArea),\n                                 static_cast<float>(lightArea),\n                                 boost::gil::rgb8_pixel_t(64, 64, 64),\n                                 boost::gil::rgb8_pixel_t(128, 128, 128)));\n      }\n      for (int32_t itx = lightArea; itx < leftBorder; itx++)\n      {\n         DrawPixelCheck(target, x + itx, y + mody, LAND_COLOR);\n      }\n   }\n\n   // Right edge\n   for (int32_t mody = -h; mody <= h; mody++)\n   {\n      float    bottomness = (mody + h) / 2.0f;\n      uint32_t modx       = static_cast<uint32_t>(bottomness);\n      DrawPixelCheck(target, x + modx, y + mody, mcr);\n   }\n}\n\nstatic void DrawDesertPattern(boost::gil::rgb8_image_t::view_t& target,\n                              int32_t                           x,\n                              int32_t                           y,\n                              boost::gil::rgb8_pixel_t          c)\n{\n   static const std::vector<Point> points = {\n      {-1, -2}, {0, -2}, {1, -2}, {2, -2}, {-2, -1}, {-1, -1}, {0, -1},\n      {4, -1},  {-4, 0}, {-3, 0}, {-2, 0}, {-1, 0},  {1, 0},   {2, 0},\n      {6, 0},   {-5, 1}, {0, 1},  {7, 1},  {8, 1},   {-8, 2},  {-7, 2}};\n\n   for (Point p : points)\n   {\n      DrawPixelCheck(target, x + p.first, y + p.second, c);\n   }\n}\n\nstatic void DrawForestPattern1(boost::gil::rgb8_image_t::view_t& target,\n                               int32_t                           x,\n                               int32_t                           y,\n                               boost::gil::rgb8_pixel_t          c1,\n                               boost::gil::rgb8_pixel_t          c2)\n{\n   static const std::vector<Point> c1Points = {\n      {0, -4}, {0, -3}, {-1, -2}, {1, -2}, {-1, -1}, {1, -1}, {-2, 0}, {1, 0},\n      {2, 0},  {-2, 1}, {2, 1},   {-3, 2}, {-1, 2},  {3, 2},  {-3, 3}, {-2, 3},\n      {-1, 3}, {0, 3},  {1, 3},   {2, 3},  {3, 3},   {0, 4}};\n   static const std::vector<Point> c2Points = {{0, -2},\n                                               {0, -1},\n                                               {-1, 0},\n                                               {0, 0},\n                                               {-1, 1},\n                                               {0, 1},\n                                               {1, 1},\n                                               {-2, 2},\n                                               {0, 2},\n                                               {1, 2},\n                                               {2, 2}};\n\n   for (Point p : c1Points)\n   {\n      DrawPixelCheck(target, x + p.first, y + p.second, c1);\n   }\n   for (Point p : c2Points)\n   {\n      DrawPixelCheck(target, x + p.first, y + p.second, c2);\n   }\n}\n\nstatic void DrawForestPattern2(boost::gil::rgb8_image_t::view_t& target,\n                               int32_t                           x,\n                               int32_t                           y,\n                               boost::gil::rgb8_pixel_t          c1,\n                               boost::gil::rgb8_pixel_t          c2)\n{\n   static const std::vector<Point> c1Points = {\n      {-1, -4}, {0, -4}, {1, -4}, {-2, -3}, {-1, -3}, {2, -3},\n      {-2, -2}, {1, -2}, {2, -2}, {-2, -1}, {2, -1},  {-2, 0},\n      {-1, 0},  {2, 0},  {-2, 1}, {1, 1},   {2, 1},   {-1, 2},\n      {0, 2},   {1, 2},  {0, 3},  {0, 4}};\n   static const std::vector<Point> c2Points = {{0, -3},\n                                               {1, -3},\n                                               {-1, -2},\n                                               {0, -2},\n                                               {-1, -1},\n                                               {0, -1},\n                                               {1, -1},\n                                               {0, 0},\n                                               {1, 0},\n                                               {-1, 1},\n                                               {0, 1}};\n\n   for (Point p : c1Points)\n   {\n      DrawPixelCheck(target, x + p.first, y + p.second, c1);\n   }\n   for (Point p : c2Points)\n   {\n      DrawPixelCheck(target, x + p.first, y + p.second, c2);\n   }\n}\n\nstatic void DrawPixelCheck(boost::gil::rgb8_image_t::view_t& target,\n                           int32_t                           x,\n                           int32_t                           y,\n                           boost::gil::rgb8_pixel_t          c)\n{\n   if (0 <= x && x < target.width() && 0 <= y && y < target.height())\n   {\n      target(x, y) = c;\n   }\n}\n\nstatic void DrawShadedPixel(boost::gil::rgb8_image_t::view_t& target,\n                            uint32_t                          x,\n                            uint32_t                          y,\n                            uint8_t                           r,\n                            uint8_t                           g,\n                            uint8_t                           b)\n{\n   const uint8_t db =\n      (bm::powm(x, y / 5, 75) + x * 23 + y * 37 + (x * y) * 13) % 75;\n   const uint8_t nr = r - db;\n   const uint8_t ng = g - db;\n   const uint8_t nb = b - db;\n\n   target(x, y) = boost::gil::rgb8_pixel_t(nr, ng, nb);\n}\n\nstatic void DrawBorealForest(boost::gil::rgb8_image_t::view_t& target,\n                             uint32_t                          x,\n                             uint32_t                          y)\n{\n   const boost::gil::rgb8_pixel_t c1(0, 32, 0);\n   const boost::gil::rgb8_pixel_t c2(0, 64, 0);\n   DrawForestPattern1(target, x, y, c1, c2);\n}\n\nstatic void\nDrawChaparral(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)\n{\n   DrawShadedPixel(target, x, y, 180, 171, 113);\n}\n\nstatic void\nDrawCoolDesert(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)\n{\n   const boost::gil::rgb8_pixel_t c(72, 72, 53);\n   DrawDesertPattern(target, x, y, c);\n}\n\nstatic void DrawColdParklands(boost::gil::rgb8_image_t::view_t& target,\n                              uint32_t                          x,\n                              uint32_t                          y)\n{\n   const uint8_t db =\n      (bm::powm(x, y / 5, 75) + x * 23 + y * 37 + (x * y) * 13) % 75;\n   const uint8_t r = 105 - db;\n   const uint8_t g = 96 - db;\n   const uint8_t b = 38 - db / 2;\n   target(x, y)    = boost::gil::rgb8_pixel_t(r, g, b);\n}\n\nstatic void\nDrawGlacier(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)\n{\n   const uint8_t rg =\n      255 - (bm::powm(x, y / 5, 75) + x * 23 + y * 37 + (x * y) * 13) % 75;\n   target(x, y) = boost::gil::rgb8_pixel_t(rg, rg, 255);\n}\n\nstatic void\nDrawHotDesert(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)\n{\n   const boost::gil::rgb8_pixel_t c(72, 72, 53);\n   DrawDesertPattern(target, x, y, c);\n}\n\nstatic void\nDrawJungle(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)\n{\n   const boost::gil::rgb8_pixel_t c1(0, 128, 0);\n   const boost::gil::rgb8_pixel_t c2(0, 255, 0);\n   DrawForestPattern2(target, x, y, c1, c2);\n}\n\nstatic void\nDrawSavanna(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)\n{\n   DrawShadedPixel(target, x, y, 255, 246, 188);\n}\n\nstatic void\nDrawSteppe(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)\n{\n   DrawShadedPixel(target, x, y, 96, 192, 96);\n}\n\nstatic void DrawTemperateForest1(boost::gil::rgb8_image_t::view_t& target,\n                                 uint32_t                          x,\n                                 uint32_t                          y)\n{\n   const boost::gil::rgb8_pixel_t c1(0, 64, 0);\n   const boost::gil::rgb8_pixel_t c2(0, 96, 0);\n   DrawForestPattern1(target, x, y, c1, c2);\n}\n\nstatic void DrawTemperateForest2(boost::gil::rgb8_image_t::view_t& target,\n                                 uint32_t                          x,\n                                 uint32_t                          y)\n{\n   const boost::gil::rgb8_pixel_t c1(0, 64, 0);\n   const boost::gil::rgb8_pixel_t c2(0, 112, 0);\n   DrawForestPattern2(target, x, y, c1, c2);\n}\n\nstatic void DrawTropicalDryForest(boost::gil::rgb8_image_t::view_t& target,\n                                  uint32_t                          x,\n                                  uint32_t                          y)\n{\n   const boost::gil::rgb8_pixel_t c1(51, 36, 3);\n   const boost::gil::rgb8_pixel_t c2(139, 204, 58);\n   DrawForestPattern2(target, x, y, c1, c2);\n}\n\nstatic void\nDrawTundra(boost::gil::rgb8_image_t::view_t& target, uint32_t x, uint32_t y)\n{\n   DrawShadedPixel(target, x, y, 166, 148, 75);\n}\n\nstatic void DrawWarmTemperateForest(boost::gil::rgb8_image_t::view_t& target,\n                                    uint32_t                          x,\n                                    uint32_t                          y)\n{\n   const boost::gil::rgb8_pixel_t c1(0, 96, 0);\n   const boost::gil::rgb8_pixel_t c2(0, 192, 0);\n   DrawForestPattern2(target, x, y, c1, c2);\n}\n\nboost::gil::rgb8_pixel_t Gradient(float                    value,\n                                  float                    low,\n                                  float                    high,\n                                  boost::gil::rgb8_pixel_t lowColor,\n                                  boost::gil::rgb8_pixel_t highColor)\n{\n   if (low == high)\n   {\n      return lowColor;\n   }\n\n   const float range = high - low;\n   const float x     = (value - low) / range;\n   const float ix    = 1.0f - x;\n\n   const uint8_t lr = lowColor[0];\n   const uint8_t lg = lowColor[1];\n   const uint8_t lb = lowColor[2];\n   const uint8_t hr = highColor[0];\n   const uint8_t hg = highColor[1];\n   const uint8_t hb = highColor[2];\n\n   const uint8_t r = static_cast<uint8_t>(lr * ix + hr * x);\n   const uint8_t g = static_cast<uint8_t>(lg * ix + hg * x);\n   const uint8_t b = static_cast<uint8_t>(lb * ix + hb * x);\n\n   return boost::gil::rgb8_pixel_t(r, g, b);\n}\n\ntemplate<typename T>\nstatic void ScaleArray(const boost::multi_array<T, 2>& input,\n                       boost::multi_array<T, 2>&       output,\n                       uint32_t                        scale)\n{\n   const uint32_t width   = static_cast<uint32_t>(input.shape()[1]);\n   const uint32_t height  = static_cast<uint32_t>(input.shape()[0]);\n   const uint32_t sWidth  = width * scale;\n   const uint32_t sHeight = height * scale;\n\n   output.resize(boost::extents[sHeight][sWidth]);\n\n   if (scale == 1)\n   {\n      output = input;\n   }\n   else\n   {\n      for (int32_t y = height - 1; y >= 0; y--)\n      {\n         for (uint32_t dy = 0; dy < scale; dy++)\n         {\n            const uint32_t yp = y * scale + dy;\n\n            for (int32_t x = width - 1; x >= 0; x--)\n            {\n               for (uint32_t dx = 0; dx < scale; dx++)\n               {\n                  const uint32_t xp = x * scale + dx;\n\n                  output[yp][xp] = input[y][x];\n               }\n            }\n         }\n      }\n   }\n}\n\n} // namespace WorldEngine\n", "meta": {"hexsha": "c286b38d132a0a5d4e02713f3fbc8caf2bea0d78", "size": 30469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "worldengine/source/images/ancient_map_image.cpp", "max_stars_repo_name": "dpaulat/worldengine-cpp", "max_stars_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T12:44:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T21:52:10.000Z", "max_issues_repo_path": "worldengine/source/images/ancient_map_image.cpp", "max_issues_repo_name": "dpaulat/worldengine-cpp", "max_issues_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T12:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T15:28:37.000Z", "max_forks_repo_path": "worldengine/source/images/ancient_map_image.cpp", "max_forks_repo_name": "dpaulat/worldengine-cpp", "max_forks_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_forks_repo_licenses": ["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.5774309724, "max_line_length": 80, "alphanum_fraction": 0.4541008894, "num_tokens": 7519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.18759006227248218}}
{"text": "/*==============================================================================\r\n    Copyright (c) 2011 Steven Watanabe\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#ifndef BOOST_PHOENIX_CMATH_HPP_INCLUDED\r\n#define BOOST_PHOENIX_CMATH_HPP_INCLUDED\r\n\r\n#include <boost/phoenix/core/limits.hpp>\r\n#include <cmath>\r\n#include <boost/phoenix/function/adapt_callable.hpp>\r\n#include <boost/type_traits/declval.hpp>\r\n#include <boost/phoenix/support/iterate.hpp>\r\n\r\nnamespace boost {\r\n\r\n#if (defined (BOOST_NO_CXX11_DECLTYPE) || \\\r\n     defined (BOOST_INTEL_CXX_VERSION) || \\\r\n             (BOOST_GCC_VERSION < 40500) )\r\n#define BOOST_PHOENIX_MATH_FUNCTION_RESULT_TYPE(name, n)                \\\r\n    typename proto::detail::uncvref<A0>::type\r\n#else\r\n#define BOOST_PHOENIX_MATH_FUNCTION_RESULT_TYPE(name, n)                \\\r\n    decltype(name(BOOST_PP_ENUM_BINARY_PARAMS(                          \\\r\n                      n                                                 \\\r\n                    , boost::declval<typename proto::detail::uncvref<A  \\\r\n                    ,  >::type>() BOOST_PP_INTERCEPT)))\r\n#endif\r\n#define BOOST_PHOENIX_MATH_FUNCTION(name, n)                            \\\r\n    namespace phoenix_impl {                                            \\\r\n    struct name ## _impl {                                              \\\r\n        template<class Sig>                                             \\\r\n        struct result;                                                  \\\r\n        template<class This, BOOST_PHOENIX_typename_A(n)>               \\\r\n        struct result<This(BOOST_PHOENIX_A(n))>                         \\\r\n        {                                                               \\\r\n            typedef                                                     \\\r\n                BOOST_PHOENIX_MATH_FUNCTION_RESULT_TYPE(name, n)        \\\r\n                type;                                                   \\\r\n        };                                                              \\\r\n        template<BOOST_PHOENIX_typename_A(n)>                           \\\r\n        typename result<name ## _impl(BOOST_PHOENIX_A(n))>::type        \\\r\n        operator()(BOOST_PHOENIX_A_const_ref_a(n)) const {              \\\r\n            using namespace std;                                        \\\r\n            return name(BOOST_PHOENIX_a(n));                            \\\r\n        }                                                               \\\r\n    };                                                                  \\\r\n    }                                                                   \\\r\n    namespace phoenix {                                                 \\\r\n    BOOST_PHOENIX_ADAPT_CALLABLE(name, phoenix_impl::name ## _impl, n)  \\\r\n    }\r\n\r\nBOOST_PHOENIX_MATH_FUNCTION(acos, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(asin, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(atan, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(atan2, 2)\r\nBOOST_PHOENIX_MATH_FUNCTION(ceil, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(cos, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(cosh, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(exp, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(fabs, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(floor, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(fmod, 2)\r\nBOOST_PHOENIX_MATH_FUNCTION(frexp, 2)\r\nBOOST_PHOENIX_MATH_FUNCTION(ldexp, 2)\r\nBOOST_PHOENIX_MATH_FUNCTION(log, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(log10, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(modf, 2)\r\nBOOST_PHOENIX_MATH_FUNCTION(pow, 2)\r\nBOOST_PHOENIX_MATH_FUNCTION(sin, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(sinh, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(sqrt, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(tan, 1)\r\nBOOST_PHOENIX_MATH_FUNCTION(tanh, 1)\r\n\r\n#undef BOOST_PHOENIX_MATH_FUNCTION\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "179e6afdd60754a2bae9bfc27221b718a6e013ad", "size": 3851, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/phoenix/stl/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/phoenix/stl/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/phoenix/stl/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": 46.3975903614, "max_line_length": 81, "alphanum_fraction": 0.4985717995, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18759005519017083}}
{"text": "/**************************************************************\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 *************************************************************/\n\n\n\n// MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n#include <canvas/debug.hxx>\n#include <tools/diagnose_ex.h>\n\n#include <comphelper/anytostring.hxx>\n#include <cppuhelper/exc_hlp.hxx>\n#include <basegfx/numeric/ftools.hxx>\n#include <basegfx/matrix/b2dhommatrix.hxx>\n#include <basegfx/polygon/b2dpolypolygontools.hxx>\n\n#include <com/sun/star/animations/TransitionType.hpp>\n#include <com/sun/star/animations/TransitionSubType.hpp>\n\n#include \"transitionfactory.hxx\"\n#include \"transitiontools.hxx\"\n#include \"parametricpolypolygonfactory.hxx\"\n#include \"animationfactory.hxx\"\n#include \"clippingfunctor.hxx\"\n\n#include <boost/bind.hpp>\n\n\nusing namespace ::com::sun::star;\n\nnamespace slideshow {\nnamespace internal {\n\n/***************************************************\n ***                                             ***\n ***          Shape Transition Effects           ***\n ***                                             ***\n ***************************************************/\n\nnamespace {\n\nclass ClippingAnimation : public NumberAnimation\n{\npublic:\n    ClippingAnimation(\n        const ParametricPolyPolygonSharedPtr&   rPolygon,\n        const ShapeManagerSharedPtr&            rShapeManager,\n        const TransitionInfo&                   rTransitionInfo,\n        bool                                    bDirectionForward,\n        bool                                    bModeIn );\n\n    ~ClippingAnimation();\n    \n    // Animation interface\n    // -------------------\n    virtual void prefetch( const AnimatableShapeSharedPtr&     rShape,\n                           const ShapeAttributeLayerSharedPtr& rAttrLayer );\n    virtual void start( const AnimatableShapeSharedPtr& \trShape,\n                        const ShapeAttributeLayerSharedPtr& rAttrLayer );\n    virtual void end();\n    \n    // NumberAnimation interface\n    // -----------------------\n    virtual bool operator()( double nValue );\n    virtual double getUnderlyingValue() const;\n        \nprivate:\n    void end_();\n\n    AnimatableShapeSharedPtr           mpShape;\n    ShapeAttributeLayerSharedPtr       mpAttrLayer;\n    ShapeManagerSharedPtr              mpShapeManager;\n    ClippingFunctor\t\t\t\t\t   maClippingFunctor;\n    bool\t\t\t\t\t\t\t   mbSpriteActive;\n};\n\nClippingAnimation::ClippingAnimation(\n    const ParametricPolyPolygonSharedPtr&   rPolygon,\n    const ShapeManagerSharedPtr&            rShapeManager,\n    const TransitionInfo&                   rTransitionInfo,\n    bool                                    bDirectionForward,\n    bool                                    bModeIn ) :\n        mpShape(),\n        mpAttrLayer(),\n        mpShapeManager( rShapeManager ),\n        maClippingFunctor( rPolygon, \n                           rTransitionInfo, \n                           bDirectionForward, \n                           bModeIn ),\n        mbSpriteActive(false)\n{\n    ENSURE_OR_THROW(\n        rShapeManager,\n        \"ClippingAnimation::ClippingAnimation(): Invalid ShapeManager\" );\n}\n\nClippingAnimation::~ClippingAnimation()\n{\n    try\n    {\n        end_();\n    }\n    catch (uno::Exception &) \n    {\n        OSL_ENSURE( false, rtl::OUStringToOString(\n                        comphelper::anyToString(\n                            cppu::getCaughtException() ),\n                        RTL_TEXTENCODING_UTF8 ).getStr() );\n    }\n}\n\nvoid ClippingAnimation::prefetch( const AnimatableShapeSharedPtr&,\n                                  const ShapeAttributeLayerSharedPtr& )\n{\n}\n\nvoid ClippingAnimation::start( const AnimatableShapeSharedPtr& \t\trShape,\n                               const ShapeAttributeLayerSharedPtr& \trAttrLayer )\n{\n    OSL_ENSURE( !mpShape,\n                \"ClippingAnimation::start(): Shape already set\" );\n    OSL_ENSURE( !mpAttrLayer,\n                \"ClippingAnimation::start(): Attribute layer already set\" );\n\n    mpShape = rShape;\n    mpAttrLayer = rAttrLayer;\n\n    ENSURE_OR_THROW( rShape,\n                      \"ClippingAnimation::start(): Invalid shape\" );\n    ENSURE_OR_THROW( rAttrLayer,\n                      \"ClippingAnimation::start(): Invalid attribute layer\" );\n\n    mpShape = rShape;\n    mpAttrLayer = rAttrLayer;\n\n    if( !mbSpriteActive )\n    {\n        mpShapeManager->enterAnimationMode( mpShape );\n        mbSpriteActive = true;\n    }\n}\n\nvoid ClippingAnimation::end()\n{\n    end_();\n}\n\nvoid ClippingAnimation::end_()\n{\n    if( mbSpriteActive )\n    {\n        mbSpriteActive = false;\n        mpShapeManager->leaveAnimationMode( mpShape );\n\n        if( mpShape->isContentChanged() )\n            mpShapeManager->notifyShapeUpdate( mpShape );\n    }\n}\n\nbool ClippingAnimation::operator()( double nValue )\n{\n    ENSURE_OR_RETURN_FALSE(\n        mpAttrLayer && mpShape,\n        \"ClippingAnimation::operator(): Invalid ShapeAttributeLayer\" );\n    \n    // set new clip\n    mpAttrLayer->setClip( maClippingFunctor( nValue,\n                                             mpShape->getDomBounds().getRange() ) );\n    \n    if( mpShape->isContentChanged() )\n        mpShapeManager->notifyShapeUpdate( mpShape );\n    \n    return true;\n}\n\ndouble ClippingAnimation::getUnderlyingValue() const\n{\n    ENSURE_OR_THROW(\n        mpAttrLayer,\n        \"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer\" );\n    \n    return 0.0;     // though this should be used in concert with \n\t\t\t\t    // ActivitiesFactory::createSimpleActivity, better\n    \t\t\t\t// explicitely name our start value.\n\t\t\t\t    // Permissible range for operator() above is [0,1]\n}\n\n} // anon namespace\n\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n    const ActivitiesFactory::CommonParameters&          rParms,\n    const AnimatableShapeSharedPtr&                     rShape,\n    const ShapeManagerSharedPtr&                        rShapeManager,\n    const ::basegfx::B2DVector&                         rSlideSize,\n    uno::Reference< animations::XTransitionFilter > const& xTransition )\n{\n    return createShapeTransition( rParms, \n                                  rShape, \n                                  rShapeManager, \n                                  rSlideSize,\n                                  xTransition, \n                                  xTransition->getTransition(), \n                                  xTransition->getSubtype() );\n}\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n    const ActivitiesFactory::CommonParameters& \t\t\t\trParms,\n    const AnimatableShapeSharedPtr& \t\t\t\t\t\trShape,\n    const ShapeManagerSharedPtr& \t\t\t\t\t\t\trShapeManager,\n    const ::basegfx::B2DVector&                             rSlideSize,\n    ::com::sun::star::uno::Reference< \n    \t::com::sun::star::animations::XTransitionFilter > const& xTransition,\n    sal_Int16               \t\t\t\t\t\t\t\tnType,\n    sal_Int16               \t\t\t\t\t\t\t\tnSubType )\n{\n    ENSURE_OR_THROW(\n        xTransition.is(),\n        \"TransitionFactory::createShapeTransition(): Invalid XTransition\" );\n    \n    const TransitionInfo* pTransitionInfo( \n        getTransitionInfo( nType, nSubType ) );\n\n    AnimationActivitySharedPtr pGeneratedActivity;\n    if( pTransitionInfo != NULL )\n    {\n        switch( pTransitionInfo->meTransitionClass )\n        {\n            default:\n            case TransitionInfo::TRANSITION_INVALID:\n                OSL_ENSURE( false, \n                            \"TransitionFactory::createShapeTransition(): Invalid transition type. \"\n                            \"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!\" );\n                return AnimationActivitySharedPtr();\n\n            \n            case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:\n            {\n                // generate parametric poly-polygon\n                ParametricPolyPolygonSharedPtr pPoly( \n                    ParametricPolyPolygonFactory::createClipPolyPolygon( \n                        nType, nSubType ) );\n            \n                // create a clip activity from that\n                pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n                    rParms,\n                    NumberAnimationSharedPtr( \n                        new ClippingAnimation( \n                            pPoly,\n                            rShapeManager,\n                            *pTransitionInfo,\n                            xTransition->getDirection(),\n                            xTransition->getMode() ) ),\n                    true );\n            }\n            break;\n        \n            case TransitionInfo::TRANSITION_SPECIAL:\n            {\n                switch( nType )\n                {\n                    case animations::TransitionType::RANDOM:\n                    {\n                        // select randomly one of the effects from the\n                        // TransitionFactoryTable\n\n                        const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );\n                        \n                        ENSURE_OR_THROW( pRandomTransitionInfo != NULL,\n                                          \"TransitionFactory::createShapeTransition(): Got invalid random transition info\" );\n\n                        ENSURE_OR_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,\n                                          \"TransitionFactory::createShapeTransition(): Got random again for random input!\" );\n\n                        // and recurse\n                        pGeneratedActivity = createShapeTransition( rParms,\n                                                                    rShape,\n                                                                    rShapeManager,\n                                                                    rSlideSize,\n                                                                    xTransition,\n                                                                    pRandomTransitionInfo->mnTransitionType,\n                                                                    pRandomTransitionInfo->mnTransitionSubType );\n                    }\n                    break;\n                \n                    // TODO(F3): Implement slidewipe for shape\n                    case animations::TransitionType::SLIDEWIPE:\n                    {\n                        sal_Int16 nBarWipeSubType(0);\n                        bool\t  bDirectionForward(true);\n\n                        // map slidewipe to BARWIPE, for now\n                        switch( nSubType )\n                        {\n                            case animations::TransitionSubType::FROMLEFT:\n                                nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n                                bDirectionForward = true;\n                                break;\n\n                            case animations::TransitionSubType::FROMRIGHT:\n                                nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n                                bDirectionForward = false;\n                                break;\n\n                            case animations::TransitionSubType::FROMTOP:\n                                nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n                                bDirectionForward = true;\n                                break;\n\n                            case animations::TransitionSubType::FROMBOTTOM:\n                                nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n                                bDirectionForward = false;\n                                break;\n\n                            default:\n                                ENSURE_OR_THROW( false,\n                                                  \"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE\" );\n                                break;\n                        }\n\n                        // generate parametric poly-polygon\n                        ParametricPolyPolygonSharedPtr pPoly( \n                            ParametricPolyPolygonFactory::createClipPolyPolygon( \n                                animations::TransitionType::BARWIPE, \n                                nBarWipeSubType ) );\n                    \n                        // create a clip activity from that\n                        pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n                            rParms,\n                            NumberAnimationSharedPtr( \n                                new ClippingAnimation( \n                                    pPoly,\n                                    rShapeManager,\n                                    *getTransitionInfo( animations::TransitionType::BARWIPE, \n                                                        nBarWipeSubType ),\n                                    bDirectionForward,\n                                    xTransition->getMode() ) ),\n                            true );\n                    }\n                    break;\n\n                    default:\n                    {\n                        // TODO(F1): Check whether there's anything left, anyway,\n                        // for _shape_ transitions. AFAIK, there are no special\n                        // effects for shapes...\n\n                        // for now, map all to fade effect\n                        pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n                            rParms,\n                            AnimationFactory::createNumberPropertyAnimation( \n                                ::rtl::OUString( \n                                    RTL_CONSTASCII_USTRINGPARAM(\"Opacity\") ),\n                                rShape, \n                                rShapeManager,\n                                rSlideSize ),\n                            xTransition->getMode() );\n                    }\n                    break;\n                }\n            }\n            break;\n        }\n    }\n\n    if( !pGeneratedActivity )\n    {\n        // No animation generated, maybe no table entry for given \n        // transition?\n        OSL_TRACE(\n            \"TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) \"\n            \"combination encountered\",\n            xTransition->getTransition(),\n            xTransition->getSubtype() );\n        OSL_ENSURE(\n            false,\n            \"TransitionFactory::createShapeTransition(): Unknown type/subtype \"\n            \"combination encountered\" );\n    }\n    \n    return pGeneratedActivity;\n}\n\n}\n}\n", "meta": {"hexsha": "0f6ff69231ff5fe29b0e93d4876e54eea9446d10", "size": 15368, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "main/slideshow/source/engine/transitions/shapetransitionfactory.cxx", "max_stars_repo_name": "jimjag/openoffice", "max_stars_repo_head_hexsha": "74746a22d8cc22b031b00fcd106f4496bf936c77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-27T19:25:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-27T19:25:34.000Z", "max_issues_repo_path": "main/slideshow/source/engine/transitions/shapetransitionfactory.cxx", "max_issues_repo_name": "ackza/openoffice", "max_issues_repo_head_hexsha": "d49dfe9c625750e261c7ed8d6ccac8d361bf3418", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-25T04:29:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-25T04:29:25.000Z", "max_forks_repo_path": "main/slideshow/source/engine/transitions/shapetransitionfactory.cxx", "max_forks_repo_name": "ackza/openoffice", "max_forks_repo_head_hexsha": "d49dfe9c625750e261c7ed8d6ccac8d361bf3418", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T00:28:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-22T06:48:49.000Z", "avg_line_length": 37.9456790123, "max_line_length": 131, "alphanum_fraction": 0.512038001, "num_tokens": 2700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.18759005164901524}}
{"text": "/**\n * @file teaset.cc\n *\n * Copyright (c) 2013 Leon Lynch\n *\n * This file is licensed under the terms of the MIT license.\n * See LICENSE file.\n */\n\n#include \"teaset.h\"\n\n#include <cstddef>\n#include <cstdio>\n\n#include <sstream>\n#include <string>\n#include <array>\n#include <vector>\n\n#include <boost/lexical_cast.hpp>\n\nextern const char teapot_geometry_str[];\nextern const char teacup_geometry_str[];\nextern const char teaspoon_geometry_str[];\n\nTeaset::~Teaset()\n{\n}\n\nstatic std::size_t readCount(std::istringstream& ss)\n{\n\tstd::string str;\n\twhile (str.empty())\n\t\tstd::getline(ss, str);\n\n\treturn boost::lexical_cast<std::size_t>(str);\n}\n\nvoid Teaset::readData(const char* data, bool data_is_ccw)\n{\n\tstd::istringstream ss(data);\n\tstd::size_t count;\n\tstd::vector<std::array<unsigned int,16>> indices;\n\tstd::vector<glm::vec3> vertices;\n\n\t// read indices\n\tcount = readCount(ss);\n\tindices.resize(count);\n\tfor (std::size_t i = 0; i < count; ++i) {\n\t\tstd::string index_str;\n\t\tstd::getline(ss, index_str);\n\n\t\tstd::sscanf(\n\t\t\tindex_str.c_str(),\n\t\t\t\"%u,%u,%u,%u,\"\n\t\t\t\"%u,%u,%u,%u,\"\n\t\t\t\"%u,%u,%u,%u,\"\n\t\t\t\"%u,%u,%u,%u\",\n\t\t\t&indices[i][0], &indices[i][1], &indices[i][2], &indices[i][3],\n\t\t\t&indices[i][4], &indices[i][5], &indices[i][6], &indices[i][7],\n\t\t\t&indices[i][8], &indices[i][9], &indices[i][10], &indices[i][11],\n\t\t\t&indices[i][12], &indices[i][13], &indices[i][14], &indices[i][15]\n\t\t);\n\t}\n\n\t// read vertices\n\tcount = readCount(ss);\n\tvertices.resize(count);\n\tfor (std::size_t i = 0; i < count; ++i) {\n\t\tstd::string vertex_str;\n\t\tstd::getline(ss, vertex_str);\n\n\t\tstd::sscanf(\n\t\t\tvertex_str.c_str(),\n\t\t\t\"%f,%f,%f\",\n\t\t\t&vertices[i][0], &vertices[i][1], &vertices[i][2]\n\t\t);\n\t}\n\n\t// lookup control points\n\tfor (auto&& index : indices) {\n\t\tBezierPatch patch;\n\n\t\tif (data_is_ccw) {\n\t\t\tfor (std::size_t i = 0; i < 16; ++i) {\n\t\t\t\tpatch.k[i/4][i%4] = vertices[index[i] - 1];\n\t\t\t}\n\t\t} else {\n\t\t\tfor (std::size_t i = 0; i < 16; ++i) {\n\t\t\t\tpatch.k[i/4][3 - (i%4)] = vertices[index[i] - 1];\n\t\t\t}\n\t\t}\n\n\t\tpatches.push_back(patch);\n\t}\n}\n\nTeapot::Teapot()\n{\n\treadData(teapot_geometry_str, false);\n}\n\nTeacup::Teacup()\n{\n\treadData(teacup_geometry_str, true);\n}\n\nTeaspoon::Teaspoon()\n{\n\treadData(teaspoon_geometry_str, true);\n}\n", "meta": {"hexsha": "4a26b82e2b485e3ecb1a75538db9b2775cd2f007", "size": 2204, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/teaset.cc", "max_stars_repo_name": "leonlynch/cortex", "max_stars_repo_head_hexsha": "239ece88de004f35ef31ad3c57fb20b0b0d86bde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-26T08:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-26T08:37:04.000Z", "max_issues_repo_path": "src/teaset.cc", "max_issues_repo_name": "leonlynch/cortex", "max_issues_repo_head_hexsha": "239ece88de004f35ef31ad3c57fb20b0b0d86bde", "max_issues_repo_licenses": ["MIT"], "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/teaset.cc", "max_forks_repo_name": "leonlynch/cortex", "max_forks_repo_head_hexsha": "239ece88de004f35ef31ad3c57fb20b0b0d86bde", "max_forks_repo_licenses": ["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.6785714286, "max_line_length": 69, "alphanum_fraction": 0.6197822142, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.18759004810785967}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\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\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// General MC for 2d materials beyond RTA\n/// The function definitions are also located in this file\n\n#include <iostream>\n#include <fstream>\n#include <structures.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/mpi.hpp>\n#include <Eigen/Dense>\n#include <collision_operator.hpp>\n#include <sstream>\n#include <sampling.hpp>\n#include <constants.hpp>\n#include <deviational_particle.hpp>\n#include <sampling.hpp>\n#include <interpolation.hpp>\n#include <exceptions.hpp>\n#include <functional>\n#include <unordered_map>\n#include <map>\n#include <pcg_random.hpp>\n#include <random>\n#if BOOST_VERSION >= 106700\n#include <boost/container_hash/hash.hpp>\n#else\n#include <boost/functional/hash.hpp>\n#endif\n#include <boost/format.hpp>\n#include <geometry_2d.hpp>\n\n#include <functional>\n#include <io_utils.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <msgpack.hpp>\n\n\n#define TBB_PREVIEW_GLOBAL_CONTROL true\n#include <tbb/concurrent_vector.h>\n#include <tbb/parallel_for.h>\n#include <tbb/parallel_for_each.h>\n#include <tbb/global_control.h>\n#include <tbb/parallel_sort.h>\n#include <tbb/enumerable_thread_specific.h>\n#include <tbb/concurrent_unordered_set.h>\n#include <tbb/concurrent_queue.h>\n#include <tbb/task_group.h>\n#include <tbb/concurrent_unordered_map.h>\n#include <mutex>\n\n///Some alias\nusing gridData = std::unordered_map<std::string,\n        std::unique_ptr<alma::Gamma_grid>>;\nusing cellData = std::unordered_map<std::string,\n        std::unique_ptr<alma::Crystal_structure>>;\n\nusing hist_type = std::vector<alma::propagator_H>;\nusing propagators = std::unordered_map<std::string,\n    std::map<double,hist_type>>;\n\n///Specialization of STD\nnamespace std {\n/// Trivial implementation of std::hash for arrays,\n/// required to create an unordered_set of arrays.\ntemplate <typename T> struct hash<std::array<T, 2>> {\n    std::size_t operator()(const array<T, 2>& key) const {\n        hash<T> backend;\n        std::size_t nruter = 0;\n\n        for (auto& e : key)\n            boost::hash_combine(nruter, backend(e));\n        return nruter;\n    }\n};\n\n} // namespace std\n\n///Computes the particle energy\n/// @param[in] grid   - phonon spectrum on a regular grid\n/// @param[in] Thot   - the maximum expected temperature\n/// @param[in] Tcold  - the minimum expected temperature\n/// @param[in] Tref   - the reference temperature of the box\n/// @param[in] volume - box_volume/unitcell_volume\n/// @param[in] nparticles - the number by which divide Eeff_box\ninline double calc_Eeff(\n    const alma::Gamma_grid&  grid, \n    double Thot, \n    double Tcold, \n    double Tref, \n    double volume,\n    std::size_t nparticles\n) {\n    \n    long double dE_hot  = 0.;\n    long double dE_cold = 0.;\n    for (std::size_t iq = 0; iq < grid.nqpoints; ++iq) {\n        auto& spectrum = grid.get_spectrum_at_q(iq);\n        for (auto im = 0; im < \n            grid.get_spectrum_at_q(0).omega.size(); ++im) {\n            if (alma::almost_equal(0., spectrum.omega(im))) \n                continue;\n            dE_hot  += 1e12 * alma::constants::hbar * spectrum.omega(im) *\n                std::abs(alma::bose_einstein(spectrum.omega(im),Thot )\n                -alma::bose_einstein(spectrum.omega(im),Tref));\n            dE_cold += 1e12 * alma::constants::hbar * spectrum.omega(im) *\n                std::abs(alma::bose_einstein(spectrum.omega(im),Tcold)\n                -alma::bose_einstein(spectrum.omega(im),Tref));\n        }\n    }\n    \n    //The max is only in case the delta in temperature is not symetrical for some weirdo reason\n    return volume*(dE_cold+dE_hot)/ grid.nqpoints / nparticles;\n}\n\n\nnamespace box_generators {\n\n///Create particles from initial distribution\n///@param[in] sys   - system boxes\n///@param[in] grids - grid data for all materials\n///@param[in] cells - cell data for all materials\n///@param[in] given_dist - the given distributions\n///@param[out] new_particles - particles generated by this generator\n///@param[in] rng   - random number generator\n///@param[in] thickness - thickness of all boxes\n///@param[in] Eff - energy of each packet\nvoid init_particles(std::vector<alma::geometry_2d>& sys,\n                    gridData& grids,\n                    cellData& cells,\n                    std::unordered_map<std::size_t,Eigen::VectorXd>& given_dist,\n                    std::vector<alma::D_particle>& new_particles,\n                    pcg64& rng,\n                    std::vector<double>& thickness,\n                    double Eff){\n    \n    new_particles.clear();\n    ///Allocate some memory\n    new_particles.reserve(\n        static_cast<std::size_t>(5.0e+6));\n    \n    if (given_dist.size()==0)\n        return;\n    \n    \n    for (auto &s : sys) {\n        ///If reservoir or peridic ignore\n        if (s.reservoir or\n            s.periodic)\n            continue;\n        \n        ///If not given ignore\n        if (given_dist.count(s.get_id()) == 0)\n            continue;\n        \n        auto mat = s.material;\n        \n        alma::ref_distribution init_dist(*(grids[mat]),\n                                            given_dist[s.get_id()],\n                                            rng);\n        \n        auto Vucell = cells.at(s.material)->V * \n                      thickness[s.get_id()]/\n                      cells.at(s.material)->lattvec(2,2);\n        \n        auto Vbox  = s.get_area() * thickness[s.get_id()];\n        \n        auto Ngen = init_dist.Ntogenerate(Vbox/Vucell,Eff);\n        \n        for (std::size_t i=0; i<Ngen; i++) {\n            Eigen::Vector2d ppos = s.get_random_point(rng);\n                    \n            auto pinfo = init_dist.sample_with_sign();\n            \n            alma::D_particle newp(ppos,\n                                std::get<1>(pinfo),\n                                std::get<0>(pinfo),\n                                std::get<2>(pinfo),\n                                0.,\n                                s.get_id());\n            \n            new_particles.push_back(newp);\n        }\n    }\n    \n    ///Free some memory\n    new_particles.shrink_to_fit();\n}\n///Creat particles at a T different from reference temperature:\n///@param[in] sys   - system boxes\n///@param[in] grids - grid data for all materials\n///@param[in] cells - cell data for all materials\n///@param[out] new_particles - particles generated by init generator \n///@param[in] rng   - random number generator\n///@param[in] thickness - thickness of all boxes\n///@param[in] Eff - energy of each packet\nvoid init_particles(std::vector<alma::geometry_2d>& sys,\n                    gridData& grids,\n                    cellData& cells,\n                    std::vector<alma::D_particle>& new_particles,\n                    pcg64& rng,\n                    std::vector<double>& thickness,\n                    double Eff){\n    \n    new_particles.clear();\n    ///Allocate some memory\n    new_particles.reserve(\n        static_cast<std::size_t>(5.0e+6));\n    \n    \n    for (auto &s : sys) {\n        ///If reservoir or peridic ignore\n        if (s.reservoir or\n            s.periodic)\n            continue;\n        \n        ///If init temperature and reference one are equal continue\n        if (alma::almost_equal(s.Teq,s.Treal))\n            continue;\n        \n        auto mat = s.material;\n        \n        alma::outTref_distribution init_dist(*(grids[mat]),\n                                            s.Treal,\n                                            s.Teq,\n                                            rng);\n        \n        auto Vucell = cells.at(s.material)->V * \n                      thickness[s.get_id()]/\n                      cells.at(s.material)->lattvec(2,2);\n        \n        auto Vbox  = s.get_area() * thickness[s.get_id()];\n        \n        auto Ngen = init_dist.Ntogenerate(Vbox/Vucell,Eff);\n        \n        for (std::size_t i=0; i<Ngen; i++) {\n            Eigen::Vector2d ppos = s.get_random_point(rng);\n                    \n            auto pinfo = init_dist.sample_with_sign();\n            \n            alma::D_particle newp(ppos,\n                                std::get<1>(pinfo),\n                                std::get<0>(pinfo),\n                                std::get<2>(pinfo),\n                                0.,\n                                s.get_id());\n            \n            new_particles.push_back(newp);\n        }\n    }\n    \n    \n    ///Free some memory\n    new_particles.shrink_to_fit();\n}\n    \n    \n///Create the particles in the adiabatic diffuse walls\n///@param[in] sys   - system boxes\n///@param[in] grids - grid data for all materials\n///@param[in] cells - cell data for all materials\n///@param[out] new_particles - particles generated by adiabatic diffuse walls\n///@param[in] rng   - random number generator\n///@param[in] thickness - thickness of all boxes\n///@param[in] dt - timestep\n///@param[in] Eff - energy of each packet\nvoid adiabatic_diffuse_walls(std::vector<alma::geometry_2d>& sys,\n                             gridData& grids,\n                             cellData& cells,\n                             std::vector<alma::D_particle>& new_particles,\n                             pcg64& rng,\n                             std::vector<double>& thickness,\n                             double dt,\n                             double Eff\n){\n    new_particles.clear();\n    new_particles.reserve(100*sys.size());\n    \n    ///Generate temperature list\n    static std::vector<double> Ts;\n    if (Ts.empty()){\n        Ts.reserve(100);\n        for (auto i=0; i<100;i++){\n            Ts.push_back(10.0+10.0*i);\n        }\n    }\n    \n    \n    ///Interpolator to get border temperature\n    static std::unordered_map<std::array<std::size_t,2>,\n            alma::CubicSpline1D> bTinterpolator;\n    \n    ///Iterate through all system\n    ///to build wall generators\n    for (auto &s : sys) {\n        ///If periodic or reservoir ignore\n        if (s.reservoir or s.periodic)\n            continue;\n        std::size_t iborder = 0;\n        \n        auto& borders = s.get_borders();\n        \n        for (auto &b : borders) {\n            \n            std::array<std::size_t,2> genID = \n                    {s.get_id(),iborder};\n                    \n            ///This means is the first time we pass by\n            ///we generate an interpolator of J vs Twall\n            if (bTinterpolator.count(genID)==0) {\n                b.Tboxeq = s.Teq;\n                \n                Eigen::VectorXd J(Ts.size()),\n                    Tvec(Ts.size());\n                \n                for (std::size_t tind = 0; tind < Ts.size();\n                    tind++) {\n                    \n                    Tvec(tind) = Ts[tind];\n                    Eigen::Vector3d nwall;\n                    nwall <<  -b.np(0), -b.np(1), 0.;\n                    alma::Isothermal_wall_distribution \n                        myGenWall(*(grids.at(s.material)),Ts[tind],s.Teq,\n                                  nwall,rng);\n                    \n                    ///Calculating the flux\n                    J(tind) =\n                        myGenWall.get_flux(cells.at(s.material)->V * \n                            thickness[s.get_id()]/\n                            cells.at(s.material)->lattvec(2,2));\n                }\n                ///Generating interpolator\n                alma::CubicSpline1D c(J,Tvec);\n                ///Creating map entry\n                \n                bTinterpolator[genID] = c; \n            }\n            \n            ///If change the equilibrium\n            ///reconstruct \n            if (b.Tboxeq!=s.Teq) {\n                b.Tboxeq = s.Teq;\n                ///If b is different from 0\n                ///build up generator\n                \n                Eigen::VectorXd J(Ts.size()),\n                    Tvec(Ts.size());\n                \n                for (std::size_t tind = 0; tind < Ts.size();\n                    tind++) {\n                    Tvec(tind) = Ts[tind];\n                    Eigen::Vector3d nwall;\n                    nwall <<  -b.np(0), -b.np(1), 0.;\n                    alma::Isothermal_wall_distribution \n                        myGenWall(*(grids.at(s.material)),Ts[tind],s.Teq,\n                                  nwall,rng);\n                    \n                    ///Calculating the flux\n                    J(tind) =\n                        myGenWall.get_flux(cells.at(s.material)->V * \n                            thickness[s.get_id()]/\n                            cells.at(s.material)->lattvec(2,2)\n                        );\n                }\n                ///Generating interpolator\n                alma::CubicSpline1D c(J,Tvec);\n                ///Modify map entry\n                bTinterpolator[genID] = c; \n            }\n            \n            ///If the border has a flux\n            ///add the particles\n            \n            if (b.Eborder != 0) {\n                ///We calculate the flux\n                ///from particle count\n                \n                ///std::cout << \"# border \" << iborder << std::endl;\n                double Jborder = Eff *\n                    b.Eborder / dt /\n                    (b.get_length()*thickness[s.get_id()]);\n                ///border temperature\n                double Tborder = \n                    bTinterpolator[genID].Interpolate(\n                    Jborder);\n                ///Building generator from \n                ///interpolated temperature\n                Eigen::Vector3d nwall;\n                nwall <<  -b.np(0), -b.np(1), 0.;\n                alma::Isothermal_wall_distribution\n                    myWallGen(*(grids.at(s.material)),Tborder,s.Teq,\n                              nwall,rng);\n                \n                \n                ///Genrating particles the number is\n                ///the same than incident particles\n                std::size_t Ng = (std::abs(b.Eborder) + 1.0e-6);\n                \n                for (std::size_t Ni=0; Ni<Ng; Ni++){\n                    \n                    Eigen::Vector2d ppos = b.get_random_point(rng);\n                    \n                    auto pinfo = myWallGen.sample_with_sign();\n                    \n                    alma::D_particle newp(ppos,\n                                        std::get<1>(pinfo),\n                                        std::get<0>(pinfo),\n                                        std::get<2>(pinfo),\n                                        0.,\n                                        s.get_id());\n                    \n                    new_particles.push_back(newp);\n                }\n                \n                b.Eborder = 0;\n            }\n            \n            iborder++;\n        }\n    }\n}\n\n///@param[in] sys   - system boxes\n///@param[in] grids - grid data for all materials\n///@param[in] cells - cell data for all materials\n///@param[out] new_particles - particles generated by adiabatic diffuse walls\n///@param[in] rng   - random number generator\n///@param[in] thickness - thickness of all boxes\n///@param[in] dt - timestep\n///@param[in] Eff - energy of each packet\n///@param[in] clear - if clear data\nvoid Isothermal_walls(std::vector<alma::geometry_2d>& sys,\n                             gridData& grids,\n                             cellData& cells,\n                             std::vector<alma::D_particle>& new_particles,\n                             pcg64& rng,\n                             std::vector<double>& thickness,\n                             double dt,\n                             double Eff,\n                             bool   clear = false\n){\n    ///Make some room for the new particles\n    new_particles.clear();\n    new_particles.reserve(1000*sys.size());\n    \n    static std::vector<double> oldT; \n    static std::unordered_map<std::array<std::size_t,2>,std::pair<\n    alma::Isothermal_wall_distribution,\n        alma::geom2d_border>> isogens;\n    \n    if (oldT.empty()) {\n        for (auto s : sys)\n            oldT.push_back(s.Teq);\n    }\n    \n    ///Iterate through system\n    for (auto &s : sys) {\n        ///If not reservoir ignore\n        if (!s.reservoir)\n            continue;\n        ///Retrive material and box id\n        auto smat = s.material;\n        auto sid  = s.get_id();\n        \n        ///Iterate through contacts:\n        ///This is done each timestep\n        ///only in case we need to recalculate\n        ///the generator\n        for (auto &[c,b] : s.get_contacts()){\n            \n            if (sys[c].reservoir or sys[c].periodic)\n                continue;\n            \n            if (alma::almost_equal(b[0].get_length(),0.))\n                continue;\n            \n            if (sys[c].material != smat) {\n                throw  alma::input_error(\n                    \"Injection from material A to B \"\n                    \"is not allowed\\n\");\n            }\n            ///Do not waste time if no particles need to be injected\n\t    if (alma::almost_equal(s.Teq,sys[c].Teq))\n\t        continue;\n            \n            std::array<std::size_t,2> ids =\n                {sid,c};\n            ///If there is change in\n            ///reservoir or box reference\n            ///temperature or at the first\n            ///pass create generator\n            if (isogens.count(ids) == 0. or \n                oldT[sid] != s.Teq       or\n                oldT[c] != sys[c].Teq) {\n                \n                Eigen::Vector3d nw;\n                nw << b[0].np(0) , b[0].np(1), 0; \n                \n                alma::Isothermal_wall_distribution\n                    igen(*(grids.at(smat)),\n                        s.Teq,\n                        sys[c].Teq,\n                        nw,\n                        rng);\n                    \n                isogens[ids] = std::make_pair(\n                    igen,b[0]);\n            }\n        }//contacts loop\n    }\n    \n    ///Iterate through\n    ///generators to\n    ///insert particles\n    for (auto &[ids,G] : isogens){\n        auto idr  = ids[0];\n        auto idi  = ids[1];\n        auto mat  = sys[idr].material;\n        auto& gen = G.first;\n        auto b    = G.second;\n        auto Lb   = b.get_length(); \n        \n        auto spf = Lb*thickness[idr]/\n            (cells.at(mat)->V * thickness[idr]/\n            cells.at(mat)->lattvec(2,2));\n        \n        auto Ngen = gen.Ntogenerate(dt,\n                       spf,Eff);\n        \n        ///As contact must insert in same material\n        for (std::size_t ni=0; ni<Ngen; ni++) {\n            Eigen::Vector2d ppos = b.get_random_point(rng);\n            \n            //Sanity check\n            //if that fails is due to\n            //numerical errors:\n            if (!sys[idi].inside(ppos)) {\n                auto d =\n                    sys[idi].get_center() - ppos;\n                ppos += 1.0e-6*d/d.norm();\n                if (!sys[idi].inside(ppos)) {\n                    throw alma::geometry_error(\n                        \"Generated particle \"\n                        \"out of insertion box\\n\");\n                }\n            }\n            \n            \n            auto pinfo = gen.sample_with_sign();\n            \n            alma::D_particle newp(ppos,\n                                std::get<1>(pinfo),\n                                std::get<0>(pinfo),\n                                std::get<2>(pinfo),\n                                0.,\n                                idi);\n            \n            new_particles.push_back(newp);\n        }\n        \n    }\n    \n    ///Update oldT;\n    for (auto s : sys)\n        oldT.push_back(s.Teq);\n    \n    if (clear) {\n        oldT.clear();\n        isogens.clear();\n    }\n}\n\n///@param[in] sys   - system boxes\n///@param[in] grids - grid data for all materials\n///@param[in] cells - cell data for all materials\n///@param[out] new_particles - particles generated by adiabatic diffuse walls\n///@param[in] rng   - random number generator\n///@param[in] thickness - thickness of all boxes\n///@param[in] dt - timestep\n///@param[in] Eff - energy of each packet\n///@param[in] calc_gradients - should we calculate gradients\n///@param[in] gradients - the gradients\nvoid source_term_gradient(\n    std::vector<alma::geometry_2d>& sys,\n                             gridData& grids,\n                             cellData& cells,\n                             std::vector<alma::D_particle>& new_particles,\n                             pcg64& rng,\n                             std::vector<double>& thickness,\n                             double dt,\n                             double Eff,\n                             bool   calc_gradients,\n                             Eigen::MatrixXd& gradients\n){\n    \n    ///If we want to calculate gradients\n    ///each timestep\n    if (calc_gradients)\n        gradients = calculate_gradientT(sys);\n    \n    auto nboxes = sys.size();\n    \n    static std::unordered_map<std::size_t,\n    alma::Nabla_T_distribution> gradient_generators;\n    static std::vector<double> ograd_data;\n    if (ograd_data.empty()) {\n        for (auto i=0;i<gradients.size();i++)\n            ograd_data.push_back(\n                gradients.data()[i]); \n    }\n    \n    Eigen::MatrixXd oldgradients(gradients);\n    \n    for (std::size_t i = 0; i< nboxes; i++) {\n        auto mat = sys[i].material;\n        Eigen::Vector3d boxGrad = \n            gradients.col(i);\n        Eigen::Vector3d oldboxGrad = \n            oldgradients.col(i);\n        if (alma::almost_equal(boxGrad.norm(),0.))\n            continue;\n        \n        ///If gradient do not change\n        ///and the generator\n        ///was already created ignore\n        if (alma::almost_equal((boxGrad-\n            oldboxGrad).norm(),0) and \n            gradient_generators.count(i)==1)\n            continue;\n        \n        alma::Nabla_T_distribution myGradGen(*(grids[mat]),\n                            boxGrad,sys[i].Teq,rng);\n        gradient_generators.emplace(std::make_pair(i,myGradGen));\n    };\n    \n    ///Here we will generate the new particles:\n    new_particles.clear();\n    for (auto &[igen,gen] : gradient_generators){\n        auto mat   = sys[igen].material;\n        auto myvol = sys[igen].get_area()*thickness[igen]/\n        (cells[mat]->V*thickness[igen]/cells[mat]->lattvec(2,2));\n        auto N2gen = gen.Ntogenerate(dt,myvol,Eff);\n        \n        for (std::size_t ip = 0; ip < N2gen; ip++) {\n            Eigen::Vector2d ppos = sys[igen].get_random_point(rng);\n            auto pinfo = gen.sample_with_sign();\n            alma::D_particle newp(ppos,\n                            std::get<1>(pinfo),\n                            std::get<0>(pinfo),\n                            std::get<2>(pinfo),\n                            0.,\n                            igen);\n            new_particles.push_back(newp);\n        }\n    }\n    \n    \n    \n    ///Updating gradients data\n    for (auto i=0;i<gradients.size();i++)\n        ograd_data[i] = gradients.data()[i]; \n}\n};\n\n///Get v:\n///We need to clean v values of small values\n///@param[in] grid - qpoint grid\n///@param[in] ib   - band index\n///@param[in] iq   - qpoint index\n///@return    phonon group velocity\ninline Eigen::Vector2d get_v(const alma::Gamma_grid&  grid,\n                             std::size_t ib,\n                             std::size_t iq) {\n    \n    Eigen::Vector3d v3 = grid.get_spectrum_at_q(iq).vg.col(ib);\n    Eigen::Vector2d v2;\n    v2 << v3(0) , v3(1);\n    for (auto i=0; i<2;i++) {\n        if (alma::almost_equal(v2(i),0.))\n            v2(i) = 0.;\n    }\n    \n    return v2;\n}\n\n///Particle evolution:\n///@param[in,out] particle - deviational particle to evolve\n///@param[in] v        - particle velocity\n///@param[in] sys      - geometry and box info\n///@param[in] dt       - time to evolve\n///@param[in] rnd     - random generator\n///@param[in] pmutex  - mutex\n///@param[in] Novoid  - flag to print info\ntemplate <class Random,class Mutex>\nvoid evolparticle(alma::D_particle& particle,\n                  Eigen::Vector2d& v,\n                  std::vector<alma::geometry_2d>& sys,\n                  double dt,\n                  Random& rnd,\n                  Mutex& pmutex){\n    ///particle mutex\n    ///to make function thread safe\n    ///Save original vector\n    Eigen::Vector2d opos(particle.pos);\n    \n    ///Check if in reservoir\n    if (sys[particle.boxid].reservoir) {\n        ///Set to be deleted\n        particle.q = 0;\n        particle.alpha = 0;\n        return;\n    }\n    \n    ///Apply PBC\n    if (sys[particle.boxid].periodic) {\n        //pmutex.lock();\n        auto PBCsol = \n            sys[particle.boxid].translate(opos,v,sys,rnd);\n        //pmutex.unlock();\n        \n        particle.boxid = PBCsol.first;\n        particle.pos   = PBCsol.second;\n    }\n    \n    \n    Eigen::Vector2d rnew = \n        particle.pos + dt*v;\n        \n    ///Check if inside the same box:\n    \n    if (sys[particle.boxid].inside(rnew)) {\n        \n        if (sys[particle.boxid].periodic){\n            std::cout << \"Periodic boxes do not exist\\n\";\n            std::cout << \"r0\\n\" << opos << std::endl;\n            std::cout << \"rf\\n\" << rnew << std::endl;\n            std::cout << \"dt \"  << dt << std::endl;\n            std::cout << particle.pos << std::endl;\n            std::cout << \"v\\n\" << v << std::endl; \n            throw alma::geometry_error(\"Peridic error\\n\");\n        }\n        \n        particle.pos = rnew;\n        return;\n    }\n    \n    ///Check the place it left\n    Eigen::Vector2d rp;\n    rp << particle.pos(0),particle.pos(1);\n    \n    ///Here we calculate where the particle is\n    ///going out\n    std::tuple<double,\n        Eigen::Vector2d,\n        std::vector<int>> MRU_sol; \n    \n    try {\n        MRU_sol = \n        sys[particle.boxid].get_inter_side(rp,v,dt);\n    }\n    catch (const alma::geometry_error& geomerror) {\n       Eigen::Vector2d d = \n            sys[particle.boxid].get_center() -\n            opos;\n       particle.pos += 1.0e-6*d/d.norm();\n       evolparticle(particle,v,sys,\n                    dt,rnd,pmutex);\n       return;\n    }\n    \n    if (std::get<0>(MRU_sol) < 0) {\n        throw alma::geometry_error(\"Error in kinematics\\n\");\n        exit(EXIT_FAILURE);\n    }\n    ///Calculating leftime\n    double left_time = dt - std::get<0>(MRU_sol);\n    if (alma::almost_equal(left_time,0.)){\n        left_time = 0.;\n    }\n    rnew = std::get<1>(MRU_sol);\n\n    decltype(rnew) reps = rnew + 1.0e-6 * v/v.norm();\n    \n    \n    ///Get contact boxes\n    std::set<std::size_t> cboxes;\n    for (auto &[ibc,border] :  \n        sys[particle.boxid].get_contacts()){\n        cboxes.insert(ibc);\n    }\n    \n    ///Check possible boxes to assign:\n    std::vector<std::size_t> pboxes;\n    \n    for (auto test : cboxes) {\n        if (test==particle.boxid) {\n            continue;\n        }\n        \n        auto border_contact = sys[particle.boxid].get_contacts()[test];\n        ///If going along border we do not change\n        bool parallel = alma::almost_equal((border_contact[0].np).dot(v),0.);\n        \n        bool oriented = ((border_contact[0].np).dot(v) > 0.);\n        \n        if ((sys[test].inside(rnew) or sys[test].inside(reps) )\n             and !parallel and oriented) {\n            pboxes.push_back(test);\n        }\n    }\n    \n    ///If going inside the void\n    if (pboxes.size()==0) {\n        ///Check if three or more\n        auto corner_problem = \n            in_corner3(rnew,sys);\n        \n        if (corner_problem.first){\n            //pmutex.lock();\n            auto csol = \n                correct_corner_problem(\n                        rnew,\n                        v,\n                        sys,\n                        corner_problem.second,\n                        rnd);\n            //pmutex.unlock();\n            particle.boxid = csol.first;\n            particle.pos = rnew;\n            \n            \n            sys[particle.boxid].add_border_Eborder(csol.second,\n                            static_cast<int>(particle.sign));\n            \n            ///Set to be deleted\n            particle.q = 0;\n            particle.alpha = 0;\n        }\n        else {\n            std::size_t iborder;\n            auto iborders = std::get<2>(MRU_sol);\n            \n            if (iborders.size() > 1) {\n                ///We first check the borders\n                ///that touch void\n                std::vector<std::size_t> voidborders;\n                \n                for (auto &tvb : iborders) {\n                    auto& mb = \n                        sys[particle.boxid].get_border(tvb);\n                    \n                    Eigen::Vector2d rc = \n                        rnew + 1.0e-4*mb.np;\n                    \n                    bool isvoid = true;\n                    for (auto &cb :  cboxes) {\n                        if (sys[cb].inside(rc)) {\n                            isvoid = false;\n                            break;\n                        }\n                    }\n                    \n                    if (isvoid) {\n                        voidborders.push_back(tvb);\n                    }\n                }\n                \n                if (voidborders.empty()) {\n                    throw alma::geometry_error(\"Error in void borders\\n\");\n                }\n                \n                //In the case two borders pointing at void\n                iborder = *(alma::choose(voidborders.begin(),\n                                       voidborders.end(),rnd));\n            }\n            else {\n                iborder = iborders[0];\n            }\n\n            sys[particle.boxid].add_border_Eborder(iborder,\n                            static_cast<int>(particle.sign));\n            ///Set to be deleted\n            particle.q = 0;\n            particle.alpha = 0;\n        }\n        \n        return;\n    }\n    else if (pboxes.size() == 1) {\n        ///Change material\n        if (sys[particle.boxid].material != \n            sys[pboxes[0]].material){\n            throw alma::geometry_error(\"Error not implemented\");\n        }\n        \n        \n        particle.boxid = pboxes[0];\n        \n        if (cboxes.find(particle.boxid)==cboxes.end()) {\n            throw alma::geometry_error(\"Teleport is not allowed\");\n        }\n        particle.pos    = rnew;\n\n        evolparticle(particle,v,sys,\n                     left_time,rnd,pmutex);\n        return;\n    }\n    else {\n        std::vector<std::size_t> pbox2;\n        \n        double tau = 1.0e-6;\n        while (true) {\n            Eigen::Vector2d rcheck = rnew + \n            tau*v;\n            \n            for (auto &PB :  pboxes) {\n                if (sys[PB].inside(rcheck)) {\n                    pbox2.push_back(PB);\n                }\n            }\n            \n            if (pbox2.empty()) {\n                tau /= 10.0;\n                if (tau < 1.0e-15) {\n                    Eigen::Vector2d d = \n                    sys[particle.boxid].get_center() -\n                    rnew;\n                    particle.pos = rnew + 1.0e-6*d/d.norm();\n                    evolparticle(particle,v,sys,\n                            left_time,rnd,pmutex);\n                    return;\n                }\n            }\n            else {\n                break;\n            }\n        }\n        \n        particle.boxid = *(alma::choose(pbox2.begin(),\n                                      pbox2.end(),rnd));\n        \n        if (cboxes.find(particle.boxid)==cboxes.end()) {\n            throw alma::geometry_error(\"Teleport is not allowed\");\n        }\n        particle.pos = rnew;\n        evolparticle(particle,v,sys,\n                     left_time,rnd,pmutex);\n        \n        return;\n    }\n    \n    \n    throw alma::geometry_error(\"This point should not be reached\");\n    \n    return;\n}\n\n///RTA Scattering \n///Scattering\n///@param[in,out] particle - deviational particles to scatter\n///@param[in] sys      - geometry and box info\n///@param[in] grids     - qgrid data for each material\n///@param[in] cells   - cells data for each material\n///@param[in] processes_map - map to vector with processes\n///@param[in] dt      - time step [ps]\n///@param[in] rng     - random number generator\n///@param[in] pmutex  - mutex\n///@param[in] world   - communicator\nvoid ScatteringRTA(std::vector<alma::D_particle>& particles,\n                std::vector<alma::geometry_2d>& sys,\n                gridData& grids,\n                cellData& cells,\n                std::unordered_map<std::string, \n                    std::unique_ptr<std::vector<alma::Threeph_process>>>& processes_map,\n                double dt,\n                tbb::enumerable_thread_specific<pcg64>& rng,\n                std::mutex& smutex,\n                boost::mpi::communicator& world\n                ){\n    static tbb::enumerable_thread_specific<\n            std::unordered_map<std::string,Eigen::ArrayXXd>> w0;\n    static tbb::enumerable_thread_specific<\n            std::unordered_map<std::string,alma::BE_derivative_distribution>>\n            material_sampler;\n        \n    tbb::concurrent_vector<alma::D_particle> newelements;\n    newelements.reserve(static_cast<std::size_t>(\n        particles.size()));\n        tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particles.size()),\n                          [&](tbb::blocked_range<std::size_t> ir) {\n        for (auto i=ir.begin(); i<ir.end();i++){\n            ///Scatter particle i\n            alma::D_particle p(particles[i]);\n            ///Material\n            auto ibox   = p.boxid;\n            auto mat    = sys[p.boxid].material;\n            //auto nbands = static_cast<std::size_t>(\n            //    grids[mat]->\n            //    get_spectrum_at_q(0).omega.size());\n            \n            auto iq       = p.q;\n            auto ib       = p.alpha;\n            \n            if (sys[ibox].reservoir or sys[ibox].periodic) {\n                std::cout << p.pos << std::endl;\n                std::cout << p.boxid << std::endl;\n                std::cout << p.q << '\\t' << p.alpha << std::endl;\n                std::cout << grids[mat]->get_spectrum_at_q(p.q).vg.col(p.alpha) << std::endl;\n                exit(EXIT_FAILURE);\n            }\n            \n            \n            ///If not present calculate\n            if (w0.local().count(mat+std::to_string(sys[ibox].Teq)) == 0) {\n                Eigen::ArrayXXd w3(\n                alma::calc_w0_threeph(*(grids[mat]), *(processes_map[mat]), sys[ibox].Teq, world));\n                auto twoph_processes = alma::find_allowed_twoph(*(grids[mat]), world);\n                Eigen::ArrayXXd w2(\n                    alma::calc_w0_twoph(*(cells[mat]), *(grids[mat]), twoph_processes, world));\n                w0.local()[mat+std::to_string(sys[ibox].Teq)] = w3 + w2;\n                material_sampler.local()[mat+std::to_string(sys[ibox].Teq)] = \n                    alma::BE_derivative_distribution(\n                    *(grids[mat]), w0.local()[mat+std::to_string(sys[ibox].Teq)], sys[ibox].Teq, rng.local());\n            }\n            \n            double my_w0 = w0.local()[mat+std::to_string(sys[ibox].Teq)](ib,iq);\n            auto R        = std::uniform_real_distribution(0., 1.)(rng.local());\n            bool scatter  = R < (1 - std::exp(-my_w0*dt));  \n            if (!scatter) {\n                newelements.push_back(p);\n            }\n            else {\n                ///Scatter\n                auto new_mode = material_sampler.local().at(mat+\n                    std::to_string(sys[ibox].Teq)).sample();\n                p.q     = new_mode[1];\n                p.alpha = new_mode[0];\n                newelements.push_back(p);\n            }\n        }\n    });\n    \n    ///Storing to STL vector\n    particles.clear();\n    particles.reserve(newelements.size());\n    particles.assign(newelements.begin(),\n                     newelements.end());\n}\n\n\n\n///Scattering\n///@param[in,out] particle - deviational particles to scatter\n///@param[in] sys      - geometry and box info\n///@param[in] modes_histo - histograms for scattering\n///@param[in] grids     - qgrid data for each material\n///@param[in] rng     - random number generator\n///@param[in] pmutex  - mutex\nvoid Scattering(std::vector<alma::D_particle>& particles,\n                std::vector<alma::geometry_2d>& sys,\n                propagators& modes_histo,\n                gridData& grids,\n                tbb::enumerable_thread_specific<pcg64>& rng,\n                std::mutex& smutex\n               ){\n    ///Random generators are by \n    ///means of their internal state\n    ///thread unsafe. Consequenty we are\n    ///protecting it with mutex\n    \n    ///tbb concurrent vector with new additions\n    ///In first iteration it have particles size\n    tbb::concurrent_vector<alma::D_particle> \n        elements;\n    elements.reserve(particles.size());\n    elements.assign(particles.begin(),\n                    particles.end());\n    \n    ///output vector (reserving enough space for each):\n    tbb::concurrent_vector<alma::D_particle> \n        outputvector;\n    outputvector.reserve(static_cast<std::size_t>(\n        2*particles.size()));\n    \n    ///Exit when no further elements are left\n    ///to process\n    while(!elements.empty()) {\n        tbb::concurrent_vector<alma::D_particle> \n            newelements;\n        newelements.reserve(2*elements.size());\n        tbb::parallel_for(tbb::blocked_range<std::size_t>(0, elements.size()),\n                          [&](tbb::blocked_range<std::size_t> ir) {\n        for (auto i=ir.begin(); i<ir.end();i++){\n            ///Scatter particle i\n            alma::D_particle p(elements[i]);\n            ///Material\n            auto ibox   = p.boxid;\n            auto mat    = sys[p.boxid].material;\n            auto nbands = static_cast<std::size_t>(\n                grids[mat]->\n                get_spectrum_at_q(0).omega.size());\n            \n            auto iq       = p.q;\n            auto ib       = p.alpha;\n            auto isign    = static_cast<double>(p.sign);\n            auto imode    = iq*nbands + ib;\n            \n            if (sys[ibox].reservoir or sys[ibox].periodic) {\n                std::cout << p.pos << std::endl;\n                std::cout << p.boxid << std::endl;\n                std::cout << p.q << '\\t' << p.alpha << std::endl;\n                std::cout << grids[mat]->get_spectrum_at_q(p.q).vg.col(p.alpha) << std::endl;\n                exit(EXIT_FAILURE);\n            }\n            \n            ///Check if in map if not try to interpolate\n            std::shared_ptr<alma::propagator_H> myP;\n            if (modes_histo[mat].count(sys[ibox].Teq)==1){\n                ///The deleter is designed to do nothing\n                ///as we dont want the data to be deleted\n                myP.reset(&(modes_histo[mat][sys[ibox].Teq][imode]),\n                          [](alma::propagator_H*){});\n            }\n            else {\n                ///Interpolate the propagator\n                auto m1 = modes_histo[mat].lower_bound(\n                    sys[ibox].Teq);\n                \n                auto Tlow = modes_histo[mat].lower_bound(0.)->first;\n                \n                auto T1 = m1->first;\n                auto m2 = m1;\n                std::advance(m2,1);\n                if (m2 != modes_histo[mat].end() and \n                    sys[ibox].Teq >= Tlow) {\n                    \n                    auto T2 = m2->first;\n                    \n                    myP =   std::make_shared<alma::propagator_H>(\n                            alma::lirp(modes_histo[mat][T1][imode],\n                                     modes_histo[mat][T2][imode],\n                                     T1,\n                                     T2,\n                                     sys[ibox].Teq));\n                }\n                else{\n                    std::cerr << \"Extrapolation is not allowed\" << std::endl;\n                    std::cerr << \"Limit Tref between the min and max temperatures\\n\";\n                    std::cerr << \"used in Propagator calculation\\n\" << std::endl;\n                    exit(EXIT_FAILURE);\n                }\n            }\n            \n            \n            \n            //smutex.lock();\n            auto R        = std::uniform_real_distribution(0., 1.)(rng.local());\n            //smutex.unlock();\n            \n            try {\n                auto solution = myP->get(R);\n                \n                auto newq    = solution.second / nbands;\n                auto newb    = solution.second % nbands;\n                \n                int newsign  = (isign*solution.first) < 0 ? -1 : 1;\n                \n                alma::D_particle s1(p);\n                s1.q       = newq;\n                s1.alpha   = newb;\n                s1.sign    = alma::get_particle_sign(newsign);\n                outputvector.push_back(s1);\n                \n                ///If the particle sign changes we add two p-like particles \n                if (newsign*isign < 0.) {\n                    newelements.push_back(p);\n                    newelements.push_back(p);\n                }\n            }\n            catch (const std::out_of_range) {\n                std::cout << \"This particle should be deleted\" << std::endl;\n                std::cout << iq << '\\t' << ib << std::endl;\n                exit(EXIT_FAILURE);\n            }\n        }\n        });\n        ///Getting elements left to process\n        std::swap(elements,newelements);\n    }\n    \n    ///Storing to STL vector\n    particles.clear();\n    particles.reserve(outputvector.size());\n    particles.assign(outputvector.begin(),\n                     outputvector.end());\n}\n\n///Delete particles\n///@param[in,out] particles - list with particles to clean out\nvoid delete_particles(std::vector<alma::D_particle>& particles) {\n    particles.erase(std::remove_if(particles.begin(), particles.end(), \n                    [&](const alma::D_particle& p)->bool {\n                        return (p.q==0 and p.alpha==0);\n                    }\n    ),particles.end());\n}\n\n\n\ntemplate <class Iterator>\nIterator search_Dparticle(Iterator first, Iterator last, std::size_t b, std::size_t q, int sign,std::size_t ibox) {\n    Eigen::Vector3d pos;\n    alma::D_particle search_particle(pos,q,b,alma::get_particle_sign(sign),0.,ibox);\n    return std::lower_bound(first,last,search_particle,std::less<alma::D_particle>());\n}\n\n///Parameters of input file\nstruct input_parameters {\n    ///Gradient\n    bool calc_gradients = true;\n    Eigen::Vector2d homoGradient;\n    Eigen::MatrixXd gradients;\n    \n    ///Geometry\n    std::vector<alma::geometry_2d>\n        system;\n    \n    ///Time\n    double dt , maxtime;\n    ///Material data\n    cellData system_cell;\n    gridData system_grid;\n    propagators system_P;\n    \n    ///Energy factor:\n    std::size_t Efactor;\n    double Edeviational = -1.;\n    ///Vector of thickness\n    std::vector<double>\n        thicknesses;\n    \n    ///Some optional stuff\n    double Tmax = 0,Tmin = 0;\n    \n    ///Init distribution info\n    std::unordered_map<std::size_t,Eigen::VectorXd> init_distribution;\n    \n    ///Information if RTA\n    bool RTA = false;\n    std::unordered_map<std::string,\n         std::unique_ptr<std::vector\n         <alma::Threeph_process> >> processes_map; \n};\n\n\ninline Eigen::VectorXd get_column(std::string name,int col) {\n    std::ifstream ifile;\n    ifile.open(name);\n    std::string line;\n    \n    std::vector<double> f_;\n    \n    while(std::getline(ifile,line)){\n        ///Ignore commented lines\n        if (line.find(\"#\")!=std::string::npos)\n            continue;\n        auto sline = alma::tokenize_homogeneous_line<double>(line,\"\\t\");\n        f_.push_back(sline[col]);\n    }\n    \n    \n    Eigen::VectorXd f = Eigen::Map<Eigen::VectorXd>(f_.data(), f_.size());\n    \n    ifile.close();\n    \n    return f;\n}\n\n\n\n///This reads the input file\n///@param[in] filename - input filename with path\n///@param[in] world    - mpi communicator\n///@return structure with input parameters\ninput_parameters \nprocess_input(std::string& filename,\n              boost::mpi::communicator& world\n){\n    // Create empty property tree object\n    boost::property_tree::ptree tree;\n\n    // Parse XML input file into the tree\n    boost::property_tree::read_xml(filename, tree);\n    \n    input_parameters inpars;\n    ///Map to store thickness\n    std::map<std::string,double> zmap;\n    \n    ///TODO: interface stuff\n    for (const auto& v : tree.get_child(\"beRTAMC2D\")) {\n        ///Reading geometry\n        if (v.first == \"geometry\") {\n            std::string gfname = \n                alma::parseXMLfield<std::string>(v, \"file\");\n            inpars.system = \n                alma::read_geometry_XML(gfname);\n        }\n        if (v.first == \"time\"){\n            inpars.dt = \n                alma::parseXMLfield<double>(v, \"dt\");\n            inpars.maxtime = \n                alma::parseXMLfield<double>(v, \"maxtime\");\n        }\n        if (v.first == \"gradient\") {\n            inpars.calc_gradients = false;\n            inpars.homoGradient(0) =\n               alma::parseXMLfield<double>(v, \"x\");\n            inpars.homoGradient(1) =\n               alma::parseXMLfield<double>(v, \"y\");\n        }\n        if (v.first == \"material\") {\n            std::string name = \n                alma::parseXMLfield<std::string>(v, \"name\");\n            std::string hdf5file = \n                alma::parseXMLfield<std::string>(v, \"database\");\n            double zsize = \n                alma::parseXMLfield<double>(v, \"thickness\");\n            auto data = \n                alma::load_bulk_hdf5(hdf5file.c_str(), world);\n            inpars.system_cell[name] = \n                std::move(std::get<1>(data));\n            inpars.system_grid[name] = \n                std::move(std::get<3>(data));\n            \n            inpars.processes_map[name] = \n                std::move(std::get<4>(data));\n            \n            zmap[name] = zsize;\n            std::map<double,hist_type> histoByT;\n            \n            ///Now reading the propagators\n            for (auto it = v.second.begin(); it != v.second.end(); it++) {\n                if (it->first == \"propagator\") {\n                    double T =\n                        alma::parseXMLfield<double>(*it, \"T\");\n                    std::string Pfname =\n                        alma::parseXMLfield<std::string>(*it, \"file\");\n                    Eigen::MatrixXd P;\n                    alma::load_P(Pfname,P,world);\n                    hist_type that_histo;\n                    that_histo.reserve(3+P.cols());\n                    \n                    ///Fill up gamma acoustic modes\n                    ///It will fail if accessed through member functions\n                    for (auto ax : {0,1,2})\n                        that_histo.emplace_back();\n                    ///Fill up other modes\n                    for (auto ic = 0; ic < P.cols(); ic++)  {\n                        Eigen::VectorXd pcol = P.col(ic);\n                        that_histo.emplace_back(pcol);\n                    }\n                    histoByT[T] = that_histo;\n                }\n            }\n            \n            inpars.system_P[name] = histoByT;\n        }\n        \n        if (v.first == \"Eeff\") {\n            if (alma::probeXMLfield<double>(v,\"particles\")) {\n            \tinpars.Efactor =\n                \talma::parseXMLfield<std::size_t>(v, \"particles\"); \n            }\n            if (alma::probeXMLfield<double>(v,\"Ed\")) {\n            \tinpars.Edeviational =\n                \talma::parseXMLfield<double>(v, \"Ed\");\n\t    }\n            \n            if (alma::probeXMLfield<double>(v,\"Tmax\")) {\n                inpars.Tmax =\n                    alma::parseXMLfield<double>(v, \"Tmax\");\n                inpars.Tmin = \n                    alma::parseXMLfield<double>(v, \"Tmin\");\n            }\n        }\n        \n        if (v.first == \"RTA\") {\n            inpars.RTA = true;\n        }\n        \n        \n        if (v.first == \"transmission\") {\n            std::cout << \"This is currently not supported\\n\";\n            world.abort(1);\n        }\n        \n        if (v.first == \"init_distribution\") {\n            auto ibox =\n                alma::parseXMLfield<std::size_t>(v, \"box\");\n            std::string fd_name = \n                alma::parseXMLfield<std::string>(v, \"file\");\n            inpars.init_distribution[ibox] = get_column(fd_name,0);\n        }\n        \n    }\n    \n    if (inpars.system_cell.size()>1){\n        std::cout << \"This is currently not supported\\n\";\n        world.abort(1);\n    }\n    \n    ///Fill thicknesses\n    for (std::size_t i=0;i<inpars.system.size();i++) {\n        auto mat = inpars.system[i].material;\n        //std::cout << mat << '\\t' << zmap[mat] << std::endl;\n        inpars.thicknesses.push_back(\n            zmap[mat]);\n    }\n    \n    if (!inpars.RTA)\n        inpars.processes_map.clear();\n    \n//     std::cout << \"Thickness\\n\";\n//     for (auto i=0;i<inpars.system.size();i++)\n//         std::cout << inpars.thicknesses[i] << std::endl;\n    \n    inpars.gradients.resize(3,inpars.system.size());\n    inpars.gradients.setZero();\n    \n    ///If gradient is calc\n    if (inpars.calc_gradients) {\n      inpars.gradients  = \n        calculate_gradientT(inpars.system);\n    }\n    else{ ///Otherwise we set it to a given value\n       for (std::size_t i=0;i<inpars.system.size();i++) {\n           if (!inpars.system[i].reservoir \n               and !inpars.system[i].periodic) {\n               inpars.gradients(0,i) = \n                 inpars.homoGradient(0);\n               inpars.gradients(1,i) = \n                 inpars.homoGradient(1);\n           }\n       }\n    }\n    \n    return inpars;\n}\n\n\nclass D_particle_map {\npublic:\n    std::vector<Eigen::VectorXi> histograma;\n// \n\n    \n    \n    D_particle_map() = default;\n    \n    \n    D_particle_map(const D_particle_map& A) {\n        histograma.reserve(A.histograma.size());\n        for (auto &i : A.histograma){\n            histograma.emplace_back(i);\n        }\n    }\n    \n    D_particle_map(const std::vector<std::pair<std::size_t,std::size_t>>& histosizes) {\n        histograma.resize(histosizes.size());\n        for (std::size_t ibox = 0 ; ibox < histosizes.size(); ibox++) {\n                histograma[ibox].resize(\n                    histosizes[ibox].first *\n                    histosizes[ibox].second );\n                histograma[ibox].setZero();\n        }\n    }\n    \n};\n\nstd::pair<\nstd::vector<double>,\nstd::vector<Eigen::Vector3d>>\ncalculate_prop(gridData& grids,\n               std::vector<alma::geometry_2d>& sys,\n               std::vector<double>& volume,\n               double Eff,\n               std::size_t nboxes,\n               std::vector<alma::D_particle>& particles) {\n    \n    std::vector<Eigen::Vector3d> flux(nboxes);\n    std::vector<double> ed(nboxes);\n    for (std::size_t i=0;i<nboxes;i++)\n        flux[i].setZero();\n    \n    ///vg is in nm/ps\n    ///volume is in nm**3\n    ///Energy is in J\n    ///Flux units J/(ps * nm**2) \n    \n    for (auto &p : particles) {\n        auto mat = sys[p.boxid].material;\n        auto iq = p.q;\n        auto ib = p.alpha;\n        auto& spectrum = grids[mat]->\n            get_spectrum_at_q(iq);\n        Eigen::VectorXd vg = spectrum.vg.col(ib);\n        int signum = static_cast<int>(p.sign);\n        auto ibox = p.boxid;\n        \n        ed[ibox]   += signum;\n        flux[ibox] += signum*vg;\n    }\n    ///We want SI\n    for (std::size_t i=0;i<nboxes;i++){\n        ed[i]   *= Eff/volume[i] * 1.0e+27;\n        flux[i] *= Eff/volume[i] * 1e12 * 1e9 * 1e9;\n    }\n    return std::make_pair(ed,flux);\n};\n\nstd::pair<\nstd::vector<double>,\nstd::vector<Eigen::Vector3d>>\ncalculate_prop(gridData& grids,\n               std::vector<alma::geometry_2d>& sys,\n               std::vector<double>& volume,\n               double Eff,\n               D_particle_map& H) {\n    \n    std::mutex blocker;\n    static std::map<std::string,\n                    Eigen::VectorXd> vx, vy;\n    static std::size_t nboxes = \n        H.histograma.size();\n    \n    ///Quantities to store\n    std::vector<Eigen::Vector3d> flux(nboxes);\n    std::vector<double> ed(nboxes);\n    for (std::size_t i=0;i<nboxes;i++)\n        flux[i].setZero();\n    \n    tbb::parallel_for(tbb::blocked_range<std::size_t>(0, nboxes),[&](tbb::blocked_range<std::size_t> box_range) {\n        for (auto ibox = box_range.begin(); ibox < box_range.end(); ibox++){\n            ///Ignore reservoirs and periodic boxes\n            if (sys[ibox].reservoir or sys[ibox].periodic)\n                continue;\n            \n            auto material = sys[ibox].material;\n            auto nq = grids.at(material)->nqpoints;\n            auto nb = grids.at(material)->get_spectrum_at_q(0).omega.size();\n            \n            ///If empty create vx and vy\n            blocker.lock();\n            if (vx.count(material) == 0) {\n                Eigen::VectorXd vx_(nq * nb) , vy_(nq*nb); \n                \n                for ( decltype(nq) iq = 0; iq < nq; iq ++ )  {\n                    auto sp = grids.at(material)->get_spectrum_at_q(iq);\n                    for (int ib = 0; ib < nb; ib++) {\n                        vx_(iq*nb+ib) = sp.vg(0,ib);\n                        vy_(iq*nb+ib) = sp.vg(1,ib);\n                    }\n                }\n                \n                vx.emplace(material,vx_);\n                vy.emplace(material,vy_);\n                \n            }            \n            blocker.unlock();\n            \n            double edfactor = Eff / volume[ibox] * 1.0e+27;\n            double fluxfactor = Eff / volume[ibox]  * 1.0e+30;\n            \n            ed[ibox] = edfactor * \n                static_cast<double>(H.histograma[ibox].sum());\n            \n            flux[ibox](0) = fluxfactor * (H.histograma[ibox].cast<double>().array() * \n                vx[material].array()).sum();\n                \n            flux[ibox](1) = fluxfactor * (H.histograma[ibox].cast<double>().array() * \n                vy[material].array()).sum();\n                \n        }\n    });\n    \n    return std::make_pair(ed,flux);\n    \n}\n\nclass data {\npublic:\n    double time;\n    double Eeff;\n    std::vector<double> temperatures;\n    D_particle_map histo;\n    \n    \n    template <typename Packer>\n    void msgpack_pack(Packer& pk) const {\n        \n        std::size_t nboxes = histo.histograma.size();\n        \n        std::vector<std::size_t> nzeros(\n            nboxes);\n        \n        for (std::size_t i = 0; i < nzeros.size();i++) {\n           nzeros[i] =  (histo.histograma[i].array() != 0).count();\n        }\n        \n        ///Count elements 3 + 2*nboxes\n        std::size_t nelements = 3 + 2*nboxes;\n        // make array of two elements, by the number of class fields\n        pk.pack_array(nelements);\n\n        // pack the first field, time\n        pk.pack_double(time);\n        // pack the second field Eeff\n        pk.pack_double(Eeff);\n        // since it is array of doubles, we can't use direct conversion or copying\n        // memory because it would be a machine-dependent representation of floats\n        // instead, we converting this POD array to some msgpack array, like this:\n\n        pk.pack_array(temperatures.size());\n        for (const auto &t : temperatures) {\n            pk.pack_double(t);\n        } \n        \n        /// We are now working the histograms:\n        for (std::size_t ibox = 0; ibox<nzeros.size();ibox++){\n            if (nzeros[ibox] == 0) {\n                pk.pack_uint64(0);\n                pk.pack_array(1);\n                pk.pack_double(42.0);\n                continue;\n            }\n            \n            ///This block is solved at compile time\n            if constexpr (sizeof(std::size_t)==sizeof(std::uint8_t)) {\n                pk.pack_uint8(static_cast<std::uint8_t>(2*nzeros[ibox]));\n            }\n            else if constexpr (sizeof(std::size_t)==sizeof(std::uint16_t)) {\n                pk.pack_uint16(static_cast<std::uint16_t>(2*nzeros[ibox]));\n            }\n            else if constexpr (sizeof(std::size_t)==sizeof(std::uint32_t)) {\n                pk.pack_uint32(static_cast<std::uint32_t>(2*nzeros[ibox]));\n            }\n            else if constexpr (sizeof(std::size_t)==sizeof(std::uint64_t)) {\n                pk.pack_uint64(static_cast<std::uint64_t>(2*nzeros[ibox]));\n            }\n            else {\n                static_assert(sizeof(std::size_t)==sizeof(std::uint8_t)||\n                                      sizeof(std::size_t)==sizeof(std::uint16_t)||\n                                      sizeof(std::size_t)==sizeof(std::uint32_t)||\n                                      sizeof(std::size_t)==sizeof(std::uint64_t),\n                                      \"std::size_t cannot be mapped to msgpack type\"\n                        );\n                exit(1);\n            }\n            \n            \n            \n            pk.pack_array(2*nzeros[ibox]);\n            //for (std::size_t j=0; j<histo[ibox].count.size(); j++){\n            for (int j=0;j<histo.histograma[ibox].rows();j++) {\n                int val = histo.histograma[ibox][j];\n                if (val!=0) {\n                    \n                    ///This block is solved at compile time\n                    if constexpr (sizeof(std::size_t)==sizeof(std::uint8_t)) {\n                        pk.pack_uint8(static_cast<std::uint8_t>(j));\n                    }\n                    else if constexpr (sizeof(std::size_t)==sizeof(std::uint16_t)) {\n                        pk.pack_uint16(static_cast<std::uint16_t>(j));\n                    }\n                    else if constexpr (sizeof(std::size_t)==sizeof(std::uint32_t)) {\n                        pk.pack_uint32(static_cast<std::uint32_t>(j));\n                    }\n                    else if constexpr (sizeof(std::size_t)==sizeof(std::uint64_t)) {\n                        pk.pack_uint64(static_cast<std::uint64_t>(j));\n                    }\n                    else {\n                        static_assert(sizeof(std::size_t)==sizeof(std::uint8_t)||\n                                      sizeof(std::size_t)==sizeof(std::uint16_t)||\n                                      sizeof(std::size_t)==sizeof(std::uint32_t)||\n                                      sizeof(std::size_t)==sizeof(std::uint64_t),\n                                      \"std::size_t cannot be mapped to msgpack type\"\n                        );\n                        exit(1);\n                    }\n                    \n                    ///This block is solved at compile time\n                    if constexpr (sizeof(int)==sizeof(std::int8_t)) {\n                        pk.pack_int8(static_cast<std::int8_t>(val));\n                    }\n                    else if constexpr (sizeof(int)==sizeof(std::int16_t)) {\n                        pk.pack_int16(static_cast<std::int16_t>(val));\n                    }\n                    else if constexpr (sizeof(int)==sizeof(std::int32_t)) {\n                        pk.pack_int32(static_cast<std::int32_t>(val));\n                    }\n                    else if constexpr (sizeof(int)==sizeof(std::int64_t)) {\n                        pk.pack_int64(static_cast<std::int64_t>(val));\n                    }\n                    else {\n                        static_assert(sizeof(int)==sizeof(std::int8_t)||\n                                      sizeof(int)==sizeof(std::int16_t)||\n                                      sizeof(int)==sizeof(std::int32_t)||\n                                      sizeof(int)==sizeof(std::int64_t),\n                                      \"std::ptrdiff_t cannot be mapped to msgpack type\"\n                        );\n                        exit(1);\n                    }\n\n                }\n            }\n        }\n    }\n};\n\nclass saver {\nprivate:\n    std::ofstream out;    \npublic:\n    \n    \n    saver(std::string fname) {\n        out.open(fname.c_str());\n    }\n    ~saver(){\n        out << \"0#\" ;\n        out.close();\n    }\n    \n    \n    bool save_frame(double time,\n                    double Eeff,\n                    std::vector<double> temperatures,\n                    D_particle_map& histo) {\n        \n        data frame_data;\n        frame_data.time = time;\n        frame_data.Eeff = Eeff;\n        frame_data.temperatures = temperatures;\n        frame_data.histo = std::move(histo); \n        \n        std::stringstream buffer;\n        msgpack::pack(buffer, frame_data);\n        \n        std::size_t block_size = buffer.str().size();\n        \n        out << block_size << \"#\" << buffer.str();\n        return false;\n    }\n    \n};\n\n///To do asyncronous operations for I/O\n///is built on top of tbb/concurrent_queue and\n///tbb tasks_group\nnamespace Queue {\n\n///@param[in,out] tasks - queue containing the jobs to do\n///@param[in]     kill  - kill signal \nvoid work_list(tbb::concurrent_bounded_queue<std::function<bool()>>& tasks,bool& kill){\n    while (true) {\n        if (!tasks.empty()) {\n            std::function<bool()> task;\n            tasks.pop(task);\n            if (task()){\n                break;\n            }\n        }\n        else {\n            if(kill)\n                break;\n        }\n    }\n}\n\n\n///This class allows one to use TBB to\n///set a thread to IO operations:\n\nclass single_worker {\nprivate:\n    ///Task taking care of the list\n    tbb::task_group my_group;\n    ///The queue of jobs\n    tbb::concurrent_bounded_queue<std::function<bool()>> task_list;\n    ///Kill signal\n    bool kill = false;\n    ///Helper to hold the task function-loop\n    std::function<void()> exec_internal;\n    \npublic:\n    ///Basic constructor\n    single_worker() {\n        exec_internal = std::bind(work_list,std::ref(task_list),std::ref(kill));\n        my_group.run(exec_internal);\n    }\n    \n    ///Be sure all threads have finished\n    ~single_worker(){\n        my_group.wait();   \n    };\n    \n    ///Pushing function job to list\n    ///@param[in] job - function with the job\n    void push_job(std::function<bool()>&& job) {\n        task_list.push(std::move(job));\n    }\n    \n    ///To finish (it is kill signal)\n    void finish() {\n        this->kill = true;\n    }\n    \n};\n\n};\n\n\n\n///Here we will generate\n\nint main(int argc, char** argv) {\n    boost::mpi::environment env;\n    boost::mpi::communicator world;\n    \n    if (world.size()>1) {\n        std::cout << \"Cannot run in MPI\" << std::endl;\n        std::cout << \"Multithreading is allowed via TBB\" << std::endl;\n        world.abort(1);\n    }\n    \n    auto my_id = world.rank();\n\n    if (my_id == 0) {\n        std::cout << \"********************************************\"\n                  << std::endl;\n        std::cout << \"This is ALMA/beyondRTA_MC2d version \"\n                  << ALMA_VERSION_MAJOR << \".\" << ALMA_VERSION_MINOR\n                  << std::endl;\n        std::cout << \"********************************************\"\n                  << std::endl;\n    }\n\n    // Check that the right number of arguments have been provided.\n    if (argc != 3) {\n        if (my_id == 0) {\n            std::cerr << boost::format(\n                             \"Usage: %1% <inputfile.xml> nthreads\") %\n                             argv[0]\n                      << std::endl;\n        }\n        return 1;\n    }\n    \n    std::size_t nthreadsTBB = std::atoi(argv[2]);\n    \n    if (nthreadsTBB < 2) {\n        throw alma::input_error(\"Two threads is the minum required\");\n    }\n    \n    \n    \n    tbb::global_control control(\n        tbb::global_control::max_allowed_parallelism,\n                                nthreadsTBB);\n    \n    ///Create the worker:\n    Queue::single_worker writer;\n    \n    \n    \n    ///Process the file:\n    std::string inputfile = argv[1];\n    \n    input_parameters inpars = \n        std::move(process_input(inputfile,world));\n        \n    bool calc_gradients = \n        inpars.calc_gradients;\n    Eigen::MatrixXd gradients = \n        inpars.gradients;\n    \n    //std::cout << gradients << std::endl;\n\n    \n    ///Geometry\n    std::vector<alma::geometry_2d>\n        system;\n    std::swap(inpars.system,system);\n    auto nboxes =\n        system.size();\n    \n//     std::cout << nboxes << std::endl;\n//     for (auto &s :  system) {\n//         std::cout << s.get_id() <<std::endl;\n//         std::cout << s.Teq << std::endl;\n//         std::cout << s.periodic << std::endl;\n//         if (s.periodic)\n//             std::cout << \"T\\n\" << s.translation << std::endl;\n//     }\n    \n    std::vector<double>\n        thicknesses;\n    std::swap(thicknesses,\n              inpars.thicknesses);\n    \n    ///Time\n    double dt = inpars.dt; \n    double maxtime = inpars.maxtime;\n    \n    ///Eeff:\n    auto Efactor = inpars.Efactor;\n    \n    ///Material data\n    cellData system_cell = \n        std::move(inpars.system_cell);\n    gridData system_grid =\n        std::move(inpars.system_grid);\n    propagators system_P =\n        std::move(inpars.system_P);\n    \n    ///The random generator\n    pcg64 rng;\n    tbb::enumerable_thread_specific<pcg64>rng_;\n    \n    ///Get the Eeff from guess\n    double maxT  = 0.;\n    double minT  = 1.416784e+32;\n    double meanT = 0.;\n    std::size_t nb_ = 0;\n    std::vector<double> volsf(nboxes);\n    std::vector<double> vols(nboxes);\n    \n    for (std::size_t i=0; i<nboxes; i++) {\n        auto mat = system[i].material;\n        auto area = \n            system[i].get_area();\n        \n//         std::cout << \"box \"<< i << '\\t' << area << '\\n';\n        double corrected_vuc =\n            thicknesses[i] * \n            system_cell[mat]->V / \n            system_cell[mat]->lattvec(2,2);\n        vols[i]  = area * \n            thicknesses[i];\n        volsf[i] = area * \n            thicknesses[i]/corrected_vuc;\n        \n    }\n    \n    \n    for (std::size_t i=0; i<nboxes; i++) {\n        \n        if (system[i].periodic)\n            continue;\n        \n        auto boxT = system[i].Teq;\n        \n        meanT += boxT;\n        nb_++;\n        \n        if (boxT < minT)\n            minT = boxT;\n        if (boxT > maxT)\n            maxT = boxT;\n    }\n    \n    if (inpars.Tmax != 0) {\n        maxT = inpars.Tmax;\n        minT = inpars.Tmin;\n    }\n    \n    meanT /= nb_;\n    \n    std::vector<double> effs;\n    double Eeff;    \n    \n    if (inpars.Edeviational < 0.) {\n\n    \tfor (std::size_t i=0; i<nboxes; i++) {\n    \t    \n    \t    if (system[i].periodic or\n    \t        system[i].reservoir\n    \t    )\n    \t        continue;\n    \t    auto mat = system[i].material;\n    \t    effs.push_back(calc_Eeff(\n    \t            *(system_grid[mat]), \n    \t            maxT, \n    \t            minT, \n    \t            meanT, \n    \t            volsf[i],\n    \t            Efactor));\n    \t}\n    \t\n    \tEeff = *(std::min_element(\n    \t    effs.begin(),effs.end()));\n    }\n    else {\n\tEeff = inpars.Edeviational;\n    }\n    ///Print inf\n    if (inpars.RTA)\n        std::cout << \"#RTA version activated\\n\";\n    ///particles\n    std::vector<alma::D_particle> particles;\n    auto time = 0.;\n    std::size_t istep = 0;\n    ///Some definitions:\n    using vpartIt = decltype(particles.begin());\n    std::function<vpartIt(vpartIt,\n                          vpartIt,\n                          std::size_t,\n                          std::size_t,\n                          int,\n                          std::size_t)> seeker = \n                          search_Dparticle<vpartIt>;\n    std::mutex cerberus;\n    std::size_t pcancel_each = 4;//static_cast<std::size_t>(std::floor(2.5/dt) +1.0e-6);\n    \n    std::unordered_map<\n        std::array<std::size_t,2>,\n        std::ptrdiff_t> particle_count;\n    \n    std::vector<double> temperatures(system.size());\n    for (auto &s : system)\n        temperatures[s.get_id()] = s.Teq;\n    \n    saver Register(\"properties.msgpack.bin\");\n    \n    ///Init particles from init given distributions\n    if (inpars.init_distribution.size()!=0)\n        box_generators::init_particles(system,system_grid,system_cell,\n                                       inpars.init_distribution,\n                                       particles,rng,thicknesses,Eeff);\n    \n    ///Init particles from temperature different from that \n    ///of equilibrium (it will discard any previous loaded distribution)\n    box_generators::init_particles(system,system_grid,system_cell,\n\t\t                   particles,rng,thicknesses,Eeff);\n    std::cout << \"#Inited deviational particles from initial conditions\" << std::endl;\n    std::cout << \"#Init particles: \"<< particles.size() << std::endl; \n    std::cout << \"#Eeff is: \"<< Eeff << \" J\" << std::endl;\n    \n    auto prop0 = calculate_prop(system_grid,system,vols,Eeff,system.size(),particles);\n    auto flux0 = prop0.second;\n    auto ed0   = prop0.first;\n    \n    std::cout << istep << '\\t' << time << '\\t' << particles.size()  << '\\t';\n    for (std::size_t ibox = 0; ibox < system.size(); ibox++)\n        std::cout << ed0[ibox] << '\\t' << flux0[ibox](0) << '\\t' << flux0[ibox](1) << '\\t';\n    std::cout << std::endl;\n    std::cout << std::flush;\n    \n    std::vector<std::pair<std::size_t,std::size_t>> histosizes;\n    for (auto &s : system) {\n        auto mat = s.material;\n        auto nq  = system_grid[mat]->nqpoints;\n        auto nb  = system_grid[mat]->get_spectrum_at_q(0).omega.size();\n        if (!s.reservoir and !s.periodic) { \n            histosizes.push_back({nq,nb});\n        }\n        else {\n            histosizes.push_back({1,1});\n        }\n    }\n    \n    const auto sign_minus = alma::get_particle_sign(-1.0);\n    \n    while (time <= maxtime) {        \n        std::cout << \"#Advection\" << std::endl;\n        auto tA = std::chrono::high_resolution_clock::now();\n        ///Move particles until non-periodic boundary or the end\n        tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particles.size()),[&](tbb::blocked_range<std::size_t> ir) {\n            for (auto i=ir.begin(); i<ir.end();i++){\n                auto mat = system[\n                    particles[i].boxid].material;\n                auto v = get_v(*(system_grid[mat]),\n                               particles[i].alpha,particles[i].q);\n                evolparticle(particles[i],v,system,dt,rng_.local(),cerberus);\n            }\n        });\n        auto tB = std::chrono::high_resolution_clock::now();\n        std::cout << \"#Advection  => DONE in \"<< \n        (static_cast<std::chrono::duration<double>>(tB - tA)).count()\n        << \" s\" << std::endl;\n        \n        \n        std::cout << \"#Generators\" << std::endl;\n        ///2.Add particle from source term and evolve it a random time\n        std::vector<alma::D_particle> grad_particles;\n        grad_particles.reserve(particles.size());\n        box_generators::source_term_gradient(\n                             system,\n                             system_grid,\n                             system_cell,\n                             grad_particles,\n                             rng,\n                             thicknesses,\n                             dt,\n                             Eeff,\n                             calc_gradients,\n                             gradients);\n        \n        tbb::parallel_for(tbb::blocked_range<std::size_t>(0, grad_particles.size()),[&](tbb::blocked_range<std::size_t> ir) {\n            for (auto i=ir.begin(); i<ir.end();i++){\n                auto mat = system[\n                    grad_particles[i].boxid].material;\n                auto v = get_v(*(system_grid[mat]),\n                               grad_particles[i].alpha,grad_particles[i].q);\n                auto rdt = dt * std::uniform_real_distribution<double>(0., 1.)(rng_.local());\n                evolparticle(grad_particles[i],v,system,rdt,rng_.local(),cerberus);\n            }\n        });\n        \n        std::cout <<\"##Source term: \" << grad_particles.size() << std::endl;  \n        \n        particles.insert( particles.end(),grad_particles.begin(), \n                          grad_particles.end());\n        \n        ///3. Add particles from Isothermal walls and evolve random time\n        std::vector<alma::D_particle> isowall_particles;\n        box_generators::Isothermal_walls(\n                         system,\n                         system_grid,\n                         system_cell,\n                         isowall_particles,\n                         rng,\n                         thicknesses,\n                         dt,\n                         Eeff);\n        tbb::parallel_for(tbb::blocked_range<std::size_t>(0, isowall_particles.size()),[&](tbb::blocked_range<std::size_t> ir) {\n            for (auto i=ir.begin(); i<ir.end();i++){\n                auto mat = system[\n                    isowall_particles[i].boxid].material;\n                auto v = get_v(*(system_grid[mat]),\n                               isowall_particles[i].alpha,isowall_particles[i].q);\n                auto rdt = dt * std::uniform_real_distribution<double>(0., 1.)(rng_.local());\n                evolparticle(isowall_particles[i],v,system,rdt,rng_.local(),cerberus);\n            }\n        });\n        std::cout <<\"##Isothermal walls: \" << isowall_particles.size() << std::endl;\n        particles.insert( particles.end(),isowall_particles.begin(), \n                          isowall_particles.end());\n        \n        ///4. Add particles from adiabatic diffuse walls and evolve random time\n        std::vector<alma::D_particle> adiabatic_particles;\n        box_generators::adiabatic_diffuse_walls(\n                             system,\n                             system_grid,\n                             system_cell,\n                             adiabatic_particles,\n                             rng,\n                             thicknesses,\n                             dt,\n                             Eeff);\n        \n        tbb::parallel_for(tbb::blocked_range<std::size_t>(0, adiabatic_particles.size()),[&](tbb::blocked_range<std::size_t> ir) {\n            for (auto i=ir.begin(); i<ir.end();i++){\n                auto mat = system[\n                    adiabatic_particles[i].boxid].material;\n                auto v = get_v(*(system_grid[mat]),\n                               adiabatic_particles[i].alpha,adiabatic_particles[i].q);\n                auto rdt = dt * std::uniform_real_distribution<double>(0., 1.)(rng_.local());\n                evolparticle(adiabatic_particles[i],v,system,rdt,rng_.local(),cerberus);\n            }\n        });\n        std::cout << \"##Adiabatic diffuse walls: \" << adiabatic_particles.size() << std::endl;\n        particles.insert( particles.end(),adiabatic_particles.begin(), \n                          adiabatic_particles.end());\n        auto tC = std::chrono::high_resolution_clock::now();\n        std::cout << \"#Generators => DONE in \"<< \n        (static_cast<std::chrono::duration<double>>(tC - tB)).count()\n        << \" s\" << std::endl;\n        \n        ///Clean particles vector from those marked to delete\n        delete_particles(particles);\n        \n        ///Scattering section\n        std::cout << \"#Scattering\" << std::endl;\n        if (inpars.RTA) {\n            ScatteringRTA(particles,system,system_grid,system_cell,inpars.processes_map,dt,rng_,cerberus,world);            \n        }\n        else{\n            Scattering(particles,system,system_P,system_grid,rng_,cerberus);\n        }\n        auto tD = std::chrono::high_resolution_clock::now();\n        std::cout << \"#Scattering => DONE in \"<< \n        (static_cast<std::chrono::duration<double>>(tD - tC)).count()\n        << \" s\" << std::endl;\n\n        ///Cancel section:\n        bool cancel_flag = (istep % pcancel_each == 0);\n        std::cout << \"#Canceling and save\" << std::endl;\n\n        D_particle_map H(histosizes);\n        \n        auto tD1 = std::chrono::high_resolution_clock::now();\n\n        for (auto &p : particles) {\n            auto ibox = p.boxid;\n                    auto nb   = histosizes[ibox].second;\n            H.histograma[ibox](p.q*nb+p.alpha) += static_cast<int>(p.sign);\n        }\n        \n        auto tD2 = std::chrono::high_resolution_clock::now();\n        \n        if (cancel_flag) {\n            \n             ///Getting one histo to modify\n             D_particle_map Hc(H);\n             \n             ///We work each box by separate:\n             order_particles_multithread(particles);\n             std::vector<alma::D_particle> particles_;\n             std::vector<std::pair<std::ptrdiff_t,std::ptrdiff_t>> boxlimits;\n             \n             for (std::size_t i = 0; i< system.size(); i++ ) {\n                 ///Search block limits\n                 alma::D_particle lbp(0,0,sign_minus,i);\n                 alma::D_particle ubp(0,0,sign_minus,i+1);\n                     \n                 auto lb = std::lower_bound(particles.begin(),particles.end(),\n                                             lbp,std::less<alma::D_particle>());\n                 auto ub = std::lower_bound(particles.begin(),particles.end(),\n                                             ubp,std::less<alma::D_particle>());\n                 \n                 boxlimits.push_back({\n                     std::distance(particles.begin(),lb),\n                     std::distance(particles.begin(),ub)\n                 });\n                 \n             }\n                 \n             \n             \n             tbb::parallel_for(tbb::blocked_range<std::size_t>(0,system.size()),[&](tbb::blocked_range<std::size_t> ir){\n                 for (auto i = ir.begin(); i<ir.end(); i++) {\n                     ///If reservoir or periodic ignore\n                     if (system[i].reservoir or system[i].periodic)\n                         continue;\n                     \n                     auto lb = particles.begin() + boxlimits[i].first;\n                     auto ub = particles.begin() + boxlimits[i].second;\n                     \n                     //If no particles in the box continue\n                     if (std::distance(lb,ub)==0)\n                         continue;\n                     \n                     auto& hbox = Hc.histograma[i];\n                     const auto nb_ = histosizes[i].second;\n                     \n                     \n                     \n                     auto newend = std::remove_if(lb,ub,\n                         [&](const alma::D_particle& p)->bool {\n                             auto iq = p.q;\n                             auto ib = p.alpha;\n                             auto imode = iq*nb_ + ib;\n                             int  s   = static_cast<int>(p.sign);\n                             int& h   = hbox[imode];\n                             \n                             if (h == 0)  {\n                                 return true;\n                             }\n                             if ( (s<0)!=(h<0) ){\n                                 return true;\n                             }\n                             h -= s;\n                             return false;\n                         }\n                     );\n                     \n                     cerberus.lock();\n                     particles_.insert(particles_.end(),lb,newend);\n \n                     cerberus.unlock();\n                 }\n             });\n             \n             std::swap(particles,particles_);\n        }    \n        auto tD3 = std::chrono::high_resolution_clock::now();\n        \n        /// Properties are extracted from histograms\n        auto prop = calculate_prop(system_grid,system,vols,Eeff,H);\n        \n        auto tD4 = std::chrono::high_resolution_clock::now();\n        \n        /// Save here the properties\n        auto frame_saving = std::bind(&saver::save_frame,&Register,\n                                      time+dt,Eeff,temperatures,H); \n        writer.push_job(frame_saving);\n        \n        \n        \n        \n        auto tE = std::chrono::high_resolution_clock::now();\n        std::cout << \"###Canceling and saving=> DONE in \"<< \n        (static_cast<std::chrono::duration<double>>(tE - tD)).count()\n        << \" s\" << std::endl;\n        std::cout << \"###Shuffle and allocate \"<< \n        (static_cast<std::chrono::duration<double>>(tD1 - tD)).count()\n        << \" s\" << std::endl;\n        std::cout << \"###Histogram building \"<< \n        (static_cast<std::chrono::duration<double>>(tD2 - tD1)).count()\n        << \" s\" << std::endl;\n        if (cancel_flag and inpars.RTA) {\n            std::cout << \"###Cancelling \"<< \n            (static_cast<std::chrono::duration<double>>(tD3 - tD2)).count()\n            << \" s\" << std::endl;\n        }\n        std::cout << \"###Calculating properties \" <<\n        (static_cast<std::chrono::duration<double>>(tD4 - tD3)).count()\n        << \" s\" << std::endl;\n        std::cout << \"###Saving \"<< \n        (static_cast<std::chrono::duration<double>>(tE - tD4)).count()\n        << \" s\" << std::endl;\n        \n        \n        istep++;\n        time += dt;\n        \n        \n        ///Here we print the properties:\n        auto flux = prop.second;\n        auto ed   = prop.first;\n        std::cout << istep << '\\t' << time << '\\t'<< particles.size() <<'\\t';\n        for (std::size_t ibox = 0; ibox < system.size(); ibox++) {\n            std::cout << ed[ibox] << '\\t' << \n            flux[ibox](0) << '\\t' << flux[ibox](1) << '\\t';\n        }\n        std::cout << std::endl;\n        \n    }\n    \n    writer.finish();\n    \n    return EXIT_SUCCESS;\n}\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "807ab6fe45f43e73bd699405e5b9f1bfeb41ef85", "size": 81148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/beyondRTA_MC2d.cpp", "max_stars_repo_name": "sousaw/BTE-Barna", "max_stars_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T03:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:11:20.000Z", "max_issues_repo_path": "src/beyondRTA_MC2d.cpp", "max_issues_repo_name": "sousaw/BTE-Barna", "max_issues_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_issues_repo_licenses": ["MIT", "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/beyondRTA_MC2d.cpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "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.2396624473, "max_line_length": 130, "alphanum_fraction": 0.4858037167, "num_tokens": 18738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1874537802199378}}
{"text": "//\n// Tracker Pattern Recognition based on Robust Helix Fit\n//\n//\n// Original author D. Brown and G. Tassielli\n//\n\n#include \"art/Framework/Principal/Event.h\"\n#include \"GeometryService/inc/GeomHandle.hh\"\n#include \"fhiclcpp/ParameterSet.h\"\n#include \"art/Framework/Principal/Handle.h\"\n#include \"art/Framework/Core/EDProducer.h\"\n#include \"art/Framework/Core/ModuleMacros.h\"\n#include \"art_root_io/TFileService.h\"\n#include \"GeneralUtilities/inc/Angles.hh\"\n#include \"Mu2eUtilities/inc/MVATools.hh\"\n\n#include \"ProditionsService/inc/ProditionsHandle.hh\"\n\n#include \"DataProducts/inc/Helicity.hh\"\n#include \"RecoDataProducts/inc/StrawHitCollection.hh\"\n#include \"RecoDataProducts/inc/StrawHitPositionCollection.hh\"\n#include \"RecoDataProducts/inc/StrawHitFlagCollection.hh\"\n#include \"RecoDataProducts/inc/TimeCluster.hh\"\n#include \"RecoDataProducts/inc/HelixSeed.hh\"\n#include \"RecoDataProducts/inc/TrkFitFlag.hh\"\n\n#include \"TrkReco/inc/TrkTimeCalculator.hh\"\n#include \"TrackerGeom/inc/Tracker.hh\"\n#include \"CalorimeterGeom/inc/DiskCalorimeter.hh\"\n\n#include \"BTrk/BaBar/BaBar.hh\"\n#include \"TrkReco/inc/RobustHelixFit.hh\"\n#include \"TrkReco/inc/Chi2HelixFit.hh\"\n\n#include \"ConfigTools/inc/ConfigFileLookupPolicy.hh\"\n#include \"Mu2eUtilities/inc/ModuleHistToolBase.hh\"\n#include \"Mu2eUtilities/inc/polyAtan2.hh\"\n#include \"Mu2eUtilities/inc/HelixTool.hh\"\n#include \"art/Utilities/make_tool.h\"\n\n#include \"TrkPatRec/inc/RobustHelixFinder_types.hh\"\n#include \"TrkReco/inc/RobustHelixFinderData.hh\"\n#include \"TrkReco/inc/TrkFaceData.hh\"\n\n#include \"CLHEP/Units/PhysicalConstants.h\"\n#include \"CLHEP/Matrix/Vector.h\"\n#include \"CLHEP/Matrix/SymMatrix.h\"\n\n#include <boost/accumulators/accumulators.hpp>\n#include \"boost_fix/accumulators/statistics/stats.hpp\"\n#include \"boost_fix/accumulators/statistics.hpp\"\n#include <boost/accumulators/statistics/median.hpp>\n\n#include \"TH1F.h\"\n#include \"Math/VectorUtil.h\"\n#include \"TVector2.h\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <memory>\n#include <utility>\n#include <functional>\n#include <float.h>\n#include <vector>\n#include <map>\n\nusing namespace std;\nusing namespace boost::accumulators;\nusing namespace ROOT::Math::VectorUtil;\n\nnamespace {\n  // comparison functor for sorting by z\n  struct zcomp : public std::binary_function<mu2e::ComboHit,mu2e::ComboHit,bool> {\n    bool operator()(mu2e::ComboHit const& p1, mu2e::ComboHit const& p2) { return p1._pos.z() < p2._pos.z(); }\n  };\n\n  // comparison functor for sorting byuniquePanel ID\n  struct panelcomp : public std::binary_function<mu2e::ComboHit,mu2e::ComboHit,bool> {\n    bool operator()(mu2e::ComboHit const& p1, mu2e::ComboHit const& p2) { return p1.strawId().uniquePanel() < p2.strawId().uniquePanel(); }\n  };\n  struct HelixHitMVA\n  {\n    std::vector <float> _pars,_pars2;\n    float& _dtrans; // distance from hit to helix perp to the wrire\n    float& _dwire;  // distance from hit to helix along the wrire\n    float& _chisq;  // chisq of spatial information, using average errors\n    float& _dt;     // time difference of hit WRT average\n    float& _drho;   // hit transverse radius minus helix radius\n    float& _dphi;   // hit azimuth minus helix azimuth (at the hit z)\n    float& _rwdot;  // dot product between circle radial direction and wire direction\n    float& _hrho;   // helix transverse radius (at the hit z)\n    float& _hhrho;  // hit transverse radius\n    //HelixHitMVA() : _pars(9,0.0),_dtrans(_pars[0]),_dwire(_pars[1]),_chisq(_pars[2]),_dt(_pars[3]),\n    // _drho(_pars[4]),_dphi(_pars[5]),_rwdot(_pars[6]),_hrho(_pars[7]),_hhrho(_pars[8]){}\n    HelixHitMVA() : _pars(7,0.0),_pars2(2,0.0),_dtrans(_pars[0]),_dwire(_pars[1]),_chisq(_pars[2]),_dt(_pars[3]),\n\t\t    _drho(_pars[4]),_dphi(_pars[5]),_rwdot(_pars[6]),_hrho(_pars[0]),_hhrho(_pars2[1]) {}\n  };\n\n}\n\nnamespace mu2e {\n\n  class RobustHelixFinder : public art::EDProducer {\n  public:\n    explicit RobustHelixFinder(fhicl::ParameterSet const&);\n    virtual ~RobustHelixFinder();\n    virtual void beginJob();\n    virtual void beginRun(art::Run&   run   );\n    virtual void produce(art::Event& event );\n\n  private:\n    int                                 _diag,_debug,_reducedchi2;\n    int                                 _printfreq;\n    bool\t\t\t\t_prefilter; // prefilter hits based on sector\n    bool\t\t\t\t_updatestereo; // update the stereo hit positions each iteration\n    int \t\t\t\t_minnsh; // minimum # of strawHits to work with\n    float\t\t\t        _pitch; // average pitch to assume in time calculations\n    float                               _maxchi2dxy;\n    float                               _maxchi2dzphi;\n    float                               _maxphihitchi2;\n    float\t\t\t\t_maxdr; // maximum hit-helix radius difference\n    float\t\t\t\t_maxrpull; // maximum hit-helix radius difference pull\n    bool                                _targetconInit;//require the firs circle fit to intersect the Al stopping Target\n    bool                                _targetcon;//require the circle fit to intersect the Al stopping Target\n    float                               _rpullScaleF;//need to scale the radial pull in filterCircleHits\n    float\t\t\t\t_maxphisep; // maximum separation in global azimuth of hits\n    TrkFitFlag\t\t\t\t_saveflag; // write out all helices that satisfy these flags\n    unsigned\t\t\t\t_maxniter;  // maximum # of iterations over outlier filtering + fitting\n    float\t\t\t\t_cradres; // average center resolution along center position (mm)\n    float\t\t\t\t_cperpres; // average center resolution perp to center position (mm)\n    float\t\t\t\t_maxdwire; // outlier cut on distance between hit and helix along wire\n    float\t\t\t\t_maxdtrans; // outlier cut on distance between hit and helix perp to wire\n    float\t\t\t\t_maxchisq; // outlier cut on chisquared\n    float\t\t\t\t_maxrwdot; // outlier cut on angle between radial direction and wire: smaller is better\n    float\t\t\t\t_minrerr; // minimum radius error\n\n    bool\t\t\t\t_usemva; // use MVA to cut outliers\n    float                               _minmva; // outlier cut on MVA\n    bool                                _useTripletAreaWt;\n\n    art::ProductToken<ComboHitCollection> const _chToken;\n    art::ProductToken<TimeClusterCollection> const _tcToken;\n\n    StrawHitFlag  _hsel, _hbkg;\n\n    MVATools _stmva, _nsmva;\n    HelixHitMVA _vmva; // input variables to TMVA for filtering hits\n\n    TH1F* _niter, *_niterxy, *_niterfz, *_nitermva;\n\n    RobustHelixFit   _hfit;\n    Chi2HelixFit     _chi2hfit;\n\n    std::vector<Helicity> _hels; // helicity values to fit\n    TrkTimeCalculator _ttcalc;\n    StrawHitFlag      _outlier;\n    bool              _updateStereo;\n\n    std::unique_ptr<ModuleHistToolBase>   _hmanager;\n    RobustHelixFinderTypes::Data_t        _data;\n    RobustHelixFinderData                 _hfResult;\n\n\n    ProditionsHandle<Tracker> _alignedTracker_h;\n    const Tracker* _tracker;\n\n    void     findHelices(ComboHitCollection& chcol, const TimeClusterCollection& tccol);\n    void     prefilterHits(RobustHelixFinderData& helixData, int& nFilteredStrawHits);\n    unsigned filterCircleHits(RobustHelixFinderData& helixData);\n    int      filterChi2ZPhiHits(RobustHelixFinderData& helixData);\n    int      filterChi2XYHits(RobustHelixFinderData& helixData);\n    bool     filterHits(RobustHelixFinderData& helixData);\n    void     fillMVA(RobustHelixFinderData& helixData);\n    bool     filterHitsMVA(RobustHelixFinderData& helixData);\n    void     updateT0(RobustHelixFinderData& helixData);\n    bool     updateStereo(RobustHelixFinderData& helixData);\n    unsigned hitCount(RobustHelixFinderData& helixData);\n    void     pickBestHelix      (std::vector<HelixSeed>& HelVec, int &Index_best);\n    void     fillFaceOrderedHits(RobustHelixFinderData& helixData);\n    void     fillGoodHits       (RobustHelixFinderData& helixData);\n    void     fitHelix           (RobustHelixFinderData& helixData);\n    void     fitChi2Helix       (RobustHelixFinderData& helixData);\n    void     refitHelix         (RobustHelixFinderData& helixData);\n    void     findMissingHits    (RobustHelixFinderData& helixData);\n    void     fillPluginDiag     (RobustHelixFinderData& helixData, int helCounter);\n    void     updateChi2HelixInfo(RobustHelixFinderData& helixData);\n    void     updateHelixXYInfo  (RobustHelixFinderData& helixData);\n    void     updateHelixZPhiInfo(RobustHelixFinderData& helixData);\n    void     searchWorstHitXY   (RobustHelixFinderData& helixData, HitInfo_t& hitInfo);\n    void     searchWorstHitZPhi (RobustHelixFinderData& helixData, HitInfo_t& hitInfo);\n  };\n\n  RobustHelixFinder::RobustHelixFinder(fhicl::ParameterSet const& pset) :\n    art::EDProducer{pset},\n    _diag        (pset.get<int>(\"diagLevel\",0)),\n    _debug       (pset.get<int>(\"debugLevel\",0)),\n    _reducedchi2 (pset.get<int>(\"reducedchi2\",0)),\n    _printfreq   (pset.get<int>(\"printFrequency\",101)),\n    _prefilter   (pset.get<bool>(\"PrefilterHits\",true)),\n    _updatestereo(pset.get<bool>(\"UpdateStereoHits\",false)),\n    _minnsh      (pset.get<int>(\"minNStrawHits\",10)),\n    _pitch       (pset.get<int>(\"AveragePitch\",0.6)),\n    _maxchi2dxy  (pset.get<float>(\"MaxChi2dXY\", 5.0)),\n    _maxchi2dzphi(pset.get<float>(\"MaxChi2dZPhi\", 5.0)),\n    _maxphihitchi2(pset.get<float>(\"MaxHitPhiChi2\", 25.0)),\n    _maxdr\t (pset.get<float>(\"MaxRadiusDiff\",100.0)), // mm\n    _maxrpull\t (pset.get<float>(\"MaxRPull\",5.0)), // unitless\n    _targetconInit(pset.get<bool>(\"targetconsistent_init\",true)),\n    _targetcon   (pset.get<bool>(\"targetconsistent\",true)),\n    _rpullScaleF (pset.get<float>(\"RPullScaleF\",1.414)), // unitless\n    _maxphisep\t (pset.get<float>(\"MaxPhiHitSeparation\",1.0)),\n    _saveflag    (pset.get<vector<string> >(\"SaveHelixFlag\",vector<string>{\"HelixOK\"})),\n    _maxniter    (pset.get<unsigned>(\"MaxIterations\",10)), // iterations over outlier removal\n    _cradres     (pset.get<float>(\"CenterRadialResolution\",20.0)),\n    _cperpres    (pset.get<float>(\"CenterPerpResolution\",12.0)),\n    _maxdwire    (pset.get<float>(\"MaxWireDistance\",200.0)), // max distance along wire\n    _maxdtrans   (pset.get<float>(\"MaxTransDistance\",80.0)), // max distance perp to wire (and z)\n    _maxchisq    (pset.get<float>(\"MaxChisquared\", 25.)), //100.0)), // max chisquared\n    _maxrwdot\t (pset.get<float>(\"MaxRWDot\",1.0)),\n    _minrerr     (pset.get<float>(\"MinRadiusErr\",20.0)), // mm\n    _usemva      (pset.get<bool>(\"UseHitMVA\",false)),\n    _minmva      (pset.get<float> (\"MinMVA\",0.1)), // min MVA output to define an outlier\n    _useTripletAreaWt(pset.get<bool>(\"UseTripletArea\", false)),\n    _chToken{consumes<ComboHitCollection>(pset.get<art::InputTag>(\"ComboHitCollection\"))},\n    _tcToken{consumes<TimeClusterCollection>(pset.get<art::InputTag>(\"TimeClusterCollection\"))},\n    _hsel        (pset.get<std::vector<std::string> >(\"HitSelectionBits\",std::vector<string>{\"TimeDivision\"})),\n    _hbkg        (pset.get<std::vector<std::string> >(\"HitBackgroundBits\",std::vector<std::string>{\"Background\"})),\n    _stmva       (pset.get<fhicl::ParameterSet>(\"HelixStereoHitMVA\",fhicl::ParameterSet())),\n    _nsmva       (pset.get<fhicl::ParameterSet>(\"HelixNonStereoHitMVA\",fhicl::ParameterSet())),\n    _hfit        (pset.get<fhicl::ParameterSet>(\"RobustHelixFit\",fhicl::ParameterSet())),\n    _chi2hfit    (pset.get<fhicl::ParameterSet>(\"Chi2HelixFit\",fhicl::ParameterSet())),\n    _ttcalc      (pset.get<fhicl::ParameterSet>(\"T0Calculator\",fhicl::ParameterSet())),\n    _outlier     (StrawHitFlag::outlier),\n    _updateStereo    (pset.get<bool>(\"UpdateStereo\",false))\n  {\n    std::vector<int> helvals = pset.get<std::vector<int> >(\"Helicities\",vector<int>{Helicity::neghel,Helicity::poshel});\n    for(auto hv : helvals) {\n      Helicity hel(hv);\n      _hels.push_back(hel);\n      produces<HelixSeedCollection>(Helicity::name(hel));\n    }\n\n     if (_diag != 0) _hmanager = art::make_tool<ModuleHistToolBase>(pset.get<fhicl::ParameterSet>(\"diagPlugin\"));\n     else            _hmanager = std::make_unique<ModuleHistToolBase>();\n\n     //    _data.result    = &_hfit;\n\n    _chi2hfit.setRobustHelixFitter(&_hfit);\n\n  }\n\n  RobustHelixFinder::~RobustHelixFinder(){}\n\n  //-----------------------------------------------------------------------------\n  void RobustHelixFinder::beginRun(art::Run& ) {\n    mu2e::GeomHandle<mu2e::Calorimeter> ch;\n\n    _hfit.setCalorimeter(ch.get());\n    _chi2hfit.setCalorimeter(ch.get());\n  }\n  //--------------------------------------------------------------------------------\n\n  void RobustHelixFinder::beginJob() {\n\n    _stmva.initMVA();\n    _nsmva.initMVA();\n    if (_debug > 0)\n      {\n\tstd::cout << \"RobustHeilxFinder Stereo Hit MVA parameters: \" << std::endl;\n\t_stmva.showMVA();\n\tstd::cout << \"RobustHeilxFinder Non-Stereo Hit MVA parameters: \" << std::endl;\n\t_nsmva.showMVA();\n      }\n\n    if (_diag > 0){\n      art::ServiceHandle<art::TFileService> tfs;\n      _niter = tfs->make<TH1F>( \"niter\" , \"Number of Fit Iteraions\",201,-0.5,200.5);\n      _niterxy = tfs->make<TH1F>( \"niterxy\" , \"Number of XY Fit Iteraions\",201,-0.5,200.5);\n      _niterfz = tfs->make<TH1F>( \"niterfz\" , \"Number of FZ Fit Iteraions\",201,-0.5,200.5);\n      _nitermva = tfs->make<TH1F>( \"nitermva\" , \"Number of MVA Fit Iteraions\",201,-0.5,200.5);\n      _hmanager->bookHistograms(tfs);\n    }\n  }\n\n  void RobustHelixFinder::produce(art::Event& event ) {\n      \n    _tracker = _alignedTracker_h.getPtr(event.id()).get();\n    _hfit.setTracker    (_tracker);\n    _chi2hfit.setTracker    (_tracker);\n\n    // find input\n    auto const& tcH = event.getValidHandle(_tcToken);\n    const TimeClusterCollection& tccol(*tcH);\n\n    auto const& chH = event.getValidHandle(_chToken);\n    const ComboHitCollection& chcol(*chH);\n\n    // create output: seperate by helicity\n    std::map<Helicity,unique_ptr<HelixSeedCollection>> helcols;\n    int counter(0);\n    for( auto const& hel : _hels) {\n      helcols[hel] = unique_ptr<HelixSeedCollection>(new HelixSeedCollection());\n      _data.nseeds [counter] = 0;\n      ++counter;\n    }\n\n    _data.event       = &event;\n    //    _data.result      = &_hfit;\n    _data.nTimePeaks  = tccol.size();\n\n    _hfResult._chcol  = &chcol;\n\n    // create initial helicies from time clusters: to begin, don't specificy helicity\n    for (size_t index=0;index< tccol.size();++index) {\n      const auto& tclust = tccol[index];\n      HelixSeed hseed;\n      hseed._status.merge(TrkFitFlag::TPRHelix);\n      //clear the variables in hfResult\n      _hfResult.clearTempVariables();\n\n      //set variables used for searching the helix candidate\n      _hfResult._hseed              = hseed;\n      _hfResult._timeCluster        = &tclust;\n      _hfResult._hseed._hhits.setParent(chcol.parent());\n      _hfResult._hseed._t0          = tclust._t0;\n      _hfResult._hseed._timeCluster = art::Ptr<TimeCluster>(tcH,index);\n      // copy combo hits\n      fillFaceOrderedHits(_hfResult);\n\n      //skip the reconstruction if there are few strawHits\n      if (_hfResult._nFiltStrawHits < _minnsh)                  continue;\n\n      // filter hits and test\n      int nFilteredSh(0);\n      if (_prefilter) prefilterHits(_hfResult,nFilteredSh);\n\n      if ((_hfResult._nFiltStrawHits - nFilteredSh) < _minnsh)  continue;\n\n      _hfResult._hseed._status.merge(TrkFitFlag::hitsOK);\n      if (_diag) _hfResult._diag.circleFitCounter = 0;\n\n      // initial circle fit\n\n      if (_reducedchi2){\n\t_chi2hfit.fitChi2Circle(_hfResult, _targetcon);\n      }else{\n\t_hfit.fitCircle(_hfResult, _targetconInit, _useTripletAreaWt);//require consistency for the trajectory of being produced in the Al stopping target\n      }\n\n      if (_diag && _reducedchi2) {\n\t_hfResult._diag.nShFitCircle = _hfResult._nXYSh;\n\t_hfResult._diag.nChFitCircle = _hfResult._sxy.qn()-1;//take into account one hit form the stopping target center\n      }\n      //check the number of points associated with the result of the circle fit\n      // if (_hfResult._nXYSh < _minnsh)                           continue;\n\n      if (_hfResult._hseed._status.hasAnyProperty(TrkFitFlag::circleOK)) {\n\t// loop over helicities.\n\tunsigned    helCounter(0);\n\tHelixSeed   helixSeed_from_fitCircle = _hfResult._hseed;\n\n\tstd::vector<HelixSeed>          helix_seed_vec;\n\n\tfor(auto const& hel : _hels ) {\n\t  // tentatively put a copy with the specified helicity in the appropriate output vector\n\t  RobustHelixFinderData tmpResult(_hfResult);\n\t  tmpResult._hseed._helix._helicity = hel;\n\n\t  //fit the helix: refine the XY-circle fit + performs the ZPhi fit\n\t  // it also performs a clean-up of the hits with large residuals\n\t  if (_reducedchi2)\n\t    fitChi2Helix(tmpResult);\n\t  else\n\t    fitHelix(tmpResult);\n\n\n\t  if (tmpResult._hseed.status().hasAnyProperty(_saveflag)){\n\t    //fill the hits in the HelixSeedCollection\n\t    fillGoodHits(tmpResult);\n\n\t    helix_seed_vec.push_back(tmpResult._hseed);\n\n\t    // HelixSeedCollection* hcol = helcols[hel].get();\n\t    // hcol->push_back(tmpResult._hseed);\n\n\t    if (_diag > 0) {\n\t      fillPluginDiag(tmpResult, helCounter);\n\t    }\n\t  }\n\t  ++helCounter;\n\t}//end loop over the helicity\n\n\tif (helix_seed_vec.size() == 0)                       continue;\n\n\tint    index_best(-1);\n\tpickBestHelix(helix_seed_vec, index_best);\n\n\tif ( (index_best>=0) && (index_best < 2) ){\n\t  Helicity              hel_best = helix_seed_vec[index_best]._helix._helicity;\n\t  HelixSeedCollection*  hcol     = helcols[hel_best].get();\n\t  hcol->push_back(helix_seed_vec[index_best]);\n\t} else if (index_best == 2){//both helices need to be saved\n\n\t  for (unsigned k=0; k<_hels.size(); ++k){\n\t    Helicity              hel   = helix_seed_vec[k]._helix._helicity;\n\t    HelixSeedCollection*  hcol  = helcols[hel].get();\n\t    hcol->push_back(helix_seed_vec[k]);\n\t  }\n\t}\n\n      }\n\n    }\n    // put final collections into event\n    if (_diag > 0) _hmanager->fillHistograms(&_data);\n\n    for(auto const& hel : _hels ) {\n      event.put(std::move(helcols[hel]),Helicity::name(hel));\n    }\n  }\n//--------------------------------------------------------------------------------\n// function to select the best Helix among the results of the two helicity hypo\n//--------------------------------------------------------------------------------\n  void  RobustHelixFinder::pickBestHelix(std::vector<HelixSeed>& HelVec, int &Index_best){\n    if (HelVec.size() == 1) {\n      Index_best = 0;\n      return;\n    }\n\n    const HelixSeed           *h1, *h2;\n    const ComboHitCollection  *tlist, *clist;\n    int                        nh1, nh2;\n\n    h1     = &HelVec[0];\n//------------------------------------------------------------------------------\n// check if an AlgorithmID collection has been created by the process\n//-----------------------------------------------------------------------------\n    tlist  = &h1->hits();\n    nh1    = tlist->size();\n\n    h2     = &HelVec[1];\n//-----------------------------------------------------------------------------\n// at Mu2e, 2 helices with different helicity could be duplicates of each other\n//-----------------------------------------------------------------------------\n    clist  = &h2->hits();\n    nh2    = clist->size();\n//-----------------------------------------------------------------------------\n// pick the helix with the largest number of hits\n//-----------------------------------------------------------------------------\n    if (nh2 > nh1) {\n//-----------------------------------------------------------------------------\n// h2 is a winner, no need to save h1\n//-----------------------------------------------------------------------------\n      Index_best = 1;\n      return;\n    }\n    else if (nh1 > nh2){\n//-----------------------------------------------------------------------------\n// h1 is a winner, mark h2 in hope that it will be OK, continue looping\n//-----------------------------------------------------------------------------\n      Index_best = 0;\n      return;\n    }\n\n//-----------------------------------------------------------------------------\n// in case they have the exact amount of hits, pick the one with better chi2dZphi\n//-----------------------------------------------------------------------------\n    if (nh1 == nh2) {\n      float   chi2dZphi_h1 = h1->helix().chi2dZPhi();\n      float   chi2dZphi_h2 = h2->helix().chi2dZPhi();\n      if (chi2dZphi_h1 < chi2dZphi_h2){\n\tIndex_best = 0;\n\treturn;\n      }else {\n\tIndex_best = 1;\n\treturn;\n      }\n    }\n\n  }\n\n//--------------------------------------------------------------------------------\n//\n//--------------------------------------------------------------------------------\n  void RobustHelixFinder::fillGoodHits(RobustHelixFinderData& helixData){\n\n    ComboHit*     hit(0);\n    unsigned      nhits = helixData._chHitsToProcess.size();\n\n    for (unsigned f=0; f<nhits; ++f){\n      hit = &helixData._chHitsToProcess[f];\n      if (hit->_flag.hasAnyProperty(_outlier))     continue;\n\n      ComboHit                hhit(*hit);\n      helixData._hseed._hhits.push_back(hhit);\n    }\n\n    if (_diag){\n      HelixTool helTool(&helixData._hseed, _tracker);//_trackerRIn, _trackerROut, _trackerLength);\n      helixData._diag.nLoops            = helTool.nLoops();\n      helixData._diag.meanHitRadialDist = helTool.meanHitRadialDist();\n    }\n  }\n\n\n  void RobustHelixFinder::fillMVA(RobustHelixFinderData& helixData)\n  {\n    RobustHelix& helix = helixData._hseed._helix;\n\n    static XYZVec  zaxis(0.0,0.0,1.0); // unit in z direction\n    ComboHit*      hhit(0);\n\n    for (unsigned f=0; f<helixData._chHitsToProcess.size(); ++f){\n      hhit = &helixData._chHitsToProcess[f];\n\n      if (hhit->_flag.hasAnyProperty(_outlier))   continue;\n\n      const XYZVec& wdir = hhit->wdir();\n      XYZVec wtdir = zaxis.Cross(wdir); // transverse direction to the wire\n      XYZVec cvec = PerpVector(hhit->pos() - helix.center(),Geom::ZDir());// direction from the circle center to the hit\n      XYZVec cdir = cvec.Unit();        // direction from the circle center to the hit\n      XYZVec cperp = zaxis.Cross(cdir); // direction perp to the radius\n\n      XYZVec hpos = hhit->pos();      // this sets the z position to the hit z\n      helix.position(hpos);                     // this computes the helix expectation at that z\n      XYZVec dh = hhit->pos() - hpos; // this is the vector between them\n\n      _vmva._dtrans = fabs(dh.Dot(wtdir));              // transverse projection\n      _vmva._dwire = fabs(dh.Dot(wdir));               // projection along wire direction\n      _vmva._drho = fabs(sqrtf(cvec.mag2()) - helix.radius()); // radius difference\n      _vmva._dphi = fabs(hhit->helixPhi() - helix.circleAzimuth(hhit->pos().z())); // azimuth difference WRT circle center\n      _vmva._hhrho = sqrtf(cvec.mag2());            // hit transverse radius WRT circle center\n      _vmva._hrho = sqrtf(hpos.Perp2());            // hit detector transverse radius\n      _vmva._rwdot = fabs(wdir.Dot(cdir));  // compare directions of radius and wire\n\n      // compute the total resolution including hit and helix parameters first along the wire\n      float wres2 = std::pow(hhit->posRes(StrawHitPosition::wire),(int)2) +\n\tstd::pow(_cradres*cdir.Dot(wdir),(int)2) +\n\tstd::pow(_cperpres*cperp.Dot(wdir),(int)2);\n\n      // transverse to the wires\n      float wtres2 = std::pow(hhit->posRes(StrawHitPosition::trans),(int)2) +\n\tstd::pow(_cradres*cdir.Dot(wtdir),(int)2) +\n\tstd::pow(_cperpres*cperp.Dot(wtdir),(int)2);\n\n      _vmva._chisq = sqrtf( _vmva._dwire*_vmva._dwire/wres2 + _vmva._dtrans*_vmva._dtrans/wtres2 );\n      _vmva._dt = hhit->time() - helixData._hseed._t0.t0();\n\n      if (hhit->_flag.hasAnyProperty(StrawHitFlag::stereo))\n\t{\n\t  hhit->_qual = _stmva.evalMVA(_vmva._pars);\n\t} else {\n\thhit->_qual = _nsmva.evalMVA(_vmva._pars);\n      }\n    }\n  }\n\n  bool RobustHelixFinder::filterHitsMVA(RobustHelixFinderData& helixData)\n  {\n    bool           changed(false);\n    ComboHit*      hhit(0);\n\n    for (unsigned f=0; f<helixData._chHitsToProcess.size(); ++f){\n\n      hhit = &helixData._chHitsToProcess[f];\n\n      bool oldout = hhit->_flag.hasAnyProperty(_outlier);\n\n      if (hhit->_qual < _minmva ) hhit->_flag.merge(_outlier);\n      else                        hhit->_flag.clear(_outlier);\n\n      changed |= oldout != hhit->_flag.hasAnyProperty(_outlier);\n    }\n\n    return changed;\n  }\n\n  int  RobustHelixFinder::filterChi2XYHits(RobustHelixFinderData& helixData)\n  {\n    //reset the value of the XY fit result\n    helixData._hseed._status.clear(TrkFitFlag::circleOK);\n\n\n    ComboHit*     hit(0);\n\n    //perform a reduced chi2 fit\n    _chi2hfit.refineFitXY(helixData, _targetcon);\n\n    int           changed(0);\n    int           oldNHitsSh = helixData._nXYSh;\n\n    RobustHelix&  helix      = helixData._hseed._helix;\n\n    // helixData._hseed._status.clear(TrkFitFlag::circleOK);\n\n    if (helixData._nXYSh >= _minnsh) {//update the helix info\n      //need to update the weights in the LSqsum\n      _chi2hfit.refineFitXY(helixData, _targetcon);\n\n      //      updateHelixXYInfo(helixData);//should be unnecessary!FIXME!\n\n      //search and remove the worst hit(s) if necessary\n      HitInfo_t  worstHit;\n      float      chi2d = helixData._sxy.chi2DofCircle();\n\n      while( (chi2d > _maxchi2dxy) && (helixData._nXYSh >= _minnsh) && (worstHit.face >=0)){\n\t//reset the content of the worstHit\n\tworstHit.face          = -1;\n\tworstHit.panel         = -1;\n\tworstHit.panelHitIndex = -1;\n\t//\tworstHit.weightXY      =  0;\n\n\tsearchWorstHitXY(helixData, worstHit);\n\n\tif (worstHit.face >=0){//check if a bad was found or not\n\t  hit    = &helixData._chHitsToProcess[worstHit.panelHitIndex];\n\n\t  hit->_flag.merge(_outlier);\n\n\t  helixData._sxy.removePoint(hit->pos().x(), hit->pos().y(), hit->_xyWeight);//worstHit.weightXY);\n\t  helixData._nXYSh -= hit->nStrawHits();\n\t  helixData._nXYCh -= 1;\n\t  _chi2hfit.refineFitXY(helixData, _targetcon);//should be unnecessary!FIXME!\n\t  chi2d             = helixData._sxy.chi2DofCircle();\n\t}\n      }\n\n      //at this point\n      if (_hfit.goodCircle(helix) && (helixData._nXYSh >= _minnsh))  {\n\thelixData._hseed._status.merge(TrkFitFlag::circleOK);\n\n\tif (_diag){\n\t  helixData._diag.rsxy_1     = helix._radius;\n\t  helixData._diag.chi2dsxy_1 = helixData._sxy.chi2DofCircle();\n\t  helixData._diag.nshsxy_1   = helixData._nXYSh;\n\t}\n      }\n    }\n\n    changed = oldNHitsSh - helixData._nXYSh;\n\n    return changed;\n  }\n\n\n  // 3d selection on top of radial selection\n  int RobustHelixFinder::filterChi2ZPhiHits(RobustHelixFinderData& helixData)\n  {\n\n    //check if the initial value of lambda and phi0 are physical\n    if (!helixData._hseed._status.hasAnyProperty(TrkFitFlag::phizOK))  return false;\n\n    //reset the value of the ZPhi fit result\n    helixData._hseed._status.clear(TrkFitFlag::phizOK);\n\n    RobustHelix&  helix  = helixData._hseed._helix;\n\n    int           changed(0);\n    int           oldNHitsSh = helixData._nZPhiSh;\n\n    ComboHit*     hit(0);\n\n    // float         z, phi, phi_ref, dx, dy, dphi, resid, wt;\n\n    //    helixData._hseed._status.clear(TrkFitFlag::circleOK);\n    _chi2hfit.refineFitZPhi(helixData);\n\n    if (helixData._nZPhiSh >= _minnsh) {//update the helix info\n      //need to update the weights in the LSqsum\n      _chi2hfit.refineFitZPhi(helixData);\n\n      //      updateHelixZPhiInfo(helixData);//should be unnecessary!FIXME!\n\n      //search and remove the worst hit(s) if necessary\n      HitInfo_t  worstHit;\n      float      chi2d = helixData._szphi.chi2DofLine();\n\n      while( (chi2d > _maxchi2dzphi) && (helixData._nZPhiSh >= _minnsh) && (worstHit.face >=0)){\n\t//reset the content of the worstHit\n\tworstHit.face          = -1;\n\tworstHit.panel         = -1;\n\tworstHit.panelHitIndex = -1;\n\n\tsearchWorstHitZPhi(helixData, worstHit);\n\n\tif (worstHit.face >=0){//check if a bad was found or not\n\t  hit    = &helixData._chHitsToProcess[worstHit.panelHitIndex];\n\n\t  hit->_flag.merge(_outlier);\n\n\t  helixData._szphi.removePoint(hit->pos().z(), hit->helixPhi(), hit->_zphiWeight);\n\t  helixData._nZPhiSh -= hit->nStrawHits();\n\t  _chi2hfit.refineFitZPhi(helixData);\n\t  //\t  updateHelixZPhiInfo(helixData);//should be unnecessary!FIXME!\n\t  chi2d               = helixData._szphi.chi2DofLine();\n\t}\n      }\n\n      //at this point\n      if (_hfit.goodFZ(helix) && (helixData._nZPhiSh >= _minnsh))  {\n\thelixData._hseed._status.merge(TrkFitFlag::phizOK);\n\n\tif (_diag){\n\t  helixData._diag.lambdaszphi_1 = helix._lambda;\n\t  helixData._diag.chi2dszphi_1  = helixData._szphi.chi2DofLine();\n\t  helixData._diag.nshszphi_1    = helixData._nZPhiSh;\n\t}\n      }\n    }\n\n    changed = oldNHitsSh - helixData._nZPhiSh;\n\n    return changed;\n  }\n\n\n  // 3d selection on top of radial selection\n  bool RobustHelixFinder::filterHits(RobustHelixFinderData& helixData)\n  {\n    RobustHelix& helix = helixData._hseed._helix;\n    bool changed(false);\n    static XYZVec zaxis(0.0,0.0,1.0); // unit in z direction\n    int      nGoodSH(0);\n\n    // loop over hits\n    ComboHit*     hit(0);\n    FaceZ_t*      facez;\n\n    int           nhitsFace(0);\n    float         chCounter(1e-10), chi2dZPhi(0);\n\n    for (int f=0; f<StrawId::_ntotalfaces; ++f){\n      facez     = &helixData._oTracker[f];\n\n      float      minChi2(_maxchisq);\n      HitInfo_t  indexBestComboHit;\n\n      nhitsFace = facez->nChHits();\n      if (nhitsFace == 0)                        continue;\n      int        idFirstFaceCh(facez->idChBegin);\n      for (int ip=0; ip<nhitsFace; ++ip){\n\thit = &helixData._chHitsToProcess[idFirstFaceCh + ip];\n\tbool trash=hit->_flag.hasAnyProperty(_outlier);\n\tif (trash)                               continue;\n\n\tfloat hphi = polyAtan2(hit->pos().y(),hit->pos().x());//phi();\n\tfloat dphi = fabs(Angles::deltaPhi(hphi,helix.fcent()));\n\n\tconst XYZVec& wdir = hit->wdir();\n\tXYZVec wtdir = zaxis.Cross(wdir);   // transverse direction to the wire\n\tXYZVec cvec = PerpVector(hit->pos() - helix.center(),Geom::ZDir()); // direction from the circle center to the hit\n\tXYZVec cdir = cvec.Unit();          // direction from the circle center to the hit\n\tXYZVec cperp = zaxis.Cross(cdir);   // direction perp to the radius\n\n\tXYZVec hpos = hit->pos(); // this sets the z position to the hit z\n\thelix.position(hpos);                // this computes the helix expectation at that z\n\tXYZVec dh = hit->pos() - hpos;   // this is the vector between them\n\tfloat dtrans = fabs(dh.Dot(wtdir)); // transverse projection\n\tfloat dwire = fabs(dh.Dot(wdir));   // projection along wire direction\n\n\t// compute the total resolution including hit and helix parameters first along the wire\n\tfloat wres2 = std::pow(hit->posRes(StrawHitPosition::wire),(int)2) +\n\t  std::pow(_cradres*cdir.Dot(wdir),(int)2) +\n\t  std::pow(_cperpres*cperp.Dot(wdir),(int)2);\n\t// transverse to the wires\n\tfloat wtres2 = std::pow(hit->posRes(StrawHitPosition::trans),(int)2) +\n\t  std::pow(_cradres*cdir.Dot(wtdir),(int)2) +\n\t  std::pow(_cperpres*cperp.Dot(wtdir),(int)2);\n\n\tfloat chisq = dwire*dwire/wres2 + dtrans*dtrans/wtres2;\n\n\tif( dphi > _maxphisep || fabs(dwire) > _maxdwire || fabs(dtrans) > _maxdtrans || chisq > _maxchisq)\n\t  {\n\t    changed = true;\n\t  }\n\n\tif ( chisq <= minChi2)\n\t  {\n\t    minChi2 = chisq;\n\n\t    indexBestComboHit.face          = f;\n\t    indexBestComboHit.panel         = hit->strawId().uniquePanel();\n\t    indexBestComboHit.panelHitIndex = facez->idChBegin + ip;\n\t  }\n\n\t//flagg all hits within the face as outlier. Only the best found will be \"cleared\"\n\thit->_flag.merge(_outlier);\n\n      }//end loop over the panels\n\n      //remove the outlier flag\n      if (indexBestComboHit.face >=0 ) {\n\thit     = &helixData._chHitsToProcess[indexBestComboHit.panelHitIndex];\n\n\t//remove the outlier flag\n\thit->_flag.clear(StrawHitFlag::outlier);\n\tnGoodSH += hit->nStrawHits();\n\n\tchi2dZPhi += minChi2;\n\tchCounter += 1.;\n      }\n    }//end loop over the faces\n\n    helixData._nZPhiSh = nGoodSH;\n\n    //update the value of the chi2ZPhi\n    helix._chi2dZPhi   = chi2dZPhi/chCounter;\n\n    if (_diag) {\n      helixData._diag.chi2dZPhi = chi2dZPhi/chCounter;\n    }\n\n    return changed;\n  }\n\n  void     RobustHelixFinder::findMissingHits(RobustHelixFinderData& helixData){\n    FaceZ_t*   facez;\n\n    ComboHit*  hit(0);\n    int        nhitsPerPanel(0), n_added_points(0);\n    HitInfo_t  bestHit;\n\n    float      wtXY(0),wtZPhi(0),dr(0),dphi(0), phi_pred(0);\n    float      drChi2, dphiChi2, hitChi2Max(_maxchi2dxy), hitChi2;\n\n    //get  dfdz and phi0\n    float      dfdz = helixData._szphi.dfdz();\n    float      phi0 = helixData._szphi.phi0();\n    //get the circle info\n    float      r    = helixData._sxy.radius();\n    XYVec      helCenter;\n    helCenter.SetX( helixData._sxy.x0());\n    helCenter.SetY( helixData._sxy.y0());\n\n\n  NEXT_ITERATION:;\n    //reset the info of the best-hit\n    bestHit.face          = -1;\n    bestHit.panel         = -1;\n    bestHit.panelHitIndex = -1;\n    // bestHit.weightXY      = 1.;\n    // bestHit.weightZPhi    = 1.;\n\n    hitChi2Max            = _maxchi2dxy;\n\n    for (int f=0; f<StrawId::_ntotalfaces; ++f){\n      facez         = &helixData._oTracker[f];\n      bool       isFaceUsed(false);\n      HitInfo_t  hitInfo;\n\n      nhitsPerPanel  = facez->nChHits();\n\n      if (nhitsPerPanel == 0)                       continue;\n\n      for (int i=0; i<nhitsPerPanel;++i){\n\thit =  &helixData._chHitsToProcess[facez->idChBegin +i];\n\tif (!hit->_flag.hasAnyProperty(_outlier))   {\n\t  isFaceUsed = true;\n\t  break;//skip the faces where there is already a hit\n\t}\n\tXYVec rvec = (XYVec(hit->pos().x(),hit->pos().y())-helCenter);\n\tdr       = sqrtf(rvec.Mag2()) - r;\n\twtXY     = _chi2hfit.evalWeightXY(*hit, helCenter);\n\tdrChi2   = sqrtf(dr*dr*wtXY);\n\n\tphi_pred = hit->pos().z()*dfdz + phi0;\n\tdphi     = phi_pred - hit->helixPhi();\n\twtZPhi   = _chi2hfit.evalWeightZPhi(*hit,helCenter,r);\n\tdphiChi2 = sqrtf(dphi*dphi*wtZPhi);\n\n\thitChi2  = (drChi2 + dphiChi2)/2.;\n\n\tif ( (drChi2<_maxchi2dxy) && (dphiChi2<_maxchi2dzphi) && (hitChi2 < hitChi2Max)){\n\t  hitChi2Max  = hitChi2;\n\n\t  hitInfo.face          = f;\n\t  hitInfo.panel         = hit->strawId().uniquePanel();\n\t  hitInfo.panelHitIndex = facez->idChBegin + i;\n\n\t  //update weight info\n\t  hit->_xyWeight        = wtXY;\n\t  hit->_zphiWeight      = wtZPhi;\n\n\t}\n      }//end loop over the hits within the panel\n\n      if( (!isFaceUsed) && (hitInfo.face >=0 ) ) {\n\tbestHit.face          = hitInfo.face         ;\n\tbestHit.panel         = hitInfo.panel        ;\n\tbestHit.panelHitIndex = hitInfo.panelHitIndex;\n      }\n    }//end loop pver the faces\n\n\n    if ( (bestHit.face >= 0) ){\n      hit    = &helixData._chHitsToProcess[bestHit.panelHitIndex];\n\n\n      //add the point\n      hit->_flag.clear(_outlier);\n\n      helixData._sxy.addPoint(hit->pos().x(), hit->pos().y(), hit->_xyWeight);//bestHit.weightXY);\n      helixData._nXYSh   += hit->nStrawHits();\n\n      helixData._szphi.addPoint(hit->pos().z(), hit->helixPhi(), hit->_zphiWeight);//bestHit.weightZPhi);\n      helixData._nZPhiSh += hit->nStrawHits();\n\n\n      //update the helix\n      updateChi2HelixInfo(helixData);\n\n      ++n_added_points;\n\t                              goto NEXT_ITERATION;\n    }\n\n    if (_diag) helixData._diag.nrescuedhits = n_added_points;\n\n  }\n\n\n\n\n  void RobustHelixFinder::prefilterHits(RobustHelixFinderData& HelixData, int& NRemovedStrawHits)\n  {\n    // ComboHitCollection& hhits = HelixData._hseed._hhits;\n\n    bool changed(true);\n    // size_t nhit = hhits.size();\n    int nhit = HelixData._nFiltComboHits;\n\n    ComboHit*  hit(0);\n    ComboHit*  worsthit(0);\n\n    NRemovedStrawHits = 0;\n\n    while (changed && nhit > 0)\n      {\n\tnhit = 0;\n\tchanged = false;\n\taccumulator_set<float, stats<tag::median(with_p_square_quantile) > > accx;\n\taccumulator_set<float, stats<tag::median(with_p_square_quantile) > > accy;\n\n\tfor (unsigned f=0; f<HelixData._chHitsToProcess.size(); ++f){\n\t  hit =  &HelixData._chHitsToProcess[f];\n\t  bool trashHit=hit->_flag.hasAnyProperty(_outlier);\n\t  if (trashHit)                              continue;\n\t  accx(hit->_pos.x());\n\t  accy(hit->_pos.y());\n\t  ++nhit;\n\t}\n\n\tfloat mx = extract_result<tag::median>(accx);\n\tfloat my = extract_result<tag::median>(accy);\n\tfloat mphi = polyAtan2(my,mx);//atan2f(my,mx);\n\n\tfloat maxdphi{0.0};\n\t// auto worsthit = hhits.end();\n\tfor (unsigned f=0; f<HelixData._chHitsToProcess.size(); ++f){\n\t  hit =  &HelixData._chHitsToProcess[f];\n\t  bool trashHit = hit->_flag.hasAnyProperty(_outlier);\n\t  if (trashHit)                              continue;\n\t  float phi  = polyAtan2(hit->pos().y(), hit->pos().x());//ihit->pos().phi();\n\t  float dphi = fabs(Angles::deltaPhi(phi,mphi));\n\t  if(dphi > maxdphi)\n\t    {\n\t      maxdphi = dphi;\n\t      worsthit = hit;\n\t    }\n\t}//end loop over the faces\n\n\tif (maxdphi > _maxphisep)\n\t  {\n\t    worsthit->_flag.merge(_outlier);\n\t    NRemovedStrawHits += worsthit->nStrawHits();\n\t    changed = true;\n\t  }\n      }\n  }\n\n  void RobustHelixFinder::updateT0(RobustHelixFinderData& helixData)\n  {\n  // compute the pitch\n    float pitch = helixData._hseed.helix().pitch();\n    accumulator_set<float, stats<tag::weighted_variance(lazy)>, float > terr;\n  // update t0 from calo cluster according to current pitch\n    if (helixData._hseed.caloCluster().isNonnull()){\n      float cwt = std::pow(1.0/_ttcalc.caloClusterTimeErr(),2);\n      terr(_ttcalc.caloClusterTime(*helixData._hseed.caloCluster(),pitch),weight=cwt);\n    }\n    ComboHit*      hit(0);\n    float hwt = std::pow(1.0/_ttcalc.strawHitTimeErr(),2);\n    for (unsigned f=0; f<helixData._chHitsToProcess.size(); ++f){\n      hit = &helixData._chHitsToProcess[f];\n      if (hit->_flag.hasAnyProperty(_outlier))   continue;\n      terr(_ttcalc.comboHitTime(*hit,pitch),weight=hwt);\n    }//end faces loop\n    if (sum_of_weights(terr) > 0.0)\n      {\n\thelixData._hseed._t0._t0 = extract_result<tag::weighted_mean>(terr);\n\thelixData._hseed._t0._t0err = sqrtf(std::max(float(0.0),extract_result<tag::weighted_variance(lazy)>(terr))/extract_result<tag::count>(terr));\n      }\n  }\n\n  //------------------------------------------------------------------------------------------\n  void     RobustHelixFinder::fillFaceOrderedHits(RobustHelixFinderData& HelixData){\n\n    const vector<StrawHitIndex>& shIndices = HelixData._timeCluster->hits();\n    mu2e::RobustHelixFinderData::ChannelID cx, co;\n\n    int     size  = shIndices.size();\n    int     nFiltComboHits(0), nFiltStrawHits(0);\n    // int nTotalStations = _tracker->nStations();\n    //--------------------------------------------------------------------------------\n    int loc;\n    StrawHitFlag flag;\n\n    //sort the hits by z coordinate\n    ComboHitCollection ordChCol;\n    ordChCol.reserve(size);\n\n    for (int i=0; i<size; ++i) {\n      loc = shIndices[i];\n      const ComboHit& ch  = (*_hfResult._chcol)[loc];\n      if(ch.flag().hasAnyProperty(_hsel) && !ch.flag().hasAnyProperty(_hbkg) ) {\n\tordChCol.push_back(ComboHit(ch));\n      }\n    }\n    std::sort(ordChCol.begin(), ordChCol.end(),panelcomp());//zcomp());\n\n\n    if (_debug>0){\n      printf(\"[RobustHelixFinder::FillHits]-----------------------------------------------------------\\n\");\n      printf(\"[RobustHelixFinder::FillHits]     i     Face     Panel      X         Y         Z        \\n\");\n      printf(\"[RobustHelixFinder::FillHits]-----------------------------------------------------------\\n\");\n    }\n\n    for (unsigned i=0; i<ordChCol.size(); ++i) {\n      // loc = shIndices[i];\n      // const ComboHit& ch  = _hfResult._chcol->at(loc);\n      ComboHit& ch = ordChCol[i];\n\n      //    if(ch.flag().hasAnyProperty(_hsel) && !ch.flag().hasAnyProperty(_hbkg) ) {\n      ComboHit hhit(ch);\n      hhit._flag.clear(StrawHitFlag::resolvedphi);\n\n      _hfResult._chHitsToProcess.push_back(hhit);\n\n      cx.Station                 = ch.strawId().station();//straw.id().getStation();\n      cx.Plane                   = ch.strawId().plane() % 2;//straw.id().getPlane() % 2;\n      cx.Face                    = ch.strawId().face();\n      cx.Panel                   = ch.strawId().panel();//straw.id().getPanel();\n\n      // get Z-ordered location\n      HelixData.orderID(&cx, &co);\n\n      int os       = co.Station;\n      int of       = co.Face;\n      int op       = co.Panel;\n\n      _hfResult._chHitsWPos.push_back(XYWVec(hhit.pos(),  of, hhit.nStrawHits()));\n\n      int       stationId = os;\n      int       faceId    = of + stationId*StrawId::_nfaces*FaceZ_t::kNPlanesPerStation;//RobustHelixFinderData::kNFaces;\n      // int       panelId   = op + faceId*RobustHelixDataFinderData::kNPanelsPerFace;\n      FaceZ_t* fz        = &HelixData._oTracker[faceId];\n      PanelZ_t*pz        = &fz->panelZs[op];\n\n      //\tpz->_chHitsToProcess.push_back(hhit);//[fz->fNHits] = hhit;\n      //\tpz->fNHits  = pz->fNHits + 1;\n      if (pz->idChBegin < 0 ){\n\tpz->idChBegin = _hfResult._chHitsToProcess.size() - 1;\n\tpz->idChEnd   = _hfResult._chHitsToProcess.size();\n      } else {\n\tpz->idChEnd   = _hfResult._chHitsToProcess.size();\n      }\n\n      if (fz->idChBegin < 0 ){\n\tfz->idChBegin = _hfResult._chHitsToProcess.size() - 1;\n\tfz->idChEnd   = _hfResult._chHitsToProcess.size();\n      } else {\n\tfz->idChEnd   = _hfResult._chHitsToProcess.size();\n      }\n\n      if (_debug>0){\n\tprintf(\"[RobustHelixFinder::FillHits] %4i %6i %10i %10.3f %10.3f %10.3f\\n\", nFiltComboHits, faceId, op, ch.pos().x(), ch.pos().y(), ch.pos().z() );\n      }\n\n      // if (pz->nChHits() > PanelZ_t::kNMaxPanelHits) printf(\"[RobustHelixDataFinderAlg::fillFaceOrderedHits] number of hits with the panel exceed the limit: NHits =  %i MaxNHits = %i\\n\", pz->fNHits, PanelZ_t::kNMaxPanelHits);\n      ++nFiltComboHits;\n      nFiltStrawHits += ch.nStrawHits();\n      //      }\n    }\n    // }\n\n    HelixData._nFiltComboHits = nFiltComboHits;  //ComboHit counter\n    HelixData._nFiltStrawHits = nFiltStrawHits;  //StrawHit counter\n\n    if (_diag) {\n      HelixData._diag.nChPPanel = 0;\n      HelixData._diag.nChHits   = HelixData._chHitsToProcess.size();\n\n      FaceZ_t*      facez;\n      PanelZ_t*     panelz;\n\n      int           nhitsFace(0);\n\n      if (_debug>0){\n\tprintf(\"[RobustHelixFinder::ReadHits]-----------------------------------------------------------\\n\");\n\tprintf(\"[RobustHelixFinder::ReadHits]    i     Face     Panel      X         Y         Z      \\n\");\n\tprintf(\"[RobustHelixFinder::ReadHits]-----------------------------------------------------------\\n\");\n\n\tfor (unsigned i=0; i<HelixData._chHitsToProcess.size(); ++i){\n\t  ComboHit* ch = &HelixData._chHitsToProcess[i];\n\t  printf(\"[RobustHelixFinder::ReadHits] %4i %6i %10i %10.3f %10.3f %10.3f\\n\", i, ch->strawId().uniqueFace(), ch->strawId().panel(), ch->pos().x(), ch->pos().y(), ch->pos().z() );\n\t}\n\n\n\tprintf(\"[RobustHelixFinder::ReadIndeces]----------------------------------------------------------------------\\n\");\n\tprintf(\"[RobustHelixFinder::ReadIndeces]    Face        fBg       fEnd       Panel       pBg        pEnd      \\n\");\n\tprintf(\"[RobustHelixFinder::ReadIndeces]----------------------------------------------------------------------\\n\");\n\n\tfor (int f=0; f<StrawId::_ntotalfaces; ++f){\n\t  facez     = &HelixData._oTracker[f];\n\n\t  for (int p=0; p<FaceZ_t::kNPanels; ++p){\n\t    panelz = &facez->panelZs[p];\n\t    if (panelz->nChHits() != 0) printf(\"[RobustHelixFinder::ReadIndeces] %6i %10i %10i %10i %10i %10i\\n\", f, facez->idChBegin, facez->idChEnd, p, panelz->idChBegin, panelz->idChEnd);\n\t  }\n\t}\n      }\n      for (int f=0; f<StrawId::_ntotalfaces; ++f){\n\tfacez     = &HelixData._oTracker[f];\n\n\tfor (int p=0; p<FaceZ_t::kNPanels; ++p){\n\t  panelz = &facez->panelZs[p];\n\t  nhitsFace = panelz->nChHits();\n\t  if ( nhitsFace > HelixData._diag.nChPPanel) HelixData._diag.nChPPanel = nhitsFace;\n\t}//end loop over the panel\n      }//end loop over the faces\n    }\n  }\n\n  unsigned  RobustHelixFinder::filterCircleHits(RobustHelixFinderData& helixData)\n  {\n    unsigned changed(0);\n    int      nGoodSH(0);\n    static XYZVec zaxis(0.0,0.0,1.0); // unit in z direction\n    RobustHelix& helix = helixData._hseed._helix;\n\n    // loop over hits\n    ComboHit*     hit(0);\n    FaceZ_t*      facez;\n\n    float         chi2dXY(0), chCounter(1e-10);\n    int           nhitsFace(0);\n\n    //for diagnostic purposes\n    float         drBestVec   [RobustHelixFinderData::kMaxResidIndex]={-9999.};\n    float         rwdotBestVec[RobustHelixFinderData::kMaxResidIndex]={-9999.};\n\n    for (int f=0; f<StrawId::_ntotalfaces; ++f){\n      facez     = &helixData._oTracker[f];\n\n      float      minChi2(_maxrpull);\n      float      drBest(-1.), rwdotBest(-1.);\n      HitInfo_t  indexBestComboHit;\n      bool       oldoutBest(false);\n\n      nhitsFace = facez->nChHits();\n      if (nhitsFace == 0)                        continue;\n\n      for (int ip=0; ip<nhitsFace; ++ip){\n\thit = &helixData._chHitsToProcess[facez->idChBegin + ip];\n\n\tbool oldout = hit->_flag.hasAnyProperty(_outlier);\n\thit->_flag.clear(_outlier);\n\n\tconst XYZVec& wdir = hit->wdir();\n\tXYZVec cvec = PerpVector(hit->pos() - helix.center(),Geom::ZDir()); // direction from the circle center to the hit\n\tXYZVec cdir = cvec.Unit(); // direction from the circle center to the hit\n\tfloat rwdot = wdir.Dot(cdir); // compare directions of radius and wire\n\tif(rwdot > _maxrwdot){\n\t  hit->_flag.merge(_outlier);\n\t  //\t  if(!oldout) ++changed;\n\t  continue;\n\t}\n\tfloat dr = sqrtf(cvec.mag2())-helix.radius();\n\tif ( fabs(dr) > _maxdr ) {\n\t  hit->_flag.merge(_outlier);\n\t  //\t  if(!oldout) ++changed;\n\t  continue;\n\t}\n\n\tfloat rwdot2 = rwdot*rwdot;\n\t// compute radial difference and pull\n\tfloat werr = hit->posRes(StrawHitPosition::wire);\n\tfloat terr = hit->posRes(StrawHitPosition::trans);\n\t// the resolution is dominated the resolution along the wire\n\t//\tfloat rres = std::max(sqrtf(werr*werr*rwdot2 + terr*terr*(1.0-rwdot2)),_minrerr);\n\tfloat rres = sqrtf(werr*werr*rwdot2 + terr*terr*(1.0-rwdot2));\n\tfloat rpull = fabs(dr/rres)*_rpullScaleF;\n\tif ( rpull > _maxrpull ) {\n\t  hit->_flag.merge(_outlier);\n\t  //\t  if(!oldout) ++changed;\n\t  continue;\n\t}\n\n\t//\tif (oldout) ++changed;\n\n\tif ( rpull < minChi2){\n\t  minChi2    = rpull;\n\t  drBest     = dr;\n\t  rwdotBest  = rwdot;\n\t  oldoutBest = oldout;\n\t  indexBestComboHit.face          = f;\n\t  indexBestComboHit.panel         = hit->strawId().uniquePanel();\n\t  indexBestComboHit.panelHitIndex = facez->idChBegin + ip;\n\t}\n\n\t//set all the hits as outlier. Only the best within the face will be cleared\n\thit->_flag.merge(_outlier);\n\n      }//end loop over the panels\n\n      if (indexBestComboHit.face >=0 ) {\n\thit     = &helixData._chHitsToProcess[indexBestComboHit.panelHitIndex];\n\n\t//remove the outlier flag\n\thit->_flag.clear(StrawHitFlag::outlier);\n\tnGoodSH += hit->nStrawHits();\n\tchi2dXY += minChi2*minChi2;\n\n\tif(oldoutBest) ++changed;\n\n\tif (chCounter < RobustHelixFinderData::kMaxResidIndex) {\n\t  drBestVec   [int(chCounter)] = drBest;\n\t  rwdotBestVec[int(chCounter)] = rwdotBest;\n\t}\n\tchCounter += 1.;\n      }\n\n    }//end loop over the faces\n\n    helixData._nXYSh = nGoodSH;\n    helixData._nXYCh = int(chCounter);\n\n    helix._chi2dXY   = chi2dXY/chCounter;\n\n    if (_diag) {\n      helixData._diag.chi2dXY = chi2dXY/chCounter;\n      helixData._diag.nXYCh   = helixData._nXYCh;\n\n      for (int i=0; i<int(chCounter); ++i){\n\tif (drBestVec   [i]>-999.) helixData._diag.resid[i] = drBestVec   [i];\n\tif (rwdotBestVec[i]>-999.) helixData._diag.rwdot[i] = rwdotBestVec[i];\n      }\n      //      helixData._diag. = chi2dXY/chCounter;\n    }\n\n    return changed;\n  }\n\n\n  void RobustHelixFinder::fitHelix(RobustHelixFinderData& helixData){\n    // iteratively fit the helix including filtering\n    unsigned niter(0);\n    unsigned nitermva(0);\n    bool     changed(true), xychanged(true), fzchanged(true);\n    unsigned niterxy(0), niterfz(0);\n\n    do {\n      niterxy = 0;\n      do {\n\t_hfit.fitCircle(helixData, _targetcon, _useTripletAreaWt);\n\txychanged = filterCircleHits(helixData) > 0;\n\t++niterxy;\n      } while (helixData._hseed._status.hasAllProperties(TrkFitFlag::circleOK) && niterxy < _maxniter && xychanged);\n\n      if (_diag) {\n\thelixData._diag.xyniter  = niterxy;\n\thelixData._diag.nShFitXY = helixData._nXYSh;\n\thelixData._diag.nChFitXY = helixData._nXYCh;\n      }\n\n      if (helixData._nXYSh < _minnsh) {\n\thelixData._hseed._status.clear(TrkFitFlag::circleOK);\n\tniter = _maxniter;//exit from this while()\n      }\n\n      // then fit phi-Z\n      if (helixData._hseed._status.hasAnyProperty(TrkFitFlag::circleOK)) {\n\tif (niterxy < _maxniter)\n\t  helixData._hseed._status.merge(TrkFitFlag::circleConverged);\n\telse\n\t  helixData._hseed._status.clear(TrkFitFlag::circleConverged);\n\n\t// solve for the longitudinal parameters\n\tniterfz = 0;\n\tfzchanged = false;\n\tdo {\n\t  _hfit.fitFZ(helixData);\n\t  fzchanged = filterHits(helixData);\n\t  ++niterfz;\n\t} while (helixData._hseed._status.hasAllProperties(TrkFitFlag::phizOK)  && niterfz < _maxniter && fzchanged);\n\n\tif (helixData._nZPhiSh < _minnsh) {\n\t  helixData._hseed._status.clear(TrkFitFlag::phizOK);\n\t  niter = _maxniter;//exit from this while()\n\t}\n\n\tif (helixData._hseed._status.hasAnyProperty(TrkFitFlag::phizOK)) {\n\t  if (niterfz < _maxniter)\n\t    helixData._hseed._status.merge(TrkFitFlag::phizConverged);\n\t  else\n\t    helixData._hseed._status.clear(TrkFitFlag::phizConverged);\n\t}\n      }\n      //here is where we should check for the hits within the face to searchfor missing/best ones\n      ++niter;\n      changed = fzchanged || xychanged;\n\n      // update the stereo hit positions; this checks how much the positions changed\n      // do this only in non trigger mode\n\n      if (_updateStereo && _hfit.goodHelix(helixData._hseed.helix()))\n\tchanged |= updateStereo(helixData);\n    } while (_hfit.goodHelix(helixData._hseed.helix()) && niter < _maxniter && changed);\n\n    if (_diag) helixData._diag.niter = niter;\n\n    if (_hfit.goodHelix(helixData._hseed.helix())  &&\n\thelixData._hseed._status.hasAnyProperty(TrkFitFlag::circleOK) &&\n\thelixData._hseed._status.hasAnyProperty(TrkFitFlag::phizOK) ) {\n\n      helixData._hseed._status.merge(TrkFitFlag::helixOK);\n      updateT0(helixData);\n      if (niter < _maxniter) helixData._hseed._status.merge(TrkFitFlag::helixConverged);\n\n      if (_usemva) {\n\tbool changed = true;\n\twhile (helixData._hseed._status.hasAllProperties(TrkFitFlag::helixOK)  && nitermva < _maxniter && changed) {\n\t  fillMVA(helixData);\n\t  changed = filterHitsMVA(helixData);\n\t  if (!changed) break;\n\t  refitHelix(helixData);\n\t  // update t0 each iteration as that's used in the MVA\n\t  updateT0(helixData);\n\t  ++nitermva;\n\t}\n\tif (nitermva < _maxniter)\n\t  helixData._hseed._status.merge(TrkFitFlag::helixConverged);\n\telse\n\t  helixData._hseed._status.clear(TrkFitFlag::helixConverged);\n      }\n    }\n    if (_diag > 0){\n      _niter->Fill(niter);\n      _niterfz->Fill(niterfz);\n      _niterxy->Fill(niterxy);\n      _nitermva->Fill(nitermva);\n      if (!_usemva) fillMVA(helixData);\n    }\n  }\n\n\n\n  //------------------------------------------------------------------------------------------\n\n\n  void RobustHelixFinder::fitChi2Helix(RobustHelixFinderData& helixData){\n    // iteratively fit the helix including filtering\n\n    //before starting, try to resolve the z-phi part of the helix\n    _chi2hfit.initFitChi2FZ(helixData);\n\n    //use chi2 line fit to make some preliminary cleanup\n    _chi2hfit.fitChi2FZ(helixData,0);\n    _chi2hfit.fitChi2FZ(helixData);\n\n    unsigned xyniter(0);\n    int      xychanged = filterChi2XYHits(helixData);\n    while (helixData._hseed._status.hasAnyProperty(TrkFitFlag::circleOK) && xyniter < _maxniter && (xychanged!=0)) {\n      xychanged = filterChi2XYHits(helixData);\n      ++xyniter;\n    }\n\n    if (_diag) {\n      helixData._diag.xyniter = xyniter;\n      helixData._diag.nShFitXY   = helixData._nXYSh;\n      helixData._diag.nChFitXY   = helixData._nXYCh;\n    }\n\n    // then fit phi-Z\n    if (helixData._hseed._status.hasAnyProperty(TrkFitFlag::circleOK)) {\n      if (xyniter < _maxniter)\n\thelixData._hseed._status.merge(TrkFitFlag::circleConverged);\n      else\n\thelixData._hseed._status.clear(TrkFitFlag::circleConverged);\n\n      // solve for the longitudinal parameters\n      unsigned fzniter(0);\n      _chi2hfit.fitChi2FZ(helixData);\n      int fzchanged = filterChi2ZPhiHits(helixData);\n      while (helixData._hseed._status.hasAnyProperty(TrkFitFlag::phizOK)  && fzniter < _maxniter && (fzchanged!=0)) {\n\tfzchanged = filterChi2ZPhiHits(helixData);\n\t++fzniter;\n      }\n\n      if (_diag) helixData._diag.fzniter = fzniter;\n\n      if (helixData._hseed._status.hasAnyProperty(TrkFitFlag::phizOK)) {\n\tif (fzniter < _maxniter){\n\t  helixData._hseed._status.merge(TrkFitFlag::phizConverged);\n\n\t  //now update all the helix parameters\n\t  updateChi2HelixInfo(helixData);\n\n\t  if (_hfit.goodHelix(helixData._hseed.helix()) && _chi2hfit.goodHelixChi2(helixData)) {\n\t    helixData._hseed._status.merge(TrkFitFlag::helixOK);\n\n\t    //now search for missing hits\n\t    findMissingHits(helixData);\n\n\t    updateT0(helixData);\n\n\t    helixData._hseed._status.merge(TrkFitFlag::helixConverged);\n\n\t    _chi2hfit.defineHelixParams(helixData);\n\t  }\n\t}\n\telse\n\t  helixData._hseed._status.clear(TrkFitFlag::phizConverged);\n      }\n\n    }\n\n  }\n\n  void RobustHelixFinder::refitHelix(RobustHelixFinderData& helixData) {\n    // reset the fit status flags, in case this is called iteratively\n\n    helixData._hseed._status.clear(TrkFitFlag::helixOK);\n    _hfit.fitCircle(helixData, _targetcon, _useTripletAreaWt);\n    if (helixData._hseed._status.hasAnyProperty(TrkFitFlag::circleOK)) {\n      _hfit.fitFZ(helixData);\n      if (_hfit.goodHelix(helixData._hseed._helix)) helixData._hseed._status.merge(TrkFitFlag::helixOK);\n    }\n  }\n\n  unsigned RobustHelixFinder::hitCount(RobustHelixFinderData& helixData) {\n    unsigned nHits(0);\n\n    ComboHit*      hit(0);\n\n    for (unsigned f=0; f<helixData._chHitsToProcess.size(); ++f){\n      hit = &helixData._chHitsToProcess[f];\n      if (hit->_flag.hasAnyProperty(_outlier))   continue;\n      ++nHits;\n    }//end faces loop\n\n    return nHits;\n  }\n\n\n  bool RobustHelixFinder::updateStereo(RobustHelixFinderData& helixData) {\n    static StrawHitFlag stereo(StrawHitFlag::stereo);\n    bool retval(false);\n    // loop over the stereo hits in the helix and update their positions given the local helix direction\n    for(auto& ch : helixData._hseed._hhits){\n      if(ch.flag().hasAllProperties(stereo) && ch.nCombo() >=2) {\n\t// local helix direction at the average z of this hit\n\tXYZVec hdir;\n\thelixData._hseed.helix().direction(ch.pos().z(),hdir);\n\t// needs re-implementing with ComboHits FIXME!\n\t//\tXYZVec pos1, pos2;\n\t//\tsthit.position(shcol,tracker,pos1,pos2,hdir);\n      }\n    }\n    return retval;\n  }\n\n\n  void RobustHelixFinder::fillPluginDiag(RobustHelixFinderData& helixData, int helCounter) {\n    //--------------------------------------------------------------------------------\n    // fill diagnostic information\n    //--------------------------------------------------------------------------------\n    float          mm2MeV = 3./10.;  // approximately , at B=1T\n\n    int loc = _data.nseeds[helCounter];\n    if (loc < _data.maxSeeds()) {\n      _data.nChPPanel   [helCounter][loc] = helixData._diag.nChPPanel;\n      _data.nChHits     [helCounter][loc] = helixData._diag.nChHits;\n\n      int nhits          = helixData._hseed._hhits.size();\n      _data.ntclhits    [helCounter][loc] = helixData._timeCluster->hits().size();\n      _data.nhits       [helCounter][loc] = nhits;\n\n      _data.ntriplet0   [helCounter][loc] = helixData._diag.ntriple_0;\n      _data.ntriplet1   [helCounter][loc] = helixData._diag.ntriple_1;\n      _data.ntriplet2   [helCounter][loc] = helixData._diag.ntriple_2;\n\n      _data.xyniter     [helCounter][loc] = helixData._diag.xyniter;\n      _data.fzniter     [helCounter][loc] = helixData._diag.fzniter;\n      _data.niter       [helCounter][loc] = helixData._diag.niter;\n      _data.nrescuedhits[helCounter][loc] = helixData._diag.nrescuedhits;\n\n      _data.nShFitCircle[helCounter][loc] = helixData._diag.nShFitCircle;\n      _data.nChFitCircle[helCounter][loc] = helixData._diag.nChFitCircle;\n      _data.nShFitXY    [helCounter][loc] = helixData._diag.nShFitXY;\n      _data.nChFitXY    [helCounter][loc] = helixData._diag.nChFitXY;\n\n\n      _data.nfz0counter [helCounter][loc] = helixData._diag.nfz0counter;\n\n      _data.nshsxy_0    [helCounter][loc] = helixData._diag.nshsxy_0;\n      _data.rsxy_0      [helCounter][loc] = helixData._diag.rsxy_0;\n      _data.chi2dsxy_0  [helCounter][loc] = helixData._diag.chi2dsxy_0;\n\n      _data.nshsxy_1    [helCounter][loc] = helixData._diag.nshsxy_1;\n      _data.rsxy_1      [helCounter][loc] = helixData._diag.rsxy_1;\n      _data.chi2dsxy_1  [helCounter][loc] = helixData._diag.chi2dsxy_1;\n\n      _data.nshszphi_0  [helCounter][loc] = helixData._diag.nshszphi_0;\n      _data.lambdaszphi_0    [helCounter][loc] = helixData._diag.lambdaszphi_0;\n      _data.chi2dszphi_0[helCounter][loc] = helixData._diag.chi2dszphi_0;\n\n      _data.nshszphi_1  [helCounter][loc] = helixData._diag.nshszphi_1;\n      _data.lambdaszphi_1    [helCounter][loc] = helixData._diag.lambdaszphi_1;\n      _data.chi2dszphi_1[helCounter][loc] = helixData._diag.chi2dszphi_1;\n\n\n      _data.nXYSh       [helCounter][loc] = helixData._nXYSh;\n      _data.nZPhiSh     [helCounter][loc] = helixData._nZPhiSh;\n\n      _data.rinit       [helCounter][loc] = helixData._diag.radius_0;\n      _data.lambda0     [helCounter][loc] = helixData._diag.lambda_0;\n      _data.lambda1     [helCounter][loc] = helixData._diag.lambda_1;\n      _data.radius      [helCounter][loc] = helixData._hseed.helix().radius();\n      _data.pT          [helCounter][loc] = mm2MeV*_data.radius[helCounter][loc];\n      _data.p           [helCounter][loc] = _data.pT[helCounter][loc]/std::cos( std::atan(helixData._hseed.helix().lambda()/_data.radius[helCounter][loc]));\n\n      _data.chi2XY      [helCounter][loc] = helixData._diag.chi2dXY;\n      _data.chi2ZPhi    [helCounter][loc] = helixData._diag.chi2dZPhi;\n\n      _data.nseeds[helCounter]++;\n\n      _data.dr          [helCounter][loc] = helixData._diag.radius_2 - helixData._diag.radius_1;\n      _data.chi2d_helix [helCounter][loc] = helixData._diag.chi2d_helix;\n\n      _data.nXYCh       [helCounter][loc] = helixData._diag.nXYCh;\n\n      _data.nLoops      [helCounter][loc] = helixData._diag.nLoops           ;\n\n      _data.nHitsLoopFailed[helCounter][loc] = helixData._diag.nHitsLoopFailed;\n\n      _data.meanHitRadialDist [helCounter][loc] = helixData._diag.meanHitRadialDist;\n\n      for (int i=0; i<helixData._diag.nXYCh; ++i) {\n\tif (helixData._diag.rwdot[i]>-999.) _data.hitRWDot[helCounter][loc][i] = helixData._diag.rwdot[i];\n\n\tif (helixData._diag.resid[i]>-999.) _data.hitDr   [helCounter][loc][i] = helixData._diag.resid[i];\n\telse break;\n      }\n    }   else {\n      printf(\" N(seeds) > %i, IGNORE SEED\\n\",_data.maxSeeds());\n    }\n  }\n\n  void     RobustHelixFinder::updateChi2HelixInfo(RobustHelixFinderData& helixData){\n    RobustHelix&  helix        = helixData._hseed._helix;\n    XYVec         center       = XYVec(helix.center().x(), helix.center().y());\n    float         radius       = helixData._sxy.radius();\n    center.SetX(helixData._sxy.x0());\n    center.SetY(helixData._sxy.y0());\n\n    //update the LSqsums\n    ComboHit*      hit(0);\n\n    helixData._sxy.clear();\n    if (_targetcon) helixData._sxy.addPoint(0.,0.,1./900.);\n\n    helixData._szphi.clear();\n    helixData._nXYSh   = 0;\n    helixData._nZPhiSh = 0;\n\n    for (unsigned f=0; f<helixData._chHitsToProcess.size(); ++f){\n      hit    = &helixData._chHitsToProcess[f];\n\n      if (hit->_flag.hasAnyProperty(_outlier))   continue;\n\n      hit->_xyWeight   = _chi2hfit.evalWeightXY(*hit, center);\n      hit->_zphiWeight = _chi2hfit.evalWeightZPhi(*hit, center, radius);\n\n      helixData._sxy.addPoint(hit->pos().x(), hit->pos().y(), hit->_xyWeight);\n      helixData._szphi.addPoint(hit->pos().z(), hit->helixPhi(), hit->_zphiWeight);\n\n      helixData._nXYSh   += hit->nStrawHits();\n      helixData._nZPhiSh += hit->nStrawHits();\n    }\n\n    center.SetX(helixData._sxy.x0());\n    center.SetY(helixData._sxy.y0());\n\n    //update the circle part\n    helix._rcent  = sqrtf(center.Mag2());\n    helix._fcent  = polyAtan2(center.y(), center.x());\n    helix._radius = helixData._sxy.radius();\n\n    //update the Z-Phi part\n    helix._lambda = 1./(helixData._szphi.dfdz());\n    helix._fz0    = helixData._szphi.phi0();\n  }\n\n  void     RobustHelixFinder::updateHelixXYInfo(RobustHelixFinderData& helixData){\n    RobustHelix&  helix        = helixData._hseed._helix;\n    XYVec         center       = XYVec(helix.center().x(), helix.center().y());\n\n    center.SetX(helixData._sxy.x0());\n    center.SetY(helixData._sxy.y0());\n\n    helix._rcent  = sqrtf(center.Mag2());\n    helix._fcent  = polyAtan2(center.y(), center.x());\n    helix._radius = helixData._sxy.radius();\n  }\n\n  void     RobustHelixFinder::updateHelixZPhiInfo(RobustHelixFinderData& helixData){\n    RobustHelix&  helix        = helixData._hseed._helix;\n\n    helix._lambda = 1./(helixData._szphi.dfdz());\n    helix._fz0    = helixData._szphi.phi0();\n  }\n\n  //----------------------------------------------------------------------------------------------------\n  void     RobustHelixFinder::searchWorstHitXY(RobustHelixFinderData& helixData, HitInfo_t& hitInfo){\n    hitInfo.face          = -1;\n    hitInfo.panel         = -1;\n    hitInfo.panelHitIndex = -1;\n\n    float          dr, wt, hitChi2;\n    XYVec          centerXY     = XYVec(helixData._hseed._helix.center().x(), helixData._hseed._helix.center().y());\n    XYZVec         center       = helixData._hseed._helix.center();\n    float          helix_radius = helixData._hseed._helix.radius();\n    float          hitChi2Worst = _maxrpull*_maxrpull;\n\n    ComboHit*      hit(0);\n    FaceZ_t*       facez(0);\n    int            nhitsFace(0);\n\n    for (int f=0; f<StrawId::_ntotalfaces; ++f){\n      facez     = &helixData._oTracker[f];\n      nhitsFace = facez->nChHits();\n\n      if (nhitsFace == 0)                          continue;\n\n      for (int ip=0; ip<nhitsFace; ++ip){\n\thit = &helixData._chHitsToProcess[facez->idChBegin + ip];\n\n\tif (hit->_flag.hasAnyProperty(_outlier))   continue;\n\n\tXYZVec  cvec  = PerpVector(hit->pos() - center,Geom::ZDir());\n\tdr    = sqrtf(cvec.mag2()) - helix_radius;\n\twt    = _chi2hfit.evalWeightXY(*hit, centerXY);\n\n\thitChi2 = dr*dr*wt;\n\n\tif (hitChi2 > hitChi2Worst) {\n\t  hitChi2Worst          = hitChi2;\n\t  hitInfo.face          = f;\n\t  hitInfo.panel         = hit->strawId().uniquePanel();\n\t  hitInfo.panelHitIndex = facez->idChBegin + ip;\n\t  hit->_xyWeight        = wt;\n\t}\n      }//end loop of the hits within the face\n    }//end faces loop\n  }\n\n  //----------------------------------------------------------------------------------------------------\n  void     RobustHelixFinder::searchWorstHitZPhi(RobustHelixFinderData& helixData, HitInfo_t& hitInfo){\n    hitInfo.face          = -1;\n    hitInfo.panel         = -1;\n    hitInfo.panelHitIndex = -1;\n\n    // XYZVec         center       = helixData._hseed._helix.center();\n    XYVec          centerXY     = XYVec(helixData._hseed._helix.center().x(), helixData._hseed._helix.center().y());\n    float          helix_radius = helixData._hseed._helix.radius();\n\n    ComboHit*      hit(0);\n    FaceZ_t*       facez(0);\n    int            nhitsFace(0);\n\n    float          chi2min(1e10), chi2;\n    ::LsqSums4     szphi;\n\n    for (int f=0; f<StrawId::_ntotalfaces; ++f){\n      facez     = &helixData._oTracker[f];\n      nhitsFace = facez->nChHits();\n\n      if (nhitsFace == 0)                          continue;\n\n      for (int ip=0; ip<nhitsFace; ++ip){\n\thit = &helixData._chHitsToProcess[facez->idChBegin + ip];\n\n\tif (hit->_flag.hasAnyProperty(_outlier))   continue;\n\n\tszphi.init(helixData._szphi);\n\n\t// XYZVec  cvec  = PerpVector(hit->pos() - center,Geom::ZDir());\n\tfloat   phi   = hit->helixPhi();\n\tfloat   wt    = _chi2hfit.evalWeightZPhi(*hit, centerXY, helix_radius);\n\n\tszphi.removePoint(hit->pos().z(), phi, wt);\n\tchi2 = szphi.chi2DofLine();\n\n\tif (chi2 < chi2min) {\n\t  chi2min               = chi2;\n\t  hitInfo.face          = f;\n\t  hitInfo.panel         = hit->strawId().uniquePanel();\n\t  hitInfo.panelHitIndex = facez->idChBegin + ip;\n\n\t  hit->_zphiWeight      = wt;\n\t  //\t    hitInfo.weightZPhi    = wt;\n\t}\n      }//end loop pver the hits within a face\n    }//end faces loop\n  }\n}\nusing mu2e::RobustHelixFinder;\nDEFINE_ART_MODULE(RobustHelixFinder);\n", "meta": {"hexsha": "aaa8df100a3e2c7d70c6c4fae202a4587546acc8", "size": 63928, "ext": "cc", "lang": "C++", "max_stars_repo_path": "TrkPatRec/src/RobustHelixFinder_module.cc", "max_stars_repo_name": "macndev/Offline", "max_stars_repo_head_hexsha": "c3344ca9e93c48d678a2352daf95917c457cf107", "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": "TrkPatRec/src/RobustHelixFinder_module.cc", "max_issues_repo_name": "macndev/Offline", "max_issues_repo_head_hexsha": "c3344ca9e93c48d678a2352daf95917c457cf107", "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": "TrkPatRec/src/RobustHelixFinder_module.cc", "max_forks_repo_name": "macndev/Offline", "max_forks_repo_head_hexsha": "c3344ca9e93c48d678a2352daf95917c457cf107", "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.9312536106, "max_line_length": 227, "alphanum_fraction": 0.6296614942, "num_tokens": 19456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.28776781576105315, "lm_q1q2_score": 0.18743897058543146}}
{"text": "#define BIORBD_API_EXPORTS\n#include \"Utils/RotoTransNode.h\"\n\n#include <Eigen/Dense>\n#include \"Utils/String.h\"\n\nbiorbd::utils::RotoTransNode::RotoTransNode() :\n    biorbd::utils::RotoTrans(),\n    biorbd::utils::Node()\n{\n    setType();\n}\n\nbiorbd::utils::RotoTransNode::RotoTransNode(\n        const RotoTrans &rt,\n        const biorbd::utils::String &name,\n        const biorbd::utils::String &parentName) :\n    biorbd::utils::RotoTrans(rt),\n    biorbd::utils::Node(name, parentName)\n{\n    setType();\n}\n\nbiorbd::utils::RotoTransNode biorbd::utils::RotoTransNode::DeepCopy() const\n{\n    biorbd::utils::RotoTransNode copy;\n    copy.DeepCopy(*this);\n    return copy;\n}\n\nvoid biorbd::utils::RotoTransNode::DeepCopy(const RotoTransNode &other)\n{\n    *this = static_cast<Eigen::Matrix4d>(other);\n    biorbd::utils::Node::DeepCopy(other);\n}\n\nvoid biorbd::utils::RotoTransNode::setType()\n{\n    *m_typeOfNode = biorbd::utils::NODE_TYPE::ROTOTRANS;\n}\n\n", "meta": {"hexsha": "c820e70af751669c176b499e80b23e77762d3d77", "size": 939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/RotoTransNode.cpp", "max_stars_repo_name": "jdowlingmedley/biorbd", "max_stars_repo_head_hexsha": "591a5372d815af626fa500047fe04743c76d7e13", "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/RotoTransNode.cpp", "max_issues_repo_name": "jdowlingmedley/biorbd", "max_issues_repo_head_hexsha": "591a5372d815af626fa500047fe04743c76d7e13", "max_issues_repo_licenses": ["MIT"], "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/RotoTransNode.cpp", "max_forks_repo_name": "jdowlingmedley/biorbd", "max_forks_repo_head_hexsha": "591a5372d815af626fa500047fe04743c76d7e13", "max_forks_repo_licenses": ["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.3571428571, "max_line_length": 75, "alphanum_fraction": 0.6869009585, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.18741990999931624}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Alejandro Cabrera 2011.\n// Distributed under the Boost\n// 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// See http://www.boost.org/libs/bloom_filter for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef BOOST_BLOOM_FILTER_TWOHASH_COUNTING_APPLY_HASH_HPP\n#define BOOST_BLOOM_FILTER_TWOHASH_COUNTING_APPLY_HASH_HPP\n\n#include <boost/bloom_filter/detail/exceptions.hpp>\n\nnamespace boost {\n  namespace bloom_filters {\n    namespace detail {\n\n      struct decrement {\n\tsize_t operator()(const size_t val, const size_t limit) {\n\t  if (val == limit)\n\t    throw bin_underflow_exception();\n\n\t  return val - 1;\n\t}\n      };\n \n      struct increment {\n\tsize_t operator()(const size_t val, const size_t limit) {\n\t  if (val == limit)\n\t    throw bin_overflow_exception();\n\n\t  return val + 1;\n\t}\n      };\n\n      template <size_t N, typename CBF, typename Op = void>\n      struct BloomOp {\n\ttypedef typename CBF::hash_function1_type hash_function1_type;\n\ttypedef typename CBF::hash_function2_type hash_function2_type;\n\ttypedef typename CBF::extension_function_type extension_function_type;\n\t\n\tBloomOp(const typename CBF::value_type& t)\n\t  : hash1_val(hash1(t)),\n\t    hash2_val(hash2(t))\n\t{\n\t}\n\n\tvoid update(typename CBF::bucket_type& slots,\n\t\t    const size_t num_bins,\n\t\t    const size_t limit)\n\t{\n\t  static Op op;\n\t  \n\t  for (size_t i = 0; i < N; ++i) {\n\t    const size_t hash = \n\t      (hash1_val + i * hash2_val + ext(i)) % num_bins;\n\t    const size_t pos = hash / CBF::bins_per_slot();\n\t    const size_t offset_bits = \n\t      (hash % CBF::bins_per_slot()) * CBF::bits_per_bin();\n\t    const size_t target_bits =\n\t      (slots[pos] >> offset_bits) & CBF::mask();\n\n\t    const size_t final_bits = op(target_bits, limit);\n\t    slots[pos] &= ~(CBF::mask() << offset_bits);\n\t    slots[pos] |= (final_bits << offset_bits);\n\t  }\n\t}\n\n\tbool check(const typename CBF::bucket_type& slots,\n\t\t   const size_t num_bins)\n\t{\n\t  for (size_t i = 0; i < N; ++i) {\n\t    const size_t hash = \n\t      (hash1_val + i * hash2_val + ext(i)) % num_bins;\n\t    const size_t pos = hash / CBF::bins_per_slot();\n\t    const size_t offset_bits = \n\t      (hash % CBF::bins_per_slot()) * CBF::bits_per_bin();\n\t    const size_t target_bits =\n\t      (slots[pos] >> offset_bits) & CBF::mask();\n\t    \n\t    if (target_bits == 0)\n\t      return false;\n\t  }\n\n\t  return true;\n\t}\n\n\tsize_t hash1_val;\n\tsize_t hash2_val;\n\thash_function1_type hash1;\n\thash_function2_type hash2;\n\textension_function_type ext;\n      };\n\n      // CBF : Counting Bloom Filter\n      template <size_t N, \n\t\tclass CBF>\n      struct twohash_counting_apply_hash\n      {\n\tstatic void insert(const typename CBF::value_type& t, \n\t\t\t   typename CBF::bucket_type& slots,\n\t\t\t   const size_t num_bins)\n\t{\n\t  BloomOp<N, CBF, increment> inserter(t);\n\t  inserter.update(slots, num_bins, \n\t\t\t  (static_cast<size_t>(1) << CBF::bits_per_bin()) - 1);\n\t}\n\n\tstatic void remove(const typename CBF::value_type& t, \n\t\t\t   typename CBF::bucket_type& slots,\n\t\t\t   const size_t num_bins)\n\t{\n\t  BloomOp<N, CBF, decrement> remover(t);\n\t  remover.update(slots, num_bins, 0);\n\t}\n\n\tstatic bool contains(const typename CBF::value_type& t, \n\t\t\t     const typename CBF::bucket_type& slots,\n\t\t\t     const size_t num_bins)\n\t{\n\t  BloomOp<N, CBF> checker(t);\n\t  return checker.check(slots, num_bins);\n\t\t\n\t}\n      };\n\n    } // namespace detail\n  } // namespace bloom_filter\n} // namespace boost\n#endif\n", "meta": {"hexsha": "e50fbf04ae57db8f345f8c0cb0c506585370a04a", "size": 3615, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/bloom_filter/detail/twohash_counting_apply_hash.hpp", "max_stars_repo_name": "tetzank/boost-bloom-filters", "max_stars_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T16:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T03:01:42.000Z", "max_issues_repo_path": "boost/bloom_filter/detail/twohash_counting_apply_hash.hpp", "max_issues_repo_name": "tetzank/boost-bloom-filters", "max_issues_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "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/bloom_filter/detail/twohash_counting_apply_hash.hpp", "max_forks_repo_name": "tetzank/boost-bloom-filters", "max_forks_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-04-15T18:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T06:29:58.000Z", "avg_line_length": 26.7777777778, "max_line_length": 78, "alphanum_fraction": 0.6320885201, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.18741990252718996}}
{"text": "//\n// Created by advcc on 2/16/22.\n//\n\n#ifndef LSEXAMPLE_THERMOGRAPHERBLOCK_HPP\n#define LSEXAMPLE_THERMOGRAPHERBLOCK_HPP\n\n#include <Lodestar/blocks/Block.hpp>\n#include <Eigen/Dense>\n#include <string>\n#include <array>\n\n#include <libirimager/direct_binding.h>\n\nnamespace ls {\n    namespace blocks {\n        template<typename TScalar = float, int NWidth = 382, int NHeight = 288>\n        class ThermographerBlock\n                : public Block<\n                        ::std::tuple<float>,\n                        ::std::tuple<Eigen::Matrix<TScalar, NHeight, NWidth, Eigen::ColMajor>, float>,\n                        ::std::tuple<::std::string>\n                > {\n        public:\n            using Base =\n            Block<\n                    ::std::tuple<float>,\n                    ::std::tuple<Eigen::Matrix<TScalar, NHeight, NWidth>, float>,\n                    ::std::tuple<::std::string>\n            >;\n\n            using Matrix = Eigen::Matrix<TScalar, NHeight, NWidth, Eigen::ColMajor>;\n            using MatrixUShort = Eigen::Matrix<unsigned short, NHeight, NWidth, Eigen::RowMajor>;\n\n            ThermographerBlock()\n            {\n                this->template i<0>().object = 0;\n                bindFunction();\n            }\n\n            ~ThermographerBlock()\n            {\n                ::evo_irimager_terminate();\n            }\n\n            typename ::std::tuple_element<0, typename Base::Params>::type &\n            serial()\n            {\n                return this->template p<0>();\n            }\n\n            const typename ::std::tuple_element<0, typename Base::Params>::type &\n            serial() const\n            {\n                return this->template p<0>();\n            }\n\n        protected:\n            void bindFunction()\n            {\n                this->equation = ::std::bind(\n                        &ThermographerBlock<TScalar, NWidth, NHeight>::triggerFunction, this,\n                        ::std::placeholders::_1);\n            }\n\n            void triggerFunction(Base &b)\n            {\n                static bool init = false;\n                static int err;\n                static int kWidth = NWidth;\n                static int kHeight = NHeight;\n                static ::std::array<unsigned short, NWidth * NHeight> thermalData{};\n                static MatrixUShort M;\n\n                if (!init) {\n                    err = ::evo_irimager_usb_init(b.template p<0>().c_str(), 0, 0);\n                    // Add error message if err != 0\n                    init = true;\n                }\n\n                evo_irimager_get_focusmotor_pos(&b.template o<1>().object);\n                b.template o<1>().propagate();\n                evo_irimager_set_focusmotor_pos(b.template i<0>().object);\n\n                static Eigen::Map<MatrixUShort> map = Eigen::Map<MatrixUShort>(&thermalData[0]);\n\n                if ((err = ::evo_irimager_get_thermal_image(&kWidth, &kHeight, &thermalData[0])) == 0) {\n                    M = map;\n                    b.template o<0>().object = M.template cast<TScalar>();\n                    b.template o<0>().object = b.template o<0>().object.unaryExpr([](TScalar T) -> TScalar { return T/10.0 - 100.0; });\n                    b.template o<0>().propagate();\n                } else {\n                    // err\n                }\n            }\n        };\n\n        template<typename TScalar, int NWidth, int NHeight>\n        class BlockTraits<ThermographerBlock<TScalar, NWidth, NHeight>> {\n        public:\n            static constexpr const BlockType blockType = BlockType::CustomBlock;\n            enum {\n                directFeedthrough = false\n            };\n\n            using type = ThermographerBlock<TScalar, NWidth, NHeight>;\n            using Base = typename type::Base;\n\n            enum {\n                kIns = Base::kIns,\n                kOuts = Base::kOuts,\n                kPars = Base::kPars\n            };\n\n            static const ::std::array<::std::string, kIns> inTypes;\n            static const ::std::array<::std::string, kOuts> outTypes;\n            static const ::std::array<::std::string, kPars> parTypes;\n\n            static const ::std::array<::std::string, 3> templateTypes;\n        };\n\n        template<typename TScalar, int NWidth, int NHeight>\n        const ::std::array<::std::string, BlockTraits<ThermographerBlock<TScalar, NWidth, NHeight>>::kIns> BlockTraits<ThermographerBlock<TScalar, NWidth, NHeight>>::inTypes =\n                {\"float\"};\n\n        template<typename TScalar, int NWidth, int NHeight>\n        const ::std::array<::std::string, BlockTraits<ThermographerBlock<TScalar, NWidth, NHeight>>::kOuts> BlockTraits<ThermographerBlock<TScalar, NWidth, NHeight>>::outTypes =\n                {demangle(typeid(Eigen::Matrix<TScalar, NHeight, NWidth, Eigen::ColMajor>).name()), \"float\"};\n\n        template<typename TScalar, int NWidth, int NHeight>\n        const ::std::array<::std::string, BlockTraits<ThermographerBlock<TScalar, NWidth, NHeight>>::kPars> BlockTraits<ThermographerBlock<TScalar, NWidth, NHeight>>::parTypes =\n                {demangle(typeid(::std::string).name())};\n\n        template<typename TScalar, int NWidth, int NHeight>\n        const ::std::array<::std::string, 3> BlockTraits<ThermographerBlock<TScalar, NWidth, NHeight>>::templateTypes =\n                {demangle(typeid(TScalar).name()), \"int\", \"int\"};\n    }\n}\n\n\n#endif //LSEXAMPLE_THERMOGRAPHERBLOCK_HPP\n", "meta": {"hexsha": "c9317ea37a125c46feefa310f99c0905c342998a", "size": 5391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobotPID/ThermographerBlock.hpp", "max_stars_repo_name": "helkebir/Lodestar-Examples", "max_stars_repo_head_hexsha": "7d8ed5715980703665fc1bfe7f0327cb4cb9b487", "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": "RobotPID/ThermographerBlock.hpp", "max_issues_repo_name": "helkebir/Lodestar-Examples", "max_issues_repo_head_hexsha": "7d8ed5715980703665fc1bfe7f0327cb4cb9b487", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobotPID/ThermographerBlock.hpp", "max_forks_repo_name": "helkebir/Lodestar-Examples", "max_forks_repo_head_hexsha": "7d8ed5715980703665fc1bfe7f0327cb4cb9b487", "max_forks_repo_licenses": ["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.9647887324, "max_line_length": 177, "alphanum_fraction": 0.5357076609, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.18734498774529545}}
{"text": "\n// MIT License\n//\n// Copyright (c) 2018 degski\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 <vector>\n\n#include <boost/container/static_vector.hpp>\n\n#include <SFML/Graphics.hpp>\n\n#include \"Globals.hpp\"\n\n#include \"Oska.hpp\"\n#include \"Mcts.hpp\"\n\n\nclass OutBox {\n\n    typedef boost::container::static_vector < Point, 8 > Captured;\n\n    Captured m_captured;\n\n    float s0, t0, s1, t1, s2, t2, a, m_l2radius;\n\n    std::uniform_real_distribution<float> xdist, ydist;\n\n    bool isClose ( const Point & point1_, const Point & point2_ ) const noexcept {\n\n        return ( point1_.x - point2_.x ) * ( point1_.x - point2_.x ) + ( point1_.y - point2_.y ) * ( point1_.y - point2_.y ) < m_l2radius;\n    }\n\n    bool isInside ( const Point & p_ ) const noexcept;\n\npublic:\n\n    void initialize ( const Point & p0_, const Point & p1_, const Point & p2_, const float l2radius_ ) noexcept;\n\n    Point randomPoint ( ) const noexcept;\n\n    void add ( const Point p_ ) noexcept {\n        m_captured.push_back ( p_ );\n    }\n\n    Point back ( ) const noexcept {\n        return m_captured.back ( );\n    }\n\n    Captured & operator ( ) ( ) noexcept {\n        return m_captured;\n    }\n};\n\n\ntemplate< typename State >\nstruct Mover {\n\n    State * m_state;\n\n    Point m_point_from, m_point_move;\n\n    sf::Time m_animation_start, m_animation_duration;\n\n    Location::type m_id = Location::invalid;\n\n    void initialize ( State & state_ ) {\n\n        m_state = &state_;\n    }\n\n    bool isActive ( const Location::type id_ ) const noexcept {\n        return m_id == id_;\n    }\n\n    void start ( const Move m_, const float speed_, const sf::Time delay_ = sf::seconds ( 0 ) ) noexcept {\n        m_id = m_state->getIdFromLocation ( m_.m_to );\n        m_state->getHexRefFromID ( m_id ).setRandomOffset ( );\n        m_point_from = m_state->getHexRefFromID ( m_state->getIdFromLocation ( m_.m_from ) ).point ( );\n        m_point_move = m_state->getHexRefFromID ( m_id ).point ( ) - m_point_from;\n        m_animation_start = now ( ) + delay_;\n        m_animation_duration = sf::milliseconds ( ( sf::Int32 ) ( std::sqrt ( m_point_move.x * m_point_move.x + m_point_move.y * m_point_move.y ) / speed_ ) );\n    }\n\n    Point move ( ) noexcept {\n        const float ratio = ( now ( ) - m_animation_start ) / m_animation_duration;\n        if ( ratio < 0.0f ) {\n            return m_point_from;\n        }\n        else if ( ratio > 1.0f ) {\n            m_id = Location::invalid;\n            return m_point_from + m_point_move;\n        }\n        else {\n            return m_point_from + m_point_move * ratio;\n        }\n    }\n};\n\n\ntemplate< typename State >\nstruct Captor {\n\n    State * m_state;\n    OutBox * m_outbox;\n\n    Point m_point_from, m_point_to, m_point_move;\n\n    sf::Time m_animation_start, m_animation_duration;\n\n    bool m_active = false;\n\n    Location::type m_id = Location::invalid;\n\n    void initialize ( State & state_, OutBox & outbox_ ) {\n        m_state = &state_;\n        m_outbox = &outbox_;\n    }\n\n    bool isActive ( ) const noexcept {\n        return m_active;\n    }\n\n    void start ( const Location & f_, const float speed_, const sf::Time delay_ = sf::seconds ( 0 ) ) noexcept {\n        m_id = m_state->getIdFromLocation ( f_ );\n        m_point_from = m_state->getHexRefFromID ( m_id ).point ( );\n        m_point_to = m_outbox->randomPoint ( );\n        m_point_move = m_point_to - m_point_from; // Make a move to some point.\n        m_animation_start = now ( ) + delay_;\n        m_animation_duration = sf::milliseconds ( ( sf::Int32 ) ( std::sqrt ( m_point_move.x * m_point_move.x + m_point_move.y * m_point_move.y ) / speed_ ) );\n        m_active = true;\n    }\n\n    Point move ( ) noexcept {\n        const float ratio = ( now ( ) - m_animation_start ) / m_animation_duration;\n        if ( ratio < 0.0f ) {\n            return m_point_from;\n        }\n        else if ( ratio > 1.0f ) {\n            if ( m_active ) {\n                m_active = false;\n                m_outbox->add ( m_point_to );\n            }\n            return m_point_to;\n        }\n        else {\n            return m_point_from + m_point_move * ratio;\n        }\n    }\n};\n\n\nclass App {\n\n    os::OskaState m_state;\n\n    std::vector<Point> m_board_polygon;\n\npublic:\n\n    float m_window_width, m_window_height;\n\n    sf::FloatRect m_window_bounds;\n    sf::FloatRect m_drag_bounding_box;\n\n    sf::RenderWindow m_window;\n\n    sf::RenderTexture m_board_texture;\n    sf::Sprite m_board;\n\nprivate:\n\n    sf::Font m_font_regular, m_font_bold, m_font_mono, m_font_numbers;\n\n    sf::Texture m_background_texture;\n    sf::Sprite m_background;\n\n    sf::Texture m_agent_stone_texture;\n    sf::Sprite m_agent_stone;\n\n    sf::Texture m_human_stone_texture;\n    sf::Sprite m_human_stone;\n\n    // Drag related.\n\n    sf::Vector2f m_mouse_point;\n\n    bool m_is_dragging = false, m_is_go_back = false;\n\n    sf::Texture m_drag_shape_texture;\n    sf::Sprite m_drag_shape;\n\n    float m_drag_shape_l2radius;\n\n    Location::type m_human_id_from = Location::invalid, m_human_id_to = Location::invalid;\n\n    OutBox m_agent_outbox, m_human_outbox;\n\n    Mover < os::OskaState > m_agent_stone_mover;\n    Captor < os::OskaState > m_agent_stone_captor, m_human_stone_captor;\n\n    sf::FloatRect m_menu_bounds, m_exit_bounds;\n\npublic:\n\n    void initialize ( const std::int32_t no_stones_ );\n\n    /*\n\n    void drawSmallLogo ( );\n\n    template<typename TextType>\n    bool enterString ( TextType &text_, const std::wstring &title_ );\n    template<typename TextType>\n    void textInputScreen ( const std::wstring &title_, const TextType &text_ );\n    std::vector<sf::FloatRect> listSelectScreen ( const std::wstring &title_, const std::vector<std::wstring> &list_ );\n\n    bool addUser ( );\n    bool authoriseUser ( );\n    void selectUser ( );\n\n    // std::wstring getCurrentUserName ( ) { return users.name ( user_id ); }\n\n    void highScoresScreen ( );\n\n    */\n\nprivate:\n\n    void setIcon ( );\n\n    void updateBoard ( )  noexcept;\n\n    template<typename T>\n    void drawStones ( T & draw_object_ ) noexcept;\n\npublic:\n\n    bool isPointInsidePolygon ( const Point & point_ ) const noexcept;\n\n    bool isOnStone ( const sf::Vector2f & point_ ) const noexcept {\n        return ( point_.x - m_mouse_point.x ) * ( point_.x - m_mouse_point.x ) + ( point_.y - m_mouse_point.y ) * ( point_.y - m_mouse_point.y ) < m_drag_shape_l2radius;\n    }\n\n    bool isWindowOpen ( ) const {\n        return m_window.isOpen ( );\n    }\n\n    bool pollWindowEvent ( sf::Event &event_ ) {\n        return m_window.pollEvent ( event_ );\n    }\n\n    void closeWindow ( ) noexcept {\n        m_window.close ( );\n    }\n\n    void updateWindow ( ) noexcept;\n\nprivate:\n\n    bool doHumanMove ( const Point point_ ) noexcept;\n    void doAgentRandomMove ( ) noexcept;\n    void doAgentMctsMove ( ) noexcept;\n\npublic:\n\n    void mouse ( );\n};\n", "meta": {"hexsha": "46c4cd0d5438dc39bfdbbfb3798911f457d98f83", "size": 7853, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Oska/App.hpp", "max_stars_repo_name": "degski/Oska", "max_stars_repo_head_hexsha": "9a4e3b938fbbcee28cfebd09d50a8b29a2aec900", "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": "Oska/App.hpp", "max_issues_repo_name": "degski/Oska", "max_issues_repo_head_hexsha": "9a4e3b938fbbcee28cfebd09d50a8b29a2aec900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Oska/App.hpp", "max_forks_repo_name": "degski/Oska", "max_forks_repo_head_hexsha": "9a4e3b938fbbcee28cfebd09d50a8b29a2aec900", "max_forks_repo_licenses": ["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.2673611111, "max_line_length": 169, "alphanum_fraction": 0.6493059977, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18734498043232767}}
{"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_HAMILTONIAN_KERNEL_HPP\n#define NETKET_HAMILTONIAN_KERNEL_HPP\n\n#include <Eigen/Core>\n#include \"Machine/abstract_machine.hpp\"\n#include \"Operator/abstract_operator.hpp\"\n#include \"Utils/messages.hpp\"\n#include \"Utils/random_utils.hpp\"\n\nnamespace netket {\n\n// Generating transitions using the Hamiltonian matrix elements\nclass HamiltonianKernel {\n  AbstractOperator &hamiltonian_;\n\n  // number of visible units\n  const Index nv_;\n\n  std::vector<std::vector<int>> tochange_;\n  std::vector<std::vector<double>> newconfs_;\n  std::vector<Complex> mel_;\n\n public:\n  HamiltonianKernel(const AbstractMachine &psi, AbstractOperator &hamiltonian);\n\n  HamiltonianKernel(AbstractOperator &ham);\n\n  void operator()(Eigen::Ref<const RowMatrix<double>> v,\n                  Eigen::Ref<RowMatrix<double>> vnew,\n                  Eigen::Ref<Eigen::ArrayXd> acceptance_correction);\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "652bf5ccbd7a412e671cc44786092835bfbcac87", "size": 1536, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sources/Sampler/hamiltonian_kernel.hpp", "max_stars_repo_name": "vigsterkr/netket", "max_stars_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "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": "Sources/Sampler/hamiltonian_kernel.hpp", "max_issues_repo_name": "vigsterkr/netket", "max_issues_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "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": "Sources/Sampler/hamiltonian_kernel.hpp", "max_forks_repo_name": "vigsterkr/netket", "max_forks_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "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.72, "max_line_length": 79, "alphanum_fraction": 0.7454427083, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.1873449767758438}}
{"text": "#include <vector>\n#include <string>\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include \"caffe/blob.hpp\"\n#include \"caffe/common.hpp\"\n#include \"caffe/layer.hpp\"\n#include \"caffe/net.hpp\"\n#include \"caffe/FRCNN/util/frcnn_param.hpp\"\n#include \"caffe/FRCNN/util/frcnn_helper.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\nnamespace FRCNN_API{\nusing std::vector;\nusing caffe::Blob;\nusing caffe::Net;\nusing caffe::Frcnn::FrcnnParam;\nusing caffe::Frcnn::Point4f;\nusing caffe::Frcnn::BBox;\nusing caffe::caffe_copy;\n\nclass Detector {\npublic:\n\n  void Set_Model(int gpu_id);\n  void predict(const cv::Mat &img_in, vector<BBox<float> > &results, boost::shared_ptr<Blob<float> > &img_crop);\n  void predict_original(const cv::Mat &img_in, vector<BBox<float> > &results, boost::shared_ptr<Blob<float> > &img_crop);\n  void predict_iterative(const cv::Mat &img_in, vector<BBox<float> > &results);\n\n//  static Detector* getInstance();\n//  static pthread_mutex_t mutex;\n//protected:\n  Detector(int gpu_id){\n//   pthread_mutex_init(&mutex,NULL);\n   Set_Model(gpu_id);\n  }\n\nprivate:\n  void preprocess(const cv::Mat &img_in, const int blob_idx);\n  void preprocess(const vector<float> &data, const int blob_idx);\n  vector<boost::shared_ptr<Blob<float> > > predict(const vector<std::string> blob_names);\n  boost::shared_ptr<Net<float> > net_;\n  float mean_[3];\n  float std_[3];\n  float reid_mean_[3];\n  float reid_std_[3];\n  int roi_pool_layer;\n\n//  Detector(){}\n//  Detector(const Detector&);\n//  Detector& operator= (const Detector&);\n//  static Detector* detector;\n};\n\nclass Identifier {\npublic:\n  void Set_Model(int gpu_id);\n  void predict(vector<cv::Mat> &crop_imgs, vector<vector<float> > &norm_features);\n  void cosine_similarity(vector<vector<float> > &query_feature, vector<vector<float> > &gallery_features, vector<float> &sims);\n  Identifier(int gpu_id){\n   Set_Model(gpu_id);\n  }\nprivate:\n  void preprocess(const cv::Mat &img_in, const int blob_idx);\n  vector<boost::shared_ptr<Blob<float> > > _predict(const vector<std::string> blob_names);\n  boost::shared_ptr<Net<float> > net_;\n  float reid_mean_[3];\n  float reid_std_[3];\n//  Identifier(const Identifier&);\n//  Identifier& operator= (const Identifier&);\n//  static Identifier* identifier;\n\n};\n\n}\n", "meta": {"hexsha": "cd8c1dcf1993436911724b07a0ddc1224bc86816", "size": 2369, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/caffe/api/FRCNN/frcnn_api.hpp", "max_stars_repo_name": "jjn037/caffe-priv-mult-thread", "max_stars_repo_head_hexsha": "0c073d5909d8b6d13a51a5cf273e9de01a7d2735", "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/caffe/api/FRCNN/frcnn_api.hpp", "max_issues_repo_name": "jjn037/caffe-priv-mult-thread", "max_issues_repo_head_hexsha": "0c073d5909d8b6d13a51a5cf273e9de01a7d2735", "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/caffe/api/FRCNN/frcnn_api.hpp", "max_forks_repo_name": "jjn037/caffe-priv-mult-thread", "max_forks_repo_head_hexsha": "0c073d5909d8b6d13a51a5cf273e9de01a7d2735", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T05:49:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-20T05:49:50.000Z", "avg_line_length": 29.6125, "max_line_length": 127, "alphanum_fraction": 0.7289995779, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18734497532765063}}
{"text": "#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/register/ring.hpp>\n\n#include <valhalla/baldr/json.h>\n#include <valhalla/loki/polygon_search.h>\n#include <valhalla/midgard/constants.h>\n#include <valhalla/midgard/logging.h>\n#include <valhalla/midgard/pointll.h>\n#include <valhalla/worker.h>\n\nnamespace bg = boost::geometry;\nnamespace vm = valhalla::midgard;\nnamespace vb = valhalla::baldr;\nnamespace vl = valhalla::loki;\n\nBOOST_GEOMETRY_REGISTER_POINT_2D(vm::PointLL, double, bg::cs::geographic<bg::degree>, first, second)\nBOOST_GEOMETRY_REGISTER_RING(std::vector<vm::PointLL>)\n\nnamespace {\n// register a few boost.geometry types\nusing line_bg_t = bg::model::linestring<vm::PointLL>;\nusing ring_bg_t = std::vector<vm::PointLL>;\nusing namespace vb::json;\n\n// map of tile for map of bin ids & their ring ids\n// TODO: simplify the logic behind this a little\nusing bins_collector =\n    std::unordered_map<uint32_t, std::unordered_map<unsigned short, std::vector<size_t>>>;\n\nstatic const auto Haversine = [] {\n  return bg::strategy::distance::haversine<float>(vm::kRadEarthMeters);\n};\n\nring_bg_t PBFToRing(const valhalla::Options::Ring& ring_pbf) {\n  ring_bg_t new_ring;\n  for (const auto& coord : ring_pbf.coords()) {\n    new_ring.push_back({coord.lng(), coord.lat()});\n  }\n  // fixes windedness & closes open rings\n  bg::correct(new_ring);\n  return new_ring;\n}\n\n#ifdef LOGGING_LEVEL_TRACE\n// serializes an edge to geojson\nstd::string to_geojson(const std::unordered_set<vb::GraphId>& edge_ids, vb::GraphReader& reader) {\n  auto features = array({});\n  for (const auto& edge_id : edge_ids) {\n    auto tile = reader.GetGraphTile(edge_id);\n    auto edge = tile->directededge(edge_id);\n    auto shape = tile->edgeinfo(edge).shape();\n    if (!edge->forward()) {\n      std::reverse(shape.begin(), shape.end());\n    }\n\n    auto coords = array({});\n    for (const auto& p : shape) {\n      coords->emplace_back(array({fixed_t{p.lng(), 6}, fixed_t{p.lat(), 6}}));\n    }\n    features->emplace_back(\n        map({{\"type\", std::string(\"Feature\")},\n             {\"properties\",\n              map({{\"shortcut\", edge->is_shortcut() ? std::string(\"True\") : std::string(\"False\")},\n                   {\"edge_id\", edge_id.value}})},\n             {\"geometry\", map({{\"type\", std::string(\"LineString\")}, {\"coordinates\", coords}})}}));\n  }\n\n  auto collection =\n      vb::json::map({{\"type\", std::string(\"FeatureCollection\")}, {\"features\", features}});\n\n  std::stringstream ss;\n  ss << *collection;\n\n  return ss.str();\n}\n#endif // LOGGING_LEVEL_TRACE\n} // namespace\n\nnamespace valhalla {\nnamespace loki {\n\nstd::unordered_set<vb::GraphId>\nedges_in_rings(const google::protobuf::RepeatedPtrField<valhalla::Options_Ring>& rings_pbf,\n               baldr::GraphReader& reader,\n               const std::shared_ptr<sif::DynamicCost>& costing,\n               float max_length) {\n\n  // convert to bg object and check length restriction\n  double rings_length = 0;\n  std::vector<ring_bg_t> rings_bg;\n  for (const auto& ring_pbf : rings_pbf) {\n    rings_bg.push_back(PBFToRing(ring_pbf));\n    const ring_bg_t ring_bg = rings_bg.back();\n    rings_length += bg::perimeter(ring_bg, Haversine());\n  }\n  if (rings_length > max_length) {\n    throw valhalla_exception_t(167, std::to_string(max_length));\n  }\n\n  // Get the lowest level and tiles\n  const auto tiles = vb::TileHierarchy::levels().back().tiles;\n  const auto bin_level = vb::TileHierarchy::levels().back().level;\n\n  // keep track which tile's bins intersect which rings\n  bins_collector bins_intersected;\n  std::unordered_set<vb::GraphId> avoid_edge_ids;\n\n  // first pull out all *unique* bins which intersect the rings\n  for (size_t ring_idx = 0; ring_idx < rings_bg.size(); ring_idx++) {\n    auto ring = rings_bg[ring_idx];\n    auto line_intersected = tiles.Intersect(ring);\n    for (const auto& tb : line_intersected) {\n      for (const auto& b : tb.second) {\n        bins_intersected[static_cast<uint32_t>(tb.first)][b].push_back(ring_idx);\n      }\n    }\n  }\n  for (const auto& intersection : bins_intersected) {\n    auto tile = reader.GetGraphTile({intersection.first, bin_level, 0});\n    if (!tile) {\n      continue;\n    }\n    for (const auto& bin : intersection.second) {\n      // tile will be mutated most likely in the loop\n      reader.GetGraphTile({intersection.first, bin_level, 0}, tile);\n      for (const auto& edge_id : tile->GetBin(bin.first)) {\n        if (avoid_edge_ids.count(edge_id) != 0) {\n          continue;\n        }\n        // TODO: optimize the tile switching by enqueuing edges\n        // from other levels & tiles and process them after this big loop\n        if (edge_id.Tile_Base() != tile->header()->graphid().Tile_Base() &&\n            !reader.GetGraphTile(edge_id, tile)) {\n          continue;\n        }\n        const auto edge = tile->directededge(edge_id);\n        auto opp_tile = tile;\n        const baldr::DirectedEdge* opp_edge = nullptr;\n        baldr::GraphId opp_id;\n\n        // bail if we wouldnt be allowed on this edge anyway (or its opposing)\n        if (!costing->Allowed(edge, tile) &&\n            (!(opp_id = reader.GetOpposingEdgeId(edge_id, opp_edge, opp_tile)).Is_Valid() ||\n             !costing->Allowed(opp_edge, opp_tile))) {\n          continue;\n        }\n\n        // TODO: some logic to set percent_along for origin/destination edges\n        // careful: polygon can intersect a single edge multiple times\n        auto edge_info = tile->edgeinfo(edge);\n        bool intersects = false;\n        for (const auto& ring_loc : bin.second) {\n          intersects = bg::intersects(rings_bg[ring_loc],\n                                      line_bg_t(edge_info.shape().begin(), edge_info.shape().end()));\n          if (intersects) {\n            break;\n          }\n        }\n        if (intersects) {\n          avoid_edge_ids.emplace(edge_id);\n          avoid_edge_ids.emplace(\n              opp_id.Is_Valid() ? opp_id : reader.GetOpposingEdgeId(edge_id, opp_edge, opp_tile));\n        }\n      }\n    }\n  }\n\n// log the GeoJSON of avoided edges\n#ifdef LOGGING_LEVEL_TRACE\n  if (!avoid_edge_ids.empty()) {\n    LOG_TRACE(\"Avoided edges GeoJSON: \\n\" + to_geojson(avoid_edge_ids, reader));\n  }\n#endif\n\n  return avoid_edge_ids;\n}\n} // namespace loki\n} // namespace valhalla\n", "meta": {"hexsha": "1fcd3e17da4eb7513a15f4e8ddf9e233a1fb5867", "size": 6298, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/loki/polygon_search.cc", "max_stars_repo_name": "huggymann/valhalla", "max_stars_repo_head_hexsha": "f0d402e9fb449795b6cb8a0cac0b7e786f4a999d", "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/loki/polygon_search.cc", "max_issues_repo_name": "huggymann/valhalla", "max_issues_repo_head_hexsha": "f0d402e9fb449795b6cb8a0cac0b7e786f4a999d", "max_issues_repo_licenses": ["MIT"], "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/loki/polygon_search.cc", "max_forks_repo_name": "huggymann/valhalla", "max_forks_repo_head_hexsha": "f0d402e9fb449795b6cb8a0cac0b7e786f4a999d", "max_forks_repo_licenses": ["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.9888888889, "max_line_length": 101, "alphanum_fraction": 0.6548110511, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.18731016229390468}}
{"text": "\n\n#include <ripple/app/paths/Credit.h>\n#include <ripple/app/paths/Flow.h>\n#include <ripple/app/paths/impl/AmountSpec.h>\n#include <ripple/app/paths/impl/StrandFlow.h>\n#include <ripple/app/paths/impl/Steps.h>\n#include <ripple/basics/Log.h>\n#include <ripple/protocol/IOUAmount.h>\n#include <ripple/protocol/XRPAmount.h>\n\n#include <boost/container/flat_set.hpp>\n\n#include <numeric>\n#include <sstream>\n\nnamespace ripple {\n\ntemplate<class FlowResult>\nstatic\nauto finishFlow (PaymentSandbox& sb,\n    Issue const& srcIssue, Issue const& dstIssue,\n    FlowResult&& f)\n{\n    path::RippleCalc::Output result;\n    if (f.ter == tesSUCCESS)\n        f.sandbox->apply (sb);\n    else\n        result.removableOffers = std::move (f.removableOffers);\n\n    result.setResult (f.ter);\n    result.actualAmountIn = toSTAmount (f.in, srcIssue);\n    result.actualAmountOut = toSTAmount (f.out, dstIssue);\n\n    return result;\n};\n\npath::RippleCalc::Output\nflow (\n    PaymentSandbox& sb,\n    STAmount const& deliver,\n    AccountID const& src,\n    AccountID const& dst,\n    STPathSet const& paths,\n    bool defaultPaths,\n    bool partialPayment,\n    bool ownerPaysTransferFee,\n    bool offerCrossing,\n    boost::optional<Quality> const& limitQuality,\n    boost::optional<STAmount> const& sendMax,\n    beast::Journal j,\n    path::detail::FlowDebugInfo* flowDebugInfo)\n{\n    Issue const srcIssue = [&] {\n        if (sendMax)\n            return sendMax->issue ();\n        if (!isXRP (deliver.issue ().currency))\n            return Issue (deliver.issue ().currency, src);\n        return xrpIssue ();\n    }();\n\n    Issue const dstIssue = deliver.issue ();\n\n    boost::optional<Issue> sendMaxIssue;\n    if (sendMax)\n        sendMaxIssue = sendMax->issue ();\n\n    auto sr = toStrands (sb, src, dst, dstIssue, limitQuality, sendMaxIssue,\n        paths, defaultPaths, ownerPaysTransferFee, offerCrossing, j);\n\n    if (sr.first != tesSUCCESS)\n    {\n        path::RippleCalc::Output result;\n        result.setResult (sr.first);\n        return result;\n    }\n\n    auto& strands = sr.second;\n\n    if (j.trace())\n    {\n        j.trace() << \"\\nsrc: \" << src << \"\\ndst: \" << dst\n            << \"\\nsrcIssue: \" << srcIssue << \"\\ndstIssue: \" << dstIssue;\n        j.trace() << \"\\nNumStrands: \" << strands.size ();\n        for (auto const& curStrand : strands)\n        {\n            j.trace() << \"NumSteps: \" << curStrand.size ();\n            for (auto const& step : curStrand)\n            {\n                j.trace() << '\\n' << *step << '\\n';\n            }\n        }\n    }\n\n    const bool srcIsXRP = isXRP (srcIssue.currency);\n    const bool dstIsXRP = isXRP (dstIssue.currency);\n\n    auto const asDeliver = toAmountSpec (deliver);\n\n    if (srcIsXRP && dstIsXRP)\n    {\n        return finishFlow (sb, srcIssue, dstIssue,\n            flow<XRPAmount, XRPAmount> (\n                sb, strands, asDeliver.xrp, partialPayment, offerCrossing,\n                limitQuality, sendMax, j, flowDebugInfo));\n    }\n\n    if (srcIsXRP && !dstIsXRP)\n    {\n        return finishFlow (sb, srcIssue, dstIssue,\n            flow<XRPAmount, IOUAmount> (\n                sb, strands, asDeliver.iou, partialPayment, offerCrossing,\n                limitQuality, sendMax, j, flowDebugInfo));\n    }\n\n    if (!srcIsXRP && dstIsXRP)\n    {\n        return finishFlow (sb, srcIssue, dstIssue,\n            flow<IOUAmount, XRPAmount> (\n                sb, strands, asDeliver.xrp, partialPayment, offerCrossing,\n                limitQuality, sendMax, j, flowDebugInfo));\n    }\n\n    assert (!srcIsXRP && !dstIsXRP);\n    return finishFlow (sb, srcIssue, dstIssue,\n        flow<IOUAmount, IOUAmount> (\n            sb, strands, asDeliver.iou, partialPayment, offerCrossing,\n            limitQuality, sendMax, j, flowDebugInfo));\n\n}\n\n} \n\n\n\n\n\n\n", "meta": {"hexsha": "a954da6e1d570909c879cf3288383afcf65b2013", "size": 3749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dfm/app/paths/Flow.cpp", "max_stars_repo_name": "dfm-official/dfm", "max_stars_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_stars_repo_licenses": ["ISC"], "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/dfm/app/paths/Flow.cpp", "max_issues_repo_name": "dfm-official/dfm", "max_issues_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_issues_repo_licenses": ["ISC"], "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/dfm/app/paths/Flow.cpp", "max_forks_repo_name": "dfm-official/dfm", "max_forks_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_forks_repo_licenses": ["ISC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9712230216, "max_line_length": 76, "alphanum_fraction": 0.6097626034, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18715415826631684}}
{"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// Overload of uBLAS prod function with MKL/GSL implementations\n\n#include \"votca/xtp/aobasis.h\"\n#include \"votca/xtp/qminterface.h\"\n#include <votca/xtp/dftengine.h>\n\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <votca/xtp/aomatrix.h>\n#include <votca/xtp/threecenters.h>\n\n#include <votca/xtp/qmpackagefactory.h>\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <votca/tools/linalg.h>\n#include <votca/tools/constants.h>\n\n#include <votca/xtp/elements.h>\n#include <votca/xtp/diis.h>\n\n#include <votca/ctp/xinteractor.h>\n#include <votca/ctp/logger.h>\n\n\n\nusing boost::format;\nusing namespace boost::filesystem;\n\nnamespace votca {\n    namespace xtp {\n        namespace ub = boost::numeric::ublas;\n        // +++++++++++++++++++++++++++++ //\n        // DFTENGINE MEMBER FUNCTIONS        //\n        // +++++++++++++++++++++++++++++ //\n\n        void DFTENGINE::CleanUp() {\n\n        }\n\n        void DFTENGINE::Initialize(Property* options) {\n\n            string key = Identify();\n\n            // get OpenMP thread number\n\n            _openmp_threads = options->ifExistsReturnElseReturnDefault<int>(key + \".openmp\", 0);\n\n            // basis sets\n            _dftbasis_name = options->ifExistsReturnElseThrowRuntimeError<string>(key + \".dftbasis\");\n\n            if (options->exists(key + \".auxbasis\")) {\n                _auxbasis_name = options->get(key + \".auxbasis\").as<string>();\n                _with_RI = true;\n            } else {\n                _with_RI = false;\n            }\n\n            if (options->exists(key + \".ecp\")) {\n                _ecp_name = options->get(key + \".ecp\").as<string>();\n                _with_ecp = true;\n            } else {\n                _with_ecp = false;\n            }\n            _with_guess = options->ifExistsReturnElseReturnDefault<bool>(key + \".read_guess\", false);\n            _initial_guess = options->ifExistsReturnElseReturnDefault<string>(key + \".initial_guess\", \"atom\");\n\n\n            // numerical integrations\n            _grid_name = options->ifExistsReturnElseReturnDefault<string>(key + \".integration_grid\", \"medium\");\n            _use_small_grid = options->ifExistsReturnElseReturnDefault<bool>(key + \".integration_grid_small\", true);\n            _grid_name_small = Choosesmallgrid(_grid_name);\n\n            // exchange and correlation as in libXC\n\n            _xc_functional_name = options->ifExistsReturnElseThrowRuntimeError<string>(key + \".xc_functional\");\n\n            _numofelectrons = 0;\n\n            if (options->exists(key + \".convergence\")) {\n\n                _Econverged = options->ifExistsReturnElseReturnDefault<double>(key + \".convergence.energy\", 1e-7);\n                _error_converged = options->ifExistsReturnElseReturnDefault<double>(key + \".convergence.error\", 1e-7);\n                _max_iter = options->ifExistsReturnElseReturnDefault<int>(key + \".convergence.max_iterations\", 100);\n\n\n\n                if (options->exists(key + \".convergence.method\")) {\n                    string method = options->get(key + \".convergence.method\").as<string>();\n                    if (method == \"DIIS\") {\n                        _usediis = true;\n                    } else if (method == \"mixing\") {\n                        _usediis = false;\n                    } else {\n                        cout << \"WARNING method not known. Using Mixing\" << endl;\n                        _usediis = false;\n                    }\n                } else {\n                    _usediis = true;\n                }\n                if (!_usediis) {\n                    _histlength = 1;\n                    _maxout = false;\n                }\n\n                if (options->exists(key + \".convergence.mixing\")) {\n                    _useautomaticmixing = false;\n                    _mixingparameter = options->get(key + \".convergence.mixing\").as<double>();\n                } else {\n                    _useautomaticmixing = true;\n                    _mixingparameter = -10;\n                }\n\n                _levelshift = options->ifExistsReturnElseReturnDefault<double>(key + \".convergence.levelshift\", 0.0);\n                _levelshiftend = options->ifExistsReturnElseReturnDefault<double>(key + \".convergence.levelshift_end\", 0.8);\n                _maxout = options->ifExistsReturnElseReturnDefault<bool>(key + \".convergence.DIIS_maxout\", false);\n                _histlength = options->ifExistsReturnElseReturnDefault<int>(key + \".convergence.DIIS_length\", 10);\n                _diis_start = options->ifExistsReturnElseReturnDefault<double>(key + \".convergence.DIIS_start\", 0.01);\n                _adiis_start = options->ifExistsReturnElseReturnDefault<double>(key + \".convergence.ADIIS_start\", 2);\n\n            } else {\n                _Econverged = 1e-7;\n                _error_converged = 1e-7;\n                _maxout = false;\n                _diis_start = 0.01;\n                _adiis_start = 2;\n                _histlength = 10;\n                _useautomaticmixing = true;\n                _mixingparameter = -10;\n                _usediis = true;\n                _max_iter = 100;\n                _levelshift = 0.25;\n                _levelshiftend = 0.8;\n            }\n\n            return;\n        }\n\n        /*\n         *    Density Functional theory implementation\n         *\n         */\n\n\n\n\n        bool DFTENGINE::Evaluate(Orbitals* _orbitals) {\n\n\n            // set the parallelization\n#ifdef _OPENMP\n\n            omp_set_num_threads(_openmp_threads);\n\n#endif\n\n\n\n\n\n            /**** END OF PREPARATION ****/\n\n            /**** Density-independent matrices ****/\n\n\n\n            ub::vector<double>& MOEnergies = _orbitals->MOEnergies();\n            ub::matrix<double>& MOCoeff = _orbitals->MOCoefficients();\n            if (MOEnergies.size() != _dftbasis.AOBasisSize()) {\n                MOEnergies.resize(_dftbasis.AOBasisSize());\n            }\n            if (MOCoeff.size1() != _dftbasis.AOBasisSize() || MOCoeff.size2() != _dftbasis.AOBasisSize()) {\n                MOCoeff.resize(_dftbasis.AOBasisSize(), _dftbasis.AOBasisSize());\n            }\n\n            /**** Construct initial density  ****/\n\n            ub::matrix<double> H0 = _dftAOkinetic.Matrix() + _dftAOESP.getNuclearpotential();\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Constructed inital density \" << flush;\n\n\n            NuclearRepulsion();\n            \n\n\n            if (_addexternalsites) {\n                H0 += _dftAOESP.getExternalpotential();\n\n                H0 += _dftAODipole_Potential.getExternalpotential();\n                H0 += _dftAOQuadrupole_Potential.getExternalpotential();\n\n                double estat = ExternalRepulsion();\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" E_electrostatic \" << estat << flush;\n                E_nucnuc += estat;\n\n            }\n\n            if (_do_externalfield) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Integrated external potential on grid \" << flush;\n                double extneralgrid_nucint = ExternalGridRepulsion(_externalgrid_nuc);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Nuclei external potential interaction \" << extneralgrid_nucint << \" Hartree\" << flush;\n                H0 += _gridIntegration_ext.IntegrateExternalPotential(_externalgrid);\n                E_nucnuc += extneralgrid_nucint;\n            }\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Nuclear Repulsion Energy is \" << E_nucnuc << flush;\n\n\n            // if we have a guess we do not need this.\n            if (_with_guess) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Reading guess from orbitals object/file\" << flush;\n                _dftAOdmat = _orbitals->DensityMatrixGroundState();\n            } else if (guess_set) {\n                ConfigOrbfile(_orbitals);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Using starting guess from last iteration\" << flush;\n                _dftAOdmat = last_dmat;\n            } else {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Setup Initial Guess using: \" << _initial_guess << flush;\n                // this temp is necessary because eigenvalues_general returns MO^T and not MO\n                if (_initial_guess == \"independent\") {\n                    ub::matrix<double> copy = H0;\n                    _diis.SolveFockmatrix(MOEnergies, MOCoeff, copy);\n                    _dftAOdmat = _orbitals->DensityMatrixGroundState();\n\n                } else if (_initial_guess == \"atom\") {\n\n                    _dftAOdmat = AtomicGuess(_orbitals);\n                    //cout<<_dftAOdmat<<endl;\n\n                    if (_with_RI) {\n                        _ERIs.CalculateERIs(_dftAOdmat);\n                    } else {\n                        _ERIs.CalculateERIs_4c_small_molecule(_dftAOdmat);\n                    }\n                    if (_use_small_grid) {\n                        _orbitals->AOVxc() = _gridIntegration_small.IntegrateVXC(_dftAOdmat);\n                        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled approximate DFT Vxc matrix \" << flush;\n                    } else {\n                        _orbitals->AOVxc() = _gridIntegration.IntegrateVXC(_dftAOdmat);\n                        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Vxc matrix \" << flush;\n                    }\n                    ub::matrix<double> H = H0 + _ERIs.getERIs() + _orbitals->AOVxc();\n                    _diis.SolveFockmatrix(MOEnergies, MOCoeff, H);\n                    _dftAOdmat = _orbitals->DensityMatrixGroundState();\n                    //cout<<_dftAOdmat<<endl;\n                    //Have to do one full iteration here, levelshift needs MOs;\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Full atomic density Matrix gives N=\" << std::setprecision(9) << linalg_traceofProd(_dftAOdmat, _dftAOoverlap.Matrix()) << \" electrons.\" << flush;\n                } else {\n                    throw runtime_error(\"Initial guess method not known/implemented\");\n                }\n\n            }\n\n\n            _orbitals->setQMpackage(\"xtp\");\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" STARTING SCF cycle\" << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \" --------------------------------------------------------------------------\" << flush;\n\n            double energyold = 0;\n            double diiserror = 100; //is evolved in DIIs scheme\n            Mixing Mixer(_useautomaticmixing, _mixingparameter, &_dftAOoverlap.Matrix(), _pLog);\n\n            for (_this_iter = 0; _this_iter < _max_iter; _this_iter++) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Iteration \" << _this_iter + 1 << \" of \" << _max_iter << flush;\n\n                if (_with_RI) {\n                    _ERIs.CalculateERIs(_dftAOdmat);\n                } else {\n                    _ERIs.CalculateERIs_4c_small_molecule(_dftAOdmat);\n                }\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Electron repulsion matrix of dimension: \" << _ERIs.getSize1() << \" x \" << _ERIs.getSize2() << flush;\n                double vxcenergy = 0.0;\n                if (_use_small_grid && diiserror > 1e-5) {\n                    _orbitals->AOVxc() = _gridIntegration_small.IntegrateVXC(_dftAOdmat);\n                    vxcenergy = _gridIntegration_small.getTotEcontribution();\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled approximate DFT Vxc matrix \" << flush;\n                } else {\n                    _orbitals->AOVxc() = _gridIntegration.IntegrateVXC(_dftAOdmat);\n                    vxcenergy = _gridIntegration.getTotEcontribution();\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Vxc matrix \" << flush;\n                }\n                //cout<<_dftAOdmat<<endl;\n                ub::matrix<double> H = H0 + _ERIs.getERIs() + _orbitals->AOVxc();\n                //cout<<H0<<endl;\n                //exit(0);\n                double Eone = linalg_traceofProd(_dftAOdmat, H0);\n                double Etwo = 0.5 * _ERIs.getERIsenergy() + vxcenergy;\n                double totenergy = Eone + E_nucnuc + Etwo;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Single particle energy \" << std::setprecision(12) << Eone << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Two particle energy \" << std::setprecision(12) << Etwo << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << std::setprecision(12) << \" Exc contribution \" << vxcenergy << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Total Energy \" << std::setprecision(12) << totenergy << flush;\n\n                diiserror = _diis.Evolve(_dftAOdmat, H, MOEnergies, MOCoeff, _this_iter, totenergy);\n                //cout<<\"Energies \"<<MOEnergies<<endl;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" DIIs error \" << diiserror << flush;\n\n                ub::matrix<double> dmatin = _dftAOdmat;\n                _dftAOdmat = _orbitals->DensityMatrixGroundState();\n                if (!(diiserror < _adiis_start && _usediis && _this_iter > 2)) {\n                    _dftAOdmat = Mixer.MixDmat(dmatin, _dftAOdmat);\n\n                } else {\n                    Mixer.Updatemix(dmatin, _dftAOdmat);\n                }\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Updated Density Matrix \" << flush;\n\n                if (tools::globals::verbose) {\n                    for (int i = 0; i<int(MOEnergies.size()); i++) {\n                        if (i <= _numofelectrons / 2 - 1) {\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t\" << i << \" occ \" << MOEnergies(i) << flush;\n                        } else {\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t\" << i << \" vir \" << MOEnergies(i) << flush;\n\n                        }\n                    }\n                }\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\tGAP \" << MOEnergies(_numofelectrons / 2) - MOEnergies(_numofelectrons / 2 - 1) << flush;\n\n                if (std::abs(totenergy - energyold) < _Econverged && diiserror < _error_converged) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Total Energy has converged to \" << std::setprecision(9) << std::abs(totenergy - energyold) << \"[Ha] after \" << _this_iter + 1 <<\n                            \" iterations. DIIS error is converged up to \" << _error_converged << \"[Ha]\" << flush;\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Final Single Point Energy \" << std::setprecision(12) << totenergy << \" Ha\" << flush;\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" MO Energies  [Ha]\" << flush;\n                    for (int i = 0; i<int(MOEnergies.size()); i++) {\n                        if (i <= _numofelectrons / 2 - 1) {\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t\" << i << \" occ \" << std::setprecision(12) << MOEnergies(i) << flush;\n                        } else {\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t\" << i << \" vir \" << std::setprecision(12) << MOEnergies(i) << flush;\n                        }\n                    }\n\n                    last_dmat = _dftAOdmat;\n                    guess_set = true;\n                    // orbitals saves total energies in [eV]\n                    _orbitals->setQMEnergy(totenergy * tools::conv::hrt2ev);\n                    break;\n                } else {\n                    energyold = totenergy;\n                }\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Density Matrix gives N=\" << std::setprecision(9) << linalg_traceofProd(_dftAOdmat, _dftAOoverlap.Matrix()) << \" electrons.\" << flush;\n\n            }\n            return true;\n        }\n\n\n\n\n        // SETUP INVARIANT AOMatrices\n\n        void DFTENGINE::SetupInvariantMatrices() {\n\n\n            // local variables for checks\n            // check eigenvalues of overlap matrix, if too small basis might have linear dependencies\n            ub::vector<double> _eigenvalues;\n            ub::matrix<double> _eigenvectors;\n\n            {\n                // DFT AOOverlap matrix\n                _dftAOoverlap.Fill(_dftbasis);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Overlap matrix of dimension: \" << _dftAOoverlap.Dimension() << flush;\n                //cout<<\"overlap\"<<_dftAOoverlap.Matrix()<<endl;\n                // check DFT basis for linear dependence\n                linalg_eigenvalues(_dftAOoverlap.Matrix(), _eigenvalues, _eigenvectors);\n\n                //Not brilliant but we need S-1/2 for DIIS and I do not want to calculate it each time\n                ub::matrix<double> _diagS = ub::zero_matrix<double>(_eigenvectors.size1(), _eigenvectors.size1());\n                for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {\n\n                    _diagS(_i, _i) = 1.0 / sqrt(_eigenvalues[_i]);\n                }\n                ub::matrix<double> _temp = ub::prod(_diagS, ub::trans(_eigenvectors));\n                _Sminusonehalf = ub::prod(_eigenvectors, _temp);\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Smallest eigenvalue of DFT Overlap matrix : \" << _eigenvalues[0] << flush;\n            }\n\n          \n            _dftAOkinetic.Fill(_dftbasis);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Kinetic energy matrix of dimension: \" << _dftAOkinetic.Dimension() << flush;\n\n\n          \n            _dftAOESP.Fillnucpotential(_dftbasis, _atoms, _with_ecp);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT nuclear potential matrix of dimension: \" << _dftAOESP.Dimension() << flush;\n\n            if (_addexternalsites) {\n                _dftAOESP.Fillextpotential(_dftbasis, _externalsites);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT external pointcharge potential matrix of dimension: \" << _dftAOESP.Dimension() << flush;\n\n                _dftAODipole_Potential.Fillextpotential(_dftbasis, _externalsites);\n                if (_dftAODipole_Potential.Dimension() > 0) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT external dipole potential matrix of dimension: \" << _dftAODipole_Potential.Dimension() << flush;\n                }\n                _dftAOQuadrupole_Potential.Fillextpotential(_dftbasis, _externalsites);\n                if (_dftAOQuadrupole_Potential.Dimension()) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT external quadrupole potential matrix of dimension: \" << _dftAOQuadrupole_Potential.Dimension() << flush;\n                }\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" External sites\\t Name \\t Coordinates \\t charge \\t dipole \\t quadrupole\" << flush;\n\n\n                for (unsigned i = 0; i < _externalsites.size(); i++) {\n\n                    vector<ctp::APolarSite*> ::iterator pit;\n                    for (pit = _externalsites[i]->begin(); pit < _externalsites[i]->end(); ++pit) {\n\n                        CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t \" << (*pit)->getName() << \" | \" << (*pit)->getPos().getX()\n                                << \" \" << (*pit)->getPos().getY() << \" \" << (*pit)->getPos().getZ() << \" | \" << (*pit)->getQ00();\n                        if ((*pit)->getRank() > 0) {\n                            tools::vec dipole = (*pit)->getQ1();\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t \" << \" | \" << dipole.getX()\n                                    << \" \" << dipole.getY() << \" \" << dipole.getZ();\n                        }\n                        if ((*pit)->getRank() > 1) {\n                            std::vector<double> quadrupole = (*pit)->getQ2();\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t \" << \" | \" << quadrupole[0] << \" \" << quadrupole[1] << \" \" << quadrupole[2] << \" \"\n                                    << quadrupole[3] << \" \" << quadrupole[4];\n                        }\n                        CTP_LOG(ctp::logDEBUG, *_pLog)  << flush;\n                    }\n                }\n            }\n\n\n\n\n            if (_with_ecp) {\n               \n                _dftAOECP.Fill(_dftbasis, vec(0, 0, 0), &_ecp);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT ECP matrix of dimension: \" << _dftAOECP.Dimension() << flush;\n                _dftAOESP.getNuclearpotential() += _dftAOECP.Matrix();\n            }\n\n            _diis.Configure(_usediis, true, _histlength, _maxout, _diismethod, _adiis_start, _diis_start, _levelshift, _levelshiftend, _numofelectrons / 2);\n            _diis.setLogger(_pLog);\n            _diis.setOverlap(&_dftAOoverlap.Matrix());\n            _diis.setSqrtOverlap(&_Sminusonehalf);\n\n            if (_with_RI) {\n\n                AOCoulomb _auxAOcoulomb;\n              \n                _auxAOcoulomb.Fill(_auxbasis);\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled AUX Coulomb matrix of dimension: \" << _auxAOcoulomb.Dimension() << flush;\n                \n                int dimensions = _auxAOcoulomb.Invert_DFT();\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Inverted AUX Coulomb matrix, removed \" << dimensions << \" functions from aux basis\" << flush;\n\n\n                // prepare invariant part of electron repulsion integrals\n                _ERIs.Initialize(_dftbasis, _auxbasis, _auxAOcoulomb.Matrix());\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Setup invariant parts of Electron Repulsion integrals \" << flush;\n            } else {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculating 4c integrals. \" << flush;\n                _ERIs.Initialize_4c_small_molecule(_dftbasis);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculated 4c integrals. \" << flush;\n            }\n\n            return;\n        }\n\n        ub::matrix<double> DFTENGINE::AtomicGuess(Orbitals* _orbitals) {\n            ub::matrix<double> guess = ub::zero_matrix<double>(_dftbasis.AOBasisSize());\n\n            std::vector<ctp::QMAtom*> uniqueelements;\n            std::vector<ctp::QMAtom*>::const_iterator at;\n            std::vector<ctp::QMAtom*>::iterator st;\n            std::vector< ub::matrix<double> > uniqueatom_guesses;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Scanning molecule of size \" << _atoms.size() << \" for unique elements\" << flush;\n            for (at = _atoms.begin(); at < _atoms.end(); ++at) {\n                bool exists = false;\n                if (uniqueelements.size() == 0) {\n                    exists = false;\n                } else {\n                    for (st = uniqueelements.begin(); st < uniqueelements.end(); ++st) {\n                        if ((*at)->type == (*st)->type) {\n                            exists = true;\n                            break;\n                        }\n                    }\n                }\n                if (!exists) {\n                    uniqueelements.push_back((*at));\n                }\n            }\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" \" << uniqueelements.size() << \" unique elements found\" << flush;\n            Elements _elements;\n            for (st = uniqueelements.begin(); st < uniqueelements.end(); ++st) {\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculating atom density for \" << (*st)->type << flush;\n                bool with_ecp = _with_ecp;\n                if ((*st)->type == \"H\" || (*st)->type == \"He\") {\n                    with_ecp = false;\n                }\n                std::vector<ctp::QMAtom*> atom;\n                atom.push_back(*st);\n\n                AOBasis dftbasis;\n                AOBasis ecp;\n                NumericalIntegration gridIntegration;\n                dftbasis.AOBasisFill(&_dftbasisset, atom);\n                if (with_ecp) {\n                    ecp.ECPFill(&_ecpbasisset, atom);\n                }\n                gridIntegration.GridSetup(_grid_name, &_dftbasisset, atom, &dftbasis);\n                gridIntegration.setXCfunctional(_xc_functional_name);\n                int numofelectrons = int(_elements.getNucCrg((*st)->type));\n                int alpha_e = 0;\n                int beta_e = 0;\n                if (with_ecp) {\n                    numofelectrons -= int(_ecpbasisset.getElement((*st)->type)->getNcore());\n                }\n\n                if ((numofelectrons % 2) != 0) {\n                    alpha_e = numofelectrons / 2 + numofelectrons % 2;\n                    beta_e = numofelectrons / 2;\n                } else {\n                    alpha_e = numofelectrons / 2;\n                    beta_e = alpha_e;\n                }\n\n                AOOverlap dftAOoverlap;\n                AOKinetic dftAOkinetic;\n                AOESP dftAOESP;\n                AOECP dftAOECP;\n                ub::vector<double> eigenvalues;\n                ub::matrix<double> eigenvectors;\n                ub::matrix<double> Sminusonehalf;\n                ERIs ERIs_atom;\n\n                // DFT AOOverlap matrix\n              \n                dftAOoverlap.Fill(dftbasis);\n                linalg_eigenvalues(dftAOoverlap.Matrix(), eigenvalues, eigenvectors);\n\n                //Not brilliant but we need S-1/2 for DIIS and I do not want to calculate it each time\n                ub::matrix<double> _diagS = ub::zero_matrix<double>(eigenvectors.size1(), eigenvectors.size1());\n                for (unsigned _i = 0; _i < eigenvalues.size(); _i++) {\n\n                    _diagS(_i, _i) = 1.0 / sqrt(eigenvalues[_i]);\n                }\n                ub::matrix<double> _temp = ub::prod(_diagS, ub::trans(eigenvectors));\n                Sminusonehalf = ub::prod(eigenvectors, _temp);\n\n               \n                dftAOkinetic.Fill(dftbasis);\n\n               \n                dftAOESP.Fillnucpotential(dftbasis, atom, with_ecp);\n                ERIs_atom.Initialize_4c_small_molecule(dftbasis);\n\n                ub::vector<double>MOEnergies_alpha;\n                ub::matrix<double>MOCoeff_alpha;\n                ub::vector<double>MOEnergies_beta;\n                ub::matrix<double>MOCoeff_beta;\n                Diis diis_alpha;\n                Diis diis_beta;\n                double adiisstart = 0;\n                double diisstart = 0.0001;\n                Mixing Mix_alpha(true, 0.7, &dftAOoverlap.Matrix(), _pLog);\n                Mixing Mix_beta(true, 0.7, &dftAOoverlap.Matrix(), _pLog);\n                diis_alpha.Configure(true, false, 20, 0, \"\", adiisstart, diisstart, 0.1, 0.000, alpha_e);\n                diis_alpha.setLogger(_pLog);\n                diis_alpha.setOverlap(&dftAOoverlap.Matrix());\n                diis_alpha.setSqrtOverlap(&Sminusonehalf);\n                diis_beta.Configure(true, false, 20, 0, \"\", adiisstart, diisstart, 0.1, 0.000, beta_e);\n                diis_beta.setLogger(_pLog);\n                diis_beta.setOverlap(&dftAOoverlap.Matrix());\n                diis_beta.setSqrtOverlap(&Sminusonehalf);\n                /**** Construct initial density  ****/\n\n                ub::matrix<double> H0 = dftAOkinetic.Matrix() + dftAOESP.getNuclearpotential();\n                if (with_ecp) {\n                    dftAOECP.Fill(dftbasis, vec(0, 0, 0), &ecp);\n                    H0 += dftAOECP.Matrix();\n                }\n                ub::matrix<double> copy = H0;\n                diis_alpha.SolveFockmatrix(MOEnergies_alpha, MOCoeff_alpha, copy);\n\n                MOEnergies_beta = MOEnergies_alpha;\n                MOCoeff_beta = MOCoeff_alpha;\n\n\n                //ub::matrix<double>dftAOdmat_alpha = DensityMatrix_frac(MOCoeff_alpha,MOEnergies_alpha,alpha_e);\n                //ub::matrix<double>dftAOdmat_beta = DensityMatrix_frac(MOCoeff_beta,MOEnergies_beta,beta_e);\n                ub::matrix<double>dftAOdmat_alpha = DensityMatrix_unres(MOCoeff_alpha, alpha_e);\n                if ((*st)->type == \"H\") {\n                    uniqueatom_guesses.push_back(dftAOdmat_alpha);\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Atomic density Matrix for \" << (*st)->type <<\n                            \" gives N=\" << std::setprecision(9) << linalg_traceofProd(dftAOdmat_alpha, dftAOoverlap.Matrix()) << \" electrons.\" << flush;\n                    continue;\n                }\n\n                ub::matrix<double>dftAOdmat_beta = DensityMatrix_unres(MOCoeff_beta, beta_e);\n                bool _HF = false;\n                double energyold = 0;\n                int maxiter = 50;\n                for (int this_iter = 0; this_iter < maxiter; this_iter++) {\n\n                    ERIs_atom.CalculateERIs_4c_small_molecule(dftAOdmat_alpha + dftAOdmat_beta);\n                    double E_two_alpha = linalg_traceofProd(ERIs_atom.getERIs(), dftAOdmat_alpha);\n                    double E_two_beta = linalg_traceofProd(ERIs_atom.getERIs(), dftAOdmat_beta);\n                    ub::matrix<double> H_alpha = H0 + ERIs_atom.getERIs();\n                    ub::matrix<double> H_beta = H0 + ERIs_atom.getERIs();\n                    if (_HF) {\n                        ERIs_atom.CalculateEXX_4c_small_molecule(dftAOdmat_alpha);\n                        double E_exx_alpha = -linalg_traceofProd(ERIs_atom.getEXX(), dftAOdmat_alpha);\n                        H_alpha -= ERIs_atom.getEXX();\n                        E_two_alpha += E_exx_alpha;\n                        ERIs_atom.CalculateEXX_4c_small_molecule(dftAOdmat_beta);\n                        double E_exx_beta = -linalg_traceofProd(ERIs_atom.getEXX(), dftAOdmat_beta);\n                        H_beta -= ERIs_atom.getEXX();\n                        E_two_beta += E_exx_beta;\n\n                    } else {\n                        ub::matrix<double> AOVxc_alpha = gridIntegration.IntegrateVXC(dftAOdmat_alpha);\n                        double E_vxc_alpha = gridIntegration.getTotEcontribution();\n                        ub::matrix<double> AOVxc_beta = gridIntegration.IntegrateVXC(dftAOdmat_beta);\n                        double E_vxc_beta = gridIntegration.getTotEcontribution();\n                        H_alpha += AOVxc_alpha;\n                        H_beta += AOVxc_beta;\n                        E_two_alpha += E_vxc_alpha;\n                        E_two_beta += E_vxc_beta;\n\n                    }\n                    double E_one_alpha = linalg_traceofProd(dftAOdmat_alpha, H0);\n                    double E_one_beta = linalg_traceofProd(dftAOdmat_beta, H0);\n\n                    double E_alpha = E_one_alpha + E_two_alpha;\n                    double E_beta = E_one_beta + E_two_beta;\n\n                    double totenergy = E_alpha + E_beta;\n                    //evolve alpha\n                    double diiserror_alpha = diis_alpha.Evolve(dftAOdmat_alpha, H_alpha, MOEnergies_alpha, MOCoeff_alpha, this_iter, E_alpha);\n\n                    ub::matrix<double> dmatin_alpha = dftAOdmat_alpha;\n                    dftAOdmat_alpha = DensityMatrix_unres(MOCoeff_alpha, alpha_e);\n\n                    if (!(diiserror_alpha < 0.005 && this_iter > 2)) {\n                        dftAOdmat_alpha = Mix_alpha.MixDmat(dmatin_alpha, dftAOdmat_alpha, false);\n                        //cout<<\"mixing_alpha\"<<endl;\n                    } else {\n                        Mix_alpha.Updatemix(dmatin_alpha, dftAOdmat_alpha);\n                    }\n                    //evolve beta\n                    double diiserror_beta = diis_beta.Evolve(dftAOdmat_beta, H_beta, MOEnergies_beta, MOCoeff_beta, this_iter, E_beta);\n                    ub::matrix<double> dmatin_beta = dftAOdmat_beta;\n                    dftAOdmat_beta = DensityMatrix_unres(MOCoeff_beta, beta_e);\n                    //dftAOdmat_beta=DensityMatrix_frac(MOCoeff_beta,MOEnergies_beta,beta_e);\n                    if (!(diiserror_beta < 0.005 && this_iter > 2)) {\n                        dftAOdmat_beta = Mix_beta.MixDmat(dmatin_beta, dftAOdmat_beta, false);\n\n                    } else {\n                        Mix_beta.Updatemix(dmatin_beta, dftAOdmat_beta);\n                    }\n\n\n                    if (tools::globals::verbose) {\n                        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Iter \" << this_iter << \" of \" << maxiter\n                                << \" Etot \" << totenergy << \" diise_a \" << diiserror_alpha << \" diise_b \" << diiserror_beta\n                                << \" a_gap \" << MOEnergies_alpha(alpha_e) - MOEnergies_alpha(alpha_e - 1) << \" b_gap \" << MOEnergies_beta(beta_e) - MOEnergies_beta(beta_e - 1) << flush;\n                    }\n                    bool converged = (std::abs(totenergy - energyold) < _Econverged && diiserror_alpha < _error_converged && diiserror_beta < _error_converged);\n                    if (converged || this_iter == maxiter - 1) {\n\n                        if (converged) {\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Converged after \" << this_iter + 1 << \" iterations\" << flush;\n                        } else {\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Not converged after \" << this_iter + 1 <<\n                                    \" iterations. Using unconverged density. DIIsError_alpha=\" << diiserror_alpha << \" DIIsError_beta=\" << diiserror_beta << flush;\n                        }\n\n\n                        ub::matrix<double> avdmat = AverageShells(dftAOdmat_alpha + dftAOdmat_beta, dftbasis);\n                        uniqueatom_guesses.push_back(avdmat);\n                        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Atomic density Matrix for \" << (*st)->type << \" gives N=\"\n                                << std::setprecision(9) << linalg_traceofProd(avdmat, dftAOoverlap.Matrix()) << \" electrons.\" << flush;\n                        break;\n\n                    } else {\n                        energyold = totenergy;\n                    }\n                }\n            }\n            unsigned start = 0;\n            unsigned end = 0;\n            for (at = _atoms.begin(); at < _atoms.end(); ++at) {\n                unsigned index = 0;\n                for (unsigned i = 0; i < uniqueelements.size(); i++) {\n                    if ((*at)->type == uniqueelements[i]->type) {\n                        index = i;\n                        break;\n                    }\n                }\n\n                Element* element = _dftbasisset.getElement((*at)->type);\n                for (Element::ShellIterator its = element->firstShell(); its != element->lastShell(); its++) {\n                    end += (*its)->getnumofFunc();\n                }\n                ub::project(guess, ub::range(start, end), ub::range(start, end)) = uniqueatom_guesses[index];\n\n\n                start = end;\n            }\n\n            return guess;\n        }\n\n        void DFTENGINE::ConfigOrbfile(Orbitals* _orbitals) {\n            if (_with_guess) {\n\n                if (_orbitals->hasDFTbasis()) {\n                    if (_orbitals->getDFTbasis() != _dftbasis_name) {\n                        throw runtime_error((boost::format(\"Basisset Name in guess orb file and in dftengine option file differ %1% vs %2%\") % _orbitals->getDFTbasis() % _dftbasis_name).str());\n                    }\n                } else {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" WARNING: Orbital file has no basisset information,using it as a guess might work or not for calculation with \" << _dftbasis_name << flush;\n                }\n            }\n            _orbitals->setDFTbasis(_dftbasis_name);\n            _orbitals->setBasisSetSize(_dftbasis.AOBasisSize());\n            if (_with_ecp) {\n                _orbitals->setECP(_ecp_name);\n            }\n\n            if (_with_guess) {\n                if(_orbitals->hasECP() || _with_ecp){\n                    if(_orbitals->getECP()!=_ecp_name){\n                        throw runtime_error((boost::format(\"ECPs in orb file: %1% and options %2% differ\") % _orbitals->getECP() % _ecp_name).str());\n                    }\n                }\n                if (_orbitals->getNumberOfElectrons() != _numofelectrons / 2) {\n                    throw runtime_error((boost::format(\"Number of electron in guess orb file: %1% and in dftengine: %2% differ.\") % _orbitals->getNumberOfElectrons() % (_numofelectrons / 2)).str());\n                }\n                if (_orbitals->getNumberOfLevels() != _dftbasis.AOBasisSize()) {\n                    throw runtime_error((boost::format(\"Number of levels in guess orb file: %1% and in dftengine: %2% differ.\") % _orbitals->getNumberOfLevels() % _dftbasis.AOBasisSize()).str());\n                }\n            } else {\n                _orbitals->setNumberOfElectrons(_numofelectrons / 2);\n                _orbitals->setNumberOfLevels(_numofelectrons / 2, _dftbasis.AOBasisSize() - _numofelectrons / 2);\n            }\n            return;\n        }\n\n\n        // PREPARATION\n\n        void DFTENGINE::Prepare(Orbitals* _orbitals) {\n            #ifdef _OPENMP\n\n            omp_set_num_threads(_openmp_threads);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Using \" << omp_get_max_threads() << \" threads\" << flush;\n\n#endif\n\n            if ( _atoms.size() == 0 ){\n            for (const auto& atom : _orbitals->QMAtoms()) {\n                if (!atom->from_environment) {\n                    _atoms.push_back(atom);\n                }\n            }\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Molecule Coordinates [A] \" << flush;\n            for (unsigned i = 0; i < _atoms.size(); i++) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t \" << _atoms[i]->type << \" \" << _atoms[i]->x << \" \" << _atoms[i]->y << \" \" << _atoms[i]->z << \" \" << flush;\n            }\n\n            // load and fill DFT basis set\n            _dftbasisset.LoadBasisSet(_dftbasis_name);\n\n            _dftbasis.AOBasisFill(&_dftbasisset, _atoms);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Loaded DFT Basis Set \" << _dftbasis_name << flush;\n\n            if (_with_RI) {\n                // load and fill AUX basis set\n                _auxbasisset.LoadBasisSet(_auxbasis_name);\n                //_orbitals->setDFTbasis( _dftbasis_name );\n                _auxbasis.AOBasisFill(&_auxbasisset, _atoms);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Loaded AUX Basis Set \" << _auxbasis_name << flush;\n            }\n            if (_with_ecp) {\n                // load ECP (element-wise information) from xml file\n                _ecpbasisset.LoadPseudopotentialSet(_ecp_name);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Loaded ECP library \" << _ecp_name << flush;\n\n                // fill auxiliary ECP basis by going through all atoms\n                _ecp.ECPFill(&_ecpbasisset, _atoms);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled ECP Basis of size \" << _ecp.getNumofShells() << flush;\n            }\n\n            // setup numerical integration grid\n            _gridIntegration.GridSetup(_grid_name, &_dftbasisset, _atoms, &_dftbasis);\n            _gridIntegration.setXCfunctional(_xc_functional_name);\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Setup numerical integration grid \" << _grid_name << \" for vxc functional \"\n                    << _xc_functional_name << \" with \" << _gridIntegration.getGridSize() << \" points\" << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t \" << \" divided into \" << _gridIntegration.getBoxesSize() << \" boxes\" << flush;\n            if (_use_small_grid) {\n                _gridIntegration_small.GridSetup(_grid_name_small, &_dftbasisset, _atoms, &_dftbasis);\n                _gridIntegration_small.setXCfunctional(_xc_functional_name);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Setup small numerical integration grid \" << _grid_name_small << \" for vxc functional \"\n                        << _xc_functional_name << \" with \" << _gridIntegration_small.getGridpoints().size() << \" points\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t \" << \" divided into \" << _gridIntegration_small.getBoxesSize() << \" boxes\" << flush;\n            }\n\n            if (_do_externalfield) {\n                _gridIntegration_ext.GridSetup(_grid_name_ext, &_dftbasisset, _atoms, &_dftbasis);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Setup numerical integration grid \" << _grid_name_ext\n                        << \" for external field with \" << _gridIntegration_ext.getGridpoints().size() << \" points\" << flush;\n            }\n\n            Elements _elements;\n            //set number of electrons and such\n\n\n            for (unsigned i = 0; i < _atoms.size(); i++) {\n                _numofelectrons += _elements.getNucCrg(_atoms[i]->type);\n            }\n\n            // if ECP\n            if (_with_ecp) {\n                for (unsigned i = 0; i < _atoms.size(); i++) {\n                    if (_atoms[i]->type == \"H\" || _atoms[i]->type == \"He\") {\n                        continue;\n                    } else {\n                        _numofelectrons -= _ecpbasisset.getElement(_atoms[i]->type)->getNcore();\n                    }\n                }\n            }\n            // here number of electrons is actually the total number, everywhere else in votca it is just alpha_electrons\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Total number of electrons: \" << _numofelectrons << flush;\n\n            ConfigOrbfile(_orbitals);\n            }\n            SetupInvariantMatrices();\n            return;\n        }\n\n        ub::matrix<double> DFTENGINE::DensityMatrix_unres(const ub::matrix<double>& MOs, int numofelec) {\n            if (numofelec == 0) {\n                return ub::zero_matrix<double>(MOs.size1());\n            }\n\n            ub::matrix<double> _dmatGS = ub::zero_matrix<double>(MOs.size1());\n#pragma omp parallel for\n            for (unsigned _i = 0; _i < MOs.size1(); _i++) {\n                for (unsigned _j = 0; _j < MOs.size1(); _j++) {\n                    for (int _level = 0; _level < numofelec; _level++) {\n\n                        _dmatGS(_i, _j) += MOs(_level, _i) * MOs(_level, _j);\n\n                    }\n                }\n            }\n            //}\n            // return\n            return _dmatGS;\n        }\n\n        ub::matrix<double> DFTENGINE::DensityMatrix_frac(const ub::matrix<double>& MOs, const ub::vector<double>& MOEnergies, int numofelec) {\n            if (numofelec == 0) {\n                return ub::zero_matrix<double>(MOs.size1());\n            }\n\n            ub::vector<double>occupation = ub::zero_vector<double>(MOEnergies.size());\n\n            double buffer = 0.0001;\n            double homo_energy = MOEnergies(numofelec - 1);\n            std::vector<unsigned> degeneracies;\n\n            for (unsigned _level = 0; _level < occupation.size(); _level++) {\n                if (MOEnergies(_level)<(homo_energy - buffer)) {\n                    occupation(_level) = 1.0;\n                    numofelec--;\n                } else if (std::abs(MOEnergies(_level) - homo_energy) < buffer) {\n                    degeneracies.push_back(_level);\n                } else if (MOEnergies(_level)>(homo_energy + buffer)) {\n                    occupation(_level) = 0.0;\n                }\n            }\n            double deg_occupation = double(numofelec) / double(degeneracies.size());\n            for (unsigned _level = 0; _level < degeneracies.size(); _level++) {\n                occupation(degeneracies[_level]) = deg_occupation;\n            }\n            ub::matrix<double> _dmatGS = ub::zero_matrix<double>(MOs.size1());\n#pragma omp parallel for\n            for (unsigned _i = 0; _i < MOs.size1(); _i++) {\n                for (unsigned _j = 0; _j < MOs.size1(); _j++) {\n                    for (unsigned _level = 0; _level < occupation.size(); _level++) {\n\n                        _dmatGS(_i, _j) += occupation(_level) * MOs(_level, _i) * MOs(_level, _j);\n\n                    }\n                }\n            }\n            return _dmatGS;\n        }\n\n        void DFTENGINE::NuclearRepulsion() {\n            Elements element;\n            E_nucnuc = 0.0;\n\n            std::vector<double> charge;\n            for (unsigned i = 0; i < _atoms.size(); i++) {\n                string name = _atoms[i]->type;\n                //cout << \" Using atom \" << name << \"\\n\" << endl;\n                double Q = element.getNucCrg(name);\n                bool HorHe = (name == \"H\" || name == \"He\");\n                if (_with_ecp && !HorHe) {\n                    Q -= _ecpbasisset.getElement(name)->getNcore();\n                }\n                charge.push_back(Q);\n            }\n\n\n            for (unsigned i = 0; i < _atoms.size(); i++) {\n                const tools::vec& r1 = _atoms[i]->getPos() * tools::conv::ang2bohr;\n                double charge1 = charge[i];\n                for (unsigned j = 0; j < i; j++) {\n                    const tools::vec& r2 = _atoms[j]->getPos() * tools::conv::ang2bohr;\n                    double charge2 = charge[j];\n                    E_nucnuc += charge1 * charge2 / (abs(r1 - r2));\n                }\n            }\n            return;\n        }\n\n        double DFTENGINE::ExternalRepulsion(ctp::Topology* top) {\n            Elements element;\n\n            if (_externalsites.size() == 0) {\n                return 0;\n            }\n\n            QMMInterface qmminter;\n            ctp::PolarSeg nuclei = qmminter.Convert(_atoms);\n\n            ctp::PolarSeg::iterator pes;\n            for (ctp::APolarSite* nucleus:nuclei) {\n                nucleus->setIsoP(0.0);\n                string name = nucleus->getName();\n                double Q = element.getNucCrg(name);\n                bool HorHe = (name == \"H\" || name == \"He\");\n                if (_with_ecp && !HorHe) {\n                    Q -= _ecpbasisset.getElement(name)->getNcore();\n                }\n                nucleus->setQ00(Q, 0);\n            }\n            ctp::XInteractor actor;\n            actor.ResetEnergy();\n            nuclei.CalcPos();\n            double E_ext = 0.0;\n            for (ctp::PolarSeg* seg:_externalsites) {\n                seg->CalcPos();\n                tools::vec s = tools::vec(0.0);\n                if (top == NULL) {\n                    s = nuclei.getPos() -seg->getPos();\n                } else {\n                    s = top->PbShortestConnect(nuclei.getPos(),seg->getPos()) + nuclei.getPos() - seg->getPos();\n                }\n\n                for (auto nucleus:nuclei) {\n                    for (auto site:(*seg)) {\n                        actor.BiasIndu(*nucleus, *site, s);\n                        nucleus->Depolarize();\n                        E_ext += actor.E_f(*nucleus, *site);\n\n\n                    }\n                }\n            }\n            return E_ext * tools::conv::int2eV * tools::conv::ev2hrt;\n        }\n\n        double DFTENGINE::ExternalGridRepulsion(std::vector<double> externalpotential_nuc) {\n            Elements element;\n            double E_ext = 0.0;\n\n            if (!_do_externalfield) {\n                return 0;\n            }\n\n            for (unsigned i = 0; i < _atoms.size(); i++) {\n                string name = _atoms[i]->type;\n                double Q = element.getNucCrg(name);\n                bool HorHe = (name == \"H\" || name == \"He\");\n                if (_with_ecp && !HorHe) {\n                    Q -= _ecpbasisset.getElement(name)->getNcore();\n                }\n                E_ext += Q * externalpotential_nuc[i];\n            }\n\n            return E_ext;\n        }\n\n        string DFTENGINE::Choosesmallgrid(string largegrid) {\n            string smallgrid;\n\n            if (largegrid == \"xfine\") {\n                smallgrid = \"fine\";\n            } else if (largegrid == \"fine\") {\n                smallgrid = \"medium\";\n            } else if (largegrid == \"medium\") {\n                _use_small_grid = false;\n                smallgrid = \"medium\";\n            } else if (largegrid == \"coarse\") {\n                _use_small_grid = false;\n                smallgrid = \"coarse\";\n            } else if (largegrid == \"xcoarse\") {\n                _use_small_grid = false;\n                smallgrid = \"xcoarse\";\n            } else {\n                throw runtime_error(\"Grid name for Vxc integration not known.\");\n            }\n\n            return smallgrid;\n        }\n\n\n        //average atom densities matrices, for SP and other combined shells average each subshell separately. Does not really work yet!!\n\n        ub::matrix<double> DFTENGINE::AverageShells(const ub::matrix<double>& dmat, AOBasis& dftbasis) {\n            ub::matrix<double> avdmat = ub::zero_matrix<double>(dmat.size1());\n            AOBasis::AOShellIterator it;\n            int start = 0.0;\n            std::vector<int> starts;\n            std::vector<int> ends;\n            for (it = dftbasis.firstShell(); it < dftbasis.lastShell(); ++it) {\n                const AOShell* shell = dftbasis.getShell(it);\n                int end = shell->getNumFunc() + start;\n\n                if (shell->getLmax() != shell->getLmin()) {\n                    std::vector<int> temp = NumFuncSubShell(shell->getType());\n                    int numfunc = start;\n                    for (unsigned i = 0; i < temp.size(); i++) {\n\n                        starts.push_back(numfunc);\n                        numfunc += temp[i];\n                        ends.push_back(numfunc);\n                    }\n                } else {\n                    starts.push_back(start);\n                    ends.push_back(end);\n                }\n                start = end;\n            }\n            for (unsigned k = 0; k < starts.size(); k++) {\n                int s1 = starts[k];\n                int e1 = ends[k];\n                int len1 = e1 - s1;\n                for (unsigned l = 0; l < starts.size(); l++) {\n                    int s2 = starts[l];\n                    int e2 = ends[l];\n                    int len2 = e2 - s2;\n                    double diag = 0.0;\n                    double offdiag = 0.0;\n                    for (int i = 0; i < len1; ++i) {\n                        for (int j = 0; j < len2; ++j) {\n                            if (i == j) {\n                                diag += dmat(s1 + i, s2 + j);\n                            } else {\n                                offdiag += dmat(s1 + i, s2 + j);\n                            }\n                        }\n                    }\n                    if (len1 == len2) {\n                        diag = diag / double(len1);\n                        offdiag = offdiag / double(len1 * (len1 - 1));\n                    } else {\n                        double avg = (diag + offdiag) / double(len1 * len2);\n                        diag = avg;\n                        offdiag = avg;\n                    }\n                    for (int i = 0; i < len1; ++i) {\n                        for (int j = 0; j < len2; ++j) {\n                            if (i == j) {\n                                avdmat(s1 + i, s2 + j) = diag;\n                            } else {\n                                avdmat(s1 + i, s2 + j) = offdiag;\n                            }\n                        }\n                    }\n                }\n            }\n\n            return avdmat;\n        }\n    }\n}\n", "meta": {"hexsha": "9ebe3593805193d9666350617c919f0689b26731", "size": 52252, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/dftengine/dftengine.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/dftengine/dftengine.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/dftengine/dftengine.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": 46.6535714286, "max_line_length": 221, "alphanum_fraction": 0.5093393554, "num_tokens": 12925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.18715415826631682}}
{"text": "//   Copyright 2015 Patrick Putnam\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 CLOTHO_GENERAL_FITNESS_SELECTION_GENERATOR_HPP_\n#define CLOTHO_GENERAL_FITNESS_SELECTION_GENERATOR_HPP_\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n#include \"clotho/data_spaces/selection/fitness_selection_generator.hpp\"\n#include \"clotho/data_spaces/fitness/general_fitness.hpp\"\n\nnamespace clotho {\nnamespace genetics {\n\ntemplate < class RNG >\nclass SelectionGenerator< RNG, fitness_selection< GeneralFitness > > {\npublic:\n    typedef RNG             random_engine_type;\n    typedef GeneralFitness  fitness_space_type;\n\n    typedef typename fitness_space_type::individual_id_type                     individual_id_type;\n\n    typedef std::vector< std::pair< individual_id_type, individual_id_type > >  mate_pair_vector;\n\n    typedef typename mate_pair_vector::iterator                                 iterator;\n    typedef typename mate_pair_vector::const_iterator                           const_iterator;\n\n    SelectionGenerator( random_engine_type * rng, boost::property_tree::ptree & config ) :\n        m_rand( rng )\n    {}\n\n    void update( const fitness_space_type & fit, unsigned int N ) {\n        typedef typename fitness_space_type::fitness_type   fitness_score_type;\n        typedef typename fitness_space_type::const_iterator iterator;\n\n        bool constant_fitness = true;\n        unsigned int M = fit.individual_count();\n\n        iterator it = fit.begin(), end = fit.end();\n\n        if( it != end ) {\n            fitness_score_type prev = *it++;\n            while( constant_fitness && it != end ) {\n                fitness_score_type cur = *it++;\n                constant_fitness = (prev == cur);\n            }\n        }\n\n        if( constant_fitness ) {\n            boost::random::uniform_int_distribution< individual_id_type > uni( 0, ((M == 0) ? 0 : (M - 1)) );\n            generate( uni, N );\n        } else {\n            boost::random::discrete_distribution< individual_id_type, fitness_score_type > disc( fit.begin(), fit.end() );\n            generate( disc, N );\n        }\n    }\n\n    mate_pair_vector & getMatePairs() const {\n        return m_pairs;\n    }\n    \n    unsigned int individual_count() const {\n        return m_pairs.size();\n    }\n\n    iterator    begin() {\n        return m_pairs.begin();\n    }\n\n    iterator    end() {\n        return m_pairs.end();\n    }\n\n    const_iterator    begin() const {\n        return m_pairs.begin();\n    }\n\n    const_iterator    end() const {\n        return m_pairs.end();\n    }\n\n    unsigned int size() const {\n        return individual_count();\n    }\n\n    virtual ~SelectionGenerator() {}\n\nprotected:\n\n    template < class DistributionType >\n    void generate( DistributionType & dist, size_t count ) {\n        m_pairs.clear();\n\n        while( m_pairs.size() < count ) {\n            individual_id_type  id0 = dist( *m_rand );\n            individual_id_type  id1 = dist( *m_rand );\n\n            m_pairs.push_back( std::make_pair( id0, id1 ) );\n        }\n    }\n\n    random_engine_type  * m_rand;\n    mate_pair_vector    m_pairs;\n};\n\n}   // namespace genetics\n}   // namespace clotho\n\n#endif  // CLOTHO_GENERAL_FITNESS_SELECTION_GENERATOR_HPP_\n\n", "meta": {"hexsha": "c92878b730281c910880be76565c8522a53deb05", "size": 3824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clotho/data_spaces/selection/general_fitness_selection_generator.hpp", "max_stars_repo_name": "putnampp/clotho", "max_stars_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T21:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:26:54.000Z", "max_issues_repo_path": "include/clotho/data_spaces/selection/general_fitness_selection_generator.hpp", "max_issues_repo_name": "putnampp/clotho", "max_issues_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T21:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-23T12:41:00.000Z", "max_forks_repo_path": "include/clotho/data_spaces/selection/general_fitness_selection_generator.hpp", "max_forks_repo_name": "putnampp/clotho", "max_forks_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "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": 30.8387096774, "max_line_length": 122, "alphanum_fraction": 0.6464435146, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.18715415471319582}}
{"text": "/***************************************************************************************************************************\n * aruco_det_v2.cpp\n * Author: Jario\n * Update Time: 2020.12.11\n *\n * \u8bf4\u660e: \u5355\u4e2a\u4e8c\u7ef4\u7801\u8bc6\u522b\u7a0b\u5e8f\uff0c\u53ef\u8bc6\u522b\u7684\u4e8c\u7ef4\u7801\u5728Prometheus/Modules/object_detection/config/aruco_images\u6587\u4ef6\u5939\u4e2d\n *      \u89c6\u91ce\u91cc\u53ea\u5141\u8bb8\u5b58\u5728\u4e00\u4e2a\u4e8c\u7ef4\u7801 \u4e14\u4e8c\u7ef4\u7801\u7684\u5b57\u5178\u7c7b\u578b\u8981\u5bf9\u5e94\n *      \u9ed8\u8ba4\u4e8c\u7ef4\u7801\u7684\u8fb9\u957f\u4e3a0.2m\n *      1. \u3010\u8ba2\u9605\u3011\u56fe\u50cf\u8bdd\u9898 (\u9ed8\u8ba4\u6765\u81eaweb_cam)\n *         /prometheus/camera/rgb/image_raw\n *      2. \u3010\u53d1\u5e03\u3011\u76ee\u6807\u4f4d\u7f6e\uff0c\u53d1\u5e03\u8bdd\u9898\u89c1 Prometheus/Modules/msgs/msg/DetectionInfo.msg\n *         /prometheus/object_detection/aruco_det\n *      3. \u3010\u53d1\u5e03\u3011\u68c0\u6d4b\u7ed3\u679c\u7684\u53ef\u89c6\u5316\u56fe\u50cf\u8bdd\u9898\n *         /prometheus/camera/rgb/image_aruco_det\n***************************************************************************************************************************/\n#include <pthread.h>\n#include <thread>\n#include <chrono>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/shared_mutex.hpp>\n\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <yaml-cpp/yaml.h>\n#include <image_transport/image_transport.h>  \n#include <cv_bridge/cv_bridge.h>  \n#include <sensor_msgs/image_encodings.h>  \n#include <geometry_msgs/PoseStamped.h>\n#include <std_msgs/Bool.h>\n#include <prometheus_msgs/DetectionInfo.h>\n#include <opencv2/imgproc/imgproc.hpp>  \n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/aruco.hpp>\n#include <opencv2/aruco/dictionary.hpp>\n#include <opencv2/aruco/charuco.hpp>\n#include <opencv2/calib3d.hpp>\n\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n\n// #include \"message_utils.h\"\n\n\nusing namespace std;\nusing namespace cv;\n\n//\u3010\u8ba2\u9605\u3011\u8f93\u5165\u56fe\u50cf\nimage_transport::Subscriber image_subscriber;\n//\u3010\u53d1\u5e03\u3011\u68c0\u6d4b\u5f97\u5230\u7684\u4f4d\u7f6e\u4e0e\u59ff\u6001\u4fe1\u606f\nros::Publisher pose_pub;\n//\u3010\u53d1\u5e03\u3011\u8f93\u5165\u68c0\u6d4b\u7ed3\u679c\u56fe\u50cf\nimage_transport::Publisher aruco_pub;\n\n\n// \u4f7f\u7528cout\u6253\u5370\u6d88\u606f\nbool local_print = true;\n\n\n// \u76f8\u673a\u8bdd\u9898\u4e2d\u7684\u56fe\u50cf\u540c\u6b65\u76f8\u5173\u53d8\u91cf\nint frame_width, frame_height;\nstd_msgs::Header image_header;\ncv::Mat cam_image_copy;\nboost::shared_mutex mutex_image_callback;\nbool image_status = false;\nboost::shared_mutex mutex_image_status;\n\n\n// \u56fe\u50cf\u63a5\u6536\u56de\u8c03\u51fd\u6570\uff0c\u63a5\u6536web_cam\u7684\u8bdd\u9898\uff0c\u5e76\u5c06\u56fe\u50cf\u4fdd\u5b58\u5728cam_image_copy\u4e2d\nvoid cameraCallback(const sensor_msgs::ImageConstPtr& msg)\n{\n    if (local_print) ROS_DEBUG(\"[ArucoDetector] USB image received.\");\n\n    cv_bridge::CvImagePtr cam_image;\n\n    try {\n        cam_image = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);\n        image_header = msg->header;\n    } catch (cv_bridge::Exception& e) {\n        if (local_print) ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n        return;\n    }\n\n    if (cam_image) {\n        {\n            boost::unique_lock<boost::shared_mutex> lockImageCallback(mutex_image_callback);\n            cam_image_copy = cam_image->image.clone();\n        }\n        {\n            boost::unique_lock<boost::shared_mutex> lockImageStatus(mutex_image_status);\n            image_status = true;\n        }\n        frame_width = cam_image->image.size().width;\n        frame_height = cam_image->image.size().height;\n    }\n    return;\n}\n\n// \u7528\u6b64\u51fd\u6570\u67e5\u770b\u662f\u5426\u6536\u5230\u56fe\u50cf\u8bdd\u9898\nbool getImageStatus(void)\n{\n    boost::shared_lock<boost::shared_mutex> lock(mutex_image_status);\n    return image_status;\n}\n\n\nstatic bool readCameraParameters(string filename, Mat &camMatrix, Mat &distCoeffs) {\n    FileStorage fs(filename, FileStorage::READ);\n    if(!fs.isOpened())\n        return false;\n    fs[\"camera_matrix\"] >> camMatrix;\n    fs[\"distortion_coefficients\"] >> distCoeffs;\n    return true;\n}\n\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"aruco_det_v2\");\n    ros::NodeHandle nh(\"~\");\n    image_transport::ImageTransport it(nh);\n    // \u66f4\u65b0\u9891\u7387\u4e3a60HZ\n    ros::Rate loop_rate(60);\n    //\u3010\u53d1\u5e03\u3011\u8bc6\u522b\n    pose_pub = nh.advertise<geometry_msgs::PoseStamped>(\"/prometheus/object_detection/aruco_det_v2\", 1);\n\n\n    std::string camera_topic = \"/prometheus/camera/rgb/image_raw\";\n    std::string camera_params_yaml;\n    std::string output_topic = \"/prometheus/camera/rgb/image_aruco_det\";\n    \n    if (nh.getParam(\"camera_topic\", camera_topic)) {\n        if (local_print) ROS_INFO(\"camera_topic is %s\", camera_topic.c_str());\n    } else {\n        if (local_print) ROS_WARN(\"didn't find parameter camera_topic\");\n    }\n    if (nh.getParam(\"camera_parameters\", camera_params_yaml)) {\n        if (local_print) ROS_INFO(\"camera_parameters is %s\", camera_params_yaml.c_str());\n    } else {\n        if (local_print) ROS_WARN(\"didn't find camera_parameters\");\n    }\n    if (nh.getParam(\"output_topic\", output_topic)) {\n        if (local_print) ROS_INFO(\"output_topic is %s\", output_topic.c_str());\n    } else {\n        if (local_print) ROS_WARN(\"didn't find parameter output_topic\");\n    }\n\n    // \u63a5\u6536\u56fe\u50cf\u7684\u8bdd\u9898\n    image_subscriber = it.subscribe(camera_topic.c_str(), 1, cameraCallback);\n    // \u53d1\u5e03ArUco\u68c0\u6d4b\u7ed3\u679c\u7684\u8bdd\u9898\n    aruco_pub = it.advertise(output_topic.c_str(), 1);\n\n    std::string ros_path = ros::package::getPath(\"prometheus_detection\");\n    if (local_print) ROS_INFO(\"DETECTION_PATH: %s\", ros_path.c_str());\n\n    cv::Mat camMatrix, distCoeffs;\n    bool readOk = readCameraParameters(camera_params_yaml.c_str(), camMatrix, distCoeffs);\n    if (!readOk) {\n        cerr << \"Invalid camera file\" << endl;\n        return 0;\n    }\n\n    if (local_print) {\n        cout << \"[camMatrix]:\" << endl;\n        cout << camMatrix << endl;\n        cout << \"[distCoeffs]:\" << endl;\n        cout << distCoeffs << endl;\n    }\n\n    int dictionaryId(2);\n    float markerLength(0.2);\n    Ptr<aruco::Dictionary> dictionary =\n        aruco::getPredefinedDictionary(aruco::PREDEFINED_DICTIONARY_NAME(dictionaryId));\n    Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();\n\n    cv::Mat frame, frameCopy;\n    const auto wait_duration = std::chrono::milliseconds(1000);\n    while (ros::ok())\n\t{\n        while (!getImageStatus() && ros::ok()) \n        {\n            if (local_print) cout << \"Waiting for image.\" << endl;\n            std::this_thread::sleep_for(wait_duration);\n            ros::spinOnce();\n        }\n\n        {\n            boost::unique_lock<boost::shared_mutex> lockImageCallback(mutex_image_callback);\n            frame = cam_image_copy.clone();\n        }\n\n        if (!frame.empty())\n        {\n            vector< int > ids;\n            vector< vector< Point2f > > corners, rejected;\n            vector< Vec3d > rvecs, tvecs;\n\n            // detect markers and estimate pose\n            aruco::detectMarkers(frame, dictionary, corners, ids, detectorParams, rejected);\n            if (ids.size() > 0)\n                aruco::estimatePoseSingleMarkers(corners, markerLength, camMatrix, distCoeffs, rvecs, tvecs);\n            \n            frame.copyTo(frameCopy);\n            if(ids.size() > 0) {\n                aruco::drawDetectedMarkers(frameCopy, corners, ids);\n\n                for(unsigned int i = 0; i < ids.size(); i++) {\n                    aruco::drawAxis(frameCopy, camMatrix, distCoeffs, rvecs[i], tvecs[i], markerLength * 0.5f);\n                    cv::Mat rotation_matrix;\n                    cv::Rodrigues(rvecs[i], rotation_matrix);\n                    Eigen::Matrix3d rotation_matrix_eigen;\n                    cv::cv2eigen(rotation_matrix, rotation_matrix_eigen);\n                    Eigen::Quaterniond q = Eigen::Quaterniond(rotation_matrix_eigen);\n                    q.normalize();\n\n                    geometry_msgs::PoseStamped pose;\n                    pose.header.frame_id = \"map\";\n                    pose.pose.position.x = tvecs[i][0];\n                    pose.pose.position.y = tvecs[i][1];\n                    pose.pose.position.z = tvecs[i][2];\n                    pose.pose.orientation.x = q.x();\n                    pose.pose.orientation.y = q.y();\n                    pose.pose.orientation.z = q.z();\n                    pose.pose.orientation.w = q.w();\n                    pose_pub.publish(pose);\n                }\n            }\n\n\n            sensor_msgs::ImagePtr det_output_msg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", frameCopy).toImageMsg();\n            aruco_pub.publish(det_output_msg);\n            // cv::imshow(\"frame\", frame);\n            // cv::waitKey(10);\n        }\n\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "89f88f1811140b7e6ecb3efd398249f01cfcf95e", "size": 8057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/object_detection/cpp_nodes/aruco_det_v2.cpp", "max_stars_repo_name": "wbzhang233/Prometheus", "max_stars_repo_head_hexsha": "95de01b6ed54d622bfd8b08b0987c2eb3a852893", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T07:55:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T07:55:54.000Z", "max_issues_repo_path": "Modules/object_detection/cpp_nodes/aruco_det_v2.cpp", "max_issues_repo_name": "maxibooksiyi/Prometheus", "max_issues_repo_head_hexsha": "f8cefb7ad517cf97338aa7d024ab577746882f8d", "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/object_detection/cpp_nodes/aruco_det_v2.cpp", "max_forks_repo_name": "maxibooksiyi/Prometheus", "max_forks_repo_head_hexsha": "f8cefb7ad517cf97338aa7d024ab577746882f8d", "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.2933884298, "max_line_length": 124, "alphanum_fraction": 0.6133796699, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18715415116007475}}
{"text": "\n#include <boost/python/def.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/return_internal_reference.hpp>\n#include <boost/python/return_by_value.hpp>\n#include <cctbx/adp_restraints/aniso_restraints.h>\n\nnamespace cctbx {namespace adp_restraints {\nnamespace {\n\n  void wrap_all ()\n  {\n    using namespace boost::python;\n    using namespace cctbx::geometry_restraints;\n    using namespace cctbx::xray;\n    typedef eval_adp_aniso_restraints w_t;\n    typedef return_value_policy<return_by_value> rbv;\n    class_<w_t>(\"eval_adp_aniso_restraints\", no_init)\n      .def(init<\n        af::const_ref<scatterer<> > const&,\n        af::const_ref<scitbx::sym_mat3<double> > const&,\n        af::const_ref<double> const&,\n        af::const_ref<bond_simple_proxy> const&,\n        af::const_ref<bool> const&,\n        af::const_ref<bool> const&,\n        unsigned,\n        bool>((\n          arg(\"scatterers\"),\n          arg(\"u_cart\"),\n          arg(\"u_iso\"),\n          arg(\"bond_proxies\"),\n          arg(\"selection\"),\n          arg(\"hd_selection\"),\n          arg(\"n_grad_u_iso\"),\n          arg(\"use_hd\"))))\n      .def(\"gradients_iso\", &w_t::gradients_iso)\n      .def(\"gradients_aniso_cart\", &w_t::gradients_aniso_cart)\n      .def_readonly(\"target\", &w_t::target)\n      .def_readonly(\"number_of_restraints\", &w_t::number_of_restraints)\n    ;\n  }\n}\nnamespace boost_python {\n  void wrap_aniso_restraints () { wrap_all(); }\n}\n}}\n", "meta": {"hexsha": "34cb30eb935190d125a71e548461ec7ba6ccad04", "size": 1597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/adp_restraints/aniso_restraints_bpl.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": "cctbx/adp_restraints/aniso_restraints_bpl.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": "cctbx/adp_restraints/aniso_restraints_bpl.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": 31.3137254902, "max_line_length": 71, "alphanum_fraction": 0.6700062617, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.18715414760695373}}
{"text": "//\u5934\u6587\u4ef6\n#include <ros/ros.h>\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n\n#include <state_from_mavros.h>\n#include <command_to_mavros.h>\n\n#include <px4_command_utils.h>\n#include <OptiTrackFeedBackRigidBody.h>\n#include <px4_command/ControlCommand.h>\n#include <px4_command/DroneState.h>\n#include <px4_command/TrajectoryPoint.h>\n#include <px4_command/AttitudeReference.h>\n\n#include <px4_command/Trajectory.h>\n//msg \u5934\u6587\u4ef6\n#include <mavros_msgs/CommandBool.h>\n#include <mavros_msgs/SetMode.h>\n#include <mavros_msgs/State.h>\n#include <mavros_msgs/AttitudeTarget.h>\n#include <mavros_msgs/PositionTarget.h>\n#include <mavros_msgs/ActuatorControl.h>\n#include <sensor_msgs/Imu.h>\n\n#include <bitset>\n#include <geometry_msgs/Vector3.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <std_msgs/Bool.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Point.h>\n#include <px4_command/Topic_for_log.h>\n\n\nusing namespace std;\n//---------------------------------------\u76f8\u5173\u53c2\u6570-----------------------------------------------\npx4_command::Topic_for_log _Topic_for_log;\n\nEigen::Vector3d pos_drone_mocap;                          //\u65e0\u4eba\u673a\u5f53\u524d\u4f4d\u7f6e (vicon)\nEigen::Quaterniond q_mocap;\nEigen::Vector3d Euler_mocap;                              //\u65e0\u4eba\u673a\u5f53\u524d\u59ff\u6001 (vicon)\nrigidbody_state UAVstate;\nEigen::Quaterniond q_fcu_target;\nEigen::Vector3d euler_fcu_target;\nfloat Thrust_target;\n\n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u51fd\u6570\u58f0\u660e<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nvoid printf_info();                                                                       //\u6253\u5370\u51fd\u6570\n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u56de\u8c03\u51fd\u6570<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nvoid log_cb(const px4_command::Topic_for_log::ConstPtr &msg)\n{\n    _Topic_for_log = *msg;\n}\n\nvoid att_target_cb(const mavros_msgs::AttitudeTarget::ConstPtr& msg)\n{\n    q_fcu_target = Eigen::Quaterniond(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z);\n\n    //Transform the Quaternion to euler Angles\n    euler_fcu_target = quaternion_to_euler(q_fcu_target);\n\n    Thrust_target = msg->thrust;\n}\n\nvoid optitrack_cb(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n    //\u4f4d\u7f6e -- optitrack\u7cfb \u5230 ENU\u7cfb\n    int optitrack_frame = 0; //Frame convention 0: Z-up -- 1: Y-up\n\n    if(optitrack_frame == 0)\n    {\n        // Read the Drone Position from the Vrpn Package [Frame: Vicon]  (Vicon to ENU frame)\n        pos_drone_mocap = Eigen::Vector3d(msg->pose.position.x,msg->pose.position.y,msg->pose.position.z);\n        // Read the Quaternion from the Vrpn Package [Frame: Vicon[ENU]]\n        q_mocap = Eigen::Quaterniond(msg->pose.orientation.w, msg->pose.orientation.x, msg->pose.orientation.y, msg->pose.orientation.z);\n    }\n    else\n    {\n        // Read the Drone Position from the Vrpn Package [Frame: Vicon]  (Vicon to ENU frame)\n        pos_drone_mocap = Eigen::Vector3d(-msg->pose.position.x,msg->pose.position.z,msg->pose.position.y);\n        // Read the Quaternion from the Vrpn Package [Frame: Vicon[ENU]]\n        q_mocap = Eigen::Quaterniond(msg->pose.orientation.w, msg->pose.orientation.x, msg->pose.orientation.z, msg->pose.orientation.y); //Y-up convention, switch the q2 & q3\n    }\n\n    // Transform the Quaternion to Euler Angles\n    Euler_mocap = quaternion_to_euler(q_mocap);\n\n}\n\n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u4e3b \u51fd \u6570<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"ground_station\");\n    ros::NodeHandle nh(\"~\");\n\n    // \u3010\u8ba2\u9605\u3011optitrack\u4f30\u8ba1\u4f4d\u7f6e\n    ros::Subscriber optitrack_sub = nh.subscribe<geometry_msgs::PoseStamped>(\"/vrpn_client_node/UAV/pose\", 10, optitrack_cb);\n\n    ros::Subscriber log_sub = nh.subscribe<px4_command::Topic_for_log>(\"/px4_command/topic_for_log\", 10, log_cb);\n\n    ros::Subscriber attitude_target_sub = nh.subscribe<mavros_msgs::AttitudeTarget>(\"/mavros/setpoint_raw/target_attitude\", 10,att_target_cb);\n\n    // \u9891\u7387\n    ros::Rate rate(10.0);\n\n    OptiTrackFeedBackRigidBody UAV(\"/vrpn_client_node/UAV/pose\",nh,3,3);\n\n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Main Loop<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n    while(ros::ok())\n    {\n        //\u56de\u8c03\u4e00\u6b21 \u66f4\u65b0\u4f20\u611f\u5668\u72b6\u6001\n        ros::spinOnce();\n\n        //\u5229\u7528OptiTrackFeedBackRigidBody\u7c7b\u83b7\u53d6optitrack\u7684\u6570\u636e\n        //UAV.GetOptiTrackState();\n\n        UAV.RosWhileLoopRun();\n        UAV.GetState(UAVstate);\n\n        //\u6253\u5370\n        printf_info();\n        rate.sleep();\n    }\n\n    return 0;\n\n}\n\nvoid printf_info()\n{\n    cout <<\">>>>>>>>>>>>>>>>>>>>>>>> Ground Station  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" <<endl;\n    //\u56fa\u5b9a\u7684\u6d6e\u70b9\u663e\u793a\n    cout.setf(ios::fixed);\n    //setprecision(n) \u8bbe\u663e\u793a\u5c0f\u6570\u7cbe\u5ea6\u4e3an\u4f4d\n    cout<<setprecision(2);\n    //\u5de6\u5bf9\u9f50\n    cout.setf(ios::left);\n    // \u5f3a\u5236\u663e\u793a\u5c0f\u6570\u70b9\n    cout.setf(ios::showpoint);\n    // \u5f3a\u5236\u663e\u793a\u7b26\u53f7\n    cout.setf(ios::showpos);\n\n    px4_command_utils::prinft_drone_state(_Topic_for_log.Drone_State);\n\n    px4_command_utils::printf_command_control(_Topic_for_log.Control_Command);\n\n    px4_command_utils::prinft_attitude_reference(_Topic_for_log.Attitude_Reference);\n\n\n    cout <<\">>>>>>>>>>>>>>>>>>>>>>>> Control Output  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" <<endl;\n    \n    cout << \"u_l [X Y Z]  : \" << _Topic_for_log.Control_Output.u_l[0] << \" [ ] \"<< _Topic_for_log.Control_Output.u_l[1] <<\" [ ] \"<< _Topic_for_log.Control_Output.u_l[2] <<\" [ ] \"<<endl;\n    \n    cout << \"u_d [X Y Z]  : \" << _Topic_for_log.Control_Output.u_d[0] << \" [ ] \"<< _Topic_for_log.Control_Output.u_d[1] <<\" [ ] \"<< _Topic_for_log.Control_Output.u_d[2] <<\" [ ] \"<<endl;\n    cout << \"NE  [X Y Z]  : \" << _Topic_for_log.Control_Output.NE[0] << \" [ ] \"<< _Topic_for_log.Control_Output.NE[1] <<\" [ ] \"<< _Topic_for_log.Control_Output.NE[2] <<\" [ ] \"<<endl;\n\n    cout << \"Thrust  [X Y Z]  : \" << _Topic_for_log.Control_Output.Thrust[0] << \" [ ] \"<< _Topic_for_log.Control_Output.Thrust[1] <<\" [ ] \"<< _Topic_for_log.Control_Output.Thrust[2] <<\" [ ] \"<<endl;\n\n    cout << \"Throttle  [X Y Z]  : \" << _Topic_for_log.Control_Output.Throttle[0] << \" [ ] \"<< _Topic_for_log.Control_Output.Throttle[1] <<\" [ ] \"<< _Topic_for_log.Control_Output.Throttle[2] <<\" [ ] \"<<endl;\n\n    cout <<\">>>>>>>>>>>>>>>>>>>>>>>> Target Info FCU <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" <<endl;\n    \n    cout << \"Pos_vicon [X Y Z]  : \" << pos_drone_mocap[0] << \" [ m ] \"<< pos_drone_mocap[1] <<\" [ m ] \"<< pos_drone_mocap[2] <<\" [ m ] \"<<endl;\n    \n    cout << \"Att_target [R P Y] : \" << euler_fcu_target[0] * 180/M_PI <<\" [deg]  \"<<euler_fcu_target[1] * 180/M_PI << \" [deg]  \"<< euler_fcu_target[2] * 180/M_PI<<\" [deg]  \"<<endl;\n    \n    cout << \"Thr_target [ 0-1 ] : \" << Thrust_target <<endl;\n\n    cout <<\">>>>>>>>>>>>>>>>>>>>>>>>Error Info [ Longhao ]<<<<<<<<<<<<<<<<<<<<<<<<<\" <<endl;\n    cout << \"Error_pos      : \" << UAVstate.Position[0] - _Topic_for_log.Drone_State.position[0] << \" [ m ] \"<< UAVstate.Position[1] - _Topic_for_log.Drone_State.position[1]<<\" [ m ] \"<< UAVstate.Position[2] - _Topic_for_log.Drone_State.position[2]<<\" [ m ] \"<<endl;\n    cout << \"Error_vel      : \" << UAVstate.V_I[0] - _Topic_for_log.Drone_State.velocity[0] << \" [m/s] \"<< UAVstate.V_I[1] - _Topic_for_log.Drone_State.velocity[1]<<\" [m/s] \"<< UAVstate.V_I[2] - _Topic_for_log.Drone_State.velocity[2]<<\" [m/s] \"<<endl;\n    cout << \"Error_att      : \" << UAVstate.Euler[0]*57.3 - _Topic_for_log.Drone_State.attitude[0]*57.3 << \" [deg] \"<< UAVstate.Euler[1]*57.3 - _Topic_for_log.Drone_State.attitude[1]*57.3<<\" [deg] \"<< UAVstate.Euler[2]*57.3 - _Topic_for_log.Drone_State.attitude[2]*57.3<<\" [deg] \"<<endl;\n    cout << \"Error_att_rate : \" << UAVstate.Omega_BI[0]*57.3 - _Topic_for_log.Drone_State.attitude_rate[0]*57.3 << \" [deg] \"<< UAVstate.Omega_BI[1]*57.3 - _Topic_for_log.Drone_State.attitude_rate[1]*57.3<<\" [deg] \"<< UAVstate.Omega_BI[2]*57.3 - _Topic_for_log.Drone_State.attitude_rate[2]*57.3<<\" [deg] \"<<endl;\n\n}\n", "meta": {"hexsha": "1f66f60c01d2ea5171ec33972358fe6ab92b5a1d", "size": 7799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ground_station.cpp", "max_stars_repo_name": "Airrey97/px4_command", "max_stars_repo_head_hexsha": "5b43443c49a61ba753debf572e9c7c989983abc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 140.0, "max_stars_repo_stars_event_min_datetime": "2019-08-07T13:46:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T02:02:56.000Z", "max_issues_repo_path": "src/ground_station.cpp", "max_issues_repo_name": "Airrey97/px4_command", "max_issues_repo_head_hexsha": "5b43443c49a61ba753debf572e9c7c989983abc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-11-06T09:34:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T13:59:35.000Z", "max_forks_repo_path": "src/ground_station.cpp", "max_forks_repo_name": "Airrey97/px4_command", "max_forks_repo_head_hexsha": "5b43443c49a61ba753debf572e9c7c989983abc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2019-08-03T02:33:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T07:52:14.000Z", "avg_line_length": 43.5698324022, "max_line_length": 311, "alphanum_fraction": 0.6062315681, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18715414405383277}}
{"text": "#include \"Phase2EndcapRing.h\"\n\n#include \"FWCore/MessageLogger/interface/MessageLogger.h\"\n\n#include \"TrackingTools/DetLayers/interface/DetLayerException.h\"\n#include \"TrackingTools/DetLayers/interface/MeasurementEstimator.h\"\n#include \"TrackingTools/GeomPropagators/interface/HelixForwardPlaneCrossing.h\"\n#include \"TrackingTools/DetLayers/interface/rangesIntersect.h\"\n#include \"TrackingTools/DetLayers/interface/ForwardRingDiskBuilderFromDet.h\"\n\n#include \"LayerCrossingSide.h\"\n#include \"DetGroupMerger.h\"\n#include \"CompatibleDetToGroupAdder.h\"\n\n#include \"TkDetUtil.h\"\n#include \"DataFormats/GeometryVector/interface/VectorUtil.h\"\n#include <boost/function.hpp>\n\nusing namespace std;\n\ntypedef GeometricSearchDet::DetWithState DetWithState;\n\nclass DetGroupElementZLess {\npublic:\n  bool operator()(DetGroup a,DetGroup b)\n  {\n    return (fabs(a.front().det()->position().z()) < fabs(b.front().det()->position().z()));\n  }\n};\n\nPhase2EndcapRing::Phase2EndcapRing(vector<const GeomDet*>& innerDets,\n\t\t\t       vector<const GeomDet*>& outerDets,\n\t\t\t       const vector<const GeomDet*>& innerDetBrothers,\n\t\t\t       const vector<const GeomDet*>& outerDetBrothers):\n  GeometricSearchDet(true),\n  theFrontDets(innerDets.begin(),innerDets.end()), \n  theBackDets(outerDets.begin(),outerDets.end()),\n  theFrontDetBrothers(innerDetBrothers.begin(),innerDetBrothers.end()), \n  theBackDetBrothers(outerDetBrothers.begin(),outerDetBrothers.end())\n{\n  theDets.assign(theFrontDets.begin(),theFrontDets.end());\n  theDets.insert(theDets.end(),theBackDets.begin(),theBackDets.end());\n  theDets.insert(theDets.end(),theFrontDetBrothers.begin(),theFrontDetBrothers.end());\n  theDets.insert(theDets.end(),theBackDetBrothers.begin(),theBackDetBrothers.end());\n\n\n  // the dets should be already phi-ordered. TO BE CHECKED\n  //sort( theFrontDets.begin(), theFrontDets.end(), DetLessPhi() );\n  //sort( theBackDets.begin(), theBackDets.end(), DetLessPhi() );\n\n  theDisk = ForwardRingDiskBuilderFromDet()( theDets );\n\n  theFrontDisk = ForwardRingDiskBuilderFromDet()( theFrontDets );\n  theBackDisk  = ForwardRingDiskBuilderFromDet()( theBackDets );\n\n  theFrontBinFinder = BinFinderType( theFrontDets.front()->surface().position().phi(),\n\t\t\t\t     theFrontDets.size());\n  theBackBinFinder  = BinFinderType( theBackDets.front()->surface().position().phi(),\n\t\t\t\t     theBackDets.size());  \n\n\n#ifdef EDM_ML_DEBUG\n  LogDebug(\"TkDetLayers\") << \"DEBUG INFO for Phase2EndcapRing\" ;\n  for(vector<const GeomDet*>::const_iterator it=theFrontDets.begin(); \n      it!=theFrontDets.end(); it++){\n    LogDebug(\"TkDetLayers\") << \"frontDet detId,phi,z,r: \"\n                            << (*it)->geographicalId().rawId()  << \" , \"\n\t\t\t    << (*it)->surface().position().phi()  << \" , \"\n\t\t\t    << (*it)->surface().position().z()    << \" , \"\n\t\t\t    << (*it)->surface().position().perp() ;\n  }\n\n  if(!theFrontDetBrothers.empty()){\n    for(vector<const GeomDet*>::const_iterator it=theFrontDetBrothers.begin(); \n        it!=theFrontDetBrothers.end(); it++){\n      LogDebug(\"TkDetLayers\") << \"frontDet brothers detId,phi,z,r: \"\n                            << (*it)->geographicalId().rawId()  << \" , \"\n  \t\t\t    << (*it)->surface().position().phi()  << \" , \"\n  \t\t\t    << (*it)->surface().position().z()    << \" , \"\n  \t\t\t    << (*it)->surface().position().perp() ;\n    }\n  }\n\n  for(vector<const GeomDet*>::const_iterator it=theBackDets.begin(); \n      it!=theBackDets.end(); it++){\n    LogDebug(\"TkDetLayers\") << \"backDet detId,phi,z,r: \"\n                            << (*it)->geographicalId().rawId()  << \" , \"\n\t\t\t    << (*it)->surface().position().phi() << \" , \"\n\t\t\t    << (*it)->surface().position().z()   << \" , \"\n\t\t\t    << (*it)->surface().position().perp() ;\n  }\n\n  if(!theBackDetBrothers.empty()){\n    for(vector<const GeomDet*>::const_iterator it=theBackDetBrothers.begin(); \n        it!=theBackDetBrothers.end(); it++){\n      LogDebug(\"TkDetLayers\") << \"backDet brothers detId,phi,z,r: \"\n                            << (*it)->geographicalId().rawId()  << \" , \"\n  \t\t\t    << (*it)->surface().position().phi() << \" , \"\n  \t\t\t    << (*it)->surface().position().z()   << \" , \"\n  \t\t\t    << (*it)->surface().position().perp() ;\n    }\n  }\n#endif\n\n}\n\nPhase2EndcapRing::~Phase2EndcapRing(){\n\n} \n\nconst vector<const GeometricSearchDet*>& \nPhase2EndcapRing::components() const \n{\n  throw DetLayerException(\"Phase2EndcapRing doesn't have GeometricSearchDet components\");\n}\n\n  \npair<bool, TrajectoryStateOnSurface>\nPhase2EndcapRing::compatible( const TrajectoryStateOnSurface&, const Propagator&, \n\t\t  const MeasurementEstimator&) const{\n  edm::LogError(\"TkDetLayers\") << \"temporary dummy implementation of Phase2EndcapRing::compatible()!!\" ;\n  return pair<bool,TrajectoryStateOnSurface>();\n}\n\n\n\nvoid \nPhase2EndcapRing::groupedCompatibleDetsV( const TrajectoryStateOnSurface& tsos,\n\t\t\t\t const Propagator& prop,\n\t\t\t\t const MeasurementEstimator& est,\n\t\t\t\t std::vector<DetGroup>& result) const\n{\n  SubLayerCrossings  crossings; \n  crossings = computeCrossings( tsos, prop.propagationDirection());\n  if(! crossings.isValid()) return;\n\n\n  std::vector<DetGroup> closestResult;\n  std::vector<DetGroup> closestBrotherResult;\n  addClosest( tsos, prop, est, crossings.closest(), closestResult,closestBrotherResult); \n  if (closestResult.empty())     return;\n  \n  DetGroupElement closestGel( closestResult.front().front());  \n  int crossingSide = LayerCrossingSide().endcapSide( closestGel.trajectoryState(), prop);\n  float phiWindow =  tkDetUtil::computeWindowSize( closestGel.det(), closestGel.trajectoryState(), est); \n  searchNeighbors( tsos, prop, est, crossings.closest(), phiWindow,\n\t\t   closestResult, closestBrotherResult, false); \n\n  vector<DetGroup> closestCompleteResult;\n  DetGroupMerger::orderAndMergeTwoLevels(std::move(closestResult),std::move(closestBrotherResult),closestCompleteResult,\n\t\t\t\t\t 0, crossingSide);\n\n  vector<DetGroup> nextResult;\n  vector<DetGroup> nextBrotherResult;\n  searchNeighbors( tsos, prop, est, crossings.other(), phiWindow,\n\t\t   nextResult, nextBrotherResult, true); \n\n  vector<DetGroup> nextCompleteResult;\n  DetGroupMerger::orderAndMergeTwoLevels(std::move(nextResult),std::move(nextBrotherResult),nextCompleteResult,\n\t\t\t\t\t 0, crossingSide);\n\n  DetGroupMerger::orderAndMergeTwoLevels( std::move(closestCompleteResult), std::move(nextCompleteResult), result,\n\t\t\t\t\t  crossings.closestIndex(), crossingSide);\n\n  //due to propagator problems, when we add single pt sub modules, we should order them in z (endcap)\n  if(!theFrontDetBrothers.empty() && !theBackDetBrothers.empty())\n    sort(result.begin(),result.end(),DetGroupElementZLess());\n\n#ifdef EDM_ML_DEBUG\n  LogTrace(\"TkDetLayers\") <<\"Number of groups : \" << result.size() << std::endl;\n  for (auto&  grp : result) {\n    if ( grp.empty() )  continue;\n      LogTrace(\"TkDetLayers\") <<\"New group in Phase2EndcapRing made by : \" << std::endl;\n      for (auto const & det : grp) {\n          LogTrace(\"TkDetLayers\") <<\" geom det at r: \" << det.det()->position().perp() <<\" id:\" << det.det()->geographicalId().rawId()\n                    <<\" tsos at:\" << det.trajectoryState().globalPosition() << std::endl;\n      }\n    }\n#endif\n\n}\n\n\nSubLayerCrossings \nPhase2EndcapRing::computeCrossings(const TrajectoryStateOnSurface& startingState,\n\t\t\t  PropagationDirection propDir) const\n{\n  auto rho = startingState.transverseCurvature();\n  \n  HelixPlaneCrossing::PositionType startPos( startingState.globalPosition() );\n  HelixPlaneCrossing::DirectionType startDir( startingState.globalMomentum() );\n  HelixForwardPlaneCrossing crossing(startPos,startDir,rho,propDir);\n\n  pair<bool,double> frontPath = crossing.pathLength( *theFrontDisk);\n  if (!frontPath.first) return SubLayerCrossings();\n\n  pair<bool,double> backPath = crossing.pathLength( *theBackDisk);\n  if (!backPath.first) return SubLayerCrossings();\n\n  GlobalPoint gFrontPoint(crossing.position(frontPath.second));\n  GlobalPoint gBackPoint( crossing.position(backPath.second));\n\n  int frontIndex = theFrontBinFinder.binIndex(gFrontPoint.barePhi()); \n  SubLayerCrossing frontSLC( 0, frontIndex, gFrontPoint);\n\n  int backIndex = theBackBinFinder.binIndex(gBackPoint.barePhi());\n  SubLayerCrossing backSLC( 1, backIndex, gBackPoint);\n\n  \n  // 0ss: frontDisk has index=0, backDisk has index=1\n  float frontDist = std::abs(Geom::deltaPhi( gFrontPoint.barePhi(), \n\t\t\t\t\t     theFrontDets[frontIndex]->surface().phi()));\n  float backDist = std::abs(Geom::deltaPhi( gBackPoint.barePhi(), \n\t\t\t\t\t    theBackDets[backIndex]->surface().phi()));\n\n\n  if (frontDist < backDist) {\n    return SubLayerCrossings( frontSLC, backSLC, 0);\n  }\n  else {\n    return SubLayerCrossings( backSLC, frontSLC, 1);\n  } \n}\n\nbool Phase2EndcapRing::addClosest( const TrajectoryStateOnSurface& tsos,\n\t\t\t\t const Propagator& prop,\n\t\t\t\t const MeasurementEstimator& est,\n\t\t\t\t const SubLayerCrossing& crossing,\n\t\t\t\t vector<DetGroup>& result,\n\t\t\t\t vector<DetGroup>& brotherresult) const\n{\n  const vector<const GeomDet*>& sub( subLayer( crossing.subLayerIndex()));\n  const GeomDet* det(sub[crossing.closestDetIndex()]);\n  bool firstgroup = CompatibleDetToGroupAdder::add( *det, tsos, prop, est, result); \n  if(theFrontDetBrothers.empty() && theBackDetBrothers.empty())   return firstgroup;\n  // it assumes that the closestDetIndex is ok also for the brother detectors: the crossing is NOT recomputed\n  const vector<const GeomDet*>& subBrothers( subLayerBrothers( crossing.subLayerIndex()));\n  const GeomDet* detBrother(subBrothers[crossing.closestDetIndex()]);\n  bool brothergroup = CompatibleDetToGroupAdder::add( *detBrother, tsos, prop, est, brotherresult); \n  return firstgroup || brothergroup;\n}\n\n\n\nvoid Phase2EndcapRing::searchNeighbors( const TrajectoryStateOnSurface& tsos,\n\t\t\t\t     const Propagator& prop,\n\t\t\t\t     const MeasurementEstimator& est,\n\t\t\t\t     const SubLayerCrossing& crossing,\n\t\t\t\t     float window, \n\t\t\t\t     vector<DetGroup>& result,\n\t\t\t\t     vector<DetGroup>& brotherresult,\n\t\t\t\t     bool checkClosest) const\n{\n  const GlobalPoint& gCrossingPos = crossing.position();\n\n  const vector<const GeomDet*>& sLayer( subLayer( crossing.subLayerIndex()));\n  // It assumes that what is ok for the front modules in the pt modules is ok also for the back module\n  const vector<const GeomDet*>& sBrotherLayer( subLayerBrothers( crossing.subLayerIndex()));\n \n  int closestIndex = crossing.closestDetIndex();\n  int negStartIndex = closestIndex-1;\n  int posStartIndex = closestIndex+1;\n\n  if (checkClosest) { // must decide if the closest is on the neg or pos side\n    if ( Geom::phiLess( gCrossingPos.barePhi(), sLayer[closestIndex]->surface().phi())) {\n      posStartIndex = closestIndex;\n    }\n    else {\n      negStartIndex = closestIndex;\n    }\n  }\n\n  const BinFinderType& binFinder = (crossing.subLayerIndex()==0 ? theFrontBinFinder : theBackBinFinder);\n\n  typedef CompatibleDetToGroupAdder Adder;\n  int half = sLayer.size()/2;  // to check if dets are called twice....\n  for (int idet=negStartIndex; idet >= negStartIndex - half; idet--) {\n    const GeomDet & neighborDet = *sLayer[binFinder.binIndex(idet)];\n    if (!tkDetUtil::overlapInPhi( gCrossingPos, neighborDet, window)) break;\n    if (!Adder::add( neighborDet, tsos, prop, est, result)) break;\n    if(theFrontDetBrothers.empty() && theBackDetBrothers.empty()) break;\n    // If the two above checks are passed also the brother module will be added with no further checks\n    const GeomDet & neighborBrotherDet = *sBrotherLayer[binFinder.binIndex(idet)];\n    Adder::add( neighborBrotherDet, tsos, prop, est, brotherresult);\n    // maybe also add shallow crossing angle test here???\n  }\n  for (int idet=posStartIndex; idet < posStartIndex + half; idet++) {\n    const GeomDet & neighborDet = *sLayer[binFinder.binIndex(idet)];\n    if (!tkDetUtil::overlapInPhi( gCrossingPos, neighborDet, window)) break;\n    if (!Adder::add( neighborDet, tsos, prop, est, result)) break;\n    if(theFrontDetBrothers.empty() && theBackDetBrothers.empty()) break;\n    // If the two above checks are passed also the brother module will be added with no further checks\n    const GeomDet & neighborBrotherDet = *sBrotherLayer[binFinder.binIndex(idet)];\n    Adder::add( neighborBrotherDet, tsos, prop, est, brotherresult);\n    // maybe also add shallow crossing angle test here???\n  }\n}\n", "meta": {"hexsha": "aa8c031220de773c1eb740caeedf48897002a2a2", "size": 12247, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RecoTracker/TkDetLayers/src/Phase2EndcapRing.cc", "max_stars_repo_name": "bisnupriyasahu/cmssw", "max_stars_repo_head_hexsha": "6cf37ca459246525be0e8a6f5172c6123637d259", "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": "RecoTracker/TkDetLayers/src/Phase2EndcapRing.cc", "max_issues_repo_name": "bisnupriyasahu/cmssw", "max_issues_repo_head_hexsha": "6cf37ca459246525be0e8a6f5172c6123637d259", "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": "RecoTracker/TkDetLayers/src/Phase2EndcapRing.cc", "max_forks_repo_name": "bisnupriyasahu/cmssw", "max_forks_repo_head_hexsha": "6cf37ca459246525be0e8a6f5172c6123637d259", "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": 41.0973154362, "max_line_length": 134, "alphanum_fraction": 0.7013146077, "num_tokens": 3255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18715414405383277}}
{"text": "#include \"stdafx.h\"\r\n#include <algorithm>\r\n\r\n#include \"boostPythonUtil.h\"\r\n#include \"VPUtil.h\"\r\n\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\n//#define make_tuple boost::python::make_tuple\r\n\r\n//using boost::python::make_tuple;\r\nnamespace bp = boost::python;\r\nnamespace np = boost::python::numpy;\r\nusing boost::python::numpy::ndarray;\r\n\r\nnamespace ublas = boost::numeric::ublas;\r\n\r\n#include \"csVpModel.h\"\r\n#include \"csVpWorld.h\"\r\n#include \"myGeom.h\"\r\n//#include \"hpBJoint.h\"\r\n//#include \"hpUJoint.h\"\r\n//#include \"hpRJoint.h\"\r\n\r\n#define MAX_X 1\t// 0001\r\n#define MAX_Y 2\t// 0010\r\n#define MAX_Z 4\t// 0100\r\n\r\n#define QP\r\n\r\n\r\n\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getJointPositionGlobal_py_overloads, getJointPositionGlobal, 1, 2);\r\n\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getBodyPositionGlobal_py_overloads, getBodyPositionGlobal_py, 1, 2);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getBodyVelocityGlobal_py_overloads, getBodyVelocityGlobal_py, 1, 2);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getBodyAccelerationGlobal_py_overloads, getBodyAccelerationGlobal_py, 1, 2);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpMotionModel_recordVelByFiniteDiff_overloads, recordVelByFiniteDiff, 0, 2);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_applyBodyGenForceGlobal_overloads, applyBodyGenForceGlobal, 3, 4);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_applyBodyForceGlobal_overloads, applyBodyForceGlobal, 2, 3);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(initializeHybridDynamics_overloads, initializeHybridDynamics, 0, 1);\r\n\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_SetJointElasticity_overloads, SetJointElasticity, 2, 4);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_SetJointsElasticity_overloads, SetJointsElasticity, 1, 3);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_SetJointDamping_overloads, SetJointDamping, 2, 4);\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_SetJointsDamping_overloads, SetJointsDamping, 1, 3);\r\n\r\nBOOST_PYTHON_MODULE(csVpModel)\r\n{\r\n\tclass_<VpModel>(\"VpModel\", init<VpWorld*, object, object>())\r\n\t\t.def(\"__str__\", &VpModel::__str__)\r\n\t\t.def(\"getBodyNum\", &VpModel::getBodyNum)\r\n\t\t.def(\"getBodyMasses\", &VpModel::getBodyMasses)\r\n\t\t.def(\"getTotalMass\", &VpModel::getTotalMass)\r\n\t\t.def(\"getBodyVerticesPositionGlobal\", &VpModel::getBodyVerticesPositionGlobal)\r\n\r\n\t\t.def(\"getBodyGeomNum\", &VpModel::getBodyGeomNum)\r\n\t\t.def(\"getBodyGeomsType\", &VpModel::getBodyGeomsType)\r\n\t\t.def(\"getBodyGeomsSize\", &VpModel::getBodyGeomsSize)\r\n\t\t.def(\"getBodyGeomsLocalFrame\", &VpModel::getBodyGeomsLocalFrame)\r\n\t\t.def(\"getBodyGeomsGlobalFrame\", &VpModel::getBodyGeomsGlobalFrame)\r\n\t\t.def(\"getBodyShape\", &VpModel::getBodyShape)\r\n\r\n\t\t.def(\"getBodyByIndex\", &VpModel::getBodyByIndex, return_value_policy<reference_existing_object>())\r\n\t\t.def(\"getBodyByName\", &VpModel::getBodyByName, return_value_policy<reference_existing_object>())\r\n\t\t.def(\"getJointByIndex\", &VpModel::getJointByIndex, return_value_policy<reference_existing_object>())\r\n\t\t.def(\"getJointByName\", &VpModel::getJointByName, return_value_policy<reference_existing_object>())\r\n\r\n\t\t.def(\"index2name\", &VpModel::index2name)\r\n\t\t.def(\"index2vpid\", &VpModel::index2vpid)\r\n\t\t.def(\"name2index\", &VpModel::name2index)\r\n\t\t.def(\"name2vpid\", &VpModel::name2vpid)\r\n\r\n\t\t.def(\"getBodyInertiaLocal\", &VpModel::getBodyInertiaLocal_py)\r\n\t\t.def(\"getBodyInertiaGlobal\", &VpModel::getBodyInertiaGlobal_py)\r\n\r\n\t\t.def(\"getBodyInertiasLocal\", &VpModel::getBodyInertiasLocal)\r\n\t\t.def(\"getBodyInertiasGlobal\", &VpModel::getBodyInertiasGlobal)\r\n\t\t\r\n\t\t.def(\"getCOM\", &VpModel::getCOM)\r\n        .def(\"getBoneT\", &VpModel::getBoneT)\r\n        .def(\"getInvBoneT\", &VpModel::getInvBoneT)\r\n\r\n        .def(\"getBodyGenVelLocal\", &VpModel::getBodyGenVelLocal)\r\n        .def(\"getBodyGenVelGlobal\", &VpModel::getBodyGenVelGlobal)\r\n        .def(\"getBodyGenAccLocal\", &VpModel::getBodyGenAccLocal)\r\n        .def(\"getBodyGenAccGlobal\", &VpModel::getBodyGenAccGlobal)\r\n\t\t.def(\"getBodyPositionGlobal\", &VpModel::getBodyPositionGlobal_py, getBodyPositionGlobal_py_overloads())\r\n\t\t.def(\"getBodyVelocityGlobal\", &VpModel::getBodyVelocityGlobal_py, getBodyVelocityGlobal_py_overloads())\r\n\t\t.def(\"getBodyAccelerationGlobal\", &VpModel::getBodyAccelerationGlobal_py, getBodyAccelerationGlobal_py_overloads())\r\n\t\t.def(\"getBodyAngVelocityGlobal\", &VpModel::getBodyAngVelocityGlobal)\r\n\t\t.def(\"getBodyAngAccelerationGlobal\", &VpModel::getBodyAngAccelerationGlobal)\r\n\t\t.def(\"getBodyOrientationGlobal\", &VpModel::getBodyOrientationGlobal)\r\n\r\n\t\t.def(\"getBodyFrame\", &VpModel::getBodyFrame)\r\n\r\n\t\t.def(\"getBodyPositionsGlobal\", &VpModel::getBodyPositionsGlobal)\r\n\t\t.def(\"getBodyVelocitiesGlobal\", &VpModel::getBodyVelocitiesGlobal)\r\n\t\t.def(\"getBodyAccelerationsGlobal\", &VpModel::getBodyAccelerationsGlobal)\r\n\t\t.def(\"getBodyAngVelocitiesGlobal\", &VpModel::getBodyAngVelocitiesGlobal)\r\n\t\t.def(\"getBodyAngAccelerationsGlobal\", &VpModel::getBodyAngAccelerationsGlobal)\r\n\t\t.def(\"getBodyOrientationsGlobal\", &VpModel::getBodyOrientationsGlobal)\r\n\r\n\t\t.def(\"getBodyTransformGlobal\", &VpModel::getBodyTransformGlobal)\r\n\r\n\t\t.def(\"setBodyPositionGlobal\", &VpModel::setBodyPositionGlobal_py)\r\n\t\t.def(\"setBodyVelocityGlobal\", &VpModel::setBodyVelocityGlobal_py)\r\n\t\t.def(\"setBodyAccelerationGlobal\", &VpModel::setBodyAccelerationGlobal_py)\r\n\t\t.def(\"setBodyAngVelocityGlobal\", &VpModel::setBodyAngVelocityGlobal)\r\n\t\t.def(\"setBodyAngAccelerationGlobal\", &VpModel::setBodyAngAccelerationGlobal)\r\n\r\n\t\t.def(\"translateByOffset\", &VpModel::translateByOffset)\r\n\t\t.def(\"rotate\", &VpModel::rotate)\r\n\t\t.def(\"SetGround\", &VpModel::SetGround)\r\n\t\t.def(\"SetBodyColor\", &VpModel::SetBodyColor)\r\n\t\t.def(\"vpid2index\", &VpModel::vpid2index)\r\n\t\t;\r\n\r\n\tclass_<VpMotionModel, bases<VpModel> >(\"VpMotionModel\", init<VpWorld*, object, object>())\r\n\t\t.def(\"update\", &VpMotionModel::update)\r\n\t\t.def(\"recordVelByFiniteDiff\", &VpMotionModel::recordVelByFiniteDiff, VpMotionModel_recordVelByFiniteDiff_overloads())\r\n\t\t;\r\n\r\n\tclass_<VpControlModel, bases<VpModel> >(\"VpControlModel\", init<VpWorld*, object, object>())\r\n\t\t.def(\"__str__\", &VpControlModel::__str__)\r\n\t\t.def(\"getJointNum\", &VpControlModel::getJointNum)\r\n\t\t.def(\"getInternalJointNum\", &VpControlModel::getInternalJointNum)\r\n\t\t.def(\"getDOFs\", &VpControlModel::getDOFs)\r\n\t\t.def(\"getInternalJointDOFs\", &VpControlModel::getInternalJointDOFs)\r\n\t\t.def(\"getTotalDOF\", &VpControlModel::getTotalDOF)\r\n\t\t.def(\"getTotalInternalJointDOF\", &VpControlModel::getTotalInternalJointDOF)\r\n\r\n\t\t.def(\"getJointDOFIndexes\", &VpControlModel::getJointDOFIndexes)\r\n\t\t.def(\"getJointDOFInternalIndexes\", &VpControlModel::getJointDOFInternalIndexes)\r\n\r\n\t\t.def(\"update\", &VpControlModel::update)\r\n\t\t.def(\"fixBody\", &VpControlModel::fixBody)\r\n\r\n\t\t.def(\"initializeHybridDynamics\", &VpControlModel::initializeHybridDynamics, initializeHybridDynamics_overloads())\r\n\t\t.def(\"initializeForwardDynamics\", &VpControlModel::initializeForwardDynamics)\r\n\t\t.def(\"setHybridDynamics\", &VpControlModel::setHybridDynamics)\r\n\t\t.def(\"solveHybridDynamics\", &VpControlModel::solveHybridDynamics)\r\n\t\t.def(\"solveForwardDynamics\", &VpControlModel::solveForwardDynamics)\r\n\t\t.def(\"solveInverseDynamics\", &VpControlModel::solveInverseDynamics)\r\n\r\n\t\t.def(\"set_q\", &VpControlModel::set_q)\r\n//\t\t.def(\"set_dq\", &VpControlModel::set_dq)\r\n\t\t.def(\"get_q\", &VpControlModel::get_q)\r\n\t\t.def(\"get_dq\", &VpControlModel::get_dq)\r\n\t\t.def(\"get_dq_nested\", &VpControlModel::get_dq_nested)\r\n\t\t.def(\"set_ddq\", &VpControlModel::set_ddq)\r\n\r\n\t\t.def(\"computeJacobian\", &VpControlModel::computeJacobian)\r\n        .def(\"computeCom_J_dJdq\", &VpControlModel::computeCom_J_dJdq)\r\n\r\n\t\t.def(\"getDOFPositions\", &VpControlModel::getDOFPositions)\r\n\t\t.def(\"getDOFVelocities\", &VpControlModel::getDOFVelocities)\r\n\t\t.def(\"getDOFAccelerations\", &VpControlModel::getDOFAccelerations)\r\n\t\t.def(\"getDOFAxeses\", &VpControlModel::getDOFAxeses)\r\n\r\n\t\t.def(\"getDOFPositionsLocal\", &VpControlModel::getDOFPositionsLocal)\r\n\t\t.def(\"getDOFVelocitiesLocal\", &VpControlModel::getDOFVelocitiesLocal)\r\n\t\t.def(\"getDOFAccelerationsLocal\", &VpControlModel::getDOFAccelerationsLocal)\r\n\t\t.def(\"getDOFAxesesLocal\", &VpControlModel::getDOFAxesesLocal)\r\n\r\n\t\t.def(\"getBodyRootDOFVelocitiesLocal\", &VpControlModel::getBodyRootDOFVelocitiesLocal)\r\n\t\t.def(\"getBodyRootDOFAccelerationsLocal\", &VpControlModel::getBodyRootDOFAccelerationsLocal)\r\n\t\t.def(\"getBodyRootDOFAxeses\", &VpControlModel::getBodyRootDOFAxeses)\r\n\r\n        .def(\"setDOFVelocities\", &VpControlModel::setDOFVelocities)\r\n\r\n\t\t.def(\"setDOFAccelerations\", &VpControlModel::setDOFAccelerations)\r\n\t\t.def(\"setDOFTorques\", &VpControlModel::setDOFTorques)\r\n\r\n\t\t.def(\"getJointOrientationLocal\", &VpControlModel::getJointOrientationLocal)\r\n\t\t.def(\"getJointAngVelocityLocal\", &VpControlModel::getJointAngVelocityLocal)\r\n\t\t.def(\"getJointAngAccelerationLocal\", &VpControlModel::getJointAngAccelerationLocal)\r\n\r\n        .def(\"getLocalJacobian\", &VpControlModel::getLocalJacobian)\r\n        .def(\"getLocalJointVelocity\", &VpControlModel::getLocalJointVelocity)\r\n        .def(\"getLocalJointDisplacementDerivatives\", &VpControlModel::getLocalJointDisplacementDerivatives)\r\n\r\n\r\n\t\t.def(\"getJointTransform\", &VpControlModel::getJointTransform)\r\n\t\t.def(\"getJointAfterTransformGlobal\", &VpControlModel::getJointAfterTransformGlobal)\r\n\t\t.def(\"getJointPositionGlobal\", &VpControlModel::getJointPositionGlobal, getJointPositionGlobal_py_overloads())\r\n//\t\t.def(\"getJointPositionGlobal\", &VpControlModel::getJointPositionGlobal)\r\n\t\t.def(\"getJointVelocityGlobal\", &VpControlModel::getJointVelocityGlobal)\r\n\t\t.def(\"getJointAccelerationGlobal\", &VpControlModel::getJointAccelerationGlobal)\r\n\t\t.def(\"getJointOrientationGlobal\", &VpControlModel::getJointOrientationGlobal)\r\n\t\t.def(\"getJointAngVelocityGlobal\", &VpControlModel::getJointAngVelocityGlobal)\r\n\t\t.def(\"getJointAngAccelerationGlobal\", &VpControlModel::getJointAngAccelerationGlobal)\r\n\r\n\t\t.def(\"getJointOrientationsLocal\", &VpControlModel::getJointOrientationsLocal)\r\n\t\t.def(\"getJointAngVelocitiesLocal\", &VpControlModel::getJointAngVelocitiesLocal)\r\n\t\t.def(\"getJointAngAccelerationsLocal\", &VpControlModel::getJointAngAccelerationsLocal)\r\n\r\n\t\t.def(\"getJointPositionsGlobal\", &VpControlModel::getJointPositionsGlobal)\r\n\t\t.def(\"getJointVelocitiesGlobal\", &VpControlModel::getJointVelocitiesGlobal)\r\n\t\t.def(\"getJointAccelerationsGlobal\", &VpControlModel::getJointAccelerationsGlobal)\r\n\t\t.def(\"getJointOrientationsGlobal\", &VpControlModel::getJointOrientationsGlobal)\r\n\t\t.def(\"getJointAngVelocitiesGlobal\", &VpControlModel::getJointAngVelocitiesGlobal)\r\n\t\t.def(\"getJointAngAccelerationsGlobal\", &VpControlModel::getJointAngAccelerationsGlobal)\r\n\r\n\t\t.def(\"getInternalJointOrientationsLocal\", &VpControlModel::getInternalJointOrientationsLocal)\r\n\t\t.def(\"getInternalJointAngVelocitiesLocal\", &VpControlModel::getInternalJointAngVelocitiesLocal)\r\n\t\t.def(\"getInternalJointAngAccelerationsLocal\", &VpControlModel::getInternalJointAngAccelerationsLocal)\r\n\r\n\t\t.def(\"getInternalJointPositionsGlobal\", &VpControlModel::getInternalJointPositionsGlobal)\r\n\t\t.def(\"getInternalJointOrientationsGlobal\", &VpControlModel::getInternalJointOrientationsGlobal)\r\n\r\n\t\t.def(\"setJointAngVelocityLocal\", &VpControlModel::setJointAngVelocityLocal)\r\n\t\t.def(\"setJointAngAccelerationLocal\", &VpControlModel::setJointAngAccelerationLocal)\r\n\r\n\t\t.def(\"setJointAccelerationGlobal\", &VpControlModel::setJointAccelerationGlobal)\r\n\t\t.def(\"setJointAngAccelerationGlobal\", &VpControlModel::setJointAngAccelerationGlobal)\r\n\r\n\t\t.def(\"setJointAngAccelerationsLocal\", &VpControlModel::setJointAngAccelerationsLocal)\r\n\t\t\r\n\t\t.def(\"setInternalJointAngAccelerationsLocal\", &VpControlModel::setInternalJointAngAccelerationsLocal)\r\n\r\n\r\n\t\t.def(\"applyBodyGenForceGlobal\", &VpControlModel::applyBodyGenForceGlobal, VpControlModel_applyBodyGenForceGlobal_overloads())\r\n\t\t.def(\"applyBodyForceGlobal\", &VpControlModel::applyBodyForceGlobal, VpControlModel_applyBodyForceGlobal_overloads())\r\n\t\t.def(\"applyBodyTorqueGlobal\", &VpControlModel::applyBodyTorqueGlobal)\r\n\r\n\t\t.def(\"getBodyForceLocal\", &VpControlModel::getBodyForceLocal)\r\n\t\t.def(\"getBodyNetForceLocal\", &VpControlModel::getBodyNetForceLocal)\r\n\t\t.def(\"getBodyGravityForceLocal\", &VpControlModel::getBodyGravityForceLocal)\r\n\r\n        .def(\"SetJointElasticity\", &VpControlModel::SetJointElasticity, VpControlModel_SetJointElasticity_overloads())\r\n\t    .def(\"SetJointsElasticity\", &VpControlModel::SetJointsElasticity, VpControlModel_SetJointsElasticity_overloads())\r\n\t    .def(\"SetJointDamping\", &VpControlModel::SetJointDamping, VpControlModel_SetJointDamping_overloads())\r\n\t    .def(\"SetJointsDamping\", &VpControlModel::SetJointsDamping, VpControlModel_SetJointsDamping_overloads())\r\n\r\n\t\t.def(\"getJointTorqueLocal\", &VpControlModel::getJointTorqueLocal)\r\n\t\t.def(\"getInternalJointTorquesLocal\", &VpControlModel::getInternalJointTorquesLocal)\r\n\r\n\t\t.def(\"setJointTorqueLocal\", &VpControlModel::setJointTorqueLocal)\r\n\t\t.def(\"setInternalJointTorquesLocal\", &VpControlModel::setInternalJointTorquesLocal)\r\n\t\t\r\n\t\t.def(\"setSpring\", &VpControlModel::setSpring)\r\n\r\n\t\t.def(\"getInverseEquationOfMotion\", &VpControlModel::getInverseEquationOfMotion)\r\n\t\t.def(\"getEquationOfMotion\", &VpControlModel::getEquationOfMotion)\r\n\t\t.def(\"stepKinematics\", &VpControlModel::stepKinematics)\r\n\t\t;\r\n}\r\n\r\n/*\r\nstatic SE3 skewVec3(const Vec3 &v)\r\n{\r\n\treturn SE3(0., v[2], -v[1], -v[2], 0., v[0], v[1], -v[0], 0.);\r\n}\r\n\r\nstatic SE3 skewVec3(const Axis &v)\r\n{\r\n\treturn SE3(0., v[2], -v[1], -v[2], 0., v[0], v[1], -v[0], 0.);\r\n}\r\n//*/\r\n \r\nVpModel::VpModel( VpWorld* pWorld, const object& createPosture, const object& config ) \r\n{\r\n    if(pWorld != nullptr)\r\n    {\r\n        _config = config;\r\n        _skeleton = createPosture.attr(\"skeleton\");\r\n\r\n        _pWorld = &pWorld->_world;\r\n        int num = XI(createPosture.attr(\"skeleton\").attr(\"getJointNum\")());\r\n        _nodes.resize(num, NULL);\r\n        _boneTs.resize(num, SE3());\r\n\r\n        createBodies(createPosture);\r\n        build_name2index();\r\n\t}\r\n}\r\n\r\nVpModel::~VpModel()\r\n{\r\n\tfor( NODES_ITOR it=_nodes.begin(); it!=_nodes.end(); ++it)\r\n\t\tif(*it)\r\n\t\t\tdelete *it;\r\n}\r\n\r\nvoid VpModel::SetGround(int index, bool flag)\r\n{\r\n\t_nodes[index]->body.SetGround(flag);\r\n}\r\n\r\nvoid VpModel::createBodies( const object& posture )\r\n{\r\n\tobject joint = posture.attr(\"skeleton\").attr(\"root\");\r\n\r\n\tobject rootPos = posture.attr(\"rootPos\");\r\n\tSE3 T = SE3(pyVec3_2_Vec3(rootPos));\r\n\r\n\tobject tpose = posture.attr(\"getTPose\")();\r\n\t_createBody(joint, T, tpose);\r\n}\r\n\r\nvoid VpModel::_createBody( const object& joint, const SE3& parentT, const object& posture )\r\n{\r\n\tint len_joint_children = len(joint.attr(\"children\")); \r\n\tif (len_joint_children == 0 )\r\n\t\treturn;\r\n\r\n\tSE3 T = parentT;\r\n\r\n\tSE3 P = SE3(pyVec3_2_Vec3(joint.attr(\"offset\")));\r\n\tT = T * P;\r\n\r\n\tstring joint_name = XS(joint.attr(\"name\"));\r\n\t//\tint joint_index = XI(posture.attr(\"skeleton\").attr(\"getElementIndex\")(joint_name));\r\n\t//\tSE3 R = pySO3_2_SE3(posture.attr(\"getLocalR\")(joint_index));\r\n\tint joint_index = XI(posture.attr(\"skeleton\").attr(\"getJointIndex\")(joint_name));\r\n\tSE3 R = pySO3_2_SE3(posture.attr(\"getJointOrientationLocal\")(joint_index));\r\n\tT = T * R;\r\n\r\n//\tif (len_joint_children > 0 && _config.attr(\"hasNode\")(joint_name))\r\n\tif (_config.attr(\"hasNode\")(joint_name))\r\n\t{\r\n\t\tVec3 offset(0);\r\n\r\n\t\tobject cfgNode = _config.attr(\"getNode\")(joint_name);\r\n\t\tobject bone_dir_child = cfgNode.attr(\"bone_dir_child\");\r\n\r\n\t\tif (!bone_dir_child.is_none())\r\n\t\t{\r\n\t\t    string bone_dir_child_name = XS(cfgNode.attr(\"bone_dir_child\"));\r\n\t\t    int child_joint_index = XI(posture.attr(\"skeleton\").attr(\"getJointIndex\")(bone_dir_child_name));\r\n\t\t    offset += pyVec3_2_Vec3(posture.attr(\"skeleton\").attr(\"getJoint\")(child_joint_index).attr(\"offset\"));\r\n//\t\t    std::cout << joint_name << \" \" << offset <<std::endl;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n            for( int i=0 ; i<len_joint_children; ++i)\r\n                offset += pyVec3_2_Vec3(joint.attr(\"children\")[i].attr(\"offset\"));\r\n\r\n            offset *= (1./len_joint_children);\r\n\t\t}\r\n\r\n\t\tSE3 boneT(offset*.5);\r\n\r\n\t\tVec3 defaultBoneV(0,0,1);\r\n\t\tSE3 boneR = getSE3FromVectors(defaultBoneV, offset);\r\n\r\n        boneT = boneT * boneR;\r\n\r\n\t\tNode* pNode = new Node(joint_name);\r\n\t\t_nodes[joint_index] = pNode;\r\n\r\n\t\t_nodes[joint_index]->offset_from_parent = pyVec3_2_Vec3(joint.attr(\"offset\"));\r\n\r\n\t\t///*\r\n\t\tint numGeom = len(cfgNode.attr(\"geoms\"));\r\n\t\tif (numGeom != 0)\r\n\t\t{\r\n\t\t\tfor (int i=0; i<numGeom; i++)\r\n\t\t\t{\r\n\t\t\t\tstring geomType = XS(cfgNode.attr(\"geoms\")[i]);\r\n\t\t\t\tif (0 == geomType.compare(\"MyFoot3\") || 0 == geomType.compare(\"MyFoot4\")\r\n\t\t\t\t    || 0 == geomType.compare(\"MyFoot5\") || 0 == geomType.compare(\"MyFoot6\"))\r\n\t\t\t\t{\r\n\t\t\t\t\tscalar density = XD(cfgNode.attr(\"geomMaterial\")[i].attr(\"density\"));\r\n\t\t\t\t\tscalar radius = XD(cfgNode.attr(\"geomMaterial\")[i].attr(\"radius\"));\r\n\t\t\t\t\tscalar height = XD(cfgNode.attr(\"geomMaterial\")[i].attr(\"height\"));\r\n\r\n\t\t\t\t\tif (height <= 0.)\r\n\t\t\t\t\t    height = Norm(offset) + 2*radius;\r\n\r\n\t\t\t\t\t// vpMaterial *pMaterial = new vpMaterial();\r\n\t\t\t\t\t// pMaterial->SetDensity(density);\r\n\t\t\t\t\t// pNode->body.SetMaterial(pMaterial);\r\n\t\t\t\t\tpNode->material.SetDensity(density);\r\n\t\t\t\t\tpNode->body.SetMaterial(&(pNode->material));\r\n\r\n\t\t\t\t\tSE3 geomT;\r\n\t\t\t\t\tgeomT.SetEye();\r\n\t\t\t\t\tif(cfgNode.attr(\"geomTs\")[i])\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tgeomT = pySO3_2_SE3(cfgNode.attr(\"geomTs\")[i][1]);\r\n//\t\t\t\t\t\tgeomT.SetPosition(geomT*pyVec3_2_Vec3(cfgNode.attr(\"geomTs\")[i][0]));\r\n\t\t\t\t\t\tgeomT.SetPosition(pyVec3_2_Vec3(cfgNode.attr(\"geomTs\")[i][0]));\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tstd::cout << \"there is no geom Ts!\" << std::endl;\r\n\r\n\t\t\t\t\tif (0 == geomType.compare(\"MyFoot3\"))\r\n\t\t\t\t\t\tpNode->body.AddGeometry(new MyFoot3(radius, height), geomT);\r\n\t\t\t\t\telse if(0 == geomType.compare(\"MyFoot4\"))\r\n\t\t\t\t\t\tpNode->body.AddGeometry(new MyFoot4(radius, height), geomT);\r\n\t\t\t\t\telse if(0 == geomType.compare(\"MyFoot6\"))\r\n\t\t\t\t\t\tpNode->body.AddGeometry(new MyFoot6(radius, height), geomT);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tpNode->body.AddGeometry(new MyFoot5(radius, height), geomT);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tscalar density = XD(cfgNode.attr(\"geomMaterial\")[i].attr(\"density\"));\r\n\t\t\t\t\tscalar width = XD(cfgNode.attr(\"geomMaterial\")[i].attr(\"width\"));\r\n\t\t\t\t\tscalar length = XD(cfgNode.attr(\"geomMaterial\")[i].attr(\"length\"));\r\n\t\t\t\t\tscalar height = XD(cfgNode.attr(\"geomMaterial\")[i].attr(\"height\"));\r\n\r\n\t\t\t\t\t// vpMaterial *pMaterial = new vpMaterial();\r\n\t\t\t\t\t// pMaterial->SetDensity(density);\r\n\t\t\t\t\t// pNode->body.SetMaterial(pMaterial);\r\n\t\t\t\t\tpNode->material.SetDensity(density);\r\n\t\t\t\t\tpNode->body.SetMaterial(&(pNode->material));\r\n\r\n\t\t\t\t\tSE3 geomT;\r\n\t\t\t\t\tgeomT.SetEye();\r\n\t\t\t\t\tif(cfgNode.attr(\"geomTs\")[i])\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tgeomT = pySO3_2_SE3(cfgNode.attr(\"geomTs\")[i][1]);\r\n\t\t\t\t\t\tgeomT.SetPosition(pyVec3_2_Vec3(cfgNode.attr(\"geomTs\")[i][0]));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpNode->body.AddGeometry(new vpBox(Vec3(width, height, length)), geomT);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t//*/\t\r\n\t\t///*\r\n\t\t\tstring geomType = XS(cfgNode.attr(\"geom\"));\r\n\t\t\tif (0 == geomType.compare(\"MyFoot3\") || 0 == geomType.compare(\"MyFoot4\")\r\n\t\t\t    || 0 == geomType.compare(\"MyFoot5\")|| 0 == geomType.compare(\"MyFoot6\"))\r\n\t\t\t{\r\n\t\t\t\tscalar radius = .05;\r\n\t\t\t\tobject width_object = cfgNode.attr(\"width\");\r\n\t\t\t\tif( !width_object.is_none() )\r\n\t\t\t\t\tradius = XD(cfgNode.attr(\"width\"));\r\n\r\n\t\t\t\tscalar length = Norm(offset) + 2*radius;\r\n\t\t\t\tscalar density = XD(cfgNode.attr(\"density\"));\r\n\t\t\t\tscalar mass = 1.;\r\n\t\t\t\tobject mass_object = cfgNode.attr(\"mass\");\r\n\t\t\t\tif( !mass_object.is_none() )\r\n\t\t\t\t{\r\n\t\t\t\t\tmass = XD(cfgNode.attr(\"mass\"));\r\n\t\t\t\t\tdensity = mass/ (radius * radius * M_PI * length);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t\tmass = density * radius * radius * M_PI * length;\r\n\r\n\t\t\t\t// density = mass/ (width*width*M_PI*(length+width));\r\n\t\t\t\tif (0 == geomType.compare(\"MyFoot3\"))\r\n\t\t\t\t\tpNode->body.AddGeometry(new MyFoot3(radius, length));\r\n\t\t\t\telse if(0 == geomType.compare(\"MyFoot4\"))\r\n\t\t\t\t\tpNode->body.AddGeometry(new MyFoot4(radius, length));\r\n\t\t\t\telse if(0 == geomType.compare(\"MyFoot6\"))\r\n\t\t\t\t\tpNode->body.AddGeometry(new MyFoot6(radius, length));\r\n\t\t\t\telse\r\n\t\t\t\t\tpNode->body.AddGeometry(new MyFoot5(radius, length));\r\n\t\t\t\tpNode->body.SetInertia(CylinderInertia(density, radius, length));\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t    object mass_object = cfgNode.attr(\"mass\");\r\n\t\t\t\tobject length_object = cfgNode.attr(\"length\");\r\n\t\t\t\tobject width_object = cfgNode.attr(\"width\");\r\n\t\t\t\tobject height_object = cfgNode.attr(\"height\");\r\n\r\n\t\t\t\tscalar length;\r\n\t\t\t\tif( !length_object.is_none() )\r\n\t\t\t\t\tlength = XD(cfgNode.attr(\"length\")) * XD(cfgNode.attr(\"boneRatio\"));\r\n\t\t\t\telse\r\n\t\t\t\t\tlength = Norm(offset) * XD(cfgNode.attr(\"boneRatio\"));\r\n\r\n\t\t\t\tscalar density = XD(cfgNode.attr(\"density\"));\r\n\t\t\t\tscalar width, height;\r\n\t\t\t\tif( !width_object.is_none() )\r\n\t\t\t\t{\r\n\t\t\t\t\twidth = XD(cfgNode.attr(\"width\"));\r\n\t\t\t\t\tif( !mass_object.is_none() )\r\n\t\t\t\t\t\theight = (XD(cfgNode.attr(\"mass\")) / (density * length)) / width;\r\n\t\t\t\t\telse if ( !height_object.is_none())\r\n\t\t\t\t\t\theight = XD(cfgNode.attr(\"height\"));\r\n\t\t\t\t\telse\r\n\t\t\t\t\t    height = .1;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif( !mass_object.is_none() )\r\n\t\t\t\t\t{\r\n                        if ( !height_object.is_none())\r\n                        {\r\n                            height = XD(cfgNode.attr(\"height\"));\r\n                            width = (XD(cfgNode.attr(\"mass\")) / (density * length)) / height;\r\n                        }\r\n                        else\r\n                        {\r\n                            width = sqrt( (XD(cfgNode.attr(\"mass\")) / (density * length)) );\r\n                            height = width;\r\n                        }\r\n                    }\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n                        if ( !height_object.is_none())\r\n                        {\r\n                            height = XD(cfgNode.attr(\"height\"));\r\n                            width = height;\r\n                        }\r\n                        else\r\n                        {\r\n                            width = .1;\r\n                            height = width;\r\n                        }\r\n                    }\r\n\t\t\t\t}\r\n\t\t\t\tstring geomType = XS(cfgNode.attr(\"geom\"));\r\n\t\t\t\tif(0 == geomType.compare(\"MyBox\"))\r\n\t\t\t\t\tpNode->body.AddGeometry(new MyBox(Vec3(width, height, length)));\r\n\t\t\t\telse if(0 == geomType.compare(\"MyFoot1\"))\r\n\t\t\t\t\tpNode->body.AddGeometry(new MyFoot1(Vec3(width, height, length)));\r\n\t\t\t\telse if(0 == geomType.compare(\"MyFoot2\"))\r\n\t\t\t\t\tpNode->body.AddGeometry(new MyFoot2(Vec3(width, height, length)));\r\n    \t\t// else if(geomType == \"MyShin\")\r\n    \t\t// \tpNode->body.AddGeometry(new MyShin(Vec3(width, height, length)));\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tpNode->body.AddGeometry(new vpBox(Vec3(width, height, length)));\r\n\t\t\t\t\tcout << geomType << \" : undefined geom type!\" << endl;\r\n\t\t\t\t}\r\n\r\n            // pNode->body.AddGeometry(new vpBox(Vec3(width, height, length)));\r\n\t\t\t\tpNode->body.SetInertia(BoxInertia(density, Vec3(width/2.,height/2.,length/2.)));\r\n\t\t\t//*/\r\n\t\t\t}\r\n\t\t}\r\n\r\n//\t\tpNode->body.SetInertia(BoxInertia(density, Vec3(width,height,length)));\r\n\t\t//pNode->body.SetInertia(BoxInertia(density, Vec3(width/2.,height/2.,length/2.)));\r\n\r\n\t\tboneT = boneT * SE3(pyVec3_2_Vec3(cfgNode.attr(\"offset\")));\r\n\t\tobject parent_object = joint.attr(\"parent\");\r\n        if(parent_object.is_none())\r\n            boneT=SE3();\r\n\r\n        _boneTs[joint_index] = boneT;\r\n\t\tSE3 newT = T * boneT;\r\n\r\n//\t\tif (joint.attr(\"parent\") == object())\r\n//\t\t\tpNode->body.SetFrame(T);\r\n//\t\telse\r\n\t\tpNode->body.SetFrame(newT);\r\n\r\n\t\t_id2index[pNode->body.GetID()] = joint_index;\r\n\t}\r\n\r\n\tfor( int i=0 ; i<len_joint_children; ++i)\r\n\t\t_createBody(joint.attr(\"children\")[i], T, posture);\r\n}\r\n\r\n//int VpModel::getParentIndex( int index )\r\n//{\r\n//\tobject parent = _skeleton.attr(\"getParentJointIndex\")(index);\r\n//\tif(parent==object())\r\n//\t\treturn -1;\r\n//\telse\r\n//\t\treturn XI(parent);\r\n//}\r\n\r\nstd::string VpModel::__str__()\r\n{\r\n\tstringstream ss;\r\n//\tss << \"<NODES>\" << endl;\r\n//\tfor(int i=0; i<_nodes.size(); ++i)\r\n//\t{\r\n//\t\tss << \"[\" << i << \"]:\";\r\n////\t\tif(_nodes[i]==NULL)\r\n////\t\t\tss << \"NULL, \";\r\n////\t\telse\r\n//\t\t\tss << _nodes[i]->name << \", \";\r\n//\t}\r\n//\tss << endl;\r\n//\r\n//\tss << \"<BODIES INDEX:(NODE INDEX) NODE NAME>\\n\";\r\n//\tfor(int i=0; i<_bodyElementIndexes.size(); ++i)\r\n//\t\tss << \"[\" << i << \"]:(\" << _bodyElementIndexes[i] << \") \" << _nodes[_bodyElementIndexes[i]]->name << \", \";\r\n//\tss << endl;\r\n\r\n\tss << \"<BODIES (,JOINTS)>\" << endl;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tss << \"[\" << i << \"]:\" << _nodes[i]->name << \", \";\r\n\tss << endl;\r\n\r\n\tss << \"<BODY MASSES>\" << endl;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n//\t\tif(_nodes[i])\r\n\t\t\tss << \"[\" << i << \"]:\" << _nodes[i]->body.GetInertia().GetMass() << \", \";\r\n\tss << endl;\r\n\r\n//\tss << \"<BODY INERTIAS>\" << endl;\r\n//\tss << \"I11 I22 I33 I12 I13 I23 offset.x offset.y offset.z mass\" << endl;\r\n//\tfor(int i=0; i<_nodes.size(); ++i)\r\n//\t\tif(_nodes[i])\r\n//\t\t{\r\n//\t\t\tss << \"[\" << i << \"]:\";\r\n//\t\t\tfor(int j=0; j<10; ++j)\r\n//\t\t\t\tss << _nodes[i]->body.GetInertia()[j] << \" \";\r\n//\t\t\tss << endl;\r\n//\t\t}\r\n//\tss << endl;\r\n\r\n\treturn ss.str();\r\n}\r\n\r\nbp::list VpModel::getBodyMasses()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(_nodes[i]->body.GetInertia().GetMass());\r\n\treturn ls;\r\n}\r\n\r\nscalar VpModel::getTotalMass()\r\n{\r\n\tscalar mass = 0.;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tmass += _nodes[i]->body.GetInertia().GetMass();\r\n\treturn mass;\r\n}\r\n\r\nint VpModel::getBodyGeomNum(int index)\r\n{\r\n    return _nodes[index]->body.GetNumGeometry();\r\n}\r\n\r\nbp::list VpModel::getBodyGeomsType(int index)\r\n{\r\n\tchar type;\r\n\tscalar data[3];\r\n\tbp::list ls;\r\n\tfor(int i=0; i<_nodes[index]->body.GetNumGeometry(); ++i)\r\n\t{\r\n        _nodes[index]->body.GetGeometry(i)->GetShape(&type, data);\r\n\t\tls.append(type);\r\n\t}\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpModel::getBodyGeomsSize(int index)\r\n{\r\n\tchar type;\r\n\tscalar data[3];\r\n\tbp::list ls;\r\n\r\n\tfor(int i=0; i<_nodes[index]->body.GetNumGeometry(); ++i)\r\n    {\r\n        ndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n        _nodes[index]->body.GetGeometry(i)->GetShape(&type, data);\r\n        object pyV = O.copy();\r\n        pyV[0] = data[0];\r\n        pyV[1] = data[1];\r\n        pyV[2] = data[2];\r\n        ls.append(pyV);\r\n    }\r\n\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpModel::getBodyGeomsLocalFrame(int index)\r\n{\r\n\tbp::list ls;\r\n\r\n\tfor(int i=0; i<_nodes[index]->body.GetNumGeometry(); ++i)\r\n    {\r\n        ndarray O = np::array(bp::make_tuple(\r\n                            bp::make_tuple(0.,0.,0.,0.),\r\n                            bp::make_tuple(0.,0.,0.,0.),\r\n                            bp::make_tuple(0.,0.,0.,0.),\r\n                            bp::make_tuple(0.,0.,0.,1.)\r\n                            )\r\n                        );\r\n        const SE3& geomFrame = _nodes[index]->body.GetGeometry(i)->GetLocalFrame();\r\n        object pyT = O.copy();\r\n\r\n        for(int j=0; j<12; j++)\r\n            pyT[bp::make_tuple(j%3, j/3)] = geomFrame[j];\r\n\r\n        ls.append(pyT);\r\n    }\r\n\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpModel::getBodyGeomsGlobalFrame(int index)\r\n{\r\n\tbp::list ls;\r\n\r\n\tfor(int i=0; i<_nodes[index]->body.GetNumGeometry(); ++i)\r\n    {\r\n        ndarray O = np::array(bp::make_tuple(\r\n                            bp::make_tuple(0.,0.,0.,0.),\r\n                            bp::make_tuple(0.,0.,0.,0.),\r\n                            bp::make_tuple(0.,0.,0.,0.),\r\n                            bp::make_tuple(0.,0.,0.,1.)\r\n                            )\r\n                        );\r\n        const SE3& geomFrame = _nodes[index]->body.GetGeometry(i)->GetGlobalFrame();\r\n        object pyT = O.copy();\r\n\r\n        for(int j=0; j<12; j++)\r\n            pyT[bp::make_tuple(j%3, j/3)] = geomFrame[j];\r\n\r\n        ls.append(pyT);\r\n    }\r\n\r\n\treturn ls;\r\n}\r\n\r\n\r\nobject VpModel::getBodyShape(int index)\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tchar type;\r\n\tscalar data[3];\r\n\r\n\t_nodes[index]->body.GetGeometry(0)->GetShape(&type, data);\r\n\r\n\tobject pyV = O.copy();\r\n\tpyV[0] = data[0];\r\n\tpyV[1] = data[1];\r\n\tpyV[2] = data[2];\r\n\r\n\treturn pyV;\r\n}\r\n\r\nbp::list VpModel::getBodyVerticesPositionGlobal(int index)\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\r\n\tconst vpGeom *pGeom;\r\n\tchar type;\r\n\tscalar data[3];\r\n\r\n\tbp::list ls_point;\r\n\r\n\tpGeom = _nodes[index]->body.GetGeometry(0);\r\n\tpGeom->GetShape(&type, data);\r\n\tconst SE3& geomFrame = pGeom->GetGlobalFrame();\r\n\r\n\tVec3 point;\r\n\tfor( int p=0; p<8; ++p)\r\n\t{\r\n\t\tpoint[0] = (p & MAX_X) ? data[0]/2. : -data[0]/2.;\r\n\t\tpoint[1] = (p & MAX_Y) ? data[1]/2. : -data[1]/2.;\r\n\t\tpoint[2] = (p & MAX_Z) ? data[2]/2. : -data[2]/2.;\r\n\t\tpoint = geomFrame * point;\r\n\r\n\t\tobject pyV = O.copy();\r\n\t\tVec3_2_pyVec3(point, pyV);\r\n\t\tls_point.append(pyV);\r\n\t}\r\n\treturn ls_point;\r\n}\r\n\r\n//bp::list VpModel::getBodyPoints()\r\n//{\r\n//\tbp::list ls;\r\n//\tchar type;\r\n//\tscalar data[3];\r\n//\r\n//\tconst vpGeom *pGeom;\r\n//\r\n//\tfor(int i=0; i<_nodes.size(); ++i)\r\n//\t\tif(_nodes[i])\r\n//\t\t{\r\n//\t\t\tbp::list ls_point;\r\n//\t\t\tfor( int j=0; j<_nodes[i]->body.GetNumGeometry(); ++j)\r\n//\t\t\t{\r\n//\t\t\t\tpGeom = _nodes[i]->body.GetGeometry(j);\r\n//\t\t\t\tpGeom->GetShape(&type, data);\r\n//\t\t\t\tconst SE3& geomFrame = pGeom->GetGlobalFrame();\r\n//\r\n//\t\t\t\tVec3 point;\r\n//\t\t\t\tfor( int p=0; p<8; ++p)\r\n//\t\t\t\t{\r\n//\t\t\t\t\tpoint[0] = (p & MAX_X) ? data[0]/2. : -data[0]/2.;\r\n//\t\t\t\t\tpoint[1] = (p & MAX_Y) ? data[1]/2. : -data[1]/2.;\r\n//\t\t\t\t\tpoint[2] = (p & MAX_Z) ? data[2]/2. : -data[2]/2.;\r\n//\t\t\t\t\tpoint = geomFrame * point;\r\n//\r\n//\t\t\t\t\tobject pyV = _O_Vec3->copy();\r\n//\t\t\t\t\tVec3_2_pyVec3(point, pyV);\r\n//\t\t\t\t\tls_point.append(pyV);\r\n//\t\t\t\t}\r\n//\t\t\t}\r\n//\t\t\tls.append(ls_point);\r\n//\t\t}\r\n//\treturn ls;\r\n//}\r\n\r\n//bp::list VpModel::getBodyShapes()\r\n//{\r\n//\tbp::list ls;\r\n//\tchar type;\r\n//\tscalar data[3];\r\n//\r\n//\tfor(int i=0; i<_nodes.size(); ++i)\r\n//\t\tif(_nodes[i])\r\n//\t\t{\r\n//\t\t\tbp::list ls_geom;\r\n//\t\t\tfor( int j=0; j<_nodes[i]->body.GetNumGeometry(); ++j)\r\n//\t\t\t{\r\n//\t\t\t\t_nodes[i]->body.GetGeometry(j)->GetShape(&type, data);\r\n//\t\t\t\tls_geom.append(bp::make_tuple(data[0], data[1], data[2]));\r\n//\t\t\t}\r\n//\t\t\tls.append(ls_geom);\r\n//\t\t}\r\n//\treturn ls;\r\n//}\r\n\r\nvoid VpModel::getBodyInertiaLocal(int index, SE3& Tin)\r\n{\r\n//\tif(!_nodes[index]) return;\r\n\r\n//\tss << \"I11 I22 I33 I12 I13 I23 offset.x offset.y offset.z mass\" << endl;\r\n\r\n//\tpyIn[bp::make_tuple(0,0)] = in[0];\r\n//\tpyIn[bp::make_tuple(1,1)] = in[1];\r\n//\tpyIn[bp::make_tuple(2,2)] = in[2];\r\n//\tpyIn[bp::make_tuple(0,1)] = pyIn[bp::make_tuple(1,0)] = in[3];\r\n//\tpyIn[bp::make_tuple(0,2)] = pyIn[bp::make_tuple(2,0)] = in[4];\r\n//\tpyIn[bp::make_tuple(1,2)] = pyIn[bp::make_tuple(2,1)] = in[5];\r\n\t\r\n//\t\t| T[0]\tT[3]\tT[6]\tT[ 9] |\r\n//\t\t| T[1]\tT[4]\tT[7]\tT[10] |\r\n//\t\t| T[2]\tT[5]\tT[8]\tT[11] |\r\n\r\n\tconst Inertia& in = _nodes[index]->body.GetInertia();\r\n\r\n\tTin[0] = in[0];\r\n\tTin[4] = in[1];\r\n\tTin[8] = in[2];\r\n\tTin[3] = Tin[1] = in[3];\r\n\tTin[6] = Tin[2] = in[4];\r\n\tTin[7] = Tin[5] = in[5];\r\n}\r\n\r\nboost::python::object VpModel::getBodyInertiaLocal_py( int index )\r\n{\r\n\tndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\tSE3 Tin;\r\n\tobject pyIn = I.copy();\r\n\r\n\tgetBodyInertiaLocal(index, Tin);\r\n\tSE3_2_pySO3(Tin, pyIn);\r\n\treturn pyIn;\r\n}\r\n\r\nboost::python::object VpModel::getBodyInertiaGlobal_py( int index )\r\n{\r\n\tndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\tSE3 Tin_local, bodyFrame;\r\n\tobject pyIn = I.copy();\r\n\r\n\tgetBodyInertiaLocal(index, Tin_local);\r\n\tbodyFrame = _nodes[index]->body.GetFrame() * SE3(_nodes[index]->body.GetCenterOfMass());\r\n\tSE3_2_pySO3(bodyFrame * Tin_local * Inv(bodyFrame), pyIn);\r\n\treturn pyIn;\r\n\t\r\n}\r\n\r\nbp::list VpModel::getBodyInertiasLocal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getBodyInertiaLocal_py(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpModel::getBodyInertiasGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getBodyInertiaGlobal_py(i));\r\n\treturn ls;\r\n}\r\n\r\nobject VpModel::getCOM()\r\n{\r\n\tobject pyV;\r\n\tmake_pyVec3(pyV);\r\n\tVec3 com(0., 0., 0.);\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tcom += _nodes[i]->body.GetInertia().GetMass() * _nodes[i]->body.GetFrame().GetPosition();\r\n\tcom *= 1./getTotalMass();\r\n\r\n\tVec3_2_pyVec3(com, pyV);\r\n\treturn pyV;\r\n\r\n}\r\n\r\nbp::list VpModel::getBoneT(int index)\r\n{\r\n\tbp::list ls;\r\n\tndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\r\n\tSE3_2_pySO3(_boneTs[index], I);\r\n\tVec3_2_pyVec3(_boneTs[index].GetPosition(), O);\r\n\r\n\tls.append(I);\r\n\tls.append(O);\r\n\r\n\treturn ls;\r\n}\r\nbp::list VpModel::getInvBoneT(int index)\r\n{\r\n\tbp::list ls;\r\n\tndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\r\n\tSE3 invBoneT = Inv(_boneTs[index]);\r\n\r\n\tSE3_2_pySO3(invBoneT, I);\r\n\tVec3_2_pyVec3(invBoneT.GetPosition(), O);\r\n\r\n\tls.append(I);\r\n\tls.append(O);\r\n\r\n\treturn ls;\r\n}\r\nobject VpModel::getBodyGenVelLocal(int index)\r\n{\r\n\tndarray O = np::array( bp::make_tuple(0., 0., 0., 0.,0.,0.) );\r\n\tobject pyV = O.copy();\r\n\tse3_2_pyVec6(_nodes[index]->body.GetGenVelocityLocal(), pyV);\r\n\treturn pyV;\r\n}\r\nobject VpModel::getBodyGenVelGlobal(int index)\r\n{\r\n\tndarray O = np::array( bp::make_tuple(0., 0., 0., 0.,0.,0.) );\r\n\tobject pyV = O.copy();\r\n\tse3_2_pyVec6(_nodes[index]->body.GetGenVelocity(), pyV);\r\n\treturn pyV;\r\n}\r\n\r\nobject VpModel::getBodyGenAccLocal(int index)\r\n{\r\n\tndarray O = np::array( bp::make_tuple(0., 0., 0., 0.,0.,0.) );\r\n\tobject pyV = O.copy();\r\n\tse3_2_pyVec6(_nodes[index]->body.GetGenAccelerationLocal(), pyV);\r\n\treturn pyV;\r\n}\r\nobject VpModel::getBodyGenAccGlobal(int index)\r\n{\r\n\tndarray O = np::array( bp::make_tuple(0., 0., 0., 0.,0.,0.) );\r\n\tobject pyV = O.copy();\r\n\tse3_2_pyVec6(_nodes[index]->body.GetGenAcceleration(), pyV);\r\n\treturn pyV;\r\n}\r\n\r\nobject VpModel::getBodyPositionGlobal_py( int index, const object& positionLocal/*=object() */ )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\tVec3 positionLocal_;\r\n\r\n\tif(positionLocal.is_none())\r\n\t\tVec3_2_pyVec3(getBodyPositionGlobal(index), pyV);\r\n\telse\r\n\t{\r\n\t\tpyVec3_2_Vec3(positionLocal, positionLocal_);\r\n\t\tVec3_2_pyVec3(getBodyPositionGlobal(index, &positionLocal_), pyV);\r\n\t}\r\n\treturn pyV;\r\n}\r\nobject VpModel::getBodyVelocityGlobal_py( int index, const object& positionLocal/*=object() */ )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\tVec3 positionLocal_;\r\n\r\n\tif(positionLocal.is_none())\r\n\t\tVec3_2_pyVec3(getBodyVelocityGlobal(index), pyV);\r\n\telse\r\n\t{\r\n\t\tpyVec3_2_Vec3(positionLocal, positionLocal_);\r\n\t\tVec3_2_pyVec3(getBodyVelocityGlobal(index, positionLocal_), pyV);\r\n\t}\r\n\treturn pyV;\r\n}\r\n\r\nbp::list VpModel::getBodyVelocitiesGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getBodyVelocityGlobal_py(i));\r\n\treturn ls;\r\n}\r\n\r\nobject VpModel::getBodyAngVelocityGlobal( int index )\r\n{\r\n\tse3 genVel;\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tgenVel = _nodes[index]->body.GetGenVelocity();\r\n\tpyV[0] = genVel[0];\r\n\tpyV[1] = genVel[1];\r\n\tpyV[2] = genVel[2];\r\n\treturn pyV;\r\n}\r\n\r\nbp::list VpModel::getBodyAngVelocitiesGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getBodyAngVelocityGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nobject VpModel::getBodyAccelerationGlobal_py(int index, const object& positionLocal )\r\n{\r\n\tse3 genAcc;\r\n\tVec3 positionLocal_;\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tif(positionLocal.is_none())\r\n\t\tVec3_2_pyVec3(getBodyAccelerationGlobal(index), pyV);\r\n\telse\r\n\t{\r\n\t\tpyVec3_2_Vec3(positionLocal, positionLocal_);\r\n\t\tVec3_2_pyVec3(getBodyAccelerationGlobal(index, &positionLocal_), pyV);\r\n\t}\r\n\treturn pyV;\r\n}\r\n\r\nobject VpModel::getBodyOrientationGlobal(int index)\r\n{\r\n\tndarray I = np::array(bp::make_tuple(bp::make_tuple(1., 0., 0.), bp::make_tuple(0., 1., 0.), bp::make_tuple(0., 0., 1.)));\r\n\tSE3 bodyFrame;\r\n\tobject pyR = I.copy();\r\n\r\n\tbodyFrame = _nodes[index]->body.GetFrame();\r\n\tSE3_2_pySO3(bodyFrame, pyR);\r\n\treturn pyR;\r\n}\r\n\r\nobject VpModel::getBodyTransformGlobal(int index)\r\n{\r\n\tndarray I = np::array(bp::make_tuple(\r\n\t                        bp::make_tuple(1., 0., 0., 0.),\r\n\t                        bp::make_tuple(0., 1., 0., 0.),\r\n\t                        bp::make_tuple(0., 0., 1., 0.),\r\n\t                        bp::make_tuple(0., 0., 0., 1.)\r\n\t                     ));\r\n\tSE3 bodyFrame;\r\n\tobject pyT = I.copy();\r\n\r\n\tbodyFrame = _nodes[index]->body.GetFrame();\r\n\tSE3_2_pySE3(bodyFrame, pyT);\r\n\treturn pyT;\r\n}\r\n\r\nbp::list VpModel::getBodyAccelerationsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getBodyAccelerationGlobal_py(i));\r\n\treturn ls;\r\n}\r\n\r\nvoid VpModel::setBodyPositionGlobal_py( int index, const object& pos )\r\n{\r\n\tVec3 position;\r\n\r\n\tpyVec3_2_Vec3(pos, position);\r\n\tsetBodyPositionGlobal(index, position); \r\n}\r\n\r\nobject VpModel::getBodyFrame(int index)\r\n{\r\n    object pyT;\r\n    make_pySE3(pyT);\r\n\tSE3 bodyFrame = _nodes[index]->body.GetFrame();\r\n    SE3_2_pySE3(bodyFrame, pyT);\r\n\treturn pyT;\r\n}\r\n\r\nvoid VpModel::setBodyVelocityGlobal_py( int index, const object& vel )\r\n{\r\n\tse3 genVel;\r\n\tgenVel = _nodes[index]->body.GetGenVelocity();\r\n\tgenVel[3] = XD(vel[0]);\r\n\tgenVel[4] = XD(vel[1]);\r\n\tgenVel[5] = XD(vel[2]);\r\n\t_nodes[index]->body.SetGenVelocity(genVel);\r\n}\r\n\r\nvoid VpModel::setBodyAccelerationGlobal_py( int index, const object& acc )\r\n{\r\n\tse3 genAcc;\r\n\tgenAcc = _nodes[index]->body.GetGenAcceleration();\r\n\tgenAcc[3] = XD(acc[0]);\r\n\tgenAcc[4] = XD(acc[1]);\r\n\tgenAcc[5] = XD(acc[2]);\r\n\t_nodes[index]->body.SetGenAcceleration(genAcc);\r\n}\r\n\r\nvoid VpModel::setBodyAngVelocityGlobal( int index, const object& angvel )\r\n{\r\n\tse3 genVel;\r\n\tgenVel = _nodes[index]->body.GetGenVelocity();\r\n\tgenVel[0] = XD(angvel[0]);\r\n\tgenVel[1] = XD(angvel[1]);\r\n\tgenVel[2] = XD(angvel[2]);\r\n\t_nodes[index]->body.SetGenVelocity(genVel);\r\n}\r\n\r\nvoid VpModel::setBodyAngAccelerationGlobal( int index, const object& angacc )\r\n{\r\n\tse3 genAcc;\r\n\tgenAcc = _nodes[index]->body.GetGenAcceleration();\r\n\tgenAcc[0] = XD(angacc[0]);\r\n\tgenAcc[1] = XD(angacc[1]);\r\n\tgenAcc[2] = XD(angacc[2]);\r\n\t_nodes[index]->body.SetGenAcceleration(genAcc);\r\n}\r\n\r\nbp::list VpModel::getBodyPositionsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getBodyPositionGlobal_py(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpModel::getBodyOrientationsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getBodyOrientationGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\n\r\nobject VpModel::getBodyAngAccelerationGlobal( int index )\r\n{\r\n\tse3 genAcc;\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tgenAcc = _nodes[index]->body.GetGenAcceleration();\r\n\tpyV[0] = genAcc[0];\r\n\tpyV[1] = genAcc[1];\r\n\tpyV[2] = genAcc[2];\r\n\treturn pyV;\r\n}\r\n\r\nbp::list VpModel::getBodyAngAccelerationsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getBodyAngAccelerationGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nvoid VpModel::translateByOffset( const object& offset )\r\n{\r\n\tVec3 v;\r\n\tpyVec3_2_Vec3(offset, v);\r\n\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tsetBodyPositionGlobal(i, getBodyPositionGlobal(i) + v);\r\n}\r\n\r\nvoid VpModel::rotate( const object& rotation )\r\n{\r\n\tSE3 R, bodyFrame;\r\n\tpySO3_2_SE3(rotation, R);\r\n\r\n\tbodyFrame = _nodes[0]->body.GetFrame();\r\n\t_nodes[0]->body.SetFrame(bodyFrame * R);\r\n\r\n\t// \ufffd\u0672\ufffd root body frame\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd joint\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd body\ufffd\ufffd frame \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\u01ae. \ufffd\u0330\ufffd\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd root body \ufffd\u03f3\ufffd\ufffd\ufffd rotation\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\u0234\ufffd. \r\n\t_pWorld->UpdateFrame();\r\n}\r\n\r\nvoid VpModel::ignoreCollisionWith( vpBody* pBody )\r\n{\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\t_pWorld->IgnoreCollision( &_nodes[i]->body, pBody );\r\n}\r\n\r\nvoid VpModel::ignoreCollisionWith_py( vpBody* pBody )\r\n{\r\n\tignoreCollisionWith(pBody);\r\n}\r\n\r\nVec3 VpModel::getBodyPositionGlobal( int index, const Vec3* pPositionLocal )\r\n{\r\n\tSE3 bodyFrame;\r\n\tbodyFrame = _nodes[index]->body.GetFrame();\r\n\tif(!pPositionLocal)\r\n\t\treturn bodyFrame.GetPosition();\r\n\telse\r\n\t\treturn bodyFrame * (*pPositionLocal);\r\n}\r\nVec3 VpModel::getBodyVelocityGlobal( int index, const Vec3& positionLocal)\r\n{\r\n\treturn _nodes[index]->body.GetLinVelocity(positionLocal);\r\n\r\n//\tstatic se3 genAccLocal, genAccGlobal;\r\n//\tgenAccLocal = _nodes[index]->body.GetGenVelocityLocal();\r\n//\tgenAccLocal = MinusLinearAd(positionLocal, genAccLocal);\r\n//\tgenAccGlobal = Rotate(_nodes[index]->body.GetFrame(), genAccLocal);\r\n//\treturn Vec3(genAccGlobal[3], genAccGlobal[4], genAccGlobal[5]);\r\n}\r\n\r\nVec3 VpModel::getBodyAccelerationGlobal( int index, const Vec3* pPositionLocal)\r\n{\r\n\tse3 genAccLocal, genAccGlobal;\r\n\r\n\tgenAccLocal = _nodes[index]->body.GetGenAccelerationLocal();\r\n\tif(pPositionLocal)\r\n\t\tgenAccLocal = MinusLinearAd(*pPositionLocal, genAccLocal);\r\n \r\n\tgenAccGlobal = Rotate(_nodes[index]->body.GetFrame(), genAccLocal);\r\n\r\n\treturn Vec3(genAccGlobal[3], genAccGlobal[4], genAccGlobal[5]);\r\n}\r\n\r\nvoid VpModel::setBodyPositionGlobal( int index, const Vec3& position )\r\n{\r\n\tSE3 bodyFrame;\r\n\tbodyFrame = _nodes[index]->body.GetFrame();\r\n\tbodyFrame.SetPosition(position);\r\n\t_nodes[index]->body.SetFrame(bodyFrame);\r\n}\r\n\r\nvoid VpModel::setBodyVelocityGlobal( int index, const Vec3& vel, const Vec3* pPositionLocal)\r\n{\r\n//\tif(pPositionLocal)\r\n//\t\tcout << \"pPositionLocal : not implemented functionality yet\" << endl;\r\n\r\n\tse3 genVel;\r\n\tgenVel = _nodes[index]->body.GetGenVelocity();\r\n\tgenVel[3] = vel[0];\r\n\tgenVel[4] = vel[1];\r\n\tgenVel[5] = vel[2];\r\n\r\n\t_nodes[index]->body.SetGenVelocity(genVel);\r\n}\r\n\r\n\r\nvoid VpModel::setBodyAccelerationGlobal( int index, const Vec3& acc, const Vec3* pPositionLocal)\r\n{\r\n//\tif(pPositionLocal)\r\n//\t\tcout << \"pPositionLocal : not implemented functionality yet\" << endl;\r\n\r\n\tse3 genAcc;\r\n\tgenAcc = _nodes[index]->body.GetGenAcceleration();\r\n\tgenAcc[3] = acc[0];\r\n\tgenAcc[4] = acc[1];\r\n\tgenAcc[5] = acc[2];\r\n\r\n\t_nodes[index]->body.SetGenAcceleration(genAcc);\r\n}\r\n\r\nVpMotionModel::VpMotionModel( VpWorld* pWorld, const object& createPosture, const object& config )\r\n\t:VpModel(pWorld, createPosture, config), _recordVelByFiniteDiff(false), _inverseMotionTimeStep(30.)\r\n{\r\n\t// OdeMotionModel\ufffd\ufffd node.body.disable()\ufffd\ufffd VpMotionModel\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd pWorld->AddBody()\ufffd\ufffd\r\n\t// \ufffd\ufffd \ufffd\ufffd\ufffd\u05b4\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd \ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd \ufffd\u03f5\ufffd\ufffd\ufffd \ufffd\u0474\ufffd.\r\n\r\n\tupdate(createPosture);\r\n\t\r\n//\taddBody(false);\r\n}\r\n\r\n\r\nvoid VpMotionModel::update( const object& posture)\r\n{\r\n\tobject joint = posture.attr(\"skeleton\").attr(\"root\");\r\n\tobject rootPos = posture.attr(\"rootPos\");\r\n\tSE3 T = SE3(pyVec3_2_Vec3(rootPos));\r\n\t_updateBody(joint, T, posture);\r\n}\r\n\r\n\r\nvoid VpMotionModel::_updateBody( const object& joint, const SE3& parentT, const object& posture)\r\n{\r\n\tint len_joint_children = len(joint.attr(\"children\")); \r\n\tif (len_joint_children == 0 )\r\n\t\treturn;\r\n\r\n\tSE3 T = parentT;\r\n\r\n\tSE3 P = SE3(pyVec3_2_Vec3(joint.attr(\"offset\")));\r\n\tT = T * P;\r\n\r\n\tstring joint_name = XS(joint.attr(\"name\"));\r\n//\tint joint_index = XI(posture.attr(\"skeleton\").attr(\"getElementIndex\")(joint_name));\r\n//\tSE3 R = pySO3_2_SE3(posture.attr(\"getLocalR\")(joint_index));\r\n\tint joint_index = XI(posture.attr(\"skeleton\").attr(\"getJointIndex\")(joint_name));\r\n\tSE3 R = pySO3_2_SE3(posture.attr(\"getJointOrientationLocal\")(joint_index));\r\n\tT = T * R;\r\n\r\n//\tint len_joint_children = len(joint.attr(\"children\")); \r\n//\tif (len_joint_children > 0 && _config.attr(\"hasNode\")(joint_name))\r\n\tif (_config.attr(\"hasNode\")(joint_name))\r\n\t{\r\n\t\tSE3 boneT = _boneTs[joint_index];\r\n\t\tSE3 newT = T * boneT;\r\n\r\n\t\tNode* pNode = _nodes[joint_index];\r\n\r\n\t\tif(_recordVelByFiniteDiff)\r\n\t\t{\r\n\t\t\tSE3 oldT, diffT;\r\n\t\t\toldT = pNode->body.GetFrame();\r\n\t\t\tdiffT = newT * Inv(oldT);\r\n\r\n\t\t\tVec3 p = newT.GetPosition() - oldT.GetPosition();\r\n\t\t\tdiffT.SetPosition(p);\r\n\r\n\t\t\tpNode->body.SetGenVelocity(Log(diffT) * _inverseMotionTimeStep);\r\n\t\t}\r\n\r\n\t\tpNode->body.SetFrame(newT);\r\n\t}\r\n\r\n\tfor( int i=0 ; i<len_joint_children; ++i)\r\n\t\t_updateBody(joint.attr(\"children\")[i], T, posture);\t\r\n}\r\n\r\n\r\nVpControlModel::VpControlModel( VpWorld* pWorld, const object& createPosture, const object& config )\r\n\t:VpModel(pWorld, createPosture, config)\r\n{\r\n    if(pWorld != nullptr)\r\n    {\r\n        addBodiesToWorld(createPosture);\r\n        ignoreCollisionBtwnBodies();\r\n\r\n        object tpose = createPosture.attr(\"getTPose\")();\r\n        createJoints(tpose);\r\n\r\n        update(createPosture);\r\n\r\n        _nodes[0]->dof = 6;\r\n        m_total_dof = 0;\r\n        int dof_start_index = 0;\r\n        for(std::vector<int>::size_type i=0; i<_nodes.size(); i++)\r\n        {\r\n            _nodes[i]->dof_start_index = dof_start_index;\r\n            dof_start_index += _nodes[i]->dof;\r\n            m_total_dof += _nodes[i]->dof;\r\n    //\t    for(std::vector<int>::size_type j=0; j<_nodes[i]->ancestors.size(); j++)\r\n    //\t        std::cout << _nodes[i]->ancestors[j] << \" \";\r\n    //\t    std::cout << std::endl;\r\n        }\r\n\r\n        for(std::vector<int>::size_type body_idx=0; body_idx<_nodes.size(); body_idx++)\r\n        {\r\n            std::vector<int> &ancestors = _nodes[body_idx]->ancestors;\r\n            for(std::vector<int>::size_type j=0; j<_nodes.size(); j++)\r\n            {\r\n                if(std::find(ancestors.begin(), ancestors.end(), j) != ancestors.end())\r\n                {\r\n                    _nodes[body_idx]->is_ancestor.push_back(true);\r\n                }\r\n                else\r\n                {\r\n                    _nodes[body_idx]->is_ancestor.push_back(false);\r\n                }\r\n            }\r\n        }\r\n\r\n\r\n\r\n    //\taddBody(true);\r\n    }\r\n}\r\n\r\nstd::string VpControlModel::__str__()\r\n{\r\n\tstring s1 = VpModel::__str__();\r\n\r\n\tstringstream ss;\r\n\r\n\tss << \"<INTERNAL JOINTS>\" << endl;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tss << \"[\" << i-1 << \"]:\" << _nodes[i]->name << \", \";\r\n\tss << endl;\r\n\r\n\treturn s1 + ss.str();\r\n}\r\n\r\nbp::list VpControlModel::getInternalJointDOFs()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t{\r\n\t\tls.append(_nodes[i]->dof);\r\n    }\r\n\treturn ls;\r\n}\r\n\r\nint VpControlModel::getTotalInternalJointDOF()\r\n{\r\n\tint dof = 0;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tdof += _nodes[i]->dof;\r\n\t\t// dof += 3;\r\n\treturn dof;\r\n}\r\n\r\nbp::list VpControlModel::getDOFs()\r\n{\r\n\tbp::list ls;\r\n\tls.append(6);\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t{\r\n\t\tls.append(_nodes[i]->dof);\r\n    }\r\n\treturn ls;\r\n}\r\n\r\nint VpControlModel::getTotalDOF()\r\n{\r\n\tint dof = 0;\r\n\tdof += 6;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tdof += _nodes[i]->dof;\r\n\t\t// dof += 3;\r\n\treturn dof;\r\n}\r\n\r\nbp::list VpControlModel::getJointDOFIndexes(int index)\r\n{\r\n    bp::list ls;\r\n    int dof_index = _nodes[index]->dof_start_index;\r\n    for(int i=0; i<_nodes[index]->dof; i++)\r\n        ls.append(dof_index++);\r\n    return ls;\r\n\r\n}\r\n\r\nbp::list VpControlModel::getJointDOFInternalIndexes(int index)\r\n{\r\n    assert(index > 0);\r\n    bp::list ls;\r\n    int dof_index = _nodes[index]->dof_start_index;\r\n    for(int i=0; i<_nodes[index]->dof; i++)\r\n        ls.append(dof_index++ - 6);\r\n    return ls;\r\n\r\n}\r\n\r\nvoid VpControlModel::createJoints( const object& posture )\r\n{\r\n\tobject joint = posture.attr(\"skeleton\").attr(\"root\");\r\n\tstd::vector<int> empty;\r\n\t_createJoint(joint, posture, empty);\r\n}\r\n\r\nvoid VpControlModel::_createJoint( const object& joint, const object& posture, const std::vector<int> &parent_ancestors)\r\n{\r\n\tint len_joint_children = len(joint.attr(\"children\"));\r\n\tif (len_joint_children == 0 )\r\n\t\treturn;\r\n\r\n\tSE3 invLocalT;\r\n\r\n\tobject offset = joint.attr(\"offset\");\r\n\tSE3 P = SE3(pyVec3_2_Vec3(joint.attr(\"offset\")));\r\n\r\n\tstring joint_name = XS(joint.attr(\"name\"));\r\n//\tint joint_index = XI(posture.attr(\"skeleton\").attr(\"getElementIndex\")(joint_name));\r\n//\tSE3 R = pySO3_2_SE3(posture.attr(\"getLocalR\")(joint_index));\r\n\tint joint_index = XI(posture.attr(\"skeleton\").attr(\"getJointIndex\")(joint_name));\r\n\tSE3 R = pySO3_2_SE3(posture.attr(\"getJointOrientationLocal\")(joint_index));\r\n\r\n\t// parent      <--------->        child\r\n\t// link     L1      L2      L3      L4\r\n\t// L4_M =  P1*R1 * P2*R2 * P3*R3 * P4*R4  (forward kinematics matrix of L4)\r\n\t// \ufffd\ufffd\ufffd\ufffd \ufffd\ufffd\u0178\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd \ufffd\ufffd\ufffd\u2fe1\ufffd\ufffd while loop\ufffd\ufffd \ufffd\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd back tracking\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\r\n\t// L4_M = Inv( Inv(R4)*Inv(P4) * Inv(R3)*Inv(P3) * ...)\r\n\t// \ufffd\ufffd\ufffd\ufffd \ufffd\u06b5\ufffd\ufffd\ufffd\ufffd\ufffd.\r\n\r\n\tinvLocalT = invLocalT * Inv(R);\r\n\tinvLocalT = invLocalT * Inv(P);\r\n\r\n\tobject temp_joint = joint;\r\n\tobject nodeExistParentJoint = object();\r\n\tstring temp_parent_name;\r\n\tint temp_parent_index;\r\n\twhile(true)\r\n\t{\r\n\t    object temp_parent_object = temp_joint.attr(\"parent\");\r\n\t\tif(temp_parent_object.is_none())\r\n\t\t{\r\n\t\t\tnodeExistParentJoint = object();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttemp_parent_name = XS(temp_joint.attr(\"parent\").attr(\"name\"));\r\n//\t\t\ttemp_parent_index = XI(posture.attr(\"skeleton\").attr(\"getElementIndex\")(temp_parent_name));\r\n\t\t\ttemp_parent_index = XI(posture.attr(\"skeleton\").attr(\"getJointIndex\")(temp_parent_name));\r\n\r\n\t\t\tif(_nodes[temp_parent_index] != NULL)\r\n\t\t\t{\r\n\t\t\t\tnodeExistParentJoint = temp_joint.attr(\"parent\");\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttemp_joint = temp_joint.attr(\"parent\");\r\n\r\n\t\t\t\tobject offset = temp_joint.attr(\"offset\");\r\n\t\t\t\tSE3 P = SE3(pyVec3_2_Vec3(offset));\r\n\r\n\t\t\t\tstring joint_name = XS(temp_joint.attr(\"name\"));\r\n\t\t\t\tobject localSO3 = posture.attr(\"localRs\")[joint_index];\r\n\t\t\t\tSE3 R = pySO3_2_SE3(localSO3);\r\n\r\n\t\t\t\tinvLocalT = invLocalT * Inv(R);\r\n\t\t\t\tinvLocalT = invLocalT * Inv(P);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n//\tint len_joint_children = len(joint.attr(\"children\"));\r\n\r\n//\tif ( nodeExistParentJoint!=object() && len_joint_children > 0  &&\r\n//\t\t_config.attr(\"hasNode\")(joint_name))\r\n\tif ( !nodeExistParentJoint.is_none() && _config.attr(\"hasNode\")(joint_name))\r\n\t{\r\n\t\tNode* pNode = _nodes[joint_index];\r\n\t\tobject cfgNode = _config.attr(\"getNode\")(joint_name);\r\n\r\n\t\tstring parent_name = XS(nodeExistParentJoint.attr(\"name\"));\r\n//\t\tint parent_index = XI(posture.attr(\"skeleton\").attr(\"getElementIndex\")(parent_name));\r\n\t\tint parent_index = XI(posture.attr(\"skeleton\").attr(\"getJointIndex\")(parent_name));\r\n\t\tNode* pParentNode = _nodes[parent_index];\r\n\t\tobject parentCfgNode = _config.attr(\"getNode\")(parent_name);\r\n\r\n\t\t//object offset = cfgNode.attr(\"offset\");\r\n\t\t//SE3 offsetT = SE3(pyVec3_2_Vec3(offset));\r\n\r\n\t\t//object parentOffset = parentCfgNode.attr(\"offset\");\r\n\t\t//SE3 parentOffsetT = SE3(pyVec3_2_Vec3(parentOffset));\r\n\r\n        if (0 == std::string(XS(cfgNode.attr(\"jointType\"))).compare(\"B\"))\r\n        {\r\n            pParentNode->body.SetJoint(&pNode->joint, Inv(_boneTs[parent_index])*Inv(invLocalT));\r\n            pNode->body.SetJoint(&pNode->joint, Inv(_boneTs[joint_index]));\r\n        }\r\n        else if (0 == std::string(XS(cfgNode.attr(\"jointType\"))).compare(\"R\"))\r\n        {\r\n            pParentNode->body.SetJoint(&pNode->joint_revolute, Inv(_boneTs[parent_index])*Inv(invLocalT));\r\n            pNode->body.SetJoint(&pNode->joint_revolute, Inv(_boneTs[joint_index]));\r\n            if (0 == std::string(XS(cfgNode.attr(\"jointAxes\")[0])).compare(\"X\"))\r\n                pNode->joint_revolute.SetAxis(Vec3(1., 0., 0.));\r\n            else if (0 == std::string(XS(cfgNode.attr(\"jointAxes\")[0])).compare(\"Y\"))\r\n                pNode->joint_revolute.SetAxis(Vec3(0., 1., 0.));\r\n            else if (0 == std::string(XS(cfgNode.attr(\"jointAxes\")[0])).compare(\"Z\"))\r\n                pNode->joint_revolute.SetAxis(Vec3(0., 0., 1.));\r\n            pNode->dof = 1;\r\n        }\r\n        else\r\n            std::cout << joint_name <<\" \" << std::string(XS(cfgNode.attr(\"jointType\"))) << \" is an unsupported joint type.\" << std::endl;\r\n\r\n\t\tscalar kt = 16.;\r\n\t\tscalar dt = 8.;\r\n\t\tSpatialSpring el(kt);\r\n\t\tSpatialDamper dam(dt);\r\n\t\t//std::cout << el <<std::endl;\r\n\t\t// pNode->joint.SetElasticity(el);\r\n\t\t// pNode->joint.SetDamping(dam);\r\n\t\tpNode->use_joint = true;\r\n\t\t_nodes[joint_index]->parent_index = parent_index;\r\n\t}\r\n\tfor (std::vector<int>::size_type i=0; i<parent_ancestors.size(); i++)\r\n\t    _nodes[joint_index]->ancestors.push_back(parent_ancestors[i]);\r\n    _nodes[joint_index]->ancestors.push_back(joint_index);\r\n\r\n\tfor( int i=0 ; i<len_joint_children; ++i)\r\n\t\t_createJoint(joint.attr(\"children\")[i], posture, _nodes[joint_index]->ancestors);\r\n}\r\n\r\nvoid VpControlModel::ignoreCollisionBtwnBodies()\r\n{\r\n\tfor( VpModel::NODES_ITOR it=_nodes.begin(); it!=_nodes.end(); ++it)\r\n\t{\r\n\t\tfor( VpModel::NODES_ITOR it2=_nodes.begin(); it2!=_nodes.end(); ++it2)\r\n\t\t{\r\n\t\t\tNode* pNode0 = *it;\r\n\t\t\tNode* pNode1 = *it2;\r\n//\t\t\tif(pNode0 && pNode1)\r\n\t\t\t\t_pWorld->IgnoreCollision(&pNode0->body, &pNode1->body);\r\n\t\t}\r\n\t}\t\r\n}\r\n\r\nvoid VpControlModel::addBodiesToWorld( const object& createPosture )\r\n{\r\n//\tobject joint = createPosture.attr(\"skeleton\").attr(\"root\");\r\n//\tstring root_name = XS(joint.attr(\"name\"));\r\n//\tint root_index = XI(createPosture.attr(\"skeleton\").attr(\"getElementIndex\")(root_name));\r\n//\tvpBody* pRootBody = &_nodes[root_index]->body;\r\n\tvpBody* pRootBody = &_nodes[0]->body;\r\n\t_pWorld->AddBody(pRootBody);\r\n}\r\n\r\nvoid VpControlModel::update( const object& posture )\r\n{\r\n\tobject joint = posture.attr(\"skeleton\").attr(\"root\");\r\n\t_updateJoint(joint, posture);\r\n}\r\n\r\nvoid VpControlModel::_updateJoint( const object& joint, const object& posture )\r\n{\r\n\tint len_joint_children = len(joint.attr(\"children\")); \r\n\tif (len_joint_children == 0 )\r\n\t\treturn;\r\n\r\n\tSE3 invLocalT;\r\n\r\n\tSE3 P = SE3(pyVec3_2_Vec3(joint.attr(\"offset\")));\r\n\r\n\tstring joint_name = XS(joint.attr(\"name\"));\r\n//\tint joint_index = XI(posture.attr(\"skeleton\").attr(\"getElementIndex\")(joint_name));\r\n//\tSE3 R = pySO3_2_SE3(posture.attr(\"getLocalR\")(joint_index));\r\n\tint joint_index = XI(posture.attr(\"skeleton\").attr(\"getJointIndex\")(joint_name));\r\n\tSE3 R = pySO3_2_SE3(posture.attr(\"getJointOrientationLocal\")(joint_index));\r\n\r\n\t// parent      <--------->        child\r\n\t// link     L1      L2      L3      L4\r\n\t// L4_M =  P1*R1 * P2*R2 * P3*R3 * P4*R4  (forward kinematics matrix of L4)\r\n\t// \ufffd\ufffd\ufffd\ufffd \ufffd\ufffd\u0178\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd \ufffd\ufffd\ufffd\u2fe1\ufffd\ufffd while loop\ufffd\ufffd \ufffd\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd back tracking\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\r\n\t// L4_M = Inv( Inv(R4)*Inv(P4) * Inv(R3)*Inv(P3) * ...)\r\n\t// \ufffd\ufffd\ufffd\ufffd \ufffd\u06b5\ufffd\ufffd\ufffd\ufffd\ufffd.\r\n\r\n\tinvLocalT = invLocalT * Inv(R);\r\n\tinvLocalT = invLocalT * Inv(P);\r\n\r\n\tobject temp_joint = joint;\r\n\tobject nodeExistParentJoint = object();\r\n\tstring temp_parent_name;\r\n\tint temp_parent_index;\r\n\twhile(true)\r\n\t{\r\n\t    object temp_parent_object = temp_joint.attr(\"parent\");\r\n\t\tif(temp_parent_object.is_none())\r\n\t\t{\r\n\t\t\tnodeExistParentJoint = object();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttemp_parent_name = XS(temp_joint.attr(\"parent\").attr(\"name\"));\r\n//\t\t\ttemp_parent_index = XI(posture.attr(\"skeleton\").attr(\"getElementIndex\")(temp_parent_name));\r\n\t\t\ttemp_parent_index = XI(posture.attr(\"skeleton\").attr(\"getJointIndex\")(temp_parent_name));\r\n\r\n\t\t\tif(_nodes[temp_parent_index] != NULL) \r\n\t\t\t{\r\n\t\t\t\tnodeExistParentJoint = temp_joint.attr(\"parent\");\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttemp_joint = temp_joint.attr(\"parent\");\r\n\r\n\t\t\t\tobject offset = temp_joint.attr(\"offset\");\r\n\t\t\t\tSE3 P = SE3(pyVec3_2_Vec3(offset));\r\n\r\n\t\t\t\tstring joint_name = XS(temp_joint.attr(\"name\"));\r\n\t\t\t\tobject localSO3 = posture.attr(\"localRs\")[joint_index];\r\n\t\t\t\tSE3 R = pySO3_2_SE3(localSO3);\r\n\r\n\t\t\t\tinvLocalT = invLocalT * Inv(R);\r\n\t\t\t\tinvLocalT = invLocalT * Inv(P);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n//\tint len_joint_children = len(joint.attr(\"children\")); \r\n\r\n//\tif(len_joint_children > 0 && _config.attr(\"hasNode\")(joint_name))\r\n\tif(_config.attr(\"hasNode\")(joint_name))\r\n\t{\r\n\t\tNode* pNode = _nodes[joint_index];\r\n\r\n\t\tif( !nodeExistParentJoint.is_none())\r\n\t\t\tpNode->joint.SetOrientation(R);\r\n\t\telse\r\n\t\t\t// root\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd body\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd SetFrame() \ufffd\ufffd\ufffd\u0634\ufffd.\r\n\t\t\tpNode->body.SetFrame(SE3(pyVec3_2_Vec3(posture.attr(\"rootPos\")))*P*R*_boneTs[joint_index]);\r\n\t}\r\n\r\n\tfor( int i=0 ; i<len_joint_children; ++i)\r\n\t\t_updateJoint(joint.attr(\"children\")[i], posture);\r\n}\r\n\r\nvoid VpControlModel::fixBody( int index )\r\n{\r\n\t_nodes[index]->body.SetGround();\r\n}\r\n\r\nvoid VpControlModel::initializeHybridDynamics(bool floatingBase)\r\n{\r\n\tstd::vector<int>::size_type rootIndex = 0;\r\n\t\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t{\r\n\t\tif(i == rootIndex)\r\n\t\t{\r\n\t\t\tif(floatingBase)\r\n\t\t\t\t_nodes[i]->body.SetHybridDynamicsType(VP::DYNAMIC);\r\n\t\t\telse\r\n\t\t\t\t_nodes[i]->body.SetHybridDynamicsType(VP::KINEMATIC);\r\n\t\t}\r\n\t\telse\r\n\t\t\t_nodes[i]->joint.SetHybridDynamicsType(VP::KINEMATIC);\r\n\t}\r\n}\r\n\r\nvoid VpControlModel::initializeForwardDynamics()\r\n{\r\n    std::vector<int>::size_type rootIndex = 0;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t{\r\n        _nodes[i]->body.SetHybridDynamicsType(VP::DYNAMIC);\r\n\t    if(i != rootIndex)\r\n            _nodes[i]->joint.SetHybridDynamicsType(VP::DYNAMIC);\r\n    }\r\n}\r\n\r\nvoid VpControlModel::setHybridDynamics(int jointIndex, std::string dynamicsType)\r\n{\r\n    if(dynamicsType == \"DYNAMIC\")\r\n    {\r\n        _nodes[jointIndex]->body.SetHybridDynamicsType(VP::DYNAMIC);\r\n        _nodes[jointIndex]->joint.SetHybridDynamicsType(VP::DYNAMIC);\r\n    }\r\n    else if(dynamicsType == \"KINEMATIC\")\r\n        _nodes[jointIndex]->joint.SetHybridDynamicsType(VP::KINEMATIC);\r\n}\r\n\r\nvoid VpControlModel::solveHybridDynamics()\r\n{\r\n\t_nodes[0]->body.GetSystem()->HybridDynamics();\t\r\n}\r\n\r\nvoid VpControlModel::solveForwardDynamics()\r\n{\r\n\t_nodes[0]->body.GetSystem()->ForwardDynamics();\r\n}\r\n\r\nvoid VpControlModel::solveInverseDynamics()\r\n{\r\n\t_nodes[0]->body.GetSystem()->InverseDynamics();\r\n}\r\n\r\nstatic Axis GetDq_Body(const SE3& R, const Vec3& V)\r\n{\r\n    Axis m_rDq;\r\n    Axis m_rQ = LogR(R);\r\n\tAxis W(V[0], V[1], V[2]);\r\n\tscalar t = Norm(m_rQ), delta, zeta, t2 = t * t;\r\n\r\n\tif ( t < BJOINT_EPS )\r\n\t{\r\n\t\tdelta  = SCALAR_1_12 + SCALAR_1_720 * t2;\r\n\t\tzeta = SCALAR_1 - SCALAR_1_12 * t2;\r\n\t} else\r\n\t{\r\n\t\tzeta = SCALAR_1_2 * t * (SCALAR_1 + cos(t)) / sin(t);\r\n\t\tdelta = (SCALAR_1 - zeta) / t2;\r\n\t}\r\n\r\n\treturn (delta * Inner(m_rQ, V)) * m_rQ + zeta * W + SCALAR_1_2 * Cross(m_rQ, W);\r\n}\r\n\r\nstatic Axis GetDq_Spatial(const SE3& R, const Vec3& V)\r\n{\r\n    Axis m_rDq;\r\n    Axis m_rQ = LogR(R);\r\n\tAxis W(V[0], V[1], V[2]);\r\n\tscalar t = Norm(m_rQ), delta, zeta, t2 = t * t;\r\n\r\n\tif ( t < BJOINT_EPS )\r\n\t{\r\n\t\tdelta  = SCALAR_1_12 + SCALAR_1_720 * t2;\r\n\t\tzeta = SCALAR_1 - SCALAR_1_12 * t2;\r\n\t} else\r\n\t{\r\n\t\tzeta = SCALAR_1_2 * t * (SCALAR_1 + cos(t)) / sin(t);\r\n\t\tdelta = (SCALAR_1 - zeta) / t2;\r\n\t}\r\n\r\n\treturn (delta * Inner(m_rQ, V)) * m_rQ + zeta * W - SCALAR_1_2 * Cross(m_rQ, W);\r\n}\r\n\r\nvoid VpControlModel::set_q(const object &q)\r\n{\r\n    SE3 rootJointFrame = Exp(Axis(XD(q[0]), XD(q[1]), XD(q[2])));\r\n    rootJointFrame.SetPosition(Vec3(XD(q[3]), XD(q[4]), XD(q[5])));\r\n    SE3 rootBodyFrame = rootJointFrame * _boneTs[0];\r\n\r\n    _nodes[0]->body.SetFrame(rootBodyFrame);\r\n\r\n    int q_idx = 6;\r\n    for(std::vector<int>::size_type j=1; j<_nodes.size(); j++)\r\n    {\r\n        _nodes[j]->joint.SetOrientation(Exp(Axis(XD(q[q_idx]), XD(q[q_idx+1]), XD(q[q_idx+2]))));\r\n        q_idx = q_idx + 3;\r\n    }\r\n    _pWorld->UpdateFrame();\r\n    for(std::vector<int>::size_type j=0; j<_nodes.size(); j++)\r\n    {\r\n        _nodes[j]->body.UpdateGeomFrame();\r\n    }\r\n}\r\n\r\nbp::list VpControlModel::get_q()\r\n{\r\n    // Angular First for root joint\r\n    bp::list ls;\r\n\tSE3 rootBodyFrame = _nodes[0]->body.GetFrame();\r\n\tSE3 rootJointFrame = rootBodyFrame * Inv(_boneTs[0]);\r\n    Vec3 rootJointPos = rootJointFrame.GetPosition();\r\n    Axis rootJointQ = LogR(rootJointFrame);\r\n    Axis jointQ;\r\n\r\n    for(int i=0; i<3; i++)\r\n    {\r\n        ls.append(rootJointQ[i]);\r\n    }\r\n    for(int i=0; i<3; i++)\r\n    {\r\n        ls.append(rootJointPos[i]);\r\n    }\r\n\tfor(std::vector<int>::size_type j=1; j<_nodes.size(); j++)\r\n\t{\r\n\t    if (_nodes[j]->dof == 3)\r\n\t    {\r\n            jointQ = _nodes[j]->joint.GetDisplacement();\r\n            for(int i=0; i<3; i++)\r\n            {\r\n                ls.append(jointQ[i]);\r\n            }\r\n\t    }\r\n\t}\r\n\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::get_dq()\r\n{\r\n    // Linear First for root joint\r\n    bp::list ls;\r\n\r\n    SE3 rootJointFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);\r\n    se3 rootBodyGenVelLocal = _nodes[0]->body.GetGenVelocityLocal();\r\n    se3 rootJointGenVelLocal = rootBodyGenVelLocal;\r\n    Vec3 rootJointAngVelLocal(rootJointGenVelLocal[0], rootJointGenVelLocal[1], rootJointGenVelLocal[2]);\r\n    Axis rootJointDq = GetDq_Body(rootJointFrame, rootJointAngVelLocal);\r\n    Vec3 rootJointLinVelGlobal = _nodes[0]->body.GetLinVelocity(Inv(_boneTs[0]).GetPosition());\r\n    for(int i=0; i<3; i++)\r\n    {\r\n        ls.append(rootJointLinVelGlobal[i]);\r\n    }\r\n    for(int i=0; i<3; i++)\r\n    {\r\n//        ls.append(rootJointDq);\r\n        ls.append(rootJointAngVelLocal[i]);\r\n    }\r\n\tfor(std::vector<int>::size_type j=1; j<_nodes.size(); j++)\r\n\t{\r\n\t    if (_nodes[j]->dof == 3)\r\n\t    {\r\n            // Axis jointDq = _nodes[j]->joint.GetDisplacementDerivate();\r\n            Vec3 jointDq = _nodes[j]->joint.GetVelocity();\r\n            for(int i=0; i<3; i++)\r\n            {\r\n                ls.append(jointDq[i]);\r\n            }\r\n\t    }\r\n\t    else if(_nodes[j]->dof == 1)\r\n\t    {\r\n\t        ls.append(_nodes[j]->joint_revolute.GetVelocity());\r\n\t    }\r\n\t}\r\n\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::get_dq_nested()\r\n{\r\n    // Angular First for root joint\r\n    bp::list ls;\r\n\tndarray rootGenVel = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));\r\n\r\n    SE3 rootJointFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);\r\n    se3 rootBodyGenVelLocal = _nodes[0]->body.GetGenVelocityLocal();\r\n    se3 rootJointGenVelLocal = rootBodyGenVelLocal;\r\n    Vec3 rootJointAngVelLocal(rootJointGenVelLocal[0], rootJointGenVelLocal[1], rootJointGenVelLocal[2]);\r\n    Axis rootJointDq = GetDq_Body(rootJointFrame, rootJointAngVelLocal);\r\n    Vec3 rootJointLinVelGlobal = _nodes[0]->body.GetLinVelocity(Inv(_boneTs[0]).GetPosition());\r\n    for(int i=0; i<3; i++)\r\n    {\r\n//        rootGenVel[i] = rootJointDq[i];\r\n        rootGenVel[i+3] = rootJointAngVelLocal[i];\r\n    }\r\n    for(int i=0; i<3; i++)\r\n    {\r\n        rootGenVel[i] = rootJointLinVelGlobal[i];\r\n    }\r\n\r\n    ls.append(rootGenVel);\r\n\r\n\tfor(std::vector<int>::size_type j=1; j<_nodes.size(); j++)\r\n\t{\r\n\t    if (_nodes[j]->dof == 3)\r\n\t    {\r\n            // Axis jointDq = _nodes[j]->joint.GetDisplacementDerivate();\r\n            // ls.append(Axis_2_pyVec3(jointDq));\r\n            Vec3 jointDq = _nodes[j]->joint.GetVelocity();\r\n            ls.append(Vec3_2_pyVec3(jointDq));\r\n\t    }\r\n\t    else if(_nodes[j]->dof == 1)\r\n\t    {\r\n\t        Vec3 jointDq = _nodes[j]->joint_revolute.GetVelocity() * _nodes[j]->joint_revolute.GetAxis();\r\n            ls.append(Vec3_2_pyVec3(jointDq));\r\n\t    }\r\n\t}\r\n\r\n\treturn ls;\r\n\r\n}\r\n\r\nvoid VpControlModel::set_ddq(const object & ddq)\r\n{\r\n    //TODO:\r\n    int ddq_index = 6;\r\n    SE3 rootJointFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);\r\n    Axis rootJointDdq(XD(ddq[3]), XD(ddq[4]), XD(ddq[5]));\r\n    _nodes[0]->joint.SetDdq(rootJointDdq);\r\n    Vec3 rootJointAngAccLocal = _nodes[0]->joint.GetAcceleration();\r\n    Vec3 rootBodyAngAccLocal = rootJointAngAccLocal;\r\n\r\n    Vec3 rootJointLinAccGlobal(XD(ddq[0]), XD(ddq[1]), XD(ddq[2]));\r\n    Vec3 rootJointLinAccLocal = InvRotate(rootJointFrame, rootJointLinAccGlobal);\r\n    Vec3 rootBodyLinAccLocal = rootJointLinAccLocal;\r\n\r\n    se3 rootBodyGenAccLocal(rootBodyAngAccLocal[0], rootBodyAngAccLocal[1], rootBodyAngAccLocal[2],\r\n                            rootBodyLinAccLocal[0], rootBodyLinAccLocal[1], rootBodyLinAccLocal[2]);\r\n\r\n    _nodes[0]->body.SetGenAccelerationLocal(rootBodyGenAccLocal);\r\n\tfor(std::vector<int>::size_type j=1; j<_nodes.size(); j++)\r\n\t{\r\n\t    if(_nodes[j]->dof == 3)\r\n\t    {\r\n            // Axis jointDdq(XD(ddq[ddq_index]), XD(ddq[ddq_index+1]), XD(ddq[ddq_index+2]));\r\n            // _nodes[j]->joint.SetDdq(jointDdq);\r\n            Vec3 jointDdq(XD(ddq[ddq_index]), XD(ddq[ddq_index+1]), XD(ddq[ddq_index+2]));\r\n            _nodes[j]->joint.SetAcceleration(jointDdq);\r\n            ddq_index += 3;\r\n        }\r\n        else if(_nodes[j]->dof == 1)\r\n        {\r\n            _nodes[j]->joint_revolute.SetAcceleration(XD(ddq[ddq_index]));\r\n            ddq_index += 1;\r\n        }\r\n\t}\r\n}\r\n\r\nvoid VpControlModel::set_ddq_vp(const std::vector<double> & ddq)\r\n{\r\n    //TODO:\r\n    int ddq_index = 6;\r\n    SE3 rootJointFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);\r\n    Axis rootJointDdq(ddq[3], ddq[4], ddq[5]);\r\n    _nodes[0]->joint.SetDdq(rootJointDdq);\r\n    Vec3 rootJointAngAccLocal = _nodes[0]->joint.GetAcceleration();\r\n    Vec3 rootBodyAngAccLocal = rootJointAngAccLocal;\r\n\r\n    Vec3 rootJointLinAccGlobal(ddq[0], ddq[1], ddq[2]);\r\n    Vec3 rootJointLinAccLocal = InvRotate(rootJointFrame, rootJointLinAccGlobal);\r\n    Vec3 rootBodyLinAccLocal = rootJointLinAccLocal;\r\n\r\n    se3 rootBodyGenAccLocal(rootBodyAngAccLocal[0], rootBodyAngAccLocal[1], rootBodyAngAccLocal[2],\r\n                            rootBodyLinAccLocal[0], rootBodyLinAccLocal[1], rootBodyLinAccLocal[2]);\r\n\r\n    _nodes[0]->body.SetGenAccelerationLocal(rootBodyGenAccLocal);\r\n\tfor(std::vector<int>::size_type j=1; j<_nodes.size(); j++)\r\n\t{\r\n\t    if(_nodes[j]->dof == 3)\r\n\t    {\r\n            // Axis jointDdq(ddq[ddq_index], ddq[ddq_index+1], ddq[ddq_index+2]);\r\n            // _nodes[j]->joint.SetDdq(jointDdq);\r\n            Vec3 jointDdq(ddq[ddq_index], ddq[ddq_index+1], ddq[ddq_index+2]);\r\n            _nodes[j]->joint.SetAcceleration(jointDdq);\r\n            ddq_index += 3;\r\n        }\r\n        else if(_nodes[j]->dof == 1)\r\n        {\r\n            _nodes[j]->joint_revolute.SetAcceleration(ddq[ddq_index]);\r\n            ddq_index += 1;\r\n        }\r\n\t}\r\n}\r\n\r\nbp::list VpControlModel::getDOFPositions()\r\n{\r\n//\tstatic ndarray rootFrame( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.), bp::make_tuple(0.,1.,0.,0.), bp::make_tuple(0.,0.,1.,0.), bp::make_tuple(0.,0.,0.,1.)) );\r\n//\r\n//\tbp::list ls = getInternalJointOrientationsLocal();\r\n//\tSE3_2_pySE3(_nodes[0]->body.GetFrame() * Inv(_boneTs[0]), rootFrame);\r\n//\tls.insert(0, rootFrame );\r\n//\treturn ls;\r\n\r\n\tndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tSE3 rootFrame;\r\n\r\n\tobject pyR = I.copy();\r\n\tobject pyV = O.copy();\r\n\r\n\tbp::list ls = getInternalJointOrientationsLocal();\r\n\r\n\trootFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);\r\n\r\n\tVec3_2_pyVec3(rootFrame.GetPosition(), pyV);\r\n\tSE3_2_pySO3(rootFrame, pyR);\r\n\r\n\tls.insert(0, bp::make_tuple(pyV, pyR));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getDOFVelocities()\r\n{\r\n\tndarray rootGenVel = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));\r\n\t\r\n\trootGenVel.slice(0,3) = getJointVelocityGlobal(0);\r\n//\trootGenVel.slice(3,6) = getJointAngVelocityGlobal(0);\r\n\trootGenVel.slice(3,6) = getJointAngVelocityLocal(0);\r\n\r\n\tbp::list ls = getInternalJointAngVelocitiesLocal();\r\n\tls.insert(0, rootGenVel);\r\n\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getDOFAccelerations()\r\n{\r\n\tndarray rootGenAcc = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));\r\n\t\r\n\trootGenAcc.slice(0,3) = getJointAccelerationGlobal(0);\r\n//\trootGenAcc.slice(3,6) = getJointAngAccelerationGlobal(0);\r\n\trootGenAcc.slice(3,6) = getJointAngAccelerationLocal(0);\r\n\r\n\tbp::list ls = getInternalJointAngAccelerationsLocal();\r\n\r\n\tls.insert(0, rootGenAcc);\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getDOFAxeses()\r\n{\r\n\tndarray rootAxeses = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.),\r\n\t\t\t\t\t\t\t\t\t\tbp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\r\n\t//ndarray rootAxesTmp = (ndarray)getJointOrientationGlobal(0);\r\n\tndarray rootAxesTmp = np::array(getJointOrientationGlobal(0));\r\n\tndarray rootAxes = transpose_pySO3(rootAxesTmp);\r\n\trootAxeses[3] = rootAxes[0];\r\n\trootAxeses[4] = rootAxes[1];\r\n\trootAxeses[5] = rootAxes[2];\r\n\r\n\tbp::list ls = getInternalJointOrientationsGlobal();\r\n\tfor(int i=0; i<len(ls); ++i)\r\n\t{\r\n\t\t//ndarray lsTmp = (ndarray)ls[i];\r\n\t\tndarray lsTmp = np::array(ls[i]);\r\n\t\tls[i] = transpose_pySO3(lsTmp);\r\n\t}\r\n\r\n\tls.insert(0, rootAxeses);\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getDOFPositionsLocal()\r\n{\r\n//\tstatic ndarray rootFrame( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.), bp::make_tuple(0.,1.,0.,0.), bp::make_tuple(0.,0.,1.,0.), bp::make_tuple(0.,0.,0.,1.)) );\r\n//\r\n//\tbp::list ls = getInternalJointOrientationsLocal();\r\n//\tSE3_2_pySE3(_nodes[0]->body.GetFrame() * Inv(_boneTs[0]), rootFrame);\r\n//\tls.insert(0, rootFrame );\r\n//\treturn ls;\r\n\r\n\tndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tSE3 rootFrame;\r\n\r\n\tobject pyR = I.copy();\r\n\tobject pyV = O.copy();\r\n\r\n\tbp::list ls = getInternalJointOrientationsLocal();\r\n\r\n\trootFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);\r\n\r\n\tVec3_2_pyVec3(-Inv(rootFrame).GetPosition(), pyV);\r\n\tSE3_2_pySO3(rootFrame, pyR);\r\n\r\n\tls.insert(0, bp::make_tuple(pyV, pyR));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getDOFVelocitiesLocal()\r\n{\r\n\tndarray rootGenVel = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));\r\n\t\r\n\t//rootGenVel.slice(0,3) = getJointVelocityGlobal(0);\r\n\t//rootGenVel.slice(3,6) = getJointAngVelocityGlobal(0);\r\n\trootGenVel.slice(0,3) = getJointVelocityLocal(0);\r\n\trootGenVel.slice(3,6) = getJointAngVelocityLocal(0);\r\n\r\n\tbp::list ls = getInternalJointAngVelocitiesLocal();\r\n\r\n\tls.insert(0, rootGenVel);\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getDOFAccelerationsLocal()\r\n{\r\n\tndarray rootGenAcc = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));\r\n\t\r\n\t//rootGenAcc.slice(0,3) = getJointAccelerationGlobal(0);\r\n\t//rootGenAcc.slice(3,6) = getJointAngAccelerationGlobal(0);\r\n\trootGenAcc.slice(0,3) = getJointAccelerationLocal(0);\r\n\trootGenAcc.slice(3,6) = getJointAngAccelerationLocal(0);\r\n\r\n\tbp::list ls = getInternalJointAngAccelerationsLocal();\r\n\r\n\tls.insert(0, rootGenAcc);\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getDOFAxesesLocal()\r\n{\r\n\tndarray rootAxeses = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.),\r\n\t\t\t\t\t\t\t\t\t\tbp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\r\n\t//ndarray rootAxesTmp = (ndarray)getJointOrientationGlobal(0);\r\n\tndarray rootAxesTmp = np::array(getJointOrientationGlobal(0));\r\n\tndarray rootAxes = transpose_pySO3(rootAxesTmp);\r\n\trootAxeses[0] = rootAxes[0];\r\n\trootAxeses[1] = rootAxes[1];\r\n\trootAxeses[2] = rootAxes[2];\r\n\trootAxeses[3] = rootAxes[0];\r\n\trootAxeses[4] = rootAxes[1];\r\n\trootAxeses[5] = rootAxes[2];\r\n\r\n\tbp::list ls = getInternalJointOrientationsGlobal();\r\n//\tbp::list ls = getInternalJointOrientationsLocal();\r\n\tfor(int i=0; i<len(ls); ++i)\r\n\t{\r\n\t\t//ndarray lsTmp = (ndarray)ls[i];\r\n\t\tndarray lsTmp = np::array(ls[i]);\r\n\t\tls[i] = transpose_pySO3(lsTmp);\r\n\t}\r\n\r\n\tls.insert(0, rootAxeses);\r\n\treturn ls;\r\n}\r\n\r\n\r\nbp::list VpControlModel::getBodyRootDOFVelocitiesLocal()\r\n{\r\n\tndarray rootGenVel = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));\r\n\r\n\trootGenVel.slice(0,3) = getBodyGenVelLocal(0).slice(3,6);\r\n\trootGenVel.slice(3,6) = getBodyGenVelLocal(0).slice(0,3);\r\n\r\n\tbp::list ls = getInternalJointAngVelocitiesLocal();\r\n\r\n\tls.insert(0, rootGenVel);\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getBodyRootDOFAccelerationsLocal()\r\n{\r\n\tndarray rootGenAcc = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));\r\n\r\n\trootGenAcc.slice(0,3) = getBodyGenAccLocal(0).slice(3,6);\r\n\trootGenAcc.slice(3,6) = getBodyGenAccLocal(0).slice(0,3);\r\n\r\n\tbp::list ls = getInternalJointAngAccelerationsLocal();\r\n\r\n\tls.insert(0, rootGenAcc);\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getBodyRootDOFAxeses()\r\n{\r\n\tndarray rootAxeses = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.),\r\n\t\t\t\t\t\t\t\t\t\tbp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\r\n\t//ndarray rootAxesTmp = (ndarray)getBodyOrientationGlobal(0);\r\n\tndarray rootAxesTmp = np::array(getBodyOrientationGlobal(0));\r\n\tndarray rootAxes = transpose_pySO3(rootAxesTmp);\r\n\trootAxeses[0] = rootAxes[0];\r\n\trootAxeses[1] = rootAxes[1];\r\n\trootAxeses[2] = rootAxes[2];\r\n\trootAxeses[3] = rootAxes[0];\r\n\trootAxeses[4] = rootAxes[1];\r\n\trootAxeses[5] = rootAxes[2];\r\n\r\n\tbp::list ls = getInternalJointOrientationsGlobal();\r\n//\tbp::list ls = getInternalJointOrientationsLocal();\r\n\tfor(int i=0; i<len(ls); ++i)\r\n\t{\r\n\t\t//ndarray lsTmp = (ndarray)ls[i];\r\n\t\tndarray lsTmp = np::array(ls[i]);\r\n\t\tls[i] = transpose_pySO3(lsTmp);\r\n\t}\r\n\r\n\tls.insert(0, rootAxeses);\r\n\treturn ls;\r\n}\r\n\r\nvoid VpControlModel::setDOFVelocities( const bp::list& dofvels)\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\r\n    setJointVelocityGlobal(0, dofvels[0].slice(0,3));\r\n\tsetJointAngVelocityLocal(0, dofvels[0].slice(3,6));\r\n\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t{\r\n\t    if (_nodes[i]->dof == 3)\r\n            _nodes[i]->joint.SetVelocity(pyVec3_2_Vec3(dofvels[i]));\r\n    }\r\n}\r\n\r\n\r\nvoid VpControlModel::setDOFAccelerations( const bp::list& dofaccs)\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\r\n\tsetJointAccelerationGlobal(0, dofaccs[0].slice(0,3));\r\n\r\n//\tsetJointAngAccelerationGlobal(0, dofaccs[0].slice(3,6));\r\n\tsetJointAngAccelerationLocal(0, dofaccs[0].slice(3,6));\r\n\r\n\tsetInternalJointAngAccelerationsLocal( ((bp::list)dofaccs.slice(1,_)) );\r\n}\r\n\r\nvoid VpControlModel::setDOFTorques(const bp::list& dofTorque)\r\n{\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t{\r\n\t    //std::cout << _nodes[i]->name << std::endl;\r\n\t    //std::cout << pyVec3_2_Vec3(dofTorque[i-1]) << std::endl;\r\n\t\t_nodes[i]->joint.SetTorque(pyVec3_2_Vec3(dofTorque[i-1]));\r\n\t}\r\n}\r\n\r\nboost::python::object VpControlModel::getJointTransform( int index )\r\n{\r\n\tndarray pyT = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.),\r\n\t                        bp::make_tuple(0.,1.,0.,0.),\r\n\t                        bp::make_tuple(0.,0.,1.,0.),\r\n\t                        bp::make_tuple(0.,0.,0.,1.)) );\r\n\r\n    if (index == 0)\r\n    {\r\n        SE3 bodyFrame = _nodes[index]->body.GetFrame();\r\n        SE3_2_pySE3(bodyFrame * Inv(_boneTs[index]), pyT);\r\n\t}\r\n\telse\r\n\t{\r\n        SE3_2_pySE3(_nodes[index]->joint.GetOrientation(), pyT);\r\n\t}\r\n\r\n\treturn pyT;\r\n}\r\n\r\nboost::python::object VpControlModel::getJointAfterTransformGlobal( int index )\r\n{\r\n\tndarray pyT = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.),\r\n\t                        bp::make_tuple(0.,1.,0.,0.),\r\n\t                        bp::make_tuple(0.,0.,1.,0.),\r\n\t                        bp::make_tuple(0.,0.,0.,1.)) );\r\n\r\n\tSE3 bodyFrame = _nodes[index]->body.GetFrame();\r\n\tSE3_2_pySE3(bodyFrame * Inv(_boneTs[index]), pyT);\r\n\r\n\treturn pyT;\r\n}\r\n\r\nboost::python::object VpControlModel::getJointOrientationLocal( int index )\r\n{\r\n\tndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\r\n\tif(index == 0)\r\n\t\treturn getJointOrientationGlobal(index);\r\n\telse\r\n\t{\r\n\t\tobject pyR = I.copy();\r\n\t\tif(_nodes[index]->dof == 3)\r\n\t\t{\r\n            SE3_2_pySO3(_nodes[index]->joint.GetOrientation(), pyR);\r\n\t\t}\r\n\t\telse if(_nodes[index]->dof == 1)\r\n\t\t{\r\n\t\t    SE3_2_pySO3(Exp(_nodes[index]->joint_revolute.GetAngle() * Vec3_2_Axis(_nodes[index]->joint_revolute.GetAxis())), pyR);\r\n\t\t}\r\n\t\treturn pyR;\r\n\t}\r\n}\r\n\r\nboost::python::object VpControlModel::getJointAngVelocityLocal( int index )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tif(index == 0)\r\n\t{\r\n\t\tse3 genVelBodyLocal, genVelJointLocal;\r\n\r\n\t\tgenVelBodyLocal = _nodes[index]->body.GetGenVelocityLocal();\r\n\t\tgenVelJointLocal = InvAd(Inv(_boneTs[index]), genVelBodyLocal);\r\n//\t\tgenVelJointLocal = Ad(_boneTs[index], genVelBodyLocal);\t// \ufffd\ufffd \ufffd\ufffd\ufffd\u03b0\ufffd \ufffd\ufffd\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd\r\n\t\tpyV[0] = genVelJointLocal[0];\r\n\t\tpyV[1] = genVelJointLocal[1];\r\n\t\tpyV[2] = genVelJointLocal[2]; \r\n\t}\r\n\telse\r\n\t{\r\n\t    if( _nodes[index]->dof == 3)\r\n\t    {\r\n            Vec3_2_pyVec3(_nodes[index]->joint.GetVelocity(), pyV);\r\n\t\t}\r\n\t    if( _nodes[index]->dof == 1)\r\n\t    {\r\n            Vec3_2_pyVec3(_nodes[index]->joint_revolute.GetVelocity() * _nodes[index]->joint_revolute.GetAxis(), pyV);\r\n\t    }\r\n    }\r\n\t\r\n\treturn pyV;\r\n}\r\n\r\nboost::python::object VpControlModel::getJointAngAccelerationLocal( int index )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tif(index == 0)\r\n\t{\r\n\t\tse3 genAccBodyLocal, genAccJointLocal;\r\n\r\n\t\tgenAccBodyLocal = _nodes[index]->body.GetGenAccelerationLocal();\r\n\t\tgenAccJointLocal = InvAd(Inv(_boneTs[index]), genAccBodyLocal);\r\n\t\tpyV[0] = genAccJointLocal[0]; \r\n\t\tpyV[1] = genAccJointLocal[1];\r\n\t\tpyV[2] = genAccJointLocal[2]; \r\n\t}\r\n\telse\r\n\t\tVec3_2_pyVec3(_nodes[index]->joint.GetAcceleration(), pyV);\r\n\t\r\n\treturn pyV;\r\n}\r\n\r\n//object VpControlModel::getJointPositionGlobal( int index )\r\nobject VpControlModel::getJointPositionGlobal( int index, const object& positionLocal/*=object() */ )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tSE3 bodyFrame;\r\n\tobject pyV = O.copy();\r\n\tVec3 positionLocal_;\r\n\r\n\t// body frame\ufffd\ufffd Inv(boneT)\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd joint \ufffd\ufffd\u0121 \u00e3\ufffd\u00b4\ufffd.\r\n\tbodyFrame = _nodes[index]->body.GetFrame();\r\n\r\n\tif(positionLocal.is_none())\r\n        Vec3_2_pyVec3((bodyFrame * Inv(_boneTs[index])).GetPosition(), pyV);\r\n\telse\r\n\t{\r\n\t\tpyVec3_2_Vec3(positionLocal, positionLocal_);\r\n        Vec3_2_pyVec3((bodyFrame * Inv(_boneTs[index])) * positionLocal_, pyV);\r\n\t}\r\n\treturn pyV;\r\n\r\n//\tif(!_nodes[index])\t// \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd \ufffd\ufffd\ufffd parent joint frame\ufffd\ufffd \u00e3\ufffd\ufffd offset\ufffd\ufffd\u016d transformation \ufffd\ufffd\u0172\ufffd\ufffd.\r\n//\t{\r\n//\t\tstatic SE3 parentJointFrame;\r\n//\t\tstatic Vec3 offset;\r\n////\t\tint parent = XI(_skeleton.attr(\"getParentIndex\")(index));\r\n//\t\tint parent = XI(_skeleton.attr(\"getParentJointIndex\")(index));\r\n//\t\tparentJointFrame = _nodes[parent]->body.GetFrame() * Inv(_boneTs[parent]);\r\n//\t\toffset = pyVec3_2_Vec3(_skeleton.attr(\"getOffset\")(index));\r\n//\t\tVec3_2_pyVec3(parentJointFrame * offset, pyV);\r\n//\t}\r\n//\telse\t// \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd \ufffd\u01b4\ufffd \ufffd\ufffd\ufffd body frame\ufffd\ufffd Inv(boneT)\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd joint \ufffd\ufffd\u0121 \u00e3\ufffd\u00b4\ufffd.\r\n//\t{\r\n//\t\tstatic SE3 bodyFrame;\r\n//\t\tbodyFrame = _nodes[index]->body.GetFrame();\r\n//\t\tVec3_2_pyVec3((bodyFrame * Inv(_boneTs[index])).GetPosition(), pyV);\r\n//\t}\r\n//\treturn pyV;\r\n}\r\nobject VpControlModel::getJointVelocityGlobal( int index )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tVec3_2_pyVec3(getBodyVelocityGlobal(index, Inv(_boneTs[index]).GetPosition()), pyV);\r\n\treturn pyV;\r\n}\r\n\r\nobject VpControlModel::getJointAccelerationGlobal( int index )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\tVec3 pospos = Inv(_boneTs[index]).GetPosition();\r\n\r\n\tVec3_2_pyVec3(getBodyAccelerationGlobal(index, &(pospos)), pyV);\r\n\treturn pyV;\r\n}\r\n\r\nboost::python::object VpControlModel::getJointOrientationGlobal( int index )\r\n{\r\n\tndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );\r\n\tSE3 bodyFrame;\r\n\tobject pyR = I.copy();\r\n\r\n\t// body frame\ufffd\ufffd Inv(boneT)\ufffd\ufffd \ufffd\ufffd\ufffd\ufffd joint frame \ufffd\ufffd\ufffd\u0474\ufffd\r\n\tbodyFrame = _nodes[index]->body.GetFrame();\r\n\tSE3_2_pySO3(bodyFrame * Inv(_boneTs[index]), pyR);\r\n\treturn pyR;\r\n}\r\n\r\nboost::python::object VpControlModel::getJointAngVelocityGlobal( int index )\r\n{\r\n\treturn getBodyAngVelocityGlobal(index);\r\n\r\n//\tstatic ndarray O(bp::make_tuple(0.,0.,0.));\r\n//\tstatic Vec3 angVel, parentAngVel;\r\n//\tobject pyV = O.copy();\r\n//\r\n//\tangVel = _nodes[index]->body.GetAngVelocity();\r\n//\r\n//\tint parentIndex = getParentIndex(index);\r\n//\tif(parentIndex==-1)\r\n//\t\tparentAngVel = Vec3(0.,0.,0.);\r\n//\telse\r\n//\t\tparentAngVel = _nodes[parentIndex]->body.GetAngVelocity();\r\n//\r\n//\tVec3_2_pyVec3(angVel - parentAngVel, pyV);\r\n//\treturn pyV;\r\n}\r\n\r\nboost::python::object VpControlModel::getJointAngAccelerationGlobal( int index )\r\n{\r\n\treturn getBodyAngAccelerationGlobal(index);\r\n}\r\n\r\nboost::python::object VpControlModel::getJointFrame( int index )\r\n{\r\n\tndarray frame = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.), bp::make_tuple(0.,1.,0.,0.), bp::make_tuple(0.,0.,1.,0.), bp::make_tuple(0.,0.,0.,1.)) );\r\n\r\n\tSE3 T = _nodes[index]->body.GetFrame() * Inv(_boneTs[index]);\r\n\tSE3_2_pySE3(T, frame);\r\n\treturn frame;\r\n}\r\n\r\nobject VpControlModel::getJointVelocityLocal( int index )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\tSE3 jointFrame = _nodes[index]->body.GetFrame() * Inv(_boneTs[index]);\r\n\r\n\tVec3_2_pyVec3(InvRotate(jointFrame, getBodyVelocityGlobal(index, Inv(_boneTs[index]).GetPosition())), pyV);\r\n\treturn pyV;\r\n}\r\n\r\nobject VpControlModel::getJointAccelerationLocal( int index )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\tVec3 pospos = Inv(_boneTs[index]).GetPosition();\r\n\tSE3 jointFrame = _nodes[index]->body.GetFrame() * Inv(_boneTs[index]);\r\n\r\n\tVec3_2_pyVec3(InvRotate(jointFrame, getBodyAccelerationGlobal(index, &(pospos))), pyV);\r\n\treturn pyV;\r\n}\r\n\r\n\r\nbp::list VpControlModel::getJointOrientationsLocal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointOrientationLocal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getJointAngVelocitiesLocal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointAngVelocityLocal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getJointAngAccelerationsLocal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointAngAccelerationLocal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getJointPositionsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointPositionGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getJointVelocitiesGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointVelocityGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getJointAccelerationsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointAccelerationGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getJointOrientationsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointOrientationGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getJointAngVelocitiesGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointAngVelocityGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getJointAngAccelerationsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointAngAccelerationGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getInternalJointOrientationsLocal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointOrientationLocal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getInternalJointAngVelocitiesLocal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointAngVelocityLocal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getInternalJointAngAccelerationsLocal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointAngAccelerationLocal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getInternalJointPositionsGlobal()\r\n{\r\n\tbp::list ls;\r\n//\tfor(int i=1; i<_jointElementIndexes.size(); ++i)\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointPositionGlobal(i));\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getInternalJointOrientationsGlobal()\r\n{\r\n\tbp::list ls;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointOrientationGlobal(i));\r\n\treturn ls;\r\n}\r\nvoid VpControlModel::setJointAngVelocityLocal( int index, const object& angvel )\r\n{\r\n\tif(index == 0)\r\n\t{\r\n\t\tse3 genVelBodyLocal, genVelJointLocal;\r\n\r\n\t\tgenVelBodyLocal = _nodes[index]->body.GetGenVelocityLocal();\r\n\r\n\t\tgenVelJointLocal = InvAd(Inv(_boneTs[index]), genVelBodyLocal);\r\n\t\tgenVelJointLocal[0] = XD(angvel[0]);\r\n\t\tgenVelJointLocal[1] = XD(angvel[1]);\r\n\t\tgenVelJointLocal[2] = XD(angvel[2]);\r\n\r\n\t\tgenVelBodyLocal = Ad(Inv(_boneTs[index]), genVelJointLocal);;\r\n\t\t_nodes[index]->body.SetGenVelocityLocal(genVelBodyLocal);\r\n\t}\r\n\telse\r\n\t\t_nodes[index]->joint.SetVelocity(pyVec3_2_Vec3(angvel));\r\n}\r\n\r\nvoid VpControlModel::setJointAngAccelerationLocal( int index, const object& angacc )\r\n{\r\n\tif(index == 0)\r\n\t{\r\n\t\tse3 genAccBodyLocal, genAccJointLocal;\r\n\r\n\t\tgenAccBodyLocal = _nodes[index]->body.GetGenAccelerationLocal();\r\n\r\n\t\tgenAccJointLocal = InvAd(Inv(_boneTs[index]), genAccBodyLocal);\r\n\t\tgenAccJointLocal[0] = XD(angacc[0]);\r\n\t\tgenAccJointLocal[1] = XD(angacc[1]);\r\n\t\tgenAccJointLocal[2] = XD(angacc[2]);\r\n\r\n\t\tgenAccBodyLocal = Ad(Inv(_boneTs[index]), genAccJointLocal);;\r\n\t\t_nodes[index]->body.SetGenAccelerationLocal(genAccBodyLocal);\r\n\t}\r\n\telse\r\n\t\t_nodes[index]->joint.SetAcceleration(pyVec3_2_Vec3(angacc));\r\n}\r\n\r\nvoid VpControlModel::setJointVelocityGlobal( int index, const object& vel )\r\n{\r\n\tif(index == 0)\r\n\t{\r\n\t\tVec3 pospos = Inv(_boneTs[index]).GetPosition();\r\n\t\tsetBodyVelocityGlobal(index, pyVec3_2_Vec3(vel), &(pospos));\r\n\t}\r\n\telse\r\n\t\tcout << \"setJointAccelerationGlobal() : not completely implemented\" << endl;\r\n}\r\n\r\nvoid VpControlModel::setJointAccelerationGlobal( int index, const object& acc )\r\n{\r\n\tif(index == 0)\r\n\t{\r\n\t\tVec3 pospos = Inv(_boneTs[index]).GetPosition();\r\n\t\tsetBodyAccelerationGlobal(index, pyVec3_2_Vec3(acc), &(pospos));\r\n\t}\r\n\telse\r\n\t\tcout << \"setJointAccelerationGlobal() : not completely implemented\" << endl;\r\n}\r\n\r\nvoid VpControlModel::setJointAngAccelerationGlobal( int index, const object& angacc )\r\n{\r\n\tsetBodyAngAccelerationGlobal(index, angacc);\r\n}\r\n\r\nvoid VpControlModel::setJointAngAccelerationsLocal( const bp::list& angaccs )\r\n{\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\tsetJointAngAccelerationLocal(i, angaccs[i]);\r\n}\r\n\r\nvoid VpControlModel::setInternalJointAngAccelerationsLocal( const bp::list& angaccs )\r\n{\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t{\r\n\t    if (_nodes[i]->dof == 3)\r\n            _nodes[i]->joint.SetAcceleration(pyVec3_2_Vec3(angaccs[i-1]));\r\n        else if(_nodes[i]->dof == 1)\r\n            _nodes[i]->joint_revolute.SetAcceleration(XD(angaccs[i-1][0]));\r\n    }\r\n}\r\n\r\nvoid VpControlModel::SetJointElasticity(int index, scalar Kx, scalar Ky, scalar Kz)\r\n{\r\n    assert(Kx < 0. && \"Joint Elasticity must larger than 0\");\r\n    if(Ky < 0.)\r\n    {\r\n        SpatialSpring k(Kx);\r\n        _nodes[index]->joint.SetElasticity(k);\r\n    }\r\n    else\r\n    {\r\n        SpatialSpring k(0., Kx, Ky, Kz);\r\n        _nodes[index]->joint.SetElasticity(k);\r\n    }\r\n}\r\nvoid VpControlModel::SetJointsElasticity(scalar Kx, scalar Ky, scalar Kz)\r\n{\r\n    for (std::vector<int>::size_type i=1; i<_nodes.size(); i++)\r\n        SetJointElasticity(i, Kx, Ky, Kz);\r\n}\r\n\r\nvoid VpControlModel::SetJointDamping(int index, scalar Dx, scalar Dy, scalar Dz)\r\n{\r\n    assert(Dx < 0. && \"Joint Damping must larger than 0\");\r\n\r\n    if(Dy < 0.)\r\n    {\r\n        SpatialDamper d(Dx);\r\n        _nodes[index]->joint.SetDamping(d);\r\n    }\r\n    else\r\n    {\r\n        SpatialDamper d(0., Dx, Dy, Dz);\r\n        _nodes[index]->joint.SetDamping(d);\r\n    }\r\n}\r\n\r\nvoid VpControlModel::SetJointsDamping(scalar Dx, scalar Dy, scalar Dz)\r\n{\r\n    for (std::vector<int>::size_type i=1; i<_nodes.size(); i++)\r\n        SetJointDamping(i, Dx, Dy, Dz);\r\n}\r\n\r\n\r\nboost::python::object VpControlModel::getJointTorqueLocal( int index )\r\n{\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tif(index==0) return pyV;\r\n\r\n\tVec3_2_pyVec3(_nodes[index]->joint.GetTorque(), pyV);\r\n\treturn pyV;\r\n}\r\n\r\nbp::list VpControlModel::getInternalJointTorquesLocal()\r\n{\r\n\tbp::list ls;\r\n//\tfor(int i=1; i<_jointElementIndexes.size(); ++i)\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\tls.append(getJointTorqueLocal(i));\r\n\treturn ls;\r\n}\r\n\r\nvoid VpControlModel::setJointTorqueLocal( int index, const object& torque )\r\n{\r\n//\tint index = _jointElementIndexes[jointIndex];\r\n    if(_nodes[index]->dof == 3)\r\n        _nodes[index]->joint.SetTorque(pyVec3_2_Vec3(torque));\r\n}\r\n\r\nvoid VpControlModel::setInternalJointTorquesLocal( const bp::list& torques )\r\n{\r\n//\tint index;\r\n//\tfor(int i=1; i<_jointElementIndexes.size(); ++i)\r\n//\t{\r\n//\t\tindex = _jointElementIndexes[i];\r\n//\t\t_nodes[index]->joint.SetTorque(pyVec3_2_Vec3(torques[i]));\r\n//\t}\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t\t_nodes[i]->joint.SetTorque(pyVec3_2_Vec3(torques[i-1]));\r\n}\r\n\r\n\r\nvoid VpControlModel::applyBodyGenForceGlobal( int index, const object& torque, const object& force, const object& positionLocal/*=object()*/ )\r\n{\r\n\tVec3 zero(0,0,0);\r\n\tif(positionLocal.is_none())\r\n\t\t_nodes[index]->body.ApplyGlobalForce(dse3(XD(torque[0]), XD(torque[1]), XD(torque[2]), XD(force[0]), XD(force[1]), XD(force[2])), zero);\r\n\telse\r\n\t\t_nodes[index]->body.ApplyGlobalForce(dse3(XD(torque[0]), XD(torque[1]), XD(torque[2]), XD(force[0]), XD(force[1]), XD(force[2])), pyVec3_2_Vec3(positionLocal));\r\n}\r\n\r\nvoid VpControlModel::applyBodyForceGlobal( int index, const object& force, const object& positionLocal/*=object()*/ )\r\n{\r\n\tVec3 zero(0,0,0);\r\n\tif(positionLocal.is_none())\r\n\t\t_nodes[index]->body.ApplyGlobalForce(dse3(0.,0.,0., XD(force[0]), XD(force[1]), XD(force[2])), zero);\r\n\telse\r\n\t\t_nodes[index]->body.ApplyGlobalForce(dse3(0.,0.,0., XD(force[0]), XD(force[1]), XD(force[2])), pyVec3_2_Vec3(positionLocal));\r\n}\r\n\r\nvoid VpControlModel::applyBodyTorqueGlobal( int index, const object& torque )\r\n{\r\n\tVec3 zero(0,0,0);\r\n\t_nodes[index]->body.ApplyGlobalForce(dse3(XD(torque[0]), XD(torque[1]), XD(torque[2]), 0.,0.,0.), zero);\r\n}\r\n\r\nobject VpControlModel::getBodyForceLocal( int index )\r\n{\r\n\tdse3 genForce;\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tgenForce = _nodes[index]->body.GetForce();\r\n\tpyV[0] = genForce[3];\r\n\tpyV[1] = genForce[4];\r\n\tpyV[2] = genForce[5];\r\n\treturn pyV;\r\n\r\n}\r\n\r\nobject VpControlModel::getBodyNetForceLocal( int index )\r\n{\r\n\tdse3 genForce;\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tgenForce = _nodes[index]->body.GetNetForce();\r\n\tpyV[0] = genForce[3];\r\n\tpyV[1] = genForce[4];\r\n\tpyV[2] = genForce[5];\r\n\treturn pyV;\r\n}\r\n\r\nobject VpControlModel::getBodyGravityForceLocal( int index )\r\n{\r\n\tdse3 genForce;\r\n\tndarray O = np::array(bp::make_tuple(0.,0.,0.));\r\n\tobject pyV = O.copy();\r\n\r\n\tgenForce = _nodes[index]->body.GetGravityForce();\r\n\tpyV[0] = genForce[3];\r\n\tpyV[1] = genForce[4];\r\n\tpyV[2] = genForce[5];\r\n\treturn pyV;\r\n}\r\n\r\nstatic ublas::vector<double> ToUblasVector(const Vec3 &v_vp)\r\n{\r\n    ublas::vector<double> v(3);\r\n    for(int i=0; i<3; i++)\r\n        v(i) = v_vp[i];\r\n    return v;\r\n}\r\n\r\nstatic ublas::vector<double> ToUblasVector(const Axis &v_vp)\r\n{\r\n    ublas::vector<double> v(3);\r\n    for(int i=0; i<3; i++)\r\n        v(i) = v_vp[i];\r\n    return v;\r\n}\r\n\r\nstatic ublas::matrix<double> ToUblasMatrix(const Vec3 &v_vp)\r\n{\r\n    ublas::matrix<double> m(3, 1);\r\n    for(int i=0; i<3; i++)\r\n        m(i, 0) = v_vp[i];\r\n    return m;\r\n}\r\n\r\nstatic ublas::matrix<double> ToUblasMatrix(const Axis &v_vp)\r\n{\r\n    ublas::matrix<double> m(3, 1);\r\n    for(int i=0; i<3; i++)\r\n        m(i, 0) = v_vp[i];\r\n    return m;\r\n}\r\n\r\nstatic ublas::matrix<double> SE3ToUblasRotate(const SE3 &T_vp)\r\n{\r\n    ublas::matrix<double> T(3, 3);\r\n    for(int i=0; i<3; i++)\r\n        for(int j=0; j<3; j++)\r\n            T(j, i) = T_vp[i*3 + j];\r\n    return T;\r\n}\r\n\r\nstatic ublas::vector<double> cross(const ublas::vector<double> &v1, const ublas::vector<double> &v2)\r\n{\r\n    ublas::vector<double> v(3);\r\n    v(0) = v1(1)*v2(2) - v1(2) * v2(1);\r\n    v(1) = v1(2)*v2(0) - v1(0) * v2(2);\r\n    v(2) = v1(0)*v2(1) - v1(1) * v2(0);\r\n    return v;\r\n}\r\n\r\nstatic ublas::matrix<double> GetCrossMatrix(const ublas::vector<double> &r)\r\n{\r\n    ublas::matrix<double> R(3, 3);\r\n    R(0, 0) = 0;\r\n    R(1, 0) = r[2];\r\n    R(2, 0) = -r[1];\r\n    R(0, 1) = -r[2];\r\n    R(1, 1) = 0;\r\n    R(2, 1) = r[0];\r\n    R(0, 2) = r[1];\r\n    R(1, 2) = -r[0];\r\n    R(2, 2) = 0;\r\n\r\n    return R;\r\n}\r\n\r\nAxis GetBJointDq(const Axis &m_rQ, const Vec3 &V)\r\n{\r\n\tAxis W(V[0], V[1], V[2]);\r\n\tscalar t = Norm(m_rQ), delta, zeta, t2 = t * t;\r\n\r\n\tif ( t < BJOINT_EPS )\r\n\t{\r\n\t\tdelta  = SCALAR_1_12 + SCALAR_1_720 * t2;\r\n\t\tzeta = SCALAR_1 - SCALAR_1_12 * t2;\r\n\t} else\r\n\t{\r\n\t\tzeta = SCALAR_1_2 * t * (SCALAR_1 + cos(t)) / sin(t);\r\n\t\tdelta = (SCALAR_1 - zeta) / t2;\r\n\t}\r\n\r\n\treturn (delta * Inner(m_rQ, V)) * m_rQ + zeta * W + SCALAR_1_2 * Cross(m_rQ, W);\r\n}\r\n\r\nstatic ublas::matrix<double> GetBJointJacobian(const Axis &m_rQ)\r\n{\r\n    ublas::matrix<double> J(3, 3);\r\n\tublas::vector<double> m_rQ_ub = ToUblasVector(m_rQ);\r\n\r\n\tscalar t = Norm(m_rQ), alpha, beta, gamma, t2 = t * t;\r\n\r\n    if ( t < BJOINT_EPS )\r\n\t{\r\n\t\talpha = SCALAR_1_6 - SCALAR_1_120 * t2;\r\n\t\tbeta = SCALAR_1 - SCALAR_1_6 * t2;\r\n\t\tgamma = SCALAR_1_2 - SCALAR_1_24 * t2;\r\n\t} else\r\n\t{\r\n\t\tbeta = sin(t) / t;\r\n\t\talpha = (SCALAR_1 - beta) / t2;\r\n\t\tgamma = (SCALAR_1 - cos(t)) / t2;\r\n\t}\r\n\r\n//\tAxis V = (alpha * Inner(m_rQ, m_rDq)) * m_rQ + beta * m_rDq + gamma * Cross(m_rDq, m_rQ);\r\n\r\n    J = alpha * outer_prod(m_rQ_ub, m_rQ_ub) + beta * ublas::identity_matrix<double>(3) - gamma * GetCrossMatrix(m_rQ_ub);\r\n\r\n//    J(0, 0) = alpha * m_rQ[0] * m_rQ[0] + beta;\r\n//    J(1, 0) = alpha * m_rQ[1] * m_rQ[0] - gamma * m_rQ[2];\r\n//    J(2, 0) = alpha * m_rQ[2] * m_rQ[0] + gamma * m_rQ[1];\r\n//    J(0, 1) = alpha * m_rQ[0] * m_rQ[1] + gamma * m_rQ[2];\r\n//    J(1, 1) = alpha * m_rQ[1] * m_rQ[1] + beta;\r\n//    J(2, 1) = alpha * m_rQ[2] * m_rQ[1] - gamma * m_rQ[0];\r\n//    J(0, 2) = alpha * m_rQ[0] * m_rQ[2] - gamma * m_rQ[1];\r\n//    J(1, 2) = alpha * m_rQ[1] * m_rQ[2] + gamma * m_rQ[0];\r\n//    J(2, 2) = alpha * m_rQ[2] * m_rQ[2] + beta;\r\n\r\n//    return alpha * mm.getDyadMatrixForm(q) + beta * np.eye(3) - gamma * mm.getCrossMatrixForm(q)\r\n    return J;\r\n}\r\n\r\nstatic Axis GetBJointJDQ(const Axis &m_rQ, const Axis &m_rDq)\r\n{\r\n    ublas::vector<double> JDQ(3);\r\n\tublas::vector<double> m_rQ_ub = ToUblasVector(m_rQ);\r\n\r\n\tscalar t = Norm(m_rQ), alpha, beta, gamma, t2 = t * t;\r\n\r\n    if ( t < BJOINT_EPS )\r\n\t{\r\n\t\talpha = SCALAR_1_6 - SCALAR_1_120 * t2;\r\n\t\tbeta = SCALAR_1 - SCALAR_1_6 * t2;\r\n\t\tgamma = SCALAR_1_2 - SCALAR_1_24 * t2;\r\n\t} else\r\n\t{\r\n\t\tbeta = sin(t) / t;\r\n\t\talpha = (SCALAR_1 - beta) / t2;\r\n\t\tgamma = (SCALAR_1 - cos(t)) / t2;\r\n\t}\r\n\r\n\tAxis V = (alpha * Inner(m_rQ, m_rDq)) * m_rQ + beta * m_rDq + gamma * Cross(m_rDq, m_rQ);\r\n\tJDQ(0) = V[0];\r\n\tJDQ(1) = V[1];\r\n\tJDQ(2) = V[2];\r\n\r\n\treturn V;\r\n}\r\n\r\nstatic Axis GetBJointDJDQ(const Axis &m_rQ, const Axis &m_rDq)\r\n{\r\n\tublas::vector<double> DJDQ(3);\r\n\tublas::vector<double> m_rQ_ub = ToUblasVector(m_rQ);\r\n\tscalar t = Norm(m_rQ), alpha, beta, gamma, d_alpha, d_beta, d_gamma, q_dq = Inner(m_rQ, m_rDq), t2 = t * t;\r\n    if ( t < BJOINT_EPS )\r\n\t{\r\n\t\talpha = SCALAR_1_6 - SCALAR_1_120 * t2;\r\n\t\tbeta = SCALAR_1 - SCALAR_1_6 * t2;\r\n\t\tgamma = SCALAR_1_2 - SCALAR_1_24 * t2;\r\n\r\n\t\td_alpha = (SCALAR_1_1260 * t2 - SCALAR_1_60) * q_dq;\r\n\t\td_beta = (SCALAR_1_30 * t2 - SCALAR_1_3) * q_dq;\r\n\t\td_gamma = (SCALAR_1_180 * t2 - SCALAR_1_12) * q_dq;\r\n\t} else\r\n\t{\r\n\t\tbeta = sin(t) / t;\r\n\t\talpha = (SCALAR_1 - beta) / t2;\r\n\t\tgamma = (SCALAR_1 - cos(t)) / t2;\r\n\r\n\t\td_alpha = (gamma - SCALAR_3 * alpha) / t2 * q_dq;\r\n\t\td_beta = (alpha - gamma) * q_dq;\r\n\t\td_gamma = (beta - SCALAR_2 * gamma) / t2 * q_dq;\r\n\t}\r\n\r\n    Axis dJdq = (d_alpha * q_dq + alpha * SquareSum(m_rDq)) * m_rQ\r\n        + (alpha*q_dq + d_beta) * m_rDq\r\n        + Cross(d_gamma*m_rDq, m_rQ);\r\n    DJDQ(0) = dJdq[0];\r\n    DJDQ(1) = dJdq[1];\r\n    DJDQ(2) = dJdq[2];\r\n\r\n    return dJdq;\r\n}\r\n\r\nstatic object ToNumpyArray(const ublas::matrix<double> &m)\r\n{\r\n\tbp::tuple shape = bp::make_tuple(m.size1(), m.size2());\r\n    np::dtype dtype = np::dtype::get_builtin<float>();\r\n\tndarray m_np = np::empty(shape, dtype);\r\n\tfor(ublas::matrix<double>::size_type i=0; i<m.size1(); i++)\r\n\t{\r\n\t    for(ublas::matrix<double>::size_type j=0; j<m.size2(); j++)\r\n\t    {\r\n\t        m_np[i][j] = m(i, j);\r\n\t    }\r\n    }\r\n\treturn m_np;\r\n}\r\n\r\nobject VpControlModel::getLocalJacobian(int index)\r\n{\r\n    return ToNumpyArray(GetBJointJacobian(_nodes[index]->joint.GetDisplacement()));\r\n}\r\n\r\nobject VpControlModel::getLocalJointVelocity(int index)\r\n{\r\n    return Vec3_2_pyVec3(_nodes[index]->joint.GetVelocity());\r\n}\r\n\r\nobject VpControlModel::getLocalJointDisplacementDerivatives(int index)\r\n{\r\n    Axis vec = _nodes[index]->joint.GetDisplacementDerivate();\r\n    return Vec3_2_pyVec3(Vec3(vec[0], vec[1], vec[2]));\r\n}\r\n\r\nobject VpControlModel::computeJacobian(int index, const object& positionGlobal)\r\n{\r\n    //TODO:\r\n\tVec3 effector_position = pyVec3_2_Vec3(positionGlobal);\r\n\tvpBJoint *joint;\r\n\tSE3 joint_frame;\r\n\r\n\tbp::tuple shape = bp::make_tuple(6, m_total_dof);\r\n    np::dtype dtype = np::dtype::get_builtin<float>();\r\n\tndarray J = np::zeros(shape, dtype);\r\n\tublas::vector<double> offset;\r\n\tublas::matrix<double> _Jw, _Jv;\r\n\r\n\t//root joint\r\n\tJ[0][3] = 1.;\r\n\tJ[1][4] = 1.;\r\n\tJ[2][5] = 1.;\r\n\r\n    joint_frame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);\r\n    offset = ToUblasVector(effector_position - joint_frame.GetPosition());\r\n    _Jw = prod(SE3ToUblasRotate(joint_frame), GetBJointJacobian(LogR(joint_frame)));\r\n    _Jv = -prod(GetCrossMatrix(offset), _Jw);\r\n    for (int dof_index = 0; dof_index < 3; dof_index++)\r\n    {\r\n        for (int j=0; j<3; j++)\r\n        {\r\n            J[j+0][dof_index] = _Jv(j, dof_index);\r\n            J[j+3][dof_index] = _Jw(j, dof_index);\r\n        }\r\n    }\r\n\r\n    //internal joint\r\n    std::vector<int> &ancestors = _nodes[index]->ancestors;\r\n    int dof_start_index = 0;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size();i++)\r\n\t{\r\n\t    if(std::find(ancestors.begin(), ancestors.end(), i) != ancestors.end())\r\n\t    {\r\n            joint = &(_nodes[i]->joint);\r\n            joint_frame = _nodes[i]->body.GetFrame() * Inv(_boneTs[i]);\r\n            offset = ToUblasVector(effector_position - joint_frame.GetPosition());\r\n            _Jw = prod(SE3ToUblasRotate(joint_frame), GetBJointJacobian(joint->GetDisplacement()));\r\n            _Jv = -prod(GetCrossMatrix(offset), _Jw);\r\n\r\n            dof_start_index = _nodes[i]->dof_start_index;\r\n            for (int dof_index = 0; dof_index < _nodes[i]->dof; dof_index++)\r\n            {\r\n                for (int j=0; j<3; j++)\r\n                {\r\n                    J[j+0][dof_start_index + dof_index] = _Jv(j, dof_index);\r\n                    J[j+3][dof_start_index + dof_index] = _Jw(j, dof_index);\r\n                }\r\n            }\r\n        }\r\n\t}\r\n\r\n\treturn J;\r\n}\r\n\r\nbp::tuple VpControlModel::computeCom_J_dJdq()\r\n{\r\n    int body_num = this->getBodyNum();\r\n\r\n\tbp::tuple shape_J = bp::make_tuple(6*body_num, m_total_dof);\r\n\tbp::tuple shape_dJdq = bp::make_tuple(6*body_num);\r\n    np::dtype dtype = np::dtype::get_builtin<float>();\r\n\tndarray J = np::zeros(shape_J, dtype);\r\n\tndarray dJdq = np::zeros(shape_dJdq, dtype);\r\n\tublas::vector<double> offset, offset_velocity;\r\n\tublas::matrix<double> _Jw, _Jv;\r\n\tublas::vector<double> _dJdqw, _dJdqv;\r\n\r\n\t//preprocessing : get joint frames\r\n\tstd::vector<SE3> joint_frames;\r\n\tfor (std::vector<Node*>::size_type i=0; i < _nodes.size(); i++)\r\n\t    joint_frames.push_back(_nodes[i]->body.GetFrame() * Inv(_boneTs[i]));\r\n\r\n\t//root joint\r\n\t// jacobian\r\n\tVec3 effector_position, effector_velocity;\r\n    _Jw = SE3ToUblasRotate(joint_frames[0]);\r\n    for(std::vector<Node*>::size_type body_idx=0; body_idx < _nodes.size(); body_idx++)\r\n    {\r\n        effector_position = _nodes[body_idx]->get_body_position();\r\n        offset = ToUblasVector(effector_position - joint_frames[0].GetPosition());\r\n        _Jv = -prod(GetCrossMatrix(offset), _Jw);\r\n        for (int dof_index = 0; dof_index < 3; dof_index++)\r\n        {\r\n            J[6*body_idx + dof_index][dof_index] = 1.;\r\n            for (int j=0; j<3; j++)\r\n            {\r\n//                J[6*body_idx + 0 + j][3 + dof_index] = joint_frames[0][3*dof_index + j];\r\n                J[6*body_idx + 0 + j][3+dof_index] = _Jv(j, dof_index);\r\n                J[6*body_idx + 3 + j][3+dof_index] = _Jw(j, dof_index);\r\n            }\r\n        }\r\n    }\r\n\r\n    // jacobian derivative\r\n    Vec3 joint_global_pos = joint_frames[0].GetPosition();\r\n    Vec3 joint_global_velocity = _nodes[0]->body.GetLinVelocity(Inv(_boneTs[0]).GetPosition());\r\n    Vec3 joint_global_ang_vel = _nodes[0]->body.GetAngVelocity();\r\n\r\n    _dJdqw = ToUblasVector(Vec3(0.));\r\n    for(std::vector<Node*>::size_type body_idx=0; body_idx < _nodes.size(); body_idx++)\r\n    {\r\n        effector_position = _nodes[body_idx]->get_body_position();\r\n        offset = ToUblasVector(effector_position - joint_global_pos);\r\n        effector_velocity = _nodes[body_idx]->get_body_com_velocity();\r\n        offset_velocity = ToUblasVector(effector_velocity - joint_global_velocity);\r\n        _dJdqv = -cross(offset, _dJdqw) - cross(offset_velocity, ToUblasVector(joint_global_ang_vel));\r\n        for (int j=0; j<3; j++)\r\n        {\r\n            dJdq[6*body_idx + 0 + j] += _dJdqv(j);\r\n            dJdq[6*body_idx + 3 + j] += _dJdqw(j);\r\n        }\r\n    }\r\n\r\n    //internal joint\r\n    for(std::vector<Node*>::size_type i=1; i<_nodes.size(); i++)\r\n    {\r\n        int parent_joint_index = _nodes[i]->parent_index;\r\n        int dof_start_index = _nodes[i]->dof_start_index;\r\n        joint_global_pos = joint_frames[i].GetPosition();\r\n        joint_global_velocity = _nodes[i]->body.GetLinVelocity(Inv(_boneTs[i]).GetPosition());\r\n        joint_global_ang_vel = _nodes[i]->body.GetAngVelocity() - _nodes[parent_joint_index]->body.GetAngVelocity();\r\n\r\n        if (_nodes[i]->dof == 3)\r\n        {\r\n            _Jw = SE3ToUblasRotate(joint_frames[i]);\r\n            // joint_global_ang_vel = Rotate(joint_frames[i], _nodes[i]->joint.GetVelocity());\r\n        }\r\n        else if(_nodes[i]->dof == 1)\r\n        {\r\n            _Jw = prod(SE3ToUblasRotate(joint_frames[i]), ToUblasMatrix(_nodes[i]->joint_revolute.GetAxis()));\r\n            // joint_global_ang_vel = Rotate(joint_frames[i], _nodes[i]->joint_revolute.GetVelocity() * _nodes[i]->joint_revolute.GetAxis());\r\n        }\r\n\r\n        _dJdqw = ToUblasVector(Cross(_nodes[parent_joint_index]->body.GetAngVelocity(), joint_global_ang_vel));\r\n\r\n        for(std::vector<Node*>::size_type body_idx=1; body_idx < _nodes.size(); body_idx++)\r\n        {\r\n            std::vector<bool> &is_body_ancestors = _nodes[body_idx]->is_ancestor;\r\n            effector_position = _nodes[body_idx]->get_body_position();\r\n            effector_velocity = _nodes[body_idx]->get_body_com_velocity();\r\n            if(is_body_ancestors[i])\r\n            {\r\n                // jacobian\r\n                offset = ToUblasVector(effector_position - joint_global_pos);\r\n                _Jv = -prod(GetCrossMatrix(offset), _Jw);\r\n\r\n                dof_start_index = _nodes[i]->dof_start_index;\r\n                for (int dof_index = 0; dof_index < _nodes[i]->dof; dof_index++)\r\n                {\r\n                    for (int j=0; j<3; j++)\r\n                    {\r\n                        J[6*body_idx + 0+j][dof_start_index + dof_index] = _Jv(j, dof_index);\r\n                        J[6*body_idx + 3+j][dof_start_index + dof_index] = _Jw(j, dof_index);\r\n                    }\r\n                }\r\n\r\n                // jacobian derivatives\r\n                offset_velocity = ToUblasVector(effector_velocity - joint_global_velocity);\r\n                _dJdqv = -cross(offset, _dJdqw) - cross(offset_velocity, ToUblasVector(joint_global_ang_vel));\r\n                for (int j=0; j<3; j++)\r\n                {\r\n                    dJdq[6*body_idx + 0 + j] += _dJdqv(j);\r\n                    dJdq[6*body_idx + 3 + j] += _dJdqw(j);\r\n                }\r\n            }\r\n        }\r\n\t}\r\n\r\n\treturn bp::make_tuple(J, dJdq);\r\n}\r\n\r\n\r\n/////////////////////////////////////////\r\n// Additional\r\nvoid VpModel::addBody(bool flagControl)\r\n{\r\n\tint n = _nodes.size();\r\n\t_nodes.resize(n + 1);\r\n\t_boneTs.resize(n + 1);\r\n\t\t\r\n\t//add body\r\n\tNode* pNode = new Node(\"Left_Toes\");\r\n\tscalar density = 1000;\r\n\tscalar width = 0.1;\r\n\tscalar height = 0.1;\r\n\tscalar length = 0.1;\r\n\tpNode->body.AddGeometry(new vpBox(Vec3(width, height, length)));\r\n\tpNode->body.SetInertia(BoxInertia(density, Vec3(width / 2., height / 2., length / 2.)));\r\n\r\n\t//boneT = boneT * SE3(pyVec3_2_Vec3(cfgNode.attr(\"offset\")));\r\n\t//_boneTs[joint_index] = boneT;\r\n\tSE3 newT;// = T * boneT;\r\n\r\n\tpNode->body.SetFrame(newT);\r\n\t_nodes[n] = pNode;\r\n\r\n\t_boneTs[n] = newT;\r\n\t\r\n\tif (flagControl == true)\r\n\t\t_pWorld->AddBody(&pNode->body);\r\n\r\n\r\n\t//create new joint\r\n\tint parent_index = n - 1;\r\n\tSE3 invLocalT;\r\n\tNode* pParentNode = _nodes[parent_index];\r\n\r\n\tpParentNode->body.SetJoint(&pNode->joint, Inv(_boneTs[parent_index])*Inv(invLocalT));\r\n\tpNode->body.SetJoint(&pNode->joint, Inv(_boneTs[n]));\r\n\tpNode->use_joint = true;\r\n\r\n}\r\n\r\n int VpModel::vpid2index(int id)\r\n {\r\n \tint index = 0;\r\n \tfor (int i = 0; i < getBodyNum(); i++)\r\n \t{\r\n \t\tif (id == index2vpid(i))\r\n \t\t{\r\n \t\t\tindex = i;\r\n \t\t\tbreak;\r\n \t\t}\r\n \t}\r\n \treturn index;\r\n }\r\n\r\nvoid VpModel::SetBodyColor(int id, unsigned char r, unsigned char g, unsigned char b, unsigned char a)\r\n{\r\n\tint index = vpid2index(id);\r\n\tNode* pNode = _nodes[index];\r\n\tpNode->color[0] = r;\r\n\tpNode->color[1] = g;\r\n\tpNode->color[2] = b;\r\n\tpNode->color[3] = a;\r\n}\r\n\r\nvoid VpControlModel::setSpring(int body1Index, int body2Index, scalar elasticity, scalar damping, const object& p1, const object& p2, scalar initialDistance)\r\n{\r\n\tvpSpring* spring = new vpSpring;\r\n\tVec3 v1 = pyVec3_2_Vec3(p1);\r\n\tVec3 v2 = pyVec3_2_Vec3(p2);\r\n\tspring->Connect(&(_nodes[body1Index]->body), &(_nodes[body2Index]->body), v1, v2);\r\n\tspring->SetElasticity(elasticity);\r\n\tspring->SetDamping(damping);\r\n\tspring->SetInitialDistance(initialDistance);\r\n\t_springs.push_back(spring);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n// must be called at first:clear all torques and accelerations\r\nbp::list VpControlModel::getInverseEquationOfMotion(object &invM, object &invMb)\r\n{\r\n\tbp::list ls;\r\n\tls.append(_nodes.size());\r\n\r\n\r\n\t// M^-1 * tau - M^-1 * b = ddq\r\n\t// ddq^T = [rootjointLin^T rootjointAng^T joints^T]^T\r\n\t\r\n\t\r\n\t//vpBody *Hip = &(_nodes.at(0)->body);\r\n\t//Hip->ResetForce();\r\n\t//for(size_t i=0; i<_nodes.size(); i++)\r\n\t//{\r\n\t\t//_nodes.at(i)->body.ResetForce();\r\n\t\t//_nodes.at(i)->joint.SetTorque(Vec3(0,0,0));\r\n\t//}\r\n\t//Hip->GetSystem()->ForwardDynamics();\r\n\t//std::cout << Hip->GetGenAccelerationLocal();\r\n\t//for(size_t i=1; i<_nodes.size(); i++)\r\n\t//{\r\n\t\t//std::cout << _nodes[i]->joint.GetAcceleration();\r\n\t//}\r\n\r\n\r\n\r\n\tint n = _nodes.size()-1;\r\n\tint N = 6+3*n;\r\n\tdse3 zero_dse3(0.0);\r\n\tVec3 zero_Vec3(0.0);\r\n\r\n\tvpBody *Hip = &(_nodes.at(0)->body);\r\n\r\n\t//save current ddq and tau\r\n\tstd::vector<Vec3> accBackup;\r\n\tstd::vector<Vec3> torBackup;\r\n\tfor(int i=0; i<n; i++)\r\n\t{\r\n\t\tvpBJoint *joint = &(_nodes.at(i+1)->joint);\r\n\t\taccBackup.push_back(joint->GetAcceleration());\r\n\t\ttorBackup.push_back(joint->GetTorque());\r\n\t}\r\n\t// se3 hipAccBackup = Hip->GetGenAcceleration();\r\n\t// dse3 hipTorBackup = Hip->GetForce();\r\n\r\n\tHip->ResetForce();\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); i++)\r\n\t{\r\n\t\t_nodes.at(i)->body.ResetForce();\r\n\t\t_nodes.at(i)->joint.SetTorque(Vec3(0,0,0));\r\n\t}\r\n\r\n\t//get invMb\r\n\tHip->ApplyLocalForce(zero_dse3, zero_Vec3);\r\n\tfor(int i=0; i<n; i++)\r\n\t{\r\n\t\tvpBJoint *joint = &(_nodes.at(i+1)->joint);\r\n\t\tjoint->SetTorque(zero_Vec3);\r\n\t}\r\n\tHip->GetSystem()->ForwardDynamics();\r\n\tse3 hipAcc_tmp = Hip->GetGenAccelerationLocal(); // represented in body frame\r\n//\tse3 hipAcc_tmp = InvAd((_boneTs[0]), Hip->GetGenAccelerationLocal()); // represented in body frame\r\n\r\n//\tse3 hipAcc_tmp = InvAd(_boneTs[0], Hip->GetGenAccelerationLocal());\r\n//\tse3 hipVelLocal_joint = InvAd(_boneTs[0], Hip->GetGenVelocityLocal());\r\n//\tVec3 hipAngVelLocal_joint(hipVelLocal_joint[0], hipVelLocal_joint[1], hipVelLocal_joint[2]);\r\n//\tVec3 hipLinVelLocal_joint(hipVelLocal_joint[3], hipVelLocal_joint[4], hipVelLocal_joint[5]);\r\n//\r\n//\thipAcc_tmp += Cross(hipAngVelLocal_joint, hipLinVelLocal_joint);\r\n\r\n//\tVec3 hipJointPosLocal = Inv(_boneTs[0]).GetPosition();\r\n//\tSE3 hipFrame_joint = Hip->GetFrame() * Inv(_boneTs[0]);\r\n//\tSE3 hipFrame_body = Hip->GetFrame();\r\n//\r\n//\tVec3 hipAngVelGlobal = Hip->GetAngVelocity();\r\n//\r\n//\tse3 hipGenAccLocal_body = Hip->GetGenAccelerationLocal();\r\n//\tVec3 hipAngAccLocal_body(hipGenAccLocal_body[0], hipGenAccLocal_body[1], hipGenAccLocal_body[2]);\r\n//\tVec3 hipLinAccLocal_body(hipGenAccLocal_body[3], hipGenAccLocal_body[4], hipGenAccLocal_body[5]);\r\n//\r\n//\tVec3 hipAngAccGlobal_body = Rotate(hipFrame_body, hipAngAccLocal_body);\r\n//\tVec3 hipLinAccGlobal_body = Rotate(hipFrame_body, hipLinAccLocal_body);\r\n//\r\n//\tVec3 hipAngAccGlobal_joint = hipAngAccGlobal_body;\r\n//\tVec3 hipLinAccGlobal_joint = hipLinAccGlobal_body + Cross(hipAngAccGlobal_body, hipJointPosLocal)\r\n//\t\t\t\t\t\t\t+ Cross(hipAngVelGlobal, Cross(hipAngVelGlobal, hipJointPosLocal));\r\n//\r\n//\tVec3 hipAngAccLocal_joint = InvRotate(hipFrame_joint, hipAngAccGlobal_joint);\r\n//\tVec3 hipLinAccLocal_joint = InvRotate(hipFrame_joint, hipLinAccGlobal_joint);\r\n//\r\n////\tse3 hipAcc_tmp(hipAngAccGlobal_joint[0], hipAngAccGlobal_joint[1], hipAngAccGlobal_joint[2],\r\n////\t\t\t\t   hipLinAccGlobal_joint[0], hipLinAccGlobal_joint[1], hipLinAccGlobal_joint[2]);\r\n//\tse3 hipAcc_tmp(hipAngAccLocal_joint[0], hipAngAccLocal_joint[1], hipAngAccLocal_joint[2],\r\n//\t\t\t\t   hipLinAccLocal_joint[0], hipLinAccLocal_joint[1], hipLinAccLocal_joint[2]);\r\n\t{\r\n\t\tinvMb[0] = -hipAcc_tmp[3];\r\n\t\tinvMb[1] = -hipAcc_tmp[4];\r\n\t\tinvMb[2] = -hipAcc_tmp[5];\r\n\t\tinvMb[3] = -hipAcc_tmp[0];\r\n\t\tinvMb[4] = -hipAcc_tmp[1];\r\n\t\tinvMb[5] = -hipAcc_tmp[2];\r\n\t}\r\n\t//std::cout << \"Hip velocity: \" << Hip->GetGenVelocity();\r\n\tfor(int i=0; i<n; i++)\r\n\t{\r\n\t\tVec3 acc(0,0,0);\r\n\t\tvpBJoint *joint = &(_nodes.at(i+1)->joint);\r\n\t\tacc = joint->GetAcceleration();\r\n\t\tfor(int j=0; j<3; j++)\r\n\t\t{\r\n\t\t\tinvMb[6+3*i+j] = -acc[j];\r\n\t\t}\r\n\t}\r\n\r\n\t//get M\r\n\tfor(int i=0; i<N; i++)\r\n\t{\r\n\t\tHip->ResetForce();\r\n\t\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); i++)\r\n\t\t{\r\n\t\t\t_nodes.at(i)->body.ResetForce();\r\n\t\t\t_nodes.at(i)->joint.SetTorque(Vec3(0,0,0));\r\n\t\t}\r\n\r\n\t\tdse3 genForceLocal(0.0);\r\n\t\tif (i < 3) genForceLocal[i+3] = 1.0;\r\n\t\telse if(i<6) genForceLocal[i-3] = 1.0;\r\n\t\tfor(int j=0; j<n; j++)\r\n\t\t{\r\n\t\t\tVec3 torque(0., 0., 0.);\r\n\t\t\tif ( i >= 6 && (i-6)/3 == j )\r\n\t\t\t\ttorque[ (i-6)%3 ] = 1.;\r\n\t\t\tvpBJoint *joint = &(_nodes.at(j+1)->joint);\r\n\t\t\tjoint->SetTorque(torque);\r\n\t\t}\r\n\t\tHip->ApplyLocalForce(genForceLocal, zero_Vec3);\r\n\r\n\t\tHip->GetSystem()->ForwardDynamics();\r\n\t\t se3 hipAcc_tmp = Hip->GetGenAccelerationLocal();\r\n////\t\t se3 hipAcc_tmp_1 = Ad((_boneTs[0]), Hip->GetGenAccelerationLocal());\r\n////\t\tse3 hipAcc_tmp_1 = InvAd(_boneTs[0], Hip->GetGenAccelerationLocal());\r\n////\t\tse3 hipVelLocal_joint_1 = InvAd(_boneTs[0], Hip->GetGenVelocityLocal());\r\n////\t\tVec3 hipAngVelLocal_joint_1(hipVelLocal_joint_1[0], hipVelLocal_joint_1[1], hipVelLocal_joint_1[2]);\r\n////\t\tVec3 hipLinVelLocal_joint_1(hipVelLocal_joint_1[3], hipVelLocal_joint_1[4], hipVelLocal_joint_1[5]);\r\n////\r\n////\t\thipAcc_tmp_1 += Cross(hipAngVelLocal_joint_1, hipLinVelLocal_joint_1);\r\n//\r\n//\t\tVec3 hipJointPosLocal = Inv(_boneTs[0]).GetPosition();\r\n//\t\tSE3 hipFrame_joint = Hip->GetFrame() * Inv(_boneTs[0]);\r\n//\t\tSE3 hipFrame_body = Hip->GetFrame();\r\n//\r\n//\t\tVec3 hipAngVelGlobal = Hip->GetAngVelocity();\r\n//\r\n//\t\tse3 hipGenAccLocal_body = Hip->GetGenAccelerationLocal();\r\n//\t\tVec3 hipAngAccLocal_body(hipGenAccLocal_body[0], hipGenAccLocal_body[1], hipGenAccLocal_body[2]);\r\n//\t\tVec3 hipLinAccLocal_body(hipGenAccLocal_body[3], hipGenAccLocal_body[4], hipGenAccLocal_body[5]);\r\n//\r\n//\t\tVec3 hipAngAccGlobal_body = Rotate(hipFrame_body, hipAngAccLocal_body);\r\n//\t\tVec3 hipLinAccGlobal_body = Rotate(hipFrame_body, hipLinAccLocal_body);\r\n//\r\n//\t\tVec3 hipAngAccGlobal_joint = hipAngAccGlobal_body;\r\n//\t\tVec3 hipLinAccGlobal_joint = hipLinAccGlobal_body + Cross(hipAngAccGlobal_body, hipJointPosLocal)\r\n//\t\t\t\t\t\t\t\t\t + Cross(hipAngVelGlobal, Cross(hipAngVelGlobal, hipJointPosLocal));\r\n//\r\n//\t\tVec3 hipAngAccLocal_joint = InvRotate(hipFrame_joint, hipAngAccGlobal_joint);\r\n//\t\tVec3 hipLinAccLocal_joint = InvRotate(hipFrame_joint, hipLinAccGlobal_joint);\r\n//\r\n////\tse3 hipAcc_tmp(hipAngAccGlobal_joint[0], hipAngAccGlobal_joint[1], hipAngAccGlobal_joint[2],\r\n////\t\t\t\t   hipLinAccGlobal_joint[0], hipLinAccGlobal_joint[1], hipLinAccGlobal_joint[2]);\r\n//\t\tse3 hipAcc_tmp(hipAngAccLocal_joint[0], hipAngAccLocal_joint[1], hipAngAccLocal_joint[2],\r\n//\t\t\t\t\t   hipLinAccLocal_joint[0], hipLinAccLocal_joint[1], hipLinAccLocal_joint[2]);\r\n\r\n\r\n\t\tfor (int j = 0; j < 3; j++)\r\n\t\t{\r\n\t\t\tinvM[j][i] = hipAcc_tmp[j+3] + invMb[j];\r\n\t\t}\r\n\t\tfor (int j = 3; j < 6; j++)\r\n\t\t{\r\n\t\t\tinvM[j][i] = hipAcc_tmp[j-3] + invMb[j];\r\n\t\t}\r\n\t\tfor(int j=0; j<n; j++)\r\n\t\t{\r\n\t\t\tVec3 acc(0,0,0);\r\n\t\t\tvpBJoint *joint = &(_nodes.at(j+1)->joint);\r\n\t\t\tacc = joint->GetAcceleration();\r\n\t\t\tfor(int k=0; k<3; k++)\r\n\t\t\t{\r\n\t\t\t\tinvM[6+3*j+k][i] = acc[k] + invMb[6+3*j+k];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// restore ddq and tau\r\n\tfor(int i=0; i<n; i++)\r\n\t{\r\n\t\tvpBJoint *joint = &(_nodes.at(i+1)->joint);\r\n\t\tjoint->SetAcceleration(accBackup.at(i));\r\n\t\tjoint->SetTorque(torBackup.at(i));\r\n\t\tjoint->SetAcceleration(Vec3(0., 0., 0.));\r\n\t\tjoint->SetTorque(Vec3(0., 0., 0.));\r\n\t}\r\n\t//Hip->SetGenAcceleration(hipAccBackup);\r\n\r\n\tHip->ResetForce();\r\n//\tHip->ApplyGlobalForce(hipTorBackup, zero_Vec3);\r\n\treturn ls;\r\n}\r\n\r\nbp::list VpControlModel::getEquationOfMotion(object& M, object& b)\r\n{\r\n\tbp::list ls;\r\n\tls.append(_nodes.size());\r\n\t//for(int i=0; i<_nodes.size(); i++)\r\n\t//{\r\n\t\t//ls.append(_nodes.at(i)->name);\r\n\t\t//ls.append(_nodes.at(i)->dof);\r\n\t//}\r\n\t//\r\n\t//RMatrix ddq = get_ddq(), tau = get_tau(); // save current ddq and tau\r\n\t//int n = getNumCoordinates();\r\n\t//M.ReNew(n,n);\r\n\t//set_ddq(Zeros(n,1));\r\n\t//GSystem::calcInverseDynamics();\r\n\t//b = get_tau();\r\n\t//for (int i=0; i<n; i++) {\r\n\t//\tRMatrix unit = Zeros(n,1);\r\n\t//\tunit[i] = 1;\r\n\t//\tset_ddq(unit);\r\n\t//\tGSystem::calcInverseDynamics();\r\n\t//\tget_tau(&M[i*n]);\r\n\t//\tfor (int j=0; j<n; j++) {\r\n\t//\t\tM[i*n+j] -= b[j];\r\n\t//\t}\r\n\t//}\r\n\t//set_ddq(ddq); set_tau(tau); // restore ddq and tau\r\n\r\n\r\n\t// M * ddq + b = tau\r\n\t// ddq^T = [rootjointLin^T rootjointAng^T joints^T]^T\r\n\t\r\n\t\r\n\tint n = _nodes.size()-1;\r\n\tint N = 6+3*n;\r\n\r\n\tvpBody *Hip = &(_nodes.at(0)->body);\r\n\r\n\t//save current ddq and tau\r\n\tstd::vector<Vec3> accBackup;\r\n\tstd::vector<Vec3> torBackup;\r\n\tfor(int i=0; i<n; i++)\r\n\t{\r\n\t\tvpBJoint *joint = &(_nodes.at(i+1)->joint);\r\n\t\taccBackup.push_back(joint->GetAcceleration());\r\n\t\ttorBackup.push_back(joint->GetTorque());\r\n\t}\r\n\tse3 hipAccBackup = Hip->GetGenAcceleration();\r\n\tdse3 hipTorBackup = Hip->GetForce();\r\n\r\n\t//Hip->ResetForce();\r\n\t//for(int i=0; i<_nodes.size(); i++)\r\n\t//{\r\n\t\t////_nodes.at(i)->body.ResetForce();\r\n\t\t//_nodes.at(i)->joint.SetTorque(Vec3(0,0,0));\r\n\t//}\r\n\r\n\t//get b\r\n\tstd::vector<double> ddq;\r\n\tfor(int i=0; i<N; i++)\r\n\t    ddq.push_back(0.);\r\n\r\n\tset_ddq_vp(ddq);\r\n\t_nodes[0]->body.GetSystem()->InverseDynamics();\r\n\r\n\t//get M\r\n\tfor(int i=0; i<N; i++)\r\n\t{\r\n\t    ddq[i] = 1.;\r\n\t    if(i > 0)\r\n\t        ddq[i+1] = 0.;\r\n\r\n\t    _nodes[0]->body.GetSystem()->InverseDynamics();\r\n\r\n\t}\r\n\r\n\t// restore ddq and tau\r\n\r\n\tVec3 zero_Vec3(0.);\r\n\tfor(int i=0; i<n; i++)\r\n\t{\r\n\t\tvpBJoint *joint = &(_nodes.at(i+1)->joint);\r\n\t\tjoint->SetAcceleration(accBackup.at(i));\r\n\t\tjoint->SetTorque(torBackup.at(i));\r\n\t}\r\n\tHip->SetGenAcceleration(hipAccBackup);\r\n\tHip->ResetForce();\r\n\tHip->ApplyGlobalForce(hipTorBackup, zero_Vec3);\r\n\treturn ls;\r\n}\r\n\r\n//void VpControlModel::stepKinematics(double dt, const object& acc)\r\n//{\r\n\t//Vec3 ddq = pyVec3_2_Vec3(acc);\r\n\t//Vec3 dq(0.0);\r\n\t//SE3 q;\r\n\t//vpBJoint *joint = &(_nodes.at(2)->joint);\r\n\t//dq = joint->GetVelocity() + ddq * dt;\r\n\t//joint->SetVelocity(dq);\r\n\t////q = joint->GetOrientation() * Exp(Axis(dq*dt));\r\n\t//q = Exp(Axis(dq*dt))*joint->GetOrientation(); \r\n\t//joint->SetOrientation(q);\r\n//}\r\n#include <VP/vpWorld.h>\r\nvoid VpControlModel::stepKinematics(double dt, const bp::list& accs)\r\n{\r\n\tvpBody *Hip = &(_nodes.at(0)->body);\r\n\tVec3 hipacc = pyVec3_2_Vec3(accs[0].slice(0,3));\r\n\tAxis hipangacc(pyVec3_2_Vec3(accs[0].slice(3,6)));\r\n\t{\r\n\t\tse3 genAccBodyLocal(hipangacc, hipacc);\r\n\t\tse3 genVelBodyLocal = Hip->GetGenVelocityLocal() + genAccBodyLocal*dt ;\r\n\t\tHip->SetGenVelocityLocal(genVelBodyLocal);\r\n\t\tSE3 rootFrame = Hip->GetFrame() * Exp(dt*genVelBodyLocal);\r\n\t\tHip->SetFrame(rootFrame);\r\n\t}\r\n\r\n\tVec3 ddq(0.0), dq(0.0), zero_Vec3(0.0);\r\n\tSE3 q;\r\n\tfor(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)\r\n\t{\r\n\t\tddq = pyVec3_2_Vec3(accs[i]);\r\n\t\tvpBJoint *joint = &(_nodes[i]->joint);\r\n\t\tdq = joint->GetVelocity() + ddq * dt;\r\n\t\tjoint->SetVelocity(dq);\r\n\t\tq = joint->GetOrientation() * Exp(Axis(dq*dt));\r\n\t\tjoint->SetOrientation(q);\r\n\t}\r\n\r\n\tfor(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)\r\n\t\t_nodes[i]->body.UpdateGeomFrame();\r\n\t\r\n\tse3 zero_se3(0.0);\r\n\tHip->ResetForce();\r\n\t//for(int i=0; i<_nodes.size(); i++)\r\n\t//{\r\n\t\t////_nodes.at(i)->body.ResetForce();\r\n\t\t//_nodes.at(i)->body.SetGenAcceleration(zero_se3);\r\n\t//}\r\n}\r\n", "meta": {"hexsha": "f0e02135b1856fc2f1948e09e03899cb4d12406d", "size": 116743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyCommon/modules/Simulator/csVpModel.cpp", "max_stars_repo_name": "hpgit/HumanFoot", "max_stars_repo_head_hexsha": "f9a1a341b7c43747bddcd5584b8c98a0d1ac2973", "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": "PyCommon/modules/Simulator/csVpModel.cpp", "max_issues_repo_name": "hpgit/HumanFoot", "max_issues_repo_head_hexsha": "f9a1a341b7c43747bddcd5584b8c98a0d1ac2973", "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": "PyCommon/modules/Simulator/csVpModel.cpp", "max_forks_repo_name": "hpgit/HumanFoot", "max_forks_repo_head_hexsha": "f9a1a341b7c43747bddcd5584b8c98a0d1ac2973", "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.8274263904, "max_line_length": 163, "alphanum_fraction": 0.6365863478, "num_tokens": 36193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.18709289516676972}}
{"text": "/* Process all images in the directory specified in the argument.\nXiang Xiang (eglxiang@gmail.com), May 2016, MIT license.\nMain functionality: compute VGG_Face features for each image.\nFirst you need to create the saving directory yourself.\nIt writes the feature vector of each face image into a txt file.\n*/\n\n#define CPU_ONLY\n#define CORR_METRIC\n#include \"Classifier.h\"\n#include <caffe/caffe.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <iostream>\n#include <math.h>\n#include <dirent.h>\n#include <string.h>\n//#include <boost/python.hpp>\n\nusing namespace caffe;\nusing namespace cv;\nusing namespace std;\n//using namespace boost::python\n\nint main(int argc, char** argv)\n{\n    // load image\n    if (argc != 4)\n    {\n        cerr<<\"Run a simple test sample using pretrained VGG face model. \" << endl\n            << \"Usage: \" << argv[0]\n            << \"deploy.prototxt network.caffemodel folderpath\" << endl;\n        return -1;\n    }\n    string model_file = argv[1];\n    string trained_file = argv[2];\n    Classifier classifier(model_file, trained_file);\n    string foldername = argv[3];\n    string rootpath = \"/mnt/localsata/selected_faces/\";\n    string folderpath = rootpath + foldername;\n\n    // list files in the folder\n    DIR *dir;\n    dir = opendir(folderpath.c_str());\n    cout << dir << endl;\n    string imgName;\n    struct dirent *ent;\n\n    if (dir != NULL) {\n        while ( (ent = readdir(dir)) != NULL ) {\n            imgName = ent->d_name;\n            if (imgName.compare(\".\")!=0 && imgName.compare(\"..\")!=0)\n            {\n                string aux;\n                aux.append(folderpath);\n                aux.append(imgName);\n                cout << aux << endl;\n                Mat img = imread(aux, -1);\n                if (! img.data) {\n                    cout << \"Could not open or find the image\" << endl;\n                    return -1;\n                }\n                int height = img.rows;\n                int width = img.cols;\n\n                // subtract the average face\n                Mat avg(height, width, CV_8UC3, Scalar(93.5940,104.7624,129.1863));\n                // Mat mean_img(height, width, CV_8UC3, Scalar(90,100,120)); //also works\n                Mat image = img - avg;\n                vector<float> output = classifier.Predict(image);\n\n                //for (vector<float>::const_iterator i = output.begin(); i != output.end(); ++i) {\n                //    cout << *i << ' ';\n                //}\n            }\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "f39b7800b0c7c373c2d2ed000cf454e49ec74be2", "size": 2561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_seq.cpp", "max_stars_repo_name": "eglxiang/vgg_face", "max_stars_repo_head_hexsha": "9e6d356ac5cdd3e1bae802712cbb754c72fbe3bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T08:42:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T17:19:19.000Z", "max_issues_repo_path": "main_seq.cpp", "max_issues_repo_name": "eglxiang/vgg_face", "max_issues_repo_head_hexsha": "9e6d356ac5cdd3e1bae802712cbb754c72fbe3bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-08-24T15:59:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T05:55:08.000Z", "max_forks_repo_path": "main_seq.cpp", "max_forks_repo_name": "eglxiang/vgg_face", "max_forks_repo_head_hexsha": "9e6d356ac5cdd3e1bae802712cbb754c72fbe3bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T08:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T05:33:56.000Z", "avg_line_length": 31.2317073171, "max_line_length": 98, "alphanum_fraction": 0.566185084, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.18709289516676972}}
{"text": "/*!\n@file\nForward declares `boost::hana::minus`.\n\n@copyright Louis Dionne 2013-2016\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_FWD_MINUS_HPP\n#define BOOST_HANA_FWD_MINUS_HPP\n\n#include <boost/hana/config.hpp>\n#include <boost/hana/core/when.hpp>\n\n\nBOOST_HANA_NAMESPACE_BEGIN\n    //! Subtract two elements of a group.\n    //! @ingroup group-Group\n    //!\n    //! Specifically, this performs the `Monoid` operation on the first\n    //! argument and on the inverse of the second argument, thus being\n    //! equivalent to:\n    //! @code\n    //!     minus(x, y) == plus(x, negate(y))\n    //! @endcode\n    //!\n    //!\n    //! Cross-type version of the method\n    //! --------------------------------\n    //! The `minus` method is \"overloaded\" to handle distinct data types\n    //! with certain properties. Specifically, `minus` is defined for\n    //! _distinct_ data types `A` and `B` such that\n    //! 1. `A` and `B` share a common data type `C`, as determined by the\n    //!    `common` metafunction\n    //! 2. `A`, `B` and `C` are all `Group`s when taken individually\n    //! 3. `to<C> : A -> B` and `to<C> : B -> C` are `Group`-embeddings, as\n    //!    determined by the `is_embedding` metafunction.\n    //!\n    //! The definition of `minus` for data types satisfying the above\n    //! properties is obtained by setting\n    //! @code\n    //!     minus(x, y) = minus(to<C>(x), to<C>(y))\n    //! @endcode\n    //!\n    //!\n    //! Example\n    //! -------\n    //! @include example/minus.cpp\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto minus = [](auto&& x, auto&& y) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename T, typename U, typename = void>\n    struct minus_impl : minus_impl<T, U, when<true>> { };\n\n    struct minus_t {\n        template <typename X, typename Y>\n        constexpr decltype(auto) operator()(X&& x, Y&& y) const;\n    };\n\n    constexpr minus_t minus{};\n#endif\nBOOST_HANA_NAMESPACE_END\n\n#endif // !BOOST_HANA_FWD_MINUS_HPP\n", "meta": {"hexsha": "a113e47dbbbb69b9ea84de57a841223641d334f6", "size": 2101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nheqminer/3rdparty/boost/hana/fwd/minus.hpp", "max_stars_repo_name": "EuroLine/nheqminer", "max_stars_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 886.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T20:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:47:52.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/hana/fwd/minus.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/hana/fwd/minus.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 30.8970588235, "max_line_length": 78, "alphanum_fraction": 0.6168491195, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.18709288632700663}}
{"text": "#include <fc/fwd_impl.hpp>\n#include <boost/config.hpp>\n\n#include \"_elliptic_impl_pub.hpp\"\n\n/* used by mixed + openssl */\n\nnamespace fc { namespace ecc {\nnamespace detail {\n\npublic_key_impl::public_key_impl() BOOST_NOEXCEPT {\n    _init_lib();\n}\n\npublic_key_impl::public_key_impl(const public_key_impl& cpy) BOOST_NOEXCEPT {\n    _init_lib();\n    *this = cpy;\n}\n\npublic_key_impl::public_key_impl(public_key_impl&& cpy) BOOST_NOEXCEPT {\n    _init_lib();\n    *this = cpy;\n}\n\npublic_key_impl::~public_key_impl() BOOST_NOEXCEPT {\n    free_key();\n}\n\npublic_key_impl&\npublic_key_impl::operator=(const public_key_impl& pk) BOOST_NOEXCEPT {\n    if(pk._key == nullptr) {\n        free_key();\n    }\n    else if(_key == nullptr) {\n        _key = EC_KEY_dup(pk._key);\n    }\n    else {\n        EC_KEY_copy(_key, pk._key);\n    }\n    return *this;\n}\n\npublic_key_impl&\npublic_key_impl::operator=(public_key_impl&& pk) BOOST_NOEXCEPT {\n    if(this != &pk) {\n        free_key();\n        _key    = pk._key;\n        pk._key = nullptr;\n    }\n    return *this;\n}\n\nvoid\npublic_key_impl::free_key() BOOST_NOEXCEPT {\n    if(_key != nullptr) {\n        EC_KEY_free(_key);\n        _key = nullptr;\n    }\n}\n\n// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields\n// recid selects which key is recovered\n// if check is non-zero, additional checks are performed\nint\npublic_key_impl::ECDSA_SIG_recover_key_GFp(EC_KEY* eckey, ECDSA_SIG* ecsig,\n                                           const unsigned char* msg,\n                                           int msglen, int recid, int check) {\n    if(!eckey)\n        FC_THROW_EXCEPTION(exception, \"null key\");\n\n    int     ret = 0;\n    BN_CTX* ctx = NULL;\n\n    BIGNUM*   x     = NULL;\n    BIGNUM*   e     = NULL;\n    BIGNUM*   order = NULL;\n    BIGNUM*   sor   = NULL;\n    BIGNUM*   eor   = NULL;\n    BIGNUM*   field = NULL;\n    EC_POINT* R     = NULL;\n    EC_POINT* O     = NULL;\n    EC_POINT* Q     = NULL;\n    BIGNUM*   rr    = NULL;\n    BIGNUM*   zero  = NULL;\n    int       n     = 0;\n    int       i     = recid / 2;\n\n    const EC_GROUP* group = EC_KEY_get0_group(eckey);\n    if((ctx = BN_CTX_new()) == NULL) {\n        ret = -1;\n        goto err;\n    }\n    BN_CTX_start(ctx);\n    order = BN_CTX_get(ctx);\n    if(!EC_GROUP_get_order(group, order, ctx)) {\n        ret = -2;\n        goto err;\n    }\n    x = BN_CTX_get(ctx);\n    if(!BN_copy(x, order)) {\n        ret = -1;\n        goto err;\n    }\n    if(!BN_mul_word(x, i)) {\n        ret = -1;\n        goto err;\n    }\n    if(!BN_add(x, x, ecsig->r)) {\n        ret = -1;\n        goto err;\n    }\n    field = BN_CTX_get(ctx);\n    if(!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) {\n        ret = -2;\n        goto err;\n    }\n    if(BN_cmp(x, field) >= 0) {\n        ret = 0;\n        goto err;\n    }\n    if((R = EC_POINT_new(group)) == NULL) {\n        ret = -2;\n        goto err;\n    }\n    if(!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) {\n        ret = 0;\n        goto err;\n    }\n    if(check) {\n        if((O = EC_POINT_new(group)) == NULL) {\n            ret = -2;\n            goto err;\n        }\n        if(!EC_POINT_mul(group, O, NULL, R, order, ctx)) {\n            ret = -2;\n            goto err;\n        }\n        if(!EC_POINT_is_at_infinity(group, O)) {\n            ret = 0;\n            goto err;\n        }\n    }\n    if((Q = EC_POINT_new(group)) == NULL) {\n        ret = -2;\n        goto err;\n    }\n    n = EC_GROUP_get_degree(group);\n    e = BN_CTX_get(ctx);\n    if(!BN_bin2bn(msg, msglen, e)) {\n        ret = -1;\n        goto err;\n    }\n    if(8 * msglen > n)\n        BN_rshift(e, e, 8 - (n & 7));\n    zero = BN_CTX_get(ctx);\n    if(!BN_zero(zero)) {\n        ret = -1;\n        goto err;\n    }\n    if(!BN_mod_sub(e, zero, e, order, ctx)) {\n        ret = -1;\n        goto err;\n    }\n    rr = BN_CTX_get(ctx);\n    if(!BN_mod_inverse(rr, ecsig->r, order, ctx)) {\n        ret = -1;\n        goto err;\n    }\n    sor = BN_CTX_get(ctx);\n    if(!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) {\n        ret = -1;\n        goto err;\n    }\n    eor = BN_CTX_get(ctx);\n    if(!BN_mod_mul(eor, e, rr, order, ctx)) {\n        ret = -1;\n        goto err;\n    }\n    if(!EC_POINT_mul(group, Q, eor, R, sor, ctx)) {\n        ret = -2;\n        goto err;\n    }\n    if(!EC_KEY_set_public_key(eckey, Q)) {\n        ret = -2;\n        goto err;\n    }\n\n    ret = 1;\n\nerr:\n    if(ctx) {\n        BN_CTX_end(ctx);\n        BN_CTX_free(ctx);\n    }\n    if(R != NULL)\n        EC_POINT_free(R);\n    if(O != NULL)\n        EC_POINT_free(O);\n    if(Q != NULL)\n        EC_POINT_free(Q);\n    return ret;\n}\n}  // namespace detail\n\npublic_key::public_key() {}\n\npublic_key::public_key(const public_key& pk)\n    : my(pk.my) {}\n\npublic_key::public_key(public_key&& pk)\n    : my(std::move(pk.my)) {}\n\npublic_key::~public_key() {}\n\npublic_key&\npublic_key::operator=(public_key&& pk) {\n    my = std::move(pk.my);\n    return *this;\n}\n\npublic_key&\npublic_key::operator=(const public_key& pk) {\n    my = pk.my;\n    return *this;\n}\n\nbool\npublic_key::valid() const {\n    return my->_key != nullptr;\n}\n\n/* WARNING! This implementation is broken, it is actually equivalent to\n     * public_key::add()!\n     */\n//    public_key public_key::mult( const fc::sha256& digest ) const\n//    {\n//        // get point from this public key\n//        const EC_POINT* master_pub   = EC_KEY_get0_public_key( my->_key );\n//        ec_group group(EC_GROUP_new_by_curve_name(NID_secp256k1));\n//\n//        ssl_bignum z;\n//        BN_bin2bn((unsigned char*)&digest, sizeof(digest), z);\n//\n//        // multiply by digest\n//        ssl_bignum one;\n//        BN_one(one);\n//        bn_ctx ctx(BN_CTX_new());\n//\n//        ec_point result(EC_POINT_new(group));\n//        EC_POINT_mul(group, result, z, master_pub, one, ctx);\n//\n//        public_key rtn;\n//        rtn.my->_key = EC_KEY_new_by_curve_name( NID_secp256k1 );\n//        EC_KEY_set_public_key(rtn.my->_key,result);\n//\n//        return rtn;\n//    }\npublic_key\npublic_key::add(const fc::sha256& digest) const {\n    try {\n        ec_group group(EC_GROUP_new_by_curve_name(NID_secp256k1));\n        bn_ctx   ctx(BN_CTX_new());\n\n        fc::bigint digest_bi((char*)&digest, sizeof(digest));\n\n        ssl_bignum order;\n        EC_GROUP_get_order(group, order, ctx);\n        if(digest_bi > fc::bigint(order)) {\n            FC_THROW_EXCEPTION(exception, \"digest > group order\");\n        }\n\n        public_key      digest_key   = private_key::regenerate(digest).get_public_key();\n        const EC_POINT* digest_point = EC_KEY_get0_public_key(digest_key.my->_key);\n\n        // get point from this public key\n        const EC_POINT* master_pub = EC_KEY_get0_public_key(my->_key);\n\n        //        ssl_bignum z;\n        //        BN_bin2bn((unsigned char*)&digest, sizeof(digest), z);\n\n        // multiply by digest\n        //        ssl_bignum one;\n        //        BN_one(one);\n\n        ec_point result(EC_POINT_new(group));\n        EC_POINT_add(group, result, digest_point, master_pub, ctx);\n\n        if(EC_POINT_is_at_infinity(group, result)) {\n            FC_THROW_EXCEPTION(exception, \"point at  infinity\");\n        }\n\n        public_key rtn;\n        rtn.my->_key = EC_KEY_new_by_curve_name(NID_secp256k1);\n        EC_KEY_set_public_key(rtn.my->_key, result);\n        return rtn;\n    }\n    FC_RETHROW_EXCEPTIONS(debug, \"digest: ${digest}\", (\"digest\", digest));\n}\n\nstd::string\npublic_key::to_base58() const {\n    public_key_data key = serialize();\n    return to_base58(key);\n}\n\n//    signature private_key::sign( const fc::sha256& digest )const\n//    {\n//        unsigned int buf_len = ECDSA_size(my->_key);\n////        fprintf( stderr, \"%d  %d\\n\", buf_len, sizeof(sha256) );\n//        signature sig;\n//        assert( buf_len == sizeof(sig) );\n//\n//        if( !ECDSA_sign( 0,\n//                    (const unsigned char*)&digest, sizeof(digest),\n//                    (unsigned char*)&sig, &buf_len, my->_key ) )\n//        {\n//            FC_THROW_EXCEPTION( exception, \"signing error\" );\n//        }\n//\n//\n//        return sig;\n//    }\n//    bool       public_key::verify( const fc::sha256& digest, const fc::ecc::signature& sig )\n//    {\n//      return 1 == ECDSA_verify( 0, (unsigned char*)&digest, sizeof(digest), (unsigned char*)&sig, sizeof(sig), my->_key );\n//    }\n\npublic_key_data\npublic_key::serialize() const {\n    public_key_data dat;\n    if(!my->_key)\n        return dat;\n    EC_KEY_set_conv_form(my->_key, POINT_CONVERSION_COMPRESSED);\n    /*size_t nbytes = i2o_ECPublicKey( my->_key, nullptr ); */\n    /*assert( nbytes == 33 )*/\n    char* front = &dat.data[0];\n    i2o_ECPublicKey(my->_key, (unsigned char**)&front);  // FIXME: questionable memory handling\n    return dat;\n    /*\n       EC_POINT* pub   = EC_KEY_get0_public_key( my->_key );\n       EC_GROUP* group = EC_KEY_get0_group( my->_key );\n       EC_POINT_get_affine_coordinates_GFp( group, pub, self.my->_pub_x.get(), self.my->_pub_y.get(), nullptr );\n       */\n}\npublic_key_point_data\npublic_key::serialize_ecc_point() const {\n    public_key_point_data dat;\n    if(!my->_key)\n        return dat;\n    EC_KEY_set_conv_form(my->_key, POINT_CONVERSION_UNCOMPRESSED);\n    char* front = &dat.data[0];\n    i2o_ECPublicKey(my->_key, (unsigned char**)&front);  // FIXME: questionable memory handling\n    return dat;\n}\n\npublic_key::public_key(const public_key_point_data& dat) {\n    const char* front = &dat.data[0];\n    if(*front == 0) {\n    }\n    else {\n        my->_key = EC_KEY_new_by_curve_name(NID_secp256k1);\n        my->_key = o2i_ECPublicKey(&my->_key, (const unsigned char**)&front, sizeof(dat));\n        if(!my->_key) {\n            FC_THROW_EXCEPTION(exception, \"error decoding public key\", (\"s\", ERR_error_string(ERR_get_error(), nullptr)));\n        }\n    }\n}\npublic_key::public_key(const public_key_data& dat) {\n    const char* front = &dat.data[0];\n    if(*front == 0) {\n    }\n    else {\n        my->_key = EC_KEY_new_by_curve_name(NID_secp256k1);\n        my->_key = o2i_ECPublicKey(&my->_key, (const unsigned char**)&front, sizeof(public_key_data));\n        if(!my->_key) {\n            FC_THROW_EXCEPTION(exception, \"error decoding public key\", (\"s\", ERR_error_string(ERR_get_error(), nullptr)));\n        }\n    }\n}\n\n//    bool       private_key::verify( const fc::sha256& digest, const fc::ecc::signature& sig )\n//    {\n//      return 1 == ECDSA_verify( 0, (unsigned char*)&digest, sizeof(digest), (unsigned char*)&sig, sizeof(sig), my->_key );\n//    }\n\npublic_key::public_key(const compact_signature& c, const fc::sha256& digest, bool check_canonical) {\n    int nV = c.data[0];\n    if(nV < 27 || nV >= 35)\n        FC_THROW_EXCEPTION(exception, \"unable to reconstruct public key from signature\");\n\n    ECDSA_SIG* sig = ECDSA_SIG_new();\n    BN_bin2bn(&c.data[1], 32, sig->r);\n    BN_bin2bn(&c.data[33], 32, sig->s);\n\n    if(check_canonical) {\n        FC_ASSERT(is_canonical(c), \"signature is not canonical\");\n    }\n\n    my->_key = EC_KEY_new_by_curve_name(NID_secp256k1);\n\n    if(nV >= 31) {\n        EC_KEY_set_conv_form(my->_key, POINT_CONVERSION_COMPRESSED);\n        nV -= 4;\n        //            fprintf( stderr, \"compressed\\n\" );\n    }\n\n    if(detail::public_key_impl::ECDSA_SIG_recover_key_GFp(my->_key, sig, (unsigned char*)&digest, sizeof(digest), nV - 27, 0) == 1) {\n        ECDSA_SIG_free(sig);\n        return;\n    }\n    ECDSA_SIG_free(sig);\n    FC_THROW_EXCEPTION(exception, \"unable to reconstruct public key from signature\");\n}\n}}  // namespace fc::ecc\n", "meta": {"hexsha": "6a006965145524f8290768e8b47758c6963d1666", "size": 11437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/fc/src/crypto/elliptic_impl_pub.cpp", "max_stars_repo_name": "Laighno/evt", "max_stars_repo_head_hexsha": "90b94e831aebb62c6ad19ce59c9089e9f51cfd77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1411.0, "max_stars_repo_stars_event_min_datetime": "2018-04-23T03:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T10:34:22.000Z", "max_issues_repo_path": "libraries/fc/src/crypto/elliptic_impl_pub.cpp", "max_issues_repo_name": "Zhang-Zexi/evt", "max_issues_repo_head_hexsha": "e90fe4dbab4b9512d120c79f33ecc62791e088bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-06-11T10:34:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-27T08:50:02.000Z", "max_forks_repo_path": "libraries/fc/src/crypto/elliptic_impl_pub.cpp", "max_forks_repo_name": "Zhang-Zexi/evt", "max_forks_repo_head_hexsha": "e90fe4dbab4b9512d120c79f33ecc62791e088bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 364.0, "max_forks_repo_forks_event_min_datetime": "2018-06-09T12:11:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T03:26:48.000Z", "avg_line_length": 27.5590361446, "max_line_length": 133, "alphanum_fraction": 0.5763749235, "num_tokens": 3191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.18709288071878985}}
{"text": "#pragma once\n\n#include \"util.hxx\"\n#include \"vec3f.hxx\"\n#include \"box.hxx\"\n#include \"span.hxx\"\n#include \"json_fwd.hxx\"\n#include \"ray.hxx\"\n\n#include <boost/container/static_vector.hpp>\n#include <numeric>\n\nnamespace guiding \n{\n\n\nnamespace kdtree\n{\n\ninline static constexpr int MAX_DEPTH = 20;\n\n\nstruct AdaptParams\n{\n  std::uint64_t max_num_points = std::numeric_limits<std::uint64_t>::max();\n};\n\nstatic constexpr int MAX_NODES = (1<<30)-1;\n\nstruct Node\n{\n  double split_pos = std::numeric_limits<double>::quiet_NaN();\n  std::uint64_t \n    split_axis : 2, \n    left_is_leaf : 1, \n    right_is_leaf : 1,\n    left_idx : 30,\n    right_idx : 30;\n};\n\nstatic_assert(sizeof(Node) == 16);\n\nstruct Handle \n{\n  int idx = -1;\n  bool is_leaf = false;\n};\n\n\nclass Tree\n{\npublic:\n  using Handle = guiding::kdtree::Handle;\n\nprivate:\n  friend class TreeAdaptor;\n  template <class, class> friend class Builder;\n  ToyVector<Node> storage;\n  Handle root;\n  int num_leafs = 0;\n  \n  Handle AllocateLeaf()\n  {\n    assert (num_leafs < MAX_NODES);\n    return Handle{ num_leafs++, true };\n  }\n\n  Handle AllocateBranch(Handle left, Handle right, int axis, double pos)\n  {\n    Node nd;\n    nd.split_pos = pos;\n    nd.split_axis = axis;\n    nd.left_is_leaf = left.is_leaf;\n    nd.right_is_leaf = right.is_leaf;\n    nd.left_idx = left.idx;\n    nd.right_idx = right.idx;\n    storage.push_back(nd);\n    return { static_cast<int>(storage.size()-1), false };\n  }\n\n  struct TagUninitialized {};\n\n  explicit Tree(TagUninitialized)\n  {\n  }\n\npublic:\n  Tree() :\n    Tree(TagUninitialized{})\n  {\n    root = AllocateLeaf();\n  }\n\n  Tree(const Tree &) = delete;\n  Tree& operator=(const Tree&) = delete;\n\n  Tree(Tree &&) = default;\n  Tree& operator=(Tree &&) = default;\n\n  int NumLeafs() const { return num_leafs; }\n\n  Handle GetRoot() const\n  {\n    return root;\n  }\n\n  auto Children(Handle node) const\n  {\n    assert (!node.is_leaf);\n    const auto& b = storage[node.idx];\n    return std::make_pair(Handle{static_cast<int>(b.left_idx), static_cast<bool>(b.left_is_leaf)},\n                          Handle{static_cast<int>(b.right_idx), static_cast<bool>(b.right_is_leaf)});\n  }\n\n  auto Split(Handle node) const\n  {\n    assert (!node.is_leaf);\n    const auto& b = storage[node.idx];\n    return std::make_pair(static_cast<int>(b.split_axis), b.split_pos);\n  }\n\n  int Lookup(const Double3 &p)\n  {\n    Handle current = root;\n    while (true)\n    {\n      if (current.is_leaf)\n      {\n        return current.idx;\n      }\n      else\n      {\n        const auto& b = storage[current.idx];\n        const bool go_left = p[b.split_axis] < b.split_pos;\n        auto [left, right] = Children(current);\n        current = go_left ? left : right;\n      }\n    }\n  }\n\n  int Lookup(const Double3 &p) const\n  {\n    return const_cast<Tree*>(this)->Lookup(p);\n  }\n\n#ifdef HAVE_JSON\n  void DumpTo(rapidjson::Document &doc, rapidjson::Value & parent) const;\n#endif\n};\n\n\nclass TreeAdaptor\n{\npublic:\n  using SplitDecision = std::function<std::pair<int, double>(int)>;\n\n  TreeAdaptor(SplitDecision split_decision_) :\n    split_decision{split_decision_}\n  {\n  }\n\n  Tree Adapt(Tree &tree)\n  {\n    this->tree = &tree;\n    new_tree.root = AdaptRecursive(tree.root, 1);\n    Tree tmp{Tree::TagUninitialized()};\n    std::swap(tmp, new_tree);\n    return tmp;\n  }\n\n  struct OldToNew\n  {\n    //int old = -1;\n    int new_first = -1;\n    int new_second = -1;\n  };\n\n  Span<const OldToNew> GetNodeMappings() const\n  {\n    return AsSpan(node_mappings); \n  }\n\nprivate:\n  SplitDecision split_decision;\n  Tree *tree = nullptr;\n  Tree new_tree{Tree::TagUninitialized()};\n  ToyVector<OldToNew> node_mappings;\n\n\n  void AddToTranslationMap(Tree::Handle old, Tree::Handle new_first, Tree::Handle new_second)\n  {\n    node_mappings.push_back({\n      /*old.idx,*/ new_first.idx, new_second.idx\n    });\n    assert(node_mappings.size() == old.idx+1);\n    assert(old.is_leaf);\n  }\n\n\n  // Axis and location\n  std::pair<int, double> DetermineSplit(Handle p)\n  {\n    assert (p.is_leaf);\n    return split_decision(p.idx);\n  }\n\n  Handle AdaptLeafRecursive(Tree::Handle node, int depth)\n  {\n    if (auto [axis, pos] = DetermineSplit(node); axis>=0 && depth<MAX_DEPTH)\n    {\n      auto left = new_tree.AllocateLeaf();\n      auto right = new_tree.AllocateLeaf();\n      auto branch = new_tree.AllocateBranch(left, right, axis, pos);\n      AddToTranslationMap(node, left, right);\n      return branch;\n    }\n    else\n    {\n      auto clone = new_tree.AllocateLeaf();\n      AddToTranslationMap(node, clone, {});\n      return clone;\n    }\n  }\n\n  Handle AdaptBranchRecursive(Tree::Handle node, int depth)\n  {\n    auto [old_left, old_right] = tree->Children(node);\n    auto [axis, pos] = tree->Split(node);\n    auto left = AdaptRecursive(old_left, depth+1);\n    auto right = AdaptRecursive(old_right, depth+1);\n    auto branch = new_tree.AllocateBranch(left, right, axis, pos);\n    return branch;\n  }\n\n  Handle AdaptRecursive(Tree::Handle node, int depth)\n  {\n    return node.is_leaf ? AdaptLeafRecursive(node, depth) : AdaptBranchRecursive(node, depth);\n  }\n};\n\n\nclass LeafIterator\n{\n  using H = Tree::Handle;\n  const Tree* tree;\n  Ray ray;\n\n  struct Entry\n  {\n    H node;\n    double tnear;\n    double tfar;\n  };\n\n  boost::container::static_vector<Entry, MAX_DEPTH> stack;\n\npublic:\n  LeafIterator(const Tree &tree_, const Ray &ray_, double tnear_init, double tfar_init)  noexcept\n    : tree{&tree_}, ray{ray_}\n    {\n      stack.push_back({tree->GetRoot(), tnear_init, tfar_init});\n      DecentToNextLeaf();\n    }\n\n  void operator++()  noexcept\n  {\n    stack.pop_back();\n    if (!stack.empty())\n      DecentToNextLeaf();\n  }\n\n  operator bool() const  noexcept\n  {\n    return !stack.empty();\n  }\n\n  struct ReturnValue {\n    int idx;\n    double tnear, tfar;\n  };\n\n  ReturnValue operator*() const  noexcept\n  {\n    auto e = stack.back();\n    return ReturnValue{e.node.idx, e.tnear, e.tfar};\n  }\n\n  std::pair<double, double> Interval() const  noexcept\n  {\n    const auto& e = stack.back();\n    return std::make_pair(e.tnear, e.tfar);\n  }\n\n  int Payload() const  noexcept\n  {\n    const auto& e = stack.back();\n    return e.node.idx;\n  }\n\nprivate:\n\n  void DecentToNextLeaf() noexcept;\n};\n\n\ntemplate<class Point, class GetCoordinates>\nclass Builder\n{\n  int max_depth, min_num_points;\n  Tree new_tree{ Tree::TagUninitialized() };\n  GetCoordinates get_coordinates;\n  ToyVector <Span<Point>> leaf_ranges;\n\n  auto MakeCompareCoordinates(int axis) const\n  {\n    auto compare = [this, axis](const Point &a, const Point &b) \n    { \n      return get_coordinates(a)[axis] < get_coordinates(b)[axis]; \n    };\n\n    return compare;\n  }\n\n  Eigen::Array<double, 3, 2> ComputeBounds(const Span<Point> pts) const\n  {\n    Eigen::Array<double, 3, 2> result;\n    for (int axis = 0; axis < 3; ++axis)\n    {  \n      auto[imin, imax] = std::minmax_element(pts.begin(), pts.end(), MakeCompareCoordinates(axis));\n      const double pmin = get_coordinates(*imin)[axis];\n      const double pmax = get_coordinates(*imax)[axis];\n      result(axis, 0) = pmin;\n      result(axis, 1) = pmax;\n    }\n    return result;\n  }\n\n  Handle BuildRecursive(Span<Point> points, int depth)\n  {\n    if (points.size() < 2*min_num_points || depth >= max_depth)\n    {\n      return BuildLeaf(points);\n    }\n    else\n    {\n      return TryBuildBranchRecursive(points, depth);\n    }\n  }\n\n  Handle BuildLeaf(Span<Point> points)\n  {\n      Handle h = new_tree.AllocateLeaf();\n      assert(h.idx == isize(leaf_ranges));\n      leaf_ranges.push_back(points);\n      return h;\n  }\n\n  static double AverageIfNonDegenerate(double a, double b)\n  {\n    assert (a < b);\n    double x = 0.5*(a+b);\n    // Use b because taking a would be an error.\n    return x==a ? b : x;\n  }\n\n  /* Returns\n       Coordinate for which all elements in the left interval are smaller.\n       Size of the left interval.\n  */\n  std::tuple<double, int> SplitRange(Span<Point> pts, int axis)\n  {\n    const auto n = pts.size();\n    if (n <= 0)\n      return { NaN, 0 };\n    \n    const auto n_split_guess = n/2;\n    std::nth_element(\n      pts.begin(), \n      pts.begin()+n_split_guess, \n      pts.end(),\n      MakeCompareCoordinates(axis));\n    \n    return {\n      get_coordinates(pts[n_split_guess])[axis],\n      n_split_guess\n    };\n  }\n\n  Handle TryBuildBranchRecursive(Span<Point> branch_points, int depth)\n  {\n    const Eigen::Array<double, 3, 2> bounds = ComputeBounds(branch_points);\n\n    int axis = -1;\n    (bounds.col(1) - bounds.col(0)).maxCoeff(&axis);\n    assert(axis >= 0);\n\n    const auto n = branch_points.size();\n    assert(n >= 2*min_num_points);\n\n    auto [pos, count_left] = SplitRange(branch_points, axis);\n    const auto count_right = n - count_left;\n\n    //std::cout << \"split axis \" << axis << \" range \" << bounds.row(axis) << \" count \" << branch_points.size() << \" nleft \" << count_left << std::endl;\n\n    if (count_left >= min_num_points && count_right >= min_num_points)\n    {\n      auto left_range = Subspan(branch_points, 0, count_left);\n      auto right_range = Subspan(branch_points, count_left, count_right);\n      Handle left = BuildRecursive(left_range, depth+1);\n      Handle right = BuildRecursive(right_range, depth+1);\n      auto branch = new_tree.AllocateBranch(left, right, axis, pos);\n      return branch;\n    }\n    else\n    {\n      Handle leaf = BuildLeaf(branch_points);\n      return leaf;\n    }\n  }\n\npublic:\n  Builder(int max_depth, int min_num_points, GetCoordinates get_coordinates)\n    : max_depth{ max_depth }, min_num_points{ min_num_points }, get_coordinates{ get_coordinates }\n  {\n    assert (max_depth > 0);\n  }\n\n  Tree Build(Span<Point> points)\n  {\n    new_tree.root = BuildRecursive(points, 1);\n    return std::move(new_tree);\n  }\n\n  Span<Point> DataRangeOfLeaf(int idx) const\n  {\n    return leaf_ranges[idx];\n  }\n};\n\ntemplate<class Point, class GetCoordinates>\ninline Builder<Point, GetCoordinates> MakeBuilder(int max_depth, int min_num_points, GetCoordinates get_coordinates)\n{\n  return Builder<Point, GetCoordinates>(max_depth, min_num_points, get_coordinates);\n}\n\n\n} // kdtree\n\n\n} // guiding", "meta": {"hexsha": "a7476a1584fd483a5343b453731b4f638ac4079c", "size": 10031, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/path_guiding_tree.hxx", "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/path_guiding_tree.hxx", "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/path_guiding_tree.hxx", "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": 22.2911111111, "max_line_length": 151, "alphanum_fraction": 0.6446017346, "num_tokens": 2640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1868103121533196}}
{"text": "/*\n Copyright (C) 2018 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 <algorithm>\n#include <boost/algorithm/string.hpp>\n#include <ored/marketdata/commoditycurve.hpp>\n#include <ored/utilities/conventionsbasedfutureexpiry.hpp>\n#include <ored/utilities/indexparser.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/wildcard.hpp>\n#include <qle/termstructures/averagefuturepricehelper.hpp>\n#include <qle/termstructures/averageoffpeakpowerhelper.hpp>\n#include <qle/termstructures/averagespotpricehelper.hpp>\n#include <qle/termstructures/commodityaveragebasispricecurve.hpp>\n#include <qle/termstructures/commoditybasispricecurve.hpp>\n#include <qle/termstructures/crosscurrencypricetermstructure.hpp>\n#include <qle/termstructures/futurepricehelper.hpp>\n#include <qle/termstructures/iterativebootstrap.hpp>\n#include <qle/termstructures/piecewisepricecurve.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n#include <ql/time/date.hpp>\n\nusing QuantExt::AverageFuturePriceHelper;\nusing QuantExt::AverageOffPeakPowerHelper;\nusing QuantExt::AverageSpotPriceHelper;\nusing QuantExt::FutureExpiryCalculator;\nusing QuantExt::FuturePriceHelper;\nusing QuantExt::CommodityAverageBasisPriceCurve;\nusing QuantExt::CommodityBasisPriceCurve;\nusing QuantExt::CommodityIndex;\nusing QuantExt::CrossCurrencyPriceTermStructure;\nusing QuantExt::CubicFlat;\nusing QuantExt::InterpolatedPriceCurve;\nusing QuantExt::LinearFlat;\nusing QuantExt::LogLinearFlat;\nusing QuantExt::PriceTermStructure;\nusing QuantExt::PiecewisePriceCurve;\nusing QuantLib::BootstrapHelper;\nusing std::make_pair;\nusing std::map;\nusing std::string;\n\n// Explicit template instantiation to avoid \"error C2079: ... uses undefined class ...\"\n// Explained in the answer to the SO question here: \n// https://stackoverflow.com/a/57666066/1771882\n// Needs to be in global namespace also i.e. not under ore::data\n// https://stackoverflow.com/a/25594741/1771882\ntemplate class QuantExt::PiecewisePriceCurve<QuantLib::Linear, QuantExt::IterativeBootstrap>;\ntemplate class QuantExt::PiecewisePriceCurve<QuantLib::LogLinear, QuantExt::IterativeBootstrap>;\ntemplate class QuantExt::PiecewisePriceCurve<QuantLib::Cubic, QuantExt::IterativeBootstrap>;\ntemplate class QuantExt::PiecewisePriceCurve<QuantExt::LinearFlat, QuantExt::IterativeBootstrap>;\ntemplate class QuantExt::PiecewisePriceCurve<QuantExt::LogLinearFlat, QuantExt::IterativeBootstrap>;\ntemplate class QuantExt::PiecewisePriceCurve<QuantExt::CubicFlat, QuantExt::IterativeBootstrap>;\ntemplate class QuantExt::PiecewisePriceCurve<QuantLib::BackwardFlat, QuantExt::IterativeBootstrap>;\n\nnamespace {\n\nusing ore::data::Convention;\nusing ore::data::Conventions;\nusing QuantLib::Date;\nusing QuantLib::Error;\nusing QuantLib::io::iso_date;\nusing QuantLib::Real;\n\nvoid addMarketFixing(const string& idxConvId, const Date& expiry, Real value, const Conventions& conventions) {\n    auto p = conventions.get(idxConvId, Convention::Type::CommodityFuture);\n    if (p.first) {\n        auto idx = parseCommodityIndex(idxConvId, conventions, false);\n        idx = idx->clone(expiry);\n        if (idx->isValidFixingDate(expiry)) {\n            try {\n                idx->addFixing(expiry, value);\n                TLOG(\"Added fixing (\" << iso_date(expiry) << \",\" << idx->name() << \",\" << value << \").\");\n            } catch (const Error& e) {\n                TLOG(\"Failed to add fixing (\" << iso_date(expiry) << \",\" << idx->name() << \",\" <<\n                    value << \"): \" << e.what());\n            }\n        } else {\n            TLOG(\"Failed to add fixing (\" << iso_date(expiry) << \",\" << idx->name() << \",\" <<\n                value << \") because \" << iso_date(expiry) << \" is not a valid fixing date.\");\n        }\n    } else {\n        TLOG(\"Failed to add fixing because no commodity future convention for \" << idxConvId << \".\");\n    }\n}\n\n}\n\nnamespace ore {\nnamespace data {\n\nCommodityCurve::CommodityCurve()\n    : commoditySpot_(Null<Real>()), onValue_(Null<Real>()), tnValue_(Null<Real>()), regexQuotes_(false) {}\n\nCommodityCurve::CommodityCurve(const Date& asof, const CommodityCurveSpec& spec, const Loader& loader,\n                               const CurveConfigurations& curveConfigs, const Conventions& conventions,\n                               const FXTriangulation& fxSpots,\n                               const map<string, boost::shared_ptr<YieldCurve>>& yieldCurves,\n                               const map<string, boost::shared_ptr<CommodityCurve>>& commodityCurves)\n    : spec_(spec), commoditySpot_(Null<Real>()), onValue_(Null<Real>()), tnValue_(Null<Real>()), regexQuotes_(false) {\n\n    try {\n\n        boost::shared_ptr<CommodityCurveConfig> config = curveConfigs.commodityCurveConfig(spec_.curveConfigID());\n\n        dayCounter_ = config->dayCountId() == \"\" ? Actual365Fixed() : parseDayCounter(config->dayCountId());\n        interpolationMethod_ = config->interpolationMethod() == \"\" ? \"Linear\" : config->interpolationMethod();\n\n        if (config->type() == CommodityCurveConfig::Type::Direct) {\n\n            // Populate the raw price curve data\n            map<Date, Handle<Quote>> data;\n            populateData(data, asof, config, loader, conventions);\n\n            // Create the commodity price curve\n            buildCurve(asof, data, config);\n\n        } else if (config->type() == CommodityCurveConfig::Type::Basis) {\n\n            // We have a commodity basis configuration\n\n            // Look up the required base price curve in the commodityCurves map\n            CommodityCurveSpec ccSpec(config->currency(), config->basePriceCurveId());\n            DLOG(\"Looking for base price curve with id, \" << config->basePriceCurveId() << \", and spec, \" << ccSpec\n                                                          << \".\");\n            auto itCc = commodityCurves.find(ccSpec.name());\n            QL_REQUIRE(itCc != commodityCurves.end(), \"Can't find price curve with id \" << config->basePriceCurveId());\n            auto pts = Handle<PriceTermStructure>(itCc->second->commodityPriceCurve());\n\n            buildBasisPriceCurve(asof, *config, conventions, pts, loader);\n\n        } else if (config->type() == CommodityCurveConfig::Type::Piecewise) {\n\n            // We have a piecewise commodity configuration\n            buildPiecewiseCurve(asof, *config, conventions, loader, commodityCurves);\n\n        } else {\n\n            // We have a cross currency type commodity curve configuration\n            boost::shared_ptr<CommodityCurveConfig> baseConfig =\n                curveConfigs.commodityCurveConfig(config->basePriceCurveId());\n\n            buildCrossCurrencyPriceCurve(asof, config, baseConfig, fxSpots, yieldCurves, commodityCurves);\n        }\n\n        // Apply extrapolation from the curve configuration\n        commodityPriceCurve_->enableExtrapolation(config->extrapolation());\n\n        // Ask for price now so that errors are thrown during the build, not later.\n        commodityPriceCurve_->price(asof + 1 * Days);\n\n    } catch (std::exception& e) {\n        QL_FAIL(\"commodity curve building failed: \" << e.what());\n    } catch (...) {\n        QL_FAIL(\"commodity curve building failed: unknown error\");\n    }\n}\n\nvoid CommodityCurve::populateData(map<Date, Handle<Quote>>& data, const Date& asof,\n                                  const boost::shared_ptr<CommodityCurveConfig>& config, const Loader& loader,\n                                  const Conventions& conventions) {\n\n    // Some default conventions for building the commodity curve\n    Period spotTenor = 2 * Days;\n    Real pointsFactor = 1.0;\n    Calendar cal = parseCalendar(config->currency());\n    bool spotRelative = true;\n    BusinessDayConvention bdc = Following;\n    bool outright = true;\n\n    // Overwrite the default conventions if the commodity curve config provides explicit conventions\n    if (!config->conventionsId().empty()) {\n        QL_REQUIRE(conventions.has(config->conventionsId()),\n                   \"Commodity conventions \" << config->conventionsId() << \" requested by commodity config \"\n                                            << config->curveID() << \" not found\");\n        auto convention =\n            boost::dynamic_pointer_cast<CommodityForwardConvention>(conventions.get(config->conventionsId()));\n        QL_REQUIRE(convention, \"Convention \" << config->conventionsId() << \" not of expected type CommodityConvention\");\n\n        spotTenor = convention->spotDays() * Days;\n        pointsFactor = convention->pointsFactor();\n        if (convention->advanceCalendar() != NullCalendar())\n            cal = convention->advanceCalendar();\n        spotRelative = convention->spotRelative();\n        bdc = convention->bdc();\n        outright = convention->outright();\n    }\n\n    // Commodity spot quote if provided by the configuration\n    Date spotDate = cal.advance(asof, spotTenor);\n    if (!config->commoditySpotQuoteId().empty()) {\n        auto spot = loader.get(config->commoditySpotQuoteId(), asof)->quote();\n        commoditySpot_ = spot->value();\n        data[spotDate] = spot;\n    } else {\n        QL_REQUIRE(outright, \"If the commodity forward quotes are not outright,\"\n                                 << \" a commodity spot quote needs to be configured\");\n    }\n\n    // Add the forward quotes to the curve data\n    for (auto& q : getQuotes(asof, config->curveID(), config->fwdQuotes(), loader)) {\n\n        // We add ON and TN quotes after this loop if they are given and not outright quotes\n        TLOG(\"Commodity Forward Price found for quote: \" << q->name());\n        Date expiry;\n        Real value = q->quote()->value();\n        if (!q->tenorBased()) {\n            expiry = q->expiryDate();\n            add(asof, expiry, value, data, outright, pointsFactor);\n        } else {\n            if (q->startTenor() == boost::none) {\n                expiry = cal.advance(spotRelative ? spotDate : asof, q->tenor(), bdc);\n                add(asof, expiry, value, data, outright, pointsFactor);\n            } else {\n                if (*q->startTenor() == 0 * Days && q->tenor() == 1 * Days) {\n                    onValue_ = q->quote()->value();\n                    if (outright)\n                        add(asof, asof, value, data, outright);\n                } else if (*q->startTenor() == 1 * Days && q->tenor() == 1 * Days) {\n                    tnValue_ = q->quote()->value();\n                    if (outright) {\n                        expiry = cal.advance(asof, 1 * Days, bdc);\n                        add(asof, expiry, value, data, outright);\n                    }\n                } else {\n                    expiry = cal.advance(cal.advance(asof, *q->startTenor(), bdc), q->tenor(), bdc);\n                    add(asof, expiry, value, data, outright, pointsFactor);\n                }\n            }\n        }\n    }\n\n    // Deal with ON and TN if quotes are not outright quotes\n    if (spotTenor == 2 * Days && tnValue_ != Null<Real>() && !outright) {\n        add(asof, cal.advance(asof, 1 * Days, bdc), -tnValue_, data, outright, pointsFactor);\n        if (onValue_ != Null<Real>()) {\n            add(asof, asof, -onValue_ - tnValue_, data, outright, pointsFactor);\n        }\n    }\n\n    // Some logging and checks\n    LOG(\"Read \" << data.size() << \" quotes for commodity curve \" << config->curveID());\n    if (!regexQuotes_) {\n        QL_REQUIRE(data.size() == config->quotes().size(), \"Found \" << data.size() << \" quotes, but \"\n                                                                    << config->quotes().size()\n                                                                    << \" quotes given in config \" << config->curveID());\n    } else {\n        QL_REQUIRE(data.size() > 0,\n                   \"Regular expression specified in commodity config \" << config->curveID() << \" but no quotes read\");\n    }\n}\n\nvoid CommodityCurve::add(const Date& asof, const Date& expiry, Real value, map<Date, Handle<Quote>>& data, bool outright,\n                         Real pointsFactor) {\n\n    if (expiry < asof)\n        return;\n\n    QL_REQUIRE(data.find(expiry) == data.end(), \"Duplicate quote for expiry \" << io::iso_date(expiry) << \" found.\");\n\n    if (!outright) {\n        QL_REQUIRE(commoditySpot_ != Null<Real>(), \"Can't use forward points without a commodity spot value\");\n        value = commoditySpot_ + value / pointsFactor;\n    }\n\n    data[expiry] = Handle<Quote>(boost::make_shared<SimpleQuote>(value));\n}\n\nvoid CommodityCurve::buildCurve(const Date& asof, const map<Date, Handle<Quote>>& data,\n                                const boost::shared_ptr<CommodityCurveConfig>& config) {\n\n    vector<Date> curveDates;\n    curveDates.reserve(data.size());\n    vector<Handle<Quote>> curvePrices;\n    curvePrices.reserve(data.size());\n    for (auto const& datum : data) {\n        curveDates.push_back(datum.first);\n        curvePrices.push_back(datum.second);\n    }\n\n    // Build the curve using the data\n    populateCurve<InterpolatedPriceCurve>(asof, curveDates, curvePrices, dayCounter_,\n                                          parseCurrency(config->currency()));\n}\n\nvoid CommodityCurve::buildCrossCurrencyPriceCurve(\n    const Date& asof, const boost::shared_ptr<CommodityCurveConfig>& config,\n    const boost::shared_ptr<CommodityCurveConfig>& baseConfig, const FXTriangulation& fxSpots,\n    const map<string, boost::shared_ptr<YieldCurve>>& yieldCurves,\n    const map<string, boost::shared_ptr<CommodityCurve>>& commodityCurves) {\n\n    // Look up the required base price curve in the commodityCurves map\n    // We pass in the commodity curve ID only in the member basePriceCurveId of config e.g. PM:XAUUSD.\n    // But, the map commodityCurves is keyed on the spec name e.g. Commodity/USD/PM:XAUUSD\n    auto commIt = commodityCurves.find(CommodityCurveSpec(baseConfig->currency(), baseConfig->curveID()).name());\n    QL_REQUIRE(commIt != commodityCurves.end(), \"Could not find base commodity curve with id \"\n                                                    << baseConfig->curveID()\n                                                    << \" required in the building of commodity curve with id \"\n                                                    << config->curveID());\n\n    // Look up the two yield curves in the yieldCurves map\n    auto baseYtsIt = yieldCurves.find(YieldCurveSpec(baseConfig->currency(), config->baseYieldCurveId()).name());\n    QL_REQUIRE(baseYtsIt != yieldCurves.end(),\n               \"Could not find base yield curve with id \"\n                   << config->baseYieldCurveId() << \" and currency \" << baseConfig->currency()\n                   << \" required in the building of commodity curve with id \" << config->curveID());\n\n    auto ytsIt = yieldCurves.find(YieldCurveSpec(config->currency(), config->yieldCurveId()).name());\n    QL_REQUIRE(ytsIt != yieldCurves.end(), \"Could not find yield curve with id \"\n                                               << config->yieldCurveId() << \" and currency \" << config->currency()\n                                               << \" required in the building of commodity curve with id \"\n                                               << config->curveID());\n\n    // Get the FX spot rate, number of units of this currency per unit of base currency\n    Handle<Quote> fxSpot = fxSpots.getQuote(baseConfig->currency() + config->currency());\n\n    // Populate the commodityPriceCurve_ member\n    commodityPriceCurve_ = boost::make_shared<CrossCurrencyPriceTermStructure>(\n        asof, QuantLib::Handle<PriceTermStructure>(commIt->second->commodityPriceCurve()), fxSpot,\n        baseYtsIt->second->handle(), ytsIt->second->handle(), parseCurrency(config->currency()));\n}\n\nvoid CommodityCurve::buildBasisPriceCurve(const Date& asof, const CommodityCurveConfig& config,\n                                          const Conventions& conventions, const Handle<PriceTermStructure>& basePts,\n                                          const Loader& loader) {\n\n    LOG(\"CommodityCurve: start building commodity basis curve.\");\n\n    // We need to have commodity future conventions for both the base curve and the basis curve\n    QL_REQUIRE(conventions.has(config.conventionsId()), \"Commodity conventions \" << config.conventionsId()\n                                                                                 << \" requested by commodity config \"\n                                                                                 << config.curveID() << \" not found\");\n    auto basisConvention =\n        boost::dynamic_pointer_cast<CommodityFutureConvention>(conventions.get(config.conventionsId()));\n    QL_REQUIRE(basisConvention,\n               \"Convention \" << config.conventionsId() << \" not of expected type CommodityFutureConvention\");\n    auto basisFec = boost::make_shared<ConventionsBasedFutureExpiry>(*basisConvention);\n\n    QL_REQUIRE(conventions.has(config.baseConventionsId()),\n               \"Commodity conventions \" << config.baseConventionsId() << \" requested by commodity config \"\n                                        << config.curveID() << \" not found\");\n    auto baseConvention =\n        boost::dynamic_pointer_cast<CommodityFutureConvention>(conventions.get(config.baseConventionsId()));\n    QL_REQUIRE(baseConvention,\n               \"Convention \" << config.baseConventionsId() << \" not of expected type CommodityFutureConvention\");\n    auto baseFec = boost::make_shared<ConventionsBasedFutureExpiry>(*baseConvention);\n\n    // Construct the commodity index.\n    auto index = parseCommodityIndex(baseConvention->id(), conventions, false, basePts);\n\n    // Sort the configured quotes on expiry dates\n    // Ignore tenor based quotes i.e. we expect an explicit expiry date and log a warning if the expiry date does not\n    // match our own calculated expiry date based on the basis conventions.\n    map<Date, Handle<Quote>> basisData;\n    for (auto& q : getQuotes(asof, config.curveID(), config.fwdQuotes(), loader, true)) {\n\n        QL_REQUIRE(basisData.find(q->expiryDate()) == basisData.end(), \"Found duplicate quote, \"\n                                                                           << q->name() << \", for expiry date \"\n                                                                           << io::iso_date(q->expiryDate()) << \".\");\n\n        basisData[q->expiryDate()] = q->quote();\n        TLOG(\"Using quote \" << q->name() << \" in commodity basis curve.\");\n\n        // We expect the expiry date in the quotes to match our calculated expiry date. The code will work if it does\n        // not but we log a warning in this case.\n        Date calcExpiry = basisFec->nextExpiry(true, q->expiryDate());\n        if (calcExpiry != q->expiryDate()) {\n            WLOG(\"Calculated expiry date, \" << io::iso_date(calcExpiry) << \", does not equal quote's expiry date \"\n                                            << io::iso_date(q->expiryDate()) << \".\");\n        }\n    }\n\n    if (basisConvention->isAveraging()) {\n        // We are building a curve that will be used to return an average price.\n        if (!baseConvention->isAveraging() && config.averageBase()) {\n            DLOG(\"Creating a CommodityAverageBasisPriceCurve.\");\n            populateCurve<CommodityAverageBasisPriceCurve>(asof, basisData, basisFec, index,\n                basePts, baseFec, config.addBasis());\n        } else {\n            // Either 1) base convention is not averaging and config.averageBase() is false or 2) the base convention \n            // is averaging. Either way, we build a CommodityBasisPriceCurve.\n            DLOG(\"Creating a CommodityBasisPriceCurve for an average price curve.\");\n            populateCurve<CommodityBasisPriceCurve>(asof, basisData, basisFec, index, basePts,\n                baseFec, config.addBasis(), config.monthOffset());\n        }\n    } else {\n        // We are building a curve that will be used to return a price on a single date.\n        QL_REQUIRE(!baseConvention->isAveraging(), \"A commodity basis curve with non-averaging\" <<\n            \" basis and averaging base is not valid.\");\n\n        DLOG(\"Creating a CommodityBasisPriceCurve.\");\n        populateCurve<CommodityBasisPriceCurve>(asof, basisData, basisFec, index, basePts,\n            baseFec, config.addBasis(), config.monthOffset());\n    }\n\n    LOG(\"CommodityCurve: finished building commodity basis curve.\");\n}\n\n// Allow for more readable code in method below.\ntemplate<class I> using Crv = QuantExt::PiecewisePriceCurve<I, QuantExt::IterativeBootstrap>;\ntemplate<class C> using BS = QuantExt::IterativeBootstrap<C>;\n\nvoid CommodityCurve::buildPiecewiseCurve(const Date& asof, const CommodityCurveConfig& config,\n    const Conventions& conventions, const Loader& loader,\n    const map<string, boost::shared_ptr<CommodityCurve>>& commodityCurves) {\n\n    LOG(\"CommodityCurve: start building commodity piecewise curve.\");\n\n    // We store the instruments in a map. The key is the instrument's pillar date. The segments are ordered in \n    // priority so if we encounter the same pillar date later, we ignore it with a debug log.\n    map<Date, boost::shared_ptr<Helper>> mpInstruments;\n    const auto& priceSegments = config.priceSegments();\n    QL_REQUIRE(!priceSegments.empty(), \"CommodityCurve: need at least one price segment to build piecewise curve.\");\n    for (const auto& kv : priceSegments) {\n        if (kv.second.type() != PriceSegment::Type::OffPeakPowerDaily) {\n            addInstruments(asof, loader, config.curveID(), config.currency(), kv.second,\n                conventions, commodityCurves, mpInstruments);\n        } else {\n            addOffPeakPowerInstruments(asof, loader, config.curveID(), kv.second, conventions, mpInstruments);\n        }\n    }\n\n    // Populate the vector of helpers.\n    vector<boost::shared_ptr<Helper>> instruments;\n    instruments.reserve(mpInstruments.size());\n    for (const auto& kv : mpInstruments) {\n        instruments.push_back(kv.second);\n    }\n\n    // Use bootstrap configuration if provided.\n    BootstrapConfig bc;\n    if (config.bootstrapConfig()) {\n        bc = *config.bootstrapConfig();\n    }\n    Real acc = bc.accuracy();\n    Real globalAcc = bc.globalAccuracy();\n    bool noThrow = bc.dontThrow();\n    Size maxAttempts = bc.maxAttempts();\n    Real maxF = bc.maxFactor();\n    Real minF = bc.minFactor();\n    Size noThrowSteps = bc.dontThrowSteps();\n\n    // Create curve based on interpolation method provided.\n    Currency ccy = parseCurrency(config.currency());\n    if (interpolationMethod_ == \"Linear\") {\n        BS<Crv<Linear>> bs(acc, globalAcc, noThrow, maxAttempts, maxF, minF, noThrowSteps);\n        commodityPriceCurve_ = boost::make_shared<Crv<Linear>>(asof, instruments, dayCounter_, ccy, Linear(), bs);\n    } else if (interpolationMethod_ == \"LogLinear\") {\n        BS<Crv<QuantLib::LogLinear>> bs(acc, globalAcc, noThrow, maxAttempts, maxF, minF, noThrowSteps);\n        commodityPriceCurve_ = boost::make_shared<Crv<QuantLib::LogLinear>>(asof, instruments,\n            dayCounter_, ccy, QuantLib::LogLinear(), bs);\n    } else if (interpolationMethod_ == \"Cubic\") {\n        BS<Crv<QuantLib::Cubic>> bs(acc, globalAcc, noThrow, maxAttempts, maxF, minF, noThrowSteps);\n        commodityPriceCurve_ = boost::make_shared<Crv<QuantLib::Cubic>>(asof, instruments,\n            dayCounter_, ccy, QuantLib::Cubic(), bs);\n    } else if (interpolationMethod_ == \"LinearFlat\") {\n        BS<Crv<QuantExt::LinearFlat>> bs(acc, globalAcc, noThrow, maxAttempts, maxF, minF, noThrowSteps);\n        commodityPriceCurve_ = boost::make_shared<Crv<QuantExt::LinearFlat>>(asof, instruments,\n            dayCounter_, ccy, QuantExt::LinearFlat(), bs);\n    } else if (interpolationMethod_ == \"LogLinearFlat\") {\n        BS<Crv<QuantExt::LogLinearFlat>> bs(acc, globalAcc, noThrow, maxAttempts, maxF, minF, noThrowSteps);\n        commodityPriceCurve_ = boost::make_shared<Crv<QuantExt::LogLinearFlat>>(asof, instruments,\n            dayCounter_, ccy, QuantExt::LogLinearFlat(), bs);\n    } else if (interpolationMethod_ == \"CubicFlat\") {\n        BS<Crv<QuantExt::CubicFlat>> bs(acc, globalAcc, noThrow, maxAttempts, maxF, minF, noThrowSteps);\n        commodityPriceCurve_ = boost::make_shared<Crv<QuantExt::CubicFlat>>(asof, instruments,\n            dayCounter_, ccy, QuantExt::CubicFlat(), bs);\n    } else if (interpolationMethod_ == \"BackwardFlat\") {\n        BS<Crv<BackwardFlat>> bs(acc, globalAcc, noThrow, maxAttempts, maxF, minF, noThrowSteps);\n        commodityPriceCurve_ = boost::make_shared<Crv<BackwardFlat>>(asof, instruments,\n            dayCounter_, ccy, BackwardFlat(), bs);\n    } else {\n        QL_FAIL(\"The interpolation method, \" << interpolationMethod_ << \", is not supported.\");\n    }\n\n    LOG(\"CommodityCurve: finished building commodity piecewise curve.\");\n}\n\nvector<boost::shared_ptr<CommodityForwardQuote>>\nCommodityCurve::getQuotes(const Date& asof, const string& configId, const vector<string>& quotes,\n    const Loader& loader, bool filter) {\n\n    LOG(\"CommodityCurve: start getting configured commodity quotes.\");\n\n    // Check if we are using a regular expression to select the quotes for the curve. If we are, the quotes should\n    // contain exactly one element.\n    auto wildcard = getUniqueWildcard(quotes);\n    regexQuotes_ = wildcard != boost::none;\n\n    // Add the relevant forward quotes to the result vector\n    vector<boost::shared_ptr<CommodityForwardQuote>> result;\n    for (auto& md : loader.loadQuotes(asof)) {\n\n        // Only looking for quotes on asof date, with quote type PRICE and instrument type commodity forward\n        if (md->asofDate() == asof && md->quoteType() == MarketDatum::QuoteType::PRICE &&\n            md->instrumentType() == MarketDatum::InstrumentType::COMMODITY_FWD) {\n\n            boost::shared_ptr<CommodityForwardQuote> q = boost::dynamic_pointer_cast<CommodityForwardQuote>(md);\n\n            // Check if the quote is requested by the config and if it isn't continue to the next quote\n            if (!wildcard) {\n                vector<string>::const_iterator it =\n                    find(quotes.begin(), quotes.end(), q->name());\n                if (it == quotes.end())\n                    continue;\n            } else {\n                if (!(*wildcard).matches(q->name()))\n                    continue;\n            }\n\n            // If filter is true, remove tenor based quotes and quotes with expiry before asof.\n            if (filter) {\n                if (q->tenorBased()) {\n                    TLOG(\"Skipping tenor based quote, \" << q->name() << \".\");\n                    continue;\n                }\n                if (q->expiryDate() < asof) {\n                    TLOG(\"Skipping quote because its expiry date, \" << io::iso_date(q->expiryDate())\n                        << \", is before the market date \" << io::iso_date(asof));\n                    continue;\n                }\n            }\n\n            // If we make it here, the quote is relevant.\n            result.push_back(q);\n            TLOG(\"Added quote \" << q->name() << \".\");\n        }\n    }\n\n    LOG(\"CommodityCurve: finished getting configured commodity quotes.\");\n\n    return result;\n}\n\nvoid CommodityCurve::addInstruments(const Date& asof, const Loader& loader, const string& configId,\n    const string& currency, const PriceSegment& priceSegment, const Conventions& conventions,\n    const map<string, boost::shared_ptr<CommodityCurve>>& commodityCurves,\n    map<Date, boost::shared_ptr<Helper>>& instruments) {\n\n    using PST = PriceSegment::Type;\n    using AD = CommodityFutureConvention::AveragingData;\n    PST type = priceSegment.type();\n\n    // Pre-populate some variables if averaging segment.\n    boost::shared_ptr<CommodityFutureConvention> convention;\n    AD ad;\n    boost::shared_ptr<CommodityIndex> index;\n    boost::shared_ptr<FutureExpiryCalculator> uFec;\n    if (type == PST::AveragingFuture || type == PST::AveragingSpot || type == PST::AveragingOffPeakPower) {\n\n        // Get the associated averaging commodity future convention.\n        convention = boost::dynamic_pointer_cast<CommodityFutureConvention>(\n            conventions.get(priceSegment.conventionsId()));\n        QL_REQUIRE(convention, \"Convention \" << priceSegment.conventionsId() <<\n            \" not of expected type CommodityFutureConvention.\");\n\n        ad = convention->averagingData();\n        QL_REQUIRE(!ad.empty(), \"CommodityCurve: convention \" << convention->id() <<\n            \" should have non-empty averaging data for piecewise price curve construction.\");\n\n        // The commodity index for which we are building a price curve.\n        index = parseCommodityIndex(ad.commodityName(), conventions, false);\n\n        // If referencing a future, we need conventions for the underlying future that is being averaged.\n        if (type == PST::AveragingFuture || type == PST::AveragingOffPeakPower) {\n\n            auto uConvention = boost::dynamic_pointer_cast<CommodityFutureConvention>(\n                conventions.get(ad.conventionsId()));\n            QL_REQUIRE(uConvention, \"Convention \" << priceSegment.conventionsId() <<\n                \" not of expected type CommodityFutureConvention.\");\n            uFec = boost::make_shared<ConventionsBasedFutureExpiry>(*uConvention);\n\n            if (ad.dailyExpiryOffset() != Null<Natural>() && ad.dailyExpiryOffset() > 0) {\n                QL_REQUIRE(uConvention->contractFrequency() == Daily, \"CommodityCurve: the averaging data has\" <<\n                    \" a positive DailyExpiryOffset (\" << ad.dailyExpiryOffset() << \") but the underlying future\" <<\n                    \" contract frequency is not daily (\" << uConvention->contractFrequency() << \").\");\n            }\n        }\n\n    }\n\n    // Pre-populate some variables if the price segment is AveragingOffPeakPower.\n    boost::shared_ptr<CommodityIndex> peakIndex;\n    Natural peakHoursPerDay = 16;\n    Calendar peakCalendar;\n    if (type == PST::AveragingOffPeakPower) {\n\n        // Look up the peak price curve in the commodityCurves map\n        const string& ppId = priceSegment.peakPriceCurveId();\n        QL_REQUIRE(!ppId.empty(), \"CommodityCurve: AveragingOffPeakPower segment in \" <<\n            \" curve configuration \" << configId << \" does not provide a peak price curve ID.\");\n        CommodityCurveSpec ccSpec(currency, ppId);\n        DLOG(\"Looking for peak price curve with id, \" << ppId << \", and spec, \" << ccSpec << \".\");\n        auto itCc = commodityCurves.find(ccSpec.name());\n        QL_REQUIRE(itCc != commodityCurves.end(), \"Can't find peak price curve with id \" << ppId);\n        auto peakPts = Handle<PriceTermStructure>(itCc->second->commodityPriceCurve());\n\n        // Create the daily peak price index linked to the peak price term structure.\n        peakIndex = parseCommodityIndex(ppId, conventions, false, peakPts);\n\n        // Calendar defining the peak business days.\n        peakCalendar = parseCalendar(priceSegment.peakPriceCalendar());\n\n        // Look up the conventions for the peak price commodity to determine peak hours per day.\n        if (conventions.has(ppId)) {\n            auto peakConvention = boost::dynamic_pointer_cast<CommodityFutureConvention>(conventions.get(ppId));\n            if (peakConvention && peakConvention->hoursPerDay() != Null<Natural>()) {\n                peakHoursPerDay = peakConvention->hoursPerDay();\n            }\n        }\n    }\n\n    // Get the relevant quotes\n    auto quotes = getQuotes(asof, configId, priceSegment.quotes(), loader, true);\n\n    // Add an instrument for each relevant quote.\n    for (const auto& quote : quotes) {\n\n        const Date& expiry = quote->expiryDate();\n        switch (type) {\n        case PST::Future:\n            if (expiry == asof) {\n                TLOG(\"Quote \" << quote->name() << \" has expiry date \" << io::iso_date(expiry) << \" equal to asof\" <<\n                    \" so not adding to instruments. Attempt to add as fixing instead.\");\n                addMarketFixing(priceSegment.conventionsId(), expiry, quote->quote()->value(), conventions);\n            } else if (instruments.count(expiry) == 0) {\n                instruments[expiry] = boost::make_shared<FuturePriceHelper>(quote->quote(), expiry);\n            } else {\n                TLOG(\"Skipping quote, \" << quote->name() << \", because its expiry date, \" <<\n                    io::iso_date(expiry) << \", is already in the instrument set.\");\n            }\n            break;\n\n        // An averaging future referencing an underlying future or spot. Setup is similar.\n        case PST::AveragingFuture:\n        case PST::AveragingSpot:\n        case PST::AveragingOffPeakPower: {\n\n            // Determine the calculation period.\n            using ADCP = AD::CalculationPeriod;\n            Date start;\n            Date end;\n            if (ad.period() == ADCP::ExpiryToExpiry) {\n\n                auto fec = boost::make_shared<ConventionsBasedFutureExpiry>(*convention);\n                end = fec->nextExpiry(true, expiry);\n                if (end != expiry) {\n                    WLOG(\"Calculated expiry date, \" << io::iso_date(end) << \", does not equal quote's expiry date \"\n                        << io::iso_date(expiry) << \". Proceed with quote's expiry.\");\n                }\n                start = fec->priorExpiry(false, end) + 1;\n\n            } else if (ad.period() == ADCP::PreviousMonth) {\n\n                end = Date::endOfMonth(expiry - 1 * Months);\n                start = Date(1, end.month(), end.year());\n            }\n\n            boost::shared_ptr<Helper> helper;\n            if (type == PST::AveragingOffPeakPower) {\n                TLOG(\"Building average off-peak power helper from quote, \" << quote->name() << \".\");\n                helper = boost::make_shared<AverageOffPeakPowerHelper>(quote->quote(), index, start,\n                    end, uFec, peakIndex, peakCalendar, peakHoursPerDay);\n            } else {\n                TLOG(\"Building average future price helper from quote, \" << quote->name() << \".\");\n                helper = boost::make_shared<AverageFuturePriceHelper>(quote->quote(), index, start, end, uFec,\n                    ad.pricingCalendar(), ad.deliveryRollDays(), ad.futureMonthOffset(), ad.useBusinessDays(),\n                    ad.dailyExpiryOffset());\n            }\n\n            // Only add to instruments if an instrument with the same pillar date is not there already.\n            Date pillar = helper->pillarDate();\n            if (instruments.count(pillar) == 0) {\n                instruments[pillar] = helper;\n            } else {\n                TLOG(\"Skipping quote, \" << quote->name() << \", because an instrument with its pillar date, \" <<\n                    io::iso_date(pillar) << \", is already in the instrument set.\");\n            }\n            break;\n        }\n\n        default:\n            QL_FAIL(\"CommodityCurve: unrecognised price segment type.\");\n            break;\n        }\n    }\n}\n\nvoid CommodityCurve::addOffPeakPowerInstruments(const Date& asof, const Loader& loader, const string& configId,\n    const PriceSegment& priceSegment, const Conventions& conventions,\n    map<Date, boost::shared_ptr<Helper>>& instruments) {\n\n    // Check that we have been called with the expected segment type.\n    using PST = PriceSegment::Type;\n    QL_REQUIRE(priceSegment.type() == PST::OffPeakPowerDaily, \"Expecting a price segment type of OffPeakPowerDaily.\");\n\n    // Check we have a commodity future convention for the price segment.\n    const string& convId = priceSegment.conventionsId();\n    auto p = conventions.get(convId, Convention::Type::CommodityFuture);\n    QL_REQUIRE(p.first, \"Could not get conventions with id \" << convId << \" for OffPeakPowerDaily price segment\" <<\n        \" in curve configuration \" << configId << \".\");\n    auto convention = boost::dynamic_pointer_cast<CommodityFutureConvention>(p.second);\n\n    // Check that the commodity future convention has off-peak information for the name.\n    const auto& oppIdxData = convention->offPeakPowerIndexData();\n    QL_REQUIRE(oppIdxData, \"Conventions with id \" << convId << \" for OffPeakPowerDaily price segment\" <<\n        \" should have an OffPeakPowerIndexData section.\");\n    Real offPeakHours = oppIdxData->offPeakHours();\n    TLOG(\"Off-peak hours is \" << offPeakHours);\n    const Calendar& peakCalendar = oppIdxData->peakCalendar();\n\n    // Check that the price segment has off-peak daily section.\n    const auto& opd = priceSegment.offPeakDaily();\n    QL_REQUIRE(opd, \"The OffPeakPowerDaily price segment for curve configuration \" << configId <<\n        \" should have an OffPeakDaily section.\");\n\n    // Get all the peak and off-peak quotes that we have and store them in a map. The map key is the expiry date and \n    // the map value is a pair of values the first being the off-peak value for that expiry and the second being the \n    // peak value for that expiry. We only need the peak portion to form the quote on peakCalendar holidays. We need \n    // the off-peak portion always.\n    map<Date, pair<Real, Real>> quotes;\n\n    auto opqs = getQuotes(asof, configId, opd->offPeakQuotes(), loader, true);\n    for (const auto& q : opqs) {\n        Real value = q->quote()->value();\n        Date expiry = q->expiryDate();\n        if (quotes.count(expiry) != 0) {\n            TLOG(\"Already have off-peak quote with expiry \" << io::iso_date(expiry) << \" so skipping \" << q->name());\n        } else {\n            TLOG(\"Adding off-peak quote \" << q->name() << \": \" << io::iso_date(expiry) << \",\" << value);\n            quotes[expiry] = make_pair(value, Null<Real>());\n        }\n    }\n\n    auto pqs = getQuotes(asof, configId, opd->peakQuotes(), loader, true);\n    for (const auto& q : pqs) {\n        Real value = q->quote()->value();\n        Date expiry = q->expiryDate();\n        auto it = quotes.find(expiry);\n        if (it == quotes.end()) {\n            TLOG(\"Have no off-peak quote with expiry \" << io::iso_date(expiry) << \" so skipping \" << q->name());\n        } else if (it->second.second != Null<Real>()) {\n            TLOG(\"Already have a peak quote with expiry \" << io::iso_date(expiry) << \" so skipping \" << q->name());\n        } else {\n            TLOG(\"Adding peak quote \" << q->name() << \": \" << io::iso_date(expiry) << \",\" << value);\n            it->second.second = value;\n        }\n    }\n\n    // Now, use the quotes to create the future instruments in the curve.\n    for (const auto& kv : quotes) {\n\n        // If the expiry is already in the instrument set, we skip it.\n        const Date& expiry = kv.first;\n        if (instruments.count(expiry) != 0) {\n            TLOG(\"Skipping expiry \" << io::iso_date(expiry) << \" because it is already in the instrument set.\");\n            continue;\n        }\n\n        // If the expiry is equal to the asof, we add fixings.\n        if (expiry == asof) {\n            TLOG(\"The off-peak power expiry date \" << io::iso_date(expiry) << \" is equal to asof\" <<\n                \" so not adding to instruments. Attempt to add fixing(s) instead.\");\n            if (peakCalendar.isHoliday(expiry) && kv.second.second == Null<Real>()) {\n                DLOG(\"The peak portion of the quote on holiday \" << io::iso_date(expiry) <<\n                    \" is missing so can't add fixings.\");\n            } else {\n                // Add the off-peak and if necessary peak fixing\n                addMarketFixing(oppIdxData->offPeakIndex(), expiry, kv.second.first, conventions);\n                if (peakCalendar.isHoliday(expiry))\n                    addMarketFixing(oppIdxData->peakIndex(), expiry, kv.second.second, conventions);\n            }\n            continue;\n        }\n\n        // Determine the quote that we will use in the future instrument for this expiry.\n        Real quote = 0.0;\n        if (peakCalendar.isHoliday(expiry)) {\n            Real peakValue = kv.second.second;\n            if (peakValue == Null<Real>()) {\n                DLOG(\"The peak portion of the quote on holiday \" << io::iso_date(expiry) << \" is missing so skip.\");\n                continue;\n            } else {\n                Real offPeakValue = kv.second.first;\n                quote = (offPeakHours * offPeakValue + (24.0 - offPeakHours) * peakValue) / 24.0;\n                TLOG(\"The quote on holiday \" << io::iso_date(expiry) << \" is \" << quote << \". (off-peak,peak) is\" <<\n                    \" (\" << offPeakValue << \",\" << peakValue << \").\");\n            }\n        } else {\n            quote = kv.second.first;\n            TLOG(\"The quote on business day \" << io::iso_date(expiry) << \" is the off-peak value \" << quote << \".\");\n        }\n\n        // Add the future helper for this expiry.\n        instruments[expiry] = boost::make_shared<FuturePriceHelper>(quote, expiry);\n\n    }\n}\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "2b60e54343c02e505439f48a0b8bd53ee0fa7c09", "size": 41204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/marketdata/commoditycurve.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": "OREData/ored/marketdata/commoditycurve.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": "OREData/ored/marketdata/commoditycurve.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": 50.4332925337, "max_line_length": 121, "alphanum_fraction": 0.6269536938, "num_tokens": 9335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.18681030966205514}}
{"text": "\n//#include \"OBB.hpp\"\n#include <stdio.h>\n// ifstream::is_open\n#include <fstream>\n#include <rwsim/dynamics/OBRManifold.hpp>\n#include <vector>\n\n#include <rw/math/LinearAlgebra.hpp>\n#include <rw/math/Vector3D.hpp>\n#include <rwsim/dynamics/ContactPoint.hpp>\n#include <rwsim/dynamics/ContactCluster.hpp>\n\n#include <boost/numeric/conversion/cast.hpp>\n\nusing namespace rw::math;\nusing namespace rwsim::dynamics;\n\n\nContactPoint makeContact(double x,double y,double z, double pen, Vector3D<> normal){\n    normal = normalize(normal);\n    ContactPoint point;\n    Transform3D<> wTa(Transform3D<>::identity());\n    Transform3D<> wTb(Transform3D<>::identity());\n    point.p = Vector3D<>(x,y,z);\n    point.penetration = pen;\n    point.n = normal;\n    point.pA = inverse(wTa) * (point.p - point.n*0.005);\n    point.pB = inverse(wTb) * (point.p + point.n*0.005);\n    return point;\n}\n\nContactPoint makeContact(double x,double y,double z, double nx,double ny,double nz, double pen){\n    return makeContact(x,y,z,pen,Vector3D<>(nx,ny,nz));\n}\n\n/**\n * @brief Contact manifold based on Oriented Bounding Boxes\n */\nclass OBBManifold {\npublic:\n    /**\n     * @brief\n     * @param thres\n     * @param sepThres\n     * @return\n     */\n    OBBManifold(double thres = 0.03, double sepThres = 0.01):\n        _nrOfContacts(0),\n        _deepestIdx(0),\n        _threshold(thres),\n        _sepThreshold(sepThres)\n    {};\n\n    virtual ~OBBManifold(){};\n\n    /**\n     * @brief adds and updates the manifold with a new point\n     * @param p\n     */\n    void addPoint(ContactPoint& p){\n        if( !inManifold(p) )\n            RW_THROW(\"Not in manifold\");\n\n        // handle if we have less than 5 points\n        if(_nrOfContacts==5){\n            // if the point is inside the obb then we only need to check if its\n            // deeper than the deepest point and if it s replace it\n            if( isInsideOBB(p.p) ){\n                if(_points[_deepestIdx].penetration<p.penetration)\n                    _points[_deepestIdx] = p;\n                return;\n            }\n            // if its outside then we need to remove another point\n            fit(p);\n            // find the point closest to center of obb\n            int minIdx = -1;\n            double minDist = MetricUtil::dist1(p.p,_t3d.P());\n            for(int i=0;i<5;i++){\n                double dist = MetricUtil::dist1(_points[i].p,_t3d.P());\n                if( dist<minDist && _deepestIdx!=i ){\n                    minIdx = i;\n                    minDist = dist;\n                }\n            }\n            if(minIdx<0)\n                return;\n            _points[minIdx] = p;\n            if( _points[_deepestIdx].penetration>p.penetration )\n                _deepestIdx = minIdx;\n        } else if(_nrOfContacts>1) {\n            fit(p);\n            _normal = p.n;\n            _points[_nrOfContacts] = p;\n            _nrOfContacts++;\n            _deepestIdx = 0;\n        } else if(_nrOfContacts==1) {\n            _normal = (p.n + _points[0].n)/2;\n            _points[_nrOfContacts] = p;\n            _t3d.P() = (p.p + _points[0].p)/2;\n            if( _points[_deepestIdx].penetration>p.penetration )\n                _deepestIdx = _nrOfContacts;\n            _nrOfContacts++;\n        } else {\n            _normal = p.n;\n            _points[0] = p;\n            _t3d.P() = p.p;\n            _deepestIdx = 0;\n            _nrOfContacts++;\n        }\n    }\n\n    void update(const Transform3D<> &aT, const Transform3D<> &bT){\n        // update the position of the contact pointshttp://www.cplusplus.com/reference/iostream/ifstream/\n        for(int i=0; i<_nrOfContacts; i++){\n            const Vector3D<>& wPa = aT * _points[i].pA;\n            const Vector3D<>& wPb = bT * _points[i].pB;\n            if( MetricUtil::dist2(wPa,wPb)> _sepThreshold ){\n                //remove point\n                _nrOfContacts--;\n                _points[i] = _points[_nrOfContacts];\n                i--;\n            } else {\n                _points[i].p = (wPa+wPb)/2;\n            }\n        }\n    }\n\n    int getNrOfContacts(){ return _nrOfContacts; };\n\n    bool inManifold(ContactPoint& p){\n\n        if( _nrOfContacts==0 ){\n            return true;\n        } else if( _nrOfContacts == 1){\n            // check distance to the deepest point\n            const double dist = MetricUtil::dist2(p.p,_points[_deepestIdx].p);\n            std::cout << \"1: Dist too point: \" << dist << std::endl;\n            if( dist <_threshold ) return true;\n            else return false;\n        } else if( _nrOfContacts == 2 ){\n            // check distance to the line\n            const double dist = MetricUtil::dist2(p.p,_points[_deepestIdx].p);\n            std::cout << \"1: Dist too point: \" << dist << std::endl;\n            if( dist <_threshold ) return true;\n            else return false;\n/*            const Vector3D<> &p1 = p.p;\n            const Vector3D<> &x1 = _points[0].p;\n            const Vector3D<> &x2 = _points[1].p;\n            double dist = MetricUtil::norm2(cross((x2-x1),(x1-p1)))/\n                          MetricUtil::norm2((x2-x1));\n            if( dist <_threshold ) return true;\n            else return false;*/\n        } else {\n            const double dist = MetricUtil::dist2(p.p,_points[_deepestIdx].p);\n            if( dist <_threshold ) return true;\n            // check if the point is inside the manifold box\n            // project it onto the plane\n            return isInsideOBB(p.p);\n        }\n    }\n\n    /**\n     * @brief fits a new manifold to the list of contact points\n     * @param p\n     */\n    void fit(ContactPoint& p){\n        // re-fit the bounding box\n        Eigen::MatrixXd covar( Eigen::MatrixXd::Zero(3, 3) );\n        Vector3D<> c = p.p+_points[0].p+_points[1].p;\n        covar(0,0) += _points[0].p(0)*_points[0].p(0) +\n                      _points[1].p(0)*_points[1].p(0) +\n                      p.p(0)+p.p(0);\n        covar(1,1) += _points[0].p(1)*_points[0].p(1) +\n                      _points[1].p(1)*_points[1].p(1) +\n                      p.p(1)+p.p(1);\n        covar(2,2) += _points[0].p(2)*_points[0].p(2) +\n                      _points[1].p(2)*_points[1].p(2) +\n                      p.p(2)+p.p(2);\n        covar(0,1) += _points[0].p(0)*_points[0].p(1) +\n                      _points[1].p(0)*_points[1].p(1) +\n                      p.p(0)+p.p(1);\n        covar(0,2) += _points[0].p(0)*_points[0].p(2) +\n                      _points[1].p(0)*_points[1].p(2) +\n                      p.p(0)+p.p(2);\n        covar(1,2) += _points[0].p(1)*_points[0].p(2) +\n                      _points[1].p(1)*_points[1].p(2) +\n                      p.p(1)+p.p(2);\n\n        for(int i=2; i<_nrOfContacts;i++){\n            const Vector3D<> &point = _points[i].p;\n            c += point;\n            covar(0,0) += point(0)*point(0);\n            covar(1,1) += point(1)*point(1);\n            covar(2,2) += point(2)*point(2);\n            covar(0,1) += point(0)*point(1);\n            covar(0,2) += point(0)*point(2);\n            covar(1,2) += point(1)*point(2);\n        }\n        const int n = _nrOfContacts+1;\n        covar(0,0) = covar(0,0)-c(0)*c(0)/n;\n        covar(1,1) = covar(1,1)-c(1)*c(1)/n;\n        covar(2,2) = covar(2,2)-c(2)*c(2)/n;\n        covar(0,1) = covar(0,1)-c(0)*c(1)/n;\n        covar(0,2) = covar(0,2)-c(0)*c(2)/n;\n        covar(1,2) = covar(1,2)-c(1)*c(2)/n;\n        covar(1,0) = covar(0,1);\n        covar(2,0) = covar(0,2);\n        covar(2,1) = covar(1,2);\n\n        typedef std::pair<Eigen::MatrixXd,Eigen::VectorXd> ResultType;\n        //std::cout << \"COVAR: \" << covar << std::endl;\n        ResultType res = LinearAlgebra::eigenDecompositionSymmetric( covar );\n\n        // 4.1 create the rotationmatrix from the normalized eigenvectors\n        // find max and the second maximal eigenvalue\n        size_t maxEigIdx=2, midEigIdx=1, minEigIdx=0;\n        double maxEigVal = res.second(maxEigIdx);\n        double midEigVal = res.second(midEigIdx);\n        double minEigVal = res.second(minEigIdx);\n        if( maxEigVal < midEigVal ){\n            std::swap(midEigVal,maxEigVal);\n            std::swap(midEigIdx,maxEigIdx);\n        }\n        if( minEigVal>midEigVal ){\n            std::swap(midEigVal,minEigVal);\n            std::swap(midEigIdx,minEigIdx);\n            if( midEigVal>maxEigVal ){\n                std::swap(midEigVal,maxEigVal);\n                std::swap(midEigIdx,maxEigIdx);\n            }\n        }\n        // specify x and y axis, x will be the axis with largest spred\n        Vector3D<> maxAxis( res.first(0,maxEigIdx), res.first(1,maxEigIdx), res.first(2,maxEigIdx) );\n        Vector3D<> midAxis( res.first(0,midEigIdx), res.first(1,midEigIdx), res.first(2,midEigIdx) );\n\n        // make sure to turn the z-axis in the direction of the normal\n        Vector3D<> crossAxis = cross(maxAxis,midAxis);\n        if( dot(crossAxis,_points[_deepestIdx].n)<0 ){\n            std::swap(maxAxis,midAxis);\n            crossAxis = -crossAxis;\n        }\n\n        _normal = normalize(crossAxis);\n\n        const Rotation3D<> rot(normalize(maxAxis),normalize(midAxis), _normal);\n        const Rotation3D<> rotInv = inverse( rot );\n\n        Vector3D<> max = rotInv * p.p;\n        Vector3D<> min = max;\n        for(int i = 0; i<_nrOfContacts; i++ ){\n            const Vector3D<> prot = rotInv * _points[i].p;\n            if( prot(0)>max(0) ) max(0) = prot(0);\n            else if( prot(0)<min(0) ) min(0) = prot(0);\n            if( prot(1)>max(1) ) max(1) = prot(1);\n            else if( prot(1)<min(1) ) min(1) = prot(1);\n            if( prot(2)>max(2) ) max(2) = prot(2);\n            else if( prot(2)<min(2) ) min(2) = prot(2);\n        }\n\n        // compute halflength of box and its midpoint\n        _t3d.P() = rot*( 0.5*(max+min));\n        _t3d.R() = rot;\n        _h = 0.5*(max-min);\n    }\n\n    Vector3D<> getNormal(){\n        return _normal;\n    }\n\n    Transform3D<> getTransform(){ return _t3d;};\n\n    Vector3D<> getHalfLengths(){ return _h; };\n\nprivate:\n    bool isInsideOBB(Vector3D<>& p){\n\n        Vector3D<> pproj = inverse(_t3d) * p;\n        if( fabs(pproj(0))<_h(0) && fabs(pproj(1))<_h(1) ){\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * The normal is an average of the normals of the contact normals until 3\n     * or more contacts are available. Then the normal becomes the z axis in\n     * the OBB that the contacts span\n     */\n    Vector3D<> _normal; //\n    Transform3D<> _t3d; // transform of the obb\n    Vector3D<> _h; //halflengths off the obb\n    // only used when 3 or more points are available\n    ContactPoint _points[5];\n    //Frame *_objA,*_objB;\n    int _nrOfContacts,_deepestIdx;\n    double _threshold,_sepThreshold;\n};\n\nstd::pair<Transform3D<>, Vector3D<> > fit(std::vector<ContactPoint>& points){\n    // re-fit the bounding box\n    Eigen::MatrixXd covar( Eigen::MatrixXd::Zero(3, 3) );\n    const std::size_t nrContacts = points.size();\n    Vector3D<> c;\n    for(ContactPoint &p : points) {\n        c += p.p;\n        covar(0,0) += p.p(0)+p.p(0);\n        covar(1,1) += p.p(1)+p.p(1);\n        covar(2,2) += p.p(2)+p.p(2);\n        covar(0,1) += p.p(0)+p.p(1);\n        covar(0,2) += p.p(0)+p.p(2);\n        covar(1,2) += p.p(1)+p.p(2);\n    }\n\n    const std::size_t n = nrContacts;\n    covar(0,0) = covar(0,0)-c(0)*c(0)/n;\n    covar(1,1) = covar(1,1)-c(1)*c(1)/n;\n    covar(2,2) = covar(2,2)-c(2)*c(2)/n;\n    covar(0,1) = covar(0,1)-c(0)*c(1)/n;\n    covar(0,2) = covar(0,2)-c(0)*c(2)/n;\n    covar(1,2) = covar(1,2)-c(1)*c(2)/n;\n    covar(1,0) = covar(0,1);\n    covar(2,0) = covar(0,2);\n    covar(2,1) = covar(1,2);\n\n    typedef std::pair<Eigen::MatrixXd,Eigen::VectorXd> ResultType;\n    //std::cout << \"COVAR: \" << covar << std::endl;\n    ResultType res = LinearAlgebra::eigenDecompositionSymmetric( covar );\n\n    // 4.1 create the rotationmatrix from the normalized eigenvectors\n    // find max and the second maximal eigenvalue\n    size_t maxEigIdx=2, midEigIdx=1, minEigIdx=0;\n    double maxEigVal = res.second(maxEigIdx);\n    double midEigVal = res.second(midEigIdx);\n    double minEigVal = res.second(minEigIdx);\n    if( maxEigVal < midEigVal ){\n        std::swap(midEigVal,maxEigVal);\n        std::swap(midEigIdx,maxEigIdx);\n    }\n    if( minEigVal>midEigVal ){\n        std::swap(midEigVal,minEigVal);\n        std::swap(midEigIdx,minEigIdx);\n        if( midEigVal>maxEigVal ){\n            std::swap(midEigVal,maxEigVal);\n            std::swap(midEigIdx,maxEigIdx);\n        }\n    }\n    // specify x and y axis, x will be the axis with largest spred\n    Vector3D<> maxAxis( res.first(0,maxEigIdx), res.first(1,maxEigIdx), res.first(2,maxEigIdx) );\n    Vector3D<> midAxis( res.first(0,midEigIdx), res.first(1,midEigIdx), res.first(2,midEigIdx) );\n\n    // make sure to turn the z-axis in the direction of the normal\n    Vector3D<> crossAxis = cross(maxAxis,midAxis);\n\n    Vector3D<> normal = normalize(crossAxis);\n\n    const Rotation3D<> rot(normalize(maxAxis),normalize(midAxis), normal);\n    const Rotation3D<> rotInv = inverse( rot );\n\n    Vector3D<> max = rotInv * points[0].p;\n    Vector3D<> min = max;\n    for(std::size_t i = 0; i < nrContacts; i++) {\n        const Vector3D<> prot = rotInv * points[i].p;\n        if( prot(0)>max(0) ) max(0) = prot(0);\n        else if( prot(0)<min(0) ) min(0) = prot(0);\n        if( prot(1)>max(1) ) max(1) = prot(1);\n        else if( prot(1)<min(1) ) min(1) = prot(1);\n        if( prot(2)>max(2) ) max(2) = prot(2);\n        else if( prot(2)<min(2) ) min(2) = prot(2);\n    }\n\n    // compute halflength of box and its midpoint\n    Transform3D<> t3d;\n    t3d.P() = rot*( 0.5*(max+min));\n    t3d.R() = rot;\n    Vector3D<> h = 0.5*(max-min);\n    return std::make_pair(t3d,h);\n}\n\n\n\nstd::vector<ContactPoint> loadContacts(std::string filename){\n    std::vector<ContactPoint> contacts;\n    std::ifstream in;\n    in.open(filename.c_str());\n    char line[200];\n    while( !in.eof() ){\n        if(in.eof())\n           break;\n\n        in.getline(line,200);\n        std::cout << \".\";\n        if(line[0]==';')\n            continue;\n        if(line[0]==0)\n            continue;\n        if(line[0]=='\\n')\n            continue;\n        float x,y,z,nx,ny,nz,pen;\n\n        sscanf(line, \"%f %f %f %f %f %f %f\", &x, &y, &z,&nx, &ny, &nz,&pen);\n\n        contacts.push_back( makeContact(x,y,z,nx,ny,nz,pen) );\n\n    }\n    return contacts;\n}\n\nint main(int argc, char** argv)\n{\n\n\tif( argc < 2 ){\n\t    std::cout << \"Arg 1 is input Filename!\" << std::endl;\n\t\tstd::cout << \"Arg 2 is cluster threshold distance!\" << std::endl;\n\t\tstd::cout << \"Arg 3 is manifold threshold!\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tstd::string filename(argv[1]);\n\n\tdouble n = 10*Deg2Rad;\n\tif(argc>2)\n\t    n = (double) std::atof(argv[2]);\n\n    /*Unused:\n     float mThres = 1.0;\n     if(argc>3)\n\t\tmThres = std::atof(argv[3]);\n     */\n\n\t// test contact cluster\n\tstd::vector<ContactPoint> src = loadContacts(filename);\n\n\tstd::vector<ContactPoint> dst(src.size());\n\tstd::vector<int> srcIdx(src.size());\n\tstd::vector<int> dstIdx(src.size());\n\n\n\t//int num = ContactCluster::thresClustering(&src[0],10,&srcIdx[0],&dstIdx[0],&dst[0],(double)n);\n\tint num = ContactCluster::normalThresClustering(&src[0],\n\t\tboost::numeric_cast<int>(src.size()),\n\t\t&srcIdx[0],&dstIdx[0],\n\t\t&dst[0],n);\n\tstd::cout << \"Number of contacts: \" << num << std::endl;\n\t//for(int i=0;i<num;i++)\n\t//    std::cout << \"i:\" << i << \" -> \" << dst[i].penetration << \" \" << dst[i].p<< \" \" << dst[i].n << std::endl;\n\n\t//std::cout << \"Dst idx array: \" << std::endl;\n    //for(size_t i=0;i<dstIdx.size();i++)\n    //    std::cout << \"i:\" << i << \" -> \" << dstIdx[i] << \" \" << src[dstIdx[i] ].p<< \" \" << src[dstIdx[i] ].n << std::endl;\n\n    //std::cout << \"Src idx array: \" << std::endl;\n    //for(size_t i=0;i<srcIdx.size();i++)\n    //    std::cout << \"i:\" << i << \" -> \" << srcIdx[i] << std::endl;\n\n    // test manifold functionality\n\n    /*\n    std::vector< OBBManifold > manifolds;\n    std::vector< std::vector<ContactPoint> > inManifolds;\n    // for each cluster we fit a manifold\n    for(int i=0;i<num;i++){\n        int idxFrom = srcIdx[i];\n        const int idxTo = srcIdx[i+1];\n        // locate the manifold that idxFrom is located in\n        ContactPoint &deepestP = src[dstIdx[idxFrom]];\n\n        OBBManifold manifold(mThres,0.1);\n        std::vector<ContactPoint> pointsinmanifold;\n        std::cout << \"Adding clustered points to manifold!\" << std::endl;\n        for(;idxFrom<idxTo; idxFrom++){\n            ContactPoint &point = src[dstIdx[idxFrom]];\n            std::cout << point.p << std::endl;\n            if( manifold.inManifold(point) ){\n                std::cout << \"The point is in manifold, add it!\" << std::endl;\n                manifold.addPoint(point);\n                pointsinmanifold.push_back(point);\n            } else {\n                std::cout << \"The point is outside manifold, discard it!\" << std::endl;\n            }\n        }\n        manifolds.push_back(manifold);\n        inManifolds.push_back(pointsinmanifold);\n    }\n    */\n\n\n    std::vector< OBRManifold > manifolds;\n    std::vector< std::vector<ContactPoint> > inManifolds;\n    // for each cluster we fit a manifold\n    for(int i=0;i<num;i++){\n        int idxFrom = srcIdx[i];\n        const int idxTo = srcIdx[i+1];\n        // locate the manifold that idxFrom is located in\n        //Unused: ContactPoint &deepestP = src[dstIdx[idxFrom]];\n\n        OBRManifold manifold(13*Deg2Rad,0.2);\n\n        std::vector<ContactPoint> pointsinmanifold;\n        std::cout << \"Adding clustered points to manifold!\" << std::endl;\n        for(;idxFrom<idxTo; idxFrom++){\n            //if(idxFrom>10)\n            //    break;\n            ContactPoint &point = src[dstIdx[idxFrom]];\n            std::cout << point.p << std::endl;\n            if( manifold.addPoint(point) ){\n                //std::cout << \"The point is in manifold, add it!\" << std::endl;\n                //manifold.addPoint(point);\n                pointsinmanifold.push_back(point);\n            } else {\n                std::cout << \"The point is outside manifold, discard it!\" << std::endl;\n            }\n        }\n        manifolds.push_back(manifold);\n        inManifolds.push_back(pointsinmanifold);\n    }\n\n\n/*\n\t//OBBManifold manifold(mThres,0.1);\n    for(int i=0;i<num;i++){\n        int idxFrom = srcIdx[i];\n        const int idxTo = srcIdx[i+1];\n        // locate the manifold that idxFrom is located in\n        ContactPoint &deepestP = src[dstIdx[idxFrom]];\n        int manifoldIdx = -1;\n        std::cout << \"Looking for manifold: \";\n        for(int j=0;j<manifolds.size(); j++){\n            if( manifolds[j].inManifold(deepestP) ){\n                manifoldIdx = j;\n                break;\n            }\n        }\n        if(manifoldIdx <0){\n            std::cout << \"not found!\" << std::endl;\n            manifoldIdx = manifolds.size();\n            manifolds.push_back(OBBManifold(mThres,0.1));\n        } else {\n            std::cout << \"found!\" << std::endl;\n        }\n        OBBManifold &manifold = manifolds[manifoldIdx];\n        std::cout << \"Adding clustered points to manifold!\" << std::endl;\n        for(;idxFrom<idxTo; idxFrom++){\n            ContactPoint &point = src[dstIdx[idxFrom]];\n            std::cout << point.p << std::endl;\n            if( manifold.inManifold(point) ){\n                std::cout << \"The point is in manifold, add it!\" << std::endl;\n                manifold.addPoint(point);\n            } else {\n                std::cout << \"The point is outside manifold, discard it!\" << std::endl;\n            }\n        }\n\n    }\n    */\n\n    std::cout << \"\\n\\nTOTAL Nr contacts in input: \" << src.size() << std::endl;\n    for(size_t i=0;i<manifolds.size();i++){\n        std::cout << i+1 << \"'th Manifold\" << std::endl;\n        //OBBManifold &manifold = manifolds[i];\n        OBRManifold &manifold = manifolds[i];\n        std::cout << \"-- Nr of points  : \" << manifold.getNrOfContacts() << std::endl;\n        std::cout << \"-- HalfLengths   : \" << manifold.getHalfLengths() << std::endl;\n        std::cout << \"-- center        : \" << manifold.getTransform().P() << std::endl;\n        std::cout << \"-- generatedfrom : \" << inManifolds[i].size() << std::endl;\n        std::pair<Transform3D<>,Vector3D<> > res = fit(inManifolds[i]);\n        std::cout << \"-- HalfLengths   : \" << res.second << std::endl;\n        std::cout << \"-- center        : \" << res.first.P() << std::endl;\n\n    }\n\n\treturn 1;\n}\n\n\n", "meta": {"hexsha": "ee03ffb11d95768b9b755b542488e256f484ed11", "size": 20296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWorkSim/example/tools/src/RWSimTest.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": "RobWorkSim/example/tools/src/RWSimTest.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": "RobWorkSim/example/tools/src/RWSimTest.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.2361111111, "max_line_length": 124, "alphanum_fraction": 0.5373965313, "num_tokens": 6183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.18675618815778994}}
{"text": "#include <iostream>\n#include <chrono>\n#include <thread>\n#include <Eigen/Eigen>\n\n#include <pangolin/pangolin.h>\n#include <SceneGraph/SceneGraph.h>\n\nusing namespace std;\n\nvoid Usage() {\n    cout << \"Usage: ModelViewer filename\" << endl;\n}\n\nint main( int argc, char* argv[] )\n{\n    if(argc != 2) {\n        Usage();\n        exit(-1);\n    }\n\n    const std::string model_filename(argv[1]);\n\n    // Create OpenGL window in single line thanks to GLUT\n    pangolin::CreateWindowAndBind(\"Main\",640,480);\n    SceneGraph::GLSceneGraph::ApplyPreferredGlSettings();\n    glClearColor( 0,0,0,0);\n    glewInit();\n\n    // Scenegraph to hold GLObjects and relative transformations\n    SceneGraph::GLSceneGraph glGraph;\n\n    SceneGraph::GLLight light(10,10,-100);\n    glGraph.AddChild(&light);\n\n    SceneGraph::GLGrid grid(10,1,true);\n    glGraph.AddChild(&grid);\n\n    SceneGraph::AxisAlignedBoundingBox bbox;\n    \n#ifdef HAVE_ASSIMP\n    // Define a mesh object and try to load model\n    SceneGraph::GLMesh glMesh;\n    try {\n        glMesh.Init(model_filename);\n        glGraph.AddChild(&glMesh);\n        bbox = glMesh.ObjectAndChildrenBounds();\n    }catch(exception e) {\n        cerr << \"Cannot load mesh.\" << endl;\n        cerr << e.what() << std::endl;\n        exit(-1);\n    }\n#endif // HAVE_ASSIMP\n\n    \n    const Eigen::Vector3d center = bbox.Center();\n    double size = bbox.Size().norm();\n   \n    // Define Camera Render Object (for view / scene browsing)\n    pangolin::OpenGlRenderState stacks3d(\n        pangolin::ProjectionMatrix(640,480,420,420,320,240, 0.01, 1000),\n        pangolin::ModelViewLookAt(center(0), center(1) + size, center(2) + size/4, center(0), center(1), center(2), pangolin::AxisZ)\n    );\n\n    // We define a new view which will reside within the container.\n    pangolin::View view3d;\n\n    // We set the views location on screen and add a handler which will\n    // let user input update the model_view matrix (stacks3d) and feed through\n    // to our scenegraph\n    view3d.SetBounds(0.0, 1.0, 0.0, 1.0, -640.0f/480.0f)\n          .SetHandler(new SceneGraph::HandlerSceneGraph(glGraph,stacks3d))\n          .SetDrawFunction(SceneGraph::ActivateDrawFunctor(glGraph, stacks3d));\n\n    // Add our views as children to the base container.\n    pangolin::DisplayBase().AddDisplay(view3d);\n\n    // Default hooks for exiting (Esc) and fullscreen (tab).\n    while( !pangolin::ShouldQuit() )\n    {\n        // Clear whole screen\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n        // Swap frames and Process Events\n        pangolin::FinishFrame();\n\n        // Pause for 1/60th of a second.\n        std::this_thread::sleep_for(std::chrono::milliseconds(1000 / 60));\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "033de32c17539ce90f77909b49f46a39a46e0f72", "size": 2699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/ModelViewer/main.cpp", "max_stars_repo_name": "bpwiselybabu/SceneGraph", "max_stars_repo_head_hexsha": "1ae7142615bb2c15883ed928a5ed69b0cd281665", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-10-18T15:11:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T02:22:13.000Z", "max_issues_repo_path": "Examples/ModelViewer/main.cpp", "max_issues_repo_name": "bpwiselybabu/SceneGraph", "max_issues_repo_head_hexsha": "1ae7142615bb2c15883ed928a5ed69b0cd281665", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-04-24T20:37:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-27T15:26:42.000Z", "max_forks_repo_path": "Examples/ModelViewer/main.cpp", "max_forks_repo_name": "bpwiselybabu/SceneGraph", "max_forks_repo_head_hexsha": "1ae7142615bb2c15883ed928a5ed69b0cd281665", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-21T18:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-08T15:15:38.000Z", "avg_line_length": 29.0215053763, "max_line_length": 132, "alphanum_fraction": 0.6517228603, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18675618449319084}}
{"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// File generated at Sat 27 Aug 2016 12:50:58\n\n/**\n * @file CMSSM_mass_eigenstates.hpp\n *\n * @brief contains class for model with routines needed to solve boundary\n *        value problem using the two_scale solver by solving EWSB\n *        and determine the pole masses and mixings\n *\n * This file was generated at Sat 27 Aug 2016 12:50:58 with FlexibleSUSY\n * 1.5.1 (git commit: 8356bacd26e8aecc6635607a32835d534ea3cf01) and SARAH 4.9.0 .\n */\n\n#ifndef CMSSM_MASS_EIGENSTATES_H\n#define CMSSM_MASS_EIGENSTATES_H\n\n#include \"CMSSM_two_scale_soft_parameters.hpp\"\n#include \"CMSSM_physical.hpp\"\n#include \"CMSSM_info.hpp\"\n#include \"two_loop_corrections.hpp\"\n#include \"problems.hpp\"\n#include \"config.h\"\n\n#include <iosfwd>\n#include <string>\n\n#ifdef ENABLE_THREADS\n#include <mutex>\n#endif\n\n#include <gsl/gsl_vector.h>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\n/**\n * @class CMSSM_mass_eigenstates\n * @brief model class with routines for determing masses and mixinga and EWSB\n */\nclass CMSSM_mass_eigenstates : public CMSSM_soft_parameters {\npublic:\n   explicit CMSSM_mass_eigenstates(const CMSSM_input_parameters& input_ = CMSSM_input_parameters());\n   virtual ~CMSSM_mass_eigenstates();\n\n   /// number of EWSB equations\n   static const std::size_t number_of_ewsb_equations = 2;\n\n   void calculate_DRbar_masses();\n   void calculate_DRbar_parameters();\n   void calculate_pole_masses();\n   void check_pole_masses_for_tachyons();\n   virtual void clear();\n   void clear_DRbar_parameters();\n   Eigen::ArrayXd get_DRbar_masses() const;\n   void do_calculate_sm_pole_masses(bool);\n   bool do_calculate_sm_pole_masses() const;\n   void do_force_output(bool);\n   bool do_force_output() const;\n   void reorder_DRbar_masses();\n   void reorder_pole_masses();\n   void set_ewsb_iteration_precision(double);\n   void set_ewsb_loop_order(unsigned);\n   void set_two_loop_corrections(const Two_loop_corrections&);\n   const Two_loop_corrections& get_two_loop_corrections() const;\n   void set_DRbar_masses(const Eigen::ArrayXd&);\n   void set_number_of_ewsb_iterations(std::size_t);\n   void set_number_of_mass_iterations(std::size_t);\n   std::size_t get_number_of_ewsb_iterations() const;\n   std::size_t get_number_of_mass_iterations() const;\n   void set_pole_mass_loop_order(unsigned);\n   unsigned get_pole_mass_loop_order() const;\n   void set_physical(const CMSSM_physical&);\n   double get_ewsb_iteration_precision() const;\n   double get_ewsb_loop_order() const;\n   const CMSSM_physical& get_physical() const;\n   CMSSM_physical& get_physical();\n   const Problems<CMSSM_info::NUMBER_OF_PARTICLES>& get_problems() const;\n   Problems<CMSSM_info::NUMBER_OF_PARTICLES>& get_problems();\n   int solve_ewsb_tree_level();\n   int solve_ewsb_one_loop();\n   int solve_ewsb();            ///< solve EWSB at ewsb_loop_order level\n\n   void calculate_spectrum();\n   void clear_problems();\n   std::string name() const;\n   void run_to(double scale, double eps = -1.0);\n   void print(std::ostream& out = std::cout) const;\n   void set_precision(double);\n   double get_precision() const;\n\n   double get_lsp(CMSSM_info::Particles&) const;\n\n   double get_MVG() const { return MVG; }\n   double get_MGlu() const { return MGlu; }\n   const Eigen::Array<double,3,1>& get_MFv() const { return MFv; }\n   double get_MFv(int i) const { return MFv(i); }\n   const Eigen::Array<double,6,1>& get_MSd() const { return MSd; }\n   double get_MSd(int i) const { return MSd(i); }\n   const Eigen::Array<double,3,1>& get_MSv() const { return MSv; }\n   double get_MSv(int i) const { return MSv(i); }\n   const Eigen::Array<double,6,1>& get_MSu() const { return MSu; }\n   double get_MSu(int i) const { return MSu(i); }\n   const Eigen::Array<double,6,1>& get_MSe() const { return MSe; }\n   double get_MSe(int i) const { return MSe(i); }\n   const Eigen::Array<double,2,1>& get_Mhh() const { return Mhh; }\n   double get_Mhh(int i) const { return Mhh(i); }\n   const Eigen::Array<double,2,1>& get_MAh() const { return MAh; }\n   double get_MAh(int i) const { return MAh(i); }\n   const Eigen::Array<double,2,1>& get_MHpm() const { return MHpm; }\n   double get_MHpm(int i) const { return MHpm(i); }\n   const Eigen::Array<double,4,1>& get_MChi() const { return MChi; }\n   double get_MChi(int i) const { return MChi(i); }\n   const Eigen::Array<double,2,1>& get_MCha() const { return MCha; }\n   double get_MCha(int i) const { return MCha(i); }\n   const Eigen::Array<double,3,1>& get_MFe() const { return MFe; }\n   double get_MFe(int i) const { return MFe(i); }\n   const Eigen::Array<double,3,1>& get_MFd() const { return MFd; }\n   double get_MFd(int i) const { return MFd(i); }\n   const Eigen::Array<double,3,1>& get_MFu() const { return MFu; }\n   double get_MFu(int i) const { return MFu(i); }\n   double get_MVWm() const { return MVWm; }\n   double get_MVP() const { return MVP; }\n   double get_MVZ() const { return MVZ; }\n\n   \n   Eigen::Array<double,1,1> get_MChargedHiggs() const;\n\n   Eigen::Array<double,1,1> get_MPseudoscalarHiggs() const;\n\n   const Eigen::Matrix<double,6,6>& get_ZD() const { return ZD; }\n   double get_ZD(int i, int k) const { return ZD(i,k); }\n   const Eigen::Matrix<double,3,3>& get_ZV() const { return ZV; }\n   double get_ZV(int i, int k) const { return ZV(i,k); }\n   const Eigen::Matrix<double,6,6>& get_ZU() const { return ZU; }\n   double get_ZU(int i, int k) const { return ZU(i,k); }\n   const Eigen::Matrix<double,6,6>& get_ZE() const { return ZE; }\n   double get_ZE(int i, int k) const { return ZE(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZH() const { return ZH; }\n   double get_ZH(int i, int k) const { return ZH(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZA() const { return ZA; }\n   double get_ZA(int i, int k) const { return ZA(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZP() const { return ZP; }\n   double get_ZP(int i, int k) const { return ZP(i,k); }\n   const Eigen::Matrix<std::complex<double>,4,4>& get_ZN() const { return ZN; }\n   const std::complex<double>& get_ZN(int i, int k) const { return ZN(i,k); }\n   const Eigen::Matrix<std::complex<double>,2,2>& get_UM() const { return UM; }\n   const std::complex<double>& get_UM(int i, int k) const { return UM(i,k); }\n   const Eigen::Matrix<std::complex<double>,2,2>& get_UP() const { return UP; }\n   const std::complex<double>& get_UP(int i, int k) const { return UP(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZEL() const { return ZEL; }\n   const std::complex<double>& get_ZEL(int i, int k) const { return ZEL(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZER() const { return ZER; }\n   const std::complex<double>& get_ZER(int i, int k) const { return ZER(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZDL() const { return ZDL; }\n   const std::complex<double>& get_ZDL(int i, int k) const { return ZDL(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZDR() const { return ZDR; }\n   const std::complex<double>& get_ZDR(int i, int k) const { return ZDR(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZUL() const { return ZUL; }\n   const std::complex<double>& get_ZUL(int i, int k) const { return ZUL(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZUR() const { return ZUR; }\n   const std::complex<double>& get_ZUR(int i, int k) const { return ZUR(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZZ() const { return ZZ; }\n   double get_ZZ(int i, int k) const { return ZZ(i,k); }\n\n   void set_PhaseGlu(std::complex<double> PhaseGlu_) { PhaseGlu = PhaseGlu_; }\n   std::complex<double> get_PhaseGlu() const { return PhaseGlu; }\n\n   double get_mass_matrix_VG() const;\n   void calculate_MVG();\n   double get_mass_matrix_Glu() const;\n   void calculate_MGlu();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fv() const;\n   void calculate_MFv();\n   Eigen::Matrix<double,6,6> get_mass_matrix_Sd() const;\n   void calculate_MSd();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Sv() const;\n   void calculate_MSv();\n   Eigen::Matrix<double,6,6> get_mass_matrix_Su() const;\n   void calculate_MSu();\n   Eigen::Matrix<double,6,6> get_mass_matrix_Se() const;\n   void calculate_MSe();\n   Eigen::Matrix<double,2,2> get_mass_matrix_hh() const;\n   void calculate_Mhh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Ah() const;\n   void calculate_MAh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Hpm() const;\n   void calculate_MHpm();\n   Eigen::Matrix<double,4,4> get_mass_matrix_Chi() const;\n   void calculate_MChi();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Cha() const;\n   void calculate_MCha();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fe() const;\n   void calculate_MFe();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fd() const;\n   void calculate_MFd();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fu() const;\n   void calculate_MFu();\n   double get_mass_matrix_VWm() const;\n   void calculate_MVWm();\n   Eigen::Matrix<double,2,2> get_mass_matrix_VPVZ() const;\n   void calculate_MVPVZ();\n\n   double get_ewsb_eq_hh_1() const;\n   double get_ewsb_eq_hh_2() const;\n\n   std::complex<double> CpUSdconjUSdVZVZ(unsigned gO1, unsigned gO2) const;\n   double CpUSdconjUSdconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSdconjUSdAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSvSv(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdFuChaPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdFuChaPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdFdChiPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdFdChiPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdSdAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdSdhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdSuHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdGluFdPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSdGluFdPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSdVGSd(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSdVPSd(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSdVZSd(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSdVWmSu(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUSvconjUSvVZVZ(unsigned gO1, unsigned gO2) const;\n   double CpUSvconjUSvconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSvconjUSvAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSvconjUSvconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSvconjUSvhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSvbarChaFePR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSvbarChaFePL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSvconjHpmSe(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSvconjUSvconjSvSv(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSvSvhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   double CpconjUSvFvChiPR(unsigned , unsigned , unsigned ) const;\n   std::complex<double> CpconjUSvFvChiPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSvconjUSvconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSvconjUSvconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSvconjUSvconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSvVZSv(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSvconjVWmSe(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuVZVZ(unsigned gO1, unsigned gO2) const;\n   double CpUSuconjUSuconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSuconjUSuAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSubarChaFdPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSubarChaFdPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuconjHpmSd(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSvSv(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuFuChiPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuFuChiPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuSuAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuSuhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuGluFuPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSuGluFuPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSuconjVWmSd(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSuVGSu(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSuVPSu(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSuVZSu(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeVZVZ(unsigned gO1, unsigned gO2) const;\n   double CpUSeconjUSeconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSeconjUSeAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSehhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSvSv(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeSvHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   double CpconjUSeFvChaPR(unsigned , unsigned , unsigned ) const;\n   std::complex<double> CpconjUSeFvChaPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeFeChiPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeFeChiPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeSeAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeSehh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeVWmSv(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSeVPSe(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSeVZSe(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUhhVZVZ(unsigned gO2) const;\n   std::complex<double> CpUhhconjVWmVWm(unsigned gO2) const;\n   std::complex<double> CpUhhbargWmgWm(unsigned gO1) const;\n   std::complex<double> CpUhhbargWmCgWmC(unsigned gO1) const;\n   std::complex<double> CpUhhbargZgZ(unsigned gO1) const;\n   std::complex<double> CpUhhUhhVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhAhAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjHpmHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhhhhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarChaChaPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarChaChaPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSvSv(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSvSv(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFdFdPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFdFdPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFeFePR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFeFePL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFuFuPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarFuFuPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhChiChiPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhChiChiPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSdSd(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSeSe(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSuSu(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhVZAh(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUhhconjVWmHpm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUAhbargWmgWm(unsigned gO1) const;\n   std::complex<double> CpUAhbargWmCgWmC(unsigned gO1) const;\n   std::complex<double> CpUAhUAhVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUAhUAhconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUAhUAhAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjHpmHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhhhAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarChaChaPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarChaChaPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSvSv(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarFdFdPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarFdFdPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarFeFePR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarFeFePL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarFuFuPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarFuFuPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhChiChiPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhChiChiPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSdSd(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSeSe(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSuSu(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhVZhh(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUAhconjVWmHpm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVWmVP(unsigned gO2) const;\n   std::complex<double> CpconjUHpmVZVWm(unsigned gO2) const;\n   std::complex<double> CpconjUHpmbargWmCgZ(unsigned gO1) const;\n   std::complex<double> CpUHpmgWmCbargZ(unsigned gO2) const;\n   std::complex<double> CpconjUHpmbargZgWm(unsigned gO1) const;\n   std::complex<double> CpUHpmgZbargWm(unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmHpmAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmHpmhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSvSv(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmbarFuFdPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmbarFuFdPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmbarFvFePR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   double CpconjUHpmbarFvFePL(unsigned , unsigned , unsigned ) const;\n   std::complex<double> CpconjUHpmconjSvSe(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmChiChaPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmChiChaPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmconjSuSd(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVWmAh(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVWmhh(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVPHpm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVZHpm(unsigned gO2, unsigned gI2) const;\n   double CpVZbargWmgWm() const;\n   double CpVZbargWmCgWmC() const;\n   double CpVZconjVWmVWm() const;\n   std::complex<double> CpVZVZAhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZhhhh(unsigned gI1, unsigned gI2) const;\n   double CpVZconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZhhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZbarChaChaPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZbarChaChaPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSvSv(unsigned gI1, unsigned gI2) const;\n   double CpVZconjSvSv(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFdFdPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFdFdPR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFeFePL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFeFePR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFuFuPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFuFuPR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFvFvPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFvFvPR(unsigned , unsigned ) const;\n   std::complex<double> CpVZChiChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZChiChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZhh(unsigned gI2) const;\n   std::complex<double> CpVZconjVWmHpm(unsigned gI2) const;\n   double CpVZVZconjVWmVWm1() const;\n   double CpVZVZconjVWmVWm2() const;\n   double CpVZVZconjVWmVWm3() const;\n   double CpconjVWmbargPgWm() const;\n   double CpconjVWmbargWmCgP() const;\n   double CpconjVWmbargWmCgZ() const;\n   double CpconjVWmbargZgWm() const;\n   double CpconjVWmVWmVP() const;\n   double CpconjVWmVZVWm() const;\n   std::complex<double> CpVWmconjVWmAhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmhhhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmHpmAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmHpmhh(unsigned gI1, unsigned gI2) const;\n   double CpVWmconjVWmconjSvSv(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmbarFuFdPL(unsigned gI1, unsigned gI2) const;\n   double CpconjVWmbarFuFdPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjVWmbarFvFePL(unsigned gI1, unsigned gI2) const;\n   double CpconjVWmbarFvFePR(unsigned , unsigned ) const;\n   std::complex<double> CpconjVWmconjSvSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmChiChaPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmChiChaPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmconjSuSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmVPHpm(unsigned gI2) const;\n   std::complex<double> CpconjVWmVWmhh(unsigned gI2) const;\n   std::complex<double> CpconjVWmVZHpm(unsigned gI2) const;\n   double CpVWmconjVWmVPVP1() const;\n   double CpVWmconjVWmVPVP2() const;\n   double CpVWmconjVWmVPVP3() const;\n   double CpVWmconjVWmVZVZ1() const;\n   double CpVWmconjVWmVZVZ2() const;\n   double CpVWmconjVWmVZVZ3() const;\n   double CpVWmconjVWmconjVWmVWm1() const;\n   double CpVWmconjVWmconjVWmVWm2() const;\n   double CpVWmconjVWmconjVWmVWm3() const;\n   std::complex<double> CpUChiconjHpmChaPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjHpmChaPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChihhChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChihhChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSvFvPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   double CpUChiconjSvFvPR(unsigned , unsigned , unsigned ) const;\n   std::complex<double> CpUChiChiAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiChiAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSdFdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSdFdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSeFePL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSeFePR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSuFuPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSuFuPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjVWmChaPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUChiconjVWmChaPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpUChiVZChiPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUChiVZChiPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUChaChaAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaChaAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChahhChaPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChahhChaPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaHpmChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaHpmChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaconjSvFePL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaconjSvFePR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChabarFuSdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChabarFuSdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   double CpbarUChabarFvSePL(unsigned , unsigned , unsigned ) const;\n   std::complex<double> CpbarUChabarFvSePR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaconjSuFdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaconjSuFdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaVPChaPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUChaVPChaPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUChaVZChaPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUChaVZChaPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUChaVWmChiPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUChaVWmChiPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFehhFePL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFehhFePR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFeHpmFvPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   double CpbarUFeHpmFvPR(unsigned , unsigned , unsigned ) const;\n   std::complex<double> CpbarUFeFeAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFeFeAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFeSvChaPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFeSvChaPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFeSeChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFeSeChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFeVPFePR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFeVPFePL(unsigned gO1, unsigned gI2) const;\n   double CpbarUFeVWmFvPR(unsigned , unsigned ) const;\n   double CpbarUFeVWmFvPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFeVZFePR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFeVZFePL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdhhFdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdhhFdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdHpmFuPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdHpmFuPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdFdAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdFdAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdSuChaPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdSuChaPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdSdChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdSdChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFdSdGluPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUFdSdGluPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUFdVGFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVGFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdVPFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVPFdPL(unsigned gO1, unsigned gI2) const;\n   double CpbarUFdVWmFuPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarUFdVWmFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdVZFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVZFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuconjHpmFdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuconjHpmFdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuhhFuPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuhhFuPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFubarChaSdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFubarChaSdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuFuAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuFuAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuSuChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuSuChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUFuSuGluPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUFuSuGluPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUFuVGFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVGFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuVPFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVPFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuVZFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVZFuPL(unsigned gO1, unsigned gI2) const;\n   double CpbarUFuconjVWmFdPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarUFuconjVWmFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpGluconjSdFdPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpGluconjSdFdPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpGluconjSuFuPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpGluconjSuFuPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpGluVGGluPR() const;\n   std::complex<double> CpGluVGGluPL() const;\n   std::complex<double> CpbarFehhFePL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFehhFePR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFeHpmFvPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   double CpbarFeHpmFvPR(unsigned , unsigned , unsigned ) const;\n   std::complex<double> CpbarFeFeAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFeFeAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFeSvChaPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFeSvChaPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFeSeChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFeSeChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   double CpbarFeVWmFvPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFeVWmFvPL(unsigned gO1, unsigned gI2) const;\n   double CpbarFeVZFePR(unsigned gO2, unsigned gI2) const;\n   double CpbarFeVZFePL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFdhhFdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdhhFdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdHpmFuPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdHpmFuPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdFdAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdFdAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdSuChaPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdSuChaPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdSdChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdSdChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdSdGluPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFdSdGluPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   double CpbarFdVWmFuPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFdVWmFuPL(unsigned gO1, unsigned gI2) const;\n   double CpbarFdVZFdPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFdVZFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFuconjHpmFdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuconjHpmFdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuhhFuPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuhhFuPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFubarChaSdPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFubarChaSdPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuFuAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuFuAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuSuChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuSuChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuSuGluPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFuSuGluPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   double CpbarFuVPFuPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFuVPFuPL(unsigned gO1, unsigned gI2) const;\n   double CpbarFuVZFuPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFuVZFuPL(unsigned gO1, unsigned gI2) const;\n   double CpbarFuconjVWmFdPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFuconjVWmFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> self_energy_Sd(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Sv(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Su(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Se(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_hh(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Ah(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Hpm(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_VZ(double p ) const;\n   std::complex<double> self_energy_VWm(double p ) const;\n   std::complex<double> self_energy_Chi_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Chi_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Chi_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Cha_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Cha_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Cha_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Glu_1(double p ) const;\n   std::complex<double> self_energy_Glu_PR(double p ) const;\n   std::complex<double> self_energy_Glu_PL(double p ) const;\n   std::complex<double> self_energy_VZ_heavy(double p ) const;\n   std::complex<double> self_energy_VWm_heavy(double p ) const;\n   std::complex<double> self_energy_Fe_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> tadpole_hh(unsigned gO1) const;\n\n\n   /// calculates the tadpoles at current loop order\n   void tadpole_equations(double[number_of_ewsb_equations]) const;\n\n   void calculate_MSu_3rd_generation(double&, double&, double&) const;\n   void calculate_MSd_3rd_generation(double&, double&, double&) const;\n   void calculate_MSv_3rd_generation(double&, double&, double&) const;\n   void calculate_MSe_3rd_generation(double&, double&, double&) const;\n\n   void self_energy_hh_2loop(double result[3]) const;\n   void self_energy_Ah_2loop(double result[3]) const;\n\n   void tadpole_hh_2loop(double result[2]) const;\n\n\n   void calculate_MVG_pole();\n   void calculate_MGlu_pole();\n   void calculate_MFv_pole();\n   void calculate_MVP_pole();\n   void calculate_MVZ_pole();\n   void calculate_MSd_pole();\n   void calculate_MSv_pole();\n   void calculate_MSu_pole();\n   void calculate_MSe_pole();\n   void calculate_Mhh_pole();\n   void calculate_MAh_pole();\n   void calculate_MHpm_pole();\n   void calculate_MChi_pole();\n   void calculate_MCha_pole();\n   void calculate_MFe_pole();\n   void calculate_MFd_pole();\n   void calculate_MFu_pole();\n   void calculate_MVWm_pole();\n   double calculate_MVWm_pole(double);\n   double calculate_MVZ_pole(double);\n\n   double calculate_MFv_DRbar(double, int) const;\n   double calculate_MFe_DRbar(double, int) const;\n   double calculate_MFu_DRbar(double, int) const;\n   double calculate_MFd_DRbar(double, int) const;\n   double calculate_MVP_DRbar(double);\n   double calculate_MVZ_DRbar(double);\n   double calculate_MVWm_DRbar(double);\n\n   double v() const;\n   double Betax() const;\n   double Alpha() const;\n   double ThetaW() const;\n\n\nprivate:\n   struct EWSB_args {\n      CMSSM_mass_eigenstates* model;\n      unsigned ewsb_loop_order;\n   };\n\n#ifdef ENABLE_THREADS\n   struct Thread {\n      typedef void(CMSSM_mass_eigenstates::*Memfun_t)();\n      CMSSM_mass_eigenstates* model;\n      Memfun_t fun;\n\n      Thread(CMSSM_mass_eigenstates* model_, Memfun_t fun_)\n         : model(model_), fun(fun_) {}\n      void operator()() {\n         try {\n            (model->*fun)();\n         } catch (...) {\n            model->thread_exception = std::current_exception();\n         }\n      }\n   };\n#endif\n\n   std::size_t number_of_ewsb_iterations;\n   std::size_t number_of_mass_iterations;\n   unsigned ewsb_loop_order;\n   unsigned pole_mass_loop_order;\n   bool calculate_sm_pole_masses; ///< switch to calculate the pole masses of the Standard Model particles\n   bool force_output;             ///< switch to force output of pole masses\n   double precision;              ///< RG running precision\n   double ewsb_iteration_precision;\n   CMSSM_physical physical; ///< contains the pole masses and mixings\n   Problems<CMSSM_info::NUMBER_OF_PARTICLES> problems;\n   Two_loop_corrections two_loop_corrections; ///< used 2-loop corrections\n#ifdef ENABLE_THREADS\n   std::exception_ptr thread_exception;\n   static std::mutex mtx_fortran; /// locks fortran functions\n#endif\n\n   int solve_ewsb_iteratively();\n   int solve_ewsb_iteratively(unsigned);\n   int solve_ewsb_iteratively_with(EWSB_solver*, const double[number_of_ewsb_equations]);\n   int solve_ewsb_tree_level_custom();\n   void ewsb_initial_guess(double[number_of_ewsb_equations]);\n   int ewsb_step(double[number_of_ewsb_equations]) const;\n   static int ewsb_step(const gsl_vector*, void*, gsl_vector*);\n   static int tadpole_equations(const gsl_vector*, void*, gsl_vector*);\n   void copy_DRbar_masses_to_pole_masses();\n\n   // Passarino-Veltman loop functions\n   double A0(double) const;\n   double B0(double, double, double) const;\n   double B1(double, double, double) const;\n   double B00(double, double, double) const;\n   double B22(double, double, double) const;\n   double H0(double, double, double) const;\n   double F0(double, double, double) const;\n   double G0(double, double, double) const;\n\n   // DR-bar masses\n   double MVG;\n   double MGlu;\n   Eigen::Array<double,3,1> MFv;\n   Eigen::Array<double,6,1> MSd;\n   Eigen::Array<double,3,1> MSv;\n   Eigen::Array<double,6,1> MSu;\n   Eigen::Array<double,6,1> MSe;\n   Eigen::Array<double,2,1> Mhh;\n   Eigen::Array<double,2,1> MAh;\n   Eigen::Array<double,2,1> MHpm;\n   Eigen::Array<double,4,1> MChi;\n   Eigen::Array<double,2,1> MCha;\n   Eigen::Array<double,3,1> MFe;\n   Eigen::Array<double,3,1> MFd;\n   Eigen::Array<double,3,1> MFu;\n   double MVWm;\n   double MVP;\n   double MVZ;\n\n   // DR-bar mixing matrices\n   Eigen::Matrix<double,6,6> ZD;\n   Eigen::Matrix<double,3,3> ZV;\n   Eigen::Matrix<double,6,6> ZU;\n   Eigen::Matrix<double,6,6> ZE;\n   Eigen::Matrix<double,2,2> ZH;\n   Eigen::Matrix<double,2,2> ZA;\n   Eigen::Matrix<double,2,2> ZP;\n   Eigen::Matrix<std::complex<double>,4,4> ZN;\n   Eigen::Matrix<std::complex<double>,2,2> UM;\n   Eigen::Matrix<std::complex<double>,2,2> UP;\n   Eigen::Matrix<std::complex<double>,3,3> ZEL;\n   Eigen::Matrix<std::complex<double>,3,3> ZER;\n   Eigen::Matrix<std::complex<double>,3,3> ZDL;\n   Eigen::Matrix<std::complex<double>,3,3> ZDR;\n   Eigen::Matrix<std::complex<double>,3,3> ZUL;\n   Eigen::Matrix<std::complex<double>,3,3> ZUR;\n   Eigen::Matrix<double,2,2> ZZ;\n\n   // phases\n   std::complex<double> PhaseGlu;\n\n};\n\nstd::ostream& operator<<(std::ostream&, const CMSSM_mass_eigenstates&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "9c5de6592c3c9d2ca4228f5c33b81f127c79919b", "size": 49676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/CMSSM/CMSSM_mass_eigenstates.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/models/CMSSM/CMSSM_mass_eigenstates.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/models/CMSSM/CMSSM_mass_eigenstates.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": 61.1020910209, "max_line_length": 111, "alphanum_fraction": 0.751852001, "num_tokens": 16187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.1867561808285918}}
{"text": "/* Copyright 2003-2013 Joaquin M Lopez Munoz.\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/libs/multi_index for library home page.\n */\n\n#ifndef BOOST_MULTI_INDEX_DETAIL_INDEX_MATCHER_HPP\n#define BOOST_MULTI_INDEX_DETAIL_INDEX_MATCHER_HPP\n\n#if defined(_MSC_VER)\n#pragma once\n#endif\n\n#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */\n#include <algorithm>\n#include <boost/noncopyable.hpp>\n#include <boost/multi_index/detail/auto_space.hpp>\n#include <cstddef>\n#include <functional>\n\nnamespace boost{\n\nnamespace multi_index{\n\nnamespace detail{\n\n/* index_matcher compares a sequence of elements against a\n * base sequence, identifying those elements that belong to the\n * longest subsequence which is ordered with respect to the base.\n * For instance, if the base sequence is:\n *\n *   0 1 2 3 4 5 6 7 8 9\n *\n * and the compared sequence (not necesarilly the same length):\n *\n *   1 4 2 3 0 7 8 9\n *\n * the elements of the longest ordered subsequence are:\n *\n *   1 2 3 7 8 9\n * \n * The algorithm for obtaining such a subsequence is called\n * Patience Sorting, described in ch. 1 of:\n *   Aldous, D., Diaconis, P.: \"Longest increasing subsequences: from\n *   patience sorting to the Baik-Deift-Johansson Theorem\", Bulletin\n *   of the American Mathematical Society, vol. 36, no 4, pp. 413-432,\n *   July 1999.\n *   http://www.ams.org/bull/1999-36-04/S0273-0979-99-00796-X/\n *   S0273-0979-99-00796-X.pdf\n *\n * This implementation is not fully generic since it assumes that\n * the sequences given are pointed to by index iterators (having a\n * get_node() memfun.)\n */\n\nnamespace index_matcher{\n\n/* The algorithm stores the nodes of the base sequence and a number\n * of \"piles\" that are dynamically updated during the calculation\n * stage. From a logical point of view, nodes form an independent\n * sequence from piles. They are stored together so as to minimize\n * allocated memory.\n */\n\nstruct entry\n{\n  entry(void* node_,std::size_t pos_=0):node(node_),pos(pos_){}\n\n  /* node stuff */\n\n  void*       node;\n  std::size_t pos;\n  entry*      previous;\n  bool        ordered;\n\n  struct less_by_node\n  {\n    bool operator()(\n      const entry& x,const entry& y)const\n    {\n      return std::less<void*>()(x.node,y.node);\n    }\n  };\n\n  /* pile stuff */\n\n  std::size_t pile_top;\n  entry*      pile_top_entry;\n\n  struct less_by_pile_top\n  {\n    bool operator()(\n      const entry& x,const entry& y)const\n    {\n      return x.pile_top<y.pile_top;\n    }\n  };\n};\n\n/* common code operating on void *'s */\n\ntemplate<typename Allocator>\nclass algorithm_base:private noncopyable\n{\nprotected:\n  algorithm_base(const Allocator& al,std::size_t size):\n    spc(al,size),size_(size),n_(0),sorted(false)\n  {\n  }\n\n  void add(void* node)\n  {\n    entries()[n_]=entry(node,n_);\n    ++n_;\n  }\n\n  void begin_algorithm()const\n  {\n    if(!sorted){\n      std::sort(entries(),entries()+size_,entry::less_by_node());\n      sorted=true;\n    }\n    num_piles=0;\n  }\n\n  void add_node_to_algorithm(void* node)const\n  {\n    entry* ent=\n      std::lower_bound(\n        entries(),entries()+size_,\n        entry(node),entry::less_by_node()); /* localize entry */\n    ent->ordered=false;\n    std::size_t n=ent->pos;                 /* get its position */\n\n    entry dummy(0);\n    dummy.pile_top=n;\n\n    entry* pile_ent=                        /* find the first available pile */\n      std::lower_bound(                     /* to stack the entry            */\n        entries(),entries()+num_piles,\n        dummy,entry::less_by_pile_top());\n\n    pile_ent->pile_top=n;                   /* stack the entry */\n    pile_ent->pile_top_entry=ent;        \n\n    /* if not the first pile, link entry to top of the preceding pile */\n    if(pile_ent>&entries()[0]){ \n      ent->previous=(pile_ent-1)->pile_top_entry;\n    }\n\n    if(pile_ent==&entries()[num_piles]){    /* new pile? */\n      ++num_piles;\n    }\n  }\n\n  void finish_algorithm()const\n  {\n    if(num_piles>0){\n      /* Mark those elements which are in their correct position, i.e. those\n       * belonging to the longest increasing subsequence. These are those\n       * elements linked from the top of the last pile.\n       */\n\n      entry* ent=entries()[num_piles-1].pile_top_entry;\n      for(std::size_t n=num_piles;n--;){\n        ent->ordered=true;\n        ent=ent->previous;\n      }\n    }\n  }\n\n  bool is_ordered(void * node)const\n  {\n    return std::lower_bound(\n      entries(),entries()+size_,\n      entry(node),entry::less_by_node())->ordered;\n  }\n\nprivate:\n  entry* entries()const{return &*spc.data();}\n\n  auto_space<entry,Allocator> spc;\n  std::size_t                 size_;\n  std::size_t                 n_;\n  mutable bool                sorted;\n  mutable std::size_t         num_piles;\n};\n\n/* The algorithm has three phases:\n *   - Initialization, during which the nodes of the base sequence are added.\n *   - Execution.\n *   - Results querying, through the is_ordered memfun.\n */\n\ntemplate<typename Node,typename Allocator>\nclass algorithm:private algorithm_base<Allocator>\n{\n  typedef algorithm_base<Allocator> super;\n\npublic:\n  algorithm(const Allocator& al,std::size_t size):super(al,size){}\n\n  void add(Node* node)\n  {\n    super::add(node);\n  }\n\n  template<typename IndexIterator>\n  void execute(IndexIterator first,IndexIterator last)const\n  {\n    super::begin_algorithm();\n\n    for(IndexIterator it=first;it!=last;++it){\n      add_node_to_algorithm(get_node(it));\n    }\n\n    super::finish_algorithm();\n  }\n\n  bool is_ordered(Node* node)const\n  {\n    return super::is_ordered(node);\n  }\n\nprivate:\n  void add_node_to_algorithm(Node* node)const\n  {\n    super::add_node_to_algorithm(node);\n  }\n\n  template<typename IndexIterator>\n  static Node* get_node(IndexIterator it)\n  {\n    return static_cast<Node*>(it.get_node());\n  }\n};\n\n} /* namespace multi_index::detail::index_matcher */\n\n} /* namespace multi_index::detail */\n\n} /* namespace multi_index */\n\n} /* namespace boost */\n\n#endif\n", "meta": {"hexsha": "f3675acd401c4f635bbbccd0a036f05e52b904e0", "size": 6071, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/multi_index/detail/index_matcher.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": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "src/third_party/boost-1.56.0/boost/multi_index/detail/index_matcher.hpp", "max_issues_repo_name": "wujf/mongo", "max_issues_repo_head_hexsha": "f2f48b749ded0c5585c798c302f6162f19336670", "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": "src/third_party/boost-1.56.0/boost/multi_index/detail/index_matcher.hpp", "max_forks_repo_name": "wujf/mongo", "max_forks_repo_head_hexsha": "f2f48b749ded0c5585c798c302f6162f19336670", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 24.3815261044, "max_line_length": 79, "alphanum_fraction": 0.6560698402, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.186697339320267}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2021 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n\n#ifndef BOOST_GEOMETRY_TEST_INTERSECTION_ALTERNATIVE_ROBUSTNESS_STRATEGY_HPP\n#define BOOST_GEOMETRY_TEST_INTERSECTION_ALTERNATIVE_ROBUSTNESS_STRATEGY_HPP\n\n#include <boost/geometry/strategies/relate/cartesian.hpp>\n\n\ntemplate <typename SideStrategy>\nclass alternative_robustness_strategy\n    : public bg::strategies::relate::cartesian<>\n{\npublic:\n    static auto side()\n    {\n        return SideStrategy();\n    }\n};\n\n\n#endif // BOOST_GEOMETRY_TEST_INTERSECTION_ALTERNATIVE_ROBUSTNESS_STRATEGY_HPP\n", "meta": {"hexsha": "9feb457c34dd71e9427d7c923d03b852f15007f7", "size": 720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/set_operations/alternative_robustness_strategy.hpp", "max_stars_repo_name": "onlykzy/geometry", "max_stars_repo_head_hexsha": "be6794b606d25cf53fe2fd312f9b5fe30ddda6fb", "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/algorithms/set_operations/alternative_robustness_strategy.hpp", "max_issues_repo_name": "onlykzy/geometry", "max_issues_repo_head_hexsha": "be6794b606d25cf53fe2fd312f9b5fe30ddda6fb", "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/algorithms/set_operations/alternative_robustness_strategy.hpp", "max_forks_repo_name": "onlykzy/geometry", "max_forks_repo_head_hexsha": "be6794b606d25cf53fe2fd312f9b5fe30ddda6fb", "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": 25.7142857143, "max_line_length": 78, "alphanum_fraction": 0.7930555556, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18669733575576}}
{"text": "/* Copyright Institute of Sound and Vibration Research - All rights reserved */\n\n\n#include <libvisr/atomic_component.hpp>\n#include <libvisr/communication_protocol_base.hpp>\n#include <libvisr/communication_protocol_factory.hpp>\n#include <libvisr/polymorphic_parameter_input.hpp>\n#include <libvisr/signal_flow_context.hpp>\n\n#include <libvisr/impl/component_implementation.hpp>\n\n#include <libpml/initialise_parameter_library.hpp>\n#include <libpml/double_buffering_protocol.hpp>\n#include <libpml/matrix_parameter.hpp>\n#include <libpml/matrix_parameter_config.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <memory>\n#include <stdexcept>\n#include <sstream>\n#include <string>\n\nnamespace visr\n{\nnamespace impl\n{\nnamespace test\n{\n\nclass TestAtom: public AtomicComponent\n{\npublic:\n  TestAtom( SignalFlowContext & context, char const * name,\n            CompositeComponent * parent = nullptr )\n   : AtomicComponent( context, name, parent )\n    , mPolyInput( \"polyIn\", *this, pml::MatrixParameter<float>::staticType(),\n      pml::DoubleBufferingProtocol::staticType(), pml::MatrixParameterConfig( 4,5 ) )\n  {\n    BOOST_CHECK( mPolyInput.protocolType() == pml::DoubleBufferingProtocol::staticType() );\n  }\n\n  void process() override\n  {\n  }\nprivate:\n  PolymorphicParameterInput mPolyInput;\n};\n\nBOOST_AUTO_TEST_CASE( ParameterConnection )\n{\n  pml::initialiseParameterLibrary();\n\n  SignalFlowContext context( 64, 1024 );\n\n  TestAtom( context, \"PolyParameterTest\" );\n}\n\n} // namespace test\n} // namespace impl\n} // namespce visr\n", "meta": {"hexsha": "0b1836f3e06b215957e509eb8ffc0cdf50ff0c69", "size": 1575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libvisr/test/polymorphic_parameter_port.cpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/libvisr/test/polymorphic_parameter_port.cpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_issues_repo_licenses": ["ISC"], "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/libvisr/test/polymorphic_parameter_port.cpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 24.2307692308, "max_line_length": 91, "alphanum_fraction": 0.7574603175, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18669733575576}}
{"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 test/swapperformance.hpp\n    \\brief Swap Exposure preformance (1K swaps, 10K samples, 60 dates);\n    \\ingroup tests\n*/\n\n#pragma once\n\n#include <boost/test/unit_test.hpp>\n\nnamespace testsuite {\n\n//! Swap Exposure Performance tests\n/*!\n  \\ingroup tests\n*/\nclass SwapPerformanceTest {\npublic:\n    //! Test performance of simulating a single 20Y swap, 80 quatertly time steps, 1000 samples (\"None\" observation\n    // mode)\n    static void testSingleSwapPerformanceNoneObs();\n    //! Test performance of a portfolio of 100 swaps with 5 currencies and maturities between 2 and 30 years, 80\n    // quatertly time steps, 1000 samples (\"None\" observation mode)\n    static void testSwapPerformanceNoneObs();\n    //! Test performance of simulating a single 20Y swap, 80 quatertly time steps, 1000 samples (\"Disable\" observation\n    // mode)\n    static void testSingleSwapPerformanceDisableObs();\n    //! Test performance of a portfolio of 100 swaps with 5 currencies and maturities between 2 and 30 years, 80\n    // quatertly time steps, 1000 samples (\"Disable\" observation mode)\n    static void testSwapPerformanceDisableObs();\n    //! Test performance of simulating a single 20Y swap, 80 quatertly time steps, 1000 samples (\"Defer\" observation\n    // mode)\n    static void testSingleSwapPerformanceDeferObs();\n    //! Test performance of a portfolio of 100 swaps with 5 currencies and maturities between 2 and 30 years, 80\n    // quatertly time steps, 1000 samples (\"Defer\" observation mode)\n    static void testSwapPerformanceDeferObs();\n    //! Test performance of simulating a single 20Y swap, 80 quatertly time steps, 1000 samples (\"Unregister\"\n    // observation mode)\n    static void testSingleSwapPerformanceUnregisterObs();\n    //! Test performance of a portfolio of 100 swaps with 5 currencies and maturities between 2 and 30 years, 80\n    // quatertly time steps, 1000 samples (\"Unregister\" observation mode)\n    static void testSwapPerformanceUnregisterObs();\n    static boost::unit_test_framework::test_suite* suite();\n};\n} // namespace testsuite\n", "meta": {"hexsha": "4d9921e429ca2b05d42c76faec56c29b970f9185", "size": 2810, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/test/swapperformance.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": "OREAnalytics/test/swapperformance.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": "OREAnalytics/test/swapperformance.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": 44.6031746032, "max_line_length": 118, "alphanum_fraction": 0.7537366548, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.1866973286267461}}
{"text": "#include <dlib/image_processing/frontal_face_detector.h>\r\n#include <dlib/image_processing.h>\r\n#include <dlib/image_io.h>\r\n#include <dlib/opencv.h>\r\n#include <iostream>\r\n#include \"face_landmark_detection.h\"\r\n\r\nusing namespace dlib;\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\nvoid FD::getEyes(Mat& image, String classifierPath, bool setNull, Mat& leftEye, Mat& rightEye,\r\n                 Point& leftEyeOffset, Point& rightEyeOffset) {\r\n\tfrontal_face_detector detector = get_frontal_face_detector();\r\n\tshape_predictor sp;\r\n\tdeserialize(classifierPath + \"/shape_predictor_68_face_landmarks.dat\") >> sp;\r\n\r\n  array2d<rgb_pixel> dlibImage;\r\n  dlib::assign_image(dlibImage, dlib::cv_image<bgr_pixel>(image));\r\n\r\n\t// Make the image larger so we can detect small faces.\r\n\t//pyramid_up(dlibImage); //TODO: evaluate if necessary\r\n\r\n\tstd::vector<dlib::rectangle> dets = detector(dlibImage);\r\n\t// detect the rectangle for the eyes\r\n\tint min_x_l = image.cols;\r\n\tint max_x_l = 0;\r\n\tint min_y_l = image.rows;\r\n\tint max_y_l = 0;\r\n\tint min_x_r = image.cols;\r\n\tint max_x_r = 0;\r\n\tint min_y_r = image.rows;\r\n\tint max_y_r = 0;\r\n\tfor (unsigned long j = 0; j < dets.size(); ++j) {\r\n\t\tfull_object_detection shape = sp(dlibImage, dets[j]);\r\n\t\t// left eye\r\n\t\tfor (int k = 36; k <= 41; k++) {\r\n\t\t\tint x = (int)shape.part(k).x();\r\n\t\t\tint y = (int)shape.part(k).y();\r\n\t\t\tmin_x_l = min(min_x_l, x);\r\n\t\t\tmax_x_l = max(max_x_l, x);\r\n\t\t\tmin_y_l = min(min_y_l, y);\r\n\t\t\tmax_y_l = max(max_y_l, y);\r\n\t\t}\r\n\t\t// right eye\r\n\t\tfor (int k = 42; k <= 47; k++) {\r\n\t\t\tint x = (int)shape.part(k).x();\r\n\t\t\tint y = (int)shape.part(k).y();\r\n\t\t\tmin_x_r = min(min_x_r, x);\r\n\t\t\tmax_x_r = max(max_x_r, x);\r\n\t\t\tmin_y_r = min(min_y_r, y);\r\n\t\t\tmax_y_r = max(max_y_r, y);\r\n\t\t}\r\n\r\n    Mat destination;\r\n\t\tif (setNull) {\r\n\t\t\t// Create a copy and draw a black rectangle at the eyes. Using the landmarks the\r\n\t\t\t// eye polygons are filled with white. After copying the original image into\r\n\t\t\t// the mask, only the eye polygon remains and the rest is black.\r\n\t\t\tMat copy = image.clone();\r\n\r\n\t\t\t// Make rectangle black for eyes\r\n\t\t\tcv::rectangle(copy, Rect(min_x_l, min_y_l, max_x_l - min_x_l, max_y_l - min_y_l), Scalar(0, 0, 0), CV_FILLED);\r\n\t\t\tcv::rectangle(copy, Rect(min_x_r, min_y_r, max_x_r - min_x_r, max_y_r - min_y_r), Scalar(0, 0, 0), CV_FILLED);\r\n\r\n\t\t\t// Make polygons for eyes\r\n\t\t\tstd::vector<Point> fillSinglePolyL;\r\n\t\t\tstd::vector<Point> fillSinglePolyR;\r\n\t\t\tfor (int k = 36; k <= 41; k++) {\r\n\t\t\t\tfillSinglePolyL.push_back(Point((int)shape.part(k).x(), (int)shape.part(k).y()));\r\n\t\t\t}\r\n\t\t\tfor (int k = 42; k <= 47; k++) {\r\n\t\t\t\tfillSinglePolyR.push_back(Point((int)shape.part(k).x(), (int)shape.part(k).y()));\r\n\t\t\t}\r\n\t\t\tstd::vector<std::vector<Point>> fillContPolyL;\r\n\t\t\tfillContPolyL.push_back(fillSinglePolyL);\r\n\t\t\tstd::vector<std::vector<Point>> fillContPolyR;\r\n\t\t\tfillContPolyR.push_back(fillSinglePolyR);\r\n\t\t\tcv::fillPoly(copy, fillContPolyL, Scalar(255, 255, 255));\r\n\t\t\tcv::fillPoly(copy, fillContPolyR, Scalar(255, 255, 255));\r\n\r\n\t\t\t// Merge original with polygon\r\n      image.copyTo(destination, copy);\r\n    }\r\n    else {\r\n      destination = image.clone();\r\n    }\r\n\t\t// Cut the eyes\r\n\t\trightEye = Mat(destination, Rect(min_x_l, min_y_l, max_x_l - min_x_l, max_y_l - min_y_l));\r\n\t\tleftEye = Mat(destination, Rect(min_x_r, min_y_r, max_x_r - min_x_r, max_y_r - min_y_r));\r\n    leftEyeOffset = Point(min_x_l, min_y_l);\r\n    rightEyeOffset = Point(min_x_r, min_y_r);\r\n    // TODO: currently just the first face\r\n    break;\r\n\t}\r\n}", "meta": {"hexsha": "34b268a79003e4893cd37c1c19f5416f71b7ce40", "size": 3490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/face_landmark_detection.cpp", "max_stars_repo_name": "AstrorEnales/EyeCenterDetection", "max_stars_repo_head_hexsha": "6f921a36f03a2273a551fb7812bf451830257c28", "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/face_landmark_detection.cpp", "max_issues_repo_name": "AstrorEnales/EyeCenterDetection", "max_issues_repo_head_hexsha": "6f921a36f03a2273a551fb7812bf451830257c28", "max_issues_repo_licenses": ["MIT"], "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/face_landmark_detection.cpp", "max_forks_repo_name": "AstrorEnales/EyeCenterDetection", "max_forks_repo_head_hexsha": "6f921a36f03a2273a551fb7812bf451830257c28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T07:06:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T07:06:54.000Z", "avg_line_length": 36.3541666667, "max_line_length": 114, "alphanum_fraction": 0.6567335244, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18669732862674604}}
{"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_OPERATOR_FUNCTIONS_SIMD_SSE_SSE2_SHIFT_RIGHT_HPP_INCLUDED\n#define BOOST_SIMD_OPERATOR_FUNCTIONS_SIMD_SSE_SSE2_SHIFT_RIGHT_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n\n#include <boost/simd/operator/functions/shift_right.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/include/functions/simd/bitwise_or.hpp>\n#include <boost/simd/include/functions/simd/bitwise_ornot.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/include/functions/simd/is_ltz.hpp>\n#include <boost/simd/include/functions/simd/if_else_allbits.hpp>\n#include <boost/simd/include/functions/simd/group.hpp>\n#include <boost/simd/include/functions/simd/split.hpp>\n#include <boost/simd/include/constants/signmask.hpp>\n#include <boost/simd/include/constants/allbits.hpp>\n#include <boost/simd/include/constants/int_splat.hpp>\n#include <boost/simd/sdk/meta/make_dependent.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n\n  BOOST_DISPATCH_IMPLEMENT         ( shift_right_, boost::simd::tag::sse2_\n                            , (A0)(A1)\n                            , ((simd_<int8_<A0>,boost::simd::tag::sse_>))\n                              (scalar_< integer_<A1> >)\n                            )\n  {\n    typedef A0                                              result_type;\n    typedef typename meta::make_dependent<int16_t,A0>::type sub_t;\n    typedef native<sub_t, boost::simd::tag::sse_>           gen_t;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"shift_right sse2 int8: a shift is out of range\");\n      gen_t a0h, a0l;\n      split(a0, a0l, a0h);\n      return group(shift_right(a0l, a1), shift_right(a0h, a1));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT         ( shift_right_, boost::simd::tag::sse2_\n                            , (A0)(A1)\n                            , ((simd_<int16_<A0>,boost::simd::tag::sse_>))\n                              (scalar_< integer_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"shift_right sse2 int16: a shift is out of range\");\n      return _mm_srai_epi16(a0, int(a1));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT         ( shift_right_, boost::simd::tag::sse2_\n                            , (A0)(A1)\n                            , ((simd_<int32_<A0>,boost::simd::tag::sse_>))\n                              (scalar_< integer_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"shift_right sse2 int32: a shift is out of range\");\n      return _mm_srai_epi32(a0, int(a1));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( shift_right_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<int64_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"shift_right sse2 int64: a shift is out of range\");\n      A0 that = _mm_srli_epi64(a0, int(a1));\n      A0 mask = _mm_srli_epi64(Allbits<A0>(), int(a1));\n      return b_ornot(that, if_else_allbits(is_ltz(a0), mask));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( shift_right_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<uint8_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    typedef typename meta::make_dependent<int32_t,A0>::type int_t;\n\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"shift_right sse2 uint8: a shift is out of range\");\n      typedef native<int_t, boost::simd::tag::sse_> gen_type;\n      result_type const Mask1 = bitwise_cast<result_type>(boost::simd::integral_constant<gen_type, int_t(0x00ff00ff)>());\n      result_type const Mask2 = bitwise_cast<result_type>(boost::simd::integral_constant<gen_type, int_t(0xff00ff00)>());\n\n      result_type tmp  = b_and(a0, Mask1);\n      result_type tmp1 = _mm_srli_epi16(tmp, int(a1));\n      tmp1 = b_and(tmp1, Mask1);\n      tmp = b_and(a0, Mask2);\n      result_type tmp3 = _mm_srli_epi16(tmp, int(a1));\n      return tmp1 | b_and(tmp3, Mask2);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( shift_right_, boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<uint16_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"shift_right sse2 uint16: a shift is out of range\");\n      return _mm_srli_epi16(a0, int(a1));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( shift_right_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<uint32_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"shift_right sse2 uint32: a shift is out of range\");\n      return _mm_srli_epi32(a0, int(a1));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( shift_right_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<uint64_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), \"shift_right sse2 uint64: a shift is out of range\");\n      return _mm_srli_epi64(a0, int(a1));\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "b2f0272e5ceff33d1b0a2ccee1eb1f5faee95009", "size": 6788, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/operator/functions/simd/sse/sse2/shift_right.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/operator/functions/simd/sse/sse2/shift_right.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/operator/functions/simd/sse/sse2/shift_right.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": 40.8915662651, "max_line_length": 121, "alphanum_fraction": 0.5383028874, "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1865594640655067}}
{"text": "/**\n * @file PlmLanguageRanker.cpp\n * @author Ian Yang\n * @date Created <2009-09-24 09:47:22>\n * @date Updated <2010-03-24 15:29:22>\n * @brief\n */\n#include \"PlmLanguageRanker.h\"\n\n#include <util/get.h>\n\n#include <boost/assert.hpp>\n\n#include <stdexcept>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nnamespace sf1r {\n\nPlmLanguageRanker::PlmLanguageRanker(\n        const TermProximityMeasure* termProximityMeasure,\n        float smooth,\n        float proximity\n)\n    : termProximityMeasure_(termProximityMeasure)\n    , smoothArg_(smooth)\n    , proximityArg_(proximity)\n    , termProximityArray_()\n{}\n\nPlmLanguageRanker::~PlmLanguageRanker()\n{\n    delete termProximityMeasure_;\n    termProximityMeasure_ = 0;\n}\n\nPlmLanguageRanker::PlmLanguageRanker(const PlmLanguageRanker& rhs)\n    : termProximityMeasure_(0)\n    , smoothArg_(rhs.smoothArg_)\n    , proximityArg_(rhs.proximityArg_)\n{\n    if (rhs.termProximityMeasure_)\n    {\n        termProximityMeasure_ = rhs.termProximityMeasure_->clone();\n    }\n}\n\nPlmLanguageRanker& PlmLanguageRanker::operator=(const PlmLanguageRanker& rhs)\n{\n    if (this != &rhs)\n    {\n        const TermProximityMeasure* cloned = 0;\n        if (rhs.termProximityMeasure_)\n        {\n            cloned = rhs.termProximityMeasure_->clone();\n        }\n\n        termProximityMeasure_ = cloned;\n        smoothArg_ = rhs.smoothArg_;\n        proximityArg_ = rhs.proximityArg_;\n    }\n\n    return *this;\n}\n\nvoid PlmLanguageRanker::setTermProximityMeasure(\n        const TermProximityMeasure* termProximityMeasure\n)\n{\n    if (termProximityMeasure != termProximityMeasure_)\n    {\n        const TermProximityMeasure* orig = termProximityMeasure_;\n        termProximityMeasure_ = termProximityMeasure;\n        delete orig;\n    }\n}\n\n\n\n\nfloat PlmLanguageRanker::getScoreSVD(\n        const RankQueryProperty& queryProperty,\n        const RankDocumentProperty& documentProperty,\n        const vector<double>& queryTF_d,\n        const vector<double>& queryTF,\n        const vector<double>& collTF\n) const\n{\n    bool USEPROX = true;\n\n    //USEPROX = true;\n    float score = 0.0F;\n    if (0.0F == queryProperty.getAveragePropertyLength())\n        return score;\n\n    std::size_t numTerms = documentProperty.size();\n    termProximityArray_.resize(numTerms);\n\n    if (numTerms > 1)\n    {\n        // calculates term proximity in array parallel to\n        // textQuery.termPositions\n        termProximityMeasure_->calculate(\n                documentProperty,\n                termProximityArray_\n        );\n    }\n    else if (numTerms == 1)\n    {\n        termProximityArray_[0] = 0.0F;\n    }\n\n    TermProximityMeasure::array_type::const_iterator termProximity\n        = termProximityArray_.begin();\n    for (RankDocumentProperty::size_type i = 0;\n            i != documentProperty.size(); ++i, ++termProximity)\n    {\n        float tfInDoc = documentProperty.termFreqAt(i);\n        float tfInQuery = queryProperty.termFreqAt(i);\n\n        //if(queryTF.size() > 0)\n        //tfInQuery = queryTF[i];\n\n        if (!collTF.empty())\n        {\n            //cout << \"YAY!\";\n            tfInDoc = collTF[i];\n        }\n\n        //double tfInQuery = queryTF[i];\n\n        //double tfInQuery = queryTF_d[i];\n        //double tfInQuery = .1;\n\n        if (tfInDoc > 0.0F)\n        {\n            float proximityFactor = *termProximity;\n            //double proximityFactor = termProximityVector[i];\n\n            float collectionMLE =\n                    queryProperty.totalTermFreqAt(i) /\n                    queryProperty.getTotalPropertyLength();\n\n            //double collectionMLE = queryTF[i];\n\n            float seenDocProb =\n                    tfInDoc\n                    + smoothArg_ * collectionMLE\n                    + proximityArg_ * proximityFactor;\n            // / (smoothArg_ + docTokenCount + proxWeight)\n\n            float unseenDocProb = collectionMLE * smoothArg_;\n            // / (smoothArg_ + docTokenCount + proxWeight)\n\n\n\n            if (USEPROX)\n            {\n                score += tfInQuery\n                        / queryProperty.getQueryLength()\n                        * std::log(seenDocProb / unseenDocProb);\n            }\n            else\n            {\n                score += tfInQuery / queryProperty.getQueryLength();\n            }\n\n\n        }\n    }\n\n    if (score > 0.0F)\n    {\n        float docTokenCount = documentProperty.docLength();\n        float proxWeight =\n                proximityArg_\n                * std::accumulate(\n                        termProximityArray_.begin(),\n                        termProximityArray_.begin() + documentProperty.size(),\n                        0.0F\n                );\n\n        if (USEPROX)\n        {\n            score += std::log((smoothArg_ ) / (smoothArg_ + docTokenCount + proxWeight));\n        }\n        else\n        {\n            score += std::log((smoothArg_ ) / (smoothArg_ + docTokenCount));\n        }\n    } // end - if\n\n    return score;\n} // end PlmLanguageRanker::getScore()\n\nfloat PlmLanguageRanker::getScore(\n        const RankQueryProperty& queryProperty,\n        const RankDocumentProperty& documentProperty\n) const\n{\n    //BOOST_ASSERT(termProximityMeasure_);\n    if (!termProximityMeasure_)\n    {\n        throw std::runtime_error(\n                \"Term Proximity Measure has not been specified\"\n        );\n    }\n\n    float score = 0.0F;\n    if (0.0F == queryProperty.getAveragePropertyLength())\n    {\n        return score;\n    }\n\n    std::size_t numTerms = documentProperty.size();\n    termProximityArray_.resize(numTerms);\n\n    if (numTerms > 1)\n    {\n        // calculates term proximity in array parallel to\n        // textQuery.termPositions\n        termProximityMeasure_->calculate(\n                documentProperty,\n                termProximityArray_\n        );\n    }\n    else if (numTerms == 1)\n    {\n        termProximityArray_[0] = 0.0F;\n    }\n\n    TermProximityMeasure::array_type::const_iterator termProximity\n    = termProximityArray_.begin();\n    for (RankDocumentProperty::size_type i = 0;\n            i != documentProperty.size(); ++i, ++termProximity)\n    {\n        float tfInDoc = documentProperty.termFreqAt(i);\n        float tfInQuery = queryProperty.termFreqAt(i);\n        // cout << \"TF: \" << i << \",\" << tfInQuery << \",\" << tfInDoc << endl;\n\n        if (tfInDoc > 0.0F)\n        {\n            float proximityFactor = *termProximity;\n\n            float collectionMLE =\n                queryProperty.totalTermFreqAt(i) /\n                queryProperty.getTotalPropertyLength();\n\n\n            float seenDocProb =\n                tfInDoc\n                + smoothArg_ * collectionMLE\n                + proximityArg_ * proximityFactor;\n            // / (smoothArg_ + docTokenCount + proxWeight)\n\n            float unseenDocProb = collectionMLE * smoothArg_;\n            // / (smoothArg_ + docTokenCount + proxWeight)\n\n            score += tfInQuery\n                / queryProperty.getQueryLength()\n                * std::log(seenDocProb / unseenDocProb);\n        }\n    }\n\n    if (score > 0.0F)\n    {\n        float docTokenCount = documentProperty.docLength();\n        float proxWeight =\n            proximityArg_\n            * std::accumulate(\n                    termProximityArray_.begin(),\n                    termProximityArray_.begin() + documentProperty.size(),\n                    0.0F\n                    );\n\n        score += std::log(\n                (smoothArg_ )\n                / (smoothArg_ + docTokenCount + proxWeight)\n        );\n    } // end - if\n\n    return score;\n} // end PlmLanguageRanker::getScore()\n\nPlmLanguageRanker* PlmLanguageRanker::clone() const\n{\n    return new PlmLanguageRanker(*this);\n}\n\n} // namespace sf1r\n", "meta": {"hexsha": "e88177cf023ea724d36431373fa768c1edf80a4e", "size": 7646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/core/ranking-manager/PlmLanguageRanker.cpp", "max_stars_repo_name": "izenecloud/sf1r-lite", "max_stars_repo_head_hexsha": "8de9aa83c38c9cd05a80b216579552e89609f136", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T20:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T18:40:49.000Z", "max_issues_repo_path": "source/core/ranking-manager/PlmLanguageRanker.cpp", "max_issues_repo_name": "fytzzh/sf1r-lite", "max_issues_repo_head_hexsha": "8de9aa83c38c9cd05a80b216579552e89609f136", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-28T08:55:47.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-10T10:10:53.000Z", "max_forks_repo_path": "source/core/ranking-manager/PlmLanguageRanker.cpp", "max_forks_repo_name": "fytzzh/sf1r-lite", "max_forks_repo_head_hexsha": "8de9aa83c38c9cd05a80b216579552e89609f136", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T03:03:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T04:22:46.000Z", "avg_line_length": 26.0955631399, "max_line_length": 89, "alphanum_fraction": 0.5799110646, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.18655945682256403}}
{"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// 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_ALGORITHMS_MAKE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_MAKE_HPP\n\n#include <boost/geometry/algorithms/assign.hpp>\n\n#include <boost/geometry/geometries/concepts/check.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace make\n{\n\n/*!\n\\brief Construct a geometry\n\\ingroup make\n\\tparam Geometry \\tparam_geometry\n\\tparam Range \\tparam_range_point\n\\param range \\param_range_point\n\\return The constructed geometry, here: a linestring or a ring\n\n\\qbk{distinguish, with a range}\n\\qbk{\n[heading Example]\n[make_with_range] [make_with_range_output]\n\n[heading See also]\n\\* [link geometry.reference.algorithms.assign.assign_points assign]\n}\n */\ntemplate <typename Geometry, typename Range>\ninline Geometry make_points(Range const& range)\n{\n    concept::check<Geometry>();\n\n    Geometry geometry;\n    geometry::append(geometry, range);\n    return geometry;\n}\n\n}} // namespace detail::make\n#endif // DOXYGEN_NO_DETAIL\n\n/*!\n\\brief Construct a geometry\n\\ingroup make\n\\details\n\\note It does not work with array-point types, like int[2]\n\\tparam Geometry \\tparam_geometry\n\\tparam Type \\tparam_numeric to specify the coordinates\n\\param c1 \\param_x\n\\param c2 \\param_y\n\\return The constructed geometry, here: a 2D point\n\n\\qbk{distinguish, 2 coordinate values}\n\\qbk{\n[heading Example]\n[make_2d_point] [make_2d_point_output]\n\n[heading See also]\n\\* [link geometry.reference.algorithms.assign.assign_values_3_2_coordinate_values assign]\n}\n*/\ntemplate <typename Geometry, typename Type>\ninline Geometry make(Type const& c1, Type const& c2)\n{\n    concept::check<Geometry>();\n\n    Geometry geometry;\n    dispatch::assign\n        <\n            typename tag<Geometry>::type,\n            Geometry,\n            geometry::dimension<Geometry>::type::value\n        >::apply(geometry, c1, c2);\n    return geometry;\n}\n\n/*!\n\\brief Construct a geometry\n\\ingroup make\n\\tparam Geometry \\tparam_geometry\n\\tparam Type \\tparam_numeric to specify the coordinates\n\\param c1 \\param_x\n\\param c2 \\param_y\n\\param c3 \\param_z\n\\return The constructed geometry, here: a 3D point\n\n\\qbk{distinguish, 3 coordinate values}\n\\qbk{\n[heading Example]\n[make_3d_point] [make_3d_point_output]\n\n[heading See also]\n\\* [link geometry.reference.algorithms.assign.assign_values_4_3_coordinate_values assign]\n}\n */\ntemplate <typename Geometry, typename Type>\ninline Geometry make(Type const& c1, Type const& c2, Type const& c3)\n{\n    concept::check<Geometry>();\n\n    Geometry geometry;\n    dispatch::assign\n        <\n            typename tag<Geometry>::type,\n            Geometry,\n            geometry::dimension<Geometry>::type::value\n        >::apply(geometry, c1, c2, c3);\n    return geometry;\n}\n\ntemplate <typename Geometry, typename Type>\ninline Geometry make(Type const& c1, Type const& c2, Type const& c3, Type const& c4)\n{\n    concept::check<Geometry>();\n\n    Geometry geometry;\n    dispatch::assign\n        <\n            typename tag<Geometry>::type,\n            Geometry,\n            geometry::dimension<Geometry>::type::value\n        >::apply(geometry, c1, c2, c3, c4);\n    return geometry;\n}\n\n\n\n\n\n/*!\n\\brief Construct a box with inverse infinite coordinates\n\\ingroup make\n\\details The make_inverse function initializes a 2D or 3D box with large coordinates, the\n    min corner is very large, the max corner is very small. This is useful e.g. in combination\n    with the expand function, to determine the bounding box of a series of geometries.\n\\tparam Geometry \\tparam_geometry\n\\return The constructed geometry, here: a box\n\n\\qbk{\n[heading Example]\n[make_inverse] [make_inverse_output]\n\n[heading See also]\n\\* [link geometry.reference.algorithms.assign.assign_inverse assign_inverse]\n}\n */\ntemplate <typename Geometry>\ninline Geometry make_inverse()\n{\n    concept::check<Geometry>();\n\n    Geometry geometry;\n    dispatch::assign_inverse\n        <\n            typename tag<Geometry>::type,\n            Geometry\n        >::apply(geometry);\n    return geometry;\n}\n\n/*!\n\\brief Construct a geometry with its coordinates initialized to zero\n\\ingroup make\n\\details The make_zero function initializes a 2D or 3D point or box with coordinates of zero\n\\tparam Geometry \\tparam_geometry\n\\return The constructed and zero-initialized geometry\n */\ntemplate <typename Geometry>\ninline Geometry make_zero()\n{\n    concept::check<Geometry>();\n\n    Geometry geometry;\n    dispatch::assign_zero\n        <\n            typename tag<Geometry>::type,\n            Geometry\n        >::apply(geometry);\n    return geometry;\n}\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_MAKE_HPP\n", "meta": {"hexsha": "a34afd06a2109ecc3f4d98de82a796620ca9bcde", "size": 5256, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/make.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/make.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/make.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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.1492537313, "max_line_length": 116, "alphanum_fraction": 0.7260273973, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061854293323, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.18655886533191898}}
{"text": "// This file is part of ViViA, and is distributed under the\n// OSI-approved BSD 3-Clause License. See top-level LICENSE file or\n// https://github.com/Kitware/vivia/blob/master/LICENSE for details.\n\n#include \"vtkVgNitfMetaDataParser.h\"\n\n#include \"vtkVgNitfEngrda.h\"\n\n#include <vgStringUtils.h>\n\n#include <vtkVgTimeStamp.h>\n\n// Boost includes\n#include <boost/date_time/gregorian/conversion.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n// C/C++ includes\n#include <ctime>\n\nnamespace bt = boost::posix_time;\n\n//----------------------------------------------------------------------------\nnamespace\n{\n  // FIXME Move this code somewhere else\n  // Convert boost posix time to std time\n  std::time_t Convert(const bt::ptime& pt)\n    {\n      bt::ptime timet_start(boost::gregorian::date(1970,1,1));\n      bt::time_duration diff = pt - timet_start;\n      return diff.total_milliseconds();\n    }\n\n  int ConvertToInt(const std::string& str)\n    {\n    int result;\n    std::istringstream iss (str);\n    iss >> result;\n    return result;\n    }\n}\n\n//----------------------------------------------------------------------------\nbool vtkVgNitfMetaDataParser::ParseDateTime(\n  const std::vector<std::string>& mdata,\n  const std::vector<std::string>& treMetaData,\n  vtkVgTimeStamp& time)\n{\n  if (mdata.empty())\n    {\n    return false;\n    }\n\n  std::vector<std::string> tokens;\n\n  for (size_t i = 0; i < mdata.size(); ++i)\n    {\n    size_t found = mdata[i].find(\"NITF_IDATIM\");\n    if (found != std::string::npos)\n      {\n      tokens = vgStringUtils::Split(mdata[i], '=');\n\n      // We get time in CCYYMMDDhhmmss format, that is\n      // (century, year, months, hours, minutes, and seconds)\n      if (tokens[1].empty())\n        {\n        return false;\n        }\n      else\n        {\n        break;\n        }\n      }\n    }\n\n  std::string nitfTime = tokens[1];\n  std::tm utm;\n\n  int years = 1970;\n  int months = 0;\n  int days = 0;\n  int hrs = 0;\n  int mins = 0;\n  int secs = 0;\n  // Milliseconds\n  int ms = -1;\n\n  years = ConvertToInt(std::string(nitfTime, 0, 4)) - 1900;\n  months = ConvertToInt(std::string(nitfTime, 4, 2)) - 1;\n  days = ConvertToInt(std::string(nitfTime, 6, 2));\n  hrs = ConvertToInt(std::string(nitfTime, 8, 2));\n  mins = ConvertToInt(std::string(nitfTime, 10, 2));\n  secs = ConvertToInt(std::string(nitfTime, 12, 2));\n\n  for (size_t i = 0; i < treMetaData.size(); ++i)\n    {\n    size_t found = treMetaData[i].find(\"ENGRDA\");\n\n    if (found != std::string::npos)\n      {\n      tokens = vgStringUtils::Split(treMetaData[i], '=');\n\n      if (!tokens[1].empty())\n        {\n        std::string msstr;\n        vtkVgNitfEngrda nitfEngdra;\n        vtkVgNitfMetaDataParser::ParseEngrda(tokens[1], nitfEngdra);\n        auto mseconds = nitfEngdra.Get(\"milliseconds\");\n        if (mseconds)\n          {\n          mseconds->GetData(msstr);\n\n          if (!msstr.empty())\n            {\n            ms = ConvertToInt(msstr);\n            }\n          }\n        }\n      }\n    }\n\n  // If ms data not read from ENGRDA, look for it in the NITF_IMAGE_COMMENTS\n  if (ms < 0)\n    {\n    for (size_t i = 0; i < mdata.size(); ++i)\n      {\n      size_t found = mdata[i].find(\"NITF_IMAGE_COMMENTS\");\n      if (found != std::string::npos)\n        {\n        tokens = vgStringUtils::Split(mdata[i], ' ');\n\n        // Format: \"     COLLECTION TIMESTAMP: 20150731184301.043659    UTC\"\n        for (int i = 0; i < tokens.size() - 2; ++i)\n          {\n          if (tokens[i] == \"COLLECTION\" && tokens[i + 1] == \"TIMESTAMP:\")\n            {\n            // Split date/time in secs from data after the decimal point\n            tokens = vgStringUtils::Split(tokens[i + 2], '.');\n            // Make sure we have exactly 3 characters\n            tokens[1].resize(3, '0');\n            ms = ConvertToInt(tokens[1]);\n            }\n          }\n\n        break;\n        }\n      }\n    }\n\n  utm.tm_mday = days;\n  utm.tm_mon = months;\n  utm.tm_year = years;\n\n  boost::posix_time::ptime pt (boost::gregorian::date_from_tm(utm),\n    bt::hours(hrs) + bt::minutes(mins) + bt::seconds(secs) +\n    bt::milliseconds(ms > -1 ? ms : 0));\n\n  // To micoseconds\n  time.SetTime(static_cast<double>(Convert(pt)) * 1e3);\n\n  return true;\n}\n\n//----------------------------------------------------------------------------\nbool vtkVgNitfMetaDataParser::ParseEngrda(const char* data, int len,\n                                          vtkVgNitfEngrda& engrda)\n{\n  return engrda.Parse(data, len);\n}\n", "meta": {"hexsha": "0b1bd6a0a8b8b15278a9c1be222841d6d9f67560", "size": 4492, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Libraries/VtkVgIO/vtkVgNitfMetaDataParser.cxx", "max_stars_repo_name": "PinkDiamond1/vivia", "max_stars_repo_head_hexsha": "70f7fbed4b33b14d34de35c69b2b14df3514d720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2016-09-16T12:33:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T02:16:33.000Z", "max_issues_repo_path": "Libraries/VtkVgIO/vtkVgNitfMetaDataParser.cxx", "max_issues_repo_name": "PinkDiamond1/vivia", "max_issues_repo_head_hexsha": "70f7fbed4b33b14d34de35c69b2b14df3514d720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-10-06T22:12:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T19:39:07.000Z", "max_forks_repo_path": "Libraries/VtkVgIO/vtkVgNitfMetaDataParser.cxx", "max_forks_repo_name": "PinkDiamond1/vivia", "max_forks_repo_head_hexsha": "70f7fbed4b33b14d34de35c69b2b14df3514d720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-06-30T13:41:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T17:38:48.000Z", "avg_line_length": 26.269005848, "max_line_length": 78, "alphanum_fraction": 0.5547640249, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.370225399544253, "lm_q1q2_score": 0.1865588633169433}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#if (defined(__aarch64__)) || (defined(__x86_64__)) // disable test failing on FireFly/Armv7\n\n#include \"ClWorkloadFactoryHelper.hpp\"\n\n#include <test/TensorHelpers.hpp>\n\n#include <backendsCommon/TensorHandle.hpp>\n#include <backendsCommon/WorkloadFactory.hpp>\n\n#include <cl/ClContextControl.hpp>\n#include <cl/ClWorkloadFactory.hpp>\n#include <cl/OpenClTimer.hpp>\n\n#include <backendsCommon/test/TensorCopyUtils.hpp>\n#include <backendsCommon/test/WorkloadTestUtils.hpp>\n\n#include <arm_compute/runtime/CL/CLScheduler.h>\n\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n\nusing namespace armnn;\n\nstruct OpenClFixture\n{\n    // Initialising ClContextControl to ensure OpenCL is loaded correctly for each test case.\n    // NOTE: Profiling needs to be enabled in ClContextControl to be able to obtain execution\n    // times from OpenClTimer.\n    OpenClFixture() : m_ClContextControl(nullptr, nullptr, true) {}\n    ~OpenClFixture() {}\n\n    ClContextControl m_ClContextControl;\n};\n\nBOOST_FIXTURE_TEST_SUITE(OpenClTimerBatchNorm, OpenClFixture)\nusing FactoryType = ClWorkloadFactory;\n\nBOOST_AUTO_TEST_CASE(OpenClTimerBatchNorm)\n{\n    auto memoryManager = ClWorkloadFactoryHelper::GetMemoryManager();\n    ClWorkloadFactory workloadFactory = ClWorkloadFactoryHelper::GetFactory(memoryManager);\n\n    const unsigned int width    = 2;\n    const unsigned int height   = 3;\n    const unsigned int channels = 2;\n    const unsigned int num      = 1;\n\n    TensorInfo inputTensorInfo( {num, channels, height, width}, DataType::Float32);\n    TensorInfo outputTensorInfo({num, channels, height, width}, DataType::Float32);\n    TensorInfo tensorInfo({channels}, DataType::Float32);\n\n    auto input = MakeTensor<float, 4>(inputTensorInfo,\n        {\n             1.f, 4.f,\n             4.f, 2.f,\n             1.f, 6.f,\n\n             1.f, 1.f,\n             4.f, 1.f,\n            -2.f, 4.f\n        });\n\n    // these values are per-channel of the input\n    auto mean     = MakeTensor<float, 1>(tensorInfo, { 3.f, -2.f });\n    auto variance = MakeTensor<float, 1>(tensorInfo, { 4.f,  9.f });\n    auto beta     = MakeTensor<float, 1>(tensorInfo, { 3.f,  2.f });\n    auto gamma    = MakeTensor<float, 1>(tensorInfo, { 2.f,  1.f });\n\n    ARMNN_NO_DEPRECATE_WARN_BEGIN\n    std::unique_ptr<ITensorHandle> inputHandle = workloadFactory.CreateTensorHandle(inputTensorInfo);\n    std::unique_ptr<ITensorHandle> outputHandle = workloadFactory.CreateTensorHandle(outputTensorInfo);\n    ARMNN_NO_DEPRECATE_WARN_END\n\n    BatchNormalizationQueueDescriptor data;\n    WorkloadInfo info;\n    ScopedTensorHandle meanTensor(tensorInfo);\n    ScopedTensorHandle varianceTensor(tensorInfo);\n    ScopedTensorHandle betaTensor(tensorInfo);\n    ScopedTensorHandle gammaTensor(tensorInfo);\n\n    AllocateAndCopyDataToITensorHandle(&meanTensor, &mean[0]);\n    AllocateAndCopyDataToITensorHandle(&varianceTensor, &variance[0]);\n    AllocateAndCopyDataToITensorHandle(&betaTensor, &beta[0]);\n    AllocateAndCopyDataToITensorHandle(&gammaTensor, &gamma[0]);\n\n    AddInputToWorkload(data, info, inputTensorInfo, inputHandle.get());\n    AddOutputToWorkload(data, info, outputTensorInfo, outputHandle.get());\n    data.m_Mean             = &meanTensor;\n    data.m_Variance         = &varianceTensor;\n    data.m_Beta             = &betaTensor;\n    data.m_Gamma            = &gammaTensor;\n    data.m_Parameters.m_Eps = 0.0f;\n\n    // for each channel:\n    // substract mean, divide by standard deviation (with an epsilon to avoid div by 0)\n    // multiply by gamma and add beta\n    std::unique_ptr<IWorkload> workload = workloadFactory.CreateBatchNormalization(data, info);\n\n    inputHandle->Allocate();\n    outputHandle->Allocate();\n\n    CopyDataToITensorHandle(inputHandle.get(), &input[0][0][0][0]);\n\n    OpenClTimer openClTimer;\n\n    BOOST_CHECK_EQUAL(openClTimer.GetName(), \"OpenClKernelTimer\");\n\n    //Start the timer\n    openClTimer.Start();\n\n    //Execute the workload\n    workload->Execute();\n\n    //Stop the timer\n    openClTimer.Stop();\n\n    BOOST_CHECK_EQUAL(openClTimer.GetMeasurements().size(), 1);\n\n    BOOST_CHECK_EQUAL(openClTimer.GetMeasurements().front().m_Name,\n                      \"OpenClKernelTimer/0: batchnormalization_layer_nchw GWS[1,3,2]\");\n\n    BOOST_CHECK(openClTimer.GetMeasurements().front().m_Value > 0);\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#endif //aarch64 or x86_64\n", "meta": {"hexsha": "1b86d2e304706199521bb0448155cd44fc84ed90", "size": 4424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/cl/test/OpenClTimerTest.cpp", "max_stars_repo_name": "tuanhe/armnn", "max_stars_repo_head_hexsha": "8a4bd6671d0106dfb788b8c9019f2f9646770f8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-03T23:46:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T23:46:08.000Z", "max_issues_repo_path": "src/backends/cl/test/OpenClTimerTest.cpp", "max_issues_repo_name": "tuanhe/armnn", "max_issues_repo_head_hexsha": "8a4bd6671d0106dfb788b8c9019f2f9646770f8d", "max_issues_repo_licenses": ["MIT"], "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/backends/cl/test/OpenClTimerTest.cpp", "max_forks_repo_name": "tuanhe/armnn", "max_forks_repo_head_hexsha": "8a4bd6671d0106dfb788b8c9019f2f9646770f8d", "max_forks_repo_licenses": ["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.7703703704, "max_line_length": 103, "alphanum_fraction": 0.7097649186, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1865588598154675}}
{"text": "/*\n * \tgrasp.hpp\n *\n *\tAuthor(s): Tamas D. Nagy\n *\tCreated on: 2017-11-08\n *\n *  Grasp the object received in the topic 'saf/vision/target'.\n *\n */\n\n#ifndef CAMERA_HPP_\n#define CAMERA_HPP_\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <cmath>\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <cmath>\n#include <limits>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry> \n\n#include <geometry_msgs/Point.h>\n\n#include <irob_utils/tool_pose.hpp>\n#include <irob_utils/utils.hpp>\n#include <irob_utils/abstract_directions.hpp>\n#include <irob_motion/surgeme_client.hpp>\n#include <irob_vision_support/vision_client.hpp>\n\n#include <irob_subtask_logic/autosurg_agent.hpp>\n\n\nnamespace saf {\n\nclass Camera : public AutosurgAgent {\n\n\nprotected:\n\n  VisionClient<geometry_msgs::Point,Eigen::Vector3d> vision;\n  double speed_carthesian;\n  double marker_dist_threshold;\n  double marker_dist_desired;\n  double marker_threshold;\n  double camera_offset_x;\n  double camera_offset_y;\n\npublic:\n  Camera(ros::NodeHandle, ros::NodeHandle, std::vector<std::string>, double, double, double, double, double, double);\n  ~Camera();\n  void moveCam();\n\n};\n\n}\n#endif /* CAMERA_HPP_ */\n", "meta": {"hexsha": "4efdc1321576e2263e772d96fd4fcc604c4b9c91", "size": 1191, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "irob_subtask_logic/include/irob_subtask_logic/camera.hpp", "max_stars_repo_name": "ABC-iRobotics/irob-saf", "max_stars_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-06-07T22:56:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:56:36.000Z", "max_issues_repo_path": "irob_subtask_logic/include/irob_subtask_logic/camera.hpp", "max_issues_repo_name": "ABC-iRobotics/irob-saf", "max_issues_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T10:04:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T13:45:25.000Z", "max_forks_repo_path": "irob_subtask_logic/include/irob_subtask_logic/camera.hpp", "max_forks_repo_name": "ABC-iRobotics/irob-saf", "max_forks_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T23:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T23:33:43.000Z", "avg_line_length": 19.2096774194, "max_line_length": 117, "alphanum_fraction": 0.7405541562, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1865588598154674}}
{"text": "\n#include <ros/ros.h>\n#include <iostream>\n#include <math.h>\n#include <boost/lexical_cast.hpp>\n\n#include <sstream>\n#include <fstream>\n#include \"functions/FormattedTime.h\"\n\n#include <QtGui/QGuiApplication>\n#include <QApplication>\n#include \"BaseStation.h\"\n\n#ifndef PI\n#define PI 3.14159265\n#endif\n\nusing namespace std;\n\n// Initial time (time when the first message arrived\nbool init_time = false;\nfunctions::FormattedTime t;\n\nint main(int argc, char** argv)\n{\n  \n  QApplication app(argc, argv);\n  BaseStation foo(argc, argv);\n  foo.show();\n  int ret_val = app.exec();\n//   ros::waitForShutdown();\n  \n  return ret_val;\n}\n\n", "meta": {"hexsha": "722f5b6f29632b048bd227b9c24d877da2b927bc", "size": 618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "base_station/src/base_station.cpp", "max_stars_repo_name": "robotics-upo/siar_remote_packages", "max_stars_repo_head_hexsha": "09bbbc88fb656524cc523a95704e7d353e260876", "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": "base_station/src/base_station.cpp", "max_issues_repo_name": "robotics-upo/siar_remote_packages", "max_issues_repo_head_hexsha": "09bbbc88fb656524cc523a95704e7d353e260876", "max_issues_repo_licenses": ["MIT"], "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_station/src/base_station.cpp", "max_forks_repo_name": "robotics-upo/siar_remote_packages", "max_forks_repo_head_hexsha": "09bbbc88fb656524cc523a95704e7d353e260876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-10T07:39:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T07:39:33.000Z", "avg_line_length": 16.7027027027, "max_line_length": 52, "alphanum_fraction": 0.715210356, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.1865588528125158}}
{"text": "// This file is part of VIO - Semi-direct Visual Odometry.\n//\n// Copyright (C) 2014 Christian Forster <forster at ifi dot uzh dot ch>\n// (Robotics and Perception Group, University of Zurich, Switzerland).\n//\n// VIO is free software: you can redistribute it and/or modify it under the\n// terms of the GNU General Public License as published by the Free Software\n// Foundation, either version 3 of the License, or any later version.\n//\n// VIO is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the 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 <algorithm>\n#include <vio/vision.h>\n#include <boost/bind.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <vio/global.h>\n#include <vio/global_optimizer.h>\n#include <vio/frame.h>\n#include <vio/point.h>\n#include <vio/feature.h>\n#include <vio/config.h>\n#include <g2o/solvers/structure_only/structure_only_solver.h>\n#if VIO_DEBUG\n#include <sys/types.h>\n#include <sys/stat.h>\n#endif\nnamespace vio {\n\n\n    BA_Glob::BA_Glob(Map& map) :map_(map),thread_(NULL)\n    {\n        optimizer_=std::make_unique<g2o::SparseOptimizer>();\n        optimizer_->setVerbose(false);\n        /*g2o::BlockSolver_6_3::LinearSolverType * linearSolver=new g2o::LinearSolverCholmod<g2o::BlockSolver_6_3::PoseMatrixType>();*/\n        std::unique_ptr<g2o::BlockSolver_6_3::LinearSolverType> linearSolver=g2o::make_unique<g2o::LinearSolverCSparse<g2o::BlockSolver_6_3::PoseMatrixType>>();\n        std::unique_ptr<g2o::OptimizationAlgorithm> solver(new g2o::OptimizationAlgorithmLevenberg(\n                g2o::make_unique<g2o::BlockSolver_6_3>(std::move(linearSolver))));\n        optimizer_->setAlgorithm(std::move(solver));\n        // setup camera\n        cam_params_ =std::make_shared<g2o::CameraParameters>(1.0, Vector2d(0.,0.), 0.);\n        cam_params_->setId(0);\n        if (!optimizer_->addParameter(cam_params_)) {\n            assert(false && \"Camera initialization in BA\");\n        }\n#if VIO_DEBUG\n        log_ =fopen((std::string(PROJECT_DIR)+\"/loop_closure_log.txt\").c_str(),\"w+\");\n        assert(log_);\n        chmod((std::string(PROJECT_DIR)+\"/loop_closure_log.txt\").c_str(), ACCESSPERMS);\n#endif\n    }\n\n    BA_Glob::~BA_Glob()\n    {\n        stopThread();\n    }\n\n    void BA_Glob::startThread()\n    {\n        thread_ = new boost::thread(&BA_Glob::updateLoop, this);\n    }\n\n    void BA_Glob::stopThread()\n    {\n\n        if(thread_ != NULL)\n        {\n            thread_->interrupt();\n            usleep(5000);\n            thread_->join();\n            thread_ = NULL;\n        }\n#if VIO_DEBUG\n        fclose(log_);\n#endif\n    }\n    void BA_Glob::updateLoop()\n    {\n        while(!boost::this_thread::interruption_requested())\n        {\n            boost::unique_lock< boost::mutex > lk( mtx_);\n            while(map_.keyframes_.empty() || new_keyframe_ == false)\n                cond_.wait(lk);\n#if VIO_DEBUG\n            fprintf(log_,\"[%s] BA loop run \\n\",\n                    vio::time_in_HH_MM_SS_MMM().c_str());\n#endif\n            new_keyframe_=false;\n            // init g2o\n            g2o::OptimizableGraph::VertexContainer points;\n            ba_mux_.lock();\n            // Go through all Keyframes\n            v_id_ = 0;\n            auto end=map_.keyframes_.end();\n            auto end_1=end--;\n            for(auto it_kf=map_.keyframes_.begin();it_kf!=map_.keyframes_.end();++it_kf)\n            {\n                // New Keyframe Vertex\n                if(it_kf !=map_.keyframes_.end() && it_kf !=end && it_kf !=end_1){\n                    (*it_kf)->v_kf_ = createG2oFrameSE3(*it_kf,true);\n                }else{\n                    (*it_kf)->v_kf_ = createG2oFrameSE3(*it_kf,false);\n                }\n                optimizer_->addVertex((*it_kf)->v_kf_);\n                for(auto& it_ftr:(*it_kf)->fts_)\n                {\n                    if(it_ftr->point==NULL)continue;\n                    if(it_ftr->point->type_ != vio::Point::TYPE_GOOD)continue;\n                    // for each keyframe add edges to all observed mapoints\n                    if(it_ftr->point->pos_.hasNaN())continue;\n                    if(it_ftr->point->pos_.norm()==0.)continue;\n                    if(it_ftr->point->v_pt_ == NULL)\n                    {\n                        // mappoint-vertex doesn't exist yet. create a new one:\n                        it_ftr->point->v_pt_ = createG2oPoint(it_ftr->point->pos_);\n                        optimizer_->addVertex(it_ftr->point->v_pt_);\n                    }\n                    optimizer_->addEdge(createG2oEdgeSE3((*it_kf)->v_kf_, it_ftr->point->v_pt_, vk::project2d(it_ftr->f),\n                                                                         true,\n                                                                         Config::poseOptimThresh()/(*it_kf)->cam_->errorMultiplier2()*Config::lobaRobustHuberWidth()));\n                }\n            }\n            for (g2o::OptimizableGraph::VertexIDMap::const_iterator it = optimizer_->vertices().begin();\n                 it != optimizer_->vertices().end(); ++it) {\n                auto v = std::static_pointer_cast<g2o::OptimizableGraph::Vertex>(it->second);\n                if (v->dimension() == 3 && v->edges().size()>2) points.push_back(v);\n            }\n            // Optimization\n            if(points.empty()){\n                optimizer_->clear();\n                ba_mux_.unlock();\n                continue;\n            }\n            optimizer_->initializeOptimization();\n            optimizer_->computeActiveErrors();\n            g2o::StructureOnlySolver<3> structure_only_ba;\n            structure_only_ba.calc(points, vio::Config::lobaNumIter());\n\n#if VIO_DEBUG\n            fprintf(log_,\"[%s] init error: %f \\n\",\n                    vio::time_in_HH_MM_SS_MMM().c_str(),optimizer_->activeChi2());\n#endif\n            if(optimizer_->optimize(vio::Config::lobaNumIter())<1){\n                optimizer_->clear();\n                ba_mux_.unlock();\n                continue;\n            }\n#if VIO_DEBUG\n            fprintf(log_,\"[%s] end error: %f \\n\",\n                    vio::time_in_HH_MM_SS_MMM().c_str(),optimizer_->activeChi2());\n#endif\n            // Update Keyframe and MapPoint Positions\n            for(list<FramePtr>::iterator it_kf = map_.keyframes_.begin();\n                it_kf != map_.keyframes_.end();++it_kf)\n            {\n                (*it_kf)->T_f_w_ = SE2_5(SE3((*it_kf)->v_kf_->estimate().rotation().toRotationMatrix(),\n                                        (*it_kf)->v_kf_->estimate().translation()));\n                for(Features::iterator it_ftr=(*it_kf)->fts_.begin(); it_ftr!=(*it_kf)->fts_.end(); ++it_ftr)\n                {\n                    if((*it_ftr)->point == NULL)\n                        continue;\n                    if((*it_ftr)->point->v_pt_ == NULL)\n                        continue;       // mp was updated before\n                    (*it_ftr)->point->pos_ = (*it_ftr)->point->v_pt_->estimate();\n                    (*it_ftr)->point->v_pt_.reset();\n                }\n            }\n            optimizer_->clear();\n            ba_mux_.unlock();\n        }\n    }\n\n   std::shared_ptr<g2o::VertexSE3Expmap>\n   BA_Glob::createG2oFrameSE3(FramePtr frame, bool state)\n   {\n       std::shared_ptr<g2o::VertexSE3Expmap> v= std::make_shared<g2o::VertexSE3Expmap>();\n       ++v_id_;\n       v->setId(v_id_);\n       // not all frames are fixed\n       v->setFixed(state);\n       v->setEstimate(g2o::SE3Quat(frame->se3().unit_quaternion(), frame->se3().translation()));\n       return v;\n   }\n\n   std::shared_ptr<g2o::VertexPointXYZ>\n   BA_Glob::createG2oPoint(Vector3d pos)\n   {\n       ++v_id_;\n       std::shared_ptr<g2o::VertexPointXYZ> v =std::make_shared<g2o::VertexPointXYZ>();\n       v->setId(v_id_);\n       //v->setFixed(false);\n       v->setMarginalized(true);\n       v->setEstimate(pos);\n       return v;\n\n   }\n\n    std::shared_ptr<g2o::EdgeProjectXYZ2UV> BA_Glob::createG2oEdgeSE3(\n            std::shared_ptr<g2o::VertexSE3Expmap> v_frame,\n            std::shared_ptr<g2o::VertexPointXYZ> v_point,\n                     const Vector2d& f_up,\n                     bool robust_kernel,\n                     double huber_width,\n                     double weight)\n   {\n       std::shared_ptr<g2o::EdgeProjectXYZ2UV> e= std::make_shared<g2o::EdgeProjectXYZ2UV>();\n       e->vertices()[0]=v_point;\n       e->vertices()[1]=v_frame;\n       e->setMeasurement(f_up);\n       e->information() = weight*Eigen::Matrix2d::Identity();\n       g2o::RobustKernelHuber* rk = new g2o::RobustKernelHuber;\n       rk->setDelta(huber_width);\n       e->setRobustKernel(rk);\n       e->setParameterId(0, 0); //old: e->setId(v_point->id());\n       return e;\n   }\n   void BA_Glob::reset_map(){\n        for(auto&& f:map_.keyframes_){\n            f->v_kf_.reset();\n            for(auto p:f->fts_)\n                if(p->point!=NULL)\n                    p->point->v_pt_.reset();\n        }\n    }\n\n} // namespace vio\n", "meta": {"hexsha": "b41ebd2f882ccd0efab4b259070a293993c05f4f", "size": 9134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GPU_version/vio/src/global_optimizer.cpp", "max_stars_repo_name": "Pilot-Labs-Dev/vio_svo", "max_stars_repo_head_hexsha": "8274e4269b383e9816fca5c3102b51cd4d1b95ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T01:12:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:17:24.000Z", "max_issues_repo_path": "GPU_version/vio/src/global_optimizer.cpp", "max_issues_repo_name": "Pilot-Labs-Dev/vio_svo", "max_issues_repo_head_hexsha": "8274e4269b383e9816fca5c3102b51cd4d1b95ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GPU_version/vio/src/global_optimizer.cpp", "max_forks_repo_name": "Pilot-Labs-Dev/vio_svo", "max_forks_repo_head_hexsha": "8274e4269b383e9816fca5c3102b51cd4d1b95ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-12T11:42:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T11:42:01.000Z", "avg_line_length": 39.5411255411, "max_line_length": 167, "alphanum_fraction": 0.558681848, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.1865588528125158}}
{"text": "/*********************************************************************\n *\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2015, Daichi Yoshikawa\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 Daichi Yoshikawa 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 * Author: Daichi Yoshikawa\n *\n *********************************************************************/\n\n#include <mutex>\n#include <Eigen/Dense>\n#include <ros/ros.h>\n#include <ahl_gazebo_interface/gazebo_interface.hpp>\n#include <ahl_gazebo_interface/exception.hpp>\n#include <ahl_robot/ahl_robot.hpp>\n#include <ahl_utils/exception.hpp>\n#include <ahl_utils/scoped_lock.hpp>\n#include <ahl_robot_controller/robot_controller.hpp>\n#include <ahl_robot_controller/tasks.hpp>\n\nusing namespace ahl_robot;\nusing namespace ahl_ctrl;\n\nstd::mutex mutex;\nRobotPtr robot;\nRobotControllerPtr controller;\nbool updated = false;\nTfPublisherPtr tf_pub;\nTaskPtr gravity_compensation;\nTaskPtr damping;\nTaskPtr joint_control;\nTaskPtr joint_limit;\nTaskPtr position_control;\nTaskPtr orientation_control;\nahl_gazebo_if::GazeboInterfacePtr gazebo_interface;\nbool initialized = false;\nbool joint_updated = false;\n\nvoid updateModel(const ros::TimerEvent&)\n{\n  try\n  {\n    ahl_utils::ScopedLock lock(mutex);\n    if(joint_updated)\n    {\n      robot->computeJacobian(\"mnp\");\n      robot->computeMassMatrix(\"mnp\");\n      controller->updateModel();\n      updated = true;\n      tf_pub->publish(robot);\n    }\n  }\n  catch(ahl_utils::Exception& e)\n  {\n    ROS_ERROR_STREAM(e.what());\n  }\n  catch(ahl_gazebo_if::Exception& e)\n  {\n    ROS_ERROR_STREAM(e.what());\n  }\n}\n\nvoid control(const ros::TimerEvent&)\n{\n  try\n  {\n    ahl_utils::ScopedLock lock(mutex);\n\n    if(gazebo_interface->subscribed())\n    {\n      Eigen::VectorXd q = gazebo_interface->getJointStates();\n      robot->update(q);\n      joint_updated = true;\n    }\n\n    if(updated)\n    {\n      static long cnt = 0;\n\n      if(initialized == false)\n      {\n        Eigen::VectorXd qd = Eigen::VectorXd::Constant(robot->getDOF(\"mnp\"), M_PI / 4.0);\n        double sin_val = 1.0;//std::abs(sin(2.0 * M_PI * 0.1 * cnt * 0.001));\n        qd = sin_val * qd;\n        joint_control->setGoal(qd);\n\n        static int32_t reached = 0;\n        if(robot->reached(\"mnp\", qd, 2.2))\n        {\n          ++reached;\n\n          if(reached > 500)\n          {\n            std::cout << \"switch to task space control.\" << std::endl;\n\n            initialized = true;\n            controller->clearTask();\n            controller->addTask(joint_control, 0);\n            controller->addTask(gravity_compensation, 10);\n            controller->addTask(position_control, 10);\n            controller->addTask(orientation_control, 5);\n            //controller->addTask(joint_limit, 100);\n\n            joint_control->setGoal(qd);\n\n            Eigen::Vector3d xd;\n            xd << 0.8, 0.35, 1.0;\n            position_control->setGoal(xd);\n\n            Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n            double rad = 0.0;\n            R << cos(rad), 0, sin(rad),\n              0, 1, 0,\n              -sin(rad), 0, cos(rad);\n            orientation_control->setGoal(R);\n          }\n        }\n        else\n        {\n          reached = 0;\n        }\n      }\n      else\n      {\n        Eigen::Vector3d xd;\n        xd << 0.8, 0.35, 1.0;\n        xd.coeffRef(0) += 0.2 * cos(2.0 * M_PI * 0.2 * cnt * 0.001);\n        xd.coeffRef(1) += 0.2 * sin(2.0 * M_PI * 0.2 * cnt * 0.001);\n        //xd.coeffRef(2) += 0.2 * cos(2.0 * M_PI * 0.2 * cnt * 0.001);\n\n        Eigen::VectorXd qd = Eigen::VectorXd::Constant(robot->getDOF(\"mnp\"), M_PI / 4.0);\n        qd[3] = -qd[3];\n        qd[7] = -qd[7];\n        joint_control->setGoal(qd);\n\n        position_control->setGoal(xd);\n        Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n        double rad = 0.0; //M_PI / 4.0 * sin(2.0 * M_PI * 0.2 * cnt * 0.001) + M_PI / 4;\n        R << cos(rad), 0, sin(rad),\n          0, 1, 0,\n          -sin(rad), 0, cos(rad);\n        orientation_control->setGoal(R);\n      }\n\n      ++cnt;\n\n      Eigen::VectorXd tau(robot->getDOF(\"mnp\"));\n      controller->computeGeneralizedForce(tau);\n\n      gazebo_interface->applyJointEfforts(tau);\n    }\n\n  }\n  catch(ahl_utils::Exception& e)\n  {\n    ROS_ERROR_STREAM(e.what());\n  }\n  catch(ahl_gazebo_if::Exception& e)\n  {\n    ROS_ERROR_STREAM(e.what());\n  }\n}\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"red_arm_server\");\n  ros::NodeHandle nh;\n\n  ros::Timer timer_update_model = nh.createTimer(ros::Duration(0.01), updateModel);\n  ros::Timer timer_control = nh.createTimer(ros::Duration(0.001), control);\n\n  robot = std::make_shared<Robot>(\"red_arm2\");\n  ParserPtr parser = std::make_shared<Parser>();\n\n  std::string path = \"/home/daichi/Work/catkin_ws/src/ahl_ros_pkg/ahl_robot/ahl_robot/yaml/red_arm2.yaml\";\n  parser->load(path, robot);\n\n  controller = std::make_shared<RobotController>();\n  controller->init(robot);\n\n  using namespace ahl_gazebo_if;\n  gazebo_interface = std::make_shared<GazeboInterface>();\n  gazebo_interface->addJoint(\"red_arm2::joint1\");\n  gazebo_interface->addJoint(\"red_arm2::joint2\");\n  gazebo_interface->addJoint(\"red_arm2::joint3\");\n  gazebo_interface->addJoint(\"red_arm2::joint4\");\n  gazebo_interface->addJoint(\"red_arm2::joint5\");\n  gazebo_interface->addJoint(\"red_arm2::joint6\");\n  gazebo_interface->addJoint(\"red_arm2::joint7\");\n  gazebo_interface->addJoint(\"red_arm2::joint8\");\n  gazebo_interface->addJoint(\"red_arm2::joint9\");\n  gazebo_interface->addJoint(\"red_arm2::joint10\");\n  gazebo_interface->addJoint(\"red_arm2::joint11\");\n  gazebo_interface->connect();\n\n  tf_pub = std::make_shared<TfPublisher>();\n\n  ManipulatorPtr mnp = robot->getManipulator(\"mnp\");\n\n  gravity_compensation = std::make_shared<GravityCompensation>(robot);\n  damping = std::make_shared<Damping>(robot);\n  joint_control = std::make_shared<JointControl>(mnp);\n  joint_limit = std::make_shared<JointLimit>(mnp, 0.087);\n  position_control = std::make_shared<PositionControl>(mnp, \"gripper\", 0.001);\n  orientation_control = std::make_shared<OrientationControl>(mnp, \"gripper\", 0.001);\n\n  controller->addTask(gravity_compensation, 0);\n  controller->addTask(joint_control, 0);\n\n  ros::MultiThreadedSpinner spinner;\n  spinner.spin();\n\n  return 0;\n}\n", "meta": {"hexsha": "411eb6eaa02892152039d8a18ec574de35465da5", "size": 7696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/ahl_lwr_server/test/test3.cpp", "max_stars_repo_name": "daichi-yoshikawa/ahl_wbc", "max_stars_repo_head_hexsha": "ea241562e521c7509d3b0405393996998f7cdc6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-12-16T15:32:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T05:09:40.000Z", "max_issues_repo_path": "samples/ahl_lwr_server/test/test3.cpp", "max_issues_repo_name": "daichi-yoshikawa/ahl_wbc", "max_issues_repo_head_hexsha": "ea241562e521c7509d3b0405393996998f7cdc6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-06-08T09:53:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T11:27:23.000Z", "max_forks_repo_path": "samples/ahl_lwr_server/test/test3.cpp", "max_forks_repo_name": "daichi-yoshikawa/ahl_wbc", "max_forks_repo_head_hexsha": "ea241562e521c7509d3b0405393996998f7cdc6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T10:30:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T05:08:27.000Z", "avg_line_length": 31.5409836066, "max_line_length": 106, "alphanum_fraction": 0.6482588358, "num_tokens": 2038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.18649440616416807}}
{"text": "/*\n * Copyright (C) 2019 Intel Corporation\n *\n * SPDX-License-Identifier: MIT\n *\n */\n\n#include \"vme_wpp/vme_wpp.hpp\"\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <vector>\n\n#include <boost/program_options.hpp>\n\n#include <boost/compute/core.hpp>\n#include <boost/compute/image.hpp>\n#include <boost/compute/utility.hpp>\n\n#include <CL/cl_ext_intel.h>\n\n#include \"align_utils/align_utils.hpp\"\n#include \"timer/timer.hpp\"\n#include \"ocl_utils/ocl_utils.hpp\"\n#include \"logging/logging.hpp\"\n\nnamespace au = compute_samples::align_utils;\nnamespace po = boost::program_options;\nnamespace compute = boost::compute;\n\nnamespace compute_samples {\n\nVmeWppApplication::Arguments VmeWppApplication::parse_command_line(\n    const std::vector<std::string> &command_line) {\n  Arguments args;\n\n  po::options_description desc(\"Allowed options\");\n  auto options = desc.add_options();\n  options(\"help,h\", \"show help message\");\n  options(\"output-bmp,b\",\n          po::value<bool>(&args.output_bmp)\n              ->default_value(false)\n              ->implicit_value(true),\n          \"output to bmp images for each frame\");\n  options(\"input-yuv,i\",\n          po::value<std::string>(&args.input_yuv_path)\n              ->default_value(\"goal_1280x720.yuv\"),\n          \"path to input yuv file\");\n  options(\"output-yuv,o\",\n          po::value<std::string>(&args.output_yuv_path)\n              ->default_value(\"output_goal_1280x720.yuv\"),\n          \"path to output yuv with motion vectors\");\n  options(\"qp,q\", po::value<int>(&args.qp)->default_value(49),\n          \"quantization parameter value to use for estimation heuristics\"\n          \"(higher for faster motion frames)\");\n  options(\"width,w\", po::value<int>(&args.width)->default_value(1280),\n          \"width of input yuv\");\n  options(\"height,h\", po::value<int>(&args.height)->default_value(720),\n          \"height of input yuv\");\n  options(\"frames,f\", po::value<int>(&args.frames)->default_value(0),\n          \"number of frame to use for motion estimation (0 represents entire \"\n          \"yuv sequence)\");\n\n  po::positional_options_description p;\n  p.add(\"input-yuv\", 1);\n  p.add(\"output-yuv\", 1);\n\n  po::variables_map vm;\n  po::store(\n      po::command_line_parser(command_line).options(desc).positional(p).run(),\n      vm);\n\n  if (vm.count(\"help\") != 0u) {\n    std::cout << desc;\n    args.help = true;\n    return args;\n  }\n\n  po::notify(vm);\n\n  if (args.qp > 51) {\n    throw std::invalid_argument(\"Invalid argument for qp. Valid range (0-51).\");\n  }\n\n  return args;\n}\n\n#define MV_PER_DIM (2)\n#define DIM_TO_MB_SZ(X, Y) (au::align_units(au::align_units(X, Y), 16))\n#define DIM_TO_MV_SZ(X, Y) (DIM_TO_MB_SZ(X, Y) * MV_PER_DIM)\n\nApplication::Status\nVmeWppApplication::run_implementation(std::vector<std::string> &command_line) {\n  const Arguments args = parse_command_line(command_line);\n  if (args.help) {\n    return Status::SKIP;\n  }\n\n  compute::device device = compute::system::default_device();\n  LOG_INFO << \"OpenCL device: \" << device.name();\n\n  if (!device.supports_extension(\n          \"cl_intel_device_side_avc_motion_estimation\")) {\n    LOG_ERROR\n        << \"The selected device doesn't support device-side motion estimation.\";\n    return Status::SKIP;\n  }\n\n  if (!device.check_version(2, 0)) {\n    LOG_ERROR << \"The selected device doesn't support OpenCL 2.0.\";\n    return Status::SKIP;\n  }\n\n  LOG_INFO << \"Input yuv path: \" << args.input_yuv_path;\n  LOG_INFO << \"Frame size: \" << args.width << \"x\" << args.height << \" pixels\";\n\n  Timer timer_total;\n\n  compute::context context(device);\n  compute::command_queue queue(context, device);\n\n  Timer timer;\n  compute::program program =\n      build_program(context, \"vme_wpp.cl\", \"-cl-std=CL2.0\");\n  timer.print(\"Program created\");\n\n  compute::kernel ds_kernel = program.create_kernel(\"downsample_3_tier\");\n  compute::kernel hme_n_kernel = program.create_kernel(\"tier_n_hme\");\n  compute::kernel wpp_kernel = program.create_kernel(\"vme_wpp\");\n  timer.print(\"Kernels created\");\n\n  YuvCapture capture(args.input_yuv_path, args.width, args.height, args.frames);\n  const int frame_count =\n      (args.frames) != 0 ? args.frames : capture.get_num_frames();\n  YuvWriter writer(args.width, args.height, frame_count, args.output_bmp);\n\n  PlanarImage planar_image(args.width, args.height);\n  capture.get_sample(0, planar_image);\n  timer.print(\"Read YUV frame 0 from disk to CPU linear memory.\");\n\n  writer.append_frame(planar_image);\n\n  compute::image_format format(CL_R, CL_UNORM_INT8);\n  compute::image2d ref_image(context, args.width, args.height, format);\n  compute::image2d src_image(context, args.width, args.height, format);\n  compute::image2d src_image_8x(context, au::align_units(args.width, 8),\n                                au::align_units(args.height, 8), format);\n  compute::image2d ref_image_8x(context, au::align_units(args.width, 8),\n                                au::align_units(args.height, 8), format);\n  compute::image2d src_image_4x(context, au::align_units(args.width, 4),\n                                au::align_units(args.height, 4), format);\n  compute::image2d ref_image_4x(context, au::align_units(args.width, 4),\n                                au::align_units(args.height, 4), format);\n  compute::image2d src_image_2x(context, au::align_units(args.width, 2),\n                                au::align_units(args.height, 2), format);\n  compute::image2d ref_image_2x(context, au::align_units(args.width, 2),\n                                au::align_units(args.height, 2), format);\n  timer.print(\"Created opencl mem objects for downsample_3_tier kernel\");\n\n  size_t origin[] = {0, 0, 0};\n  size_t region[] = {static_cast<size_t>(args.width),\n                     static_cast<size_t>(args.height), 1};\n  queue.enqueue_write_image(src_image, origin, region, planar_image.get_y(),\n                            planar_image.get_pitch_y());\n  timer.print(\"Copied frame 0 to tiled memory.\");\n\n  ds_kernel.set_args(src_image, src_image_2x, src_image_4x, src_image_8x);\n  queue.enqueue_nd_range_kernel(\n      ds_kernel, 2, nullptr,\n      compute::dim(au::align16(au::align_units(args.width, 4)),\n                   au::align_units(args.height, 16))\n          .data(),\n      compute::dim(16, 1).data());\n  timer.print(\"Enqueued downsample_3_tier kernel for frame 0\");\n\n  for (int k = 1; k < frame_count; k++) {\n    LOG_INFO << \"Processing frame \" << k << \"...\";\n    run_vme_wpp(args, device, context, queue, ds_kernel, hme_n_kernel,\n                wpp_kernel, capture, planar_image, src_image, ref_image,\n                src_image_2x, ref_image_2x, src_image_4x, ref_image_4x,\n                src_image_8x, ref_image_8x, k);\n    writer.append_frame(planar_image);\n  }\n\n  LOG_INFO << \"Wrote \" << frame_count << \" frames with overlaid \"\n           << \"motion vectors to \" << args.output_yuv_path << \" .\";\n  writer.write_to_file(args.output_yuv_path.c_str());\n\n  timer_total.print(\"Total\");\n  return Status::OK;\n}\n\nvoid VmeWppApplication::run_vme_wpp(\n    const VmeWppApplication::Arguments &args, compute::device &device,\n    compute::context &context, compute::command_queue &queue,\n    compute::kernel &ds_kernel, compute::kernel &hme_n_kernel,\n    compute::kernel &wpp_kernel, YuvCapture &capture, PlanarImage &planar_image,\n    compute::image2d &src_image, compute::image2d &ref_image,\n    compute::image2d &src_2x_image, compute::image2d &ref_2x_image,\n    compute::image2d &src_4x_image, compute::image2d &ref_4x_image,\n    compute::image2d &src_8x_image, compute::image2d &ref_8x_image,\n    int frame_idx) const {\n  Timer timer;\n\n  int width = args.width;\n  int height = args.height;\n\n  std::swap(ref_image, src_image);\n  std::swap(ref_2x_image, src_2x_image);\n  std::swap(ref_4x_image, src_4x_image);\n  std::swap(ref_8x_image, src_8x_image);\n\n  capture.get_sample(frame_idx, planar_image);\n  timer.print(\"Read next YUV frame from disk to CPU linear memory.\");\n\n  size_t origin[] = {0, 0, 0};\n  size_t region[] = {static_cast<size_t>(width), static_cast<size_t>(height),\n                     1};\n  queue.enqueue_write_image(src_image, origin, region, planar_image.get_y(),\n                            planar_image.get_pitch_y());\n  timer.print(\"Copied next frame to GPU tiled memory.\");\n\n  ds_kernel.set_args(src_image, src_2x_image, src_4x_image, src_8x_image);\n  queue.enqueue_nd_range_kernel(\n      ds_kernel, 2, nullptr,\n      compute::dim(au::align16(au::align_units(width, 4)),\n                   au::align_units(height, 16))\n          .data(),\n      compute::dim(16, 1).data());\n  timer.print(\"Enqueued downsample_3_tier kernel for next frame\");\n\n  uint32_t mv_8x_count = DIM_TO_MV_SZ(width, 8) * DIM_TO_MV_SZ(height, 8);\n  au::PageAlignedVector<cl_short2> predictors_4x(au::align64(mv_8x_count));\n  uint32_t mv_4x_count = DIM_TO_MV_SZ(width, 4) * DIM_TO_MV_SZ(height, 4);\n  au::PageAlignedVector<cl_short2> predictors_2x(au::align64(mv_4x_count));\n  uint32_t mv_2x_count = DIM_TO_MV_SZ(width, 2) * DIM_TO_MV_SZ(height, 2);\n  au::PageAlignedVector<cl_short2> predictors(au::align64(mv_2x_count));\n\n  compute::buffer pred_4x_buffer(\n      context, au::align64(mv_8x_count * sizeof(cl_short2)),\n      CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, predictors_4x.data());\n  compute::buffer pred_2x_buffer(\n      context, au::align64(mv_4x_count * sizeof(cl_short2)),\n      CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, predictors_2x.data());\n  compute::buffer pred_buffer(\n      context, au::align64(mv_2x_count * sizeof(cl_short2)),\n      CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, predictors.data());\n  timer.print(\"Created opencl mem objects for tier_n_hme kernel\");\n\n  hme_n_kernel.set_arg(0, src_8x_image);\n  hme_n_kernel.set_arg(1, ref_8x_image);\n  hme_n_kernel.set_arg(2, sizeof(cl_mem), nullptr);\n  hme_n_kernel.set_arg(3, pred_4x_buffer);\n  queue.enqueue_nd_range_kernel(\n      hme_n_kernel, 2, nullptr,\n      compute::dim(au::align16(au::align_units(width, 8)),\n                   DIM_TO_MB_SZ(height, 8))\n          .data(),\n      compute::dim(16, 1).data());\n  timer.print(\"Enqueued tier 3 hme kernel for next frame\");\n\n  hme_n_kernel.set_args(src_4x_image, ref_4x_image, pred_4x_buffer,\n                        pred_2x_buffer);\n  queue.enqueue_nd_range_kernel(\n      hme_n_kernel, 2, nullptr,\n      compute::dim(au::align16(au::align_units(width, 4)),\n                   DIM_TO_MB_SZ(height, 4))\n          .data(),\n      compute::dim(16, 1).data());\n  timer.print(\"Enqueued tier 2 hme kernel for next frame\");\n\n  hme_n_kernel.set_args(src_2x_image, ref_2x_image, pred_2x_buffer,\n                        pred_buffer);\n  queue.enqueue_nd_range_kernel(\n      hme_n_kernel, 2, nullptr,\n      compute::dim(au::align16(au::align_units(width, 2)),\n                   DIM_TO_MB_SZ(height, 2))\n          .data(),\n      compute::dim(16, 1).data());\n  timer.print(\"Enqueued tier 1 hme kernel for next frame\");\n\n  int mb_image_width = au::align_units(width, 16);\n  int mb_image_height = au::align_units(height, 16);\n  int mb_count = mb_image_width * mb_image_height;\n  int mv_image_width = mb_image_width * 4;\n  int mv_image_height = mb_image_height * 4;\n  int mv_count = mv_image_width * mv_image_height;\n\n  uint32_t num_eu = device.compute_units();\n  uint32_t num_threads_per_eu = 7;\n  uint32_t max_threads = num_eu * num_threads_per_eu;\n  uint32_t width_mb_sz = au::align_units(width, 16);\n  uint32_t num_blocks = (width_mb_sz < max_threads) ? width_mb_sz : max_threads;\n  uint32_t simd_size = 16;\n\n  au::PageAlignedVector<cl_short2> mvs(au::align64(mv_count));\n  au::PageAlignedVector<cl_ushort> residuals(au::align64(mv_count));\n  au::PageAlignedVector<cl_uchar2> shapes(au::align64(mb_count));\n  au::PageAlignedVector<cl_int> scoreboard(au::align64(width_mb_sz), 0);\n\n  compute::buffer scoreboard_buffer(\n      context, au::align64(width_mb_sz * sizeof(uint32_t)),\n      CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, scoreboard.data());\n  compute::buffer mv_buffer(context, au::align64(mv_count * sizeof(cl_short2)),\n                            CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,\n                            mvs.data());\n  compute::buffer residual_buffer(\n      context, au::align64(mv_count * sizeof(cl_ushort)),\n      CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, residuals.data());\n  compute::buffer shape_buffer(\n      context, au::align64(mb_count * sizeof(cl_uchar2)),\n      CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, shapes.data());\n  timer.print(\"Created opencl mem objects for tier 0 wpp kernel\");\n\n  auto qp = static_cast<cl_uchar>(args.qp);\n  cl_uchar sad_adjustment = CL_AVC_ME_SAD_ADJUST_MODE_NONE_INTEL;\n  cl_uchar pixel_mode = CL_AVC_ME_SUBPIXEL_MODE_QPEL_INTEL;\n  wpp_kernel.set_args(src_image, ref_image, pred_buffer, mv_buffer,\n                      residual_buffer, shape_buffer, scoreboard_buffer, qp,\n                      sad_adjustment, pixel_mode);\n  size_t local_size = 16;\n  size_t global_size = num_blocks * simd_size;\n  queue.enqueue_nd_range_kernel(wpp_kernel, 1, nullptr, &global_size,\n                                &local_size);\n  timer.print(\"Enquequed tier 0 vme_wpp kernel\");\n\n  queue.finish();\n  timer.print(\"Kernel finished.\");\n\n  planar_image.overlay_vectors(reinterpret_cast<motion_vector *>(mvs.data()),\n                               reinterpret_cast<inter_shape *>(shapes.data()));\n}\n} // namespace compute_samples\n", "meta": {"hexsha": "74a12b6480e525c900d68deef1e51719054fc426", "size": 13309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compute_samples/applications/vme_wpp/src/vme_wpp.cpp", "max_stars_repo_name": "maximd33/compute-samples", "max_stars_repo_head_hexsha": "b16a666b76b43c2a7bd1671edc563b45e978f1a7", "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": "compute_samples/applications/vme_wpp/src/vme_wpp.cpp", "max_issues_repo_name": "maximd33/compute-samples", "max_issues_repo_head_hexsha": "b16a666b76b43c2a7bd1671edc563b45e978f1a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-24T01:18:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T01:18:27.000Z", "max_forks_repo_path": "compute_samples/applications/vme_wpp/src/vme_wpp.cpp", "max_forks_repo_name": "maximd33/compute-samples", "max_forks_repo_head_hexsha": "b16a666b76b43c2a7bd1671edc563b45e978f1a7", "max_forks_repo_licenses": ["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.4925816024, "max_line_length": 80, "alphanum_fraction": 0.6810429033, "num_tokens": 3571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.18621982248099755}}
{"text": "#ifndef AUTONOMY_SCRIPT_COMMANDS_HPP\n#define AUTONOMY_SCRIPT_COMMANDS_HPP\n#include <boost/random.hpp>\n\n#include <autonomy/script_instruction.hpp>\n#include <autonomy/entity/scripted_drone.hpp>\n\nnamespace autonomy {\n    //! \\brief Move command.\n    //! Takes 2 \"directions\", up and right.\n    //! A direction is either positive, 0 or negative\n    struct move : public script_instruction_base<move>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"move\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<move>);\n            }\n    };\n\n    struct get_x : public script_instruction_base<get_x>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"get_x\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<get_x>);\n            }\n    };\n\n    struct get_y : public script_instruction_base<get_y>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"get_y\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<get_y>);\n            }\n    };\n\n    //! \\brief scan command\n    //! Takes an x and a y and returns an \"object type\"\n    struct scan : public script_instruction_base<scan>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"scan\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<scan>);\n            }\n    };\n\n    struct is_drone : public script_instruction_base<is_drone>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"is_drone\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<is_drone>);\n            }\n    };\n\n    struct is_asteroid : public script_instruction_base<is_asteroid>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"is_asteroid\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<is_asteroid>);\n            }\n    };\n\n    struct is_base : public script_instruction_base<is_base>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"is_base\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone );\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<is_base>);\n            }\n    };\n\n    //! \\brief Random direction command\n    //! Returns a random \"direction\" which is either -1, 0, or 1\n    struct rand_dir : public script_instruction_base<rand_dir>\n    {\n        friend class boost::serialization::access;\n        rand_dir()\n        {}\n        static std::string name() { return \"rand_dir\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        static boost::mt19937 rng;\n        static boost::uniform_int<> dir;\n        static boost::variate_generator<boost::mt19937&, boost::uniform_int<> > _rand_dir;\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<rand_dir>);\n            }\n    };\n\n    //! \\brief Mine command\n    //! Takes an x, and a y and mines an asteroid some set amount if there is one there\n    struct mine : public script_instruction_base<mine>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"mine\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<mine>);\n            }\n    };\n    \n    //! \\brief Unload command\n    //! Takes an x, and a y and unloads some set amount to a basestation\n    struct unload : public script_instruction_base<unload>\n    {\n        friend class boost::serialization::access;\n        static std::string name() { return \"unload\"; }\n        unsigned int execute(size_t which_queue, entity::scripted_drone & drone);\n        private:\n        template<class Archive>\n            void serialize(Archive & ar, const unsigned int version)\n            {\n                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<unload>);\n            }\n    };\n}\n#endif\n", "meta": {"hexsha": "4dddccd6861c9ebff6d530023c4981974fbe7aed", "size": 5947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autonomy/script_commands.hpp", "max_stars_repo_name": "medlefsen/autonomy", "max_stars_repo_head_hexsha": "ed9da86e9be98dd2505a7f02af9cd4db995e6baf", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-31T20:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T16:11:14.000Z", "max_issues_repo_path": "src/autonomy/script_commands.hpp", "max_issues_repo_name": "medlefsen/autonomy", "max_issues_repo_head_hexsha": "ed9da86e9be98dd2505a7f02af9cd4db995e6baf", "max_issues_repo_licenses": ["Artistic-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/autonomy/script_commands.hpp", "max_forks_repo_name": "medlefsen/autonomy", "max_forks_repo_head_hexsha": "ed9da86e9be98dd2505a7f02af9cd4db995e6baf", "max_forks_repo_licenses": ["Artistic-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.1217948718, "max_line_length": 95, "alphanum_fraction": 0.6330923155, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18621981890568792}}
{"text": "#pragma once\n\n#include <protozero/pbf_writer.hpp>\n#include <protozero/varint.hpp>\n\n#include <boost/geometry.hpp>\n\n#include \"web_mercator.hpp\"\n#include \"vector_tile.hpp\"\n#include \"common.hpp\"\n\nnamespace util { namespace tile {\n\ntypedef boost::geometry::model::point<std::int32_t, 2, boost::geometry::cs::cartesian> tile_point_t;\ntypedef boost::geometry::model::linestring<tile_point_t> tile_linestring_t;\ntypedef boost::geometry::model::box<tile_point_t> tile_box_t;\n\ntypedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> mercator_point_t;\ntypedef boost::geometry::model::linestring<mercator_point_t> mercator_linestring_t;\ntypedef boost::geometry::model::box<mercator_point_t> mercator_box_t;\ntypedef boost::geometry::model::multi_linestring<mercator_linestring_t> mercator_multi_linestring_t;\n\nconst static tile_box_t tile_clip_box(tile_point_t(-util::vector_tile::BUFFER, -util::vector_tile::BUFFER),\n                                      tile_point_t(util::vector_tile::EXTENT + util::vector_tile::BUFFER,\n                                                   util::vector_tile::EXTENT + util::vector_tile::BUFFER));\n\nstruct tile_point_hash {\n    std::size_t operator()(const tile_point_t &key) const {\n        const auto a = std::hash<std::int32_t>()(key.get<0>());\n        const auto b = std::hash<std::int32_t>()(key.get<1>());\n        // From boost::hash_combine\n        return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));\n    }\n};\n\nstruct tile_point_equal {\n    bool operator()(const tile_point_t &a, const tile_point_t &b) const {\n        return a.get<0>() == b.get<0>() && a.get<1>() == b.get<1>();\n    }\n};\n\n\n\n// from mapnik-vector-tile\n// Encodes a linestring using protobuf zigzag encoding\ninline bool encodeLinestring(const tile_linestring_t  &line,\n                             protozero::packed_field_uint32 &geometry,\n                             std::int32_t &start_x,\n                             std::int32_t &start_y)\n{\n    const std::size_t line_size = line.size();\n    if (line_size < 2)\n    {\n        return false;\n    }\n\n    const unsigned LINETO_count = static_cast<const unsigned>(line_size) - 1;\n\n    auto pt = line.begin();\n    const constexpr int MOVETO_COMMAND = 9;\n    geometry.add_element(MOVETO_COMMAND); // move_to | (1 << 3)\n    geometry.add_element(protozero::encode_zigzag32(pt->get<0>() - start_x));\n    geometry.add_element(protozero::encode_zigzag32(pt->get<1>() - start_y));\n    start_x = pt->get<0>();\n    start_y = pt->get<1>();\n    // This means LINETO repeated N times\n    // See: https://github.com/mapbox/vector-tile-spec/tree/master/2.1#example-command-integers\n    geometry.add_element((LINETO_count << 3u) | 2u);\n    // Now that we've issued the LINETO REPEAT N command, we append\n    // N coordinate pairs immediately after the command.\n    for (++pt; pt != line.end(); ++pt)\n    {\n        const std::int32_t dx = pt->get<0>() - start_x;\n        const std::int32_t dy = pt->get<1>() - start_y;\n        geometry.add_element(protozero::encode_zigzag32(dx));\n        geometry.add_element(protozero::encode_zigzag32(dy));\n        start_x = pt->get<0>();\n        start_y = pt->get<1>();\n    }\n    return true;\n}\n\ninline tile_linestring_t segmentToTileLine(const wgs84_segment_t &segment,\n                                           const mercator_box_t &tile_bbox)\n{\n    wgs84_linestring_t geo_line;\n    geo_line.push_back(segment.first);\n    geo_line.push_back(segment.second);\n\n    mercator_linestring_t unclipped_line;\n\n    auto wgs84_to_tile = [&tile_bbox](const wgs84_point_t &wgs84_point) {\n        // Convert lon/lat to global mercator coordinates\n        double mercator_x = wgs84_point.get<0>() * util::web_mercator::DEGREE_TO_PX;\n        double mercator_y = util::web_mercator::latToY(wgs84_point.get<1>()) *\n                            util::web_mercator::DEGREE_TO_PX;\n\n        // Convert global mercator coordinates to relative positions on\n        // the provide mercator tile\n        // convert lon/lat to tile coordinates\n        const auto box_width = tile_bbox.max_corner().get<0>() - tile_bbox.min_corner().get<0>();\n        const auto box_height = tile_bbox.max_corner().get<1>() - tile_bbox.min_corner().get<1>();\n        const auto tile_x = std::round(\n            ((mercator_x - tile_bbox.min_corner().get<0>()) * util::web_mercator::TILE_SIZE / box_width) *\n            util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE);\n        const auto tile_y = std::round(\n            ((tile_bbox.max_corner().get<1>() - mercator_y) * util::web_mercator::TILE_SIZE / box_height) *\n            util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE);\n\n        return mercator_point_t(tile_x, tile_y);\n    };\n\n    boost::geometry::append(unclipped_line, wgs84_to_tile(segment.first));\n    boost::geometry::append(unclipped_line, wgs84_to_tile(segment.second));\n\n    mercator_multi_linestring_t clipped_line;\n\n    boost::geometry::intersection(tile_clip_box, unclipped_line, clipped_line);\n\n    tile_linestring_t tile_line;\n\n    // b::g::intersection might return a line with one point if the\n    // original line was very short and coords were dupes\n    if (!clipped_line.empty() && clipped_line[0].size() == 2)\n    {\n        if (clipped_line[0].size() == 2)\n        {\n            for (const auto &p : clipped_line[0])\n            {\n                tile_line.emplace_back(p.get<0>(), p.get<1>());\n            }\n        }\n    }\n\n    return tile_line;\n}\n\n} }\n\n", "meta": {"hexsha": "4e5de5f1447a9d9a35be2daa7329fd1f9149369d", "size": 5449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tile.hpp", "max_stars_repo_name": "danpat/atuin", "max_stars_repo_head_hexsha": "097915a8fdc085627a7545fe836a7b6f018cdd69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-08-30T21:00:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T11:22:41.000Z", "max_issues_repo_path": "src/tile.hpp", "max_issues_repo_name": "danpat/atuin", "max_issues_repo_head_hexsha": "097915a8fdc085627a7545fe836a7b6f018cdd69", "max_issues_repo_licenses": ["MIT"], "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/tile.hpp", "max_forks_repo_name": "danpat/atuin", "max_forks_repo_head_hexsha": "097915a8fdc085627a7545fe836a7b6f018cdd69", "max_forks_repo_licenses": ["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.9214285714, "max_line_length": 107, "alphanum_fraction": 0.6472747293, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18621981890568792}}
{"text": "//\n// Created by markus on 20.04.21.\n//\n\n#include <random>\n#include \"ParticleOperator.h\"\n#include \"BasicWithNovelty.h\"\n#include \"../lib/helpers.h\"\n#include <boost/math/distributions/exponential.hpp>\n#include <chrono>\n\nusing namespace std::chrono;\n\n\nParticleOperator::ParticleOperator(RobotControlInterface *robot, std::string map_filename, bool benchmarkMode) : RobotOperator(robot), particleFilter(robot, map_filename) {\n    if (benchmarkMode) std::cout << \"Benchmark mode support has been removed from the particle filter class. If required implement it on Scenario/Operator level\" << std::endl;\n    this->secondOperator = new BasicWithNovelty(robot);\n}\n\n\n/** loop function which will be called once every tick\n *\n */\nvoid ParticleOperator::update() {\n    // using another operator for the actual movement, so this one can focus on particle filter\n    this->secondOperator->update();\n    this->particleFilter.update();\n\n}\n", "meta": {"hexsha": "8a24d0d964d718e069618faf3b93e9b8b4763174", "size": 924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Operators/ParticleOperator.cpp", "max_stars_repo_name": "Glutamat42/Robot-Simulator", "max_stars_repo_head_hexsha": "4cec0e3bcb2aeb607f57e83bd545d626ea53af1a", "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": "Operators/ParticleOperator.cpp", "max_issues_repo_name": "Glutamat42/Robot-Simulator", "max_issues_repo_head_hexsha": "4cec0e3bcb2aeb607f57e83bd545d626ea53af1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Operators/ParticleOperator.cpp", "max_forks_repo_name": "Glutamat42/Robot-Simulator", "max_forks_repo_head_hexsha": "4cec0e3bcb2aeb607f57e83bd545d626ea53af1a", "max_forks_repo_licenses": ["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.8, "max_line_length": 175, "alphanum_fraction": 0.7467532468, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.18621981533037835}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Regression\n\n#include <fstream>\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n\n#include <xolotl/core/flux/W100FitFluxHandler.h>\n#include <xolotl/core/network/PSIReactionNetwork.h>\n#include <xolotl/options/Options.h>\n#include <xolotl/test/CommandLine.h>\n#include <xolotl/util/MPIUtils.h>\n\nusing namespace std;\nusing namespace xolotl;\nusing namespace core;\nusing namespace flux;\n\nusing Kokkos::ScopeGuard;\nBOOST_GLOBAL_FIXTURE(ScopeGuard);\n\n/**\n * The test suite is responsible for testing the W100FitFluxHandler.\n */\nBOOST_AUTO_TEST_SUITE(W100FitFluxHandlerTester_testSuite)\n\nBOOST_AUTO_TEST_CASE(checkComputeIncidentFlux)\n{\n\t// Create the option to create a network\n\txolotl::options::Options opts;\n\t// Create a good parameter file\n\tstd::string parameterFile = \"param.txt\";\n\tstd::ofstream paramFile(parameterFile);\n\tparamFile << \"netParam=9 0 0 0 0\" << std::endl;\n\tparamFile.close();\n\n\t// Create a fake command line to read the options\n\ttest::CommandLine<2> cl{{\"fakeXolotlAppNameForTests\", parameterFile}};\n\tutil::mpiInit(cl.argc, cl.argv);\n\topts.readParams(cl.argc, cl.argv);\n\n\tstd::remove(parameterFile.c_str());\n\n\t// Create a grid\n\tstd::vector<double> grid;\n\tfor (int l = 0; l < 7; l++) {\n\t\tgrid.push_back((double)l * 1.25);\n\t}\n\t// Specify the surface position\n\tint surfacePos = 0;\n\n\t// Create the network\n\tusing NetworkType =\n\t\tnetwork::PSIReactionNetwork<network::PSIFullSpeciesList>;\n\tNetworkType::AmountType maxV = opts.getMaxV();\n\tNetworkType::AmountType maxI = opts.getMaxI();\n\tNetworkType::AmountType maxHe = opts.getMaxImpurity();\n\tNetworkType::AmountType maxD = opts.getMaxD();\n\tNetworkType::AmountType maxT = opts.getMaxT();\n\tNetworkType network({maxHe, maxD, maxT, maxV, maxI}, grid.size(), opts);\n\tnetwork.syncClusterDataOnHost();\n\tnetwork.getSubpaving().syncZones(plsm::onHost);\n\t// Get its size\n\tconst int dof = network.getDOF();\n\n\t// Create the W100 flux handler\n\tauto testFitFlux = make_shared<W100FitFluxHandler>(opts);\n\t// Set the flux amplitude\n\ttestFitFlux->setFluxAmplitude(1.0);\n\t// Initialize the flux handler\n\ttestFitFlux->initializeFluxHandler(network, surfacePos, grid);\n\n\t// Create a time\n\tdouble currTime = 1.0;\n\n\t// The array of concentration\n\tdouble newConcentration[5 * dof];\n\n\t// Initialize their values\n\tfor (int i = 0; i < 5 * dof; i++) {\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// The pointer to the grid point we want\n\tdouble* updatedConc = &newConcentration[0];\n\tdouble* updatedConcOffset = updatedConc + dof;\n\n\t// Update the concentrations at some grid points\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 1, surfacePos);\n\tupdatedConcOffset = updatedConc + 2 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 2, surfacePos);\n\tupdatedConcOffset = updatedConc + 3 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 3, surfacePos);\n\n\t// Check the value at some grid points\n\tBOOST_REQUIRE_CLOSE(newConcentration[9], 0.444777, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[18], 0.247638, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[27], 0.10758, 0.01);\n\n\treturn;\n}\n\nBOOST_AUTO_TEST_CASE(checkComputeIncidentFluxNoGrid)\n{\n\t// Create the option to create a network\n\txolotl::options::Options opts;\n\t// Create a good parameter file\n\tstd::string parameterFile = \"param.txt\";\n\tstd::ofstream paramFile(parameterFile);\n\tparamFile << \"netParam=9 0 0 0 0\" << std::endl;\n\tparamFile.close();\n\n\t// Create a fake command line to read the options\n\ttest::CommandLine<2> cl{{\"fakeXolotlAppNameForTests\", parameterFile}};\n\topts.readParams(cl.argc, cl.argv);\n\n\tstd::remove(parameterFile.c_str());\n\n\t// Create a grid\n\tstd::vector<double> grid;\n\t// Specify the surface position\n\tint surfacePos = 0;\n\n\t// Create the network\n\tusing NetworkType =\n\t\tnetwork::PSIReactionNetwork<network::PSIFullSpeciesList>;\n\tNetworkType::AmountType maxV = opts.getMaxV();\n\tNetworkType::AmountType maxI = opts.getMaxI();\n\tNetworkType::AmountType maxHe = opts.getMaxImpurity();\n\tNetworkType::AmountType maxD = opts.getMaxD();\n\tNetworkType::AmountType maxT = opts.getMaxT();\n\tNetworkType network({maxHe, maxD, maxT, maxV, maxI}, grid.size(), opts);\n\tnetwork.syncClusterDataOnHost();\n\tnetwork.getSubpaving().syncZones(plsm::onHost);\n\t// Get its size\n\tconst int dof = network.getDOF();\n\n\t// Create the W100 flux handler\n\tauto testFitFlux = make_shared<W100FitFluxHandler>(opts);\n\t// Set the flux amplitude\n\ttestFitFlux->setFluxAmplitude(1.0);\n\t// Initialize the flux handler\n\ttestFitFlux->initializeFluxHandler(network, surfacePos, grid);\n\n\t// Create a time\n\tdouble currTime = 1.0;\n\n\t// The array of concentration\n\tdouble newConcentration[dof];\n\n\t// Initialize their values\n\tfor (int i = 0; i < dof; i++) {\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// The pointer to the grid point we want\n\tdouble* updatedConc = &newConcentration[0];\n\tdouble* updatedConcOffset = updatedConc;\n\n\t// Update the concentrations at some grid points\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 0, surfacePos);\n\n\t// Check the value at some grid points\n\tBOOST_REQUIRE_CLOSE(newConcentration[0], 1.0, 0.01);\n\n\treturn;\n}\n\nBOOST_AUTO_TEST_CASE(checkFluence)\n{\n\t// Create the option to create a network\n\txolotl::options::Options opts;\n\t// Create a good parameter file\n\tstd::string parameterFile = \"param.txt\";\n\tstd::ofstream paramFile(parameterFile);\n\tparamFile << \"netParam=9 0 0 0 0\" << std::endl;\n\tparamFile.close();\n\n\t// Create a fake command line to read the options\n\ttest::CommandLine<2> cl{{\"fakeXolotlAppNameForTests\", parameterFile}};\n\topts.readParams(cl.argc, cl.argv);\n\n\tstd::remove(parameterFile.c_str());\n\n\t// Create a grid\n\tstd::vector<double> grid;\n\tfor (int l = 0; l < 7; l++) {\n\t\tgrid.push_back((double)l * 1.25);\n\t}\n\t// Specify the surface position\n\tint surfacePos = 0;\n\n\t// Create the network\n\tusing NetworkType =\n\t\tnetwork::PSIReactionNetwork<network::PSIFullSpeciesList>;\n\tNetworkType::AmountType maxV = opts.getMaxV();\n\tNetworkType::AmountType maxI = opts.getMaxI();\n\tNetworkType::AmountType maxHe = opts.getMaxImpurity();\n\tNetworkType::AmountType maxD = opts.getMaxD();\n\tNetworkType::AmountType maxT = opts.getMaxT();\n\tNetworkType network({maxHe, maxD, maxT, maxV, maxI}, grid.size(), opts);\n\tnetwork.syncClusterDataOnHost();\n\tnetwork.getSubpaving().syncZones(plsm::onHost);\n\t// Get its size\n\tconst int dof = network.getDOF();\n\n\t// Create the W100 flux handler\n\tauto testFitFlux = make_shared<W100FitFluxHandler>(opts);\n\t// Set the flux amplitude\n\ttestFitFlux->setFluxAmplitude(1.0);\n\t// Initialize the flux handler\n\ttestFitFlux->initializeFluxHandler(network, surfacePos, grid);\n\n\t// Check that the fluence is 0.0 at the beginning\n\tBOOST_REQUIRE_EQUAL(testFitFlux->getFluence(), 0.0);\n\n\t// Increment the fluence\n\ttestFitFlux->incrementFluence(1.0e-8);\n\n\t// Check that the fluence is not 0.0 anymore\n\tBOOST_REQUIRE_EQUAL(testFitFlux->getFluence(), 1.0e-8);\n\n\treturn;\n}\n\nBOOST_AUTO_TEST_CASE(checkFluxAmplitude)\n{\n\t// Create the option to create a network\n\txolotl::options::Options opts;\n\t// Create a good parameter file\n\tstd::string parameterFile = \"param.txt\";\n\tstd::ofstream paramFile(parameterFile);\n\tparamFile << \"netParam=9 0 0 0 0\" << std::endl;\n\tparamFile.close();\n\n\t// Create a fake command line to read the options\n\ttest::CommandLine<2> cl{{\"fakeXolotlAppNameForTests\", parameterFile}};\n\topts.readParams(cl.argc, cl.argv);\n\n\tstd::remove(parameterFile.c_str());\n\n\t// Create a grid\n\tstd::vector<double> grid;\n\tfor (int l = 0; l < 7; l++) {\n\t\tgrid.push_back((double)l * 1.25);\n\t}\n\t// Specify the surface position\n\tint surfacePos = 0;\n\n\t// Create the network\n\tusing NetworkType =\n\t\tnetwork::PSIReactionNetwork<network::PSIFullSpeciesList>;\n\tNetworkType::AmountType maxV = opts.getMaxV();\n\tNetworkType::AmountType maxI = opts.getMaxI();\n\tNetworkType::AmountType maxHe = opts.getMaxImpurity();\n\tNetworkType::AmountType maxD = opts.getMaxD();\n\tNetworkType::AmountType maxT = opts.getMaxT();\n\tNetworkType network({maxHe, maxD, maxT, maxV, maxI}, grid.size(), opts);\n\tnetwork.syncClusterDataOnHost();\n\tnetwork.getSubpaving().syncZones(plsm::onHost);\n\t// Get its size\n\tconst int dof = network.getDOF();\n\n\t// Create the W100 flux handler\n\tauto testFitFlux = make_shared<W100FitFluxHandler>(opts);\n\n\t// Set the factor to change the flux amplitude\n\ttestFitFlux->setFluxAmplitude(2.5);\n\t// Initialize the flux handler\n\ttestFitFlux->initializeFluxHandler(network, surfacePos, grid);\n\n\t// Check the value of the flux amplitude\n\tBOOST_REQUIRE_EQUAL(testFitFlux->getFluxAmplitude(), 2.5);\n\n\t// Create a time\n\tdouble currTime = 1.0;\n\n\t// The array of concentration\n\tdouble newConcentration[5 * dof];\n\n\t// Initialize their values\n\tfor (int i = 0; i < 5 * dof; i++) {\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// The pointer to the grid point we want\n\tdouble* updatedConc = &newConcentration[0];\n\tdouble* updatedConcOffset = updatedConc + dof;\n\n\t// Update the concentrations at some grid points\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 1, surfacePos);\n\tupdatedConcOffset = updatedConc + 2 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 2, surfacePos);\n\tupdatedConcOffset = updatedConc + 3 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 3, surfacePos);\n\n\t// Check the value at some grid points\n\tBOOST_REQUIRE_CLOSE(newConcentration[9], 1.111943, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[18], 0.619095, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[27], 0.268961, 0.01);\n\n\treturn;\n}\n\nBOOST_AUTO_TEST_CASE(checkTimeProfileFlux)\n{\n\t// Create the option to create a network\n\txolotl::options::Options opts;\n\t// Create a good parameter file\n\tstd::string parameterFile = \"param.txt\";\n\tstd::ofstream paramFile(parameterFile);\n\tparamFile << \"netParam=9 0 0 0 0\" << std::endl;\n\tparamFile.close();\n\n\t// Create a fake command line to read the options\n\ttest::CommandLine<2> cl{{\"fakeXolotlAppNameForTests\", parameterFile}};\n\topts.readParams(cl.argc, cl.argv);\n\n\tstd::remove(parameterFile.c_str());\n\n\t// Create a grid\n\tstd::vector<double> grid;\n\tfor (int l = 0; l < 7; l++) {\n\t\tgrid.push_back((double)l * 1.25);\n\t}\n\t// Specify the surface position\n\tint surfacePos = 0;\n\n\t// Create the network\n\tusing NetworkType =\n\t\tnetwork::PSIReactionNetwork<network::PSIFullSpeciesList>;\n\tNetworkType::AmountType maxV = opts.getMaxV();\n\tNetworkType::AmountType maxI = opts.getMaxI();\n\tNetworkType::AmountType maxHe = opts.getMaxImpurity();\n\tNetworkType::AmountType maxD = opts.getMaxD();\n\tNetworkType::AmountType maxT = opts.getMaxT();\n\tNetworkType network({maxHe, maxD, maxT, maxV, maxI}, grid.size(), opts);\n\tnetwork.syncClusterDataOnHost();\n\tnetwork.getSubpaving().syncZones(plsm::onHost);\n\t// Get its size\n\tconst int dof = network.getDOF();\n\n\t// Create a file with a time profile for the flux\n\t// First column with the time and the second with\n\t// the amplitude (in He/nm2/s) at that time.\n\tstd::string fluxFile = \"fluxFile.dat\";\n\tstd::ofstream writeFluxFile(fluxFile);\n\twriteFluxFile << \"0.0 1000.0 \\n\"\n\t\t\t\t\t \"1.0 4000.0 \\n\"\n\t\t\t\t\t \"2.0 2000.0 \\n\"\n\t\t\t\t\t \"3.0 3000.0 \\n\"\n\t\t\t\t\t \"4.0 0.0\";\n\twriteFluxFile.close();\n\n\tauto testFitFlux = make_shared<W100FitFluxHandler>(opts);\n\t// Initialize the time profile for the flux handler\n\ttestFitFlux->initializeTimeProfile(fluxFile);\n\t// Initialize the flux handler\n\ttestFitFlux->initializeFluxHandler(network, surfacePos, grid);\n\n\t// Create a time\n\tdouble currTime = 0.5;\n\n\t// The array of concentration\n\tdouble newConcentration[5 * dof];\n\n\t// Initialize their values\n\tfor (int i = 0; i < 5 * dof; i++) {\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// The pointer to the grid point we want\n\tdouble* updatedConc = &newConcentration[0];\n\tdouble* updatedConcOffset = updatedConc + dof;\n\n\t// Update the concentrations at some grid points\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 1, surfacePos);\n\tupdatedConcOffset = updatedConc + 2 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 2, surfacePos);\n\tupdatedConcOffset = updatedConc + 3 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 3, surfacePos);\n\n\t// Check the value at some grid points\n\tBOOST_REQUIRE_CLOSE(newConcentration[9], 1111.94, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[18], 619.095, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[27], 268.961, 0.01);\n\t// Check the value of the flux amplitude\n\tBOOST_REQUIRE_EQUAL(testFitFlux->getFluxAmplitude(), 2500.0);\n\n\t// Change the current time\n\tcurrTime = 3.5;\n\n\t// Reinitialize their values\n\tfor (int i = 0; i < 5 * dof; i++) {\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// Update the concentrations at some grid points\n\tupdatedConcOffset = updatedConc + dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 1, surfacePos);\n\tupdatedConcOffset = updatedConc + 2 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 2, surfacePos);\n\tupdatedConcOffset = updatedConc + 3 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 3, surfacePos);\n\n\t// Check the value at some grid points\n\tBOOST_REQUIRE_CLOSE(newConcentration[9], 667.166, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[18], 371.457, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[27], 161.377, 0.01);\n\t// Check the value of the flux amplitude\n\tBOOST_REQUIRE_EQUAL(testFitFlux->getFluxAmplitude(), 1500.0);\n\n\t// Remove the created file\n\tstd::remove(fluxFile.c_str());\n\n\t// Finalize MPI\n\tMPI_Finalize();\n\n\treturn;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b55751ae11c62c3c08569c8d9bbd5118f7e8b6bb", "size": 13405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/flux/W100FitFluxHandlerTester.cpp", "max_stars_repo_name": "ORNL-Fusion/xolotl", "max_stars_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-06-13T18:08:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T02:39:01.000Z", "max_issues_repo_path": "test/core/flux/W100FitFluxHandlerTester.cpp", "max_issues_repo_name": "ORNL-Fusion/xolotl", "max_issues_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2018-02-14T15:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T16:29:48.000Z", "max_forks_repo_path": "test/core/flux/W100FitFluxHandlerTester.cpp", "max_forks_repo_name": "ORNL-Fusion/xolotl", "max_forks_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-02-13T20:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T14:54:16.000Z", "avg_line_length": 30.6750572082, "max_line_length": 73, "alphanum_fraction": 0.7374114137, "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.18615862445564657}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SCALAR_EXPRECNEGC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SCALAR_EXPRECNEGC_HPP_INCLUDED\n\n#include <boost/simd/function/definition/exprecnegc.hpp>\n#include <boost/simd/arch/common/scalar/function/exprecnegc.hpp>\n\n#endif\n", "meta": {"hexsha": "cb596da3b47031cd25141d7297dfc546d44df1fa", "size": 633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/scalar/exprecnegc.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/scalar/exprecnegc.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/scalar/exprecnegc.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.2352941176, "max_line_length": 100, "alphanum_fraction": 0.5545023697, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.18615862445564654}}
{"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_REDUCTION_FUNCTIONS_SIMD_SSE_SSE2_HMSB_HPP_INCLUDED\n#define BOOST_SIMD_REDUCTION_FUNCTIONS_SIMD_SSE_SSE2_HMSB_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n\n#include <boost/simd/reduction/functions/hmsb.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <cstddef>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( hmsb_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_ < type8_<A0>\n                                              , boost::simd::tag::sse_\n                                              >\n                                      ))\n                                    )\n  {\n    typedef std::size_t result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      return _mm_movemask_epi8(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( hmsb_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_ < type32_<A0>\n                                              , boost::simd::tag::sse_\n                                              >\n                                      ))\n                                    )\n  {\n    typedef std::size_t result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      typedef typename dispatch::meta::as_floating<A0>::type type;\n      return _mm_movemask_ps(bitwise_cast<type>(a0));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( hmsb_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_ < type64_<A0>\n                                              , boost::simd::tag::sse_\n                                              >\n                                      ))\n                      )\n  {\n    typedef std::size_t result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      typedef typename dispatch::meta::as_floating<A0>::type type;\n      return _mm_movemask_pd(bitwise_cast<type>(a0));\n    }\n  };\n\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "fecdad0cbc5ef4157ac89c444def4a8c7899b9c7", "size": 2831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/reduction/functions/simd/sse/sse2/hmsb.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/reduction/functions/simd/sse/sse2/hmsb.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/reduction/functions/simd/sse/sse2/hmsb.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": 37.7466666667, "max_line_length": 80, "alphanum_fraction": 0.4464853409, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.18615862445564654}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 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#define BOOST_TEST_MODULE threshold_test\n\n#include <nil/crypto3/pubkey/modes/algorithm/sign.hpp>\n#include <nil/crypto3/pubkey/modes/algorithm/verify.hpp>\n#include <nil/crypto3/pubkey/modes/algorithm/part_verify.hpp>\n#include <nil/crypto3/pubkey/modes/algorithm/aggregate.hpp>\n#include <nil/crypto3/pubkey/algorithm/deal_shares.hpp>\n#include <nil/crypto3/pubkey/modes/algorithm/create_key.hpp>\n\n#include <nil/crypto3/pubkey/modes/threshold.hpp>\n\n#include <nil/crypto3/pubkey/bls.hpp>\n\n#include <nil/crypto3/pubkey/secret_sharing.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include <iostream>\n#include <string>\n#include <cassert>\n#include <unordered_map>\n\nusing namespace nil::crypto3::algebra;\nusing namespace nil::crypto3::hashes;\nusing namespace nil::crypto3::pubkey;\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp<FieldParams> &e) {\n    os << e.data << std::endl;\n}\n\ntemplate<typename FpCurveGroupElement>\nvoid print_fp_curve_group_element(std::ostream &os, const FpCurveGroupElement &e) {\n    os << std::hex << \"( \" << e.X.data << \" : \" << e.Y.data << \" : \" << e.Z.data << \" )\" << std::endl;\n}\n\ntemplate<typename Fp2CurveGroupElement>\nvoid print_fp2_curve_group_element(std::ostream &os, const Fp2CurveGroupElement &e) {\n    os << std::hex << \"(\" << e.X.data[0].data << \" , \" << e.X.data[1].data << \") : (\" << e.Y.data[0].data << \" , \"\n       << e.Y.data[1].data << \") : (\" << e.Z.data[0].data << \" , \" << e.Z.data[1].data << \")\" << std::endl;\n}\n\nnamespace boost {\n    namespace test_tools {\n        namespace tt_detail {\n            template<>\n            struct print_log_value<typename curves::bls12<381>::g1_type::value_type> {\n                void operator()(std::ostream &os, typename curves::bls12<381>::g1_type::value_type const &e) {\n                    print_fp_curve_group_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<typename curves::bls12<381>::g2_type::value_type> {\n                void operator()(std::ostream &os, typename curves::bls12<381>::g2_type::value_type const &e) {\n                    print_fp2_curve_group_element(os, e);\n                }\n            };\n\n            template<template<typename, typename> class P, typename K, typename V>\n            struct print_log_value<P<K, V>> {\n                void operator()(std::ostream &, P<K, V> const &) {\n                }\n            };\n        }    // namespace tt_detail\n    }        // namespace test_tools\n}    // namespace boost\n\nconst std::string msg_str = \"hello foo\";\nconst std::vector<std::uint8_t> msg(msg_str.begin(), msg_str.end());\n\nBOOST_AUTO_TEST_SUITE(threshold_self_test_suite)\n\nBOOST_AUTO_TEST_CASE(threshold_bls_feldman_self_test) {\n    using curve_type = curves::bls12_381;\n    using hash_type = sha2<256>;\n    using bls_variant = bls_mps_ro_variant<curve_type, hash_type>;\n    using base_scheme_type = bls<bls_variant, bls_basic_scheme>;\n    using mode_type = modes::threshold<base_scheme_type, feldman_sss, nop_padding>;\n    using scheme_type = typename mode_type::scheme_type;\n    using privkey_type = private_key<scheme_type>;\n    using pubkey_type = public_key<scheme_type>;\n    using no_key_type = no_key_ops<scheme_type>;\n    using sss_pubkey_no_key_type = typename privkey_type::sss_public_key_no_key_ops_type;\n\n    std::size_t n = 20;\n    std::size_t t = 10;\n\n    //===========================================================================\n    // dealer creates participants keys and its public key\n    typename sss_pubkey_no_key_type::coeffs_type coeffs = sss_pubkey_no_key_type::get_poly(t, n);\n    typename sss_pubkey_no_key_type::public_coeffs_type public_coeffs =\n        sss_pubkey_no_key_type::get_public_coeffs(coeffs);\n    typename sss_pubkey_no_key_type::public_coeffs_type public_coeffs_wrong(public_coeffs.begin(),\n                                                                            public_coeffs.end() - 1);\n    auto [PK, privkeys] = nil::crypto3::create_key<scheme_type>(coeffs, n);\n\n    //===========================================================================\n    // participants should check received shares before key creating\n    std::vector<privkey_type> verified_privkeys;\n    typename sss_pubkey_no_key_type::shares_type verified_shares =\n        nil::crypto3::deal_shares<typename privkey_type::sss_public_key_group_type>(coeffs, n);\n    for (auto &s : verified_shares) {\n        verified_privkeys.emplace_back(nil::crypto3::create_key<scheme_type>(public_coeffs, s, n));\n        BOOST_CHECK(verified_privkeys.back().verify_key(public_coeffs));\n        BOOST_CHECK(!verified_privkeys.back().verify_key(public_coeffs_wrong));\n    }\n\n    //===========================================================================\n    // participants sign messages and verify its signatures\n    std::vector<typename privkey_type::part_signature_type> part_signatures;\n    for (auto &sk : privkeys) {\n        part_signatures.emplace_back(nil::crypto3::sign<mode_type>(msg, sk));\n        BOOST_CHECK(static_cast<bool>(nil::crypto3::part_verify<mode_type>(msg, part_signatures.back(), sk)));\n    }\n\n    //===========================================================================\n    // threshold number of participants aggregate partial signatures\n    typename no_key_type::signature_type sig =\n        nil::crypto3::aggregate<mode_type>(part_signatures.begin(), part_signatures.begin() + t);\n    BOOST_CHECK(static_cast<bool>(nil::crypto3::verify<mode_type>(msg, sig, PK)));\n\n    //===========================================================================\n    // less than threshold number of participants cannot aggregate partial signatures\n    typename no_key_type::signature_type wrong_sig =\n        nil::crypto3::aggregate<mode_type>(part_signatures.begin(), part_signatures.begin() + t - 1);\n    BOOST_CHECK(!static_cast<bool>(nil::crypto3::verify<mode_type>(msg, wrong_sig, PK)));\n}\n\nBOOST_AUTO_TEST_CASE(threshold_bls_pedersen_self_test) {\n    using curve_type = curves::bls12_381;\n    using hash_type = sha2<256>;\n    using bls_variant = bls_mps_ro_variant<curve_type, hash_type>;\n    using base_scheme_type = bls<bls_variant, bls_basic_scheme>;\n    using mode_type = modes::threshold<base_scheme_type, pedersen_dkg, nop_padding>;\n    using scheme_type = typename mode_type::scheme_type;\n    using privkey_type = private_key<scheme_type>;\n    using pubkey_type = public_key<scheme_type>;\n    using no_key_type = no_key_ops<scheme_type>;\n    using sss_pubkey_group_type = typename privkey_type::sss_public_key_group_type;\n    using sss_pubkey_no_key_type = typename privkey_type::sss_public_key_no_key_ops_type;\n\n    std::size_t n = 20;\n    std::size_t t = 10;\n\n    //===========================================================================\n    // every participant generates polynomial\n\n    std::vector<typename sss_pubkey_no_key_type::coeffs_type> P_polys;\n    std::generate_n(std::back_inserter(P_polys), n, [t, n]() { return sss_pubkey_no_key_type::get_poly(t, n); });\n\n    //===========================================================================\n    // each participant calculates public values representing coefficients of its polynomial,\n    // then he broadcasts these values\n\n    std::vector<typename sss_pubkey_no_key_type::public_coeffs_type> P_public_polys;\n    std::transform(P_polys.begin(), P_polys.end(), std::back_inserter(P_public_polys),\n                   [](const auto &poly_i) { return sss_pubkey_no_key_type::get_public_coeffs(poly_i); });\n\n    //===========================================================================\n    // every participant generates shares for each participant in group,\n    // which he then transmits to the intended parties\n\n    std::vector<typename sss_pubkey_no_key_type::shares_type> P_generated_shares;\n    std::transform(P_polys.begin(), P_polys.end(), std::back_inserter(P_generated_shares), [n, t](const auto &poly_i) {\n        return static_cast<typename sss_pubkey_no_key_type::shares_type>(\n            nil::crypto3::deal_shares<sss_pubkey_group_type>(poly_i, n));\n    });\n\n    std::vector<std::vector<typename sss_pubkey_no_key_type::share_type>> P_received_shares(n);\n    for (auto &i_generated_shares : P_generated_shares) {\n        for (auto it = i_generated_shares.begin(); it != i_generated_shares.end(); it++) {\n            P_received_shares.at(it->first - 1).emplace_back(*it);\n        }\n    }\n\n    //===========================================================================\n    // each participant check received share and create key\n\n    std::vector<pubkey_type> PKs;\n    std::vector<privkey_type> privkeys;\n    for (auto &shares : P_received_shares) {\n        auto [PK_temp, privkey] = nil::crypto3::create_key<scheme_type>(P_public_polys, shares, n);\n        PKs.emplace_back(PK_temp);\n        privkeys.emplace_back(privkey);\n    }\n\n    //===========================================================================\n    // participants sign messages and verify its signatures\n    std::vector<typename privkey_type::part_signature_type> part_signatures;\n    for (auto &sk : privkeys) {\n        part_signatures.emplace_back(nil::crypto3::sign<mode_type>(msg, sk));\n        BOOST_CHECK(static_cast<bool>(nil::crypto3::part_verify<mode_type>(msg, part_signatures.back(), sk)));\n    }\n\n    //===========================================================================\n    // threshold number of participants aggregate partial signatures\n    typename no_key_type::signature_type sig =\n        nil::crypto3::aggregate<mode_type>(part_signatures.begin(), part_signatures.begin() + t);\n    BOOST_CHECK(static_cast<bool>(nil::crypto3::verify<mode_type>(msg, sig, PKs.back())));\n\n    //===========================================================================\n    // less than threshold number of participants cannot aggregate partial signatures\n    typename no_key_type::signature_type wrong_sig =\n        nil::crypto3::aggregate<mode_type>(part_signatures.begin(), part_signatures.begin() + t - 1);\n    BOOST_CHECK(!static_cast<bool>(nil::crypto3::verify<mode_type>(msg, wrong_sig, PKs.back())));\n}\n\nBOOST_AUTO_TEST_CASE(threshold_bls_weighted_shamir_test) {\n    using curve_type = curves::bls12_381;\n    using hash_type = sha2<256>;\n    using bls_variant = bls_mps_ro_variant<curve_type, hash_type>;\n    using base_scheme_type = bls<bls_variant, bls_basic_scheme>;\n    using mode_type = modes::threshold<base_scheme_type, weighted_shamir_sss, nop_padding>;\n    using scheme_type = typename mode_type::scheme_type;\n    using privkey_type = private_key<scheme_type>;\n    using pubkey_type = public_key<scheme_type>;\n    using no_key_type = no_key_ops<scheme_type>;\n    using sss_pubkey_no_key_type = typename privkey_type::sss_public_key_no_key_ops_type;\n\n    std::size_t n = 20;\n    std::size_t t = 10;\n\n    auto i = 1;\n    auto j = 1;\n    typename privkey_type::sss_public_key_no_key_ops_type::weights_type weights;\n    std::generate_n(std::inserter(weights, weights.end()), n, [&i, &j, &t]() {\n        j = j >= t ? 1 : j;\n        return typename privkey_type::sss_public_key_no_key_ops_type::weight_type(i++, j++);\n    });\n\n    //===========================================================================\n    // dealer creates participants keys and its public key\n    typename sss_pubkey_no_key_type::coeffs_type coeffs = sss_pubkey_no_key_type::get_poly(t, n);\n    auto [PK, privkeys] = nil::crypto3::create_key<scheme_type>(coeffs, weights);\n\n    //===========================================================================\n    // participants sign messages and verify its signatures\n    std::vector<typename privkey_type::part_signature_type> part_signatures;\n    for (auto &sk : privkeys) {\n        part_signatures.emplace_back(\n            nil::crypto3::sign<mode_type>(msg.begin(), msg.end(), weights.begin(), weights.end(), sk));\n        BOOST_CHECK(static_cast<bool>(nil::crypto3::part_verify<mode_type>(msg.begin(), msg.end(), weights.begin(),\n                                                                           weights.end(), part_signatures.back(), sk)));\n    }\n\n    //===========================================================================\n    // confirmed group of participants aggregate partial signatures\n    typename no_key_type::signature_type sig =\n        nil::crypto3::aggregate<mode_type>(part_signatures.begin(), part_signatures.end());\n    BOOST_CHECK(static_cast<bool>(nil::crypto3::verify<mode_type>(msg, sig, PK)));\n\n    //===========================================================================\n    // not confirmed group of participants cannot aggregate partial signatures\n    typename no_key_type::signature_type wrong_sig =\n        nil::crypto3::aggregate<mode_type>(part_signatures.begin(), part_signatures.end() - 1);\n    BOOST_CHECK(!static_cast<bool>(nil::crypto3::verify<mode_type>(msg, wrong_sig, PK)));\n\n    //===========================================================================\n    // threshold number of participants sign messages and verify its signatures\n\n    std::vector<typename privkey_type::part_signature_type> part_signatures_t;\n    typename privkey_type::sss_public_key_no_key_ops_type::weights_type confirmed_weights;\n    std::vector<privkey_type> confirmed_keys;\n    auto it_weight_t = privkeys.begin();\n    auto weight = 0;\n    while (true) {\n        weight += it_weight_t->get_weight();\n        if (weight >= t) {\n            confirmed_keys.emplace_back(*it_weight_t);\n            confirmed_weights.emplace(it_weight_t->get_index(), weights.at(it_weight_t->get_index()));\n            it_weight_t++;\n            break;\n        }\n        confirmed_keys.emplace_back(*it_weight_t);\n        confirmed_weights.emplace(it_weight_t->get_index(), weights.at(it_weight_t->get_index()));\n        it_weight_t++;\n    }\n\n    for (auto &sk : confirmed_keys) {\n        part_signatures_t.emplace_back(nil::crypto3::sign<mode_type>(msg.begin(), msg.end(), confirmed_weights.begin(),\n                                                                     confirmed_weights.end(), sk));\n        BOOST_CHECK(static_cast<bool>(nil::crypto3::part_verify<mode_type>(\n            msg.begin(), msg.end(), confirmed_weights.begin(), confirmed_weights.end(), part_signatures_t.back(), sk)));\n    }\n\n    //===========================================================================\n    // threshold number of participants aggregate partial signatures\n\n    typename no_key_type::signature_type sig_t =\n        nil::crypto3::aggregate<mode_type>(part_signatures_t.begin(), part_signatures_t.end());\n    BOOST_CHECK(static_cast<bool>(nil::crypto3::verify<mode_type>(msg, sig_t, PK)));\n\n    //===========================================================================\n    // less than threshold number of participants sign messages and verify its signatures\n\n    std::vector<typename privkey_type::part_signature_type> part_signatures_less_t;\n    typename privkey_type::sss_public_key_no_key_ops_type::weights_type confirmed_weights_less_t;\n    std::vector<privkey_type> confirmed_keys_less_t;\n    auto it_weight_less_t = privkeys.begin();\n    auto weight_less_t = 0;\n    while (true) {\n        weight_less_t += it_weight_less_t->get_weight();\n        if (weight_less_t >= t) {\n            break;\n        }\n        confirmed_keys_less_t.emplace_back(*it_weight_less_t);\n        confirmed_weights_less_t.emplace(it_weight_less_t->get_index(), weights.at(it_weight_less_t->get_index()));\n        it_weight_t++;\n    }\n\n    for (auto &sk : confirmed_keys_less_t) {\n        part_signatures_less_t.emplace_back(nil::crypto3::sign<mode_type>(\n            msg.begin(), msg.end(), confirmed_weights_less_t.begin(), confirmed_weights_less_t.end(), sk));\n        BOOST_CHECK(static_cast<bool>(\n            nil::crypto3::part_verify<mode_type>(msg.begin(), msg.end(), confirmed_weights_less_t.begin(),\n                                                 confirmed_weights_less_t.end(), part_signatures_less_t.back(), sk)));\n    }\n\n    //===========================================================================\n    // less than threshold number of participants cannot aggregate partial signatures\n\n    typename no_key_type::signature_type sig_less_t =\n        nil::crypto3::aggregate<mode_type>(part_signatures_less_t.begin(), part_signatures_less_t.end());\n    BOOST_CHECK(!static_cast<bool>(nil::crypto3::verify<mode_type>(msg, sig_less_t, PK)));\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "80ab5280e4d673de709bd01223deddfbcf8da316", "size": 17857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/threshold.cpp", "max_stars_repo_name": "JasonCoombs/crypto3-pkmodes", "max_stars_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "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/threshold.cpp", "max_issues_repo_name": "JasonCoombs/crypto3-pkmodes", "max_issues_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-04-01T15:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T03:45:24.000Z", "max_forks_repo_path": "test/threshold.cpp", "max_forks_repo_name": "JasonCoombs/crypto3-pkmodes", "max_forks_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:40:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T03:13:02.000Z", "avg_line_length": 50.4435028249, "max_line_length": 120, "alphanum_fraction": 0.6323010584, "num_tokens": 3868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.186158617427378}}
{"text": "#ifndef FOURTOP_FUNCTIONS\n#define FOURTOP_FUNCTIONS\n\n//#include <boost>\n#include <cstring>\n#include <stdio.h>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <TObject.h>\n// #include <TH.h>\n#include <TH1.h>\n#include <TH2.h>\n#include <TH3.h>\n#include <TFile.h>\n#include <TMath.h>\n#include <TUUID.h>\n#include \"ROOT/RDF/RInterface.hxx\"\n#include \"ROOT/RVec.hxx\"\n#include \"LHAPDF/LHAPDF.h\"\n\ntypedef ROOT::VecOps::RVec<Float_t>                        RVec_f;\ntypedef ROOT::VecOps::RVec<Float_t>::const_iterator        RVec_f_iter;\ntypedef ROOT::VecOps::RVec<Int_t>                          RVec_i;\ntypedef ROOT::VecOps::RVec<Int_t>::const_iterator          RVec_i_iter;\ntypedef ROOT::VecOps::RVec<std::string>                    RVec_str;\ntypedef ROOT::VecOps::RVec<std::string>::const_iterator    RVec_str_iter;\n\n//aim for a std::vector<std::map<std::string, ROOT::TH>> format where the vector index corresponds to the slot # for multithreaded lookups\n// class LUT: public TObject {\nclass LUT {\n  //LookUp Table\npublic:\n  LUT() { _LUT_MAP_TH1.clear(); _LUT_MAP_TH2.clear(); _LUT_MAP_TH3.clear(); }\n  // LUT(std::string file, std::string path);\n  LUT(const LUT &lut);\n  ~LUT() {}\n  void Add(std::string file, std::string path, std::string handle = \"\");\n  std::vector<std::string> TH1Keys();\n  std::vector<std::string> TH2Keys();\n  std::vector<std::string> TH3Keys();\n\n\n  //Lookup gets bin content, Err gets bin error, if Flow is appended, then the histogram bin may be amongst the flow, instead of being forced to the non-flow bins\n  template <typename X>\n  double TH1Lookup(std::string key, X xval);\n  template <typename X>\n  double TH1LookupErr(std::string key, X xval);\n  template <typename X>\n  double TH1LookupFlow(std::string key, X xval);\n  template <typename X>\n  double TH1LookupErrFlow(std::string key, X xval);\n\n  template <typename X, typename Y>\n  double TH2Lookup(std::string key, X xval, Y yval);\n  template <typename X, typename Y>\n  double TH2LookupErr(std::string key, X xval, Y yval);\n  template <typename X, typename Y>\n  double TH2LookupFlow(std::string key, X xval, Y yval);\n  template <typename X, typename Y>\n  double TH2LookupErrFlow(std::string key, X xval, Y yval);\n\n  template <typename X, typename Y, typename Z>\n  double TH3Lookup(std::string key, X xval, Y yval, Z zval);\n  template <typename X, typename Y, typename Z>\n  double TH3LookupErr(std::string key, X xval, Y yval, Z zval);\n  template <typename X, typename Y, typename Z>\n  double TH3LookupFlow(std::string key, X xval, Y yval, Z zval);\n  template <typename X, typename Y, typename Z>\n  double TH3LookupErrFlow(std::string key, X xval, Y yval, Z zval);\n\nprivate:\n  std::map<std::string, TH1*> _LUT_MAP_TH1;\n  std::map<std::string, TH2*> _LUT_MAP_TH2;\n  std::map<std::string, TH3*> _LUT_MAP_TH3;\n  \n};\nLUT::LUT(const LUT &lut) {\n  TUUID uuid = TUUID();\n  std::map<std::string, TH1*> _LUT_MAP_TH1;\n  std::map<std::string, TH2*> _LUT_MAP_TH2;\n  std::map<std::string, TH3*> _LUT_MAP_TH3;\n  //Clone each histogram in each map, appending this copy constructor's uuid onto the end. Each histogram in the original should have a unique uuid,\n  //the ones here will inherit them and append a single copy-constructor uuid to them\n  for(auto th1_iter = lut._LUT_MAP_TH1.begin(); th1_iter != lut._LUT_MAP_TH1.end(); ++th1_iter){\n    std::string name = static_cast<std::string>(th1_iter->second->GetName()) + \"___\" + uuid.AsString();\n    _LUT_MAP_TH1[th1_iter->first] = static_cast<TH1*>(th1_iter->second->Clone(name.c_str()));\n    _LUT_MAP_TH1[th1_iter->first]->SetDirectory(0);\n  }\n  for(auto th2_iter = lut._LUT_MAP_TH2.begin(); th2_iter != lut._LUT_MAP_TH2.end(); ++th2_iter){\n    std::string name = static_cast<std::string>(th2_iter->second->GetName()) + \"___\" + uuid.AsString();\n    _LUT_MAP_TH2[th2_iter->first] = static_cast<TH2*>(th2_iter->second->Clone(name.c_str()));\n    _LUT_MAP_TH2[th2_iter->first]->SetDirectory(0);\n  }\n  for(auto th3_iter = lut._LUT_MAP_TH3.begin(); th3_iter != lut._LUT_MAP_TH3.end(); ++th3_iter){\n    std::string name = static_cast<std::string>(th3_iter->second->GetName()) + \"___\" + uuid.AsString();\n    _LUT_MAP_TH3[th3_iter->first] = static_cast<TH3*>(th3_iter->second->Clone(name.c_str()));\n    _LUT_MAP_TH3[th3_iter->first]->SetDirectory(0);\n  }\n}  \nvoid LUT::Add(std::string file, std::string path, std::string handle) {\n  TUUID uuid = TUUID();\n  TFile *f = TFile::Open(file.c_str(), \"read\");\n  if(f) {\n    if(f->IsOpen()){\n      auto temp = f->Get(path.c_str());\n      if(temp){\n\tstd::string key;\n\tBool_t isTH1 = (std::strncmp(temp->ClassName(), \"TH1\", 3) == 0);\n\tBool_t isTH2 = (std::strncmp(temp->ClassName(), \"TH2\", 3) == 0);\n\tBool_t isTH3 = (std::strncmp(temp->ClassName(), \"TH3\", 3) == 0);\n\tstd::string name = static_cast<std::string>(temp->GetName()) + \"___\" + uuid.AsString();\n\tif(handle.length() == 0) {\n\t  key = path;\n\t}\n\telse {\n\t  key = handle;\n\t}\n\tif( isTH1 ) { \n\t  _LUT_MAP_TH1[key] = static_cast<TH1*>(temp->Clone(name.c_str()));\n\t  _LUT_MAP_TH1[key]->SetDirectory(0);\n\t}\n\telse if( isTH2 ) { \n\t  _LUT_MAP_TH2[key] = static_cast<TH2*>(temp->Clone(name.c_str())); \n\t  _LUT_MAP_TH2[key]->SetDirectory(0);\n\t    }\n\telse if( isTH3 ) { \n\t  _LUT_MAP_TH3[key] = static_cast<TH3*>(temp->Clone(name.c_str())); \n\t  _LUT_MAP_TH3[key]->SetDirectory(0);\n\t}\n\telse { throw std::runtime_error( \"Unhandled LookUpTable class \" + static_cast<std::string>(temp->ClassName())); }\n\tf->Close();\n      }\n      else {\n\tf->Close();\n\tthrow std::runtime_error( \"Failed to instantiate valid LUT for path \" + path + \" in file \" + file );\n      }\n    }\n    else {\n      throw std::runtime_error( \"Failed to open file: \" + file );\n    }\n  }\n  else {\n      throw std::runtime_error( \"LookUpTable got a null pointer opening up the file: \" + file );\n  }\n      \n}\nstd::vector<std::string> LUT::TH1Keys(){\n  std::vector<std::string> ret;\n  for(std::map< std::string, TH1* >::iterator th1_iter = _LUT_MAP_TH1.begin(); th1_iter != _LUT_MAP_TH1.end(); ++th1_iter){\n    ret.push_back(th1_iter->first);\n  }  \n  return ret;\n}\nstd::vector<std::string> LUT::TH2Keys(){\n  std::vector<std::string> ret;\n  for(std::map< std::string, TH2* >::iterator th2_iter = _LUT_MAP_TH2.begin(); th2_iter != _LUT_MAP_TH2.end(); ++th2_iter){\n    ret.push_back(th2_iter->first);\n  }  \n  return ret;\n}\nstd::vector<std::string> LUT::TH3Keys(){\n  std::vector<std::string> ret;\n  for(std::map< std::string, TH3* >::iterator th3_iter = _LUT_MAP_TH3.begin(); th3_iter != _LUT_MAP_TH3.end(); ++th3_iter){\n    ret.push_back(th3_iter->first);\n  }  \n  return ret;\n}\ntemplate<typename X>\ndouble LUT::TH1Lookup(std::string key, X xval){\n  try {\n    int binx = std::max(0, std::min(_LUT_MAP_TH1[key]->GetNbinsX() + 1, _LUT_MAP_TH1[key]->GetXaxis()->FindBin(xval)));\n    return _LUT_MAP_TH1[key]->GetBinContent(binx);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH1Lookup\" << std::endl;\n    if( _LUT_MAP_TH1.find( key ) != _LUT_MAP_TH1.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH1 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X>\ndouble LUT::TH1LookupErr(std::string key, X xval){\n  try {\n    int binx = std::max(1, std::min(_LUT_MAP_TH1[key]->GetNbinsX(), _LUT_MAP_TH1[key]->GetXaxis()->FindBin(xval)));\n    return _LUT_MAP_TH1[key]->GetBinError(binx);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH1LookupErr\" << std::endl;\n    if( _LUT_MAP_TH1.find( key ) != _LUT_MAP_TH1.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH1 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X>\ndouble LUT::TH1LookupFlow(std::string key, X xval){\n  try {\n    int binx = std::max(0, std::min(_LUT_MAP_TH1[key]->GetNbinsX() + 1, _LUT_MAP_TH1[key]->GetXaxis()->FindBin(xval)));\n    return _LUT_MAP_TH1[key]->GetBinContent(binx);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH1Lookup\" << std::endl;\n    if( _LUT_MAP_TH1.find( key ) != _LUT_MAP_TH1.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH1 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X>\ndouble LUT::TH1LookupErrFlow(std::string key, X xval){\n  try {\n    int binx = std::max(0, std::min(_LUT_MAP_TH1[key]->GetNbinsX() + 1, _LUT_MAP_TH1[key]->GetXaxis()->FindBin(xval)));\n    return _LUT_MAP_TH1[key]->GetBinError(binx);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH1LookupErr\" << std::endl;\n    if( _LUT_MAP_TH1.find( key ) != _LUT_MAP_TH1.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH1 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X, typename Y>\ndouble LUT::TH2Lookup(std::string key, X xval, Y yval){\n  try {\n    int binx = std::max(1, std::min(_LUT_MAP_TH2[key]->GetNbinsX(), _LUT_MAP_TH2[key]->GetXaxis()->FindBin(xval)));\n    int biny = std::max(1, std::min(_LUT_MAP_TH2[key]->GetNbinsY(), _LUT_MAP_TH2[key]->GetYaxis()->FindBin(yval)));\n    return _LUT_MAP_TH2[key]->GetBinContent(binx, biny);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH2Lookup\" << std::endl;\n    if( _LUT_MAP_TH2.find( key ) != _LUT_MAP_TH2.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH2 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X, typename Y>\ndouble LUT::TH2LookupErr(std::string key, X xval, Y yval){\n  try {\n    int binx = std::max(0, std::min(_LUT_MAP_TH2[key]->GetNbinsX() + 1, _LUT_MAP_TH2[key]->GetXaxis()->FindBin(xval)));\n    int biny = std::max(0, std::min(_LUT_MAP_TH2[key]->GetNbinsY() + 1, _LUT_MAP_TH2[key]->GetYaxis()->FindBin(yval)));\n    return _LUT_MAP_TH2[key]->GetBinError(binx, biny);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH2LookupErr\" << std::endl;\n    if( _LUT_MAP_TH2.find( key ) != _LUT_MAP_TH2.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH2 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X, typename Y>\ndouble LUT::TH2LookupFlow(std::string key, X xval, Y yval){\n  try {\n    int binx = std::max(0, std::min(_LUT_MAP_TH2[key]->GetNbinsX() + 1, _LUT_MAP_TH2[key]->GetXaxis()->FindBin(xval)));\n    int biny = std::max(0, std::min(_LUT_MAP_TH2[key]->GetNbinsY() + 1, _LUT_MAP_TH2[key]->GetYaxis()->FindBin(yval)));\n    return _LUT_MAP_TH2[key]->GetBinContent(binx, biny);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH2Lookup\" << std::endl;\n    if( _LUT_MAP_TH2.find( key ) != _LUT_MAP_TH2.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH2 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X, typename Y>\ndouble LUT::TH2LookupErrFlow(std::string key, X xval, Y yval){\n  try {\n    int binx = std::max(0, std::min(_LUT_MAP_TH2[key]->GetNbinsX() + 1, _LUT_MAP_TH2[key]->GetXaxis()->FindBin(xval)));\n    int biny = std::max(0, std::min(_LUT_MAP_TH2[key]->GetNbinsY() + 1, _LUT_MAP_TH2[key]->GetYaxis()->FindBin(yval)));\n    return _LUT_MAP_TH2[key]->GetBinError(binx, biny);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH2LookupErr\" << std::endl;\n    if( _LUT_MAP_TH2.find( key ) != _LUT_MAP_TH2.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH2 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X, typename Y, typename Z>\ndouble LUT::TH3Lookup(std::string key, X xval, Y yval, Z zval){\n  try {\n    int binx = std::max(1, std::min(_LUT_MAP_TH3[key]->GetNbinsX(), _LUT_MAP_TH3[key]->GetXaxis()->FindBin(xval)));\n    int biny = std::max(1, std::min(_LUT_MAP_TH3[key]->GetNbinsY(), _LUT_MAP_TH3[key]->GetYaxis()->FindBin(yval)));\n    int binz = std::max(1, std::min(_LUT_MAP_TH3[key]->GetNbinsZ(), _LUT_MAP_TH3[key]->GetZaxis()->FindBin(zval)));\n    return _LUT_MAP_TH3[key]->GetBinContent(binx, biny);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH3Lookup\" << std::endl;\n    if( _LUT_MAP_TH3.find( key ) != _LUT_MAP_TH3.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH3 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X, typename Y, typename Z>\ndouble LUT::TH3LookupErr(std::string key, X xval, Y yval, Z zval){\n  try {\n    int binx = std::max(1, std::min(_LUT_MAP_TH3[key]->GetNbinsX(), _LUT_MAP_TH3[key]->GetXaxis()->FindBin(xval)));\n    int biny = std::max(1, std::min(_LUT_MAP_TH3[key]->GetNbinsY(), _LUT_MAP_TH3[key]->GetYaxis()->FindBin(yval)));\n    int binz = std::max(1, std::min(_LUT_MAP_TH3[key]->GetNbinsZ(), _LUT_MAP_TH3[key]->GetZaxis()->FindBin(zval)));\n    return _LUT_MAP_TH3[key]->GetBinError(binx, biny);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH3LookupErr\" << std::endl;\n    if( _LUT_MAP_TH3.find( key ) != _LUT_MAP_TH3.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH3 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X, typename Y, typename Z>\ndouble LUT::TH3LookupFlow(std::string key, X xval, Y yval, Z zval){\n  try {\n    int binx = std::max(0, std::min(_LUT_MAP_TH3[key]->GetNbinsX() + 1, _LUT_MAP_TH3[key]->GetXaxis()->FindBin(xval)));\n    int biny = std::max(0, std::min(_LUT_MAP_TH3[key]->GetNbinsY() + 1, _LUT_MAP_TH3[key]->GetYaxis()->FindBin(yval)));\n    int binz = std::max(0, std::min(_LUT_MAP_TH3[key]->GetNbinsZ() + 1, _LUT_MAP_TH3[key]->GetZaxis()->FindBin(zval)));\n    return _LUT_MAP_TH3[key]->GetBinContent(binx, biny);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH3Lookup\" << std::endl;\n    if( _LUT_MAP_TH3.find( key ) != _LUT_MAP_TH3.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH3 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\ntemplate<typename X, typename Y, typename Z>\ndouble LUT::TH3LookupErrFlow(std::string key, X xval, Y yval, Z zval){\n  try {\n    int binx = std::max(0, std::min(_LUT_MAP_TH3[key]->GetNbinsX() + 1, _LUT_MAP_TH3[key]->GetXaxis()->FindBin(xval)));\n    int biny = std::max(0, std::min(_LUT_MAP_TH3[key]->GetNbinsY() + 1, _LUT_MAP_TH3[key]->GetYaxis()->FindBin(yval)));\n    int binz = std::max(0, std::min(_LUT_MAP_TH3[key]->GetNbinsZ() + 1, _LUT_MAP_TH3[key]->GetZaxis()->FindBin(zval)));\n    return _LUT_MAP_TH3[key]->GetBinError(binx, biny);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Caught exception in LUT::TH3LookupErr\" << std::endl;\n    if( _LUT_MAP_TH3.find( key ) != _LUT_MAP_TH3.end() ){ \n      std::cout << \"Key \\\"\" << key << \"\\\" not found in the TH3 LUT\" << std::endl;\n    }\n    std::cout << \"\\nCaught exception: \" << e.what() << std::endl;\n    throw;\n  }\n}\n\nclass LUTManager {\n  //LookUp Table Manager\npublic:\n  LUTManager() {origin = new LUT(); lut_vector = std::make_shared< std::vector<LUT*> >();}\n  ~LUTManager() {}\n  void Add(std::map< std::string, std::vector<std::string> > idmap, bool verbose = false);\n  void Finalize(int nThreads);\nstd::shared_ptr< std::vector<LUT*> > GetLUTVector();\n\nprivate:\n  std::shared_ptr< std::vector<LUT*> > lut_vector; // = std::make_shared< std::vector<LUT*> >();\n  LUT *origin;\n};\nvoid LUTManager::Add(std::map< std::string, std::vector<std::string> > idmap, bool verbose) {\n  for(std::map< std::string, std::vector<std::string> >::iterator id_iter = idmap.begin(); id_iter != idmap.end(); ++id_iter){\n    // std::cout << \"Key: \" << id_iter->first << std::endl;\n    // std::cout << \"Values: \";\n    std::vector<std::string> vec_values = id_iter->second;\n    // for(std::vector<std::string>::iterator vector_iter = id_iter->second.begin(); vector_iter != id_iter->second.end(); ++vector_iter){\n    //   std::cout << *vector_iter;\n    // }\n    // std::cout << std::endl;\n    //Load each map into the origin LUT, from which all others will be copied in the finalize method\n    if(vec_values.size() > 1){\n      if(verbose)\n\tstd::cout << vec_values[0] << \" \" << vec_values[1] << std::endl;\n      origin->Add(vec_values[0], vec_values[1], id_iter->first);\n    }\n  }\n  std::cout << \"Finalizing\" << std::endl;\n}\nvoid LUTManager::Finalize(int nThreads) {\n  for(int n_iter = 0; n_iter < nThreads; ++n_iter){\n    LUT *temp(origin);\n    lut_vector->push_back(temp);\n  }\n}\nstd::shared_ptr< std::vector<LUT*> > LUTManager::GetLUTVector(){\n  return lut_vector;\n}\n\nclass baseLUT {\n  //LookUp Table\npublic:\n  baseLUT() { _LUT_TH1 = 0; _LUT_TH2 = 0; _LUT_TH3 = 0; }\n  baseLUT(std::string file, std::string path);\n  ~baseLUT() {}\n  double TH2Lookup(double xval, double yval, bool flow = false);\n  double TH2LookupErr(double xval, double yval, bool flow = false);\n\nprivate:\n  //unique uuid for multiple instances to be created in multithreading, will be prepended to histogram memory names to avoid name-clashes, i.e. may be _rdfslot\n  int uuid = 0; \n  TH1 *_LUT_TH1;\n  TH2 *_LUT_TH2;\n  TH3 *_LUT_TH3;\n  // std::map<std::string, TH*> _LUT_MAP;\n  \n};\nbaseLUT::baseLUT(std::string file, std::string path) {\n  TUUID uuid = TUUID();\n  TFile *f = TFile::Open(file.c_str(), \"read\");\n  if(f) {\n    if(f->IsOpen()){\n      auto temp = f->Get(path.c_str());\n      if(temp){\n\tBool_t isTH1 = (std::strncmp(temp->ClassName(), \"TH1\", 3) == 0);\n\tBool_t isTH2 = (std::strncmp(temp->ClassName(), \"TH2\", 3) == 0);\n\tBool_t isTH3 = (std::strncmp(temp->ClassName(), \"TH3\", 3) == 0);\n\tstd::string name = static_cast<std::string>(temp->GetName()) + \"___\" + uuid.AsString();\n\tif( isTH1 ) { \n\t  _LUT_TH1 = static_cast<TH1*>(temp->Clone(name.c_str()));\n\t  _LUT_TH1->SetDirectory(0);\n\t}\n\telse if( isTH2 ) { \n\t  _LUT_TH2 = static_cast<TH2*>(temp->Clone(name.c_str())); \n\t  _LUT_TH2->SetDirectory(0);\n\t    }\n\telse if( isTH3 ) { \n\t  _LUT_TH3 = static_cast<TH3*>(temp->Clone(name.c_str())); \n\t  _LUT_TH3->SetDirectory(0);\n\t}\n\telse { throw std::runtime_error( \"Unhandled LookUpTable class \" + static_cast<std::string>(temp->ClassName())); }\n\tf->Close();\n      }\n      else {\n\tf->Close();\n\tthrow std::runtime_error( \"Failed to instantiate valid LUT for path \" + path + \" in file \" + file );\n      }\n    }\n    else {\n      throw std::runtime_error( \"Failed to open file: \" + file );\n    }\n  }\n  else {\n      throw std::runtime_error( \"LookUpTable got a null pointer opening up the file: \" + file );\n  }\n      \n}\ndouble baseLUT::TH2Lookup(double xval, double yval, bool flow){\n  int binx = std::max(1, std::min(_LUT_TH2->GetNbinsX(), _LUT_TH2->GetXaxis()->FindBin(xval)));\n  int biny = std::max(1, std::min(_LUT_TH2->GetNbinsY(), _LUT_TH2->GetYaxis()->FindBin(yval)));\n  return _LUT_TH2->GetBinContent(binx, biny);\n}\ndouble baseLUT::TH2LookupErr(double xval, double yval, bool flow){\n  int binx = std::max(1, std::min(_LUT_TH2->GetNbinsX(), _LUT_TH2->GetXaxis()->FindBin(xval)));\n  int biny = std::max(1, std::min(_LUT_TH2->GetNbinsY(), _LUT_TH2->GetYaxis()->FindBin(yval)));\n  return _LUT_TH2->GetBinError(binx, biny);\n}\n  \n\nclass TH2Lookup {\npublic:\n\n  TH2Lookup() {lookupMap_.clear();}\n  TH2Lookup(std::string file, std::string slot=\"0\", bool debug=false);\n  TH2Lookup(std::string file, std::vector<std::string> histos, std::string slot);\n  ~TH2Lookup() {}\n\n  //void setJets(int nJet, int *jetHadronFlavour, float *jetPt, float *jetEta);\n\n  float getLookup(std::string key, float x_val, float y_val, bool debug=false);\n  float getLookupErr(std::string key, float x_val, float y_val, bool debug=false);\n  RVec_f getJetEfficiencySimple(ROOT::VecOps::RVec<int>* jets_flav, ROOT::VecOps::RVec<float>* jets_pt, ROOT::VecOps::RVec<float>* jets_eta);\n  RVec_f getJetEfficiency(std::string category, std::string tagger_WP, RVec_i* jets_flav, RVec_f* jets_pt, RVec_f* jets_eta);\n  double getEventYieldRatio(std::string sample, std::string variation, int nJet, double HT, bool debug=false);\n  double getEventYieldRatio(std::string key, int nJet, double HT, bool debug=false);\n  //const std::vector<float> & run();\n\nprivate:\n  std::map<std::string, TH2*> lookupMap_;\n  std::vector<std::string> validKeys_;\n  bool declaredFailure_;\n  // std::vector<float> ret_;\n  // int nJet_;\n  // float *Jet_eta_, *Jet_pt_;\n  // int *Jet_flav_;\n};\n\nTH2Lookup::TH2Lookup(std::string file, std::string slot, bool debug) {\n  lookupMap_.clear();\n  validKeys_.clear();\n  TFile *f = TFile::Open(file.c_str(),\"read\");\n  if(!f) {\n    std::cout << \"WARNING! File \" << file << \" cannot be opened.\" << std::endl;\n    declaredFailure_ = true;\n  }\n  for(const auto&& obj: *(f->GetListOfKeys())){\n    std::string key = obj->GetName();\n    std::string clone_key = \"TH2LU_\" + slot + \"_\" + key;\n    //for(int i=0; i<(int)histos.size();++i) {\n    lookupMap_[obj->GetName()] = (TH2*)(f->Get(key.c_str())->Clone(clone_key.c_str()));\n    lookupMap_[obj->GetName()]->SetDirectory(0);\n    if(debug){std::cout << obj->GetName() << \"     \";}\n  }\n  f->Close();\n}\n\nTH2Lookup::TH2Lookup(std::string file, std::vector<std::string> histos, std::string slot) {\n  lookupMap_.clear();\n  validKeys_.clear();\n  TFile *f = TFile::Open(file.c_str(),\"read\");\n  if(!f) {\n    std::cout << \"WARNING! File \" << file << \" cannot be opened. Skipping this efficiency\" << std::endl;\n  }\n\n  for(int i=0; i<(int)histos.size();++i) {\n    lookupMap_[histos[i]] = (TH2*)(f->Get(histos[i].c_str()))->Clone((\"TH2LU_\"+slot+\"_\"+histos[i]).c_str());\n    lookupMap_[histos[i]]->SetDirectory(0);\n    if(!lookupMap_[histos[i]]) {\n      std::cout << \"ERROR! Histogram \" << histos[i] << \" not in file \" << file << \". Not considering this lookup. \" << std::endl;\n    } else {\n      validKeys_.push_back(histos[i]);\n      std::cout << \"Loading histogram \" << histos[i] << \" from file \" << file << \"... \" << std::endl;\n    }\n  }\n  f->Close();\n}\n\n/*void TH2Lookup::setJets(int nJet, int *jetFlav, float *lepPt, float *lepEta) {\n  nJet_ = nJet; Jet_flav_ = jetFlav; Jet_pt_ = lepPt; Jet_eta_ = lepEta;\n  }*/\n\nfloat TH2Lookup::getLookup(std::string key, float x_val, float y_val, bool debug) {\n  if(debug){std::cout << \"TH2Lookup::getLookup invoked \" << std::endl;}\n  if ( lookupMap_.find(key) == lookupMap_.end() ) {\n    // not found ... not sure how intensive this lookup is, but we need to guard against bad keys\n    if(debug){std::cout << \"Failed to find key\" << std::endl;}\n    double fail = -9999.9;\n    return fail;\n  } else {\n    //found\n    if(debug){std::cout << \"Found key \" << key << std::endl;}\n    int binx = std::max(1, std::min(lookupMap_[key]->GetNbinsX(), lookupMap_[key]->GetXaxis()->FindBin(x_val)));\n    int biny = std::max(1, std::min(lookupMap_[key]->GetNbinsY(), lookupMap_[key]->GetYaxis()->FindBin(y_val)));\n    return lookupMap_[key]->GetBinContent(binx,biny);\n  }\n}\n\nfloat TH2Lookup::getLookupErr(std::string key, float x_val, float y_val, bool debug) {\n  int binx = std::max(1, std::min(lookupMap_[key]->GetNbinsX(), lookupMap_[key]->GetXaxis()->FindBin(x_val)));\n  int biny = std::max(1, std::min(lookupMap_[key]->GetNbinsY(), lookupMap_[key]->GetYaxis()->FindBin(y_val)));\n  return lookupMap_[key]->GetBinError(binx,biny);\n}\n\nRVec_f TH2Lookup::getJetEfficiency(std::string category, std::string tagger_wp, RVec_i* jets_flav, RVec_f* jets_pt, RVec_f* jets_eta){\n  //RVec_str keys;\n  RVec_f eff;\n  std::string key = \"\";\n  \n  //this only works with boost library...\n  /*for(auto iter = boost::make_zip_iterator(std::make_tuple(jets_flav->cbegin(), jets_pt->cbegin(), jets_eta->cbegin())),\n\tiEnd = boost::make_zip_iterator(std::make_tuple(jets_flav->cend(), jets_pt->cend(), jets_eta->cend()));\n      iter != iEnd; ++i){//do stuff}*/\n  for(int i = 0; i < jets_flav->size(); ++i){\n    if(jets_flav->at(i) == 5){\n      key = category + \"_bjets_\" + tagger_wp;\n    } else if(jets_flav->at(i) == 4){\n      key = category + \"_cjets_\" + tagger_wp;\n    } else {\n      key = category + \"_udsgjets_\" + tagger_wp;\n    }\n    eff.push_back(getLookup(key, jets_pt->at(i), fabs(jets_eta->at(i))));\n  }\n  return eff;\n}\n\ndouble TH2Lookup::getEventYieldRatio(std::string sample, std::string variation, int nJet, double HT, bool debug){\n  //Latest version uses keys of form \"Aggregate__nom\", so sample = \"Aggregate_\" and variation = \"_nom\"\n  //For pseudo-1D lookups, this uses \"<name>_1D<DIM>\" such as \"tttt_1DX\" -> key = \"tttt_1DY_nom\" for example\n  double yield = 1.0;\n  std::string key = \"\";\n  key = sample + variation;\n  if(debug){std::cout << \"getEventYield key: \" << key << std::endl;}\n  yield = getLookup(key, HT, nJet, debug);\n  return yield;\n}\n\ndouble TH2Lookup::getEventYieldRatio(std::string key, int nJet, double HT, bool debug){\n  //Latest version uses keys of form \"Aggregate__nom\", so sample = \"Aggregate_\" and variation = \"_nom\"\n  //For pseudo-1D lookups, this uses \"<name>_1D<DIM>\" such as \"tttt_1DX\" -> key = \"tttt_1DY_nom\" for example\n  double yield = 1.0;\n  if(debug){std::cout << \"getEventYield key: \" << key << std::endl;}\n  yield = getLookup(key, HT, nJet, debug);\n  return yield;\n}\n\n/*const std::vector<float> & TH2Lookup::run() {\n  ret_.clear();\n  for (int iJ = 0, nJ = nJet_; iL < nJ; ++iJ) {\n    ret_.push_back(getEff((Jet_flav_)[iJ], (Jet_pt_)[iJ], (Jet_eta_)[iJ]));\n  }\n  return ret_;\n  }*/\n\n/*RVec_i generateIndex(RVec_i *v){\n  RVec_i i(v->size());\n  std::iota(i.begin(), i.end(), 0);\n  return i;\n  }*/\n\n//namespace FourTop Analysis\nnamespace FTA{\n  //Future need: function for reweighting cross-section with multiple samples in a phase space, i.e. ttbar with nGenJet >= 7,\n  //GenHT >= 500 for ttJets, TTTo2L2Nu, TTTo2L2Nu_nJet7HT500. Makes sense to weight the events in this phase space with \n  //XS_i =  proc_XS * N_i/Sum(N_i) * 1/sumWeights_i, where N_i is number of events from each sample in the phase space,\n  //sumWeights_i is the sum of event weights for that sample in that phase space, etc. So summing over all events and over all samples\n  //gives proc_XS * SUM[ N_i/Sum(N_i) * sumWeights_i/sumWeights_i] = proc_XS * Sum[N_i/Sum(N_i)] = proc_XS\n\n  // std::map<std::string, int> datasetCode\n\n  // std::map<std::string, int> metaEventId(std::string dataset, std::string campaign){\n  //   //return a map of meta information for encoding the packedEventId efficiently. This contains info like datasetId, campaignId, ...\n  //   std::map<std::string, std::string> datasetCode;\n  //   datasetCode[\"/TTTT_TuneCP5_PSweights_13TeV-amcatnlo-pythia8/RunIIFall17NanoAODv5-PU2017_12Apr2018_Nano1June2019_102X_mc2017_realistic_v7-v1/NANOAODSIM\"] = 1;\n  //   datasetCode[\"\"] = 2;\n  //   datasetCode[\"/TTToSemiLepton_HT500Njet9_TuneCP5_PSweights_13TeV-powheg-pythia8/RunIIFall17NanoAODv5-PU2017_12Apr2018_Nano1June2019_102X_mc2017_realistic_v7-v1/NANOAODSIM\"] = 3;\n  //   datasetCode[\"\"] = 4;\n  //   datasetCode[\"\"] = 5;\n  //   datasetCode[\"\"] = 6;\n  //   datasetCode[\"\"] = 7;\n  //   datasetCode[\"\"] = 8;\n  //   datasetCode[\"\"] = 9;\n  //   datasetCode[\"\"] = 10;\n  //   datasetCode[\"\"] = 11;\n  //   datasetCode[\"\"] = 12;\n  //   datasetCode[\"\"] = 13;\n  //   datasetCode[\"\"] = 14;\n  //   datasetCode[\"\"] = 15;\n  //   datasetCode[\"\"] = 16;\n  //   datasetCode[\"\"] = 17;\n  //   datasetCode[\"\"] = 18;\n  //   datasetCode[\"\"] = 19;\n  //   datasetCode[\"\"] = 20;\n  //   datasetCode[\"\"] = 21;\n  //   datasetCode[\"\"] = 22;\n  //   datasetCode[\"\"] = 23;\n  //   datasetCode[\"\"] = 24;\n  //   datasetCode[\"\"] = 25;\n  //   datasetCode[\"\"] = 26;\n  //   datasetCode[\"\"] = 27;\n  //   datasetCode[\"\"] = 28;\n  //   datasetCode[\"\"] = 29;\n  //   datasetCode[\"\"] = 30;\n\n  //   std::map<std::string, int> campaignCode;\n  //   campaignCode[\"\"\n  //     //code to get the luminosity lookup from the main function...\n  //     retCode[\"luminosity\"] = std::to_string(unpackEventId(packedEventId, genWeight, luminosity, true));\n  //   } else {\n  //     retCode[\"luminosity\"] = \"This is probably a bad idea, KISS my friend! Drop the lumi and genWeight\";\n  //   }\n  //   return retCode;\n  // }\n  //Can't get what I want from this, so work from the python end. FFS, another day's effort wasted on buggy shit. Need to know the compression enumeration is ROOT.ROOT.(algo)\n  // const UInt_t barWidth = 60;\n  // ULong64_t processed = 0, totalEvents = 0;\n  // std::string progressBar;\n  // std::mutex barMutex;\n  // auto registerEvents = [](ULong64_t nIncrement) {totalEvents += nIncrement;};\n\n  // ROOT::RDF::RResultPtr<ULong64_t> AddProgressBar(ROOT::RDF::RNode df, int everyN=10000, int totalN=100000) {\n  //   registerEvents(totalN);\n  //   auto c = df.Count();\n  //   c.OnPartialResultSlot(everyN, [everyN] (unsigned int slot, ULong64_t &cnt){\n  // \tstd::lock_guard<std::mutex> l(barMutex);\n  //       processed += everyN; //everyN captured by value for this lambda\n  //       progressBar = \"[\";\n  //       for(UInt_t i = 0; i < static_cast<UInt_t>(static_cast<Float_t>(processed)/totalEvents*barWidth); ++i){\n  // \t  progressBar.push_back('|');\n  //       }\n  //       // escape the '\\' when defined in python string\n  // \tstd::cout << \"\\\\r\" << std::left << std::setw(barWidth) << progressBar << \"] \" << processed << \"/\" << totalEvents << std::flush;\n  //     });\n  //   return c;\n  // }\n\n  ROOT::RDF::RNode applyMETandPVFilters(ROOT::RDF::RNode df, std::string era, std::string legacy, std::string VFP=\"\", bool isData=true, bool verbose=false){\n    auto rdf = df;\n    //flags for MET filters\n    ROOT::Detail::RDF::ColumnNames_t flags = {};\n    // std::vector<ROOT::RDF::RInterface::ColumnNames_t> flags = {};\n    double minNDoF, maxAbsZ, maxRho;\n    std::vector<std::string> deprecated_flags = {\"Flag_BadChargedCandidateFilter\", \"Flag_eeBadScFilter\"};\n    if(legacy == \"non-UL\"){\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_goodVertices\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_globalSuperTightHalo2016Filter\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_HBHENoiseFilter\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_HBHENoiseIsoFilter\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_EcalDeadCellTriggerPrimitiveFilter\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_BadPFMuonFilter\");\n      if(                 era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_ecalBadCalibFilterV2\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") minNDoF = 4;\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") maxAbsZ = 24.0;\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") maxRho = 2;\n      \n    }\n    else if(legacy == \"UL\"){\n      std::cout << \"Recommendations were still under review for MET Filters on Ultra-Legacy datasets. Please check current recommendations. Check for differences in preVFP and postVFP\" << std::endl;\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_goodVertices\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_globalSuperTightHalo2016Filter\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_HBHENoiseFilter\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_HBHENoiseIsoFilter\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_EcalDeadCellTriggerPrimitiveFilter\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_BadPFMuonFilter\");\n      if(                 era == \"2017\" || era == \"2018\") flags.push_back(\"Flag_ecalBadCalibFilterV2\");\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") minNDoF = 4;\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") maxAbsZ = 24.0;\n      if(era == \"2016\" || era == \"2017\" || era == \"2018\") maxRho = 2;\n    }\n    auto checkFilter =   [](bool met_filter){return met_filter;};\n    auto lambdaMinNDoF = [minNDoF](float ndof){return ndof > minNDoF;};\n    auto lambdaMaxAbsZ = [maxAbsZ](float z){return abs(z) < maxAbsZ;};\n    auto lambdaMaxRho =  [maxRho](float x, float y){return sqrt(pow(x, 2) + pow(y, 2)) < maxRho;};\n    df = df\n      .Filter(lambdaMinNDoF, {\"PV_ndof\"}, \"PV minimum d.o.f.\")\n      .Filter(lambdaMaxAbsZ, {\"PV_z\"}, \"PV maximum |z|\")\n      .Filter(lambdaMaxRho, {\"PV_x\", \"PV_y\"}, \"PV maximum rho\");\n    for(int i = 0; i < flags.size(); ++i){\n      df = df.Filter(checkFilter, {flags.at(i)}, \"MET filter \" + flags.at(i));\n    }\n    return df;\n  }\n  std::map< std::string, std::vector<std::string> > GetCorrectorMap(std::string era, \n\t\t\t\t\t\t\t\t    std::string legacy, \n\t\t\t\t\t\t\t\t    std::string VFP=\"\",\n\t\t\t\t\t\t\t\t    std::string muon_top_path = \"\",\n\t\t\t\t\t\t\t\t    std::string muon_id = \"\",\n\t\t\t\t\t\t\t\t    std::string muon_iso = \"\",\n\t\t\t\t\t\t\t\t    std::string electron_top_path = \"\",\n\t\t\t\t\t\t\t\t    std::string electron_id = \"\",\n\t\t\t\t\t\t\t\t    std::string electron_eff = \"\",\n\t\t\t\t\t\t\t\t    bool verbose = false){\n    //python constructor:\n    //def __init__(self, muon_ID=None, muon_ISO=None, electron_ID=None, era=None, doMuonHLT=False, doElectronHLT_ZVtx=False, \n    //pre2018Run316361Lumi = 8.942, post2018Run316361Lumi = 50.785\n\n    //about paths... \n    //el_pre = \"{0:s}/src/FourTopNAOD/Kai/python/data/leptonSF/Electron/{1:s}/\".format(os.environ['CMSSW_BASE'], self.era)\n\n    std::string muon_path, electron_path;\n    if(era != \"2016\" && legacy != \"UL\"){\n      muon_path = muon_top_path + \"/\" + era + \"/\" + legacy + \"/\";\n      electron_path = electron_top_path + \"/\" + era + \"/\" + legacy + \"/\";\n    }\n    else{\n      if(!( VFP == \"postVFP\" || VFP == \"preVFP\")){\n\tstd::cout << \"WARNING: Invalid path due to VFP parameter not matching options for 2016 Ultra-Legacy production\" << std::endl;\n      }\n      muon_path = muon_top_path + \"/\" + era + \"/\" + legacy + \"/\" + VFP + \"/\";\n      electron_path = electron_top_path + \"/\" + era + \"/\" + legacy + \"/\" + VFP + \"/\";\n    }\n    \n    std::cout << \"Era: \" << era << \"\\nLegacy: \" << legacy <<  \"\\nPreVFP: \" << VFP << \"\\nMuon top path: \" << muon_top_path << \"\\nElectron top path: \" << electron_top_path << std::endl;\n\n    //mu_pre = \"{0:s}/src/FourTopNAOD/Kai/python/data/leptonSF/Muon/{1:s}/\".format(os.environ['CMSSW_BASE'], self.era)\n    //store the ID map per era, with a path being prepended to the filenames listed below at the end\n    std::map< std::string, std::vector<std::string> > electron_options_central;\n    std::map< std::string, std::vector<std::string> > electron_options_uncertainty;\n    std::map< std::string, std::vector<std::string> > muon_options_central;\n    std::map< std::string, std::vector<std::string> > muon_options_stat;\n    std::map< std::string, std::vector<std::string> > muon_options_syst;\n    if(legacy == \"UL\"){\n      std::cout << \"WARNING: In FTA:::GetIDMap, legacy = 'UL' was specified. Right now, this defaults to the non-UL/EOY processing maps\" << std::endl;\n      //https://twiki.cern.ch/twiki/bin/viewauth/CMS/EgammaUL2016To2018#SFs_for_Electrons_UL_2018\n      if(era == \"2016\"){\n\tstd::cout << \"WARNING: Ultra-Legacy era 2016 should be handled differently pre and postVFP... Note done yet\" << std::endl;\n      }\n    }\n    //Electron ID's\n    //Note on uncertainties: stored in the same maps and accessed by bin error, so just copy...\n    if(era == \"2016\"){\n      if(legacy == \"non-UL\"){\n\telectron_options_central[\"EFF_ptBelow20\"] =\t{\"EGM2D_BtoH_low_RecoSF_Legacy2016.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptBelow20\"] = {\"EGM2D_BtoH_low_RecoSF_Legacy2016.root\", \"EGamma_SF2D\", \"TH2LookupErr\"\"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"EFF_ptAbove20\"] =\t{\"EGM2D_BtoH_GT20GeV_RecoSF_Legacy2016.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptAboe20\"] =  {\"EGM2D_BtoH_GT20GeV_RecoSF_Legacy2016.root\", \"EGamma_SF2D\", \"TH2LookupErr\"\"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"LooseID\"]  =\t\t{\"2016LegacyReReco_ElectronLoose_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"LooseID\"]  =\t{\"2016LegacyReReco_ElectronLoose_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MediumID\"]  =\t\t{\"2016LegacyReReco_ElectronMedium_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MediumID\"]  =\t{\"2016LegacyReReco_ElectronMedium_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"TightID\"]  =\t\t{\"2016LegacyReReco_ElectronTight_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"TightID\"]  =\t{\"2016LegacyReReco_ElectronTight_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80iso\"]  =\t\t{\"2016LegacyReReco_ElectronMVA80_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80iso\"]  =\t{\"2016LegacyReReco_ElectronMVA80_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80noiso\"]  =\t{\"2016LegacyReReco_ElectronMVA80noiso_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80noiso\"]  =\t{\"2016LegacyReReco_ElectronMVA80noiso_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90iso\"]  =\t\t{\"2016LegacyReReco_ElectronMVA90_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90iso\"]  =\t{\"2016LegacyReReco_ElectronMVA90_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90noiso\"]  =\t{\"2016LegacyReReco_ElectronMVA90noiso_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90noiso\"]  =\t{\"2016LegacyReReco_ElectronMVA90noiso_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n      }\n      else if(legacy == \"UL\" && VFP == \"preVFP\"){\n\t//Failed to deduce axis --> eta on x-axis, pt on y-axis. \n\telectron_options_central[\"EFF_ptAbove20\"] =\t{\"egammaEffi_ptAbove20.txt_EGM2D_UL2016preVFP.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptAbove20\"] = {\"egammaEffi_ptAbove20.txt_EGM2D_UL2016preVFP.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"EFF_ptBelow20\"] =\t{\"egammaEffi_ptBelow20.txt_EGM2D_UL2016preVFP.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptBelow20\"] = {\"egammaEffi_ptBelow20.txt_EGM2D_UL2016preVFP.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Veto\"] =\t\t{\"egammaEffi.txt_Ele_Veto_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Veto\"] =\t\t{\"egammaEffi.txt_Ele_Veto_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Loose\"] =\t\t{\"egammaEffi.txt_Ele_Loose_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Loose\"] =\t\t{\"egammaEffi.txt_Ele_Loose_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Medium\"] =\t\t{\"egammaEffi.txt_Ele_Medium_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Medium\"] =\t{\"egammaEffi.txt_Ele_Medium_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Tight\"] =\t\t{\"egammaEffi.txt_Ele_Tight_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Tight\"] =\t\t{\"egammaEffi.txt_Ele_Tight_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80iso\"] =\t\t{\"egammaEffi.txt_Ele_wp80iso_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80iso\"] =\t{\"egammaEffi.txt_Ele_wp80iso_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80noiso\"] =\t{\"egammaEffi.txt_Ele_wp80noiso_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80noiso\"] =\t{\"egammaEffi.txt_Ele_wp80noiso_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90iso\"] =\t\t{\"egammaEffi.txt_Ele_wp90iso_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90iso\"] =\t{\"egammaEffi.txt_Ele_wp90iso_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90noiso\"] =\t{\"egammaEffi.txt_Ele_wp90noiso_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90noiso\"] =\t{\"egammaEffi.txt_Ele_wp90noiso_preVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\t\n      }\n      else if(legacy == \"UL\" && VFP == \"postVFP\"){\n\tstd::cout << \"WARNING: postVFP UL for 2016 is loading 2016 Legacy efficiencies, since postVFP UL versions haven't been made available as of writing.\";\n\tstd::cout << std::endl;\n\telectron_options_central[\"EFF_ptBelow20\"] =\t{\"../../non-UL/EGM2D_BtoH_low_RecoSF_Legacy2016.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"EFF_ptBelow20\"] =\t{\"../../non-UL/EGM2D_BtoH_GT20GeV_RecoSF_Legacy2016.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"EFF_ptAbove20\"] =\t{\"../../non-UL/EGM2D_BtoH_GT20GeV_RecoSF_Legacy2016.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptAboe20\"] =  {\"../../non-UL/EGM2D_BtoH_GT20GeV_RecoSF_Legacy2016.root\", \"EGamma_SF2D\", \"TH2LookupErr\"\"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Veto\"] =\t\t{\"egammaEffi.txt_Ele_Veto_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Veto\"] =\t\t{\"egammaEffi.txt_Ele_Veto_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Loose\"] =\t\t{\"egammaEffi.txt_Ele_Loose_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Loose\"] =\t\t{\"egammaEffi.txt_Ele_Loose_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Medium\"] =\t\t{\"egammaEffi.txt_Ele_Medium_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Medium\"] =\t{\"egammaEffi.txt_Ele_Medium_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Tight\"] =\t\t{\"egammaEffi.txt_Ele_Tight_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Tight\"] =\t\t{\"egammaEffi.txt_Ele_Tight_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80iso\"] =\t\t{\"egammaEffi.txt_Ele_wp80iso_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80iso\"] =\t{\"egammaEffi.txt_Ele_wp80iso_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80noiso\"] =\t{\"egammaEffi.txt_Ele_wp80noiso_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80noiso\"] =\t{\"egammaEffi.txt_Ele_wp80noiso_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90iso\"] =\t\t{\"egammaEffi.txt_Ele_wp90iso_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90iso\"] =\t{\"egammaEffi.txt_Ele_wp90iso_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90noiso\"] =\t{\"egammaEffi.txt_Ele_wp90noiso_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90noiso\"] =\t{\"egammaEffi.txt_Ele_wp90noiso_postVFP_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n      }\n    }\n    else if(era == \"2017\"){\n      if(legacy == \"non-UL\"){\n\tstd::cout << \"WARNING: for 2017 non-UL, Efficiencies are both from the non-low Et measurements, in case this has changed...\" << std::endl;\n\telectron_options_central[\"EFF_ptBelow20\"] =\t{\"egammaEffi.txt_EGM2D_runBCDEF_passingRECO_lowEt.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptBelow20\"] = {\"egammaEffi.txt_EGM2D_runBCDEF_passingRECO_lowEt.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"EFF_ptAbove20\"] =\t{\"egammaEffi.txt_EGM2D_runBCDEF_passingRECO.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptAbove20\"] = {\"egammaEffi.txt_EGM2D_runBCDEF_passingRECO.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Veto\"] =\t\t{\"2017_ElectronWPVeto_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Veto\"] =\t\t{\"2017_ElectronWPVeto_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Loose\"] =\t\t{\"2017_ElectronLoose.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Loose\"] =\t\t{\"2017_ElectronLoose.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Medium\"] =\t\t{\"2017_ElectronMedium.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Medium\"] =\t{\"2017_ElectronMedium.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Tight\"] =\t\t{\"2017_ElectronTight.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Tight\"] =\t\t{\"2017_ElectronTight.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80noiso\"] =\t{\"2017_ElectronMVA80noiso.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80noiso\"] =\t{\"2017_ElectronMVA80noiso.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80iso\"] =\t\t{\"2017_ElectronMVA80.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80iso\"] =\t{\"2017_ElectronMVA80.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90noiso\"] =\t{\"2017_ElectronMVA90noiso.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90noiso\"] =\t{\"2017_ElectronMVA90noiso.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90iso\"] =\t\t{\"2017_ElectronMVA90.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90iso\"] =\t{\"2017_ElectronMVA90.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n      }\n      else if(legacy == \"UL\"){\n\t//Failed to deduce axis--> not checked, assume the same... more waste of my precious goddamned fucking time\n\telectron_options_central[\"EFF_ptBelow20\"] =\t{\"egammaEffi_ptBelow20.txt_EGM2D_UL2017.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptBelow20\"] = {\"egammaEffi_ptBelow20.txt_EGM2D_UL2017.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"EFF_ptAbove20\"] =\t{\"egammaEffi_ptAbove20.txt_EGM2D_UL2017.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptAbove20\"] = {\"egammaEffi_ptAbove20.txt_EGM2D_UL2017.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Veto\"] =\t\t{\"egammaEffi.txt_EGM2D_Veto_UL17.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Veto\"] =\t\t{\"egammaEffi.txt_EGM2D_Veto_UL17.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Loose\"] =\t\t{\"egammaEffi.txt_EGM2D_Loose_UL17.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Loose\"] =\t\t{\"egammaEffi.txt_EGM2D_Loose_UL17.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Medium\"] =\t\t{\"egammaEffi.txt_EGM2D_Medium_UL17.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Medium\"] =\t{\"egammaEffi.txt_EGM2D_Medium_UL17.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Tight\"] =\t\t{\"egammaEffi.txt_EGM2D_Tight_UL17.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Tight\"] =\t\t{\"egammaEffi.txt_EGM2D_Tight_UL17.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80iso\"] =\t\t{\"egammaEffi.txt_EGM2D_MVA80iso_UL17.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80iso\"] =\t{\"egammaEffi.txt_EGM2D_MVA80iso_UL17.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80noiso\"] =\t{\"egammaEffi.txt_EGM2D_MVA80noIso_UL17.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80noiso\"] =\t{\"egammaEffi.txt_EGM2D_MVA80noIso_UL17.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90iso\"] =\t\t{\"egammaEffi.txt_EGM2D_MVA90iso_UL17.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90iso\"] =\t{\"egammaEffi.txt_EGM2D_MVA90iso_UL17.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90noiso\"] =\t{\"egammaEffi.txt_EGM2D_MVA90noIso_UL17.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90noiso\"] =\t{\"egammaEffi.txt_EGM2D_MVA90noIso_UL17.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n      }\n    }\n    else if(era == \"2018\"){\n      if(legacy == \"non-UL\"){\n\telectron_options_central[\"EFF_ptBelow20\"] =\t{\"egammaEffi.txt_EGM2D_updatedAll.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptBelow20\"] = {\"egammaEffi.txt_EGM2D_updatedAll.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"EFF_ptAbove20\"] =\t{\"egammaEffi.txt_EGM2D_updatedAll.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptAbove20\"] = {\"egammaEffi.txt_EGM2D_updatedAll.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Veto\"] =\t\t{\"2018_ElectronWPVeto_Fall17V2.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Veto\"] =\t\t{\"2018_ElectronWPVeto_Fall17V2.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Loose\"] =\t\t{\"2018_ElectronLoose.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Loose\"] =\t\t{\"2018_ElectronLoose.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Medium\"] =\t\t{\"2018_ElectronMedium.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Medium\"] =\t{\"2018_ElectronMedium.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Tight\"] =\t\t{\"2018_ElectronTight.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Tight\"] =\t\t{\"2018_ElectronTight.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80noiso\"] =\t{\"2018_ElectronMVA80noiso.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80noiso\"] =\t{\"2018_ElectronMVA80noiso.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80iso\"] =\t\t{\"2018_ElectronMVA80.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80iso\"] =\t{\"2018_ElectronMVA80.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90noiso\"] =\t{\"2018_ElectronMVA90noiso.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90noiso\"] =\t{\"2018_ElectronMVA90noiso.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90iso\"] =\t\t{\"2018_ElectronMVA90.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90iso\"] =\t{\"2018_ElectronMVA90.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n      }\n      else if(legacy == \"UL\"){\n\t//Failed to deduce axis\n\telectron_options_central[\"EFF_ptBelow20\"] =\t{\"egammaEffi_ptBelow20.txt_EGM2D_UL2018.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptBelow20\"] = {\"egammaEffi_ptBelow20.txt_EGM2D_UL2018.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"EFF_ptAbove20\"] =\t{\"egammaEffi_ptAbove20.txt_EGM2D_UL2018.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"EFF_ptAbove20\"] = {\"egammaEffi_ptAbove20.txt_EGM2D_UL2018.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Veto\"] =\t\t{\"egammaEffi.txt_Ele_Veto_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Veto\"] =\t\t{\"egammaEffi.txt_Ele_Veto_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Loose\"] =\t\t{\"egammaEffi.txt_Ele_Loose_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Loose\"] =\t\t{\"egammaEffi.txt_Ele_Loose_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Medium\"] =\t\t{\"egammaEffi.txt_Ele_Medium_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Medium\"] =\t{\"egammaEffi.txt_Ele_Medium_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"Tight\"] =\t\t{\"egammaEffi.txt_Ele_Tight_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"Tight\"] =\t\t{\"egammaEffi.txt_Ele_Tight_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80iso\"] =\t\t{\"egammaEffi.txt_Ele_wp80iso_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80iso\"] =\t{\"egammaEffi.txt_Ele_wp80iso_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA80noiso\"] =\t{\"egammaEffi.txt_Ele_wp80noiso_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA80noiso\"] =\t{\"egammaEffi.txt_Ele_wp80noiso_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90iso\"] =\t\t{\"egammaEffi.txt_Ele_wp90iso_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90iso\"] =\t{\"egammaEffi.txt_Ele_wp90iso_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_central[\"MVA90noiso\"] =\t{\"egammaEffi.txt_Ele_wp90noiso_EGM2D.root\", \"EGamma_SF2D\", \"TH2Lookup\", \"Electron_eta\", \"Electron_pt\"};\n\telectron_options_uncertainty[\"MVA90noiso\"] =\t{\"egammaEffi.txt_Ele_wp90noiso_EGM2D.root\", \"EGamma_SF2D\", \"TH2LookupErr\", \"Electron_eta\", \"Electron_pt\"};\n      }\n    }\n    //Muon SFs //Mostly the errors are stored in separate histograms inside two files, 1 for ISO and 1 for ID \n    //So for 2017 and 2018 non-UL: BinContent from unique histogram ...ratio, BinError from unique histogram ...ratio_stat, ...ratio_syst\n    //for 2016, central is BinContent and syst error is BinError on a single central histogram\n    // \"TRG_SL\": {\"Mu_Trg.root\", \"IsoMu24_OR_IsoTkMu24_PtEtaBins/pt_abseta_ratio\",\n    //            \"STAT\": \"Mu_Trg.root\", \"IsoMu24_OR_IsoTkMu24_PtEtaBins/pt_abseta_ratio\"},\n    // \"TRG_SL50\": {\"Mu_Trg.root\", \"Mu50_OR_TkMu50_PtEtaBins/pt_abseta_ratio\",\n    //              \"STAT\": \"Mu_Trg.root\", \"Mu50_OR_TkMu50_PtEtaBins/pt_abseta_ratio\"},\n    if(era == \"2016\"){\n      if(legacy == \"non-UL\"){\n\tmuon_options_central[\"LooseID\"] =                {\"Mu_ID.root\", \"MC_NUM_LooseID_DEN_genTracks_PAR_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseID\"] =                   {\"Mu_ID.root\", \"MC_NUM_LooseID_DEN_genTracks_PAR_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"MediumID2016\"] =           {\"Mu_ID.root\", \"MC_NUM_MediumID2016_DEN_genTracks_PAR_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"MediumID2016\"] =              {\"Mu_ID.root\", \"MC_NUM_MediumID2016_DEN_genTracks_PAR_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"MediumID\"] =               {\"Mu_ID.root\", \"MC_NUM_MediumID_DEN_genTracks_PAR_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"MediumID\"] =                  {\"Mu_ID.root\", \"MC_NUM_MediumID_DEN_genTracks_PAR_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightID\"] =                {\"Mu_ID.root\", \"MC_NUM_TightID_DEN_genTracks_PAR_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightID\"] =                   {\"Mu_ID.root\", \"MC_NUM_TightID_DEN_genTracks_PAR_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"HighPtID\"] =               {\"Mu_ID.root\", \"MC_NUM_HighPtID_DEN_genTracks_PAR_newpt_eta/pair_ne_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"HighPtID\"] =                  {\"Mu_ID.root\", \"MC_NUM_HighPtID_DEN_genTracks_PAR_newpt_eta/pair_ne_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\n\tmuon_options_central[\"LooseRelIso_LooseID\"] =    {\"Mu_Iso.root\", \"LooseISO_LooseID_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_LooseID\"] =       {\"Mu_Iso.root\", \"LooseISO_LooseID_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelIso_MediumID\"] =   {\"Mu_Iso.root\", \"LooseISO_MediumID_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_MediumID\"] =      {\"Mu_Iso.root\", \"LooseISO_MediumID_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelIso_TightID\"] =    {\"Mu_Iso.root\", \"LooseISO_TightID_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_TightID\"] =       {\"Mu_Iso.root\", \"LooseISO_TightID_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightRelIso_MediumID\"] =   {\"Mu_Iso.root\", \"TightISO_MediumID_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelIso_MediumID\"] =      {\"Mu_Iso.root\", \"TightISO_MediumID_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightRelIso_TightID\"] =    {\"Mu_Iso.root\", \"TightISO_TightID_pt_eta/pt_abseta_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelIso_TightID\"] =       {\"Mu_Iso.root\", \"TightISO_TightID_pt_eta/pt_abseta_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelTkIso_HighPtID\"] = {\"Mu_Iso.root\", \"tkLooseISO_highptID_newpt_eta/pair_ne_ratio\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelTkIso_HighPtID\"] =    {\"Mu_Iso.root\", \"tkLooseISO_highptID_newpt_eta/pair_ne_ratio\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n      }\n      else if(legacy == \"UL\" && VFP == \"preVFP\"){\n\tmuon_options_central[\"HighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"HighPtID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"HighPtID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"MediumID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"MediumPromptID\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"SoftID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"SoftID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"SoftID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\t\n\t\n\tmuon_options_central[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelTkIso_HighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_HIPM_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n      }\n      else if(legacy == \"UL\" && VFP == \"postVFP\"){\n\tmuon_options_central[\"HighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"HighPtID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"HighPtID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"MediumID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"MediumPromptID\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"SoftID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"SoftID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"SoftID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\n\tmuon_options_central[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelTkIso_HighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2016_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n      }\n    }\n    else if(era == \"2017\"){\n      if(legacy == \"non-UL\"){\n\t// muon_options_central[\"TRG_SL\"] = {\"EfficienciesAndSF_RunBtoF_Nov17Nov2017.root\", \"IsoMu27_PtEtaBins/pt_abseta_ratio\", \"TH2Lookup\", };\n\t// muon_options_stat[] = { \"EfficienciesAndSF_RunBtoF_Nov17Nov2017.root\", \"IsoMu27_PtEtaBins/pt_abseta_ratio\", \"TH2Lookup\", };\n\n\tmuon_options_central[\"LooseID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_LooseID_DEN_genTracks_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_LooseID_DEN_genTracks_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_LooseID_DEN_genTracks_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_TightID_DEN_genTracks_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_TightID_DEN_genTracks_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_TightID_DEN_genTracks_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"MediumID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_MediumID_DEN_genTracks_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"MediumID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_MediumID_DEN_genTracks_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"MediumID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_MediumID_DEN_genTracks_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"HighPtID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_HighPtID_DEN_genTracks_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"HighPtID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_HighPtID_DEN_genTracks_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"HighPtID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_HighPtID_DEN_genTracks_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_TrkHighPtID_DEN_genTracks_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_TrkHighPtID_DEN_genTracks_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_TrkHighPtID_DEN_genTracks_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"SoftID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_SoftID_DEN_genTracks_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"SoftID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_SoftID_DEN_genTracks_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"SoftID\"] =\t\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_SoftID_DEN_genTracks_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"MediumPromptID\"] =\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_MediumPromptID_DEN_genTracks_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"MediumPromptID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_MediumPromptID_DEN_genTracks_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"MediumPromptID\"] =\t\t{\"RunBCDEF_SF_ID_syst.root\", \"NUM_MediumPromptID_DEN_genTracks_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\t\n\t\n\tmuon_options_central[\"TightRelIso_MediumID\"] =\t\t        {\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelIso_DEN_MediumID_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightRelIso_MediumID\"] =\t\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelIso_DEN_MediumID_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelIso_MediumID\"] =\t\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelIso_DEN_MediumID_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelIso_MediumID\"] =\t\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_MediumID_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelIso_MediumID\"] =\t\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_MediumID_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_MediumID\"] =\t\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_MediumID_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelIso_LooseID\"] =\t\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_LooseID_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelIso_LooseID\"] =\t\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_LooseID_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_LooseID\"] =\t\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_LooseID_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightRelTkIso_TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightRelTkIso_TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelTkIso_TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelTkIso_TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelTkIso_TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelTkIso_TrkHighPtID\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightRelTkIso_HighPtIDandIPCut\"] =\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"RunBCDEF_SF_ISO_syst.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n      }\n      else if(legacy == \"UL\"){\n\tmuon_options_central[\"HighPtID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"HighPtID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"HighPtID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"MediumID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"MediumID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"MediumID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"MediumPromptID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"MediumPromptID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"MediumPromptID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"SoftID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"SoftID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"SoftID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightID\"] =\t\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TrkHighPtID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TrkHighPtID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TrkHighPtID\"] =\t\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\t\n\tmuon_options_central[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelTkIso_HighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2017_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n      }\n    }\n    else if(era == \"2018\"){\n      if(legacy == \"non-UL\"){\n\t// muon_options_central[\"TRG_SL_preRun316361\"] =\t {\"EfficienciesAndSF_2018Data_BeforeMuonHLTUpdate.root\", \"IsoMu24_PtEtaBins/pt_abseta_ratio\", \"TH2Lookup\", };\n\t// muon_options_stat[\"TRG_SL_preRun316361\"] =\t\t {\"EfficienciesAndSF_2018Data_BeforeMuonHLTUpdate.root\", \"IsoMu24_PtEtaBins/pt_abseta_ratio\", \"TH2Lookup\", };\n\t// muon_options_central[\"TRG_SL\"] =\t\t\t {\"EfficienciesAndSF_2018Data_AfterMuonHLTUpdate.root\", \"IsoMu24_PtEtaBins/pt_abseta_ratio\", \"TH2Lookup\", };\n\t// muon_options_stat[\"TRG_SL_preRun316361\"] =\t\t {\"EfficienciesAndSF_2018Data_AfterMuonHLTUpdate.root\", \"IsoMu24_PtEtaBins/pt_abseta_ratio\", \"TH2Lookup\", };\n\n\tmuon_options_central[\"LooseID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_TightID_DEN_TrackerMuons_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_TightID_DEN_TrackerMuons_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_TightID_DEN_TrackerMuons_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"MediumID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"MediumID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"MediumID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"HighPtID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"HighPtID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"HighPtID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TrkHighPtID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TrkHighPtID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TrkHighPtID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"SoftID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"SoftID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"SoftID\"] =\t\t\t{\"RunABCD_SF_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"MediumPromptID\"] =\t{\"RunABCD_SF_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"MediumPromptID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"MediumPromptID\"] =\t\t{\"RunABCD_SF_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\t\n\n\tmuon_options_central[\"TightRelIso_MediumID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightRelIso_MediumID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelIso_MediumID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelIso_MediumID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelIso_MediumID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_MediumID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelIso_LooseID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelIso_LooseID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_LooseID\"] =\t\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightRelTkIso_TrkHighPtID\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightRelTkIso_TrkHighPtID\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelTkIso_TrkHighPtID\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelTkIso_TrkHighPtID\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelTkIso_TrkHighPtID\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelTkIso_TrkHighPtID\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtID_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_central[\"TightRelTkIso_HighPtIDandIPCut\"] =\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta\", \"TH2Lookup\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_stat[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta_stat\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n\tmuon_options_syst[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"RunABCD_SF_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_pair_newTuneP_probe_pt_abseta_syst\", \"TH2LookupErr\", \"Muon_pt\", \"Muon_eta\"};\n      }\n      else if(legacy == \"UL\"){\n\tmuon_options_central[\"HighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"HighPtID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"HighPtID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_HighPtID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_LooseID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"MediumID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_MediumID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"MediumPromptID\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_MediumPromptID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"SoftID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"SoftID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"SoftID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_SoftID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_TightID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TrkHighPtID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ID.root\", \"NUM_TrkHighPtID_DEN_TrackerMuons_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\t\n\t\n\tmuon_options_central[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_LooseID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_LooseID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_MediumPromptID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelIso_DEN_TightIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"LooseRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_LooseRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_MediumID\"] =\t\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_MediumPromptID\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_MediumPromptID_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelIso_TightIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelIso_DEN_TightIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelTkIso_HighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelTkIso_HighPtIDandIPCut\"] =\t\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_HighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_central[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt\", \"TH2Lookup\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_stat[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_stat\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n\tmuon_options_syst[\"TightRelTkIso_TrkHighPtIDandIPCut\"] =\t{\"Efficiencies_muon_generalTracks_Z_Run2018_UL_ISO.root\", \"NUM_TightRelTkIso_DEN_TrkHighPtIDandIPCut_abseta_pt_syst\", \"TH2LookupErr\", \"Muon_eta\", \"Muon_pt\"};\n      }\n    }//era is 2018\n\n    std::map< std::string, std::vector<std::string> > ret;\n    //muon ID and ISO\n    if(muon_id != \"\"){\n      if(muon_options_central.find(muon_id) != muon_options_central.end()){\n\tret[\"Muon_SF_ID_nom\"] = muon_options_central[muon_id];\n\tret[\"Muon_SF_ID_nom\"][0] = muon_path + ret[\"Muon_SF_ID_nom\"][0];\n      }\n      if(muon_options_stat.find(muon_id) != muon_options_stat.end()){\n\tret[\"Muon_SF_ID_stat\"] = muon_options_stat[muon_id];\n\tret[\"Muon_SF_ID_stat\"][0] = muon_path + ret[\"Muon_SF_ID_stat\"][0];\n      }\n      if(muon_options_syst.find(muon_id) != muon_options_syst.end()){\n\tret[\"Muon_SF_ID_syst\"] = muon_options_syst[muon_id];\n\tret[\"Muon_SF_ID_syst\"][0] = muon_path + ret[\"Muon_SF_ID_syst\"][0];\n      }\n\n    }\n    if(muon_iso != \"\"){\n      if(muon_options_central.find(muon_iso) != muon_options_central.end()){\n\tret[\"Muon_SF_ISO_nom\"] = muon_options_central[muon_iso];\n\tret[\"Muon_SF_ISO_nom\"][0] = muon_path + ret[\"Muon_SF_ISO_nom\"][0];\n      }\n      if(muon_options_stat.find(muon_iso) != muon_options_stat.end()){\n\tret[\"Muon_SF_ISO_stat\"] = muon_options_stat[muon_iso];\n\tret[\"Muon_SF_ISO_stat\"][0] = muon_path + ret[\"Muon_SF_ISO_stat\"][0];\n      }\n      if(muon_options_syst.find(muon_iso) != muon_options_syst.end()){\n\tret[\"Muon_SF_ISO_syst\"] = muon_options_syst[muon_iso];\n\tret[\"Muon_SF_ISO_syst\"][0] = muon_path + ret[\"Muon_SF_ISO_syst\"][0];\n      }\n    }\n    //Electron ID and EFF\n    if(electron_id != \"\"){\n      if(electron_options_central.find(electron_id) != electron_options_central.end()){\n\tret[\"Electron_SF_ID_nom\"] = electron_options_central[electron_id];\n\tret[\"Electron_SF_ID_nom\"][0] = electron_path + ret[\"Electron_SF_ID_nom\"][0];\n      }\n      if(electron_options_uncertainty.find(electron_id) != electron_options_uncertainty.end()){\n\tret[\"Electron_SF_ID_unc\"] = electron_options_uncertainty[electron_id];\n\tret[\"Electron_SF_ID_unc\"][0] = electron_path + ret[\"Electron_SF_ID_unc\"][0];\n      }\n    }\n    if(electron_eff != \"\"){\n      if(electron_options_central.find(\"EFF_ptBelow20\") != electron_options_central.end()){\n\tret[\"Electron_SF_EFF_ptBelow20_nom\"] = electron_options_central[\"EFF_ptBelow20\"];\n\tret[\"Electron_SF_EFF_ptBelow20_nom\"][0] = electron_path + ret[\"Electron_SF_EFF_ptBelow20_nom\"][0];\n      }\n      if(electron_options_uncertainty.find(\"EFF_ptBelow20\") != electron_options_uncertainty.end()){\n\tret[\"Electron_SF_EFF_ptBelow20_unc\"] = electron_options_uncertainty[\"EFF_ptBelow20\"];\n\tret[\"Electron_SF_EFF_ptBelow20_unc\"][0] = electron_path + ret[\"Electron_SF_EFF_ptBelow20_unc\"][0];\n      }\n      if(electron_options_central.find(\"EFF_ptAbove20\") != electron_options_central.end()){\n\tret[\"Electron_SF_EFF_ptAbove20_nom\"] = electron_options_central[\"EFF_ptAbove20\"];\n\tret[\"Electron_SF_EFF_ptAbove20_nom\"][0] = electron_path + ret[\"Electron_SF_EFF_ptAbove20_nom\"][0];\n      }\n      if(electron_options_uncertainty.find(\"EFF_ptAbove20\") != electron_options_uncertainty.end()){\n\tret[\"Electron_SF_EFF_ptAbove20_unc\"] = electron_options_uncertainty[\"EFF_ptAbove20\"];\n\tret[\"Electron_SF_EFF_ptAbove20_unc\"][0] = electron_path + ret[\"Electron_SF_EFF_ptAbove20_unc\"][0];\n      }\n    }\n    return ret;\n  }\n\n  std::map< std::string, std::vector<std::string> > GetBtaggingCorrectorMap(std::string era, \n\t\t\t\t\t\t\t\t\t    std::string legacy, \n\t\t\t\t\t\t\t\t\t    std::string VFP=\"\",\n\t\t\t\t\t\t\t\t\t    std::string btag_top_path = \"\",\n\t\t\t\t\t\t\t\t\t    std::map<std::string, std::vector< std::pair< std::string, std::string> > > btag_process_map = std::map<std::string, std::vector< std::pair< std::string, std::string> > >(),\n\t\t\t\t\t\t\t\t\t    std::map<std::string, std::vector< std::pair< std::string, std::string> > > btag_inclusive_map = std::map<std::string, std::vector< std::pair< std::string, std::string> > >(),\n\t\t\t\t\t\t\t\t\t    bool btag_use_aggregate = false,\n\t\t\t\t\t\t\t\t\t    bool btag_use_HT_only = false,\n\t\t\t\t\t\t\t\t\t    bool btag_use_nJet_only = false,\n\t\t\t\t\t\t\t\t\t    bool verbose = false){\n    std::cout << \"Era: \" << era << \"\\nLegacy: \" << legacy <<  \"\\nPreVFP: \" << VFP << \"\\nBtag top path: \" << btag_top_path << std::endl;\n    std::map< std::string, std::vector<std::string> > ret;\n    //Load btag SFs for each process and systematic specified\n    if(btag_top_path != \"\"){\n      for(std::map<std::string, std::vector< std::pair<std::string, std::string> > >::iterator bit = btag_inclusive_map.begin(); bit != btag_inclusive_map.end(); ++bit){\n\tstd::string proc_name = bit->first;\n\tfor(std::vector< std::pair<std::string, std::string> >::iterator sit = (bit->second).begin(); sit != (bit->second).end(); ++sit){\n\t  std::string btag_key, syst_name, branch_postfix;\n\t  syst_name = sit->first; \n\t  branch_postfix = sit->second;\n\t  if(strncmp(syst_name.c_str(), \"$NOMINAL\", 8) == 0 || strncmp(syst_name.c_str(), \"nom\", 3) == 0) syst_name = \"nom\";\n\t  //Force inclusive processes to use the Aggregate method, because we don't store the maps for the inclusive processes (a previous workaround to avoid double counting in the aggregate maps)\n\t  btag_key = \"Aggregate\";\n\t  if(btag_use_HT_only) btag_key += \"1DX\";\n\t  if(btag_use_nJet_only) btag_key += \"1DY\";\n\t  btag_key += \"___\" + syst_name;\n\t  if(verbose)\n\t    std::cout << \"Btag key formed for process \" << static_cast<std::string>(proc_name) << \": \" << btag_key << std::endl;\n\t  //the branch_postfix is based on whether a systematic variations is a scale variation/central (nominal, jes, jer...) or purely a weight variation (FSR, ISR, etc...). If the latter, the branch_postfix should default to the 'nominal'\n\t  ret[\"btag___\" + era + \"___\" + static_cast<std::string>(proc_name) + \"___\" + syst_name] = {btag_top_path + \"BTaggingYields.root\", \n\t\t\t\t\t\t\t\t\t\t\t\t    btag_key, \n\t\t\t\t\t\t\t\t\t\t\t\t    \"TH2LookupFlow\", \n\t\t\t\t\t\t\t\t\t\t\t\t    \"HT__\" + branch_postfix, \n\t\t\t\t\t\t\t\t\t\t\t\t    \"nFTAJet__\" + branch_postfix};\n\t}\n      }\n      //Do the non-inclusve ones now, which will over-write in case any names clash... \n      for(std::map<std::string, std::vector< std::pair<std::string, std::string> > >::iterator bit = btag_process_map.begin(); bit != btag_process_map.end(); ++bit){\n\tstd::string proc_name = bit->first;\n\tfor(std::vector< std::pair<std::string, std::string> >::iterator sit = (bit->second).begin(); sit != (bit->second).end(); ++sit){\n\t  std::string btag_key, syst_name, branch_postfix;\n\t  syst_name = sit->first; \n\t  branch_postfix = sit->second; \n\t  if(strncmp(syst_name.c_str(), \"$NOMINAL\", 8) == 0 || strncmp(syst_name.c_str(), \"nom\", 3) == 0) syst_name = \"nom\";\n\t  if(btag_use_aggregate) btag_key = \"Aggregate\";\n\t  else btag_key = era + \"___\" + static_cast<std::string>(proc_name) + \"_\";\n\t  if(btag_use_HT_only) btag_key += \"1DX\";\n\t  if(btag_use_nJet_only) btag_key += \"1DY\";\n\t  btag_key += \"___\" + static_cast<std::string>(syst_name);\n\t  if(verbose)\n\t    std::cout << \"Btag key formed for process \" << static_cast<std::string>(proc_name) << \": \" << btag_key << std::endl;\n\t  //the branch_postfix is based on whether a systematic variations is a scale variation/central (nominal, jes, jer...) or purely a weight variation (FSR, ISR, etc...). If the latter, the branch_postfix should default to the 'nominal'\n\t  ret[\"btag___\" + era + \"___\" + static_cast<std::string>(proc_name) + \"___\" + syst_name] = {btag_top_path + \"BTaggingYields.root\", \n\t\t\t\t\t\t\t\t\t\t\t\t    btag_key, \n\t\t\t\t\t\t\t\t\t\t\t\t    \"TH2LookupFlow\", \n\t\t\t\t\t\t\t\t\t\t\t\t    \"HT__\" + branch_postfix, \n\t\t\t\t\t\t\t\t\t\t\t\t    \"nFTAJet__\" + branch_postfix};\n\t}\n      }\n    }\n    return ret;\n  }\n\n  // std::pair< ROOT::RDF::RNode, std::vector<LUT*> > AddLeptonSF(ROOT::RDF::RNode df, std::string_view era, std::map< std::string, std::vector<std::string> > idmap){\n  ROOT::RDF::RNode AddLeptonSF(ROOT::RDF::RNode df, std::string era, std::string processname,\n\t\t\t       std::shared_ptr< std::vector<LUT*> > veclut, std::map< std::string, std::vector<std::string> > correctormap, bool verbose=false){\n    // for(std::vector<string>::const_iterator req_iter = requiredLUTs.begin(); req_iter != requiredLUTs.end(); ++ req_iter){\n    //   if((*veclut)[0].find(*req_iter) == (*veclut)[0].end()){ std::cout << \"Required map not found: \" << *req_iter << std::endl; }\n    //   else {std::cout << \"Required map found: \" << *req_iter << std::endl;}\n    // }\n    // auto vGen = [&](int len) {\n    //   RVec<double> v(len);\n    //   std::transform(v.begin(), v.end(), v.begin(), unifGen);\n    //   return v;\n    // };\n    // RDataFrame d(1024);\n    // auto d0 = d.Define(\"len\", []() { return (int)gRandom->Uniform(0, 16); })\n    //   .Define(\"x\", vGen, {\"len\"})\n    //   .Define(\"y\", vGen, {\"len\"});\n    // rdf2 = rdf.Define(\"Muon_SF_ID_altnom\", \"ROOT::VecOps::RVec<double> ret = {}; \"\\\n    //               \"for(int i=0; i < Muon_pt.size(); ++i) {\"\\\n    //               \"ret.push_back(testLUT->TH2Lookup(\\\"TightRelIso/MediumID\\\", Muon_pt[i], abs(Muon_eta[i])));\"\\\n    //               \"}\"\\\n    //               \"return ret;\"\n    ROOT::RDF::RNode ret = df;\n    auto branches = ret.GetColumnNames();\n    Bool_t low_electron_eff = false;\n    Bool_t high_electron_eff = false;\n    Bool_t composite_electron_eff_defined = false;\n\n    for(std::map< std::string, std::vector<std::string> >::iterator cm_iter = correctormap.begin(); cm_iter != correctormap.end(); ++cm_iter){\n      std::string branch_and_key, lookup_type;\n      std::vector<std::string> arg_list = {};\n\n      branch_and_key = cm_iter->first;\n      //skip branches that are already defined\n      Bool_t already_defined = false;\n      for(int bi = 0; bi < branches.size(); ++bi){\n\tif(branch_and_key == branches.at(bi)) already_defined = true;\n\tif(!composite_electron_eff_defined && branches.at(bi) == \"Electron_SF_EFF_nom\") composite_electron_eff_defined = true;\n      }\n      if(already_defined){\n\tif(verbose)\n\t  std::cout << \"Branch \" << branch_and_key << \" already defined, skipping.\" << std::endl;\n\tcontinue;\n      }\n\n      //skip correctors that are not starting with Muon or Electron\n      if(std::strncmp(branch_and_key.c_str(), \"Muon\", 4) != 0 && std::strncmp(branch_and_key.c_str(), \"Electron\", 8) != 0){\n\tif(verbose)\n\t  std::cout << \"AddLeptonSF() skipping non-Electron and non-Muon branch definition for: \" << branch_and_key << std::endl;\n\tcontinue;\n      }\n\n      //check if we should compose the overall electron efficiency scale factor, only after skipping branches that are already defined and don't need a composition\n      if(branch_and_key == \"Electron_SF_EFF_ptBelow20_nom\") low_electron_eff = true;\n      if(branch_and_key == \"Electron_SF_EFF_ptAbove20_nom\") high_electron_eff = true;\n\n\n      //store the argument list in a vector\n      for(int i = 0; i < (cm_iter->second).size(); ++i){\n\tif(i == 2) lookup_type = cm_iter->second[i];\n\telse if(i > 2) arg_list.push_back(cm_iter->second[i]);\n\t// std::cout << cm_iter->second[i] << \" \";\n      }\n      if(lookup_type == \"TH2Lookup\"){\n\tif(arg_list[0] == \"Muon_eta\" || arg_list[0] == \"Muon_pt\"){\n\t  auto slottedLookup = [veclut, branch_and_key](int slot, ROOT::VecOps::RVec<float> X, ROOT::VecOps::RVec<float> Y){\n\t    ROOT::VecOps::RVec<float> rvec_return = {};\n\t    for(int li=0; li < X.size(); ++li) {\n\t      rvec_return.push_back((*veclut)[slot]->TH2Lookup(branch_and_key, fabs(X[li]), fabs(Y[li])));\n\t    }\n\t    return rvec_return;\n\t  };\n\t  ret = ret.DefineSlot(branch_and_key, slottedLookup, arg_list);\n\t}\n\telse if(arg_list[0] == \"Electron_eta\" || arg_list[0] == \"Electron_pt\"){\n\t  auto slottedLookup = [veclut, branch_and_key](int slot, ROOT::VecOps::RVec<float> X, ROOT::VecOps::RVec<float> Y){\n\t    ROOT::VecOps::RVec<float> rvec_return = {};\n\t    for(int li=0; li < X.size(); ++li) {\n\t      rvec_return.push_back((*veclut)[slot]->TH2Lookup(branch_and_key, X[li], Y[li]));\n\t\t}\n\t    return rvec_return;\n\t  };\n\t  ret = ret.DefineSlot(branch_and_key, slottedLookup, arg_list);\n\t}\n\telse std::cout << \"Unhandled type in AddLeptonSF()\" << std::endl;\n      }\n      else if(lookup_type == \"TH2LookupErr\"){\n\tif(arg_list[0] == \"Muon_eta\" || arg_list[0] == \"Muon_pt\"){\n\t  auto slottedLookup = [veclut, branch_and_key](int slot, ROOT::VecOps::RVec<float> X, ROOT::VecOps::RVec<float> Y){\n\t    ROOT::VecOps::RVec<float> rvec_return = {};\n\t    for(int li=0; li < X.size(); ++li) {\n\t      rvec_return.push_back((*veclut)[slot]->TH2LookupErr(branch_and_key, fabs(X[li]), fabs(Y[li])));\n\t\t}\n\t    return rvec_return;\n\t  };\n\t  ret = ret.DefineSlot(branch_and_key, slottedLookup, arg_list);\n\t}\n\telse if(arg_list[0] == \"Electron_eta\" || arg_list[0] == \"Electron_pt\"){\n\t  auto slottedLookup = [veclut, branch_and_key](int slot, ROOT::VecOps::RVec<float> X, ROOT::VecOps::RVec<float> Y){\n\t    ROOT::VecOps::RVec<float> rvec_return = {};\n\t    for(int li=0; li < X.size(); ++li) {\n\t      rvec_return.push_back((*veclut)[slot]->TH2LookupErr(branch_and_key, X[li], Y[li]));\n\t\t}\n\t    return rvec_return;\n\t  };\n\t  ret = ret.DefineSlot(branch_and_key, slottedLookup, arg_list);\n\t}\n\telse std::cout << \"Unhandled type in AddLeptonSF()\" << std::endl;\n      }\n    }\n    if(low_electron_eff && high_electron_eff){\n      // if(!composite_electron_eff_defined){\n      if(true){\n\tret = ret.DefineSlot(\"Electron_SF_EFF_nom\", \n\t\t\t     [](int slot, ROOT::VecOps::RVec<float> low_eff,  ROOT::VecOps::RVec<float> high_eff,  ROOT::VecOps::RVec<float> pt){\n\t\t\t       ROOT::VecOps::RVec<float> rvec_return = {};\n\t\t\t       for(int pi=0; pi < pt.size(); ++pi) {\n\t\t\t\t rvec_return.push_back((pt.at(pi) >= 20.0 ? high_eff.at(pi) : low_eff.at(pi)));\n\t\t\t       }\n\t\t\t       return rvec_return;\n\t\t\t     },\n\t\t\t     {\"Electron_SF_EFF_ptBelow20_nom\", \"Electron_SF_EFF_ptAbove20_nom\", \"Electron_pt\"});\n\tret = ret.DefineSlot(\"Electron_SF_EFF_unc\", \n\t\t\t     [](int slot, ROOT::VecOps::RVec<float> low_eff,  ROOT::VecOps::RVec<float> high_eff,  ROOT::VecOps::RVec<float> pt){\n\t\t\t       ROOT::VecOps::RVec<float> rvec_return = {};\n\t\t\t       for(int pi=0; pi < pt.size(); ++pi) {\n\t\t\t\t rvec_return.push_back((pt.at(pi) >= 20.0 ? high_eff.at(pi) : low_eff.at(pi)));\n\t\t\t       }\n\t\t\t       return rvec_return;\n\t\t\t     },\n\t\t\t     {\"Electron_SF_EFF_ptBelow20_unc\", \"Electron_SF_EFF_ptAbove20_unc\", \"Electron_pt\"});\n      }\n      else std::cout << \"Branch Electron_SF_EFF_nom already defined, skipping composition\" << std::endl;\n    }\n    return ret;\n  }\n  ROOT::RDF::RNode AddBTaggingYieldsRenormalization(ROOT::RDF::RNode df, std::string era, std::string processname, \n\t\t\t\t\t\t    std::shared_ptr< std::vector<LUT*> > veclut, std::map< std::string, std::vector<std::string> > correctormap, bool verbose=false){\n    ROOT::RDF::RNode ret = df;\n    auto branches = ret.GetColumnNames();\n    std::string expected_corrector_start = \"btag___\" + era + \"___\" + processname + \"___\";\n\n    Bool_t low_electron_eff = false;\n    Bool_t high_electron_eff = false;\n    Bool_t composite_electron_eff_defined = false;\n\n    for(std::map< std::string, std::vector<std::string> >::iterator cm_iter = correctormap.begin(); cm_iter != correctormap.end(); ++cm_iter){\n      std::string corrector_key, btag_final_weight, btag_sf_product, lookup_type, syst_postfix;\n      std::vector<std::string> arg_list = {};\n\n      //key is not precisely the branch for btag corrections, since we need individual ones for each process!\n      corrector_key = cm_iter->first;\n\n      //store the argument list in a vector\n      for(int i = 0; i < (cm_iter->second).size(); ++i){\n\tif(i == 2) lookup_type = cm_iter->second[i];\n\telse if(i > 2) arg_list.push_back(cm_iter->second[i]);\n\t// std::cout << cm_iter->second[i] << \" \";\n      }\n\n      //skip correctors that are not starting with btag___<era>___<process_name>\n      if(std::strncmp(corrector_key.c_str(), expected_corrector_start.c_str(), expected_corrector_start.length()) != 0){\n\tif(verbose)\n\t  std::cout << \"AddBTaggingYieldRenormalization() skipping non-relavant correction \" << corrector_key << std::endl;\n\tcontinue;\n      }\n\n      //determine the systematic postfix, then define the final btag branch weight name, and the required input branch btag_sf_product, appending the last to the argument list\n      syst_postfix = corrector_key.substr(expected_corrector_start.length(), corrector_key.length() - expected_corrector_start.length());\n      if(verbose)\n\tstd::cout << \"syst_postfix: \" << syst_postfix << std::endl;\n      btag_final_weight = \"pwgt_btag___\" + syst_postfix;\n      btag_sf_product = \"btagSFProduct___\" + syst_postfix;\n      arg_list.push_back(btag_sf_product);\n\n      //skip branches that are already defined\n      Bool_t already_defined = false;\n      Bool_t btag_sf_product_exists = false;\n      for(int bi = 0; bi < branches.size(); ++bi){\n\tif(btag_final_weight == branches.at(bi)) already_defined = true;\n\tif(btag_sf_product == branches.at(bi)) btag_sf_product_exists = true;\n      }\n      if(already_defined){\n\tif(verbose)\n\t  std::cout << \"Branch \" << btag_final_weight << \" already defined, skipping.\" << std::endl;\n\tcontinue;\n      }\n      if(!btag_sf_product_exists){\n\tif(verbose)\n\t  std::cout << \"btagSFProduct branch \" << btag_sf_product << \" does not exist, not calculating btag event weight in AddBTaggingYieldsRenormalization()\" << std::endl;\n\tcontinue;\n      }\n\n      if(lookup_type == \"TH1LookupFlow\"){\n\tauto slottedLookup = [veclut, corrector_key](int slot, float X, double input_btag_sf_product){\n\t  return input_btag_sf_product * (*veclut)[slot]->TH1LookupFlow(corrector_key, X);\n\t};\n\tret = ret.DefineSlot(btag_final_weight, slottedLookup, arg_list);\n\n      }\n      else if(lookup_type == \"TH2LookupFlow\"){\n\t// arg_list.push_back(\"rdfentry_\");\n\t// auto slottedLookup = [veclut, corrector_key](int slot, float X, int Y, double input_btag_sf_product, ULong64_t rdfentry_){\n\t//   bool verbose = false;\n\t//   if( X > 195.45 && X < 195.55 && Y == 2){\n\t//     verbose = true;\n\t//     std::cout << \"Debugging info:\\nX: \" << X << \"\\nY: \" << Y << \"\\nLUT value: \" << (*veclut)[slot]->TH2LookupFlow(corrector_key, verbose, X, Y) << \"\\nSFproduct: \" << input_btag_sf_product\n\t//     << \"\\nResult: \" << input_btag_sf_product * (*veclut)[slot]->TH2LookupFlow(corrector_key, verbose, X, Y) << std::endl;\n\t//   }\n\t//   return input_btag_sf_product * (*veclut)[slot]->TH2LookupFlow(corrector_key, verbose, X, Y);\n\t//   };\n\tauto slottedLookup = [veclut, corrector_key](int slot, float X, int Y, double input_btag_sf_product){\n\t  return input_btag_sf_product * (*veclut)[slot]->TH2LookupFlow(corrector_key, X, Y);\n\t};\n\tret = ret.DefineSlot(btag_final_weight, slottedLookup, arg_list);\n      }\n      else if(lookup_type == \"TH3LookupFlow\"){\n\tauto slottedLookup = [veclut, corrector_key](int slot, float X, int Y, float Z, double input_btag_sf_product){\n\t  return input_btag_sf_product * (*veclut)[slot]->TH3LookupFlow(corrector_key, X, Y, Z);\n\t};\n\tret = ret.DefineSlot(btag_final_weight, slottedLookup, arg_list);\n      }\n      else std::cout << \"Unhandled type in AddBTaggingYieldRenormalization()\" << std::endl;\n    }\n    return ret;\n  }\n  template <typename T>\n  ROOT::RDF::RResultPtr<T> bookLazySnapshot(ROOT::RDF::RNode df, std::string_view treename, std::string_view filename, \n\t\t\tconst ROOT::Detail::RDF::ColumnNames_t columnList, std::string_view mode = \"RECREATE\"){\n    //ROOT::kZLIB //faster read speed, but less compression than LZMA. //==1L\n    //ROOT::kLZMA //highest ratio, very slow decompression //==2L\n    //ROOT::kLZ4 //fastest read speed for decent compression ratio //==4L\n    //ROOT::kZSTD //unknown performance //==5L\n    //ROOT::RDF::RSnapshotOptions(std::string_view mode, ECAlgo comprAlgo, int comprLevel, int autoFlush, int splitLevel, bool lazy, bool overwriteIfExists=false); \n    auto sopt = ROOT::RDF::RSnapshotOptions(mode, ROOT::kLZ4, 6, 0, 99, true); //, true); // but overwrite is exclusive to 6.22 + version\n    //ROOT::RDF::RInterface::Snapshot ( std::string_view  treename, std::string_view  filename, const ColumnNames_t &  columnList, const RSnapshotOptions &  options = RSnapshotOptions())\n    // sopt.fLazy = false;\n    std::cout << \"filename = \" << filename << \" mode = \" << sopt.fMode << \" lazy = \" << sopt.fLazy << std::endl;\n    // auto ret = df.Snapshot(treename, filename, columnList, sopt);\n    // return ret;\n    return sopt;\n  }\n  ROOT::RDF::RSnapshotOptions getOption(std::string_view mode = \"RECREATE\"){\n    std::cout << ROOT::kLZMA\n\t      << ROOT::kLZ4 \n\t      << ROOT::kZSTD\n\t      << ROOT::kZLIB\n\t      << std::endl;\n\n    auto sopt = ROOT::RDF::RSnapshotOptions(mode, ROOT::kLZ4, 6, 0, 99, true); //, true); // but overwrite is exclusive to 6.22 + version\n    return sopt;\n  }\n  int packEventId(int datasetId, int campaignId, int genTtbarId = -1, int ttbarNGenJet = -1, double ttbarGenHT = -1, int otherPhaseSpaceID = -1){\n    //Store integer key packing info about dataset (TTTo2L2Nu...), campaign (RunIIFall17NanoAODv6...), ttbar categorization, phase space, etc.\n    // Reserve 1000 codes for dataset, 100 for campaign, \n    int retCode = 0;\n    return retCode;\n  }\n  double unpackEventId(int packedEventId, double genWeight, double luminosity = -1, bool details = false){\n    //return the event level XS weight accounting for luminosity, genWeight, sumWeights, etc. \n    //Use a default for luminosity based on the era determined by the campaign, perhaps...\n    double retCode = 0;\n    return retCode;\n  }\n  std::map<std::string, std::string> unpackEventId(int packedEventId, double genWeight, double luminosity = -1){\n    //return the event level XS weight accounting for luminosity, genWeight, sumWeights, etc. \n    std::map<std::string, std::string> retCode;\n    if(luminosity < 0){\n      //code to get the luminosity lookup from the main function...\n      retCode[\"luminosity\"] = std::to_string(unpackEventId(packedEventId, genWeight, luminosity, true));\n    } else {\n      retCode[\"luminosity\"] = \"This is probably a bad idea, KISS my friend! Drop the lumi and genWeight\";\n    }\n    return retCode;\n  }\n  double ElMu2017HLTSF(double lep1pt, double lep2pt){\n    double sf = 1;\n    if(lep1pt > 20 && lep2pt > 15){\n      if(lep1pt < 40){\n\tif(lep2pt < 30){\n\t  sf = 0.948121;\n\t  return sf;\n\t}\n\telse { // > 30\n\t  sf = 0.958362; \n\t  return sf;\n\t}\n      }\n      else if(lep1pt < 60){\n\tif(lep2pt < 30){\n\t  sf = 0.957376;\n\t  return sf;\n\t}\n\telse if(lep2pt < 45){\n\t  sf = 0.985497;\n\t  return sf;\n\t}\n\telse { // > 45, < 60\n\t  sf = 0.987867; \n\t  return sf;\n\t}\n      }\n      else if(lep1pt < 80){\n\tif(lep2pt < 30){\n\t  sf = 0.981871;\n\t  return sf;\n\t}\n\telse if(lep2pt < 45){\n\t  sf = 0.989406;\n\t  return sf;\n\t}\n\telse if(lep2pt < 60){\n\t  sf = 0.993657;\n\t  return sf;\n\t}\n\telse { // > 60, < 80\n\t  sf = 0.992759; \n\t  return sf;\n\t}\n      }\n      else if(lep1pt < 100){\n\tif(lep2pt < 30){\n\t  sf = 0.986281;\n\t  return sf;\n\t}\n\telse if(lep2pt < 45){\n\t  sf = 0.990969;\n\t  return sf;\n\t}\n\telse if(lep2pt < 60){\n\t  sf = 0.99191;\n\t  return sf;\n\t}\n\telse if(lep2pt < 80){\n\t  sf = 0.993743;\n\t  return sf;\n\t}\n\telse { // > 80, < 100\n\t  sf = 0.994792; \n\t  return sf;\n\t}\n      }\n      else if(lep1pt < 150){\n\tif(lep2pt < 30){\n\t  sf = 0.972893;\n\t  return sf;\n\t}\n\telse if(lep2pt < 45){\n\t  sf = 0.98453;\n\t  return sf;\n\t}\n\telse if(lep2pt < 60){\n\t  sf = 0.992017;\n\t  return sf;\n\t}\n\telse if(lep2pt < 80){\n\t  sf = 0.994693;\n\t  return sf;\n\t}\n\telse if(lep2pt < 100){\n\t  sf = 0.995513;\n\t  return sf;\n\t}\n\telse { // > 100, < 150\n\t  sf = 0.995142; \n\t  return sf;\n\t}\n      }\n      else { //lep1pt > 150\n\tif(lep2pt < 30){\n\t  sf = 0.986643;\n\t  return sf;\n\t}\n\telse if(lep2pt < 45){\n\t  sf = 0.977584;\n\t  return sf;\n\t}\n\telse if(lep2pt < 60){\n\t  sf = 0.986496;\n\t  return sf;\n\t}\n\telse if(lep2pt < 80){\n\t  sf = 0.988663;\n\t  return sf;\n\t}\n\telse if(lep2pt < 100){\n\t  sf = 0.990325;\n\t  return sf;\n\t}\n\telse if(lep2pt < 150){\n\t  sf = 0.996006;\n\t  return sf;\n\t}\n\telse { // > 150\n\t  sf = 0.996827; \n\t  return sf;\n\t}\n      }\n    } else {\n      std::cout << \"HLT SF cannot be computed for lep1pt \" << lep1pt << \" and lep2pt \" << lep2pt << std::endl;\n      sf = -1000000000000;\n      return sf;\n    }\n  }\n\n  std::vector<int> unpackGenTtbarId(int genTtbarId){\n  // Implementation:\n  //   The classification scheme returns an ID per event, and works as follows:\n     \n  //   All jets in the following need to be in the acceptance as given by the config parameters |eta|, pt.\n  //    A c jet must contain at least one c hadron and should contain no b hadrons\n     \n  //   First, b jets from top are identified, i.e. jets containing a b hadron from t->b decay\n  //   They are encoded in the ID as numberOfBjetsFromTop*100, i.e.\n  //   0xx: no b jets from top in acceptance\n  //   1xx: 1 b jet from top in acceptance\n  //   2xx: both b jets from top in acceptance\n     \n  //   Then, b jets from W are identified, i.e. jets containing a b hadron from W->b decay\n  //   They are encoded in the ID as numberOfBjetsFromW*1000, i.e.\n  //   0xxx: no b jets from W in acceptance\n  //   1xxx: 1 b jet from W in acceptance\n  //   2xxx: 2 b jets from W in acceptance\n     \n  //   Then, c jets from W are identified, i.e. jets containing a c hadron from W->c decay, but no b hadrons\n  //   They are encoded in the ID as numberOfCjetsFromW*10000, i.e.\n  //   0xxxx: no c jets from W in acceptance\n  //   1xxxx: 1 c jet from W in acceptance\n  //   2xxxx: 2 c jets from W in acceptance\n\n  //   From the remaining jets, the ID is formed based on the additional b jets (IDs x5x) and c jets (IDs x4x) in the following order:\n  //   x55: at least 2 additional b jets with at least two of them having >= 2 b hadrons in each\n  //   x54: at least 2 additional b jets with one of them having >= 2 b hadrons, the others having =1 b hadron\n  //   x53: at least 2 additional b jets with all having =1 b hadron\n  //   x52: exactly 1 additional b jet having >=2 b hadrons\n  //   x51: exactly 1 additional b jet having =1 b hadron\n  //   x45: at least 2 additional c jets with at least two of them having >= 2 c hadrons in each\n  //   x44: at least 2 additional c jets with one of them having >= 2 c hadrons, the others having =1 c hadron\n  //   x43: at least 2 additional c jets with all having =1 c hadron\n  //   x42: exactly 1 additional c jet having >=2 c hadrons\n  //   x41: exactly 1 additional c jet having =1 c hadron\n  //   x00: No additional b or c jet, i.e. only light flavour jets or no additional jets\n    std::vector<int> jetTypes;\n    int x5 = (int) (genTtbarId/10000);\n    int x4 = (int) (genTtbarId - 10000*x5)/1000;\n    int x3 = (int) (genTtbarId - 10000*x5 - 1000*x4)/100;\n    int x21 = (int) (genTtbarId - 10000*x5 - 1000*x4 - 100*x3);\n\n    switch (x21) {\n    case 55: \n      jetTypes.push_back(2); //number of minimal additional b jets \n      jetTypes.push_back(2); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(0); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(0); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(0); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(0); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 54: \n      jetTypes.push_back(2); //number of minimal additional b jets \n      jetTypes.push_back(1); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(1); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(0); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(0); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(0); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 53: \n      jetTypes.push_back(2); //number of minimal additional b jets \n      jetTypes.push_back(0); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(2); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(0); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(0); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(0); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 52: \n      jetTypes.push_back(1); //number of minimal additional b jets \n      jetTypes.push_back(1); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(0); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(0); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(0); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(0); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 51: \n      jetTypes.push_back(1); //number of minimal additional b jets \n      jetTypes.push_back(0); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(1); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(0); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(0); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(0); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 45: \n      jetTypes.push_back(0); //number of minimal additional b jets \n      jetTypes.push_back(0); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(0); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(2); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(2); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(0); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 44: \n      jetTypes.push_back(0); //number of minimal additional b jets \n      jetTypes.push_back(0); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(0); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(2); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(1); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(1); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 43: \n      jetTypes.push_back(0); //number of minimal additional b jets \n      jetTypes.push_back(0); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(0); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(2); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(0); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(2); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 42: \n      jetTypes.push_back(0); //number of minimal additional b jets \n      jetTypes.push_back(0); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(0); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(1); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(1); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(0); //number of minimal additional c jets with 1 C hadron\n      break;\n    case 41: \n      jetTypes.push_back(0); //number of minimal additional b jets \n      jetTypes.push_back(0); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(0); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(1); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(0); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(1); //number of minimal additional c jets with 1 C hadron\n      break;\n    default: \n      jetTypes.push_back(0); //number of minimal additional b jets \n      jetTypes.push_back(0); //number of minimal additional b jets with 2+ B hadrons\n      jetTypes.push_back(0); //number of minimal additional b jets with 1 B hadron\n      jetTypes.push_back(0); //number of minimal additional c jets with precedence to b jets\n      jetTypes.push_back(0); //number of minimal additional c jets with 2+ C hadrons\n      jetTypes.push_back(0); //number of minimal additional c jets with 1 C hadron\n      break;\n    }\n\n    jetTypes.push_back(x3); //store number of b jets from t\n    jetTypes.push_back(x4); //store number of b jets from W\n    jetTypes.push_back(x5); //Store number of c jets from W\n\n    //return vector{additional b jets, double-B b jets, single-B b jets, additional c jets (if no b jets),\n    // double-C c jets, single-C c jets, minimal t->b jets in acceptance, minimal W->b jets in acceptance, \n    //minimal W-> c jets in acceptance\n    assert (jetTypes.size() == 9);\n    return jetTypes;\n  }\n\n  double btagEventWeight_count(double btag_threshold, RVec_f *jets_eff, RVec_f *jets_sf, RVec_f *jets_btag){\n    double weight = 1.0;\n    double prob_data = 1, prob_mc = 1;\n    for(int i = 0; i < jets_eff->size(); ++i){\n      if(jets_sf->at(i) >= btag_threshold){\n\tprob_mc *= jets_eff->at(i);\n\tprob_data *= jets_sf->at(i) * jets_eff->at(i);\n      } else {\n\tprob_mc *= (1 - jets_eff->at(i));\n\tprob_data *= (1 - jets_sf->at(i) * jets_eff->at(i));\n      }\n    }\n    weight = prob_data/prob_mc;\n    return weight;\n  }\n  \n  \n  double btagEventWeight_shape(RVec_f jets_sf){\n    //return the PRE-weight from shape variations, based on the product of all selected jets' SFs.\n    //This needs to be multiplied with the event yield [sum(weights before)/sum(weights after)] after multiplying\n    //this preweight with the rest of the event weight\n    double weight = 1.0;\n    for(int i = 0; i < jets_sf.size(); ++i){\n      weight *= jets_sf.at(i);\n    }\n    return weight;\n  }\n  \n  double btagEventWeight_shape(RVec_f jets_sf, RVec_i jets_mask){\n    //return the PRE-weight from shape variations, based on the product of all selected jets' SFs.\n    //This needs to be multiplied with the event yield [sum(weights before)/sum(weights after)] after multiplying\n    //this preweight with the rest of the event weight\n    RVec_f masked_jets_sf = jets_sf[jets_mask];\n    double weight = 1.0;\n    for(int i = 0; i < masked_jets_sf.size(); ++i){\n      weight *= masked_jets_sf.at(i);\n    }\n    return weight;\n  }\n  \n  RVec_i generateIndices(RVec_i v){\n    RVec_i i(v.size());\n    std::iota(i.begin(), i.end(), 0);\n    return i;\n  }\n  \n  RVec_i generateIndices(RVec_f v){\n    RVec_i i(v.size());\n    std::iota(i.begin(), i.end(), 0);\n    return i;\n  }\n  \n  RVec_f transverseMass(RVec_f pt1, RVec_f phi1, RVec_f m1, RVec_f pt2, RVec_f phi2, RVec_f m2){\n    //This function only accepts vectors of equal size\n    if(pt1.size() != pt2.size()){\n      RVec_f v = {-9999.9};\n      return v;\n    }\n    else {\n      //RVec multiplication is element-by-element, i.e. {0, 1, 2}*{1, -3, 9.5} = {0, -3, 19}\n      //auto MT2 = (*m1)*(*m1) + (*m2)*(*m2) + 2*(sqrt((*m1)*(*m1) + (*pt1)*(*pt1)) * sqrt((*m2)*(*m2) + (*pt2)*(*pt2)) - (*pt1)*(*pt2)*cos(ROOT::VecOps::DeltaPhi(*phi1, *phi2)));\n      auto MT2 = (m1)*(m1) + (m2)*(m2) + 2*(sqrt((m1)*(m1) + (pt1)*(pt1)) * sqrt((m2)*(m2) + (pt2)*(pt2)) - (pt1)*(pt2)*cos(ROOT::VecOps::DeltaPhi(phi1, phi2)));\n      return sqrt(MT2);\n    }\n  }\n\n  RVec_f transverseMassMET(RVec_f pt1, RVec_f phi1, RVec_f m1, double pt2_uncast, double phi2_uncast){\n    if(pt1.size() == 0){\n      RVec_f v = {-9999.9};\n      return v;\n    }\n    else {\n      RVec_f pt2, phi2, m2;\n      double m2_uncast = 0;\n      //broadcast the double to RVec's\n      for(int z = 0; z < pt1.size(); ++z){\n\tpt2.push_back(pt2_uncast);\n\tphi2.push_back(phi2_uncast);\n\tm2.push_back(m2_uncast);\n      }\n      //RVec multiplication is element-by-element, i.e. {0, 1, 2}*{1, -3, 9.5} = {0, -3, 19}\n      //auto MT2 = (*m1)*(*m1) + (*m2)*(*m2) + 2*(sqrt((*m1)*(*m1) + (*pt1)*(*pt1)) * sqrt((*m2)*(*m2) + (*pt2)*(*pt2)) - (*pt1)*(*pt2)*cos(ROOT::VecOps::DeltaPhi(*phi1, *phi2)));\n      auto MT2 = (m1)*(m1) + (m2)*(m2) + 2*(sqrt((m1)*(m1) + (pt1)*(pt1)) * sqrt((m2)*(m2) + (pt2)*(pt2)) - (pt1)*(pt2)*cos(ROOT::VecOps::DeltaPhi(phi1, phi2)));\n      return sqrt(MT2);\n    }\n  }\n  enum TheRunEra{y2016B,y2016C,y2016D,y2016E,y2016F,y2016G,y2016H,y2017B,y2017C,y2017D,y2017E,y2017F,y2018A,y2018B,y2018C,y2018D,y2016MC,y2017MC,y2018MC};  \n  std::pair<double,double> METXYCorr(double uncormet, double uncormet_phi, int runnb, int year, bool isData, int npv){\n\n    bool isMC = !isData; //flip for convention used in FourTop analysis\n    std::pair<double,double>  TheXYCorr_Met_MetPhi(uncormet,uncormet_phi);\n    \n    if(npv>100) npv=100;\n    int runera =-1;\n    bool usemetv2 =false;\n    if(isMC && year == 2016) runera = y2016MC;\n    else if(isMC && year == 2017) {runera = y2017MC; usemetv2 =true;}\n    else if(isMC && year == 2018) runera = y2018MC;\n    \n    else if(!isMC && runnb >=272007 &&runnb<=275376  ) runera = y2016B;\n    else if(!isMC && runnb >=275657 &&runnb<=276283  ) runera = y2016C;\n    else if(!isMC && runnb >=276315 &&runnb<=276811  ) runera = y2016D;\n    else if(!isMC && runnb >=276831 &&runnb<=277420  ) runera = y2016E;\n    else if(!isMC && runnb >=277772 &&runnb<=278808  ) runera = y2016F;\n    else if(!isMC && runnb >=278820 &&runnb<=280385  ) runera = y2016G;\n    else if(!isMC && runnb >=280919 &&runnb<=284044  ) runera = y2016H;\n    \n    else if(!isMC && runnb >=297020 &&runnb<=299329 ){ runera = y2017B; usemetv2 =true;}\n    else if(!isMC && runnb >=299337 &&runnb<=302029 ){ runera = y2017C; usemetv2 =true;}\n    else if(!isMC && runnb >=302030 &&runnb<=303434 ){ runera = y2017D; usemetv2 =true;}\n    else if(!isMC && runnb >=303435 &&runnb<=304826 ){ runera = y2017E; usemetv2 =true;}\n    else if(!isMC && runnb >=304911 &&runnb<=306462 ){ runera = y2017F; usemetv2 =true;}\n    \n    else if(!isMC && runnb >=315252 &&runnb<=316995 ) runera = y2018A;\n    else if(!isMC && runnb >=316998 &&runnb<=319312 ) runera = y2018B;\n    else if(!isMC && runnb >=319313 &&runnb<=320393 ) runera = y2018C;\n    else if(!isMC && runnb >=320394 &&runnb<=325273 ) runera = y2018D;\n    \n    else {\n      //Couldn't find data/MC era => no correction applied\n      return TheXYCorr_Met_MetPhi;\n    }\n    \n    double METxcorr(0.),METycorr(0.);\n    \n    if(!usemetv2){//Current recommendation for 2016 and 2018\n      if(runera==y2016B) METxcorr = -(-0.0478335*npv -0.108032);\n      if(runera==y2016B) METycorr = -(0.125148*npv +0.355672);\n      if(runera==y2016C) METxcorr = -(-0.0916985*npv +0.393247);\n      if(runera==y2016C) METycorr = -(0.151445*npv +0.114491);\n      if(runera==y2016D) METxcorr = -(-0.0581169*npv +0.567316);\n      if(runera==y2016D) METycorr = -(0.147549*npv +0.403088);\n      if(runera==y2016E) METxcorr = -(-0.065622*npv +0.536856);\n      if(runera==y2016E) METycorr = -(0.188532*npv +0.495346);\n      if(runera==y2016F) METxcorr = -(-0.0313322*npv +0.39866);\n      if(runera==y2016F) METycorr = -(0.16081*npv +0.960177);\n      if(runera==y2016G) METxcorr = -(0.040803*npv -0.290384);\n      if(runera==y2016G) METycorr = -(0.0961935*npv +0.666096);\n      if(runera==y2016H) METxcorr = -(0.0330868*npv -0.209534);\n      if(runera==y2016H) METycorr = -(0.141513*npv +0.816732);\n      if(runera==y2017B) METxcorr = -(-0.259456*npv +1.95372);\n      if(runera==y2017B) METycorr = -(0.353928*npv -2.46685);\n      if(runera==y2017C) METxcorr = -(-0.232763*npv +1.08318);\n      if(runera==y2017C) METycorr = -(0.257719*npv -1.1745);\n      if(runera==y2017D) METxcorr = -(-0.238067*npv +1.80541);\n      if(runera==y2017D) METycorr = -(0.235989*npv -1.44354);\n      if(runera==y2017E) METxcorr = -(-0.212352*npv +1.851);\n      if(runera==y2017E) METycorr = -(0.157759*npv -0.478139);\n      if(runera==y2017F) METxcorr = -(-0.232733*npv +2.24134);\n      if(runera==y2017F) METycorr = -(0.213341*npv +0.684588);\n      if(runera==y2018A) METxcorr = -(0.362865*npv -1.94505);\n      if(runera==y2018A) METycorr = -(0.0709085*npv -0.307365);\n      if(runera==y2018B) METxcorr = -(0.492083*npv -2.93552);\n      if(runera==y2018B) METycorr = -(0.17874*npv -0.786844);\n      if(runera==y2018C) METxcorr = -(0.521349*npv -1.44544);\n      if(runera==y2018C) METycorr = -(0.118956*npv -1.96434);\n      if(runera==y2018D) METxcorr = -(0.531151*npv -1.37568);\n      if(runera==y2018D) METycorr = -(0.0884639*npv -1.57089);\n      if(runera==y2016MC) METxcorr = -(-0.195191*npv -0.170948);\n      if(runera==y2016MC) METycorr = -(-0.0311891*npv +0.787627);\n      if(runera==y2017MC) METxcorr = -(-0.217714*npv +0.493361);\n      if(runera==y2017MC) METycorr = -(0.177058*npv -0.336648);\n      if(runera==y2018MC) METxcorr = -(0.296713*npv -0.141506);\n      if(runera==y2018MC) METycorr = -(0.115685*npv +0.0128193);\n    }\n    else {//these are the corrections for v2 MET recipe (currently recommended for 2017)\n      if(runera==y2016B) METxcorr = -(-0.0374977*npv +0.00488262);\n      if(runera==y2016B) METycorr = -(0.107373*npv +-0.00732239);\n      if(runera==y2016C) METxcorr = -(-0.0832562*npv +0.550742);\n      if(runera==y2016C) METycorr = -(0.142469*npv +-0.153718);\n      if(runera==y2016D) METxcorr = -(-0.0400931*npv +0.753734);\n      if(runera==y2016D) METycorr = -(0.127154*npv +0.0175228);\n      if(runera==y2016E) METxcorr = -(-0.0409231*npv +0.755128);\n      if(runera==y2016E) METycorr = -(0.168407*npv +0.126755);\n      if(runera==y2016F) METxcorr = -(-0.0161259*npv +0.516919);\n      if(runera==y2016F) METycorr = -(0.141176*npv +0.544062);\n      if(runera==y2016G) METxcorr = -(0.0583851*npv +-0.0987447);\n      if(runera==y2016G) METycorr = -(0.0641427*npv +0.319112);\n      if(runera==y2016H) METxcorr = -(0.0706267*npv +-0.13118);\n      if(runera==y2016H) METycorr = -(0.127481*npv +0.370786);\n      if(runera==y2017B) METxcorr = -(-0.19563*npv +1.51859);\n      if(runera==y2017B) METycorr = -(0.306987*npv +-1.84713);\n      if(runera==y2017C) METxcorr = -(-0.161661*npv +0.589933);\n      if(runera==y2017C) METycorr = -(0.233569*npv +-0.995546);\n      if(runera==y2017D) METxcorr = -(-0.180911*npv +1.23553);\n      if(runera==y2017D) METycorr = -(0.240155*npv +-1.27449);\n      if(runera==y2017E) METxcorr = -(-0.149494*npv +0.901305);\n      if(runera==y2017E) METycorr = -(0.178212*npv +-0.535537);\n      if(runera==y2017F) METxcorr = -(-0.165154*npv +1.02018);\n      if(runera==y2017F) METycorr = -(0.253794*npv +0.75776);\n      if(runera==y2018A) METxcorr = -(0.362642*npv +-1.55094);\n      if(runera==y2018A) METycorr = -(0.0737842*npv +-0.677209);\n      if(runera==y2018B) METxcorr = -(0.485614*npv +-2.45706);\n      if(runera==y2018B) METycorr = -(0.181619*npv +-1.00636);\n      if(runera==y2018C) METxcorr = -(0.503638*npv +-1.01281);\n      if(runera==y2018C) METycorr = -(0.147811*npv +-1.48941);\n      if(runera==y2018D) METxcorr = -(0.520265*npv +-1.20322);\n      if(runera==y2018D) METycorr = -(0.143919*npv +-0.979328);\n      if(runera==y2016MC) METxcorr = -(-0.159469*npv +-0.407022);\n      if(runera==y2016MC) METycorr = -(-0.0405812*npv +0.570415);\n      if(runera==y2017MC) METxcorr = -(-0.182569*npv +0.276542);\n      if(runera==y2017MC) METycorr = -(0.155652*npv +-0.417633);\n      if(runera==y2018MC) METxcorr = -(0.299448*npv +-0.13866);\n      if(runera==y2018MC) METycorr = -(0.118785*npv +0.0889588);\n    }\n    \n    double CorrectedMET_x = uncormet *cos( uncormet_phi)+METxcorr;\n    double CorrectedMET_y = uncormet *sin( uncormet_phi)+METycorr;\n    \n    double CorrectedMET = sqrt(CorrectedMET_x*CorrectedMET_x+CorrectedMET_y*CorrectedMET_y);\n    double CorrectedMETPhi;\n    if(CorrectedMET_x==0 && CorrectedMET_y>0) CorrectedMETPhi = TMath::Pi();\n    else if(CorrectedMET_x==0 && CorrectedMET_y<0 )CorrectedMETPhi = -TMath::Pi();\n    else if(CorrectedMET_x >0) CorrectedMETPhi = TMath::ATan(CorrectedMET_y/CorrectedMET_x);\n    else if(CorrectedMET_x <0&& CorrectedMET_y>0) CorrectedMETPhi = TMath::ATan(CorrectedMET_y/CorrectedMET_x) + TMath::Pi();\n    else if(CorrectedMET_x <0&& CorrectedMET_y<0) CorrectedMETPhi = TMath::ATan(CorrectedMET_y/CorrectedMET_x) - TMath::Pi();\n    else CorrectedMETPhi =0;\n    \n    TheXYCorr_Met_MetPhi.first= CorrectedMET;\n    TheXYCorr_Met_MetPhi.second= CorrectedMETPhi;\n    //std::cout << \"runera \" << runera << \" pt shift: \" << (CorrectedMET - uncormet) << \" phi shift: \" << (CorrectedMETPhi - uncormet_phi) << std::endl;\n    return TheXYCorr_Met_MetPhi;\n    \n  }\n}\n#endif\n", "meta": {"hexsha": "2ae28ad01b79cbaddec5df60e40641b26de53ea4", "size": 164223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RDF/FTFunctions.cpp", "max_stars_repo_name": "NJManganelli/FourTopNAOD", "max_stars_repo_head_hexsha": "9743d5b49bdbad27a74abb7b2d5b7295f678a0e3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T17:29:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T17:29:38.000Z", "max_issues_repo_path": "RDF/FTFunctions.cpp", "max_issues_repo_name": "NJManganelli/FourTopNAOD", "max_issues_repo_head_hexsha": "9743d5b49bdbad27a74abb7b2d5b7295f678a0e3", "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": "RDF/FTFunctions.cpp", "max_forks_repo_name": "NJManganelli/FourTopNAOD", "max_forks_repo_head_hexsha": "9743d5b49bdbad27a74abb7b2d5b7295f678a0e3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-15T10:56:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T10:56:50.000Z", "avg_line_length": 73.3465832961, "max_line_length": 234, "alphanum_fraction": 0.72651821, "num_tokens": 54576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.186158617427378}}
{"text": "/*******\nedit_distance: STL and Boost compatible edit distance functions for C++\n\nCopyright (c) 2013 Erik Erlandson\n\nAuthor:  Erik Erlandson <erikerlandson@yahoo.com>\n\nDistributed under the Boost Software License, Version 1.0.\nSee accompanying file LICENSE or copy at\nhttp://www.boost.org/LICENSE_1_0.txt\n*******/\n\n#if !defined(BOOST_ALGORITHM_SEQUENCE_DETAIL_EDIT_DISTANCE_TYPES_HPP)\n#define BOOST_ALGORITHM_SEQUENCE_DETAIL_EDIT_DISTANCE_TYPES_HPP\n\n#include <cstddef>\n#include <iterator>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_io.hpp>\n\n#include <boost/exception/exception.hpp>\n\n#include <boost/type_traits.hpp>\n#include <boost/type_traits/is_arithmetic.hpp>\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/typeof/std/utility.hpp>\n\n#include <boost/function_types/result_type.hpp>\n#include <boost/function_types/function_arity.hpp>\n#include <boost/function_types/parameter_types.hpp>\n\n#include <boost/tti/has_type.hpp>\n#include <boost/tti/has_member_function.hpp>\n\n#include <boost/range/metafunctions.hpp>\n#include <boost/range/as_literal.hpp>\n\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/logical.hpp>\n#include <boost/mpl/equal_to.hpp>\n\n#include <boost/concept/assert.hpp>\n#include <boost/concept/usage.hpp>\n\n#include <boost/unordered_set.hpp>\n#include <boost/functional/hash.hpp>\n\n#include <boost/parameter/name.hpp>\n#include <boost/parameter/preprocessor.hpp>\n\nnamespace boost {\nnamespace algorithm {\nnamespace sequence {\n\nstruct unit_cost {\n    typedef size_t cost_type;\n\n    template <typename value_type> inline\n    cost_type insertion(value_type const&) const {\n        return cost_type(1);\n    }\n\n    template <typename value_type> inline\n    cost_type deletion(value_type const&) const {\n        return cost_type(1);\n    }\n\n    template <typename value_type_1, typename value_type_2> inline\n    cost_type substitution(value_type_1 const&, value_type_2 const&) const {\n        return cost_type(1);\n    }\n};\n\n\nstruct max_edit_cost_exception : public boost::exception {};\n\n\nnamespace parameter {\n    BOOST_PARAMETER_NAME(sequence1)\n    BOOST_PARAMETER_NAME(sequence2)\n    BOOST_PARAMETER_NAME(cost)\n    BOOST_PARAMETER_NAME(equal)\n    BOOST_PARAMETER_NAME(script)\n    BOOST_PARAMETER_NAME(substitution)\n    BOOST_PARAMETER_NAME(max_cost)\n    BOOST_PARAMETER_NAME(max_cost_exception)\n}\n\n\nnamespace detail {\n\nusing boost::is_same;\nusing boost::is_member_function_pointer;\nusing boost::integral_constant;\nusing boost::false_type;\nusing boost::true_type;\nusing boost::function_types::result_type;\nusing boost::function_types::parameter_types;\nusing boost::function_types::function_arity;\nusing boost::mpl::at_c;\nusing boost::mpl::and_;\nusing boost::mpl::not_;\nusing boost::mpl::equal_to;\nusing boost::enable_if;\n\ntemplate <typename X> struct invoke : public true_type {};\n\nstruct none {};\n\ntemplate <typename T> inline T& nonconst_default() {\n    static T r;\n    return r;\n}\n\ntemplate <typename Range1, typename Range2, typename Tag> struct range_category : public\n    and_<is_same<typename std::iterator_traits<typename boost::range_iterator<Range1>::type>::iterator_category, Tag>,\n         is_same<typename std::iterator_traits<typename boost::range_iterator<Range2>::type>::iterator_category, Tag> > {};\n\ntemplate <typename MaxCost, typename CostT, typename Node, typename Enable = void> struct max_cost_checker {};\n\ntemplate <typename MaxCost, typename CostT, typename Node>\nstruct max_cost_checker<MaxCost, CostT, Node, typename enable_if<is_same<MaxCost, none> >::type> {\n    typedef typename Node::pos1_type pos1_type;\n    typedef typename Node::pos2_type pos2_type;\n    max_cost_checker(const MaxCost&, const pos1_type&, const pos2_type&) {}\n    inline bool operator()(const CostT&) const { return false; }\n    inline void update(const Node*) const {}\n    inline void get(Node*&) const {}\n};\n\ntemplate <typename MaxCost, typename CostT, typename Node>\nstruct max_cost_checker<MaxCost, CostT, Node, typename enable_if<is_arithmetic<MaxCost> >::type> {\n    typedef typename Node::pos1_type pos1_type;\n    typedef typename Node::pos2_type pos2_type;\n    typedef typename pos1_type::difference_type diff_type;\n\n    CostT max_cost;\n    pos1_type beg1;\n    pos2_type beg2;\n    diff_type mcmin;\n    diff_type mctec;\n    Node* mcnode;\n\n    max_cost_checker(const MaxCost& max_cost_, const pos1_type& pos1_, const pos2_type& pos2_) : max_cost(CostT(std::abs(max_cost_))), beg1(pos1_), beg2(pos2_), mcmin(-1), mctec(-1), mcnode(NULL) {}\n    inline bool operator()(const CostT& c) const { return c > max_cost; }\n    inline void update(Node* node) {\n        // primary criteria:  position that consumes most sequence elements\n        diff_type ttec = (node->pos1 - beg1) + (node->pos2 - beg2);\n        if (ttec < mctec) return;\n\n        // secondary criteria: favor positions closest to diagonal\n        diff_type tmin = std::min(node->pos1 - beg1, node->pos2 - beg2);\n        if (ttec > mctec  ||  tmin > mcmin) {\n            mcnode = node;\n            mctec = ttec;\n            mcmin = tmin;\n        }\n    }\n    inline void get(Node*& node) const {\n        node = mcnode;\n    }\n};\n\nstruct remainder {\n    enum kind { none, forward, reverse, bidirectional };\n};\n\ntemplate <typename MaxCost, typename CostT, typename Pos, typename Enable = void> struct max_cost_checker_myers {};\n\ntemplate <typename MaxCost, typename CostT, typename Pos>\nstruct max_cost_checker_myers<MaxCost, CostT, Pos, typename enable_if<is_same<MaxCost, none> >::type> {\n    max_cost_checker_myers(const MaxCost&) {}\n    inline bool operator()(const CostT&) const { return false; }\n    inline void update(const Pos&, const Pos&, const CostT&) const {}\n    inline void get(Pos&, Pos&, CostT&) const {}\n    template <typename Itr>\n    inline void update(const Pos&, const Itr&, const Itr&, const Pos&, const Pos&, const Pos&, const Pos&) const {}\n    inline void get(Pos&, remainder::kind&) const {}\n};\n\ntemplate <typename MaxCost, typename CostT, typename Pos>\nstruct max_cost_checker_myers<MaxCost, CostT, Pos, typename enable_if<is_arithmetic<MaxCost> >::type> {\n    CostT max_cost;\n    Pos mcmin;\n    Pos mctec;\n    Pos mck;\n    remainder::kind kind;\n\n    max_cost_checker_myers(const MaxCost& max_cost_) : max_cost(CostT(std::abs(max_cost_))), mcmin(-1), mctec(-1), mck(0), kind(remainder::none) {}\n    inline bool operator()(const CostT& c) const { return c > max_cost; }\n    template <typename Itr>\n    inline void update(const Pos& k, const Itr& Vf, const Itr& Vr, const Pos& delta, const Pos& L1, const Pos& L2, const Pos& D) {\n        Pos j1f = Vf[k];\n        Pos j2f = Vf[k]-k;\n        Pos cf = j1f+j2f;\n        \n        // test bi-directional path\n        if ((k-delta) >= -D  &&  (k-delta) <= D) {\n            Pos j1r = Vr[k];\n            Pos j2r = Vr[k]-k;\n            Pos cr = (L1-j1r)+(L2-j2r);\n\n            Pos ttec = cf+cr;\n            if (ttec < mctec) return;\n            \n            Pos tmin = std::min(j1f, j2f);\n            if (ttec > mctec  ||  tmin > mcmin) {\n                mctec = ttec;\n                mcmin = tmin;\n                mck = k;\n                kind = remainder::bidirectional;\n            }\n\n            // if a bidirectional path is available, that will be the best possible for this (k),\n            // so we do not have to test forward/reverse individually:\n            return;\n        }\n\n        // test forward path\n        if (cf >= mctec) {\n            Pos tmin = std::min(j1f, j2f);\n            if (cf > mctec || tmin > mcmin) {\n                mctec = cf;\n                mcmin = tmin;\n                mck = k;\n                kind = remainder::forward;\n            }\n        }\n\n        // test reverse path\n        Pos j1r = Vr[k+delta];\n        Pos j2r = Vr[k+delta]-(k+delta);\n        Pos cr = (L1-j1r)+(L2-j2r);\n        if (cr >= mctec) {\n            Pos tmin = std::min((L1-j1r), (L2-j2r));\n            if (cr > mctec  ||  tmin > mcmin) {\n                mctec = cr;\n                mcmin = tmin;\n                mck = k+delta;\n                kind = remainder::reverse;\n            }    \n        }\n    }\n\n    inline void get(Pos& k_, remainder::kind& kind_) const {\n        k_ = mck;\n        kind_ = kind;\n    }\n};\n\n\nstruct default_equal {\n    template <typename T1, typename T2>\n    inline bool operator()(const T1& a, const T2& b) const { return a == b; }\n};\n\n\ntemplate <typename AllowSub, typename Cost, typename CostT, typename Output, typename Enable=void>\nstruct sub_checker {\n    // informative compile error here \n};\n\ntemplate <typename AllowSub, typename Cost, typename CostT, typename Output>\nstruct sub_checker<AllowSub, Cost, CostT, Output, typename enable_if<is_same<AllowSub, bool> >::type> {\n    bool allow;\n    sub_checker(const bool& allow_) : allow(allow_) {}\n    inline bool operator()() const { return allow; }\n    template <typename V1, typename V2> inline CostT substitution(const Cost& cost, const V1& v1, const V2& v2) const { return cost.substitution(v1, v2); }\n    template <typename V1, typename V2> inline void substitution(Output& out, const V1& v1, const V2& v2, const CostT& csub) const { out.substitution(v1, v2, csub); }\n};\n\ntemplate <typename AllowSub, typename Cost, typename CostT, typename Output>\nstruct sub_checker<AllowSub, Cost, CostT, Output, typename enable_if<is_same<AllowSub, true_type> >::type> {\n    sub_checker(const AllowSub&) {}\n    inline bool operator()() const { return true; }\n    template <typename V1, typename V2> inline CostT substitution(const Cost& cost, const V1& v1, const V2& v2) const { return cost.substitution(v1, v2); }\n    template <typename V1, typename V2> inline void substitution(Output& out, const V1& v1, const V2& v2, const CostT& csub) const { out.substitution(v1, v2, csub); }\n};\n\ntemplate <typename AllowSub, typename Cost, typename CostT, typename Output>\nstruct sub_checker<AllowSub, Cost, CostT, Output, typename enable_if<is_same<AllowSub, false_type> >::type> {\n    sub_checker(const AllowSub&) {}\n    inline bool operator()() const { return false; }\n    template <typename V1, typename V2> inline CostT substitution(const Cost&, const V1&, const V2&) const { return 0; }\n    template <typename V1, typename V2> inline void substitution(Output&, const V1&, const V2&, const CostT&) const {}\n};\n\n\ntemplate <typename Itr, typename Enabled=void>\nstruct position {\n    typedef Itr itr_type;\n    typedef typename std::iterator_traits<Itr>::difference_type idx_type;\n    typedef typename std::iterator_traits<Itr>::difference_type difference_type;\n    typedef typename std::iterator_traits<Itr>::value_type value_type;\n    typedef typename std::iterator_traits<Itr>::reference reference;\n\n    itr_type j;\n    idx_type idx;\n\n    inline void beg(const itr_type& src) { j = src;  idx = 0; }\n\n    inline reference operator*() { return *j; }\n    inline bool operator==(const itr_type& rhs) const { return j == rhs; }\n    inline bool operator!=(const itr_type& rhs) const { return j != rhs; }\n    inline bool operator<(const position& rhs) const { return idx < rhs.idx; }\n    inline position& operator++() { ++j; ++idx; return *this; }\n    inline difference_type operator-(const position& rhs) const { return idx - rhs.idx; }\n};\n\ntemplate <typename Itr>\nstruct position<Itr, typename enable_if<is_same<typename std::iterator_traits<Itr>::iterator_category, std::random_access_iterator_tag> >::type> {\n    typedef Itr itr_type;\n    typedef typename std::iterator_traits<Itr>::difference_type idx_type;\n    typedef typename std::iterator_traits<Itr>::difference_type difference_type;\n    typedef typename std::iterator_traits<Itr>::value_type value_type;\n    typedef typename std::iterator_traits<Itr>::reference reference;\n\n    itr_type j;\n\n    inline void beg(const itr_type& src) { j = src; }\n\n    inline reference operator*() { return *j; }\n    inline bool operator==(const itr_type& rhs) const { return j == rhs; }\n    inline bool operator!=(const itr_type& rhs) const { return j != rhs; }\n    inline bool operator<(const position& rhs) const { return j < rhs.j; }\n    inline position& operator++() { ++j; return *this; }    \n    inline difference_type operator-(const position& rhs) const { return j - rhs.j; }\n};\n\ntemplate <typename Itr1, typename Itr2, typename Cost>\nstruct path_head {\n    typedef position<Itr1> pos1_type;\n    typedef position<Itr2> pos2_type;\n\n    pos1_type pos1;\n    pos2_type pos2;\n    Cost cost;\n};\n\ntemplate <typename Itr1, typename Itr2, typename Cost>\nstruct path_node : public path_head<Itr1, Itr2, Cost> {\n    struct path_node* edge;\n};\n\ntemplate <typename Pool, typename Visited, typename Pos1, typename Pos2, typename Cost>\ninline\npath_head<typename Pos1::itr_type, typename Pos2::itr_type, Cost>*\nconstruct(Pool& pool, Visited& visited, const Pos1& pos1_, const Pos2& pos2_, const Cost& cost_) {\n    typedef path_head<typename Pos1::itr_type, typename Pos2::itr_type, Cost> head_t;\n    head_t w;\n    w.pos1 = pos1_;\n    w.pos2 = pos2_;\n    typename Visited::iterator f(visited.find(&w));\n    if (visited.end() != f   &&   cost_ >= (*f)->cost) return static_cast<head_t*>(NULL);\n    head_t* r = pool.construct();\n    r->pos1 = pos1_;\n    r->pos2 = pos2_;\n    r->cost = cost_;\n    if (visited.end() != f) visited.erase(f);\n    visited.insert(r);\n    return r;\n}\n\ntemplate <typename Pool, typename Visited, typename Pos1, typename Pos2, typename Cost>\ninline\npath_node<typename Pos1::itr_type, typename Pos2::itr_type, Cost>*\nconstruct(Pool& pool, Visited& visited, const Pos1& pos1_, const Pos2& pos2_, const Cost& cost_, path_node<typename Pos1::itr_type, typename Pos2::itr_type, Cost>* const& edge_) {\n    typedef path_node<typename Pos1::itr_type, typename Pos2::itr_type, Cost> head_t;\n    head_t w;\n    w.pos1 = pos1_;\n    w.pos2 = pos2_;\n    typename Visited::iterator f(visited.find(&w));\n    if (visited.end() != f   &&   cost_ >= (*f)->cost) return static_cast<head_t*>(NULL);\n    head_t* r = pool.construct();\n    r->pos1 = pos1_;\n    r->pos2 = pos2_;\n    r->cost = cost_;\n    r->edge = edge_;\n    if (visited.end() != f) visited.erase(f);\n    visited.insert(r);\n    return r;\n}\n\ntemplate <typename Pos1, typename Pos2>\nstruct heap_lessthan {\n    Pos1 beg1;\n    Pos2 beg2;\n    heap_lessthan(const Pos1& pos1_, const Pos2& pos2_) : beg1(pos1_), beg2(pos2_) {}\n    template <typename T> inline bool operator()(T const* a, T const* b) const {\n        return a->cost > b->cost;\n    }\n};\n\ntemplate <typename Pos1, typename Pos2>\nstruct visited_hash {\n    Pos1 beg1;\n    Pos2 beg2;\n    visited_hash(const Pos1& pos1_, const Pos2& pos2_) : beg1(pos1_), beg2(pos2_) {}\n    template<typename T> inline\n    size_t operator()(T const* e) const {\n        size_t h = 0;\n        boost::hash_combine(h, e->pos1-beg1);\n        boost::hash_combine(h, e->pos2-beg2);        \n        return h;\n    }\n};\n\nstruct visited_equal {\n    template<typename T> inline\n    bool operator()(T const* a, T const* b) const {\n        return (a->pos1.j == b->pos1.j) && (a->pos2.j == b->pos2.j);\n    }\n};\n\ntemplate <typename X>\nstruct ForwardRangeConvertible {\n    BOOST_CONCEPT_USAGE(ForwardRangeConvertible) {\n        // all I really want to capture here is that any sequence argument to edit_distance()\n        // and friends can be treated as a ForwardRange -- currently I'm doing this by\n        // applying as_literal() to all incoming arguments, which seems to allow me to send in\n        // null-terminated strings, ranges, sequence containers, etc, which is what I want.\n        boost::as_literal(x);\n    }\n    X x;\n};\n\n// I'm a little surprised this doesn't exist already\ntemplate <typename X>\nstruct Arithmetic {\n    BOOST_CONCEPT_USAGE(Arithmetic) {   \n        BOOST_STATIC_ASSERT(boost::is_arithmetic<X>::value);\n    }\n    X x;\n};\n\nBOOST_TTI_HAS_TYPE(cost_type)\n\ntemplate <typename X, typename V, typename Enable=void>\nstruct cost_type {\n    static X x;\n    static V v;\n    // by default, we infer cost_type from the return value of cost functions\n    typedef BOOST_TYPEOF(x.insertion(v)) type;\n};\n\ntemplate <typename X, typename V>\nstruct cost_type<X, V, typename enable_if<has_type_cost_type<X> >::type> {\n    // if the class explicitly defines a cost_type, then that is what we use\n    typedef typename X::cost_type type;\n};\n\n\ntemplate <typename X, typename Sequence, typename Enabled=void> struct TestCostSub {};\n\ntemplate <typename X, typename Sequence>\nstruct TestCostSub<X, Sequence, typename enable_if<invoke<BOOST_TYPEOF_TPL(&X::substitution)> >::type> {\n    typedef typename boost::range_value<Sequence>::type value_type;\n    typedef typename cost_type<X, value_type>::type cost_type;\n    BOOST_CONCEPT_USAGE(TestCostSub) {\n        c = x.substitution(v,v);\n    }\n\n    X x;\n    cost_type c;\n    value_type v;\n};\n\n\ntemplate <typename X, typename Sequence> struct SequenceAlignmentCost {\n    BOOST_CONCEPT_ASSERT((ForwardRangeConvertible<Sequence>));\n\n    typedef typename boost::range_value<Sequence>::type value_type;\n    typedef typename cost_type<X, value_type>::type cost_type;\n    BOOST_CONCEPT_ASSERT((Arithmetic<cost_type>));\n\n    BOOST_CONCEPT_USAGE(SequenceAlignmentCost) {\n        c = x.insertion(v);\n        c = x.deletion(v);\n    }\n\n    // test x.substitution() method, if it is defined \n    BOOST_CONCEPT_ASSERT((TestCostSub<X, Sequence>));\n\n    X x;\n    cost_type c;\n    value_type v;\n};\n\n\n}}}}\n\n#endif\n", "meta": {"hexsha": "0e680547da462678b68a1b942a805fd74f92d7cc", "size": 17345, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "includes/boost/algorithm/sequence/detail/edit_distance_types.hpp", "max_stars_repo_name": "marcus1337/BTMaker", "max_stars_repo_head_hexsha": "0525bfebb07832b8b0258fd6e9b668467558d1dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-10-22T05:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T14:03:12.000Z", "max_issues_repo_path": "includes/boost/algorithm/sequence/detail/edit_distance_types.hpp", "max_issues_repo_name": "marcus1337/BTMaker", "max_issues_repo_head_hexsha": "0525bfebb07832b8b0258fd6e9b668467558d1dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-01-23T20:26:59.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-23T20:26:59.000Z", "max_forks_repo_path": "includes/boost/algorithm/sequence/detail/edit_distance_types.hpp", "max_forks_repo_name": "marcus1337/BTMaker", "max_forks_repo_head_hexsha": "0525bfebb07832b8b0258fd6e9b668467558d1dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T04:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-27T04:38:41.000Z", "avg_line_length": 34.8993963783, "max_line_length": 198, "alphanum_fraction": 0.6781781493, "num_tokens": 4481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.186158617427378}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 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_UNITS_CODATA_ELECTRON_CONSTANTS_HPP\n#define BOOST_UNITS_CODATA_ELECTRON_CONSTANTS_HPP\n\n#include <boost/units/static_constant.hpp>\n\n#include <boost/units/systems/detail/constants.hpp>\n#include <boost/units/systems/si/amount.hpp>\n#include <boost/units/systems/si/area.hpp>\n#include <boost/units/systems/si/electric_charge.hpp>\n#include <boost/units/systems/si/energy.hpp>\n#include <boost/units/systems/si/frequency.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/wavenumber.hpp>\n\n#include <boost/units/systems/si/codata/typedefs.hpp>\n\n/// \\file\n/// CODATA recommended values of fundamental atomic and nuclear constants\n/// CODATA 2006 values as of 2007/03/30\n\nnamespace boost {\n\nnamespace units { \n\nnamespace si {\n                            \nnamespace constants {\n\nnamespace codata {\n\n/// CODATA recommended values of the fundamental physical constants: NIST SP 961\n\n/// electron mass\nBOOST_UNITS_PHYSICAL_CONSTANT(m_e,quantity<mass>,9.10938215e-31*kilograms,4.5e-38*kilograms);\n/// electron-muon mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_e_over_m_mu,quantity<dimensionless>,4.83633171e-3*dimensionless(),1.2e-10*dimensionless());\n/// electron-tau mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_e_over_m_tau,quantity<dimensionless>,2.87564e-4*dimensionless(),4.7e-8*dimensionless());\n/// electron-proton mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_e_over_m_p,quantity<dimensionless>,5.4461702177e-4*dimensionless(),2.4e-13*dimensionless());\n/// electron-neutron mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_e_over_m_n,quantity<dimensionless>,5.4386734459e-4*dimensionless(),3.3e-13*dimensionless());\n/// electron-deuteron mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_e_over_m_d,quantity<dimensionless>,2.7244371093e-4*dimensionless(),1.2e-13*dimensionless());\n/// electron-alpha particle mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_e_over_m_alpha,quantity<dimensionless>,1.37093355570e-4*dimensionless(),5.8e-14*dimensionless());\n/// electron charge to mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(e_over_m_e,quantity<electric_charge_over_mass>,1.758820150e11*coulombs/kilogram,4.4e3*coulombs/kilogram);\n/// electron molar mass\nBOOST_UNITS_PHYSICAL_CONSTANT(M_e,quantity<mass_over_amount>,5.4857990943e-7*kilograms/mole,2.3e-16*kilograms/mole);\n/// Compton wavelength\nBOOST_UNITS_PHYSICAL_CONSTANT(lambda_C,quantity<length>,2.4263102175e-12*meters,3.3e-21*meters);\n/// classical electron radius\nBOOST_UNITS_PHYSICAL_CONSTANT(r_e,quantity<length>,2.8179402894e-15*meters,5.8e-24*meters);\n/// Thompson cross section\nBOOST_UNITS_PHYSICAL_CONSTANT(sigma_e,quantity<area>,0.6652458558e-28*square_meters,2.7e-37*square_meters);\n/// electron magnetic moment\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e,quantity<energy_over_magnetic_flux_density>,-928.476377e-26*joules/tesla,2.3e-31*joules/tesla);\n/// electron-Bohr magenton moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e_over_mu_B,quantity<dimensionless>,-1.00115965218111*dimensionless(),7.4e-13*dimensionless());\n/// electron-nuclear magneton moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e_over_mu_N,quantity<dimensionless>,-183.28197092*dimensionless(),8.0e-7*dimensionless());\n/// electron magnetic moment anomaly\nBOOST_UNITS_PHYSICAL_CONSTANT(a_e,quantity<dimensionless>,1.15965218111e-3*dimensionless(),7.4e-13*dimensionless());\n/// electron g-factor\nBOOST_UNITS_PHYSICAL_CONSTANT(g_e,quantity<dimensionless>,-2.0023193043622*dimensionless(),1.5e-12*dimensionless());\n/// electron-muon magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e_over_mu_mu,quantity<dimensionless>,206.7669877*dimensionless(),5.2e-6*dimensionless());\n/// electron-proton magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e_over_mu_p,quantity<dimensionless>,-658.2106848*dimensionless(),5.4e-6*dimensionless());\n/// electron-shielded proton magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e_over_mu_p_prime,quantity<dimensionless>,-658.2275971*dimensionless(),7.2e-6*dimensionless());\n/// electron-neutron magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e_over_mu_n,quantity<dimensionless>,960.92050*dimensionless(),2.3e-4*dimensionless());\n/// electron-deuteron magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e_over_mu_d,quantity<dimensionless>,-2143.923498*dimensionless(),1.8e-5*dimensionless());\n/// electron-shielded helion magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_e_over_mu_h_prime,quantity<dimensionless>,864.058257*dimensionless(),1.0e-5*dimensionless());\n/// electron gyromagnetic ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(gamma_e,quantity<frequency_over_magnetic_flux_density>,1.760859770e11/second/tesla,4.4e3/second/tesla);\n\n} // namespace codata\n\n} // namespace constants    \n\n} // namespace si\n\n} // namespace units\n\n} // namespace boost\n\n#endif // BOOST_UNITS_CODATA_ELECTRON_CONSTANTS_HPP\n", "meta": {"hexsha": "131ba923955bbb3b9463b2304a13bf3c85359e84", "size": 5318, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/units/systems/si/codata/electron_constants.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "boost/boost/units/systems/si/codata/electron_constants.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/units/systems/si/codata/electron_constants.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 50.1698113208, "max_line_length": 135, "alphanum_fraction": 0.8106430989, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816806, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.1861586154802328}}
{"text": "#ifndef FAST_GICP_FAST_VGICP_HPP\n#define FAST_GICP_FAST_VGICP_HPP\n\n#include <unordered_map>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/registration/registration.h>\n\n#include <fast_gicp/gicp/gicp_settings.hpp>\n#include <fast_gicp/gicp/fast_gicp.hpp>\n#include <fast_gicp/gicp/fast_vgicp_voxel.hpp>\n\nnamespace fast_gicp {\n\n/**\n * @brief Fast Voxelized GICP algorithm boosted with OpenMP\n */\ntemplate<typename PointSource, typename PointTarget>\nclass FastVGICP : public FastGICP<PointSource, PointTarget> {\npublic:\n  using Scalar = float;\n  using Matrix4 = typename pcl::Registration<PointSource, PointTarget, Scalar>::Matrix4;\n\n  using PointCloudSource = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudSource;\n  using PointCloudSourcePtr = typename PointCloudSource::Ptr;\n  using PointCloudSourceConstPtr = typename PointCloudSource::ConstPtr;\n\n  using PointCloudTarget = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudTarget;\n  using PointCloudTargetPtr = typename PointCloudTarget::Ptr;\n  using PointCloudTargetConstPtr = typename PointCloudTarget::ConstPtr;\n\n#if PCL_VERSION >= PCL_VERSION_CALC(1, 10, 0)\n  using Ptr = pcl::shared_ptr<FastVGICP<PointSource, PointTarget>>;\n  using ConstPtr = pcl::shared_ptr<const FastVGICP<PointSource, PointTarget>>;\n#else\n  using Ptr = boost::shared_ptr<FastVGICP<PointSource, PointTarget>>;\n  using ConstPtr = boost::shared_ptr<const FastVGICP<PointSource, PointTarget>>;\n#endif\n\nprotected:\n  using pcl::Registration<PointSource, PointTarget, Scalar>::input_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::target_;\n\n  using FastGICP<PointSource, PointTarget>::num_threads_;\n  using FastGICP<PointSource, PointTarget>::source_kdtree_;\n  using FastGICP<PointSource, PointTarget>::target_kdtree_;\n  using FastGICP<PointSource, PointTarget>::source_covs_;\n  using FastGICP<PointSource, PointTarget>::target_covs_;\n\npublic:\n  FastVGICP();\n  virtual ~FastVGICP() override;\n\n  void setResolution(double resolution);\n  void setVoxelAccumulationMode(VoxelAccumulationMode mode);\n  void setNeighborSearchMethod(NeighborSearchMethod method);\n\n  virtual void swapSourceAndTarget() override;\n  virtual void setInputTarget(const PointCloudTargetConstPtr& cloud) override;\n\nprotected:\n  virtual void computeTransformation(PointCloudSource& output, const Matrix4& guess) override;\n  virtual void update_correspondences(const Eigen::Isometry3d& trans) override;\n  virtual double linearize(const Eigen::Isometry3d& trans, Eigen::Matrix<double, 6, 6>* H = nullptr, Eigen::Matrix<double, 6, 1>* b = nullptr) override;\n  virtual double compute_error(const Eigen::Isometry3d& trans) override;\n\nprotected:\n  double voxel_resolution_;\n  NeighborSearchMethod search_method_;\n  VoxelAccumulationMode voxel_mode_;\n\n  std::unique_ptr<GaussianVoxelMap<PointTarget>> voxelmap_;\n\n  std::vector<std::pair<int, GaussianVoxel::Ptr>> voxel_correspondences_;\n  std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>> voxel_mahalanobis_;\n};\n}  // namespace fast_gicp\n\n#endif\n", "meta": {"hexsha": "f57870a549aa9b4bd6b2c8b28a7cf806a39612b5", "size": 3166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fast_gicp/gicp/fast_vgicp.hpp", "max_stars_repo_name": "Gatsby23/fast_gicp", "max_stars_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "include/fast_gicp/gicp/fast_vgicp.hpp", "max_issues_repo_name": "Gatsby23/fast_gicp", "max_issues_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "include/fast_gicp/gicp/fast_vgicp.hpp", "max_forks_repo_name": "Gatsby23/fast_gicp", "max_forks_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 37.2470588235, "max_line_length": 152, "alphanum_fraction": 0.7950094757, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.1861477620201787}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2014 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2013 - 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_VMX_ALTIVEC_TRUNC_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_VMX_ALTIVEC_TRUNC_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_VMX_SUPPORT\n\n#include <boost/simd/arithmetic/functions/trunc.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( trunc_\n                                    , boost::simd::tag::vmx_\n                                    , (A0)\n                                    , ((simd_< single_<A0>\n                                            , boost::simd::tag::vmx_\n                                            >\n                                      ))\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return vec_trunc( a0() );\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "f5324988253759e747ea18b7b1969448d1b22ff3", "size": 1397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/vmx/altivec/trunc.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/vmx/altivec/trunc.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/vmx/altivec/trunc.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": 36.7631578947, "max_line_length": 80, "alphanum_fraction": 0.4731567645, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1861477546759651}}
{"text": "//\n// GraphTools library\n// Copyright 2017-2019 Illumina, Inc.\n// All rights reserved.\n//\n// Author: Roman Petrovski <RPetrovski@illumina.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#pragma once\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n\n#include <boost/algorithm/string/join.hpp>\n#include <boost/assert.hpp>\n\n#include \"dagAligner/AffineAlignMatrix.hh\"\n#include \"dagAligner/AffineAlignMatrixVectorized.hh\"\n#include \"dagAligner/PenaltyMatrix.hh\"\n\nnamespace graphalign\n{\n\nnamespace dagAligner\n{\n    /**\n     * Performs global alignment of query against DAG of target nodes.\n     * \\param clipFront true instructs to represent insertions at the start of CIGAR as soft clips\n     */\n    template <typename AlignMatrix, bool clipFront = true> class Aligner\n    {\n        AlignMatrix alignMatrix_;\n\n        // max number of best paths to backtrack\n        const std::size_t maxRepeats_;\n\n    public:\n        Aligner(\n            const typename AlignMatrix::PenaltyMatrix& penaltyMatrix, Score gapOpen, Score gapExt,\n            std::size_t maxRepeats = 10)\n            : alignMatrix_(penaltyMatrix, gapOpen, gapExt)\n            , maxRepeats_(maxRepeats)\n        {\n        }\n\n        template <typename QueryIt, typename TargetIt>\n        void __attribute((noinline))\n        align(QueryIt queryBegin, QueryIt queryEnd, TargetIt targetBegin, TargetIt targetEnd, const EdgeMap& edgeMap)\n        {\n            alignMatrix_.init(queryBegin, queryEnd, targetBegin, targetEnd, edgeMap);\n        }\n\n        struct Step\n        {\n            Cigar::OpCode operation_;\n            int q_;\n            int t_;\n        };\n\n        static bool removeDuplicateCigars(std::vector<Cigar>& cigars)\n        {\n            std::sort(cigars.begin(), cigars.end());\n            std::vector<Cigar>::iterator uniq = std::unique(cigars.begin(), cigars.end());\n            if (cigars.end() != uniq)\n            {\n                cigars.erase(uniq, cigars.end());\n                return true;\n            }\n\n            return false;\n        }\n        template <bool localAlign>\n        Score __attribute((noinline))\n        backtrackAllPaths(const EdgeMap& edgeMap, std::vector<Cigar>& cigars, Score& secondBestScore) const\n        {\n            Score bestScore = SCORE_MIN;\n            secondBestScore = SCORE_MIN;\n            typename AlignMatrix::const_iterator bestCell\n                = alignMatrix_.template nextBestAlign<localAlign>(alignMatrix_.alignBegin(), secondBestScore);\n            for (; alignMatrix_.alignEnd() != bestCell && bestScore <= secondBestScore;\n                 bestCell = alignMatrix_.template nextBestAlign<localAlign>(bestCell + 1, secondBestScore))\n            {\n                bestScore = secondBestScore;\n                const int t = alignMatrix_.targetOffset(bestCell);\n                const int q = alignMatrix_.queryOffset(bestCell);\n                const int softClip = alignMatrix_.queryLen() - 1 - q;\n\n                std::size_t firstNodeId = edgeMap.getNodeId(t);\n                Cigar start;\n                start.push_back(Cigar::Operation(Cigar::NODE_START, firstNodeId));\n                if (softClip)\n                {\n                    start.push_back(Cigar::Operation(Cigar::SOFT_CLIP, softClip));\n                }\n\n                if (!backtrackPath<true>(edgeMap, start, firstNodeId, q, t, cigars))\n                {\n                    // ran out of cigars buffer\n                    return bestScore;\n                }\n            }\n\n            removeDuplicateCigars(cigars);\n            if (1 < cigars.size())\n            {\n                // at least one duplicate, reset secondBestScore\n                secondBestScore = bestScore;\n            }\n            else if (alignMatrix_.alignEnd() == bestCell)\n            {\n                // one candidate only, no second best. Might had some duplicates, reset secondBestScore\n                secondBestScore = SCORE_MIN;\n            }\n            // else scondBest is set properly\n            return bestScore;\n        }\n\n        template <bool localAlign>\n        Cigar __attribute((noinline))\n        backtrackBestPath(const EdgeMap& edgeMap, Score& bestScore, Score& secondBestScore) const\n        {\n            bestScore = SCORE_MIN;\n            secondBestScore = SCORE_MIN;\n            typename AlignMatrix::const_iterator bestCell\n                = alignMatrix_.template nextBestAlign<localAlign>(alignMatrix_.alignBegin(), bestScore);\n            if (alignMatrix_.alignEnd() == bestCell)\n            {\n                throw std::logic_error(\"No best path available\");\n            }\n            std::vector<Cigar> ret;\n            const int t = alignMatrix_.targetOffset(bestCell);\n            const int q = alignMatrix_.queryOffset(bestCell);\n            const int softClip = alignMatrix_.queryLen() - 1 - q;\n\n            std::size_t firstNodeId = edgeMap.getNodeId(t);\n            Cigar start;\n            start.push_back(Cigar::Operation(Cigar::NODE_START, firstNodeId));\n            if (softClip)\n            {\n                start.push_back(Cigar::Operation(Cigar::SOFT_CLIP, softClip));\n            }\n\n            backtrackPath<false>(edgeMap, start, firstNodeId, q, t, ret);\n            alignMatrix_.template nextBestAlign<localAlign>(bestCell + 1, secondBestScore);\n            return ret.front();\n        }\n\n    private:\n        template <bool exploreAllPaths>\n        Step __attribute((noinline)) stepBack(\n            const EdgeMap& edgeMap, const Cigar& base, std::size_t lastNodeId, int q, int t,\n            std::vector<Cigar>& cigars) const\n        {\n            Step ret = { Cigar::UNKNOWN, q, t };\n\n            if (alignMatrix_.isInsertion(q, t))\n            {\n                const Cigar::OpCode code\n                    = (1 == base.length() && Cigar::NODE_START == base.lastOp()) || Cigar::SOFT_CLIP == base.lastOp()\n                    ? Cigar::SOFT_CLIP\n                    : Cigar::INSERT;\n                ret = Step{ code, q - 1, t };\n            }\n\n            EdgeMap::OffsetEdges::const_iterator prevNodeIndexIt = edgeMap.prevNodesBegin(t);\n            while (prevNodeIndexIt != edgeMap.prevNodesEnd(t))\n            {\n                const int p = *prevNodeIndexIt;\n                if (alignMatrix_.isDeletion(q, t, p))\n                {\n                    if (Cigar::UNKNOWN != ret.operation_ && exploreAllPaths)\n                    {\n                        // recurse if more than one path is possible\n                        if (!backtrackPath<true>(edgeMap, base + Cigar::DELETE, lastNodeId, q, p, cigars))\n                        {\n                            return Step{ Cigar::UNKNOWN, q, t };\n                        }\n                    }\n                    else\n                    {\n                        ret = Step{ Cigar::DELETE, q, p };\n                    }\n                }\n\n                if (alignMatrix_.isMatch(q, t, p))\n                {\n                    if (Cigar::UNKNOWN != ret.operation_ && exploreAllPaths)\n                    {\n                        // recurse if more than one path is possible\n                        if (!backtrackPath<true>(edgeMap, base + Cigar::MATCH, lastNodeId, q - 1, p, cigars))\n                        {\n                            return Step{ Cigar::UNKNOWN, q, t };\n                        }\n                    }\n                    else\n                    {\n                        ret = Step{ Cigar::MATCH, q - 1, p };\n                    }\n                }\n                else if (alignMatrix_.isMismatch(q, t, p))\n                {\n                    const Cigar::OpCode code = (1 == base.length() && Cigar::NODE_START == base.lastOp())\n                            || Cigar::SOFT_CLIP == base.lastOp()\n                        ? Cigar::SOFT_CLIP\n                        : Cigar::MISMATCH;\n                    if (Cigar::UNKNOWN != ret.operation_ && exploreAllPaths)\n                    {\n                        // recurse if more than one path is possible\n                        if (!backtrackPath<true>(edgeMap, base + code, lastNodeId, q - 1, p, cigars))\n                        {\n                            return Step{ Cigar::UNKNOWN, q, t };\n                        }\n                    }\n                    else\n                    {\n                        ret = Step{ code, q - 1, p };\n                    }\n                }\n\n                ++prevNodeIndexIt;\n            }\n\n            if (Cigar::UNKNOWN == ret.operation_)\n            {\n                throw std::logic_error(\"backtracking failure: no nodes found on best path!\");\n            }\n\n            // Return the one we have not recursed for. If only one path is possible, no recursion occurs\n            return ret;\n        }\n\n        template <bool exploreAllPaths>\n        bool backtrackPath(\n            const EdgeMap& edgeMap, const Cigar& base, std::size_t lastNodeId, int q, int t,\n            std::vector<Cigar>& cigars) const\n        {\n            Cigar ret = base;\n            while (-1 != t)\n            {\n                const std::size_t curNodeId = edgeMap.getNodeId(t);\n                if (lastNodeId != curNodeId)\n                {\n                    ret.push_back(Cigar::Operation(Cigar::NODE_END, lastNodeId));\n                    ret.push_back(Cigar::Operation(Cigar::NODE_START, curNodeId));\n                    lastNodeId = curNodeId;\n                }\n\n                Step step = stepBack<exploreAllPaths>(edgeMap, ret, lastNodeId, q, t, cigars);\n                if (Cigar::UNKNOWN == step.operation_)\n                {\n                    // ran out of cigars buffer\n                    return false;\n                }\n\n                ret.append(step.operation_);\n                q = step.q_;\n                t = step.t_;\n            }\n\n            if (-1 != q)\n            {\n                if (Cigar::DELETE == ret.lastOp())\n                {\n                    const Cigar::Operation del = ret.pop_back();\n                    ret.push_back(Cigar::Operation(Cigar::INSERT, q + 1));\n                    ret.push_back(del);\n                }\n                else\n                {\n                    ret.push_back(Cigar::Operation(Cigar::INSERT, q + 1));\n                }\n            }\n            // TODO: according to while loop above, this cannot happen. Code below is legacy for\n            // the original termination condition of while loop\n            else if (-1 != t) // we're either on -1 row or -1 column\n            {\n                // count number of bases to the start of the last node\n                const std::size_t nodeId = edgeMap.getNodeId(t + 1);\n                int cur = t + 1;\n                while (cur && edgeMap.getNodeId(cur - 1) == nodeId)\n                {\n                    --cur;\n                }\n                if (t + 1 != cur)\n                {\n                    ret.push_back(Cigar::Operation(Cigar::DELETE, t + 1 - cur));\n                }\n            }\n\n            if (clipFront && Cigar::INSERT == ret.lastOp())\n            {\n                ret.lastOp() = Cigar::SOFT_CLIP;\n            }\n            ret.push_back(Cigar::Operation(Cigar::NODE_END, lastNodeId));\n\n            ret.collapseLastEmptyNode();\n            ret.reverse();\n            if (cigars.size() == maxRepeats_ && !removeDuplicateCigars(cigars))\n            {\n                return false;\n            }\n            cigars.push_back(ret);\n            return true;\n        }\n\n        friend std::ostream& operator<<(std::ostream& os, const Aligner& aligner)\n        {\n            return os << \"Aligner(\" << aligner.alignMatrix_ << \")\";\n        }\n    };\n\n} // namespace dagAligner\n\n// template <bool penalizeMove>\n// class DagAligner\n//     : public dagAligner::Aligner<dagAligner::AffineAlignMatrix<dagAligner::FixedPenaltyMatrix, penalizeMove>>\n// {\n// public:\n// DagAligner(const dagAligner::FixedPenaltyMatrix& penaltyMatrix, dagAligner::Score gapOpen, dagAligner::Score gapExt)\n// : dagAligner::Aligner<dagAligner::AffineAlignMatrix<dagAligner::FixedPenaltyMatrix, penalizeMove>>(\n// penaltyMatrix, gapOpen, gapExt)\n// {\n// }\n//\n// DagAligner(dagAligner::Score match, dagAligner::Score mismatch, dagAligner::Score gapOpen, dagAligner::Score gapExt)\n// : dagAligner::Aligner<dagAligner::AffineAlignMatrix<dagAligner::FixedPenaltyMatrix, penalizeMove>>(\n// dagAligner::FixedPenaltyMatrix(match, mismatch), gapOpen, gapExt)\n// {\n// }\n// };\n\ntemplate <bool penalizeMove, bool clipFront = true, bool matchQueryN = true, bool matchTargetN = true>\nclass DagAligner : public dagAligner::Aligner<\n                       dagAligner::AffineAlignMatrixVectorized<\n                           dagAligner::FixedPenaltyMatrix<matchQueryN, matchTargetN>, penalizeMove>,\n                       clipFront>\n{\n    typedef dagAligner::FixedPenaltyMatrix<matchQueryN, matchTargetN> PenaltyMatrix;\n\npublic:\n    DagAligner(const PenaltyMatrix& penaltyMatrix, dagAligner::Score gapOpen, dagAligner::Score gapExt)\n        : dagAligner::Aligner<dagAligner::AffineAlignMatrixVectorized<PenaltyMatrix, penalizeMove>, clipFront>(\n              penaltyMatrix, gapOpen, gapExt)\n    {\n    }\n\n    DagAligner(dagAligner::Score match, dagAligner::Score mismatch, dagAligner::Score gapOpen, dagAligner::Score gapExt)\n        : dagAligner::Aligner<dagAligner::AffineAlignMatrixVectorized<PenaltyMatrix, penalizeMove>, clipFront>(\n              PenaltyMatrix(match, mismatch), gapOpen, gapExt)\n    {\n    }\n};\n\n// template <bool penalizeMove>\n// class DagAligner\n//     : public dagAligner::Aligner<dagAligner::AffineAlignMatrix<dagAligner::FreePenaltyMatrix, penalizeMove>>\n// {\n// public:\n//    DagAligner(const dagAligner::FreePenaltyMatrix& penaltyMatrix, dagAligner::Score gapOpen, dagAligner::Score\n//    gapExt)\n//        : dagAligner::Aligner<dagAligner::AffineAlignMatrix<dagAligner::FreePenaltyMatrix, penalizeMove>>(\n//              penaltyMatrix, gapOpen, gapExt)\n//    {\n//    }\n//\n//    DagAligner(dagAligner::Score match, dagAligner::Score mismatch, dagAligner::Score gapOpen, dagAligner::Score\n//    gapExt)\n//        : dagAligner::Aligner<dagAligner::AffineAlignMatrix<dagAligner::FreePenaltyMatrix, penalizeMove>>(\n//              dagAligner::FreePenaltyMatrix(match, mismatch), gapOpen, gapExt)\n//    {\n//    }\n// };\n\n} // namespace graphalign\n", "meta": {"hexsha": "b795877d84963ec575700a0109b6048d66d37a54", "size": 14776, "ext": "hh", "lang": "C++", "max_stars_repo_path": "thirdparty/graph-tools-master/include/graphalign/DagAlignerAffine.hh", "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": 122.0, "max_stars_repo_stars_event_min_datetime": "2017-01-06T16:19:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T00:05:50.000Z", "max_issues_repo_path": "thirdparty/graph-tools-master/include/graphalign/DagAlignerAffine.hh", "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": 90.0, "max_issues_repo_issues_event_min_datetime": "2017-01-04T00:23:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T12:55:52.000Z", "max_forks_repo_path": "thirdparty/graph-tools-master/include/graphalign/DagAlignerAffine.hh", "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": 35.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T13:39:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T17:34:11.000Z", "avg_line_length": 38.0824742268, "max_line_length": 120, "alphanum_fraction": 0.5450730915, "num_tokens": 3294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1861477546759651}}
{"text": "\ufeff#pragma once\n#include <EigenLinearSolvers/EigenDirectSparseSolver[CRS].h>\n\n#include <sofa/helper/ScopedAdvancedTimer.h>\n\nnamespace EigenLinearSolvers\n{\ntemplate <class TBlockType, class EigenSolver>\nvoid EigenDirectSparseSolver<\n    sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>,\n    sofa::linearalgebra::FullVector<typename sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>::Real>, EigenSolver>\n    ::init()\n{\n    updateSolverOderingMethod();\n}\n\ntemplate <class TBlockType, class EigenSolver>\nvoid EigenDirectSparseSolver<\n    sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>,\n    sofa::linearalgebra::FullVector<typename sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>::Real>, EigenSolver>\n    ::reinit()\n{\n    updateSolverOderingMethod();\n}\n\ntemplate <class TBlockType, class EigenSolver>\nvoid EigenDirectSparseSolver<sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>, sofa::linearalgebra::FullVector<typename sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>::Real>, EigenSolver >\n    ::solve(Matrix& A, Vector& x, Vector& b)\n{\n    SOFA_UNUSED(A);\n\n    EigenVectorXdMap xMap(x.ptr(), x.size());\n    EigenVectorXdMap bMap(b.ptr(), b.size());\n\n    std::visit([&bMap, &xMap](auto&& solver)\n    {\n        xMap = solver.solve(bMap);\n    }, m_solver);\n}\n\ntemplate <class TBlockType, class EigenSolver>\nvoid EigenDirectSparseSolver<sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>, sofa::linearalgebra::FullVector<typename sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>::Real>, EigenSolver >\n    ::invert(Matrix& A)\n{\n    {\n        sofa::helper::ScopedAdvancedTimer copyTimer(\"copyMatrixData\");\n        Mfiltered.copyNonZeros(A);\n        Mfiltered.compress();\n    }\n\n    if (!m_map)\n    {\n        m_map = std::make_unique<EigenSparseMatrixMap>(Mfiltered.rows(), Mfiltered.cols(), Mfiltered.getColsValue().size(),\n            (typename EigenSparseMatrixMap::StorageIndex*)Mfiltered.rowBegin.data(), (typename EigenSparseMatrixMap::StorageIndex*)Mfiltered.colsIndex.data(), Mfiltered.colsValue.data());\n    }\n\n    const bool analyzePattern = (MfilteredrowBegin != Mfiltered.rowBegin) || (MfilteredcolsIndex != Mfiltered.colsIndex);\n\n    if (analyzePattern)\n    {\n        sofa::helper::ScopedAdvancedTimer patternAnalysisTimer(\"patternAnalysis\");\n        std::visit([this](auto&& solver)\n        {\n            solver.analyzePattern(*m_map);\n        }, m_solver);\n\n        MfilteredrowBegin = Mfiltered.rowBegin;\n        MfilteredcolsIndex = Mfiltered.colsIndex;\n    }\n\n    {\n        sofa::helper::ScopedAdvancedTimer factorizeTimer(\"factorization\");\n        std::visit([this](auto&& solver)\n        {\n            solver.factorize(*m_map);\n        }, m_solver);\n    }\n\n    msg_error_when(getSolverInfo() == Eigen::ComputationInfo::InvalidInput) << \"Solver cannot factorize: invalid input\";\n    msg_error_when(getSolverInfo() == Eigen::ComputationInfo::NoConvergence) << \"Solver cannot factorize: no convergence\";\n    msg_error_when(getSolverInfo() == Eigen::ComputationInfo::NumericalIssue) << \"Solver cannot factorize: numerical issue\";\n}\n\ntemplate <class TBlockType, class EigenSolver>\nEigen::ComputationInfo EigenDirectSparseSolver<\n    sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>,\n    sofa::linearalgebra::FullVector<typename sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>::Real>, EigenSolver>\n::getSolverInfo() const\n{\n    Eigen::ComputationInfo info;\n    std::visit([&info](auto&& solver)\n    {\n        info = solver.info();\n    }, m_solver);\n    return info;\n}\n\ntemplate <class TBlockType, class EigenSolver>\nvoid EigenDirectSparseSolver<sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>, sofa::linearalgebra::FullVector\n<typename sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>::Real>, EigenSolver>::updateSolverOderingMethod()\n{\n    if (m_selectedOrderingMethod != d_orderingMethod.getValue().getSelectedId())\n    {\n        switch(d_orderingMethod.getValue().getSelectedId())\n        {\n        case 0:  m_solver.template emplace<std::variant_alternative_t<0, decltype(m_solver)> >(); break;\n        case 1:  m_solver.template emplace<std::variant_alternative_t<1, decltype(m_solver)> >(); break;\n        case 2:  m_solver.template emplace<std::variant_alternative_t<2, decltype(m_solver)> >(); break;\n#if EIGENLINEARSOLVERS_HAS_METIS_INCLUDE == 1\n        case 3:  m_solver.template emplace<std::variant_alternative_t<3, decltype(m_solver)> >(); break;\n#endif\n        default: m_solver.template emplace<std::variant_alternative_t<1, decltype(m_solver)> >(); break;\n        }\n        m_selectedOrderingMethod = d_orderingMethod.getValue().getSelectedId();\n        if (m_selectedOrderingMethod >= std::variant_size_v<decltype(m_solver)>)\n            m_selectedOrderingMethod = 1;\n\n        MfilteredrowBegin.clear();\n        MfilteredcolsIndex.clear();\n        m_map.reset();\n    }\n}\n\ntemplate <class TBlockType, class EigenSolver>\nEigenDirectSparseSolver<sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>, sofa::linearalgebra::FullVector<\ntypename sofa::linearalgebra::CompressedRowSparseMatrix<TBlockType>::Real>, EigenSolver>::EigenDirectSparseSolver()\n    : Inherit1()\n    , d_orderingMethod(initData(&d_orderingMethod, \"ordering\", \"Ordering method\"))\n{\n#if EIGENLINEARSOLVERS_HAS_METIS_INCLUDE == 1\n    sofa::helper::OptionsGroup d_orderingMethodOptions(4,\"Natural\", \"AMD\", \"COLAMD\", \"Metis\");\n#else\n    sofa::helper::OptionsGroup d_orderingMethodOptions(3,\"Natural\", \"AMD\", \"COLAMD\");\n#endif\n\n    d_orderingMethodOptions.setSelectedItem(1); // default None\n    d_orderingMethod.setValue(d_orderingMethodOptions);\n}\n\n}\n", "meta": {"hexsha": "29cfd5cc855ab7271d073ec7b624387e9ca7f260", "size": 5662, "ext": "inl", "lang": "C++", "max_stars_repo_path": "src/EigenLinearSolvers/EigenDirectSparseSolver[CRS].inl", "max_stars_repo_name": "alxbilger/EigenLinearSolvers", "max_stars_repo_head_hexsha": "d6218d59984a43a333f1d33f749ae2b102b0d963", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T06:51:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:51:12.000Z", "max_issues_repo_path": "src/EigenLinearSolvers/EigenDirectSparseSolver[CRS].inl", "max_issues_repo_name": "alxbilger/EigenLinearSolvers", "max_issues_repo_head_hexsha": "d6218d59984a43a333f1d33f749ae2b102b0d963", "max_issues_repo_licenses": ["MIT"], "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/EigenLinearSolvers/EigenDirectSparseSolver[CRS].inl", "max_forks_repo_name": "alxbilger/EigenLinearSolvers", "max_forks_repo_head_hexsha": "d6218d59984a43a333f1d33f749ae2b102b0d963", "max_forks_repo_licenses": ["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.1560283688, "max_line_length": 210, "alphanum_fraction": 0.7292476157, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.18614775100385833}}
{"text": "/**************************************************************************\n** Copyright (C) 2020 MS-Cheminformatics LLC\n*\n** Contact: info@ms-cheminfo.com\n**\n** Commercial Usage\n**\n** Licensees holding valid MS-Cheminformatics commercial licenses may use this file in\n** accordance with the MS-Cheminformatics Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and MS-Cheminformatics.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.TXT included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\n**\n**************************************************************************/\n\n#pragma once\n\n// #include \"adportable_global.h\"\n#include <date/date.h>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/format.hpp>\n#include <chrono>\n#include <ctime>\n#include <iostream>\n#include <string>\n#include <type_traits>\n\nnamespace adportable {\n\n    struct /* ADPORTABLESHARED_EXPORT */ subseconds {\n        static std::string to_str( int64_t, size_t n );\n    };\n\n    template< bool is_system_clock = true >\n    struct date_time_t {\n        template< typename duration_t, typename time_point_t >\n        std::pair< std::time_t, duration_t > to_time_t( time_point_t tp ) {\n            // std::cout << \"-- system_clock -->\";\n            auto utc = std::chrono::system_clock::to_time_t( std::chrono::time_point_cast< std::chrono::system_clock::duration >( tp ) );\n            return { utc, duration_t( std::chrono::time_point_cast< duration_t >( tp ) - date::floor< std::chrono::seconds >( tp ) ) };\n        }\n    };\n\n    template<>\n    template< typename duration_t, typename time_point_t >\n    std::pair< std::time_t, duration_t >\n    date_time_t< false >::to_time_t( time_point_t tp ) {\n        typedef typename decltype( tp )::clock clock_t;\n        // std::cout << \"-- steady_clock -->\";\n        auto tt = std::chrono::time_point_cast< duration_t >( std::chrono::system_clock::now() ) + ( tp - clock_t::now() );\n        auto utc = std::chrono::system_clock::to_time_t( std::chrono::time_point_cast< std::chrono::system_clock::duration >( tt ) );\n        return { utc, std::chrono::duration_cast< duration_t >( tt - date::floor< std::chrono::seconds >( tt ) ) };\n    }\n\n    template< uint64_t N > struct num_digits {\n        enum { value = 1 + num_digits< N / 10 >::value };\n    };\n\n    template<> struct num_digits<0> {\n        enum { value = 0 };\n    };\n\n    struct date_time {\n\n        template< typename duration_t, typename time_point_t >\n        static std::string to_iso( time_point_t tp, bool utc_offset = true ) {\n            typedef typename decltype( tp )::clock clock_t;\n#if __cplusplus < 201703L\n            std::time_t utc; duration_t subseconds;\n            std::tie( utc, subseconds )\n#else\n            auto [utc, subseconds]\n#endif\n                  = date_time_t< std::is_same< clock_t, std::chrono::system_clock >::value >(). template to_time_t< duration_t >( tp );\n\n            // subseconds_t< num_digits< duration_t::period::den >::value - 1 > subseconds_to_string;\n            constexpr size_t N = num_digits< duration_t::period::den >::value - 1;\n\n            std::ostringstream o;\n            if ( utc_offset ) {\n                auto tz( boost::posix_time::second_clock::local_time() - boost::posix_time::second_clock::universal_time() );\n                o << std::put_time( std::localtime(&utc), \"%FT%T\" ) << subseconds::to_str( subseconds.count(), N )\n                  << boost::format( \"%c%02d%02d\" )\n                    % (tz.is_negative() ? '-' : '+')\n                    % boost::date_time::absolute_value( tz.hours() )\n                    % boost::date_time::absolute_value( tz.minutes() );\n            } else {\n                auto syst = std::chrono::time_point_cast< duration_t >( std::chrono::system_clock::from_time_t( utc ) ) + duration_t( subseconds );\n                o << date::format(\"%FT%TZ\", syst );\n            }\n            return o.str();\n        }\n    };\n}\n", "meta": {"hexsha": "3139ea87aeb6e04932ad025aaf27a58ff2ac3585", "size": 4383, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tools/injctl/date_time.hpp", "max_stars_repo_name": "qtplatz/socfpga_modules", "max_stars_repo_head_hexsha": "5f1ecc950bcb46f361970ff50176502c2ff17df1", "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/tools/injctl/date_time.hpp", "max_issues_repo_name": "qtplatz/socfpga_modules", "max_issues_repo_head_hexsha": "5f1ecc950bcb46f361970ff50176502c2ff17df1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-30T10:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T10:06:23.000Z", "max_forks_repo_path": "src/tools/injctl/date_time.hpp", "max_forks_repo_name": "qtplatz/socfpga_modules", "max_forks_repo_head_hexsha": "5f1ecc950bcb46f361970ff50176502c2ff17df1", "max_forks_repo_licenses": ["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.5533980583, "max_line_length": 147, "alphanum_fraction": 0.6103125713, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.18614774402024992}}
{"text": "#include <complex>\n#include <exception>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <range/v3/all.hpp>\n#include <cstdint>\n#include <boost/icl/closed_interval.hpp>\n#include <boost/icl/interval_set.hpp>\nnamespace icl = boost::icl;\nusing gint = std::int64_t;\n\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    gint l, h;\n    icl::interval_set<gint> ips;\n    std::ifstream ifs(argv[1]);\n    while (ifs >> l >> h) {\n      icl::interval<gint>::type p(l, h);\n      ips.add(p);\n    }\n    std::cout << \"A\\n\";\n    int n = 0;\n    icl::interval_set<gint> ipsb = ips;\n    auto j = ips.begin();\n    ++j;\n    for (auto i = ips.begin(); i != ips.end() && (j != ips.end()); ++i, ++j) {\n      if (j->lower() - i->upper() == 1) {\n        icl::interval<gint>::type p(i->upper(), j->lower());\n        ipsb.add(p);\n      }\n    }\n    for (auto i = ipsb.begin(); i != ipsb.end(); ++i) {\n      std::cout << \"i:\" << *i << std::endl;\n      if (n == 1) {\n        break;\n      }\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "7c3fac78aceaadf28689c142c13451c14b7a6d76", "size": 1039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "game24/aoc162001.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "game24/aoc162001.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "game24/aoc162001.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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.0888888889, "max_line_length": 78, "alphanum_fraction": 0.5283926853, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.18600685481923762}}
{"text": "//\n// Expansion Hunter\n// Copyright 2016-2019 Illumina, Inc.\n// All rights reserved.\n//\n// Author: Egor Dolzhenko <edolzhenko@illumina.com>,\n//         Mitch Bekritsky <mbekritsky@illumina.com>, Richard Shaw\n// Concept: Michael Eberle <meberle@illumina.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#include \"genotyping/RepeatGenotyper.hh\"\n\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n\n#include <boost/math/distributions/poisson.hpp>\n\n#include \"genotyping/RegionLengthEstimation.hh\"\n#include \"genotyping/ShortRepeatGenotyper.hh\"\n\nnamespace ehunter\n{\n\nusing boost::optional;\nusing std::map;\nusing std::string;\nusing std::vector;\n\nstatic CountTable combineFlankingAndInrepeatReads(\n    int maxNumUnitsInRead, const CountTable& flankingCounts, const CountTable& inrepeatCounts)\n{\n    int maxNumReadsToTransfer = 5;\n    CountTable updatedFlankingCounts = flankingCounts;\n    for (int numUnits = maxNumUnitsInRead; numUnits != 0; --numUnits)\n    {\n        const int count = inrepeatCounts.countOf(numUnits);\n        const int countToTransfer = std::min(count, maxNumReadsToTransfer);\n\n        for (int counter = 0; counter != countToTransfer; ++counter)\n        {\n            updatedFlankingCounts.incrementCountOf(numUnits);\n        }\n\n        maxNumReadsToTransfer -= countToTransfer;\n        if (maxNumReadsToTransfer == 0)\n        {\n            break;\n        }\n    }\n\n    return updatedFlankingCounts;\n}\n\noptional<RepeatGenotype> RepeatGenotyper::genotypeRepeat(const vector<int32_t>& alleleSizeCandidates) const\n{\n    if (alleleSizeCandidates.empty())\n    {\n        return optional<RepeatGenotype>();\n    }\n\n    const CountTable countsOfFlankingReadsForShortRepeatGenotyper\n        = combineFlankingAndInrepeatReads(maxNumUnitsInRead_, countsOfFlankingReads_, countsOfInrepeatReads_);\n\n    ShortRepeatGenotyper shortRepeatGenotyper(repeatUnitLen_, maxNumUnitsInRead_, propCorrectMolecules_);\n\n    int repeatReadCount\n        = ::ehunter::countFullLengthRepeatReads(maxNumUnitsInRead_, countsOfFlankingReads_, countsOfInrepeatReads_);\n\n    const int minInrepeatReadsInLongExpansion = 1;\n    if (repeatReadCount >= minInrepeatReadsInLongExpansion)\n    {\n        repeatReadCount += 2 * countOfInrepeatReadPairs_;\n    }\n\n    if (expectedAlleleCount_ == AlleleCount::kOne)\n    {\n        RepeatGenotype genotype = shortRepeatGenotyper.genotypeRepeatWithOneAllele(\n            countsOfFlankingReadsForShortRepeatGenotyper, countsOfSpanningReads_, alleleSizeCandidates);\n\n        const bool isSpanningAllele = countsOfSpanningReads_.countOf(genotype.longAlleleSizeInUnits()) != 0;\n\n        if (!isSpanningAllele && repeatReadCount != 0)\n        {\n            extendGenotypeWhenOneAlleleIsRepeat(genotype, repeatReadCount);\n        }\n        else if (!isSpanningAllele)\n        {\n            extendGenotypeWhenOneAlleleIsFlanking(genotype);\n        }\n        else\n        {\n            assert(countsOfSpanningReads_.countOf(genotype.longAlleleSizeInUnits()));\n        }\n\n        return genotype;\n    }\n\n    assert(expectedAlleleCount_ == AlleleCount::kTwo);\n\n    RepeatGenotype genotype = shortRepeatGenotyper.genotypeRepeatWithTwoAlleles(\n        countsOfFlankingReadsForShortRepeatGenotyper, countsOfSpanningReads_, alleleSizeCandidates);\n\n    const bool shortAlleleIsSpanning = countsOfSpanningReads_.countOf(genotype.shortAlleleSizeInUnits()) != 0;\n    const bool longAlleleIsSpanning = countsOfSpanningReads_.countOf(genotype.longAlleleSizeInUnits()) != 0;\n    // const int repeatReadCount = countFullLengthRepeatReads();\n\n    if (!longAlleleIsSpanning && !shortAlleleIsSpanning && repeatReadCount != 0)\n    {\n        extendGenotypeWhenBothAllelesAreRepeat(genotype, repeatReadCount);\n    }\n    else if (!longAlleleIsSpanning && repeatReadCount != 0)\n    {\n        extendGenotypeWhenOneAlleleIsRepeat(genotype, repeatReadCount);\n    }\n    else if (shortAlleleIsSpanning && longAlleleIsSpanning)\n    {\n        // Nothing needs to be done.\n    }\n    else if (shortAlleleIsSpanning)\n    {\n        // assert(countsOfFlankingReads_.countOf(genotype.longAlleleSizeInUnits()));\n        extendGenotypeWhenOneAlleleIsFlanking(genotype);\n    }\n    else\n    {\n        // Both alleles must be flanking.\n        // assert(countsOfFlankingReads_.countOf(genotype.shortAlleleSizeInUnits()));\n        // assert(countsOfFlankingReads_.countOf(genotype.longAlleleSizeInUnits()));\n\n        extendGenotypeWhenBothAllelesAreFlanking(genotype);\n    }\n\n    return genotype;\n}\n\nvoid RepeatGenotyper::extendGenotypeWhenBothAllelesAreFlanking(RepeatGenotype& genotype) const\n{\n    // In some exceptional situations flanking reads might be filtered out before the extension step; if this happens,\n    // genotype extension is aborted.\n    if (countFlankingReadsLongerThanSpanning() == 0)\n    {\n        return;\n    }\n\n    int32_t flankingAlleleSize, flankingAlleleCiLower, flankingAlleleCiUpper;\n    estimateFlankingAlleleSize(flankingAlleleSize, flankingAlleleCiLower, flankingAlleleCiUpper);\n\n    // genotype.setLongAlleleSizeInUnits(flankingAlleleSize);\n    flankingAlleleCiLower = std::min(genotype.shortAlleleSizeInUnits(), flankingAlleleCiLower);\n    flankingAlleleCiUpper = std::max(genotype.longAlleleSizeInUnits(), flankingAlleleCiUpper);\n\n    genotype.setLongAlleleSizeInUnitsCi(flankingAlleleCiLower, flankingAlleleCiUpper);\n\n    // genotype.setShortAlleleSizeInUnits(flankingAlleleSize);\n    genotype.setShortAlleleSizeInUnitsCi(flankingAlleleCiLower, flankingAlleleCiUpper);\n}\n\nvoid RepeatGenotyper::extendGenotypeWhenOneAlleleIsFlanking(RepeatGenotype& genotype) const\n{\n    // In some exceptional situations flanking reads might be filtered out before the extension step; if this happens,\n    // genotype extension is aborted.\n    if (countFlankingReadsLongerThanSpanning() == 0)\n    {\n        return;\n    }\n\n    int32_t flankingAlleleSize, flankingAlleleCiLower, flankingAlleleCiUpper;\n    estimateFlankingAlleleSize(flankingAlleleSize, flankingAlleleCiLower, flankingAlleleCiUpper);\n\n    // genotype.setLongAlleleSizeInUnits(flankingAlleleSize);\n    flankingAlleleCiLower = std::min(genotype.shortAlleleSizeInUnits(), flankingAlleleCiLower);\n    flankingAlleleCiUpper = std::max(genotype.longAlleleSizeInUnits(), flankingAlleleCiUpper);\n\n    genotype.setLongAlleleSizeInUnitsCi(flankingAlleleCiLower, flankingAlleleCiUpper);\n}\n\nvoid RepeatGenotyper::extendGenotypeWhenOneAlleleIsRepeat(RepeatGenotype& genotype, int numRepeatReads) const\n{\n    assert(numRepeatReads);\n\n    int32_t longAlleleSize, longAlleleSizeLowerBound, longAlleleSizeUpperBound;\n    estimateRepeatAlleleSize(numRepeatReads, longAlleleSize, longAlleleSizeLowerBound, longAlleleSizeUpperBound);\n    genotype.setLongAlleleSizeInUnits(longAlleleSize);\n    genotype.setLongAlleleSizeInUnitsCi(longAlleleSizeLowerBound, longAlleleSizeUpperBound);\n}\n\nvoid RepeatGenotyper::extendGenotypeWhenBothAllelesAreRepeat(RepeatGenotype& genotype, int numRepeatReads) const\n{\n    assert(numRepeatReads);\n\n    int32_t allIrrSize, allIrrSizeLowerBound, allIrrlongSizeUpperBound;\n    estimateRepeatAlleleSize(numRepeatReads, allIrrSize, allIrrSizeLowerBound, allIrrlongSizeUpperBound);\n\n    int32_t halfIrrSize, halfIrrSizeLowerBound, halfIrrSizeUpperBound;\n    estimateRepeatAlleleSize(numRepeatReads / 2, halfIrrSize, halfIrrSizeLowerBound, halfIrrSizeUpperBound);\n\n    const int longAlleleSizeLowerBound = halfIrrSizeLowerBound;\n    const int longAlleleSizeUpperBound = allIrrlongSizeUpperBound;\n    const int longAlleleSize = (longAlleleSizeLowerBound + longAlleleSizeUpperBound) / 2;\n\n    genotype.setLongAlleleSizeInUnits(longAlleleSize);\n    genotype.setLongAlleleSizeInUnitsCi(longAlleleSizeLowerBound, longAlleleSizeUpperBound);\n\n    const int shortAlleleSizeLowerBound = maxNumUnitsInRead_;\n    const int shortAlleleSizeUpperBound = halfIrrSizeUpperBound;\n    const int shortAlleleSize = (shortAlleleSizeLowerBound + shortAlleleSizeUpperBound) / 2;\n\n    genotype.setShortAlleleSizeInUnits(shortAlleleSize);\n    genotype.setShortAlleleSizeInUnitsCi(shortAlleleSizeLowerBound, shortAlleleSizeUpperBound);\n}\n\nvoid RepeatGenotyper::estimateRepeatAlleleSize(\n    int32_t numIrrs, int32_t& size, int32_t& sizeLowerBound, int32_t& sizeUpperBound) const\n{\n    const int32_t readLength = repeatUnitLen_ * maxNumUnitsInRead_;\n    estimateRegionLength(numIrrs, readLength, haplotypeDepth_, size, sizeLowerBound, sizeUpperBound);\n\n    size /= repeatUnitLen_;\n    sizeLowerBound /= repeatUnitLen_;\n    sizeUpperBound /= repeatUnitLen_;\n}\n\nvoid RepeatGenotyper::estimateFlankingAlleleSize(\n    int32_t& flankingAlleleSize, int32_t& flankingAlleleCiLower, int32_t& flankingAlleleCiUpper) const\n{\n    const int32_t readLength = repeatUnitLen_ * maxNumUnitsInRead_;\n\n    const int longestSpanning = calculateLongestSpanning();\n    const int numFlankingReadsLongerThanSpanning = countFlankingReadsLongerThanSpanning();\n\n    // Haplotype depth should be twice as high because flanking reads come from both flanks of the repeat.\n    estimateRegionLength(\n        numFlankingReadsLongerThanSpanning, readLength, 2 * haplotypeDepth_, flankingAlleleSize, flankingAlleleCiLower,\n        flankingAlleleCiUpper);\n\n    // estimateRegionLength adds read length to size estimates so we need to subtract it out.\n    flankingAlleleSize -= readLength;\n    flankingAlleleCiLower -= readLength;\n    flankingAlleleCiUpper -= readLength;\n\n    flankingAlleleSize = flankingAlleleSize / repeatUnitLen_ + longestSpanning + 1;\n    flankingAlleleCiLower = flankingAlleleCiLower / repeatUnitLen_ + longestSpanning + 1;\n    flankingAlleleCiUpper = flankingAlleleCiUpper / repeatUnitLen_ + longestSpanning + 1;\n\n    // Repeat must be at least at long as the longest flanking read.\n    const vector<int32_t>& flankingSizes = countsOfFlankingReads_.getElementsWithNonzeroCounts();\n    const int32_t longestFlanking = *std::max_element(flankingSizes.begin(), flankingSizes.end());\n\n    flankingAlleleCiLower = std::max(flankingAlleleCiLower, longestFlanking);\n    flankingAlleleSize = std::max(flankingAlleleSize, longestFlanking);\n    flankingAlleleCiUpper = std::max(flankingAlleleCiUpper, longestFlanking);\n\n    // Repeat estimated from flanking reads cannot be longer than the read length.\n    flankingAlleleCiLower = std::min(flankingAlleleCiLower, maxNumUnitsInRead_);\n    flankingAlleleSize = std::min(flankingAlleleSize, maxNumUnitsInRead_);\n    flankingAlleleCiUpper = std::min(flankingAlleleCiUpper, maxNumUnitsInRead_);\n}\n\nint RepeatGenotyper::countFullLengthRepeatReads() const\n{\n    const double kMinProportionAlignedBases = 0.93;\n    const int fullLengthSizeCutoff = static_cast<int>(std::round(maxNumUnitsInRead_ * kMinProportionAlignedBases));\n\n    int repeatReadCount = 0;\n    for (int numUnits : countsOfInrepeatReads_.getElementsWithNonzeroCounts())\n    {\n        if (numUnits >= fullLengthSizeCutoff)\n        {\n            repeatReadCount += countsOfInrepeatReads_.countOf(numUnits);\n        }\n    }\n\n    return repeatReadCount;\n}\n\nint RepeatGenotyper::calculateLongestSpanning() const\n{\n    const vector<int32_t>& spanningSizes = countsOfSpanningReads_.getElementsWithNonzeroCounts();\n    const int longestSpanning\n        = spanningSizes.empty() ? 0 : *std::max_element(spanningSizes.begin(), spanningSizes.end());\n    return longestSpanning;\n}\n\nint RepeatGenotyper::countFlankingReadsLongerThanSpanning() const\n{\n    const int longestSpanning = calculateLongestSpanning();\n    int32_t numFlankingReadsLongerThanSpanning = 0;\n    for (int32_t repeatSize : countsOfFlankingReads_.getElementsWithNonzeroCounts())\n    {\n        if (repeatSize > longestSpanning)\n        {\n            numFlankingReadsLongerThanSpanning += countsOfFlankingReads_.countOf(repeatSize);\n        }\n    }\n    return numFlankingReadsLongerThanSpanning;\n}\n\nstatic int depthBasedCountOfInrepeatReads(\n    int maxNumUnitsInRead, const CountTable& countsOfFlankingReads, const CountTable& countsOfInrepeatReads)\n{\n    const int kNumFlanks = 2;\n    const double kPropLowConfidenceFlank = 0.1;\n    const double kPropHighConfidenceFlank = 1.0 - kPropLowConfidenceFlank;\n\n    const int maxUnitsFromLowConfidenceFlank\n        = static_cast<int>(std::round(maxNumUnitsInRead * kPropHighConfidenceFlank));\n\n    int numPutativeIrrs = 0;\n    for (const auto& numUnitsSpannedAndCount : countsOfInrepeatReads)\n    {\n        int numUnitsSpanned = numUnitsSpannedAndCount.first;\n        int readCount = numUnitsSpannedAndCount.second;\n\n        if (numUnitsSpanned >= maxUnitsFromLowConfidenceFlank)\n        {\n            numPutativeIrrs += readCount;\n        }\n    }\n\n    int numFlankingReads = 0;\n    for (const auto& numUnitsSpannedAndCount : countsOfFlankingReads)\n    {\n        int numUnitsSpanned = numUnitsSpannedAndCount.first;\n        int readCount = numUnitsSpannedAndCount.second;\n\n        if (numUnitsSpanned < maxUnitsFromLowConfidenceFlank)\n        {\n            numFlankingReads += readCount;\n        }\n    }\n    if (numFlankingReads == 0)\n        return 0;\n\n    const double estimatedDepth = numFlankingReads / (kNumFlanks * kPropHighConfidenceFlank);\n    const double expectedNumLowconfidenceFlankingReads = kNumFlanks * kPropLowConfidenceFlank * estimatedDepth;\n\n    boost::math::poisson_distribution<> lowconfidenceFlankingDistro(expectedNumLowconfidenceFlankingReads);\n    const double probability = boost::math::cdf(lowconfidenceFlankingDistro, numPutativeIrrs);\n\n    const double kProbabilityCutoff = 0.95;\n    return (probability >= kProbabilityCutoff ? numPutativeIrrs : 0);\n}\n\nstatic int lengthBasedCountOfInrepeatReads(int maxNumUnitsInRead, const CountTable& countsOfInrepeatReads)\n{\n    const double kPropForFullLength = 0.96;\n    const int minNumUnitsForFullLength = static_cast<int>(std::round(maxNumUnitsInRead * kPropForFullLength));\n\n    int numIrrs = 0;\n    for (const auto& numUnitsSpannedAndCount : countsOfInrepeatReads)\n    {\n        int numUnitsSpanned = numUnitsSpannedAndCount.first;\n        int readCount = numUnitsSpannedAndCount.second;\n\n        if (numUnitsSpanned >= minNumUnitsForFullLength)\n        {\n            numIrrs += readCount;\n        }\n    }\n\n    return numIrrs;\n}\n\nint countFullLengthRepeatReads(\n    int maxNumUnitsInRead, const CountTable& countsOfFlankingReads, const CountTable& countsOfInrepeatReads)\n{\n    const int lengthBasedCount = lengthBasedCountOfInrepeatReads(maxNumUnitsInRead, countsOfInrepeatReads);\n    const int depthBasedCount\n        = depthBasedCountOfInrepeatReads(maxNumUnitsInRead, countsOfFlankingReads, countsOfInrepeatReads);\n    return std::max(lengthBasedCount, depthBasedCount);\n}\n\n}\n", "meta": {"hexsha": "5696a995747acafad826522ce01de25fecc4de07", "size": 15089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "genotyping/RepeatGenotyper.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/RepeatGenotyper.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/RepeatGenotyper.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": 38.8891752577, "max_line_length": 119, "alphanum_fraction": 0.7606865929, "num_tokens": 3978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1860068520536948}}
{"text": "#include <stdint.h>\n#include <cstdlib>\n\n#include <iostream>\n#include <memory>\n#include <random>\n#include <string>\n#include <vector>\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdeprecated-register\"\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_edge.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/cholmod/linear_solver_cholmod.h>\n#include <g2o/solvers/pcg/linear_solver_pcg.h>\n#include <g2o/stuff/sampler.h>\n#pragma clang diagnostic pop\n\n#include <cpp_mpl.hpp>\n\n#include \"sampler.hpp\"\n\nusing cppmpl::NumpyArray;\n\ncppmpl::CppMatplotlib MplConnect (void);\n\n// Need to define types for\n// - vertices in the graph\n// - edges that link the vertex types\n\n// Example for a vertex.  UNDERLYING_TYPE is the type of the _estimate field.\n// class VertexType : public g2o::BaseVertex<DIMENSION, UNDERLYING_TYPE> {\n// public:\n//   EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n//     VertexType() {\n//       _estimate.setZero();\n//     }\n//\n//   | kind of a \"reset\" method\n//   virtual void setToOriginImpl() {\n//     _estimate.setZero();\n//   }\n//\n//   | has oPlusImpl that describes how a step in the minimal representation\n//   | updates the state represented by this vertex\n//   virtual void oplusImpl(const double* update) {\n//     _estimate = ApplyUpdate(update);\n//   }\n//\n//   | (optional) serialization\n//   virtual bool read(std::istream& /*is*/) { return false; }\n//   virtual bool write(std::ostream& /*os*/) const { return false; }\n// };\n\nint main (int argc, char **argv) {\n  (void) argc;\n  (void) argv;\n\n\n  return 0;\n}\n\ncppmpl::CppMatplotlib MplConnect (void) {\n  auto config_path = std::getenv(\"IPYTHON_KERNEL\");\n  if (config_path == nullptr) {\n    std::cerr << \"Please export IPYTHON_KERNEL=/path/to/kernel-NNN.json\"\n      << std::endl;\n    std::exit(-1);\n  }\n\n  cppmpl::CppMatplotlib mpl{config_path};\n  mpl.Connect();\n\n  return mpl;\n}\n", "meta": {"hexsha": "a37f695656a47d5bb7a93d696be2d729de3f8790", "size": 2115, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/scale.cc", "max_stars_repo_name": "daemacles/monoslam-scale-estimation", "max_stars_repo_head_hexsha": "cbf94e5c60d8ab6e0306e0b110d232672b34ae8d", "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/scale.cc", "max_issues_repo_name": "daemacles/monoslam-scale-estimation", "max_issues_repo_head_hexsha": "cbf94e5c60d8ab6e0306e0b110d232672b34ae8d", "max_issues_repo_licenses": ["MIT"], "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/scale.cc", "max_forks_repo_name": "daemacles/monoslam-scale-estimation", "max_forks_repo_head_hexsha": "cbf94e5c60d8ab6e0306e0b110d232672b34ae8d", "max_forks_repo_licenses": ["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.1785714286, "max_line_length": 77, "alphanum_fraction": 0.6997635934, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.18600595767786912}}
{"text": "/****************************************************************************\n*\n*    Copyright (c) 2019 Vivante Corporation\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 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\n*    DEALINGS IN THE SOFTWARE.\n*\n*****************************************************************************/\n\n#pragma once\n\n#include <backendsCommon/CpuTensorHandle.hpp>\n#include <backendsCommon/Workload.hpp>\n#include <backendsCommon/WorkloadData.hpp>\n#include <boost/log/trivial.hpp>\n#include \"TNpuWorkloads.hpp\"\n\nnamespace armnn {\ntemplate <typename ParentDescriptor, nnrt::OperationType operationType,\n         typename armnn::DataType... DataTypes>\nclass NpuElementwiseWorkload : public TNpuWorkload<ParentDescriptor, DataTypes...> {\n   public:\n    using base_type = TNpuWorkload<ParentDescriptor, DataTypes...>;\n    explicit NpuElementwiseWorkload(const ParentDescriptor& descriptor, const WorkloadInfo& info)\n        : TNpuWorkload<ParentDescriptor, DataTypes...>(descriptor, info) {\n        // Add inputs operand\n        assert(2 == descriptor.m_Inputs.size());\n        std::vector<uint32_t> inOperandIds = this->AddOperandWithTensorHandle(\n                descriptor.m_Inputs);\n\n        std::vector<uint32_t> outOperandIds;\n        NpuTensorHandler* outputTensorHandle =\n            dynamic_cast<NpuTensorHandler*>(descriptor.m_Outputs[0]);\n        uint32_t outputTensorId = this->AddOperandAndSetValue(\n            outputTensorHandle->GetTensorInfo(), outputTensorHandle->GetShape(), nullptr);\n        outOperandIds.push_back(outputTensorId);\n\n        this->AddOperation(operationType,\n                           inOperandIds.size(),\n                           inOperandIds.data(),\n                           outOperandIds.size(),\n                           outOperandIds.data());\n    }\n};\nusing NpuAdditionFloat32Workload = NpuElementwiseWorkload<AdditionQueueDescriptor,\n      nnrt::OperationType::ADD, armnn::DataType::Float32>;\nusing NpuAdditionFloat16Workload = NpuElementwiseWorkload<AdditionQueueDescriptor,\n      nnrt::OperationType::ADD, armnn::DataType::Float16>;\nusing NpuAdditionUint8Workload = NpuElementwiseWorkload<AdditionQueueDescriptor,\n      nnrt::OperationType::ADD, armnn::DataType::QuantisedAsymm8>;\n\nusing NpuMinimumFloat32Workload = NpuElementwiseWorkload<MinimumQueueDescriptor,\n      nnrt::OperationType::MINIMUM, armnn::DataType::Float32>;\nusing NpuMinimumFloat16Workload = NpuElementwiseWorkload<MinimumQueueDescriptor,\n      nnrt::OperationType::MINIMUM, armnn::DataType::Float16>;\nusing NpuMinimumUint8Workload = NpuElementwiseWorkload<MinimumQueueDescriptor,\n      nnrt::OperationType::MINIMUM, armnn::DataType::QuantisedAsymm8>;\n\nusing NpuMaximumFloat32Workload = NpuElementwiseWorkload<MaximumQueueDescriptor,\n      nnrt::OperationType::MAXIMUM, armnn::DataType::Float32>;\nusing NpuMaximumFloat16Workload = NpuElementwiseWorkload<MaximumQueueDescriptor,\n      nnrt::OperationType::MAXIMUM, armnn::DataType::Float16>;\nusing NpuMaximumUint8Workload = NpuElementwiseWorkload<MaximumQueueDescriptor,\n      nnrt::OperationType::MAXIMUM, armnn::DataType::QuantisedAsymm8>;\n\nusing NpuSubtractionFloat32Workload = NpuElementwiseWorkload<SubtractionQueueDescriptor,\n      nnrt::OperationType::SUB, armnn::DataType::Float32>;\nusing NpuSubtractionFloat16Workload = NpuElementwiseWorkload<SubtractionQueueDescriptor,\n      nnrt::OperationType::SUB, armnn::DataType::Float16>;\nusing NpuSubtractionUint8Workload = NpuElementwiseWorkload<SubtractionQueueDescriptor,\n      nnrt::OperationType::SUB, armnn::DataType::QuantisedAsymm8>;\n\nusing NpuDivisionFloat32Workload = NpuElementwiseWorkload<DivisionQueueDescriptor,\n      nnrt::OperationType::DIV, armnn::DataType::Float32>;\nusing NpuDivisionFloat16Workload = NpuElementwiseWorkload<DivisionQueueDescriptor,\n      nnrt::OperationType::DIV, armnn::DataType::Float16>;\nusing NpuDivisionUint8Workload = NpuElementwiseWorkload<DivisionQueueDescriptor,\n      nnrt::OperationType::DIV, armnn::DataType::QuantisedAsymm8>;\n\nusing NpuMultiplicationFloat32Workload = NpuElementwiseWorkload<MultiplicationQueueDescriptor,\n      nnrt::OperationType::MUL, armnn::DataType::Float32>;\nusing NpuMultiplicationFloat16Workload = NpuElementwiseWorkload<MultiplicationQueueDescriptor,\n      nnrt::OperationType::MUL, armnn::DataType::Float16>;\nusing NpuMultiplicationUint8Workload = NpuElementwiseWorkload<MultiplicationQueueDescriptor,\n      nnrt::OperationType::MUL, armnn::DataType::QuantisedAsymm8>;\n}  // namespace armnn\n", "meta": {"hexsha": "1fa26b623da5f487a0bf673e05b7fd77299e09fc", "size": 5482, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuElementwiseWorkload.hpp", "max_stars_repo_name": "phytec-mirrors/nn-imx", "max_stars_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "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": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuElementwiseWorkload.hpp", "max_issues_repo_name": "phytec-mirrors/nn-imx", "max_issues_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuElementwiseWorkload.hpp", "max_forks_repo_name": "phytec-mirrors/nn-imx", "max_forks_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.7450980392, "max_line_length": 97, "alphanum_fraction": 0.742247355, "num_tokens": 1285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.1860059576778691}}
{"text": "// Copyright 2020 Oscar Higgott\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 <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include <boost/graph/connected_components.hpp>\n#include \"matching_graph.h\"\n#include <memory>\n#include <set>\n#include <utility>\n#include <stdexcept>\n#include <cstdint>\n#include <iostream>\n#include <limits>\n#include <cmath>\n#include \"rand_gen.h\"\n\n\nWeightedEdgeData::WeightedEdgeData() {}\n\nWeightedEdgeData::WeightedEdgeData(\n    std::set<int> fault_ids,\n    double weight,\n    double error_probability,\n    bool has_error_probability,\n    bool weight_is_negative\n): fault_ids(fault_ids), weight(weight),\nerror_probability(error_probability), has_error_probability(has_error_probability),\nweight_is_negative(weight_is_negative) {}\n\n\nstd::string set_repr(std::set<int> x) {\n    std::stringstream ss;\n    ss << \"{\";\n    bool first = true;\n    for (auto i : x){\n        if (first){\n            first = false;\n        } else {\n            ss << \", \";\n        }\n        ss << i;\n    }\n    ss << \"}\";\n    return ss.str();\n}\n\n\nstd::string WeightedEdgeData::repr() const {\n    std::stringstream ss;\n    ss << \"pymatching._cpp_mwpm.WeightedEdgeData(\";\n    ss << set_repr(fault_ids) << \", \" << weight << \", \" << error_probability << \", \"\n    << has_error_probability << \")\";\n    return ss.str();\n}\n\n\nMatchingGraph::MatchingGraph()\n    : all_edges_have_error_probabilities(true),\n     connected_components_need_updating(true),\n     negative_weight_sum(0.0)  {\n    wgraph_t sgraph = wgraph_t();\n    this->matching_graph = sgraph;\n}\n\n\nMatchingGraph::MatchingGraph(\n    int num_detectors,\n    std::set<int>& boundary)\n    : all_edges_have_error_probabilities(true),\n    boundary(boundary),\n    connected_components_need_updating(true),\n     negative_weight_sum(0.0) {\n    wgraph_t sgraph = wgraph_t(num_detectors+boundary.size());\n    this->matching_graph = sgraph;\n}\n\nvoid MatchingGraph::AddEdge(\n    int node1, \n    int node2, \n    std::set<int> fault_ids,\n    double weight, \n    double error_probability, \n    bool has_error_probability){\n        if (has_error_probability && (error_probability > 1 || error_probability < 0)){\n            throw std::invalid_argument(\"error_probability must be between 0 and 1\");\n        }\n        if (node1 < 0 || node2 < 0){\n            throw std::invalid_argument(\"Node IDs must be non-negative\");\n        }\n        auto n1 = boost::vertex(node1, matching_graph);\n        auto n2 = boost::vertex(node2, matching_graph);\n        int num_nodes = GetNumNodes();\n        bool nodes_in_graph = (n1 < num_nodes) && (n2 < num_nodes);\n        if (nodes_in_graph && boost::edge(n1, n2, matching_graph).second){\n            throw std::invalid_argument(\"This edge already exists in the graph. \"\n                                        \"Parallel edges are not supported.\");\n        }\n        if (std::signbit(weight)){\n            HandleNewNegativeWeightEdge(node1, node2, weight, fault_ids);\n        }\n        if (!has_error_probability){\n            all_edges_have_error_probabilities = false;\n            error_probability = -1;\n        }\n        connected_components_need_updating = true;\n        WeightedEdgeData data;\n        data.fault_ids = fault_ids;\n        data.weight = std::abs(weight);\n        data.error_probability = error_probability;\n        data.has_error_probability = has_error_probability;\n        data.weight_is_negative = std::signbit(weight);\n        boost::add_edge(\n            n1,\n            n2,\n            data, \n            matching_graph);\n}\n\n\nvoid MatchingGraph::HandleNewNegativeWeightEdge(int u, int v, double weight, std::set<int> &fault_ids){\n    assert(std::signbit(weight));\n    negative_weight_sum += weight;\n\n    for (auto fid : fault_ids){\n        if (negative_edge_fault_ids.find(fid) != negative_edge_fault_ids.end()){\n            negative_edge_fault_ids.erase(fid);\n        } else {\n            negative_edge_fault_ids.insert(fid);\n        }\n    }\n\n    for (auto node : {u, v}){\n        if (negative_edge_syndrome.find(node) != negative_edge_syndrome.end()){\n            negative_edge_syndrome.erase(node);\n        } else {\n            negative_edge_syndrome.insert(node);\n        }\n    }\n\n}\n\n\nvoid MatchingGraph::ComputeAllPairsShortestPaths(){\n    int n = boost::num_vertices(matching_graph);\n    all_distances.clear();\n    all_predecessors.clear();\n    for (int i=0; i<n; i++){\n        std::vector<double> distances(n);\n        std::vector<vertex_descriptor> p(n);\n        vertex_descriptor from = boost::vertex(i, matching_graph);\n        boost::dijkstra_shortest_paths(matching_graph, from,\n            boost::weight_map(boost::get(&WeightedEdgeData::weight, matching_graph))\n            .distance_map(boost::make_iterator_property_map(distances.begin(),\n                            boost::get(boost::vertex_index, matching_graph)))\n            .predecessor_map(&p[0]));\n        all_distances.push_back(distances);\n        all_predecessors.push_back(p);\n    }\n}\n\nclass exit_search{};\n\n\nclass DijkstraNeighbourVisitor : public boost::default_dijkstra_visitor\n{\n    public:\n        DijkstraNeighbourVisitor(std::vector<int>& defect_id, \n            int num_defects, std::vector<int>& examined_defects,\n            std::vector<int>& discovered_nodes) : \n        defect_id(defect_id), num_defects(num_defects), \n        examined_defects(examined_defects), num_found(0),\n        discovered_nodes(discovered_nodes) {}\n\n        void examine_vertex(wgraph_t::vertex_descriptor v, const wgraph_t &g)\n        {\n            if (defect_id[v] > -1){\n                num_found++;\n                examined_defects.push_back(v);\n                if (num_found >= num_defects) {\n                    throw exit_search();\n                }\n            }   \n        }\n        void discover_vertex(wgraph_t::vertex_descriptor v, const wgraph_t &g){\n            discovered_nodes.push_back(v);\n        }\n        std::vector<int>& defect_id;\n        int num_defects;\n        std::vector<int>& examined_defects;\n        std::vector<int>& discovered_nodes;\n        int num_found;\n};\n\n\nvoid MatchingGraph::ResetDijkstraNeighbours(){\n    int n = boost::num_vertices(matching_graph);\n    double inf = std::numeric_limits<double>::max();\n    if (_distances.size() < n){\n        _distances.resize(n, inf);\n    }\n    if (_predecessors.size() < n){\n        _predecessors.resize(n);\n        for (int i=0; i<_predecessors.size(); i++){\n            _predecessors[i] = i;\n        }\n    }\n}\n\n\nstd::vector<std::pair<int, double>> MatchingGraph::GetNearestNeighbours(\n    int source, int num_neighbours, std::vector<int>& defect_id){\n    int n = boost::num_vertices(matching_graph);\n    if (source < 0 || source >= n) {\n        throw std::invalid_argument(\"source must be non-negative and less than the number of nodes \"\n                                    \"in the matching graph\");\n    }\n    if (defect_id.size() != n) {\n        throw std::invalid_argument(\"defect_id must have the same number of elements as the number \"\n                                    \"of nodes in the matching graph\");\n    }\n    if (num_neighbours < 0) {\n        throw std::invalid_argument(\"num_neighbours must be a positive integer\");\n    }\n    double inf = std::numeric_limits<double>::max();\n    ResetDijkstraNeighbours();\n    _distances[source] = 0;\n    std::vector<int> examined_defects;\n    std::vector<int> discovered_nodes;\n    int source_is_defect = defect_id[source] > -1;\n    DijkstraNeighbourVisitor vis = DijkstraNeighbourVisitor(\n        defect_id, num_neighbours + source_is_defect, examined_defects, discovered_nodes);\n    vertex_descriptor from = boost::vertex(source, matching_graph);\n    try {\n        boost::dijkstra_shortest_paths_no_color_map_no_init(matching_graph, from,\n                &_predecessors[0], boost::make_iterator_property_map(_distances.begin(),\n                boost::get(boost::vertex_index, matching_graph)),\n                boost::get(&WeightedEdgeData::weight, matching_graph),\n                boost::get(boost::vertex_index, matching_graph),\n                std::less<double>(),\n                boost::closed_plus<double>(),\n                inf,\n                0,\n                vis);\n    } catch (exit_search e) {}\n    \n    std::vector<std::pair<int, double>> neighbours;\n    for (auto d : examined_defects){\n        if (d != source){\n            neighbours.push_back({d, _distances[d]});\n        }\n    }\n\n    for (auto n : discovered_nodes){\n        _distances[n] = inf;\n        _predecessors[n] = n;\n    }\n    return neighbours;    \n}\n\n\nclass DijkstraPathVisitor : public boost::default_dijkstra_visitor\n{\n    public:\n        DijkstraPathVisitor(int target, std::vector<int>& discovered_nodes) : \n        target(target),\n        discovered_nodes(discovered_nodes) {}\n\n        void examine_vertex(wgraph_t::vertex_descriptor v, const wgraph_t &g)\n        {\n            if (v == target){\n                throw exit_search();\n            }   \n        }\n        void discover_vertex(wgraph_t::vertex_descriptor v, const wgraph_t &g){\n            discovered_nodes.push_back(v);\n        }\n        int target;\n        std::vector<int>& discovered_nodes;\n};\n\n\nstd::vector<int> MatchingGraph::GetPath(\n    int source, int target){\n    int n = boost::num_vertices(matching_graph);\n    if (source >= n || target >= n\n        || source < 0 || target < 0){\n        throw std::invalid_argument(\"source and target must non-negative and less \"\n                                    \"than the number of nodes\");\n    }\n    double inf = std::numeric_limits<double>::max();\n    ResetDijkstraNeighbours();\n    _distances[source] = 0;\n    std::vector<int> discovered_nodes;\n    DijkstraPathVisitor vis = DijkstraPathVisitor(\n        target, discovered_nodes);\n    vertex_descriptor from = boost::vertex(source, matching_graph);\n    try {\n        boost::dijkstra_shortest_paths_no_color_map_no_init(matching_graph, from,\n                &_predecessors[0], boost::make_iterator_property_map(_distances.begin(),\n                boost::get(boost::vertex_index, matching_graph)),\n                boost::get(&WeightedEdgeData::weight, matching_graph),\n                boost::get(boost::vertex_index, matching_graph),\n                std::less<double>(),\n                boost::closed_plus<double>(),\n                inf,\n                0,\n                vis);\n    } catch (exit_search e) {}\n\n    std::vector<int> path;\n    path.push_back(target);\n    while (_predecessors[target] != target){\n        target = _predecessors[target];\n        path.push_back(target);\n    }\n    std::reverse(path.begin(),path.end());\n\n    for (auto n : discovered_nodes){\n        _distances[n] = inf;\n        _predecessors[n] = n;\n    }\n    return path;    \n}\n\n\ndouble MatchingGraph::Distance(int node1, int node2) {\n    int num_nodes = GetNumNodes();\n    if (node1 >= num_nodes || node2 >= num_nodes\n        || node1 < 0 || node2 < 0){\n        throw std::invalid_argument(\"node1 and node2 must non-negative and less \"\n                                    \"than the number of nodes\");\n    }\n    if (!HasComputedAllPairsShortestPaths()){\n        ComputeAllPairsShortestPaths();\n    }\n    vertex_descriptor n2 = boost::vertex(node2, matching_graph);\n    return all_distances[node1][n2];\n}\n\nstd::vector<int> MatchingGraph::ShortestPath(int node1, int node2) {\n    int num_nodes = GetNumNodes();\n    if (node1 >= num_nodes || node2 >= num_nodes\n        || node1 < 0 || node2 < 0){\n        throw std::invalid_argument(\"node1 and node2 must non-negative and less \"\n                                    \"than the number of nodes\");\n    }\n    if (!HasComputedAllPairsShortestPaths()){\n        ComputeAllPairsShortestPaths();\n    }\n    std::vector<vertex_descriptor> parent = all_predecessors[node2];\n    auto index = boost::get(boost::vertex_index, matching_graph);\n    int c = boost::vertex(node1, matching_graph);\n    std::vector<int> path;\n    path.push_back(index[c]);\n    while (parent[c]!=c){\n        c = parent[c];\n        path.push_back(index[c]);\n    }\n    return path;\n}\n\n\nint MatchingGraph::GetNumEdges() const {\n    return boost::num_edges(matching_graph);\n}\n\n\nint MatchingGraph::GetNumFaultIDs() const {\n    auto qid = boost::get(&WeightedEdgeData::fault_ids, matching_graph);\n    int num_edges = boost::num_edges(matching_graph);\n    int maxid = -1;\n    std::set<int> edge_fault_ids;\n    auto es = boost::edges(matching_graph);\n    for (auto eit = es.first; eit != es.second; ++eit) {\n        edge_fault_ids = qid[*eit];\n        for (auto fault_id : edge_fault_ids){\n            if (fault_id >= maxid){\n                maxid = fault_id;\n            }\n            if (fault_id < 0 && fault_id != -1){\n                throw std::runtime_error(\"Fault ids must be non-negative, or -1 if no fault IDs are associated with the edge.\");\n            }\n        }\n    }\n    return maxid + 1;\n}\n\nint MatchingGraph::GetNumNodes() const {\n    return boost::num_vertices(matching_graph);\n};\n\nstd::set<int> MatchingGraph::FaultIDs(int node1, int node2) const {\n    int num_nodes = GetNumNodes();\n    if (node1 >= num_nodes || node2 >= num_nodes\n        || node1 < 0 || node2 < 0){\n        throw std::invalid_argument(\"node1 and node2 must non-negative and less \"\n                                    \"than the number of nodes\");\n    }\n    auto e = boost::edge(node1, node2, matching_graph);\n    if (!e.second){\n        throw std::invalid_argument(\"Graph does not contain edge (\"\n                        + std::to_string((int)node1) + \", \"\n                        + std::to_string((int)node2) + \").\");\n    }\n    return matching_graph[e.first].fault_ids;\n}\n\nstd::pair<py::array_t<std::uint8_t>,py::array_t<std::uint8_t>> MatchingGraph::AddNoise() const {\n    auto syndrome = new std::vector<int>(GetNumNodes(), 0);\n    auto error = new std::vector<int>(GetNumFaultIDs(), 0);\n    double p;\n    std::set<int> qids;\n    vertex_descriptor s, t;\n    bool to_flip;\n    auto es = boost::edges(matching_graph);\n    for (auto eit = es.first; eit != es.second; ++eit) {\n        p = matching_graph[*eit].error_probability;\n        if ((p >= 0) && (rand_float(0.0, 1.0) < p)){\n            s = boost::source(*eit, matching_graph);\n            t = boost::target(*eit, matching_graph);\n            (*syndrome)[s] = ((*syndrome)[s] + 1) % 2;\n            (*syndrome)[t] = ((*syndrome)[t] + 1) % 2;\n            qids = matching_graph[*eit].fault_ids;\n            for (auto qid : qids){\n                if (qid >= 0){\n                    (*error)[qid] = ((*error)[qid] + 1) % 2;\n                }\n            }\n        }\n    }\n    for (auto b : boundary){\n        (*syndrome)[b] = 0;\n    }\n\n    auto capsule = py::capsule(syndrome, [](void *syndrome) { delete reinterpret_cast<std::vector<int>*>(syndrome); });\n    py::array_t<int> syndrome_arr = py::array_t<int>(syndrome->size(), syndrome->data(), capsule);\n    auto err_capsule = py::capsule(error, [](void *error) { delete reinterpret_cast<std::vector<int>*>(error); });\n    py::array_t<int> error_arr = py::array_t<int>(error->size(), error->data(), err_capsule);\n    return {error_arr, syndrome_arr};\n}\n\nstd::set<int> MatchingGraph::GetBoundary() const {\n    return boundary;\n}\n\nvoid MatchingGraph::SetBoundary(std::set<int>& boundary) {\n    for (auto b: boundary){\n        if (b < 0){\n            throw std::invalid_argument(\"Boundary nodes must be non-negative.\");\n        }\n    }\n    this->boundary = boundary;\n    connected_components_need_updating = true;\n    return;\n}\n\nstd::vector<std::tuple<int,int,WeightedEdgeData>> MatchingGraph::GetEdges() const {\n    std::vector<std::tuple<int,int,WeightedEdgeData>> edges;\n    auto es = boost::edges(matching_graph);\n    for (auto eit = es.first; eit != es.second; ++eit) {\n        WeightedEdgeData edata = matching_graph[*eit];\n        int s = boost::source(*eit, matching_graph);\n        int t = boost::target(*eit, matching_graph);\n        if (edata.weight_is_negative) {\n            edata.weight = -1 * edata.weight;\n        }\n        std::tuple<int,int,WeightedEdgeData> edge = std::make_tuple(s, t, edata);\n        edges.push_back(edge);\n    }\n    return edges;\n}\n\nbool MatchingGraph::HasComputedAllPairsShortestPaths() const {\n    int n = boost::num_vertices(matching_graph);\n    bool has_distances = all_distances.size() == n;\n    bool has_preds = all_predecessors.size() == n;\n    return has_distances && has_preds;\n}\n\nint MatchingGraph::GetNumConnectedComponents() {\n    if (connected_components_need_updating){\n        component.resize(GetNumNodes());\n        num_components = boost::connected_components(matching_graph, &component[0]);\n        component_boundary.resize(num_components, -1);\n        for (auto b : boundary){\n            if (b >= GetNumNodes() || b < 0){\n                throw std::invalid_argument(\n                    \"Boundary node ID \" + std::to_string(b)\n                    + \" does not correspond to a node in the graph, which \"\n                    \"has \" + std::to_string(GetNumNodes()) + \" nodes.\"\n                );\n            }\n            int c = component[b];\n            if (component_boundary[c] == -1){\n                component_boundary[c] = b;\n            }\n        }\n    }\n    connected_components_need_updating = false;\n    return num_components;\n}\n\nvoid MatchingGraph::FlipBoundaryNodesIfNeeded(std::set<int> &defects){\n    int num_comps = GetNumConnectedComponents();\n    if (num_comps == 1){\n        if ((defects.size() % 2) == 0){\n            return;\n        } else if ((defects.size() % 2) == 1 && boundary.size() == 0){\n            throw std::invalid_argument(\n            \"The syndrome has an odd number of defects, but no boundary nodes were provided\"\n            );\n        }\n    }\n    std::vector<std::uint8_t> component_parities(num_comps, 0);\n    for (auto df : defects){\n        if (df >= component.size()){\n            throw std::invalid_argument(\n            \"Defect id should not exceed the number of vertices in the graph\"\n            );\n        }\n        component_parities[component[df]] ^= 1;\n    }\n\n    for (int i=0; i<component_parities.size(); i++){\n        if (component_parities[i] == 1){\n            int b = component_boundary[i];\n            if (b == -1){\n                throw std::invalid_argument(\n                    \"The syndrome has an odd number of defects in a component of the matching graph \"\n                    \"that does not have a boundary node\"\n                    );\n            }\n            bool is_in_defects = defects.find(b) != defects.end();\n            if (is_in_defects){\n                defects.erase(b);\n            } else {\n                defects.insert(b);\n            }\n        }\n    }\n}\n\nbool MatchingGraph::AllEdgesHaveErrorProbabilities() const {\n    return all_edges_have_error_probabilities;\n}\n\nstd::string MatchingGraph::repr() const {\n    std::stringstream ss;\n    ss << \"<pymatching._cpp_mwpm.MatchingGraph object with \";\n    ss << GetNumNodes() << \" nodes, \";\n    ss << GetNumEdges() << \" edges and \" << GetBoundary().size() << \" boundary nodes>\";\n    return ss.str();\n}\n", "meta": {"hexsha": "0c1cf0a4938b0cfb0502af7f24fedd092e4b1770", "size": 19635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pymatching/matching_graph.cpp", "max_stars_repo_name": "oscarhiggott/PyMatching", "max_stars_repo_head_hexsha": "7d799d1a74747f50e3ce3c7d527a16067077e7a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-08-03T10:46:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:45:27.000Z", "max_issues_repo_path": "src/pymatching/matching_graph.cpp", "max_issues_repo_name": "oscarhiggott/PyMatching", "max_issues_repo_head_hexsha": "7d799d1a74747f50e3ce3c7d527a16067077e7a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2020-11-25T18:40:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T22:20:22.000Z", "max_forks_repo_path": "src/pymatching/matching_graph.cpp", "max_forks_repo_name": "oscarhiggott/PyMatching", "max_forks_repo_head_hexsha": "7d799d1a74747f50e3ce3c7d527a16067077e7a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-01-12T16:12:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T07:24:58.000Z", "avg_line_length": 34.5686619718, "max_line_length": 128, "alphanum_fraction": 0.6065699007, "num_tokens": 4659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.18600595404751952}}
{"text": "/****************************************************************************\n*\n*    Copyright (c) 2019 Vivante Corporation\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 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\n*    DEALINGS IN THE SOFTWARE.\n*\n*****************************************************************************/\n\n#pragma once\n\n#include <backendsCommon/CpuTensorHandle.hpp>\n#include <backendsCommon/Workload.hpp>\n#include <backendsCommon/WorkloadData.hpp>\n#include <boost/log/trivial.hpp>\n#include \"TNpuWorkloads.hpp\"\n\nnamespace armnn {\ntemplate <typename armnn::DataType... DataTypes>\nclass NpuNormalizationWorkload : public TNpuWorkload<NormalizationQueueDescriptor, DataTypes...> {\n   public:\n    using base_type = TNpuWorkload<NormalizationQueueDescriptor, DataTypes...>;\n    explicit NpuNormalizationWorkload(const NormalizationQueueDescriptor& descriptor,\n                                      const WorkloadInfo& info)\n        : TNpuWorkload<NormalizationQueueDescriptor, DataTypes...>(descriptor, info),\n          m_NormChannelType(descriptor.m_Parameters.m_NormChannelType),\n          m_NormMethodType(descriptor.m_Parameters.m_NormMethodType),\n          m_NormSize(descriptor.m_Parameters.m_NormSize),\n          m_Alpha(descriptor.m_Parameters.m_Alpha),\n          m_Beta(descriptor.m_Parameters.m_Beta),\n          m_K(descriptor.m_Parameters.m_K),\n          m_DataLayout(descriptor.m_Parameters.m_DataLayout) {\n        std::vector<uint32_t> inOperandIds;\n\n        // Only 1 input tensor\n        NpuTensorHandler* inputTensorHandle =\n            dynamic_cast<NpuTensorHandler*>(descriptor.m_Inputs[0]);\n        uint32_t inputOperandId = this->AddOperandAndSetValue(\n            inputTensorHandle->GetTensorInfo(), inputTensorHandle->GetShape(), nullptr);\n        inOperandIds.push_back(inputOperandId);\n\n        // order is important\n        // Add norm size(radius) operand\n        // Strong Assumption on rounding Mode\n        inOperandIds.push_back(this->AddOperandAndSetValue(m_NormSize / 2u));\n\n        // Add kappa(bias) operand\n        inOperandIds.push_back(this->AddOperandAndSetValue(m_K));\n\n        // Add alpha operand\n        inOperandIds.push_back(this->AddOperandAndSetValue(m_Alpha));\n\n        // Add beta oparand\n        inOperandIds.push_back(this->AddOperandAndSetValue(m_Beta));\n\n        // Add channel type operand\n        inOperandIds.push_back(this->AddOperandAndSetValue(uint32_t(m_NormChannelType)));\n\n        // Add method type operand\n        inOperandIds.push_back(this->AddOperandAndSetValue(uint32_t(m_NormMethodType)));\n\n        // Add layout operand\n        int32_t layoutCode = m_DataLayout == armnn::DataLayout::NCHW\n                                 ? int32_t(nnrt::DataLayout::NCHW)\n                                 : int32_t(nnrt::DataLayout::NHWC);\n        inOperandIds.push_back(this->AddOperandAndSetValue(layoutCode));\n\n        std::vector<uint32_t> outOperandIds;\n        NpuTensorHandler* outputTensorHandle =\n            dynamic_cast<NpuTensorHandler*>(descriptor.m_Outputs[0]);\n        uint32_t outputTensorId = this->AddOperandAndSetValue(\n            outputTensorHandle->GetTensorInfo(), outputTensorHandle->GetShape(), nullptr);\n        outOperandIds.push_back(outputTensorId);\n\n        this->AddOperation(nnrt::OperationType::LOCAL_RESPONSE_NORMALIZATION,\n                           inOperandIds.size(),\n                           inOperandIds.data(),\n                           outOperandIds.size(),\n                           outOperandIds.data());\n    }\n\n   private:\n    /// Normalization channel algorithm to use (Across, Within).\n    NormalizationAlgorithmChannel m_NormChannelType;\n    /// Normalization method algorithm to use (LocalBrightness, LocalContrast).\n    NormalizationAlgorithmMethod m_NormMethodType;\n    /// Depth radius value.\n    uint32_t m_NormSize;\n    /// Alpha value for the normalization equation.\n    float m_Alpha;\n    /// Beta value for the normalization equation.\n    float m_Beta;\n    /// Kappa value used for the across channel normalization equation.\n    float m_K;\n    /// The data layout to be used (NCHW, NHWC).\n    DataLayout m_DataLayout;\n};\nusing NpuNormalizationFloat32Workload = NpuNormalizationWorkload<armnn::DataType::Float32>;\nusing NpuNormalizationFloat16Workload = NpuNormalizationWorkload<armnn::DataType::Float16>;\nusing NpuNormalizationUint8Workload = NpuNormalizationWorkload<armnn::DataType::QuantisedAsymm8>;\n}  // namespace armnn", "meta": {"hexsha": "19aa99f990ab98837a2244fce6a55a8693da2b9e", "size": 5434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuNormalizationWorkload.hpp", "max_stars_repo_name": "phytec-mirrors/nn-imx", "max_stars_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "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": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuNormalizationWorkload.hpp", "max_issues_repo_name": "phytec-mirrors/nn-imx", "max_issues_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nn_runtime/armnn_backend_vsi_npu/workloads/NpuNormalizationWorkload.hpp", "max_forks_repo_name": "phytec-mirrors/nn-imx", "max_forks_repo_head_hexsha": "58525bf968e8d90004f6d782ad37cea28991a439", "max_forks_repo_licenses": ["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.8448275862, "max_line_length": 98, "alphanum_fraction": 0.6858667648, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.18600595189802974}}
{"text": "#ifndef GUNEROMERKLETREE_H_\n#define GUNEROMERKLETREE_H_\n\n#include <deque>\n#include <boost/optional.hpp>\n#include <boost/static_assert.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>\n#include <libff/algebra/fields/field_utils.hpp>\n#include <libff/algebra/scalar_multiplication/multiexp.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>\n#include <libff/common/utils.hpp>\n\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>\n\n\nusing namespace libsnark;\n\nnamespace gunero {\n\n/**\n * A Merkle tree is maintained as two maps:\n * - a map from addresses to values, and\n * - a map from addresses to hashes.\n *\n * The second map maintains the intermediate hashes of a Merkle tree\n * built atop the values currently stored in the tree (the\n * implementation admits a very efficient support for sparse\n * trees). Besides offering methods to load and store values, the\n * class offers methods to retrieve the root of the Merkle tree and to\n * obtain the authentication paths for (the value at) a given address.\n */\n\ntypedef libff::bit_vector gunero_merkle_authentication_node;\ntypedef std::vector<gunero_merkle_authentication_node> gunero_merkle_authentication_path;\n\nstd::ostream& operator<<(std::ostream &out, const gunero_merkle_authentication_node& node);\nstd::istream& operator>>(std::istream &in, gunero_merkle_authentication_node& node);\nstd::ostream& operator<<(std::ostream &out, const std::vector<gunero_merkle_authentication_node>& M_account);\nstd::istream& operator>>(std::istream &in, std::vector<gunero_merkle_authentication_node>& M_account);\n\ntemplate<typename HashT>\nclass gunero_merkle_tree {\nprivate:\n\n    typedef typename HashT::hash_value_type hash_value_type;\n    typedef typename HashT::merkle_authentication_path_type gunero_merkle_authentication_path_type;\n\npublic:\n\n    std::vector<hash_value_type> hash_defaults;\n    std::map<size_t, libff::bit_vector> values;\n    std::map<size_t, hash_value_type> hashes;\n\n    size_t depth;\n    size_t value_size;\n    size_t digest_size;\n\n    gunero_merkle_tree(const size_t depth, const size_t value_size);\n    gunero_merkle_tree(const size_t depth, const size_t value_size, const std::vector<libff::bit_vector> &contents_as_vector);\n    gunero_merkle_tree(const size_t depth, const size_t value_size, const std::map<size_t, libff::bit_vector> &contents);\n\n    libff::bit_vector get_value(const libff::bit_vector address) const;\n    void set_value(const libff::bit_vector address, const libff::bit_vector &value);\n\n    hash_value_type get_root() const;\n    gunero_merkle_authentication_path_type get_path(const libff::bit_vector address) const;\n\n    void dump() const;\n};\n\ntemplate<typename FieldT, typename HashT>\nclass gunero_merkle_authentication_path_variable : public gadget<FieldT> {\npublic:\n\n    const size_t tree_depth;\n    std::vector<digest_variable<FieldT> > left_digests;\n    std::vector<digest_variable<FieldT> > right_digests;\n\n    gunero_merkle_authentication_path_variable(protoboard<FieldT> &pb,\n                                        const size_t tree_depth,\n                                        const std::string &annotation_prefix) :\n        gadget<FieldT>(pb, annotation_prefix),\n        tree_depth(tree_depth)\n    {\n        for (size_t i = 0; i < tree_depth; ++i)\n        {\n            left_digests.emplace_back(digest_variable<FieldT>(pb, HashT::get_digest_len(), FMT(annotation_prefix, \" left_digests_%zu\", i)));\n            right_digests.emplace_back(digest_variable<FieldT>(pb, HashT::get_digest_len(), FMT(annotation_prefix, \" right_digests_%zu\", i)));\n        }\n    }\n\n    void generate_r1cs_constraints()\n    {\n        for (size_t i = 0; i < tree_depth; ++i)\n        {\n            left_digests[i].generate_r1cs_constraints();\n            right_digests[i].generate_r1cs_constraints();\n        }\n    }\n\n    void generate_r1cs_witness(const libff::bit_vector address, const gunero_merkle_authentication_path &path)\n    {\n        assert(address.size() == tree_depth);\n        assert(path.size() == tree_depth);\n\n        for (size_t i = 0; i < tree_depth; ++i)\n        {\n            //if (address & (1ul << (tree_depth-1-i)))\n            //if (address.at(tree_depth-1-i))\n            if (address.at(i))\n            {\n                left_digests[i].generate_r1cs_witness(path[i]);\n            }\n            else\n            {\n                right_digests[i].generate_r1cs_witness(path[i]);\n            }\n        }\n    }\n    gunero_merkle_authentication_path get_authentication_path(const libff::bit_vector address) const;\n};\n\ntemplate<typename FieldT, typename HashT>\nclass gunero_merkle_tree_check_read_gadget : public gadget<FieldT> {\nprivate:\n\n    std::vector<HashT> hashers;\n    std::vector<block_variable<FieldT> > hasher_inputs;\n    std::vector<digest_selector_gadget<FieldT> > propagators;\n    std::vector<digest_variable<FieldT> > internal_output;\n\n    std::shared_ptr<digest_variable<FieldT> > computed_root;\n    std::shared_ptr<bit_vector_copy_gadget<FieldT> > check_root;\n\npublic:\n\n    const size_t digest_size;\n    const size_t tree_depth;\n    pb_linear_combination_array<FieldT> address_bits;\n    digest_variable<FieldT> leaf;\n    digest_variable<FieldT> root;\n    gunero_merkle_authentication_path_variable<FieldT, HashT> path;\n    pb_linear_combination<FieldT> read_successful;\n\n    gunero_merkle_tree_check_read_gadget(protoboard<FieldT> &pb,\n                                  const size_t tree_depth,\n                                  const pb_linear_combination_array<FieldT> &address_bits,\n                                  const digest_variable<FieldT> &leaf_digest,\n                                  const digest_variable<FieldT> &root_digest,\n                                  const gunero_merkle_authentication_path_variable<FieldT, HashT> &path,\n                                  const pb_linear_combination<FieldT> &read_successful,\n                                  const std::string &annotation_prefix) :\n        gadget<FieldT>(pb, annotation_prefix),\n        digest_size(HashT::get_digest_len()),\n        tree_depth(tree_depth),\n        address_bits(address_bits),\n        leaf(leaf_digest),\n        root(root_digest),\n        path(path),\n        read_successful(read_successful)\n    {\n        /*\n        The tricky part here is ordering. For Merkle tree\n        authentication paths, path[0] corresponds to one layer below\n        the root (and path[tree_depth-1] corresponds to the layer\n        containing the leaf), while address_bits has the reverse order:\n        address_bits[0] is LSB, and corresponds to layer containing the\n        leaf, and address_bits[tree_depth-1] is MSB, and corresponds to\n        the subtree directly under the root.\n        */\n        assert(tree_depth > 0);\n        assert(tree_depth == address_bits.size());\n\n        for (size_t i = 0; i < tree_depth-1; ++i)\n        {\n            internal_output.emplace_back(digest_variable<FieldT>(pb, digest_size, FMT(this->annotation_prefix, \" internal_output_%zu\", i)));\n        }\n\n        computed_root.reset(new digest_variable<FieldT>(pb, digest_size, FMT(this->annotation_prefix, \" computed_root\")));\n\n        for (size_t i = 0; i < tree_depth; ++i)\n        {\n            block_variable<FieldT> inp(pb, path.left_digests[i], path.right_digests[i], FMT(this->annotation_prefix, \" inp_%zu\", i));\n            hasher_inputs.emplace_back(inp);\n            hashers.emplace_back(HashT(pb, 2*digest_size, inp, (i == 0 ? *computed_root : internal_output[i-1]),\n                                    FMT(this->annotation_prefix, \" load_hashers_%zu\", i)));\n        }\n\n        for (size_t i = 0; i < tree_depth; ++i)\n        {\n            /*\n            The propagators take a computed hash value (or leaf in the\n            base case) and propagate it one layer up, either in the left\n            or the right slot of authentication_path_variable.\n            */\n            propagators.emplace_back(digest_selector_gadget<FieldT>(pb, digest_size, i < tree_depth - 1 ? internal_output[i] : leaf,\n                                                                    address_bits[tree_depth-1-i], path.left_digests[i], path.right_digests[i],\n                                                                    FMT(this->annotation_prefix, \" digest_selector_%zu\", i)));\n        }\n\n        check_root.reset(new bit_vector_copy_gadget<FieldT>(pb, computed_root->bits, root.bits, read_successful, FieldT::capacity(), FMT(annotation_prefix, \" check_root\")));\n    }\n\n    void generate_r1cs_constraints()\n    {\n        /* ensure correct hash computations */\n        for (size_t i = 0; i < tree_depth; ++i)\n        {\n            // Note that we check root outside and have enforced booleanity of path.left_digests/path.right_digests outside in path.generate_r1cs_constraints\n            hashers[i].generate_r1cs_constraints(false);\n        }\n\n        /* ensure consistency of path.left_digests/path.right_digests with internal_output */\n        for (size_t i = 0; i < tree_depth; ++i)\n        {\n            propagators[i].generate_r1cs_constraints();\n        }\n\n        check_root->generate_r1cs_constraints(false, false);\n    }\n\n    void generate_r1cs_witness()\n    {\n        /* do the hash computations bottom-up */\n        for (int i = tree_depth-1; i >= 0; --i)\n        {\n            /* propagate previous input */\n            propagators[i].generate_r1cs_witness();\n\n            /* compute hash */\n            hashers[i].generate_r1cs_witness();\n        }\n\n        check_root->generate_r1cs_witness();\n    }\n\n    static size_t root_size_in_bits();\n    /* for debugging purposes */\n    static size_t expected_constraints(const size_t tree_depth);\n};\n\n\n} // end namespace `gunero`\n\n#endif /* GUNEROMERKLETREE_H_ */", "meta": {"hexsha": "592bd8d69e7955e515b89bae22aa21e62871e9d2", "size": 10526, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gunero_merkle_tree.hpp", "max_stars_repo_name": "GunClear/Silencer", "max_stars_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-17T22:27:54.000Z", "max_issues_repo_path": "src/gunero_merkle_tree.hpp", "max_issues_repo_name": "GunClear/Silencer", "max_issues_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T19:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-04T15:49:02.000Z", "max_forks_repo_path": "src/gunero_merkle_tree.hpp", "max_forks_repo_name": "GunClear/Silencer", "max_forks_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_forks_repo_licenses": ["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.1171875, "max_line_length": 173, "alphanum_fraction": 0.6773703211, "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18600595041716997}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <signal.h>\n#include <stdio.h>\n#include <boost/bind.hpp>\n#include <dark_msgs/Detect.h>\n#include <dark_msgs/DetectArray.h>\n\n#include \"dark_yolo.h\"\n\ndarknet::Yolo yolo_detector_;\ndarknet::Classify classifier_;\n\nros::Publisher detect_publish;\n\nnamespace darknet\n{\n    uint32_t Yolo::get_network_height()\n    {\n        return darknet_network_->h;\n    }\n    uint32_t Yolo::get_network_width()\n    {\n        return darknet_network_->w;\n    }\n    void Yolo::load(std::string& in_model_file, std::string& in_trained_file, double in_min_confidence, double in_nms_threshold)\n    {\n        min_confidence_ = in_min_confidence;\n        nms_threshold_ = in_nms_threshold;\n        darknet_network_ = parse_network_cfg(&in_model_file[0]);\n        load_weights(darknet_network_, &in_trained_file[0]);\n        set_batch_network(darknet_network_, 1);\n\n        layer output_layer = darknet_network_->layers[darknet_network_->n - 1];\n        darknet_boxes_.resize(output_layer.w * output_layer.h * output_layer.n);\n    }\n\n    Yolo::~Yolo()\n    {\n        free_network(darknet_network_);\n    }\n\n    std::vector< RectClassScore<float> > Yolo::detect(image& in_darknet_image)\n    {\n        return forward(in_darknet_image);\n    }\n\n    image Yolo::convert_image(const sensor_msgs::ImageConstPtr& msg)\n    {\n        if (msg->encoding != sensor_msgs::image_encodings::BGR8)\n        {\n            ROS_ERROR(\"Unsupported encoding\");\n            exit(-1);\n        }\n\n        auto data = msg->data;\n        uint32_t height = msg->height, width = msg->width, offset = msg->step - 3 * width;\n        uint32_t i = 0, j = 0;\n        image im = make_image(width, height, 3);\n\n        for (uint32_t line = height; line; line--)\n        {\n            for (uint32_t column = width; column; column--)\n            {\n                for (uint32_t channel = 0; channel < 3; channel++)\n                    im.data[i + width * height * channel] = data[j++] / 255.;\n                i++;\n            }\n            j += offset;\n        }\n\n        if (darknet_network_->w == (int) width && darknet_network_->h == (int) height)\n        {\n            return im;\n        }\n        image resized = resize_image(im, darknet_network_->w, darknet_network_->h);\n        free_image(im);\n        return resized;\n    }\n\n    std::vector< RectClassScore<float> > Yolo::forward(image& in_darknet_image)\n    {\n        float * in_data = in_darknet_image.data;\n        float *prediction = network_predict(darknet_network_, in_data);\n        layer output_layer = darknet_network_->layers[darknet_network_->n - 1];\n\n        output_layer.output = prediction;\n        int nboxes = 0;\n        int num_classes = output_layer.classes;\n        detection *darknet_detections = get_network_boxes(darknet_network_, darknet_network_->w, darknet_network_->h, min_confidence_, .5, NULL, 0, &nboxes);\n\n        do_nms_sort(darknet_detections, nboxes, num_classes, nms_threshold_);\n\n        std::vector< RectClassScore<float> > detections;\n\n        for (int i = 0; i < nboxes; i++)\n        {\n            int class_id = -1;\n            float score = 0.f;\n            //find the class\n            for(int j = 0; j < num_classes; ++j){\n                if (darknet_detections[i].prob[j] >= min_confidence_){\n                    if (class_id < 0) {\n                        class_id = j;\n                        score = darknet_detections[i].prob[j];\n                    }\n                }\n            }\n            //if class found\n            if (class_id >= 0)\n            {\n                RectClassScore<float> detection;\n\n                detection.x = darknet_detections[i].bbox.x - darknet_detections[i].bbox.w/2;\n                detection.y = darknet_detections[i].bbox.y - darknet_detections[i].bbox.h/2;\n                detection.w = darknet_detections[i].bbox.w;\n                detection.h = darknet_detections[i].bbox.h;\n                detection.score = score;\n                detection.class_type = class_id;\n                //std::cout << detection.toString() << std::endl;\n\n                detections.push_back(detection);\n            }\n        }\n        //std::cout << std::endl;\n        return detections;\n    }\n\n    uint32_t Classify::get_network_height()\n    {\n        return classify_network_->h;\n    }\n    uint32_t Classify::get_network_width()\n    {\n        return classify_network_->w;\n    }\n    void Classify::load(std::string& in_model_file, std::string& in_trained_file)\n    {\n        classify_network_ = parse_network_cfg(&in_model_file[0]);\n        // load_weights(classify_network_, &in_trained_file[0]);\n        // set_batch_network(classify_network_, 1);\n\n\n        // layer output_layer = classify_network_->layers[classify_network_->n - 1];\n        // darknet_boxes_.resize(output_layer.w * output_layer.h * output_layer.n);\n    }\n\n    Classify::~Classify()\n    {\n        free_network(classify_network_);\n    }\n\n    void Classify::classify_image(image& in_darknet_image)\n    {\n        return forward(in_darknet_image);\n    }\n\n    image Classify::convert_image(const sensor_msgs::ImageConstPtr& msg)\n    {\n        if (msg->encoding != sensor_msgs::image_encodings::BGR8)\n        {\n            ROS_ERROR(\"Unsupported encoding\");\n            exit(-1);\n        }\n\n        auto data = msg->data;\n        uint32_t height = msg->height, width = msg->width, offset = msg->step - 3 * width;\n        uint32_t i = 0, j = 0;\n        image im = make_image(width, height, 3);\n\n        for (uint32_t line = height; line; line--)\n        {\n            for (uint32_t column = width; column; column--)\n            {\n                for (uint32_t channel = 0; channel < 3; channel++)\n                    im.data[i + width * height * channel] = data[j++] / 255.;\n                i++;\n            }\n            j += offset;\n        }\n\n        if (classify_network_->w == (int) width && classify_network_->h == (int) height)\n        {\n            return im;\n        }\n        image resized = resize_image(im, classify_network_->w, classify_network_->h);\n        free_image(im);\n        return resized;\n    }\n\n    void Classify::forward(image& in_darknet_image)\n    {\n        float * in_data = in_darknet_image.data;\n        float *prediction = network_predict(classify_network_, in_data);\n\n        if(classify_network_->hierarchy) hierarchy_predictions(prediction, classify_network_->outputs, classify_network_->hierarchy, 1, 1);\n        // layer output_layer = classify_network_->layers[classify_network_->n - 1];\n        //\n        // output_layer.output = prediction;\n        // int nboxes = 0;\n        // int num_classes = output_layer.classes;\n        // detection *darknet_detections = get_network_boxes(classify_network_, classify_network_->w, classify_network_->h, min_confidence_, .5, NULL, 0, &nboxes);\n        //\n        // do_nms_sort(darknet_detections, nboxes, num_classes, nms_threshold_);\n        //\n        // std::vector< RectClassScore<float> > detections;\n        //\n        // for (int i = 0; i < nboxes; i++)\n        // {\n        //     int class_id = -1;\n        //     float score = 0.f;\n        //     //find the class\n        //     for(int j = 0; j < num_classes; ++j){\n        //         if (darknet_detections[i].prob[j] >= min_confidence_){\n        //             if (class_id < 0) {\n        //                 class_id = j;\n        //                 score = darknet_detections[i].prob[j];\n        //             }\n        //         }\n        //     }\n        //     //if class found\n        //     if (class_id >= 0)\n        //     {\n        //         RectClassScore<float> detection;\n        //\n        //         detection.x = darknet_detections[i].bbox.x - darknet_detections[i].bbox.w/2;\n        //         detection.y = darknet_detections[i].bbox.y - darknet_detections[i].bbox.h/2;\n        //         detection.w = darknet_detections[i].bbox.w;\n        //         detection.h = darknet_detections[i].bbox.h;\n        //         detection.score = score;\n        //         detection.class_type = class_id;\n        //         //std::cout << detection.toString() << std::endl;\n        //\n        //         detections.push_back(detection);\n        //     }\n        // }\n        // //std::cout << std::endl;\n        // return detections;\n    }\n}  // namespace darknet\n\nvoid rgbgr_image_y(image& im)\n{\n    int i;\n    for(i = 0; i < im.w*im.h; ++i)\n    {\n        float swap = im.data[i];\n        im.data[i] = im.data[i+im.w*im.h*2];\n        im.data[i+im.w*im.h*2] = swap;\n    }\n}\n\nimage convert_ipl_to_image(const sensor_msgs::ImageConstPtr& msg)\n{\n\n    double image_ratio_;\n    uint32_t image_top_bottom_border_;//black strips added to the input image to maintain aspect ratio while resizing it to fit the network input size\n    uint32_t image_left_right_border_;\n\n    cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(msg, \"bgr8\");//toCvCopy(image_source, sensor_msgs::image_encodings::BGR8);\n    cv::Mat mat_image = cv_image->image;\n\n    uint32_t network_input_width = yolo_detector_.get_network_width();\n    uint32_t network_input_height = yolo_detector_.get_network_height();\n\n    uint32_t image_height = msg->height,\n            image_width = msg->width;\n\n    IplImage ipl_image;\n    cv::Mat final_mat;\n\n    if (network_input_width!=image_width\n        || network_input_height != image_height)\n    {\n        //final_mat = cv::Mat(network_input_width, network_input_height, CV_8UC3, cv::Scalar(0,0,0));\n        image_ratio_ = (double ) network_input_width /  (double)mat_image.cols;\n\n        cv::resize(mat_image, final_mat, cv::Size(), image_ratio_, image_ratio_);\n        image_top_bottom_border_ = abs(final_mat.rows-network_input_height)/2;\n        image_left_right_border_ = abs(final_mat.cols-network_input_width)/2;\n        cv::copyMakeBorder(final_mat, final_mat,\n                           image_top_bottom_border_, image_top_bottom_border_,\n                           image_left_right_border_, image_left_right_border_,\n                           cv::BORDER_CONSTANT, cv::Scalar(0,0,0));\n\n    }\n    else\n        final_mat = mat_image;\n\n    ipl_image = final_mat;\n\n    unsigned char *data = (unsigned char *)ipl_image.imageData;\n    int h = ipl_image.height;\n    int w = ipl_image.width;\n    int c = ipl_image.nChannels;\n    int step = ipl_image.widthStep;\n    int i, j, k;\n\n    image darknet_image = make_image(w, h, c);\n\n    for(i = 0; i < h; ++i){\n        for(k= 0; k < c; ++k){\n            for(j = 0; j < w; ++j){\n                darknet_image.data[k*w*h + i*w + j] = data[i*step + j*c + k]/255.;\n            }\n        }\n    }\n    rgbgr_image_y(darknet_image);\n    return darknet_image;\n}\n\nint maximum_in_array(float* array, int N){\n  float big = array[0];\n  int idx = 0;\n  for(int i = 1; i < N; i++){\n    if(big < array[i]){\n      big = array[i];\n      idx = i;\n    }\n  }\n  return idx;\n}\n\nvoid image_callback(const sensor_msgs::ImageConstPtr& in_image_message)\n{\n    std::vector< RectClassScore<float> > detections;\n    image darknet_image_ = {};\n    darknet_image_ = convert_ipl_to_image(in_image_message);\n\n    detections = yolo_detector_.detect(darknet_image_);\n\n    //Check the if the network is able to score_threshold\n    // float score_array[detections.size()];\n    // for (unsigned int i = 0; i < detections.size(); ++i)\n    //   score_array[i] = detections[i].score;\n    //\n    // int idx_max = maximum_in_array(score_array,detections.size());\n    // std::cout<<\"Score: \"<<detections[idx_max].score<<\" \"<<\"Class: \"<<detections[idx_max].class_type<<std::endl;\n\n    //Output messages for detect /darknet_ros\n\n    dark_msgs::DetectArray output_detect_array;\n    output_detect_array.header = in_image_message->header;\n    for (unsigned int i = 0; i < detections.size(); ++i)\n    {\n        if(detections.size()>0)\n        {\n            dark_msgs::Detect output_detect;\n\n            output_detect.x = detections[i].x;\n            output_detect.y = detections[i].y;\n            output_detect.w = detections[i].w;\n            output_detect.h = detections[i].h;\n            if (detections[i].x < 0)\n                output_detect.x = 0;\n            if (detections[i].y < 0)\n                output_detect.y = 0;\n            if (detections[i].w < 0)\n                output_detect.w = 0;\n            if (detections[i].h < 0)\n                output_detect.h = 0;\n\n            output_detect.score = detections[i].score;\n            output_detect.class_id = detections[i].class_type;\n            //std::cout << \"x \"<< rect.x<< \" y \" << rect.y << \" w \"<< rect.width << \" h \"<< rect.height<< \" s \" << rect.score << \" c \" << in_objects[i].class_type << std::endl;\n\n            output_detect_array.objects.push_back(output_detect);\n\n        }\n    }\n\n    detect_publish.publish(output_detect_array);\n    free(darknet_image_.data);\n}\n\n// void YoloNode::config_cb(const autoware_msgs::ConfigSsd::ConstPtr& param)\n// {\n//     score_threshold_ \t= param->score_threshold;\n// }\n\nvoid mySigintHandler(int sig)\n{\n  // Do some custom action.\n  // For example, publish a stop message to some other nodes.\n\n  // All the default sigint handler does is call shutdown()\n  ros::shutdown();\n}\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"dark_ros\");\n  ROS_INFO(\"dl interface for ros is now running\");\n  ros::NodeHandle nh(\"~\");\n  signal(SIGINT, mySigintHandler);\n\n  int flag = 1; //temprorily - detection 0, classification 1, segmentation 2\n  //Network stuff\n  //Here we have to give a condition, if the network chosen in YOLO\n  //parameters which are to be converted with yaml\n\n  if(flag==0){\n    std::string image_raw_topic_str = \"/usb_cam/image_raw\", network_definition_file = \"/home/ajwahir/ros_dl/src/dl_interface/darknet/cfg/yolo.cfg\" ,pretrained_model_file = \"/home/ajwahir/ros_dl/src/dl_interface/darknet/data/yolo.weights\" ;\n    float score_threshold_ = 0.5, nms_threshold_ = 0.45;\n    ros::Subscriber subscriber_image_raw_;\n\n    ROS_INFO(\"Initializing the network on Darknet...\");\n    yolo_detector_.load(network_definition_file, pretrained_model_file, score_threshold_, nms_threshold_);\n    ROS_INFO(\"Initialization complete.\");\n\n    ROS_INFO(\"Subscribing to... %s\", image_raw_topic_str.c_str());\n    detect_publish = nh.advertise<dark_msgs::DetectArray>(\"detected_objects\", 1);\n    subscriber_image_raw_ = nh.subscribe(image_raw_topic_str, 1, image_callback);\n  }\n  else if(flag==1){\n    std::string image_raw_topic_str = \"/usb_cam/image_raw\", network_definition_file = \"/home/ajwahir/ros_dl/src/dl_interface/darknet/cfg/tiny.cfg\" ,pretrained_model_file = \"/home/ajwahir/ros_dl/src/dl_interface/darknet/data/tiny.weights\" ;\n    ros::Subscriber subscriber_image_raw_;\n\n    ROS_INFO(\"Initializing the network on Darknet...\");\n    classifier_.load(network_definition_file, pretrained_model_file);\n    ROS_INFO(\"Initialization complete.\");\n\n    ROS_INFO(\"Subscribing to... %s\", image_raw_topic_str.c_str());\n    // detect_publish = nh.advertise<dark_msgs::DetectArray>(\"detected_objects\", 1);\n    // subscriber_image_raw_ = nh.subscribe(image_raw_topic_str, 1, image_callback);\n  }\n\n\n  ros::spin();\n\n  return 0;\n}\n", "meta": {"hexsha": "bf4606f43c5aa5adc3ce5c3c0d9224a00ec98813", "size": 15037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dl_interface/src/dark_ros.cpp", "max_stars_repo_name": "ajwahir/ros_dl", "max_stars_repo_head_hexsha": "b2848a2ea72a02b61df8dc6a25bccdcad7dbbb8b", "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/dl_interface/src/dark_ros.cpp", "max_issues_repo_name": "ajwahir/ros_dl", "max_issues_repo_head_hexsha": "b2848a2ea72a02b61df8dc6a25bccdcad7dbbb8b", "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/dl_interface/src/dark_ros.cpp", "max_forks_repo_name": "ajwahir/ros_dl", "max_forks_repo_head_hexsha": "b2848a2ea72a02b61df8dc6a25bccdcad7dbbb8b", "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": 34.727482679, "max_line_length": 239, "alphanum_fraction": 0.6029128151, "num_tokens": 3743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.18600594893631}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// quant_traits.hpp\r\n//\r\n//  Copyright 2004 Eric Niebler. 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_XPRESSIVE_DETAIL_STATIC_PRODUCTIONS_QUANT_TRAITS_HPP_EAN_10_04_2005\r\n#define BOOST_XPRESSIVE_DETAIL_STATIC_PRODUCTIONS_QUANT_TRAITS_HPP_EAN_10_04_2005\r\n\r\n#include <boost/mpl/or.hpp>\r\n#include <boost/mpl/bool.hpp>\r\n#include <boost/mpl/integral_c.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/xpressive/proto/proto.hpp>\r\n#include <boost/xpressive/detail/detail_fwd.hpp>\r\n\r\n#ifdef BOOST_MSVC\r\n# pragma warning(push)\r\n# pragma warning(disable: 4307) // '+' : integral constant overflow\r\n#endif\r\n\r\nnamespace boost { namespace xpressive { namespace detail\r\n{\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // generic_quant_tag\r\n    template<uint_t Min, uint_t Max>\r\n    struct generic_quant_tag\r\n      : proto::unary_tag\r\n    {\r\n        typedef mpl::integral_c<uint_t, Min> min_type;\r\n        typedef mpl::integral_c<uint_t, Max> max_type;\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // min_type / max_type\r\n    template<typename Tag>\r\n    struct min_type : Tag::min_type {};\r\n\r\n    template<>\r\n    struct min_type<proto::unary_plus_tag> : mpl::integral_c<uint_t, 1> {};\r\n\r\n    template<>\r\n    struct min_type<proto::unary_star_tag> : mpl::integral_c<uint_t, 0> {};\r\n\r\n    template<>\r\n    struct min_type<proto::logical_not_tag> : mpl::integral_c<uint_t, 0> {};\r\n\r\n    template<typename Tag>\r\n    struct max_type : Tag::max_type {};\r\n\r\n    template<>\r\n    struct max_type<proto::unary_plus_tag> : mpl::integral_c<uint_t, UINT_MAX-1> {};\r\n\r\n    template<>\r\n    struct max_type<proto::unary_star_tag> : mpl::integral_c<uint_t, UINT_MAX-1> {};\r\n\r\n    template<>\r\n    struct max_type<proto::logical_not_tag> : mpl::integral_c<uint_t, 1> {};\r\n\r\n    struct use_simple_repeat_predicate\r\n    {\r\n        template<typename Op, typename, typename>\r\n        struct apply\r\n          : use_simple_repeat<typename proto::arg_type<Op>::type>\r\n        {\r\n        };\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // is_greedy_quant\r\n    template<typename Xpr>\r\n    struct is_greedy_quant\r\n      : mpl::false_\r\n    {\r\n    };\r\n\r\n    template<typename Op, typename Tag>\r\n    struct is_greedy_quant<proto::unary_op<Op, Tag> >\r\n      : mpl::or_\r\n        <\r\n            is_same<Tag, proto::unary_plus_tag>\r\n          , is_same<Tag, proto::unary_star_tag>\r\n          , is_same<Tag, proto::logical_not_tag>\r\n        >\r\n    {\r\n    };\r\n\r\n    template<typename Op, uint_t Min, uint_t Max>\r\n    struct is_greedy_quant<proto::unary_op<Op, generic_quant_tag<Min, Max> > >\r\n      : mpl::true_\r\n    {\r\n    };\r\n\r\n}}}\r\n\r\n#ifdef BOOST_MSVC\r\n# pragma warning(pop)\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "a947adc2178ac7b8a419f38e7fb8e6b7b3cd10d8", "size": 3025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/xpressive/detail/static/productions/quant_traits.hpp", "max_stars_repo_name": "dstrigl/mcotf", "max_stars_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "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/xpressive/detail/static/productions/quant_traits.hpp", "max_issues_repo_name": "dstrigl/mcotf", "max_issues_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "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/xpressive/detail/static/productions/quant_traits.hpp", "max_forks_repo_name": "dstrigl/mcotf", "max_forks_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "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.3689320388, "max_line_length": 85, "alphanum_fraction": 0.5811570248, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18573737651311362}}
{"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 NUMSCALE SAS\n//\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_MEMORY_FUNCTIONS_SIMD_SSE_AVX_EXTRACT_HPP_INCLUDED\n#define BOOST_SIMD_MEMORY_FUNCTIONS_SIMD_SSE_AVX_EXTRACT_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_AVX_SUPPORT\n\n#include <boost/simd/memory/functions/extract.hpp>\n#include <boost/simd/sdk/simd/meta/retarget.hpp>\n#include <boost/simd/sdk/meta/cardinal_of.hpp>\n#include <boost/simd/sdk/meta/scalar_of.hpp>\n#include <boost/mpl/modulus.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( extract_\n                                    , boost::simd::tag::avx_\n                                    , (A0)(A1)\n                                    , ((simd_< integer_<A0>, boost::simd::tag::avx_ >))\n                                      (mpl_integral_< scalar_< integer_<A1> > >)\n                                    )\n  {\n    typedef typename meta::scalar_of<A0>::type   result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1) const\n    {\n      typedef typename meta::retarget<A0, tag::sse_>::type ltype;\n      typedef typename meta::cardinal_of<ltype>::type card;\n\n      ltype that = _mm256_extractf128_si256(a0(), A1::value / ltype::static_size);\n      return extract(that, mpl::modulus< A1, card >());\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( extract_\n                                    , boost::simd::tag::avx_\n                                    , (A0)(A1)\n                                    , ((simd_< single_<A0>, boost::simd::tag::avx_ >))\n                                      (mpl_integral_< scalar_< integer_<A1> > >)\n                                    )\n  {\n    typedef typename meta::scalar_of<A0>::type   result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1) const\n    {\n      typedef typename meta::retarget<A0, tag::sse_>::type ltype;\n      typedef typename meta::cardinal_of<ltype>::type card;\n\n      ltype that = _mm256_extractf128_ps(a0(), A1::value / ltype::static_size);\n      return extract(that, mpl::modulus< A1, card >());\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( extract_\n                                    , boost::simd::tag::avx_\n                                    , (A0)(A1)\n                                    , ((simd_< double_<A0>, boost::simd::tag::avx_ >))\n                                      (mpl_integral_< scalar_< integer_<A1> > >)\n                                    )\n  {\n    typedef typename meta::scalar_of<A0>::type   result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1) const\n    {\n      typedef typename meta::retarget<A0, tag::sse_>::type ltype;\n      typedef typename meta::cardinal_of<ltype>::type card;\n\n      ltype that = _mm256_extractf128_pd(a0(), A1::value / ltype::static_size);\n      return extract(that, mpl::modulus< A1, card >());\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "e5f6e5d2cc23fe577f17bcae105ca1194b4f4c6a", "size": 3363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/memory/functions/simd/sse/avx/extract.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/sdk/include/boost/simd/memory/functions/simd/sse/avx/extract.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/sdk/include/boost/simd/memory/functions/simd/sse/avx/extract.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": 40.5180722892, "max_line_length": 87, "alphanum_fraction": 0.5304787392, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18573737651311362}}
{"text": "#include \"abstract.hpp\"\n\n#include \"t1p.h\"\n#include \"box.h\"\n\n#include <ap_disjunction.h>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <list>\n#include <Eigen/Dense>\n\n//static Managers mans{t1p_manager_alloc(), box_manager_alloc()};\n\nArithExpr::ArithExpr(): expr{nullptr} {}\n\nArithExpr::ArithExpr(double constant):\n  expr{ap_texpr0_cst_scalar_double(constant)} {}\n\nArithExpr::ArithExpr(int ind): expr{ap_texpr0_dim(ind)} {}\n\nArithExpr::ArithExpr(double lower, double upper):\n  expr{ap_texpr0_cst_interval_double(lower, upper)} {}\n\nArithExpr::ArithExpr(ap_texpr0_t* e): expr{e} {}\n\nArithExpr::ArithExpr(const ArithExpr& other):\n  expr{ap_texpr0_copy(other.expr)} {}\n\nArithExpr::ArithExpr(ArithExpr&& other): expr(other.expr) {\n  other.expr = nullptr;\n}\n\nArithExpr::~ArithExpr() {\n  if (expr != nullptr) {\n    ap_texpr0_free(expr);\n  }\n}\n\nArithExpr& ArithExpr::operator=(const ArithExpr& other) {\n  if (expr != nullptr) {\n    ap_texpr0_free(expr);\n  }\n  expr = ap_texpr0_copy(other.expr);\n  return *this;\n}\n\nArithExpr& ArithExpr::operator=(ArithExpr&& other) {\n  if (expr != nullptr) {\n    ap_texpr0_free(expr);\n  }\n  expr = other.expr;\n  other.expr = nullptr;\n  return *this;\n}\n\nArithExpr ArithExpr::negate() const {\n  return ArithExpr{ap_texpr0_unop(AP_TEXPR_NEG, ap_texpr0_copy(expr),\n        AP_RTYPE_DOUBLE, AP_RDIR_NEAREST)};\n}\n\nArithExpr ArithExpr::operator+(const ArithExpr& other) const {\n  return ArithExpr{ap_texpr0_binop(AP_TEXPR_ADD,\n      ap_texpr0_copy(expr),\n      ap_texpr0_copy(other.expr),\n      AP_RTYPE_DOUBLE, AP_RDIR_NEAREST)};\n}\n\nArithExpr ArithExpr::operator-(const ArithExpr& other) const {\n  return ArithExpr{ap_texpr0_binop(AP_TEXPR_SUB,\n      ap_texpr0_copy(expr),\n      ap_texpr0_copy(other.expr),\n      AP_RTYPE_DOUBLE, AP_RDIR_NEAREST)};\n}\n\nArithExpr ArithExpr::operator*(const ArithExpr& other) const {\n  return ArithExpr{ap_texpr0_binop(AP_TEXPR_MUL,\n      ap_texpr0_copy(expr),\n      ap_texpr0_copy(other.expr),\n      AP_RTYPE_DOUBLE, AP_RDIR_NEAREST)};\n}\n\nArithExpr ArithExpr::operator/(const ArithExpr& other) const {\n  return ArithExpr{ap_texpr0_binop(AP_TEXPR_DIV,\n      ap_texpr0_copy(expr),\n      ap_texpr0_copy(other.expr),\n      AP_RTYPE_DOUBLE, AP_RDIR_NEAREST)};\n}\n\nArithExpr ArithExpr::operator^(int power) const {\n  // Apron's t1p domain does not support exponents yet, but since we only\n  // allow exponents to integer powers we just expand the exponent here.\n  ap_texpr0_t* ret = ap_texpr0_copy(this->expr);\n  for (int i = 0; i < power - 1; i++) {\n    ret = ap_texpr0_binop(AP_TEXPR_MUL,\n        ap_texpr0_copy(this->expr),\n        ret,\n        AP_RTYPE_DOUBLE, AP_RDIR_NEAREST);\n  }\n  return ArithExpr{ret};\n}\n\nLinCons::LinCons(): weights{Eigen::MatrixXd(0, 0)},\n  biases{Eigen::VectorXd(0)} {}\n\nLinCons::LinCons(const Eigen::MatrixXd& ws, const Eigen::VectorXd& bs):\n  weights{ws}, biases{bs} {}\n\ndouble LinCons::distance_from(const Eigen::VectorXd& x) const {\n  // A x <= b -> A x - b <= 0\n  // distance = max(A x - b)\n  // If distance is positive then it is the l_infty distance between x and\n  // the constrained space. Otherwise, distance decreases as we move away\n  // from the safe region.\n  return (this->weights * x - this->biases).maxCoeff();\n}\n\ninline ap_manager_t* get_manager_from_domain(AbstractDomain dom, size_t size) {\n  ap_manager_t* base;\n  switch (dom) {\n    case AbstractDomain::ZONOTOPE:\n      base = t1p_manager_alloc();\n      break;\n    case AbstractDomain::INTERVAL:\n      base = box_manager_alloc();\n      break;\n    case AbstractDomain::POLYHEDRA:\n      base = pk_manager_alloc(false);\n      break;\n    default:\n      throw std::runtime_error(\"Unrecognized domain in get_manager\");\n  }\n  if (size <= 1) {\n    return base;\n  }\n  return ap_disjunction_manager_alloc(base, NULL);\n}\n\nAbstractVal::AbstractVal(): man{nullptr}, value{nullptr} {}\n\n// Note that ap_manager_copy doesn't actually create a copy of m, it only\n// increments a reference count, so this copy is not expensive.\nAbstractVal::AbstractVal(ap_manager_t* m, ap_abstract0_t* v):\n  man{ap_manager_copy(m)}, value{v} {}\n\nAbstractVal::AbstractVal(AbstractDomain dom,\n    const std::vector<Eigen::VectorXd>& a,\n    const std::vector<double>& b): domain{dom} {\n  //if (dom == AbstractDomain::ZONOTOPE) {\n  //  man = mans.get_t1p_manager();\n  //} else {\n  //  man = mans.get_box_manager();\n  //}\n  man = get_manager_from_domain(dom, 1);\n  ap_lincons0_array_t arr = ap_lincons0_array_make(a.size());\n  for (size_t i = 0; i < a.size(); i++) {\n    ap_linexpr0_t* expr = ap_linexpr0_alloc(AP_LINEXPR_DENSE, a[i].size());\n    for (int j = 0; j < a[i].size(); j++) {\n      ap_linexpr0_set_coeff_scalar_double(expr, j, -a[i](j));\n    }\n    ap_linexpr0_set_cst_scalar_double(expr, b[i]);\n    ap_lincons0_t cons = ap_lincons0_make(AP_CONS_SUPEQ, expr, NULL);\n    arr.p[i] = cons;\n  }\n  value = ap_abstract0_of_lincons_array(man, 0, a[0].size(), &arr);\n  ap_lincons0_array_clear(&arr);\n}\n\nAbstractVal::AbstractVal(AbstractDomain dom, const LinCons& lc) {\n  man = get_manager_from_domain(dom, 1);\n  ap_lincons0_array_t arr = ap_lincons0_array_make(lc.biases.size());\n  for (int i = 0; i < lc.biases.size(); i++) {\n    ap_linexpr0_t* expr = ap_linexpr0_alloc(AP_LINEXPR_DENSE,\n        lc.weights.row(i).size());\n    for (int j = 0; j < lc.weights.row(i).size(); j++) {\n      ap_linexpr0_set_coeff_scalar_double(expr, j, -lc.weights(i, j));\n    }\n    ap_linexpr0_set_cst_scalar_double(expr, lc.biases(i));\n    ap_lincons0_t cons = ap_lincons0_make(AP_CONS_SUPEQ, expr, NULL);\n    arr.p[i] = cons;\n  }\n  value = ap_abstract0_of_lincons_array(man, 0, lc.weights.row(0).size(), &arr);\n  ap_lincons0_array_clear(&arr);\n}\n\nAbstractVal::AbstractVal(AbstractDomain dom,\n    const Eigen::VectorXd& lowers,\n    const Eigen::VectorXd& uppers): domain{dom} {\n  //if (dom == AbstractDomain::ZONOTOPE) {\n  //  man = mans.get_t1p_manager();\n  //} else {\n  //  man = mans.get_box_manager();\n  //}\n  man = get_manager_from_domain(dom, 1);\n  ap_interval_t** itv =\n    (ap_interval_t**) malloc(lowers.size() * sizeof(ap_interval_t*));\n  for (int i = 0; i < lowers.size(); i++) {\n    itv[i] = ap_interval_alloc();\n    ap_interval_set_double(itv[i], lowers(i), uppers(i));\n  }\n  value = ap_abstract0_of_box(man, 0, lowers.size(), itv);\n  ap_interval_array_free(itv, lowers.size());\n}\n\nAbstractVal::AbstractVal(const AbstractVal& other) {\n  man = ap_manager_copy(other.man);\n  value = ap_abstract0_copy(man, other.value);\n}\n\nAbstractVal::AbstractVal(AbstractVal&& other) {\n  man = other.man;\n  value = other.value;\n  other.man = nullptr;\n  other.value = nullptr;\n}\n\nAbstractVal::~AbstractVal() {\n  if (value != nullptr) {\n    ap_abstract0_free(man, value);\n  }\n  if (man != nullptr) {\n    // Internally, apron managers are reference counted. If this manager is\n    // still used elsewhere (assuming it was copied with ap_manager_copy) the\n    // reference count will be decremented but the manager will not be freed.\n    ap_manager_free(man);\n  }\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::add_trailing_dimensions(\n    int n) const {\n  ap_dimchange_t* dimchange = ap_dimchange_alloc(0, n);\n  int d = dims();\n  for (int i = 0; i < n; i++) {\n    dimchange->dim[i] = d;\n  }\n  ap_abstract0_t* res = ap_abstract0_add_dimensions(\n      man, false, value, dimchange, false);\n  ap_dimchange_free(dimchange);\n  return this->make_new(res);\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::add_leading_dimensions(\n    int n) const {\n  ap_dimchange_t* dimchange = ap_dimchange_alloc(0, n);\n  for (int i = 0; i < n; i++) {\n    dimchange->dim[i] = 0;\n  }\n  ap_abstract0_t* res = ap_abstract0_add_dimensions(\n      man, false, value, dimchange, false);\n  ap_dimchange_free(dimchange);\n  return this->make_new(res);\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::remove_trailing_dimensions(\n    int n) const {\n  // NOTE: t1p_remove_dimensions is buggy, but seems to work for removing\n  // one dimension. Therefore, we remove one dimension at a time until n\n  // dimensions have been removed.\n  ap_abstract0_t* res = ap_abstract0_copy(man, value);\n  ap_dimchange_t* dimchange = ap_dimchange_alloc(0, 1);\n  for (int i = 0; i < n; i++) {\n    int d = ap_abstract0_dimension(man, res).realdim;\n    dimchange->dim[0] = d - 1;\n\n    //std::cout << \"remove_trailing_dimensions before\" << std::endl;\n    //this->print(stdout);\n    res = ap_abstract0_remove_dimensions(man, true, res, dimchange);\n    //std::cout << \"remove_trailing_dimensions after\" << std::endl;\n    //ap_abstract0_fprint(stdout, man, res, NULL);\n  }\n  ap_dimchange_free(dimchange);\n  return this->make_new(res);\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::meet_linear_constraint(\n    const Eigen::MatrixXd& a,\n    const Eigen::VectorXd& b) const {\n  int size = b.size();\n  ap_lincons0_array_t arr = ap_lincons0_array_make(size);\n\n  // a1 x1 + a2 x2 + ... + an xn <= b ==>\n  // -a1 x1 - a2 x2 - ... - an xn + b >= 0\n  for (int i = 0; i < size; i++) {\n    ap_linexpr0_t* expr = ap_linexpr0_alloc(AP_LINEXPR_DENSE, a.cols());\n    for (int j = 0; j < a.cols(); j++) {\n      ap_linexpr0_set_coeff_scalar_double(expr, j, -a(i,j));\n    }\n    ap_linexpr0_set_cst_scalar_double(expr, b(i));\n    arr.p[i] = ap_lincons0_make(AP_CONS_SUPEQ, expr, NULL);\n  }\n\n  ap_abstract0_t* v = ap_abstract0_meet_lincons_array(man, false, value, &arr);\n  ap_lincons0_array_clear(&arr);\n\n  return this->make_new(v);\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::scalar_affine(\n    const Eigen::MatrixXd& w,\n    const Eigen::VectorXd& b) const {\n  int in_size = w.cols();\n  int out_size = w.rows();\n\n  std::unique_ptr<AbstractVal> v{};\n  if (out_size > in_size) {\n    v = this->add_trailing_dimensions(out_size - in_size);\n  } else {\n    v = this->clone();\n  }\n\n  ap_dim_t* dims = (ap_dim_t*) malloc(out_size * sizeof(ap_dim_t));\n  ap_linexpr0_t** update = (ap_linexpr0_t**) malloc(out_size *\n      sizeof(ap_linexpr0_t*));\n  for (int j = 0; j < out_size; j++) {\n    dims[j] = j;\n    update[j] = ap_linexpr0_alloc(AP_LINEXPR_DENSE, in_size);\n    for (int k = 0; k < in_size; k++) {\n      ap_linexpr0_set_coeff_scalar_double(update[j], k, w(j,k));\n    }\n    ap_linexpr0_set_cst_scalar_double(update[j], b(j));\n  }\n\n  ap_abstract0_t* res = ap_abstract0_assign_linexpr_array(\n      man, false, v->get_value(), dims, update, out_size, NULL);\n\n  free(dims);\n  for (int j = 0; j < out_size; j++) {\n    ap_linexpr0_free(update[j]);\n  }\n  free(update);\n\n  std::unique_ptr<AbstractVal> ret = this->make_new(res);\n  if (in_size > out_size) {\n    ret = ret->remove_trailing_dimensions(in_size - out_size);\n  }\n  return ret;\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::interval_affine(\n    const Eigen::MatrixXd& wl,\n    const Eigen::MatrixXd& wu,\n    const Eigen::VectorXd& bl,\n    const Eigen::VectorXd& bu) const {\n  int in_size = wl.cols();\n  int out_size = wl.rows();\n\n  std::unique_ptr<AbstractVal> v{};\n  if (out_size > in_size) {\n    v = this->add_trailing_dimensions(out_size - in_size);\n  } else {\n    v = this->clone();\n  }\n\n  ap_dim_t* dims = (ap_dim_t*) malloc(out_size * sizeof(ap_dim_t));\n  ap_linexpr0_t** update = (ap_linexpr0_t**) malloc(out_size *\n      sizeof(ap_linexpr0_t*));\n  for (int j = 0; j < out_size; j++) {\n    dims[j] = j;\n    update[j] = ap_linexpr0_alloc(AP_LINEXPR_DENSE, in_size);\n    for (int k = 0; k < in_size; k++) {\n      ap_linexpr0_set_coeff_interval_double(update[j], k, wl(j,k), wu(j, k));\n    }\n    ap_linexpr0_set_cst_interval_double(update[j], bl(j), bu(j));\n  }\n\n  ap_abstract0_t* res = ap_abstract0_assign_linexpr_array(\n      man, false, v->get_value(), dims, update, out_size, NULL);\n\n  free(dims);\n  for (int j = 0; j < out_size; j++) {\n    ap_linexpr0_free(update[j]);\n  }\n  free(update);\n\n  std::unique_ptr<AbstractVal> ret = this->make_new(res);\n  if (in_size > out_size) {\n    ret = ret->remove_trailing_dimensions(in_size - out_size);\n  }\n  return ret;\n\n  /*\n  // Create an abstract value for the coefficients.\n  ap_interval_t** arr = (ap_interval_t**) malloc((in_size + 1) * out_size *\n      sizeof(ap_interval_t*));\n  for (int i = 0; i < in_size * out_size; i++) {\n    arr[i] = ap_interval_alloc();\n    int r = i / in_size;\n    int c = i % in_size;\n    ap_interval_set_double(arr[i], wl(r, c), wu(r, c));\n  }\n  for (int i = 0; i < out_size; i++) {\n    int ind = i + in_size * out_size;\n    arr[ind] = ap_interval_alloc();\n    ap_interval_set_double(arr[ind], bl(i), bu(i));\n  }\n  std::unique_ptr<AbstractVal> coeffs = this->make_new(\n      ap_abstract0_of_box(\n          this->man, 0, (in_size + 1) * out_size, arr));\n\n  std::unique_ptr<AbstractVal> input = this->append(*coeffs);\n  // NOTE: the size of input is in_size * out_size (for the coefficients\n  // + out_size (for the biases) + in_size (for the input)\n\n  // Construct an ArithExpr for this assignment\n  std::vector<ArithExpr> exprs;\n  for (int i = 0; i < out_size; i++) {\n    // Start with the bias term\n    ArithExpr row(in_size * (out_size + 1) + i);\n    for (int j = 0; j < in_size; j++) {\n      // r = r + coeff(i, j) * x(j)\n      row = row + ArithExpr((i + 1) * in_size + j) * ArithExpr(j);\n    }\n    exprs.push_back(row);\n  }\n\n  // Perform computation\n  std::unique_ptr<AbstractVal> output = input->arith_computation(exprs);\n  return output->remove_trailing_dimensions(in_size * out_size + in_size);\n  */\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::relu() const {\n  std::unique_ptr<AbstractVal> z = this->clone();\n  size_t num_dims = this->dims();\n  Eigen::VectorXd b{Eigen::VectorXd::Zero(1)};\n  Eigen::MatrixXd relu_w = Eigen::MatrixXd::Identity(num_dims, num_dims);\n  Eigen::VectorXd relu_b = Eigen::VectorXd::Zero(num_dims);\n  for (size_t i = 0; i < num_dims; i++) {\n    Eigen::MatrixXd alt = Eigen::MatrixXd::Zero(1, num_dims);\n    Eigen::MatrixXd agt = alt;\n    alt(0,i) = 1.0;\n    agt(0,i) = -1.0;\n\n    std::unique_ptr<AbstractVal> zlt = z->meet_linear_constraint(alt, b);\n    z = z->meet_linear_constraint(agt, b);\n\n    relu_w(i, i) = 0.0;\n    zlt = zlt->scalar_affine(relu_w, relu_b);\n    relu_w(i, i) = 1.0;\n\n    z = z->join(*zlt);\n  }\n\n  return z;\n}\n\n// NOTE: by convention, the this and other should point to the same manager.\n// The manager of this is used, so if it is not compatible with the manager of\n// other I'm not sure what happens.\nstd::unique_ptr<AbstractVal> AbstractVal::join(const AbstractVal& other) const {\n  ap_abstract0_t* res = ap_abstract0_join(man, false, value, other.get_value());\n  return this->make_new(res);\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::meet(const AbstractVal& other) const {\n  ap_abstract0_t* res = ap_abstract0_meet(man, false, value, other.get_value());\n  return this->make_new(res);\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::widen(\n    const AbstractVal& other) const {\n  ap_abstract0_t* res = ap_abstract0_widening(man, value, other.get_value());\n  return this->make_new(res);\n}\n\nbool AbstractVal::operator==(const AbstractVal& other) const {\n  return ap_abstract0_is_eq(man, value, other.get_value());\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::append(const AbstractVal& b) const {\n  int n1 = b.dims();\n  int n2 = this->dims();\n  std::unique_ptr<AbstractVal> p1 = this->add_trailing_dimensions(n1);\n  std::unique_ptr<AbstractVal> p2 = b.add_leading_dimensions(n2);\n  // At this point p1 has n1 extra unconstrained dimensions at the end and\n  // p2 has n2 extra unconstrained dimensions at the beginning. Meeting\n  // these two gives the desired result.\n\n  // Apron seems to have a problem doing this meet when the zonotopes have some\n  // unconstrained dimensions.\n  // return p1->meet(*p2);\n  //\n  // Our second attempt was to convert both abstract values to arrays of linear\n  // constraints, append the two arrays, then create a new value which\n  // satisfies all of the resulting constraints. This runs into a very strange\n  // use-after-free bug which I haven't been able to track down.\n  //\n  // The current strategy is to convert only b to an array of linear\n  // constraints and to meet this with the resulting array.\n\n  ap_lincons0_array_t lc2 = ap_abstract0_to_lincons_array(\n      p2->get_manager(), p2->get_value());\n\n  ap_abstract0_t* v = ap_abstract0_meet_lincons_array(\n      man, false, p1->get_value(), &lc2);\n\n  ap_lincons0_array_clear(&lc2);\n\n  return this->make_new(v);\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::arith_computation(\n    const std::vector<ArithExpr>& exprs) const {\n  int in_size = this->dims();\n  int out_size = exprs.size();\n  std::unique_ptr<AbstractVal> inp;\n  if (out_size > in_size) {\n    inp = this->add_trailing_dimensions(out_size - in_size);\n  } else {\n    inp = this->clone();\n  }\n  ap_texpr0_t** arr =\n    (ap_texpr0_t**) malloc(exprs.size() * sizeof(ap_texpr0_t*));\n  ap_dim_t* dims = (ap_dim_t*) malloc(exprs.size() * sizeof(dims));\n  for (size_t i = 0; i < exprs.size(); i++) {\n    arr[i] = ap_texpr0_copy(exprs[i].get_texpr());\n    dims[i] = i;\n  }\n  ap_abstract0_t* v = ap_abstract0_assign_texpr_array(\n      man, false, inp->get_value(), dims, arr, exprs.size(), NULL);\n  free(dims);\n  for (size_t i = 0; i < exprs.size(); i++) {\n    ap_texpr0_free(arr[i]);\n  }\n  free(arr);\n  std::unique_ptr<AbstractVal> ret = this->make_new(v);\n  if (in_size > out_size) {\n    ret = ret->remove_trailing_dimensions(in_size - out_size);\n  }\n  return ret;\n}\n\nbool AbstractVal::contains_point(const Eigen::VectorXd& x) const {\n  ap_interval_t** itv = (ap_interval_t**) malloc(\n      x.size() * sizeof(ap_interval_t*));\n  for (int i = 0; i < x.size(); i++) {\n    itv[i] = ap_interval_alloc();\n    ap_interval_set_double(itv[i], x(i), x(i));\n  }\n  ap_abstract0_t* point = ap_abstract0_of_box(man, 0, x.size(), itv);\n  ap_interval_array_free(itv, x.size());\n  ap_abstract0_t* meet = ap_abstract0_meet(man, false, value, point);\n  ap_abstract0_free(man, point);\n  bool bottom = ap_abstract0_is_bottom(man, meet);\n  ap_abstract0_free(man, meet);\n  return !bottom;\n}\n\nbool AbstractVal::contains(const AbstractVal& x) const {\n  // Convert this to an array of linear constraints\n  ap_lincons0_array_t arr = ap_abstract0_to_lincons_array(man, value);\n\n  // Negate each constraint\n  for (size_t i = 0; i < arr.size; i++) {\n    ap_linexpr0_t* expr = arr.p[i].linexpr0;\n    for (size_t j = 0; j < x.dims(); j++) {\n      ap_coeff_t* c = ap_linexpr0_coeffref(expr, j);\n      ap_coeff_neg(c, c);\n    }\n    ap_coeff_t* c = ap_linexpr0_cstref(expr);\n    ap_coeff_neg(c, c);\n  }\n\n  // Meet the new constraints with x\n  ap_abstract0_t* v = ap_abstract0_meet_lincons_array(man, false, value, &arr);\n  ap_lincons0_array_clear(&arr);\n\n  // Since the new constraints contain everything NOT in this, if the meet is\n  // not empty, then x is not entirely contained within this.\n  bool bottom = ap_abstract0_is_bottom(man, v);\n  ap_abstract0_free(man, v);\n  return bottom;\n}\n\nEigen::VectorXd AbstractVal::get_center() const {\n  ap_interval_t** bbox = ap_abstract0_to_box(man, value);\n  Eigen::VectorXd center(dims());\n  for (size_t i = 0; i < dims(); i++) {\n    double l, u;\n    ap_double_set_scalar(&l, bbox[i]->inf, MPFR_RNDN);\n    ap_double_set_scalar(&u, bbox[i]->sup, MPFR_RNDN);\n    center(i) = (l + u) / 2.0;\n  }\n  return center;\n}\n\nEigen::VectorXd AbstractVal::get_contained_point() const {\n  ap_interval_t** bbox = ap_abstract0_to_box(man, value);\n  Eigen::VectorXd lower(this->dims());\n  Eigen::VectorXd upper(this->dims());\n  for (size_t i = 0; i < dims(); i++) {\n    double l, u;\n    ap_double_set_scalar(&l, bbox[i]->inf, MPFR_RNDN);\n    ap_double_set_scalar(&u, bbox[i]->sup, MPFR_RNDN);\n    lower(i) = l;\n    upper(i) = u;\n  }\n  while (true) {\n    // Choose a random point inside the bounding box of this abstract value,\n    // then check to see if it is contained in this value. If it is we return\n    // it, otherwise try another point.\n    Eigen::VectorXd rand = Eigen::VectorXd::Random(dims());\n    for (size_t i = 0; i < this->dims(); i++) {\n      rand(i) = (1 + rand(i)) * (upper(i) - lower(i)) / 2.0 + lower(i);\n    }\n    if (this->contains_point(rand)) {\n      return rand;\n    }\n  }\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::clone() const {\n  return std::make_unique<AbstractVal>(man, ap_abstract0_copy(man, value));\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::bottom() const {\n  return std::make_unique<AbstractVal>(man, ap_abstract0_bottom(man,\n        0, this->dims()));\n}\n\nLinCons AbstractVal::get_lincons() const {\n  ap_lincons0_array_t res = ap_abstract0_to_lincons_array(man, value);\n  int d = dims();\n  std::vector<Eigen::VectorXd> ws;\n  std::vector<double> bs;\n  for (int i = 0; i < res.size; i++) {\n    Eigen::VectorXd r(d);\n    ap_linexpr0_t* exp = res.p[i].linexpr0;\n    for (int j = 0; j < d; j++) {\n      ap_coeff_t* c = ap_linexpr0_coeffref(exp, j);\n      if (c->discr != AP_COEFF_SCALAR) {\n        throw std::runtime_error(\"Non-scalar coefficient in get_lincons\");\n      }\n      double d;\n      ap_double_set_scalar(&d, c->val.scalar, MPFR_RNDN);\n      r(j) = d;\n    }\n    ap_coeff_t* c = ap_linexpr0_cstref(exp);\n    if (c->discr != AP_COEFF_SCALAR) {\n      throw std::runtime_error(\"Non-scalar coefficient in get_lincons\");\n    }\n    double d;\n    ap_double_set_scalar(&d, c->val.scalar, MPFR_RNDN);\n    switch (res.p[i].constyp) {\n      case AP_CONS_EQ:\n        ws.push_back(r);\n        bs.push_back(-d);\n        ws.push_back(-r);\n        bs.push_back(d);\n        break;\n      case AP_CONS_SUPEQ:\n      case AP_CONS_SUP:\n        ws.push_back(-r);\n        bs.push_back(d);\n        break;\n      default:\n        throw std::runtime_error(\"Unknown constraint type in get_lincons\");\n    }\n  }\n  ap_lincons0_array_clear(&res);\n  Eigen::MatrixXd weights(ws.size(), d);\n  Eigen::VectorXd biases(bs.size());\n  for (int i = 0; i < ws.size(); i++) {\n    weights.row(i) = ws[i];\n    biases(i) = bs[i];\n  }\n  return LinCons(weights, biases);\n}\n\nstd::unique_ptr<AbstractVal> AbstractVal::make_new(ap_abstract0_t* a) const {\n  return std::make_unique<AbstractVal>(man, a);\n}\n\n//double distance_to_abstract0(ap_manager_t* man, ap_abstract0_t* a,\n//    const Eigen::VectorXd& x) {\n//  // Convert the abstract value to an array of linear constraints\n//  ap_lincons0_array_t arr = ap_abstract0_to_lincons_array(man, a);\n//  // Determine whether each constraint is satisfied and find the constraint\n//  // which is closest to x\n//  bool satisfies_all = true;\n//  for (int i = 0; i < arr.size; i++) {\n//    // TODO: I'm not sure what the semantics of arr.p[i].scalar are. It seems\n//    // to only be used for EQMOD constraints.\n//    ap_linexpr0_t* expr = arr.p[i].linexpr0;\n//    Eigen::VectorXd coeffs(x.size());\n//    for (int j = 0; j < x.size(); j++) {\n//      ap_coeff_t* c = ap_linexpr0_coeffref(expr, j);\n//      if (c->discr == AP_COEFF_SCALAR) {\n//        // TODO\n//      } else {\n//        // TODO\n//      }\n//    }\n//  }\n//  return 0;\n//}\n//\n//double AbstractVal::distance_to_point(const Eigen::VectorXd& x) const {\n//  return distance_to_abstract0(this->man, this->value, x);\n//}\n\ntypedef struct {\n  ap_abstract0_t* abs;\n  Eigen::VectorXd center;\n} abstract_value;\n\nEigen::VectorXd compute_center(ap_manager_t* man, ap_abstract0_t* a) {\n  ap_interval_t** itv = ap_abstract0_to_box(man, a);\n  int d = ap_abstract0_dimension(man, a).realdim;\n  Eigen::VectorXd center(d);\n  for (int i = 0; i < d; i++) {\n    double l, u;\n    ap_double_set_scalar(&l, itv[i]->inf, MPFR_RNDN);\n    ap_double_set_scalar(&u, itv[i]->sup, MPFR_RNDN);\n    center(d) = (l + u) / 2.0;\n  }\n  ap_interval_array_free(itv, d);\n  return center;\n}\n\n// Given a manager (this is a manager for the disjunction domain) and a\n// disjunctive element, reduce the number of disjuncts to size. This is done\n// in place so that after this call, the value pointed to by a is a disjunctive\n// value with an appropriate number of disjuncts. Note that this function does\n// not perform any checks and assumes a is a disjunction. This function\n// typically returns a reference to a, but not always.\nap_abstract0_t* merge_disjuncts(ap_manager_t* man, ap_abstract0_t* a,\n    size_t size) {\n  ap_disjunction_t* ad = (ap_disjunction_t*) a->value;\n  size_t s = ad->size;\n  // Get the manager for the underlying abstract domain\n  ap_disjunction_internal_t* in = (ap_disjunction_internal_t*) man->internal;\n  ap_manager_t* under = in->manager;\n\n  // Compute the center of the bounding box of each disjunct\n  std::list<abstract_value> vals{};\n  bool is_top = false;\n  for (size_t i = 0; i < s; i++) {\n    abstract_value v;\n    ap_abstract0_t* abs = (ap_abstract0_t*) ad->p[i];\n    if (ap_abstract0_is_top(under, abs)) {\n      is_top = true;\n      break;\n    } else if (ap_abstract0_is_bottom(under, abs)) {\n      // Don't add bottom elements to vals\n      continue;\n    }\n    v.abs = ap_abstract0_copy(under, (ap_abstract0_t*) ad->p[i]);\n    v.center = compute_center(under, v.abs);\n    vals.push_back(v);\n  }\n  if (is_top) {\n    int d = ap_abstract0_dimension(man, a).realdim;\n    ap_abstract0_free(man, a);\n    return ap_abstract0_top(man, 0, d);\n  } else if (vals.size() == 0) {\n    int d = ap_abstract0_dimension(man, a).realdim;\n    ap_abstract0_free(man, a);\n    return ap_abstract0_bottom(man, 0, d);\n  }\n\n  if (s <= size) {\n    return a;\n  }\n\n  while (vals.size() > size) {\n    // Find the two elements whose centers (computed by bounding box) are\n    // closest to each other.\n    std::list<abstract_value>::iterator it1;\n    std::list<abstract_value>::iterator it2;\n    double best_dist = std::numeric_limits<double>::max();\n    for (auto i = vals.begin(); i != vals.end(); i++) {\n      for (auto j = vals.begin(); j != vals.end(); j++) {\n        double dist = (i->center - j->center).norm();\n        if (dist < best_dist) {\n          best_dist = dist;\n          it1 = i;\n          it2 = j;\n        }\n      }\n    }\n    // Join these two elements.\n    ap_abstract0_t* a1 = it1->abs;\n    ap_abstract0_t* a2 = it2->abs;\n    ap_abstract0_t* join = ap_abstract0_join(under, false, a1, a2);\n    abstract_value av;\n    av.abs = join;\n    av.center = compute_center(under, join);\n    // Remove the two elements from vals and add the new one.\n    vals.erase(it1);\n    vals.erase(it2);\n    vals.push_back(av);\n  }\n\n  // Finally, we replace the values in a with those in vals.\n  for (size_t i = 0; i < s; i++) {\n    ap_abstract0_free(under, (ap_abstract0_t*) ad->p[i]);\n  }\n  free(ad->p);\n  ad->size = size;\n  ad->p = (void**) malloc(size * sizeof(void*));\n  int ind = 0;\n  for (auto it = vals.begin(); it != vals.end(); it++) {\n    ad->p[ind] = it->abs;\n    ind++;\n  }\n  return a;\n}\n\nvoid AbstractVal::print(FILE* out) const {\n  ap_abstract0_fprint(out, man, value, NULL);\n}\n\nPowerset::Powerset(ap_manager_t* m, ap_abstract0_t* v, size_t s):\n  AbstractVal{m, v}, size{s} {}\n\nPowerset::Powerset(const Powerset& p): AbstractVal{p}, size{p.size} {}\n\nPowerset::Powerset(AbstractDomain dom, size_t s,\n    const std::vector<Eigen::VectorXd>& a, const std::vector<double>& b) {\n  //ap_manager_t* base_manager;\n  //if (dom == AbstractDomain::ZONOTOPE) {\n  //  base_manager = mans.get_t1p_manager();\n  //} else {\n  //  base_manager = mans.get_box_manager();\n  //}\n  //man = mans.get_disj_manager(base_manager);\n  man = get_manager_from_domain(dom, s);\n  size = s;\n  ap_lincons0_array_t arr = ap_lincons0_array_make(a.size());\n  for (size_t i = 0; i < a.size(); i++) {\n    ap_linexpr0_t* expr = ap_linexpr0_alloc(AP_LINEXPR_DENSE, a[i].size());\n    for (int j = 0; j < a[i].size(); j++) {\n      ap_linexpr0_set_coeff_scalar_double(expr, j, -a[i](j));\n    }\n    ap_linexpr0_set_cst_scalar_double(expr, b[i]);\n    ap_lincons0_t cons = ap_lincons0_make(AP_CONS_SUPEQ, expr, NULL);\n    arr.p[i] = cons;\n  }\n  value = ap_abstract0_of_lincons_array(man, 0, a[0].size(), &arr);\n  ap_lincons0_array_clear(&arr);\n}\n\nPowerset::Powerset(AbstractDomain dom, size_t s, const LinCons& lc) {\n  man = get_manager_from_domain(dom, s);\n  ap_lincons0_array_t arr = ap_lincons0_array_make(lc.biases.size());\n  for (int i = 0; i < lc.biases.size(); i++) {\n    ap_linexpr0_t* expr = ap_linexpr0_alloc(AP_LINEXPR_DENSE,\n        lc.weights.row(i).size());\n    for (int j = 0; j < lc.weights.row(i).size(); j++) {\n      ap_linexpr0_set_coeff_scalar_double(expr, j, -lc.weights(i, j));\n    }\n    ap_linexpr0_set_cst_scalar_double(expr, lc.biases(i));\n    ap_lincons0_t cons = ap_lincons0_make(AP_CONS_SUPEQ, expr, NULL);\n    arr.p[i] = cons;\n  }\n  value = ap_abstract0_of_lincons_array(man, 0, lc.weights.row(0).size(), &arr);\n  ap_lincons0_array_clear(&arr);\n}\n\nPowerset::Powerset(AbstractDomain dom, size_t s,\n    const Eigen::VectorXd& lowers, const Eigen::VectorXd& uppers) {\n  domain = dom;\n  //ap_manager_t* base_manager;\n  //if (dom == AbstractDomain::ZONOTOPE) {\n  //  base_manager = mans.get_t1p_manager();\n  //} else {\n  //  base_manager = mans.get_box_manager();\n  //}\n  //man = mans.get_disj_manager(base_manager);\n  man = get_manager_from_domain(dom, s);\n  ap_interval_t** itv =\n    (ap_interval_t**) malloc(lowers.size() * sizeof(ap_interval_t*));\n  for (int i = 0; i < lowers.size(); i++) {\n    itv[i] = ap_interval_alloc();\n    ap_interval_set_double(itv[i], lowers(i), uppers(i));\n  }\n  value = ap_abstract0_of_box(man, 0, lowers.size(), itv);\n  ap_interval_array_free(itv, lowers.size());\n}\n\nPowerset& Powerset::operator=(const Powerset& other) {\n  size = other.size;\n  man = other.man;\n  value = ap_abstract0_copy(man, other.value);\n  return *this;\n}\n\nstd::unique_ptr<AbstractVal> Powerset::join(const AbstractVal& other) const {\n  std::unique_ptr<AbstractVal> res = this->AbstractVal::join(other);\n  ap_manager_t* m = res->get_manager();\n  ap_abstract0_t* a = res->get_value();\n  a = merge_disjuncts(m, a, size);\n  ap_abstract0_t* ra = (ap_abstract0_t*) malloc(sizeof(ap_abstract0_t));\n  ra->value = a;\n  ra->man = m;\n  return this->make_new(ra);\n}\n\nstd::unique_ptr<AbstractVal> Powerset::meet(const AbstractVal& other) const {\n  std::unique_ptr<AbstractVal> res = this->AbstractVal::meet(other);\n  ap_manager_t* m = res->get_manager();\n  ap_abstract0_t* a = res->get_value();\n  a = merge_disjuncts(m, a, size);\n  ap_abstract0_t* ra = (ap_abstract0_t*) malloc(sizeof(ap_abstract0_t));\n  ra->value = a;\n  ra->man = m;\n  return this->make_new(ra);\n}\n\nstd::unique_ptr<AbstractVal> Powerset::arith_computation(\n    const std::vector<ArithExpr>& exprs) const {\n  std::unique_ptr<AbstractVal> res =\n    this->AbstractVal::arith_computation(exprs);\n  ap_manager_t* m = res->get_manager();\n  ap_abstract0_t* a = res->get_value();\n  a = merge_disjuncts(m, a, size);\n  ap_abstract0_t* ra = (ap_abstract0_t*) malloc(sizeof(ap_abstract0_t));\n  ra->value = a;\n  ra->man = m;\n  return this->make_new(ra);\n}\n\nEigen::VectorXd Powerset::get_contained_point() const {\n  ap_disjunction_t* ad = (ap_disjunction_t*) value->value;\n  size_t s = ad->size;\n  // Get the manager for the underlying abstract domain\n  ap_disjunction_internal_t* in = (ap_disjunction_internal_t*) man->internal;\n  ap_manager_t* under = in->manager;\n  if (s == 0) {\n    return Eigen::VectorXd(0);\n  }\n  ap_abstract0_t* disjunct = (ap_abstract0_t*) ad->p[0];\n  return compute_center(under, disjunct);\n}\n\nstd::unique_ptr<AbstractVal> Powerset::clone() const {\n  return std::make_unique<Powerset>(man, ap_abstract0_copy(man, value), size);\n}\n\nstd::unique_ptr<AbstractVal> Powerset::bottom() const {\n  return std::make_unique<Powerset>(man, ap_abstract0_bottom(man,\n        0, this->dims()), this->size);\n}\n\nstd::unique_ptr<AbstractVal> Powerset::make_new(ap_abstract0_t* a) const {\n  return std::make_unique<Powerset>(man, a, size);\n}\n\n", "meta": {"hexsha": "e1b9ef0c28abb47704eb0a0c70f9ecd3c025f41d", "size": 31373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abstract.cpp", "max_stars_repo_name": "gavlegoat/safe-learning", "max_stars_repo_head_hexsha": "614ad97834f1a96e6c9d7c8e6677277d9af4d816", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T14:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T16:33:03.000Z", "max_issues_repo_path": "abstract.cpp", "max_issues_repo_name": "gavlegoat/safe-learning", "max_issues_repo_head_hexsha": "614ad97834f1a96e6c9d7c8e6677277d9af4d816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-11-13T19:09:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:23:23.000Z", "max_forks_repo_path": "abstract.cpp", "max_forks_repo_name": "gavlegoat/safe-learning", "max_forks_repo_head_hexsha": "614ad97834f1a96e6c9d7c8e6677277d9af4d816", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:52:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T01:36:17.000Z", "avg_line_length": 33.0242105263, "max_line_length": 80, "alphanum_fraction": 0.6687916361, "num_tokens": 9342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18573737651311362}}
{"text": "/**\n  \\class    TSGForOIDNN\n  \\brief    Create L3MuonTrajectorySeeds from L2 Muons in an outside-in manner\n  \\author   Dmitry Kondratyev, Arnab Purohit, Jan-Frederik Schulte (Purdue University, West Lafayette, USA)\n */\n\n#include \"DataFormats/TrackReco/interface/Track.h\"\n#include \"FWCore/Framework/interface/global/EDProducer.h\"\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/Framework/interface/EventSetup.h\"\n#include \"FWCore/Framework/interface/ESHandle.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n#include \"FWCore/MessageLogger/interface/MessageLogger.h\"\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n#include \"Geometry/CommonDetUnit/interface/GlobalTrackingGeometry.h\"\n#include \"Geometry/Records/interface/GlobalTrackingGeometryRecord.h\"\n#include \"MagneticField/Engine/interface/MagneticField.h\"\n#include \"MagneticField/Records/interface/IdealMagneticFieldRecord.h\"\n#include \"RecoTracker/MeasurementDet/interface/MeasurementTrackerEvent.h\"\n#include \"TrackingTools/GeomPropagators/interface/Propagator.h\"\n#include \"TrackingTools/KalmanUpdators/interface/Chi2MeasurementEstimator.h\"\n#include \"TrackingTools/KalmanUpdators/interface/KFUpdator.h\"\n#include \"TrackingTools/MeasurementDet/interface/MeasurementDet.h\"\n#include \"TrackingTools/PatternTools/interface/TrajMeasLessEstim.h\"\n#include \"TrackingTools/Records/interface/TrackingComponentsRecord.h\"\n#include \"TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h\"\n#include \"TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h\"\n#include \"TrackingTools/GeomPropagators/interface/StateOnTrackerBound.h\"\n#include \"PhysicsTools/TensorFlow/interface/TensorFlow.h\"\n#include \"TrackingTools/DetLayers/interface/NavigationSchool.h\"\n#include \"RecoTracker/Record/interface/NavigationSchoolRecord.h\"\n#include \"DataFormats/Math/interface/deltaR.h\"\n#include \"Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h\"\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <memory>\nnamespace pt = boost::property_tree;\n\nclass TSGForOIDNN : public edm::global::EDProducer<> {\npublic:\n  explicit TSGForOIDNN(const edm::ParameterSet& iConfig);\n  ~TSGForOIDNN() override;\n  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);\n  void produce(edm::StreamID sid, edm::Event& iEvent, const edm::EventSetup& iSetup) const override;\n\nprivate:\n  /// Labels for input collections\n  const edm::EDGetTokenT<reco::TrackCollection> src_;\n  /// Tokens for ESHandle\n  const edm::ESGetToken<Chi2MeasurementEstimatorBase, TrackingComponentsRecord> t_estimatorH_;\n  const edm::ESGetToken<MagneticField, IdealMagneticFieldRecord> t_magfieldH_;\n  const edm::ESGetToken<Propagator, TrackingComponentsRecord> t_propagatorAlongH_;\n  const edm::ESGetToken<Propagator, TrackingComponentsRecord> t_propagatorOppositeH_;\n  const edm::ESGetToken<TrackerGeometry, TrackerDigiGeometryRecord> t_tmpTkGeometryH_;\n  const edm::ESGetToken<GlobalTrackingGeometry, GlobalTrackingGeometryRecord> t_geometryH_;\n  const edm::ESGetToken<NavigationSchool, NavigationSchoolRecord> t_navSchool_;\n  const edm::ESGetToken<Propagator, TrackingComponentsRecord> t_SHPOpposite_;\n  const std::unique_ptr<TrajectoryStateUpdator> updator_;\n  const edm::EDGetTokenT<MeasurementTrackerEvent> measurementTrackerTag_;\n  const std::string theCategory_;\n\n  /// Maximum number of seeds for each L2\n  const unsigned int maxSeeds_;\n  /// Maximum number of hitbased seeds for each L2\n  const unsigned int maxHitSeeds_;\n  /// Maximum number of hitless seeds for each L2\n  const unsigned int maxHitlessSeeds_;\n  /// How many layers to try\n  const unsigned int numOfLayersToTry_;\n  /// How many hits to try per layer\n  const unsigned int numOfHitsToTry_;\n  /// Rescale L2 parameter uncertainties (fixed error vs pT, eta)\n  const double fixedErrorRescalingForHitless_;\n  /// Estimator used to find dets and TrajectoryMeasurements\n  const std::string estimatorName_;\n  /// Minimum eta value to activate searching in the TEC\n  const double minEtaForTEC_;\n  /// Maximum eta value to activate searching in the TOB\n  const double maxEtaForTOB_;\n\n  /// IP refers to TSOS at interaction point,\n  /// MuS refers to TSOS at muon system\n  const unsigned int maxHitlessSeedsIP_;\n  const unsigned int maxHitlessSeedsMuS_;\n  const unsigned int maxHitDoubletSeeds_;\n\n  /// Get number of seeds to use from DNN output instead of \"max..Seeds\" parameters\n  const bool getStrategyFromDNN_;\n  /// Whether to use DNN regressor (if false, will use classifier)\n  const bool useRegressor_;\n\n  /// Settings for classifier\n  const double etaSplitForDnn_;\n  std::string dnnModelPath_barrel_;\n  std::string dnnModelPath_endcap_;\n  std::unique_ptr<tensorflow::GraphDef> graphDef_barrel_;\n  tensorflow::Session* tf_session_barrel_;\n  std::unique_ptr<tensorflow::GraphDef> graphDef_endcap_;\n  tensorflow::Session* tf_session_endcap_;\n\n  /// Settings for regressor\n  std::string dnnModelPath_HB_;\n  std::string dnnModelPath_HLIP_;\n  std::string dnnModelPath_HLMuS_;\n  std::unique_ptr<tensorflow::GraphDef> graphDef_HB_;\n  tensorflow::Session* tf_session_HB_;\n  std::unique_ptr<tensorflow::GraphDef> graphDef_HLIP_;\n  tensorflow::Session* tf_session_HLIP_;\n  std::unique_ptr<tensorflow::GraphDef> graphDef_HLMuS_;\n  tensorflow::Session* tf_session_HLMuS_;\n\n  /// DNN metadata\n  const std::string dnnMetadataPath_;\n  pt::ptree metadata_;\n\n  /// Create seeds without hits on a given layer (TOB or TEC)\n  void makeSeedsWithoutHits(const GeometricSearchDet& layer,\n                            const TrajectoryStateOnSurface& tsos,\n                            const Propagator& propagatorAlong,\n                            const Chi2MeasurementEstimatorBase& estimator,\n                            double errorSF,\n                            unsigned int& hitlessSeedsMade,\n                            unsigned int& numSeedsMade,\n                            std::vector<TrajectorySeed>& out) const;\n\n  /// Find hits on a given layer (TOB or TEC) and create seeds from updated TSOS with hit\n  void makeSeedsFromHits(const GeometricSearchDet& layer,\n                         const TrajectoryStateOnSurface& tsos,\n                         const Propagator& propagatorAlong,\n                         const Chi2MeasurementEstimatorBase& estimator,\n                         const MeasurementTrackerEvent& measurementTracker,\n                         unsigned int& hitSeedsMade,\n                         unsigned int& numSeedsMade,\n                         const unsigned int& maxHitSeeds,\n                         unsigned int& layerCount,\n                         std::vector<TrajectorySeed>& out) const;\n\n  /// Similar to makeSeedsFromHits, but seed is created only if there are compatible hits on two adjacent layers\n  void makeSeedsFromHitDoublets(const GeometricSearchDet& layer,\n                                const TrajectoryStateOnSurface& tsos,\n                                const Propagator& propagatorAlong,\n                                const Chi2MeasurementEstimatorBase& estimator,\n                                const MeasurementTrackerEvent& measurementTracker,\n                                const NavigationSchool& navSchool,\n                                unsigned int& hitDoubletSeedsMade,\n                                unsigned int& numSeedsMade,\n                                const unsigned int& maxHitDoubletSeeds,\n                                unsigned int& layerCount,\n                                std::vector<TrajectorySeed>& out) const;\n\n  /// Update dictionary of inputs for DNN\n  void updateFeatureMap(std::unordered_map<std::string, float>& the_map,\n                        const reco::Track& l2,\n                        const TrajectoryStateOnSurface& tsos_IP,\n                        const TrajectoryStateOnSurface& tsos_MuS) const;\n\n  /// Container for DNN outupts\n  struct StrategyParameters {\n    int nHBd, nHLIP, nHLMuS, sf;\n  };\n\n  /// Evaluate DNN classifier\n  void evaluateClassifier(const std::unordered_map<std::string, float>& feature_map,\n                          tensorflow::Session* session,\n                          const pt::ptree& metadata,\n                          StrategyParameters& out,\n                          bool& dnnSuccess) const;\n\n  /// Evaluate DNN regressor\n  void evaluateRegressor(const std::unordered_map<std::string, float>& feature_map,\n                         tensorflow::Session* session_HB,\n                         const pt::ptree& metadata_HB,\n                         tensorflow::Session* session_HLIP,\n                         const pt::ptree& metadata_HLIP,\n                         tensorflow::Session* session_HLMuS,\n                         const pt::ptree& metadata_HLMuS,\n                         StrategyParameters& out,\n                         bool& dnnSuccess) const;\n};\n\nTSGForOIDNN::TSGForOIDNN(const edm::ParameterSet& iConfig)\n    : src_(consumes(iConfig.getParameter<edm::InputTag>(\"src\"))),\n      t_estimatorH_(esConsumes(edm::ESInputTag(\"\", iConfig.getParameter<std::string>(\"estimator\")))),\n      t_magfieldH_(esConsumes()),\n      t_propagatorAlongH_(esConsumes(edm::ESInputTag(\"\", iConfig.getParameter<std::string>(\"propagatorName\")))),\n      t_propagatorOppositeH_(esConsumes(edm::ESInputTag(\"\", iConfig.getParameter<std::string>(\"propagatorName\")))),\n      t_tmpTkGeometryH_(esConsumes()),\n      t_geometryH_(esConsumes()),\n      t_navSchool_(esConsumes(edm::ESInputTag(\"\", \"SimpleNavigationSchool\"))),\n      t_SHPOpposite_(esConsumes(edm::ESInputTag(\"\", \"hltESPSteppingHelixPropagatorOpposite\"))),\n      updator_(new KFUpdator()),\n      measurementTrackerTag_(consumes(iConfig.getParameter<edm::InputTag>(\"MeasurementTrackerEvent\"))),\n      theCategory_(std::string(\"Muon|RecoMuon|TSGForOIDNN\")),\n      maxSeeds_(iConfig.getParameter<uint32_t>(\"maxSeeds\")),\n      maxHitSeeds_(iConfig.getParameter<uint32_t>(\"maxHitSeeds\")),\n      maxHitlessSeeds_(iConfig.getParameter<uint32_t>(\"maxHitlessSeeds\")),\n      numOfLayersToTry_(iConfig.getParameter<int32_t>(\"layersToTry\")),\n      numOfHitsToTry_(iConfig.getParameter<int32_t>(\"hitsToTry\")),\n      fixedErrorRescalingForHitless_(iConfig.getParameter<double>(\"fixedErrorRescaleFactorForHitless\")),\n      minEtaForTEC_(iConfig.getParameter<double>(\"minEtaForTEC\")),\n      maxEtaForTOB_(iConfig.getParameter<double>(\"maxEtaForTOB\")),\n      maxHitlessSeedsIP_(iConfig.getParameter<uint32_t>(\"maxHitlessSeedsIP\")),\n      maxHitlessSeedsMuS_(iConfig.getParameter<uint32_t>(\"maxHitlessSeedsMuS\")),\n      maxHitDoubletSeeds_(iConfig.getParameter<uint32_t>(\"maxHitDoubletSeeds\")),\n      getStrategyFromDNN_(iConfig.getParameter<bool>(\"getStrategyFromDNN\")),\n      useRegressor_(iConfig.getParameter<bool>(\"useRegressor\")),\n      etaSplitForDnn_(iConfig.getParameter<double>(\"etaSplitForDnn\")),\n      dnnMetadataPath_(iConfig.getParameter<std::string>(\"dnnMetadataPath\")) {\n  if (getStrategyFromDNN_) {\n    edm::FileInPath dnnMetadataPath(dnnMetadataPath_);\n    pt::read_json(dnnMetadataPath.fullPath(), metadata_);\n    tensorflow::setLogging(\"3\");\n\n    if (useRegressor_) {\n      // use regressor\n      dnnModelPath_HB_ = metadata_.get<std::string>(\"HB.dnnmodel_path\");\n      edm::FileInPath dnnPath_HB(dnnModelPath_HB_);\n      graphDef_HB_ = std::unique_ptr<tensorflow::GraphDef>(tensorflow::loadGraphDef(dnnPath_HB.fullPath()));\n      tf_session_HB_ = tensorflow::createSession(graphDef_HB_.get());\n\n      dnnModelPath_HLIP_ = metadata_.get<std::string>(\"HLIP.dnnmodel_path\");\n      edm::FileInPath dnnPath_HLIP(dnnModelPath_HLIP_);\n      graphDef_HLIP_ = std::unique_ptr<tensorflow::GraphDef>(tensorflow::loadGraphDef(dnnPath_HLIP.fullPath()));\n      tf_session_HLIP_ = tensorflow::createSession(graphDef_HLIP_.get());\n\n      dnnModelPath_HLMuS_ = metadata_.get<std::string>(\"HLMuS.dnnmodel_path\");\n      edm::FileInPath dnnPath_HLMuS(dnnModelPath_HLMuS_);\n      graphDef_HLMuS_ = std::unique_ptr<tensorflow::GraphDef>(tensorflow::loadGraphDef(dnnPath_HLMuS.fullPath()));\n      tf_session_HLMuS_ = tensorflow::createSession(graphDef_HLMuS_.get());\n    } else {\n      // use classifier (default)\n      dnnModelPath_barrel_ = metadata_.get<std::string>(\"barrel.dnnmodel_path\");\n      edm::FileInPath dnnPath_barrel(dnnModelPath_barrel_);\n      graphDef_barrel_ = std::unique_ptr<tensorflow::GraphDef>(tensorflow::loadGraphDef(dnnPath_barrel.fullPath()));\n      tf_session_barrel_ = tensorflow::createSession(graphDef_barrel_.get());\n\n      dnnModelPath_endcap_ = metadata_.get<std::string>(\"endcap.dnnmodel_path\");\n      edm::FileInPath dnnPath_endcap(dnnModelPath_endcap_);\n      graphDef_endcap_ = std::unique_ptr<tensorflow::GraphDef>(tensorflow::loadGraphDef(dnnPath_endcap.fullPath()));\n      tf_session_endcap_ = tensorflow::createSession(graphDef_endcap_.get());\n    }\n  }\n  produces<std::vector<TrajectorySeed> >();\n}\n\nTSGForOIDNN::~TSGForOIDNN() {\n  if (getStrategyFromDNN_) {\n    if (useRegressor_) {\n      tensorflow::closeSession(tf_session_HB_);\n      tensorflow::closeSession(tf_session_HLIP_);\n      tensorflow::closeSession(tf_session_HLMuS_);\n    } else {\n      tensorflow::closeSession(tf_session_barrel_);\n      tensorflow::closeSession(tf_session_endcap_);\n    }\n  }\n}\n\n//\n// Produce seeds\n//\nvoid TSGForOIDNN::produce(edm::StreamID sid, edm::Event& iEvent, edm::EventSetup const& iEventSetup) const {\n  // Initialize variables\n  unsigned int numSeedsMade = 0;\n  unsigned int layerCount = 0;\n  unsigned int hitlessSeedsMadeIP = 0;\n  unsigned int hitlessSeedsMadeMuS = 0;\n  unsigned int hitSeedsMade = 0;\n  unsigned int hitDoubletSeedsMade = 0;\n\n  // Container for DNN inputs\n  std::unordered_map<std::string, float> feature_map;\n\n  // Container for DNN outputs\n  StrategyParameters strPars;\n\n  // Surface used to make a TSOS at the PCA to the beamline\n  Plane::PlanePointer dummyPlane = Plane::build(Plane::PositionType(), Plane::RotationType());\n\n  // Get setup objects\n  const MagneticField& magfield = iEventSetup.getData(t_magfieldH_);\n  const Chi2MeasurementEstimatorBase& estimator = iEventSetup.getData(t_estimatorH_);\n  const Propagator& tmpPropagatorAlong = iEventSetup.getData(t_propagatorAlongH_);\n  const Propagator& tmpPropagatorOpposite = iEventSetup.getData(t_propagatorOppositeH_);\n  const TrackerGeometry& tmpTkGeometry = iEventSetup.getData(t_tmpTkGeometryH_);\n  const GlobalTrackingGeometry& geometry = iEventSetup.getData(t_geometryH_);\n  const NavigationSchool& navSchool = iEventSetup.getData(t_navSchool_);\n  auto const& measurementTracker = iEvent.get(measurementTrackerTag_);\n\n  // Read L2 track collection\n  auto const& l2TrackCol = iEvent.get(src_);\n\n  // The product\n  std::unique_ptr<std::vector<TrajectorySeed> > result(new std::vector<TrajectorySeed>());\n\n  // Get vector of Detector layers\n  auto const* gsTracker = measurementTracker.geometricSearchTracker();\n  std::vector<BarrelDetLayer const*> const& tob = gsTracker->tobLayers();\n  std::vector<ForwardDetLayer const*> const& tecPositive =\n      tmpTkGeometry.isThere(GeomDetEnumerators::P2OTEC) ? gsTracker->posTidLayers() : gsTracker->posTecLayers();\n  std::vector<ForwardDetLayer const*> const& tecNegative =\n      tmpTkGeometry.isThere(GeomDetEnumerators::P2OTEC) ? gsTracker->negTidLayers() : gsTracker->negTecLayers();\n\n  // Get suitable propagators\n  std::unique_ptr<Propagator> propagatorAlong = SetPropagationDirection(tmpPropagatorAlong, alongMomentum);\n  std::unique_ptr<Propagator> propagatorOpposite = SetPropagationDirection(tmpPropagatorOpposite, oppositeToMomentum);\n\n  // Stepping Helix Propagator for propogation from muon system to tracker\n  edm::ESHandle<Propagator> shpOpposite = iEventSetup.getHandle(t_SHPOpposite_);\n\n  // Loop over the L2's and make seeds for all of them\n  LogTrace(theCategory_) << \"TSGForOIDNN::produce: Number of L2's: \" << l2TrackCol.size();\n\n  for (auto const& l2 : l2TrackCol) {\n    // Container of Seeds\n    std::vector<TrajectorySeed> out;\n    LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::produce: L2 muon pT, eta, phi --> \" << l2.pt() << \" , \" << l2.eta()\n                            << \" , \" << l2.phi();\n\n    FreeTrajectoryState fts = trajectoryStateTransform::initialFreeState(l2, &magfield);\n\n    dummyPlane->move(fts.position() - dummyPlane->position());\n    TrajectoryStateOnSurface tsosAtIP = TrajectoryStateOnSurface(fts, *dummyPlane);\n    LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::produce: Created TSOSatIP: \" << tsosAtIP;\n\n    // Get the TSOS on the innermost layer of the L2\n    TrajectoryStateOnSurface tsosAtMuonSystem = trajectoryStateTransform::innerStateOnSurface(l2, geometry, &magfield);\n    LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::produce: Created TSOSatMuonSystem: \" << tsosAtMuonSystem;\n\n    LogTrace(\"TSGForOIDNN\")\n        << \"TSGForOIDNN::produce: Check the error of the L2 parameter and use hit seeds if big errors\";\n\n    StateOnTrackerBound fromInside(propagatorAlong.get());\n    TrajectoryStateOnSurface outerTkStateInside = fromInside(fts);\n\n    StateOnTrackerBound fromOutside(&*shpOpposite);\n    TrajectoryStateOnSurface outerTkStateOutside = fromOutside(tsosAtMuonSystem);\n\n    // Check if the two positions (using updated and not-updated TSOS) agree withing certain extent.\n    // If both TSOSs agree, use only the one at vertex, as it uses more information. If they do not agree, search for seeds based on both.\n    double l2muonEta = l2.eta();\n    double absL2muonEta = std::abs(l2muonEta);\n\n    // make non-const copies of parameters, so they can be overriden for individual L2 muons\n    unsigned int maxHitSeeds = maxHitSeeds_;\n    unsigned int maxHitDoubletSeeds = maxHitDoubletSeeds_;\n    unsigned int maxHitlessSeedsIP = maxHitlessSeedsIP_;\n    unsigned int maxHitlessSeedsMuS = maxHitlessSeedsMuS_;\n\n    float errorSFHitless = fixedErrorRescalingForHitless_;\n\n    // update strategy parameters by evaluating DNN\n    if (getStrategyFromDNN_) {\n      bool dnnSuccess = false;\n\n      // Update feature map with parameters of the current muon\n      updateFeatureMap(feature_map, l2, tsosAtIP, outerTkStateOutside);\n\n      if (useRegressor_) {\n        // Use regressor\n        evaluateRegressor(feature_map,\n                          tf_session_HB_,\n                          metadata_.get_child(\"HB\"),\n                          tf_session_HLIP_,\n                          metadata_.get_child(\"HLIP\"),\n                          tf_session_HLMuS_,\n                          metadata_.get_child(\"HLMuS\"),\n                          strPars,\n                          dnnSuccess);\n      } else {\n        // Use classifier\n        bool isBarrel = absL2muonEta < etaSplitForDnn_;\n        const pt::ptree& tr = isBarrel ? metadata_.get_child(\"barrel\") : metadata_.get_child(\"endcap\");\n        tensorflow::Session* tf = isBarrel ? tf_session_barrel_ : tf_session_endcap_;\n        evaluateClassifier(feature_map, tf, tr, strPars, dnnSuccess);\n      }\n      if (!dnnSuccess)\n        break;\n\n      maxHitSeeds = 0;\n      maxHitDoubletSeeds = strPars.nHBd;\n      maxHitlessSeedsIP = strPars.nHLIP;\n      maxHitlessSeedsMuS = strPars.nHLMuS;\n      errorSFHitless = strPars.sf;\n    }\n\n    numSeedsMade = 0;\n    hitlessSeedsMadeIP = 0;\n    hitlessSeedsMadeMuS = 0;\n    hitSeedsMade = 0;\n    hitDoubletSeedsMade = 0;\n\n    auto createSeeds = [&](auto const& layers) {\n      for (auto const& layer : layers) {\n        if (hitlessSeedsMadeIP < maxHitlessSeedsIP && numSeedsMade < maxSeeds_)\n          makeSeedsWithoutHits(*layer,\n                               tsosAtIP,\n                               *(propagatorAlong.get()),\n                               estimator,\n                               errorSFHitless,\n                               hitlessSeedsMadeIP,\n                               numSeedsMade,\n                               out);\n\n        if (outerTkStateInside.isValid() && outerTkStateOutside.isValid() && hitlessSeedsMadeMuS < maxHitlessSeedsMuS &&\n            numSeedsMade < maxSeeds_)\n          makeSeedsWithoutHits(*layer,\n                               outerTkStateOutside,\n                               *(propagatorOpposite.get()),\n                               estimator,\n                               errorSFHitless,\n                               hitlessSeedsMadeMuS,\n                               numSeedsMade,\n                               out);\n\n        if (hitSeedsMade < maxHitSeeds && numSeedsMade < maxSeeds_)\n          makeSeedsFromHits(*layer,\n                            tsosAtIP,\n                            *(propagatorAlong.get()),\n                            estimator,\n                            measurementTracker,\n                            hitSeedsMade,\n                            numSeedsMade,\n                            maxHitSeeds,\n                            layerCount,\n                            out);\n\n        if (hitDoubletSeedsMade < maxHitDoubletSeeds && numSeedsMade < maxSeeds_)\n          makeSeedsFromHitDoublets(*layer,\n                                   tsosAtIP,\n                                   *(propagatorAlong.get()),\n                                   estimator,\n                                   measurementTracker,\n                                   navSchool,\n                                   hitDoubletSeedsMade,\n                                   numSeedsMade,\n                                   maxHitDoubletSeeds,\n                                   layerCount,\n                                   out);\n      };\n    };\n\n    // BARREL\n    if (absL2muonEta < maxEtaForTOB_) {\n      layerCount = 0;\n      createSeeds(tob);\n      LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN:::produce: NumSeedsMade = \" << numSeedsMade\n                              << \" , layerCount = \" << layerCount;\n    }\n\n    // Reset number of seeds if in overlap region\n    if (absL2muonEta > minEtaForTEC_ && absL2muonEta < maxEtaForTOB_) {\n      numSeedsMade = 0;\n      hitlessSeedsMadeIP = 0;\n      hitlessSeedsMadeMuS = 0;\n      hitSeedsMade = 0;\n      hitDoubletSeedsMade = 0;\n    }\n\n    // ENDCAP+\n    if (l2muonEta > minEtaForTEC_) {\n      layerCount = 0;\n      createSeeds(tecPositive);\n      LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN:::produce: NumSeedsMade = \" << numSeedsMade\n                              << \" , layerCount = \" << layerCount;\n    }\n\n    // ENDCAP-\n    if (l2muonEta < -minEtaForTEC_) {\n      layerCount = 0;\n      createSeeds(tecNegative);\n      LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN:::produce: NumSeedsMade = \" << numSeedsMade\n                              << \" , layerCount = \" << layerCount;\n    }\n\n    for (std::vector<TrajectorySeed>::iterator it = out.begin(); it != out.end(); ++it) {\n      result->push_back(*it);\n    }\n\n  }  // L2Collection\n\n  edm::LogInfo(theCategory_) << \"TSGForOIDNN::produce: number of seeds made: \" << result->size();\n\n  iEvent.put(std::move(result));\n}\n\n//\n// Create seeds without hits on a given layer (TOB or TEC)\n//\nvoid TSGForOIDNN::makeSeedsWithoutHits(const GeometricSearchDet& layer,\n                                       const TrajectoryStateOnSurface& tsos,\n                                       const Propagator& propagatorAlong,\n                                       const Chi2MeasurementEstimatorBase& estimator,\n                                       double errorSF,\n                                       unsigned int& hitlessSeedsMade,\n                                       unsigned int& numSeedsMade,\n                                       std::vector<TrajectorySeed>& out) const {\n  // create hitless seeds\n  LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsWithoutHits: Start hitless\";\n  std::vector<GeometricSearchDet::DetWithState> dets;\n  layer.compatibleDetsV(tsos, propagatorAlong, estimator, dets);\n  if (!dets.empty()) {\n    auto const& detOnLayer = dets.front().first;\n    auto& tsosOnLayer = dets.front().second;\n    LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsWithoutHits: tsosOnLayer \" << tsosOnLayer;\n    if (!tsosOnLayer.isValid()) {\n      edm::LogInfo(theCategory_) << \"ERROR!: Hitless TSOS is not valid!\";\n    } else {\n      tsosOnLayer.rescaleError(errorSF);\n      PTrajectoryStateOnDet const& ptsod =\n          trajectoryStateTransform::persistentState(tsosOnLayer, detOnLayer->geographicalId().rawId());\n      TrajectorySeed::RecHitContainer rHC;\n      out.push_back(TrajectorySeed(ptsod, rHC, oppositeToMomentum));\n      LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsWithoutHits: TSOS (Hitless) done \";\n      hitlessSeedsMade++;\n      numSeedsMade++;\n    }\n  }\n}\n\n//\n// Find hits on a given layer (TOB or TEC) and create seeds from updated TSOS with hit\n//\nvoid TSGForOIDNN::makeSeedsFromHits(const GeometricSearchDet& layer,\n                                    const TrajectoryStateOnSurface& tsos,\n                                    const Propagator& propagatorAlong,\n                                    const Chi2MeasurementEstimatorBase& estimator,\n                                    const MeasurementTrackerEvent& measurementTracker,\n                                    unsigned int& hitSeedsMade,\n                                    unsigned int& numSeedsMade,\n                                    const unsigned int& maxHitSeeds,\n                                    unsigned int& layerCount,\n                                    std::vector<TrajectorySeed>& out) const {\n  if (layerCount > numOfLayersToTry_)\n    return;\n\n  const TrajectoryStateOnSurface& onLayer(tsos);\n\n  std::vector<GeometricSearchDet::DetWithState> dets;\n  layer.compatibleDetsV(onLayer, propagatorAlong, estimator, dets);\n\n  // Find Measurements on each DetWithState\n  LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsFromHits: Find measurements on each detWithState  \" << dets.size();\n  std::vector<TrajectoryMeasurement> meas;\n  for (auto const& detI : dets) {\n    MeasurementDetWithData det = measurementTracker.idToDet(detI.first->geographicalId());\n    if (det.isNull())\n      continue;\n    if (!detI.second.isValid())\n      continue;  // Skip if TSOS is not valid\n\n    std::vector<TrajectoryMeasurement> mymeas =\n        det.fastMeasurements(detI.second, onLayer, propagatorAlong, estimator);  // Second TSOS is not used\n    for (auto const& measurement : mymeas) {\n      if (measurement.recHit()->isValid())\n        meas.push_back(measurement);  // Only save those which are valid\n    }\n  }\n\n  // Update TSOS using TMs after sorting, then create Trajectory Seed and put into vector\n  LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsFromHits: Update TSOS using TMs after sorting, then create \"\n                             \"Trajectory Seed, number of TM = \"\n                          << meas.size();\n  std::sort(meas.begin(), meas.end(), TrajMeasLessEstim());\n\n  unsigned int found = 0;\n  for (auto const& measurement : meas) {\n    if (hitSeedsMade >= maxHitSeeds)\n      return;\n    TrajectoryStateOnSurface updatedTSOS = updator_->update(measurement.forwardPredictedState(), *measurement.recHit());\n    LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsFromHits: TSOS for TM \" << found;\n    if (not updatedTSOS.isValid())\n      continue;\n\n    edm::OwnVector<TrackingRecHit> seedHits;\n    seedHits.push_back(*measurement.recHit()->hit());\n    PTrajectoryStateOnDet const& pstate =\n        trajectoryStateTransform::persistentState(updatedTSOS, measurement.recHit()->geographicalId().rawId());\n    LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsFromHits: Number of seedHits: \" << seedHits.size();\n    TrajectorySeed seed(pstate, std::move(seedHits), oppositeToMomentum);\n    out.push_back(seed);\n    found++;\n    numSeedsMade++;\n    hitSeedsMade++;\n    if (found == numOfHitsToTry_)\n      break;\n  }\n\n  if (found)\n    layerCount++;\n}\n\n//\n// Find hits compatible with L2 trajectory on two adjacent layers; if found, create a seed using both hits\n//\nvoid TSGForOIDNN::makeSeedsFromHitDoublets(const GeometricSearchDet& layer,\n                                           const TrajectoryStateOnSurface& tsos,\n                                           const Propagator& propagatorAlong,\n                                           const Chi2MeasurementEstimatorBase& estimator,\n                                           const MeasurementTrackerEvent& measurementTracker,\n                                           const NavigationSchool& navSchool,\n                                           unsigned int& hitDoubletSeedsMade,\n                                           unsigned int& numSeedsMade,\n                                           const unsigned int& maxHitDoubletSeeds,\n                                           unsigned int& layerCount,\n                                           std::vector<TrajectorySeed>& out) const {\n  // This method is similar to makeSeedsFromHits, but the seed is created\n  // only when in addition to a hit on a given layer, there are more compatible hits\n  // on next layers (going from outside inwards), compatible with updated TSOS.\n  // If that's the case, multiple compatible hits are used to create a single seed.\n\n  // Configured to only check the immideately adjacent layer and add one more hit\n  int max_addtnl_layers = 1;  // max number of additional layers to scan\n  int max_meas = 1;           // number of measurements to consider on each additional layer\n\n  // // // First, regular procedure to find a compatible hit - like in makeSeedsFromHits // // //\n\n  const TrajectoryStateOnSurface& onLayer(tsos);\n\n  // Find dets compatible with original TSOS\n  std::vector<GeometricSearchDet::DetWithState> dets;\n  layer.compatibleDetsV(onLayer, propagatorAlong, estimator, dets);\n\n  LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsFromHitDoublets: Find measurements on each detWithState  \"\n                          << dets.size();\n  std::vector<TrajectoryMeasurement> meas;\n\n  // Loop over dets\n  for (auto const& detI : dets) {\n    MeasurementDetWithData det = measurementTracker.idToDet(detI.first->geographicalId());\n\n    if (det.isNull())\n      continue;  // skip if det does not exist\n    if (!detI.second.isValid())\n      continue;  // skip if TSOS is invalid\n\n    // Find measurements on this det\n    std::vector<TrajectoryMeasurement> mymeas = det.fastMeasurements(detI.second, onLayer, propagatorAlong, estimator);\n\n    // Save valid measurements\n    for (auto const& measurement : mymeas) {\n      if (measurement.recHit()->isValid())\n        meas.push_back(measurement);\n    }  // end loop over meas\n  }    // end loop over dets\n\n  LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsFromHitDoublets: Update TSOS using TMs after sorting, then create \"\n                             \"Trajectory Seed, number of TM = \"\n                          << meas.size();\n\n  // sort valid measurements found on the first layer\n  std::sort(meas.begin(), meas.end(), TrajMeasLessEstim());\n\n  unsigned int found = 0;\n  int hit_num = 0;\n\n  // Loop over all valid measurements compatible with original TSOS\n  //for (std::vector<TrajectoryMeasurement>::const_iterator mea = meas.begin(); mea != meas.end(); ++mea) {\n  for (auto const& measurement : meas) {\n    if (hitDoubletSeedsMade >= maxHitDoubletSeeds)\n      return;  // abort if enough seeds created\n\n    hit_num++;\n\n    // Update TSOS with measurement on first considered layer\n    TrajectoryStateOnSurface updatedTSOS = updator_->update(measurement.forwardPredictedState(), *measurement.recHit());\n\n    LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsFromHitDoublets: TSOS for TM \" << found;\n    if (not updatedTSOS.isValid())\n      continue;  // Skip if updated TSOS is invalid\n\n    edm::OwnVector<TrackingRecHit> seedHits;\n\n    // Save hit on first layer\n    seedHits.push_back(*measurement.recHit()->hit());\n    const DetLayer* detLayer = dynamic_cast<const DetLayer*>(&layer);\n\n    // // // Now for this measurement we will loop over additional layers and try to update the TSOS again // // //\n\n    // find layers compatible with updated TSOS\n    auto const& compLayers = navSchool.nextLayers(*detLayer, *updatedTSOS.freeState(), alongMomentum);\n\n    int addtnl_layers_scanned = 0;\n    int found_compatible_on_next_layer = 0;\n    int det_id = 0;\n\n    // Copy updated TSOS - we will update it again with a measurement from the next layer, if we find it\n    TrajectoryStateOnSurface updatedTSOS_next(updatedTSOS);\n\n    // loop over layers compatible with updated TSOS\n    for (auto compLayer : compLayers) {\n      int nmeas = 0;\n\n      if (addtnl_layers_scanned >= max_addtnl_layers)\n        break;  // break if we already looped over enough layers\n      if (found_compatible_on_next_layer > 0)\n        break;  // break if we already found additional hit\n\n      // find dets compatible with updated TSOS\n      std::vector<GeometricSearchDet::DetWithState> dets_next;\n      TrajectoryStateOnSurface onLayer_next(updatedTSOS);\n\n      compLayer->compatibleDetsV(onLayer_next, propagatorAlong, estimator, dets_next);\n\n      //if (!detWithState.size()) continue;\n      std::vector<TrajectoryMeasurement> meas_next;\n\n      // find measurements on dets_next and save the valid ones\n      for (auto const& detI_next : dets_next) {\n        MeasurementDetWithData det = measurementTracker.idToDet(detI_next.first->geographicalId());\n\n        if (det.isNull())\n          continue;  // skip if det does not exist\n        if (!detI_next.second.isValid())\n          continue;  // skip if TSOS is invalid\n\n        // Find measurements on this det\n        std::vector<TrajectoryMeasurement> mymeas_next =\n            det.fastMeasurements(detI_next.second, onLayer_next, propagatorAlong, estimator);\n\n        for (auto const& mea_next : mymeas_next) {\n          // save valid measurements\n          if (mea_next.recHit()->isValid())\n            meas_next.push_back(mea_next);\n\n        }  // end loop over mymeas_next\n      }    // end loop over dets_next\n\n      // sort valid measurements found on this layer\n      std::sort(meas_next.begin(), meas_next.end(), TrajMeasLessEstim());\n\n      // loop over valid measurements compatible with updated TSOS (TSOS updated with a hit on the first layer)\n      for (auto const& mea_next : meas_next) {\n        if (nmeas >= max_meas)\n          break;  // skip if we already found enough hits\n\n        // try to update TSOS again, with an additional hit\n        updatedTSOS_next = updator_->update(mea_next.forwardPredictedState(), *mea_next.recHit());\n\n        if (not updatedTSOS_next.isValid())\n          continue;  // skip if TSOS updated with additional hit is not valid\n\n        // If there was a compatible hit on this layer, we end up here.\n        // An additional compatible hit is saved.\n        seedHits.push_back(*mea_next.recHit()->hit());\n        det_id = mea_next.recHit()->geographicalId().rawId();\n        nmeas++;\n        found_compatible_on_next_layer++;\n\n      }  // end loop over meas_next\n\n      addtnl_layers_scanned++;\n\n    }  // end loop over compLayers (additional layers scanned after the original layer)\n\n    if (found_compatible_on_next_layer == 0)\n      continue;\n    // only consider the hit if there was a compatible hit on one of the additional scanned layers\n\n    // Create a seed from two saved hits\n    PTrajectoryStateOnDet const& pstate = trajectoryStateTransform::persistentState(updatedTSOS_next, det_id);\n    TrajectorySeed seed(pstate, std::move(seedHits), oppositeToMomentum);\n\n    LogTrace(\"TSGForOIDNN\") << \"TSGForOIDNN::makeSeedsFromHitDoublets: Number of seedHits: \" << seedHits.size();\n    out.push_back(seed);\n\n    found++;\n    numSeedsMade++;\n    hitDoubletSeedsMade++;\n\n    if (found == numOfHitsToTry_)\n      break;  // break if enough measurements scanned\n\n  }  // end loop over measurements compatible with original TSOS\n\n  if (found)\n    layerCount++;\n}\n\n//\n// Update the dictionary of variables to use as input features for DNN\n//\nvoid TSGForOIDNN::updateFeatureMap(std::unordered_map<std::string, float>& the_map,\n                                   const reco::Track& l2,\n                                   const TrajectoryStateOnSurface& tsos_IP,\n                                   const TrajectoryStateOnSurface& tsos_MuS) const {\n  the_map[\"pt\"] = l2.pt();\n  the_map[\"eta\"] = l2.eta();\n  the_map[\"phi\"] = l2.phi();\n  the_map[\"validHits\"] = l2.found();\n  if (tsos_IP.isValid()) {\n    the_map[\"tsos_IP_eta\"] = tsos_IP.globalPosition().eta();\n    the_map[\"tsos_IP_phi\"] = tsos_IP.globalPosition().phi();\n    the_map[\"tsos_IP_pt\"] = tsos_IP.globalMomentum().perp();\n    the_map[\"tsos_IP_pt_eta\"] = tsos_IP.globalMomentum().eta();\n    the_map[\"tsos_IP_pt_phi\"] = tsos_IP.globalMomentum().phi();\n    const AlgebraicSymMatrix55& matrix_IP = tsos_IP.curvilinearError().matrix();\n    the_map[\"err0_IP\"] = sqrt(matrix_IP[0][0]);\n    the_map[\"err1_IP\"] = sqrt(matrix_IP[1][1]);\n    the_map[\"err2_IP\"] = sqrt(matrix_IP[2][2]);\n    the_map[\"err3_IP\"] = sqrt(matrix_IP[3][3]);\n    the_map[\"err4_IP\"] = sqrt(matrix_IP[4][4]);\n    the_map[\"tsos_IP_valid\"] = 1.0;\n  } else {\n    the_map[\"tsos_IP_eta\"] = -999;\n    the_map[\"tsos_IP_phi\"] = -999;\n    the_map[\"tsos_IP_pt\"] = -999;\n    the_map[\"tsos_IP_pt_eta\"] = -999;\n    the_map[\"tsos_IP_pt_phi\"] = -999;\n    the_map[\"err0_IP\"] = -999;\n    the_map[\"err1_IP\"] = -999;\n    the_map[\"err2_IP\"] = -999;\n    the_map[\"err3_IP\"] = -999;\n    the_map[\"err4_IP\"] = -999;\n    the_map[\"tsos_IP_valid\"] = 0.0;\n  }\n  if (tsos_MuS.isValid()) {\n    the_map[\"tsos_MuS_eta\"] = tsos_MuS.globalPosition().eta();\n    the_map[\"tsos_MuS_phi\"] = tsos_MuS.globalPosition().phi();\n    the_map[\"tsos_MuS_pt\"] = tsos_MuS.globalMomentum().perp();\n    the_map[\"tsos_MuS_pt_eta\"] = tsos_MuS.globalMomentum().eta();\n    the_map[\"tsos_MuS_pt_phi\"] = tsos_MuS.globalMomentum().phi();\n    const AlgebraicSymMatrix55& matrix_MuS = tsos_MuS.curvilinearError().matrix();\n    the_map[\"err0_MuS\"] = sqrt(matrix_MuS[0][0]);\n    the_map[\"err1_MuS\"] = sqrt(matrix_MuS[1][1]);\n    the_map[\"err2_MuS\"] = sqrt(matrix_MuS[2][2]);\n    the_map[\"err3_MuS\"] = sqrt(matrix_MuS[3][3]);\n    the_map[\"err4_MuS\"] = sqrt(matrix_MuS[4][4]);\n    the_map[\"tsos_MuS_valid\"] = 1.0;\n  } else {\n    the_map[\"tsos_MuS_eta\"] = -999;\n    the_map[\"tsos_MuS_phi\"] = -999;\n    the_map[\"tsos_MuS_pt\"] = -999;\n    the_map[\"tsos_MuS_pt_eta\"] = -999;\n    the_map[\"tsos_MuS_pt_phi\"] = -999;\n    the_map[\"err0_MuS\"] = -999;\n    the_map[\"err1_MuS\"] = -999;\n    the_map[\"err2_MuS\"] = -999;\n    the_map[\"err3_MuS\"] = -999;\n    the_map[\"err4_MuS\"] = -999;\n    the_map[\"tsos_MuS_valid\"] = 0.0;\n  }\n}\n\n//\n// Obtain seeding strategy parameters by evaluating DNN classifier for a given muon\n//\nvoid TSGForOIDNN::evaluateClassifier(const std::unordered_map<std::string, float>& feature_map,\n                                     tensorflow::Session* session,\n                                     const pt::ptree& metadata,\n                                     StrategyParameters& out,\n                                     bool& dnnSuccess) const {\n  int n_features = metadata.get<int>(\"n_features\", 0);\n\n  // Prepare tensor for DNN inputs\n  tensorflow::Tensor input(tensorflow::DT_FLOAT, {1, n_features});\n  std::string fname;\n  int i_feature = 0;\n  for (const pt::ptree::value_type& feature : metadata.get_child(\"feature_names\")) {\n    fname = feature.second.data();\n    if (feature_map.find(fname) == feature_map.end()) {\n      // don't evaluate DNN if any input feature is missing\n      dnnSuccess = false;\n    } else {\n      input.matrix<float>()(0, i_feature) = float(feature_map.at(fname));\n      i_feature++;\n    }\n  }\n\n  // Prepare tensor for DNN outputs\n  std::vector<tensorflow::Tensor> outputs;\n\n  // Evaluate DNN and put results in output tensor\n  std::string inputLayer = metadata.get<std::string>(\"input_layer\");\n  std::string outputLayer = metadata.get<std::string>(\"output_layer\");\n\n  tensorflow::run(session, {{inputLayer, input}}, {outputLayer}, &outputs);\n  tensorflow::Tensor out_tensor = outputs[0];\n  tensorflow::TTypes<float, 1>::Matrix dnn_outputs = out_tensor.matrix<float>();\n\n  // Find output with largest prediction\n  int imax = -1;\n  float out_max = 0;\n  for (long long int i = 0; i < out_tensor.dim_size(1); i++) {\n    float ith_output = dnn_outputs(0, i);\n    if (ith_output > out_max) {\n      imax = i;\n      out_max = ith_output;\n    }\n  }\n\n  // Decode output\n  const std::string label = \"output_labels.label_\" + std::to_string(imax);\n  out.nHBd = metadata.get<int>(label + \".nHBd\");\n  out.nHLIP = metadata.get<int>(label + \".nHLIP\");\n  out.nHLMuS = metadata.get<int>(label + \".nHLMuS\");\n  out.sf = metadata.get<int>(label + \".SF\");\n\n  dnnSuccess = true;\n}\n\n//\n// Obtain seeding strategy parameters by evaluating DNN regressor for a given muon\n//\nvoid TSGForOIDNN::evaluateRegressor(const std::unordered_map<std::string, float>& feature_map,\n                                    tensorflow::Session* session_HB,\n                                    const pt::ptree& metadata_HB,\n                                    tensorflow::Session* session_HLIP,\n                                    const pt::ptree& metadata_HLIP,\n                                    tensorflow::Session* session_HLMuS,\n                                    const pt::ptree& metadata_HLMuS,\n                                    StrategyParameters& out,\n                                    bool& dnnSuccess) const {\n  int n_features = metadata_HB.get<int>(\"n_features\", 0);\n\n  // Prepare tensor for DNN inputs\n  tensorflow::Tensor input(tensorflow::DT_FLOAT, {1, n_features});\n  std::string fname;\n  int i_feature = 0;\n  for (const pt::ptree::value_type& feature : metadata_HB.get_child(\"feature_names\")) {\n    fname = feature.second.data();\n    if (feature_map.find(fname) == feature_map.end()) {\n      // don't evaluate DNN if any input feature is missing\n      dnnSuccess = false;\n    } else {\n      input.matrix<float>()(0, i_feature) = float(feature_map.at(fname));\n      i_feature++;\n    }\n  }\n\n  // Prepare tensor for DNN outputs\n  std::vector<tensorflow::Tensor> outputs_HB;\n  // Evaluate DNN and put results in output tensor\n  std::string inputLayer_HB = metadata_HB.get<std::string>(\"input_layer\");\n  std::string outputLayer_HB = metadata_HB.get<std::string>(\"output_layer\");\n  tensorflow::run(session_HB, {{inputLayer_HB, input}}, {outputLayer_HB}, &outputs_HB);\n  tensorflow::Tensor out_tensor_HB = outputs_HB[0];\n  tensorflow::TTypes<float, 1>::Matrix dnn_outputs_HB = out_tensor_HB.matrix<float>();\n\n  // Prepare tensor for DNN outputs\n  std::vector<tensorflow::Tensor> outputs_HLIP;\n  // Evaluate DNN and put results in output tensor\n  std::string inputLayer_HLIP = metadata_HLIP.get<std::string>(\"input_layer\");\n  std::string outputLayer_HLIP = metadata_HLIP.get<std::string>(\"output_layer\");\n  tensorflow::run(session_HLIP, {{inputLayer_HLIP, input}}, {outputLayer_HLIP}, &outputs_HLIP);\n  tensorflow::Tensor out_tensor_HLIP = outputs_HLIP[0];\n  tensorflow::TTypes<float, 1>::Matrix dnn_outputs_HLIP = out_tensor_HLIP.matrix<float>();\n\n  // Prepare tensor for DNN outputs\n  std::vector<tensorflow::Tensor> outputs_HLMuS;\n  // Evaluate DNN and put results in output tensor\n  std::string inputLayer_HLMuS = metadata_HLMuS.get<std::string>(\"input_layer\");\n  std::string outputLayer_HLMuS = metadata_HLMuS.get<std::string>(\"output_layer\");\n  tensorflow::run(session_HLMuS, {{inputLayer_HLMuS, input}}, {outputLayer_HLMuS}, &outputs_HLMuS);\n  tensorflow::Tensor out_tensor_HLMuS = outputs_HLMuS[0];\n  tensorflow::TTypes<float, 1>::Matrix dnn_outputs_HLMuS = out_tensor_HLMuS.matrix<float>();\n\n  // Decode output\n  out.nHBd = round(dnn_outputs_HB(0, 0));\n  out.nHLIP = round(dnn_outputs_HLIP(0, 0));\n  out.sf = round(dnn_outputs_HLIP(0, 1));\n  out.nHLMuS = round(dnn_outputs_HLMuS(0, 0));\n\n  // Prevent prediction of negative number of seeds or too many seeds\n  out.nHBd = std::clamp(out.nHBd, 0, 10);\n  out.nHLIP = std::clamp(out.nHLIP, 0, 10);\n  out.nHLMuS = std::clamp(out.nHLMuS, 0, 10);\n\n  // Prevent prediction of 0 seeds in total\n  if (out.nHBd == 0 && out.nHLIP == 0 && out.nHLMuS == 0) {\n    // default strategy, similar to Run 2\n    out.nHBd = 1;\n    out.nHLIP = 5;\n  }\n\n  // Prevent extreme predictions for scale factors\n  // (on average SF=2 was found to be optimal)\n  if (out.sf <= 0)\n    out.sf = 2;\n  if (out.sf > 10)\n    out.sf = 10;\n\n  dnnSuccess = true;\n}\n\n//\n// Default values of configuration parameters\n//\nvoid TSGForOIDNN::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {\n  edm::ParameterSetDescription desc;\n  desc.add<edm::InputTag>(\"src\", edm::InputTag(\"hltL2Muons\", \"UpdatedAtVtx\"));\n  desc.add<int>(\"layersToTry\", 2);\n  desc.add<double>(\"fixedErrorRescaleFactorForHitless\", 2.0);\n  desc.add<int>(\"hitsToTry\", 1);\n  desc.add<edm::InputTag>(\"MeasurementTrackerEvent\", edm::InputTag(\"hltSiStripClusters\"));\n  desc.add<std::string>(\"estimator\", \"hltESPChi2MeasurementEstimator100\");\n  desc.add<double>(\"maxEtaForTOB\", 1.8);\n  desc.add<double>(\"minEtaForTEC\", 0.7);\n  desc.addUntracked<bool>(\"debug\", false);\n  desc.add<unsigned int>(\"maxSeeds\", 20);\n  desc.add<unsigned int>(\"maxHitlessSeeds\", 5);\n  desc.add<unsigned int>(\"maxHitSeeds\", 1);\n  desc.add<std::string>(\"propagatorName\", \"PropagatorWithMaterialParabolicMf\");\n  desc.add<unsigned int>(\"maxHitlessSeedsIP\", 5);\n  desc.add<unsigned int>(\"maxHitlessSeedsMuS\", 0);\n  desc.add<unsigned int>(\"maxHitDoubletSeeds\", 0);\n  desc.add<bool>(\"getStrategyFromDNN\", false);\n  desc.add<bool>(\"useRegressor\", false);\n  desc.add<double>(\"etaSplitForDnn\", 1.0);\n  desc.add<std::string>(\"dnnMetadataPath\", \"\");\n  descriptions.add(\"tsgForOIDNN\", desc);\n}\n\nDEFINE_FWK_MODULE(TSGForOIDNN);\n", "meta": {"hexsha": "2cd4f5eca0d651e9776db6b184e2aff94a7340c5", "size": 45336, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RecoMuon/TrackerSeedGenerator/plugins/TSGForOIDNN.cc", "max_stars_repo_name": "malbouis/cmssw", "max_stars_repo_head_hexsha": "16173a30d3f0c9ecc5419c474bb4d272c58b65c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 852.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T21:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T21:14:00.000Z", "max_issues_repo_path": "RecoMuon/TrackerSeedGenerator/plugins/TSGForOIDNN.cc", "max_issues_repo_name": "gartung/cmssw", "max_issues_repo_head_hexsha": "3072dde3ce94dcd1791d778988198a44cde02162", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30371.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T00:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:26:05.000Z", "max_forks_repo_path": "RecoMuon/TrackerSeedGenerator/plugins/TSGForOIDNN.cc", "max_forks_repo_name": "gartung/cmssw", "max_forks_repo_head_hexsha": "3072dde3ce94dcd1791d778988198a44cde02162", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3240.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T05:53:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:24:21.000Z", "avg_line_length": 44.6660098522, "max_line_length": 138, "alphanum_fraction": 0.661858126, "num_tokens": 11538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.18573737298689014}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SIMD_CORRECT_FMA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIMD_CORRECT_FMA_HPP_INCLUDED\n\n#include <boost/simd/function/scalar/correct_fma.hpp>\n#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>\n#include <boost/simd/arch/common/simd/function/correct_fma.hpp>\n\n#if defined(BOOST_HW_SIMD_X86_OR_AMD_AVAILABLE)\n#  if BOOST_HW_SIMD_X86_AMD_FMA4\n#    include <boost/simd/arch/x86/fma4/simd/function/correct_fma.hpp>\n#  endif\n#  if BOOST_HW_SIMD_X86_FMA3\n#    include <boost/simd/arch/x86/fma3/simd/function/correct_fma.hpp>\n#  endif\n#endif\n\n#if defined(BOOST_HW_SIMD_PPC_AVAILABLE)\n#  if BOOST_HW_SIMD_PPC >= BOOST_HW_SIMD_PPC_VMX_VERSION\n#    include <boost/simd/arch/ppc/vmx/simd/function/correct_fma.hpp>\n#  endif\n#endif\n\n#endif\n", "meta": {"hexsha": "5e91ce79a6676d326807fd571240031ccdfb536b", "size": 1157, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/simd/correct_fma.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/simd/correct_fma.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/simd/correct_fma.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": 35.0606060606, "max_line_length": 100, "alphanum_fraction": 0.6611927398, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.18573737298689014}}
{"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#include <boost/qvm/scalar_traits.hpp>\n#include <boost/qvm/vec.hpp>\n#include <boost/qvm/mat.hpp>\n#include <boost/qvm/quat.hpp>\n\ntemplate <bool>\nstruct tester;\n\ntemplate <>\nstruct\ntester<true>\n    {\n    };\n\nusing namespace boost::qvm;\ntester<is_scalar<char>::value> t1;\ntester<is_scalar<signed char>::value> t2;\ntester<is_scalar<unsigned char>::value> t3;\ntester<is_scalar<signed short>::value> t4;\ntester<is_scalar<unsigned short>::value> t5;\ntester<is_scalar<signed int>::value> t6;\ntester<is_scalar<unsigned int>::value> t7;\ntester<is_scalar<signed long>::value> t8;\ntester<is_scalar<unsigned long>::value> t9;\ntester<is_scalar<float>::value> t10;\ntester<is_scalar<double>::value> t11;\ntester<is_scalar<long double>::value> t13;\ntester<!is_scalar<vec<float,4> >::value> t14;\ntester<!is_scalar<mat<float,4,4> >::value> t15;\ntester<!is_scalar<quat<float> >::value> t16;\n", "meta": {"hexsha": "b419cdeebd73d139f1d96f610ed68d1461f1181b", "size": 1091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/qvm/test/scalar_traits_test.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/qvm/test/scalar_traits_test.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/qvm/test/scalar_traits_test.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": 30.3055555556, "max_line_length": 78, "alphanum_fraction": 0.7442713107, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1857373694606667}}
{"text": "#include <drake/systems/plants/RigidBodyIK.h>\n#include <drake/systems/plants/RigidBodyTree.h>\n#include <drake/systems/plants/constraint/RigidBodyConstraint.h>\n\n#include <drake/systems/plants/IKoptions.h>\n#include <iostream>\n#include <cstdlib>\n#include <limits>\n#include <boost/shared_ptr.hpp>\n\nusing namespace std;\nusing namespace Eigen;\n\n#include \"lcmtypes/bot_core/robot_state_t.hpp\"\n#include \"lcmtypes/drc/robot_plan_w_keyframes_t.hpp\"\n#include <lcm/lcm-cpp.hpp>\n\n// Find the joint position indices corresponding to 'name'\nvector<int> getJointPositionVectorIndices(const RigidBodyTree &model, const std::string &name) {\n  shared_ptr<RigidBody> joint_parent_body = model.findJoint(name);\n  int num_positions = joint_parent_body->getJoint().getNumPositions();\n  vector<int> ret(static_cast<size_t>(num_positions));\n\n  // fill with sequentially increasing values, starting at joint_parent_body->position_num_start:\n  iota(ret.begin(), ret.end(), joint_parent_body->position_num_start);\n  return ret;\n}\n\nvoid findJointAndInsert(const RigidBodyTree &model, const std::string &name, vector<int> &position_list) {\n  auto position_indices = getJointPositionVectorIndices(model, name);\n\n  position_list.insert(position_list.end(), position_indices.begin(), position_indices.end());\n}\n\n\nclass App{\n  public:\n    App(boost::shared_ptr<lcm::LCM> &lcm_);\n    \n    ~App(){\n    }\n\n    void getRobotState(bot_core::robot_state_t& robot_state_msg, int64_t utime_in, Eigen::VectorXd q, std::vector<std::string> jointNames);\n\n  private:\n    boost::shared_ptr<lcm::LCM> lcm_;\n\n};\n\nApp::App(boost::shared_ptr<lcm::LCM> &lcm_):\n                       lcm_(lcm_){\n\n}\n\n\nEigen::Quaterniond euler_to_quat(double roll, double pitch, double yaw) {\n  \n  // This conversion function introduces a NaN in Eigen Rotations when:\n  // roll == pi , pitch,yaw =0    ... or other combinations.\n  // cos(pi) ~=0 but not exactly 0 \n  // Post DRC Trails: replace these with Eigen's own conversions\n  if ( ((roll==M_PI) && (pitch ==0)) && (yaw ==0)){\n    return  Eigen::Quaterniond(0,1,0,0);\n  }else if( ((pitch==M_PI) && (roll ==0)) && (yaw ==0)){\n    return  Eigen::Quaterniond(0,0,1,0);\n  }else if( ((yaw==M_PI) && (roll ==0)) && (pitch ==0)){\n    return  Eigen::Quaterniond(0,0,0,1);\n  }\n  \n  double sy = sin(yaw*0.5);\n  double cy = cos(yaw*0.5);\n  double sp = sin(pitch*0.5);\n  double cp = cos(pitch*0.5);\n  double sr = sin(roll*0.5);\n  double cr = cos(roll*0.5);\n  double w = cr*cp*cy + sr*sp*sy;\n  double x = sr*cp*cy - cr*sp*sy;\n  double y = cr*sp*cy + sr*cp*sy;\n  double z = cr*cp*sy - sr*sp*cy;\n  return Eigen::Quaterniond(w,x,y,z);\n}\n\n\nvoid quat_to_euler(Eigen::Quaterniond q, double& roll, double& pitch, double& yaw) {\n  const double q0 = q.w();\n  const double q1 = q.x();\n  const double q2 = q.y();\n  const double q3 = q.z();\n  roll = atan2(2*(q0*q1+q2*q3), 1-2*(q1*q1+q2*q2));\n  pitch = asin(2*(q0*q2-q3*q1));\n  yaw = atan2(2*(q0*q3+q1*q2), 1-2*(q2*q2+q3*q3));\n}\n\nvoid App::getRobotState(bot_core::robot_state_t& robot_state_msg, int64_t utime_in, Eigen::VectorXd q, std::vector<std::string> jointNames){\n  robot_state_msg.utime = utime_in;\n\n  // Pelvis Pose:\n  robot_state_msg.pose.translation.x =q(0);\n  robot_state_msg.pose.translation.y =q(1);\n  robot_state_msg.pose.translation.z =q(2);\n\n  Eigen::Quaterniond quat = euler_to_quat( q(3), q(4), q(5));\n\n  robot_state_msg.pose.rotation.w = quat.w();\n  robot_state_msg.pose.rotation.x = quat.x();\n  robot_state_msg.pose.rotation.y = quat.y();\n  robot_state_msg.pose.rotation.z = quat.z();\n\n  robot_state_msg.twist.linear_velocity.x  = 0;\n  robot_state_msg.twist.linear_velocity.y  = 0;\n  robot_state_msg.twist.linear_velocity.z  = 0;\n  robot_state_msg.twist.angular_velocity.x = 0;\n  robot_state_msg.twist.angular_velocity.y = 0;\n  robot_state_msg.twist.angular_velocity.z = 0;\n\n  // Joint States:\n  for (size_t i = 0; i < jointNames.size(); i++)  {\n    robot_state_msg.joint_name.push_back( jointNames[i] );\n    robot_state_msg.joint_position.push_back( q(i) );\n    robot_state_msg.joint_velocity.push_back( 0);\n    robot_state_msg.joint_effort.push_back( 0 );\n  }\n  robot_state_msg.num_joints = robot_state_msg.joint_position.size();\n}\n\n\n\n\n\nint main(int argc, char *argv[])\n{\n\n  std::string file_path = \"fname\";\n  if ((argc > 1)){\n    file_path = argv[1];\n  }else{\n    std::cout << \"you need to provide the path to atlas_minimal_contact.urdf\\n\";\n    return 1;\n  }\n\n  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM() );\n  App app(lcm);\n\n  RigidBodyTree model(file_path);\n\n  Vector2d tspan;\n  tspan << 0, 1;\n\n  // Default Atlas v5 posture:\n  VectorXd qstar(model.num_positions);\n  qstar <<\n  -0.0260, 0, 0.8440, 0, 0, 0, 0, 0, 0, 0.2700, 0, 0.0550, -0.5700, 1.1300, -0.5500, -0.0550, -1.3300, 2.1530, 0.5000, 0.0985, 0, 0.0008, -0.2700, 0, -0.0550, -0.5700, 1.1300, -0.5500, 0.0550, 1.3300, 2.1530, -0.5000, 0.0985, 0, 0.0008, 0.2564;\n\n  // 1 Back Posture Constraint\n  PostureConstraint kc_posture_back(&model, tspan);\n  std::vector<int> back_idx;\n  findJointAndInsert(model, \"back_bkz\", back_idx);\n  findJointAndInsert(model, \"back_bky\", back_idx);\n  findJointAndInsert(model, \"back_bkx\", back_idx);\n  VectorXd back_lb = VectorXd::Zero(3);\n  VectorXd back_ub = VectorXd::Zero(3);\n  kc_posture_back.setJointLimits(3, back_idx.data(), back_lb, back_ub);\n\n  // 2 Knees Constraint\n  PostureConstraint kc_posture_knees(&model, tspan);\n  std::vector<int> knee_idx;\n  findJointAndInsert(model, \"l_leg_kny\", knee_idx);\n  findJointAndInsert(model, \"r_leg_kny\", knee_idx);\n  VectorXd knee_lb = VectorXd::Zero(2);\n  knee_lb(0) = 1.0; // usually use 0.6\n  knee_lb(1) = 1.0; // usually use 0.6\n  VectorXd knee_ub = VectorXd::Zero(2);\n  knee_ub(0) = 2.5;\n  knee_ub(1) = 2.5;\n  kc_posture_knees.setJointLimits(2, knee_idx.data(), knee_lb, knee_ub);\n\n  // 3 Left Arm Constraint\n  PostureConstraint kc_posture_larm(&model, tspan);\n  std::vector<int> larm_idx;\n  findJointAndInsert(model, \"l_arm_shz\", larm_idx);\n  findJointAndInsert(model, \"l_arm_shx\", larm_idx);\n  findJointAndInsert(model, \"l_arm_ely\", larm_idx);\n  findJointAndInsert(model, \"l_arm_elx\", larm_idx);\n  findJointAndInsert(model, \"l_arm_uwy\", larm_idx);\n  findJointAndInsert(model, \"l_arm_mwx\", larm_idx);\n  findJointAndInsert(model, \"l_arm_lwy\", larm_idx);\n  VectorXd larm_lb = VectorXd::Zero(7);\n  larm_lb(0) = 0.27;\n  larm_lb(1) = -1.33;\n  larm_lb(2) = 2.153;\n  larm_lb(3) = 0.500;\n  larm_lb(4) = 0.0985;\n  larm_lb(5) = 0;\n  larm_lb(6) = 0.0008;\n  VectorXd larm_ub = larm_lb;\n  kc_posture_larm.setJointLimits(7, larm_idx.data(), larm_lb, larm_ub);\n\n  // 4 Left Foot Position and Orientation Constraints\n  int l_foot = model.findLinkId(\"l_foot\");\n  Vector3d l_foot_pt = Vector3d::Zero();\n  Vector3d lfoot_pos0;\n  lfoot_pos0(0) = 0;\n  lfoot_pos0(1) = 0.13;\n  lfoot_pos0(2) = 0.08;\n  Vector3d lfoot_pos_lb = lfoot_pos0;\n  lfoot_pos_lb(0) += 0.001;\n  lfoot_pos_lb(1) += 0.001;\n  lfoot_pos_lb(2) += 0.001;\n  Vector3d lfoot_pos_ub = lfoot_pos_lb;\n  lfoot_pos_ub(2) += 0.01;\n  // std::cout << lfoot_pos0.transpose() << \" lfoot\\n\" ;\n  WorldPositionConstraint kc_lfoot_pos(&model, l_foot, l_foot_pt, lfoot_pos_lb, lfoot_pos_ub, tspan);\n  Eigen::Vector4d quat_des(1, 0, 0, 0);\n  double tol = 0.0017453292519943296;\n  WorldQuatConstraint kc_lfoot_quat(&model, l_foot, quat_des, tol, tspan);\n\n  // 5 Right Foot Position and Orientation Constraints\n  int r_foot = model.findLinkId(\"r_foot\");\n  Vector3d r_foot_pt = Vector3d::Zero();\n  Vector3d rfoot_pos0;\n  rfoot_pos0(0) = 0;\n  rfoot_pos0(1) = -0.13;\n  rfoot_pos0(2) = 0.08;\n  Vector3d rfoot_pos_lb = rfoot_pos0;\n  rfoot_pos_lb(0) += 0.001;\n  rfoot_pos_lb(1) += 0.001;\n  rfoot_pos_lb(2) += 0.001;\n  Vector3d rfoot_pos_ub = rfoot_pos_lb;\n  rfoot_pos_ub(2) += 0.001;\n  //std::cout << rfoot_pos0.transpose() << \" lfoot\\n\" ;\n  WorldPositionConstraint kc_rfoot_pos(&model, r_foot, r_foot_pt, rfoot_pos_lb, rfoot_pos_ub, tspan);\n  WorldQuatConstraint kc_rfoot_quat(&model, r_foot, quat_des, tol, tspan);\n\n\n  // 6 Right Position Constraints (actual reaching constraint)\n  int r_hand = model.findLinkId(\"r_hand\");\n  Vector3d r_hand_pt = Vector3d::Zero();\n  Vector3d rhand_pos0;\n  //Vector3d rhand_pos0 = model.forwardKin(r_hand_pt, r_hand, 0, 0);\n  rhand_pos0(0) = 0.2;\n  rhand_pos0(1) = -0.5;\n  rhand_pos0(2) = 0.4;\n  Vector3d rhand_pos_lb = rhand_pos0;\n  rhand_pos_lb(0) += 0.05;\n  rhand_pos_lb(1) += 0.05;\n  rhand_pos_lb(2) += 0.05;\n  Vector3d rhand_pos_ub = rhand_pos_lb;\n  rhand_pos_ub(2) += 0.05;\n  //std::cout << rhand_pos_ub.transpose() << \" rhand\\n\" ;\n  WorldPositionConstraint kc_rhand(&model, r_hand, r_hand_pt, rhand_pos_lb, rhand_pos_ub, tspan);\n\n\n  // 7 QuasiStatic Constraints\n  QuasiStaticConstraint kc_quasi(&model, tspan);\n  kc_quasi.setShrinkFactor(0.2);\n  kc_quasi.setActive(true);\n  Eigen::Matrix3Xd l_foot_pts = Eigen::Matrix3Xd::Zero(3, 4);\n  l_foot_pts << -0.0820, -0.0820, 0.1780, 0.1780,\n      0.0624, -0.0624, 0.0624, -0.0624,\n      -0.0811, -0.0811, -0.0811, -0.0811;\n  kc_quasi.addContact(1, &l_foot, &l_foot_pts);\n  Eigen::Matrix3Xd r_foot_pts = Eigen::Matrix3Xd::Zero(3, 4);\n  r_foot_pts << -0.0820, -0.0820, 0.1780, 0.1780,\n      0.0624, -0.0624, 0.0624, -0.0624,\n      -0.0811, -0.0811, -0.0811, -0.0811;\n  kc_quasi.addContact(1, &r_foot, &r_foot_pts);\n\n\n  std::vector<RigidBodyConstraint *> constraint_array;\n  constraint_array.push_back(&kc_quasi);\n  constraint_array.push_back(&kc_posture_knees);\n  constraint_array.push_back(&kc_lfoot_pos);\n  constraint_array.push_back(&kc_lfoot_quat);\n  constraint_array.push_back(&kc_rfoot_pos);\n  constraint_array.push_back(&kc_rfoot_quat);\n  constraint_array.push_back(&kc_rhand);\n  constraint_array.push_back(&kc_posture_larm);\n  constraint_array.push_back(&kc_posture_back);\n\n  IKoptions ikoptions(&model);\n  VectorXd q_sol(model.num_positions);\n  int info;\n  vector<string> infeasible_constraint;\n  inverseKin(&model, qstar, qstar, constraint_array.size(), constraint_array.data(), q_sol, info, infeasible_constraint, ikoptions);\n  printf(\"INFO = %d\\n\", info);\n  if (info != 1) {\n    return 1;\n  }\n\n\n\n  /////////////////////////////////////////\n  KinematicsCache<double> cache = model.doKinematics(q_sol);\n  Vector3d com = model.centerOfMass(cache);\n  printf(\"%5.2f\\n%5.2f\\n%5.2f\\n\",com(0),com(1),com(2));\n\n  bot_core::robot_state_t robot_state_msg;\n  std::vector<string> jointNames;\n  for (int i=0 ; i <model.num_positions ; i++){\n    // std::cout << model.getPositionName(i) << \" \" << i << \"\\n\";\n    jointNames.push_back( model.getPositionName(i) ) ;\n  }  \n\n  app.getRobotState(robot_state_msg, 0*1E6, q_sol , jointNames);\n\n  lcm->publish(\"EST_ROBOT_STATE\",&robot_state_msg);\n  return 0;\n}\n", "meta": {"hexsha": "7263e9b6f1cdd3921c8d92418a2003e7b726584f", "size": 10578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/control/src/tests/testIKMoreConstraintsLCM.cpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/control/src/tests/testIKMoreConstraintsLCM.cpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/control/src/tests/testIKMoreConstraintsLCM.cpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 34.2330097087, "max_line_length": 244, "alphanum_fraction": 0.6935148421, "num_tokens": 3584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18573736946066666}}
{"text": "// This file is part of VIO - Semi-direct Visual Odometry.\n//\n// Copyright (C) 2014 Christian Forster <forster at ifi dot uzh dot ch>\n// (Robotics and Perception Group, University of Zurich, Switzerland).\n//\n// VIO is free software: you can redistribute it and/or modify it under the\n// terms of the GNU General Public License as published by the Free Software\n// Foundation, either version 3 of the License, or any later version.\n//\n// VIO is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the 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 <vio/abstract_camera.h>\n#include <stdlib.h>\n#include <Eigen/StdVector>\n#include <boost/bind.hpp>\n#include <fstream>\n#include <vio/frame_handler_base.h>\n#include <vio/config.h>\n#include <vio/feature.h>\n#include <vio/matcher.h>\n#include <vio/map.h>\n#include <vio/point.h>\n\nnamespace vio\n{\n\n// definition of global and static variables which were declared in the header\n\nFrameHandlerBase::FrameHandlerBase() :\n  stage_(STAGE_PAUSED),\n  set_reset_(false),\n  set_start_(false),\n  num_obs_last_(0)\n{\n}\n\nFrameHandlerBase::~FrameHandlerBase()\n{\n}\n\nbool FrameHandlerBase::startFrameProcessingCommon(const double timestamp)\n{\n  if(set_start_)\n  {\n    resetAll();\n    stage_ = STAGE_FIRST_FRAME;\n  }\n\n  if(stage_ == STAGE_PAUSED)\n    return false;\n\n  map_.emptyTrash();\n  return true;\n}\n\nint FrameHandlerBase::finishFrameProcessingCommon(\n    const size_t update_id,\n    const UpdateResult dropout,\n    const size_t num_observations)\n{\n\n  if(stage_ == STAGE_DEFAULT_FRAME)\n  num_obs_last_ = num_observations;\n\n  if(dropout == RESULT_FAILURE &&\n      (stage_ == STAGE_DEFAULT_FRAME || stage_ == STAGE_RELOCALIZING ))\n  {\n    //stage_ = STAGE_RELOCALIZING;\n  }\n  if(set_reset_)\n    resetAll();\n\n  return 0;\n}\n\nvoid FrameHandlerBase::resetCommon()\n{\n  map_.reset();\n  stage_ = STAGE_PAUSED;\n  set_reset_ = false;\n  set_start_ = false;\n  num_obs_last_ = 0;\n}\n\nbool ptLastOptimComparator(Point* lhs, Point* rhs)\n{\n  return (lhs->last_structure_optim_ < rhs->last_structure_optim_);\n}\n\nvoid FrameHandlerBase::optimizeStructure(\n    FramePtr frame,\n    size_t max_n_pts,\n    int max_iter)\n{\n  for(auto&& it:frame->fts_){\n      if(it->point==NULL)continue;\n      if(it->point->obs_.size()<2){\n          it->point->last_frame_overlap_id_= frame->id_;\n          continue;\n      }\n      it->point->optimize(max_iter);\n      it->point->last_frame_overlap_id_= frame->id_;\n  }\n}\nvoid FrameHandlerBase::posEdit(\n            FramePtr frame)\n    {\n        for(auto&& it:frame->fts_){\n            if(it->point!=NULL && !it->point->pos_.hasNaN() && it->point->pos_.norm() !=0.){\n                if(it->point->obs_.size()==2){\n                    Eigen::Matrix<double,4,4> A,frame_a,frame_b;\n                    frame_a=it->point->obs_.front()->frame->se3().matrix();\n                    frame_b=it->point->obs_.back()->frame->se3().matrix();\n                    A.row(0) = it->point->obs_.front()->f(0) * frame_a.row(2) - it->point->obs_.front()->f(2) * frame_a.row(0);\n                    A.row(1) = it->point->obs_.front()->f(1) * frame_a.row(2) - it->point->obs_.front()->f(2) * frame_a.row(1);\n                    A.row(2) = it->point->obs_.back()->f(0) * frame_b.row(2) - it->point->obs_.back()->f(2) * frame_b.row(0);\n                    A.row(3) = it->point->obs_.back()->f(1) * frame_b.row(2) - it->point->obs_.back()->f(2) * frame_b.row(1);\n                    // A\u3092\u7279\u7570\u5024\u5206\u89e3\u3059\u308b (A = U S Vt)\n                    // https://eigen.tuxfamily.org/dox/classEigen_1_1JacobiSVD.html\n                    Eigen::JacobiSVD<Eigen::Matrix<double,4,4>> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n                    const Eigen::Matrix<double,4,1> singular_vector = svd.matrixV().block<4, 1>(0, 3);\n                    it->point->pos_=singular_vector.block<3, 1>(0, 0) / singular_vector(3);\n                }\n                //if(frame->w2f(it->point->pos_).z()<1e-9)map_.safeDeletePoint(it->point);\n            }else{\n                map_.safeDeletePoint(it->point);\n            }\n        }\n    }\n\n} // namespace vio\n", "meta": {"hexsha": "9c44be6daaaf792e62625d8a2fe7baf30e81042c", "size": 4310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GPU_version/vio/src/frame_handler_base.cpp", "max_stars_repo_name": "Pilot-Labs-Dev/vio_svo", "max_stars_repo_head_hexsha": "8274e4269b383e9816fca5c3102b51cd4d1b95ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T01:12:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:17:24.000Z", "max_issues_repo_path": "GPU_version/vio/src/frame_handler_base.cpp", "max_issues_repo_name": "Pilot-Labs-Dev/vio_svo", "max_issues_repo_head_hexsha": "8274e4269b383e9816fca5c3102b51cd4d1b95ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GPU_version/vio/src/frame_handler_base.cpp", "max_forks_repo_name": "Pilot-Labs-Dev/vio_svo", "max_forks_repo_head_hexsha": "8274e4269b383e9816fca5c3102b51cd4d1b95ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-12T11:42:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T11:42:01.000Z", "avg_line_length": 31.4598540146, "max_line_length": 127, "alphanum_fraction": 0.6329466357, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.1857373659344433}}
{"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\u20131488.\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\u20131636.\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#include \"selection_parser.h\"\n#include \"pteros/core/system.h\"\n#include \"pteros/core/selection.h\"\n#include \"pteros/core/logging.h\"\n#include \"pteros/core/pteros_error.h\"\n#include \"pteros/core/distance_search.h\"\n#include <Eigen/Core>\n#include <boost/algorithm/string.hpp>\n#include <boost/range/counting_range.hpp>\n#include <unordered_set>\n#include <regex>\n#include <list>\n\nusing namespace std;\nusing namespace pteros;\nusing namespace boost;\n\n\n//===============================================\n\n// We derive from normal peg::parser\nclass Pteros_PEG_parser: public peg::parser {\npublic:\n    Pteros_PEG_parser(const char* s): peg::parser(s) {\n        enable_ast<MyAst>();\n        enable_packrat_parsing();\n        log = [&](size_t ln, size_t col, const string& msg) {\n            error_message = fmt::format(\"{}:{}\",col,msg);\n        };        \n    }\n\n    virtual ~Pteros_PEG_parser(){}\n\n    string error_message;\n};\n\n\n// Instance of the parser itself\nPteros_PEG_parser _parser(R\"(\n        LOGICAL_EXPR       <-  LOGICAL_OPERAND (LOGICAL_OPERATOR LOGICAL_OPERAND)*\n        LOGICAL_OPERATOR   <-  < 'or' / 'and' >\n        LOGICAL_OPERAND    <-  (NOT / BY)? ( '(' LOGICAL_EXPR ')' / ALL / NUM_COMPARISON / KEYWORD_EXPR / WITHIN )\n        ALL                <-  < 'all' >\n        NOT                <-  < 'not' >\n        BY                 <-  'by' < ('residue' / 'chain' / 'mol') > / 'same' < ('residue' / 'chain' / 'mol') > 'as'\n\n        NUM_COMPARISON     <-  NUM_EXPR COMPARISON_OPERATOR NUM_EXPR (COMPARISON_OPERATOR NUM_EXPR)?\n        COMPARISON_OPERATOR <- <  '==' / '<=' / '>=' / '<>' / '!=' / '<' / '>' / '=' >\n        NUM_EXPR           <- NUM_TERM (PLUS_MINUS NUM_TERM)*\n        NUM_TERM           <- NUM_POWER (DIV_MUL NUM_POWER)*\n        NUM_POWER          <- NUM_FACTOR (POW NUM_FACTOR)?\n        NUM_FACTOR         <- UNARY_MINUS? ( '(' NUM_EXPR ')' / X / Y / Z / BETA / OCC / RESINDEX / INDEX\n                                                              / RESID / DIST / MASS / CHARGE ) / FLOAT\n        PLUS_MINUS         <- < '+' / '-' >\n        DIV_MUL            <- < '*' / '/' >\n        POW                <- < '^' / '**' >\n        UNARY_MINUS        <- < '-' >\n\n        X                  <-  ('X' / 'x') ('of' COM)?\n        Y                  <-  ('Y' / 'y') ('of' COM)?\n        Z                  <-  ('Z' / 'z') ('of' COM)?\n        BETA               <- < 'beta' >\n        OCC                <- < 'occupancy' / 'occ' >\n        RESINDEX           <- < 'resindex' >\n        INDEX              <- < 'index' >\n        RESID              <- < 'resid' >\n        MASS               <- < 'mass' >\n        CHARGE             <- < 'charge' >\n\n        COM                <- COM_TYPE PBC? 'of' LOGICAL_OPERAND\n        COM_TYPE           <- < 'com' / 'cog' >\n\n        DIST               <- ('dist' / 'distance') (POINT / VECTOR / PLANE)\n        POINT              <- 'point' PBC? (FLOAT FLOAT FLOAT / COM)\n        VECTOR             <- 'vector' PBC? (FLOAT FLOAT FLOAT / COM) FLOAT FLOAT FLOAT\n        PLANE              <- 'plane' PBC? (FLOAT FLOAT FLOAT / COM) FLOAT FLOAT FLOAT\n\n        FLOAT              <- < INTEGER ('.' [0-9]+ )? ( ('e' / 'E' ) INTEGER )? >\n        INTEGER            <- < ('-' / '+')? [0-9]+ >\n\n        KEYWORD_EXPR       <- STR_KEYWORD_EXPR / INT_KEYWORD_EXPR\n        STR_KEYWORD_EXPR   <- STR_KEYWORD (STR / REGEX)+\n        STR_KEYWORD        <- < 'name' / 'resname' / 'tag' / 'chain' / 'type' >\n        STR                <- !('or'/'and') < [a-zA-Z0-9]+ >\n\n        INT_KEYWORD_EXPR   <- INT_KEYWORD (RANGE / INTEGER)+\n        INT_KEYWORD        <- < 'resindex' / 'index' / 'resid' >\n        RANGE              <- INTEGER ('-'/'to'/':') INTEGER\n\n        WITHIN             <- 'within' FLOAT (PBC SELF / SELF PBC / PBC / SELF)? 'of' LOGICAL_OPERAND\n\n        PBC                <- < 'pbc' / 'nopbc' / 'periodic' / 'nonperiodic' >\n        SELF               <- < 'self' / 'noself' >\n\n        %whitespace      <-  [ \\t\\r\\n]*\n\n        REGEX              <- '\"' <(!'\"' .)*> '\"' / \"'\" <(!\"'\" .)*> \"'\"\n    )\");\n\n\n\n//===============================================\n\n\nbool is_node_coordinate_dependent(const std::shared_ptr<MyAst>& node){\n    if(node->name == \"X\" || node->name == \"Y\" || node->name == \"Z\" || node->name == \"WITHIN\"\n            || node->name == \"POINT\" || node->name == \"PLANE\" || node->name == \"VECTOR\" || node->name == \"COM\"\n      ){\n        return true;\n    } else {\n        return false;\n    }\n}\n\n\nSelection_parser::Selection_parser(std::vector<int> *subset):\n    has_coord(false),\n    starting_subset(subset),\n    sys(nullptr)\n{\n\n}\n\nSelection_parser::~Selection_parser(){}\n\n\nvoid set_coord_dependence(const std::shared_ptr<MyAst>& node){\n    node->is_coord_dependent = is_node_coordinate_dependent(node);\n    if(node->nodes.size()){\n        // tree\n        node->is_coord_dependent = is_node_coordinate_dependent(node);\n        for(int i=0;i<node->nodes.size();++i){\n            set_coord_dependence(node->nodes[i]);\n            if(node->nodes[i]->is_coord_dependent) node->is_coord_dependent = true;\n        }\n    }\n\n    //cout << node->name << \" :: \" << node->is_coord_dependent << endl;\n}\n\n\nvoid Selection_parser::optimize(std::shared_ptr<MyAst>& node){\n    // optimize arithmetics\n    if(node->name == \"NUM_EXPR\" || node->name == \"NUM_TERM\" || node->name == \"NUM_POWER\") {\n        // If not-coord dependent just optimize\n        if(!node->is_coord_dependent){\n            // Replace with float node\n            node = std::make_shared<MyAst>(\"\",0,0,\"FLOAT\", fmt::format(\"{}\", get_numeric(node)(0)));\n            node->is_coord_dependent = false; // Keep correct flag just in case\n        }\n    }\n\n    // Convert chained logic into a tree\n    if(node->name == \"LOGICAL_EXPR\" && node->nodes.size()>3){\n        // second operand and all after it should become new node\n        vector<std::shared_ptr<MyAst>> ch;\n        copy(node->nodes.begin()+2,node->nodes.end(),back_inserter(ch));\n        auto operand2 = std::make_shared<MyAst>(\"\",0,0,\"LOGICAL_EXPR\",ch);\n        // Inherit coord dependence for this new node (important in order not to mislead precomputer)\n        operand2->is_coord_dependent = node->is_coord_dependent;\n        // keep only 3 nodes\n        node->nodes.resize(3);\n        // Put new second operand\n        node->nodes[2] = operand2;\n    }\n\n    // Recurse into children\n    for(int i=0;i<node->nodes.size();++i) optimize(node->nodes[i]);\n}\n\n\nvoid Selection_parser::precompute(std::shared_ptr<MyAst>& node){\n    if(    node->name!=\"PRE\"\n        && node->name!=\"NUM_COMPARISON\"\n        && node->name!=\"STR_KEYWORD_EXPR\"\n        && node->name!=\"INT_KEYWORD_EXPR\"\n        && node->name!=\"LOGICAL_EXPR\"\n        && node->name!=\"LOGICAL_OPERAND\"\n        && node->name!=\"ALL\"\n        && node->name!=\"WITHIN\"\n        && node->name!=\"BYRES\") return;\n\n    if(!node->is_coord_dependent){        \n        auto ast = std::make_shared<MyAst>(\"\",0,0,\"PRE\",\"\");\n        eval_node(node, ast->precomputed);\n        node = ast;\n    } else if(!node->nodes.empty()) {\n        for(int i=0;i<node->nodes.size();++i) precompute(node->nodes[i]);\n    }\n}\n\nvoid Selection_parser::create_ast(string& sel_str, System* system){\n    if (_parser.parse(sel_str.c_str(), tree)) {\n        tree = peg::AstOptimizer(true,{\"POINT\",\"X\",\"Y\",\"Z\"}).optimize(tree);\n\n        //cout << sel_str << endl;\n        //cout << peg::ast_to_s(tree) << endl;\n\n        set_coord_dependence(tree);\n    } else {\n        throw Pteros_error(_parser.error_message);\n    }\n\n    if(tree->is_coord_dependent) has_coord = true; // Global coord dependence\n\n    sys = system;\n    Natoms = sys->num_atoms();\n\n    if(starting_subset)\n        current_subset = starting_subset;\n    else\n        current_subset = nullptr;\n\n    // Optimize tree\n    optimize(tree);\n\n    //cout << peg::ast_to_s(tree) << endl;\n\n    // proceed with optimizing pure nodes to precomputed if needed\n    if(has_coord) precompute(tree);\n}\n\nvoid Selection_parser::apply_ast(size_t fr, vector<int>& result){\n    frame = fr;\n    eval_node(tree,result);\n}\n\n\nvoid Selection_parser::eval_node(const std::shared_ptr<MyAst> &node, std::vector<int>& result){\n\n    result.clear();\n\n    // Here starts evaluation\n\n    if(node->name == \"PRE\"){ // Precomputed nodes are created during optimization stage\n        result = node->precomputed;\n    }\n\n    else if(node->name == \"NUM_COMPARISON\")\n    {\n        vector<string> c; // comparison operators\n        vector<std::function<float(int)>> op; // comparison operands\n        vector<std::function<bool(float,float)>> comparison; // Function(s) to evaluate\n\n        if(node->nodes.size() == 3){ // simple\n            c.resize(1);\n            op.resize(2);\n            comparison.resize(1);\n\n            c[0]  = node->nodes[1]->token;\n            op[0] = get_numeric(node->nodes[0]);\n            op[1] = get_numeric(node->nodes[2]);\n\n        } else { // chained\n            c.resize(2);\n            op.resize(3);\n            comparison.resize(2);\n\n            c[0]  = node->nodes[1]->token;\n            c[1]  = node->nodes[3]->token;\n            op[0] = get_numeric(node->nodes[0]);\n            op[1] = get_numeric(node->nodes[2]);\n            op[2] = get_numeric(node->nodes[4]);\n        }\n\n        for(int i=0;i<c.size();++i){\n            if(c[i] == \"=\" || c[i]== \"==\"){\n                comparison[i] = [](float a, float b){ return a==b; };\n            } else if (c[i] == \"!=\" || c[i]==\"<>\"){\n                comparison[i] = [](float a, float b){ return a!=b; };\n            } else if (c[i] == \"<\"){\n                comparison[i] = [](float a, float b){ return a<b; };\n            } else if (c[i] == \">\"){\n                comparison[i] = [](float a, float b){ return a>b; };\n            } else if (c[i] == \"<=\"){\n                comparison[i] = [](float a, float b){ return a<=b; };\n            } else if (c[i] == \">=\"){\n                comparison[i] = [](float a, float b){ return a>=b; };\n            }\n        }\n\n        if(!current_subset) {\n            if(node->nodes.size() == 3){ // simple\n                for(int at=0;at<Natoms;++at)\n                    if( comparison[0](op[0](at),op[1](at)) ) result.push_back(at);\n            } else { // chained\n                for(int at=0;at<Natoms;++at)\n                    if( comparison[0](op[0](at),op[1](at)) && comparison[1](op[1](at),op[2](at)) ) result.push_back(at);\n            }\n        } else {\n            if(node->nodes.size() == 3){ // simple\n                for(int at: *current_subset)\n                    if( comparison[0](op[0](at),op[1](at)) ) result.push_back(at);\n            } else { // chained\n                for(int at: *current_subset)\n                    if( comparison[0](op[0](at),op[1](at)) && comparison[1](op[1](at),op[2](at)) ) result.push_back(at);\n            }\n        }\n    }\n\n    else if(node->name == \"STR_KEYWORD_EXPR\")\n    {\n        std::function<bool(int,const string&)> comp_func_str;\n        std::function<bool(int,const std::regex&)> comp_func_regex;\n\n        const string& keyword = node->nodes[0]->token;\n\n        if(keyword == \"name\"){\n            comp_func_str = [this](int at, const string& str){ return sys->atoms[at].name == str; };\n            comp_func_regex = [this](int at, const std::regex& reg){ return std::regex_match(sys->atoms[at].name.c_str(),reg); };\n        } else if(keyword == \"type\"){\n            comp_func_str = [this](int at, const string& str){ return sys->atoms[at].type_name == str; };\n            comp_func_regex = [this](int at, const std::regex& reg){ return std::regex_match(sys->atoms[at].type_name.c_str(),reg); };\n        } else if(keyword == \"resname\"){\n            comp_func_str = [this](int at, const string& str){ return sys->atoms[at].resname == str; };\n            comp_func_regex = [this](int at, const std::regex& reg){ return std::regex_match(sys->atoms[at].resname.c_str(),reg); };\n        } else if(keyword == \"tag\"){\n            comp_func_str = [this](int at, const string& str){ return sys->atoms[at].tag== str; };\n            comp_func_regex = [this](int at, const std::regex& reg){ return std::regex_match(sys->atoms[at].tag.c_str(),reg); };\n        } else if(keyword == \"chain\"){\n            comp_func_str = [this](int at, const string& str){ return sys->atoms[at].chain == str[0]; };\n            comp_func_regex = [this](int at, const std::regex& reg){\n                string s(\" \");\n                s[0] = sys->atoms[at].chain;\n                return std::regex_match(s.c_str(),reg);\n            };\n        }\n\n        list<string> str_values;\n        list<std::regex> regex_values;\n        for(int i=1;i<node->nodes.size();++i){\n            if(node->nodes[i]->name==\"STR\")\n                str_values.emplace_back(node->nodes[i]->token);\n            else\n                regex_values.emplace_back(node->nodes[i]->token);\n        }\n\n        // Loop body\n        auto body = [&](int at){\n            // Cycle over regex values\n            bool reg_found = false;\n            for(const auto& reg: regex_values){\n                if(comp_func_regex(at,reg)){\n                    result.push_back(at);\n                    reg_found = true;\n                    break;\n                }\n            }\n\n            // If at least one regex matched no need to proceed with strings\n            if(reg_found) return;\n\n            // Cycle over string values\n            for(const auto& str: str_values){\n                if(comp_func_str(at,str)){\n                    result.push_back(at);\n                    break;\n                }\n            }\n        };\n\n        if(!current_subset){\n            for(int at=0;at<Natoms;++at) body(at);\n        } else {\n            for(int at: *current_subset) body(at);\n        }\n\n        // Sort unique\n        sort(result.begin(),result.end());\n        vector<int>::iterator it = unique(result.begin(), result.end());\n        result.resize( it - result.begin() );\n    }\n\n    //---------------------------------------------------------------------------\n    else if(node->name == \"INT_KEYWORD_EXPR\")\n    {\n        const string& keyword = node->nodes[0]->token;\n        int Nchildren = node->nodes.size(); // Get number of children\n\n        // If starting subset is present than this is a subselection and\n        // we have to interpret indexes as local indexes!\n        if(keyword == \"index\") {\n            // Cycle over children\n            for(int i=1;i<Nchildren;++i){\n                if(node->nodes[i]->name == \"INTEGER\") {\n                    int k = stoi(node->nodes[i]->token);\n                    // Shift to local index for subselection if needed\n                    if(starting_subset) k+=(*starting_subset)[0];\n                    // We have to check the range here\n                    if(k>=0 && k<Natoms)\n                        result.push_back(k);\n                } else {\n                    // this is a range, not an integer\n                    int i1 = stoi(node->nodes[i]->nodes[0]->token);\n                    int i2 = stoi(node->nodes[i]->nodes[1]->token);\n                    // Shift to local index for subselection if needed\n                    if(starting_subset){\n                        i1+=(*starting_subset)[0];\n                        i2+=(*starting_subset)[0];\n                    }\n                    for(int k=i1;k<=i2;++k)                        \n                        // We have to check the range here\n                        if(k>=0 && k<Natoms)\n                            result.push_back(k);\n                }\n            }\n\n        } else { // resid or resindex\n\n            // Make lists\n            vector<int> int_list;\n            vector<int> range_list;\n            for(int i=1;i<Nchildren;++i){\n                if(node->nodes[i]->name == \"INTEGER\") {\n                    int_list.push_back(stoi(node->nodes[i]->token));\n                } else {\n                    range_list.push_back(stoi(node->nodes[i]->nodes[0]->token));\n                    range_list.push_back(stoi(node->nodes[i]->nodes[1]->token));\n                }\n            }\n\n            // Comparison function\n            std::function<bool(int,int)> comp_func;\n            if(keyword == \"resid\"){\n                comp_func = [this](int at, int k){ return sys->atoms[at].resid == k; };\n            } else if(keyword == \"resindex\"){\n                comp_func = [this](int at, int k){ return sys->atoms[at].resindex == k; };\n            }\n\n            // Loop body\n            auto body = [&](int at){\n                // Individual numbers\n                for(int k: int_list)\n                    if(comp_func(at,k)) result.push_back(at);\n                // Ranges\n                for(int i=0;i<range_list.size();i+=2){ // Itarage by pair\n                    for(int k=range_list[i];k<=range_list[i+1];++k){ // Inside range\n                        if(comp_func(at,k)) result.push_back(at);\n                    }\n                }\n            };\n\n            // Do loop\n            if(!current_subset){\n                for(int at=0;at<Natoms;++at) body(at);\n            } else {\n                for(int at: *current_subset) body(at);\n            }\n        } // index if\n\n        sort(result.begin(),result.end());\n        vector<int>::iterator it = unique(result.begin(), result.end());\n        result.resize( it - result.begin() );\n    }\n\n    //---------------------------------------------------------------------------\n\n    else if(node->name == \"LOGICAL_EXPR\")\n    {\n        if(node->nodes[1]->token == \"or\") {\n            vector<int> res1,res2;\n            eval_node(node->nodes[0],res1);\n            eval_node(node->nodes[2],res2);\n            std::set_union(res1.begin(),res1.end(),res2.begin(),res2.end(),back_inserter(result));\n\n        } else if(node->nodes[1]->token == \"and\") {\n            // Optimize to put pure node first\n            bool pure1 = !node->nodes[0]->is_coord_dependent;\n            bool pure2 = !node->nodes[2]->is_coord_dependent;\n\n            if(pure2 && !pure1) std::swap(node->nodes[0],node->nodes[2]);\n\n            vector<int> res1,res2;\n            eval_node(node->nodes[0],res1);\n            current_subset = &res1; // Set subset for second\n            eval_node(node->nodes[2],res2); // Is using filled current subset\n\n            std::set_intersection(res1.begin(),res1.end(),res2.begin(),res2.end(),back_inserter(result));\n\n            // Reset subset\n            if(starting_subset){\n                current_subset = starting_subset;\n            } else {\n                current_subset = nullptr;\n            }\n        }\n    }\n\n    else if(node->name == \"LOGICAL_OPERAND\")\n    {\n        vector<int> res;\n        eval_node(node->nodes[1],res);\n\n        if(node->nodes[0]->name == \"NOT\"){\n            if(!current_subset){\n                auto r = boost::counting_range(0,Natoms);\n                std::set_difference(r.begin(),r.end(), res.begin(),res.end(), back_inserter(result));\n            } else {\n                // For subset\n                std::set_difference(current_subset->begin(),current_subset->end(), res.begin(),res.end(), back_inserter(result));\n            }\n\n        } else if(node->nodes[0]->name == \"BY\"){\n            if(node->nodes[0]->token == \"residue\"){\n                // First make a set of resids we need to search\n                std::unordered_set<int> resind;\n                for(auto at: res) resind.insert(sys->atoms[at].resindex);\n\n                // Now cycle over all atoms in the starting subset if present (not current subset!!!)\n                if(starting_subset){\n                    for(int at: *starting_subset) // over starting subset\n                        if(resind.count(sys->atoms[at].resindex)) result.push_back(at);\n                } else {\n                    for(int at=0;at<Natoms;++at) // over all atoms\n                        if(resind.count(sys->atoms[at].resindex)) result.push_back(at);\n                }\n\n            } else if(node->nodes[0]->token == \"chain\") {\n                // First make a set of chains we need to search\n                std::unordered_set<char> chains;\n                for(auto at: res) chains.insert(sys->atoms[at].chain);\n\n                // Now cycle over all atoms in the starting subset if present (not current subset!!!)\n                if(starting_subset){\n                    for(int at: *starting_subset) // over starting subset\n                        if(chains.count(sys->atoms[at].chain)) result.push_back(at);\n                } else {\n                    for(int at=0;at<Natoms;++at) // over all atoms\n                        if(chains.count(sys->atoms[at].chain)) result.push_back(at);\n                }\n\n            } else if(node->nodes[0]->token == \"mol\") {\n                if(!sys->force_field.ready) throw Pteros_error(\"Can't select by molecule: no topology!\");\n\n                // set of mols we need to include\n                std::unordered_set<int> mols;\n\n                // go over res and add mol is we need it\n                for(auto at: res){\n                    // Cycle over all molecules in the system\n                    for(int j=0; j<sys->force_field.molecules.size(); ++j){ // Over molecules\n                        if(at>=sys->force_field.molecules[j](0) && at<=sys->force_field.molecules[j](1)){\n                            mols.insert(j);\n                            break;\n                        }\n                    }\n                }\n\n                // Now add all chosen molecules\n                for(int m: mols)\n                    for(int at=sys->force_field.molecules[m](0); at<=sys->force_field.molecules[m](1); ++at)\n                        result.push_back(at);\n\n                // Sort and restrict to starting subset (!) if needed\n                sort(result.begin(),result.end());\n                if(starting_subset)\n                    std::set_intersection(result.begin(),result.end(),\n                                          starting_subset->begin(),starting_subset->end(),\n                                          back_inserter(result));\n\n            } // mol\n        } //BY\n    }\n\n    else if(node->name == \"ALL\")\n    {\n        result.resize(Natoms);\n        for(int at=0;at<Natoms;++at) result[at] = at;\n    }\n\n    else if(node->name == \"WITHIN\")\n    {        \n        float cutoff = stof(node->nodes[0]->token);\n        bool periodic = false;\n        bool include_self = true;        \n\n        int eval_ind;\n\n        if(node->nodes.size() == 4){ // Both pbc and self\n            if(node->nodes[1]->name == \"PBC\" && (node->nodes[1]->token == \"pbc\" || node->nodes[1]->token == \"periodic\"))\n                periodic = true;\n\n            if(node->nodes[2]->name == \"PBC\" && (node->nodes[2]->token == \"pbc\" || node->nodes[2]->token == \"periodic\"))\n                periodic = true;\n\n            if(node->nodes[1]->name == \"SELF\" && node->nodes[1]->token == \"noself\")\n                include_self = false;\n\n            if(node->nodes[2]->name == \"SELF\" && node->nodes[2]->token == \"noself\")\n                include_self = false;\n\n            eval_ind = 3;\n\n        } else if(node->nodes.size() == 3){ // Either pbc or self\n            if(node->nodes[1]->name == \"PBC\" && (node->nodes[1]->token == \"pbc\" || node->nodes[1]->token == \"periodic\"))\n                periodic = true;\n\n            if(node->nodes[1]->name == \"SELF\" && node->nodes[1]->token == \"noself\")\n                include_self = false;\n\n            eval_ind = 2;\n\n        } else { // Neither pbc nor self\n            eval_ind = 1;\n        }\n\n        Selection dum1(*sys), dum2(*sys);\n        // Result is returned directly into the index array of selection dum2\n        // thus no additional copying\n        eval_node(node->nodes[eval_ind],dum2._index);\n\n        // Prepare selection dum1\n        if(!current_subset){\n            // We are NOT limited by subspace\n            dum1._index.resize(Natoms);\n            for(int i=0;i<Natoms;++i) dum1._index[i] = i;\n        } else {\n            // We are limited by subspace\n            dum1._index = *current_subset;\n        }\n\n        // Set frame for both selections\n        dum1.set_frame(frame);\n        dum2.set_frame(frame);\n\n        search_within(cutoff,dum1,dum2,result,include_self,periodic);\n    }\n\n    else\n    {\n        throw Pteros_error(\"Unknown node {}!\",node->name);\n    }\n}\n\n//returns a 3-vector\nEigen::Vector3f Selection_parser::get_vector(const std::shared_ptr<MyAst> &node){\n    if(node->name == \"COM\")\n    {\n        bool with_mass = (node->nodes[0]->token == \"com\") ? true : false;\n\n        auto pbc = noPBC;\n        if(node->nodes[1]->name == \"PBC\" && (node->nodes[1]->token == \"pbc\" || node->nodes[1]->token == \"periodic\")) pbc = fullPBC;\n\n        Selection sel(*sys);\n        // We have to ignore current subset here!\n        // Reset subset\n        auto old_subset = current_subset;\n        current_subset = nullptr;\n\n        eval_node(node->nodes.back(), sel._index);\n        sel.set_frame(frame);\n\n        current_subset = old_subset;\n\n        return sel.center(with_mass,pbc);\n    }\n}\n\n// Returns callable, which returns value for numeric node for atom at\nstd::function<float(int)> Selection_parser::get_numeric(const std::shared_ptr<MyAst> &node){\n\n    std::function<float(int)> res;\n\n    // terminals\n    if(node->name == \"INTEGER\"){\n        float val = stol(node->token);\n        res = [val](int at){ return val; };\n    } else if(node->name == \"FLOAT\"){\n        float val = stof(node->token);\n        res = [val](int at){ return val; };\n    } else if(node->name == \"X\"){\n        if(node->nodes.empty())\n            res =[this](int at){ return sys->traj[frame].coord[at](0); };\n        else {\n            float x = get_vector(node->nodes[0])[0];\n            res =[x](int at){ return x; };\n        }\n    } else if(node->name == \"Y\"){\n        if(node->nodes.empty())\n            res =[this](int at){ return sys->traj[frame].coord[at](1); };\n        else {\n            float y = get_vector(node->nodes[0])[1];\n            res =[y](int at){ return y; };\n        }\n    } else if(node->name == \"Z\"){\n        if(node->nodes.empty())\n            res =[this](int at){ return sys->traj[frame].coord[at](2); };\n        else {\n            float z = get_vector(node->nodes[0])[2];\n            res =[z](int at){ return z; };\n        }\n    } else if(node->name == \"BETA\"){\n        res = [this](int at){ return sys->atoms[at].beta; };\n    } else if(node->name == \"OCC\"){\n        res = [this](int at){ return sys->atoms[at].occupancy; };\n    } else if(node->name == \"INDEX\"){\n        res = [](int at){ return at; };\n    } else if(node->name == \"RESINDEX\"){\n        res = [this](int at){ return sys->atoms[at].resindex; };\n    } else if(node->name == \"RESID\"){\n        res = [this](int at){ return sys->atoms[at].resid; };\n    } else if(node->name == \"MASS\"){\n        res = [this](int at){ return sys->atoms[at].mass; };\n    } else if(node->name == \"CHARGE\"){\n        res = [this](int at){ return sys->atoms[at].charge; };\n    // Compounds\n    } else if(node->name == \"UNARY_MINUS\"){\n        auto func = get_numeric(node->nodes[0]);\n        res = [func](int at){ return -func(at); };\n\n    } else if(node->name == \"NUM_EXPR\" || node->name == \"NUM_TERM\" || node->name == \"NUM_POWER\") {\n\n        int N = node->nodes.size();\n\n        vector<std::function<float(int)>> operands((N-1)/2+1);\n        vector<std::function<float(float,float)>> operators((N-1)/2);\n\n        for(int i=0;i<operands.size();++i){\n            operands[i] = get_numeric(node->nodes[i*2]);\n        }\n\n        for(int i=0;i<operators.size();++i){\n            auto op = node->nodes[i*2+1]->token;\n            if     (op==\"+\") {\n                operators[i] = [](float a,float b){ return a+b; };\n            } else if(op==\"-\") {\n                operators[i] = [](float a,float b){ return a-b; };\n            } else if(op==\"*\") {\n                operators[i] = [](float a,float b){ return a*b; };\n            } else if(op==\"/\") {\n                operators[i] = [](float a,float b){\n                    if(b==0.0) throw Pteros_error(\"Division by zero in selection!\");\n                    return a/b;\n                };\n            } else if(op==\"^\" || op==\"**\") {\n                operators[i] = [](float a,float b){ return std::pow(a,b); };\n            }\n        }\n\n        res = [operands,operators](int at){\n            float result = operands[0](at);\n            for(int i=0;i<operators.size();++i) result = operators[i](result,operands[i+1](at));\n            return result;\n        };\n\n    } else if(node->name == \"POINT\") {\n        Eigen::Vector3f p;\n\n        int N = node->nodes.size();\n        int offset = 0;\n\n        bool pbc = false;\n        if(node->nodes[0]->token == \"pbc\" || node->nodes[0]->token == \"periodic\"){\n            pbc = true;\n            offset = 1;\n        }\n\n        if(N==1 || N==2){ // com and possibly pbc\n            p = get_vector(node->nodes[0+offset]);\n        } else { // 3 floats and possibly pbc\n            p(0) = get_numeric(node->nodes[0+offset])(0);\n            p(1) = get_numeric(node->nodes[1+offset])(0);\n            p(2) = get_numeric(node->nodes[2+offset])(0);\n        }\n\n        // Return distance\n        if(pbc){\n            res = [this,p](int at){\n                return sys->box(frame).distance(p, sys->traj[frame].coord[at]);\n            };\n        } else {\n            res = [this,p](int at){\n                return (p - sys->traj[frame].coord[at]).norm();\n            };\n        }\n\n    } else if(node->name == \"VECTOR\" || node->name == \"PLANE\") {\n        Eigen::Vector3f p,dir;\n\n        int N = node->nodes.size();\n        int offset = 0;\n\n        bool pbc = false;\n        if(node->nodes[0]->token == \"pbc\" || node->nodes[0]->token == \"periodic\"){\n            pbc = true;\n            offset = 1;\n        }\n\n        if(N==4 || N==5){ // com + 3 floats\n            p = get_vector(node->nodes[0+offset]);\n            dir(0) = get_numeric(node->nodes[1+offset])(0);\n            dir(1) = get_numeric(node->nodes[2+offset])(0);\n            dir(2) = get_numeric(node->nodes[3+offset])(0);\n        } if(N==6){ // 6 floats\n            p(0) = get_numeric(node->nodes[0+offset])(0);\n            p(1) = get_numeric(node->nodes[1+offset])(0);\n            p(2) = get_numeric(node->nodes[2+offset])(0);\n            dir(0) = get_numeric(node->nodes[3+offset])(0);\n            dir(1) = get_numeric(node->nodes[4+offset])(0);\n            dir(2) = get_numeric(node->nodes[5+offset])(0);\n        }\n\n        if(node->name == \"VECTOR\"){\n            // For vector\n            res = [this,p,dir,pbc](int at){\n                Eigen::Vector3f atom = sys->traj[frame].coord[at];\n                // Get vector from p to current atom\n                Eigen::Vector3f v = atom - p;\n                // Project v onto dir\n                v = (v.dot(dir)/dir.squaredNorm())*dir;\n                // Get the end point of projection\n                v += p;\n                // Return distance between atom and v\n                if(pbc){\n                    return sys->box(frame).distance(atom, v);\n                } else {\n                    return (atom-v).norm();\n                }\n            };\n        } else {\n            // For plane\n            res = [this,p,dir,pbc](int at){\n                Eigen::Vector3f atom = sys->traj[frame].coord[at];\n                // Get vector from p to current atom\n                Eigen::Vector3f v = atom - p;\n                // Project v onto dir\n                v = (v.dot(dir)/dir.squaredNorm())*dir;\n                // Get closest point on a plane to atom\n                v = atom-v;\n                // Return distance between atom and v\n                if(pbc){\n                    return sys->box(frame).distance(atom, v);\n                } else {\n                    return (atom-v).norm();\n                }\n            };\n        }\n\n    }  else {\n        throw Pteros_error(\"Wrong numeric node!\");\n    }\n\n    return res;    \n}\n\n\n", "meta": {"hexsha": "07aadd457baca5c34167bc058daf675d57b8a3c9", "size": 32627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/selection_parser/selection_parser.cpp", "max_stars_repo_name": "MDSYN2019/pteros", "max_stars_repo_head_hexsha": "d9dd5017dcf4690746f9dd6569955ba282740542", "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/selection_parser/selection_parser.cpp", "max_issues_repo_name": "MDSYN2019/pteros", "max_issues_repo_head_hexsha": "d9dd5017dcf4690746f9dd6569955ba282740542", "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/selection_parser/selection_parser.cpp", "max_forks_repo_name": "MDSYN2019/pteros", "max_forks_repo_head_hexsha": "d9dd5017dcf4690746f9dd6569955ba282740542", "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": 37.3734249714, "max_line_length": 134, "alphanum_fraction": 0.4906978883, "num_tokens": 8029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.18573736405497407}}
{"text": "#include \"script_visitor.hpp\"\n\n#include <program_ast.hpp>\n#include <intvar.hpp>\n#include <realvar.hpp>\n#include <strvar.hpp>\n#include <listvar.hpp>\n#include <reply.hpp>\n#include <op_package.hpp>\n#include <compiler.hpp>\n\n#include <iostream>\n#include <boost/iterator/indirect_iterator.hpp>\n\nusing namespace Moove;\n\ntemplate<class T, class VariantType>\nstruct FixedCast {\n   T operator () (const Variant& var)const\n   { return dynamic_cast<const VariantType&>(var).value(); }\n};\n\ntemplate<class T, class VariantType1, class VariantType2>\nstruct BinaryCast {\n   T operator () (const Variant& var)const\n   {\n      if(const VariantType1* v1 = dynamic_cast<const VariantType1*>(&var))\n\t return v1->value();\n      else if(const VariantType2* v2 = dynamic_cast<const VariantType2*>(&var))\n\t return v2->value();\n\n      throw std::bad_cast();\n      return T();\n   }\n};\n   \ntemplate<class ResultVariant, class Cast>\nclass ScriptOperatorPackage : public OperatorPackage {\nprivate:\n   Cast m_cast;\n\n   Reply doBinaryMathOp(Opcode op, const Variant& left, const Variant& right)const\n   {\n      boost::shared_ptr<ResultVariant> resultVar(dynamic_cast<ResultVariant*>(ResultVariant::classFactory().create()));\n      assert(resultVar.get() != 0);\n\n      switch(op) {\n\t case OP_ADD:\n\t    resultVar->setValue(m_cast(left) + m_cast(right));\n\t    break;\n\n\t case OP_SUB:\n\t    resultVar->setValue(m_cast(left) - m_cast(right));\n\t    break;\n\n\t case OP_MUL:\n\t    resultVar->setValue(m_cast(left) * m_cast(right));\n\t    break;\n\n\t case OP_DIV:\n\t    resultVar->setValue(m_cast(left) / m_cast(right));\n\t    break;\n\n\t default:\n\t    return OperatorPackage::doBinaryOp(op, left, right);\n      }\n\n      return Reply(Reply::NORMAL, resultVar);\n   }\n\n   Reply doBinaryCompareOp(Opcode op, const Variant& left, const Variant& right)const\n   {\n      boost::shared_ptr<DefaultIntVar> resultVar(DefaultIntVar::classFactory().create());\n      assert(resultVar.get() != 0);\n      \n      switch(op) {\n\t case OP_LT:\n\t    resultVar->setValue(m_cast(left) < m_cast(right));\n\t    break;\n\n\t case OP_LE:\n\t    resultVar->setValue(m_cast(left) <= m_cast(right));\n\t    break;\n\n\t case OP_EQ:\n\t    resultVar->setValue(m_cast(left) == m_cast(right));\n\t    break;\n\n\t case OP_NE:\n\t    resultVar->setValue(m_cast(left) != m_cast(right));\n\t    break;\n\n\t case OP_GE:\n\t    resultVar->setValue(m_cast(left) >= m_cast(right));\n\t    break;\n\n\t case OP_GT:\n\t    resultVar->setValue(m_cast(left) > m_cast(right));\n\t    break;\n\n\t default:\n\t    return OperatorPackage::doBinaryOp(op, left, right);\n      }\n\n      return Reply(Reply::NORMAL, resultVar);\n   }\n\npublic:\n   Reply doBinaryOp(Opcode op, const Variant& left, const Variant& right)const\n   {\n      switch(op) {\n\t case OP_ADD:\n\t case OP_SUB:\n\t case OP_MUL:\n\t case OP_DIV:\n\t    return doBinaryMathOp(op, left, right);\n\n\t case OP_LT:\n\t case OP_LE:\n\t case OP_EQ:\n\t case OP_NE:\n\t case OP_GE:\n\t case OP_GT:\n\t    return doBinaryCompareOp(op, left, right);\n      }\n\n      return OperatorPackage::doBinaryOp(op, left, right);\n   }\n};\n\ntemplate<>\nReply \nScriptOperatorPackage<DefaultStrVar, \n\t\t      FixedCast<const std::string&, StrVar> >::doBinaryMathOp(Opcode op, const Variant& left, const Variant& right)const\n{\n   if(op == OP_ADD) {\n      boost::shared_ptr<DefaultStrVar> resultVar(DefaultStrVar::classFactory().create());\n      assert(resultVar.get() != 0);\n\n      resultVar->setValue(m_cast(left) + m_cast(right));\n      return Reply(Reply::NORMAL, resultVar);\n   }\n\n   return OperatorPackage::doBinaryOp(op, left, right);\n}\n      \ntypedef ScriptOperatorPackage<DefaultIntVar, FixedCast<int, IntVar> > IntOpPkg;\ntypedef ScriptOperatorPackage<DefaultRealVar, FixedCast<double, RealVar> > RealOpPkg;\ntypedef ScriptOperatorPackage<DefaultRealVar, BinaryCast<double, IntVar, RealVar> > IntRealOpPkg;\ntypedef ScriptOperatorPackage<DefaultStrVar, FixedCast<const std::string&, StrVar> > StrOpPkg;\n\nnamespace {\n\nIntOpPkg\tpkgInt;\nRealOpPkg\tpkgReal;\nIntRealOpPkg\tpkgIntReal;\nStrOpPkg\tpkgStr;\n\n}\n\nvoid ScriptVisitor::visitStmts(const Stmt::Block& block)\n{\n   Stmt::Block::const_iterator end = block.end();\n   for(Stmt::Block::const_iterator stmt = block.begin(); stmt != end; ++stmt)\n      (*stmt)->accept(*this);\n}\n\nvoid ScriptVisitor::doBinaryOp(Opcode op, const Expr::BinaryExpr& binExpr)\n{\n   binExpr.left().accept(*this);\n   binExpr.right().accept(*this);\n   m_vm.doBinaryOp(op);\n}\n\nvoid ScriptVisitor::assignTo(const Expr::Expr& expr)\n{\n   if(const Expr::Variable* var = dynamic_cast<const Expr::Variable*>(&expr))\n      m_vars[var->id()] = m_vm.stackTop();\n   else \n      throw InvalidAssignment(\"Invalid Assignment\");\n}\n\nvoid ScriptVisitor::acceptArgs(const Expr::ArgList& args)\n{\n   ListVar::Container contents;\n\n   Expr::ArgList::const_iterator end = args.end();\n   for(Expr::ArgList::const_iterator elem = args.begin(); elem != end; ++elem) {\n      m_spliceFlag = false;\n      (*elem)->accept(*this);\n\n      if(m_spliceFlag) {\n\t boost::shared_ptr<ListVar> splice = boost::dynamic_pointer_cast<ListVar>(m_vm.popOffStack());\n\t assert(splice);\n\t contents.insert(contents.end(), splice->contents().begin(), splice->contents().end());\n      } else {\n\t contents.push_back(m_vm.popOffStack());\n      }\n   }\n\n   m_spliceFlag = false;\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultListVar::classFactory().createList(contents)));\n}\n\nbool ScriptVisitor::runIf(const Expr::Expr& test, const Stmt::Block& stmts)\n{\n   test.accept(*this);\n   boost::shared_ptr<Variant> result = m_vm.popOffStack();\n\n   bool shouldRun = false;\n\n   if(boost::shared_ptr<IntVar> intVar = boost::dynamic_pointer_cast<IntVar>(result))\n      shouldRun = intVar->value() != 0;\n   else if(boost::shared_ptr<RealVar> realVar = boost::dynamic_pointer_cast<RealVar>(result))\n      shouldRun = realVar->value() != 0;\n   else if(boost::shared_ptr<StrVar> strVar = boost::dynamic_pointer_cast<StrVar>(result))\n      shouldRun = !strVar->value().empty();\n\n   if(shouldRun)\n      visitStmts(stmts);\n\n   return shouldRun;\n}\n\nScriptVisitor::ScriptVisitor() : m_spliceFlag(false), m_vm(m_opMap)\n{\n   const TypeRegistry::TypeEntry& intType = m_typeReg.registerType(\"int\", DefaultIntVar::classFactory());\n   const TypeRegistry::TypeEntry& realType = m_typeReg.registerType(\"real\", DefaultRealVar::classFactory());\n   const TypeRegistry::TypeEntry& strType = m_typeReg.registerType(\"str\", DefaultStrVar::classFactory());\n\n   m_opMap.registerUnary(intType, pkgInt);\n   m_opMap.registerUnary(realType, pkgReal);\n   m_opMap.registerUnary(strType, pkgStr);\n   \n   m_opMap.registerBinary(intType, intType, pkgInt);\n   m_opMap.registerBinary(realType, realType, pkgReal);\n   m_opMap.registerBinary(intType, realType, pkgIntReal);\n   m_opMap.registerBinary(realType, intType, pkgIntReal);\n   m_opMap.registerBinary(strType, strType, pkgStr);\n}\n\nvoid ScriptVisitor::visit(const Program& program)\n{\n   m_vars.clear();\n   m_vm.reset();\n   m_program = &program;\n\n   visitStmts(program.stmts());\n}\n      \nvoid ScriptVisitor::visit(const Expr::Integer& intExpr)\n{\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultIntVar::classFactory().createInt(intExpr.value())));\n}\n\nvoid ScriptVisitor::visit(const Expr::Real& realExpr)\n{\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultRealVar::classFactory().createReal(realExpr.value())));\n}\n\nvoid ScriptVisitor::visit(const Expr::Str& strExpr)\n{\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultStrVar::classFactory().createStr(strExpr.str())));\n}\n\nvoid ScriptVisitor::visit(const Expr::List& listExpr)\n{\n   acceptArgs(listExpr.elements());\n}\n\nvoid ScriptVisitor::visit(const Expr::Variable& varExpr)\n{\n   VariableTable::const_iterator var = m_vars.find(varExpr.id());\n   if(var == m_vars.end())\n      throw UndefinedVariable(\"Undefined Variable\");\n  \n   m_vm.pushOnStack(var->second);\n}\n\nvoid ScriptVisitor::visit(const Expr::Splice& spliceExpr)\n{\n   spliceExpr.operand().accept(*this);\n   m_spliceFlag = true;\n}\n   \nvoid ScriptVisitor::visit(const Expr::PreInc& preIncExpr)\n{\n   preIncExpr.operand().accept(*this);\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultIntVar::classFactory().createInt(1)));\n   m_vm.doBinaryOp(OP_ADD);\n   assignTo(preIncExpr.operand());\n}\n\nvoid ScriptVisitor::visit(const Expr::PreDec& preDecExpr)\n{\n   preDecExpr.operand().accept(*this);\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultIntVar::classFactory().createInt(-1)));\n   m_vm.doBinaryOp(OP_ADD);\n   assignTo(preDecExpr.operand());\n}\n\nvoid ScriptVisitor::visit(const Expr::PostInc& postIncExpr)\n{\n   postIncExpr.operand().accept(*this);\n   m_vm.pushOnStack(m_vm.stackTop());\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultIntVar::classFactory().createInt(1)));\n   m_vm.doBinaryOp(OP_ADD);\n   assignTo(postIncExpr.operand());\n   m_vm.popOffStack();\n}\n\nvoid ScriptVisitor::visit(const Expr::PostDec& postDecExpr)\n{\n   postDecExpr.operand().accept(*this);\n   m_vm.pushOnStack(m_vm.stackTop());\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultIntVar::classFactory().createInt(-1)));\n   m_vm.doBinaryOp(OP_ADD);\n   assignTo(postDecExpr.operand());\n   m_vm.popOffStack();\n}\n\nvoid ScriptVisitor::visit(const Expr::Assign& assignExpr)\n{\n   assignExpr.right().accept(*this);\n   assignTo(assignExpr.left());\n}\n\nvoid ScriptVisitor::visit(const Expr::AddEqual& addEqExpr)\n{\n   doBinaryOp(OP_ADD, addEqExpr);\n   assignTo(addEqExpr.left());\n}\n\nvoid ScriptVisitor::visit(const Expr::SubEqual& subEqExpr)\n{\n   doBinaryOp(OP_SUB, subEqExpr);\n   assignTo(subEqExpr.left());\n}\n\nvoid ScriptVisitor::visit(const Expr::MulEqual& mulEqExpr)\n{\n   doBinaryOp(OP_MUL, mulEqExpr);\n   assignTo(mulEqExpr.left());\n}\n\nvoid ScriptVisitor::visit(const Expr::DivEqual& divEqExpr)\n{\n   doBinaryOp(OP_DIV, divEqExpr);\n   assignTo(divEqExpr.left());\n}\n\nvoid ScriptVisitor::visit(const Expr::Conditional& condExpr)\n{\n   condExpr.test().accept(*this);\n   boost::shared_ptr<IntVar> result = boost::dynamic_pointer_cast<IntVar>(m_vm.popOffStack());\n   assert(result);\n\n   if(result->value())\n      condExpr.trueExpr().accept(*this);\n   else\n      condExpr.falseExpr().accept(*this);\n}\n\nvoid ScriptVisitor::visit(const Expr::Index& expr)\n{\n   expr.expr().accept(*this);\n   expr.index().accept(*this);\n\n   boost::shared_ptr<IntVar> index = boost::dynamic_pointer_cast<IntVar>(m_vm.popOffStack());\n   boost::shared_ptr<ListVar> value = boost::dynamic_pointer_cast<ListVar>(m_vm.popOffStack());\n   assert(index && value);\n\n   if(index->value() >= 1 && index->value() <= value->contents().size())\n      m_vm.pushOnStack(value->contents()[index->value() - 1]);\n   else\n      throw OutOfRange(\"Index value out of range\");\n}\n\nvoid ScriptVisitor::printVariant(const Variant& var)\n{\n   if(const IntVar* intValue = dynamic_cast<const IntVar*>(&var)) {\n      std::cout << intValue->value();\n   } else if(const RealVar* realValue = dynamic_cast<const RealVar*>(&var)) {\n      std::cout << realValue->value();\n   } else if(const StrVar* strValue = dynamic_cast<const StrVar*>(&var)) {\n      std::cout << strValue->value();\n   } else if(const ListVar* listValue = dynamic_cast<const ListVar*>(&var)) {\n      std::cout << \"{\";\n      \n      ListVar::Container::const_iterator end = listValue->contents().end();\n      for(ListVar::Container::const_iterator elem = listValue->contents().begin(); elem != end; ++elem) {\n\t printVariant(**elem);\n\t \n\t if(elem + 1 != end)\n\t    std::cout << \", \";\n      }\n\n      std::cout << \"}\";\n   } else {\n      std::cout << \"(unknown type: \" << var.factory().regEntry().name() << \")\";\n   }\n}\n\nvoid ScriptVisitor::visit(const Expr::Builtin& builtinExpr)\n{\n   typedef boost::indirect_iterator<ListVar::Container::const_iterator> ArgIterator;\n\n   boost::shared_ptr<Variant> resultVar;\n   boost::shared_ptr<ListVar> argsVar;\n\n   acceptArgs(builtinExpr.args());\n   if(!(argsVar = boost::dynamic_pointer_cast<ListVar>(m_vm.popOffStack())))\n      throw InvalidType(\"Invalid Type\");\n\n   if(builtinExpr.name() == \"print\") {\n      std::for_each(ArgIterator(argsVar->contents().begin()), ArgIterator(argsVar->contents().end()), &printVariant);\n      std::cout << std::endl;\n   } else if(builtinExpr.name() == \"input\") {\n      assert(argsVar->contents().size() == 1);\n\n      boost::shared_ptr<StrVar> inputType = boost::dynamic_pointer_cast<StrVar>(argsVar->contents()[0]);\n      assert(inputType);\n\n      std::cout << \"Enter value: \";\n\n      if(inputType->value() == \"int\") {\n\t int value;\n\t \n\t assert(std::cin >> value);\n\t std::cin.ignore();\n\t resultVar.reset(DefaultIntVar::classFactory().createInt(value));\n      } else if(inputType->value() == \"real\") {\n\t double value;\n\n\t assert(std::cin >> value);\n\t std::cin.ignore();\n\t resultVar.reset(DefaultRealVar::classFactory().createReal(value));\n      } else if(inputType->value() == \"str\") {\n\t std::string value;\n\n\t assert(getline(std::cin, value));\n\t resultVar.reset(DefaultStrVar::classFactory().createStr(value));\n      } else {\n\t throw InvalidType(\"Invalid Type\");\n      }\n   }\n\n   // this is an expression, so it needs a return value\n   m_vm.pushOnStack(resultVar ? resultVar : boost::shared_ptr<Variant>(DefaultIntVar::classFactory().createInt(0)));\n}\n\nvoid ScriptVisitor::visit(const Expr::Length&)\n{\n   boost::shared_ptr<ListVar> listValue = boost::dynamic_pointer_cast<ListVar>(m_vm.stackTop());\n   m_vm.pushOnStack(boost::shared_ptr<Variant>(DefaultIntVar::classFactory().createInt(listValue->contents().size())));\n}\n\nvoid ScriptVisitor::visit(const Stmt::If& ifStmt)\n{\n   if(!runIf(ifStmt.test(), ifStmt.body())) {\n      Stmt::If::ElseList::const_iterator clause, end = ifStmt.elseList().end();\n      for(clause = ifStmt.elseList().begin(); clause != end; ++clause) {\n\t m_ranIf = false;\n\t (*clause)->accept(*this);\n\n\t if(m_ranIf)\n\t    break;\n      }\n   }\n}\n\nvoid ScriptVisitor::visit(const Stmt::If::Else& elseClause)\n{\n   if(elseClause.hasTest())\t\t// elseif\n      m_ranIf = runIf(elseClause.test(), elseClause.body());\n   else {\t\t\t\t// else\n      visitStmts(elseClause.body());\n      m_ranIf = true;\n   }\n}\n   \nvoid ScriptVisitor::visit(const Stmt::While& whileStmt)\n{\n   for(;;) {\n      whileStmt.test().accept(*this);\n      boost::shared_ptr<IntVar> testResult = boost::dynamic_pointer_cast<IntVar>(m_vm.popOffStack());\n      assert(testResult.get() != 0);\n\n      if(!testResult->value())\n\t break;\n\n      visitStmts(whileStmt.body());\n   }\n}\n\t\t \nvoid ScriptVisitor::visit(const Stmt::ForRange& forRangeStmt)\n{\n   forRangeStmt.start().accept(*this);\n   boost::shared_ptr<Variant> indexVar = m_vm.stackTop();\n\n   forRangeStmt.end().accept(*this);\n   boost::shared_ptr<Variant> endVar = m_vm.stackTop();\n\n   for(;;) {\n      m_vm.doBinaryOp(OP_LE);\n      boost::shared_ptr<IntVar> compResult = boost::dynamic_pointer_cast<IntVar>(m_vm.popOffStack());\n      assert(compResult);\n      \n      if(compResult->value()) {\n\t m_vars[forRangeStmt.id()] = indexVar;\n\t visitStmts(forRangeStmt.body());\n\t \n\t m_vm.pushOnStack(indexVar);\n\t m_vm.pushOnStack(boost::shared_ptr<DefaultIntVar>(DefaultIntVar::classFactory().createInt(1)));\n\t m_vm.doBinaryOp(OP_ADD);\n\t indexVar = m_vm.stackTop();\n\t m_vm.pushOnStack(endVar);\n      } else {\n\t break;\n      }\n   }\n}\n\nvoid ScriptVisitor::visit(const Stmt::Expr& exprStmt)\n{\n   exprStmt.expr().accept(*this);\n   m_vm.popOffStack();\n}\n\n", "meta": {"hexsha": "fd6ed60ddaf84c52edd60c63cd71893bb54f27d0", "size": 15181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moosh/src/script_visitor.cpp", "max_stars_repo_name": "mujido/moove", "max_stars_repo_head_hexsha": "380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b", "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": "moosh/src/script_visitor.cpp", "max_issues_repo_name": "mujido/moove", "max_issues_repo_head_hexsha": "380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b", "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": "moosh/src/script_visitor.cpp", "max_forks_repo_name": "mujido/moove", "max_forks_repo_head_hexsha": "380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b", "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.6433962264, "max_line_length": 122, "alphanum_fraction": 0.6871088861, "num_tokens": 3961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18573736240821992}}
{"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//\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_R1CS_GG_PPZKSNARK_IPP2_PROVE_HPP\n#define CRYPTO3_R1CS_GG_PPZKSNARK_IPP2_PROVE_HPP\n\n#include <algorithm>\n#include <vector>\n#include <tuple>\n#include <string>\n\n#include <boost/iterator/zip_iterator.hpp>\n\n#include <nil/crypto3/detail/pack_numeric.hpp>\n\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n#include <nil/crypto3/hash/sha2.hpp>\n\n#include <nil/crypto3/math/polynomial/basic_operations.hpp>\n\n#include <nil/crypto3/algebra/multiexp/multiexp.hpp>\n#include <nil/crypto3/algebra/multiexp/policies.hpp>\n#include <nil/crypto3/algebra/algorithms/pair.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/detail/basic_policy.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/proof.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/srs.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/transcript.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/proof.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace zk {\n            namespace snark {\n                /// Returns the vector used for the linear combination fo the inner pairing product\n                /// between A and B for the Groth16 aggregation: A^r * B. It is required as it\n                /// is not enough to simply prove the ipp of A*B, we need a random linear\n                /// combination of those.\n                template<typename FieldType>\n                std::vector<typename FieldType::value_type>\n                    structured_scalar_power(std::size_t num, const typename FieldType::value_type &s) {\n                    std::vector<typename FieldType::value_type> powers = {FieldType::value_type::one()};\n                    for (int i = 1; i < num; i++) {\n                        powers.emplace_back(powers.back() * s);\n                    }\n                    return powers;\n                }\n\n                /// compress is similar to commit::{V,W}KEY::compress: it modifies the `vec`\n                /// vector by setting the value at index $i:0 -> split$  $vec[i] = vec[i] +\n                /// vec[i+split]^scaler$. The `vec` vector is half of its size after this call.\n                template<typename CurveType, typename InputRange,\n                         typename ValueType = typename std::iterator_traits<typename InputRange::iterator>::value_type>\n                typename std::enable_if<\n                    std::is_same<typename CurveType::template g1_type<>::value_type, ValueType>::value ||\n                    std::is_same<typename CurveType::template g2_type<>::value_type, ValueType>::value ||\n                    std::is_same<typename CurveType::scalar_field_type::value_type, ValueType>::value>::type\n                    compress(InputRange &vec, std::size_t split,\n                             const typename CurveType::scalar_field_type::value_type &scalar) {\n                    std::for_each(boost::make_zip_iterator(boost::make_tuple(vec.begin(), vec.begin() + split)),\n                                  boost::make_zip_iterator(boost::make_tuple(vec.begin() + split, vec.end())),\n                                  [&](const boost::tuple<ValueType &, ValueType &> &t) {\n                                      t.template get<0>() = t.template get<0>() + t.template get<1>() * scalar;\n                                  });\n                    vec.resize(split);\n                }\n\n                /// It returns the evaluation of the polynomial $\\prod (1 + x_{l-j}(rX)^{2j}$ at\n                /// the point z, where transcript contains the reversed order of all challenges (the x).\n                /// The challenges must be in reversed order for the correct evaluation of the\n                /// polynomial in O(logn)\n                template<typename FieldType, typename InputFieldValueIterator>\n                typename std::enable_if<std::is_same<typename std::iterator_traits<InputFieldValueIterator>::value_type,\n                                                     typename FieldType::value_type>::value,\n                                        typename FieldType::value_type>::type\n                    polynomial_evaluation_product_form_from_transcript(InputFieldValueIterator transcript_first,\n                                                                       InputFieldValueIterator transcript_last,\n                                                                       const typename FieldType::value_type &z,\n                                                                       const typename FieldType::value_type &r_shift) {\n                    // this is the term (rz) that will get squared at each step to produce the\n                    // $(rz)^{2j}$ of the formula\n                    typename FieldType::value_type power_zr = z;\n                    power_zr = power_zr * r_shift;\n\n                    // 0 iteration\n                    InputFieldValueIterator transcript_iter = transcript_first;\n                    typename FieldType::value_type res = FieldType::value_type::one() + (*transcript_iter * power_zr);\n                    power_zr = power_zr * power_zr;\n                    ++transcript_iter;\n\n                    // the rest\n                    while (transcript_iter != transcript_last) {\n                        res = res * (FieldType::value_type::one() + (*transcript_iter * power_zr));\n                        power_zr = power_zr * power_zr;\n                        ++transcript_iter;\n                    }\n\n                    return res;\n                }\n\n                // Compute the coefficients of the polynomial $\\prod_{j=0}^{l-1} (1 + x_{l-j}(rX)^{2j})$\n                // It does this in logarithmic time directly; here is an example with 2\n                // challenges:\n                //\n                //     We wish to compute $(1+x_1ra)(1+x_0(ra)^2) = 1 +  x_1ra + x_0(ra)^2 + x_0x_1(ra)^3$\n                //     Algorithm: $c_{-1} = [1]$; $c_j = c_{i-1} \\| (x_{l-j} * c_{i-1})$; $r = r*r$\n                //     $c_0 = c_{-1} \\| (x_1 * r * c_{-1}) = [1] \\| [rx_1] = [1, rx_1]$, $r = r^2$\n                //     $c_1 = c_0 \\| (x_0 * r^2c_0) = [1, rx_1] \\| [x_0r^2, x_0x_1r^3] = [1, x_1r, x_0r^2, x_0x_1r^3]$\n                //     which is equivalent to $f(a) = 1 + x_1ra + x_0(ra)^2 + x_0x_1r^2a^3$\n                //\n                // This method expects the coefficients in reverse order so transcript[i] =\n                // x_{l-j}.\n                template<typename FieldType, typename InputFieldValueIterator>\n                typename std::enable_if<std::is_same<typename std::iterator_traits<InputFieldValueIterator>::value_type,\n                                                     typename FieldType::value_type>::value,\n                                        std::vector<typename FieldType::value_type>>::type\n                    polynomial_coefficients_from_transcript(InputFieldValueIterator transcript_first,\n                                                            InputFieldValueIterator transcript_last,\n                                                            const typename FieldType::value_type &r_shift) {\n                    std::vector<typename FieldType::value_type> coefficients = {FieldType::value_type::one()};\n                    typename FieldType::value_type power_2_r = r_shift;\n\n                    InputFieldValueIterator transcript_iter = transcript_first;\n                    while (transcript_iter != transcript_last) {\n                        std::size_t n = coefficients.size();\n                        for (int j = 0; j < n; j++) {\n                            coefficients.emplace_back(coefficients[j] * (*transcript_iter * power_2_r));\n                        }\n                        power_2_r = power_2_r * power_2_r;\n\n                        ++transcript_iter;\n                    }\n\n                    return coefficients;\n                }\n\n                /// Returns the KZG opening proof for the given commitment key. Specifically, it\n                /// returns $g^{f(alpha) - f(z) / (alpha - z)}$ for $a$ and $b$.\n                template<typename GroupType, typename InputGroupIterator, typename InputScalarRange>\n                typename std::enable_if<\n                    std::is_same<typename GroupType::value_type,\n                                 typename std::iterator_traits<InputGroupIterator>::value_type>::value &&\n                        std::is_same<\n                            typename GroupType::curve_type::scalar_field_type::value_type,\n                            typename std::iterator_traits<typename InputScalarRange::iterator>::value_type>::value,\n                    kzg_opening<GroupType>>::type\n                    prove_commitment_key_kzg_opening(\n                        InputGroupIterator srs_powers_alpha_first, InputGroupIterator srs_powers_alpha_last,\n                        InputGroupIterator srs_powers_beta_first, InputGroupIterator srs_powers_beta_last,\n                        const InputScalarRange &poly,\n                        const typename GroupType::curve_type::scalar_field_type::value_type &eval_poly,\n                        const typename GroupType::curve_type::scalar_field_type::value_type &kzg_challenge) {\n                    typename GroupType::curve_type::scalar_field_type::value_type neg_kzg_challenge = -kzg_challenge;\n\n                    BOOST_ASSERT(poly.size() == std::distance(srs_powers_alpha_first, srs_powers_alpha_last));\n                    BOOST_ASSERT(poly.size() == std::distance(srs_powers_beta_first, srs_powers_beta_last));\n\n                    // f_v(X) - f_v(z) / (X - z)\n                    std::vector<typename GroupType::curve_type::scalar_field_type::value_type> f_vX_sub_f_vZ;\n                    math::_polynomial_subtraction(f_vX_sub_f_vZ,\n                                                  poly,\n                                                  {{\n                                                      eval_poly,\n                                                  }});\n                    std::vector<typename GroupType::curve_type::scalar_field_type::value_type> quotient_polynomial,\n                        remainder_polynomial;\n                    math::_polynomial_division<typename GroupType::curve_type::scalar_field_type>(\n                        quotient_polynomial, remainder_polynomial, f_vX_sub_f_vZ,\n                        {{\n                            neg_kzg_challenge,\n                            GroupType::curve_type::scalar_field_type::value_type::one(),\n                        }});\n\n                    if (quotient_polynomial.size() < poly.size()) {\n                        quotient_polynomial.resize(poly.size(),\n                                                   GroupType::curve_type::scalar_field_type::value_type::zero());\n                    }\n                    BOOST_ASSERT(quotient_polynomial.size() == poly.size());\n\n                    // we do one proof over h^a and one proof over h^b (or g^a and g^b depending\n                    // on the curve we are on). that's the extra cost of the commitment scheme\n                    // used which is compatible with Groth16 CRS insteaf of the original paper\n                    // of Bunz'19\n                    return kzg_opening<GroupType> {algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(\n                                                       srs_powers_alpha_first, srs_powers_alpha_last,\n                                                       quotient_polynomial.begin(), quotient_polynomial.end(), 1),\n                                                   algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(\n                                                       srs_powers_beta_first, srs_powers_beta_last,\n                                                       quotient_polynomial.begin(), quotient_polynomial.end(), 1)};\n                }\n\n                template<typename CurveType, typename InputG2Iterator, typename InputScalarIterator>\n                typename std::enable_if<\n                    std::is_same<typename CurveType::template g2_type<>::value_type,\n                                 typename std::iterator_traits<InputG2Iterator>::value_type>::value &&\n                        std::is_same<typename CurveType::scalar_field_type::value_type,\n                                     typename std::iterator_traits<InputScalarIterator>::value_type>::value,\n                    kzg_opening<typename CurveType::template g2_type<>>>::type\n                    prove_commitment_v(InputG2Iterator srs_powers_alpha_first, InputG2Iterator srs_powers_alpha_last,\n                                       InputG2Iterator srs_powers_beta_first, InputG2Iterator srs_powers_beta_last,\n                                       InputScalarIterator transcript_first, InputScalarIterator transcript_last,\n                                       const typename CurveType::scalar_field_type::value_type &kzg_challenge) {\n                    std::vector<typename CurveType::scalar_field_type::value_type> vkey_poly =\n                        polynomial_coefficients_from_transcript<typename CurveType::scalar_field_type>(\n                            transcript_first, transcript_last, CurveType::scalar_field_type::value_type::one());\n                    math::_condense(vkey_poly);\n                    BOOST_ASSERT(!math::_is_zero(vkey_poly));\n\n                    typename CurveType::scalar_field_type::value_type vkey_poly_z =\n                        polynomial_evaluation_product_form_from_transcript<typename CurveType::scalar_field_type>(\n                            transcript_first, transcript_last, kzg_challenge,\n                            CurveType::scalar_field_type::value_type::one());\n\n                    return prove_commitment_key_kzg_opening<typename CurveType::template g2_type<>>(\n                        srs_powers_alpha_first, srs_powers_alpha_last, srs_powers_beta_first, srs_powers_beta_last,\n                        vkey_poly, vkey_poly_z, kzg_challenge);\n                }\n\n                template<typename CurveType, typename InputG1Iterator, typename InputScalarIterator>\n                typename std::enable_if<\n                    std::is_same<typename CurveType::template g1_type<>::value_type,\n                                 typename std::iterator_traits<InputG1Iterator>::value_type>::value &&\n                        std::is_same<typename CurveType::scalar_field_type::value_type,\n                                     typename std::iterator_traits<InputScalarIterator>::value_type>::value,\n                    kzg_opening<typename CurveType::template g1_type<>>>::type\n                    prove_commitment_w(InputG1Iterator srs_powers_alpha_first, InputG1Iterator srs_powers_alpha_last,\n                                       InputG1Iterator srs_powers_beta_first, InputG1Iterator srs_powers_beta_last,\n                                       InputScalarIterator transcript_first, InputScalarIterator transcript_last,\n                                       typename CurveType::scalar_field_type::value_type r_shift,\n                                       const typename CurveType::scalar_field_type::value_type &kzg_challenge) {\n                    std::size_t n = std::distance(srs_powers_beta_first, srs_powers_beta_last) / 2;\n                    BOOST_ASSERT(2 * n == std::distance(srs_powers_alpha_first, srs_powers_alpha_last));\n\n                    // this computes f(X) = \\prod (1 + x (rX)^{2^j})\n                    std::vector<typename CurveType::scalar_field_type::value_type> fcoeffs =\n                        polynomial_coefficients_from_transcript<typename CurveType::scalar_field_type>(\n                            transcript_first, transcript_last, r_shift);\n                    // this computes f_w(X) = X^n * f(X) - it simply shifts all coefficients to by n\n                    fcoeffs.insert(fcoeffs.begin(), n, CurveType::scalar_field_type::value_type::zero());\n\n                    // this computes f(z)\n                    typename CurveType::scalar_field_type::value_type fz =\n                        polynomial_evaluation_product_form_from_transcript<typename CurveType::scalar_field_type>(\n                            transcript_first, transcript_last, kzg_challenge, r_shift);\n                    // this computes the \"shift\" z^n\n                    typename CurveType::scalar_field_type::value_type zn = kzg_challenge.pow(n);\n                    // this computes f_w(z) by multiplying by zn\n                    typename CurveType::scalar_field_type::value_type fwz = fz * zn;\n\n                    return prove_commitment_key_kzg_opening<typename CurveType::template g1_type<>>(\n                        srs_powers_alpha_first, srs_powers_alpha_last, srs_powers_beta_first, srs_powers_beta_last,\n                        fcoeffs, fwz, kzg_challenge);\n                }\n\n                /// gipa_tipp_mipp peforms the recursion of the GIPA protocol for TIPP and MIPP.\n                /// It returns a proof containing all intermdiate committed values, as well as\n                /// the challenges generated necessary to do the polynomial commitment proof\n                /// later in TIPP.\n                template<typename CurveType, typename Hash = hashes::sha2<256>, typename InputG1Iterator1,\n                         typename InputG2Iterator, typename InputG1Iterator2, typename InputScalarIterator>\n                typename std::enable_if<\n                    std::is_same<typename CurveType::template g1_type<>::value_type,\n                                 typename std::iterator_traits<InputG1Iterator1>::value_type>::value &&\n                        std::is_same<typename CurveType::template g2_type<>::value_type,\n                                     typename std::iterator_traits<InputG2Iterator>::value_type>::value &&\n                        std::is_same<typename CurveType::scalar_field_type::value_type,\n                                     typename std::iterator_traits<InputScalarIterator>::value_type>::value &&\n                        std::is_same<typename CurveType::template g1_type<>::value_type,\n                                     typename std::iterator_traits<InputG1Iterator2>::value_type>::value,\n                    std::tuple<gipa_proof<CurveType>, std::vector<typename CurveType::scalar_field_type::value_type>,\n                               std::vector<typename CurveType::scalar_field_type::value_type>>>::type\n                    gipa_tipp_mipp(transcript<CurveType, Hash> &tr, InputG1Iterator1 a_first, InputG1Iterator1 a_last,\n                                   InputG2Iterator b_first, InputG2Iterator b_last, InputG1Iterator2 c_first,\n                                   InputG1Iterator2 c_last, const r1cs_gg_ppzksnark_ipp2_vkey<CurveType> &vkey_input,\n                                   const r1cs_gg_ppzksnark_ipp2_wkey<CurveType> &wkey_input,\n                                   InputScalarIterator r_first, InputScalarIterator r_last) {\n                    std::size_t input_len = std::distance(a_first, a_last);\n                    BOOST_ASSERT(input_len >= 2);\n                    BOOST_ASSERT((input_len & (input_len - 1)) == 0);\n                    BOOST_ASSERT(input_len == std::distance(b_first, b_last));\n                    BOOST_ASSERT(input_len == std::distance(r_first, r_last));\n                    BOOST_ASSERT(input_len == std::distance(c_first, c_last));\n\n                    // the values of vectors A and B rescaled at each step of the loop\n                    // the values of vectors C and r rescaled at each step of the loop\n                    std::vector<typename CurveType::template g1_type<>::value_type> m_a {a_first, a_last}, m_c {c_first, c_last};\n                    std::vector<typename CurveType::template g2_type<>::value_type> m_b {b_first, b_last};\n                    std::vector<typename CurveType::scalar_field_type::value_type> m_r {r_first, r_last};\n\n                    // the values of the commitment keys rescaled at each step of the loop\n                    r1cs_gg_ppzksnark_ipp2_vkey<CurveType> vkey = vkey_input;\n                    r1cs_gg_ppzksnark_ipp2_wkey<CurveType> wkey = wkey_input;\n\n                    // storing the values for including in the proof\n                    std::vector<std::pair<typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type,\n                                          typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type>>\n                        comms_ab;\n                    std::vector<std::pair<typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type,\n                                          typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type>>\n                        comms_c;\n                    std::vector<\n                        std::pair<typename CurveType::gt_type::value_type, typename CurveType::gt_type::value_type>>\n                        z_ab;\n                    std::vector<\n                        std::pair<typename CurveType::template g1_type<>::value_type, typename CurveType::template g1_type<>::value_type>>\n                        z_c;\n                    std::vector<typename CurveType::scalar_field_type::value_type> challenges, challenges_inv;\n\n                    constexpr std::array<std::uint8_t, 4> domain_separator {'g', 'i', 'p', 'a'};\n                    tr.write_domain_separator(domain_separator.begin(), domain_separator.end());\n                    typename CurveType::scalar_field_type::value_type _i = tr.read_challenge();\n\n                    while (m_a.size() > 1) {\n                        // recursive step\n                        // Recurse with problem of half size\n                        std::size_t split = m_a.size() / 2;\n\n                        auto [vk_left, vk_right] = vkey.split(split);\n                        auto [wk_left, wk_right] = wkey.split(split);\n\n                        // TODO: parallel\n                        // See section 3.3 for paper version with equivalent names\n                        // TIPP part\n                        typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type tab_l =\n                            r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(\n                                vk_left, wk_right, m_a.begin() + split, m_a.end(), m_b.begin(), m_b.begin() + split);\n                        typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type tab_r =\n                            r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(\n                                vk_right, wk_left, m_a.begin(), m_a.begin() + split, m_b.begin() + split, m_b.end());\n\n                        // \\prod e(A_right,B_left)\n                        typename CurveType::gt_type::value_type zab_l = CurveType::gt_type::value_type::one();\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(m_a.begin() + split, m_b.begin())),\n                                      boost::make_zip_iterator(boost::make_tuple(m_a.end(), m_b.begin() + split)),\n                                      [&](const boost::tuple<const typename CurveType::template g1_type<>::value_type &,\n                                                             const typename CurveType::template g2_type<>::value_type &> &t) {\n                                          zab_l = zab_l *\n                                                  algebra::pair<CurveType>(t.template get<0>(), t.template get<1>());\n                                      });\n                        zab_l = algebra::final_exponentiation<CurveType>(zab_l);\n                        typename CurveType::gt_type::value_type zab_r = CurveType::gt_type::value_type::one();\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(m_a.begin(), m_b.begin() + split)),\n                                      boost::make_zip_iterator(boost::make_tuple(m_a.begin() + split, m_b.end())),\n                                      [&](const boost::tuple<const typename CurveType::template g1_type<>::value_type &,\n                                                             const typename CurveType::template g2_type<>::value_type &> &t) {\n                                          zab_r = zab_r *\n                                                  algebra::pair<CurveType>(t.template get<0>(), t.template get<1>());\n                                      });\n                        zab_r = algebra::final_exponentiation<CurveType>(zab_r);\n\n                        // MIPP part\n                        // z_l = c[n':] ^ r[:n']\n                        typename CurveType::template g1_type<>::value_type zc_l =\n                            algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(\n                                m_c.begin() + split, m_c.end(), m_r.begin(), m_r.begin() + split, 1);\n                        // Z_r = c[:n'] ^ r[n':]\n                        typename CurveType::template g1_type<>::value_type zc_r =\n                            algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(\n                                m_c.begin(), m_c.begin() + split, m_r.begin() + split, m_r.end(), 1);\n                        // u_l = c[n':] * v[:n']\n                        typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type tuc_l =\n                            r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::single(vk_left, m_c.begin() + split,\n                                                                                 m_c.end());\n                        // u_r = c[:n'] * v[n':]\n                        typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type tuc_r =\n                            r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::single(vk_right, m_c.begin(),\n                                                                                 m_c.begin() + split);\n\n                        // Fiat-Shamir challenge\n                        // combine both TIPP and MIPP transcript\n                        tr.template write<typename CurveType::gt_type>(zab_l);\n                        tr.template write<typename CurveType::gt_type>(zab_r);\n                        tr.template write<typename CurveType::template g1_type<>>(zc_l);\n                        tr.template write<typename CurveType::template g1_type<>>(zc_r);\n                        tr.template write<typename CurveType::gt_type>(tab_l.first);\n                        tr.template write<typename CurveType::gt_type>(tab_l.second);\n                        tr.template write<typename CurveType::gt_type>(tab_r.first);\n                        tr.template write<typename CurveType::gt_type>(tab_r.second);\n                        tr.template write<typename CurveType::gt_type>(tuc_l.first);\n                        tr.template write<typename CurveType::gt_type>(tuc_l.second);\n                        tr.template write<typename CurveType::gt_type>(tuc_r.first);\n                        tr.template write<typename CurveType::gt_type>(tuc_r.second);\n                        typename CurveType::scalar_field_type::value_type c_inv = tr.read_challenge();\n\n                        // Optimization for multiexponentiation to rescale G2 elements with\n                        // 128-bit challenge Swap 'c' and 'c_inv' since can't control bit size\n                        // of c_inv\n                        typename CurveType::scalar_field_type::value_type c = c_inv.inversed();\n\n                        // Set up values for next step of recursion\n                        // A[:n'] + A[n':] ^ x\n                        compress<CurveType>(m_a, split, c);\n                        // B[:n'] + B[n':] ^ x^-1\n                        compress<CurveType>(m_b, split, c_inv);\n                        // c[:n'] + c[n':]^x\n                        compress<CurveType>(m_c, split, c);\n                        // r[:n'] + r[n':]^x^-1\n                        compress<CurveType>(m_r, split, c_inv);\n\n                        // v_left + v_right^x^-1\n                        vkey = vk_left.compress(vk_right, c_inv);\n                        // w_left + w_right^x\n                        wkey = wk_left.compress(wk_right, c);\n\n                        comms_ab.emplace_back(std::make_pair(tab_l, tab_r));\n                        comms_c.emplace_back(std::make_pair(tuc_l, tuc_r));\n                        z_ab.emplace_back(std::make_pair(zab_l, zab_r));\n                        z_c.emplace_back(std::make_pair(zc_l, zc_r));\n                        challenges.emplace_back(c);\n                        challenges_inv.emplace_back(c_inv);\n                    }\n\n                    BOOST_ASSERT(m_a.size() == 1 && m_b.size() == 1);\n                    BOOST_ASSERT(m_c.size() == 1 && m_r.size() == 1);\n                    BOOST_ASSERT(vkey.a.size() == 1 && vkey.b.size() == 1);\n                    BOOST_ASSERT(wkey.a.size() == 1 && wkey.b.size() == 1);\n\n                    return std::make_tuple(gipa_proof<CurveType> {input_len, comms_ab, comms_c, z_ab, z_c, m_a[0],\n                                                                  m_b[0], m_c[0], vkey.first(), wkey.first()},\n                                           challenges, challenges_inv);\n                }\n\n                /// Proves a TIPP relation between A and B as well as a MIPP relation with C and\n                /// r. Commitment keys must be of size of A, B and C. In the context of Groth16\n                /// aggregation, we have that B = B^r and wkey is scaled by r^{-1}. The\n                /// commitment key v is used to commit to A and C recursively in GIPA such that\n                /// only one KZG proof is needed for v. In the original paper version, since the\n                /// challenges of GIPA would be different, two KZG proofs would be needed.\n                template<typename CurveType, typename Hash = hashes::sha2<256>, typename InputG1Iterator1,\n                         typename InputG2Iterator, typename InputG1Iterator2, typename InputScalarIterator>\n                typename std::enable_if<\n                    std::is_same<typename CurveType::template g1_type<>::value_type,\n                                 typename std::iterator_traits<InputG1Iterator1>::value_type>::value &&\n                        std::is_same<typename CurveType::template g2_type<>::value_type,\n                                     typename std::iterator_traits<InputG2Iterator>::value_type>::value &&\n                        std::is_same<typename CurveType::template g1_type<>::value_type,\n                                     typename std::iterator_traits<InputG1Iterator2>::value_type>::value &&\n                        std::is_same<typename CurveType::scalar_field_type::value_type,\n                                     typename std::iterator_traits<InputScalarIterator>::value_type>::value,\n                    tipp_mipp_proof<CurveType>>::type\n                    prove_tipp_mipp(const r1cs_gg_ppzksnark_aggregate_proving_srs<CurveType> &srs,\n                                    transcript<CurveType, Hash> &tr, InputG1Iterator1 a_first, InputG1Iterator1 a_last,\n                                    InputG2Iterator b_first, InputG2Iterator b_last, InputG1Iterator2 c_first,\n                                    InputG1Iterator2 c_last, const r1cs_gg_ppzksnark_ipp2_wkey<CurveType> &wkey,\n                                    InputScalarIterator r_first, InputScalarIterator r_last) {\n                    typename CurveType::scalar_field_type::value_type r_shift = *(r_first + 1);\n                    // Run GIPA\n                    auto [proof, challenges, challenges_inv] = gipa_tipp_mipp<CurveType>(\n                        tr, a_first, a_last, b_first, b_last, c_first, c_last, srs.vkey, wkey, r_first, r_last);\n\n                    // Prove final commitment keys are wellformed\n                    // we reverse the transcript so the polynomial in kzg opening is constructed\n                    // correctly - the formula indicates x_{l-j}. Also for deriving KZG\n                    // challenge point, input must be the last challenge.\n                    std::reverse(challenges.begin(), challenges.end());\n                    std::reverse(challenges_inv.begin(), challenges_inv.end());\n                    typename CurveType::scalar_field_type::value_type r_inverse = r_shift.inversed();\n\n                    // KZG challenge point\n                    constexpr std::array<std::uint8_t, 8> domain_separator {'r', 'a', 'n', 'd', 'o', 'm', '-', 'z'};\n                    tr.write_domain_separator(domain_separator.begin(), domain_separator.end());\n                    tr.template write<typename CurveType::scalar_field_type>(challenges[0]);\n                    tr.template write<typename CurveType::template g2_type<>>(proof.final_vkey.first);\n                    tr.template write<typename CurveType::template g2_type<>>(proof.final_vkey.second);\n                    tr.template write<typename CurveType::template g1_type<>>(proof.final_wkey.first);\n                    tr.template write<typename CurveType::template g1_type<>>(proof.final_wkey.second);\n                    typename CurveType::scalar_field_type::value_type z = tr.read_challenge();\n\n                    // Complete KZG proofs\n                    return tipp_mipp_proof<CurveType> {\n                        proof,\n                        prove_commitment_v<CurveType>(srs.h_alpha_powers.begin(), srs.h_alpha_powers.end(),\n                                                      srs.h_beta_powers.begin(), srs.h_beta_powers.end(),\n                                                      challenges_inv.begin(), challenges_inv.end(), z),\n                        prove_commitment_w<CurveType>(srs.g_alpha_powers.begin(), srs.g_alpha_powers.end(),\n                                                      srs.g_beta_powers.begin(), srs.g_beta_powers.end(),\n                                                      challenges.begin(), challenges.end(), r_inverse, z)};\n                }\n\n                /// Aggregate `n` zkSnark proofs, where `n` must be a power of two.\n                template<typename CurveType, typename Hash = hashes::sha2<256>, typename InputTranscriptIncludeIterator,\n                         typename InputProofIterator>\n                typename std::enable_if<\n                    std::is_same<std::uint8_t,\n                                 typename std::iterator_traits<InputTranscriptIncludeIterator>::value_type>::value &&\n                        std::is_same<typename std::iterator_traits<InputProofIterator>::value_type,\n                                     r1cs_gg_ppzksnark_proof<CurveType>>::value,\n                    r1cs_gg_ppzksnark_aggregate_proof<CurveType>>::type\n                    aggregate_proofs(const r1cs_gg_ppzksnark_aggregate_proving_srs<CurveType> &srs,\n                                     InputTranscriptIncludeIterator tr_include_first,\n                                     InputTranscriptIncludeIterator tr_include_last, InputProofIterator proofs_first,\n                                     InputProofIterator proofs_last) {\n                    std::size_t nproofs = std::distance(proofs_first, proofs_last);\n                    BOOST_ASSERT(nproofs >= 2);\n                    BOOST_ASSERT((nproofs & (nproofs - 1)) == 0);\n                    BOOST_ASSERT(srs.has_correct_len(nproofs));\n\n                    // TODO: parallel\n                    // We first commit to A B and C - these commitments are what the verifier\n                    // will use later to verify the TIPP and MIPP proofs\n                    std::vector<typename CurveType::template g1_type<>::value_type> a, c;\n                    std::vector<typename CurveType::template g2_type<>::value_type> b;\n                    auto proofs_it = proofs_first;\n                    while (proofs_it != proofs_last) {\n                        a.emplace_back(proofs_it->g_A);\n                        b.emplace_back(proofs_it->g_B);\n                        c.emplace_back(proofs_it->g_C);\n                        ++proofs_it;\n                    }\n\n                    // A and B are committed together in this scheme\n                    // we need to take the reference so the macro doesn't consume the value\n                    // first\n                    typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type com_ab =\n                        r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(srs.vkey, srs.wkey, a.begin(), a.end(),\n                                                                           b.begin(), b.end());\n                    typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type com_c =\n                        r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::single(srs.vkey, c.begin(), c.end());\n\n                    // Derive a random scalar to perform a linear combination of proofs\n                    constexpr std::array<std::uint8_t, 9> application_tag = {'s', 'n', 'a', 'r', 'k',\n                                                                             'p', 'a', 'c', 'k'};\n                    constexpr std::array<std::uint8_t, 8> domain_separator {'r', 'a', 'n', 'd', 'o', 'm', '-', 'r'};\n                    transcript<CurveType, Hash> tr(application_tag.begin(), application_tag.end());\n                    tr.write_domain_separator(domain_separator.begin(), domain_separator.end());\n                    tr.template write<typename CurveType::gt_type>(com_ab.first);\n                    tr.template write<typename CurveType::gt_type>(com_ab.second);\n                    tr.template write<typename CurveType::gt_type>(com_c.first);\n                    tr.template write<typename CurveType::gt_type>(com_c.second);\n                    tr.write(tr_include_first, tr_include_last);\n                    typename CurveType::scalar_field_type::value_type r = tr.read_challenge();\n\n                    // 1,r, r^2, r^3, r^4 ...\n                    std::vector<typename CurveType::scalar_field_type::value_type> r_vec =\n                        structured_scalar_power<typename CurveType::scalar_field_type>(\n                            std::distance(proofs_first, proofs_last), r);\n                    // 1,r^-1, r^-2, r^-3\n                    std::vector<typename CurveType::scalar_field_type::value_type> r_inv;\n                    std::transform(r_vec.begin(), r_vec.end(), std::back_inserter(r_inv),\n                                   [](const auto &r_i) { return r_i.inversed(); });\n\n                    // B^{r}\n                    std::vector<typename CurveType::template g2_type<>::value_type> b_r;\n                    std::for_each(\n                        boost::make_zip_iterator(boost::make_tuple(b.begin(), r_vec.begin())),\n                        boost::make_zip_iterator(boost::make_tuple(b.end(), r_vec.end())),\n                        [&](const boost::tuple<const typename CurveType::template g2_type<>::value_type &,\n                                               const typename CurveType::scalar_field_type::value_type &> &t) {\n                            b_r.emplace_back((t.template get<0>() * t.template get<1>()));\n                        });\n                    // TODO: parallel\n                    // compute A * B^r for the verifier\n                    // auto ip_ab = algebra::pair<CurveType>(a, b_r);\n                    typename CurveType::gt_type::value_type ip_ab = CurveType::gt_type::value_type::one();\n                    std::for_each(boost::make_zip_iterator(boost::make_tuple(a.begin(), b_r.begin())),\n                                  boost::make_zip_iterator(boost::make_tuple(a.end(), b_r.end())),\n                                  [&](const boost::tuple<const typename CurveType::template g1_type<>::value_type &,\n                                                         const typename CurveType::template g2_type<>::value_type &> &t) {\n                                      ip_ab =\n                                          ip_ab * algebra::pair<CurveType>(t.template get<0>(), t.template get<1>());\n                                  });\n                    ip_ab = algebra::final_exponentiation<CurveType>(ip_ab);\n                    // compute C^r for the verifier\n                    typename CurveType::template g1_type<>::value_type agg_c =\n                        algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(c.begin(), c.end(),\n                                                                                         r_vec.begin(), r_vec.end(), 1);\n                    tr.template write<typename CurveType::gt_type>(ip_ab);\n                    tr.template write<typename CurveType::template g1_type<>>(agg_c);\n\n                    // w^{r^{-1}}\n                    r1cs_gg_ppzksnark_ipp2_commitment_key<typename CurveType::template g1_type<>> wkey_r_inv =\n                        srs.wkey.scale(r_inv.begin(), r_inv.end());\n\n                    // we prove tipp and mipp using the same recursive loop\n                    tipp_mipp_proof<CurveType> proof =\n                        prove_tipp_mipp(srs, tr, a.begin(), a.end(), b_r.begin(), b_r.end(), c.begin(), c.end(),\n                                        wkey_r_inv, r_vec.begin(), r_vec.end());\n\n                    // debug assert\n                    BOOST_ASSERT(com_ab == r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(\n                                               srs.vkey, wkey_r_inv, a.begin(), a.end(), b_r.begin(), b_r.end()));\n\n                    return {com_ab, com_c, ip_ab, agg_c, proof};\n                }\n\n                template<typename CurveType, typename BasicProver>\n                class r1cs_gg_ppzksnark_aggregate_prover {\n                    typedef detail::r1cs_gg_ppzksnark_basic_policy<CurveType, ProvingMode::Aggregate> policy_type;\n\n                public:\n\n                    typedef BasicProver basic_prover;\n\n                    typedef typename policy_type::primary_input_type primary_input_type;\n                    typedef typename policy_type::auxiliary_input_type auxiliary_input_type;\n                    typedef typename policy_type::proving_key_type proving_key_type;\n                    typedef typename policy_type::proving_srs_type proving_srs_type;\n                    typedef typename policy_type::proof_type proof_type;\n                    typedef typename policy_type::aggregate_proof_type aggregate_proof_type;\n\n                    // Aggregate prove\n                    template<typename Hash, typename InputTranscriptIncludeIterator, typename InputProofIterator>\n                    static inline aggregate_proof_type process(const proving_srs_type &srs,\n                                                               InputTranscriptIncludeIterator transcript_include_first,\n                                                               InputTranscriptIncludeIterator transcript_include_last,\n                                                               InputProofIterator proofs_first,\n                                                               InputProofIterator proofs_last) {\n                        return aggregate_proofs<CurveType, Hash>(srs, transcript_include_first, transcript_include_last,\n                                                                 proofs_first, proofs_last);\n                    }\n\n                    // Basic prove\n                    static inline proof_type process(const proving_key_type &pk,\n                                                     const primary_input_type &primary_input,\n                                                     const auxiliary_input_type &auxiliary_input) {\n\n                        return BasicProver::process(pk, primary_input, auxiliary_input);\n                    }\n                };\n            }    // namespace snark\n        }        // namespace zk\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_R1CS_GG_PPZKSNARK_TYPES_POLICY_HPP\n", "meta": {"hexsha": "54d781e744a61cc758c20ee28fbc2656f67f8c4b", "size": 45351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/prover.hpp", "max_stars_repo_name": "NilFoundation/crypto3-zk", "max_stars_repo_head_hexsha": "44a19899759599bd957ee2b824a093f7861fb3a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-31T06:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:31:02.000Z", "max_issues_repo_path": "include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/prover.hpp", "max_issues_repo_name": "tonlabs/crypto3-zk", "max_issues_repo_head_hexsha": "44a19899759599bd957ee2b824a093f7861fb3a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-09-15T18:32:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:53:01.000Z", "max_forks_repo_path": "include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/prover.hpp", "max_forks_repo_name": "tonlabs/crypto3-zk", "max_forks_repo_head_hexsha": "44a19899759599bd957ee2b824a093f7861fb3a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-22T16:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:31:07.000Z", "avg_line_length": 69.8782742681, "max_line_length": 138, "alphanum_fraction": 0.5404511477, "num_tokens": 9041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18572647814787097}}
{"text": "\n#include <chrono>\n#include <iostream>\n#include <memory>\n#include <random>\n// uncomment to disable assert()\n// #define NDEBUG\n#include <cassert>\n\n#include <clipper/constants.hpp>\n#include <clipper/containers.hpp>\n#include <clipper/logging.hpp>\n#include <clipper/metrics.hpp>\n#include <clipper/util.hpp>\n\n#include <boost/circular_buffer.hpp>\n#include <boost/thread.hpp>\n\nnamespace clipper {\n\nconst std::string LOGGING_TAG_CONTAINERS = \"CONTAINERS\";\n\nModelContainer::ModelContainer(VersionedModelId model, int container_id,\n                               int replica_id, InputType input_type)\n    : model_(model),\n      container_id_(container_id),\n      replica_id_(replica_id),\n      input_type_(input_type),\n      avg_throughput_per_milli_(0),\n      throughput_buffer_(THROUGHPUT_BUFFER_CAPACITY) {\n  std::string model_str = versioned_model_to_str(model);\n  log_info_formatted(LOGGING_TAG_CONTAINERS,\n                     \"Creating new ModelContainer for model {}, id: {}\",\n                     model_str, std::to_string(container_id));\n}\n\nvoid ModelContainer::update_throughput(size_t batch_size,\n                                       long total_latency_micros) {\n  if (batch_size <= 0 || total_latency_micros <= 0) {\n    throw std::invalid_argument(\n        \"Batch size and latency must be positive for throughput updates!\");\n  }\n  boost::unique_lock<boost::shared_mutex> lock(throughput_mutex_);\n  double new_throughput = 1000 * (static_cast<double>(batch_size) /\n                                  static_cast<double>(total_latency_micros));\n  double old_total_throughput =\n      avg_throughput_per_milli_ * throughput_buffer_.size();\n  if (throughput_buffer_.size() == throughput_buffer_.capacity()) {\n    // If the throughput buffer is already at maximum capacity,\n    // we replace the oldest throughput sample with\n    // the latest throughput and recalculate the average\n    double oldest_throughput = throughput_buffer_.front();\n    double new_total_throughput =\n        (old_total_throughput - oldest_throughput + new_throughput);\n    avg_throughput_per_milli_ =\n        new_total_throughput / static_cast<double>(throughput_buffer_.size());\n  } else {\n    // If the throughput buffer is not yet at capacity,\n    // we add the latest throughput sample to the buffer\n    // and incorporate it into the average\n    avg_throughput_per_milli_ =\n        (old_total_throughput + new_throughput) /\n        static_cast<double>(throughput_buffer_.size() + 1);\n  }\n  throughput_buffer_.push_back(new_throughput);\n}\n\ndouble ModelContainer::get_average_throughput_per_millisecond() {\n  boost::shared_lock<boost::shared_mutex> lock(throughput_mutex_);\n  return avg_throughput_per_milli_;\n}\n\nsize_t ModelContainer::get_batch_size(Deadline deadline) {\n  double current_time_millis =\n      std::chrono::duration_cast<std::chrono::milliseconds>(\n          std::chrono::system_clock::now().time_since_epoch())\n          .count();\n  double deadline_millis =\n      std::chrono::duration_cast<std::chrono::milliseconds>(\n          deadline.time_since_epoch())\n          .count();\n  double remaining_time_millis = deadline_millis - current_time_millis;\n  boost::shared_lock<boost::shared_mutex> lock(throughput_mutex_);\n  int batch_size =\n      static_cast<int>(avg_throughput_per_milli_ * remaining_time_millis);\n  if (batch_size < 1) {\n    batch_size = 1;\n  }\n  return batch_size;\n}\n\nActiveContainers::ActiveContainers()\n    : containers_(\n          std::unordered_map<VersionedModelId,\n                             std::map<int, std::shared_ptr<ModelContainer>>,\n                             decltype(&versioned_model_hash)>(\n              100, &versioned_model_hash)) {}\n\nvoid ActiveContainers::add_container(VersionedModelId model, int connection_id,\n                                     int replica_id, InputType input_type) {\n  log_info_formatted(LOGGING_TAG_CONTAINERS,\n                     \"Adding new container - model: {}, version: {}, \"\n                     \"connection ID: {}, replica ID: {}, input_type: {}\",\n                     model.first, model.second, connection_id, replica_id,\n                     get_readable_input_type(input_type));\n  boost::unique_lock<boost::shared_mutex> l{m_};\n  auto new_container = std::make_shared<ModelContainer>(model, connection_id,\n                                                        replica_id, input_type);\n  auto entry = containers_[new_container->model_];\n  entry.emplace(replica_id, new_container);\n  containers_[new_container->model_] = entry;\n  assert(containers_[new_container->model_].size() > 0);\n  std::stringstream log_msg;\n  log_msg << \"\\nActive containers:\\n\";\n  for (auto model : containers_) {\n    log_msg << \"\\tModel: \" << versioned_model_to_str(model.first) << \"\\n\";\n    for (auto r : model.second) {\n      log_msg << \"\\t\\trep_id: \" << r.first\n              << \", container_id: \" << r.second->container_id_ << \"\\n\";\n    }\n  }\n  log_info(LOGGING_TAG_CONTAINERS, log_msg.str());\n}\n\nstd::shared_ptr<ModelContainer> ActiveContainers::get_model_replica(\n    const VersionedModelId &model, const int replica_id) {\n  boost::shared_lock<boost::shared_mutex> l{m_};\n\n  auto replicas_map_entry = containers_.find(model);\n  if (replicas_map_entry == containers_.end()) {\n    log_error_formatted(LOGGING_TAG_CONTAINERS,\n                        \"Requested replica {} for model {} NOT FOUND\",\n                        replica_id, versioned_model_to_str(model));\n    return nullptr;\n  }\n\n  std::map<int, std::shared_ptr<ModelContainer>> replicas_map =\n      replicas_map_entry->second;\n  auto replica_entry = replicas_map.find(replica_id);\n  if (replica_entry != replicas_map.end()) {\n    return replica_entry->second;\n  } else {\n    log_error_formatted(LOGGING_TAG_CONTAINERS,\n                        \"Requested replica {} for model {} NOT FOUND\",\n                        replica_id, versioned_model_to_str(model));\n    return nullptr;\n  }\n}\n\nstd::vector<VersionedModelId> ActiveContainers::get_known_models() {\n  boost::shared_lock<boost::shared_mutex> l{m_};\n  std::vector<VersionedModelId> keys;\n  for (auto m : containers_) {\n    keys.push_back(m.first);\n  }\n  return keys;\n}\n}\n", "meta": {"hexsha": "dce7283c4cddc3bdd5b91c9a7348d79e1b18de23", "size": 6131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libclipper/src/containers.cpp", "max_stars_repo_name": "Corey-Zumar/clipper-db-queries", "max_stars_repo_head_hexsha": "e60f8d8b11c0ccc5f0287b63fe5cb86d128b72f0", "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/libclipper/src/containers.cpp", "max_issues_repo_name": "Corey-Zumar/clipper-db-queries", "max_issues_repo_head_hexsha": "e60f8d8b11c0ccc5f0287b63fe5cb86d128b72f0", "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/libclipper/src/containers.cpp", "max_forks_repo_name": "Corey-Zumar/clipper-db-queries", "max_forks_repo_head_hexsha": "e60f8d8b11c0ccc5f0287b63fe5cb86d128b72f0", "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.5597484277, "max_line_length": 80, "alphanum_fraction": 0.676724841, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18572647814787097}}
{"text": "// Copyright (c) 2013 Spotify AB\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#include \"Python.h\"\n#include <stdio.h>\n#include <string>\n#include <boost/python.hpp>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <fcntl.h>\n#include <sys/mman.h>\n#include <string.h>\n#include <math.h>\n#include <vector>\n#include <queue>\n#include <limits>\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n\n#ifndef NO_PACKED_STRUCTS\n#define PACKED_STRUCTS_EXTRA __attribute__((__packed__))\n// TODO: this is turned on by default, but may not work for all architectures! Need to investigate.\n#endif\n\nusing namespace std;\nusing namespace boost;\n\ntemplate<typename T>\nstruct Randomness {\n  // Just a dummy class to avoid code repetition.\n  // Owned by the AnnoyIndex, passed around to the distance metrics\n  mt19937 _rng;\n  normal_distribution<T> _nd;\n  variate_generator<mt19937&, \n\t\t    normal_distribution<T> > _var_nor;\n  uniform_01<T> _ud;\n  variate_generator<mt19937&, \n\t\t    uniform_01<T> > _var_uni;\n  bernoulli_distribution<T> _bd;\n  variate_generator<mt19937&, \n\t\t    bernoulli_distribution<T> > _var_ber;\n  Randomness() : _rng(), _nd(), _var_nor(_rng, _nd), _ud(), _var_uni(_rng, _ud), _bd(), _var_ber(_rng, _bd) {}\n  inline T gaussian() {\n    return _var_nor();\n  }\n  inline int flip() {\n    return _var_ber();\n  }\n  inline T uniform(T min, T max) {\n    return _var_uni() * (max - min) + min;\n  }\n};\n\ntemplate<typename T>\ninline void normalize(T* v, int f) {\n  T sq_norm = 0;\n  for (int z = 0; z < f; z++)\n    sq_norm += v[z] * v[z];\n  T norm = sqrt(sq_norm);\n  for (int z = 0; z < f; z++)\n    v[z] /= norm;\n}\n\n\ntemplate<typename T>\nstruct Angular {\n  struct PACKED_STRUCTS_EXTRA node {\n    /*\n     * We store a binary tree where each node has two things\n     * - A vector associated with it\n     * - Two children\n     * All nodes occupy the same amount of memory\n     * All nodes with n_descendants == 1 are leaf nodes.\n     * A memory optimization is that for nodes with 2 <= n_descendants <= K,\n     * we skip the vector. Instead we store a list of all descendants. K is\n     * determined by the number of items that fits in the same space.\n     * For nodes with n_descendants == 1 or > K, there is always a\n     * corresponding vector. \n     * Note that we can't really do sizeof(node<T>) because we cheat and allocate\n     * more memory to be able to fit the vector outside\n     */\n    int n_descendants;\n    int children[2]; // Will possibly store more than 2\n    T v[0]; // Hack. We just allocate as much memory as we need and let this array overflow\n  };\n  static inline T distance(const T* x, const T* y, int f) {\n    // want to calculate (a/|a| - b/|b|)^2\n    // = a^2 / a^2 + b^2 / b^2 - 2ab/|a||b|\n    // = 2 - 2cos\n    T pp = 0, qq = 0, pq = 0;\n    for (int z = 0; z < f; z++) {\n      pp += x[z] * x[z];\n      qq += y[z] * y[z];\n      pq += x[z] * y[z];\n    }\n    T ppqq = pp * qq;\n    if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq);\n    else return 2.0; // cos is 0\n  }\n  static inline T margin(const node* n, const T* y, int f) {\n    T dot = 0;\n    for (int z = 0; z < f; z++)\n      dot += n->v[z] * y[z];\n    return dot;\n  }\n  static inline bool side(const node* n, const T* y, int f, Randomness<T>* random) {\n    T dot = margin(n, y, f);\n    if (dot != 0)\n      return (dot > 0);\n    else\n      return random->flip();\n  }\n  static inline void create_split(const vector<node*>& nodes, int f, Randomness<T>* random, node* n) {\n    for (int z = 0; z < f; z++)\n      n->v[z] = random->gaussian();\n    normalize(n->v, f);\n  }\n};\n\ntemplate<typename T>\nstruct Euclidean {\n  struct __attribute__((__packed__)) node {\n    int n_descendants;\n    T a; // need an extra constant term to determine the offset of the plane\n    int children[2];\n    T v[0];\n  };\n  static inline T distance(const T* x, const T* y, int f) {\n    T d = 0.0;\n    for (int i = 0; i < f; i++) \n      d += (x[i] - y[i]) * (x[i] - y[i]);\n    return d;\n  }\n  static inline T margin(const node* n, const T* y, int f) {\n    T dot = n->a;\n    for (int z = 0; z < f; z++)\n      dot += n->v[z] * y[z];\n    return dot;\n  }\n  static inline bool side(const node* n, const T* y, int f, Randomness<T>* random) {\n    T dot = margin(n, y, f);\n    if (dot != 0)\n      return (dot > 0);\n    else\n      return random->flip();\n  }\n  static inline void create_split(const vector<node*>& nodes, int f, Randomness<T>* random, node* n) {\n    // See http://en.wikipedia.org/wiki/Bertrand_paradox_(probability)\n    // We want to sample a random hyperplane out of all hyperplanes that cut the convex hull.\n    // The probability of each angle is in proportion to the extent of the projection.\n    // This is good because it means we try to split in the longest direction.\n    // Doing this using Metropolis-Hastings sampling using 10 steps\n    T* v = (T*)malloc(sizeof(T) * f); // TODO: would be really nice to get rid of this allocation\n    double max_proj = 0.0;\n    for (int step = 0; step < 10; step++) {\n      for (int z = 0; z < f; z++)\n\tv[z] = random->gaussian();\n      normalize(v, f);\n      // Project the nodes onto the vector and calculate max and min\n      T min = INFINITY, max = -INFINITY;\n      for (size_t i = 0; i < nodes.size(); i++) {\n\tT dot = 0;\n\tfor (int z = 0; z < f; z++)\n\t  dot += nodes[i]->v[z] * v[z];\n\tif (dot > max)\n\t  max = dot;\n\tif (dot < min)\n\t  min = dot;\n      }\n      if (max - min > random->uniform(0, max_proj)) {\n\tmax_proj = max - min;\n\tmemcpy(n->v, v, sizeof(T) * f);\n\tn->a = -random->uniform(min, max); // Take a random split along this axis\n      }\n    }\n    free(v);\n  }\n};\n\ntemplate<typename T, typename Distance>\nclass AnnoyIndex {\n  /*\n   * We use random projection to build a forest of binary trees of all items.\n   * Basically just split the hyperspace into two sides by a hyperplane,\n   * then recursively split each of those subtrees etc.\n   * We create a tree like this q times. The default q is determined automatically\n   * in such a way that we at most use 2x as much memory as the vectors take.\n   */\nprotected:\n  int _f;\n  size_t _s;\n  int _n_items;\n  Randomness<T> _random;\n  void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate\n  int _n_nodes;\n  int _nodes_size;\n  vector<int> _roots;\n  int _K;\n  bool _loaded;\npublic:\n  AnnoyIndex(int f) : _random() {\n    _f = f;\n    _s = sizeof(typename Distance::node) + sizeof(T) * f; // Size of each node\n    _n_items = 0;\n    _n_nodes = 0;\n    _nodes_size = 0;\n    _nodes = NULL;\n    _loaded = false;\n\n    _K = (sizeof(T) * f + sizeof(int) * 2) / sizeof(int);\n  }\n  ~AnnoyIndex() {\n    if (_loaded) {\n      unload();\n    } else if(_nodes) {\n      free(_nodes);\n    }\n  }\n\n  void add_item(int item, const T* w) {\n    _allocate_size(item+1);\n    typename Distance::node* n = _get(item);\n\n    n->children[0] = 0;\n    n->children[1] = 0;\n    n->n_descendants = 1;\n\n    for (int z = 0; z < _f; z++)\n      n->v[z] = w[z];\n\n    if (item >= _n_items)\n      _n_items = item + 1;\n  }\n\n  void build(int q) {\n    _n_nodes = _n_items;\n    while (1) {\n      if (q == -1 && _n_nodes >= _n_items * 2)\n\tbreak;\n      if (q != -1 && _roots.size() >= (size_t)q)\n\tbreak;\n      fprintf(stderr, \"pass %zd...\\n\", _roots.size());\n\n      vector<int> indices;\n      for (int i = 0; i < _n_items; i++)\n\tindices.push_back(i);\n\n      _roots.push_back(_make_tree(indices));\n    }\n    // Also, copy the roots into the last segment of the array\n    // This way we can load them faster without reading the whole file\n    _allocate_size(_n_nodes + _roots.size());\n    for (size_t i = 0; i < _roots.size(); i++)\n      memcpy(_get(_n_nodes + i), _get(_roots[i]), _s);\n    _n_nodes += _roots.size();\n      \n    fprintf(stderr, \"has %d nodes\\n\", _n_nodes);\n  }\n\n  void save(const string& filename) {\n    FILE *f = fopen(filename.c_str(), \"w\");\n    \n    fwrite(_nodes, _s, _n_nodes, f);\n\n    fclose(f);\n\n    free(_nodes);\n    _n_items = 0;\n    _n_nodes = 0;\n    _nodes_size = 0;\n    _nodes = NULL;\n    _roots.clear();\n    load(filename);\n  }\n\n  void reinitialize() {\n    _nodes = NULL;\n    _loaded = false;\n    _n_items = 0;\n    _n_nodes = 0;\n    _nodes_size = 0;\n    _roots.clear();\n  }\n\n  void unload() {\n    off_t size = _n_nodes * _s;\n    munmap(_nodes, size);\n    reinitialize();\n    fprintf(stderr, \"unloaded\\n\");\n  }\n\n  void load(const string& filename) {\n    struct stat buf;\n    stat(filename.c_str(), &buf);\n    off_t size = buf.st_size;\n    int fd = open(filename.c_str(), O_RDONLY, (mode_t)0400);\n#ifdef MAP_POPULATE\n    _nodes = (typename Distance::node*)mmap(\n        0, size, PROT_READ, MAP_SHARED | MAP_POPULATE, fd, 0);\n#else\n    _nodes = (typename Distance::node*)mmap(\n        0, size, PROT_READ, MAP_SHARED, fd, 0);\n#endif\n\n    _n_nodes = size / _s;\n\n    // Find the roots by scanning the end of the file and taking the nodes with most descendants\n    int m = -1;\n    for (int i = _n_nodes - 1; i >= 0; i--) {\n      int k = _get(i)->n_descendants;\n      if (m == -1 || k == m) {\n\t_roots.push_back(i);\n\tm = k;\n      } else {\n\tbreak;\n      }\n    }\n    _loaded = true;\n    _n_items = m;\n    fprintf(stderr, \"found %lu roots with degree %d\\n\", _roots.size(), m);\n  }\n\n  inline T get_distance(int i, int j) {\n    const T* x = _get(i)->v;\n    const T* y = _get(j)->v;\n    return Distance::distance(x, y, _f);\n  }\n\n  void get_nns_by_item(int item, size_t n, vector<int>* result) {\n    const typename Distance::node* m = _get(item);\n    _get_all_nns(m->v, n, result);\n  }\n\n  void get_nns_by_vector(const T* w, size_t n, vector<int>* result) {\n    _get_all_nns(w, n, result);\n  }\n  int get_n_items() {\n    return _n_items;\n  }\nprotected:\n  void _allocate_size(int n) {\n    if (n > _nodes_size) {\n      int new_nodes_size = (_nodes_size + 1) * 2;\n      if (n > new_nodes_size)\n\tnew_nodes_size = n;\n      _nodes = realloc(_nodes, _s * new_nodes_size);\n      memset((char *)_nodes + (_nodes_size * _s)/sizeof(char), 0, (new_nodes_size - _nodes_size) * _s);\n      _nodes_size = new_nodes_size;\n    }\n  }\n\n  inline typename Distance::node* _get(int i) {\n    return (typename Distance::node*)((char *)_nodes + (_s * i)/sizeof(char));\n  }\n\n  int _make_tree(const vector<int >& indices) {\n    if (indices.size() == 1)\n      return indices[0];\n\n    _allocate_size(_n_nodes + 1);\n    int item = _n_nodes++;\n    typename Distance::node* m = _get(item);\n    m->n_descendants = indices.size();\n\n    if (indices.size() <= (size_t)_K) {\n      for (size_t i = 0; i < indices.size(); i++)\n\tm->children[i] = indices[i];\n      return item;\n    }\n\n    vector<int> children_indices[2];\n    for (int attempt = 0; attempt < 20; attempt ++) {\n      /*\n       * Create a random hyperplane.\n       * If all points end up on the same time, we try again.\n       * We could in principle *construct* a plane so that we split\n       * all items evenly, but I think that could violate the guarantees\n       * given by just picking a hyperplane at random\n       */\n      vector<typename Distance::node*> children;\n\n      for (size_t i = 0; i < indices.size(); i++) {\n\t// TODO: this loop isn't needed for the angular distance, because\n\t// we can just split by a random vector and it's fine. For Euclidean\n\t// distance we need it to calculate the offset\n\tint j = indices[i];\n\ttypename Distance::node* n = _get(j);\n\tif (n)\n\t  children.push_back(n);\n      }\n\n      Distance::create_split(children, _f, &_random, m);\n      \n      children_indices[0].clear();\n      children_indices[1].clear();\n\n      for (size_t i = 0; i < indices.size(); i++) {\n\tint j = indices[i];\n\ttypename Distance::node* n = _get(j);\n\tif (n) {\n\t  bool side = Distance::side(m, n->v, _f, &_random);\n\t  children_indices[side].push_back(j);\n\t}\n      }\n\n      if (children_indices[0].size() > 0 && children_indices[1].size() > 0) {\n\tbreak;\n      }\n    }\n\n    while (children_indices[0].size() == 0 || children_indices[1].size() == 0) {\n      // If we didn't find a hyperplane, just randomize sides as a last option\n      if (indices.size() > 100000)\n\tfprintf(stderr, \"Failed splitting %lu items\\n\", indices.size());\n\n      children_indices[0].clear();\n      children_indices[1].clear();\n\n      // Set the vector to 0.0\n      for (int z = 0; z < _f; z++)\n\tm->v[z] = 0.0;\n\n      for (size_t i = 0; i < indices.size(); i++) {\n\tint j = indices[i];\n\t// Just randomize...\n\tchildren_indices[_random.flip()].push_back(j);\n      }\n    }\n\n    int children_0 = _make_tree(children_indices[0]);\n    int children_1 = _make_tree(children_indices[1]);\n\n    // We need to fetch m again because it might have been reallocated\n    m = _get(item);\n    m->children[0] = children_0;\n    m->children[1] = children_1;\n\n    return item;\n  }\n\n  void _get_nns(const T* v, int i, vector<int>* result, int limit) {\n    const typename Distance::node* n = _get(i);\n\n    if (n->n_descendants == 0) {\n      // unknown item, nothing to do...\n    } else if (n->n_descendants == 1) {\n      result->push_back(i);\n    } else if (n->n_descendants <= _K) {\n      for (int j = 0; j < n->n_descendants; j++) {\n\tresult->push_back(n->children[j]);\n      }\n    } else {\n      bool side = Distance::side(n, v, _f, &_random);\n\n      _get_nns(v, n->children[side], result, limit);\n      if (result->size() < (size_t)limit)\n\t_get_nns(v, n->children[!side], result, limit);\n    }\n  }\n\n  void _get_all_nns(const T* v, size_t n, vector<int>* result) {\n    std::priority_queue<pair<T, int> > q;\n\n    for (size_t i = 0; i < _roots.size(); i++) {\n      q.push(make_pair(numeric_limits<T>::infinity(), _roots[i]));\n    }\n\n    vector<int> nns;\n    while (nns.size() < n * _roots.size() && !q.empty()) {\n      const pair<T, int>& top = q.top();\n      int i = top.second;\n      const typename Distance::node* n = _get(top.second);\n      q.pop();\n      if (n->n_descendants == 1) {\n\tnns.push_back(i);\n      } else if (n->n_descendants <= _K) {\n\tfor (int x = 0; x < n->n_descendants; x++) {\n\t  int j = n->children[x];\n\t  nns.push_back(j);\n\t}\t\n      } else{\n\tT margin = Distance::margin(n, v, _f);\n\tq.push(make_pair(+margin, n->children[1]));\n\tq.push(make_pair(-margin, n->children[0]));\n      }\n    }\n\n    sort(nns.begin(), nns.end());\n    vector<pair<T, int> > nns_dist;\n    int last = -1;\n    for (size_t i = 0; i < nns.size(); i++) {\n      int j = nns[i];\n      if (j == last)\n\tcontinue;\n      last = j;\n      nns_dist.push_back(make_pair(Distance::distance(v, _get(j)->v, _f), j));\n    }\n\n    sort(nns_dist.begin(), nns_dist.end());\n    for (size_t i = 0; i < nns_dist.size() && result->size() < n; i++) {\n      result->push_back(nns_dist[i].second);\n    }\n  }\n};\n\ntemplate<typename T, typename Distance>\nclass AnnoyIndexPython : public AnnoyIndex<T, Distance > {\npublic:\n  AnnoyIndexPython(int f): AnnoyIndex<T, Distance>(f) {}\n  void add_item_py(int item, const python::list& v) {\n    vector<T> w;\n    for (int z = 0; z < this->_f; z++)\n      w.push_back(python::extract<T>(v[z]));\n\n    this->add_item(item, &w[0]);\n  }\n  python::list get_nns_by_item_py(int item, size_t n) {\n    vector<int> result;\n    this->get_nns_by_item(item, n, &result);\n    python::list l;\n    for (size_t i = 0; i < result.size(); i++)\n      l.append(result[i]);\n    return l;\n  }\n  python::list get_nns_by_vector_py(python::list v, size_t n) {\n    vector<T> w(this->_f);\n    for (int z = 0; z < this->_f; z++)\n      w[z] = python::extract<T>(v[z]);\n    vector<int> result;\n    this->get_nns_by_vector(&w[0], n, &result);\n    python::list l;\n    for (size_t i = 0; i < result.size(); i++)\n      l.append(result[i]);\n    return l;\n  }\n  python::list get_item_vector_py(int item) {\n    const typename Distance::node* m = this->_get(item);\n    const T* v = m->v;\n    python::list l;\n    for (int z = 0; z < this->_f; z++) {\n      l.append(v[z]);\n    }\n    return l;\n  }\n};\n\ntemplate<typename C>\nvoid expose_methods(python::class_<C> c) {\n  c.def(\"add_item\",          &C::add_item_py)\n    .def(\"build\",             &C::build)\n    .def(\"save\",              &C::save)\n    .def(\"load\",              &C::load)\n    .def(\"unload\",            &C::unload)\n    .def(\"get_distance\",      &C::get_distance)\n    .def(\"get_nns_by_item\",   &C::get_nns_by_item_py)\n    .def(\"get_nns_by_vector\", &C::get_nns_by_vector_py)\n    .def(\"get_item_vector\",   &C::get_item_vector_py)\n    .def(\"get_n_items\",       &C::get_n_items);\n}\n\nBOOST_PYTHON_MODULE(annoylib)\n{\n  expose_methods(python::class_<AnnoyIndexPython<float, Angular<float> > >(\"AnnoyIndexAngular\", python::init<int>()));\n  expose_methods(python::class_<AnnoyIndexPython<float, Euclidean<float> > >(\"AnnoyIndexEuclidean\", python::init<int>()));\n}\n", "meta": {"hexsha": "3d716c3c273960ca609acd5aca64341fd98d3d7f", "size": 17170, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/annoylib.cc", "max_stars_repo_name": "ummae/annoy", "max_stars_repo_head_hexsha": "bddca13ad0c1481db21ce68e8796288142aca907", "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/annoylib.cc", "max_issues_repo_name": "ummae/annoy", "max_issues_repo_head_hexsha": "bddca13ad0c1481db21ce68e8796288142aca907", "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/annoylib.cc", "max_forks_repo_name": "ummae/annoy", "max_forks_repo_head_hexsha": "bddca13ad0c1481db21ce68e8796288142aca907", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T13:29:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T13:29:05.000Z", "avg_line_length": 29.5017182131, "max_line_length": 122, "alphanum_fraction": 0.6028538148, "num_tokens": 5196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18572181923758121}}
{"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_SIMD_FUNCTION_BITWISE_XOR_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_BITWISE_XOR_HPP_INCLUDED\n\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/detail/traits.hpp>\n#include <boost/simd/detail/nsm.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  BOOST_DISPATCH_OVERLOAD_IF( bitwise_xor_\n                            , (typename A0,typename A1,typename X, typename Y)\n                            , (nsm::and_< nsm::not_ < std::is_same<A0,A1> >\n                                            , nsm::and_ < detail::is_native<X>\n                                                            , detail::is_native<Y>\n                                                            >\n                                            >\n                              )\n                            , bd::cpu_\n                            , bs::pack_<bd::arithmetic_<A0>,X>\n                            , bs::pack_<bd::arithmetic_<A1>,Y>\n                            )\n  {\n    BOOST_FORCEINLINE A0 operator()(const A0& a0, const A1& a1) const BOOST_NOEXCEPT\n    {\n      return bitwise_xor(a0, bitwise_cast<A0>(a1));\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "b9c4a74f74804de13df05d67138c09f69188efe7", "size": 1675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/bitwise_xor.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/bitwise_xor.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/bitwise_xor.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.9534883721, "max_line_length": 100, "alphanum_fraction": 0.4662686567, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.18551996674150914}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <optional>\n#include <ostream>\n#include <pup.h>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"DataStructures/Tensor/EagerMath/Magnitude.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Domain.hpp\"\n#include \"Domain/FaceNormal.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/DirectionMap.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Domain/Tags/FaceNormal.hpp\"\n#include \"Domain/Tags/Faces.hpp\"\n#include \"Domain/Tags/SurfaceJacobian.hpp\"\n#include \"Elliptic/BoundaryConditions/ApplyBoundaryCondition.hpp\"\n#include \"Elliptic/DiscontinuousGalerkin/DgOperator.hpp\"\n#include \"Elliptic/DiscontinuousGalerkin/SubdomainOperator/Tags.hpp\"\n#include \"Elliptic/DiscontinuousGalerkin/Tags.hpp\"\n#include \"Elliptic/Systems/GetSourcesComputer.hpp\"\n#include \"Elliptic/Utilities/ApplyAt.hpp\"\n#include \"NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.hpp\"\n#include \"NumericalAlgorithms/DiscontinuousGalerkin/Tags.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Parallel/PupStlCpp17.hpp\"\n#include \"ParallelAlgorithms/LinearSolver/Schwarz/ElementCenteredSubdomainData.hpp\"\n#include \"ParallelAlgorithms/LinearSolver/Schwarz/OverlapHelpers.hpp\"\n#include \"ParallelAlgorithms/LinearSolver/Schwarz/SubdomainOperator.hpp\"\n#include \"ParallelAlgorithms/LinearSolver/Schwarz/Tags.hpp\"\n#include \"Utilities/EqualWithinRoundoff.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// Items related to the restriction of the DG operator to an element-centered\n/// subdomain\nnamespace elliptic::dg::subdomain_operator {\n\nnamespace detail {\n// Wrap the `Tag` in `LinearSolver::Schwarz::Tags::Overlaps`, except if it is\n// included in `TakeFromCenterTags`.\ntemplate <typename Tag, typename Dim, typename OptionsGroup,\n          typename TakeFromCenterTags>\nstruct make_overlap_tag_impl {\n  using type = tmpl::conditional_t<\n      tmpl::list_contains_v<TakeFromCenterTags, Tag>, Tag,\n      LinearSolver::Schwarz::Tags::Overlaps<Tag, Dim::value, OptionsGroup>>;\n};\n\n// Wrap the `Tag` in `Tags::NeighborMortars`\ntemplate <typename Tag, typename Dim>\nstruct make_neighbor_mortars_tag_impl {\n  using type = Tags::NeighborMortars<Tag, Dim::value>;\n};\n}  // namespace detail\n\n/*!\n * \\brief The elliptic DG operator on an element-centered subdomain\n *\n * This operator is a restriction of the full (linearized) DG-operator to an\n * element-centered subdomain with a few points overlap into neighboring\n * elements. It is a `LinearSolver::Schwarz::SubdomainOperator` to be used with\n * the Schwarz linear solver when it solves the elliptic DG operator.\n *\n * This operator requires the following tags are available on overlap regions\n * with neighboring elements:\n *\n * - Geometric quantities provided by\n *   `elliptic::dg::subdomain_operator::InitializeSubdomain`.\n * - All `System::fluxes_computer::argument_tags` and\n *   `System::sources_computer::argument_tags` (or\n *   `System::sources_computer_linearized::argument_tags` for nonlinear\n *   systems), except those listed in `ArgsTagsFromCenter`. The latter will be\n *   taken from the central element's DataBox, so they don't need to be made\n *   available on overlaps.\n * - The `System::fluxes_computer::argument_tags` on internal and external\n *   interfaces, except those listed in `System::fluxes_computer::volume_tags`.\n *\n * Some of these tags may require communication between elements. For example,\n * nonlinear system fields are constant background fields for the linearized DG\n * operator, but are updated in every nonlinear solver iteration. Therefore, the\n * updated nonlinear fields must be communicated across overlaps between\n * nonlinear solver iterations. To perform the communication you can use\n * `LinearSolver::Schwarz::Actions::SendOverlapFields` and\n * `LinearSolver::Schwarz::Actions::ReceiveOverlapFields`, setting\n * `RestrictToOverlap` to `false`. See\n * `LinearSolver::Schwarz::SubdomainOperator` for details.\n *\n * \\par Overriding boundary conditions\n * Sometimes the subdomain operator should not use the boundary conditions that\n * have been selected when setting up the domain. For example, when the\n * subdomain operator is cached between non-linear solver iterations but the\n * boundary conditions depend on the non-linear fields, the preconditioning can\n * become ineffective (see\n * `LinearSolver::Schwarz::Actions::ResetSubdomainSolver`). Another example is\n * `elliptic::subdomain_preconditioners::MinusLaplacian`, where an auxiliary\n * Poisson system is used for preconditioning that doesn't have boundary\n * conditions set up in the domain. In these cases, the boundary conditions used\n * for the subdomain operator can be overridden with the optional\n * `override_boundary_conditions` argument to the `operator()`. If the\n * overriding boundary conditions are different from those listed in\n * `Metavariables::factory_creation`, you can supply the list of\n * boundary-condition classes to the `BoundaryConditionClasses` template\n * parameter. Note that the subdomain operator always applies the _linearized_\n * boundary conditions.\n *\n * \\warning The subdomain operator hasn't been tested with periodic boundary\n * conditions so far.\n */\ntemplate <typename System, typename OptionsGroup,\n          typename ArgsTagsFromCenter = tmpl::list<>,\n          typename BoundaryConditionClasses = tmpl::list<>>\nstruct SubdomainOperator\n    : LinearSolver::Schwarz::SubdomainOperator<System::volume_dim> {\n public:\n  using system = System;\n  using options_group = OptionsGroup;\n\n private:\n  static constexpr size_t Dim = System::volume_dim;\n\n  // Operator applications happen sequentially so we don't have to keep track of\n  // the temporal id\n  static constexpr size_t temporal_id = 0;\n\n  // The subdomain operator always applies the linearized DG operator\n  static constexpr bool linearized = true;\n\n  using BoundaryConditionsBase = typename System::boundary_conditions_base;\n\n  // These are the arguments that we need to retrieve from the DataBox and pass\n  // to the functions in `elliptic::dg`, both on the central element and on\n  // neighbors\n  using prepare_args_tags =\n      tmpl::list<domain::Tags::Element<Dim>, domain::Tags::Mesh<Dim>,\n                 domain::Tags::InverseJacobian<Dim, Frame::ElementLogical,\n                                               Frame::Inertial>,\n                 domain::Tags::Faces<Dim, domain::Tags::FaceNormal<Dim>>,\n                 domain::Tags::Faces<\n                     Dim, domain::Tags::UnnormalizedFaceNormalMagnitude<Dim>>,\n                 ::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>,\n                 ::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>>;\n  using apply_args_tags = tmpl::list<\n      domain::Tags::Element<Dim>, domain::Tags::Mesh<Dim>,\n      domain::Tags::InverseJacobian<Dim, Frame::ElementLogical,\n                                    Frame::Inertial>,\n      domain::Tags::DetInvJacobian<Frame::ElementLogical, Frame::Inertial>,\n      domain::Tags::Faces<Dim,\n                          domain::Tags::UnnormalizedFaceNormalMagnitude<Dim>>,\n      domain::Tags::Faces<Dim, domain::Tags::DetSurfaceJacobian<\n                                   Frame::ElementLogical, Frame::Inertial>>,\n      ::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>,\n      ::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>,\n      ::Tags::Mortars<domain::Tags::DetSurfaceJacobian<Frame::ElementLogical,\n                                                       Frame::Inertial>,\n                      Dim>,\n      elliptic::dg::Tags::PenaltyParameter, elliptic::dg::Tags::Massive>;\n  using fluxes_args_tags = typename System::fluxes_computer::argument_tags;\n  using sources_args_tags =\n      typename elliptic::get_sources_computer<System,\n                                              linearized>::argument_tags;\n\n  // We need the fluxes args also on interfaces (internal and external). The\n  // volume tags are the subset that don't have to be taken from interfaces.\n  using fluxes_args_volume_tags = typename System::fluxes_computer::volume_tags;\n\n  // These tags can be taken directly from the central element's DataBox, even\n  // when evaluating neighbors\n  using args_tags_from_center = tmpl::remove_duplicates<\n      tmpl::push_back<ArgsTagsFromCenter, elliptic::dg::Tags::PenaltyParameter,\n                      elliptic::dg::Tags::Massive>>;\n\n  // Data on neighbors is stored in the central element's DataBox in\n  // `LinearSolver::Schwarz::Tags::Overlaps` maps, so we wrap the argument tags\n  // with this prefix\n  using make_overlap_tag =\n      detail::make_overlap_tag_impl<tmpl::_1, tmpl::pin<tmpl::size_t<Dim>>,\n                                    tmpl::pin<OptionsGroup>,\n                                    tmpl::pin<args_tags_from_center>>;\n  using prepare_args_tags_overlap =\n      tmpl::transform<prepare_args_tags, make_overlap_tag>;\n  using apply_args_tags_overlap =\n      tmpl::transform<apply_args_tags, make_overlap_tag>;\n  using fluxes_args_tags_overlap =\n      tmpl::transform<fluxes_args_tags, make_overlap_tag>;\n  using sources_args_tags_overlap =\n      tmpl::transform<sources_args_tags, make_overlap_tag>;\n  using fluxes_args_tags_overlap_faces = tmpl::transform<\n      domain::make_faces_tags<Dim, fluxes_args_tags, fluxes_args_volume_tags>,\n      make_overlap_tag>;\n\n  // We also need some data on the remote side of all neighbors' mortars. Such\n  // data is stored in the central element's DataBox in `Tags::NeighborMortars`\n  // maps\n  using make_neighbor_mortars_tag =\n      detail::make_neighbor_mortars_tag_impl<tmpl::_1,\n                                             tmpl::pin<tmpl::size_t<Dim>>>;\n\n public:\n  /// \\warning This function is not thread-safe because it accesses mutable\n  /// memory buffers.\n  template <typename ResultTags, typename OperandTags, typename DbTagsList>\n  void operator()(\n      const gsl::not_null<\n          LinearSolver::Schwarz::ElementCenteredSubdomainData<Dim, ResultTags>*>\n          result,\n      const LinearSolver::Schwarz::ElementCenteredSubdomainData<\n          Dim, OperandTags>& operand,\n      const db::DataBox<DbTagsList>& box,\n      const std::unordered_map<std::pair<size_t, Direction<Dim>>,\n                               const BoundaryConditionsBase&,\n                               boost::hash<std::pair<size_t, Direction<Dim>>>>&\n          override_boundary_conditions = {}) const {\n    // Used to retrieve items out of the DataBox to forward to functions. This\n    // replaces a long series of db::get calls.\n    const auto get_items = [](const auto&... args) {\n      return std::forward_as_tuple(args...);\n    };\n\n    // Retrieve data out of the DataBox\n    using tags_to_retrieve = tmpl::flatten<tmpl::list<\n        domain::Tags::Domain<Dim>, domain::Tags::Element<Dim>,\n        ::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>,\n        // Data on overlaps with neighbors\n        tmpl::transform<\n            tmpl::flatten<tmpl::list<\n                Tags::ExtrudingExtent, domain::Tags::Element<Dim>,\n                domain::Tags::Mesh<Dim>,\n                domain::Tags::Faces<\n                    Dim, domain::Tags::UnnormalizedFaceNormalMagnitude<Dim>>,\n                ::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>,\n                ::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>,\n                // Data on the remote side of the neighbor's mortars\n                tmpl::transform<\n                    tmpl::list<\n                        domain::Tags::Mesh<Dim>,\n                        domain::Tags::UnnormalizedFaceNormalMagnitude<Dim>,\n                        domain::Tags::Mesh<Dim - 1>,\n                        ::Tags::MortarSize<Dim - 1>>,\n                    make_neighbor_mortars_tag>>>,\n            make_overlap_tag>>>;\n    const auto& [domain, central_element, central_mortar_meshes,\n                 all_overlap_extents, all_neighbor_elements,\n                 all_neighbor_meshes,\n                 all_neighbor_face_normal_magnitudes,\n                 all_neighbor_mortar_meshes, all_neighbor_mortar_sizes,\n                 all_neighbors_neighbor_meshes,\n                 all_neighbors_neighbor_face_normal_magnitudes,\n                 all_neighbors_neighbor_mortar_meshes,\n                 all_neighbors_neighbor_mortar_sizes] =\n        db::apply<tags_to_retrieve>(get_items, box);\n    const auto fluxes_args = db::apply<fluxes_args_tags>(get_items, box);\n    const auto sources_args = db::apply<sources_args_tags>(get_items, box);\n    using FluxesArgs = std::decay_t<decltype(fluxes_args)>;\n    DirectionMap<Dim, FluxesArgs> fluxes_args_on_faces{};\n    for (const auto& direction : Direction<Dim>::all_directions()) {\n      fluxes_args_on_faces.emplace(\n          direction, elliptic::util::apply_at<\n                         domain::make_faces_tags<Dim, fluxes_args_tags,\n                                                 fluxes_args_volume_tags>,\n                         fluxes_args_volume_tags>(get_items, box, direction));\n    }\n\n    // Setup boundary conditions\n    const auto apply_boundary_condition =\n        [&box, &local_domain = domain, &override_boundary_conditions](\n            const ElementId<Dim>& local_element_id,\n            const Direction<Dim>& local_direction, auto is_overlap,\n            const auto& map_keys, const auto... fields_and_fluxes) {\n          constexpr bool is_overlap_v =\n              std::decay_t<decltype(is_overlap)>::value;\n          // Get boundary conditions from domain, or use overridden boundary\n          // conditions\n          const auto& boundary_condition = [&local_domain, &local_element_id,\n                                            &local_direction,\n                                            &override_boundary_conditions]()\n              -> const BoundaryConditionsBase& {\n            if (not override_boundary_conditions.empty()) {\n              const auto found_overridden_boundary_conditions =\n                  override_boundary_conditions.find(\n                      {local_element_id.block_id(), local_direction});\n              ASSERT(found_overridden_boundary_conditions !=\n                         override_boundary_conditions.end(),\n                     \"Overriding boundary conditions in subdomain operator, \"\n                     \"but none is available for block \"\n                         << local_element_id.block_id() << \" in direction \"\n                         << local_direction\n                         << \". Make sure you have considered this external \"\n                            \"boundary of the subdomain. If this is \"\n                            \"intentional, add support to \"\n                            \"elliptic::dg::SubdomainOperator.\");\n              return found_overridden_boundary_conditions->second;\n            }\n            const auto& boundary_conditions =\n                local_domain.blocks()\n                    .at(local_element_id.block_id())\n                    .external_boundary_conditions();\n            ASSERT(boundary_conditions.contains(local_direction),\n                   \"No boundary condition is available in block \"\n                       << local_element_id.block_id() << \" in direction \"\n                       << local_direction\n                       << \". Make sure you are setting up boundary conditions \"\n                          \"when creating the domain.\");\n            ASSERT(\n                dynamic_cast<const BoundaryConditionsBase*>(\n                    boundary_conditions.at(local_direction).get()) != nullptr,\n                \"The boundary condition in block \"\n                    << local_element_id.block_id() << \" in direction \"\n                    << local_direction\n                    << \" has an unexpected type. Make sure it derives off the \"\n                       \"'boundary_conditions_base' class set in the system.\");\n            return dynamic_cast<const BoundaryConditionsBase&>(\n                *boundary_conditions.at(local_direction));\n          }();\n          elliptic::apply_boundary_condition<\n              linearized,\n              tmpl::conditional_t<is_overlap_v, make_overlap_tag, void>,\n              BoundaryConditionClasses>(boundary_condition, box, map_keys,\n                                        fields_and_fluxes...);\n        };\n\n    // Check if the subdomain data is sparse, i.e. if some elements have zero\n    // data. If they are, the operator is a lot cheaper to apply due to its\n    // linearity.\n    std::unordered_set<ElementId<Dim>> elements_in_subdomain{\n        central_element.id()};\n    std::unordered_set<ElementId<Dim>> elements_with_zero_data{};\n    if (equal_within_roundoff(operand.element_data, 0.)) {\n      elements_with_zero_data.insert(central_element.id());\n    }\n    for (const auto& [overlap_id, overlap_data] : operand.overlap_data) {\n      elements_in_subdomain.insert(overlap_id.second);\n      if (equal_within_roundoff(overlap_data, 0.)) {\n        elements_with_zero_data.insert(overlap_id.second);\n      }\n    }\n    const auto is_in_subdomain =\n        [&elements_in_subdomain](const ElementId<Dim>& element_id) {\n          return elements_in_subdomain.find(element_id) !=\n                 elements_in_subdomain.end();\n        };\n    const auto data_is_zero = [&elements_with_zero_data, &is_in_subdomain](\n                                  const ElementId<Dim>& element_id) {\n      return elements_with_zero_data.find(element_id) !=\n                 elements_with_zero_data.end() or\n             // Data outside the subdomain is zero by definition\n             not is_in_subdomain(element_id);\n    };\n    const bool central_data_is_zero = data_is_zero(central_element.id());\n\n    // The subdomain operator essentially does two sweeps over all elements in\n    // the subdomain: In the first sweep it prepares the mortar data and stores\n    // them on both sides of all mortars, and in the second sweep it consumes\n    // the mortar data to apply the operator. This implementation is relatively\n    // simple because it can re-use the implementation for the parallel DG\n    // operator. However, it is also possible to apply the subdomain operator in\n    // a single sweep over all elements, incrementally building up the mortar\n    // data and applying boundary corrections immediately to both adjacent\n    // elements once the data is available. That approach is possibly a\n    // performance optimization but requires re-implementing a lot of logic for\n    // the DG operator here. It should be considered once the subdomain operator\n    // has been identified as the performance bottleneck. An alternative to\n    // optimizing the subdomain operator performance is to precondition the\n    // subdomain solve with a _much_ simpler subdomain operator, such as a\n    // finite-difference Laplacian, so fewer applications of the more expensive\n    // DG subdomain operator are necessary.\n\n    // 1. Prepare mortar data on all elements in the subdomain and store them on\n    //    mortars, reorienting if needed\n    //\n    // Prepare central element\n    const auto apply_boundary_condition_center =\n        [&apply_boundary_condition, &local_central_element = central_element](\n            const Direction<Dim>& local_direction,\n            const auto... fields_and_fluxes) {\n          apply_boundary_condition(local_central_element.id(), local_direction,\n                                   std::false_type{}, local_direction,\n                                   fields_and_fluxes...);\n        };\n    db::apply<prepare_args_tags>(\n        [this, &operand](const auto&... args) {\n          elliptic::dg::prepare_mortar_data<System, linearized>(\n              make_not_null(&central_auxiliary_vars_),\n              make_not_null(&central_auxiliary_fluxes_),\n              make_not_null(&central_primal_fluxes_),\n              make_not_null(&central_mortar_data_), operand.element_data,\n              args...);\n        },\n        box, temporal_id, apply_boundary_condition_center, fluxes_args,\n        sources_args, fluxes_args_on_faces, data_is_zero);\n    // Prepare neighbors\n    for (const auto& [direction, neighbors] : central_element.neighbors()) {\n      const auto& orientation = neighbors.orientation();\n      const auto direction_from_neighbor = orientation(direction.opposite());\n      for (const auto& neighbor_id : neighbors) {\n        const LinearSolver::Schwarz::OverlapId<Dim> overlap_id{direction,\n                                                               neighbor_id};\n        const auto& overlap_extent = all_overlap_extents.at(overlap_id);\n        const auto& neighbor = all_neighbor_elements.at(overlap_id);\n        const auto& neighbor_mesh = all_neighbor_meshes.at(overlap_id);\n        const auto& mortar_id = overlap_id;\n        const auto& mortar_mesh = central_mortar_meshes.at(mortar_id);\n        const ::dg::MortarId<Dim> mortar_id_from_neighbor{\n            direction_from_neighbor, central_element.id()};\n        const bool neighbor_data_is_zero = data_is_zero(neighbor_id);\n\n        // Intercept empty overlaps. In the unlikely case that overlaps have\n        // zero extent, meaning no point of the neighbor is part of the\n        // subdomain (which is fairly useless, except for testing), the\n        // subdomain is identical to the central element and no communication\n        // with neighbors is necessary. We can just handle the mortar between\n        // central element and neighbor and continue.\n        if (UNLIKELY(overlap_extent == 0)) {\n          const auto& mortar_mesh_from_neighbor =\n              all_neighbor_mortar_meshes.at(overlap_id)\n                  .at(mortar_id_from_neighbor);\n          const auto& mortar_size_from_neighbor =\n              all_neighbor_mortar_sizes.at(overlap_id)\n                  .at(mortar_id_from_neighbor);\n          auto remote_boundary_data =\n              elliptic::dg::zero_boundary_data_on_mortar<\n                  typename System::primal_fields,\n                  typename System::primal_fluxes>(\n                  direction_from_neighbor, neighbor_mesh,\n                  all_neighbor_face_normal_magnitudes.at(overlap_id)\n                      .at(direction_from_neighbor),\n                  mortar_mesh_from_neighbor, mortar_size_from_neighbor);\n          if (not orientation.is_aligned()) {\n            remote_boundary_data.orient_on_slice(\n                mortar_mesh_from_neighbor.extents(),\n                direction_from_neighbor.dimension(), orientation.inverse_map());\n          }\n          central_mortar_data_.at(mortar_id).remote_insert(\n              temporal_id, std::move(remote_boundary_data));\n          continue;\n        }\n\n        // Copy the central element's mortar data to the neighbor\n        if (not(central_data_is_zero and neighbor_data_is_zero)) {\n          auto oriented_mortar_data =\n              central_mortar_data_.at(mortar_id).local_data(temporal_id);\n          if (not orientation.is_aligned()) {\n            oriented_mortar_data.orient_on_slice(\n                mortar_mesh.extents(), direction.dimension(), orientation);\n          }\n          neighbors_mortar_data_[overlap_id][::dg::MortarId<Dim>{\n                                                 direction_from_neighbor,\n                                                 central_element.id()}]\n              .remote_insert(temporal_id, std::move(oriented_mortar_data));\n        }\n\n        // Now we switch perspective to the neighbor. First, we extend the\n        // overlap data to the full neighbor mesh by padding it with zeros. This\n        // is necessary because spectral operators such as derivatives require\n        // data on the full mesh.\n        if (not neighbor_data_is_zero) {\n          LinearSolver::Schwarz::extended_overlap_data(\n              make_not_null(&extended_operand_vars_[overlap_id]),\n              operand.overlap_data.at(overlap_id), neighbor_mesh.extents(),\n              overlap_extent, direction_from_neighbor);\n        }\n\n        const auto apply_boundary_condition_neighbor =\n            [&apply_boundary_condition, &local_neighbor_id = neighbor_id,\n             &overlap_id](const Direction<Dim>& local_direction,\n                          const auto... fields_and_fluxes) {\n              apply_boundary_condition(\n                  local_neighbor_id, local_direction, std::true_type{},\n                  std::forward_as_tuple(overlap_id, local_direction),\n                  fields_and_fluxes...);\n            };\n\n        const auto fluxes_args_on_overlap =\n            elliptic::util::apply_at<fluxes_args_tags_overlap,\n                                     args_tags_from_center>(get_items, box,\n                                                            overlap_id);\n        const auto sources_args_on_overlap =\n            elliptic::util::apply_at<sources_args_tags_overlap,\n                                     args_tags_from_center>(get_items, box,\n                                                            overlap_id);\n        DirectionMap<Dim, FluxesArgs> fluxes_args_on_overlap_faces{};\n        for (const auto& neighbor_direction :\n             Direction<Dim>::all_directions()) {\n          fluxes_args_on_overlap_faces.emplace(\n              neighbor_direction,\n              elliptic::util::apply_at<fluxes_args_tags_overlap_faces,\n                                       args_tags_from_center>(\n                  get_items, box,\n                  std::forward_as_tuple(overlap_id, neighbor_direction)));\n        }\n\n        elliptic::util::apply_at<prepare_args_tags_overlap,\n                                 args_tags_from_center>(\n            [this, &overlap_id](const auto&... args) {\n              elliptic::dg::prepare_mortar_data<System, linearized>(\n                  make_not_null(&neighbors_auxiliary_vars_[overlap_id]),\n                  make_not_null(&neighbors_auxiliary_fluxes_[overlap_id]),\n                  make_not_null(&neighbors_primal_fluxes_[overlap_id]),\n                  make_not_null(&neighbors_mortar_data_[overlap_id]),\n                  extended_operand_vars_[overlap_id], args...);\n            },\n            box, overlap_id, temporal_id, apply_boundary_condition_neighbor,\n            fluxes_args_on_overlap, sources_args_on_overlap,\n            fluxes_args_on_overlap_faces, data_is_zero);\n\n        // Copy this neighbor's mortar data to the other side of the mortars. On\n        // the other side we either have the central element, or another element\n        // that may or may not be part of the subdomain.\n        const auto& neighbor_mortar_meshes =\n            all_neighbor_mortar_meshes.at(overlap_id);\n        for (const auto& neighbor_mortar_id_and_data :\n             neighbors_mortar_data_.at(overlap_id)) {\n          // No structured bindings because capturing these in lambdas doesn't\n          // work until C++20\n          const auto& neighbor_mortar_id = neighbor_mortar_id_and_data.first;\n          const auto& neighbor_mortar_data = neighbor_mortar_id_and_data.second;\n          const auto& neighbor_direction = neighbor_mortar_id.first;\n          const auto& neighbors_neighbor_id = neighbor_mortar_id.second;\n          // No need to do anything on external boundaries\n          if (neighbors_neighbor_id == ElementId<Dim>::external_boundary_id()) {\n            continue;\n          }\n          const auto& neighbor_orientation =\n              neighbor.neighbors().at(neighbor_direction).orientation();\n          const auto neighbors_neighbor_direction =\n              neighbor_orientation(neighbor_direction.opposite());\n          const ::dg::MortarId<Dim> mortar_id_from_neighbors_neighbor{\n              neighbors_neighbor_direction, neighbor_id};\n          const auto send_mortar_data =\n              [&neighbor_orientation, &neighbor_mortar_meshes,\n               &neighbor_mortar_data, &neighbor_mortar_id, &neighbor_direction,\n               &neighbor_data_is_zero,\n               &data_is_zero](auto& remote_mortar_data,\n                              const ElementId<Dim>& remote_element_id) {\n                if (neighbor_data_is_zero and data_is_zero(remote_element_id)) {\n                  return;\n                }\n                const auto& neighbor_mortar_mesh =\n                    neighbor_mortar_meshes.at(neighbor_mortar_id);\n                auto oriented_neighbor_mortar_data =\n                    neighbor_mortar_data.local_data(temporal_id);\n                if (not neighbor_orientation.is_aligned()) {\n                  oriented_neighbor_mortar_data.orient_on_slice(\n                      neighbor_mortar_mesh.extents(),\n                      neighbor_direction.dimension(), neighbor_orientation);\n                }\n                remote_mortar_data.remote_insert(\n                    temporal_id, std::move(oriented_neighbor_mortar_data));\n              };\n          if (neighbors_neighbor_id == central_element.id() and\n              mortar_id_from_neighbors_neighbor == mortar_id) {\n            send_mortar_data(central_mortar_data_.at(mortar_id),\n                             central_element.id());\n            continue;\n          }\n          // Determine whether the neighbor's neighbor overlaps with the\n          // subdomain and find its overlap ID if it does.\n          const auto neighbors_neighbor_overlap_id =\n              [&local_all_neighbor_mortar_meshes = all_neighbor_mortar_meshes,\n               &neighbors_neighbor_id, &mortar_id_from_neighbors_neighbor,\n               &is_in_subdomain]()\n              -> std::optional<LinearSolver::Schwarz::OverlapId<Dim>> {\n            if (not is_in_subdomain(neighbors_neighbor_id)) {\n              return std::nullopt;\n            }\n            for (const auto& [local_overlap_id, local_mortar_meshes] :\n                 local_all_neighbor_mortar_meshes) {\n              if (local_overlap_id.second != neighbors_neighbor_id) {\n                continue;\n              }\n              for (const auto& local_mortar_id_and_mesh : local_mortar_meshes) {\n                if (local_mortar_id_and_mesh.first ==\n                    mortar_id_from_neighbors_neighbor) {\n                  return local_overlap_id;\n                }\n              }\n            }\n            ERROR(\"The neighbor's neighbor \"\n                  << neighbors_neighbor_id\n                  << \" is part of the subdomain, but we didn't find its \"\n                     \"overlap ID. This is a bug, so please file an issue.\");\n          }();\n          if (neighbors_neighbor_overlap_id.has_value()) {\n            // The neighbor's neighbor is part of the subdomain so we copy the\n            // mortar data over. Once the loop is complete we will also have\n            // received mortar data back. At that point, both neighbors have a\n            // copy of each other's mortar data, which is the subject of the\n            // possible optimizations mentioned above. Note that the data may\n            // differ by orientations.\n            send_mortar_data(\n                neighbors_mortar_data_[*neighbors_neighbor_overlap_id]\n                                      [mortar_id_from_neighbors_neighbor],\n                neighbors_neighbor_overlap_id->second);\n          } else if (not neighbor_data_is_zero) {\n            // The neighbor's neighbor does not overlap with the subdomain, so\n            // we don't copy mortar data and also don't expect to receive any.\n            // Instead, we assume the data on it is zero and manufacture\n            // appropriate remote boundary data.\n            const auto& neighbors_neighbor_mortar_mesh =\n                all_neighbors_neighbor_mortar_meshes.at(overlap_id)\n                    .at(neighbor_mortar_id);\n            auto zero_mortar_data = elliptic::dg::zero_boundary_data_on_mortar<\n                typename System::primal_fields, typename System::primal_fluxes>(\n                neighbors_neighbor_direction,\n                all_neighbors_neighbor_meshes.at(overlap_id)\n                    .at(neighbor_mortar_id),\n                all_neighbors_neighbor_face_normal_magnitudes.at(overlap_id)\n                    .at(neighbor_mortar_id),\n                neighbors_neighbor_mortar_mesh,\n                all_neighbors_neighbor_mortar_sizes.at(overlap_id)\n                    .at(neighbor_mortar_id));\n            // The data is zero, but auxiliary quantities such as the face\n            // normal magnitude may need re-orientation\n            if (not neighbor_orientation.is_aligned()) {\n              zero_mortar_data.orient_on_slice(\n                  neighbors_neighbor_mortar_mesh.extents(),\n                  neighbors_neighbor_direction.dimension(),\n                  neighbor_orientation.inverse_map());\n            }\n            neighbors_mortar_data_.at(overlap_id)\n                .at(neighbor_mortar_id)\n                .remote_insert(temporal_id, std::move(zero_mortar_data));\n          }\n        }  // loop over neighbor's mortars\n      }    // loop over neighbors\n    }      // loop over directions\n\n    // 2. Apply the operator on all elements in the subdomain\n    //\n    // Apply on central element\n    db::apply<apply_args_tags>(\n        [this, &result, &operand](const auto&... args) {\n          elliptic::dg::apply_operator<System, linearized>(\n              make_not_null(&result->element_data),\n              make_not_null(&central_mortar_data_), operand.element_data,\n              central_primal_fluxes_, args...);\n        },\n        box, temporal_id, sources_args, data_is_zero);\n    // Apply on neighbors\n    for (const auto& [direction, neighbors] : central_element.neighbors()) {\n      const auto& orientation = neighbors.orientation();\n      const auto direction_from_neighbor = orientation(direction.opposite());\n      for (const auto& neighbor_id : neighbors) {\n        const LinearSolver::Schwarz::OverlapId<Dim> overlap_id{direction,\n                                                               neighbor_id};\n        const auto& overlap_extent = all_overlap_extents.at(overlap_id);\n        const auto& neighbor_mesh = all_neighbor_meshes.at(overlap_id);\n\n        if (UNLIKELY(overlap_extent == 0)) {\n          continue;\n        }\n\n        elliptic::util::apply_at<apply_args_tags_overlap,\n                                 args_tags_from_center>(\n            [this, &overlap_id](const auto&... args) {\n              elliptic::dg::apply_operator<System, linearized>(\n                  make_not_null(&extended_results_[overlap_id]),\n                  make_not_null(&neighbors_mortar_data_.at(overlap_id)),\n                  extended_operand_vars_.at(overlap_id),\n                  neighbors_primal_fluxes_.at(overlap_id), args...);\n            },\n            box, overlap_id, temporal_id,\n            elliptic::util::apply_at<sources_args_tags_overlap,\n                                     args_tags_from_center>(get_items, box,\n                                                            overlap_id),\n            data_is_zero);\n\n        // Restrict the extended operator data back to the subdomain, assuming\n        // we can discard any data outside the overlaps. WARNING: This\n        // assumption may break with changes to the DG operator that affect its\n        // sparsity. For example, multiplying the DG operator with the _full_\n        // inverse mass-matrix (\"massless\" scheme with no \"mass-lumping\"\n        // approximation) means that lifted boundary corrections bleed into the\n        // volume.\n        if (UNLIKELY(\n                result->overlap_data[overlap_id].number_of_grid_points() !=\n                operand.overlap_data.at(overlap_id).number_of_grid_points())) {\n          result->overlap_data[overlap_id].initialize(\n              operand.overlap_data.at(overlap_id).number_of_grid_points());\n        }\n        LinearSolver::Schwarz::data_on_overlap(\n            make_not_null(&result->overlap_data[overlap_id]),\n            extended_results_.at(overlap_id), neighbor_mesh.extents(),\n            overlap_extent, direction_from_neighbor);\n      }  // loop over neighbors\n    }    // loop over directions\n  }\n\n  // NOLINTNEXTLINE(google-runtime-references)\n  void pup(PUP::er& /*p*/) {}\n\n private:\n  // Memory buffers for repeated operator applications\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable Variables<typename System::auxiliary_fields>\n      central_auxiliary_vars_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable Variables<typename System::primal_fluxes> central_primal_fluxes_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable Variables<typename System::auxiliary_fluxes>\n      central_auxiliary_fluxes_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable LinearSolver::Schwarz::OverlapMap<\n      Dim, Variables<typename System::auxiliary_fields>>\n      neighbors_auxiliary_vars_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable LinearSolver::Schwarz::OverlapMap<\n      Dim, Variables<typename System::primal_fluxes>>\n      neighbors_primal_fluxes_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable LinearSolver::Schwarz::OverlapMap<\n      Dim, Variables<typename System::auxiliary_fluxes>>\n      neighbors_auxiliary_fluxes_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable LinearSolver::Schwarz::OverlapMap<\n      Dim, Variables<typename System::primal_fields>>\n      extended_operand_vars_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable LinearSolver::Schwarz::OverlapMap<\n      Dim, Variables<typename System::primal_fields>>\n      extended_results_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable ::dg::MortarMap<\n      Dim, elliptic::dg::MortarData<size_t, typename System::primal_fields,\n                                    typename System::primal_fluxes>>\n      central_mortar_data_{};\n  // NOLINTNEXTLINE(spectre-mutable)\n  mutable LinearSolver::Schwarz::OverlapMap<\n      Dim, ::dg::MortarMap<Dim, elliptic::dg::MortarData<\n                                    size_t, typename System::primal_fields,\n                                    typename System::primal_fluxes>>>\n      neighbors_mortar_data_{};\n};\n\n}  // namespace elliptic::dg::subdomain_operator\n", "meta": {"hexsha": "cd5cb9869328b51fa33b256f78be1e456730db1d", "size": 38094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Elliptic/DiscontinuousGalerkin/SubdomainOperator/SubdomainOperator.hpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-11T00:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T00:17:33.000Z", "max_issues_repo_path": "src/Elliptic/DiscontinuousGalerkin/SubdomainOperator/SubdomainOperator.hpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "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/Elliptic/DiscontinuousGalerkin/SubdomainOperator/SubdomainOperator.hpp", "max_forks_repo_name": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.9959839357, "max_line_length": 83, "alphanum_fraction": 0.646401008, "num_tokens": 7870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1855199630625036}}
{"text": "/* Copyright (C) 2016-2018 Alibaba Group Holding Limited\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#include <glog/logging.h>\n#include <Eigen/Dense>\n\n#include \"ps-plus/server/slice.h\"\n#include \"ps-plus/common/hashmap.h\"\n#include \"ps-plus/server/streaming_model_utils.h\"\n#include \"ps-plus/server/udf/simple_udf.h\"\n#include \"ps-plus/common/initializer/constant_initializer.h\"\n\nnamespace ps {\nnamespace server {\nnamespace udf {\n\nclass HashFeatureScoreFilter : public SimpleUdf<float, float, float, float, float ,int64_t> {\n public:\n  virtual Status SimpleRun(UdfContext* ctx, const float& decay_rate,\n                           const float& nonclk_weight, const float& clk_weight,\n                           const float& train_threshold,\n                           const float& export_threshold,\n                           const int64_t& cur_step) const {\n    Variable* variable = GetVariable(ctx);\n    if (variable == nullptr) {\n      return Status::ArgumentError(\"HashFeatureScoreFilter: Variable should not be empty\");\n    }\n\n    if (variable->GetData()->Shape().IsScalar()) {\n      return Status::ArgumentError(\"HashFeatureScoreFilter: Variable should not be Scalar\");\n    }\n\n    WrapperData<HashMap>* hashmap = dynamic_cast<WrapperData<HashMap>*>(variable->GetSlicer());\n    if (hashmap == nullptr) {\n      return Status::ArgumentError(\"HashFeatureScoreFilter: Variable Should be a Hash Variable\");\n    }\n\n    HashMap::HashMapStruct map;\n    if (hashmap->Internal().GetHashKeys(&map) != 0) {\n      return Status::Unknown(\"HashFeatureScoreFilter Get Hash Keys Error\");\n    }\n\n    auto& items = map.items;\n    if (!items.size()) {\n      return Status::Ok();\n    }\n\n    variable->SetFeaExportThreshold(export_threshold);\n\n    //1. decay fea stats\n    auto stats_vec = variable->GetStatsVec();\n    LOG_ASSERT(stats_vec.size()) << \"fea stats num eq 0.\";\n\n    Tensor* tensor = nullptr;\n    PS_CHECK_STATUS(variable->GetExistSlot(\"fea_stats\", &tensor));\n\n    size_t stats_num = stats_vec.size();\n    auto& shape = tensor->Shape();\n\n    LOG_ASSERT(shape.Size() == 2) << \"fea_stats should have 2 dims.\";\n    LOG_ASSERT(shape[1] == stats_num) << \"fea_stats dims 1 doesn't eq fea stats num.\";\n\n    CASES(tensor->Type(), {\n        T* pstats = tensor->Raw<T>();\n        T* dst;\n        for (size_t i = 0; i < items.size(); ++i) {\n          dst = pstats + items[i].id * stats_num;\n          for (size_t j = 0; j < stats_num; ++j) {\n            *(dst + j) *= decay_rate;\n          }\n        }\n    });\n\n    //2. build show and click vector\n    Eigen::VectorXd show_vector(items.size());\n    Eigen::VectorXd clk_vector(items.size());\n\n    auto show_iter = std::find(stats_vec.begin(), stats_vec.end(), \"show\");\n    auto click_iter = std::find(stats_vec.begin(), stats_vec.end(), \"click\");\n    assert(show_iter != stats_vec.end() && click_iter != stats_vec.end());\n\n    size_t show_idx = show_iter - stats_vec.begin();\n    size_t click_idx = click_iter - stats_vec.begin();\n\n    CASES(tensor->Type(), {\n      T* pstats = tensor->Raw<T>();\n      T* dst;\n      for (size_t i = 0; i < items.size(); ++i) {\n        auto& item = items[i];\n        dst = pstats + item.id * stats_num;\n        show_vector(i) = *(dst + show_idx);\n        clk_vector(i) = *(dst + click_idx);\n      }\n    });\n\n    //3. compute fea score\n    auto score = (show_vector - clk_vector) * nonclk_weight + clk_vector * clk_weight;\n    std::string var_name = ctx->GetVariableName();\n    printf(\"HashFeatureScoreFilter for %s fea score min %f max %f, cur_step:%ld\\n\",\n           var_name.c_str(), score.minCoeff(), score.maxCoeff(), cur_step);\n\n    //4. select keys and store fea score\n    std::vector<int64_t> keys;\n    Tensor* fea_scores = variable->GetVariableLikeSlot(\"fea_score\", DataType::kFloat, TensorShape(),\n                                                       []{ return new initializer::ConstantInitializer(0); });\n    float* pscores = fea_scores->Raw<float>();\n    for (size_t i = 0; i < items.size(); ++i) {\n      pscores[items[i].id] = score(i);\n      if (score(i) < train_threshold) {\n        keys.push_back(items[i].x);\n        keys.push_back(items[i].y);\n      }\n    }\n\n    //5. delete\n    hashmap->Internal().Del(&(keys[0]), keys.size() / 2, 2);\n\n    if (!ctx->GetStreamingModelArgs()->streaming_hash_model_addr.empty()) {\n      PS_CHECK_STATUS(StreamingModelUtils::DelHash(ctx->GetVariableName(), keys));\n    }\n\n    printf(\"HashFeatureScoreFilter for %s origin= %ld, clear= %ld\\n\",\n           var_name.c_str(), items.size(), keys.size() / 2);\n\n    return Status::Ok();\n  }\n};\n\nSIMPLE_UDF_REGISTER(HashFeatureScoreFilter, HashFeatureScoreFilter);\n\n}\n}\n}\n\n", "meta": {"hexsha": "623232d54c69341fc82e84c14dfbbc6b65ab1718", "size": 5188, "ext": "cc", "lang": "C++", "max_stars_repo_path": "xdl/ps-plus/ps-plus/server/udf/hash_feature_score_filter.cc", "max_stars_repo_name": "bigo-sg/x-deeplearning", "max_stars_repo_head_hexsha": "d7c006d316f50a8d0c38478101d0ef8be4b9c886", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T10:11:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T10:11:26.000Z", "max_issues_repo_path": "xdl/ps-plus/ps-plus/server/udf/hash_feature_score_filter.cc", "max_issues_repo_name": "bigo-sg/x-deeplearning", "max_issues_repo_head_hexsha": "d7c006d316f50a8d0c38478101d0ef8be4b9c886", "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": "xdl/ps-plus/ps-plus/server/udf/hash_feature_score_filter.cc", "max_forks_repo_name": "bigo-sg/x-deeplearning", "max_forks_repo_head_hexsha": "d7c006d316f50a8d0c38478101d0ef8be4b9c886", "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.2925170068, "max_line_length": 110, "alphanum_fraction": 0.6289514264, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.1855199507778933}}
{"text": "//\n// Created by Kanishka Ganguly on 6/25/19.\n// Copyright (c) 2019 Amazon Robotics. All rights reserved.\n//\n\n#pragma once\n\n/** C++ Imports */\n#include <algorithm>\n#include <chrono>\n#include <ctime>\n#include <cmath>\n#include <functional>\n#include <future>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <math.h>\n#include <mutex>\n#include <queue>\n#include <sstream>\n#include <string>\n#include <thread>\n#include <tinyxml2.h>\n#include <type_traits>\n#include <vector>\n#include \"../include/logger.hpp\"\n#include \"../include/prettyprint.hpp\"\n\n/** Boost imports */\n#include <boost/bind.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/thread.hpp>\n\n/** Gazebo Imports */\n#include <gazebo/common/common.hh>\n#include <gazebo/common/Plugin.hh>\n#include <gazebo/gazebo.hh>\n#include <gazebo/gazebo_client.hh>\n#include <gazebo/gazebo_config.h>\n#include <gazebo/msgs/msgs.hh>\n#include <gazebo/physics/physics.hh>\n#include <gazebo/sensors/sensors.hh>\n#include <gazebo/transport/transport.hh>\n#include <gazebo_plugins/gazebo_ros_utils.h>\n#include <sdf/sdf.hh>\n\n/** Eigen Imports */\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/StdVector>\n#include <eigen3/unsupported/Eigen/CXX11/Tensor>\n\n/** ROS imports */\n#ifdef USE_ROS\n#include <actionlib/client/simple_action_client.h>\n#include <actionlib/client/terminal_state.h>\n#include <actionlib/server/simple_action_server.h>\n#include <controller_manager_msgs/ControllerState.h>\n#include <controller_manager_msgs/ListControllers.h>\n#include <control_msgs/FollowJointTrajectoryAction.h>\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <sensor_msgs/JointState.h>\n#include <trajectory_msgs/JointTrajectory.h>\n#include <trajectory_msgs/JointTrajectoryPoint.h>\n#include <voxel_grid_plugin/ModelControlAction.h>\n#include <voxel_grid_plugin/RobotControlAction.h>\n#include <voxel_grid_plugin/SimControlAction.h>\n#include <voxel_grid_plugin/VoxelGridAction.h>\n#include <voxel_grid_plugin/VoxelData.h>\n#endif\n\n/** Visualization */\n#ifdef SHOW_VIZ\n#include <cilantro/common_renderables.hpp>\n#include <cilantro/point_cloud.hpp>\n#include <cilantro/visualizer.hpp>\n#endif\n\n\ntypedef Eigen::TensorFixedSize<int, Eigen::Sizes<127, 127, 127>> Tensor;    /**< @typedef Eigen::TensorFixedSizefor grid management */\ntypedef Eigen::Vector3f Color;                                              /**< @typedef Eigen::Vector3f for managing cilantro::PointCloud colors */\ntypedef Eigen::Vector3f v3f;                                                /**< @typedef Eigen::Vector3f shorthand */\ntypedef Eigen::Vector3i v3i;                                                /**< @typedef Eigen::Vector3i shorthand */\ntypedef std::vector<std::tuple<std::string, int, Color>> CustomCellState;   /**< @typedef Vector of data for voxel grid with multiple items */\n\n/**\n * @namespace math_helper\n * @brief Small helper functions for math\n */\nnamespace math_helper {\n\n/**\n * @fn inline static double DEG2RAD(const T &DEG)\n * @brief Convert degrees to radians\n * @tparam T\n * @param DEG - Degrees\n * @return Radians\n */\n\ttemplate<typename T>\n\tinline static double DEG2RAD(const T &DEG) {\n\t\treturn DEG * 0.017453293;\n\t}\n\n/**\n * @fn inline static double RAD2DEG(const T &RAD)\n * @brief Convert radians to degrees\n * @tparam T\n * @param RAD - Radians\n * @return Degrees\n */\n\ttemplate<typename T>\n\tinline static double RAD2DEG(const T &RAD) {\n\t\treturn RAD * 57.29577951;\n\t}\n\n\tnamespace gazebo_eigen_conversions {\n\t\t/**\n\t\t* @brief Converts gazebo::math::Matrix3 to Eigen::Matrix3f\n\t\t* @param input_mat - Gazebo Matrix3 to be converted\n\t\t* @return output_mat - Eigen Matrix3f after conversion\n\t\t*/\n\t\tinline static Eigen::Matrix3f GazeboMat3ToEigenMat3(const gazebo::math::Matrix3 &input_mat) {\n\t\t\tEigen::Matrix3f output_mat;\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\t\toutput_mat(i, j) = input_mat[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output_mat;\n\t\t}\n\n\t\t/**\n\t\t * @brief Converts Eigen::Matrix3f to gazebo::math::Matrix3\n\t\t * @param input_mat - Eigen Matrix3f to be converted\n\t\t * @return output_mat - Gazebo Matrix3 after conversion\n\t\t */\n\t\tinline static gazebo::math::Matrix3 EigenMat3ToGazeboMat3(const Eigen::Matrix3f &input_mat) {\n\t\t\tgazebo::math::Matrix3 output_mat;\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\t\toutput_mat[i][j] = input_mat(i, j);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output_mat;\n\t\t}\n\n\t\t/**\n\t\t * @brief Converts gazebo::math::Vector3 to Eigen::Vector3f\n\t\t * @param input_vec - Gazebo Vector3 to be converted\n\t\t * @return output_vec - Eigen Vector3f after conversion\n\t\t */\n\t\tinline static Eigen::Vector3f GazeboVec3ToEigenVec3(const gazebo::math::Vector3 &input_vec) {\n\t\t\tEigen::Vector3f output_vec;\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\toutput_vec(i) = input_vec[i];\n\t\t\t}\n\t\t\treturn output_vec;\n\t\t}\n\n\t\t/**\n\t\t * @brief Converts Eigen::Vector3f to gazebo::math::Vector3\n\t\t * @param input_vec - Eigen Vector3f to be converted\n\t\t * @return output_vec - Gazebo Vector3 after conversion\n\t\t */\n\t\tinline static gazebo::math::Vector3 EigenVec3ToGazeboVec3(const Eigen::Vector3f &input_vec) {\n\t\t\tgazebo::math::Vector3 output_vec;\n\t\t\toutput_vec.x = input_vec(0);\n\t\t\toutput_vec.y = input_vec(1);\n\t\t\toutput_vec.z = input_vec(2);\n\t\t\treturn output_vec;\n\t\t}\n\n\t\t/**\n\t\t * @brief Converts Eigen::Quaternionf to gazebo::math::Quaternion\n\t\t * @param input_quat - Eigen Quaternion to be converted\n\t\t * @return output_quat - Gazebo Quaternion after conversion\n\t\t */\n\t\tinline static gazebo::math::Quaternion EigenQuaternionToGazeboQuaternion(const Eigen::Quaternionf &input_quat) {\n\t\t\tgazebo::math::Quaternion output_quat;\n\t\t\toutput_quat.Set(input_quat.w(), input_quat.x(), input_quat.y(), input_quat.z());\n\t\t\treturn output_quat;\n\t\t}\n\n\t\t/**\n\t\t * @brief Converts gazebo::math::Quaternion to Eigen::Quaternionf\n\t\t * @param input_quat - Gazebo Quaternion to be converted\n\t\t * @return output_quat - Eigen Quaternion after conversion\n\t\t */\n\t\tinline static Eigen::Quaternionf GazeboQuaternionToEigenQuaternion(const gazebo::math::Quaternion &input_quat) {\n\t\t\tEigen::Quaternionf output_quat;\n\t\t\toutput_quat.w() = input_quat.w;\n\t\t\toutput_quat.x() = input_quat.x;\n\t\t\toutput_quat.y() = input_quat.y;\n\t\t\toutput_quat.z() = input_quat.z;\n\t\t\treturn output_quat;\n\t\t}\n\t}\n\n\tnamespace eigen_conversions {\n\t\t/**\n\t\t * @brief Convert roll, pitch, yaw to Quaternion\n\t\t * @param r - Roll\n\t\t * @param p - Pitch\n\t\t * @param y - Yaw\n\t\t * @return q - Quaternion\n\t\t */\n\t\tinline static Eigen::Quaternionf EulerXYZToEigenQuaternion(const float &r, const float &p, const float &y) {\n\t\t\tEigen::Quaternionf q;\n\t\t\tq = Eigen::AngleAxisf(r, Eigen::Vector3f::UnitX())\n\t\t\t\t* Eigen::AngleAxisf(p, Eigen::Vector3f::UnitY())\n\t\t\t\t* Eigen::AngleAxisf(y, Eigen::Vector3f::UnitZ());\n\t\t\treturn q;\n\t\t}\n\n\t\t/**\n\t\t * @brief Convert Quaternion to roll, pitch, yaw\n\t\t * @param q - Quaternion\n\t\t * @return - Vector3 of roll, pitch, yaw\n\t\t */\n\t\tinline static Eigen::Vector3f EigenQuaternionToEulerXYZ(const Eigen::Quaternionf &q) {\n\t\t\treturn q.toRotationMatrix().eulerAngles(0, 1, 2);\n\t\t};\n\n\t\t/**\n\t\t * @brief Get 3x3 rotation and 3x1 translation components from 4x4 transformation matrix\n\t\t * @param matrix4 Transformation matrix to decompose\n\t\t * @param rot 3x3 rotation matrix\n\t\t * @param pos 3x1 position vector\n\t\t */\n\t\tinline void GetRotationTranslationEigen(const Eigen::Matrix4f &matrix4, Eigen::Matrix3f &rot, Eigen::Vector3f &pos) {\n\t\t\t// Rightmost 3x1 column of 4x4 matrix is translation\n\t\t\tpos = matrix4.block<3, 1>(0, 3);\n\t\t\t// Top left 3x3 matrix of 4x4 matrix is rotation\n\t\t\trot = matrix4.block<3, 3>(0, 0);\n\t\t}\n\n\t\t/**\n\t\t * @brief Get 3x1 translation components from 4x4 transformation matrix\n\t\t * @param matrix4 Transformation matrix to decompose\n\t\t * @param pos 3x1 position vector\n\t\t */\n\t\tinline void GetTranslationEigen(const Eigen::Matrix4f &matrix4, Eigen::Vector3f &pos) {\n\t\t\t// Rightmost 3x1 column of 4x4 matrix is translation\n\t\t\tpos = matrix4.block<3, 1>(0, 3);\n\t\t}\n\n\t\t/**\n\t\t * @brief Get 3x3 rotation components from 4x4 transformation matrix\n\t\t * @param matrix4 Transformation matrix to decompose\n\t\t * @param rot 3x3 rotation matrix\n\t\t */\n\t\tinline void GetRotationEigen(const Eigen::Matrix4f &matrix4, Eigen::Matrix3f &rot) {\n\t\t\t// Top left 3x3 matrix of 4x4 matrix is rotation\n\t\t\trot = matrix4.block<3, 3>(0, 0);\n\t\t}\n\n\t\t/**\n\t\t * @brief Converts Eigen::Vector3f and Eigen::Matrix3f to Eigen::Matrix4f\n\t\t * @param pos - Translation Vector3f to convert\n\t\t * @param rot - Matrix3f to convert\n\t\t * @param matrix4 - Converted Eigen::Matrix4f output\n\t\t */\n\t\tinline void PoseToMatrix4(const Eigen::Vector3f &pos, const Eigen::Matrix3f &rot, Eigen::Matrix4f &matrix4) {\n\t\t\tmatrix4.topLeftCorner(3, 3) = rot;\n\t\t\tmatrix4.topRightCorner(3, 1) = pos;\n\t\t\tmatrix4(3, 3) = 1;\n\t\t}\n\t}\n\n\tnamespace gazebo_conversions {\n\t\t/**\n\t\t * @brief Convert roll, pitch, yaw to Quaternion\n\t\t * @param r - Roll\n\t\t * @param p - Pitch\n\t\t * @param y - Yaw\n\t\t * @return q - Quaternion\n\t\t */\n\t\tinline static gazebo::math::Quaternion EulerXYZToGazeboQuaternion(const double &r, const double &p, const double &y) {\n\t\t\tgazebo::math::Quaternion q;\n\t\t\tq.SetFromEuler(r, p, y);\n\t\t\treturn q;\n\t\t}\n\n\t\t/**\n\t\t * @brief Convert Quaternion to roll, pitch, yaw\n\t\t * @return rpy - roll, pitch, yaw\n\t\t */\n\t\tinline static gazebo::math::Vector3 GazeboQuaternionToEulerXYZ(const gazebo::math::Quaternion &q) {\n\t\t\tgazebo::math::Vector3 EulerZYX = q.GetAsEuler();\n\t\t\tgazebo::math::Vector3 EulerXYZ;\n\t\t\tEulerXYZ.Set(EulerZYX.z, EulerZYX.y, EulerZYX.x);\n\t\t\treturn EulerXYZ;\n\t\t}\n\n\t\t/**\n\t\t * @brief Converts math::Pose to math::Matrix4\n\t\t * @param pose - Pose to convert\n\t\t * @param matrix4 - Converted math::Matrix4 output\n\t\t */\n\t\tinline void PoseToMatrix4(const gazebo::math::Pose &pose, gazebo::math::Matrix4 &matrix4) {\n\t\t\t/** Initialize to ZERO */\n\t\t\tmatrix4 = gazebo::math::Matrix4::ZERO;\n\t\t\t/** Set last element to 1 for valid transformation matrix */\n\t\t\tmatrix4[3][3] = 1;\n\t\t\t/** Set rotation data in transformation matrix */\n\t\t\tgazebo::math::Matrix3 rot_as_matrix3 = pose.rot.GetAsMatrix3();\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\t\tmatrix4[i][j] = rot_as_matrix3[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\t/** Set translation data in transformation matrix */\n\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\tmatrix4[j][3] = pose.pos[j];\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t* @brief Converts math::Vector3 and math::Quaternion to math::Matrix4\n\t\t* @param pos - Translation vector to convert\n\t\t* @param rot - Quaternion to convert\n\t\t* @param matrix4 - Converted math::Matrix4 output\n\t\t*/\n\t\tinline void PoseToMatrix4(const gazebo::math::Vector3 &pos, const gazebo::math::Quaternion &rot, gazebo::math::Matrix4 &matrix4) {\n\t\t\t/** Initialize to ZERO */\n\t\t\tmatrix4 = gazebo::math::Matrix4::ZERO;\n\t\t\t/** Set last element to 1 for valid transformation matrix */\n\t\t\tmatrix4[3][3] = 1;\n\t\t\t/** Set rotation data in transformation matrix */\n\t\t\tgazebo::math::Matrix3 rot_as_matrix3 = rot.GetAsMatrix3();\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\t\tmatrix4[i][j] = rot_as_matrix3[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\t/** Set translation data in transformation matrix */\n\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\tmatrix4[j][3] = pos[j];\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * @brief Converts math::Vector3 and math::Matrix3 to math::Matrix4\n\t\t * @param pos - Translation vector to convert\n\t\t * @param rot - Matrix3 to convert\n\t\t * @param matrix4 - Converted math::Matrix4 output\n\t\t */\n\t\tinline void PoseToMatrix4(const gazebo::math::Vector3 &pos, const gazebo::math::Matrix3 &rot, gazebo::math::Matrix4 &matrix4) {\n\t\t\t/** Initialize to ZERO */\n\t\t\tmatrix4 = gazebo::math::Matrix4::ZERO;\n\t\t\t/** Set last element to 1 for valid transformation matrix */\n\t\t\tmatrix4[3][3] = 1;\n\t\t\t/** Set rotation data in transformation matrix */\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\t\tmatrix4[i][j] = rot[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\t/** Set translation data in transformation matrix */\n\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\tmatrix4[j][3] = pos[j];\n\t\t\t}\n\t\t}\n\n\t}\n\n/**\n* @fn inline void UpdateElement(const std::string &elem, const double &value, math::Vector3 &vec)\n* @brief Updates value of math::Vector3 at index given by axis specifier \"x\", \"y\" or \"z\"\n* @param elem - Axis to modify\n* @param value - Value to set\n* @param vec - Vector that will be updated\n*/\n\tinline void UpdateElement(const std::string &elem, const double &value, gazebo::math::Vector3 &vec) {\n\t\tif (elem == \"x\") {\n\t\t\tvec.x = value;\n\t\t} else if (elem == \"y\") {\n\t\t\tvec.y = value;\n\t\t} else if (elem == \"z\") {\n\t\t\tvec.z = value;\n\t\t}\n\t}\n\n/**\n * @overload\n */\n\tinline void UpdateElement(const int &idx, const double &value, gazebo::math::Vector3 &vec) {\n\t\tassert(idx >= 0 && idx <= 3);\n\t\tswitch (idx) {\n\t\t\tcase 0:\n\t\t\t\tvec.x = value;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tvec.y = value;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tvec.z = value;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n}\n", "meta": {"hexsha": "c13497d601a93e8ee96eda3415eec247eba9861b", "size": 12717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/imports.hpp", "max_stars_repo_name": "kanishkaganguly/UR10VoxelGrid", "max_stars_repo_head_hexsha": "b57d7b2a064f6a6dc6415c49d30546ad190fb119", "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/imports.hpp", "max_issues_repo_name": "kanishkaganguly/UR10VoxelGrid", "max_issues_repo_head_hexsha": "b57d7b2a064f6a6dc6415c49d30546ad190fb119", "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/imports.hpp", "max_forks_repo_name": "kanishkaganguly/UR10VoxelGrid", "max_forks_repo_head_hexsha": "b57d7b2a064f6a6dc6415c49d30546ad190fb119", "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.4777227723, "max_line_length": 149, "alphanum_fraction": 0.671777935, "num_tokens": 3792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.185466331660736}}
{"text": "\n#include \"GenericReconCartesianNonLinearSpirit2DTGadget.h\"\n#include \"hoSPIRIT2DTOperator.h\"\n#include \"hoSPIRIT2DTDataFidelityOperator.h\"\n#include \"hoWavelet2DTOperator.h\"\n#include \"mri_core_spirit.h\"\n#include \"mri_core_grappa.h\"\n#include \"hoNDArray_reductions.h\"\n#include \"hoGdSolver.h\"\n#include <boost/make_shared.hpp>\n\nnamespace Gadgetron {\n\n    GenericReconCartesianNonLinearSpirit2DTGadget::GenericReconCartesianNonLinearSpirit2DTGadget() : BaseClass()\n    {\n    }\n\n    GenericReconCartesianNonLinearSpirit2DTGadget::~GenericReconCartesianNonLinearSpirit2DTGadget()\n    {\n    }\n\n    int GenericReconCartesianNonLinearSpirit2DTGadget::process_config(ACE_Message_Block* mb)\n    {\n        GADGET_CHECK_RETURN(BaseClass::process_config(mb) == GADGET_OK, GADGET_FAIL);\n\n        // -------------------------------------------------\n\n        ISMRMRD::IsmrmrdHeader h;\n        try\n        {\n            deserialize(mb->rd_ptr(), h);\n        }\n        catch (...)\n        {\n            GDEBUG(\"Error parsing ISMRMRD Header\");\n        }\n\n        // -------------------------------------------------\n        // check the parameters\n        if(this->spirit_nl_iter_max.value()==0)\n        {\n            this->spirit_nl_iter_max.value(15);\n            GDEBUG_STREAM(\"spirit_iter_max: \" << this->spirit_nl_iter_max.value());\n        }\n\n        if (this->spirit_nl_iter_thres.value()<FLT_EPSILON)\n        {\n            this->spirit_nl_iter_thres.value(0.004);\n            GDEBUG_STREAM(\"spirit_nl_iter_thres: \" << this->spirit_nl_iter_thres.value());\n        }\n\n        if (this->spirit_image_reg_lamda.value() < FLT_EPSILON)\n        {\n            if(this->spirit_reg_proximity_across_cha.value())\n            {\n                if(spirit_reg_estimate_noise_floor.value())\n                {\n                    this->spirit_image_reg_lamda.value(0.001);\n                }\n                else\n                {\n                    this->spirit_image_reg_lamda.value(0.0002);\n                }\n            }\n            else\n            {\n                if(spirit_reg_estimate_noise_floor.value())\n                {\n                    this->spirit_image_reg_lamda.value(0.002);\n                }\n                else\n                {\n                    this->spirit_image_reg_lamda.value(0.00005);\n                }\n            }\n\n            GDEBUG_STREAM(\"spirit_image_reg_lamda: \" << this->spirit_image_reg_lamda.value());\n        }\n\n        if (this->spirit_reg_N_weighting_ratio.value() < FLT_EPSILON)\n        {\n            if(acceFactorE1_[0]<=5)\n            {\n                this->spirit_reg_N_weighting_ratio.value(10.0);\n            }\n            else\n            {\n                this->spirit_reg_N_weighting_ratio.value(20.0);\n            }\n\n            GDEBUG_STREAM(\"spirit_reg_N_weighting_ratio: \" << this->spirit_reg_N_weighting_ratio.value());\n        }\n\n        return GADGET_OK;\n    }\n\n    void GenericReconCartesianNonLinearSpirit2DTGadget::perform_unwrapping(IsmrmrdReconBit& recon_bit, ReconObjType& recon_obj, size_t e)\n    {\n        try\n        {\n            size_t RO = recon_bit.data_.data_.get_size(0);\n            size_t E1 = recon_bit.data_.data_.get_size(1);\n            size_t E2 = recon_bit.data_.data_.get_size(2);\n            size_t dstCHA = recon_bit.data_.data_.get_size(3);\n            size_t N = recon_bit.data_.data_.get_size(4);\n            size_t S = recon_bit.data_.data_.get_size(5);\n            size_t SLC = recon_bit.data_.data_.get_size(6);\n\n            hoNDArray< std::complex<float> >& src = recon_obj.ref_calib_;\n\n            size_t ref_RO = src.get_size(0);\n            size_t ref_E1 = src.get_size(1);\n            size_t ref_E2 = src.get_size(2);\n            size_t srcCHA = src.get_size(3);\n            size_t ref_N = src.get_size(4);\n            size_t ref_S = src.get_size(5);\n            size_t ref_SLC = src.get_size(6);\n\n            size_t convkRO = recon_obj.kernel_.get_size(0);\n            size_t convkE1 = recon_obj.kernel_.get_size(1);\n            size_t convkE2 = recon_obj.kernel_.get_size(2);\n\n            recon_obj.recon_res_.data_.create(RO, E1, E2, 1, N, S, SLC);\n            Gadgetron::clear(recon_obj.recon_res_.data_);\n            recon_obj.full_kspace_ = recon_bit.data_.data_;\n            Gadgetron::clear(recon_obj.full_kspace_);\n\n            std::stringstream os;\n            os << \"encoding_\" << e;\n            std::string suffix = os.str();\n\n            if (!debug_folder_full_path_.empty()) { gt_exporter_.export_array_complex(recon_bit.data_.data_, debug_folder_full_path_ + \"data_src_\" + suffix); }\n\n            // ------------------------------------------------------------------\n            // compute effective acceleration factor\n            // ------------------------------------------------------------------\n            float effective_acce_factor(1), snr_scaling_ratio(1);\n            this->compute_snr_scaling_factor(recon_bit, effective_acce_factor, snr_scaling_ratio);\n            if (effective_acce_factor > 1)\n            {\n                Gadgetron::scal(snr_scaling_ratio, recon_bit.data_.data_);\n            }\n\n            Gadgetron::GadgetronTimer timer(false);\n\n            // ------------------------------------------------------------------\n            // compute the reconstruction\n            // ------------------------------------------------------------------\n            if(this->acceFactorE1_[e]<=1 && this->acceFactorE2_[e]<=1)\n            {\n                recon_obj.full_kspace_ = recon_bit.data_.data_;\n            }\n            else\n            {\n                hoNDArray< std::complex<float> >& kspace = recon_bit.data_.data_;\n                hoNDArray< std::complex<float> >& res = recon_obj.full_kspace_;\n                hoNDArray< std::complex<float> >& ref = recon_obj.ref_calib_;\n\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_parallel_imaging_lamda             : \" << this->spirit_parallel_imaging_lamda.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_image_reg_lamda                    : \" << this->spirit_image_reg_lamda.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_data_fidelity_lamda                : \" << this->spirit_data_fidelity_lamda.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_nl_iter_max                        : \" << this->spirit_nl_iter_max.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_nl_iter_thres                      : \" << this->spirit_nl_iter_thres.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_name                           : \" << this->spirit_reg_name.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_level                          : \" << this->spirit_reg_level.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_keep_approx_coeff              : \" << this->spirit_reg_keep_approx_coeff.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_keep_redundant_dimension_coeff : \" << this->spirit_reg_keep_redundant_dimension_coeff.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_proximity_across_cha           : \" << this->spirit_reg_proximity_across_cha.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_use_coil_sen_map               : \" << this->spirit_reg_use_coil_sen_map.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_RO_weighting_ratio             : \" << this->spirit_reg_RO_weighting_ratio.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_E1_weighting_ratio             : \" << this->spirit_reg_E1_weighting_ratio.value());\n                GDEBUG_CONDITION_STREAM(this->verbose.value(), \"spirit_reg_N_weighting_ratio              : \" << this->spirit_reg_N_weighting_ratio.value());\n\n                size_t slc, s;\n\n                for (slc = 0; slc < SLC; slc++)\n                {\n                    for (s = 0; s < S; s++)\n                    {\n                        std::stringstream os;\n                        os << \"encoding_\" << e << \"_s\" << s << \"_slc\" << slc;\n                        std::string suffix_2DT = os.str();\n\n                        // ------------------------------\n\n                        std::complex<float>* pKspace = &kspace(0, 0, 0, 0, 0, s, slc);\n                        hoNDArray< std::complex<float> > kspace2DT(RO, E1, E2, dstCHA, N, 1, 1, pKspace);\n\n                        // ------------------------------\n\n                        long long kernelS = s;\n                        if (kernelS >= (long long)ref_S) kernelS = (long long)ref_S - 1;\n\n                        std::complex<float>* pKIm = &recon_obj.kernelIm2D_(0, 0, 0, 0, 0, kernelS, slc);\n                        hoNDArray< std::complex<float> > kIm2DT(RO, E1, srcCHA, dstCHA, ref_N, 1, 1, pKIm);\n\n                        // ------------------------------\n\n                        std::complex<float>* pRef = &ref(0, 0, 0, 0, 0, kernelS, slc);\n                        hoNDArray< std::complex<float> > ref2DT(ref.get_size(0), ref.get_size(1), ref.get_size(2), dstCHA, ref_N, 1, 1, pRef);\n\n                        // ------------------------------\n\n                        hoNDArray< std::complex<float> > coilMap2DT;\n                        if (recon_obj.coil_map_.get_size(6) == SLC)\n                        {\n                            size_t coil_S = recon_obj.coil_map_.get_size(5);\n                            std::complex<float>* pCoilMap = &recon_obj.coil_map_(0, 0, 0, 0, 0, ((s>=coil_S) ? coil_S-1 : s), slc);\n                            coilMap2DT.create(RO, E1, E2, dstCHA, ref_N, 1, 1, pCoilMap);\n                        }\n\n                        // ------------------------------\n\n                        std::complex<float>* pRes = &res(0, 0, 0, 0, 0, s, slc);\n                        hoNDArray< std::complex<float> > res2DT(RO, E1, E2, dstCHA, N, 1, 1, pRes);\n\n                        // ------------------------------\n\n                        if (!debug_folder_full_path_.empty()) { gt_exporter_.export_array_complex(kspace2DT, debug_folder_full_path_ + \"kspace2DT_nl_spirit_\" + suffix_2DT); }\n                        if (!debug_folder_full_path_.empty()) { gt_exporter_.export_array_complex(kIm2DT, debug_folder_full_path_ + \"kIm2DT_nl_spirit_\" + suffix_2DT); }\n                        if (!debug_folder_full_path_.empty()) { gt_exporter_.export_array_complex(ref2DT, debug_folder_full_path_ + \"ref2DT_nl_spirit_\" + suffix_2DT); }\n\n                        // ------------------------------\n\n                        std::string timing_str = \"SPIRIT, Non-linear unwrapping, 2DT_\" + suffix_2DT;\n                        if (this->perform_timing.value()) timer.start(timing_str.c_str());\n                        this->perform_nonlinear_spirit_unwrapping(kspace2DT, kIm2DT, ref2DT, coilMap2DT, res2DT, e);\n                        if (this->perform_timing.value()) timer.stop();\n\n                        if (!debug_folder_full_path_.empty()) { gt_exporter_.export_array_complex(res2DT, debug_folder_full_path_ + \"res_nl_spirit_2DT_\" + suffix_2DT); }\n                    }\n                }\n            }\n\n            // ---------------------------------------------------------------------\n            // compute coil combined images\n            // ---------------------------------------------------------------------\n            if (this->perform_timing.value()) timer.start(\"SPIRIT Non linear, coil combination ... \");\n            this->perform_spirit_coil_combine(recon_obj);\n            if (this->perform_timing.value()) timer.stop();\n\n            if (!debug_folder_full_path_.empty()) { gt_exporter_.export_array_complex(recon_obj.recon_res_.data_, debug_folder_full_path_ + \"unwrappedIm_\" + suffix); }\n        }\n        catch (...)\n        {\n            GADGET_THROW(\"Errors happened in GenericReconCartesianNonLinearSpirit2DTGadget::perform_unwrapping(...) ... \");\n        }\n    }\n\n    class solverCallBack : public hoGdSolverCallBack< hoNDArray< std::complex<float> >, hoWavelet2DTOperator< std::complex<float> > >\n    {\n        public:\n        typedef hoGdSolverCallBack< hoNDArray< std::complex<float> >, hoWavelet2DTOperator< std::complex<float> > > BaseClass;\n\n        solverCallBack() : BaseClass() {}\n        virtual ~solverCallBack() {}\n\n        void execute(const hoNDArray< std::complex<float> >& b, hoNDArray< std::complex<float> >& x)\n        {\n            typedef hoSPIRIT2DTDataFidelityOperator< std::complex<float> > SpiritOperType;\n            SpiritOperType* pOper = dynamic_cast<SpiritOperType*> (this->solver_->oper_system_);\n            pOper->restore_acquired_kspace(x);\n        }\n    };\n\n    void GenericReconCartesianNonLinearSpirit2DTGadget::perform_nonlinear_spirit_unwrapping(hoNDArray< std::complex<float> >& kspace, \n        hoNDArray< std::complex<float> >& kerIm, hoNDArray< std::complex<float> >& ref2DT, hoNDArray< std::complex<float> >& coilMap2DT, hoNDArray< std::complex<float> >& res, size_t e)\n    {\n        try\n        {\n            bool print_iter = this->spirit_print_iter.value();\n\n            size_t RO = kspace.get_size(0);\n            size_t E1 = kspace.get_size(1);\n            size_t E2 = kspace.get_size(2);\n            size_t CHA = kspace.get_size(3);\n            size_t N = kspace.get_size(4);\n            size_t S = kspace.get_size(5);\n            size_t SLC = kspace.get_size(6);\n\n            size_t ref_N = kerIm.get_size(4);\n            size_t ref_S = kerIm.get_size(5);\n\n            hoNDArray< std::complex<float> > kspaceLinear(kspace);\n            res = kspace;\n\n            // detect whether random sampling is used\n            bool use_random_sampling = false;\n            std::vector<long long> sampled_step_size;\n            long long n, e1;\n            for (n=0; n<(long long)N; n++)\n            {\n                long long prev_sampled_line = -1;\n                for (e1=0; e1<(long long)E1; e1++)\n                {\n                    if(std::abs(kspace(RO/2, e1, 0, 0, 0, 0, 0))>0 && std::abs(kspace(RO/2, e1, 0, CHA-1, 0, 0, 0))>0)\n                    {\n                        if(prev_sampled_line>0)\n                        {\n                            sampled_step_size.push_back(e1 - prev_sampled_line);\n                        }\n\n                        prev_sampled_line = e1;\n                    }\n                }\n            }\n\n            if(sampled_step_size.size()>4)\n            {\n                size_t s;\n                for (s=2; s<sampled_step_size.size()-1; s++)\n                {\n                    if(sampled_step_size[s]!=sampled_step_size[s-1])\n                    {\n                        use_random_sampling = true;\n                        break;\n                    }\n                }\n            }\n\n            if(use_random_sampling)\n            {\n                GDEBUG_STREAM(\"SPIRIT Non linear, random sampling is detected ... \");\n            }\n\n            Gadgetron::GadgetronTimer timer(false);\n\n            boost::shared_ptr< hoNDArray< std::complex<float> > > coilMap;\n\n            bool hasCoilMap = false;\n            if (coilMap2DT.get_size(0) == RO && coilMap2DT.get_size(1) == E1 && coilMap2DT.get_size(3)==CHA)\n            {\n                if (ref_N < N)\n                {\n                    coilMap = boost::shared_ptr< hoNDArray< std::complex<float> > >(new hoNDArray< std::complex<float> >(RO, E1, CHA, coilMap2DT.begin()));\n                }\n                else\n                {\n                    coilMap = boost::shared_ptr< hoNDArray< std::complex<float> > >(new hoNDArray< std::complex<float> >(RO, E1, CHA, ref_N, coilMap2DT.begin()));\n                }\n\n                hasCoilMap = true;\n            }\n\n            hoNDArray<float> gFactor;\n            float gfactorMedian = 0;\n\n            float smallest_eigen_value(0);\n\n            // -----------------------------------------------------\n            // estimate gfactor\n            // -----------------------------------------------------\n\n            // mean over N\n            hoNDArray< std::complex<float> > meanKSpace;\n\n            if(calib_mode_[e]==ISMRMRD_interleaved)\n            {\n                Gadgetron::compute_averaged_data_N_S(kspace, true, true, true, meanKSpace);\n            }\n            else\n            {\n                Gadgetron::compute_averaged_data_N_S(ref2DT, true, true, true, meanKSpace);\n            }\n\n            if (!debug_folder_full_path_.empty()) { gt_exporter_.export_array_complex(meanKSpace, debug_folder_full_path_ + \"spirit_nl_2DT_meanKSpace\"); }\n\n            hoNDArray< std::complex<float> > acsSrc(meanKSpace.get_size(0), meanKSpace.get_size(1), CHA, meanKSpace.begin());\n            hoNDArray< std::complex<float> > acsDst(meanKSpace.get_size(0), meanKSpace.get_size(1), CHA, meanKSpace.begin());\n\n            double grappa_reg_lamda = 0.0005;\n            size_t kRO = 5;\n            size_t kE1 = 4;\n\n            hoNDArray< std::complex<float> > convKer;\n            hoNDArray< std::complex<float> > kIm(RO, E1, CHA, CHA);\n\n            Gadgetron::grappa2d_calib_convolution_kernel(acsSrc, acsDst, (size_t)this->acceFactorE1_[e], grappa_reg_lamda, kRO, kE1, convKer);\n            Gadgetron::grappa2d_image_domain_kernel(convKer, RO, E1, kIm);\n\n            hoNDArray< std::complex<float> > unmixC;\n\n            if(hasCoilMap)\n            {\n                Gadgetron::grappa2d_unmixing_coeff(kIm, *coilMap, (size_t)acceFactorE1_[e], unmixC, gFactor);\n\n                if (!debug_folder_full_path_.empty()) gt_exporter_.export_array(gFactor, debug_folder_full_path_ + \"spirit_nl_2DT_gFactor\");\n\n                hoNDArray<float> gfactorSorted(gFactor);\n                std::sort(gfactorSorted.begin(), gfactorSorted.begin()+RO*E1);\n                gfactorMedian = gFactor((RO*E1 / 2));\n\n                GDEBUG_STREAM(\"SPIRIT Non linear, the median gfactor is found to be : \" << gfactorMedian);\n            }\n\n            if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(kIm, debug_folder_full_path_ + \"spirit_nl_2DT_kIm\");\n\n            hoNDArray< std::complex<float> > complexIm;\n\n            // compute linear solution as the initialization\n            if(use_random_sampling)\n            {\n                if (this->perform_timing.value()) timer.start(\"SPIRIT Non linear, perform linear spirit recon ... \");\n                this->perform_spirit_unwrapping(kspace, kerIm, kspaceLinear);\n                if (this->perform_timing.value()) timer.stop();\n            }\n            else\n            {\n                if (this->perform_timing.value()) timer.start(\"SPIRIT Non linear, perform linear recon ... \");\n\n                //size_t ref2DT_RO = ref2DT.get_size(0);\n                //size_t ref2DT_E1 = ref2DT.get_size(1);\n\n                //// mean over N\n                //hoNDArray< std::complex<float> > meanKSpace;\n                //Gadgetron::sum_over_dimension(ref2DT, meanKSpace, 4);\n\n                //if (!debug_folder_full_path_.empty()) { gt_exporter_.export_array_complex(meanKSpace, debug_folder_full_path_ + \"spirit_nl_2DT_meanKSpace\"); }\n\n                //hoNDArray< std::complex<float> > acsSrc(ref2DT_RO, ref2DT_E1, CHA, meanKSpace.begin());\n                //hoNDArray< std::complex<float> > acsDst(ref2DT_RO, ref2DT_E1, CHA, meanKSpace.begin());\n\n                //double grappa_reg_lamda = 0.0005;\n                //size_t kRO = 5;\n                //size_t kE1 = 4;\n\n                //hoNDArray< std::complex<float> > convKer;\n                //hoNDArray< std::complex<float> > kIm(RO, E1, CHA, CHA);\n\n                //Gadgetron::grappa2d_calib_convolution_kernel(acsSrc, acsDst, (size_t)this->acceFactorE1_[e], grappa_reg_lamda, kRO, kE1, convKer);\n                //Gadgetron::grappa2d_image_domain_kernel(convKer, RO, E1, kIm);\n\n                //if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(kIm, debug_folder_full_path_ + \"spirit_nl_2DT_kIm\");\n\n                Gadgetron::hoNDFFT<float>::instance()->ifft2c(kspace, complex_im_recon_buf_);\n                if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(complex_im_recon_buf_, debug_folder_full_path_ + \"spirit_nl_2DT_aliasedImage\");\n\n                hoNDArray< std::complex<float> > resKSpace(RO, E1, CHA, N);\n                hoNDArray< std::complex<float> > aliasedImage(RO, E1, CHA, N, complex_im_recon_buf_.begin());\n                Gadgetron::grappa2d_image_domain_unwrapping_aliased_image(aliasedImage, kIm, resKSpace);\n\n                if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(resKSpace, debug_folder_full_path_ + \"spirit_nl_2DT_linearImage\");\n\n                Gadgetron::hoNDFFT<float>::instance()->fft2c(resKSpace);\n\n                memcpy(kspaceLinear.begin(), resKSpace.begin(), resKSpace.get_number_of_bytes());\n\n                Gadgetron::apply_unmix_coeff_aliased_image(aliasedImage, unmixC, complexIm);\n\n                if (this->perform_timing.value()) timer.stop();\n            }\n\n            if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(kspaceLinear, debug_folder_full_path_ + \"spirit_nl_2DT_kspaceLinear\");\n\n            if(hasCoilMap)\n            {\n                if(N>=spirit_reg_minimal_num_images_for_noise_floor.value())\n                {\n                    // estimate the noise level\n\n                    if(use_random_sampling)\n                    {\n                        Gadgetron::hoNDFFT<float>::instance()->ifft2c(kspaceLinear, complex_im_recon_buf_);\n\n                        hoNDArray< std::complex<float> > complexLinearImage(RO, E1, CHA, N, complex_im_recon_buf_.begin());\n\n                        Gadgetron::coil_combine(complexLinearImage, *coilMap, 2, complexIm);\n                    }\n\n                    if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(complexIm, debug_folder_full_path_ + \"spirit_nl_2DT_linearImage_complexIm\");\n\n                    // if N is sufficiently large, we can estimate the noise floor by the smallest eigen value\n                    hoMatrix< std::complex<float> > data;\n                    data.createMatrix(RO*E1, N, complexIm.begin(), false);\n\n                    hoNDArray< std::complex<float> > eigenVectors, eigenValues, eigenVectorsPruned;\n\n                    // compute eigen\n                    hoNDKLT< std::complex<float> > klt;\n                    klt.prepare(data, (size_t)1, (size_t)0);\n                    klt.eigen_value(eigenValues);\n\n                    if (this->verbose.value())\n                    {\n                        GDEBUG_STREAM(\"SPIRIT Non linear, computes eigen values for all 2D kspaces ... \");\n                        eigenValues.print(std::cout);\n\n                        for (size_t i = 0; i<eigenValues.get_size(0); i++)\n                        {\n                            GDEBUG_STREAM(i << \" = \" << eigenValues(i));\n                        }\n                    }\n\n                    smallest_eigen_value = std::sqrt( std::abs(eigenValues(N - 1).real()) / (RO*E1) );\n                    GDEBUG_STREAM(\"SPIRIT Non linear, the smallest eigen value is : \" << smallest_eigen_value);\n                }\n            }\n\n            // perform nonlinear reconstruction\n            {\n                boost::shared_ptr<hoNDArray< std::complex<float> > > ker(new hoNDArray< std::complex<float> >(RO, E1, CHA, CHA, ref_N, kerIm.begin()));\n                boost::shared_ptr<hoNDArray< std::complex<float> > > acq(new hoNDArray< std::complex<float> >(RO, E1, CHA, N, kspace.begin()));\n                hoNDArray< std::complex<float> > kspaceInitial(RO, E1, CHA, N, kspaceLinear.begin());\n                hoNDArray< std::complex<float> > res2DT(RO, E1, CHA, N, res.begin());\n\n                if (this->spirit_data_fidelity_lamda.value() > 0)\n                {\n                    GDEBUG_STREAM(\"Start the NL SPIRIT data fidelity iteration - regularization strength : \" << this->spirit_image_reg_lamda.value()\n                                    << \" - number of iteration : \"                      << this->spirit_nl_iter_max.value()\n                                    << \" - proximity across cha : \"                     << this->spirit_reg_proximity_across_cha.value()\n                                    << \" - redundant dimension weighting ratio : \"      << this->spirit_reg_N_weighting_ratio.value()\n                                    << \" - using coil sen map : \"                       << this->spirit_reg_use_coil_sen_map.value()\n                                    << \" - iter thres : \"                               << this->spirit_nl_iter_thres.value()\n                                    << \" - wavelet name : \"                             << this->spirit_reg_name.value()\n                                    );\n\n                    typedef hoGdSolver< hoNDArray< std::complex<float> >, hoWavelet2DTOperator< std::complex<float> > > SolverType;\n                    SolverType solver;\n                    solver.iterations_ = this->spirit_nl_iter_max.value();\n                    solver.set_output_mode(this->spirit_print_iter.value() ? SolverType::OUTPUT_VERBOSE : SolverType::OUTPUT_SILENT);\n                    solver.grad_thres_ = this->spirit_nl_iter_thres.value();\n\n                    if(spirit_reg_estimate_noise_floor.value() && std::abs(smallest_eigen_value)>0)\n                    {\n                        solver.scale_factor_ = smallest_eigen_value;\n                        solver.proximal_strength_ratio_ = this->spirit_image_reg_lamda.value() * gfactorMedian;\n\n                        GDEBUG_STREAM(\"SPIRIT Non linear, eigen value is used to derive the regularization strength : \" << solver.proximal_strength_ratio_ << \" - smallest eigen value : \" << solver.scale_factor_);\n                    }\n                    else\n                    {\n                        solver.proximal_strength_ratio_ = this->spirit_image_reg_lamda.value();\n                    }\n\n                    boost::shared_ptr< hoNDArray< std::complex<float> > > x0 = boost::make_shared< hoNDArray< std::complex<float> > >(kspaceInitial);\n                    solver.set_x0(x0);\n\n                    // parallel imaging term\n                    std::vector<size_t> dims;\n                    acq->get_dimensions(dims);\n                    hoSPIRIT2DTDataFidelityOperator< std::complex<float> > spirit(&dims);\n                    spirit.set_forward_kernel(*ker, false);\n                    spirit.set_acquired_points(*acq);\n\n                    // image reg term\n                    hoWavelet2DTOperator< std::complex<float> > wav3DOperator(&dims);\n                    wav3DOperator.set_acquired_points(*acq);\n                    wav3DOperator.scale_factor_first_dimension_ = this->spirit_reg_RO_weighting_ratio.value();\n                    wav3DOperator.scale_factor_second_dimension_ = this->spirit_reg_E1_weighting_ratio.value();\n                    wav3DOperator.scale_factor_third_dimension_ = this->spirit_reg_N_weighting_ratio.value();\n                    wav3DOperator.with_approx_coeff_ = !this->spirit_reg_keep_approx_coeff.value();\n                    wav3DOperator.change_coeffcients_third_dimension_boundary_ = !this->spirit_reg_keep_redundant_dimension_coeff.value();\n                    wav3DOperator.proximity_across_cha_ = this->spirit_reg_proximity_across_cha.value();\n                    wav3DOperator.no_null_space_ = true;\n                    wav3DOperator.input_in_kspace_ = true;\n                    wav3DOperator.select_wavelet(this->spirit_reg_name.value());\n\n                    if (this->spirit_reg_use_coil_sen_map.value() && 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                    if (this->perform_timing.value()) timer.start(\"NonLinear SPIRIT solver for 2DT with data fidelity ... \");\n                    solver.solve(*acq, res2DT);\n                    if (this->perform_timing.value()) timer.stop();\n\n                    if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(res2DT, debug_folder_full_path_ + \"spirit_nl_2DT_data_fidelity_res\");\n                }\n                else\n                {\n                    GDEBUG_STREAM(\"Start the NL SPIRIT iteration with regularization strength : \"<< this->spirit_image_reg_lamda.value()\n                                    << \" - number of iteration : \" << this->spirit_nl_iter_max.value()\n                                    << \" - proximity across cha : \" << this->spirit_reg_proximity_across_cha.value()\n                                    << \" - redundant dimension weighting ratio : \" << this->spirit_reg_N_weighting_ratio.value()\n                                    << \" - using coil sen map : \" << this->spirit_reg_use_coil_sen_map.value()\n                                    << \" - iter thres : \" << this->spirit_nl_iter_thres.value()\n                                    << \" - wavelet name : \" << this->spirit_reg_name.value()\n                                    );\n\n                    typedef hoGdSolver< hoNDArray< std::complex<float> >, hoWavelet2DTOperator< std::complex<float> > > SolverType;\n                    SolverType solver;\n                    solver.iterations_ = this->spirit_nl_iter_max.value();\n                    solver.set_output_mode(this->spirit_print_iter.value() ? SolverType::OUTPUT_VERBOSE : SolverType::OUTPUT_SILENT);\n                    solver.grad_thres_ = this->spirit_nl_iter_thres.value();\n\n                    if(spirit_reg_estimate_noise_floor.value() && std::abs(smallest_eigen_value)>0)\n                    {\n                        solver.scale_factor_ = smallest_eigen_value;\n                        solver.proximal_strength_ratio_ = this->spirit_image_reg_lamda.value() * gfactorMedian;\n\n                        GDEBUG_STREAM(\"SPIRIT Non linear, eigen value is used to derive the regularization strength : \" << solver.proximal_strength_ratio_ << \" - smallest eigen value : \" << solver.scale_factor_);\n                    }\n                    else\n                    {\n                        solver.proximal_strength_ratio_ = this->spirit_image_reg_lamda.value();\n                    }\n\n                    boost::shared_ptr< hoNDArray< std::complex<float> > > x0 = boost::make_shared< hoNDArray< std::complex<float> > >(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< std::complex<float> > 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< std::complex<float> > wav3DOperator(&dim);\n                    wav3DOperator.set_acquired_points(*acq);\n                    wav3DOperator.scale_factor_first_dimension_ = this->spirit_reg_RO_weighting_ratio.value();\n                    wav3DOperator.scale_factor_second_dimension_ = this->spirit_reg_E1_weighting_ratio.value();\n                    wav3DOperator.scale_factor_third_dimension_ = this->spirit_reg_N_weighting_ratio.value();\n                    wav3DOperator.with_approx_coeff_ = !this->spirit_reg_keep_approx_coeff.value();\n                    wav3DOperator.change_coeffcients_third_dimension_boundary_ = !this->spirit_reg_keep_redundant_dimension_coeff.value();\n                    wav3DOperator.proximity_across_cha_ = this->spirit_reg_proximity_across_cha.value();\n                    wav3DOperator.no_null_space_ = true;\n                    wav3DOperator.input_in_kspace_ = true;\n                    wav3DOperator.select_wavelet(this->spirit_reg_name.value());\n\n                    if (this->spirit_reg_use_coil_sen_map.value() && 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                    solverCallBack cb;\n                    cb.solver_ = &solver;\n                    solver.call_back_ = &cb;\n\n                    hoNDArray< std::complex<float> > b(kspaceInitial);\n                    Gadgetron::clear(b);\n\n                    if (this->perform_timing.value()) timer.start(\"NonLinear SPIRIT solver for 2DT ... \");\n                    solver.solve(b, res2DT);\n                    if (this->perform_timing.value()) timer.stop();\n\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(kspace, 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        catch (...)\n        {\n            GADGET_THROW(\"Errors happened in GenericReconCartesianNonLinearSpirit2DTGadget::perform_nonlinear_spirit_unwrapping(...) ... \");\n        }\n    }\n\n    GADGET_FACTORY_DECLARE(GenericReconCartesianNonLinearSpirit2DTGadget)\n}\n", "meta": {"hexsha": "21766182af00200e2bf98f048a076a99b95b3b89", "size": 33711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gadgets/mri_core/generic_recon_gadgets/GenericReconCartesianNonLinearSpirit2DTGadget.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": "gadgets/mri_core/generic_recon_gadgets/GenericReconCartesianNonLinearSpirit2DTGadget.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": "gadgets/mri_core/generic_recon_gadgets/GenericReconCartesianNonLinearSpirit2DTGadget.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": 50.3901345291, "max_line_length": 212, "alphanum_fraction": 0.5443030465, "num_tokens": 7691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.18543260439660955}}
{"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_PREDICATES_FUNCTIONS_SIMD_SSE_SSE2_IS_LTZ_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_PREDICATES_FUNCTIONS_SIMD_SSE_SSE2_IS_LTZ_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n#include <boost/simd/toolbox/predicates/functions/is_ltz.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n#include <boost/simd/sdk/meta/make_dependent.hpp>\n#include <boost/simd/toolbox/swar/functions/details/shuffle.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::is_ltz_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_<int64_<A0>,boost::simd::tag::sse_>))\n                                    )\n  {\n    typedef typename meta::as_logical<A0>::type                     result_type;\n    typedef typename meta::make_dependent<int32_t,A0>::type         int32_type;\n    typedef boost::simd::native<int32_type,boost::simd::tag::sse_>  type;\n\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return  bitwise_cast<result_type>\n              (\n                details::shuffle<1,1,3,3>\n                ( is_ltz(bitwise_cast<type>(a0))() )\n              );\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "dc59862275655e18faff720a08bc949894e5e0b6", "size": 1745, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/predicates/include/boost/simd/toolbox/predicates/functions/simd/sse/sse2/is_ltz.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/predicates/include/boost/simd/toolbox/predicates/functions/simd/sse/sse2/is_ltz.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/predicates/include/boost/simd/toolbox/predicates/functions/simd/sse/sse2/is_ltz.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.5476190476, "max_line_length": 82, "alphanum_fraction": 0.558739255, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.1854325971193552}}
{"text": "/*\n==== Author:\n\nRelja Arandjelovic (relja@robots.ox.ac.uk)\nVisual Geometry Group,\nDepartment of Engineering Science\nUniversity of Oxford\n\n==== Copyright:\n\nThe library belongs to Relja Arandjelovic and the University of Oxford.\nNo usage or redistribution is allowed without explicit permission.\n*/\n\n#include \"det_ransac.h\"\n\n#include <Eigen/Dense>\n\n#include \"putative.h\"\n\n\n\ninline double mysqr( double x ){ return x*x; }\n\n\n\ndouble\ndetRansac::matchWords_Hard(\n    sameRandomUint32 const &sameRandomObj,\n    \n    uint32_t &nInliers,\n    \n    std::vector<quantDesc> const &ids1,\n    std::vector<ellipse> const &ellipses1,\n    std::vector<uint32_t> const *presortedInds1,\n    std::vector<quantDesc> const &ids2,\n    std::vector<ellipse> const &ellipses2,\n    \n    double errorThr,\n    double lowAreaChange, double highAreaChange,\n    uint32_t nReest,\n    \n    homography *H,\n    matchesType *inlierInds\n    \n    ){\n    \n    std::vector<uint32_t> ids1_flat, ids2_flat;\n    quantDesc::flattenHard( ids1, ids1_flat );\n    quantDesc::flattenHard( ids2, ids2_flat );\n    \n    std::vector< std::pair<uint32_t, uint32_t> > putativeMatches;\n    putative_quantized::getPutativeMatches_Hard( ids1_flat, ids2_flat, putativeMatches, presortedInds1 );\n    \n    return detRansac::match( sameRandomObj, nInliers, ellipses1, ellipses2, putativeMatches, NULL, errorThr, lowAreaChange, highAreaChange, nReest, H, inlierInds );\n    \n}\n\n\n\ndouble\ndetRansac::matchWords_Soft(\n    sameRandomUint32 const &sameRandomObj,\n    \n    uint32_t &nInliers,\n    \n    std::vector<quantDesc> const &ids1,\n    std::vector<ellipse> const &ellipses1,\n    std::vector<uint32_t> const *presortedInds1,\n    std::vector<quantDesc> const &ids2,\n    std::vector<ellipse> const &ellipses2,\n    \n    double errorThr,\n    double lowAreaChange, double highAreaChange,\n    uint32_t nReest,\n    \n    homography *H,\n    matchesType *inlierInds\n    \n    ){\n    \n    std::vector<wordWeightPair> ids1_flat, ids2_flat;\n    std::vector<uint32_t> qDInds1, qDInds2;\n    quantDesc::flatten( ids1, ids1_flat, &qDInds1, true );\n    quantDesc::flatten( ids2, ids2_flat, &qDInds2, true );\n    \n    std::vector< std::pair<uint32_t, uint32_t> > putativeMatches;\n    std::vector<double> PMweights;\n    putative_quantized::getPutativeMatches_Soft( ids1_flat, qDInds1, ids2_flat, qDInds2, putativeMatches, PMweights, presortedInds1 );\n    \n//     return detRansac::match( sameRandomObj, nInliers, ellipses1, ellipses2, putativeMatches, NULL, errorThr, lowAreaChange, highAreaChange, nReest, H, inlierInds );\n    return detRansac::match( sameRandomObj, nInliers, ellipses1, ellipses2, putativeMatches, &PMweights, errorThr, lowAreaChange, highAreaChange, nReest, H, inlierInds );\n    \n}\n\n\n\ndouble\ndetRansac::matchDesc(\n    sameRandomUint32 const &sameRandomObj,\n    \n    uint32_t &nInliers,\n    \n    float const* desc1,\n    std::vector<ellipse> const &ellipses1,\n    float const* desc2,\n    std::vector<ellipse> const &ellipses2,\n    uint32_t nDims,\n    \n    double errorThr,\n    double lowAreaChange, double highAreaChange,\n    uint32_t nReest,\n    \n    bool useLowe,\n    float deltaSq,\n    float epsilon,\n    \n    homography *H,\n    matchesType *inlierInds\n    \n    ){\n    \n    std::vector< std::pair<uint32_t, uint32_t> > putativeMatches;\n    \n    putative_desc<float>::getPutativeMatches( desc1, ellipses1.size(), desc2, ellipses2.size(), nDims, putativeMatches, useLowe, deltaSq, epsilon );\n    \n    return detRansac::match( sameRandomObj, nInliers, ellipses1, ellipses2, putativeMatches, NULL, errorThr, lowAreaChange, highAreaChange, nReest, H, inlierInds);\n    \n}\n\n\n\ndouble\ndetRansac::match(\n    sameRandomUint32 const &sameRandomObj,\n    \n    uint32_t &bestNInliers,\n    \n    std::vector<ellipse> const &ellipses1,\n    std::vector<ellipse> const &ellipses2,\n    matchesType const &putativeMatches,\n    std::vector<double> const *PMweights,\n    \n    double errorThr,\n    double lowAreaChange, double highAreaChange,\n    uint32_t nReest,\n    \n    homography *H,\n    matchesType *inlierInds\n    \n    ){\n    \n    bestNInliers= 0;\n    \n    uint32_t nPutativeMatches= putativeMatches.size();\n    \n    if (nPutativeMatches<3)\n        return 0;\n    \n    //------- prepare\n    \n    bool delWeights= false;\n    if (PMweights==NULL) {\n        PMweights= new std::vector<double>( nPutativeMatches, 1.0 );\n        delWeights= true;\n    }\n    \n    //------- generate Hs\n    \n    detRansac::inlierFinder inlierFinder_obj( ellipses1, ellipses2, putativeMatches, *PMweights, errorThr, lowAreaChange, highAreaChange );\n    \n    // initialize with identity\n    homography Hident; Hident.setIdentity();\n    homography bestH= Hident;\n    \n    double bestScore= 0.0;\n    bestNInliers= 0;\n    bestScore= inlierFinder_obj.getScore( bestH, bestNInliers, NULL );\n    \n    std::vector<homography> Hs;\n    Hs.reserve( nPutativeMatches );\n    \n    for (std::vector< std::pair<uint32_t, uint32_t> >::const_iterator itPM= putativeMatches.begin();\n         itPM!=putativeMatches.end();\n         ++itPM){\n        \n        Hs.push_back( homography( ellipses1[itPM->first], ellipses2[itPM->second] ) );\n        \n    }\n    \n    uint32_t globalNIter= 0;\n    \n    sameRandomObj.shuffle<homography>( Hs.begin(), Hs.end() );\n    \n    {\n        //------- RANSAC core\n        \n        static const double pFail= 0.001;\n        \n        uint32_t nInliers, iH= 0;\n        double score;\n        \n        for (std::vector<homography>::const_iterator itH= Hs.begin();\n             itH!=Hs.end() && globalNIter < detRansac::getNStopping(pFail, nPutativeMatches, bestNInliers);\n             ++itH, ++globalNIter, ++iH){\n            \n            score= inlierFinder_obj.getScore( *itH, nInliers, NULL );\n            \n            if (nInliers>3 && score>bestScore) {\n                bestNInliers= nInliers;\n                bestScore= score;\n                bestH= *itH;\n            }\n            \n        }\n        \n    }\n    \n    \n    if (bestNInliers > 3){\n        \n        matchesType bestInliers;\n        bestInliers.reserve(bestNInliers);\n        uint32_t nInliers_new;\n        inlierFinder_obj.getScore( bestH, nInliers_new, &bestInliers );\n        \n        //------- reestimate\n        \n        homography H_new= bestH;\n        double score_new;\n        matchesType inliers_new= bestInliers;\n        \n        uint32_t iReest;\n        for (iReest= 0; nInliers_new>3 && iReest<nReest; ++iReest){\n            detRansac::getH( ellipses1, ellipses2, inliers_new, H_new );\n            score_new= inlierFinder_obj.getScore( H_new, nInliers_new, &inliers_new );\n            if (nInliers_new>3 && score_new>bestScore){\n                bestScore= score_new;\n                bestNInliers= nInliers_new;\n                bestH= H_new;\n                bestInliers= inliers_new; // don't swap as getH in next iteration needs it!\n            }\n        }\n        \n        if (inlierInds)\n            inlierInds->swap( bestInliers );\n        \n        if (H)\n            *H= bestH;\n        \n    }\n    \n    //------- cleanup\n    \n    if (delWeights)\n        delete PMweights;\n    \n    return bestScore;\n    \n}\n\n\n\nvoid\ndetRansac::getH( std::vector<ellipse> const &ellipses1,\n                 std::vector<ellipse> const &ellipses2,\n                 matchesType const &inliers, homography &H ){\n    \n    Eigen::Matrix<double, Eigen::Dynamic, 7> A( inliers.size()*2, 7 );\n    \n    double *x1, *y1, *x2, *y2, *_temp;\n    ellipse::getCentres( ellipses1, ellipses2, inliers, x1, y1, x2, y2, _temp );\n    uint32_t nInliers= inliers.size();\n    \n    // normalize points\n    homography Hnorm1, Hnorm2;\n    normPoints(x1, y1, nInliers, Hnorm1);\n    normPoints(x2, y2, nInliers, Hnorm2);\n    double Hnorm2inv[9];\n    Hnorm2.getInverse(Hnorm2inv);\n    \n    // fit homography\n    uint32_t i=0;\n    \n    for (matchesType::const_iterator itIn= inliers.begin();\n         itIn!=inliers.end();\n         ++itIn, ++i){\n        \n        A.coeffRef( i*2   , 0 )=    0.0;\n        A.coeffRef( i*2   , 1 )=    0.0;\n        A.coeffRef( i*2   , 2 )=    0.0;\n        A.coeffRef( i*2   , 3 )=  x1[i];\n        A.coeffRef( i*2   , 4 )=  y1[i];\n        A.coeffRef( i*2   , 5 )=    1.0;\n        A.coeffRef( i*2   , 6 )= -y2[i];\n        \n        A.coeffRef( i*2+1 , 0 )= -x1[i];\n        A.coeffRef( i*2+1 , 1 )= -y1[i];\n        A.coeffRef( i*2+1 , 2 )=   -1.0;\n        A.coeffRef( i*2+1 , 3 )=    0.0;\n        A.coeffRef( i*2+1 , 4 )=    0.0;\n        A.coeffRef( i*2+1 , 5 )=    0.0;\n        A.coeffRef( i*2+1 , 6 )=  x2[i];\n        \n    }\n    \n    delete []x1; delete []y1; delete []x2; delete []y2; delete []_temp;\n    \n    typedef Eigen::Matrix<double, 7, 7> matrix7x7;\n    matrix7x7 AtA;\n    AtA.noalias()= A.transpose() * A;\n    Eigen::SelfAdjointEigenSolver<matrix7x7> sol( AtA );\n    Eigen::Matrix<double,7,1> x= sol.eigenvectors().col(0);\n    \n    H.H[0]= x.coeff(0,0); H.H[1]= x.coeff(1,0); H.H[2]= x.coeff(2,0);\n    H.H[3]= x.coeff(3,0); H.H[4]= x.coeff(4,0); H.H[5]= x.coeff(5,0);\n    H.H[6]=          0.0; H.H[7]=          0.0; H.H[8]= x.coeff(6,0);\n    H.normLast();\n    \n    // denormalize H: H= Hnorm2inv * Hnorm * Hnorm1\n    \n    Eigen::Matrix<double, 3, 3> Hnorm2inv_, Hnorm1_, Hnorm_;\n    for (int i=0; i<3; ++i)\n        for (int j=0; j<3; ++j){\n            Hnorm_.coeffRef(i,j)= H.H[i*3+j];\n            Hnorm1_.coeffRef(i,j)= Hnorm1.H[i*3+j];\n            Hnorm2inv_.coeffRef(i,j)= Hnorm2inv[i*3+j];\n        }\n    Eigen::Matrix<double, 3, 3> H_;\n    H_.noalias()= Hnorm2inv_ * Hnorm_ * Hnorm1_;\n    \n    for (int i=0; i<3; ++i)\n        for (int j=0; j<3; ++j)\n            H.H[i*3+j]= H_.coeff(i,j);\n    \n#if 0\n    // this is how it used to be done in OpenCV, not updating though so it might be obsolete..\n    \n    cv::Mat A( inliers.size()*2, 7, cv::DataType<double>::type ), x;\n    \n    double *x1, *y1, *x2, *y2, *_temp;\n    ellipse::getCentres( ellipses1, ellipses2, inliers, x1, y1, x2, y2, _temp );\n    uint32_t nInliers= inliers.size();\n    \n    // normalize points\n    homography Hnorm1, Hnorm2;\n    normPoints(x1, y1, nInliers, Hnorm1);\n    normPoints(x2, y2, nInliers, Hnorm2);\n    double Hnorm2inv[9];\n    Hnorm2.getInverse(Hnorm2inv);\n    \n    // fit homography\n    uint32_t i=0;\n    \n    for (matchesType::const_iterator itIn= inliers.begin();\n         itIn!=inliers.end();\n         ++itIn, ++i){\n        \n        // normalize transform\n        \n        A.at<double>( i*2   , 0 )=    0.0;\n        A.at<double>( i*2   , 1 )=    0.0;\n        A.at<double>( i*2   , 2 )=    0.0;\n        A.at<double>( i*2   , 3 )=  x1[i];\n        A.at<double>( i*2   , 4 )=  y1[i];\n        A.at<double>( i*2   , 5 )=    1.0;\n        A.at<double>( i*2   , 6 )= -y2[i];\n        \n        A.at<double>( i*2+1 , 0 )= -x1[i];\n        A.at<double>( i*2+1 , 1 )= -y1[i];\n        A.at<double>( i*2+1 , 2 )=   -1.0;\n        A.at<double>( i*2+1 , 3 )=    0.0;\n        A.at<double>( i*2+1 , 4 )=    0.0;\n        A.at<double>( i*2+1 , 5 )=    0.0;\n        A.at<double>( i*2+1 , 6 )=  x2[i];\n        \n    }\n    \n    delete []x1; delete []y1; delete []x2; delete []y2; delete []_temp;\n    \n    cv::SVD::solveZ(A, x);\n    \n    H.H[0]= x.at<double>(0,0); H.H[1]= x.at<double>(1,0); H.H[2]= x.at<double>(2,0);\n    H.H[3]= x.at<double>(3,0); H.H[4]= x.at<double>(4,0); H.H[5]= x.at<double>(5,0);\n    H.H[6]=               0.0; H.H[7]=               0.0; H.H[8]= x.at<double>(6,0);\n    H.normLast();\n    \n    // denormalize H: H= Hnorm2inv * Hnorm * Hnorm1\n    \n    cv::Mat Hnorm2inv_(3,3, cv::DataType<double>::type),\n            Hnorm1_(3,3, cv::DataType<double>::type),\n            Hnorm_(3,3, cv::DataType<double>::type);\n    for (int i=0; i<3; ++i)\n        for (int j=0; j<3; ++j){\n            Hnorm_.at<double>(i,j)= H.H[i*3+j];\n            Hnorm1_.at<double>(i,j)= Hnorm1.H[i*3+j];\n            Hnorm2inv_.at<double>(i,j)= Hnorm2inv[i*3+j];\n        }\n    cv::Mat H_= Hnorm2inv_ * Hnorm_ * Hnorm1_;\n    \n    for (int i=0; i<3; ++i)\n        for (int j=0; j<3; ++j)\n            H.H[i*3+j]= H_.at<double>(i,j);\n#endif\n    \n}\n\n\n\nvoid\ndetRansac::normPoints( double *x, double *y, uint32_t n, homography &Hnorm ){\n    \n    double EX= 0, EY= 0, stdX, stdY, EX2= 0, EY2= 0;\n    uint32_t i;\n    \n    // get mean/variance\n    for (i= 0; i<n; ++i){\n        EX+= x[i];\n        EY+= y[i];\n        EX2+= mysqr(x[i]);\n        EY2+= mysqr(y[i]);\n    }\n    EX/=n; EY/=n;\n    EX2/=n; EY2/=n;\n    // max is there just in case std=0 (as later norm=NaN in this case), in this case the dimension gets mapped to 0 (as mean is 0) so scaling makes no difference.. This is not nice however, as it means the problem is illposed\n    stdX= std::max( sqrt(EX2-mysqr(EX)), 1e-4 );\n    stdY= std::max( sqrt(EY2-mysqr(EY)), 1e-4 );\n    \n    double normX= sqrt(2.0)/stdX, normY= sqrt(2.0)/stdY;\n    \n    Hnorm.setIdentity();\n    Hnorm.H[0]= normX; Hnorm.H[2]= -EX*normX;\n    Hnorm.H[4]= normY; Hnorm.H[5]= -EY*normY;\n    \n    // normalize points\n    for (i= 0; i<n; ++i){\n        x[i]= (x[i]-EX)*normX;\n        y[i]= (y[i]-EY)*normY;\n    }\n    \n}\n\n\n\ndetRansac::inlierFinder::inlierFinder(\n    std::vector<ellipse> const &aEllipses1,\n    std::vector<ellipse> const &aEllipses2,\n    matchesType const &aPutativeMatches,\n    std::vector<double> const &aPMweights,\n    double aErrorThr,\n    double aLowAreaChange, double aHighAreaChange) :\n    \n    nIter(0),\n    putativeMatches(&aPutativeMatches), PMweights(&aPMweights),\n    errorThrSq(mysqr(aErrorThr)),\n    lowAreaChangeSq(mysqr(aLowAreaChange)),\n    highAreaChangeSq(mysqr(aHighAreaChange)),\n    nPutativeMatches(aPutativeMatches.size()) {\n    \n    //------- get largest pIDs\n    \n    uint32_t maxpID1= 0, maxpID2= 0;\n    \n    for (matchesType::const_iterator itPM=putativeMatches->begin();\n         itPM != putativeMatches->end();\n         ++itPM){\n        maxpID1= std::max(maxpID1, itPM->first);\n        maxpID2= std::max(maxpID2, itPM->second);\n    }\n    point1Used.clear(); point1Used.resize(maxpID1+1,0);\n    point1Used.clear(); point2Used.resize(maxpID2+1,0);\n    \n    ellipse::getCentres( aEllipses1, aEllipses2, *putativeMatches, x1, y1, x2, y2, areaDiffSq );\n    \n}\n\n\n\ndetRansac::inlierFinder::~inlierFinder(){\n    delete []x1; delete []y1; delete []x2; delete []y2; delete []areaDiffSq;\n}\n\n\n\ndouble\ndetRansac::inlierFinder::getScore( homography const &H, uint32_t &nInliers, matchesType *inliers ){\n    \n    \n    double score, detASq;\n        \n    score= 0.0;\n    nInliers= 0;\n    if (inliers)\n        inliers->clear();\n    \n    detASq= mysqr( H.getDetAffine() );\n    if (detASq<1e-4) return 0.0;\n    \n    double error;\n    uint32_t pID1, pID2, iPM;\n    double x, y, xi, yi;\n    double lowAreaChangeSqByD =  lowAreaChangeSq / detASq;\n    double highAreaChangeSqByD= highAreaChangeSq / detASq;\n    \n    double Hinv[9];\n    H.getInverse( Hinv );\n    \n    ++nIter;\n    \n    iPM= 0;\n    for (matchesType::const_iterator itPM= putativeMatches->begin();\n         itPM!=putativeMatches->end();\n         ++itPM, ++iPM){\n        \n        pID1= itPM->first;\n        pID2= itPM->second;\n        if (point1Used[ pID1 ]==nIter || point2Used[ pID2 ]==nIter)\n            continue;\n        \n        homography::affTransform( H.H , x1[iPM], y1[iPM], x , y );\n        homography::affTransform( Hinv, x2[iPM], y2[iPM], xi, yi );\n        \n        error= mysqr( x1[iPM]-xi ) + mysqr( y1[iPM]-yi ) +\n               mysqr( x2[iPM]-x  ) + mysqr( y2[iPM]-y  );\n        \n        if (error < errorThrSq){\n            /*\n            areaChangeSq= detASq * ellipses2[ pID2 ].getPropAreaSq() / ellipses1[ pID1 ].getPropAreaSq();\n            if ( areaChangeSq > lowAreaChangeSq && areaChangeSq < highAreaChangeSq ){\n            */\n            if (areaDiffSq[iPM] > lowAreaChangeSqByD && areaDiffSq[iPM] < highAreaChangeSqByD) {\n                score+= PMweights->at(iPM);\n                ++nInliers;\n                point1Used[ pID1 ]= nIter;\n                point2Used[ pID2 ]= nIter;\n                if (inliers)\n                    inliers->push_back(std::make_pair(pID1,pID2));\n            }\n        }\n        \n    }\n    \n    return score;\n    \n}\n", "meta": {"hexsha": "62764bb6051dbca82dc75477b10dbcb80fbc9d59", "size": 15979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/search_engine/relja_retrival/matching/det_ransac/det_ransac.cpp", "max_stars_repo_name": "kaloyan13/vise2", "max_stars_repo_head_hexsha": "833a8510c7cbac3cbb8ac4569fd51448906e62f3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2017-07-06T23:44:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T06:53:29.000Z", "max_issues_repo_path": "src/search_engine/relja_retrival/matching/det_ransac/det_ransac.cpp", "max_issues_repo_name": "kaloyan13/vise2", "max_issues_repo_head_hexsha": "833a8510c7cbac3cbb8ac4569fd51448906e62f3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T03:52:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T14:08:33.000Z", "max_forks_repo_path": "src/search_engine/relja_retrival/matching/det_ransac/det_ransac.cpp", "max_forks_repo_name": "kaloyan13/vise2", "max_forks_repo_head_hexsha": "833a8510c7cbac3cbb8ac4569fd51448906e62f3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-07-27T10:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T13:42:43.000Z", "avg_line_length": 29.2655677656, "max_line_length": 226, "alphanum_fraction": 0.573815633, "num_tokens": 5286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18543258984210098}}
{"text": "#pragma once\n#include <Eigen/Core>\n\n#include \"ear/ear.hpp\"\n#include \"tensorfile.hpp\"\n\nnamespace bear {\n\n/// holds two arbitrary values relating to the direct and diffuse paths\ntemplate <typename T>\nstruct DirectDiffuse {\n  T direct;\n  T diffuse;\n};\n\n/// holds two arbitrary values relating to the left and right channels/ears\ntemplate <typename T>\nstruct LeftRight {\n  T left;\n  T right;\n};\n\n/// reference to a single view from a multi-view BRIR set\nstruct SelectedBRIR {\n  size_t brir_index;\n  // TODO: add orientation here\n};\n\nusing namespace Eigen;\n\n/// Holds all non-user-configurable renderer information (like virtual\n/// loudspeaker layouts, BRIR sets, delay sets, decorrelation filters), and\n/// provides methods intended to be used to drive the baseline DSP (like\n/// calculating gains and delays, or accessing the BRIR sets).\n///\n/// For Objects, the data flow should look like this:\n///\n///   type_metadata -calc_objects_gains-> gains\n///   gains, selected_brir -get_vs_gains-> vs_gains\n///   gains, selected_brir -get_direct_delays-> direct_delays\n///   selected_brir -get_diffuse_delays-> diffuse_delays\n///\n/// vs_gains, direct_delays and diffuse_delays are the gains and delays used by\n/// the DSP components.\n///\n/// Note that the gains (length num_gains()) and virtual loudspeaker gains\n/// (length num_virtual_loudspeakers()) are separate, so that extra\n/// processing (e.g. gain normalisation, virtual loudspeaker remapping) can be\n/// inserted without affecting the delay calculation.\nclass Panner {\n public:\n  Panner(const std::string &brir_file_name);\n\n  size_t num_gains() const { return n_gains_; }\n  size_t num_virtual_loudspeakers() const { return n_virtual_loudspeakers_; }\n  size_t num_views() const { return n_views_; }\n\n  void calc_objects_gains(const ear::ObjectsTypeMetadata &type_metadata,\n                          DirectDiffuse<Ref<VectorXd>> gains) const;\n\n  void get_vs_gains(const DirectDiffuse<const Ref<const VectorXd> &> &gains,\n                    DirectDiffuse<Ref<VectorXd>> vs_gains,\n                    SelectedBRIR selected_brir = {}) const;\n\n  // frontal delay used to initialise direct path\n  double get_default_direct_delay() const;\n  // frontal delay used to initialise static path\n  double get_default_static_delay() const;\n\n  LeftRight<double> get_direct_delays(const DirectDiffuse<const Ref<const VectorXd> &> &gains,\n                                      SelectedBRIR selected_brir = {}) const;\n\n  LeftRight<double> get_direct_speakers_delays(const Ref<const VectorXd> &gains,\n                                               SelectedBRIR selected_brir = {}) const;\n\n  void get_diffuse_delays(LeftRight<Ref<VectorXd>> diffuse_delays, SelectedBRIR selected_brir = {}) const;\n\n  void calc_direct_speakers_gains(const ear::DirectSpeakersTypeMetadata &type_metadata,\n                                  Ref<VectorXd> gains) const;\n\n  size_t decorrelator_length() const;\n  const float *get_decorrelator(size_t i) const;\n\n  size_t brir_length() const;\n  const float *get_brir(size_t view, size_t virtual_loudspeaker, size_t ear) const;\n\n  Eigen::MatrixX3d get_views() const;\n\n  bool has_gain_compensation() const;\n  // delays in seconds\n  double compensation_gain(double *gains,\n                           LeftRight<double> direct_delays,\n                           SelectedBRIR selected_brir = {}) const;\n  double compensation_gain(DirectDiffuse<Ref<VectorXd>> gains,\n                           LeftRight<double> direct_delays,\n                           SelectedBRIR selected_brir) const;\n\n  double compensation_gain_direct(const Ref<const VectorXd> &gains, SelectedBRIR selected_brir) const;\n\n  const double decorrelation_delay() const;\n\n  size_t n_hoa_channels() const { return n_hoa_channels_; }\n  size_t hoa_order() const { return hoa_order_; }\n  size_t hoa_ir_length() const { return hoa_irs->shape(2); }\n  const float *get_hoa_ir(size_t channel, size_t ear) const;\n  double hoa_delay() const { return hoa_delay_ / fs; }\n\n private:\n  double get_real_gain_quick(double *gains,\n                             LeftRight<double> direct_delays,\n                             SelectedBRIR selected_brir) const;\n  double get_expected_gain_quick(double *gains,\n                                 LeftRight<double> direct_delays,\n                                 SelectedBRIR selected_brir) const;\n\n  double get_real_gain_quick_direct(const Ref<const VectorXd> &gains, SelectedBRIR selected_brir) const;\n  double get_expected_gain_quick_direct(const Ref<const VectorXd> &gains, SelectedBRIR selected_brir) const;\n\n  template <typename Derived>\n  LeftRight<double> get_delays(const Eigen::DenseBase<Derived> &gains, SelectedBRIR selected_brir = {}) const;\n\n  size_t n_gains_;\n  size_t n_views_;\n  size_t n_virtual_loudspeakers_;\n  size_t brir_length_;\n  size_t decorrelator_length_;\n  size_t decorrelation_delay_;\n  size_t front_loudspeaker_;\n  size_t n_hoa_channels_;\n  size_t hoa_order_;\n  double hoa_delay_ = 0.0;\n  enum class GainCompType { NONE, QUICK } gain_comp_type = GainCompType::NONE;\n\n  std::shared_ptr<tensorfile::NDArrayT<float>> views;\n  std::shared_ptr<tensorfile::NDArrayT<float>> brirs;\n  std::shared_ptr<tensorfile::NDArrayT<float>> delays;\n  std::shared_ptr<tensorfile::NDArrayT<float>> decorrelation_filters;\n  std::shared_ptr<tensorfile::NDArrayT<float>> gain_comp_factors;\n  std::shared_ptr<tensorfile::NDArrayT<float>> hoa_irs;\n  double fs;\n\n  std::unique_ptr<ear::GainCalculatorObjects> gain_calc;\n  std::unique_ptr<ear::GainCalculatorDirectSpeakers> direct_speakers_gain_calc;\n\n  mutable std::vector<double> temp_direct;\n  mutable std::vector<double> temp_diffuse;\n  mutable std::vector<double> temp_direct_diffuse;\n\n  mutable std::vector<double> temp_direct_speakers;\n};\n\n}  // namespace bear\n", "meta": {"hexsha": "61f4e5bb831c2379b0d745157d0c99068f9ffe52", "size": 5757, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "visr_bear/src/panner.hpp", "max_stars_repo_name": "ebu/bear", "max_stars_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2022-02-01T16:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T11:24:59.000Z", "max_issues_repo_path": "visr_bear/src/panner.hpp", "max_issues_repo_name": "ebu/bear", "max_issues_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-03T06:49:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:10:43.000Z", "max_forks_repo_path": "visr_bear/src/panner.hpp", "max_forks_repo_name": "ebu/bear", "max_forks_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "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.6274509804, "max_line_length": 110, "alphanum_fraction": 0.7182560361, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017746, "lm_q2_score": 0.28457601635158564, "lm_q1q2_score": 0.1853599764698333}}
{"text": "// Copyright (c) 2019 Graphcore Ltd. All rights reserved.\n#include \"poplin/Norms.hpp\"\n#include \"poplibs_support/Tracepoint.hpp\"\n#include \"poplibs_support/logging.hpp\"\n#include \"poplin/ConvUtil.hpp\"\n#include \"poplin/Convolution.hpp\"\n#include \"popops/ElementWise.hpp\"\n#include \"popops/Rearrange.hpp\"\n#include \"popops/Reduce.hpp\"\n#include \"popops/ScaledAdd.hpp\"\n#include \"poputil/DebugInfo.hpp\"\n#include \"poputil/TileMapping.hpp\"\n#include \"poputil/Util.hpp\"\n#include \"poputil/VertexTemplates.hpp\"\n#include \"poputil/exceptions.hpp\"\n#include <boost/icl/interval_map.hpp>\n#include <cassert>\n#include <cmath>\n#include <set>\n\nusing namespace poplar;\nusing namespace poplar::program;\nusing namespace poputil;\nusing namespace popops;\nnamespace logging = poplibs_support::logging;\n\nnamespace poplin {\n\nstatic Tensor normReduce(Graph &graph, const Tensor &actsUngrouped,\n                         const Tensor &scale, bool doSquare, Sequence &prog,\n                         const Type &, // partialsType,\n                         const Type &outputType,\n                         const Tensor *outputToCloneFrom,\n                         const DebugNameAndId &dnai) {\n  std::string layer = \"ReduceResult\";\n  Tensor t;\n\n  // The output tensor mapping may be specified or created\n  if (outputToCloneFrom) {\n    t = graph.clone(outputType, *outputToCloneFrom, {dnai, layer});\n  } else {\n    t = createBroadcastOperand(graph, actsUngrouped, outputType, 1, true,\n                               {dnai, layer});\n  }\n\n  if (actsUngrouped.rank() < 2)\n    throw poplibs_error(\"NormReduce with rank \" +\n                        std::to_string(actsUngrouped.rank()) + \" expected >=2\");\n\n  std::vector<std::size_t> reduceDims(actsUngrouped.rank() - 1);\n  std::iota(reduceDims.begin() + 1, reduceDims.end(), 2);\n\n  popops::reduceWithOutput(\n      graph, actsUngrouped, t, reduceDims,\n      {doSquare ? popops::Operation::SQUARE_ADD : popops::Operation::ADD, false,\n       scale},\n      prog, {dnai});\n  return t;\n}\n\nstatic Tensor computeInvStdDev(Graph &graph, const Tensor &mean,\n                               const Tensor &power, float eps, float scaleVar,\n                               Sequence &prog, const Type &invStdDevType,\n                               bool stableAlgo, const DebugNameAndId &dnai) {\n  const auto meanType = mean.elementType();\n  const auto powerType = power.elementType();\n  auto iStdDev = graph.clone(invStdDevType, mean, {dnai, \"iStdDev\"});\n\n  const auto meanFlat = mean.flatten();\n  const auto powerFlat = power.flatten();\n  const auto iStdDevFlat = iStdDev.flatten();\n\n  const auto &target = graph.getTarget();\n  const auto numTiles = target.getNumTiles();\n  const auto cs = graph.addComputeSet({dnai, \"iStdDev\"});\n\n  const auto mapping = graph.getTileMapping(iStdDev);\n  const auto grainSize = target.getVectorWidth(invStdDevType);\n\n  for (auto tile = 0U; tile != numTiles; ++tile) {\n    const auto tileContiguousRegions =\n        graph.getSortedContiguousRegions(iStdDevFlat, mapping[tile]);\n    auto vertexRegions = splitRegionsBetweenWorkers(\n        target, tileContiguousRegions, grainSize, 2 * grainSize);\n\n    for (const auto &regions : vertexRegions) {\n      auto v = graph.addVertex(cs,\n                               templateVertex(\"poplin::InverseStdDeviation\",\n                                              meanType, powerType,\n                                              invStdDevType, stableAlgo),\n                               {{\"mean\", meanFlat.slices(regions)},\n                                {\"power\", powerFlat.slices(regions)},\n                                {\"iStdDev\", iStdDevFlat.slices(regions)}});\n      graph.setInitialValue(v[\"eps\"], eps);\n      graph.setInitialValue(v[\"scaleVar\"], scaleVar);\n      graph.setTileMapping(v, tile);\n    }\n  }\n  prog.add(Execute(cs, {dnai}));\n  return iStdDev;\n}\n\nstatic Tensor broadcastChannelToMatch(const Tensor &ref, const Tensor &t) {\n  return t.flatten().expand(std::vector<std::size_t>(ref.rank() - 2, 1));\n}\n\nstatic bool shouldExecuteCallback(unsigned replicaNormSize, unsigned normSize,\n                                  DistributedNormReduceCallback callback) {\n  // The callback should only be invoked when there is distributed reduction to\n  // be performed.\n  bool executeCallback =\n      normSize > replicaNormSize && callback != nullptr && replicaNormSize > 0;\n  if (executeCallback && normSize % replicaNormSize) {\n    throw poplibs_error(\"Norm batch size must be an integer multiple of \"\n                        \"replica batch size\");\n  }\n  if (executeCallback) {\n    logging::poplin::info(\"All-reduce callback called with group size of {}\",\n                          normSize / replicaNormSize);\n  }\n  return executeCallback;\n}\n\nstatic std::pair<Tensor, Tensor>\nnormStatisticsImpl(Graph &graph, const Tensor &acts, float eps, Sequence &prog,\n                   bool unbiasedVarEstimate, bool stableAlgo,\n                   const Type &partialsType,\n                   DistributedNormReduceCallback reduceCallback,\n                   unsigned normSize, const DebugNameAndId &dnai) {\n  const std::string layer = \"Norm/statistics\";\n  logging::poplin::info(\n      \"normStatistics acts={}, eps={}, unbiasedVarEstimate={}, type={}, \"\n      \"normSize={} name={}\",\n      acts.shape(), eps, unbiasedVarEstimate, partialsType, normSize,\n      dnai.getPathName() + \"/\" + layer);\n\n  size_t numElements = acts.numElements();\n  const auto replicaSize = acts.dim(0);\n  bool executeCallback =\n      shouldExecuteCallback(replicaSize, normSize, reduceCallback);\n\n  // Ideally, we would like the scaling due to the distributed all-reduced to\n  // be done by the all-reduce (see T36825).\n  // But we know it doesn't do that for now and hence the scaling is folded in\n  // here.\n  if (executeCallback) {\n    numElements *= normSize / replicaSize;\n  }\n\n  // Avoid a possible divide by zero FP exception.\n  // Note that numElements will be 0 if acts.dim(1) is 0.\n  if (acts.dim(1) > 0)\n    numElements /= acts.dim(1);\n\n  float scale = 1.0f;\n  float scaleVar = 1.0f;\n  if (numElements > 1) {\n    scale /= numElements;\n    if (unbiasedVarEstimate)\n      scaleVar = static_cast<float>(numElements) / (numElements - 1);\n  }\n\n  auto scaleTensor =\n      graph.addConstant(FLOAT, {}, scale, {dnai, layer + \"/scaleTensor\"});\n  graph.setTileMapping(scaleTensor, 0);\n\n  if (acts.rank() < 2)\n    throw poplibs_error(\"NormReduce with rank \" + std::to_string(acts.rank()) +\n                        \" expected >=2\");\n  std::vector<std::size_t> dims(acts.rank() - 1);\n  std::iota(dims.begin() + 1, dims.end(), 2);\n\n  const auto meanOutputType = acts.elementType();\n  // The actual output type for squared sum may be different as the dynamic\n  // range is higher. The selection should be based on actual statistics\n  // gathered from training experiments. For now keep it at reduced precision\n  // to save memory\n  const auto powerOutputType = partialsType;\n\n  constexpr bool update = false;\n  popops::ReduceParams meanParams{popops::Operation::ADD, update, scaleTensor};\n  popops::ReduceParams powerParams{popops::Operation::SQUARE_ADD, update,\n                                   scaleTensor};\n  poplar::Tensor mean =\n      createBroadcastOperand(graph, acts, meanOutputType, 1, true,\n                             {dnai, layer + \"/mean/ReduceResult\"});\n  poplar::Tensor power =\n      graph.clone(powerOutputType, mean, {dnai, layer + \"/power/ReduceResult\"});\n  if (stableAlgo) {\n    reduceWithOutput(graph, acts, mean, dims, std::move(meanParams), prog,\n                     {dnai, layer + \"/mean\"});\n    logging::poplin::info(\"Stable statistics estimator used\");\n    if (executeCallback) {\n      auto allReduceResult =\n          reduceCallback(graph, {mean}, prog, normSize / replicaSize,\n                         {dnai, layer + \"/mean\"}, {});\n      mean = allReduceResult.at(0);\n    }\n    using namespace popops::expr;\n    auto zeroMeanActs = popops::map(graph, _1 - Cast(_2, acts.elementType()),\n                                    {acts, broadcastChannelToMatch(acts, mean)},\n                                    prog, {dnai, layer + \"/removeMean\"});\n    reduceWithOutput(graph, std::move(zeroMeanActs), power, std::move(dims),\n                     std::move(powerParams), prog, {dnai, layer + \"/power\"});\n  } else {\n    std::vector<poplar::Tensor> outputs = {std::move(mean), std::move(power)};\n    std::vector<popops::SingleReduceOp> reductions = {\n        popops::SingleReduceOp{/*in     = */ acts,\n                               /*dims   = */ dims,\n                               /*params = */ std::move(meanParams),\n                               /*debugName = */ \"mean\"},\n        popops::SingleReduceOp{/*in     = */ acts,\n                               /*dims   = */ std::move(dims),\n                               /*params = */ std::move(powerParams),\n                               /*debugName = */ \"power\"}};\n    popops::reduceMany(graph, reductions, outputs, prog,\n                       {dnai, layer + \"/reduceMany\"});\n    mean = std::move(outputs[0]);\n    power = std::move(outputs[1]);\n  }\n\n  if (executeCallback) {\n    std::vector<Tensor> inputsToCallback;\n    std::string str;\n    if (stableAlgo) {\n      str = \"/power\";\n    } else {\n      inputsToCallback.push_back(mean);\n      str = \"/meanAndPower\";\n    }\n    inputsToCallback.push_back(power);\n\n    auto allReduceResult =\n        reduceCallback(graph, inputsToCallback, prog, normSize / replicaSize,\n                       {dnai, layer + str}, {});\n    if (stableAlgo) {\n      power = allReduceResult.at(0);\n    } else {\n      mean = allReduceResult.at(0);\n      power = allReduceResult.at(1);\n    }\n  }\n\n  auto iStdDev = computeInvStdDev(graph, mean, power, eps, scaleVar, prog,\n                                  acts.elementType(), stableAlgo, {dnai});\n  return std::make_pair(mean, iStdDev);\n}\n\nstd::pair<Tensor, Tensor>\nnormStatistics(Graph &graph, const Tensor &acts, float eps, Sequence &prog,\n               bool unbiasedVarEstimate, bool stableAlgo,\n               const Type &partialsType,\n               const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(\n      debugContext,\n      DI_ARGS(acts, eps, unbiasedVarEstimate, stableAlgo, partialsType));\n\n  auto [mean, iStdDev] = normStatisticsImpl(\n      graph, acts, eps, prog, unbiasedVarEstimate, stableAlgo, partialsType,\n      nullptr, acts.dim(0), {di, \"nonDistributed\"});\n  di.addOutputs(DI_ARGS(mean, iStdDev));\n  return std::make_pair(mean, iStdDev);\n}\n\nstd::pair<poplar::Tensor, poplar::Tensor> distributedNormStatistics(\n    poplar::Graph &graph, const poplar::Tensor &acts, float eps,\n    poplar::program::Sequence &prog, bool unbiasedVarEstimate,\n    DistributedNormReduceCallback callback, unsigned normSize, bool stableAlgo,\n    const poplar::Type &partialsType,\n    const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(\n      debugContext,\n      DI_ARGS(acts, eps, unbiasedVarEstimate, stableAlgo, partialsType));\n  auto [mean, iStdDev] = normStatisticsImpl(\n      graph, acts, eps, prog, unbiasedVarEstimate, stableAlgo, partialsType,\n      callback, normSize, {di, \"Distributed\"});\n  di.addOutputs(DI_ARGS(mean, iStdDev));\n  return std::make_pair(mean, iStdDev);\n}\n\nTensor createNormGamma(Graph &graph, const Tensor &acts, const Type &type,\n                       const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(acts, type));\n  auto output =\n      createBroadcastOperand(graph, acts, type, 1, true, {di, \"gamma\"});\n  di.addOutput(output);\n  return output;\n}\n\nTensor createNormGamma(Graph &graph, const Tensor &acts,\n                       const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(acts));\n  auto output = createNormGamma(graph, acts, acts.elementType(), {di});\n  di.addOutput(output);\n  return output;\n}\n\nTensor createNormBeta(Graph &graph, const Tensor &acts, const Type &type,\n                      const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(acts, type));\n  auto output =\n      createBroadcastOperand(graph, acts, type, 1, true, {di, \"beta\"});\n  di.addOutput(output);\n  return output;\n}\n\nTensor createNormBeta(Graph &graph, const Tensor &acts,\n                      const poplar::DebugContext &debugContext) {\n  poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(acts));\n  auto output = createNormBeta(graph, acts, acts.elementType(), {di});\n  di.addOutput(output);\n  return output;\n}\n\nstd::pair<Tensor, Tensor>\ncreateNormParams(Graph &graph, const Tensor &acts,\n                 const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(acts));\n  auto gamma = createNormGamma(graph, acts, {di});\n  auto beta = createNormBeta(graph, acts, {di});\n  di.addOutputs(DI_ARGS(gamma, beta));\n  return std::make_pair(gamma, beta);\n}\n\nTensor normWhiten(Graph &graph, const Tensor &acts, const Tensor &mean,\n                  const Tensor &iStdDev, Sequence &prog,\n                  const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(acts, mean, iStdDev));\n\n  const std::string layer = \"Whiten\";\n  logging::poplin::info(\"normWhiten acts={}, mean={}, iStdDev={}, name={}\",\n                        acts.shape(), mean.shape(), iStdDev.shape(),\n                        debugContext.getPathName() + \"/\" + layer);\n\n  auto meanBroadcast = broadcastChannelToMatch(acts, mean);\n  auto actsWhitened =\n      sub(graph, acts, meanBroadcast, prog, {di, layer + \"/mean\"});\n  auto iStdDevBroadcast = broadcastChannelToMatch(actsWhitened, iStdDev);\n  mulInPlace(graph, actsWhitened, iStdDevBroadcast, prog,\n             {di, layer + \"/istdDev\"});\n  di.addOutput(actsWhitened);\n  return actsWhitened;\n}\n\nTensor normalise(Graph &graph, const Tensor &actsWhitened, const Tensor &gamma,\n                 const Tensor &beta, Sequence &prog,\n                 const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(debugContext,\n                                 DI_ARGS(actsWhitened, gamma, beta));\n\n  const std::string layer = \"Norm/normalise\";\n  logging::poplin::info(\"normalise actsWhitened={}, gamma={}, beta={}, name={}\",\n                        actsWhitened.shape(), gamma.shape(), beta.shape(),\n                        debugContext.getPathName() + \"/\" + layer);\n\n  auto gammaBroadcast = broadcastChannelToMatch(actsWhitened, gamma);\n  auto actsNormalised =\n      mul(graph, actsWhitened, gammaBroadcast, prog, {di, layer + \"/gamma\"});\n  auto betaBroadcast = broadcastChannelToMatch(actsNormalised, beta);\n  addInPlace(graph, actsNormalised, betaBroadcast, prog, {di, layer + \"/beta\"});\n  di.addOutput(actsNormalised);\n  return actsNormalised;\n}\n\nstatic std::pair<Tensor, Tensor>\nnormParamGradients(Graph &graph, const Tensor &actsWhitened,\n                   const Tensor &gradsIn, float scale, Sequence &prog,\n                   const Type &partialsType, bool attemptRegroup,\n                   const DebugNameAndId &dnai) {\n  const std::string layer = \"Norm/deltas\";\n  logging::poplin::info(\n      \"normParamGradients actsWhitened={}, gradsIn={}, scale={}, \"\n      \"type={}, attemptRegroup={}, name={}\",\n      actsWhitened.shape(), gradsIn.shape(), scale, partialsType,\n      attemptRegroup, dnai.getPathName() + \"/\" + layer);\n\n  auto gradsInMaybeRegrouped =\n      attemptRegroup ? popops::rearrange::regroupIfBeneficial(\n                           graph, gradsIn, actsWhitened, prog, {dnai})\n                     : gradsIn;\n  const auto gradsInMultActs =\n      mul(graph, actsWhitened, gradsInMaybeRegrouped, prog, {dnai, layer});\n\n  auto numChannels = gradsInMultActs.dim(1);\n  const auto concatInputs = concat({gradsInMultActs, gradsInMaybeRegrouped}, 1);\n\n  // For beta = Re{gradsIn} where Re{x} reduces the tensor x along the\n  //                              second dimension to produce a vector\n  //                              of length x.dim(1)\n  // For gamma = Re{actsWhitened .* gradsIn}\n  //                              .* is element-wise multiplication operator\n  //                              Reduction along second dimension\n\n  auto scaleTensor = graph.addConstant(FLOAT, {}, scale, {dnai, \"scaleTensor\"});\n  graph.setTileMapping(scaleTensor, 0);\n\n  const auto concatDeltas =\n      normReduce(graph, concatInputs, scaleTensor, false, prog, partialsType,\n                 gradsInMaybeRegrouped.elementType(), nullptr,\n                 {dnai, layer + \"/JointGammaDelta\"});\n\n  return std::make_pair(concatDeltas.slice(0, numChannels),\n                        concatDeltas.slice(numChannels, 2 * numChannels));\n}\n\nstd::pair<Tensor, Tensor>\nnormParamGradients(Graph &graph, const Tensor &actsWhitened,\n                   const Tensor &gradsIn, Sequence &prog,\n                   const Type &partialsType,\n                   const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(debugContext,\n                                 DI_ARGS(actsWhitened, gradsIn, partialsType));\n\n  auto outputs = normParamGradients(graph, actsWhitened, gradsIn, 1.0, prog,\n                                    partialsType, true, {di});\n  di.addOutputs({{\"gammaGrad\", toProfileValue(outputs.first)},\n                 {\"betaGrad\", toProfileValue(outputs.second)}});\n  return outputs;\n}\n\nTensor normGradients(Graph &graph, const Tensor &gradsIn, const Tensor &gamma,\n                     Sequence &prog, const poplar::DebugContext &debugContext) {\n  poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(gradsIn, gamma));\n\n  const auto layer = \"NormGrad\";\n  logging::poplin::info(\"normGradients gradsIn={}, gamma={}, name={}\",\n                        gradsIn.shape(), gamma.shape(),\n                        debugContext.getPathName() + \"/\" + layer);\n  auto gammaBroadcast = broadcastChannelToMatch(gradsIn, gamma);\n  auto output = mul(graph, gradsIn, gammaBroadcast, prog, {di, layer});\n  di.addOutput(output);\n  return output;\n}\n\nTensor normStatisticsGradientsImpl(Graph &graph, const Tensor &actsWhitened,\n                                   const Tensor &gradsIn,\n                                   const Tensor &invStdDev, Sequence &prog,\n                                   const Type &partialsType, // currently unused\n                                   DistributedNormReduceCallback reduceCallback,\n                                   unsigned normSize,\n                                   const DebugNameAndId &dnai) {\n  logging::poplin::info(\"normStatisticsGradients actsWhitened={}, gradsIn={}, \"\n                        \"invStdDev={}, name={}\",\n                        actsWhitened.shape(), gradsIn.shape(),\n                        invStdDev.shape(), dnai.getPathName());\n\n  const auto replicaNormSize = actsWhitened.dim(0);\n  auto executeCallback =\n      shouldExecuteCallback(replicaNormSize, normSize, reduceCallback);\n  const auto actsShape = actsWhitened.shape();\n  auto numElements = actsWhitened.numElements() / actsWhitened.dim(1);\n\n  // Ideally, we would like the scaling due to the distributed all-reduced to\n  // be done by the all-reduce. But we know it doesn't do that for now and hence\n  // the scaling is folded in here.\n  if (executeCallback) {\n    numElements *= normSize / replicaNormSize;\n  }\n  const float rScale = 1.0f / numElements;\n\n  auto gradsInMaybeRegrouped = popops::rearrange::regroupIfBeneficial(\n      graph, gradsIn, actsWhitened, prog, {dnai});\n\n  // split rScale = rScale1 * rScale2;\n  // TODO: T12898 Research what the optimal split would be dependent on model\n  // and field size.\n  const auto scaleSplit = 3.0f / 4;\n  float rScale1 = std::pow(rScale, scaleSplit);\n  float rScale2 = rScale / rScale1;\n  const auto dType = actsWhitened.elementType();\n\n  // If type is half, ensure that rScale2 is exactly representable in device\n  // HALF type so that the fastest codelet is picked up when rScale2 is used\n  // in the scaledAddTo below.\n  if (dType == HALF) {\n    rScale2 = castToDeviceHalfValue(graph.getTarget(), rScale2);\n    // re-evaluate to get better combined precision\n    rScale1 = rScale / rScale2;\n  }\n  Tensor varDelta, meanDelta;\n  // See Description of Re{} operator in normParamGradients\n  // varDelta = Re{actsWhitened .* gradsIn} * -rScale\n  //   Size of varDelta is the size of inverse standard deviation\n  // meanDelta = Re{gradsIn} * -rScale\n  std::tie(varDelta, meanDelta) =\n      normParamGradients(graph, actsWhitened, gradsInMaybeRegrouped, -rScale1,\n                         prog, partialsType, false, {dnai});\n\n  if (executeCallback) {\n    auto reducedGrads = reduceCallback(graph, {varDelta, meanDelta}, prog,\n                                       normSize / replicaNormSize, {dnai}, {});\n    varDelta = reducedGrads.at(0);\n    meanDelta = reducedGrads.at(1);\n  }\n\n  auto gradient = graph.clone(actsWhitened, {dnai, \"/gradsIn\"});\n  prog.add(Copy(gradsInMaybeRegrouped, gradient, false, {dnai}));\n\n  // gradOut = gradsIn - rScale * actsWhitened .* Br{varDelta}\n  // where Br{x} broadcast x along all dimensions other than dim(1) of\n  // actsWhitened\n  // gradsOut = gradsIn - rScale * actsWhitened .* Br{varDelta} + Br{meanDelta}\n\n  auto varDeltaBroadcast = broadcastChannelToMatch(actsWhitened, varDelta);\n  auto varGrads =\n      mul(graph, actsWhitened, varDeltaBroadcast, prog, {dnai, \"varGrads\"});\n  mulInPlace(graph, meanDelta, rScale2, prog, {dnai, \"scaleMeanDelta\"});\n  auto meanDeltaBroadcast = broadcastChannelToMatch(gradient, meanDelta);\n  addInPlace(graph, gradient, meanDeltaBroadcast, prog, {dnai, \"meanGrads\"});\n  // TODO: T12899 Once scaledAddTo is targeted efficiently in element-wise ops,\n  // this should become a mapInPlace() expression.\n  scaledAddTo(graph, gradient, varGrads, rScale2, prog, {dnai, \"addGrads\"});\n\n  // Br{invStdDev} .* (gradsIn - rScale * actsWhitened .* Br{varDelta}\n  //                   + Br{meanDelta})\n  auto invStdDevBroadcast = broadcastChannelToMatch(gradient, invStdDev);\n  mulInPlace(graph, gradient, invStdDevBroadcast, prog, {dnai});\n  return gradient;\n}\n\nTensor normStatisticsGradients(Graph &graph, const Tensor &actsWhitened,\n                               const Tensor &gradsIn, const Tensor &invStdDev,\n                               Sequence &prog,\n                               const Type &partialsType, // currently unused\n                               const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(\n      debugContext, DI_ARGS(actsWhitened, gradsIn, invStdDev, partialsType));\n  const std::string layer = \"NonDistributedNorm/gradients\";\n\n  auto gradient = normStatisticsGradientsImpl(\n      graph, actsWhitened, gradsIn, invStdDev, prog, partialsType, nullptr,\n      actsWhitened.dim(0), {di, layer});\n  di.addOutput(gradient);\n  return gradient;\n}\n\nTensor distributedNormStatisticsGradients(\n    Graph &graph, const Tensor &actsWhitened, const Tensor &gradsIn,\n    const Tensor &invStdDev, Sequence &prog,\n    DistributedNormReduceCallback normReduceCallback, unsigned normSize,\n    const Type &partialsType, const poplar::DebugContext &debugContext) {\n  POPLIN_TRACEPOINT();\n  poputil::PoplibsOpDebugInfo di(\n      debugContext, DI_ARGS(actsWhitened, gradsIn, invStdDev, partialsType));\n  const std::string layer = \"DistributedNorm/gradients\";\n  auto gradient = normStatisticsGradientsImpl(\n      graph, actsWhitened, gradsIn, invStdDev, prog, partialsType,\n      normReduceCallback, normSize, {di, layer});\n  di.addOutput(gradient);\n  return gradient;\n}\n\n} // namespace poplin\n", "meta": {"hexsha": "5c8361adea3122365d6ad1c9d6de73d22e2f4f59", "size": 23685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/poplin/Norms.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/poplin/Norms.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/poplin/Norms.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": 41.9946808511, "max_line_length": 80, "alphanum_fraction": 0.6441207515, "num_tokens": 5842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.18530842850740364}}
{"text": "// Copyright (c) 2014-2018 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <key_io.h>\n\n#include <base58.h>\n#include <bech32.h>\n#include <script/script.h>\n#include <util/strencodings.h>\n\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/static_visitor.hpp>\n\n#include <assert.h>\n#include <string.h>\n#include <algorithm>\n\n\n/** All alphanumeric characters except for \"0\", \"I\", \"O\", and \"l\" */\nstatic const char* pszBase58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nbool N_DecodeBase58(const char* psz, std::vector<unsigned char>& vch)\n{\n    // Skip leading spaces.\n    while (*psz && isspace(*psz))\n        psz++;\n    // Skip and count leading '1's.\n    int zeroes = 0;\n    while (*psz == '1') {\n        zeroes++;\n        psz++;\n    }\n    // Allocate enough space in big-endian base256 representation.\n    std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.\n    // Process the characters.\n    while (*psz && !isspace(*psz)) {\n        // Decode base58 character\n        const char* ch = strchr(pszBase58, *psz);\n        if (ch == NULL)\n            return false;\n        // Apply \"b256 = b256 * 58 + ch\".\n        int carry = ch - pszBase58;\n        for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {\n            carry += 58 * (*it);\n            *it = carry % 256;\n            carry /= 256;\n        }\n        assert(carry == 0);\n        psz++;\n    }\n    // Skip trailing spaces.\n    while (isspace(*psz))\n        psz++;\n    if (*psz != 0)\n        return false;\n    // Skip leading zeroes in b256.\n    std::vector<unsigned char>::iterator it = b256.begin();\n    while (it != b256.end() && *it == 0)\n        it++;\n    // Copy result into output vector.\n    vch.reserve(zeroes + (b256.end() - it));\n    vch.assign(zeroes, 0x00);\n    while (it != b256.end())\n        vch.push_back(*(it++));\n    return true;\n}\n\nstd::string N_DecodeBase58(const char* psz)\n{\n    std::vector<unsigned char> vch;\n    N_DecodeBase58(psz, vch);\n    std::stringstream ss;\n    ss << std::hex;\n\n    for (unsigned int i = 0; i < vch.size(); i++) {\n        unsigned char* c = &vch[i];\n        ss << std::setw(2) << std::setfill('0') << (int)c[0];\n    }\n\n    return ss.str();\n}\n\nstd::string N_EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)\n{\n    // Skip & count leading zeroes.\n    int zeroes = 0;\n    while (pbegin != pend && *pbegin == 0) {\n        pbegin++;\n        zeroes++;\n    }\n    // Allocate enough space in big-endian base58 representation.\n    std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.\n    // Process the bytes.\n    while (pbegin != pend) {\n        int carry = *pbegin;\n        // Apply \"b58 = b58 * 256 + ch\".\n        for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {\n            carry += 256 * (*it);\n            *it = carry % 58;\n            carry /= 58;\n        }\n        assert(carry == 0);\n        pbegin++;\n    }\n    // Skip leading zeroes in base58 result.\n    std::vector<unsigned char>::iterator it = b58.begin();\n    while (it != b58.end() && *it == 0)\n        it++;\n    // Translate the result into a string.\n    std::string str;\n    str.reserve(zeroes + (b58.end() - it));\n    str.assign(zeroes, '1');\n    while (it != b58.end())\n        str += pszBase58[*(it++)];\n    return str;\n}\n\nstd::string N_EncodeBase58(const std::vector<unsigned char>& vch)\n{\n    return N_EncodeBase58(&vch[0], &vch[0] + vch.size());\n}\n\nbool N_DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n    return N_DecodeBase58(str.c_str(), vchRet);\n}\n\nstd::string N_EncodeBase58Check(const std::vector<unsigned char>& vchIn)\n{\n    // add 4-byte hash check to the end\n    std::vector<unsigned char> vch(vchIn);\n    uint256 hash = Hash(vch.begin(), vch.end());\n    vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);\n    return N_EncodeBase58(vch);\n}\n\nbool N_DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)\n{\n    if (!N_DecodeBase58(psz, vchRet) ||\n        (vchRet.size() < 4)) {\n        vchRet.clear();\n        return false;\n    }\n    // re-calculate the checksum, insure it matches the included 4-byte checksum\n    uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);\n    if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {\n        vchRet.clear();\n        return false;\n    }\n    vchRet.resize(vchRet.size() - 4);\n    return true;\n}\n\nbool N_DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n    return N_DecodeBase58Check(str.c_str(), vchRet);\n}\n\n//namespace\n//{\nclass DestinationEncoder : public boost::static_visitor<std::string>\n{\nprivate:\n    const CChainParams& m_params;\n\npublic:\n    explicit DestinationEncoder(const CChainParams& params) : m_params(params) {}\n\n    //TO_FIX: set body this operator\n    std::string operator()(const CKeyID& id) const\n    {\n        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);\n        data.insert(data.end(), id.begin(), id.end());\n        return EncodeBase58Check(data);\n    }\n\n    //TO_FIX: set body this operator\n    std::string operator()(const CScriptID& id) const\n    {\n        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);\n        data.insert(data.end(), id.begin(), id.end());\n        return EncodeBase58Check(data);\n    }\n    std::string operator()(const PKHash& id) const\n    {\n        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);\n        data.insert(data.end(), id.begin(), id.end());\n        return EncodeBase58Check(data);\n    }\n\n    std::string operator()(const ScriptHash& id) const\n    {\n        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n        data.insert(data.end(), id.begin(), id.end());\n        return N_EncodeBase58Check(data);\n    }\n\n    std::string operator()(const WitnessV0KeyHash& id) const\n    {\n        std::vector<unsigned char> data = {0};\n        data.reserve(33);\n        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());\n        //TO_FIX: Link with body\n       // return bech32::Encode(m_params.Bech32HRP(), data);\n    }\n\n    std::string operator()(const WitnessV0ScriptHash& id) const\n    {\n        std::vector<unsigned char> data = {0};\n        data.reserve(53);\n        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());\n        //TO_FIX: Link with body\n        //return bech32::Encode(m_params.Bech32HRP(), data);\n    }\n\n    std::string operator()(const WitnessUnknown& id) const\n    {\n        if (id.version < 1 || id.version > 16 || id.length < 2 || id.length > 40) {\n            return {};\n        }\n        std::vector<unsigned char> data = {(unsigned char)id.version};\n        data.reserve(1 + (id.length * 8 + 4) / 5);\n        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.program, id.program + id.length);\n        //TO_FIX: Link with body\n        //return bech32::Encode(m_params.Bech32HRP(), data);\n    }\n\n    std::string operator()(const CNoDestination& no) const { return {}; }\n};\n\nCTxDestination DecodeDestination(const std::string& str, const CChainParams& params)\n{\n    std::vector<unsigned char> data;\n    uint160 hash;\n    if (N_DecodeBase58Check(str, data)) {\n        // base58-encoded Bitcoin addresses.\n        // Public-key-hash-addresses have version 0 (or 111 testnet).\n        // The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.\n        const std::vector<unsigned char>& pubkey_prefix = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);\n        if (data.size() == hash.size() + pubkey_prefix.size() && std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {\n            std::copy(data.begin() + pubkey_prefix.size(), data.end(), hash.begin());\n            return PKHash(hash);\n        }\n        // Script-hash-addresses have version 5 (or 196 testnet).\n        // The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.\n        const std::vector<unsigned char>& script_prefix = params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n        if (data.size() == hash.size() + script_prefix.size() && std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {\n            std::copy(data.begin() + script_prefix.size(), data.end(), hash.begin());\n            return ScriptHash(hash);\n        }\n    }\n    data.clear();\n    auto bech = bech32::Decode(str);\n    if (bech.second.size() > 0 /*&& bech.first == params.Bech32HRP()*/) {\n        // Bech32 decoding\n        int version = bech.second[0]; // The first 5 bit symbol is the witness version (0-16)\n        // The rest of the symbols are converted witness program bytes.\n        data.reserve(((bech.second.size() - 1) * 5) / 8);\n        if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, bech.second.begin() + 1, bech.second.end())) {\n            if (version == 0) {\n                {\n                    WitnessV0KeyHash keyid;\n                    if (data.size() == keyid.size()) {\n                        std::copy(data.begin(), data.end(), keyid.begin());\n                        return keyid;\n                    }\n                }\n                {\n                    /*WitnessV0ScriptHash scriptid;\n                    if (data.size() == scriptid.size()) {\n                        std::copy(data.begin(), data.end(), scriptid.begin());\n                        return scriptid;\n                    }*/\n                }\n                return CNoDestination();\n            }\n            if (version > 16 || data.size() < 2 || data.size() > 40) {\n                return CNoDestination();\n            }\n            /*WitnessUnknown unk;\n            unk.version = version;\n            std::copy(data.begin(), data.end(), unk.program);\n            unk.length = data.size();\n            return unk;*/\n        }\n    }\n    return CNoDestination();\n}\n//} // namespace\n\nCKey DecodeSecret(const std::string& str)\n{\n    CKey key;\n    std::vector<unsigned char> data;\n    if (N_DecodeBase58Check(str, data)) {\n        const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);\n        if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&\n            std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {\n            bool compressed = data.size() == 33 + privkey_prefix.size();\n            key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);\n        }\n    }\n    if (!data.empty()) {\n        memory_cleanse(data.data(), data.size());\n    }\n    return key;\n}\n\nstd::string EncodeSecret(const CKey& key)\n{\n    assert(key.IsValid());\n    std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);\n    data.insert(data.end(), key.begin(), key.end());\n    if (key.IsCompressed()) {\n        data.push_back(1);\n    }\n    std::string ret = N_EncodeBase58Check(data);\n    memory_cleanse(data.data(), data.size());\n    return ret;\n}\n\nCExtPubKey DecodeExtPubKey(const std::string& str)\n{\n    CExtPubKey key;\n    std::vector<unsigned char> data;\n    if (N_DecodeBase58Check(str, data)) {\n        const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);\n        if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {\n            key.Decode(data.data() + prefix.size());\n        }\n    }\n    return key;\n}\n\nstd::string EncodeExtPubKey(const CExtPubKey& key)\n{\n    std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);\n    size_t size = data.size();\n    data.resize(size + BIP32_EXTKEY_SIZE);\n    key.Encode(data.data() + size);\n    std::string ret = N_EncodeBase58Check(data);\n    return ret;\n}\n\nCExtKey DecodeExtKey(const std::string& str)\n{\n    CExtKey key;\n    std::vector<unsigned char> data;\n    if (N_DecodeBase58Check(str, data)) {\n        const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);\n        if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {\n            key.Decode(data.data() + prefix.size());\n        }\n    }\n    return key;\n}\n\nstd::string EncodeExtKey(const CExtKey& key)\n{\n    std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);\n    size_t size = data.size();\n    data.resize(size + BIP32_EXTKEY_SIZE);\n    key.Encode(data.data() + size);\n    std::string ret = N_EncodeBase58Check(data);\n    memory_cleanse(data.data(), data.size());\n    return ret;\n}\n\nstd::string EncodeDestination(const CTxDestination& dest)\n{\n    return boost::apply_visitor(DestinationEncoder(Params()), dest);\n}\n\nCTxDestination DecodeDestination(const std::string& str)\n{\n    return DecodeDestination(str, Params());\n}\n\nbool IsValidDestinationString(const std::string& str, const CChainParams& params)\n{\n    return IsValidDestination(DecodeDestination(str, params));\n}\n\nbool IsValidDestinationString(const std::string& str)\n{\n    return IsValidDestinationString(str, Params());\n}\n\nbool IsValidContractSenderAddressString(const std::string& str)\n{\n    return IsValidContractSenderAddress(DecodeDestination(str));\n}\n\n#ifdef ENABLE_BITCORE_RPC\nbool DecodeIndexKey(const std::string &str, uint256 &hashBytes, int &type)\n{\n    CTxDestination dest = DecodeDestination(str);\n    if (IsValidDestination(dest))\n    {\n        const PKHash *keyID = boost::get<PKHash>(&dest);\n        if(keyID)\n        {\n            memcpy(&hashBytes, keyID, 20);\n            type = 1;\n            return true;\n        }\n\n        const ScriptHash *scriptID = boost::get<ScriptHash>(&dest);\n        if(scriptID)\n        {\n            memcpy(&hashBytes, scriptID, 20);\n            type = 2;\n            return true;\n        }\n\n        const WitnessV0ScriptHash *witnessV0ScriptID = boost::get<WitnessV0ScriptHash>(&dest);\n        if (witnessV0ScriptID) {\n            memcpy(&hashBytes, witnessV0ScriptID, 32);\n            type = 3;\n            return true;\n        }\n\n        const WitnessV0KeyHash *witnessV0KeyID = boost::get<WitnessV0KeyHash>(&dest);\n        if (witnessV0KeyID) {\n            memcpy(&hashBytes, witnessV0KeyID, 20);\n            type = 4;\n            return true;\n        }\n    }\n\n    return false;\n}\n#endif\n", "meta": {"hexsha": "c627b6fcbc7075ce8ea37a5475eaeb5e9eda671b", "size": 14745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/key_io.cpp", "max_stars_repo_name": "newcodepusher/bu", "max_stars_repo_head_hexsha": "309652ccff4992fd8265900cde6d3aaeb9c86dad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T01:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T14:35:04.000Z", "max_issues_repo_path": "src/key_io.cpp", "max_issues_repo_name": "newcodepusher/bu", "max_issues_repo_head_hexsha": "309652ccff4992fd8265900cde6d3aaeb9c86dad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-04T02:08:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T02:36:08.000Z", "max_forks_repo_path": "src/key_io.cpp", "max_forks_repo_name": "newcodepusher/bu", "max_forks_repo_head_hexsha": "309652ccff4992fd8265900cde6d3aaeb9c86dad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-01-04T02:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T02:06:43.000Z", "avg_line_length": 33.8965517241, "max_line_length": 136, "alphanum_fraction": 0.6000678196, "num_tokens": 3797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.18529531731680318}}
{"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_AUXILIARY_LARFB_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_AUXILIARY_LARFB_HPP\n\n#include <boost/assert.hpp>\n#include <boost/numeric/bindings/begin.hpp>\n#include <boost/numeric/bindings/data_order.hpp>\n#include <boost/numeric/bindings/detail/array.hpp>\n#include <boost/numeric/bindings/detail/if_left.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/trans_tag.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 larfb 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//\ntemplate< typename Side, typename Trans >\ninline std::ptrdiff_t larfb( const Side, const Trans, const char direct,\n        const char storev, const fortran_int_t m, const fortran_int_t n,\n        const fortran_int_t k, const float* v, const fortran_int_t ldv,\n        const float* t, const fortran_int_t ldt, float* c,\n        const fortran_int_t ldc, float* work, const fortran_int_t ldwork ) {\n    fortran_int_t info(0);\n    LAPACK_SLARFB( &lapack_option< Side >::value, &lapack_option<\n            Trans >::value, &direct, &storev, &m, &n, &k, v, &ldv, t, &ldt, c,\n            &ldc, work, &ldwork );\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//\ntemplate< typename Side, typename Trans >\ninline std::ptrdiff_t larfb( const Side, const Trans, const char direct,\n        const char storev, const fortran_int_t m, const fortran_int_t n,\n        const fortran_int_t k, const double* v, const fortran_int_t ldv,\n        const double* t, const fortran_int_t ldt, double* c,\n        const fortran_int_t ldc, double* work, const fortran_int_t ldwork ) {\n    fortran_int_t info(0);\n    LAPACK_DLARFB( &lapack_option< Side >::value, &lapack_option<\n            Trans >::value, &direct, &storev, &m, &n, &k, v, &ldv, t, &ldt, c,\n            &ldc, work, &ldwork );\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//\ntemplate< typename Side, typename Trans >\ninline std::ptrdiff_t larfb( const Side, const Trans, const char direct,\n        const char storev, const fortran_int_t m, const fortran_int_t n,\n        const fortran_int_t k, const std::complex<float>* v,\n        const fortran_int_t ldv, const std::complex<float>* t,\n        const fortran_int_t ldt, std::complex<float>* c,\n        const fortran_int_t ldc, std::complex<float>* work,\n        const fortran_int_t ldwork ) {\n    fortran_int_t info(0);\n    LAPACK_CLARFB( &lapack_option< Side >::value, &lapack_option<\n            Trans >::value, &direct, &storev, &m, &n, &k, v, &ldv, t, &ldt, c,\n            &ldc, work, &ldwork );\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//\ntemplate< typename Side, typename Trans >\ninline std::ptrdiff_t larfb( const Side, const Trans, const char direct,\n        const char storev, const fortran_int_t m, const fortran_int_t n,\n        const fortran_int_t k, const std::complex<double>* v,\n        const fortran_int_t ldv, const std::complex<double>* t,\n        const fortran_int_t ldt, std::complex<double>* c,\n        const fortran_int_t ldc, std::complex<double>* work,\n        const fortran_int_t ldwork ) {\n    fortran_int_t info(0);\n    LAPACK_ZLARFB( &lapack_option< Side >::value, &lapack_option<\n            Trans >::value, &direct, &storev, &m, &n, &k, v, &ldv, t, &ldt, c,\n            &ldc, work, &ldwork );\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 larfb.\n//\ntemplate< typename Value, typename Enable = void >\nstruct larfb_impl {};\n\n//\n// This implementation is enabled if Value is a real type.\n//\ntemplate< typename Value >\nstruct larfb_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 Side, typename MatrixV, typename MatrixT,\n            typename MatrixC, typename WORK >\n    static std::ptrdiff_t invoke( const Side side, const char direct,\n            const char storev, const MatrixV& v, const MatrixT& t, MatrixC& c,\n            const fortran_int_t ldwork, detail::workspace1< WORK > work ) {\n        namespace bindings = ::boost::numeric::bindings;\n        typedef typename result_of::data_order< MatrixT >::type order;\n        typedef typename result_of::trans_tag< MatrixV, order >::type trans;\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixC >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixV >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixT >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixV >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixC >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixC >::value) );\n        BOOST_ASSERT( bindings::size(work.select(real_type())) >=\n                min_size_work( ldwork, bindings::size_column(t) ));\n        BOOST_ASSERT( bindings::size_minor(c) == 1 ||\n                bindings::stride_minor(c) == 1 );\n        BOOST_ASSERT( bindings::size_minor(t) == 1 ||\n                bindings::stride_minor(t) == 1 );\n        BOOST_ASSERT( bindings::size_minor(v) == 1 ||\n                bindings::stride_minor(v) == 1 );\n        BOOST_ASSERT( bindings::stride_major(c) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_row(c)) );\n        BOOST_ASSERT( bindings::stride_major(t) >= bindings::size_column(t) );\n        BOOST_ASSERT( direct == 'F' || direct == 'B' );\n        BOOST_ASSERT( storev == 'C' || storev == 'R' );\n        return detail::larfb( side, trans(), direct, storev,\n                bindings::size_row(c), bindings::size_column(c),\n                bindings::size_column(t), bindings::begin_value(v),\n                bindings::stride_major(v), bindings::begin_value(t),\n                bindings::stride_major(t), bindings::begin_value(c),\n                bindings::stride_major(c),\n                bindings::begin_value(work.select(real_type())), ldwork );\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 Side, typename MatrixV, typename MatrixT,\n            typename MatrixC >\n    static std::ptrdiff_t invoke( const Side side, const char direct,\n            const char storev, const MatrixV& v, const MatrixT& t, MatrixC& c,\n            const fortran_int_t ldwork, minimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        typedef typename result_of::data_order< MatrixT >::type order;\n        typedef typename result_of::trans_tag< MatrixV, order >::type trans;\n        bindings::detail::array< real_type > tmp_work( min_size_work( ldwork,\n                bindings::size_column(t) ) );\n        return invoke( side, direct, storev, v, t, c, ldwork,\n                workspace( tmp_work ) );\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 Side, typename MatrixV, typename MatrixT,\n            typename MatrixC >\n    static std::ptrdiff_t invoke( const Side side, const char direct,\n            const char storev, const MatrixV& v, const MatrixT& t, MatrixC& c,\n            const fortran_int_t ldwork, optimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        typedef typename result_of::data_order< MatrixT >::type order;\n        typedef typename result_of::trans_tag< MatrixV, order >::type trans;\n        return invoke( side, direct, storev, v, t, c, ldwork,\n                minimal_workspace() );\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 std::ptrdiff_t ldwork,\n            const std::ptrdiff_t k ) {\n        return ldwork * k;\n    }\n};\n\n//\n// This implementation is enabled if Value is a complex type.\n//\ntemplate< typename Value >\nstruct larfb_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 Side, typename MatrixV, typename MatrixT,\n            typename MatrixC, typename WORK >\n    static std::ptrdiff_t invoke( const Side side, const char direct,\n            const char storev, const MatrixV& v, const MatrixT& t, MatrixC& c,\n            const fortran_int_t ldwork, detail::workspace1< WORK > work ) {\n        namespace bindings = ::boost::numeric::bindings;\n        typedef typename result_of::data_order< MatrixT >::type order;\n        typedef typename result_of::trans_tag< MatrixV, order >::type trans;\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixC >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixV >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixT >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixV >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixC >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixC >::value) );\n        BOOST_ASSERT( bindings::size(work.select(value_type())) >=\n                min_size_work( ldwork, bindings::size_column(t) ));\n        BOOST_ASSERT( bindings::size_minor(c) == 1 ||\n                bindings::stride_minor(c) == 1 );\n        BOOST_ASSERT( bindings::size_minor(t) == 1 ||\n                bindings::stride_minor(t) == 1 );\n        BOOST_ASSERT( bindings::size_minor(v) == 1 ||\n                bindings::stride_minor(v) == 1 );\n        BOOST_ASSERT( bindings::stride_major(c) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_row(c)) );\n        BOOST_ASSERT( bindings::stride_major(t) >= bindings::size_column(t) );\n        BOOST_ASSERT( direct == 'F' || direct == 'B' );\n        BOOST_ASSERT( storev == 'C' || storev == 'R' );\n        return detail::larfb( side, trans(), direct, storev,\n                bindings::size_row(c), bindings::size_column(c),\n                bindings::size_column(t), bindings::begin_value(v),\n                bindings::stride_major(v), bindings::begin_value(t),\n                bindings::stride_major(t), bindings::begin_value(c),\n                bindings::stride_major(c),\n                bindings::begin_value(work.select(value_type())), ldwork );\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 Side, typename MatrixV, typename MatrixT,\n            typename MatrixC >\n    static std::ptrdiff_t invoke( const Side side, const char direct,\n            const char storev, const MatrixV& v, const MatrixT& t, MatrixC& c,\n            const fortran_int_t ldwork, minimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        typedef typename result_of::data_order< MatrixT >::type order;\n        typedef typename result_of::trans_tag< MatrixV, order >::type trans;\n        bindings::detail::array< value_type > tmp_work( min_size_work( ldwork,\n                bindings::size_column(t) ) );\n        return invoke( side, direct, storev, v, t, c, ldwork,\n                workspace( tmp_work ) );\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 Side, typename MatrixV, typename MatrixT,\n            typename MatrixC >\n    static std::ptrdiff_t invoke( const Side side, const char direct,\n            const char storev, const MatrixV& v, const MatrixT& t, MatrixC& c,\n            const fortran_int_t ldwork, optimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        typedef typename result_of::data_order< MatrixT >::type order;\n        typedef typename result_of::trans_tag< MatrixV, order >::type trans;\n        return invoke( side, direct, storev, v, t, c, ldwork,\n                minimal_workspace() );\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 std::ptrdiff_t ldwork,\n            const std::ptrdiff_t k ) {\n        return ldwork * k;\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 larfb_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 larfb. Its overload differs for\n// * User-defined workspace\n//\ntemplate< typename Side, typename MatrixV, typename MatrixT, typename MatrixC,\n        typename Workspace >\ninline typename boost::enable_if< detail::is_workspace< Workspace >,\n        std::ptrdiff_t >::type\nlarfb( const Side side, const char direct, const char storev,\n        const MatrixV& v, const MatrixT& t, MatrixC& c,\n        const fortran_int_t ldwork, Workspace work ) {\n    return larfb_impl< typename bindings::value_type<\n            MatrixV >::type >::invoke( side, direct, storev, v, t, c, ldwork,\n            work );\n}\n\n//\n// Overloaded function for larfb. Its overload differs for\n// * Default workspace-type (optimal)\n//\ntemplate< typename Side, typename MatrixV, typename MatrixT, typename MatrixC >\ninline typename boost::disable_if< detail::is_workspace< MatrixC >,\n        std::ptrdiff_t >::type\nlarfb( const Side side, const char direct, const char storev,\n        const MatrixV& v, const MatrixT& t, MatrixC& c,\n        const fortran_int_t ldwork ) {\n    return larfb_impl< typename bindings::value_type<\n            MatrixV >::type >::invoke( side, direct, storev, v, t, c, ldwork,\n            optimal_workspace() );\n}\n\n} // namespace lapack\n} // namespace bindings\n} // namespace numeric\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "e36cc9d7c4e0bc119c6e7a340f3666c49c26277d", "size": 17061, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/boost/numeric/bindings/lapack/auxiliary/larfb.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/auxiliary/larfb.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/auxiliary/larfb.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": 43.3020304569, "max_line_length": 84, "alphanum_fraction": 0.6601606002, "num_tokens": 4058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.18529531024132528}}
{"text": "//\n// Created by eliane on 26/12/18.\n//\n\n#include \"ReScorer.h\"\n\n#include <exception>\n\n#include <Engines/Internals/InternalsUtilityFunctions.h>\n\n#include <boost/log/core.hpp>\n#include <boost/log/trivial.hpp>\n\nnamespace SmolDock {\n    ReScorer::ReScorer(SmolDock::Protein &prot, SmolDock::Molecule &mol, Score::ScoringFunctionType scorFuncType) :\n            protein(prot), molecule(mol),\n            scoringFunctionType(scorFuncType) {\n\n\n    }\n\n    bool ReScorer::prepare() {\n\n\n        this->iprotein = this->protein.getiProtein();\n        this->iconformer = this->molecule.getInitialConformer();\n        this->itransform = iTransformIdentityInit();\n        this->scoringFunction = scoringFunctionFactory(this->scoringFunctionType, this->iconformer,\n                                                       this->iprotein, this->itransform,\n                                                       10e-3);\n\n        return true;\n    }\n\n    double ReScorer::getScore() {\n        if (this->prepared == false) {\n            BOOST_LOG_TRIVIAL(error) << \"Rescorer getScore() called before prepare() \";\n            std::terminate();\n        }\n        arma::mat state = this->scoringFunction->getStartingConditions();\n        double score = this->scoringFunction->Evaluate(state);\n        return score;\n    }\n\n\n}\n", "meta": {"hexsha": "c64d6ebed6ca7e4b75323fdbdc620073688adb04", "size": 1300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Utilities/ReScorer.cpp", "max_stars_repo_name": "ElianeBriand/SMolDock", "max_stars_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T02:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T02:33:13.000Z", "max_issues_repo_path": "Utilities/ReScorer.cpp", "max_issues_repo_name": "ElianeBriand/SMolDock", "max_issues_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "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": "Utilities/ReScorer.cpp", "max_forks_repo_name": "ElianeBriand/SMolDock", "max_forks_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T19:11:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:45:49.000Z", "avg_line_length": 27.6595744681, "max_line_length": 115, "alphanum_fraction": 0.5992307692, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.1852728217793457}}
{"text": "#include <polyfem/SplineBasis3d.hpp>\n\n#include <polyfem/QuadraticBSpline3d.hpp>\n#include <polyfem/HexQuadrature.hpp>\n\n\n#include <polysolve/LinearSolver.hpp>\n#include <polyfem/MeshNodes.hpp>\n#include <polyfem/FEBasis3d.hpp>\n#include <polyfem/Types.hpp>\n\n#include <polyfem/Common.hpp>\n#include <polyfem/auto_q_bases.hpp>\n\n#include <Eigen/Sparse>\n\n#include <cassert>\n#include <iostream>\n#include <vector>\n#include <array>\n#include <map>\n#include <numeric>\n\n\n//TODO carefull with simplices\n\nnamespace polyfem\n{\n    using namespace Eigen;\n    using namespace polysolve;\n\n    namespace\n    {\n        class SpaceMatrix\n        {\n        public:\n            inline const int &operator()(const int i, const int j, const int k) const\n            {\n                return space_[k](i,j);\n            }\n\n            inline int &operator()(const int i, const int j, const int k)\n            {\n                return space_[k](i,j);\n            }\n\n            bool is_k_regular = false;\n            int x,y,z;\n            int edge_id;\n\n\n            bool is_regular(const int xx, const int yy, const int zz) const\n            {\n                if(!is_k_regular) return true;\n\n                return !((x == 1 && y == yy && z == zz) || (x == xx && y == 1 && z == zz) || (x == xx && y == yy && z == 1));\n                // space(1, y, z).size() <= 1 && space(x, 1, z).size() <= 1 && space(x, y, 1).size() <= 1\n            }\n\n        private:\n            std::array<Matrix<int, 3, 3> , 3> space_;\n        };\n\n        bool is_edge_singular(const Navigation3D::Index &index, const Mesh3D &mesh)\n        {\n            std::vector<int> ids;\n            mesh.get_edge_elements_neighs(index.edge, ids);\n\n            if(ids.size() == 4 || mesh.is_boundary_edge(index.edge))\n                return false;\n\n            for(auto idx : ids)\n            {\n                if(mesh.is_polytope(idx))\n                    return false;\n            }\n\n            return true;\n        }\n\n\n        void print_local_space(const SpaceMatrix &space)\n        {\n            for(int k = 2; k >= 0; --k)\n            {\n                for(int j=2; j >=0; --j)\n                {\n                    for(int i=0; i < 3; ++i)\n                    {\n                        // if(space(i, j, k).size() > 0){\n                            // for(std::size_t l = 0; l < space(i, j, k).size(); ++l)\n                        std::cout<<space(i, j, k)<<\"\\t\";\n                        // }\n                        // else\n                            // std::cout<<\"x\\t\";\n                    }\n                    std::cout<<std::endl;\n                }\n\n                std::cout<<\"\\n\"<<std::endl;\n            }\n        }\n\n\n\n\n        int node_id_from_face_index(const Mesh3D &mesh, MeshNodes &mesh_nodes, const Navigation3D::Index &index)\n        {\n            int el_id = mesh.switch_element(index).element;\n            if(el_id >= 0 && mesh.is_cube(el_id))\n            {\n                return mesh_nodes.node_id_from_cell(el_id);\n            }\n\n            return mesh_nodes.node_id_from_face(index.face);\n        }\n\n        int node_id_from_edge_index(const Mesh3D &mesh, MeshNodes &mesh_nodes, const Navigation3D::Index &index)\n        {\n            Navigation3D::Index new_index = mesh.switch_element(index);\n            int el_id = new_index.element;\n\n            if(el_id < 0 || mesh.is_polytope(el_id))\n            {\n                new_index = mesh.switch_element(mesh.switch_face(index));\n                el_id = new_index.element;\n\n                if(el_id < 0 || mesh.is_polytope(el_id))\n                {\n                    return mesh_nodes.node_id_from_edge(index.edge);\n                }\n\n                return node_id_from_face_index(mesh, mesh_nodes, mesh.switch_face(new_index));\n            }\n\n            return node_id_from_face_index(mesh, mesh_nodes, mesh.switch_face(new_index));\n        }\n\n\n        int node_id_from_vertex_index_explore(const Mesh3D &mesh, const MeshNodes &mesh_nodes, const Navigation3D::Index &index, int &node_id)\n        {\n            Navigation3D::Index new_index = mesh.switch_element(index);\n\n            int id = new_index.element;\n\n            if(id < 0 || mesh.is_polytope(id))\n            {\n                // id = vertex_node_id(index.vertex);\n                // node = node_from_vertex(index.vertex);\n                node_id = mesh_nodes.primitive_from_vertex(index.vertex);\n                return 3;\n            }\n\n            new_index = mesh.switch_element(mesh.switch_face(new_index));\n            id = new_index.element;\n\n            if(id < 0 || mesh.is_polytope(id))\n            {\n                // id = edge_node_id(switch_edge(new_index).edge);\n                // node = node_from_edge(switch_edge(new_index).edge);\n                node_id = mesh_nodes.primitive_from_edge(mesh.switch_edge(new_index).edge);\n                return 2;\n            }\n\n            new_index = mesh.switch_element(mesh.switch_face(mesh.switch_edge(new_index)));\n            id = new_index.element;\n\n            if(id < 0 || mesh.is_polytope(id))\n            {\n                // id = face_node_id(new_index.face);\n                // node = node_from_face(new_index.face);\n                node_id = mesh_nodes.primitive_from_face(new_index.face);\n                return 1;\n            }\n\n            // node = node_from_element(id);\n            node_id = mesh_nodes.primitive_from_cell(id);\n            return 0;\n        }\n\n        int node_id_from_vertex_index(const Mesh3D &mesh, MeshNodes &mesh_nodes, const Navigation3D::Index &index)\n        {\n            std::array<int, 6> path;\n            std::array<int, 6> primitive_ids;\n\n            path[0] = node_id_from_vertex_index_explore(mesh, mesh_nodes, index, primitive_ids[0]);\n            path[1] = node_id_from_vertex_index_explore(mesh, mesh_nodes, mesh.switch_face(index), primitive_ids[1]);\n\n            path[2] = node_id_from_vertex_index_explore(mesh, mesh_nodes, mesh.switch_edge(index), primitive_ids[2]);\n            path[3] = node_id_from_vertex_index_explore(mesh, mesh_nodes, mesh.switch_face(mesh.switch_edge(index)), primitive_ids[3]);\n\n            path[4] = node_id_from_vertex_index_explore(mesh, mesh_nodes, mesh.switch_edge(mesh.switch_face(index)), primitive_ids[4]);\n            path[5] = node_id_from_vertex_index_explore(mesh, mesh_nodes, mesh.switch_face(mesh.switch_edge(mesh.switch_face(index))), primitive_ids[5]);\n\n            const int min_path = *std::min_element(path.begin(), path.end());\n\n            int primitive_id = 0;\n            for(int i = 0 ; i < 6; ++i)\n            {\n                if(path[i]==min_path)\n                {\n                    primitive_id = primitive_ids[i];\n                    break;\n                }\n            }\n\n            return mesh_nodes.node_id_from_primitive(primitive_id);\n        }\n\n\n        void get_edge_elements_neighs(const Mesh3D &mesh, MeshNodes &mesh_nodes, const int element_id, const int edge_id, int dir, std::vector<int> &ids)\n        {\n            std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 12> to_edge;\n            mesh.to_edge_functions(to_edge);\n\n            Navigation3D::Index index;\n            for(int i = 0; i < 12; ++i)\n            {\n                index = to_edge[i](mesh.get_index_from_element(element_id));\n\n                if(index.edge == edge_id)\n                    break;\n            }\n\n            assert(index.edge == edge_id);\n\n            if(dir == 1)\n            {\n                int id;\n                do\n                {\n                    ids.push_back(mesh_nodes.node_id_from_cell(index.element));\n                    index = mesh.next_around_edge(index);\n                }\n                while(index.element != element_id);\n\n                return;\n            }\n\n            if(dir == 0)\n            {\n                int id;\n                do\n                {\n                    const Navigation3D::Index f_index = mesh.switch_face(mesh.switch_edge(index));\n                    ids.push_back(node_id_from_face_index(mesh, mesh_nodes, f_index));\n\n                    index = mesh.next_around_edge(index);\n                }\n                while(index.element != element_id);\n\n                return;\n            }\n\n            if(dir == 2)\n            {\n                int id;\n                do\n                {\n                    const Navigation3D::Index f_index = mesh.switch_face(mesh.switch_edge(mesh.switch_vertex(index)));\n                    ids.push_back(node_id_from_face_index(mesh, mesh_nodes, f_index));\n\n                    index = mesh.next_around_edge(index);\n                }\n                while(index.element != element_id);\n\n                return;\n            }\n\n            assert(false);\n        }\n\n        void add_edge_id_for_poly(const Navigation3D::Index &index, const Mesh3D &mesh, MeshNodes &mesh_nodes, const int global_index, std::map<int, InterfaceData> &poly_face_to_data)\n        {\n           const int f1 = index.face;\n           const int f2 = mesh.switch_face(index).face;\n\n           const int id1 = mesh_nodes.primitive_from_face(f1);\n           const int id2 = mesh_nodes.primitive_from_face(f2);\n\n           if(mesh_nodes.is_primitive_interface(id1))\n           {\n            InterfaceData &data = poly_face_to_data[f1];\n            data.local_indices.push_back(global_index);\n        }\n\n        if(mesh_nodes.is_primitive_interface(id2))\n        {\n            InterfaceData &data = poly_face_to_data[f2];\n            data.local_indices.push_back(global_index);\n        }\n    }\n\n    void add_vertex_id_for_poly(const Navigation3D::Index &index, const Mesh3D &mesh, MeshNodes &mesh_nodes, const int global_index, std::map<int, InterfaceData> &poly_face_to_data)\n    {\n       const int f1 = index.face;\n       const int f2 = mesh.switch_face(index).face;\n       const int f3 = mesh.switch_face(mesh.switch_edge(index)).face;\n\n       const int id1 = mesh_nodes.primitive_from_face(f1);\n       const int id2 = mesh_nodes.primitive_from_face(f2);\n       const int id3 = mesh_nodes.primitive_from_face(f3);\n\n       if(mesh_nodes.is_primitive_interface(id1))\n       {\n        InterfaceData &data = poly_face_to_data[f1];\n        data.local_indices.push_back(global_index);\n    }\n\n    if(mesh_nodes.is_primitive_interface(id2))\n    {\n        InterfaceData &data = poly_face_to_data[f2];\n        data.local_indices.push_back(global_index);\n    }\n\n    if(mesh_nodes.is_primitive_interface(id3))\n    {\n        InterfaceData &data = poly_face_to_data[f3];\n        data.local_indices.push_back(global_index);\n    }\n}\n\nvoid explore_edge(const Navigation3D::Index &index, const Mesh3D &mesh, MeshNodes &mesh_nodes, const int x, const int y, const int z, SpaceMatrix &space, LocalBoundary &local_boundary, std::map<int, InterfaceData> &poly_face_to_data)\n{\n    int node_id = node_id_from_edge_index(mesh, mesh_nodes, index);\n    space(x, y, z) = node_id;\n            // node(x, y, z) = mesh_nodes.node_position(node_id);\n\n\n    if(is_edge_singular(index, mesh))\n    {\n        std::vector<int> ids;\n        mesh.get_edge_elements_neighs(index.edge, ids);\n                //irregular edge\n\n        assert(!space.is_k_regular);\n        space.is_k_regular = true;\n        space.x = x; space.y = y; space.z = z;\n        space.edge_id = index.edge;\n    }\n\n    // if(mesh_nodes.is_boundary(node_id))\n        // bounday_nodes.push_back(node_id);\n\n    add_edge_id_for_poly(index, mesh, mesh_nodes, 9*z + 3*y + x, poly_face_to_data);\n}\n\nvoid explore_vertex(const Navigation3D::Index &index, const Mesh3D &mesh, MeshNodes &mesh_nodes, const int x, const int y, const int z, SpaceMatrix &space, LocalBoundary &local_boundary, std::map<int, InterfaceData> &poly_face_to_data)\n{\n    int node_id = node_id_from_vertex_index(mesh, mesh_nodes, index);\n    space(x, y, z) = node_id;\n            // node(x, y, z) = mesh_nodes.node_position(node_id);\n\n    // if(mesh_nodes.is_boundary(node_id))\n        // bounday_nodes.push_back(node_id);\n\n    add_vertex_id_for_poly(index, mesh, mesh_nodes, 9*z + 3*y + x, poly_face_to_data);\n}\n\nvoid explore_face(const Navigation3D::Index &index, const Mesh3D &mesh, MeshNodes &mesh_nodes, const int x, const int y, const int z,  SpaceMatrix &space, LocalBoundary &local_boundary, std::map<int, InterfaceData> &poly_face_to_data)\n{\n    int node_id = node_id_from_face_index(mesh, mesh_nodes, index);\n    space(x, y, z) = node_id;\n            // node(x, y, z) = mesh_nodes.node_position(node_id);\n\n    if(mesh_nodes.is_boundary(node_id))\n    {\n        // local_boundary.add_boundary_primitive(index.face, FEBasis3d::quadr_hex_face_local_nodes(mesh, index)[8]-20);\n        local_boundary.add_boundary_primitive(index.face, FEBasis3d::hex_face_local_nodes(false, 2, mesh, index)[8]-20);\n        // bounday_nodes.push_back(node_id);\n    }\n    else if(mesh_nodes.is_interface(node_id))\n    {\n        InterfaceData &data = poly_face_to_data[index.face];\n        data.local_indices.push_back(9*z + 3*y + x);\n                // igl::viewer::Viewer &viewer = UIState::ui_state().viewer;\n                // viewer.data.add_points(mesh_nodes.node_position(node_id), Eigen::MatrixXd::Constant(1, 3, 0));\n    }\n}\n\nvoid build_local_space(const Mesh3D &mesh,  MeshNodes &mesh_nodes, const int el_index,  SpaceMatrix &space, std::vector<LocalBoundary> &local_boundary, std::map<int, InterfaceData> &poly_face_to_data)\n{\n    assert(mesh.is_volume());\n\n    Navigation3D::Index start_index = mesh.get_index_from_element(el_index);\n    Navigation3D::Index index;\n\n    std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 6> to_face;\n    mesh.to_face_functions(to_face);\n\n    std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 12> to_edge;\n    mesh.to_edge_functions(to_edge);\n\n    std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 8> to_vertex;\n    mesh.to_vertex_functions(to_vertex);\n\n    const int node_id = mesh_nodes.node_id_from_cell(el_index);\n    space(1, 1, 1) = node_id;\n            // node(1, 1, 1) = mesh_nodes.node_position(node_id);\n\n    LocalBoundary lb(el_index, BoundaryType::Quad);\n\n            ///////////////////////\n    index = to_face[1](start_index);\n    explore_face(index, mesh, mesh_nodes, 1, 1, 0, space, lb, poly_face_to_data);\n\n    index = to_face[0](start_index);\n    explore_face(index, mesh, mesh_nodes, 1, 1, 2, space, lb, poly_face_to_data);\n\n    index = to_face[3](start_index);\n    explore_face(index, mesh, mesh_nodes, 0, 1, 1, space, lb, poly_face_to_data);\n\n    index = to_face[2](start_index);\n    explore_face(index, mesh, mesh_nodes, 2, 1, 1, space, lb, poly_face_to_data);\n\n    index = to_face[5](start_index);\n    explore_face(index, mesh, mesh_nodes, 1, 0, 1, space, lb, poly_face_to_data);\n\n    index = to_face[4](start_index);\n    explore_face(index, mesh, mesh_nodes, 1, 2, 1, space, lb, poly_face_to_data);\n\n\n            ///////////////////////\n    index = to_edge[0](start_index);\n    explore_edge(index, mesh, mesh_nodes, 1, 0, 0, space, lb, poly_face_to_data);\n\n    index = to_edge[1](start_index);\n    explore_edge(index, mesh, mesh_nodes, 2, 1, 0, space, lb, poly_face_to_data);\n\n    index = to_edge[2](start_index);\n    explore_edge(index, mesh, mesh_nodes, 1, 2, 0, space, lb, poly_face_to_data);\n\n    index = to_edge[3](start_index);\n    explore_edge(index, mesh, mesh_nodes, 0, 1, 0, space, lb, poly_face_to_data);\n\n\n    index = to_edge[4](start_index);\n    explore_edge(index, mesh, mesh_nodes, 0, 0, 1, space, lb, poly_face_to_data);\n\n    index = to_edge[5](start_index);\n    explore_edge(index, mesh, mesh_nodes, 2, 0, 1, space, lb, poly_face_to_data);\n\n    index = to_edge[6](start_index);\n    explore_edge(index, mesh, mesh_nodes, 2, 2, 1, space, lb, poly_face_to_data);\n\n    index = to_edge[7](start_index);\n    explore_edge(index, mesh, mesh_nodes, 0, 2, 1, space, lb, poly_face_to_data);\n\n\n\n    index = to_edge[8](start_index);\n    explore_edge(index, mesh, mesh_nodes, 1, 0, 2, space, lb, poly_face_to_data);\n\n    index = to_edge[9](start_index);\n    explore_edge(index, mesh, mesh_nodes, 2, 1, 2, space, lb, poly_face_to_data);\n\n    index = to_edge[10](start_index);\n    explore_edge(index, mesh, mesh_nodes, 1, 2, 2, space, lb, poly_face_to_data);\n\n    index = to_edge[11](start_index);\n    explore_edge(index, mesh, mesh_nodes, 0, 1, 2, space, lb, poly_face_to_data);\n\n\n            ////////////////////////////////////////////////////////////////////////\n    index = to_vertex[0](start_index);\n    explore_vertex(index, mesh, mesh_nodes, 0, 0, 0, space, lb, poly_face_to_data);\n\n    index = to_vertex[1](start_index);\n    explore_vertex(index, mesh, mesh_nodes, 2, 0, 0, space, lb, poly_face_to_data);\n\n    index = to_vertex[2](start_index);\n    explore_vertex(index, mesh, mesh_nodes, 2, 2, 0, space, lb, poly_face_to_data);\n\n    index = to_vertex[3](start_index);\n    explore_vertex(index, mesh, mesh_nodes, 0, 2, 0, space, lb, poly_face_to_data);\n\n\n\n    index = to_vertex[4](start_index);\n    explore_vertex(index, mesh, mesh_nodes, 0, 0, 2, space, lb, poly_face_to_data);\n\n    index = to_vertex[5](start_index);\n    explore_vertex(index, mesh, mesh_nodes, 2, 0, 2, space, lb, poly_face_to_data);\n\n    index = to_vertex[6](start_index);\n    explore_vertex(index, mesh, mesh_nodes, 2, 2, 2, space, lb, poly_face_to_data);\n\n    index = to_vertex[7](start_index);\n    explore_vertex(index, mesh, mesh_nodes, 0, 2, 2, space, lb, poly_face_to_data);\n\n    if(!lb.empty())\n        local_boundary.emplace_back(lb);\n}\n\nvoid setup_knots_vectors(MeshNodes &mesh_nodes, const SpaceMatrix &space, std::array<std::array<double, 4>, 3> &h_knots, std::array<std::array<double, 4>, 3> &v_knots, std::array<std::array<double, 4>, 3> &w_knots)\n{\n            //left and right neigh are absent\n    if(mesh_nodes.is_boundary_or_interface(space(0, 1, 1)) && mesh_nodes.is_boundary_or_interface(space(2, 1, 1)))\n    {\n        h_knots[0] = {{0, 0, 0, 1}};\n        h_knots[1] = {{0, 0, 1, 1}};\n        h_knots[2] = {{0, 1, 1, 1}};\n    }\n             //left neigh is absent\n    else if(mesh_nodes.is_boundary_or_interface(space(0, 1, 1)))\n    {\n        h_knots[0] = {{0, 0, 0, 1}};\n        h_knots[1] = {{0, 0, 1, 2}};\n        h_knots[2] = {{0, 1, 2, 3}};\n    }\n            //right neigh is absent\n    else if(mesh_nodes.is_boundary_or_interface(space(2,1,1)))\n    {\n        h_knots[0] = {{-2, -1, 0, 1}};\n        h_knots[1] = {{-1, 0, 1, 1}};\n        h_knots[2] = {{0, 1, 1, 1}};\n    }\n    else\n    {\n        h_knots[0] = {{-2, -1, 0, 1}};\n        h_knots[1] = {{-1, 0, 1, 2}};\n        h_knots[2] = {{0, 1, 2, 3}};\n    }\n\n\n            //top and bottom neigh are absent\n    if(mesh_nodes.is_boundary_or_interface(space(1,0,1)) && mesh_nodes.is_boundary_or_interface(space(1,2,1)))\n    {\n        v_knots[0] = {{0, 0, 0, 1}};\n        v_knots[1] = {{0, 0, 1, 1}};\n        v_knots[2] = {{0, 1, 1, 1}};\n    }\n            //bottom neigh is absent\n    else if(mesh_nodes.is_boundary_or_interface(space(1,0,1)))\n    {\n        v_knots[0] = {{0, 0, 0, 1}};\n        v_knots[1] = {{0, 0, 1, 2}};\n        v_knots[2] = {{0, 1, 2, 3}};\n    }\n            //top neigh is absent\n    else if(mesh_nodes.is_boundary_or_interface(space(1,2,1)))\n    {\n        v_knots[0] = {{-2, -1, 0, 1}};\n        v_knots[1] = {{-1, 0, 1, 1}};\n        v_knots[2] = {{0, 1, 1, 1}};\n    }\n    else\n    {\n        v_knots[0] = {{-2, -1, 0, 1}};\n        v_knots[1] = {{-1, 0, 1, 2}};\n        v_knots[2] = {{0, 1, 2, 3}};\n    }\n\n\n            //front and back neigh are absent\n    if(mesh_nodes.is_boundary_or_interface(space(1,1,0)) && mesh_nodes.is_boundary_or_interface(space(1,1,2)))\n    {\n        w_knots[0] = {{0, 0, 0, 1}};\n        w_knots[1] = {{0, 0, 1, 1}};\n        w_knots[2] = {{0, 1, 1, 1}};\n    }\n            //back neigh is absent\n    else if(mesh_nodes.is_boundary_or_interface(space(1,1,0)))\n    {\n        w_knots[0] = {{0, 0, 0, 1}};\n        w_knots[1] = {{0, 0, 1, 2}};\n        w_knots[2] = {{0, 1, 2, 3}};\n    }\n            //front neigh is absent\n    else if(mesh_nodes.is_boundary_or_interface(space(1,1,2)))\n    {\n        w_knots[0] = {{-2, -1, 0, 1}};\n        w_knots[1] = {{-1, 0, 1, 1}};\n        w_knots[2] = {{0, 1, 1, 1}};\n    }\n    else\n    {\n        w_knots[0] = {{-2, -1, 0, 1}};\n        w_knots[1] = {{-1, 0, 1, 2}};\n        w_knots[2] = {{0, 1, 2, 3}};\n    }\n}\n\nvoid basis_for_regular_hex(MeshNodes &mesh_nodes, const SpaceMatrix &space, const std::array<std::array<double, 4>, 3> &h_knots, const std::array<std::array<double, 4>, 3> &v_knots, const std::array<std::array<double, 4>, 3> &w_knots, ElementBases &b)\n{\n    for(int z = 0; z < 3; ++z)\n    {\n        for(int y = 0; y < 3; ++y)\n        {\n            for(int x = 0; x < 3; ++x)\n            {\n                        if(space.is_regular(x,y,z)) //space(1, y, z).size() <= 1 && space(x, 1, z).size() <= 1 && space(x, y, 1).size() <= 1)\n                        {\n                            const int local_index = 9*z + 3*y + x;\n                            const int global_index = space(x, y, z);\n                            const auto node = mesh_nodes.node_position(global_index);\n                            // loc_nodes(x, y, z);\n\n                            b.bases[local_index].init(2, global_index, local_index, node);\n\n                            const QuadraticBSpline3d spline(h_knots[x], v_knots[y], w_knots[z]);\n\n                            b.bases[local_index].set_basis([spline](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { spline.interpolate(uv, val); });\n                            b.bases[local_index].set_grad( [spline](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { spline.derivative(uv, val); });\n                        }\n                    }\n                }\n            }\n        }\n\n\n        void basis_for_irregulard_hex(const int el_index, const Mesh3D &mesh, MeshNodes &mesh_nodes, const SpaceMatrix &space, const std::array<std::array<double, 4>, 3> &h_knots, const std::array<std::array<double, 4>, 3> &v_knots, const std::array<std::array<double, 4>, 3> &w_knots, ElementBases &b, std::map<int, InterfaceData> &poly_face_to_data)\n        {\n            for(int z = 0; z < 3; ++z)\n            {\n                for(int y = 0; y < 3; ++y)\n                {\n                    for(int x = 0; x < 3; ++x)\n                    {\n                        if(!space.is_regular(x,y,z)) //space(1, y, z).size() > 1 || space(x, 1, z).size() > 1 || space(x, y, 1).size() > 1)\n                        {\n                            const int local_index = 9*z + 3*y + x;\n\n\n                            int mpx = -1;\n                            int mpy = -1;\n                            int mpz = -1;\n\n                            int mmx = -1;\n                            int mmy = -1;\n                            int mmz = -1;\n\n                            int xx = 1;\n                            int yy = 1;\n                            int zz = 1;\n\n                            const int edge_id = space.edge_id;\n                            int dir = -1;\n\n                            if(space.x == x && space.y == y && space.z == 1)\n                            {\n                                mpx = 1;\n                                mpy = y;\n                                mpz = z;\n\n                                mmx = x;\n                                mmy = 1;\n                                mmz = z;\n\n                                zz = z;\n                                dir = z;\n                            }\n                            else if(space.x == x && space.y == 1 && space.z == z)\n                            {\n                                mpx = 1;\n                                mpy = y;\n                                mpz = z;\n\n                                mmx = x;\n                                mmy = y;\n                                mmz = 1;\n\n                                yy = y;\n                                dir = y;\n                            }\n                            else if(space.x == 1 && space.y == y && space.z == z)\n                            {\n                                mpx = x;\n                                mpy = y;\n                                mpz = 1;\n\n                                mmx = x;\n                                mmy = 1;\n                                mmz = z;\n\n                                xx = x;\n                                dir = x;\n                            }\n                            else\n                                assert(false);\n\n                            const auto &center = b.bases[zz*9 + yy*3 + xx].global().front();\n\n                            const auto &el1 = b.bases[mpz*9 + mpy*3 + mpx].global().front();\n                            const auto &el2 = b.bases[mmz*9 + mmy*3 + mmx].global().front();\n\n                            // std::cout<<\"el_index \"<<el_index<<std::endl;\n                            // std::cout<<\"center \"<<center.index<<std::endl;\n                            // std::cout<<\"el1 \"<<el1.index<<std::endl;\n                            // std::cout<<\"el2 \"<<el2.index<<std::endl;\n\n\n                            std::vector<int> ids;\n                            get_edge_elements_neighs(mesh, mesh_nodes, el_index, edge_id, dir, ids);\n\n                            if(ids.front() != center.index)\n                            {\n                                assert(dir != 1);\n                                ids.clear();\n                                get_edge_elements_neighs(mesh, mesh_nodes, el_index, edge_id, dir == 2 ? 0 : 2, ids);\n                            }\n\n                            assert(ids.front() == center.index);\n\n                            std::vector<int> other_indices;\n                            std::vector<Eigen::MatrixXd> other_nodes;\n                            for(size_t i = 0; i < ids.size(); ++i)\n                            {\n                                const int node_id = ids[i];\n                                if(node_id != center.index && node_id != el1.index && node_id != el2.index){\n                                    other_indices.push_back(node_id);\n                                }\n                            }\n\n                            // std::cout<<ids.size()<< \" \" << other_indices.size()<<std::endl;\n\n                            auto &base = b.bases[local_index];\n\n                            const int k = int(other_indices.size()) + 3;\n\n                            // const bool is_interface = mesh_nodes.is_interface(center.index);\n                            // const int face_id = is_interface ? mesh_nodes.face_from_node_id(center.index) : -1;\n\n\n                            base.global().resize(k);\n\n                            base.global()[0].index = center.index;\n                            base.global()[0].val = (4. - k) / k;\n                            base.global()[0].node = center.node;\n\n                            base.global()[1].index = el1.index;\n                            base.global()[1].val = (4. - k) / k;\n                            base.global()[1].node = el1.node;\n\n                            base.global()[2].index = el2.index;\n                            base.global()[2].val = (4. - k) / k;\n                            base.global()[2].node = el2.node;\n\n                            // if(is_interface){\n                                // poly_face_to_data[face_id].local_indices.push_back(local_index);\n                            // }\n\n                            for(std::size_t n = 0; n < other_indices.size(); ++n)\n                            {\n                                base.global()[3+n].index = other_indices[n];\n                                base.global()[3+n].val = 4./k;\n                                base.global()[3+n].node = mesh_nodes.node_position(other_indices[n]);\n                            }\n\n\n                            const QuadraticBSpline3d spline(h_knots[x], v_knots[y], w_knots[z]);\n\n                            b.bases[local_index].set_basis([spline](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { spline.interpolate(uv, val); });\n                            b.bases[local_index].set_grad( [spline](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { spline.derivative(uv, val); });\n                        }\n                    }\n                }\n            }\n        }\n\n\n        void create_q2_nodes(const Mesh3D &mesh, const int el_index, std::set<int> &vertex_id, std::set<int> &edge_id, std::set<int> &face_id, ElementBases &b, std::vector<LocalBoundary> &local_boundary, int &n_bases)\n        {\n            b.bases.resize(27);\n\n            std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 6> to_face;\n            mesh.to_face_functions(to_face);\n\n            std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 12> to_edge;\n            mesh.to_edge_functions(to_edge);\n\n            std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 8> to_vertex;\n            mesh.to_vertex_functions(to_vertex);\n\n            LocalBoundary lb(el_index, BoundaryType::Quad);\n\n            const Navigation3D::Index start_index = mesh.get_index_from_element(el_index);\n            for (int j = 0; j < 8; ++j)\n            {\n                const Navigation3D::Index index = to_vertex[j](start_index);\n                // const int loc_index = FEBasis3d::quadr_hex_face_local_nodes(mesh, index)[0];\n                const int loc_index = FEBasis3d::hex_face_local_nodes(false, 2, mesh, index)[0];\n\n\n                int current_vertex_node_id = -1;\n                Eigen::MatrixXd current_vertex_node;\n\n                //if the edge/vertex is boundary the it is a Q2 edge\n                bool is_vertex_q2 = true;\n\n                std::vector<int> vertex_neighs;\n                mesh.get_vertex_elements_neighs(index.vertex, vertex_neighs);\n\n                for(size_t i = 0; i < vertex_neighs.size(); ++i)\n                {\n                    if(mesh.is_spline_compatible(vertex_neighs[i]))\n                    {\n                        is_vertex_q2 = false;\n                        break;\n                    }\n                }\n                const bool is_vertex_boundary = mesh.is_boundary_vertex(index.vertex);\n\n                if(is_vertex_q2)\n                {\n                    const bool is_new_vertex = vertex_id.insert(index.vertex).second;\n\n                    if(is_new_vertex)\n                    {\n                        current_vertex_node_id = n_bases++;\n                        current_vertex_node = mesh.point(index.vertex);\n\n                        // if(is_vertex_boundary)//mesh.is_vertex_boundary(index.vertex))\n                            // bounday_nodes.push_back(current_vertex_node_id);\n                    }\n                }\n\n                //init new Q2 nodes\n                if(current_vertex_node_id >= 0)\n                    b.bases[loc_index].init(2, current_vertex_node_id, loc_index, current_vertex_node);\n\n                b.bases[loc_index].set_basis([loc_index](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { autogen::q_basis_value_3d     (2, loc_index, uv, val); });\n                b.bases[loc_index].set_grad( [loc_index](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { autogen::q_grad_basis_value_3d(2, loc_index, uv, val); });\n            }\n\n\n            for (int j = 0; j < 12; ++j)\n            {\n                Navigation3D::Index index = to_edge[j](start_index);\n\n                int current_edge_node_id = -1;\n                Eigen::Matrix<double, 1, 3> current_edge_node;\n                // const int loc_index = FEBasis3d::quadr_hex_face_local_nodes(mesh, index)[1];\n                const int loc_index = FEBasis3d::hex_face_local_nodes(false, 2, mesh, index)[4];\n\n\n                bool is_edge_q2 = true;\n\n                std::vector<int> edge_neighs;\n                mesh.get_edge_elements_neighs(index.edge, edge_neighs);\n\n                for(size_t i = 0; i < edge_neighs.size(); ++i)\n                {\n                    if(mesh.is_spline_compatible(edge_neighs[i]))\n                    {\n                        is_edge_q2 = false;\n                        break;\n                    }\n                }\n                const bool is_edge_boundary = mesh.is_boundary_edge(index.edge);\n\n                if(is_edge_q2)\n                {\n                    const bool is_new_edge = edge_id.insert(index.edge).second;\n\n                    if(is_new_edge)\n                    {\n                        current_edge_node_id = n_bases++;\n                        current_edge_node = mesh.edge_barycenter(index.edge);\n\n                        // if(is_edge_boundary)\n                            // bounday_nodes.push_back(current_edge_node_id);\n                    }\n                }\n\n                //init new Q2 nodes\n                if(current_edge_node_id >= 0)\n                    b.bases[loc_index].init(2, current_edge_node_id, loc_index, current_edge_node);\n\n                b.bases[loc_index].set_basis([loc_index](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { autogen::q_basis_value_3d     (2, loc_index, uv, val); });\n                b.bases[loc_index].set_grad( [loc_index](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { autogen::q_grad_basis_value_3d(2, loc_index, uv, val); });\n            }\n\n            for (int j = 0; j < 6; ++j)\n            {\n                Navigation3D::Index index = to_face[j](start_index);\n\n                int current_face_node_id = -1;\n\n                Eigen::Matrix<double, 1, 3> current_face_node;\n                const int opposite_element = mesh.switch_element(index).element;\n                const bool is_face_q2 = opposite_element < 0 || !mesh.is_spline_compatible(opposite_element);\n                // const int loc_index = FEBasis3d::quadr_hex_face_local_nodes(mesh, index)[8];\n                const int loc_index = FEBasis3d::hex_face_local_nodes(false, 2, mesh, index)[8];\n\n\n                if (is_face_q2)\n                {\n                    const bool is_new_face = face_id.insert(index.face).second;\n\n                    if(is_new_face)\n                    {\n                        current_face_node_id = n_bases++;\n                        current_face_node = mesh.face_barycenter(index.face);\n\n                        const int b_index = loc_index - 20;\n\n                        if(opposite_element < 0) // && mesh.n_element_faces(opposite_element) == 6 && mesh.n_element_vertices(opposite_element) == 8)\n                        {\n                            // bounday_nodes.push_back(current_face_node_id);\n                            lb.add_boundary_primitive(index.face, b_index);\n                        }\n                    }\n                }\n\n                //init new Q2 nodes\n                if(current_face_node_id >= 0)\n                    b.bases[loc_index].init(2, current_face_node_id, loc_index, current_face_node);\n\n                b.bases[loc_index].set_basis([loc_index](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { autogen::q_basis_value_3d     (2, loc_index, uv, val); });\n                b.bases[loc_index].set_grad( [loc_index](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { autogen::q_grad_basis_value_3d(2, loc_index, uv, val); });\n            }\n\n            // //central node always present\n            b.bases[26].init(2, n_bases++, 26, mesh.cell_barycenter(el_index));\n            b.bases[26].set_basis([](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { autogen::q_basis_value_3d     (2, 26, uv, val); });\n            b.bases[26].set_grad( [](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { autogen::q_grad_basis_value_3d(2, 26, uv, val); });\n\n            if(!lb.empty())\n                local_boundary.emplace_back(lb);\n        }\n\n        void insert_into_global(const int el_index, const Local2Global &data, std::vector<Local2Global> &vec, const int size)\n        {\n            //ignore small weights\n            if(fabs(data.val) <1e-10 )\n                return;\n\n            bool found = false;\n\n            for(int i = 0; i < size; ++i)\n            {\n                if(vec[i].index == data.index)\n                {\n                    // if(fabs(vec[i].val - data.val) > 1e-10){\n                    //     std::cout<<el_index <<\" \"<<vec[i].val <<\" \"<< data.val<<\" \"<<fabs(vec[i].val - data.val)<<std::endl;\n                    //     // vec[i].val += data.val;\n                    // }\n                    // assert(fabs(vec[i].val - data.val) < 1e-10);\n                    assert((vec[i].node - data.node).norm() < 1e-10);\n                    found = true;\n                    break;\n                }\n            }\n\n            if(!found)\n                vec.push_back(data);\n        }\n\n        void assign_q2_weights(const Mesh3D &mesh, const int el_index, std::vector< ElementBases > &bases)\n        {\n            // Eigen::MatrixXd eval_p;\n            std::vector<AssemblyValues> eval_p;\n            const Navigation3D::Index start_index = mesh.get_index_from_element(el_index);\n            ElementBases &b = bases[el_index];\n\n            std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 6> to_face;\n            mesh.to_face_functions(to_face);\n            for (int f = 0; f < 6; ++f)\n            {\n                const Navigation3D::Index index = to_face[f](start_index);\n                const int opposite_element = mesh.switch_element(index).element;\n\n                if(opposite_element < 0 || !mesh.is_cube(opposite_element))\n                    continue;\n\n                // const auto &param_p     = FEBasis3d::quadr_hex_face_local_nodes_coordinates(mesh, mesh.switch_element(index));\n                Eigen::Matrix<double, 9, 3> param_p;\n                {\n                    Eigen::MatrixXd hex_loc_nodes; polyfem::autogen::q_nodes_3d(2, hex_loc_nodes);\n                    const auto opposite_indices = FEBasis3d::hex_face_local_nodes(false, 2, mesh, mesh.switch_element(index));\n                    for(int k = 0; k < 9; ++k)\n                        param_p.row(k) = hex_loc_nodes.row(opposite_indices[k]);\n                }\n                const auto &other_bases = bases[opposite_element];\n\n                // const auto &indices     = FEBasis3d::quadr_hex_face_local_nodes(mesh, index);\n                const auto &indices     = FEBasis3d::hex_face_local_nodes(false, 2, mesh, index);\n\n                std::array<int, 9> sizes;\n\n                for(int l = 0; l < 9; ++l)\n                    sizes[l] = b.bases[indices[l]].global().size();\n\n                other_bases.evaluate_bases(param_p, eval_p);\n                for(std::size_t i = 0; i < other_bases.bases.size(); ++i)\n                {\n                    const auto &other_b = other_bases.bases[i];\n\n                    if(other_b.global().empty()) continue;\n\n                    // other_b.basis(param_p, eval_p);\n                    assert(eval_p[i].val.size() == 9);\n\n                    //basis i of element opposite element is zero on this elements\n                    if(eval_p[i].val.cwiseAbs().maxCoeff() <= 1e-10)\n                        continue;\n\n                    for(std::size_t k = 0; k < other_b.global().size(); ++k)\n                    {\n                        for(int l = 0; l < 9; ++l)\n                        {\n                            Local2Global glob = other_b.global()[k];\n                            glob.val *= eval_p[i].val(l);\n\n                            insert_into_global(el_index, glob, b.bases[indices[l]].global(), sizes[l]);\n                        }\n                    }\n                }\n            }\n        }\n\n        void setup_data_for_polygons(const Mesh3D &mesh, const int el_index, const ElementBases &b, std::map<int, InterfaceData> &poly_face_to_data)\n        {\n            const Navigation3D::Index start_index = mesh.get_index_from_element(el_index);\n            std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 6> to_face;\n            mesh.to_face_functions(to_face);\n            for (int f = 0; f < 6; ++f)\n            {\n                const Navigation3D::Index index = to_face[f](start_index);\n\n                const int opposite_element = mesh.switch_element(index).element;\n                const bool is_neigh_poly = opposite_element >= 0 && mesh.is_polytope(opposite_element);\n\n                if(is_neigh_poly)\n                {\n                    // auto e2l = FEBasis3d::quadr_hex_face_local_nodes(mesh, index);\n                    auto e2l = FEBasis3d::hex_face_local_nodes(false, 2, mesh, index);\n\n                    InterfaceData &data = poly_face_to_data[index.face];\n\n                    for(int kk = 0; kk < e2l.size(); ++kk)\n                    {\n                        const auto idx = e2l(kk);\n                        data.local_indices.push_back(idx);\n                    }\n                }\n            }\n        }\n    }\n\n\n\n    int SplineBasis3d::build_bases(const Mesh3D &mesh, const int quadrature_order, std::vector< ElementBases > &bases, std::vector< LocalBoundary > &local_boundary, std::map<int, InterfaceData> &poly_face_to_data)\n    {\n        using std::max;\n        assert(mesh.is_volume());\n\n        MeshNodes mesh_nodes(mesh, true, true, 1, 1, 1);\n\n        const int n_els = mesh.n_elements();\n        bases.resize(n_els);\n        local_boundary.clear();\n\n        // bounday_nodes.clear();\n\n        // HexQuadrature hex_quadrature;\n\n        std::array<std::array<double, 4>, 3> h_knots;\n        std::array<std::array<double, 4>, 3> v_knots;\n        std::array<std::array<double, 4>, 3> w_knots;\n\n        for(int e = 0; e < n_els; ++e)\n        {\n            if(!mesh.is_spline_compatible(e))\n                continue;\n\n            SpaceMatrix space;\n\n            build_local_space(mesh, mesh_nodes, e, space, local_boundary, poly_face_to_data);\n\n            ElementBases &b=bases[e];\n            b.set_quadrature([quadrature_order](Quadrature &quad){\n                HexQuadrature hex_quadrature;\n                hex_quadrature.get_quadrature(quadrature_order, quad);\n            });\n            // hex_quadrature.get_quadrature(quadrature_order, b.quadrature);\n            b.bases.resize(27);\n\n            b.set_local_node_from_primitive_func([e](const int primitive_id, const Mesh &mesh)\n            {\n                const auto &mesh3d = dynamic_cast<const Mesh3D &>(mesh);\n\n                std::array<std::function<Navigation3D::Index(Navigation3D::Index)>, 6> to_face;\n                mesh3d.to_face_functions(to_face);\n\n                auto start_index = mesh3d.get_index_from_element(e);\n                auto index = start_index;\n\n                int lf;\n                for(lf = 0; lf < mesh3d.n_cell_faces(e); ++lf)\n                {\n                    index = to_face[lf](start_index);\n                    if(index.face == primitive_id)\n                        break;\n                }\n                assert(index.face == primitive_id);\n\n\n                static constexpr std::array<std::array<int, 9>, 6> face_to_index = {{\n                    {{2*9+0*3+0, 2*9+1*3+0, 2*9+2*3+0, 2*9+0*3+1, 2*9+1*3+1, 2*9+2*3+1, 2*9+0*3+2, 2*9+1*3+2, 2*9+2*3+2}}, //0\n                    {{0*9+0*3+0, 0*9+1*3+0, 0*9+2*3+0, 0*9+0*3+1, 0*9+1*3+1, 0*9+2*3+1, 0*9+0*3+2, 0*9+1*3+2, 0*9+2*3+2}}, //1\n\n                    {{0*9+0*3+2, 0*9+1*3+2, 0*9+2*3+2, 1*9+0*3+2, 1*9+1*3+2, 1*9+2*3+2, 2*9+0*3+2, 2*9+1*3+2, 2*9+2*3+2}}, //2\n                    {{0*9+0*3+0, 0*9+1*3+0, 0*9+2*3+0, 1*9+0*3+0, 1*9+1*3+0, 1*9+2*3+0, 2*9+0*3+0, 2*9+1*3+0, 2*9+2*3+0}}, //3\n\n                    {{0*9+2*3+0, 0*9+2*3+1, 0*9+2*3+2, 1*9+2*3+0, 1*9+2*3+1, 1*9+2*3+2, 2*9+2*3+0, 2*9+2*3+1, 2*9+2*3+2}}, //4\n                    {{0*9+0*3+0, 0*9+0*3+1, 0*9+0*3+2, 1*9+0*3+0, 1*9+0*3+1, 1*9+0*3+2, 2*9+0*3+0, 2*9+0*3+1, 2*9+0*3+2}}, //5\n                }};\n\n                Eigen::VectorXi res(9);\n\n                for(int i = 0; i< 9; ++i)\n                    res(i)=face_to_index[lf][i];\n\n                return res;\n            });\n\n\n            setup_knots_vectors(mesh_nodes, space, h_knots, v_knots, w_knots);\n            // print_local_space(space);\n\n            basis_for_regular_hex(mesh_nodes, space, h_knots, v_knots, w_knots, b);\n            basis_for_irregulard_hex(e, mesh, mesh_nodes, space, h_knots, v_knots, w_knots, b, poly_face_to_data);\n        }\n\n        int n_bases = mesh_nodes.n_nodes();\n\n\n        std::set<int> face_id;\n        std::set<int> edge_id;\n        std::set<int> vertex_id;\n\n        for(int e = 0; e < n_els; ++e)\n        {\n            if(mesh.is_polytope(e) || mesh.is_spline_compatible(e))\n                continue;\n\n            ElementBases &b=bases[e];\n            // hex_quadrature.get_quadrature(quadrature_order, b.quadrature);\n            b.set_quadrature([quadrature_order](Quadrature &quad){\n                HexQuadrature hex_quadrature;\n                hex_quadrature.get_quadrature(quadrature_order, quad);\n            });\n\n            b.set_local_node_from_primitive_func([e](const int primitive_id, const Mesh &mesh)\n            {\n                const auto &mesh3d = dynamic_cast<const Mesh3D &>(mesh);\n                Navigation3D::Index index;\n\n                for(int lf = 0; lf < 6; ++lf)\n                {\n                    index = mesh3d.get_index_from_element(e, lf, 0);\n                    if(index.face == primitive_id)\n                        break;\n                }\n                assert(index.face == primitive_id);\n\n                // const auto indices = FEBasis3d::quadr_hex_face_local_nodes(mesh3d, index);\n                const auto indices = FEBasis3d::hex_face_local_nodes(false, 2, mesh3d, index);\n                Eigen::VectorXi res(indices.size());\n\n                for(size_t i = 0; i< indices.size(); ++i)\n                    res(i)=indices[i];\n\n                return res;\n            });\n\n            create_q2_nodes(mesh, e, vertex_id, edge_id, face_id, b, local_boundary, n_bases);\n        }\n\n\n        bool missing_bases = false;\n        do\n        {\n            missing_bases = false;\n            for(int e = 0; e < n_els; ++e)\n            {\n                if(mesh.is_polytope(e) || mesh.is_spline_compatible(e))\n                    continue;\n\n                auto &b=bases[e];\n                if(b.is_complete())\n                    continue;\n\n                assign_q2_weights(mesh, e, bases);\n\n                missing_bases = missing_bases || b.is_complete();\n            }\n        }\n        while(missing_bases);\n\n\n        for(int e = 0; e < n_els; ++e)\n        {\n            if(mesh.is_polytope(e) || mesh.is_spline_compatible(e))\n                continue;\n\n            const ElementBases &b=bases[e];\n            setup_data_for_polygons(mesh, e, b, poly_face_to_data);\n        }\n\n        // for(int e = 0; e < n_els; ++e)\n        // {\n        //     if(!mesh.is_polytope(e))\n        //         continue;\n\n        //     for (int lf = 0; lf < mesh.n_cell_faces(e); ++lf)\n        //     {\n        //         auto index = mesh.get_index_from_element(e, lf, 0);\n        //         auto index2 = mesh.switch_element(index);\n        //         if (index2.element >= 0) {\n        //             auto &array = poly_face_to_data[index.face].local_indices;\n        //             auto &b = bases[index2.element];\n        //             array.resize(b.bases.size());\n        //             std::iota(array.begin(), array.end(), 0);\n        //         }\n        //     }\n        // }\n\n        for(auto &k : poly_face_to_data)\n        {\n            auto &array = k.second.local_indices;\n            std::sort(array.begin(), array.end());\n            auto it = std::unique(array.begin(), array.end());\n            array.resize(std::distance(array.begin(), it));\n        }\n\n        return n_bases;\n    }\n\n\n    void SplineBasis3d::fit_nodes(const Mesh3D &mesh, const int n_bases, std::vector< ElementBases > &gbases)\n    {\n        assert(false);\n        // const int dim = 3;\n        // const int n_constraints =  27;\n        // const int n_elements = mesh.n_elements();\n\n        // std::vector< Eigen::Triplet<double> > entries, entries_t;\n\n        // MeshNodes nodes(mesh, true, true, 1, 1, 1);\n        // // Eigen::MatrixXd tmp;\n        // std::vector<AssemblyValues> tmp_val;\n\n        // Eigen::MatrixXd node_rhs(n_constraints*n_elements, dim);\n        // Eigen::MatrixXd samples(n_constraints, dim);\n\n        // for(int i = 0; i < n_constraints; ++i)\n        //     samples.row(i) = FEBasis3d::quadr_hex_local_node_coordinates(i);\n\n        // for(int i = 0; i < n_elements; ++i)\n        // {\n        //     auto &base = gbases[i];\n\n        //     if(!mesh.is_cube(i))\n        //         continue;\n\n        //     auto global_ids = FEBasis3d::quadr_hex_local_to_global(mesh, i);\n        //     assert(global_ids.size() == n_constraints);\n\n        //     for(int j = 0; j < n_constraints; ++j)\n        //     {\n        //         auto n_id = nodes.node_id_from_primitive(global_ids[j]);\n        //         auto n = nodes.node_position(n_id);\n        //         for(int d = 0; d < dim; ++d)\n        //             node_rhs(n_constraints*i + j, d) = n(d);\n        //     }\n\n        //     base.evaluate_bases(samples, tmp_val);\n        //     const auto &lbs = base.bases;\n\n        //     const int n_local_bases = int(lbs.size());\n        //     for(int j = 0; j < n_local_bases; ++j)\n        //     {\n        //         const Basis &b = lbs[j];\n        //         const auto &tmp = tmp_val[j].val;\n\n        //         for(std::size_t ii = 0; ii < b.global().size(); ++ii)\n        //         {\n        //             for (long k = 0; k < tmp.size(); ++k)\n        //             {\n        //                 entries.emplace_back(n_constraints*i + k, b.global()[ii].index, tmp(k)*b.global()[ii].val);\n        //                 entries_t.emplace_back(b.global()[ii].index, n_constraints*i + k, tmp(k)*b.global()[ii].val);\n        //             }\n        //         }\n        //     }\n        // }\n\n        // Eigen::MatrixXd new_nodes(n_bases, dim);\n        // {\n        //     StiffnessMatrix mat(n_constraints*n_elements, n_bases);\n        //     StiffnessMatrix mat_t(n_bases, n_constraints*n_elements);\n\n        //     mat.setFromTriplets(entries.begin(), entries.end());\n        //     mat_t.setFromTriplets(entries_t.begin(), entries_t.end());\n\n        //     StiffnessMatrix A = mat_t * mat;\n        //     Eigen::MatrixXd b = mat_t * node_rhs;\n\n        //     json params = {\n        //         {\"mtype\", -2}, // matrix type for Pardiso (2 = SPD)\n        //         // {\"max_iter\", 0}, // for iterative solvers\n        //         // {\"tolerance\", 1e-9}, // for iterative solvers\n        //     };\n        //     auto solver = LinearSolver::create(\"\", \"\");\n        //     solver->setParameters(params);\n        //     solver->analyzePattern(A);\n        //     solver->factorize(A);\n\n        //     for(int d = 0; d < dim; ++d)\n        //         solver->solve(b.col(d), new_nodes.col(d));\n        // }\n\n        // for(int i = 0; i < n_elements; ++i)\n        // {\n        //     auto &base = gbases[i];\n\n        //     if(!mesh.is_cube(i))\n        //         continue;\n\n        //     auto &lbs = base.bases;\n        //     const int n_local_bases = int(lbs.size());\n        //     for(int j = 0; j < n_local_bases; ++j)\n        //     {\n        //         Basis &b = lbs[j];\n\n        //         for(std::size_t ii = 0; ii < b.global().size(); ++ii)\n        //         {\n        //             // if(nodes.is_primitive_boundary(b.global()[ii].index))\n        //                 // continue;\n\n        //             for(int d = 0; d < dim; ++d)\n        //             {\n        //                 b.global()[ii].node(d) = new_nodes(b.global()[ii].index, d);\n        //             }\n        //         }\n        //     }\n        // }\n    }\n\n}\n", "meta": {"hexsha": "afceb1c683c3fd1eb58dba0432d4b16c6abacb8c", "size": 51580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/basis/SplineBasis3d.cpp", "max_stars_repo_name": "danielepanozzo/polyfem", "max_stars_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T19:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:30:51.000Z", "max_issues_repo_path": "src/basis/SplineBasis3d.cpp", "max_issues_repo_name": "danielepanozzo/polyfem", "max_issues_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:50:35.000Z", "max_forks_repo_path": "src/basis/SplineBasis3d.cpp", "max_forks_repo_name": "danielepanozzo/polyfem", "max_forks_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2018-12-31T02:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T02:42:01.000Z", "avg_line_length": 38.4065524944, "max_line_length": 351, "alphanum_fraction": 0.505932532, "num_tokens": 13041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.18527281894486308}}
{"text": "#ifndef LSC_PLANNER_TRAJ_OPTIMIZER_HPP\n#define LSC_PLANNER_TRAJ_OPTIMIZER_HPP\n\n#include <sp_const.hpp>\n#include <polynomial.hpp>\n#include <param.hpp>\n#include <mission.hpp>\n#include <collision_constraints.hpp>\n\n// Eigen\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n// CPLEX\n#include <ilcplex/ilocplex.h>\n\nnamespace DynamicPlanning {\n    class TrajOptimizer {\n    public:\n        TrajOptimizer(const Param& param, const Mission& mission, const Eigen::MatrixXd& B);\n\n        void solve(const Agent& agent, const CollisionConstraints& constraints);\n\n        void updateParam(const Param& param);\n\n        traj_t getTrajectory();\n\n        double getQPcost() const;\n\n    private:\n        Param param;\n        Mission mission;\n        Eigen::MatrixXd Q_base, Aeq_base, deq, B;\n\n        // trajectory optimization results\n        traj_t trajectory;\n        double current_qp_cost;\n\n        // Frequently used constants\n        int M, n, phi, dim;\n\n        void buildConstraintMatrices(const Agent& agent);\n\n        // Cost matrix Q\n        void buildQBase();\n\n        // Constraint matrix A_eq x > d_eq\n        void buildAeqBase();\n\n        void buildDeq(const Agent& agent);\n\n        void populatebyrow(IloModel model, IloNumVarArray x, IloRangeArray c,\n                           const Agent& agent, const CollisionConstraints& constraints);\n\n        int getTerminalSegments(const Agent& agent) const;\n    };\n}\n\n\n#endif //LSC_PLANNER_TRAJ_OPTIMIZER_HPP\n", "meta": {"hexsha": "f011aceee37b6661befd2364a2dd8ef5fd68d681", "size": 1453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/traj_optimizer.hpp", "max_stars_repo_name": "dabinkim-LGOM/lsc_planner", "max_stars_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-09-04T15:14:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T04:34:13.000Z", "max_issues_repo_path": "include/traj_optimizer.hpp", "max_issues_repo_name": "dabinkim-LGOM/lsc_planner", "max_issues_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_issues_repo_licenses": ["MIT"], "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/traj_optimizer.hpp", "max_forks_repo_name": "dabinkim-LGOM/lsc_planner", "max_forks_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T11:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T05:24:33.000Z", "avg_line_length": 23.8196721311, "max_line_length": 92, "alphanum_fraction": 0.6675843083, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1852728142790936}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE PTranformd bench\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/timer/timer.hpp>\n// The inclusion of boost chrono was commented in timer.hpp for boost >= 1.60.\n// Because of this, the auto-link feature does not incude the chrono library\n// anymore, what causes a link error.\n// (see also https://svn.boost.org/trac/boost/ticket/11862)\n// We add manually the line.\n// Possible alternative: include only for specific version of boost and\n// auto-link capable compiler\n#include <boost/chrono/chrono.hpp>\n\n// SpaceVecAlg\n#include <SpaceVecAlg/SpaceVecAlg>\n\ntypedef Eigen::Matrix<double, 6, Eigen::Dynamic> Matrix6Xd;\n\nBOOST_AUTO_TEST_CASE(PTransfromd_PTransformd)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<PTransformd> pt2(size, PTransformd::Identity());\n  std::vector<PTransformd> ptRes(size);\n\n  std::cout << \"PTransform vs PTransform\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      ptRes[i] = pt1[i] * pt2[i];\n    }\n  }\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(PTransfromd_MotionVec)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<MotionVecd> mv(size, MotionVecd(Eigen::Vector6d::Random()));\n  std::vector<MotionVecd> mvRes(size);\n\n  std::cout << \"PTransform vs MotionVec\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      mvRes[i] = pt1[i] * mv[i];\n    }\n  }\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(PTransfromd_MotionEigen)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  const std::size_t cols = 3;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<Matrix6Xd> mv(size, Matrix6Xd::Random(6, cols));\n  std::vector<Matrix6Xd> mvRes(size, Matrix6Xd(6, cols));\n\n  std::cout << \"PTransform vs MotionEigen\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      pt1[i].mul(mv[i], mvRes[i]);\n    }\n  }\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(PTransfromd_as_matrix_MotionEigen)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  const std::size_t cols = 3;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<Matrix6Xd> mv(size, Matrix6Xd::Random(6, cols));\n  std::vector<Matrix6Xd> mvRes(size, Matrix6Xd(6, cols));\n\n  std::cout << \"PTransform as matrix vs MotionEigen\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      mvRes[i].noalias() = pt1[i].matrix() * mv[i];\n    }\n  }\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(PTransfromd_MotionEigen_as_motion)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  const std::size_t cols = 3;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<Matrix6Xd> mv(size, Matrix6Xd::Random(6, cols));\n  std::vector<Matrix6Xd> mvRes(size, Matrix6Xd(6, cols));\n\n  std::cout << \"PTransform vs MotionEigen as MotionVec\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      for(std::size_t j = 0; j < cols; ++j)\n      {\n        mvRes[i].col(j).noalias() = (pt1[i] * MotionVecd(mv[i].col(j))).vector();\n      }\n    }\n  }\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(PTransfromd_inv_MotionVec)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<MotionVecd> mv(size, MotionVecd(Eigen::Vector6d::Random()));\n  std::vector<MotionVecd> mvRes(size);\n\n  std::cout << \"PTransform_inv vs MotionVec\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      mvRes[i] = pt1[i].inv() * mv[i];\n    }\n  }\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(PTransfromd_invMul_MotionVec)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<MotionVecd> mv(size, MotionVecd(Eigen::Vector6d::Random()));\n  std::vector<MotionVecd> mvRes(size);\n\n  std::cout << \"PTransform_invMul vs MotionVec\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      mvRes[i] = pt1[i].invMul(mv[i]);\n    }\n  }\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(PTransfromd_dual_ForceVec)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<ForceVecd> mv(size, ForceVecd(Eigen::Vector6d::Random()));\n  std::vector<ForceVecd> mvRes(size);\n\n  std::cout << \"PTransform dual vs ForceVec\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      mvRes[i] = pt1[i].dualMul(mv[i]);\n    }\n  }\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(PTransfromd_trans_ForceVec)\n{\n  using namespace sva;\n\n  const std::size_t size = 10000000;\n  std::vector<PTransformd> pt1(size, PTransformd::Identity());\n  std::vector<ForceVecd> mv(size, ForceVecd(Eigen::Vector6d::Random()));\n  std::vector<ForceVecd> mvRes(size);\n\n  std::cout << \"PTransform trans vs ForceVec\" << std::endl;\n  {\n    boost::timer::auto_cpu_timer t;\n    for(std::size_t i = 0; i < size; ++i)\n    {\n      mvRes[i] = pt1[i].transMul(mv[i]);\n    }\n  }\n  std::cout << std::endl;\n}\n", "meta": {"hexsha": "f8eef808696a28ea0db54b8f196ffc02d15e7997", "size": 5677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/PTransformBench.cpp", "max_stars_repo_name": "gergondet/SpaceVecAlg", "max_stars_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "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": "tests/PTransformBench.cpp", "max_issues_repo_name": "gergondet/SpaceVecAlg", "max_issues_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "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": "tests/PTransformBench.cpp", "max_forks_repo_name": "gergondet/SpaceVecAlg", "max_forks_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "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": 26.5280373832, "max_line_length": 81, "alphanum_fraction": 0.6575656156, "num_tokens": 1804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.18520356746570452}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// as_quantifier.hpp\r\n//\r\n//  Copyright 2008 Eric Niebler. 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_XPRESSIVE_DETAIL_STATIC_TRANSFORMS_AS_QUANTIFIER_HPP_EAN_04_01_2007\r\n#define BOOST_XPRESSIVE_DETAIL_STATIC_TRANSFORMS_AS_QUANTIFIER_HPP_EAN_04_01_2007\r\n\r\n// MS compatible compilers support #pragma once\r\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\r\n# pragma once\r\n#endif\r\n\r\n#include <boost/mpl/assert.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/xpressive/detail/detail_fwd.hpp>\r\n#include <boost/xpressive/detail/static/static.hpp>\r\n#include <boost/xpressive/proto/proto.hpp>\r\n\r\nnamespace boost { namespace xpressive { namespace detail\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // generic_quant_tag\r\n    template<uint_t Min, uint_t Max>\r\n    struct generic_quant_tag\r\n    {\r\n        typedef mpl::integral_c<uint_t, Min> min_type;\r\n        typedef mpl::integral_c<uint_t, Max> max_type;\r\n    };\r\n}}}\r\n\r\nnamespace boost { namespace xpressive { namespace grammar_detail\r\n{\r\n    using detail::uint_t;\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // min_type / max_type\r\n    template<typename Tag>\r\n    struct min_type : Tag::min_type {};\r\n\r\n    template<>\r\n    struct min_type<proto::tag::posit> : mpl::integral_c<uint_t, 1> {};\r\n\r\n    template<>\r\n    struct min_type<proto::tag::dereference> : mpl::integral_c<uint_t, 0> {};\r\n\r\n    template<>\r\n    struct min_type<proto::tag::logical_not> : mpl::integral_c<uint_t, 0> {};\r\n\r\n    template<typename Tag>\r\n    struct max_type : Tag::max_type {};\r\n\r\n    template<>\r\n    struct max_type<proto::tag::posit> : mpl::integral_c<uint_t, UINT_MAX-1> {};\r\n\r\n    template<>\r\n    struct max_type<proto::tag::dereference> : mpl::integral_c<uint_t, UINT_MAX-1> {};\r\n\r\n    template<>\r\n    struct max_type<proto::tag::logical_not> : mpl::integral_c<uint_t, 1> {};\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // as_simple_quantifier\r\n    template<typename Grammar, typename Greedy>\r\n    struct as_simple_quantifier : proto::callable\r\n    {\r\n        template<typename Sig> struct result {};\r\n\r\n        template<typename This, typename Expr, typename State, typename Visitor>\r\n        struct result<This(Expr, State, Visitor)>\r\n        {\r\n            typedef typename proto::result_of::arg<Expr>::type arg_type;\r\n            typedef typename Grammar::template result<void(arg_type, detail::true_xpression, Visitor)>::type xpr_type;\r\n            typedef detail::simple_repeat_matcher<xpr_type, Greedy> matcher_type;\r\n            typedef typename proto::terminal<matcher_type>::type type;\r\n        };\r\n\r\n        template<typename Expr, typename State, typename Visitor>\r\n        typename result<void(Expr, State, Visitor)>::type\r\n        operator ()(Expr const &expr, State const &, Visitor &visitor) const\r\n        {\r\n            typedef result<void(Expr, State, Visitor)> result_;\r\n            typedef typename result_::arg_type arg_type;\r\n            typedef typename result_::xpr_type xpr_type;\r\n            typedef typename result_::matcher_type matcher_type;\r\n            typedef typename Expr::proto_tag tag;\r\n\r\n            xpr_type const &xpr = Grammar()(proto::arg(expr), detail::true_xpression(), visitor);\r\n            matcher_type matcher(xpr, (uint_t)min_type<tag>(), (uint_t)max_type<tag>(), xpr.get_width().value());\r\n            return proto::terminal<matcher_type>::type::make(matcher);\r\n        }\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // add_hidden_mark\r\n    struct add_hidden_mark : proto::callable\r\n    {\r\n        template<typename Sig> struct result {};\r\n\r\n        template<typename This, typename Expr, typename State, typename Visitor>\r\n        struct result<This(Expr, State, Visitor)>\r\n        {\r\n            typedef\r\n                typename shift_right<\r\n                    terminal<detail::mark_begin_matcher>::type\r\n                  , typename shift_right<\r\n                        Expr\r\n                      , terminal<detail::mark_end_matcher>::type\r\n                    >::type\r\n                >::type\r\n            type;\r\n        };\r\n\r\n        template<typename Expr, typename State, typename Visitor>\r\n        typename result<void(Expr, State, Visitor)>::type\r\n        operator ()(Expr const &expr, State const &, Visitor &visitor) const\r\n        {\r\n            // we're inserting a hidden mark ... so grab the next hidden mark number.\r\n            int mark_nbr = visitor.get_hidden_mark();\r\n            detail::mark_begin_matcher begin(mark_nbr);\r\n            detail::mark_end_matcher end(mark_nbr);\r\n\r\n            typename result<void(Expr, State, Visitor)>::type that\r\n                = {{begin}, {expr, {end}}};\r\n            return that;\r\n        }\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // InsertMark\r\n    struct InsertMark\r\n      : or_<\r\n            when<proto::assign<detail::basic_mark_tag, _>, _>\r\n          , otherwise<add_hidden_mark>\r\n        >\r\n    {};\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // as_default_quantifier_impl\r\n    template<typename Greedy, uint_t Min, uint_t Max>\r\n    struct as_default_quantifier_impl : proto::callable\r\n    {\r\n        template<typename Sig> struct result {};\r\n\r\n        template<typename This, typename Expr, typename State, typename Visitor>\r\n        struct result<This(Expr, State, Visitor)>\r\n        {\r\n            typedef\r\n                typename InsertMark::template result<void(typename proto::result_of::arg<Expr>::type, State, Visitor)>::type\r\n            marked_sub_type;\r\n\r\n            typedef\r\n                typename shift_right<\r\n                    terminal<detail::repeat_begin_matcher>::type\r\n                  , typename shift_right<\r\n                        marked_sub_type\r\n                      , typename terminal<detail::repeat_end_matcher<Greedy> >::type\r\n                    >::type\r\n                >::type\r\n            type;\r\n        };\r\n\r\n        template<typename Expr, typename State, typename Visitor>\r\n        typename result<void(Expr, State, Visitor)>::type\r\n        operator ()(Expr const &expr, State const &state, Visitor &visitor) const\r\n        {\r\n            // Ensure this sub-expression is book-ended with mark matchers\r\n            typename result<void(Expr, State, Visitor)>::marked_sub_type const &\r\n                marked_sub = InsertMark()(proto::arg(expr), state, visitor);\r\n\r\n            // Get the mark_number from the begin_mark_matcher\r\n            int mark_number = proto::arg(proto::left(marked_sub)).mark_number_;\r\n            BOOST_ASSERT(0 != mark_number);\r\n\r\n            uint_t min_ = (uint_t)min_type<typename Expr::proto_tag>();\r\n            uint_t max_ = (uint_t)max_type<typename Expr::proto_tag>();\r\n\r\n            detail::repeat_begin_matcher begin(mark_number);\r\n            detail::repeat_end_matcher<Greedy> end(mark_number, min_, max_);\r\n\r\n            typename result<void(Expr, State, Visitor)>::type that\r\n                = {{begin}, {marked_sub, {end}}};\r\n            return that;\r\n        }\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // optional_tag\r\n    template<typename Greedy>\r\n    struct optional_tag\r\n    {};\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // as_default_optional\r\n    template<typename Grammar, typename Greedy>\r\n    struct as_default_optional : proto::callable\r\n    {\r\n        template<typename Sig> struct result {};\r\n\r\n        template<typename This, typename Expr, typename State, typename Visitor>\r\n        struct result<This(Expr, State, Visitor)>\r\n        {\r\n            typedef detail::optional_matcher<\r\n                typename Grammar::template result<void(Expr, detail::alternate_end_xpression, Visitor)>::type\r\n              , Greedy\r\n            > type;\r\n        };\r\n\r\n        template<typename Expr, typename State, typename Visitor>\r\n        typename result<void(Expr, State, Visitor)>::type\r\n        operator ()(Expr const &expr, State const &, Visitor &visitor) const\r\n        {\r\n            return typename result<void(Expr, State, Visitor)>::type(\r\n                Grammar()(expr, detail::alternate_end_xpression(), visitor)\r\n            );\r\n        }\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // as_mark_optional\r\n    template<typename Grammar, typename Greedy>\r\n    struct as_mark_optional : proto::callable\r\n    {\r\n        template<typename Sig> struct result {};\r\n\r\n        template<typename This, typename Expr, typename State, typename Visitor>\r\n        struct result<This(Expr, State, Visitor)>\r\n        {\r\n            typedef detail::optional_mark_matcher<\r\n                typename Grammar::template result<void(Expr, detail::alternate_end_xpression, Visitor)>::type\r\n              , Greedy\r\n            > type;\r\n        };\r\n\r\n        template<typename Expr, typename State, typename Visitor>\r\n        typename result<void(Expr, State, Visitor)>::type\r\n        operator ()(Expr const &expr, State const &, Visitor &visitor) const\r\n        {\r\n            int mark_number = proto::arg(proto::left(expr)).mark_number_;\r\n            return typename result<void(Expr, State, Visitor)>::type(\r\n                Grammar()(expr, detail::alternate_end_xpression(), visitor)\r\n              , mark_number\r\n            );\r\n        }\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // IsMarkerOrRepeater\r\n    struct IsMarkerOrRepeater\r\n      : or_<\r\n            shift_right<terminal<detail::repeat_begin_matcher>, _>\r\n          , assign<terminal<detail::mark_placeholder>, _>\r\n        >\r\n    {};\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // as_optional\r\n    template<typename Grammar, typename Greedy>\r\n    struct as_optional\r\n      : or_<\r\n            when<IsMarkerOrRepeater, as_mark_optional<Grammar, Greedy> >\r\n          , otherwise<as_default_optional<Grammar, Greedy> >\r\n        >\r\n    {};\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // make_optional_\r\n    template<typename Greedy>\r\n    struct make_optional_ : proto::callable\r\n    {\r\n        template<typename Sig> struct result {};\r\n\r\n        template<typename This, typename Expr, typename State, typename Visitor>\r\n        struct result<This(Expr, State, Visitor)>\r\n        {\r\n            typedef typename unary_expr<optional_tag<Greedy>, Expr>::type type;\r\n        };\r\n\r\n        template<typename Expr, typename State, typename Visitor>\r\n        typename unary_expr<optional_tag<Greedy>, Expr>::type\r\n        operator ()(Expr const &expr, State const &, Visitor &) const\r\n        {\r\n            typename unary_expr<optional_tag<Greedy>, Expr>::type that = {expr};\r\n            return that;\r\n        }\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // as_default_quantifier_impl\r\n    template<typename Greedy, uint_t Max>\r\n    struct as_default_quantifier_impl<Greedy, 0, Max>\r\n      : call<make_optional_<Greedy>(as_default_quantifier_impl<Greedy, 1, Max>)>\r\n    {};\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // as_default_quantifier_impl\r\n    template<typename Greedy>\r\n    struct as_default_quantifier_impl<Greedy, 0, 1>\r\n      : call<make_optional_<Greedy>(_arg)>\r\n    {};\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // as_default_quantifier\r\n    template<typename Greedy>\r\n    struct as_default_quantifier : proto::callable\r\n    {\r\n        template<typename Sig> struct result {};\r\n\r\n        template<typename This, typename Expr, typename State, typename Visitor>\r\n        struct result<This(Expr, State, Visitor)>\r\n        {\r\n            typedef\r\n                as_default_quantifier_impl<\r\n                    Greedy\r\n                  , min_type<typename Expr::proto_tag>::value\r\n                  , max_type<typename Expr::proto_tag>::value\r\n                >\r\n            impl;\r\n\r\n            typedef typename impl::template result<void(Expr, State, Visitor)>::type type;\r\n        };\r\n\r\n        template<typename Expr, typename State, typename Visitor>\r\n        typename result<void(Expr, State, Visitor)>::type\r\n        operator ()(Expr const &expr, State const &state, Visitor &visitor) const\r\n        {\r\n            return as_default_quantifier_impl<\r\n                Greedy\r\n              , min_type<typename Expr::proto_tag>::value\r\n              , max_type<typename Expr::proto_tag>::value\r\n            >()(expr, state, visitor);\r\n        }\r\n    };\r\n\r\n}}}\r\n\r\n#endif\r\n", "meta": {"hexsha": "73cfd1d211b145abc13adb7b65d349d78680e7a1", "size": 13076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/xpressive/boost/xpressive/detail/static/transforms/as_quantifier.hpp", "max_stars_repo_name": "xoxox4dev/madedit", "max_stars_repo_head_hexsha": "8e0dd08818e040b099251c1eb8833b836cb36c6e", "max_stars_repo_licenses": ["Ruby"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-06-28T17:48:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T08:47:26.000Z", "max_issues_repo_path": "libs/xpressive/boost/xpressive/detail/static/transforms/as_quantifier.hpp", "max_issues_repo_name": "mcanthony/madedit", "max_issues_repo_head_hexsha": "8e0dd08818e040b099251c1eb8833b836cb36c6e", "max_issues_repo_licenses": ["Ruby"], "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/xpressive/boost/xpressive/detail/static/transforms/as_quantifier.hpp", "max_forks_repo_name": "mcanthony/madedit", "max_forks_repo_head_hexsha": "8e0dd08818e040b099251c1eb8833b836cb36c6e", "max_forks_repo_licenses": ["Ruby"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-04-25T00:40:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T06:39:48.000Z", "avg_line_length": 38.4588235294, "max_line_length": 125, "alphanum_fraction": 0.5406852248, "num_tokens": 2587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18520356387055378}}
{"text": "\n#include <boost/algorithm/hex.hpp>\n#include <boost/version.hpp>\n#if BOOST_VERSION >= 106600\n#include <boost/uuid/detail/sha1.hpp>\n#else\n#include <boost/uuid/sha1.hpp>\n#endif\n#include <cstring>\n#include <util/crypto_hash.h>\n\nclass crypto_hash_private\n{\npublic:\n  boost::uuids::detail::sha1 s;\n};\n\nbool crypto_hash::operator<(const crypto_hash h2) const\n{\n  if(memcmp(hash, h2.hash, CRYPTO_HASH_SIZE) < 0)\n    return true;\n\n  return false;\n}\n\nstd::string crypto_hash::to_string() const\n{\n  std::ostringstream buf;\n  for(unsigned int i : hash)\n    buf << std::hex << std::setfill('0') << std::setw(8) << i;\n\n  return buf.str();\n}\n\ncrypto_hash::crypto_hash()\n  : p_crypto(std::make_shared<crypto_hash_private>()), hash{0}\n{\n}\n\nvoid crypto_hash::ingest(void const *data, unsigned int size)\n{\n  p_crypto->s.process_bytes(data, size);\n}\n\nvoid crypto_hash::fin()\n{\n  p_crypto->s.get_digest(hash);\n}\n", "meta": {"hexsha": "bd46ba347982a4695d512304428a5d82d0949682", "size": 892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/crypto_hash.cpp", "max_stars_repo_name": "shmarovfedor/esbmc", "max_stars_repo_head_hexsha": "3226a3d68b009d44b9535a993ac0f25e1a1fbedd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 143.0, "max_stars_repo_stars_event_min_datetime": "2015-06-22T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:41:17.000Z", "max_issues_repo_path": "src/util/crypto_hash.cpp", "max_issues_repo_name": "shmarovfedor/esbmc", "max_issues_repo_head_hexsha": "3226a3d68b009d44b9535a993ac0f25e1a1fbedd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 542.0, "max_issues_repo_issues_event_min_datetime": "2017-06-02T13:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:35:17.000Z", "max_forks_repo_path": "src/util/crypto_hash.cpp", "max_forks_repo_name": "shmarovfedor/esbmc", "max_forks_repo_head_hexsha": "3226a3d68b009d44b9535a993ac0f25e1a1fbedd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 81.0, "max_forks_repo_forks_event_min_datetime": "2015-10-21T22:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T14:07:55.000Z", "avg_line_length": 18.2040816327, "max_line_length": 62, "alphanum_fraction": 0.697309417, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18520356387055378}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, 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_ALGORITHMS_DETAIL_CLOSEST_POINTS_POINT_TO_GEOMETRY_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_CLOSEST_POINTS_POINT_TO_GEOMETRY_HPP\n\n#include <iterator>\n#include <type_traits>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n#include <boost/range/size.hpp>\n#include <boost/range/value_type.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/algorithms/detail/closest_feature/geometry_to_range.hpp>\n#include <boost/geometry/algorithms/detail/closest_feature/point_to_range.hpp>\n#include <boost/geometry/algorithms/detail/distance/is_comparable.hpp>\n#include <boost/geometry/algorithms/detail/distance/iterator_selector.hpp>\n#include <boost/geometry/algorithms/detail/distance/strategy_utils.hpp>\n#include <boost/geometry/algorithms/detail/within/point_in_geometry.hpp>\n#include <boost/geometry/algorithms/dispatch/distance.hpp>\n\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/tag.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/relate/services.hpp>\n#include <boost/geometry/strategies/tags.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace closest_points\n{\n\nstruct point_to_point\n{\n    template <typename P1, typename P2, typename Segment, typename Strategies>\n    static inline void apply(P1 const& p1, P2 const& p2,  \n                             Segment& shortest_seg, Strategies const&)\n    {\n        set_segment_from_points::apply(p1, p2, shortest_seg);\n    }\n};\n\nstruct point_to_segment\n{\n    template <typename Point, typename Segment, typename OutputSegment, typename Strategies>\n    static inline void apply(Point const& point, Segment const& segment,\n                             OutputSegment& shortest_seg, Strategies const& strategies)\n    {\n        typename point_type<Segment>::type p[2];\n        geometry::detail::assign_point_from_index<0>(segment, p[0]);\n        geometry::detail::assign_point_from_index<1>(segment, p[1]);\n\n        boost::ignore_unused(strategies);\n\n        auto closest_point = strategies.closest_points(point, segment)\n            .apply(point, p[0], p[1]);\n\n        set_segment_from_points::apply(point, closest_point, shortest_seg);    \n    }\n};\n\n/*\nstruct point_to_box\n{\n    template<typename Point, typename Box, typename Strategies>\nstatic inline auto apply(Point const& point, Box const& box,\n                             Strategies const& strategies)\n    {\n        boost::ignore_unused(strategies);\n        return strategies.closest_points(point, box).apply(point, box);\n    }\n};\n*/\n\ntemplate <closure_selector Closure>\nclass point_to_range\n{\npublic:\n\n    template <typename Point, typename Range, typename Segment, typename Strategies>\n    static inline void apply(Point const& point, Range const& range,\n                             Segment& shortest_seg,\n                             Strategies const& strategies)\n    {\n        using point_to_point_range = detail::closest_feature::point_to_point_range\n            <\n                Point, Range, Closure\n            >;\n\n        if (boost::size(range) == 0)\n        {\n            set_segment_from_points::apply(point, point, shortest_seg);\n            return;\n        }\n\n        closest_points::creturn_t<Point, Range, Strategies> cd_min;\n        \n        auto comparable_distance = strategy::distance::services::get_comparable\n            <\n                decltype(strategies.distance(point, range))\n            >::apply(strategies.distance(point, range));\n        \n        auto closest_segment = point_to_point_range::apply(point, \n                                                           boost::begin(range),\n                                                           boost::end(range), \n                                                           comparable_distance,\n                                                           cd_min);\n        \n        auto closest_point = strategies.closest_points(point, range)\n            .apply(point, *closest_segment.first, *closest_segment.second);\n\n        set_segment_from_points::apply(point, closest_point, shortest_seg);        \n    }\n};\n\n\ntemplate<closure_selector Closure>\nstruct point_to_ring\n{\n    template <typename Point, typename Ring, typename Segment, typename Strategies>\n    static inline auto apply(Point const& point,\n                             Ring const& ring,\n                             Segment& shortest_seg,\n                             Strategies const& strategies)\n    {\n        if (within::within_point_geometry(point, ring, strategies))\n        {\n            set_segment_from_points::apply(point, point, shortest_seg); \n        }\n        else\n        {\n            point_to_range\n            <\n                closure<Ring>::value\n            >::apply(point, ring, shortest_seg, strategies);\n        }\n            \n    }\n};\n\n\ntemplate <closure_selector Closure>\nclass point_to_polygon\n{\n    template <typename Polygon>\n    struct distance_to_interior_rings\n    {\n        template \n        <\n            typename Point, \n            typename InteriorRingIterator, \n            typename Segment, \n            typename Strategies\n        >\n        static inline void apply(Point const& point,\n                                 InteriorRingIterator first,\n                                 InteriorRingIterator last,\n                                 Segment& shortest_seg,\n                                 Strategies const& strategies)\n        {\n            using per_ring = point_to_range<Closure>;\n\n            for (InteriorRingIterator it = first; it != last; ++it)\n            {\n                if (within::within_point_geometry(point, *it, strategies))\n                {\n                    // the point is inside a polygon hole, so its distance\n                    // to the polygon is its distance to the polygon's\n                    // hole boundary\n                    per_ring::apply(point, *it, shortest_seg, strategies);\n                    return;\n                }\n            }\n            set_segment_from_points::apply(point, point, shortest_seg); \n        }\n\n        template \n        <\n            typename Point, \n            typename InteriorRings, \n            typename Segment, \n            typename Strategies\n        >\n        static inline void apply(Point const& point, InteriorRings const& interior_rings,\n                                 Segment& shortest_seg, Strategies const& strategies)\n        {\n            apply(point,\n                  boost::begin(interior_rings),\n                  boost::end(interior_rings),\n                  shortest_seg,\n                  strategies);\n        }\n    };\n\n\npublic:\n    template \n    <\n        typename Point, \n        typename Polygon, \n        typename Segment, \n        typename Strategies\n    >\n    static inline void apply(Point const& point,\n                             Polygon const& polygon,\n                             Segment& shortest_seg,\n                             Strategies const& strategies)\n    {\n        using per_ring = point_to_range<Closure>;\n\n        if (! within::covered_by_point_geometry(point, exterior_ring(polygon),\n                                                strategies))\n        {\n            // the point is outside the exterior ring, so its distance\n            // to the polygon is its distance to the polygon's exterior ring\n            per_ring::apply(point, exterior_ring(polygon), shortest_seg, strategies);\n            return;\n        }\n\n        // Check interior rings\n        distance_to_interior_rings<Polygon>::apply(point,\n                                                   interior_rings(polygon),\n                                                   shortest_seg,\n                                                   strategies);\n    }\n};\n\n\ntemplate\n<\n    typename MultiGeometry,\n    bool CheckCoveredBy = std::is_same\n        <\n            typename tag<MultiGeometry>::type, multi_polygon_tag\n        >::value\n>\nclass point_to_multigeometry\n{\nprivate:\n    using geometry_to_range = detail::closest_feature::geometry_to_range;\n\npublic:\n\n    template \n    <\n        typename Point,\n        typename Segment,\n        typename Strategies\n    >\n    static inline void apply(Point const& point,\n                             MultiGeometry const& multigeometry,\n                             Segment& shortest_seg,\n                             Strategies const& strategies)\n    {\n        using selector_type = distance::iterator_selector<MultiGeometry const>;\n\n        closest_points::creturn_t<Point, MultiGeometry, Strategies> cd;\n\n        auto comparable_distance = strategy::distance::services::get_comparable\n            <\n                decltype(strategies.distance(point, multigeometry))\n            >::apply(strategies.distance(point, multigeometry));\n\n        typename selector_type::iterator_type it_min\n            = geometry_to_range::apply(point,\n                                       selector_type::begin(multigeometry),\n                                       selector_type::end(multigeometry),\n                                       comparable_distance,\n                                       cd);\n        \n        dispatch::closest_points\n            <\n                Point,\n                typename std::iterator_traits\n                    <\n                        typename selector_type::iterator_type\n                    >::value_type\n            >::apply(point, *it_min, shortest_seg, strategies);\n    }\n};\n\n\n// this is called only for multipolygons, hence the change in the\n// template parameter name MultiGeometry to MultiPolygon\ntemplate <typename MultiPolygon>\nstruct point_to_multigeometry<MultiPolygon, true>\n{\n    template \n    <\n        typename Point,\n        typename Segment,\n        typename Strategies\n    >\n    static inline void apply(Point const& point,\n                             MultiPolygon const& multipolygon,\n                             Segment& shortest_seg,\n                             Strategies const& strategies)\n    {\n        if (within::covered_by_point_geometry(point, multipolygon, strategies))\n        {\n            set_segment_from_points::apply(point, point, shortest_seg); \n            return;\n        }\n\n        return point_to_multigeometry\n            <\n                MultiPolygon, false\n            >::apply(point, multipolygon, shortest_seg, strategies);\n    }\n};\n\n\n}} // namespace detail::closest_points\n#endif // DOXYGEN_NO_DETAIL\n\n\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\ntemplate <typename P1, typename P2>\nstruct closest_points\n    <\n        P1, P2, point_tag, point_tag, false\n    > : detail::closest_points::point_to_point\n{};\n\n\ntemplate <typename Point, typename Linestring>\nstruct closest_points\n    <\n        Point, Linestring, point_tag, linestring_tag, false\n    > : detail::closest_points::point_to_range<closed>\n{};\n\n\ntemplate <typename Point, typename Ring>\nstruct closest_points\n    <\n        Point, Ring, point_tag, ring_tag, false\n    > : detail::closest_points::point_to_ring\n        <\n            closure<Ring>::value\n        >\n{};\n\n\ntemplate <typename Point, typename Polygon>\nstruct closest_points\n    <\n        Point, Polygon, point_tag, polygon_tag, false\n    > : detail::closest_points::point_to_polygon\n        <\n            closure<Polygon>::value\n        >\n{};\n\n\ntemplate <typename Point, typename Segment>\nstruct closest_points\n    <\n        Point, Segment, point_tag, segment_tag, false\n    > : detail::closest_points::point_to_segment\n{};\n\n/*\ntemplate <typename Point, typename Box>\nstruct closest_points\n    <\n         Point, Box, point_tag, box_tag,\n         strategy_tag_distance_point_box, false\n    > : detail::closest_points::point_to_box<Point, Box>\n{};\n*/\n\ntemplate<typename Point, typename MultiPoint>\nstruct closest_points\n    <\n        Point, MultiPoint, point_tag, multi_point_tag, false\n    > : detail::closest_points::point_to_multigeometry<MultiPoint>\n{};\n\n\ntemplate<typename Point, typename MultiLinestring>\nstruct closest_points\n    <\n        Point, MultiLinestring, point_tag, multi_linestring_tag, false\n    > : detail::closest_points::point_to_multigeometry<MultiLinestring>\n{};\n\n\ntemplate<typename Point, typename MultiPolygon>\nstruct closest_points\n    <\n        Point, MultiPolygon, point_tag, multi_polygon_tag, false\n    > : detail::closest_points::point_to_multigeometry<MultiPolygon>\n{};\n\n\ntemplate <typename Point, typename Linear>\nstruct closest_points\n    <\n         Point, Linear, point_tag, linear_tag, false\n    > : closest_points\n        <\n            Point, Linear,\n            point_tag, typename tag<Linear>::type, false\n        >\n{};\n\n\ntemplate <typename Point, typename Areal>\nstruct closest_points\n    <\n         Point, Areal, point_tag, areal_tag, false\n    > : closest_points\n        <\n            Point, Areal,\n            point_tag, typename tag<Areal>::type, false\n        >\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_CLOSEST_POINTS_POINT_TO_GEOMETRY_HPP\n", "meta": {"hexsha": "88fad5247f3f85c862b797669db846a6912a268b", "size": 13653, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/algorithms/detail/closest_points/point_to_geometry.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/geometry/algorithms/detail/closest_points/point_to_geometry.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/geometry/algorithms/detail/closest_points/point_to_geometry.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": 30.0065934066, "max_line_length": 92, "alphanum_fraction": 0.6069728265, "num_tokens": 2635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1852035515052762}}
{"text": "#include \"FighterEntity.h\"\n#include \"../Config/PlayerMovement.h\"\n#include \"../Config/GameRules.h\"\n#include <boost/math/constants/constants.hpp>\n\n#include <DescentEngine/src/EntityEngine/EntityEngine.h>\n#include <DescentEngine/src/Pathfinding/Pathfinding.h>\n#include <DescentEngine/src/Pathfinding/Node.h>\n#include <DescentEngine/src/Timing.h>\n#include <bullet/btBulletCollisionCommon.h>\n\nFighterEntity::FighterEntity(Vector2 intialPosition, Rectangle2 boundingBox) :\n\t\tMultiVisualEntity(intialPosition, boundingBox), m_dead(false), m_life(GameRules::FighterLife), m_attackTime(\n\t\t\t\tEnemyBehaviour::AttacDelay), m_lastHit(-1.0f) {\n\tm_doesCollisionStick = true;\n\tsetCollisionGroup(GameCollisionGroups::Characters);\n\tsetCollisionMask(GameCollisionGroups::Characters_CollidesWith);\n}\n\nint FighterEntity::getCurrentSekktor() const {\n\tauto dir = getDirection();\n\n\tfloat cosPhi = acos(dir.y());\n\t// handle left sektor\n\tif (dir.x() < 0.0f) {\n\t\tcosPhi = boost::math::constants::pi<float>() + boost::math::constants::pi<float>() - cosPhi;\n\t}\n\tfloat sektor = (cosPhi / (2.0f * boost::math::constants::pi<float>())) * 8.0f;\n\t// rotate, so the up / down position will be in the middle of a sekktor\n\t// and not on the border\n\tsektor += 0.5f;\n\t// handle wrap around\n\tif (sektor < 0.0f) {\n\t\tsektor = std::fabs(0.5f + sektor);\n\t}\n\tif (sektor >= 8.0f) {\n\t\tsektor = 0.0f;\n\t}\n\n\treturn std::floor(sektor);\n}\n\nvoid FighterEntity::updateVisual(Engines & eg) {\n\tconst int sekktor = getCurrentSekktor();\n\n\tif (isDead()) {\n\t\tchangeActiveVisual(eg, DescentTextureIds::Dead_0 + sekktor);\n\t} else if (getJumpAction().isActive()) {\n\t\tchangeActiveVisual(eg, DescentTextureIds::Jump_0 + sekktor);\n\t} else if (getKickAction().isActive()) {\n\t\tchangeActiveVisual(eg, DescentTextureIds::Kick_0 + sekktor);\n\t} else if (getHitAction().isActive()) {\n\t\tchangeActiveVisual(eg, DescentTextureIds::Hit_0 + sekktor);\n\t\t// todo: use movement here so only walk when we actually move\n\t} else if (wasMoved()) {\n\t\tchangeActiveVisual(eg, DescentTextureIds::Walk_0 + sekktor);\n\t} else {\n\t\t// idle animation\n\t\t// todo: call only when needed\n\t\tchangeActiveVisual(eg, DescentTextureIds::Stand_0 + sekktor);\n\t}\n}\n\nvoid FighterEntity::validateActions(float deltaT, float hitRegenTime) {\n\t// todo: not so nice, make this more generic\n\tgetJumpAction().validate(deltaT, PlayerMovement::JumpRegenerationTime);\n\tgetKickAction().validate(deltaT, PlayerMovement::JumpRegenerationTime);\n\tgetHitAction().validate(deltaT, hitRegenTime);\n}\n\nvoid FighterEntity::die() {\n\tm_dead = true;\n\tsetCollisionGroup(GameCollisionGroups::CharactersDead);\n\tsetCollisionMask(GameCollisionGroups::CharactersDead_CollidesWith);\n\tlogging::Debug<>() << \"A Fighter died !\";\n}\n\nfloat FighterEntity::runTo(Vector2 location, float maxSpeed, float deltaT, EntityEngine & entNG,\n\t\tfloat closeThreshold) {\n\n\tconstexpr float minimumMoveSq(util::sq(0.1f));\n\n\t// we are almost there already ...\n\tif (util::withinDelta(getPosition(), location, minimumMoveSq)) {\n\t\treturn 0.0f;\n\t}\n\n\tbool runPathfinding = true;\n\n\tif (m_nextNode.isValid())\n\t\tif (!util::withinDelta(getPosition(), m_nextNode.getValue(), minimumMoveSq)) {\n\t\t\t// just move further to the last node found\n\t\t\t// not close enough to this node, yet\n\t\t\trunPathfinding = false;\n\t\t}\n\n\tif (runPathfinding) {\n\t\tPathfinding & finding = entNG.getPathfinding();\n\n\t\tNode * startNode = entNG.findClosestNode(this->getPosition());\n\t\tNode * endNode = entNG.findClosestNode(location);\n\n\t\tassert(startNode);\n\t\tassert(endNode);\n\n\t\t//Timing tm;\n\t\tfinding.reset();\n\t\tfinding.resetNodes(entNG.getPathfindingNodes());\n\t\tconst auto path = finding.pathToNode(startNode, endNode);\n\t\t//float dt = tm.end();\n\t\t//logging::Info() << \"Pathfinding took \" << dt << \" seconds\";\n\n\t\t// move to the next node:\n\t\tconst float distToTarget = startNode->distanceTo(endNode);\n\t\tif (path.size() > 1) {\n\t\t\tconst Vector2 nextLocation = path[1]->Location;\n\t\t\tm_nextNode.setValue(nextLocation);\n\t\t} else {\n\t\t\tm_nextNode.invalidate();\n\t\t\treturn 0.0f;\n\t\t}\n\t}\n\tconst Vector2 conVector(m_nextNode.getValue() - getPosition());\n\tconst float dist = conVector.mag();\n\tconst Vector2 dir = conVector.normalizedCopy();\n\n\tif (dir.nonZero()) {\n\t\tconst float maxSpeedPerTimeStep = maxSpeed * deltaT;\n\n\t\tconst Vector2 maxMove = dir * maxSpeedPerTimeStep;\n\t\tsetDirection(dir);\n\t\tsetMoveDelta(maxMove);\n\t}\n\n\tconst float distToTarget = (getPosition() - location).mag();\n\n\treturn distToTarget;\n}\n\n", "meta": {"hexsha": "0fd5abcf2f0d3ff78f3233cf5096eacf0292c3bc", "size": 4396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DescentLogic/src/Entities/FighterEntity.cpp", "max_stars_repo_name": "poseidn/KungFoo-legacy", "max_stars_repo_head_hexsha": "9b79d65b596acc9dff4725ef5bfab8ecc4164afb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-24T03:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-24T03:01:31.000Z", "max_issues_repo_path": "src/DescentLogic/src/Entities/FighterEntity.cpp", "max_issues_repo_name": "poseidn/KungFoo-legacy", "max_issues_repo_head_hexsha": "9b79d65b596acc9dff4725ef5bfab8ecc4164afb", "max_issues_repo_licenses": ["MIT"], "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/DescentLogic/src/Entities/FighterEntity.cpp", "max_forks_repo_name": "poseidn/KungFoo-legacy", "max_forks_repo_head_hexsha": "9b79d65b596acc9dff4725ef5bfab8ecc4164afb", "max_forks_repo_licenses": ["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.4, "max_line_length": 110, "alphanum_fraction": 0.7242948135, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.18483967437237464}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2016.\n// Modifications copyright (c) 2016 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_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR\n\n\n#include <boost/core/ignore_unused.hpp>\n\n#include <boost/range.hpp>\n\n#include <boost/geometry/core/assert.hpp>\n\n#include <boost/geometry/arithmetic/dot_product.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/algorithms/comparable_distance.hpp>\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/algorithms/expand.hpp>\n#include <boost/geometry/algorithms/detail/disjoint/point_box.hpp>\n#include <boost/geometry/algorithms/detail/disjoint/box_box.hpp>\n#include <boost/geometry/algorithms/detail/overlay/segment_identifier.hpp>\n#include <boost/geometry/algorithms/detail/overlay/get_turn_info.hpp>\n#include <boost/geometry/policies/compare.hpp>\n#include <boost/geometry/strategies/buffer.hpp>\n#include <boost/geometry/algorithms/detail/buffer/buffer_policies.hpp>\n\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n#include <boost/geometry/strategies/cartesian/side_of_intersection.hpp>\n#endif\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace buffer\n{\n\nstruct piece_get_box\n{\n    template <typename Box, typename Piece>\n    static inline void apply(Box& total, Piece const& piece)\n    {\n        geometry::expand(total, piece.robust_envelope);\n    }\n};\n\nstruct piece_ovelaps_box\n{\n    template <typename Box, typename Piece>\n    static inline bool apply(Box const& box, Piece const& piece)\n    {\n        if (piece.type == strategy::buffer::buffered_flat_end\n            || piece.type == strategy::buffer::buffered_concave)\n        {\n            // Turns cannot be inside a flat end (though they can be on border)\n            // Neither we need to check if they are inside concave helper pieces\n\n            // Skip all pieces not used as soon as possible\n            return false;\n        }\n\n        return ! geometry::detail::disjoint::disjoint_box_box(box, piece.robust_envelope);\n    }\n};\n\nstruct turn_get_box\n{\n    template <typename Box, typename Turn>\n    static inline void apply(Box& total, Turn const& turn)\n    {\n        geometry::expand(total, turn.robust_point);\n    }\n};\n\nstruct turn_ovelaps_box\n{\n    template <typename Box, typename Turn>\n    static inline bool apply(Box const& box, Turn const& turn)\n    {\n        return ! geometry::detail::disjoint::disjoint_point_box(turn.robust_point, box);\n    }\n};\n\n\nenum analyse_result\n{\n    analyse_unknown,\n    analyse_continue,\n    analyse_disjoint,\n    analyse_within,\n    analyse_on_original_boundary,\n    analyse_on_offsetted\n#if ! defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n    , analyse_near_offsetted\n#endif\n};\n\ntemplate <typename Point>\ninline bool in_box(Point const& previous,\n        Point const& current, Point const& point)\n{\n    // Get its box (TODO: this can be prepared-on-demand later)\n    typedef geometry::model::box<Point> box_type;\n    box_type box;\n    geometry::assign_inverse(box);\n    geometry::expand(box, previous);\n    geometry::expand(box, current);\n\n    return geometry::covered_by(point, box);\n}\n\ntemplate <typename Point, typename Turn>\ninline analyse_result check_segment(Point const& previous,\n        Point const& current, Turn const& turn,\n        bool from_monotonic)\n{\n\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n    typedef geometry::model::referring_segment<Point const> segment_type;\n    segment_type const p(turn.rob_pi, turn.rob_pj);\n    segment_type const q(turn.rob_qi, turn.rob_qj);\n    segment_type const r(previous, current);\n    int const side = strategy::side::side_of_intersection::apply(p, q, r,\n                turn.robust_point);\n\n    if (side == 0)\n    {\n        return analyse_on_offsetted;\n    }\n    if (side == -1 && from_monotonic)\n    {\n        return analyse_within;\n    }\n    if (side == 1 && from_monotonic)\n    {\n        return analyse_disjoint;\n    }\n    return analyse_continue;\n\n#else\n\n    typedef typename strategy::side::services::default_strategy\n        <\n            typename cs_tag<Point>::type\n        >::type side_strategy;\n    typedef typename geometry::coordinate_type<Point>::type coordinate_type;\n\n    coordinate_type const twice_area\n        = side_strategy::template side_value\n            <\n                coordinate_type,\n                coordinate_type\n            >(previous, current, turn.robust_point);\n\n    if (twice_area == 0)\n    {\n        // Collinear, only on segment if it is covered by its bbox\n        if (in_box(previous, current, turn.robust_point))\n        {\n            return analyse_on_offsetted;\n        }\n    }\n    else if (twice_area < 0)\n    {\n        // It is in the triangle right-of the segment where the\n        // segment is the hypothenusa. Check if it is close\n        // (within rounding-area)\n        if (twice_area * twice_area < geometry::comparable_distance(previous, current)\n            && in_box(previous, current, turn.robust_point))\n        {\n            return analyse_near_offsetted;\n        }\n        else if (from_monotonic)\n        {\n            return analyse_within;\n        }\n    }\n    else if (twice_area > 0 && from_monotonic)\n    {\n        // Left of segment\n        return analyse_disjoint;\n    }\n\n    // Not monotonic, on left or right side: continue analysing\n    return analyse_continue;\n#endif\n}\n\n\nclass analyse_turn_wrt_point_piece\n{\npublic :\n    template <typename Turn, typename Piece>\n    static inline analyse_result apply(Turn const& turn, Piece const& piece)\n    {\n        typedef typename Piece::section_type section_type;\n        typedef typename Turn::robust_point_type point_type;\n        typedef typename geometry::coordinate_type<point_type>::type coordinate_type;\n\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n        typedef geometry::model::referring_segment<point_type const> segment_type;\n        segment_type const p(turn.rob_pi, turn.rob_pj);\n        segment_type const q(turn.rob_qi, turn.rob_qj);\n#else\n        typedef strategy::within::winding<point_type> strategy_type;\n\n        typename strategy_type::state_type state;\n        strategy_type strategy;\n        boost::ignore_unused(strategy);\n#endif\n\n        BOOST_GEOMETRY_ASSERT(! piece.sections.empty());\n\n        coordinate_type const point_x = geometry::get<0>(turn.robust_point);\n\n        for (std::size_t s = 0; s < piece.sections.size(); s++)\n        {\n            section_type const& section = piece.sections[s];\n            // If point within horizontal range of monotonic section:\n            if (! section.duplicate\n                && section.begin_index < section.end_index\n                && point_x >= geometry::get<min_corner, 0>(section.bounding_box) - 1\n                && point_x <= geometry::get<max_corner, 0>(section.bounding_box) + 1)\n            {\n                for (signed_size_type i = section.begin_index + 1; i <= section.end_index; i++)\n                {\n                    point_type const& previous = piece.robust_ring[i - 1];\n                    point_type const& current = piece.robust_ring[i];\n\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n\n                    // First check if it is in range - if it is not, the\n                    // expensive side_of_intersection does not need to be\n                    // applied\n                    coordinate_type x1 = geometry::get<0>(previous);\n                    coordinate_type x2 = geometry::get<0>(current);\n\n                    if (x1 > x2)\n                    {\n                        std::swap(x1, x2);\n                    }\n\n                    if (point_x >= x1 - 1 && point_x <= x2 + 1)\n                    {\n                        segment_type const r(previous, current);\n                        int const side = strategy::side::side_of_intersection::apply(p, q, r,\n                                    turn.robust_point);\n\n                        // Sections are monotonic in x-dimension\n                        if (side == 1)\n                        {\n                            // Left on segment\n                            return analyse_disjoint;\n                        }\n                        else if (side == 0)\n                        {\n                            // Collinear - TODO: check if really on segment\n                            return analyse_on_offsetted;\n                        }\n                    }\n#else\n                    analyse_result code = check_segment(previous, current, turn, false);\n                    if (code != analyse_continue)\n                    {\n                        return code;\n                    }\n\n                    // Get the state (to determine it is within), we don't have\n                    // to cover the on-segment case (covered above)\n                    strategy.apply(turn.robust_point, previous, current, state);\n#endif\n                }\n            }\n        }\n\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n        // It is nowhere outside, and not on segment, so it is within\n        return analyse_within;\n#else\n        int const code = strategy.result(state);\n        if (code == 1)\n        {\n            return analyse_within;\n        }\n        else if (code == -1)\n        {\n            return analyse_disjoint;\n        }\n\n        // Should normally not occur - on-segment is covered\n        return analyse_unknown;\n#endif\n    }\n\n};\n\nclass analyse_turn_wrt_piece\n{\n    template <typename Point, typename Turn>\n    static inline analyse_result check_helper_segment(Point const& s1,\n                Point const& s2, Turn const& turn,\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n                bool , // is on original, to be reused\n#else\n                bool is_original,\n#endif\n                Point const& offsetted)\n    {\n        boost::ignore_unused(offsetted);\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n        typedef geometry::model::referring_segment<Point const> segment_type;\n        segment_type const p(turn.rob_pi, turn.rob_pj);\n        segment_type const q(turn.rob_qi, turn.rob_qj);\n        segment_type const r(s1, s2);\n        int const side = strategy::side::side_of_intersection::apply(p, q, r,\n                    turn.robust_point);\n\n        if (side == 1)\n        {\n            // left of segment\n            return analyse_disjoint;\n        }\n        else if (side == 0)\n        {\n            // If is collinear, either on segment or before/after\n            typedef geometry::model::box<Point> box_type;\n\n            box_type box;\n            geometry::assign_inverse(box);\n            geometry::expand(box, s1);\n            geometry::expand(box, s2);\n\n            if (geometry::covered_by(turn.robust_point, box))\n            {\n                // Points on helper-segments (and not on its corners)\n                // are considered as within\n                return analyse_within;\n            }\n\n            // It is collinear but not on the segment. Because these\n            // segments are convex, it is outside\n            // Unless the offsetted ring is collinear or concave w.r.t.\n            // helper-segment but that scenario is not yet supported\n            return analyse_disjoint;\n        }\n\n        // right of segment\n        return analyse_continue;\n#else\n        typedef typename strategy::side::services::default_strategy\n            <\n                typename cs_tag<Point>::type\n            >::type side_strategy;\n\n        switch(side_strategy::apply(s1, s2, turn.robust_point))\n        {\n            case 1 :\n                return analyse_disjoint; // left of segment\n            case 0 :\n                {\n                    // If is collinear, either on segment or before/after\n                    typedef geometry::model::box<Point> box_type;\n\n                    box_type box;\n                    geometry::assign_inverse(box);\n                    geometry::expand(box, s1);\n                    geometry::expand(box, s2);\n\n                    if (geometry::covered_by(turn.robust_point, box))\n                    {\n                        // It is on the segment\n                        if (! is_original\n                            && geometry::comparable_distance(turn.robust_point, offsetted) <= 1)\n                        {\n                            // It is close to the offsetted-boundary, take\n                            // any rounding-issues into account\n                            return analyse_near_offsetted;\n                        }\n\n                        // Points on helper-segments are considered as within\n                        // Points on original boundary are processed differently\n                        return is_original\n                            ? analyse_on_original_boundary\n                            : analyse_within;\n                    }\n\n                    // It is collinear but not on the segment. Because these\n                    // segments are convex, it is outside\n                    // Unless the offsetted ring is collinear or concave w.r.t.\n                    // helper-segment but that scenario is not yet supported\n                    return analyse_disjoint;\n                }\n                break;\n        }\n\n        // right of segment\n        return analyse_continue;\n#endif\n    }\n\n    template <typename Turn, typename Piece>\n    static inline analyse_result check_helper_segments(Turn const& turn, Piece const& piece)\n    {\n        typedef typename Turn::robust_point_type point_type;\n        geometry::equal_to<point_type> comparator;\n\n        point_type points[4];\n\n        signed_size_type helper_count = static_cast<signed_size_type>(piece.robust_ring.size())\n                                            - piece.offsetted_count;\n        if (helper_count == 4)\n        {\n            for (int i = 0; i < 4; i++)\n            {\n                points[i] = piece.robust_ring[piece.offsetted_count + i];\n            }\n\n            //      3--offsetted outline--0\n            //      |                     |\n            // left |                     | right\n            //      |                     |\n            //      2===>==original===>===1\n\n        }\n        else if (helper_count == 3)\n        {\n            // Triangular piece, assign points but assign second twice\n            for (int i = 0; i < 4; i++)\n            {\n                int index = i < 2 ? i : i - 1;\n                points[i] = piece.robust_ring[piece.offsetted_count + index];\n            }\n        }\n        else\n        {\n            // Some pieces (e.g. around points) do not have helper segments.\n            // Others should have 3 (join) or 4 (side)\n            return analyse_continue;\n        }\n\n        // First check point-equality\n        point_type const& point = turn.robust_point;\n        if (comparator(point, points[0]) || comparator(point, points[3]))\n        {\n            return analyse_on_offsetted;\n        }\n        if (comparator(point, points[1]))\n        {\n            // On original, right corner\n            return piece.is_flat_end ? analyse_continue : analyse_on_original_boundary;\n        }\n        if (comparator(point, points[2]))\n        {\n            // On original, left corner\n            return piece.is_flat_start ? analyse_continue : analyse_on_original_boundary;\n        }\n\n        // Right side of the piece\n        analyse_result result\n            = check_helper_segment(points[0], points[1], turn,\n                    false, points[0]);\n        if (result != analyse_continue)\n        {\n            return result;\n        }\n\n        // Left side of the piece\n        result = check_helper_segment(points[2], points[3], turn,\n                    false, points[3]);\n        if (result != analyse_continue)\n        {\n            return result;\n        }\n\n        if (! comparator(points[1], points[2]))\n        {\n            // Side of the piece at side of original geometry\n            result = check_helper_segment(points[1], points[2], turn,\n                        true, point);\n            if (result != analyse_continue)\n            {\n                return result;\n            }\n        }\n\n        // We are within the \\/ or |_| shaped piece, where the top is the\n        // offsetted ring.\n        if (! geometry::covered_by(point, piece.robust_offsetted_envelope))\n        {\n            // Not in offsetted-area. This makes a cheap check possible\n            typedef typename strategy::side::services::default_strategy\n                <\n                    typename cs_tag<point_type>::type\n                >::type side_strategy;\n\n            switch(side_strategy::apply(points[3], points[0], point))\n            {\n                case 1 : return analyse_disjoint;\n                case -1 : return analyse_within;\n                case 0 : return analyse_disjoint;\n            }\n        }\n\n        return analyse_continue;\n    }\n\n    template <typename Turn, typename Piece, typename Compare>\n    static inline analyse_result check_monotonic(Turn const& turn, Piece const& piece, Compare const& compare)\n    {\n        typedef typename Piece::piece_robust_ring_type ring_type;\n        typedef typename ring_type::const_iterator it_type;\n        it_type end = piece.robust_ring.begin() + piece.offsetted_count;\n        it_type it = std::lower_bound(piece.robust_ring.begin(),\n                    end,\n                    turn.robust_point,\n                    compare);\n\n        if (it != end\n            && it != piece.robust_ring.begin())\n        {\n            // iterator points to point larger than point\n            // w.r.t. specified direction, and prev points to a point smaller\n            // We now know if it is inside/outside\n            it_type prev = it - 1;\n            return check_segment(*prev, *it, turn, true);\n        }\n        return analyse_continue;\n    }\n\npublic :\n    template <typename Turn, typename Piece>\n    static inline analyse_result apply(Turn const& turn, Piece const& piece)\n    {\n        typedef typename Turn::robust_point_type point_type;\n        analyse_result code = check_helper_segments(turn, piece);\n        if (code != analyse_continue)\n        {\n            return code;\n        }\n\n        geometry::equal_to<point_type> comparator;\n\n        if (piece.offsetted_count > 8)\n        {\n            // If the offset contains some points and is monotonic, we try\n            // to avoid walking all points linearly.\n            // We try it only once.\n            if (piece.is_monotonic_increasing[0])\n            {\n                code = check_monotonic(turn, piece, geometry::less<point_type, 0>());\n                if (code != analyse_continue) return code;\n            }\n            else if (piece.is_monotonic_increasing[1])\n            {\n                code = check_monotonic(turn, piece, geometry::less<point_type, 1>());\n                if (code != analyse_continue) return code;\n            }\n            else if (piece.is_monotonic_decreasing[0])\n            {\n                code = check_monotonic(turn, piece, geometry::greater<point_type, 0>());\n                if (code != analyse_continue) return code;\n            }\n            else if (piece.is_monotonic_decreasing[1])\n            {\n                code = check_monotonic(turn, piece, geometry::greater<point_type, 1>());\n                if (code != analyse_continue) return code;\n            }\n        }\n\n        // It is small or not monotonic, walk linearly through offset\n        // TODO: this will be combined with winding strategy\n\n        for (signed_size_type i = 1; i < piece.offsetted_count; i++)\n        {\n            point_type const& previous = piece.robust_ring[i - 1];\n            point_type const& current = piece.robust_ring[i];\n\n            // The robust ring can contain duplicates\n            // (on which any side or side-value would return 0)\n            if (! comparator(previous, current))\n            {\n                code = check_segment(previous, current, turn, false);\n                if (code != analyse_continue)\n                {\n                    return code;\n                }\n            }\n        }\n\n        return analyse_unknown;\n    }\n\n};\n\n\ntemplate <typename Turns, typename Pieces>\nclass turn_in_piece_visitor\n{\n    Turns& m_turns; // because partition is currently operating on const input only\n    Pieces const& m_pieces; // to check for piece-type\n\n    template <typename Operation, typename Piece>\n    inline bool skip(Operation const& op, Piece const& piece) const\n    {\n        if (op.piece_index == piece.index)\n        {\n            return true;\n        }\n        Piece const& pc = m_pieces[op.piece_index];\n        if (pc.left_index == piece.index || pc.right_index == piece.index)\n        {\n            if (pc.type == strategy::buffer::buffered_flat_end)\n            {\n                // If it is a flat end, don't compare against its neighbor:\n                // it will always be located on one of the helper segments\n                return true;\n            }\n            if (pc.type == strategy::buffer::buffered_concave)\n            {\n                // If it is concave, the same applies: the IP will be\n                // located on one of the helper segments\n                return true;\n            }\n        }\n\n        return false;\n    }\n\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n    // NOTE: this function returns a side value in {-1, 0, 1}\n    template <typename Turn, typename Piece>\n    static inline int turn_in_convex_piece(Turn const& turn,\n            Piece const& piece)\n    {\n        typedef typename Turn::robust_point_type point_type;\n        typedef typename Piece::piece_robust_ring_type ring_type;\n        typedef geometry::model::referring_segment<point_type const> segment;\n\n        segment const p(turn.rob_pi, turn.rob_pj);\n        segment const q(turn.rob_qi, turn.rob_qj);\n\n        typedef typename boost::range_iterator<ring_type const>::type iterator_type;\n        iterator_type it = boost::begin(piece.robust_ring);\n        iterator_type end = boost::end(piece.robust_ring);\n\n        // A robust ring is always closed, and always clockwise\n        for (iterator_type previous = it++; it != end; ++previous, ++it)\n        {\n            geometry::equal_to<point_type> comparator;\n            if (comparator(*previous, *it))\n            {\n                // Points are the same\n                continue;\n            }\n\n            segment r(*previous, *it);\n\n            int const side = strategy::side::side_of_intersection::apply(p, q, r,\n                        turn.robust_point);\n\n            if (side == 1)\n            {\n                // IP is left of segment, so it is outside\n                return -1; // outside\n            }\n            else if (side == 0)\n            {\n                // IP is collinear with segment. TODO: we should analyze this further\n                // For now we use the fallback point\n                if (in_box(*previous, *it, turn.robust_point))\n                {\n                    return 0;\n                }\n                else\n                {\n                    return -1; // outside\n                }\n            }\n        }\n        return 1; // inside\n    }\n#endif\n\n\npublic:\n\n    inline turn_in_piece_visitor(Turns& turns, Pieces const& pieces)\n        : m_turns(turns)\n        , m_pieces(pieces)\n    {}\n\n    template <typename Turn, typename Piece>\n    inline bool apply(Turn const& turn, Piece const& piece, bool first = true)\n    {\n        boost::ignore_unused_variable_warning(first);\n\n        if (turn.count_within > 0)\n        {\n            // Already inside - no need to check again\n            return true;\n        }\n\n        if (piece.type == strategy::buffer::buffered_flat_end\n            || piece.type == strategy::buffer::buffered_concave)\n        {\n            // Turns cannot be located within flat-end or concave pieces\n            return true;\n        }\n\n        if (! geometry::covered_by(turn.robust_point, piece.robust_envelope))\n        {\n            // Easy check: if the turn is not in the envelope, we can safely return\n            return true;\n        }\n\n        if (skip(turn.operations[0], piece) || skip(turn.operations[1], piece))\n        {\n            return true;\n        }\n\n        // TODO: mutable_piece to make some on-demand preparations in analyse\n        Turn& mutable_turn = m_turns[turn.turn_index];\n\n        if (piece.type == geometry::strategy::buffer::buffered_point)\n        {\n            // Optimization for buffer around points: if distance from center\n            // is not between min/max radius, the result is clear\n            typedef typename default_comparable_distance_result\n                <\n                    typename Turn::robust_point_type\n                >::type distance_type;\n\n            distance_type const cd\n                = geometry::comparable_distance(piece.robust_center,\n                        turn.robust_point);\n\n            if (cd < piece.robust_min_comparable_radius)\n            {\n                mutable_turn.count_within++;\n                return true;\n            }\n            if (cd > piece.robust_max_comparable_radius)\n            {\n                return true;\n            }\n        }\n\n        analyse_result analyse_code =\n            piece.type == geometry::strategy::buffer::buffered_point\n                ? analyse_turn_wrt_point_piece::apply(turn, piece)\n                : analyse_turn_wrt_piece::apply(turn, piece);\n\n        switch(analyse_code)\n        {\n            case analyse_disjoint :\n                return true;\n            case analyse_on_offsetted :\n                mutable_turn.count_on_offsetted++; // value is not used anymore\n                return true;\n            case analyse_on_original_boundary :\n                mutable_turn.count_on_original_boundary++;\n                return true;\n            case analyse_within :\n                mutable_turn.count_within++;\n                return true;\n#if ! defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n            case analyse_near_offsetted :\n                mutable_turn.count_within_near_offsetted++;\n                return true;\n#endif\n            default :\n                break;\n        }\n\n#if defined(BOOST_GEOMETRY_BUFFER_USE_SIDE_OF_INTERSECTION)\n        // We don't know (yet)\n        int geometry_code = 0;\n        if (piece.is_convex)\n        {\n            geometry_code = turn_in_convex_piece(turn, piece);\n        }\n        else\n        {\n\n            // TODO: this point_in_geometry is a performance-bottleneck here and\n            // will be replaced completely by extending analyse_piece functionality\n            geometry_code = detail::within::point_in_geometry(turn.robust_point, piece.robust_ring);\n        }\n#else\n        int geometry_code = detail::within::point_in_geometry(turn.robust_point, piece.robust_ring);\n#endif\n\n        if (geometry_code == 1)\n        {\n            mutable_turn.count_within++;\n        }\n\n        return true;\n    }\n};\n\n\n}} // namespace detail::buffer\n#endif // DOXYGEN_NO_DETAIL\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR\n", "meta": {"hexsha": "29e49f9dae375a64fe795024c6e2ee0371c61bf8", "size": 27661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tether/boost/geometry/algorithms/detail/buffer/turn_in_piece_visitor.hpp", "max_stars_repo_name": "fictheader/fcolorwheel", "max_stars_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 918.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T02:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:21:35.000Z", "max_issues_repo_path": "tether/boost/geometry/algorithms/detail/buffer/turn_in_piece_visitor.hpp", "max_issues_repo_name": "fictheader/fcolorwheel", "max_issues_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 203.0, "max_issues_repo_issues_event_min_datetime": "2016-12-27T12:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:46:55.000Z", "max_forks_repo_path": "tether/boost/geometry/algorithms/detail/buffer/turn_in_piece_visitor.hpp", "max_forks_repo_name": "fictheader/fcolorwheel", "max_forks_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T17:38:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T14:25:49.000Z", "avg_line_length": 33.6508515815, "max_line_length": 110, "alphanum_fraction": 0.5729727776, "num_tokens": 5778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.18483966707976987}}
{"text": "/**\n * Copyright (c) 2017 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 <boost/utility/in_place_factory.hpp>\n\n#include <ogr_spatialref.h>\n#include <cpl_conv.h>\n\n#include \"dbglog/dbglog.hpp\"\n\n#include \"utility/streams.hpp\"\n\n#include \"srsdef.hpp\"\n#include \"srs.hpp\"\n#include \"enu.hpp\"\n#include \"csconvertor.hpp\"\n\nnamespace geo {\n\nEnu::Enu(const math::Point3 &origin, const SrsDefinition &srs)\n{\n    auto geog(srs.reference());\n    auto o(origin);\n\n    if (!geog.IsGeographic()) {\n        // extract geographic ref from this srs\n        ::OGRSpatialReference tmp;\n        if (tmp.CopyGeogCSFrom(&geog) != OGRERR_NONE) {\n            LOGTHROW(err1, std::runtime_error)\n                << \"Could not extract geographic SRS from definition \\\"\"\n                << srs << \"\\\".\";\n        }\n\n        // convert origin\n        const CsConvertor conv(geog, tmp);\n        o = conv(o);\n    }\n\n    // construct ENU from geographic system's spheroid and origin\n    lon0 = o(0);\n    lat0 = o(1);\n    h0 = o(2);\n\n    // TODO: check for WGS84 and do not set following\n    spheroid = boost::in_place(geog.GetSemiMajor(), geog.GetSemiMinor());\n    towgs84.resize(7);\n    geog.GetTOWGS84(towgs84.data(), int(towgs84.size()));\n}\n\n} // namespace geo\n", "meta": {"hexsha": "04195abe387cafc165a909acdf0d7631727d5c1a", "size": 2525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geo/enu.cpp", "max_stars_repo_name": "ExploreWilder/libgeo", "max_stars_repo_head_hexsha": "118ba7f527cbfb5fc6b600495208c1c7d4178414", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-17T11:47:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-17T11:47:27.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/libgeo/geo/enu.cpp", "max_issues_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_issues_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-07T03:37:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T03:33:51.000Z", "max_forks_repo_path": "externals/browser/externals/browser/externals/libgeo/geo/enu.cpp", "max_forks_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_forks_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:22:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T14:10:03.000Z", "avg_line_length": 34.1216216216, "max_line_length": 78, "alphanum_fraction": 0.699009901, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.1848396547934426}}
{"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_CORE_FUNCTIONS_SIMD_INNER_FOLD_HPP_INCLUDED\n#define NT2_CORE_FUNCTIONS_SIMD_INNER_FOLD_HPP_INCLUDED\n\n#include <nt2/core/functions/inner_fold.hpp>\n#include <nt2/core/functions/details/fold_step.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/simd/sdk/simd/meta/is_vectorizable.hpp>\n\n\n#ifndef BOOST_SIMD_NO_SIMD\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  // General inner_fold\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT_IF   ( inner_fold_, boost::simd::tag::simd_\n                                , (Out)(In)(Neutral)(Bop)(Uop)\n                                , ( boost::simd::meta::\n                                    is_vectorizable < typename Out::value_type\n                                                    , BOOST_SIMD_DEFAULT_EXTENSION\n                                                    >\n                                  )\n                                , ((ast_< Out, nt2::container::domain>))\n                                  ((ast_< In, nt2::container::domain>))\n                                  (unspecified_<Neutral>)\n                                  (unspecified_<Bop>)\n                                  (unspecified_<Uop>)\n                                )\n  {\n    typedef void                                                              result_type;\n    typedef typename Out::value_type                                           value_type;\n    typedef typename In::extent_type                                          extent_type;\n    typedef boost::simd::native<value_type,BOOST_SIMD_DEFAULT_EXTENSION>      target_type;\n\n    BOOST_FORCEINLINE result_type\n    operator()(Out& out, In& in\n              , Neutral const& neutral, Bop const& bop, Uop const& uop\n              ) const\n    {\n      extent_type ext = in.extent();\n      std::size_t obound = nt2::numel(boost::fusion::pop_front(ext));\n      static const std::size_t N = boost::simd::meta::cardinal_of<target_type>::value;\n      std::size_t bound  = boost::fusion::at_c<0>(ext);\n      std::size_t nb_vec = (bound/N);\n      std::size_t ibound = nb_vec * N;\n\n      for(std::size_t j = 0, k = 0; j != obound; ++j, k+=bound)\n      {\n        target_type vec_out = details::fold_step(\n          neutral(nt2::meta::as_<target_type>()), in, bop, k, nb_vec, N\n        );\n\n        value_type s_out = uop( vec_out );\n        s_out = details::fold_step(s_out, in, bop, k+ibound, bound-ibound, 1);\n\n        nt2::run(out, j, s_out);\n      }\n    }\n  };\n} }\n\n#endif\n#endif\n", "meta": {"hexsha": "b261642c10fdf6b905bc116ae83aee71ee479f9a", "size": 3113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/reduction/include/nt2/core/functions/simd/inner_fold.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/reduction/include/nt2/core/functions/simd/inner_fold.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/reduction/include/nt2/core/functions/simd/inner_fold.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": 42.6438356164, "max_line_length": 90, "alphanum_fraction": 0.4667523289, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.1848326447995416}}
{"text": "// Copyright (c) 2019-2020, CNRS\n// Authors: Pierre Fernbach <pierre.fernbach@laas.fr>,\n\n#include <iostream>\n\n#define BOOST_TEST_MODULE StatsTests\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\n#include \"multicontact-api/scenario/contact-sequence.hpp\"\n#include \"multicontact-api/scenario/fwd.hpp\"\n#include \"curves/fwd.h\"\n#include <curves/so3_linear.h>\n#include <curves/se3_curve.h>\n#include <curves/polynomial.h>\n#include <curves/bezier_curve.h>\n#include <curves/piecewise_curve.h>\n#include <curves/exact_cubic.h>\n#include <curves/cubic_hermite_spline.h>\n\n/**\n * This unit test try to deserialize the ContactSequences in the examples/previous_versions folder\n * And check that they are compatible with the current version\n */\n\nusing namespace multicontact_api::scenario;\n\nconst std::string path = TEST_DATA_PATH;\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(api_0) {\n  ContactSequence cs;\n  cs.loadFromBinary(path + \"previous_versions/api_0.cs\");\n  BOOST_CHECK_EQUAL(cs.size(), 9);\n  BOOST_CHECK(cs.haveConsistentContacts());\n  BOOST_CHECK(cs.haveTimings());\n  BOOST_CHECK(cs.haveCentroidalValues());\n  BOOST_CHECK(cs.haveCentroidalTrajectories());\n  BOOST_CHECK(cs.haveEffectorsTrajectories(1e-1));\n  BOOST_CHECK(cs.haveJointsTrajectories());\n  BOOST_CHECK(cs.haveJointsDerivativesTrajectories());\n  BOOST_CHECK(cs.haveContactForcesTrajectories());\n  BOOST_CHECK(cs.haveZMPtrajectories());\n  BOOST_CHECK(cs.haveFriction());\n  BOOST_CHECK(!cs.haveContactModelDefined());\n}\n\nBOOST_AUTO_TEST_CASE(api_1) {\n  ContactSequence cs;\n  cs.loadFromBinary(path + \"previous_versions/api_1.cs\");\n  BOOST_CHECK_EQUAL(cs.size(), 9);\n  BOOST_CHECK(cs.haveConsistentContacts());\n  BOOST_CHECK(cs.haveTimings());\n  BOOST_CHECK(cs.haveCentroidalValues());\n  BOOST_CHECK(cs.haveCentroidalTrajectories());\n  BOOST_CHECK(cs.haveEffectorsTrajectories(1e-1));\n  BOOST_CHECK(cs.haveJointsTrajectories());\n  BOOST_CHECK(cs.haveJointsDerivativesTrajectories());\n  BOOST_CHECK(cs.haveContactForcesTrajectories());\n  BOOST_CHECK(cs.haveZMPtrajectories());\n  BOOST_CHECK(cs.haveFriction());\n  BOOST_CHECK(cs.haveContactModelDefined());\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ef6a935fdf287377559ddaff89fe9a8c1645eec5", "size": 2183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/serialization_versionning.cpp", "max_stars_repo_name": "proyan/multicontact-api", "max_stars_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "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": "unittest/serialization_versionning.cpp", "max_issues_repo_name": "proyan/multicontact-api", "max_issues_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "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": "unittest/serialization_versionning.cpp", "max_forks_repo_name": "proyan/multicontact-api", "max_forks_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "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.5820895522, "max_line_length": 98, "alphanum_fraction": 0.7856161246, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18483264299556632}}
{"text": "#pragma once\n\n#include <atomic>\n#include <condition_variable>\n#include <map>\n#include <mutex>\n#include <optional>\n#include <variant>\n\n#include <boost/asio/steady_timer.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <koinos/block_production/block_producer.hpp>\n#include <koinos/contracts/pow/pow.pb.h>\n\nnamespace koinos::block_production {\n\nusing boost::multiprecision::uint512_t;\nusing boost::multiprecision::uint256_t;\n\nusing worker_group_type = std::pair< uint256_t, uint256_t >;\nusing hash_count_type   = std::atomic< uint64_t >;\nusing contract_id_type  = std::string;\n\nclass pow_producer : public block_producer\n{\npublic:\n   pow_producer(\n      crypto::private_key signing_key,\n      boost::asio::io_context& main_context,\n      boost::asio::io_context& production_context,\n      std::shared_ptr< mq::client > rpc_client,\n      int64_t production_threshold,\n      uint64_t resources_lower_bound,\n      uint64_t resources_upper_bound,\n      uint64_t max_inclusion_attempts,\n      contract_id_type pow_contract_id,\n      std::size_t worker_groups\n   );\n   ~pow_producer();\n\n   virtual void on_block_accept( const protocol::block& b ) override;\n\nprotected:\n   void commence() override;\n   void halt() override;\n\nprivate:\n   std::map< std::size_t, hash_count_type >      _worker_hashrate;\n   std::vector< worker_group_type >              _worker_groups;\n   std::mutex                                    _cv_mutex;\n   std::condition_variable                       _cv;\n   boost::asio::steady_timer                     _update_timer;\n   uint64_t                                      _last_known_height = 0;\n   boost::asio::steady_timer                     _error_timer;\n   std::atomic< std::chrono::seconds >           _error_wait_time = std::chrono::seconds( 5 );\n   std::atomic< bool >                           _hashing;\n   const contract_id_type                        _pow_contract_id;\n   const std::size_t                             _num_worker_groups;\n\n   void produce( const boost::system::error_code& ec );\n   void display_hashrate( const boost::system::error_code& ec );\n   void find_nonce(\n      std::size_t worker_index,\n      const protocol::block& block,\n      uint256_t difficulty,\n      uint256_t start,\n      uint256_t end,\n      std::shared_ptr< std::optional< uint256_t > > nonce,\n      std::shared_ptr< std::atomic< bool > > done\n   );\n   bool target_met( const crypto::multihash& hash, uint256_t target );\n   contracts::pow::difficulty_metadata get_difficulty_meta();\n   std::string hashrate_to_string( double hashrate );\n   std::string compute_network_hashrate( const contracts::pow::difficulty_metadata& meta );\n};\n\n} // koinos::block_production\n", "meta": {"hexsha": "6f13d2fd574c37ffa848f96b68017b4e95982c7f", "size": 2680, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/block_production/include/koinos/block_production/pow_producer.hpp", "max_stars_repo_name": "koinos/koinos-block-producer", "max_stars_repo_head_hexsha": "b6b15542e0f02fc97119920ab6b0d76dbfd3d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T08:45:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T08:45:26.000Z", "max_issues_repo_path": "libraries/block_production/include/koinos/block_production/pow_producer.hpp", "max_issues_repo_name": "koinos/koinos-block-producer", "max_issues_repo_head_hexsha": "b6b15542e0f02fc97119920ab6b0d76dbfd3d6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2021-04-27T06:49:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T23:48:31.000Z", "max_forks_repo_path": "libraries/block_production/include/koinos/block_production/pow_producer.hpp", "max_forks_repo_name": "koinos/koinos-block-producer", "max_forks_repo_head_hexsha": "b6b15542e0f02fc97119920ab6b0d76dbfd3d6a8", "max_forks_repo_licenses": ["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.9240506329, "max_line_length": 94, "alphanum_fraction": 0.6667910448, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.18483263944688974}}
{"text": "/*******************************************************\n *\n * Copyright (C) 2022, Chen Jianqu, Shanghai University\n *\n * This file is part of detector_desktop.\n *\n * Licensed under the MIT License;\n * you may not use this file except in compliance with the License.\n *******************************************************/\n#include \"detector_desktop/Arm.h\"\n#include <iostream>\n#include <thread>\n#include <Eigen/Core>\n#include <opencv2/core/eigen.hpp>\n#include <pcl/point_cloud.h>\n#include <std_msgs/Header.h>\n#include <geometry_msgs/Pose.h>\n#include <tf_conversions/tf_eigen.h>\n\n\nusing namespace std;\n\nArm::Arm(ros::NodeHandle* np_){\n    arm_client.reset(new ArmClient(*np_, Config::kKinovaPoseActionAddress, true));\n    finger_client.reset(new FingerClient(*np_, Config::kKinovaFingerActionAddress, true));\n    transform_listener.reset(new tf::TransformListener);\n    transform_broadcaster.reset(new tf::TransformBroadcaster);\n    cv::cv2eigen(Config::kCamToArm, Tca.matrix());\n    Eigen::AngleAxisd yawAngle(Config::kGraspPoseEuler.at<double>(0, 0), Eigen::Vector3d::UnitZ());\n    Eigen::AngleAxisd pitchAngle(Config::kGraspPoseEuler.at<double>(1, 0), Eigen::Vector3d::UnitY());\n    Eigen::AngleAxisd rollAngle(Config::kGraspPoseEuler.at<double>(2, 0), Eigen::Vector3d::UnitX());\n    grasp_q=yawAngle*pitchAngle*rollAngle; //\u5148\u7ed5z\u65cb\u8f6cyaw,\u518d\u7ed5y\u65cb\u8f6cpitch\uff0c\u6700\u540e\u7ed5x\u65cb\u8f6croll\n}\n\n\nvoid Arm::GetGraspPose(Instance &inst, geometry_msgs::Pose &pose)\n{\n    Eigen::Quaterniond q;\n\n    //\u6293\u53d6\u7684\u4f4d\u7f6e\u5e94\u8be5\u662f,\u6839\u636e\u673a\u68b0\u81c2\u7684\u5b89\u88c5\u4f4d\u7f6e\uff0cx z\u8f74\u5747\u4e3a\u4e2d\u5fc3\u70b9\uff0c\u7269\u4f53\u7684y\u8f74\u4e3a\u8d1f\u7684\uff0c\u56e0\u6b64\u9700\u8981+y_half\n    auto minPt=inst.minPt;\n    auto maxPt=inst.maxPt;\n    float y_half_len=std::abs(std::abs(minPt.y)-std::abs(maxPt.y))/2.0f;//\u534a\u5f84\n    float z_half_len=std::abs(std::abs(minPt.z)-std::abs(maxPt.z))/2.0f;//\u534a\u5f84\n    Eigen::Vector3d center((minPt.x+maxPt.x)/2,(minPt.y+maxPt.y)/2,(minPt.z+maxPt.z)/2); //\u70b9\u4e91\u4e2d\u5fc3\u70b9\n    pose.position.x=center.x();\n    pose.position.y=center.y();//y_half_len+0.02f;//0.02f\u4e3a\u4f59\u91cf\n    pose.position.z=center.z()+z_half_len;\n\n    //\u6293\u53d6\u65b9\u5411\u8bbe\u7f6e:\u4f7f\u7528\u9884\u5148\u5b9a\u4e49\u7684\u65b9\u5411\n    pose.orientation.x=grasp_q.x();\n    pose.orientation.y=grasp_q.y();\n    pose.orientation.z=grasp_q.z();\n    pose.orientation.w=grasp_q.w();\n}\n\n//\u53d1\u5e03\u6293\u53d6\u4f4d\u7f6e\u7684tf\uff0c\u7528\u4e8e\u53ef\u89c6\u5316\nvoid Arm::BroadcastGraspPose(const geometry_msgs::Pose &pose)\n{\n    tf::Transform Ttf;\n    tf::Quaternion q;\n    q.setX(pose.orientation.x);\n    q.setY(pose.orientation.y);\n    q.setZ(pose.orientation.z);\n    q.setW(pose.orientation.w);\n    Ttf.setRotation(q);\n\n    tf::Vector3 v;\n    v.setX(pose.position.x);\n    v.setY(pose.position.y);\n    v.setZ(pose.position.z);\n    Ttf.setOrigin(v);\n\n    transform_broadcaster->sendTransform(\n            tf::StampedTransform(Ttf, ros::Time::now(),\n                                 \"j2n6s300_link_base\", \"grasp_target_frame\"));\n}\n\n\nbool Arm::SetFinger(float value){\n    kinova_msgs::SetFingersPositionGoal goalFinger;\n    goalFinger.fingers.finger1=value;//6120\u662f%90\u7684\u95ed\u5408\uff0c0\u662f\u5f20\u5230\u6700\u5927\u7684\u72b6\u6001\n    goalFinger.fingers.finger2=value;\n    goalFinger.fingers.finger3=value;\n    finger_client->sendGoal(goalFinger);\n\n    if(!finger_client->waitForResult(ros::Duration(5.0))){\n        Debugt(\"fingerClient \u8d85\u65f6\");\n        return false;\n    }\n    if(finger_client->getState() != actionlib::SimpleClientGoalState::SUCCEEDED){\n        Debugt(\"fingerClient \u5931\u8d25,State:{}\",finger_client->getState().toString());\n        return false;\n    }\n    return true;\n}\n\n\nbool Arm::SetArmPose(geometry_msgs::Pose &pose)\n{\n    //\u8bbe\u7f6e\u76ee\u6807\n    kinova_msgs::ArmPoseGoal goalArm;\n    goalArm.pose.header.frame_id=Config::kArmMsgFrame;\n    goalArm.pose.pose=pose;\n    arm_client->sendGoal(goalArm);\n\n    if(!arm_client->waitForResult(ros::Duration(10.0))){\n        Debugt(\"armClient \u8d85\u65f6\");\n        return false;\n    }\n    if(arm_client->getState() != actionlib::SimpleClientGoalState::SUCCEEDED){\n        Debugt(\"armClient \u5931\u8d25,State:{}\",arm_client->getState().toString());\n        return false;\n    }\n    return true;\n}\n\n\n\nbool Arm::Run(Instance inst)\n{\n    if(inst.pc->empty()){\n        Debugt(\"instance\u672a\u6784\u5efa\");\n        return false;\n    }\n\n    //\u6293\u53d6\u70b9\u7684\u8bbe\u7f6e\n    geometry_msgs::Pose target_pose,pose;\n    GetGraspPose(inst, target_pose);\n    Debugt(\"\u6293\u53d6\u76ee\u6807\u7684\u4e09\u7ef4\u4f4d\u7f6e\uff1a({},{},{})\",target_pose.position.x,target_pose.position.y,target_pose.position.z);\n    BroadcastGraspPose(target_pose);\n    Debugt(\"Wait Action Server...\");\n    arm_client->waitForServer();\n    finger_client->waitForServer();\n    if(!SetFinger(0)) //\u6253\u5f00\u624b\u6307\n        return false;\n    std::this_thread::sleep_for(500ms);//\u4f11\u7720\n    pose=target_pose;\n    pose.position.z +=0.1;\n    if(!SetArmPose(pose)) //\u5148\u5230\u8fbe\u76ee\u6807\u4e0a\u65b9\n        return false;\n    pose.position.z -=0.1;\n    if(!SetArmPose(pose)) //\u5230\u8fbe\u76ee\u6807\u6240\u5728\u7684\u4f4d\u7f6e\n        return false;\n    std::this_thread::sleep_for(500ms);\n    if(!SetFinger(Config::kArmFingerValue)) //\u5173\u95ed\u624b\u6307\uff0c\u6293\u53d6\n        return false;\n    std::this_thread::sleep_for(500ms);\n    Debugt(\"\u5df2\u6293\u53d6\u7269\u4f53 \u5f80\u56de\u8fd0\u52a8\");\n    pose.position.z+=0.1; //\u5f80\u4e0a0.2m\n    if(!SetArmPose(pose))\n        return false;\n    pose.position.x+=0.1; //\u5f80\u5de60.1m\n    if(!SetArmPose(pose))\n        return false;\n    Debugt(\"\u6293\u53d6\u7ebf\u7a0b\u5b8c\u6210\");\n    return true;\n}\n\n\n//\u4f7f\u7528future\u7684\u65b9\u5f0f\u5224\u65ad\u7a0b\u5e8f\u673a\u68b0\u81c2\u662f\u5426\u6b63\u5728\u8fd0\u884c\n//\u8fd9\u79cd\u65b9\u6cd5\u867d\u7136\u4e0d\u662f\u5f88\u76f4\u89c2\nbool Arm::TryRunArm(Instance &inst) {\n    if(!is_arm_running.valid()){ //\u7b2c\u4e00\u6b21\u8fd0\u884c\u673a\u68b0\u81c2\u6216\u7ed3\u679c\u5df2\u4ecefuture\u4e2d\u53d6\u51fa\n        is_arm_running=std::async(std::launch::async, &Arm::Run, this, inst);//\u7acb\u5373\u542f\u52a8\n        return true;\n    }\n    else{\n        if(is_arm_running.wait_for(std::chrono::milliseconds(1)) == std::future_status::ready){\n            Debugt(\"\u524d\u4e00\u6b21\u673a\u68b0\u81c2\u6267\u884c\u7ed3\u679c:{}\",(is_arm_running.get() ? \"\u6210\u529f\" : \"\u5931\u8d25\"));\n            is_arm_running=std::async(std::launch::async, &Arm::Run, this, inst);\n            return true;\n        }\n        else{\n            return false;\n        }\n    }\n}\n\n", "meta": {"hexsha": "80c24fcee590c397fcc41cd065731c1274e7853b", "size": 5597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Arm.cpp", "max_stars_repo_name": "chenjianqu/detector_desktop", "max_stars_repo_head_hexsha": "6fc3aa5f09f5c32e3c23a59360d10fea7e2b4e77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-13T03:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T07:42:08.000Z", "max_issues_repo_path": "src/Arm.cpp", "max_issues_repo_name": "chenjianqu/detector_desktop", "max_issues_repo_head_hexsha": "6fc3aa5f09f5c32e3c23a59360d10fea7e2b4e77", "max_issues_repo_licenses": ["MIT"], "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/Arm.cpp", "max_forks_repo_name": "chenjianqu/detector_desktop", "max_forks_repo_head_hexsha": "6fc3aa5f09f5c32e3c23a59360d10fea7e2b4e77", "max_forks_repo_licenses": ["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.0944444444, "max_line_length": 104, "alphanum_fraction": 0.6519564052, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1848326358982131}}
{"text": "#ifndef INCLUDE_SWIFT_VIO_POINT_SHARED_DATA_HPP_\n#define INCLUDE_SWIFT_VIO_POINT_SHARED_DATA_HPP_\n\n#include <memory>\n#include <unordered_map>\n#include <Eigen/StdVector>\n\n#include <swift_vio/VectorOperations.hpp>\n#include <okvis/FrameTypedefs.hpp>\n\n#include <okvis/Measurements.hpp>\n#include <okvis/Parameters.hpp>\n#include <okvis/ceres/PoseParameterBlock.hpp>\n\nnamespace swift_vio {\n// The state info for one keypoint relevant to computing the pose (T_WB) and\n// (linear and angular) velocity (v_WB, omega_WB_B) at keypoint observation epoch.\nstruct StateInfoForOneKeypoint {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    StateInfoForOneKeypoint() {\n\n    }\n    StateInfoForOneKeypoint(\n        uint64_t _frameId, size_t _camIdx,\n        std::shared_ptr<const okvis::ceres::ParameterBlock> T_WB_ptr,\n        double _normalizedRow, okvis::Time imageStamp)\n        : frameId(_frameId),\n          cameraId(_camIdx),\n          T_WBj_ptr(T_WB_ptr),\n          normalizedRow(_normalizedRow),\n          imageTimestamp(imageStamp) {}\n\n    uint64_t frameId;\n    size_t cameraId;\n    std::shared_ptr<const okvis::ceres::ParameterBlock> T_WBj_ptr;\n    std::shared_ptr<const okvis::ceres::ParameterBlock> speedAndBiasPtr;\n    // IMU measurements covering the state epoch.\n    std::shared_ptr<const okvis::ImuMeasurementDeque> imuMeasurementPtr;\n    okvis::Time stateEpoch;\n    double normalizedRow; // v / imageHeight - 0.5.\n    okvis::Time imageTimestamp; // raw image frame timestamp may be different for cameras in NFrame.\n    // linearization points at the state.\n    std::shared_ptr<const Eigen::Matrix<double, 6, 1>> positionVelocityPtr;\n    // Pose of the body frame in the world frame at the feature observation epoch.\n    // It should be computed with IMU propagation for RS cameras.\n    okvis::kinematics::Transformation T_WBtij;\n    Eigen::Vector3d v_WBtij;\n    Eigen::Vector3d omega_Btij;\n    okvis::kinematics::Transformation  T_WBtij_fej;\n    Eigen::Vector3d v_WBtij_fej;\n};\n\nenum class PointSharedDataState {\n  Barebones = 0,\n  ImuInfoReady = 1,\n  NavStateReady = 2,\n  NavStateForJacReady = 3,\n};\n\n// Data shared by observations of a point landmark in computing Jacobians\n// relative to pose (T_WB) and velocity (v_WB) and camera time parameters.\n// The data of the class members may be updated in ceres EvaluationCallback.\nclass PointSharedData {\n public:\n  typedef std::vector<StateInfoForOneKeypoint,\n                      Eigen::aligned_allocator<StateInfoForOneKeypoint>>\n      StateInfoForObservationsType;\n\n  PointSharedData() : status_(PointSharedDataState::Barebones) {}\n\n  void addKeypointObservation(\n      const okvis::KeypointIdentifier& kpi,\n      std::shared_ptr<const okvis::ceres::ParameterBlock> T_WBj_ptr,\n      double normalizedRow, okvis::Time imageTimestamp) {\n    stateInfoForObservations_.emplace_back(kpi.frameId, kpi.cameraIndex,\n                                           T_WBj_ptr, normalizedRow, imageTimestamp);\n  }\n\n  /// @name Setters for data for IMU propagation.\n  /// @{\n  void setVelocityParameterBlockPtr(\n      int index,\n      std::shared_ptr<const okvis::ceres::ParameterBlock> speedAndBiasPtr) {\n    stateInfoForObservations_[index].speedAndBiasPtr = speedAndBiasPtr;\n  }\n\n  void setImuInfo(\n      int index, const okvis::Time stateEpoch,\n      std::shared_ptr<const okvis::ImuMeasurementDeque> imuMeasurements,\n      std::shared_ptr<const Eigen::Matrix<double, 6, 1>> positionVelocityPtr) {\n    stateInfoForObservations_[index].stateEpoch = stateEpoch;\n    stateInfoForObservations_[index].imuMeasurementPtr = imuMeasurements;\n    stateInfoForObservations_[index].positionVelocityPtr = positionVelocityPtr;\n  }\n\n  void setImuAugmentedParameterPtrs(\n      const std::vector<std::shared_ptr<const okvis::ceres::ParameterBlock>>&\n          imuAugmentedParamBlockPtrs,\n      const okvis::ImuParameters* imuParams) {\n    imuAugmentedParamBlockPtrs_ = imuAugmentedParamBlockPtrs;\n    imuParameters_ = imuParams;\n  }\n\n  void setCameraTimeParameterPtrs(\n      const std::vector<std::shared_ptr<const okvis::ceres::ParameterBlock>>&\n          tdParamBlockPtrs,\n      const std::vector<std::shared_ptr<const okvis::ceres::ParameterBlock>>&\n          trParamBlockPtrs) {\n    tdParamBlockPtrs_ = tdParamBlockPtrs;\n    trParamBlockPtrs_ = trParamBlockPtrs;\n    status_ = PointSharedDataState::ImuInfoReady;\n  }\n  /// @}\n\n  /// @name functions for IMU propagation.\n  /// @{\n  /**\n   * @brief computePoseAndVelocityAtObservation.\n   *     for feature i, estimate $p_B^G(t_{f_i})$, $R_B^G(t_{f_i})$,\n   *     $v_B^G(t_{f_i})$, and $\\omega_{GB}^B(t_{f_i})$ with the corresponding\n   *     states' LATEST ESTIMATES and imu measurements.\n   * @warning Call this function after setImuAugmentedParameterPtrs().\n   */\n  void computePoseAndVelocityAtObservation();\n\n  /**\n   * @brief computePoseAndVelocityForJacobians\n   * @warning Only call this function after\n   * computePoseAndVelocityAtObservation() has finished.\n   * @param useLinearizationPoint\n   */\n  void computePoseAndVelocityForJacobians(bool useLinearizationPoint);\n  /// @}\n\n  /**\n   * @brief computeSharedJacobians compute Jacobians common to every\n   * observation of the landmark.\n   * @param cameraObservationModelId\n   */\n  void computeSharedJacobians(int cameraObservationModelId);\n\n  /// @name Functions for anchors.\n  /// @{\n  void setAnchors(const std::vector<AnchorFrameIdentifier>& anchorIds) {\n    anchorIds_ = anchorIds;    \n  }\n\n  const std::vector<AnchorFrameIdentifier>& anchorIds() const {\n    return anchorIds_;\n  }\n\n  /**\n   * @brief Get index of observations from the anchor frames in the observation sequence.\n   * @warning This only support a monocular camera.\n   * @return\n   */\n  std::vector<int> anchorObservationIds() const;\n\n  okvis::kinematics::Transformation T_WB_mainAnchor() const {\n    return stateInfoForObservations_[anchorIds_[0].observationIndex_].T_WBtij;\n  }\n\n  okvis::kinematics::Transformation T_WB_mainAnchorForJacobian(bool useFirstEstimate) const {\n    if (useFirstEstimate)\n      return stateInfoForObservations_[anchorIds_[0].observationIndex_].T_WBtij_fej;\n    else\n      return T_WB_mainAnchor();\n  }\n\n  okvis::kinematics::Transformation T_WB_mainAnchorStateEpoch() const {\n    const StateInfoForOneKeypoint& mainAnchorItem =\n        stateInfoForObservations_.at(anchorIds_[0].observationIndex_);\n    return std::static_pointer_cast<const okvis::ceres::PoseParameterBlock>(\n            mainAnchorItem.T_WBj_ptr)\n            ->estimate();\n  }\n\n  okvis::kinematics::Transformation T_WB_mainAnchorStateEpochForJacobian(\n      bool useFirstEstimate) const {\n    const StateInfoForOneKeypoint& mainAnchorItem =\n        stateInfoForObservations_.at(anchorIds_[0].observationIndex_);\n    okvis::kinematics::Transformation T_WB_fej =\n        std::static_pointer_cast<const okvis::ceres::PoseParameterBlock>(\n            mainAnchorItem.T_WBj_ptr)\n            ->estimate();\n    if (useFirstEstimate) {\n      std::shared_ptr<const Eigen::Matrix<double, 6, 1>>\n          posVelFirstEstimatePtr = mainAnchorItem.positionVelocityPtr;\n      T_WB_fej = okvis::kinematics::Transformation(\n          posVelFirstEstimatePtr->head<3>(), T_WB_fej.q());\n    }\n    return T_WB_fej;\n  }\n  /// @}\n\n  /// @name functions for managing the main stateInfo list.\n  /// @{\n  StateInfoForObservationsType::iterator begin() {\n    return stateInfoForObservations_.begin();\n  }\n\n  StateInfoForObservationsType::iterator end() {\n      return stateInfoForObservations_.end();\n  }\n\n  void removeBadObservations(const std::vector<bool>& projectStatus) {\n      removeUnsetMatrices<StateInfoForOneKeypoint>(&stateInfoForObservations_, projectStatus);\n  }\n\n  /**\n   * @brief removeExtraObservations\n   * @warning orderedSelectedFrameIds must be a subsets of stateInfoForObservations_\n   * @param orderedSelectedFrameIds\n   * @param imageNoise2dStdList\n   */\n  void removeExtraObservations(const std::vector<uint64_t>& orderedSelectedFrameIds,\n                               std::vector<double>* imageNoise2dStdList);\n\n  void removeExtraObservationsLegacy(\n      const std::vector<uint64_t>& orderedSelectedFrameIds,\n      std::vector<double>* imageNoise2dStdList);\n  /// @}\n\n  /// @name Getters for frameIds.\n  /// @{\n  size_t numObservations() const {\n      return stateInfoForObservations_.size();\n  }\n\n  std::vector<std::pair<uint64_t, size_t>> frameIds() const {\n    std::vector<std::pair<uint64_t, size_t>> frameIds;\n    frameIds.reserve(stateInfoForObservations_.size());\n    for (auto item : stateInfoForObservations_) {\n      frameIds.emplace_back(item.frameId, item.cameraId);\n    }\n    return frameIds;\n  }\n\n  uint64_t frameId(int index) const {\n    return stateInfoForObservations_[index].frameId;\n  }\n\n  uint64_t lastFrameId() const {\n    return stateInfoForObservations_.back().frameId;\n  }\n  /// @}\n\n  /// @name Getters\n  /// @{\n  double normalizedFeatureTime(int observationIndex) const {\n    return normalizedFeatureTime(stateInfoForObservations_[observationIndex]);\n  }\n\n  double normalizedFeatureTime(const StateInfoForOneKeypoint& item) const {\n    size_t cameraIdx = item.cameraId;\n    return tdParamBlockPtrs_[cameraIdx]->parameters()[0] +\n           trParamBlockPtrs_[cameraIdx]->parameters()[0] * item.normalizedRow +\n        (item.imageTimestamp - item.stateEpoch).toSec();\n  }\n\n  size_t cameraIndex(size_t observationIndex) const {\n    return stateInfoForObservations_[observationIndex].cameraId;\n  }\n\n  double normalizedRow(int index) const {\n    return stateInfoForObservations_[index].normalizedRow;\n  }\n\n  std::vector<okvis::kinematics::Transformation,\n              Eigen::aligned_allocator<okvis::kinematics::Transformation>>\n  poseAtObservationList() const {\n    std::vector<okvis::kinematics::Transformation,\n                Eigen::aligned_allocator<okvis::kinematics::Transformation>>\n        T_WBtij_list;\n    T_WBtij_list.reserve(stateInfoForObservations_.size());\n    for (auto item : stateInfoForObservations_) {\n      T_WBtij_list.push_back(item.T_WBtij);\n    }\n    return T_WBtij_list;\n  }\n\n  std::vector<size_t> cameraIndexList() const {\n    std::vector<size_t> camIndices;\n    camIndices.reserve(stateInfoForObservations_.size());\n    for (auto item : stateInfoForObservations_) {\n      camIndices.push_back(item.cameraId);\n    }\n    return camIndices;\n  }\n\n  void poseAtObservation(int index, okvis::kinematics::Transformation* T_WBtij) const {\n    *T_WBtij = stateInfoForObservations_[index].T_WBtij;\n  }\n\n  okvis::kinematics::Transformation T_WBtij(int index) const {\n    return stateInfoForObservations_[index].T_WBtij;\n  }\n\n  Eigen::Vector3d omega_Btij(int index) const {\n    return stateInfoForObservations_[index].omega_Btij;\n  }\n\n  Eigen::Vector3d v_WBtij(int index) const {\n    return stateInfoForObservations_[index].v_WBtij;\n  }\n\n  okvis::kinematics::Transformation T_WBtij_ForJacobian(int index) const {\n    return stateInfoForObservations_[index].T_WBtij_fej;\n  }\n\n  Eigen::Matrix3d Phi_pq_feature(int observationIndex) const {\n    const StateInfoForOneKeypoint& item =\n        stateInfoForObservations_[observationIndex];\n    double relFeatureTime = normalizedFeatureTime(item);\n    Eigen::Vector3d gW(0, 0, -imuParameters_->g);\n    Eigen::Vector3d dr =\n        -(item.T_WBtij_fej.r() - item.positionVelocityPtr->head<3>() -\n          item.positionVelocityPtr->tail<3>() * relFeatureTime -\n          0.5 * gW * relFeatureTime * relFeatureTime);\n    return okvis::kinematics::crossMx(dr);\n  }\n\n  Eigen::Vector3d v_WBtij_ForJacobian(int index) const {\n    return stateInfoForObservations_[index].v_WBtij_fej;\n  }\n\n  PointSharedDataState status() const {\n    return status_;\n  }\n\n  double gravityNorm() const {\n    return imuParameters_->g;\n  }\n  /// @}\n\n  /// @name Getters for parameter blocks\n  /// @{\n  std::shared_ptr<const okvis::ceres::PoseParameterBlock> poseParameterBlockPtr(\n      int observationIndex) const;\n\n  std::shared_ptr<const okvis::ceres::ParameterBlock>\n  speedAndBiasParameterBlockPtr(int observationIndex) const {\n    return stateInfoForObservations_.at(observationIndex).speedAndBiasPtr;\n  }\n\n  std::shared_ptr<const okvis::ceres::ParameterBlock>\n  cameraTimeDelayParameterBlockPtr(size_t cameraIndex) const {\n    return tdParamBlockPtrs_[cameraIndex];\n  }\n\n  std::shared_ptr<const okvis::ceres::ParameterBlock>\n  frameReadoutTimeParameterBlockPtr(size_t cameraIndex) const {\n    return trParamBlockPtrs_[cameraIndex];\n  }\n  /// @}\n\n private:\n  // The items of stateInfoForObservations_ are added in an ordered manner\n  // by sequentially examining the ordered elements of MapPoint.observations.\n  std::vector<StateInfoForOneKeypoint,\n              Eigen::aligned_allocator<StateInfoForOneKeypoint>>\n      stateInfoForObservations_;\n\n  std::vector<AnchorFrameIdentifier> anchorIds_;\n\n  std::vector<std::shared_ptr<const okvis::ceres::ParameterBlock>>\n      tdParamBlockPtrs_;\n  std::vector<std::shared_ptr<const okvis::ceres::ParameterBlock>>\n      trParamBlockPtrs_;\n  std::vector<std::shared_ptr<const okvis::ceres::ParameterBlock>>\n      imuAugmentedParamBlockPtrs_;\n  const okvis::ImuParameters* imuParameters_;\n\n  // The structure of sharedJacobians is determined by an external cameraObservationModelId.\n  std::vector<\n      Eigen::Matrix<double, -1, -1, Eigen::RowMajor>,\n      Eigen::aligned_allocator<Eigen::Matrix<double, -1, -1, Eigen::RowMajor>>>\n      sharedJacobians_;\n  PointSharedDataState status_;\n};\n} // namespace swift_vio\n\n#endif // INCLUDE_SWIFT_VIO_POINT_SHARED_DATA_HPP_\n", "meta": {"hexsha": "10b20c0a31b23e438378315fd16f34d80f248e64", "size": 13458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_ceres/include/swift_vio/PointSharedData.hpp", "max_stars_repo_name": "wbl1997/okvis", "max_stars_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "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": "okvis_ceres/include/swift_vio/PointSharedData.hpp", "max_issues_repo_name": "wbl1997/okvis", "max_issues_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "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": "okvis_ceres/include/swift_vio/PointSharedData.hpp", "max_forks_repo_name": "wbl1997/okvis", "max_forks_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "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.046875, "max_line_length": 100, "alphanum_fraction": 0.7275969683, "num_tokens": 3502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.18472683018536495}}
{"text": "#pragma once\n\n#include <scorum/protocol/betting/market.hpp>\n#include <scorum/chain/schema/scorum_object_types.hpp>\n#include <scorum/protocol/odds.hpp>\n\n#include <boost/multi_index/hashed_index.hpp>\n#include <boost/multi_index/composite_key.hpp>\n\nnamespace scorum {\nnamespace chain {\n\nusing scorum::protocol::asset;\nusing scorum::protocol::odds;\nusing scorum::protocol::wincase_type;\nusing scorum::protocol::market_type;\n\nenum class pending_bet_kind : uint8_t\n{\n    live = 0b01,\n    non_live = 0b10\n};\n\nstruct bet_data\n{\n    uuid_type uuid;\n    fc::time_point_sec created;\n\n    account_name_type better;\n    wincase_type wincase;\n    asset stake = asset(0, SCORUM_SYMBOL);\n\n    class odds odds;\n    pending_bet_kind kind = pending_bet_kind::live;\n};\n\nclass bet_uuid_history_object : public object<bet_uuid_history_object_type, bet_uuid_history_object>\n{\npublic:\n    /// @cond DO_NOT_DOCUMENT\n    CHAINBASE_DEFAULT_CONSTRUCTOR(bet_uuid_history_object)\n    /// @endcond\n\n    id_type id;\n    uuid_type uuid;\n};\n\nclass pending_bet_object : public object<pending_bet_object_type, pending_bet_object>\n{\npublic:\n    /// @cond DO_NOT_DOCUMENT\n    CHAINBASE_DEFAULT_CONSTRUCTOR(pending_bet_object)\n    /// @endcond\n\n    id_type id;\n    uuid_type game_uuid;\n    market_type market;\n\n    bet_data data;\n\n    // clang-format off\n    fc::time_point_sec get_created() const { return data.created; }\n    account_name_type get_better() const { return data.better; }\n    pending_bet_kind get_kind() const { return data.kind; }\n    uuid_type get_uuid() const { return data.uuid; }\n    wincase_type get_wincase() const { return data.wincase; }\n\n    // clang-format on\n};\n\nclass matched_bet_object : public object<matched_bet_object_type, matched_bet_object>\n{\npublic:\n    /// @cond DO_NOT_DOCUMENT\n    CHAINBASE_DEFAULT_CONSTRUCTOR(matched_bet_object)\n    /// @endcond\n\n    id_type id;\n    uuid_type game_uuid;\n    market_type market;\n    fc::time_point_sec created;\n\n    bet_data bet1_data;\n    bet_data bet2_data;\n\n    // clang-format off\n    uuid_type get_bet1_uuid() const { return bet1_data.uuid; }\n    uuid_type get_bet2_uuid() const { return bet2_data.uuid; }\n    // clang-format on\n};\n\nstruct by_uuid;\nstruct by_game_uuid_kind;\nstruct by_game_uuid_market;\nstruct by_game_uuid_created;\n\nstruct by_game_uuid_wincase_asc;\n\nusing bet_uuid_history_index\n    = shared_multi_index_container<bet_uuid_history_object,\n                                   indexed_by<ordered_unique<tag<by_id>,\n                                                             member<bet_uuid_history_object,\n                                                                    bet_uuid_history_id_type,\n                                                                    &bet_uuid_history_object::id>>,\n                                              hashed_unique<tag<by_uuid>,\n                                                            member<bet_uuid_history_object,\n                                                                   uuid_type,\n                                                                   &bet_uuid_history_object::uuid>>>>;\n\nusing pending_bet_index\n    = shared_multi_index_container<pending_bet_object,\n                                   indexed_by<ordered_unique<tag<by_id>,\n                                                             member<pending_bet_object,\n                                                                    pending_bet_id_type,\n                                                                    &pending_bet_object::id>>,\n\n                                              hashed_unique<tag<by_uuid>,\n                                                            const_mem_fun<pending_bet_object,\n                                                                          uuid_type,\n                                                                          &pending_bet_object::get_uuid>>,\n\n                                              ordered_unique<tag<by_game_uuid_wincase_asc>,\n                                                             composite_key<pending_bet_object,\n                                                                           member<pending_bet_object,\n                                                                                  uuid_type,\n                                                                                  &pending_bet_object::game_uuid>,\n                                                                           const_mem_fun<pending_bet_object,\n                                                                                         wincase_type,\n                                                                                         &pending_bet_object::\n                                                                                             get_wincase>,\n                                                                           const_mem_fun<pending_bet_object,\n                                                                                         fc::time_point_sec,\n                                                                                         &pending_bet_object::\n                                                                                             get_created>,\n                                                                           member<pending_bet_object,\n                                                                                  pending_bet_id_type,\n                                                                                  &pending_bet_object::id>>,\n                                                             composite_key_compare<std::less<uuid_type>,\n                                                                                   std::less<wincase_type>,\n                                                                                   std::less<time_point_sec>,\n                                                                                   std::less<pending_bet_id_type>>>,\n\n                                              ordered_unique<tag<by_game_uuid_kind>,\n                                                             composite_key<pending_bet_object,\n                                                                           member<pending_bet_object,\n                                                                                  uuid_type,\n                                                                                  &pending_bet_object::game_uuid>,\n                                                                           const_mem_fun<pending_bet_object,\n                                                                                         pending_bet_kind,\n                                                                                         &pending_bet_object::get_kind>,\n                                                                           member<pending_bet_object,\n                                                                                  pending_bet_id_type,\n                                                                                  &pending_bet_object::id>>>,\n\n                                              ordered_unique<tag<by_game_uuid_market>,\n                                                             composite_key<pending_bet_object,\n                                                                           member<pending_bet_object,\n                                                                                  uuid_type,\n                                                                                  &pending_bet_object::game_uuid>,\n                                                                           member<pending_bet_object,\n                                                                                  market_type,\n                                                                                  &pending_bet_object::market>,\n                                                                           member<pending_bet_object,\n                                                                                  pending_bet_id_type,\n                                                                                  &pending_bet_object::id>>>,\n\n                                              ordered_unique<tag<by_game_uuid_created>,\n                                                             composite_key<pending_bet_object,\n                                                                           member<pending_bet_object,\n                                                                                  uuid_type,\n                                                                                  &pending_bet_object::game_uuid>,\n                                                                           const_mem_fun<pending_bet_object,\n                                                                                         fc::time_point_sec,\n                                                                                         &pending_bet_object::\n                                                                                             get_created>,\n                                                                           member<pending_bet_object,\n                                                                                  pending_bet_id_type,\n                                                                                  &pending_bet_object::id>>>>>;\n\nstruct by_bet1_uuid;\nstruct by_bet2_uuid;\n\nusing matched_bet_index\n    = shared_multi_index_container<matched_bet_object,\n                                   indexed_by<ordered_unique<tag<by_id>,\n                                                             member<matched_bet_object,\n                                                                    matched_bet_id_type,\n                                                                    &matched_bet_object::id>>,\n\n                                              ordered_unique<tag<by_bet1_uuid>,\n                                                             composite_key<matched_bet_object,\n                                                                           const_mem_fun<matched_bet_object,\n                                                                                         uuid_type,\n                                                                                         &matched_bet_object::\n                                                                                             get_bet1_uuid>,\n                                                                           member<matched_bet_object,\n                                                                                  matched_bet_id_type,\n                                                                                  &matched_bet_object::id>>>,\n\n                                              ordered_unique<tag<by_bet2_uuid>,\n                                                             composite_key<matched_bet_object,\n                                                                           const_mem_fun<matched_bet_object,\n                                                                                         uuid_type,\n                                                                                         &matched_bet_object::\n                                                                                             get_bet2_uuid>,\n                                                                           member<matched_bet_object,\n                                                                                  matched_bet_id_type,\n                                                                                  &matched_bet_object::id>>>,\n\n                                              ordered_unique<tag<by_game_uuid_market>,\n                                                             composite_key<matched_bet_object,\n                                                                           member<matched_bet_object,\n                                                                                  uuid_type,\n                                                                                  &matched_bet_object::game_uuid>,\n                                                                           member<matched_bet_object,\n                                                                                  market_type,\n                                                                                  &matched_bet_object::market>,\n                                                                           member<matched_bet_object,\n                                                                                  matched_bet_id_type,\n                                                                                  &matched_bet_object::id>>>,\n\n                                              ordered_unique<tag<by_game_uuid_created>,\n                                                             composite_key<matched_bet_object,\n                                                                           member<matched_bet_object,\n                                                                                  uuid_type,\n                                                                                  &matched_bet_object::game_uuid>,\n                                                                           member<matched_bet_object,\n                                                                                  fc::time_point_sec,\n                                                                                  &matched_bet_object::created>,\n                                                                           member<matched_bet_object,\n                                                                                  matched_bet_id_type,\n                                                                                  &matched_bet_object::id>>>>>;\n}\n}\n\n// clang-format off\n\nFC_REFLECT(scorum::chain::bet_uuid_history_object,\n           (id)\n           (uuid)\n           )\n\nCHAINBASE_SET_INDEX_TYPE(scorum::chain::bet_uuid_history_object, scorum::chain::bet_uuid_history_index)\n\nFC_REFLECT_ENUM(scorum::chain::pending_bet_kind,\n                (live)\n                (non_live))\n\nFC_REFLECT(scorum::chain::bet_data,\n           (uuid)\n           (created)\n           (better)\n           (wincase)\n           (stake)\n           (odds)\n           (kind))\n\nFC_REFLECT(scorum::chain::pending_bet_object,\n           (id)\n           (game_uuid)\n           (market)\n           (data)\n           )\n\nCHAINBASE_SET_INDEX_TYPE(scorum::chain::pending_bet_object, scorum::chain::pending_bet_index)\n\nFC_REFLECT(scorum::chain::matched_bet_object,\n           (id)\n           (game_uuid)\n           (market)\n           (created)\n           (bet1_data)\n           (bet2_data)\n           )\n\nCHAINBASE_SET_INDEX_TYPE(scorum::chain::matched_bet_object, scorum::chain::matched_bet_index)\n// clang-format on\n", "meta": {"hexsha": "a8417cae204f9a51f12304f8a4f8b725d066f036", "size": 15103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/include/scorum/chain/schema/bet_objects.hpp", "max_stars_repo_name": "scorum/scorum", "max_stars_repo_head_hexsha": "1da00651f2fa14bcf8292da34e1cbee06250ae78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:20:48.000Z", "max_issues_repo_path": "libraries/chain/include/scorum/chain/schema/bet_objects.hpp", "max_issues_repo_name": "Scorum/Scorum", "max_issues_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2017-11-25T09:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T09:17:22.000Z", "max_forks_repo_path": "libraries/chain/include/scorum/chain/schema/bet_objects.hpp", "max_forks_repo_name": "Scorum/Scorum", "max_forks_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T19:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:50:42.000Z", "avg_line_length": 54.3273381295, "max_line_length": 120, "alphanum_fraction": 0.3405283718, "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18472683018536493}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2009-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NGT platform is licensed under the Apache License, Version 2.0 (the\n//  \"License\"); you may not use this file except in compliance with the\n//  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/// \\file nurbs.cc\n///\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <vw/vw.h>\nusing namespace vw;\n\n#include \"SurfaceNURBS.h\"\n\nusing namespace vw;\n\nint main( int argc, char *argv[] ) {\n\n  std::string input_file_name, output_file_name;\n  unsigned int num_iterations;\n\n  po::options_description desc(\"Options\");\n  desc.add_options()\n    (\"help\", \"Display this help message\")\n    (\"input-file\", po::value<std::string>(&input_file_name), \"Explicitly specify the input file\")\n    (\"output-file,o\", po::value<std::string>(&output_file_name)->default_value(\"output.png\"), \"Specify the output file\")\n    (\"iterations,i\", po::value<unsigned int>(&num_iterations), \"The number of iterations to perform\")\n    (\"holes-only,h\", \"Only fill areas with no pixels (zero alpha) with interpolated data.\")\n    (\"normalize\", \"Normalize the output image\")\n    (\"verbose\", \"Verbose output\");\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( argc, argv ).options(desc).positional(p).run(), vm );\n  po::notify( vm );\n\n  if( vm.count(\"help\") ) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  if( vm.count(\"input-file\") != 1 ) {\n    std::cout << \"Error: Must specify exactly one input file!\" << std::endl;\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  if( vm.count(\"verbose\") ) {\n    set_debug_level(VerboseDebugMessage);\n  }\n\n  try {\n    ImageView<PixelGrayA<float> > image;\n    read_image( image, input_file_name );\n\n    ImageView<PixelGrayA<float> > output;\n    output = MBASurfaceNURBS(image, num_iterations);\n    \n    if (vm.count(\"holes-only\") ) {\n      for (int j = 0; j < image.rows(); ++j) {\n        for (int i = 0; i < image.cols(); ++i) {\n          if (image(i,j).a() != 0) {\n            output(i,j) = image(i,j);\n          }\n        }\n      }\n    }\n\n    if( vm.count(\"normalize\") ) {\n      output = normalize(output);\n    }\n\n    write_image( output_file_name, output );\n  }\n  catch( Exception& e ) {\n    std::cerr << \"Error: \" << e.what() << std::endl;\n  }\n\n  return 0;\n}\n\n", "meta": {"hexsha": "aa4a9babeeb1de612d8686c416d93f00375fdeb7", "size": 3010, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graveyard/nurbs.cc", "max_stars_repo_name": "AndrewAnnex/StereoPipeline", "max_stars_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 323.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T12:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:52:22.000Z", "max_issues_repo_path": "graveyard/nurbs.cc", "max_issues_repo_name": "AndrewAnnex/StereoPipeline", "max_issues_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 252.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T16:36:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:34:28.000Z", "max_forks_repo_path": "graveyard/nurbs.cc", "max_forks_repo_name": "AndrewAnnex/StereoPipeline", "max_forks_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 105.0, "max_forks_repo_forks_event_min_datetime": "2015-02-28T02:37:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T09:17:30.000Z", "avg_line_length": 28.9423076923, "max_line_length": 120, "alphanum_fraction": 0.6568106312, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18472683018536493}}
{"text": "#include \"navigation/algorithm/timetable.hpp\"\n#include \"navigation/route.hpp\"\n#include \"search/stop_to_line.hpp\"\n#include \"timetable/timetable.hpp\"\n\n#include \"id/line.hpp\"\n#include \"id/stop.hpp\"\n\n#include <algorithm>\n#include <cstdint>\n#include <iterator>\n#include <limits>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include <boost/assert.hpp>\n\nnamespace nepomuk\n{\nnamespace navigation\n{\nnamespace algorithm\n{\n\nTimeTable::TimeTable(timetable::TimeTable const &time_table, search::StopToLine const &stop_to_line)\n    : RoutingAlgorithm(time_table.lines()), time_table(time_table), stop_to_line(stop_to_line)\n{\n}\n\nboost::optional<Route> TimeTable::\noperator()(date::Time const departure, StopID const origin, StopID const destination) const\n{\n    ReachedStateContainer earliest_arrival;\n    StateContainer internal_state;\n\n    add_origin(origin, departure, internal_state, earliest_arrival);\n\n    date::Time upper_bound;\n    upper_bound = upper_bound + std::numeric_limits<std::uint32_t>::max();\n    StopID reached_destination = destination;\n    auto const destination_station = time_table.station(destination);\n\n    auto const check_and_improve_upper_bound = [&](StopID const stop) {\n        auto const itr = earliest_arrival.find(stop);\n        if (itr != earliest_arrival.end() && itr->second.arrival < upper_bound)\n        {\n            // std::cout << \"Found new upper bound: \" << stop << \" \" << itr->second.arrival\n            //          << std::endl;\n            upper_bound = itr->second.arrival;\n            reached_destination = stop;\n        }\n    };\n    // relax by lines, in order of hops\n    auto const &destination_stops = time_table.stops(destination_station);\n    std::size_t offset = 0;\n    while (offset < internal_state.size())\n    {\n        // relax all hops\n        std::sort(internal_state.begin() + offset,\n                  internal_state.end(),\n                  [](auto const &lhs, auto const &rhs) { return lhs.arrival < rhs.arrival; });\n\n        std::for_each(\n            destination_stops.begin(), destination_stops.end(), check_and_improve_upper_bound);\n\n        auto const new_offset = internal_state.size();\n        relax(\n            upper_bound, offset, internal_state.size() - offset, internal_state, earliest_arrival);\n        offset = new_offset;\n    }\n\n    std::for_each(\n        destination_stops.begin(), destination_stops.end(), check_and_improve_upper_bound);\n\n    if (!earliest_arrival.count(reached_destination))\n        return boost::none;\n\n    return make_route(extract_path(reached_destination, earliest_arrival));\n}\n\nboost::optional<Route> TimeTable::operator()(date::Time const departure,\n                                             std::vector<ADLeg> const &origins,\n                                             std::vector<ADLeg> const &destinations) const\n{\n    if (origins.empty() || destinations.empty())\n        return boost::none;\n\n    ReachedStateContainer earliest_arrival;\n    StateContainer internal_state;\n\n    for (auto const &leg : origins)\n        add_origin(leg.stop, departure + leg.seconds, internal_state, earliest_arrival);\n\n    std::vector<std::pair<StopID, std::uint32_t>> destination_stations;\n    destination_stations.reserve(destinations.size());\n    std::transform(destinations.begin(),\n                   destinations.end(),\n                   std::back_inserter(destination_stations),\n                   [this](auto const &adleg) {\n                       return std::make_pair(time_table.station(adleg.stop), adleg.seconds);\n                   });\n\n    std::sort(destination_stations.begin(), destination_stations.end());\n    destination_stations.erase(\n        std::unique(destination_stations.begin(),\n                    destination_stations.end(),\n                    [](auto const &lhs, auto const &rhs) { return lhs.first < rhs.first; }),\n        destination_stations.end());\n\n    date::Time upper_bound;\n    upper_bound = upper_bound + std::numeric_limits<std::uint32_t>::max();\n    StopID reached_destination = destinations.front().stop;\n    // make into multiple stations\n    auto const check_and_improve_upper_bound = [&](auto const &stop_and_time) {\n        auto const itr = earliest_arrival.find(stop_and_time.first);\n        if (itr != earliest_arrival.end() &&\n            (itr->second.arrival + stop_and_time.second) < upper_bound)\n        {\n            reached_destination = stop_and_time.first;\n        }\n    };\n\n    std::size_t offset = 0;\n    while (offset < internal_state.size())\n    {\n        std::sort(internal_state.begin() + offset,\n                  internal_state.end(),\n                  [](auto const &lhs, auto const &rhs) { return lhs.arrival < rhs.arrival; });\n\n        std::for_each(destination_stations.begin(),\n                      destination_stations.end(),\n                      check_and_improve_upper_bound);\n\n        auto const new_offset = internal_state.size();\n        relax(\n            upper_bound, offset, internal_state.size() - offset, internal_state, earliest_arrival);\n        offset = new_offset;\n    }\n\n    if (!earliest_arrival.count(reached_destination))\n        return boost::none;\n\n    return make_route(extract_path(reached_destination, earliest_arrival));\n}\n\nvoid TimeTable::add_origin(StopID const origin,\n                           date::Time const departure,\n                           StateContainer &internal_state,\n                           ReachedStateContainer &reached) const\n{\n    for (auto start : time_table.stops(time_table.station(origin)))\n    {\n        if (!reached.count(start) || departure < (reached[start].arrival))\n        {\n            // std::cout << \"[origin] \" << start << \" at \" << departure << std::endl;\n            internal_state.push_back({start, departure});\n            reached[start] = {departure, start, departure, WALKING_TRANSFER};\n        }\n    }\n}\n\nvoid TimeTable::relax(date::Time const &upper_bound,\n                      std::size_t offset,\n                      std::size_t count,\n                      StateContainer &internal_state,\n                      ReachedStateContainer &earliest_arrival) const\n{\n    auto const add_if_improved = [&](StopID const stop,\n                                     date::Time const time,\n                                     StopID const parent,\n                                     LineID const line,\n                                     date::Time const departure) {\n        if (!earliest_arrival.count(stop) || time < earliest_arrival[stop].arrival)\n        {\n            BOOST_ASSERT(parent != stop);\n            earliest_arrival[stop] = {time, parent, departure, line};\n            // std::cout << \"\\t\\t[Reach] \" << stop << \" from \" << parent << \" at \" << time << \" via\n            // \"\n            //          << line << std::endl;\n            return true;\n        }\n        else\n            return false;\n    };\n\n    auto const relax_line = [&](auto const &state, auto const line_id) {\n        // std::cout << \"-------\" << std::endl;\n        auto const trip_optional = time_table.line(line_id).get(state.stop_id, state.arrival);\n        if (!trip_optional)\n            return;\n\n        auto const &trip = *trip_optional;\n        auto time = trip.departure;\n\n        auto duration_itr = trip.duration_range.begin();\n        for (auto stop_itr = trip.stop_range.begin(); stop_itr != trip.stop_range.end();\n             ++stop_itr, ++duration_itr)\n        {\n            auto const stop_id = *stop_itr;\n            // std::cout << \"\\t\\t\" << stop_id << \" \" << time + *duration_itr << std::endl;\n            if (add_if_improved(stop_id, time, state.stop_id, line_id, trip.departure))\n            {\n                auto transfers = time_table.transfers(stop_id);\n                // add all transfers\n                for (auto transfer : transfers)\n                {\n                    auto transfer_time = time + std::max<int>(transfer.duration, 60);\n                    if (add_if_improved(\n                            transfer.stop_id, transfer_time, stop_id, WALKING_TRANSFER, time) ||\n                        (transfer.stop_id == stop_id))\n                    {\n                        // needs to be a transfer line instead of 0\n                        internal_state.push_back({transfer.stop_id, time + transfer.duration});\n                    }\n                }\n            }\n            time = time + *duration_itr;\n        }\n    };\n\n    // std::cout << \"[Round]\" << std::endl;\n    while (count--)\n    {\n        auto const state = internal_state[offset++];\n\n        // std::cout << \"\\tAt: \" << state.stop_id << \" \" << state.arrival << std::endl;\n        // stop when the earliest arrival is known\n        if (upper_bound <= state.arrival)\n            break; // sorted, all current states will be out of bound\n\n        // get all lines at the given stop\n        auto trip_range = stop_to_line(state.stop_id);\n        for (auto line : trip_range)\n            relax_line(state, line);\n    }\n}\n\nstd::vector<TimeTable::PathEntry>\nTimeTable::extract_path(StopID current_stop, ReachedStateContainer const &earliest_arrival) const\n{\n    std::vector<PathEntry> path;\n    auto entry = earliest_arrival.find(current_stop)->second;\n    path.push_back({current_stop, entry.line_id, entry.arrival, entry.parent_departure});\n    do\n    {\n        current_stop = entry.parent;\n        entry = earliest_arrival.find(current_stop)->second;\n        path.push_back({current_stop, entry.line_id, entry.arrival, entry.parent_departure});\n    } while (entry.parent != current_stop);\n\n    std::reverse(path.begin(), path.end());\n    return path;\n}\n\n} // namespace algorithm\n} // namespace navigation\n} // namespace nepomuk\n", "meta": {"hexsha": "176918f0a66dd6f3436fd4affdc66082eb7d35de", "size": 9645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/navigation/algorithm/timetable.cpp", "max_stars_repo_name": "mapbox/nepomuk", "max_stars_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-12T11:52:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T06:05:08.000Z", "max_issues_repo_path": "src/navigation/algorithm/timetable.cpp", "max_issues_repo_name": "mapbox/nepomuk", "max_issues_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2017-05-11T16:13:58.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-13T11:19:17.000Z", "max_forks_repo_path": "src/navigation/algorithm/timetable.cpp", "max_forks_repo_name": "mapbox/nepomuk", "max_forks_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T12:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:14:25.000Z", "avg_line_length": 37.2393822394, "max_line_length": 100, "alphanum_fraction": 0.5974079834, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18472683018536493}}
{"text": "// ======================================================================\n/*!\n * \\file\n * \\brief Implementation of class TextGen::WindChillFunctionAnalyzer\n */\n// ======================================================================\n/*!\n * \\class TextGen::WindChillFunctionAnalyzer\n *\n * \\brief Regular function analysis\n *\n */\n// ======================================================================\n\n#include \"WindChillFunctionAnalyzer.h\"\n#include \"AnalysisSources.h\"\n#include \"CalculatorFactory.h\"\n#include \"MaskSource.h\"\n#include \"QueryDataIntegrator.h\"\n#include \"Settings.h\"\n#include \"TextGenError.h\"\n#include \"WeatherArea.h\"\n#include \"WeatherPeriod.h\"\n#include \"WeatherResult.h\"\n#include \"WeatherSource.h\"\n#include \"WindChillQueryInfo.h\"\n#include <boost/shared_ptr.hpp>\n#include <macgyver/StringConversion.h>\n#include <newbase/NFmiEnumConverter.h>\n#include <newbase/NFmiQueryData.h>\n#include <sstream>\n#include <string>\n\nnamespace\n{\n//! A static instance to avoid construction costs\n\nNFmiEnumConverter converter;\n}  // namespace\n\nnamespace TextGen\n{\n// ----------------------------------------------------------------------\n/*!\n * \\brief Constructor\n *\n * \\param theAreaFunction The area function\n * \\param theTimeFunction The time function\n * \\param theSubTimeFunction The time function for subperiods\n */\n// ----------------------------------------------------------------------\n\nWindChillFunctionAnalyzer::WindChillFunctionAnalyzer(const WeatherFunction& theAreaFunction,\n                                                     const WeatherFunction& theTimeFunction,\n                                                     const WeatherFunction& theSubTimeFunction)\n    : itsAreaFunction(theAreaFunction),\n      itsTimeFunction(theTimeFunction),\n      itsSubTimeFunction(theSubTimeFunction),\n      itIsModulo(false),\n      itsModulo(-1)\n{\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the modulo of the parameter values\n *\n * Throws for 0 or negative modulo\n *\n * \\param theModulo The modulo value\n */\n// ----------------------------------------------------------------------\n\nvoid WindChillFunctionAnalyzer::modulo(int theModulo)\n{\n  if (theModulo <= 0)\n    throw TextGenError(\"Trying to analyze data modulo \" + Fmi::to_string(theModulo));\n  itsModulo = theModulo;\n  itIsModulo = true;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Analyze area and time functions\n *\n * Note that theTester argument is associated to both itsAreaCalculator\n * and itsTimeCalculator. Naturally the association is real only\n * for functions which require the tester. At the moment Percentage\n * is the only such function.\n *\n * It is assumed that the space and time functions are never both\n * Percentage, hence atmost one Acceptor is needed for Percentage\n * calculations.\n *\n * \\param theSources Analysis sources\n * \\param theDataType Analysis data type\n * \\param theArea Analysis area\n * \\param thePeriods Analysis periods\n * \\param theAreaAcceptor The data acceptor in area integration\n * \\param theTimeAcceptor The data acceptor in space integration\n * \\param theTester The data tester for Percentage calculations\n * \\param theDataName The name of the data file\n * \\param theParameterName The name of the parameter\n * \\return The analysis result\n */\n// ----------------------------------------------------------------------\n\nWeatherResult WindChillFunctionAnalyzer::analyze(const AnalysisSources& theSources,\n                                                 const WeatherDataType& theDataType,\n                                                 const WeatherArea& theArea,\n                                                 const WeatherPeriodGenerator& thePeriods,\n                                                 const Acceptor& theAreaAcceptor,\n                                                 const Acceptor& theTimeAcceptor,\n                                                 const Acceptor& theTester,\n                                                 const std::string& theDataName,\n                                                 const std::string& /* theParameterName */) const\n{\n  // Establish the data\n\n  const std::string default_forecast = Settings::optional_string(\"textgen::default_forecast\", \"\");\n  const std::string datavar = theDataName + '_' + data_type_name(theDataType);\n  const std::string dataname = Settings::optional_string(datavar, default_forecast);\n\n  // Get the data into use\n\n  boost::shared_ptr<WeatherSource> wsource = theSources.getWeatherSource();\n  boost::shared_ptr<NFmiQueryData> qd = wsource->data(dataname);\n\n  NFmiFastQueryInfo qi = NFmiFastQueryInfo(qd.get());\n  WindChillQueryInfo wi(qi);\n\n  // Try activating the parameter\n\n  /*\n  // WindChill parameter does not exists in querydata, but\n  // it is composed of wind speed and temperature\n  FmiParameterName param = FmiParameterName(converter.ToEnum(theParameterName));\n  if(param == kFmiBadParameter)\n  throw TextGenError(\"Parameter \"+theParameterName+\" is not defined in newbase\");\n\n  if(!qi.Param(param))\n  throw TextGenError(theParameterName+\" is not available in \"+dataname);\n  */\n\n  boost::shared_ptr<Calculator> spacemod, timemod, subtimemod;\n\n  if (!itIsModulo)\n  {\n    timemod.reset(CalculatorFactory::create(itsTimeFunction, theTester));\n    subtimemod.reset(CalculatorFactory::create(itsSubTimeFunction, theTester));\n  }\n  else\n  {\n    timemod.reset(CalculatorFactory::create(itsTimeFunction, theTester, itsModulo));\n    subtimemod.reset(CalculatorFactory::create(itsSubTimeFunction, theTester, itsModulo));\n  }\n  timemod->acceptor(theTimeAcceptor);\n  subtimemod->acceptor(theTimeAcceptor);\n\n  if (!theArea.isPoint())\n  {\n    MaskSource::mask_type mask;\n\n    switch (theArea.type())\n    {\n      case WeatherArea::Full:\n        mask = theSources.getMaskSource()->mask(theArea, dataname, *wsource);\n        break;\n      case WeatherArea::Land:\n        mask = theSources.getLandMaskSource()->mask(theArea, dataname, *wsource);\n        break;\n      case WeatherArea::Coast:\n        mask = theSources.getCoastMaskSource()->mask(theArea, dataname, *wsource);\n        break;\n      case WeatherArea::Inland:\n        mask = theSources.getInlandMaskSource()->mask(theArea, dataname, *wsource);\n        break;\n      case WeatherArea::Northern:\n        mask = theSources.getNorthernMaskSource()->mask(theArea, dataname, *wsource);\n        break;\n      case WeatherArea::Southern:\n        mask = theSources.getSouthernMaskSource()->mask(theArea, dataname, *wsource);\n        break;\n      case WeatherArea::Eastern:\n        mask = theSources.getEasternMaskSource()->mask(theArea, dataname, *wsource);\n        break;\n      case WeatherArea::Western:\n        mask = theSources.getWesternMaskSource()->mask(theArea, dataname, *wsource);\n        break;\n    }\n\n    // Result\n\n    if (!itIsModulo)\n      spacemod.reset(CalculatorFactory::create(itsAreaFunction, theTester));\n    else\n      spacemod.reset(CalculatorFactory::create(itsAreaFunction, theTester, itsModulo));\n    spacemod->acceptor(theAreaAcceptor);\n\n    float result =\n        QueryDataIntegrator::Integrate(wi, thePeriods, *subtimemod, *timemod, *mask, *spacemod);\n    if (result == kFloatMissing) return WeatherResult(kFloatMissing, 0);\n\n    if (itsAreaFunction != Mean) return WeatherResult(result, 0);\n\n    // Calculate standard deviation for the mean\n\n    if (!itIsModulo)\n      spacemod.reset(CalculatorFactory::create(StandardDeviation, theTester));\n    else\n      spacemod.reset(CalculatorFactory::create(StandardDeviation, theTester, itsModulo));\n    spacemod->acceptor(theAreaAcceptor);\n\n    float error =\n        QueryDataIntegrator::Integrate(wi, thePeriods, *subtimemod, *timemod, *mask, *spacemod);\n\n    // This would happen if the area covers one point only\n    if (error == kFloatMissing) return WeatherResult(result, 0);\n\n    return {result, error};\n  }\n\n  if (!(qi.Location(theArea.point())))\n  {\n    std::ostringstream msg;\n    msg << \"Could not set desired coordinate (\" << theArea.point().X() << ',' << theArea.point().Y()\n        << ')';\n    if (theArea.isNamed()) msg << \" named \" << theArea.name();\n    msg << \" in \" << dataname;\n    throw TextGenError(msg.str());\n  }\n\n  float result = QueryDataIntegrator::Integrate(wi, thePeriods, *subtimemod, *timemod);\n\n  return {result, 0};\n}\n\n}  // namespace TextGen\n\n// ======================================================================\n", "meta": {"hexsha": "805e2785bb35d9a978ded035d914d509a88c39bd", "size": 8434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calculator/WindChillFunctionAnalyzer.cpp", "max_stars_repo_name": "fmidev/smartmet-library-calculator", "max_stars_repo_head_hexsha": "19366ff5af4d3a456d1841c3c3cb598eb900d86a", "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": "calculator/WindChillFunctionAnalyzer.cpp", "max_issues_repo_name": "fmidev/smartmet-library-calculator", "max_issues_repo_head_hexsha": "19366ff5af4d3a456d1841c3c3cb598eb900d86a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculator/WindChillFunctionAnalyzer.cpp", "max_forks_repo_name": "fmidev/smartmet-library-calculator", "max_forks_repo_head_hexsha": "19366ff5af4d3a456d1841c3c3cb598eb900d86a", "max_forks_repo_licenses": ["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.9958506224, "max_line_length": 100, "alphanum_fraction": 0.6183305668, "num_tokens": 1852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.1847268301853649}}
{"text": "#include \"general_quantum_operator.hpp\"\n\n#include <Eigen/Dense>\n#include <csim/stat_ops.hpp>\n#include <csim/update_ops.hpp>\n#include <csim/update_ops_dm.hpp>\n#include <cstring>\n#include <fstream>\n#include <numeric>\n\n#include \"gate_factory.hpp\"\n#include \"pauli_operator.hpp\"\n#include \"state.hpp\"\n#include \"type.hpp\"\n#include \"utility.hpp\"\n\n#ifdef _USE_GPU\n#include <gpusim/update_ops_cuda.h>\n#endif\n\nGeneralQuantumOperator::GeneralQuantumOperator(const UINT qubit_count)\n    : _qubit_count(qubit_count), _is_hermitian(true) {}\n\nGeneralQuantumOperator::~GeneralQuantumOperator() {\n    for (auto& term : this->_operator_list) {\n        delete term;\n    }\n}\n\nvoid GeneralQuantumOperator::add_operator(const PauliOperator* mpt) {\n    PauliOperator* _mpt = mpt->copy();\n    if (!check_Pauli_operator(this, _mpt)) {\n        std::stringstream error_message_stream;\n        error_message_stream\n            << \"Error: GeneralQuantumOperator::add_operator(const \"\n               \"PauliOperator*): pauli_operator applies target qubit of \"\n               \"which the index is larger than qubit_count\";\n        throw std::invalid_argument(error_message_stream.str());\n    }\n    if (this->_is_hermitian && std::abs(_mpt->get_coef().imag()) > 0) {\n        this->_is_hermitian = false;\n    }\n    this->_operator_list.push_back(_mpt);\n}\n\nvoid GeneralQuantumOperator::add_operator(\n    CPPCTYPE coef, std::string pauli_string) {\n    PauliOperator* _mpt = new PauliOperator(pauli_string, coef);\n    if (!check_Pauli_operator(this, _mpt)) {\n        std::stringstream error_message_stream;\n        error_message_stream\n            << \"Error: \"\n               \"GeneralQuantumOperator::add_operator(double,std::string):\"\n               \" pauli_operator applies target qubit of which the index \"\n               \"is larger than qubit_count\";\n        throw std::invalid_argument(error_message_stream.str());\n    }\n    if (this->_is_hermitian && std::abs(coef.imag()) > 0) {\n        this->_is_hermitian = false;\n    }\n    this->add_operator(_mpt);\n    delete _mpt;\n}\n\nCPPCTYPE GeneralQuantumOperator::get_expectation_value(\n    const QuantumStateBase* state) const {\n    if (this->_qubit_count > state->qubit_count) {\n        std::stringstream error_message_stream;\n        error_message_stream\n            << \"Error: GeneralQuantumOperator::get_expectation_value(const \"\n               \"QuantumStateBase*): invalid qubit count\";\n        throw std::invalid_argument(error_message_stream.str());\n    }\n    auto sum = std::accumulate(this->_operator_list.cbegin(),\n        this->_operator_list.cend(), (CPPCTYPE)0.0,\n        [&](CPPCTYPE acc, PauliOperator* pauli) {\n            return acc + pauli->get_expectation_value(state);\n        });\n    return sum;\n}\n\nCPPCTYPE GeneralQuantumOperator::get_expectation_value_single_thread(\n    const QuantumStateBase* state) const {\n    if (this->_qubit_count > state->qubit_count) {\n        std::cerr\n            << \"Error: GeneralQuantumOperator::get_expectation_value(const \"\n               \"QuantumStateBase*): invalid qubit count\"\n            << std::endl;\n        return 0.;\n    }\n    auto sum = std::accumulate(this->_operator_list.cbegin(),\n        this->_operator_list.cend(), (CPPCTYPE)0.0,\n        [&](CPPCTYPE acc, PauliOperator* pauli) {\n            return acc + pauli->get_expectation_value_single_thread(state);\n        });\n    return sum;\n}\n\nCPPCTYPE GeneralQuantumOperator::get_transition_amplitude(\n    const QuantumStateBase* state_bra,\n    const QuantumStateBase* state_ket) const {\n    if (this->_qubit_count > state_bra->qubit_count ||\n        state_bra->qubit_count != state_ket->qubit_count) {\n        std::stringstream error_message_stream;\n        error_message_stream\n            << \"Error: GeneralQuantumOperator::get_transition_amplitude(const \"\n               \"QuantumStateBase*, const QuantumStateBase*): invalid qubit \"\n               \"count\";\n        throw std::invalid_argument(error_message_stream.str());\n    }\n\n    auto sum = std::accumulate(this->_operator_list.cbegin(),\n        this->_operator_list.cend(), (CPPCTYPE)0.0,\n        [&](CPPCTYPE acc, PauliOperator* pauli) {\n            return acc + pauli->get_transition_amplitude(state_bra, state_ket);\n        });\n    return sum;\n}\n\nvoid GeneralQuantumOperator::add_random_operator(const UINT operator_count) {\n    const auto qubit_count = this->get_qubit_count();\n    Random random;\n    for (UINT operator_index = 0; operator_index < operator_count;\n         operator_index++) {\n        auto target_qubit_index_list = std::vector<UINT>(qubit_count, 0);\n        auto target_qubit_pauli_list = std::vector<UINT>(qubit_count, 0);\n        for (UINT qubit_index = 0; qubit_index < qubit_count; qubit_index++) {\n            const UINT pauli_id = random.int32() % 4;\n            target_qubit_index_list.at(qubit_index) = qubit_index;\n            target_qubit_pauli_list.at(qubit_index) = pauli_id;\n        }\n        // -1.0 <= coef <= 1.0\n        const CPPCTYPE coef = random.uniform() * 2 - 1.0;\n        auto pauli_operator = PauliOperator(\n            target_qubit_index_list, target_qubit_pauli_list, coef);\n        this->add_operator(&pauli_operator);\n    }\n}\n\nCPPCTYPE\nGeneralQuantumOperator::solve_ground_state_eigenvalue_by_arnoldi_method(\n    QuantumStateBase* state, const UINT iter_count, const CPPCTYPE mu) const {\n    if (this->get_term_count() == 0) {\n        std::stringstream error_message_stream;\n        error_message_stream\n            << \"Error: \"\n               \"GeneralQuantumOperator::solve_ground_state_eigenvalue_by_\"\n               \"arnoldi_method(\"\n               \"QuantumStateBase * state, const UINT iter_count, const \"\n               \"CPPCTYPE mu): At least one PauliOperator is required.\";\n        throw std::invalid_argument(error_message_stream.str());\n    }\n\n    // Implemented based on\n    // https://files.transtutors.com/cdn/uploadassignments/472339_1_-numerical-linear-aljebra.pdf\n    const auto qubit_count = this->get_qubit_count();\n    auto present_state = QuantumState(qubit_count);\n    auto tmp_state = QuantumState(qubit_count);\n    auto multiplied_state = QuantumState(qubit_count);\n    auto mu_timed_state = QuantumState(qubit_count);\n\n    // Vectors composing Krylov subspace.\n    std::vector<QuantumStateBase*> state_list;\n    state_list.reserve(iter_count + 1);\n    state->normalize(state->get_squared_norm());\n    state_list.push_back(state->copy());\n\n    CPPCTYPE mu_;\n    if (mu == 0.0) {\n        // mu is not changed from default value.\n        mu_ = this->calculate_default_mu();\n    } else {\n        mu_ = mu;\n    }\n\n    ComplexMatrix hessenberg_matrix =\n        ComplexMatrix::Zero(iter_count, iter_count);\n    for (UINT i = 0; i < iter_count; i++) {\n        mu_timed_state.load(state_list[i]);\n        mu_timed_state.multiply_coef(-mu_);\n        this->apply_to_state(&tmp_state, *state_list[i], &multiplied_state);\n        multiplied_state.add_state(&mu_timed_state);\n\n        for (UINT j = 0; j < i + 1; j++) {\n            const auto coef = state::inner_product(\n                static_cast<QuantumState*>(state_list[j]), &multiplied_state);\n            hessenberg_matrix(j, i) = coef;\n            tmp_state.load(state_list[j]);\n            tmp_state.multiply_coef(-coef);\n            multiplied_state.add_state(&tmp_state);\n        }\n\n        const auto norm = multiplied_state.get_squared_norm();\n        if (i != iter_count - 1) {\n            hessenberg_matrix(i + 1, i) = std::sqrt(norm);\n        }\n        multiplied_state.normalize(norm);\n        state_list.push_back(multiplied_state.copy());\n    }\n\n    Eigen::ComplexEigenSolver<ComplexMatrix> eigen_solver(hessenberg_matrix);\n    const auto eigenvalues = eigen_solver.eigenvalues();\n    const auto eigenvectors = eigen_solver.eigenvectors();\n\n    // Find ground state eigenvalue and eigenvector.\n    UINT minimum_eigenvalue_index = 0;\n    auto minimum_eigenvalue = eigenvalues[0];\n    for (UINT i = 0; i < eigenvalues.size(); i++) {\n        if (eigenvalues[i].real() < minimum_eigenvalue.real()) {\n            minimum_eigenvalue_index = i;\n            minimum_eigenvalue = eigenvalues[i];\n        }\n    }\n\n    // Compose ground state vector and store it to `state`.\n    present_state.multiply_coef(0.0);\n    for (UINT i = 0; i < state_list.size() - 1; i++) {\n        tmp_state.load(state_list[i]);\n        tmp_state.multiply_coef(eigenvectors(i, minimum_eigenvalue_index));\n        present_state.add_state(&tmp_state);\n    }\n    state->load(&present_state);\n\n    // Free states allocated by `QuantumState::copy()`.\n    for (auto used_state : state_list) {\n        delete used_state;\n    }\n    return minimum_eigenvalue + mu_;\n}\n\nCPPCTYPE GeneralQuantumOperator::solve_ground_state_eigenvalue_by_power_method(\n    QuantumStateBase* state, const UINT iter_count, const CPPCTYPE mu) const {\n    if (this->get_term_count() == 0) {\n        std::stringstream error_message_stream;\n        error_message_stream\n            << \"Error: \"\n               \"GeneralQuantumOperator::solve_ground_state_eigenvalue_by_\"\n               \"power_method(\"\n               \"QuantumStateBase * state, const UINT iter_count, const \"\n               \"CPPCTYPE mu): At least one PauliOperator is required.\";\n        throw std::invalid_argument(error_message_stream.str());\n    }\n\n    CPPCTYPE mu_;\n    if (mu == 0.0) {\n        // mu is not changed from default value.\n        mu_ = this->calculate_default_mu();\n    } else {\n        mu_ = mu;\n    }\n\n    // Stores a result of A|a>\n    auto multiplied_state = QuantumState(state->qubit_count);\n    // Stores a result of -\\mu|a>\n    auto mu_timed_state = QuantumState(state->qubit_count);\n    auto work_state = QuantumState(state->qubit_count);\n    for (UINT i = 0; i < iter_count; i++) {\n        mu_timed_state.load(state);\n        mu_timed_state.multiply_coef(-mu_);\n\n        multiplied_state.multiply_coef(0.0);\n        this->apply_to_state(&work_state, *state, &multiplied_state);\n        state->load(&multiplied_state);\n        state->add_state(&mu_timed_state);\n        state->normalize(state->get_squared_norm());\n    }\n    return this->get_expectation_value(state) + mu;\n}\n\nvoid GeneralQuantumOperator::apply_to_state(QuantumStateBase* work_state,\n    const QuantumStateBase& state_to_be_multiplied,\n    QuantumStateBase* dst_state) const {\n    if (state_to_be_multiplied.qubit_count != dst_state->qubit_count) {\n        throw std::invalid_argument(\n            \"Qubit count of state_to_be_multiplied and dst_state must be the \"\n            \"same\");\n    }\n\n    dst_state->multiply_coef(0.0);\n    const auto term_count = this->get_term_count();\n    for (UINT i = 0; i < term_count; i++) {\n        work_state->load(&state_to_be_multiplied);\n        const auto term = this->get_term(i);\n        auto pauli_operator =\n            gate::Pauli(term->get_index_list(), term->get_pauli_id_list());\n        pauli_operator->update_quantum_state(work_state);\n        work_state->multiply_coef(term->get_coef());\n        dst_state->add_state(work_state);\n        delete pauli_operator;\n    }\n}\n\nvoid GeneralQuantumOperator::apply_to_state(\n    QuantumStateBase* state, QuantumStateBase* dst_state) const {\n    if (state->qubit_count != dst_state->qubit_count) {\n        throw std::invalid_argument(\n            \"Qubit count of state_to_be_multiplied and dst_state must be the \"\n            \"same\");\n    }\n\n    dst_state->set_zero_norm_state();\n    const auto term_count = this->get_term_count();\n    for (UINT i = 0; i < term_count; i++) {\n        const auto term = this->get_term(i);\n        _apply_pauli_to_state(\n            term->get_pauli_id_list(), term->get_index_list(), state);\n        dst_state->add_state_with_coef(term->get_coef(), state);\n        _apply_pauli_to_state(\n            term->get_pauli_id_list(), term->get_index_list(), state);\n    }\n}\n\nvoid GeneralQuantumOperator::apply_to_state_single_thread(\n    QuantumStateBase* state, QuantumStateBase* dst_state) const {\n    if (state->qubit_count != dst_state->qubit_count) {\n        throw std::invalid_argument(\n            \"Qubit count of state_to_be_multiplied and dst_state must be the \"\n            \"same\");\n    }\n\n    dst_state->set_zero_norm_state();\n    const auto term_count = this->get_term_count();\n    for (UINT i = 0; i < term_count; i++) {\n        const auto term = this->get_term(i);\n        _apply_pauli_to_state_single_thread(\n            term->get_pauli_id_list(), term->get_index_list(), state);\n        dst_state->add_state_with_coef_single_thread(term->get_coef(), state);\n        _apply_pauli_to_state_single_thread(\n            term->get_pauli_id_list(), term->get_index_list(), state);\n    }\n}\n\nvoid GeneralQuantumOperator::_apply_pauli_to_state(\n    std::vector<UINT> pauli_id_list, std::vector<UINT> target_index_list,\n    QuantumStateBase* state) const {\n    // this function is same as the gate::Pauli update quantum state\n    if (state->is_state_vector()) {\n#ifdef _USE_GPU\n        if (state->get_device_name() == \"gpu\") {\n            multi_qubit_Pauli_gate_partial_list_host(target_index_list.data(),\n                pauli_id_list.data(), (UINT)target_index_list.size(),\n                state->data(), state->dim, state->get_cuda_stream(),\n                state->device_number);\n            // _update_func_gpu(this->_target_qubit_list[0].index(), _angle,\n            // state->data(), state->dim);\n            return;\n        }\n#endif\n        multi_qubit_Pauli_gate_partial_list(target_index_list.data(),\n            pauli_id_list.data(), (UINT)target_index_list.size(),\n            state->data_c(), state->dim);\n    } else {\n        dm_multi_qubit_Pauli_gate_partial_list(target_index_list.data(),\n            pauli_id_list.data(), (UINT)target_index_list.size(),\n            state->data_c(), state->dim);\n    }\n}\n\nvoid GeneralQuantumOperator::_apply_pauli_to_state_single_thread(\n    std::vector<UINT> pauli_id_list, std::vector<UINT> target_index_list,\n    QuantumStateBase* state) const {\n    // this function is same as the gate::Pauli update quantum state\n    if (state->is_state_vector()) {\n#ifdef _USE_GPU\n        if (state->get_device_name() == \"gpu\") {\n            // TODO: make it single thread for this function\n            multi_qubit_Pauli_gate_partial_list_host(target_index_list.data(),\n                pauli_id_list.data(), (UINT)target_index_list.size(),\n                state->data(), state->dim, state->get_cuda_stream(),\n                state->device_number);\n            // _update_func_gpu(this->_target_qubit_list[0].index(), _angle,\n            // state->data(), state->dim);\n            return;\n        }\n#endif\n        multi_qubit_Pauli_gate_partial_list_single_thread(\n            target_index_list.data(), pauli_id_list.data(),\n            (UINT)target_index_list.size(), state->data_c(), state->dim);\n    } else {\n        // TODO: make it single thread for this function\n        dm_multi_qubit_Pauli_gate_partial_list(target_index_list.data(),\n            pauli_id_list.data(), (UINT)target_index_list.size(),\n            state->data_c(), state->dim);\n    }\n}\n\nCPPCTYPE GeneralQuantumOperator::calculate_default_mu() const {\n    double mu = 0.0;\n    const auto term_count = this->get_term_count();\n    for (UINT i = 0; i < term_count; i++) {\n        const auto term = this->get_term(i);\n        mu += std::abs(term->get_coef().real());\n    }\n    return static_cast<CPPCTYPE>(mu);\n}\n\nGeneralQuantumOperator* GeneralQuantumOperator::copy() const {\n    auto quantum_operator = new GeneralQuantumOperator(_qubit_count);\n    for (auto pauli : this->_operator_list) {\n        quantum_operator->add_operator(pauli->copy());\n    }\n    return quantum_operator;\n}\n\nGeneralQuantumOperator GeneralQuantumOperator::operator+(\n    const GeneralQuantumOperator& target) const {\n    auto res = this->copy();\n    *res += target;\n    return *res;\n}\n\nGeneralQuantumOperator* GeneralQuantumOperator::get_dagger() const {\n    auto quantum_operator = new GeneralQuantumOperator(_qubit_count);\n    for (auto pauli : this->_operator_list) {\n        quantum_operator->add_operator(\n            std::conj(pauli->get_coef()), pauli->get_pauli_string());\n    }\n    return quantum_operator;\n}\n\nGeneralQuantumOperator GeneralQuantumOperator::operator+(\n    const PauliOperator& target) const {\n    auto res = this->copy();\n    *res += target;\n    return *res;\n}\n\nGeneralQuantumOperator& GeneralQuantumOperator::operator+=(\n    const GeneralQuantumOperator& target) {\n    ITYPE i, j;\n    auto terms = target.get_terms();\n#pragma omp parallel for\n    for (i = 0; i < _operator_list.size(); i++) {\n        auto pauli_operator = _operator_list[i];\n        for (j = 0; j < terms.size(); j++) {\n            auto target_operator = terms[j];\n            auto pauli_x = pauli_operator->get_x_bits();\n            auto pauli_z = pauli_operator->get_z_bits();\n            auto target_x = target_operator->get_x_bits();\n            auto target_z = target_operator->get_z_bits();\n            if (pauli_x.size() != target_x.size()) {\n                UINT max_size = std::max(pauli_x.size(), target_x.size());\n                pauli_x.resize(max_size);\n                pauli_z.resize(max_size);\n                target_x.resize(max_size);\n                target_z.resize(max_size);\n            }\n            if (pauli_x == target_x && pauli_z == target_z) {\n                _operator_list[i]->change_coef(_operator_list[i]->get_coef() +\n                                               target_operator->get_coef());\n            }\n        }\n    }\n    for (j = 0; j < terms.size(); j++) {\n        auto target_operator = terms[j];\n        bool flag = true;\n        for (i = 0; i < _operator_list.size(); i++) {\n            auto pauli_operator = _operator_list[i];\n            auto pauli_x = pauli_operator->get_x_bits();\n            auto pauli_z = pauli_operator->get_z_bits();\n            auto target_x = target_operator->get_x_bits();\n            auto target_z = target_operator->get_z_bits();\n            if (pauli_x.size() != target_x.size()) {\n                UINT max_size = std::max(pauli_x.size(), target_x.size());\n                pauli_x.resize(max_size);\n                pauli_z.resize(max_size);\n                target_x.resize(max_size);\n                target_z.resize(max_size);\n            }\n            if (pauli_x == target_x && pauli_z == target_z) {\n                flag = false;\n            }\n        }\n        if (flag) {\n            this->add_operator(target_operator->copy());\n        }\n    }\n    return *this;\n}\n\nGeneralQuantumOperator& GeneralQuantumOperator::operator+=(\n    const PauliOperator& target) {\n    bool flag = true;\n    ITYPE i;\n#pragma omp parallel for\n    for (i = 0; i < _operator_list.size(); i++) {\n        auto pauli_operator = _operator_list[i];\n        auto pauli_x = pauli_operator->get_x_bits();\n        auto pauli_z = pauli_operator->get_z_bits();\n        auto target_x = target.get_x_bits();\n        auto target_z = target.get_z_bits();\n        if (pauli_x.size() != target_x.size()) {\n            UINT max_size = std::max(pauli_x.size(), target_x.size());\n            pauli_x.resize(max_size);\n            pauli_z.resize(max_size);\n            target_x.resize(max_size);\n            target_z.resize(max_size);\n        }\n        if (pauli_x == target_x && pauli_z == target_z) {\n            _operator_list[i]->change_coef(\n                _operator_list[i]->get_coef() + target.get_coef());\n            flag = false;\n        }\n    }\n    if (flag) {\n        this->add_operator(target.copy());\n    }\n    return *this;\n}\n\nGeneralQuantumOperator GeneralQuantumOperator::operator-(\n    const GeneralQuantumOperator& target) const {\n    auto res = this->copy();\n    *res -= target;\n    return *res;\n}\n\nGeneralQuantumOperator GeneralQuantumOperator::operator-(\n    const PauliOperator& target) const {\n    auto res = this->copy();\n    *res -= target;\n    return *res;\n}\n\nGeneralQuantumOperator& GeneralQuantumOperator::operator-=(\n    const GeneralQuantumOperator& target) {\n    ITYPE i, j;\n    auto terms = target.get_terms();\n#pragma omp parallel for\n    for (i = 0; i < _operator_list.size(); i++) {\n        auto pauli_operator = _operator_list[i];\n        for (j = 0; j < terms.size(); j++) {\n            auto target_operator = terms[j];\n            auto pauli_x = pauli_operator->get_x_bits();\n            auto pauli_z = pauli_operator->get_z_bits();\n            auto target_x = target_operator->get_x_bits();\n            auto target_z = target_operator->get_z_bits();\n            if (pauli_x.size() != target_x.size()) {\n                UINT max_size = std::max(pauli_x.size(), target_x.size());\n                pauli_x.resize(max_size);\n                pauli_z.resize(max_size);\n                target_x.resize(max_size);\n                target_z.resize(max_size);\n            }\n            if (pauli_x == target_x && pauli_z == target_z) {\n                _operator_list[i]->change_coef(_operator_list[i]->get_coef() -\n                                               target_operator->get_coef());\n            }\n        }\n    }\n    for (j = 0; j < terms.size(); j++) {\n        auto target_operator = terms[j];\n        bool flag = true;\n        for (i = 0; i < _operator_list.size(); i++) {\n            auto pauli_operator = _operator_list[i];\n            auto pauli_x = pauli_operator->get_x_bits();\n            auto pauli_z = pauli_operator->get_z_bits();\n            auto target_x = target_operator->get_x_bits();\n            auto target_z = target_operator->get_z_bits();\n            if (pauli_x.size() != target_x.size()) {\n                UINT max_size = std::max(pauli_x.size(), target_x.size());\n                pauli_x.resize(max_size);\n                pauli_z.resize(max_size);\n                target_x.resize(max_size);\n                target_z.resize(max_size);\n            }\n            if (pauli_x == target_x && pauli_z == target_z) {\n                flag = false;\n            }\n        }\n        if (flag) {\n            auto copy = target_operator->copy();\n            copy->change_coef(-copy->get_coef());\n            this->add_operator(copy);\n        }\n    }\n    return *this;\n}\n\nGeneralQuantumOperator& GeneralQuantumOperator::operator-=(\n    const PauliOperator& target) {\n    bool flag = true;\n    ITYPE i;\n    for (i = 0; i < _operator_list.size(); i++) {\n        auto pauli_operator = _operator_list[i];\n        auto pauli_x = pauli_operator->get_x_bits();\n        auto pauli_z = pauli_operator->get_z_bits();\n        auto target_x = target.get_x_bits();\n        auto target_z = target.get_z_bits();\n        if (pauli_x.size() != target_x.size()) {\n            UINT max_size = std::max(pauli_x.size(), target_x.size());\n            pauli_x.resize(max_size);\n            pauli_z.resize(max_size);\n            target_x.resize(max_size);\n            target_z.resize(max_size);\n        }\n        if (pauli_x == target_x && pauli_z == target_z) {\n            _operator_list[i]->change_coef(\n                _operator_list[i]->get_coef() - target.get_coef());\n            flag = false;\n        }\n    }\n    if (flag) {\n        auto copy = target.copy();\n        copy->change_coef(-copy->get_coef());\n        this->add_operator(copy);\n    }\n    return *this;\n}\nGeneralQuantumOperator GeneralQuantumOperator::operator*(\n    const GeneralQuantumOperator& target) const {\n    auto res = this->copy();\n    *res *= target;\n    return *res;\n}\n\nGeneralQuantumOperator GeneralQuantumOperator::operator*(\n    const PauliOperator& target) const {\n    auto res = this->copy();\n    *res *= target;\n    return *res;\n}\nGeneralQuantumOperator GeneralQuantumOperator::operator*(\n    CPPCTYPE target) const {\n    auto res = this->copy();\n    *res *= target;\n    return *res;\n}\n\nGeneralQuantumOperator& GeneralQuantumOperator::operator*=(\n    const GeneralQuantumOperator& target) {\n    auto copy = this->copy();\n    _operator_list.clear();\n    auto terms = copy->get_terms();\n    auto target_terms = target.get_terms();\n    ITYPE i, j;\n#pragma omp parallel for\n    for (i = 0; i < terms.size(); i++) {\n        auto pauli_operator = terms[i];\n        for (j = 0; j < target_terms.size(); j++) {\n            auto target_operator = target_terms[j];\n            PauliOperator* product = new PauliOperator;\n            *product = (*pauli_operator) * (*target_operator);\n            *this += *product;\n        }\n    }\n    return *this;\n}\n\nGeneralQuantumOperator& GeneralQuantumOperator::operator*=(\n    const PauliOperator& target) {\n    auto copy = this->copy();\n    _operator_list.clear();\n    ITYPE i;\n    auto terms = copy->get_terms();\n#pragma omp parallel for\n    for (i = 0; i < terms.size(); i++) {\n        auto pauli_operator = terms[i];\n        PauliOperator* product = new PauliOperator;\n        *product = (*pauli_operator) * (target);\n        *this += *product;\n    }\n    return *this;\n}\n\nGeneralQuantumOperator& GeneralQuantumOperator::operator*=(CPPCTYPE target) {\n    ITYPE i;\n#pragma omp parallel for\n    for (i = 0; i < _operator_list.size(); i++) {\n        *_operator_list[i] *= target;\n    }\n    return *this;\n}\nnamespace quantum_operator {\nGeneralQuantumOperator* create_general_quantum_operator_from_openfermion_file(\n    std::string file_path) {\n    UINT qubit_count = 0;\n    std::vector<CPPCTYPE> coefs;\n    std::vector<std::string> ops;\n\n    // loading lines and check qubit_count\n    std::string str_buf;\n    std::vector<std::string> index_list;\n\n    std::ifstream ifs;\n    std::string line;\n    ifs.open(file_path);\n\n    while (getline(ifs, line)) {\n        std::tuple<double, double, std::string> parsed_items =\n            parse_openfermion_line(line);\n        const auto coef_real = std::get<0>(parsed_items);\n        const auto coef_imag = std::get<1>(parsed_items);\n        str_buf = std::get<2>(parsed_items);\n\n        CPPCTYPE coef(coef_real, coef_imag);\n        coefs.push_back(coef);\n        ops.push_back(str_buf);\n        index_list = split(str_buf, \"IXYZ \");\n\n        for (UINT i = 0; i < index_list.size(); ++i) {\n            UINT n = std::stoi(index_list[i]) + 1;\n            if (qubit_count < n) qubit_count = n;\n        }\n    }\n    if (!ifs.eof()) {\n        std::stringstream error_message_stream;\n        error_message_stream << \"ERROR: Invalid format\";\n        throw std::runtime_error(error_message_stream.str());\n    }\n    ifs.close();\n\n    GeneralQuantumOperator* general_quantum_operator =\n        new GeneralQuantumOperator(qubit_count);\n\n    for (UINT i = 0; i < ops.size(); ++i) {\n        general_quantum_operator->add_operator(\n            new PauliOperator(ops[i].c_str(), coefs[i]));\n    }\n\n    return general_quantum_operator;\n}\n\nGeneralQuantumOperator* create_general_quantum_operator_from_openfermion_text(\n    std::string text) {\n    UINT qubit_count = 0;\n    std::vector<CPPCTYPE> coefs;\n    std::vector<std::string> ops;\n\n    std::string str_buf;\n    std::vector<std::string> index_list;\n\n    std::vector<std::string> lines;\n    lines = split(text, \"\\n\");\n    for (std::string line : lines) {\n        std::tuple<double, double, std::string> parsed_items =\n            parse_openfermion_line(line);\n        const auto coef_real = std::get<0>(parsed_items);\n        const auto coef_imag = std::get<1>(parsed_items);\n        str_buf = std::get<2>(parsed_items);\n\n        CPPCTYPE coef(coef_real, coef_imag);\n        coefs.push_back(coef);\n        ops.push_back(str_buf);\n        index_list = split(str_buf, \"IXYZ \");\n\n        for (UINT i = 0; i < index_list.size(); ++i) {\n            UINT n = std::stoi(index_list[i]) + 1;\n            if (qubit_count < n) qubit_count = n;\n        }\n    }\n    GeneralQuantumOperator* general_quantum_operator =\n        new GeneralQuantumOperator(qubit_count);\n\n    for (UINT i = 0; i < ops.size(); ++i) {\n        general_quantum_operator->add_operator(\n            new PauliOperator(ops[i].c_str(), coefs[i]));\n    }\n\n    return general_quantum_operator;\n}\n\nstd::pair<GeneralQuantumOperator*, GeneralQuantumOperator*>\ncreate_split_general_quantum_operator(std::string file_path) {\n    UINT qubit_count = 0;\n    std::vector<CPPCTYPE> coefs;\n    std::vector<std::string> ops;\n\n    std::ifstream ifs;\n    ifs.open(file_path);\n\n    if (!ifs) {\n        std::stringstream error_message_stream;\n        error_message_stream << \"ERROR: Cannot open file\";\n        throw std::runtime_error(error_message_stream.str());\n    }\n\n    // loading lines and check qubit_count\n    std::string str_buf;\n    std::vector<std::string> index_list;\n\n    std::string line;\n    while (getline(ifs, line)) {\n        std::tuple<double, double, std::string> parsed_items =\n            parse_openfermion_line(line);\n        const auto coef_real = std::get<0>(parsed_items);\n        const auto coef_imag = std::get<1>(parsed_items);\n        str_buf = std::get<2>(parsed_items);\n        if (str_buf == (std::string)NULL) {\n            continue;\n        }\n        CPPCTYPE coef(coef_real, coef_imag);\n        coefs.push_back(coef);\n        ops.push_back(str_buf);\n        index_list = split(str_buf, \"IXYZ \");\n\n        for (UINT i = 0; i < index_list.size(); ++i) {\n            UINT n = std::stoi(index_list[i]) + 1;\n            if (qubit_count < n) qubit_count = n;\n        }\n    }\n    if (!ifs.eof()) {\n        std::stringstream error_message_stream;\n        error_message_stream << \"ERROR: Invalid format\";\n        throw std::runtime_error(error_message_stream.str());\n    }\n    ifs.close();\n\n    GeneralQuantumOperator* general_quantum_operator_diag =\n        new GeneralQuantumOperator(qubit_count);\n    GeneralQuantumOperator* general_quantum_operator_non_diag =\n        new GeneralQuantumOperator(qubit_count);\n\n    for (UINT i = 0; i < ops.size(); ++i) {\n        if (ops[i].find(\"X\") != std::string::npos ||\n            ops[i].find(\"Y\") != std::string::npos) {\n            general_quantum_operator_non_diag->add_operator(\n                new PauliOperator(ops[i].c_str(), coefs[i]));\n        } else {\n            general_quantum_operator_diag->add_operator(\n                new PauliOperator(ops[i].c_str(), coefs[i]));\n        }\n    }\n\n    return std::make_pair(\n        general_quantum_operator_diag, general_quantum_operator_non_diag);\n}\n}  // namespace quantum_operator\n\nbool check_Pauli_operator(const GeneralQuantumOperator* quantum_operator,\n    const PauliOperator* pauli_operator) {\n    auto vec = pauli_operator->get_index_list();\n    UINT val = 0;\n    if (vec.size() > 0) {\n        val = std::max(val, *std::max_element(vec.begin(), vec.end()));\n    }\n    return val < (quantum_operator->get_qubit_count());\n}\n\nstd::string GeneralQuantumOperator::to_string() const {\n    std::stringstream os;\n    auto term_count = this->get_term_count();\n    for (UINT index = 0; index < term_count; index++) {\n        os << this->get_term(index)->get_coef() << \" \";\n        os << this->get_term(index)->get_pauli_string();\n        if (index != term_count - 1) {\n            os << \" + \";\n        }\n    }\n    return os.str();\n}\n", "meta": {"hexsha": "78c60e1abc7413ed787462984421c26b911221c0", "size": 30832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppsim/general_quantum_operator.cpp", "max_stars_repo_name": "sdual/qulacs-osaka", "max_stars_repo_head_hexsha": "9e0396214304ada98123e5ce3aab56ea661165af", "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/cppsim/general_quantum_operator.cpp", "max_issues_repo_name": "sdual/qulacs-osaka", "max_issues_repo_head_hexsha": "9e0396214304ada98123e5ce3aab56ea661165af", "max_issues_repo_licenses": ["MIT"], "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/cppsim/general_quantum_operator.cpp", "max_forks_repo_name": "sdual/qulacs-osaka", "max_forks_repo_head_hexsha": "9e0396214304ada98123e5ce3aab56ea661165af", "max_forks_repo_licenses": ["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.1877934272, "max_line_length": 97, "alphanum_fraction": 0.6256486767, "num_tokens": 7504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.18472682669825868}}
{"text": "#include <alien/kernels/mtl/algebra/MTLInternalLinearAlgebra.h>\n\n#include <alien/core/backend/LinearAlgebraT.h>\n\n#include <alien/kernels/mtl/data_structure/MTLInternal.h>\n#include <alien/kernels/mtl/data_structure/MTLMatrix.h>\n#include <alien/kernels/mtl/data_structure/MTLVector.h>\n#include <alien/kernels/mtl/MTLBackEnd.h>\n#include <boost/numeric/mtl/mtl.hpp>\n\n#include <alien/core/impl/MultiMatrixImpl.h>\n#include <alien/core/impl/MultiVectorImpl.h>\n\n#include <arccore/base/NotImplementedException.h>\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nnamespace Alien {\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\ntemplate class ALIEN_EXTERNAL_PACKAGES_EXPORT LinearAlgebra<BackEnd::tag::mtl>;\n\nIInternalLinearAlgebra<MTLMatrix, MTLVector>*\nMTLInternalLinearAlgebraFactory()\n{\n  return new MTLInternalLinearAlgebra();\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nMTLInternalLinearAlgebra::MTLInternalLinearAlgebra()\n{\n  // Devrait faire le MTLInitialize qui est actuellement dans le solveur\n  // Attention, cette initialisation serait globale et non restreinte \u00e0 cet objet\n}\n\n/*---------------------------------------------------------------------------*/\n\nMTLInternalLinearAlgebra::~MTLInternalLinearAlgebra()\n{\n}\n\n/*---------------------------------------------------------------------------*/\n\nArccore::Real\nMTLInternalLinearAlgebra::norm0(const Vector& x) const\n{\n  return infinity_norm(x.internal()->m_internal);\n}\n\n/*---------------------------------------------------------------------------*/\n\nArccore::Real\nMTLInternalLinearAlgebra::norm1(const Vector& x) const\n{\n  return one_norm(x.internal()->m_internal);\n}\n\n/*---------------------------------------------------------------------------*/\n\nArccore::Real\nMTLInternalLinearAlgebra::norm2(const Vector& x) const\n{\n  return two_norm(x.internal()->m_internal);\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::mult(const Matrix& a, const Vector& x, Vector& r) const\n{\n  r.internal()->m_internal = a.internal()->m_internal * x.internal()->m_internal;\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::axpy(\n    Real alpha, const Vector& x, Vector& r) const\n{\n  r.internal()->m_internal += alpha * x.internal()->m_internal;\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::aypx(\n    Real alpha, Vector& y, const Vector& x) const\n{\n  throw Arccore::NotImplementedException(\n      A_FUNCINFO, \"MTLInternalLinearAlgebra::aypx not implemented\");\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::copy(const Vector& x, Vector& r) const\n{\n  r.internal()->m_internal = x.internal()->m_internal;\n}\n\n/*---------------------------------------------------------------------------*/\n\nArccore::Real\nMTLInternalLinearAlgebra::dot(const Vector& x, const Vector& y) const\n{\n  return dot_real(x.internal()->m_internal, y.internal()->m_internal);\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::scal(Real alpha, Vector& x) const\n{\n  throw Arccore::NotImplementedException(\n      A_FUNCINFO, \"MTLInternalLinearAlgebra::scal not implemented\");\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::diagonal(const Matrix& a, Vector& x) const\n{\n  throw Arccore::NotImplementedException(\n      A_FUNCINFO, \"MTLInternalLinearAlgebra::diagonal not implemented\");\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::reciprocal(Vector& x) const\n{\n  throw Arccore::NotImplementedException(\n      A_FUNCINFO, \"MTLInternalLinearAlgebra::reciprocal not implemented\");\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::pointwiseMult(const Vector& x, const Vector& y, Vector& w) const\n{\n  throw Arccore::NotImplementedException(\n      A_FUNCINFO, \"MTLInternalLinearAlgebra::pointwiseMult not implemented\");\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid\nMTLInternalLinearAlgebra::mult(\n    const Matrix& a, const UniqueArray<Real>& x, UniqueArray<Real>& r) const\n{\n  throw NotImplementedException(A_FUNCINFO, \"LinearAlgebra::mult not implemented\");\n}\nvoid\nMTLInternalLinearAlgebra::axpy(\n    Real alpha, const UniqueArray<Real>& x, UniqueArray<Real>& r) const\n{\n  throw NotImplementedException(A_FUNCINFO, \"LinearAlgebra::axpy not implemented\");\n}\nvoid\nMTLInternalLinearAlgebra::aypx(\n    Real alpha, UniqueArray<Real>& y, const UniqueArray<Real>& x) const\n{\n  throw NotImplementedException(A_FUNCINFO, \"LinearAlgebra::aypx not implemented\");\n}\nvoid\nMTLInternalLinearAlgebra::copy(const UniqueArray<Real>& x, UniqueArray<Real>& r) const\n{\n  throw NotImplementedException(A_FUNCINFO, \"LinearAlgebra::copy not implemented\");\n}\nReal\nMTLInternalLinearAlgebra::dot(\n    Integer local_size, const UniqueArray<Real>& x, const UniqueArray<Real>& y) const\n{\n  throw NotImplementedException(A_FUNCINFO, \"LinearAlgebra::dot not implemented\");\n  return Real();\n}\nvoid\nMTLInternalLinearAlgebra::scal(Real alpha, UniqueArray<Real>& x) const\n{\n  throw NotImplementedException(A_FUNCINFO, \"HypreLinearAlgebra::scal not implemented\");\n}\n\n} // END_NAMESPACE\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n", "meta": {"hexsha": "6c187e23c5bb69cedb3241a6183f4acd2dde83d6", "size": 6014, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/external_packages/src/alien/kernels/mtl/algebra/MTLInternalLinearAlgebra.cc", "max_stars_repo_name": "cedricga91/alien_legacy_plugins", "max_stars_repo_head_hexsha": "459701026d76dbe1e8a6b20454f6b50ec9722f7f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T09:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T14:22:35.000Z", "max_issues_repo_path": "modules/external_packages/src/alien/kernels/mtl/algebra/MTLInternalLinearAlgebra.cc", "max_issues_repo_name": "cedricga91/alien_legacy_plugins", "max_issues_repo_head_hexsha": "459701026d76dbe1e8a6b20454f6b50ec9722f7f", "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": "modules/external_packages/src/alien/kernels/mtl/algebra/MTLInternalLinearAlgebra.cc", "max_forks_repo_name": "cedricga91/alien_legacy_plugins", "max_forks_repo_head_hexsha": "459701026d76dbe1e8a6b20454f6b50ec9722f7f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-11-23T14:50:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:23:07.000Z", "avg_line_length": 31.1606217617, "max_line_length": 90, "alphanum_fraction": 0.5349185234, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061556288288, "lm_q2_score": 0.36658972940200996, "lm_q1q2_score": 0.18472682123597947}}
{"text": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <boost/format.hpp>\n#include <GL/glew.h>\n#include <GLFW/glfw3.h>\n#include <glm/glm.hpp>\n#include \"util.hpp\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace glm;\n\nconst static int WIDTH = 512;\nconst static int HEIGHT = 512;\nconst static int COUNT = 160;\nconst static int DEPTH = 1024;\nconst static int BATCH = 4;\n\nint main(int argc, char* argv[]) {\n\tif (!glfwInit()) {\n\t\tthrow runtime_error(\"Failed to initialize GLFW\");\n\t}\n\n\tglfwWindowHint(GLFW_SAMPLES, 4);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);\n\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n\tGLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, \"Render\", NULL, NULL);\n\tif (!window) {\n\t\tthrow runtime_error(\"Failed to open GLFW window\");\n\t}\n\tglfwMakeContextCurrent(window);\n\tglfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);\n\n\tglewExperimental = GL_TRUE;\n\tif (glewInit() != GLEW_OK) {\n\t\tthrow runtime_error(\"Failed to initialize GLEW\");\n\t}\n\tcheckError(\"init\");\n\n\t// motion\n\tconst unsigned char* motionData = readBMP(\"motion.bmp\");\n\tGLuint motion;\n\tglGenTextures(1, &motion);\n\tglActiveTexture(GL_TEXTURE0);\n\tglBindTexture(GL_TEXTURE_2D, motion);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, motionData);\n\tglBindImageTexture(0, motion, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA8UI);\n\tcheckError(\"motion\");\n\n\t// position\n\t/*float* positionData = new float[COUNT * COUNT * DEPTH * 4];\n\tfor (int i = 0; i < COUNT * COUNT * DEPTH; i += 4) {\n\t\tpositionData[i + 3] = 0;\n\t}*/\n\n\tGLuint position;\n\tglGenTextures(1, &position);\n\tglActiveTexture(GL_TEXTURE1);\n\tglBindTexture(GL_TEXTURE_3D, position);\n\tglTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, COUNT, COUNT, DEPTH, 0, GL_RGBA, GL_FLOAT, NULL);\n\tglBindImageTexture(1, position, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);\n\tcheckError(\"position\");\n\n\t// velocity\n\t/*float* velocityData = new float[COUNT * COUNT * 4];\n\tfor (int i = 0; i < COUNT * COUNT; i += 4) {\n\t\tvelocityData[i    ] = 0.5;\n\t\tvelocityData[i + 1] = 0;\n\t}*/\n\n\tGLuint velocity;\n\tglGenTextures(1, &velocity);\n\tglActiveTexture(GL_TEXTURE2);\n\tglBindTexture(GL_TEXTURE_3D, velocity);\n\tglTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, COUNT, COUNT, DEPTH, 0, GL_RGBA, GL_FLOAT, NULL);\n\tglBindImageTexture(2, velocity, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);\n\tcheckError(\"velocity\");\n\n\t// control\n\tfloat* controlData = new float[COUNT * COUNT * DEPTH * 4];\n\tfor (int i = 0; i < (COUNT * COUNT * DEPTH * 4); i++) {\n\t\tcontrolData[i] = float(rand()) / RAND_MAX;\n\t}\n\tGLuint control;\n\tglGenTextures(1, &control);\n\tglActiveTexture(GL_TEXTURE3);\n\tglBindTexture(GL_TEXTURE_3D, control);\n\tglTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, COUNT, COUNT, DEPTH, 0, GL_RGBA, GL_FLOAT, controlData);\n\tglBindImageTexture(3, control, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);\n\tcheckError(\"control\");\n\n\t// display\n\tGLuint display;\n\tglGenTextures(1, &display);\n\tglActiveTexture(GL_TEXTURE4);\n\tglBindTexture(GL_TEXTURE_2D, display);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);\n\tglBindImageTexture(4, display, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8UI);\n\tglGenerateMipmap(GL_TEXTURE_2D);\n\tcheckError(\"display\");\n\n\t// compute shader\n\tconst static char* computeSrc =\n\t\t#include \"compute.shader\"\n\t;\n\tGLenum computeType[] = { GL_COMPUTE_SHADER };\n\tGLuint compute = buildProgram(&computeSrc, computeType, 1);\n\tglUseProgram(compute);\n\tglUniform1i(glGetUniformLocation(compute, \"depth\"), DEPTH);\n\tglUniform1i(glGetUniformLocation(compute, \"batch\"), BATCH);\n\tglUniform2i(glGetUniformLocation(compute, \"size\"), WIDTH, HEIGHT);\n\tcheckError(\"compute\");\n\n\t// draw shader\n\tconst static char* vertexSrc =\n\t\t#include \"vertex.shader\"\n\t;\n\tconst static char* fragmentSrc =\n\t\t#include \"fragment.shader\"\n\t;\n\tconst char* drawSrc[] = { vertexSrc, fragmentSrc };\n\tGLenum drawType[] = { GL_VERTEX_SHADER, GL_FRAGMENT_SHADER };\n\tGLuint draw = buildProgram(drawSrc, drawType, 2);\n\tglUseProgram(draw);\n\tglUniform2i(glGetUniformLocation(draw, \"size\"), WIDTH, HEIGHT);\n\tcheckError(\"draw\");\n\n\t// draw data\n\tGLuint vertexArray;\n\tglGenVertexArrays(1, &vertexArray);\n\tglBindVertexArray(vertexArray);\n\n\tconst static GLfloat vertexData[] = {\n\t\t-1.0f, -1.0f,\n\t\t-1.0f,  1.0f,\n\t\t 1.0f, -1.0f,\n\t\t 1.0f,  1.0f\n\t};\n\n\tGLuint vertexBuffer;\n\tglGenBuffers(1, &vertexBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);\n\n\tglVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);\n\tglEnableVertexAttribArray(0);\n\tcheckError(\"vertex\");\n\n\t// main loop\n\tdouble lastTime = glfwGetTime();\n\tdouble nowTime;\n\tchar fpsTitle[32];\n\tdo {\n\t\tglUseProgram(compute);\n\t\tglDispatchCompute(COUNT / 16, COUNT / 16, 1);\n\t\tglUseProgram(draw);\n\t\tglDrawArrays(GL_TRIANGLE_STRIP, 0, sizeof(vertexData));\n\t\tglfwSwapBuffers(window);\n\t\tglfwPollEvents();\n\t\tglClearTexImage(display, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);\n\n\t\tnowTime = glfwGetTime();\n\t\tsprintf(fpsTitle, \"Render - FPS: %.2f\", 1 / (nowTime - lastTime));\n\t\tglfwSetWindowTitle(window, fpsTitle);\n\t\tlastTime = nowTime;\n\t} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "662155844d84ed670ce61ec111d0371e380369fe", "size": 5270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "motion-field-texture-synthesis/main.cpp", "max_stars_repo_name": "Preffer/motion-field-texture-synthesis", "max_stars_repo_head_hexsha": "6e5639e1f9026bfcd81d8f972efda94729e0efd1", "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": "motion-field-texture-synthesis/main.cpp", "max_issues_repo_name": "Preffer/motion-field-texture-synthesis", "max_issues_repo_head_hexsha": "6e5639e1f9026bfcd81d8f972efda94729e0efd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "motion-field-texture-synthesis/main.cpp", "max_forks_repo_name": "Preffer/motion-field-texture-synthesis", "max_forks_repo_head_hexsha": "6e5639e1f9026bfcd81d8f972efda94729e0efd1", "max_forks_repo_licenses": ["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.6395348837, "max_line_length": 100, "alphanum_fraction": 0.7290322581, "num_tokens": 1517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.18466529540868526}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <numeric>\n#include <limits>\n#include <boost/timer.hpp>\n#include <sys/stat.h>\n#include <errno.h>\n#include <string.h>\n#include <omp.h>\n\n#include \"absmc3D.h\"\n\nusing namespace absmc;\nusing namespace absmc::graphics;\n\nusing util::createFileName;\nusing util::parseFileName;\nusing util::config;\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\ntypedef AgentBase<3> agent_t;\ntypedef Point<3, double> point_t;\n\nclass FSetState : public std::binary_function<size_t, agent_t, void> {\npublic:\n    void operator()(size_t id, agent_t* agentBase) {\n        SMC3D* agent = dynamic_cast<SMC3D*>(agentBase);\n        if (agent) { agent->setState(SMC3D::SG2M); }\n    }\n};\n\n/// This executable is outdated. Use at your own risk\n/// main\nint main(int argc, char *argv[])\n{\n    if (argc!=3) {\n        cout << \"Usage: runStandAlone configDir outputRoot\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    const std::string configDir(argv[1]);\n    const std::string outputRoot(argv[2]);\n    if (mkdir(outputRoot.c_str(),0755)==-1 && errno != EEXIST) {\n    cout<<\"miserably failed to create outputRoot <\" << outputRoot << \">: \"<<((std::string)strerror(errno)) << endl;\n    return 1;\n    }\n\n    if (mkdir((outputRoot+\"/data.runStandAlone\").c_str(),0755)==-1 && errno != EEXIST) {cout<<\"miserably failed to create data.runStandAlone <\" << outputRoot << \"/data.runStandAlone>: \"<<((std::string)strerror(errno)) << endl; return 1; }\n    const std::string outputDir = createFileName(outputRoot, \"data.runStandAlone\", \"\");\n\n    const std::string configFileName  = createFileName(configDir, \"absmc\", \"cfg\");\n    config().readFile(configFileName);\n\n    // agent input files\n    const std::string inFileName = config().getValue<std::string>(\"run_input_file\");\n    const std::string baseName = parseFileName(inFileName).baseName;\n\n    // morse potential parameters (dimensionless)\n    const double U1 = config().getValue<double>(\"U1\");\n    const double r1 = config().getValue<double>(\"r1\");\n    const double U2 = config().getValue<double>(\"U2\");\n    const double r2 = config().getValue<double>(\"r2\");\n    // equilibrium distance (dimensionless)\n    const double r0 = r1*r2/(r2-r1)*log(U1/U2*r2/r1);\n    // characteristic length scale\n    const double L = config().getValue<double>(\"smc_mean_rad\");\n    // boundary range\n    const double BR = config().getValue<double>(\"Boundary_Inactivity_Range\");\n\n    // load agents from file; includes smc+iel+obstacle agents\n    AgentContainer<3> agents;\n    AgentFileReader<3>::readFile(createFileName(configDir, \"stage3.\"+baseName, \"dat\"), AgentFactory3D(), agents);\n    cout << agents.count() << \" agents loaded.\" << endl;\n\n    // initialise neighbourhoods\n    AccumulativeNeighbourDetector<agent_t> nbDetector(r0*L);\n    const std::string nbFileName = createFileName(configDir, \"stage3.\"+baseName+\"_nb\", \"dat\");\n    NBReader<3>::readFile(nbFileName, agents);\n\n    // set agents at longitudinal (x) domain boundaries immobile;\n    const double lX = config().getValue<double>(\"lX\");\n    const double mX = config().getValue<double>(\"run_boundary_mobility_x\");\n    const double mY = config().getValue<double>(\"run_boundary_mobility_y\");\n    const double mZ = config().getValue<double>(\"run_boundary_mobility_z\");\n    agents.forAll(PSelectCloseToBoundary<agent_t>(0, 0.0, lX, BR), FSetMobility<agent_t>(point_t(mX, mY, mZ) ) );\n\n    //ADDED set mobility of EEL AND SMCS to zero\n    agents.forAll(tEEL3D, FSetMobility<agent_t>(point_t(0.0, 0.0, 0.0) ) );\n    agents.forAll(tIEL3D, FSetMobility<agent_t>(point_t(0.0, 0.0, 0.0) ) );\n//    agents.forAll(tSMC3D, FSetMobility<agent_t>(point_t(0.0, 0.0, 0.0) ) );\n\n    // set SMC agents at longitudinal (x) domain boundaries and at the outer surface biologically inactive\n    agents.forAll(PSelectCloseToBoundary<agent_t>(0, 0.0, lX, BR), FSetSMC3DInactive() );\n    // set rules for SMC agents; no rules for IEL agents.\n    const double smcMaxStress = config().getValue<double>(\"smc_max_stress\");\n    SMCNecrosisRule3D smcNecrosisRule(smcMaxStress);\n\n    const double ciWeightSMC          = config().getValue<double>(\"ci_weight_smc\");\n    const double ciWeightIEL          = config().getValue<double>(\"ci_weight_iel\");\n    const double ciWeightEEL          = config().getValue<double>(\"ci_weight_eel\");\n    const double ciWeightObstacle     = config().getValue<double>(\"ci_weight_obstacle\");\n    const double ciRangeFactor        = config().getValue<double>(\"ci_range_factor\");\n    const double ciThresholdCount     = config().getValue<double>(\"ci_threshold_count\");\n    const double ciRange = ciRangeFactor*r0*L;\n    NeighbourCache<agent_t>* nbCacheForCiRule = 0;\n    SMCContactInhibitionRule3D smcContactInhibitionRule(ciWeightSMC, ciWeightIEL, ciWeightEEL, ciWeightObstacle, ciRange, ciThresholdCount, &nbCacheForCiRule);\n\n    const double drugConcThreshold    = config().getValue<double>(\"smc_drug_conc_threshold\");\n    const double wssMaxThreshold      = config().getValue<double>(\"smc_wss_max_threshold\");\n    SMCCellCycleRule3D smcCellCycleRule(drugConcThreshold, wssMaxThreshold);\n\n    //pretending we have a blood flow code running\n\n\n    //    logger::info(\"Sizes nagents=%d, OSI=%d, WSS=%d, Drug=%d\",nAgents,dataWssOsi.size(),dataWssMax.size(),dataDrugConc.size());\n        int timeStep = 0;\n    //new Nitric oxide rule\n    SMCNitricOxideRule3D smcNitricOxideRule3D(0.0); //is timestep defined?\n\n    CompositeRule<SMC3D> smcRule;\n//    smcRule.add(&smcNecrosisRule);\n    smcRule.add(&smcContactInhibitionRule);\n    smcRule.add(&smcCellCycleRule);\n    smcRule.add(&smcNitricOxideRule3D);\n\n    // set rules for bulk smc agents only; other smc agents are left biologically inactive with nil agent rule.\n    const double outerRadius = config().getValue<double>(\"outer_radius\");\n    agents.forAll(PSelectBulkAgentsOfSpecifiedType<agent_t>(0.0, lX, 0.0, 0.0, outerRadius, 4.0*0.5*r0*L, tSMC3D),\n                  FSetAgentRule<SMC3D>(&smcRule) );\n\n    //set initial number of SMCS in NO rule\n    smcNitricOxideRule3D.setInitial_Num_SMCs(agents.count(tSMC3D));\n/*\n    //////////////// physics parameters for Morse force (dimensionless)\n    // cell-cell stiffness at equilibrium distance is zero, so kEq is at 0.001\n    //    const double young = 0.1; //MPa\n    const double youngeq = 0.77;//0.5*young/(1.0-0.27*0.27);\n    const double B = 1.0/8.3439;//20.0*youngeq/(9.0*math::pi); //MPa = N/mm2\n    const double kEq = 0.00273753;//0.5*B*math::pi*0.000716223/L;// N/mm/L\n    // maximal time step (from rough stability estimation)\n    const double maxDt = 2.0 / kEq; // L*mm/N\n    // maximal time step passed to solver\n    const double solverMaxDt = maxDt;  // mm/N\n    // maximal displacement\n    const double solverMaxDispl = 0.05*2.0*L;// mm //0.1*0.5*r0;\n*/\n\n    //////////////// physics parameters for Morse force (dimensionless)\n    // cell-cell stiffness at equilibrium distance\n    const double kEq = 8.0;//U1/(r1*r1)*exp(-r0/r1) - U2/(r2*r2)*exp(-r0/r2);\n    // maximal time step (from rough stability estimation)\n    const double maxDt = 2.0 / kEq;;\n    // maximal time step passed to solver\n    const double solverMaxDt = 0.01*maxDt;;\n    // maximal displacement\n    const double solverMaxDispl = 0.01*0.5*r0;\n\n/*\n    //////////////// physics parameters for Morse force (dimensionless)\n    // cell-cell stiffness at equilibrium distance\n    const double B = 1.0/8.3439;\n    const double kEq = B*0.0027/0.015/0.015;//0.01/6.0/0.015;//U1/(r1*r1)*exp(-r0/r1) - U2/(r2*r2)*exp(-r0/r2);\n    // maximal time step (from rough stability estimation)\n    const double maxDt = 2.0 / kEq;;\n    // maximal time step passed to solver\n    const double solverMaxDt = 0.1*maxDt;;\n    // maximal displacement\n    const double solverMaxDispl = 0.1*0.5*r0;\n*/\n\n    cout << \"U1                = \" << U1 << endl;\n    cout << \"r1                = \" << r1 << endl;\n    cout << \"U2                = \" << U2 << endl;\n    cout << \"r2                = \" << r2 << endl;\n    cout << \"r0                = \" << r0 << endl;\n    cout << \"kEq               = \" << kEq << endl;;\n    cout << \"maxDt             = \" << maxDt << endl;\n    cout << \"solverMaxDt       = \" << solverMaxDt << endl;\n    cout << \"solverMaxDispl    = \" << solverMaxDispl << endl;\n\n    ZeroUnaryForce3D uForce;\n    Bilinear3D bForce(U1, r1, U2, r2, L);\n\n    std::ofstream integratorLogFile(createFileName(outputDir, \"fr\", \"dat\").c_str() );\n    AdaptiveEulerIntegrator<agent_t, ZeroUnaryForce3D, Bilinear3D>\n            integrator(uForce, bForce, L, solverMaxDispl, solverMaxDt, nbDetector, integratorLogFile);\n\n    // iteration parameters\n    const double iterTime = config().getValue<double>(\"run_iter_time\");\n    const int maxIter     = config().getValue<int>(\"run_max_iter\");\n    const int vtkIter     = config().getValue<int>(\"run_vtk_iter\");\n    const int datIter     = config().getValue<int>(\"run_dat_iter\");\n    FixedIntervalController fixedIntervalController(iterTime);\n\n    // system-characteristic force\n    const double charForce = kEq * r0 * 0.1;\n    // desired convergence level\n    const double eps      = config().getValue<double>(\"run_convergence_level\");\n\n    cout << \"charForce         = \" << charForce << endl;\n    cout << \"eps               = \" << eps << endl;\n    //cahrForce*eps = 0.000108268 for morse seems like 0.00005 for beyondhertz (already multiplied by 0.015, still need to apply B).\n    ForceResidualMaxNormController frMaxNormController(std::numeric_limits<double>::infinity(), charForce, eps);\n\n    // vtp output parameters\n    const std::string vtpScalars = config().getValue<std::string>(\"run_vtp_scalars\");\n    const std::string vtpVectors = config().getValue<std::string>(\"run_vtp_vectors\");\n\n    boost::timer timer;\n    double tIter = 0.0;\n    double tTotal = 0.0;\n    double omptimefinal = 0.0;\n\n    double omptime = omp_get_wtime();\n\n    // main loop\n\n    timeStep = 0;\n    int newSMCs = 0;\n    smcNitricOxideRule3D.setNewSMCCounter(newSMCs);\n\n    int oldNumOfSMCs = agents.count(tSMC3D);\n    int newNumOfSMCs = oldNumOfSMCs;\n    int selectedSMCs = 0;\n    int initial_num_SMCs = agents.count(tSMC3D);\n    double new_endothelial_probability = 0.0;\n    util::Random::init(0); //trying to control the randomness by allowing repetition\n\n\n    for (int iter=0; iter<maxIter; iter++) {\n\n        const size_t nAgents = agents.getAgentVector().size();\n        //pretending we have a blood flow code running\n        for (size_t iAgent = 0; iAgent < nAgents; iAgent++)\n        {\n            if ((agents.getAgentVector()[iAgent]->getTypeId() == tSMC3D) || (agents.getAgentVector()[iAgent]->getTypeId() == tIEL3D))\n            {\n                CellBase3D * agent;\n                agent = (CellBase3D*) agents.getAgentVector()[iAgent];\n                //        agent->setWssOsi(dataWssOsi[iAgent]);\n                agent->setWssMax(12.0);\n\n            }\n        }\n\n\n        if (iter%vtkIter==0) {\n\n            tIter = timer.elapsed();\n            tTotal += tIter;\n            omptimefinal = - omptime + omp_get_wtime();\n\n            VtkWriter<agent_t>::writeVtkPolyData(agents.getAgentVector(),\n                                                 createFileName(outputDir, baseName, \"vtp\", iter, 6),\n                                                 vtpScalars, vtpVectors);\n\n            cout << \"iter=\" << iter << \",  t(\" << vtkIter << \" it)=\";\n            cout << std::setprecision(4) << tIter << \",  t(total)=\" << tTotal;\n            cout << \",  t(omp)=\" << std::setprecision(4) << omptimefinal;\n            cout << \", nSMC=\" << agents.count(tSMC3D) << \", nIEL=\" << agents.count(tIEL3D)<< \", nEEL=\" << agents.count(tEEL3D)<< \", nSEL=\" << selectedSMCs\n            << \", nNEW=\" << newSMCs << \", prob=\" << 100.0*new_endothelial_probability << std::endl;\n\n            timer.restart();\n        }\n\n        if (datIter!=0 && iter%datIter==0) {\n            NBWriter<3>::writeFile(agents, createFileName(configDir, \"stage4.\"+baseName+\"_nb\", \"dat\") );\n            agents.writeFile(createFileName(outputDir, baseName, \"dat\", iter, 6) );\n        }\n         // set SMC agents at longitudinal (x) domain boundaries and at the outer surface biologically inactive\n        agents.forAll(PSelectCloseToBoundary<agent_t>(0, 0.0, lX, BR), FSetSMC3DInactive() );\n        // exec agent rules\n        nbCacheForCiRule = new NeighbourCache<agent_t>(agents.getAgentVector() );\n\n\n\n        double increase_rate = 0.0205/24.0;                 // considering 59% endothelium after day 3rd and 100% after 23 days. equation y=(41/20)x + 52.85. so we just take the slope, staring point is 59%.\n        //       double increase_rate = 0.41/12.0/24.0;             // considering 59% endothelium after day 3rd and 100% after 15 days. equation y=(41/12)x + 48.75. so we just take the slope, staring point is 59%.\n        //double increase_rate = 1.0/23.0/24.0;         //0.181159420289855    // considering 0% endothelium after day 0 and 100% after 23 days. equation y=(100/23)x + 0. so we just take the slope, staring point is 0%.\n        double old_endothelial_probability = 0.0;            // probability assuming a fixed number of cells. This is just used to calculate the probabilty defined in the next line.\n        //endothelial_probability = 0.0;\n        new_endothelial_probability = 0.0;            // probability that includes the newly produced SMCs, More the SMC divide into daugter cells, more the probabilty is.\n\n        if (iter <=72) {\n            increase_rate = 0.59/3.0/24.0; //going from 0 to 59% between days 0 an 3. Note: it could very well be that coverage does not end up to be exactly 59% after day 3.\n        } else {\n            increase_rate = 0.41/12.0/24.0;\n        }\n\n        if (iter <= 360) {                     // EC probabilty will be 100% after 15 days, 15x24=360\n            //old_endothelial_probability = 100.0*increase_rate/(47.15 - iter*increase_rate); //NOW iter SHOULD BE IN HOURS, VALID FOR 3 to 23, we use 100-52.85=47.15\n            //        old_endothelial_probability = 100.0*increase_rate/(51.25 - iter*increase_rate); //NOW iter SHOULD BE IN HOURS, VALID FOR 3 to 15, we use 100-48.75=51.25\n            if (iter <=72) {\n                old_endothelial_probability = increase_rate/(1.0 - iter*increase_rate); //0.001934235976789 //NOW iter SHOULD BE IN HOURS, VALID FOR 0 to 23\n            } else {\n                old_endothelial_probability = increase_rate/(1.0 - 72.0*0.59/3.0/24.0 - (iter-72.0)*increase_rate);\n            }\n            //double percent_cells_left = 47.15 - iter*increase_rate;        //VALID FOR 3 to 23, we use 100-52.85=47.15\n            //        double percent_cells_left = 51.25 - iter*increase_rate;        //VALID FOR 3 to 15, we use 100-48.75=51.25\n            double percent_cells_left = 1.0 - iter*increase_rate;    //0.936594202898551    //VALID FOR 0 to 23\n            int num_cells_left = (percent_cells_left * initial_num_SMCs); //274991.550724637679798\n            //        int newSMCs = 0;\n            //    endothelial_probability = 100.0*(old_endothelial_probability*num_cells_left/100.0 + newSMCs)/(num_cells_left + newSMCs);\n            new_endothelial_probability = old_endothelial_probability;//(old_endothelial_probability*num_cells_left + newSMCs)/(num_cells_left + newSMCs);  // this is required as the total number of SMCs are also increasing with time.\n\n            //                if (iter == 72) { /*endothelial_probability = 59.0;*/new_endothelial_probability = 59.0;}     // first step for Nakazawa et al.\n        } else { /*endothelial_probability = 100.0;*/new_endothelial_probability = 1.0; }\n\n\n        //    printf(\"endprob = %f \\n\", new_endothelial_probability);\n\n\n        if (new_endothelial_probability > 1.0) { /*endothelial_probability =100.0;*/new_endothelial_probability = 1.0; }\n\n\n        smcNitricOxideRule3D.setnew_endothelial_probability(100.0*new_endothelial_probability);\n\n        agents.execAgentRules();\n        newNumOfSMCs = agents.count(tSMC3D);\n        selectedSMCs = agents.countSelected(tSMC3D);\n        newSMCs = newNumOfSMCs - oldNumOfSMCs;\n        smcNitricOxideRule3D.setNewSMCCounter(newSMCs);\n        delete nbCacheForCiRule;\n\n        // ... and restore equilibrium\n        nbDetector.updateSlowTimeScale(agents.getAgentVector() );\n        integrator.integrate(agents.getAgentVector(), frMaxNormController);\n    }\n\n    // write the final configuration to file\n    agents.writeFile(createFileName(configDir, \"stage4.\"+baseName, \"dat\") );\n     NBWriter<3>::writeFile(agents, createFileName(configDir, \"stage4.\"+baseName+\"_nb\", \"dat\") );\n    VtkWriter<agent_t>::writeVtkPolyData(agents.getAgentVector(), createFileName(configDir, \"stage4.\"+baseName, \"vtp\"), vtpScalars, vtpVectors);\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3efc59b4e015cdb223d459e73e17014f0816db27", "size": 16717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/absmc/src/app3D/runStandAlone3D.cpp", "max_stars_repo_name": "ISR3D/ISR3D", "max_stars_repo_head_hexsha": "e4f31a2bddbedb8e2743e088ee24f865bc97ec30", "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": "kernel/absmc/src/app3D/runStandAlone3D.cpp", "max_issues_repo_name": "ISR3D/ISR3D", "max_issues_repo_head_hexsha": "e4f31a2bddbedb8e2743e088ee24f865bc97ec30", "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": "kernel/absmc/src/app3D/runStandAlone3D.cpp", "max_forks_repo_name": "ISR3D/ISR3D", "max_forks_repo_head_hexsha": "e4f31a2bddbedb8e2743e088ee24f865bc97ec30", "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.8801169591, "max_line_length": 238, "alphanum_fraction": 0.64808279, "num_tokens": 4773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.18466529540868523}}
{"text": "/* Copyright \u00a9 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// ML Data\n#include <unity/toolkits/ml_data_2/ml_data.hpp>\n#include <unity/toolkits/ml_data_2/metadata.hpp>\n#include <unity/toolkits/ml_data_2/ml_data_iterators.hpp>\n#include <unity/toolkits/ml_data_2/sframe_index_mapping.hpp>\n\n// Toolkits\n#include <unity/toolkits/nearest_neighbors/nearest_neighbors.hpp>\n#include <unity/toolkits/nearest_neighbors/ball_tree_neighbors.hpp>\n#include <unity/lib/variant_deep_serialize.hpp>\n#include <unity/lib/toolkit_util.hpp>\n#include <logger/assertions.hpp>\n#include <sframe/groupby.hpp>\n#include <sframe/sframe.hpp>\n#include <sframe/sarray.hpp>\n\n// Miscellaneous\n#include <timer/timer.hpp>\n#include <algorithm>\n#include <Eigen/SparseCore>\n#include <limits>\n#include <stack>\n#include <table_printer/table_printer.hpp>\n\nnamespace turi {\nnamespace nearest_neighbors {   \n\n#define NONE_FLAG ((size_t) -1)\n\n\n/**\n * Destructor. Make sure bad things don't happen\n */\nball_tree_neighbors::~ball_tree_neighbors(){\n\n}\n\n\n/**\n* Set options\n*/ \nvoid ball_tree_neighbors::init_options(\n  const std::map<std::string, flexible_type>& _options) { \n\n  options.create_integer_option(\"leaf_size\",\n                            \"Max number of points in a leaf node of the ball tree\",\n                            0,\n                            0,\n                            std::numeric_limits<int>::max(),\n                            true); \n\n  options.create_string_option(\"label\",\n                             \"Name of the reference dataset column with row labels.\",\n                             \"\",\n                             false);\n\n  // Set options and update model state with final option values\n  options.set_options(_options); \n  add_or_update_state(flexmap_to_varmap(options.current_option_values())); \n}\n\n\n/**\n * Train a ball tree nearest neighbors model.\n */\nvoid ball_tree_neighbors::train(const sframe& X,\n                                const std::vector<flexible_type>& ref_labels,\n                                const std::vector<dist_component_type>& composite_distance_params,\n                                const std::map<std::string, flexible_type>& opts) {\n\n  logprogress_stream << \"Starting ball tree nearest neighbors model training.\" << std::endl;\n\n  timer t;\n  double start_time = t.current_time();\n\n  // Validate the inputs.\n  init_options(opts);\n  validate_distance_components(composite_distance_params, X);\n\n  // Create the ml_data object for the reference data.\n  initialize_model_data(X, ref_labels);\n\n  // Initialize the distance components. NOTE: this needs data to be initialized\n  // first because the row slicers need the column indices to be sorted.\n  initialize_distances(); \n  \n  ASSERT_FALSE(composite_distances.empty()); \n  dist_component c = composite_distances[0];\n\n\n  if (metadata->num_dimensions() > 100) {\n    logprogress_stream << \"\\nWARNING: The computational advantage of the \"\n      << \"ball tree tends to diminish as the number of variables grows. With more \"\n      << \"than 100 variables, the ball tree may not be optimal for this dataset.\"\n      << std::endl;\n  }\n\n\n  // Figure out leaf size if the user didn't set it\n  size_t leaf_size = (size_t)options.value(\"leaf_size\");\n\n  if (leaf_size == 0) {\n    leaf_size = std::max((size_t)1000, (size_t)ceil((double)num_examples / 2048)); // max tree depth of 12\n    options.set_option(\"leaf_size\", leaf_size);\n  }\n\n  size_t min_leaves = ceil((double)num_examples / leaf_size);\n  tree_depth = ceil(log2(min_leaves)) + 1;\n  size_t num_leaves = std::max(size_t(1), size_t(std::pow(2, tree_depth - 1)));\n  size_t num_nodes = 2 * num_leaves - 1;\n\n  if (tree_depth > 12) {\n    logprogress_stream << \"\\nWARNING: The ball tree is very large. Consider \"\n      << \"increasing the leaf size to create a smaller tree and improve \"\n      << \"performance.\" << std::endl;\n  }\n\n\n  // Initialize tree and loop objects\n  if (is_dense) {\n    pivots.resize(num_nodes);     // pivot observations\n  } else {\n    pivots_sp.resize(num_nodes);\n  }\n\n  node_radii.resize(num_nodes);                      // distance from pivot to furthest node member\n  std::vector<double> first_child_radius (num_nodes, 0);  // distance from the pivot to the first child observation\n  std::vector<double> median_dist (num_nodes);   // median of distances to the first child point\n  double middle_dist;                            // the temporary container for the median distance in a node\n  membership.resize(num_examples);               // point membership in nodes\n  std::vector<double> pivot_dist(num_examples);  // distance from each point to its pivot (at the lowest tree level)\n  std::vector<double> first_child_dist(num_examples);  // distance from each point to the first child (at the lowest tree level)\n\n\n  // Set the radius and membership to 0 to start\n  for (size_t i = 0; i < num_nodes; ++i) {\n    node_radii[i] = 0;\n  }\n\n  for (size_t i = 0; i < num_examples; ++i) {\n    membership[i] = 0;\n  }\n\n  size_t num_variables = metadata->num_dimensions();\n\n  // Declare loop variables\n  DenseVector p(num_variables);      // dense pivot observation\n  DenseVector x(num_variables);      // dense generic observation\n  SparseVector x_sp(num_variables);  // sparse pivot observation\n  SparseVector p_sp(num_variables);  // sparse query observation\n\n  size_t a;                          // generic row index for a point\n  size_t idx_node;                   // index of the current node\n  size_t idx_node_start;             // index of the first node on a level\n  size_t idx_node_end;               // index of the last node on a level\n  size_t num_level_nodes;            // number of nodes on a level\n\n  // Switch for maintaining balance in the nodes. If a point is exactly on the\n  // median this toggle indicates which child node to assign it to.\n  bool first_child_median_flag = true;\n\n\n  // Choose the first pivot\n  // NOTE: for now this will be the first row of the reference data, but this\n  // should probably be chosen randomly.\n\n  if (is_dense) {\n    mld_ref.get_iterator().fill_observation(x);\n    pivots[0] = x;\n  } else {\n    mld_ref.get_iterator().fill_observation(x_sp);\n    pivots_sp[0] = x_sp;\n  }\n\n\n  table_printer table( {{\"Tree level\", 0}, {\"Elapsed Time\", 0} });\n  table.print_header();\n\n  // The main loop over levels of the tree\n  // NOTE: the second-to-last tree level creates the leaves, so the loop should\n  // end at tree_depth - 1.\n  for (size_t tree_level = 0; tree_level < (tree_depth - 1); ++tree_level) {\n\n    if (cppipc::must_cancel()) {\n      log_and_throw(\"Toolkit cancelled by user.\");\n    }\n\n    // Get the node indices for nodes on the current level\n    idx_node_start = std::pow(2, tree_level) - 1;\n    idx_node_end = std::pow(2, (tree_level + 1)) - 2;\n    num_level_nodes = idx_node_end - idx_node_start + 1;\n\n\n    // First pass over the data\n    for (auto it = mld_ref.get_iterator(); !it.done(); ++it) {\n      \n      // Get the required data\n      a = it.row_index();\n      idx_node = membership[a];\n\n      if (is_dense) {\n        p = pivots[idx_node];\n        it.fill_observation(x);\n        pivot_dist[a] = c.distance->distance(x, p);\n      \n        // find the largest distance to the pivot and index of the point\n        if (pivot_dist[a] >= node_radii[idx_node]) {\n          node_radii[idx_node] = pivot_dist[a];\n          pivots[2 * idx_node + 1] = x;\n        }\n\n      } else {  // data is not dense\n        p_sp = pivots_sp[idx_node];\n        it.fill_observation(x_sp);\n        pivot_dist[a] = c.distance->distance(x_sp, p_sp);\n\n        // find the largest distance to the pivot and index of the point\n        if (pivot_dist[a] >= node_radii[idx_node]) {\n          node_radii[idx_node] = pivot_dist[a];\n          pivots_sp[2 * idx_node + 1] = x_sp;\n        }\n      }\n    }\n\n\n    // Create vector of vectors to store the first child distances contiguously\n    // for each node.\n    std::vector<std::vector<double>> node_dists(num_level_nodes);\n    \n\n    // Second pass over the data\n    for (auto it = mld_ref.get_iterator(); !it.done(); ++it) {\n      \n      // Get the required data\n      a = it.row_index();\n      idx_node = membership[a];\n\n      if (is_dense) {\n        p = pivots[2 * idx_node + 1];\n        it.fill_observation(x);\n\n        // Find all of the distances to the first child and pick the second child\n        // as the point furthest away.\n        first_child_dist[a] = c.distance->distance(x, p);\n\n        if (first_child_dist[a] >= first_child_radius[idx_node]) {\n          first_child_radius[idx_node] = first_child_dist[a];\n          pivots[2 * idx_node + 2] = x;\n        }\n\n      } else { // data is not dense\n        p_sp = pivots_sp[2 * idx_node + 1];\n        it.fill_observation(x_sp);\n\n        // Find all of the distances to the first child and pick the second child\n        // as the point furthest away.\n        first_child_dist[a] = c.distance->distance(x_sp, p_sp);\n\n        if (first_child_dist[a] >= first_child_radius[idx_node]) {\n          first_child_radius[idx_node] = first_child_dist[a];\n          pivots_sp[2 * idx_node + 2] = x_sp;\n        }\n      }\n\n      // Keep the first child distances compiled by node for median computation\n      node_dists[idx_node - idx_node_start].push_back(first_child_dist[a]);\n    }\n\n\n    // Find the median first child distance for each node\n    for (size_t j = 0; j < num_level_nodes; ++j) {\n      if (node_dists[j].size() > 1) {\n\n        std::nth_element(node_dists[j].begin(),\n                         node_dists[j].begin() + node_dists[j].size()/2,\n                         node_dists[j].end());\n        middle_dist = node_dists[j][node_dists[j].size()/2];\n\n        // if there are an even number of elements get the median of the middle two\n        if (node_dists[j].size() % 2 == 0) {\n          std::nth_element(node_dists[j].begin(),\n                           node_dists[j].begin() + node_dists[j].size()/2 - 1,\n                           node_dists[j].end());\n          middle_dist = (middle_dist + node_dists[j][node_dists[j].size()/2 - 1]) / 2;\n        }\n\n        median_dist[j + idx_node_start] = middle_dist;\n\n      } else {\n        // set median distance to -1 so that singletons always go to second child\n        median_dist[j + idx_node_start] = -1;\n      }\n    }\n\n\n    // Third pass over the data\n    // - assign each point to a child\n    // - careful about maintaining balance here\n    for (size_t b = 0; b < num_examples; ++b) {\n      idx_node = membership[b];\n      if (first_child_dist[b] < median_dist[idx_node]) {\n        membership[b] = 2 * idx_node + 1;\n\n      } else if (first_child_dist[b] > median_dist[idx_node]) {\n        membership[b] = 2 * idx_node + 2;\n\n      } else {  // the point is exactly on the median\n          if (first_child_median_flag) {\n            membership[b] = 2 * idx_node + 1;\n            first_child_median_flag = false;\n\n          } else {\n            membership[b] = 2 * idx_node + 2;\n            first_child_median_flag = true;\n          }\n      }\n    }\n\n\n    table.print_row(tree_level, progress_time());\n\n  } // end loop over tree levels\n\n\n  // Find the radii for each of the leaf nodes\n  for (auto it = mld_ref.get_iterator(); !it.done(); ++it) {\n    \n    // Get the required data\n    a = it.row_index();\n    idx_node = membership[a];\n\n    if (is_dense) {\n      // Find the largest distance to the pivot and index of that point\n      p = pivots[idx_node];\n      it.fill_observation(x);\n      pivot_dist[a] = c.distance->distance(x, p);\n\n    } else { // data is not dense\n      // Find the largest distance to the pivot and index of that point\n      p_sp = pivots_sp[idx_node];\n      it.fill_observation(x_sp);\n      pivot_dist[a] = c.distance->distance(x_sp, p_sp);\n    }\n\n    if (pivot_dist[a] >= node_radii[idx_node]) {\n      node_radii[idx_node] = pivot_dist[a];\n    }\n  }\n\n  table.print_row(tree_depth - 1, progress_time());\n\n\n  \n  // Group the reference data by leaf node ID\n\n  // convert the reference labels to an SArray.\n  std::shared_ptr<sarray<flexible_type>> sa_ref_labels(new sarray<flexible_type>);\n  sa_ref_labels->open_for_write();\n  flex_type_enum ref_label_type = reference_labels[0].get_type();\n  sa_ref_labels->set_type(ref_label_type);\n  turi::copy(ref_labels.begin(), ref_labels.end(), *sa_ref_labels);\n  sa_ref_labels->close();\n\n  // convert membership into a shared pointer to an sarray\n  std::shared_ptr<sarray<flexible_type>> member_column(new sarray<flexible_type>);\n  member_column->open_for_write();\n  member_column->set_type(flex_type_enum::INTEGER);\n  turi::copy(membership.begin(), membership.end(), *member_column);\n  member_column->close();\n\n  // add the membership sarray as a column to the reference data and group\n  sframe sf_refs = X.add_column(sa_ref_labels, \"__nearest_neighbors_ref_label\");\n  sf_refs = sf_refs.add_column(member_column, \"__nearest_neighbors_membership\");\n  sf_refs = turi::group(sf_refs, \"__nearest_neighbors_membership\");\n\n  // extract the grouped membership vector and remove from the dataset.\n  auto member_reader = sf_refs.select_column(\"__nearest_neighbors_membership\")->get_reader();\n  std::vector<flexible_type> temp(num_examples);\n  member_reader->read_rows(0, num_examples, temp);\n  std::copy(temp.begin(), temp.end(), membership.begin());\n\n  size_t idx_member_column = sf_refs.column_index(\"__nearest_neighbors_membership\");\n  sf_refs = sf_refs.remove_column(idx_member_column);\n  \n  // extract the map of grouped row indices from the dataset.\n  auto label_reader = sf_refs.select_column(\"__nearest_neighbors_ref_label\")->get_reader();\n  std::vector<flexible_type> temp2(num_examples);\n  label_reader->read_rows(0, num_examples, temp2);\n\n  // this modifies the model's stored reference labels, *not* the vector passed to this function.\n  std::copy(temp2.begin(), temp2.end(), reference_labels.begin());\n\n  size_t idx_label_column = sf_refs.column_index(\"__nearest_neighbors_ref_label\");\n  sf_refs = sf_refs.remove_column(idx_label_column);\n\n  \n  // Re-make the ML data with the row-permuted data for storage in the model\n  mld_ref = v2::ml_data(metadata);\n  mld_ref.fill(sf_refs);\n\n\n  add_or_update_state({ {\"method\", \"ball_tree\"},\n                        {\"tree_depth\", tree_depth},\n                        {\"leaf_size\", leaf_size},\n                        {\"training_time\", t.current_time() - start_time} });\n  table.print_footer();\n}  // end the create function\n\n\n/**\n * Make predictions using an existing ball tree nearest neighbors model. \n * /note For each query point compute the distance to every reference point.\n */\nsframe ball_tree_neighbors::query(const v2::ml_data& mld_queries,\n                                  const std::vector<flexible_type>& query_labels,\n                                  const size_t k, const double radius,\n                                  const bool include_self_edges) const {\n\n  timer t;\n\n  size_t num_queries = mld_queries.size();\n  size_t num_nodes = node_radii.size();\n\n\n  // Construct the distance object pointer\n  ASSERT_FALSE(composite_distances.empty()); \n  dist_component c = composite_distances[0];\n\n  // Compute the actual number of nearest neighbors and construct the data\n  // structures to hold candidate neighbors while reference points are searched\n  size_t kstar;\n\n  if (k == NONE_FLAG) {\n    kstar = NONE_FLAG;\n  } else {\n    kstar = std::min(k, mld_ref.size());\n  }\n  \n  std::vector<neighbor_candidates> topk (num_queries,\n                    neighbor_candidates(-1, kstar, radius, include_self_edges));\n\n  parallel_for(0, num_queries, [&](size_t i) {\n    topk[i].set_label(i);\n  });\n\n\n  atomic<size_t> n_query_points = 0;\n\n  table_printer table({ {\"Query points\", 0}, {\"% Complete.\", 0}, {\"Elapsed Time\", 0}});\n  table.print_header();\n\n  in_parallel([&](size_t thread_idx, size_t num_threads) GL_GCC_ONLY(GL_HOT) {\n\n      // Find the nearest neighbors for each query point\n      // ---------------------------------------------------------------------------\n\n      size_t num_variables = metadata->num_dimensions();\n\n      DenseVector x(num_variables);  // reference observation\n      DenseVector q(num_variables);  // query observation\n      SparseVector x_sp(num_variables);  // reference observation\n      SparseVector q_sp(num_variables);  // query observation\n\n      std::stack<size_t> node_stack; // nodes that still need to be checked\n      size_t idx_node;               // node currently being checked\n      size_t idx_query;              // index of the query point\n      bool activate_node;            // indicates whether to traverse the node\n      double dist_child1;            // distance to the first child pivot of an active node\n      double dist_child2;            // distance to the second child pivot of an active node\n      size_t idx_start, idx_end;     // indicate where the reference data starts and stops for leaf nodes\n      double dist;                   // distance between a query point and a leaf reference point\n      double min_dist_possible;      // minimum possible distance between a query and a node\n\n\n      auto it_ref = mld_ref.get_iterator();\n\n      // Iterate over query points\n      for (auto it_query = mld_queries.get_iterator(thread_idx, num_threads);\n           !it_query.done(); ++it_query) {\n\n        if (cppipc::must_cancel()) {\n          log_and_throw(\"Toolkit cancelled by user.\");\n        }\n\n        ASSERT_TRUE(it_query.row_index() != NONE_FLAG);\n\n        if (is_dense) {\n          it_query.fill_observation(q);\n        } else {\n          it_query.fill_observation(q_sp);\n        }\n\n        idx_query = it_query.row_index();\n        node_stack.push(0);\n        min_dist_possible = 0;\n\n\n        // Loop over nodes in the traversal queue\n        while (!node_stack.empty()) {\n          idx_node = node_stack.top();\n          node_stack.pop();\n\n          // Compute the minimum possible distance from the query to the node\n          if (is_dense) {\n            min_dist_possible =\n                c.distance->distance(pivots[idx_node], q) - node_radii[idx_node];\n          } else {\n            min_dist_possible =\n                c.distance->distance(pivots_sp[idx_node], q_sp) - node_radii[idx_node];\n          }\n\n          // Decide if the node needs to be processed\n          activate_node = activate_query_node(kstar, radius, min_dist_possible,\n                                              topk[idx_query].candidates.size(),\n                                              topk[idx_query].get_max_dist());\n\n          if (activate_node) {\n\n            // The active node is internal\n            if (idx_node < num_nodes / 2) {\n\n              // find the closest child pivot to the query\n              if (is_dense) {\n                dist_child1 = c.distance->distance(q, pivots[2 * idx_node + 1]);\n                dist_child2 = c.distance->distance(q, pivots[2 * idx_node + 2]);\n              } else {\n                dist_child1 = c.distance->distance(q_sp, pivots_sp[2 * idx_node + 1]);\n                dist_child2 = c.distance->distance(q_sp, pivots_sp[2 * idx_node + 2]);\n              }\n\n              // add child nodes to the stack, closest on the top\n              if (dist_child1 <= dist_child2) {\n                node_stack.push(2 * idx_node + 2);\n                node_stack.push(2 * idx_node + 1);\n              } else {\n                node_stack.push(2 * idx_node + 1);\n                node_stack.push(2 * idx_node + 2);\n              }\n\n              // The active node is a leaf\n            } else {\n\n              // figure out where the leaf members are in the reference ml_data\n              idx_start = NONE_FLAG;\n              idx_end = NONE_FLAG;\n\n              for (size_t i = 0; i < membership.size(); i++) {\n                if ((idx_start == NONE_FLAG) && (membership[i] == idx_node)) {\n                  idx_start = i;\n                }\n\n                if ((idx_start != NONE_FLAG) && (membership[i] == idx_node)) {\n                  idx_end = i + 1;\n                }\n              }\n\n              DASSERT_TRUE(idx_end >= idx_start);\n\n              if ((idx_start == NONE_FLAG) || (idx_end == NONE_FLAG)) {\n                continue;  // if the node is empty, move on to the next node in the stack\n              }\n\n              for (it_ref.seek(idx_start); it_ref.row_index() != idx_end; ++it_ref) {\n\n                if (is_dense) {\n                  it_ref.fill_observation(x);\n                  dist = c.distance->distance(x, q);\n                } else {\n                  it_ref.fill_observation(x_sp);\n                  dist = c.distance->distance(x_sp, q_sp);\n                }\n\n                DASSERT_TRUE(it_ref.row_index() != NONE_FLAG);\n\n                topk[idx_query].evaluate_point(\n                    std::pair<double, size_t>(dist, it_ref.row_index()));\n\n              }  // end the loop over reference points in the leaf\n            }  // end the leaf node processing\n          } // end active node processing\n        } // end tree traversal for a given query point\n\n        size_t n_query_points_so_far = (++n_query_points);\n\n        table.print_timed_progress_row( n_query_points_so_far,\n                                        std::floor((4 * 100.0 * n_query_points_so_far) / num_queries) / 4.0,\n                                        progress_time());\n\n      }  // end the loop over query points\n    });  \n\n  table.print_row(\"Done\", \" \", progress_time());\n  table.print_footer();\n\n  sframe result = write_neighbors_to_sframe(topk, reference_labels, query_labels);\n  return result;\n}\n\n\n/**\n* Turi Serialization Save\n*/\nvoid ball_tree_neighbors::save_impl(turi::oarchive& oarc) const {\n\n  variant_deep_save(state, oarc);\n\n  std::map<std::string, variant_type> data;\n\n  data[\"membership\"]         = to_variant(membership);\n  data[\"node_radii\"]         = to_variant(node_radii);\n  data[\"tree_depth\"]         = to_variant(tree_depth);\n  data[\"is_dense\"]           = to_variant(is_dense);\n\n  variant_deep_save(data, oarc);\n\n  // Now, a few that couldn't get saved in the above map\n  oarc << pivots << pivots_sp;\n  oarc << options\n       << mld_ref\n       << composite_params\n       << untranslated_cols\n       << reference_labels;\n}\n\n\n/**\n * Turi Serialization Load\n */\nvoid ball_tree_neighbors::load_version(turi::iarchive& iarc, size_t version) {\n\n  ASSERT_MSG((version == 0) || (version == 1) || (version == 2),\n             \"This model version cannot be loaded. Please re-save your model.\");\n\n  variant_deep_load(state, iarc);\n\n  std::map<std::string, variant_type> data;\n\n  variant_deep_load(data, iarc);\n\n#define __EXTRACT(var) var = variant_get_value<decltype(var)>(data.at(#var));\n\n  __EXTRACT(membership);\n  __EXTRACT(node_radii);\n  __EXTRACT(tree_depth);\n  __EXTRACT(is_dense);\n#undef __EXTRACT\n\n  iarc >> pivots >> pivots_sp;\n  iarc >> options;\n  iarc >> mld_ref;\n\n\n\n\n  metadata = mld_ref.metadata();\n\n  // If loading from an old version, manually construct a single component that\n  // assumes a single distance across all features. This is necessary because\n  // the GLC v1.1 ball tree query operates on a set of distance components\n  // stored in the model, rather than a distance name as in GLC v1.\n  if (version == 0) {\n    auto fn = function_closure_info();\n    fn.native_fn_name = \"_distances.\";\n    fn.native_fn_name += std::string(options.value(\"distance\"));\n    std::vector<std::string> features = variant_get_value<std::vector<std::string>>(state[\"features\"]); \n    dist_component_type p = std::make_tuple(features, fn, 1.0);\n    composite_params = {p};\n\n    // set empty untranslated columns for string features.\n    untranslated_cols = {};\n  }\n\n  else {\n    iarc >> composite_params;\n    iarc >> untranslated_cols;    \n  }\n\n\n  // construct the reference labels from the target column of the reference\n  // ml_data.\n  if (version < 2) {\n    reference_labels.resize(mld_ref.size());\n\n    in_parallel([&](size_t thread_idx, size_t num_threads) {\n      for (auto it = mld_ref.get_iterator(); !it.done(); ++it) {\n        reference_labels[it.row_index()] = metadata->target_indexer()->map_index_to_value(it.target_index());\n      }\n    });\n    \n    add_or_update_state({ {\"num_distance_components\", 1} });\n  }\n\n  else {\n    iarc >> reference_labels;\n  }\n\n  initialize_distances(); \n}\n\n\n/**\n* Helper function to decide if a node should be activated for a query.\n*/\nbool ball_tree_neighbors::activate_query_node(size_t k, double radius,\n                                              double min_poss_dist,\n                                              size_t num_current_neighbors,\n                                              double max_current_dist) const {\n  bool activate = false;\n\n  if (k == NONE_FLAG) {\n\n    if (radius < 0) {         // neither k nor radius is defined\n      activate = true;\n\n    } else {                  // k is undefined, radius is defined\n      if (min_poss_dist < radius)\n        activate = true;\n    }\n\n  } else {\n      // NOTE: in future versions, the default radius will be infinity. All\n      // neighbors will be checked against radius, so the following conditional\n      // won't be needed.\n    if (radius < 0) {         // k is defined, radius is undefined\n      \n      // if the candidates set is empty, max_current_dist is -1.0, but\n      // num_current_neighbors should be 0, so this should trigger (unless k is\n      // 0). The same thing occurs when both k and radius are defined (below).\n      if ((num_current_neighbors < k) || (min_poss_dist < max_current_dist))\n        activate = true;\n    \n    } else {                  // both k and radius are defined\n      if (min_poss_dist < radius)\n       if ((min_poss_dist < max_current_dist) || (num_current_neighbors < k))\n        activate = true;\n    }\n  }\n\n  return activate;\n}\n\n}  // namespace nearest_neighbors\n}  // namespace turi\n", "meta": {"hexsha": "ab3fe51de5804b15b0648623218a1b128dc5c413", "size": 25839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/unity/toolkits/nearest_neighbors/ball_tree_neighbors.cpp", "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/ball_tree_neighbors.cpp", "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/ball_tree_neighbors.cpp", "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": 34.4979973298, "max_line_length": 128, "alphanum_fraction": 0.6228569217, "num_tokens": 6070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18466528820031858}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <vw/Mosaic/GigapanQuadTreeConfig.h>\n\n#include <boost/bind.hpp>\n\n#include <boost/filesystem/path.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/filesystem/convenience.hpp>\nnamespace fs = boost::filesystem;\n\nnamespace vw {\nnamespace mosaic {\n\n  struct GigapanQuadTreeConfigData {\n    BBox2 m_longlat_bbox;\n\n\n    std::vector<std::pair<std::string,vw::BBox2i> > branch_func( QuadTreeGenerator const&, std::string const& name, BBox2i const& region ) const;\n    void metadata_func( QuadTreeGenerator const&, QuadTreeGenerator::TileInfo const& info ) const;\n\n    public:\n      GigapanQuadTreeConfigData() : m_longlat_bbox(0, 0, 0, 0) {}\n  };\n\n  GigapanQuadTreeConfig::GigapanQuadTreeConfig()\n    : m_data( new GigapanQuadTreeConfigData() )\n  {}\n\n  std::string GigapanQuadTreeConfig::image_path( QuadTreeGenerator const& qtree, std::string const& name ) {\n    return QuadTreeGenerator::tiered_image_path()(qtree, name);\n  }\n\n  void GigapanQuadTreeConfig::configure( QuadTreeGenerator& qtree ) const {\n    qtree.set_image_path_func( &image_path );\n    qtree.set_cull_images( true );\n    qtree.set_metadata_func( boost::bind(&GigapanQuadTreeConfigData::metadata_func,m_data,_1,_2) );\n\n    if (m_data->m_longlat_bbox.width() != 0 || m_data->m_longlat_bbox.height() != 0) {\n      qtree.set_branch_func( boost::bind(&GigapanQuadTreeConfigData::branch_func,m_data,_1,_2,_3) );\n    }\n  }\n\n  void GigapanQuadTreeConfig::set_longlat_bbox( BBox2 const& bbox ) {\n    m_data->m_longlat_bbox = bbox;\n  }\n\n  std::vector<std::pair<std::string,vw::BBox2i> > GigapanQuadTreeConfigData::branch_func( QuadTreeGenerator const& qtree, std::string const& name, BBox2i const& region ) const {\n    std::vector<std::pair<std::string,vw::BBox2i> > children;\n    if( region.height() > qtree.get_tile_size() ) {\n\n      Vector2i dims = qtree.get_dimensions();\n      double aspect_ratio = 2 * (region.width()/region.height()) * ( (m_longlat_bbox.width()/dims.x()) / (m_longlat_bbox.height()/dims.y()) );\n\n      double bottom_lat = m_longlat_bbox.max().y() - region.max().y()*m_longlat_bbox.height() / dims.y();\n      double top_lat = m_longlat_bbox.max().y() - region.min().y()*m_longlat_bbox.height() / dims.y();\n      bool top_merge = ( bottom_lat > 0 ) && ( ( 1.0 / cos(M_PI/180 * bottom_lat) ) > aspect_ratio );\n      bool bottom_merge = ( top_lat < 0 ) && ( ( 1.0 / cos(M_PI/180 * top_lat) ) > aspect_ratio );\n\n      if( top_merge ) {\n        children.push_back( std::make_pair( name + \"4\", BBox2i( region.min(), region.max() - Vector2i(0,region.height()/2) ) ) );\n      }\n      else {\n        children.push_back( std::make_pair( name + \"0\", BBox2i( (region + region.min()) / 2 ) ) );\n        children.push_back( std::make_pair( name + \"1\", BBox2i( (region + Vector2i(region.max().x(),region.min().y())) / 2 ) ) );\n      }\n      if( bottom_merge ) {\n        children.push_back( std::make_pair( name + \"5\", BBox2i( region.min() + Vector2i(0,region.height()/2), region.max() ) ) );\n      }\n      else {\n        children.push_back( std::make_pair( name + \"2\", BBox2i( (region + Vector2i(region.min().x(),region.max().y())) / 2 ) ) );\n        children.push_back( std::make_pair( name + \"3\", BBox2i( (region + region.max()) / 2 ) ) );\n      }\n    }\n    return children;\n  }\n\n  void GigapanQuadTreeConfigData::metadata_func( QuadTreeGenerator const& qtree, QuadTreeGenerator::TileInfo const& info ) const {\n    bool root_node = ( info.name.size() == 0 );\n\n\n    if ( root_node) {\n      std::ostringstream json;\n      fs::path file_path( info.filepath, fs::native );\n      fs::path json_path = change_extension( file_path, \".json\" );\n\n      json << \"{\" << std::endl\n           << \"  \\\"width\\\": \" << qtree.get_dimensions()[0] << \",\" << std::endl\n           << \"  \\\"height\\\": \" << qtree.get_dimensions()[1] << \",\" << std::endl\n           << \"  \\\"nlevels\\\": \" << qtree.get_tree_levels() << std::endl\n           << \"}\" << std::endl;\n\n      fs::ofstream jsonfs(json_path);\n      jsonfs << json.str();\n    }\n  }\n\n  // TODO: Is this actually the right function for Gigapan?\n  cartography::GeoReference GigapanQuadTreeConfig::output_georef(uint32 xresolution, uint32 yresolution) {\n    if (yresolution == 0)\n      yresolution = xresolution;\n\n    VW_ASSERT(xresolution == yresolution, LogicErr() << \"TMS requires square pixels\");\n\n    cartography::GeoReference r;\n    r.set_pixel_interpretation(cartography::GeoReference::PixelAsArea);\n\n    // Note: the global TMS pixel space extends from +270 to -90\n    // latitude, so that the lower-left hand corner is tile-\n    // aligned, since TMS uses an origin in the lower left.\n    Matrix3x3 transform;\n    transform(0,0) = 360.0 / xresolution;\n    transform(0,2) = -180;\n    transform(1,1) = -360.0 / yresolution;\n    transform(1,2) = 270;\n    transform(2,2) = 1;\n    r.set_transform(transform);\n\n    return r;\n  }\n} // namespace mosaic\n} // namespace vw\n", "meta": {"hexsha": "66fc1ae8e1e8793148115791883df0745f64e44b", "size": 5128, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Mosaic/GigapanQuadTreeConfig.cc", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/Mosaic/GigapanQuadTreeConfig.cc", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.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": "src/vw/Mosaic/GigapanQuadTreeConfig.cc", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 39.7519379845, "max_line_length": 177, "alphanum_fraction": 0.6560062402, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18466528820031855}}
{"text": "// Copyright 2015-2019 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#ifndef UTILIZATION__UTIL_HPP_\n#define UTILIZATION__UTIL_HPP_\n\n#include <lanelet2_extension/utility/query.hpp>\n#include <tier4_autoware_utils/geometry/geometry.hpp>\n#include <tier4_autoware_utils/trajectory/trajectory.hpp>\n#include <utilization/boost_geometry_helper.hpp>\n\n#include <autoware_auto_perception_msgs/msg/predicted_object.hpp>\n#include <autoware_auto_perception_msgs/msg/predicted_objects.hpp>\n#include <autoware_auto_planning_msgs/msg/path.hpp>\n#include <autoware_auto_planning_msgs/msg/path_point.hpp>\n#include <autoware_auto_planning_msgs/msg/path_with_lane_id.hpp>\n#include <autoware_auto_planning_msgs/msg/trajectory.hpp>\n#include <autoware_auto_planning_msgs/msg/trajectory_point.hpp>\n#include <geometry_msgs/msg/point.hpp>\n#include <geometry_msgs/msg/pose_stamped.hpp>\n#include <geometry_msgs/msg/quaternion.hpp>\n#include <tier4_planning_msgs/msg/stop_reason.hpp>\n#include <visualization_msgs/msg/marker.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include <lanelet2_core/LaneletMap.h>\n#include <lanelet2_core/geometry/Lanelet.h>\n#include <lanelet2_core/geometry/Point.h>\n#include <lanelet2_routing/RoutingGraph.h>\n#include <pcl/point_types.h>\n#include <tf2/utils.h>\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <vector>\n\nnamespace tier4_autoware_utils\n{\ntemplate <>\ninline geometry_msgs::msg::Point getPoint(\n  const autoware_auto_planning_msgs::msg::PathPointWithLaneId & p)\n{\n  return p.point.pose.position;\n}\n}  // namespace tier4_autoware_utils\n\nnamespace behavior_velocity_planner\n{\nstruct SearchRangeIndex\n{\n  size_t min_idx;\n  size_t max_idx;\n};\nstruct DetectionRange\n{\n  bool use_right = true;\n  bool use_left = true;\n  double interval;\n  double min_longitudinal_distance;\n  double max_longitudinal_distance;\n  double min_lateral_distance;\n  double max_lateral_distance;\n};\nstruct PointWithSearchRangeIndex\n{\n  geometry_msgs::msg::Point point;\n  SearchRangeIndex index;\n};\n\nusing Point2d = boost::geometry::model::d2::point_xy<double>;\nusing autoware_auto_planning_msgs::msg::PathPoint;\nusing autoware_auto_planning_msgs::msg::PathPointWithLaneId;\nusing autoware_auto_planning_msgs::msg::PathWithLaneId;\nusing BasicPolygons2d = std::vector<lanelet::BasicPolygon2d>;\nusing Polygons2d = std::vector<Polygon2d>;\nnamespace planning_utils\n{\nusing geometry_msgs::msg::Pose;\ninline geometry_msgs::msg::Point getPoint(const geometry_msgs::msg::Point & p) { return p; }\ninline geometry_msgs::msg::Point getPoint(const geometry_msgs::msg::Pose & p) { return p.position; }\ninline geometry_msgs::msg::Point getPoint(const geometry_msgs::msg::PoseStamped & p)\n{\n  return p.pose.position;\n}\ninline geometry_msgs::msg::Point getPoint(const autoware_auto_planning_msgs::msg::PathPoint & p)\n{\n  return p.pose.position;\n}\ninline geometry_msgs::msg::Point getPoint(\n  const autoware_auto_planning_msgs::msg::PathPointWithLaneId & p)\n{\n  return p.point.pose.position;\n}\ninline geometry_msgs::msg::Point getPoint(\n  const autoware_auto_planning_msgs::msg::TrajectoryPoint & p)\n{\n  return p.pose.position;\n}\ninline geometry_msgs::msg::Pose getPose(\n  const autoware_auto_planning_msgs::msg::Path & path, int idx)\n{\n  return path.points.at(idx).pose;\n}\ninline geometry_msgs::msg::Pose getPose(\n  const autoware_auto_planning_msgs::msg::PathWithLaneId & path, int idx)\n{\n  return path.points.at(idx).point.pose;\n}\ninline geometry_msgs::msg::Pose getPose(\n  const autoware_auto_planning_msgs::msg::Trajectory & traj, int idx)\n{\n  return traj.points.at(idx).pose;\n}\n\n// create detection area from given range return false if creation failure\nbool createDetectionAreaPolygons(\n  Polygons2d & slices, const PathWithLaneId & path, const geometry_msgs::msg::Pose & current_pose,\n  const DetectionRange & da_range, const double obstacle_vel_mps, const double min_velocity = 1.0);\nPathPoint getLerpPathPointWithLaneId(const PathPoint p0, const PathPoint p1, const double ratio);\nPoint2d calculateOffsetPoint2d(const Pose & pose, const double offset_x, const double offset_y);\nvoid extractClosePartition(\n  const geometry_msgs::msg::Point position, const BasicPolygons2d & all_partitions,\n  BasicPolygons2d & close_partition, const double distance_thresh = 30.0);\nvoid getAllPartitionLanelets(const lanelet::LaneletMapConstPtr ll, BasicPolygons2d & polys);\nvoid setVelocityFrom(const size_t idx, const double vel, PathWithLaneId * input);\nvoid insertVelocity(\n  PathWithLaneId & path, const PathPointWithLaneId & path_point, const double v,\n  size_t & insert_index, const double min_distance = 0.001);\ninline int64_t bitShift(int64_t original_id) { return original_id << (sizeof(int32_t) * 8 / 2); }\n\ninline double square(const double & a) { return a * a; }\ndouble normalizeEulerAngle(double euler);\ngeometry_msgs::msg::Quaternion getQuaternionFromYaw(double yaw);\n\ntemplate <class T1, class T2>\ndouble calcSquaredDist2d(const T1 & a, const T2 & b)\n{\n  return square(getPoint(a).x - getPoint(b).x) + square(getPoint(a).y - getPoint(b).y);\n}\n\ntemplate <class T1, class T2>\ndouble calcDist2d(const T1 & a, const T2 & b)\n{\n  return std::sqrt(calcSquaredDist2d<T1, T2>(a, b));\n}\n\ntemplate <class T>\nbool calcClosestIndex(\n  const T & path, const geometry_msgs::msg::Pose & pose, int & closest, double dist_thr = 3.0,\n  double angle_thr = M_PI_4);\n\ntemplate <class T>\nbool calcClosestIndex(\n  const T & path, const geometry_msgs::msg::Point & point, int & closest, double dist_thr = 3.0);\n\ngeometry_msgs::msg::Pose transformRelCoordinate2D(\n  const geometry_msgs::msg::Pose & target, const geometry_msgs::msg::Pose & origin);\ngeometry_msgs::msg::Pose transformAbsCoordinate2D(\n  const geometry_msgs::msg::Pose & relative, const geometry_msgs::msg::Pose & origin);\nSearchRangeIndex getPathIndexRangeIncludeLaneId(\n  const autoware_auto_planning_msgs::msg::PathWithLaneId & path, const int64_t lane_id);\n/**\n * @brief find nearest segment index with search range\n */\ntemplate <class T>\nsize_t findNearestSegmentIndex(const T & points, const PointWithSearchRangeIndex & point_with_index)\n{\n  const auto & index = point_with_index.index;\n  const auto point = point_with_index.point;\n\n  tier4_autoware_utils::validateNonEmpty(points);\n\n  double min_dist = std::numeric_limits<double>::max();\n  size_t nearest_idx = 0;\n\n  for (size_t i = index.min_idx; i <= index.max_idx; ++i) {\n    const auto dist = tier4_autoware_utils::calcSquaredDistance2d(points.at(i), point);\n    if (dist < min_dist) {\n      min_dist = dist;\n      nearest_idx = i;\n    }\n  }\n\n  if (nearest_idx == 0) {\n    return 0;\n  }\n  if (nearest_idx == points.size() - 1) {\n    return points.size() - 2;\n  }\n\n  const double signed_length =\n    tier4_autoware_utils::calcLongitudinalOffsetToSegment(points, nearest_idx, point);\n\n  if (signed_length <= 0) {\n    return nearest_idx - 1;\n  }\n\n  return nearest_idx;\n}\n/**\n * @brief find nearest segment index within distance threshold\n */\ntemplate <class T>\nPointWithSearchRangeIndex findFirstNearSearchRangeIndex(\n  const T & points, const geometry_msgs::msg::Point & point, const double distance_thresh = 9.0)\n{\n  tier4_autoware_utils::validateNonEmpty(points);\n\n  bool min_idx_found = false;\n  PointWithSearchRangeIndex point_with_range = {point, {static_cast<size_t>(0), points.size() - 1}};\n  for (size_t i = 0; i < points.size(); i++) {\n    const auto & p = points.at(i).point.pose.position;\n    const double dist = std::hypot(point.x - p.x, point.y - p.y);\n    if (dist < distance_thresh) {\n      if (!min_idx_found) {\n        point_with_range.index.min_idx = i;\n        min_idx_found = true;\n      }\n      point_with_range.index.max_idx = i;\n    }\n  }\n  return point_with_range;\n}\n/**\n * @brief calcSignedArcLength from point to point with search range\n */\ntemplate <class T>\ndouble calcSignedArcLengthWithSearchIndex(\n  const T & points, const PointWithSearchRangeIndex & src_point_with_range,\n  const PointWithSearchRangeIndex & dst_point_with_range)\n{\n  tier4_autoware_utils::validateNonEmpty(points);\n  const size_t src_idx = planning_utils::findNearestSegmentIndex(points, src_point_with_range);\n  const size_t dst_idx = planning_utils::findNearestSegmentIndex(points, dst_point_with_range);\n  const double signed_length = tier4_autoware_utils::calcSignedArcLength(points, src_idx, dst_idx);\n  const double signed_length_src_offset = tier4_autoware_utils::calcLongitudinalOffsetToSegment(\n    points, src_idx, src_point_with_range.point);\n  const double signed_length_dst_offset = tier4_autoware_utils::calcLongitudinalOffsetToSegment(\n    points, dst_idx, dst_point_with_range.point);\n  return signed_length - signed_length_src_offset + signed_length_dst_offset;\n}\nPolygon2d toFootprintPolygon(const autoware_auto_perception_msgs::msg::PredictedObject & object);\nbool isAheadOf(const geometry_msgs::msg::Pose & target, const geometry_msgs::msg::Pose & origin);\nPolygon2d generatePathPolygon(\n  const autoware_auto_planning_msgs::msg::PathWithLaneId & path, const size_t start_idx,\n  const size_t end_idx, const double width);\n\ndouble calcJudgeLineDistWithAccLimit(\n  const double velocity, const double max_stop_acceleration, const double delay_response_time);\n\ndouble calcJudgeLineDistWithJerkLimit(\n  const double velocity, const double acceleration, const double max_stop_acceleration,\n  const double max_stop_jerk, const double delay_response_time);\n\ndouble calcDecelerationVelocityFromDistanceToTarget(\n  const double max_slowdown_jerk, const double max_slowdown_accel, const double current_accel,\n  const double current_velocity, const double distance_to_target);\n\ndouble findReachTime(\n  const double jerk, const double accel, const double velocity, const double distance,\n  const double t_min, const double t_max);\n\ntier4_planning_msgs::msg::StopReason initializeStopReason(const std::string & stop_reason);\n\nvoid appendStopReason(\n  const tier4_planning_msgs::msg::StopFactor stop_factor,\n  tier4_planning_msgs::msg::StopReason * stop_reason);\n\nstd::vector<geometry_msgs::msg::Point> toRosPoints(\n  const autoware_auto_perception_msgs::msg::PredictedObjects & object);\n\ngeometry_msgs::msg::Point toRosPoint(const pcl::PointXYZ & pcl_point);\ngeometry_msgs::msg::Point toRosPoint(const Point2d & boost_point, const double z);\n\nLineString2d extendLine(\n  const lanelet::ConstPoint3d & lanelet_point1, const lanelet::ConstPoint3d & lanelet_point2,\n  const double & length);\n\ntemplate <class T>\nstd::vector<T> concatVector(const std::vector<T> & vec1, const std::vector<T> & vec2)\n{\n  auto concat_vec = vec1;\n  concat_vec.insert(std::end(concat_vec), std::begin(vec2), std::end(vec2));\n  return concat_vec;\n}\n\n}  // namespace planning_utils\n}  // namespace behavior_velocity_planner\n\n#endif  // UTILIZATION__UTIL_HPP_\n", "meta": {"hexsha": "d7a029f818fd765ceb2f983b4e09c7a1fbe60bb9", "size": 11348, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "planning/behavior_velocity_planner/include/utilization/util.hpp", "max_stars_repo_name": "kaancolak/autoware.universe", "max_stars_repo_head_hexsha": "7b5b88dc902b64401bb4c352348f52030cde0db4", "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": "planning/behavior_velocity_planner/include/utilization/util.hpp", "max_issues_repo_name": "kaancolak/autoware.universe", "max_issues_repo_head_hexsha": "7b5b88dc902b64401bb4c352348f52030cde0db4", "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": "planning/behavior_velocity_planner/include/utilization/util.hpp", "max_forks_repo_name": "kaancolak/autoware.universe", "max_forks_repo_head_hexsha": "7b5b88dc902b64401bb4c352348f52030cde0db4", "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.0849673203, "max_line_length": 100, "alphanum_fraction": 0.7768769827, "num_tokens": 2876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18466528820031855}}
{"text": "/*\n\tTest case for ticket #7951\n\ttests whether or not xxx() == xxx(0) for various engines\n\tThanks to Stephen T. Lavavej for his close reading of 26.5.3.3 [rand.eng.sub]/7 \n*/\n\n#include <boost/random/ranlux.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4244)\n#endif\n\nBOOST_AUTO_TEST_CASE(test_zero_seed)\n{\n    BOOST_CHECK(boost::random::ranlux24_base(0) == boost::random::ranlux24_base()); \n    BOOST_CHECK(boost::random::minstd_rand0(0)  == boost::random::minstd_rand0()); \n    BOOST_CHECK(boost::random::mt19937(0)       != boost::random::mt19937()); \n\n    BOOST_CHECK(boost::random::ranlux48_base(0) == boost::random::ranlux48_base ()); \n\n    BOOST_CHECK(boost::random::ranlux_base_01(0) == boost::random::ranlux_base_01 ()); \n    BOOST_CHECK(boost::random::ranlux64_base_01(0) == boost::random::ranlux64_base_01 ()); \n}\n", "meta": {"hexsha": "983f395ba9d18d141ac1d667c2b274145d74c90f", "size": 1000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/random/test/test_zero_seed.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/random/test/test_zero_seed.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/random/test/test_zero_seed.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": 33.3333333333, "max_line_length": 91, "alphanum_fraction": 0.723, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.1846652845961353}}
{"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_BLOCK_CIPHER_STATE_HPP\n#define CRYPTO3_BLOCK_CIPHER_STATE_HPP\n\n#include <boost/accumulators/framework/accumulator_set.hpp>\n#include <boost/accumulators/framework/features.hpp>\n\n#include <boost/crypto3/block/accumulators/block.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace block {\n            /*!\n             * @brief Accumulator set with pre-defined block cipher accumulator params.\n             *\n             * Meets the requirements of AccumulatorSet\n             *\n             * @ingroup block\n             *\n             * @tparam Mode Cipher state preprocessing mode type (e.g. isomorphic_encryption_mode<aes128>)\n             * @tparam Endian\n             * @tparam ValueBits\n             * @tparam LengthBits\n             */\n            template<typename ProcessingMode>\n            using accumulator_set = boost::accumulators::accumulator_set<\n                digest<ProcessingMode::block_bits>,\n                boost::accumulators::features<accumulators::tag::block<ProcessingMode>>, std::size_t>;\n        }    // namespace block\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_BLOCK_CIPHER_STATE_HPP\n", "meta": {"hexsha": "7f7e22a3fe696909fab3a4016609bf385d318975", "size": 1563, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/block/cipher_state.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/block/cipher_state.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/block/cipher_state.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": 38.1219512195, "max_line_length": 106, "alphanum_fraction": 0.5815738964, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.1846652845961352}}
{"text": "/*    Copyright (c) 2010-2018, 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 <iostream>\n\n#include <boost/make_shared.hpp>\n#include <boost/lambda/lambda.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/coordinateConversions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createBodies.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\nusing namespace ephemerides;\nusing namespace gravitation;\n\n//! Function that determines the order in which bodies are to be created\nstd::vector< std::pair< std::string, std::shared_ptr< BodySettings > > > determineBodyCreationOrder(\n        const std::map< std::string, std::shared_ptr< BodySettings > >& bodySettings )\n{\n    std::vector< std::pair< std::string, std::shared_ptr< BodySettings > > > outputVector;\n\n    // Create vector of pairs (body name and body settings) that is to be created.\n    for( std::map< std::string, std::shared_ptr< BodySettings > >::const_iterator bodyIterator\n         = bodySettings.begin( );\n         bodyIterator != bodySettings.end( ); bodyIterator ++ )\n    {\n        outputVector.push_back( std::make_pair( bodyIterator->first, bodyIterator->second ) );\n    }\n\n    return outputVector;\n}\n\n\n//! Function to create a map of bodies objects.\nNamedBodyMap createBodies(\n        const std::map< std::string, std::shared_ptr< BodySettings > >& bodySettings )\n{\n    std::vector< std::pair< std::string, std::shared_ptr< BodySettings > > > orderedBodySettings\n            = determineBodyCreationOrder( bodySettings );\n\n    // Declare map of bodies that is to be returned.\n    NamedBodyMap bodyMap;\n\n    // Create empty body objects.\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        bodyMap[ orderedBodySettings.at( i ).first ] = std::make_shared< Body >( );\n    }\n\n    // Define constant mass for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        const double constantMass = orderedBodySettings.at( i ).second->constantMass;\n        if ( constantMass == constantMass )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setConstantBodyMass( constantMass );\n        }\n    }\n\n    // Create ephemeris objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->ephemerisSettings != nullptr )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setEphemeris(\n                        createBodyEphemeris( orderedBodySettings.at( i ).second->ephemerisSettings,\n                                             orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n    // Create atmosphere model objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->atmosphereSettings != nullptr )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setAtmosphereModel(\n                        createAtmosphereModel( orderedBodySettings.at( i ).second->atmosphereSettings,\n                                               orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n    // Create body shape model objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->shapeModelSettings != nullptr )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setShapeModel(\n                        createBodyShapeModel( orderedBodySettings.at( i ).second->shapeModelSettings,\n                                              orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n    // Create rotation model objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->rotationModelSettings != nullptr )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setRotationalEphemeris(\n                        createRotationModel( orderedBodySettings.at( i ).second->rotationModelSettings,\n                                             orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n    // Create gravity field model objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->gravityFieldSettings != nullptr )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setGravityFieldModel(\n                        createGravityFieldModel( orderedBodySettings.at( i ).second->gravityFieldSettings,\n                                                 orderedBodySettings.at( i ).first, bodyMap,\n                                                 orderedBodySettings.at( i ).second->gravityFieldVariationSettings ) );\n        }\n    }\n\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->gravityFieldVariationSettings.size( ) > 0 )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setGravityFieldVariationSet(\n                        createGravityFieldModelVariationsSet(\n                            orderedBodySettings.at( i ).first, bodyMap,\n                            orderedBodySettings.at( i ).second->gravityFieldVariationSettings ) );\n        }\n    }\n\n    // Create aerodynamic coefficient interface objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->aerodynamicCoefficientSettings != nullptr )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setAerodynamicCoefficientInterface(\n                        createAerodynamicCoefficientInterface(\n                            orderedBodySettings.at( i ).second->aerodynamicCoefficientSettings,\n                            orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n\n    // Create radiation pressure coefficient objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        std::map< std::string, std::shared_ptr< RadiationPressureInterfaceSettings > >\n                radiationPressureSettings\n                = orderedBodySettings.at( i ).second->radiationPressureSettings;\n        for( std::map< std::string, std::shared_ptr< RadiationPressureInterfaceSettings > >::iterator\n             radiationPressureSettingsIterator = radiationPressureSettings.begin( );\n             radiationPressureSettingsIterator != radiationPressureSettings.end( );\n             radiationPressureSettingsIterator++ )\n        {\n            bodyMap[ orderedBodySettings.at( i ).first ]->setRadiationPressureInterface(\n                        radiationPressureSettingsIterator->first,\n                        createRadiationPressureInterface(\n                            radiationPressureSettingsIterator->second,\n                            orderedBodySettings.at( i ).first, bodyMap ) );\n        }\n\n    }\n\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        for( unsigned int j = 0; j < orderedBodySettings.at( i ).second->groundStationSettings.size( ); j++ )\n        {\n            createGroundStation( bodyMap.at( orderedBodySettings.at( i ).first ), orderedBodySettings.at( i ).first,\n                     orderedBodySettings.at( i ).second->groundStationSettings.at( j ) );\n        }\n    }\n    return bodyMap;\n\n}\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "0ef6a70688641c286dbe4d0bbbe62293dd41597f", "size": 8035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/EnvironmentSetup/createBodies.cpp", "max_stars_repo_name": "different91988/tudat", "max_stars_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "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/EnvironmentSetup/createBodies.cpp", "max_issues_repo_name": "different91988/tudat", "max_issues_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "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/EnvironmentSetup/createBodies.cpp", "max_forks_repo_name": "different91988/tudat", "max_forks_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "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.2894736842, "max_line_length": 119, "alphanum_fraction": 0.6216552582, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18466528308318927}}
{"text": "#include <chrono>\n#include <boost/predef.h>\n#include <algorithm>\n\n#include \"StreamFlowControlFilter.hpp\"\n\n#define BUFFER_SIZE 300000\n#define MAX_CHUNK_SIZE 10000\n\nStreamFlowControlFilter* StreamFlowControlFilter::createNew(UsageEnvironment& env,\n\t                                                            FramedSource* inputSource,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned long bandwidth)\n{\n\treturn new StreamFlowControlFilter(env, inputSource, bandwidth);\n}\n\nStreamFlowControlFilter::StreamFlowControlFilter(UsageEnvironment& env,\n\tFramedSource* inputSource,\n\tunsigned long bandwidth)\n\t:\n\tFramedFilter(env, inputSource),\n\tbandwidth(bandwidth),\n\tbuffer(new unsigned char[BUFFER_SIZE]),\n\tbufferSize(0),\n\tprocessedBytes(0)\n{\n}\n\nvoid StreamFlowControlFilter::doGetNextFrame()\n{\n\tif (processedBytes < bufferSize)\n\t{\n\t\tdeliverChunk();\n\t}\n\telse\n\t{\n\t\t// Read directly from our input source into our client's buffer:\n\t\tfFrameSize = 0;\n\t\tfInputSource->getNextFrame(buffer,\n\t\t\t\t\t\t\t\t   BUFFER_SIZE,\n\t\t\t                       afterGettingFrame0,\n\t\t\t                       this,\n\t\t\t                       FramedSource::handleClosure,\n\t\t\t                       this);\n\t}\n}\n\nvoid StreamFlowControlFilter::afterGettingFrame0(void* clientData,\n\t                                               unsigned frameSize,\n                                                   unsigned numTruncatedBytes,\n                                                   struct timeval presentationTime,\n\t                                               unsigned durationInMicroseconds)\n{\n\tStreamFlowControlFilter* framer = (StreamFlowControlFilter*)clientData;\n\tframer->afterGettingFrame(frameSize, presentationTime);\n}\n\nvoid StreamFlowControlFilter::afterGettingFrame(unsigned frameSize,\n                                                struct timeval presentationTime)\n{\n\tbufferSize = frameSize;\n\tfPresentationTime = presentationTime;\n\tprocessedBytes = 0;\n\tdeliverChunk();\n}\n\nvoid StreamFlowControlFilter::deliverChunk()\n{\n\t// Fill buffer with next chunk\n\tfFrameSize = (std::min)((unsigned int)MAX_CHUNK_SIZE, fMaxSize);\n\tfFrameSize = (std::min)(fFrameSize, (unsigned int)(bufferSize - processedBytes));\n\tmemcpy(fTo, buffer + processedBytes, fFrameSize);\n\tprocessedBytes += fFrameSize;\n\n#if BOOST_OS_WINDOWS\n\tauto durationPerKBit = std::chrono::nanoseconds(boost::ratio_multiply<boost::giga, boost::kilo>::num / bandwidth);\n\n\tLARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;\n\tLARGE_INTEGER Frequency;\n\n\tQueryPerformanceFrequency(&Frequency);\n\tQueryPerformanceCounter(&StartingTime);\n#endif\n\n\t// Activity to be timed\n\tafterGetting(this);\n\n#if BOOST_OS_WINDOWS\n\tQueryPerformanceCounter(&EndingTime);\n\tElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;\n\n\t//\n\t// We now have the elapsed number of ticks, along with the\n\t// number of ticks-per-second. We use these values\n\t// to convert to the number of elapsed microseconds.\n\t// To guard against loss-of-precision, we convert\n\t// to microseconds *before* dividing by ticks-per-second.\n\t//\n\n\tElapsedMicroseconds.QuadPart *= 1000000;\n\tElapsedMicroseconds.QuadPart /= Frequency.QuadPart;\n\n\tauto isDuration = std::chrono::microseconds(ElapsedMicroseconds.QuadPart);\n\tauto shouldDuration = durationPerKBit * fFrameSize * 8 / 1000;\n\tauto coolDownDuration = shouldDuration - isDuration;\n\n\t// Let network cool down\n\tQueryPerformanceCounter(&StartingTime);\n\tstd::chrono::microseconds elapsedCoolDownDuration;\n\tdo\n\t{\n\t\tQueryPerformanceCounter(&EndingTime);\n\t\tElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;\n\t\tElapsedMicroseconds.QuadPart *= 1000000;\n\t\tElapsedMicroseconds.QuadPart /= Frequency.QuadPart;\n\t\telapsedCoolDownDuration = std::chrono::microseconds(ElapsedMicroseconds.QuadPart);\n\t} while (elapsedCoolDownDuration < coolDownDuration);\n#endif\n}", "meta": {"hexsha": "8890e46c84a5773b7f9b5a0cd362b3cea6961e3b", "size": 3793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AlloServer_Binoculars/StreamFlowControlFilter.cpp", "max_stars_repo_name": "AlloSphere-Research-Group/AlloStreamer", "max_stars_repo_head_hexsha": "611f7db9c9e4aab3ca83ad62eec0a0c637e76119", "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": "AlloServer_Binoculars/StreamFlowControlFilter.cpp", "max_issues_repo_name": "AlloSphere-Research-Group/AlloStreamer", "max_issues_repo_head_hexsha": "611f7db9c9e4aab3ca83ad62eec0a0c637e76119", "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": "AlloServer_Binoculars/StreamFlowControlFilter.cpp", "max_forks_repo_name": "AlloSphere-Research-Group/AlloStreamer", "max_forks_repo_head_hexsha": "611f7db9c9e4aab3ca83ad62eec0a0c637e76119", "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.8739495798, "max_line_length": 115, "alphanum_fraction": 0.7012918534, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18452087299137426}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2015 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_ALGORITHMS_DETAIL_RESULT_INVERSE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_RESULT_INVERSE_HPP\n\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/srs.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/algorithms/detail/flattening.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace detail\n{\n\ntemplate <typename T>\nstruct result_inverse\n{\n    void set(T const& d, T const& a)\n    {\n        distance = d;\n        azimuth = a;\n    }\n\n    T distance;\n    T azimuth;\n};\n\n}}} // namespace geofeatures_boost::geometry::detail\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_RESULT_INVERSE_HPP\n", "meta": {"hexsha": "83a31dc6ebab5ff2ac0f92d9e10ce9fd9e64c204", "size": 1115, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/detail/result_inverse.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/detail/result_inverse.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/detail/result_inverse.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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.7777777778, "max_line_length": 135, "alphanum_fraction": 0.7596412556, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.18447270003988492}}
{"text": "/******************************************************************************\n * Copyright 2017 Baidu Robotic Vision 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 \"IBA/IBA.h\"\n#include \"feature_utils.h\"\n#include \"image_utils.h\"\n#include \"xp_quaternion.h\"\n#include \"param.h\"  // calib\n#include \"basic_datatype.h\"\n#include \"iba_helper.h\"\n#include \"pose_viewer.h\"\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <glog/logging.h>\n#include <gflags/gflags.h>\n#include <opencv2/core.hpp>\n\n//ros\u76f8\u5173\n#include <ros/ros.h>\n#include <std_msgs/Header.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/image_encodings.h>\n#include <cv_bridge/cv_bridge.h>\n\n#include <tf/transform_broadcaster.h>\n#include \"../ros_visualization/visualization.h\"\n#include <eigen3/Eigen/Dense>\n\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n\n#include <algorithm>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <queue>\n#include <memory>\n\n//\u95ed\u73af\n#include \"LoopClosing.h\"\n#include \"CameraBase.hpp\"\n#include \"NCameraSystem.hpp\"\n#include \"ParamsInit.h\"\n\nDEFINE_bool(show_track_img,true,\"output trackimg(ros msg)\");\nDEFINE_string(config_file, \"\", \"\u50cfvinsfuison,\u7ed9\u603b\u914d\u7f6e\u6587\u4ef6\u7684\u8def\u5f84\");\nDEFINE_int32(grid_row_num, 1, \"Number of rows of detection grids\");\nDEFINE_int32(grid_col_num, 1, \"Number of cols of detection grids\");\nDEFINE_int32(max_num_per_grid, 150, \"Max number of points per grid\");\nDEFINE_double(feat_quality, 0.07, \"Tomasi-Shi feature quality level\");\nDEFINE_double(feat_min_dis, 10, \"Tomasi-Shi feature minimal distance\");\nDEFINE_bool(not_use_fast, false, \"Whether or not use FAST\");\nDEFINE_int32(pyra_level, 2, \"Total pyramid levels\");\nDEFINE_int32(start_idx, 0, \"The image index of the first detection (from 0)\");\nDEFINE_int32(end_idx, -1, \"The image index of the last detection\");\nDEFINE_double(uniform_radius, 40, \"< 5 disables uniformaty enforcement\");\nDEFINE_int32(ft_len, 125, \"The feature track length threshold when dropout kicks in\");\nDEFINE_double(ft_droprate, 0.05, \"The drop out rate when acc feature track exceeds ft_len\");\nDEFINE_bool(show_feat_only, false, \"wether or not show detection results only\");\nDEFINE_int32(fast_thresh, 10, \"FAST feature threshold (only meaningful if use_fast=true)\");\nDEFINE_double(min_feature_distance_over_baseline_ratio,\n              4, \"Used for slave image feature detection\");\nDEFINE_double(max_feature_distance_over_baseline_ratio,\n              3000, \"Used for slave image feature detection\");\nDEFINE_string(iba_param_path, \"\", \"iba parameters path\");\nDEFINE_string(gba_result_path, \"\", \"Save the gab_result\");\nDEFINE_string(result_folder, \"\", \"Save the result\");\nDEFINE_bool(stereo, false, \"monocular or stereo mode\");\nDEFINE_bool(save_feature, false, \"Save features to .dat file\");\nDEFINE_string(image0_topic, \"\", \"\u5de6\u76ee\u8bdd\u9898\");\nDEFINE_string(image1_topic, \"\", \"\u53f3\u76ee\u8bdd\u9898\");\nDEFINE_string(imu_topic, \"\", \"imu\u8bdd\u9898\");\nDEFINE_bool(LoopClosure, true, \"use LoopClosure?\");\nDEFINE_bool(GetGT, true, \"GTdata\");\nDEFINE_bool(UseIMU,true, \"use imu data?\");\nDEFINE_string(GT_path, \"\", \"\");\nDEFINE_string(dbow3_voc_path, \"\", \"dbow3_voc_path,must set!\");\nDEFINE_int32(mono_init_th,3,\"\u5927\u4e8e3\u6b21\u8ba4\u4e3aok\");\n\n\nstd::queue<IBA::RelativeConstraint> loop_info;\n\nstd::queue<IBA::CurrentFrame> CFs_buf;\nstd::queue<IBA::KeyFrame> KFs_buf;\nstd::mutex m_buf,m_syn_buf,m_solver_buf,m_loop_buf;\nstd::condition_variable con;\nstd::unique_ptr<XP::FeatureTrackDetector> feat_track_detector_ptr;\nstd::unique_ptr<XP::ImgFeaturePropagator> slave_img_feat_propagator_ptr;\nstd::vector<float> total_time;\n\nstd::unique_ptr<LC::LoopClosing> LoopCloser_ptr;\n\nXP::DuoCalibParam duo_calib_param;\n//\u7ed8\u56fe\u5668\nXP::PoseViewer pose_viewer;\n//\u6c42\u89e3\u5668\u521d\u59cb\u5316\nIBA::Solver solver;\n//\u5916\u53c2\nEigen::Matrix4f T_Cl_Cr;\nEigen::Matrix4d T_Cl_Cr_d;\nEigen::Matrix4d Tbc0;\n//\u7528\u4e8eLBA\u56de\u8c03\u7684\u7ed8\u56fe\u5668\nEigen::Vector3f last_position = Eigen::Vector3f::Zero();\nfloat travel_dist = 0.f;\ndouble offset_ts = 0;\nbool set_relative_pose = false;\nbool init_first_track = true;\n\nEigen::Matrix4d relative_pose; //Twc(first) * Twc.inv(gt)\n// Create masks based on FOVs computed from intrinsics\nstd::vector<cv::Mat_<uchar> > masks(2);\n\nfloat prev_img_time_stamp = 0.0f;\n// load previous image//\u5de6\u76ee\u4e4b\u524d\u7684\u7279\u5f81\u70b9\u548c\u63cf\u8ff0\u5b50\nstd::vector<cv::KeyPoint> pre_image_key_points;\ncv::Mat pre_image_features;\nint mono_init_count = 0;\nbool need_mono_init = true;\n\nstd::map<int,Eigen::Vector3f> cur_Mp_info; //\u524d\u4e00\u5e27\u8ffd\u8e2a\u5230\u7684\u5730\u56fe\u70b9\u76843d\u5750\u6807\nstd::vector<std::tuple<int,int,cv::KeyPoint>> cur_track;//\u5730\u56fe\u70b9id,\u5de6\u53f3\u76ee,\u89c2\u6d4b ;\nEigen::Matrix4f last_pose_Twc0;\n\nbool process_frontend()\n{\n    while (true)\n    {\n        std::vector<std::pair<std::vector<XP::ImuData>, stereo_Img_info_f >> measurements;\n\n        std::unique_lock <std::mutex> lk(m_buf);\n        con.wait(lk, [&] {\n            return (measurements = getMeasurements()).size() != 0;//\u5c06\u76ee\u524d\u6240\u6709\u7684\u6d4b\u91cf\u53d6\u51fa\u6765\n        });\n\n        lk.unlock();\n\n        //\u5904\u7406\u591a\u7ec4\u89c2\u6d4b\n        for (auto &measurement : measurements)\n        {\n            stereo_Img_info_f cur_img_info = measurement.second;\n            // get timestamp from image file name (s)\n            //\u8fd9\u91cc\u7528\u7684\u65f6\u95f4\u6233\u90fd\u662f\u76f8\u5bf9\u4e8eimu\u7b2c\u4e00\u5e27\u7684\u65f6\u95f4\u6233,time_stamp\u4e3a\u5de6\u56fe\u50cf\u65f6\u95f4\u6233\n            const float img_time_stamp = cur_img_info.first;\n            std::vector<XP::ImuData> imu_meas = measurement.first;//\u4e24\u5e27\u56fe\u50cf\u4e4b\u95f4imu\u7684\u539f\u59cb\u6d4b\u91cf\u6570\u636e\n            cv::Mat img_in_raw;\n            if(cur_img_info.second.first.type() == CV_8UC1 )\n                img_in_raw = cur_img_info.second.first;\n            else if(cur_img_info.second.first.type() == CV_8UC3)\n            {\n                cv::cvtColor(cur_img_info.second.first, img_in_raw, CV_BGR2GRAY);\n            }\n            CHECK_EQ(img_in_raw.rows, duo_calib_param.Camera.img_size.height);\n            CHECK_EQ(img_in_raw.cols, duo_calib_param.Camera.img_size.width);\n            cv::Mat img_in_smooth;\n            cv::blur(img_in_raw, img_in_smooth, cv::Size(3, 3));//\u56fe\u50cf\u53bb\u566a\n            if (img_in_smooth.rows == 0) {\n                std::cerr << \"Cannot smooth \" <<std::endl;\n                return EXIT_FAILURE;\n            }\n            // load slave image\n            cv::Mat slave_img_smooth;  // for visualization later\n\n            if (FLAGS_stereo) //\u4e5f\u5c31\u662f\u53cc\u76ee\u7684\u60c5\u51b5\n            {//\u8bfb\u53d6\u53f3\u76ee\u76f8\u673a,\u4e00\u6837\u505a\u964d\u566a\u5904\u7406\n                cv::Mat slave_img_in;\n                if(cur_img_info.second.second.type() == CV_8UC1 )\n                    slave_img_in = cur_img_info.second.second;\n                else if(cur_img_info.second.second.type() == CV_8UC3)\n                {\n                    cv::cvtColor(cur_img_info.second.second, slave_img_in, CV_BGR2GRAY);\n                }\n                cv::blur(slave_img_in, slave_img_smooth, cv::Size(3, 3));\n            }\n\n            std::vector<cv::KeyPoint> key_pnts;//\u5de6\u76ee\u63d0\u53d6\u5230\u7684\u7279\u5f81\u70b9\n            cv::Mat orb_feat;//\u5de6\u76eeorb\u63cf\u8ff0\u5b50\n            cv::Mat pre_img_in_smooth;\n            // load slave image\n            std::vector<cv::KeyPoint> key_pnts_slave;\n            cv::Mat orb_feat_slave;\n            if(init_first_track) //\u9996\u6b21\u8ffd\u8e2a\n            {\n                // first frame\n                //\u7b2c\u4e00\u5e27\u5de6\u76f8\u673a\u63d0\u53d6\u7279\u5f81\u70b9\n                //\u8f93\u5165\u5de6\u76f8\u673a\u56fe\u7247,\u56fe\u50cf\u63a9\u7801,\u6700\u5927\u63d0\u53d6\u7684\u7279\u5f81\u70b9\u6570\u91cf,\u91d1\u5b57\u5854\u5c42\u6570,fast\u70b9\u9608\u503c,\u7279\u5f81\u70b9,\u63cf\u8ff0\u5b50\n                //\u4e3b\u8981\u5c31\u662f\u63d0\u70b9,\u8ba1\u7b97\u63cf\u8ff0\u5b50\n                feat_track_detector_ptr->detect(img_in_smooth,\n                                                masks[0],\n                                                FLAGS_max_num_per_grid * FLAGS_grid_row_num * FLAGS_grid_col_num,\n                                                FLAGS_pyra_level,\n                                                FLAGS_fast_thresh,\n                                                &key_pnts,\n                                                nullptr);\n                feat_track_detector_ptr->build_img_pyramids(img_in_smooth,//\u6784\u5efa\u56fe\u50cf\u91d1\u5b57\u5854,\u5b58\u5230\u524d\u4e00\u5e27\u7f13\u5b58\u5668\u4e2d\n                                                            XP::FeatureTrackDetector::BUILD_TO_PREV);\n            } else\n            {\n\n                VLOG(1) << \"pre_image_key_points.size(): \" << pre_image_key_points.size();\n                const int request_feat_num = FLAGS_max_num_per_grid * FLAGS_grid_row_num * FLAGS_grid_col_num;//\u6700\u5927\u63d0\u53d6\u7684\u7279\u5f81\u70b9\u6570\u91cf\n                feat_track_detector_ptr->build_img_pyramids(img_in_smooth,\n                                                            XP::FeatureTrackDetector::BUILD_TO_CURR);//\u5b58\u50a8\u5f53\u524d\u5de6\u76ee\u7684\u91d1\u5b57\u5854\n                if (imu_meas.size() > 1) {//\u5982\u679c\u6709imu\u7684\u8bdd\n                    // Here we simply the transformation chain to rotation only and assume zero translation\n                    cv::Matx33f old_R_new;\n                    XP::XpQuaternion I_new_q_I_old;  // The rotation between the new {I} and old {I}\n                    //RK4\u9884\u79ef\u5206,\u7b97\u51faRi(cur)_i(pre)\n                    for (size_t i = 1; i < imu_meas.size(); ++i) {\n                        XP::XpQuaternion q_end;\n                        XP::IntegrateQuaternion(imu_meas[i - 1].ang_v/*k\u65f6\u523b\u7684\u89d2\u901f\u5ea6*/,\n                                                imu_meas[i].ang_v/*k+1\u65f6\u523b\u7684\u89d2\u901f\u5ea6*/,\n                                                I_new_q_I_old,\n                                                imu_meas[i].time_stamp - imu_meas[i - 1].time_stamp/*delta_t*/,\n                                                &q_end);\n                        I_new_q_I_old = q_end;\n                    }\n                    Eigen::Matrix3f I_new_R_I_old = I_new_q_I_old.ToRotationMatrix();\n                    Eigen::Matrix4f I_T_C =//\u5de6\u76f8\u673a\u5230imu\u7684\u53d8\u6362\n                            duo_calib_param.Imu.D_T_I.inverse() * duo_calib_param.Camera.D_T_C_lr[0];//Ti_d * Td_cl = Ti_cl\n                    Eigen::Matrix3f I_R_C = I_T_C.topLeftCorner<3, 3>();//\u5916\u53c2\u65cb\u8f6c\u90e8\u5206\n                    //imu\u6d4b\u51fa\u662fimu\u7cfb\u524d\u540e\u4e24\u5e27\u4e4b\u95f4\u7684\u65cb\u8f6c\uff0c\u9700\u8981\u8f6c\u5230\u5de6\u76f8\u673a\u5750\u6807\u7cfb\u7684\u65cb\u8f6c\n                    Eigen::Matrix3f C_new_R_C_old = I_R_C.transpose() * I_new_R_I_old * I_R_C;// Rcl_i * Ri(cur)_i(pre) * Ri_cl = Rcl(cur)_cl(pre)\n                    //Rcl(pre)_cl(cur)\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            old_R_new(j, i) = C_new_R_C_old(i, j);\n                        }\n                    }\n\n                    if (VLOG_IS_ON(1)) {\n                        XP::XpQuaternion C_new_q_C_old;\n                        C_new_q_C_old.SetFromRotationMatrix(C_new_R_C_old);\n                        VLOG(1) << \"C_new_R_C_old = \\n\" << C_new_R_C_old;\n                        VLOG(1) << \"ea =\\n\" << C_new_q_C_old.ToEulerRadians() * 180 / M_PI;\n                    }\n                    feat_track_detector_ptr->optical_flow_and_detect(masks[0]/*\u5de6\u76f8\u673a\u63a9\u7801*/,\n                                                                     pre_image_features/*\u5de6\u76f8\u673a\u4e0a\u4e00\u5e27\u68c0\u6d4b\u5230\u7684\u7279\u5f81\u70b9\u7684\u63cf\u8ff0\u5b50*/,\n                                                                     pre_image_key_points/*\u5de6\u76f8\u673a\u4e0a\u4e00\u5e27\u68c0\u6d4b\u5230\u7684\u7279\u5f81\u70b9*/,\n                                                                     request_feat_num/*\u6700\u5927\u8981\u6c42\u63d0\u53d6\u7684\u7279\u5f81\u70b9\u6570\u91cf*/,\n                                                                     FLAGS_pyra_level/*\u91d1\u5b57\u5854\u5c42*/,\n                                                                     FLAGS_fast_thresh/*fast\u9608\u503c*/,\n                                                                     &key_pnts/*\u5de6\u76f8\u673a\u5f53\u524d\u5e27\u63d0\u53d6\u5230\u7684\u7279\u5f81\u70b9*/,\n                                                                     nullptr/*\u5de6\u76f8\u673a\u5f53\u524d\u5e27\u63d0\u53d6\u5230\u7684\u7279\u5f81\u70b9\u5bf9\u5e94\u7684\u63cf\u8ff0\u5b50*/,\n                                                                     duo_calib_param.Camera.fishEye,\n                                                                     cv::Vec2f(0, 0),  // shift init pixels\n                                                                     &duo_calib_param.Camera.cv_camK_lr[0]/*cv\u5f62\u5f0f\u7684\u5de6\u53f3\u76f8\u673a\u5185\u53c2*/,\n                                                                     &duo_calib_param.Camera.cv_dist_coeff_lr[0]/*\u5de6\u53f3\u76f8\u673a\u7684\u7578\u53d8\u53c2\u6570*/,\n                                                                     &old_R_new/*Rcl(pre)_cl(cur)\u5de6\u76f8\u673a\u5f53\u524d\u5e27\u5230\u524d\u4e00\u5e27\u7684\u65cb\u8f6c*/);\n                } else {\n                    feat_track_detector_ptr->optical_flow_and_detect(masks[0],\n                                                                     pre_image_features,\n                                                                     pre_image_key_points,\n                                                                     request_feat_num,\n                                                                     FLAGS_pyra_level,\n                                                                     FLAGS_fast_thresh,\n                                                                     &key_pnts,\n                                                                     nullptr);\n                }\n                feat_track_detector_ptr->update_img_pyramids();//\u66f4\u65b0\u91d1\u5b57\u5854buffer\n                VLOG(1) << \"after OF key_pnts.size(): \" << key_pnts.size() << \" requested # \"\n                        << FLAGS_max_num_per_grid * FLAGS_grid_row_num * FLAGS_grid_col_num;\n            }\n\n            //\u5982\u679c\u662f\u53cc\u76ee\u7684\u8bdd\n            if (slave_img_smooth.rows > 0)\n            {\n                CHECK(orb_feat_slave.empty());\n                auto det_slave_img_start = std::chrono::high_resolution_clock::now();\n                //\u8f93\u5165\u53f3\u5de6\u76ee\u56fe\u7247\uff0c\u5de6\u76ee\u63d0\u53d6\u7684\u7279\u5f81\u70b9,\u5de6\u53f3\u76ee\u5916\u53c2,\u53f3\u76ee\u63d0\u53d6\u7684\u7279\u5f81\u70b9,\u63cf\u8ff0\u5b50,\u662f\u5426\u8981\u8f93\u51fadebug\u4fe1\u606f\n                //\u7528svo\u7684\u5757\u5339\u914d\u7684\u601d\u8def\u7b97\u51fa\u53f3\u76f8\u673a\u4e2d\u7279\u5f81\u70b9\u7684\u5750\u6807,\u5e76\u4e14\u8ba1\u7b97\u63cf\u8ff0\u5b50\n                slave_img_feat_propagator_ptr->PropagateFeatures(slave_img_smooth,  // cur \u53f3\u76ee\n                                                                 img_in_smooth,  // ref \u5de6\u76ee\n                                                                 key_pnts, //\u5de6\u76ee\u63d0\u53d6\u7684\u7279\u5f81\u70b9\n                                                                 T_Cl_Cr,  // T_ref_cur //\u5de6\u53f3\u76ee\u5916\u53c2\n                                                                 &key_pnts_slave,\n                                                                 nullptr,\n                                                                 false);  // draw_debug\n                VLOG(1) << \"detect slave key_pnts.size(): \" << key_pnts_slave.size() << \" takes \"\n                        << std::chrono::duration_cast<std::chrono::microseconds>(\n                                std::chrono::high_resolution_clock::now() - det_slave_img_start).count() / 1e3\n                        << \" ms\";\n            }\n            //\u6839\u636eclass_id(\u4e0e\u5730\u56fe\u70b9id\u4e00\u81f4)\u8fdb\u884c\u6392\u5e8f,\u4e0d\u8fc7\u672c\u6765\u5c31\u662f\u8fd9\u4e2a\u987a\u5e8f\u5427\n            std::sort(key_pnts.begin(), key_pnts.end(), cmp_by_class_id);\n            std::sort(key_pnts_slave.begin(), key_pnts_slave.end(), cmp_by_class_id);\n\n            if(init_first_track)\n                init_first_track = false;\n            else\n            {\n                if(FLAGS_show_track_img)\n                    pubTrackImage(img_in_smooth,slave_img_smooth,pre_image_key_points,key_pnts,key_pnts_slave,(double)img_time_stamp + offset_ts);\n            }\n            if(!FLAGS_stereo)//\u5355\u76ee\u7b80\u5355\u7684\u5224\u65ad\u4e00\u4e0b\u7b2c\u4e00\u6b21\u9700\u8981\u5f00\u59cb\u5427\n            {//\u7b97\u4e00\u4e0b\u8fd0\u52a8\n                mono_begin_compute(pre_image_key_points,key_pnts,duo_calib_param.Camera.cv_camK_lr[0],\n                                   &duo_calib_param.Camera.cv_dist_coeff_lr[0],\n                                   duo_calib_param.Camera.fishEye,\n                                   masks[0],&mono_init_count);\n                if(need_mono_init && mono_init_count >= FLAGS_mono_init_th )//\u5927\u4e8e5\u6b21\u5c31\u8ba4\u4e3a\u5728\u6fc0\u52b1,\u5f00\u59cb\u8ffd\u8e2a\u5427\n                {\n                    need_mono_init = false;\n                }\n                else if(need_mono_init)\n                {\n                    pre_image_key_points = key_pnts;\n                    pre_image_features = orb_feat.clone();\n\n                    prev_img_time_stamp = img_time_stamp;\n                    continue;\n                }\n            }\n\n            // push to IBA\n            IBA::CurrentFrame CF;\n            IBA::KeyFrame KF;\n            //\u8f93\u5165\u5de6\u76f8\u673a\u7279\u5f81\u70b9,\u53f3\u76f8\u673a\u7279\u5f81\u70b9,imu\u6d4b\u91cf,\u5de6\u76ee\u65f6\u95f4\u6233,\u5f53\u524d\u5e27,\u5173\u952e\u5e27\n            //\u8fdb\u884c\u70b9\u7ba1\u7406(\u65b0\u65e7\u5730\u56fe\u70b9\u7684\u89c2\u6d4b\u66f4\u65b0),\u4ee5\u53ca\u5173\u952e\u5e27\u5224\u65ad\u4ee5\u53ca\u751f\u6210\n            create_iba_frame(key_pnts, key_pnts_slave, imu_meas, img_time_stamp, &CF, &KF);\n\n            if(FLAGS_LoopClosure)\n            {\n                if(KF.iFrm != -1)\n                {\n\n                    std::vector<cv::KeyPoint> loop_key_pnts;//\u5de6\u76ee\u63d0\u53d6\u5230\u7684\u7279\u5f81\u70b9\n                    cv::Mat loop_orb_feat;//\u5de6\u76eeorb\u63cf\u8ff0\u5b50\n\n                    feat_track_detector_ptr->detect_for_loop(img_in_smooth,\n                                                             masks[0],\n                                                             1000,\n                                                             FLAGS_pyra_level,\n                                                             FLAGS_fast_thresh,\n                                                             &loop_key_pnts,\n                                                             &loop_orb_feat);\n\n                    cv::Mat cur_orb_feat;\n                    feat_track_detector_ptr->ComputeDescriptors(img_in_smooth,&key_pnts,&cur_orb_feat);\n                    LoopCloser_ptr ->InsertKeyFrame(std::shared_ptr<LC::KeyFrame> (new LC::KeyFrame(KF.iFrm,key_pnts,cur_orb_feat,loop_key_pnts,loop_orb_feat,img_in_smooth)));\n                }\n            }\n\n            m_solver_buf.lock();\n            CFs_buf.push(CF);\n            if(KF.iFrm != -1)\n                KFs_buf.push(KF);\n            m_solver_buf.unlock();\n\n\n            pre_image_key_points = key_pnts;\n            pre_image_features = orb_feat.clone();\n\n            prev_img_time_stamp = img_time_stamp;\n        }\n\n    }\n}\n\nvoid process_backend()\n{\n    while(1)\n    {\n        IBA::CurrentFrame CF;\n        IBA::KeyFrame KF;\n        CF.iFrm = -1;\n        KF.iFrm = -1;\n        m_solver_buf.lock();\n        if (!CFs_buf.empty())\n        {\n            CF = CFs_buf.front();\n            CFs_buf.pop();\n            if(!KFs_buf.empty())\n            {\n                if( CF.iFrm == KFs_buf.front().iFrm)//KF\u91cc\u7684\u7d22\u5f15\u53ea\u53ef\u80fd>= cf\u7684\n                {\n                    KF = KFs_buf.front();\n                    KFs_buf.pop();\n                }\n            }\n        }\n        m_solver_buf.unlock();\n        if(CF.iFrm != -1)\n        {\n            if(FLAGS_LoopClosure)\n            {\n                std::vector<IBA::RelativeConstraint> loop_Relative_priors;\n                m_loop_buf.lock();\n                while(!loop_info.empty())\n                {\n                    loop_Relative_priors.push_back(loop_info.front());\n                    loop_info.pop();\n                }\n                m_loop_buf.unlock();\n                //\u5c06\u5f53\u524d\u5e27\u4ee5\u53ca\u5173\u952e\u5e27(\u5982\u679c\u6709\u7684\u8bdd)\u653e\u8fdb\u6c42\u89e3\u5668\n                if(!loop_Relative_priors.empty())\n                {\n                    for (int i = 0; i < loop_Relative_priors.size(); ++i)\n                    {\n                        solver.PushRelativeConstraint(loop_Relative_priors[i]);\n                    }\n                    solver.Wakeup_GBA();\n                }\n            }\n\n            if(total_time.size() > CF.iFrm)//\u5148\u8fd9\u4e48\u5b58\u4e00\u4e0b\u5427,\u5148\u4e0d\u8003\u8651\u4e0a\u9650\u7684\u95ee\u9898\n                total_time[CF.iFrm] = CF.t;\n            else\n            {\n                total_time.resize(total_time.size()+300);\n                total_time[CF.iFrm] = CF.t;\n            }\n\n            if(!FLAGS_UseIMU)\n            {\n                Get_Track(CF,cur_track);\n\n                if(SolveMulticamPnP(cur_track,cur_Mp_info,last_pose_Twc0))\n                {\n                    Eigen::Matrix3f pose_pnp_Rc0w = last_pose_Twc0.block<3,3>(0,0).transpose();\n                    Eigen::Vector3f pose_pnp_twc0 = last_pose_Twc0.block<3,1>(0,3);\n                    for (int i = 0; i < 3; ++i)\n                    {\n                        CF.Cam_state.Cam_pose.p[i] = pose_pnp_twc0[i];\n                        for (int j = 0; j < 3; ++j) {\n                            CF.Cam_state.Cam_pose.R[i][j] = pose_pnp_Rc0w(i,j);\n                        }\n\n                    }\n                    KF.Cam_pose = CF.Cam_state.Cam_pose;\n                }\n            }\n            solver.PushCurrentFrame(CF, KF.iFrm == -1 ? nullptr : &KF);//\u5148\u8bf4\u660e\u4e00\u4e0b,\u6211\u4e60\u60ef\u7684\u6c42\u89e3\u589e\u91cf\u7684\u8868\u8fbe\u662fHx=b,\u4f46\u662f\u8fd9\u91cc\u662fHx=-b\n//          show pose\n            pose_viewer.displayTo(\"trajectory\");\n            cv::waitKey(1);\n        }\n\n    }\n}\n\n\n//euroc\u6d4b\u8bd5\u4ee3\u7801\nint main(int argc, char** argv)\n{\n    //\u521d\u59cb\u5316glog\u76f8\u5173\u7a0b\u5e8f\n    google::InitGoogleLogging(argv[0]);\n    google::ParseCommandLineFlags(&argc, &argv, true);\n    google::InstallFailureSignalHandler();\n\n    ros::init(argc, argv, \"ice_ba\");\n    ros::NodeHandle n(\"~\");\n\n    registerPub(n);\n\n    total_time.resize(4000);\n\n    //\u5982\u679c\u6ca1\u6709\u7ed9image\u6587\u4ef6\u5939\u7684\u8bdd\n    if (FLAGS_config_file.empty() )//\n    {\n        google::ShowUsageWithFlags(argv[0]);\n        return -1;\n    }\n\n    if(!FLAGS_result_folder.empty())\n    {\n        if (!fs::is_directory(FLAGS_result_folder + \"/dat\")) {\n            fs::create_directories(FLAGS_result_folder + \"/dat\");\n        }\n\n    }\n\n    try {//\u8f93\u51fa\u6807\u5b9a\u53c2\u6570\uff08\u5185\u5916\u53c2,\u7acb\u4f53\u77eb\u6b63,\u53bb\u5b8c\u7578\u53d8\u540e\u7684\u6620\u5c04\uff09\n        load_Parameters(FLAGS_config_file, duo_calib_param);\n    } catch (...){\n        LOG(ERROR) << \"Load calibration file error\";\n        return -1;\n    }\n\n\n    int Num_Cam = FLAGS_stereo ? 2:1;\n    for (int lr = 0; lr < Num_Cam; ++lr) {\n        float fov;\n        //\u8f93\u51fa\u6bcf\u4e00\u76ee\u7684mask\u548c\u89c6\u573a\u89d2\n        if (XP::generate_cam_mask(duo_calib_param.Camera.cv_camK_lr[lr],\n                                  duo_calib_param.Camera.cv_dist_coeff_lr[lr],\n                                  duo_calib_param.Camera.fishEye,\n                                  duo_calib_param.Camera.img_size,\n                                  &masks[lr],\n                                  &fov)) {\n            std::cout << \"camera \" << lr << \" fov: \" << fov << \" deg\\n\";\n        }\n    }\n\n    if(FLAGS_LoopClosure)\n    {\n        LoopCloser_ptr.reset(new LC::LoopClosing(FLAGS_dbow3_voc_path,\n                                                 duo_calib_param.Camera.cameraK_lr[0],  // ref_camK \u5de6\u76f8\u673a\u5185\u53c2\n                                                 duo_calib_param.Camera.cv_dist_coeff_lr[0],  // ref_dist_coeff \u5de6\u76f8\u673a\u7578\u53d8\n                                                 duo_calib_param.Camera.fishEye,\n                                                 masks[0]));\n    }\n\n    //\u521d\u59cb\u5316\u7279\u5f81\u63d0\u53d6\u5668\n    feat_track_detector_ptr.reset(new XP::FeatureTrackDetector(FLAGS_ft_len/*\u56fe\u50cf\u5927\u5c0f*/,\n                                                               FLAGS_ft_droprate/*\u56fe\u50cf\u5927\u5c0f*/,\n                                                               !FLAGS_not_use_fast/*\u662f\u5426\u7528fast\u70b9*/,\n                                                               FLAGS_uniform_radius/*\u56fe\u50cf\u5927\u5c0f*/,\n                                                               duo_calib_param.Camera.img_size/*\u56fe\u50cf\u5927\u5c0f*/));\n\n    if(FLAGS_stereo)\n    {\n        //\u914d\u7f6e\u5de6\u53f3\u76f8\u673a\u7684\u6295\u5f71\u548c\u7578\u53d8\u6a21\u578b,\u76ee\u524d\u53ea\u652f\u6301\u9488\u5b54+radtan\n        slave_img_feat_propagator_ptr.reset(new XP::ImgFeaturePropagator(\n                duo_calib_param.Camera.cameraK_lr[1],  // cur_camK \u53f3\u76f8\u673a\u5185\u53c2\n                duo_calib_param.Camera.cameraK_lr[0],  // ref_camK \u5de6\u76f8\u673a\u5185\u53c2\n                duo_calib_param.Camera.cv_dist_coeff_lr[1],  // cur_dist_coeff \u53f3\u76f8\u673a\u7578\u53d8\n                duo_calib_param.Camera.cv_dist_coeff_lr[0],  // ref_dist_coeff \u5de6\u76f8\u673a\u7578\u53d8\n                duo_calib_param.Camera.fishEye,\n                masks[1],//\u53f3\u76f8\u673a\u7684\u63a9\u7801\n                FLAGS_pyra_level,//\u6240\u6709\u91d1\u5b57\u5854\u5c42\u6570\n                FLAGS_min_feature_distance_over_baseline_ratio,//\u7279\u5f81\u70b9\u6700\u5c0f\u6df1\u5ea6\u6bd4\u4f8b,\u7528\u4e8e\u6781\u7ebf\u641c\u7d22\n                FLAGS_max_feature_distance_over_baseline_ratio));//\u7279\u5f81\u70b9\u6700\u5927\u6df1\u5ea6\u6bd4\u4f8b,\u7528\u4e8e\u6781\u7ebf\u641c\u7d22)\n\n        //\u53cc\u76ee\u5916\u53c2\n        T_Cl_Cr = T_Cl_Cr_d.cast<float>();\n\n    }\n    //\u7ed8\u5236\u524d\u6e05\u9664\u753b\u5e03\n    pose_viewer.set_clear_canvas_before_draw(true);\n    if (FLAGS_save_feature) {\n        //\u5b58\u50a8\u5916\u53c2,\u5185\u53c2\u6587\u4ef6\n        IBA::SaveCalibration(FLAGS_result_folder + \"/calibration.dat\", to_iba_calibration(duo_calib_param));\n    }\n\n    //\u5de6\u53f3\u76ee\u7684\u5185\u5916\u53c2,,\u662f\u5426\u8981\u8f93\u51fa\u7ec6\u8282\u5185\u5bb9,\u662f\u5426\u8f93\u51fadebug\u4fe1\u606f,,\u53c2\u6570\u6240\u5728\u4f4d\u7f6e\n    solver.Create(to_iba_calibration(duo_calib_param),\n                  257,\n                  IBA_VERBOSE_NONE,\n                  IBA_DEBUG_NONE,\n                  257,\n                  FLAGS_iba_param_path,//iba\u7684\u914d\u7f6e\u6587\u4ef6\n                  \"\" /* iba directory */);\n\n    if(FLAGS_LoopClosure)\n    {\n        LoopCloser_ptr->SetCallback([&](const vector<Eigen::Matrix4f> & rKFpose/*\u53c2\u8003\u5173\u952e\u5e27Twc*/,\n                                        const Eigen::Matrix4f & lKFpose,vector<int> riFrm,int liFrm)\n        {\n            pubLoopCamPose(lKFpose.cast<double>());\n            for (int k = 0; k < rKFpose.size(); ++k)\n            {\n                LA::AlignedMatrix6x6f S;\n                IBA::RelativeConstraint Z;\n\n                Eigen::Matrix4f Tlr = lKFpose.inverse() * rKFpose[k];////Tc0(\u89c2\u6d4b\u5173\u952e\u5e27)c0(\u53c2\u8003\u5173\u952e\u5e27)\n                float pose_f[3][4];\n                for (int i = 0; i < 3; ++i)\n                {\n                    for (int j = 0; j < 4; ++j)\n                    {\n                        pose_f[i][j] = Tlr(i,j);\n                    }\n\n                }\n                Rigid3D T;\n                T.Set(pose_f);////Tc0(\u89c2\u6d4b\u5173\u952e\u5e27)c0(\u53c2\u8003\u5173\u952e\u5e27)\n\n                Z.iFrm1 = riFrm[k];\n                Z.iFrm2 = liFrm;\n                T.Rotation3D::Get(Z.T.R);\n                T.GetPosition().Get(Z.T.p);\n                S.MakeDiagonal(LOOP_S2P, LOOP_S2R);//\u56fa\u5b9a\u4e00\u4e0b\u53c2\u8003\u5173\u952e\u5e27\n                S.Get(Z.S.S);\n                m_loop_buf.lock();\n                loop_info.push(Z);\n                m_loop_buf.unlock();\n            }\n\n\n        });\n\n    }\n    //\u5bf9GBA\u6c42\u89e3\u5668\u8bbe\u7f6e\u56de\u8c03\u51fd\u6570m_callback,\u7528\u6765\u53ef\u89c6\u5316\n    solver.SetCallbackGBA([&](const int iFrm,/*\u6700\u65b0\u4e00\u5e27\u7684id*/ const float ts/*\u6700\u65b0\u4e00\u5e27\u7684\u65f6\u95f4\u6233*/)\n    {\n\n        if(FLAGS_LoopClosure)\n        {\n            IBA::Global_Map GM;\n            solver.GetUpdateGba(&GM);\n            LoopCloser_ptr->UpdateKfInfo(GM);\n        }\n\n        std::vector<std::pair<int,IBA::CameraPose>> total_kfs = solver.Get_Total_KFs();\n        std::vector<std::pair<double,Eigen::Matrix4d>> kf_poses;\n        kf_poses.resize(total_kfs.size());\n        for (int kf_id = 0; kf_id < total_kfs.size(); ++kf_id)\n        {\n            kf_poses[kf_id].first = (double)total_time[total_kfs[kf_id].first] + offset_ts;\n            kf_poses[kf_id].second = Eigen::Matrix4d::Identity();\n\n            for (int i = 0; i < 3; ++i) {\n                kf_poses[kf_id].second(i, 3) = (double)total_kfs[kf_id].second.p[i];\n                for (int j = 0; j < 3; ++j) {\n                    kf_poses[kf_id].second(i,j) = (double)total_kfs[kf_id].second.R[j][i];\n                }\n            }\n        }\n        pubKFsPose(kf_poses);\n    });\n\n\n    //\u5bf9LBA\u6c42\u89e3\u5668\u8bbe\u7f6e\u56de\u8c03\u51fd\u6570m_callback,\u7528\u6765\u53ef\u89c6\u5316\n    solver.SetCallbackLBA([&](const int iFrm,/*\u6700\u65b0\u4e00\u5e27\u7684id*/ const float ts/*\u6700\u65b0\u4e00\u5e27\u7684\u65f6\u95f4\u6233*/)\n    {\n        // as we may be able to send out information directly in the callback arguments\n        IBA::SlidingWindow sliding_window;\n        //\u83b7\u5f97LBA\u4e2d\u7684\u6ed1\u7a97\u4e2d\u66f4\u65b0\u4e86\u7684\u666e\u901a\u5e27\u4ee5\u53ca\u66f4\u65b0\u4e86\u7684\u5173\u952e\u5e27\u8fd8\u6709\u66f4\u65b0\u4e86\u7684\u5730\u56fe\u70b9\n        solver.GetSlidingWindow(&sliding_window);\n        const IBA::CameraIMUState& X = sliding_window.CsLF.back();//\u6700\u65b0\u7684\u4e00\u5e27\n        const IBA::CameraPose& C = X.Cam_pose;\n        Eigen::Matrix4f W_vio_T_S = Eigen::Matrix4f::Identity();  // Twc0\u6700\u65b0\u7684\n        for (int i = 0; i < 3; ++i) {\n            W_vio_T_S(i, 3) = C.p[i];\n            for (int j = 0; j < 3; ++j) {\n                W_vio_T_S(i, j) = C.R[j][i];  //\u56e0\u4e3a\u5b58\u50a8\u7684\u662fC.R\u91cc\u662fRc0w,\u6240\u4ee5\u8981\u8f6c\u6210Rwc0     Cam_state.R is actually R_SW\n            }\n        }\n        Eigen::Matrix4d Twc0 = W_vio_T_S.cast<double>();\n        Eigen::Matrix<float, 9, 1> speed_and_biases;\n        Eigen::Matrix<double , 9, 1> speed_and_biases_d;\n        for (int i = 0; i < 3; ++i) {\n            speed_and_biases(i) = X.v[i];\n            speed_and_biases(i + 3) = X.ba[i];\n            speed_and_biases(i + 6) = X.bw[i];\n\n            speed_and_biases_d(i) = (double)X.v[i];\n            speed_and_biases_d(i + 3) = (double)X.ba[i];\n            speed_and_biases_d(i + 6) = (double)X.bw[i];\n        }\n\n        Eigen::Vector3f cur_position = W_vio_T_S.topRightCorner(3, 1);\n        travel_dist += (cur_position - last_position).norm();\n        last_position = cur_position;\n        pose_viewer.addPose(W_vio_T_S, speed_and_biases, travel_dist);\n\n        CHECK_EQ(sliding_window.iFrms.size(),sliding_window.CsLF.size());\n\n        double cur_time =(double)total_time[sliding_window.iFrms.back()] + offset_ts;\n\n        if(!FLAGS_UseIMU)\n        {\n            vector<int> track_idx;\n            for (int i = 0; i < cur_track.size(); ++i)\n                track_idx.push_back(std::get<0>(cur_track[i]));\n            solver.Get_cur_Mps(track_idx,cur_Mp_info);\n            last_pose_Twc0 = W_vio_T_S;\n        }\n\n        //ROS pub\n//        pubUpdatePointClouds(sliding_window.Xs,cur_time);\n        pubLatestCameraPose(Twc0,speed_and_biases_d.block<3,1>(0,0),cur_time);\n        pubTF(Twc0,cur_time);\n\n\n    });\n\n\n    //\u542f\u52a8\u6c42\u89e3\u5668\n    solver.Start();\n\n\n\n    //\u5de6\u53f3\u76f8\u673a\u540c\u6b65\n    std::thread sync_thread{sync_stereo};\n    //\u524d\u7aef\n    std::thread measurement_process{process_frontend};\n    //\u540e\u7aef\n    std::thread Backend_process{process_backend};\n    //\n    ros::Subscriber sub_imu = n.subscribe(FLAGS_imu_topic, 2000, imu_callback, ros::TransportHints().tcpNoDelay());\n    ros::Subscriber sub_img0 = n.subscribe(FLAGS_image0_topic, 100, img0_callback);\n    ros::Subscriber sub_img1 = n.subscribe(FLAGS_image1_topic, 100, img1_callback);\n\n    ros::Subscriber sub_odom = n.subscribe(\"/ice_ba/imu_pose\", 1000, odom_callback);\n\n    ros::spin();\n\n\n    return 0;\n}", "meta": {"hexsha": "464db13499c04130f062d1db31152f3cab7b8f89", "size": 29168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "App/ICE-BA-ROS.cpp", "max_stars_repo_name": "wangyuanbiubiubiu/ICE-BA-ros", "max_stars_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-03-06T10:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:06:37.000Z", "max_issues_repo_path": "App/ICE-BA-ROS.cpp", "max_issues_repo_name": "wangyuanbiubiubiu/ICE-BA-Annotation", "max_issues_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T11:57:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T01:47:22.000Z", "max_forks_repo_path": "App/ICE-BA-ROS.cpp", "max_forks_repo_name": "wangyuanbiubiubiu/ICE-BA-Annotation", "max_forks_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-06T10:19:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T13:23:22.000Z", "avg_line_length": 41.3730496454, "max_line_length": 175, "alphanum_fraction": 0.5220789907, "num_tokens": 7496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.1843495832145345}}
{"text": "// ======================================================================\n/*!\n * \\file shapepack.cpp\n * \\brief A program to convert a shapefile into a packed attribute table\n */\n// ======================================================================\n/*!\n * \\page shapepack shapepack\n *\n * shapepack takes as input a single file shapefile containing latlon\n * polygonal data, the name of the desired attribute, and converts the\n * shape into packed 2D table. The default bounding box for the data\n * is the world from -180 to 180 longitude, -90 to 90 latitude, but\n * it can be altered via the command line.\n *\n * The program was originally created for getting a quick method to\n * determine the timezone of any given coordinate on the planet.\n * The selected attribute was the name of the timezone at the coordinate.\n * For this reason the 2D table is always indexed so that latitude\n * is the inner index in the actual binary encoded table.\n *\n * The format of the shapepacked file is as follows\n * \\code\n * SHAPEPACK\n * width_in_pixels height_in_pixels\n * lon1 lat1 lon2 lat2\n * number_of_attributes\n * attribute1\n * attribute2\n * ...\n * attributeN\n * table2d\n * \\endcode\n * The header part is in plain ASCII, the 2D table is in the following\n * binary format:\n * \\code\n * uint32 number_of_entries\n * uint32 position1 (always 0)\n * uint16 attribute_index_1\n * uint32 position2\n * uint16 attribute_index_2\n * ...\n * uint32 positionN (always width*height)\n * uint16 0\n * \\endcode\n * The indices start at one. Zero return values are used to indicate\n * missing data. The final zero is output only for programming convenience.\n *\n * The position for a particular latlon coordinate is calculated as\n * follows:\n * \\code\n * ypos = (lat-lat1)/(lat2-lat1)*(height-1)\n * xpos = (lon-lon1)/(lon2-lon1)*(width-1)\n * pos = ypos+xpos*height\n * \\endcode\n * ypos and xpos are rounded to nearest integers before the final\n * integer position is calculated.\n *\n */\n// ======================================================================\n\n#include <imagine/NFmiEsriPolygon.h>\n#include <imagine/NFmiEsriShape.h>\n#include <imagine/NFmiFillMap.h>\n#include <imagine/NFmiImage.h>\n\n#include <macgyver/WorldTimeZones.h>\n\n#include <boost/foreach.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <set>\n#include <stdexcept>\n#include <string>\n\nextern \"C\"\n{\n#include <stdint.h>\n}\n\nusing namespace std;\nusing namespace Imagine;\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Command line options\n */\n// ----------------------------------------------------------------------\n\nstruct Options\n{\n  string shapefile;\n  string packfile;\n  string pngfile;\n  string zonefile;\n  int width;\n  int height;\n  float lon1;\n  float lat1;\n  float lon2;\n  float lat2;\n  string attribute;\n  bool verbose;\n  bool accurate;\n\n  Options()\n      : shapefile(),\n        packfile(),\n        pngfile(),\n        zonefile(),\n        width(-1),\n        height(-1),\n        lon1(-180),\n        lat1(-90),\n        lon2(180),\n        lat2(90),\n        attribute(),\n        verbose(false),\n        accurate(false)\n  {\n  }\n};\n\nOptions options;\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Parse the command line\n */\n// ----------------------------------------------------------------------\n\nbool parse_options(int argc, char *argv[])\n{\n  namespace po = boost::program_options;\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help,h\", \"print out help message\")(\n      \"verbose,v\", po::bool_switch(&options.verbose), \"set verbose mode on\")(\n      \"version,V\", \"display version number\")(\n      \"attribute,a\", po::value(&options.attribute), \"shapefile attribute name\")(\n      \"shapefile,s\", po::value(&options.shapefile), \"shapefile (without suffix)\")(\n      \"output,o\", po::value(&options.packfile), \"output filename\")(\n      \"pngfile,p\", po::value(&options.pngfile), \"optional image filename\")(\n      \"zonefile,z\",\n      po::value(&options.zonefile),\n      \"optional shapepack with which to combine the information with\")(\n      \"width,W\", po::value(&options.width), \"width of rendered image\")(\n      \"height,H\", po::value(&options.height), \"height of rendered image\")(\n      \"lon1\", po::value(&options.lon1), \"bottom left longitude (default is -180)\")(\n      \"lat1\", po::value(&options.lat1), \"bottom left latitude (default is -90)\")(\n      \"lon2\", po::value(&options.lon2), \"top right longitude (default is 180)\")(\n      \"lat2\", po::value(&options.lat2), \"top right latitude (default is 90)\")(\n      \"accurate,A\", po::bool_switch(&options.accurate));\n\n  po::positional_options_description p;\n  p.add(\"shapefile\", 1);\n  p.add(\"output\", 1);\n\n  po::variables_map opt;\n  po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), opt);\n\n  po::notify(opt);\n\n  if (opt.count(\"version\") != 0)\n  {\n    cout << \"shapepack v1.0 (\" << __DATE__ << ' ' << __TIME__ << ')' << endl;\n  }\n\n  if (opt.count(\"help\"))\n  {\n    cout << \"Usage: shapepack [options] shapefile outfile\" << endl\n         << endl\n         << \"shapepack picks an attribute from a polygonal shapefile\" << endl\n         << \"and converts the data into a fast access 2D table.\" << endl\n         << endl\n         << desc << endl;\n    return false;\n  }\n\n  if (opt.count(\"shapefile\") == 0)\n    throw runtime_error(\"shapefile name not specified\");\n\n  if (opt.count(\"output\") == 0)\n    throw runtime_error(\"output name not specified\");\n\n  // Check bounding box\n\n  if (options.lon1 >= options.lon2 || options.lat1 >= options.lat2)\n    throw runtime_error(\"Stupid bounding box, fix it\");\n\n  // Preserve image aspect if one size attribute is missing\n\n  if (options.width < 0 && options.height < 0)\n    throw runtime_error(\"Either image width or height must be specified\");\n\n  if (options.width < 0 && options.height > 0)\n  {\n    options.width = static_cast<int>(options.height * (options.lon2 - options.lon1) /\n                                     (options.lat2 - options.lat1));\n  }\n\n  if (options.height < 0 && options.width > 0)\n  {\n    options.height = static_cast<int>(options.width * (options.lat2 - options.lat1) /\n                                      (options.lon2 - options.lon1));\n  }\n\n  if (options.height == 0 || options.width == 0)\n    throw runtime_error(\"Try a larger image, this is pointless\");\n\n  return true;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Get attribute value as string\n */\n// ----------------------------------------------------------------------\n\nstring get_attribute_value(const NFmiEsriElement &theElement, const NFmiEsriAttributeName &theName)\n{\n  string name = theName.Name();\n  switch (theName.Type())\n  {\n    case kFmiEsriString:\n      return theElement.GetString(name);\n    case kFmiEsriInteger:\n      return boost::lexical_cast<string>(theElement.GetInteger(name));\n    case kFmiEsriDouble:\n      return boost::lexical_cast<string>(theElement.GetDouble(name));\n    default:\n      throw runtime_error(\"Unknown attribute value type\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Find the given attribute name\n */\n// ----------------------------------------------------------------------\n\nNFmiEsriShape::attributes_type::const_iterator find_attribute(\n    const NFmiEsriShape::attributes_type &theAttributes, const std::string &theName)\n{\n  NFmiEsriShape::attributes_type::const_iterator it = theAttributes.begin();\n  for (; it != theAttributes.end(); ++it)\n  {\n    if ((*it)->Name() == theName)\n      break;\n  }\n  if (it == theAttributes.end())\n    throw runtime_error(\"No attribute named '\" + theName + \"' in the shape\");\n  return it;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Find all unique attribute values for the given attribute\n */\n// ----------------------------------------------------------------------\n\nset<string> find_unique_attributes(const NFmiEsriShape &theShape, const string &theAttribute)\n{\n  const NFmiEsriShape::attributes_type &attributes = theShape.Attributes();\n\n  NFmiEsriShape::attributes_type::const_iterator at = find_attribute(attributes, theAttribute);\n\n  set<string> values;\n\n  for (NFmiEsriShape::const_iterator it = theShape.Elements().begin();\n       it != theShape.Elements().end();\n       ++it)\n  {\n    if (*it == nullptr)\n      continue;\n    string value = get_attribute_value(**it, **at);\n    values.insert(value);\n  }\n\n  return values;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Verbose printout of unique attribute values\n */\n// ----------------------------------------------------------------------\n\nvoid print_uniques(const set<string> &theValues)\n{\n  cout << \"There were \" << theValues.size() << \" unique values in the shape:\" << endl;\n  int pos = 1;\n  for (set<string>::const_iterator it = theValues.begin(); it != theValues.end(); ++it, ++pos)\n  {\n    cout << pos << ' ' << *it << endl;\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Map set of strings to integer indices\n */\n// ----------------------------------------------------------------------\n\nmap<string, int> make_attribute_map(const set<string> &theSet)\n{\n  map<string, int> ret;\n  int i = 1;\n  for (set<string>::const_iterator it = theSet.begin(); it != theSet.end(); ++it)\n  {\n    ret.insert(map<string, int>::value_type(*it, i++));\n  }\n  return ret;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Pixel scaling\n */\n// ----------------------------------------------------------------------\n\ninline float xpixel(float x)\n{\n  return (x + 180) / 360 * options.width;\n}\n\ninline float ypixel(float y)\n{\n  return (y + 90) / 180 * options.height;\n}\n\ninline float lonpixel(int x)\n{\n  return (360.0 * x / options.width - 180);\n}\n\ninline float latpixel(int y)\n{\n  return (180.0 * y / options.height - 90);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Insert polygon to fillmap\n */\n// ----------------------------------------------------------------------\n\nvoid polygon_to_fillmap(NFmiFillMap &theMap, const NFmiEsriElement *theElement)\n{\n  switch (theElement->Type())\n  {\n    case kFmiEsriPolygon:\n    case kFmiEsriPolygonM:\n    case kFmiEsriPolygonZ:\n    {\n      const NFmiEsriPolygon *elem = static_cast<const NFmiEsriPolygon *>(theElement);\n      for (int part = 0; part < elem->NumParts(); part++)\n      {\n        int i1, i2;\n        i1 = elem->Parts()[part];  // start of part\n        if (part + 1 == elem->NumParts())\n          i2 = elem->NumPoints() - 1;  // end of part\n        else\n          i2 = elem->Parts()[part + 1] - 1;  // end of part\n\n        for (int i = i1 + 1; i <= i2; i++)\n          theMap.Add(xpixel(elem->Points()[i - 1].X()),\n                     ypixel(elem->Points()[i - 1].Y()),\n                     xpixel(elem->Points()[i].X()),\n                     ypixel(elem->Points()[i].Y()));\n      }\n      break;\n    }\n    default:\n      break;\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Render the image to be compressed\n */\n// ----------------------------------------------------------------------\n\nvoid render_image(NFmiImage &theImage,\n                  const NFmiEsriShape &theShape,\n                  const map<string, int> &theValues)\n{\n  if (options.verbose)\n  {\n    cout << \"Rendering \" << theImage.Width() << \"x\" << theImage.Height()\n         << \" size image, this may take a while\" << endl;\n  }\n\n  // Attribute information\n\n  const NFmiEsriShape::attributes_type &attributes = theShape.Attributes();\n\n  NFmiEsriShape::attributes_type::const_iterator at = find_attribute(attributes, options.attribute);\n\n  for (NFmiEsriShape::const_iterator it = theShape.Elements().begin();\n       it != theShape.Elements().end();\n       ++it)\n  {\n    if (*it == nullptr)\n      continue;\n\n    const string value = get_attribute_value(**it, **at);\n    NFmiColorTools::Color color = theValues.find(value)->second;\n\n    NFmiFillMap fillmap;\n    polygon_to_fillmap(fillmap, *it);\n    fillmap.Fill(theImage, color, NFmiColorTools::kFmiColorCopy);\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Test if the given point is inside the polygon\n *\n * Copied from shapefind.cpp\n */\n// ----------------------------------------------------------------------\n\nbool is_inside(const NFmiEsriPolygon &thePoly, double theX, double theY)\n{\n  // Check bounding box first\n  const NFmiEsriBox &box = thePoly.Box();\n\n  if (!box.IsValid())\n    return false;\n\n  if (theX < box.Xmin() || theX > box.Xmax() || theY < box.Ymin() || theY > box.Ymax())\n    return false;\n\n  // Then do an actual inside-test if it is possible the point is inside\n\n  int counter = 0;\n\n  for (int part = 0; part < thePoly.NumParts(); part++)\n  {\n    int i1 = thePoly.Parts()[part];  // start of part\n    int i2;\n    if (part + 1 == thePoly.NumParts())\n      i2 = thePoly.NumPoints() - 1;  // end of part\n    else\n      i2 = thePoly.Parts()[part + 1] - 1;  // end of part\n\n    if (i2 >= i1)\n    {\n      double x1 = thePoly.Points()[i1].X();\n      double y1 = thePoly.Points()[i1].Y();\n\n      for (int i = i1 + 1; i <= i2; i++)\n      {\n        double x2 = thePoly.Points()[i].X();\n        double y2 = thePoly.Points()[i].Y();\n        if (theY > std::min(y1, y2) && theY <= std::max(y1, y2) && theX <= std::max(x1, x2) &&\n            y1 != y2)\n        {\n          const double xinters = (theY - y1) * (x2 - x1) / (y2 - y1) + x1;\n          if (x1 == x2 || theX <= xinters)\n            counter++;\n        }\n        x1 = x2;\n        y1 = y2;\n      }\n    }\n  }\n\n  return (counter % 2 != 0);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Find polygon surrounding point from polygon shapefile\n */\n// ----------------------------------------------------------------------\n\nstring find_enclosing_polygon(const NFmiEsriShape &theShape, float theLon, float theLat)\n{\n  // Find the first match\n\n  const NFmiEsriShape::elements_type &elements = theShape.Elements();\n\n  NFmiEsriShape::elements_type::size_type i;\n  for (i = 0; i < elements.size(); i++)\n  {\n    if (elements[i] == 0)  // null element?\n      continue;\n\n    const NFmiEsriPolygon *elem = static_cast<const NFmiEsriPolygon *>(elements[i]);\n\n    bool enclosed = is_inside(*elem, theLon, theLat);\n\n    if (enclosed)\n      break;\n  }\n\n  // Print the results.\n\n  if (i < elements.size())\n  {\n    const NFmiEsriPolygon *elem = static_cast<const NFmiEsriPolygon *>(elements[i]);\n    const NFmiEsriShape::attributes_type &attributes = theShape.Attributes();\n    NFmiEsriShape::attributes_type::const_iterator at =\n        find_attribute(attributes, options.attribute);\n    const string value = get_attribute_value(*elem, **at);\n    return value;\n  }\n  else\n    return \"\";\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Test if pixel color is the same if the coordinate is inside image\n *\n * We intentionally return true for pixels outside the image.\n */\n// ----------------------------------------------------------------------\n\ninline bool same_color(const NFmiImage &theImage, int i, int j, NFmiColorTools::Color c)\n{\n  return (i < 0 || j < 0 || i >= theImage.Width() || j >= theImage.Height() || theImage(i, j) == c);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Check if pixel is surrounded by indentical pixels or not\n */\n// ----------------------------------------------------------------------\n\ninline bool is_boundary_pixel(const NFmiImage &theImage, int i, int j)\n{\n  const NFmiColorTools::Color color = theImage(i, j);\n\n  return !(same_color(theImage, i - 1, j - 1, color) && same_color(theImage, i + 1, j - 1, color) &&\n           same_color(theImage, i, j - 1, color) && same_color(theImage, i - 1, j, color) &&\n           same_color(theImage, i + 1, j, color) && same_color(theImage, i - 1, j + 1, color) &&\n           same_color(theImage, i, j + 1, color) && same_color(theImage, i + 1, j + 1, color));\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Guess timezone from nearest pixels if filling fails\n *\n * This is needed mostly to get values for pixels at -180/+180 longitudes\n * since those coordinates are not strictly inside polygons. We only\n * check horizontally or vertically adjacent pixels.\n */\n// ----------------------------------------------------------------------\n\ninline int find_nearest_zone(const NFmiImage &theImage, int i, int j)\n{\n  if (i - 1 >= 0 && theImage(i - 1, j) >= 0)\n    return theImage(i, j);\n  if (i + 1 < theImage.Width() && theImage(i + 1, j) >= 0)\n    return theImage(i + 1, j);\n  if (j - 1 >= 0 && theImage(i, j - 1) >= 0)\n    return theImage(i, j - 1);\n  if (j + 1 < theImage.Height() && theImage(i, j + 1) >= 0)\n    return theImage(i, j + 1);\n  return -1;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Check accuracy of image near borders\n */\n// ----------------------------------------------------------------------\n\nvoid refine_image(NFmiImage &theImage,\n                  const NFmiEsriShape &theShape,\n                  const map<string, int> &theValues)\n{\n  int checks = 0;\n  int changes = 0;\n  int pixels = 0;\n\n  int percentage = 0;\n  int perstep = 1;\n  int total_pixels = theImage.Width() * theImage.Height();\n\n  if (options.verbose)\n    cout << \"Validating border areas...\" << endl;\n\n  for (int i = 0; i < theImage.Width(); i++)\n    for (int j = 0; j < theImage.Height(); j++)\n    {\n      ++pixels;\n      if (pixels * 100.0 / total_pixels - percentage > perstep)\n      {\n        percentage += perstep;\n        if (options.verbose)\n          cout << \"\\t\" << percentage << \"%\" << endl;\n      }\n\n      if (theImage(i, j) < 0 || is_boundary_pixel(theImage, i, j))\n      {\n        ++checks;\n\n        string tz = find_enclosing_polygon(theShape, lonpixel(i), latpixel(j));\n\n        if (!tz.empty())\n        {\n          int idx = theValues.find(tz)->second;\n          if (theImage(i, j) != idx)\n          {\n            if (options.verbose)\n              cout << \"Changed \" << i << \",\" << j << \" value from \" << theImage(i, j) << \" to \"\n                   << idx << \" (\" << tz << \")\" << endl;\n            ++changes;\n            theImage(i, j) = idx;\n          }\n        }\n      }\n\n      if (theImage(i, j) < 0)\n      {\n        auto idx = find_nearest_zone(theImage, i, j);\n        if (idx > 0)\n        {\n          theImage(i, j) = idx;\n          ++changes;\n          if (options.verbose)\n            cout << \"Changed \" << i << \",\" << j << \" value from -1 to \" << idx << endl;\n        }\n      }\n    }\n\n  if (options.verbose)\n    cout << \"Total checks:  \" << checks << endl << \"Total changes: \" << changes << endl;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Output uint32 binary representation\n */\n// ----------------------------------------------------------------------\n\nvoid output_uint32(std::ostream &out, uint32_t theValue)\n{\n  uint32_t value = theValue;\n  out.write(reinterpret_cast<char *>(&value), sizeof(uint32_t));\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Output uint16 binary representation\n */\n// ----------------------------------------------------------------------\n\nvoid output_uint16(std::ostream &out, uint16_t theValue)\n{\n  uint16_t value = theValue;\n  out.write(reinterpret_cast<char *>(&value), sizeof(uint16_t));\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Compress the image\n */\n// ----------------------------------------------------------------------\n\nstring compress_image(const NFmiImage &theImage, const map<string, int> &theMap)\n{\n  // Header\n  ostringstream out;\n  out << \"SHAPEPACK\\n\"\n      << theImage.Width() << ' ' << theImage.Height() << '\\n'\n      << options.lon1 << ' ' << options.lat1 << ' ' << options.lon2 << ' ' << options.lat2 << '\\n';\n\n  // Attribute index\n\n  out << theMap.size() << '\\n';\n\n  for (map<string, int>::const_iterator it = theMap.begin(); it != theMap.end(); ++it)\n  {\n    out << it->first << '\\n';\n  }\n\n  // Raw data\n\n  ostringstream table;\n  int startpos = 0;\n  int entries = 0;\n  int lastcolor = theImage(0, 0);\n  int duplicates = 0;\n\n#if 1\n  std::cout << \"Unique values:\" << std::endl;\n  std::set<int> uniques;\n  int last = -1000;\n  for (int i = 0; i < theImage.Width(); i++)\n    for (int j = 0; j < theImage.Height(); j++)\n    {\n      if (theImage(i, j) != last)\n        uniques.insert(theImage(i, j));\n      last = theImage(i, j);\n    }\n  BOOST_FOREACH (int c, uniques)\n    std::cout << c << std::endl;\n#endif\n\n  if (options.verbose)\n    std::cout << \"Compressing the image data\" << std::endl;\n\n  for (int i = 0; i < theImage.Width(); i++)\n    for (int j = 0; j < theImage.Height(); j++)\n    {\n      if (theImage(i, j) == lastcolor)\n        ++duplicates;\n      else\n      {\n        ++entries;\n        output_uint32(table, startpos);\n        output_uint16(table, lastcolor);\n        startpos = j + i * theImage.Height();\n        lastcolor = theImage(i, j);\n      }\n    }\n  // Flush remaining line\n  if (duplicates > 0)\n  {\n    output_uint32(table, startpos);\n    output_uint16(table, lastcolor);\n  }\n  // And terminate table\n  output_uint32(table, theImage.Width() * theImage.Height());\n  output_uint16(table, 0);\n\n  // Final output\n\n  output_uint32(out, entries);\n  out << table.str();\n\n  return out.str();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Render a shapepack onto an image\n */\n// ----------------------------------------------------------------------\n\nvoid render_shapepack(NFmiImage &img,\n                      const Fmi::WorldTimeZones &zones,\n                      const map<string, int> &attmap)\n{\n  if (options.verbose)\n    std::cout << \"Rendering background shapepack\" << std::endl;\n\n  for (int i = 0; i < img.Width(); i++)\n    for (int j = 0; j < img.Height(); j++)\n    {\n      try\n      {\n        std::string tz = zones.zone_name(lonpixel(i), latpixel(j));\n        map<string, int>::const_iterator it = attmap.find(tz);\n        if (it == attmap.end())\n        {\n          cerr << \"Failed to find index for timezone \" << tz << \" at coordinate \" << i << \",\" << j\n               << \" at lonlat \" << lonpixel(i) << \",\" << latpixel(j) << endl;\n        }\n        else\n          img(i, j) = attmap.find(tz)->second;\n      }\n      catch (...)\n      {\n      }\n    }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief The main program\n *\n * -# read the shapefile\n * -# verify chosen attribute is valid\n * -# list all unique attribute values\n * -# render the polygons using attribute indices as values\n * -# compress the image\n * -# output the image\n */\n// ----------------------------------------------------------------------\n\nint domain(int argc, char *argv[])\n{\n  if (!parse_options(argc, argv))\n    return 0;\n\n  // Read the shape\n\n  NFmiEsriShape shape;\n  if (!shape.Read(options.shapefile, true))\n    throw runtime_error(\"Failed to read '\" + options.shapefile + \"'\");\n\n  const NFmiEsriShape::attributes_type &attributes = shape.Attributes();\n\n  if (attributes.size() == 0)\n    throw runtime_error(\"shapefile does not contain any attributes\");\n\n  // If no attribute option was given, we accept it as long as\n  // the shape contains exactly one attribute\n\n  if (options.attribute.empty())\n  {\n    if (attributes.size() > 1)\n    {\n      ostringstream out;\n      out << \"shapefile contains multiple attributes, choose one: \";\n      int pos = 0;\n      for (NFmiEsriShape::attributes_type::const_iterator at = attributes.begin();\n           at != attributes.end();\n           ++at, ++pos)\n      {\n        if (pos > 0)\n          out << \",\";\n        out << (*at)->Name();\n      }\n\n      throw runtime_error(out.str());\n    }\n    options.attribute = (*attributes.begin())->Name();\n  }\n\n  // Help informatio\n\n  boost::shared_ptr<Fmi::WorldTimeZones> zones;\n  if (!options.zonefile.empty())\n    zones.reset(new Fmi::WorldTimeZones(options.zonefile));\n\n  // Unique attributes\n\n  set<string> uniques = find_unique_attributes(shape, options.attribute);\n\n  if (options.verbose)\n    print_uniques(uniques);\n\n  if (zones)\n  {\n    BOOST_FOREACH (const string &z, zones->zones())\n      uniques.insert(z);\n  }\n\n  map<string, int> attmap = make_attribute_map(uniques);\n\n  if (options.verbose)\n    print_uniques(uniques);\n\n  // Render the image\n\n  NFmiImage img(options.width, options.height, -1);\n  if (zones)\n    render_shapepack(img, *zones, attmap);\n\n  render_image(img, shape, attmap);\n\n  if (options.accurate)\n    refine_image(img, shape, attmap);\n\n  if (!options.pngfile.empty())\n    img.WritePng(options.pngfile);\n\n  // Compress the data\n\n  string data = compress_image(img, attmap);\n\n  ofstream out(options.packfile.c_str());\n  if (!out)\n    throw runtime_error(\"Could not open '\" + options.packfile + \"' for writing\");\n  out << data;\n  out.close();\n\n  return 0;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Main program\n */\n// ----------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n  try\n  {\n    return domain(argc, argv);\n  }\n  catch (exception &e)\n  {\n    cerr << \"Error: \" << e.what() << endl;\n  }\n  catch (...)\n  {\n    cerr << \"Error: An unknown exception occurred\" << endl;\n  }\n  return 1;\n}\n", "meta": {"hexsha": "3c2441ac689a5eb138fc7b2f3363a5b121a9fb5c", "size": 25648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main/shapepack.cpp", "max_stars_repo_name": "fmidev/smartmet-shapetools", "max_stars_repo_head_hexsha": "8ca25d3a007af8582c2553c9f608ec18482ea0d4", "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/shapepack.cpp", "max_issues_repo_name": "fmidev/smartmet-shapetools", "max_issues_repo_head_hexsha": "8ca25d3a007af8582c2553c9f608ec18482ea0d4", "max_issues_repo_licenses": ["MIT"], "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/shapepack.cpp", "max_forks_repo_name": "fmidev/smartmet-shapetools", "max_forks_repo_head_hexsha": "8ca25d3a007af8582c2553c9f608ec18482ea0d4", "max_forks_repo_licenses": ["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.3403314917, "max_line_length": 100, "alphanum_fraction": 0.5279164067, "num_tokens": 6165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047914, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18434958133316923}}
{"text": "#include \"../elysium.h\"\n#include \"../rules.h\"\n#include \"../sp.h\"\n\n#include \"base58.h\"\n#include \"chainparams.h\"\n#include \"test/test_bitcoin.h\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <limits>\n\nusing namespace elysium;\n\nBOOST_FIXTURE_TEST_SUITE(elysium_elysium_tests, TestingSetup)\n\nBOOST_AUTO_TEST_CASE(elysium_mints_overflow)\n{\n    _my_sps = new CMPSPInfo(pathTemp / \"MP_spinfo_test\", false);\n\n    CMPSPInfo::Entry sp;\n    sp.denominations = {MAX_INT_8_BYTES};\n    auto property = _my_sps->putSP(0, sp); // non-standard\n\n    std::vector<uint8_t> denoms = {0, 0};\n    BOOST_CHECK_EXCEPTION(\n        SumDenominationsValue(property, denoms.begin(), denoms.end()),\n        std::overflow_error,\n        [](std::overflow_error const &e) -> bool {\n            return std::string(\"summation of mints is overflow\") == e.what();\n        }\n    );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "128af24166666b1bbaa89252bcce7032b9035e20", "size": 874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/elysium/test/elysium_tests.cpp", "max_stars_repo_name": "blondfrogs/tecracoin", "max_stars_repo_head_hexsha": "8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 582.0, "max_stars_repo_stars_event_min_datetime": "2016-09-26T00:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T19:07:24.000Z", "max_issues_repo_path": "src/elysium/test/elysium_tests.cpp", "max_issues_repo_name": "blondfrogs/tecracoin", "max_issues_repo_head_hexsha": "8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 570.0, "max_issues_repo_issues_event_min_datetime": "2016-09-28T07:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T10:24:19.000Z", "max_forks_repo_path": "src/elysium/test/elysium_tests.cpp", "max_forks_repo_name": "blondfrogs/tecracoin", "max_forks_repo_head_hexsha": "8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 409.0, "max_forks_repo_forks_event_min_datetime": "2016-09-21T12:37:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-18T14:54:17.000Z", "avg_line_length": 24.2777777778, "max_line_length": 77, "alphanum_fraction": 0.680778032, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.1843495760964686}}
{"text": "/*\n * Copyright 2016 The Cartographer Authors\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 \"cartographer/mapping/internal/3d/scan_matching/ceres_scan_matcher_3d.h\"\n\n#include <memory>\n\n#include \"Eigen/Core\"\n#include \"cartographer/common/internal/testing/lua_parameter_dictionary_test_helpers.h\"\n#include \"cartographer/mapping/3d/hybrid_grid.h\"\n#include \"cartographer/sensor/point_cloud.h\"\n#include \"cartographer/sensor/internal/voxel_filter.h\"\n#include \"cartographer/transform/rigid_transform.h\"\n#include \"cartographer/transform/rigid_transform_test_helpers.h\"\n#include \"gtest/gtest.h\"\n#include \"cartographer/mapping/internal/3d/scan_matching/occupied_space_cost_function_3d.h\"\n#include <chrono>\n#include <thread>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/registration/icp.h>\n#include <pcl/registration/gicp.h>\n#include <pcl/registration/ndt.h>\n#include <pcl/filters/approximate_voxel_grid.h>\n#include <pcl/visualization/pcl_visualizer.h>\n//using namespace std::chrono_literals;\n#include <map>\n#include <boost/algorithm/string/trim.hpp>\n#include <string.h>\n#include <regex>\n/* jwang 1/6/22\n *\n * TestFromInitialPose2()\n *\n * ptselection = 0|1|2\n * 0 for pcd file\n * 1 for dbg file\n * 2 for two pcd files: one for submap and one for curr scan\n * point_cloud_3_ from debug file\n * point_cloud_2_ from pcdfilename\n *\n *\n */\nnamespace cartographer {\nnamespace mapping {\nnamespace scan_matching {\nnamespace {\nclass CeresScanMatcher3DTest : public ::testing::Test {\n protected:\n  CeresScanMatcher3DTest()\n      : hybrid_grid_(0.1f),\n        intensity_hybrid_grid_(0.1f),\n        expected_pose_(\n            transform::Rigid3d::Translation(Eigen::Vector3d(-1., 0., 0.))) {\n    std::vector<sensor::RangefinderPoint> points;\n    std::vector<float> intensities;\n    for (const Eigen::Vector3f& point :\n         {Eigen::Vector3f(-3.f, 2.f, 0.f), Eigen::Vector3f(-4.f, 2.f, 0.f),\n          Eigen::Vector3f(-5.f, 2.f, 0.f), Eigen::Vector3f(-6.f, 2.f, 0.f),\n          Eigen::Vector3f(-6.f, 3.f, 1.f), Eigen::Vector3f(-6.f, 4.f, 2.f),\n          Eigen::Vector3f(-7.f, 3.f, 1.f)}) \n    {\n      points.push_back({point});\n      intensities.push_back(50);\n      hybrid_grid_.SetProbability(\n          hybrid_grid_.GetCellIndex(expected_pose_.cast<float>() * point), 1.);\n      intensity_hybrid_grid_.AddIntensity(\n          intensity_hybrid_grid_.GetCellIndex(expected_pose_.cast<float>() *\n                                              point),\n          50);\n    }\n    point_cloud_ = sensor::PointCloud(points, intensities);\n    std::string filename2=\"testopt2.txt\";\n    std::ifstream stream2(filename2.c_str());\n    std::string myoptstr2= std::string((std::istreambuf_iterator<char>(stream2)),\n                     std::istreambuf_iterator<char>());\n    char *token;\n    token = strtok(const_cast<char*>(myoptstr2.c_str()), \"\\n\");\n    while (token != NULL) {\n\t    std::string s(token);\n\t    size_t pos = s.find(\":\");\n\t    std::string svalue = s.substr(pos + 1, std::string::npos);\n\t    boost::algorithm::trim(svalue);\n\t    mymap[s.substr(0, pos)] = svalue;\n\t    token = strtok(NULL, \"\\n\");\n    }\n\n    //for (auto keyval : mymap)\n    //\t    std::cout << keyval.first << \":\" << keyval.second << std::endl;\n    //std::cout<< mymap[\"pcdfilename\"] <<std::endl;\n\n    std::string filename=\"testopt.lua\";\n    std::ifstream stream(filename.c_str());\n    myoptstr= std::string((std::istreambuf_iterator<char>(stream)),\n                     std::istreambuf_iterator<char>());\n    //LOG(INFO)<< myoptstr;\n\n    std::string testoptstr=R\"text(\n        return {\n          occupied_space_weight_0 = 1.,\n          intensity_cost_function_options_0 = {\n            weight = 0.5,\n            huber_scale = 55,\n            intensity_threshold = 100,\n          },\n          translation_weight = 0.01,\n          rotation_weight = 0.1,\n          only_optimize_yaw = false,\n          ceres_solver_options = {\n            use_nonmonotonic_steps = true,\n            max_num_iterations = 100,\n            num_threads = 1,\n          },\n        })text\";\n\n    auto parameter_dictionary = common::MakeDictionary(myoptstr);\n    options_ = CreateCeresScanMatcherOptions3D(parameter_dictionary.get());\n    //LOG(INFO) << parameter_dictionary->GetKeys();\n    //LOG(INFO) << parameter_dictionary->ToString();\n    ceres_scan_matcher_.reset(new CeresScanMatcher3D(options_));\n  }\n/********************************************************************/\n  void TestFromInitialPose(const transform::Rigid3d& initial_pose) {\n    transform::Rigid3d pose;\n\n    ceres::Solver::Summary summary;\n\n    IntensityHybridGrid* intensity_hybrid_grid_ptr =\n        point_cloud_.intensities().empty() ? nullptr : &intensity_hybrid_grid_;\n\n    ceres_scan_matcher_->Match(\n        initial_pose.translation(), initial_pose,\n        {{&point_cloud_, &hybrid_grid_, intensity_hybrid_grid_ptr}}, &pose,\n        &summary);\n    LOG(INFO) << \"estimated pose: \"<< pose;\n    EXPECT_NEAR(0., summary.final_cost, 1e-2) << summary.FullReport();\n    EXPECT_THAT(pose, transform::IsNearly(expected_pose_, 3e-2));\n  }\n\n\n/* ******************************************************\n * convert initpose string to Rigid3d\n */\n  transform::Rigid3d makepose(std::string posestring)\n  {\n\t  std::cout<<\"\\nmake pose: \" <<\"\\n\";\n\t  std::istringstream ss(posestring);\n\t  float x,y,z,qw,qx,qy,qz;\n\t  ss>> x;\n\t  ss>> y;\n\t  ss>> z;\n\t  ss>> qw;\n\t  ss>> qx;\n\t  ss>> qy;\n\t  ss>> qz;\n\t  std::cout << \"xyz: \" <<x <<\" \" <<y<<\" \" <<z<<\" quat \" <<qw<<\" \" <<qx<<\" \" <<qy<<\" \" <<qz <<\"\\n\";\n\t  Eigen::Matrix<double, 3, 1> trans;\n\t  Eigen::Vector3d trans2;\n\t  trans2 = Eigen::Vector3d(x, y,z);\n\t  //trans2 = Eigen::Vector3d(-0.95, -0.05, 0.05);\n\t  std::cout<<\"\\nmake pose: input pose: wxyz \" <<qw<<\" \" << qx<<\" \"<< qy<<\" \" <<qz<<\"\\n\";\n\t  Eigen::Quaternion<double> rotation(qw,qx,qy,qz);\n\t  Eigen::Quaternion<double> rotation3=rotation.normalized();\n\t  Eigen::Matrix3d mat3 = rotation3.toRotationMatrix();\n\t  Eigen::Quaternion<double> rotation2(mat3);\n\t  std::cout<<\"\\nmake pose: eigen pose normalized: wxyz \" <<rotation3.w()<<\" \" << rotation3.x()<<\" \"<< rotation3.y()<<\" \" <<rotation3.z()<<\"\\n\";\n\t  std::cout<<\"\\nmake pose: eigen pose recreated: wxyz \" <<rotation2.w()<<\" \" << rotation2.x()<<\" \"<< rotation2.y()<<\" \" <<rotation2.z()<<\"\\n\";\n\t  //Eigen::Quaternion<double> rotation(1,0,0,0);\n\t  return transform::Rigid3d(trans2, rotation2);\n  }\n  /*************** convert xyzi cloud t xyz cloud  ****/\n  void convert_xyzi_2_xyz(pcl::PointCloud<pcl::PointXYZI>::Ptr pclcloud_i, pcl::PointCloud<pcl::PointXYZ>::Ptr pclcloud)\n  {\n\t  pcl::PointCloud<pcl::PointXYZ>::Ptr target_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n\t  pclcloud->width = pclcloud_i->width;\n\t  pclcloud->height = 1;\n\t  pclcloud->is_dense = false;\n\n\t  pclcloud->points.resize (pclcloud->width * pclcloud->height);\n\t  for (int i =0; i< pclcloud->width; i++){\n\t\t  pclcloud->points[i].x= pclcloud_i->points[i].x;\n\t\t  pclcloud->points[i].y= pclcloud_i->points[i].y;\n\t\t  pclcloud->points[i].z= pclcloud_i->points[i].z;\n\t  }\n\t  //pclcloud= target_cloud; this not work\n  }\n/******************************************************\n * convert PCD XYZI cloud to carto's hybrid_grid\n */\n  \n  void PCDCloud_2_HybridGrid(pcl::PointCloud<pcl::PointXYZI>::Ptr pclcloud, HybridGrid & hybrid_grid, IntensityHybridGrid & intensity_hybrid_grid)\n  {\n    int ptcount=0;\n\n    Eigen::Vector3f point;\n    for (const pcl::PointXYZI& pointxyzi : pclcloud->points)\n    {\n\tptcount++;\n\tpoint(0)=pointxyzi.x;\n\tpoint(1)=pointxyzi.y;\n\tpoint(2)=pointxyzi.z;\n\thybrid_grid.SetProbability(\n          hybrid_grid.GetCellIndex(point), pointxyzi.intensity);\n\tintensity_hybrid_grid.AddIntensity(\n          intensity_hybrid_grid.GetCellIndex(point),\n          50);\n    }\n  }\n  \n/******************************************************\n * convert PCD cloud to carto's hybrid_grid\n */\n  void PCDCloud_2_HybridGrid(pcl::PointCloud<pcl::PointXYZ>::Ptr pclcloud, HybridGrid & hybrid_grid, IntensityHybridGrid & intensity_hybrid_grid)\n  {\n    int ptcount=0;\n\n    Eigen::Vector3f point;\n    // pc2 points number: 33024\n    for (const pcl::PointXYZ& pointxyz : pclcloud->points)\n    {\n\tptcount++;\n\tpoint(0)=pointxyz.x;\n\tpoint(1)=pointxyz.y;\n\tpoint(2)=pointxyz.z;\n\thybrid_grid.SetProbability(\n          hybrid_grid.GetCellIndex(point), 1.);\n\tintensity_hybrid_grid.AddIntensity(\n          intensity_hybrid_grid.GetCellIndex(point),\n          50);\n    }\n    std::cout<< \"pcd RangefinderPoint: \";\n  }\n\n  // tbi\n  void PCLCloud_2_Range(pcl::PointCloud<pcl::PointXYZ>::Ptr pclcloud)\n  {\n  }\n/******************************************************\n * convert  carto's sensor::PointCloud to PCL/PCD cloud\n */\n  void PointCloud_2_PCLCloud(sensor::PointCloud & point_cloud, pcl::PointCloud<pcl::PointXYZ>::Ptr pclcloud)\n  {\n\t  int numpoints = point_cloud.size();\n\t  pclcloud->width=numpoints;\n\t  pclcloud->height=1;\n\t  pclcloud->points.resize (pclcloud->width * pclcloud->height);\n\t  auto points=point_cloud.points();\n\t  for (int i=0;i <numpoints; i++){\n\t\t  pclcloud->points[i].x=points[i].position(0);\n\t\t  pclcloud->points[i].y=points[i].position(1);\n\t\t  pclcloud->points[i].z=points[i].position(2);\n\t  }\n  }\n/******************************************************\n * convert PCD cloud to carto's sensor::PointCloud\n */\n  void PCDCloud_2_PointCloud(pcl::PointCloud<pcl::PointXYZ>::Ptr pclcloud,sensor::PointCloud & point_cloud)\n  {\n    int ptcount=0;\n    Eigen::Vector3f point;\n    std::vector<float> intensities;\n    std::vector<sensor::RangefinderPoint> points;\n    // pc2 points number: 33024\n    for (const pcl::PointXYZ& pointxyz : pclcloud->points)\n    {\n\tptcount++;\n        //LOG(INFO) << \"point: \"<< pointxyz;\n\tpoint(0)=pointxyz.x;\n\tpoint(1)=pointxyz.y;\n\tpoint(2)=pointxyz.z;\n      \tpoints.push_back({point});\n        intensities.push_back(50);\n\t/*\n\thybrid_grid_2_.SetProbability(\n          hybrid_grid_2_.GetCellIndex(expected_pose_.cast<float>() * point), 1.);\n\tintensity_hybrid_grid_2_.AddIntensity(\n          intensity_hybrid_grid_2_.GetCellIndex(expected_pose_.cast<float>() *\n                                              point),\n          50);\n\t  */\n    }\n    std::cout<< \"pcd RangefinderPoint: \";\n    point_cloud = sensor::PointCloud(points, intensities);\n  }\n\n/***********************************************\n * read a pcd file, return cloud\n  pcl::PointCloud<pcl::PointXYZI>::Ptr readPCD_file(std::string pcdfn1)\n  {\n        pcl::PointCloud<pcl::PointXYZI>::Ptr target_cloud (new pcl::PointCloud<pcl::PointXYZI>);\n\tpcl::io::loadPCDFile<pcl::PointXYZI> (pcdfn1, *target_cloud);\n\tLOG(INFO) << *target_cloud;\n\treturn target_cloud;\n  }\n */\n/***********************************************\n * read a pcd file, return cloud\n */\ntemplate <class T> \ntypename  pcl::PointCloud<T>::Ptr readPCD_file(std::string pcdfn1)\n  {\n        typename pcl::PointCloud<T>::Ptr target_cloud (new pcl::PointCloud<T>);\n//\tpcdfn1= \"/home/student/Documents/AirSim/ros/src/hdl_graph_slam/mapdata_13.pcd\";\n\tpcl::io::loadPCDFile<T> (pcdfn1, *target_cloud);\n\tLOG(INFO) << *target_cloud;\n\treturn target_cloud;\n  }\n\n  /*********************************************************\n   * reset scanmatch to use one pair of scan/submap\n   */\n  void scanmatch_reset_single()\n  {\n    myoptstr = std::regex_replace(myoptstr, std::regex(\"occupied_space_weight_1\"), \"occupied_space_weight_0\");\n  //  std::cout<<myoptstr;\n    auto parameter_dictionary = common::MakeDictionary(myoptstr);\n    options_ = CreateCeresScanMatcherOptions3D(parameter_dictionary.get());\n    ceres_scan_matcher_.reset(new CeresScanMatcher3D(options_));\n  }\n\n  /*********************************************************\n   * sweep init pose to test costfun \n   */\nvoid sweeptest(const transform::Rigid3d& initial_pose, sensor::PointCloud &point_cloud, HybridGrid * hybrid_grid)\n{\n    std::ofstream outFile(\"/home/student//Documents/cartographer/test_ceres_pcd/sweep4.txt\");\n    std::ofstream outFile2(\"/home/student//Documents/cartographer/test_ceres_pcd/sweep4.csv\"); //gnuplot csv\n    outFile2 << \"# pose_x, y, z, costfun, ceres_initcost, ceres_finalcost\\n\";\n    std::ostringstream ssout;\n    transform::Rigid3d pose;\n    ceres::Solver::Summary summary;\n    double *residual = new double [point_cloud_5_.size()];\n    double trans[3]= {initial_pose.translation().x(), initial_pose.translation().y(),initial_pose.translation().z()};\n\t\t    \n    double quat[4] ={initial_pose.rotation().w(),initial_pose.rotation().x(),initial_pose.rotation().y(),initial_pose.rotation().z()};\n    //OccupiedSpaceCostFunction3D::scan_matching_verbose=1;\n    OccupiedSpaceCostFunction3D  costfun (1.0, point_cloud, *hybrid_grid);\n    double sweepstep,sweeprange;\n    std::istringstream(mymap[\"sweepstep\"])>>sweepstep;\t    \n    std::istringstream(mymap[\"sweeprange\"])>>sweeprange;\t\n    int sweepcnt = sweeprange/sweepstep;\t\n    for (int j = -sweepcnt; j<sweepcnt; j++){\n\tfor(int k=-sweepcnt; k<sweepcnt; k++){\n\t    trans[0]= sweepstep*j;\n\t    trans[1]= sweepstep*k;\n\t    transform::Rigid3d pose2(Eigen::Matrix<double, 3, 1>(trans[0],trans[1],trans[2]),initial_pose.rotation());\n\t    costfun(trans,quat, residual);\n\t    double sqsum_residual=0;\n\t    for (int i =0; i< point_cloud.size();i++){\n\t\t    sqsum_residual +=residual[i]*residual[i];\n\t    }\n\t    summary = run_lowreso_match(pose2,point_cloud,hybrid_grid, pose);\n\t    ssout.str(\"\");\n\t    ssout<<\"\\n\\t init_xyz: \"<<trans[0]<<\" \"<<trans[1]<<\" \"<<trans[2]<<\" residual \" \n\t\t\t    << sqsum_residual <<\" ceres init/final cost \" << summary.initial_cost<<\" \" << summary.final_cost <<\" final pose \"\n\t\t\t    <<pose.translation().x() <<\" \" << pose.translation().y() <<\" \" <<pose.translation().z()<<\"\";\n\t    outFile << ssout.str();\n\t    outFile2 << trans[0]<<\", \"<<trans[1]<<\", \"<<trans[2]<<\", \" <<sqsum_residual<<\", \" << summary.initial_cost<<\", \" << summary.final_cost<<\"\\n\";\n\t    std::cout<< ssout.str();\n\t}\n    }\n}\n  /*********************************************************\n   * run low resolution scanmatch \n   */\n  ceres::Solver::Summary run_lowreso_match(const transform::Rigid3d& initial_pose, sensor::PointCloud &point_cloud, HybridGrid * hybrid_grid, transform::Rigid3d & pose_o)\n  {\n    transform::Rigid3d pose_1;\n    ceres::Solver::Summary summary_1;\n    std::vector<PointCloudAndHybridGridsPointers> point_clouds_and_hybrid_grids_1;\n    scanmatch_reset_single();\n    point_clouds_and_hybrid_grids_1={{&point_cloud, hybrid_grid, nullptr}};\n    ceres_scan_matcher_->Match(initial_pose.translation(), initial_pose, point_clouds_and_hybrid_grids_1, &pose_1,&summary_1);\n\t    \n    pose_o=pose_1;\n    return summary_1;\n  }\n  /*********************************************************\n * jwang: new scan match test code from here\n * ptselection: 0|1|2\n * 2 for testing two pcd files scan match\n * *********************************************************/\n  void TestFromInitialPose2(const transform::Rigid3d& initial_pose) {\n    transform::Rigid3d pose;\n\n     Eigen::Transform<double, 3, Eigen::Affine > pose_transform;\n     Eigen::Matrix3f mat3 = Eigen::Quaternionf(1, 0,0,0).toRotationMatrix();\n    ceres::Solver::Summary summary;\n    std::vector<PointCloudAndHybridGridsPointers> point_clouds_and_hybrid_grids;\n\n//--------------- select which one to run ceres on: pcd points or debug points\n    int ptselection = std::stoi(mymap[\"ptselection\"]);\n    if (ptselection ==0){\n\t    //use single pcd file\n\tstd::cout <<\"use pcd file points\\n\";\n\tIntensityHybridGrid* intensity_hybrid_grid_ptr =\n        point_cloud_2_.intensities().empty() ? nullptr : &intensity_hybrid_grid_2_;\n\tceres_scan_matcher_->Match(\n        initial_pose.translation(), initial_pose,\n        {{&point_cloud_2_, &hybrid_grid_2_, intensity_hybrid_grid_ptr}}, &pose,\n        &summary);\n    }\n    else if (ptselection ==1){\n\t    // use single ebug txt filea\n\tstd::cout <<\"use debug txt file points\";\n    \n\tIntensityHybridGrid* intensity_hybrid_grid_ptr =\n        \tpoint_cloud_3_.intensities().empty() ? nullptr : &intensity_hybrid_grid_3_;\n\n\tpoint_clouds_and_hybrid_grids={{&point_cloud_3_, &hybrid_grid_3_, intensity_hybrid_grid_ptr}};\n\tstd::cout << \"point_clouds_and_hybrid_grids.size(): \"<<point_clouds_and_hybrid_grids.size() << \"\\npoint_cloud\\n\" << point_clouds_and_hybrid_grids[0].point_cloud <<std::endl;\n\tstd::cout << \"\\nhybrid_grid:\\n \" << point_clouds_and_hybrid_grids[0].hybrid_grid <<std::endl;\n    \n\tOccupiedSpaceCostFunction3D::scan_matching_verbose=1;\n    \n\tceres_scan_matcher_->Match(\n        initial_pose.translation(), initial_pose,\n        {{&point_cloud_3_, &hybrid_grid_3_, intensity_hybrid_grid_ptr}}, &pose,\n        &summary);\n    }else if (ptselection ==2){\n            // use two pcd files: pcdfilename1 pcdfilename2\n\tstd::cout <<\"use two pcd file points\\n\";\n\t    std::string pcdf1, pcdf2, pcdf3, pcdf4;\n\t    transform::Rigid3d initial_pose2;\n\t    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1;\n\t    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2(new pcl::PointCloud<pcl::PointXYZ>);\n\t    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud2_i;\n\t    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud4;\n\t    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud5(new pcl::PointCloud<pcl::PointXYZ>);\n\t    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud5_i;\n\t    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud3(new pcl::PointCloud<pcl::PointXYZ>);\n\t    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud6(new pcl::PointCloud<pcl::PointXYZ>);\n\t    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1_filtered(new pcl::PointCloud<pcl::PointXYZ>);\n\t    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1_edgefiltered(new pcl::PointCloud<pcl::PointXYZ>);\n\t    pcdf1 =  mymap[\"pcdfilename1\"]; //scan pcd high res\n\t    pcdf2 =  mymap[\"pcdfilename2\"]; //submap pcd high res\n\t    pcdf3 =  mymap[\"pcdfilename3\"]; //scan pcd low res\n\t    pcdf4 =  mymap[\"pcdfilename4\"]; //submap pcd low res\n\t    initial_pose2 = makepose(mymap[\"initpose\"]);\n\n\t    int hgridxyzi = std::stoi(mymap[\"hgridxyzi\"]);\n\t    //read scan data, high and low res\n\t    cloud1 = readPCD_file<pcl::PointXYZ>(pcdf1);\n\t    PCDCloud_2_PointCloud(cloud1,point_cloud_4_);\n\t    \t//convert to point_cloud_4_  carto's pointcloud class\n\t    cloud4 = readPCD_file<pcl::PointXYZ>(pcdf3);\n\t    PCDCloud_2_PointCloud(cloud4,point_cloud_5_);\n\n    //\t    std::vector<RangefinderPoint> cloud1_ranges = PCLcloud_2_Range(cloud1);\n\n\t  //  std::vector<PointCloud> \n\t  auto cloud1_filtered_carto =\n\t    sensor::VoxelFilter(\n      point_cloud_4_, 1.5f );\n\t  auto cloud1_edgefiltered_carto =\n\t    sensor::VoxelFilterEdge(\n      point_cloud_4_, 0.5f, 0.6f );\n\t  PointCloud_2_PCLCloud(cloud1_filtered_carto,cloud1_filtered);\n\t  PointCloud_2_PCLCloud(cloud1_edgefiltered_carto,cloud1_edgefiltered);\n\t    show_pcl_2cloud(cloud1,cloud1_filtered, \"high res scan and voxel filtered 0.5\");\n\t    show_pcl_2cloud(cloud1,cloud1_edgefiltered, \"high res scan and voxel edgefiltered 0.5\");\n\t    show_pcl_cloud(cloud1, \"high res scan cloud1\");\n\t    show_pcl_cloud(cloud1_edgefiltered, \"high res scan voxel edgefiltered 0.5\");\n\t    //read hbrid data, xyzi or xyz type, high and low res\n\t    if (hgridxyzi==1){\n\t    \tcloud2_i=readPCD_file<pcl::PointXYZI>(pcdf2);\n\t    \tcloud5_i = readPCD_file<pcl::PointXYZI>(pcdf4);\n\t\tstd::cout<<\"\\n converted cloud2: \" <<cloud2<<\"\\n\";\n\t\tconvert_xyzi_2_xyz(cloud2_i, cloud2);\n\t\tstd::cout<<\" converted cloud2: \" <<cloud2<<\"\\n\";\n\t\tconvert_xyzi_2_xyz(cloud5_i, cloud5);\n\t    }\n\t    else{\n\t    \tcloud2 = readPCD_file<pcl::PointXYZ>(pcdf2);\n\t    \tcloud5 = readPCD_file<pcl::PointXYZ>(pcdf4);\n\t    }\n\n\t    show_pcl_2cloud(cloud1,cloud2, \"high res scan and submap no transform\");\n\t    transform_cloud (cloud1, cloud3, initial_pose2.translation(), initial_pose2.rotation());\n\t    show_pcl_2cloud(cloud3, cloud2, \"high res scan and submap, transform initial_pose2\");\n\t    float hgrid_res_h;\n\t    float hgrid_res_l;\n\t    std::istringstream ss_h(mymap[\"hgrid_res_h\"]);\n\t    std::istringstream ss_l(mymap[\"hgrid_res_l\"]);\n\t    ss_h >> hgrid_res_h; //submap pcd\n\t    ss_l >> hgrid_res_l; //submap pcd\n\t    hybrid_grid_4_ = new HybridGrid(hgrid_res_h);\n\t    hybrid_grid_5_ = new HybridGrid(hgrid_res_l);\n\n\t    //convert pcl cloud to hbrid, there are two version of PCDCloud_2_HybridGrid\n\t    if (hgridxyzi==0){\n\t    \tPCDCloud_2_HybridGrid(cloud2,*hybrid_grid_4_,intensity_hybrid_grid_4_);\t    \n\t    \tPCDCloud_2_HybridGrid(cloud5,*hybrid_grid_5_,intensity_hybrid_grid_5_);\t    \n\t    }else{\n\t\t//hgrid pcd is xyzi format with prob value.\n\t    \tPCDCloud_2_HybridGrid(cloud2_i,*hybrid_grid_4_,intensity_hybrid_grid_4_);\t    \n\t    \tPCDCloud_2_HybridGrid(cloud5_i,*hybrid_grid_5_,intensity_hybrid_grid_5_);\t    \n\t    }\n\t\n\t    IntensityHybridGrid* intensity_hybrid_grid_ptr =\n\t\t    point_cloud_2_.intensities().empty() ? \n\t\t    nullptr : &intensity_hybrid_grid_2_;\n\t    if (mymap[\"usehighres\"] ==\"1\" && mymap[\"uselowres\"] ==\"1\")\n\t    {\n\t\t    std::cout<<\"******************  usehighres and uselowres***\\n\\n\";\n\t\t    if (mymap[\"usehighres\"] ==\"1\" ){\n\t\t\t    std::cout<<\"******************  twostep:  ***\\n\\n\";\n\t\t\t    scanmatch_reset_single();\n\t\t\t    point_clouds_and_hybrid_grids={{&point_cloud_5_, hybrid_grid_5_, nullptr}};\n                    \n\t\t\t    ceres_scan_matcher_->Match(initial_pose2.translation(), initial_pose2, point_clouds_and_hybrid_grids, &pose,&summary);\n\t\t\t    std::cout<<\"******************  twostep: phase 1 low res ***\\n\\tpose: \"<< pose<<\"\\n\";\n\t\t\t    point_clouds_and_hybrid_grids={{&point_cloud_4_, hybrid_grid_4_, intensity_hybrid_grid_ptr}};\n\t\t    \n\t\t\t    ceres_scan_matcher_->Match(pose.translation(), pose, point_clouds_and_hybrid_grids, &pose,&summary);\n\t\t\t    std::cout<<\"******************  twostep: phase 2 high res ***\\n\\tpose: \"<< pose<<\"\\n\";\n\n\t\t    }else{\n\t\t\t    std::cout<<\"******************  twostep:0 high/low in once Match call ***\\n\\n\";\n\t\t\t    point_clouds_and_hybrid_grids={{&point_cloud_4_, hybrid_grid_4_, intensity_hybrid_grid_ptr},{&point_cloud_5_,hybrid_grid_5_,nullptr}};\n\t\t\t    ceres_scan_matcher_->Match(initial_pose2.translation(), initial_pose2, point_clouds_and_hybrid_grids, &pose,&summary);\n\t\t    }\n\t    } \n\t    if (mymap[\"usehighres\"] ==\"1\" && mymap[\"uselowres\"] ==\"0\")\n\t    {\n\t\t    std::cout<<\"******************  usehighres ***\\n\\n\";\n\t\t    scanmatch_reset_single();\n\t\t    point_clouds_and_hybrid_grids={{&point_cloud_4_, hybrid_grid_4_, intensity_hybrid_grid_ptr}};\n\t\t    ceres_scan_matcher_->Match(initial_pose2.translation(), initial_pose2, point_clouds_and_hybrid_grids, &pose,&summary);\n\n\t    }\n\t    if (mymap[\"usehighres\"] ==\"0\" && mymap[\"uselowres\"] ==\"1\")\n\t    {\n\t\t    std::cout<<\"******************  uselowres ***\\n\\n\";\n\t\t    summary = run_lowreso_match(initial_pose2,point_cloud_5_,hybrid_grid_5_, pose);\n\t\t    /*\n\t    LOG(INFO) << \"\\nestimated pose: \"<< pose;\n\t    LOG(INFO) << summary.FullReport();\n\t\t    std::cout<<\"******************  uselowres ***\\n\\n\";\n\t\t    scanmatch_reset_single();\n\t\t    point_clouds_and_hybrid_grids={{&point_cloud_5_, hybrid_grid_5_, nullptr}};\n\t\t    ceres_scan_matcher_->Match(initial_pose2.translation(), initial_pose2, point_clouds_and_hybrid_grids, &pose,&summary);\n\t\t    */\n\t    }\n\t    if (mymap[\"usehighres\"] ==\"0\" && mymap[\"uselowres\"] ==\"0\")\n\t    {\n\t\t    double *residual = new double [point_cloud_5_.size()];\n\t\t    double trans[3]= {initial_pose2.translation().x(), initial_pose2.translation().y(),initial_pose2.translation().z()};\n\t\t    double quat[4] ={initial_pose2.rotation().w(),initial_pose2.rotation().x(),initial_pose2.rotation().y(),initial_pose2.rotation().z()};\n\n\t\t    std::cout<<\"****************** both usehighres and uselowres are false, perform sweep func ***\\n\\ttrans\" << trans[0]<<\" \"<<trans[1]<<\" \"<<trans[2] <<\" quat \"<< quat[0]<<\" \" << quat[1]<<\" \" <<quat[2]<<\" \" <<quat[3] <<\"\\n\";\n\n\t\t    sweeptest(initial_pose2, point_cloud_5_, hybrid_grid_5_);\n\t    }\n\n\t    //ceres_scan_matcher_->Match(initial_pose2.translation(), initial_pose2, point_clouds_and_hybrid_grids, &pose,&summary);\n    \n\t    LOG(INFO) << \"\\nestimated pose: \"<< pose;\n\t    LOG(INFO) << summary.FullReport();\n    \n\t    //transform cloud1 (scan) to cloud3 using estimated pose\n\t    transform_cloud (cloud1, cloud3, pose.translation(), pose.rotation());\n\t    transform_cloud (cloud4, cloud6, pose.translation(), pose.rotation());\n\t    // show high res submap and transformed scan\n\t    show_pcl_2cloud(cloud3,cloud2, \"high res scan/submap aligned\");\n\t    // show low res submap and transformed scan\n\t    show_pcl_2cloud(cloud6,cloud5, \"low res scan/submap aligned\");\n\t    return;\n    }//end if ptselection\n\n\n    OccupiedSpaceCostFunction3D::scan_matching_verbose=0;\n    LOG(INFO) << \"estimated pose: \"<< pose;\n    LOG(INFO) << summary.FullReport();\n    //EXPECT_NEAR(0., summary.final_cost, 1e-2) << summary.FullReport();\n    //EXPECT_THAT(pose, transform::IsNearly(expected_pose_, 3e-2));\n  }\n\n  void transform_cloud(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_out, Eigen::Matrix<double, 3, 1> trans, Eigen::Quaternion<double> quat0)\n  {\n        Eigen::Quaterniond quat(1, 0,0,0);\n\n        Eigen::Matrix3d mat3 = Eigen::Quaterniond(1, 0,0,0).toRotationMatrix();\n        Eigen::Matrix3d mat4 = quat0.toRotationMatrix();\n    \n\tEigen::Vector3d v3d(-3., 0., 0.);\n    \n\tEigen::Transform<double, 3, Eigen::Affine > pose_trans;\n//\tpose_trans.translation()=v3d;\n\tpose_trans.translation()=trans;\n\tpose_trans.linear()=mat4;\n\tstd::cout<<\"transform_cloud quat0 wxyz: \"<< quat0.w()<<\" \"<< quat0.x()<<\" \"<< quat0.y()<<\" \"<<quat0.z() <<\"\\n\";\n\tstd::cout<<\"Eigen::Transform: \"<< pose_trans.translation() <<\"\\n\";\n\tstd::cout<<\"Eigen::Transform: rotation\"<< pose_trans.rotation() <<\"\\n\";\n\tpcl::transformPointCloud (*cloud_in, *cloud_out, pose_trans);\n  }\n\n/********************************************************************/\n  /* read from txt file debugging cloud point */\n  void add_dbg_pts(int dbgpt, std::vector<sensor::RangefinderPoint> &points, std::vector<float> &intensities)\n  {\n\n    //std::vector<sensor::RangefinderPoint> points;\n    //std::vector<float> intensities;\n    Eigen::Vector3f point;\n    std::string dbgfilename = mymap[\"dbgfilename\"];\n    std::ifstream stream2(dbgfilename.c_str());\n    std::string mypt_str= std::string((std::istreambuf_iterator<char>(stream2)),\n                     std::istreambuf_iterator<char>());\n    char *token;\n    //std::cout<< \"strings from dbg point file:\\n\" << mypt_str <<\"\\n\";\n    token = strtok(const_cast<char*>(mypt_str.c_str()), \"\\n\");\n    while (token != NULL) {\n\t    std::string svalue(token);\n\t    size_t pos = svalue.find(\",\");\n            std::string svalue2 = svalue.substr(pos + 1, std::string::npos);\n\t    size_t pos2 = svalue2.find(\",\");\n            std::string svalue3 = svalue2.substr(pos2 + 1, std::string::npos);\n\t    //std::cout<<\"dbg \" << pos<<\" \"<<pos2 <<\" \"<<svalue.substr(0, pos)<<\" \" <<svalue2.substr(0, pos2) << \" \" << svalue3 << \"\\n\";\n\t    point(0) = std::stof(svalue.substr(0, pos));\n\t    point(1) = std::stof(svalue2.substr(0, pos2));\n\t    point(2) = std::stof(svalue3);\n\n\t    points.push_back({point});\n\t    intensities.push_back(50);\n\t    token = strtok(NULL, \"\\n\");\n// std::cout<<NULL will cause exception and terminate the func call, but the rest of the parent func still run.\n\t    if (token == NULL) std::cout<< \"token is NULL\" << (token ==NULL)<<\"\\n\";\n\t    else std::cout<< \"line \" << token <<\" ----\\n\";\n    }\n  }\n\n/********************************************************************/\n  // setup test points from either pcd cloud or debug file\n  void initpc2(pcl::PointCloud<pcl::PointXYZ>::Ptr pclcloud) {\n    std::vector<sensor::RangefinderPoint> points;\n    std::vector<sensor::RangefinderPoint> points_dbg;\n    std::vector<float> intensities;\n    std::vector<float> intensities_dbg;\n    int maxpt = std::stoi(mymap[\"ptcount\"]);\n    maxpt = std::min(maxpt, int(pclcloud->width * pclcloud->height));\n    int dbgpt = std::stoi(mymap[\"dbgpt\"]);\n\n    //----------------------read the dbg points from file\n    add_dbg_pts(dbgpt, points_dbg, intensities_dbg);\n    std::cout<< \"dbg RangefinderPoint:\\n\";\n    for(int i=0;i<dbgpt;i++){\n    \tstd::cout<<  points_dbg[i].position(0) << \", \" <<points_dbg[i].position(1) <<\", \"<<points_dbg[i].position(2) <<std::endl;\n      hybrid_grid_3_.SetProbability(\n          hybrid_grid_3_.GetCellIndex(expected_pose_.cast<float>() * points_dbg[i].position), 1.);\n      intensity_hybrid_grid_3_.AddIntensity(\n          intensity_hybrid_grid_3_.GetCellIndex(expected_pose_.cast<float>() *\n                                              points_dbg[i].position),\n          50);\n    }\n    point_cloud_3_ = sensor::PointCloud(points_dbg, intensities_dbg);\n\n    //--------------------- pcd file data -----------------\n\n    int ptcount=0;\n    // pc2 points number: 33024\n    for (const pcl::PointXYZ& pointxyz : pclcloud->points)\n    {\n\t    ptcount++;\n\t    if (ptcount > maxpt) break;\n\tEigen::Vector3f point;\n        //LOG(INFO) << \"point: \"<< pointxyz;\n\tpoint(0)=pointxyz.x;\n\tpoint(1)=pointxyz.y;\n\tpoint(2)=pointxyz.z;\n      \tpoints.push_back({point});\n        intensities.push_back(50);\n\n      hybrid_grid_2_.SetProbability(\n          hybrid_grid_2_.GetCellIndex(expected_pose_.cast<float>() * point), 1.);\n      intensity_hybrid_grid_2_.AddIntensity(\n          intensity_hybrid_grid_2_.GetCellIndex(expected_pose_.cast<float>() *\n                                              point),\n          50);\n    }\n    std::cout<< \"pcd RangefinderPoint: \";\n    for(int i=0;i<10;i++){\n    \tstd::cout<<  points[i].position(0) << \", \" <<points[i].position(1) <<\", \"<<points[i].position(2) <<std::endl;\n    }\n    point_cloud_2_ = sensor::PointCloud(points, intensities);\n  }\n\n  void init_pcl_viewer(std::string title)\n  {\n\t  // Initializing point cloud visualizer\n // pcl::visualization::PCLVisualizer::Ptr\n  viewer_final.reset( new pcl::visualization::PCLVisualizer (title));\n  viewer_final->setBackgroundColor (0, 0, 0);\n  // Coloring and visualizing target cloud (red).\n//  viewer_final->addPointCloud<pcl::PointXYZ> (target_cloud, target_color, \"target cloud\");\n  // Starting visualizer\n  viewer_final->addCoordinateSystem (1.0, \"global\");\n  viewer_final->initCameraParameters ();\n  viewer_final->setCameraPosition(0, 0, -4, 10, 5, 10, 10, 0, 10);\n\n  }\n\n  void wait_pcl()\n  {\n  // Wait until visualizer window is closed.\n\tstd::chrono::milliseconds dura( 100 );\n\twhile (!viewer_final->wasStopped ())\n\t{\n\t     \tviewer_final->spinOnce (100);\n\t\tstd::this_thread::sleep_for(dura);\n\t}\n  }\n\n  void show_pcl_cloud(pcl::PointCloud<pcl::PointXYZ>::Ptr target_cloud, std::string title)\n  {\n\tinit_pcl_viewer(title); //need to init pcl every time it was closed.\n  \tpcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>\n\t\ttarget_color (target_cloud, 255, 0, 0);\n  \n\tviewer_final->addPointCloud<pcl::PointXYZ> (target_cloud, target_color, \"target cloud\");\n\n\twait_pcl();\n\t/*\n  // Wait until visualizer window is closed.\n\tstd::chrono::milliseconds dura( 100 );\n\twhile (!viewer_final->wasStopped ())\n\t{\n\t     \tviewer_final->spinOnce (100);\n\t\tstd::this_thread::sleep_for(dura);\n\t}\n\t*/\n  }\n\n  void show_pcl_2cloud(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2, std::string title)\n  {\n\t  init_pcl_viewer(title); //need to init pcl every time it was closed.\n\t  \n\t  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>\n  \t\tcolor1 (cloud1, 255, 0, 0);\n    \n\t  viewer_final->addPointCloud<pcl::PointXYZ> (cloud1, color1, \"target cloud\");\n\t  viewer_final->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE,\n                                                  1, \"target cloud\");\n\t  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>\n  \t\tcolor2 (cloud2, 0, 255, 0);\n\t  viewer_final->addPointCloud<pcl::PointXYZ> (cloud2, color2, \"output cloud\");\n\t  viewer_final->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE,\n                                                  1, \"output cloud\");\n\t  wait_pcl();\n\n  }\n  \n/********************************************************************/\n  HybridGrid hybrid_grid_;\n  IntensityHybridGrid intensity_hybrid_grid_;\n  transform::Rigid3d expected_pose_;\n  sensor::PointCloud point_cloud_;\n  proto::CeresScanMatcherOptions3D options_;\n  std::unique_ptr<CeresScanMatcher3D> ceres_scan_matcher_;\n\n  pcl::visualization::PCLVisualizer::Ptr viewer_final;\n\n  HybridGrid hybrid_grid_2_ = HybridGrid(1.f);\n  IntensityHybridGrid intensity_hybrid_grid_2_ = IntensityHybridGrid(1.f);\n  HybridGrid hybrid_grid_3_ = HybridGrid(1.f);\n  IntensityHybridGrid intensity_hybrid_grid_3_ = IntensityHybridGrid(1.f);\n  sensor::PointCloud point_cloud_2_;\n  sensor::PointCloud point_cloud_3_;\n  sensor::PointCloud point_cloud_4_; // for scan pcd high res\n  HybridGrid * hybrid_grid_4_; // = HybridGrid(0.4f); // for submap pcd high res\n  HybridGrid * hybrid_grid_5_; // = HybridGrid(0.4f); // for submap pcd low res\n  IntensityHybridGrid intensity_hybrid_grid_4_ = IntensityHybridGrid(1.f);\n  IntensityHybridGrid intensity_hybrid_grid_5_ = IntensityHybridGrid(1.f);\n  sensor::PointCloud point_cloud_5_; // for scan pcd low res\n\n    std::map<std::string, std::string> mymap;\n    std::string myoptstr;\n};\n\n/********************************************************************/\n/********************************************************************/\nTEST_F(CeresScanMatcher3DTest, PerfectEstimate) {\n\tLOG(INFO) << \"test ceres scan matching with pcd files :\";\n\t        // Loading first scan, as reference or target cloud\n        pcl::PointCloud<pcl::PointXYZ>::Ptr target_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n        std::string pcdfn1;\n\tpcdfn1 = mymap[\"pcdfilename\"];\n//\tpcdfn1= \"/home/student/Documents/AirSim/ros/src/hdl_graph_slam/mapdata_13.pcd\";\n\tpcl::io::loadPCDFile<pcl::PointXYZ> (pcdfn1, *target_cloud);\n\tLOG(INFO) << *target_cloud;\n\tinitpc2(target_cloud);\n\n\t//init_pcl_viewer();\n\tshow_pcl_cloud(target_cloud, pcdfn1);\n  \n\tLOG(INFO) << \"new test case: \";\n  \n\tTestFromInitialPose2(\n\t\ttransform::Rigid3d::Translation(Eigen::Vector3d(-1.5, 0., 0.)));\n  \n\tLOG(INFO) << \"orig test case: \";\n  \n\tTestFromInitialPose(\n      \t\ttransform::Rigid3d::Translation(Eigen::Vector3d(-1., 0., 0.)));\n}\n\nTEST_F(CeresScanMatcher3DTest, AlongX) {\n  ceres_scan_matcher_.reset(new CeresScanMatcher3D(options_));\n  TestFromInitialPose(\n      transform::Rigid3d::Translation(Eigen::Vector3d(-2.8, 0., 0.)));\n}\n\nTEST_F(CeresScanMatcher3DTest, AlongZ) {\n  TestFromInitialPose(\n      transform::Rigid3d::Translation(Eigen::Vector3d(-1., 0., -0.2)));\n}\n\nTEST_F(CeresScanMatcher3DTest, AlongXYZ) {\n  TestFromInitialPose(\n      transform::Rigid3d::Translation(Eigen::Vector3d(-0.9, -0.2, 0.2)));\n}\n\nTEST_F(CeresScanMatcher3DTest, FullPoseCorrection) {\n  // We try to find the rotation around z...\n  const auto additional_transform = transform::Rigid3d::Rotation(\n      Eigen::AngleAxisd(0.05, Eigen::Vector3d(0., 0., 1.)));\n  point_cloud_ = sensor::TransformPointCloud(\n      point_cloud_, additional_transform.cast<float>());\n  expected_pose_ = expected_pose_ * additional_transform.inverse();\n  // ...starting initially with rotation around x.\n  TestFromInitialPose(\n      transform::Rigid3d(Eigen::Vector3d(-0.95, -0.05, 0.05),\n                         Eigen::AngleAxisd(0.05, Eigen::Vector3d(1., 0., 0.))));\n}\n\n}  // namespace\n}  // namespace scan_matching\n}  // namespace mapping\n}  // namespace cartographer\n", "meta": {"hexsha": "6242df5cccbc632e28fe57ca1bc67dd62621a519", "size": 35678, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cartographer/mapping/internal/3d/scan_matching/ceres_scan_matcher_3d_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": "cartographer/mapping/internal/3d/scan_matching/ceres_scan_matcher_3d_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": "cartographer/mapping/internal/3d/scan_matching/ceres_scan_matcher_3d_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": 41.8264947245, "max_line_length": 227, "alphanum_fraction": 0.6492516397, "num_tokens": 9771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.1843495725374357}}
{"text": "// -*- C++ -*-\n//\n// Package:     MVAComputer\n// Class  :     ProcSort\n//\n\n// Implementation:\n//     Sorts the input variables. Each input variable must appear in the\n//     multiplicity as the others. One variable is the sorting \"leader\" by\n//     which all variables are reordered the same way. The ordering is\n//     determined by either ascending or descending order of the leader.\n//\n// Author:      Christophe Saout\n// Created:     Sun Sep 16 14:52 CEST 2007\n//\n\n#include <cstdlib>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n\n#include <boost/iterator/transform_iterator.hpp>\n\n#include \"PhysicsTools/MVAComputer/interface/VarProcessor.h\"\n#include \"PhysicsTools/MVAComputer/interface/Calibration.h\"\n\nusing namespace PhysicsTools;\n\nnamespace {  // anonymous\n\n  class ProcSort : public VarProcessor {\n  public:\n    typedef VarProcessor::Registry::Registry<ProcSort, Calibration::ProcSort> Registry;\n\n    ProcSort(const char *name, const Calibration::ProcSort *calib, const MVAComputer *computer);\n    ~ProcSort() override {}\n\n    void configure(ConfIterator iter, unsigned int n) override;\n    void eval(ValueIterator iter, unsigned int n) const override;\n    std::vector<double> deriv(ValueIterator iter, unsigned int n) const override;\n\n  private:\n    unsigned int leader;\n    bool descending;\n  };\n\n  ProcSort::Registry registry(\"ProcSort\");\n\n  ProcSort::ProcSort(const char *name, const Calibration::ProcSort *calib, const MVAComputer *computer)\n      : VarProcessor(name, calib, computer), leader(calib->sortByIndex), descending(calib->descending) {}\n\n  void ProcSort::configure(ConfIterator iter, unsigned int n) {\n    if (leader >= n)\n      return;\n\n    iter << iter;\n    while (iter)\n      iter << iter++(Variable::FLAG_ALL);\n  }\n\n  namespace {  // anonymous\n    struct LeaderLookup {\n      inline LeaderLookup() {}\n      inline LeaderLookup(const double *values) : values(values) {}\n\n      inline double operator()(int index) const { return values[index]; }\n\n      const double *values;\n    };\n  }  // anonymous namespace\n\n  void ProcSort::eval(ValueIterator iter, unsigned int n) const {\n    ValueIterator leaderIter = iter;\n    for (unsigned int i = 0; i < leader; i++, leaderIter++)\n      ;\n    unsigned int size = leaderIter.size();\n    LeaderLookup lookup(leaderIter.begin());\n\n    int *sort = (int *)alloca(size * sizeof(int));\n    for (unsigned int i = 0; i < size; i++)\n      sort[i] = (int)i;\n\n    boost::transform_iterator<LeaderLookup, int *> begin(sort, lookup);\n    boost::transform_iterator<LeaderLookup, int *> end = begin;\n\n    for (unsigned int i = 0; i < size; i++, end++) {\n      unsigned int pos = std::lower_bound(begin, end, leaderIter[i]) - begin;\n      std::memmove(sort + (pos + 1), sort + pos, (i - pos) * sizeof(*sort));\n      sort[pos] = i;\n    }\n\n    if (descending)\n      std::reverse(sort, sort + size);\n\n    for (unsigned int i = 0; i < size; i++)\n      iter << (double)sort[i];\n    iter();\n\n    while (iter) {\n      for (unsigned int i = 0; i < size; i++)\n        iter << iter[sort[i]];\n      iter();\n      iter++;\n    }\n  }\n\n  std::vector<double> ProcSort::deriv(ValueIterator iter, unsigned int n) const {\n    unsigned int in = 0;\n    for (ValueIterator iter2 = iter; iter2; ++iter2)\n      in += iter2.size();\n\n    ValueIterator leaderIter = iter;\n    for (unsigned int i = 0; i < leader; i++, leaderIter++)\n      ;\n    unsigned int size = leaderIter.size();\n    LeaderLookup lookup(leaderIter.begin());\n\n    std::vector<int> sort;\n    for (unsigned int i = 0; i < size; i++)\n      sort.push_back((int)i);\n\n    boost::transform_iterator<LeaderLookup, std::vector<int>::const_iterator> begin(sort.begin(), lookup);\n    boost::transform_iterator<LeaderLookup, std::vector<int>::const_iterator> end = begin;\n\n    for (unsigned int i = 0; i < size; i++, end++) {\n      unsigned int pos = std::lower_bound(begin, end, leaderIter[i]) - begin;\n      std::memmove(&sort.front() + (pos + 1), &sort.front() + pos, (i - pos) * sizeof(sort.front()));\n      sort[pos] = i;\n    }\n\n    if (descending)\n      std::reverse(sort.begin(), sort.end());\n\n    std::vector<double> result(size * in, 0.0);\n\n    for (unsigned int pos = 0; iter; pos += (iter++).size()) {\n      for (unsigned int i = 0; i < size; i++) {\n        unsigned int row = result.size();\n        result.resize(row + in);\n        result[row + pos + sort[i]] = 1.0;\n      }\n    }\n\n    return result;\n  }\n\n}  // anonymous namespace\n", "meta": {"hexsha": "28e5c5069f26f578bfe4489f2e34a929a10cca7b", "size": 4439, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PhysicsTools/MVAComputer/src/ProcSort.cc", "max_stars_repo_name": "ckamtsikis/cmssw", "max_stars_repo_head_hexsha": "ea19fe642bb7537cbf58451dcf73aa5fd1b66250", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 852.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T21:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T21:14:00.000Z", "max_issues_repo_path": "PhysicsTools/MVAComputer/src/ProcSort.cc", "max_issues_repo_name": "ckamtsikis/cmssw", "max_issues_repo_head_hexsha": "ea19fe642bb7537cbf58451dcf73aa5fd1b66250", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30371.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T00:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:26:05.000Z", "max_forks_repo_path": "PhysicsTools/MVAComputer/src/ProcSort.cc", "max_forks_repo_name": "ckamtsikis/cmssw", "max_forks_repo_head_hexsha": "ea19fe642bb7537cbf58451dcf73aa5fd1b66250", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3240.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T05:53:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:24:21.000Z", "avg_line_length": 29.9932432432, "max_line_length": 106, "alphanum_fraction": 0.634377112, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18434957253743567}}
{"text": "#include \"mj_sim_impl.h\"\n#include \"mj_utils.h\"\n\n#include <cassert>\n#include <chrono>\n#include <type_traits>\n\n#include \"MujocoClient.h\"\n#include \"config.h\"\n\n#include \"backends/imgui_impl_glfw.h\"\n#include \"backends/imgui_impl_opengl3.h\"\n\n#include \"implot.h\"\n\n#include \"ImGuizmo.h\"\n\n#include \"MujocoClient.h\"\n\n#include <boost/filesystem.hpp>\nnamespace bfs = boost::filesystem;\n\n#include <mc_rtc/version.h>\n\nnamespace mc_mujoco\n{\n\ndouble MjRobot::PD(double jnt_id, double q_ref, double q, double qdot_ref, double qdot)\n{\n  double p_error = q_ref - q;\n  double v_error = qdot_ref - qdot;\n  double ret = (kp[jnt_id] * p_error + kd[jnt_id] * v_error);\n  return ret;\n}\n\n/* Load PD gains from file (taken from RobotHardware/robot.cpp) */\nbool MjRobot::loadGain(const std::string & path_to_pd, const std::vector<std::string> & joints)\n{\n  std::ifstream strm(path_to_pd.c_str());\n  if(!strm.is_open())\n  {\n    mc_rtc::log::error_and_throw<std::runtime_error>(\"[mc_mujoco] Cannot open PD gains file for {} at {}\", name,\n                                                     path_to_pd);\n  }\n\n  int num_joints = joints.size();\n  if(!num_joints)\n  {\n    return false;\n  }\n  std::vector<double> default_pgain(num_joints, 0);\n  std::vector<double> default_dgain(num_joints, 0);\n  for(int i = 0; i < num_joints; i++)\n  {\n    std::string str;\n    bool getlinep;\n    while((getlinep = !!(std::getline(strm, str))))\n    {\n      if(str.empty())\n      {\n        continue;\n      }\n      if(str[0] == '#')\n      {\n        continue;\n      }\n      double tmp;\n      std::istringstream sstrm(str);\n      sstrm >> tmp;\n      default_pgain[i] = tmp;\n      if(sstrm.eof()) break;\n\n      sstrm >> tmp;\n      default_dgain[i] = tmp;\n      if(sstrm.eof()) break;\n      break;\n    }\n    if(!getlinep)\n    {\n      if(i < num_joints)\n      {\n        mc_rtc::log::error(\n            \"[mc_mujoco] loadGain error: size of gains reading from file ({}) does not match size of joints\",\n            path_to_pd);\n      }\n      break;\n    }\n  }\n\n  strm.close();\n  mc_rtc::log::info(\"[mc_mujoco] Gains for {}\", name);\n  for(unsigned int i = 0; i < num_joints; i++)\n  {\n    mc_rtc::log::info(\"[mc_mujoco] {}, pgain = {}, dgain = {}\", joints[i], default_pgain[i], default_dgain[i]);\n    // push to kp and kd\n    default_kp.push_back(default_pgain[i]);\n    default_kd.push_back(default_dgain[i]);\n    kp.push_back(default_pgain[i]);\n    kd.push_back(default_dgain[i]);\n  }\n  return true;\n}\n\nMjSimImpl::MjSimImpl(const MjConfiguration & config)\n: controller(std::make_unique<mc_control::MCGlobalController>(config.mc_config)), config(config)\n{\n  auto get_robot_cfg_path = [&](const std::string & robot_name) -> std::string {\n    if(bfs::exists(bfs::path(mc_mujoco::USER_FOLDER) / (robot_name + \".yaml\")))\n    {\n      return (bfs::path(mc_mujoco::USER_FOLDER) / (robot_name + \".yaml\")).string();\n    }\n    else if(bfs::exists(bfs::path(mc_mujoco::SHARE_FOLDER) / (robot_name + \".yaml\")))\n    {\n      return (bfs::path(mc_mujoco::SHARE_FOLDER) / (robot_name + \".yaml\")).string();\n    }\n    else\n    {\n      return \"\";\n    }\n  };\n\n  std::vector<std::string> mujRobots;\n  std::vector<std::string> xmlFiles;\n  std::vector<std::string> pdGainsFiles;\n#if MC_RTC_VERSION_MAJOR > 1\n  for(const auto & r_ptr : controller->robots())\n  {\n    const auto & r = *r_ptr;\n#else\n  for(const auto & r : controller->robots())\n  {\n#endif\n    const auto & robot_cfg_path = get_robot_cfg_path(r.module().name);\n    if(robot_cfg_path.size())\n    {\n      auto robot_cfg = mc_rtc::Configuration(robot_cfg_path);\n      if(!robot_cfg.has(\"xmlModelPath\"))\n      {\n        mc_rtc::log::error_and_throw<std::runtime_error>(\"Missing xmlModelPath in {}\", robot_cfg_path);\n      }\n      mujRobots.push_back(r.name());\n      xmlFiles.push_back(static_cast<std::string>(robot_cfg(\"xmlModelPath\")));\n      pdGainsFiles.push_back(robot_cfg(\"pdGainsPath\", std::string(\"\")));\n      if(!bfs::exists(xmlFiles.back()))\n      {\n        mc_rtc::log::error_and_throw<std::runtime_error>(\"[mc_mujoco] XML model cannot be found at {}\",\n                                                         xmlFiles.back());\n      }\n    }\n  }\n\n  if(!xmlFiles.size())\n  {\n    mc_rtc::log::error_and_throw<std::runtime_error>(\"No Mujoco model associated to any robots in the controller\");\n  }\n\n  // initial mujoco here and load XML model\n  bool initialized = mujoco_init(this, mujRobots, xmlFiles);\n  if(!initialized)\n  {\n    mc_rtc::log::error_and_throw<std::runtime_error>(\"[mc_mujoco] Initialized failed.\");\n  }\n\n  // read PD gains from file\n  for(size_t i = 0; i < robots.size(); ++i)\n  {\n    auto & r = robots[i];\n    bool has_motor =\n        std::any_of(r.mj_mot_names.begin(), r.mj_mot_names.end(), [](const std::string & m) { return m.size() != 0; });\n    const auto & robot = controller->robot(r.name);\n    if(robot.mb().nrDof() == 0 || (robot.mb().nrDof() == 6 && robot.mb().joint(0).dof() == 6) || !has_motor)\n    {\n      continue;\n    }\n    if(!bfs::exists(pdGainsFiles[i]))\n    {\n      mc_rtc::log::error_and_throw<std::runtime_error>(\"[mc_mujoco] PD gains file for {} cannot be found at {}\", r.name,\n                                                       pdGainsFiles.back());\n    }\n    r.loadGain(pdGainsFiles[i], controller->robots().robot(r.name).module().ref_joint_order());\n  }\n\n  if(config.with_visualization)\n  {\n    mujoco_create_window(this);\n    if(config.with_mc_rtc_gui)\n    {\n      client = std::make_unique<MujocoClient>();\n    }\n  }\n  mc_rtc::log::info(\"[mc_mujoco] Initialized successful.\");\n}\n\nvoid MjSimImpl::cleanup()\n{\n  mujoco_cleanup(this);\n}\n\nvoid MjRobot::initialize(mjModel * model, const mc_rbdyn::Robot & robot)\n{\n  mj_jnt_ids.resize(0);\n  for(const auto & j : mj_jnt_names)\n  {\n    mj_jnt_ids.push_back(mj_name2id(model, mjOBJ_JOINT, j.c_str()));\n  }\n  auto fill_acuator_ids = [&](const std::vector<std::string> & names, std::vector<int> & ids) {\n    ids.resize(0);\n    for(const auto & n : names)\n    {\n      if(n.size())\n      {\n        ids.push_back(mj_name2id(model, mjOBJ_ACTUATOR, n.c_str()));\n      }\n      else\n      {\n        ids.push_back(-1);\n      }\n    }\n  };\n  fill_acuator_ids(mj_mot_names, mj_mot_ids);\n  fill_acuator_ids(mj_pos_act_names, mj_pos_act_ids);\n  fill_acuator_ids(mj_vel_act_names, mj_vel_act_ids);\n  if(root_body.size())\n  {\n    root_body_id = mj_name2id(model, mjOBJ_BODY, root_body.c_str());\n  }\n  auto init_sensor_id = [&](const char * mj_name, const char * mc_name, const std::string & sensor_name,\n                            const char * suffix, mjtSensor type, std::unordered_map<std::string, int> & mapping) {\n    auto mj_sensor = prefixed(fmt::format(\"{}_{}\", sensor_name, suffix));\n    auto sensor_id = mujoco_get_sensor_id(*model, mj_sensor, type);\n    if(sensor_id == -1)\n    {\n      mc_rtc::log::error(\"[mc_mujoco] No MuJoCo {} for {} {} in {}, expected to find a {} named {}\", mj_name,\n                         sensor_name, mc_name, name, mj_name, mj_sensor);\n    }\n    mapping[sensor_name] = sensor_id;\n  };\n  for(const auto & fs : robot.module().forceSensors())\n  {\n    wrenches[fs.name()] = sva::ForceVecd(Eigen::Vector3d(0, 0, 0), Eigen::Vector3d(0, 0, 0));\n    init_sensor_id(\"force sensor\", \"force sensor\", fs.name(), \"fsensor\", mjSENS_FORCE, mc_fs_to_mj_fsensor_id);\n    init_sensor_id(\"torque sensor\", \"force sensor\", fs.name(), \"tsensor\", mjSENS_TORQUE, mc_fs_to_mj_tsensor_id);\n  }\n  for(const auto & bs : robot.bodySensors())\n  {\n    if(bs.name() == \"FloatingBase\" || bs.name().empty())\n    {\n      continue;\n    }\n    gyros[bs.name()] = Eigen::Vector3d::Zero();\n    accelerometers[bs.name()] = Eigen::Vector3d::Zero();\n    init_sensor_id(\"gyro sensor\", \"body sensor\", bs.name(), \"gyro\", mjSENS_GYRO, mc_bs_to_mj_gyro_id);\n    init_sensor_id(\"accelerometer sensor\", \"body sensor\", bs.name(), \"accelerometer\", mjSENS_ACCELEROMETER,\n                   mc_bs_to_mj_accelerometer_id);\n  }\n  reset(robot);\n}\n\nvoid MjRobot::reset(const mc_rbdyn::Robot & robot)\n{\n  const auto & mbc = robot.mbc();\n  const auto & rjo = robot.module().ref_joint_order();\n  if(rjo.size() != mj_jnt_names.size())\n  {\n    mc_rtc::log::error_and_throw<std::runtime_error>(\n        \"[mc_mujoco] Missmatch in model for {}, reference joint order has {} joints but MuJoCo models has {} joints\",\n        name, rjo.size(), mj_jnt_names.size());\n  }\n  mj_to_mbc.resize(0);\n  mj_prev_ctrl_q.resize(0);\n  mj_prev_ctrl_alpha.resize(0);\n  mj_jnt_to_rjo.resize(0);\n  mj_to_mbc.resize(0);\n  encoders = std::vector<double>(rjo.size(), 0.0);\n  alphas = std::vector<double>(rjo.size(), 0.0);\n  torques = std::vector<double>(rjo.size(), 0.0);\n  for(const auto & mj_jn : mj_jnt_names)\n  {\n    const auto & jn = [&]() {\n      if(prefix.size())\n      {\n        return mj_jn.substr(prefix.size() + 1);\n      }\n      return mj_jn;\n    }();\n    auto rjo_it = std::find(rjo.begin(), rjo.end(), jn);\n    int rjo_idx = -1;\n    if(rjo_it != rjo.end())\n    {\n      rjo_idx = std::distance(rjo.begin(), rjo_it);\n    }\n    mj_jnt_to_rjo.push_back(rjo_idx);\n    if(robot.hasJoint(jn))\n    {\n      auto jIndex = robot.jointIndexByName(jn);\n      mj_to_mbc.push_back(jIndex);\n      if(robot.mb().joint(jIndex).dof() != 1)\n      {\n        mc_rtc::log::error_and_throw<std::runtime_error>(\n            \"[mc_mujoco] Only support revolute and prismatic joint for control\");\n      }\n      mj_prev_ctrl_q.push_back(robot.mbc().q[jIndex][0]);\n      mj_prev_ctrl_alpha.push_back(robot.mbc().alpha[jIndex][0]);\n      if(rjo_idx != -1)\n      {\n        encoders[rjo_idx] = mj_prev_ctrl_q.back();\n        alphas[rjo_idx] = mj_prev_ctrl_alpha.back();\n      }\n    }\n    else\n    {\n      mj_to_mbc.push_back(-1);\n    }\n  }\n  mj_ctrl = mj_prev_ctrl_q;\n  mj_next_ctrl_q = mj_prev_ctrl_q;\n  mj_next_ctrl_alpha = mj_prev_ctrl_alpha;\n\n  // reset the PD gains to default values\n  kp = default_kp;\n  kd = default_kd;\n}\n\nvoid MjSimImpl::setSimulationInitialState()\n{\n  if(controller)\n  {\n    qInit.resize(0);\n    alphaInit.resize(0);\n    for(auto & r : robots)\n    {\n      const auto & robot = controller->robots().robot(r.name);\n      r.initialize(model, robot);\n      if(r.root_joint.size())\n      {\n        r.root_qpos_idx = qInit.size();\n        r.root_qvel_idx = alphaInit.size();\n        if(robot.mb().joint(0).dof() == 6)\n        {\n          const auto & t = robot.posW().translation();\n          for(size_t i = 0; i < 3; ++i)\n          {\n            qInit.push_back(t[i]);\n            // push linear/angular velocities\n            alphaInit.push_back(0);\n            alphaInit.push_back(0);\n          }\n          Eigen::Quaterniond q = Eigen::Quaterniond(robot.posW().rotation()).inverse();\n          qInit.push_back(q.w());\n          qInit.push_back(q.x());\n          qInit.push_back(q.y());\n          qInit.push_back(q.z());\n        }\n      }\n      else if(r.root_body_id != -1)\n      {\n        const auto & t = robot.posW().translation();\n        model->body_pos[3 * r.root_body_id + 0] = t.x();\n        model->body_pos[3 * r.root_body_id + 1] = t.y();\n        model->body_pos[3 * r.root_body_id + 2] = t.z();\n        Eigen::Quaterniond q = Eigen::Quaterniond(robot.posW().rotation()).inverse();\n        model->body_quat[4 * r.root_body_id + 0] = q.w();\n        model->body_quat[4 * r.root_body_id + 1] = q.x();\n        model->body_quat[4 * r.root_body_id + 2] = q.y();\n        model->body_quat[4 * r.root_body_id + 3] = q.z();\n      }\n      for(size_t i = 0; i < r.mj_jnt_names.size(); ++i)\n      {\n        qInit.push_back(r.encoders[r.mj_jnt_to_rjo[i]]);\n        alphaInit.push_back(r.alphas[r.mj_jnt_to_rjo[i]]);\n      }\n    }\n  }\n  // set initial qpos, qvel in mujoco\n  if(!mujoco_set_const(model, data, qInit, alphaInit))\n  {\n    mc_rtc::log::error_and_throw<std::runtime_error>(\"[mc_mujoco] Set inital state failed.\");\n  }\n  mj_forward(model, data);\n}\n\nvoid MjSimImpl::makeDatastoreCalls()\n{\n  for(auto & r : robots)\n  {\n    // make_call for setting pd gains (for all joints)\n    controller->controller().datastore().make_call(\n        r.name + \"::SetPDGains\", [this, &r](const std::vector<double> & p_vec, const std::vector<double> & d_vec) {\n          const auto & rjo = controller->robots().robot(r.name).module().ref_joint_order();\n          if(p_vec.size() != rjo.size())\n          {\n            mc_rtc::log::warning(\"[mc_mujoco] {}::SetPDGains failed. p_vec size({})!=ref_joint_order size({})\", r.name,\n                                 p_vec.size(), rjo.size());\n            return false;\n          }\n          if(d_vec.size() != rjo.size())\n          {\n            mc_rtc::log::warning(\"[mc_mujoco] {}::SetPDGains failed. d_vec size({})!=ref_joint_order size({})\", r.name,\n                                 d_vec.size(), rjo.size());\n            return false;\n          }\n          r.kp = p_vec;\n          r.kd = d_vec;\n          return true;\n        });\n\n    // make_call for setting pd gains (by name)\n    controller->controller().datastore().make_call(\n        r.name + \"::SetPDGainsByName\", [this, &r](const std::string & jn, double p, double d) {\n          const auto & rjo = controller->robots().robot(r.name).module().ref_joint_order();\n          auto rjo_it = std::find(rjo.begin(), rjo.end(), jn);\n          if(rjo_it == rjo.end())\n          {\n            mc_rtc::log::warning(\"[mc_mujoco] {}::SetPDGainsByName failed. Joint {} not found in ref_joint_order.\",\n                                 r.name, jn);\n            return false;\n          }\n          int rjo_idx = std::distance(rjo.begin(), rjo_it);\n          r.kp[rjo_idx] = p;\n          r.kd[rjo_idx] = d;\n          return true;\n        });\n\n    // make_call for reading pd gains (for all joints)\n    controller->controller().datastore().make_call(\n        r.name + \"::GetPDGains\", [this, &r](std::vector<double> & p_vec, std::vector<double> & d_vec) {\n          p_vec.resize(0);\n          d_vec.resize(0);\n          p_vec = r.kp;\n          d_vec = r.kd;\n          const auto & rjo = controller->robots().robot(r.name).module().ref_joint_order();\n          if(p_vec.size() != rjo.size())\n          {\n            mc_rtc::log::warning(\"[mc_mujoco] {}::GetPDGains failed. p_vec size({})!=ref_joint_order size({})\", r.name,\n                                 p_vec.size(), rjo.size());\n            return false;\n          }\n          if(d_vec.size() != rjo.size())\n          {\n            mc_rtc::log::warning(\"[mc_mujoco] {}::GetPDGains failed. d_vec size({})!=ref_joint_order size({})\", r.name,\n                                 d_vec.size(), rjo.size());\n            return false;\n          }\n          return true;\n        });\n\n    // make_call for reading pd gains (by name)\n    controller->controller().datastore().make_call(\n        r.name + \"::GetPDGainsByName\", [this, &r](const std::string & jn, double & p, double & d) {\n          const auto & rjo = controller->robots().robot(r.name).module().ref_joint_order();\n          auto rjo_it = std::find(rjo.begin(), rjo.end(), jn);\n          if(rjo_it == rjo.end())\n          {\n            mc_rtc::log::warning(\"[mc_mujoco] {}::GetPDGainsByName failed. Joint {} not found in ref_joint_order.\",\n                                 r.name, jn);\n            return false;\n          }\n          int rjo_idx = std::distance(rjo.begin(), rjo_it);\n          p = r.kp[rjo_idx];\n          d = r.kd[rjo_idx];\n          return true;\n        });\n  }\n}\n\nvoid MjSimImpl::startSimulation()\n{\n  setSimulationInitialState();\n  if(!config.with_controller)\n  {\n    controller.reset();\n    return;\n  }\n\n  makeDatastoreCalls();\n\n  // get sim timestep and set the frameskip parameter\n  double simTimestep = model->opt.timestep;\n  frameskip_ = std::round(controller->timestep() / simTimestep);\n  mc_rtc::log::info(\"[mc_mujoco] MC-RTC timestep: {}. MJ timestep: {}\", controller->timestep(), simTimestep);\n  mc_rtc::log::info(\"[mc_mujoco] Hence, Frameskip: {}\", frameskip_);\n\n  for(const auto & r : robots)\n  {\n    controller->setEncoderValues(r.name, r.encoders);\n  }\n  controller->init(robots[0].encoders);\n  controller->running = true;\n}\n\nvoid MjRobot::updateSensors(mc_control::MCGlobalController * gc, mjModel * model, mjData * data)\n{\n  for(size_t i = 0; i < mj_jnt_ids.size(); ++i)\n  {\n    if(mj_jnt_to_rjo[i] == -1)\n    {\n      continue;\n    }\n    encoders[mj_jnt_to_rjo[i]] = data->qpos[model->jnt_qposadr[mj_jnt_ids[i]]];\n    alphas[mj_jnt_to_rjo[i]] = data->qvel[model->jnt_dofadr[mj_jnt_ids[i]]];\n  }\n  for(size_t i = 0; i < mj_mot_ids.size(); ++i)\n  {\n    if(mj_jnt_to_rjo[i] == -1)\n    {\n      continue;\n    }\n    torques[mj_jnt_to_rjo[i]] = data->qfrc_actuator[model->jnt_dofadr[mj_jnt_ids[i]]];\n  }\n  if(!gc)\n  {\n    return;\n  }\n  auto & robot = gc->controller().robots().robot(name);\n\n  // Body sensor updates\n  if(root_qpos_idx != -1)\n  {\n    root_pos = Eigen::Map<Eigen::Vector3d>(&data->qpos[root_qpos_idx]);\n    root_ori.w() = data->qpos[root_qpos_idx + 3];\n    root_ori.x() = data->qpos[root_qpos_idx + 4];\n    root_ori.y() = data->qpos[root_qpos_idx + 5];\n    root_ori.z() = data->qpos[root_qpos_idx + 6];\n    root_ori = root_ori.inverse();\n    root_linvel = Eigen::Map<Eigen::Vector3d>(&data->qvel[root_qvel_idx]);\n    root_angvel = Eigen::Map<Eigen::Vector3d>(&data->qvel[root_qvel_idx + 3]);\n    root_linacc = Eigen::Map<Eigen::Vector3d>(&data->qacc[root_qvel_idx]);\n    root_angacc = Eigen::Map<Eigen::Vector3d>(&data->qacc[root_qvel_idx + 3]);\n    if(robot.hasBodySensor(\"FloatingBase\"))\n    {\n      gc->setSensorPositions(name, {{\"FloatingBase\", root_pos}});\n      gc->setSensorOrientations(name, {{\"FloatingBase\", root_ori}});\n      gc->setSensorLinearVelocities(name, {{\"FloatingBase\", root_linvel}});\n      gc->setSensorAngularVelocities(name, {{\"FloatingBase\", root_angvel}});\n      gc->setSensorLinearAccelerations(name, {{\"FloatingBase\", root_linacc}});\n      // FIXME Not implemented in mc_rtc\n      // gc->setSensorAngularAccelerations(name, {{\"FloatingBase\", root_angacc}});\n    }\n  }\n\n  // Gyro update\n  for(auto & gyro : gyros)\n  {\n    mujoco_get_sensordata(*model, *data, mc_bs_to_mj_gyro_id[gyro.first], gyro.second.data());\n  }\n  gc->setSensorAngularVelocities(name, gyros);\n\n  // Accelerometers update\n  for(auto & accelerometer : accelerometers)\n  {\n    mujoco_get_sensordata(*model, *data, mc_bs_to_mj_accelerometer_id[accelerometer.first],\n                          accelerometer.second.data());\n  }\n  gc->setSensorLinearAccelerations(name, accelerometers);\n\n  // Force sensor update\n  for(auto & fs : wrenches)\n  {\n    mujoco_get_sensordata(*model, *data, mc_fs_to_mj_fsensor_id[fs.first], fs.second.force().data());\n    mujoco_get_sensordata(*model, *data, mc_fs_to_mj_tsensor_id[fs.first], fs.second.couple().data());\n    fs.second *= -1;\n  }\n  gc->setWrenches(name, wrenches);\n\n  // Joint sensor updates\n  gc->setEncoderValues(name, encoders);\n  gc->setEncoderVelocities(name, alphas);\n  gc->setJointTorques(name, torques);\n}\n\nvoid MjSimImpl::updateData()\n{\n  for(auto & r : robots)\n  {\n    r.updateSensors(controller.get(), model, data);\n  }\n}\n\nvoid MjRobot::updateControl(const mc_rbdyn::Robot & robot)\n{\n  mj_prev_ctrl_q = mj_next_ctrl_q;\n  mj_prev_ctrl_alpha = mj_next_ctrl_alpha;\n  size_t ctrl_idx = 0;\n  for(size_t i = 0; i < mj_to_mbc.size(); ++i)\n  {\n    auto jIndex = mj_to_mbc[i];\n    if(jIndex != -1)\n    {\n      mj_next_ctrl_q[ctrl_idx] = robot.mbc().q[jIndex][0];\n      mj_next_ctrl_alpha[ctrl_idx] = robot.mbc().alpha[jIndex][0];\n      ctrl_idx++;\n    }\n  }\n}\n\nvoid MjRobot::sendControl(const mjModel & model, mjData & data, size_t interp_idx, size_t frameskip_)\n{\n  for(size_t i = 0; i < mj_ctrl.size(); ++i)\n  {\n    auto mot_id = mj_mot_ids[i];\n    auto pos_act_id = mj_pos_act_ids[i];\n    auto vel_act_id = mj_vel_act_ids[i];\n    auto rjo_id = mj_jnt_to_rjo[i];\n    if(rjo_id == -1)\n    {\n      continue;\n    }\n    // compute desired q using interpolation\n    double q_ref = (interp_idx + 1) * (mj_next_ctrl_q[i] - mj_prev_ctrl_q[i]) / frameskip_;\n    q_ref += mj_prev_ctrl_q[i];\n    // compute desired alpha using interpolation\n    double alpha_ref = (interp_idx + 1) * (mj_next_ctrl_alpha[i] - mj_prev_ctrl_alpha[i]) / frameskip_;\n    alpha_ref += mj_prev_ctrl_alpha[i];\n    if(mot_id != -1)\n    {\n      // compute desired torque using PD control\n      mj_ctrl[i] = PD(i, q_ref, encoders[rjo_id], alpha_ref, alphas[rjo_id]);\n      double ratio = model.actuator_gear[6 * mot_id];\n      data.ctrl[mot_id] = mj_ctrl[i] / ratio;\n    }\n    if(pos_act_id != -1)\n    {\n      data.ctrl[pos_act_id] = q_ref;\n    }\n    if(vel_act_id != -1)\n    {\n      data.ctrl[vel_act_id] = alpha_ref;\n    }\n  }\n}\n\nbool MjSimImpl::controlStep()\n{\n  auto interp_idx = iterCount_ % frameskip_;\n  // After every frameskip iters\n  if(config.with_controller && interp_idx == 0)\n  {\n    // run the controller\n    if(!controller->run())\n    {\n      return true;\n    }\n    for(auto & r : robots)\n    {\n      r.updateControl(controller->robots().robot(r.name));\n    }\n  }\n  // On each control iter\n  for(auto & r : robots)\n  {\n    r.sendControl(*model, *data, interp_idx, frameskip_);\n  }\n  iterCount_++;\n  return false;\n}\n\nvoid MjSimImpl::simStep()\n{\n  // clear old perturbations, apply new\n  mju_zero(data->xfrc_applied, 6 * model->nbody);\n  mjv_applyPerturbPose(model, data, &pert, 0); // move mocap bodies only\n  mjv_applyPerturbForce(model, data, &pert);\n\n  // take one step in simulation\n  // model.opt.timestep will be used here\n  mj_step(model, data);\n}\n\nvoid MjSimImpl::resetSimulation(const std::map<std::string, std::vector<double>> & reset_qs,\n                                const std::map<std::string, sva::PTransformd> & reset_pos)\n{\n  iterCount_ = 0;\n  reset_simulation_ = false;\n  if(controller)\n  {\n    controller->reset(reset_qs, reset_pos);\n    for(auto & robot : robots)\n    {\n      robot.reset(controller->robot(robot.name));\n    }\n    controller->running = true;\n  }\n  mj_resetData(model, data);\n  setSimulationInitialState();\n  makeDatastoreCalls();\n}\n\nbool MjSimImpl::stepSimulation()\n{\n  if(reset_simulation_)\n  {\n    resetSimulation({}, {});\n  }\n  auto start_step = clock::now();\n  // Only run the GUI update if the simulation is paused\n  if(config.step_by_step && rem_steps == 0)\n  {\n    if(controller)\n    {\n      controller->running = false;\n      controller->run();\n      controller->running = true;\n    }\n    mj_sim_start_t = start_step;\n    std::this_thread::sleep_for(std::chrono::milliseconds(10));\n    return false;\n  }\n  if(iterCount_ > 0)\n  {\n    duration_us dt = start_step - mj_sim_start_t;\n    mj_sync_delay += duration_us(1e6 * model->opt.timestep) - dt;\n    mj_sim_dt[(iterCount_ - 1) % mj_sim_dt.size()] = dt.count();\n  }\n  mj_sim_start_t = start_step;\n  auto do_step = [this, &start_step]() {\n    {\n      std::lock_guard<std::mutex> lock(rendering_mutex_);\n      simStep();\n    }\n    updateData();\n    return controlStep();\n  };\n  bool done = false;\n  if(!config.step_by_step)\n  {\n    done = do_step();\n  }\n  if(config.step_by_step && rem_steps > 0)\n  {\n    // Doing 'frameskip_' steps of sim + control\n    // (But controller.run() will execute only when interp_idx == 0)\n    for(size_t i = 0; i < frameskip_; i++)\n    {\n      done = do_step() && done;\n    }\n    rem_steps--;\n  }\n  if(config.sync_real_time)\n  {\n    std::this_thread::sleep_until(start_step + duration_us(1e6 * model->opt.timestep) + mj_sync_delay);\n  }\n  return done;\n}\n\nvoid MjSimImpl::updateScene()\n{\n  // update scene and render\n  std::lock_guard<std::mutex> lock(rendering_mutex_);\n  mjv_updateScene(model, data, &options, &pert, &camera, mjCAT_ALL, &scene);\n\n  if(client)\n  {\n    client->updateScene(scene);\n  }\n\n  // process pending GUI events, call GLFW callbacks\n  glfwPollEvents();\n}\n\nbool MjSimImpl::render()\n{\n  if(!config.with_visualization)\n  {\n    return true;\n  }\n\n  // mj render\n  mjr_render(uistate.rect[0], &scene, &context);\n\n  // Render ImGui\n  ImGui_ImplOpenGL3_NewFrame();\n  ImGui_ImplGlfw_NewFrame();\n  ImGui::NewFrame();\n  ImGuizmo::BeginFrame();\n  ImGuiIO & io = ImGui::GetIO();\n  ImGuizmo::AllowAxisFlip(false);\n  ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);\n  if(client)\n  {\n    client->update();\n    client->draw2D(window);\n    client->draw3D();\n  }\n  {\n    auto right_margin = 5.0f;\n    auto top_margin = 5.0f;\n    auto width = io.DisplaySize.x - 2 * right_margin;\n    auto height = io.DisplaySize.y - 2 * top_margin;\n    ImGui::SetNextWindowPos({0.8f * width - right_margin, top_margin}, ImGuiCond_FirstUseEver);\n    ImGui::SetNextWindowSize({0.2f * width, 0.3f * height}, ImGuiCond_FirstUseEver);\n#if mjVERSION_HEADER <= 210\n    ImGui::Begin(fmt::format(\"mc_mujoco (MuJoCo {})\", mj_version()).c_str());\n#else\n    ImGui::Begin(fmt::format(\"mc_mujoco (MuJoCo {})\", mj_versionString()).c_str());\n#endif\n    size_t nsamples = std::min(mj_sim_dt.size(), iterCount_);\n    mj_sim_dt_average = 0;\n    for(size_t i = 0; i < nsamples; ++i)\n    {\n      mj_sim_dt_average += mj_sim_dt[i] / nsamples;\n    }\n    ImGui::Text(\"Average sim time: %.2f\u03bcs\", mj_sim_dt_average);\n    ImGui::Text(\"Simulation/Real time: %.2f\", mj_sim_dt_average / (1e6 * model->opt.timestep));\n    if(ImGui::Checkbox(\"Sync with real-time\", &config.sync_real_time))\n    {\n      if(config.sync_real_time)\n      {\n        mj_sync_delay = duration_us(0);\n      }\n    }\n    ImGui::Checkbox(\"Step-by-step\", &config.step_by_step);\n    if(config.step_by_step)\n    {\n      auto doNStepsButton = [&](size_t n, bool final_) {\n        size_t n_ms = std::ceil(n * 1000 * (controller ? controller->timestep() : model->opt.timestep));\n        if(ImGui::Button(fmt::format(\"+{}ms\", n_ms).c_str()))\n        {\n          rem_steps = n;\n        }\n        if(!final_)\n        {\n          ImGui::SameLine();\n        }\n      };\n      doNStepsButton(1, false);\n      doNStepsButton(5, false);\n      doNStepsButton(10, false);\n      doNStepsButton(50, false);\n      doNStepsButton(100, true);\n    }\n    auto flag_to_gui = [&](const char * label, mjtVisFlag flag) {\n      bool show = options.flags[flag];\n      if(ImGui::Checkbox(label, &show))\n      {\n        options.flags[flag] = show;\n      }\n    };\n    flag_to_gui(\"Show contact points [C]\", mjVIS_CONTACTPOINT);\n    flag_to_gui(\"Show contact forces [F]\", mjVIS_CONTACTFORCE);\n    flag_to_gui(\"Make Transparent [T]\", mjVIS_TRANSPARENT);\n    auto group_to_checkbox = [&](size_t group, bool last) {\n      bool show = options.geomgroup[group];\n      if(ImGui::Checkbox(fmt::format(\"{}\", group).c_str(), &show))\n      {\n        options.geomgroup[group] = show;\n      }\n      if(!last)\n      {\n        ImGui::SameLine();\n      }\n    };\n    ImGui::Text(\"%s\", fmt::format(\"Visible layers [0-{}]\", mjNGROUP).c_str());\n    for(size_t i = 0; i < mjNGROUP; ++i)\n    {\n      group_to_checkbox(i, i == mjNGROUP - 1);\n    }\n    if(ImGui::Button(\"Reset simulation\", ImVec2(-FLT_MIN, 0.0f)))\n    {\n      reset_simulation_ = true;\n    }\n    ImGui::End();\n  }\n  ImGui::Render();\n  ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());\n\n  // swap OpenGL buffers (blocking call due to v-sync)\n  glfwSwapBuffers(window);\n\n  return !glfwWindowShouldClose(window);\n}\n\nvoid MjSimImpl::stopSimulation() {}\n\nvoid MjSimImpl::saveGUISettings()\n{\n  auto user_path = bfs::path(USER_FOLDER);\n  if(!bfs::exists(user_path))\n  {\n    if(!bfs::create_directories(user_path))\n    {\n      mc_rtc::log::critical(\"Failed to create the user directory: {}. GUI configuration will not be saved\",\n                            user_path.string());\n      return;\n    }\n  }\n  mc_rtc::Configuration config;\n  auto camera_c = config.add(\"camera\");\n  auto lookat = camera_c.array(\"lookat\", 3);\n  for(size_t i = 0; i < 3; ++i)\n  {\n    lookat.push(camera.lookat[i]);\n  }\n  camera_c.add(\"distance\", camera.distance);\n  camera_c.add(\"azimuth\", camera.azimuth);\n  camera_c.add(\"elevation\", camera.elevation);\n  auto visualize_c = config.add(\"visualize\");\n  visualize_c.add(\"collisions\", static_cast<bool>(options.geomgroup[0]));\n  visualize_c.add(\"visuals\", static_cast<bool>(options.geomgroup[1]));\n  visualize_c.add(\"contact-points\", static_cast<bool>(options.flags[mjVIS_CONTACTPOINT]));\n  visualize_c.add(\"contact-forces\", static_cast<bool>(options.flags[mjVIS_CONTACTFORCE]));\n  auto path_out = (user_path / \"mc_mujoco.yaml\").string();\n  config.save(path_out);\n  mc_rtc::log::success(\"[mc_mujoco] Configuration saved to {}\", path_out);\n}\n\nMjSim::MjSim(const MjConfiguration & config) : impl(new MjSimImpl(config))\n{\n  impl->startSimulation();\n}\n\nMjSim::~MjSim()\n{\n  impl->cleanup();\n}\n\nbool MjSim::stepSimulation()\n{\n  return impl->stepSimulation();\n}\n\nvoid MjSim::stopSimulation()\n{\n  impl->stopSimulation();\n}\n\nvoid MjSim::updateScene()\n{\n  impl->updateScene();\n}\n\nvoid MjSim::resetSimulation(const std::map<std::string, std::vector<double>> & reset_qs,\n                            const std::map<std::string, sva::PTransformd> & reset_pos)\n{\n  impl->resetSimulation(reset_qs, reset_pos);\n}\n\nbool MjSim::render()\n{\n  return impl->render();\n}\n\nmc_control::MCGlobalController * MjSim::controller() noexcept\n{\n  return impl->get_controller();\n}\n\n} // namespace mc_mujoco\n", "meta": {"hexsha": "dfedde047e70543dad2b766dd28c7ae9022e5a2d", "size": 28909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mj_sim.cpp", "max_stars_repo_name": "rohanpsingh/mc_mujoco", "max_stars_repo_head_hexsha": "dd944da579a715967098c9d8261753d50ee4299c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T07:43:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T08:18:22.000Z", "max_issues_repo_path": "src/mj_sim.cpp", "max_issues_repo_name": "rohanpsingh/mc_mujoco", "max_issues_repo_head_hexsha": "dd944da579a715967098c9d8261753d50ee4299c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-15T09:56:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T05:02:58.000Z", "max_forks_repo_path": "src/mj_sim.cpp", "max_forks_repo_name": "rohanpsingh/mc_mujoco", "max_forks_repo_head_hexsha": "dd944da579a715967098c9d8261753d50ee4299c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T06:48:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T10:14:27.000Z", "avg_line_length": 30.4947257384, "max_line_length": 120, "alphanum_fraction": 0.6129233111, "num_tokens": 8191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18432007592949032}}
{"text": "#ifndef DATASET_HPP\n#define DATASET_HPP\n\n#include <fstream>\n#include <boost/filesystem.hpp>\n\n#include \"Eigen/Core\"\n#include <Eigen/Geometry> \n\n\nclass DataSet\n{\npublic:\n  DataSet(const std::string& folder);\n  ~DataSet();\n  \n  bool get_next_point_cloud(Eigen::MatrixXd& P, Eigen::MatrixXd &colors, Eigen::Matrix4d& t_camera);\n  Eigen::Affine3f findPlaneRotation(Eigen::MatrixXd& points);\nprivate:\n  bool operational;\n  int next_file_idx;\n  std::string folder_path;\n  std::vector<std::string> depth_files;\n  std::string rgb_ref_file_name;\n  std::fstream camera_ref_file;\n  Eigen::Matrix4d rOffset;\n  \n  bool get_next_camera(Eigen::Matrix4d& cam, const double timestamp);\n  std::string get_next_rgb(const double timestamp);\n};\n\n#endif // DATASET_HPP\n", "meta": {"hexsha": "64465391af85250fdef96a9febbdcf8561fd41e8", "size": 746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DataSet.hpp", "max_stars_repo_name": "asterycs/rtsr", "max_stars_repo_head_hexsha": "176bf342581daa58f84eaffc6d34034a98cfa255", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-09T23:38:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T09:06:46.000Z", "max_issues_repo_path": "src/DataSet.hpp", "max_issues_repo_name": "haohanxingkong/rtsr", "max_issues_repo_head_hexsha": "176bf342581daa58f84eaffc6d34034a98cfa255", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-05T14:38:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-14T18:33:46.000Z", "max_forks_repo_path": "src/DataSet.hpp", "max_forks_repo_name": "haohanxingkong/rtsr", "max_forks_repo_head_hexsha": "176bf342581daa58f84eaffc6d34034a98cfa255", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-08-22T12:30:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T13:09:24.000Z", "avg_line_length": 22.6060606061, "max_line_length": 100, "alphanum_fraction": 0.7479892761, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18432007592949032}}
{"text": "// Copyright David Abrahams 2002.\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#include <boost/python/object/inheritance.hpp>\r\n#include <boost/python/type_id.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n#if _MSC_FULL_VER >= 13102171 && _MSC_FULL_VER <= 13102179\r\n# include <boost/graph/reverse_graph.hpp>\r\n#endif \r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/reverse_graph.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/bind.hpp>\r\n#include <boost/integer_traits.hpp>\r\n#include <boost/tuple/tuple.hpp>\r\n#include <boost/tuple/tuple_comparison.hpp>\r\n#include <queue>\r\n#include <vector>\r\n#include <functional>\r\n\r\n//\r\n// Procedure:\r\n//\r\n//      The search is a BFS over the space of (type,address) pairs\r\n//      guided by the edges of the casting graph whose nodes\r\n//      correspond to classes, and whose edges are traversed by\r\n//      applying associated cast functions to an address. We use\r\n//      vertex distance to the goal node in the cast_graph to rate the\r\n//      paths. The vertex distance to any goal node is calculated on\r\n//      demand and outdated by the addition of edges to the graph.\r\n\r\nnamespace boost {\r\nnamespace\r\n{\r\n  enum edge_cast_t { edge_cast = 8010 };\r\n  template <class T> inline void unused_variable(const T&) { }\r\n}\r\n\r\n// Install properties\r\nBOOST_INSTALL_PROPERTY(edge, cast);\r\n\r\nnamespace\r\n{\r\n  typedef void*(*cast_function)(void*);\r\n  \r\n  //\r\n  // Here we put together the low-level data structures of the\r\n  // casting graph representation.\r\n  //\r\n  typedef python::type_info class_id;\r\n\r\n  // represents a graph of available casts\r\n  \r\n#if 0\r\n  struct cast_graph\r\n      :\r\n#else\r\n        typedef\r\n#endif \r\n        adjacency_list<vecS,vecS, bidirectionalS, no_property\r\n\r\n      // edge index property allows us to look up edges in the connectivity matrix\r\n      , property<edge_index_t,std::size_t\r\n  \r\n                 // The function which casts a void* from the edge's source type\r\n                 // to its destination type.\r\n                 , property<edge_cast_t,cast_function> > >\r\n#if 0\r\n  {};\r\n#else\r\n  cast_graph;\r\n#endif \r\n\r\n  typedef cast_graph::vertex_descriptor vertex_t;\r\n  typedef cast_graph::edge_descriptor edge_t;\r\n  \r\n  struct smart_graph\r\n  {\r\n      typedef std::vector<std::size_t>::const_iterator node_distance_map;\r\n      \r\n      typedef std::pair<cast_graph::out_edge_iterator\r\n                        , cast_graph::out_edge_iterator> out_edges_t;\r\n      \r\n      // Return a map of the distances from any node to the given\r\n      // target node\r\n      node_distance_map distances_to(vertex_t target) const\r\n      {\r\n          std::size_t n = num_vertices(m_topology);\r\n          if (m_distances.size() != n * n)\r\n          {\r\n              m_distances.clear();\r\n              m_distances.resize(n * n, (std::numeric_limits<std::size_t>::max)());\r\n              m_known_vertices = n;\r\n          }\r\n          \r\n          std::vector<std::size_t>::iterator to_target = m_distances.begin() + n * target;\r\n\r\n          // this node hasn't been used as a target yet\r\n          if (to_target[target] != 0)\r\n          {\r\n              typedef reverse_graph<cast_graph> reverse_cast_graph;\r\n              reverse_cast_graph reverse_topology(m_topology);\r\n              \r\n              to_target[target] = 0;\r\n              \r\n              breadth_first_search(\r\n                  reverse_topology, target\r\n                  , visitor(\r\n                      make_bfs_visitor(\r\n                          record_distances(\r\n                              make_iterator_property_map(\r\n                                  to_target\r\n                                  , get(vertex_index, reverse_topology)\r\n# ifdef BOOST_NO_STD_ITERATOR_TRAITS\r\n                                  , *to_target\r\n# endif \r\n                                  )\r\n                              , on_tree_edge()\r\n                              ))));\r\n          }\r\n\r\n          return to_target;\r\n      }\r\n\r\n      cast_graph& topology() { return m_topology; }\r\n      cast_graph const& topology() const { return m_topology; }\r\n\r\n      smart_graph()\r\n          : m_known_vertices(0)\r\n      {}\r\n      \r\n   private:\r\n      cast_graph m_topology;\r\n      mutable std::vector<std::size_t> m_distances;\r\n      mutable std::size_t m_known_vertices;\r\n  };\r\n  \r\n  smart_graph& full_graph()\r\n  {\r\n      static smart_graph x;\r\n      return x;\r\n  }\r\n  \r\n  smart_graph& up_graph()\r\n  {\r\n      static smart_graph x;\r\n      return x;\r\n  }\r\n\r\n  //\r\n  // Our index of class types\r\n  //\r\n  using boost::python::objects::dynamic_id_function;\r\n  typedef tuples::tuple<\r\n      class_id               // static type\r\n      , vertex_t             // corresponding vertex \r\n      , dynamic_id_function  // dynamic_id if polymorphic, or 0\r\n      >\r\n  index_entry_interface;\r\n  typedef index_entry_interface::inherited index_entry;\r\n  enum { ksrc_static_t, kvertex, kdynamic_id };\r\n  \r\n  typedef std::vector<index_entry> type_index_t;\r\n\r\n  \r\n  type_index_t& type_index()\r\n  {\r\n      static type_index_t x;\r\n      return x;\r\n  }\r\n\r\n  template <class Tuple>\r\n  struct select1st\r\n  {\r\n      typedef typename tuples::element<0, Tuple>::type result_type;\r\n      \r\n      result_type const& operator()(Tuple const& x) const\r\n      {\r\n          return tuples::get<0>(x);\r\n      }\r\n  };\r\n  \r\n  // map a type to a position in the index\r\n  inline type_index_t::iterator type_position(class_id type)\r\n  {\r\n      typedef index_entry entry;\r\n      \r\n      return std::lower_bound(\r\n          type_index().begin(), type_index().end()\r\n          , boost::make_tuple(type, vertex_t(), dynamic_id_function(0))\r\n          , boost::bind<bool>(std::less<class_id>()\r\n               , boost::bind<class_id>(select1st<entry>(), _1)\r\n               , boost::bind<class_id>(select1st<entry>(), _2)));\r\n  }\r\n\r\n  inline index_entry* seek_type(class_id type)\r\n  {\r\n      type_index_t::iterator p = type_position(type);\r\n      if (p == type_index().end() || tuples::get<ksrc_static_t>(*p) != type)\r\n          return 0;\r\n      else\r\n          return &*p;\r\n  }\r\n  \r\n  // Get the entry for a type, inserting if necessary\r\n  inline type_index_t::iterator demand_type(class_id type)\r\n  {\r\n      type_index_t::iterator p = type_position(type);\r\n\r\n      if (p != type_index().end() && tuples::get<ksrc_static_t>(*p) == type)\r\n          return p;\r\n\r\n      vertex_t v = add_vertex(full_graph().topology());\r\n      vertex_t v2 = add_vertex(up_graph().topology());\r\n      unused_variable(v2);\r\n      assert(v == v2);\r\n      return type_index().insert(p, boost::make_tuple(type, v, dynamic_id_function(0)));\r\n  }\r\n\r\n  // Map a two types to a vertex in the graph, inserting if necessary\r\n  typedef std::pair<type_index_t::iterator, type_index_t::iterator>\r\n        type_index_iterator_pair;\r\n  \r\n  inline type_index_iterator_pair\r\n  demand_types(class_id t1, class_id t2)\r\n  {\r\n      // be sure there will be no reallocation\r\n      type_index().reserve(type_index().size() + 2);\r\n      type_index_t::iterator first = demand_type(t1);\r\n      type_index_t::iterator second = demand_type(t2);\r\n      if (first == second)\r\n          ++first;\r\n      return std::make_pair(first, second);\r\n  }\r\n\r\n  struct q_elt\r\n  {\r\n      q_elt(std::size_t distance\r\n            , void* src_address\r\n            , vertex_t target\r\n            , cast_function cast\r\n            )\r\n          : distance(distance)\r\n          , src_address(src_address)\r\n          , target(target)\r\n          , cast(cast)\r\n      {}\r\n      \r\n      std::size_t distance;\r\n      void* src_address;\r\n      vertex_t target;\r\n      cast_function cast;\r\n\r\n      bool operator<(q_elt const& rhs) const\r\n      {\r\n          return distance < rhs.distance;\r\n      }\r\n  };\r\n\r\n  // Optimization:\r\n  //\r\n  // Given p, src_t, dst_t\r\n  //\r\n  // Get a pointer pd to the most-derived object\r\n  //    if it's polymorphic, dynamic_cast to void*\r\n  //    otherwise pd = p\r\n  //\r\n  // Get the most-derived typeid src_td\r\n  //\r\n  // ptrdiff_t offset = p - pd\r\n  //\r\n  // Now we can keep a cache, for [src_t, offset, src_td, dst_t] of\r\n  // the cast transformation function to use on p and the next src_t\r\n  // in the chain.  src_td, dst_t don't change throughout this\r\n  // process. In order to represent unreachability, when a pair is\r\n  // found to be unreachable, we stick a 0-returning \"dead-cast\"\r\n  // function in the cache.\r\n  \r\n  // This is needed in a few places below\r\n  inline void* identity_cast(void* p)\r\n  {\r\n      return p;\r\n  }\r\n\r\n  void* search(smart_graph const& g, void* p, vertex_t src, vertex_t dst)\r\n  {\r\n      // I think this test was thoroughly bogus -- dwa\r\n      // If we know there's no path; bail now.\r\n      // if (src > g.known_vertices() || dst > g.known_vertices())\r\n      //    return 0;\r\n      \r\n      smart_graph::node_distance_map d(g.distances_to(dst));\r\n\r\n      if (d[src] == (std::numeric_limits<std::size_t>::max)())\r\n          return 0;\r\n\r\n      typedef property_map<cast_graph,edge_cast_t>::const_type cast_map;\r\n      cast_map casts = get(edge_cast, g.topology());\r\n      \r\n      typedef std::pair<vertex_t,void*> search_state;\r\n      typedef std::vector<search_state> visited_t;\r\n      visited_t visited;\r\n      std::priority_queue<q_elt> q;\r\n      \r\n      q.push(q_elt(d[src], p, src, identity_cast));\r\n      while (!q.empty())\r\n      {\r\n          q_elt top = q.top();\r\n          q.pop();\r\n          \r\n          // Check to see if we have a real state\r\n          void* dst_address = top.cast(top.src_address);\r\n          if (dst_address == 0)\r\n              continue;\r\n\r\n          if (top.target == dst)\r\n              return dst_address;\r\n          \r\n          search_state s(top.target,dst_address);\r\n\r\n          visited_t::iterator pos = std::lower_bound(\r\n              visited.begin(), visited.end(), s);\r\n\r\n          // If already visited, continue\r\n          if (pos != visited.end() && *pos == s)\r\n              continue;\r\n          \r\n          visited.insert(pos, s); // mark it\r\n\r\n          // expand it:\r\n          smart_graph::out_edges_t edges = out_edges(s.first, g.topology());\r\n          for (cast_graph::out_edge_iterator p = edges.first\r\n                   , finish = edges.second\r\n                   ; p != finish\r\n                   ; ++p\r\n              )\r\n          {\r\n              edge_t e = *p;\r\n              q.push(q_elt(\r\n                         d[target(e, g.topology())]\r\n                         , dst_address\r\n                         , target(e, g.topology())\r\n                         , boost::get(casts, e)));\r\n          }\r\n      }\r\n      return 0;\r\n  }\r\n\r\n  struct cache_element\r\n  {\r\n      typedef tuples::tuple<\r\n          class_id              // source static type\r\n          , class_id            // target type\r\n          , std::ptrdiff_t      // offset within source object\r\n          , class_id            // source dynamic type\r\n          >::inherited key_type;\r\n\r\n      cache_element(key_type const& k)\r\n          : key(k)\r\n          , offset(0)\r\n      {}\r\n      \r\n      key_type key;\r\n      std::ptrdiff_t offset;\r\n\r\n      BOOST_STATIC_CONSTANT(\r\n          std::ptrdiff_t, not_found = integer_traits<std::ptrdiff_t>::const_min);\r\n      \r\n      bool operator<(cache_element const& rhs) const\r\n      {\r\n          return this->key < rhs.key;\r\n      }\r\n\r\n      bool unreachable() const\r\n      {\r\n          return offset == not_found;\r\n      }\r\n  };\r\n  \r\n  enum { kdst_t = ksrc_static_t + 1, koffset, ksrc_dynamic_t };\r\n  typedef std::vector<cache_element> cache_t;\r\n\r\n  cache_t& cache()\r\n  {\r\n      static cache_t x;\r\n      return x;\r\n  }\r\n\r\n  inline void* convert_type(void* const p, class_id src_t, class_id dst_t, bool polymorphic)\r\n  {\r\n      // Quickly rule out unregistered types\r\n      index_entry* src_p = seek_type(src_t);\r\n      if (src_p == 0)\r\n          return 0;\r\n\r\n      index_entry* dst_p = seek_type(dst_t);\r\n      if (dst_p == 0)\r\n          return 0;\r\n    \r\n      // Look up the dynamic_id function and call it to get the dynamic\r\n      // info\r\n      boost::python::objects::dynamic_id_t dynamic_id = polymorphic\r\n          ? tuples::get<kdynamic_id>(*src_p)(p)\r\n          : std::make_pair(p, src_t);\r\n    \r\n      // Look in the cache first for a quickie address translation\r\n      std::ptrdiff_t offset = (char*)p - (char*)dynamic_id.first;\r\n\r\n      cache_element seek(boost::make_tuple(src_t, dst_t, offset, dynamic_id.second));\r\n      cache_t& c = cache();\r\n      cache_t::iterator const cache_pos\r\n          = std::lower_bound(c.begin(), c.end(), seek);\r\n                      \r\n\r\n      // if found in the cache, we're done\r\n      if (cache_pos != c.end() && cache_pos->key == seek.key)\r\n      {\r\n          return cache_pos->offset == cache_element::not_found\r\n              ? 0 : (char*)p + cache_pos->offset;\r\n      }\r\n\r\n      // If we are starting at the most-derived type, only look in the up graph\r\n      smart_graph const& g = polymorphic && dynamic_id.second != src_t\r\n          ? full_graph() : up_graph();\r\n    \r\n      void* result = search(\r\n          g, p, tuples::get<kvertex>(*src_p)\r\n          , tuples::get<kvertex>(*dst_p));\r\n\r\n      // update the cache\r\n      c.insert(cache_pos, seek)->offset\r\n          = (result == 0) ? cache_element::not_found : (char*)result - (char*)p;\r\n\r\n      return result;\r\n  }\r\n}\r\n\r\nnamespace python { namespace objects {\r\n\r\nBOOST_PYTHON_DECL void* find_dynamic_type(void* p, class_id src_t, class_id dst_t)\r\n{\r\n    return convert_type(p, src_t, dst_t, true);\r\n}\r\n\r\nBOOST_PYTHON_DECL void* find_static_type(void* p, class_id src_t, class_id dst_t)\r\n{\r\n    return convert_type(p, src_t, dst_t, false);\r\n}\r\n\r\nBOOST_PYTHON_DECL void add_cast(\r\n    class_id src_t, class_id dst_t, cast_function cast, bool is_downcast)\r\n{\r\n    // adding an edge will invalidate any record of unreachability in\r\n    // the cache.\r\n    static std::size_t expected_cache_len = 0;\r\n    cache_t& c = cache();\r\n    if (c.size() > expected_cache_len)\r\n    {\r\n        c.erase(std::remove_if(\r\n                    c.begin(), c.end(),\r\n                    mem_fn(&cache_element::unreachable))\r\n                , c.end());\r\n\r\n        // If any new cache entries get added, we'll have to do this\r\n        // again when the next edge is added\r\n        expected_cache_len = c.size();\r\n    }\r\n    \r\n    type_index_iterator_pair types = demand_types(src_t, dst_t);\r\n    vertex_t src = tuples::get<kvertex>(*types.first);\r\n    vertex_t dst = tuples::get<kvertex>(*types.second);\r\n\r\n    cast_graph* const g[2] = { &up_graph().topology(), &full_graph().topology() };\r\n    \r\n    for (cast_graph*const* p = g + (is_downcast ? 1 : 0); p < g + 2; ++p)\r\n    {\r\n        edge_t e;\r\n        bool added;\r\n\r\n        tie(e, added) = add_edge(src, dst, **p);\r\n        assert(added);\r\n\r\n        put(get(edge_cast, **p), e, cast);\r\n        put(get(edge_index, **p), e, num_edges(full_graph().topology()) - 1);\r\n    }\r\n}\r\n\r\nBOOST_PYTHON_DECL void register_dynamic_id_aux(\r\n    class_id static_id, dynamic_id_function get_dynamic_id)\r\n{\r\n    tuples::get<kdynamic_id>(*demand_type(static_id)) = get_dynamic_id;\r\n}\r\n\r\n}}} // namespace boost::python::objects\r\n", "meta": {"hexsha": "9c81b4a0e77b666e6930b71b396c5d7a6efe232e", "size": 15205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/python/src/object/inheritance.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": "thirdparty/boost-python/libs/python/src/object/inheritance.cpp", "max_issues_repo_name": "alexa-infra/negine", "max_issues_repo_head_hexsha": "d9060a7c83a41c95c361c470b56c2ddab3ba04de", "max_issues_repo_licenses": ["MIT"], "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": "thirdparty/boost-python/libs/python/src/object/inheritance.cpp", "max_forks_repo_name": "alexa-infra/negine", "max_forks_repo_head_hexsha": "d9060a7c83a41c95c361c470b56c2ddab3ba04de", "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": 30.6552419355, "max_line_length": 93, "alphanum_fraction": 0.5727063466, "num_tokens": 3511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.18432007243017431}}
{"text": "#include <chrono>\n#include <thread>\n#include <boost/test/unit_test.hpp>\n#include \"instruments/meter.hpp\"\n#include \"common.hpp\"\n\nnamespace mock{\n\tclass ticker;\n\tstatic std::vector<ticker*> one_minute_tickers;\n\tstatic std::vector<ticker*> five_minute_tickers;\n\tstatic std::vector<ticker*> fifteen_minute_tickers;\n\t\n\tclass ticker {\n\tpublic:\n\t\ttypedef std::chrono::duration<double, std::chrono::nanoseconds::period> time_type;\n\n\t\ttemplate<typename DurationAll, typename DurationTick>\n\t\tticker(const DurationAll& footprint,const DurationTick& tick)\n\t\t: m_tick(std::chrono::duration_cast<std::chrono::nanoseconds>(tick)),\n\t\t  m_tick_count(0),\n\t\t  m_mark_count(0),\n\t\t  m_footprint(std::chrono::duration_cast<std::chrono::minutes>(footprint))\n\t\t{\n\t\t\tif(m_footprint == std::chrono::minutes(1)){\n\t\t\t\tone_minute_tickers.push_back(this);\n\t\t\t} else if(m_footprint == std::chrono::minutes(5)){\n\t\t\t\tfive_minute_tickers.push_back(this);\n\t\t\t} else if(m_footprint == std::chrono::minutes(15)){\n\t\t\t\tfifteen_minute_tickers.push_back(this);\n\t\t\t} else {\n\t\t\t\tthrow std::invalid_argument(\"mock ticker received a non-standard footprint.\");\n\t\t\t}\n\t\t}\n\n\t\tvoid tick(const unsigned int& count){\n\t\t\tm_mark_count += count;\n\t\t\t++m_tick_count;\n\t\t}\n\n\t\ttemplate<typename Duration = std::chrono::minutes>\n\t    double rate(const Duration& unit = std::chrono::minutes(1)) {\n\t        return 0.0;\n\t    }\n\n\t    time_type interval(){\n\t    \treturn std::chrono::nanoseconds(5000);\n\t    }\n\n\t    int count(){\n\t    \treturn m_mark_count;\n\t    }\n\n\t    int ticks(){\n\t    \treturn m_tick_count;\n\t    }\n\t    std::chrono::nanoseconds m_tick;\n\t    std::chrono::minutes m_footprint;\n\t    unsigned int m_tick_count;\n\t    unsigned int m_mark_count;\n\t};\n}\n\nBOOST_AUTO_TEST_CASE(meter_counting_test){\n\tmetrics::instruments::meter m;\n\tBOOST_CHECK_EQUAL(m.count(),0);\n\n\t// test mark by 1, by n\n\tm.mark();\n\tBOOST_CHECK_EQUAL(m.count(),1);\n\n\t// test increment-by-delta\n\tm.mark(7);\n\tBOOST_CHECK_EQUAL(m.count(),8);\n}\n\nBOOST_AUTO_TEST_CASE(meter_rate_test){\n\tmock::clock::set_time(0);\n\tmetrics::instruments::clocked_meter<mock::clock> m;\n\tmock::clock::set_time(1);\n\tBOOST_CHECK_EQUAL(m.mean_rate(),0);\n\n\tmock::clock::set_time(5);\n\tm.mark();\n\tBOOST_CHECK_CLOSE(m.mean_rate(),0.2,1e-8);\n\n\n\tmock::clock::set_time(100);\n\tm.mark(99);\n\tBOOST_CHECK_CLOSE(m.mean_rate(),1,1e-8);\n}\n\nBOOST_AUTO_TEST_CASE(meter_ticker_test){\n\tusing mock::ticker;\n\n\tmock::clock::set_time(0);\n\ttypedef metrics::instruments::clocked_meter<mock::clock,mock::ticker> mock_meter;\n\tmock_meter m;\n\tBOOST_ASSERT(mock::one_minute_tickers.size() == 1);\n\tBOOST_ASSERT(mock::five_minute_tickers.size() == 1);\n\tBOOST_ASSERT(mock::fifteen_minute_tickers.size() == 1);\n\n\tticker& ticker_1 = *mock::one_minute_tickers[0];\n\tticker& ticker_5 = *mock::five_minute_tickers[0];\n\tticker& ticker_15 = *mock::fifteen_minute_tickers[0];\n\n\tBOOST_CHECK_EQUAL(ticker_1.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_5.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_15.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_1.ticks(),0);\n\tBOOST_CHECK_EQUAL(ticker_5.ticks(),0);\n\tBOOST_CHECK_EQUAL(ticker_15.ticks(),0);\n\n\n\tmock::clock::set_time(4);\n\n\tBOOST_CHECK_EQUAL(ticker_1.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_5.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_15.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_1.ticks(),0);\n\tBOOST_CHECK_EQUAL(ticker_5.ticks(),0);\n\tBOOST_CHECK_EQUAL(ticker_15.ticks(),0);\n\n\tm.mark(5);\n\n\tBOOST_CHECK_EQUAL(ticker_1.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_5.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_15.count(),0);\n\tBOOST_CHECK_EQUAL(ticker_1.ticks(),0);\n\tBOOST_CHECK_EQUAL(ticker_5.ticks(),0);\n\tBOOST_CHECK_EQUAL(ticker_15.ticks(),0);\n\n\tmock::clock::set_time(5);\n\t\n\t// regardless of implementation\n\t// getting the latest value\n\t// has to flush ticks\n\tdouble r = m.one_minute_rate();\n\n\tBOOST_CHECK_EQUAL(ticker_1.count(),5);\n\tBOOST_CHECK_EQUAL(ticker_5.count(),5);\n\tBOOST_CHECK_EQUAL(ticker_15.count(),5);\n\tBOOST_CHECK_EQUAL(ticker_1.ticks(),1);\n\tBOOST_CHECK_EQUAL(ticker_5.ticks(),1);\n\tBOOST_CHECK_EQUAL(ticker_15.ticks(),1);\n\n\tm.mark(95);\n\tmock::clock::set_time(100);\n\n\tr = m.fifteen_minute_rate();\n\n\n\tBOOST_CHECK_EQUAL(ticker_1.count(),100);\n\tBOOST_CHECK_EQUAL(ticker_5.count(),100);\n\tBOOST_CHECK_EQUAL(ticker_15.count(),100);\n\tBOOST_CHECK_EQUAL(ticker_1.ticks(),20);\n\tBOOST_CHECK_EQUAL(ticker_5.ticks(),20);\n\tBOOST_CHECK_EQUAL(ticker_15.ticks(),20);\n\n\tmock::clock::set_time(104);\n\tm.mark(1);\n\tmock::clock::set_time(105);\n\tm.mark(1);\n\tr = m.fifteen_minute_rate();\n\n\t// test the extra unit didn't get included in the previous interval\n\tBOOST_CHECK_EQUAL(ticker_1.count(),101);\n\tBOOST_CHECK_EQUAL(ticker_5.count(),101);\n\tBOOST_CHECK_EQUAL(ticker_15.count(),101);\n\tBOOST_CHECK_EQUAL(ticker_1.ticks(),21);\n\tBOOST_CHECK_EQUAL(ticker_5.ticks(),21);\n\tBOOST_CHECK_EQUAL(ticker_15.ticks(),21);\n\n\tmock::clock::set_time(110);\n\tr = m.fifteen_minute_rate();\n\n\t// test the extra unit didn't get forgotten\n\tBOOST_CHECK_EQUAL(ticker_1.count(), 102);\n\tBOOST_CHECK_EQUAL(ticker_5.count(), 102);\n\tBOOST_CHECK_EQUAL(ticker_15.count(), 102);\n\tBOOST_CHECK_EQUAL(ticker_1.ticks(), 22);\n\tBOOST_CHECK_EQUAL(ticker_5.ticks(), 22);\n\tBOOST_CHECK_EQUAL(ticker_15.ticks(), 22);\n\n\n\n}\n\nBOOST_AUTO_TEST_CASE(meter_ewma_test){\n\tmock::clock::set_time(0);\n\tmetrics::instruments::clocked_meter<mock::clock> m;\n\t// mean_rate returns nan\n\t// is this good? It's accurate.\n\t//BOOST_CHECK_EQUAL(m.mean_rate(),0);\n\t//BOOST_CHECK_EQUAL(m.one_minute_rate(),0);\n\t//BOOST_CHECK_EQUAL(m.five_minute_rate(),0);\n\t//BOOST_CHECK_EQUAL(m.fifteen_minute_rate(),0);\n\n\tmock::clock::set_time(1);\n\tBOOST_CHECK_EQUAL(m.mean_rate(),0);\n\tBOOST_CHECK_EQUAL(m.one_minute_rate(),0);\n\tBOOST_CHECK_EQUAL(m.five_minute_rate(),0);\n\tBOOST_CHECK_EQUAL(m.fifteen_minute_rate(),0);\n\n\tbool terminate = false;\n\tauto force_count = [&terminate,&m](std::atomic<int>& time){\n\t\twhile(!terminate){\n\t\t\tint local_time = mock::clock::time();\n\t\t\tif(time != local_time){\n\t\t\t\tint diff = local_time - time;\n\t\t\t\tm.mark(5 * diff);\n\t\t\t\ttime = (int)local_time;\n\t\t\t}\n\t\t}\n\t};\n\n\tstd::atomic<int> time_0((int)mock::clock::time());\n\tstd::atomic<int> time_1((int)mock::clock::time());\n\n\tstd::thread marker_0(force_count,std::ref(time_0));\n\tstd::thread marker_1(force_count,std::ref(time_1));\n\n\tBOOST_CHECK_EQUAL(m.count(),0);\n\tBOOST_CHECK_EQUAL(m.mean_rate(),0);\n\tBOOST_CHECK_EQUAL(m.one_minute_rate(),0);\n\tBOOST_CHECK_EQUAL(m.five_minute_rate(),0);\n\tBOOST_CHECK_EQUAL(m.fifteen_minute_rate(),0);\n\n\tmock::clock::set_time(2);\n\n\tauto verify_2= [&time_0,&time_1]()->bool{\n\t\t\treturn (time_0 == 2) && (time_1 == 2);\n\t};\n\n\tauto verify_4 = [&time_0,&time_1]()->bool{\n\t\t\treturn (time_0 == 4) && (time_1 == 4);\n\t};\n\n\twait_for(verify_2);\n\n\tBOOST_CHECK_EQUAL(m.count(),10);\n\tBOOST_CHECK_EQUAL(m.mean_rate(),10 / mock::clock::time());\n\tBOOST_CHECK_EQUAL(m.one_minute_rate(),0);\n\tBOOST_CHECK_EQUAL(m.five_minute_rate(),0);\n\tBOOST_CHECK_EQUAL(m.fifteen_minute_rate(),0);\n\n\n\tmock::clock::set_time(4);\n\n\twait_for(verify_4);\n\n\tint count_before_interval = m.count();\n\tBOOST_CHECK_EQUAL(count_before_interval,30);\n\tterminate = true;\n\n\n\tmarker_0.join();\n\tmarker_1.join();\n\n\tmock::clock::set_time(5);\n\n\tBOOST_CHECK_EQUAL(time_0, 4);\n\tBOOST_CHECK_EQUAL(time_1, 4);\n\tBOOST_CHECK_EQUAL(m.count(), count_before_interval);\n\tBOOST_CHECK_EQUAL(mock::clock::time(), 5);\n\tBOOST_CHECK_EQUAL(m.mean_rate(), count_before_interval / (double)mock::clock::time());\n\tBOOST_CHECK_EQUAL(m.one_minute_rate(),(count_before_interval / mock::clock::time()) * 60);\n\tBOOST_CHECK_EQUAL(m.five_minute_rate(),(count_before_interval / mock::clock::time()) * 60);\n\tBOOST_CHECK_EQUAL(m.fifteen_minute_rate(),(count_before_interval / mock::clock::time()) * 60);\n\n\n}\n", "meta": {"hexsha": "9c257ac5b286196ebc2642fa12b0f86294a3a367", "size": 7571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/meter_test.cpp", "max_stars_repo_name": "andrew-murray/cpp-metrics", "max_stars_repo_head_hexsha": "9d126227b825c561fab5db79b01f267bd0ea9412", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T00:49:23.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-31T00:49:23.000Z", "max_issues_repo_path": "test/meter_test.cpp", "max_issues_repo_name": "andrew-murray/cpp-metrics", "max_issues_repo_head_hexsha": "9d126227b825c561fab5db79b01f267bd0ea9412", "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/meter_test.cpp", "max_forks_repo_name": "andrew-murray/cpp-metrics", "max_forks_repo_head_hexsha": "9d126227b825c561fab5db79b01f267bd0ea9412", "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.8345588235, "max_line_length": 95, "alphanum_fraction": 0.7219653943, "num_tokens": 2086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.18432006893085828}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/xray/each_hkl_gradients_direct.h>\n#include <boost/python/class.hpp>\n\nnamespace cctbx { namespace xray { namespace structure_factors {\nnamespace boost_python {\n\nnamespace {\n\n  struct each_hkl_gradients_direct_wrappers\n  {\n    typedef each_hkl_gradients_direct<> w_t;\n    typedef w_t::scatterer_type scatterer_type;\n    typedef w_t::float_type float_type;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"each_hkl_gradients_direct\", no_init)\n        .def(init<uctbx::unit_cell const&,\n                  sgtbx::space_group const&,\n                  af::const_ref<miller::index<> > const&,\n                  af::const_ref<scatterer_type> const&,\n                  af::const_ref<float_type> const&,\n                  scattering_type_registry const&,\n                  sgtbx::site_symmetry_table const&,\n                  std::size_t>())\n        .def(init<math::cos_sin_table<double> const&,\n                  uctbx::unit_cell const&,\n                  sgtbx::space_group const&,\n                  af::const_ref<miller::index<> > const&,\n                  af::const_ref<scatterer_type> const&,\n                  af::const_ref<float_type> const&,\n                  scattering_type_registry const&,\n                  sgtbx::site_symmetry_table const&,\n                  std::size_t>())\n        .def(\"d_fcalc_d_fp\", &w_t::d_fcalc_d_fp)\n        .def(\"d_fcalc_d_fdp\", &w_t::d_fcalc_d_fdp)\n      ;\n    }\n  };\n\n} // namespace <anoymous>\n\n}} // namespace structure_factors::boost_python\n\nnamespace boost_python {\n\n  void wrap_each_hkl_gradients_direct()\n  {\n    structure_factors::boost_python::each_hkl_gradients_direct_wrappers::wrap();\n  }\n\n}}} // namespace cctbx::xray::boost_python\n", "meta": {"hexsha": "26d9ea65a4b35c7e3b1fd58297e3ddc6659e3bb3", "size": 1772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/xray/boost_python/each_hkl_gradients_direct.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": "cctbx/xray/boost_python/each_hkl_gradients_direct.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": "cctbx/xray/boost_python/each_hkl_gradients_direct.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": 31.0877192982, "max_line_length": 80, "alphanum_fraction": 0.6196388262, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.18431027108894324}}
{"text": "#ifndef BIGGLES_DETAIL_PHYSICS_HPP___\n#define BIGGLES_DETAIL_PHYSICS_HPP___\n\n#include <Eigen/Dense>\n\n#include \"../observation.hpp\"\n\nnamespace biggles { namespace detail\n{\n\n/// @brief This is the default maximum separation of observations to be considered for observations to be neighbours.\nstatic const time_stamp last_delta_t_ = 31;\n\n/// @brief The default maximum separation of observations to be considered for extending a track.\nstatic const time_stamp extend_last_delta_t_ = 2;\n\n/// @brief The default maximum separation of observations to be considered for extending a track.\nstatic const float extend_speed_of_light_ = 1.2f;\n\n/// @brief This is the default speed of light.\n///\n/// @note If this were any other algorithm, specifying a 'default' speed of light would be a bit of a WTF.\nstatic const float speed_of_light_ = 3.f;\n\ninline Eigen::Matrix4f initQ() {\n    Eigen::Matrix4f Q(Eigen::Matrix4f::Zero());\n    Q(0,0) = Q(2,2) = 1e-1f * 1e-1f * speed_of_light_ * speed_of_light_;\n    Q(1,1) = Q(3,3) = 1e-2f * 1e-2f * speed_of_light_ * speed_of_light_;\n    return Q;\n}\n\n\n} }\n\n#endif // BIGGLES_DETAIL_PHYSICS_HPP___\n", "meta": {"hexsha": "3031bc85a23677a1ea7c49ea84e10eecd813f298", "size": 1124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/detail/physics.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/detail/physics.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/detail/physics.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": 31.2222222222, "max_line_length": 117, "alphanum_fraction": 0.7446619217, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.29098086006635987, "lm_q1q2_score": 0.1843102632998377}}
{"text": "// Copyright (c) 2020 The PIVX developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or https://www.opensource.org/licenses/mit-license.php.\n\n#include \"wallet/test/wallet_test_fixture.h\"\n\n#include \"consensus/merkle.h\"\n#include \"primitives/block.h\"\n#include \"random.h\"\n#include \"sapling/note.h\"\n#include \"sapling/noteencryption.h\"\n#include \"sapling/transaction_builder.h\"\n#include \"test/librust/utiltest.h\"\n#include \"wallet/wallet.h\"\n\n#include <boost/filesystem.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nCAmount fee = COIN; // Hardcoded fee\n\nBOOST_FIXTURE_TEST_SUITE(wallet_shielded_balances_tests, WalletTestingSetup)\n\nvoid setupWallet(CWallet& wallet)\n{\n    wallet.SetMinVersion(FEATURE_SAPLING);\n    wallet.SetupSPKM(false);\n}\n\n// Find and set notes data in the tx + add any missing ivk to the wallet's keystore.\nCWalletTx& SetWalletNotesData(CWallet* wallet, CWalletTx& wtx)\n{\n    Optional<mapSaplingNoteData_t> saplingNoteData{nullopt};\n    wallet->FindNotesDataAndAddMissingIVKToKeystore(wtx, saplingNoteData);\n    assert(static_cast<bool>(saplingNoteData));\n    wtx.SetSaplingNoteData(*saplingNoteData);\n    BOOST_CHECK(wallet->AddToWallet(wtx));\n    // Updated tx\n    return wallet->mapWallet[wtx.GetHash()];\n}\n\n/**\n * Creates and send a tx with an input of 'inputAmount' to 'vDest'.\n */\nCWalletTx& AddShieldedBalanceToWallet(const CAmount& inputAmount,\n                                      std::vector<ShieldedDestination> vDest,\n                                      CWallet* wallet,\n                                      const Consensus::Params& consensusParams)\n{\n\n    // Dummy wallet, used to generate the dummy transparent input key and sign it in the transaction builder\n    CWallet dummyWallet;\n    dummyWallet.SetMinVersion(FEATURE_SAPLING);\n    dummyWallet.SetupSPKM(false, true);\n    LOCK(dummyWallet.cs_wallet);\n\n    // Create a transaction shielding balance to 'vDest' and load it to the wallet.\n    CWalletTx wtx = GetValidSaplingReceive(consensusParams, dummyWallet, inputAmount, vDest, wallet);\n\n    // Updated tx after load it to the wallet\n    CWalletTx& wtxUpdated = SetWalletNotesData(wallet, wtx);\n    // Check tx credit now\n    BOOST_CHECK_EQUAL(wtxUpdated.GetCredit(ISMINE_ALL), inputAmount);\n    BOOST_CHECK(wtxUpdated.IsAmountCached(CWalletTx::CREDIT, ISMINE_SPENDABLE_SHIELDED));\n    return wtxUpdated;\n}\n\nCWalletTx& AddShieldedBalanceToWallet(libzcash::SaplingPaymentAddress& sendTo, CAmount amount,\n                                CWallet& wallet, const Consensus::Params& consensusParams,\n                                libzcash::SaplingExtendedSpendingKey& extskOut)\n{\n    // Create a transaction shielding balance to 'sendTo' and load it to the wallet.\n    BOOST_CHECK(wallet.GetSaplingExtendedSpendingKey(sendTo, extskOut));\n    std::vector<ShieldedDestination> vDest;\n    vDest.push_back({extskOut, amount});\n    return AddShieldedBalanceToWallet(amount, vDest, &wallet, consensusParams);\n}\n\nstruct SaplingSpendValues {\n    libzcash::SaplingNote note;\n    const uint256 anchor;\n    const SaplingWitness witness;\n};\n\n/**\n * Update the wallet internally as if the wallet would had received a valid block containing wtx.\n * Then return the note, anchor and witness for any subsequent spending process.\n */\nSaplingSpendValues UpdateWalletInternalNotesData(CWalletTx& wtx, SaplingOutPoint& sapPoint, CWallet& wallet)\n{\n    // Get note\n    SaplingNoteData nd = wtx.mapSaplingNoteData.at(sapPoint);\n    assert(nd.IsMyNote());\n    const auto& ivk = *(nd.ivk);\n    auto maybe_pt = libzcash::SaplingNotePlaintext::decrypt(\n            wtx.sapData->vShieldedOutput[sapPoint.n].encCiphertext,\n            ivk,\n            wtx.sapData->vShieldedOutput[sapPoint.n].ephemeralKey,\n            wtx.sapData->vShieldedOutput[sapPoint.n].cmu);\n    assert(static_cast<bool>(maybe_pt));\n    boost::optional<libzcash::SaplingNotePlaintext> notePlainText = maybe_pt.get();\n    libzcash::SaplingNote note = notePlainText->note(ivk).get();\n\n    // Append note to the tree\n    auto commitment = note.cmu().get();\n    SaplingMerkleTree tree;\n    tree.append(commitment);\n    auto anchor = tree.root();\n    auto witness = tree.witness();\n\n    // Update wtx credit chain data\n    // Pretend we mined the tx by adding a fake witness and nullifier to be able to spend it.\n    wtx.mapSaplingNoteData[sapPoint].witnesses.push_front(tree.witness());\n    wtx.mapSaplingNoteData[sapPoint].witnessHeight = 1;\n    wallet.GetSaplingScriptPubKeyMan()->nWitnessCacheSize = 1;\n    wallet.GetSaplingScriptPubKeyMan()->UpdateSaplingNullifierNoteMapWithTx(wtx);\n    return {note, anchor, witness};\n}\n\n/**\n * Validates:\n * 1) CWalletTx getCredit for shielded credit.\n * Incoming spendable shielded balance must be cached in the cacheableAmounts.\n *\n * 2) CWalletTx getDebit & getCredit for shielded debit to transparent address.\n * Same wallet as point (1), spending half of the credit received in (1) to a transparent remote address.\n * The other half of the balance - minus fee - must appear as credit (shielded change).\n *\n */\nBOOST_AUTO_TEST_CASE(GetShieldedSimpleCachedCreditAndDebit)\n{\n\n    ///////////////////////\n    //////// Credit ////////\n    ///////////////////////\n\n    auto consensusParams = RegtestActivateSapling();\n\n    // Main wallet\n    CWallet &wallet = *pwalletMain;\n    LOCK2(cs_main, wallet.cs_wallet);\n    setupWallet(wallet);\n\n    // First generate a shielded address\n    libzcash::SaplingPaymentAddress pa = wallet.GenerateNewSaplingZKey();\n    CAmount firstCredit = COIN * 10;\n\n    // Add shielded balance.\n    libzcash::SaplingExtendedSpendingKey extskOut;\n    CWalletTx& wtxUpdated = AddShieldedBalanceToWallet(pa, firstCredit, wallet, consensusParams, extskOut);\n\n    ///////////////////////\n    //////// Debit ////////\n    ///////////////////////\n\n    // Update transaction and wallet internal state to be able to spend it.\n    SaplingOutPoint sapPoint {wtxUpdated.GetHash(), 0};\n    SaplingSpendValues sapSpendValues = UpdateWalletInternalNotesData(wtxUpdated, sapPoint, wallet);\n\n    // Debit value\n    CAmount firstDebit = COIN * 5;\n    CAmount firstDebitShieldedChange = firstDebit - fee;\n\n    // Create the spending transaction\n    auto builder = TransactionBuilder(consensusParams, 1, &wallet);\n    builder.SetFee(fee);\n    builder.AddSaplingSpend(\n            extskOut.expsk,\n            sapSpendValues.note,\n            sapSpendValues.anchor,\n            sapSpendValues.witness);\n\n    // Send to transparent address\n    builder.AddTransparentOutput(CreateDummyDestinationScript(),\n                                 firstDebit);\n\n    CTransaction tx = builder.Build().GetTxOrThrow();\n    // add tx to wallet and update it.\n    wallet.AddToWallet({&wallet, tx});\n    CWalletTx& wtxDebit = wallet.mapWallet[tx.GetHash()];\n    // Update tx notes data (shielded change need it)\n    CWalletTx& wtxDebitUpdated = SetWalletNotesData(&wallet, wtxDebit);\n\n    // The debit need to be the entire first note value\n    BOOST_CHECK_EQUAL(wtxDebitUpdated.GetDebit(ISMINE_ALL), firstCredit);\n    BOOST_CHECK(wtxDebitUpdated.IsAmountCached(CWalletTx::DEBIT, ISMINE_SPENDABLE_SHIELDED));\n    // The credit should be only the change.\n    BOOST_CHECK_EQUAL(wtxDebitUpdated.GetCredit(ISMINE_ALL), firstDebitShieldedChange);\n    BOOST_CHECK(wtxDebitUpdated.IsAmountCached(CWalletTx::CREDIT, ISMINE_SPENDABLE_SHIELDED));\n\n    // Checks that the only shielded output of this tx is change.\n    BOOST_CHECK(wallet.GetSaplingScriptPubKeyMan()->IsNoteSaplingChange(\n            SaplingOutPoint(wtxDebitUpdated.GetHash(), 0), pa));\n\n    // Revert to default\n    RegtestDeactivateSapling();\n}\n\nlibzcash::SaplingPaymentAddress getNewDummyShieldedAddress()\n{\n    HDSeed seed;\n    auto m = libzcash::SaplingExtendedSpendingKey::Master(seed);\n    return m.DefaultAddress();\n}\n\nCWalletTx& buildTxAndLoadToWallet(CWallet& wallet, libzcash::SaplingExtendedSpendingKey extskOut,\n                                  const SaplingSpendValues& sapSpendValues, libzcash::SaplingPaymentAddress dest,\n                                  const CAmount& destAmount, const Consensus::Params& consensus)\n{\n    // Create the spending transaction\n    auto builder = TransactionBuilder(consensus, 1, &wallet);\n    builder.SetFee(fee);\n    builder.AddSaplingSpend(\n            extskOut.expsk,\n            sapSpendValues.note,\n            sapSpendValues.anchor,\n            sapSpendValues.witness);\n\n    // Send to shielded address\n    builder.AddSaplingOutput(\n            extskOut.expsk.ovk,\n            dest,\n            destAmount,\n            {}\n    );\n\n    CTransaction tx = builder.Build().GetTxOrThrow();\n    // add tx to wallet and update it.\n    wallet.AddToWallet({&wallet, tx});\n    CWalletTx& wtx = wallet.mapWallet[tx.GetHash()];\n    // Update tx notes data and return the updated wtx.\n    return SetWalletNotesData(&wallet, wtx);\n}\n\n/**\n * Validates shielded to remote shielded + change cached balances.\n */\nBOOST_AUTO_TEST_CASE(VerifyShieldedToRemoteShieldedCachedBalance)\n{\n    auto consensusParams = RegtestActivateSapling();\n\n    // Main wallet\n    CWallet &wallet = *pwalletMain;\n    LOCK2(cs_main, wallet.cs_wallet);\n    setupWallet(wallet);\n\n    // First generate a shielded address\n    libzcash::SaplingPaymentAddress pa = wallet.GenerateNewSaplingZKey();\n    CAmount firstCredit = COIN * 20;\n\n    // Add shielded balance.\n    libzcash::SaplingExtendedSpendingKey extskOut;\n    CWalletTx& wtxUpdated = AddShieldedBalanceToWallet(pa, firstCredit, wallet, consensusParams, extskOut);\n\n    // Update transaction and wallet internal state to be able to spend it.\n    SaplingOutPoint sapPoint {wtxUpdated.GetHash(), 0};\n    SaplingSpendValues sapSpendValues = UpdateWalletInternalNotesData(wtxUpdated, sapPoint, wallet);\n\n    // Remote destination values\n    libzcash::SaplingPaymentAddress destShieldedAddress = getNewDummyShieldedAddress();\n    CAmount destAmount = COIN * 8;\n\n    // Create the spending transaction and load it to the wallet\n    CWalletTx& wtxDebitUpdated = buildTxAndLoadToWallet(wallet,\n                           extskOut,\n                           sapSpendValues,\n                           destShieldedAddress,\n                           destAmount,\n                           consensusParams);\n\n    // Validate results\n    CAmount expectedShieldedChange = firstCredit - destAmount - fee;\n\n    // The debit need to be the entire first note value\n    BOOST_CHECK_EQUAL(wtxDebitUpdated.GetDebit(ISMINE_ALL), firstCredit);\n    BOOST_CHECK(wtxDebitUpdated.IsAmountCached(CWalletTx::DEBIT, ISMINE_SPENDABLE_SHIELDED));\n    // The credit should be only the change.\n    BOOST_CHECK_EQUAL(wtxDebitUpdated.GetCredit(ISMINE_ALL), expectedShieldedChange);\n    BOOST_CHECK(wtxDebitUpdated.IsAmountCached(CWalletTx::CREDIT, ISMINE_SPENDABLE_SHIELDED));\n    // Plus, change should be same and be cached as well\n    BOOST_CHECK_EQUAL(wtxDebitUpdated.GetShieldedChange(), expectedShieldedChange);\n    BOOST_CHECK(wtxDebitUpdated.fShieldedChangeCached);\n\n    // Revert to default\n    RegtestDeactivateSapling();\n}\n\nstruct FakeBlock\n{\n    CBlock block;\n    CBlockIndex* pindex;\n};\n\nFakeBlock SimpleFakeMine(CWalletTx& wtx, SaplingMerkleTree& currentTree)\n{\n    FakeBlock fakeBlock;\n    fakeBlock.block.nVersion = 8;\n    fakeBlock.block.vtx.emplace_back(MakeTransactionRef(wtx));\n    fakeBlock.block.hashMerkleRoot = BlockMerkleRoot(fakeBlock.block);\n    for (const OutputDescription& out : wtx.sapData->vShieldedOutput) {\n        currentTree.append(out.cmu);\n    }\n    fakeBlock.block.hashFinalSaplingRoot = currentTree.root();\n    fakeBlock.pindex = new CBlockIndex(fakeBlock.block);\n    mapBlockIndex.insert(std::make_pair(fakeBlock.block.GetHash(), fakeBlock.pindex));\n    fakeBlock.pindex->phashBlock = &mapBlockIndex.find(fakeBlock.block.GetHash())->first;\n    chainActive.SetTip(fakeBlock.pindex);\n    BOOST_CHECK(chainActive.Contains(fakeBlock.pindex));\n    wtx.SetMerkleBranch(fakeBlock.pindex->GetBlockHash(), 0);\n    return fakeBlock;\n}\n\n/**\n * Test:\n * 1) receive two shielded notes on the same tx.\n * 2) check available credit.\n * 3) spend one of them.\n * 4) force available credit cache recalculation and validate the updated amount.\n */\nBOOST_AUTO_TEST_CASE(GetShieldedAvailableCredit)\n{\n    auto consensusParams = RegtestActivateSapling();\n\n    // Main wallet\n    CWallet &wallet = *pwalletMain;\n    LOCK2(cs_main, wallet.cs_wallet);\n    setupWallet(wallet);\n\n    // 1) generate a shielded address and send 20 NOMD in two shielded outputs\n    libzcash::SaplingPaymentAddress pa = wallet.GenerateNewSaplingZKey();\n    CAmount credit = COIN * 20;\n\n    // Add two equal shielded outputs.\n    libzcash::SaplingExtendedSpendingKey extskOut;\n    BOOST_CHECK(wallet.GetSaplingExtendedSpendingKey(pa, extskOut));\n\n    std::vector<ShieldedDestination> vDest;\n    vDest.push_back({extskOut, credit / 2});\n    vDest.push_back({extskOut, credit / 2});\n    CWalletTx& wtxUpdated = AddShieldedBalanceToWallet(credit, vDest, &wallet, consensusParams);\n\n    // Available credit ISMINE_SPENDABLE must be 0\n    // Available credit ISMINE_SHIELDED_SPENDABLE must be 'credit' and be cached.\n    BOOST_CHECK_EQUAL(wtxUpdated.GetAvailableCredit(true, ISMINE_SPENDABLE), 0);\n    BOOST_CHECK_EQUAL(wtxUpdated.GetShieldedAvailableCredit(), credit);\n    BOOST_CHECK(wtxUpdated.IsAmountCached(CWalletTx::AVAILABLE_CREDIT, ISMINE_SPENDABLE_SHIELDED));\n\n    // 2) Confirm the tx\n    SaplingMerkleTree tree;\n    FakeBlock fakeBlock = SimpleFakeMine(wtxUpdated, tree);\n    wallet.ChainTip(fakeBlock.pindex, &fakeBlock.block, tree);\n    wtxUpdated = wallet.mapWallet[wtxUpdated.GetHash()];\n\n    // 3) Now can spend one output and recalculate the shielded credit.\n    std::vector<SaplingNoteEntry> saplingEntries;\n    Optional<libzcash::SaplingPaymentAddress> opPa(pa);\n    wallet.GetSaplingScriptPubKeyMan()->GetFilteredNotes(saplingEntries,\n                                                         opPa,\n                                                         0);\n\n    std::vector<SaplingOutPoint> ops = {saplingEntries[0].op};\n    uint256 anchor;\n    std::vector<boost::optional<SaplingWitness>> witnesses;\n    pwalletMain->GetSaplingScriptPubKeyMan()->GetSaplingNoteWitnesses(ops, witnesses, anchor);\n    SaplingSpendValues sapSpendValues{saplingEntries[0].note, anchor, *witnesses[0]};\n\n    // Remote destination values\n    libzcash::SaplingPaymentAddress destShieldedAddress = getNewDummyShieldedAddress();\n    CAmount change = COIN * 1;\n    CAmount destAmount = credit / 2 - fee - change; // one note - fee\n\n    // Create the spending transaction and load it to the wallet\n    CWalletTx& wtxDebitUpdated = buildTxAndLoadToWallet(wallet,\n                                                        extskOut,\n                                                        sapSpendValues,\n                                                        destShieldedAddress,\n                                                        destAmount,\n                                                        consensusParams);\n\n    // Check previous credit tx balance being the same and then force a recalculation\n    BOOST_CHECK_EQUAL(wtxUpdated.GetShieldedAvailableCredit(), credit);\n    BOOST_CHECK_EQUAL(wtxUpdated.GetShieldedAvailableCredit(false), credit / 2);\n    BOOST_CHECK_EQUAL(wtxUpdated.GetShieldedChange(), 0);\n\n    // Now check the debit tx\n    BOOST_CHECK_EQUAL(wtxDebitUpdated.GetDebit(ISMINE_SPENDABLE_SHIELDED), credit / 2);\n    BOOST_CHECK_EQUAL(wtxDebitUpdated.GetShieldedChange(), change);\n    BOOST_CHECK_EQUAL(wtxDebitUpdated.GetCredit(ISMINE_SPENDABLE_SHIELDED), change);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c8f21f71732c801e85dc89ff8148ee5e143d7693", "size": 15628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wallet/test/wallet_shielded_balances_tests.cpp", "max_stars_repo_name": "Nomadic-Official/nomadic-nomd-coin", "max_stars_repo_head_hexsha": "e9f758e5d43b9024c1ef876c2888934be08d4edd", "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/wallet/test/wallet_shielded_balances_tests.cpp", "max_issues_repo_name": "Nomadic-Official/nomadic-nomd-coin", "max_issues_repo_head_hexsha": "e9f758e5d43b9024c1ef876c2888934be08d4edd", "max_issues_repo_licenses": ["MIT"], "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/wallet/test/wallet_shielded_balances_tests.cpp", "max_forks_repo_name": "Nomadic-Official/nomadic-nomd-coin", "max_forks_repo_head_hexsha": "e9f758e5d43b9024c1ef876c2888934be08d4edd", "max_forks_repo_licenses": ["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.8673469388, "max_line_length": 113, "alphanum_fraction": 0.7011133862, "num_tokens": 3867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.3345894346180164, "lm_q1q2_score": 0.18422741206564627}}
{"text": "#include \"domains/team_comp_sar.h\"\n#include <math.h>\n#include <stdlib.h>\n#include \"plan_trace.h\"\n#include \"plangrapher.h\"\n#include <istream>\n#include <nlohmann/json.hpp>\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nusing json = nlohmann::json;\n\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n  int R = 30;\n  double e = 0.4;\n  double alpha = 0.5;\n  int aux_R = 10;\n  std::string map_json = \"../apps/data_parsing/Saturn_map_info.json\";\n  std::string cpm_json;\n  try {\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"resource_cycles,R\", po::value<int>(), \"Number of resource cycles allowed for each search action (int)\")\n      (\"exp_param,e\",po::value<double>(),\"The exploration parameter for the planner (double)\")\n      (\"alpha,a\", po::value<double>(), \"default frequency measure for missing conditional probabilities in CFM (default)\")\n      (\"map_json,m\", po::value<std::string>(),\"json file with map data (string)\")\n      (\"cpm_json,j\",po::value<std::string>(),\"json file to parse CPM (string)\")\n      (\"aux_r,a\", po::value<int>(), \"Auxiliary resources for bad expansions (int)\")\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      std::cout << desc << std::endl;\n      return 0;\n    }\n\n    if (vm.count(\"resource_cycles\")) {\n      R = vm[\"resource_cycles\"].as<int>();\n    }\n\n    if (vm.count(\"exp_param\")) {\n      e = vm[\"exp_param\"].as<double>();\n    }\n\n    if (vm.count(\"alpha\")) {\n      alpha = vm[\"alpha\"].as<double>();\n    }\n\n    if (vm.count(\"aux_r\")) {\n      aux_R = vm[\"aux_r\"].as<int>();\n    }\n\n    if (vm.count(\"cpm_json\")) {\n      cpm_json = vm[\"cpm_json\"].as<std::string>();\n    }\n\n    if (vm.count(\"map_json\")) {\n      map_json = vm[\"map_json\"].as<std::string>();\n    }\n  }\n  catch(std::exception& e) {\n    std::cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n  catch(...) {\n    std::cerr << \"Exception of unknown type!\\n\";\n  }\n\n    std::ifstream f(map_json);\n    json g;\n    f >> g;\n  \n    auto state1 = TeamSARState();\n    std::string agent1 = \"A1\";\n    std::string agent2 = \"A2\";\n    std::string agent3 = \"A3\";\n    state1.agents.push_back(agent1);\n    state1.agents.push_back(agent2);\n    state1.agents.push_back(agent3);\n    \n    state1.class_only_boundary = \"el\";\n    state1.change_zone = g[\"change_zone\"].get<std::string>();\n    for (auto& nvz : g[\"no_victim_zones\"]) {\n      state1.no_victim_zones.push_back(nvz.get<std::string>());\n    }\n    for (auto& mrz : g[\"multi_room_zones\"]) {\n      state1.multi_room_zones.push_back(mrz.get<std::string>());\n    }\n    for (auto& z : g[\"zones\"]) {\n      state1.zones.push_back(z.get<std::string>());\n    }\n    \n    for (auto& [l,vl] : g[\"graph\"].items()) {\n      for (auto& c : vl) {\n        state1.graph[l].push_back(c.get<std::string>()); \n      }\n    }\n\n    for (auto& [d,di] : g[\"dist_from_change_zone\"].items()) {\n        state1.dist_from_change_zone[d] = di.get<int>();\n    }\n\n    for (auto& mrz : g[\"multi_room_zones\"]) {\n      state1.multi_room_zones.push_back(mrz.get<std::string>());\n    }\n    for (auto& r : g[\"rooms\"]) {\n      state1.rooms.push_back(r.get<std::string>());\n    }\n\n\n    for (auto a : state1.agents) {\n      state1.role[a] = \"NONE\";\n\n      state1.agent_loc[a] = state1.change_zone;\n\n      state1.holding[a] = false;\n\n      state1.time[a] = 0;\n\n      state1.loc_tracker[a] = {};\n\n      state1.action_tracker[a] = {};\n\n      for (auto s : state1.zones) {\n        if (s == state1.change_zone) {\n          state1.visited[a][s] = 1;\n        }\n        else {\n          state1.visited[a][s] = 0;\n        }\n      }\n    }\n    \n    for (auto s : state1.zones) {\n      state1.blocks_broken[s] = 0;\n\n      state1.r_triaged_here[s] = false;\n\n      state1.c_triaged_here[s] = false;\n\n      state1.c_awake[s] = false;\n\n    }\n\n    state1.c_triage_total = 0;\n\n    state1.r_triage_total = 0;\n\n    state1.c_max = 5;\n    state1.r_max = 50;\n\n    auto domain = TeamSARDomain();\n    \n    CPM cpm = {};\n\n    if (cpm_json != \"\") {\n      std::ifstream i(cpm_json); \n      json j;\n      i >> j;\n      for (auto& [k1, v1] : j.items()) {\n        for (auto& [k2,v2] : v1.items()) {\n          for (auto& [k3, v3] : v2.items()) {\n            cpm[k1][k2][k3] = v3;\n          }\n        }\n      }\n    }\n\n    Tasks tasks = {\n        {Task(\"SAR\", Args({{\"agent3\", agent3},{\"agent2\", agent2},{\"agent1\",agent1}}),{\"agent1\",\"agent2\",\"agent3\"},{agent1,agent2,agent3})}};\n    auto pt = cppMCTShop(state1, tasks, domain, cpm,R,e,alpha,4021,aux_R);\n\n    json j_tree = generate_plan_trace_tree(pt.first,pt.second,true,\"team_comp_sar_trace_tree.json\");\n    generate_graph_from_json(j_tree, \"team_comp_sar_tree_graph.png\");\n    generate_plan_trace(pt.first,pt.second,true,\"team_comp_sar_trace.json\");\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "1c243c76bc93ec44148c7103e32ca396e87a108b", "size": 4904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/planners/team_comp_sar_MCTS_planner.cpp", "max_stars_repo_name": "ml4ai/tomcat-planrec", "max_stars_repo_head_hexsha": "70af6464851c641eb414fd1c818cfb5b1351e079", "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": "apps/planners/team_comp_sar_MCTS_planner.cpp", "max_issues_repo_name": "ml4ai/tomcat-planrec", "max_issues_repo_head_hexsha": "70af6464851c641eb414fd1c818cfb5b1351e079", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-06-17T15:21:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-18T20:20:07.000Z", "max_forks_repo_path": "apps/planners/team_comp_sar_MCTS_planner.cpp", "max_forks_repo_name": "ml4ai/tomcat-planrec", "max_forks_repo_head_hexsha": "70af6464851c641eb414fd1c818cfb5b1351e079", "max_forks_repo_licenses": ["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.652173913, "max_line_length": 140, "alphanum_fraction": 0.5758564437, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.18422740584962996}}
{"text": "#include <boost/python/class.hpp>\n#include <boost/python/enum.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/return_by_value.hpp>\n#include <boost/python/return_internal_reference.hpp>\n\n#include <scitbx/array_family/boost_python/shared_wrapper.h>\n\n\n#include <cctbx/miller/amplitude_normalisation.h>\n\nnamespace cctbx { namespace miller { namespace boost_python {\n\n  template <typename FloatType>\n  struct amplitude_normalisation_wrapper\n  {\n    typedef amplitude_normalisation<FloatType> wt;\n    typedef typename wt::float_type float_type;\n\n    static void wrap() {\n      using namespace boost::python;\n      return_value_policy<return_by_value> rbv;\n      typedef return_internal_reference<> rir;\n\n      af::boost_python::shared_wrapper<\n        typename wt::form_factor_t, rir>::wrap(\n        \"shared_gaussian_form_factors\");\n\n      class_<wt>(\"amplitude_normalisation\", no_init)\n        .def(init<af::const_ref<typename wt::form_factor_t> const &,\n                  af::const_ref<float_type> const &,\n                  float_type,\n                  float_type,\n                  uctbx::unit_cell const &,\n                  sgtbx::space_group const &,\n                  af::const_ref<index<> > const &>(\n              (arg(\"form_factors\"),\n               arg(\"multiplicities\"),\n               arg(\"wilson_intensity_scale_factor\"),\n               arg(\"wilson_b\"),\n               arg(\"unit_cell\"),\n               arg(\"space_group\"),\n               arg(\"indices\"))))\n        .add_property(\"normalisations\", make_getter(&wt::normalisations, rbv))\n        ;\n    }\n  };\n\n  void wrap_amplitude_normalisation() {\n    amplitude_normalisation_wrapper<double>::wrap();\n  }\n}}} // cctbx::miller::boostpython\n", "meta": {"hexsha": "86f1078b1451a6770cf0e6c23692417b6f63687f", "size": 1758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/miller/boost_python/amplitude_normalisation.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": "cctbx/miller/boost_python/amplitude_normalisation.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": "cctbx/miller/boost_python/amplitude_normalisation.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": 32.5555555556, "max_line_length": 78, "alphanum_fraction": 0.6439135381, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.18422740347757838}}
{"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 <ored/model/crossassetmodelbuilder.hpp>\n#include <ored/model/eqbsbuilder.hpp>\n#include <ored/model/fxbsbuilder.hpp>\n#include <ored/model/infdkbuilder.hpp>\n#include <ored/model/lgmbuilder.hpp>\n#include <ored/model/utilities.hpp>\n#include <ored/utilities/correlationmatrix.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n\n#include <qle/models/fxbsconstantparametrization.hpp>\n#include <qle/models/fxbspiecewiseconstantparametrization.hpp>\n#include <qle/models/fxeqoptionhelper.hpp>\n#include <qle/models/irlgm1fconstantparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiseconstanthullwhiteadaptor.hpp>\n#include <qle/models/irlgm1fpiecewiseconstantparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiselinearparametrization.hpp>\n#include <qle/pricingengines/analyticcclgmfxoptionengine.hpp>\n#include <qle/pricingengines/analyticdkcpicapfloorengine.hpp>\n#include <qle/pricingengines/analyticlgmswaptionengine.hpp>\n#include <qle/pricingengines/analyticxassetlgmeqoptionengine.hpp>\n\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/utilities/dataformatters.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/lexical_cast.hpp>\n\nnamespace ore {\nnamespace data {\n\nCrossAssetModelBuilder::CrossAssetModelBuilder(const boost::shared_ptr<ore::data::Market>& market,\n                                               const std::string& configurationLgmCalibration,\n                                               const std::string& configurationFxCalibration,\n                                               const std::string& configurationEqCalibration,\n                                               const std::string& configurationInfCalibration,\n                                               const std::string& configurationFinalModel, const DayCounter& dayCounter)\n    : market_(market), configurationLgmCalibration_(configurationLgmCalibration),\n      configurationFxCalibration_(configurationFxCalibration), configurationEqCalibration_(configurationEqCalibration),\n      configurationInfCalibration_(configurationInfCalibration), configurationFinalModel_(configurationFinalModel),\n      dayCounter_(dayCounter),\n      optimizationMethod_(boost::shared_ptr<OptimizationMethod>(new LevenbergMarquardt(1E-8, 1E-8, 1E-8))),\n      endCriteria_(EndCriteria(1000, 500, 1E-8, 1E-8, 1E-8)) {\n    QL_REQUIRE(market != NULL, \"CrossAssetModelBuilder: no market given\");\n}\n\nboost::shared_ptr<QuantExt::CrossAssetModel>\nCrossAssetModelBuilder::build(const boost::shared_ptr<CrossAssetModelData>& config) {\n\n    LOG(\"Start building CrossAssetModel, configurations: LgmCalibration \"\n        << configurationLgmCalibration_ << \", FxCalibration \" << configurationFxCalibration_ << \", EqCalibration \"\n        << configurationEqCalibration_ << \", InfCalibration \" << configurationInfCalibration_ << \", FinalModel \"\n        << configurationFinalModel_);\n\n    QL_REQUIRE(config->irConfigs().size() > 0, \"missing IR configurations\");\n    QL_REQUIRE(config->irConfigs().size() == config->fxConfigs().size() + 1,\n               \"FX configuration size \" << config->fxConfigs().size() << \" inconsisitent with IR configuration size \"\n                                        << config->irConfigs().size());\n\n    swaptionBaskets_.resize(config->irConfigs().size());\n    optionExpiries_.resize(config->irConfigs().size());\n    swaptionMaturities_.resize(config->irConfigs().size());\n    swaptionCalibrationErrors_.resize(config->irConfigs().size());\n    fxOptionBaskets_.resize(config->fxConfigs().size());\n    fxOptionExpiries_.resize(config->fxConfigs().size());\n    fxOptionCalibrationErrors_.resize(config->fxConfigs().size());\n    eqOptionBaskets_.resize(config->eqConfigs().size());\n    eqOptionExpiries_.resize(config->eqConfigs().size());\n    eqOptionCalibrationErrors_.resize(config->eqConfigs().size());\n    infCapFloorBaskets_.resize(config->infConfigs().size());\n    infCapFloorExpiries_.resize(config->infConfigs().size());\n    infCapFloorCalibrationErrors_.resize(config->infConfigs().size());\n\n    /*******************************************************\n     * Build the IR parametrizations and calibration baskets\n     */\n    std::vector<boost::shared_ptr<QuantExt::IrLgm1fParametrization>> irParametrizations;\n    std::vector<RelinkableHandle<YieldTermStructure>> irDiscountCurves;\n    std::vector<std::string> currencies, regions, crNames, eqNames, infIndices;\n    std::vector<boost::shared_ptr<LgmBuilder>> irBuilder;\n\n    for (Size i = 0; i < config->irConfigs().size(); i++) {\n        boost::shared_ptr<IrLgmData> ir = config->irConfigs()[i];\n        LOG(\"IR Parametrization \" << i << \" ccy \" << ir->ccy());\n        boost::shared_ptr<LgmBuilder> builder =\n            boost::make_shared<LgmBuilder>(market_, ir, configurationLgmCalibration_, config->bootstrapTolerance());\n        irBuilder.push_back(builder);\n        boost::shared_ptr<QuantExt::IrLgm1fParametrization> parametrization = builder->parametrization();\n        swaptionBaskets_[i] = builder->swaptionBasket();\n        currencies.push_back(ir->ccy());\n        irParametrizations.push_back(parametrization);\n        irDiscountCurves.push_back(builder->discountCurve());\n    }\n\n    QL_REQUIRE(irParametrizations.size() > 0, \"missing IR parametrizations\");\n\n    QuantLib::Currency domesticCcy = irParametrizations[0]->currency();\n\n    /*******************************************************\n     * Build the FX parametrizations and calibration baskets\n     */\n    std::vector<boost::shared_ptr<QuantExt::FxBsParametrization>> fxParametrizations;\n    for (Size i = 0; i < config->fxConfigs().size(); i++) {\n        LOG(\"FX Parametrization \" << i);\n        boost::shared_ptr<FxBsData> fx = config->fxConfigs()[i];\n        QuantLib::Currency ccy = ore::data::parseCurrency(fx->foreignCcy());\n        QuantLib::Currency domCcy = ore::data::parseCurrency(fx->domesticCcy());\n\n        QL_REQUIRE(ccy.code() == irParametrizations[i + 1]->currency().code(),\n                   \"FX parametrization currency[\" << i << \"]=\" << ccy << \" does not match IR currrency[\" << i + 1\n                                                  << \"]=\" << irParametrizations[i + 1]->currency().code());\n\n        QL_REQUIRE(domCcy == domesticCcy, \"FX parametrization [\" << i << \"]=\" << ccy << \"/\" << domCcy\n                                                                 << \" does not match domestic ccy \" << domesticCcy);\n\n        boost::shared_ptr<FxBsBuilder> builder =\n            boost::make_shared<FxBsBuilder>(market_, fx, configurationFxCalibration_);\n        boost::shared_ptr<QuantExt::FxBsParametrization> parametrization = builder->parametrization();\n\n        fxOptionBaskets_[i] = builder->optionBasket();\n\n        fxParametrizations.push_back(parametrization);\n    }\n\n    /*******************************************************\n     * Build the EQ parametrizations and calibration baskets\n     */\n    std::vector<boost::shared_ptr<QuantExt::EqBsParametrization>> eqParametrizations;\n    for (Size i = 0; i < config->eqConfigs().size(); i++) {\n        LOG(\"EQ Parametrization \" << i);\n        boost::shared_ptr<EqBsData> eq = config->eqConfigs()[i];\n        string eqName = eq->eqName();\n        QuantLib::Currency eqCcy = ore::data::parseCurrency(eq->currency());\n        QL_REQUIRE(std::find(currencies.begin(), currencies.end(), eqCcy.code()) != currencies.end(),\n                   \"Currency (\" << eqCcy << \") for equity \" << eqName << \" not covered by CrossAssetModelData\");\n        boost::shared_ptr<EqBsBuilder> builder =\n            boost::make_shared<EqBsBuilder>(market_, eq, domesticCcy, configurationEqCalibration_);\n        boost::shared_ptr<QuantExt::EqBsParametrization> parametrization = builder->parametrization();\n        eqOptionBaskets_[i] = builder->optionBasket();\n        eqParametrizations.push_back(parametrization);\n        eqNames.push_back(eqName);\n    }\n\n    /*******************************************************\n     * Build the INF parametrizations and calibration baskets\n     */\n    std::vector<boost::shared_ptr<QuantExt::InfDkParametrization>> infParametrizations;\n    for (Size i = 0; i < config->infConfigs().size(); i++) {\n        LOG(\"INF Parametrization \" << i);\n        boost::shared_ptr<InfDkData> inf = config->infConfigs()[i];\n        string infIndex = inf->infIndex();\n        boost::shared_ptr<InfDkBuilder> builder =\n            boost::make_shared<InfDkBuilder>(market_, inf, configurationInfCalibration_);\n        boost::shared_ptr<QuantExt::InfDkParametrization> parametrization = builder->parametrization();\n        infCapFloorBaskets_[i] = builder->optionBasket();\n        infParametrizations.push_back(parametrization);\n        infIndices.push_back(infIndex);\n    }\n\n    std::vector<boost::shared_ptr<QuantExt::Parametrization>> parametrizations;\n    for (Size i = 0; i < irParametrizations.size(); i++)\n        parametrizations.push_back(irParametrizations[i]);\n    for (Size i = 0; i < fxParametrizations.size(); i++)\n        parametrizations.push_back(fxParametrizations[i]);\n    for (Size i = 0; i < eqParametrizations.size(); i++)\n        parametrizations.push_back(eqParametrizations[i]);\n    for (Size i = 0; i < infParametrizations.size(); i++)\n        parametrizations.push_back(infParametrizations[i]);\n\n    QL_REQUIRE(fxParametrizations.size() == irParametrizations.size() - 1, \"mismatch in IR/FX parametrization sizes\");\n\n    /******************************\n     * Build the correlation matrix\n     */\n\n    ore::data::CorrelationMatrixBuilder cmb;\n    for (auto it = config->correlations().begin(); it != config->correlations().end(); it++) {\n        std::string factor1 = it->first.first;\n        std::string factor2 = it->first.second;\n        Real corr = it->second;\n        LOG(\"Add correlation for \" << factor1 << \" \" << factor2);\n        cmb.addCorrelation(factor1, factor2, corr);\n    }\n\n    LOG(\"Get correlation matrix for currencies:\");\n    for (auto c : currencies)\n        LOG(\"Currency \" << c);\n\n    Matrix corrMatrix = cmb.correlationMatrix(currencies, infIndices, crNames, eqNames);\n\n    /*****************************\n     * Build the cross asset model\n     */\n\n    boost::shared_ptr<QuantExt::CrossAssetModel> model =\n        boost::make_shared<QuantExt::CrossAssetModel>(parametrizations, corrMatrix);\n\n    /*************************\n     * Calibrate IR components\n     */\n\n    for (Size i = 0; i < irBuilder.size(); i++) {\n        LOG(\"IR Calibration \" << i);\n        swaptionCalibrationErrors_[i] = irBuilder[i]->error();\n    }\n\n    /*************************\n     * Relink LGM discount curves to curves used for FX calibration\n     */\n\n    for (Size i = 0; i < irParametrizations.size(); i++) {\n        auto p = irParametrizations[i];\n        irDiscountCurves[i].linkTo(*market_->discountCurve(p->currency().code(), configurationFxCalibration_));\n        LOG(\"Relinked discounting curve for \" << p->currency().code() << \" for FX calibration\");\n    }\n\n    /*************************\n     * Calibrate FX components\n     */\n\n    for (Size i = 0; i < fxParametrizations.size(); i++) {\n        boost::shared_ptr<FxBsData> fx = config->fxConfigs()[i];\n\n        if (fx->calibrationType() == CalibrationType::None || !fx->calibrateSigma()) {\n            LOG(\"FX Calibration \" << i << \" skipped\");\n            continue;\n        }\n\n        LOG(\"FX Calibration \" << i);\n\n        // attach pricing engines to helpers\n        boost::shared_ptr<QuantExt::AnalyticCcLgmFxOptionEngine> engine =\n            boost::make_shared<QuantExt::AnalyticCcLgmFxOptionEngine>(model, i);\n        // enable caching for calibration\n        // TODO: review this\n        engine->cache(true);\n        for (Size j = 0; j < fxOptionBaskets_[i].size(); j++)\n            fxOptionBaskets_[i][j]->setPricingEngine(engine);\n\n        if (fx->calibrationType() == CalibrationType::Bootstrap && fx->sigmaParamType() == ParamType::Piecewise)\n            model->calibrateBsVolatilitiesIterative(CrossAssetModelTypes::FX, i, fxOptionBaskets_[i],\n                                                    *optimizationMethod_, endCriteria_);\n        else\n            model->calibrateBsVolatilitiesGlobal(CrossAssetModelTypes::FX, i, fxOptionBaskets_[i], *optimizationMethod_,\n                                                 endCriteria_);\n\n        LOG(\"FX \" << fx->foreignCcy() << \" calibration errors:\");\n        fxOptionCalibrationErrors_[i] =\n            logCalibrationErrors(fxOptionBaskets_[i], fxParametrizations[i], irParametrizations[0]);\n        if (fx->calibrationType() == CalibrationType::Bootstrap) {\n            QL_REQUIRE(fabs(fxOptionCalibrationErrors_[i]) < config->bootstrapTolerance(),\n                       \"calibration error \" << fxOptionCalibrationErrors_[i] << \" exceeds tolerance \"\n                                            << config->bootstrapTolerance());\n        }\n    }\n\n    /*************************\n     * Relink LGM discount curves to curves used for EQ calibration\n     */\n\n    for (Size i = 0; i < irParametrizations.size(); i++) {\n        auto p = irParametrizations[i];\n        irDiscountCurves[i].linkTo(*market_->discountCurve(p->currency().code(), configurationEqCalibration_));\n        LOG(\"Relinked discounting curve for \" << p->currency().code() << \" for EQ calibration\");\n    }\n\n    /*************************\n     * Calibrate EQ components\n     */\n\n    for (Size i = 0; i < eqParametrizations.size(); i++) {\n        boost::shared_ptr<EqBsData> eq = config->eqConfigs()[i];\n        if (!eq->calibrateSigma()) {\n            LOG(\"EQ Calibration \" << i << \" skipped\");\n            continue;\n        }\n        LOG(\"EQ Calibration \" << i);\n        // attach pricing engines to helpers\n        Currency eqCcy = eqParametrizations[i]->currency();\n        Size eqCcyIdx = model->ccyIndex(eqCcy);\n        boost::shared_ptr<QuantExt::AnalyticXAssetLgmEquityOptionEngine> engine =\n            boost::make_shared<QuantExt::AnalyticXAssetLgmEquityOptionEngine>(model, i, eqCcyIdx);\n        for (Size j = 0; j < eqOptionBaskets_[i].size(); j++)\n            eqOptionBaskets_[i][j]->setPricingEngine(engine);\n\n        if (eq->calibrationType() == CalibrationType::Bootstrap && eq->sigmaParamType() == ParamType::Piecewise)\n            model->calibrateBsVolatilitiesIterative(CrossAssetModelTypes::EQ, i, eqOptionBaskets_[i],\n                                                    *optimizationMethod_, endCriteria_);\n        else\n            model->calibrateBsVolatilitiesGlobal(CrossAssetModelTypes::EQ, i, eqOptionBaskets_[i], *optimizationMethod_,\n                                                 endCriteria_);\n\n        LOG(\"EQ \" << eq->eqName() << \" calibration errors:\");\n        eqOptionCalibrationErrors_[i] =\n            logCalibrationErrors(eqOptionBaskets_[i], eqParametrizations[i], irParametrizations[0]);\n        if (eq->calibrationType() == CalibrationType::Bootstrap) {\n            QL_REQUIRE(fabs(eqOptionCalibrationErrors_[i]) < config->bootstrapTolerance(),\n                       \"calibration error \" << eqOptionCalibrationErrors_[i] << \" exceeds tolerance \"\n                                            << config->bootstrapTolerance());\n        }\n    }\n\n    /*************************\n     * Relink LGM discount curves to curves used for INF calibration\n     */\n\n    for (Size i = 0; i < irParametrizations.size(); i++) {\n        auto p = irParametrizations[i];\n        irDiscountCurves[i].linkTo(*market_->discountCurve(p->currency().code(), configurationFinalModel_));\n        LOG(\"Relinked discounting curve for \" << p->currency().code() << \" as final model curves\");\n    }\n\n    /*************************\n    * Calibrate INF components\n\n    */\n\n    for (Size i = 0; i < infParametrizations.size(); i++) {\n        boost::shared_ptr<InfDkData> inf = config->infConfigs()[i];\n        if ((!inf->calibrateA() && !inf->calibrateH()) || (inf->calibrationType() == CalibrationType::None)) {\n            LOG(\"INF Calibration \" << i << \" skipped\");\n            continue;\n        }\n        LOG(\"INF Calibration \" << i);\n        // attach pricing engines to helpers\n\n        Handle<ZeroInflationIndex> zInfIndex =\n            market_->zeroInflationIndex(model->infdk(i)->name(), configurationInfCalibration_);\n        Real baseCPI = zInfIndex->fixing(zInfIndex->zeroInflationTermStructure()->baseDate());\n\n        boost::shared_ptr<QuantExt::AnalyticDkCpiCapFloorEngine> engine =\n            boost::make_shared<QuantExt::AnalyticDkCpiCapFloorEngine>(model, i, baseCPI);\n        for (Size j = 0; j < infCapFloorBaskets_[i].size(); j++)\n            infCapFloorBaskets_[i][j]->setPricingEngine(engine);\n\n        if (inf->calibrateA() && !inf->calibrateH()) {\n            if (inf->calibrationType() == CalibrationType::Bootstrap && inf->aParamType() == ParamType::Piecewise) {\n                model->calibrateInfDkVolatilitiesIterative(i, infCapFloorBaskets_[i], *optimizationMethod_,\n                                                           endCriteria_);\n            } else {\n                model->calibrateInfDkVolatilitiesGlobal(i, infCapFloorBaskets_[i], *optimizationMethod_, endCriteria_);\n            }\n        } else if (!inf->calibrateA() && inf->calibrateH()) {\n            if (inf->calibrationType() == CalibrationType::Bootstrap && inf->hParamType() == ParamType::Piecewise) {\n                model->calibrateInfDkReversionsIterative(i, infCapFloorBaskets_[i], *optimizationMethod_, endCriteria_);\n            } else {\n                model->calibrateInfDkReversionsGlobal(i, infCapFloorBaskets_[i], *optimizationMethod_, endCriteria_);\n            }\n        } else {\n            model->calibrate(infCapFloorBaskets_[i], *optimizationMethod_, endCriteria_);\n        }\n\n        LOG(\"INF \" << inf->infIndex() << \" calibration errors:\");\n        infCapFloorCalibrationErrors_[i] =\n            logCalibrationErrors(infCapFloorBaskets_[i], infParametrizations[i], irParametrizations[0]);\n        if (inf->calibrationType() == CalibrationType::Bootstrap) {\n            QL_REQUIRE(fabs(infCapFloorCalibrationErrors_[i]) < config->bootstrapTolerance(),\n                       \"calibration error \" << infCapFloorCalibrationErrors_[i] << \" exceeds tolerance \"\n                                            << config->bootstrapTolerance());\n        }\n    }\n\n    /*************************\n     * Relink LGM discount curves to final model curves\n     */\n\n    for (Size i = 0; i < irParametrizations.size(); i++) {\n        auto p = irParametrizations[i];\n        irDiscountCurves[i].linkTo(*market_->discountCurve(p->currency().code(), configurationFinalModel_));\n        LOG(\"Relinked discounting curve for \" << p->currency().code() << \" as final model curves\");\n    }\n\n    // play safe (although the cache of the model should be empty at\n    // this point from all what we know...)\n    model->update();\n\n    LOG(\"Building CrossAssetModel done\");\n\n    return model;\n}\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "a7e2a16831ddebf92691c2448fb1627dd7dff2e9", "size": 19745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/model/crossassetmodelbuilder.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": "OREData/ored/model/crossassetmodelbuilder.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": "OREData/ored/model/crossassetmodelbuilder.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": 48.9950372208, "max_line_length": 120, "alphanum_fraction": 0.6338819954, "num_tokens": 4678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.18420742249755662}}
{"text": "#include <iostream>\n#include <Eigen/Eigen>                        // for vector maths\n#include <pangolin/pangolin.h>                // for open GL state management\n#include <SceneGraph/SceneGraph.h>            // for open GL scene graph\n#include \"GetPot\"                             // for command line parsing\n#include \"CVarHelpers.h\"                      // for parsing Eigen vars as CVars\n#include <cvars/CVar.h>                       // for glconsole\n#include <ModelGraph/Models.h>            // Include the ModelGraph\n#include \"RenderClass.h\"\n#include \"PhysicsClass.h\"\n\nusing namespace std;\nusing namespace CVarUtils;\nusing namespace pangolin;\nusing namespace SceneGraph;\n\n#define USAGE    \\\n\"USAGE: Robot -n <name> -d <media directory>\\n\"\\\n\"      Options:\\n\"\\\n\"      --RobotName, -n        Name of this Robot process.\\n\"\\\n\"      --MediaDir, -d         Directory where game media (meshes, maps, models etc.) are stored.\\n\"\n\n\nclass App\n{\n    public:\n        ///////////////////////////////////////////////////////////////////\n        SceneGraph::GLShadowLight   m_light;\n        SceneGraph::GLBox           m_ground;\n        SceneGraph::GLGrid          m_grid;\n        SceneGraph::GLSceneGraph&   m_rSceneGraph;\n        std::string                 m_sRobotName;\n        SceneGraph::GLMesh          m_RobotMesh;\n        std::string                 m_sRobotMeshFilename;\n        std::string                 m_sMediaDir; // path to media files, meshes, etc\n        Model                       m_RobotModel;// focus of our example app\n        Phys*                       m_Phys;\n        Render                      m_Render;\n\n        // TODO TODO\n        // rpg::CameraDevice           cam;\n        //rpg::CarDevice              car;\n\n\n        ///////////////////////////////////////////////////////////////////\n        App(\n                SceneGraph::GLSceneGraph& glGraph,  //< Input: reference to glGraph\n                const std::string& sRobotName,      //< Input: name of robot proxy\n                const std::string& sMediaDir        //< Input: location of meshes, models, maps etc\n                )\n            : m_rSceneGraph( glGraph )/*, m_pSim(pSim)*/\n        {\n            // look in the given media dir for the robot models/meshes\n            m_sMediaDir = sMediaDir;\n            m_sRobotMeshFilename = m_sMediaDir+\"/model.blend\";\n            m_sRobotName = sRobotName;\n            BuildRobot();\n            PrintRobotGraph( m_RobotModel );\n            Eigen::Vector6d RobotPose;\n            RobotPose << 0, 0, -10, 0, 0, 0;\n//            BuildRenderGraph(m_RobotModel, RobotPose);\n            m_Phys = new Phys;\n            m_Phys->Init();\n            AssociatePhysicsBodies( m_RobotModel, RobotPose );\n            AssociatePhysicsJoints( m_RobotModel, RobotPose );\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void BuildRobot( void )\n        {\n            //  First enter the root node to build off of\n//            BoxShape box = BoxShape(1,1,1);\n//            Body* pChassis = new Body( std::string(\"Anchor\"), box, 0 );\n//            pChassis->SetPose( 0,0,0,0,0,0 );\n//            m_RobotModel.SetName(\"SlideTest\");\n//            m_RobotModel.m_pParent = NULL;\n//            m_RobotModel.SetBase( pChassis );\n\n//            Body* pMass = new Body( std::string(\"Bob\"), box, 1 );\n//            pMass->SetPose( 0,0,4,0,0,0 );\n\n            Eigen::Vector6d Ta, Tb;\n\n            Ta << 0, 0, 13.5, 0, M_PI / 2, 0;\n            Tb << 0, 0, 13.5, 0, M_PI / 2, 0;\n\n            BoxShape box = BoxShape(2,1,3);\n            Body* pChassis = new Body( std::string(\"Chassis\"), box, 1.0f );\n            pChassis->SetPose( 0,0,0,0,0,0 );\n            m_RobotModel.SetName(\"Robot\");\n            m_RobotModel.m_pParent = NULL;\n            m_RobotModel.SetBase( pChassis ); // main body\n\n            box = BoxShape(1,1,1.5);\n            Body* pUpperRArm = new Body( \"UpperRArm\", box, 1 );\n            pUpperRArm->SetPose( 3,0,-1.5, 0,0, 2);\n\n            box = BoxShape(1,1,1.5);\n            Body* pUpperLArm = new Body( \"UpperLArm\", box, 1 );\n            pUpperLArm->SetPose( -3,0,-1.5, 0,0, -2 );\n\n            box = BoxShape(1,1,1);\n            Body* pHead = new Body( \"Head\", box, 1 );\n            pHead->SetPose( 0,0,-5, 0,0, 0 );\n\n            CylinderShape cylinder = CylinderShape(1, 2);\n            Body* pRWheel = new Body(\"RWheel\", cylinder, 1);\n            pRWheel->SetPose(2.5, 0, 2.8, 0, M_PI / 2, 0);\n\n            Body* pLWheel = new Body(\"LWheel\", cylinder, 1);\n            pLWheel->SetPose(-2.5, 0, 2.8, 0, M_PI / 2, 0);\n\n            box = BoxShape(0.5, 0.5, 0.5);\n            Body* pRHand = new Body(\"RHand\", box, 1);\n            pRHand->SetPose(0, 0, 2.5, 0, 0, 0);\n\n            box = BoxShape(0.5, 0.5, 0.5);\n            Body* pLHand = new Body(\"LHand\", box, 1);\n            pLHand->SetPose(0, 0, 2.5, 0, 0, 0);\n\n\n            // create a joint connecting two bodies\n            HingeJoint* pRHinge = new HingeJoint( \"RArmJoint\", pChassis, pUpperRArm, 2, 0, -2.8, 1,0,0 );\n            HingeJoint* pLHinge = new HingeJoint( \"LArmJoint\", pChassis, pUpperLArm, -2, 0, -2.8, 1,0,0 );\n            HingeJoint* pRAxle = new HingeJoint( \"RAxleJoint\", pChassis, pRWheel, 2.5, 0, 2.8, 1,0,0, 0, -1, 0 );\n            HingeJoint* pLAxle = new HingeJoint( \"LAxleJoint\", pChassis, pLWheel, -2.5, 0, 2.8, 1,0,0, 0, -1, 0 );\n\n            Eigen::Vector3d axis1;\n            Eigen::Vector3d axis2;\n            Eigen::Vector3d anchor;\n            Eigen::Vector3d LowerLinearLimit;\n            Eigen::Vector3d UpperLinearLimit;\n            Eigen::Vector3d LowerAngleLimit;\n            Eigen::Vector3d UpperAngleLimit;\n            anchor << 0, 0, -13.5;\n            LowerLinearLimit << 0, 0, -3;\n            UpperLinearLimit << 0, 0, -5;\n            LowerAngleLimit << 0, 0, 0;\n            UpperAngleLimit << 1, 0, 0;\n\n            SliderJoint* pSlider = new SliderJoint( \"Neck\", pChassis, pHead, Ta, Tb, true);\n            pSlider->setLowerLimit(5);\n            pSlider->setUpperLimit(6);\n//            Hinge2Joint* pNeck = new Hinge2Joint( \"Neck\", pChassis, pHead, axis1, axis2, anchor, 0.2, 0.2, LowerLinearLimit, UpperLinearLimit, LowerAngleLimit, UpperAngleLimit);\n\n            axis1 << 0, 0, 2.5;\n            axis2 << 0, 0, 1;\n            Point2Point* pP2P = new Point2Point(\"RWrist\", pUpperRArm, pRHand, axis1, axis2);\n\n            Ta << 0, 0, 2.5, 0, 0, 0;\n            Tb << 0, 0, 0, 0, 0, 0;\n//            ConeTwist* pCT = new ConeTwist(\"LWrist\", pUpperLArm, pLHand, Ta, Tb, false);\n            GenericJoint* pGJ = new GenericJoint(\"LWrist\", pUpperLArm, pLHand, Ta, Tb, false);\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void AssociatePhysicsBodies( ModelNode& item, Eigen::Vector6d WorldPose )\n        {\n            if (dynamic_cast<Body*>(&item))\n                m_Phys->RegisterObject( &item, item.GetName(), WorldPose);\n            Eigen::Vector6d ChildWorldPose;\n            for ( int count = 0; count < item.NumChildren(); count++ ) {\n                ChildWorldPose = _T2Cart(_Cart2T(WorldPose)*(item.m_vChildren[count]->GetPoseMatrix()));\n                AssociatePhysicsBodies(*(item.m_vChildren[count]), ChildWorldPose);\n            }\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void AssociatePhysicsJoints( ModelNode& item, Eigen::Vector6d WorldPose )\n        {\n            if (dynamic_cast<Joint*>(&item))\n                m_Phys->RegisterObject( &item, item.GetName(), WorldPose);\n            Eigen::Vector6d ChildWorldPose;\n            for ( int count = 0; count < item.NumChildren(); count++ ) {\n                ChildWorldPose = _T2Cart(_Cart2T(WorldPose)*(item.m_vChildren[count]->GetPoseMatrix()));\n                AssociatePhysicsJoints(*(item.m_vChildren[count]), ChildWorldPose);\n            }\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void BuildRenderGraph( ModelNode& item, Eigen::Vector6d WorldPose )\n        {\n            m_Render.AddNode(&item, WorldPose);\n\n            Eigen::Vector6d ChildWorldPose;\n            for ( int count = 0; count < item.NumChildren(); count++ ) {\n                ChildWorldPose = _T2Cart(_Cart2T(WorldPose)*(item.m_vChildren[count]->GetPoseMatrix()));\n                BuildRenderGraph(*(item.m_vChildren[count]), ChildWorldPose);\n            }\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void PrintRobotGraph( ModelNode& mn )\n        {\n            if (mn.m_pParent == NULL)\n                std::cout<<\"I am \"<<mn.GetName()<<\" and I have \"<<mn.NumChildren()<<\" child(ren).\"<<std::endl;\n            else{\n                std::cout<<\"I am \"<<mn.GetName()<<\".  My parent is \"<<mn.m_pParent->GetName()<<\" and I have \"<<mn.NumChildren()<<\" child(ren).\"<<std::endl;\n\n                if (dynamic_cast<Body*>(&mn) != NULL){\n                    Body* pBody = (Body*)(&mn);\n                    if (dynamic_cast<BoxShape*>(pBody->m_RenderShape) != NULL)\n                    {\n                        std::cout<<\"I am a Box\"<<std::endl;\n                    }\n                    else if (dynamic_cast<CylinderShape*>(pBody->m_RenderShape) != NULL)\n                    {\n                        std::cout<<\"I am a Cylinder\"<<std::endl;\n                    }\n                    std::cout<<\"I am a Body\"<<std::endl;\n                }else if (HingeJoint* test = dynamic_cast<HingeJoint*>(&mn)) {\n                    std::cout<<\"I am a HingeJoint\"<<std::endl;\n                } else if (HingeJoint* test = dynamic_cast<HingeJoint*>(&mn)) {\n                    std::cout<<\"I am a Hinge2Joint\"<<std::endl;\n                }\n                else{\n                    std::cout << \"I don't seem to exist.\" << std::endl;\n                }\n            }\n\n            for ( int count = 0; count < mn.NumChildren(); count++ ) {\n                PrintRobotGraph(*(mn.m_vChildren[count]));\n            }\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void LeftKey()\n        {\n            Eigen::Matrix4d Tab = GLCart2T( 0, 0, 0, 0, 0, -0.1 );\n            Eigen::Matrix4d Twa = GLCart2T( m_RobotMesh.GetPose() );\n            Eigen::Matrix4d Twb = Twa*Tab;\n            m_RobotMesh.SetPose( GLT2Cart(Twb) );\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void RightKey()\n        {\n            Eigen::Matrix4d Tab = GLCart2T( 0, 0, 0, 0, 0, 0.1 );\n            Eigen::Matrix4d Twa = GLCart2T( m_RobotMesh.GetPose() );\n            Eigen::Matrix4d Twb = Twa*Tab;\n            m_RobotMesh.SetPose( GLT2Cart(Twb) );\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void ForwardKey()\n        {\n            Eigen::Matrix4d Tab = GLCart2T( 0.1, 0, 0, 0, 0, 0 );\n            Eigen::Matrix4d Twa = GLCart2T( m_RobotMesh.GetPose() );\n            Eigen::Matrix4d Twb = Twa*Tab;\n            m_RobotMesh.SetPose( GLT2Cart(Twb) );\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        void ReverseKey()\n        {\n            Eigen::Matrix4d Tab = GLCart2T( -0.1, 0, 0, 0, 0, 0 );\n            Eigen::Matrix4d Twa = GLCart2T( m_RobotMesh.GetPose() );\n            Eigen::Matrix4d Twb = Twa*Tab;\n            m_RobotMesh.SetPose( GLT2Cart(Twb) );\n        }\n\n        ///////////////////////////////////////////////////////////////////\n        /// Re-allocate the simulator each time\n        void InitReset()\n        {\n            m_rSceneGraph.Clear();\n            m_Render.AddToScene( &m_rSceneGraph );\n\n//            Eigen::Vector6d RobotPose;\n//            RobotPose << 0, 0, -8, 0, 0, 0;\n//            BuildRenderGraph(m_RobotModel, RobotPose);\n//            if (m_Phys)\n//            {\n//                delete m_Phys;\n//            }\n//            m_Phys = new Phys;\n//            m_Phys->Init();\n//            AssociatePhysicsBodies( m_RobotModel, RobotPose );\n//            AssociatePhysicsJoints( m_RobotModel, RobotPose );\n\n\n            m_light.SetPosition( 10,10,-100 );\n            m_rSceneGraph.AddChild( &m_light );\n\n            m_grid.SetNumLines(20);\n            m_grid.SetLineSpacing(1);\n            m_rSceneGraph.AddChild(&m_grid);\n\n            double dThickness = 1;\n            m_ground.SetPose( 0,0, dThickness/2.0,0,0,0 );\n            m_ground.SetExtent( 10,10, dThickness );\n\n            BoxShape bs = BoxShape(10, 10, 1/2.0f);\n            Body* ground = new Body(\"Ground\", bs);\n            ground->m_dMass = 0;\n            ground->SetWPose( m_ground.GetPose4x4_po() );\n            m_Phys->RegisterObject(ground, \"Ground\", m_ground.GetPose());\n\n            Eigen::Vector6d InitPose;\n            InitPose.setZero(6, 1);\n\n            m_light.AddShadowReceiver( &m_ground );\n\n            m_Render.UpdateScene();\n\n        }\n\n        void StepForward( void )\n        {\n            m_Phys->StepSimulation();\n            m_Render.UpdateScene();\n        }\n};\n\n\n///////////////////////////////////////////////////////////////////\nint main( int argc, char** argv )\n{\n    // parse command line arguments\n    GetPot cl( argc, argv );\n    std::string sRobotName = cl.follow( \"Bender\", 2, \"--RobotName\", \"-n\" );\n    std::string sMediaDir = cl.follow( \"./\", 2, \"--MediaDir\", \"-d\" ); // md specifies the media dir\n//    if( argc != 5 ){\n//        puts(USAGE);\n//        return -1;\n//    }\n\n    // Create OpenGL window in single line thanks to GLUT\n    pangolin::CreateWindowAndBind(\"Main\",640,480);\n    SceneGraph::GLSceneGraph::ApplyPreferredGlSettings();\n    glClearColor(0, 0, 0, 0);\n    glewInit();\n\n    // sinle application context holds everything\n    SceneGraph::GLSceneGraph  glGraph;\n    App app( glGraph, sRobotName, sMediaDir/*, pSim*/ ); // initialize exactly one RobotProxy\n    app.InitReset(); // this will populate the scene graph with objects and\n    // register these objects with the simulator.\n\n    //////////////////////////////////////////////\n    // <Pangolin boilerplate>\n    const SceneGraph::AxisAlignedBoundingBox bbox = glGraph.ObjectAndChildrenBounds();\n    const Eigen::Vector3d center = bbox.Center();\n    const double size = bbox.Size().norm();\n    const double far = 10*size;\n    const double near = far / 1E3;\n\n    // Define Camera Render Object (for view / scene browsing)\n    pangolin::OpenGlRenderState stacks3d(\n            pangolin::ProjectionMatrix(640,480,420,420,320,240,near,far),\n            pangolin::ModelViewLookAt(center(0), center(1) + size, center(2) - size/4,\n                center(0), center(1), center(2), pangolin::AxisNegZ) );\n\n    // We define a new view which will reside within the container.\n    pangolin::View view3d;\n\n    // We set the views location on screen and add a handler which will\n    // let user input update the model_view matrix (stacks3d) and feed through\n    // to our scenegraph\n    view3d.SetBounds( 0.0, 1.0, 0.0, 1.0, -640.0f/480.0f );\n    view3d.SetHandler( new SceneGraph::HandlerSceneGraph( glGraph, stacks3d) );\n    view3d.SetDrawFunction( SceneGraph::ActivateDrawFunctor( glGraph, stacks3d) );\n\n    // Add our views as children to the base container.\n    pangolin::DisplayBase().AddDisplay( view3d );\n\n    // register a keyboard hook to trigger the reset method\n    pangolin::RegisterKeyPressCallback( pangolin::PANGO_CTRL + 'r',\n            std::bind( &App::InitReset, &app ) );\n\n    // simple asdw control\n//    RegisterKeyPressCallback( 'a', bind( &Robot::LeftKey, &app ) );\n//    RegisterKeyPressCallback( 'A', bind( &Robot::LeftKey, &app ) );\n\n//    RegisterKeyPressCallback( 's', bind( &Robot::ReverseKey, &app ) );\n//    RegisterKeyPressCallback( 'S', bind( &Robot::ReverseKey, &app ) );\n\n//    RegisterKeyPressCallback( 'd', bind( &Robot::RightKey, &app ) );\n//    RegisterKeyPressCallback( 'D', bind( &Robot::RightKey, &app ) );\n\n//    RegisterKeyPressCallback( 'w', bind( &Robot::ForwardKey, &app ) );\n//    RegisterKeyPressCallback( 'W', bind( &Robot::ForwardKey, &app ) );\n\n    RegisterKeyPressCallback( ' ', bind( &App::StepForward, &app ) );\n    RegisterKeyPressCallback( PANGO_CTRL + 'r', bind( &App::InitReset, &app ) );\n\n    // </Pangolin boilerplate>\n    //////////////////////////////////////////////\n\n    // Default hooks for exiting (Esc) and fullscreen (tab).\n    while( !pangolin::ShouldQuit() ) {\n\n        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n        GLColor(1, 1, 1, 1);\n\n        DisplayBase().ActivateScissorAndClear();\n        // 1) SENSE: Read from robot sensors\n\n        // 2) PLAN:  do stuff\n\n        // 3) ACT: Send commands to the robot\n\n        // optionally, draw info for a human to look at\n\n        app.m_Phys->DebugDrawWorld();\n//        app.m_Phys->StepSimulation();\n//        app.m_Render.UpdateScene();\n\n        // loop through robot graph and for each body update the associated GL object pose\n\n\n        pangolin::FinishFrame();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "8284ef05939e31dbc13d256d4cc67008417ef4ec", "size": 16941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/ConstraintDemo/main.cpp", "max_stars_repo_name": "bpwiselybabu/SceneGraph", "max_stars_repo_head_hexsha": "1ae7142615bb2c15883ed928a5ed69b0cd281665", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-10-18T15:11:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T02:22:13.000Z", "max_issues_repo_path": "Examples/ConstraintDemo/main.cpp", "max_issues_repo_name": "bpwiselybabu/SceneGraph", "max_issues_repo_head_hexsha": "1ae7142615bb2c15883ed928a5ed69b0cd281665", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-04-24T20:37:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-27T15:26:42.000Z", "max_forks_repo_path": "Examples/ConstraintDemo/main.cpp", "max_forks_repo_name": "bpwiselybabu/SceneGraph", "max_forks_repo_head_hexsha": "1ae7142615bb2c15883ed928a5ed69b0cd281665", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-21T18:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-08T15:15:38.000Z", "avg_line_length": 40.6258992806, "max_line_length": 179, "alphanum_fraction": 0.5129567322, "num_tokens": 4537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.18420741880658403}}
{"text": "#include <stan/math/rev.hpp>\n#include <boost/mp11.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/functor/test_fixture_ode.hpp>\n#include <test/unit/math/rev/functor/test_fixture_ode_lorenz.hpp>\n#include <stan/math/torsten/test/unit/dsolve/ode_test_functors.hpp>\n\n/**\n *\n * Use same solver functor type for both w & w/o tolerance control\n */\ntemplate <typename solve_type, typename... Ts>\nusing ode_test_tuple = std::tuple<solve_type, solve_type, Ts...>;\n\n/**\n * Outer product of test types\n */\nusing lorenz_test_types = boost::mp11::mp_product<\n    ode_test_tuple,\n    ::testing::Types<pmx_ode_adams_functor, pmx_ode_bdf_functor, pmx_ode_ckrk_functor,\n                     pmx_ode_rk45_functor>>;\n\nTYPED_TEST_SUITE_P(lorenz_test);\nTYPED_TEST_P(lorenz_test, param_and_data_finite_diff) {\n  if (std::is_same<TypeParam,\n                   std::tuple<pmx_ode_rk45_functor, pmx_ode_rk45_functor>>::value) {\n    this->test_fd_vd(1.e-6, 3e-2);\n    this->test_fd_dv(1.e-6, 3e-2);\n    this->test_fd_vv(1.e-6, 3e-2);\n  } else if (std::is_same<TypeParam, std::tuple<pmx_ode_ckrk_functor,\n                                                pmx_ode_ckrk_functor>>::value) {\n    this->test_fd_vd(1.e-6, 5e-2);\n    this->test_fd_dv(1.e-6, 5e-2);\n    this->test_fd_vv(1.e-6, 5e-2);\n  } else {\n    this->test_fd_vd(1.e-6, 1e-2);\n    this->test_fd_dv(1.e-6, 1e-2);\n    this->test_fd_vv(1.e-6, 1e-2);\n  }\n}\nREGISTER_TYPED_TEST_SUITE_P(lorenz_test, param_and_data_finite_diff);\nINSTANTIATE_TYPED_TEST_SUITE_P(StanOde, lorenz_test, lorenz_test_types);\n", "meta": {"hexsha": "04e2a6d1ad51e90a9df7b2815cc30ae4a21f805a", "size": 1539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/dsolve/lorenz_ode_typed_fd_test.cpp", "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": "test/unit/dsolve/lorenz_ode_typed_fd_test.cpp", "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": "test/unit/dsolve/lorenz_ode_typed_fd_test.cpp", "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": 35.7906976744, "max_line_length": 86, "alphanum_fraction": 0.6920077973, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.1842074151156115}}
{"text": "// Boost.Geometry Index\r\n//\r\n// R-tree strategies\r\n//\r\n// Copyright (c) 2019, Oracle and/or its affiliates.\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_GEOGRAPHIC_INDEX_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_INDEX_HPP\r\n\r\n\r\n#include <boost/geometry/strategies/geographic/distance.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_andoyer.hpp> // backward compatibility\r\n#include <boost/geometry/strategies/geographic/distance_cross_track.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_cross_track_point_box.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_segment_box.hpp>\r\n#include <boost/geometry/strategies/geographic/distance_thomas.hpp> // backward compatibility\r\n#include <boost/geometry/strategies/geographic/distance_vincenty.hpp> // backward compatibility\r\n#include <boost/geometry/strategies/geographic/envelope_segment.hpp>\r\n#include <boost/geometry/strategies/geographic/expand_segment.hpp>\r\n#include <boost/geometry/strategies/geographic/intersection.hpp>\r\n#include <boost/geometry/strategies/geographic/point_in_poly_winding.hpp>\r\n\r\n#include <boost/geometry/strategies/spherical/index.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry { namespace strategy { namespace index\r\n{\r\n\r\ntemplate\r\n<\r\n    typename FormulaPolicy = strategy::andoyer,\r\n    typename Spheroid = geometry::srs::spheroid<double>,\r\n    typename CalculationType = void\r\n>\r\nstruct geographic\r\n    : spherical<CalculationType>\r\n{\r\n    typedef geographic_tag cs_tag;\r\n\r\n    typedef geometry::strategy::envelope::geographic_segment\r\n        <\r\n            FormulaPolicy, Spheroid, CalculationType\r\n        > envelope_segment_strategy_type;\r\n\r\n    inline envelope_segment_strategy_type get_envelope_segment_strategy() const\r\n    {\r\n        return envelope_segment_strategy_type(m_spheroid);\r\n    }\r\n\r\n    typedef geometry::strategy::expand::geographic_segment\r\n        <\r\n            FormulaPolicy, Spheroid, CalculationType\r\n        > expand_segment_strategy_type;\r\n\r\n    inline expand_segment_strategy_type get_expand_segment_strategy() const\r\n    {\r\n        return expand_segment_strategy_type(m_spheroid);\r\n    }\r\n\r\n    // used in equals(Seg, Seg) but only to get_point_in_point_strategy()\r\n    typedef geometry::strategy::intersection::geographic_segments\r\n        <\r\n            FormulaPolicy,\r\n            // If index::geographic formula is derived from intersection::geographic_segments\r\n            // formula with different Order this may cause an inconsistency\r\n            strategy::default_order<FormulaPolicy>::value,\r\n            Spheroid,\r\n            CalculationType\r\n        > relate_segment_segment_strategy_type;\r\n\r\n    inline relate_segment_segment_strategy_type get_relate_segment_segment_strategy() const\r\n    {\r\n        return relate_segment_segment_strategy_type(m_spheroid);\r\n    }\r\n\r\n\ttypedef geometry::strategy::distance::geographic\r\n        <\r\n            FormulaPolicy, Spheroid, CalculationType\r\n        > comparable_distance_point_point_strategy_type;\r\n\r\n    inline comparable_distance_point_point_strategy_type get_comparable_distance_point_point_strategy() const\r\n    {\r\n        return comparable_distance_point_point_strategy_type(m_spheroid);\r\n    }\r\n\r\n    typedef geometry::strategy::distance::geographic_cross_track_point_box\r\n        <\r\n            FormulaPolicy, Spheroid, CalculationType\r\n        > comparable_distance_point_box_strategy_type;\r\n\r\n    inline comparable_distance_point_box_strategy_type get_comparable_distance_point_box_strategy() const\r\n    {\r\n        return comparable_distance_point_box_strategy_type(m_spheroid);\r\n    }\r\n\r\n    typedef geometry::strategy::distance::geographic_cross_track\r\n        <\r\n            FormulaPolicy, Spheroid, CalculationType\r\n        > comparable_distance_point_segment_strategy_type;\r\n\r\n    inline comparable_distance_point_segment_strategy_type get_comparable_distance_point_segment_strategy() const\r\n    {\r\n        return comparable_distance_point_segment_strategy_type(m_spheroid);\r\n    }\r\n\r\n    typedef geometry::strategy::distance::geographic_segment_box\r\n        <\r\n            FormulaPolicy, Spheroid, CalculationType\r\n        > comparable_distance_segment_box_strategy_type;\r\n\r\n    inline comparable_distance_segment_box_strategy_type get_comparable_distance_segment_box_strategy() const\r\n    {\r\n        return comparable_distance_segment_box_strategy_type(m_spheroid);\r\n    }\r\n\r\n    geographic()\r\n        : m_spheroid()\r\n    {}\r\n\r\n    explicit geographic(Spheroid const& spheroid)\r\n        : m_spheroid(spheroid)\r\n    {}\r\n\r\npublic:\r\n    Spheroid m_spheroid;\r\n};\r\n\r\n\r\nnamespace services\r\n{\r\n\r\ntemplate <typename Geometry>\r\nstruct default_strategy<Geometry, geographic_tag>\r\n{\r\n    typedef geographic<> type;\r\n};\r\n\r\n\r\n// within and relate (MPt, Mls/MPoly)\r\ntemplate <typename Point1, typename Point2, typename Formula, typename Spheroid, typename CalculationType>\r\nstruct from_strategy<within::geographic_winding<Point1, Point2, Formula, Spheroid, CalculationType> >\r\n{\r\n    typedef strategy::index::geographic<Formula, Spheroid, CalculationType> type;\r\n\r\n    static inline type get(within::geographic_winding<Point1, Point2, Formula, Spheroid, CalculationType> const& strategy)\r\n    {\r\n        return type(strategy.model());\r\n    }\r\n};\r\n\r\n// distance (MPt, MPt)\r\ntemplate <typename Formula, typename Spheroid, typename CalculationType>\r\nstruct from_strategy<distance::geographic<Formula, Spheroid, CalculationType> >\r\n{\r\n    typedef strategy::index::geographic<Formula, Spheroid, CalculationType> type;\r\n\r\n    static inline type get(distance::geographic<Formula, Spheroid, CalculationType> const& strategy)\r\n    {\r\n        return type(strategy.model());\r\n    }\r\n};\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct from_strategy<distance::andoyer<Spheroid, CalculationType> >\r\n{\r\n    typedef strategy::index::geographic<strategy::andoyer, Spheroid, CalculationType> type;\r\n\r\n    static inline type get(distance::andoyer<Spheroid, CalculationType> const& strategy)\r\n    {\r\n        return type(strategy.model());\r\n    }\r\n};\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct from_strategy<distance::thomas<Spheroid, CalculationType> >\r\n{\r\n    typedef strategy::index::geographic<strategy::thomas, Spheroid, CalculationType> type;\r\n\r\n    static inline type get(distance::thomas<Spheroid, CalculationType> const& strategy)\r\n    {\r\n        return type(strategy.model());\r\n    }\r\n};\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct from_strategy<distance::vincenty<Spheroid, CalculationType> >\r\n{\r\n    typedef strategy::index::geographic<strategy::vincenty, Spheroid, CalculationType> type;\r\n\r\n    static inline type get(distance::vincenty<Spheroid, CalculationType> const& strategy)\r\n    {\r\n        return type(strategy.model());\r\n    }\r\n};\r\n\r\n// distance (MPt, Linear/Areal)\r\ntemplate <typename Formula, typename Spheroid, typename CalculationType>\r\nstruct from_strategy<distance::geographic_cross_track<Formula, Spheroid, CalculationType> >\r\n{\r\n    typedef strategy::index::geographic<Formula, Spheroid, CalculationType> type;\r\n\r\n    static inline type get(distance::geographic_cross_track<Formula, Spheroid, CalculationType> const& strategy)\r\n    {\r\n        return type(strategy.model());\r\n    }\r\n};\r\n\r\n\r\n} // namespace services\r\n\r\n\r\n}}}} // namespace boost::geometry::strategy::index\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_INDEX_HPP\r\n", "meta": {"hexsha": "c9e503dcdb3e17148dc351709df0257a693fb22f", "size": 7666, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/strategies/geographic/index.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/geometry/strategies/geographic/index.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/geometry/strategies/geographic/index.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": 35.3271889401, "max_line_length": 123, "alphanum_fraction": 0.7363683799, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18413818750733035}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// Schema.cpp\n//\n// Copyright (c) 2013-2014 Eric Lombrozo\n//\n// All Rights Reserved.\n//\n\n#include \"Schema.h\"\n\n#include <stdutils/stringutils.h>\n\n#include <CoinCore/hash.h>\n#include <CoinCore/CoinNodeData.h>\n#include <CoinCore/MerkleTree.h>\n#include <CoinCore/hdkeys.h>\n#include <CoinCore/aes.h>\n#include <CoinCore/random.h>\n\n#include <logger/logger.h>\n\n// support for boost serialization\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\n#include <cstring>\n\n//#define ENABLE_CRYPTO\n\nusing namespace CoinDB;\n\n/*\n * class Keychain\n */\n\nKeychain::Keychain(const std::string& name, const secure_bytes_t& entropy, const secure_bytes_t& lock_key)\n    : name_(name), hidden_(false)\n{\n    if (name.empty() || name[0] == '@') throw std::runtime_error(\"Invalid keychain name.\");\n    if (entropy.size() < 16) throw std::runtime_error(\"At least 128 bits of entropy must be supplied.\");\n\n    Coin::HDSeed hdSeed(entropy);\n    Coin::HDKeychain hdKeychain(hdSeed.getMasterKey(), hdSeed.getMasterChainCode());\n\n    depth_ = (uint32_t)hdKeychain.depth();\n    parent_fp_ = hdKeychain.parent_fp();\n    child_num_ = hdKeychain.child_num();\n    chain_code_ = hdKeychain.chain_code();\n    pubkey_ = hdKeychain.pubkey();\n    privkey_ = hdKeychain.privkey();\n    if (lock_key.empty())\n    {\n        privkey_salt_ = 0;\n        privkey_ciphertext_ = privkey_;\n    }\n    else\n    {\n        privkey_salt_ = AES::random_salt();\n        privkey_ciphertext_ = AES::encrypt(lock_key, privkey_, true, privkey_salt_);\n    }\n    privkey_.clear();\n    hash_ = hdKeychain.full_hash();\n}\n\nKeychain& Keychain::operator=(const Keychain& source)\n{\n    base::operator=(source);\n\n    depth_ = source.depth_;\n    parent_fp_ = source.parent_fp_;\n    child_num_ = source.child_num_;\n    pubkey_ = source.pubkey_;\n\n    chain_code_ = source.chain_code_;\n\n    privkey_ = source.privkey_;\n    privkey_ciphertext_ = source.privkey_ciphertext_;\n    privkey_salt_ = source.privkey_salt_;\n\n    parent_ = source.parent_;\n\n    derivation_path_ = source.derivation_path_;\n\n    uchar_vector_secure hashdata = pubkey_;\n    hashdata += chain_code_;\n    hash_ = ripemd160(sha256(hashdata));\n\n    hidden_ = source.hidden_;\n\n    return *this;\n}\n\nstd::shared_ptr<Keychain> Keychain::child(uint32_t i, bool get_private, const secure_bytes_t& lock_key)\n{\n    if (get_private && !isPrivate()) throw std::runtime_error(\"Cannot get private child from nonprivate keychain.\");\n    if (get_private)\n    {\n        if (privkey_.empty()) throw std::runtime_error(\"Private key is locked.\");\n        Coin::HDKeychain hdkeychain(privkey_, chain_code_, child_num_, parent_fp_, depth_);\n        hdkeychain = hdkeychain.getChild(i);\n        std::shared_ptr<Keychain> child(new Keychain());\n        child->parent_ = get_shared_ptr();\n        child->pubkey_ = hdkeychain.pubkey();\n        child->chain_code_ = hdkeychain.chain_code();\n\n        child->privkey_ = hdkeychain.privkey();\n        if (lock_key.empty())\n        {\n            child->privkey_salt_ = 0;\n            child->privkey_ciphertext_ = privkey_;\n        }\n        else\n        {\n            child->privkey_salt_ = AES::random_salt();\n            child->privkey_ciphertext_ = AES::encrypt(lock_key, child->privkey_, true, child->privkey_salt_);\n        }\n        child->privkey_.clear();\n\n        child->child_num_ = hdkeychain.child_num();\n        child->parent_fp_ = hdkeychain.parent_fp();\n        child->depth_ = hdkeychain.depth();\n        child->hash_ = hdkeychain.full_hash();\n        child->derivation_path_ = derivation_path_;\n        child->derivation_path_.push_back(i);\n        return child;\n    }\n    else\n    {\n        Coin::HDKeychain hdkeychain(pubkey_, chain_code_, child_num_, parent_fp_, depth_);\n        hdkeychain = hdkeychain.getChild(i);\n        std::shared_ptr<Keychain> child(new Keychain());;\n        child->parent_ = get_shared_ptr();\n        child->pubkey_ = hdkeychain.pubkey();\n        child->chain_code_ = hdkeychain.chain_code();\n        child->child_num_ = hdkeychain.child_num();\n        child->parent_fp_ = hdkeychain.parent_fp();\n        child->depth_ = hdkeychain.depth();\n        child->hash_ = hdkeychain.full_hash();\n        child->derivation_path_ = derivation_path_;\n        child->derivation_path_.push_back(i);\n        return child;\n    }\n}\n\nvoid Keychain::lock() const\n{\n    privkey_.clear();\n}\n\nvoid Keychain::unlock(const secure_bytes_t& lock_key) const\n{\n    if (!isPrivate()) throw std::runtime_error(\"Cannot unlock a nonprivate keychain.\");\n    if (privkey_salt_ == 0)\n    {\n        privkey_ = privkey_ciphertext_;\n    }\n    else\n    {\n        privkey_ = AES::decrypt(lock_key, privkey_ciphertext_, true, privkey_salt_); \n    }\n}\n\nbool Keychain::isLocked() const\n{\n    return privkey_.empty();\n}\n\nvoid Keychain::encrypt(const secure_bytes_t& lock_key)\n{\n    if (!isPrivate()) throw std::runtime_error(\"Cannot encrypt a nonprivate keychain.\");\n    if (isLocked()) throw std::runtime_error(\"Keychain is locked.\");\n\n    privkey_salt_ = AES::random_salt();\n    privkey_ciphertext_ = AES::encrypt(lock_key, privkey_, true, privkey_salt_);\n}\n\nvoid Keychain::decrypt()\n{\n    if (!isPrivate()) throw std::runtime_error(\"Cannot unencrypt a nonprivate keychain.\");\n    if (isLocked()) throw std::runtime_error(\"Keychain is locked.\");\n\n    privkey_salt_ = 0;\n    privkey_ciphertext_ = privkey_;\n}\n\nsecure_bytes_t Keychain::getSigningPrivateKey(uint32_t i, const std::vector<uint32_t>& derivation_path) const\n{\n    if (!isPrivate()) throw std::runtime_error(\"Missing private key.\");\n    if (isLocked()) throw std::runtime_error(\"Private key is locked.\");\n\n    // Remove initial zero from privkey if necessary\n    secure_bytes_t stripped_privkey = (privkey_.size() > 32) ? secure_bytes_t(privkey_.begin() + 1, privkey_.end()) : privkey_;\n    Coin::HDKeychain hdkeychain(stripped_privkey, chain_code_, child_num_, parent_fp_, depth_);\n    for (auto k: derivation_path) { hdkeychain = hdkeychain.getChild(k); }\n    return hdkeychain.getPrivateSigningKey(i);\n}\n\nbytes_t Keychain::getSigningPublicKey(uint32_t i, bool get_compressed, const std::vector<uint32_t>& derivation_path) const\n{\n    Coin::HDKeychain hdkeychain(pubkey_, chain_code_, child_num_, parent_fp_, depth_);\n    for (auto k: derivation_path) { hdkeychain = hdkeychain.getChild(k); }\n    return hdkeychain.getPublicSigningKey(i, get_compressed);\n}\n\nsecure_bytes_t Keychain::privkey() const\n{\n    if (!isPrivate()) throw std::runtime_error(\"Keychain is nonprivate.\");\n    if (privkey_.empty()) throw std::runtime_error(\"Keychain is locked.\");\n    return privkey_;\n}\n\nvoid Keychain::importPrivateKey(const Keychain& source)\n{\n    privkey_ciphertext_ = source.privkey_ciphertext_;\n    privkey_salt_ = source.privkey_salt_;\n}\n\nvoid Keychain::importBIP32(const secure_bytes_t& extkey, const secure_bytes_t& lock_key)\n{\n    Coin::HDKeychain hdKeychain(extkey);\n\n    depth_ = (uint32_t)hdKeychain.depth();\n    parent_fp_ = hdKeychain.parent_fp();\n    child_num_ = hdKeychain.child_num();\n    chain_code_ = hdKeychain.chain_code();\n    privkey_.clear();\n    if (hdKeychain.isPrivate())\n    {\n        if (!lock_key.empty())\n        {\n            privkey_salt_ = AES::random_salt();\n            privkey_ciphertext_ = AES::encrypt(lock_key, hdKeychain.key(), true, privkey_salt_);\n        }\n        else\n        {\n            privkey_salt_ = 0;\n            privkey_ciphertext_ = hdKeychain.key();\n        }\n    }\n    else\n    {\n        privkey_salt_ = 0;\n        privkey_ciphertext_.clear();\n    }\n\n    pubkey_ = hdKeychain.pubkey();\n    hash_ = hdKeychain.full_hash();\n}\n\nsecure_bytes_t Keychain::exportBIP32(bool export_private) const\n{\n    secure_bytes_t key;\n\n    if (export_private)\n    {\n        if (!isPrivate()) throw std::runtime_error(\"Keychain is nonprivate.\");\n        if (isLocked()) throw std::runtime_error(\"Keychain is locked.\");\n\n        // Remove initial zero from privkey if necessary\n        key = (privkey_.size() > 32) ? secure_bytes_t(privkey_.begin() + 1, privkey_.end()) : privkey_;\n    }\n    else\n    {\n        key = pubkey_;\n    }\n\n    return Coin::HDKeychain(key, chain_code_, child_num_, parent_fp_, depth_).extkey();\n}\n\nvoid Keychain::clearPrivateKey()\n{\n    privkey_.clear();\n    privkey_ciphertext_.clear();\n    privkey_salt_ = 0;\n}\n\n\n/*\n * class Key\n */\n\nKey::Key(const std::shared_ptr<Keychain>& keychain, uint32_t index, bool compressed)\n{\n    root_keychain_ = keychain->root();\n    derivation_path_ = keychain->derivation_path();\n    index_ = index;\n\n    pubkey_ = keychain->getSigningPublicKey(index_, compressed);\n    updatePrivate();\n}\n\nsecure_bytes_t Key::privkey() const\n{\n    if (!is_private_ || root_keychain_->isLocked()) return secure_bytes_t();\n    return root_keychain_->getSigningPrivateKey(index_, derivation_path_);\n}\n\n// and a version that throws exceptions\nsecure_bytes_t Key::try_privkey() const\n{\n    if (!is_private_) throw std::runtime_error(\"Key::privkey - cannot get private key from nonprivate key object.\");\n    if (root_keychain_->isLocked()) throw std::runtime_error(\"Key::privkey - private key is locked.\");\n\n    return root_keychain_->getSigningPrivateKey(index_, derivation_path_);\n}\n\n\n/*\n * class Account\n */\n\nAccount::Account(const std::string& name, unsigned int minsigs, const KeychainSet& keychains, uint32_t unused_pool_size, uint32_t time_created, bool compressed_keys)\n    : name_(name), minsigs_(minsigs), keychains_(keychains), unused_pool_size_(unused_pool_size), time_created_(time_created), compressed_keys_(compressed_keys)\n{\n    // TODO: Use exception classes\n    if (name_.empty() || name[0] == '@') throw std::runtime_error(\"Invalid account name.\");\n    if (keychains_.size() > 15) throw std::runtime_error(\"Account can use at most 15 keychains.\");\n    if (minsigs > keychains_.size()) throw std::runtime_error(\"Account minimum signatures cannot exceed number of keychains.\");\n    if (minsigs < 1) throw std::runtime_error(\"Account must require at least one signature.\");\n\n    updateHash();\n}\n\nvoid Account::updateHash()\n{\n    std::vector<bytes_t> keychain_hashes;\n    for (auto& keychain: keychains_) { keychain_hashes.push_back(keychain->hash()); }\n    std::sort(keychain_hashes.begin(), keychain_hashes.end());\n\n    uchar_vector data;\n    data.push_back((unsigned char)minsigs_);\n    for (auto& keychain_hash: keychain_hashes) { data += keychain_hash; }\n\n    if (!compressed_keys_) { data.push_back(0x00); }\n\n    hash_ = ripemd160(sha256(data));\n}\n\nAccountInfo Account::accountInfo() const\n{\n    std::vector<std::string> keychain_names;\n    for (auto& keychain: keychains_) { keychain_names.push_back(keychain->name()); }\n\n    std::vector<std::string> bin_names;\n    uint32_t issued_script_count = 0;\n    for (auto& bin: bins_)\n    {\n        bin_names.push_back(bin->name());\n        if (bin->next_script_index() > 0)\n        {\n            issued_script_count += (bin->next_script_index() - 1);\n        }\n    }\n\n    return AccountInfo(id_, name_, minsigs_, keychain_names, issued_script_count, unused_pool_size_, time_created_, bin_names, compressed_keys_);\n}\n\nstd::shared_ptr<AccountBin> Account::addBin(const std::string& name)\n{\n    uint32_t index = bins_.size() + 1;\n    std::shared_ptr<AccountBin> bin(new AccountBin(shared_from_this(), index, name));\n    bins_.push_back(bin);\n    return bin;\n}\n\n\n/*\n * class AccountBin\n */\n\nAccountBin::AccountBin(std::shared_ptr<Account> account, uint32_t index, const std::string& name)\n    : account_(account), index_(index), name_(name), script_count_(0), next_script_index_(0), minsigs_(account->minsigs())\n{\n    if (index == 0) throw std::runtime_error(\"Account bin index cannot be zero.\");\n    if (index == CHANGE_INDEX && name != CHANGE_BIN_NAME) throw std::runtime_error(\"Account bin index reserved for change.\");\n    if (index == DEFAULT_INDEX && name != DEFAULT_BIN_NAME) throw std::runtime_error(\"Account bin index reserved for default.\"); \n\n    updateHash();\n}\n\nstd::string AccountBin::account_name() const\n{\n    return account() ? account()->name() : std::string(\"@null\");\n}\n\nSigningScriptVector AccountBin::generateSigningScripts()\n{\n    SigningScriptVector signingscripts;\n    for (uint32_t i = 0; i < next_script_index_; i++)\n    {\n        std::string label;\n        auto it = script_label_map_.find(i);\n        if (it != script_label_map_.end())   { label = it->second; }\n        SigningScript::status_t status = (index_ == CHANGE_INDEX) ? SigningScript::CHANGE : SigningScript::ISSUED;\n        std::shared_ptr<SigningScript> signingscript(new SigningScript(shared_from_this(), i, label, status));\n        signingscripts.push_back(signingscript);\n    }\n\n    script_count_ = next_script_index_ + unused_pool_size();\n    for (uint32_t i = next_script_index_; i < script_count_; i++)\n    {\n        std::shared_ptr<SigningScript> signingscript(new SigningScript(shared_from_this(), i));\n        signingscripts.push_back(signingscript);\n    }\n\n    return signingscripts;\n}\n\nuint32_t AccountBin::unused_pool_size() const\n{\n    std::shared_ptr<Account> account = account_.lock();\n    return account ? account->unused_pool_size() : DEFAULT_UNUSED_POOL_SIZE;\n}\n\nvoid AccountBin::loadKeychains() const\n{\n    if (!keychains__.empty()) return;\n    if (!account())\n    {\n        // If we do not have an account for this bin we cannot derive the keychains, so use the stored values.\n        keychains__ = keychains_;\n    }\n    else\n    {\n        for (auto& keychain: account()->keychains())\n        {\n            std::shared_ptr<Keychain> child(keychain->child(index_));\n            keychains__.insert(child);\n        }\n    }\n}\n\nvoid AccountBin::updateHash()\n{\n    loadKeychains();\n\n    std::vector<bytes_t> keychain_hashes;\n    for (auto& keychain: keychains__) { keychain_hashes.push_back(keychain->hash()); }\n    std::sort(keychain_hashes.begin(), keychain_hashes.end());\n\n    uchar_vector data;\n    data.push_back((unsigned char)minsigs_);\n    for (auto& keychain_hash: keychain_hashes) { data += keychain_hash; }\n\n    hash_ = ripemd160(sha256(data));\n}\n\nstd::shared_ptr<SigningScript> AccountBin::newSigningScript(const std::string& label)\n{\n    std::shared_ptr<SigningScript> signingscript(new SigningScript(shared_from_this(), script_count_++, label));\n    return signingscript;\n}\n\nvoid AccountBin::markSigningScriptIssued(uint32_t script_index)\n{\n    if (script_index >= next_script_index_)\n        next_script_index_ = script_index + 1;\n}\n\nvoid AccountBin::makeExport(const std::string& name)\n{\n    name_ = name;\n    loadKeychains();\n    keychains_ = keychains__;\n    for (auto& keychain: keychains_) { keychain->name(\"\"); }\n    index_ = 0;\n    account_.reset();\n}\n\nvoid AccountBin::makeImport()\n{\n    updateHash();\n    keychains_.clear();\n}\n\nvoid AccountBin::setScriptLabel(uint32_t index, const std::string& label)\n{\n    if (!label.empty()) { script_label_map_[index] = label; }\n}\n\n\n/*\n * class SigningScript\n */\n\n// static\nstd::string SigningScript::getStatusString(int status)\n{\n    std::vector<std::string> flags;\n    if (status & UNUSED) flags.push_back(\"UNUSED\");\n    if (status & CHANGE) flags.push_back(\"CHANGE\");\n    if (status & ISSUED) flags.push_back(\"ISSUED\");\n    if (status & USED) flags.push_back(\"USED\");\n    if (flags.empty()) return \"NONE\";\n\n    return stdutils::delimited_list(flags, \" | \");\n}\n\n// static\nstd::vector<SigningScript::status_t> SigningScript::getStatusFlags(int status)\n{\n    std::vector<status_t> flags;\n    if (status & UNUSED) flags.push_back(UNUSED);\n    if (status & CHANGE) flags.push_back(CHANGE);\n    if (status & ISSUED) flags.push_back(ISSUED);\n    if (status & USED) flags.push_back(USED);\n    return flags;\n}\n\nSigningScript::SigningScript(std::shared_ptr<AccountBin> account_bin, uint32_t index, const std::string& label, status_t status)\n    : account_(account_bin->account()), account_bin_(account_bin), index_(index), label_(label), status_(status)\n{\n    if (!account_) throw std::runtime_error(\"SigningScript::SigningScript() - account is null.\");\n\n    auto& keychains = account_bin_->keychains();\n    for (auto& keychain: keychains)\n    {\n        std::shared_ptr<Key> key(new Key(keychain, index, account_->compressed_keys()));\n        keys_.push_back(key);\n    }\n\n    // sort keys into canonical order\n    std::sort(keys_.begin(), keys_.end(), [](std::shared_ptr<Key> key1, std::shared_ptr<Key> key2) { return key1->pubkey() < key2->pubkey(); });\n\n    std::vector<bytes_t> pubkeys;\n    for (auto& key: keys_) { pubkeys.push_back(key->pubkey()); }\n    CoinQ::Script::Script script(CoinQ::Script::Script::PAY_TO_MULTISIG_SCRIPT_HASH, account_bin->minsigs(), pubkeys);\n    txinscript_ = script.txinscript(CoinQ::Script::Script::EDIT);\n    txoutscript_ = script.txoutscript();\n\n    account_bin_->setScriptLabel(index, label);\n}\n\nvoid SigningScript::label(const std::string& label)\n{\n    label_ = label;\n    account_bin_->setScriptLabel(index_, label);\n}\n\nvoid SigningScript::status(status_t status)\n{\n    status_ = status;\n    if (status > UNUSED) account_bin_->markSigningScriptIssued(index_);\n}\n\nvoid SigningScript::markUsed()\n{\n\tif (account_bin_->index() == AccountBin::CHANGE_INDEX)\n\t{\n\t\tstatus_ = CHANGE;\n\t}\n\telse\n\t{\n\t\tstatus_ = USED;\n\t}\n\n\taccount_bin_->markSigningScriptIssued(index_);\n}\n\n\n/*\n * class BlockHeader\n */\n\nvoid BlockHeader::fromCoinCore(const Coin::CoinBlockHeader& blockheader, uint32_t height)\n{\n    hash_ = blockheader.hash();\n    height_ = height;\n    version_ = blockheader.version();\n    prevhash_ = blockheader.prevBlockHash();\n    merkleroot_ = blockheader.merkleRoot();\n    timestamp_ = blockheader.timestamp();\n    bits_ = blockheader.bits();\n    nonce_ = blockheader.nonce();\n}\n\nCoin::CoinBlockHeader BlockHeader::toCoinCore() const\n{\n    return Coin::CoinBlockHeader(version_, timestamp_, bits_, nonce_, prevhash_, merkleroot_);\n}\n\nstd::string BlockHeader::toJson() const\n{\n    std::stringstream ss;\n    ss << \"{\"\n       << \"\\\"hash\\\":\\\"\" << uchar_vector(hash_).getHex() << \"\\\",\"\n       << \"\\\"height\\\":\" << height_ << \",\"\n       << \"\\\"version\\\":\" << version_ << \",\"\n       << \"\\\"prevhash\\\":\\\"\" << uchar_vector(prevhash_).getHex() << \"\\\",\"\n       << \"\\\"merkleroot\\\":\\\"\" << uchar_vector(merkleroot_).getHex() << \"\\\",\"\n       << \"\\\"timestamp\\\":\" << timestamp_ << \",\"\n       << \"\\\"bits\\\":\" << bits_ << \",\"\n       << \"\\\"nonce\\\":\" << nonce_\n       << \"}\";\n    return ss.str();\n}\n\nvoid BlockHeader::updateHash()\n{\n    hash_ = Coin::CoinBlockHeader(version_, timestamp_, bits_, nonce_, prevhash_, merkleroot_).hash();\n}\n\n\n/*\n * class MerkleBlock\n */\n\nvoid MerkleBlock::fromCoinCore(const Coin::MerkleBlock& merkleblock, uint32_t height)\n{\n    blockheader_ = std::shared_ptr<BlockHeader>(new BlockHeader(merkleblock.blockHeader, height));\n    txcount_ = merkleblock.nTxs;\n    hashes_.assign(merkleblock.hashes.begin(), merkleblock.hashes.end()); \n    for (auto& hash: hashes_) { std::reverse(hash.begin(), hash.end()); }\n    flags_ = merkleblock.flags;\n}\n\nCoin::MerkleBlock MerkleBlock::toCoinCore() const\n{\n    Coin::MerkleBlock merkleblock;\n    merkleblock.blockHeader = blockheader_->toCoinCore();\n    merkleblock.nTxs = txcount_;\n    merkleblock.hashes.assign(hashes_.begin(), hashes_.end());\n    for (auto& hash: merkleblock.hashes) { std::reverse(hash.begin(), hash.end()); }\n    merkleblock.flags = flags_;\n    return merkleblock;\n}\n\nstd::string MerkleBlock::toJson() const\n{\n    std::stringstream ss;\n    ss << \"{\"\n       << \"\\\"header\\\":\" << blockheader_->toJson() << \",\"\n       << \"\\\"txcount\\\":\" << txcount_ << \",\"\n       << \"\\\"hashes\\\":[\";\n    bool addComma = false;\n    for (auto& hash: hashes_)\n    {\n        if (addComma)   { ss << \",\"; }\n        else            { addComma = true; }\n        ss << \"\\\"\" << uchar_vector(hash).getHex() << \"\\\"\"; \n    }\n    ss << \"],\"\n       << \"\\\"flags\\\":\\\"\" << uchar_vector(flags_).getHex() << \"\\\"\"\n       << \"}\";\n    return ss.str();\n}\n\n\n/*\n * class TxIn\n */\n\nTxIn::TxIn(const Coin::TxIn& coin_txin)\n{\n\tfromCoinCore(coin_txin);\n}\n\nTxIn::TxIn(const bytes_t& raw)\n{\n    Coin::TxIn coin_txin(raw);\n\tfromCoinCore(coin_txin);\n}\n\nvoid TxIn::fromCoinCore(const Coin::TxIn& coin_txin)\n{\n    outhash_ = coin_txin.getOutpointHash();\n    outindex_ = coin_txin.getOutpointIndex();\n    script_ = coin_txin.scriptSig;\n    sequence_ = coin_txin.sequence;\n}\n\nCoin::TxIn TxIn::toCoinCore() const\n{\n    Coin::TxIn coin_txin;\n    coin_txin.previousOut = Coin::OutPoint(outhash_, outindex_);\n    coin_txin.scriptSig = script_;\n    coin_txin.sequence = sequence_;\n    return coin_txin;\n}\n\nbytes_t TxIn::unsigned_script() const\n{\n    using namespace CoinQ::Script;\n\n    Script script(script_);\n    script.clearSigs();\n    return script.txinscript(Script::EDIT);\n}\n\nbytes_t TxIn::raw() const\n{\n    return toCoinCore().getSerialized();\n}\n\nvoid TxIn::outpoint(std::shared_ptr<TxOut> outpoint)\n{\n    outpoint_ = outpoint;\n    if (!outpoint) return;\n\n    std::shared_ptr<Tx> tx = outpoint->tx();\n    // TODO: Tx exception class\n    if (outindex_ != outpoint->txindex())\n        throw std::runtime_error(\"TxIn::outpoint - incorrect outindex.\");\n    if (!tx)\n        throw std::runtime_error(\"TxIn::outpoint - tx is null.\");\n    if (tx->status() == Tx::UNSIGNED)\n        throw std::runtime_error(\"TxIn::outpoint - tx is missing signatures.\");\n    if (outhash_ != tx->hash())\n        throw std::runtime_error(\"TxIn::outpoint - incorrect outhash.\");\n}\n\nstd::string TxIn::toJson() const\n{\n    std::stringstream ss;\n    ss << \"{\"\n       << \"\\\"outhash\\\":\\\"\" << uchar_vector(outhash_).getHex() << \"\\\",\"\n       << \"\\\"outindex\\\":\" << outindex_ << \",\"\n       << \"\\\"script\\\":\\\"\" << uchar_vector(script_).getHex() << \"\\\",\"\n       << \"\\\"sequence\\\":\" << sequence_\n       << \"}\";\n    return ss.str();\n}\n\n\n/*\n * class TxOut\n */\n\n// static\nstd::string TxOut::getStatusString(int flags)\n{\n    std::vector<std::string> str_flags;\n    if (flags & UNSPENT)    str_flags.push_back(\"UNSPENT\");\n    if (flags & SPENT)      str_flags.push_back(\"SPENT\");\n    if (str_flags.empty())  return \"NEITHER\";\n    return stdutils::delimited_list(str_flags, \" | \");\n}\n\n// static\nstd::vector<TxOut::status_t> TxOut::getStatusFlags(int flags)\n{\n    std::vector<status_t> vflags;\n    if (flags & UNSPENT)    vflags.push_back(UNSPENT);\n    if (flags & SPENT)      vflags.push_back(SPENT);\n    return vflags;\n}\n\n// static\nstd::string TxOut::getRoleString(int flags)\n{\n    std::vector<std::string> str_flags;\n    if (flags & ROLE_SENDER)        str_flags.push_back(\"SEND\");\n    if (flags & ROLE_RECEIVER)      str_flags.push_back(\"RECEIVE\");\n    if (str_flags.empty())          return \"NONE\";\n    return stdutils::delimited_list(str_flags, \" | \");\n}\n\n// static\nstd::vector<TxOut::role_t> TxOut::getRoleFlags(int flags)\n{\n    std::vector<role_t> vflags;\n    if (flags & ROLE_SENDER)        vflags.push_back(ROLE_SENDER);\n    if (flags & ROLE_RECEIVER)      vflags.push_back(ROLE_RECEIVER);\n    return vflags;\n}\n\nTxOut::TxOut(uint64_t value, std::shared_ptr<SigningScript> signingscript)\n    : value_(value), status_(UNSPENT)\n{\n    this->signingscript(signingscript);\n}\n\nTxOut::TxOut(const Coin::TxOut& coin_txout)\n    : value_(coin_txout.value), script_(coin_txout.scriptPubKey), status_(UNSPENT)\n{\n}\n\nTxOut::TxOut(const bytes_t& raw)\n{\n    Coin::TxOut coin_txout(raw);\n    value_ = coin_txout.value;\n    script_ = coin_txout.scriptPubKey;\n    status_ = UNSPENT;\n}\n\nvoid TxOut::spent(std::shared_ptr<TxIn> spent)\n{\n    spent_ = spent;\n    status_ = spent ? SPENT : UNSPENT;\n}\n\nvoid TxOut::signingscript(std::shared_ptr<SigningScript> signingscript)\n{\n    if (!signingscript) throw std::runtime_error(\"TxOut::signingscript - null signingscript.\");\n\n    script_ = signingscript->txoutscript();\n    receiving_account_ = signingscript->account();\n    if (receiving_label_.empty()) { receiving_label_ = signingscript->label(); }\n    account_bin_ = signingscript->account_bin();\n    signingscript_ = signingscript;\n}\n\nCoin::TxOut TxOut::toCoinCore() const\n{\n    Coin::TxOut coin_txout;\n    coin_txout.value = value_;\n    coin_txout.scriptPubKey = script_;\n    return coin_txout;\n}\n\nbytes_t TxOut::raw() const\n{\n    return toCoinCore().getSerialized();\n}\n\nstd::string TxOut::toJson() const\n{\n    std::stringstream ss;\n    ss << \"{\"\n       << \"\\\"value\\\":\" << value_ << \",\"\n       << \"\\\"script\\\":\\\"\" << uchar_vector(script_).getHex() << \"\\\",\"\n       << \"\\\"sending_label\\\":\\\"\" << sending_label_ << \"\\\",\"\n       << \"\\\"receiving_label\\\":\\\"\" << receiving_label_ << \"\\\"\";\n\n    if (signingscript_ && signingscript_->contact())\n    {\n        ss << \",\\\"sender_username\\\":\\\"\" << signingscript_->contact()->username() << \"\\\"\";\n    }\n\n    ss << \"}\";\n    return ss.str(); \n}\n\n\n/*\n * class Tx\n */\n\n// static\nstd::string Tx::getStatusString(int status, bool lowercase)\n{\n    std::vector<std::string> flags;\n    if (status & UNSIGNED) flags.push_back(lowercase ? \"unsigned\" : \"UNSIGNED\");\n    if (status & UNSENT) flags.push_back(lowercase ? \"unsent\" : \"UNSENT\");\n    if (status & SENT) flags.push_back(lowercase ? \"send\" : \"SENT\");\n    if (status & PROPAGATED) flags.push_back(lowercase ? \"propagated\" : \"PROPAGATED\");\n    if (status & CANCELED) flags.push_back(lowercase ? \"canceled\" : \"CANCELED\");\n    if (status & CONFIRMED) flags.push_back(lowercase ? \"confirmed\" : \"CONFIRMED\");\n    if (flags.empty()) return lowercase ? \"no_status\" : \"NO_STATUS\";\n    return stdutils::delimited_list(flags, \" | \");\n}\n\n// static\nstd::vector<Tx::status_t> Tx::getStatusFlags(int status)\n{\n    std::vector<status_t> flags;\n    if (status & UNSIGNED) flags.push_back(UNSIGNED);\n    if (status & UNSENT) flags.push_back(UNSENT);\n    if (status & SENT) flags.push_back(SENT);\n    if (status & PROPAGATED) flags.push_back(PROPAGATED);\n    if (status & CANCELED) flags.push_back(CANCELED);\n    if (status & CONFIRMED) flags.push_back(CONFIRMED);\n    return flags;\n}\n\nvoid Tx::set(uint32_t version, const txins_t& txins, const txouts_t& txouts, uint32_t locktime, uint32_t timestamp, status_t status, bool conflicting)\n{\n    version_ = version;\n\n    int i = 0;\n    txins_.clear();\n    for (auto& txin: txins)\n    {\n        txin->tx(shared_from_this());\n        txin->txindex(i++);\n        txins_.push_back(txin);\n    }\n\n    i = 0;\n    txouts_.clear();\n    for (auto& txout: txouts)\n    {\n        txout->tx(shared_from_this());\n        txout->txindex(i++);\n        txouts_.push_back(txout);\n    }\n\n    locktime_ = locktime;\n    timestamp_ = timestamp;\n\n    Coin::Transaction coin_tx = toCoinCore();\n\n    if (missingSigCount())  { status_ = UNSIGNED; }\n    else                    { status_ = status; hash_ = coin_tx.hash(); }\n\n    conflicting_ = conflicting;\n\n    coin_tx.clearScriptSigs();\n    unsigned_hash_ = coin_tx.hash();\n    updateTotals();\n}\n\nvoid Tx::set(Coin::Transaction coin_tx, uint32_t timestamp, status_t status, bool conflicting)\n{\n    //LOGGER(trace) << \"Tx::set - fromCoinCore(coin_tx);\" << std::endl;\n    fromCoinCore(coin_tx);\n\n    timestamp_ = timestamp;\n\n    if (missingSigCount())  { status_ = UNSIGNED; }\n    else                    { status_ = status; hash_ = coin_tx.hash(); }\n\n    conflicting_ = conflicting;\n\n    coin_tx.clearScriptSigs();\n    unsigned_hash_ = coin_tx.hash();\n    updateTotals();\n}\n\nvoid Tx::set(const bytes_t& raw, uint32_t timestamp, status_t status, bool conflicting)\n{\n    Coin::Transaction coin_tx(raw);\n    fromCoinCore(coin_tx);\n    timestamp_ = timestamp;\n\n    if (missingSigCount())  { status_ = UNSIGNED; }\n    else                    { status_ = status; hash_ = coin_tx.hash(); }\n\n    conflicting_ = conflicting;\n\n    coin_tx.clearScriptSigs();\n    unsigned_hash_ = coin_tx.hash();\n    updateTotals();\n}\n\nbool Tx::updateStatus(status_t status /* = NO_STATUS */)\n{\n    // Tx is not signed.\n    if (missingSigCount())\n    {\n        status_ = UNSIGNED;\n        hash_ = bytes_t();\n        return true;\n    }\n\n    // Tx status changed from unsigned to signed.\n    if (status_ == UNSIGNED)\n    {\n        switch (status)\n        {\n        case NO_STATUS:\n            status_ = UNSENT;\n            break;\n\n        case UNSIGNED:\n            status_ = PROPAGATED;\n            break;\n\n        default:\n            status_ = status;\n        }\n\n        hash_ = toCoinCore().hash();\n        return true;\n    }\n\n    // Only update the status if the new status is valid.\n    if (status && status != UNSIGNED && status != status_)\n    {\n        status_ = status;\n        return true;\n    }\n\n    return false;\n}\n\nCoin::Transaction Tx::toCoinCore() const\n{\n    Coin::Transaction coin_tx;\n    coin_tx.version = version_;\n    for (auto& txin:  txins_) { coin_tx.inputs.push_back(txin->toCoinCore()); }\n    for (auto& txout: txouts_) { coin_tx.outputs.push_back(txout->toCoinCore()); }\n    coin_tx.lockTime = locktime_;\n    return coin_tx;\n}\n\nvoid Tx::setBlock(std::shared_ptr<BlockHeader> blockheader, uint32_t blockindex)\n{\n    blockheader_ = blockheader;\n    blockindex_ = blockindex;\n}\n\nvoid Tx::blockheader(std::shared_ptr<BlockHeader> blockheader)\n{\n    blockheader_ = blockheader;\n    if (blockheader)                { status_ = CONFIRMED;  }\n    else if (status_ == CONFIRMED)  { status_ = PROPAGATED; }   \n}\n\nbytes_t Tx::raw() const\n{\n    return toCoinCore().getSerialized();\n}\n\nvoid Tx::updateTotals()\n{\n    have_all_outpoints_ = true;\n    txin_total_ = 0;\n    for (auto& txin: txins_)\n    {\n        std::shared_ptr<TxOut> outpoint = txin->outpoint();\n        if (!outpoint)\n        {\n            have_all_outpoints_ = false;\n        }\n        else\n        {\n            txin_total_ += outpoint->value();\n        }\n    }\n\n    txout_total_ = 0;\n    for (auto& txout: txouts_)\n    {\n        txout_total_ += txout->value(); \n    }\n}\n\nvoid Tx::shuffle_txins()\n{\n    int i = 0;\n    std::random_shuffle(txins_.begin(), txins_.end());\n    for (auto& txin: txins_) { txin->txindex(i++); }\n}\n\nvoid Tx::shuffle_txouts()\n{\n    int i = 0;\n    std::random_shuffle(txouts_.begin(), txouts_.end());\n    for (auto& txout: txouts_) { txout->txindex(i++); }\n}\n\nvoid Tx::fromCoinCore(const Coin::Transaction& coin_tx)\n{\n    version_ = coin_tx.version;\n\n    int i = 0;\n    txins_.clear();\n    for (auto& coin_txin: coin_tx.inputs)\n    {\n        std::shared_ptr<TxIn> txin(new TxIn(coin_txin));\n        txin->tx(shared_from_this());\n        txin->txindex(i++);\n        txins_.push_back(txin);\n    }\n\n    i = 0;\n    txouts_.clear();\n    for (auto& coin_txout: coin_tx.outputs)\n    {\n        std::shared_ptr<TxOut> txout(new TxOut(coin_txout));\n        txout->tx(shared_from_this());\n        txout->txindex(i++);\n        txouts_.push_back(txout);\n    }\n\n    locktime_ = coin_tx.lockTime;\n}\n\nunsigned int Tx::missingSigCount() const\n{\n    // Assume for now all inputs belong to the same account.\n    using namespace CoinQ::Script;\n    unsigned int count = 0;\n    for (auto& txin: txins_)\n    {\n        Script script(txin->script());\n        unsigned int sigsneeded = script.sigsneeded();\n        if (sigsneeded > count) count = sigsneeded;\n    }\n    return count;\n}\n\nstd::set<bytes_t> Tx::missingSigPubkeys() const\n{\n    using namespace CoinQ::Script;\n    std::set<bytes_t> pubkeys;\n    for (auto& txin: txins_)\n    {\n        Script script(txin->script());\n        std::vector<bytes_t> txinpubkeys = script.missingsigs();\n        for (auto& txinpubkey: txinpubkeys) { pubkeys.insert(txinpubkey); }\n    } \n    return pubkeys;\n}\n\nstd::set<bytes_t> Tx::presentSigPubkeys() const\n{\n    std::set<bytes_t> pubkeys;\n\n    using namespace CoinQ::Script;\n    Signer signer(toCoinCore(), true);\n    for (auto& script: signer.getScripts())\n    {\n        std::vector<bytes_t> txinpubkeys = script.presentsigs();\n        for (auto& txinpubkey: txinpubkeys) { pubkeys.insert(txinpubkey); }\n    } \n    return pubkeys;\n}\n\nCoinQ::Script::Signer Tx::signer() const\n{\n    return CoinQ::Script::Signer(toCoinCore(), true);\n}\n\nstd::string Tx::toJson(bool includeRawHex) const\n{\n    std::stringstream ss;\n    ss << \"{\"\n       << \"\\\"version\\\":\" << version_ << \",\"\n       << \"\\\"locktime\\\":\" << locktime_ << \",\"\n       << \"\\\"hash\\\":\\\"\" << uchar_vector(hash()).getHex() << \"\\\",\"\n       << \"\\\"unsignedhash\\\":\\\"\" << uchar_vector(unsigned_hash()).getHex() << \"\\\",\"\n       << \"\\\"status\\\":\\\"\" << getStatusString(status_) << \"\\\",\"\n       << \"\\\"height\\\":\";\n    if (blockheader_)   { ss << blockheader_->height(); }\n    else                { ss << \"null\"; }\n    ss << \",\"\n       << \"\\\"txins\\\":[\";\n    bool addComma = false;\n    for (auto& txin: txins_)\n    {\n        if (addComma)   { ss << \",\"; }\n        else            { addComma = true; }\n        ss << txin->toJson();\n    }\n    ss << \"],\"\n       << \"\\\"txouts\\\":[\";\n    addComma = false;\n    for (auto& txout: txouts_)\n    {\n        if (addComma)   { ss << \",\"; }\n        else            { addComma = true; }\n        ss << txout->toJson();\n    }\n    ss << \"]\";\n\n    if (includeRawHex)\n    {\n        ss << \",\\\"rawhex\\\":\\\"\" << uchar_vector(raw()).getHex() << \"\\\"\";\n    }\n\n    ss << \"}\";\n    return ss.str();\n}\n\nstd::string Tx::toSerialized() const\n{\n    std::stringstream ss;\n    boost::archive::text_oarchive oa(ss);\n    oa << *this;\n    return ss.str();\n}\n\nvoid Tx::fromSerialized(const std::string& serialized)\n{\n    std::stringstream ss;\n    ss << serialized;\n    boost::archive::text_iarchive ia(ss);\n    ia >> *this;\n}\n\n", "meta": {"hexsha": "361211dafb42f3d9e61ff2efd0b5cc9eb00c733a", "size": 33194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/CoinDB/src/Schema.cpp", "max_stars_repo_name": "anypath/CoinVault", "max_stars_repo_head_hexsha": "ec9fb9bdf557086b8bcad273c232319ed04442b9", "max_stars_repo_licenses": ["Unlicense", "OpenSSL", "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/CoinDB/src/Schema.cpp", "max_issues_repo_name": "anypath/CoinVault", "max_issues_repo_head_hexsha": "ec9fb9bdf557086b8bcad273c232319ed04442b9", "max_issues_repo_licenses": ["Unlicense", "OpenSSL", "MIT"], "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/CoinDB/src/Schema.cpp", "max_forks_repo_name": "anypath/CoinVault", "max_forks_repo_head_hexsha": "ec9fb9bdf557086b8bcad273c232319ed04442b9", "max_forks_repo_licenses": ["Unlicense", "OpenSSL", "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.2742759796, "max_line_length": 165, "alphanum_fraction": 0.6437307947, "num_tokens": 8753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18413818750733035}}
{"text": "#include <boost/bind.hpp>\n#include <gazebo/gazebo.hh>\n#include <gazebo/physics/physics.hh>\n#include <gazebo/sensors/sensors.hh>\n#include <gazebo/common/common.hh>\n#include <gazebo/transport/TransportTypes.hh>\n#include <gazebo/msgs/MessageTypes.hh>\n#include <gazebo/common/Time.hh>\n#include <stdio.h>\n#include <gazebo/math/gzmath.hh>\n#include \"flipper_control_msgs.hh\"\n\n#include <termios.h>\n#include <iostream>\n\n#define Gp 3.0  //0.05\n#define Gi 0.00 //0.00005\n\nnamespace gazebo\n{\nclass MobileBasePlugin : public ModelPlugin\n{\n  transport::NodePtr node;\n  physics::ModelPtr  model;\n  common::Time       simTime;\n\n  transport::SubscriberPtr velSub;\n  transport::SubscriberPtr flpSub;\n  transport::SubscriberPtr statsSub;\n  event::ConnectionPtr updateConnection;\n\n  physics::JointPtr hinge1;\n  physics::JointPtr hinge2;\n  physics::JointPtr hinge3;\n  physics::JointPtr hinge4;\n  physics::JointPtr hinge5;\n  physics::JointPtr hinge6;\n  physics::JointPtr hinge7;\n  physics::JointPtr hinge8;\n  physics::JointPtr hinge9;\n  physics::JointPtr hinge10;\n  physics::JointPtr hinge11;\n  physics::JointPtr hinge12;\n  physics::JointPtr hinge13;\n  physics::JointPtr hinge14;\n  physics::JointPtr hinge15;\n  physics::JointPtr hinge16;\n  physics::JointPtr hinge17;\n  physics::JointPtr hinge18;\n  physics::JointPtr hinge19;\n  physics::JointPtr hinge20;\n  physics::JointPtr hinge21;\n  physics::JointPtr hinge22;\n  physics::JointPtr hinge23;\n  physics::JointPtr hinge24;\n  physics::JointPtr hinge25;\n  physics::JointPtr hinge26;\n  physics::JointPtr hinge27;\n  physics::JointPtr hinge28;\n\n  //sensors::RaySensorPtr laser;\n  physics::LinkPtr  sensor;\n\n  /// Wheel speed and gain\n  double THETA[30];\n  double gain;\n \n  /// Distance between wheels on the same axis (Determined from SDF)\n  double wheelSeparation;\n\n  /// Radius of the wheels (Determined from SDF)\n  double wheelRadius;\n\n  /// Flipper target angle \n  double FLP_FR, FLP_FL, FLP_RR, FLP_RL;\n\n  /// Flipper angle controller\n  double dev_FLP_FR;\n  double dev_FLP_FL;\n  double dev_FLP_RR;\n  double dev_FLP_RL;\n  double dev_FLP_FR_sum;\n  double dev_FLP_FL_sum;\n  double dev_FLP_RR_sum;\n  double dev_FLP_RL_sum;\n\n  public:\n  MobileBasePlugin(void)\n  {\n    FLP_FR = FLP_FL = FLP_RR = FLP_RL = M_PI / 4;\n    dev_FLP_FR = dev_FLP_FL = dev_FLP_RR = dev_FLP_RL = 0;\n    dev_FLP_FR_sum = dev_FLP_FL_sum = dev_FLP_RR_sum = dev_FLP_RL_sum = 0;\n    wheelRadius     = 0.2;\n    wheelSeparation = 1;\n    for(int i = 0; i < 30; i++)\n      THETA[i] = 0;\n  }\n\n  void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)\n  {\n    // physics::WorldPtr world = physics::get_world(\"default\");\n    this->model = _model;\n    this->node = transport::NodePtr(new transport::Node());\n    this->node->Init(this->model->GetWorld()->GetName());\n    if(this->LoadParams(_sdf))\n    {\n      this->velSub = this->node->Subscribe(\n      std::string(\"~/\") + this->model->GetName() + std::string(\"/vel_cmd\"),\n      &MobileBasePlugin::OnVelMsg, this);\n      this->flpSub = this->node->Subscribe(\n      std::string(\"~/\") + this->model->GetName() + std::string(\"/flp_cmd\"),\n      &MobileBasePlugin::OnFlpMsg, this);\n      this->updateConnection\n        = event::Events::ConnectWorldUpdateBegin(\n                  boost::bind(&MobileBasePlugin::OnUpdate, this));\n    }\n  }\n \n  bool LoadParams(sdf::ElementPtr _sdf)\n  {\n    if(!_sdf->HasElement(\"gain\"))\n    {\n        gzerr << \"param [gain] not found\\n\";\n        return false;\n    }\n    else\n        this->gain = _sdf->Get<double>(\"gain\");\n    hinge1 = this->model->GetJoint(\"right_front\");\n    hinge2 = this->model->GetJoint(\"right_center1\");\n    hinge3 = this->model->GetJoint(\"right_center2\");\n    hinge4 = this->model->GetJoint(\"right_rear\");\n\n    hinge5 = this->model->GetJoint(\"left_front\");\n    hinge6 = this->model->GetJoint(\"left_center1\");\n    hinge7 = this->model->GetJoint(\"left_center2\");\n    hinge8 = this->model->GetJoint(\"left_rear\");\n\n    hinge9 = this->model->GetJoint(\"right_front_arm\");\n    hinge10 = this->model->GetJoint(\"right_rear_arm\");\n    hinge11 = this->model->GetJoint(\"left_front_arm\");\n    hinge12 = this->model->GetJoint(\"left_rear_arm\");\n\n    hinge13 = this->model->GetJoint(\"right_front_arm_wheel_1\");\n    hinge14 = this->model->GetJoint(\"right_front_arm_wheel_2\");\n    hinge15 = this->model->GetJoint(\"right_front_arm_wheel_3\");\n\n    hinge16 = this->model->GetJoint(\"left_front_arm_wheel_1\");\n    hinge17 = this->model->GetJoint(\"left_front_arm_wheel_2\");\n    hinge18 = this->model->GetJoint(\"left_front_arm_wheel_3\");\n\n    hinge19 = this->model->GetJoint(\"right_rear_arm_wheel_1\");\n    hinge20 = this->model->GetJoint(\"right_rear_arm_wheel_2\");\n    hinge21 = this->model->GetJoint(\"right_rear_arm_wheel_3\");\n\n    hinge22 = this->model->GetJoint(\"left_rear_arm_wheel_1\");\n    hinge23 = this->model->GetJoint(\"left_rear_arm_wheel_2\");\n    hinge24 = this->model->GetJoint(\"left_rear_arm_wheel_3\");\n\n    hinge25 = this->model->GetJoint(\"right_sub2\");\n    hinge26 = this->model->GetJoint(\"right_sub3\");\n\n    hinge27 = this->model->GetJoint(\"left_sub2\");\n    hinge28 = this->model->GetJoint(\"left_sub3\");\n    return true;\n  }\n\n  /////////////////////////////////////////////////\n  void OnVelMsg(ConstPosePtr &_msg)\n  {\n    // gzmsg << \"cmd_vel: \" << msg->position().x() << \", \"\n    //       <<msgs::Convert(msg->orientation()).GetAsEuler().z<<std::endl;\n    double vel_lin = _msg->position().x() / this->wheelRadius;\n#if(GAZEBO_MAJOR_VERSION == 5)\n    double vel_rot = -1 * msgs::Convert(_msg->orientation()).GetAsEuler().z\n                     * (this->wheelSeparation / this->wheelRadius);\n#endif\n#if(GAZEBO_MAJOR_VERSION == 7)\n    double vel_rot = -1 * msgs::ConvertIgn(_msg->orientation()).Euler().Z()\n                     * (this->wheelSeparation / this->wheelRadius);\n#endif\n    set_velocity(vel_lin - vel_rot, vel_lin + vel_rot);\n  }\n\n  void set_velocity(double  vr, double  vl)\n  {\n    THETA[1] = vr;\n    THETA[2] = vr;\n    THETA[3] = vr;\n    THETA[4] = vr;\n    THETA[13] = vr;\n    THETA[14] = vr;\n    THETA[15] = vr;\n    THETA[19] = vr;\n    THETA[20] = vr;\n    THETA[21] = vr;\n    THETA[25] = vr;\n    THETA[26] = vr;\n\n    THETA[5] = vl;\n    THETA[6] = vl;\n    THETA[7] = vl;\n    THETA[8] = vl;\n    THETA[16] = vl;\n    THETA[17] = vl;\n    THETA[18] = vl;\n    THETA[22] = vl;\n    THETA[23] = vl;\n    THETA[24] = vl;\n    THETA[27] = vl;\n    THETA[28] = vl;\n  }\n\n  /////////////////////////////////////////////////\n  void OnFlpMsg(ConstFlipperControlPtr &_msg)\n  {\n    FLP_FR = _msg->fr();\n    FLP_FL = _msg->fl();\n    FLP_RR = _msg->rr();\n    FLP_RL = _msg->rl();\n  }\n\n  /////////////////////////////////////////////////\n  void MoveWheel(void)\n  {\n    hinge1->SetVelocity(0, THETA[1]);\n    hinge2->SetVelocity(0, THETA[2]);\n    hinge3->SetVelocity(0, THETA[3]);\n    hinge4->SetVelocity(0, THETA[4]);\n    hinge5->SetVelocity(0, THETA[5]);\n    hinge6->SetVelocity(0, THETA[6]);\n    hinge7->SetVelocity(0, THETA[7]);\n    hinge8->SetVelocity(0, THETA[8]);\n    hinge13->SetVelocity(0, THETA[13]);\n    hinge14->SetVelocity(0, THETA[14]);\n    hinge15->SetVelocity(0, THETA[15]);\n    hinge16->SetVelocity(0, THETA[16]);\n    hinge17->SetVelocity(0, THETA[17]);\n    hinge18->SetVelocity(0, THETA[18]);\n    hinge19->SetVelocity(0, THETA[19]);\n    hinge20->SetVelocity(0, THETA[20]);\n    hinge21->SetVelocity(0, THETA[21]);\n    hinge22->SetVelocity(0, THETA[22]);\n    hinge23->SetVelocity(0, THETA[23]);\n    hinge24->SetVelocity(0, THETA[24]);\n    hinge21->SetVelocity(0, THETA[25]);\n    hinge22->SetVelocity(0, THETA[26]);\n    hinge23->SetVelocity(0, THETA[27]);\n    hinge24->SetVelocity(0, THETA[28]);\n  }\n\n  void MoveFlipper(void)\n  {\n    // Get current arm angle\n    double flp_fr = hinge9->GetAngle(0).Radian();\n    double flp_fl = hinge11->GetAngle(0).Radian();\n    double flp_rr = hinge10->GetAngle(0).Radian();   \n    double flp_rl = hinge12->GetAngle(0).Radian();\n//printf(\"right_front=%6.3f right_rear=%6.3f left_front=%6.3f left_rear=%6.3f \\r \", flp_fr, flp_fl, flp_rr, flp_rl);\n    // Calc anguler velocity of Front Right flipper\n    dev_FLP_FR = flp_fr - (-FLP_FR);\n    THETA[9] = dev_FLP_FR*(-1)*Gp + dev_FLP_FR_sum*(-1)*Gi;\n    dev_FLP_FR_sum += dev_FLP_FR;\n    // Calc anguler velocity of Front Left flipper\n    dev_FLP_FL = flp_fl - (-FLP_FL);    \n    THETA[11] = dev_FLP_FL*(-1)*Gp + dev_FLP_FL_sum*(-1)*Gi; \n    dev_FLP_FL_sum += dev_FLP_FL;\n    // Calc anguler velocity of Rear Right flipper\n    dev_FLP_RR = flp_rr - FLP_RR;\n    THETA[10] = dev_FLP_RR*(-1)*Gp + dev_FLP_RR_sum*(-1)*Gi;\n    dev_FLP_RR_sum += dev_FLP_RR;\n    // Calc anguler velocity of Rear Left flipper\n    dev_FLP_RL = flp_rl - FLP_RL;    \n    THETA[12] = dev_FLP_RL*(-1)*Gp + dev_FLP_RL_sum*(-1)*Gi; \n    dev_FLP_RL_sum += dev_FLP_RL;\n    // Set flipper anguler velocity\n    hinge9->SetVelocity(0, THETA[9]);\n    hinge10->SetVelocity(0, THETA[10]);\n    hinge11->SetVelocity(0, THETA[11]);\n    hinge12->SetVelocity(0, THETA[12]);\n  }\n \n  public:\n  void OnUpdate()\n  {\n    MoveWheel();\n    MoveFlipper();\n  }\n};\n\nGZ_REGISTER_MODEL_PLUGIN(MobileBasePlugin)\n}\n", "meta": {"hexsha": "1e79f71c8d0ee952dfb3ede13ed93673768b8503", "size": 9012, "ext": "cc", "lang": "C++", "max_stars_repo_path": "crawler_robot_1DEG.cc", "max_stars_repo_name": "nicedone/RoboCupRescuePackage", "max_stars_repo_head_hexsha": "ed1abed5e232490109b2d27182976462257649ab", "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": "crawler_robot_1DEG.cc", "max_issues_repo_name": "nicedone/RoboCupRescuePackage", "max_issues_repo_head_hexsha": "ed1abed5e232490109b2d27182976462257649ab", "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": "crawler_robot_1DEG.cc", "max_forks_repo_name": "nicedone/RoboCupRescuePackage", "max_forks_repo_head_hexsha": "ed1abed5e232490109b2d27182976462257649ab", "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.8630136986, "max_line_length": 116, "alphanum_fraction": 0.6450288504, "num_tokens": 2846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.18410724290305405}}
{"text": "#include \"lm.h\"\n#include <fstream>\n#include <assert.h>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nvoid LM::load_chars(const std::string& fname)\n{\n    std::string line;\n    std::ifstream ifs(fname.c_str());\n    std::vector<std::string> splits;\n    while (std::getline(ifs, line))\n    {\n        boost::trim(line);\n        boost::split(splits, line, boost::is_any_of(\" \\t\\n\"));\n        char_map[splits[0]] = atoi(splits[1].c_str());\n        std::cout << splits[0] << \" -> \" << char_map[splits[0]] << std::endl;\n    }\n    ifs.close();\n}\n\nvoid LM::load_words(const std::string& fname)\n{\n    std::string line;\n    std::ifstream ifs(fname.c_str());\n    while (std::getline(ifs, line))\n    {\n        word_list.push_back(boost::trim_copy(line));\n    }\n    std::cout << \"Loaded \" << word_list.size() << \" words\" << std::endl;\n}\n\nint LM::get_word_id(const std::string& word_string)\n{\n    if (word_to_int.find(word_string) != word_to_int.end())\n        return word_to_int[word_string];\n    else\n        return unk;\n}\n\nvoid LM::read_header(std::ifstream& ifs)\n{\n    std::string line = \"\";\n    std::vector<std::string> splits;\n    while (boost::trim_copy(line) != \"\\\\data\\\\\")\n        std::getline(ifs, line);\n    std::getline(ifs, line);\n    assert(line.find(\"ngram 1\") != std::string::npos);\n    boost::trim(line);\n    boost::split(splits, line, boost::is_any_of(\"=\"));\n    num_words = atoi(splits[1].c_str());\n    std::getline(ifs, line);\n    assert(line.find(\"ngram 2\") != std::string::npos);\n    std::getline(ifs, line);\n    if (line.find(\"ngram 3\") != std::string::npos)\n        is_trigram = true;\n    else\n        is_trigram = false;\n}\n\nvoid LM::load_ug(std::ifstream& ifs)\n{\n    int count = 0;\n    std::string line;\n    std::vector<std::string> splits;\n    while (line.find(\"\\\\1-grams\") == std::string::npos)\n        std::getline(ifs, line);\n    while (true)\n    {\n        std::getline(ifs, line);\n        //std::cout << line << std::endl;\n        boost::trim(line);\n        boost::split(splits, line, boost::is_any_of(\" \\t\"));\n        if (splits.size() < 2)\n            break;\n        word_to_int[splits[1]] = count;\n        if (splits.size() == 3)\n        {\n            ug_probs[count] = std::make_pair(LM_CONSTS::SCALE * atof(splits[0].c_str()),\n                                             LM_CONSTS::SCALE * atof(splits[2].c_str()));\n        }\n        else\n        {\n            ug_probs[count] = std::make_pair(LM_CONSTS::SCALE * atof(splits[0].c_str()),\n                                             0.0f);\n        }\n        count += 1;\n    }\n    std::cout << \"Loaded \" << count << \" unigrams\" << std::endl;\n}\n\nvoid LM::load_bg(std::ifstream& ifs)\n{\n    std::string line;\n    std::vector<std::string> splits;\n    while (line.find(\"\\\\2-grams\") == std::string::npos)\n        std::getline(ifs, line);\n    int count = 0;\n    while (true)\n    {\n        std::getline(ifs, line);\n        boost::trim(line);\n        boost::split(splits, line, boost::is_any_of(\" \\t\"));\n        if (splits.size() < 3 || splits[0] == \"\\\\end\\\\\")\n            break;\n        // TODO Handle trigrams backoffs here\n        bg_probs[std::make_pair(word_to_int[splits[1]],\n                word_to_int[splits[2]])] = LM_CONSTS::SCALE * atof(splits[0].c_str());\n        count += 1;\n    }\n    std::cout << \"Loaded \" << count << \" bigrams\" << std::endl;\n}\n\nfloat LM::ug_prob(int wid)\n{\n    return ug_probs[wid].first;\n}\n\nfloat LM::bg_prob(int w1, int w2)\n{\n    float p = bg_probs[std::make_pair(w1, w2)];\n    if (p == 0.0)\n    {\n        p += ug_probs[w1].second + ug_probs[w2].first;\n    }\n    return p;\n}\n\nfloat LM::score_bg(const std::string& sentence)\n{\n    std::vector<std::string> splits;\n    std::string s = boost::trim_copy(sentence);\n    boost::split(splits, s, boost::is_any_of(\" \\t\"));\n    std::vector<int> word_ids;\n    for (int k = 0; k < splits.size(); k++)\n    {\n        word_ids.push_back(get_word_id(splits[k]));\n    }\n\n    float score = 0.0;\n    std::cout << bg_prob(start, word_ids[0]) << std::endl;\n    score += bg_prob(start, word_ids[0]);\n    for (int k = 0; k < word_ids.size() - 1; k++)\n    {\n        std::cout << k << \" \" << bg_prob(word_ids[k], word_ids[k+1]) << std::endl;\n        score += bg_prob(word_ids[k], word_ids[k+1]);\n    }\n\n    std::cout << bg_prob(word_ids[word_ids.size() - 1], end) << std::endl;\n    score += bg_prob(word_ids[word_ids.size() - 1], end);\n    return score;\n}\n", "meta": {"hexsha": "2a436d5ef6ffae87246ee9b10228f2c5b2c1c767", "size": 4390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ctc_fast/decoder/fastdecode/lm.cpp", "max_stars_repo_name": "SrikarSiddarth/stanford-ctc", "max_stars_repo_head_hexsha": "c8f8257227ec218c4794a96a089ef0a093dcbdfd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 268.0, "max_stars_repo_stars_event_min_datetime": "2015-06-15T20:59:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T15:05:50.000Z", "max_issues_repo_path": "ctc_fast/decoder/fastdecode/lm.cpp", "max_issues_repo_name": "guker/stanford-ctc", "max_issues_repo_head_hexsha": "3d3bd9ce92cfdc0173b1bd2096ecea8634d6b62f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T03:22:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-11T15:58:57.000Z", "max_forks_repo_path": "ctc_fast/decoder/fastdecode/lm.cpp", "max_forks_repo_name": "guker/stanford-ctc", "max_forks_repo_head_hexsha": "3d3bd9ce92cfdc0173b1bd2096ecea8634d6b62f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 109.0, "max_forks_repo_forks_event_min_datetime": "2015-07-07T15:36:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T03:48:15.000Z", "avg_line_length": 28.6928104575, "max_line_length": 89, "alphanum_fraction": 0.5494305239, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.18410724073684823}}
{"text": "#ifndef abstract_primitive_hpp\n#define abstract_primitive_hpp\n\n#include <iostream>\n#include <Eigen/Core>\n#include <QOpenGLFunctions_2_1>\n\nnamespace threedimutil\n{\n    class AbstractPrimitive : protected QOpenGLFunctions_2_1\n    {\n    public:\n        // static void Initialize();\n        // static void Draw();\n        // static AbstractPrimitive& GetInstance();\n        \n    protected:\n        void InitializeInternal()\n        {\n            if (ready_)\n            {\n                std::cerr << \"Warning: Initialize() is called but it is already initialized. This call is ignored.\" << std::endl;\n                return;\n            }\n\n            initializeOpenGLFunctions();\n            \n            CreateVertexData();\n            \n            this->glGenBuffers(1, &vertex_vbo_);\n            this->glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo_);\n            this->glBufferData(GL_ARRAY_BUFFER, sizeof(GLdouble) * vertices_.size(), vertices_.data(), GL_STATIC_DRAW);\n            \n            this->glGenBuffers(1, &normal_vbo_);\n            this->glBindBuffer(GL_ARRAY_BUFFER, normal_vbo_);\n            this->glBufferData(GL_ARRAY_BUFFER, sizeof(GLdouble) * normals_.size(), normals_.data(), GL_STATIC_DRAW);\n            \n            ready_ = true;\n        }\n        \n        void DrawInternal()\n        {\n            if (!ready_) { InitializeInternal(); }\n            \n            this->glEnableClientState(GL_VERTEX_ARRAY);\n            this->glEnableClientState(GL_NORMAL_ARRAY);\n            \n            this->glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo_);\n            this->glVertexPointer(3, GL_DOUBLE, 0, NULL);\n            \n            this->glBindBuffer(GL_ARRAY_BUFFER, normal_vbo_);\n            this->glNormalPointer(GL_DOUBLE, 0, NULL);\n            \n            this->glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vertices_.cols()));\n            \n            this->glBindBuffer(GL_ARRAY_BUFFER, 0);\n            \n            this->glDisableClientState(GL_VERTEX_ARRAY);\n            this->glDisableClientState(GL_NORMAL_ARRAY);\n        }\n        \n        AbstractPrimitive() = default;\n        ~AbstractPrimitive()\n        {\n            if (ready_)\n            {\n                this->glDeleteBuffers(1, &vertex_vbo_);\n                this->glDeleteBuffers(1, &normal_vbo_);\n            }\n        }\n        AbstractPrimitive(const AbstractPrimitive&)            = delete;\n        AbstractPrimitive& operator=(const AbstractPrimitive&) = delete;\n        AbstractPrimitive(AbstractPrimitive&&)                 = delete;\n        AbstractPrimitive& operator=(AbstractPrimitive&&)      = delete;\n        \n        Eigen::MatrixXd vertices_;\n        Eigen::MatrixXd normals_;\n        \n    private:\n        virtual void CreateVertexData() = 0;\n        \n        bool ready_ = false;\n        \n        GLuint vertex_vbo_;\n        GLuint normal_vbo_;\n    };\n}\n\n#endif /* abstract_primitive_hpp */\n", "meta": {"hexsha": "b11ece89ff043da8660dc373dad6cbb76986fc23", "size": 2896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/three-dim-util/opengl2/primitives/abstract-primitive.hpp", "max_stars_repo_name": "yuki-koyama/3d-util", "max_stars_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:07:55.000Z", "max_issues_repo_path": "include/three-dim-util/opengl2/primitives/abstract-primitive.hpp", "max_issues_repo_name": "yuki-koyama/3d-util", "max_issues_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-05-14T00:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T13:50:42.000Z", "max_forks_repo_path": "include/three-dim-util/opengl2/primitives/abstract-primitive.hpp", "max_forks_repo_name": "yuki-koyama/3d-util", "max_forks_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T07:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T19:42:33.000Z", "avg_line_length": 32.1777777778, "max_line_length": 129, "alphanum_fraction": 0.5645718232, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18410723567781317}}
{"text": "// Boost.Geometry Index\n//\n// R-tree R*-tree next node choosing algorithm implementation\n//\n// Copyright (c) 2011-2014 Adam Wulkiewicz, Lodz, Poland.\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_INDEX_DETAIL_RTREE_RSTAR_CHOOSE_NEXT_NODE_HPP\n#define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_RSTAR_CHOOSE_NEXT_NODE_HPP\n\n#include <algorithm>\n\n#include <boost/geometry/algorithms/expand.hpp>\n\n#include <boost/geometry/index/detail/algorithms/content.hpp>\n#include <boost/geometry/index/detail/algorithms/intersection_content.hpp>\n#include <boost/geometry/index/detail/algorithms/union_content.hpp>\n\n#include <boost/geometry/index/detail/rtree/node/node.hpp>\n#include <boost/geometry/index/detail/rtree/visitors/is_leaf.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace index {\n\nnamespace detail { namespace rtree {\n\ntemplate <typename Value, typename Options, typename Box, typename Allocators>\nclass choose_next_node<Value, Options, Box, Allocators, choose_by_overlap_diff_tag>\n{\n    typedef typename rtree::node<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type node;\n    typedef typename rtree::internal_node<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type internal_node;\n    typedef typename rtree::leaf<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type leaf;\n\n    typedef typename rtree::elements_type<internal_node>::type children_type;\n    typedef typename children_type::value_type child_type;\n\n    typedef typename Options::parameters_type parameters_type;\n\n    typedef typename index::detail::default_content_result<Box>::type content_type;\n\npublic:\n    template <typename Indexable>\n    static inline size_t apply(internal_node & n,\n                               Indexable const& indexable,\n                               parameters_type const& parameters,\n                               size_t node_relative_level)\n    {\n        ::geofeatures_boost::ignore_unused_variable_warning(parameters);\n\n        children_type & children = rtree::elements(n);\n        \n        // children are leafs\n        if ( node_relative_level <= 1 )\n        {\n            return choose_by_minimum_overlap_cost(children, indexable, parameters.get_overlap_cost_threshold());\n        }\n        // children are internal nodes\n        else\n            return choose_by_minimum_content_cost(children, indexable);\n    }\n\nprivate:\n    template <typename Indexable>\n    static inline size_t choose_by_minimum_overlap_cost(children_type const& children,\n                                                        Indexable const& indexable,\n                                                        size_t overlap_cost_threshold)\n    {\n        const size_t children_count = children.size();\n\n        content_type min_content_diff = (std::numeric_limits<content_type>::max)();\n        content_type min_content = (std::numeric_limits<content_type>::max)();\n        size_t choosen_index = 0;\n\n        // create container of children sorted by content enlargement needed to include the new value\n        typedef geofeatures_boost::tuple<size_t, content_type, content_type> child_contents;\n\n        typename rtree::container_from_elements_type<children_type, child_contents>::type children_contents;\n        children_contents.resize(children_count);\n\n        for ( size_t i = 0 ; i < children_count ; ++i )\n        {\n            child_type const& ch_i = children[i];\n\n            // expanded child node's box\n            Box box_exp(ch_i.first);\n            geometry::expand(box_exp, indexable);\n\n            // areas difference\n            content_type content = index::detail::content(box_exp);\n            content_type content_diff = content - index::detail::content(ch_i.first);\n\n            children_contents[i] = geofeatures_boost::make_tuple(i, content_diff, content);\n\n            if ( content_diff < min_content_diff ||\n                 (content_diff == min_content_diff && content < min_content) )\n            {\n                min_content_diff = content_diff;\n                min_content = content;\n                choosen_index = i;\n            }\n        }\n\n        // is this assumption ok? if min_content_diff == 0 there is no overlap increase?\n\n        if ( min_content_diff < -std::numeric_limits<double>::epsilon() || std::numeric_limits<double>::epsilon() < min_content_diff )\n        {\n            size_t first_n_children_count = children_count;\n            if ( 0 < overlap_cost_threshold && overlap_cost_threshold < children.size() )\n            {\n                first_n_children_count = overlap_cost_threshold;\n                // rearrange by content_diff\n                // in order to calculate nearly minimum overlap cost\n                std::nth_element(children_contents.begin(), children_contents.begin() + first_n_children_count, children_contents.end(), content_diff_less);\n            }\n\n            // calculate minimum or nearly minimum overlap cost\n            choosen_index = choose_by_minimum_overlap_cost_first_n(children, indexable, first_n_children_count, children_count, children_contents);\n        }\n\n        return choosen_index;\n    }\n\n    static inline bool content_diff_less(geofeatures_boost::tuple<size_t, content_type, content_type> const& p1, geofeatures_boost::tuple<size_t, content_type, content_type> const& p2)\n    {\n        return geofeatures_boost::get<1>(p1) < geofeatures_boost::get<1>(p2) ||\n               (geofeatures_boost::get<1>(p1) == geofeatures_boost::get<1>(p2) && geofeatures_boost::get<2>(p1) < geofeatures_boost::get<2>(p2));\n    }\n\n    template <typename Indexable, typename ChildrenContents>\n    static inline size_t choose_by_minimum_overlap_cost_first_n(children_type const& children,\n                                                                Indexable const& indexable,\n                                                                size_t const first_n_children_count,\n                                                                size_t const children_count,\n                                                                ChildrenContents const& children_contents)\n    {\n        BOOST_GEOMETRY_INDEX_ASSERT(first_n_children_count <= children_count, \"unexpected value\");\n        BOOST_GEOMETRY_INDEX_ASSERT(children_contents.size() == children_count, \"unexpected number of elements\");\n\n        // choose index with smallest overlap change value, or content change or smallest content\n        size_t choosen_index = 0;\n        content_type smallest_overlap_diff = (std::numeric_limits<content_type>::max)();\n        content_type smallest_content_diff = (std::numeric_limits<content_type>::max)();\n        content_type smallest_content = (std::numeric_limits<content_type>::max)();\n\n        // for each child node\n        for (size_t i = 0 ; i < first_n_children_count ; ++i )\n        {\n            child_type const& ch_i = children[i];\n\n            Box box_exp(ch_i.first);\n            // calculate expanded box of child node ch_i\n            geometry::expand(box_exp, indexable);\n\n            content_type overlap_diff = 0;\n\n            // calculate overlap\n            for ( size_t j = 0 ; j < children_count ; ++j )\n            {\n                if ( i != j )\n                {\n                    child_type const& ch_j = children[j];\n\n                    content_type overlap_exp = index::detail::intersection_content(box_exp, ch_j.first);\n                    if ( overlap_exp < -std::numeric_limits<content_type>::epsilon() || std::numeric_limits<content_type>::epsilon() < overlap_exp )\n                    {\n                        overlap_diff += overlap_exp - index::detail::intersection_content(ch_i.first, ch_j.first);\n                    }\n                }\n            }\n\n            content_type content = geofeatures_boost::get<2>(children_contents[i]);\n            content_type content_diff = geofeatures_boost::get<1>(children_contents[i]);\n\n            // update result\n            if ( overlap_diff < smallest_overlap_diff ||\n                ( overlap_diff == smallest_overlap_diff && ( content_diff < smallest_content_diff ||\n                ( content_diff == smallest_content_diff && content < smallest_content ) )\n                ) )\n            {\n                smallest_overlap_diff = overlap_diff;\n                smallest_content_diff = content_diff;\n                smallest_content = content;\n                choosen_index = i;\n            }\n        }\n\n        return choosen_index;\n    }\n\n    template <typename Indexable>\n    static inline size_t choose_by_minimum_content_cost(children_type const& children, Indexable const& indexable)\n    {\n        size_t children_count = children.size();\n\n        // choose index with smallest content change or smallest content\n        size_t choosen_index = 0;\n        content_type smallest_content_diff = (std::numeric_limits<content_type>::max)();\n        content_type smallest_content = (std::numeric_limits<content_type>::max)();\n\n        // choose the child which requires smallest box expansion to store the indexable\n        for ( size_t i = 0 ; i < children_count ; ++i )\n        {\n            child_type const& ch_i = children[i];\n\n            // expanded child node's box\n            Box box_exp(ch_i.first);\n            geometry::expand(box_exp, indexable);\n\n            // areas difference\n            content_type content = index::detail::content(box_exp);\n            content_type content_diff = content - index::detail::content(ch_i.first);\n\n            // update the result\n            if ( content_diff < smallest_content_diff ||\n                ( content_diff == smallest_content_diff && content < smallest_content ) )\n            {\n                smallest_content_diff = content_diff;\n                smallest_content = content;\n                choosen_index = i;\n            }\n        }\n\n        return choosen_index;\n    }\n};\n\n}} // namespace detail::rtree\n\n}}} // namespace geofeatures_boost::geometry::index\n\n#endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_RSTAR_CHOOSE_NEXT_NODE_HPP\n", "meta": {"hexsha": "0f7e7d0ce527b51f1d803a76712dfe9f58cacdc3", "size": 10307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/geometry/index/detail/rtree/rstar/choose_next_node.hpp", "max_stars_repo_name": "tonystone/geofeatures", "max_stars_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "boost/boost/geometry/index/detail/rtree/rstar/choose_next_node.hpp", "max_issues_repo_name": "tonystone/geofeatures", "max_issues_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "boost/boost/geometry/index/detail/rtree/rstar/choose_next_node.hpp", "max_forks_repo_name": "tonystone/geofeatures", "max_forks_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 44.047008547, "max_line_length": 184, "alphanum_fraction": 0.6396623654, "num_tokens": 2024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.18410723351160727}}
{"text": "//\n//  TDF SDK\n//\n//  Created by Sujan Reddy on 2019/04/16\n//  Copyright 2019 Virtru Corporation\n//\n\n#define BOOST_TEST_MODULE test_gcm_decoding_suite\n\n#include \"gcm_decryption.h\"\n#include \"bytes.h\"\n#include \"tdf_exception.h\"\n#include \"crypto_utils.h\"\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(test_gcm_decoding_suite)\n\n    constexpr size_t kChunkSize = 25u;\n    constexpr size_t kBufferSize = 1024u;\n\n    using namespace std::string_literals;\n    using namespace virtru::crypto;\n\n    const static auto kPlainText =\n            \"Ehrsam, Meyer, Smith and Tuchman invented the Cipher Block Chaining (CBC) mode of operation in 1976. \"\n            \"In CBC mode, each block of plaintext is XORed with the previous ciphertext block before being encrypted. \"\n            \"This way, each ciphertext block depends on all plaintext blocks processed up to that point. \"\n            \"To make each message unique, an initialization vector must be used in the first block.\"s;\n\n    const static auto kEncryptedAes256GCMBase64 =\n            \"RFo0e8Q+dFtuBtMh0VGZk5u7BlXwUZvSbtPEZNJlrm5b893voEVhuqnQNF7HoPAN/Un0OL72cUJiLc8h0ufHhA6L3VtXFqSXTr+ebsphfTW2HI\"\n            \"kV7s3p4MD2eg/XwjsAt4FxkYV/FoeQti8TSlkCfytnq6ClqQnYYw00UKNHoAb7uromnTz/IBeRRvBxQgg26arS5AvIHD9UdN4LfAvTXcsn+OfK\"\n            \"9mWhiM9A6WAJSr/D/LXgvn6YLmtzd5txDpYrpR/2H6AI1yJDuv5CXjrsxbK1kk2gORWSCqozACQXnMT1v3nnSwr+DT6rXZ/ZdS5jl3hOdqQnCU\"\n            \"477M2pJ1mWh87pmb6w9TyGqvwpuvc2Y36Z03LbrXPJw/sQWhRDIUtWTnPJsHKch/H+Dbw6Tdj7HnJb4o/7+IT9GpvgnDgNJ55yfZsAU655+Cag\"\n            \"X5tCvCA+hYixxsD+/J5e+frs+SBacKQzNeq01IxA0vsVkoSryG+4sFu3nZI/gtgtu1vL693B\"s;\n\n    const static std::array<std :: uint8_t, 32u> kSymmetricKey = {\n            0xf0, 0x5b, 0x5f, 0xab, 0x91, 0x60, 0xf3, 0xc6,\n            0x51, 0x6a, 0x83, 0x3e, 0x82, 0xa3, 0x56, 0x62,\n            0x65, 0xb1, 0x68, 0x01, 0xf2, 0x9f, 0x9a, 0x55,\n            0xe2, 0x01, 0xba, 0xc6, 0x8a, 0xb8, 0x91, 0xf6\n    };\n\n    const static std::array<std :: uint8_t, 12u> kIV = {\n            0x1a, 0x5f, 0x26, 0xf9, 0x5f, 0x81,\n            0xf4, 0x42, 0x94, 0x60, 0x3b, 0x73\n    };\n\n    /// For testing message data authenticity (integrity).\n    static std::array<std :: uint8_t, 16u> kAuthTagNoAad = {0x6c, 0x61, 0xc4, 0x6b, 0x8f, 0x80, 0x8e, 0x27, 0x67, 0x76, 0xaa, 0x24, 0xbb, 0x1d, 0x10, 0x77};\n    const static std::vector<std :: uint8_t> kAuthAad = {0xeb, 0xfe, 0xa8, 0x74, 0x64, 0x28, 0x80, 0x96, 0x7b, 0x8a, 0x2a, 0x5f};\n    static std::array<std :: uint8_t, 16> kAuthTagForDefinedAad = {0xf3, 0xc1, 0x92, 0x81, 0x89, 0xe8, 0x9, 0x4, 0x61, 0x5f, 0xc1, 0x38, 0x5, 0x44, 0x7a, 0xb8};\n\n\n    BOOST_AUTO_TEST_CASE(test_gcm_decoding_with_no_aad) {\n\n        auto decoder = GCMDecryption::create(toBytes(kSymmetricKey), toBytes(kIV));\n        auto cipherText = base64Decode(toBytes(kEncryptedAes256GCMBase64));\n\n        ByteArray<kBufferSize > buffer;\n        auto bufferSpan = WriteableBytes{buffer};\n\n        // This extra span is not required because decrypt updates\n        // the size but to exercise some span features.\n        auto outBufferSpan = bufferSpan;\n        decoder->decrypt(toBytes(cipherText), outBufferSpan);\n\n        auto authTag = WriteableBytes{ toWriteableBytes(kAuthTagNoAad) };\n        decoder->finish(authTag);\n\n        BOOST_TEST(toBytes(kPlainText) == toBytes(bufferSpan.first(outBufferSpan.size())));\n    }\n\n    BOOST_AUTO_TEST_CASE(test_gcm_decoding_with_same_io_buffer) {\n\n        auto cipherText = base64Decode(toBytes(kEncryptedAes256GCMBase64));\n        std::vector<gsl::byte> buffer(cipherText.size());\n        std::transform(cipherText.begin(), cipherText.end(), buffer.begin(),\n                       [] (char c) { return gsl::byte(c); });\n\n        auto writeableBytes = toWriteableBytes(buffer);\n        auto decoder = GCMDecryption::create(toBytes(kSymmetricKey), toBytes(kIV));\n\n        /// Passing the same buffer as input and output\n        decoder->decrypt(writeableBytes, writeableBytes);\n\n        auto authTag = WriteableBytes{ toWriteableBytes(kAuthTagNoAad) };\n        decoder->finish(authTag);\n        \n        std::string decryptedMessage(reinterpret_cast<const char *>(&writeableBytes[0]), writeableBytes.size());\n        BOOST_TEST(kPlainText == decryptedMessage);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_gcm_encoding_with_stream_and_no_aad) {\n        \n        auto cipherText = base64Decode(toBytes(kEncryptedAes256GCMBase64));\n        auto decoder = GCMDecryption::create(toBytes(kSymmetricKey), toBytes(kIV));\n        \n        ByteArray<kBufferSize> buffer;\n        const auto bufferSpan = WriteableBytes{buffer};\n        \n        size_t numberOfEncryptedBytes = 0u;\n        size_t numberOfBytesToEncrypt = cipherText.size();\n        \n        while (numberOfBytesToEncrypt) {\n            \n            const auto inBufferSpan = toBytes(cipherText).subspan(cipherText.size() - numberOfBytesToEncrypt,\n                                                                  (std::min)(kChunkSize, numberOfBytesToEncrypt));\n            \n            auto outBufferSpan = bufferSpan.subspan(numberOfEncryptedBytes);\n            decoder->decrypt(inBufferSpan, outBufferSpan);\n            \n            numberOfBytesToEncrypt -= inBufferSpan.size();\n            numberOfEncryptedBytes += outBufferSpan.size();\n        }\n\n        auto authTag = WriteableBytes{ toWriteableBytes(kAuthTagNoAad) };\n        decoder->finish(authTag);\n        BOOST_TEST(toBytes(kPlainText) == toBytes(bufferSpan.first(numberOfEncryptedBytes)));\n    }\n\n    BOOST_AUTO_TEST_CASE(test_gcm_decoding_with_small_out_buffer ) {\n        \n        auto decoder = GCMDecryption::create(toBytes(kSymmetricKey), toBytes(kIV));\n        auto cipherText = base64Decode(toBytes(kEncryptedAes256GCMBase64));\n\n        std::vector<gsl :: byte> outBuffer(cipherText.size() - 1);\n        auto outBufferSpan = WriteableBytes{outBuffer};\n    \n        BOOST_CHECK_THROW(decoder->decrypt(toBytes(cipherText), outBufferSpan), virtru::Exception);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_gcm_decoding_with_defined_aad) {\n        \n        auto decoder = GCMDecryption::create(toBytes(kSymmetricKey), toBytes(kIV), toBytes(kAuthAad));\n        auto cipherText = base64Decode(toBytes(kEncryptedAes256GCMBase64));\n        \n        gsl::byte buffer[kBufferSize];\n        auto bufferSpan = WriteableBytes { buffer };\n        \n        decoder->decrypt(toBytes(cipherText), bufferSpan);\n\n        auto authTag = WriteableBytes{ toWriteableBytes(kAuthTagForDefinedAad)};\n        decoder->finish(authTag);\n        \n        BOOST_TEST(toBytes(kPlainText) == toBytes(bufferSpan));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "a7d8c7e47f4ed0667b5e1a24190d3e6e7e9d2078", "size": 6607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/test_gcm_decryption.cpp", "max_stars_repo_name": "opentdf/client-cpp", "max_stars_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "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/tests/test_gcm_decryption.cpp", "max_issues_repo_name": "opentdf/client-cpp", "max_issues_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-01-31T14:42:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T22:44:54.000Z", "max_forks_repo_path": "src/tests/test_gcm_decryption.cpp", "max_forks_repo_name": "opentdf/client-cpp", "max_forks_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-09T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T18:40:47.000Z", "avg_line_length": 43.4671052632, "max_line_length": 160, "alphanum_fraction": 0.6820039352, "num_tokens": 2120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.18389260723565776}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2014 Joel de Guzman\n    Copyright (c) 2001-2011 Hartmut Kaiser\n    Copyright (c) 2011 Jan Frederick Eick\n    Copyright (c) 2011 Christopher Jefferson\n    Copyright (c) 2006 Stephen Nutt\n    Copyright (c) 2019 T. Zachary Laine\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_PARSER_DETAIL_NUMERIC_HPP\n#define BOOST_PARSER_DETAIL_NUMERIC_HPP\n\n#include <boost/spirit/home/x3/numeric/real_policies.hpp>\n#include <boost/spirit/home/x3/support/numeric_utils/detail/extract_int.hpp>\n#include <boost/spirit/home/x3/support/numeric_utils/extract_real.hpp>\n\n\nnamespace boost { namespace parser { namespace detail_spirit_x3 {\n\n    // Copied from\n    // boost/spirit/home/x3/support/numeric_utils/detail/extract_int.hpp\n    // (Boost 1.67),and modified for use with iterator, sentinel pairs:\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  extract_int_impl: main code for extracting integers\n    ///////////////////////////////////////////////////////////////////////////\n#define BOOST_PARSER_NUMERIC_INNER_LOOP(z, x, data)                             \\\n        if (!spirit::x3::detail::check_max_digits<MaxDigits>::call(count + leading_zeros) \\\n            || it == last)                                                      \\\n            break;                                                              \\\n        ch = *it;                                                               \\\n        if (!radix_check::is_valid(ch) || !extractor::call(ch, count, val))     \\\n            break;                                                              \\\n        ++it;                                                                   \\\n        ++count;                                                                \\\n    /**/\n\n    template <\n        typename T, unsigned Radix, unsigned MinDigits, int MaxDigits\n      , typename Accumulator = spirit::x3::detail::positive_accumulator<Radix>\n      , bool Accumulate = false\n    >\n    struct extract_int_impl\n    {\n        template <typename Iterator, typename Sentinel, typename Attribute>\n        inline static bool\n        parse_main(\n            Iterator& first\n          , Sentinel last\n          , Attribute& attr)\n        {\n            typedef spirit::x3::detail::radix_traits<Radix> radix_check;\n            typedef spirit::x3::detail::int_extractor<Radix, Accumulator, MaxDigits> extractor;\n            typedef typename\n                boost::detail::iterator_traits<Iterator>::value_type\n            char_type;\n\n            Iterator it = first;\n            std::size_t leading_zeros = 0;\n            if (!Accumulate)\n            {\n                // skip leading zeros\n                while (it != last && *it == '0' && leading_zeros < MaxDigits)\n                {\n                    ++it;\n                    ++leading_zeros;\n                }\n            }\n\n            typedef typename\n                spirit::x3::traits::attribute_type<Attribute>::type\n            attribute_type;\n\n            attribute_type val = Accumulate ? attr : attribute_type(0);\n            std::size_t count = 0;\n            char_type ch;\n\n            while (true)\n            {\n                BOOST_PP_REPEAT(\n                    3\n                  , BOOST_PARSER_NUMERIC_INNER_LOOP, _)\n            }\n\n            if (count + leading_zeros >= MinDigits)\n            {\n                spirit::x3::traits::move_to(val, attr);\n                first = it;\n                return true;\n            }\n            return false;\n        }\n\n        template <typename Iterator, typename Sentinel>\n        inline static bool\n        parse(\n            Iterator& first\n          , Sentinel last\n          , spirit::x3::unused_type)\n        {\n            T n = 0; // must calculate value to detect over/underflow\n            return parse_main(first, last, n);\n        }\n\n        template <typename Iterator, typename Sentinel, typename Attribute>\n        inline static bool\n        parse(\n            Iterator& first\n          , Sentinel last\n          , Attribute& attr)\n        {\n            return parse_main(first, last, attr);\n        }\n    };\n#undef BOOST_PARSER_NUMERIC_INNER_LOOP\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  extract_int_impl: main code for extracting integers\n    //  common case where MinDigits == 1 and MaxDigits = -1\n    ///////////////////////////////////////////////////////////////////////////\n#define BOOST_PARSER_NUMERIC_INNER_LOOP(z, x, data)                             \\\n        if (it == last)                                                         \\\n            break;                                                              \\\n        ch = *it;                                                               \\\n        if (!radix_check::is_valid(ch))                                         \\\n            break;                                                              \\\n        if (!extractor::call(ch, count, val))                                   \\\n            return false;                                                       \\\n        ++it;                                                                   \\\n        ++count;                                                                \\\n    /**/\n\n    template <typename T, unsigned Radix, typename Accumulator, bool Accumulate>\n    struct extract_int_impl<T, Radix, 1, -1, Accumulator, Accumulate>\n    {\n        template <typename Iterator, typename Sentinel, typename Attribute>\n        inline static bool\n        parse_main(\n            Iterator& first\n          , Sentinel last\n          , Attribute& attr)\n        {\n            typedef spirit::x3::detail::radix_traits<Radix> radix_check;\n            typedef spirit::x3::detail::int_extractor<Radix, Accumulator, -1> extractor;\n            typedef typename\n                boost::detail::iterator_traits<Iterator>::value_type\n            char_type;\n\n            Iterator it = first;\n            std::size_t count = 0;\n            if (!Accumulate)\n            {\n                // skip leading zeros\n                while (it != last && *it == '0')\n                {\n                    ++it;\n                    ++count;\n                }\n\n                if (it == last)\n                {\n                    if (count == 0) // must have at least one digit\n                        return false;\n                    attr = 0;\n                    first = it;\n                    return true;\n                }\n            }\n\n            typedef typename\n                spirit::x3::traits::attribute_type<Attribute>::type\n            attribute_type;\n\n            attribute_type val = Accumulate ? attr : attribute_type(0);\n            char_type ch = *it;\n\n            if (!radix_check::is_valid(ch) || !extractor::call(ch, 0, val))\n            {\n                if (count == 0) // must have at least one digit\n                    return false;\n                spirit::x3::traits::move_to(val, attr);\n                first = it;\n                return true;\n            }\n\n            count = 0;\n            ++it;\n            while (true)\n            {\n                BOOST_PP_REPEAT(\n                    3\n                  , BOOST_PARSER_NUMERIC_INNER_LOOP, _)\n            }\n\n            spirit::x3::traits::move_to(val, attr);\n            first = it;\n            return true;\n        }\n\n        template <typename Iterator, typename Sentinel>\n        inline static bool\n        parse(\n            Iterator& first\n          , Sentinel last\n          , spirit::x3::unused_type)\n        {\n            T n = 0; // must calculate value to detect over/underflow\n            return parse_main(first, last, n);\n        }\n\n        template <typename Iterator, typename Sentinel, typename Attribute>\n        inline static bool\n        parse(\n            Iterator& first\n          , Sentinel last\n          , Attribute& attr)\n        {\n            return parse_main(first, last, attr);\n        }\n    };\n\n#undef BOOST_PARSER_NUMERIC_INNER_LOOP\n\n\n    // Copied from boost/spirit/home/x3/support/numeric_utils/extract_int.hpp\n    // (Boost 1.67), and modified for use with iterator, sentinel pairs:\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  Extract the prefix sign (- or +), return true if a '-' was found\n    ///////////////////////////////////////////////////////////////////////////\n    template<typename Iterator, typename Sentinel>\n    inline bool extract_sign(Iterator & first, Sentinel last)\n    {\n        (void)last;                  // silence unused warnings\n        BOOST_ASSERT(first != last); // precondition\n\n        // Extract the sign\n        bool neg = *first == '-';\n        if (neg || (*first == '+'))\n        {\n            ++first;\n            return neg;\n        }\n        return false;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // Low level unsigned integer parser\n    ///////////////////////////////////////////////////////////////////////////\n    template <typename T, unsigned Radix, unsigned MinDigits, int MaxDigits\n      , bool Accumulate = false>\n    struct extract_uint\n    {\n        // check template parameter 'Radix' for validity\n        static_assert(\n            (Radix >= 2 && Radix <= 36),\n            \"Error Unsupported Radix\");\n\n        template <typename Iterator, typename Sentinel>\n        inline static bool call(Iterator& first, Sentinel last, T& attr)\n        {\n            if (first == last)\n                return false;\n\n            typedef extract_int_impl<\n                T\n              , Radix\n              , MinDigits\n              , MaxDigits\n              , spirit::x3::detail::positive_accumulator<Radix>\n              , Accumulate>\n            extract_type;\n\n            Iterator save = first;\n            if (!extract_type::parse(first, last, attr))\n            {\n                first = save;\n                return false;\n            }\n            return true;\n        }\n    };\n\n    ///////////////////////////////////////////////////////////////////////////\n    // Low level signed integer parser\n    ///////////////////////////////////////////////////////////////////////////\n    template <typename T, unsigned Radix, unsigned MinDigits, int MaxDigits>\n    struct extract_int\n    {\n        // check template parameter 'Radix' for validity\n        static_assert(\n            (Radix == 2 || Radix == 8 || Radix == 10 || Radix == 16),\n            \"Error Unsupported Radix\");\n\n        template <typename Iterator, typename Sentinel>\n        inline static bool call(Iterator& first, Sentinel last, T& attr)\n        {\n            if (first == last)\n                return false;\n\n            typedef extract_int_impl<\n                T, Radix, MinDigits, MaxDigits>\n            extract_pos_type;\n\n            typedef extract_int_impl<\n                T, Radix, MinDigits, MaxDigits, spirit::x3::detail::negative_accumulator<Radix> >\n            extract_neg_type;\n\n            Iterator save = first;\n            bool hit = detail_spirit_x3::extract_sign(first, last);\n            if (hit)\n                hit = extract_neg_type::parse(first, last, attr);\n            else\n                hit = extract_pos_type::parse(first, last, attr);\n\n            if (!hit)\n            {\n                first = save;\n                return false;\n            }\n            return true;\n        }\n    };\n\n    // Copied from boost/spirit/home/x3/support/numeric_utils/extract_real.hpp\n    // (Boost 1.67), and modified for use with iterator, sentinel pairs:\n\n    template <typename T, typename RealPolicies>\n    struct extract_real\n    {\n        template <typename Iterator, typename Sentinel, typename Attribute>\n        static bool\n        parse(Iterator& first, Sentinel last, Attribute& attr,\n            RealPolicies const& p)\n        {\n            if (first == last)\n                return false;\n            Iterator save = first;\n\n            // Start by parsing the sign. neg will be true if\n            // we got a \"-\" sign, false otherwise.\n            bool neg = detail_spirit_x3::extract_sign(first, last);\n\n            // Now attempt to parse an integer\n            T n = 0;\n            bool got_a_number = p.parse_n(first, last, n);\n\n            // If we did not get a number it might be a NaN, Inf or a leading\n            // dot.\n            if (!got_a_number)\n            {\n                // Check whether the number to parse is a NaN or Inf\n                if (p.parse_nan(first, last, n) ||\n                    p.parse_inf(first, last, n))\n                {\n                    // If we got a negative sign, negate the number\n                    spirit::x3::traits::move_to(spirit::x3::extension::negate(neg, n), attr);\n                    return true;    // got a NaN or Inf, return early\n                }\n\n                // If we did not get a number and our policies do not\n                // allow a leading dot, fail and return early (no-match)\n                if (!p.allow_leading_dot)\n                {\n                    first = save;\n                    return false;\n                }\n            }\n\n            bool e_hit = false;\n            int frac_digits = 0;\n\n            // Try to parse the dot ('.' decimal point)\n            if (p.parse_dot(first, last))\n            {\n                // We got the decimal point. Now we will try to parse\n                // the fraction if it is there. If not, it defaults\n                // to zero (0) only if we already got a number.\n                Iterator savef = first;\n                if (p.parse_frac_n(first, last, n))\n                {\n                    // Optimization note: don't compute frac_digits if T is\n                    // an unused_type. This should be optimized away by the compiler.\n                    if (!is_same<T, spirit::x3::unused_type>::value)\n                        frac_digits =\n                            static_cast<int>(std::distance(savef, first));\n                    BOOST_ASSERT(frac_digits >= 0);\n                }\n                else if (!got_a_number || !p.allow_trailing_dot)\n                {\n                    // We did not get a fraction. If we still haven't got a\n                    // number and our policies do not allow a trailing dot,\n                    // return no-match.\n                    first = save;\n                    return false;\n                }\n\n                // Now, let's see if we can parse the exponent prefix\n                e_hit = p.parse_exp(first, last);\n            }\n            else\n            {\n                // No dot and no number! Return no-match.\n                if (!got_a_number)\n                {\n                    first = save;\n                    return false;\n                }\n\n                // If we must expect a dot and we didn't see an exponent\n                // prefix, return no-match.\n                e_hit = p.parse_exp(first, last);\n                if (p.expect_dot && !e_hit)\n                {\n                    first = save;\n                    return false;\n                }\n            }\n\n            if (e_hit)\n            {\n                // We got the exponent prefix. Now we will try to parse the\n                // actual exponent. It is an error if it is not there.\n                int exp = 0;\n                if (p.parse_exp_n(first, last, exp))\n                {\n                    // Got the exponent value. Scale the number by\n                    // exp-frac_digits.\n                    spirit::x3::extension::scale(exp, frac_digits, n);\n                }\n                else\n                {\n                    // Oops, no exponent, return no-match.\n                    first = save;\n                    return false;\n                }\n            }\n            else if (frac_digits)\n            {\n                // No exponent found. Scale the number by -frac_digits.\n                spirit::x3::extension::scale(-frac_digits, n);\n            }\n            else if (spirit::x3::extension::is_equal_to_one(n))\n            {\n                // There is a chance of having to parse one of the 1.0#...\n                // styles some implementations use for representing NaN or Inf.\n\n                // Check whether the number to parse is a NaN or Inf\n                if (p.parse_nan(first, last, n) ||\n                    p.parse_inf(first, last, n))\n                {\n                    // If we got a negative sign, negate the number\n                    spirit::x3::traits::move_to(spirit::x3::extension::negate(neg, n), attr);\n                    return true;    // got a NaN or Inf, return immediately\n                }\n            }\n\n            // If we got a negative sign, negate the number\n            spirit::x3::traits::move_to(spirit::x3::extension::negate(neg, n), attr);\n\n            // Success!!!\n            return true;\n        }\n    };\n\n}}}\n\n#endif\n", "meta": {"hexsha": "75939e547cb5938a69753a7d7950e1a915cb45f8", "size": 17189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/parser/detail/numeric.hpp", "max_stars_repo_name": "tzlaine/yaml", "max_stars_repo_head_hexsha": "958716b79697d4501f57d10eca8d3024047f5e2d", "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/parser/detail/numeric.hpp", "max_issues_repo_name": "tzlaine/yaml", "max_issues_repo_head_hexsha": "958716b79697d4501f57d10eca8d3024047f5e2d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T02:01:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T02:13:51.000Z", "max_forks_repo_path": "include/boost/parser/detail/numeric.hpp", "max_forks_repo_name": "tzlaine/yaml", "max_forks_repo_head_hexsha": "958716b79697d4501f57d10eca8d3024047f5e2d", "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.4946921444, "max_line_length": 97, "alphanum_fraction": 0.4476700215, "num_tokens": 3286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.18389260372469995}}
{"text": "#include \"examples/cuttingstock.hpp\"\n#include \"examples/multipleknapsack.hpp\"\n#include \"examples/binpackingwithconflicts.hpp\"\n#include \"examples/capacitatedvehiclerouting.hpp\"\n#include \"examples/vehicleroutingwithtimewindows.hpp\"\n#include \"examples/capacitatedopenvehiclerouting.hpp\"\n#include \"examples/parallelschedulingwithfamilysetuptimestwct.hpp\"\n#include \"examples/starobservationscheduling.hpp\"\n\n#include \"columngenerationsolver/read_args.hpp\"\n\n#include <boost/program_options.hpp>\n\nusing namespace columngenerationsolver;\n\nnamespace po = boost::program_options;\n\nvoid run(\n        std::string algorithm,\n        std::string columngeneration_args_string,\n        const optimizationtools::Info& info,\n        Parameters& p)\n{\n    std::vector<std::string> algorithm_args\n        = boost::program_options::split_unix(algorithm);\n    std::vector<char*> algorithm_argv;\n    for (Counter i = 0; i < (Counter)algorithm_args.size(); ++i)\n        algorithm_argv.push_back(const_cast<char*>(algorithm_args[i].c_str()));\n\n    ColumnGenerationOptionalParameters columngeneration_parameters\n        = read_columngeneration_args(columngeneration_args_string);\n\n    if (algorithm_args[0] == \"columngeneration\") {\n        columngeneration_parameters.info = info;\n        columngeneration(p, columngeneration_parameters);\n    } else if (algorithm_args[0] == \"greedy\") {\n        GreedyOptionalParameters op;\n        op.info = info;\n        op.columngeneration_parameters = columngeneration_parameters;\n        greedy(p, op);\n    } else if (algorithm_args[0] == \"limiteddiscrepancysearch\") {\n        auto op = read_limiteddiscrepancysearch_args(algorithm_argv);\n        op.info = info;\n        op.columngeneration_parameters = columngeneration_parameters;\n        limiteddiscrepancysearch(p, op);\n    } else if (algorithm_args[0] == \"heuristictreesearch\") {\n        auto op = read_heuristictreesearch_args(algorithm_argv);\n        op.info = info;\n        op.columngeneration_parameters = columngeneration_parameters;\n        heuristictreesearch(p, op);\n    } else {\n        std::cerr << \"\\033[31m\" << \"ERROR, unknown algorithm: '\" << algorithm_args[0] << \"'.\\033[0m\" << std::endl;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n\n    // Parse program options\n\n    std::string problem = \"cuttingstock\";\n    std::string instance_path = \"\";\n    std::string output_path = \"\";\n    std::string certificate_path = \"\";\n    std::string format = \"\";\n    std::string algorithm = \"heuristictreesearch\";\n    std::string columngeneration_args_string = \"\";\n    double time_limit = std::numeric_limits<double>::infinity();\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help,h\", \"produce help message\")\n        (\"problem,p\", po::value<std::string>(&problem)->required(), \"set problem (required)\")\n        (\"input,i\", po::value<std::string>(&instance_path)->required(), \"set input path (required)\")\n        (\"output,o\", po::value<std::string>(&output_path), \"set JSON output path\")\n        (\"certificate,c\", po::value<std::string>(&certificate_path), \"set certificate path\")\n        (\"format,f\", po::value<std::string>(&format), \"set input file format (default: orlibrary)\")\n        (\"algorithm,a\", po::value<std::string>(&algorithm), \"set algorithm\")\n        (\"column-generation-parameters,g\", po::value<std::string>(&columngeneration_args_string), \"set column generation parameters\")\n        (\"time-limit,t\", po::value<double>(&time_limit), \"Time limit in seconds\\n  ex: 3600\")\n        (\"verbose,v\", \"\")\n        (\"print-instance\", \"\")\n        (\"print-solution\", \"\")\n        ;\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;;\n        return 1;\n    }\n    try {\n        po::notify(vm);\n    } catch (const po::required_option& e) {\n        std::cout << desc << std::endl;;\n        return 1;\n    }\n\n    optimizationtools::Info info = optimizationtools::Info()\n        .set_verbose(vm.count(\"verbose\"))\n        .set_time_limit(time_limit)\n        .set_json_output_path(output_path)\n        .set_sigint_handler()\n        ;\n\n    // Run algorithm\n\n    if (problem == \"cuttingstock\") {\n        cuttingstock::Instance instance(instance_path, format);\n        //if (vm.count(\"print-instance\")) TODO\n        //    std::cout << instance << std::endl;\n        Parameters p = cuttingstock::get_parameters(instance);\n        run(algorithm, columngeneration_args_string, info, p);\n\n    } else if (problem == \"multipleknapsack\") {\n        multipleknapsack::Instance instance(instance_path, format);\n        //if (vm.count(\"print-instance\")) TODO\n        //    std::cout << instance << std::endl;\n        Parameters p = multipleknapsack::get_parameters(instance);\n        run(algorithm, columngeneration_args_string, info, p);\n\n    } else if (problem == \"binpackingwithconflicts\") {\n        binpackingwithconflicts::Instance instance(instance_path, format);\n        //if (vm.count(\"print-instance\")) TODO\n        //    std::cout << instance << std::endl;\n        Parameters p = binpackingwithconflicts::get_parameters(instance);\n        run(algorithm, columngeneration_args_string, info, p);\n\n    } else if (problem == \"capacitatedvehiclerouting\") {\n        capacitatedvehiclerouting::Instance instance(instance_path, format);\n        //if (vm.count(\"print-instance\")) TODO\n        //    std::cout << instance << std::endl;\n        Parameters p = capacitatedvehiclerouting::get_parameters(instance);\n        run(algorithm, columngeneration_args_string, info, p);\n\n    } else if (problem == \"vehicleroutingwithtimewindows\") {\n        vehicleroutingwithtimewindows::Instance instance(instance_path, format);\n        //if (vm.count(\"print-instance\")) TODO\n        //    std::cout << instance << std::endl;\n        Parameters p = vehicleroutingwithtimewindows::get_parameters(instance);\n        run(algorithm, columngeneration_args_string, info, p);\n\n    } else if (problem == \"capacitatedopenvehiclerouting\") {\n        capacitatedopenvehiclerouting::Instance instance(instance_path, format);\n        if (vm.count(\"print-instance\"))\n            std::cout << instance << std::endl;\n        Parameters p = capacitatedopenvehiclerouting::get_parameters(instance);\n        run(algorithm, columngeneration_args_string, info, p);\n\n    } else if (problem == \"parallelschedulingwithfamilysetuptimestwct\") {\n        parallelschedulingwithfamilysetuptimestwct::Instance instance(instance_path, format);\n        if (vm.count(\"print-instance\"))\n            std::cout << instance << std::endl;\n        Parameters p = parallelschedulingwithfamilysetuptimestwct::get_parameters(instance);\n        run(algorithm, columngeneration_args_string, info, p);\n\n    } else if (problem == \"starobservationscheduling\") {\n        starobservationscheduling::Instance instance(instance_path, format);\n        //if (vm.count(\"print-instance\")) TODO\n        //    std::cout << instance << std::endl;\n        Parameters p = starobservationscheduling::get_parameters(instance);\n        run(algorithm, columngeneration_args_string, info, p);\n\n    } else {\n        std::cerr << \"\\033[31m\" << \"ERROR, unknown problem: '\" << problem << \"'.\\033[0m\" << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "30444be5e9f655f0cd5d0431a4c4752e058fa64c", "size": 7258, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/main.cpp", "max_stars_repo_name": "fontanf/columngenerationsolver", "max_stars_repo_head_hexsha": "f0261d0f621e2c342aeca86f404d5f92fff3fc7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T21:36:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T15:50:55.000Z", "max_issues_repo_path": "examples/main.cpp", "max_issues_repo_name": "fontanf/columngenerationsolver", "max_issues_repo_head_hexsha": "f0261d0f621e2c342aeca86f404d5f92fff3fc7a", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "fontanf/columngenerationsolver", "max_forks_repo_head_hexsha": "f0261d0f621e2c342aeca86f404d5f92fff3fc7a", "max_forks_repo_licenses": ["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.4444444444, "max_line_length": 133, "alphanum_fraction": 0.664508129, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18389260021374218}}
{"text": "\n#include \"slamdunk/include/camera_tracker.h\"\n#include \"slamdunk/include/pretty_printer.h\"\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <boost/timer/timer.hpp>\n\n#include <android/log.h>\n\n#include <time.h>\n\n#define  LOG_TAG2\t\"slamdunk_app\"\n#define  LOGI2(...)\t__android_log_print(ANDROID_LOG_INFO, LOG_TAG2, __VA_ARGS__)\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\nvoid slamdunk::FeatureTracker::signalMovedFrames(const VertexPoseSet& vset)\n{\n  // update the tree\n  if(vset.empty())\n    return;\n\n  bool ok = true;\n  for(VertexPoseSet::const_iterator it = vset.begin(); it != vset.end(); ++it)\n    ok &= m_tree.update(*it, Eigen::Vector2d((*it)->estimate().translation().x(), (*it)->estimate().translation().z()));\n\n  if(!ok && m_verbose)\n    std::cout << SLAM_DUNK_ERROR_STR(\"At least one frame has moved out of quad tree's bounds\") << std::endl;\n\n  // update the feature matcher\n  calcActiveWindow();\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\nvoid slamdunk::FeatureTracker::setFrames(const VertexPoseSet& vset)\n{\n  m_tree.clear();\n  if(vset.empty())\n  {\n    m_reference_vxs.clear();\n    return;\n  }\n\n  bool ok = true;\n  for(VertexPoseSet::const_iterator it = vset.begin(); it != vset.end(); ++it)\n    ok &= m_tree.insert(*it, Eigen::Vector2d((*it)->estimate().translation().x(), (*it)->estimate().translation().z()));\n\n  if(!ok && m_verbose)\n    std::cout << SLAM_DUNK_ERROR_STR(\"At least one frame is out of quad tree's bounds\") << std::endl;\n\n  // update the feature matcher\n  calcActiveWindow();\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\nvoid slamdunk::FeatureTracker::calcActiveWindow()\n{\n  boost::timer::cpu_timer stopwatch;\n\n  QuadTreeType::ElementList elems;\n  m_tree.query( m_last_tracked.m_pose.translation().x() - m_half_active_win_length,\n                m_last_tracked.m_pose.translation().z() - m_half_active_win_length,\n                2.*m_half_active_win_length, 2.*m_half_active_win_length, elems);\n  m_active_win_center = Eigen::Vector2d(m_last_tracked.m_pose.translation().x(), m_last_tracked.m_pose.translation().z());\n  m_active_win_pose = m_last_tracked.m_pose.cast<double>();\n\n  m_reference_vxs.clear();\n  std::vector<cv::Mat> frame_descriptors;\n\n  Eigen::Vector4f homv(0,0,0,1);\n  for(QuadTreeType::ElementList::const_iterator it = elems.begin(); it != elems.end(); ++it)\n    //if(m_last_tracked.m_pose.rotation().col(2).dot(it->m_data->estimate().rotation().col(2)) > m_min_pov_cosangle_th)\n    //{\n      //m_reference_vxs[frame_descriptors.size()] = it->m_data;\n      //frame_descriptors.push_back(static_cast<const FrameData*>(it->m_data->userData())->m_descriptors);\n    //}\n  {\n    const FrameData* fdata = static_cast<const FrameData*>(it->m_data->userData());\n    // Count features within the frustum\n    unsigned nfeats = 0;\n    for(std::vector<Eigen::Vector3f>::const_iterator kpit = fdata->m_keypoints.begin(); kpit < fdata->m_keypoints.end(); ++kpit)\n    {\n      homv.head<3>() = *kpit;\n      if(((m_frustum_mtx * homv).array() < 0).all())\n        ++nfeats;\n    }\n    if((float)nfeats/(float)fdata->m_keypoints.size() > m_perc_feat_overlap)\n    {\n      m_reference_vxs[frame_descriptors.size()] = it->m_data;\n      frame_descriptors.push_back(fdata->m_descriptors);\n    }\n  }\n  stopwatch.stop();\n\n  if(!frame_descriptors.empty())\n    m_matcher->setModels(frame_descriptors);\n  else\n    std::cout << SLAM_DUNK_ERROR_STR(\"Active window is empty: using last frame\") << std::endl;\n\n  if(m_verbose)\n    std::cout << SLAM_DUNK_INFO_STR(\"Active window updated with \" << m_reference_vxs.size() << \" frames >>> \")\n              << stopwatch.format() << std::endl;\n\n  if(m_deb_func)\n  {\n    StampedPoseVector poses;\n    for(std::map<int, VertexPoseConstPtr>::const_iterator it = m_reference_vxs.begin(); it != m_reference_vxs.end(); ++it)\n      poses.push_back(std::make_pair(static_cast<const FrameData*>(it->second->userData())->m_timestamp, it->second->estimate()));\n    m_deb_func(poses);\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\nvoid slamdunk::FeatureTracker::setFrustum(const Eigen::Matrix3f& inverse_kcam, int width, int height,\n                                        float near_plane, float far_plane)\n{\n  const Eigen::Vector3f& tl = inverse_kcam.col(2);\n  Eigen::Vector3f tr = tl; tr[0] += width*inverse_kcam(0,0);\n  Eigen::Vector3f bl = tl; bl[1] += height*inverse_kcam(1,1);\n  const Eigen::Vector3f br(tr[0], bl[1], 1.f);\n  const Eigen::Vector3f npl(0,0,near_plane);\n  const Eigen::Vector3f fpl(0,0,far_plane);\n\n  m_frustum_mtx.row(0).head<3>() = Eigen::Vector3f::UnitZ();\n                    m_frustum_mtx(0,3) = -1 * m_frustum_mtx.row(0).head<3>().dot(fpl);  // far\n  m_frustum_mtx.row(1).head<3>() = -1 * m_frustum_mtx.row(0).head<3>();\n                    m_frustum_mtx(1,3) = m_frustum_mtx.row(0).head<3>().dot(npl);       // near\n  m_frustum_mtx.row(2).head<3>() = tr.cross(tl).normalized(); m_frustum_mtx(2,3) = 0.f; // top\n  m_frustum_mtx.row(3).head<3>() = bl.cross(br).normalized(); m_frustum_mtx(3,3) = 0.f; // bottom\n  m_frustum_mtx.row(4).head<3>() = tl.cross(bl).normalized(); m_frustum_mtx(4,3) = 0.f; // left\n  m_frustum_mtx.row(5).head<3>() = br.cross(tr).normalized(); m_frustum_mtx(5,3) = 0.f; // right\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\nnamespace\n{\n  enum { SLAM_DUNK_FEATURE_GRID_SIZE = 4 };\n}\n\nbool slamdunk::FeatureTracker::track(const RGBDFrame& frame)\n{\n  boost::timer::cpu_timer stopwatch;\n\n  std::vector<cv::KeyPoint> kpts;\n  extractFrameData(frame, m_last_tracked.m_frame_data, &kpts);\n  if(m_last_tracked.m_frame_data.m_keypoints.size() < m_min_matches)\n  {\n    if(m_verbose) std::cout << SLAM_DUNK_WARNING_STR(\"Too few valid visual features...track failure\") << std::endl;\n    return false;\n  }\n\n  // frame-frame matching\n  std::vector<FMatch> ff_matches;\n  stopwatch.start();\n  m_matcher->match(m_last_tracked.m_frame_data.m_descriptors, ff_matches);\n  stopwatch.stop();\n  if(m_verbose) std::cout << SLAM_DUNK_INFO_STR(ff_matches.size() << \" matches found with previous frames >>> \" << stopwatch.format()) << std::endl;\n#ifndef NDEBUG\n  if(m_debug)\n  {\n    std::map<int, std::vector<cv::DMatch> > ref2matches;\n    for(unsigned i = 0; i < ff_matches.size(); ++i)\n    {\n      std::vector<cv::DMatch>& dmatches = ref2matches[ff_matches[i].m_model_idx];\n      dmatches.push_back(cv::DMatch(ff_matches[i].m_feat_idx, ff_matches[i].m_query_idx, 0));\n    }\n    for(std::map<int, std::vector<cv::DMatch> >::const_iterator dmit = ref2matches.begin(); dmit != ref2matches.end(); ++dmit)\n    {\n      VertexPoseConstPtr frame_vx = m_reference_vxs[dmit->first];\n      std::cout << SLAM_DUNK_DEBUG_STR(dmit->second.size() << \" matches with reference vx #\" << frame_vx->id()) << std::endl;\n      const FrameData* fd = static_cast<const FrameData*>(frame_vx->userData());\n      cv::Mat outimg;\n      cv::drawMatches(fd->m_image, fd->m_kpts2d,\n                      m_last_tracked.m_frame_data.m_image, m_last_tracked.m_frame_data.m_kpts2d,\n                      dmit->second, outimg);\n      cv::imshow(\"debug\", outimg);\n      cv::waitKey();\n    }\n  }\n#endif\n  if(ff_matches.size() < m_min_matches)\n  {\n    if(m_verbose) std::cout << SLAM_DUNK_WARNING_STR(\"Too few feature matches...track failure\") << std::endl;\n    return false;\n  }\n\n  //TODO prova matches\n  /*std::vector<std::vector<cv::DMatch> > allMatches;\n  for(unsigned i = 0; i < m_reference_vxs.size(); ++i)\n  {\n\t  std::vector<cv::DMatch> matches;\n\t  allMatches.push_back(matches);\n  }\n  for(unsigned i = 0; i < ff_matches.size(); ++i)\n  {\n\t  cv::DMatch match;\n\t  match.imgIdx = ff_matches[i].m_model_idx;\n\t  match.queryIdx = ff_matches[i].m_query_idx;\n\t  match.trainIdx = ff_matches[i].m_feat_idx;\n\t  allMatches[ff_matches[i].m_model_idx].push_back(match);\n  }\n  for(unsigned i = 0; i < m_reference_vxs.size(); ++i)\n  {\n\t  cv::Mat imgOut;\n\t  const FrameData* data = static_cm_overlapping_featuresast<const FrameData*>(m_reference_vxs[i]->userData());\n\t  cv::drawMatches(m_last_tracked.m_frame_data.m_image, m_last_tracked.m_frame_data.m_kpts2d, data->m_image, data->m_kpts2d, allMatches[i], imgOut);\n\t  std::stringstream ssf;\n\t  ssf << \"/sdcard/testImages/image\" << i << \".png\";\n\t  cv::imwrite(ssf.str(), imgOut);\n\n\t  cv::Mat imgOutF;\n\t  cv::drawKeypoints(data->m_image, data->m_kpts2d, imgOutF, cv::Scalar(0, 0, 255), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n\t  std::stringstream ssf2;\n\t  ssf2 << \"/sdcard/testImages/imageF\" << i << \".png\";\n\t  cv::imwrite(ssf2.str(), imgOutF);\n  }*/\n\n  // outlier rejection\n  std::vector<Eigen::Vector3f> ff_ref_kpts(ff_matches.size());\n  std::vector< std::pair<unsigned, unsigned> > ref_query_ids(ff_matches.size());\n  std::vector<VertexPoseConstPtr> ref_vxs(ff_matches.size());\n  for(unsigned i = 0; i < ff_matches.size(); ++i)\n  {\n    VertexPoseConstPtr frame_vx = m_reference_vxs[ff_matches[i].m_model_idx];\n\n    ff_ref_kpts[i] = frame_vx->estimate().cast<float>() *\n                      (static_cast<const FrameData*>(frame_vx->userData())->m_keypoints[ff_matches[i].m_feat_idx]);\n    ref_query_ids[i] = std::pair<unsigned, unsigned>(i, ff_matches[i].m_query_idx);\n    ref_vxs[i] = frame_vx;\n  }\n\n  /*for (int i = 0; i < ff_matches.size(); i++)\n  {\n\t  std::stringstream ss;\n\t  ss << \"ffRefKey: (\" << ff_ref_kpts[i].x() << \",\" << ff_ref_kpts[i].y() << \",\" <<\n\t\t\tff_ref_kpts[i].z() << \"); refQueryIds: (\" << ref_query_ids[i].first << \",\" <<\n\t\t\tref_query_ids[i].second << \"); refVxs: (\" << ref_vxs[i]->id() << \")\";\n\t  LOGI2(\"%s\", ss.str().data());\n  }*/\n\n  stopwatch.start();\n  clock_t start = clock();\n  m_outlier_rejection->findInliers(ff_ref_kpts, m_last_tracked.m_frame_data.m_keypoints, ref_query_ids);\n  stopwatch.stop();\n  clock_t end = clock();\n  std::stringstream ss;\n  ss << \"RANSAC: \" << (1000.0F * (float)(end - start) / (float)CLOCKS_PER_SEC);\n  LOGI2(\"%s\", ss.str().data());\n  const std::vector<unsigned>& rqi_inliers = m_outlier_rejection->getRefQueryInliers();\n  if(m_verbose) std::cout << SLAM_DUNK_INFO_STR(rqi_inliers.size() << \" inliers survived >>> \" << stopwatch.format()) << std::endl;\n#ifndef NDEBUG\n  if(m_debug)\n  {\n    std::map<VertexPoseConstPtr, std::vector<cv::DMatch> > ref2matches;\n    for(unsigned i = 0; i < rqi_inliers.size(); ++i)\n    {\n      const std::pair<unsigned, unsigned>& inlier_pair = ref_query_ids[rqi_inliers[i]];\n      std::vector<cv::DMatch>& dmatches = ref2matches[ ref_vxs[inlier_pair.first] ];\n      dmatches.push_back(cv::DMatch(ff_matches[inlier_pair.first].m_feat_idx, inlier_pair.second, 0));\n    }\n    for(std::map<VertexPoseConstPtr, std::vector<cv::DMatch> >::const_iterator dmit = ref2matches.begin(); dmit != ref2matches.end(); ++dmit)\n    {\n      const VertexPoseConstPtr frame_vx = dmit->first;\n      std::cout << SLAM_DUNK_DEBUG_STR(dmit->second.size() << \" matches with reference vx #\" << frame_vx->id()) << std::endl;\n      const FrameData* fd = static_cast<const FrameData*>(frame_vx->userData());\n      cv::Mat outimg;\n      cv::drawMatches(fd->m_image, fd->m_kpts2d,\n                      m_last_tracked.m_frame_data.m_image, m_last_tracked.m_frame_data.m_kpts2d,\n                      dmit->second, outimg);\n      cv::imshow(\"debug\", outimg);\n      cv::waitKey();\n    }\n  }\n#endif\n  if(rqi_inliers.size() < m_min_matches)\n  {\n    if(m_verbose) std::cout << SLAM_DUNK_WARNING_STR(\"Too few feature matches...track failure\") << std::endl;\n    return false;\n  }\n\n  // get the inliers\n  bool inlier_grid[SLAM_DUNK_FEATURE_GRID_SIZE*SLAM_DUNK_FEATURE_GRID_SIZE];\n  //bool feature_grid[SLAM_DUNK_FEATURE_GRID_SIZE*SLAM_DUNK_FEATURE_GRID_SIZE];\n  std::memset(inlier_grid, false, SLAM_DUNK_FEATURE_GRID_SIZE*SLAM_DUNK_FEATURE_GRID_SIZE*sizeof(bool));\n  //std::memset(feature_grid, false, SLAM_DUNK_FEATURE_GRID_SIZE*SLAM_DUNK_FEATURE_GRID_SIZE*sizeof(bool));\n\n  //int min_x = frame.m_color_image.cols, max_x = 0, min_y = frame.m_color_image.rows, max_y = 0;\n\n  m_last_tracked.m_ff_matches.resize(rqi_inliers.size());\n  std::vector< std::pair<unsigned, unsigned> > ref_query_ids_inliers;\n\n  m_last_tracked_keyframes.clear();\n  for(unsigned i = 0; i < rqi_inliers.size(); ++i)\n  {\n    const std::pair<unsigned, unsigned>& inlier_pair = ref_query_ids[rqi_inliers[i]];\n    ref_query_ids_inliers.push_back(inlier_pair);\n\n    FrameToFrameMatch& ffm = m_last_tracked.m_ff_matches[i];\n    ffm.m_matching_frame_id = ref_vxs[inlier_pair.first]->id();\n    ffm.m_matching_frame_feat = ff_matches[inlier_pair.first].m_feat_idx;\n    ffm.m_ref_frame_feat = inlier_pair.second;\n    ffm.m_score = ff_matches[inlier_pair.first].m_match_score;\n\n    m_last_tracked_keyframes.insert(ffm.m_matching_frame_id);\n\n    const cv::KeyPoint& kp = kpts[ ffm.m_ref_frame_feat ];\n    //if(kp.pt.x < min_x) min_x = kp.pt.x;\n    //if(kp.pt.x > max_x) max_x = kp.pt.x;\n    //if(kp.pt.y < min_y) min_y = kp.pt.y;\n    //if(kp.pt.y > max_y) max_y = kp.pt.y;\n\n    const int ug = (int)(kp.pt.x * (float)SLAM_DUNK_FEATURE_GRID_SIZE / (float)frame.m_color_image.cols);\n    const int vg = (int)(kp.pt.y * (float)SLAM_DUNK_FEATURE_GRID_SIZE / (float)frame.m_color_image.rows);\n    assert(ug >= 0 && ug < SLAM_DUNK_FEATURE_GRID_SIZE);\n    assert(vg >= 0 && vg < SLAM_DUNK_FEATURE_GRID_SIZE);\n    inlier_grid[ug + vg*SLAM_DUNK_FEATURE_GRID_SIZE] = true;\n  }\n  //for(unsigned i = 0; i < m_last_tracked.m_frame_data.m_keypoints.size(); ++i)\n  //{\n    //const cv::KeyPoint& kp = kpts[i];\n    //const int ug = (int)(kp.pt.x * (float)SLAM_DUNK_FEATURE_GRID_SIZE / (float)frame.m_color_image.cols);\n    //const int vg = (int)(kp.pt.y * (float)SLAM_DUNK_FEATURE_GRID_SIZE / (float)frame.m_color_image.rows);\n    //assert(ug >= 0 && ug < SLAM_DUNK_FEATURE_GRID_SIZE);\n    //assert(vg >= 0 && vg < SLAM_DUNK_FEATURE_GRID_SIZE);\n    //feature_grid[ug + vg*SLAM_DUNK_FEATURE_GRID_SIZE] = true;\n  //}\n\n  // pose estimation\n  stopwatch.start();\n  slamdunk::estimateTransformationSVD(ff_ref_kpts, m_last_tracked.m_frame_data.m_keypoints, ref_query_ids_inliers, m_last_tracked.m_pose);\n  stopwatch.stop();\n  const Eigen::Isometry3d incremental_pose = m_last_tracked.m_pose.inverse() * m_active_win_pose;\n  const double cosTheta = (incremental_pose.rotation().trace()-1.)*0.5;\n  const float angleScore = (float)(cosTheta < 0.707106781 ? 0. : std::pow(2.*cosTheta*cosTheta -1., 2));\n  // overlapping score computation\n  m_last_tracked.m_overlapping_features = (float)std::count(inlier_grid, inlier_grid+SLAM_DUNK_FEATURE_GRID_SIZE*SLAM_DUNK_FEATURE_GRID_SIZE, true)\n  \t  \t  \t  \t  \t  \t  \t  \t  \t  \t  / (float)(SLAM_DUNK_FEATURE_GRID_SIZE*SLAM_DUNK_FEATURE_GRID_SIZE);\n  m_last_tracked.m_overlapping_score = 0.33333333f * (\n\t\t  m_last_tracked.m_overlapping_features\n\t\t  + angleScore\n\t\t  + (float)(1. - std::min(1., incremental_pose.translation().norm()*2.5/m_half_active_win_length))\n                                                      );\n\n  if(m_verbose)\n    std::cout << SLAM_DUNK_INFO_STR(\"Pose estimated by SVD (overlapping score: \")\n              << ((float)std::count(inlier_grid, inlier_grid+SLAM_DUNK_FEATURE_GRID_SIZE*SLAM_DUNK_FEATURE_GRID_SIZE, true)\n                    / (float)(SLAM_DUNK_FEATURE_GRID_SIZE*SLAM_DUNK_FEATURE_GRID_SIZE))/3. << \"+\"\n              << angleScore/3.f << \"+\"\n              << (1. - std::min(1., incremental_pose.translation().norm()*2.5/m_half_active_win_length))/3. << \"=\"\n              << m_last_tracked.m_overlapping_score << \") >>> \" << stopwatch.format() << std::endl;\n\n  return true;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////\nvoid slamdunk::FeatureTracker::updateOverlappingScore(Eigen::Isometry3d& new_estimated_pose)\n{\n\tm_last_tracked.m_pose = new_estimated_pose;\n\tconst Eigen::Isometry3d incremental_pose = m_last_tracked.m_pose.inverse() * m_active_win_pose;\n\tconst double cosTheta = (incremental_pose.rotation().trace() - 1.) * 0.5;\n\tconst float angleScore = (float)(cosTheta < 0.707106781 ? 0. : std::pow(2. * cosTheta * cosTheta - 1., 2));\n\t// overlapping score computation\n\tm_last_tracked.m_overlapping_score = 0.33333333f * (\n\t\t\tm_last_tracked.m_overlapping_features\n\t\t\t+ angleScore\n\t\t\t+ (float)(1. - std::min(1., incremental_pose.translation().norm() * 2.5 / m_half_active_win_length)));\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////\nvoid slamdunk::FeatureTracker::updateMap()\n{\n  // should we move the active window?\n  if( (((Eigen::Vector2d(m_last_tracked.m_pose.translation().x(), m_last_tracked.m_pose.translation().z()) -\n          m_active_win_center).cwiseAbs() - m_win_movement_step).array() > 0).any() )\n  {\n    if(m_verbose) std::cout << SLAM_DUNK_INFO_STR(\"Moving active window\") << std::endl;\n    calcActiveWindow();\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////\nvoid slamdunk::FeatureTracker::extractFrameData(const RGBDFrame& frame, FrameData& frame_data) const\n{\n  extractFrameData(frame, frame_data, NULL);\n}\n\nvoid slamdunk::FeatureTracker::extractFrameData(const RGBDFrame& frame, FrameData& frame_data, std::vector<cv::KeyPoint>* kpts_ptr) const\n{\n  boost::timer::cpu_timer stopwatch;\n\n  frame_data.m_timestamp = frame.m_timestamp;\n  // feature extraction\n  std::vector<cv::KeyPoint> kpts;\n  cv::Mat cvdesc;\n  if (m_use_detector_extractor)\n  {\n\t  stopwatch.start();\n\t  clock_t start = clock();\n\t  (*m_feature_detector_extractor)(frame.m_color_image, cv::Mat(), kpts, cvdesc, false);\n\t  clock_t end = clock();\n\t  stopwatch.stop();\n\t  std::stringstream ss;\n\t  ss << \"KEYPOINT DETECTION AND EXTRACTION: \" << (1000.0F * (float)(end - start) / (float)CLOCKS_PER_SEC) << \" >>> \" << cvdesc.rows;\n\t  LOGI2(\"%s\", ss.str().data());\n  }\n  else\n  {\n\t  stopwatch.start();\n\t  clock_t start = clock();\n\t  m_feature_detector->detect(frame.m_color_image, kpts);\n\t  clock_t end = clock();\n\t  std::stringstream ss;\n\t  ss << \"KEYPOINT DETECTION: \" << (1000.0F * (float)(end - start) / (float)CLOCKS_PER_SEC) << \" >>> \" << kpts.size();\n\t  LOGI2(\"%s\", ss.str().data());\n\t  start = clock();\n\t  m_feature_extractor->compute(frame.m_color_image, kpts, cvdesc);\n\t  stopwatch.stop();\n\t  end = clock();\n\t  stopwatch.stop();\n\t  std::stringstream ss2;\n\t  ss2 << \"FEATURE EXTRACTION: \" << (1000.0F * (float)(end - start) / (float)CLOCKS_PER_SEC) << \" >>> \" << cvdesc.rows;\n\t  LOGI2(\"%s\", ss2.str().data());\n  }\n  if(m_verbose) std::cout << SLAM_DUNK_INFO_STR(cvdesc.rows << \" features extracted >>> \" << stopwatch.format()) << std::endl;\n  if(m_debug)\n  {\n    std::cout << SLAM_DUNK_DEBUG_STR(\"Extracted Keypoints\") << std::endl;\n    cv::Mat outimg;\n    if(frame.m_color_image.channels() == 3) outimg = frame.m_color_image.clone();\n    else cv::cvtColor(frame.m_color_image, outimg, CV_GRAY2BGR);\n    cv::drawKeypoints(outimg, kpts, outimg, cv::Scalar::all(-1),\n                      cv::DrawMatchesFlags::DRAW_OVER_OUTIMG | cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n    cv::imshow(\"debug\", outimg);\n    cv::waitKey();\n  }\n\n  // keep only feats with a valid depth value\n  cv::Mat valid_desc(cvdesc.rows, cvdesc.cols, cvdesc.type());\n  unsigned feat_with_depth = 0;\n  frame_data.m_keypoints.clear();\n//#ifndef NDEBUG\n  frame_data.m_kpts2d.clear();\n  frame_data.m_image = frame.m_color_image;\n//#endif\n  for(unsigned i = 0; i < kpts.size() && feat_with_depth < m_max_feats_per_frame; ++i)\n  {\n    assert(kpts[0].response >= kpts[i].response);\n    const float& z = frame.m_depth_image(kpts[i].pt);\n    if(z > 0)\n    {\n      const Eigen::Vector3f pt3d = m_inverse_kcam * Eigen::Vector3f(kpts[i].pt.x*z, kpts[i].pt.y*z, z);\n      assert(std::isfinite(pt3d.x()) && std::isfinite(pt3d.y()) && std::isfinite(pt3d.z()) && std::abs(pt3d.z()) > 0.2);\n      frame_data.m_keypoints.push_back(pt3d);\n      if(kpts_ptr != NULL)\n        kpts_ptr->push_back(kpts[i]);\n    //#ifndef NDEBUG\n      frame_data.m_kpts2d.push_back(kpts[i]);\n    //#endif\n      cvdesc.row(i).copyTo(valid_desc.row(feat_with_depth));\n\n      ++feat_with_depth;\n    }\n  }\n  frame_data.m_descriptors = valid_desc.rowRange(0, feat_with_depth);\n\n  if(m_verbose) std::cout << SLAM_DUNK_INFO_STR(frame_data.m_descriptors.rows << \" features have a valid depth value\") << std::endl;\n#ifndef NDEBUG\n  if(m_debug)\n  {\n    std::cout << SLAM_DUNK_DEBUG_STR(\"Valid Keypoints\") << std::endl;\n    cv::Mat imgleft, imgright, outimg;\n    if(frame.m_color_image.channels() == 3)\n    {\n      imgleft = frame.m_color_image.clone();\n      imgright = frame.m_color_image.clone();\n    } else\n    {\n      cv::cvtColor(frame.m_color_image, imgleft, CV_GRAY2BGR);\n      cv::cvtColor(frame.m_color_image, imgright, CV_GRAY2BGR);\n    }\n    cv::drawKeypoints(imgleft, kpts, imgleft, cv::Scalar::all(-1),\n                      cv::DrawMatchesFlags::DRAW_OVER_OUTIMG | cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n    cv::drawKeypoints(imgright, frame_data.m_kpts2d, imgright, cv::Scalar::all(-1),\n                      cv::DrawMatchesFlags::DRAW_OVER_OUTIMG | cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n\n    outimg.create(imgleft.rows, imgleft.cols+imgright.cols, imgleft.type());\n    imgleft.copyTo(outimg.colRange(0, imgleft.cols));\n    imgright.copyTo(outimg.colRange(imgleft.cols, outimg.cols));\n\n    cv::imshow(\"debug\", outimg);\n    cv::waitKey();\n  }\n#endif\n}\n", "meta": {"hexsha": "e79853c98a2bfb0e445c96bde2133e84152282c3", "size": 21433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jni/slamdunk/src/feature_tracker.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": "jni/slamdunk/src/feature_tracker.cpp", "max_issues_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_issues_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_issues_repo_licenses": ["Apache-2.0"], "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": "jni/slamdunk/src/feature_tracker.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": 43.3866396761, "max_line_length": 148, "alphanum_fraction": 0.6496990622, "num_tokens": 6031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.18387042934433856}}
{"text": "/**\n * @file \n * @brief \n *\n * (c) 2010 the IceCube Collaboration\n *\n * $Id: I3SuperDST.cxx 173719 2019-06-04 16:18:41Z david.schultz $\n * @version $Revision: 173719 $\n * @date $Date: 2019-06-04 10:18:41 -0600 (Tue, 04 Jun 2019) $\n * @author Jakob van Santen <vansanten@wisc.edu>\n *\n */\n\n#include <cassert>\n\n#include <serialization/binary_object.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/utility.hpp>\n#include <boost/foreach.hpp>\n\n#include \"icetray/OMKey.h\"\n#include \"icetray/I3Units.h\"\n\n#include \"dataclasses/payload/I3SuperDST.h\"\n#include \"dataclasses/payload/I3SuperDSTUtils.h\"\n\n/* Maximum bit widths used in discretization */\n#define I3SUPERDSTCHARGESTAMP_TIME_BITS_V0   8\n#define I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0 6\n#define I3SUPERDSTCHARGESTAMP_BYTESIZE_V0    2\n\n#define I3SUPERDST_DOMID_BITS_V0     13\n#define I3SUPERDST_SLOP_BITS_V0       3\n#define I3SUPERDST_HEADER_BYTESIZE_V0 2\n\n/* Earliest representable time (relative to the readout window) */\nconst double I3SuperDST::tmin_ = -512.0;\n\nusing namespace I3SuperDSTUtils;\n\nI3SuperDSTChargeStamp::I3SuperDSTChargeStamp(double time, double charge, double width,\n    bool hlc, Discretization format) : timecode_(0), chargecode_(0), charge_overflow_(0),\n    version_(i3superdst_version_), kind_(hlc ? HLC : SLC), charge_format_(format)\n{\n\ti3_assert( time >= 0.0 );\n\ti3_assert( charge >= 0.0 );\n\t\n\t/* Don't truncate integer codes, since we need to relativize the times later. */\n\ttimecode_ = I3SuperDST::EncodeTime(time, 31, version_);\n\twidthcode_ = I3SuperDST::EncodeWidth(width, 31, version_);\n\tchargecode_ = I3SuperDST::EncodeCharge(charge, 31, version_, charge_format_);\n}\n\nvoid\nI3SuperDSTChargeStamp::SetTimeReference(const I3SuperDSTChargeStamp &other)\n{\n\ti3_assert(timecode_ >= other.timecode_);\n\t\n\ttimecode_ -= other.timecode_;\n}\n\ndouble\nI3SuperDSTChargeStamp::GetTime() const\n{\n\treturn I3SuperDST::DecodeTime(timecode_, version_);\n}\n\ndouble\nI3SuperDSTChargeStamp::GetWidth() const\n{\n\treturn I3SuperDST::DecodeWidth(widthcode_, version_);\n}\n\ndouble\nI3SuperDSTChargeStamp::GetCharge() const\n{\n\treturn I3SuperDST::DecodeCharge(chargecode_ + charge_overflow_,\n\t    version_, charge_format_);\n}\n\nbool\nI3SuperDSTChargeStamp::operator==(const I3SuperDSTChargeStamp& rhs) const {\n  return (this->timecode_ == rhs.timecode_ &&\n          this->widthcode_ == rhs.widthcode_ &&\n          this->chargecode_ == rhs.chargecode_ &&\n          this->charge_overflow_ == rhs.charge_overflow_ &&\n          this->version_ == rhs.version_ &&\n          this->kind_ == rhs.kind_ &&\n          this->charge_format_ == rhs.charge_format_);\n}\n\nI3SuperDSTReadout::I3SuperDSTReadout(const OMKey &om, bool hlc,\n    const std::list<I3RecoPulse>::const_iterator &start,\n    const std::list<I3RecoPulse>::const_iterator &end, double t0)\n{\n\tstd::list<I3RecoPulse>::const_iterator pulse_it = start;\n\n\tDiscretization format = (om.GetOM() > 60) ? LOG : LINEAR;\n\t\n\tfor ( ; pulse_it != end; pulse_it++) {\n\t\tstamps_.push_back(I3SuperDSTChargeStamp(pulse_it->GetTime()-t0,\n\t\t    std::max(pulse_it->GetCharge(), 0.0f),\n\t\t    std::max(pulse_it->GetWidth(), 1.0f), hlc, format));\n\t}\n\t\n\ttime_overflow_ = 0;\n\tom_ = om;\n\tkind_ = hlc ? I3SuperDSTChargeStamp::HLC : I3SuperDSTChargeStamp::SLC;\n\ti3_assert(start != end);\n\tstart_time_ = start->GetTime()-t0;\n}\n\nvoid\nI3SuperDSTReadout::SetTimeReference(const I3SuperDSTReadout &other)\n{\n\tconst I3SuperDSTChargeStamp &other_stamp = other.stamps_.front();\n\t\n\ti3_assert(start_time_ >= other.start_time_);\n\ti3_assert(other.stamps_.size() > 0);\n\t\n\t/* \n\t * Set the times of any secondary stamp relative to the one prior to\n\t * it, then set the time of the first stamp relative to first\n\t * stamp in the other readout.\n\t */\n\tRelativize();\n\tstamps_.front().SetTimeReference(other_stamp);\n}\n\nvoid\nI3SuperDSTReadout::Relativize()\n{\n\tstd::vector<I3SuperDSTChargeStamp>::reverse_iterator stamp_rit = stamps_.rbegin();\n\t/* \n\t * Set the time of each secondary stamp relative to the one\n\t * preceding it. (Reverse iterators are fun!)\n\t */\n\tfor ( ; stamp_rit != stamps_.rend()-1; stamp_rit++) {\n\t\ti3_assert(stamp_rit->GetTimeCode() >= (stamp_rit+1)->GetTimeCode());\n\t\tstamp_rit->SetTimeReference(*(stamp_rit+1));\n\t}\n}\n\ndouble\nI3SuperDSTReadout::GetTime() const\n{\n\ti3_assert(stamps_.size() != 0);\n\t\n\treturn (stamps_.front().GetTime() +\n\t    I3SuperDST::DecodeTime(time_overflow_, i3superdst_version_));\n}\n\nbool\nI3SuperDSTReadout::operator==(const I3SuperDSTReadout& rhs) const {\n  return (this->om_ == rhs.om_ &&\n          this->start_time_ == rhs.start_time_ &&\n          this->stamps_ == rhs.stamps_ &&\n          this->kind_ == rhs.kind_ &&\n          this->time_overflow_ == rhs.time_overflow_);\n}\n\nnamespace I3SuperDSTRecoPulseUtils {\n\tstatic bool\n\tTimeOrdering(const I3RecoPulse &p1, const I3RecoPulse &p2)\n\t{ return p1.GetTime() < p2.GetTime(); }\n\t\n\tstatic bool\n\tIsBorked(const I3RecoPulse &p1)\n\t{\n\t\treturn (!std::isfinite(p1.GetTime()) || !std::isfinite(p1.GetCharge()));\n\t}\n\n\tstatic bool\n\tHasLC(const I3RecoPulse &p1)\n\t{\n\t\treturn (p1.GetFlags() & I3RecoPulse::LC);\n\t}\n\n\tstatic bool\n\tShouldSplit(const OMKey &key, const I3RecoPulse &current,\n\t    const I3RecoPulse &previous)\n\t{\n\t\t/*\n\t\t * Split if pulses are not from the same launch. \n\t\t */\n\t\tstatic const double tmax = 6.45e3;\n\n\t\treturn (key.GetOM() > 60 || HasLC(current) != HasLC(previous)\n\t\t    || current.GetTime() - previous.GetTime() > tmax);\n\t}\n};\n\nvoid\nI3SuperDST::AddPulseMap(const I3RecoPulseSeriesMap &pulses, double t0)\n{\n\tI3RecoPulseSeriesMap::const_iterator map_iter;\n\tstd::list<I3RecoPulse> pulse_list;\n\tstd::list<I3RecoPulse>::const_iterator pulse_head, pulse_tail;\n\t\n\tunpacked_.reset();\n\t\n\t/* \n\t * Convert the pulse series map to a list of \"readouts\"\n\t * (pulses spaced closely in time in a single DOM)\n\t */ \n\tfor (map_iter = pulses.begin(); map_iter != pulses.end(); map_iter++) {\n\t\t/*\n\t\t * Get a time-ordered representation of the pulse series,\n\t\t * except those pulses with nonsensical charges or times.\n\t\t */\n\t\tusing namespace I3SuperDSTRecoPulseUtils;\n\t\tpulse_list.clear();\n\t\tstd::remove_copy_if(map_iter->second.begin(),\n\t\t    map_iter->second.end(), std::back_inserter(pulse_list),\n\t\t    IsBorked);\n\t\tif (pulse_list.size() == 0) continue;\n\t\tpulse_list.sort(TimeOrdering);\n\t\t\n\t\tpulse_head = pulse_list.begin();\n\t\tpulse_tail = boost::next(pulse_head);\n\t\t\n\t\tfor ( ; pulse_tail != pulse_list.end(); pulse_tail++) {\n\t\t\t/* \n\t\t\t * Split the preceding run off into its own readout\n\t\t\t * if it is from a different kind of launch or this is\n\t\t\t * and IceTop DOM (where we assume exactly one pulse\n\t\t\t * per launch)\n\t\t\t */\n\t\t\tif (ShouldSplit(map_iter->first, *pulse_tail,\n\t\t\t    *(pulse_head))) {\n\t\t\t\treadouts_.push_back(I3SuperDSTReadout(\n\t\t\t\t    map_iter->first, HasLC(*pulse_head),\n\t\t\t\t    pulse_head, pulse_tail, t0));\n\t\t\t\tpulse_head = pulse_tail;\n\t\t\t}\n\t\t}\n\t\t\n\t\t/* Push the remaining pulses into a readout. */\n\t\treadouts_.push_back(I3SuperDSTReadout(\n\t\t    map_iter->first, HasLC(*pulse_head), pulse_head, pulse_tail, t0));\n\t}\n}\n\nvoid\nI3SuperDST::AddPulseMap(const I3RecoPulseSeriesMap &pulses)\n{\n\t/* \n\t * Get the earliest leading-edge time present in the input.\n\t * This must be >= -512 ns to be representable.\n\t */\n\tconst double t0 = FindStartTime(pulses);\n\tif (t0 < tmin_)\n\t\tlog_fatal(\"First pulse time %g ns < %3.0f ns is unrepresentable! \"\n\t\t    \"Is this un-timeshifted simulation?\", t0, tmin_);\n\t\n\t/* \n\t * Convert the pulse series map to a list of \"readouts\"\n\t * (pulses spaced closely in time in a single DOM)\n\t */ \n\tAddPulseMap(pulses, tmin_);\n\n\t/* Sort the readouts by start time */\n\treadouts_.sort();\n\t\n\t/* Convert the absolute times in each readout to time deltas. */\n\tstd::list<I3SuperDSTReadout>::reverse_iterator list_rit = readouts_.rbegin();\n\tif (list_rit != readouts_.rend()) {\n\t\tfor ( ; boost::next(list_rit) != readouts_.rend(); list_rit++)\n\t\t\tlist_rit->SetTimeReference(*boost::next(list_rit));\n\t\tlist_rit->Relativize(); /* Relativize the first readout as well. */\n\t\ti3_assert(boost::next(list_rit).base() == readouts_.begin());\n\t}\n}\n\nstd::list<I3SuperDSTReadout>\nI3SuperDST::GetReadouts(bool hlc) const\n{\n\tstd::list<I3SuperDSTReadout> filtered;\n\tstd::list<I3SuperDSTReadout>::const_iterator list_it;\n\t\n\tfor (list_it = readouts_.begin(); list_it != readouts_.end(); list_it++)\n\t\tif (hlc == (list_it->kind_ == I3SuperDSTChargeStamp::HLC))\n\t\t\tfiltered.push_back(*list_it);\n\t\t\t\n\treturn filtered;\n}\n\nI3SuperDST::I3SuperDST(const I3RecoPulseSeriesMap &pulses)\n    : version_(i3superdst_version_)\n{\n\tAddPulseMap(pulses);\n\t\n\tInitDebug();\n}\n\n/* Expand charge stamps into fake I3RecoPulses */\nI3RecoPulseSeriesMapConstPtr\nI3SuperDST::Unpack() const\n{\n\tif (unpacked_)\n\t\treturn unpacked_;\n\n\tstd::vector<I3SuperDSTChargeStamp>::const_iterator stamp_it;\n\tstd::list<I3SuperDSTReadout>::const_iterator readout_it;\n\tdouble t_ref;\n\t\n\tunpacked_ = I3RecoPulseSeriesMapPtr(new I3RecoPulseSeriesMap);\n\n\tt_ref = tmin_;\n\t\n\tfor (readout_it = readouts_.begin(); readout_it != readouts_.end(); readout_it++) {\n\t\tint flags = (readout_it->kind_ == I3SuperDSTChargeStamp::HLC) ?\n\t\t    I3RecoPulse::ATWD | I3RecoPulse::FADC | I3RecoPulse::LC : I3RecoPulse::FADC;\n\t\tI3RecoPulseSeries &target = unpacked_->operator[](readout_it->om_);\n\t\t\n\t\tt_ref += readout_it->GetTime();\n\t\tdouble t_ref_internal = t_ref;\n\t\t\n\t\tstamp_it = readout_it->stamps_.begin();\n\t\t\n\t\tif (stamp_it != readout_it->stamps_.end()) {\n\t\t\tI3RecoPulse pulse;\n\t\t\t\n\t\t\tpulse.SetTime(t_ref);\n\t\t\tpulse.SetCharge(stamp_it->GetCharge());\n\t\t\tpulse.SetWidth(stamp_it->GetWidth());\n\t\t\tpulse.SetFlags(flags);\n\t\t\ttarget.push_back(pulse);\n\t\t\t\n\t\t\tstamp_it++;\n\t\t}\n\t\n\t\tfor ( ; stamp_it != readout_it->stamps_.end(); stamp_it++) {\n\t\t\tI3RecoPulse pulse;\n\t\t\t\n\t\t\tt_ref_internal += stamp_it->GetTime();\n\t\t\tpulse.SetTime(t_ref_internal);\n\t\t\tpulse.SetCharge(stamp_it->GetCharge());\n\t\t\tpulse.SetWidth(stamp_it->GetWidth());\n\t\t\tpulse.SetFlags(flags);\n\t\t\ttarget.push_back(pulse);\n\t\t}\n\t}\n\n\tBOOST_FOREACH(I3RecoPulseSeriesMap::value_type &target, *unpacked_) {\n\t\tstd::sort(target.second.begin(), target.second.end(), \n\t\t    I3SuperDSTRecoPulseUtils::TimeOrdering);\n\n\t\tI3RecoPulseSeries::iterator prev, current, next;\n\t\tprev = target.second.end();\n\t\tcurrent = target.second.begin();\n\t\tnext = current+1;\n\t\tbool merge = false;\n\t\t/* Ensure that pulses do not overlap. */\n\t\twhile (next < target.second.end()) {\n\t\t\tcurrent->SetWidth(std::min(current->GetWidth(),\n\t\t\t    float(next->GetTime()-current->GetTime())));\n\t\t\tif (current->GetWidth() == 0 || merge) {\n\t\t\t\tif (prev != target.second.end()) {\n\t\t\t\t\t/* Merge widths with previous pulse */\n\t\t\t\t\tif (prev->GetWidth() == 0 && current->GetWidth() > 0)\n\t\t\t\t\t\tprev->SetWidth(current->GetWidth());\n\t\t\t\t\tcurrent->SetWidth(prev->GetWidth()/2.);\n\t\t\t\t\tprev->SetWidth(prev->GetWidth()/2.);\n\t\t\t\t\tcurrent->SetTime(prev->GetTime()+prev->GetWidth());\n\t\t\t\t\tmerge = false;\n\t\t\t\t} else {\n\t\t\t\t\tmerge = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmerge = false;\n\t\t\t}\n\t\t\tprev = current;\n\t\t\tcurrent++;\n\t\t\tnext = current+1;\n\t\t}\n\t\tif (merge && prev != target.second.end()) {\n\t\t\tif (prev->GetWidth() == 0 && current->GetWidth() > 0)\n\t\t\t\tprev->SetWidth(current->GetWidth());\n\t\t\tcurrent->SetWidth(prev->GetWidth()/2.);\n\t\t\tprev->SetWidth(prev->GetWidth()/2.);\n\t\t\tcurrent->SetTime(prev->GetTime()+prev->GetWidth());\n\t\t}\n\t}\n\t\n\treturn unpacked_;\n}\n\nuint32_t\nI3SuperDST::EncodeOMKey(const OMKey &key, unsigned int maxbits, unsigned int version)\n{\n\tuint32_t encoded(0);\n\tint string = key.GetString();\n\tint om = key.GetOM();\n\n\ti3_assert(string >= 0);\n\ti3_assert(om > 0);\n\ti3_assert(om <= 64);\n\ti3_assert(maxbits <= 31);\n\t\n\t/*\n\t * NB: this is the same encoding scheme as the DAQ:\n\t * upper 7 bits: string number, lower 6 bits: OM number\n\t */\n\tencoded |= ((unsigned(string) << 6) & ~((1<<6)-1));\n\tencoded |= ((unsigned(om)-1) & ((1<<6)-1));\n\ti3_assert( encoded <= uint32_t((1<<maxbits)-1) );\n\t\n\treturn (encoded);\n}\n\nOMKey\nI3SuperDST::DecodeOMKey(uint32_t dom_id, unsigned int version)\n{\n\tint string(0), om(0);\n\t\n\tstring = unsigned((dom_id >> 6) & ((1<<7)-1));\n\tom = unsigned(dom_id & ((1<<6)-1))+1;\n\t\n\treturn OMKey(string, om);\n}\n\ninline uint32_t\ntruncate(double val, unsigned int maxbits)\n{\n\tuint32_t code(lround(val)); /* Round to nearest integer */\n\ti3_assert(maxbits <= 31);\n\t\n\t/* Truncate if greater than 2^(maxbits)-1 */\n\tif (code > uint32_t((1<<maxbits)-1))\n\t\tcode = uint32_t((1<<maxbits)-1);\n\t\n\treturn (code);\n}\n\nuint32_t\nI3SuperDST::EncodeTime(double time, unsigned int maxbits,\n    unsigned int version)\n{\n\tuint32_t encoded(0);\n\t\n\ti3_assert( time >= 0.0 );\n\tswitch (version) {\n\t\tcase 0:\n\t\t\tencoded = truncate(time / (4.0*I3Units::ns), maxbits);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tencoded = truncate(time / (1.0*I3Units::ns), maxbits);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\t\n\treturn (encoded);\n}\n\ndouble\nI3SuperDST::DecodeTime(uint32_t dt, unsigned int version)\n{\n\tdouble decoded(0);\n\t\n\tswitch (version) {\n\t\tcase 0:\n\t\t\tdecoded = dt*4.0*I3Units::ns;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tdecoded = dt*1.0*I3Units::ns;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\t\n\treturn (decoded);\n}\n\ninline unsigned\nGetExponent(uint64_t i, unsigned mbits, unsigned ebits)\n{\n\tusing namespace I3SuperDSTUtils;\n\ti3_assert(mbits > 0);\n\ti3_assert(ebits > 0);\n\tint e = std::max(findlastset(i)-int(mbits-1), 0);\n\treturn std::min(unsigned(e), (1u << ebits)-1);\n}\n\nuint32_t\nI3SuperDST::EncodeWidth(double width, unsigned int maxbits,\n    unsigned int version)\n{\n\ti3_assert(width > 0 && width < double(std::numeric_limits<unsigned>::max()));\n\tunsigned rounded = unsigned(ceil(width/1.0));\n\tunsigned code = std::min(unsigned(findlastset(rounded)), (1u << maxbits)-1);\n\treturn (rounded == 1u << (code-1)) ? code-1 : code;\n}\n\ndouble\nI3SuperDST::DecodeWidth(uint32_t dt, unsigned int version)\n{\n\ti3_assert(dt <= 31);\n\treturn double(1u << dt);\n}\n\nuint32_t\nI3SuperDST::EncodeCharge(double charge, unsigned int maxbits,\n    unsigned int version, Discretization mode)\n{\n\tuint32_t encoded(0);\n\t\n\ti3_assert( charge >= 0 );\n\t\n\tif (mode == LOG) {\n\t\ti3_assert(maxbits >= 14);\n\t\tdouble logq = std::max(0.0, log10(charge) + 2.0);\n\t\tdouble step = 9.0/double((1<<14)-1);\n\t\tencoded = truncate(logq/step, maxbits);\n\t} else {\n\t\tif (version == 0) {\n\t\t\tencoded = truncate(charge/0.15, maxbits);\n\t\t} else {\n\t\t\tencoded = uint32_t(floor(std::max(0., charge)/0.05));\t\n\t\t}\n\t}\n\n\t\n\treturn (encoded);\n}\n\ndouble\nI3SuperDST::DecodeCharge(uint32_t chargecode, unsigned int version,\n    Discretization mode)\n\n{\n\tdouble decoded(0);\n\t\n\tif (mode == LOG) {\n\t\tdouble step = 9.0/double((1<<14)-1);\n\t\tdecoded = pow(10., chargecode*step - 2.0);\n\t} else {\n\t\tif (version == 0)\n\t\t\tdecoded = chargecode*0.15;\n\t\telse {\n\t\t\t// Decode at bin center \n\t\t\tdecoded = chargecode*0.05 + 0.025;\n\t\t}\n\t}\n\t\n\treturn (decoded);\n}\n\ndouble\nI3SuperDST::FindStartTime(const I3RecoPulseSeriesMap &pmap)\n{\n\tdouble tmin = std::numeric_limits<double>::max();\n\tI3RecoPulseSeriesMap::const_iterator map_it = pmap.begin();\n\tI3RecoPulseSeries::const_iterator pulse_it;\n\t\n\tfor ( ; map_it != pmap.end() ; map_it++)\n\t\tfor (pulse_it = map_it->second.begin();\n\t\t    pulse_it != map_it->second.end(); pulse_it++)\n\t\t\tif (std::isfinite(pulse_it->GetTime()) &&\n\t\t\t    pulse_it->GetTime() < tmin)\n\t\t\t\ttmin = pulse_it->GetTime();\n\t\t\t\t\n\treturn (tmin);\n}\n\nbool\nI3SuperDST::operator==(const I3SuperDST& rhs) const {\n  if (bool(this->unpacked_) != bool(rhs.unpacked_)) {\n    return false;\n  }\n  if (this->unpacked_) {\n    if (!(*(this->unpacked_) == *(rhs.unpacked_))) {\n      return false;\n    }\n  }\n  return (this->readouts_ == rhs.readouts_ &&\n          this->tmin_ == rhs.tmin_ &&\n          this->version_ == rhs.version_);\n}\n\n/* \n * NB: While the internal layout of bitfields is implementation-defined,\n * (see ISO 14882 [http://www-d0.fnal.gov/~dladams/cxx_standard.pdf] p. 159)\n * GCC >= 3.4.6 obeys the following conventions under __attribute((packed)):\n *\n * - on little-endian platforms, fields are laid out in native byte order\n *   starting from the least significant bit of the parent struct\n * \n * - on big-endian platforms, fields are laid out starting from the most\n *   significant bit of the parent struct\n *\n * To properly interpet the binary representation of a bitfield from a little-\n * endian platform on a big-endian one (and vice versa), it is necessary not\n * only to swap the order of the bytes in memory, but also to reverse the\n * order of the fields.\n */\n\nnamespace I3SuperDSTSerialization {\n\nstruct DOMHeader {\n#if BYTE_ORDER == BIG_ENDIAN\n\tuint16_t slop      : I3SUPERDST_SLOP_BITS_V0; /* most significant 3 bits of first HLC time */\n\tuint16_t dom_id    : I3SUPERDST_DOMID_BITS_V0;\n#else\n\tuint16_t dom_id    : I3SUPERDST_DOMID_BITS_V0;\n\tuint16_t slop      : I3SUPERDST_SLOP_BITS_V0; /* most significant 3 bits of first HLC time */\n#endif\n} __attribute((packed));\n\nBOOST_STATIC_ASSERT( sizeof(DOMHeader) == I3SUPERDST_HEADER_BYTESIZE_V0 );\n\nunion ChargeStamp {\n\tstruct {\n#if BYTE_ORDER == BIG_ENDIAN\n\t\tuint16_t stop     : 1;\n\t\tuint16_t hlc_bit  : 1;\n\t\tuint16_t charge   : I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0;\n\t\tuint16_t rel_time : I3SUPERDSTCHARGESTAMP_TIME_BITS_V0;\n#else\n\t\tuint16_t rel_time : I3SUPERDSTCHARGESTAMP_TIME_BITS_V0;\n\t\tuint16_t charge   : I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0;\n\t\tuint16_t hlc_bit  : 1;\n\t\tuint16_t stop     : 1;\n#endif\n\t} stamp;\n\tstruct {\n#if BYTE_ORDER == BIG_ENDIAN\n\t\tuint16_t stop : 1; /* The stop bit is always valid. */\n\t\tuint16_t code : 15;\n#else\n\t\tuint16_t code : 15;\n\t\tuint16_t stop : 1; /* The stop bit is always valid. */\n#endif\n\t} overflow;\n\tuint16_t raw;\n} __attribute((packed));\n\nBOOST_STATIC_ASSERT( sizeof(ChargeStamp) == I3SUPERDSTCHARGESTAMP_BYTESIZE_V0 );\n\n}\n\n#ifndef NDEBUG\n#include <sys/resource.h>\nclass I3SuperDSTTimer {\npublic:\n\tI3SuperDSTTimer(double *acc, unsigned *counter)\n\t: acc_(acc), counter_(counter)\n\t{\n\t\tif (acc_)\n\t\t\terr_ = getrusage(RUSAGE_SELF, &start_);\n\t}\n\t~I3SuperDSTTimer()\n\t{\n\t\tif ((acc_) && !err_ && !getrusage(RUSAGE_SELF, &end_)) {\n\t\t\t*acc_ += double(end_.ru_utime.tv_sec + end_.ru_stime.tv_sec\n\t\t\t    - start_.ru_utime.tv_sec - start_.ru_stime.tv_sec)\n\t\t\t    + double(end_.ru_utime.tv_usec + end_.ru_stime.tv_usec\n\t\t\t    - start_.ru_utime.tv_usec - start_.ru_stime.tv_usec)\n\t\t\t    *1e-6;\n\t\t}\n\t\tif (counter_)\n\t\t\t*counter_ += 1;\n\t}\nprivate:\n\tdouble *acc_;\n\tunsigned *counter_;\n\tint err_;\n\trusage start_, end_;\n};\n#endif\n\ntemplate <class T>\nstatic void\nswap_vector(std::vector<T> &vec)\n{\n#if BYTE_ORDER == BIG_ENDIAN\n\tBOOST_STATIC_ASSERT(sizeof(T) == 2);\n\ttypename std::vector<T>::iterator it = vec.begin();\n\tfor ( ; it != vec.end(); it++) {\n\t\tuint16_t *swapit = (uint16_t*)(&*it);\n\t\t*swapit = ((*swapit & 0x00FF) << 8) | ((*swapit & 0xFF00) >> 8);\t\n\t}\n#endif\n};\n\nI3MapKeyVectorInt\nI3SuperDST::GetEncodedSizes() const\n{\n\tI3MapKeyVectorInt sizes;\n\tstd::ostringstream oarchive_stream;\n\ticecube::archive::portable_binary_oarchive oarchive(oarchive_stream);\n\n\t/* Piggy-back on the current implementation of save() */\n\tthis->save(oarchive, icecube::serialization::version<I3SuperDST>::value,\n\t    &sizes);\n\n\treturn sizes;\n}\n\nnamespace I3SuperDSTUtils {\n\n\tvoid RunCodec::EncodeRun(vector_t &codes, uint8_t val, unsigned len)\n\t{\n\t\tunsigned nblocks = (findlastset(len)-1)/4 + 1;\n#if BYTE_ORDER == BIG_ENDIAN\n\t\tfor (unsigned i=nblocks-1; i >= 0; i--) {\n#else \n\t\tfor (unsigned i=0; i < nblocks; i++) {\n#endif\n\t\t\tuint8_t code = (val & 0xf);;\n\t\t\tcode |= ((len >> (i*4u)) << 4) & 0xf0;\n\t\t\tcodes.push_back(code);\n\t\t}\n\t}\n\n\tvoid RunCodec::DecodeRun(vector_t &target,\n\t    const vector_t::const_iterator &head,\n\t    const vector_t::const_iterator &tail)\n\t{\n\t\tuint8_t code = *head & 0xf;\n\t\tunsigned runlength = 0;\n\t\tunsigned offset = 0;\n#if BYTE_ORDER == BIG_ENDIAN\n\t\tvector_t::const_iterator it = tail-1;\n\t\tfor ( ; it >= head; it--, offset+=4u)\n#else\t\t\n\t\tvector_t::const_iterator it = head;\n\t\tfor ( ; it != tail; it++, offset+=4u)\n#endif\n\t\t\trunlength |= (((*it >> 4) & 0xf) << offset);\n\t\ttarget.insert(target.end(), runlength, code);\n\t}\n\n\tvoid RunCodec::Encode(const vector_t &runs, vector_t &codes)\n\t{\n\t\tvector_t::const_iterator head, tail;\n\t\thead = runs.begin();\n\t\ttail = head+1;\n\t\tfor ( ; tail < runs.end(); tail++)\n\t\t\tif (*tail != *head) {\n\t\t\t\t/* Start a new run */\n\t\t\t\tunsigned runlength = std::distance(head, tail);\n\t\t\t\tEncodeRun(codes, *head, runlength);\n\t\t\t\thead = tail;\n\t\t\t}\n\n\t\t/* True by construction, unless the vector has length 0 */\n\t\tif (tail == runs.end()) {\n\t\t\tunsigned runlength = std::distance(head, tail);\n\t\t\tEncodeRun(codes, *head, runlength);\n\t\t}\n\t}\n\n\tvoid RunCodec::Decode(const std::vector<uint8_t> &codes, vector_t &runs)\n\t{\n\t\tvector_t::const_iterator head, tail;\n\t\truns.clear();\n\t\thead = codes.begin();\n\t\ttail = head+1;\n\t\tfor ( ; tail < codes.end(); tail++)\n\t\t\tif ((*tail & 0xf) != (*head & 0xf)) {\n\t\t\t\t/* A run has ended. */\n\t\t\t\tDecodeRun(runs, head, tail);\n\t\t\t\thead = tail;\n\t\t\t}\n\n\t\t/* True by construction, unless the vector has length 0 */\n\t\tif (tail == codes.end()) {\n\t\t\tDecodeRun(runs, head, tail);\n\t\t}\n\t}\n\n\ttemplate <class Archive>\n\tvoid SizeCodec::save(Archive &ar, unsigned version) const\n\t{\n\t\tif (size_ < 0xff-sizeof(size_type)) {\n\t\t\tuint8_t tag = size_;\n\t\t\tar & make_nvp(\"Tag\", tag);\n\t\t} else {\n\t\t\tuint8_t n_bytes = (findlastset(size_)-1)/8 + 1;\n\t\t\tuint8_t tag = 0xff - n_bytes;\n\t\t\tar & make_nvp(\"Tag\", tag);\n\n\t\t\tuint8_t bytes[8];\n\t\t\tuint64_t s = size_;\n#if BYTE_ORDER == BIG_ENDIAN\n\t\t\tfor (unsigned i=n_bytes-1; i >= 0; i--, s=s>>8)\n#else\n\t\t\tfor (unsigned i=0; i < n_bytes; i++, s=s>>8)\n#endif\n\t\t\t\tbytes[i] = s & 0xff;\n\n\t\t\tar & make_nvp(\"Bytes\", icecube::serialization::make_binary_object(\n\t\t\t    bytes, n_bytes));\n\t\t}\n\t}\n\t\n\ttemplate <class Archive>\n\tvoid SizeCodec::load(Archive &ar, unsigned version)\n\t{\n\t\tuint8_t tag = 0;\n\t\tsize_ = 0;\n\t\tar & make_nvp(\"Tag\", tag);\n\t\tif (tag < 0xff-sizeof(size_type)) {\n\t\t\tsize_ = tag;\n\t\t} else {\n\t\t\tunsigned n_bytes = 0xff - tag;\n\t\t\tuint8_t bytes[8];\n\t\t\tar & make_nvp(\"Bytes\", icecube::serialization::make_binary_object(\n\t\t\t    bytes, n_bytes));\n\n#if BYTE_ORDER == BIG_ENDIAN\n\t\t\tfor (unsigned i=n_bytes-1; i >= 0; i--)\n#else\n\t\t\tfor (unsigned i=0; i < n_bytes; i++)\n#endif\n\t\t\t\tsize_ |= (size_t(bytes[i]) << (i*8));\n\t\t}\n\t}\n\n}\n\ntemplate <class Archive>\nvoid\nI3SuperDST::save(Archive& ar, unsigned version) const\n{\n\tsave(ar, version, NULL);\n}\n\nnamespace {\n\nsize_t\nencode_overflow(CompactVector<I3SuperDSTSerialization::ChargeStamp> &stamp_stream,\n   unsigned code, unsigned max_overflow)\n{\n\tsize_t readout_bytes = 0;\n\t\n\tI3SuperDSTSerialization::ChargeStamp stamp;\n\t// emit overflow in blocks of max_overflow\n\tdo {\n\t\tstamp.raw = std::min(code, max_overflow);\n\t\tcode -= std::min(code, max_overflow);\n\t\n\t\tstamp_stream.push_back(stamp);\n\t\treadout_bytes += sizeof(stamp);\n\n\t} while (code > 0);\n\t\n\t// the decoder interprets stamps with value max_overflow as a signal\n\t// to continue. emit one with value 0 to make it stop.\n\tif (stamp.raw == max_overflow) {\n\t\tstamp.raw = 0;\n\t\tstamp_stream.push_back(stamp);\n\t\treadout_bytes += sizeof(stamp);\n\t}\n\t\n\treturn readout_bytes;\n}\n\n}\n\ntemplate <class Archive>\nvoid\nI3SuperDST::save(Archive& ar, unsigned version,\n    std::map<OMKey, std::vector<int > > *sizes) const\n{\n#ifndef NDEBUG\n\tI3SuperDSTTimer timer(serialization_time_, serialization_counter_);\n#endif\n\tCompactVector<I3SuperDSTSerialization::DOMHeader> header_stream;\n\tCompactVector<I3SuperDSTSerialization::ChargeStamp> stamp_stream;\n\tCompactVector<uint8_t> ldr_stream;\n\tstd::vector<uint8_t> widths[4];\n\t\n\tstd::list<I3SuperDSTReadout>::const_iterator readout_it;\n\tstd::vector<I3SuperDSTChargeStamp>::const_iterator stamp_it;\n\t\n\tconst unsigned max_timecode_header = (1u << (I3SUPERDSTCHARGESTAMP_TIME_BITS_V0\n\t    + I3SUPERDST_SLOP_BITS_V0)) - 1;\n\tconst unsigned max_timecode = (1u << I3SUPERDSTCHARGESTAMP_TIME_BITS_V0) - 1;\n\tconst unsigned max_chargecode = (1u << I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0) - 1;\n\tconst unsigned max_overflow = UINT16_MAX;\n\n\tfor (readout_it = readouts_.begin();\n\t    readout_it != readouts_.end(); readout_it++) {\n\t\t\n\t\tI3SuperDSTSerialization::DOMHeader header;\n\t\t\n\t\theader.dom_id = EncodeOMKey(readout_it->om_, 13, version);\n\t\tsize_t readout_bytes = sizeof(header);\n\n\t\t// Widths: {InIce SLC, InIce HLC, IceTop SLC, IceTop HLC}\n\t\tstd::vector<uint8_t> &width =\n\t\t    widths[2*(readout_it->om_.GetOM() > 60) + readout_it->GetLCBit()];\n\t\t\n\t\t/*\n\t\t * Special case for the first stamp in the series:\n\t\t * use the slop space in the header to extend the time range.\n\t\t */\n\t\tstamp_it = readout_it->stamps_.begin();\n\t\tDiscretization charge_format = stamp_it->GetChargeFormat();\n\t\tif (stamp_it != readout_it->stamps_.end()) {\n\t\t\tunsigned timecode = stamp_it->GetTimeCode();\n\t\t\tunsigned chargecode = stamp_it->GetChargeCode();\n\t\t\tconst bool stop = (boost::next(stamp_it) == readout_it->stamps_.end());\n\t\t\theader.slop = (std::min(timecode, max_timecode_header)\n\t\t\t    >> I3SUPERDSTCHARGESTAMP_TIME_BITS_V0)\n\t\t\t    & ((1 << I3SUPERDST_SLOP_BITS_V0)-1);\n\t\t\t\n\t\t\tI3SuperDSTSerialization::ChargeStamp stampytown; /* Population: 5! */\n\t\t\tstampytown.stamp.rel_time = std::min(timecode, max_timecode_header)\n\t\t\t    & ((1 << I3SUPERDSTCHARGESTAMP_TIME_BITS_V0)-1);\n\t\t\tstampytown.stamp.hlc_bit = stamp_it->GetLCBit();\n\t\t\tstampytown.stamp.stop = stop;\n\n\t\t\tif (charge_format == LINEAR) {\n\t\t\t\tstampytown.stamp.charge =\n\t\t\t\t    std::min(chargecode, max_chargecode); \n\t\t\t} else {\n\t\t\t\t/*\n\t\t\t\t * Special case for floating-point scheme: pack lower 6\n\t\t\t\t * bits in the charge stamp; upper 8 bits in an\n\t\t\t\t * extra stream.\n\t\t\t\t */ \n\t\t\t\tstampytown.stamp.charge = chargecode &\n\t\t\t\t    ((1<<I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0)-1);\n\t\t\t\tuint8_t ldr = (chargecode >> I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0) &\n\t\t\t\t    ((1<<8)-1);\n\t\t\t\tldr_stream.push_back(ldr);\n\t\t\t\treadout_bytes += sizeof(ldr);\n\t\t\t}\n\n\t\t\twidth.push_back(stamp_it->GetWidthCode());\n\t\t\tstamp_stream.push_back(stampytown);\n\t\t\treadout_bytes += sizeof(stampytown);\n\t\t\t\n\t\t\t/*\n\t\t\t * If we still have any time overflow, subtract it\n\t\t\t * off in 16-bit chunks until it's gone. The saturated\n\t\t\t * timecode serves as a sentinel for this case.\n\t\t\t */\n\t\t\tif (timecode >= max_timecode_header) {\n\t\t\t\treadout_bytes += encode_overflow(stamp_stream,\n\t\t\t\t    timecode-max_timecode_header, max_overflow);\n\t\t\t}\n\t\t\t\n\t\t\t/*\n\t\t\t * Repeat the same overflow procedure for charge in the\n\t\t\t * linear scheme. The floating-point scheme has no overflow.\n\t\t\t */\n\t\t\tif (charge_format == LINEAR && chargecode >= max_chargecode) {\n\t\t\t\treadout_bytes += encode_overflow(stamp_stream,\n\t\t\t\t    chargecode-max_chargecode, max_overflow);\n\t\t\t}\n\t\t\t\n\t\t\tstamp_it++;\n\t\t}\n\t\t\n\t\theader_stream.push_back(header);\n\t\t\n\t\t/* Only one stamp in the floating point scheme */\n\t\ti3_assert(charge_format != LOG || stamp_it == readout_it->stamps_.end());\n\t\t\n\t\tfor ( ; stamp_it != readout_it->stamps_.end(); ) {\n\t\t\tI3SuperDSTSerialization::ChargeStamp stampytown;\n\t\t\tconst bool stop = (boost::next(stamp_it)\n\t\t\t    == readout_it->stamps_.end());\n\t\t\tunsigned chargecode = stamp_it->GetChargeCode();\n\t\t\tunsigned timecode = stamp_it->GetTimeCode();\n\t\t\t\n\t\t\tstampytown.stamp.rel_time = std::min(timecode, max_timecode);\n\t\t\tstampytown.stamp.charge = std::min(chargecode, max_chargecode);\n\t\t\tstampytown.stamp.hlc_bit = stamp_it->GetLCBit();\n\t\t\t\n\t\t\tstampytown.stamp.stop = stop;\n\t\t\twidth.push_back(stamp_it->GetWidthCode());\n\t\t\tstamp_stream.push_back(stampytown);\n\t\t\treadout_bytes += sizeof(stampytown);\n\t\t\t\n\t\t\t/* Encode any time overflow. */\n\t\t\tif (timecode >= max_timecode) {\n\t\t\t\treadout_bytes += encode_overflow(stamp_stream,\n\t\t\t\t    timecode-max_timecode, max_overflow);\n\t\t\t}\n\t\t\t\n\t\t\t/* Encode any charge overflow. */\n\t\t\tif (chargecode >= max_chargecode) {\n\t\t\t\treadout_bytes += encode_overflow(stamp_stream,\n\t\t\t\t    chargecode-max_chargecode, max_overflow);\n\t\t\t}\n\t\t\t\n\t\t\tstamp_it++;\n\t\t}\n\n\t\tif (sizes != NULL)\n\t\t\t(*sizes)[readout_it->om_].push_back(readout_bytes);\n\t}\n\t\n\tar & make_nvp(\"I3FrameObject\", base_object<I3FrameObject>(*this));\n\n\tswap_vector(stamp_stream);\n\tar & make_nvp(\"ChargeStamps\", stamp_stream);\n\n\tswap_vector(header_stream);\n\tar & make_nvp(\"DOMHeaders\", header_stream);\n\n\tCompactVector<uint8_t> width_runs;\n\tfor (int i = 0; i < 4; i++) {\n\t\twidth_runs.clear();\n\t\tRunCodec::Encode(widths[i], width_runs);\n\t\tar & make_nvp(\"Widths\", width_runs);\n\t}\n\n\tar & make_nvp(\"ExtraBytes\", ldr_stream);\n\t\n\treturn;\n}\n\ntemplate <typename Archive>\nvoid I3SuperDST::load_v0(Archive &ar)\n{\n\tuint16_t stream_size;\n\tar & make_nvp(\"NRecords\", stream_size);\n\tstd::vector<I3SuperDSTSerialization::ChargeStamp> stamp_stream;\n\tstamp_stream.resize(stream_size);\n\tar & make_nvp(\"ChargeStamps\",\n\t    icecube::serialization::make_binary_object(&stamp_stream.front(),\n\t    stream_size*sizeof(I3SuperDSTSerialization::ChargeStamp)));\n\tswap_vector(stamp_stream);\n\t\n\t/* Count the number of distinct units in the stamp stream */\n\tunsigned n_headers = 0;\n\tBOOST_FOREACH(const I3SuperDSTSerialization::ChargeStamp &stamp, stamp_stream)\n\t\tif (stamp.stamp.stop)\n\t\t\tn_headers++;\n\t\t\n\t/* Now that we know the length of the header stream, resurrect it. */\n\tstd::vector<I3SuperDSTSerialization::DOMHeader> header_stream;\n\theader_stream.resize(n_headers);\n\tar & make_nvp(\"DOMHeaders\",\n\t    icecube::serialization::make_binary_object(&header_stream.front(),\n\t    n_headers*sizeof(I3SuperDSTSerialization::DOMHeader)));\n\tswap_vector(header_stream);\n\n\t/* Saturation values */\n\tconst unsigned max_timecode_header = (1 << (I3SUPERDSTCHARGESTAMP_TIME_BITS_V0\n\t    + I3SUPERDST_SLOP_BITS_V0)) - 1;\n\tconst unsigned max_chargecode = (1u << I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0) - 1;\n\t\n\tstd::vector<I3SuperDSTSerialization::ChargeStamp>::const_iterator stamp_it\n\t    = stamp_stream.begin();\n\tstd::vector<I3SuperDSTSerialization::DOMHeader>::const_iterator header_it\n\t    = header_stream.begin();\n\n\tconst uint32_t widthcode =\n\t    I3SuperDST::EncodeWidth(I3SuperDST::DecodeTime(1, 0), 0);\n\t\n\tfor ( ; header_it != header_stream.end(); header_it++) {\n\t\tI3SuperDSTReadout readout;\n\t\t\n\t\treadout.om_ = I3SuperDST::DecodeOMKey(header_it->dom_id, 0);\n\t\tbool hlc = stamp_it->stamp.hlc_bit;\n\t\t\n\t\t/* \n\t\t * Use the slop bits in the header as the most significant\n\t\t * bits for the time of the first header.\n\t\t */\n\t\tunsigned timecode = stamp_it->stamp.rel_time;\n\t\tunsigned chargecode = stamp_it->stamp.charge;\n\t\ttimecode |= (unsigned(header_it->slop) <<\n\t\t    I3SUPERDSTCHARGESTAMP_TIME_BITS_V0);\n\t\t\n\t\t/* If the time is saturated, add the next 15 bits. */\n\t\tif (timecode == max_timecode_header) {\n\t\t\tstamp_it++;\n\t\t\ttimecode += stamp_it->overflow.code;\n\t\t\t//readout.time_overflow_ = stamp_it->overflow.code;\n\t\t}\n\t\n\t\t/* If the time is saturated, add the next 15 bits. */\n\t\tif (chargecode == max_chargecode) {\n\t\t\tstamp_it++;\n\t\t\tchargecode += stamp_it->overflow.code;\n\t\t}\n\t\t\n\t\tI3SuperDSTChargeStamp stamp(timecode, chargecode, widthcode,\n\t\t    hlc, LINEAR, 0);\n\t\t\n\t\treadout.stamps_.push_back(stamp);\n\t\t\n\t\t/* Read in the remaining stamps until we hit a stop. */\n\t\twhile (!stamp_it->stamp.stop) {\n\t\t\tstamp_it++;\n\t\t\t\n\t\t\t/* No funny schtuff, ja Lebovski? */\n\t\t\ti3_assert( stamp_it->stamp.hlc_bit == hlc );\n\t\t\t\n\t\t\ttimecode = stamp_it->stamp.rel_time;\n\t\t\tchargecode = stamp_it->stamp.charge;\n\t\t\t\n\t\t\t/* Add charge overflow if we have it */\n\t\t\tif (chargecode == max_chargecode) {\n\t\t\t\tstamp_it++;\n\t\t\t\tchargecode += stamp_it->overflow.code;\n\t\t\t}\n\t\t\t\n\t\t\tI3SuperDSTChargeStamp stamp(timecode, chargecode, widthcode,\n\t\t\t    hlc, LINEAR, 0);\n\t\t\t\n\t\t\treadout.stamps_.push_back(stamp);\n\t\t}\n\t\ti3_assert( stamp_it != stamp_stream.end() );\n\t\tstamp_it++; /* Advance for the next readout */\n\t\t\n\t\treadout.kind_ = hlc ? I3SuperDSTChargeStamp::HLC : I3SuperDSTChargeStamp::SLC;\n\t\treadouts_.push_back(readout);\n\t}\n\t\n\t/* Populate the start_time_ fields of the readouts_ for consistency. */\n\tdouble t_ref = 0.0;\n\tBOOST_FOREACH(I3SuperDSTReadout &readout, readouts_) {\n\t\ti3_assert(readout.stamps_.size() > 0);\n\t\tt_ref += readout.GetTime();\n\t\treadout.start_time_ = t_ref;\n\t}\n}\n\ntemplate <typename Archive>\nvoid I3SuperDST::load_v1(Archive &ar)\n{\n\tCompactVector<I3SuperDSTSerialization::ChargeStamp> stamp_stream;\n\tar & make_nvp(\"ChargeStamps\", stamp_stream);\n\tswap_vector(stamp_stream);\n\n\tCompactVector<I3SuperDSTSerialization::DOMHeader> header_stream;\n\tar & make_nvp(\"DOMHeaders\", header_stream);\n\tswap_vector(header_stream);\n\n\tstd::vector<uint8_t> widths[4];\n\tstd::vector<uint8_t>::const_iterator width_its[4];\n\tCompactVector<uint8_t> width_runs;\n\tfor (int i = 0; i < 4; i++) {\n\t\twidth_runs.clear();\n\t\tar & make_nvp(\"Widths\", width_runs);\n\t\tRunCodec::Decode(width_runs, widths[i]);\n\t\twidth_its[i] = widths[i].begin();\n\t}\n\n\tCompactVector<uint8_t> byte_stream;\n\tar & make_nvp(\"ExtraBytes\", byte_stream);\n\t\n\t/* Saturation values */\n\tconst unsigned max_timecode_header = (1 << (I3SUPERDSTCHARGESTAMP_TIME_BITS_V0\n\t    + I3SUPERDST_SLOP_BITS_V0)) - 1;\n\tconst unsigned max_timecode = (1u << I3SUPERDSTCHARGESTAMP_TIME_BITS_V0) - 1;\n\tconst unsigned max_chargecode = (1u << I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0) - 1;\n\t\n\tstd::vector<I3SuperDSTSerialization::ChargeStamp>::const_iterator stamp_it\n\t    = stamp_stream.begin();\n\tstd::vector<I3SuperDSTSerialization::DOMHeader>::const_iterator header_it\n\t    = header_stream.begin();\n\tstd::vector<uint8_t>::const_iterator ldr_it = byte_stream.begin();\n\t\n\tfor ( ; header_it != header_stream.end(); header_it++) {\n\t\tI3SuperDSTReadout readout;\n\t\t\n\t\treadout.om_ = I3SuperDST::DecodeOMKey(header_it->dom_id, 1);\n\t\ti3_assert(stamp_it < stamp_stream.end());\n\t\tbool hlc = stamp_it->stamp.hlc_bit;\n\t\tbool stop = stamp_it->stamp.stop;\n\n\t\t/* Widths: {InIce SLC, InIce HLC, IceTop SLC, IceTop HLC} */\n\t\tstd::vector<uint8_t>::const_iterator &width_it =\n\t\t    width_its[2*(readout.om_.GetOM() > 60) + hlc];\n\t\tstd::vector<uint8_t>::const_iterator width_end =\n\t\t    widths[2*(readout.om_.GetOM() > 60) + hlc].end();\n\t\t\n\t\t/* \n\t\t * Use the slop bits in the header as the most significant\n\t\t * bits for the time of the first stamp.\n\t\t */\n\t\tunsigned timecode = stamp_it->stamp.rel_time;\n\t\tunsigned chargecode = stamp_it->stamp.charge;\n\t\ttimecode |= (unsigned(header_it->slop) <<\n\t\t    I3SUPERDSTCHARGESTAMP_TIME_BITS_V0);\n\n\t\tDiscretization charge_format = (readout.om_.GetOM() > 60)\n\t\t    ? LOG : LINEAR;\n\t\t\n\t\tif (timecode == max_timecode_header) {\n\t\t\ti3_assert(stamp_it < stamp_stream.end());\n\t\t\tdo {\n\t\t\t\ttimecode += (++stamp_it)->raw;\n\t\t\t} while (stamp_it->raw == UINT16_MAX);\n\t\t}\n\t\tif (charge_format == LINEAR && chargecode == max_chargecode) {\n\t\t\ti3_assert(stamp_it < stamp_stream.end());\n\t\t\tdo {\n\t\t\t\tchargecode += (++stamp_it)->raw;\n\t\t\t} while (stamp_it->raw == UINT16_MAX);\n\t\t} else if (charge_format == LOG) {\n\t\t\ti3_assert(ldr_it < byte_stream.end());\n\t\t\tchargecode |= unsigned(*ldr_it) <<\n\t\t\t    I3SUPERDSTCHARGESTAMP_CHARGE_BITS_V0;\n\t\t\tldr_it++;\n\t\t}\n\t\t\n\t\ti3_assert(width_it < width_end);\n\t\tI3SuperDSTChargeStamp stamp(timecode, chargecode, *width_it++,\n\t\t    hlc, charge_format, 1);\n\t\t\n\t\treadout.stamps_.push_back(stamp);\n\t\t\n\t\t/* Read in the remaining stamps until we hit a stop. */\n\t\twhile (!stop) {\n\t\t\tstamp_it++;\n\t\t\t\n\t\t\t/* No funny schtuff, ja Lebovski? */\n\t\t\ti3_assert(charge_format == LINEAR);\n\t\t\ti3_assert( stamp_it->stamp.hlc_bit == hlc );\n\t\t\t\n\t\t\ttimecode = stamp_it->stamp.rel_time;\n\t\t\tchargecode = stamp_it->stamp.charge;\n\t\t\tstop = stamp_it->stamp.stop;\n\t\t\t\n\t\t\tif (timecode == max_timecode) {\n\t\t\t\ti3_assert(stamp_it < stamp_stream.end());\n\t\t\t\tdo {\n\t\t\t\t\ttimecode += (++stamp_it)->raw;\n\t\t\t\t} while (stamp_it->raw == UINT16_MAX);\n\t\t\t}\n\t\t\tif (chargecode == max_chargecode) {\n\t\t\t\ti3_assert(stamp_it < stamp_stream.end());\n\t\t\t\tdo {\n\t\t\t\t\tchargecode += (++stamp_it)->raw;\n\t\t\t\t} while (stamp_it->raw == UINT16_MAX);\n\t\t\t}\n\t\t\t\n\t\t\ti3_assert(width_it < width_end);\n\t\t\tI3SuperDSTChargeStamp stamp(timecode, chargecode, *width_it++,\n\t\t\t    hlc, LINEAR, 1);\n\t\t\t\n\t\t\treadout.stamps_.push_back(stamp);\n\t\t}\n\t\ti3_assert( stamp_it < stamp_stream.end() );\n\t\tstamp_it++; /* Advance for the next readout */\n\t\t\n\t\treadout.kind_ = hlc ? I3SuperDSTChargeStamp::HLC : I3SuperDSTChargeStamp::SLC;\n\t\treadouts_.push_back(readout);\n\t}\n\n\ti3_assert(stamp_it == stamp_stream.end());\n\n\n\t/* Populate the start_time_ fields of the readouts_ for consistency. */\n\tdouble t_ref = 0.0;\n\tBOOST_FOREACH(I3SuperDSTReadout &readout, readouts_) {\n\t\ti3_assert(readout.stamps_.size() > 0);\n\t\tt_ref += readout.GetTime();\n\t\treadout.start_time_ = t_ref;\n\t}\n}\n\ntemplate <class Archive>\nvoid\nI3SuperDST::load(Archive& ar, unsigned version)\n{\n\tar & make_nvp(\"I3FrameObject\", base_object<I3FrameObject>(*this));\n\n\tswitch (version) {\n\t\tcase 0:\n\t\t\tload_v0(ar);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tload_v1(ar);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tlog_fatal(\"Foo!\");\n\t}\n\t\n\tversion_ = version;\n\t\n\treturn;\n}\n\nI3_SPLIT_SERIALIZABLE(I3SuperDST);\n\n// explicitly instantiate serialization functions to avoid linker errors\n// when compiling superdst-test\ntemplate void I3SuperDSTUtils::SizeCodec::save(icecube::archive::portable_binary_oarchive&, unsigned) const;\ntemplate void I3SuperDSTUtils::SizeCodec::load(icecube::archive::portable_binary_iarchive&, unsigned);\ntemplate void I3SuperDSTUtils::SizeCodec::load(icecube::archive::xml_iarchive&, unsigned);\ntemplate void I3SuperDSTUtils::SizeCodec::save(icecube::archive::xml_oarchive&, unsigned) const;\n\n\n", "meta": {"hexsha": "625ce0585e327ef520901e80f2f709348757d0b5", "size": 36757, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "dataclasses/private/dataclasses/payload/I3SuperDST.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": "dataclasses/private/dataclasses/payload/I3SuperDST.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": "dataclasses/private/dataclasses/payload/I3SuperDST.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": 28.3400154202, "max_line_length": 108, "alphanum_fraction": 0.6889844111, "num_tokens": 11098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.18384635297481508}}
{"text": "// Copyright (c) 2021-2022, The iTw3 Project\n//\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//\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n//\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\n//    materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    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\n// EXPRESS 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\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// 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\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"multisig_kex_msg.h\"\n#include \"multisig_kex_msg_serialization.h\"\n\n#include \"common/base58.h\"\n#include \"crypto/crypto.h\"\nextern \"C\"\n{\n#include \"crypto/crypto-ops.h\"\n}\n#include \"cryptonote_basic/cryptonote_format_utils.h\"\n#include \"include_base_utils.h\"\n#include \"ringct/rctOps.h\"\n#include \"serialization/binary_archive.h\"\n#include \"serialization/serialization.h\"\n\n#include <boost/utility/string_ref.hpp> \n\n#include <sstream>\n#include <utility>\n#include <vector>\n\n\n#undef MONERO_DEFAULT_LOG_CATEGORY\n#define MONERO_DEFAULT_LOG_CATEGORY \"multisig\"\n\nconst boost::string_ref MULTISIG_KEX_V1_MAGIC{\"MultisigV1\"};\nconst boost::string_ref MULTISIG_KEX_MSG_V1_MAGIC{\"MultisigxV1\"};\nconst boost::string_ref MULTISIG_KEX_MSG_V2_MAGIC_1{\"MultisigxV2R1\"};  //round 1\nconst boost::string_ref MULTISIG_KEX_MSG_V2_MAGIC_N{\"MultisigxV2Rn\"};  //round n > 1\n\nnamespace multisig\n{\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_kex_msg: EXTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  multisig_kex_msg::multisig_kex_msg(const std::uint32_t round,\n    const crypto::secret_key &signing_privkey,\n    std::vector<crypto::public_key> msg_pubkeys,\n    const crypto::secret_key &msg_privkey) :\n      m_kex_round{round}\n  {\n    CHECK_AND_ASSERT_THROW_MES(round > 0, \"Kex round must be > 0.\");\n    CHECK_AND_ASSERT_THROW_MES(sc_check((const unsigned char*)&signing_privkey) == 0 &&\n      signing_privkey != crypto::null_skey, \"Invalid msg signing key.\");\n\n    if (round == 1)\n    {\n      CHECK_AND_ASSERT_THROW_MES(sc_check((const unsigned char*)&msg_privkey) == 0 &&\n        msg_privkey != crypto::null_skey, \"Invalid msg privkey.\");\n\n      m_msg_privkey = msg_privkey;\n    }\n    else\n    {\n      for (const auto &pubkey : msg_pubkeys)\n      {\n        CHECK_AND_ASSERT_THROW_MES(pubkey != crypto::null_pkey && pubkey != rct::rct2pk(rct::identity()),\n          \"Pubkey for message was invalid.\");\n        CHECK_AND_ASSERT_THROW_MES((rct::scalarmultKey(rct::pk2rct(pubkey), rct::curveOrder()) == rct::identity()),\n          \"Pubkey for message was not in prime subgroup.\");\n      }\n\n      m_msg_pubkeys = std::move(msg_pubkeys);\n    }\n    CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(signing_privkey, m_signing_pubkey),\n      \"Failed to derive public key\");\n\n    // sets message and signing pub key\n    construct_msg(signing_privkey);\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_kex_msg: EXTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  multisig_kex_msg::multisig_kex_msg(std::string msg) : m_msg{std::move(msg)}\n  {\n    parse_and_validate_msg();\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_kex_msg: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  crypto::hash multisig_kex_msg::get_msg_to_sign() const\n  {\n    ////\n    // msg_content = kex_round | signing_pubkey | expand(msg_pubkeys) | OPTIONAL msg_privkey\n    // sign_msg = versioning-domain-sep | msg_content\n    ///\n\n    std::string data;\n    CHECK_AND_ASSERT_THROW_MES(MULTISIG_KEX_MSG_V2_MAGIC_1.size() == MULTISIG_KEX_MSG_V2_MAGIC_N.size(),\n      \"Multisig kex msg magic inconsistency.\");\n    data.reserve(MULTISIG_KEX_MSG_V2_MAGIC_1.size() + 4 + 32*(1 + (m_kex_round == 1 ? 1 : 0) + m_msg_pubkeys.size()));\n\n    // versioning domain-sep\n    if (m_kex_round == 1)\n      data.append(MULTISIG_KEX_MSG_V2_MAGIC_1.data(), MULTISIG_KEX_MSG_V2_MAGIC_1.size());\n    else\n      data.append(MULTISIG_KEX_MSG_V2_MAGIC_N.data(), MULTISIG_KEX_MSG_V2_MAGIC_N.size());\n\n    // kex_round as little-endian bytes\n    for (std::size_t i{0}; i < 4; ++i)\n    {\n      data += static_cast<char>(m_kex_round >> i*8);\n    }\n\n    // signing pubkey\n    data.append((const char *)&m_signing_pubkey, sizeof(crypto::public_key));\n\n    // add msg privkey if kex_round == 1\n    if (m_kex_round == 1)\n      data.append((const char *)&m_msg_privkey, sizeof(crypto::secret_key));\n    else\n    {\n      // only add pubkeys if not round 1\n\n      // msg pubkeys\n      for (const auto &key : m_msg_pubkeys)\n        data.append((const char *)&key, sizeof(crypto::public_key));\n    }\n\n    // message to sign\n    crypto::hash hash;\n    crypto::cn_fast_hash(data.data(), data.size(), hash);\n\n    return hash;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_kex_msg: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  void multisig_kex_msg::construct_msg(const crypto::secret_key &signing_privkey)\n  {\n    ////\n    // msg_content = kex_round | signing_pubkey | expand(msg_pubkeys) | OPTIONAL msg_privkey\n    // sign_msg = versioning-domain-sep | msg_content\n    // msg = versioning-domain-sep | serialize(msg_content | crypto_sig[signing_privkey](sign_msg))\n    ///\n\n    // sign the message\n    crypto::signature msg_signature;\n    crypto::hash msg_to_sign{get_msg_to_sign()};\n    crypto::generate_signature(msg_to_sign, m_signing_pubkey, signing_privkey, msg_signature);\n\n    // assemble the message\n    m_msg.clear();\n\n    std::stringstream serialized_msg_ss;\n    binary_archive<true> b_archive(serialized_msg_ss);\n\n    if (m_kex_round == 1)\n    {\n      m_msg.append(MULTISIG_KEX_MSG_V2_MAGIC_1.data(), MULTISIG_KEX_MSG_V2_MAGIC_1.size());\n\n      multisig_kex_msg_serializable_round1 msg_serializable;\n      msg_serializable.msg_privkey    = m_msg_privkey;\n      msg_serializable.signing_pubkey = m_signing_pubkey;\n      msg_serializable.signature      = msg_signature;\n\n      CHECK_AND_ASSERT_THROW_MES(::serialization::serialize(b_archive, msg_serializable),\n        \"Failed to serialize multisig kex msg\");\n    }\n    else\n    {\n      m_msg.append(MULTISIG_KEX_MSG_V2_MAGIC_N.data(), MULTISIG_KEX_MSG_V2_MAGIC_N.size());\n\n      multisig_kex_msg_serializable_general msg_serializable;\n      msg_serializable.kex_round      = m_kex_round;\n      msg_serializable.msg_pubkeys    = m_msg_pubkeys;\n      msg_serializable.signing_pubkey = m_signing_pubkey;\n      msg_serializable.signature      = msg_signature;\n\n      CHECK_AND_ASSERT_THROW_MES(::serialization::serialize(b_archive, msg_serializable),\n        \"Failed to serialize multisig kex msg\");\n    }\n\n    m_msg.append(tools::base58::encode(serialized_msg_ss.str()));\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_kex_msg: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  void multisig_kex_msg::parse_and_validate_msg()\n  {\n    // check message type\n    CHECK_AND_ASSERT_THROW_MES(m_msg.size() > 0, \"Kex message unexpectedly empty.\");\n    CHECK_AND_ASSERT_THROW_MES(m_msg.substr(0, MULTISIG_KEX_V1_MAGIC.size()) != MULTISIG_KEX_V1_MAGIC,\n      \"V1 multisig kex messages are deprecated (unsafe).\");\n    CHECK_AND_ASSERT_THROW_MES(m_msg.substr(0, MULTISIG_KEX_MSG_V1_MAGIC.size()) != MULTISIG_KEX_MSG_V1_MAGIC,\n      \"V1 multisig kex messages are deprecated (unsafe).\");\n\n    // deserialize the message\n    std::string msg_no_magic;\n    CHECK_AND_ASSERT_THROW_MES(MULTISIG_KEX_MSG_V2_MAGIC_1.size() == MULTISIG_KEX_MSG_V2_MAGIC_N.size(),\n      \"Multisig kex msg magic inconsistency.\");\n    CHECK_AND_ASSERT_THROW_MES(tools::base58::decode(m_msg.substr(MULTISIG_KEX_MSG_V2_MAGIC_1.size()), msg_no_magic),\n      \"Multisig kex msg decoding error.\");\n    binary_archive<false> b_archive{epee::strspan<std::uint8_t>(msg_no_magic)};\n    crypto::signature msg_signature;\n\n    if (m_msg.substr(0, MULTISIG_KEX_MSG_V2_MAGIC_1.size()) == MULTISIG_KEX_MSG_V2_MAGIC_1)\n    {\n      // try round 1 message\n      multisig_kex_msg_serializable_round1 kex_msg_rnd1;\n\n      if (::serialization::serialize(b_archive, kex_msg_rnd1))\n      {\n        // in round 1 the message stores a private ancillary key component for the multisig account\n        // that will be shared by all participants (e.g. a shared private view key)\n        m_kex_round      = 1;\n        m_msg_privkey    = kex_msg_rnd1.msg_privkey;\n        m_signing_pubkey = kex_msg_rnd1.signing_pubkey;\n        msg_signature    = kex_msg_rnd1.signature;\n      }\n      else\n      {\n        CHECK_AND_ASSERT_THROW_MES(false, \"Deserializing kex msg failed.\");\n      }\n    }\n    else if (m_msg.substr(0, MULTISIG_KEX_MSG_V2_MAGIC_N.size()) == MULTISIG_KEX_MSG_V2_MAGIC_N)\n    {\n      // try general message\n      multisig_kex_msg_serializable_general kex_msg_general;\n\n      if (::serialization::serialize(b_archive, kex_msg_general))\n      {\n        m_kex_round      = kex_msg_general.kex_round;\n        m_msg_privkey    = crypto::null_skey;\n        m_msg_pubkeys    = std::move(kex_msg_general.msg_pubkeys);\n        m_signing_pubkey = kex_msg_general.signing_pubkey;\n        msg_signature    = kex_msg_general.signature;\n\n        CHECK_AND_ASSERT_THROW_MES(m_kex_round > 1, \"Invalid kex message round (must be > 1 for the general msg type).\");\n      }\n      else\n      {\n        CHECK_AND_ASSERT_THROW_MES(false, \"Deserializing kex msg failed.\");\n      }\n    }\n    else\n    {\n      // unknown message type\n      CHECK_AND_ASSERT_THROW_MES(false, \"Only v2 multisig kex messages are supported.\");\n    }\n\n    // checks\n    for (const auto &pubkey: m_msg_pubkeys)\n    {\n      CHECK_AND_ASSERT_THROW_MES(pubkey != crypto::null_pkey && pubkey != rct::rct2pk(rct::identity()),\n        \"Pubkey from message was invalid.\");\n      CHECK_AND_ASSERT_THROW_MES(rct::isInMainSubgroup(rct::pk2rct(pubkey)),\n        \"Pubkey from message was not in prime subgroup.\");\n    }\n\n    CHECK_AND_ASSERT_THROW_MES(m_signing_pubkey != crypto::null_pkey && m_signing_pubkey != rct::rct2pk(rct::identity()),\n      \"Message signing key was invalid.\");\n    CHECK_AND_ASSERT_THROW_MES(rct::isInMainSubgroup(rct::pk2rct(m_signing_pubkey)),\n      \"Message signing key was not in prime subgroup.\");\n\n    // validate signature\n    crypto::hash signed_msg{get_msg_to_sign()};\n    CHECK_AND_ASSERT_THROW_MES(crypto::check_signature(signed_msg, m_signing_pubkey, msg_signature),\n      \"Multisig kex msg signature invalid.\");\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n} //namespace multisig\n", "meta": {"hexsha": "e1cc86a7357a55d5a6977060f2f8f55a80ce307c", "size": 12318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multisig/multisig_kex_msg.cpp", "max_stars_repo_name": "Snider/blockchain", "max_stars_repo_head_hexsha": "64a856edc03f2e0b52a1c4475f16f60b5e20acc9", "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/multisig/multisig_kex_msg.cpp", "max_issues_repo_name": "Snider/blockchain", "max_issues_repo_head_hexsha": "64a856edc03f2e0b52a1c4475f16f60b5e20acc9", "max_issues_repo_licenses": ["MIT"], "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/multisig/multisig_kex_msg.cpp", "max_forks_repo_name": "Snider/blockchain", "max_forks_repo_head_hexsha": "64a856edc03f2e0b52a1c4475f16f60b5e20acc9", "max_forks_repo_licenses": ["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.3298969072, "max_line_length": 122, "alphanum_fraction": 0.637035233, "num_tokens": 2936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.18384634422629953}}
{"text": "\ufeff/*! \\file meshlist.cpp\n    \\brief \u30a2\u30eb\u30b4\u30f3\u306b\u5bfe\u3057\u3066\u3001\u5206\u5b50\u52d5\u529b\u5b66\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u3092\u884c\u3046\u30af\u30e9\u30b9\u306e\u5ba3\u8a00\n\n    Copyright \u00a9  2017 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"meshlist.h\"\n#include <algorithm>        // for std::fill\n#include <boost/assert.hpp> // for BOOST_ASSERT\n\nnamespace moleculardynamics {\n    MeshList::MeshList(double periodiclen) : periodiclen_(periodiclen)\n    {\n        auto const SL = SystemParam::RCUTOFF + SystemParam::MARGIN;\n        \n        m_ = static_cast<std::int32_t>(periodiclen / SL) - 1;\n        mesh_size_ = static_cast<double>(periodiclen) / m_;\n        \n        BOOST_ASSERT(m_ > 2);\n        BOOST_ASSERT(mesh_size_ > SL);\n        \n        number_of_mesh_ = m_ * m_ * m_;\n        count_.resize(number_of_mesh_);\n        indexes_.resize(number_of_mesh_);\n    }\n\n    void MeshList::make_pair(SystemParam::myatomvector & atoms, SystemParam::mypairvector & pairs)\n    {\n        pairs.clear();\n        \n        auto const pn = atoms.size();\n\n        std::vector<std::int32_t> particle_position(pn, 0);\n        std::vector<std::int32_t> pointer(number_of_mesh_, 0);\n\n        std::fill(count_.begin(), count_.end(), 0);\n\n        auto const im = 1.0 / mesh_size_;\n        for (auto i = 0; i < pn; i++) {\n            auto ix = static_cast<std::int32_t>(atoms[i].r[0] * im);\n            auto iy = static_cast<std::int32_t>(atoms[i].r[1] * im);\n            auto iz = static_cast<std::int32_t>(atoms[i].r[2] * im);\n            \n            if (ix < 0) {\n                ix += m_;\n            }\n            else if (ix >= m_) {\n                ix -= m_;\n            }\n\n            if (iy < 0) {\n                iy += m_;\n            }\n            else if (iy >= m_) {\n                iy -= m_;\n            }\n            if (iz < 0) {\n                iz += m_;\n            }\n            else if (iz >= m_) {\n                iz -= m_;\n            }\n\n            auto const index = ix + iy * m_ + iz * m_ * m_;\n            \n            BOOST_ASSERT(index >= 0);\n            BOOST_ASSERT(index < number_of_mesh_);\n            \n            count_[index]++;\n            particle_position[i] = index;\n        }\n        \n        indexes_[0] = 0;\n        auto sum = 0;\n        \n        for (auto i = 0; i < number_of_mesh_ - 1; i++) {\n            sum += count_[i];\n            indexes_[i + 1] = sum;\n        }\n        \n        for (auto i = 0; i < pn; i++) {\n            auto const pos = particle_position[i];\n            auto const j = indexes_[pos] + pointer[pos];\n            sorted_buffer[j] = i;\n            ++pointer[pos];\n        }\n        \n        for (auto i = 0; i < number_of_mesh_; i++) {\n            search(i, atoms, pairs);\n        }\n    }\n\n    void MeshList::search_other(std::int32_t id, std::int32_t ix, std::int32_t iy, std::int32_t iz, SystemParam::myatomvector & atoms, SystemParam::mypairvector & pairs)\n    {\n        if (ix < 0) {\n            ix += m_;\n        }\n        else if (ix >= m_) {\n            ix -= m_;\n        }\n        \n        if (iy < 0) {\n            iy += m_;\n        }\n        else if (iy >= m_) {\n            iy -= m_;\n        }\n        \n        if (iz < 0) {\n            iz += m_;\n        }\n        else if (iz >= m_) {\n            iz -= m_;\n        }\n        \n        auto const id2 = ix + iy * m_ + iz * m_ * m_;\n\n        for (auto k = indexes_[id]; k < indexes_[id] + count_[id]; k++) {\n            for (auto m_ = indexes_[id2]; m_ < indexes_[id2] + count_[id2]; m_++) {\n                auto const i = sorted_buffer[k];\n                auto const j = sorted_buffer[m_];\n\n                Eigen::Vector4d d = atoms[j].r - atoms[i].r;\n                \n                SystemParam::adjust_periodic(d, periodiclen_);\n                \n                if (d.squaredNorm() <= SystemParam::ML2) {\n                    pairs.push_back(std::make_pair(i, j));\n                }\n            }\n        }\n    }\n\n    void MeshList::search(std::int32_t id, SystemParam::myatomvector & atoms, SystemParam::mypairvector & pairs)\n    {\n        auto const ix = id % m_;\n        auto const iy = (id / m_) % m_;\n        auto const iz = (id / m_ / m_);\n\n        search_other(id, ix + 1, iy, iz, atoms, pairs);\n        search_other(id, ix - 1, iy + 1, iz, atoms, pairs);\n        search_other(id, ix, iy + 1, iz, atoms, pairs);\n        search_other(id, ix + 1, iy + 1, iz, atoms, pairs);\n\n        search_other(id, ix - 1, iy, iz + 1, atoms, pairs);\n        search_other(id, ix, iy, iz + 1, atoms, pairs);\n        search_other(id, ix + 1, iy, iz + 1, atoms, pairs);\n\n        search_other(id, ix - 1, iy - 1, iz + 1, atoms, pairs);\n        search_other(id, ix, iy - 1, iz + 1, atoms, pairs);\n        search_other(id, ix + 1, iy - 1, iz + 1, atoms, pairs);\n\n        search_other(id, ix - 1, iy + 1, iz + 1, atoms, pairs);\n        search_other(id, ix, iy + 1, iz + 1, atoms, pairs);\n        search_other(id, ix + 1, iy + 1, iz + 1, atoms, pairs);\n\n        // Registration of self box\n        auto const si = indexes_[id];\n        auto const n = count_[id];\n\n        for (auto k = si; k < si + n - 1; k++) {\n            for (auto m_ = k + 1; m_ < si + n; m_++) {\n                auto const i = sorted_buffer[k];\n                auto const j = sorted_buffer[m_];\n\n                Eigen::Vector4d d = atoms[j].r - atoms[i].r;\n\n                SystemParam::adjust_periodic(d, periodiclen_);\n\n                if (d.squaredNorm() <= SystemParam::ML2) {\n                    pairs.push_back(std::make_pair(i, j));\n                }\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "ba813a7e5d68250f209baa44fa7e1347e6add560", "size": 5510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moleculardynamics/meshlist.cpp", "max_stars_repo_name": "dc1394/LJ_Argon_MD2", "max_stars_repo_head_hexsha": "d010df2563541008eb0bf76a382537038ded3e6f", "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": "moleculardynamics/meshlist.cpp", "max_issues_repo_name": "dc1394/LJ_Argon_MD2", "max_issues_repo_head_hexsha": "d010df2563541008eb0bf76a382537038ded3e6f", "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": "moleculardynamics/meshlist.cpp", "max_forks_repo_name": "dc1394/LJ_Argon_MD2", "max_forks_repo_head_hexsha": "d010df2563541008eb0bf76a382537038ded3e6f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-05T21:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-05T21:18:09.000Z", "avg_line_length": 30.9550561798, "max_line_length": 169, "alphanum_fraction": 0.4676950998, "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.18384634065749497}}
{"text": "/******************************\n  Copyright (C) 2021 Icey Chiu\n******************************/\n#include <boost/lexical_cast.hpp>\n#include \"../include/marker_detection.h\"\n\nint main(int argc,char **argv){\n//   if (argc != 2 ){ std::cerr<<\"Usage: inimage\"<<std::endl;return -1;}\n     /* load parameters */\n    const std::string h_matrix_dir = \"/home/zebra/test/groundtruth/extrinsic_calibrationfile.yaml\";\n    std::string result_dir;\n    const std::string setting_dir = \"/home/zebra/test/groundtruth/intrinsic_calibrationfile.yaml\";\n    \n    groundtruth gt;\n    gt.intrinsic(setting_dir);\n    aruco::MarkerDetector MDetector;\n    MDetector.setDictionary(\"ARUCO\");\n    cv::String folder = \"/home/zebra/Downloads/2020325/image/*.png\";                                         \n    std::vector<cv::String> filenames;\n    std::vector<cv::String> names;\n    std::vector<double> name;\n    cv::glob(folder, filenames, false);\n    int nImages = filenames.size();\n    cv::Mat image;\n    float start_x;\n    float start_y;\n    /*\n    for (int i = 0; i < nImages; ++i)\n    {\n        images.push_back(cv::imread(filenames[i]));\n    }\n    */\n    for (int i = 0; i < nImages; ++i)\n    {\n        image = cv::imread(filenames[i]);\n        if (image.empty())\n        {\n            std::cout << \"frame: \" << image << std::endl;\n            break;\n        }\n        \n        gt.undistort(image);\n        gt.pnp(h_matrix_dir, i);\n        gt.markers;\n        for (size_t i = 0; i < gt.markers.size(); i++){ \n            int id = gt.markers[i].id;\n        \n            switch ( id )\n            {\n                case 0:\n                    result_dir = \"/home/zebra/test/groundtruth/result_0.txt\";\n                    break;\n                case 1:\n                    result_dir = \"/home/zebra/test/groundtruth/result_1.txt\";\n                    break;\n                case 10:\n                    result_dir = \"/home/zebra/test/groundtruth/result_10.txt\";\n                    break;\n                case 16:\n                    result_dir = \"/home/zebra/test/groundtruth/result_16.txt\";\n                    break;\n                case 23:\n                    result_dir = \"/home/zebra/test/groundtruth/result_23.txt\";\n                    break;\n            }\n        }\n        if (i == 0)\n        {\n            start_x = gt.pt[i][0];\n            start_y = gt.pt[i][1];\n        }\n        std::ofstream  groundtruth_file(result_dir, std::ofstream::app);\n\tstd::cout << filenames[i] << std::endl;\n        names.push_back(filenames[i].substr(36, 19));\n        name.push_back(std::stod(names[i], NULL) / 1000000000.00);\n        if (i > 0)\n            if (((name[i] - name[i - 1]) < 0.06) && ((abs(gt.pt[i][0] - gt.pt[i - 1][0]) > 0.02) || (abs(gt.pt[i][1] - gt.pt[i - 1][1]) > 0.02)))\n                continue;\n        groundtruth_file << names[i] << \" \" << (gt.pt[i][0] - start_x) * 0.96595 - 0.0221 << \" \" << (gt.pt[i][1] - start_y) * 0.96595 + 0.001895 << \" 0.0\"\n                << \" 0.0\" << \" 0.0\" << \" 0.0\" << \" 0.0\" << std::endl;\n\n        imshow(\"video\", image);\n        //cv::waitKey(1);\n   }\n   return 0;\n}\n\n", "meta": {"hexsha": "e38f44185dbe6d212e88aea3e424dd3f014037d5", "size": 3086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/MVS/Samples/64/GrabImage/src/marker_detection.cpp", "max_stars_repo_name": "IceyChiu/Visual-Tracking-System", "max_stars_repo_head_hexsha": "d43b873a408d94a5c7191fcaeae5b94f8d6e4087", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-09T02:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T02:40:57.000Z", "max_issues_repo_path": "thirdparty/MVS/Samples/64/GrabImage/src/marker_detection.cpp", "max_issues_repo_name": "IceyChiu/Visual-Tracking-System", "max_issues_repo_head_hexsha": "d43b873a408d94a5c7191fcaeae5b94f8d6e4087", "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": "thirdparty/MVS/Samples/64/GrabImage/src/marker_detection.cpp", "max_forks_repo_name": "IceyChiu/Visual-Tracking-System", "max_forks_repo_head_hexsha": "d43b873a408d94a5c7191fcaeae5b94f8d6e4087", "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.0681818182, "max_line_length": 154, "alphanum_fraction": 0.4841218406, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18384634065749494}}
{"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_PPC_VMX_LIMITS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_PPC_VMX_LIMITS_HPP_INCLUDED\n\n#include <boost/simd/arch/ppc/tags.hpp>\n#include <boost/simd/arch/common/limits.hpp>\n#include <boost/simd/detail/dispatch/meta/make_integer.hpp>\n#include <boost/simd/detail/brigand.hpp>\n#include <cstdint>\n\nnamespace boost { namespace simd\n{\n  template<> struct limits<boost::simd::vmx_>\n  {\n    using parent = boost::simd::simd_;\n\n    struct largest_integer\n    {\n      template<typename Sign> struct apply : boost::dispatch::make_integer<4,Sign> {};\n    };\n\n    struct smallest_integer\n    {\n      template<typename Sign> struct apply : boost::dispatch::make_integer<1,Sign> {};\n    };\n\n    using largest_real   = float;\n    using smallest_real  = float;\n\n    enum { bits = 128, bytes = 16 };\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "ae3f96c669e5138ec44d92741f34d05d3d2bd1b4", "size": 1199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/ppc/vmx/limits.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/ppc/vmx/limits.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/ppc/vmx/limits.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": 28.5476190476, "max_line_length": 100, "alphanum_fraction": 0.5921601334, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3486451353339457, "lm_q1q2_score": 0.18384634065749492}}
{"text": "/*\n * Copyright 2021 IBM Corporation\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 <SPL/Runtime/Common/RuntimeDebugAspect.h>\n#include <SPL/Runtime/ProcessingElement/ElasticPortAdapter.h>\n#include <SPL/Runtime/ProcessingElement/PEImpl.h>\n#include <TRC/DistilleryDebug.h>\n\n#include <boost/thread/thread.hpp>\n\n#include <cmath>\n#include <fstream>\n\nusing namespace SPL;\n#define PERF_GROUP_NUM 9\n#define PERF_GROUP_SIZE 40\n#define GRANULARITY 0.1\n\n/*Adjustment entry related functions */\nElasticPortAdapter::Adjustment::Adjustment(double& prevThroughput,\n                                           std::vector<uint32_t>& operators,\n                                           int& groupNum)\n  : maxThroughput_(prevThroughput)\n  , operators_(operators)\n  , curGroup_(groupNum)\n{\n    initialize();\n}\n\nvoid ElasticPortAdapter::Adjustment::initialize()\n{\n    lastPositivePos_ = -1;\n    size_ = (int)operators_.size();\n    currLevel_ = size_;\n    currAdjustment_ = new MetaAdjustment(size_, size_, 0, size_, 0);\n    adjustInfo_[size_] = currAdjustment_;\n    range_.first = 0;\n    range_.second = size_;\n}\n\nElasticPortAdapter::Adjustment::~Adjustment()\n{\n    for (std::map<int, MetaAdjustment*>::iterator it = adjustInfo_.begin(); it != adjustInfo_.end();\n         ++it) {\n        delete it->second;\n    }\n}\n\nbool ElasticPortAdapter::Adjustment::trustAbove()\n{\n    if (adjustInfo_.find(currAdjustment_->aboveLevel) == adjustInfo_.end()) {\n        return false;\n    }\n    return true;\n}\n\nbool ElasticPortAdapter::Adjustment::trustBelow()\n{\n    if (adjustInfo_.find(currAdjustment_->belowLevel) == adjustInfo_.end()) {\n        return false;\n    }\n    return true;\n}\n\nbool ElasticPortAdapter::Adjustment::trendAbove()\n{\n    std::map<int, MetaAdjustment*>::iterator above = adjustInfo_.find(currAdjustment_->aboveLevel);\n    if (above == adjustInfo_.end()) {\n        return false;\n    }\n\n    MetaAdjustment* aboveAdjust = above->second;\n    if (aboveAdjust->throughput > curThroughput_ &&\n        (aboveAdjust->throughput - curThroughput_) > 0.05 * curThroughput_) {\n        return true;\n    }\n\n    return false;\n}\n\nbool ElasticPortAdapter::Adjustment::trendBelow()\n{\n    std::map<int, MetaAdjustment*>::iterator below = adjustInfo_.find(currAdjustment_->belowLevel);\n    if (below == adjustInfo_.end()) {\n        return false;\n    }\n\n    MetaAdjustment* belowAdjust = below->second;\n    if (curThroughput_ > belowAdjust->throughput &&\n        (curThroughput_ - belowAdjust->throughput) > belowAdjust->throughput * 0.05) {\n        return true;\n    }\n\n    return false;\n}\n\n/*\n *Evaluate the performance trend between the MetaAdjustment\n */\nElasticPortAdapter::AdjustDecision ElasticPortAdapter::Adjustment::nextStep(bool furtherRefine)\n{\n    ElasticPortAdapter::AdjustDecision decision;\n    if (!furtherRefine) {\n        searchMax(decision);\n    } else {\n        if ((trendBelow() && !trustAbove()) || trendAbove()) {\n            // increase scheduler queue count\n            int nextLevel_ = (currAdjustment_->upperBound + currLevel_) / 2;\n            if ((nextLevel_ - currLevel_) <= 2) {\n                // too small adjustment, stop\n                searchMax(decision);\n            } else {\n                int newAboveLevel = currAdjustment_->upperBound;\n                int newBelowLevel = currLevel_;\n                MetaAdjustment* tmp = currAdjustment_;\n                while (tmp->next != NULL) {\n                    tmp = tmp->next;\n                    // search for the adjustment above the current level\n                    if (tmp->level > nextLevel_ && tmp->level < newAboveLevel) {\n                        newAboveLevel = tmp->level;\n                    }\n                    if (tmp->level < nextLevel_ && tmp->level > newBelowLevel) {\n                        newBelowLevel = tmp->level;\n                    }\n                }\n\n                if ((newAboveLevel - nextLevel_) <= 2 || (nextLevel_ - newBelowLevel) <= 2) {\n                    // the difference between previous adjustment is too small, stop\n                    searchMax(decision);\n                } else {\n                    adjustRange_.first = currLevel_;\n                    adjustRange_.second = nextLevel_;\n                    range_.second = nextLevel_;\n                    int newUpperBound = currAdjustment_->upperBound;\n                    int newLowerBound = currLevel_;\n                    currAdjustment_ = new MetaAdjustment(nextLevel_, newAboveLevel, newBelowLevel,\n                                                         newUpperBound, newLowerBound);\n                    insertAdjustment(newAboveLevel, newBelowLevel);\n                    adjustInfo_[nextLevel_] = currAdjustment_;\n                    currLevel_ = nextLevel_;\n                    decision = CONTINUE_UP;\n                }\n            }\n        } else if (currLevel_ == size_ || !trustBelow() || !trendBelow()) {\n            // decrease the scheduler queue count\n            int nextLevel_ = (currAdjustment_->lowerBound + currLevel_) / 2;\n            if ((currLevel_ - nextLevel_) <= 2) {\n                // too small adjustment, stop\n                searchMax(decision);\n            } else {\n                int newAboveLevel = currLevel_;\n                int newBelowLevel = currAdjustment_->lowerBound;\n                MetaAdjustment* tmp = currAdjustment_;\n                while (tmp->prev != NULL) {\n                    tmp = tmp->prev;\n                    if (tmp->level > nextLevel_ && tmp->level < newAboveLevel) {\n                        newAboveLevel = tmp->level;\n                    }\n                    if (tmp->level < nextLevel_ && tmp->level > newBelowLevel) {\n                        newBelowLevel = tmp->level;\n                    }\n                }\n\n                if ((newAboveLevel - nextLevel_) <= 2 || (nextLevel_ - newBelowLevel) <= 2) {\n                    searchMax(decision);\n                } else {\n                    adjustRange_.second = currLevel_;\n                    adjustRange_.first = nextLevel_;\n                    range_.second = nextLevel_;\n                    int newUpperBound = currAdjustment_->aboveLevel;\n                    int newLowerBound = currAdjustment_->lowerBound;\n                    currAdjustment_ = new MetaAdjustment(nextLevel_, newAboveLevel, newBelowLevel,\n                                                         newUpperBound, newLowerBound);\n                    insertAdjustment(newAboveLevel, newBelowLevel);\n                    adjustInfo_[nextLevel_] = currAdjustment_;\n                    currLevel_ = nextLevel_;\n                    decision = CONTINUE_DOWN;\n                }\n            }\n        } else {\n            // trendBelow & !trendAbove\n            searchMax(decision);\n        }\n    }\n    return decision;\n}\n\nvoid ElasticPortAdapter::Adjustment::insertAdjustment(int above, int below)\n{\n    std::map<int, MetaAdjustment*>::iterator it_above = adjustInfo_.find(above);\n    std::map<int, MetaAdjustment*>::iterator it_below = adjustInfo_.find(below);\n    if (it_above != adjustInfo_.end()) {\n        MetaAdjustment* aboveAdjust = it_above->second;\n        if (aboveAdjust->prev != NULL) {\n            aboveAdjust->prev->next = currAdjustment_;\n        }\n        currAdjustment_->next = aboveAdjust;\n        aboveAdjust->prev = currAdjustment_;\n    }\n\n    if (it_below != adjustInfo_.end()) {\n        MetaAdjustment* belowAdjust = it_below->second;\n        if (belowAdjust->next != NULL) {\n            belowAdjust->next->prev = currAdjustment_;\n        }\n        currAdjustment_->prev = belowAdjust;\n        belowAdjust->next = currAdjustment_;\n    }\n}\n\nvoid ElasticPortAdapter::Adjustment::extend(std::vector<uint32_t>& ops, int c)\n{\n    curGroup_ = c;\n    operators_.insert(operators_.end(), ops.begin(), ops.end());\n    size_ = (int)operators_.size();\n    currLevel_ = size_;\n    adjustRange_.first = range_.second;\n    adjustRange_.second = size_;\n    range_.first = 0;\n    range_.second = size_;\n    for (std::map<int, MetaAdjustment*>::iterator it = adjustInfo_.begin(); it != adjustInfo_.end();\n         ++it) {\n        delete it->second;\n    }\n    adjustInfo_.clear();\n    currAdjustment_ = new MetaAdjustment(size_, size_, 0, size_, 0);\n    adjustInfo_[size_] = currAdjustment_;\n}\n\nvoid ElasticPortAdapter::Adjustment::incStat(double& throughput)\n{\n    curThroughput_ = throughput;\n    currAdjustment_->throughput = throughput;\n}\n\nvoid ElasticPortAdapter::Adjustment::searchMax(ElasticPortAdapter::AdjustDecision& decision)\n{\n    for (std::map<int, MetaAdjustment*>::iterator it = adjustInfo_.begin(); it != adjustInfo_.end();\n         ++it) {\n        MetaAdjustment* tmp = it->second;\n        if (tmp->throughput > maxThroughput_ &&\n            (tmp->throughput - maxThroughput_) > 0.05 * maxThroughput_) {\n            maxThroughput_ = tmp->throughput;\n            lastPositivePos_ = it->first;\n        }\n    }\n    if (lastPositivePos_ != -1) {\n        decision = RESET;\n    } else {\n        decision = NEG_STOP;\n    }\n}\n/*End Adjustment entry related functions */\n\n/*ElasticPortAdapter related functions */\nElasticPortAdapter::ElasticPortAdapter(ScheduledQueue& sq)\n  : _sq(sq)\n{\n    initialize(UP);\n}\n\nvoid ElasticPortAdapter::initialize(AdjustDirection dir)\n{\n    _trend = dir;\n    _curAdjustment = NULL;\n    _recordHist = false;\n    _affectedPorts.clear();\n}\n\nvoid ElasticPortAdapter::clear()\n{\n    _sq.turnOffScheduledPort(_tmpExcludedSet);\n    _tmpExcludedSet.clear();\n    _affectedPorts.clear();\n    initialize(UP);\n}\n\nvoid ElasticPortAdapter::adjust(double& t)\n{\n    if (_curAdjustment == NULL) {\n        addNewAdjustment(t);\n    } else {\n        refine(t);\n    }\n}\n\n/*\n *Evaluate whether to continue with QueueElasticity\n */\nvoid ElasticPortAdapter::refine(double& t)\n{\n    _curAdjustment->incStat(t);\n    bool furtherRefine =\n      _curAdjustment->getSize() <= GRANULARITY * (int)_sq.getScheduledPortCount() ? false : true;\n    AdjustDecision ad = _curAdjustment->nextStep(furtherRefine);\n    switch (ad) {\n        case CONTINUE:\n            break;\n        case RESET: {\n            resetSchedulerQueuePlacement();\n            confirmToRemove(_curAdjustment->getOperators(), _curAdjustment->getRange());\n\n            double maxThroughput = _curAdjustment->getMaxThroughput();\n            _affectedPorts.insert(_affectedPorts.end(), _curAdjustment->getOperators().begin(),\n                                  _curAdjustment->getOperators().begin() +\n                                    _curAdjustment->getEndPos());\n            _recordHist = true;\n\n            delete _curAdjustment;\n            _curAdjustment = NULL;\n            addNewAdjustment(maxThroughput);\n        } break;\n\n        case NEG_STOP: {\n            bool toExtend =\n              (_curAdjustment->getSize() > GRANULARITY * (int)_sq.getScheduledPortCount()) ? false\n                                                                                           : true;\n\n            if (toExtend && extendAdjustment()) {\n                if (_trend == UP) {\n                    _sq.turnOnScheduledPort(_curAdjustment->getOperators(),\n                                            _curAdjustment->getAdjustRange());\n                } else {\n                    _sq.turnOffScheduledPort(_curAdjustment->getOperators(),\n                                             _curAdjustment->getAdjustRange());\n                }\n            } else {\n                if (_trend == UP) {\n                    _sq.turnOffScheduledPort(_curAdjustment->getOperators(),\n                                             _curAdjustment->getRange());\n                } else {\n                    _sq.turnOnScheduledPort(_curAdjustment->getOperators(),\n                                            _curAdjustment->getRange());\n                }\n                double maxThroughput = _curAdjustment->getMaxThroughput();\n                delete _curAdjustment;\n                _curAdjustment = NULL;\n                _sq.adjustingDone(_recordHist, _trend, maxThroughput, _affectedPorts);\n                _affectedPorts.clear();\n            }\n        } break;\n\n        case CONTINUE_DOWN: {\n            if (_trend == UP) {\n                _sq.turnOffScheduledPort(_curAdjustment->getOperators(),\n                                         _curAdjustment->getAdjustRange());\n            } else {\n                _sq.turnOnScheduledPort(_curAdjustment->getOperators(),\n                                        _curAdjustment->getAdjustRange());\n            }\n        } break;\n\n        case CONTINUE_UP: {\n            if (_trend == UP) {\n                _sq.turnOnScheduledPort(_curAdjustment->getOperators(),\n                                        _curAdjustment->getAdjustRange());\n            } else {\n                _sq.turnOffScheduledPort(_curAdjustment->getOperators(),\n                                         _curAdjustment->getAdjustRange());\n            }\n        } break;\n    }\n}\n\n// reset the placement to the best performance configuration\nvoid ElasticPortAdapter::resetSchedulerQueuePlacement()\n{\n    int end = _curAdjustment->getEndPos();\n    int lastPositiveEnd = _curAdjustment->getLastPositivePos();\n    if (_trend == UP) {\n        if (lastPositiveEnd > end) {\n            std::pair<int, int> ret = std::make_pair(end, lastPositiveEnd);\n            _sq.turnOnScheduledPort(_curAdjustment->getOperators(), ret);\n        } else if (lastPositiveEnd < end) {\n            std::pair<int, int> ret = std::make_pair(lastPositiveEnd, end);\n            _sq.turnOffScheduledPort(_curAdjustment->getOperators(), ret);\n        }\n    } else {\n        if (lastPositiveEnd > end) {\n            std::pair<int, int> ret = std::make_pair(end, lastPositiveEnd);\n            _sq.turnOffScheduledPort(_curAdjustment->getOperators(), ret);\n        } else if (lastPositiveEnd < end) {\n            std::pair<int, int> ret = std::make_pair(lastPositiveEnd, end);\n            _sq.turnOnScheduledPort(_curAdjustment->getOperators(), ret);\n        }\n    }\n    _curAdjustment->reset();\n}\n\nbool ElasticPortAdapter::extendAdjustment()\n{\n    int i;\n    if (_trend == UP) {\n        i = getPrevGroupNum(_curAdjustment->getCurGroupNum());\n    } else {\n        i = getNextGroupNum(_curAdjustment->getCurGroupNum());\n    }\n    if (i != -1) {\n        std::vector<uint32_t>& operators = _perfGroups[i];\n        _curAdjustment->extend(operators, i);\n        return true;\n    } else {\n        return false;\n    }\n}\n\nvoid ElasticPortAdapter::addNewAdjustment(double& t)\n{\n    int curGroup;\n    int i;\n\n    groupOperators();\n\n    if (_trend == UP) {\n        i = getHeaviestGroupNum();\n    } else {\n        i = getLightestGroupNum();\n    }\n\n    if (i != -1) {\n        curGroup = i;\n        std::vector<uint32_t>& operators = _perfGroups[i];\n        _curAdjustment = new Adjustment(t, operators, curGroup);\n        if (_trend == UP) {\n            _sq.turnOnScheduledPort(operators, _curAdjustment->getRange());\n        } else {\n            _sq.turnOffScheduledPort(operators, _curAdjustment->getRange());\n        }\n    } else {\n        // no available queues for adjustment\n        _sq.adjustingDone(false, _trend, 0.0, _affectedPorts);\n    }\n}\n\nint ElasticPortAdapter::getNextGroupNum(int& i)\n{\n    if (i == PERF_GROUP_NUM - 1) {\n        return -1;\n    }\n    assert(i + 1 >= 0);\n    for (unsigned int j = i + 1; j < PERF_GROUP_NUM; j++) {\n        assert(j <= PERF_GROUP_NUM - 1);\n        if (_perfGroups[j].size() != 0) {\n            return j;\n        }\n    }\n    return -1;\n}\n\nint ElasticPortAdapter::getPrevGroupNum(int& i)\n{\n    if (i == 0) {\n        return -1;\n    }\n    assert(i - 1 >= 0);\n    for (unsigned int j = i - 1;; j--) {\n        assert(j <= PERF_GROUP_NUM - 1);\n        if (_perfGroups[j].size() != 0) {\n            return j;\n        }\n        if (j == 0) {\n            break;\n        }\n    }\n    return -1;\n}\n\nint ElasticPortAdapter::getHeaviestGroupNum()\n{\n    int heaviestGroup = -1;\n    for (unsigned int i = PERF_GROUP_NUM - 1;; i--) {\n        if (_perfGroups[i].size() != 0) {\n            heaviestGroup = i;\n            break;\n        }\n        if (i == 0) {\n            break;\n        }\n    }\n    return heaviestGroup;\n}\n\nint ElasticPortAdapter::getLightestGroupNum()\n{\n    int cheapestGroup = -1;\n    for (unsigned int i = 0; i < PERF_GROUP_NUM; i++) {\n        if (_perfGroups[i].size() != 0) {\n            cheapestGroup = i;\n            break;\n        }\n    }\n    return cheapestGroup;\n}\n\nvoid ElasticPortAdapter::groupOperators()\n{\n    _perfGroups.clear();\n    _perfGroups.resize(PERF_GROUP_NUM);\n\n    ThreadProfiler& tp = PEImpl::instance().getThreadProfiler();\n    std::vector<double> relativeCost;\n    relativeCost.resize(PEImpl::instance().getOperators().size(), 0);\n    tp.getOperatorRelativeCost(relativeCost);\n\n    if (_trend == DOWN) {\n        //_trend DOWN fill the min bin first\n        std::vector<uint32_t> relatedOperators;\n        double min = 1;\n        for (unsigned int i = 0; i < relativeCost.size(); i++) {\n            if (_sq.hasScheduledPort(i)) {\n                std::set<uint32_t>::iterator it = _tmpExcludedSet.find(i);\n                if (_trend == DOWN && it != _tmpExcludedSet.end()) {\n                    relatedOperators.push_back(i);\n                    double counter = relativeCost[i];\n                    if (counter > 0.0 && min > counter) {\n                        min = counter;\n                    }\n                }\n            }\n        }\n\n        for (unsigned int i = 0; i < relatedOperators.size(); i++) {\n            unsigned int j = relatedOperators[i];\n            int base = int(floor((double)relativeCost[j] / (double)min));\n            if (base == 0) {\n                _perfGroups[0].push_back(j);\n            } else {\n                base = floor(log2(base) / log2(2)) + 1;\n                if (base >= PERF_GROUP_NUM) {\n                    base = PERF_GROUP_NUM - 1;\n                }\n                _perfGroups[base].push_back(j);\n            }\n        }\n    } else {\n        //_trend UP fill the max bin first\n        std::vector<uint32_t> relatedOperators;\n        double max = 0;\n        for (unsigned int i = 0; i < relativeCost.size(); i++) {\n            if (_sq.hasScheduledPort(i)) {\n                std::set<uint32_t>::iterator it = _tmpExcludedSet.find(i);\n                if (_trend == UP && it == _tmpExcludedSet.end()) {\n                    relatedOperators.push_back(i);\n                    double counter = relativeCost[i];\n                    if (counter > 0.0 && counter > max) {\n                        max = counter;\n                    }\n                }\n            }\n        }\n\n        for (unsigned int i = 0; i < relatedOperators.size(); i++) {\n            unsigned int j = relatedOperators[i];\n            if (relativeCost[j] <= 0.0) {\n                _perfGroups[0].push_back(j);\n            } else {\n                int base = int(floor((double)max / (double)relativeCost[j]));\n                base = PERF_GROUP_NUM - base;\n                if (base < 0) {\n                    base = 0;\n                }\n                _perfGroups[base].push_back(j);\n            }\n        }\n    }\n}\n\nvoid ElasticPortAdapter::confirmToRemove(vector<uint32_t>& operators, pair<int, int>& range)\n{\n    if (_trend == UP) {\n        _tmpExcludedSet.insert(operators.begin() + range.first, operators.begin() + range.second);\n    } else {\n        for (int i = range.first; i < range.second; i++) {\n            _tmpExcludedSet.erase(operators[i]);\n        }\n    }\n}\n\nvoid ElasticPortAdapter::confirmToAdd(vector<uint32_t>& operators, pair<int, int>& range)\n{\n    if (_trend == DOWN) {\n        _tmpExcludedSet.insert(operators.begin() + range.first, operators.begin() + range.second);\n    } else {\n        for (int i = range.first; i < range.second; i++) {\n            _tmpExcludedSet.erase(operators[i]);\n        }\n    }\n}\n", "meta": {"hexsha": "63ba9bbdb94b4e4f43ac85e59f7ba024b5ff844e", "size": 20277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/SPL/Runtime/ProcessingElement/ElasticPortAdapter.cpp", "max_stars_repo_name": "IBMStreams/OSStreams", "max_stars_repo_head_hexsha": "c6287bd9ec4323f567d2faf59125baba8604e1db", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-02-19T20:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T05:11:50.000Z", "max_issues_repo_path": "src/cpp/SPL/Runtime/ProcessingElement/ElasticPortAdapter.cpp", "max_issues_repo_name": "xguerin/openstreams", "max_issues_repo_head_hexsha": "7000370b81a7f8778db283b2ba9f9ead984b7439", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T01:17:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-08T14:56:34.000Z", "max_forks_repo_path": "src/cpp/SPL/Runtime/ProcessingElement/ElasticPortAdapter.cpp", "max_forks_repo_name": "IBMStreams/OSStreams", "max_forks_repo_head_hexsha": "c6287bd9ec4323f567d2faf59125baba8604e1db", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T18:43:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T14:18:16.000Z", "avg_line_length": 33.6827242525, "max_line_length": 100, "alphanum_fraction": 0.558662524, "num_tokens": 4672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.1836204506264789}}
{"text": "\n\n#include <dlib/data_io.h>\n#include <dlib/dnn.h>\n#include <dlib/gui_widgets.h>\n#include <dlib/image_processing.h>\n#include <dlib/image_transforms.h>\n#include <dlib/opencv/cv_image.h>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include <boost/asio.hpp>\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#include <opencv2/video/video.hpp>\n\n#include <google/protobuf/util/delimited_message_util.h>\n\n#include \"feature/feature_detect_pipe.h\"\n#include \"util/pcl_cv.h\"\n\n#include \"io/socket/asio.h\"\n#include \"messages/messages.pb.h\"\n\nusing namespace std;\nusing namespace dlib;\nusing namespace telef::io;\nusing namespace boost::asio;\n\nnamespace telef::feature {\n/**\n * DlibFaceDetectionPipe\n * @param pretrained_model\n */\nDlibFaceDetectionPipe::DlibFaceDetectionPipe(\n    const std::string &pretrained_model) {\n  deserialize(pretrained_model) >> net;\n}\n\nFeatureDetectSuite::Ptr DlibFaceDetectionPipe::_processData(InputPtrT in) {\n  matrix<rgb_pixel> img;\n\n  // Convert PCL image to dlib image\n  auto pclImage = in->rawImage;\n\n  auto matImg = cv::Mat(pclImage->getHeight(), pclImage->getWidth(), CV_8UC3);\n  pclImage->fillRGB(matImg.cols, matImg.rows, matImg.data, matImg.step);\n  cv::cvtColor(matImg, matImg, CV_RGB2BGR);\n  dlib::cv_image<bgr_pixel> cvImg(matImg);\n  dlib::assign_image(img, cvImg);\n\n  auto dets = net(img);\n  dlib::rectangle bbox;\n  double detection_confidence = 0;\n\n  // Get best face detected\n  // TODO: Handle face detection failure\n  for (auto &&d : dets) {\n    if (d.detection_confidence > detection_confidence) {\n      detection_confidence = d.detection_confidence;\n      bbox = d.rect;\n    }\n  }\n\n  FeatureDetectSuite::Ptr result = boost::make_shared<FeatureDetectSuite>();\n\n  result->deviceInput = in;\n  result->feature = boost::make_shared<Feature>();\n  result->feature->boundingBox.setBoundingBox(bbox);\n\n  return result;\n}\n\nFeatureDetectionClientPipe::FeatureDetectionClientPipe(\n    string address_, boost::asio::io_service &service)\n    : isConnected(false), address(address_), ioService(service), clientSocket(),\n      msg_id(0) {}\n\n//    FeatureDetectionClientPipe::~FeatureDetectionClientPipe(){\n//        // Cleanly close connection\n//        disconnect();\n//    };\n\nFeatureDetectSuite::Ptr FeatureDetectionClientPipe::_processData(\n    FeatureDetectionClientPipe::InputPtrT in) {\n  if (clientSocket == nullptr || !isConnected) {\n    if (!connect()) {\n      in->feature->points = landmarks;\n      return in;\n    }\n  }\n\n  // Convert PCL image to bytes\n  auto pclImage = in->deviceInput->rawImage;\n  std::vector<unsigned char> imgBuffer(pclImage->getDataSize());\n  pclImage->fillRaw(imgBuffer.data());\n\n  LmkReq reqMsg;\n  auto hdr = reqMsg.mutable_hdr();\n  hdr->set_id(++msg_id);\n  hdr->set_width(pclImage->getHeight());\n  hdr->set_height(pclImage->getWidth());\n  hdr->set_channels(3); // TODO: What if we have grey or 4-ch image??\n\n  auto imgData = reqMsg.mutable_data();\n  imgData->set_buffer(imgBuffer.data(), pclImage->getDataSize());\n\n  auto in_bbox = in->feature->boundingBox.getRect();\n  auto bbox = reqMsg.mutable_bbox();\n  bbox->set_left(in_bbox.left());\n  bbox->set_top(in_bbox.top());\n  bbox->set_right(in_bbox.right());\n  bbox->set_bottom(in_bbox.bottom());\n\n  bool msgSent = send(reqMsg);\n\n  LmkRsp rspMsg;\n  if (msgSent && recv(rspMsg)) {\n    //            cout << \"Lmk Size: \" << rspMsg.dim().shape().size() << endl;\n    //            cout << \"Lmk Dim: \" << rspMsg.dim().shape()[0] << \", \" <<\n    //            rspMsg.dim().shape()[1] << endl;\n\n    auto data = rspMsg.data();\n\n    // construct and populate the matrix\n    cv::Mat m(\n        rspMsg.dim().shape()[0], rspMsg.dim().shape()[1], CV_32F, data.data());\n    //            cout << \"M_lmks = \"  << m << endl << endl;\n\n    // make depth negative??\n    m.col(2) *= -1.0f;\n\n    cv::cv2eigen(m.t(), landmarks);\n    //            cout << \"eigen_Lmks:\\n\" << landmarks << endl;\n  }\n\n  in->feature->points = landmarks;\n  return in;\n}\n\nbool FeatureDetectionClientPipe::send(google::protobuf::MessageLite &msg) {\n  if (isConnected != true)\n    return false;\n\n  try {\n    telef::io::socket::AsioOutputStream aos(*clientSocket);\n    google::protobuf::io::CopyingOutputStreamAdaptor cos_adp(&aos);\n    google::protobuf::io::CodedOutputStream cos(&cos_adp);\n\n    google::protobuf::util::SerializeDelimitedToCodedStream(msg, &cos);\n    cout << \"Sending Message ID: \" << msg_id << endl;\n  } catch (exception &e) {\n    std::cerr << \"Error while sending message: \" << e.what() << endl;\n    disconnect();\n    return false;\n  }\n\n  return true;\n}\n\nbool FeatureDetectionClientPipe::recv(google::protobuf::MessageLite &msg) {\n  if (isConnected != true)\n    return false;\n  try {\n    telef::io::socket::AsioInputStream ais(*clientSocket);\n    google::protobuf::io::CopyingInputStreamAdaptor cis_adp(&ais);\n    google::protobuf::io::CodedInputStream cis(&cis_adp);\n    bool parseStatus = false;\n\n    google::protobuf::util::ParseDelimitedFromCodedStream(\n        &msg, &cis, &parseStatus);\n  } catch (exception &e) {\n    std::cerr << \"Error while receiving message: \" << e.what() << endl;\n    disconnect();\n    return false;\n  }\n\n  return true;\n}\n\nbool FeatureDetectionClientPipe::connect() {\n  isConnected = false;\n\n  clientSocket = make_shared<SocketT>(ioService);\n\n  try {\n    clientSocket->connect(\n        boost::asio::local::stream_protocol::endpoint(address));\n    isConnected = true;\n\n    cout << \"Connected to server\" << endl;\n  } catch (std::exception &e) {\n    std::cerr << e.what() << std::endl;\n    std::cerr << \"Failed to connect to server...\" << std::endl;\n    disconnect();\n  }\n\n  return isConnected;\n}\n\nvoid FeatureDetectionClientPipe::disconnect() {\n  isConnected = false;\n\n  try {\n    // clientSocket->shutdown(boost::asio::ip::tcp::socket::shutdown_both);\n    // clientSocket->close();\n    cout << \"Disconnected...\" << endl;\n  } catch (std::exception &e) {\n    std::cerr << e.what() << std::endl;\n    std::cerr << \"Failed to cleanly disconnect to server...\" << std::endl;\n  }\n\n  clientSocket.reset();\n}\n} // namespace telef::feature\n", "meta": {"hexsha": "d8fe9120059938a1f3dce063e511f0f0af1cd649", "size": 6121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/feature/feature_detect_pipe.cpp", "max_stars_repo_name": "ycjungSubhuman/Kinect-Face", "max_stars_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-12T22:05:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:39:32.000Z", "max_issues_repo_path": "src/feature/feature_detect_pipe.cpp", "max_issues_repo_name": "ycjungSubhuman/Kinect-Face", "max_issues_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_issues_repo_licenses": ["CNRI-Python"], "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/feature_detect_pipe.cpp", "max_forks_repo_name": "ycjungSubhuman/Kinect-Face", "max_forks_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-14T08:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-01T07:11:17.000Z", "avg_line_length": 27.9497716895, "max_line_length": 80, "alphanum_fraction": 0.668518216, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.18359611232982354}}
{"text": "#include <opencv2/opencv.hpp>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <glog/logging.h>\n#include \"../../src/Tracker/OLaRank_old.h\"\n#include \"../../src/Tracker/LocationSampler.h\"\n\n#include \"../../src/Tracker/AllTrackers.h\"\n#include \"../../src/Kernels/AllKernels.h\"\n#include \"../../src/Features/AllFeatures.h\"\n#include \"numpy-opencv-converter/np_opencv_converter.hpp\"\n#include <boost/python.hpp>\n\nclass DeepStruck {\n  public:\n    Struck *tracker;\n\n    std::vector<cv::Rect> rects;\n    cv::Mat currentImage;\n\n    const int maxFeatures = 100;\n\n    // INITIALIZE #1\n    void initializeBefore(std::string filename, int x, int y, int width,\n                          int height) {\n\n        cv::Mat image = cv::imread(filename);\n        cv::Rect location(x, y, width, height);\n\n        this->currentImage = image.clone();\n        srand(tracker->seed);\n        // set dimensions of the sampler\n\n        tracker->updateEveryNframes = 3;\n        // NOW\n        int m = image.rows;\n        int n = image.cols;\n\n        tracker->samplerForSearch->setDimensions(n, m, location.height,\n                                                 location.width);\n        tracker->samplerForUpdate->setDimensions(n, m, location.height,\n                                                 location.width);\n\n        tracker->boundingBoxes.push_back(location);\n        tracker->lastLocation = location;\n        // sample in polar coordinates first\n\n        std::vector<cv::Rect> locations;\n\n        // add ground truth\n        locations.push_back(location);\n        tracker->samplerForUpdate->sampleEquiDistant(location, locations);\n\n        this->rects = locations;\n    }\n\n    boost::python::list getImages() {\n        boost::python::list out;\n        for (int i = 0; i < this->rects.size(); i++) {\n            cv::Mat im(this->currentImage, this->rects[i]);\n            out.append(im);\n        }\n        return out;\n    }\n\n    // INITIALIZE #3\n    void initializeAfter(const cv::Mat &x) {\n        cv::Mat y = tracker->feature->reshapeYs(this->rects);\n        LOG(INFO) << \"Prior to olarank->initialize\";\n        LOG(INFO) << \"Rows: \" << x.rows;\n        LOG(INFO) << \"Cols: \" << x.cols;\n        LOG(INFO) << \"Type: \" << x.type();\n        LOG(INFO) << \"Rows: \" << y.rows;\n        LOG(INFO) << \"Cols: \" << y.cols;\n\n        tracker->olarank->initialize(x, y, 0, tracker->framesTracked);\n        LOG(INFO) << \"AFTER olarank->initialize\";\n        // add images, in case we want to show support vectors\n\n        if (tracker->display == 1) {\n            cv::Scalar color(0, 255, 0);\n            cv::Mat plotImg = this->currentImage.clone();\n\n            cv::rectangle(plotImg, tracker->lastLocation, color, 2);\n            cv::imshow(\"Tracking window\", plotImg);\n            tracker->objectnessCanvas = plotImg;\n            cv::waitKey(1);\n        }\n\n        tracker->framesTracked++;\n    }\n\n    void trackDetectBefore(std::string filename) {\n        cv::Mat image = cv::imread(filename);\n\n        this->currentImage = image.clone();\n        std::vector<cv::Rect> locationsOnaGrid;\n\n        locationsOnaGrid.push_back(tracker->lastLocation);\n\n        tracker->samplerForSearch->sampleEquiDistantMultiScale(\n            tracker->lastLocation, locationsOnaGrid);\n\n        this->rects = locationsOnaGrid;\n    }\n\n    boost::python::list trackDetectAfter(const cv::Mat &x) {\n        std::vector<double> predictions = tracker->olarank->predictAll(x);\n        int groundTruth = 0;\n        double maxElement = predictions[0];\n        for (int i = 0; i < predictions.size(); i++) {\n            if (maxElement < predictions[i]) {\n                maxElement = predictions[i];\n                groundTruth = i;\n            }\n        }\n        cv::Rect bestLocationDetector = this->rects[groundTruth];\n        tracker->boundingBoxes.push_back(bestLocationDetector);\n        tracker->lastLocation = bestLocationDetector;\n\n        boost::python::list output;\n        cv::Rect r = bestLocationDetector;\n\n        output.append(r.x);\n        output.append(r.y);\n        output.append(r.width);\n        output.append(r.height);\n        return output;\n    }\n\n    void trackUpdateBefore() {\n        if (tracker->updateTracker &&\n            tracker->boundingBoxes.size() % tracker->updateEveryNframes == 0) {\n\n            // sample for updating the tracker\n            std::vector<cv::Rect> locationsOnPolarPlane;\n            locationsOnPolarPlane.push_back(tracker->lastLocation);\n\n            tracker->samplerForUpdate->sampleEquiDistant(tracker->lastLocation,\n                                                         locationsOnPolarPlane);\n\n            this->rects = locationsOnPolarPlane;\n        }\n    }\n\n    void trackUpdateAfter(const cv::Mat &x_update) {\n        cv::Mat y_update = tracker->feature->reshapeYs(this->rects);\n        tracker->olarank->process(x_update, y_update, 0,\n                                  tracker->framesTracked);\n\n        if (tracker->display == 1) {\n            cv::Scalar color(255, 0, 0);\n            cv::Mat plotImg = currentImage.clone();\n            cv::rectangle(plotImg, tracker->lastLocation, color, 2);\n\n            cv::imshow(\"Tracking window\", plotImg);\n            cv::waitKey(1);\n            tracker->objectnessCanvas = plotImg;\n        }\n\n        tracker->framesTracked++;\n    }\n\n    ~DeepStruck() { delete tracker; }\n\n    void createTracker(std::string kernel, std::string feature, int filter) {\n\n        bool pretraining = false;\n        bool useEdgeDensity = false;\n        bool useStraddling = false;\n        bool scalePrior = false;\n\n        std::string note = \"Struck tracker\";\n\n        bool useFilter = false;\n\n        this->tracker =\n            new Struck(pretraining, useFilter, useEdgeDensity, useStraddling,\n                       scalePrior, kernel, feature, note);\n    }\n\n    void setDisplay(int display) {\n        CHECK_NOTNULL(tracker);\n        this->tracker->display = display;\n    }\n\n    void killDisplay() { cv::destroyAllWindows(); }\n};\n\ncv::Mat cloneImage(const cv::Mat &image) {\n    cv::Mat out;\n    image.convertTo(out, CV_64F);\n    return out;\n}\n\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE(DeepAntrack)\n\n{\n    boost::python::def(\"cloneImage\", &cloneImage);\n\n    class_<DeepStruck>(\"DeepStruck\")\n        .def(\"initializeBefore\", &DeepStruck::initializeBefore)\n        .def(\"getImages\", &DeepStruck::getImages)\n        .def(\"initializeAfter\", &DeepStruck::initializeAfter)\n        .def(\"trackDetectBefore\", &DeepStruck::trackDetectBefore)\n        .def(\"trackDetectAfter\", &DeepStruck::trackDetectAfter)\n        .def(\"trackUpdateBefore\", &DeepStruck::trackUpdateBefore)\n        .def(\"trackUpdateAfter\", &DeepStruck::trackUpdateAfter)\n        .def(\"createTracker\", &DeepStruck::createTracker)\n        .def(\"setDisplay\", &DeepStruck::setDisplay)\n        .def(\"killDisplay\", &DeepStruck::killDisplay);\n}\n// find how to write functions which return some values in c++/python boost\n// framework\n", "meta": {"hexsha": "3351ded6a27cd827c119f97fb43c7c779c4d55d8", "size": 6935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python_wrappers/tracker_python.cpp", "max_stars_repo_name": "ibogun/DeepAntrack", "max_stars_repo_head_hexsha": "0b13d363a30c8ad63c0e2c8cbc16aebff90de69a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-13T18:20:17.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-13T18:20:17.000Z", "max_issues_repo_path": "src/python_wrappers/tracker_python.cpp", "max_issues_repo_name": "ibogun/DeepAntrack", "max_issues_repo_head_hexsha": "0b13d363a30c8ad63c0e2c8cbc16aebff90de69a", "max_issues_repo_licenses": ["MIT"], "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_wrappers/tracker_python.cpp", "max_forks_repo_name": "ibogun/DeepAntrack", "max_forks_repo_head_hexsha": "0b13d363a30c8ad63c0e2c8cbc16aebff90de69a", "max_forks_repo_licenses": ["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": 80, "alphanum_fraction": 0.5914924297, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.18352966120205083}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\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\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// VRMC solver based on the Peraud-Hadjiconstantinou method\n/// [APL 101, 153114 (2012)].\n/// Internally the solver runs multiple partial simulations.\n/// This allows us to provide the stochastic uncertainty\n/// on the reported output variables.\n\n#include <string>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <Eigen/Dense>\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/mpi.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-variable\"\n#include <pcg_random.hpp>\n#pragma GCC diagnostic pop\n#include <cmakevars.hpp>\n#include <constants.hpp>\n#include <utilities.hpp>\n#include <io_utils.hpp>\n#include <structures.hpp>\n#include <bulk_hdf5.hpp>\n#include <sampling.hpp>\n#include <bulk_properties.hpp>\n#include <deviational_particle.hpp>\n#include <isotopic_scattering.hpp>\n#include <analytic1d.hpp>\n\n/// Working directory of the user\nboost::filesystem::path launch_path;\n/// Target directory for writing output\nstd::string target_directory = \"AUTO\";\n\n/// Probability density function for a Gamma distribution.\n///\n/// @param[in] k - shape parameter\n/// @param[in] theta - scale parameter\n/// @param[in] x - point at which to evaluate the function\n/// @return the value of the pdf\ndouble gamma_pdf(double k, double theta, double x) {\n    return boost::math::gamma_p_derivative(k, x / theta) / theta;\n}\n\n/// Helper function that determines in which position bin of the\n/// a particle is situated.\n///\n/// @param[in] xgrid - sorted grid of x values defining the bins\n/// @para[in] xtarget - position of the particle\n/// @return the index of the bin where the particle is\ninline int get_bin_index(const Eigen::Ref<const Eigen::VectorXd>& xgrid,\n                         double xtarget) {\n    auto first = xgrid.data();\n    auto last = xgrid.data() + xgrid.size();\n\n    return static_cast<int>(std::lower_bound(first, last, xtarget) - first) - 1;\n}\n\n/// Compute the deviational power per unit area at an isothermal\n/// surface.\n///\n/// @param[in] poscar - a description of the unit cell\n/// @param[in] grid - phonon spectrum on a regular grid\n/// @param[in] Twall - the temperature of the wall in K\n/// @param[in] Tref - the simulation temperature in K\n/// @param[in] normal - a normal vector pointing out\n/// of the wall\n/// @return  the deviational power per unit area in units of\n/// kB / ps / nm ** 2\ninline double calc_dotEeff_wall(\n    const alma::Crystal_structure& poscar,\n    const alma::Gamma_grid& grid,\n    double Twall,\n    double Tref,\n    const Eigen::Ref<const Eigen::Vector3d>& normal) {\n    if (normal.norm() == 0.) {\n        throw alma::value_error(\"invalid normal vector\");\n    }\n    Eigen::Vector3d u(normal.array() / normal.norm());\n    double nruter = 0.;\n    double nqpoints = grid.nqpoints;\n    double nmodes = grid.get_spectrum_at_q(0).omega.size();\n\n    for (std::size_t iq = 0; iq < nqpoints; ++iq) {\n        auto& spectrum = grid.get_spectrum_at_q(iq);\n\n        for (std::size_t im = 0; im < nmodes; ++im) {\n            double vn = u.dot(spectrum.vg.col(im).matrix());\n\n            if (vn >= 0.) {\n                nruter +=\n                    alma::bose_einstein_kernel(spectrum.omega(im), Tref) * vn;\n            }\n        }\n    }\n    nruter *= std::abs((Twall - Tref) / poscar.V / nqpoints);\n    return nruter;\n}\n\n/// Class that helps run simulations of general 1D structures sandwiched\n/// between two thermal reservoirs, in the steady-state regime.\nclass Steady_1d_simulator {\nprivate:\n    /// Random number generator.\n    pcg64 rng;\n    /// Description of H5 repository root directory\n    std::string h5_repository = \".\";\n    /// Vector of base names for the materials in the structure.\n    std::vector<std::string> material_base;\n    /// Vector of \"compound\" names for the materials in the structure.\n    std::vector<std::string> material_compound;\n    /// Vector of superlattice flags for the materials in the structure.\n    std::vector<bool> material_superlattice;\n    /// Vector of superlattice UIDs for the materials in the structure.\n    std::vector<std::string> material_superlattice_UID;\n    /// Vector of superlattice distorder scattering rates for the materials in\n    /// the structure.\n    std::vector<Eigen::ArrayXXd> material_w0_SLdisorder;\n    /// Vector of superlattice barrier scattering rates for the materials in the\n    /// structure.\n    std::vector<Eigen::ArrayXXd> material_w0_SLbarriers;\n    /// Vector containing the q-point grid density along A axis for all\n    /// materials in the structure.\n    std::vector<int> material_grid_densityA;\n    /// Vector containing the q-point grid density along B axis for all\n    /// materials in the structure.\n    std::vector<int> material_grid_densityB;\n    /// Vector containing the q-point grid density along C axis for all\n    /// materials in the structure.\n    std::vector<int> material_grid_densityC;\n    /// Vector of structures holding configurational information about each\n    /// material in the structure.\n    std::vector<std::unique_ptr<alma::Crystal_structure>> material_structure;\n    /// Vector of structures holding information about the phonon spectrum of\n    /// each material in the structure.\n    std::vector<std::unique_ptr<alma::Gamma_grid>> material_grid;\n    /// Vector of structures containing information about allowed three-phonon\n    /// processes in each structure.\n    std::vector<std::unique_ptr<std::vector<alma::Threeph_process>>>\n        material_processes;\n    /// 1D thermal transport axis\n    Eigen::Vector3d u;\n    /// Material making up each layer in the structure.\n    std::vector<int> layer_material;\n    /// Thickness of each layer in the structure.\n    std::vector<double> layer_thickness;\n    /// Value of the coordinate marking the beginning of each layer in the\n    /// structure.\n    std::vector<double> layer_top;\n    /// Value of the coordinate marking the end of each layer in the structure.\n    std::vector<double> layer_bottom;\n    /// Number of particles to be used for the whole simulation.\n    int nparticles;\n    /// Number of particles considered in a partial run.\n    int nparticles_partial;\n    /// Temperature differential between the reservoirs.\n    double deltaT;\n    /// Ambient temperature.\n    /// Reservoir temperatures will be set to Tambient +/- deltaT/2.\n    double Tambient;\n    /// Temperature at the top of the structure.\n    double Ttop;\n    /// Temperature at the bottom of the structure.\n    double Tbottom;\n    /// Description of the layer structure\n    std::stringstream structureinfo;\n    /// Number of ticks in the real-space grid.\n    ///\n    /// Note that the number of bins equals this number minus 1.\n    int nspace;\n    /// Spatial grid containing the edged of the bins where the\n    /// steady-state distribution should be evaluated.\n    Eigen::VectorXd spacegrid;\n    /// Auxiliary grid with the midpoint of each bin.\n    Eigen::VectorXd bgrid;\n    /// Width of each bin.\n    double deltaspace;\n    /// Map from bins to layers.\n    std::vector<int> bin_layer;\n    /// Number of bins in each layer.\n    Eigen::ArrayXi layer_nbins;\n    /// Diffuse mismatch samplers for each interface.\n    std::vector<alma::Diffuse_mismatch_distribution> interface_sampler;\n    /// MPI communicator used to synchronize with other processes.\n    boost::mpi::communicator comm;\n    /// Heat flux [J/ps/nm^2]\n    double jq;\n    /// Coordinates [nm] of the surfaces where spectral flux should be resolved.\n    std::vector<double> jq_surfaces;\n    /// Angular frequencies [rad/ps] for spectral flux evaluation.\n    Eigen::ArrayXd jq_omega;\n    /// Spectral heat flux at selected surface [J/nm^2/rad].\n    Eigen::ArrayXXd djq;\n    // Deviational energy density in space.\n    Eigen::VectorXd gzeta;\n    // Pseudotemperature in space [= sum(gzeta/tau)/sum(C/tau)]\n    Eigen::VectorXd Tpseudo;\n    // \"Macroscopic\" temperature in space [= sum(gzeta)/sum(C)]\n    Eigen::VectorXd Tmacro;\n\n    // VARIABLES USED WHILE RUNNING SIMULATION\n\n    std::vector<double> layer_cv;\n    std::vector<Eigen::ArrayXXd> layer_w0;\n    std::vector<double> layer_cv_over_tau;\n    std::vector<alma::BE_derivative_distribution> layer_sampler;\n\npublic:\n    /// Create an object based on the description contained in an XML file.\n    ///\n    /// @param[in] filename - path to the input XML file\n    /// @param[inout] comm_ - MPI communicator used to synchronize with other\n    /// processes\n    Steady_1d_simulator(const std::string& filename,\n                        double T_ambient,\n                        boost::mpi::communicator comm_)\n        : Tambient(T_ambient), comm(comm_), jq{0.},\n          rng{pcg_extras::seed_seq_from<std::random_device>()} {\n        auto my_id = comm.rank();\n\n        // Parse the inputs and create the structures, only in the master\n        // process.\n        std::size_t njq_omega = 100;\n        if (my_id == 0) {\n            std::cout << \"PARSING \" << filename << \" ...\" << std::endl;\n            // Create empty property tree object\n            boost::property_tree::ptree tree;\n            // Parse XML input file into the tree\n            boost::property_tree::read_xml(filename, tree);\n\n            // Traverse the tree and create the structure\n            // 1. Parse materials\n\n            std::map<std::string, int> material_catalog;\n\n            for (const auto& v : tree.get_child(\"materials\")) {\n                if (v.first == \"H5repository\") {\n                    h5_repository =\n                        alma::parseXMLfield<std::string>(v, \"root_directory\");\n                }\n\n                if (v.first == \"material\") {\n                    std::string label{\n                        alma::parseXMLfield<std::string>(v, \"label\")};\n                    std::string base{\n                        alma::parseXMLfield<std::string>(v, \"directory\")};\n                    std::string compound{\n                        alma::parseXMLfield<std::string>(v, \"compound\")};\n                    std::string SL_UID(\"NULL\");\n\n                    if (alma::probeXMLfield<std::string>(v,\n                                                         \"superlattice_UID\")) {\n                        SL_UID = alma::parseXMLfield<std::string>(\n                            v, \"superlattice_UID\");\n                    }\n\n                    int gridDensityA{alma::parseXMLfield<int>(v, \"gridA\")};\n                    int gridDensityB{alma::parseXMLfield<int>(v, \"gridB\")};\n                    int gridDensityC{alma::parseXMLfield<int>(v, \"gridC\")};\n\n                    if (material_catalog.count(label) == 0) {\n                        // material is not yet in the list; add it\n                        std::size_t next_index = material_catalog.size();\n                        material_catalog[label] = next_index;\n                        material_base.emplace_back(base);\n                        material_compound.emplace_back(compound);\n                        material_superlattice_UID.emplace_back(SL_UID);\n                        material_grid_densityA.emplace_back(gridDensityA);\n                        material_grid_densityB.emplace_back(gridDensityB);\n                        material_grid_densityC.emplace_back(gridDensityC);\n                    }\n                    else {\n                        std::cerr << \"WARNING: found duplicate entry for \"\n                                     \"material label \"\n                                  << label << std::endl;\n                    }\n                }\n            }\n            auto nmaterials = material_base.size();\n            std::cout << \" Structure contains \" << nmaterials << \" materials.\"\n                      << std::endl;\n\n            // 2. Parse layer structure\n\n            std::map<int, std::string> layer_catalog_material;\n            std::map<int, double> layer_catalog_thickness;\n\n            for (const auto& v : tree.get_child(\"layers\")) {\n                if (v.first == \"layer\") {\n                    std::string label{\n                        alma::parseXMLfield<std::string>(v, \"label\")};\n                    int index{alma::parseXMLfield<int>(v, \"index\")};\n                    std::string material{\n                        alma::parseXMLfield<std::string>(v, \"material\")};\n                    double thickness{\n                        alma::parseXMLfield<double>(v, \"thickness\")};\n\n                    if (layer_catalog_material.count(index) == 0) {\n                        // this layer index has not been created yet\n                        layer_catalog_material[index] = material;\n                        layer_catalog_thickness[index] = thickness;\n                    }\n                    else {\n                        std::cerr << \"ERROR: duplicate layer index found in \"\n                                     \"input file.\"\n                                  << std::endl;\n                        comm.abort(1);\n                    }\n                }\n            }\n            // All layer information is now known, create simulation\n            // structure: determine and verify total number of layers\n\n            auto nlayers = static_cast<int>(layer_catalog_material.size());\n\n            if (my_id == 0) {\n                std::cout << \" Structure contains \" << nlayers\n                          << \" layers:\" << std::endl;\n            }\n\n            for (auto& it : layer_catalog_material) {\n                if (it.first > nlayers) {\n                    std::cerr << \"ERROR: layer index in input file should not \"\n                                 \"exceed total number of layers.\"\n                              << std::endl;\n                    comm.abort(1);\n                }\n            }\n\n            for (int index = 1; index <= nlayers; ++index) {\n                std::cout << \"  \" << layer_catalog_material[index] << \" (\"\n                          << layer_catalog_thickness[index] << \"nm)\"\n                          << std::endl;\n                structureinfo\n                    << \"LAYER \" << index << \" \" << layer_catalog_material[index]\n                    << \" (\"\n                    << alma::engineer_format(\n                           1e-9 * layer_catalog_thickness[index], true)\n                    << \"m)\" << std::endl;\n            }\n\n            layer_material.resize(nlayers);\n            layer_thickness.resize(nlayers);\n\n            for (auto& it : layer_catalog_material) {\n                layer_material.at(it.first - 1) = material_catalog[it.second];\n                layer_thickness.at(it.first - 1) =\n                    layer_catalog_thickness[it.first];\n            }\n\n            // 3. Parse simulation settings.\n\n            for (const auto& v : tree.get_child(\"simulation\")) {\n                if (v.first == \"core\") {\n                    deltaT = alma::parseXMLfield<double>(v, \"deltaT\");\n\n                    Ttop = Tambient + 0.5 * deltaT;\n                    Tbottom = Tambient - 0.5 * deltaT;\n\n                    nparticles = static_cast<int>(\n                        alma::parseXMLfield<double>(v, \"particles\"));\n                    nspace = static_cast<int>(\n                                 alma::parseXMLfield<double>(v, \"bins\")) +\n                             1;\n                }\n\n                if (v.first == \"transportAxis\") {\n                    u(0) = alma::parseXMLfield<double>(v, \"x\");\n                    u(1) = alma::parseXMLfield<double>(v, \"y\");\n                    u(2) = alma::parseXMLfield<double>(v, \"z\");\n                    u.normalize();\n                }\n\n                if (v.first == \"target\") {\n                    target_directory =\n                        alma::parseXMLfield<std::string>(v, \"directory\");\n                }\n            }\n\n            // 4. Parse settings for resolving spectral flux, if applicable\n\n            bool spectralflux = true;\n            try {\n                tree.get_child(\"spectralflux\");\n            }\n            catch (boost::property_tree::ptree_bad_path& bad_path_error) {\n                spectralflux = false;\n            }\n\n            if (spectralflux) {\n                for (const auto& v : tree.get_child(\"spectralflux\")) {\n                    if (v.first == \"resolution\") {\n                        njq_omega = alma::parseXMLfield<std::size_t>(\n                            v, \"frequencybins\");\n                    }\n\n                    if (v.first == \"location\") {\n                        this->jq_surfaces.emplace_back(\n                            alma::parseXMLfield<double>(v, \"position\"));\n                    }\n\n                    if (v.first == \"locationrange\") {\n                        double start = alma::parseXMLfield<double>(v, \"start\");\n                        double stop = alma::parseXMLfield<double>(v, \"stop\");\n                        double step = alma::parseXMLfield<double>(v, \"step\");\n\n                        for (double pos = start; pos <= stop; pos += step) {\n                            this->jq_surfaces.emplace_back(pos);\n                        }\n                    }\n                }\n            }\n\n            // Calculate coordinates of layer boundaries\n            layer_top.resize(nlayers);\n            layer_bottom.resize(nlayers);\n            layer_top.at(0) = 0.0;\n\n            for (int nlayer = 0; nlayer < nlayers; ++nlayer) {\n                layer_bottom.at(nlayer) =\n                    layer_top.at(nlayer) + layer_thickness.at(nlayer);\n\n                if (nlayer < nlayers - 1) {\n                    layer_top.at(nlayer + 1) = layer_bottom.at(nlayer);\n                }\n            }\n        }\n\n        // Broadcast all relevant information to all processes with id != 0.\n        boost::mpi::broadcast(comm, material_base, 0);\n        boost::mpi::broadcast(comm, h5_repository, 0);\n        boost::mpi::broadcast(comm, material_compound, 0);\n        boost::mpi::broadcast(comm, material_superlattice_UID, 0);\n        boost::mpi::broadcast(comm, material_grid_densityA, 0);\n        boost::mpi::broadcast(comm, material_grid_densityB, 0);\n        boost::mpi::broadcast(comm, material_grid_densityC, 0);\n        boost::mpi::broadcast(comm, layer_material, 0);\n        boost::mpi::broadcast(comm, layer_thickness, 0);\n        boost::mpi::broadcast(comm, deltaT, 0);\n        boost::mpi::broadcast(comm, Tambient, 0);\n        boost::mpi::broadcast(comm, Ttop, 0);\n        boost::mpi::broadcast(comm, Tbottom, 0);\n        boost::mpi::broadcast(comm, nparticles, 0);\n        boost::mpi::broadcast(comm, nspace, 0);\n        boost::mpi::broadcast(comm, u.data(), u.size(), 0);\n        boost::mpi::broadcast(comm, layer_bottom, 0);\n        boost::mpi::broadcast(comm, layer_top, 0);\n        boost::mpi::broadcast(comm, njq_omega, 0);\n        boost::mpi::broadcast(comm, jq_surfaces, 0);\n\n        // Create the spatial grids used for binning.\n        spacegrid =\n            Eigen::VectorXd::LinSpaced(nspace, 0.0, layer_bottom.back());\n        deltaspace = spacegrid(1) - spacegrid(0);\n        bgrid = spacegrid.head(nspace - 1).array() + .5 * deltaspace;\n        // Assign each bin to a layer. Note that only the midpoint is\n        // taken into account, regardless of whether a bin overlaps with\n        // several layers.\n        bin_layer.resize(nspace - 1);\n        auto nlayers = static_cast<int>(layer_material.size());\n        layer_nbins.resize(nlayers);\n        int firstbin = 0;\n\n        for (auto i = 0; i < nlayers; ++i) {\n            int lastbin = get_bin_index(bgrid, layer_bottom[i]) + 1;\n\n            if (lastbin == firstbin) {\n                if (my_id == 0) {\n                    std::cerr << \"Error: one of the bins is empty\" << std::endl;\n                }\n                exit(1);\n            }\n\n            for (auto j = firstbin; j < lastbin; ++j) {\n                bin_layer[j] = i;\n            }\n\n            layer_nbins(i) = lastbin - firstbin;\n            firstbin = lastbin;\n        }\n\n        // Load and save data about phonons for the materials involved in the\n        // calculation.\n\n        // Initialise file system and verify that directories actually exist\n\n        launch_path = boost::filesystem::current_path();\n        auto basedir = boost::filesystem::path(h5_repository);\n\n        if (!(boost::filesystem::exists(boost::filesystem::path(basedir)))) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"Repository directory \" << basedir\n                      << \" does not exist.\" << std::endl;\n            exit(1);\n        }\n\n        int nmaterials = material_base.size();\n\n        for (int nmat = 0; nmat < nmaterials; ++nmat) {\n            if (my_id == 0) {\n                std::cout << \"Importing phonon data for \"\n                          << material_compound.at(nmat) << std::endl;\n            }\n\n            if (!(boost::filesystem::exists(boost::filesystem::path(\n                    basedir / material_base.at(nmat))))) {\n                if (my_id == 0) {\n                    std::cerr << \"ERROR:\" << std::endl;\n                    std::cerr << \"Material directory \" << material_base.at(nmat)\n                              << \" does not exist within the HDF5 repository.\"\n                              << std::endl;\n                }\n                comm.abort(1);\n            }\n\n            auto path =\n                basedir / boost::filesystem::path(material_base.at(nmat)) /\n                boost::filesystem::path((boost::format(\"%1%_%2%_%3%_%4%.h5\") %\n                                         material_compound.at(nmat) %\n                                         material_grid_densityA.at(nmat) %\n                                         material_grid_densityB.at(nmat) %\n                                         material_grid_densityC.at(nmat))\n                                            .str());\n\n            if (!(boost::filesystem::exists(path))) {\n                if (my_id == 0) {\n                    std::cerr << \"ERROR:\" << std::endl;\n                    std::cerr << \"HDF5 file \" << path << \" does not exist.\"\n                              << std::endl;\n                }\n                comm.abort(1);\n            }\n\n            auto data = alma::load_bulk_hdf5(path.string().c_str(), comm);\n            material_structure.emplace_back(std::move(std::get<1>(data)));\n            material_grid.emplace_back(std::move(std::get<3>(data)));\n            material_processes.emplace_back(std::move(std::get<4>(data)));\n\n            // Check if we are dealing with a superlattice.\n            // If so, load the applicable scattering data.\n\n            bool superlattice = false;\n            std::string superlattice_UID = material_superlattice_UID.at(nmat);\n\n            auto subgroups =\n                alma::list_scattering_subgroups(path.string().c_str(), comm);\n\n            int superlattice_count = 0;\n\n            for (std::size_t ngroup = 0; ngroup < subgroups.size(); ngroup++) {\n                if (subgroups.at(ngroup).find(\"superlattice\") !=\n                    std::string::npos) {\n                    superlattice_count++;\n                }\n            }\n\n            superlattice_count /= 2;\n\n            if (superlattice_count > 0) {\n                superlattice = true;\n            }\n\n            Eigen::ArrayXXd w0_SLdisorder;\n            Eigen::ArrayXXd w0_SLbarriers;\n\n            if (superlattice) {\n                // complain if there are multiple possibilities\n\n                if ((superlattice_count > 1) && (superlattice_UID == \"NULL\")) {\n                    if (my_id == 0) {\n                        std::cerr << \"ERROR:\" << std::endl;\n                        std::cerr << \"H5 file contains scattering information \"\n                                     \"for multiple superlattices.\"\n                                  << std::endl;\n                        std::cerr << \"Must provide the superlattice UID via \"\n                                     \"the <superlattice> XML tag.\"\n                                  << std::endl;\n                    }\n                    comm.abort(1);\n                }\n\n                // if the user provided a UID, verify that corresponding data\n                // exists\n\n                if (superlattice_UID != \"NULL\") {\n                    int UIDcount = 0;\n\n                    for (std::size_t ngroup = 0; ngroup < subgroups.size();\n                         ngroup++) {\n                        if (subgroups.at(ngroup).find(superlattice_UID) !=\n                            std::string::npos) {\n                            UIDcount++;\n                        }\n                    }\n\n                    if (UIDcount != 2) {\n                        if (my_id == 0) {\n                            std::cerr << \"ERROR:\" << std::endl;\n                            std::cerr << \"H5 file does not contain any \"\n                                         \"superlattice data with provided UID \"\n                                      << superlattice_UID << \".\" << std::endl;\n                        }\n                        comm.abort(1);\n                    }\n                }\n\n                // load the scattering rates from the H5 file\n\n                bool UIDmatch = true;\n\n                for (std::size_t ngroup = 0; ngroup < subgroups.size();\n                     ngroup++) {\n                    bool contains_SLdisorder =\n                        (subgroups.at(ngroup).find(\"superlattice\") !=\n                         std::string::npos) &&\n                        (subgroups.at(ngroup).find(\"disorder\") !=\n                         std::string::npos);\n                    bool contains_SLbarriers =\n                        (subgroups.at(ngroup).find(\"superlattice\") !=\n                         std::string::npos) &&\n                        (subgroups.at(ngroup).find(\"barriers\") !=\n                         std::string::npos);\n\n                    if (superlattice_count > 1) {\n                        UIDmatch = (subgroups.at(ngroup).find(\n                                        superlattice_UID) != std::string::npos);\n                    }\n\n                    if (contains_SLdisorder && UIDmatch) {\n                        auto mysubgroup = alma::load_scattering_subgroup(\n                            path.string().c_str(), subgroups.at(ngroup), comm);\n                        w0_SLdisorder = mysubgroup.w0;\n                    }\n\n                    if (contains_SLbarriers && UIDmatch) {\n                        auto mysubgroup = alma::load_scattering_subgroup(\n                            path.string().c_str(), subgroups.at(ngroup), comm);\n                        w0_SLbarriers = mysubgroup.w0;\n                    }\n                }\n            }\n\n            material_superlattice.push_back(superlattice);\n            material_w0_SLdisorder.emplace_back(w0_SLdisorder);\n            material_w0_SLbarriers.emplace_back(w0_SLbarriers);\n        }\n\n        // Now the spectrum is known. Compute the frequencies at which\n        // the heat flux density will be evaluated.\n\n        double maxfreq = 0.;\n        for (auto im = 0; im < nmaterials; ++im) {\n            const auto& grid = material_grid[im];\n            for (std::size_t iq = 0; iq < grid->nqpoints; ++iq) {\n                const auto& spectrum = grid->get_spectrum_at_q(iq);\n                maxfreq = std::max(maxfreq, spectrum.omega.maxCoeff());\n            }\n        }\n\n        this->jq_omega.resize(njq_omega);\n\n        for (std::size_t iw = 0; iw < njq_omega; ++iw) {\n            this->jq_omega(iw) = iw * maxfreq / static_cast<double>(njq_omega);\n        }\n\n        this->djq.resize(njq_omega, this->jq_surfaces.size());\n        this->djq.fill(0.);\n\n\n        // Process the interfaces.\n        int ninterfaces = layer_material.size() - 1;\n\n        for (int nint = 0; nint < ninterfaces; ++nint) {\n            if (my_id == 0)\n                std::cout << \"Creating diffuse mismatch distribution \"\n                          << nint + 1 << \" of \" << ninterfaces << std::endl;\n            int id1 = layer_material[nint];\n            int id2 = layer_material[nint + 1];\n\n            interface_sampler.emplace_back(\n                alma::Diffuse_mismatch_distribution(*material_grid[id1],\n                                                    *material_structure[id1],\n                                                    *material_grid[id2],\n                                                    *material_structure[id2],\n                                                    u,\n                                                    0.1,\n                                                    rng));\n        }\n\n    } // END CONSTRUCTOR\n\n    /// Return the number of real-space bins used in this calculation.\n    ///\n    /// @return the number of ticks in the real-space grid minus one\n    int get_nbins() const {\n        return this->nspace - 1;\n    }\n    /// Return the temperature at the top heat reservoir\n    ///\n    /// @return the temperature at the top of the structure [K]\n    double get_Ttop() const {\n        return Ttop;\n    }\n    /// Return the temperature at the bottom heat reservoir\n    ///\n    /// @return the temperature at the bottom of the structure [K]\n    double get_Tbottom() const {\n        return Tbottom;\n    }\n    /// Return a description of the layer structure\n    ///\n    /// @return description\n    std::string get_layerdescription() const {\n        return structureinfo.str();\n    }\n    /// Return the total thickness of the structure.\n    ///\n    /// @return the sum of all layer widths [nm]\n    double get_thickness() const {\n        return layer_bottom.back();\n    }\n    /// Return the average heat flux per unit area computed in the last\n    /// simulation.\n    double get_jq() const {\n        return this->jq;\n    }\n    /// Return the number of surfaces at which heat flux is computed.\n    ///\n    /// @return the number of surfaces defined in the input XML file\n    std::size_t get_nsurfaces() const {\n        return this->jq_surfaces.size();\n    }\n    /// Return the location where spectral flux is computed.\n    ///\n    /// @param[in] isurf - a surface index\n    /// @return location of the surface\n    double get_surfacelocation(std::size_t nsurf) const {\n        return this->jq_surfaces.at(nsurf);\n    }\n\n    /// Return the computed heat flux density profile at a surface.\n    ///\n    /// @param[in] isurf - a surface index\n    /// @return an array with two columns, one for angular frequencies\n    /// [rad/ps] and one for flux densities [J/m^2/rad]\n    Eigen::ArrayXXd get_flux_at_surface(std::size_t isurf) const {\n        if (isurf >= this->jq_surfaces.size()) {\n            throw alma::value_error(\"invalid surface index\");\n        }\n        Eigen::ArrayXXd nruter(this->jq_omega.size(), 2);\n        nruter.col(0) = this->jq_omega;\n        nruter.col(1) = 1e30 * this->djq.col(isurf);\n        return nruter;\n    }\n\n    /// Return the number of particles used for the whole simulation.\n    ///\n    /// @return number of particles\n    int get_nparticles() const {\n        return this->nparticles;\n    }\n\n    /// Helper function for processing trajectories\n\n    void processSegment(double zetastart,\n                        double zetastop,\n                        double duration,\n                        double w0,\n                        double sign,\n                        double mu,\n                        double sigma) {\n        auto nsurfaces = this->jq_surfaces.size();\n        int startbin = get_bin_index(spacegrid, zetastart);\n        startbin = std::max(0, std::min(startbin, nspace - 2));\n        int stopbin = get_bin_index(spacegrid, zetastop);\n        stopbin = std::max(0, std::min(stopbin, nspace - 2));\n\n        if (startbin == stopbin) {\n            gzeta(startbin) += duration * sign;\n            Tpseudo(startbin) += w0 * duration * sign;\n        }\n        else {\n            int minbin = std::min(startbin, stopbin);\n            int maxbin = std::max(startbin, stopbin);\n            double zetamin = std::min(zetastart, zetastop);\n            double zetamax = std::max(zetastart, zetastop);\n            double deltazeta = zetamax - zetamin;\n\n            // process internal segments\n            for (int nbin = minbin + 1; nbin < maxbin; ++nbin) {\n                gzeta(nbin) += sign * duration * deltaspace / deltazeta;\n                Tpseudo(nbin) += w0 * sign * duration * deltaspace / deltazeta;\n            }\n            // process left edge of segment\n            gzeta(minbin) +=\n                sign * duration * (spacegrid(minbin + 1) - zetamin) / deltazeta;\n            Tpseudo(minbin) += w0 * sign * duration *\n                               (spacegrid(minbin + 1) - zetamin) / deltazeta;\n            // process right edge of segment\n            gzeta(maxbin) +=\n                sign * duration * (zetamax - spacegrid(maxbin)) / deltazeta;\n            Tpseudo(maxbin) += w0 * sign * duration *\n                               (zetamax - spacegrid(maxbin)) / deltazeta;\n        }\n\n        // Obtain the contribution of this segment to the spectral\n        // heat flux at each surface.\n        // This is performed through kernel density estimation with\n        // Gamma distributions,\n        // to avoid loss of norm towards negative frequencies.\n\n        double k = mu * mu / sigma;\n        double theta = sigma / mu;\n\n        for (std::size_t is = 0; is < nsurfaces; ++is) {\n            double zetas = this->jq_surfaces[is];\n            // If the particle has crossed the surface, count\n            // its contribution.\n            if ((zetas - zetastart) * (zetas - zetastop) < 0) {\n                double corrected_sign = (zetastop > zetastart) ? sign : -sign;\n                for (std::size_t iw = 0;\n                     iw < static_cast<std::size_t>(this->jq_omega.size());\n                     ++iw) {\n                    this->djq(iw, is) +=\n                        corrected_sign *\n                        gamma_pdf(k, theta, this->jq_omega(iw));\n                }\n            }\n        }\n    }\n\n\n    /// Perform simulation\n    ///\n    /// @param[in] T0 - equilibrium reference temperature [K]\n\n    Eigen::MatrixXd run(double T0, int npartial, int Npartial) {\n        if (npartial == Npartial - 1) {\n            nparticles_partial =\n                nparticles - (Npartial - 1) * (nparticles / Npartial);\n        }\n        else {\n            nparticles_partial = nparticles / Npartial;\n        }\n\n        auto nprocs = comm.size();\n        auto my_id = comm.rank();\n\n        auto nlayers = static_cast<int>(layer_material.size());\n\n        if (npartial == 0) {\n            // Compute specific heats and scattering rates in each layer at the\n            // reference temperature.\n\n            for (auto i = 0; i < nlayers; ++i) {\n                auto id = layer_material[i];\n                layer_cv.emplace_back(alma::calc_cv(\n                    *material_structure[id], *material_grid[id], T0));\n                Eigen::ArrayXXd w3{alma::calc_w0_threeph(\n                    *material_grid[id], *material_processes[id], T0, comm)};\n\n                Eigen::ArrayXXd w_elastic;\n\n                if (material_superlattice.at(id)) {\n                    w_elastic = material_w0_SLdisorder.at(id).array() +\n                                material_w0_SLbarriers.at(id).array();\n                }\n                else {\n                    auto twoph_proc =\n                        alma::find_allowed_twoph(*material_grid[id], comm);\n                    w_elastic = alma::calc_w0_twoph(*material_structure[id],\n                                                    *material_grid[id],\n                                                    twoph_proc,\n                                                    comm);\n                }\n                layer_w0.emplace_back(w_elastic + w3);\n            }\n\n            // Compute sum(C/tau) in each layer at the reference temperature.\n\n            for (auto i = 0; i < nlayers; ++i) {\n                double C_over_tau = 0.0;\n                auto id = layer_material[i];\n\n                std::size_t Nq = material_grid[id]->nqpoints;\n                std::size_t Nbranches =\n                    material_grid[id]->get_spectrum_at_q(0).omega.size();\n\n                double Cscaling = alma::constants::kB /\n                                  static_cast<double>(Nq) /\n                                  material_structure[id]->V;\n\n                for (std::size_t nq = 0; nq < Nq; nq++) {\n                    auto& spectrum = material_grid[id]->get_spectrum_at_q(nq);\n\n                    for (std::size_t nbranch = 0; nbranch < Nbranches;\n                         nbranch++) {\n                        double myC =\n                            Cscaling * alma::bose_einstein_kernel(\n                                           spectrum.omega(nbranch), T0);\n                        double myw0 = layer_w0.at(i).operator()(nbranch, nq);\n                        C_over_tau += myC * myw0;\n                    }\n                }\n\n                layer_cv_over_tau.emplace_back(C_over_tau);\n            }\n\n            // Create a set of random samplers for intrinsic scattering.\n\n            for (auto i = 0; i < nlayers; ++i) {\n                auto id = layer_material[i];\n                layer_sampler.emplace_back(alma::BE_derivative_distribution(\n                    *material_grid[id], layer_w0[i], T0, rng));\n            }\n        }\n\n        // Distributions for the top and bottom heat reservoirs.\n        alma::Isothermal_wall_distribution dist_top{\n            *material_grid[layer_material.front()], Ttop, T0, u, rng};\n        alma::Isothermal_wall_distribution dist_bottom{\n            *material_grid[layer_material.back()], Tbottom, T0, -u, rng};\n\n        // Deviational power per unit area at the two reservoirs.\n        double dotEeff_top =\n            alma::constants::kB *\n            calc_dotEeff_wall(*material_structure[layer_material.front()],\n                              *material_grid[layer_material.front()],\n                              Ttop,\n                              T0,\n                              u);\n        double dotEeff_bottom =\n            alma::constants::kB *\n            calc_dotEeff_wall(*material_structure[layer_material.back()],\n                              *material_grid[layer_material.back()],\n                              Tbottom,\n                              T0,\n                              -u);\n\n        // Total deviational power per unit area.\n        double dotEeff = dotEeff_top + dotEeff_bottom;\n        // Total deviational power per particle.\n        double dotepsilon = dotEeff / static_cast<double>(nparticles_partial);\n\n        // Probability that a particle is emitted from the top.\n        // (Probability for bottom = 1.0-p_top)\n        double p_top = dotEeff_top / dotEeff;\n\n        auto indices = alma::my_jobs(nparticles_partial, nprocs, my_id);\n        auto nindices = indices[1] - indices[0];\n        unsigned int previous_percentage = 0;\n\n        // Sum of contributions to the heat flux.\n        double myjq = 0.;\n\n        // Initialise energy density and temperature\n        gzeta.resize(nspace - 1);\n        gzeta.setConstant(0.0);\n        Tpseudo.resize(nspace - 1);\n        Tpseudo.setConstant(0.0);\n        Tmacro.resize(nspace - 1);\n        Tmacro.setConstant(0.0);\n\n        // Initialise spectral flux\n        this->djq.fill(0.0);\n\n        // *** MAIN MONTE CARLO LOOP ***\n\n        for (auto nparticle = indices[0]; nparticle < indices[1]; ++nparticle) {\n            // Variables that define a trajectory segment.\n            // zeta signifies the coordinate measured along the 1D transport\n            // axis.\n            double traj_zeta1;\n            double traj_t1;\n            double traj_zeta2;\n            double traj_t2;\n            double traj_w0;\n            double traj_omega;\n            double traj_sigma;\n            double traj_zetaLAUNCH;\n            double traj_zetaFINAL;\n\n            unsigned int current_percentage = static_cast<unsigned int>(\n                100. * (nparticle + 1) / (Npartial * nindices));\n\n            if (npartial > 0) {\n                current_percentage += 100 * npartial / Npartial;\n            }\n\n            if ((my_id == 0) && (current_percentage > previous_percentage)) {\n                unsigned int nchars = static_cast<unsigned int>(\n                    72. * (nparticle + 1) / (Npartial * nindices));\n\n                if (npartial > 0) {\n                    nchars += static_cast<unsigned int>(\n                        std::round(72.0 * static_cast<double>(npartial) /\n                                   static_cast<double>(Npartial)));\n                }\n\n                std::cout << \"[\";\n\n                for (auto i = 0u; i < nchars; ++i) {\n                    std::cout << \"-\";\n                }\n                std::cout << \">\";\n\n                for (auto i = nchars; i < 72; ++i) {\n                    std::cout << \" \";\n                }\n                std::cout << \"] \" << current_percentage << \"%\\r\";\n                std::cout.flush();\n                previous_percentage = current_percentage;\n            }\n\n            // LAUNCH A NEW PARTICLE FROM ONE OF THE HEAT SOURCES.\n\n            traj_t1 = 0.0;\n\n            std::unique_ptr<alma::D_particle> particle;\n            double choice{std::uniform_real_distribution(0., 1.)(rng)};\n            int inside_layer;\n            int at_interface = -1;\n            bool discard = false;\n\n            if (choice < p_top) { // Particle emitted from the top.\n                auto mode = dist_top.sample();\n                particle = std::make_unique<alma::D_particle>(\n                    Eigen::Vector3d(0., 0., layer_top.front()),\n                    mode[1],\n                    mode[0],\n                    alma::get_particle_sign(Ttop - T0),\n                    0.);\n                inside_layer = 0;\n                at_interface = -1;\n                traj_zeta1 = layer_top.front();\n            }\n            else { // Particle emitted from the bottom.\n                auto mode = dist_bottom.sample();\n                particle = std::make_unique<alma::D_particle>(\n                    Eigen::Vector3d(0., 0., layer_bottom.back()),\n                    mode[1],\n                    mode[0],\n                    alma::get_particle_sign(Tbottom - T0),\n                    0.);\n                inside_layer = nlayers - 1;\n                at_interface = -1;\n                traj_zeta1 = layer_bottom.back();\n            }\n\n            traj_zetaLAUNCH = traj_zeta1;\n\n            // TRACK PARTICLE UNTIL IT IS ABSORBED\n            for (;;) {\n                bool scattered_at_top = false;\n                bool scattered_at_bottom = false;\n                bool scattered_at_interface = false;\n                bool scattered_inside = false;\n                char interface_side = 'X';\n\n                int mat_id = layer_material[inside_layer];\n                double dt = alma::random_dt(\n                    layer_w0[inside_layer](particle->alpha, particle->q), rng);\n\n                // Provisionally move the particle\n                auto& spectrum =\n                    material_grid[mat_id]->get_spectrum_at_q(particle->q);\n                Eigen::Vector3d vg = spectrum.vg.col(particle->alpha);\n                double zetastart = traj_zeta1;\n                double deltazeta = u.dot(vg) * dt;\n                double zetaend = zetastart + deltazeta;\n                traj_omega = spectrum.omega[particle->alpha];\n                traj_sigma =\n                    material_grid[layer_material[inside_layer]]->base_sigma(vg);\n                traj_w0 = layer_w0[inside_layer](particle->alpha, particle->q);\n\n                // fix numerical artifacts that can trap a particle\n                if ((zetastart == layer_top.at(inside_layer)) &&\n                    (zetaend == zetastart)) { // trapped at top\n                    zetaend = zetastart + 1e-8;\n                }\n\n                if ((zetastart == layer_bottom.at(inside_layer)) &&\n                    (zetaend == zetastart)) { // trapped at bottom\n                    zetaend = zetastart - 1e-8;\n                }\n\n                // Check if particle would still be within the same\n                // layer. If not, enforce scattering at the encountered\n                // boundary and determine where scattering took place.\n\n                if (zetaend >= layer_bottom.at(inside_layer)) {\n                    if (inside_layer ==\n                        nlayers - 1) { // particle is at the bottom of structure\n                        scattered_at_bottom = true;\n                    }\n                    else { // not at the bottom\n                        scattered_at_interface = true;\n                        at_interface = inside_layer;\n                        // bottom of n-th layer = n-th interface\n                        interface_side = 'A';\n                    }\n                    traj_zeta2 = layer_bottom.at(inside_layer);\n                }\n                else if (zetaend <= layer_top.at(inside_layer)) {\n                    if (inside_layer == 0) {\n                        // particle is at the top of the structure\n                        scattered_at_top = true;\n                    }\n                    else { // not at the top\n                        scattered_at_interface = true;\n                        at_interface = inside_layer - 1;\n                        // top of n-th layer is (n-1)-th interface\n                        interface_side = 'B';\n                    }\n                    traj_zeta2 = layer_top.at(inside_layer);\n                }\n                else { // particle scattered intrinsically inside a layer\n                    scattered_inside = true;\n                    traj_zeta2 = zetaend;\n                }\n\n                if (alma::almost_equal(zetaend, zetastart)) {\n                    traj_t2 = traj_t1 + dt;\n                }\n                else {\n                    traj_t2 = traj_t1 + dt * std::abs((traj_zeta2 - zetastart) /\n                                                      (zetaend - zetastart));\n                }\n\n                // PROCESS THIS SEGMENT\n                processSegment(traj_zeta1,\n                               traj_zeta2,\n                               traj_t2 - traj_t1,\n                               traj_w0,\n                               static_cast<double>(particle->sign),\n                               traj_omega,\n                               traj_sigma);\n\n                // Draw new particle information\n\n                // Scattering took place inside a layer: draw new mode and\n                // accept\n                if (scattered_inside) {\n                    auto mode = layer_sampler.at(inside_layer).sample();\n                    particle->q = mode[1];\n                    particle->alpha = mode[0];\n                }\n                // Scattering took place at the top or the bottom: absorb and\n                // terminate particle.\n                else if (scattered_at_top || scattered_at_bottom) {\n                    traj_zetaFINAL = traj_zeta2;\n                    break;\n                }\n                // scattering took place at an interface\n                else if (scattered_at_interface) {\n                    char newside = interface_sampler.at(at_interface)\n                                       .reemit(interface_side, *particle);\n\n                    if ((interface_side == 'A') && (newside == 'B')) {\n                        // crosses interface left to right\n                        inside_layer++;\n                    }\n\n                    if ((interface_side == 'B') && (newside == 'A')) {\n                        // crosses interface right to left\n                        inside_layer--;\n                    }\n\n                    if (newside == 'X') { // something went wrong\n                        discard = true;\n                        break;\n                    }\n                }\n\n                // INITIALISE NEXT SEGMENT\n                traj_zeta1 = traj_zeta2;\n                traj_t1 = traj_t2;\n\n            } // this particle is terminated\n\n            // Obtain the particle's contribution to the total heat flux.\n            if (!discard) {\n                myjq += static_cast<double>(particle->sign) *\n                        (traj_zetaFINAL - traj_zetaLAUNCH);\n            }\n\n        } // END OF MONTE CARLO LOOP\n\n        // Obtain the total heat flux.\n        myjq *= dotepsilon / (layer_top.front() - layer_bottom.back());\n        this->jq = 0.;\n        boost::mpi::all_reduce(comm, myjq, this->jq, std::plus<double>());\n\n        // And the total spectral flux.\n\n        if (this->jq_surfaces.size() != 0) {\n            Eigen::ArrayXXd mydjq{this->djq * dotepsilon};\n            this->djq.fill(0.);\n            boost::mpi::all_reduce(comm,\n                                   mydjq.data(),\n                                   mydjq.size(),\n                                   this->djq.data(),\n                                   std::plus<double>());\n        }\n\n        if (my_id == 0 && npartial == Npartial - 1) {\n            std::cout << std::endl;\n        }\n\n        // Obtain the output total deviational power profile.\n        Eigen::ArrayXd gzeta_final{nspace - 1};\n        boost::mpi::all_reduce(comm,\n                               gzeta.data(),\n                               gzeta.size(),\n                               gzeta_final.data(),\n                               std::plus<double>());\n        gzeta_final *= (dotepsilon / deltaspace);\n\n        // Determine the deviational pseudotemperature\n        Eigen::VectorXd Tpseudo_final{nspace - 1};\n        boost::mpi::all_reduce(comm,\n                               Tpseudo.data(),\n                               Tpseudo.size(),\n                               Tpseudo_final.data(),\n                               std::plus<double>());\n        Tpseudo_final *= (dotepsilon / deltaspace);\n\n        for (auto i = 0; i < nspace - 1; ++i) {\n            Tpseudo_final(i) /= layer_cv_over_tau[bin_layer[i]];\n        }\n\n        // Determine the deviational \"macroscopic\" temperature\n        Eigen::VectorXd Tmacro_final{nspace - 1};\n\n        for (auto i = 0; i < nspace - 1; ++i) {\n            Tmacro_final(i) = gzeta_final(i) / layer_cv[bin_layer[i]];\n        }\n\n        // Add the reference to get absolute temperatures.\n        for (auto i = 0; i < nspace - 1; ++i) {\n            Tpseudo_final(i) += T0;\n            Tmacro_final(i) += T0;\n        }\n\n        // Return the result.\n        Eigen::MatrixXd result(nspace - 1, 2);\n        result.col(0) = Tpseudo_final;\n        result.col(1) = Tmacro_final;\n\n        return result;\n    } // END run()\n};    // END CLASS\n\nint main(int argc, char** argv) {\n    boost::mpi::environment env;\n    boost::mpi::communicator world;\n    auto my_id = world.rank();\n\n    if (my_id == 0) {\n        std::cout << \"********************************************\"\n                  << std::endl;\n        std::cout << \"This is ALMA/steady_montecarlo1d version \"\n                  << ALMA_VERSION_MAJOR << \".\" << ALMA_VERSION_MINOR\n                  << std::endl;\n        std::cout << \"********************************************\"\n                  << std::endl;\n    }\n\n    // Check that the right number of arguments have been provided.\n    if (argc < 2) {\n        if (my_id == 0) {\n            std::cerr << boost::format(\n                             \"Usage: %1% <inputfile.xml> <OPTIONAL: T0>\") %\n                             argv[0]\n                      << std::endl;\n        }\n        return 1;\n    }\n\n    // Default setting for reference temperature\n    double T_ambient = 300.0;\n\n    // Read user-provided value from command line if applicable\n\n    if (argc > 2) {\n        T_ambient = atof(argv[2]);\n\n        if (T_ambient <= 0.0) {\n            if (my_id == 0) {\n                std::cerr << \"Invalid reference temperature (\" << T_ambient\n                          << \"K) provided.\" << std::endl;\n            }\n            return 1;\n        }\n    }\n\n    // verify that input file exists.\n    if (!boost::filesystem::exists(boost::filesystem::path{argv[1]})) {\n        if (my_id == 0) {\n            std::cout << \"ERROR: input file \" << argv[1] << \" does not exist.\"\n                      << std::endl;\n        }\n        world.abort(1);\n    }\n\n    // Build the simulator object.\n\n    boost::filesystem::path xmlfile{argv[1]};\n    Steady_1d_simulator sim(xmlfile.string(), T_ambient, world);\n    world.barrier();\n\n    if (my_id == 0) {\n        std::cout << \"Initialization finished\" << std::endl;\n    }\n\n    // Resolve output directory and create it when needed\n\n    boost::filesystem::current_path(launch_path);\n    boost::filesystem::path outputbase;\n\n    if (target_directory.compare(\"AUTO\") == 0) {\n        // Strip path information and extension from filename to build output\n        // path.\n        outputbase = boost::filesystem::path(\"output\") /\n                     boost::filesystem::path(\"steady_montecarlo1d\") /\n                     xmlfile.stem();\n    }\n\n    else {\n        outputbase = boost::filesystem::path(target_directory);\n    }\n\n    if (!(boost::filesystem::exists(outputbase))) {\n        boost::filesystem::create_directories(outputbase);\n    }\n\n    if (my_id == 0) {\n        std::cout << \"Files will be written to \" << outputbase.string()\n                  << std::endl;\n    }\n\n    if (my_id == 0) {\n        std::cout << \"RUNNING SIMULATION...\" << std::endl;\n    }\n\n    // Run a series of partial simulations\n\n    int Npartial = 5;\n    Eigen::VectorXd kappaeff_partial(Npartial);\n    Eigen::VectorXd heatflux_partial(Npartial);\n    Eigen::VectorXd Tpseudo;\n    Eigen::VectorXd Tmacro;\n\n    int Nsurfaces = sim.get_nsurfaces();\n    Eigen::MatrixXd spectralflux;\n\n    for (int npartial = 0; npartial < Npartial; npartial++) {\n        Eigen::MatrixXd result = sim.run(T_ambient, npartial, Npartial);\n\n        // Obtain results\n        Eigen::VectorXd Tpseudo_partial = result.col(0);\n        Eigen::VectorXd Tmacro_partial = result.col(1);\n\n        if (npartial == 0) {\n            Tpseudo.resize(Tpseudo_partial.size());\n            Tpseudo.setConstant(0.0);\n            Tmacro.resize(Tmacro_partial.size());\n            Tmacro.setConstant(0.0);\n        }\n\n        for (int nrow = 0; nrow < Tpseudo_partial.size(); nrow++) {\n            Tpseudo(nrow) +=\n                Tpseudo_partial(nrow) / static_cast<double>(Npartial);\n            Tmacro(nrow) +=\n                Tmacro_partial(nrow) / static_cast<double>(Npartial);\n        }\n\n        heatflux_partial(npartial) = std::abs(sim.get_jq() * 1e12 * 1e9 * 1e9);\n        kappaeff_partial(npartial) =\n            std::abs(sim.get_jq() * 1e12 * 1e9 * 1e9 /\n                     ((sim.get_Ttop() - sim.get_Tbottom()) /\n                      (sim.get_thickness() * 1e-9)));\n\n        for (int nsurface = 0; nsurface < Nsurfaces; nsurface++) {\n            Eigen::VectorXd surfaceflux =\n                sim.get_flux_at_surface(nsurface).col(1);\n\n            if (npartial == 0 && nsurface == 0) {\n                spectralflux.resize(surfaceflux.size(), Nsurfaces);\n                spectralflux.fill(0.0);\n            }\n\n            for (int nomega = 0; nomega < surfaceflux.size(); nomega++) {\n                spectralflux(nomega, nsurface) +=\n                    surfaceflux(nomega) / static_cast<double>(Npartial);\n            }\n        }\n    }\n\n    // Determine net heat flux and kappa_eff and their stochastic uncertainty\n\n    double heatflux = heatflux_partial.sum() / static_cast<double>(Npartial);\n    double sigma_heatflux =\n        std::sqrt((heatflux_partial.array() - heatflux).square().sum() /\n                  static_cast<double>(Npartial * (Npartial - 1)));\n\n    double kappa_eff = kappaeff_partial.sum() / static_cast<double>(Npartial);\n    double sigma_kappaeff =\n        std::sqrt((kappaeff_partial.array() - kappa_eff).square().sum() /\n                  static_cast<double>(Npartial * (Npartial - 1)));\n\n    // Obtain some basic information\n    std::size_t Nbins = sim.get_nbins();\n    double Ttop = sim.get_Ttop();\n    double Tbottom = sim.get_Tbottom();\n\n    if (my_id == 0) {\n        std::cout << \"Ttop = \" << Ttop << \" K\" << std::endl;\n        std::cout << \"Tbottom = \" << Tbottom << \" K\" << std::endl;\n        std::cout << \"Tambient = \" << T_ambient << \" K\" << std::endl;\n    }\n\n    // Save all relevant data to output files.\n    if (my_id == 0) {\n        // Write basic information\n        std::string filename{\n            (boost::format(\"basicproperties_%|g|K.txt\") % T_ambient).str()};\n        std::string path{(outputbase / filename).string()};\n\n        std::ofstream infowriter;\n        infowriter.open(path);\n        infowriter << sim.get_layerdescription();\n        infowriter << \"T_TOP \" << Ttop << \" K\" << std::endl;\n        infowriter << \"T_BOTTOM \" << Tbottom << \" K\" << std::endl;\n        infowriter << \"T_REF \" << T_ambient << \" K\" << std::endl;\n        infowriter << \"N_PARTICLES \" << sim.get_nparticles() << std::endl;\n        infowriter << \"HEAT_FLUX \" << alma::engineer_format(heatflux, true)\n                   << \"W/m^2\" << std::endl;\n        infowriter << \"HEAT_FLUX_TOLERANCE \"\n                   << alma::engineer_format(sigma_heatflux, true) << \"W/m^2\"\n                   << std::endl;\n        infowriter << \"EFF_CONDUCTIVITY \" << kappa_eff << \" W/m-K\" << std::endl;\n        infowriter << \"EFF_CONDUCTIVITY_TOLERANCE \" << sigma_kappaeff\n                   << \" W/m-K\" << std::endl;\n        double r_eff = 1e-9 * sim.get_thickness() / kappa_eff;\n        infowriter << \"EFF_RESISTIVITY \" << alma::engineer_format(r_eff, true)\n                   << \"K-m^2/W\" << std::endl;\n        infowriter << \"EFF_CONDUCTANCE \"\n                   << alma::engineer_format(1.0 / r_eff, true) << \"W/K-m^2\"\n                   << std::endl;\n        infowriter.close();\n\n        // Write temperature profile\n        filename = (boost::format(\"temperature_%|g|K.csv\") % T_ambient).str();\n        path = (outputbase / filename).string();\n        int nspace = Nbins + 1;\n        Eigen::ArrayXd bgrid{\n            Eigen::VectorXd::LinSpaced(nspace, 0.0, sim.get_thickness())\n                .head(Nbins)};\n        Eigen::MatrixXd output{Nbins, 2};\n        output.col(0).array() = bgrid.array() + .5 * (bgrid(1) - bgrid(0));\n        output.col(1) = Tmacro;\n        alma::write_to_csv(path, output, ',');\n\n        // Write spectral heat flux\n        auto nsurfaces = sim.get_nsurfaces();\n        for (std::size_t is = 0; is < nsurfaces; ++is) {\n            filename = (boost::format(\"spectralflux_surface_%|d|_%|g|K.csv\") %\n                        (is + 1) % T_ambient)\n                           .str();\n            path = (outputbase / filename).string();\n            std::stringstream fileheader;\n            fileheader << \"PHONON_FREQUENCY,SPECTRALFLUX_AT_POSITION_\";\n            fileheader << sim.get_surfacelocation(is) << std::endl;\n\n            Eigen::MatrixXd dummy = sim.get_flux_at_surface(is);\n            Eigen::MatrixXd output(dummy.rows(), 2);\n            output.col(0) = dummy.col(0);\n            output.col(1) = spectralflux.col(is);\n            alma::write_to_csv(path, output, ',', false, fileheader.str());\n        }\n    }\n\n    if (my_id == 0) {\n        std::cout << \"Average heat flux: \"\n                  << alma::engineer_format(heatflux, true) << \"W/m^2\";\n        std::cout << \" +/- \" << alma::engineer_format(sigma_heatflux, true)\n                  << \"W/m^2\" << std::endl;\n        std::cout << \"Effective conductivity: \" << kappa_eff << \" +/- \"\n                  << sigma_kappaeff << \" W/m-K\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "8481eaf4c2cfd9730a1bf5289aa8eac8f4f55c2b", "size": 60126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/steady_montecarlo1d.cpp", "max_stars_repo_name": "sousaw/BTE-Barna", "max_stars_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T03:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:11:20.000Z", "max_issues_repo_path": "src/steady_montecarlo1d.cpp", "max_issues_repo_name": "sousaw/BTE-Barna", "max_issues_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_issues_repo_licenses": ["MIT", "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/steady_montecarlo1d.cpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "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": 39.6348055372, "max_line_length": 80, "alphanum_fraction": 0.5147856169, "num_tokens": 13231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.18352965896184986}}
{"text": "#pragma once\n#include \"macro.hpp\"\n#include \"myintrin.hpp\"\n#include <boost/serialization/access.hpp>\n#include <boost/serialization/traits.hpp>\n#include <boost/serialization/nvp.hpp>\n#include <functional>\n\n#if !defined(SSE_LEVEL) || SSE_LEVEL <= 2\n\t#define SUMVEC(r)\t{ reg128 tmp = reg_shuffle_ps(r, r, _REG_SHUFFLE(0,1,2,3)); \\\n\t\ttmp = reg_add_ps(r, tmp); \\\n\t\tr = reg_shuffle_ps(tmp,tmp, _REG_SHUFFLE(1,0,0,1)); \\\n\t\tr = reg_add_ps(r, tmp); }\n#else\n\t// r\u306e\u5404\u8981\u7d20\u3092\u8db3\u3057\u5408\u308f\u305b\u308b\n\t#define SUMVEC(r)\t{ r = reg_hadd_ps(r,r); \\\n\t\tr = reg_hadd_ps(r,r); }\n#endif\n#define RCP22BIT(r) { reg128 tmprcp = reg_rcp_ps(r); \\\n\tr = reg_mul_ps(r, reg_mul_ps(tmprcp, tmprcp)); \\\n\ttmprcp = reg_add_ps(tmprcp,tmprcp); \\\n\tr = reg_sub_ps(tmprcp, r); }\n\n#include <cmath>\n#include <cstdint>\nnamespace spn {\n//! \u30cb\u30e5\u30fc\u30c8\u30f3\u6cd5\u3067\u9006\u6570\u3092\u8a08\u7b97\ninline reg128 Rcp22Bit(reg128 r) {\n\treg128 tmp(reg_rcp_ps(r));\n\tr = reg_mul_ps(r, reg_mul_ps(tmp,tmp));\n\ttmp = reg_add_ps(tmp,tmp);\n\treturn reg_sub_ps(tmp, r);\n}\n//! \u30cb\u30e5\u30fc\u30c8\u30f3\u6cd5\u3067\u9006\u6570\u3092\u8a08\u7b97\u3057\u3066\u7a4d\u7b97 = reg_div_ps\u3088\u308a\u306f\u30de\u30b7\u306a\u9664\u7b97\ninline reg128 _mmDivPs(reg128 r0, reg128 r1) {\n\treturn reg_mul_ps(r0, Rcp22Bit(r1));\n}\ninline reg128 _mmAbsPs(reg128 r) {\n\tconst static reg128 signMask = reg_set1_ps(-0.0f);\n\treturn reg_andnot_ps(signMask, r);\n}\ninline reg128 _mmSetPs(float w, float z, float y, float x) {\n\tconst float tmp[4]{w,z,y,x};\n\treturn reg_loadu_ps(tmp);\n}\ninline reg128 _mmSetPs(float s) {\n\treturn reg_load1_ps(&s);\n}\ninline reg128 _mmSetPdw(int32_t w, int32_t z, int32_t y, int32_t x) {\n\tconst int32_t tmp[4] = {w,z,y,x};\n\treturn reg_loadu_ps(reinterpret_cast<const float*>(tmp));\n}\ninline reg128 _mmSetPdw(int32_t d) {\n\treturn _mmSetPdw(d,d,d,d);\n}\n\ninline float Rcp22Bit(float s) {\n\treg128 tmp = reg_load_ss(&s);\n\tRCP22BIT(tmp)\n\tfloat ret;\n\treg_store_ss(&ret, tmp);\n\treturn ret;\n}\ninline float Sqrt(float s) {\n\treg_store_ss(&s, reg_sqrt_ss(reg_load_ss(&s)));\n\treturn s;\n}\ninline float RSqrt(float s) {\n\treturn Rcp22Bit(spn::Sqrt(s));\n}\n\nconstexpr static uint32_t Fullbit = 0xffffffff,\n\t\t\t\t\t\tAbsbit = 0x7fffffff;\nconstexpr float FLOAT_EPSILON = 1e-5f;\t\t//!< 2\u3064\u306e\u5024\u3092\u540c\u4e00\u3068\u307f\u306a\u3059\u8aa4\u5dee\n// \u30d9\u30af\u30c8\u30eb\u30ec\u30b8\u30b9\u30bf\u7528\u306e\u5b9a\u6570\nclass xmm_const {\n\tprotected:\n\t\tstatic void Initialize();\n\t\tstatic void Terminate();\n\n\t#define DefXmm(name) \\\n\t\tprivate: static reg128 _##name; \\\n\t\tpublic: static const reg128& name() { return _##name; }\n\tDefXmm(tmp0001)\n\tDefXmm(tmp0001_i)\n\tDefXmm(tmp0111)\n\tDefXmm(tmp0111_i)\n\tDefXmm(tmp0000)\n\tDefXmm(tmp0000_i)\n\tDefXmm(tmp1000)\n\tDefXmm(tmp1000_i)\n\tDefXmm(tmp1111)\n\tDefXmm(tmp1111_i)\n\tDefXmm(epsilon)\n\tDefXmm(epsilonM)\n\tDefXmm(minus0)\n\tDefXmm(fullbit)\n\tDefXmm(absmask)\n\t#undef DefXmm\n\n\tusing XmmA4 = const reg128 (&)[4];\n\t#define DefXmmA(name, n) \\\n\t\tprivate: static reg128 _##name[n]; \\\n\t\tpublic: static XmmA4 name() { return _##name; }\n\tDefXmmA(mask, 4)\n\tDefXmmA(maskN, 4)\n\tDefXmmA(matI, 4)\n\t#undef DefXmmA\n\n\tusing FA44 = const float (&)[4][4];\n\tprivate: static float _cs_matI[4][4];\n\tpublic: static FA44 cs_matI() { return _cs_matI; }\n};\n}\n\n#include \"structure/niftycounter.hpp\"\nnamespace spn {\nDEF_NIFTY_INITIALIZER(xmm_const)\n//! \u30ec\u30b8\u30b9\u30bf\u8981\u7d20\u304c\u5168\u3066\u30bc\u30ed\u304b\u5224\u5b9a (+0 or -0)\ninline bool _mmIsZero(reg128 r) {\n\tr = reg_andnot_ps(xmm_const::minus0(), r);\n\tr = reg_cmpeq_ps(r, xmm_const::tmp0000());\n\treturn reg_movemask_ps(r) == 0;\n}\n//! \u8aa4\u5dee\u3092\u542b\u3093\u3060\u30bc\u30ed\u5224\u5b9a\ninline bool _mmIsZeroEps(reg128 r) {\n\treg128 xm0 = reg_cmplt_ps(r, xmm_const::epsilon()),\n\t\t\txm1 = reg_cmpnle_ps(r, xmm_const::epsilonM());\n\txm0 = reg_or_ps(xm0, xm1);\n\treturn reg_movemask_ps(xm0) == 0;\n}\n\ntemplate <int A, int B, int C, int D>\ninline reg128 _makeMask() {\n\treg128 zero = reg_setzero_ps();\n\treg128 full = reg_andnot_ps(zero, zero);\n\tconst int tmp2 = (((~D)&1)<<3)|(((~C)&1)<<2)|(((~B)&1)<<1)|((~A)&1);\n\treg128 tmp = reg_move_ss(zero, full);\n\treturn reg_shuffle_ps(tmp, tmp, tmp2);\n}\ntemplate <class T>\nconstexpr T Pi = T(3.1415926535);\t// std::atan(1.0f)*4\nconstexpr float PI = Pi<float>,\n\t\t\t\tSIN0 = 0,\n\t\t\t\tSIN30 = 1.f/2,\n\t\t\t\tSIN45 = 1.f/1.41421356f,\n\t\t\t\tSIN60 = 1.7320508f/2,\n\t\t\t\tSIN90 = 1.f,\n\t\t\t\tCOS0 =  SIN90,\n\t\t\t\tCOS30 = SIN60,\n\t\t\t\tCOS45 = SIN45,\n\t\t\t\tCOS60 = SIN30,\n\t\t\t\tCOS90 = SIN0;\ntemplate <class T>\nT Square(const T& t0) { return t0*t0; }\ntemplate <class T>\nT Cubic(const T& t0) { return t0*t0*t0; }\n// \u4ee3\u308f\u308a\u306bDegree::ToRadian(ang)\u3092\u4f7f\u3046\ninline float DEGtoRAD(float ang) {\n\treturn ang * spn::Rcp22Bit(180.f) * PI;\n}\n// \u4ee3\u308f\u308a\u306bRadian::ToDegree(ang)\u3092\u4f7f\u3046\ninline float RADtoDEG(float ang) {\n\treturn ang * spn::Rcp22Bit(PI) * 180.f;\n}\n\ntemplate <class T>\nstruct TrivialWrapperBase : boost::serialization::traits<T,\n\t\t\t\t\t\t\tboost::serialization::object_serializable,\n\t\t\t\t\t\t\tboost::serialization::track_selectively>\n{};\n//! T\u3092trivial\u306actor\u3067\u30e9\u30c3\u30d7\ntemplate <class T>\nstruct TrivialWrapper : TrivialWrapperBase<TrivialWrapper<T>> {\n\tuint8_t _buff[sizeof(T)];\n\n\tT& operator * () { return (T&)*this; }\n\tconst T& operator * () const { return (const T&)*this; }\n\toperator T& () { return *reinterpret_cast<T*>(_buff); }\n\toperator const T& () const { return *reinterpret_cast<const T*>(_buff); }\n\tT* operator -> () { return reinterpret_cast<T*>(_buff); }\n\tconst T* operator -> () const { return reinterpret_cast<const T*>(_buff); }\n\tTrivialWrapper<T>& operator = (const T& t) {\n\t\t((T&)(*this)) = t;\n\t\treturn *this;\n\t}\n\n\tfriend class boost::serialization::access;\n\ttemplate <class Archive>\n\tvoid serialize(Archive& ar, const unsigned int /*ver*/) {\n\t\tar & boost::serialization::make_nvp(\"value\", static_cast<T&>(*this));\n\t}\n\n\ttemplate <class TA>\n\tbool operator == (const TA& t) const {\n\t\treturn static_cast<const T&>(*this) == static_cast<const T&>(t);\n\t}\n\ttemplate <class TA>\n\tbool operator != (const TA& t) const {\n\t\treturn static_cast<const T&>(*this) != static_cast<const T&>(t);\n\t}\n};\ntemplate <class T, int N>\nstruct TrivialWrapper<T[N]> : TrivialWrapperBase<TrivialWrapper<T[N]>> {\n\tT _buff[N];\n\tusing AR = T (&)[N];\n\tusing AR_C = const T (&)[N];\n\n\tAR operator * () { return _buff; }\n\tAR_C operator * () const { return _buff; }\n\toperator AR () { return _buff; }\n\tT& operator [] (int n) { return _buff[n]; }\n\tconst T& operator [] (int n) const { return _buff[n]; }\n\n\tfriend class boost::serialization::access;\n\ttemplate <class Archive>\n\tvoid serialize(Archive& ar, const unsigned int /*ver*/) {\n\t\tar & boost::serialization::make_nvp(\"value\", _buff);\n\t}\n\n\ttemplate <class TA>\n\tbool operator == (const TA& t) const {\n\t\tfor(int i=0 ; i<N ; i++) {\n\t\t\tif(_buff[i] != t[i])\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\ttemplate <class TA>\n\tbool operator != (const TA& t) const {\n\t\treturn !(this->operator == (t));\n\t}\n};\n}\n\n// \u6b21\u5143\u6bce\u306e\u30ed\u30fc\u30c9/\u30b9\u30c8\u30a2\u95a2\u6570\u3092\u5b9a\u7fa9\n// LOADPS_[ZeroFlag][AlignedFlag][Dim]\n#define LOADPS_A4(ptr)\t\treg_load_ps(ptr)\t\t\t// \u30a2\u30e9\u30a4\u30f3\u30e1\u30f3\u30c8\u6e08\u307f4\u6b21\u5143\u30d9\u30af\u30c8\u30eb\u8aad\u307f\u8fbc\u307f\n#define LOADPS_4(ptr)\t\treg_loadu_ps(ptr)\n#define LOADPS_ZA4(ptr)\t\tLOADPS_A4(ptr)\t\t\t\t// \u7a7a\u304d\u8981\u7d20\u304c\u30bc\u30ed\u521d\u671f\u5316\u4ed8\u304d\n#define LOADPS_Z4(ptr)\t\tLOADPS_4(ptr)\n#define LOADPS_IA4(ptr,n)\tLOADPS_A4(ptr)\t\t\t\t// \u7a7a\u304d\u304b\u3064\u5bfe\u89d2\u8981\u7d20\u306e\u307f\u304c1\u3001\u4ed6\u306f0\n#define LOADPS_I4(ptr,n)\tLOADPS_4(ptr)\n#define STOREPS_A4(ptr, r)\treg_store_ps(ptr, r)\t\t// \u30a2\u30e9\u30a4\u30f3\u30e1\u30f3\u30c8\u6e08\u307f4\u6b21\u5143\u30d9\u30af\u30c8\u30eb\u66f8\u304d\u8fbc\u307f\n#define STOREPS_4(ptr, r)\treg_storeu_ps(ptr, r)\n\n#define LOADPS_A3(ptr)\t\tLOADPS_A4(ptr)\n#define LOADPS_3(ptr)\t\tLOADPS_4(ptr)\n#define LOADPS_BASE3(ptr,src,lfunc)\treg_mul_ps(src, lfunc(ptr))\n#define LOADPS_ZA3(ptr)\t\treg_and_ps(spn::xmm_const::tmp0111_i(), reg_load_ps(ptr))\n#define LOADPS_Z3(ptr)\t\treg_and_ps(spn::xmm_const::tmp0111_i(), reg_loadu_ps(ptr))\n#define LOADPS_IA3(ptr,n)\tBOOST_PP_IF(BOOST_PP_EQUAL(n,3), \\\n\t\t\t\t\t\t\t\t\t\treg_or_ps(spn::xmm_const::matI()[3], LOADPS_ZA3(ptr)), \\\n\t\t\t\t\t\t\t\t\t\tLOADPS_ZA3(ptr))\n#define LOADPS_I3(ptr,n)\tBOOST_PP_IF(BOOST_PP_EQUAL(n,3), \\\n\t\t\t\t\t\t\t\t\t\treg_or_ps(spn::xmm_const::matI()[3], LOADPS_Z3(ptr)), \\\n\t\t\t\t\t\t\t\t\t\tLOADPS_Z3(ptr))\n#define STOREPS_A3(ptr, r)\t{ reg_storel_pi((reg64i*)ptr, r); reg_store_ss(ptr+2, reg_shuffle_ps(r, r, _REG_SHUFFLE(2,2,2,2))); }\n#define STOREPS_3(ptr, r)\tSTOREPS_A3(ptr,r)\n\n#define LOADPS_A2(ptr)\t\tLOADPS_A4(ptr)\n#define LOADPS_2(ptr)\t\tLOADPS_4(ptr)\n#define LOADPS_ZA2(ptr)\t\treg_loadl_pi(spn::xmm_const::tmp0000(), (const reg64i*)ptr)\n#define LOADPS_Z2(ptr)\t\tLOADPS_ZA2(ptr)\n#define LOADPS_IA2(ptr,n)\treg_loadl_pi(spn::xmm_const::matI()[n], (const reg64i*)ptr)\n#define LOADPS_I2(ptr,n)\tLOADPS_IA2(ptr,n)\n#define STOREPS_A2(ptr, r)\treg_storel_pi((reg64i*)ptr,r)\n#define STOREPS_2(ptr, r)\tSTOREPS_A2(ptr,r)\n\n#define BOOLNIZE(b) BOOST_PP_IF(b,true,false)\n#define AFLAG(a) BOOST_PP_IF(a,A,NOTHING)\n\n//! \u30a2\u30e9\u30a4\u30f3\u6e08\u307f\u884c\u5217\u306e\u9699\u9593\u3092\u57cb\u3081\u308b\u5909\u6570\u5b9a\u7fa9\n#define GAP_MATRIX(matname, m, n, seq) GAP_MATRIX_DEF(NOTHING , matname, m, n, seq)\n//! const\u3084mutable\u3092\u4ed8\u3051\u308b\u5834\u5408\u306e\u5b9a\u7fa9\n#define GAP_MATRIX_DEF(prefix, matname, m, n, seq) union { prefix BOOST_PP_CAT(BOOST_PP_CAT(spn::AMat,m),n) matname; struct { BOOST_PP_SEQ_FOR_EACH_I(GAP_TFUNC_OUTER, n, seq) }; };\n#define GAP_DUMMY(aux,index,amount) BOOST_PP_CAT(BOOST_PP_CAT(BOOST_PP_CAT(float dummy, __LINE__), aux), index)[amount];\n//! Tuple\u306e\u8981\u7d20\u6700\u5f8c\u5c3e\u306esizeof\u3092\u8db3\u3057\u5408\u308f\u305b\u308b\n#define COUNT_SIZE(tup)\t\t\t((BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(tup), COUNT_SIZE2, tup)+3)/4)\n#define COUNT_SIZE2(z,idx,data)\t+sizeof(GET_LAST(BOOST_PP_TUPLE_ELEM(idx,data)))\n#define GET_LAST(tup) BOOST_PP_TUPLE_ELEM(BOOST_PP_DEC(BOOST_PP_TUPLE_SIZE(tup)), tup)\n//! \u8981\u7d20\u306e\u30b5\u30a4\u30ba\u3092\u8003\u616e\u3057\u3064\u3064, 16byte aligned\u306b\u306a\u308b\u3088\u3046\u524d\u5f8c\u306b\u9069\u5207\u306a\u30d1\u30c7\u30a3\u30f3\u30b0\u3092\u5165\u308c\u308b\n#define GAP_TFUNC_OUTER(z,nAr,idx,elem) \\\n\t\tGAP_DUMMY(_,idx,nAr) \\\n\t\tBOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(elem), GAP_TFUNC_INNER, elem) \\\n\t\tGAP_DUMMY(_B,idx,4-nAr-COUNT_SIZE(elem))\n//! \u5947\u6570\u8981\u7d20\u3068\u5076\u6570\u8981\u7d20\u3092\u9023\u7d50\u3057\u3066\u5909\u6570\u5ba3\u8a00\u3068\u3059\u308b\n#define GAP_TFUNC_INNER(z,idx,data) BOOST_PP_IF(BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_ELEM(idx,data)),2), GAP_TFUNC_INNER2, GAP_TFUNC_INNER3)(BOOST_PP_TUPLE_ELEM(idx,data))\n#define GAP_TFUNC_INNER2(tup) ARGPAIR(BOOST_PP_TUPLE_ELEM(0,tup), BOOST_PP_TUPLE_ELEM(1,tup))\n#define GAP_TFUNC_INNER3(tup) BOOST_PP_TUPLE_ELEM(0,tup) ARGPAIR(BOOST_PP_TUPLE_ELEM(1,tup), BOOST_PP_TUPLE_ELEM(2,tup))\n#define ARGPAIR(a,b)\tspn::TrivialWrapper<a> b;\n\n//! \u30a2\u30e9\u30a4\u30f3\u6e08\u307f\u30d9\u30af\u30c8\u30eb\u306e\u9699\u9593\u3092\u57cb\u3081\u308b\u5b9a\u7fa9\n#define GAP_VECTOR(vecname, n, seq) GAP_VECTOR_DEF(NOTHING, vecname, n, seq)\n#define GAP_VECTOR_DEF(prefix, vecname, n, seq)\tunion { prefix BOOST_PP_CAT(spn::AVec, n) vecname; struct { float _dummy[n]; BOOST_PP_SEQ_FOR_EACH(GAP_TFUNC_VEC, NOTHING, seq) }; };\n#define GAP_TFUNC_VEC(z,dummy,elem)\telem;\n\n// ----------- \u30d9\u30af\u30c8\u30eb\u3084\u884c\u5217\u306e\u30d7\u30ed\u30c8\u30bf\u30a4\u30d7\u5b9a\u7fa9 -----------\nnamespace spn {\n\tenum AXIS_FLAG {\n\t\tAXIS_X,\n\t\tAXIS_Y,\n\t\tAXIS_Z,\n\t\tNUM_AXIS\n\t};\n\n\ttemplate <int N, bool A>\n\tstruct VecT;\n\n\tstruct MatBase {\n\t\t//! \u5bfe\u89d2\u7dda\u4e0a\u306b\u6570\u5024\u3092\u8a2d\u5b9a\u3002\u6b8b\u308a\u306f\u30bc\u30ed\n\t\tstatic struct _TagDiagonal {} TagDiagonal;\n\t\tstatic struct _TagIdentity {} TagIdentity;\n\t\t//! \u5168\u3066\u3092\u5bfe\u8c61\n\t\tstatic struct _TagAll {} TagAll;\n\t};\n\ttemplate <int M, int N, bool A>\n\tstruct MatT;\n\n\ttemplate <bool A>\n\tstruct PlaneT;\n\n\tstruct QuatBase {\n\t\tstatic struct _TagIdentity {} TagIdentity;\n\t};\n\ttemplate <bool A>\n\tstruct QuatT;\n\ttemplate <bool A>\n\tstruct ExpQuatT;\n\n\t//! Vector\u578b\u306e\u6642\u306ftrue_type, \u305d\u308c\u4ee5\u5916\u306ffalse_type\n\ttemplate <class T>\n\tstruct IsVectorT : std::false_type {};\n\ttemplate <int N, bool A>\n\tstruct IsVectorT<spn::VecT<N,A>> : std::true_type {};\n\t//! Matrix\u578b\u306e\u6642\u306ftrue_type, \u305d\u308c\u4ee5\u5916\u306ffalse_type\n\ttemplate <class T>\n\tstruct IsMatrixT : std::false_type {};\n\ttemplate <int M, int N, bool A>\n\tstruct IsMatrixT<spn::MatT<M,N,A>> : std::true_type {};\n\t//! Quaternion\u578b\u306e\u6642\u306ftrue_type, \u305d\u308c\u4ee5\u5916\u306ffalse_type\n\ttemplate <class T>\n\tstruct IsQuatT : std::false_type {};\n\ttemplate <bool A>\n\tstruct IsQuatT<spn::QuatT<A>> : std::true_type {};\n}\nnamespace std {\n\ttemplate <int N, bool A>\n\tstruct hash<spn::VecT<N,A>> {\n\t\tsize_t operator()(const spn::VecT<N,A>& v) const {\n\t\t\tauto* src = reinterpret_cast<const uint32_t*>(&v);\n\t\t\tsize_t tmp = 0xc000feee;\n\t\t\tfor(int i=0 ; i<N ; i++)\n\t\t\t\ttmp ^= size_t(src[i] << (i+3)) ^ src[i];\n\t\t\treturn tmp;\n\t\t}\n\t};\n\ttemplate <int M, int N, bool A>\n\tstruct hash<spn::MatT<M,N,A>> {\n\t\tsize_t operator()(const spn::MatT<M,N,A>& m) const {\n\t\t\tsize_t tmp = 0xc000feee;\n\t\t\tfor(int i=0 ; i<M ; i++) {\n\t\t\t\tauto* src = reinterpret_cast<const uint32_t*>(m.ma[i]);\n\t\t\t\tfor(int j=0 ; j<N ; j++)\n\t\t\t\t\ttmp ^= (src[j] << (j+3)) ^ src[j];\n\t\t\t}\n\t\t\treturn tmp;\n\t\t}\n\t};\n\ttemplate <bool A>\n\tstruct hash<spn::QuatT<A>> {\n\t\tsize_t operator()(const spn::QuatT<A>& q) const {\n\t\t\tusing VT = spn::VecT<4,A>;\n\t\t\treturn hash<VT>()(reinterpret_cast<const VT&>(q));\n\t\t}\n\t};\n}\n\n", "meta": {"hexsha": "332b465f251a72189929ec7547de7b7b9a59fd2d", "size": 11918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spn_math.hpp", "max_stars_repo_name": "degarashi/spinner", "max_stars_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "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": "spn_math.hpp", "max_issues_repo_name": "degarashi/spinner", "max_issues_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spn_math.hpp", "max_forks_repo_name": "degarashi/spinner", "max_forks_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_forks_repo_licenses": ["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.4459102902, "max_line_length": 184, "alphanum_fraction": 0.6944118141, "num_tokens": 4262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1835232503371751}}
{"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#include <Eigen/Core>\n#include \"gflags/gflags.h\"\n#include \"glog/logging.h\"\n#include \"gtest/gtest.h\"\n\n#include \"bark/commons/params/setter_params.hpp\"\n#include \"bark/geometry/polygon.hpp\"\n#include \"bark/geometry/standard_shapes.hpp\"\n#include \"bark/models/behavior/constant_acceleration/constant_acceleration.hpp\"\n#include \"bark/models/behavior/rule_based/mobil.hpp\"\n#include \"bark/models/behavior/rule_based/mobil_behavior.hpp\"\n#include \"bark/models/dynamic/single_track.hpp\"\n#include \"bark/models/execution/interpolation/interpolate.hpp\"\n#include \"bark/world/goal_definition/goal_definition_polygon.hpp\"\n#include \"bark/world/objects/agent.hpp\"\n#include \"bark/world/observed_world.hpp\"\n#include \"bark/world/tests/make_test_xodr_map.hpp\"\n\nusing namespace bark::models::dynamic;\nusing namespace bark::models::execution;\nusing namespace bark::commons;\nusing namespace bark::models::behavior;\nusing namespace bark::world::map;\nusing namespace bark::models::dynamic;\n\nusing bark::geometry::Model3D;\nusing bark::geometry::Point2d;\nusing bark::geometry::Polygon;\nusing bark::geometry::Pose;\nusing bark::geometry::standard_shapes::CarRectangle;\nusing bark::geometry::standard_shapes::GenerateGoalRectangle;\nusing bark::world::ObservedWorld;\nusing bark::world::World;\nusing bark::world::WorldPtr;\nusing bark::world::goal_definition::GoalDefinitionPolygon;\nusing bark::world::objects::Agent;\nusing bark::world::objects::AgentPtr;\nusing bark::world::tests::MakeXodrMapEndingLaneInParallel;\nusing bark::world::tests::MakeXodrMapOneRoadTwoLanes;\n\nObservedWorld make_observed_world_mobil(double vel, ParamsPtr params) {\n  // Setting Up Map\n  auto open_drive_map = MakeXodrMapOneRoadTwoLanes();\n  auto map_interface = std::make_shared<MapInterface>();\n  map_interface->interface_from_opendrive(open_drive_map);\n\n  Polygon car_polygon = CarRectangle();\n\n  Polygon polygon = GenerateGoalRectangle(6, 3);\n  std::shared_ptr<Polygon> goal_polygon(\n      std::dynamic_pointer_cast<Polygon>(polygon.Translate(\n          Point2d(100, -2))));  // < move the goal polygon into the driving\n                                // corridor in front of the ego vehicle\n  auto goal_definition_ptr =\n      std::make_shared<GoalDefinitionPolygon>(*goal_polygon);\n\n  ExecutionModelPtr exec_model(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model(new BehaviorMobilRuleBased(params));\n\n  State init_state1(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state1 << 0.0, 53.0, -1.75, 0.0, vel;\n  AgentPtr agent1(new Agent(init_state1, beh_model, dyn_model, exec_model,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Preceding Agent\n  ExecutionModelPtr exec_model2(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model2(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model2(new BehaviorConstantAcceleration(params));\n\n  State init_state2(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state2 << 0.0, 80.0, -1.75, 0.0, vel;\n  AgentPtr agent2(new Agent(init_state2, beh_model2, dyn_model2, exec_model2,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Agent coming from behind on the right\n  ExecutionModelPtr exec_model3(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model3(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model3(new BehaviorConstantAcceleration(params));\n\n  State init_state3(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state3 << 0.0, 43.0, -1.75 - 3.5, 0.0, vel;\n  AgentPtr agent3(new Agent(init_state3, beh_model3, dyn_model3, exec_model3,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Following Agent\n  ExecutionModelPtr exec_model4(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model4(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model4(new BehaviorConstantAcceleration(params));\n\n  State init_state4(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state4 << 0.0, 20.0, -1.75, 0.0, vel;\n  AgentPtr agent4(new Agent(init_state4, beh_model4, dyn_model4, exec_model4,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Agent on the right in front\n  ExecutionModelPtr exec_model5(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model5(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model5(new BehaviorConstantAcceleration(params));\n\n  State init_state5(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state5 << 0.0, 100.0, -1.75 - 3.5, 0.0, vel;\n  AgentPtr agent5(new Agent(init_state5, beh_model5, dyn_model5, exec_model5,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Construct World\n  WorldPtr world(new World(params));\n  world->AddAgent(agent1);\n  world->AddAgent(agent2);\n  world->AddAgent(agent3);\n  world->AddAgent(agent4);\n  world->AddAgent(agent5);\n  world->UpdateAgentRTree();\n\n  WorldPtr current_world_state(world->Clone());\n  ObservedWorld observed_world(current_world_state, agent1->GetAgentId());\n\n  return observed_world;\n}\n\nTEST(safety_not_met, behavior_mobil) {\n  double vel = 5.0;\n  auto params = std::make_shared<SetterParams>();\n  params->SetReal(\"BehaviorIDMClassic::DesiredVelocity\", vel);\n  params->SetReal(\"BehaviorMobilRuleBased::AThr\", 0.2);\n  params->SetReal(\"BehaviorMobilRuleBased::Politeness\", 0.0);\n  params->SetReal(\"BehaviorMobilRuleBased::BSafe\", 1.0);\n\n  ObservedWorld observed_world = make_observed_world_mobil(vel, params);\n\n  const BehaviorModelPtr behavior_model =\n      observed_world.GetEgoAgent()->GetBehaviorModel();\n  auto behavior_mobil =\n      std::dynamic_pointer_cast<BehaviorMobilRuleBased>(behavior_model);\n  behavior_mobil->SetLaneCorridor(observed_world.GetLaneCorridor());\n\n  LaneChangeDecision decision;\n  LaneCorridorPtr lane_corr;\n  std::tie(decision, lane_corr) =\n      behavior_mobil->CheckIfLaneChangeBeneficial(observed_world);\n  EXPECT_EQ(decision, LaneChangeDecision::KeepLane);\n  BARK_EXPECT_TRUE(lane_corr != nullptr);\n}\n\nTEST(impolite_incentive_met_safety_met, behavior_mobil) {\n  double vel_ego = 5.0;\n  auto params = std::make_shared<SetterParams>();\n  params->SetReal(\"BehaviorIDMClassic::DesiredVelocity\", vel_ego);\n  params->SetReal(\"BehaviorMobilRuleBased::AThr\", 0.1);\n  params->SetReal(\"BehaviorMobilRuleBased::Politeness\", 0.0);\n  params->SetReal(\"BehaviorMobilRuleBased::BSafe\", 4.0);\n\n  ObservedWorld observed_world = make_observed_world_mobil(vel_ego, params);\n\n  const BehaviorModelPtr behavior_model =\n      observed_world.GetEgoAgent()->GetBehaviorModel();\n  auto behavior_mobil =\n      std::dynamic_pointer_cast<BehaviorMobilRuleBased>(behavior_model);\n  behavior_mobil->SetLaneCorridor(observed_world.GetLaneCorridor());\n\n  LaneChangeDecision decision;\n  LaneCorridorPtr lane_corr;\n  std::tie(decision, lane_corr) =\n      behavior_mobil->CheckIfLaneChangeBeneficial(observed_world);\n  EXPECT_EQ(decision, LaneChangeDecision::ChangeLane);\n  BARK_EXPECT_TRUE(lane_corr != nullptr);\n}\n\nTEST(polite_incentive_not_met_safety_met, behavior_mobil) {\n  double vel_ego = 5.0;\n  auto params = std::make_shared<SetterParams>();\n  params->SetReal(\"BehaviorIDMClassic::DesiredVelocity\", vel_ego);\n  params->SetReal(\"BehaviorMobilRuleBased::AThr\", 0.2);\n  params->SetReal(\"BehaviorMobilRuleBased::Politeness\", 1.0);\n  params->SetReal(\"BehaviorMobilRuleBased::BSafe\", 4.0);\n\n  ObservedWorld observed_world = make_observed_world_mobil(vel_ego, params);\n\n  const BehaviorModelPtr behavior_model =\n      observed_world.GetEgoAgent()->GetBehaviorModel();\n  auto behavior_mobil =\n      std::dynamic_pointer_cast<BehaviorMobilRuleBased>(behavior_model);\n  behavior_mobil->SetLaneCorridor(observed_world.GetLaneCorridor());\n\n  LaneChangeDecision decision;\n  LaneCorridorPtr lane_corr;\n  std::tie(decision, lane_corr) =\n      behavior_mobil->CheckIfLaneChangeBeneficial(observed_world);\n  EXPECT_EQ(decision, LaneChangeDecision::KeepLane);\n  BARK_EXPECT_TRUE(lane_corr != nullptr);\n}\n\nTEST(polite_incentive_met_safety_met, behavior_mobil) {\n  double vel_ego = 5.0;\n  auto params = std::make_shared<SetterParams>();\n  params->SetReal(\"BehaviorIDMClassic::DesiredVelocity\", vel_ego);\n  params->SetReal(\"BehaviorMobilRuleBased::AThr\", -5.0);  // HACK\n  params->SetReal(\"BehaviorMobilRuleBased::Politeness\", 1.0);\n  params->SetReal(\"BehaviorMobilRuleBased::BSafe\", 4.0);\n\n  ObservedWorld observed_world = make_observed_world_mobil(vel_ego, params);\n\n  const BehaviorModelPtr behavior_model =\n      observed_world.GetEgoAgent()->GetBehaviorModel();\n  auto behavior_mobil =\n      std::dynamic_pointer_cast<BehaviorMobilRuleBased>(behavior_model);\n  behavior_mobil->SetLaneCorridor(observed_world.GetLaneCorridor());\n\n  LaneChangeDecision decision;\n  LaneCorridorPtr lane_corr;\n  std::tie(decision, lane_corr) =\n      behavior_mobil->CheckIfLaneChangeBeneficial(observed_world);\n  EXPECT_EQ(decision, LaneChangeDecision::ChangeLane);\n  BARK_EXPECT_TRUE(lane_corr != nullptr);\n}\n\nTEST(change_lane_due_to_lane_ending, behavior_mobil) {\n  double vel_ego = 5.0;\n  auto params = std::make_shared<SetterParams>();\n  params->SetReal(\"BehaviorIDMClassic::DesiredVelocity\", vel_ego);\n  params->SetBool(\"BehaviorIDMClassic::BrakeForLaneEnd\", true);\n  params->SetReal(\"BehaviorIDMClassic::BrakeForLaneEndEnabledDistance\", 60);\n  params->SetReal(\"BehaviorIDMClassic::MaxAcceleration\", 1.9);\n  params->SetReal(\"BehaviorMobilRuleBased::AThr\", 0.2);\n  params->SetReal(\"BehaviorMobilRuleBased::Politeness\", 0.5);\n  params->SetReal(\"BehaviorMobilRuleBased::BSafe\", 4.0);\n\n  // Setting Up Map\n  auto open_drive_map = MakeXodrMapEndingLaneInParallel();\n  auto map_interface = std::make_shared<MapInterface>();\n  map_interface->interface_from_opendrive(open_drive_map);\n\n  Polygon car_polygon = CarRectangle();\n\n  Polygon polygon = GenerateGoalRectangle(6, 3);\n  std::shared_ptr<Polygon> goal_polygon(\n      std::dynamic_pointer_cast<Polygon>(polygon.Translate(\n          Point2d(100, -2))));  // < move the goal polygon into the driving\n                                // corridor in front of the ego vehicle\n  auto goal_definition_ptr =\n      std::make_shared<GoalDefinitionPolygon>(*goal_polygon);\n\n  ExecutionModelPtr exec_model(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model(new BehaviorMobilRuleBased(params));\n\n  State init_state1(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state1 << 0.0, 30.0, -1.75 - 3.5, 0.0, vel_ego;\n  AgentPtr agent1(new Agent(init_state1, beh_model, dyn_model, exec_model,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Construct World\n  WorldPtr world(new World(params));\n  world->AddAgent(agent1);\n  world->UpdateAgentRTree();\n\n  WorldPtr current_world_state(world->Clone());\n  ObservedWorld observed_world(current_world_state, agent1->GetAgentId());\n\n  const BehaviorModelPtr behavior_model = agent1->GetBehaviorModel();\n\n  auto behavior_mobil =\n      std::dynamic_pointer_cast<BehaviorMobilRuleBased>(behavior_model);\n  behavior_mobil->SetLaneCorridor(observed_world.GetLaneCorridor());\n\n  LaneChangeDecision decision;\n  LaneCorridorPtr lane_corr;\n  std::tie(decision, lane_corr) =\n      behavior_mobil->CheckIfLaneChangeBeneficial(observed_world);\n  EXPECT_EQ(decision, LaneChangeDecision::ChangeLane);\n  BARK_EXPECT_TRUE(lane_corr != nullptr);\n}\n\nTEST(no_lane_change_to_ending_lane, behavior_mobil) {\n  double vel = 5.0;\n  auto params = std::make_shared<SetterParams>();\n  params->SetReal(\"BehaviorIDMClassic::DesiredVelocity\", vel);\n  params->SetBool(\"BehaviorIDMClassic::BrakeForLaneEnd\", true);\n  params->SetReal(\"BehaviorIDMClassic::BrakeForLaneEndEnabledDistance\", 60);\n  params->SetReal(\"BehaviorIDMClassic::MaxAcceleration\", 1.9);\n  params->SetReal(\"BehaviorMobilRuleBased::AThr\", 0.1);\n  params->SetReal(\"BehaviorMobilRuleBased::Politeness\", 0.5);\n  params->SetReal(\"BehaviorMobilRuleBased::BSafe\", 4.0);\n\n  // Setting Up Map\n  auto open_drive_map = MakeXodrMapEndingLaneInParallel();\n  auto map_interface = std::make_shared<MapInterface>();\n  map_interface->interface_from_opendrive(open_drive_map);\n\n  Polygon car_polygon = CarRectangle();\n\n  Polygon polygon = GenerateGoalRectangle(6, 3);\n  std::shared_ptr<Polygon> goal_polygon(\n      std::dynamic_pointer_cast<Polygon>(polygon.Translate(\n          Point2d(100, -2))));  // < move the goal polygon into the driving\n                                // corridor in front of the ego vehicle\n  auto goal_definition_ptr =\n      std::make_shared<GoalDefinitionPolygon>(*goal_polygon);\n\n  ExecutionModelPtr exec_model(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model(new BehaviorMobilRuleBased(params));\n\n  State init_state1(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state1 << 0.0, 30.0, -1.75, 0.0, vel;\n  AgentPtr agent1(new Agent(init_state1, beh_model, dyn_model, exec_model,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Preceding Agent\n  ExecutionModelPtr exec_model2(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model2(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model2(new BehaviorConstantAcceleration(params));\n\n  State init_state2(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state2 << 0.0, 60.0, -1.75, 0.0, vel;\n  AgentPtr agent2(new Agent(init_state2, beh_model2, dyn_model2, exec_model2,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Construct World\n  WorldPtr world(new World(params));\n  world->AddAgent(agent1);\n  world->AddAgent(agent2);\n  world->UpdateAgentRTree();\n\n  WorldPtr current_world_state(world->Clone());\n  ObservedWorld observed_world(current_world_state, agent1->GetAgentId());\n\n  const BehaviorModelPtr behavior_model = agent1->GetBehaviorModel();\n\n  auto behavior_mobil =\n      std::dynamic_pointer_cast<BehaviorMobilRuleBased>(behavior_model);\n  behavior_mobil->SetLaneCorridor(observed_world.GetLaneCorridor());\n\n  LaneChangeDecision decision;\n  LaneCorridorPtr lane_corr;\n  std::tie(decision, lane_corr) =\n      behavior_mobil->CheckIfLaneChangeBeneficial(observed_world);\n  EXPECT_EQ(decision, LaneChangeDecision::KeepLane);\n  BARK_EXPECT_TRUE(lane_corr != nullptr);\n}\n\nTEST(slower_preceding_agent, behavior_mobil) {\n  // Setting Up Map\n  auto open_drive_map = MakeXodrMapOneRoadTwoLanes();\n  auto map_interface = std::make_shared<MapInterface>();\n  map_interface->interface_from_opendrive(open_drive_map);\n\n  auto params = std::make_shared<SetterParams>();\n  Polygon car_polygon = CarRectangle();\n\n  Polygon polygon(\n      Pose(1, 1, 0),\n      std::vector<Point2d>{Point2d(0, 0), Point2d(0, 2), Point2d(2, 2),\n                           Point2d(2, 0), Point2d(0, 0)});\n  std::shared_ptr<Polygon> goal_polygon(\n      std::dynamic_pointer_cast<Polygon>(polygon.Translate(\n          Point2d(50, -2))));  // < move the goal polygon into the driving\n                               // corridor in front of the ego vehicle\n  auto goal_definition_ptr =\n      std::make_shared<GoalDefinitionPolygon>(*goal_polygon);\n\n  // Ego Agent\n  ExecutionModelPtr exec_model(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model(new BehaviorMobil(params));\n\n  State init_state1(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state1 << 0.0, 3.0, -1.75, 0.0, 5.0;\n  AgentPtr agent1(new Agent(init_state1, beh_model, dyn_model, exec_model,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Preceding Agent\n  ExecutionModelPtr exec_model2(new ExecutionModelInterpolate(params));\n  DynamicModelPtr dyn_model2(new SingleTrackModel(params));\n  BehaviorModelPtr beh_model2(new BehaviorMobil(params));\n\n  State init_state2(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  init_state2 << 0.0, 15.0, -1.75, 0.0, 2.0;\n  AgentPtr agent2(new Agent(init_state2, beh_model2, dyn_model2, exec_model2,\n                            car_polygon, params, goal_definition_ptr,\n                            map_interface, bark::geometry::Model3D()));\n\n  // Construct World\n  WorldPtr world(new World(params));\n  world->AddAgent(agent1);\n  world->AddAgent(agent2);\n  world->UpdateAgentRTree();\n\n  WorldPtr current_world_state(world->Clone());\n  ObservedWorld observed_world(current_world_state, agent1->GetAgentId());\n\n  const BehaviorModelPtr behavior_model = agent1->GetBehaviorModel();\n\n  auto behavior_mobil =\n      std::dynamic_pointer_cast<BehaviorMobil>(behavior_model);\n\n  LaneChangeDecision decision;\n  LaneCorridorPtr lane_corr;\n  std::tie(decision, lane_corr) =\n      behavior_mobil->CheckIfLaneChangeBeneficial(observed_world);\n  EXPECT_EQ(decision, LaneChangeDecision::ChangeRight);\n  BARK_EXPECT_TRUE(lane_corr != nullptr);\n}\n\nTEST(behavior_mobil, clone) {\n  auto params = std::make_shared<SetterParams>();\n  BehaviorModelPtr beh_model(new BehaviorMobil(params));\n  ASSERT_EQ(BehaviorStatus::VALID, beh_model->GetBehaviorStatus());\n  beh_model->SetBehaviorStatus(BehaviorStatus::EXPIRED);\n\n  auto cloned_model = BehaviorModelPtr(beh_model->Clone());\n  ASSERT_EQ(BehaviorStatus::EXPIRED, cloned_model->GetBehaviorStatus());\n}\n\nint main(int argc, char** argv) {\n  // FLAGS_v=2;\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "400039bc576ae97b25be6ffb0212127385c63f16", "size": 18243, "ext": "cc", "lang": "C++", "max_stars_repo_path": "bark/models/tests/behavior_mobil_test.cc", "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/tests/behavior_mobil_test.cc", "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/tests/behavior_mobil_test.cc", "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": 41.8417431193, "max_line_length": 79, "alphanum_fraction": 0.7445047415, "num_tokens": 4591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.18352324189388253}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/DirectionMap.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/ConservativeFromPrimitive.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Tags.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nnamespace NewtonianEuler::fd {\ntemplate <typename PrimsTags, typename TagsList, size_t Dim,\n          size_t ThermodynamicDim, typename F>\nvoid reconstruct_prims_work(\n    const gsl::not_null<std::array<Variables<TagsList>, Dim>*>\n        vars_on_lower_face,\n    const gsl::not_null<std::array<Variables<TagsList>, Dim>*>\n        vars_on_upper_face,\n    const F& reconstruct, const Variables<PrimsTags>& volume_prims,\n    const EquationsOfState::EquationOfState<false, ThermodynamicDim>& eos,\n    const Element<Dim>& element,\n    const FixedHashMap<\n        maximum_number_of_neighbors(Dim),\n        std::pair<Direction<Dim>, ElementId<Dim>>, std::vector<double>,\n        boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>& neighbor_data,\n    const Mesh<Dim>& subcell_mesh, const size_t ghost_zone_size) {\n  // Conservative vars tags\n  using MassDensityCons = Tags::MassDensityCons;\n  using EnergyDensity = Tags::EnergyDensity;\n  using MomentumDensity = Tags::MomentumDensity<Dim>;\n\n  // Primitive vars tags\n  using MassDensity = Tags::MassDensity<DataVector>;\n  using Velocity = Tags::Velocity<DataVector, Dim>;\n  using SpecificInternalEnergy = Tags::SpecificInternalEnergy<DataVector>;\n  using Pressure = Tags::Pressure<DataVector>;\n\n  using prim_tags_for_reconstruction =\n      tmpl::list<MassDensity, Velocity, Pressure>;\n\n  ASSERT(Mesh<Dim>(subcell_mesh.extents(0), subcell_mesh.basis(0),\n                   subcell_mesh.quadrature(0)) == subcell_mesh,\n         \"The subcell mesh should be isotropic but got \" << subcell_mesh);\n  const size_t volume_num_pts = subcell_mesh.number_of_grid_points();\n  const size_t reconstructed_num_pts =\n      (subcell_mesh.extents(0) + 1) *\n      subcell_mesh.extents().slice_away(0).product();\n  const size_t neighbor_num_pts =\n      ghost_zone_size * subcell_mesh.extents().slice_away(0).product();\n  size_t vars_in_neighbor_count = 0;\n  tmpl::for_each<prim_tags_for_reconstruction>(\n      [&element, &neighbor_data, neighbor_num_pts, &reconstruct,\n       reconstructed_num_pts, volume_num_pts, &volume_prims,\n       &vars_in_neighbor_count, &vars_on_lower_face, &vars_on_upper_face,\n       &subcell_mesh](auto tag_v) {\n        using tag = tmpl::type_from<decltype(tag_v)>;\n        auto& volume_tensor = get<tag>(volume_prims);\n\n        const size_t number_of_components = volume_tensor.size();\n        const gsl::span<const double> volume_vars = gsl::make_span(\n            volume_tensor[0].data(), number_of_components * volume_num_pts);\n        std::array<gsl::span<double>, Dim> upper_face_vars{};\n        std::array<gsl::span<double>, Dim> lower_face_vars{};\n        for (size_t i = 0; i < Dim; ++i) {\n          gsl::at(upper_face_vars, i) = gsl::make_span(\n              get<tag>(gsl::at(*vars_on_upper_face, i))[0].data(),\n              number_of_components * reconstructed_num_pts);\n          gsl::at(lower_face_vars, i) = gsl::make_span(\n              get<tag>(gsl::at(*vars_on_lower_face, i))[0].data(),\n              number_of_components * reconstructed_num_pts);\n        }\n\n        DirectionMap<Dim, gsl::span<const double>> ghost_cell_vars{};\n        for (const auto& direction : Direction<Dim>::all_directions()) {\n          const auto& neighbors_in_direction =\n              element.neighbors().at(direction);\n          ASSERT(neighbors_in_direction.size() == 1,\n                 \"Currently only support one neighbor in each direction, but \"\n                 \"got \"\n                     << neighbors_in_direction.size() << \" in direction \"\n                     << direction);\n          ghost_cell_vars[direction] = gsl::make_span(\n              &neighbor_data.at(std::pair{\n                  direction,\n                  *neighbors_in_direction\n                       .begin()})[vars_in_neighbor_count * neighbor_num_pts],\n              number_of_components * neighbor_num_pts);\n        }\n\n        reconstruct(make_not_null(&upper_face_vars),\n                    make_not_null(&lower_face_vars), volume_vars,\n                    ghost_cell_vars, subcell_mesh.extents(),\n                    number_of_components);\n\n        vars_in_neighbor_count += number_of_components;\n      });\n\n  for (size_t i = 0; i < Dim; ++i) {\n    auto& vars_upper_face = gsl::at(*vars_on_upper_face, i);\n    auto& vars_lower_face = gsl::at(*vars_on_lower_face, i);\n\n    if constexpr (ThermodynamicDim == 2) {\n      get<SpecificInternalEnergy>(vars_upper_face) =\n          eos.specific_internal_energy_from_density_and_pressure(\n              get<MassDensity>(vars_upper_face),\n              get<Pressure>(vars_upper_face));\n      get<SpecificInternalEnergy>(vars_lower_face) =\n          eos.specific_internal_energy_from_density_and_pressure(\n              get<MassDensity>(vars_lower_face),\n              get<Pressure>(vars_lower_face));\n    } else {\n      get<SpecificInternalEnergy>(vars_upper_face) =\n          eos.specific_internal_energy_from_density(\n              get<MassDensity>(vars_upper_face));\n      get<SpecificInternalEnergy>(vars_lower_face) =\n          eos.specific_internal_energy_from_density(\n              get<MassDensity>(vars_lower_face));\n    }\n\n    // Compute conserved variables on faces\n    NewtonianEuler::ConservativeFromPrimitive<Dim>::apply(\n        make_not_null(&get<MassDensityCons>(vars_upper_face)),\n        make_not_null(&get<MomentumDensity>(vars_upper_face)),\n        make_not_null(&get<EnergyDensity>(vars_upper_face)),\n        get<MassDensity>(vars_upper_face), get<Velocity>(vars_upper_face),\n        get<SpecificInternalEnergy>(vars_upper_face));\n    NewtonianEuler::ConservativeFromPrimitive<Dim>::apply(\n        make_not_null(&get<MassDensityCons>(vars_lower_face)),\n        make_not_null(&get<MomentumDensity>(vars_lower_face)),\n        make_not_null(&get<EnergyDensity>(vars_lower_face)),\n        get<MassDensity>(vars_lower_face), get<Velocity>(vars_lower_face),\n        get<SpecificInternalEnergy>(vars_lower_face));\n  }\n}\n\ntemplate <typename TagsList, typename PrimsTags, size_t Dim,\n          size_t ThermodynamicDim, typename F0, typename F1>\nvoid reconstruct_fd_neighbor_work(\n    const gsl::not_null<Variables<TagsList>*> vars_on_face,\n    const F0& reconstruct_lower_neighbor, const F1& reconstruct_upper_neighbor,\n    const Variables<PrimsTags>& subcell_volume_prims,\n    const EquationsOfState::EquationOfState<false, ThermodynamicDim>& eos,\n    const Element<Dim>& element,\n    const FixedHashMap<\n        maximum_number_of_neighbors(Dim),\n        std::pair<Direction<Dim>, ElementId<Dim>>, std::vector<double>,\n        boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>& neighbor_data,\n    const Mesh<Dim>& subcell_mesh,\n    const Direction<Dim>& direction_to_reconstruct,\n    const size_t ghost_zone_size) {\n  // Conservative vars tags\n  using MassDensityCons = Tags::MassDensityCons;\n  using EnergyDensity = Tags::EnergyDensity;\n  using MomentumDensity = Tags::MomentumDensity<Dim>;\n\n  // Primitive vars tags\n  using MassDensity = Tags::MassDensity<DataVector>;\n  using Velocity = Tags::Velocity<DataVector, Dim>;\n  using SpecificInternalEnergy = Tags::SpecificInternalEnergy<DataVector>;\n  using Pressure = Tags::Pressure<DataVector>;\n\n  using prim_tags_for_reconstruction =\n      tmpl::list<MassDensity, Velocity, Pressure>;\n\n  const std::pair mortar_id{\n      direction_to_reconstruct,\n      *element.neighbors().at(direction_to_reconstruct).begin()};\n  Index<Dim> ghost_data_extents = subcell_mesh.extents();\n  ghost_data_extents[direction_to_reconstruct.dimension()] = ghost_zone_size;\n  Variables<prim_tags_for_reconstruction> neighbor_prims{\n      ghost_data_extents.product()};\n  {\n    ASSERT(neighbor_data.contains(mortar_id),\n           \"The neighbor data does not contain the mortar: (\"\n               << mortar_id.first << ',' << mortar_id.second << \")\");\n    const auto& neighbor_data_in_direction = neighbor_data.at(mortar_id);\n    std::copy(neighbor_data_in_direction.begin(),\n              std::next(neighbor_data_in_direction.begin(),\n                        static_cast<std::ptrdiff_t>(\n                            neighbor_prims.number_of_independent_components *\n                            ghost_data_extents.product())),\n              neighbor_prims.data());\n  }\n\n  tmpl::for_each<prim_tags_for_reconstruction>(\n      [&direction_to_reconstruct, &ghost_data_extents, &neighbor_prims,\n       &reconstruct_lower_neighbor, &reconstruct_upper_neighbor, &subcell_mesh,\n       &subcell_volume_prims, &vars_on_face](auto tag_v) {\n        using tag = tmpl::type_from<decltype(tag_v)>;\n        const auto& tensor_volume = get<tag>(subcell_volume_prims);\n        const auto& tensor_neighbor = get<tag>(neighbor_prims);\n        auto& tensor_on_face = get<tag>(*vars_on_face);\n        if (direction_to_reconstruct.side() == Side::Upper) {\n          for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();\n               ++tensor_index) {\n            reconstruct_upper_neighbor(\n                make_not_null(&tensor_on_face[tensor_index]),\n                tensor_volume[tensor_index], tensor_neighbor[tensor_index],\n                subcell_mesh.extents(), ghost_data_extents,\n                direction_to_reconstruct);\n          }\n        } else {\n          for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();\n               ++tensor_index) {\n            reconstruct_lower_neighbor(\n                make_not_null(&tensor_on_face[tensor_index]),\n                tensor_volume[tensor_index], tensor_neighbor[tensor_index],\n                subcell_mesh.extents(), ghost_data_extents,\n                direction_to_reconstruct);\n          }\n        }\n      });\n\n  if constexpr (ThermodynamicDim == 2) {\n    get<SpecificInternalEnergy>(*vars_on_face) =\n        eos.specific_internal_energy_from_density_and_pressure(\n            get<MassDensity>(*vars_on_face), get<Pressure>(*vars_on_face));\n  } else {\n    get<SpecificInternalEnergy>(*vars_on_face) =\n        eos.specific_internal_energy_from_density(\n            get<MassDensity>(*vars_on_face));\n  }\n  NewtonianEuler::ConservativeFromPrimitive<Dim>::apply(\n      make_not_null(&get<MassDensityCons>(*vars_on_face)),\n      make_not_null(&get<MomentumDensity>(*vars_on_face)),\n      make_not_null(&get<EnergyDensity>(*vars_on_face)),\n      get<MassDensity>(*vars_on_face), get<Velocity>(*vars_on_face),\n      get<SpecificInternalEnergy>(*vars_on_face));\n}\n}  // namespace NewtonianEuler::fd\n", "meta": {"hexsha": "497c4d42a0b0f98fa4e349bddebf90dbc8f984dc", "size": 11325, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/NewtonianEuler/FiniteDifference/ReconstructWork.tpp", "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/Evolution/Systems/NewtonianEuler/FiniteDifference/ReconstructWork.tpp", "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/Evolution/Systems/NewtonianEuler/FiniteDifference/ReconstructWork.tpp", "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": 45.4819277108, "max_line_length": 79, "alphanum_fraction": 0.6903311258, "num_tokens": 2561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.18352324084266933}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/xray/fast_gradients.h>\n#include <scitbx/boost_python/is_polymorphic_workaround.h>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\nSCITBX_BOOST_IS_POLYMORPHIC_WORKAROUND(cctbx::xray::fast_gradients<>)\n\nnamespace cctbx { namespace xray { namespace boost_python {\n\nnamespace {\n\n  struct fast_gradients_wrappers\n  {\n    typedef fast_gradients<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t, bases<w_t::base_t> >(\"fast_gradients\", no_init)\n        .def(init<uctbx::unit_cell const&,\n                  af::const_ref<scatterer<> > const&,\n                  scattering_type_registry const&,\n                  optional<double const&,\n                           double const&,\n                           double const&,\n                           double const&> >(\n          (arg(\"unit_cell\"),\n           arg(\"scatterers\"),\n           arg(\"scattering_type_registry\"),\n           arg(\"u_base\"),\n           arg(\"wing_cutoff\"),\n           arg(\"exp_table_one_over_step_size\"),\n           arg(\"tolerance_positive_definite\"))))\n        .def(\"sampling\",\n          (void(w_t::*)(\n            af::const_ref<scatterer<> > const&,\n            af::const_ref<double> const&,\n            scattering_type_registry const&,\n            sgtbx::site_symmetry_table const&,\n            af::const_ref<double, w_t::accessor_type> const&,\n            std::size_t,\n            bool)) &w_t::sampling,\n          (arg(\"scatterers\"),\n           arg(\"u_iso_refinable_params\"),\n           arg(\"scattering_type_registry\"),\n           arg(\"site_symmetry_table\"),\n           arg(\"ft_d_target_d_f_calc\"),\n           arg(\"n_parameters\"),\n           arg(\"sampled_density_must_be_positive\")))\n        .def(\"sampling\",\n          (void(w_t::*)(\n            af::const_ref<scatterer<> > const&,\n            af::const_ref<double> const&,\n            scattering_type_registry const&,\n            sgtbx::site_symmetry_table const&,\n            af::const_ref<std::complex<double>, w_t::accessor_type> const&,\n            std::size_t,\n            bool)) &w_t::sampling,\n          (arg(\"scatterers\"),\n           arg(\"u_iso_refinable_params\"),\n           arg(\"scattering_type_registry\"),\n           arg(\"site_symmetry_table\"),\n           arg(\"ft_d_target_d_f_calc\"),\n           arg(\"n_parameters\"),\n           arg(\"sampled_density_must_be_positive\")))\n        .def(\"packed\", &w_t::packed)\n        .def(\"d_target_d_site_cart\", &w_t::d_target_d_site_cart)\n        .def(\"d_target_d_u_iso\", &w_t::d_target_d_u_iso)\n        .def(\"d_target_d_u_cart\", &w_t::d_target_d_u_cart)\n        .def(\"d_target_d_occupancy\", &w_t::d_target_d_occupancy)\n        .def(\"d_target_d_fp\", &w_t::d_target_d_fp)\n        .def(\"d_target_d_fdp\", &w_t::d_target_d_fdp)\n      ;\n    }\n  };\n\n} // namespace <anoymous>\n\n  void wrap_fast_gradients()\n  {\n    fast_gradients_wrappers::wrap();\n  }\n\n}}} // namespace cctbx::xray::boost_python\n", "meta": {"hexsha": "75cdfdc930394e7fdc74072f3f0bf79265a63079", "size": 2971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/xray/boost_python/fast_gradients.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": "cctbx/xray/boost_python/fast_gradients.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": "cctbx/xray/boost_python/fast_gradients.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": 33.7613636364, "max_line_length": 75, "alphanum_fraction": 0.5853248065, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.32423538592116924, "lm_q1q2_score": 0.18352323819784286}}
{"text": "#include <chrono>\n#include <iostream>\n#include <iomanip>\n#include <filesystem>\n#include <fstream>\n#include <boost/program_options.hpp>\n#include \"io_service_pool.hpp\"\n#include \"safe_counter.hpp\"\n#include \"random_forest.hpp\"\n#include \"receptor.hpp\"\n#include \"ligand.hpp\"\n#include \"array.hpp\"\n\nint main(int argc, char* argv[])\n{\n\tusing namespace std;\n\tusing namespace std::filesystem;\n\tpath receptor_path, ligand_path, out_path;\n\tarray<double, 3> center, size;\n\tsize_t seed, num_threads, num_trees, num_tasks, max_conformations;\n\tdouble granularity;\n\tbool score_only = true;\n\tbool anna_test = true;\n\n\t// Process program options.\n\ttry\n\t{\n\t\t// Initialize the default values of optional arguments.\n\t\tusing namespace std::chrono;\n\t\tconst path default_out_path = \".\";\n\t\tconst size_t default_seed = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();\n\t\tconst size_t default_num_threads = std::thread::hardware_concurrency();\n\t\tconst size_t default_num_trees = 500;\n\t\tconst size_t default_num_tasks = 64;\n\t\tconst size_t default_max_conformations = 9;\n\t\tconst double default_granularity = 0.125;\n\n\t\t// Set up options description.\n\t\tusing namespace boost::program_options;\n\t\toptions_description input_options(\"input (required)\");\n\t\tinput_options.add_options()\n\t\t\t(\"receptor\", value<path>(&receptor_path)->required(), \"receptor in PDBQT format\")\n\t\t\t(\"ligand\", value<path>(&ligand_path)->required(), \"ligand or folder of ligands in PDBQT format\")\n\t\t\t(\"center_x\", value<double>(&center[0])->required(), \"x coordinate of the search space center\")\n\t\t\t(\"center_y\", value<double>(&center[1])->required(), \"y coordinate of the search space center\")\n\t\t\t(\"center_z\", value<double>(&center[2])->required(), \"z coordinate of the search space center\")\n\t\t\t(\"size_x\", value<double>(&size[0])->required(), \"size in the x dimension in Angstrom\")\n\t\t\t(\"size_y\", value<double>(&size[1])->required(), \"size in the y dimension in Angstrom\")\n\t\t\t(\"size_z\", value<double>(&size[2])->required(), \"size in the z dimension in Angstrom\")\n\t\t\t;\n\t\toptions_description output_options(\"output (optional)\");\n\t\toutput_options.add_options()\n\t\t\t(\"out\", value<path>(&out_path)->default_value(default_out_path), \"folder of predicted conformations in PDBQT format\")\n\t\t\t;\n\t\toptions_description miscellaneous_options(\"options (optional)\");\n\t\tmiscellaneous_options.add_options()\n\t\t\t(\"seed\", value<size_t>(&seed)->default_value(default_seed), \"explicit non-negative random seed\")\n\t\t\t(\"threads\", value<size_t>(&num_threads)->default_value(default_num_threads), \"number of worker threads to use\")\n\t\t\t(\"trees\", value<size_t>(&num_trees)->default_value(default_num_trees), \"number of decision trees in random forest\")\n\t\t\t(\"tasks\", value<size_t>(&num_tasks)->default_value(default_num_tasks), \"number of Monte Carlo tasks for global search\")\n\t\t\t(\"conformations\", value<size_t>(&max_conformations)->default_value(default_max_conformations), \"maximum number of binding conformations to write\")\n\t\t\t(\"granularity\", value<double>(&granularity)->default_value(default_granularity), \"density of probe atoms of grid maps\")\n\t\t\t(\"score_only\", bool_switch(&score_only), \"scoring without docking\")\n\t\t\t(\"help\", \"this help information\")\n\t\t\t(\"version\", \"version information\")\n\t\t\t(\"config\", value<path>(), \"configuration file to load options from\")\n\t\t\t;\n\t\toptions_description all_options;\n\t\tall_options.add(input_options).add(output_options).add(miscellaneous_options);\n\n\t\t// Parse command line arguments.\n\t\tvariables_map vm;\n\t\tstore(parse_command_line(argc, argv, all_options), vm);\n\n\t\t// If no command line argument is supplied or help is requested, print the usage and exit.\n\t\tif (argc == 1 || vm.count(\"help\"))\n\t\t{\n\t\t\tcout << all_options;\n\t\t\treturn 0;\n\t\t}\n\n\t\t// If version is requested, print the version and exit.\n\t\tif (vm.count(\"version\"))\n\t\t{\n\t\t\tcout << \"2.2.3\" << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\t// If a configuration file is present, parse it.\n\t\tif (vm.count(\"config\"))\n\t\t{\n\t\t\tifstream config_file(vm[\"config\"].as<path>());\n\t\t\tstore(parse_config_file(config_file, all_options), vm);\n\t\t}\n\n\t\t// Notify the user of parsing errors, if any.\n\t\tvm.notify();\n\n\t\t// Validate receptor_path.\n\t\tif (!exists(receptor_path))\n\t\t{\n\t\t\tcerr << \"Option receptor \" << receptor_path << \" does not exist\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (!is_regular_file(receptor_path))\n\t\t{\n\t\t\tcerr << \"Option receptor \" << receptor_path << \" is not a regular file\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\t// Validate ligand_path.\n\t\tif (!exists(ligand_path))\n\t\t{\n\t\t\tcerr << \"Option ligand \" << ligand_path << \" does not exist\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\t// Validate out_path.\n\t\tif (exists(out_path))\n\t\t{\n\t\t\tif (!is_directory(out_path))\n\t\t\t{\n\t\t\t\tcerr << \"Option out \" << out_path << \" is not a directory\" << endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!create_directories(out_path))\n\t\t\t{\n\t\t\t\tcerr << \"Failed to create output folder \" << out_path << endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\t// Validate miscellaneous options.\n\t\tif (!num_threads)\n\t\t{\n\t\t\tcerr << \"Option threads must be 1 or greater\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (!num_tasks)\n\t\t{\n\t\t\tcerr << \"Option tasks must be 1 or greater\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (!max_conformations)\n\t\t{\n\t\t\tcerr << \"Option conformations must be 1 or greater\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (granularity <= 0)\n\t\t{\n\t\t\tcerr << \"Option granularity must be positive\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\tcatch (const exception& e)\n\t{\n\t\tcerr << e.what() << endl;\n\t\treturn 1;\n\t}\n\n\tcout << \"Hello\" << endl;\n\t// Parse the receptor.\n\tcout << \"Parsing the receptor \" << receptor_path << endl;\n\treceptor rec(receptor_path, center, size, granularity);\n\n\t// Reserve storage for result containers.\n\tvector<vector<result>> result_containers(num_tasks);\n\tfor (auto& rc : result_containers)\n\t{\n\t\trc.reserve(20);\t// Maximum number of results obtained from a single Monte Carlo task.\n\t}\n\tvector<result> results;\n\tresults.reserve(max_conformations);\n\n\t// Enumerate and sort input ligands.\n\tcout << \"Enumerating input ligands in \" << ligand_path << endl;\n\tvector<path> input_ligand_paths;\n\tif (is_regular_file(ligand_path))\n\t{\n\t\tinput_ligand_paths.push_back(ligand_path);\n\t}\n\telse\n\t{\n\t\tfor (directory_iterator dir_iter(ligand_path), end_dir_iter; dir_iter != end_dir_iter; ++dir_iter)\n\t\t{\n\t\t\t// Filter files with .pdbqt and .PDBQT extensions.\n\t\t\tconst path input_ligand_path = dir_iter->path();\n\t\t\tconst auto ext = input_ligand_path.extension();\n\t\t\tif (ext != \".pdbqt\" && ext != \".PDBQT\") continue;\n\t\t\tinput_ligand_paths.push_back(input_ligand_path);\n\t\t}\n\t}\n\tconst size_t num_input_ligands = input_ligand_paths.size();\n\tcout << \"Sorting \" << num_input_ligands << \" input ligands in alphabetical order\" << endl;\n\tsort(input_ligand_paths.begin(), input_ligand_paths.end());\n\n\t// Initialize a Mersenne Twister random number generator.\n\tcout << \"Seeding a random number generator with \" << seed << endl;\n\tmt19937_64 rng(seed);\n\n\t// Initialize an io service pool and create worker threads for later use.\n\tcout << \"Creating an io service pool of \" << num_threads << \" worker threads\" << endl;\n\tio_service_pool io(num_threads);\n\tsafe_counter<size_t> cnt;\n\n\t// Precalculate the scoring function in parallel.\n\tcout << \"Calculating a scoring function of \" << scoring_function::n << \" atom types\" << endl;\n\tscoring_function sf;\n\tcnt.init((sf.n + 1) * sf.n >> 1);\n\tfor (size_t t1 = 0; t1 < sf.n; ++t1)\n\tfor (size_t t0 = 0; t0 <=  t1; ++t0)\n\t{\n\t\tio.post([&, t0, t1]()\n\t\t{\n\t\t\tsf.precalculate(t0, t1);\n\t\t\tcnt.increment();\n\t\t});\n\t}\n\tcnt.wait();\n\tsf.clear();\n\n\t// Train RF-Score on the fly.\n\tcout << \"Training a random forest of \" << num_trees << \" trees with \" << tree::nv << \" variables and \" << tree::ns << \" samples\" << endl;\n\tforest f(num_trees, seed);\n\tcnt.init(num_trees);\n\tfor (size_t i = 0; i < num_trees; ++i)\n\t{\n\t\tio.post([&, i]()\n\t\t{\n\t\t\tf[i].train(8, f.u01_s);\n\t\t\tcnt.increment();\n\t\t});\n\t}\n\tcnt.wait();\n\tf.clear();\n\n\t// Output headers to the standard output and the log file.\n\tcout << \"Creating GRID maps of \" << granularity << \" A and running \" << num_tasks << \" Monte Carlo searches per ligand\" << endl\n\t\t<< \"   Index             Ligand   nConfs   idock score (kcal/mol)   RF-Score (pKd)\" << endl << setprecision(2);\n\tcout.setf(ios::fixed, ios::floatfield);\n\tofstream log(out_path / \"log.csv\");\n\tlog.setf(ios::fixed, ios::floatfield);\n\tlog << \"Ligand,nConfs,idock score (kcal/mol),RF-Score (pKd)\" << endl << setprecision(2);\n\t// Start to dock each input ligand.\n\tsize_t index = 0;\n\tfor (const auto& input_ligand_path : input_ligand_paths)\n\t{\n\t\t// Output the ligand file stem.\n\t\tconst string stem = input_ligand_path.stem().string();\n\t\tcout << setw(8) << ++index << \"   \" << setw(16) << stem << \"   \" << flush;\n\n\t\t// Check if the current ligand has already been docked.\n\t\tsize_t num_confs = 0;\n\t\tdouble id_score = 0;\n\t\tdouble rf_score = 0;\n\t\tconst path output_ligand_path = out_path / input_ligand_path.filename();\n\t\tif (exists(output_ligand_path) && !equivalent(ligand_path, out_path) && !anna_test)\n\t\t{\n\t\t\t// Extract idock score and RF-Score from output file.\n\t\t\t// cout << \"Use previous dock\" << endl;\n\t\t\t// string line;\n\t\t\t// for (ifstream ifs(output_ligand_path); getline(ifs, line);)\n\t\t\t// {\n\t\t\t// \tconst string record = line.substr(0, 10);\n\t\t\t// \tif (record == \"MODEL     \")\n\t\t\t// \t{\n\t\t\t// \t\t++num_confs;\n\t\t\t// \t}\n\t\t\t// \telse if (num_confs == 1 && record == \"REMARK 921\")\n\t\t\t// \t{\n\t\t\t// \t\tid_score = stod(line.substr(55, 8));\n\t\t\t// \t}\n\t\t\t// \telse if (num_confs == 1 && record == \"REMARK 927\")\n\t\t\t// \t{\n\t\t\t// \t\trf_score = stod(line.substr(55, 8));\n\t\t\t// \t}\n\t\t\t// }\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Parse the ligand.\n\t\t\tarray<double, 3> origin;\n\t\t\tconst ligand lig(input_ligand_path, origin);\n\n\t\t\t// Find atom types that are present in the current ligand but not present in the grid maps.\n\t\t\tvector<size_t> xs;\n\t\t\tfor (size_t t = 0; t < sf.n; ++t)\n\t\t\t{\n\t\t\t\tif (lig.xs[t] && rec.maps[t].empty())\n\t\t\t\t{\n\t\t\t\t\trec.maps[t].resize(rec.num_probes_product);\n\t\t\t\t\txs.push_back(t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Create grid maps on the fly if necessary.\n\t\t\tif (xs.size())\n\t\t\t{\n\t\t\t\t// Precalculate p_offset.\n\t\t\t\trec.precalculate(xs);\n\n\t\t\t\t// Populate the grid map task container.\n\t\t\t\tcnt.init(rec.num_probes[2]);\n\t\t\t\tfor (size_t z = 0; z < rec.num_probes[2]; ++z)\n\t\t\t\t{\n\t\t\t\t\tio.post([&, z]()\n\t\t\t\t\t{\n\t\t\t\t\t\trec.populate(xs, z, sf);\n\t\t\t\t\t\tcnt.increment();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcnt.wait();\n\t\t\t}\n\n\t\t\tif (score_only)\n\t\t\t{\n\t\t\t\tcout << \"SCORE ONLY\" <<endl;\n\t\t\t\tif (anna_test){\n\t\t\t\t\tcout << \"ANNA TEST\" << endl;\n\t\t\t\t\tofstream testfile;\n\t\t\t\t\ttestfile.open(\"test_03.txt\");\n\n\t\t\t\t\t// Define constants.\n\t\t\t\t\tstatic const double pi = 3.1415926535897932; //!< Pi.\n\t\t\t\t\tstatic const size_t seed = 1641317389;\n\t\t\t\t\tconst size_t num_entities = 2 + lig.num_active_torsions; // Number of entities to mutate.\n\t\t\t\t\tconst double e_upper_bound = static_cast<double>(4 * lig.num_heavy_atoms); // A conformation will be droped if its free energy is not better than e_upper_bound.\n\t\t\t\t\tcout << \"the e_upper_bound\" << e_upper_bound << endl;\n\t\t\t\t\tmt19937_64 rng(seed);\n\t\t\t\t\tuniform_real_distribution<double> u01(0, 1);\n\t\t\t\t\tuniform_real_distribution<double> u11(-1, 1);\n\t\t\t\t\tuniform_real_distribution<double> upi(-pi, pi);\n\t\t\t\t\tuniform_real_distribution<double> ub0(rec.corner0[0], rec.corner1[0]);\n\t\t\t\t\tuniform_real_distribution<double> ub1(rec.corner0[1], rec.corner1[1]);\n\t\t\t\t\tuniform_real_distribution<double> ub2(rec.corner0[2], rec.corner1[2]);\n\t\t\t\t\tuniform_int_distribution<size_t> uen(0, num_entities - 1);\n\t\t\t\t\tnormal_distribution<double> n01(0, 1);\n\n\t\t\t\t\t// Generate an initial random conformation c0, and evaluate it.\n\t\t\t\t\tconformation c0(lig.num_active_torsions);\n\t\t\t\t\tdouble e0, f0;\n\t\t\t\t\tchange g0(lig.num_active_torsions);\n\t\t\t\t\tbool valid_conformation = false;\n\t\t\t\t\tfor (size_t i = 0; (i < 1000); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Randomize conformation c0.\n\t\t\t\t\t\tc0.position = array<double, 3>{{ub0(rng), ub1(rng), ub2(rng)}};\n\t\t\t\t\t\tfor (size_t i = 0; i < c0.position.size(); i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//cout << c0.position[i] << \" \";\n\t\t\t\t\t\t\ttestfile << c0.position[i] << \" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tc0.orientation = normalize(array<double, 4>{{n01(rng), n01(rng), n01(rng), n01(rng)}});\n\t\t\t\t\t\tfor (size_t i = 0; i < c0.orientation.size(); i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//cout << c0.orientation[i] << \" \";\n\t\t\t\t\t\t\ttestfile << c0.orientation[i] << \" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (size_t i = 0; i < lig.num_active_torsions; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tc0.torsions[i] = upi(rng);\n\t\t\t\t\t\t\t//cout << c0.torsions[i] << \" \";\n\t\t\t\t\t\t\ttestfile << c0.torsions[i] << \" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(lig.evaluate(c0, sf, rec, e_upper_bound, e0, f0, g0)){\n\t\t\t\t\t\t\t// Save gradient\n\t\t\t\t\t\t\ttestfile << g0[0] << \" \";\n\t\t\t\t\t\t\ttestfile << g0[1] << \" \";\n\t\t\t\t\t\t\ttestfile << g0[2] << \" \";\n\t\t\t\t\t\t\ttestfile << g0[3] << \" \";\n\t\t\t\t\t\t\ttestfile << g0[4] << \" \";\n\t\t\t\t\t\t\ttestfile << g0[5] << \" \";\n\n\t\t\t\t\t\t\t// Save the inter-molecular energy\n\t\t\t\t\t\t\ttestfile << f0 << \" \";\n\t\t\t\t\t\t\t// Save the intermolecular free energy \n\t\t\t\t\t\t\tcout << \"Energy 2: \" << e0 << endl;\n\t\t\t\t\t\t\t// Save the total free energy\n\t\t\t\t\t\t\ttestfile << e0 << endl;\n\n\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttestfile << 0 << endl;\n\t\t\t\t\t\t}\n\t\n\t\t\t\t\t}\n\t\t\t\t\ttestfile.close();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\tnum_confs = 1;\n\t\t\t\tconformation c0(lig.num_active_torsions);\n\t\t\t\tc0.position = origin;\n\t\t\t\tdouble e0, f0;\n\t\t\t\tchange g0(0);\n\t\t\t\tlig.evaluate(c0, sf, rec, -99, e0, f0, g0);\n\t\t\t\tauto r0 = lig.compose_result(e0, f0, c0);\n\t\t\t\tr0.e_nd = r0.f * lig.flexibility_penalty_factor;\n\t\t\t\tr0.rf = lig.calculate_rf_score(r0, rec, f);\n\t\t\t\tid_score = r0.e_nd;\n\t\t\t\trf_score = r0.rf;\n\t\t\t\tlig.write_models(output_ligand_path, {{ move(r0) }}, rec);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Run the Monte Carlo tasks.\n\t\t\t\tcnt.init(num_tasks);\n\t\t\t\tfor (size_t i = 0; i < num_tasks; ++i)\n\t\t\t\t{\n\t\t\t\t\tassert(result_containers[i].empty());\n\t\t\t\t\tconst size_t s = rng();\n\t\t\t\t\tio.post([&, i, s]()\n\t\t\t\t\t{\n\t\t\t\t\t\tlig.monte_carlo(result_containers[i], s, sf, rec);\n\t\t\t\t\t\tcnt.increment();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcnt.wait();\n\n\t\t\t\t// Merge results from all tasks into one single result container.\n\t\t\t\tassert(results.empty());\n\t\t\t\tconst double required_square_error = static_cast<double>(4 * lig.num_heavy_atoms); // Ligands with RMSD < 2.0 will be clustered into the same cluster.\n\t\t\t\tfor (auto& result_container : result_containers)\n\t\t\t\t{\n\t\t\t\t\tfor (auto& result : result_container)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult::push(results, move(result), required_square_error);\n\t\t\t\t\t}\n\t\t\t\t\tresult_container.clear();\n\t\t\t\t}\n\n\t\t\t\t// If conformations are found, output them.\n\t\t\t\tnum_confs = results.size();\n\t\t\t\tif (num_confs)\n\t\t\t\t{\n\t\t\t\t\t// Adjust free energy relative to the best conformation and flexibility.\n\t\t\t\t\tconst auto& best_result = results.front();\n\t\t\t\t\tconst double best_result_intra_e = best_result.e - best_result.f;\n\t\t\t\t\tfor (auto& result : results)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult.e_nd = (result.e - best_result_intra_e) * lig.flexibility_penalty_factor;\n\t\t\t\t\t\tresult.rf = lig.calculate_rf_score(result, rec, f);\n\t\t\t\t\t}\n\t\t\t\t\tid_score = best_result.e_nd;\n\t\t\t\t\trf_score = best_result.rf;\n\n\t\t\t\t\t// Write models to file.\n\t\t\t\t\tlig.write_models(output_ligand_path, results, rec);\n\n\t\t\t\t\t// Clear the results of the current ligand.\n\t\t\t\t\tresults.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If output file or conformations are found, output the idock score and RF-Score.\n\t\tcout << setw(6) << num_confs;\n\t\tlog << stem << ',' << num_confs;\n\t\tif (num_confs)\n\t\t{\n\t\t\tcout << \"   \" << setw(22) << id_score << \"   \" << setw(14) << rf_score;\n\t\t\tlog << ',' << id_score << ',' << rf_score;\n\t\t}\n\t\tcout << endl;\n\t\tlog << '\\n';\n\n\t\t// Output to the log file in csv format. The log file can be sorted using: head -1 log.csv && tail -n +2 log.csv | awk -F, '{ printf \"%s,%s\\n\", $2||0, $0 }' | sort -t, -k1nr -k3n | cut -d, -f2-\n\t}\n\n\t// Wait until the io service pool has finished all its tasks.\n\tio.wait();\n}\n", "meta": {"hexsha": "dd4ed93ad8d6e0fc99591cff2aba95ccbaaa5af6", "size": 15597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "annanguyen99/test_idock", "max_stars_repo_head_hexsha": "e032ad158705baba68780e1da430d364d36fa559", "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/main.cpp", "max_issues_repo_name": "annanguyen99/test_idock", "max_issues_repo_head_hexsha": "e032ad158705baba68780e1da430d364d36fa559", "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": "annanguyen99/test_idock", "max_forks_repo_head_hexsha": "e032ad158705baba68780e1da430d364d36fa559", "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.629707113, "max_line_length": 195, "alphanum_fraction": 0.6390331474, "num_tokens": 4493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.18352323714662977}}
{"text": "//\n// Created by Andrea on 28/07/2017.\n//\n\n#include \"Task3D.h\"\n\n#include <custom_conversions/Conversions.h>\n#include <vtkCubeSource.h>\n#include <boost/thread/thread.hpp>\n\nnamespace  ThreeDColors {\n    double Green_Arrow[3]{0.3176, 0.6431, 0.3215};\n    double Green[3]{0.0, 0.9, 0.03};\n    double Yellow[3]{1.0, 0.702, 0.0};\n\n}\nTask3D::Task3D()\n        :\n        SimTask(NULL,100) ,\n        time_last(ros::Time::now())\n{\n\n\n    InitBullet();\n\n    double density = 120000;\n    double friction = 0.5;\n    std::vector<int> first_path = {1, 3, 2, 0};\n    std::vector<int> second_path = {3, 1, 0, 2};\n    std::vector<int> third_path = {2, 1, 0, 3};\n    index.push_back(first_path);\n    index.push_back(second_path);\n    index.push_back(third_path);\n    target = std::rand() % 3;\n    task_state = TaskState::Idle;\n\n    // -------------------------------------------------------------------------\n    // Create static target objects\n\n    radii = new double[rings_number] {0.012, 0.01, 0.011, 0.014};\n\n    std::vector<double> _dim = {1};\n\n    rot.DoRotX(M_PI);\n    rot.DoRotZ(-M_PI/180*105);\n\n    KDL::Vector cam_position(0.118884, 0.27565, 0.14583);\n    KDL::Vector focal_point(-0.04443, -0.57915, -0.413638);\n    KDL::Vector direction = (focal_point-cam_position);\n    direction = direction/direction.Norm();\n\n    kine_dim = {0.002, 0.002};\n\n    for (int i = 0; i<rings_number; i++){\n\n        std::stringstream input_file_dir;\n        input_file_dir << MESH_DIRECTORY << std::string(\"3Dring\")\n                       << i+1 <<std::string(\".obj\");\n        std::string mesh_file_dir_str = input_file_dir.str();\n\n        KDL::Vector ring_pos;\n        ring_pos = cam_position +  ((double)i* 0.05 + 0.16 +\n                                    sin((double)i*M_PI/3)*(0.05/4))*direction;\n        KDL::Frame pose(rot,KDL::Vector(ring_pos.x(),\n                                        ring_pos.y(),\n                                        ring_pos.z()) );\n        ideal_position[i].x(pose.p[0]);\n        ideal_position[i].y(pose.p[1]);\n        ideal_position[i].z(pose.p[2]);\n\n        ring[i] = new SimObject(ObjectShape::MESH, ObjectType::DYNAMIC, _dim,\n                                pose, density, friction,\n                                mesh_file_dir_str, 0);\n\n        dynamicsWorld->addRigidBody(ring[i]->GetBody());\n        graphics_actors.push_back(ring[i]->GetActor());\n        ring[i]->GetActor()->GetProperty()->SetColor(0.8f, 0.8f, 0.8f);\n\n\n        const btVector3 btPivotA(0.f, 0.f, -float(0.025f+radii[i])*B_DIM_SCALE);\n        btVector3 btAxisA( 1.0f, 0.0f, 0.0f );\n        hinges[i] = new btHingeConstraint( *ring[i]->GetBody(), btPivotA, btAxisA );\n        hinges[i]->enableAngularMotor(true, 0 , 0.00015);\n        dynamicsWorld->addConstraint(hinges[i]);\n\n\n        // ---------------------------------------------------------------------\n        // hinge objects\n\n        std::stringstream input_file_dir_hinge;\n        input_file_dir_hinge << MESH_DIRECTORY << std::string(\"hinge\")\n                             <<std::string(\".obj\");\n        std::string mesh_file_dir_hinge_str = input_file_dir_hinge.str();\n\n        KDL::Frame pose2(rot,KDL::Vector(ring_pos.x(),\n                                        ring_pos.y(),\n                                        ring_pos.z() + 0.025 + radii[i]) );\n        hinge_cyl[i] = new SimObject(ObjectShape::MESH, ObjectType::DYNAMIC,\n                                     _dim, pose2, 0.0, friction,\n                                     mesh_file_dir_hinge_str, 0);\n\n        dynamicsWorld->addRigidBody(hinge_cyl[i]->GetBody());\n        hinge_cyl[i]->GetActor()->GetProperty()->SetColor(0.4, 0.4, 0.4);\n        graphics_actors.push_back(hinge_cyl[i]->GetActor());\n    }\n\n    // -------------------------------------------------------------------------\n    // Arrow for Idle\n\n    std::stringstream input_file_dir;\n    input_file_dir << MESH_DIRECTORY << std::string(\"arrow\")\n                   <<std::string(\".obj\");\n    std::string mesh_file_dir_str = input_file_dir.str();\n\n    rot.DoRotX(-M_PI/2);\n    rot.GetQuaternion(arrow_x, arrow_y, arrow_z, arrow_w);\n\n    arrow = new SimObject(ObjectShape::MESH, ObjectType::DYNAMIC, _dim,\n                          KDL::Frame(), 0.0, friction,\n                          mesh_file_dir_str, 0);\n\n    dynamicsWorld->addRigidBody(arrow->GetBody());\n    graphics_actors.push_back(arrow->GetActor());\n    arrow->GetActor()->GetProperty()->SetColor(ThreeDColors::Green_Arrow);\n    arrow->GetActor()->GetProperty()->SetOpacity(1);\n\n    // -------------------------------------------------------------------------\n    // Create kinematic pointer\n\n    friction = 0.1;\n\n    kine_dim = {0.005, 4*0.007};\n    kine_p=\n            new SimObject(ObjectShape::CYLINDER, ObjectType::KINEMATIC,\n                          kine_dim, KDL::Frame(), 0.0, friction,\n                          NULL, 0);\n    dynamicsWorld->addRigidBody(kine_p->GetBody());\n    kine_p->GetActor()->GetProperty()->SetColor(0.6314, 0.0, 0.0);\n    graphics_actors.push_back(kine_p->GetActor());\n\n\n    // Define a master manipulator\n    master = new Manipulator(nh, \"/sigma7/sigma0\", \"/pose\", \"/gripper_angle\");\n};\n\n//------------------------------------------------------------------------------\nvoid Task3D::StepWorld() {\n\n    //-----------------POINTER: update position on the upper plane\n\n    KDL::Frame tool_pose;\n\n    master->GetPoseWorld(tool_pose);\n\n    pointer_posit = tool_pose * KDL::Vector( -0.0, -0.0, -0.03+0.01);\n    KDL::Rotation _rot;\n    _rot.DoRotZ(M_PI/180*105);\n    double x, y, z, w;\n    _rot.GetQuaternion(x, y, z, w);\n    double pointer_pose[7] = {pointer_posit[0], pointer_posit[1], pointer_posit[2],\n                              x,y,z,w};\n    kine_p->SetKinematicPose(pointer_pose);\n\n    //--------------------------------\n    // step the world\n    StepPhysics();\n\n    if (task_state == TaskState::Idle){\n        // Manage the position of the arrow\n        ArrowManager();\n        axes_dist=0;\n    }\n    else{\n        // Find the tool coordinates in the target rf\n        vtkMatrix4x4* ring_rf = vtkMatrix4x4::New();\n        ring[index[target][path]]->GetActor()->GetMatrix(ring_rf);\n        double actual_posit[4] = {pointer_posit[0], pointer_posit[1],\n                                  pointer_posit[2], 1};\n        ring_rf->Invert();\n        ring_rf->MultiplyPoint(actual_posit, transf);\n\n        if (task_state == TaskState::Entry){\n            // Verify if the tool is crossing the target\n            CheckCrossing();\n        }\n        else if (task_state == TaskState::Exit){\n\n            ExitChecking();\n        }\n\n        TaskEvaluation();\n\n        // Compute the distance between the cylinder axis and the axis\n        // orthogonal to the ring and passing through its center\n        axes_dist=(float) sqrt(pow(transf[0], 2) + pow(transf[2], 2));\n\n\n        // Verify if the ring is touched\n        if (fabs(ring[index[target][path]]->GetActor()->GetCenter()[0] -\n                 ideal_position[index[target][path]].x()) >= 0.0005){\n            touch = 1;\n        }\n\n    }\n}\n\n\n//------------------------------------------------------------------------------\nvoid Task3D::ArrowManager() {\n\n    ring[index[target][path]]->GetActor()->GetProperty()->SetColor\n            (ThreeDColors::Yellow);\n\n    KDL::Vector shift(0.0, 0.0, -0.03 + 0.005*sin(var));\n    arrow_posit = rot*shift;\n\n    double* pose;\n    pose = new double[7]{arrow_posit[0] + ideal_position[index[target][path]].x(),\n                         arrow_posit[1] + ideal_position[index[target][path]].y(),\n                         arrow_posit[2] + ideal_position[index[target][path]].z(),\n                         arrow_x, arrow_y, arrow_z, arrow_w};\n    var = var + 0.05;\n\n    arrow->GetActor()->SetUserMatrix(PoseArrayToVTKMatrix(pose));\n\n    // Check if the arrow has been approached\n    double* arrow_position;\n    arrow_position = arrow->GetActor()->GetCenter();\n    KDL::Vector arrow_pos;\n    arrow_pos.x(arrow_position[0]);\n    arrow_pos.y(arrow_position[1]);\n    arrow_pos.z(arrow_position[2]);\n    distance = arrow_pos - pointer_posit;\n    double norm_distance = distance.Norm();\n    if (norm_distance <= threshold) {\n        task_state = TaskState::Entry;\n        begin = ros::Time::now();\n        arrow->GetActor()->GetProperty()->SetOpacity(0.0);\n        var = 0;\n    }\n}\n\n\n//------------------------------------------------------------------------------\nvoid Task3D::CheckCrossing() {\n\n    // Verify if the tool is crossing the target\n    if (transf[1] >= -kine_dim[1]/2){\n        cond=1;\n    }\n\n    // Verify if the tool is crossing the target\n    if (transf[1] >= 0 && transf[1] <= kine_dim[1]/2 &&\n        pow(transf[0], 2) + pow(transf[2], 2) <= pow\n                (radii[index[target][path]], 2)){\n\n        ring[index[target][path]]->GetActor()->GetProperty()->SetColor\n                (ThreeDColors::Green);\n        task_state = TaskState::Exit;\n        cond=0;\n    }\n\n}\n\n//------------------------------------------------------------------------------\nvoid Task3D::TaskEvaluation() {\n\n\n    // Populate the task state message\n    task_state_msg.task_name = \"3D Task\";\n    task_state_msg.task_state = (uint8_t)task_state;\n    task_state_msg.number_of_repetition = n_rep;\n\n    // ******* TO FINISH!!!!!!!!!! *******\n    //task_state_msg.error_condition=cond;\n    //task_state_msg.ring_touch=touch;\n    //************************************\n\n    task_state_msg.error_field_1 = axes_dist;\n\n    time = (ros::Time::now() - begin).toSec();\n    task_state_msg.time_stamp = time;\n}\n\n//------------------------------------------------------------------------------\nvoid Task3D::ExitChecking() {\n\n    if (transf[1] >= -kine_dim[1]/2) {\n        if (path == 3){\n            ring[index[target][path]]->GetActor()->GetProperty()->SetColor\n                    (ThreeDColors::Green);\n        }\n        else {\n            ring[index[target][path\n                               + 1]]->GetActor()->GetProperty()->SetColor\n                    (ThreeDColors::Yellow);\n            ring[index[target][path]]->GetActor()->GetProperty()->SetColor(ThreeDColors::Green);\n        }\n    }\n    if (transf[1] < -kine_dim[1]/2){\n        ring[index[target][path]]->GetActor()->GetProperty()->SetColor(1.0, 1.0, 1.0);\n        path = path + 1;\n        task_state = TaskState::Entry;\n        touch = 0;\n        if (path > 3){\n            target = std::rand() % 3;\n            path = 0;\n            task_state = TaskState::Idle;\n            n_rep=n_rep+(unsigned char)1;\n            arrow->GetActor()->GetProperty()->SetOpacity(1);\n        }\n    }\n}\n\n\ncustom_msgs::TaskState Task3D::GetTaskStateMsg() {\n    return task_state_msg;\n}\n\nvoid Task3D::ResetTask() {\n    ROS_INFO(\"Repetition completed. Resetting the task.\");\n\n}\n\nvoid Task3D::ResetCurrentAcquisition() {\n    ROS_INFO(\"Resetting current acquisition.\");\n\n}\n\n\nvoid Task3D::HapticsThread() {\n\n    ros::Publisher pub_desired[2];\n\n    ros::NodeHandlePtr node = boost::make_shared<ros::NodeHandle>();\n    pub_desired[0] = node->advertise<geometry_msgs::PoseStamped>\n            (\"/PSM1/tool_pose_desired\", 10);\n//    if(bimanual)\n//        pub_desired[1] = node->advertise<geometry_msgs::PoseStamped>\n//                (\"/PSM2/tool_pose_desired\", 10);\n\n    ros::Rate loop_rate(200);\n\n    while (ros::ok())\n    {\n\n//        CalculatedDesiredToolPose();\n\n//        // publish desired poses\n//        for (int n_arm = 0; n_arm < 1+ int(bimanual); ++n_arm) {\n//\n//            // convert to pose message\n//            geometry_msgs::PoseStamped pose_msg;\n//            tf::poseKDLToMsg(tool_desired_pose_kdl[n_arm], pose_msg.pose);\n//            // fill the header\n//            pose_msg.header.frame_id = \"/task_space\";\n//            pose_msg.header.stamp = ros::Time::now();\n//            // publish\n//            pub_desired[n_arm].publish(pose_msg);\n//        }\n\n        ros::spinOnce();\n        loop_rate.sleep();\n        boost::this_thread::interruption_point();\n    }\n}\n\n\n\n\n\nvoid Task3D::InitBullet() {\n\n    ///-----initialization_start-----\n\n    ///collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration.\n    collisionConfiguration = new btDefaultCollisionConfiguration();\n\n    ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)\n    dispatcher = new btCollisionDispatcher(collisionConfiguration);\n\n    ///btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep.\n    overlappingPairCache = new btDbvtBroadphase();\n\n    ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)\n    solver = new btSequentialImpulseConstraintSolver;\n\n    dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,\n                                                overlappingPairCache, solver,\n                                                collisionConfiguration);\n\n    dynamicsWorld->setGravity(btVector3(0, 0, -10));\n\n\n}\n\n\nvoid Task3D::StepPhysics() {\n    ///-----stepsimulation_start-----\n\n    ///-----stepsimulation_start-----\n    double time_step = (ros::Time::now() - time_last).toSec();\n\n    // simulation seems more realistic when time_step is halved right now!\n    dynamicsWorld->stepSimulation(btScalar(time_step), 5);\n    time_last = ros::Time::now();\n//    //print positions of all objects\n//    for (int j = dynamics_world->getNumCollisionObjects() - 1; j >= 0; j--)\n//    {\n//        btCollisionObject* obj = dynamics_world->getCollisionObjectArray()[j];\n//        btRigidBody* body_ = btRigidBody::upcast(obj);\n//        btTransform trans;\n//        if (body_ && body_->getMotionState())\n//        {\n//            body_->getMotionState()->getWorldTransform(trans);\n//        }\n//        else\n//        {\n//            trans = obj->getWorldTransform();\n//        }\n//\n//            heights[j] = trans.getOrigin().z();\n//        heights2[j] = graphics_actors[j]->GetMatrix()->Element[2][3];\n//    }\n\n}\n\n\nTask3D::~Task3D() {\n\n    ROS_INFO(\"Destructing Bullet task: %d\",\n             dynamicsWorld->getNumCollisionObjects());\n    //remove the rigidbodies from the dynamics world and delete them\n    for (int i = dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)\n    {\n        btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[i];\n        btRigidBody* body = btRigidBody::upcast(obj);\n        if (body && body->getMotionState())\n        {\n            delete body->getMotionState();\n        }\n        dynamicsWorld->removeCollisionObject(obj);\n        delete obj;\n    }\n\n    for (int j = 0; j < rings_number; ++j) {\n\n        delete hinges[j];\n    }\n//    for (int j = 0; j < NUM_BULLET_SPHERES; ++j) {\n//        SimObject* sphere = spheres[j];\n//        spheres[j] = 0;\n//        delete sphere;\n//    }\n//    //delete collision shapes\n////    for (int j = 0; j < collisionShapes.size(); j++)\n//    for (int j = 0; j < 2; j++) // because we use the same collision shape\n//        // for all spheres\n//    {\n//        btCollisionShape* shape = collisionShapes[j];\n//        collisionShapes[j] = 0;\n//        delete shape;\n//    }\n\n    //delete dynamics world\n    delete dynamicsWorld;\n\n    //delete solver\n    delete solver;\n\n    //delete broadphase\n    delete overlappingPairCache;\n\n    //delete dispatcher\n    delete dispatcher;\n\n    delete collisionConfiguration;\n\n    //next line is optional: it will be cleared by the destructor when the array goes out of scope\n//    collisionShapes.clear();\n}\n\n\n", "meta": {"hexsha": "034ae568f4f0910d3f33025fb2f399b78e31a148", "size": 15522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/deprecated/Task3D.cpp", "max_stars_repo_name": "neemoh/ART", "max_stars_repo_head_hexsha": "3f990b9d3c4b58558adf97866faf4eea553ba71b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-06-29T19:08:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T07:13:00.000Z", "max_issues_repo_path": "src/deprecated/Task3D.cpp", "max_issues_repo_name": "liuxia-zju/ATAR", "max_issues_repo_head_hexsha": "3f990b9d3c4b58558adf97866faf4eea553ba71b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T23:44:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T23:44:55.000Z", "max_forks_repo_path": "src/deprecated/Task3D.cpp", "max_forks_repo_name": "liuxia-zju/ATAR", "max_forks_repo_head_hexsha": "3f990b9d3c4b58558adf97866faf4eea553ba71b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T14:26:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T01:57:14.000Z", "avg_line_length": 32.0702479339, "max_line_length": 134, "alphanum_fraction": 0.5530215178, "num_tokens": 3889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18344462060986297}}
{"text": "#include \"settings_utils.h\"\n\n#include <boost/any.hpp>\n#include <boost/program_options.hpp>\n#include <boost/spirit/include/qi.hpp>\n\nnamespace carl::settings {\n\n// Adapted from https://stackoverflow.com/questions/45071699/\nvoid validate(boost::any& v, const std::vector<std::string>& values, carl::settings::duration* /*unused*/, int /*unused*/) {\n\tnamespace pov = boost::program_options::validators;\n\tnamespace qi = boost::spirit::qi;\n\n\tstd::string s(pov::get_single_string(values));\n\n\tlong value = 0;\n\tstd::chrono::nanoseconds factor;\n\tqi::symbols<char, std::chrono::nanoseconds> unit;\n\tunit.add\n\t\t(\"ns\", std::chrono::nanoseconds(1))\n\t\t(\"\u00b5s\", std::chrono::microseconds(1))\n\t\t(\"us\", std::chrono::microseconds(1))\n\t\t(\"ms\", std::chrono::milliseconds(1))\n\t\t(\"s\", std::chrono::seconds(1))\n\t\t(\"m\", std::chrono::minutes(1))\n\t\t(\"h\", std::chrono::hours(1))\n\t;\n\tif (qi::parse(s.begin(), s.end(), qi::long_ >> unit >> qi::eoi, value, factor)) {\n\t\tv = duration(value * factor);\n\t} else {\n\t\tthrow boost::program_options::invalid_option_value(s);\n\t}\n}\n\nvoid validate(boost::any& v, const std::vector<std::string>& values, carl::settings::binary_quantity* /*unused*/, int /*unused*/) {\n\tnamespace pov = boost::program_options::validators;\n\tnamespace qi = boost::spirit::qi;\n\n\tstd::string s(pov::get_single_string(values));\n\n\tstd::size_t value = 0;\n\tstd::size_t factor = 1;\n\tqi::symbols<char, std::size_t> unit;\n\tunit.add\n\t\t(\"K\", static_cast<std::size_t>(1) << 10U)\n\t\t(\"Ki\", static_cast<std::size_t>(1) << 10U)\n\t\t(\"M\", static_cast<std::size_t>(1) << 20U)\n\t\t(\"Mi\", static_cast<std::size_t>(1) << 20U)\n\t\t(\"G\", static_cast<std::size_t>(1) << 30U)\n\t\t(\"Gi\", static_cast<std::size_t>(1) << 30U)\n\t\t(\"T\", static_cast<std::size_t>(1) << 40U)\n\t\t(\"Ti\", static_cast<std::size_t>(1) << 40U)\n\t\t(\"P\", static_cast<std::size_t>(1) << 50U)\n\t\t(\"Pi\", static_cast<std::size_t>(1) << 50U)\n\t\t(\"E\", static_cast<std::size_t>(1) << 60U)\n\t\t(\"Ei\", static_cast<std::size_t>(1) << 60U)\n\t;\n\tif (qi::parse(s.begin(), s.end(), qi::ulong_long >> -unit >> qi::eoi, value, factor)) {\n\t\tv = binary_quantity(value * factor);\n\t} else {\n\t\tthrow boost::program_options::invalid_option_value(s);\n\t}\n}\n\nvoid validate(boost::any& v, const std::vector<std::string>& values, carl::settings::metric_quantity* /*unused*/, int /*unused*/) {\n\tnamespace pov = boost::program_options::validators;\n\tnamespace qi = boost::spirit::qi;\n\n\tstd::string s(pov::get_single_string(values));\n\n\tstd::size_t value = 0;\n\tstd::size_t factor = 1;\n\tqi::symbols<char, std::size_t> unit;\n\tunit.add\n\t\t(\"K\", 1000)\n\t\t(\"M\", 1000000)\n\t\t(\"G\", 1000000000)\n\t\t(\"T\", 1000000000000)\n\t\t(\"P\", 1000000000000000)\n\t\t(\"E\", 1000000000000000000)\n\t;\n\tif (qi::parse(s.begin(), s.end(), qi::ulong_long >> -unit >> qi::eoi, value, factor)) {\n\t\tv = metric_quantity(value * factor);\n\t} else {\n\t\tthrow boost::program_options::invalid_option_value(s);\n\t}\n}\n\n}", "meta": {"hexsha": "be75833a366ad1657b60197e12f2e364b540b6b0", "size": 2845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/carl-settings/settings_utils.cpp", "max_stars_repo_name": "sjunges/carl", "max_stars_repo_head_hexsha": "5013c31c035990d9912a6265944e7d4add4c378b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-05-19T12:17:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T17:53:00.000Z", "max_issues_repo_path": "src/carl-settings/settings_utils.cpp", "max_issues_repo_name": "sjunges/carl", "max_issues_repo_head_hexsha": "5013c31c035990d9912a6265944e7d4add4c378b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2016-10-26T12:47:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:19:38.000Z", "max_forks_repo_path": "src/carl-settings/settings_utils.cpp", "max_forks_repo_name": "sjunges/carl", "max_forks_repo_head_hexsha": "5013c31c035990d9912a6265944e7d4add4c378b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2015-05-27T07:35:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T17:53:08.000Z", "avg_line_length": 31.9662921348, "max_line_length": 131, "alphanum_fraction": 0.6513181019, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1834446206098629}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <boost/functional/hash.hpp>  // IWYU pragma: keep\n#include <cstddef>\n#include <memory>\n#include <pup.h>\n#include <string>\n#include <utility>\n\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"DataStructures/DataBox/Tag.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/CoordinateMaps/Affine.hpp\"\n#include \"Domain/CoordinateMaps/CoordinateMap.hpp\"\n#include \"Domain/CoordinateMaps/CoordinateMap.tpp\"\n#include \"Domain/CoordinateMaps/ProductMaps.hpp\"\n#include \"Domain/CoordinateMaps/ProductMaps.tpp\"\n#include \"Domain/CoordinateMaps/TimeDependent/CubicScale.hpp\"\n#include \"Domain/ElementMap.hpp\"\n#include \"Domain/FunctionsOfTime/FunctionOfTime.hpp\"\n#include \"Domain/FunctionsOfTime/PiecewisePolynomial.hpp\"\n#include \"Domain/FunctionsOfTime/RegisterDerivedWithCharm.hpp\"\n#include \"Domain/LogicalCoordinates.hpp\"\n#include \"Domain/SizeOfElement.hpp\"  // IWYU pragma: keep\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/LimiterActions.hpp\"  // IWYU pragma: keep\n#include \"Evolution/DiscontinuousGalerkin/Limiters/Minmod.tpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodType.hpp\"\n#include \"Framework/ActionTesting.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"NumericalAlgorithms/Spectral/Spectral.hpp\"\n#include \"Parallel/PhaseDependentActionList.hpp\"  // IWYU pragma: keep\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n// IWYU pragma: no_include \"Evolution/DiscontinuousGalerkin/Limiters/Minmod.hpp\"\n\n// IWYU pragma: no_forward_declare ActionTesting::InitializeDataBox\n\nnamespace {\nstruct TemporalId : db::SimpleTag {\n  using type = int;\n};\n\nstruct Var : db::SimpleTag {\n  using type = Scalar<DataVector>;\n};\n\ntemplate <size_t Dim>\nstruct System {\n  static constexpr const size_t volume_dim = Dim;\n  using variables_tag = Tags::Variables<tmpl::list<Var>>;\n};\n\nstruct LimiterTag : db::SimpleTag {\n  using type = Limiters::Minmod<2, tmpl::list<Var>>;\n};\n\ntemplate <size_t Dim, typename Metavariables>\nstruct component {\n  using metavariables = Metavariables;\n  using chare_type = ActionTesting::MockArrayChare;\n  using array_index = ElementId<Dim>;\n  using const_global_cache_tags = tmpl::list<LimiterTag>;\n  using simple_tags = db::AddSimpleTags<\n      TemporalId, domain::Tags::Mesh<Dim>, domain::Tags::Element<Dim>,\n      domain::Tags::ElementMap<Dim, Frame::Grid>,\n      domain::CoordinateMaps::Tags::CoordinateMap<2, Frame::Grid,\n                                                  Frame::Inertial>,\n      ::Tags::Time, domain::Tags::FunctionsOfTime, Var>;\n  using compute_tags =\n      db::AddComputeTags<::domain::Tags::LogicalCoordinates<Dim>,\n                         ::domain::Tags::MappedCoordinates<\n                             ::domain::Tags::ElementMap<Dim, Frame::Grid>,\n                             ::domain::Tags::Coordinates<Dim, Frame::Logical>>,\n                         domain::Tags::SizeOfElementCompute<Dim>>;\n  using phase_dependent_action_list = tmpl::list<\n      Parallel::PhaseActions<\n          typename Metavariables::Phase, Metavariables::Phase::Initialization,\n          tmpl::list<\n              ActionTesting::InitializeDataBox<simple_tags, compute_tags>>>,\n      Parallel::PhaseActions<\n          typename Metavariables::Phase, Metavariables::Phase::Testing,\n          tmpl::list<Limiters::Actions::SendData<Metavariables>,\n                     Limiters::Actions::Limit<Metavariables>>>>;\n};\n\ntemplate <size_t Dim>\nstruct Metavariables {\n  using component_list = tmpl::list<component<Dim, Metavariables>>;\n  using limiter = LimiterTag;\n  using system = System<Dim>;\n  using temporal_id = TemporalId;\n  static constexpr bool local_time_stepping = false;\n  enum class Phase { Initialization, Testing, Exit };\n};\n}  // namespace\n\n// This test checks that the Minmod limiter's interfaces and type aliases\n// succesfully integrate with the limiter actions. It does this by compiling\n// together the Minmod limiter and the actions, then making calls to the\n// SendData and the Limit actions. No checks are performed here that the limiter\n// and/or actions produce correct output: that is done in other tests.\nSPECTRE_TEST_CASE(\"Unit.Evolution.DG.Limiters.LimiterActions.Minmod\",\n                  \"[Unit][NumericalAlgorithms][Actions]\") {\n  using metavariables = Metavariables<2>;\n  using my_component = component<2, metavariables>;\n\n  const Mesh<2> mesh{3, Spectral::Basis::Legendre,\n                     Spectral::Quadrature::GaussLobatto};\n  const ElementId<2> self_id(1, {{{2, 0}, {1, 0}}});\n  const Element<2> element(self_id, {});\n\n  using Affine = domain::CoordinateMaps::Affine;\n  using Affine2D = domain::CoordinateMaps::ProductOf2Maps<Affine, Affine>;\n  using CubicScaleMap = domain::CoordinateMaps::TimeDependent::CubicScale<2>;\n  PUPable_reg(\n      SINGLE_ARG(domain::CoordinateMap<Frame::Logical, Frame::Grid, Affine2D>));\n  PUPable_reg(SINGLE_ARG(\n      domain::CoordinateMap<Frame::Grid, Frame::Inertial, CubicScaleMap>));\n  domain::FunctionsOfTime::register_derived_with_charm();\n\n  const Affine xi_map{-1., 1., 3., 7.};\n  const Affine eta_map{-1., 1., 7., 3.};\n  auto logical_to_grid_map = ElementMap<2, Frame::Grid>(\n      self_id, domain::make_coordinate_map_base<Frame::Logical, Frame::Grid>(\n                   Affine2D(xi_map, eta_map)));\n  std::unique_ptr<domain::CoordinateMapBase<Frame::Grid, Frame::Inertial, 2>>\n      grid_to_inertial_map =\n          domain::make_coordinate_map_base<Frame::Grid, Frame::Inertial>(\n              CubicScaleMap{10.0, \"Expansion\", \"Expansion\"});\n\n  const double initial_time = 0.0;\n  const double expiration_time = 2.5;\n  std::unordered_map<std::string,\n                     std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>\n      functions_of_time{};\n  functions_of_time.insert(std::make_pair(\n      \"Expansion\",\n      std::make_unique<domain::FunctionsOfTime::PiecewisePolynomial<2>>(\n          initial_time, std::array<DataVector, 3>{{{0.0}, {1.0}, {0.0}}},\n          expiration_time)));\n\n  auto var = Scalar<DataVector>(mesh.number_of_grid_points(), 1234.);\n\n  const double tvb_constant = 0.0;\n  ActionTesting::MockRuntimeSystem<metavariables> runner{\n      Limiters::Minmod<2, tmpl::list<Var>>(Limiters::MinmodType::LambdaPi1,\n                                           tvb_constant)};\n  ActionTesting::emplace_component_and_initialize<my_component>(\n      &runner, self_id,\n      {0, mesh, element, std::move(logical_to_grid_map),\n       std::move(grid_to_inertial_map), 1.0, std::move(functions_of_time),\n       std::move(var)});\n  ActionTesting::set_phase(make_not_null(&runner),\n                           metavariables::Phase::Testing);\n\n  // SendData\n  runner.next_action<my_component>(self_id);\n  CHECK(runner.is_ready<my_component>(self_id));\n  // Limit\n  runner.next_action<my_component>(self_id);\n}\n", "meta": {"hexsha": "0fa43f68acc1c59fe2def3b84fd78237768c65f4", "size": 7079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Evolution/DiscontinuousGalerkin/Limiters/Test_LimiterActionsWithMinmod.cpp", "max_stars_repo_name": "Ambrou/spectre", "max_stars_repo_head_hexsha": "a819ebbcca607d8af9683db3683bea14bf4ac23c", "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/Unit/Evolution/DiscontinuousGalerkin/Limiters/Test_LimiterActionsWithMinmod.cpp", "max_issues_repo_name": "Ambrou/spectre", "max_issues_repo_head_hexsha": "a819ebbcca607d8af9683db3683bea14bf4ac23c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T18:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:30:39.000Z", "max_forks_repo_path": "tests/Unit/Evolution/DiscontinuousGalerkin/Limiters/Test_LimiterActionsWithMinmod.cpp", "max_forks_repo_name": "isaaclegred/spectre", "max_forks_repo_head_hexsha": "5765da85dad680cad992daccd479376c67458a8c", "max_forks_repo_licenses": ["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.3976608187, "max_line_length": 92, "alphanum_fraction": 0.711682441, "num_tokens": 1787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.18344461886209312}}
{"text": "// Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n//\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted under the terms of the BSD License. See\n// LICENSE file in the root of the Project.\n\n#ifndef NIX_CHECKS_H\n#define NIX_CHECKS_H\n\n#include <nix/util/util.hpp>\n#include <nix/valid/helper.hpp>\n\n#include <nix/base/IDimensions.hpp>\n\n#include <nix/types.hpp>\n\n#include <boost/optional.hpp>\n#include <boost/any.hpp>\n\nnamespace nix {\nnamespace valid {\n\n    /**\n     * @brief Check if later given not greater than initally defined value.\n     *\n     * One Check struct that checks whether the given value is not greater\n     * than the initially given other value, both of which have to be\n     * convertible to double.\n     */\n    struct notGreater {\n        const double value;\n\n        template<typename T>\n        notGreater(T value) : value(static_cast<double>(value)) {}\n\n        template<typename T2>\n        bool operator()(const T2 &val) const {\n            return !(static_cast<double>(val) > value);\n        }\n    };\n\n    /**\n     * @brief Check if later given greater than initally defined value.\n     *\n     * One Check struct that checks whether the given value is greater than\n     * the initially given other value, both of which have to be\n     * convertible to double.\n     */\n    struct isGreater {\n        const double value;\n\n        template<typename T>\n        isGreater(T value) : value(static_cast<double>(value)) {}\n\n        template<typename T2>\n        bool operator()(const T2 &val) const {\n            return static_cast<double>(val) > value;\n        }\n    };\n\n    /**\n     * @brief Check if later given not smaller than initally defined value.\n     *\n     * One Check struct that checks whether the given value is not smaller\n     * than the initially given other value, both of which have to be\n     * convertible to double.\n     */\n    struct notSmaller {\n        const double value;\n\n        template<typename T>\n        notSmaller(T value) : value(static_cast<double>(value)) {}\n\n        template<typename T2>\n        bool operator()(const T2 &val) const {\n            return !(static_cast<double>(val) < value);\n        }\n    };\n\n    /**\n     * @brief Check if later given smaller than initally defined value.\n     *\n     * One Check struct that checks whether the given value is smaller than\n     * the initially given other value, both of which have to be\n     * convertible to double.\n     */\n    struct isSmaller {\n        const double value;\n\n        template<typename T>\n        isSmaller(T value) : value(static_cast<double>(value)) {}\n\n        template<typename T2>\n        bool operator()(const T2 &val) const {\n            return static_cast<double>(val) < value;\n        }\n    };\n\n    /**\n     * @brief Check for un-equality of initally defined and later given value.\n     *\n     * One Check struct that checks whether the given value is not equal\n     * to the initially given other value.\n     */\n    template<typename T>\n    struct notEqual {\n        const T value;\n\n        notEqual(T value) : value(value) {}\n\n        template<typename T2>\n        bool operator()(const T2 &val) const {\n            return value != val;\n        }\n    };\n\n    /**\n     * @brief Check for equality of initally defined and later given value.\n     *\n     * One Check struct that checks whether the given value is equal to\n     * the initially given other value.\n     */\n    template<typename T>\n    struct isEqual {\n        const T value;\n\n        isEqual(T value) : value(value) {}\n\n        template<typename T2>\n        bool operator()(const T2 &val) const {\n            return value == val;\n        }\n    };\n    // needed because: for bizarre reasons bool converts to int when compared to boost::optional\n    template<>\n    struct isEqual<bool> {\n        const bool value;\n\n        isEqual(bool value) : value(value) {}\n\n        template<typename T2>\n        bool operator()(const T2 &val) const {\n            return value ? !!val : !val;\n        }\n    };\n\n    /**\n     * @brief Check if given value casts to boolean true\n     *\n     * One Check struct that checks whether the given value casts to true\n     * or to false.\n     * T can be: boost::optional, boost::none, nix-entity\n     * and any basic type.\n     */\n    struct notFalse {\n        // WARNING: enum will convert via int, which means 0 = false !\n        template<typename T>\n        bool operator()(const T &val) const {\n            return !!val;\n        }\n    };\n\n    /**\n     * @brief Check if given value casts to boolean false\n     *\n     * One Check struct that checks whether the given value casts to false\n     * or to true.\n     * T can be: boost::optional, boost::none, nix-entity\n     * and any basic type.\n     */\n    struct isFalse {\n        // WARNING: enum will convert via int, which means 0 = false !\n        template<typename T>\n        bool operator()(const T &val) const {\n            return !val;\n        }\n    };\n\n    /**\n     * @brief Check if given class/struct returns \"empty() == false\"\n     *\n     * One Check struct that checks whether the given value is not empty\n     * or is empty.\n     * T can be: any STL container.\n     */\n    struct notEmpty {\n        template<typename T>\n        bool operator()(const T &val) const {\n            return !(val.empty());\n        }\n    };\n\n    /**\n     * @brief Check if given class/struct returns \"empty() == true\"\n     *\n     * One Check struct that checks whether the given value is empty or\n     * not.\n     * T can be: any STL container.\n     */\n    struct isEmpty {\n        template<typename T>\n        bool operator()(const T &val) const {\n            return val.empty();\n        }\n    };\n\n    /**\n     * @brief Check if given class represents valid SI unit string(s)\n     *\n     * Base struct to be inherited by the {@link isValidUnit}, {@link\n     * isAtomicUnit}, {@link isCompoundUnit}. Not viable on its own!\n     */\n    struct isUnit {\n        typedef std::function<bool(std::string)> TPRED;\n\n        virtual bool operator()(const std::string &u) const = 0;\n\n        bool operator()(const boost::optional<std::string> &u) const {\n            // note: relying on short-curcuiting here\n            return u && (*this)(*u);\n        }\n\n        bool operator()(const std::vector<std::string> &u, TPRED obj) const {\n            // if test succeeds find_if_not will not find anything & return it == end\n            return std::find_if_not(u.begin(), u.end(), obj) == u.end();\n        }\n\n        virtual ~isUnit() { }\n    };\n\n    /**\n     * @brief Check if given class represents valid SI unit string(s)\n     *\n     * One Check struct that checks whether the given string(s) represent(s)\n     * a valid atomic or compound SI unit.\n     * Parameter can be of type boost optional (containing nothing or\n     * string) or of type string or a vector of strings.\n     */\n    struct isValidUnit : public isUnit {\n        bool operator()(const std::string &u) const {\n            return (util::isSIUnit(u) || util::isCompoundSIUnit(u));\n        }\n        bool operator()(const boost::optional<std::string> &u) const {\n            return isUnit::operator()(u);\n        }\n        bool operator()(const std::vector<std::string> &u) const {\n            return isUnit::operator()(u, *this);\n        }\n    };\n\n    /**\n     * @brief Check if given class represents valid atomic SI unit string(s)\n     *\n     * One Check struct that checks whether the given string(s) represent(s)\n     * a valid atomic SI unit.\n     * Parameter can be of type boost optional (containing nothing or\n     * string) or of type string or a vector of strings.\n     */\n    struct isAtomicUnit : public isUnit {\n        bool operator()(const std::string &u) const {\n            return util::isSIUnit(u);\n        }\n        bool operator()(const boost::optional<std::string> &u) const {\n            return isUnit::operator()(u);\n        }\n        bool operator()(const std::vector<std::string> &u) const {\n            return isUnit::operator()(u, *this);\n        }\n    };\n\n    /**\n     * @brief Check if given class represents valid compound SI unit string(s)\n     *\n     * One Check struct that checks whether the given string(s) represent(s)\n     * a valid compound SI unit.\n     * Parameter can be of type boost optional (containing nothing or\n     * string) or of type string or a vector of strings.\n     */\n    struct isCompoundUnit : public isUnit {\n        bool operator()(const std::string &u) const {\n            return util::isCompoundSIUnit(u);\n        }\n        bool operator()(const boost::optional<std::string> &u) const {\n            return isUnit::operator()(u);\n        }\n        bool operator()(const std::vector<std::string> &u) const {\n            return isUnit::operator()(u, *this);\n        }\n    };\n\n    /**\n     * @brief Check if given value can be regarded as being set\n     *\n     * One Check struct that checks whether the given value can be\n     * considered set, by applying {@link notFalse} and {@link notEmpty}\n     * checks. Value thus is set if: STL cotnainer not empty OR\n     * bool is true OR boost optional is set OR number is not 0.\n     * Parameter can be of above types or even boost none_t.\n     * NOTE: use this if you don't know wheter a type has and \"empty\"\n     * method.\n     */\n    struct isSet {\n        template<typename T>\n        bool operator()(const T &val) const {\n            typedef typename std::conditional<hasEmpty<T>::value, notEmpty, notFalse>::type subCheck;\n            return subCheck(val);\n        }\n    };\n\n    /**\n     * @brief Check if given container is sorted using std::is_sorted\n     *\n     * One Check struct that checks whether the given container is sorted\n     * according to std::is_sorted. Thus supports types that are\n     * supported by std::is_sorted.\n     */\n    struct isSorted {\n        template<typename T>\n        bool operator()(const T &container) const {\n            return std::is_sorted(container.begin(), container.end());\n        }\n    };\n\n    /**\n     * @brief Check if given DataArray has given dimensionality\n     *\n     * One Check struct that checks whether the given DataArray entity\n     * has a dimensionality of the given uint value by getting its'\n     * NDSize class via the \"dataExtent\" method and checking its' size\n     * via \"size\" the method.\n     */\n    struct NIXAPI dimEquals {\n        size_t value;\n\n        dimEquals(const size_t &value) : value(value) {}\n\n        bool operator()(const DataArray &array) const;\n    };\n\n    /**\n     * @brief Checks if units of the passed DataArray dimensions matches those\n     * defined in the Tag\n     *\n     * Struct to check whether the units defined in the Tag match with the units\n     * specified in the referenced DataArray dimensions. The check tests for\n     * scalability of the tag-provided units and the ones of the DataArrays.\n     * \n     */\n    struct NIXAPI tagUnitsMatchRefsUnits {\n        std::vector<std::string> units;\n\n        tagUnitsMatchRefsUnits(const std::vector<std::string> &units) : units(units) {}\n\n        bool operator()(const std::vector<DataArray> &references) const;\n    };\n\n    /**\n     * @brief Check if range dimension specifics ticks match data\n     *\n     * One Check struct that checks whether the dimensions of type\n     * \"Range\" in the given dimensions vector have ticks that match\n     * the given DataArray's data: number of ticks == number of entries\n     * along the corresponding dimension in the data.\n     */\n    struct NIXAPI dimTicksMatchData {\n        const DataArray &data;\n\n        dimTicksMatchData(const DataArray &data) : data(data) {}\n\n        bool operator()(const std::vector<Dimension> &dims) const;\n    };\n\n    /**\n     * @brief Check if set dimension specifics labels match data\n     *\n     * One Check struct that checks whether the dimensions of type\n     * \"Set\" in the given dimensions vector have labels that match\n     * the given DataArray's data: number of labels == number of entries\n     * along the corresponding dimension in the data.\n     */\n    struct NIXAPI dimLabelsMatchData {\n        const DataArray &data;\n\n        dimLabelsMatchData(const DataArray &data) : data(data) {}\n\n        bool operator()(const std::vector<Dimension> &dims) const;\n    };\n\n    /**\n     * @brief Check if DataFrame dimension specifics ticks match data\n     *\n     * Struct for checking whether the number of rows in the dimensions of type\n     * \"DataFrame\" in the given dimensions vector matches the given DataArray's\n     * data extent in the respective dimension: number of rows in DataFrame == number of\n     * entries along the corresponding dimension in the data.\n     */\n    struct NIXAPI dimDataFrameTicksMatchData {\n        const DataArray &data;\n\n        dimDataFrameTicksMatchData(const DataArray &data) : data(data) {}\n\n        bool operator()(const std::vector<Dimension> &dims) const;\n    };\n\n} // namespace valid\n} // namespace nix\n\n#endif // NIX_CHECKS_H\n", "meta": {"hexsha": "527491230eca167e749f6f0005014c7e007a5861", "size": 12989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nix/valid/checks.hpp", "max_stars_repo_name": "mpsonntag/nix", "max_stars_repo_head_hexsha": "3e2b874973355f51fcfbaee31eeeb5d9eccab943", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T01:04:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T14:26:04.000Z", "max_issues_repo_path": "include/nix/valid/checks.hpp", "max_issues_repo_name": "mpsonntag/nix", "max_issues_repo_head_hexsha": "3e2b874973355f51fcfbaee31eeeb5d9eccab943", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 262.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T13:24:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-02T13:45:31.000Z", "max_forks_repo_path": "include/nix/valid/checks.hpp", "max_forks_repo_name": "mpsonntag/nix", "max_forks_repo_head_hexsha": "3e2b874973355f51fcfbaee31eeeb5d9eccab943", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-03-27T16:41:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T06:47:59.000Z", "avg_line_length": 31.603406326, "max_line_length": 101, "alphanum_fraction": 0.61228732, "num_tokens": 2950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.1834446170878355}}
{"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_CORE_FUNCTIONS_SIMD_OUTER_FOLD_HPP_INCLUDED\n#define NT2_CORE_FUNCTIONS_SIMD_OUTER_FOLD_HPP_INCLUDED\n\n#include <nt2/core/functions/outer_fold.hpp>\n#include <boost/simd/sdk/simd/meta/is_vectorizable.hpp>\n#include <boost/fusion/include/pop_back.hpp>\n#include <nt2/sdk/config/cache.hpp>\n\n#ifndef BOOST_SIMD_NO_SIMD\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  // Generates outer_fold\n  //============================================================================\n  NT2_FUNCTOR_IMPLEMENTATION_IF( nt2::tag::outer_fold_, boost::simd::tag::simd_, (A0)(S0)(T0)(N0)(A1)(A2)(A3)(A4)\n                               , (boost::simd::meta::is_vectorizable<typename A0::value_type, BOOST_SIMD_DEFAULT_EXTENSION>)\n                               , ((expr_< table_< unspecified_<A0>, S0 >\n                                        , T0\n                                        , N0\n                                        >\n                                 ))\n                                 ((ast_< A1, nt2::container::domain>))\n                                 (unspecified_<A2>)\n                                 (unspecified_<A3>)\n                                 (unspecified_<A4>)\n                               )\n  {\n    typedef void                                                              result_type;\n    typedef typename A0::value_type                                           value_type;\n    typedef typename A1::extent_type                                          extent_type;\n    typedef boost::simd::native<value_type,BOOST_SIMD_DEFAULT_EXTENSION>      target_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0& out, A1& in, A2 const& neutral, A3 const& bop, A4 const&) const\n    {\n      extent_type ext = in.extent();\n      static const std::size_t N = boost::simd::meta::cardinal_of<target_type>::value;\n      std::size_t ibound  = boost::fusion::at_c<0>(ext);\n      std::size_t mbound =  boost::fusion::at_c<1>(ext);\n      std::size_t obound =  boost::fusion::at_c<2>(ext);\n      std::size_t id;\n\n      std::size_t cache_line_size = nt2::config::top_cache_line_size(2); // in byte\n      std::size_t nb_vec = cache_line_size/(sizeof(value_type)*N);\n      std::size_t cache_bound = (nb_vec)*N;\n      std::size_t bound  =  ((ibound)/cache_bound) * cache_bound;\n\n      for(std::size_t o = 0, o_ = 0; o < obound; ++o, o_+=ibound)\n      {\n        for(std::size_t i = 0; i < bound; i+=cache_bound)\n        {\n          id = i+o_;\n          for (std::size_t k = 0, k_ = id; k < nb_vec; ++k, k_+=N)\n            nt2::run(out, k_, neutral(nt2::meta::as_<target_type>()));\n\n          for(std::size_t m = 0, m_ = 0; m < mbound; ++m, m_+=ibound)\n          {\n            for (std::size_t k = 0, k_ = id; k < nb_vec; ++k, k_+=N)\n              nt2::run( out, k_\n                      , bop( nt2::run(out, k_, meta::as_<target_type>())\n                           , nt2::run(in, k_+m_, meta::as_<target_type>())\n                           )\n                      );\n          }\n        }\n\n        // scalar part\n        for(std::size_t i = bound; i < ibound; ++i)\n        {\n          id = i+o_;\n          nt2::run(out, id, neutral(nt2::meta::as_<value_type>()));\n          for(std::size_t m = 0, m_ = 0; m < mbound; ++m, m_+=ibound)\n          {\n            nt2::run( out, id\n                    , bop( nt2::run(out, id,meta::as_<value_type>())\n                         , nt2::run(in, id+m_,meta::as_<value_type>())\n                         )\n                    );\n          }\n        }\n      }\n    }\n  };\n\n  } }\n\n#endif\n#endif\n", "meta": {"hexsha": "e5c80be3aca7c4a13ae49027cdb143fcd5d54d10", "size": 4107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/reduction/include/nt2/core/functions/simd/outer_fold.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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/reduction/include/nt2/core/functions/simd/outer_fold.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/reduction/include/nt2/core/functions/simd/outer_fold.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": 42.78125, "max_line_length": 124, "alphanum_fraction": 0.4536157779, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.1833231618894886}}
{"text": "// Copyright (c) 2015-2018, CNRS\n// Authors: Justin Carpentier <jcarpent@laas.fr>\n\n#ifndef __multicontact_api_scenario_contact_phase_humanoid_hpp__\n#define __multicontact_api_scenario_contact_phase_humanoid_hpp__\n\n#include \"multicontact-api/scenario/contact-phase.hpp\"\n#include \"multicontact-api/scenario/contact-sequence.hpp\"\n#include \"multicontact-api/serialization/spatial.hpp\"\n#include \"multicontact-api/serialization/aligned-vector.hpp\"\n\n#include \"multicontact-api/trajectories/cubic-hermite-spline.hpp\"\n\n#include <pinocchio/container/aligned-vector.hpp>\n#include <pinocchio/spatial/force.hpp>\n\n#include <boost/serialization/vector.hpp>\n\n#include <vector>\n#include <Eigen/StdVector>\n\nnamespace multicontact_api\n{\n  namespace scenario\n  {\n\n    template<typename _Scalar>\n    struct ContactPhaseHumanoidTpl\n    : public ContactPhaseTpl<_Scalar,4>\n    , public serialization::Serializable< ContactPhaseHumanoidTpl<_Scalar> >\n    {\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n      typedef ContactPhaseTpl<_Scalar,4> Base;\n      typedef _Scalar Scalar;\n      typedef pinocchio::ForceTpl<Scalar> Force;\n      enum {\n        state_dim = 9,\n        control_dim = 6,\n        com_position_id = 0,\n        com_velocity_id = 3,\n        com_acceleration_id = 3,\n        am_id = 6,\n        am_variations_id = 6,\n        linear_control_id = 0,\n        angular_control_id = 3\n      };\n\n      typedef Eigen::Matrix<Scalar,state_dim,1> StateVector;\n      typedef Eigen::Matrix<Scalar,control_dim,1> ControlVector;\n      typedef Eigen::Matrix<Scalar,3,1> Vector3;\n      typedef Eigen::Map<Vector3> MapVector3;\n\n      typedef Eigen::Map<StateVector> MapStateVector;\n      typedef Eigen::Map<ControlVector> MapControlVector;\n\n      typedef pinocchio::container::aligned_vector<StateVector> VectorStateVector;\n\n      //      typedef pinocchio::container::aligned_vector<Force> VectorForce;\n      typedef std::vector<Force, Eigen::aligned_allocator<Force> > VectorForce;\n      typedef pinocchio::container::aligned_vector<ControlVector> VectorControlVector;\n      typedef std::vector<Scalar> VectorScalar;\n      typedef VectorScalar TimeVector;\n      typedef Eigen::Matrix<_Scalar,Eigen::Dynamic,1> ConfigurationVector;\n      typedef pinocchio::container::aligned_vector<ConfigurationVector> VectorConfigurationVector;\n\n      typedef boost::array<VectorForce,4> ForceVectorArray;\n\n      typedef trajectories::CubicHermiteSplineTpl<Scalar,3> CubicHermiteSpline3;\n      typedef trajectories::CubicHermiteSplineTpl<Scalar,24> CubicHermiteSpline24;\n      \n      using Base::dim;\n      using Base::operator==;\n      using typename Base::ContactPatch;\n      using Base::m_contact_patches;\n\n      /// \\brief default constructor\n      ContactPhaseHumanoidTpl()\n      : Base()\n      , RF_patch(m_contact_patches[0])\n      , LF_patch(m_contact_patches[1])\n      , RH_patch(m_contact_patches[2])\n      , LH_patch(m_contact_patches[3])\n      , m_init_state()\n      , m_final_state()\n      , m_state_trajectory(0)\n      , m_dot_state_trajectory(0)\n      , m_control_trajectory(0)\n      , m_time_trajectory(0)\n      , m_objective_trajectory(0)\n      , m_raw_control_trajectory(0)\n      , m_angular_momentum_ref(CubicHermiteSpline3::Constant(CubicHermiteSpline3::VectorD::Zero()))\n      , m_com_ref(CubicHermiteSpline3::Constant(CubicHermiteSpline3::VectorD::Zero()))\n      , m_vcom_ref(CubicHermiteSpline3::Constant(CubicHermiteSpline3::VectorD::Zero()))\n      , m_forces_ref(CubicHermiteSpline24::Constant(CubicHermiteSpline24::VectorD::Zero()))\n      , m_reference_configurations(0)\n      {}\n\n      /// \\brief copy constructor\n      ContactPhaseHumanoidTpl(const ContactPhaseHumanoidTpl & other)\n      : Base(other)\n      , RF_patch(m_contact_patches[0])\n      , LF_patch(m_contact_patches[1])\n      , RH_patch(m_contact_patches[2])\n      , LH_patch(m_contact_patches[3])\n      , m_init_state(other.m_init_state)\n      , m_final_state(other.m_final_state)\n      , m_state_trajectory(other.m_state_trajectory)\n      , m_dot_state_trajectory(other.m_dot_state_trajectory)\n      , m_control_trajectory(other.m_control_trajectory)\n      , m_time_trajectory(other.m_time_trajectory)\n      , m_objective_trajectory(other.m_objective_trajectory)\n      , m_contact_forces_trajectories(other.m_contact_forces_trajectories)\n      , m_raw_control_trajectory(other.m_raw_control_trajectory)\n      , m_angular_momentum_ref(other.m_angular_momentum_ref)\n      , m_com_ref(other.m_com_ref)\n      , m_vcom_ref(other.m_vcom_ref)\n      , m_forces_ref(other.m_forces_ref)\n      , m_reference_configurations(other.m_reference_configurations)\n      {}\n\n      /// \\brief copy operator\n//      template<typename S2>\n      ContactPhaseHumanoidTpl & operator=(const ContactPhaseHumanoidTpl & other)\n      {\n        Base::operator=(other);\n        m_init_state = other.m_init_state;\n        m_final_state = other.m_final_state;\n        m_state_trajectory = other.m_state_trajectory;\n        m_dot_state_trajectory = other.m_dot_state_trajectory;\n        m_control_trajectory = other.m_control_trajectory;\n        m_time_trajectory = other.m_time_trajectory;\n        m_objective_trajectory = other.m_objective_trajectory;\n        m_contact_forces_trajectories = other.m_contact_forces_trajectories;\n        m_raw_control_trajectory = other.m_raw_control_trajectory;\n        m_angular_momentum_ref = other.m_angular_momentum_ref;\n        m_com_ref = other.m_com_ref;\n        m_vcom_ref = other.m_vcom_ref;\n        m_forces_ref = other.m_forces_ref;\n        m_reference_configurations = other.m_reference_configurations;\n        return *this;\n      }\n\n      ContactPatch & RF_patch;\n      ContactPatch & LF_patch;\n      ContactPatch & RH_patch;\n      ContactPatch & LH_patch;\n\n      StateVector m_init_state;\n      StateVector m_final_state;\n\n      VectorStateVector m_state_trajectory;\n      VectorStateVector m_dot_state_trajectory;\n      VectorControlVector m_control_trajectory;\n      TimeVector m_time_trajectory;\n      VectorScalar m_objective_trajectory;\n      VectorConfigurationVector m_reference_configurations;\n      ForceVectorArray m_contact_forces_trajectories;\n      VectorConfigurationVector m_raw_control_trajectory;\n      CubicHermiteSpline3 m_angular_momentum_ref;\n      CubicHermiteSpline3 m_com_ref;\n      CubicHermiteSpline3 m_vcom_ref;\n      CubicHermiteSpline24 m_forces_ref;\n\n    private:\n\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      {\n        ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Base);\n        ar & boost::serialization::make_nvp(\"init_state\",m_init_state);\n        ar & boost::serialization::make_nvp(\"final_state\",m_final_state);\n        ar & boost::serialization::make_nvp(\"state_trajectory\",m_state_trajectory);\n        ar & boost::serialization::make_nvp(\"dot_state_trajectory\",m_dot_state_trajectory);\n        ar & boost::serialization::make_nvp(\"control_trajectory\",m_control_trajectory);\n        ar & boost::serialization::make_nvp(\"time_trajectory\",m_time_trajectory);\n        ar & boost::serialization::make_nvp(\"objective_trajectory\",m_objective_trajectory);\n\n        size_t reference_configurations_size = m_reference_configurations.size();\n        ar & boost::serialization::make_nvp(\"reference_configurations_size\",reference_configurations_size);\n        for(typename VectorConfigurationVector::const_iterator it = m_reference_configurations.begin();\n            it != m_reference_configurations.end(); ++it)\n          ar & boost::serialization::make_nvp(\"reference_configuration\",*it);\n\n        for(typename ForceVectorArray::const_iterator it = m_contact_forces_trajectories.begin();\n            it != m_contact_forces_trajectories.end(); ++it)\n          ar & boost::serialization::make_nvp(\"contact_force_trajectory\",*it);\n\n//        const typename VectorConfigurationVector::vector_base & m_raw_control_trajectory_ =\n//        static_cast<const typename VectorConfigurationVector::vector_base&> (m_raw_control_trajectory);\n        ar & boost::serialization::make_nvp(\"raw_control\",m_raw_control_trajectory);\n        ar & boost::serialization::make_nvp(\"angular_momentum_ref\",m_angular_momentum_ref);\n        ar & boost::serialization::make_nvp(\"com_ref\",m_com_ref);\n        ar & boost::serialization::make_nvp(\"vcom_ref\",m_vcom_ref);\n        ar & boost::serialization::make_nvp(\"forces_ref\",m_forces_ref);        \n      }\n\n      template<class Archive>\n      void load(Archive & ar, const unsigned int /*version*/)\n      {\n        ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(Base);\n        ar >> boost::serialization::make_nvp(\"init_state\",m_init_state);\n        ar >> boost::serialization::make_nvp(\"final_state\",m_final_state);\n        ar >> boost::serialization::make_nvp(\"state_trajectory\",m_state_trajectory);\n        ar >> boost::serialization::make_nvp(\"dot_state_trajectory\",m_dot_state_trajectory);\n        ar >> boost::serialization::make_nvp(\"control_trajectory\",m_control_trajectory);\n        ar >> boost::serialization::make_nvp(\"time_trajectory\",m_time_trajectory);\n        ar >> boost::serialization::make_nvp(\"objective_trajectory\",m_objective_trajectory);\n\n        size_t reference_configurations_size = 0;\n        ar >> boost::serialization::make_nvp(\"reference_configurations_size\",reference_configurations_size);\n        m_reference_configurations.resize(reference_configurations_size);\n        for(typename VectorConfigurationVector::iterator it = m_reference_configurations.begin();\n            it != m_reference_configurations.end(); ++it)\n          ar >> boost::serialization::make_nvp(\"reference_configuration\",*it);\n\n        for(typename ForceVectorArray::iterator it = m_contact_forces_trajectories.begin();\n            it != m_contact_forces_trajectories.end(); ++it)\n          ar >> boost::serialization::make_nvp(\"contact_force_trajectory\",*it);\n\n//        typename VectorConfigurationVector::vector_base & m_raw_control_trajectory_ =\n//        static_cast<typename VectorConfigurationVector::vector_base&> (m_raw_control_trajectory);\n        ar >> boost::serialization::make_nvp(\"raw_control\",m_raw_control_trajectory);\n        ar >> boost::serialization::make_nvp(\"angular_momentum_ref\",m_angular_momentum_ref);\n        ar >> boost::serialization::make_nvp(\"com_ref\",m_com_ref);\n        ar >> boost::serialization::make_nvp(\"vcom_ref\",m_vcom_ref);\n        ar >> boost::serialization::make_nvp(\"forces_ref\",m_forces_ref);\n      }\n\n      BOOST_SERIALIZATION_SPLIT_MEMBER()\n\n    };\n  }\n}\n\n#endif // ifndef __multicontact_api_scenario_contact_phase_humanoid_hpp__\n", "meta": {"hexsha": "f7efbfdadec63b8453b513428398b54b325c24a9", "size": 10621, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/multicontact-api/scenario/contact-phase-humanoid.hpp", "max_stars_repo_name": "pFernbach/multicontact-api", "max_stars_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-17T09:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T09:19:05.000Z", "max_issues_repo_path": "include/multicontact-api/scenario/contact-phase-humanoid.hpp", "max_issues_repo_name": "pFernbach/multicontact-api", "max_issues_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "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/multicontact-api/scenario/contact-phase-humanoid.hpp", "max_forks_repo_name": "pFernbach/multicontact-api", "max_forks_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "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": 44.4393305439, "max_line_length": 108, "alphanum_fraction": 0.7268618774, "num_tokens": 2426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1833231598559455}}
{"text": "\n#include <upo_rrt_planners/ros/ValidityChecker3.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Core>\n#include <ros/console.h>\n\nusing namespace std;\n\nupo_RRT_ros::ValidityChecker3::ValidityChecker3(tf::TransformListener* tf, float resol, int width, int height, unsigned int dimensions, int distType) : StateChecker()\n{\n\n\tcapture_ = new Capture();\n\n\tcm_resolution_ = resol; //m/cell\n\tcm_width_ = width * 2.0;\t//m\n\tcm_height_ = height * 2.0;\t//m\n \n\tcm_width_pixs_ = cm_width_/cm_resolution_;\n\tcm_height_pixs_ = cm_height_/cm_resolution_;\n\n\t//The robot position (center) from the upper-right corner\n\tcm_origin_.clear();\n\tcm_origin_.push_back(cm_width_/2.0);  //x\n\tcm_origin_.push_back(cm_height_/2.0); //y  //negative earlier\n\n\tcostmap_.clear();\n\tcostmap_.assign((cm_width_pixs_*cm_height_pixs_), 1.0);\n\n\n\ttf_ = tf;\n\tdimensions_ = dimensions;\n\tdistanceType_ = distType;\n\ttime_ = ros::Time::now();\n\n\tsetup();\n}\n\n\n/*upo_RRT_ros::ValidityChecker3::ValidityChecker3(tf::TransformListener* tf, unsigned int dimensions, int distType) : StateChecker()\n{\n\tcapture_ = new Capture();\n\n\n\ttf_ = tf;\n\tdimensions_ = dimensions;\n\tdistanceType_ = distType;\n\ttime_ = ros::Time::now();\n\n\t//Build a default costmap\n\tresolution_ = 0.05; \t//m/cell\n\twidth_ = 100;\t\t\t//cells\n \theight_ = 100;\t\t\t//cells\n\torigin_.clear();\n\torigin_.push_back(2.5); //m\n\torigin_.push_back(2.5); //m\n\torigin_.push_back(0.0); //rad\n    costmap_mutex_.lock();\n\tcostmap_.clear();\n\tfor(unsigned int i=0; i<(width_*height_); i++)\n\t\tcostmap_.push_back((int)0);\n\tcostmap_mutex_.unlock();\n\n\tsetup();\n}*/\n\n\nupo_RRT_ros::ValidityChecker3::~ValidityChecker3() {\n\t\n\tdelete capture_;\n}\n\n\nvoid upo_RRT_ros::ValidityChecker3::setup()\n{\n\tros::NodeHandle nh;\n\t\n\n\tros::NodeHandle n(\"~/Validity_checker\");\n\tstring pc_topic;\n\tn.param<string>(\"pc_topic\", pc_topic, std::string(\"/scan360/point_cloud3\")); \n\tprintf(\"ValidityChecker3. pc_topic: %s\\n\", pc_topic.c_str());\n\tint pc_type;\n\tn.param<int>(\"pc_type\", pc_type, 2); //1->PointCloud, 2->PointCloud2\n\tprintf(\"ValidityChecker3. pc_type: %i\\n\", pc_type);\n\n \tn.param<bool>(\"project_onto_map\", project_onto_map_, false);\n\n\tdouble thres;\n\tn.param<double>(\"path_threshold\", thres, 0.0);\n\tpath_threshold_ = (float)thres;\n\n\tn.param<double>(\"robot_radius\", insc_radius_robot_, 0.30);\n\tprintf(\"ValidityChecker3. Robot Radius: %.2f\\n\", insc_radius_robot_);\n\n\tgoal_sub_ = n.subscribe(\"/rrt_goal\", 1, &ValidityChecker3::goalCallback, this);\n\t\n\tsub_people_ = n.subscribe(\"/people/navigation\", 1, &ValidityChecker3::peopleCallback, this); \n\n \tif(pc_type == 1) \t//pointCloud\n\t\tsub_pc_ = n.subscribe(pc_topic, 1, &ValidityChecker3::pcCallback, this);\n\telse   \t\t\t\t//pointCloud2\n\t\tsub_pc_ = n.subscribe(pc_topic, 1, &ValidityChecker3::pc2Callback, this);\n\n\t//Network prediction service\n  \tcnn_client_ = nh.serviceClient<path_prediction::PathPrediction>(\"path_prediction\");\n\n\tcostmap_pub_ = nh.advertise<nav_msgs::OccupancyGrid>(\"prediction_rewardmap\", 1);\n\n\tif(project_onto_map_)\n\t\tsetupStaticMap(nh);\n\telse\n\t\tsetupNoMapProjection();\n\n}\n\n\nvoid upo_RRT_ros::ValidityChecker3::setupStaticMap(ros::NodeHandle nh)\n{\n\n\tpeople_paint_area_ = 25;\n\t\n\tros::ServiceClient map_client = nh.serviceClient<nav_msgs::GetMap>(\"/static_map\");\n\twhile (! ros::service::waitForService(\"/static_map\",1)){\n\t\tROS_INFO(\"Waiting for map service\");\n\t}\n\n\tnav_msgs::GetMap srv;\n\tmap_client.call(srv);\n\tROS_INFO_STREAM(srv.response.map.info);\n\tmap_image_ = cv::Mat(srv.response.map.info.height, srv.response.map.info.width,CV_8UC1, cv::Scalar(0));\n\tmap_metadata_ =srv.response.map.info;\n\tmap_resolution_ = (double) map_metadata_.resolution;\n\tmap_origin_.push_back(map_metadata_.origin.position.x);\n\tmap_origin_.push_back(map_metadata_.origin.position.y);\n\tmap_origin_.push_back(tf::getYaw(map_metadata_.origin.orientation));\n\tuint8_t *myData = map_image_.data;\n\tfor (int i=0;i<srv.response.map.data.size();i++){\n\t\tif (srv.response.map.data.at(i)==100  || srv.response.map.data.at(i)==-1 ){\n\t\t}\n\t\telse {\n\t\t\tmap_image_.data[i] = 255;\n\t\t}\n\t}\n\n\tdt_mutex_.lock();\n\tdistance_transform_ = cv::Mat(map_image_.rows,map_image_.cols,CV_32FC1);\n\tcv::distanceTransform(map_image_,distance_transform_,CV_DIST_L1,3);\n\tdt_mutex_.unlock();\n}\n\n\nvoid upo_RRT_ros::ValidityChecker3::setupNoMapProjection()\n{\n\tpeople_paint_area_ = 25;\n\t\n\tmap_image_ = cv::Mat(cm_width_pixs_, cm_height_pixs_, CV_8UC1, cv::Scalar(255));\n\n\tmap_metadata_.resolution = cm_resolution_;\n\tmap_metadata_.width = cm_width_pixs_;   //Cells\n\tmap_metadata_.height = cm_height_pixs_; //Cells\n\tgeometry_msgs::Pose orig;\n\torig.position.x = cm_origin_[0];\n\torig.position.y = cm_origin_[1];\n\torig.position.z = 0.0;\n\torig.orientation = tf::createQuaternionMsgFromYaw(cm_origin_[2]);\n\tmap_metadata_.origin = orig; //m\n\n\tdt_mutex_.lock();\n\tdistance_transform_ = cv::Mat(map_image_.rows,map_image_.cols,CV_32FC1);\n\t//cv::distanceTransform(map_image_,distance_transform_,CV_DIST_L1,3);\n\tdt_mutex_.unlock();\n \n}\n\n\n\n\n\n//Update map with point cloud data\nvoid upo_RRT_ros::ValidityChecker3::updateDistTransform(){\n\t\n\tsensor_msgs::PointCloud temp_pt_cloud;\n\tpc_mutex_.lock();  \n\tsensor_msgs::PointCloud2 lcloud = laser_cloud_;\n\tpc_mutex_.unlock();\n\t\n\tif(lcloud.data.size() <= 0) {\n\t\tROS_WARN(\"No cloud updated\");\n\t\treturn;\n\t}\n\t\n\tbool done = sensor_msgs::convertPointCloud2ToPointCloud(lcloud, temp_pt_cloud);\n\tif(!done) \n\t\tROS_ERROR(\"\\n\\nUpdateDistTransform. convertPointCloud2toPoingCloud!!!!!\\n\");\n\t\n\t//Add the laser readings (pointcloud) to the map\n\tdt_mutex_.lock();\n\tcv::Mat map_copy = map_image_.clone();\n\tdt_mutex_.unlock();\n\tfor (int i =0;i<temp_pt_cloud.points.size();i++){\n\t\tvector<int> pix;\n\t\tif(project_onto_map_)\n\t\t\tpix = worldToMap(&(temp_pt_cloud.points[i]),&map_metadata_);\n\t\telse\n\t\t\tpix = BaseLinkWorldToImg(&(temp_pt_cloud.points[i]));\n\n\t\tif(pix[0] >= 0.0 && pix[0] < map_metadata_.width && pix[1] >= 0.0 && pix[1] < map_metadata_.height) \n\t\t\tmap_copy.at<unsigned char>(pix[1],pix[0]) = 0;\t\n\t\t//else\n\t\t\t//ROS_WARN(\"\\n\\nNAV FEATURES. UPDATEDT. pixel out of range!\\n\");\n\t}\n\t\n\t//Remove the people detected from the map\n\t/*people_mutex_.lock();\n\tstd::vector<upo_msgs::PersonPoseUPO> per = people_;\n\tpeople_mutex_.unlock();\n\tfor (int i=0; i<per.size(); i++){\n\t\tgeometry_msgs::Point32 temp_point;\n\t\ttemp_point.x = per[i].position.x;\n\t\ttemp_point.y = per[i].position.y;\n\t\tvector<int> pix;\n\t\tif(project_onto_map_)\n\t\t\tpix = worldToMap(&temp_point,&map_metadata_);\n\t\telse\n\t\t\tpix = BaseLinkWorldToImg(&temp_point);\n\n\t\t\n\t\tif (pix[0] >= 0.0 && pix[0] < map_metadata_.width && pix[1] >= 0.0 && pix[1] < map_metadata_.height)\n\t\t{\n\t\t\tfor (int j = -floor(people_paint_area_/2);j<ceil(people_paint_area_/2);j++){\n\t\t\t\tfor (int k = -floor(people_paint_area_/2);k<ceil(people_paint_area_/2);k++){\n\t\t\t\t\tif (pix[1]+k>=0 && pix[0]+j>=0){\n\t\t\t\t\t\tmap_copy.at<unsigned char>(pix[1]+k,pix[0]+j) =255;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}*/\n\t\n\tcv::Mat dt;\n\ttry{\n\t\tcv::distanceTransform(map_copy, dt, CV_DIST_L1, 3);\n\t} catch(...){\n\t\tROS_ERROR(\"\\n\\nValidityChecker3. UpdateDistTrans. cv::distanceTransform!!!!!\\n\");\n\t} \n\n\tdt_mutex_.lock();\n\tdistance_transform_ = dt.clone();\n\tdt_mutex_.unlock(); \n\t\n\t//gettimeofday(&stop, NULL);\n\t//printf(\"took %lu\\n\", stop.tv_usec - start.tv_usec);\n\timwrite(ros::package::getPath(\"upo_rrt_planners\").append(\"/test_write.jpg\"), map_copy);\n}\n\n\n\n//People callback\nvoid upo_RRT_ros::ValidityChecker3::peopleCallback(const upo_msgs::PersonPoseArrayUPO::ConstPtr& msg) \n{\n\tROS_INFO_ONCE(\"People received!!\");\n\tpeople_mutex_.lock();\n\tpeople_ = msg->personPoses;\n\t/*if(people_.size() > 0) {\n\t\tpeople_frame_id_ = msg->header.frame_id;\n\t}*/\n\tpeople_mutex_.unlock();\n\t\n}\n\n\n\n//Point_cloud2 callback\nvoid upo_RRT_ros::ValidityChecker3::pc2Callback(const sensor_msgs::PointCloud2::ConstPtr& pc_in){\n\t\n\tsetObstacles(*pc_in);\n}\n\n\n//Point_cloud callback\nvoid upo_RRT_ros::ValidityChecker3::pcCallback(const sensor_msgs::PointCloud::ConstPtr& pc_in){\n\t\n\tsensor_msgs::PointCloud2 pc2;\n\tbool ok = sensor_msgs::convertPointCloudToPointCloud2(*pc_in, pc2);\n\tif(!ok) {\n\t\tROS_WARN(\"NavFeatures. Error transforming pointCloud to pointCloud2\");\n\t}\n\t\n\tsetObstacles(pc2);\n\t\n}\n\n\n\n//Goal callback\nvoid upo_RRT_ros::ValidityChecker3::goalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n\tROS_INFO_ONCE(\"Goal received!!\");\n\tsetGoal(*msg);\n}\n\n\n\nvoid upo_RRT_ros::ValidityChecker3::setObstacles(sensor_msgs::PointCloud2 obs)\n{\n\tROS_INFO_ONCE(\"Obstacles received!\\n\");\n\tsensor_msgs::PointCloud2 lcloud;\n\tobs.header.stamp = ros::Time();\n\ttry{  \n\t\tif(project_onto_map_) {\n\t\t\tif(!pcl_ros::transformPointCloud(\"/map\", obs, lcloud, *tf_))\n\t\t\t\tROS_WARN(\"TransformPointCloud failed!!!!!\");\n\t\t} else {\n\t\t\tif(!pcl_ros::transformPointCloud(\"/base_link\", obs, lcloud, *tf_))\n\t\t\t\tROS_WARN(\"TransformPointCloud failed!!!!!\");\n\t\t}\t\t\t\n\n\t} catch (tf::TransformException ex){\n\t\tROS_WARN(\"NAV FEATURES. pcCallback. TransformException: %s\", ex.what());\n\t}\n\t\n\tpc_mutex_.lock();\n\tlaser_cloud_ = lcloud;\n\tpc_mutex_.unlock();\n}\n\n\n\n\n//Publish the path planning prediction into a ros costmap for visualization\nvoid upo_RRT_ros::ValidityChecker3::publish_costmap_ros(ros::Time t)\n{\n\t//Get the robot coordinates in odom frame\n\ttf::StampedTransform transform;\n\ttry{\n\t\ttf_->waitForTransform(\"/odom\", \"/base_link\", ros::Time(0), ros::Duration(1.0));\n\t\ttf_->lookupTransform(\"/odom\", \"/base_link\",  ros::Time(0), transform); //t\n\t}\n\tcatch (tf::TransformException ex){\n\t\tROS_ERROR(\"Publish_feature_costmap. TF exception: %s\",ex.what());\n\t}\n\t  \n\tnav_msgs::OccupancyGrid cmap;\n\tcmap.header.frame_id = \"odom\"; //\"base_link\";\n\tcmap.header.stamp = ros::Time::now(); //t;\n\t//time map_load_time. The time at which the map was loaded\n\tcmap.info.map_load_time = cmap.header.stamp; //t;\n\t//float32 resolution. The map resolution [m/cell]\n\tcmap.info.resolution = cm_resolution_;  //0.25 m/cell\n\t//uint32 width. Map width [cells]\n\tcmap.info.width = cm_height_pixs_; //x\n\t//uint32 height. Map height [cells]\n\tcmap.info.height = cm_width_pixs_; //y\n\t//geometry_msgs/Pose origin. The origin of the map [m, m, rad].  This is the real-world pose of the\n\t// cell (0,0) in the map.\n\tgeometry_msgs::Pose p;\n\tp.position.x = transform.getOrigin().x()-(cm_height_/2.0); //x\n\tp.position.y = transform.getOrigin().y()-(cm_width_/2.0);  //y (substraction initially)\n\tp.position.z = 0.0;\n\tp.orientation = tf::createQuaternionMsgFromYaw(0.0); //robot_odom_h\n\tcmap.info.origin = p;\n\t//int8[] cmap.data. The map data, in row-major order, starting with (0,0).  Occupancy\n\t// probabilities are in the range [0,100].  Unknown is -1.\n\tstd::vector<signed char> data; // size =(cmap.info.width*cmap.info.height)\n\tdouble cost = 0.0;\n\t//for(int i=0; i<cmap.info.height; i++)\n\tfor(int i=(cmap.info.height-1); i>0; i--) \n\t{\n\t\tfor(unsigned int j=0; j<cmap.info.width; j++)\n\t\t{\n\t\t\tfloat reward = costmap_[i*cm_width_pixs_ + j]>1.0?1.0:costmap_[i*cm_width_pixs_ + j];\n\t\t\t//cost = (1 - reward);\t\t\t\t\t\t\n\t\t\t//Transform cost into the scale[0,100]  \n\t\t\tdata.push_back((int)round(reward*100.0)); \n\t\t}\n\t}\n\tcmap.data = data;\n\tcostmap_pub_.publish(cmap);\n}\n\n\n\n\n\n\n\nbool upo_RRT_ros::ValidityChecker3::predictionService(vector<int> input, int rows, int cols)\n{\n\tpath_prediction::PathPrediction srv;\n  \tsrv.request.input = input;\n  \tsrv.request.input_rows = rows;\n\tsrv.request.input_cols = cols;\n  \tif (cnn_client_.call(srv))\n  \t{\n    \tROS_INFO(\"Service path prediction called!\");\n\t\tcostmap_mutex_.lock();\n\t\tcostmap_.clear();\n\t\tcostmap_ = srv.response.prediction;\n\t\tcm_width_pixs_ = srv.response.pred_cols;\n\t\tcm_height_pixs_ = srv.response.pred_rows;\n\t\tcm_width_ = cm_width_pixs_ * cm_resolution_;\n\t\tcm_height_ = cm_height_pixs_ * cm_resolution_;\n\t\tcostmap_mutex_.unlock();\n\n\n\t\t/*printf(\"Prediction received:\\n\");\n\t\tprintf(\"Vector size: %u\\n\", (unsigned int)costmap_.size());\n\t\tfor(unsigned int i=0; i<cm_height_pixs_; i++)\n\t\t{\n\t\t\tfor(unsigned int j=0; j<cm_width_pixs_; j++)\n\t\t\t\tprintf(\"%.2f \", costmap_[i*cm_width_pixs_ + j]);\n\t\t\tprintf(\"\\n\");\n\t\t}*/\n\n\n\t\treturn true;\t\t\n  \t}\n  \telse\n  \t{\n    \tROS_ERROR(\"Failed to call service path_prediction\");\n    \treturn false;\n  \t}\n\n}\n\n\n\n//Update the navigation scene and get the path planning prediction\nvoid upo_RRT_ros::ValidityChecker3::preplanning_computations()\n{\n\tstruct timeval t_ini1, t_fin1;\n\tgettimeofday(&t_ini1, NULL);\n\t//if(project_onto_map_)\n\t\tupdateDistTransform();\n\n\t//Take point cloud\n\tpc_mutex_.lock();\n\tsensor_msgs::PointCloud2 pc2 = laser_cloud_; //base_link\n\tpc_mutex_.unlock();\n\tsensor_msgs::PointCloud pc;\n\tbool done = sensor_msgs::convertPointCloud2ToPointCloud(pc2, pc);\n\tif(!done)\n\t\tROS_ERROR(\"\\n\\nPreplanning computations. convertPointCloud2toPointCloud!!!!!\\n\");\n\n\t//Take people\n\tpeople_mutex_.lock();\n\tvector<upo_msgs::PersonPoseUPO> p = people_;\t//odom\n\tpeople_mutex_.unlock();\n\n\t//Take goal\n\tgoal_mutex_.lock();\n\tgeometry_msgs::PoseStamped g = goal_;\t\t\t//base_link\n\tgoal_mutex_.unlock();\n\n\t\n\t//Form current navigation scene\n\tvector<int> input = capture_->generateImg(&pc, &p, &g);\n\tgettimeofday(&t_fin1, NULL);\n\tdouble secs1 = capture_->timeval_diff(&t_fin1, &t_ini1);\n  \t\n\n\t/*printf(\"Nav scene vector generated: \\n\");\n\tfor(unsigned int i=0; i<200; i++) {\n\t\tfor(unsigned int j=0; j<200; j++)\n\t\t\tprintf(\"%i\", input[((i*200)+j)]);\n\t\tprintf(\"\\n\");\n\t}*/\n\n\tstruct timeval t_ini2, t_fin2;\n\tgettimeofday(&t_ini2, NULL);\n\t//Update the path prediction (costmap)\n\tpredictionService(input, cm_height_pixs_, cm_width_pixs_);\n\tgettimeofday(&t_fin2, NULL);\n\tdouble secs2 = capture_->timeval_diff(&t_fin2, &t_ini2);\n\tprintf(\"Preplanning times:\\n \\tGenerate input: %.3f msecs\\n \\tGeneratePrediction: %.3f msecs\\n\", (secs1*1000.0), (secs2*1000.0) );\n}\n\n\n\n\nvector<upo_RRT::State> upo_RRT_ros::ValidityChecker3::getPredictedPointList()\n{\n\tvector<upo_RRT::State> points;\n\tcostmap_mutex_.lock();\n\tfor(unsigned int i=0; i<cm_height_pixs_; i++) {\n\t\tfor(unsigned int j=0; j<cm_width_pixs_; j++) {\n\t\t\tif(costmap_[i*cm_width_pixs_+j] > path_threshold_) {\n\t\t\t\tvector<int> cell;\n\t\t\t\tcell.push_back(j); //x\n\t\t\t\tcell.push_back(i); //y\n\t\t\t\tvector<float> pos = costmapCellToPose(cell);\n\t\t\t\tupo_RRT::State state(pos[0], pos[1], 0.0); //x, y, yaw \n\t\t\t\tpoints.push_back(state);\n\t\t\t}\n\t\t}\n\t} \n\tcostmap_mutex_.unlock();\n\treturn points;\n}\n\n\n\n// Transform a point in the world to the pixels in the static map\nvector<int> upo_RRT_ros::ValidityChecker3::worldToMap(geometry_msgs::Point32* world_point,nav_msgs::MapMetaData* map_metadata) const {\n\tvector<int> pixels;\n\tfloat x_map = world_point->x - map_metadata->origin.position.x;\n\tfloat y_map = world_point->y - map_metadata->origin.position.y;\n\tpixels.push_back((int)floor(x_map/map_metadata->resolution ));\n\tpixels.push_back((int)floor(y_map/map_metadata->resolution));\n\treturn pixels;\n}\n\n/**\n* transform point in base link frame (m) to pixel\n*/\nvector<int> upo_RRT_ros::ValidityChecker3::BaseLinkWorldToImg(geometry_msgs::Point32* point) const\n{ \n\tvector<int> pix;\n\tfloat wx = cm_origin_[0] + point->x;\n\tfloat wy = cm_origin_[1] + point->y; \n\tpix.push_back((int)floor(wx/cm_resolution_));\n\tpix.push_back((int)floor(wy/cm_resolution_));\n\treturn pix;\n\n}\n\n\nvector<int> upo_RRT_ros::ValidityChecker3::poseToCostmapCell(vector<float> pose) const\n{\n\t//Be careful, I'm not taking into account the rotation because is zero usually.\n\t//Pose is in robot frame coordinates, and the robot is centered in the costmap\n\tint x =  floor(fabs((pose[0] + cm_origin_[0])/cm_resolution_)); //x\n\tint y =  floor(fabs((pose[1] - cm_origin_[1])/cm_resolution_)); //y\n \tvector<int> cell;\n\tcell.push_back(x);\n\tcell.push_back(y);\n\treturn cell;\n}\n\n\n\nvector<float> upo_RRT_ros::ValidityChecker3::costmapCellToPose(vector<int> cell) const\n{\n\t//Be careful, I'm not taking into account the rotation because is zero usually.\n\tfloat x = (cell[0]*cm_resolution_) - cm_origin_[0]  + (cm_resolution_/2.0);  //-\n\tfloat y = (-1)*((cell[1]*cm_resolution_) - cm_origin_[1]  + (cm_resolution_/2.0)); //+\n\tvector<float> pose;\n\tpose.push_back(x);\n\tpose.push_back(y);\n\treturn pose;\n}\n\n\n//This checking is done over the static map (updated with the point cloud or not)\nbool upo_RRT_ros::ValidityChecker3::isValid(upo_RRT::State* s) const\n{\n\tgeometry_msgs::PoseStamped p_in;\n\tp_in.header.frame_id = \"base_link\"; \n\t//p_in.header.stamp = ros::Time(0); //this is a problem when the planning time is long. the time stamp should be the time when the rrt started to plan.\n\tif((ros::Time::now()-time_).toSec() > 2.0) {\n\t\t//time_ = ros::Time::now();\n\t\tp_in.header.stamp = ros::Time(0);\n\t} else \n\t\tp_in.header.stamp = time_;\n\t\n\tp_in.pose.position.x = s->getX();\n\tp_in.pose.position.y = s->getY();\n\tp_in.pose.orientation = tf::createQuaternionMsgFromYaw(s->getYaw());\n\n\t//Transform the coordinates\n\tfloat res;\n\tvector<int> pix;\n\tgeometry_msgs::PoseStamped sm;\n\tif(project_onto_map_) {\n\t\tres = map_metadata_.resolution;\n\t\tsm = transformPoseTo(&p_in, string(\"/map\"), false);\n\t\tgeometry_msgs::Point32 point;\n\t\tpoint.x = sm.pose.position.x;\n\t\tpoint.y = sm.pose.position.y;\n\t\tpoint.z = 0.0;\n\t\t//pix = worldToMap(&point, &map_metadata_);\n\t\tfloat x_map = point.x - map_metadata_.origin.position.x;\n\t\tfloat y_map = point.y - map_metadata_.origin.position.y;\n\t\tpix.push_back((int)floor(x_map/map_metadata_.resolution));\n\t\tpix.push_back((int)floor(y_map/map_metadata_.resolution));\n\n\t}else {\n\t\tres = cm_resolution_;\n\t\t//sm = transformPoseTo(&p_in, string(\"/base_link\"), false);\n\t\tgeometry_msgs::Point32 point;\n\t\tpoint.x = s->getX(); //sm.pose.position.x;\n\t\tpoint.y = s->getY(); //sm.pose.position.y;\n\t\tpoint.z = 0.0;\n\t\tpix = BaseLinkWorldToImg(&point);\n\t}\n\n\tfloat px = pix[0];\n\tfloat py = pix[1];\n\tfloat distance = 0.0;\n\t//dt_mutex_.lock();\n\tif (py<0 || px<0  || px > map_image_.cols || py > map_image_.rows) {\n\t\tdistance = 0.0;\n\t} else{\n\t\ttry{\n\t\t\t\n\t\t\tdistance = distance_transform_.at<float>(py,px)*res;\n\t\t\t\n\t\t} catch(...)\n\t\t{\n\t\t\tROS_ERROR(\"ERROR. IS_VALID. px:%.2f, py:%.2f, distance:%.2f\", px, py, distance);\n\t\t\tdistance = 0.0;\n\t\t}\n\t}\n\t//dt_mutex_.unlock();\n\t// Take into account the robot radius \n\tif(distance <= insc_radius_robot_) {\n\t\treturn false;\n\t}else {\n\t\t\n\t\treturn true;\n\t}\n\n}\n\n\n\nfloat upo_RRT_ros::ValidityChecker3::distance(upo_RRT::State* s1, upo_RRT::State* s2) const\n{\n\tfloat dx = s1->getX() - s2->getX();\n\tfloat dy = s1->getY() - s2->getY();\n\t//float dist = sqrt(dx*dx + dy*dy);\n\tfloat dist = dx*dx + dy*dy;\n\t\n\tswitch(distanceType_) {\n\t\t\n\t\tcase 1:\n\t\t\treturn dist;\n\n\t\tcase 2:\n\t\t\treturn sqrt(dist);\n\n\t\tcase 3:\n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//SUM w1*|| Pi+1 - Pi|| + w2*(1-|Qi+1 * Qi|)\u00b2\n\t\t\t\tfloat euc_dist = sqrt(dist);\n\t\t\n\t\t\t\ttf::Quaternion q1 = tf::createQuaternionFromYaw(s1->getYaw());\n\t\t\t\ttf::Quaternion q2 = tf::createQuaternionFromYaw(s2->getYaw());\n\t\t\t\tfloat dot_prod = q1.dot(q2);\n\t\t\t\tfloat angle_dist =  (1 - fabs(dot_prod))*(1 - fabs(dot_prod));\n\t\t\t\treturn 0.7*euc_dist + 0.3*angle_dist;\n\t\t\t}\n\t\t\t\n\t\tcase 4:\n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t// Another option\n\t\t\t\t/*\n\t\t\t\tFirst, transform the robot location into person location frame: \n\t\t\t\t\t\t\t\t\t\t\t|cos(th)  sin(th)  0|\n\t\t\t\t\tRotation matrix R(th)= \t|-sin(th) cos(th)  0|\n\t\t\t\t\t\t\t\t\t\t\t|  0        0      1|\n\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\tx' = (xr-xp)*cos(th_p)+(yr-yp)*sin(th_p)\n\t\t\t\t\ty' = (xr-xp)*(-sin(th_p))+(yr-yp)*cos(th_p)\n\t\t\t\t*/\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\treturn (0.8*sqrt(dist)+0.2*fabs(alpha));\n\t\t\t}\n\t\t\t\n\t\tcase 5:  \n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//UPO. Dist + sum of the angles of both points regarding the intersection line\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\tfloat beta = s2->getYaw() - alpha;\n\t\t\t\tbeta = normalizeAngle(beta, -M_PI, M_PI);\n\t\t\t\treturn (0.6*sqrt(dist)+0.4*(fabs(alpha)+fabs(beta)));\n\t\t\t}\n\t\t\t\n\t\tcase 6:  \n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//Paper IROS2015 \"Feedback motion planning via non-holonomic RRT* for mobile robots\"\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\tfloat phi = s2->getYaw() - alpha;\n\t\t\t\tphi = normalizeAngle(phi, -M_PI, M_PI);\n\t\t\t\tfloat ka = 0.5;\n\t\t\t\tfloat ko = ka/8.0;\n\t\t\t\tdist = sqrt(dist);\n\t\t\t\t// two options\n\t\t\t\tfloat alpha_prime = atan(-ko*phi);\n\t\t\t\t//float alpha_prime = atan(-ko*ko * phi/(dist*dist));\n\t\t\t\tfloat r = normalizeAngle((alpha-alpha_prime), -M_PI, M_PI);\n\t\t\t\treturn (sqrt(dist*dist + ko*ko + phi*phi) + ka*fabs(r));\n\t\t\t}\n\t\t\t\n\t\tdefault:\n\t\t\treturn sqrt(dist);\n\t}\n\t\n}\n\n\n\nfloat upo_RRT_ros::ValidityChecker3::getCost(upo_RRT::State* s)\n{\n\t//cell.first = x = column, cell.second = y = row\n\tvector<float> pose;\n\tpose.push_back((float)s->getX());\n\tpose.push_back((float)s->getY());\n\tcostmap_mutex_.lock();\n\tvector<int> cell = poseToCostmapCell(pose);\n\t//vector<int> cell = BaseLinkWorldToImg(&p);\n\tint ind = (cell[1]*cm_width_pixs_) + cell[0]; \n\t//if(ind < 0 || ind >= (200*200))\n\t//\tprintf(\"GetCost. Ind out of range: %i\\n\", ind); \n\tfloat reward = costmap_[ind]>1.0?1.0:costmap_[ind];\n\t//if(reward == 0.0)\n\t//\treturn 10.0;\n\t//printf(\"r: %.2f\\t\", reward);\n\tcostmap_mutex_.unlock();\n\treturn (1-reward); //*1000.0 //Value between [0,1]\n}\n\n\n\ngeometry_msgs::PoseStamped upo_RRT_ros::ValidityChecker3::transformPoseTo(geometry_msgs::PoseStamped* pose_in, std::string frame_out, bool usetime) const {\n\t\n\tgeometry_msgs::PoseStamped in = *pose_in;\n\tif(!usetime)\n\t\tin.header.stamp = ros::Time();\n\t\t\t\n\tgeometry_msgs::PoseStamped pose_out;\n\t\t\n\ttry {\n\t\ttf_->transformPose(frame_out.c_str(), in, pose_out);\n\t}catch (tf::TransformException ex){\n\t\tROS_WARN(\"ValidityChecker3. TransformException in method transformPoseTo. TargetFrame: %s : %s\", frame_out.c_str(), ex.what());\n\t}\n\treturn pose_out;\n\t\n}\n\nbool upo_RRT_ros::ValidityChecker3::isQuaternionValid(const geometry_msgs::Quaternion q) {\n\t\n\t\n\t\t//first we need to check if the quaternion has nan's or infs\n\t\tif(!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w)){\n\t\t\tROS_ERROR(\"Quaternion has infs!!!!\");\n\t\t\treturn false;\n\t\t}\n\t\tif(std::isnan(q.x) || std::isnan(q.y) || std::isnan(q.z) || std::isnan(q.w)) {\n\t\t\tROS_ERROR(\"Quaternion has nans !!!\");\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(std::fabs(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w - 1) > 0.01) {\n\t\t\tROS_ERROR(\"Quaternion malformed, magnitude: %.3f should be 1.0\", (q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w));\n\t\t\treturn false;\n\t\t}\n\n\t\ttf::Quaternion tf_q(q.x, q.y, q.z, q.w);\n\n\t\t//next, we need to check if the length of the quaternion is close to zero\n\t\tif(tf_q.length2() < 1e-6){\n\t\t  ROS_ERROR(\"Quaternion has length close to zero... discarding.\");\n\t\t  return false;\n\t\t}\n\n\t\t//next, we'll normalize the quaternion and check that it transforms the vertical vector correctly\n\t\ttf_q.normalize();\n\n\t\ttf::Vector3 up(0, 0, 1);\n\n\t\tdouble dot = up.dot(up.rotate(tf_q.getAxis(), tf_q.getAngle()));\n\n\t\tif(fabs(dot - 1) > 1e-3){\n\t\t  ROS_ERROR(\"Quaternion is invalid... for navigation the z-axis of the quaternion must be close to vertical.\");\n\t\t  return false;\n\t\t}\n\n\t\treturn true;\n\t\n}\n\n\n\n\n\n", "meta": {"hexsha": "ee930c14ccacf11c2b3cb7a7e2caf41c22e7ea2d", "size": 23217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rrt_planners/src/ros/ValidityChecker3.cpp", "max_stars_repo_name": "Tutorgaming/indires_navigation", "max_stars_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-07-19T13:44:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:39:15.000Z", "max_issues_repo_path": "rrt_planners/src/ros/ValidityChecker3.cpp", "max_issues_repo_name": "Tutorgaming/indires_navigation", "max_issues_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T07:32:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T09:38:44.000Z", "max_forks_repo_path": "rrt_planners/src/ros/ValidityChecker3.cpp", "max_forks_repo_name": "Tutorgaming/indires_navigation", "max_forks_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T14:43:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T21:39:19.000Z", "avg_line_length": 28.9128268991, "max_line_length": 166, "alphanum_fraction": 0.6829478399, "num_tokens": 7100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18332315473351177}}
{"text": "/*\n * MIT License\n *\n * Copyright (c) 2018 Tech Solutions Malta 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\n#include <graphene/chain/das33_evaluator.hpp>\n#include <graphene/chain/database.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <graphene/chain/market_object.hpp>\n\nnamespace graphene { namespace chain {\n\n  // Helper methods:\n  share_type users_total_pledges_in_round(account_id_type user_id, das33_project_id_type project_id, share_type round, const database& d)\n  {\n    share_type sum = 0;\n    const auto& idx = d.get_index_type<das33_pledge_holder_index>().indices().get<by_user>().equal_range(user_id);\n    for( auto it = idx.first; it != idx.second; ++it )\n    {\n      if (it->project_id == project_id && it->phase_number == round)\n        sum += (it->base_expected.amount);\n    }\n    return sum;\n  }\n\n  void price_check(const price& price_to_check, asset_id_type first_asset, asset_id_type second_asset)\n  {\n    FC_ASSERT(price_to_check.base.asset_id == first_asset || price_to_check.quote.asset_id == first_asset,\n              \"Price must be for ${1}\", (\"1\", first_asset));\n    FC_ASSERT(price_to_check.base.asset_id == second_asset || price_to_check.quote.asset_id == second_asset,\n                  \"Price must be for ${1}\", (\"1\", second_asset));\n  }\n\n  share_type precision_modifier(asset_object a, asset_object b)\n  {\n    share_type result = 1;\n    if (a.precision > b.precision)\n    {\n      result = std::pow(10, a.precision - b.precision);\n    }\n    return result;\n  }\n\n  optional<price> calculate_price(asset_id_type asset_id, das33_project_id_type project_id, const database& d)\n  {\n      const auto& project_obj = project_id(d);\n      const auto& price_override_it = project_obj.price_override.find(asset_id);\n\n      // Check if we are in alliance pay project and HF time ...\n      if (asset_id == d.get_dascoin_asset_id()\n              && project_id == das33_project_id_type{3}\n              && d.head_block_time() > HARDFORK_FIX_PLEDGE_PRICE_START\n              && d.head_block_time() < HARDFORK_FIX_PLEDGE_PRICE_END)\n      {\n          // .. if yes set fixed price to 0.1 We\n          return price{asset{100000, d.get_dascoin_asset_id()}, asset{10, d.get_web_asset_id()}};\n      }\n      else if (asset_id == d.get_dascoin_asset_id()\n               && project_id == das33_project_id_type{2}\n               && d.head_block_time() > HARDFORK_FIX_PLEDGE_PRICE_START\n               && d.head_block_time() < HARDFORK_FIX_PLEDGE_PRICE_END)\n      {\n          // .. or if we are in Greenstorc and HF time set fixed price to 0.0188 We\n          return price{asset{10000000, d.get_dascoin_asset_id()}, asset{188, d.get_web_asset_id()}};\n      }\n      else if (price_override_it != project_obj.price_override.end())\n      {\n          // ... or if we have price override, use that\n          return (*price_override_it).second;\n      }\n      else\n      {\n          // .. otherwise get price from db\n          return d.get_price_in_web_eur(asset_id);\n      }\n  }\n\n  typedef boost::multiprecision::uint128_t uint128_t;\n\n  asset asset_price_multiply ( const asset& a, int64_t precision, const price& b, const price& c )\n  {\n    uint128_t result;\n     if( a.asset_id == b.base.asset_id )\n     {\n        FC_ASSERT( b.base.amount.value > 0 );\n        result = (uint128_t(a.amount.value) * precision * b.quote.amount.value)/b.base.amount.value;\n        if (b.quote.asset_id == c.base.asset_id)\n        {\n          FC_ASSERT( c.base.amount.value > 0 );\n          result = (result * c.quote.amount.value)/c.base.amount.value;\n          result = result / precision;\n          return asset( result.convert_to<int64_t>(), c.quote.asset_id );\n        }\n        else\n        {\n          FC_ASSERT( c.quote.amount.value > 0 );\n          result = (result * c.base.amount.value)/c.quote.amount.value;\n          result = result / precision;\n          return asset( result.convert_to<int64_t>(), c.base.asset_id );\n        }\n\n     }\n     else if( a.asset_id == b.quote.asset_id )\n     {\n        FC_ASSERT( b.quote.amount.value > 0 );\n        result = (uint128_t(a.amount.value) * precision * b.base.amount.value)/b.quote.amount.value;\n        if (b.base.asset_id == c.base.asset_id)\n        {\n          FC_ASSERT( c.base.amount.value > 0 );\n          result = (result * c.quote.amount.value)/c.base.amount.value;\n          result = result / precision;\n          return asset( result.convert_to<int64_t>(), c.quote.asset_id );\n        }\n        else\n        {\n          FC_ASSERT( c.quote.amount.value > 0 );\n          result = (result * c.base.amount.value)/c.quote.amount.value;\n          result = result / precision;\n          return asset( result.convert_to<int64_t>(), c.base.asset_id );\n        }\n     }\n     FC_THROW_EXCEPTION( fc::assert_exception, \"invalid asset * price\", (\"asset\",a)(\"price\",b) );\n  }\n\n  // method implementations:\n\n  void_result das33_project_create_evaluator::do_evaluate( const operation_type& op )\n  {\n    try {\n      const auto& d = db();\n      const auto& gpo = d.get_global_properties();\n\n      // Check authority\n      const auto& authority_obj = op.authority(d);\n      d.perform_chain_authority_check(\"das33 authority\", gpo.authorities.das33_administrator, authority_obj);\n\n      // Check that name is unique\n      const auto& idx = d.get_index_type<das33_project_index>().indices().get<by_project_name>();\n      FC_ASSERT(idx.find(op.name) == idx.end(), \"Das33 project called ${1} already exists.\", (\"1\", op.name));\n\n      // Check that owner is a wallet\n      const auto& owner_obj = op.owner(d);\n      FC_ASSERT( owner_obj.is_wallet(), \"Owner account '${name}' is not a wallet account\", (\"name\", owner_obj.name));\n\n      // Check that token exists\n      const auto& token_index = d.get_index_type<asset_index>().indices().get<by_id>();\n      FC_ASSERT(token_index.find(op.token) != token_index.end(), \"Token with id ${1} does not exist\", (\"1\", op.token));\n\n      // Check that token has max_supply\n      FC_ASSERT(op.token(d).options.max_supply > 0, \"Token must have max_supply > 0\");\n\n      // Check that token isn't one of the system assets\n      FC_ASSERT(op.token != d.get_core_asset().id\n             && op.token != d.get_web_asset_id()\n             && op.token != d.get_dascoin_asset_id()\n             && op.token != d.get_btc_asset_id()\n             && op.token != d.get_cycle_asset_id(), \"Can not create project with system assets\");\n\n      // Check that token is not used by another project\n      const auto& it = std::find_if(idx.begin(), idx.end(),\n            [op](const das33_project_object& m) -> bool { return m.token_id == op.token; });\n      FC_ASSERT(it == idx.end(), \"Token with id ${1} is already used by another project\", (\"1\", op.token));\n\n      // Check that discounts exist\n      FC_ASSERT(op.discounts.size() > 0, \"Discounts must be provided. Only assets in discounts can be pledged.\");\n\n      // Check that discounts are in (0,1] range\n      for (auto itr = op.discounts.begin(); itr != op.discounts.end(); itr++)\n      {\n        FC_ASSERT(itr->second > 0,\n                  \"Discount can not be zero or negative (${name}:${value})\",\n                  (\"name\", itr->first)\n                  (\"value\", itr->second));\n        FC_ASSERT(itr->second <= 1 * BONUS_PRECISION,\n                  \"Discount can not be larger than 1.00 (${name}:${value})\",\n                  (\"name\", itr->first)\n                  (\"value\", itr->second));\n      }\n      return {};\n\n    } FC_CAPTURE_AND_RETHROW((op))\n  }\n\n  object_id_type das33_project_create_evaluator::do_apply( const operation_type& op )\n  {\n    try {\n      auto& d = db();\n\n      const asset_object token = op.token(d);\n      const asset max_supply {token.options.max_supply, token.id};\n      const asset to_collect {op.goal_amount_eur, d.get_web_asset_id()};\n      const price token_price = to_collect / max_supply;\n\n      return d.create<das33_project_object>([&](das33_project_object& dpo){\n             dpo.name = op.name;\n             dpo.owner = op.owner;\n             dpo.token_id = op.token;\n             dpo.goal_amount_eur = op.goal_amount_eur;\n             dpo.discounts = op.discounts;\n             dpo.min_pledge = op.min_pledge;\n             dpo.max_pledge = op.max_pledge;\n             dpo.token_price = token_price;\n             dpo.collected_amount_eur = 0;\n             dpo.tokens_sold = 0;\n             dpo.status = das33_project_status::inactive;\n             dpo.phase_number = 0;\n             dpo.phase_limit = max_supply.amount;\n             dpo.phase_end = time_point_sec::min();\n           }).id;\n    } FC_CAPTURE_AND_RETHROW((op))\n  }\n\n  void_result das33_project_update_evaluator::do_evaluate( const operation_type& op )\n  {\n    try {\n      const auto& d = db();\n      const auto& gpo = d.get_global_properties();\n\n      // Check authority\n      const auto& authority_obj = op.authority(d);\n      d.perform_chain_authority_check(\"das33 authority\", gpo.authorities.das33_administrator, authority_obj);\n\n      // Get project\n      const auto& idx = d.get_index_type<das33_project_index>().indices().get<by_id>();\n      auto project_iterator = idx.find(op.project_id);\n      FC_ASSERT(project_iterator != idx.end(), \"Das33 project with id ${1} does not exist.\", (\"1\", op.project_id));\n      project_to_update = &(*project_iterator);\n\n      // Check name\n      if (op.name.valid())\n      {\n        const auto& name_index = d.get_index_type<das33_project_index>().indices().get<by_project_name>();\n        FC_ASSERT(name_index.find(*op.name) == name_index.end(), \"Das33 project called ${1} already exists.\", (\"1\", *op.name));\n      }\n\n      // Check owner\n      if (op.owner.valid())\n      {\n        const auto& owner_obj = (*op.owner)(d);\n        FC_ASSERT( owner_obj.is_wallet(), \"Owner account '${name}' is not a wallet account\", (\"name\", owner_obj.name));\n      }\n\n      // Check price\n      if (op.token_price.valid())\n      {\n        price_check(*op.token_price, d.get_web_asset_id(), project_to_update->token_id);\n      }\n\n      // Check bonuses\n      if (op.discounts.valid())\n      {\n        // Check that discounts are in (0,1] range\n        for (auto itr = op.discounts->begin(); itr != op.discounts->end(); itr++)\n        {\n          FC_ASSERT(itr->second > 0,\n                    \"Discount can not be zero or negative (${name}:${value})\",\n                    (\"name\", itr->first)\n                    (\"value\", itr->second));\n          FC_ASSERT(itr->second <= 1 * BONUS_PRECISION,\n                    \"Discount can not be larger than 1.00  (${name}:${value})\",\n                    (\"name\", itr->first)\n                    (\"value\", itr->second));\n        }\n      }\n\n      // Check phase number\n      if (op.phase_number.valid())\n      {\n        FC_ASSERT(*op.phase_number > project_to_update->phase_number, \"Phase number can not be decreased\");\n      }\n\n      // Check phase limit\n      if (op.phase_limit.valid())\n      {\n        share_type new_limit = *op.phase_limit;\n        asset_object token = project_to_update->token_id(d);\n        // If previous limit is not max supply\n        if (project_to_update->phase_limit != token.options.max_supply )\n        {\n          // New limit must be more than what is already collected\n          FC_ASSERT(new_limit >= project_to_update->tokens_sold, \"New phase limit must be more than already collected\");\n        }\n        FC_ASSERT(new_limit <= token.options.max_supply, \"New limit can not be more then max supply of token\");\n      }\n\n      // Check status\n      if (op.status.valid())\n      {\n        FC_ASSERT(*op.status < das33_project_status::DAS33_PROJECT_STATUS_COUNT, \"Unknown status value\");\n      }\n\n      return {};\n    } FC_CAPTURE_AND_RETHROW((op))\n  }\n\n  void_result das33_project_update_evaluator::do_apply( const operation_type& op )\n  {\n    try {\n      auto& d = db();\n\n      d.modify<das33_project_object>(*project_to_update, [&](das33_project_object& dpo){\n        if (op.name) dpo.name = *op.name;\n        if (op.owner) dpo.owner = *op.owner;\n        // token_id: we can't alter\n        if (op.goal_amount) dpo.goal_amount_eur = *op.goal_amount;\n        if (op.discounts) dpo.discounts = *op.discounts;\n        if (op.min_pledge) dpo.min_pledge = *op.min_pledge;\n        if (op.max_pledge) dpo.max_pledge = *op.max_pledge;\n        if (op.token_price) dpo.token_price = *op.token_price;\n        // collected_amount_eur: we can't alter\n        // tokens_sold: we can't alter\n        if (op.status) dpo.status = static_cast<das33_project_status>(*op.status);\n        if (op.phase_number) dpo.phase_number = *op.phase_number;\n        if (op.phase_limit) dpo.phase_limit = *op.phase_limit;\n        if (op.phase_end) dpo.phase_end = *op.phase_end;\n\n        for (const auto& ext : op.extensions)\n        {\n           ext.visit(das33_project_visitor{dpo.report});\n        }\n\n        auto new_price_override_it = std::find_if(op.extensions.begin(), op.extensions.end(),\n                                         [](const das33_project_update_operation::das33_project_extension& ext){\n                                               return ext.which() == das33_project_update_operation::das33_project_extension::tag< map<asset_id_type, price> >::value;\n                                        });\n        if (new_price_override_it != op.extensions.end())\n        {\n            dpo.price_override = (*new_price_override_it).get<map<asset_id_type, price>>();\n        }\n      });\n\n      return {};\n    } FC_CAPTURE_AND_RETHROW((op))\n  }\n\n  void_result das33_project_delete_evaluator::do_evaluate( const operation_type& op )\n  {\n    try {\n      const auto& d = db();\n      const auto& gpo = d.get_global_properties();\n\n      const auto& authority_obj = op.authority(d);\n      d.perform_chain_authority_check(\"das33 authority\", gpo.authorities.das33_administrator, authority_obj);\n\n      const auto& idx = d.get_index_type<das33_project_index>().indices().get<by_id>();\n      auto project_iterator = idx.find(op.project_id);\n      FC_ASSERT(project_iterator != idx.end(), \"Das33 project with id ${1} does not exist.\", (\"1\", op.project_id));\n      project_to_delete = &(*project_iterator);\n\n      const auto& pledges_idx = d.get_index_type<das33_pledge_holder_index>().indices().get<by_project>().equal_range(op.project_id);\n      //auto pledges_iterator = pledges_idx.begin();\n      FC_ASSERT(pledges_idx.first == pledges_idx.second, \"Project can not be deleted as it has pledges\");\n\n      return {};\n    } FC_CAPTURE_AND_RETHROW((op))\n  }\n\n  void_result das33_project_delete_evaluator::do_apply( const operation_type& op )\n  {\n    try {\n      auto& d = db();\n\n      d.remove(*project_to_delete);\n\n      return {};\n    } FC_CAPTURE_AND_RETHROW((op))\n  }\n\n  void_result das33_pledge_asset_evaluator::do_evaluate(const das33_pledge_asset_operation& op)\n  { try {\n\n    const auto& d = db();\n    const auto& project_obj = op.project_id(d);\n    const auto& token_obj = project_obj.token_id(d);\n\n    // Check if pledged asset and project token are different assets\n    FC_ASSERT( op.pledged.asset_id != project_obj.token_id, \"Cannot pledge project tokens\" );\n\n    // Assure target project exists:\n    const auto& idx = d.get_index_type<das33_project_index>().indices().get<by_id>();\n    FC_ASSERT( idx.find(project_obj.id) != idx.end(), \"Bad project id\" );\n\n    // Check if project is active\n    FC_ASSERT(project_obj.status == das33_project_status::active, \"Pladge can only be made to active project\");\n\n    // Assure we have enough balance to pledge:\n    const auto& balance_obj = d.get_balance_object(op.account_id, op.pledged.asset_id);\n    FC_ASSERT( balance_obj.get_balance() >= op.pledged,\n               \"Not enough balance on user account ${a}, left ${l}, needed ${n}\",\n               (\"a\", op.account_id)\n               (\"l\", d.to_pretty_string(balance_obj.get_balance()))\n               (\"n\", d.to_pretty_string(op.pledged))\n    );\n\n    // Assure current phase hasn't ended\n    if (project_obj.phase_end != time_point_sec::min())\n    {\n      FC_ASSERT(d.head_block_time() < project_obj.phase_end, \"Can not pledge: new ICO phase hasn;t started yet\");\n    }\n\n    // Assure that all tokens aren't sold\n    FC_ASSERT(project_obj.tokens_sold < token_obj.options.max_supply, \"All tokens for project are sold\");\n    FC_ASSERT(project_obj.tokens_sold < project_obj.phase_limit, \"All tokens in this phase are sold\");\n\n    // Calculate expected amount\n    share_type precision = precision_modifier(op.pledged.asset_id(d), d.get_web_asset_id()(d));\n    total.asset_id = project_obj.token_id;\n\n    optional<price> conversion_price = calculate_price(op.pledged.asset_id, op.project_id, d);\n\n    FC_ASSERT(conversion_price.valid(), \"There is no proper price for ${asset}\", (\"asset\", op.pledged.asset_id));\n\n    price_at_evaluation = *conversion_price;\n    base = asset_price_multiply(op.pledged, precision.value, price_at_evaluation, project_obj.token_price);\n\n    // Assure that pledge amount is above minimum\n    if (!(op.pledged.asset_id == d.get_dascoin_asset_id()\n                   && op.project_id == das33_project_id_type{2}\n                   && d.head_block_time() > HARDFORK_FIX_PLEDGE_PRICE_START\n                   && d.head_block_time() < HARDFORK_FIX_PLEDGE_PRICE_END))\n    {\n        FC_ASSERT(base.amount >= project_obj.min_pledge, \"Can not pledge: must buy at least ${min} tokens\", (\"min\", project_obj.min_pledge));\n    }\n\n\n    // Assure that pledge amount is below maximum for current user\n    auto previous_pledges = users_total_pledges_in_round(op.account_id, op.project_id, project_obj.phase_number, d);\n    if (op.pledged.asset_id == d.get_dascoin_asset_id()\n            && op.project_id == das33_project_id_type{3}\n            && d.head_block_time() > HARDFORK_FIX_PLEDGE_PRICE_START\n            && d.head_block_time() < HARDFORK_FIX_PLEDGE_PRICE_END)\n    {\n        FC_ASSERT( previous_pledges + base.amount <= 100000000000000,\n                  \"Can not buy more then ${max} tokens per phase and you already pledged for ${previous} in this phase.\",\n                  (\"max\", project_obj.max_pledge)\n                  (\"previous\", previous_pledges));\n    }\n    else\n    {\n        FC_ASSERT( previous_pledges + base.amount <= project_obj.max_pledge,\n                  \"Can not buy more then ${max} tokens per phase and you already pledged for ${previous} in this phase.\",\n                  (\"max\", project_obj.max_pledge)\n                  (\"previous\", previous_pledges));\n    }\n\n    // Calculate expected amount with discounts\n    auto discount_iterator = project_obj.discounts.find(op.pledged.asset_id);\n    FC_ASSERT( discount_iterator != project_obj.discounts.end(), \"This asset can not be used in this project phase\" );\n    discount = discount_iterator->second;\n    total.amount = base.amount * BONUS_PRECISION / discount;\n\n    // Assure that pledge amount is above zero\n    FC_ASSERT(total.amount > 0,\n              \"Cannot pledge because expected amount of ${tok} is ${ex}\",\n              (\"tok\", token_obj.symbol)\n              (\"ex\", d.to_pretty_string(total))\n    );\n\n    bool total_reduced = false;\n    // Decrease amount if it passes tokens max supply\n    if (project_obj.tokens_sold + total.amount > token_obj.options.max_supply)\n    {\n        total.amount = token_obj.options.max_supply - project_obj.tokens_sold;\n        total_reduced = true;\n    }\n\n    // Decrease amount if it passes current phase limit\n    if (project_obj.tokens_sold + total.amount > project_obj.phase_limit)\n    {\n        total.amount = project_obj.phase_limit - project_obj.tokens_sold;\n        total_reduced = true;\n    }\n\n    if (total_reduced)\n    {\n      base = {total.amount * discount / BONUS_PRECISION, total.asset_id};\n      bonus = total - base;\n      precision = precision_modifier(base.asset_id(d), d.get_web_asset_id()(d));\n      to_take = asset_price_multiply(base, precision.value, project_obj.token_price, price_at_evaluation);\n    }\n    else\n    {\n      bonus = total - base;\n      to_take = op.pledged;\n    }\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  object_id_type das33_pledge_asset_evaluator::do_apply(const das33_pledge_asset_operation& op)\n  { try {\n\n    auto& d = db();\n    const auto& project_obj = op.project_id(d);\n\n    // Adjust the balance and spent amount:\n    const auto& balance_obj = d.get_balance_object(op.account_id, op.pledged.asset_id);\n    d.modify(balance_obj, [&](account_balance_object& from){\n      from.balance -= to_take.amount;\n      from.spent += to_take.amount;\n    });\n\n    // Update project\n    d.modify(project_obj, [&](das33_project_object& p){\n        p.tokens_sold += total.amount;\n        p.collected_amount_eur += (to_take * price_at_evaluation).amount;\n    });\n\n    // Create the holder object and return its ID:\n    return d.create<das33_pledge_holder_object>([&](das33_pledge_holder_object& cpho){\n      cpho.account_id = op.account_id;\n      cpho.pledged = to_take;\n      cpho.pledge_remaining = to_take;\n      cpho.base_remaining = base;\n      cpho.base_expected = base;\n      cpho.bonus_remaining = bonus;\n      cpho.bonus_expected = bonus;\n      cpho.phase_number = project_obj.phase_number;\n      cpho.project_id = op.project_id;\n      cpho.timestamp = d.head_block_time();\n    }).id;\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_distribute_project_pledges_evaluator::do_evaluate(const das33_distribute_project_pledges_operation& op)\n  { try {\n\n     auto& d = db();\n\n     auto& pro_index = d.get_index_type<das33_project_index>().indices().get<by_id>();\n     auto pro_itr = pro_index.find(op.project);\n     account_id_type pro_owner;\n     FC_ASSERT(pro_itr != pro_index.end(), \"Missing project object with this project_id!\");\n\n     _pro_owner = pro_itr->owner;\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_distribute_project_pledges_evaluator::do_apply(const das33_distribute_project_pledges_operation& op)\n  { try {\n\n    auto& d = db();\n\n    std::vector<object_id_type> pledges_to_remove;\n    const auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_project>().equal_range(op.project);\n    auto itr = index.first;\n\n    while(itr != index.second)\n    {\n       if(op.phase_number.valid() && itr->phase_number != *op.phase_number) {\n           ++itr;\n           continue;\n       }\n\n       const das33_pledge_holder_object& pho = *itr;\n\n       // calc amount of token and asset that will be exchanged\n       share_type base = std::round(static_cast<double>(pho.base_expected.amount.value) * op.base_to_pledger.value / BONUS_PRECISION / 100);\n                  base = (base < pho.base_remaining.amount) ? base : pho.base_remaining.amount;\n       share_type bonus = std::round(static_cast<double>(pho.bonus_expected.amount.value) * op.bonus_to_pledger.value / BONUS_PRECISION / 100);\n                  bonus = (bonus < pho.bonus_remaining.amount) ? bonus : pho.bonus_remaining.amount;\n       share_type pledge = std::round(static_cast<double>(pho.pledged.amount.value) * op.to_escrow.value / BONUS_PRECISION / 100);\n                  pledge = (pledge < pho.pledge_remaining.amount) ? pledge : pho.pledge_remaining.amount;\n\n       // make virtual op for history traking\n       das33_pledge_result_operation pledge_result;\n          pledge_result.funders_account = pho.account_id;\n          pledge_result.account_to_fund = _pro_owner;\n          pledge_result.completed = true;\n          pledge_result.pledged = pledge;\n          pledge_result.received = base + bonus;\n          pledge_result.project_id = op.project;\n          pledge_result.timestamp = d.head_block_time();\n       d.push_applied_operation(pledge_result);\n\n       d.adjust_balance(_pro_owner, asset{pledge, pho.pledged.asset_id}, 0 /*reserved_delta*/);\n\n       // issue balance object if it does not exists\n       if(!d.check_if_balance_object_exists(pho.account_id,pho.base_expected.asset_id))\n       {\n          d.create<account_balance_object>([&pho](account_balance_object& abo){\n             abo.owner = pho.account_id;\n             abo.asset_type = pho.base_expected.asset_id;\n             abo.balance = 0;\n             abo.reserved = 0;\n          });\n       }\n\n       // issue token asset\n       auto& balance1_obj = d.get_balance_object(pho.account_id, pho.base_expected.asset_id);\n       d.issue_asset(balance1_obj, base + bonus, 0);\n\n       // update pledge holder object\n       d.modify(pho, [&](das33_pledge_holder_object& p){\n          p.pledge_remaining.amount -= pledge;\n          p.base_remaining.amount -= base;\n          p.bonus_remaining.amount -= bonus;\n       });\n\n       // if everything is distributed remove object\n       if(pho.pledge_remaining.amount + pho.base_remaining.amount + pho.bonus_remaining.amount <= 0)\n       {\n          pledges_to_remove.push_back(pho.id);\n       }\n       itr++;\n    }\n\n    auto& index1 = d.get_index_type<das33_pledge_holder_index>().indices().get<by_id>();\n    for(object_id_type id : pledges_to_remove)\n    {\n       auto itr = index1.find(id);\n       if(itr != index1.end())\n          d.remove(*itr);\n    }\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_project_reject_evaluator::do_evaluate(const das33_project_reject_operation& op)\n  { try {\n\n     auto& d = db();\n\n     auto& pro_index = d.get_index_type<das33_project_index>().indices().get<by_id>();\n     auto pro_itr = pro_index.find(op.project);\n     FC_ASSERT(pro_itr != pro_index.end(), \"Missing project object with this project_id!\");\n\n     auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_project>();\n     auto itr = index.lower_bound(op.project);\n     auto end = index.upper_bound(op.project);\n     while(itr != end)\n     {\n        const das33_pledge_holder_object& pho = *itr;\n        FC_ASSERT(pho.base_expected.amount == pho.base_remaining.amount\n           && pho.bonus_expected.amount == pho.bonus_remaining.amount\n           && pho.pledged.amount == pho.pledge_remaining.amount,\n           \"Project already accepted, can't be rejected!\");\n        itr++;\n     }\n\n     _pro_owner = pro_itr->owner;\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_project_reject_evaluator::do_apply(const das33_project_reject_operation& op)\n  { try {\n\n     auto& d = db();\n\n     while(true)\n     {\n        auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_project>();\n        auto itr = index.lower_bound(op.project);\n        auto end = index.upper_bound(op.project);\n        if(itr == end)\n           break;\n\n        const das33_pledge_holder_object& pho = *itr;\n\n        das33_pledge_result_operation pledge_result;\n           pledge_result.funders_account = pho.account_id;\n           pledge_result.account_to_fund = _pro_owner;\n           pledge_result.completed = false;\n           pledge_result.pledged = pho.pledged;\n           pledge_result.received = pho.pledged;\n           pledge_result.project_id = op.project;\n           pledge_result.timestamp = d.head_block_time();\n        d.push_applied_operation(pledge_result);\n\n        auto& balance_obj = d.get_balance_object(pho.account_id, pho.pledged.asset_id);\n        d.modify(balance_obj, [&](account_balance_object& balance_obj){\n           balance_obj.balance += pho.pledged.amount;\n        });\n\n        d.remove(pho);\n     }\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_distribute_pledge_evaluator::do_evaluate(const das33_distribute_pledge_operation& op)\n  { try {\n     auto& d = db();\n\n     // find pledge object\n     auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_id>();\n     auto itr = index.find(op.pledge);\n     FC_ASSERT(itr != index.end(),\"Missing pledge object with this pledge_id.\");\n\n     auto& pro_index = d.get_index_type<das33_project_index>().indices().get<by_id>();\n     auto pro_itr = pro_index.find(itr->project_id);\n     account_id_type pro_owner;\n     FC_ASSERT(pro_itr != pro_index.end(), \"Missing project object with this project_id!\");\n\n     _pro_owner = pro_itr->owner;\n     _pledge_holder_ptr = &(*itr);\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_distribute_pledge_evaluator::do_apply(const das33_distribute_pledge_operation& op)\n  { try {\n\n     auto& d = db();\n     const das33_pledge_holder_object& pho = *_pledge_holder_ptr;\n\n     // calc amount of token and asset that will be exchanged\n     share_type base = std::round(static_cast<double>(pho.base_expected.amount.value) * op.base_to_pledger.value / BONUS_PRECISION / 100);\n                base = (base < pho.base_remaining.amount) ? base : pho.base_remaining.amount;\n     share_type bonus = std::round(static_cast<double>(pho.bonus_expected.amount.value) * op.bonus_to_pledger.value / BONUS_PRECISION / 100);\n                bonus = (bonus < pho.bonus_remaining.amount) ? bonus : pho.bonus_remaining.amount;\n     share_type pledge = std::round(static_cast<double>(pho.pledged.amount.value) * op.to_escrow.value / BONUS_PRECISION / 100);\n                pledge = (pledge < pho.pledge_remaining.amount) ? pledge : pho.pledge_remaining.amount;\n\n     // make virtual op for history traking\n     das33_pledge_result_operation pledge_result;\n        pledge_result.funders_account = pho.account_id;\n        pledge_result.account_to_fund = _pro_owner;\n        pledge_result.completed = true;\n        pledge_result.pledged = pledge;\n        pledge_result.received = base + bonus;\n        pledge_result.project_id = pho.project_id;\n        pledge_result.timestamp = d.head_block_time();\n     d.push_applied_operation(pledge_result);\n\n     d.adjust_balance(_pro_owner, asset{pledge, pho.pledged.asset_id}, 0 /*reserved_delta*/);\n\n     // issue balance object if it does not exists\n     if(!d.check_if_balance_object_exists(pho.account_id,pho.base_expected.asset_id))\n     {\n        d.create<account_balance_object>([&pho](account_balance_object& abo){\n           abo.owner = pho.account_id;\n           abo.asset_type = pho.base_expected.asset_id;\n           abo.balance = 0;\n           abo.reserved = 0;\n        });\n     }\n\n     // issue token asset\n     auto& balance1_obj = d.get_balance_object(pho.account_id, pho.base_expected.asset_id);\n     d.issue_asset(balance1_obj, base + bonus, 0);\n\n     // update pledge holder object\n     d.modify(pho, [&](das33_pledge_holder_object& p){\n        p.pledge_remaining.amount -= pledge;\n        p.base_remaining.amount -= base;\n        p.bonus_remaining.amount -= bonus;\n     });\n\n     // if everything is distributed remove object\n     if(pho.pledge_remaining.amount + pho.base_remaining.amount + pho.bonus_remaining.amount <= 0)\n     {\n        d.remove(pho);\n     }\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_pledge_reject_evaluator::do_evaluate(const das33_pledge_reject_operation& op)\n  { try {\n\n     auto& d = db();\n\n     // find pledge object\n     auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_id>();\n     auto itr = index.find(op.pledge);\n     FC_ASSERT(itr != index.end(),\"Missing pledge object with this pledge_id.\");\n\n     auto& pro_index = d.get_index_type<das33_project_index>().indices().get<by_id>();\n     auto pro_itr = pro_index.find(itr->project_id);\n     account_id_type pro_owner;\n     FC_ASSERT(pro_itr != pro_index.end(), \"Missing project object with this project_id!\");\n\n     _pro_owner = pro_itr->owner;\n     _pledge_holder_ptr = &(*itr);\n     const das33_pledge_holder_object& pho = *_pledge_holder_ptr;\n     FC_ASSERT(pho.base_expected.amount == pho.base_remaining.amount\n           && pho.bonus_expected.amount == pho.bonus_remaining.amount\n           && pho.pledged.amount == pho.pledge_remaining.amount,\n           \"Project already accepted, can't be rejected!\");\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_pledge_reject_evaluator::do_apply(const das33_pledge_reject_operation& op)\n  { try {\n\n     auto& d = db();\n\n     // make virtual op for history traking\n     const das33_pledge_holder_object& pho = *_pledge_holder_ptr;\n\n     // make virtual op for history traking\n     das33_pledge_result_operation pledge_result;\n        pledge_result.funders_account = pho.account_id;\n        pledge_result.account_to_fund = _pro_owner;\n        pledge_result.completed = false;\n        pledge_result.pledged = pho.pledged;\n        pledge_result.received = pho.pledged;\n        pledge_result.project_id = pho.project_id;\n        pledge_result.timestamp = d.head_block_time();\n     d.push_applied_operation(pledge_result);\n\n     // give to project owner pledged amount\n     auto& balance_obj = d.get_balance_object(pho.account_id, pho.pledged.asset_id);\n     d.modify(balance_obj, [&](account_balance_object& balance_obj){\n        balance_obj.balance += pho.pledged.amount;\n     });\n\n     d.remove(pho);\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_set_use_external_btc_price_evaluator::do_evaluate(const operation_type& op)\n  { try {\n\n      return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_set_use_external_btc_price_evaluator::do_apply(const operation_type& op)\n  { try {\n\n      return {};\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_set_use_market_price_for_token_evaluator::do_evaluate(const operation_type& op)\n  { try {\n    const auto& d = db();\n    const auto& gpo = d.get_global_properties();\n    const auto& authority_obj = op.authority(d);\n\n    d.perform_chain_authority_check(\"das33 authority\", gpo.authorities.das33_administrator, authority_obj);\n\n    return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n  void_result das33_set_use_market_price_for_token_evaluator::do_apply(const operation_type& op)\n  { try {\n    auto& d = db();\n\n    d.modify(d.get_global_properties(), [&](global_property_object& gpo){\n      gpo.use_market_price_for_token = op.use_market_price_for_token;\n  });\n\n      return {};\n\n  } FC_CAPTURE_AND_RETHROW((op)) }\n\n} }  // namespace graphene::chain\n", "meta": {"hexsha": "27809e365e89699f3957d50c645b2f3a601a53d7", "size": 34859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/das33_evaluator.cpp", "max_stars_repo_name": "powerchain-ltd/greenpower-blockchain", "max_stars_repo_head_hexsha": "ff04c37f2de11677c3a34889fdede1256a3e5e02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-26T02:42:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T02:42:01.000Z", "max_issues_repo_path": "libraries/chain/das33_evaluator.cpp", "max_issues_repo_name": "green-powerchain-ltd/greenpower-blockchain", "max_issues_repo_head_hexsha": "ff04c37f2de11677c3a34889fdede1256a3e5e02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/das33_evaluator.cpp", "max_forks_repo_name": "green-powerchain-ltd/greenpower-blockchain", "max_forks_repo_head_hexsha": "ff04c37f2de11677c3a34889fdede1256a3e5e02", "max_forks_repo_licenses": ["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.4779161948, "max_line_length": 166, "alphanum_fraction": 0.6540922, "num_tokens": 8282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18332315473351177}}
{"text": "// Copyright (c) 2020 Graphcore Ltd. All rights reserved.\n\n#include <iostream>\n#include <random>\n\n#include <boost/optional.hpp>\n#include <boost/random.hpp>\n\n#include <poplar/Graph.hpp>\n\n#include <poplibs_support/Algorithm.hpp>\n#include <poplibs_support/VectorUtils.hpp>\n\n#include \"SparseDensePartitionElementWise.hpp\"\n#include <popsolver/Model.hpp>\n#include <poputil/Util.hpp>\n\n// Test functions to generate sparse tensor data and metadata for codelet\n// testing\n\nusing namespace poplar;\nusing namespace poputil;\nusing namespace poplibs_support;\n\ntemplate <typename RandomEngine>\nstd::vector<std::array<unsigned, 2>>\ngenerateSparseIndices(RandomEngine &randomEngine,\n                      const std::vector<std::size_t> &shape, std::size_t n) {\n  // Generate n random indices that are within the flattened given shape.\n  std::vector<unsigned> randomIndices(product(shape));\n  std::iota(randomIndices.begin(), randomIndices.end(), 0);\n  auto randomGen = [&](unsigned max) {\n    boost::random::uniform_int_distribution<unsigned> dist(0, max - 1);\n    return dist(randomEngine);\n  };\n  boost::range::random_shuffle(randomIndices, randomGen);\n  randomIndices.resize(n);\n\n  std::vector<std::array<unsigned, 2>> rowColumnIndices(n);\n  for (std::size_t i = 0; i < n; ++i) {\n    const auto unflattenedIndex =\n        vectorConvert<unsigned>(unflattenIndex(shape, randomIndices[i]));\n    rowColumnIndices[i] = {unflattenedIndex[0], unflattenedIndex[1]};\n  }\n  return rowColumnIndices;\n}\n\nstd::tuple<unsigned, unsigned, unsigned>\ngetForwardWorkerPartition(const Target &target, const Type &inputType,\n                          const unsigned bColumns, const unsigned aRows,\n                          const std::vector<unsigned> &aRowColumnCounts) {\n  // Split rows of a and columns of b between workers.\n  //\n  // For this functional test we'll just first split columns of b, then\n  // rows of a to try and utilise all workers.\n  //\n  // NOTE: A problem with this is that by needing a contiguous range of\n  // columns to process, in the given order, we are restricting how work\n  // can be split. We cannot change the order of columns because that\n  // would make things difficult for other passes. We could do some more\n  // heavy encoding to allow interleaved columns to be selected for\n  // workers but it's more memory to encode.\n  const auto bColumnGrainSize = target.getVectorWidth(inputType);\n  const auto bColumnGrains = ceildiv(bColumns, bColumnGrainSize);\n\n  popsolver::Model m;\n  const auto mWorkerARowsPartition = m.addVariable(1, aRows);\n  const auto mWorkerBColumnGrainsPartition = m.addVariable(1, bColumnGrains);\n\n  const auto mNumARows = m.addConstant(aRows);\n  const auto mNumBColumnGrains = m.addConstant(bColumnGrains);\n\n  const auto mWorkerARows = m.ceildiv(mNumARows, mWorkerARowsPartition);\n  const auto mWorkerBColumnGrains =\n      m.ceildiv(mNumBColumnGrains, mWorkerBColumnGrainsPartition);\n\n  const auto numWorkers = target.getNumWorkerContexts();\n  const auto mMaxWorkerAElems = m.call<unsigned>(\n      {mWorkerARows},\n      [&](const std::vector<unsigned> &values) -> popsolver::DataType {\n        const auto workerARows = values[0];\n        unsigned maxWorkerAElems = 0;\n        for (unsigned worker = 0; worker < numWorkers; ++worker) {\n          const auto elems = std::accumulate(\n              aRowColumnCounts.begin() +\n                  std::min<unsigned>(worker * workerARows, aRows),\n              aRowColumnCounts.begin() +\n                  std::min<unsigned>((worker + 1) * workerARows, aRows),\n              0u);\n          maxWorkerAElems = std::max<unsigned>(maxWorkerAElems, elems);\n        }\n        return popsolver::DataType{maxWorkerAElems};\n      });\n\n  m.lessOrEqual(\n      m.product({mWorkerARowsPartition, mWorkerBColumnGrainsPartition}),\n      popsolver::DataType{numWorkers});\n\n  const auto mMaxWorkerGrains =\n      m.product({mMaxWorkerAElems, mWorkerBColumnGrains});\n\n  const auto s = m.minimize(mMaxWorkerGrains);\n  if (!s.validSolution()) {\n    throw poplibs_error(\"Failed to find a plan to split work between workers!\");\n  }\n\n  const auto numAPartitions = s[mWorkerARowsPartition].getAs<unsigned>();\n  const auto numBPartitions =\n      s[mWorkerBColumnGrainsPartition].getAs<unsigned>();\n  return std::make_tuple(bColumnGrainSize, numAPartitions, numBPartitions);\n}\n\nstd::tuple<unsigned, unsigned>\ngetGradWWorkerPartition(const Target &target, const Type &inputType,\n                        const unsigned bColumns, const unsigned aRows,\n                        const std::vector<unsigned> &aRowColumnCounts) {\n  // Much easier than forward partitions. Just partition the total number\n  // of columns of A between workers.\n  const auto totalAElems = std::accumulate(\n      aRowColumnCounts.begin(), aRowColumnCounts.end(), std::size_t(0));\n\n  // Grain size of columns of b is the same as for forward for GradW codelet.\n  const auto bColumnGrainSize = target.getVectorWidth(inputType);\n  const auto numWorkers = target.getNumWorkerContexts();\n  const auto aElemsPerWorker = ceildiv(totalAElems, numWorkers);\n  const auto numAPartitions = ceildiv(totalAElems, aElemsPerWorker);\n\n  return std::make_tuple(bColumnGrainSize, numAPartitions);\n}\n\ntemplate <typename RandomEngine>\nstd::vector<std::vector<unsigned>> generateMetaInfoAndPartition(\n    RandomEngine &randomEngine, std::vector<std::array<unsigned, 2>> &indices,\n    const std::vector<std::size_t> &aShape,\n    const std::vector<std::size_t> &bShape, unsigned numBuckets,\n    unsigned processedSubGroupId, const std::vector<unsigned> &otherSubGroupIds,\n    const std::vector<std::vector<unsigned>> processedSubGroupIndices,\n    const std::vector<std::vector<unsigned>> &subGroupNumElems,\n    const Target &target, const Type &inputType, const Type &partialType,\n    VertexType vertexType, unsigned xPartition, unsigned yPartition) {\n  const auto generateGradWMetaInfo = vertexType == VertexType::GradW;\n  const auto generateGradAMetaInfo = vertexType == VertexType::GradA;\n\n  // Factor by which row and column offsets are scaled\n  const auto yOffsetFactor = inputType == FLOAT ? 4 : 2;\n\n  // Order indices of a by column then row\n  std::sort(indices.begin(), indices.end());\n\n  std::vector<std::vector<unsigned>> metaInfo(numBuckets);\n  auto garbageDist =\n      boost::random::uniform_int_distribution<unsigned>(0, 0xffff);\n  std::size_t nzOffset = 0;\n  for (unsigned bucket = 0; bucket < numBuckets; ++bucket) {\n    std::size_t splitIdx = 0;\n    std::size_t numSplits = processedSubGroupIndices.at(bucket).size();\n    for (std::size_t i = 0; i < otherSubGroupIds.size() + numSplits; ++i) {\n      if (splitIdx != numSplits &&\n          i == processedSubGroupIndices[bucket][splitIdx]) {\n\n        std::vector<unsigned> rows;\n        std::vector<unsigned> rowColumnCounts;\n        boost::optional<unsigned> lastRowIndex;\n        for (std::size_t nzIdx = nzOffset;\n             nzIdx < nzOffset + subGroupNumElems[bucket].at(i); ++nzIdx) {\n          if (!lastRowIndex || *lastRowIndex != indices.at(nzIdx)[0]) {\n            rows.emplace_back();\n            rowColumnCounts.emplace_back();\n          }\n          rows.back() = indices.at(nzIdx)[0];\n          ++rowColumnCounts.back();\n          lastRowIndex = rows.back();\n        }\n\n        const auto bColumns = bShape[1];\n\n        unsigned fwdBColumnGrainSize, fwdNumAPartitions, fwdNumBPartitions;\n        std::tie(fwdBColumnGrainSize, fwdNumAPartitions, fwdNumBPartitions) =\n            getForwardWorkerPartition(target, inputType, bColumns, rows.size(),\n                                      rowColumnCounts);\n\n        const auto fwdBColumnGrains = ceildiv(bColumns, fwdBColumnGrainSize);\n        const auto fwdNumUsedWorkers = fwdNumAPartitions * fwdNumBPartitions;\n        const auto fwdMaxPartitionARows =\n            ceildiv(rows.size(), fwdNumAPartitions);\n        const auto fwdMaxPartitionBColumnGrains =\n            ceildiv(fwdBColumnGrains, fwdNumBPartitions);\n\n        std::vector<unsigned> fwdPartitionAElemOffsets(fwdNumAPartitions, 0);\n        for (unsigned partition = 1; partition < fwdNumAPartitions;\n             ++partition) {\n          const auto prevPartitionARowStart =\n              (partition - 1) * fwdMaxPartitionARows;\n          const auto prevPartitionARowEnd = partition * fwdMaxPartitionARows;\n          fwdPartitionAElemOffsets[partition] =\n              fwdPartitionAElemOffsets[partition - 1] +\n              std::accumulate(rowColumnCounts.begin() + prevPartitionARowStart,\n                              rowColumnCounts.begin() + prevPartitionARowEnd,\n                              unsigned(0));\n        }\n\n        unsigned gradWNumUsedWorkers, gradWBColumnGrainSize,\n            gradWNumAPartitions = 0;\n        if (generateGradWMetaInfo) {\n          std::tie(gradWBColumnGrainSize, gradWNumAPartitions) =\n              getGradWWorkerPartition(target, inputType, bColumns, rows.size(),\n                                      rowColumnCounts);\n          gradWNumUsedWorkers = gradWNumAPartitions;\n        }\n\n        metaInfo[bucket].emplace_back(processedSubGroupId);\n        const auto processedSubGroupNumElems = subGroupNumElems[bucket].at(i);\n        const auto elemsPerNzElem = generateGradAMetaInfo ? 2 : 1;\n\n        metaInfo[bucket].emplace_back(xPartition);\n        metaInfo[bucket].emplace_back(yPartition);\n        metaInfo[bucket].emplace_back(processedSubGroupNumElems);\n        const auto totalMetaInfoElems =\n            9 + fwdNumUsedWorkers * 5 + rows.size() * 2 +\n            processedSubGroupNumElems * elemsPerNzElem +\n            (generateGradWMetaInfo ? 1 + 4 * gradWNumUsedWorkers : 0);\n        const auto offsetToFirstOutputEntry =\n            totalMetaInfoElems -\n            (rows.size() * 2 + processedSubGroupNumElems * elemsPerNzElem);\n\n        metaInfo[bucket].emplace_back(totalMetaInfoElems);\n        metaInfo[bucket].emplace_back(bColumns);\n        metaInfo[bucket].emplace_back(rows.size() - 1);\n        metaInfo[bucket].emplace_back(offsetToFirstOutputEntry);\n        metaInfo[bucket].emplace_back(fwdNumUsedWorkers);\n\n        // Reserve space for worker entries\n        std::vector<std::size_t> metaInfoFwdWorkerEntryIndices(\n            fwdNumUsedWorkers);\n        for (unsigned worker = 0; worker < fwdNumUsedWorkers; ++worker) {\n          metaInfoFwdWorkerEntryIndices[worker] = metaInfo[bucket].size();\n          for (std::size_t i = 0; i < 5; ++i) {\n            metaInfo[bucket].emplace_back(~0u);\n          }\n        }\n\n        // If needed reserve space for GradW worker entries\n        std::vector<unsigned> metaInfoGradWWorkerEntryIndices;\n        if (generateGradWMetaInfo) {\n          metaInfo[bucket].emplace_back(gradWNumUsedWorkers);\n\n          metaInfoGradWWorkerEntryIndices.resize(gradWNumUsedWorkers);\n          for (unsigned worker = 0; worker < gradWNumUsedWorkers; ++worker) {\n            metaInfoGradWWorkerEntryIndices[worker] = metaInfo[bucket].size();\n            for (std::size_t i = 0; i < 4; ++i) {\n              metaInfo[bucket].emplace_back(~0u);\n            }\n          }\n        }\n\n        // Output row -> column list meta-info\n        std::vector<unsigned> outputEntryMetaInfoIndices(rows.size());\n        std::size_t offsetGradA = 0;\n        for (std::size_t r = 0; r < rows.size(); ++r) {\n          const auto aRow = indices.at(nzOffset)[0];\n          // First entry is offset into output memory to process.\n          // bColumns are inner-most dimension.\n          const auto aRowOffsetInC = aRow;\n          outputEntryMetaInfoIndices[r] = metaInfo[bucket].size();\n          metaInfo[bucket].push_back(aRowOffsetInC);\n          // Use 1 less for float input type\n          metaInfo[bucket].push_back(rowColumnCounts[r]);\n          for (unsigned c = 0; c < rowColumnCounts[r]; ++c) {\n            if (generateGradAMetaInfo) {\n              metaInfo[bucket].push_back(yOffsetFactor * offsetGradA++);\n            }\n            metaInfo[bucket].push_back(indices.at(nzOffset)[1] * bColumns *\n                                       yOffsetFactor);\n            ++nzOffset;\n          }\n        }\n\n        // Fill out worklist info for each worker\n        for (unsigned worker = 0; worker < fwdNumUsedWorkers; ++worker) {\n          const auto aPartitionIdx = worker % fwdNumAPartitions;\n          const auto bPartitionIdx = worker / fwdNumAPartitions;\n          const auto aRowIndex = aPartitionIdx * fwdMaxPartitionARows;\n          const auto aRowEndIndex =\n              std::min((aPartitionIdx + 1) * fwdMaxPartitionARows, rows.size());\n          const auto bColumnIndex = bPartitionIdx *\n                                    fwdMaxPartitionBColumnGrains *\n                                    fwdBColumnGrainSize;\n          const auto bColumnEndIndex =\n              std::min((bPartitionIdx + 1) * fwdMaxPartitionBColumnGrains *\n                           fwdBColumnGrainSize,\n                       bColumns);\n          const auto workerEntryIndex = metaInfoFwdWorkerEntryIndices[worker];\n          metaInfo[bucket][workerEntryIndex + 0] =\n              generateGradAMetaInfo ? 0\n                                    : fwdPartitionAElemOffsets[aPartitionIdx];\n          metaInfo[bucket][workerEntryIndex + 1] =\n              bColumnEndIndex - bColumnIndex;\n          metaInfo[bucket][workerEntryIndex + 2] = bColumnIndex;\n          // Number is 1 less\n          metaInfo[bucket][workerEntryIndex + 3] = aRowEndIndex - aRowIndex - 1;\n          metaInfo[bucket][workerEntryIndex + 4] =\n              outputEntryMetaInfoIndices[aRowIndex] - workerEntryIndex;\n        }\n\n        if (generateGradWMetaInfo) {\n          const auto totalAElems = std::accumulate(\n              rowColumnCounts.begin(), rowColumnCounts.end(), std::size_t(0));\n          const auto numAElemsPerPartition =\n              ceildiv(totalAElems, gradWNumAPartitions);\n          unsigned currRowIndex = 0;\n          unsigned currRowColumnIndex = 0;\n          for (unsigned worker = 0; worker < gradWNumUsedWorkers; ++worker) {\n            const auto sparseStartIndex = worker * numAElemsPerPartition;\n            const auto sparseEndIndex =\n                std::min((worker + 1) * numAElemsPerPartition, totalAElems);\n            const auto numSparseElems = sparseEndIndex - sparseStartIndex;\n\n            unsigned startRowIndex = currRowIndex;\n            unsigned startRowStartColumnIndex = currRowColumnIndex;\n            const auto workerEntryIndex =\n                metaInfoGradWWorkerEntryIndices[worker];\n            metaInfo[bucket][workerEntryIndex + 0] = sparseStartIndex;\n            metaInfo[bucket][workerEntryIndex + 1] =\n                outputEntryMetaInfoIndices[startRowIndex] - workerEntryIndex;\n            metaInfo[bucket][workerEntryIndex + 2] = startRowStartColumnIndex;\n            metaInfo[bucket][workerEntryIndex + 3] = numSparseElems;\n\n            // Advance to next worker's work\n            unsigned numRemainingElems = numSparseElems;\n            while (numRemainingElems > 0) {\n              const auto elemsThisRow =\n                  std::min(numRemainingElems,\n                           rowColumnCounts[currRowIndex] - currRowColumnIndex);\n              numRemainingElems -= elemsThisRow;\n              currRowColumnIndex += elemsThisRow;\n              if (currRowColumnIndex >= rowColumnCounts[currRowIndex]) {\n                currRowColumnIndex = 0;\n                currRowIndex++;\n              }\n            }\n          }\n        }\n        ++splitIdx;\n      } else {\n        const auto otherSubGroupIdx = i - splitIdx;\n        const auto subGroupId = otherSubGroupIds[otherSubGroupIdx];\n        const auto numElems = subGroupNumElems[bucket][i];\n        metaInfo[bucket].emplace_back(subGroupId);\n        // Enforce a large numbered partition to go with sub group IDs that\n        // aren't to be used.\n        metaInfo[bucket].emplace_back(0xffff);\n        metaInfo[bucket].emplace_back(0xffff);\n        metaInfo[bucket].emplace_back(numElems);\n        // We also just use this no. of sub-elements as garbage in the meta-info\n        // for the other (unprocessed) sub-groups.\n        metaInfo[bucket].emplace_back(numElems + 5);\n        for (std::size_t i = 0; i < numElems; ++i) {\n          metaInfo[bucket].emplace_back(garbageDist(randomEngine));\n        }\n      }\n    }\n    constexpr unsigned endSubGroupId = 0;\n    metaInfo[bucket].push_back(endSubGroupId);\n  }\n\n  return metaInfo;\n}\n\ntemplate std::vector<std::array<unsigned, 2>>\ngenerateSparseIndices<std::mt19937>(std::mt19937 &randomEngine,\n                                    const std::vector<std::size_t> &shape,\n                                    std::size_t n);\n\ntemplate std::vector<std::vector<unsigned>>\ngenerateMetaInfoAndPartition<std::mt19937>(\n    std::mt19937 &randomEngine, std::vector<std::array<unsigned, 2>> &indices,\n    const std::vector<std::size_t> &aShape,\n    const std::vector<std::size_t> &bShape, unsigned numBuckets,\n    unsigned processedSubGroupId, const std::vector<unsigned> &otherSubGroupIds,\n    const std::vector<std::vector<unsigned>> processedSubGroupIndices,\n    const std::vector<std::vector<unsigned>> &subGroupNumElems,\n    const Target &target, const Type &inputType, const Type &partialType,\n    VertexType vertexType, unsigned xPartition, unsigned yPartition);\n", "meta": {"hexsha": "72d24bfea3cfa1ccfecf3376e5f1fa306ffd32e3", "size": 17224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popsparse/codelets/SparseDensePartitionElementWise.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": "tests/popsparse/codelets/SparseDensePartitionElementWise.cpp", "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": "tests/popsparse/codelets/SparseDensePartitionElementWise.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "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": 44.8541666667, "max_line_length": 80, "alphanum_fraction": 0.6562354854, "num_tokens": 4127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.18332315269996857}}
{"text": "// SPDX-License-Identifier: MIT\n// The MIT License (MIT)\n//\n// Copyright (c) 2014-2018, Institute for Software & Systems Engineering\n// Copyright (c) 2018-2019, Johannes Leupolz\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 \"pemc/lmc/lmc_model_checker.h\"\n\n#include <boost/timer/timer.hpp>\n#include <utility>\n#include <vector>\n\n#include \"pemc/basic/exceptions.h\"\n#include \"pemc/formula/formula_utils.h\"\n\nnamespace {\nusing namespace pemc;\nusing boost::timer::cpu_timer;\n\nenum PrecalculatedTransition : uint8_t {\n  Nothing = 0,\n  SatisfiedDirect = 1,\n  ExcludedDirect = 2,\n  Satisfied = 4,  // Satisfied for the current run\n  Excluded = 8,   // Excluded for the current run\n  Mark = 16,\n};\n\nvoid calculateIteration(Lmc& lmc,\n                        gsl::span<PrecalculatedTransition> precalculations,\n                        gsl::span<Probability> xold,\n                        gsl::span<Probability> xnew) {\n  auto stateCount = lmc.getStates().size();\n  for (StateIndex s = 0; s < stateCount; ++s) {\n    auto transitions = lmc.getTransitions();\n    auto sum = Probability::Zero();\n    TransitionIndex begin, end = 0;\n    std::tie(begin, end) = lmc.getTransitionIndexesOfState(s);\n\n    for (TransitionIndex t = begin; t < end; t++) {\n      auto& transition = transitions[t];\n      auto& precalulated = precalculations[t];\n      if (precalulated & PrecalculatedTransition::Satisfied) {\n        sum += transition.probability;\n\n      } else if (precalulated & PrecalculatedTransition::Excluded) {\n      } else {\n        sum += transition.probability * xold[transition.state];\n      }\n    }\n    xnew[s] = sum;\n  }\n}\n\nProbability calculateInitialProbability(\n    Lmc& lmc,\n    gsl::span<PrecalculatedTransition> precalculations,\n    gsl::span<Probability> x) {\n  auto transitions = lmc.getTransitions();\n  auto sum = Probability::Zero();\n  TransitionIndex begin, end = 0;\n  std::tie(begin, end) = lmc.getInitialTransitionIndexes();\n\n  for (TransitionIndex t = begin; t < end; t++) {\n    auto& transition = transitions[t];\n    auto& precalulated = precalculations[t];\n    if (precalulated & PrecalculatedTransition::Satisfied) {\n      sum += transition.probability;\n    } else if (precalulated & PrecalculatedTransition::Excluded) {\n    } else {\n      sum += transition.probability * x[transition.state];\n    }\n  }\n  return sum;\n}\n\nvoid precalculateDirectSatisfactionAndExclusion(\n    Lmc& lmc,\n    gsl::span<PrecalculatedTransition> precalculatedTransitions,\n    Formula* phi,\n    Formula* psi,\n    std::ostream& cout) {\n  cout << \"Precalculate transitions that are directly satisfied or excluded. \"\n       << std::endl;\n  cpu_timer timer;\n\n  auto psiEvaluator = lmc.createLabelBasedFormulaEvaluator(psi);\n  std::function<bool(TransitionIndex)> returnFalse = [](TransitionIndex t) {\n    return false;\n  };\n  auto phiEvaluator =\n      phi != nullptr ? lmc.createLabelBasedFormulaEvaluator(psi) : returnFalse;\n\n  // bitwise or casts uint8_t implicitly to int\n  auto satisfied =\n      (PrecalculatedTransition)(PrecalculatedTransition::SatisfiedDirect |\n                                PrecalculatedTransition::Satisfied);\n  auto excluded =\n      (PrecalculatedTransition)(PrecalculatedTransition::ExcludedDirect |\n                                PrecalculatedTransition::Excluded);\n\n  for (TransitionIndex t = 0; t < precalculatedTransitions.size(); t++) {\n    if (psiEvaluator(t)) {\n      precalculatedTransitions[t] = satisfied;\n    } else if (phiEvaluator(t)) {\n      precalculatedTransitions[t] = excluded;\n    } else {\n      precalculatedTransitions[t] = PrecalculatedTransition::Nothing;\n    }\n  }\n\n  timer.stop();\n  auto elapsedTime = timer.elapsed();\n  auto elapsedTimeStr = format(elapsedTime);\n  cout << \"\\t\\tFinished in \" << elapsedTimeStr << \".\" << std::endl;\n}\n\nProbability calculateBoundedUntil(Lmc& lmc,\n                                  Formula* phi,\n                                  Formula* psi,\n                                  int bound,\n                                  std::ostream& cout) {\n  cpu_timer timer;\n\n  auto transitions = lmc.getTransitions();\n  std::vector<PrecalculatedTransition> precalculations(transitions.size());\n  precalculateDirectSatisfactionAndExclusion(lmc, precalculations, phi, psi,\n                                             cout);\n\n  auto stateCount = lmc.getStates().size();\n  auto probablityVector1 = std::vector<Probability>(stateCount);\n  auto probablityVector2 = std::vector<Probability>(stateCount);\n  auto xold = gsl::span<Probability>(probablityVector1);\n  auto xnew = gsl::span<Probability>(probablityVector2);\n\n  for (auto i = 0; i < bound; i++) {\n    calculateIteration(lmc, precalculations, xold, xnew);\n    std::swap(xold, xnew);\n\n    if (i % 10 == 0) {\n      cout << \"Calculated \" << i << \" iterations\" << std::endl;\n    }\n  }\n\n  auto result = calculateInitialProbability(lmc, precalculations, xold);\n\n  timer.stop();\n  auto elapsedTime = timer.elapsed();\n  auto elapsedTimeStr = format(elapsedTime);\n\n  return result;\n}\n}  // namespace\n\nnamespace pemc {\n\nusing boost::timer::cpu_timer;\n\nLmcModelChecker::LmcModelChecker(Lmc& _lmc, const Configuration& _conf)\n    : lmc(_lmc), conf(_conf){};\n\nProbability LmcModelChecker::calculateProbability(Formula& formulaToCheck) {\n  auto matchFormula = tryExtractPhiUntilPsiWithBound(formulaToCheck);\n  if (matchFormula == std::nullopt)\n    return Probability::Error();\n  Formula* phi;\n  Formula* psi;\n  std::optional<int> bound;\n  std::tie(phi, psi, bound) = *matchFormula;\n\n  *conf.cout << \"Checking formula: \" << formulaToString(formulaToCheck)\n             << std::endl;\n\n  if (bound != std::nullopt) {\n    return calculateBoundedUntil(lmc, phi, psi, *bound, *conf.cout);\n  } else {\n    // CalculateUnboundUntil\n    throw NotImplementedYetException();\n  }\n\n  return Probability::Error();\n}\n\n}  // namespace pemc\n", "meta": {"hexsha": "db5631ae07a4e5daaba3e094803993bb7c07bca4", "size": 6851, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pemc/lmc/lmc_model_checker.cc", "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "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": "pemc/lmc/lmc_model_checker.cc", "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pemc/lmc/lmc_model_checker.cc", "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": ["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.7487684729, "max_line_length": 80, "alphanum_fraction": 0.6765435703, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.18297634246844513}}
{"text": "#include <turbodbc/make_description.h>\n\n#include <turbodbc/descriptions.h>\n#include <sqlext.h>\n\n#include <boost/variant/apply_visitor.hpp>\n\n#include <stdexcept>\n#include <sstream>\n#include <algorithm>\n\n\nnamespace turbodbc {\n\nnamespace {\n\nSQLULEN const digits_representable_by_64_bit_integer = 18;\n\n/*\n * This function returns a buffer size for the given string\n * which leaves room for future, larger strings.\n *\n * The intent is to waste little space for small strings while\n * keeping the number of required buffer rebinds small.\n */\nstd::size_t size_after_growth_strategy(std::size_t const & size)\n{\n    std::size_t const minimum_size = 10;\n    if (size < minimum_size) {\n        return minimum_size;\n    }\n    return std::ceil(size * 1.2);\n}\n\nstd::unique_ptr<description const> make_small_decimal_description(cpp_odbc::column_description const & source)\n{\n    if (source.decimal_digits == 0) {\n        return std::unique_ptr<description>(new integer_description(source.name, source.allows_null_values));\n    } else {\n        return std::unique_ptr<description>(new floating_point_description(source.name, source.allows_null_values));\n    }\n}\n\nstd::unique_ptr<description const> make_large_decimal_description(cpp_odbc::column_description const & source, turbodbc::options const & options)\n{\n    if (options.large_decimals_as_64_bit_types) {\n        return make_small_decimal_description(source);\n    } else {\n        // fall back to strings; add two characters for decimal point and sign!\n        return std::unique_ptr<description>(new string_description(source.name,\n                                                                   source.allows_null_values,\n                                                                   source.size + 2));\n    }\n}\n\nstd::unique_ptr<description const> make_decimal_description(cpp_odbc::column_description const & source, turbodbc::options const & options)\n{\n    if (source.size <= digits_representable_by_64_bit_integer) {\n        return make_small_decimal_description(source);\n    } else {\n        return make_large_decimal_description(source, options);\n    }\n}\n\nusing description_ptr = description const *;\n\nstruct description_by_value : public boost::static_visitor<description_ptr> {\n    description_ptr operator()(int64_t const &) const\n    {\n        return new integer_description;\n    }\n\n    description_ptr operator()(double const &) const\n    {\n        return new floating_point_description;\n    }\n\n    description_ptr operator()(bool const &) const\n    {\n        return new boolean_description;\n    }\n\n    description_ptr operator()(boost::gregorian::date const &) const\n    {\n        return new date_description;\n    }\n\n    description_ptr operator()(boost::posix_time::ptime const &) const\n    {\n        return new timestamp_description;\n    }\n\n    description_ptr operator()(std::string const & s) const\n    {\n        auto const target_size = size_after_growth_strategy(s.size());\n        return new string_description(target_size);\n    }\n};\n\n\ntemplate <typename Description>\nstd::unique_ptr<description> make_character_description(cpp_odbc::column_description const & source,\n                                                        turbodbc::options const & options)\n{\n    int const capacity_multiplier = (options.force_extra_capacity_for_unicode ? Description::max_code_units_per_unicode_code_point : 1);\n    std::size_t const sanitized_size = (source.size == 0 ? options.varchar_max_character_limit : source.size);\n    std::size_t const limited_size = (options.limit_varchar_results_to_max ?\n                                      std::min(sanitized_size, options.varchar_max_character_limit) :\n                                      sanitized_size) * capacity_multiplier;\n    return std::unique_ptr<description>(new Description(source.name,\n                                                        source.allows_null_values,\n                                                        limited_size));\n}\n\n}\n\n\n\nstd::unique_ptr<description const> make_description(cpp_odbc::column_description const & source,\n                                                    turbodbc::options const & options)\n{\n    switch (source.data_type) {\n        case SQL_CHAR:\n        case SQL_VARCHAR:\n        case SQL_LONGVARCHAR:\n            if (options.prefer_unicode) {\n                return make_character_description<unicode_description>(source, options);\n            } else {\n                return make_character_description<string_description>(source, options);\n            }\n        case SQL_WVARCHAR:\n        case SQL_WLONGVARCHAR:\n        case SQL_WCHAR:\n            if (options.fetch_wchar_as_char) {\n                return make_character_description<string_description>(source, options);\n            } else {\n                return make_character_description<unicode_description>(source, options);\n            }\n        case SQL_INTEGER:\n        case SQL_SMALLINT:\n        case SQL_BIGINT:\n        case SQL_TINYINT:\n            return std::unique_ptr<description>(new integer_description(source.name, source.allows_null_values));\n        case SQL_REAL:\n        case SQL_FLOAT:\n        case SQL_DOUBLE:\n            return std::unique_ptr<description>(new floating_point_description(source.name, source.allows_null_values));\n        case SQL_BIT:\n            return std::unique_ptr<description>(new boolean_description(source.name, source.allows_null_values));\n        case SQL_NUMERIC:\n        case SQL_DECIMAL:\n            return make_decimal_description(source, options);\n        case SQL_TYPE_DATE:\n            return std::unique_ptr<description>(new date_description(source.name, source.allows_null_values));\n        case SQL_TYPE_TIMESTAMP:\n            return std::unique_ptr<description>(new timestamp_description(source.name, source.allows_null_values));\n        default:\n            std::ostringstream message;\n            message << \"Error! Unsupported type identifier for column \" << source << \")\";\n            throw std::runtime_error(message.str());\n    }\n}\n\n\nstd::unique_ptr<description const> make_description(field const & value)\n{\n    return std::unique_ptr<description const>(boost::apply_visitor(description_by_value{}, value));\n}\n\nstd::unique_ptr<description const> make_description(type_code type, std::size_t size)\n{\n    switch (type) {\n        case type_code::floating_point:\n            return std::unique_ptr<description const>(new floating_point_description);\n        case type_code::boolean:\n            return std::unique_ptr<description const>(new boolean_description);\n        case type_code::date:\n            return std::unique_ptr<description const>(new date_description);\n        case type_code::timestamp:\n            return std::unique_ptr<description const>(new timestamp_description);\n        case type_code::string:\n            return std::unique_ptr<description const>(new string_description(size_after_growth_strategy(size)));\n        case type_code::unicode:\n            return std::unique_ptr<description const>(new unicode_description(size_after_growth_strategy(size)));\n        default:\n            return std::unique_ptr<description const>(new integer_description);\n    }\n}\n\n}\n", "meta": {"hexsha": "43953db96dc59ce40e73ecfa8692dc1acd01d624", "size": 7166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/turbodbc/Library/src/make_description.cpp", "max_stars_repo_name": "arikfr/turbodbc", "max_stars_repo_head_hexsha": "80a29a7edfbdabf12410af01c0c0ae74bfc3aab4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 537.0, "max_stars_repo_stars_event_min_datetime": "2016-03-18T21:46:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T04:43:17.000Z", "max_issues_repo_path": "cpp/turbodbc/Library/src/make_description.cpp", "max_issues_repo_name": "arikfr/turbodbc", "max_issues_repo_head_hexsha": "80a29a7edfbdabf12410af01c0c0ae74bfc3aab4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 325.0, "max_issues_repo_issues_event_min_datetime": "2016-04-08T11:54:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T23:58:42.000Z", "max_forks_repo_path": "cpp/turbodbc/Library/src/make_description.cpp", "max_forks_repo_name": "arikfr/turbodbc", "max_forks_repo_head_hexsha": "80a29a7edfbdabf12410af01c0c0ae74bfc3aab4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T13:55:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T02:32:26.000Z", "avg_line_length": 37.5183246073, "max_line_length": 145, "alphanum_fraction": 0.6656433157, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1829763424684451}}
{"text": "/**\n * @file blmc_joint_module.hpp\n * @author Manuel Wuthrich\n * @author Maximilien Naveau (maximilien.naveau@gmail.com)\n * @author Julian Viereck (jviereck@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck\n * Gesellschaft.\n * @date 2020-02-17\n */\n#pragma once\n\n#include <math.h>\n#include <Eigen/Eigen>\n#include <array>\n#include <iostream>\n#include <stdexcept>\n\n#include \"blmc_drivers/devices/motor.hpp\"\n#include \"solo/common_header.hpp\"\n\n#include \"master_board_sdk/defines.h\"\n#include \"master_board_sdk/master_board_interface.h\"\n\n#include <stdexcept>\n\nnamespace solo\n{\n/**\n * @brief This class defines an interface to a collection of BLMC joints. It\n * creates a BLMCJointModule for every blmc_driver::MotorInterface provided.\n */\ntemplate <int COUNT>\nclass SpiJointModules\n{\npublic:\n    /**\n     * @brief Defines a static Eigen vector type in order to define the\n     * interface.\n     */\n    typedef Eigen::Matrix<double, COUNT, 1> Vector;\n\n    /**\n     * @brief Construct a new SpiJointModules object.\n     */\n    SpiJointModules(std::shared_ptr<MasterBoardInterface> robot_if,\n                    std::array<int, COUNT>& motor_to_card_index,\n                    std::array<int, COUNT>& motor_to_card_port_index,\n                    const Vector& motor_constants,\n                    const Vector& gear_ratios,\n                    const Vector& zero_angles,\n                    const Vector& max_currents,\n                    std::array<bool, COUNT> reverse_polarities)\n    {\n        robot_if_ = robot_if;\n\n        // Setup the motor vectores based on the card and port mapping.\n        for (int i = 0; i < COUNT; i++)\n        {\n            int driver_idx = motor_to_card_index[i];\n            if (motor_to_card_port_index[i] == 0)\n            {\n                motors_[i] = (robot_if->motor_drivers[driver_idx].motor1);\n            }\n            else\n            {\n                motors_[i] = (robot_if->motor_drivers[driver_idx].motor2);\n            }\n\n            polarities_[i] = reverse_polarities[i] ? -1. : 1.;\n        }\n\n        motor_constants_ = motor_constants;\n        gear_ratios_ = gear_ratios;\n        zero_angles_ = zero_angles;\n        max_currents_ = max_currents;\n\n        motor_to_card_index_ = motor_to_card_index;\n\n        index_angles_.fill(0.);\n    }\n\n    /**\n     * @brief Enable all motors and motor drivers used by the joint module.\n     */\n    void enable()\n    {\n        for (int i = 0; i < COUNT; i++)\n        {\n            int driver_idx = motor_to_card_index_[i];\n            robot_if_->motor_drivers[driver_idx].motor1->SetCurrentReference(0);\n            robot_if_->motor_drivers[driver_idx].motor2->SetCurrentReference(0);\n            robot_if_->motor_drivers[driver_idx].motor1->Enable();\n            robot_if_->motor_drivers[driver_idx].motor2->Enable();\n            robot_if_->motor_drivers[driver_idx].EnablePositionRolloverError();\n            robot_if_->motor_drivers[driver_idx].SetTimeout(5);\n            robot_if_->motor_drivers[driver_idx].Enable();\n        }\n        robot_if_->SendCommand();\n    }\n\n    /**\n     * @brief Checks if all motors report ready.\n     *\n     * @return True if all motors are ready, false otherwise.\n     */\n    bool is_ready()\n    {\n        for (int i = 0; i < COUNT; i++)\n        {\n            if (!motors_[i]->IsEnabled() || !motors_[i]->IsReady())\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    std::array<bool, COUNT> get_motor_enabled()\n    {\n        std::array<bool, COUNT> motor_enabled;\n        for (int i = 0; i < COUNT; i++)\n        {\n            motor_enabled[i] = motors_[i]->IsEnabled();\n        }\n        return motor_enabled;\n    }\n\n    std::array<bool, COUNT> get_motor_ready()\n    {\n        std::array<bool, COUNT> motor_ready;\n        for (int i = 0; i < COUNT; i++)\n        {\n            motor_ready[i] = motors_[i]->IsReady();\n        }\n        return motor_ready;\n    }\n\n    /**\n     * @brief Send the registered torques to all modules.\n     */\n    void send_torques()\n    {\n        robot_if_->SendCommand();\n    }\n\n    /**\n     * @brief Updates the measurements based on the lastest package from\n     * the master board.\n     */\n    void acquire_sensors()\n    {\n        robot_if_->ParseSensorData();\n\n        // Keep tack of the first recorded encoder.\n        Vector positions = get_measured_angles();\n        for (int i = 0; i < COUNT; i++)\n        {\n            if (saw_index_[i] == false && motors_[i]->HasIndexBeenDetected())\n            {\n                saw_index_[i] = true;\n                index_angles_[i] = positions(i);\n            }\n        }\n    }\n\n    /**\n     * @brief Register the joint torques to be sent for all modules.\n     *\n     * @param desired_torques (Nm)\n     */\n    void set_torques(const Vector& desired_torques)\n    {\n        Vector desired_current = polarities_.cwiseProduct(desired_torques)\n                                     .cwiseQuotient(gear_ratios_)\n                                     .cwiseQuotient(motor_constants_);\n\n        // Current clamping.\n        desired_current = desired_current.cwiseMin(max_currents_);\n        desired_current = desired_current.cwiseMax(-max_currents_);\n        // Vector desired_current;\n        // desired_current.setZero();\n\n        for (std::size_t i = 0; i < motors_.size(); i++)\n        {\n            motors_[i]->SetCurrentReference(desired_current(i));\n        }\n    }\n\n    /**\n     * @brief Get the maximum admissible joint torque that can be applied.\n     *\n     * @return Vector (N/m)\n     */\n    Vector get_max_torques()\n    {\n        return max_currents_.cwiseProduct(gear_ratios_)\n            .cwiseProduct(motor_constants_);\n    }\n\n    /**\n     * @brief Get the previously sent torques.\n     *\n     * @return Vector (Nm)\n     */\n    Vector get_sent_torques() const\n    {\n        Vector torques;\n        for (size_t i = 0; i < COUNT; i++)\n        {\n            torques(i) = motors_[i]->current_ref;\n        }\n        torques = torques.cwiseProduct(polarities_)\n                      .cwiseProduct(gear_ratios_)\n                      .cwiseProduct(motor_constants_);\n        return torques;\n    }\n\n    /**\n     * @brief Get the measured joint torques.\n     *\n     * @return Vector (Nm)\n     */\n    Vector get_measured_torques() const\n    {\n        Vector torques;\n        for (size_t i = 0; i < COUNT; i++)\n        {\n            torques(i) = motors_[i]->GetCurrent();\n        }\n        torques = torques.cwiseProduct(polarities_)\n                      .cwiseProduct(gear_ratios_)\n                      .cwiseProduct(motor_constants_);\n        return torques;\n    }\n\n    /**\n     * @brief Get the measured joint angles.\n     *\n     * @return Vector (rad)\n     */\n    Vector get_measured_angles() const\n    {\n        Vector positions;\n        for (size_t i = 0; i < COUNT; i++)\n        {\n            positions(i) = motors_[i]->GetPosition();\n        }\n        positions =\n            positions.cwiseProduct(polarities_).cwiseQuotient(gear_ratios_) -\n            zero_angles_;\n        return positions;\n    }\n\n    /**\n     * @brief Get the measured joint velocities.\n     *\n     * @return Vector (rad/s)\n     */\n    Vector get_measured_velocities() const\n    {\n        Vector velocities;\n        for (size_t i = 0; i < COUNT; i++)\n        {\n            velocities(i) = motors_[i]->GetVelocity();\n        }\n        velocities =\n            velocities.cwiseProduct(polarities_).cwiseQuotient(gear_ratios_);\n        return velocities;\n    }\n\n    /**\n     * @brief Set the zero_angles. These are the joint angles between the\n     * starting pose and the zero theoretical pose of the urdf.\n     *\n     * @param zero_angles (rad)\n     */\n    void set_zero_angles(const Vector& zero_angles)\n    {\n        zero_angles_ = zero_angles;\n    }\n    /**\n     * @brief Get the zero_angles. These are the joint angles between the\n     * starting pose and the zero theoretical pose of the urdf.\n     *\n     * @return Vector (rad)\n     */\n    Vector get_zero_angles() const\n    {\n        return zero_angles_;\n    }\n    /**\n     * @brief Get the index_angles. There is one index per motor rotation so\n     * there are gear_ratio indexes per joint rotation.\n     *\n     * @return Vector (rad)\n     */\n    Vector get_measured_index_angles() const\n    {\n        return index_angles_;\n    }\n\nprivate:\n    Vector motor_constants_;\n    Vector gear_ratios_;\n    Vector max_currents_;\n    Vector zero_angles_;\n    Vector polarities_;\n\n    std::array<int, COUNT> motor_to_card_index_;\n\n    Vector index_angles_;\n    std::array<bool, COUNT> saw_index_;\n\n    /**\n     * @brief Holds the motors in the joint order.\n     */\n    std::array<Motor*, COUNT> motors_;\n\n    std::shared_ptr<MasterBoardInterface> robot_if_;\n};\n\n}  // namespace solo\n", "meta": {"hexsha": "4743ce8d290db11be5232a724bf30026be268cb7", "size": 8813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solo/spi_joint_module.hpp", "max_stars_repo_name": "caoliheng/solo", "max_stars_repo_head_hexsha": "e6d86f54e05977a533c68e30c85a5048a03ab753", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T03:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T14:06:50.000Z", "max_issues_repo_path": "include/solo/spi_joint_module.hpp", "max_issues_repo_name": "caoliheng/solo", "max_issues_repo_head_hexsha": "e6d86f54e05977a533c68e30c85a5048a03ab753", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-19T13:54:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T08:53:49.000Z", "max_forks_repo_path": "include/solo/spi_joint_module.hpp", "max_forks_repo_name": "caoliheng/solo", "max_forks_repo_head_hexsha": "e6d86f54e05977a533c68e30c85a5048a03ab753", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T16:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T16:13:36.000Z", "avg_line_length": 27.200617284, "max_line_length": 80, "alphanum_fraction": 0.5741518212, "num_tokens": 2104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1829763424684451}}
{"text": "/*\nCopyright 2015-2016 Joanna Hulboj <j@hulboj.org>\nCopyright 2016 Milosz Hulboj <m@hulboj.org>\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#include \"vanilla_date.h\"\n\n#include \"util/parse.h\"\n\n#include <boost/spirit/include/karma.hpp>\n\n#include <contrib/date/date.h>\n#include <chrono>\n#include <functional>\n#include <iterator>\n\nnamespace cornelich\n{\n\n\nstd::int32_t cycle_formatter::cycle_from_date(const std::string & date) const\n{\n    return cycle_from_date_impl(date);\n}\n\nstd::string cycle_formatter::date_from_cycle(std::int64_t cycle) const\n{\n    // TODO: Is it worth it...?\n    auto hash = std::hash<std::int64_t>()(cycle) % (CACHE_SIZE - 1);\n    auto cached = std::atomic_load(&m_cache[hash]);\n    if(cached && cached->m_cycle == cycle)\n    {\n        // Cache hit - return the string\n        return cached->m_data;\n    }\n    // Cache miss -> evaluate and cache the string\n    auto node = std::make_shared<node_t>(cycle, date_from_cycle_impl(cycle));\n    std::atomic_store(&m_cache[hash], node);\n    return node->m_data;\n}\n\n\nusing namespace date;\nusing namespace std::chrono;\nusing namespace boost::spirit;\n\nstatic const day_point unix_epoch = day(1)/jan/1970;\n\nbool parse_date(const std::string & date, day_point & dp)\n{\n    int y = 0, m = 0, d = 0;\n    if(BOOST_UNLIKELY(\n                !util::parse_number(date.begin(), date.begin() + 4, y) ||\n                !util::parse_number(date.begin() + 4, date.begin() + 6, m) ||\n                !util::parse_number(date.begin() + 6, date.begin() + 8, d)))\n    {\n        return false;\n    }\n    auto ymd = year(y)/m/d;\n    dp = ymd;\n    return ymd.ok();\n}\n\nstd::int64_t get_epoch_seconds(const system_clock::time_point & ts)\n{\n    day_point today = time_point_cast<days>(ts);\n    system_clock::time_point this_morning = today;\n    days days_since_epoch = today - unix_epoch;\n    auto s = ts - this_morning;\n    std::int64_t unix_timestamp = (days_since_epoch + s) / seconds(1);\n    return unix_timestamp;\n}\n\nstd::int32_t cycle_formatter_yyyymmdd::cycle_from_date_impl(const std::string & date) const\n{\n    thread_local day_point dp;\n    if(BOOST_UNLIKELY(date.length() != 8))\n        return -1;\n    if(BOOST_UNLIKELY(!parse_date(date, dp)))\n        return -1;\n    system_clock::time_point ts = dp;\n    auto unix_timestamp = get_epoch_seconds(ts);\n\n    return unix_timestamp * 1000 / m_cycle_length;\n}\n\nstd::string cycle_formatter_yyyymmdd::date_from_cycle_impl(std::int64_t cycle) const\n{\n    const auto s = static_cast<std::time_t>(cycle * m_cycle_length / 1000);\n    auto ts = system_clock::time_point(seconds(s));\n    auto daypoint = floor<days>(ts);\n    auto ymd = year_month_day(daypoint);\n\n    using namespace boost::spirit;\n\n    std::string result;\n    std::back_insert_iterator<std::string> sink(result);\n    karma::generate(sink,\n                    karma::right_align(4, '0')[karma::int_] << karma::right_align(2, '0')[karma::uint_] << karma::right_align(2, '0')[karma::uint_],\n            int(ymd.year()), unsigned(ymd.month()), unsigned(ymd.day()));\n    return result;\n}\n\nstd::int32_t cycle_formatter_yyyymmddhh::cycle_from_date_impl(const std::string & date) const\n{\n    thread_local day_point dp;\n    int h = 0;\n    if(BOOST_UNLIKELY(date.length() != 10))\n        return -1;\n    if(BOOST_UNLIKELY(\n                !parse_date(date, dp) ||\n                !util::parse_number(date.begin() + 8, date.begin() + 10, h) || h > 24))\n        return -1;\n    system_clock::time_point ts = dp + hours(h);\n    auto unix_timestamp = get_epoch_seconds(ts);\n\n    return unix_timestamp * 1000 / m_cycle_length;\n}\n\nstd::string cycle_formatter_yyyymmddhh::date_from_cycle_impl(std::int64_t cycle) const\n{\n    const auto s = static_cast<std::time_t>(cycle * m_cycle_length / 1000);\n    auto ts = system_clock::time_point(seconds(s));\n    auto daypoint = floor<days>(ts);\n    auto ymd = year_month_day(daypoint);\n    auto tod = make_time(ts - daypoint);\n\n    using namespace boost::spirit;\n\n    std::string result;\n    std::back_insert_iterator<std::string> sink(result);\n    karma::generate(sink,\n                    karma::right_align(4, '0')[karma::int_] << karma::right_align(2, '0')[karma::uint_] << karma::right_align(2, '0')[karma::uint_] << karma::right_align(2, '0')[karma::uint_],\n            int(ymd.year()), unsigned(ymd.month()), unsigned(ymd.day()), tod.hours().count());\n    return result;\n}\n\nstd::int32_t cycle_formatter_yyyymmddhhmm::cycle_from_date_impl(const std::string & date) const\n{\n    thread_local day_point dp;\n    int h = 0, min = 0;\n    if(BOOST_UNLIKELY(date.length() != 12))\n        return -1;\n    if(BOOST_UNLIKELY(\n                !parse_date(date, dp) ||\n                !util::parse_number(date.begin() + 8, date.begin() + 10, h) || h > 24 ||\n                !util::parse_number(date.begin() + 10, date.begin() + 12, min) || min > 60\n                ))\n        return -1;\n\n    system_clock::time_point ts = dp + hours(h) + minutes(min);\n    auto unix_timestamp = get_epoch_seconds(ts);\n\n    return unix_timestamp * 1000 / m_cycle_length;\n}\n\nstd::string cycle_formatter_yyyymmddhhmm::date_from_cycle_impl(std::int64_t cycle) const\n{\n    const auto s = static_cast<std::time_t>(cycle * m_cycle_length / 1000);\n    auto ts = system_clock::time_point(seconds(s));\n    auto daypoint = floor<days>(ts);\n    auto ymd = year_month_day(daypoint);\n    auto tod = make_time(ts - daypoint);\n\n    using namespace boost::spirit;\n\n    std::string result;\n    std::back_insert_iterator<std::string> sink(result);\n    karma::generate(sink,\n                    karma::right_align(4, '0')[karma::int_] << karma::right_align(2, '0')[karma::uint_] << karma::right_align(2, '0')[karma::uint_] << karma::right_align(2, '0')[karma::uint_] << karma::right_align(2, '0')[karma::uint_],\n            int(ymd.year()), unsigned(ymd.month()), unsigned(ymd.day()), tod.hours().count(), tod.minutes().count());\n    return result;\n}\n\n}\n", "meta": {"hexsha": "9b448e38f01b8376df6145b315663ad39f130340", "size": 6366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cornelich/vanilla_date.cpp", "max_stars_repo_name": "jh0x/cornelich", "max_stars_repo_head_hexsha": "ef9265d0bc1deefcd02571fe6b9b6ef4b17d013b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-09-26T07:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-10T09:11:00.000Z", "max_issues_repo_path": "cornelich/vanilla_date.cpp", "max_issues_repo_name": "jfhk/cornelich", "max_issues_repo_head_hexsha": "ef9265d0bc1deefcd02571fe6b9b6ef4b17d013b", "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": "cornelich/vanilla_date.cpp", "max_forks_repo_name": "jfhk/cornelich", "max_forks_repo_head_hexsha": "ef9265d0bc1deefcd02571fe6b9b6ef4b17d013b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-01-26T16:54:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T03:45:04.000Z", "avg_line_length": 33.8617021277, "max_line_length": 236, "alphanum_fraction": 0.6588124411, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3522017820478897, "lm_q1q2_score": 0.18297633540340255}}
{"text": "/* \n * File:   score_calculator.cpp\n * Author: malone\n * \n * Created on November 24, 2012, 5:46 PM\n */\n\n#include <algorithm>\n#include <math.h>\n\n#include <boost/dynamic_bitset.hpp>\n#include <limits>\n\n#include <boost/thread.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include \"score_calculator.h\"\n#include \"scoring_function.h\"\n\nscoring::ScoreCalculator::ScoreCalculator(scoring::ScoringFunction *scoringFunction, int maxParents, int variableCount, int runningTime, scoring::Constraints *constraints) {\n    this->scoringFunction = scoringFunction;\n    this->maxParents = maxParents;\n    this->variableCount = variableCount;\n    this->runningTime = runningTime;\n    this->constraints = constraints;\n}\n\nvoid scoring::ScoreCalculator::timeout(const boost::system::error_code& /*e*/) {\n    printf(\"Out of time\\n\");\n    outOfTime = true;\n}\n\nvoid scoring::ScoreCalculator::calculateScores(int variable, FloatMap &cache, varset & neighbors) {\n    this->outOfTime = false;\n    \n    //io.reset();\n    //boost::asio::deadline_timer *t;\n    boost::asio::io_service io_t;\n    t = new boost::asio::deadline_timer(io_t);\n    if (runningTime > 0) {\n        printf(\"I am using a timer in the calculation function.\\n\");\n        t->expires_from_now(boost::posix_time::seconds(runningTime));\n        t->async_wait(boost::bind(&scoring::ScoreCalculator::timeout, this, boost::asio::placeholders::error));\n        boost::thread workerThread(boost::bind(&scoring::ScoreCalculator::calculateScores_internal, this, variable, boost::ref(cache), boost::ref(neighbors)));\n        io_t.run();\n        workerThread.join();\n        io_t.stop();\n//        t.cancel();\n    } else {\n        calculateScores_internal(variable, cache, neighbors);\n    }\n}\n\nvoid scoring::ScoreCalculator::calculateScores_internal(int variable, FloatMap &cache, varset & neighbors) {\n    // calculate the initial score\n    VARSET_NEW(empty, variableCount);\n    float score = scoringFunction->calculateScore(variable, empty, cache);\n    \n    if (score < 1) {\n        cache[empty] = score;\n    }\n    \n    int prunedCount = 0;\n    // Ni added, record the neighbors' indices\n    std::vector<int> neighbor_indices;\n    for(int  i = 0; i  < variableCount; i++)\n    {\n        if(VARSET_GET(neighbors,  i))\n        {\n            //printf(\"Will map compact bit # %d to neighbor variable #%d, for variable %d\\n\", int(neighbor_indices.size()),  i, variable);\n            neighbor_indices.push_back(i);\n        }\n    }\n    const int num_neighbors = neighbor_indices.size();\n    \n    //printf(\"calculateScores_internal, variable %d has %d neighbors, total variable count  %d\\n\", variable, num_neighbors, variableCount);\n\n    for (int layer = 1; layer <= maxParents && !outOfTime; layer++) {\n#ifdef DEBUG\n        printf(\"layer: %d, prunedCount: %d\\n\", layer, prunedCount);\n#endif\n\n        VARSET_NEW(compact_variables, num_neighbors);\n        for (int i = 0; i < layer; i++) {\n            VARSET_SET(compact_variables, i);\n        }\n\n        VARSET_NEW(max, num_neighbors);\n        VARSET_SET(max, num_neighbors);\n        \n        while (VARSET_LESS_THAN(compact_variables, max) && !outOfTime) {\n            //Ni added, translate shorter bitset compact_variables to full-length bitset variables\n            VARSET_NEW(variables, variableCount);\n            for(int i = 0; i < num_neighbors; i++)\n            {\n                if(VARSET_GET(compact_variables, i))\n                    VARSET_SET(variables, neighbor_indices[i]);\n            }\n            \n            if (!VARSET_GET(variables, variable)) {\n            \n                \n                score = scoringFunction->calculateScore(variable, variables, cache);\n                \n#ifdef VERBOSE_DEBUG\n                printf(\"%d, %\" PRIu64 \": %f\\n\", variable, variables, score);\n#endif\n                \n                \n                // only store the score if it was not pruned\n                if (score < 0) {\n                    cache[variables] = score;\n                } else {\n                    prunedCount++;\n                }\n            }\n\n            // find the next combination\n            compact_variables = nextPermutation(compact_variables);\n        }\n        \n        if (!outOfTime) highestCompletedLayer = layer;\n    }\n    \n//    io.stop();\n    t->cancel();\n//    io.reset();\n\n#ifdef VERBOSE_DEBUG\n    printf(\"Scores\\n\");\n    for (auto it = cache.begin(); it != cache.end(); it++) {\n        printf(\"%d, %d: %f\\n\", variable, (*it).first, (*it).second);\n    }\n#endif\n}\n\nstruct compareSecond {\n\n    bool operator()(std::pair<varset, float> lhs, std::pair<varset, float> rhs) const {\n        float val = lhs.second - rhs.second;\n        \n        if (fabs(val) > 2 * std::numeric_limits<float>::epsilon()) {\n            return val > 0;\n        }\n        \n        return lhs.first < rhs.first;\n    }\n} comparator;\n\nvoid scoring::ScoreCalculator::prune(FloatMap &cache) {\n    std::vector< std::pair<varset, float> > pairs;\n    for (auto pair = cache.begin();\n            pair != cache.end();\n            pair++) {\n        pairs.push_back(*pair);\n    }\n    \n    std::sort(pairs.begin(), pairs.end(), comparator);\n\n#ifdef VERBOSE_DEBUG\n    printf(\"Sorted Scores\\n\");\n    for (auto it = pairs.begin(); it != pairs.end(); it++) {\n        printf(\"%d: %f\\n\", (*it).first, (*it).second);\n    }\n#endif\n    \n    // keep track of the ones that have been pruned\n    boost::dynamic_bitset<> prunedSets(pairs.size());\n    for (int i = 0; i < pairs.size(); i++) {\n        if (prunedSets.test(i)) {\n            continue;\n        }\n\n        varset pi = pairs[i].first;\n        \n        // make sure this variable set is not in an incomplete last layer\n        if (cardinality(pi) > highestCompletedLayer) {\n            prunedSets.set(i);\n            continue;\n        }\n\n        for (int j = i + 1; j < pairs.size(); j++) {\n            if (prunedSets.test(j)) {\n                continue;\n            }\n\n            // check if parents[i] is a subset of parents[j]\n            varset pj = pairs[j].first;\n            \n            if (VARSET_IS_SUBSET_OF(pi, pj)) {\n                // then we can prune pj\n                prunedSets.set(j);\n                cache.erase(pj);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "16024d5c00bb8a6069a781d42fac27dc6ba38a61", "size": 6206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "urlearning/scoring_function/score_calculator.cpp", "max_stars_repo_name": "ninalu/urlearning-cpp", "max_stars_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "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": "urlearning/scoring_function/score_calculator.cpp", "max_issues_repo_name": "ninalu/urlearning-cpp", "max_issues_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "urlearning/scoring_function/score_calculator.cpp", "max_forks_repo_name": "ninalu/urlearning-cpp", "max_forks_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T04:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-12T04:17:55.000Z", "avg_line_length": 31.3434343434, "max_line_length": 173, "alphanum_fraction": 0.5776667741, "num_tokens": 1466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.1829763318708813}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2013 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_POLICIES_ROBUSTNESS_SEGMENT_RATIO_HPP\n#define BOOST_GEOMETRY_POLICIES_ROBUSTNESS_SEGMENT_RATIO_HPP\n\n#include <boost/config.hpp>\n#include <boost/rational.hpp>\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n\nnamespace detail { namespace segment_ratio\n{\n\ntemplate\n<\n    typename Type,\n    bool IsIntegral = geofeatures_boost::is_integral<Type>::type::value\n>\nstruct less {};\n\ntemplate <typename Type>\nstruct less<Type, true>\n{\n    template <typename Ratio>\n    static inline bool apply(Ratio const& lhs, Ratio const& rhs)\n    {\n        return geofeatures_boost::rational<Type>(lhs.numerator(), lhs.denominator())\n             < geofeatures_boost::rational<Type>(rhs.numerator(), rhs.denominator());\n    }\n};\n\ntemplate <typename Type>\nstruct less<Type, false>\n{\n    template <typename Ratio>\n    static inline bool apply(Ratio const& lhs, Ratio const& rhs)\n    {\n        BOOST_GEOMETRY_ASSERT(lhs.denominator() != 0);\n        BOOST_GEOMETRY_ASSERT(rhs.denominator() != 0);\n        return lhs.numerator() * rhs.denominator()\n             < rhs.numerator() * lhs.denominator();\n    }\n};\n\ntemplate\n<\n    typename Type,\n    bool IsIntegral = geofeatures_boost::is_integral<Type>::type::value\n>\nstruct equal {};\n\ntemplate <typename Type>\nstruct equal<Type, true>\n{\n    template <typename Ratio>\n    static inline bool apply(Ratio const& lhs, Ratio const& rhs)\n    {\n        return geofeatures_boost::rational<Type>(lhs.numerator(), lhs.denominator())\n            == geofeatures_boost::rational<Type>(rhs.numerator(), rhs.denominator());\n    }\n};\n\ntemplate <typename Type>\nstruct equal<Type, false>\n{\n    template <typename Ratio>\n    static inline bool apply(Ratio const& lhs, Ratio const& rhs)\n    {\n        BOOST_GEOMETRY_ASSERT(lhs.denominator() != 0);\n        BOOST_GEOMETRY_ASSERT(rhs.denominator() != 0);\n        return geometry::math::equals\n            (\n                lhs.numerator() * rhs.denominator(),\n                rhs.numerator() * lhs.denominator()\n            );\n    }\n};\n\n}}\n\n//! Small class to keep a ratio (e.g. 1/4)\n//! Main purpose is intersections and checking on 0, 1, and smaller/larger\n//! The prototype used Boost.Rational. However, we also want to store FP ratios,\n//! (so numerator/denominator both in float)\n//! and Boost.Rational starts with GCD which we prefer to avoid if not necessary\n//! On a segment means: this ratio is between 0 and 1 (both inclusive)\n//!\ntemplate <typename Type>\nclass segment_ratio\n{\npublic :\n    typedef Type numeric_type;\n\n    // Type-alias for the type itself\n    typedef segment_ratio<Type> thistype;\n\n    inline segment_ratio()\n        : m_numerator(0)\n        , m_denominator(1)\n        , m_approximation(0)\n    {}\n\n    inline segment_ratio(const Type& nominator, const Type& denominator)\n        : m_numerator(nominator)\n        , m_denominator(denominator)\n    {\n        initialize();\n    }\n\n    inline Type const& numerator() const { return m_numerator; }\n    inline Type const& denominator() const { return m_denominator; }\n\n    inline void assign(const Type& nominator, const Type& denominator)\n    {\n        m_numerator = nominator;\n        m_denominator = denominator;\n        initialize();\n    }\n\n    inline void initialize()\n    {\n        // Minimal normalization\n        // 1/-4 => -1/4, -1/-4 => 1/4\n        if (m_denominator < 0)\n        {\n            m_numerator = -m_numerator;\n            m_denominator = -m_denominator;\n        }\n\n        m_approximation =\n            m_denominator == 0 ? 0\n            : geofeatures_boost::numeric_cast<double>\n                (\n                    geofeatures_boost::numeric_cast<fp_type>(m_numerator) * scale()\n                  / geofeatures_boost::numeric_cast<fp_type>(m_denominator)\n                );\n    }\n\n    inline bool is_zero() const { return math::equals(m_numerator, 0); }\n    inline bool is_one() const { return math::equals(m_numerator, m_denominator); }\n    inline bool on_segment() const\n    {\n        // e.g. 0/4 or 4/4 or 2/4\n        return m_numerator >= 0 && m_numerator <= m_denominator;\n    }\n    inline bool in_segment() const\n    {\n        // e.g. 1/4\n        return m_numerator > 0 && m_numerator < m_denominator;\n    }\n    inline bool on_end() const\n    {\n        // e.g. 0/4 or 4/4\n        return is_zero() || is_one();\n    }\n    inline bool left() const\n    {\n        // e.g. -1/4\n        return m_numerator < 0;\n    }\n    inline bool right() const\n    {\n        // e.g. 5/4\n        return m_numerator > m_denominator;\n    }\n\n    inline bool near_end() const\n    {\n        if (left() || right())\n        {\n            return false;\n        }\n\n        static fp_type const small_part_of_scale = scale() / 100.0;\n        return m_approximation < small_part_of_scale\n            || m_approximation > scale() - small_part_of_scale;\n    }\n\n    inline bool close_to(thistype const& other) const\n    {\n        return geometry::math::abs(m_approximation - other.m_approximation) < 2;\n    }\n\n    inline bool operator< (thistype const& other) const\n    {\n        return close_to(other)\n            ? detail::segment_ratio::less<Type>::apply(*this, other)\n            : m_approximation < other.m_approximation;\n    }\n\n    inline bool operator== (thistype const& other) const\n    {\n        return close_to(other)\n            && detail::segment_ratio::equal<Type>::apply(*this, other);\n    }\n\n    static inline thistype zero()\n    {\n        static thistype result(0, 1);\n        return result;\n    }\n\n    static inline thistype one()\n    {\n        static thistype result(1, 1);\n        return result;\n    }\n\n#if defined(BOOST_GEOMETRY_DEFINE_STREAM_OPERATOR_SEGMENT_RATIO)\n    friend std::ostream& operator<<(std::ostream &os, segment_ratio const& ratio)\n    {\n        os << ratio.m_numerator << \"/\" << ratio.m_denominator\n           << \" (\" << (static_cast<double>(ratio.m_numerator)\n                        / static_cast<double>(ratio.m_denominator))\n           << \")\";\n        return os;\n    }\n#endif\n\n\n\nprivate :\n    typedef typename promote_floating_point<Type>::type fp_type;\n\n    Type m_numerator;\n    Type m_denominator;\n\n    // Contains ratio on scale 0..1000000 (for 0..1)\n    // This is an approximation for fast and rough comparisons\n    // Boost.Rational is used if the approximations are close.\n    // Reason: performance, Boost.Rational does a GCD by default and also the\n    // comparisons contain while-loops.\n    fp_type m_approximation;\n\n\n    static inline fp_type scale()\n    {\n        return 1000000.0;\n    }\n};\n\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_POLICIES_ROBUSTNESS_SEGMENT_RATIO_HPP\n", "meta": {"hexsha": "100164a8afd024a13d60d7ccc493c28734bb998f", "size": 7117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/policies/robustness/segment_ratio.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/policies/robustness/segment_ratio.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/policies/robustness/segment_ratio.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 27.5852713178, "max_line_length": 116, "alphanum_fraction": 0.6373471969, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.3276683139517237, "lm_q1q2_score": 0.1829460696838004}}
{"text": "/*\n SuperCollider real time audio synthesis system\n Copyright (c) 2002 James McCartney. All rights reserved.\n http://www.audiosynth.com\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\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA\n */\n\n//UGen by Nick Collins\n//Released under the GNU GPL as extensions for SuperCollider 3\n\n//cmake -DSC_PATH=/data/gitprojects/SuperCollider -DCMAKE_OSX_ARCHITECTURES='x86_64' ..\n\n//NOTE: there are certain assumptions in this code about the size of the input and output (currently 2048 frames of spectral data). However, more general UGens are possible based on adapting more of Kerasify, etc. The current code should work with deeper nets as long as input and output at size 2048\n//It is also worth saying that realtime deep learning with smaller spectral frames gets very intensive; with the NRT thread it will never keep up, but there is a possibility of adapting KerasifyA\n\n\n//uses Kerasify, thank you Robert W. Rose\n//https://github.com/moof2k/kerasify\n//note that this dependency could probably be removed, e.g. I've rolled my own neural net here since Kerasify itself wasn't realtime memory management efficient, but use Kerasify for export from python and loading a model in the UGen, to save writing my own export/import too.\n\n//if use NRT via DoAsynchronousCommand, too slow\n//if try to call model in RT, too much load for one block\n\n//two solutions are possible\n//amortiseflag = 0) PV_Kerasify: otherwise must write own thread, see DiskIO_UGens.cpp, potential issues with setting thread priority, but in practice does work out OK (just don't use DoAsynchronousCommand, that NRT thread on the server is far too slow)\n//https://stackoverflow.com/questions/18884510/portable-way-of-setting-stdthread-priority-in-c11\n//https://chromium.googlesource.com/chromium/src/base/+/master/threading/platform_thread_mac.mm\n//https://stackoverflow.com/questions/10876342/equivalent-of-setthreadpriority-on-linux-pthreads\n\n//amortiseflag = 1) Can only amortise over blocks if write own model calculations (going a layer at a time per block, etc). Did try going a layer at a time in Kerasify itself, but it was still too slow. So wrote own net implementation. First block sets up data, subsequent blocks calculate a layer of the network at a time\n//assumes network not so deep that more layers than available blocks...\n\n\n#include \"keras_model.h\"\n\n#include \"SC_PlugIn.h\"\n#include <math.h>\n#include <stdlib.h>\n#include \"FFT_UGens.h\"\n#include <time.h>\n\n//int messagecounter = 0;\n\nclock_t start, end;\ndouble cpu_time_used;\n\n\nInterfaceTable *ft; \n\n\n//those supported by kerasify, keras has a few more\n//https://keras.io/activations/\nenum {\n    activation_linear,\n    activation_relu,\n    activation_softplus,\n    activation_sigmoid,\n    activation_tanh,\n    activation_hardsigmoid\n};\n\n//public by default\nstruct NCLayer {\n    \n    int inputsize;\n    int numunits;\n    float * connectionmatrix;//rows by columns, as flat array\n    float * bias;\n    int activationtype;\n    float * output;\n    \n};\n\n//assumes sizes all fine\nvoid CalculateNCLayer(NCLayer* layer, float * input) {\n    \n    int i,j;\n    float unitsum;\n    \n    int inputsize = layer->inputsize;\n    float * matrix = layer->connectionmatrix;\n    float * bias = layer->bias;\n    int activation = layer->activationtype;\n    float calc;\n    float * output = layer->output;\n    \n    for (i=0; i<layer->numunits; ++i) {\n        \n        unitsum = 0.0f;\n        float * weightsnow = matrix + (i*inputsize);\n        \n        for (j=0; j<inputsize; ++j)\n        {\n            unitsum += weightsnow[j] * input[j];\n            \n        }\n        \n        unitsum += bias[i];\n        \n        //nothing to do for linear?\n        //activation function\n        switch(activation) {\n            \n            case activation_relu:\n            if(unitsum<0.0) unitsum = 0.0;\n            break;\n            \n            case activation_softplus:\n            unitsum = log(1.0 + exp(unitsum));\n            break;\n            case activation_sigmoid: {\n                float x = unitsum;\n                \n                if (x >= 0) {\n                    unitsum = 1.0 / (1.0 + exp(-x));\n                } else {\n                    float z = exp(x);\n                    unitsum = z / (1.0 + z);\n                }\n            }\n            break;\n            case activation_tanh:\n            unitsum = tanh(unitsum);\n            break;\n            case activation_hardsigmoid: {\n                \n                float x = (unitsum * 0.2) + 0.5;\n                \n                if (x <= 0) {\n                    unitsum = 0.0;\n                } else if (x >= 1) {\n                    unitsum = 1.0;\n                } else {\n                    unitsum = x;\n                }\n                \n            }\n            break;\n            \n            default:\n            break;\n        }\n        \n        output[i] = unitsum;\n        \n    }\n    \n    \n}\n\n\n\nvoid CalculateNCLayerAmort(NCLayer* layer, float * input, int startunit, int unitstodo) {\n    \n    int i,j;\n    float unitsum;\n    \n    int inputsize = layer->inputsize;\n    float * matrix = layer->connectionmatrix;\n    float * bias = layer->bias;\n    int activation = layer->activationtype;\n    float calc;\n    float * output = layer->output;\n    \n    int endunit = startunit+unitstodo;\n    \n    if(endunit>layer->numunits) {\n        \n        endunit = layer->numunits;\n    }\n    \n    for (i=startunit; i<endunit; ++i) {\n        \n        unitsum = 0.0f;\n        float * weightsnow = matrix + (i*inputsize);\n        \n        for (j=0; j<inputsize; ++j)\n        {\n            unitsum += weightsnow[j] * input[j];\n            \n        }\n        \n        unitsum += bias[i];\n        \n        //nothing to do for linear?\n        //activation function\n        switch(activation) {\n            \n            case activation_relu:\n            if(unitsum<0.0) unitsum = 0.0;\n            break;\n            \n            case activation_softplus:\n            unitsum = log(1.0 + exp(unitsum));\n            break;\n            case activation_sigmoid: {\n                float x = unitsum;\n                \n                if (x >= 0) {\n                    unitsum = 1.0 / (1.0 + exp(-x));\n                } else {\n                    float z = exp(x);\n                    unitsum = z / (1.0 + z);\n                }\n            }\n            break;\n            case activation_tanh:\n            unitsum = tanh(unitsum);\n            break;\n            case activation_hardsigmoid: {\n                \n                float x = (unitsum * 0.2) + 0.5;\n                \n                if (x <= 0) {\n                    unitsum = 0.0;\n                } else if (x >= 1) {\n                    unitsum = 1.0;\n                } else {\n                    unitsum = x;\n                }\n                \n            }\n            break;\n            \n            default:\n            break;\n        }\n        \n        output[i] = unitsum;\n        \n    }\n    \n    \n}\n\n\n\n\n//KerasModel * g_model;\n\nstruct PV_Kerasify : public Unit\n{\n    //int m_n;\n    //float * m_topn;\n    //int * m_topnindices;\n    \n    char * path;\n    \n    KerasModel * model;\n    \n    float * phases; //[2048];\n    float * spectrumnow;\n    \n    //no longer needed, rolled own network below\n    // Create a 1D Tensor on length 10 for input data.\n    //Tensor * in; //(2048);\n    //float datafortensor[2048];\n    // Run prediction.\n    //Tensor * out;\n    \n    bool modelready;\n    bool newoutput;\n    \n    //roll own neural network\n    float * input;\n    int numlayers;\n    NCLayer * layers;\n    float * output;\n    \n    int amortisationflag;\n    int amortisationcounter;\n    \n    float * currentinputpointer; //used in amortisation to shift active input data\n    //int amortschedulelayer[100];\n    //int amortscheduleindexstart[100];\n    //int amortscheduleunitstodo[100];\n    \n    \n    \n};\n\n\n#include \"SC_SyncCondition.h\"\n#include <atomic>\n//#include <new>\n//#include <functional>\n#include <thread>\n//#include \"SC_Lock.h\"\n#include <boost/lockfree/queue.hpp>\n#include <boost/lockfree/spsc_queue.hpp>\n\nenum {\n    kCmd_Ctor,\n    kCmd_Run,\n    kCmd_Dtor,\n};\n\nstruct KerasifyMsg\n{\n    //        World *mWorld;\n    int16 mCommand;\n    int counter;\n    //        int16 mChannels;\n    //        int32 mBufNum;\n    //        int32 mPos;\n    //        int32 mFrames;\n    \n    PV_Kerasify * unit;\n    \n    void Perform();\n};\n\nvoid KerasifyMsg::Perform()\n{\n    //PV_Kerasify* unit = (PV_Kerasify*)unit;\n    \n    switch (mCommand) {\n        case kCmd_Run : {\n            \n            //printf(\"before apply \\n\");\n            \n            // Run prediction.\n            //Tensor out(2048); // &out\n            \n            //out.PrintShape();\n            //printf(\"after print \\n\");\n            \n            //printf(\"thread which %d model %p unit %p %p %p\\n\",counter, (void*)g_model, (void*)unit, (void*)unit->in, (void*)unit->out);\n            \n            //printf(\"unit %f %f %f\\n\", unit->spectrumnow[0],unit->spectrumnow[1],unit->spectrumnow[2]);\n            \n            //unit->in->PrintShape();\n            //unit->out->PrintShape();\n            \n            //start = clock();\n            //... /* Do the work. */\n            \n            //unit->model->Apply(unit->in, unit->out);\n            //end = clock();\n            //cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;\n            \n            //printf(\"took %f seconds to execute \\n\", cpu_time_used);\n            \n            \n            \n            float * input = unit->input;\n            \n            for (int k=0; k<unit->numlayers; ++k) {\n                \n                CalculateNCLayer(&unit->layers[k],input);\n                \n                input = unit->layers[k].output;\n                \n            }\n            \n            //final input pointer points to final layer output\n            for (int i=0; i<2048; ++i) {\n                \n                unit->spectrumnow[i] = input[i]; //((i*i)%17)/17.0;\n            }\n            \n            //printf(\"unit %f %f %f\\n\", unit->spectrumnow[0],unit->spectrumnow[1],unit->spectrumnow[2]);\n            \n            \n            \n            \n            unit->newoutput = true;\n            \n            \n        }\n        break;\n        case kCmd_Ctor :\n        {\n            \n            // Initialize model.\n            \n            //unit->in = new Tensor(2048);\n            //unit->out = new Tensor(2048);\n            \n            // Create a 1D Tensor on length 10 for input data.\n            //Tensor in(2048);\n            //std::vector<float> data_;\n            //float data[2048];\n            \n            //for (int i=0; i<2048; ++i) {\n            \n            //  data[i] = 0.0f; //((i*i)%17)/17.0;\n            //}\n            \n            //https://stackoverflow.com/questions/259297/how-do-you-copy-the-contents-of-an-array-to-a-stdvector-in-c-without-looping\n            //in.data_.insert(in.data_.end(), &data[0], &data[2048]);\n            \n            //unit->in->data_.insert(unit->in->data_.end(), &data[0], &data[2048]);\n            \n            //unit->out->data_.insert(unit->out->data_.end(), &data[0], &data[2048]);\n            \n            //in.data_ = data;\n            //in.data_ = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};\n            \n            //g_model = new KerasModel();\n            //g_model->LoadModel(unit->path); //\"DNN1.model\");\n            \n            \n            unit->model = new KerasModel();\n            \n            unit->model->LoadModel(unit->path); //\"DNN1.model\");\n            \n            //unit->in.data_.insert(unit->in.data_.end(), &(unit->datafortensor[0]), &(unit->datafortensor[2048]));\n            \n            printf(\"loaded %s\\n\",unit->path);\n            \n            //copy model data to my own local struct\n            \n            unit->input = new float[2048];\n            \n            unit->numlayers = unit->model->layers_.size();\n            \n            unit->layers = new NCLayer[unit->numlayers];\n            \n            for (int k=0; k<unit->numlayers; ++k) {\n                \n                //inputsize  * outputsize\n                Tensor * weights_ = &(((KerasLayerDense*)unit->model->layers_[k])->weights_);\n                Tensor * biases_ = &(((KerasLayerDense*)unit->model->layers_[k])->biases_);\n                \n                float * matrix = new float[weights_->dims_[0] * weights_->dims_[1]];\n                float * bias = new float[biases_->dims_[0]];\n                \n                int inputsize = weights_->dims_[0];\n                \n                unit->layers[k].inputsize = inputsize;\n                unit->layers[k].numunits = weights_->dims_[1];\n                \n                \n                for (int i = 0; i < weights_->dims_[1]; i++) {\n                    \n                    float * target = matrix + (inputsize*i);\n                    \n                    for (int j = 0; j < weights_->dims_[0]; j++) {\n                        target[j] = (*weights_)(j, i);\n                    }\n                }\n                \n                for (int i = 0; i < biases_->dims_[0]; i++) {\n                    bias[i] = (*biases_)(i);\n                }\n                \n                unit->layers[k].connectionmatrix = matrix;\n                unit->layers[k].bias = bias;\n                \n                unit->layers[k].output = new float[biases_->dims_[0]];\n                \n                \n                int type = ((KerasLayerDense*)unit->model->layers_[k])->activation_.activation_type_;\n                //KerasLayerActivation::ActivationType\n                \n                unit->layers[k].activationtype = activation_linear;\n                \n                \n                if(type == KerasLayerActivation::ActivationType::kRelu) unit->layers[k].activationtype = activation_relu;\n                \n                if(type == KerasLayerActivation::ActivationType::kSoftPlus) unit->layers[k].activationtype = activation_softplus;\n                \n                if(type == KerasLayerActivation::ActivationType::kSigmoid) unit->layers[k].activationtype = activation_sigmoid;\n                \n                if(type == KerasLayerActivation::ActivationType::kTanh) unit->layers[k].activationtype = activation_tanh;\n                \n                if(type == KerasLayerActivation::ActivationType::kHardSigmoid) unit->layers[k].activationtype = activation_hardsigmoid;\n                \n                \n                \n                printf(\"layer number %d type %d inputsize %d numunits %d \\n\",k, type, inputsize, unit->layers[k].numunits);\n                \n            }\n            \n            \n            \n            printf(\"Set up internal model data structure with %d layers\\n\", unit->numlayers);\n            \n            // Run prediction.\n            //Tensor out;\n            \n            //            start = clock();\n            //            //... /* Do the work. */\n            //            unit->model->Apply(unit->in, unit->out);\n            //            end = clock();\n            //            cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;\n            //\n            //            printf(\"first time took %f seconds to execute \\n\", cpu_time_used);\n            //\n            \n            unit-> modelready = true;\n            \n            \n        }\n        break;\n        case kCmd_Dtor :\n        {\n            //problem if unit already deallocated by this point\n            //delete unit->in;\n            //delete unit->out;\n            delete unit->model;\n            \n            for (int k=0; k<unit->numlayers; ++k) {\n                \n                delete [] unit->layers[k].connectionmatrix;\n                delete [] unit->layers[k].bias;\n                delete [] unit->layers[k].output;\n                \n            }\n            \n            delete [] unit->layers;\n            delete [] unit->input;\n            \n            \n        }\n        break;\n    }\n    \n}\n\nstruct KerasifyThread\n{\n    SC_SyncCondition mKerasifyFifoHasData;\n    \n#ifdef SUPERNOVA\n    boost::lockfree::queue<KerasifyMsg, boost::lockfree::capacity<256> > mKerasifyFifo;\n#else\n    boost::lockfree::spsc_queue<KerasifyMsg, boost::lockfree::capacity<256> > mKerasifyFifo;\n#endif\n    \n    std::atomic<bool> mRunning;\n    std::thread mThread;\n    \n    KerasifyThread():\n    mRunning(false)\n    {}\n    \n    ~KerasifyThread()\n    {\n        if (mRunning) {\n            mRunning.store(false);\n            mKerasifyFifoHasData.Signal();\n            mThread.join();\n        }\n    }\n    \n    void launchThread()\n    {\n        using namespace std;\n        mRunning.store(true);\n        \n        mThread = thread( bind(&KerasifyThread::kerasifyThreadFunc, this) ) ;\n    }\n    \n    bool Run(KerasifyMsg& data)\n    {\n        bool pushSucceeded = mKerasifyFifo.push(data);\n        if (pushSucceeded)\n        mKerasifyFifoHasData.Signal();\n        return pushSucceeded;\n    }\n    \n    void kerasifyThreadFunc()\n    {\n        while (mRunning.load()) {\n            mKerasifyFifoHasData.WaitEach();\n            \n            KerasifyMsg msg;\n            bool popSucceeded = mKerasifyFifo.pop(msg);\n            \n            if (popSucceeded)\n            msg.Perform();\n        }\n    }\n};\n\nKerasifyThread *gKerasify;\n\n\n\nextern \"C\" {  \n    \n    void PV_Kerasify_next(PV_Kerasify* unit, int inNumSamples);\n    void PV_Kerasify_Ctor(PV_Kerasify* unit);\n    void PV_Kerasify_Dtor(PV_Kerasify* unit);\n    \n}\n\n\n\n\nvoid PV_Kerasify_Ctor( PV_Kerasify* unit ) {\n    \n    //printf(\"PV_Kerasify_Ctor /n hello \\n\");\n    \n    unit-> amortisationflag = (int)ZIN0(1);\n    \n    unit-> amortisationcounter = 0;\n    \n    unit->modelready = false;\n    unit->newoutput = false;\n    \n    World *world = unit->mWorld;\n    \n    unit->phases = (float * ) RTAlloc(unit->mWorld, 2048*sizeof(float));\n    unit->spectrumnow = (float * ) RTAlloc(unit->mWorld, 2048*sizeof(float));\n    \n    for (int i=0; i<2048; ++i) {\n        \n        unit->phases[i] = 0.0f;\n        unit->spectrumnow[i] = 0.0f;\n    }\n    \n    int pathsize = (int) ZIN0(2);\n    \n    unit->path = (char *) RTAlloc(unit->mWorld,sizeof(char)*(pathsize+1));\n    \n    for(int i=0; i<pathsize; ++i) {\n        unit->path[i] = (char)ZIN0(3+i);\n    }\n    \n    unit->path[pathsize] = 0;\n    \n    printf(\"constructor for PV_Kerasify loading %s\\n\",unit->path);\n    \n    // send a message to side thread\n    KerasifyMsg msg;\n    msg.unit = unit;\n    //msg.counter = messagecounter;\n    msg.mCommand = kCmd_Ctor;\n    gKerasify->Run(msg);\n    \n    \n    SETCALC(PV_Kerasify_next);\n    ZOUT0(0) = ZIN0(0);\n    \n}\n\n\nvoid PV_Kerasify_Dtor( PV_Kerasify* unit ) {\n    \n    RTFree(unit->mWorld, unit->path);\n    \n    RTFree(unit->mWorld, unit->phases);\n    RTFree(unit->mWorld, unit->spectrumnow);\n    \n    // send a message to side thread\n    KerasifyMsg msg;\n    msg.unit = unit;\n    //msg.counter = messagecounter;\n    msg.mCommand = kCmd_Dtor;\n    gKerasify->Run(msg);\n    \n    \n}\n\n\nvoid PV_Kerasify_next( PV_Kerasify *unit, int inNumSamples ) {\n    \n    int i,j,k;\n    \n    if(unit-> amortisationcounter<=0) {\n        \n        float fbufnum = ZIN0(0);\n        \n        //if (fbufnum < 0.f) return;\n        \n        if (fbufnum < 0.f) { ZOUT0(0) = -1.f; return; }\n        ZOUT0(0) = fbufnum;\n        \n        int ibufnum = (uint32)fbufnum;\n        \n        World *world = unit->mWorld;\n        SndBuf *buf;\n        \n        if (ibufnum >= world->mNumSndBufs) {\n            int localBufNum = ibufnum - world->mNumSndBufs;\n            Graph *parent = unit->mParent;\n            if(localBufNum <= parent->localBufNum) {\n                buf = parent->mLocalSndBufs + localBufNum;\n            } else {\n                buf = world->mSndBufs;\n            }\n        } else {\n            buf = world->mSndBufs + ibufnum;\n        }\n        \n        LOCK_SNDBUF(buf);\n        \n        \n        if(unit-> modelready) {\n            \n            int numbins = (buf->samples - 2) >> 1;\n            \n            float * data = buf->data; //just use it, it is in form dc, nyquist then real,imag pairs per ascending band\n            \n            //SCComplexBuf* complex = ToComplexApx(buf);\n            //SCComplex * data = complex->bin;\n            //also dc, nyquist\n            \n            float real, imag;\n            \n            real = data[0]; //DC\n            \n            //unit->in->data_[0] = 0.09163326695 * log((real*real) + 1);\n            //unit->spectrumnow[0] = 0.09163326695 * log((real*real) + 1);\n            unit->input[0] = 0.09163326695 * log((real*real) + 1);\n            \n            unit->phases[0] = 0.0;\n            \n            //printf(\"before prep data \\n\");\n            \n            for  (j=1;j<numbins; ++j) {\n                \n                int index = 2*j;\n                \n                real = data[index];\n                imag = data[index+1];\n                \n                //0.5*Math.log(power+1)*scalefactor; //(1/5.456533600026138)\n                //float ampnow = sqrt((real*real) + (imag*imag));\n                \n                //relates to scale factor and log power encoding used for training neural net in first place with spectral data in range [0,1]\n                \n                //unit->in->data_[j] = 0.09163326695 * log((real*real) + (imag*imag) + 1);\n                \n                //unit->spectrumnow[j] = 0.09163326695 * log((real*real) + (imag*imag) + 1);\n                \n                unit->input[j] = 0.09163326695 * log((real*real) + (imag*imag) + 1);\n                \n                unit->phases[j] = atan2(imag, real);\n                \n            }\n            \n            unit->currentinputpointer = unit->input;\n            \n            \n            if(unit->newoutput) {\n                //musn't be replaced mid use, so need to only transfer over from a completed run\n                //previous output data potentially\n                //power spectrum back to complex (eg no phase, real only)\n                \n                float magnitude, phase;\n                \n                for (i = 0; i < numbins; ++i) {\n                    \n                    //out.data_[i] unit->out->data_[i] unit->out->data_[i]\n                    magnitude = exp((unit->spectrumnow[i])*5.456533600026138)-1;\n                    \n                    phase = unit->phases[i];\n                    \n                    //fftdata[2*i] = outputspectra.w[i]; //act.w[i]; //\n                    //return to magnitude not power\n                    data[2*i] =  magnitude * cos(phase);//Math.sqrt(Math.abs(outputspectra.w[i]));\n                    data[2*i+1] = magnitude * sin(phase); //0.0;\n                    \n                    //if(i<10) fftdata[2*i] = 0.0;\n                    \n                }\n                \n                unit->newoutput = false; //or not needed at all?\n            }\n            \n            \n            //printf(\"pre message %d model %p unit %p %p %p\\n\", messagecounter,(void*)g_model,(void*)unit, (void*)unit->in, (void*)unit->out);\n            \n            if(unit->amortisationflag==0) {\n                \n                // send a message to side thread\n                KerasifyMsg msg;\n                msg.unit = unit;\n                //msg.counter = messagecounter;\n                msg.mCommand = kCmd_Run;\n                \n                //++messagecounter;\n                \n                \n                //printf(\"sendMessage %d  %d %d %d\\n\", msg.mBufNum, msg.mPos, msg.mFrames, msg.mChannels);\n                gKerasify->Run(msg);\n                \n            } else\n            unit->amortisationcounter = 1; //unit->model->layers_.size();\n            \n            \n        }\n        \n        return;\n        \n    } else {\n        \n        //amortise layer by layer\n        //could refine to calculate parts of layers for further amortisation\n        //can create a schedule based on available blocks spread over calcs per layer and layers\n        \n        //printf(\"amortise flag %d counter %d layer %d of %d \\n\",unit->amortisationflag, unit->amortisationcounter, unit->amortisationcounter-1, unit->numlayers);\n        \n        //available amort periods before new spectral frame = (2048/64 - 1) = 31\n        //assuming 2048 hop, 64 sample block size\n        \n        int stepsperlayer = unit->amortisationflag; //let user set this\n        \n        float * input = unit->currentinputpointer;\n        \n        int layernum = (unit->amortisationcounter-1)/stepsperlayer; //split each layer into stepsperlayer\n        NCLayer * layernow = &unit->layers[layernum];\n        int layerstep = (unit->amortisationcounter-1)%stepsperlayer;\n        \n        int unitsavailableinlayer = layernow->numunits;\n        int totalperamortstep = unitsavailableinlayer/stepsperlayer; //assumes divisible by stepsperlayer, else add 1 to compensate\n        \n        if((totalperamortstep*stepsperlayer) < unitsavailableinlayer) {\n            totalperamortstep = totalperamortstep + 1;\n        }\n        \n        int startposforamortstep = totalperamortstep * layerstep;\n        \n        //printf(\"amortise flag %d counter %d layer %d of %d layernum %d layerste %d  unitsavailableinlayer %d totalperamortstep %d startposforamortstep %d \\n\",unit->amortisationflag, unit->amortisationcounter, unit->amortisationcounter-1, unit->numlayers, layernum, layerstep, unitsavailableinlayer, totalperamortstep, startposforamortstep);\n        \n        //all at once too high peak CPU\n        //CalculateNCLayer(layernow,input);\n        \n        CalculateNCLayerAmort(layernow,input,startposforamortstep,totalperamortstep);\n        \n        //if((startposforamortstep+totalperamortstep)>=unitsavailableinlayer)\n        if(layerstep==(stepsperlayer-1)) //just did final step of 4 per layer\n        {\n            unit->currentinputpointer = layernow->output;\n            input = unit->currentinputpointer;\n        }\n        \n        ++unit->amortisationcounter;\n        \n        //unit->amortisationcounter>unit->numlayers\n        if(unit->amortisationcounter>(unit->numlayers*stepsperlayer)) {\n            unit->amortisationcounter = 0;\n            \n            //final input pointer points to final layer output\n            for (int i=0; i<2048; ++i) {\n                \n                unit->spectrumnow[i] = input[i];\n            }\n            \n            unit->newoutput = true;\n        }\n        \n        //safety\n        ZOUT0(0) = -1.f;\n        return;\n        \n    }\n    \n    \n    /*\n     \n     \n     //amortise by hacking KerasModel class\n     //layers_ made public rather than private\n     //call from outside, a step at a time over layers\n     \n     //bool KerasModel::Apply(Tensor* in, Tensor* out) {\n     \n     Tensor *temp_in, *temp_out;\n     \n     //for (unsigned int i = 0; i < layers_.size(); i++) {\n     \n     if (unit->amortisationcounter == 1) {\n     temp_in = unit->in;\n     temp_out = unit->out;\n     } else {\n     \n     temp_in = unit->out;\n     temp_out = unit->in;\n     }\n     //printf(\"Apply layer %d of %d layer(s)\\n\", unit->amortisationcounter-1, unit->model->layers_.size());\n     \n     bool result = unit->model->layers_[unit->amortisationcounter-1]->Apply(temp_in, temp_out);\n     \n     if(!result) printf(\"Failed to apply layer %d \\n\", unit->amortisationcounter-1);\n     \n     *(unit->out) = *temp_out;\n     \n     \n     \n     //        Tensor temp_in, temp_out;\n     //\n     //        //for (unsigned int i = 0; i < layers_.size(); i++) {\n     //\n     //            if (unit->amortisationcounter == 1) {\n     //                temp_in = *(unit->in);\n     //            } else {\n     //\n     //                temp_in = *(unit->out);\n     //            }\n     //\n     //\n     //    printf(\"Apply layer %d of %d layer(s)\\n\", unit->amortisationcounter-1, unit->model->layers_.size());\n     //    bool result = unit->model->layers_[unit->amortisationcounter-1]->Apply(&temp_in, &temp_out);\n     //\n     //    if(!result) printf(\"Failed to apply layer %d \\n\", unit->amortisationcounter-1);\n     //\n     //            //temp_in = temp_out;\n     //        //}\n     //\n     //        //*out = temp_out;\n     //\n     //        *(unit->out) = temp_out;\n     //\n     ++unit->amortisationcounter;\n     \n     if(unit->amortisationcounter>unit->model->layers_.size()) {\n     unit->amortisationcounter = 0;\n     unit->newoutput = true;\n     }\n     \n     \n     //}\n     */\n    \n    \n    //NRT thread too slow\n    /*\n     //run model on latest data, will lag at least one spectral frame behind, but only way to amortise\n     CmdData* cmd = (CmdData*)RTAlloc(unit->mWorld, sizeof(CmdData));\n     //cmd->samplingrate_ = unit->mRate->mSampleRate;\n     cmd->unit = (Unit *)unit;\n     cmd->nrtallocated = NULL; //will be allocated in NRT thread\n     cmd->type = CmdData::NRTModelRunPV_Kerasify;\n     \n     DoAsynchronousCommand(unit->mWorld, 0, \"\", (void*)cmd,\n     (AsyncStageFn)cmdStage2,\n     (AsyncStageFn)cmdStage3,\n     NULL,\n     cmdCleanup,\n     0, 0);\n     \n     */\n    \n    \n    \n    \n    \n}\n\n\n\n\n\n\n\n\n#define DefinePVUnit(name) \\\n(*ft->fDefineUnit)(#name, sizeof(PV_Unit), (UnitCtorFunc)&name##_Ctor, 0, 0);\n\nC_LINKAGE SC_API_EXPORT void unload(InterfaceTable *inTable)\n{\n    delete gKerasify;\n}\n\nPluginLoad(PV_Kerasify)\n{\n    \n    init_SCComplex(inTable);\n    \n    ft = inTable;\n    \n    gKerasify = new KerasifyThread();\n    gKerasify->launchThread();\n    \n    DefinePVUnit(PV_Kerasify);\n    \n    \n    \n}\n\n\n", "meta": {"hexsha": "eed28588904f7b147a72ccf96b4c748023640bcc", "size": 29882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SuperCollider UGen/source/PV_Kerasify.cpp", "max_stars_repo_name": "musikinformatik/Keras-to-Realtime-Audio", "max_stars_repo_head_hexsha": "e0fe84566ef7038b55873d6b7f58e3d84ed45078", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-15T17:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T21:17:37.000Z", "max_issues_repo_path": "SuperCollider UGen/source/PV_Kerasify.cpp", "max_issues_repo_name": "musikinformatik/Keras-to-Realtime-Audio", "max_issues_repo_head_hexsha": "e0fe84566ef7038b55873d6b7f58e3d84ed45078", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SuperCollider UGen/source/PV_Kerasify.cpp", "max_forks_repo_name": "musikinformatik/Keras-to-Realtime-Audio", "max_forks_repo_head_hexsha": "e0fe84566ef7038b55873d6b7f58e3d84ed45078", "max_forks_repo_licenses": ["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.1838383838, "max_line_length": 342, "alphanum_fraction": 0.5121812462, "num_tokens": 7400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.1829460612019071}}
{"text": "\n#ifndef ISOLATOR_ANALYZE_HPP\n#define ISOLATOR_ANALYZE_HPP\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <map>\n#include <set>\n#include <string>\n#include <vector>\n#include <cstdio>\n\n#include \"hdf5.hpp\"\n#include \"fragment_model.hpp\"\n#include \"queue.hpp\"\n#include \"sampler.hpp\"\n#include \"transcripts.hpp\"\n\nclass SamplerTickThread;\nclass ConditionMeanShapeSamplerThread;\nclass ExperimentMeanShapeSamplerThread;\nclass GammaBetaSampler;\nclass AlphaSampler;\nclass BetaSampler;\nclass GammaNormalSigmaSampler;\nclass GammaStudentTSigmaSampler;\nclass ConditionSpliceMuSigmaEtaSamplerThread;\nclass ExperimentSpliceMuSigmaSamplerThread;\nclass GammaShapeSampler;\ntypedef std::pair<int, int> IdxRange;\n\n\nclass Analyze\n{\n    public:\n        Analyze(unsigned int rng_seed,\n                size_t burnin,\n                size_t num_samples,\n                TranscriptSet& ts,\n                const char* genome_filename,\n                bool run_seqbias_correction,\n                bool run_gc_correction,\n                bool run_3p_correction,\n                bool run_frag_correction,\n                bool collect_qc_data,\n                bool nopriors,\n                std::set<std::string> excluded_seqs,\n                std::set<std::string> bias_training_seqnames,\n                double experiment_shape_alpha,\n                double experiment_shape_beta,\n                double experiment_splice_sigma_alpha,\n                double experiment_splice_sigma_beta,\n                double condition_shape_alpha,\n                double condition_shape_beta_a,\n                double condition_shape_beta_b,\n                double condition_splice_alpha,\n                double condition_splice_beta_a,\n                double condition_splice_beta_b);\n        ~Analyze();\n\n        // Add a replicate under a particular condition\n        void add_sample(const char* condition_name,\n                        const char* filename);\n\n        void run(hid_t file_id, bool dryrun);\n        void cleanup();\n\n    private:\n        void setup_samplers();\n        void setup_output(hid_t output_file_id);\n        void sample(bool optimize_state);\n        void write_output(size_t sample_num);\n\n        void qsampler_update_hyperparameters();\n\n        void compute_ts();\n        void compute_xs();\n\n        void choose_initial_values();\n        void compute_scaling();\n\n        // number of burnin samples\n        size_t burnin;\n\n        // number of samples to generate\n        size_t num_samples;\n\n        // transcript set\n        TranscriptSet& transcripts;\n\n        // File name of a fasta file containing the reference genome sequence\n        // against which the reads are aligned.\n        const char* genome_filename;\n\n        // True if SeqBias correction should be used.\n        bool run_seqbias_correction;\n\n        // True if GC content correction should be used.\n        bool run_gc_correction;\n\n        // True if 3' bias should be corrected\n        bool run_3p_correction;\n\n        // True if fragmentation bias should be corrected\n        bool run_frag_correction;\n\n        // Sequences on which aligned reads should be ignored\n        std::set<std::string> excluded_seqs;\n\n        // If non-empty, contains names of sequence to which bias training\n        // should be restricted.\n        std::set<std::string> bias_training_seqnames;\n\n        // True if extra extra QC data should be collected\n        bool collect_qc_data;\n\n        // True if priors should not be applie during quantification\n        bool nopriors;\n\n        // file names for the BAM/SAM file corresponding to each\n        std::vector<std::string> filenames;\n\n        // condition index to sample indexes\n        std::vector<std::vector<int> > condition_samples;\n\n        // fragment models for each sample\n        std::vector<FragmentModel*> fms;\n\n        // quantification samplers for each sample\n        std::vector<Sampler*> qsamplers;\n\n        // threads used for iterating samplers\n        std::vector<SamplerTickThread*> qsampler_threads;\n        std::vector<ConditionMeanShapeSamplerThread*> meanshape_sampler_threads;\n        std::vector<ExperimentMeanShapeSamplerThread*> experiment_meanshape_sampler_threads;\n        GammaBetaSampler* gamma_beta_sampler;\n        BetaSampler* invgamma_beta_sampler;\n        GammaNormalSigmaSampler* gamma_normal_sigma_sampler;\n        GammaShapeSampler* gamma_shape_sampler;\n\n        std::vector<ConditionSpliceMuSigmaEtaSamplerThread*> splice_mu_sigma_sampler_threads;\n        std::vector<ExperimentSpliceMuSigmaSamplerThread*>\n            experiment_splice_mu_sigma_sampler_threads;\n\n        // queues to send work to sampler threads, and be notified on completion\n        // of ticks.\n        Queue<int> qsampler_tick_queue, qsampler_notify_queue;\n\n        // work is doled out in block for these. Otherwise threads can starve\n        // when there are few sample in the experiment\n        Queue<IdxRange> meanshape_sampler_tick_queue,\n                        experiment_meanshape_sampler_tick_queue,\n                        splice_mu_sigma_sampler_tick_queue,\n                        experiment_splice_mu_sigma_sampler_tick_queue;\n\n        Queue<int> meanshape_sampler_notify_queue,\n                   experiment_meanshape_sampler_notify_queue,\n                   splice_mu_sigma_sampler_notify_queue,\n                   experiment_splice_mu_sigma_sampler_notify_queue;\n\n        // We maintain a different rng for every unit of work for threads.\n        // That way we can actually make isolator run reproducible.\n        std::vector<rng_t> transcript_rng_pool;\n        std::vector<rng_t> splice_rng_pool;\n\n        // matrix containing relative transcript abundance samples, indexed by:\n        //   sample -> transcript (tid)\n        boost::numeric::ublas::matrix<float> Q;\n\n        // transcript mean parameter, indexed by condition -> transcript\n        boost::numeric::ublas::matrix<float> condition_mean;\n\n        // transcript shape parameter, indexed by transcript\n        std::vector<float> condition_shape;\n\n        // parameters of the inverse gamma prior on condition_splice_sigma\n        double condition_splice_alpha, condition_splice_beta;\n\n        // parameters of the inverse gamma prior on condition_shape\n        double condition_shape_alpha, condition_shape_beta;\n\n        // experiment-wise transcript position paremeter, indexed by transcript\n        std::vector<float> experiment_mean;\n\n        // experiment-wide transcript scale parameter\n        double experiment_shape;\n\n        // gamma hypeparameters for prior on experiment_shape\n        double experiment_shape_alpha;\n        double experiment_shape_beta;\n\n        // parameters for normal prior over experiment_mean\n        double experiment_mean0, experiment_shape0;\n\n        // tids belonging to each tgroup (indexed by tgroup)\n        std::vector<std::vector<unsigned int> > tgroup_tids;\n\n        // sorted indexes of tgroups with multiple transcripts\n        std::vector<unsigned int> spliced_tgroup_indexes;\n\n        // condition slice mean indexed by condition, spliced tgroup, transcript\n        // according to spliced_tgroup_indexes and tgroup_tids\n        std::vector<std::vector<std::vector<float> > > condition_splice_mu;\n\n        // per-spliced-tgroup experiment wide logistic-normal mean\n        std::vector<std::vector<float> > experiment_splice_mu;\n\n        // prior parameters for experimient_splice_mu\n        double experiment_splice_nu, experiment_splice_mu0, experiment_splice_sigma0;\n\n        // experiment std. dev.\n        double experiment_splice_sigma;\n\n        // gamma hypeparameters for prior on experiment_splice_sigma\n        double experiment_splice_sigma_alpha;\n        double experiment_splice_sigma_beta;\n\n        // splicing precision, indexed by spliced tgroup\n        std::vector<std::vector<float> > condition_splice_sigma;\n\n        // overparameterization to unstick stuck samplers\n        std::vector<std::vector<float> > condition_splice_eta;\n\n        // flattened condition_splice_sigma used for sampling alpha, beta\n        // params.\n        std::vector<float> condition_splice_sigma_work;\n        std::vector<float> experiment_splice_sigma_work;\n\n        // paramaters for the inverse gamma priors on splice_alpha and\n        // splice_beta\n        double condition_splice_beta_a,\n               condition_splice_beta_b;\n\n        // Condition index corresponding to the given name\n        std::map<std::string, int> condition_index;\n\n        // Condition index of sample i\n        std::vector<int> condition;\n\n        // normalization constant for each sample\n        std::vector<float> scale;\n\n        // temporary space used for computing scale\n        std::vector<float> scale_work;\n\n        // number of sequenced samples\n        unsigned int K;\n\n        // number of conditions\n        unsigned int C;\n\n        // number of transcripts\n        unsigned int N;\n\n        // number of tgroups\n        unsigned int T;\n\n        // Hyperparams for inverse gamma prior on tgroup_alpha/tgroup_beta\n        double condition_shape_beta_a,\n               condition_shape_beta_b;\n\n        // RNG used for alpha/beta samplers\n        unsigned int rng_seed;\n        rng_t rng;\n\n        // HDF5 dataspace ids, for output purposes\n\n        // dataspaces\n        hid_t h5_experiment_mean_dataspace;\n        hid_t h5_condition_mean_dataspace;\n        hid_t h5_condition_mean_mem_dataspace;\n        hid_t h5_row_mem_dataspace;\n        hid_t h5_sample_quant_dataspace;\n        hid_t h5_sample_quant_mem_dataspace;\n        hid_t h5_experiment_splice_dataspace;\n        hid_t h5_condition_splice_mu_dataspace;\n        hid_t h5_condition_splice_sigma_dataspace;\n        hid_t h5_splicing_mem_dataspace;\n        hid_t h5_sample_scaling_dataspace;\n        hid_t h5_sample_scaling_mem_dataspace;\n\n        // datasets\n        hid_t h5_experiment_mean_dataset;\n        hid_t h5_condition_mean_dataset;\n        hid_t h5_condition_shape_dataset;\n        hid_t h5_sample_quant_dataset;\n        hid_t h5_experiment_splice_mu_dataset;\n        hid_t h5_experiment_splice_sigma_dataset;\n        hid_t h5_condition_splice_mu_dataset;\n        hid_t h5_condition_splice_sigma_dataset;\n        hid_t h5_sample_scaling_dataset;\n\n        // variable length array for splicing paramaters\n        hid_t h5_splice_param_type;\n\n        // structure for the ragged-array splicing data\n        hvl_t* h5_splice_work;\n\n        // a write buffer for hdf5 output\n        std::vector<float> row_data;\n\n        friend void write_qc_data(FILE* fout, Analyze& analyze);\n        friend void compare_seqbias(Analyze& analyze, TranscriptSet& ts,\n                                    const char* genome_filename);\n};\n\n\n#endif\n\n", "meta": {"hexsha": "878dae289027370daf94eefb58add2c81bb01656", "size": 10714, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/analyze.hpp", "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/analyze.hpp", "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/analyze.hpp", "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": 34.6731391586, "max_line_length": 93, "alphanum_fraction": 0.6748179951, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.1829328150975256}}
{"text": "/*\n Copyright (C) 2017 Sascha Meiers\n Distributed under the MIT software license, see the accompanying\n file LICENSE.md or http://www.opensource.org/licenses/mit-license.php.\n */\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <unordered_map>\n#include <tuple>\n\n#include <boost/program_options/cmdline.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/progress.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/stream_buffer.hpp>\n#include <boost/iostreams/device/file.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/zlib.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <htslib/sam.h>\n\n#include \"version.hpp\"\n#include \"intervals.hpp\"\n#include \"counter.hpp\"\n#include \"distribution.hpp\"\n#include \"hmm.hpp\"\n#include \"iocounts.hpp\"\n\n\n/**\n * @file\n * @defgroup count Bin, count and classify W/C reads.\n *\n * Summary of how Strand-seq data is binned, counted and classified.\n *\n * ## Strand-seq read counting\n *\n * @todo write documentation about counting.\n*/\n\n\nusing interval::Interval;\nusing count::TGenomeCounts;\nusing count::Counter;\n\n\nstruct Conf {\n    std::vector<boost::filesystem::path> f_in;\n    boost::filesystem::path f_out;\n    boost::filesystem::path f_bins;\n    boost::filesystem::path f_excl;\n    boost::filesystem::path f_info;\n    boost::filesystem::path f_sample_info;\n    boost::filesystem::path f_removed_bins;\n    boost::filesystem::path f_segments;\n    int minMapQual;\n    unsigned int window;\n    std::string mode;\n};\n\n\n/**\n *\n */\nvoid run_standard_HMM(std::vector<TGenomeCounts> & counts,\n                      std::vector<unsigned> const & good_cells,\n                      std::vector<CellInfo>  & cells,\n                      std::vector<unsigned> const & good_bins,\n                      std::vector<int32_t> const & good_map,\n                      std::unordered_map<std::string, SampleInfo> const & samples,\n                      float p_trans)\n{\n    // Set up and run HMM:\n    hmm::HMM<unsigned, hmm::MultiVariate<hmm::NegativeBinomial> > hmm({\"CC\", \"WC\", \"WW\"});\n    hmm.set_initials({0.3333, 0.3333, 0.3333});\n    hmm.set_transitions({1-2*p_trans, p_trans,     p_trans,    \\\n        p_trans,     1-2*p_trans, p_trans,    \\\n        p_trans,     p_trans,     1-2*p_trans});\n\n    for (auto i = good_cells.begin(); i != good_cells.end(); ++i)\n    {\n        // set NB(n,p) parameters according to `p` of sample and mean of cell.\n        float p = samples.at(cells[*i].sample_name).p;\n        float n = (float)cells[*i].mean_bin_count * p / (1-p);\n        float a = 0.1;\n        cells[*i].nb_p = p;\n        cells[*i].nb_r = n;\n        cells[*i].nb_a = a;\n\n        //std::cout << \"NB parameters for cell <?>\" << \": p=\" << p << \"\\tn=\" << n << \"\\tz=\" << z << std::endl;\n\n        hmm.set_emissions( {\\\n            hmm::MultiVariate<hmm::NegativeBinomial>({hmm::NegativeBinomial(p, (1-a)*n), hmm::NegativeBinomial(p, a*n)}), // CC\n            hmm::MultiVariate<hmm::NegativeBinomial>({hmm::NegativeBinomial(p, n/2),     hmm::NegativeBinomial(p, n/2)}), // WC\n            hmm::MultiVariate<hmm::NegativeBinomial>({hmm::NegativeBinomial(p, a*n),     hmm::NegativeBinomial(p, (1-a)*n)})  // WW\n        });\n        run_HMM(hmm, counts[*i], good_bins, good_map);\n    }\n}\n\n\n\n\n\nint main_count(int argc, char **argv)\n{\n\n    // Command line options\n    Conf conf;\n    boost::program_options::options_description generic(\"Generic options\");\n    generic.add_options()\n    (\"help,?\", \"show help message\")\n    (\"verbose,v\", \"Be more verbose in the output\")\n    (\"mapq,q\", boost::program_options::value<int>(&conf.minMapQual)->default_value(10), \"min mapping quality\")\n    (\"window,w\", boost::program_options::value<unsigned int>(&conf.window)->default_value(500000), \"window size of fixed windows\")\n    (\"out,o\", boost::program_options::value<boost::filesystem::path>(&conf.f_out)->default_value(\"out.txt.gz\"), \"output file for counts + strand state (gz)\")\n    (\"bins,b\", boost::program_options::value<boost::filesystem::path>(&conf.f_bins), \"BED file with manual bins (disables -w). See also 'makebins'\")\n    (\"exclude,x\", boost::program_options::value<boost::filesystem::path>(&conf.f_excl), \"Exclude chromosomes and regions\")\n    (\"info,i\", boost::program_options::value<boost::filesystem::path>(&conf.f_info), \"Write info about samples\")\n    (\"do-not-filter-by-WC\", \"When black-listing bins, only consider coverage and not WC/WW/CC states\")\n    (\"do-not-blacklist-hmm\", \"Do not output a blacklist (None bins). Bins will be blacklisted for parameter estimation, but not during HMM\")\n    ;\n    // Note: Currently the blacklisting is done after counting via R/norm.R. A better way would be to \n    // input the blacklist + normalization into MosaiCatcher during the counting, then the HMM could be run\n    // only on non-blacklisted bins. Now it is run through many bad bin that potentially affect the quality of results.\n\n    boost::program_options::options_description hidden(\"Hidden options\");\n    hidden.add_options()\n    (\"input-file\", boost::program_options::value<std::vector<boost::filesystem::path> >(&conf.f_in), \"input bam file(s)\")\n    (\"sample_info,S\", boost::program_options::value<boost::filesystem::path>(&conf.f_sample_info),   \"write info per sample\")\n    (\"removed_bins,R\", boost::program_options::value<boost::filesystem::path>(&conf.f_removed_bins), \"bins that were removed (bed file)\")\n    ;\n\n    boost::program_options::positional_options_description pos_args;\n    pos_args.add(\"input-file\", -1);\n\n    boost::program_options::options_description cmdline_options;\n    cmdline_options.add(generic).add(hidden);\n    boost::program_options::options_description visible_options;\n    visible_options.add(generic);\n    boost::program_options::variables_map vm;\n\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);\n    boost::program_options::notify(vm);\n\n    // Check command line arguments\n    if (!vm[\"window\"].defaulted() && vm.count(\"bins\")) {\n        std::cerr << \"[Error] -w and -b cannot be specified together\" << std::endl << std::endl;\n        goto print_usage_and_exit;\n    }\n    if (vm.count(\"bins\") && vm.count(\"exclude\")) {\n        std::cerr << \"[Error] Exclude chromosomes (-x) have no effect when -b is specified. Stop\" << std::endl << std::endl;\n        goto print_usage_and_exit;\n    }\n\n    if (vm.count(\"help\") || !vm.count(\"input-file\"))\n    {\n    print_usage_and_exit:\n        std::cout << std::endl;\n        std::cout << \"Mosaicatcher \" << STRINGIFYMACRO(MOSAIC_VERSION_MAJOR);\n        std::cout << \".\" << STRINGIFYMACRO(MOSAIC_VERSION_MINOR) << std::endl;\n        std::cout << \"> Count reads from Strand-seq BAM files.\" << std::endl;\n        std::cout << std::endl;\n        std::cout << \"Usage:   \" << argv[0] << \" [OPTIONS] <cell1.bam> <cell2.bam> ...\" << std::endl << std::endl;\n        std::cout << visible_options << std::endl;\n        std::cout << \"Notes:\" << std::endl;\n        std::cout << \"  * writes a table of bin counts and state classifcation as a gzip file (default: out.txt.gz)\" << std::endl;\n        std::cout << \"  * Reads are counted by start position\" << std::endl;\n        std::cout << \"  * One cell per BAM file, including SM tag in header\" << std::endl;\n        std::cout << \"  * For paired-end data, only read 1 is counted\" << std::endl;\n        return vm.count(\"help\") ? 0 : 1;\n    }\n\n\n    /////////////////////////////////////////////////////////// global variables\n    /* leave one BAM header open to get chrom names & lengths */\n    bam_hdr_t* hdr = NULL;\n\n    /* regarding each cell */\n    std::vector<CellInfo>       cells(conf.f_in.size());\n    std::vector<TGenomeCounts>  counts(conf.f_in.size());\n    std::vector<unsigned>       good_cells;\n\n    /* regarding each sample */\n    std::unordered_map<std::string, SampleInfo> samples;\n\n    /* regarding bins */\n    std::vector<Interval>       bins;\n    std::vector<int32_t>        chrom_map;\n    std::vector<unsigned>       good_bins;\n    std::vector<int32_t>        good_map;\n    ////////////////////////////////////////////////////////////////////////////\n\n\n\n    //\n    // Chapter: Binning & counting\n    // ===========================\n    //\n\n    // Read sample names from headers.\n    // Keep one header throughout the program.\n    if (vm.count(\"verbose\")) std::cout << \"[Info] Exploring SAM headers...\" << std::endl;\n    for(unsigned i = 0; i < conf.f_in.size(); ++i)\n    {\n        cells[i].id = (int32_t)i;\n        cells[i].bam_file = conf.f_in[i].string();\n        samFile* samfile = sam_open(conf.f_in[i].string().c_str(), \"r\");\n        if (samfile == NULL) {\n            std::cerr << \"[Error] Fail to open file \" << conf.f_in[i].string() << std::endl;\n            return 1;\n        }\n        hdr = sam_hdr_read(samfile);\n        if (!get_RG_tag(\"SM\", hdr->text, cells[i].sample_name)) {\n            std::cerr << \"[Error] Each BAM file has to have exactly one RG tag. Group cells \" << std::endl;\n            std::cerr << \"        belonging to the same sample by the SM tag.\" << std::endl;\n            std::cerr << \"        Problematic file: \" << conf.f_in[i].string() << std::endl << std::endl;\n            goto print_usage_and_exit;\n        }\n        if (!get_RG_tag(\"ID\", hdr->text, cells[i].cell_name, /*allow_multiple_matches = */ true)) {\n            std::cerr << \"[Error] Each BAM file has to have exactly one RG tag.\" << std::endl;\n            std::cerr << \"        Problematic file: \" << conf.f_in[i].string() << std::endl;\n            goto print_usage_and_exit;\n        }\n        sam_close(samfile);\n    }\n\n\n    // Bin the genome\n    unsigned median_binsize;\n    chrom_map = std::vector<int32_t>(hdr->n_targets, -1);\n    if (vm.count(\"bins\"))\n    {\n        if (!read_dynamic_bins(bins,\n                               chrom_map,\n                               conf.f_bins.string().c_str(),\n                               hdr))\n            return 1;\n        TMedianAccumulator<unsigned> med_acc;\n        for (Interval const & b : bins)\n            med_acc(b.end - b.start);\n        median_binsize = boost::accumulators::median(med_acc);\n        std::cout << \"[Info] Reading \" << bins.size() << \" variable-width bins with median bin size of \" << round(median_binsize/1000) << \"kb\" << std::endl;\n    }\n    else\n    {\n        std::vector<Interval> exclude;\n        if (vm.count(\"exclude\")) {\n            read_exclude_file(conf.f_excl.string(), hdr, exclude, vm.count(\"verbose\"));\n            sort(exclude.begin(), exclude.end(), interval::invt_less);\n        }\n        std::cout << \"[Info] Creating \" << round(conf.window/1000) << \"kb bins with \" << exclude.size() << \" excluded regions\" << std::endl;\n        create_fixed_bins(bins,\n                          chrom_map,\n                          conf.window,\n                          exclude,\n                          hdr->n_targets,\n                          hdr->target_len);\n        median_binsize = conf.window;\n    }\n    // add last element for easy calculation of number of bins\n    chrom_map.push_back((int32_t)bins.size());\n\n\n    // Count in bins. If A bam file cannot be read, the cell is ignored and\n    //     the respective entry in `counts` and `cells` will be erased.\n    std::cout << \"[Info] Reading \" << conf.f_in.size() <<  \" BAM files...\";\n    boost::progress_display show_progress1(conf.f_in.size());\n    for (unsigned i = 0, i_f = 0; i_f < conf.f_in.size(); ++i, ++i_f)\n    {\n        if (!count_sorted_reads(conf.f_in[i_f].string(),\n                                bins,\n                                chrom_map,\n                                hdr,\n                                conf.minMapQual,\n                                counts[i],\n                                cells[i]))\n        {\n            std::cerr << \"[Warning] Ignoring cell \" << conf.f_in[i_f].string() << std::endl;\n            counts.erase(counts.begin()+i);\n            cells.erase(cells.begin()+i);\n            --i;\n        }\n        ++show_progress1;\n    }\n\n\n\n\n\n    //\n    // Chapter: Filter cells and bins and estimate NB parameter p\n    // ==========================================================\n    //\n\n    // median per cell\n    count::set_median_per_cell(counts, cells);\n\n    // filter cells with low counts\n    good_cells = count::get_good_cells(counts, cells);\n\n    // filter bins with abnormal counts\n    if (good_cells.size() < 5) {\n        std::cerr << \"[Warning] Only few cells with sufficient coverage. I will not filter bad bins\" << std::endl;\n        good_bins.resize(bins.size());\n        std::iota(good_bins.begin(), good_bins.end(), 0); // fill with 0,1,2,...\n    } else {\n        good_bins = count::get_good_bins(counts,\n                                         cells,\n                                         good_cells,\n                                         vm.count(\"verbose\"),\n                                         !vm.count(\"do-not-filter-by-WC\"));\n        if (vm.count(\"verbose\")) std::cout << \"[Info] Filtered out \" << bins.size() - good_bins.size() << \" bad bins from \" << bins.size() << std::endl;\n    }\n\n    // build chrom_map for good bins\n    good_map = std::vector<int32_t>(chrom_map.size() - 1, -1);\n    int32_t pos = 0;\n    for (int32_t chr = 0; chr < static_cast<int32_t>(good_map.size()); ++chr) {\n        while (pos < good_bins.size() && bins[good_bins[pos]].chr < chr)\n            ++pos;\n        // now goodit is either at first occurence of chr, or at the end.\n        if (pos >= good_bins.size()) good_map[chr] = (int32_t)good_bins.size();\n        else good_map[chr] = pos;\n    }\n    // add last element for easy calculation of number of bins\n    good_map.push_back((int32_t)good_bins.size());\n\n\n\n    // calculate cell means and cell variances, grouped by sample (not cell)\n    calculate_new_cell_mean(samples, cells, counts, good_cells, good_bins);\n\n\n    // Estimation of parameter p per sample (should work even with one cell only)\n    for (auto it = samples.begin(); it != samples.end(); ++it) {\n        SampleInfo & s = it->second;\n        s.p = std::inner_product(s.means.begin(), s.means.end(), s.means.begin(), 0.0f) \\\n        / std::inner_product(s.means.begin(), s.means.end(), s.vars.begin(), 0.0f);\n    }\n\n    // Write sample information to file\n    if (vm.count(\"sample_info\")) {\n        if (vm.count(\"verbose\")) std::cout << \"[Write] sample information: \" << conf.f_sample_info.string() << std::endl;\n        std::ofstream out(conf.f_sample_info.string());\n        if (out.is_open()) {\n            out << \"sample\\tcells\\tp\\tmeans\\tvars\" << std::endl;\n            for (auto it = samples.begin(); it != samples.end(); ++it) {\n                SampleInfo const & s = it->second;\n                out << it->first << \"\\t\" << s.means.size() << \"\\t\" << s.p << \"\\t\" << s.means[0];\n                for (unsigned k=1; k<s.means.size(); ++k) out << \",\" << s.means[k];\n                out << \"\\t\" << s.vars[0];\n                for (unsigned k=1; k<s.vars.size(); ++k) out << \",\" << s.vars[k];\n                out << std::endl;\n            }\n        } else {\n            std::cerr << \"[Warning] Cannot write to \" << conf.f_sample_info.string() << std::endl;\n        }\n    }\n\n\n\n\n    //\n    // Chapter: Run HMM\n    // ================\n    //\n    if(vm.count(\"do-not-blacklist-hmm\")) {\n        if (vm.count(\"verbose\")) std::cout << \"[Info] Previous filters are not used during HMM phase\" << std::endl;\n        std::vector<unsigned> normal_bins(bins.size());\n        std::iota(normal_bins.begin(), normal_bins.end(), 0);\n        run_standard_HMM(counts,\n                         good_cells,\n                         cells,\n                         normal_bins,\n                         chrom_map,\n                         samples,\n                         10.0f / bins.size());\n    } else {\n        run_standard_HMM(counts,\n                         good_cells,\n                         cells,\n                         good_bins,\n                         good_map,\n                         samples,\n                         10.0f / good_bins.size());\n    }\n\n\n\n    // Print cell information:\n    if (vm.count(\"info\")) {\n        if (vm.count(\"verbose\")) std::cout << \"[Write] Cell summary: \" << conf.f_info.string() << std::endl;\n        write_cell_info(conf.f_info.string(), cells);\n    }\n\n\n    // Write final counts + classification\n    std::cout << \"[Write] count table: \" << conf.f_out.string() << std::endl;\n    {\n        // TODO: why do I pass vector<pair>? I could make it two separate vectors. Just check where else the io function is called.\n        struct sample_cell_name_wrapper {\n            std::vector<CellInfo> const & cells;\n            sample_cell_name_wrapper(std::vector<CellInfo> const & cells) : cells(cells)\n            {}\n            std::pair<std::string,std::string> operator[](size_t i) const {\n                return std::make_pair(cells[i].sample_name, cells[i].cell_name);\n            }\n        };\n\n        if (!io::write_counts_gzip(conf.f_out.string(),\n                                   counts,\n                                   bins,\n                                   hdr->target_name,\n                                   sample_cell_name_wrapper(cells)) )\n            return 1;\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "1bbb1268f5eb559749c276cb7b474e883f2b55fd", "size": 17428, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/count.hpp", "max_stars_repo_name": "tobiasmarschall/mosaicatcher", "max_stars_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-26T01:36:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T00:28:01.000Z", "max_issues_repo_path": "src/count.hpp", "max_issues_repo_name": "tobiasmarschall/mosaicatcher", "max_issues_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-01-12T11:56:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T16:09:34.000Z", "max_forks_repo_path": "src/count.hpp", "max_forks_repo_name": "tobiasmarschall/mosaicatcher", "max_forks_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T09:12:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-02T11:33:28.000Z", "avg_line_length": 40.8149882904, "max_line_length": 157, "alphanum_fraction": 0.568510443, "num_tokens": 4205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.18293280552893076}}
{"text": "#include <sstream>\n#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"stringlib.h\"\n#include \"hg_sampler.h\"\n#include \"sentence_metadata.h\"\n#include \"ns.h\"\n#include \"ns_docscorer.h\"\n#include \"verbose.h\"\n#include \"viterbi.h\"\n#include \"hg.h\"\n#include \"prob.h\"\n#include \"kbest.h\"\n#include \"ff_register.h\"\n#include \"decoder.h\"\n#include \"filelib.h\"\n#include \"fdict.h\"\n#include \"weights.h\"\n#include \"sparse_vector.h\"\n#include \"sampler.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nbool invert_score;\nboost::shared_ptr<MT19937> rng;\n\nvoid RandomPermutation(int len, vector<int>* p_ids) {\n  vector<int>& ids = *p_ids;\n  ids.resize(len);\n  for (int i = 0; i < len; ++i) ids[i] = i;\n  for (int i = len; i > 0; --i) {\n    int j = rng->next() * i;\n    if (j == i) i--;\n    swap(ids[i-1], ids[j]);\n  }  \n}\n\nbool InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"input_weights,w\",po::value<string>(),\"Input feature weights file\")\n        (\"source,i\",po::value<string>(),\"Source file for development set\")\n        (\"passes,p\", po::value<int>()->default_value(15), \"Number of passes through the training data\")\n        (\"reference,r\",po::value<vector<string> >(), \"[REQD] Reference translation(s) (tokenized text file)\")\n        (\"mt_metric,m\",po::value<string>()->default_value(\"ibm_bleu\"), \"Scoring metric (ibm_bleu, nist_bleu, koehn_bleu, ter, combi)\")\n        (\"max_step_size,C\", po::value<double>()->default_value(0.01), \"regularization strength (C)\")\n        (\"mt_metric_scale,s\", po::value<double>()->default_value(1.0), \"Amount to scale MT loss function by\")\n        (\"k_best_size,k\", po::value<int>()->default_value(250), \"Size of hypothesis list to search for oracles\")\n        (\"sample_forest,f\", \"Instead of a k-best list, sample k hypotheses from the decoder's forest\")\n        (\"sample_forest_unit_weight_vector,x\", \"Before sampling (must use -f option), rescale the weight vector used so it has unit length; this may improve the quality of the samples\")\n        (\"random_seed,S\", po::value<uint32_t>(), \"Random seed (if not specified, /dev/random will be used)\")\n        (\"decoder_config,c\",po::value<string>(),\"Decoder configuration file\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config\", po::value<string>(), \"Configuration file\")\n        (\"help,h\", \"Print this help message and exit\");\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(opts).add(clo);\n  \n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"config\")) {\n    ifstream config((*conf)[\"config\"].as<string>().c_str());\n    po::store(po::parse_config_file(config, dconfig_options), *conf);\n  }\n  po::notify(*conf);\n\n  if (conf->count(\"help\") || !conf->count(\"input_weights\") || !conf->count(\"source\") || !conf->count(\"decoder_config\") || !conf->count(\"reference\")) {\n    cerr << dcmdline_options << endl;\n    return false;\n  }\n  return true;\n}\n\nstatic const double kMINUS_EPSILON = -1e-6;\n\nstruct HypothesisInfo {\n  SparseVector<double> features;\n  double mt_metric;\n};\n\nstruct GoodBadOracle {\n  boost::shared_ptr<HypothesisInfo> good;\n  boost::shared_ptr<HypothesisInfo> bad;\n};\n\nstruct TrainingObserver : public DecoderObserver {\n  TrainingObserver(const int k, const DocumentScorer& d, const EvaluationMetric& m, bool sf, vector<GoodBadOracle>* o) : ds(d), metric(m), oracles(*o), kbest_size(k), sample_forest(sf) {}\n  const DocumentScorer& ds;\n  const EvaluationMetric& metric;\n  vector<GoodBadOracle>& oracles;\n  boost::shared_ptr<HypothesisInfo> cur_best;\n  const int kbest_size;\n  const bool sample_forest;\n\n  const HypothesisInfo& GetCurrentBestHypothesis() const {\n    return *cur_best;\n  }\n\n  virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) {\n    UpdateOracles(smeta.GetSentenceID(), *hg);\n  }\n\n  boost::shared_ptr<HypothesisInfo> MakeHypothesisInfo(const SparseVector<double>& feats, const double score) {\n    boost::shared_ptr<HypothesisInfo> h(new HypothesisInfo);\n    h->features = feats;\n    h->mt_metric = score;\n    return h;\n  }\n\n  void UpdateOracles(int sent_id, const Hypergraph& forest) {\n    boost::shared_ptr<HypothesisInfo>& cur_good = oracles[sent_id].good;\n    boost::shared_ptr<HypothesisInfo>& cur_bad = oracles[sent_id].bad;\n    cur_bad.reset();  // TODO get rid of??\n\n    if (sample_forest) {\n      vector<WordID> cur_prediction;\n      ViterbiESentence(forest, &cur_prediction);\n      SufficientStats sstats;\n      ds[sent_id]->Evaluate(cur_prediction, &sstats);\n      float sentscore = metric.ComputeScore(sstats);\n      cur_best = MakeHypothesisInfo(ViterbiFeatures(forest), sentscore);\n\n      vector<HypergraphSampler::Hypothesis> samples;\n      HypergraphSampler::sample_hypotheses(forest, kbest_size, &*rng, &samples);\n      for (unsigned i = 0; i < samples.size(); ++i) {\n        ds[sent_id]->Evaluate(samples[i].words, &sstats);\n        float sentscore = metric.ComputeScore(sstats);\n        if (invert_score) sentscore *= -1.0;\n        if (!cur_good || sentscore > cur_good->mt_metric)\n          cur_good = MakeHypothesisInfo(samples[i].fmap, sentscore);\n        if (!cur_bad || sentscore < cur_bad->mt_metric)\n          cur_bad = MakeHypothesisInfo(samples[i].fmap, sentscore);\n      }\n    } else {\n      KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(forest, kbest_size);\n      SufficientStats sstats;\n      for (int i = 0; i < kbest_size; ++i) {\n        const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d =\n          kbest.LazyKthBest(forest.nodes_.size() - 1, i);\n        if (!d) break;\n        ds[sent_id]->Evaluate(d->yield, &sstats);\n        float sentscore = metric.ComputeScore(sstats);\n        if (invert_score) sentscore *= -1.0;\n        // cerr << TD::GetString(d->yield) << \" ||| \" << d->score << \" ||| \" << sentscore << endl;\n        if (i == 0)\n          cur_best = MakeHypothesisInfo(d->feature_values, sentscore);\n        if (!cur_good || sentscore > cur_good->mt_metric)\n          cur_good = MakeHypothesisInfo(d->feature_values, sentscore);\n        if (!cur_bad || sentscore < cur_bad->mt_metric)\n          cur_bad = MakeHypothesisInfo(d->feature_values, sentscore);\n      }\n      //cerr << \"GOOD: \" << cur_good->mt_metric << endl;\n      //cerr << \" CUR: \" << cur_best->mt_metric << endl;\n      //cerr << \" BAD: \" << cur_bad->mt_metric << endl;\n    }\n  }\n};\n\nvoid ReadTrainingCorpus(const string& fname, vector<string>* c) {\n  ReadFile rf(fname);\n  istream& in = *rf.stream();\n  string line;\n  while(in) {\n    getline(in, line);\n    if (!in) break;\n    c->push_back(line);\n  }\n}\n\nbool ApproxEqual(double a, double b) {\n  if (a == b) return true;\n  return (fabs(a-b)/fabs(b)) < 0.000001;\n}\n\nint main(int argc, char** argv) {\n  register_feature_functions();\n  SetSilent(true);  // turn off verbose decoder output\n\n  po::variables_map conf;\n  if (!InitCommandLine(argc, argv, &conf)) return 1;\n\n  if (conf.count(\"random_seed\"))\n    rng.reset(new MT19937(conf[\"random_seed\"].as<uint32_t>()));\n  else\n    rng.reset(new MT19937);\n  const bool sample_forest = conf.count(\"sample_forest\") > 0;\n  const bool sample_forest_unit_weight_vector = conf.count(\"sample_forest_unit_weight_vector\") > 0;\n  if (sample_forest_unit_weight_vector && !sample_forest) {\n    cerr << \"Cannot --sample_forest_unit_weight_vector without --sample_forest\" << endl;\n    return 1;\n  }\n  vector<string> corpus;\n  ReadTrainingCorpus(conf[\"source\"].as<string>(), &corpus);\n\n  string metric_name = UppercaseString(conf[\"mt_metric\"].as<string>());\n  if (metric_name == \"COMBI\") {\n    cerr << \"WARNING: 'combi' metric is no longer supported, switching to 'COMB:TER=-0.5;IBM_BLEU=0.5'\\n\";\n    metric_name = \"COMB:TER=-0.5;IBM_BLEU=0.5\";\n  } else if (metric_name == \"BLEU\") {\n    cerr << \"WARNING: 'BLEU' is ambiguous, assuming 'IBM_BLEU'\\n\";\n    metric_name = \"IBM_BLEU\";\n  }\n  EvaluationMetric* metric = EvaluationMetric::Instance(metric_name);\n  DocumentScorer ds(metric, conf[\"reference\"].as<vector<string> >());\n  cerr << \"Loaded \" << ds.size() << \" references for scoring with \" << metric_name << endl;\n  invert_score = metric->IsErrorMetric();\n\n  if (ds.size() != corpus.size()) {\n    cerr << \"Mismatched number of references (\" << ds.size() << \") and sources (\" << corpus.size() << \")\\n\";\n    return 1;\n  }\n\n  ReadFile ini_rf(conf[\"decoder_config\"].as<string>());\n  Decoder decoder(ini_rf.stream());\n\n  // load initial weights\n  vector<weight_t>& dense_weights = decoder.CurrentWeightVector();\n  SparseVector<weight_t> lambdas;\n  Weights::InitFromFile(conf[\"input_weights\"].as<string>(), &dense_weights);\n  Weights::InitSparseVector(dense_weights, &lambdas);\n\n  const double max_step_size = conf[\"max_step_size\"].as<double>();\n  const double mt_metric_scale = conf[\"mt_metric_scale\"].as<double>();\n\n  assert(corpus.size() > 0);\n  vector<GoodBadOracle> oracles(corpus.size());\n\n  TrainingObserver observer(conf[\"k_best_size\"].as<int>(), ds, *metric, sample_forest, &oracles);\n  int cur_sent = 0;\n  int lcount = 0;\n  int normalizer = 0;\n  double tot_loss = 0;\n  int dots = 0;\n  int cur_pass = 0;\n  SparseVector<double> tot;\n  tot += lambdas;          // initial weights\n  normalizer++;            // count for initial weights\n  int max_iteration = conf[\"passes\"].as<int>() * corpus.size();\n  string msg = \"# MIRA tuned weights\";\n  string msga = \"# MIRA tuned weights AVERAGED\";\n  vector<int> order;\n  RandomPermutation(corpus.size(), &order);\n  while (lcount <= max_iteration) {\n    lambdas.init_vector(&dense_weights);\n    if ((cur_sent * 40 / corpus.size()) > dots) { ++dots; cerr << '.'; }\n    if (corpus.size() == cur_sent) {\n      cerr << \" [AVG METRIC LAST PASS=\" << (tot_loss / corpus.size()) << \"]\\n\";\n      Weights::ShowLargestFeatures(dense_weights);\n      cur_sent = 0;\n      tot_loss = 0;\n      dots = 0;\n      ostringstream os;\n      os << \"weights.mira-pass\" << (cur_pass < 10 ? \"0\" : \"\") << cur_pass << \".gz\";\n      SparseVector<double> x = tot;\n      x /= normalizer;\n      ostringstream sa;\n      sa << \"weights.mira-pass\" << (cur_pass < 10 ? \"0\" : \"\") << cur_pass << \"-avg.gz\";\n      x.init_vector(&dense_weights);\n      Weights::WriteToFile(os.str(), dense_weights, true, &msg);\n      ++cur_pass;\n      RandomPermutation(corpus.size(), &order);\n    }\n    if (cur_sent == 0) {\n      cerr << \"PASS \" << (lcount / corpus.size() + 1) << endl;\n    }\n    decoder.SetId(order[cur_sent]);\n    double sc = 1.0;\n    if (sample_forest_unit_weight_vector) {\n      sc = lambdas.l2norm();\n      if (sc > 0) {\n        for (unsigned i = 0; i < dense_weights.size(); ++i)\n          dense_weights[i] /= sc;\n      }\n    }\n    decoder.Decode(corpus[order[cur_sent]], &observer);  // update oracles\n    if (sc && sc != 1.0) {\n      for (unsigned i = 0; i < dense_weights.size(); ++i)\n        dense_weights[i] *= sc;\n    }\n    const HypothesisInfo& cur_hyp = observer.GetCurrentBestHypothesis();\n    const HypothesisInfo& cur_good = *oracles[order[cur_sent]].good;\n    const HypothesisInfo& cur_bad = *oracles[order[cur_sent]].bad;\n    tot_loss += cur_hyp.mt_metric;\n    if (!ApproxEqual(cur_hyp.mt_metric, cur_good.mt_metric)) {\n      const double loss = cur_bad.features.dot(dense_weights) - cur_good.features.dot(dense_weights) +\n          mt_metric_scale * (cur_good.mt_metric - cur_bad.mt_metric);\n      //cerr << \"LOSS: \" << loss << endl;\n      if (loss > 0.0) {\n        SparseVector<double> diff = cur_good.features;\n        diff -= cur_bad.features;\n        double step_size = loss / diff.l2norm_sq();\n        //cerr << loss << \" \" << step_size << \" \" << diff << endl;\n        if (step_size > max_step_size) step_size = max_step_size;\n        lambdas += (cur_good.features * step_size);\n        lambdas -= (cur_bad.features * step_size);\n        //cerr << \"L: \" << lambdas << endl;\n      }\n    }\n    tot += lambdas;\n    ++normalizer;\n    ++lcount;\n    ++cur_sent;\n  }\n  cerr << endl;\n  Weights::WriteToFile(\"weights.mira-final.gz\", dense_weights, true, &msg);\n  tot /= normalizer;\n  tot.init_vector(dense_weights);\n  msg = \"# MIRA tuned weights (averaged vector)\";\n  Weights::WriteToFile(\"weights.mira-final-avg.gz\", dense_weights, true, &msg);\n  cerr << \"Optimization complete.\\nAVERAGED WEIGHTS: weights.mira-final-avg.gz\\n\";\n  return 0;\n}\n\n", "meta": {"hexsha": "2868de0c265502c40cabe505750be82264e7e06c", "size": 12540, "ext": "cc", "lang": "C++", "max_stars_repo_path": "training/mira/kbest_mira.cc", "max_stars_repo_name": "kho/cdec", "max_stars_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 114.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T05:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T03:47:12.000Z", "max_issues_repo_path": "training/mira/kbest_mira.cc", "max_issues_repo_name": "kho/cdec", "max_issues_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T01:00:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-25T06:04:02.000Z", "max_forks_repo_path": "training/mira/kbest_mira.cc", "max_forks_repo_name": "kho/cdec", "max_forks_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T13:48:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-07T09:45:11.000Z", "avg_line_length": 38.8235294118, "max_line_length": 187, "alphanum_fraction": 0.6548644338, "num_tokens": 3436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18290242931817688}}
{"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#ifndef FILECOIN_STORAGE_PROOFS_CORE_COMPONENTS_VARIABLES_HPP\n#define FILECOIN_STORAGE_PROOFS_CORE_COMPONENTS_VARIABLES_HPP\n\n#include <boost/variant.hpp>\n\n#include <nil/crypto3/zk/snark/blueprint_variable.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        /*!\n         * @brief Root represents a root commitment which may be either a raw value or an already-allocated number.\n         * This allows subcomponents to depend on roots which may optionally be shared with their parent\n         * or sibling components.\n         *\n         * @tparam FieldType\n         */\n        template<typename FieldType>\n        struct root {\n            typedef FieldType field_type;\n\n            typedef boost::variant<crypto3::zk::snark::blueprint_variable<field_type>, typename field_type::value_type>\n                value_type;\n        };\n    }    // namespace filecoin\n}    // namespace nil\n\n#endif // FILECOIN_STORAGE_PROOFS_CORE_COMPONENTS_VARIABLES_HPP\n", "meta": {"hexsha": "e2d4135078ba3d66c25a539b309825202b1621fe", "size": 2351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/components/variables.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/components/variables.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/components/variables.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": 43.537037037, "max_line_length": 119, "alphanum_fraction": 0.676733305, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061854293322, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1829024277817054}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2020, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, 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_STRATEGIES_ENVELOPE_CARTESIAN_HPP\n#define BOOST_GEOMETRY_STRATEGIES_ENVELOPE_CARTESIAN_HPP\n\n\n#include <type_traits>\n\n#include <boost/geometry/strategy/cartesian/envelope.hpp>\n#include <boost/geometry/strategy/cartesian/envelope_box.hpp>\n#include <boost/geometry/strategy/cartesian/envelope_point.hpp>\n#include <boost/geometry/strategy/cartesian/envelope_multipoint.hpp>\n#include <boost/geometry/strategy/cartesian/envelope_segment.hpp>\n\n#include <boost/geometry/strategies/detail.hpp>\n#include <boost/geometry/strategies/envelope/services.hpp>\n#include <boost/geometry/strategies/expand/cartesian.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace envelope\n{\n\ntemplate <typename CalculationType = void>\nstruct cartesian\n    : strategies::expand::cartesian<CalculationType>\n{\n    template <typename Geometry, typename Box>\n    static auto envelope(Geometry const&, Box const&,\n                         typename util::enable_if_point_t<Geometry> * = nullptr)\n    {\n        return strategy::envelope::cartesian_point();\n    }\n\n    template <typename Geometry, typename Box>\n    static auto envelope(Geometry const&, Box const&,\n                         typename util::enable_if_multi_point_t<Geometry> * = nullptr)\n    {\n        return strategy::envelope::cartesian_multipoint();\n    }\n\n    template <typename Geometry, typename Box>\n    static auto envelope(Geometry const&, Box const&,\n                         typename util::enable_if_box_t<Geometry> * = nullptr)\n    {\n        return strategy::envelope::cartesian_box();\n    }\n\n    template <typename Geometry, typename Box>\n    static auto envelope(Geometry const&, Box const&,\n                         typename util::enable_if_segment_t<Geometry> * = nullptr)\n    {\n        return strategy::envelope::cartesian_segment<CalculationType>();\n    }\n\n    template <typename Geometry, typename Box>\n    static auto envelope(Geometry const&, Box const&,\n                         typename util::enable_if_polysegmental_t<Geometry> * = nullptr)\n    {\n        return strategy::envelope::cartesian<CalculationType>();\n    }\n};\n\n\nnamespace services\n{\n\ntemplate <typename Geometry, typename Box>\nstruct default_strategy<Geometry, Box, cartesian_tag>\n{\n    using type = strategies::envelope::cartesian<>;\n};\n\n\ntemplate <>\nstruct strategy_converter<strategy::envelope::cartesian_point>\n{\n    static auto get(strategy::envelope::cartesian_point const& )\n    {\n        return strategies::envelope::cartesian<>();\n    }\n};\n\ntemplate <>\nstruct strategy_converter<strategy::envelope::cartesian_multipoint>\n{\n    static auto get(strategy::envelope::cartesian_multipoint const&)\n    {\n        return strategies::envelope::cartesian<>();\n    }\n};\n\ntemplate <>\nstruct strategy_converter<strategy::envelope::cartesian_box>\n{\n    static auto get(strategy::envelope::cartesian_box const& )\n    {\n        return strategies::envelope::cartesian<>();\n    }\n};\n\ntemplate <typename CT>\nstruct strategy_converter<strategy::envelope::cartesian_segment<CT> >\n{\n    static auto get(strategy::envelope::cartesian_segment<CT> const&)\n    {\n        return strategies::envelope::cartesian<CT>();\n    }\n};\n\ntemplate <typename CT>\nstruct strategy_converter<strategy::envelope::cartesian<CT> >\n{\n    static auto get(strategy::envelope::cartesian<CT> const&)\n    {\n        return strategies::envelope::cartesian<CT>();\n    }\n};\n\n\n} // namespace services\n\n}} // namespace strategies::envelope\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_ENVELOPE_CARTESIAN_HPP\n", "meta": {"hexsha": "3bce5dbc3ec0eb2e472a20940b7ce2371079afce", "size": 3793, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/envelope/cartesian.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/strategies/envelope/cartesian.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/strategies/envelope/cartesian.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.6861313869, "max_line_length": 88, "alphanum_fraction": 0.7110466649, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1829024223733729}}
{"text": "//=============================================================================================================\n/**\n* @file     eegref.cpp\n* @author   Viktor Kl\u00fcber <v.klueber@gmx.net>;\n*           Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     January, 2017\n*\n* @section  LICENSE\n*\n* Copyright (C) 2017, Viktor Kl\u00fcber, Lorenz Esch and Matti Hamalainen. 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*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* 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)\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* @brief    EEGRef class definition.\n*\n*/\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"eegref.h\"\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Dense>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace REFERENCEPLUGIN;\nusing namespace Eigen;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nEEGRef::EEGRef()\n{\n}\n\n\n//*************************************************************************************************************\n\nMatrixXd EEGRef::applyCAR(MatrixXd &matIER, FIFFLIB::FiffInfo::SPtr &pFiffInfo)\n{\n    unsigned int numTrueCh  = 0;\n    unsigned int numCh      = pFiffInfo->chs.size();\n    MatrixXd matOnes        = MatrixXd::Ones(numCh, numCh);\n    MatrixXd matCenter      = MatrixXd::Identity(numCh, numCh);\n\n    //determine the number of true channels\n    for(unsigned int i = 0; i < numCh; ++i)\n    {\n        if(pFiffInfo->chs.at(i).ch_name.contains(\"EEG\") && !pFiffInfo->bads.contains(pFiffInfo->chs.at(i).ch_name))\n        {\n            numTrueCh++;\n        }\n        else\n        {\n            // excluding non-EEG channels from the centering matrix\n            matOnes.row(i).setZero();\n            matOnes.col(i).setZero();\n            matCenter.row(i).setZero();\n            matCenter.col(i).setZero();\n        }\n    }\n\n    //detrmine centering matrix\n    matCenter = matCenter - (1/double(numTrueCh))*matOnes;\n\n    // determine EEG CAR data matrix\n    MatrixXd matCAR = matCenter*matIER;\n\n    //add former excluded non-EEG channels to the EEG CAR data matrix\n    for(unsigned int i = 0; i < numCh; ++i)\n    {\n        if(!pFiffInfo->chs.at(i).ch_name.contains(\"EEG\"))\n        {\n            matCAR.row(i) = matIER.row(i);\n        }\n    }\n\n    return matCAR;\n}\n", "meta": {"hexsha": "99b2ba3bc5355cd2f765aae0ec324c780d649c71", "size": 4889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/mne_scan/plugins/reference/eegref.cpp", "max_stars_repo_name": "ChunmingGu/mne-cpp-master", "max_stars_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T07:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-14T07:38:25.000Z", "max_issues_repo_path": "applications/mne_scan/plugins/reference/eegref.cpp", "max_issues_repo_name": "ChunmingGu/mne-cpp-master", "max_issues_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-23T12:40:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-23T12:40:56.000Z", "max_forks_repo_path": "applications/mne_scan/plugins/reference/eegref.cpp", "max_forks_repo_name": "ChunmingGu/mne-cpp-master", "max_forks_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "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.1465517241, "max_line_length": 116, "alphanum_fraction": 0.4643076294, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1829024223733729}}
{"text": "/**\n * @file fathometer_collection.cc\n * Container for one fathometer_collection instance.\n */\n\n#include <usml/sensors/fathometer_collection.h>\n#include <boost/foreach.hpp>\n\n#include <netcdfcpp.h>\n\nusing namespace boost ;\nusing namespace usml::sensors ;\n\n\n/**\n * Updates the fathometer data with the parameters provided.\n */\nvoid fathometer_collection::dead_reckon(double delta_time,\n                                    double slant_range, double prev_range) {\n    // Set new slant_range\n    _slant_range = slant_range;\n\n    write_lock_guard guard(_eigenrays_mutex);\n\n    eigenray_list::iterator iter;\n    for (iter = _eigenrays.begin(); iter != _eigenrays.end(); ++iter) {\n\n        iter->time = iter->time + delta_time;\n        for (int i = 0; i < iter->frequencies->size(); ++i) {\n        \titer->intensity[i] = iter->intensity[i] -\n                (20*log10(prev_range)) + (20*log10(_slant_range));\n        }\n    }\n}\n\n/**\n * Write fathometer_collection data to to netCDF file.\n */\nvoid fathometer_collection::write_netcdf( const char* filename, const char* long_name )\n{\n\n    NcFile* nc_file = new NcFile(filename, NcFile::Replace);\n    if (long_name) {\n        nc_file->add_att(\"long_name\", long_name);\n    }\n    nc_file->add_att(\"Conventions\", \"COARDS\");\n\n    //read_lock_guard guard(_eigenrays_mutex);\n    if ( _eigenrays.size() == 0 ) {\n        nc_file->add_att(\"Eigenrays\", \"None Found\");\n        // close file\n        delete nc_file;\n        return;\n    }\n    // Get the list to get the frequency size\n    long num_frequencies = ( long ) _eigenrays.front().frequencies->size();\n\n    // dimensions\n\n    NcDim *freq_dim = nc_file->add_dim(\"frequency\", num_frequencies);\n    NcVar *freq_var = nc_file->add_var(\"frequency\", ncDouble, freq_dim);\n    NcDim *eigenray_dim = nc_file->add_dim(\"eigenrays\", ( long ) _eigenrays.size());\n   \n    // fathometer_collection attributes\n\n    NcVar *source_id = nc_file->add_var(\"source_id\", ncShort);\n    NcVar *receiver_id = nc_file->add_var(\"receiver_id\", ncShort);\n    NcVar *initial_time = nc_file->add_var(\"initial_time\", ncDouble);\n    NcVar *slant_range = nc_file->add_var(\"slant_range\", ncDouble);\n\n    // coordinates\n\n    NcVar *src_lat_var = nc_file->add_var(\"source_latitude\", ncDouble);\n    NcVar *src_lng_var = nc_file->add_var(\"source_longitude\", ncDouble);\n    NcVar *src_alt_var = nc_file->add_var(\"source_altitude\", ncDouble);\n\n    NcVar *rcv_lat_var = nc_file->add_var(\"receiver_latitude\", ncDouble);\n    NcVar *rcv_lng_var = nc_file->add_var(\"receiver_longitude\", ncDouble);\n    NcVar *rcv_alt_var = nc_file->add_var(\"receiver_altitude\", ncDouble);\n\n    NcVar *intensity_var = nc_file->add_var(\"intensity\", ncDouble, eigenray_dim, freq_dim);\n    NcVar *phase_var = nc_file->add_var(\"phase\", ncDouble, eigenray_dim, freq_dim);\n    NcVar *time_var = nc_file->add_var(\"travel_time\", ncDouble, eigenray_dim);\n    NcVar *source_de_var = nc_file->add_var(\"source_de\", ncDouble, eigenray_dim);\n    NcVar *source_az_var = nc_file->add_var(\"source_az\", ncDouble, eigenray_dim);\n    NcVar *target_de_var = nc_file->add_var(\"target_de\", ncDouble, eigenray_dim);\n    NcVar *target_az_var = nc_file->add_var(\"target_az\", ncDouble, eigenray_dim);\n    NcVar *surface_var = nc_file->add_var(\"surface\", ncShort, eigenray_dim);\n    NcVar *bottom_var = nc_file->add_var(\"bottom\", ncShort, eigenray_dim);\n    NcVar *caustic_var = nc_file->add_var(\"caustic\", ncShort, eigenray_dim);\n    NcVar *upper_var = nc_file->add_var(\"upper\", ncShort, eigenray_dim);\n    NcVar *lower_var = nc_file->add_var(\"lower\", ncShort, eigenray_dim);\n\n    // units\n\n    freq_var->add_att(\"units\", \"Hertz\");\n    src_lat_var->add_att(\"units\", \"degrees_north\");\n    src_lng_var->add_att(\"units\", \"degrees_east\");\n    src_alt_var->add_att(\"units\", \"meters\");\n    src_alt_var->add_att(\"positive\", \"up\");\n\n    rcv_lat_var->add_att(\"units\", \"degrees_north\");\n    rcv_lng_var->add_att(\"units\", \"degrees_east\");\n    rcv_alt_var->add_att(\"units\", \"meters\");\n    rcv_alt_var->add_att(\"positive\", \"up\");\n\n    intensity_var->add_att(\"units\", \"dB\");\n    phase_var->add_att(\"units\", \"radians\");\n    time_var->add_att(\"units\", \"seconds\");\n\n    source_de_var->add_att(\"units\", \"degrees\");\n    source_de_var->add_att(\"positive\", \"up\");\n    source_az_var->add_att(\"units\", \"degrees_true\");\n    source_az_var->add_att(\"positive\", \"clockwise\");\n\n    target_de_var->add_att(\"units\", \"degrees\");\n    target_de_var->add_att(\"positive\", \"up\");\n    target_az_var->add_att(\"units\", \"degrees_true\");\n    target_az_var->add_att(\"positive\", \"clockwise\");\n\n    surface_var->add_att(\"units\", \"count\");\n    bottom_var->add_att(\"units\", \"count\");\n    caustic_var->add_att(\"units\", \"count\");\n    upper_var->add_att(\"units\", \"count\");\n    lower_var->add_att(\"units\", \"count\");\n\n    int item;\n    double v;\n    int record = 0; // current record number\n\n    \n    // write base attributes\n\n    freq_var->put(_eigenrays.front().frequencies->data().begin(), num_frequencies);\n    item = _source_id; source_id->put(&item, 1);\n    item = _receiver_id; receiver_id->put(&item, 1); \n\n    v = _initial_time;  initial_time->put(&v, 1);\n    v = _slant_range;   slant_range->put(&v, 1);\n\n    // write source parameters\n\n    v = _source_position.latitude();    src_lat_var->put(&v, 1);\n    v = _source_position.longitude();   src_lng_var->put(&v, 1);\n    v = _source_position.altitude();    src_alt_var->put(&v, 1);\n\n    // write receiver parameters\n\n    v = _receiver_position.latitude();    rcv_lat_var->put(&v, 1);\n    v = _receiver_position.longitude();   rcv_lng_var->put(&v, 1);\n    v = _receiver_position.altitude();    rcv_alt_var->put(&v, 1);\n\n    BOOST_FOREACH(eigenray ray, _eigenrays)\n    {\n        // set record number for each eigenray data element\n\n        intensity_var->set_cur(record);\n        phase_var->set_cur(record);\n        time_var->set_cur(record);\n        source_de_var->set_cur(record);\n        source_az_var->set_cur(record);\n        target_de_var->set_cur(record);\n        target_az_var->set_cur(record);\n        surface_var->set_cur(record);\n        bottom_var->set_cur(record);\n        caustic_var->set_cur(record);\n        upper_var->set_cur(record);\n        lower_var->set_cur(record);\n        ++record;\n\n        intensity_var->put(ray.intensity.data().begin(), 1, num_frequencies);\n        phase_var->put(ray.phase.data().begin(), 1, num_frequencies);\n        time_var->put(&( ray.time ), 1);\n        source_de_var->put(&( ray.source_de ), 1);\n        source_az_var->put(&( ray.source_az ), 1);\n        target_de_var->put(&( ray.target_de ), 1);\n        target_az_var->put(&( ray.target_az ), 1);\n        surface_var->put(&( ray.surface ), 1);\n        bottom_var->put(&( ray.bottom ), 1);\n        caustic_var->put(&( ray.caustic ), 1);\n        upper_var->put(&( ray.caustic ), 1);\n        lower_var->put(&( ray.caustic ), 1);\n\n    } // loop over # of eigenrays\n\n    // close file\n    delete nc_file; // destructor frees all netCDF temp variables\n}\n\n\n", "meta": {"hexsha": "0912b2bc3916d7dac15232bf0601bc515ed1331c", "size": 6952, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sensors/fathometer_collection.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "sensors/fathometer_collection.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "sensors/fathometer_collection.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": 36.3979057592, "max_line_length": 91, "alphanum_fraction": 0.6582278481, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1829024223733729}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_UNIFORM_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_UNIFORM_RNG_HPP\n\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/variate_generator.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_not_nan.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n\nnamespace stan {\nnamespace math {\n\ntemplate <class RNG>\ninline double uniform_rng(double alpha, double beta, RNG& rng) {\n  using boost::random::uniform_real_distribution;\n  using boost::variate_generator;\n\n  static const char* function = \"uniform_rng\";\n\n  check_finite(function, \"Lower bound parameter\", alpha);\n  check_finite(function, \"Upper bound parameter\", beta);\n  check_greater(function, \"Upper bound parameter\", beta, alpha);\n\n  variate_generator<RNG&, uniform_real_distribution<> > uniform_rng(\n      rng, uniform_real_distribution<>(alpha, beta));\n  return uniform_rng();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "40ddbbd61a89ed0b7c15f54942680113851a4870", "size": 1261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/prob/uniform_rng.hpp", "max_stars_repo_name": "sakrejda/math", "max_stars_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "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/uniform_rng.hpp", "max_issues_repo_name": "sakrejda/math", "max_issues_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "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/uniform_rng.hpp", "max_forks_repo_name": "sakrejda/math", "max_forks_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "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.0810810811, "max_line_length": 68, "alphanum_fraction": 0.7819191118, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.18290242237337287}}
{"text": "/*Copyright (c) 2020 James Gayvert\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/*\n * qchem_interface.cpp\n */\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n#include <string>\n#include \"qchem_interface.h\"\n#include \"opencap_exception.h\"\n#include \"gto_ordering.h\"\n#include \"utils.h\"\n#include \"BasisSet.h\"\n#include <Eigen/Dense>\n\n\nstd::array<std::vector<std::vector<Eigen::MatrixXd>>,2> qchem_read_dms(std::string fchk_filename,BasisSet &bs)\n{\n\tstd::ifstream is(fchk_filename);\n\tsize_t nstates = 0;\n\tbool sep_alpha_beta;\n\tstd::string line, rest;\n\twhile(is.peek() != EOF )\n\t{\n    \tstd::getline(is, line);\n    \tif(line.find(\"Alpha  State Density\")!= std::string::npos)\n    \t{\n    \t\tsep_alpha_beta=true;\n\t\t\tint num_elements = stoi(split(line,' ').back());\n\t\t\tif(sqrt(num_elements)!=bs.Nbasis)\n\t\t\t\topencap_throw(\"Error: dimensions of DMs do not match specified basis set.\");\n    \t\tbreak;\n    \t}\n    \telse if(line.find(\"State Density\")!= std::string::npos)\n    \t{\n    \t\tsep_alpha_beta=false;\n\t\t\tint num_elements = stoi(split(line,' ').back());\n\t\t\tif(sqrt(num_elements)!=bs.Nbasis)\n\t\t\t\topencap_throw(\"Error: dimensions of state DMs do not match specified basis set.\");\n    \t\tbreak;\n    \t}\n\t}\n\tis.seekg (0, ios::beg);\n\twhile(is.peek()!=EOF)\n\t{\n    \tstd::getline(is, line);\n    \tif(line.find(\"Alpha  State Density\")!= std::string::npos && sep_alpha_beta)\n    \t\tnstates++;\n    \telse if(line.find(\"State Density\")!= std::string::npos && !sep_alpha_beta)\n    \t\tnstates++;\n\t}\n\tif(nstates==0)\n\t\topencap_throw(\"Error:Unable to find any densities in:\" +fchk_filename);\n\tif(sep_alpha_beta)\n\t\treturn qchem_read_in_dms_open_shell(fchk_filename,nstates,bs);\n\telse\n\t\treturn qchem_read_in_dms_closed_shell(fchk_filename,nstates,bs);\n\n\n}\n\nstd::array<std::vector<std::vector<Eigen::MatrixXd>>,2> qchem_read_in_dms_open_shell(std::string dmat_filename,\n\t\tsize_t nstates, BasisSet bs)\n{\n\tstd::vector< std::vector<Eigen::MatrixXd>> alpha_opdms(nstates, std::vector<Eigen::MatrixXd> (nstates));\n\tstd::vector< std::vector<Eigen::MatrixXd>> beta_opdms(nstates, std::vector<Eigen::MatrixXd> (nstates));\n\t//start with state density matrices, alpha and beta densities\n\tstd::ifstream is(dmat_filename);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n    \tfor (size_t i=0;i<nstates;i++)\n    \t{\n    \t\t\t//alpha first, then beta\n    \t\t\tfor(size_t spin=1;spin<=2;spin++)\n    \t\t\t{\n\t\t\t\t\twhile(line.find(\"State Density\")== std::string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::getline(is,line);\n\t    \t    \t\tif (is.peek()==EOF)\n\t    \t    \t\t\topencap_throw(\"Error: Reached end of file before densities for \"+\n\t    \t    \t\t\t\t\tstd::to_string(nstates) + \" states were found.\");\n\t\t\t\t\t}\n\t\t\t\t\t//last part of line should be number of elements to read\n\t\t\t\t\tint num_elements = stoi(split(line,' ').back());\n\t\t\t\t\tif(sqrt(num_elements)!=bs.Nbasis)\n\t\t\t\t\t\topencap_throw(\"Error: dimensions of TDMs do not match specified basis set.\");\n\t\t\t\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\t\t\t\tstd::vector<double> matrix_elements;\n\t\t\t\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::getline(is,line);\n\t\t\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\t\t\tfor (auto token:tokens)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmatrix_elements.push_back(std::stod(token));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tEigen::MatrixXd st_opdm(bs.Nbasis,bs.Nbasis);\n\t\t\t\t\tst_opdm=Eigen::MatrixXd::Zero(bs.Nbasis,bs.Nbasis);\n\t\t\t\t\tfill_mat(matrix_elements,st_opdm);\n\t\t\t\t\tto_opencap_ordering(st_opdm,bs,get_qchem_ids(bs));\n\t\t\t\t\tif(spin==1)\n\t\t\t\t\t\talpha_opdms[i][i]=st_opdm;\n\t\t\t\t\telse\n\t\t\t\t\t\tbeta_opdms[i][i]=st_opdm;\n    \t\t\t}\n\t\t}\n    \t//now tdms\n    \tfor(size_t i=0;i<nstates;i++)\n    \t{\n    \t\tfor (size_t j=i+1;j<nstates;j++)\n    \t\t{\n    \t\t\t//alpha first, then beta\n    \t\t\tfor (size_t spin=1;spin<=2;spin++)\n    \t\t\t{\n\t\t\t\t\twhile(line.find(\"Transition DM\")== std::string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::getline(is,line);\n\t    \t    \t\tif (is.peek()==EOF)\n\t    \t    \t\t\topencap_throw(\"Error: Reached end of file before densities for \"+\n\t    \t    \t\t\t\t\tstd::to_string(nstates) + \" states were found.\");\n\t\t\t\t\t}\n\t\t\t\t\t//last part of line should be number of elements to read\n\t\t\t\t\tsize_t num_elements = stoi(split(line,' ').back());\n\t\t\t\t\tif(sqrt(num_elements)!=bs.Nbasis)\n\t\t\t\t\t\topencap_throw(\"Error: dimensions of TDMs do not match specified basis set.\");\n\t\t\t\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\t\t\t\tstd::vector<double> matrix_elements;\n\t\t\t\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::getline(is,line);\n\t\t\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\t\t\tfor (auto token:tokens)\n\t\t\t\t\t\t\tmatrix_elements.push_back(std::stod(token));\n\t\t\t\t\t}\n\t\t\t\t\tEigen::MatrixXd st_opdm(bs.Nbasis,bs.Nbasis);\n\t\t\t\t\tst_opdm=Eigen::MatrixXd::Zero(bs.Nbasis,bs.Nbasis);\n\t\t\t\t\tfill_mat(matrix_elements,st_opdm);\n\t\t\t\t\tto_opencap_ordering(st_opdm,bs,get_qchem_ids(bs));\n\t\t\t\t\tif(spin==1)\n\t\t\t\t\t{\n\t\t\t\t\t\talpha_opdms[i][j]=st_opdm;\n\t\t\t\t\t\talpha_opdms[j][i]=st_opdm;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbeta_opdms[i][j]=st_opdm;\n\t\t\t\t\t\tbeta_opdms[j][i]=st_opdm;\n\t\t\t\t\t}\n    \t\t\t}\n    \t\t}\n    \t}\n    }\n    return {alpha_opdms,beta_opdms};\n}\n\nEigen::MatrixXd qchem_read_overlap(std::string dmat_filename, BasisSet bs)\n{\n\tsize_t num_bf = bs.Nbasis;\n    std::ifstream is(dmat_filename);\n\tEigen::MatrixXd smat(num_bf,num_bf);\n\tsmat=Eigen::MatrixXd::Zero(num_bf,num_bf);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \twhile (line.find(\"Overlap Matrix\")== std::string::npos)\n    \t{\n        \tstd::getline(is, line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Overlap Matrix was found.\");\n    \t}\n    \tsize_t num_elements = stoi(split(line,' ').back());\n\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tstd::vector<double> matrix_elements;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tmatrix_elements.push_back(std::stod(token));\n\t\t}\n\t\tfill_LT(matrix_elements,smat);\n\t\tto_opencap_ordering(smat,bs,get_qchem_ids(bs));\n    }\n    return smat;\n}\n\nEigen::MatrixXd read_qchem_energies(size_t nstates,std::string method,std::string output_file)\n{\n\tEigen::MatrixXd ZERO_ORDER_H(nstates,nstates);\n\tZERO_ORDER_H=Eigen::MatrixXd::Zero(nstates,nstates);\n\ttransform(method.begin(),method.end(),method.begin(),::toupper);\n\tstd::ifstream is(output_file);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n    \tsize_t state_idx = 1;\n    \twhile (state_idx<=nstates)\n    \t{\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before \"+ std::to_string(nstates) + \" energies were found.\");\n    \t\tstd::string line_to_find = method +\" transition \" + std::to_string(state_idx);\n    \t\tif (line.find(line_to_find)!= std::string::npos)\n    \t\t{\n\t\t\t\tstd::getline(is,line);\n\t\t\t\tZERO_ORDER_H(state_idx-1,state_idx-1) = std::stod(split(line,' ')[3]);\n\t\t\t\tstate_idx++;\n    \t\t}\n    \t\telse\n    \t\t\tstd::getline(is,line);\n    \t}\n    }\n    return ZERO_ORDER_H;\n}\n\nstd::array<std::vector<std::vector<Eigen::MatrixXd>>,2> qchem_read_in_dms_closed_shell(std::string dmat_filename,\n\t\tsize_t nstates, BasisSet bs)\n{\n\tstd::vector< std::vector<Eigen::MatrixXd>> opdms(nstates, std::vector<Eigen::MatrixXd> (nstates));\n\t//start with state density matrices\n\tstd::ifstream is(dmat_filename);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n    \tfor (size_t i=0;i<nstates;i++)\n    \t{\n\t\t\t\twhile(line.find(\"State Density\")== std::string::npos)\n\t\t\t\t{\n\t\t\t\t\tstd::getline(is,line);\n    \t    \t\tif (is.peek()==EOF)\n    \t    \t\t\topencap_throw(\"Error: Reached end of file before densities for \"+\n    \t    \t\t\t\t\tstd::to_string(nstates) + \" states were found.\");\n\t\t\t\t}\n\t\t\t\t//last part of line should be number of elements to read\n\t\t\t\tsize_t num_elements = stoi(split(line,' ').back());\n\t\t\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\t\t\tstd::vector<double> matrix_elements;\n\t\t\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t\t\t{\n\t\t\t\t\tstd::getline(is,line);\n\t\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\t\tfor (auto token:tokens)\n\t\t\t\t\t{\n\t\t\t\t\t\tmatrix_elements.push_back(std::stod(token));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tEigen::MatrixXd st_opdm(bs.Nbasis,bs.Nbasis);\n\t\t\t\tst_opdm=Eigen::MatrixXd::Zero(bs.Nbasis,bs.Nbasis);\n\t\t\t\tfill_mat(matrix_elements,st_opdm);\n\t\t\t\tto_opencap_ordering(st_opdm,bs,get_qchem_ids(bs));\n\t\t\t\topdms[i][i]=0.5*st_opdm;\n\t\t}\n    \t//now tdms\n    \tfor(size_t i=0;i<nstates;i++)\n    \t{\n    \t\tfor (size_t j=i+1;j<nstates;j++)\n    \t\t{\n\t\t\t\twhile(line.find(\"Transition DM\")== std::string::npos)\n\t\t\t\t{\n\t\t\t\t\tstd::getline(is,line);\n    \t    \t\tif (is.peek()==EOF)\n    \t    \t\t\topencap_throw(\"Error: Reached end of file before densities for \"+\n    \t    \t\t\t\t\tstd::to_string(nstates) + \" states were found.\");\n\t\t\t\t}\n\t\t\t\t//last part of line should be number of elements to read\n\t\t\t\tsize_t num_elements = stoi(split(line,' ').back());\n\t\t\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\t\t\tstd::vector<double> matrix_elements;\n\t\t\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t\t\t{\n\t\t\t\t\tstd::getline(is,line);\n\t\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\t\tfor (auto token:tokens)\n\t\t\t\t\t\tmatrix_elements.push_back(std::stod(token));\n\t\t\t\t}\n\t\t\t\tEigen::MatrixXd st_opdm(bs.Nbasis,bs.Nbasis);\n\t\t\t\tst_opdm=Eigen::MatrixXd::Zero(bs.Nbasis,bs.Nbasis);\n\t\t\t\tfill_mat(matrix_elements,st_opdm);\n\t\t\t\tto_opencap_ordering(st_opdm,bs,get_qchem_ids(bs));\n\t\t\t\topdms[i][j]=0.5*st_opdm;\n\t\t\t\topdms[j][i]=0.5*st_opdm;\n    \t\t}\n    \t}\n    }\n    return {opdms,opdms};\n\n}\n\nstd::vector<Atom> read_geometry_from_fchk(std::string fchk_filename)\n{\n\tstd::vector<Atom> atoms;\n\tstd::vector<size_t> atom_nums;\n\tstd::vector<double> coords;\n\tstd::ifstream is(fchk_filename);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n\t\twhile(line.find(\"Atomic numbers\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before atomic numbers were found.\");\n\t\t}\n\t\tsize_t num_elements = stoi(split(line,' ').back());\n\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tatom_nums.push_back(std::stoi(token));\n\t\t}\n\t\twhile(line.find(\"Current cartesian coordinates\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Current Cartesian Coordinates were found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tcoords.push_back(std::stod(token));\n\t\t}\n\t\t//ok now lets populate our atoms\n\t\tfor(size_t i=0;i<atom_nums.size();i++)\n\t\t\tatoms.push_back(Atom(atom_nums[i],coords[i*3],coords[i*3+1],coords[i*3+2]));\n    }\n    else\n    {\n    \topencap_throw(\"Error: I couldn't read:\" + fchk_filename);\n    }\n    return atoms;\n}\n\nBasisSet read_basis_from_fchk(std::string fchk_filename, std::vector<Atom> atoms)\n{\n\tstd::vector<int> shell_types;\n\tstd::vector<int> prims_per_shell;\n\tstd::vector<int> atom_ids;\n\tstd::vector<double> exps;\n\tstd::vector<double> coeffs;\n\t// needed for SP specification\n\tstd::vector<double> p_coeffs;\n\tbool SP_basis_function = true;\n\tBasisSet bs;\n\tfor(auto atm:atoms)\n\t\tbs.centers.push_back(atm.coords);\n\tstd::vector<shell_id> ids;\n\tstd::ifstream is(fchk_filename);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n    \t//First lets figure out if there are SP functions\n    \t//shell types\n\t\twhile(line.find(\"Shell types\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before shell types were found.\");\n\t\t}\n\t\tsize_t num_elements = stoi(split(line,' ').back());\n\t\tsize_t lines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t{\n\t\t\t\tshell_types.push_back(std::stoi(token));\n\t\t\t}\n\t\t}\n\t\t//prims per shell\n\t\twhile(line.find(\"Number of primitives per shell\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Number of primitives per shell were found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tprims_per_shell.push_back(std::stoi(token));\n\t\t}\n\t\t//atom ids\n\t\twhile(line.find(\"Shell to atom map\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Shell to atom map was found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tatom_ids.push_back(std::stoi(token));\n\t\t}\n\t\t//prims\n\t\twhile(line.find(\"Primitive exponents\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Primitive exponents were found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\texps.push_back(std::stod(token));\n\t\t}\n\t\t//coeffs\n\t\twhile(line.find(\"Contraction coefficients\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Contraction coefficients were found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tcoeffs.push_back(std::stod(token));\n\t\t}\n\t\twhile(line.find(\"P(S=P) Contraction coefficients\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t{\n    \t\t\tSP_basis_function = false;\n    \t\t\tbreak;\n    \t\t}\n\t\t}\n\t\tif (SP_basis_function)\n\t\t{\n\t\t\tnum_elements = stoi(split(line,' ').back());\n\t\t\tlines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t\t{\n\t\t\t\tstd::getline(is,line);\n\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\tfor (auto token:tokens)\n\t\t\t\t\tp_coeffs.push_back(std::stod(token));\n\t\t\t}\n\t\t}\n    }\n    size_t prim_idx=0;\n    for(size_t i=0;i<shell_types.size();i++)\n    {\n    \t//SP\n    \tif(shell_types[i]==-1)\n    \t{\n    \t\tif(p_coeffs.size()==0)\n    \t\t\topencap_throw(\"Error: missing section P(S=P) Contraction coefficients.\");\n    \t\tShell s_shell(0,atoms[atom_ids[i]-1].coords);\n    \t\tShell p_shell(1,atoms[atom_ids[i]-1].coords);\n\t\t\tint num_prims = prims_per_shell[i];\n\t\t\tfor(int j=1;j<=num_prims;j++)\n\t\t\t{\n\t\t\t\ts_shell.add_primitive(exps[prim_idx],coeffs[prim_idx]);\n\t\t\t\tp_shell.add_primitive(exps[prim_idx],p_coeffs[prim_idx]);\n\t\t\t\tprim_idx++;\n\t\t\t}\n\t\t\tbs.add_shell(s_shell);\n\t\t\tbs.add_shell(p_shell);\n    \t}\n    \telse\n    \t{\n\t\t\tShell new_shell(abs(shell_types[i]),atoms[atom_ids[i]-1].coords);\n\t\t\tif(shell_types[i]>0 && new_shell.l>1)\n\t\t\t\tnew_shell.pure=false;\n\t\t\tint num_prims = prims_per_shell[i];\n\t\t\tfor(int j=1;j<=num_prims;j++)\n\t\t\t{\n\t\t\t\tnew_shell.add_primitive(exps[prim_idx],coeffs[prim_idx]);\n\t\t\t\tprim_idx++;\n\t\t\t}\n\t\t\tbs.add_shell(new_shell);\n    \t}\n    }\n    bs.normalize();\n    return bs;\n}\n", "meta": {"hexsha": "a7920688f11be88f4ecc4a3acfae981b11f241cc", "size": 17166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/qchem_interface.cpp", "max_stars_repo_name": "trex47/opencap", "max_stars_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "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": "opencap/src/qchem_interface.cpp", "max_issues_repo_name": "trex47/opencap", "max_issues_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencap/src/qchem_interface.cpp", "max_forks_repo_name": "trex47/opencap", "max_forks_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "max_forks_repo_licenses": ["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.6349809886, "max_line_length": 113, "alphanum_fraction": 0.6482581848, "num_tokens": 4851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.18290241542856905}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\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\r\n#include <iostream>\r\n#include <sstream>\r\n#include <stdexcept>\r\n\r\n#include <boost/uuid/uuid.hpp>\r\n#include <boost/uuid/uuid_generators.hpp>\r\n#include <boost/uuid/uuid_io.hpp>\r\n\r\n#include \"rttbStructure.h\"\r\n#include \"rttbNullPointerException.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace core\r\n\t{\r\n\r\n\t\t/*! Compares two polygons in the same plane.\r\n\t\t\tHelper function for sorting of polygons.\r\n\t\t*/\r\n\t\tbool comparePolygon(PolygonType A, PolygonType B)\r\n\t\t{\r\n\t\t\tPolygonType::iterator it;\r\n\r\n\t\t\tfor (it = A.begin(); it != A.end(); ++it)\r\n\t\t\t{\r\n\t\t\t\tif ((*it)(2) != A.at(0)(2))\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow std::range_error(\"Error: A must in the same _z plane!\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tPolygonType::iterator it2;\r\n\r\n\t\t\tfor (it2 = B.begin(); it2 != B.end(); ++it2)\r\n\t\t\t{\r\n\t\t\t\tif ((*it2)(2) != B.at(0)(2))\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow std::range_error(\"Error: B must in the same _z plane!\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (A.size() == 0 || B.size() == 0)\r\n\t\t\t{\r\n\t\t\t\tthrow std::range_error(\"Error: A and B must not be empty!\");\r\n\t\t\t}\r\n\r\n\t\t\treturn (A.at(0)(2) < B.at(0)(2));\r\n\r\n\t\t}\r\n\r\n\t\tStructure::Structure() : _structureVector(0), _label(\"\")\r\n\t\t{\r\n\t\t\tif (_strUID.empty())\r\n\t\t\t{\r\n\t\t\t\tboost::uuids::uuid id;\r\n\t\t\t\tboost::uuids::random_generator generator;\r\n\t\t\t\tid = generator();\r\n\r\n\t\t\t\tstd::stringstream ss;\r\n\t\t\t\tss << id;\r\n\r\n\t\t\t\t_strUID = ss.str();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tStructure::Structure(PolygonSequenceType strVector) : Structure()\r\n\t\t{\r\n\t\t\t_structureVector = strVector;\r\n\t\t\tsort(_structureVector.begin(), _structureVector.end(), comparePolygon);\r\n\t\t}\r\n\r\n\r\n\t\tStructure::Structure(const Structure& copy) : _structureVector(copy.getStructureVector()),\r\n\t\t\t_strUID(copy.getUID()),\r\n\t\t\t_label(copy.getLabel())\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tStructure::~Structure() = default;\r\n\r\n\t\tconst PolygonSequenceType& Structure::getStructureVector() const\r\n\t\t{\r\n\t\t\treturn _structureVector;\r\n\t\t}\r\n\r\n\r\n\r\n\t\tint Structure::getNumberOfEndpoints() const\r\n\t\t{\r\n\t\t\tint count = 0;\r\n\t\t\tPolygonSequenceType::const_iterator itVV;\r\n\r\n\t\t\tfor (itVV = _structureVector.begin(); itVV != _structureVector.end(); ++itVV)\r\n\t\t\t{\r\n\t\t\t\tcount += (int)(*itVV).size();\r\n\t\t\t}\r\n\r\n\t\t\treturn count;\r\n\t\t}\r\n\r\n\t\tIDType Structure::getUID() const\r\n\t\t{\r\n\r\n\t\t\treturn _strUID;\r\n\t\t}\r\n\r\n\t\tvoid Structure::setUID(const IDType& aUID)\r\n\t\t{\r\n\t\t\t_strUID = aUID;\r\n\t\t}\r\n\r\n\t\tvoid Structure::setLabel(const StructureLabel& aLabel)\r\n\t\t{\r\n\t\t\t_label = aLabel;\r\n\t\t}\r\n\r\n\t\tStructureLabel Structure::getLabel() const\r\n\t\t{\r\n\t\t\treturn _label;\r\n\t\t}\r\n\r\n\t}//end namespace core\r\n}//end namespace rttb\r\n", "meta": {"hexsha": "22dfe89f40ac2402b21ec23cd359aa169c41e62e", "size": 3183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/core/rttbStructure.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "code/core/rttbStructure.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "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/core/rttbStructure.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 22.7357142857, "max_line_length": 93, "alphanum_fraction": 0.5984919887, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18290241542856903}}
{"text": "#include <tf/transform_datatypes.h>\n\n#include <urdf_parser/urdf_parser.h>\n\n#include <boost/assign.hpp>\n#include <angles/angles.h>\n#include <control_toolbox/filters.h>\n#include <walrus_pod_controller/walrus_pod_controller.h>\n\nnamespace walrus_pod_controller{\n\nPod::Pod(ros::NodeHandle nh)\n  : nh_(nh), next_state_update_(0), controller_state_period_(0.5),\n    command_timeout_(0.5) {\n  last_command_.mode = walrus_pod_controller::PodCommand::DISABLED;\n}\n\nbool Pod::init(hardware_interface::EffortJointInterface* hw, urdf::Model urdf) {\n  std::string joint_name;\n\n  nh_.param(\"command_timeout\", command_timeout_, command_timeout_);\n\n  if (!nh_.getParam(\"joint\", joint_name)) {\n    ROS_ERROR(\"No joint given (namespace: %s)\", nh_.getNamespace().c_str());\n    return false;\n  }\n\n  joint_ = hw->getHandle(joint_name);\n  boost::shared_ptr<const urdf::Joint> joint_urdf =  urdf.getJoint(joint_name);\n  if (!joint_urdf) {\n    ROS_ERROR(\"Could not find joint '%s' in urdf\", joint_name.c_str());\n    return false;\n  }\n\n  if (!pid_controller_.init(ros::NodeHandle(nh_, \"pid\")))\n    return false;\n\n  controller_state_publisher_.reset(new realtime_tools::RealtimePublisher<control_msgs::JointControllerState>(nh_, \"state\", 1));\n\n  command_sub_ = nh_.subscribe<walrus_pod_controller::PodCommand>(\"command\", 1, &Pod::setCommandCallback, this);\n}\n\nvoid Pod::setCommandCallback(const walrus_pod_controller::PodCommandConstPtr& command) {\n  walrus_pod_controller::PodCommandStamped command_stamped;\n  command_stamped.header.stamp = ros::Time::now();\n  command_stamped.command = *command;\n  command_buffer_.writeFromNonRT(command_stamped);\n}\n\nvoid Pod::starting(const ros::Time& time) {\n  walrus_pod_controller::PodCommandStamped command;\n  command.header.stamp = ros::Time(0);\n  command.command.mode = walrus_pod_controller::PodCommand::HOLD_POSITION;\n  command_buffer_.initRT(command);\n}\n\nvoid Pod::stopping(const ros::Time& time) {\n  joint_.setCommand(0.0); // set joint effort to zero\n}\n\nvoid Pod::update(const ros::Time& time, const ros::Duration& period) {\n  double current_position = joint_.getPosition();\n  walrus_pod_controller::PodCommandStamped command_stamped = *(command_buffer_.readFromRT());\n\n  const double dt = (time - command_stamped.header.stamp).toSec();\n  double command_effort;\n  double command_position;\n  double error;\n\n  walrus_pod_controller::PodCommand command = command_stamped.command;\n  if (dt > command_timeout_) {\n    // timeout\n    command.mode = walrus_pod_controller::PodCommand::DISABLED;\n  }\n\n  if(command.mode == walrus_pod_controller::PodCommand::POSITION ||\n     command.mode == walrus_pod_controller::PodCommand::HOLD_POSITION) {\n    // switching to position mode so reset the pid controller\n    if(last_command_.mode != walrus_pod_controller::PodCommand::POSITION &&\n       last_command_.mode != walrus_pod_controller::PodCommand::HOLD_POSITION) {\n      pid_controller_.reset();\n    }\n\n    if(command.mode == walrus_pod_controller::PodCommand::HOLD_POSITION) {\n      // Hold the position that was held last time\n      if(last_command_.mode == walrus_pod_controller::PodCommand::HOLD_POSITION) {\n\tcommand.set_point = last_command_.set_point;\n      }\n      else {\n\tcommand.set_point = current_position;\n      }\n    }\n\n    command_position = filters::clamp(command.set_point, -M_PI, M_PI);\n    error = angles::shortest_angular_distance(current_position, command_position);\n    command_effort = pid_controller_.computeCommand(error, period);\n  }\n  else if(command.mode == walrus_pod_controller::PodCommand::EFFORT) {\n    command_position = std::numeric_limits<double>::quiet_NaN();\n    error = std::numeric_limits<double>::quiet_NaN();\n    command_effort = command.set_point;\n  }\n  else { // disabled\n    command_position = std::numeric_limits<double>::quiet_NaN();\n    error = std::numeric_limits<double>::quiet_NaN();\n    command_effort = 0.0;\n  }\n  last_command_ = command;\n  joint_.setCommand(command_effort);\n\n  // publish state\n  if (time > next_state_update_) {\n    if(controller_state_publisher_ && controller_state_publisher_->trylock()) {\n      controller_state_publisher_->msg_.header.stamp = time;\n      controller_state_publisher_->msg_.set_point = command_position;\n      controller_state_publisher_->msg_.process_value = current_position;\n      controller_state_publisher_->msg_.process_value_dot = joint_.getVelocity();\n      controller_state_publisher_->msg_.error = error;\n      controller_state_publisher_->msg_.time_step = period.toSec();\n      controller_state_publisher_->msg_.command = command_effort;\n\n      double dummy;\n      pid_controller_.getGains(controller_state_publisher_->msg_.p,\n\t\t\t       controller_state_publisher_->msg_.i,\n\t\t\t       controller_state_publisher_->msg_.d,\n\t\t\t       controller_state_publisher_->msg_.i_clamp,\n\t\t\t       dummy);\n      controller_state_publisher_->unlockAndPublish();\n    }\n    next_state_update_ = time + controller_state_period_;\n  }\n}\n\n\nWalrusPodController::WalrusPodController()\n{\n}\n\nbool WalrusPodController::init(hardware_interface::EffortJointInterface* hw,\n\t\t\t\t ros::NodeHandle& root_nh,\n\t\t\t\t ros::NodeHandle &controller_nh)\n{\n  urdf::Model urdf;\n  if (!urdf.initParam(\"robot_description\")) {\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n\n  front.reset(new Pod(ros::NodeHandle(controller_nh, \"front\")));\n  if(!front->init(hw, urdf))\n    return false;\n\n  back.reset(new Pod(ros::NodeHandle(controller_nh, \"back\")));\n  if(!back->init(hw, urdf))\n    return false;\n\n\n  return true;\n}\n\nvoid WalrusPodController::update(const ros::Time& time, const ros::Duration& period)\n{\n  front->update(time, period);\n  back->update(time, period);\n}\n\nvoid WalrusPodController::starting(const ros::Time& time)\n{\n  front->starting(time);\n  back->starting(time);\n}\n\nvoid WalrusPodController::stopping(const ros::Time& time)\n{\n  front->stopping(time);\n  back->stopping(time);\n}\n\n\n\n} // namespace diff_pod_controller\n\n", "meta": {"hexsha": "a8d860348d857b3f2b1a596c2d8911db5311380d", "size": 5908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "walrus_pod_controller/src/walrus_pod_controller.cpp", "max_stars_repo_name": "RIVeR-Lab/walrus", "max_stars_repo_head_hexsha": "28d285cec8e181e9300fdd9a82a299c7c025f32e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-03-04T22:48:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T11:57:53.000Z", "max_issues_repo_path": "walrus_pod_controller/src/walrus_pod_controller.cpp", "max_issues_repo_name": "RIVeR-Lab/walrus", "max_issues_repo_head_hexsha": "28d285cec8e181e9300fdd9a82a299c7c025f32e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T05:50:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T20:34:50.000Z", "max_forks_repo_path": "walrus_pod_controller/src/walrus_pod_controller.cpp", "max_forks_repo_name": "RIVeR-Lab/walrus", "max_forks_repo_head_hexsha": "28d285cec8e181e9300fdd9a82a299c7c025f32e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-24T10:05:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T11:58:03.000Z", "avg_line_length": 32.2841530055, "max_line_length": 128, "alphanum_fraction": 0.7347664184, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18290241542856903}}
{"text": "//\n// Created by jestjest on 11/19/17.\n//\n\n#include <boost/bind.hpp>\n#include <cereal/archives/binary.hpp>\n#include <messages/queryMessage.hpp>\n#include <messages/responseMessage.hpp>\n#include <messages/findQuery.hpp>\n#include <messages/storeQuery.hpp>\n#include <queue>\n#include <messages/findValueResponse.hpp>\n#include <messages/findNodeResponse.hpp>\n#include \"protocol.hpp\"\n#include \"network.hpp\"\n\n\nnamespace kdml {\n\n    using boost::asio::ip::udp;\n    namespace asio = boost::asio;\n    namespace mp = boost::multiprecision;\n\n    Protocol::Protocol(const NodeInfo& node)\n            : owner(node),\n              routingTable(node.id),\n              ioService{},\n              ioLock(new asio::io_service::work(ioService)) {\n\n        network = new net::Network(node, ioService, this);\n        network->startReceive();\n        ioThread = std::thread([this]() { ioService.run(); });\n    }\n\n    void Protocol::async_get(mp::uint256_t key, kdml::GetCallback callback) {\n        node_lookup(key, callback, true, false);\n    }\n\n    void Protocol::async_store(mp::uint256_t key, NodeInfo value) {\n        node_lookup(key, NULL, false, true);\n    }\n\n    // TODO queue user commands while bootstrapping).\n    void Protocol::bootstrap(const NodeInfo& peer) {\n        Nodes endpoints = resolveEndpoint(peer);\n        probePeers(std::move(endpoints));\n    }\n\n    void Protocol::join() {\n        ioService.stop();\n        if (ioThread.joinable()) {\n            ioThread.join();\n        }\n    }\n\n    void Protocol::handleReceive(const boost::system::error_code& error,\n                                 std::size_t /*bytes_transferred*/) {\n\n        if (error == asio::error::operation_aborted) {\n            return;\n        }\n\n        asio::streambuf sb;\n        boost::system::error_code recvError = network->populateBuf(sb);\n\n        if (!recvError) {\n            NodeInfo sender(network->getRemotePeer());\n            std::shared_ptr<kdml::net::Message> message;\n            {\n                std::istream istream(&sb);\n                cereal::BinaryInputArchive iarchive(istream);\n                iarchive(message);\n            }\n\n            std::cout << \"Parsed message: \" << *message << std::endl;\n            handleMessage(message, sender);\n        }\n        network->startReceive();\n    }\n\n    void Protocol::probePeers(Nodes endpoints) {\n        if (endpoints.empty()) {\n            throw std::string(\"Failed to find peers\");\n        } else {\n            NodeInfo ep = endpoints.back();\n            endpoints.pop_back();\n\n            SimpleCallback onPong = [=](bool failure) {\n                if (failure) {\n                    probePeers(endpoints);\n                } else {\n                    auto bucket = routingTable.insertNode(ep);\n                    node_lookup(owner.id, [bucket](Nodes found) {\n                        // TODO: refresh buckets after bucket\n                    }, false, false);\n                }\n            };\n\n            network->send_ping(ep, onPong);\n        }\n    }\n\n    Nodes Protocol::resolveEndpoint(const NodeInfo& endpoint) {\n        udp::resolver resolver(ioService);\n        udp::resolver::query query(udp::v4(), endpoint.getIpAddr(),\n                                   std::to_string(endpoint.port));\n        Nodes eps;\n        auto resolvedEndpoints = resolver.resolve(query);\n        decltype(resolvedEndpoints) end;\n\n        while (resolvedEndpoints != end) {\n            auto ep = (*resolvedEndpoints).endpoint();\n            eps.emplace_back(NodeInfo{ep.address().to_string(), ep.port()});\n            resolvedEndpoints++;\n        }\n        return eps;\n    }\n\n    void Protocol::handleMessage(std::shared_ptr<net::Message> msg,\n                                 NodeInfo sender) {\n\n        switch (msg->getMessageType()) {\n            case net::MessageType::ERROR: {\n                std::cerr << \"Received error message: \" << *msg << std::endl;\n                break;\n            }\n            case net::MessageType::QUERY: {\n                routingTable.insertNode(sender);\n                handleQuery(std::dynamic_pointer_cast<net::QueryMessage>(msg), std::move(sender));\n                break;\n            }\n            case net::MessageType::RESPONSE: {\n                routingTable.insertNode(sender);\n                handleResponse(std::dynamic_pointer_cast<net::ResponseMessage>(msg));\n                break;\n            }\n        }\n    }\n\n    void Protocol::find_value_callback(Nodes nodes, bool found, GetCallback callback) {\n        if(found) {\n            std::cout << \"Found nodes: first one: \" << (*nodes.begin()).getIpAddr() << std::endl;\n            callback(nodes);\n        } else {\n            std::cout << \"Did not find a knowledgeable node.\" << std::endl;\n            callback({});\n        }\n    }\n\n    void Protocol::store_callback(mp::uint256_t key, Nodes nodes) {\n        for(NodeInfo node : nodes) {\n            network->send_store(key, node);\n        }\n    }\n\n    /*\n     * Pick a closest nodes to key from bucket, send asynchronous FIND_NODE rpcs to each.\n     */\n    void Protocol::node_lookup(mp::uint256_t key, GetCallback callback, bool findValue, bool store) {\n\n        std::vector<NodeInfo> a_closest_nodes = routingTable.getAClosestNodes(ALPHA, key);\n        RequestState request_state;\n        request_state.key = key;\n        request_state.findValue = findValue;\n        request_state.store = store;\n        request_state.callback = callback;\n        for(NodeInfo node : a_closest_nodes) {\n            NodeInfoWrapper node_wrapper(key, node);\n            request_state.k_closest_nodes.insert(node_wrapper);\n            request_state.responses_waiting++;\n            if (request_state.findValue) {\n                network->send_find_value(key, node);\n            } else {\n                network->send_find_node(key, node);\n            }\n        }\n        lookups[key] = request_state;\n    }\n\n    //TODO: Nodes that fail to respond should be removed from consideration unless they respond\n\n    void Protocol::node_lookup_callback(mp::uint256_t sender, RequestState& request_state, Nodes k_nodes,\n                                        mp::uint256_t key, bool found) {\n\n        request_state.responses_waiting--;\n        request_state.responded_nodes.insert(sender);\n\n        if (found) {\n            assert(request_state.findValue);\n            // If found, k_nodes will be the list of values associated with key\n            find_value_callback(k_nodes, found, request_state.callback);\n            lookups.erase(lookups.find(key), lookups.end());\n            return;\n        }\n\n        for(NodeInfo node : k_nodes) {\n            NodeInfoWrapper node_wrapper(key, node);\n            request_state.k_closest_nodes.insert(node_wrapper);\n        }\n\n        // Query alpha more nodes\n        // Terminates when has queried and heard responses from k closest nodes\n        int responded = 0;\n        bool k_responded = true;\n        for (auto it=request_state.k_closest_nodes.begin(); it!=request_state.k_closest_nodes.end(); ++it) {\n            if (request_state.responses_waiting >= ALPHA) break;\n            if (k_responded && responded >= kdml::K) break;\n\n            NodeInfoWrapper node_wrapper = *it;\n\n            // Keep track if k closest nodes have responded\n            auto responded_it = request_state.responded_nodes.find(node_wrapper.node.id);\n            if (responded_it != request_state.responded_nodes.end()) {\n                responded++;\n            } else {\n                k_responded = false;\n            }\n\n            // Do not query if node has already been queried\n            auto queried_it = request_state.queried_nodes.find(node_wrapper.node.id);\n            if (queried_it != request_state.queried_nodes.end()) {\n                continue;\n            }\n\n            request_state.responses_waiting++;\n            request_state.queried_nodes.insert(node_wrapper.node.id);\n            if (request_state.findValue) {\n                network->send_find_value(key, node_wrapper.node);\n            } else {\n                network->send_find_node(key, node_wrapper.node);\n            }\n        }\n\n        if (request_state.responses_waiting == 0) {\n            Nodes k_closest_nodes_list;\n            for (auto it=request_state.k_closest_nodes.begin(); it!=request_state.k_closest_nodes.end()\n                    && k_closest_nodes_list.size() < kdml::K; ++it) {\n                NodeInfoWrapper node_wrapper = *it;\n                k_closest_nodes_list.push_back(node_wrapper.node);\n            }\n            if (request_state.findValue) {\n                find_value_callback(k_closest_nodes_list, found, request_state.callback);\n            } else if (request_state.store){\n                store_callback(key, k_closest_nodes_list);\n            } else {\n                std::cout << \"Completed lookup for bootstrapping\" << std::endl;\n            }\n\n            lookups.erase (lookups.find(key), lookups.end());\n        }\n    }\n\n\n    void Protocol::handleQuery(std::shared_ptr<net::QueryMessage> msg,\n                               NodeInfo sender) {\n\n        switch (msg->getQueryType()) {\n            case net::QueryType::PING: {\n                network->send_ping_response(sender, msg->getTid());\n                break;\n            }\n            case net::QueryType::FIND_NODE: {\n                auto query = std::dynamic_pointer_cast<net::FindQuery>(msg);\n                auto nodes = routingTable.getKClosestNodes(query->getTarget());\n                network->send_find_node_response(sender, nodes, msg->getTid());\n                break;\n            }\n            case net::QueryType::FIND_VALUE: {\n                auto query = std::dynamic_pointer_cast<net::FindQuery>(msg);\n                auto value = storage.find(query->getTarget());\n                bool found = (value != storage.end());\n                Nodes result;\n                if (found) {\n                    result = value->second;\n                } else {\n                    result = routingTable.getKClosestNodes(query->getTarget());\n                }\n                network->send_find_value_response(sender, found, result,\n                                                  msg->getTid());\n                break;\n            }\n            case net::QueryType::STORE: {\n                auto query = std::dynamic_pointer_cast<net::StoreQuery>(msg);\n                bool success = false;\n\n                try {\n                    storage[query->getKey()].emplace_back(query->getVal());\n                    success = true;\n                } catch (...) {}\n\n                network->send_store_response(sender, success, msg->getTid());\n                break;\n            }\n        }\n    }\n\n    void Protocol::handleResponse(std::shared_ptr<net::ResponseMessage> msg) {\n        uint32_t tid = msg->getTid();\n\n        if (!network->containsRequest(tid)) {\n            std::cerr << \"Received alien message\" << *msg << std::endl;\n            return;\n        }\n\n        Request outstanding = network->getRequest(tid);\n        if (msg->getQueryType() == net::QueryType::PING) {\n            network->removeRequest(tid);\n            outstanding.onDone(msg, false);\n        } else {\n            auto it = lookups.find(outstanding.key);\n            if (it != lookups.end()) {\n                RequestState& request_state = it->second;\n                if (outstanding.findValue) {\n                    auto value_res = std::dynamic_pointer_cast<net::FindValueResponse>(msg);\n                    node_lookup_callback(msg->id, request_state, value_res->data, outstanding.key, value_res->found);\n                } else {\n                    auto find_res = std::dynamic_pointer_cast<net::FindNodeResponse>(msg);\n                    node_lookup_callback(msg->id, request_state, find_res->nodes, outstanding.key, false);\n                }\n            } else {\n                std::cout << \"Got response for nonexistent nodes lookup\" << std::endl;\n            }\n        }\n    }\n\n}\n", "meta": {"hexsha": "845bbf26891de1f4023d1a1a09cf004f0efe1bac", "size": 11929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/protocol.cpp", "max_stars_repo_name": "jakerachleff/simple-kademlia", "max_stars_repo_head_hexsha": "dedbd05e7724b0e9a2f527cd27ad8c6e5251b62b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-02T10:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T10:48:28.000Z", "max_issues_repo_path": "src/protocol.cpp", "max_issues_repo_name": "jakerachleff/simple-kademlia", "max_issues_repo_head_hexsha": "dedbd05e7724b0e9a2f527cd27ad8c6e5251b62b", "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/protocol.cpp", "max_forks_repo_name": "jakerachleff/simple-kademlia", "max_forks_repo_head_hexsha": "dedbd05e7724b0e9a2f527cd27ad8c6e5251b62b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-24T12:25:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T12:42:14.000Z", "avg_line_length": 36.4801223242, "max_line_length": 117, "alphanum_fraction": 0.5550339509, "num_tokens": 2426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18290241542856903}}
{"text": "#pragma once\n\n#include <unordered_map>\n\n#include <boost/gil/gil_all.hpp>\n#include <boost/optional.hpp>\n\n// assimp::Importer\n#include <assimp/Importer.hpp>\n// aiPostProcessSteps for assimp::Importer::ReadFile\n#include <assimp/postprocess.h>\n// aiScene, aiNode\n#include <assimp/scene.h>\n\n#include \"../glew.detail/c.hxx\"\n#include \"../glew.detail/gl_type.hxx\"\n#include \"../glew.detail/error.hxx\"\n\n#include \"helper.hxx\"\n#include \"material.hxx\"\n#include \"bone.hxx\"\n#include \"animation_data.hxx\"\n\n#include \"../shader.detail/constant.hxx\"\n\nnamespace wonder_rabbit_project\n{\n  namespace wonderland\n  {\n    namespace renderer\n    {\n      namespace model\n      {\n        \n        struct vertex_buffer_t\n        {\n          using float_t = float;\n          \n          glm::vec4 position;\n          glm::vec4 color;\n          glm::vec2 texcoord0;\n          glm::vec2 texcoord1;\n          glm::vec2 texcoord2;\n          glm::vec2 texcoord3;\n          glm::vec2 texcoord4;\n          glm::vec2 texcoord5;\n          glm::vec2 texcoord6;\n          glm::vec2 texcoord7;\n          glm::vec3 normal;\n          glm::vec3 tangent;\n          glm::vec3 bitangent;\n          glm::vec4 bone_ids;\n          glm::vec4 bone_weights;\n          \n          vertex_buffer_t\n          ( glm::vec4&& pos\n          , glm::vec4&& col\n          , glm::vec2&& tex0\n          , glm::vec2&& tex1\n          , glm::vec2&& tex2\n          , glm::vec2&& tex3\n          , glm::vec2&& tex4\n          , glm::vec2&& tex5\n          , glm::vec2&& tex6\n          , glm::vec2&& tex7\n          , glm::vec3&& nor\n          , glm::vec3&& tan\n          , glm::vec3&& bit\n          , glm::vec4&& bid\n          , glm::vec4&& bwt\n          )\n          : position     ( std::move( pos ) )\n          , color        ( std::move( col ) )\n          , texcoord0    ( std::move( tex0 ) )\n          , texcoord1    ( std::move( tex1 ) )\n          , texcoord2    ( std::move( tex2 ) )\n          , texcoord3    ( std::move( tex3 ) )\n          , texcoord4    ( std::move( tex4 ) )\n          , texcoord5    ( std::move( tex5 ) )\n          , texcoord6    ( std::move( tex6 ) )\n          , texcoord7    ( std::move( tex7 ) )\n          , normal       ( std::move( nor ) )\n          , tangent      ( std::move( tan ) )\n          , bitangent    ( std::move( bit ) )\n          , bone_ids     ( std::move( bid ) )\n          , bone_weights ( std::move( bwt ) )\n          { }\n          \n          template < class T = float_t >\n          auto to_ptr() const\n          -> const T*\n          { return reinterpret_cast< const T* >( &position.x ); }\n          \n          static constexpr auto size_of_element = sizeof( float_t );\n          \n          static constexpr auto size_of_memory\n          = ( sizeof( decltype( position ) )\n          + sizeof( decltype( color ) )\n          + sizeof( decltype( texcoord0 ) )\n          + sizeof( decltype( texcoord1 ) )\n          + sizeof( decltype( texcoord2 ) )\n          + sizeof( decltype( texcoord3 ) )\n          + sizeof( decltype( texcoord4 ) )\n          + sizeof( decltype( texcoord5 ) )\n          + sizeof( decltype( texcoord6 ) )\n          + sizeof( decltype( texcoord7 ) )\n          + sizeof( decltype( normal ) )\n          + sizeof( decltype( tangent ) )\n          + sizeof( decltype( bitangent ) )\n          + sizeof( decltype( bone_ids ) )\n          + sizeof( decltype( bone_weights ) )\n          );\n          \n          static constexpr auto count_of_elements = size_of_memory / size_of_element;\n          \n          static constexpr auto count_of_position_elements     = sizeof( decltype( position )     ) / size_of_element;\n          static constexpr auto count_of_color_elements        = sizeof( decltype( color )        ) / size_of_element;\n          static constexpr auto count_of_texcoord0_elements    = sizeof( decltype( texcoord0 )    ) / size_of_element;\n          static constexpr auto count_of_texcoord1_elements    = sizeof( decltype( texcoord1 )    ) / size_of_element;\n          static constexpr auto count_of_texcoord2_elements    = sizeof( decltype( texcoord2 )    ) / size_of_element;\n          static constexpr auto count_of_texcoord3_elements    = sizeof( decltype( texcoord3 )    ) / size_of_element;\n          static constexpr auto count_of_texcoord4_elements    = sizeof( decltype( texcoord4 )    ) / size_of_element;\n          static constexpr auto count_of_texcoord5_elements    = sizeof( decltype( texcoord5 )    ) / size_of_element;\n          static constexpr auto count_of_texcoord6_elements    = sizeof( decltype( texcoord6 )    ) / size_of_element;\n          static constexpr auto count_of_texcoord7_elements    = sizeof( decltype( texcoord7 )    ) / size_of_element;\n          static constexpr auto count_of_normal_elements       = sizeof( decltype( normal )       ) / size_of_element;\n          static constexpr auto count_of_tangent_elements      = sizeof( decltype( tangent )      ) / size_of_element;\n          static constexpr auto count_of_bitangent_elements    = sizeof( decltype( bitangent )    ) / size_of_element;\n          static constexpr auto count_of_bone_ids_elements     = sizeof( decltype( bone_ids )     ) / size_of_element;\n          static constexpr auto count_of_bone_weights_elements = sizeof( decltype( bone_weights ) ) / size_of_element;\n          \n          static constexpr auto memory_offset_of_position     = std::size_t( 0 );\n          static constexpr auto memory_offset_of_color        = memory_offset_of_position  + sizeof( decltype( position  ) );\n          static constexpr auto memory_offset_of_texcoord0    = memory_offset_of_color     + sizeof( decltype( color     ) );\n          static constexpr auto memory_offset_of_texcoord1    = memory_offset_of_texcoord0 + sizeof( decltype( texcoord0 ) );\n          static constexpr auto memory_offset_of_texcoord2    = memory_offset_of_texcoord1 + sizeof( decltype( texcoord1 ) );\n          static constexpr auto memory_offset_of_texcoord3    = memory_offset_of_texcoord2 + sizeof( decltype( texcoord2 ) );\n          static constexpr auto memory_offset_of_texcoord4    = memory_offset_of_texcoord3 + sizeof( decltype( texcoord3 ) );\n          static constexpr auto memory_offset_of_texcoord5    = memory_offset_of_texcoord4 + sizeof( decltype( texcoord4 ) );\n          static constexpr auto memory_offset_of_texcoord6    = memory_offset_of_texcoord5 + sizeof( decltype( texcoord5 ) );\n          static constexpr auto memory_offset_of_texcoord7    = memory_offset_of_texcoord6 + sizeof( decltype( texcoord6 ) );\n          static constexpr auto memory_offset_of_normal       = memory_offset_of_texcoord7 + sizeof( decltype( texcoord7 ) );\n          static constexpr auto memory_offset_of_tangent      = memory_offset_of_normal    + sizeof( decltype( normal    ) );\n          static constexpr auto memory_offset_of_bitangent    = memory_offset_of_tangent   + sizeof( decltype( tangent   ) );\n          static constexpr auto memory_offset_of_bone_ids     = memory_offset_of_bitangent + sizeof( decltype( bitangent ) );\n          static constexpr auto memory_offset_of_bone_weights = memory_offset_of_bone_ids  + sizeof( decltype( bone_ids  ) );\n        };\n        \n        class mesh_t\n        {\n          friend class node_t;\n          \n          glew::gl_type::GLuint  _triangle_vb_id;\n          glew::gl_type::GLuint  _triangle_ib_id;\n          glew::gl_type::GLsizei _count_of_indices;\n          \n          glew::gl_type::GLuint  _triangle_vao_id;\n          \n          const material_t&      _material;\n          \n          // \u30dc\u30fc\u30f3\u30c7\u30fc\u30bf\n          std::vector< glm::mat4 >& _bone_offsets;\n          \n          std::unordered_map< std::string, unsigned >& _bone_name_to_bone_index_mapping;\n          \n          const std::unordered_map< std::string, animation_t >& _animations;\n          \n          using vertices_buffer_t = std::vector< vertex_buffer_t >;\n          using indices_buffer_t  = std::vector< glew::gl_type::GLuint >;\n          \n          auto initialize_prepare_buffers( const aiMesh* mesh, vertices_buffer_t& vb, indices_buffer_t& ib )\n            -> void\n          {\n            \n            constexpr auto indices_of_triangle = 3;\n            \n            for ( auto n_vertex = 0u; n_vertex < mesh -> mNumVertices; ++ n_vertex )\n              vb.emplace_back\n              ( std::move( helper::to_glm_vec4( mesh -> mVertices           + n_vertex ) )\n              , std::move( mesh -> mColors[ 0 ]        ? helper::to_glm_vec4( mesh -> mColors[ 0 ]        + n_vertex ) : glm::vec4( std::nanf(\"\") ) )\n              , std::move( mesh -> mTextureCoords[ 0 ] ? helper::to_glm_vec2( mesh -> mTextureCoords[ 0 ] + n_vertex ) : glm::vec2( std::nanf(\"\") ) )\n              , std::move( mesh -> mTextureCoords[ 1 ] ? helper::to_glm_vec2( mesh -> mTextureCoords[ 1 ] + n_vertex ) : glm::vec2( std::nanf(\"\") ) )\n              , std::move( mesh -> mTextureCoords[ 2 ] ? helper::to_glm_vec2( mesh -> mTextureCoords[ 2 ] + n_vertex ) : glm::vec2( std::nanf(\"\") ) )\n              , std::move( mesh -> mTextureCoords[ 3 ] ? helper::to_glm_vec2( mesh -> mTextureCoords[ 3 ] + n_vertex ) : glm::vec2( std::nanf(\"\") ) )\n              , std::move( mesh -> mTextureCoords[ 4 ] ? helper::to_glm_vec2( mesh -> mTextureCoords[ 4 ] + n_vertex ) : glm::vec2( std::nanf(\"\") ) )\n              , std::move( mesh -> mTextureCoords[ 5 ] ? helper::to_glm_vec2( mesh -> mTextureCoords[ 5 ] + n_vertex ) : glm::vec2( std::nanf(\"\") ) )\n              , std::move( mesh -> mTextureCoords[ 6 ] ? helper::to_glm_vec2( mesh -> mTextureCoords[ 6 ] + n_vertex ) : glm::vec2( std::nanf(\"\") ) )\n              , std::move( mesh -> mTextureCoords[ 7 ] ? helper::to_glm_vec2( mesh -> mTextureCoords[ 7 ] + n_vertex ) : glm::vec2( std::nanf(\"\") ) )\n              , std::move( mesh -> mNormals            ? helper::to_glm_vec3( mesh -> mNormals            + n_vertex ) : glm::vec3( std::nanf(\"\") ) )\n              , std::move( mesh -> mTangents           ? helper::to_glm_vec3( mesh -> mTangents           + n_vertex ) : glm::vec3( std::nanf(\"\") ) )\n              , std::move( mesh -> mBitangents         ? helper::to_glm_vec3( mesh -> mBitangents         + n_vertex ) : glm::vec3( std::nanf(\"\") ) )\n              , std::move( glm::vec4( 0.0f ) )\n              , std::move( glm::vec4( 0.0f ) )\n              );\n            \n            for ( auto n_face = 0u; n_face < mesh -> mNumFaces; ++ n_face )\n            {\n              const auto face = mesh -> mFaces + n_face;\n              \n              if ( face -> mNumIndices not_eq indices_of_triangle )\n                throw std::runtime_error( \"required must be indices of face is 3. try create_model with aiProcess_Triangulate.\" );\n              \n              ib.emplace_back( std::move( face -> mIndices[0] ) );\n              ib.emplace_back( std::move( face -> mIndices[1] ) );\n              ib.emplace_back( std::move( face -> mIndices[2] ) );\n              \n            }\n            \n            _count_of_indices = ib.size();\n            \n          }\n          \n          auto initialize_animation_bone\n          ( const aiMesh* mesh\n          , vertices_buffer_t& vb\n          )\n            -> void\n          {\n            // \u30a2\u30cb\u30e1\u30fc\u30b7\u30e7\u30f3\u30fb\u30dc\u30fc\u30f3\u307e\u308f\u308a\n            \n            const auto bones = mesh -> mBones;\n            \n            for ( auto n_bone = 0u; n_bone < mesh -> mNumBones; ++n_bone )\n            {\n              const auto bone = bones[ n_bone ];\n              \n              const std::string bone_name( bone -> mName.C_Str() );\n              \n              unsigned bone_index = 0;\n              \n              if ( _bone_name_to_bone_index_mapping.find( bone_name ) == _bone_name_to_bone_index_mapping.end() )\n              {\n                bone_index = _bone_name_to_bone_index_mapping.size();\n                _bone_offsets.push_back( glm::mat4( 1.0f ) );\n                \n                if ( _bone_offsets.size() > shader::max_bones )\n                  throw std::runtime_error\n                  ( \"bone offset size \" + std::to_string( _bone_offsets.size() )\n                  + \" over shader::max_bones \" + std::to_string( shader::max_bones )\n                  + \".\"\n                  );\n              }\n              else\n                bone_index = _bone_name_to_bone_index_mapping[ bone_name ];\n              \n              _bone_name_to_bone_index_mapping[ bone_name ] = bone_index;\n              \n              // TODO: \u3082\u3057\u304b\u3057\u305f\u3089 .x \u4ee5\u5916\u3067\u306f bone_offset \u306b transpose \u3057\u3066\u3044\u308b\u3068\u602a\u5947\u73fe\u8c61\u5316\u3059\u308b\u304b\u3082\u3002\u8981\u78ba\u8a8d\n              // pattern: .x is ok\n              _bone_offsets[ bone_index ] = glm::transpose( helper::to_glm_mat4( bone -> mOffsetMatrix ) );\n              //_bone_offsets[ bone_index ] = helper::to_glm_mat4( bone -> mOffsetMatrix );\n              \n              for ( auto n_weight = 0u; n_weight < bone -> mNumWeights; ++n_weight )\n              {\n                const auto& weight = bone -> mWeights[ n_weight ];\n                \n                auto& vertex = vb[ weight.mVertexId ];\n                bool overflow_check = true;\n                \n                for ( auto n = 0; n < 4; ++n )\n                  if ( vertex.bone_weights[ n ] == 0.0f )\n                  {\n                    vertex.bone_ids    [ n ] = bone_index;\n                    vertex.bone_weights[ n ] = weight.mWeight;\n                    overflow_check = false;\n                    break;\n                  }\n                  \n                  if ( overflow_check )\n                    throw std::runtime_error( \"bone buffer is not enought, need limit data bone/vertex <= 4, or fix engine.\" );\n              }\n            }\n          }\n          \n          auto initialize_generate_buffers( const vertices_buffer_t& vb, const indices_buffer_t& ib )\n            -> void\n          {\n            // \u4e09\u89d2\u7fa4\u306e\u30d0\u30c3\u30d5\u30a1\u30fc\u3092\u751f\u6210\n            // http://www.opengl.org/sdk/docs/man/html/glGenVertexArrays.xhtml\n            //  glew::gl_type::GLsizei n, glew::gl_type::GLuint* arrays\n            glew::c::glGenVertexArrays( 1, &_triangle_vao_id );\n            glew::test_error( __FILE__, __LINE__ );\n            \n            // http://www.opengl.org/sdk/docs/man/html/glBindVertexArray.xhtml\n            //  glew::gl_type::GLuint array\n            glew::c::glBindVertexArray( _triangle_vao_id );\n            glew::test_error( __FILE__, __LINE__ );\n            \n            // http://www.opengl.org/sdk/docs/man/html/glGenBuffers.xhtml\n            //  glew::gl_type::GLsizei n, glew::gl_type::GLuint* buffers\n            glew::c::glGenBuffers( 1, &_triangle_vb_id);\n            glew::test_error( __FILE__, __LINE__ );\n            \n            glew::c::glGenBuffers( 1, &_triangle_ib_id);\n            glew::test_error( __FILE__, __LINE__ );\n            \n            // http://www.opengl.org/sdk/docs/man/html/glBindBuffer.xhtml\n            //  GLenum target, glew::gl_type::GLuint buffer\n            glew::c::glBindBuffer( GL_ARRAY_BUFFER, _triangle_vb_id );\n            glew::test_error( __FILE__, __LINE__ );\n            \n            glew::c::glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _triangle_ib_id );\n            glew::test_error( __FILE__, __LINE__ );\n            \n            // http://www.opengl.org/sdk/docs/man/html/glBufferData.xhtml\n            //  GLenum target, glew::gl_type::GLsizeiptr size, const GLvoid* data, GLenum usage\n            glew::c::glBufferData\n            ( GL_ARRAY_BUFFER\n            , vb.size() * vertex_buffer_t::size_of_memory\n            , vb.data() -> to_ptr<void>()\n            , glew::gl_type::GLenum( GL_STATIC_DRAW )\n            );\n            glew::test_error( __FILE__, __LINE__ );\n            \n            glew::c::glBufferData\n            ( GL_ELEMENT_ARRAY_BUFFER\n            , ib.size() * sizeof( indices_buffer_t::value_type )\n            , reinterpret_cast< const void* >( ib.data() )\n            , glew::gl_type::GLenum( GL_STATIC_DRAW )\n            );\n            glew::test_error( __FILE__, __LINE__ );\n            \n            // \u5f8c\u59cb\u672b\n            glew::c::glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );\n            glew::test_error( __FILE__, __LINE__ );\n            \n            glew::c::glBindBuffer( GL_ARRAY_BUFFER, 0 );\n            glew::test_error( __FILE__, __LINE__ );\n            \n            glew::c::glBindVertexArray( 0 );\n            glew::test_error( __FILE__, __LINE__ );\n          }\n          \n        public:\n          \n          ~mesh_t()\n          {\n            // http://www.opengl.org/sdk/docs/man/html/glDeleteBuffers.xhtml\n            //  glew::gl_type::GLsizei n, const glew::gl_type::GLuint buffers\n            glew::c::glDeleteBuffers( 1, &_triangle_ib_id );\n            glew::c::glDeleteBuffers( 1, &_triangle_vb_id );\n            \n            // http://www.opengl.org/sdk/docs/man/html/glDeleteVertexArrays.xhtml\n            //  glew::gl_type::GLsizei n, const glew::gl_type::GLuint* arrays\n            glew::c::glDeleteVertexArrays( 1, &_triangle_vao_id );\n          }\n          \n          mesh_t\n          ( const aiMesh* mesh\n          , const std::vector<material_t>& materials_\n          , std::vector< glm::mat4 >& bone_offsets\n          , std::unordered_map< std::string, unsigned >& bone_name_to_bone_index_mapping\n          , const std::unordered_map< std::string, animation_t >& animations\n          )\n            : _material( materials_.at( mesh -> mMaterialIndex ) )\n            , _bone_offsets( bone_offsets )\n            , _bone_name_to_bone_index_mapping( bone_name_to_bone_index_mapping )\n            , _animations( animations )\n          {\n            vertices_buffer_t vb;\n            indices_buffer_t ib;\n            \n            initialize_prepare_buffers ( mesh, vb, ib );\n            initialize_animation_bone  ( mesh, vb     );\n            initialize_generate_buffers(       vb, ib );\n          }\n          \n          auto draw( const glew::gl_type::GLint program_id )\n            -> void\n          {\n            // vertex transfar\n            \n            constexpr glew::gl_type::GLenum    attribute = GL_FLOAT;\n            constexpr glew::gl_type::GLboolean normalize_on  = true;\n            constexpr glew::gl_type::GLboolean normalize_off = false;\n            \n            const auto set_vertex_attribute = [ this, program_id ]\n            {\n              const auto location_of_vs_position     = glew::c::glGetAttribLocation( program_id, \"position\"     );\n              const auto location_of_vs_color        = glew::c::glGetAttribLocation( program_id, \"color\"        );\n              const auto location_of_vs_texcoord0    = glew::c::glGetAttribLocation( program_id, \"texcoord0\"    );\n              const auto location_of_vs_texcoord1    = glew::c::glGetAttribLocation( program_id, \"texcoord1\"    );\n              const auto location_of_vs_texcoord2    = glew::c::glGetAttribLocation( program_id, \"texcoord2\"    );\n              const auto location_of_vs_texcoord3    = glew::c::glGetAttribLocation( program_id, \"texcoord3\"    );\n              const auto location_of_vs_texcoord4    = glew::c::glGetAttribLocation( program_id, \"texcoord4\"    );\n              const auto location_of_vs_texcoord5    = glew::c::glGetAttribLocation( program_id, \"texcoord5\"    );\n              const auto location_of_vs_texcoord6    = glew::c::glGetAttribLocation( program_id, \"texcoord6\"    );\n              const auto location_of_vs_texcoord7    = glew::c::glGetAttribLocation( program_id, \"texcoord7\"    );\n              const auto location_of_vs_normal       = glew::c::glGetAttribLocation( program_id, \"normal\"       );\n              const auto location_of_vs_tangent      = glew::c::glGetAttribLocation( program_id, \"tangent\"      );\n              const auto location_of_vs_bitangent    = glew::c::glGetAttribLocation( program_id, \"bitangent\"    );\n              const auto location_of_vs_bone_ids     = glew::c::glGetAttribLocation( program_id, \"bone_ids\"     );\n              const auto location_of_vs_bone_weights = glew::c::glGetAttribLocation( program_id, \"bone_weights\" );\n              \n              if ( location_of_vs_position not_eq -1 )\n              {\n                // http://www.opengl.org/sdk/docs/man/html/glVertexAttribPointer.xhtml\n                //  glew::gl_type::GLuint index, GLint size, GLenum type, GLboolean normalized, glew::gl_type::GLsizei stride, const GLvoid* pointer\n                glew::c::glVertexAttribPointer( location_of_vs_position, vertex_buffer_t::count_of_position_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_position ) );\n                // http://www.opengl.org/sdk/docs/man/html/glEnableVertexAttribArray.xhtml\n                //  glew::gl_type::GLuint index\n                glew::c::glEnableVertexAttribArray( location_of_vs_position );\n              }\n              \n              if ( location_of_vs_color not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_color, vertex_buffer_t::count_of_color_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_color ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_color );\n              }\n              \n              if ( location_of_vs_texcoord0 not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_texcoord0, vertex_buffer_t::count_of_texcoord0_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_texcoord0 ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_texcoord0 );\n              }\n              if ( location_of_vs_texcoord1 not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_texcoord1, vertex_buffer_t::count_of_texcoord1_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_texcoord1 ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_texcoord1 );\n              }\n              if ( location_of_vs_texcoord2 not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_texcoord2, vertex_buffer_t::count_of_texcoord2_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_texcoord2 ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_texcoord2 );\n              }\n              if ( location_of_vs_texcoord3 not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_texcoord3, vertex_buffer_t::count_of_texcoord3_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_texcoord3 ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_texcoord3 );\n              }\n              if ( location_of_vs_texcoord4 not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_texcoord4, vertex_buffer_t::count_of_texcoord4_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_texcoord4 ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_texcoord4 );\n              }\n              if ( location_of_vs_texcoord5 not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_texcoord5, vertex_buffer_t::count_of_texcoord5_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_texcoord5 ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_texcoord5 );\n              }\n              if ( location_of_vs_texcoord6 not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_texcoord6, vertex_buffer_t::count_of_texcoord6_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_texcoord6 ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_texcoord6 );\n              }\n              if ( location_of_vs_texcoord7 not_eq -1 )\n              { \n                glew::c::glVertexAttribPointer( location_of_vs_texcoord7, vertex_buffer_t::count_of_texcoord7_elements, attribute, normalize_off, vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_texcoord7 ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_texcoord7 );\n              }\n              \n              if ( location_of_vs_normal not_eq -1 )\n              {\n                glew::c::glVertexAttribPointer( location_of_vs_normal  , vertex_buffer_t::count_of_normal_elements  , attribute, normalize_on , vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_normal   ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_normal   );\n              }\n              \n              if ( location_of_vs_tangent not_eq -1 )\n              {\n                glew::c::glVertexAttribPointer( location_of_vs_tangent , vertex_buffer_t::count_of_tangent_elements , attribute, normalize_off , vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_tangent  ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_tangent  );\n              }\n              \n              if ( location_of_vs_bitangent not_eq -1 )\n              {\n                glew::c::glVertexAttribPointer( location_of_vs_bitangent , vertex_buffer_t::count_of_bitangent_elements , attribute, normalize_off , vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_bitangent  ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_bitangent  );\n              }\n              \n              if ( location_of_vs_bone_ids not_eq -1 )\n              {\n                glew::c::glVertexAttribPointer( location_of_vs_bone_ids , vertex_buffer_t::count_of_bone_ids_elements , attribute, normalize_off , vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_bone_ids  ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_bone_ids  );\n              }\n              \n              if ( location_of_vs_bone_weights not_eq -1 )\n              {\n                glew::c::glVertexAttribPointer( location_of_vs_bone_weights , vertex_buffer_t::count_of_bone_weights_elements , attribute, normalize_off , vertex_buffer_t::size_of_memory, reinterpret_cast<void*>( vertex_buffer_t::memory_offset_of_bone_weights  ) );\n                glew::c::glEnableVertexAttribArray( location_of_vs_bone_weights  );\n              }\n            };\n            \n            // \u4e09\u89d2\u7fa4\u63cf\u753b\n            {\n              glew::c::glBindVertexArray( _triangle_vao_id );\n              WRP_GLEW_TEST_ERROR\n              \n              // http://www.opengl.org/sdk/docs/man/html/glBindBuffer.xhtml\n              //  GLenum target, glew::gl_type::GLuint buffer\n              glew::c::glBindBuffer( GL_ARRAY_BUFFER, _triangle_vb_id );\n              WRP_GLEW_TEST_ERROR\n              \n              glew::c::glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _triangle_ib_id );\n              WRP_GLEW_TEST_ERROR\n              \n              set_vertex_attribute();\n              WRP_GLEW_TEST_ERROR\n              \n              // \u30de\u30c6\u30ea\u30a2\u30eb\u306e\u6709\u52b9\u5316\n              auto materia_scopes = _material.draw( program_id );\n              WRP_GLEW_TEST_ERROR\n              \n              // http://www.opengl.org/wiki/GLAPI/glDrawElements\n              //  GLenum mode, GLsizei count, GLenum type, const GLvoid* indices\n              glew::c::glDrawElements( GL_TRIANGLES, _count_of_indices, GL_UNSIGNED_INT, nullptr );\n              WRP_GLEW_TEST_ERROR\n            }\n            \n            // \u5f8c\u59cb\u672b\n            glew::c::glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );\n            glew::c::glBindBuffer( GL_ARRAY_BUFFER, 0 );\n            glew::c::glBindVertexArray( 0 );\n          }\n          \n        };\n      }\n    }\n  }\n}", "meta": {"hexsha": "622d0be1d2760896c9d428fccee7c9bb58bd5282", "size": 27968, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/wonder_rabbit_project/wonderland.renderer.detail/model.detail/mesh.hxx", "max_stars_repo_name": "usagi/wonderland.renderer", "max_stars_repo_head_hexsha": "3222f69f23cc4fe586ef1743cccf43d674bfbe24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-03-16T08:07:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-05T00:15:06.000Z", "max_issues_repo_path": "include/wonder_rabbit_project/wonderland.renderer.detail/model.detail/mesh.hxx", "max_issues_repo_name": "usagi/wonderland.renderer", "max_issues_repo_head_hexsha": "3222f69f23cc4fe586ef1743cccf43d674bfbe24", "max_issues_repo_licenses": ["MIT"], "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/wonder_rabbit_project/wonderland.renderer.detail/model.detail/mesh.hxx", "max_forks_repo_name": "usagi/wonderland.renderer", "max_forks_repo_head_hexsha": "3222f69f23cc4fe586ef1743cccf43d674bfbe24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-05-18T09:17:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-13T21:59:24.000Z", "avg_line_length": 53.8882466281, "max_line_length": 265, "alphanum_fraction": 0.5849899886, "num_tokens": 6631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.18282086150404936}}
{"text": "/**\n * spaint: ArUcoFiducialDetector.cpp\n * Copyright (c) Torr Vision Group, University of Oxford, 2016. All rights reserved.\n */\n\n#include \"fiducials/ArUcoFiducialDetector.h\"\n\n#include <cmath>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/optional.hpp>\n\n#include <opencv2/aruco.hpp>\n#include <opencv2/calib3d.hpp>\n\n#include <ITMLib/Objects/Camera/ITMIntrinsics.h>\n#include <ITMLib/Utils/ITMProjectionUtils.h>\nusing namespace ITMLib;\n\n#include <itmx/base/MemoryBlockFactory.h>\n#include <itmx/ocv/OpenCVUtil.h>\n#include <itmx/util/CameraPoseConverter.h>\nusing namespace itmx;\nusing namespace rigging;\n\n#include \"picking/PickerFactory.h\"\n\nnamespace spaint {\n\n//#################### CONSTRUCTORS ####################\n\nArUcoFiducialDetector::ArUcoFiducialDetector(const Settings_CPtr& settings)\n: m_settings(settings)\n{}\n\n//#################### PUBLIC MEMBER FUNCTIONS ####################\n\nstd::map<std::string,FiducialMeasurement> ArUcoFiducialDetector::detect_fiducials(const View_CPtr& view, const ORUtils::SE3Pose& pose, const VoxelRenderState_CPtr& renderState,\n                                                                                  PoseEstimationMode poseEstimationMode) const\n{\n  std::map<std::string,FiducialMeasurement> result;\n\n  // Convert the current colour input image to OpenCV format.\n  const ITMUChar4Image *rgb = view->rgb;\n  rgb->UpdateHostFromDevice();\n  cv::Mat3b rgbImage = OpenCVUtil::make_rgb_image(rgb->GetData(MEMORYDEVICE_CPU), rgb->noDims.x, rgb->noDims.y);\n\n  // Detect any ArUco fiducials that are visible.\n  cv::aruco::Dictionary dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_ARUCO_ORIGINAL);\n  std::vector<std::vector<cv::Point2f> > corners;\n  std::vector<int> ids;\n  cv::aruco::detectMarkers(rgbImage, dictionary, corners, ids);\n\n#if 0\n  // Visualise the detected fiducials for debugging purposes.\n  cv::Mat3b markerImage = rgbImage.clone();\n  cv::aruco::drawDetectedMarkers(markerImage, corners, ids);\n  cv::imshow(\"Detected Markers\", markerImage);\n#endif\n\n  // Construct the fiducial measurements.\n  std::vector<boost::optional<FiducialMeasurement> > measurements;\n  switch(poseEstimationMode)\n  {\n    case PEM_COLOUR:\n      measurements = construct_measurements_from_colour(ids, corners, view, pose);\n      break;\n    case PEM_DEPTH:\n      measurements = construct_measurements_from_depth(ids, corners, view, pose);\n      break;\n    case PEM_RAYCAST:\n      measurements = construct_measurements_from_raycast(ids, corners, renderState, pose);\n      break;\n    default:\n      // This should never happen.\n      throw std::runtime_error(\"Unknown fiducial pose estimation mode\");\n  }\n\n  for(size_t i = 0, size = ids.size(); i < size; ++i)\n  {\n    if(!measurements[i]) continue;\n    result.insert(std::make_pair(boost::lexical_cast<std::string>(ids[i]), *measurements[i]));\n  }\n\n  return result;\n}\n\n//#################### PRIVATE STATIC MEMBER FUNCTIONS ####################\n\nstd::vector<boost::optional<FiducialMeasurement> >\nArUcoFiducialDetector::construct_measurements_from_colour(const std::vector<int>& ids, const std::vector<std::vector<cv::Point2f> >& corners,\n                                                          const View_CPtr& view, const ORUtils::SE3Pose& pose) const\n{\n  std::vector<boost::optional<FiducialMeasurement> > measurements;\n\n  // Estimate the poses of the fiducials in eye space.\n  const ITMIntrinsics& intrinsics = view->calib.intrinsics_rgb;\n  cv::Mat1f cameraMatrix = cv::Mat1f::zeros(3, 3);\n  cameraMatrix(0, 0) = intrinsics.projectionParamsSimple.fx;\n  cameraMatrix(1, 1) = intrinsics.projectionParamsSimple.fy;\n  cameraMatrix(0, 2) = intrinsics.projectionParamsSimple.px;\n  cameraMatrix(1, 2) = intrinsics.projectionParamsSimple.py;\n  cameraMatrix(2, 2) = 1.0f;\n\n  std::vector<cv::Vec3d> rvecs, tvecs;\n  cv::aruco::estimatePoseSingleMarkers(corners, 0.02f, cameraMatrix, cv::noArray(), rvecs, tvecs);\n\n  // Convert the poses of the fiducials into world space and return them.\n  for(size_t i = 0, size = corners.size(); i < size; ++i)\n  {\n    cv::Mat1d rot;\n    cv::Rodrigues(rvecs[i], rot);\n\n    Matrix4f fiducialToEye(0.0f);\n    for(int y = 0; y < 3; ++y)\n    {\n      for(int x = 0; x < 3; ++x)\n      {\n        fiducialToEye(x,y) = static_cast<float>(rot(cv::Point2i(x,y)));\n      }\n    }\n    fiducialToEye(3,0) = static_cast<float>(tvecs[i](0));\n    fiducialToEye(3,1) = static_cast<float>(tvecs[i](1));\n    fiducialToEye(3,2) = static_cast<float>(tvecs[i](2));\n    fiducialToEye(3,3) = 1.0f;\n\n    const Matrix4f eyeToWorld = pose.GetInvM();\n    const Matrix4f fiducialToWorld = eyeToWorld * fiducialToEye;\n\n    ORUtils::SE3Pose fiducialPoseWorld;\n    fiducialPoseWorld.SetInvM(fiducialToWorld);\n    measurements.push_back(FiducialMeasurement(boost::lexical_cast<std::string>(ids[i]), boost::none, fiducialPoseWorld));\n  }\n\n  return measurements;\n}\n\nstd::vector<boost::optional<FiducialMeasurement> >\nArUcoFiducialDetector::construct_measurements_from_depth(const std::vector<int>& ids, const std::vector<std::vector<cv::Point2f> >& corners,\n                                                         const View_CPtr& view, const ORUtils::SE3Pose& pose) const\n{\n  std::vector<boost::optional<FiducialMeasurement> > measurements;\n\n  // Make sure that the live depth image is available on the CPU.\n  view->depth->UpdateHostFromDevice();\n\n  for(size_t i = 0, size = corners.size(); i < size; ++i)\n  {\n    boost::optional<ORUtils::SE3Pose> fiducialPoseEye = make_pose_from_corners(\n      pick_corner_from_depth(corners[i][3], view),\n      pick_corner_from_depth(corners[i][2], view),\n      pick_corner_from_depth(corners[i][0], view)\n    );\n\n    boost::optional<ORUtils::SE3Pose> fiducialPoseWorld;\n    if(fiducialPoseEye) fiducialPoseWorld.reset(fiducialPoseEye->GetM() * pose.GetM());\n\n    measurements.push_back(FiducialMeasurement(boost::lexical_cast<std::string>(ids[i]), fiducialPoseEye, fiducialPoseWorld));\n  }\n\n  return measurements;\n}\n\nstd::vector<boost::optional<FiducialMeasurement> >\nArUcoFiducialDetector::construct_measurements_from_raycast(const std::vector<int>& ids, const std::vector<std::vector<cv::Point2f> >& corners,\n                                                           const VoxelRenderState_CPtr& renderState, const ORUtils::SE3Pose& pose) const\n{\n  std::vector<boost::optional<FiducialMeasurement> > measurements;\n\n  for(size_t i = 0, size = corners.size(); i < size; ++i)\n  {\n    boost::optional<ORUtils::SE3Pose> fiducialPoseWorld = make_pose_from_corners(\n      pick_corner_from_raycast(corners[i][3], renderState),\n      pick_corner_from_raycast(corners[i][2], renderState),\n      pick_corner_from_raycast(corners[i][0], renderState)\n    );\n\n    boost::optional<ORUtils::SE3Pose> fiducialPoseEye;\n    if(fiducialPoseWorld) fiducialPoseEye.reset(fiducialPoseWorld->GetM() * pose.GetInvM());\n\n    measurements.push_back(FiducialMeasurement(boost::lexical_cast<std::string>(ids[i]), fiducialPoseEye, fiducialPoseWorld));\n  }\n\n  return measurements;\n}\n\nboost::optional<Vector3f> ArUcoFiducialDetector::pick_corner_from_depth(const cv::Point2f& corner, const View_CPtr& view) const\n{\n  // FIXME: I'm currently assuming that there is an identity mapping between the depth and colour cameras - in general, this won't be the case.\n  const int width = view->depth->noDims.x, height = view->depth->noDims.y;\n  const int ux = (int)CLAMP(ROUND(corner.x), 0, width - 1), uy = (int)CLAMP(ROUND(corner.y), 0, height - 1);\n  const int locId = uy * width + ux;\n  const float depth = view->depth->GetData(MEMORYDEVICE_CPU)[locId];\n\n  const float EPSILON = 1e-3f;\n  if(fabs(depth + 1) > EPSILON) // i.e. if(depth != -1)\n  {\n    return unproject(ux, uy, depth, view->calib.intrinsics_d.projectionParamsSimple.all);\n  }\n  else return boost::none;\n}\n\nboost::optional<Vector3f> ArUcoFiducialDetector::pick_corner_from_raycast(const cv::Point2f& corner, const VoxelRenderState_CPtr& renderState) const\n{\n  // FIXME: I'm currently assuming that there is an identity mapping between the depth and colour cameras - in general, this won't be the case.\n  const int width = renderState->raycastResult->noDims.x, height = renderState->raycastResult->noDims.y;\n  Vector2i p((int)CLAMP(ROUND(corner.x), 0, width - 1), (int)CLAMP(ROUND(corner.y), 0, height - 1));\n\n  if(!m_picker) m_picker = PickerFactory::make_picker(m_settings->deviceType);\n\n  static boost::shared_ptr<ORUtils::MemoryBlock<Vector3f> > pickPointFloatMB = MemoryBlockFactory::instance().make_block<Vector3f>(1);\n  bool pickPointFound = m_picker->pick(p.x, p.y, renderState.get(), *pickPointFloatMB);\n  if(!pickPointFound) return boost::none;\n\n  return Picker::get_positions<Vector3f>(*pickPointFloatMB, m_settings->sceneParams.voxelSize)[0];\n}\n\n//#################### PRIVATE STATIC MEMBER FUNCTIONS ####################\n\nboost::optional<ORUtils::SE3Pose> ArUcoFiducialDetector::make_pose_from_corners(const boost::optional<Vector3f>& v0,\n                                                                                const boost::optional<Vector3f>& v1,\n                                                                                const boost::optional<Vector3f>& v2)\n{\n  boost::optional<ORUtils::SE3Pose> pose;\n\n  if(v0 && v1 && v2)\n  {\n    Vector3f xp = (*v1 - *v0).normalised();\n    Vector3f yp = (*v2 - *v0).normalised();\n    Vector3f zp = ORUtils::cross(xp, yp);\n    yp = ORUtils::cross(zp, xp);\n\n    SimpleCamera cam(\n      Eigen::Vector3f(v0->x, v0->y, v0->z),\n      Eigen::Vector3f(zp.x, zp.y, zp.z),\n      Eigen::Vector3f(-yp.x, -yp.y, -yp.z)\n    );\n\n    pose = CameraPoseConverter::camera_to_pose(cam);\n  }\n\n  return pose;\n}\n\n}\n", "meta": {"hexsha": "f815445820521ace319d4f66c10df1963ef33dfc", "size": 9607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/spaint/src/fiducials/ArUcoFiducialDetector.cpp", "max_stars_repo_name": "GucciPrada/spaint", "max_stars_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-16T06:39:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T06:39:21.000Z", "max_issues_repo_path": "modules/spaint/src/fiducials/ArUcoFiducialDetector.cpp", "max_issues_repo_name": "GucciPrada/spaint", "max_issues_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "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": "modules/spaint/src/fiducials/ArUcoFiducialDetector.cpp", "max_forks_repo_name": "GucciPrada/spaint", "max_forks_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "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.0528455285, "max_line_length": 176, "alphanum_fraction": 0.6817945248, "num_tokens": 2655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.18278026734727043}}
{"text": "#include <cstdint>\n#include <string>\n#include <vector>\n\n#include \"baldr/graphconstants.h\"\n#include \"filesystem.h\"\n#include \"mjolnir/adminbuilder.h\"\n#include \"mjolnir/adminconstants.h\"\n#include \"mjolnir/osmpbfparser.h\"\n#include \"mjolnir/pbfadminparser.h\"\n#include \"mjolnir/util.h\"\n\n// sqlite is included in util.h and must be before spatialite\n#include <spatialite.h>\n\n#include \"config.h\"\n\n/* Need to know which geos version we have to work out which headers to include */\n#include <geos/version.h>\n\n#define USE_UNSTABLE_GEOS_CPP_API\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 8\n#include <geos/geom/CoordinateArraySequence.h>\n#else\n#include <geos/geom/CoordinateSequenceFactory.h>\n#endif\n#include <geos/geom/Geometry.h>\n#include <geos/geom/GeometryFactory.h>\n#include <geos/geom/LineString.h>\n#include <geos/geom/LinearRing.h>\n#include <geos/geom/MultiLineString.h>\n#include <geos/geom/MultiPolygon.h>\n#include <geos/geom/Point.h>\n#include <geos/geom/Polygon.h>\n#include <geos/io/WKTReader.h>\n#include <geos/io/WKTWriter.h>\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 9\n#include <geos/operation/linemerge/LineMerger.h>\n#else\n#include <geos/opLinemerge.h>\n#endif\n#include <geos/util/GEOSException.h>\n\n#include <boost/optional.hpp>\n#include <boost/property_tree/ptree.hpp>\n\nusing namespace geos::geom;\nusing namespace geos::io;\nusing namespace geos::util;\nusing namespace geos::operation::linemerge;\n\n// For OSM pbf reader\nusing namespace valhalla::mjolnir;\nusing namespace valhalla::baldr;\n\nusing namespace valhalla::midgard;\n\nnamespace {\n\nstruct polygondata {\n  Polygon* polygon;\n  LinearRing* ring;\n  double area;\n  int iscontained;\n  unsigned containedbyid;\n};\n\nint polygondata_comparearea(const void* vp1, const void* vp2) {\n  const polygondata* p1 = (const polygondata*)vp1;\n  const polygondata* p2 = (const polygondata*)vp2;\n\n  if (p1->area == p2->area) {\n    return 0;\n  }\n  if (p1->area > p2->area) {\n    return -1;\n  }\n  return 1;\n}\n\nstd::vector<std::string> GetWkts(std::unique_ptr<Geometry>& mline) {\n  std::vector<std::string> wkts;\n\n#if 3 == GEOS_VERSION_MAJOR && 6 <= GEOS_VERSION_MINOR\n  auto gf = GeometryFactory::create();\n#else\n  std::unique_ptr<GeometryFactory> gf(new GeometryFactory());\n#endif\n\n  LineMerger merger;\n  merger.add(mline.get());\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 9\n  std::vector<std::unique_ptr<LineString>> merged(merger.getMergedLineStrings());\n#else\n  std::unique_ptr<std::vector<LineString*>> merged(merger.getMergedLineStrings());\n#endif\n  WKTWriter writer;\n\n  // Procces ways into lines or simple polygon list\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 9\n  polygondata* polys = new polygondata[merged.size()];\n#else\n  polygondata* polys = new polygondata[merged->size()];\n#endif\n\n  unsigned totalpolys = 0;\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 9\n  for (unsigned i = 0; i < merged.size(); ++i) {\n    std::unique_ptr<LineString> pline(merged[i].release());\n#else\n  for (unsigned i = 0; i < merged->size(); ++i) {\n    std::unique_ptr<LineString> pline((*merged)[i]);\n#endif\n    if (pline->getNumPoints() > 3 && pline->isClosed()) {\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 8\n      polys[totalpolys].polygon =\n          gf->createPolygon(gf->createLinearRing(pline->getCoordinates())).release();\n      polys[totalpolys].ring = gf->createLinearRing(pline->getCoordinates()).release();\n#else\n      polys[totalpolys].polygon = gf->createPolygon(gf->createLinearRing(pline->getCoordinates()), 0);\n      polys[totalpolys].ring = gf->createLinearRing(pline->getCoordinates());\n#endif\n      polys[totalpolys].area = polys[totalpolys].polygon->getArea();\n      polys[totalpolys].iscontained = 0;\n      polys[totalpolys].containedbyid = 0;\n      if (polys[totalpolys].area > 0.0) {\n        totalpolys++;\n      } else {\n        delete (polys[totalpolys].polygon);\n        delete (polys[totalpolys].ring);\n      }\n    }\n  }\n\n  if (totalpolys) {\n    qsort(polys, totalpolys, sizeof(polygondata), polygondata_comparearea);\n\n    for (unsigned i = 0; i < totalpolys; ++i) {\n      if (polys[i].iscontained != 0) {\n        continue;\n      }\n\n      for (unsigned j = i + 1; j < totalpolys; ++j) {\n        // Does polygon[i] contain the smaller polygon[j]?\n        if (polys[j].containedbyid == 0 && polys[i].polygon->contains(polys[j].polygon)) {\n          // are we in a [i] contains [k] contains [j] situation\n          // which would actually make j top level\n          bool istoplevelafterall = false;\n          for (unsigned k = i + 1; k < j; ++k) {\n            if (polys[k].iscontained && polys[k].containedbyid == i &&\n                polys[k].polygon->contains(polys[j].polygon)) {\n              istoplevelafterall = true;\n              break;\n            }\n          }\n          if (istoplevelafterall) {\n            polys[j].iscontained = 1;\n            polys[j].containedbyid = i;\n          }\n        }\n      }\n    }\n    // polys now is a list of polygons tagged with which ones are inside each other\n\n    // List of polygons for multipolygon\n    std::unique_ptr<std::vector<Geometry*>> polygons(new std::vector<Geometry*>);\n\n    // For each top level polygon create a new polygon including any holes\n    for (unsigned i = 0; i < totalpolys; ++i) {\n      if (polys[i].iscontained != 0) {\n        continue;\n      }\n\n      // List of holes for this top level polygon\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 8\n      std::unique_ptr<std::vector<LinearRing*>> interior(new std::vector<LinearRing*>);\n#else\n      std::unique_ptr<std::vector<Geometry*>> interior(new std::vector<Geometry*>);\n#endif\n      for (unsigned j = i + 1; j < totalpolys; ++j) {\n        if (polys[j].iscontained == 1 && polys[j].containedbyid == i) {\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 8\n          interior->push_back(polys[j].ring);\n#else\n          interior->push_back(polys[j].ring);\n#endif\n        }\n      }\n\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 8\n      Polygon* poly(gf->createPolygon(polys[i].ring, interior.release()));\n#else\n      Polygon* poly(gf->createPolygon(polys[i].ring, interior.release()));\n#endif\n      poly->normalize();\n      polygons->push_back(poly);\n    }\n\n    // Make a multipolygon\n    std::unique_ptr<Geometry> multipoly(gf->createMultiPolygon(polygons.release()));\n    if (!multipoly->isValid()) {\n      multipoly = std::unique_ptr<Geometry>(multipoly->buffer(0));\n    }\n    multipoly->normalize();\n\n    if (multipoly->isValid()) {\n      wkts.push_back(writer.write(multipoly.get()));\n    }\n  }\n\n  for (unsigned i = 0; i < totalpolys; ++i) {\n    delete (polys[i].polygon);\n  }\n\n  delete[](polys);\n\n  return wkts;\n}\n\n} // anonymous namespace\n\nnamespace valhalla {\nnamespace mjolnir {\n\n/**\n * Build admins from protocol buffer input.\n */\nvoid BuildAdminFromPBF(const boost::property_tree::ptree& pt,\n                       const std::vector<std::string>& input_files) {\n\n  // Read the OSM protocol buffer file. Callbacks for nodes, ways, and\n  // relations are defined within the PBFParser class\n  OSMAdminData osm_admin_data = PBFAdminParser::Parse(pt, input_files);\n\n  // done with the protobuffer library, cant use it again after this\n  OSMPBF::Parser::free();\n\n  // Bail if bad path\n  auto database = pt.get_optional<std::string>(\"admin\");\n\n  if (!database) {\n    LOG_INFO(\"Admin config info not found. Admins will not be created.\");\n    return;\n  }\n\n  if (!filesystem::exists(filesystem::path(*database).parent_path())) {\n    filesystem::create_directories(filesystem::path(*database).parent_path());\n  }\n\n  if (!filesystem::exists(filesystem::path(*database).parent_path())) {\n    LOG_INFO(\"Admin directory not found. Admins will not be created.\");\n    return;\n  }\n\n  if (filesystem::exists(*database)) {\n    filesystem::remove(*database);\n  }\n\n  spatialite_init(0);\n\n  sqlite3* db_handle;\n  sqlite3_stmt* stmt;\n  uint32_t ret;\n  char* err_msg = NULL;\n  std::string sql;\n\n  ret = sqlite3_open_v2((*database).c_str(), &db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,\n                        NULL);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"cannot open \" + (*database));\n    sqlite3_close(db_handle);\n    return;\n  }\n\n  // loading SpatiaLite as an extension\n  if (!valhalla::mjolnir::load_spatialite(db_handle)) {\n    sqlite3_close(db_handle);\n    return;\n  }\n\n  /* creating an admin POLYGON table */\n  sql = \"SELECT InitSpatialMetaData(1); CREATE TABLE admins (\";\n  sql += \"admin_level INTEGER NOT NULL,\";\n  sql += \"iso_code TEXT,\";\n  sql += \"parent_admin INTEGER,\";\n  sql += \"name TEXT NOT NULL,\";\n  sql += \"name_en TEXT,\";\n  sql += \"drive_on_right INTEGER NOT NULL,\";\n  sql += \"allow_intersection_names INTEGER NOT NULL)\";\n\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n\n  /* creating an admin access table\n   * We could support all the commented out\n   * columns below; however, for now we only\n   * need the following ones until more people\n   * update the specs on the wiki.\n   */\n\n  sql = \"CREATE TABLE admin_access (\";\n  sql += \"admin_id INTEGER NOT NULL,\";\n  sql += \"iso_code TEXT,\";\n  // sql += \"motorway INTEGER DEFAULT NULL,\";\n  // sql += \"motorway_link INTEGER DEFAULT NULL,\";\n  sql += \"trunk INTEGER DEFAULT NULL,\";\n  sql += \"trunk_link INTEGER DEFAULT NULL,\";\n  // sql += \"prim_ary INTEGER DEFAULT NULL,\";\n  // sql += \"prim_ary_link INTEGER DEFAULT NULL,\";\n  // sql += \"secondary INTEGER DEFAULT NULL,\";\n  // sql += \"secondary_link INTEGER DEFAULT NULL,\";\n  // sql += \"residential INTEGER DEFAULT NULL,\";\n  // sql += \"residential_link INTEGER DEFAULT NULL,\";\n  // sql += \"service INTEGER DEFAULT NULL,\";\n  // sql += \"tertiary INTEGER DEFAULT NULL,\";\n  // sql += \"tertiary_link INTEGER DEFAULT NULL,\";\n  // sql += \"road INTEGER DEFAULT NULL,\";\n  sql += \"track INTEGER DEFAULT NULL,\";\n  // sql += \"unclassified INTEGER DEFAULT NULL,\";\n  // sql += \"undefined INTEGER DEFAULT NULL,\";\n  // sql += \"unknown INTEGER DEFAULT NULL,\";\n  // sql += \"living_street INTEGER DEFAULT NULL,\";\n  sql += \"footway INTEGER DEFAULT NULL,\";\n  sql += \"pedestrian INTEGER DEFAULT NULL,\";\n  // sql += \"steps INTEGER DEFAULT NULL,\";\n  sql += \"bridleway INTEGER DEFAULT NULL,\";\n  // sql += \"construction INTEGER DEFAULT NULL,\";\n  sql += \"cycleway INTEGER DEFAULT NULL,\";\n  // sql += \"bus_guideway INTEGER DEFAULT NULL,\";\n  sql += \"path INTEGER DEFAULT NULL,\";\n  sql += \"motorroad INTEGER DEFAULT NULL)\";\n\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n\n  LOG_INFO(\"Created admin access table.\");\n\n  /* creating a MULTIPOLYGON Geometry column */\n  sql = \"SELECT AddGeometryColumn('admins', \";\n  sql += \"'geom', 4326, 'MULTIPOLYGON', 2)\";\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n\n  LOG_INFO(\"Created admin table.\");\n\n  /*\n   * inserting some MULTIPOLYGONs\n   * this time too we'll use a Prepared Statement\n   */\n  sql = \"INSERT INTO admins (admin_level, iso_code, parent_admin, name, name_en, \";\n  sql += \"drive_on_right, allow_intersection_names, geom) VALUES (?, ?, ?, ?, ?, ? ,?, \";\n  sql += \"CastToMulti(GeomFromText(?, 4326)))\";\n\n  ret = sqlite3_prepare_v2(db_handle, sql.c_str(), strlen(sql.c_str()), &stmt, NULL);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"SQL error: \" + sql);\n    LOG_ERROR(std::string(sqlite3_errmsg(db_handle)));\n  }\n  ret = sqlite3_exec(db_handle, \"BEGIN\", NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n\n  uint32_t count = 0;\n  bool has_data;\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 6\n  auto gf = GeometryFactory::create();\n#else\n  std::unique_ptr<GeometryFactory> gf(new GeometryFactory());\n#endif\n\n  try {\n\n    for (const auto& admin : osm_admin_data.admins_) {\n\n      std::unique_ptr<Geometry> geom;\n      std::unique_ptr<std::vector<Geometry*>> lines(new std::vector<Geometry*>);\n      has_data = true;\n\n      for (const auto memberid : admin.ways()) {\n\n        auto itr = osm_admin_data.way_map.find(memberid);\n\n        // A relation may be included in an extract but it's members may not.\n        // Example:  PA extract can contain a NY relation.\n        if (itr == osm_admin_data.way_map.end()) {\n          has_data = false;\n          break;\n        }\n\n#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 8\n        auto coords = std::unique_ptr<CoordinateArraySequence>(new CoordinateArraySequence);\n#else\n        std::unique_ptr<CoordinateSequence> coords(\n            gf->getCoordinateSequenceFactory()->create((size_t)0, (size_t)2));\n#endif\n\n        for (const auto ref_id : itr->second) {\n\n          const PointLL ll = osm_admin_data.shape_map.at(ref_id);\n\n          Coordinate c;\n          c.x = ll.lng();\n          c.y = ll.lat();\n          coords->add(c, 0);\n        }\n\n        if (coords->getSize() > 1) {\n          geom = std::unique_ptr<Geometry>(gf->createLineString(coords.release()));\n          lines->push_back(geom.release());\n        }\n\n      } // member loop\n\n      if (has_data) {\n\n        std::unique_ptr<Geometry> mline(gf->createMultiLineString(lines.release()));\n        std::vector<std::string> wkts = GetWkts(mline);\n        std::string name;\n        std::string name_en;\n        std::string iso;\n\n        for (const auto& wkt : wkts) {\n\n          count++;\n          sqlite3_reset(stmt);\n          sqlite3_clear_bindings(stmt);\n          sqlite3_bind_int(stmt, 1, admin.admin_level());\n\n          if (admin.iso_code_index()) {\n            iso = osm_admin_data.name_offset_map.name(admin.iso_code_index());\n            sqlite3_bind_text(stmt, 2, iso.c_str(), iso.length(), SQLITE_STATIC);\n          } else {\n            sqlite3_bind_null(stmt, 2);\n          }\n\n          sqlite3_bind_null(stmt, 3);\n\n          name = osm_admin_data.name_offset_map.name(admin.name_index());\n          sqlite3_bind_text(stmt, 4, name.c_str(), name.length(), SQLITE_STATIC);\n\n          if (admin.name_en_index()) {\n            name_en = osm_admin_data.name_offset_map.name(admin.name_en_index());\n            sqlite3_bind_text(stmt, 5, name_en.c_str(), name_en.length(), SQLITE_STATIC);\n          } else {\n            sqlite3_bind_null(stmt, 5);\n          }\n\n          sqlite3_bind_int(stmt, 6, admin.drive_on_right());\n          sqlite3_bind_int(stmt, 7, admin.allow_intersection_names());\n          sqlite3_bind_text(stmt, 8, wkt.c_str(), wkt.length(), SQLITE_STATIC);\n          /* performing INSERT INTO */\n          ret = sqlite3_step(stmt);\n          if (ret == SQLITE_DONE || ret == SQLITE_ROW) {\n            continue;\n          }\n          LOG_ERROR(\"sqlite3_step() error: \" + std::string(sqlite3_errmsg(db_handle)));\n          LOG_ERROR(\"sqlite3_step() Name: \" +\n                    osm_admin_data.name_offset_map.name(admin.name_index()));\n          LOG_ERROR(\"sqlite3_step() Name:en: \" +\n                    osm_admin_data.name_offset_map.name(admin.name_en_index()));\n          LOG_ERROR(\"sqlite3_step() Admin Level: \" + std::to_string(admin.admin_level()));\n          LOG_ERROR(\"sqlite3_step() Drive on Right: \" + std::to_string(admin.drive_on_right()));\n          LOG_ERROR(\"sqlite3_step() Allow Intersection Names: \" +\n                    std::to_string(admin.allow_intersection_names()));\n        }\n      } // has data\n    }   // admins\n  } catch (std::exception& e) {\n    LOG_ERROR(\"Standard exception processing relation: \" + std::string(e.what()));\n  } catch (...) { LOG_ERROR(\"Exception caught processing relations.\"); }\n\n  sqlite3_finalize(stmt);\n  ret = sqlite3_exec(db_handle, \"COMMIT\", NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n  LOG_INFO(\"Inserted \" + std::to_string(count) + \" admin areas\");\n\n  sql = \"SELECT CreateSpatialIndex('admins', 'geom')\";\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n  LOG_INFO(\"Created spatial index\");\n\n  sql = \"CREATE INDEX IdxLevel ON admins (admin_level)\";\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n  LOG_INFO(\"Created Level index\");\n\n  sql = \"CREATE INDEX IdxDriveOnRight ON admins (drive_on_right)\";\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n  LOG_INFO(\"Created Drive On Right index\");\n\n  sql = \"CREATE INDEX IdxAllowIntersectionNames ON admins (allow_intersection_names)\";\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n  LOG_INFO(\"Created allow intersection names index\");\n\n  sql = \"update admins set drive_on_right = (select a.drive_on_right from admins\";\n  sql += \" a where ST_Covers(a.geom, admins.geom) and admins.admin_level != \";\n  sql += \"a.admin_level and a.drive_on_right=0) where rowid = \";\n  sql += \"(select admins.rowid from admins a where ST_Covers(a.geom, admins.geom) \";\n  sql += \"and admins.admin_level != a.admin_level and a.drive_on_right=0)\";\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n  LOG_INFO(\"Done updating drive on right column.\");\n\n  sql = \"update admins set allow_intersection_names = (select a.allow_intersection_names from admins\";\n  sql += \" a where ST_Covers(a.geom, admins.geom) and admins.admin_level != \";\n  sql += \"a.admin_level and a.allow_intersection_names=1) where rowid = \";\n  sql += \"(select admins.rowid from admins a where ST_Covers(a.geom, admins.geom) \";\n  sql += \"and admins.admin_level != a.admin_level and a.allow_intersection_names=1)\";\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n  LOG_INFO(\"Done updating allow intersection names column.\");\n\n  sql = \"update admins set parent_admin = (select a.rowid from admins\";\n  sql += \" a where ST_Covers(a.geom, admins.geom) and admins.admin_level != \";\n  sql += \"a.admin_level) where rowid = \";\n  sql += \"(select admins.rowid from admins a where ST_Covers(a.geom, admins.geom) \";\n  sql += \"and admins.admin_level != a.admin_level)\";\n  ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n  LOG_INFO(\"Done updating Parent admin\");\n\n  sql = \"INSERT into admin_access (admin_id, iso_code, trunk, trunk_link, track, footway, \";\n  sql += \"pedestrian, bridleway, cycleway, path, motorroad) VALUES (\";\n  sql += \"(select rowid from admins where (name = ? or name_en = ?)), \";\n  sql += \"(select iso_code from admins where (name = ? or name_en = ?)), \";\n  sql += \"?, ?, ?, ?, ?, ?, ?, ?, ?)\";\n\n  ret = sqlite3_prepare_v2(db_handle, sql.c_str(), strlen(sql.c_str()), &stmt, NULL);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"SQL error: \" + sql);\n    LOG_ERROR(std::string(sqlite3_errmsg(db_handle)));\n  }\n  ret = sqlite3_exec(db_handle, \"BEGIN\", NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n\n  for (const auto& access : kCountryAccess) {\n\n    const std::vector<int> column_values = access.second;\n\n    sqlite3_reset(stmt);\n    sqlite3_clear_bindings(stmt);\n    sqlite3_bind_text(stmt, 1, access.first.c_str(), access.first.length(), SQLITE_STATIC);\n    sqlite3_bind_text(stmt, 2, access.first.c_str(), access.first.length(), SQLITE_STATIC);\n    sqlite3_bind_text(stmt, 3, access.first.c_str(), access.first.length(), SQLITE_STATIC);\n    sqlite3_bind_text(stmt, 4, access.first.c_str(), access.first.length(), SQLITE_STATIC);\n\n    for (uint32_t col = 0; col != column_values.size(); ++col) {\n      int val = column_values.at(col);\n      if (val != -1) {\n        sqlite3_bind_int(stmt, col + 5, val);\n      } else {\n        sqlite3_bind_null(stmt, col + 5);\n      }\n    }\n\n    /* performing INSERT INTO */\n    ret = sqlite3_step(stmt);\n    if (ret == SQLITE_DONE || ret == SQLITE_ROW) {\n      continue;\n    }\n    LOG_ERROR(\"sqlite3_step() error: \" + std::string(sqlite3_errmsg(db_handle)) +\n              \".  Ignore if not using a planet extract or check if there was a name change for \" +\n              access.first.c_str());\n  }\n\n  sqlite3_finalize(stmt);\n  ret = sqlite3_exec(db_handle, \"COMMIT\", NULL, NULL, &err_msg);\n  if (ret != SQLITE_OK) {\n    LOG_ERROR(\"Error: \" + std::string(err_msg));\n    sqlite3_free(err_msg);\n    sqlite3_close(db_handle);\n    return;\n  }\n\n  sqlite3_close(db_handle);\n\n  LOG_INFO(\"Finished.\");\n}\n\n} // namespace mjolnir\n\n} // namespace valhalla\n", "meta": {"hexsha": "a3a532c9828318509fdabdceeee2292c5742206c", "size": 21690, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mjolnir/adminbuilder.cc", "max_stars_repo_name": "Georepublic/valhalla", "max_stars_repo_head_hexsha": "079c11978093608e730b22a52c2363d39eefdc15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-19T05:31:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T05:31:55.000Z", "max_issues_repo_path": "src/mjolnir/adminbuilder.cc", "max_issues_repo_name": "Georepublic/valhalla", "max_issues_repo_head_hexsha": "079c11978093608e730b22a52c2363d39eefdc15", "max_issues_repo_licenses": ["MIT"], "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/mjolnir/adminbuilder.cc", "max_forks_repo_name": "Georepublic/valhalla", "max_forks_repo_head_hexsha": "079c11978093608e730b22a52c2363d39eefdc15", "max_forks_repo_licenses": ["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.4206471495, "max_line_length": 102, "alphanum_fraction": 0.6497925311, "num_tokens": 5752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18278025658752428}}
{"text": "#include <src/node/wallet.hpp>\n\n#include <src/lib/interface.h>\n#include <src/node/node.hpp>\n#include <src/node/xorshift.hpp>\n\n#include <argon2.h>\n\n#include <boost/filesystem.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include <future>\n\n#include <ed25519-donna/ed25519.h>\n\ngerm::uint256_union germ::wallet_store::check (MDB_txn * transaction_a)\n{\n    germ::wallet_value value (entry_get_raw (transaction_a, germ::wallet_store::check_special));\n    return value.key;\n}\n\ngerm::uint256_union germ::wallet_store::salt (MDB_txn * transaction_a)\n{\n    germ::wallet_value value (entry_get_raw (transaction_a, germ::wallet_store::salt_special));\n    return value.key;\n}\n\nvoid germ::wallet_store::wallet_key (germ::raw_key & prv_a, MDB_txn * transaction_a)\n{\n    std::lock_guard<std::recursive_mutex> lock (mutex);\n    germ::raw_key wallet_l;\n    wallet_key_mem.value (wallet_l);\n    germ::raw_key password_l;\n    password.value (password_l);\n    prv_a.decrypt (wallet_l.data, password_l, salt (transaction_a).owords[0]);\n}\n\nvoid germ::wallet_store::seed (germ::raw_key & prv_a, MDB_txn * transaction_a)\n{\n    germ::wallet_value value (entry_get_raw (transaction_a, germ::wallet_store::seed_special));\n    germ::raw_key password_l;\n    wallet_key (password_l, transaction_a);\n    prv_a.decrypt (value.key, password_l, salt (transaction_a).owords[0]);\n}\n\nvoid germ::wallet_store::seed_set (MDB_txn * transaction_a, germ::raw_key const & prv_a)\n{\n    germ::raw_key password_l;\n    wallet_key (password_l, transaction_a);\n    germ::uint256_union ciphertext;\n    ciphertext.encrypt (prv_a, password_l, salt (transaction_a).owords[0]);\n    entry_put_raw (transaction_a, germ::wallet_store::seed_special, germ::wallet_value (ciphertext, 0));\n    deterministic_clear (transaction_a);\n}\n\ngerm::public_key germ::wallet_store::deterministic_insert (MDB_txn * transaction_a)\n{\n    auto index (deterministic_index_get (transaction_a));\n    germ::raw_key prv;\n    deterministic_key (prv, transaction_a, index);\n    germ::public_key result;\n    ed25519_publickey (prv.data.bytes.data (), result.bytes.data ());\n    while (exists (transaction_a, result))\n    {\n        ++index;\n        deterministic_key (prv, transaction_a, index);\n        ed25519_publickey (prv.data.bytes.data (), result.bytes.data ());\n    }\n    uint64_t marker (1);\n    marker <<= 32;\n    marker |= index;\n    entry_put_raw (transaction_a, result, germ::wallet_value (germ::uint256_union (marker), 0));\n    ++index;\n    deterministic_index_set (transaction_a, index);\n    return result;\n}\n\nvoid germ::wallet_store::deterministic_key (germ::raw_key & prv_a, MDB_txn * transaction_a, uint32_t index_a)\n{\n    assert (valid_password (transaction_a));\n    germ::raw_key seed_l;\n    seed (seed_l, transaction_a);\n    germ::deterministic_key (seed_l.data, index_a, prv_a.data);\n}\n\nuint32_t germ::wallet_store::deterministic_index_get (MDB_txn * transaction_a)\n{\n    germ::wallet_value value (entry_get_raw (transaction_a, germ::wallet_store::deterministic_index_special));\n    return value.key.number ().convert_to<uint32_t> ();\n}\n\nvoid germ::wallet_store::deterministic_index_set (MDB_txn * transaction_a, uint32_t index_a)\n{\n    germ::uint256_union index_l (index_a);\n    germ::wallet_value value (index_l, 0);\n    entry_put_raw (transaction_a, germ::wallet_store::deterministic_index_special, value);\n}\n\nvoid germ::wallet_store::deterministic_clear (MDB_txn * transaction_a)\n{\n    germ::uint256_union key (0);\n    for (auto i (begin (transaction_a)), n (end ()); i != n;)\n    {\n        switch (key_type (germ::wallet_value (i->second)))\n        {\n            case germ::key_type::deterministic:\n            {\n                germ::uint256_union key (i->first.uint256 ());\n                erase (transaction_a, key);\n                i = begin (transaction_a, key);\n                break;\n            }\n            default:\n            {\n                ++i;\n                break;\n            }\n        }\n    }\n    deterministic_index_set (transaction_a, 0);\n}\n\nbool germ::wallet_store::valid_password (MDB_txn * transaction_a)\n{\n    germ::raw_key zero;\n    zero.data.clear ();\n    germ::raw_key wallet_key_l;\n    wallet_key (wallet_key_l, transaction_a);\n    germ::uint256_union check_l;\n    check_l.encrypt (zero, wallet_key_l, salt (transaction_a).owords[0]);\n    bool ok = check (transaction_a) == check_l;\n    return ok;\n}\n\nbool germ::wallet_store::attempt_password (MDB_txn * transaction_a, std::string const & password_a)\n{\n    bool result = false;\n    {\n        std::lock_guard<std::recursive_mutex> lock (mutex);\n        germ::raw_key password_l;\n        derive_key (password_l, transaction_a, password_a);\n        password.value_set (password_l);\n        result = !valid_password (transaction_a);\n    }\n    if (!result)\n    {\n        if (version (transaction_a) == version_1)\n        {\n            upgrade_v1_v2 ();\n        }\n        if (version (transaction_a) == version_2)\n        {\n            upgrade_v2_v3 ();\n        }\n    }\n    return result;\n}\n\nbool germ::wallet_store::rekey (MDB_txn * transaction_a, std::string const & password_a)\n{\n    std::lock_guard<std::recursive_mutex> lock (mutex);\n    bool result (false);\n    if (valid_password (transaction_a))\n    {\n        germ::raw_key password_new;\n        derive_key (password_new, transaction_a, password_a);\n        germ::raw_key wallet_key_l;\n        wallet_key (wallet_key_l, transaction_a);\n        germ::raw_key password_l;\n        password.value (password_l);\n        password.value_set (password_new);\n        germ::uint256_union encrypted;\n        encrypted.encrypt (wallet_key_l, password_new, salt (transaction_a).owords[0]);\n        germ::raw_key wallet_enc;\n        wallet_enc.data = encrypted;\n        wallet_key_mem.value_set (wallet_enc);\n        entry_put_raw (transaction_a, germ::wallet_store::wallet_key_special, germ::wallet_value (encrypted, 0));\n    }\n    else\n    {\n        result = true;\n    }\n    return result;\n}\n\nvoid germ::wallet_store::derive_key (germ::raw_key & prv_a, MDB_txn * transaction_a, std::string const & password_a)\n{\n    auto salt_l (salt (transaction_a));\n    kdf.phs (prv_a, password_a, salt_l);\n}\n\ngerm::fan::fan (germ::uint256_union const & key, size_t count_a)\n{\n    std::unique_ptr<germ::uint256_union> first (new germ::uint256_union (key));\n    for (auto i (1); i < count_a; ++i)\n    {\n        std::unique_ptr<germ::uint256_union> entry (new germ::uint256_union);\n        random_pool.GenerateBlock (entry->bytes.data (), entry->bytes.size ());\n        *first ^= *entry;\n        values.push_back (std::move (entry));\n    }\n    values.push_back (std::move (first));\n}\n\nvoid germ::fan::value (germ::raw_key & prv_a)\n{\n    std::lock_guard<std::mutex> lock (mutex);\n    value_get (prv_a);\n}\n\nvoid germ::fan::value_get (germ::raw_key & prv_a)\n{\n    assert (!mutex.try_lock ());\n    prv_a.data.clear ();\n    for (auto & i : values)\n    {\n        prv_a.data ^= *i;\n    }\n}\n\nvoid germ::fan::value_set (germ::raw_key const & value_a)\n{\n    std::lock_guard<std::mutex> lock (mutex);\n    germ::raw_key value_l;\n    value_get (value_l);\n    *(values[0]) ^= value_l.data;\n    *(values[0]) ^= value_a.data;\n}\n\ngerm::wallet_value::wallet_value (germ::mdb_val const & val_a)\n{\n    assert (val_a.size () == sizeof (*this));\n    std::copy (reinterpret_cast<uint8_t const *> (val_a.data ()), reinterpret_cast<uint8_t const *> (val_a.data ()) + sizeof (key), key.chars.begin ());\n    std::copy (reinterpret_cast<uint8_t const *> (val_a.data ()) + sizeof (key), reinterpret_cast<uint8_t const *> (val_a.data ()) + sizeof (key) + sizeof (work), reinterpret_cast<char *> (&work));\n}\n\ngerm::wallet_value::wallet_value (germ::uint256_union const & key_a, uint64_t work_a) :\nkey (key_a),\nwork (work_a)\n{\n}\n\ngerm::mdb_val germ::wallet_value::val () const\n{\n    static_assert (sizeof (*this) == sizeof (key) + sizeof (work), \"Class not packed\");\n    return germ::mdb_val (sizeof (*this), const_cast<germ::wallet_value *> (this));\n}\n\nunsigned const germ::wallet_store::version_1 (1);\nunsigned const germ::wallet_store::version_2 (2);\nunsigned const germ::wallet_store::version_3 (3);\nunsigned const germ::wallet_store::version_current (version_3);\n// Wallet version number\ngerm::uint256_union const germ::wallet_store::version_special (0);\n// Random number used to salt private key encryption\ngerm::uint256_union const germ::wallet_store::salt_special (1);\n// Key used to encrypt wallet keys, encrypted itself by the user password\ngerm::uint256_union const germ::wallet_store::wallet_key_special (2);\n// Check value used to see if password is valid\ngerm::uint256_union const germ::wallet_store::check_special (3);\n// Representative account to be used if we open a new account\ngerm::uint256_union const germ::wallet_store::representative_special (4);\n// Wallet seed for deterministic key generation\ngerm::uint256_union const germ::wallet_store::seed_special (5);\n// Current key index for deterministic keys\ngerm::uint256_union const germ::wallet_store::deterministic_index_special (6);\nint const germ::wallet_store::special_count (7);\n\ngerm::wallet_store::wallet_store (bool & init_a, germ::kdf & kdf_a, germ::transaction & transaction_a, germ::account representative_a, unsigned fanout_a, std::string const & wallet_a, std::string const & json_a) :\npassword (0, fanout_a),\nwallet_key_mem (0, fanout_a),\nkdf (kdf_a),\nenvironment (transaction_a.environment)\n{\n    init_a = false;\n    initialize (transaction_a, init_a, wallet_a);\n    if (init_a)\n        return ;\n\n    MDB_val junk;\n    assert (mdb_get (transaction_a, handle, germ::mdb_val (version_special), &junk) == MDB_NOTFOUND);\n    boost::property_tree::ptree wallet_l;\n    std::stringstream istream (json_a);\n    try\n    {\n        boost::property_tree::read_json (istream, wallet_l);\n    }\n    catch (...)\n    {\n        init_a = true;\n    }\n    for (auto i (wallet_l.begin ()), n (wallet_l.end ()); i != n; ++i)\n    {\n        germ::uint256_union key;\n        init_a = key.decode_hex (i->first);\n        if (!init_a)\n        {\n            germ::uint256_union value;\n            init_a = value.decode_hex (wallet_l.get<std::string> (i->first));\n            if (!init_a)\n            {\n                entry_put_raw (transaction_a, key, germ::wallet_value (value, 0));\n            }\n            else\n            {\n                init_a = true;\n            }\n        }\n        else\n        {\n            init_a = true;\n        }\n    }\n    init_a |= mdb_get (transaction_a, handle, germ::mdb_val (version_special), &junk) != 0;\n    init_a |= mdb_get (transaction_a, handle, germ::mdb_val (wallet_key_special), &junk) != 0;\n    init_a |= mdb_get (transaction_a, handle, germ::mdb_val (salt_special), &junk) != 0;\n    init_a |= mdb_get (transaction_a, handle, germ::mdb_val (check_special), &junk) != 0;\n    init_a |= mdb_get (transaction_a, handle, germ::mdb_val (representative_special), &junk) != 0;\n    germ::raw_key key;\n    key.data.clear ();\n    password.value_set (key);\n    key.data = entry_get_raw (transaction_a, germ::wallet_store::wallet_key_special).key;\n    wallet_key_mem.value_set (key);\n}\n\ngerm::wallet_store::wallet_store (bool & init_a, germ::kdf & kdf_a, germ::transaction & transaction_a, germ::account representative_a, unsigned fanout_a, std::string const & wallet_a) :\npassword (0, fanout_a),\nwallet_key_mem (0, fanout_a),\nkdf (kdf_a),\nenvironment (transaction_a.environment)\n{\n    init_a = false;\n    initialize (transaction_a, init_a, wallet_a);\n    do\n    {\n        if (init_a)\n            break;\n\n        int version_status;\n        MDB_val version_value;\n        version_status = mdb_get (transaction_a, handle, germ::mdb_val (version_special), &version_value);\n        if (version_status != MDB_NOTFOUND)\n            break;\n\n        version_put (transaction_a, version_current);\n        germ::uint256_union salt_l;\n        random_pool.GenerateBlock (salt_l.bytes.data (), salt_l.bytes.size ());\n        entry_put_raw (transaction_a, germ::wallet_store::salt_special, germ::wallet_value (salt_l, 0));\n        // Wallet key is a fixed random key that encrypts all entries\n        germ::raw_key wallet_key;\n        random_pool.GenerateBlock (wallet_key.data.bytes.data (), sizeof (wallet_key.data.bytes));\n        germ::raw_key password_l;\n        password_l.data.clear ();\n        password.value_set (password_l);\n        germ::raw_key zero;\n        zero.data.clear ();\n        // Wallet key is encrypted by the user's password\n        germ::uint256_union encrypted;\n        encrypted.encrypt (wallet_key, zero, salt_l.owords[0]);\n        entry_put_raw (transaction_a, germ::wallet_store::wallet_key_special, germ::wallet_value (encrypted, 0));\n        germ::raw_key wallet_key_enc;\n        wallet_key_enc.data = encrypted;\n        wallet_key_mem.value_set (wallet_key_enc);\n        germ::uint256_union check;\n        check.encrypt (zero, wallet_key, salt_l.owords[0]);\n        entry_put_raw (transaction_a, germ::wallet_store::check_special, germ::wallet_value (check, 0));\n        entry_put_raw (transaction_a, germ::wallet_store::representative_special, germ::wallet_value (representative_a, 0));\n        germ::raw_key seed;\n        random_pool.GenerateBlock (seed.data.bytes.data (), seed.data.bytes.size ());\n        seed_set (transaction_a, seed);\n        entry_put_raw (transaction_a, germ::wallet_store::deterministic_index_special, germ::wallet_value (germ::uint256_union (0), 0));\n\n    } while (0);\n\n    germ::raw_key key;\n    key.data = entry_get_raw (transaction_a, germ::wallet_store::wallet_key_special).key;\n    wallet_key_mem.value_set (key);\n}\n\nstd::vector<germ::account> germ::wallet_store::accounts (MDB_txn * transaction_a)\n{\n    std::vector<germ::account> result;\n    for (auto i (begin (transaction_a)), n (end ()); i != n; ++i)\n    {\n        germ::account account (i->first.uint256 ());\n        result.push_back (account);\n    }\n    return result;\n}\n\nvoid germ::wallet_store::initialize (MDB_txn * transaction_a, bool & init_a, std::string const & path_a)\n{\n    assert (strlen (path_a.c_str ()) == path_a.size ());\n    auto error (0);\n    error |= mdb_dbi_open (transaction_a, path_a.c_str (), MDB_CREATE, &handle);\n    init_a = error != 0;\n}\n\nbool germ::wallet_store::is_representative (MDB_txn * transaction_a)\n{\n    return exists (transaction_a, representative (transaction_a));\n}\n\nvoid germ::wallet_store::representative_set (MDB_txn * transaction_a, germ::account const & representative_a)\n{\n    entry_put_raw (transaction_a, germ::wallet_store::representative_special, germ::wallet_value (representative_a, 0));\n}\n\ngerm::account germ::wallet_store::representative (MDB_txn * transaction_a)\n{\n    germ::wallet_value value (entry_get_raw (transaction_a, germ::wallet_store::representative_special));\n    return value.key;\n}\n\ngerm::public_key germ::wallet_store::insert_adhoc (MDB_txn * transaction_a, germ::raw_key const & prv)\n{\n    assert (valid_password (transaction_a));\n    germ::public_key pub;\n    ed25519_publickey (prv.data.bytes.data (), pub.bytes.data ());\n    germ::raw_key password_l;\n    wallet_key (password_l, transaction_a);\n    germ::uint256_union ciphertext;\n    ciphertext.encrypt (prv, password_l, salt (transaction_a).owords[0]);\n    entry_put_raw (transaction_a, pub, germ::wallet_value (ciphertext, 0));\n    return pub;\n}\n\nvoid germ::wallet_store::insert_watch (MDB_txn * transaction_a, germ::public_key const & pub)\n{\n    entry_put_raw (transaction_a, pub, germ::wallet_value (germ::uint256_union (0), 0));\n}\n\nvoid germ::wallet_store::erase (MDB_txn * transaction_a, germ::public_key const & pub)\n{\n    auto status (mdb_del (transaction_a, handle, germ::mdb_val (pub), nullptr));\n    assert (status == 0);\n}\n\ngerm::wallet_value germ::wallet_store::entry_get_raw (MDB_txn * transaction_a, germ::public_key const & pub_a)\n{\n    germ::wallet_value result;\n    germ::mdb_val value;\n    auto status (mdb_get (transaction_a, handle, germ::mdb_val (pub_a), value));\n    if (status == 0)\n    {\n        result = germ::wallet_value (value);\n    }\n    else\n    {\n        result.key.clear ();\n        result.work = 0;\n    }\n    return result;\n}\n\nvoid germ::wallet_store::entry_put_raw (MDB_txn * transaction_a, germ::public_key const & pub_a, germ::wallet_value const & entry_a)\n{\n    auto status (mdb_put (transaction_a, handle, germ::mdb_val (pub_a), entry_a.val (), 0));\n    assert (status == 0);\n}\n\ngerm::key_type germ::wallet_store::key_type (germ::wallet_value const & value_a)\n{\n    auto number (value_a.key.number ());\n    germ::key_type result;\n    auto text (number.convert_to<std::string> ());\n    if (number > std::numeric_limits<uint64_t>::max ())\n    {\n        result = germ::key_type::adhoc;\n    }\n    else\n    {\n        if ((number >> 32).convert_to<uint32_t> () == 1)\n        {\n            result = germ::key_type::deterministic;\n        }\n        else\n        {\n            result = germ::key_type::unknown;\n        }\n    }\n    return result;\n}\n\nbool germ::wallet_store::fetch (MDB_txn * transaction_a, germ::public_key const & pub, germ::raw_key & prv)\n{\n    auto result (false);\n    if (valid_password (transaction_a))\n    {\n        germ::wallet_value value (entry_get_raw (transaction_a, pub));\n        if (!value.key.is_zero ())\n        {\n            switch (key_type (value))\n            {\n                case germ::key_type::deterministic:\n                {\n                    germ::raw_key seed_l;\n                    seed (seed_l, transaction_a);\n                    uint32_t index (value.key.number ().convert_to<uint32_t> ());\n                    deterministic_key (prv, transaction_a, index);\n                    break;\n                }\n                case germ::key_type::adhoc:\n                {\n                    // Ad-hoc keys\n                    germ::raw_key password_l;\n                    wallet_key (password_l, transaction_a);\n                    prv.decrypt (value.key, password_l, salt (transaction_a).owords[0]);\n                    break;\n                }\n                default:\n                {\n                    result = true;\n                    break;\n                }\n            }\n        }\n        else\n        {\n            result = true;\n        }\n    }\n    else\n    {\n        result = true;\n    }\n    if (!result)\n    {\n        germ::public_key compare;\n        ed25519_publickey (prv.data.bytes.data (), compare.bytes.data ());\n        if (!(pub == compare))\n        {\n            result = true;\n        }\n    }\n    return result;\n}\n\nbool germ::wallet_store::exists (MDB_txn * transaction_a, germ::public_key const & pub)\n{\n    return find (transaction_a, pub) != end ();\n}\n\nvoid germ::wallet_store::serialize_json (MDB_txn * transaction_a, std::string & string_a)\n{\n    boost::property_tree::ptree tree;\n    for (germ::store_iterator i (transaction_a, handle), n (nullptr); i != n; ++i)\n    {\n        tree.put (germ::uint256_union (i->first.uint256 ()).to_string (), germ::wallet_value (i->second).key.to_string ());\n    }\n    std::stringstream ostream;\n    boost::property_tree::write_json (ostream, tree);\n    string_a = ostream.str ();\n}\n\nvoid germ::wallet_store::write_backup (MDB_txn * transaction_a, boost::filesystem::path const & path_a)\n{\n    std::ofstream backup_file;\n    backup_file.open (path_a.string ());\n    if (!backup_file.fail ())\n    {\n        // Set permissions to 600\n        boost::system::error_code ec;\n        boost::filesystem::permissions (path_a, boost::filesystem::perms::owner_read | boost::filesystem::perms::owner_write, ec);\n\n        std::string json;\n        serialize_json (transaction_a, json);\n        backup_file << json;\n    }\n}\n\nbool germ::wallet_store::move (MDB_txn * transaction_a, germ::wallet_store & other_a, std::vector<germ::public_key> const & keys)\n{\n    assert (valid_password (transaction_a));\n    assert (other_a.valid_password (transaction_a));\n    auto result (false);\n    for (auto i (keys.begin ()), n (keys.end ()); i != n; ++i)\n    {\n        germ::raw_key prv;\n        auto error (other_a.fetch (transaction_a, *i, prv));\n        result = result | error;\n        if (!result)\n        {\n            insert_adhoc (transaction_a, prv);\n            other_a.erase (transaction_a, *i);\n        }\n    }\n    return result;\n}\n\nbool germ::wallet_store::import (MDB_txn * transaction_a, germ::wallet_store & other_a)\n{\n    assert (valid_password (transaction_a));\n    assert (other_a.valid_password (transaction_a));\n    auto result (false);\n    for (auto i (other_a.begin (transaction_a)), n (end ()); i != n; ++i)\n    {\n        germ::raw_key prv;\n        auto error (other_a.fetch (transaction_a, i->first.uint256 (), prv));\n        result = result | error;\n        if (!result)\n        {\n            insert_adhoc (transaction_a, prv);\n            other_a.erase (transaction_a, i->first.uint256 ());\n        }\n    }\n    return result;\n}\n\nbool germ::wallet_store::work_get (MDB_txn * transaction_a, germ::public_key const & pub_a, uint64_t & work_a)\n{\n    auto result (false);\n    auto entry (entry_get_raw (transaction_a, pub_a));\n    if (!entry.key.is_zero ())\n    {\n        work_a = entry.work;\n    }\n    else\n    {\n        result = true;\n    }\n    return result;\n}\n\nvoid germ::wallet_store::work_put (MDB_txn * transaction_a, germ::public_key const & pub_a, uint64_t work_a)\n{\n    auto entry (entry_get_raw (transaction_a, pub_a));\n    assert (!entry.key.is_zero ());\n    entry.work = work_a;\n    entry_put_raw (transaction_a, pub_a, entry);\n}\n\nunsigned germ::wallet_store::version (MDB_txn * transaction_a)\n{\n    germ::wallet_value value (entry_get_raw (transaction_a, germ::wallet_store::version_special));\n    auto entry (value.key);\n    auto result (static_cast<unsigned> (entry.bytes[31]));\n    return result;\n}\n\nvoid germ::wallet_store::version_put (MDB_txn * transaction_a, unsigned version_a)\n{\n    germ::uint256_union entry (version_a);\n    entry_put_raw (transaction_a, germ::wallet_store::version_special, germ::wallet_value (entry, 0));\n}\n\nvoid germ::wallet_store::upgrade_v1_v2 ()\n{\n    germ::transaction transaction (environment, nullptr, true);\n    assert (version (transaction) == 1);\n    germ::raw_key zero_password;\n    germ::wallet_value value (entry_get_raw (transaction, germ::wallet_store::wallet_key_special));\n    germ::raw_key kdf;\n    kdf.data.clear ();\n    zero_password.decrypt (value.key, kdf, salt (transaction).owords[0]);\n    derive_key (kdf, transaction, \"\");\n    germ::raw_key empty_password;\n    empty_password.decrypt (value.key, kdf, salt (transaction).owords[0]);\n    for (auto i (begin (transaction)), n (end ()); i != n; ++i)\n    {\n        germ::public_key key (i->first.uint256 ());\n        germ::raw_key prv;\n        if (!fetch (transaction, key, prv))\n            continue;\n\n        // Key failed to decrypt despite valid password\n        germ::wallet_value data (entry_get_raw (transaction, key));\n        prv.decrypt (data.key, zero_password, salt (transaction).owords[0]);\n        germ::public_key compare;\n        ed25519_publickey (prv.data.bytes.data (), compare.bytes.data ());\n        if (compare == key)\n        {\n            // If we successfully decrypted it, rewrite the key back with the correct wallet key\n            insert_adhoc (transaction, prv);\n        }\n        else\n        {\n            // Also try the empty password\n            germ::wallet_value data (entry_get_raw (transaction, key));\n            prv.decrypt (data.key, empty_password, salt (transaction).owords[0]);\n            germ::public_key compare;\n            ed25519_publickey (prv.data.bytes.data (), compare.bytes.data ());\n            if (compare == key)\n            {\n                // If we successfully decrypted it, rewrite the key back with the correct wallet key\n                insert_adhoc (transaction, prv);\n            }\n        }\n    }\n    version_put (transaction, 2);\n}\n\nvoid germ::wallet_store::upgrade_v2_v3 ()\n{\n    germ::transaction transaction (environment, nullptr, true);\n    assert (version (transaction) == 2);\n    germ::raw_key seed;\n    random_pool.GenerateBlock (seed.data.bytes.data (), seed.data.bytes.size ());\n    seed_set (transaction, seed);\n    entry_put_raw (transaction, germ::wallet_store::deterministic_index_special, germ::wallet_value (germ::uint256_union (0), 0));\n    version_put (transaction, 3);\n}\n\nvoid germ::kdf::phs (germ::raw_key & result_a, std::string const & password_a, germ::uint256_union const & salt_a)\n{\n    std::lock_guard<std::mutex> lock (mutex);\n    auto success (argon2_hash (1, germ::wallet_store::kdf_work, 1, password_a.data (), password_a.size (), salt_a.bytes.data (), salt_a.bytes.size (), result_a.data.bytes.data (), result_a.data.bytes.size (), NULL, 0, Argon2_d, 0x10));\n    assert (success == 0);\n    (void)success;\n}\n\ngerm::wallet::wallet (bool & init_a, germ::transaction & transaction_a, germ::node & node_a, std::string const & wallet_a) :\nlock_observer ([](bool, bool) {}),\nstore (init_a, node_a.wallets.kdf, transaction_a, node_a.config.random_representative (), node_a.config.password_fanout, wallet_a),\nnode (node_a)\n{\n}\n\ngerm::wallet::wallet (bool & init_a, germ::transaction & transaction_a, germ::node & node_a, std::string const & wallet_a, std::string const & json) :\nlock_observer ([](bool, bool) {}),\nstore (init_a, node_a.wallets.kdf, transaction_a, node_a.config.random_representative (), node_a.config.password_fanout, wallet_a, json),\nnode (node_a)\n{\n}\n\nvoid germ::wallet::enter_initial_password ()\n{\n    germ::transaction transaction (store.environment, nullptr, true);\n    std::lock_guard<std::recursive_mutex> lock (store.mutex);\n    germ::raw_key password_l;\n    store.password.value (password_l);\n    if (password_l.data.is_zero ())\n    {\n        if (valid_password ())\n        {\n            // Newly created wallets have a zero key\n            store.rekey (transaction, \"\");\n        }\n        enter_password (\"\");\n    }\n}\n\nbool germ::wallet::valid_password ()\n{\n    germ::transaction transaction (store.environment, nullptr, false);\n    auto result (store.valid_password (transaction));\n    return result;\n}\n\nbool germ::wallet::enter_password (std::string const & password_a)\n{\n    germ::transaction transaction (store.environment, nullptr, false);\n    auto result (store.attempt_password (transaction, password_a));\n    if (!result)\n    {\n        auto this_l (shared_from_this ());\n        node.background ([this_l]() {\n            this_l->search_pending ();\n        });\n    }\n    lock_observer (result, password_a.empty ());\n    return result;\n}\n\ngerm::public_key germ::wallet::deterministic_insert (MDB_txn * transaction_a, bool generate_work_a)\n{\n    germ::public_key key (0);\n    if (store.valid_password (transaction_a))\n    {\n        key = store.deterministic_insert (transaction_a);\n        if (generate_work_a)\n        {\n            work_ensure (key, key);\n        }\n    }\n    return key;\n}\n\ngerm::public_key germ::wallet::deterministic_insert (bool generate_work_a)\n{\n    germ::transaction transaction (store.environment, nullptr, true);\n    auto result (deterministic_insert (transaction, generate_work_a));\n    return result;\n}\n\ngerm::public_key germ::wallet::insert_adhoc (MDB_txn * transaction_a, germ::raw_key const & key_a, bool generate_work_a)\n{\n    germ::public_key key (0);\n    if (store.valid_password (transaction_a))\n    {\n        key = store.insert_adhoc (transaction_a, key_a);\n        if (generate_work_a)\n        {\n            work_ensure (key, node.ledger.latest_root (transaction_a, key));\n        }\n    }\n    return key;\n}\n\ngerm::public_key germ::wallet::insert_adhoc (germ::raw_key const & account_a, bool generate_work_a)\n{\n    germ::transaction transaction (store.environment, nullptr, true);\n    auto result (insert_adhoc (transaction, account_a, generate_work_a));\n    return result;\n}\n\nvoid germ::wallet::insert_watch (MDB_txn * transaction_a, germ::public_key const & pub_a)\n{\n    store.insert_watch (transaction_a, pub_a);\n}\n\nbool germ::wallet::exists (germ::public_key const & account_a)\n{\n    germ::transaction transaction (store.environment, nullptr, false);\n    return store.exists (transaction, account_a);\n}\n\nbool germ::wallet::import (std::string const & json_a, std::string const & password_a)\n{\n    auto error (false);\n    std::unique_ptr<germ::wallet_store> temp;\n    {\n        germ::transaction transaction (store.environment, nullptr, true);\n        germ::uint256_union id;\n        random_pool.GenerateBlock (id.bytes.data (), id.bytes.size ());\n        temp.reset (new germ::wallet_store (error, node.wallets.kdf, transaction, 0, 1, id.to_string (), json_a));\n    }\n    if (!error)\n    {\n        germ::transaction transaction (store.environment, nullptr, false);\n        error = temp->attempt_password (transaction, password_a);\n    }\n    germ::transaction transaction (store.environment, nullptr, true);\n    if (!error)\n    {\n        error = store.import (transaction, *temp);\n    }\n    temp->destroy (transaction);\n    return error;\n}\n\nvoid germ::wallet::serialize (std::string & json_a)\n{\n    germ::transaction transaction (store.environment, nullptr, false);\n    store.serialize_json (transaction, json_a);\n}\n\nvoid germ::wallet_store::destroy (MDB_txn * transaction_a)\n{\n    auto status (mdb_drop (transaction_a, handle, 1));\n    assert (status == 0);\n}\n\nstd::shared_ptr<germ::tx> germ::wallet::receive_action (germ::tx const & send_a, germ::account const & representative_a, germ::uint128_union const & amount_a, bool generate_work_a)\n{\n    germ::account account;\n    auto hash (send_a.hash ());\n    std::shared_ptr<germ::tx> block;\n\n    do\n    {\n        if (node.config.receive_minimum.number () > amount_a.number ())\n        {\n            BOOST_LOG (node.log) << boost::str (boost::format (\"Not receiving block %receive_action (1% due to minimum receive threshold\") % hash.to_string ());\n            // Someone sent us something below the threshold of receiving\n            break;\n        }\n\n        germ::transaction transaction (node.ledger.store.environment, nullptr, false);\n        germ::pending_info pending_info;\n        if (!node.store.block_exists (transaction, hash))\n        {\n            // Ledger doesn't have this block anymore.\n            break;\n        }\n\n        account = node.ledger.block_destination (transaction, send_a);\n        if ( !node.ledger.store.pending_get (transaction, germ::pending_key (account, hash), pending_info) )\n        {\n            // Ledger doesn't have this marked as available to receive anymore\n            break;\n        }\n\n        germ::raw_key prv;\n        if (store.fetch (transaction, account, prv))\n        {\n            BOOST_LOG (node.log) << \"Unable to receive, wallet locked\";\n            break;\n        }\n//        auto source (node.ledger.account(transaction, hash));\n        germ::account_info info;\n        auto exist_account (node.ledger.store.account_get (transaction, account, info));\n        auto latest (node.ledger.latest (transaction, account));\n        germ::tx_message tx_info(200, \"eeeeeeeee\", 40, 10);\n        if (!exist_account)\n        {\n            block.reset (new germ::tx(account,0, hash, account, germ::amount(pending_info.amount.number ()), tx_info, 0, prv, account));\n        }\n        else\n        {\n            block.reset (new germ::tx(latest,0, hash, account, germ::amount(info.balance.number () + pending_info.amount.number ()), tx_info, 0, prv, account));\n        }\n\n    } while (0);\n\n    if (block != nullptr)\n    {\n        node.process_active (block);\n        node.block_processor.flush ();\n    }\n    return block;\n}\n\nstd::shared_ptr<germ::tx> germ::wallet::change_action (germ::account const & source_a, germ::account const & representative_a, bool generate_work_a)\n{\n    std::shared_ptr<germ::tx> block;\n    {\n        germ::transaction transaction (store.environment, nullptr, false);\n        if (store.valid_password (transaction))\n        {\n            auto existing (store.find (transaction, source_a));\n            if (existing != store.end () && !node.ledger.latest (transaction, source_a).is_zero ())\n            {\n                germ::account_info info;\n                auto found (node.ledger.store.account_get (transaction, source_a, info));\n                assert (found);\n                germ::raw_key prv;\n                auto error2 (store.fetch (transaction, source_a, prv));\n                assert (!error2);\n//                uint64_t cached_work (0);\n//                store.work_get (transaction, source_a, cached_work);\n//                block.reset (new germ::state_block (source_a, info.head, /*representative_a,*/ info.balance, 0, prv, source_a, cached_work));\n\n            }\n        }\n    }\n    if (block != nullptr)\n    {\n//        if (!germ::work_validate (*block))\n//        {\n//            node.work_generate_blocking (*block);\n//        }\n        node.process_active (block);\n        node.block_processor.flush ();\n        if (generate_work_a)\n        {\n            work_ensure (source_a, block->hash ());\n        }\n    }\n    return block;\n}\n\nstd::shared_ptr<germ::tx> germ::wallet::send_action (germ::account const & source_a, germ::account const & account_a, germ::uint128_t const & amount_a, bool generate_work_a, boost::optional<std::string> id_a)\n{\n    std::shared_ptr<germ::tx> block;\n    boost::optional<germ::mdb_val> id_mdb_val;\n    if (id_a)\n    {\n        id_mdb_val = germ::mdb_val (id_a->size (), const_cast<char *> (id_a->data ()));\n    }\n    bool error = false;\n    bool cached_block = false;\n    {\n        germ::transaction transaction (store.environment, nullptr, (bool)id_mdb_val);\n        if (id_mdb_val)\n        {\n            germ::mdb_val result;\n            auto status (mdb_get (transaction, node.wallets.send_action_ids, *id_mdb_val, result));\n            if (status == 0)\n            {\n                auto hash (result.uint256 ());\n                block = node.store.block_get (transaction, hash);\n                if (block != nullptr)\n                {\n                    cached_block = true;\n                    node.network.republish_block (transaction, block);\n                }\n            }\n            else if (status != MDB_NOTFOUND)\n            {\n                error = true;\n            }\n        }\n\n        do\n        {\n            if (error || block != nullptr)\n                break;\n\n            if (!store.valid_password (transaction))\n                break;\n\n            auto existing (store.find (transaction, source_a));\n            if (existing == store.end ())\n                break;\n\n            auto balance (node.ledger.account_balance (transaction, source_a));\n            if (balance.is_zero () || balance < amount_a)\n                break;\n\n            germ::account_info info;\n            auto found (node.ledger.store.account_get (transaction, source_a, info));\n            assert (found);\n            germ::raw_key prv;\n            auto error2 (store.fetch (transaction, source_a, prv));\n            assert (!error2);\n//            std::shared_ptr<germ::tx> rep_block = node.ledger.store.block_get (transaction, info.rep_block);\n//            assert (rep_block != nullptr);\n//            uint64_t cached_work (0);\n//            store.work_get (transaction, source_a, cached_work);\n//            block.reset (new germ::state_block (source_a, info.head, rep_block->representative (), balance - amount_a, account_a, prv, source_a, cached_work))\n\n            auto latest (node.ledger.latest (transaction, source_a));\n            if ( !latest.is_zero() )\n            {\n                germ::tx_message tx_info(200, \"eeeeeeeee\", 40, 10);\n                block.reset (new germ::tx(latest,account_a, source_a, source_a, germ::amount(balance-amount_a), tx_info, 0, prv, source_a));\n            }\n\n//            std::vector<uint8_t > buffer;\n//            {\n//                germ::vectorstream stream(buffer);\n//                block->serialize(stream);\n//            }\n//            std::cout << block->hash().to_string() << \"   \" << buffer.size() << std::endl;\n//\n//            bool isOk = false;\n//            germ::bufferstream stream1 (buffer.data(), buffer.size());\n//            auto t = new germ::tx(isOk, stream1);\n//            std::cout << t->hash().to_string() << std::endl;\n\n            if (id_mdb_val)\n            {\n                auto status (mdb_put (transaction, node.wallets.send_action_ids, *id_mdb_val, germ::mdb_val (block->hash ()), 0));\n                if (status != 0)\n                {\n                    block = nullptr;\n                    error = true;\n                }\n            }\n\n        }while (0);\n    }\n    if (!error && block != nullptr && !cached_block)\n    {\n//        if (!germ::work_validate (*block))\n//        {\n//            node.work_generate_blocking (*block);\n//        }\n        node.process_active (block);\n        node.block_processor.flush ();\n        if (generate_work_a)\n        {\n            work_ensure (source_a, block->hash ());\n        }\n    }\n    return block;\n}\n\nbool germ::wallet::change_sync (germ::account const & source_a, germ::account const & representative_a)\n{\n    std::promise<bool> result;\n    change_async (source_a, representative_a, [&result](std::shared_ptr<germ::tx> block_a) {\n        result.set_value (block_a == nullptr);\n    },\n    true);\n    return result.get_future ().get ();\n}\n\nvoid germ::wallet::change_async (germ::account const & source_a, germ::account const & representative_a, std::function<void(std::shared_ptr<germ::tx>)> const & action_a, bool generate_work_a)\n{\n    node.wallets.queue_wallet_action (germ::wallets::high_priority, [this, source_a, representative_a, action_a, generate_work_a]() {\n        auto block (change_action (source_a, representative_a, generate_work_a));\n        action_a (block);\n    });\n}\n\nbool germ::wallet::receive_sync (std::shared_ptr<germ::tx> block_a, germ::account const & representative_a, germ::uint128_t const & amount_a)\n{\n    std::promise<bool> result;\n    receive_async (block_a, representative_a, amount_a, [&result](std::shared_ptr<germ::tx> block_a) {\n        result.set_value (block_a == nullptr);\n    },\n    true);\n    return result.get_future ().get ();\n}\n\nvoid germ::wallet::receive_async (std::shared_ptr<germ::tx> block_a, germ::account const & representative_a, germ::uint128_t const & amount_a, std::function<void(std::shared_ptr<germ::tx>)> const & action_a, bool generate_work_a)\n{\n    //assert (dynamic_cast<germ::send_block *> (block_a.get ()) != nullptr);\n    node.wallets.queue_wallet_action (amount_a, [this, block_a, representative_a, amount_a, action_a, generate_work_a]() {\n        auto block (receive_action (*static_cast<germ::tx *> (block_a.get ()), representative_a, amount_a, generate_work_a));\n        action_a (block);\n    });\n}\n\ngerm::block_hash germ::wallet::send_sync (germ::account const & source_a, germ::account const & account_a, germ::uint128_t const & amount_a)\n{\n    std::promise<germ::block_hash> result;\n    send_async (source_a, account_a, amount_a, [&result](std::shared_ptr<germ::tx> block_a) {\n        result.set_value (block_a->hash ());\n    },\n    true);\n    return result.get_future ().get ();\n}\n\nvoid germ::wallet::send_async (germ::account const & source_a, germ::account const & account_a, germ::uint128_t const & amount_a, std::function<void(std::shared_ptr<germ::tx>)> const & action_a, bool generate_work_a, boost::optional<std::string> id_a)\n{\n    this->node.wallets.queue_wallet_action (germ::wallets::high_priority, [this, source_a, account_a, amount_a, action_a, generate_work_a, id_a]() {\n        auto block (send_action (source_a, account_a, amount_a, generate_work_a, id_a));\n        action_a (block);\n    });\n}\n\n// Update work for account if latest root is root_a\nvoid germ::wallet::work_update (MDB_txn * transaction_a, germ::account const & account_a, germ::block_hash const & root_a, uint64_t work_a)\n{\n    assert (germ::work_validate (root_a, work_a));\n    assert (store.exists (transaction_a, account_a));\n    auto latest (node.ledger.latest_root (transaction_a, account_a));\n    if (latest == root_a)\n    {\n        store.work_put (transaction_a, account_a, work_a);\n    }\n    else\n    {\n        BOOST_LOG (node.log) << \"Cached work no longer valid, discarding\";\n    }\n}\n\nvoid germ::wallet::work_ensure (germ::account const & account_a, germ::block_hash const & hash_a)\n{\n    auto this_l (shared_from_this ());\n    node.wallets.queue_wallet_action (germ::wallets::generate_priority, [this_l, account_a, hash_a] {\n        this_l->work_cache_blocking (account_a, hash_a);\n    });\n}\n\nbool germ::wallet::search_pending ()\n{\n    germ::transaction transaction (store.environment, nullptr, false);\n    auto result (!store.valid_password (transaction));\n    if (result)\n    {\n        BOOST_LOG (node.log) << \"Stopping search, wallet is locked\";\n        return result;\n    }\n\n    BOOST_LOG (node.log) << \"Beginning pending block search\";\n    germ::transaction transaction_pend (node.store.environment, nullptr, false);\n    for (auto i (store.begin (transaction_pend)), n (store.end ()); i != n; ++i)\n    {\n        germ::account account (i->first.uint256 ());\n        // Don't search pending for watch-only accounts\n        if (germ::wallet_value (i->second).key.is_zero ())\n            continue;\n\n        for (auto j (node.store.pending_begin (transaction_pend, germ::pending_key (account, 0))), m (node.store.pending_begin (transaction_pend, germ::pending_key (account.number () + 1, 0))); j != m; ++j)\n        {\n            germ::pending_key key (j->first);\n            auto hash (key.hash);\n            germ::pending_info pending (j->second);\n            auto amount (pending.amount.number ());\n            if (node.config.receive_minimum.number () <= amount)\n            {\n                BOOST_LOG (node.log) << boost::str (boost::format (\"Found a pending block %1% for account %2%\") % hash.to_string () % pending.source.to_account ());\n                node.block_confirm (node.store.block_get (transaction_pend, hash));\n            }\n        }\n    }\n    BOOST_LOG (node.log) << \"Pending block search phase complete\";\n    return result;\n}\n\nvoid germ::wallet::init_free_accounts (MDB_txn * transaction_a)\n{\n    free_accounts.clear ();\n    for (auto i (store.begin (transaction_a)), n (store.end ()); i != n; ++i)\n    {\n        free_accounts.insert (i->first.uint256 ());\n    }\n}\n\ngerm::public_key germ::wallet::change_seed (MDB_txn * transaction_a, germ::raw_key const & prv_a)\n{\n    store.seed_set (transaction_a, prv_a);\n    auto account = deterministic_insert (transaction_a);\n    uint32_t count (0);\n    for (uint32_t i (1), n (64); i < n; ++i)\n    {\n        germ::raw_key prv;\n        store.deterministic_key (prv, transaction_a, i);\n        germ::keypair pair (prv.data.to_string ());\n        // Check if account received at least 1 block\n        auto latest (node.ledger.latest (transaction_a, pair.pub));\n        if (!latest.is_zero ())\n        {\n            count = i;\n            // i + 64 - Check additional 64 accounts\n            // i/64 - Check additional accounts for large wallets. I.e. 64000/64 = 1000 accounts to check\n            n = i + 64 + (i / 64);\n        }\n        else\n        {\n            // Check if there are pending blocks for account\n            germ::account end (pair.pub.number () + 1);\n            for (auto ii (node.store.pending_begin (transaction_a, germ::pending_key (pair.pub, 0))), nn (node.store.pending_begin (transaction_a, germ::pending_key (end, 0))); ii != nn; ++ii)\n            {\n                count = i;\n                n = i + 64 + (i / 64);\n                break;\n            }\n        }\n    }\n    for (uint32_t i (0); i < count; ++i)\n    {\n        // Generate work for first 4 accounts only to prevent weak CPU nodes stuck\n        account = deterministic_insert (transaction_a, i < 4);\n    }\n\n    return account;\n}\n\nvoid germ::wallet::work_cache_blocking (germ::account const & account_a, germ::block_hash const & root_a)\n{\n    auto begin (std::chrono::steady_clock::now ());\n    auto work (node.work_generate_blocking (root_a));\n    if (node.config.logging.work_generation_time ())\n    {\n        BOOST_LOG (node.log) << \"Work generation complete: \" << (std::chrono::duration_cast<std::chrono::microseconds> (std::chrono::steady_clock::now () - begin).count ()) << \" us\";\n    }\n    germ::transaction transaction (store.environment, nullptr, true);\n    if (store.exists (transaction, account_a))\n    {\n        work_update (transaction, account_a, root_a, work);\n    }\n}\n\ngerm::wallets::wallets (bool & error_a, germ::node & node_a) :\nobserver ([](bool) {}),\nnode (node_a),\nstopped (false),\nthread ([this]() { do_wallet_actions (); })\n{\n    if (error_a)\n        return ;\n\n    germ::transaction transaction (node.store.environment, nullptr, true);\n    auto status (mdb_dbi_open (transaction, nullptr, MDB_CREATE, &handle));\n    status |= mdb_dbi_open (transaction, \"send_action_ids\", MDB_CREATE, &send_action_ids);\n    assert (status == 0);\n    std::string beginning (germ::uint256_union (0).to_string ());\n    std::string end ((germ::uint256_union (germ::uint256_t (0) - germ::uint256_t (1))).to_string ());\n    for (germ::store_iterator i (transaction, handle, germ::mdb_val (beginning.size (), const_cast<char *> (beginning.c_str ()))), n (transaction, handle, germ::mdb_val (end.size (), const_cast<char *> (end.c_str ()))); i != n; ++i)\n    {\n        germ::uint256_union id;\n        std::string text (reinterpret_cast<char const *> (i->first.data ()), i->first.size ());\n        auto error (id.decode_hex (text));\n        assert (!error);\n        assert (items.find (id) == items.end ());\n        auto wallet (std::make_shared<germ::wallet> (error, transaction, node_a, text));\n        if (!error)\n        {\n            node_a.background ([wallet]() {\n                wallet->enter_initial_password ();\n            });\n            items[id] = wallet;\n        }\n        else\n        {\n            // Couldn't open wallet\n        }\n    }\n}\n\ngerm::wallets::~wallets ()\n{\n    stop ();\n}\n\nstd::shared_ptr<germ::wallet> germ::wallets::open (germ::uint256_union const & id_a)\n{\n    std::shared_ptr<germ::wallet> result;\n    auto existing (items.find (id_a));\n    if (existing != items.end ())\n    {\n        result = existing->second;\n    }\n    return result;\n}\n\nstd::shared_ptr<germ::wallet> germ::wallets::create (germ::uint256_union const & id_a)\n{\n    assert (items.find (id_a) == items.end ());\n    std::shared_ptr<germ::wallet> result;\n    bool error;\n    {\n        germ::transaction transaction (node.store.environment, nullptr, true);\n        result = std::make_shared<germ::wallet> (error, transaction, node, id_a.to_string ());\n    }\n    if (!error)\n    {\n        items[id_a] = result;\n        node.background ([result]() {\n            result->enter_initial_password ();\n        });\n    }\n    return result;\n}\n\nbool germ::wallets::search_pending (germ::uint256_union const & wallet_a)\n{\n    auto result (false);\n    auto existing (items.find (wallet_a));\n    result = existing == items.end ();\n    if (!result)\n    {\n        auto wallet (existing->second);\n        result = wallet->search_pending ();\n    }\n    return result;\n}\n\nvoid germ::wallets::search_pending_all ()\n{\n    for (auto i : items)\n    {\n        i.second->search_pending ();\n    }\n}\n\nvoid germ::wallets::destroy (germ::uint256_union const & id_a)\n{\n    germ::transaction transaction (node.store.environment, nullptr, true);\n    auto existing (items.find (id_a));\n    assert (existing != items.end ());\n    auto wallet (existing->second);\n    items.erase (existing);\n    wallet->store.destroy (transaction);\n}\n\nvoid germ::wallets::do_wallet_actions ()\n{\n    std::unique_lock<std::mutex> lock (mutex);\n    while (!stopped)\n    {\n        if (!actions.empty ())\n        {\n            auto first (actions.begin ());\n            auto current (std::move (first->second));\n            actions.erase (first);\n            lock.unlock ();\n            observer (true);\n            current ();\n            observer (false);\n            lock.lock ();\n        }\n        else\n        {\n            condition.wait (lock);\n        }\n    }\n}\n\nvoid germ::wallets::queue_wallet_action (germ::uint128_t const & amount_a, std::function<void()> const & action_a)\n{\n    std::lock_guard<std::mutex> lock (mutex);\n    actions.insert (std::make_pair (amount_a, std::move (action_a)));\n    condition.notify_all ();\n}\n\nvoid germ::wallets::foreach_representative (MDB_txn * transaction_a, std::function<void(germ::public_key const & pub_a, germ::raw_key const & prv_a)> const & action_a)\n{\n    for (auto i (items.begin ()), n (items.end ()); i != n; ++i)\n    {\n        auto & wallet (*i->second);\n        for (auto j (wallet.store.begin (transaction_a)), m (wallet.store.end ()); j != m; ++j)\n        {\n            germ::account account (j->first.uint256 ());\n            if (node.ledger.weight (transaction_a, account).is_zero ())\n                continue;\n\n            if (wallet.store.valid_password (transaction_a))\n            {\n                germ::raw_key prv;\n                auto error (wallet.store.fetch (transaction_a, j->first.uint256 (), prv));\n                assert (!error);\n                action_a (j->first.uint256 (), prv);\n            }\n            else\n            {\n                static auto last_log = std::chrono::steady_clock::time_point ();\n                if (last_log < std::chrono::steady_clock::now () - std::chrono::seconds (60))\n                {\n                    last_log = std::chrono::steady_clock::now ();\n                    BOOST_LOG (node.log) << boost::str (boost::format (\"Representative locked inside wallet %1%\") % i->first.to_string ());\n                }\n            }\n        }\n    }\n}\n\nbool germ::wallets::exists (MDB_txn * transaction_a, germ::public_key const & account_a)\n{\n    auto result (false);\n    for (auto i (items.begin ()), n (items.end ()); !result && i != n; ++i)\n    {\n        result = i->second->store.exists (transaction_a, account_a);\n    }\n    return result;\n}\n\nvoid germ::wallets::stop ()\n{\n    {\n        std::lock_guard<std::mutex> lock (mutex);\n        stopped = true;\n        condition.notify_all ();\n    }\n    if (thread.joinable ())\n    {\n        thread.join ();\n    }\n}\n\ngerm::uint128_t const germ::wallets::generate_priority = std::numeric_limits<germ::uint128_t>::max ();\ngerm::uint128_t const germ::wallets::high_priority = std::numeric_limits<germ::uint128_t>::max () - 1;\n\ngerm::store_iterator germ::wallet_store::begin (MDB_txn * transaction_a)\n{\n    germ::store_iterator result (transaction_a, handle, germ::mdb_val (germ::uint256_union (special_count)));\n    return result;\n}\n\ngerm::store_iterator germ::wallet_store::begin (MDB_txn * transaction_a, germ::uint256_union const & key)\n{\n    germ::store_iterator result (transaction_a, handle, germ::mdb_val (key));\n    return result;\n}\n\ngerm::store_iterator germ::wallet_store::find (MDB_txn * transaction_a, germ::uint256_union const & key)\n{\n    auto result (begin (transaction_a, key));\n    germ::store_iterator end (nullptr);\n    if (result == end)\n        return end;\n\n    if (germ::uint256_union (result->first.uint256 ()) == key)\n    {\n        return result;\n    }\n    else\n    {\n        return end;\n    }\n\n    return result;\n}\n\ngerm::store_iterator germ::wallet_store::end ()\n{\n    return germ::store_iterator (nullptr);\n}\n", "meta": {"hexsha": "fed246a125edb95fdc16832553aff82dd68c1f78", "size": 51233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/node/wallet.cpp", "max_stars_repo_name": "mar348/village", "max_stars_repo_head_hexsha": "fecc81b19018b1e9bf48c352696325869a2847a2", "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/node/wallet.cpp", "max_issues_repo_name": "mar348/village", "max_issues_repo_head_hexsha": "fecc81b19018b1e9bf48c352696325869a2847a2", "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/node/wallet.cpp", "max_forks_repo_name": "mar348/village", "max_forks_repo_head_hexsha": "fecc81b19018b1e9bf48c352696325869a2847a2", "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": 34.971331058, "max_line_length": 251, "alphanum_fraction": 0.6280912693, "num_tokens": 12519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.30074557267388247, "lm_q1q2_score": 0.18275200800421967}}
{"text": "#include \"TSRGoal.h\"\n#include \"RobotStateSpace.h\"\n\n#include <boost/foreach.hpp>\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n#include <ompl/util/RandomNumbers.h>\n\nusing namespace or_ompl;\nnamespace ob = ompl::base;\n\nTSRGoal::TSRGoal(const ob::SpaceInformationPtr &si,\n\t\t\t\t const TSR::Ptr &tsr, \n\t\t\t\t OpenRAVE::RobotBasePtr robot)\n    : ob::GoalSampleableRegion(si),  _robot(robot){\n    \n\tstd::vector<TSR::Ptr> tsrs(1);\n\ttsrs.push_back(tsr);\n\tTSRChain::Ptr tsrchain = boost::make_shared<TSRChain>(true, false, false, tsrs);\n\t_tsr_chains.push_back(tsrchain);\n}\n\nTSRGoal::TSRGoal(const ob::SpaceInformationPtr &si,\n\t\t\t\t const TSRChain::Ptr &tsrchain, \n\t\t\t\t OpenRAVE::RobotBasePtr robot)\n    : ob::GoalSampleableRegion(si), _robot(robot){\n\n\t_tsr_chains.push_back(tsrchain);\n}\n\nTSRGoal::TSRGoal(const ob::SpaceInformationPtr &si,\n\t\t\t\t const std::vector<TSRChain::Ptr> &tsrchains, \n\t\t\t\t OpenRAVE::RobotBasePtr robot)\n    : ob::GoalSampleableRegion(si), _tsr_chains(tsrchains), _robot(robot){\n    \n}\n\nTSRGoal::~TSRGoal() {\n    \n}\n\nbool TSRGoal::isSatisfied(const ompl::base::State *state) const {\n\n    bool satisfied = (distanceGoal(state) == 0.0);\n\treturn satisfied;\n}\n            \ndouble TSRGoal::distanceGoal(const ompl::base::State *state) const {\n\n\t// Save the state of the robot\n    OpenRAVE::EnvironmentMutex::scoped_lock lockenv(_robot->GetEnv()->GetMutex());\n\tOpenRAVE::KinBody::KinBodyStateSaver rsaver(_robot);\n\n    OpenRAVE::RobotBase::ManipulatorPtr active_manip = _robot->GetActiveManipulator();\n\n\t// Put the robot in the pose that is represented in the state\n\tconst RobotState* mstate = state->as<RobotState>();\n    unsigned int check_limits = 0; // The planner does this\n    _robot->SetDOFValues(mstate->getValues(), check_limits, mstate->getIndices());\n\n\t// Get the end effector transform\n\tOpenRAVE::Transform or_tf = active_manip->GetEndEffectorTransform();\n    OpenRAVE::TransformMatrix or_matrix(or_tf);\n\t\n\t// Convert to Eigen\n    Eigen::Affine3d ee_pose = Eigen::Affine3d::Identity();\n    ee_pose.linear() << or_matrix.m[0], or_matrix.m[1], or_matrix.m[2],\n        or_matrix.m[4], or_matrix.m[5], or_matrix.m[6],\n        or_matrix.m[8], or_matrix.m[9], or_matrix.m[10];\n    ee_pose.translation() << or_matrix.trans.x, or_matrix.trans.y, or_matrix.trans.z;\n\n\t// Get distance to TSR\n\tdouble distance = std::numeric_limits<double>::infinity();\n\tBOOST_FOREACH(TSRChain::Ptr tsrchain, _tsr_chains){\n\t\tEigen::Matrix<double, 6, 1> ee_distance = tsrchain->distance(ee_pose);\n\t\tdouble tdistance = ee_distance.norm();\n\t\tif(tdistance < distance){\n\t\t\tdistance = tdistance;\n\t\t}\n\t}\n\n\t// Reset the state of the robot\n\trsaver.Restore();\n\n\treturn distance;\n}\n            \nvoid TSRGoal::sampleGoal(ompl::base::State *state) const {\n\n\tbool success = false;\n\n\t// TODO: Figure out how to bail correctly if an IK isn't found\n\tfor(unsigned int count=0; count < 20 && !success; count++){\n\t\t// Pick a TSR to sample\n\t\tint idx = 0;\n\t\tif(_tsr_chains.size() > 1){\n\t\t\tompl::RNG rng;\n\t\t\tidx = rng.uniformInt(0, _tsr_chains.size()-1);\n\t\t}\n\n\t\t// Sample the TSR\n\t\tEigen::Affine3d ee_pose = _tsr_chains[idx]->sample();\n\n\t\t// Find an associated IK\n\t\tOpenRAVE::TransformMatrix or_matrix;\n\t\tor_matrix.rotfrommat(\n\t\t\tee_pose.matrix()(0, 0), ee_pose.matrix()(0, 1), ee_pose.matrix()(0, 2),\n\t\t\tee_pose.matrix()(1, 0), ee_pose.matrix()(1, 1), ee_pose.matrix()(1, 2),\n\t\t\tee_pose.matrix()(2, 0), ee_pose.matrix()(2, 1), ee_pose.matrix()(2, 2)\n\t\t\t);\n\t\tor_matrix.trans.x = ee_pose(0, 3);\n\t\tor_matrix.trans.y = ee_pose(1, 3);\n\t\tor_matrix.trans.z = ee_pose(2, 3);\n\n\t\tOpenRAVE::IkParameterization ik_param(or_matrix, OpenRAVE::IKP_Transform6D);\n\t\tstd::vector<OpenRAVE::dReal> ik_solution;\n\t\tsuccess = _robot->GetActiveManipulator()->FindIKSolution(ik_param, ik_solution, OpenRAVE::IKFO_CheckEnvCollisions);\n\n\t\t// Set the state\n\t\tif(success){\n\n\t\t\tconst RobotState* mstate = state->as<RobotState>();\n\n            std::vector<int> arm_indices = _robot->GetActiveManipulator()->GetArmIndices();\n            std::vector<int> state_indices = mstate->getIndices();\n\t\t\tfor(unsigned int idx=0; idx < ik_solution.size(); idx++){\n\n                unsigned int sidx = std::find(state_indices.begin(),\n                                              state_indices.end(),\n                                              arm_indices[idx]) - state_indices.begin();\n\n\t\t\t\tmstate->values[sidx] = ik_solution[idx];\n\t\t\t}\n\t\t}\n\t}\n\n\tif(!success){\n\t\tRAVELOG_ERROR(\"[TSRGoal] Failed to sample valid goal.\\n\");\n        const RobotState* mstate = state->as<RobotState>();\n        mstate->values[0] = std::numeric_limits<double>::quiet_NaN();\n\t}\n}\n\nunsigned int TSRGoal::maxSampleCount() const {\n\n    return std::numeric_limits<unsigned int>::max();\n}\n", "meta": {"hexsha": "7b96ccad5fdb1de4ae99fedb5ce4723545a76d3b", "size": 4690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TSRGoal.cpp", "max_stars_repo_name": "DavidB-CMU/or_ompl", "max_stars_repo_head_hexsha": "ebdc809a48bf2d3adc0c723967eb42bc36fd3acd", "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/TSRGoal.cpp", "max_issues_repo_name": "DavidB-CMU/or_ompl", "max_issues_repo_head_hexsha": "ebdc809a48bf2d3adc0c723967eb42bc36fd3acd", "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/TSRGoal.cpp", "max_forks_repo_name": "DavidB-CMU/or_ompl", "max_forks_repo_head_hexsha": "ebdc809a48bf2d3adc0c723967eb42bc36fd3acd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-19T13:23:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-19T13:23:06.000Z", "avg_line_length": 31.9047619048, "max_line_length": 117, "alphanum_fraction": 0.6771855011, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.18248937999302084}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python/def.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/python/return_internal_reference.hpp>\n#include <boost/python/return_by_value.hpp>\n#include <scitbx/array_family/boost_python/shared_wrapper.h>\n#include <cctbx/adp_restraints/isotropic_adp.h>\n#include <scitbx/boost_python/container_conversions.h>\n\n\nnamespace cctbx { namespace adp_restraints {\n\nnamespace {\n\n\n  struct isotropic_adp_proxy_wrappers\n  {\n    typedef isotropic_adp_proxy w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      typedef return_value_policy<return_by_value> rbv;\n      class_<w_t, bases<adp_restraint_proxy<1> > >\n        (\"isotropic_adp_proxy\", no_init)\n        .def(init<\n           af::tiny<unsigned, 1> const &,\n           double>(\n          (arg(\"i_seqs\"),\n           arg(\"weight\"))))\n      ;\n      {\n        scitbx::af::boost_python::shared_wrapper<w_t>::wrap(\n          \"shared_isotropic_adp_proxy\")\n        ;\n      }\n    }\n  };\n\n  struct isotropic_adp_wrappers\n  {\n    typedef isotropic_adp w_t;\n\n    static void\n    wrap() {\n      using namespace boost::python;\n      typedef return_value_policy<return_by_value> rbv;\n      class_<w_t, bases<adp_restraint_base_6<1> > >\n            (\"isotropic_adp\", no_init)\n        .def(init<\n            scitbx::sym_mat3<double> const &,\n            double>(\n          (arg(\"u_cart\"),\n           arg(\"weight\"))))\n        .def(init<\n            adp_restraint_params<double> const &,\n            isotropic_adp_proxy const &>(\n          (arg(\"params\"),\n           arg(\"proxy\"))))\n      ;\n    }\n  };\n\n  void wrap_all() {\n    using namespace boost::python;\n    isotropic_adp_wrappers::wrap();\n    isotropic_adp_proxy_wrappers::wrap();\n  }\n\n}\n\nnamespace boost_python {\n\n  void\n  wrap_isotropic_adp() { wrap_all(); }\n\n}}}\n", "meta": {"hexsha": "bacc07ca96a373a6f1dbffbba9e88b9751b0d8e3", "size": 1965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/adp_restraints/isotropic_adp_bpl.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": "cctbx/adp_restraints/isotropic_adp_bpl.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": "cctbx/adp_restraints/isotropic_adp_bpl.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": 23.6746987952, "max_line_length": 60, "alphanum_fraction": 0.6361323155, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.1824893799930208}}
{"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_OPT_CMAES_HPP\n#define LIMBO_OPT_CMAES_HPP\n\n#include <Eigen/Core>\n#include <iostream>\n#include <vector>\n\n#include <limbo/opt/optimizer.hpp>\n#include <limbo/tools/macros.hpp>\n#include <limbo/tools/parallel.hpp>\n\n#ifndef USE_LIBCMAES\n#warning NO libcmaes support\n#else\n\n#include <libcmaes/cmaes.h>\n\nnamespace limbo {\n    namespace defaults {\n        struct opt_cmaes {\n            /// @ingroup opt_defaults\n            /// number of restarts of CMA-ES\n            BO_PARAM(int, restarts, 1);\n            /// @ingroup opt_defaults\n            /// maximum number of calls to the function to be optimized\n            BO_PARAM(int, max_fun_evals, -1);\n            /// @ingroup opt_defaults\n            /// maximum number of iterations to be optimized\n            BO_PARAM(int, max_iters, -1);\n            /// @ingroup opt_defaults\n            /// enable/disable automatic max iterations\n            BO_PARAM(bool, auto_max_iters, true);\n            /// @ingroup opt_defaults\n            /// enable/disable stopping if getting the same function value repeatedly\n            BO_PARAM(bool, equal_fun_evals, true);\n            /// @ingroup opt_defaults\n            BO_PARAM(bool, stagnation, true);\n            /// @ingroup opt_defaults\n            /// threshold based on the difference in value of a fixed number\n            /// of trials: if bigger than 0, it enables the tolerance criteria\n            /// for stopping based in the history of rewards.\n            BO_PARAM(double, fun_tolerance, -1);\n            /// @ingroup opt_defaults\n            /// tolerance for convergence: stop when an optimization step (or an\n            /// estimate of the optimum) changes all the parameter values by\n            /// less than tol multiplied by the absolute value of the parameter\n            /// value.\n            /// IGNORED if negative\n            BO_PARAM(double, xrel_tolerance, -1);\n            /// @ingroup opt_defaults\n            /// function value target: if bigger than 0, enables the function\n            /// target criteria for stopping if the performance is greater than this value.\n            BO_PARAM(double, fun_target, -1);\n            /// @ingroup opt_defaults\n            /// computes initial objective function value: if true, it evaluates the\n            /// provided starting point (if any).\n            BO_PARAM(bool, fun_compute_initial, false);\n            /// @ingroup opt_defaults\n            /// sets the version of cmaes to use (possible values are: CMAES_DEFAULT, IPOP_CMAES, BIPOP_CMAES, aCMAES, aIPOP_CMAES, aBIPOP_CMAES, sepCMAES, sepIPOP_CMAES, sepBIPOP_CMAES, sepaCMAES, sepaIPOP_CMAES, sepaBIPOP_CMAES, VD_CMAES, VD_IPOP_CMAES, VD_BIPOP_CMAES\n            BO_PARAM(int, variant, aIPOP_CMAES);\n            /// @ingroup opt_defaults\n            /// defines elitism strategy:\n            /// 0 -> no elitism\n            /// 1 -> elitism: reinjects the best-ever seen solution\n            /// 2 -> initial elitism: reinject x0 as long as it is not improved upon\n            /// 3 -> initial elitism on restart: restart if best encountered solution is not the the final\n            /// solution and reinjects the best solution until the population has better fitness, in its majority\n            BO_PARAM(int, elitism, 0);\n            /// @ingroup opt_defaults\n            /// enables or disables uncertainty handling: https://hal.inria.fr/file/index/docid/276216/filename/TEC2008.pdf\n            BO_PARAM(bool, handle_uncertainty, false);\n            /// @ingroup opt_defaults\n            /// enables or disables verbose mode for cmaes\n            BO_PARAM(bool, verbose, false);\n            /// @ingroup opt_defaults\n            /// lower bound (in input) for cmaes\n            BO_PARAM(double, lbound, 0.0);\n            /// @ingroup opt_defaults\n            /// upper bound (in input) for cmaes\n            BO_PARAM(double, ubound, 1.0);\n            /// @ingroup opt_defaults\n            /// if stochastic, the mean of the\n            /// last distribution is returned\n            /// otherwise, the best ever candidate\n            /// is returned. If handle_uncertainty is on,\n            /// this is also enabled.\n            BO_PARAM(bool, stochastic, false);\n            /// @ingroup opt_defaults\n            /// number of parent population\n            /// -1 to automatically determine\n            BO_PARAM(int, lambda, -1);\n        };\n    } // namespace defaults\n\n    namespace opt {\n        /// @ingroup opt\n        /// Covariance Matrix Adaptation Evolution Strategy by Hansen et al.\n        /// (See: https://www.lri.fr/~hansen/cmaesintro.html)\n        /// - our implementation is based on libcmaes (https://github.com/beniz/libcmaes)\n        /// - Support bounded and unbounded optimization\n        /// - Only available if libcmaes is installed (see the compilation instructions)\n        ///\n        /// - Parameters :\n        ///   - int variant\n        ///   - int elitism\n        ///   - int restarts\n        ///   - int max_fun_evals\n        ///   - int max_iters\n        ///   - bool auto_max_iters\n        ///   - bool equal_fun_evals\n        ///   - bool stagnation\n        ///   - double fun_tolerance\n        ///   - double xrel_tolerance\n        ///   - double fun_target\n        ///   - bool fun_compute_initial\n        ///   - bool handle_uncertainty\n        ///   - bool verbose\n        ///   - double lb (lower bounds)\n        ///   - double ub (upper bounds)\n        ///   - bool stochastic\n        ///   - int lambda\n        template <typename Params>\n        struct Cmaes {\n        public:\n            using ProgressFunction = std::function<void(const libcmaes::CMASolutions&)>;\n            using ProgressFunctionUnbounded = std::function<int(const libcmaes::CMAParameters<libcmaes::GenoPheno<libcmaes::NoBoundStrategy>>&, const libcmaes::CMASolutions&)>;\n            using ProgressFunctionBounded = std::function<int(const libcmaes::CMAParameters<libcmaes::GenoPheno<libcmaes::pwqBoundStrategy>>&, const libcmaes::CMASolutions&)>;\n\n            template <typename F>\n            Eigen::VectorXd operator()(const F& f, const Eigen::VectorXd& init, double bounded) const\n            {\n                size_t dim = init.size();\n\n                // wrap the function\n                libcmaes::FitFunc f_cmaes = [&](const double* x, const int n) {\n                    Eigen::Map<const Eigen::VectorXd> m(x, n);\n                    // remember that our optimizers maximize\n                    return -eval(f, m);\n                };\n\n                if (bounded)\n                    return _opt_bounded(f_cmaes, dim, init);\n                else\n                    return _opt_unbounded(f_cmaes, dim, init);\n            }\n\n            void set_progress_function(const ProgressFunction& pfunc) { _pfunc = pfunc; }\n            void set_unbounded_progress_function(const ProgressFunctionUnbounded& pfunc) { _pfunc_unbounded = pfunc; }\n            void set_bounded_progress_function(const ProgressFunctionBounded& pfunc) { _pfunc_bounded = pfunc; }\n\n        private:\n            ProgressFunction _pfunc;\n            ProgressFunctionUnbounded _pfunc_unbounded;\n            ProgressFunctionBounded _pfunc_bounded;\n\n            // F is a CMA-ES style function, not our function\n            template <typename F>\n            Eigen::VectorXd _opt_unbounded(F& f_cmaes, int dim, const Eigen::VectorXd& init) const\n            {\n                using namespace libcmaes;\n                // initial step-size, i.e. estimated initial parameter error.\n                double sigma = 0.5;\n                std::vector<double> x0(init.data(), init.data() + init.size());\n\n                CMAParameters<> cmaparams(x0, sigma, Params::opt_cmaes::lambda());\n                _set_common_params(cmaparams, dim);\n\n                auto pfunc = CMAStrategy<CovarianceUpdate, GenoPheno<NoBoundStrategy>>::_defaultPFunc;\n                if (_pfunc_unbounded) {\n                    pfunc = _pfunc_unbounded;\n                }\n                else if (_pfunc) {\n                    pfunc = [this](const CMAParameters<GenoPheno<NoBoundStrategy>>& params, const CMASolutions& sols) { _pfunc(sols); return 0; };\n                }\n\n                // the optimization itself\n                CMASolutions cmasols = cmaes<>(f_cmaes, cmaparams, pfunc);\n                if (Params::opt_cmaes::stochastic() || Params::opt_cmaes::handle_uncertainty())\n                    return cmasols.xmean();\n\n                return cmasols.get_best_seen_candidate().get_x_dvec();\n            }\n\n            // F is a CMA-ES style function, not our function\n            template <typename F>\n            Eigen::VectorXd _opt_bounded(F& f_cmaes, int dim, const Eigen::VectorXd& init) const\n            {\n                using namespace libcmaes;\n                // create the parameter object\n                // boundary_transformation\n                double lbounds[dim], ubounds[dim]; // arrays for lower and upper parameter bounds, respectively\n                for (int i = 0; i < dim; i++) {\n                    lbounds[i] = Params::opt_cmaes::lbound();\n                    ubounds[i] = Params::opt_cmaes::ubound();\n                }\n                GenoPheno<pwqBoundStrategy> gp(lbounds, ubounds, dim);\n                // initial step-size, i.e. estimated initial parameter error.\n                double sigma = 0.5 * std::abs(Params::opt_cmaes::ubound() - Params::opt_cmaes::lbound());\n                Eigen::VectorXd init_geno = gp.geno(init);\n                std::vector<double> x0(init_geno.data(), init_geno.data() + init_geno.size());\n                // -1 for automatically decided lambda, 0 is for random seeding of the internal generator.\n                CMAParameters<GenoPheno<pwqBoundStrategy>> cmaparams(dim, &x0.front(), sigma, Params::opt_cmaes::lambda(), 0, gp);\n                _set_common_params(cmaparams, dim);\n\n                auto pfunc = CMAStrategy<CovarianceUpdate, GenoPheno<pwqBoundStrategy>>::_defaultPFunc;\n                if (_pfunc_bounded) {\n                    pfunc = _pfunc_bounded;\n                }\n                else if (_pfunc) {\n                    pfunc = [this](const CMAParameters<GenoPheno<pwqBoundStrategy>>& params, const CMASolutions& sols) { _pfunc(sols); return 0; };\n                }\n\n                // the optimization itself\n                CMASolutions cmasols = cmaes<GenoPheno<pwqBoundStrategy>>(f_cmaes, cmaparams, pfunc);\n                if (Params::opt_cmaes::stochastic() || Params::opt_cmaes::handle_uncertainty())\n                    return gp.pheno(cmasols.xmean());\n\n                return gp.pheno(cmasols.get_best_seen_candidate().get_x_dvec());\n            }\n\n            template <typename P>\n            void _set_common_params(P& cmaparams, int dim) const\n            {\n                using namespace libcmaes;\n\n                // set multi-threading to true\n                cmaparams.set_mt_feval(true);\n                // aCMAES should be the best choice\n                // [see: https://github.com/beniz/libcmaes/wiki/Practical-hints ]\n                // but we want the restart -> aIPOP_CMAES\n                cmaparams.set_algo(Params::opt_cmaes::variant());\n                cmaparams.set_restarts(Params::opt_cmaes::restarts());\n                cmaparams.set_elitism(Params::opt_cmaes::elitism());\n\n                // if no max fun evals provided, we compute a recommended value\n                size_t max_evals = Params::opt_cmaes::max_fun_evals() < 0\n                    ? (900.0 * (dim + 3.0) * (dim + 3.0))\n                    : Params::opt_cmaes::max_fun_evals();\n                cmaparams.set_max_fevals(max_evals);\n                cmaparams.set_stopping_criteria(MAXFEVALS, true);\n\n                // if no max iters provided, we put a safety limit (to not take forever)\n                size_t max_iters = Params::opt_cmaes::max_iters() < 0\n                    ? 1000000\n                    : Params::opt_cmaes::max_iters();\n                cmaparams.set_max_iter(max_iters);\n                cmaparams.set_stopping_criteria(MAXITER, true);\n\n                // enable/disable automatic max iterations\n                cmaparams.set_stopping_criteria(AUTOMAXITER, Params::opt_cmaes::auto_max_iters());\n\n                if (Params::opt_cmaes::fun_tolerance() < 0) {\n                    cmaparams.set_stopping_criteria(TOLHISTFUN, false);\n                }\n                else {\n                    // the FTARGET criteria also allows us to enable ftolerance\n                    cmaparams.set_stopping_criteria(TOLHISTFUN, true);\n                    cmaparams.set_ftolerance(Params::opt_cmaes::fun_tolerance());\n                }\n\n                // we allow to set the ftarget parameter\n                if (Params::opt_cmaes::fun_target() > 0) {\n                    cmaparams.set_stopping_criteria(FTARGET, true);\n                    cmaparams.set_ftarget(-Params::opt_cmaes::fun_target());\n                }\n                else {\n                    // we do not know what is the actual maximum / minimum of the function\n                    // therefore we deactivate this stopping criterion\n                    cmaparams.set_stopping_criteria(FTARGET, false);\n                }\n\n                // enable stopping criteria by several equalfunvals\n                cmaparams.set_stopping_criteria(EQUALFUNVALS, Params::opt_cmaes::equal_fun_evals());\n\n                // enable additional criteria to stop\n                // set different tolerance if available\n                if (Params::opt_cmaes::xrel_tolerance() > 0) {\n                    cmaparams.set_stopping_criteria(TOLX, true);\n                    cmaparams.set_xtolerance(Params::opt_cmaes::xrel_tolerance());\n                }\n                else {\n                    cmaparams.set_stopping_criteria(TOLX, false);\n                }\n\n                // enable stopping criteria because of mal-conditions\n                cmaparams.set_stopping_criteria(CONDITIONCOV, true);\n                cmaparams.set_stopping_criteria(TOLUPSIGMA, true);\n\n                // disable stopping criteria for partial success\n                cmaparams.set_stopping_criteria(NOEFFECTAXIS, false);\n                cmaparams.set_stopping_criteria(NOEFFECTCOOR, false);\n\n                cmaparams.set_stopping_criteria(STAGNATION, Params::opt_cmaes::stagnation());\n\n                // enable or disable different parameters\n                cmaparams.set_initial_fvalue(Params::opt_cmaes::fun_compute_initial());\n                cmaparams.set_uh(Params::opt_cmaes::handle_uncertainty());\n                cmaparams.set_quiet(!Params::opt_cmaes::verbose());\n            }\n        };\n    } // namespace opt\n} // namespace limbo\n#endif\n#endif", "meta": {"hexsha": "3668339fbcdee4c83bbebed2106fac47dd8d99df", "size": 17072, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/opt/cmaes.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/opt/cmaes.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/opt/cmaes.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": 48.9169054441, "max_line_length": 270, "alphanum_fraction": 0.6008083411, "num_tokens": 3954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18248937650885402}}
{"text": "// Copyright 2019, Intel Corporation\n\n#include \"pmlc/dialect/stripe/analysis.h\"\n\n#include <utility>\n\n#include <boost/math/common_factor.hpp>\n\n#include \"pmlc/dialect/stripe/dialect.h\"\n\nnamespace pmlc {\nnamespace dialect {\nnamespace stripe {\n\nAffineRange::AffineRange(int64_t _min, int64_t _max, uint64_t _stride) : min(_min), max(_max), stride(_stride) {\n  if (min == max) {\n    stride = 0;\n  }\n}\n\nAffineRange& AffineRange::operator*=(int64_t x) {\n  min *= x;\n  max *= x;\n  if (x < 0) {\n    std::swap(min, max);\n  }\n  stride *= x;\n  return *this;\n}\n\nAffineRange& AffineRange::operator+=(const AffineRange& x) {\n  min += x.min;\n  max += x.max;\n  stride = boost::math::gcd(stride, x.stride);\n  return *this;\n}\n\nAffineRange& AffineRange::operator|=(const AffineRange& x) {\n  min = std::min(min, x.min);\n  max = std::max(max, x.max);\n  stride = boost::math::gcd(stride, x.stride);\n  return *this;\n}\n\nAffineRange::AffineRange(const AffinePolynomial& poly) : min(poly.constant), max(poly.constant), stride(0) {\n  // Go over each term and adjust\n  for (const auto& kvp : poly.terms) {\n    // Update the stride\n    stride = boost::math::gcd(stride, uint64_t(std::abs(kvp.second)));\n    // Extract the parallel for this affine is an argument of\n    auto pf = mlir::cast<ParallelForOp>(kvp.first.getOwner()->getParentOp());\n    // Extract the appropriate attribute from ranges\n    Attribute ra = pf.ranges().getValue()[kvp.first.getArgNumber()];\n    // Turn the range into an integer\n    int64_t range = ra.cast<IntegerAttr>().getInt();\n    // Update min/max\n    if (kvp.second >= 0) {\n      max += (range - 1) * kvp.second;\n    } else {\n      min += (range - 1) * kvp.second;\n    }\n  }\n}\n\nbool FlatTensorAccess::operator<(const FlatTensorAccess& rhs) const {\n  if (base != rhs.base) {\n    return base.getAsOpaquePointer() < rhs.base.getAsOpaquePointer();\n  }\n  return access < rhs.access;\n}\n\nbool FlatTensorAccess::operator==(const FlatTensorAccess& rhs) const {\n  return base == rhs.base && access == rhs.access;\n}\n\nFlatTensorAccess ComputeAccess(Value tensor) {\n  FlatTensorAccess ret;\n  if (auto bop = tensor.getDefiningOp()) {\n    if (auto op = mlir::dyn_cast<AllocateOp>(bop)) {\n      ret.base = op.result();\n      ret.base_type = op.layout();\n      ret.access.resize(ret.base_type.getRank());\n    } else if (auto op = mlir::dyn_cast<RefineOp>(bop)) {\n      ret = ComputeAccess(op.in());\n      for (size_t i = 0; i < ret.access.size(); i++) {\n        ret.access[i] += AffinePolynomial(op.getOffset(i));\n      }\n    } else {\n      throw std::runtime_error(\"Invalid tensor value in ComputeAccess\");\n    }\n  } else if (auto arg = tensor.dyn_cast<mlir::BlockArgument>()) {\n    auto parentOp = arg.getOwner()->getParentOp();\n    auto funcOp = mlir::dyn_cast<mlir::FuncOp>(parentOp);\n    if (!funcOp) {\n      throw std::runtime_error(\"Invalid tensor value: block argument not contained by FuncOp\");\n    }\n    auto attrName = stripe::Dialect::getDialectAttrName(\"layout\");\n    auto attr = funcOp.getArgAttrOfType<mlir::TypeAttr>(arg.getArgNumber(), attrName);\n    assert(attr && \"Expected 'layout' attribute in TensorRefType function argument\");\n    ret.base = tensor;\n    ret.base_type = attr.getValue().cast<TensorType>();\n    ret.access.resize(ret.base_type.getRank());\n  } else {\n    throw std::runtime_error(\"Invalid tensor value\");\n  }\n  return ret;\n}\n\nbool SafeConstraintInterior(ParallelForOp op) {\n  // Get an iterator to the begining of the interior\n  auto block = &op.inner().front();\n  // Get the penultimate Op (ignoring the terminator), which should be a constraint\n  auto it_con = std::prev(block->end(), 2);\n  // Check that it's good\n  if (it_con == block->end() || !mlir::isa<ConstraintOp>(*it_con)) {\n    return false;\n  }\n  // Check that all prior ops are no-side-effect and fail if not\n  for (auto it = block->begin(); it != it_con; ++it) {\n    if (!it->hasNoSideEffect()) {\n      return false;\n    }\n  }\n  return true;\n}\n\n}  // namespace stripe\n}  // namespace dialect\n}  // namespace pmlc\n", "meta": {"hexsha": "edfc3efdf40f3fca007eb870edc0f43ef6042014", "size": 3999, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pmlc/dialect/stripe/analysis.cc", "max_stars_repo_name": "redoclag/plaidml", "max_stars_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4535.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T05:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:42:33.000Z", "max_issues_repo_path": "pmlc/dialect/stripe/analysis.cc", "max_issues_repo_name": "HOZHENWAI/plaidml", "max_issues_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 984.0, "max_issues_repo_issues_event_min_datetime": "2017-10-20T17:16:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:43:18.000Z", "max_forks_repo_path": "pmlc/dialect/stripe/analysis.cc", "max_forks_repo_name": "HOZHENWAI/plaidml", "max_forks_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 492.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T18:22:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:00:05.000Z", "avg_line_length": 30.7615384615, "max_line_length": 112, "alphanum_fraction": 0.6554138535, "num_tokens": 1108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.18248937302468726}}
{"text": "#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <util/test_macros.hpp>\n#include <numerics/armadillo.hpp>\n\n#include <unity/lib/variant.hpp>\n#include <unity/lib/unity_sframe.hpp>\n#include <unity/lib/gl_sframe.hpp>\n#include <toolkits/supervised_learning/logistic_regression.hpp>\n#include <unity/dml/dml_class_registry.hpp>\n#include <sframe/testing_utils.hpp>\n\n#include <unity/dml/dml_toolkit_runner.hpp>\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic,1>  DenseVector;\nusing namespace turi;\nusing namespace turi::supervised;\n\n/**\n * Test suite for distributed logistic regression. \n*/\nstruct distributed_logistic_regression_test  {\n\n public:\n  void test_logistic_regression_basic_2d() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 100}, \n      {\"features\", 1}}; \n\n    size_t n = runner.get_default_num_workers_from_env(); \n    test_impl(opts, n);\n  }\n  \n  void test_logistic_regression_small() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 1000}, \n      {\"features\", 10}}; \n\n    size_t n = runner.get_default_num_workers_from_env(); \n    test_impl(opts, n);\n  }\n\n\n  void setup() {\n    runner.set_library(\"libdistributed_supervised_learning.so\");\n    dml_class_registry::get_instance().register_model<logistic_regression>();\n    working_dir = turi::get_temp_name();\n    fileio::create_directory(working_dir);\n  }\n\n  void teardown() {\n    fileio::delete_path_recursive(working_dir);\n  }\n\n  void test_impl(std::map<std::string, flexible_type> opts, size_t num_workers) {\n\n    setup();\n\n    try {\n      // Arrange\n      // ----------------------------------------------------------------------\n      size_t examples = opts.at(\"examples\");\n      size_t features = opts.at(\"features\");\n\n      // Coefficients \n      DenseVector coefs(features+1);\n      coefs.randn();\n      \n      // Feature names\n      std::string feature_types;\n      for(size_t i=0; i < features; i++){\n        feature_types += \"n\";\n      }\n\n      // Generate some data.\n      sframe data = make_random_sframe(examples, feature_types, true);\n      // Binary target.\n      sframe _y = data.select_columns({\"target\"});\n      std::shared_ptr<unity_sframe> _uy(new unity_sframe());\n      _uy->construct_from_sframe(_y);\n      gl_sframe gl_y(_uy);\n      gl_y[\"target\"] = gl_y[\"target\"] > gl_y[\"target\"].mean();\n\n      // Make the data into the right format.\n      sframe y = (*gl_y.get_proxy()->get_underlying_sframe());\n      sframe X = data;\n      X = X.remove_column(X.column_index(\"target\"));\n\n      // Setup the arguments. \n      std::map<std::string, flexible_type> options = { \n        {\"convergence_threshold\", 1e-2},\n        {\"step_size\", 1.0},\n        {\"lbfgs_memory_level\", 3},\n        {\"max_iterations\", 10},\n        {\"solver\", \"newton\"},\n        {\"l1_penalty\", 0.0},\n        {\"l2_penalty\", 0.0}\n      };\n      variant_map_type params;\n      std::shared_ptr<unity_sframe> uX(new unity_sframe());\n      std::shared_ptr<unity_sframe> uy(new unity_sframe());\n      uX->construct_from_sframe(X);\n      uy->construct_from_sframe(y);\n      params[\"model_name\"] = std::string(\"classifier_logistic_regression\");\n      params[\"features\"] = to_variant(uX);\n      params[\"target\"] = to_variant(uy);\n      for (const auto& kvp: options){\n        params[kvp.first] = to_variant(kvp.second);\n      }\n\n      // Act\n      // ----------------------------------------------------------------------\n      // Train the model. \n      variant_type ret = runner.run(\"distributed_supervised_train\", params, working_dir, num_workers);\n      std::shared_ptr<logistic_regression> model =\n            variant_get_value<std::shared_ptr<logistic_regression>>(ret);\n\n      // Assert\n      // ----------------------------------------------------------------------\n      // Check options.\n      std::map<std::string, flexible_type> _options = model->get_current_options();\n      for (auto& kvp: options){\n        TS_ASSERT(_options[kvp.first] == kvp.second);\n      }\n      TS_ASSERT(model->is_trained() == true);\n    } catch (...) {\n      teardown();\n      throw;\n    }\n    teardown();\n  }\n\n  dml_toolkit_runner runner;\n  std::string working_dir;\n};\n\nBOOST_FIXTURE_TEST_SUITE(_distributed_logistic_regression_test, distributed_logistic_regression_test)\nBOOST_AUTO_TEST_CASE(test_logistic_regression_basic_2d) {\n  distributed_logistic_regression_test::test_logistic_regression_basic_2d();\n}\nBOOST_AUTO_TEST_CASE(test_logistic_regression_small) {\n  distributed_logistic_regression_test::test_logistic_regression_small();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "44335331473533fb60144cf9be54e89dda1836e6", "size": 4555, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/unity/dml/distributed_logistic_regression_tests.cxx", "max_stars_repo_name": "fossabot/turicreate", "max_stars_repo_head_hexsha": "a500d5e52143ad15ebdf771d9f74198982c7c45c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T19:51:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-16T19:51:18.000Z", "max_issues_repo_path": "test/unity/dml/distributed_logistic_regression_tests.cxx", "max_issues_repo_name": "tashby/turicreate", "max_issues_repo_head_hexsha": "7f07ce795833d0c56c72b3a1fb9339bed6d178d1", "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": "test/unity/dml/distributed_logistic_regression_tests.cxx", "max_forks_repo_name": "tashby/turicreate", "max_forks_repo_head_hexsha": "7f07ce795833d0c56c72b3a1fb9339bed6d178d1", "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": 31.4137931034, "max_line_length": 102, "alphanum_fraction": 0.6357848518, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.1824893730246872}}
{"text": "/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http://www.mitk.org for details.\n\n===================================================================*/\n\n//misc\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n// Blueberry\n#include <berryISelectionService.h>\n#include <berryIWorkbenchWindow.h>\n\n// Qmitk\n#include \"QmitkBrainExtractionView.h\"\n\n// MITK\n#include <mitkNodePredicateDataType.h>\n\n// Qt\n#include <QMessageBox>\n#include <QFileDialog>\n#include <QDir>\n#include <QDirIterator>\n#include <QTimer>\n\n#include <mitkNodePredicateDimension.h>\n#include <mitkNodePredicateAnd.h>\n#include <mitkIOUtil.h>\n#include <mitkIPythonService.h>\n#include <itkResampleImageFilter.h>\n#include <mitkImageCast.h>\n#include <itkBSplineInterpolateImageFunction.h>\n#include <itkLinearInterpolateImageFunction.h>\n#include <itkThresholdImageFilter.h>\n#include <itksys/SystemTools.hxx>\n#include <itkB0ImageExtractionToSeparateImageFilter.h>\n\n#include <usGetModuleContext.h>\n#include <usModuleContext.h>\n#include <usModule.h>\n#include <usModuleResource.h>\n#include <usModuleResourceStream.h>\n#include <boost/algorithm/string.hpp>\n\n#include <BetData.h>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\ntypedef itksys::SystemTools ist;\n\nconst std::string QmitkBrainExtractionView::VIEW_ID = \"org.mitk.views.brainextraction\";\n\nQmitkBrainExtractionView::QmitkBrainExtractionView()\n  : QmitkAbstractView()\n  , m_Controls( 0 )\n  , m_DiffusionImage( nullptr )\n{\n\n}\n\n// Destructor\nQmitkBrainExtractionView::~QmitkBrainExtractionView()\n{\n}\n\nvoid QmitkBrainExtractionView::CreateQtPartControl( QWidget *parent )\n{\n  // build up qt view, unless already done\n  if ( !m_Controls )\n  {\n    // create GUI widgets from the Qt Designer's .ui file\n    m_Controls = new Ui::QmitkBrainExtractionViewControls;\n    m_Controls->setupUi( parent );\n    connect( m_Controls->m_ImageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateGUI()) );\n    connect( m_Controls->m_StartButton, SIGNAL(clicked()), this, SLOT(StartBrainExtraction()) );\n    this->m_Parent = parent;\n\n    m_Controls->m_ImageBox->SetDataStorage(this->GetDataStorage());\n    mitk::NodePredicateDimension::Pointer dimPred = mitk::NodePredicateDimension::New(3);\n    mitk::TNodePredicateDataType<mitk::Image>::Pointer isImagePredicate = mitk::TNodePredicateDataType<mitk::Image>::New();\n    m_Controls->m_ImageBox->SetPredicate(isImagePredicate);\n\n    UpdateGUI();\n  }\n}\n\nvoid QmitkBrainExtractionView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& )\n{\n}\n\nvoid QmitkBrainExtractionView::UpdateGUI()\n{\n  if (m_Controls->m_ImageBox->GetSelectedNode().IsNotNull())\n    m_Controls->m_StartButton->setEnabled(true);\n  else\n    m_Controls->m_StartButton->setEnabled(false);\n}\n\nvoid QmitkBrainExtractionView::SetFocus()\n{\n  UpdateGUI();\n  m_Controls->m_StartButton->setFocus();\n}\n\nstd::string QmitkBrainExtractionView::GetPythonFile(std::string filename)\n{\n  std::string out = \"\";\n  std::string exec_dir = QCoreApplication::applicationDirPath().toStdString();\n  for (auto dir : mitk::bet::relative_search_dirs)\n  {\n    if ( ist::FileExists( ist::GetCurrentWorkingDirectory() + dir + filename) )\n    {\n      out = ist::GetCurrentWorkingDirectory() + dir + filename;\n      return out;\n    }\n    if ( ist::FileExists( exec_dir + dir + filename) )\n    {\n      out = exec_dir + dir + filename;\n      return out;\n    }\n  }\n  for (auto dir : mitk::bet::absolute_search_dirs)\n  {\n    if ( ist::FileExists( dir + filename) )\n    {\n      out = dir + filename;\n      return out;\n    }\n  }\n\n  return out;\n}\n\nvoid QmitkBrainExtractionView::StartBrainExtraction()\n{\n  mitk::DataNode::Pointer node = m_Controls->m_ImageBox->GetSelectedNode();\n  mitk::Image::Pointer mitk_image = dynamic_cast<mitk::Image*>(node->GetData());\n\n  bool missing_file = false;\n  std::string missing_file_string = \"\";\n  if ( GetPythonFile(\"run_mitk.py\").empty() )\n  {\n    missing_file_string += \"Brain extraction script file missing: run_mitk.py\\n\\n\";\n    missing_file = true;\n  }\n\n  if ( GetPythonFile(\"model_final.model\").empty() )\n  {\n    missing_file_string += \"Brain extraction model file missing: model_final.model\\n\\n\";\n    missing_file = true;\n  }\n\n  if ( GetPythonFile(\"basic_config_just_like_braintumor.py\").empty() )\n  {\n    missing_file_string += \"Config file missing: basic_config_just_like_braintumor.py\\n\\n\";\n    missing_file = true;\n  }\n\n  if (missing_file)\n  {\n    QMessageBox::warning(nullptr, \"Error\", (missing_file_string).c_str(), QMessageBox::Ok);\n    return;\n  }\n\n  try\n  {\n    us::ModuleContext* context = us::GetModuleContext();\n    us::ServiceReference<mitk::IPythonService> m_PythonServiceRef = context->GetServiceReference<mitk::IPythonService>();\n    mitk::IPythonService* m_PythonService = dynamic_cast<mitk::IPythonService*> ( context->GetService<mitk::IPythonService>(m_PythonServiceRef) );\n    mitk::IPythonService::ForceLoadModule();\n\n    // load essential modules\n    m_PythonService->Execute(\"import SimpleITK as sitk\");\n    m_PythonService->Execute(\"import SimpleITK._SimpleITK as _SimpleITK\");\n    m_PythonService->Execute(\"import numpy\");\n\n    // extend python search path\n    std::string exec_dir = QCoreApplication::applicationDirPath().toStdString();\n    std::string pythonpath = \"\";\n    for (auto dir : mitk::bet::relative_search_dirs)\n      pythonpath += \"','\" + ist::GetCurrentWorkingDirectory() + dir;\n    for (auto dir : mitk::bet::relative_search_dirs)\n      pythonpath += \"','\" + exec_dir + dir;\n    for (auto dir : mitk::bet::absolute_search_dirs)\n      pythonpath += \"','\" + dir;\n    m_PythonService->Execute(\"paths=['\"+pythonpath+\"']\");\n\n    // set input files (model and config)\n    m_PythonService->Execute(\"model_file=\\\"\"+GetPythonFile(\"model_final.model\")+\"\\\"\");\n    m_PythonService->Execute(\"config_file=\\\"\"+GetPythonFile(\"basic_config_just_like_braintumor.py\")+\"\\\"\");\n\n    // copy input  image to python\n    m_PythonService->CopyToPythonAsSimpleItkImage( mitk_image, \"in_image\");\n\n    // run segmentation script\n    m_PythonService->ExecuteScript( GetPythonFile(\"run_mitk.py\") );\n\n    // clean up after running script (better way than deleting individual variables?)\n    if(m_PythonService->DoesVariableExist(\"in_image\"))\n      m_PythonService->Execute(\"del in_image\");\n\n    // check for errors\n    if(!m_PythonService->GetVariable(\"error_string\").empty())\n    {\n      QMessageBox::warning(nullptr, \"Error\", QString(m_PythonService->GetVariable(\"error_string\").c_str()), QMessageBox::Ok);\n      return;\n    }\n\n    // get output images and add to datastorage\n    std::string output_variables = m_PythonService->GetVariable(\"output_variables\");\n    std::vector<std::string> outputs;\n    boost::split(outputs, output_variables, boost::is_any_of(\",\"));\n\n    std::string output_types = m_PythonService->GetVariable(\"output_types\");\n    std::vector<std::string> types;\n    boost::split(types, output_types, boost::is_any_of(\",\"));\n\n    for (unsigned int i=0; i<outputs.size(); ++i)\n    {\n      if (m_PythonService->DoesVariableExist(outputs.at(i)))\n      {\n        mitk::Image::Pointer image = m_PythonService->CopySimpleItkImageFromPython(outputs.at(i));\n\n        if(types.at(i)==\"input\" && mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage(mitk_image))\n        {\n          mitk::DiffusionPropertyHelper::CopyProperties(mitk_image, image, true);\n          mitk::DiffusionPropertyHelper::InitializeImage(image);\n        }\n\n        mitk::DataNode::Pointer corrected_node = mitk::DataNode::New();\n        corrected_node->SetData( image );\n        std::string name = node->GetName();\n        name += \"_\";\n        name += outputs.at(i);\n        corrected_node->SetName(name);\n        GetDataStorage()->Add(corrected_node, node);\n        m_PythonService->Execute(\"del \" + outputs.at(i));\n\n        mitk::RenderingManager::GetInstance()->InitializeViews( corrected_node->GetData()->GetTimeGeometry(),\n                                                                mitk::RenderingManager::REQUEST_UPDATE_ALL,\n                                                                true);\n      }\n    }\n  }\n  catch(...)\n  {\n    QMessageBox::warning(nullptr, \"Error\", \"File could not be processed.\\nIs pytorch installed on your system?\\nDoes your script use the correct input and output variable names (in: in_image & model, out: brain_mask & brain_extracted)?\", QMessageBox::Ok);\n  }\n}\n", "meta": {"hexsha": "1b53fc21303818d23e00ce2a8f657e90278dc2e8", "size": 8682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkBrainExtractionView.cpp", "max_stars_repo_name": "wyyrepo/MITK", "max_stars_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-20T08:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T08:19:27.000Z", "max_issues_repo_path": "Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkBrainExtractionView.cpp", "max_issues_repo_name": "wyyrepo/MITK", "max_issues_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "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": "Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkBrainExtractionView.cpp", "max_forks_repo_name": "wyyrepo/MITK", "max_forks_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "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.0114068441, "max_line_length": 255, "alphanum_fraction": 0.6924671735, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18248936954052047}}
{"text": "/*!\n@file\nDefines `boost::hana::Foldable::mcd`.\n\n@copyright Louis Dionne 2014\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_FOLDABLE_MCD_HPP\n#define BOOST_HANA_FOLDABLE_MCD_HPP\n\n#include <boost/hana/foldable/foldable.hpp>\n\n#include <boost/hana/integral.hpp>\n#include <boost/hana/logical/logical.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/monoid/monoid.hpp>\n#include <boost/hana/orderable/orderable.hpp>\n\n\nnamespace boost { namespace hana {\n    //! @details\n    //! Minimal complete definition: `foldl` and `foldr`\n    struct Foldable::mcd {\n        template <typename Foldable_, typename F>\n        static constexpr auto foldr1_impl(Foldable_ foldable, F f) {\n            auto g = [=](auto x, auto mstate) {\n                return just(maybe(\n                    x,\n                    [=](auto state) { return f(x, state); },\n                    mstate\n                ));\n            };\n            return from_just(foldr(foldable, nothing, g));\n        }\n\n        template <typename Foldable_, typename F>\n        static constexpr auto foldl1_impl(Foldable_ foldable, F f) {\n            auto g = [=](auto mstate, auto x) {\n                return maybe(\n                    just(x),\n                    [=](auto state) { return just(f(state, x)); },\n                    mstate\n                );\n            };\n            return from_just(foldl(foldable, nothing, g));\n        }\n\n        template <typename Foldable_>\n        static constexpr auto length_impl(Foldable_ foldable) {\n            auto plus1 = [](auto n, auto _) { return n + size_t<1>; };\n            return foldl(foldable, size_t<0>, plus1);\n        }\n\n        template <typename Foldable_>\n        static constexpr auto minimum_impl(Foldable_ foldable)\n        { return minimum_by(less, foldable); }\n\n        template <typename Foldable_>\n        static constexpr auto maximum_impl(Foldable_ foldable)\n        { return maximum_by(less, foldable); }\n\n        template <typename Pred, typename Foldable_>\n        static constexpr auto minimum_by_impl(Pred pred, Foldable_ foldable) {\n            return foldl1(foldable, [=](auto x, auto y) {\n                return if_(pred(x, y), x, y);\n            });\n        }\n\n        template <typename Pred, typename Foldable_>\n        static constexpr auto maximum_by_impl(Pred pred, Foldable_ foldable) {\n            return foldl1(foldable, [=](auto x, auto y) {\n                return if_(pred(x, y), y, x);\n            });\n        }\n\n        //! @todo\n        //! The base case can't be `int_<0>`, it should be the identity of\n        //! a given `Monoid`?\n        template <typename Xs>\n        static constexpr auto sum_impl(Xs xs) {\n            return foldl(xs, int_<0>, plus);\n        }\n\n        template <typename Foldable_>\n        static constexpr auto product_impl(Foldable_ foldable) {\n            return foldl(foldable, int_<1>, [](auto x, auto y) {\n                return x * y;\n            });\n        }\n\n        template <typename Foldable_, typename Pred>\n        static constexpr auto count_impl(Foldable_ foldable, Pred pred) {\n            return foldl(foldable, size_t<0>, [=](auto counter, auto x) {\n                return if_(pred(x), plus(counter, size_t<1>), counter);\n            });\n        }\n\n        template <typename Foldable_, typename F>\n        static constexpr auto unpack_impl(Foldable_ foldable, F f) {\n            return foldl(foldable, f, [](auto g, auto x) {\n                return [=](auto ...y) { return g(x, y...); };\n            })();\n        }\n    };\n}} // end namespace boost::hana\n\n#endif // !BOOST_HANA_FOLDABLE_MCD_HPP\n", "meta": {"hexsha": "78c2d4480e9bd3dabb9d3463a1e24e4ff6a89fe2", "size": 3706, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/hana/foldable/mcd.hpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "include/boost/hana/foldable/mcd.hpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/hana/foldable/mcd.hpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.6909090909, "max_line_length": 78, "alphanum_fraction": 0.568267674, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18248936954052047}}
{"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_IEEE_FUNCTIONS_SIMD_COMMON_SIGN_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_SIMD_COMMON_SIGN_HPP_INCLUDED\n\n#include <boost/simd/ieee/functions/sign.hpp>\n#include <boost/simd/include/functions/simd/is_nan.hpp>\n#include <boost/simd/include/functions/simd/is_gtz.hpp>\n#include <boost/simd/include/functions/simd/is_ltz.hpp>\n#include <boost/simd/include/functions/simd/is_equal.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/functions/simd/shift_right.hpp>\n#include <boost/simd/include/functions/simd/if_one_else_zero.hpp>\n#include <boost/simd/include/functions/simd/if_allbits_else.hpp>\n#include <boost/simd/include/functions/simd/minus.hpp>\n#include <boost/simd/include/functions/simd/unary_minus.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( sign_, tag::cpu_\n                                    , (A0)(X)\n                                    , ((simd_<arithmetic_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      return if_one_else_zero(is_gtz(a0))-if_one_else_zero(is_ltz(a0));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( sign_, tag::cpu_\n                                    , (A0)(X)\n                                    , ((simd_<unsigned_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      return if_one_else_zero(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( sign_, tag::cpu_\n                                    , (A0)(X)\n                                    , ((simd_<floating_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      A0 r = if_one_else_zero(is_gtz(a0))-if_one_else_zero(is_ltz(a0));\n      #ifdef BOOST_SIMD_NO_NANS\n      return r;\n      #else\n      return if_allbits_else(is_nan(a0), r);\n      #endif\n    }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "0a8449c80d6ec9092be3d87ee57090d22058d546", "size": 2682, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/ieee/functions/simd/common/sign.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/ieee/functions/simd/common/sign.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/ieee/functions/simd/common/sign.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": 37.7746478873, "max_line_length": 80, "alphanum_fraction": 0.576808352, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.18248796547631738}}
{"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_MAC_CBC_MAC_HPP\n#define CRYPTO3_MAC_CBC_MAC_HPP\n\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n\n#include <nil/crypto3/mac/detail/cbc_mac/cbc_mac_policy.hpp>\n#include <nil/crypto3/mac/detail/cbc_mac/accumulator.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace mac {\n            /*!\n             * @brief CBC-MAC\n             * @tparam BlockCipher\n             * @ingroup mac\n             */\n            template<typename BlockCipher>\n            class cbc_mac {\n                typedef detail::cbc_mac_policy<BlockCipher> policy_type;\n\n            public:\n                typedef BlockCipher block_cipher_type;\n\n                constexpr static const std::size_t block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                constexpr static const std::size_t key_bits = policy_type::key_bits;\n                constexpr static const std::size_t key_words = policy_type::key_words;\n                typedef typename policy_type::key_type key_type;\n\n                constexpr static const std::size_t state_bits = policy_type::state_bits;\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 digest_bits = policy_type::digest_bits;\n                typedef typename policy_type::digest_type digest_type;\n\n                cbc_mac(const block_cipher_type &cipher) : cipher(cipher) {\n                }\n\n                cbc_mac(const key_type &key) : cipher(key) {\n                }\n\n                inline void begin_message(state_type &state, const block_type &block) {\n                    size_t xored = std::min(output_length() - m_position, length);\n                    xor_buf(&m_state[m_position], input, xored);\n                    m_position += xored;\n\n                    if (m_position < output_length()) {\n                        return;\n                    }\n\n                    m_cipher->encrypt(m_state);\n                    input += xored;\n                    length -= xored;\n                    while (length >= output_length()) {\n                        xor_buf(m_state, input, output_length());\n                        m_cipher->encrypt(m_state);\n                        input += output_length();\n                        length -= output_length();\n                    }\n\n                    xor_buf(m_state, input, length);\n                    m_position = length;\n                }\n\n                void process_block(state_type &state, const block_type &block) {\n                    size_t xored = std::min(output_length() - m_position, length);\n                    xor_buf(&m_state[m_position], input, xored);\n                    m_position += xored;\n\n                    if (m_position < output_length()) {\n                        return;\n                    }\n\n                    m_cipher->encrypt(m_state);\n                    input += xored;\n                    length -= xored;\n                    while (length >= output_length()) {\n                        xor_buf(m_state, input, output_length());\n                        m_cipher->encrypt(m_state);\n                        input += output_length();\n                        length -= output_length();\n                    }\n\n                    xor_buf(m_state, input, length);\n                    m_position = length;\n                }\n\n                void end_message(digest_type &digest, const state_type &state, const block_type &block) {\n                    if (m_position) {\n                        m_cipher->encrypt(m_state);\n                    }\n\n                    copy_mem(mac, m_state.data(), m_state.size());\n                    zeroise(m_state);\n                    m_position = 0;\n                }\n\n            protected:\n                void schedule_key(const key_type &key) {\n                }\n\n                block_cipher_type cipher;\n            };\n        }    // namespace mac\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "ea7ddbf6d0d15e86d19ab969d0d2315e4a433baa", "size": 5514, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/mac/include/nil/crypto3/mac/cbc_mac.hpp", "max_stars_repo_name": "idealatom/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "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/mac/include/nil/crypto3/mac/cbc_mac.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T18:20:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T14:26:44.000Z", "max_forks_repo_path": "libs/mac/include/nil/crypto3/mac/cbc_mac.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": 40.2481751825, "max_line_length": 105, "alphanum_fraction": 0.5449764236, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.1824879619338816}}
{"text": "#ifndef PERIOR_TREE_RTREE_HPP\n#define PERIOR_TREE_RTREE_HPP\n#include \"rtree_node.hpp\"\n#include \"expand.hpp\"\n#include \"within.hpp\"\n#include \"area.hpp\"\n#include \"dump.hpp\"\n#include <boost/container/vector.hpp>\n#include <boost/container/small_vector.hpp>\n#include <boost/optional.hpp>\n#include <utility>\n#include <memory>\n#include <functional>\n#include <limits>\n#include <tuple>\n\nnamespace perior\n{\n\nnamespace detail\n{\ntemplate<typename T>\nstruct indexable_type_of\n{\n    typedef typename std::tuple_element<0, T>::type type;\n\n    static inline type const&\n    invoke(const T& t) noexcept {return std::get<0>(t);}\n\n    static inline type&\n    invoke(T& t)       noexcept {return std::get<0>(t);}\n\n    static inline type&&\n    invoke(T&& t)      noexcept {return std::get<0>(t);}\n};\n} // detail\n\ntemplate<std::size_t Min, std::size_t Max>\nstruct quadratic\n{\n    static constexpr std::size_t min_elem = Min;\n    static constexpr std::size_t max_elem = Max;\n};\n\ntemplate<typename T, std::size_t N>\naabb<T, N> make_aabb(const aabb<T, N>& b) noexcept\n{\n    return b;\n}\n\ntemplate<typename T, std::size_t N>\naabb<T, N> make_aabb(const point<T, N>& p) noexcept\n{\n    return aabb<T, N>(p, p);\n}\n\ntemplate<typename T,\n         typename Params,\n         typename Boundary,\n         typename EqualTo   = std::equal_to<T>,\n         typename Allocator = boost::container::new_allocator<T> >\nclass rtree\n{\n  public:\n    typedef T         value_type;\n    typedef Params    parameter_type;\n    typedef Boundary  boundary_type;\n    typedef EqualTo   equal_to_type;\n    typedef Allocator allocator_type;\n\n    typedef detail::indexable_type_of<value_type> indexable;\n    typedef typename indexable::type              indexable_type;\n    typedef typename indexable_type::scalar_type  scalar_type;\n    static constexpr std::size_t dim = indexable_type::dim;\n    typedef point<scalar_type, dim> point_type;\n    typedef aabb<scalar_type, dim>  aabb_type;\n\n    static constexpr std::size_t min_entry = parameter_type::min_elem;\n    static constexpr std::size_t max_entry = parameter_type::max_elem;\n\n    typedef boost::container::vector<value_type, allocator_type> container_type;\n    typedef typename container_type::iterator       iterator;\n    typedef typename container_type::const_iterator const_iterator;\n\n    typedef detail::rtree_node<scalar_type, dim, min_entry, max_entry> node_type;\n    typedef typename allocator_type::template rebind<node_type>::other\n            node_allocator_type;\n    typedef boost::container::vector<node_type, node_allocator_type> tree_type;\n    typedef boost::container::small_vector<std::size_t, 8> index_buffer_type;\n\n  private:\n\n    static constexpr std::size_t nil = std::numeric_limits<std::size_t>::max();\n\n  public:\n\n    rtree(): root_(nil){}\n    ~rtree() = default;\n    rtree(const rtree&) = default;\n    rtree(rtree&&)      = default;\n    rtree& operator=(const rtree&) = default;\n    rtree& operator=(rtree&&)      = default;\n\n    explicit rtree(const boundary_type& b): root_(nil), boundary_(b){}\n    explicit rtree(const equal_to_type& e): root_(nil),  equal_to_(e){}\n    rtree(const boundary_type& b, const equal_to_type& e)\n        : root_(nil), equal_to_(e), boundary_(b)\n    {}\n\n    std::size_t size() const noexcept {return container_.size();}\n    bool empty()       const noexcept {return container_.empty();}\n    void clear()\n    {\n        this->root_ = nil;\n        this->tree_.clear();\n        this->container_.clear();\n        this->overwritable_nodes_.clear();\n        this->overwritable_values_.clear();\n        return;\n    }\n\n    void insert(const value_type& v)\n    {\n        const std::size_t     idx   = this->add_value(v);\n        std::cerr << \"new value index = \" << idx << std::endl;\n\n        const indexable_type& entry = indexable::invoke(v);\n\n        std::cerr << \"seaching leaf to insert...\" << std::endl;\n        const std::size_t L = this->choose_leaf(entry);\n        std::cerr << \"leaf to insert = \" << L << std::endl;\n\n        if(tree_.at(L).has_enough_storage())\n        {\n            std::cerr << \"node \" << L << \" has enough storage. insert and expand.\" << std::endl;\n            tree_.at(L).entry.push_back(idx);\n            expand(tree_.at(L).box, entry, this->boundary_);\n            this->adjust_tree(L);\n        }\n        else\n        {\n            std::cerr << \"node \" << L << \" has no storage.\" << std::endl;\n            const std::size_t LL = this->add_node(this->split_leaf(L, idx, entry));\n            std::cerr << \"create new node \" << LL << \".\" << std::endl;\n            this->adjust_tree(L, LL);\n        }\n        return;\n    }\n    bool remove(const value_type& v)\n    {\n        if(this->root_ == nil)\n        {\n            return false;\n        }\n        if(boost::optional<std::pair<std::size_t, typename node_type::const_iterator>>\n                found = this->find_leaf(this->root_, v))\n        {\n            const std::size_t node_idx  = found->first;\n            const std::size_t value_idx = *(found->second);\n            this->tree_.at(node_idx).entry.erase(found->second);\n            this->erase_value(value_idx);\n            this->condense_box(this->tree_.at(node_idx));\n            this->condense_leaf(node_idx);\n            return true;\n        }\n        return false;\n    }\n\n    template<typename Query, typename OutputIterator>\n    void query(Query q, OutputIterator out) const\n    {\n        if(this->root_ == nil){return;}\n        return query_impl(this->root_, q, out);\n    }\n\n    template<typename charT, typename traits>\n    std::basic_ostream<charT, traits>&\n    dump(std::basic_ostream<charT, traits>& os) const\n    {\n        if(this->root_ == nil){return os;}\n        std::vector<std::string> colors;\n        colors.push_back(\"red\");\n        colors.push_back(\"green\");\n        colors.push_back(\"blue\");\n        return dump_node(os, this->root_, 0, colors);\n    }\n\n  private:\n\n    template<typename charT, typename traits>\n    std::basic_ostream<charT, traits>&\n    dump_node(std::basic_ostream<charT, traits>& os,\n              const std::size_t N, const std::size_t depth,\n              const std::vector<std::string>& clrs) const\n    {\n        const std::string& clr = clrs.at(depth%3);\n        to_svg(os, tree_.at(N).box, this->boundary_, clr, 5, \"none\");\n        os << '\\n';\n        if(tree_.at(N).is_leaf)\n        {\n            for(auto i=tree_.at(N).entry.cbegin(), e=tree_.at(N).entry.cend();\n                    i!=e; ++i)\n            {\n                to_svg(os, indexable::invoke(container_.at(*i)), this->boundary_, \"black\", 1, \"black\");\n                os << '\\n';\n            }\n            return os;\n        }\n        else\n        {\n            for(auto i=tree_.at(N).entry.cbegin(), e=tree_.at(N).entry.cend();\n                    i!=e; ++i)\n            {\n                dump_node(os, *i, depth+1, clrs);\n            }\n            return os;\n        }\n    }\n\n    std::size_t choose_leaf(const indexable_type& entry)\n    {\n        std::cerr << \"root = \" << this->root_ << std::endl;\n        if(this->root_ == nil)\n        {\n            std::cerr << \"this tree has no node. add new root\" << std::endl;\n\n            node_type n(true, nil);\n            n.box = make_aabb(entry);\n            this->root_ = this->add_node(n);\n\n            std::cerr << \"new root = \" << this->root_ << std::endl;\n            return this->root_;\n        }\n        std::cerr << \"now tree has root \" << this->root_ << std::endl;\n\n        std::size_t node_idx = this->root_;\n        while(!(this->tree_.at(node_idx).is_leaf))\n        {\n            scalar_type diff_area_min = std::numeric_limits<scalar_type>::max();\n            scalar_type area_min      = std::numeric_limits<scalar_type>::max();\n\n            const node_type& node = this->tree_.at(node_idx);\n            for(typename node_type::const_iterator\n                    i(node.entry.begin()), e(node.entry.end()); i != e; ++i)\n            {\n                aabb_type box = tree_.at(*i).box;\n                const scalar_type area_initial = area(box, this->boundary_);\n\n                expand(box, entry, this->boundary_);\n\n                const scalar_type area_expanded = area(box, this->boundary_);\n                const scalar_type diff_area     = area_expanded - area_initial;\n                if((diff_area <  diff_area_min) ||\n                   (diff_area == diff_area_min  && area_expanded < area_min))\n                {\n                    node_idx = *i;\n                    diff_area_min = diff_area;\n                    area_min = area_expanded;\n                }\n            }\n        }\n        return node_idx;\n    }\n\n    void adjust_tree(std::size_t node_idx)\n    {\n        while(tree_.at(node_idx).parent != nil)\n        {\n            const node_type& node = tree_.at(node_idx);\n            node_type& parent_ = tree_.at(node.parent);\n            expand(parent_.box, node.box, this->boundary_);\n\n            node_idx = node.parent;\n        }\n        return;\n    }\n    void adjust_tree(const std::size_t N, const std::size_t NN)\n    {\n        if(tree_.at(N).parent == nil) // grow tree taller\n        {\n            std::cerr << \"node \" << N << \" has no parent.\" << std::endl;\n            node_type new_root(false, nil);\n            new_root.entry.push_back(N);\n            new_root.entry.push_back(NN);\n            new_root.box = tree_.at(N).box;\n            expand(new_root.box, tree_.at(NN).box, this->boundary_);\n            this->root_ = this->add_node(new_root);\n            std::cerr << \"NR(\" << this->root_ << \") = \";\n            to_svg(std::cerr, tree_.at(this->root_).box, this->boundary_);\n\n            this->tree_.at(N).parent = this->root_;\n            this->tree_.at(NN).parent = this->root_;\n            std::cerr << \"\\nN (\" << N << \") = \";\n            to_svg(std::cerr, tree_.at(N).box, this->boundary_);\n            std::cerr << \"\\nNN(\" << NN << \") = \";\n            to_svg(std::cerr, tree_.at(NN).box, this->boundary_);\n            std::cerr << \"\\nadjust_tree: grow tree taller. new root is \" << this->root_ << std::endl;\n            return;\n        }\n        else\n        {\n            const node_type& node    = tree_.at(N);\n            const node_type& partner = tree_.at(NN);\n\n            assert(node.parent == partner.parent);\n            node_type& parent_ = tree_.at(node.parent);\n            expand(parent_.box, node.box, this->boundary_);\n            std::cerr << \"adjust_tree(N, NN): parent has \" << parent_.entry.size() << \"entry.\" << std::endl;\n            if(parent_.has_enough_storage())\n            {\n                std::cerr << \"storage is enough.\" << std::endl;\n                expand(parent_.box, partner.box, this->boundary_);\n                parent_.entry.push_back(NN);\n                return this->adjust_tree(node.parent);\n            }\n            else\n            {\n                std::cerr << \"storage is not enough.\" << std::endl;\n\n                const std::size_t PP = this->split_node(node.parent, NN);\n\n                std::cerr << \"adjust_tree: split node \" << node.parent\n                          << \" and \" << PP << std::endl;\n                std::cerr << \"node (\" << node.parent << \") = \";\n                to_svg(std::cerr, tree_.at(node.parent).box, this->boundary_);\n                std::cerr << \"\\npartner(\" << PP << \") = \";\n                to_svg(std::cerr, tree_.at(PP).box, this->boundary_);\n                std::cerr << std::endl;\n\n                return this->adjust_tree(node.parent, PP);\n            }\n        }\n    }\n\n    boost::optional<std::pair<std::size_t, typename node_type::const_iterator>>\n    find_leaf(std::size_t node_idx, const value_type& entry) const\n    {\n        const node_type& node = tree_.at(node_idx);\n        if(within(indexable::invoke(entry), node.box, this->boundary_) == false)\n        {\n            return boost::none;\n        }\n\n        if(node.is_leaf)\n        {\n            for(typename node_type::const_iterator\n                    i(node.entry.begin()), e(node.entry.end()); i != e; ++i)\n            {\n                if(equal_to_(container_.at(*i), entry))\n                {\n                    return std::make_pair(node_idx, i);\n                }\n            }\n            return boost::none;\n        }\n        else\n        {\n            for(typename node_type::const_iterator\n                    i(node.entry.begin()), e(node.entry.end()); i != e; ++i)\n            {\n                if(!within(indexable::invoke(entry), tree_.at(*i).box, this->boundary_))\n                {\n                    continue;\n                }\n\n                if(boost::optional<std::pair<std::size_t, typename node_type::const_iterator>\n                    > found = this->find_leaf(*i, entry))\n                {\n                    return found;\n                }\n            }\n            return boost::none;\n        }\n    }\n\n    void condense_leaf(const std::size_t N)\n    {\n        const node_type& node = this->tree_.at(N);\n        assert(node.is_leaf);\n\n        std::cerr << \"condense_leaf for \" << N << std::endl;\n        std::cerr << \"leaf-node \" << N << \" has \" << node.entry.size()\n                  << \" entries.\" << std::endl;\n\n        if(node.has_enough_entry() || node.parent == nil)\n        {\n            std::cerr << \"leaf-node \" << N << \" is root or has enough entry\"\n                      << std::endl;\n            return;\n        }\n\n        std::cerr << \"node \" << N << \" should be eliminated.\" << std::endl;\n        std::cerr << \"parent of node \" << N << \" is \" << node.parent << std::endl;\n\n        // copy index of objects\n        boost::container::small_vector<std::size_t, min_entry> eliminated_objs;\n        std::copy(node.entry.begin(), node.entry.end(),\n                  std::back_inserter(eliminated_objs));\n\n        // erase the node N from its parent and condense aabb\n        typename node_type::iterator found = std::find(\n                this->tree_.at(node.parent).entry.begin(),\n                this->tree_.at(node.parent).entry.end(), N);\n        assert(found != this->tree_.at(node.parent).entry.end());\n        this->tree_.at(node.parent).entry.erase(found);\n        this->condense_box(this->tree_.at(node.parent));\n\n        // re-insert entries eliminated from node N\n        for(auto i(eliminated_objs.begin()), e(eliminated_objs.end()); i!=e; ++i)\n        {\n            this->insert(this->container_.at(*i));\n        }\n\n        // condense ancester nodes...\n        condense_node(node.parent);\n        return;\n    }\n\n    void condense_node(const std::size_t N)\n    {\n        const node_type& node = this->tree_.at(N);\n        assert(node.is_leaf == false);\n\n        std::cerr << \"condense_node for \" << N << std::endl;\n        std::cerr << \"internal-node \" << N << \" has \" << node.entry.size()\n                  << \" entries.\" << std::endl;\n\n        if(node.has_enough_entry())\n        {\n            std::cerr << \"internal-node \" << N << \" has enough entry\"\n                      << std::endl;\n            return;\n        }\n        if(node.parent == nil && node.entry.size() == 1)\n        {\n            std::cerr << \"root-node has only 1 entry. remove.\" << std::endl;\n            this->root_ = node.entry.front();\n            this->erase_node(N);\n            std::cerr << \"new root is \" << this->root_ << std::endl;\n            return;\n        }\n        std::cerr << \"internal node has parent \" << node.parent << std::endl;\n\n        // collect index of nodes that are children of the node to be removed\n        boost::container::small_vector<std::size_t, min_entry> eliminated_nodes;\n        std::copy(node.entry.begin(), node.entry.end(),\n                  std::back_inserter(eliminated_nodes));\n\n        // erase the node N from its parent and condense its aabb\n        typename node_type::iterator found = std::find(\n                this->tree_.at(node.parent).entry.begin(),\n                this->tree_.at(node.parent).entry.end(), N);\n        assert(found != this->tree_.at(node.parent).entry.end());\n        this->tree_.at(node.parent).entry.erase(found);\n        this->condense_box(this->tree_.at(node.parent));\n\n        // re-insert nodes eliminated from node N\n        for(auto i(eliminated_nodes.begin()), e(eliminated_nodes.end()); i!=e; ++i)\n        {\n            this->re_insert(*i);\n        }\n        this->condense_node(node.parent);\n        return;\n    }\n\n\n    // split nodes because of one entry\n    node_type split_leaf(const std::size_t N,\n                         const std::size_t vidx, const indexable_type& entry)\n    {\n        std::cerr << \"split_leaf\" << std::endl;\n\n        node_type& node = tree_.at(N);\n        node_type  partner(true, node.parent);\n\n        boost::container::static_vector<std::pair<std::size_t, indexable_type>,\n            max_entry+1> entries;\n        entries.push_back(std::make_pair(vidx, entry));\n\n        for(typename node_type::const_iterator\n                i(node.entry.begin()), e(node.entry.end()); i != e; ++i)\n        {\n            entries.push_back(std::make_pair(\n                        *i, indexable::invoke(container_.at(*i))));\n        }\n        node.entry.clear();\n        partner.entry.clear(); // for make it sure\n\n        /* assign first 2 entries to node and partner */\n        {\n            const std::array<std::size_t, 2> seeds = this->pick_seeds(entries);\n            std::cerr << \"seeds = {\" << entries.at(seeds[0]).first\n                      << \", \" << entries.at(seeds[1]).first << \"}\" << std::endl;\n            std::cerr << \"entries.size() = \" << entries.size() << std::endl;\n               node.entry.push_back(entries.at(seeds[0]).first);\n            partner.entry.push_back(entries.at(seeds[1]).first);\n\n            std::cerr << \"clear box\" << std::endl;\n               node.box = make_aabb(entries.at(seeds[0]).second);\n            partner.box = make_aabb(entries.at(seeds[1]).second);\n\n            // remove them from entries pool\n            entries.erase(entries.begin() + std::min(seeds[0], seeds[1]));\n            entries.erase(entries.begin() + std::max(seeds[0], seeds[1]) - 1);\n        }\n\n        std::cerr << \"start splitting\" << std::endl;\n        while(!entries.empty())\n        {\n            if(min_entry > node.entry.size() &&\n               min_entry - node.entry.size() >= entries.size())\n            {\n                for(auto i(entries.begin()), e(entries.end()); i != e; ++i)\n                {\n                    node.entry.push_back(i->first);\n                    expand(node.box, i->second, this->boundary_);\n                }\n                return partner;\n            }\n            if(min_entry > partner.entry.size() &&\n               min_entry - partner.entry.size() >= entries.size())\n            {\n                for(auto i(entries.begin()), e(entries.end()); i != e; ++i)\n                {\n                    partner.entry.push_back(i->first);\n                    expand(partner.box, i->second, this->boundary_);\n                }\n                return partner;\n            }\n\n            const std::pair<std::size_t, bool> next =\n                this->pick_next(entries, node.box, partner.box);\n            if(next.second) // next is for node\n            {\n                std::cerr << \"next entry \" << entries.at(next.first).first\n                          << \" is for node.\" << std::endl;\n                node.entry.push_back(entries.at(next.first).first);\n                expand(node.box, entries.at(next.first).second, this->boundary_);\n            }\n            else // next is for partner\n            {\n                std::cerr << \"next entry \" << entries.at(next.first).first\n                          << \" is for partner.\" << std::endl;\n                partner.entry.push_back(entries.at(next.first).first);\n                expand(partner.box, entries.at(next.first).second, this->boundary_);\n            }\n            entries.erase(entries.begin() + next.first);\n        }\n        return partner;\n    }\n\n    // objT should be indexable_type or aabb_type\n    template<typename objT>\n    std::array<std::size_t, 2> pick_seeds(const boost::container::static_vector<\n            std::pair<std::size_t, objT>, max_entry+1>& entries)\n    {\n        assert(entries.size() >= 2);\n\n        std::array<std::size_t, 2> retval;\n\n        scalar_type max_d = 0;\n        for(std::size_t i=0; i<entries.size()-1; ++i)\n        {\n            for(std::size_t j=i+1; j<entries.size(); ++j)\n            {\n                const aabb_type E1I = make_aabb(entries.at(i).second);\n                const aabb_type E2I = make_aabb(entries.at(j).second);\n                aabb_type J = E1I;\n                expand(J, E2I, this->boundary_);\n                const scalar_type d =\n                    area(J, boundary_) - area(E1I, boundary_) - area(E2I, boundary_);\n                if(max_d < std::abs(d))\n                {\n                    max_d = std::abs(d);\n                    retval[0] = i;\n                    retval[1] = j;\n                    std::cerr << \"found seeds {\" << i << \", \" << j << \"}\" << std::endl;\n                    std::cerr << \"max_d = \" << max_d << std::endl;\n                }\n            }\n        }\n        return retval;\n    }\n\n    // objT should be indexable_type or aabb_type\n    template<typename objT>\n    std::pair<std::size_t, bool> pick_next(const boost::container::static_vector<\n            std::pair<std::size_t, objT>, max_entry+1>& entries,\n            const aabb_type& node, const aabb_type& ptnr)\n    {\n        std::cerr << \"pick_next\" << std::endl;\n        assert(!entries.empty());\n        bool is_node;\n        std::size_t idx;\n        scalar_type max_dd = -1;\n        for(std::size_t i=0; i<entries.size(); ++i)\n        {\n            aabb_type box1 = node; expand(box1, make_aabb(entries.at(i).second), this->boundary_);\n            aabb_type box2 = ptnr; expand(box2, make_aabb(entries.at(i).second), this->boundary_);\n            const scalar_type d1 = area(box1, this->boundary_) - area(node, this->boundary_);\n            const scalar_type d2 = area(box2, this->boundary_) - area(ptnr, this->boundary_);\n            const scalar_type dd = d1 - d2;\n            if(max_dd < std::abs(dd))\n            {\n                max_dd = std::abs(dd);\n                idx = i;\n                is_node = (dd < 0);\n            }\n        }\n        return std::make_pair(idx, is_node);\n    }\n\n    // split nodes because of new node NN by quadratic algorithm\n    std::size_t split_node(const std::size_t P, const std::size_t NN)\n    {\n        node_type& node = tree_.at(P);\n        const std::size_t PP = this->add_node(node_type(false, node.parent));\n        node_type& partner = tree_.at(PP);\n\n        std::cerr << \"split_node: node = \" << P << \", partner = \" << PP << std::endl;\n\n        boost::container::static_vector<std::pair<std::size_t, aabb_type>,\n            max_entry+1> entries;\n        entries.push_back(std::make_pair(NN, tree_.at(NN).box));\n        std::cerr << \"entry node \" << NN << \" = \";\n        to_svg(std::cerr, tree_.at(NN).box, this->boundary_);\n        std::cerr << std::endl;\n\n        for(typename node_type::const_iterator\n                i(node.entry.begin()), e(node.entry.end()); i != e; ++i)\n        {\n            entries.push_back(std::make_pair(*i, tree_.at(*i).box));\n\n            std::cerr << \"entry node \" << *i << \" = \";\n            to_svg(std::cerr, tree_.at(*i).box, this->boundary_);\n            std::cerr << std::endl;\n        }\n        node.entry.clear();\n        partner.entry.clear(); // for make it sure\n\n        /* assign first 2 entries to node and partner */{\n            const std::array<std::size_t, 2> seeds = this->pick_seeds(entries);\n            std::cerr << \"seeds = \" << entries.at(seeds[0]).first << \" for node, \"\n                      << entries.at(seeds[1]).first << \" for partner.\" << std::endl;\n\n               node.entry.push_back(entries.at(seeds[0]).first);\n            partner.entry.push_back(entries.at(seeds[1]).first);\n\n            tree_.at(entries.at(seeds[0]).first).parent = P;\n            tree_.at(entries.at(seeds[1]).first).parent = PP;\n\n            std::cerr << \"set box of node and partner\" << std::endl;\n               node.box = entries.at(seeds[0]).second;// these are AABB.\n            partner.box = entries.at(seeds[1]).second;\n\n            std::cerr << \"node(\" << P << \")    = \";\n            to_svg(std::cerr, node.box, this->boundary_);\n            std::cerr << std::endl;\n            std::cerr << \"partner(\" << PP << \") = \";\n            to_svg(std::cerr, partner.box, this->boundary_);\n            std::cerr << std::endl;\n\n            // remove them from entries pool\n            entries.erase(entries.begin() + std::min(seeds[0], seeds[1]));\n            entries.erase(entries.begin() + std::max(seeds[0], seeds[1]) - 1);\n        }\n\n        while(!entries.empty())\n        {\n            if(min_entry > node.entry.size() &&\n               min_entry - node.entry.size() >= entries.size())\n            {\n                std::cerr << \"min_entry = \" << min_entry\n                          << \", node.entry.size() = \" << node.entry.size()\n                          << \", entries.size() = \" << entries.size() << std::endl;\n                for(auto i(entries.begin()), e(entries.end()); i != e; ++i)\n                {\n                    node.entry.push_back(i->first);\n                    expand(node.box, i->second, this->boundary_);\n                }\n                return PP;\n            }\n            if(min_entry > partner.entry.size() &&\n               min_entry - partner.entry.size() >= entries.size())\n            {\n                std::cerr << \"min_entry = \" << min_entry\n                          << \", partner.entry.size() = \" << partner.entry.size()\n                          << \", entries.size() = \" << entries.size() << std::endl;\n                for(auto i(entries.begin()), e(entries.end()); i != e; ++i)\n                {\n                    partner.entry.push_back(i->first);\n                    expand(partner.box, i->second, this->boundary_);\n                }\n                return PP;\n            }\n\n            const std::pair<std::size_t, bool> next =\n                this->pick_next(entries, node.box, partner.box);\n            if(next.second) // next is partner\n            {\n                std::cerr << \"next entry \" << entries.at(next.first).first\n                          << \" is for node.\" << std::endl;\n                node.entry.push_back(entries.at(next.first).first);\n                tree_.at(entries.at(next.first).first).parent = P;\n                expand(node.box, entries.at(next.first).second, this->boundary_);\n\n                std::cerr << \"node expanded;\" << std::endl;\n                std::cerr << \"node(\" << P << \")    = \";\n                to_svg(std::cerr, node.box, this->boundary_);\n                std::cerr << std::endl;\n                std::cerr << \"partner(\" << PP << \") = \";\n                to_svg(std::cerr, partner.box, this->boundary_);\n                std::cerr << std::endl;\n            }\n            else // next is for partner\n            {\n                std::cerr << \"next entry \" << entries.at(next.first).first\n                          << \" is for partner.\" << std::endl;\n                partner.entry.push_back(entries.at(next.first).first);\n                tree_.at(entries.at(next.first).first).parent = PP;\n                expand(partner.box, entries.at(next.first).second, this->boundary_);\n\n                std::cerr << \"partner expanded;\" << std::endl;\n                std::cerr << \"node(\" << P << \")    = \";\n                to_svg(std::cerr, node.box, this->boundary_);\n                std::cerr << std::endl;\n                std::cerr << \"partner(\" << PP << \") = \";\n                to_svg(std::cerr, partner.box, this->boundary_);\n                std::cerr << std::endl;\n            }\n            entries.erase(entries.begin() + next.first);\n        }\n        tree_.at(P) = node;\n        tree_.at(PP) = partner;\n        std::cerr << \"node(\" << P << \")    = \";\n        to_svg(std::cerr, tree_.at(P).box, this->boundary_);\n        std::cerr << std::endl;\n        std::cerr << \"partner(\" << PP << \") = \";\n        to_svg(std::cerr, tree_.at(PP).box, this->boundary_);\n        std::cerr << std::endl;\n        std::cerr << \"all entries are inserted.\" << std::endl;\n        return PP;\n    }\n\n    template<typename Query, typename OutputIterator>\n    void query_impl(std::size_t node_idx, Query q, OutputIterator out) const\n    {\n        const node_type& node = tree_.at(node_idx);\n        if(node.is_leaf)\n        {\n            for(typename node_type::const_iterator\n                i(node.entry.begin()), e(node.entry.end()); i != e; ++i)\n            {\n                value_type const& val = container_.at(*i);\n                if(q.match(indexable::invoke(val)) && q.match(val))\n                {\n                    *out = val;\n                    ++out;\n                }\n            }\n        }\n        else\n        {\n            for(typename node_type::const_iterator\n                i(node.entry.begin()), e(node.entry.end()); i != e; ++i)\n            {\n                const std::size_t next = *i;\n                if(q.match(tree_.at(next).box))\n                {\n                    this->query_impl(next, q, out);\n                }\n            }\n        }\n        return;\n    }\n\n  private:\n\n    std::size_t level_of(std::size_t node_idx) const\n    {\n        std::size_t level = 0;\n        while(!(tree_.at(node_idx).is_leaf))\n        {\n            ++level;\n            node_idx = tree_.at(node_idx).entry.front();\n        }\n        return level;\n    }\n\n    void re_insert(const std::size_t N)\n    {\n        // reset connection to the parent!\n        std::cerr << \"re-insert node \" << N << std::endl;\n\n        // insert node to its proper parent. to find the parent of this node N,\n        // add 1 to level. root node should NOT come here.\n        const std::size_t lvl = level_of(N) + 1;\n        const aabb_type&  entry = tree_.at(N).box;\n        const std::size_t L = choose_node_with_level(entry, lvl);\n\n        std::cerr << \"its level is \" << lvl << std::endl;\n        std::cerr << \"its parents node is \" << lvl << std::endl;\n\n        if(tree_.at(L).has_enough_storage())\n        {\n            tree_.at(L).entry.push_back(N);\n            tree_.at(N).parent = L;\n            expand(tree_.at(L).box, entry, this->boundary_);\n            this->adjust_tree(L);\n        }\n        else\n        {\n            const std::size_t LL = this->split_node(L, N);\n            this->adjust_tree(L, LL);\n        }\n        return;\n    }\n\n    std::size_t choose_node_with_level(const aabb_type& entry, const std::size_t lvl)\n    {\n        std::size_t node_idx = this->root_;\n        if(level_of(this->root_) < lvl)\n        {\n            throw std::logic_error(\"root is under the node\");\n        }\n\n        while(level_of(node_idx) != lvl)\n        {\n            scalar_type diff_area_min = std::numeric_limits<scalar_type>::max();\n            scalar_type area_min      = std::numeric_limits<scalar_type>::max();\n\n            const node_type& node = this->tree_.at(node_idx);\n            for(typename node_type::const_iterator\n                    i(node.entry.begin()), e(node.entry.end()); i != e; ++i)\n            {\n                aabb_type box = tree_.at(*i).box;\n                const scalar_type area_initial = area(box, this->boundary_);\n\n                expand(box, entry, this->boundary_);\n\n                const scalar_type area_expanded = area(box, this->boundary_);\n                const scalar_type diff_area     = area_expanded - area_initial;\n                if(diff_area < diff_area_min ||\n                   (diff_area == diff_area_min && area_expanded < area_min))\n                {\n                    node_idx = *i;\n                    diff_area_min = diff_area;\n                    area_min = area_expanded;\n                }\n            }\n        }\n        return node_idx;\n    }\n\n    void condense_box(node_type& node)\n    {\n        assert(!node.entry.empty());\n        if(node.is_leaf)\n        {\n            std::cerr << \"leaf node has values {\";\n            for(auto i: node.entry)\n            {\n                std::cerr << i << \", \";\n            }\n            std::cerr << '}' << std::endl;\n\n            auto i = node.entry.cbegin();\n            node.box = indexable::invoke(this->container_.at(*i));\n            ++i;\n            for(auto e(node.entry.cend()); i != e; ++i)\n            {\n                expand(node.box, indexable::invoke(this->container_.at(*i)),\n                       this->boundary_);\n            }\n        }\n        else\n        {\n            std::cerr << \"internal node has values {\";\n            for(auto i: node.entry)\n            {\n                std::cerr << i << \", \";\n            }\n            std::cerr << '}' << std::endl;\n\n            auto i = node.entry.cbegin();\n            node.box = this->tree_.at(*i).box;\n            ++i;\n            for(auto e(node.entry.cend()); i != e; ++i)\n            {\n                expand(node.box, this->tree_.at(*i).box, this->boundary_);\n            }\n        }\n        return;\n    }\n\n  private:\n\n    std::size_t add_value(const value_type& v)\n    {\n        if(overwritable_values_.empty())\n        {\n            const std::size_t idx = container_.size();\n            container_.push_back(v);\n            return idx;\n        }\n        else\n        {\n            const std::size_t idx = overwritable_values_.back();\n            overwritable_values_.pop_back();\n            container_.at(idx) = v;\n            return idx;\n        }\n    }\n    void erase_value(const std::size_t i)\n    {\n        overwritable_values_.push_back(i);\n        return;\n    }\n\n    std::size_t add_node(const node_type& n)\n    {\n        if(overwritable_nodes_.empty())\n        {\n            const std::size_t idx = tree_.size();\n            tree_.push_back(n);\n            return idx;\n        }\n        else\n        {\n            const std::size_t idx = overwritable_nodes_.back();\n            overwritable_nodes_.pop_back();\n            tree_.at(idx) = n;\n            return idx;\n        }\n    }\n    void erase_node(const std::size_t i)\n    {\n        overwritable_nodes_.push_back(i);\n        return;\n    }\n\n  private:\n\n    std::size_t       root_;\n    equal_to_type     equal_to_;\n    boundary_type     boundary_;\n    tree_type         tree_;\n    container_type    container_;\n    index_buffer_type overwritable_values_;\n    index_buffer_type overwritable_nodes_;\n};\n\n\n} // perior\n#endif//PERIOR_TREE_RTREE_HPP\n", "meta": {"hexsha": "0ce2a95c5ccc7e326047ac42ed6d4b6a9cb1a636", "size": 34327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "experimental/rtree.hpp", "max_stars_repo_name": "lasergyro/periortree", "max_stars_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T14:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T11:11:50.000Z", "max_issues_repo_path": "experimental/rtree.hpp", "max_issues_repo_name": "lasergyro/periortree", "max_issues_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-14T03:37:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-14T12:16:29.000Z", "max_forks_repo_path": "experimental/rtree.hpp", "max_forks_repo_name": "lasergyro/periortree", "max_forks_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-14T03:52:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T15:49:30.000Z", "avg_line_length": 35.9069037657, "max_line_length": 108, "alphanum_fraction": 0.5139394646, "num_tokens": 8055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.18248227404489664}}
{"text": "/*\n * Copyright 2010,\n * Fran\u00e7ois Bleibel,\n * Olivier Stasse,\n *\n * CNRS/AIST\n *\n */\n\n/* --------------------------------------------------------------------- */\n/* --- INCLUDE --------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n\n//#define WITH_CHRONO\n\n//#define VP_DEBUG\n//#define VP_DEBUG_MODE 45\n#include <sot/core/debug.hh>\n\n#include <sot/core/solver-hierarchical-inequalities.hh>\nusing namespace dynamicgraph::sot;\n\n#ifndef WIN32\n#include <sys/time.h>\n#else\n#include <sot/core/utils-windows.hh>\n#endif /*WIN32*/\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#define FORTRAN_ID(id) id##_\n\n/* ---------------------------------------------------------- */\n/* --- BINDING FORTRAN -------------------------------------- */\n/* ---------------------------------------------------------- */\n#define LAPACK_DGEQP3 FORTRAN_ID(dgeqp3)\n#define LAPACK_DGEQPF FORTRAN_ID(dgeqpf)\nextern \"C\" {\nvoid LAPACK_DGEQP3(const int *m, const int *n, double *a, const int *lda,\n                   int *jpvt, double *tau, double *work, const int *lwork,\n                   int *info);\nvoid LAPACK_DGEQPF(const int *m, const int *n, double *a, const int *lda,\n                   int *jpvt, double *tau, double *work, int *info);\n}\n\nnamespace boost {\nnamespace numeric {\nnamespace bindings {\nnamespace lapack {\n\ntemplate <typename bubTemplateMatrix>\ninline int geqp(bubTemplateMatrix &A, bub::vector<int> &jp, bubVector &tau) {\n  int const mF = A.size1();\n  int const nF = A.size2();\n  if ((nF == 0) || (mF == 0))\n    return 0;\n  ::boost::numeric::ublas::vector<double> work(std::max(1, nF * 32));\n\n  assert(nF <= (int)tau.size());\n  assert(nF <= (int)work.size());\n\n  ::boost::numeric::ublas::matrix<double> tmpA;\n  tmpA = A;\n  double *aF = MRAWDATA(tmpA);\n\n  int const ldaF = traits::leading_dimension(A);\n  int *jpvtF = VRAWDATA(jp);\n  double *tauF = VRAWDATA(tau);\n  double *workF = VRAWDATA(work);\n  int const lworkF = work.size();\n  int infoF;\n\n  LAPACK_DGEQP3(&mF, &nF, aF, &ldaF, jpvtF, tauF, workF, &lworkF, &infoF);\n  // LAPACK_DGEQPF(&mF, &nF, aF, &ldaF, jpvtF, tauF, workF, &infoF);\n  return infoF;\n}\n\n} // namespace lapack\n} // namespace bindings\n} // namespace numeric\n} // namespace boost\n\ntemplate <typename bubTemplateMatrix>\nvoid bubRemoveColumn(bubTemplateMatrix &M, const unsigned int col) {\n  for (unsigned int j = col; j < M.size2() - 1; ++j)\n    for (unsigned int i = 0; i < M.size1(); ++i)\n      M(i, j) = M(i, j + 1);\n  for (unsigned int i = 0; i < M.size1(); ++i)\n    M(i, M.size2() - 1) = 0;\n}\nvoid bubRemoveColumn(bub::triangular_matrix<double, bub::upper> &M,\n                     const unsigned int col) {\n  for (unsigned int j = col; j < M.size2() - 1; ++j)\n    for (unsigned int i = 0; i <= j; ++i)\n      M(i, j) = M(i, j + 1);\n  for (unsigned int i = 0; i < M.size1(); ++i)\n    M(i, M.size2() - 1) = 0;\n}\ntemplate <typename bubTemplateMatrix>\nvoid bubRemoveColumn(bub::triangular_adaptor<bubTemplateMatrix, bub::upper> M,\n                     const unsigned int col) {\n  for (unsigned int j = col; j < M.size2() - 1; ++j)\n    for (unsigned int i = 0; i <= j; ++i)\n      M(i, j) = M(i, j + 1);\n  for (unsigned int i = 0; i < std::min(M.size1(), M.size2()); ++i)\n    M(i, M.size2() - 1) = 0;\n}\n\nbub::indirect_array<> &operator+=(bub::indirect_array<> &order,\n                                  unsigned int _el) {\n  const unsigned int N = order.size();\n  bub::indirect_array<> o2(N + 1);\n  //  std::copy(order.begin(),order.end(),o2.data().begin()); // Not working!\n  //  Why?\n  for (unsigned int i = 0; i < N; ++i)\n    o2[i] = order[i];\n  o2[N] = _el;\n  return order = o2;\n}\n\nbub::indirect_array<> &operator-=(bub::indirect_array<> &order,\n                                  unsigned int _el) {\n  const unsigned int N = order.size();\n  bub::indirect_array<> o2(N - 1);\n  unsigned int newi = 0;\n  for (unsigned int i = 0; i < N; ++i) {\n    if (newi == N) {\n      std::cerr << \"Error while removing one elmt of <order>.\" << std::endl;\n      throw \"Error while removing one elmt of <order>.\";\n    }\n    if (order[i] != _el)\n      o2[newi++] = order[i];\n  }\n  return order = o2;\n}\n\n/* ---------------------------------------------------------- */\n/* ---------------------------------------------------------- */\n/* ---------------------------------------------------------- */\n\nConstraintMem::ConstraintMem(const ConstraintMem &clone)\n    : active(clone.active), equality(clone.equality), notToBeConsidered(false),\n      Ji(0), eiInf(clone.eiInf), eiSup(clone.eiSup), boundSide(clone.boundSide),\n      activeSide(clone.activeSide), rankIncreaser(clone.rankIncreaser),\n      constraintRow(clone.constraintRow), range(clone.range),\n      lagrangian(clone.lagrangian), Ju(clone.Ju), Jdu(clone.Jdu) {\n  if (clone.Ji.size()) {\n    Ji.resize(clone.Ji.size(), false);\n    Ji.assign(clone.Ji);\n  }\n  sotDEBUG(15) << \"ConstraintMem cloning\" << std::endl;\n}\n\nnamespace dynamicgraph {\nnamespace sot {\nstd::ostream &operator<<(std::ostream &os,\n                         const ConstraintMem::BoundSideType &bs) {\n  switch (bs) {\n  case ConstraintMem::BOUND_VOID:\n    os << \"#\";\n    break;\n  case ConstraintMem::BOUND_INF:\n    os << \"-\";\n    break;\n  case ConstraintMem::BOUND_SUP:\n    os << \"+\";\n    break;\n  case ConstraintMem::BOUND_BOTH:\n    os << \"+/-\";\n    break;\n  }\n  return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const ConstraintMem &c) {\n  os << \"Cs[\" << c.constraintRow << \"] \" << std::endl;\n  if (c.Ji.size())\n    os << \"\" << c.Ji;\n  if (c.boundSide & ConstraintMem::BOUND_INF)\n    os << \"/[-]\" << c.eiInf;\n  if (c.boundSide & ConstraintMem::BOUND_SUP)\n    os << \"/[+]\" << c.eiSup;\n  if (c.active) {\n    os << \"\\n\\t-> active [\" << c.activeSide << \"] <rg=\" << c.range << \"> \"\n       << std::endl\n       << \"\\t-> \";\n    if (c.rankIncreaser)\n      os << \"rank-inc \";\n    else {\n      os << \"non-rank-inc\";\n    }\n    if (c.lagrangian != 0)\n      os << std::endl << \"\\t-> l=\" << c.lagrangian;\n    if (c.equality)\n      os << std::endl << \"\\t-> blocked(equality)\";\n    else\n      os << std::endl << \"\\t-> floating(inequality)\";\n  } else {\n    if (c.notToBeConsidered)\n      os << \"\\n\\t->not to be considered\";\n    else\n      os << \"\\n\\t-> inactive\";\n  }\n  return os;\n}\n\n} /* namespace sot */\n} /* namespace dynamicgraph */\n\n/* ---------------------------------------------------------- */\n/* Specify the size of the constraint matrix, for pre-alocation. */\nvoid SolverHierarchicalInequalities::initConstraintSize(\n    const unsigned int size) {\n  if (Rh.size1() != nJ) {\n    Rh.resize(nJ, nJ, false);\n    Rh.clear();\n  }\n  rankh = 0;\n  u0.resize(nJ, false);\n  u0.clear();\n  // constraintH.reserve(size);\n  constraintS.reserve(size + 1);\n}\n\nvoid SolverHierarchicalInequalities::setInitialCondition(\n    const bubVector &_u0, const unsigned int _rankh) {\n  u0.resize(nJ, false);\n  u0.assign(_u0);\n  rankh = _rankh;\n  freeRank = nJ - rankh;\n}\n\nvoid SolverHierarchicalInequalities::setInitialConditionVoid(void) {\n  u0.resize(nJ, false);\n  u0.clear();\n  rankh = 0;\n  freeRank = nJ;\n}\nvoid SolverHierarchicalInequalities::setNbDof(const unsigned int _nJ) {\n  sotDEBUGIN(15);\n  if (nJ == _nJ)\n    return;\n  nJ = _nJ;\n  Qh.resize(nJ);\n  Rh.resize(nJ, nJ);\n  sotDEBUGOUT(15);\n}\n\n/* ---------------------------------------------------------- */\n\nvoid SolverHierarchicalInequalities::recordInitialConditions(void) {\n  initialActiveH.resize(constraintH.size());\n  initialSideH.resize(constraintH.size());\n  std::vector<bool>::iterator iterBool = initialActiveH.begin();\n  ConstraintMem::BoundSideVector::iterator iterSide = initialSideH.begin();\n  ConstraintList::const_iterator iterCH = constraintH.begin();\n  for (; iterCH != constraintH.end(); ++iterBool, ++iterCH, ++iterSide) {\n    sotDEBUG(45) << \"Initial \" << iterCH->activeSide << iterCH->active\n                 << std::endl;\n    (*iterBool) = iterCH->active;\n    (*iterSide) = iterCH->activeSide;\n    sotDEBUG(45) << \"Initial \" << (*iterSide) << (*iterBool) << std::endl;\n  }\n\n  du0.resize(u0.size(), false);\n  du0.assign(-u0);\n}\nvoid SolverHierarchicalInequalities::computeDifferentialCondition(void) {\n  if (constraintH.size() > initialActiveH.size()) {\n    std::vector<bool>::const_iterator iterBool = initialActiveH.begin();\n    ConstraintList::iterator iterCH = constraintH.begin();\n    ConstraintMem::BoundSideVector::const_iterator iterSide =\n        initialSideH.begin();\n    toActivate.clear();\n    toInactivate.clear();\n    for (; iterBool != initialActiveH.end(); ++iterBool, ++iterCH, ++iterSide) {\n      ConstraintMem &ch = *iterCH;\n      sotDEBUG(45) << \"Initial \" << (*iterSide) << (*iterBool) << \" - Final \"\n                   << ch.activeSide << ch.active << std::endl;\n      /* Constraint was active, and is not anymore or changed side. */\n      if ((*iterBool) && ((!ch.active) || (*iterSide != ch.activeSide))) {\n        toInactivate.push_back(ConstraintRef(ch.constraintRow));\n      }\n      /* Constraint is now active, but was inactive or changed side. */\n      if ((ch.active) && ((!(*iterBool)) || (*iterSide != ch.activeSide))) {\n        toActivate.push_back(ConstraintRef(ch.constraintRow, ch.activeSide));\n      }\n    }\n  }\n  du0 += u0;\n\n  /* Compute the slack set to be initialize at first iteration. */\n  unsigned int i = 0;\n  slackActiveSet.resize(constraintSactive.size());\n  for (ConstraintRefList::const_iterator iter = constraintSactive.begin();\n       iter != constraintSactive.end(); ++iter, ++i) {\n    slackActiveSet[i].id = (*iter)->constraintRow;\n    slackActiveSet[i].side = (*iter)->activeSide;\n  }\n\n  warmStartReady = true;\n}\n\nvoid SolverHierarchicalInequalities::printDifferentialCondition(\n    std::ostream &os) const {\n  if (!warmStartReady)\n    return;\n\n  os << \"To activate = { \";\n  for (std::vector<ConstraintRef>::const_iterator iterCH = toActivate.begin();\n       toActivate.end() != iterCH; ++iterCH) {\n    os << *iterCH << \", \";\n  }\n  os << \" }\" << std::endl;\n\n  os << \"To inactivate = { \";\n  for (std::vector<ConstraintRef>::const_iterator iterCH = toInactivate.begin();\n       toInactivate.end() != iterCH; ++iterCH) {\n    os << *iterCH << \", \";\n  }\n  os << \" }\" << std::endl;\n\n  os << \"Active slack = { \";\n  for (std::vector<ConstraintRef>::const_iterator iter = slackActiveSet.begin();\n       iter != slackActiveSet.end(); ++iter) {\n    os << (*iter) << \", \";\n  }\n  os << \" }\" << std::endl;\n\n  os << \"du = \" << (MATLAB)du0 << std::endl;\n}\n\n/* ---------------------------------------------------------- */\n\n// SolverHierarchicalInequalities::bubMatrixQROrdered\n// SolverHierarchicalInequalities::\n// accessQRs( void )\n// {\n//   bubMatrixQR QRs( QhJsU,freerange(),bub::range::all() );\n//   bubMatrixQROrdered QRord( QRs,bubOrder::all(),orderS );\n//   return QRord;\n// }\n// SolverHierarchicalInequalities::bubMatrixQROrderedConst\n// SolverHierarchicalInequalities::\n// accessQRs( void ) const\n// {\n//   bubMatrixQRConst QRs( QhJsU,freerange(),bub::range::all() );\n//   bubMatrixQROrderedConst QRord( QRs,bubOrder::all(),orderS );\n//   return QRord;\n// }\n// SolverHierarchicalInequalities::bubMatrixQROrderedTri\n// SolverHierarchicalInequalities::\n// accessRs( void )\n// {\n//   bubMatrixQR QRs( QhJsU,freeranges(),bub::range::all() );\n//    bubMatrixQROrdered QRord( QRs,bubOrder::all(),orderS );\n//    return QRord;\n//  }\nSolverHierarchicalInequalities::bubMatrixQROrderedTriConst\nSolverHierarchicalInequalities::accessRsConst(void) const {\n  bubMatrixQRConst QRs(QhJsU, freeranges(), bub::range(0, sizes));\n  bubOrder iall(ranks);\n  for (unsigned int i = 0; i < ranks; ++i)\n    iall(i) = i;\n  bubMatrixQROrderedConst QRord(QRs, iall, orderS);\n  return QRord;\n}\n\nbub::triangular_adaptor<bub::matrix_range<const bubMatrix>, bub::upper>\nSolverHierarchicalInequalities::accessRhConst(void) const {\n  bub::matrix_range<const bubMatrix> Rhup(Rh, rangeh(), rangeh());\n  return Rhup;\n}\n\nbub::triangular_adaptor<bub::matrix_range<bubMatrix>, bub::upper>\nSolverHierarchicalInequalities::accessRh(void) {\n  bub::matrix_range<bubMatrix> Rhup(Rh, rangeh(), rangeh());\n  return Rhup;\n}\n\n/* Assuming a diagonal-ordered triangular matrix. */\ntemplate <typename bubTemplateMatrix>\nunsigned int\nSolverHierarchicalInequalities::rankDetermination(const bubTemplateMatrix &A,\n                                                  const double threshold) {\n  unsigned int res = 0;\n  for (unsigned int i = 0; i < std::min(A.size1(), A.size2()); ++i) {\n    if (fabs(A(i, i)) > threshold)\n      res++;\n    else\n      break;\n  }\n  return res;\n}\n\n/* ---------------------------------------------------------- */\n#ifdef VP_DEBUG\nvoid SolverHierarchicalInequalities::displayConstraint(ConstraintList &cs) {\n  for (ConstraintList::iterator iter = cs.begin(); iter != cs.end(); ++iter) {\n    ConstraintMem &ci = *iter;\n    sotDEBUG(25) << ci << std::endl;\n  }\n}\n#else\nvoid SolverHierarchicalInequalities::displayConstraint(ConstraintList &) {}\n#endif //#ifdef VP_DEBUG\n\nvoid SolverHierarchicalInequalities::printDebug(void) {\n#ifdef VP_DEBUG\n  sotDEBUG(15) << \"constraintSactive:\" << std::endl;\n  for (ConstraintRefList::const_iterator iter = constraintSactive.begin();\n       iter != constraintSactive.end(); ++iter) {\n    ConstraintMem &cs = **iter;\n    sotDEBUG(15) << \"+\" << cs << std::endl;\n  }\n\n  sotDEBUG(45) << \"Sconstraints :: \" << std::endl;\n  displayConstraint(constraintS);\n\n  sotDEBUG(25) << \"Hconstraints :: \" << std::endl;\n  displayConstraint(constraintH);\n\n  bubMatrix Jh(rankh, nJ); /***/\n  std::fill(Jh.data().begin(), Jh.data().end(), -1);\n  for (ConstraintList::iterator iter = constraintH.begin();\n       iter != constraintH.end(); ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.active && cs.rankIncreaser) {\n      if (cs.notToBeConsidered)\n        continue;\n      if (cs.range < rankh) {\n        bub::row(Jh, cs.range).assign(cs.Ji);\n      } else {\n        sotDEBUG(1) << \"!!!\" << cs << std::endl;\n      }\n    }\n  }\n  sotDEBUG(15) << \"rankh = \" << rankh << std::endl;\n  sotDEBUG(15) << \"Jh = \" << (MATLAB)Jh << std::endl;\n  sotDEBUG(15) << \"Qh = \" << MATLAB(Qh, nJ) << std::endl;\n  sotDEBUG(15) << \"QhJs = \" << (MATLAB)bub::subrange(QhJs, 0, nJ, 0, sizes)\n               << std::endl;\n  sotDEBUG(15) << \"QhJsU = \" << (MATLAB)bub::subrange(QhJsU, 0, nJ, 0, sizes)\n               << std::endl;\n  sotDEBUG(15) << \"u0 = \" << MATLAB(u0) << std::endl;\n  {\n    bubMatrix toto(nJ, nJ);\n    toto = bub::prod(QhJs, bub::trans(QhJs));\n    bubMatrix tata(nJ, nJ);\n    tata = bub::prod(QhJsU, bub::trans(QhJsU));\n    toto -= tata;\n    sotDEBUG(45) << \"dQJJQ = \" << (MATLAB)toto << std::endl;\n  }\n\n  bubMatrix Jht(bub::trans(Jh));\n  Qh.multiplyRightTranspose(Jht);\n  bub::matrix_range<bubMatrix> Jht0(Jht, rangeh(), bub::range(0, rankh));\n  sotDEBUG(55) << \"QJh = \" << (MATLAB)Jht0 << std::endl;\n  Jht0 -= bub::matrix_range<bubMatrix>(Rh, rangeh(), rangeh());\n  sotDEBUG(55) << \"Rh = \" << (MATLAB)Rh << std::endl;\n  sotDEBUG(55) << \"Rh_QhJh = \" << (MATLAB)Jht0 << std::endl;\n  sotDEBUG(15) << \"||Rh_QhJh|| = \" << bub::norm_1(Jht0) << std::endl;\n\n  bubMatrix Js(sizes, nJ);\n  for (ConstraintRefList::iterator iter = constraintSactive.begin();\n       iter != constraintSactive.end(); ++iter) {\n    ConstraintMem &cs = **iter;\n    if (cs.active) {\n      if (cs.range < sizes) {\n        bub::row(Js, cs.range).assign(cs.Ji);\n      } else {\n        sotDEBUG(1) << \"!!!\" << cs << std::endl;\n      }\n    }\n  }\n  sotDEBUG(45) << \"Js = \" << (MATLAB)Js << std::endl;\n  sotDEBUG(45) << \"QhJs = \" << (MATLAB)QhJs << std::endl;\n\n  bubMatrix Jst(bub::trans(Js));\n  Qh.multiplyRightTranspose(Jst);\n  Jst -= bub::subrange(QhJs, 0, nJ, 0, sizes);\n  sotDEBUG(15) << \"||Rs_QhJs|| = \" << bub::norm_1(Jst) << std::endl;\n\n#endif // ifdef VP_DEBUG\n}\n\n/* ---------------------------------------------------------- */\n/* ---------------------------------------------------------- */\n/* ---------------------------------------------------------- */\n\nvoid SolverHierarchicalInequalities::warmStart(void) {\n  if (!warmStartReady)\n    return;\n  ConstraintRefList toInactivateCH;\n  for (std::vector<ConstraintRef>::const_iterator iter = toInactivate.begin();\n       iter != toInactivate.end(); ++iter) {\n    toInactivateCH.push_back(&constraintH[iter->id]);\n  }\n  if (toInactivateCH.size() > 0)\n    forceDowndateHierachic(toInactivateCH);\n\n  applyFreeSpaceMotion(du0);\n\n  ConstraintRefList toActivateCH;\n  ConstraintMem::BoundSideVector toActivateSide;\n  for (std::vector<ConstraintRef>::const_iterator iter = toActivate.begin();\n       iter != toActivate.end(); ++iter) {\n    toActivateCH.push_back(&constraintH[iter->id]);\n    toActivateSide.push_back(iter->side);\n  }\n  if (toActivateCH.size() > 0)\n    forceUpdateHierachic(toActivateCH, toActivateSide);\n}\n\nvoid SolverHierarchicalInequalities::applyFreeSpaceMotion(\n    const bubVector &_du) {\n  printDebug();\n  du.assign(_du);\n  sotDEBUG(15) << \"du = \" << (MATLAB)du << std::endl;\n  /* Multiply by Ph. */\n  Qh.multiplyRangeLeft(du, rankh, 0);\n  Qh.multiplyRight(du);\n  sotDEBUG(15) << \"Phdu = \" << (MATLAB)du << std::endl;\n\n  double tau;\n  selecActivationHierarchic(tau);\n  sotDEBUG(5) << \"Warm start du limited by tau=\" << tau << std::endl;\n  du *= tau;\n  u0 += du;\n}\n\nvoid SolverHierarchicalInequalities::forceUpdateHierachic(\n    ConstraintRefList &toUpdate,\n    const ConstraintMem::BoundSideVector &boundSide) {\n  {\n    sotDEBUG(5) << \"Now activating { \";\n    ConstraintMem::BoundSideVector::const_iterator iterBound =\n        boundSide.begin();\n    for (ConstraintRefList::const_iterator iterCH = toUpdate.begin();\n         toUpdate.end() != iterCH; ++iterCH, ++iterBound) {\n      sotDEBUGMUTE(5) << *iterBound << (*iterCH)->constraintRow << \", \";\n    }\n    sotDEBUGMUTE(5) << \" }\" << std::endl;\n  }\n\n  sotDEBUG(15) << \"/* Create the matrix Js by concatenation of matrix cs.Ji. */\"\n               << std::endl;\n  unsigned int sizes = toUpdate.size();\n  bubMatrix _Jse(sizes, nJ);\n  bubVector _ese(sizes);\n\n  unsigned int col = 0;\n  ConstraintMem::BoundSideVector::const_iterator iterBound = boundSide.begin();\n  for (ConstraintRefList::iterator iter = toUpdate.begin();\n       toUpdate.end() != iter; ++iter, ++iterBound) {\n    ConstraintMem &cs = **iter;\n    if (!cs.active) {\n      sotDEBUG(1) << \"Activation WSH <\" << *iterBound << cs.constraintRow << \">\"\n                  << std::endl;\n\n      sotDEBUG(45) << cs << std::endl;\n      bub::row(_Jse, col).assign(cs.Ji);\n      if ((*iterBound) == ConstraintMem::BOUND_INF)\n        _ese(col) = cs.eiInf;\n      else\n        _ese(col) = cs.eiSup;\n      col++;\n      cs.active = false;\n      cs.notToBeConsidered = true;\n      cs.activeSide = *iterBound;\n    } else {\n      sotDEBUG(1) << \"Error: <\" << cs.constraintRow << \"> is already active. \"\n                  << std::endl;\n    }\n  }\n  sotDEBUG(45) << \"Jwsh = \" << (MATLAB)_Jse << std::endl;\n  if (sizes > col) {\n    sizes = col;\n    _Jse.resize(sizes, nJ, true);\n    _ese.resize(sizes, true);\n  }\n  sotDEBUG(25) << \"Jwsh = \" << (MATLAB)_Jse << std::endl;\n\n  sotDEBUG(15) << \"/* Solve these constraints. */\" << std::endl;\n  bubMatrix _Jsi(0, 0);\n  bubVector _esiInf(0), _esiSup(0);\n  std::vector<ConstraintMem::BoundSideType> _esiBound(0);\n  solve(_Jse, _ese, _Jsi, _esiInf, _esiSup, _esiBound, false);\n\n  sotDEBUG(15) << \"/* Copy S in H. */\" << std::endl;\n  /* Pe is the range of the actual column of QR in the original\n   * matrix: QR[:,i] == Jse'[:,pe(i)]. */\n  sotDEBUG(15) << \"orderS = \" << (MATLAB)orderS << std::endl;\n  //   for( ConstraintList::iterator iter=constraintS.begin();\n  //        constraintS.end() != iter;++iter )\n  //     {\n  //       ConstraintMem & cs = *iter;\n  //       ConstraintMem & ch = *toUpdate[cs.constraintRow];\n  unsigned int rangeInS = 0;\n  for (ConstraintRefList::iterator iter = toUpdate.begin();\n       toUpdate.end() != iter; ++iter) {\n    ConstraintMem &ch = **iter;\n    if (!ch.notToBeConsidered)\n      continue;\n    ConstraintMem &cs = constraintS[rangeInS++];\n    ch.range = cs.range + rankh;\n    ch.rankIncreaser = cs.rankIncreaser;\n    ch.equality = false; // TODO: ?? lock a constraint ??\n    ch.notToBeConsidered = false;\n    ch.active = true;\n    sotDEBUG(15) << \"Add eq FR: \" << ch << std::endl;\n  }\n\n  sotDEBUG(15) << \"/* Copy a triangular of Rs in Rh. */\" << std::endl;\n  sotRotationComposed Qlast;\n  for (unsigned int i = 0; i < ranks; ++i) {\n    typedef bub::matrix_column<bubMatrixQRWide> bubQJsCol;\n    bubQJsCol QJk(QhJs, orderS(i));\n    Qlast.multiplyLeft(QJk);\n    sotDEBUG(45) << \"QhJs_\" << i << \" = \" << (MATLAB)QJk << std::endl;\n    bub::vector_range<bubQJsCol> Ftdown(QJk, freerange());\n    double beta;\n    double normSignFt // Norm with sign!\n        = sotRotationSimpleHouseholder::householderExtraction(Ftdown, beta,\n                                                              THRESHOLD_ZERO);\n    sotDEBUG(45) << \"Ft_\" << i << \" = \" << (MATLAB)Ftdown << std::endl;\n    sotDEBUG(45) << \"b_\" << i << \" = \" << beta << std::endl;\n    if (fabs(beta) > THRESHOLD_ZERO) {\n      Qlast.pushBack(sotRotationSimpleHouseholder(Ftdown, beta));\n    }\n\n    bub::matrix_column<bubMatrix> Rhk(Rh, rankh);\n    bub::project(Rhk, rangeh()).assign(bub::project(QJk, rangeh()));\n    bub::project(Rhk, freerange()).assign(bub::zero_vector<double>(freeRank));\n    Rh(rankh, rankh) = normSignFt;\n    sotDEBUG(45) << \"Rh_\" << i << \" = \" << (MATLAB)Rhk << std::endl;\n\n    rankh++;\n    freeRank--;\n  }\n  Qh.pushBack(Qlast);\n}\n\nvoid SolverHierarchicalInequalities::forceDowndateHierachic(\n    ConstraintRefList &toDowndate) {\n  {\n    sotDEBUG(5) << \"Now inactivating { \";\n    for (ConstraintRefList::const_iterator iterCH = toDowndate.begin();\n         toDowndate.end() != iterCH; ++iterCH) {\n      sotDEBUGMUTE(5) << (*iterCH)->constraintRow << \", \";\n    }\n    sotDEBUGMUTE(5) << \" }\" << std::endl;\n  }\n\n  unsigned int rankhDec = 0;\n\n  sotDEBUG(15) << \"/* Precompute the new structure of Rh matrix. */\"\n               << std::endl;\n  std::vector<bool> colDeleted(rankh, false);\n  std::vector<unsigned int> colOffset(rankh);\n  for (ConstraintRefList::iterator iter = toDowndate.begin();\n       toDowndate.end() != iter; ++iter) {\n    ConstraintMem &cs = **iter;\n    if (cs.active && cs.rankIncreaser) {\n      sotDEBUG(1) << \"Inactivation WSH <\" << cs.activeSide << cs.constraintRow\n                  << \">\" << std::endl;\n      sotDEBUG(45) << \"Force downdate cs \" << cs << std::endl;\n      const unsigned int range = cs.range;\n      colDeleted[range] = true;\n      ++rankhDec;\n      cs.active = false;\n    } else {\n      sotDEBUG(1) << \"Can not force down inactive constraint \"\n                  << cs.constraintRow << std::endl;\n    }\n  }\n\n  {\n    unsigned int offset = 0;\n    for (unsigned int i = 0; i < rankh; ++i) {\n      if (colDeleted[i])\n        offset++;\n      else\n        colOffset[i] = offset;\n    }\n  }\n\n  for (ConstraintList::iterator iter = constraintH.begin();\n       constraintH.end() != iter; ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.active) {\n      const unsigned int range = cs.range;\n      cs.range -= colOffset[range];\n    }\n  }\n\n  sotDEBUG(15) << \"/* Reduce the Rh matrix. */\" << std::endl;\n  for (unsigned int j = 0; j < rankh; ++j) {\n    const unsigned int offset = colOffset[j];\n    if ((!colDeleted[j]) && (offset > 0)) {\n      sotDEBUG(15) << \"Copy \" << j << \" in \" << j - offset << std::endl;\n      for (unsigned int i = 0; i < rankh; ++i) {\n        Rh(i, j - offset) = Rh(i, j);\n      }\n    }\n  }\n  rankh -= rankhDec;\n  freeRank += rankhDec;\n\n  sotDEBUG(15) << \"/* Correct the pseudo-hessenberg matrix. */\" << std::endl;\n  bub::matrix_range<bubMatrix> Rhlim(Rh, bub::range(0, rankh + rankhDec),\n                                     rangeh());\n  sotDEBUG(15) << \"Rh_hess = \" << (MATLAB)Rhlim << std::endl;\n  for (unsigned int j = 0; j < rankh + rankhDec; ++j) {\n    const unsigned int offset = colOffset[j];\n    if ((!colDeleted[j]) && (offset > 0)) {\n      for (unsigned int i = 0; i < offset; ++i) {\n        sotRotationSimpleGiven Gr(Rh, j - i - 1, j - i, j - offset);\n        Gr.inverse();\n        Gr.multiplyRightTranspose(Rhlim);\n        Qh.pushBack(Gr);\n        sotDEBUG(55) << \"Rh_down\" << j << \"x\" << i << \" = \" << (MATLAB)Rh\n                     << std::endl;\n        sotDEBUG(55) << \"Gr\" << j << \"x\" << i << \" = \" << Gr << std::endl;\n      }\n    }\n  }\n  sotDEBUG(5) << \"Rh_down = \" << (MATLAB)accessRh() << std::endl;\n\n  sotDEBUG(15) << \"/* Activate rankd-def constraints. */\" << std::endl;\n  for (ConstraintList::iterator iter = constraintH.begin();\n       constraintH.end() != iter; ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.active && (!cs.rankIncreaser)) {\n      bubVector QJk(cs.Ji);\n      Qh.multiplyLeft(QJk);\n      if (fabs(QJk(rankh)) > THRESHOLD_ZERO) {\n        sotDEBUG(5) << \"No rank loss when force downdating => \"\n                    << cs.constraintRow << std::endl;\n        bub::vector_range<bubVector> Ftdown(QJk, freerange());\n        double beta;\n        double normSignFt // Norm with sign!\n            = sotRotationSimpleHouseholder::householderExtraction(\n                Ftdown, beta, THRESHOLD_ZERO);\n        sotDEBUG(45) << \"Ft_\"\n                     << \" = \" << (MATLAB)Ftdown << std::endl;\n        sotDEBUG(45) << \"b_\"\n                     << \" = \" << beta << std::endl;\n        if (fabs(beta) > THRESHOLD_ZERO) {\n          Qh.pushBack(sotRotationSimpleHouseholder(Ftdown, beta));\n        }\n\n        bub::matrix_column<bubMatrix> Rhk(Rh, rankh);\n        bub::project(Rhk, rangeh()).assign(bub::project(QJk, rangeh()));\n        bub::project(Rhk, freerange())\n            .assign(bub::zero_vector<double>(freeRank));\n        Rh(rankh, rankh) = normSignFt;\n        sotDEBUG(45) << \"Rh\"\n                     << \" = \" << (MATLAB)Rhk << std::endl;\n\n        cs.range = rankh;\n        cs.rankIncreaser = true;\n        rankh++;\n        freeRank--;\n      }\n    }\n  }\n}\n\n/* ---------------------------------------------------------- */\n/* ---------------------------------------------------------- */\n/* ---------------------------------------------------------- */\n#ifdef WITH_CHRONO\n#define SOT_DEFINE_CHRONO                                                      \\\n  struct timeval t0, t1;                                                       \\\n  double dtsolver\n#define SOT_INIT_CHRONO gettimeofday(&t0, NULL)\n#define SOT_CHRONO(txt)                                                        \\\n  gettimeofday(&t1, NULL);                                                     \\\n  dtsolver = (t1.tv_sec - t0.tv_sec) * 1000. +                                 \\\n             (t1.tv_usec - t0.tv_usec + 0.) / 1000.;                           \\\n  std::cout << \"t_\" << txt << \" = \" << dtsolver << \" %ms\" << std::endl;        \\\n  gettimeofday(&t0, NULL)\n#else // ifdef WITH_CHRONO\n#define SOT_DEFINE_CHRONO\n#define SOT_INIT_CHRONO\n#define SOT_CHRONO(txt)\n#endif // ifdef WITH_CHRONO\n\n/* ---------------------------------------------------------- */\n\nSOT_DEFINE_CHRONO\nvoid SolverHierarchicalInequalities::solve(\n    const bubMatrix &Jse, const bubVector &ese, const bubMatrix &Jsi,\n    const bubVector &esiInf, const bubVector &esiSup,\n    const std::vector<ConstraintMem::BoundSideType> esiBoundSide,\n    bool pushBackAtTheEnd) {\n  std::vector<ConstraintRef> vectVoid;\n  solve(Jse, ese, Jsi, esiInf, esiSup, esiBoundSide, vectVoid,\n        pushBackAtTheEnd);\n}\n\nvoid SolverHierarchicalInequalities::solve(\n    const bubMatrix &Jse, const bubVector &ese, const bubMatrix &Jsi,\n    const bubVector &esiInf, const bubVector &esiSup,\n    const ConstraintMem::BoundSideVector &esiBoundSide,\n    const std::vector<ConstraintRef> &slackActiveWarmStart,\n    bool pushBackAtTheEnd) {\n  sotDEBUGIN(1);\n  /*!*/ SOT_INIT_CHRONO;\n\n  initializeConstraintMemory(Jse, ese, Jsi, esiInf, esiSup, esiBoundSide,\n                             slackActiveWarmStart);\n  /*!*/ SOT_CHRONO(\"copy\");\n\n  /***/ sotDEBUG(15) << \"/* Initialize [Qs Rs]. */\" << std::endl;\n  initializeDecompositionSlack();\n  /*!*/ SOT_CHRONO(\"init\");\n\n  do {\n\n    /***/ sotDEBUG(15)\n        << \"* - LOOP 1  * - * - * - * - * - * - * - * - * - * - * - *\"\n        << std::endl;\n    /***/ sotDEBUG(15) << \"/* Active/inactive H-constraint. */\" << std::endl;\n    if (Hactivation) {\n      updateConstraintHierarchic(HactivationRef, HactivationSide);\n      /*!*/ SOT_CHRONO(\"UpdateH\");\n      Hactivation = false;\n      /***/ sotDEBUG(15) << \"/* Update Rank-1 [Qs Rs]. */\" << std::endl;\n      updateRankOneDowndate();\n      /*!*/ SOT_CHRONO(\"rankoneDowndate\");\n\n    } else if (Hinactivation) {\n      downdateConstraintHierarchic(HinactivationRef);\n      /*!*/ SOT_CHRONO(\"DowndateH\");\n      Hinactivation = false;\n      /***/ sotDEBUG(15) << \"/* Update Rank-1 [Qs Rs]. */\" << std::endl;\n      updateRankOneUpdate();\n      /*!*/ SOT_CHRONO(\"rankoneUpdate\");\n    }\n\n    /***/ sotDEBUG(15) << \"/* Activate/inactivate S-constraint. */\"\n                       << std::endl;\n    if (Sactivation) {\n      /***/ sotDEBUG(15) << \"/* Activate S-constraint. */\" << std::endl;\n      updateConstraintSlack(SactivationRef, SactivationSide);\n      /*!*/ SOT_CHRONO(\"UpS\");\n      /***/ sotDEBUG(15) << \"/* Activate S-constraint. */\" << std::endl;\n    } else if (Sinactivation) {\n      /***/ sotDEBUG(15) << \"/* Inactivate S-constraint. */\" << std::endl;\n      downdateConstraintSlack(SinactivationRef);\n      /*!*/ SOT_CHRONO(\"DownS\");\n    }\n    /***/ printDebug();\n    /*!*/ SOT_CHRONO(\"Print\");\n\n    /***/ sotDEBUG(15) << \"/* Compute Primal. */\" << std::endl;\n    computePrimal();\n    /*!*/ SOT_CHRONO(\"primal\");\n\n    Sactivation = false;\n    Sinactivation = false;\n    Hactivation = false;\n    Hinactivation = false;\n\n    /***/ sotDEBUG(15) << \"/* Compute Slack. */\" << std::endl;\n    u0 += du;\n    computeSlack();\n    u0 -= du;\n    /*!*/ SOT_CHRONO(\"Slack\");\n    /***/ sotDEBUG(15) << \"/* Selec S-activation. */\" << std::endl;\n    Sactivation = selecActivationSlack();\n    /*!*/ SOT_CHRONO(\"SelecAcS\");\n    if (Sactivation) {\n      continue;\n    }\n\n    /***/ sotDEBUG(15) << \"/* Selec H-activation. */\" << std::endl;\n    double tau;\n    Hactivation = selecActivationHierarchic(tau);\n    /*!*/ SOT_CHRONO(\"SelecAcH\");\n    if (Hactivation) {\n      /***/ sotDEBUG(15) << \"tau = \" << tau << std::endl;\n      du *= tau;\n      u0 += du;\n      /*!*/ SOT_CHRONO(\"IncUtau\");\n    } else {\n      u0 += du;\n      /*!*/ SOT_CHRONO(\"IncUsimple\");\n\n      //             /***/sotDEBUG(15) << \"/* Compute Slack. */\" << std::endl;\n      //             computeSlack();\n      //             /*!*/SOT_CHRONO(\"Slack\");\n      //             /***/sotDEBUG(15) << \"/* Selec S-activation. */\" <<\n      //             std::endl; Sactivation = selecActivationSlack();\n      //             //if( Sactivation ) continue;\n      //             /*!*/SOT_CHRONO(\"SelecAcS\");\n      //             /***/sotDEBUG(15) << \"/* Selec S-inactivation. */\" <<\n      //             std::endl; Sinactivation = selecInactivationSlack();\n      //             //if( Sinactivation ) continue;\n      //             /*!*/SOT_CHRONO(\"SelecInacS\");\n\n      /***/ sotDEBUG(15) << \"/* Compute Lagrangian. */\" << std::endl;\n      computeLagrangian();\n      /*!*/ SOT_CHRONO(\"Lagrang\");\n      /***/ sotDEBUG(15) << \"/* Selec H-inactivation. */\" << std::endl;\n      Hinactivation = selecInactivationHierarchic();\n      /*!*/ SOT_CHRONO(\"SelecInacH\");\n\n      if (!Hinactivation) {\n        /***/ sotDEBUG(15) << \"/* Selec S-inactivation. */\" << std::endl;\n        Sinactivation = selecInactivationSlack();\n        /*!*/ SOT_CHRONO(\"SelecInacS\");\n        if (Sinactivation) {\n          continue;\n        }\n      }\n    }\n    /***/ sotDEBUG(3) << \"u = \" << (MATLAB)u0 << std::endl;\n\n  } while (Sactivation || Sinactivation || Hactivation || Hinactivation);\n\n  /* Push-back S-constraint. */\n  /* Push-back [ Qs Rs ]. */\n  /*!*/ SOT_CHRONO(\"void\");\n  if (pushBackAtTheEnd)\n    pushBackSlackToHierarchy();\n  /*!*/ SOT_CHRONO(\"PBSlack\");\n  printDebug();\n  /***/ sotDEBUGOUT(1);\n}\n\n/* ---------------------------------------------------------- */\nvoid SolverHierarchicalInequalities::initializeConstraintMemory(\n    const bubMatrix &Jse, const bubVector &ese, const bubMatrix &Jsi,\n    const bubVector &esiInf, const bubVector &esiSup,\n    const ConstraintMem::BoundSideVector &esiBoundSide,\n    const std::vector<ConstraintRef> &warmStartSide) {\n  // TODO ... activate those protection.\n  //     if(!(\n  //     (esiInf.size()==esiSup.size())&&(esiInf.size()==esiBoundSide.size())&&(esiInf.size()==Jsi.size1()))\n  //     )\n  //       {\n  //         sotERROR << \"Error in the size of I matrices. \" << std::endl;\n  //         throw \"Error in the size of I matrices. \";\n  //       }\n  //     if(!( (ese.size()==Jse.size1())) )\n  //       {\n  //         sotERROR << \"Error in the size of E matrices. \" << std::endl;\n  //         throw \"Error in the size of E matrices. \";\n  //       }\n  sotDEBUG(45) << \"Je = \" << (MATLAB)Jse << std::endl;\n  sotDEBUG(45) << \"Ji = \" << (MATLAB)Jsi << std::endl;\n  {\n    sotDEBUG(25) << \"Warm start active slack = { \";\n    for (std::vector<ConstraintRef>::const_iterator iter =\n             warmStartSide.begin();\n         iter != warmStartSide.end(); ++iter) {\n      sotDEBUGMUTE(25) << (*iter) << \", \";\n    }\n    sotDEBUGMUTE(25) << \" }\" << std::endl;\n  }\n\n  Hactivation = false;\n  Hinactivation = false;\n  constraintS.clear();\n  constraintS.resize(ese.size() + Jsi.size1());\n  constraintSactive.resize(0);\n\n  sotDEBUG(15) << \"/* Copy the Jacobian to memory. */\" << std::endl;\n  unsigned int row = 0;\n  const unsigned int sizee = ese.size();\n  for (ConstraintList::iterator iter = constraintS.begin();\n       iter != constraintS.end(); ++iter, ++row) {\n    ConstraintMem &cs = *iter;\n\n    cs.Ji.resize(nJ, false);\n    cs.constraintRow = row;\n    cs.active = false;\n    cs.range = 0;\n    cs.rankIncreaser = false;\n    if (row < sizee) {\n      cs.Ji.assign(bub::row(Jse, row));\n      cs.eiInf = ese(row);\n      cs.equality = true;\n      cs.active = true;\n      cs.boundSide = cs.activeSide = ConstraintMem::BOUND_INF;\n    } else {\n      const unsigned int rowi = row - sizee;\n      cs.Ji.assign(bub::row(Jsi, rowi));\n      cs.boundSide = ConstraintMem::BOUND_VOID;\n      if ((esiBoundSide[rowi] & ConstraintMem::BOUND_INF) &&\n          (!boost::math::isnan(esiInf(rowi)))) {\n        cs.eiInf = esiInf(rowi);\n        cs.boundSide = (ConstraintMem::BoundSideType)(cs.boundSide |\n                                                      ConstraintMem::BOUND_INF);\n      }\n      if ((esiBoundSide[rowi] & ConstraintMem::BOUND_SUP) &&\n          (!boost::math::isnan(esiSup(rowi)))) {\n        cs.eiSup = esiSup(rowi);\n        cs.boundSide = (ConstraintMem::BoundSideType)(cs.boundSide |\n                                                      ConstraintMem::BOUND_SUP);\n      }\n      cs.equality = false;\n    }\n    sotDEBUG(15) << \"Init \" << cs << std::endl;\n  }\n\n  /* Activation Warm start. */\n  {\n    for (std::vector<ConstraintRef>::const_iterator iter =\n             warmStartSide.begin();\n         iter != warmStartSide.end(); ++iter) {\n      if (iter->id < constraintS.size()) {\n        constraintS[iter->id].active = true;\n        constraintS[iter->id].activeSide = iter->side;\n        sotDEBUG(1) << \"Activation WS < \" << *iter << \">\" << std::endl;\n      }\n    }\n  }\n}\n\nvoid SolverHierarchicalInequalities::initializeDecompositionSlack(void) {\n  QhJsU.resize(nJ, constraintS.size(), false);\n  QhJsU.clear();\n  QhJs.resize(nJ, constraintS.size(), false);\n  QhJs.clear();\n  Sactivation = false;\n  Sinactivation = false;\n\n  sotDEBUG(15) << \"/* 1.a Compute the limited matrix. */\" << std::endl;\n  sizes = 0;\n  for (ConstraintList::iterator iter = constraintS.begin();\n       iter != constraintS.end(); ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.active) {\n      bub::column(QhJsU, sizes++) = cs.Ji;\n    }\n  }\n  bubMatrixQR QhJeU(QhJsU, fullrange(), bub::range(0, sizes));\n  /*!*/ SOT_CHRONO(\"BuildJs\");\n  Qh.multiplyRightTranspose(QhJeU);\n  sotDEBUG(15) << \"QhJs = \" << (MATLAB)QhJeU << std::endl;\n  /*!*/ SOT_CHRONO(\"QhJs\");\n\n  if (freeRank == 0) {\n    ranks = 0;\n    orderS = bubOrder(0);\n    bub::project(QhJs, fullrange(), bub::range(0, sizes)).assign(QhJeU);\n    /* Initialize the constraintMem. */\n    unsigned int row = 0;\n    for (ConstraintList::iterator iter = constraintS.begin();\n         iter != constraintS.end(); ++iter, ++row) {\n      ConstraintMem &cs = *iter;\n      cs.range = row;\n      if (cs.active) {\n        constraintSactive.push_back(&cs);\n      }\n    }\n    sotDEBUG(15) << \"Freerank null, initial decomposition void.\" << std::endl;\n    return;\n  }\n\n  sotDEBUG(15) << \"/* 1.b Compute the QR decomposition. */\" << std::endl;\n  bubMatrixQR QRs(QhJsU, bub::range(rankh, nJ), bub::range(0, sizes));\n  bubVector betas(sizes);\n  betas.clear();\n  bub::vector<int> orderSe(sizes);\n  orderSe.clear();\n  boost::numeric::bindings::lapack::geqp(QRs, orderSe, betas);\n  ranks = rankDetermination(QRs);\n  sotDEBUG(15) << \"ranks = \" << ranks << std::endl;\n  sotDEBUG(15) << \"QRs = \" << (MATLAB)QhJeU << std::endl;\n  sotDEBUG(15) << \"orderSe = \" << orderSe << std::endl;\n  /*!*/ SOT_CHRONO(\"QRdecomp\");\n\n  sotDEBUG(15) << \"/* 1.c Organize into Q2 and R2. */\" << std::endl;\n  /* If Je is rank deficient, then the last <m-r> householder vectors\n   * do not affect the range basis M (where Q=[M N]). If M is constant\n   * wrt these vector, then Span(N)=orth(Span(M)) is also constant, even\n   * if N is non constant, and thus these vectors can be neglect. */\n  sotRotationComposed Qs;\n  Qs.householderQRinit(QRs, betas, ranks);\n  Qh.pushBack(Qs);\n\n  /* Remove the lower triangle (householder vectors). */\n  for (unsigned int j = 0; j < sizes; ++j)\n    for (unsigned int i = j + 1; i < freeRank; ++i)\n      QRs(i, j) = 0;\n  sotDEBUG(45) << \"Qs = \" << MATLAB(Qs, nJ) << std::endl;\n  sotDEBUG(15) << \"QJs = \" << (MATLAB)QhJeU << std::endl;\n  /*!*/ SOT_CHRONO(\"QRorganize\");\n\n  /* Save QhJs (without U). */\n  for (unsigned int j = 0; j < sizes; ++j) {\n    for (unsigned int i = 0; i < rankh; ++i) {\n      QhJs(i, j) = QhJeU(i, orderSe(j) - 1);\n    }\n    for (unsigned int i = rankh; i < nJ; ++i) {\n      QhJs(i, j) = QhJeU(i, j);\n    }\n  }\n  QhJeU = bub::project(QhJs, fullrange(), bub::range(0, sizes));\n  orderS = bubOrder(ranks);\n  for (unsigned int i = 0; i < ranks; ++i)\n    orderS[i] = i;\n  sotDEBUG(15) << \"QhsJs = \" << (MATLAB)QhJeU << std::endl;\n  sotDEBUG(15) << \"orderS = \" << (MATLAB)orderS << std::endl;\n  /*!*/ SOT_CHRONO(\"SaveQhJs\");\n\n  /* Full range decomposition R0 = Qh.Js.U . */\n  regularizeQhJsU();\n  /*!*/ SOT_CHRONO(\"FullRankDecompo\");\n\n  /* Initialize the constraintMem. */\n  ConstraintRefList activeOrderRaw;\n  for (ConstraintList::iterator iter = constraintS.begin();\n       iter != constraintS.end(); ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.active)\n      activeOrderRaw.push_back(&cs);\n  }\n  /* Push the constraint in cSactive in the order decided by the QR\n   * decomposition. */\n  for (unsigned int i = 0; i < sizes; ++i) {\n    ConstraintMem &cs = *activeOrderRaw[orderSe[i] - 1];\n    if (i < ranks) {\n      cs.rankIncreaser = true;\n    }\n    cs.range = i;\n    constraintSactive.push_back(&cs);\n    sotDEBUG(15) << \"Activate \" << cs << std::endl;\n  }\n  /*!*/ SOT_CHRONO(\"InitActiveMem\");\n}\n\n/* ---------------------------------------------------------- */\n/* <constraintId> is the number of the constraint in the constraintH list. */\nvoid SolverHierarchicalInequalities::updateConstraintHierarchic(\n    const unsigned int constraintId, const ConstraintMem::BoundSideType side) {\n  sotDEBUG(15) << \"khup = \" << constraintId << std::endl;\n  ConstraintMem &chup = constraintH[constraintId];\n\n  /* Compute the limited Jacobian. */\n  bub::matrix_column<bubMatrix> QtJt(Rh, rankh);\n  QtJt.assign(chup.Ji);\n  Qh.multiplyLeft(QtJt);\n  sotDEBUG(15) << \"Jk = \" << (MATLAB)chup.Ji << std::endl;\n  sotDEBUG(15) << \"QJk = \" << (MATLAB)QtJt << std::endl;\n\n  chup.rankIncreaser = false;\n  bub::triangular_adaptor<bub::matrix_range<bubMatrix>, bub::upper> Rhprev =\n      accessRh();\n  if (rankh < nJ) {\n    lastRotation.clear();\n    /* Given rotation to nullify the new column. */\n    for (unsigned int row = nJ - 1; row > rankh; row--) {\n      if (fabs(QtJt(row)) > THRESHOLD_ZERO) {\n        chup.rankIncreaser = true;\n        sotRotationSimpleGiven gr(Rh, row - 1, row, rankh);\n        gr.inverse();\n        gr.multiplyLeft(QtJt);\n        lastRotation.pushBack(gr);\n      }\n    }\n    sotDEBUG(45) << \"Add GR = \" << lastRotation << std::endl;\n    Qh.pushBack(lastRotation);\n\n    /* Update information about the constraint. */\n    chup.active = true;\n    chup.rankIncreaser = true;\n    chup.activeSide = side;\n    chup.range = rankh;\n    /* Increase the number of data. */\n    rankh++;\n    freeRank--;\n    freeRankChange = -1;\n  }\n\n  if (!chup.rankIncreaser) {\n    std::cerr << \"Error, H-up should always be full rank!\" << std::endl;\n    throw \"Error, H-up should always be full rank!\";\n  }\n\n  sotDEBUG(15) << \"Rh = \" << (MATLAB)accessRhConst() << std::endl;\n  sotDEBUG(15) << \"Constraint = \" << chup << std::endl;\n}\n\n/* <constraintId> is the number of the constraint in the constraintH list. */\nvoid SolverHierarchicalInequalities::downdateConstraintHierarchic(\n    const unsigned int kdown) {\n  ConstraintMem &cdown = constraintH[kdown];\n  sotDEBUG(15) << \"kdown = \" << kdown << std::endl;\n  if (!constraintH[kdown].active)\n    return;\n\n  /* Rh is hessenberg: trigonalize. */\n  lastRotation.clear();\n  for (unsigned int i = cdown.range + 1; i < rankh; ++i) {\n    sotRotationSimpleGiven Gr(Rh, i - 1, i, i);\n    Gr.inverse();\n    Gr.multiplyRightTranspose(Rh);\n    lastRotation.pushBack(Gr);\n  }\n  Qh.pushBack(lastRotation);\n  /* Shift the column after kdown to the left. */\n  for (ConstraintList::iterator iter = constraintH.begin();\n       iter != constraintH.end(); ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.range > cdown.range)\n      cs.range--;\n  }\n  /* Remove the columnd <kdown> from Rh. */\n  // bubClearMatrix(bub::column(Rh,cdown.range));\n  // bubClearMatrix(bub::column(Rh,cdown.range).data());\n  // bub::vector_assign_scalar<bub::scalar_assign>(bub::column(Rh,cdown.range),0);\n  bub::column(Rh, cdown.range).assign(bub::zero_vector<double>(Rh.size1()));\n  bubRemoveColumn(accessRh(), cdown.range);\n  rankh--;\n  freeRank++;\n  freeRankChange = +1;\n  cdown.active = false;\n  sotDEBUG(5) << \"Rhdown = \" << (MATLAB)accessRhConst() << std::endl;\n  sotDEBUG(5) << \"Qhdown = \" << MATLAB(Qh, nJ) << std::endl;\n  sotDEBUG(5) << \"Qhlast = \" << MATLAB(lastRotation, nJ) << std::endl;\n  sotDEBUG(5) << \"Qhlast = \" << lastRotation << std::endl;\n\n  /* Check for active rank-def constraint. */\n  for (ConstraintList::iterator iter = constraintH.begin();\n       iter != constraintH.end(); ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.active && (!cs.rankIncreaser)) {\n      bubVector QJk(cs.Ji);\n      Qh.multiplyLeft(QJk);\n      if (fabs(QJk(rankh)) > THRESHOLD_ZERO) { /* Update constraint: Qh'Ji' = [\n                                                * Mh'Ji' mh'Ji' Nh'Ji], with\n                                                * Nh'Ji=0. Simply add the\n                                                * [Mh'Ji' mh'Ji' ] to Rh. */\n        sotDEBUG(5) << \"No rank loss when downdating [\" << kdown << \"] => \"\n                    << cs.constraintRow << std::endl;\n        bub::matrix_column<bubMatrix> Rhk(Rh, rankh);\n        bub::project(Rhk, bub::range(0, rankh + 1))\n            .assign(bub::project(QJk, bub::range(0, rankh + 1)));\n        cs.range = rankh;\n        cs.rankIncreaser = true;\n        rankh++;\n        freeRank--;\n        freeRankChange = 0;\n        break;\n      }\n    }\n  }\n}\n\n/* ---------------------------------------------------------- */\n/* <kup> is the number of the constraint in the constraintS list. */\nvoid SolverHierarchicalInequalities::updateConstraintSlack(\n    const unsigned int kup, const ConstraintMem::BoundSideType activeSide) {\n  sotDEBUG(15) << \"kup = \" << activeSide << kup << std::endl;\n  ConstraintMem &csup = constraintS[kup];\n  //     if( freeRank>0 )\n  //       {\n  /* Compute the limited Jacobian. */\n  bubVector QtJt(nJ);\n  QtJt.assign(csup.Ji);\n  Qh.multiplyLeft(QtJt);\n  bub::vector_range<bubVector> Ft(QtJt, freerange());\n  sotDEBUG(15) << \"QsNhJk = \" << (MATLAB)Ft << std::endl;\n\n  /* TODO: copy directly ck.Ji in JsU, instead of using the tmp var Ft. */\n  bub::matrix_column<bubMatrixQRWide> JskU(QhJsU, sizes);\n  bub::project(JskU, rangehs()) = bub::project(QtJt, rangehs());\n  bub::matrix_column<bubMatrixQRWide> Jsk(QhJs, sizes);\n  bub::project(Jsk, rangehs()) = bub::project(QtJt, rangehs());\n\n  bool rankDef = true;\n  if (ranks + rankh < nJ) {\n    /* Householder transposition of QJk. */\n    bub::vector_range<bubVector> Ftdown(QtJt, bub::range(rankh + ranks, nJ));\n    double beta;\n    double normSignFt // Norm with sign!\n        = sotRotationSimpleHouseholder::householderExtraction(Ftdown, beta,\n                                                              THRESHOLD_ZERO);\n    sotDEBUG(15) << \"hk = \" << (MATLAB)Ftdown << std::endl;\n    sotDEBUG(15) << \"betak = \" << beta << std::endl;\n    sotDEBUG(15) << \"normH = \" << normSignFt << std::endl;\n\n    /* Add a new column in R. */\n    QhJsU(rankh + ranks, sizes) = normSignFt;\n    QhJs(rankh + ranks, sizes) = normSignFt;\n\n    /* Add a new rotation in Qh. */\n    if (fabs(normSignFt) >\n        THRESHOLD_ZERO) { /* If Jk is adding information to the current R. */\n      /* Add the new householder vector in Q. */\n      if (fabs(beta) > THRESHOLD_ZERO) {\n        Qh.pushBack(sotRotationSimpleHouseholder(Ftdown, beta));\n      }\n      /* Update information about the constraint. */\n      csup.rankIncreaser = true;\n      /* Increase the number of data. */\n      ranks++;\n      rankDef = false;\n      orderS += sizes;\n    }\n  }\n  csup.range = sizes;\n  sizes++;\n\n  sotDEBUG(45) << \"QhJs = \" << (MATLAB)QhJs << std::endl;\n  sotDEBUG(45) << \"QhJsU = \" << (MATLAB)QhJsU << std::endl;\n  if (rankDef && (freeRank > 0)) { /* The new line does not add any information.\n                                      Regularize the pseudo-triangle. */\n    /* Select the non zero part of R. */\n    bubMatrixQR QJdown(QhJsU, freeranges(), bub::range(0, sizes));\n    bubMatrixQRTri RrRh(QJdown);\n    /* Regularize. */\n    sotDEBUG(15) << \"RrRh = \" << (MATLAB)RrRh << std::endl;\n    sotRotationComposed Uchol;\n    Uchol.regularizeRankDeficientTriangle(RrRh, orderS, sizes - 1);\n    csup.rankIncreaser = false;\n    bubMatrixQR Jsup(QhJsU, rangeh(), bub::range(0, sizes));\n    Uchol.multiplyLeft(Jsup);\n  }\n  sotDEBUG(15) << \"kup = \" << kup << \" VS \" << constraintS.size() << std::endl;\n  csup.active = true;\n  csup.activeSide = activeSide;\n  constraintSactive.push_back(&csup);\n  sotDEBUG(15) << \"Rei = \" << (MATLAB)accessRsConst() << std::endl;\n  sotDEBUG(15) << \"Constraint = \" << csup << std::endl;\n}\n\n/* Regularize from right (Q.J from Q.J.U). */\nvoid SolverHierarchicalInequalities::regularizeQhJs(void) {\n  typedef bub::matrix_column<bubMatrixQRWide> bubQJsCol;\n  sotRotationComposed Qlast;\n  for (unsigned int i = 0; i < ranks; ++i) {\n    bubQJsCol QJk(QhJs, orderS(i));\n    Qlast.multiplyLeft(QJk);\n    sotDEBUG(45) << \"QhJs_\" << i << \" = \" << (MATLAB)QJk << std::endl;\n    bub::vector_range<bubQJsCol> Ftdown(\n        QJk, bub::range(rankh + i, std::min(nJ, rankh + ranks + 1)));\n    double beta;\n    double normSignFt = sotRotationSimpleHouseholder::householderExtraction(\n        Ftdown, beta, THRESHOLD_ZERO);\n    sotDEBUG(45) << \"Ft_\" << i << \" = \" << (MATLAB)Ftdown << std::endl;\n    sotDEBUG(45) << \"b_\" << i << \" = \" << beta << std::endl;\n    if (fabs(beta) > THRESHOLD_ZERO) {\n      Qlast.pushBack(sotRotationSimpleHouseholder(Ftdown, beta));\n    }\n    std::fill(Ftdown.begin(), Ftdown.end(), 0);\n    Ftdown(0) = normSignFt;\n  }\n  Qh.pushBack(Qlast);\n  for (ConstraintRefList::iterator iter = constraintSactive.begin();\n       iter != constraintSactive.end(); ++iter) {\n    ConstraintMem &cs = **iter;\n    if (!cs.rankIncreaser) {\n      bubQJsCol QJk(QhJs, cs.range);\n      Qlast.multiplyLeft(QJk);\n    }\n  }\n  sotDEBUG(15) << \"QhJs = \" << (MATLAB)QhJs << std::endl;\n  sotDEBUG(15) << \"Qreg = \" << MATLAB(Qlast, nJ) << std::endl;\n}\n\n/* Regularize from right (Q.J from Q.J.U). */\nvoid SolverHierarchicalInequalities::regularizeQhJsU(void) {\n  if (ranks == sizes)\n    return;\n  bubMatrixQR QhJsinf(QhJsU, bub::range(rankh, rankh + ranks),\n                      bub::range(0, sizes));\n  bubMatrixQRTri Rrh(QhJsinf);\n  bubMatrixQR Jssup(QhJsU, rangeh(), bub::range(0, sizes));\n  sotDEBUG(15) << \"Rrh = \" << (MATLAB)Rrh << std::endl;\n\n  /* Search for the rank def columns. */\n  std::vector<bool> rankDefColumns(sizes, true);\n  for (unsigned int i = 0; i < ranks; ++i)\n    rankDefColumns[orderS(i)] = false;\n\n  /* Regularize the rank def cols. */\n  for (unsigned int i = 0; i < sizes; ++i)\n    if (rankDefColumns[i]) {\n      sotRotationComposed Gr;\n      Gr.regularizeRankDeficientTriangle(Rrh, orderS, i);\n      Gr.multiplyLeft(Jssup);\n    }\n  sotDEBUG(45) << \"R0 = \" << (MATLAB)Rrh << std::endl;\n  sotDEBUG(15) << \"QhJsU = \" << (MATLAB)bub::subrange(QhJsU, 0, nJ, 0, sizes)\n               << std::endl;\n}\n\n/* <constraintId> is the number of the constraint in the constraintS list. */\nvoid SolverHierarchicalInequalities::downdateConstraintSlack(\n    const unsigned int kdown) {\n  /* Remove the column. */\n  ConstraintMem &cs = constraintS[kdown];\n  sotDEBUG(15) << \"Downdate S \" << cs;\n  const unsigned int range = cs.range;\n  if (orderS.end() != std::find(orderS.begin(), orderS.end(), range)) {\n    orderS -= range;\n    ranks--;\n  }\n  bubRemoveColumn(QhJs, range);\n  sizes--;\n  cs.active = false;\n  constraintSactive.erase(constraintSactive.begin() + range);\n  for (unsigned int i = 0; i < ranks; ++i)\n    if (orderS(i) > range)\n      orderS(i)--;\n  for (ConstraintRefList::iterator iter = constraintSactive.begin();\n       iter != constraintSactive.end(); ++iter) {\n    if ((*iter)->range > range)\n      (*iter)->range--;\n    sotDEBUG(15) << \"Remains \" << **iter << std::endl;\n  }\n  /* Triangularize the remaining QhJs matrix. */\n  regularizeQhJs();\n  /* Check for rank update. */\n  for (unsigned int i = 0; i < sizes; ++i) {\n    sotDEBUG(45) << \"At i=\" << i << \",j=\" << rankh + ranks\n                 << \": qj=\" << QhJs(rankh + ranks, i) << std::endl;\n    if ((freeRank > ranks) && (fabs(QhJs(rankh + ranks, i)) > THRESHOLD_ZERO)) {\n      sotDEBUG(15) << \"No ranks lost when downdating S.\" << std::endl;\n      orderS += i;\n      ranks++;\n      constraintSactive[i]->rankIncreaser = true;\n      break;\n    }\n  }\n\n  bub::project(QhJsU, bub::range(0, nJ), bub::range(0, sizes))\n      .assign(bub::project(QhJs, bub::range(0, nJ), bub::range(0, sizes)));\n  bub::project(QhJs, bub::range(0, nJ), bub::range(sizes, QhJsU.size2()))\n      .assign(bub::zero_matrix<double>(nJ, QhJsU.size2() - sizes));\n  bub::project(QhJsU, bub::range(0, nJ), bub::range(sizes, QhJsU.size2()))\n      .assign(bub::zero_matrix<double>(nJ, QhJsU.size2() - sizes));\n  regularizeQhJsU();\n\n  //     std::cerr << \"Not implemented yet (RotationSimple l\" << __LINE__\n  //               << \").\" << std::endl;\n  //     throw  \"Not implemented yet.\";\n}\n\n/* ---------------------------------------------------------- */\nvoid SolverHierarchicalInequalities::updateRankOneDowndate(void) {\n  sotDEBUG(15) << \"/* Apply the last corrections of Qh. */\" << std::endl;\n  bubMatrixQR QhJranksU(QhJsU, fullrange(), bub::range(0, sizes));\n  lastRotation.multiplyRightTranspose(QhJranksU);\n  bubMatrixQR QhJranks(QhJs, fullrange(), bub::range(0, sizes));\n  lastRotation.multiplyRightTranspose(QhJranks);\n\n  sotDEBUG(15) << \"/* Check for the full rank of Rs. */\" << std::endl;\n  sotDEBUG(25) << \"beforeQhJsU = \"\n               << (MATLAB)bub::subrange(QhJsU, 0, nJ, 0, sizes) << std::endl;\n  sotDEBUG(25) << \"beforeQhJs = \"\n               << (MATLAB)bub::subrange(QhJs, 0, nJ, 0, sizes) << std::endl;\n  bubMatrixQR Rsno(QhJsU, bub::range(rankh, std::min(nJ, rankh + ranks)),\n                   bub::range(0, sizes));\n  for (unsigned int i = 0; i < ranks; ++i) {\n    const unsigned int col = orderS[i];\n    if ((i >= freeRank) || (fabs(Rsno(i, col)) < THRESHOLD_ZERO)) {\n      sotDEBUG(5) << \"Rank lost at \" << i << \".\" << std::endl;\n      orderS -= col;\n      ranks--;\n      constraintSactive[col]->rankIncreaser = false;\n      if (i > 0) {\n        sotRotationComposed Gr;\n        bubMatrixQR Ri(QhJsU, bub::range(rankh, std::min(nJ, rankh + i)),\n                       bub::range(0, sizes));\n        Gr.regularizeRankDeficientTriangle(Ri, orderS, col);\n        bubMatrixQR Jsup(QhJsU, rangeh(), bub::range(0, sizes));\n        Gr.multiplyLeft(Jsup);\n      }\n\n      break;\n    }\n  }\n  sotDEBUG(5) << \"unrQhJsU = \" << (MATLAB)QhJsU << std::endl;\n  sotDEBUG(15) << \"/* Regularize the Hessenberg matrix. */\" << std::endl;\n  for (unsigned int i = 0; i < ranks; ++i) {\n    const unsigned int col = orderS[i];\n    if ((i + 1 < freeRank) &&\n        (fabsf(QhJsU(rankh + i + 1, col)) > THRESHOLD_ZERO)) {\n      sotRotationSimpleGiven Gr(QhJsU, rankh + i, rankh + i + 1, col);\n      Gr.inverse();\n      Gr.multiplyRightTranspose(QhJsU);\n      Gr.multiplyRightTranspose(QhJs);\n      Qh.pushBack(Gr);\n    }\n    sotDEBUG(45) << \"QhJs = \" << (MATLAB)QhJs << std::endl;\n    sotDEBUG(15) << \"QhJsU = \" << (MATLAB)QhJsU << std::endl;\n    sotDEBUG(5) << \"Rs = \" << (MATLAB)accessRsConst() << std::endl;\n  }\n}\n\nvoid SolverHierarchicalInequalities::updateRankOneUpdate(void) {\n  sotDEBUG(15) << \"ranks = \" << ranks << std::endl;\n  sotDEBUG(15) << \"/* Apply the last corrections of Qh. */\" << std::endl;\n  bubMatrixQR QhJranksU(QhJsU, fullrange(), bub::range(0, sizes));\n  sotDEBUG(25) << \"beforeQhJsU = \" << (MATLAB)QhJranksU << std::endl;\n  lastRotation.multiplyRightTranspose(QhJranksU);\n  bubMatrixQR QhJranks(QhJs, fullrange(), bub::range(0, sizes));\n  sotDEBUG(25) << \"beforeQhJs = \" << (MATLAB)QhJranks << std::endl;\n  lastRotation.multiplyRightTranspose(QhJranks);\n\n  sotDEBUG(25) << \"hessenbergQhJsU = \" << (MATLAB)QhJranksU << std::endl;\n  sotDEBUG(25) << \"order = \" << (MATLAB)orderS << std::endl;\n  sotDEBUG(15) << \"/* Regularize the Hessenberg matrix. */\" << std::endl;\n  std::vector<bool> notFullRank(sizes, true);\n  sotRotationComposed Qhdebug;\n  for (unsigned int i = 0; i < ranks; ++i) {\n    const unsigned int col = orderS[i];\n    if ((i + 1 < freeRank) &&\n        (fabs(QhJsU(rankh + i + 1, col)) > THRESHOLD_ZERO)) {\n      sotDEBUG(45) << \"Regularize diag-up on \" << col << \". \" << std::endl;\n      sotRotationSimpleGiven Gr(QhJsU, rankh + i, rankh + i + 1, col);\n      Gr.inverse();\n      Gr.multiplyRightTranspose(QhJsU);\n      Gr.multiplyRightTranspose(QhJs);\n      Qh.pushBack(Gr);\n      Qhdebug.pushBack(Gr);\n    }\n    notFullRank[col] = false;\n  }\n\n  sotDEBUG(25) << \"Qhmodif = \" << MATLAB(Qhdebug, nJ) << std::endl;\n  if (freeRank > 0) {\n    sotDEBUG(25) << \"regQhJsU = \" << (MATLAB)QhJranksU << std::endl;\n    sotDEBUG(25) << \"regQhJs = \" << (MATLAB)QhJranks << std::endl;\n    sotDEBUG(15) << \"/* Check for the rank update of Rs. */\" << std::endl;\n    bool rankOneUpdateDone = false;\n    for (unsigned int i = 0; i < sizes; ++i) {\n      bubMatrixQR Rsno(QhJsU, bub::range(rankh, rankh + ranks),\n                       bub::range(0, sizes));\n      if (notFullRank[i]) {\n        /* Check that last-row value is still null. */\n        if ((!rankOneUpdateDone) && (rankh + ranks < nJ) &&\n            (fabs(QhJsU(rankh + ranks, i)) > THRESHOLD_ZERO)) {\n          sotDEBUG(5) << \"Rank inc at \" << i << \".\" << std::endl;\n          ranks++;\n          orderS += i;\n          rankOneUpdateDone = true;\n          ;\n          constraintSactive[i]->rankIncreaser = true;\n        } else if (orderS.size() > 0) {\n          sotDEBUG(5) << \"ranks_after = \" << ranks << std::endl;\n          sotRotationComposed U;\n          U.regularizeRankDeficientTriangle(Rsno, orderS, i);\n          bubMatrixQR Jsup(QhJsU, rangeh(), bub::range(0, sizes));\n          U.multiplyLeft(Jsup);\n        }\n      }\n    }\n  }\n  sotDEBUG(45) << \"QhJs = \" << (MATLAB)QhJs << std::endl;\n  sotDEBUG(15) << \"QhJsU = \" << (MATLAB)QhJsU << std::endl;\n  sotDEBUG(5) << \"Rs = \" << (MATLAB)accessRsConst() << std::endl;\n}\n\n/* ---------------------------------------------------------- */\n//   void updateRankOneSlack( void )\n//   {\n//     sotDEBUG(15) << \"/* Apply the last corrections of Qh. */\"<<std::endl;\n//     bubMatrixQR QhJranksU(QhJsU,fullrange(),bub::range(0,sizes));\n//     lastRotation.multiplyRightTranspose(QhJranksU);\n//     bubMatrixQR QhJranks(QhJs,fullrange(),bub::range(0,sizes));\n//     lastRotation.multiplyRightTranspose(QhJranks);\n\n//     sotDEBUG(15) << \"/* Check for the full rank of Rs. */\"<<std::endl;\n//     sotDEBUG(25) << \"beforeQhJsU = \" <<\n//     (MATLAB)bub::subrange(QhJsU,0,nJ,0,sizes) << std::endl;\n//     /* rpc contains a map giving for each rank=1:sizes the ref of the column\n//     of that size. */ std::vector< std::list<unsigned int> >\n//     rankPerColumn(sizes); sotDEBUG(15) << \"/* Classify the columns per rank\n//     in <rankPerColumn>. */\"<<std::endl; for( unsigned int\n//     col=0;col<sizes;++col )\n//       {\n//         for( unsigned int row=nJ-1;row>=rankh;--row )\n//           {\n//             sotDEBUG(50) << row << \" x \" << col << \" = \" <<\n//             fabs(QhJsU(row,col)) << std::endl;\n//             /* Search for the first non-zero. */\n//             if( fabs(QhJsU(row,col))>THRESHOLD_ZERO )\n//               { rankPerColumn[row-rankh].push_back(col); break; }\n//           }\n//       }\n//     sotDEBUG(15) << \"/* Select the columns to shape a triangle.\n//     */\"<<std::endl; bub::unbounded_array<std::size_t> columnOrder(sizes);\n//     ranks=0; std::list<unsigned int> needRightRegularization; bool\n//     needLeftRegularization = false; for( unsigned int i=0;i<sizes;++i )\n//       {\n//         sotDEBUG(45) << i << std::endl;\n//         std::list<unsigned int> & rpci = rankPerColumn[i];\n//         if( rpci.size()>0 )\n//           {\n//             columnOrder[i] = rpci.front(); ranks++;\n//             rpci.pop_front();\n//           }\n//         else\n//           {\n//             sotDEBUG(5) << \"Need left regularization for col \" << i <<\n//             std::endl; needLeftRegularization = true;\n//           }\n//         if( rpci.size()>0 )\n//           needRightRegularization.insert(needRightRegularization.end(),\n//           rpci.begin(), rpci.end());\n//       }\n//     orderS = bubOrder(ranks,columnOrder);\n//     sotDEBUG(5) << \"unrQhJsU = \"<< (MATLAB)accessQRs() << std::endl;\n//     if( needLeftRegularization )\n//       {\n//         sotDEBUG(15) << \"/* Regularize the Hessenberg matrix. */\"<<std::endl;\n//         for( unsigned int i=0;i<ranks;++i )\n//           {\n//             sotRotationSimpleGiven Gr( QhJsU,rankh+i,rankh+i+1,columnOrder[i]\n//             );  Gr.inverse(); Gr.multiplyRightTranspose(QhJsU);\n//             Gr.multiplyRightTranspose(QhJs);\n//             Qh.pushBack(Gr);\n//           }\n//       }\n//     sotDEBUG(5) << \"rlQhJsU = \"<< (MATLAB)QhJsU << std::endl;\n//     sotDEBUG(15) << \"/* Regularize the rank-def columns. */\"<<std::endl;\n//     bubMatrixQR QhJsUdown(\n//     QhJsU,bub::range(rankh,rankh+ranks),bub::range(0,sizes)); for(\n//     std::list<unsigned int>::iterator iter=needRightRegularization.begin();\n//          iter!=needRightRegularization.end();++iter )\n//       {\n//         sotDEBUG(25) << \"Regularize right \" << *iter << std::endl;\n//         sotRotationComposed Gr;\n//         Gr.regularizeRankDeficientTriangle(QhJsUdown,orderS,*iter);\n//       }\n//     sotDEBUG(45) << \"QhJs = \" << (MATLAB)QhJs << std::endl;\n//     sotDEBUG(15) << \"QhJsU = \" << (MATLAB)QhJsU << std::endl;\n//     sotDEBUG(5) << \"Rs = \" << (MATLAB)accessRsConst() << std::endl;\n//   }\n\n/* ---------------------------------------------------------- */\n/* Compute b = Ja' ( ea - Ja u0), with Ja,ea the jacobian and reference\n * of the active slack constraints.\n * <gradient> must be of size <nJ> (no resize).\n */\nvoid SolverHierarchicalInequalities::computeGradient(bubVector &gradientWide) {\n  //     bubVector gse(ese.size()); gse=ese;\n  //     bub::axpy_prod( Jse,-u0,gse,false ); /* gse = ese - Jse u0 */\n  //     bub::axpy_prod( gse,Jse,gradientWide,true ); /* g = J' (ese - Jse u0 )\n  //     */\n  gradientWide.clear();\n  for (ConstraintRefList::const_iterator iter = constraintSactive.begin();\n       iter != constraintSactive.end(); ++iter) {\n    const ConstraintMem &ci = **iter;\n    const double ciei =\n        (ci.activeSide == ConstraintMem::BOUND_INF) ? ci.eiInf : ci.eiSup;\n    double epJu = ciei - bub::inner_prod(ci.Ji, u0);\n    gradientWide += epJu * ci.Ji;\n    sotDEBUG(55) << \"Gradient with \" << ci << \" -> g = \" << (MATLAB)gradientWide\n                 << std::endl;\n  }\n}\n\n/* Compute the primal solution of the (equality-only) QP problem,\n * using the Null-Space method:\n *   du = Nh Ms Rs^-T Rs^-1 Ms' Nh' Js' ( es - Js u0 )\n */\nvoid SolverHierarchicalInequalities::computePrimal(void) {\n  if ((0 == freeRank) || (0 == ranks)) {\n    sotDEBUG(15) << \"Ranks null, du is 0.\" << std::endl;\n    du.resize(nJ, false);\n    du.clear();\n    return;\n  }\n\n  const bubMatrixQROrderedTriConst Rei = accessRsConst();\n  sotDEBUG(15) << \"Rei = \" << (MATLAB)Rei << std::endl;\n  sotDEBUG(15) << \"/* du <- Js' ( es - Js u0 ) */\" << std::endl;\n  du.resize(nJ, false);\n  computeGradient(du);\n  sotDEBUG(15) << \"Jtei = \" << (MATLAB)du << std::endl;\n  sotDEBUG(15) << \"/* Mbei <- Ms' Nh' Js' ( es - Js u0 ) */\" << std::endl;\n  bub::vector_range<bubVector> Mbei =\n      Qh.multiplyRangeLeft(du, rankh, freeRank - ranks);\n  sotDEBUG(15) << \"--\" << std::endl;\n  sotDEBUG(45) << \"Qbei = \" << (MATLAB)du << std::endl;\n  sotDEBUG(15) << \"Mbei = \" << (MATLAB)Mbei << std::endl;\n  sotDEBUG(15) << \"/* Mbei <- R-ei Ms' Jt' et */\" << std::endl;\n  bub::lu_substitute(Rei, Mbei);\n  sotDEBUG(15) << \"RMbei = \" << (MATLAB)Mbei << std::endl;\n  sotDEBUG(15) << \"/* Mbei <- R'-1 R-1 Ms' Jt' et */\" << std::endl;\n  bub::lu_substitute(Mbei, (const bubMatrix &)Rei);\n  sotDEBUG(15) << \"RRMbei = \" << (MATLAB)Mbei << std::endl;\n  sotDEBUG(15) << \"/* du <- Qh * [ 0 ; Qs * [ Mbei; 0 ] ] */\" << std::endl;\n  Qh.multiplyRangeRight(du, rankh, (freeRank - ranks));\n  sotDEBUG(5) << \"duei = \" << (MATLAB)du << std::endl;\n}\n/* ---------------------------------------------------------- */\n/* Compute the slack w = es-Js(u0+du). Since esi<Jsi.u, the slack\n * w = esi-Jsi.u should be negative. Since Jss.u<ess, the slack\n * w = Jss.u-ess should also be negative. */\nvoid SolverHierarchicalInequalities::computeSlack(void) {\n  slackInf.resize(constraintS.size(), false);\n  slackInf.clear();\n  slackSup.resize(constraintS.size(), false);\n  slackSup.clear();\n  bubVector updu(nJ);\n  updu = u0; // updu+=du;\n  sotDEBUG(5) << \"updu = \" << (MATLAB)updu << std::endl;\n  for (ConstraintList::const_iterator iter = constraintS.begin();\n       iter != constraintS.end(); ++iter) {\n    const ConstraintMem &cs = *iter;\n    if (!cs.equality) {\n      const double Ju = bub::inner_prod(cs.Ji, updu);\n      sotDEBUG(55) << \"J = \" << (MATLAB)cs.Ji << std::endl;\n      sotDEBUG(55) << \"Ju = \" << Ju << std::endl;\n\n      if (cs.boundSide & ConstraintMem::BOUND_INF) {\n        slackInf(cs.constraintRow) = cs.eiInf - Ju;\n      } else {\n        slackInf(cs.constraintRow) = 0;\n      }\n      if (cs.boundSide & ConstraintMem::BOUND_SUP) {\n        slackSup(cs.constraintRow) = Ju - cs.eiSup;\n      } else {\n        slackSup(cs.constraintRow) = 0;\n      }\n    }\n  }\n  sotDEBUG(5) << \"slackInf = \" << (MATLAB)slackInf << std::endl;\n  sotDEBUG(5) << \"slackSup = \" << (MATLAB)slackSup << std::endl;\n}\nvoid SolverHierarchicalInequalities::computeLagrangian(void) {\n  if (rankh == 0)\n    return;\n  lagrangian.resize(rankh, false);\n  lagrangian.clear();\n\n  /* bs <- Js' (es - Js.u) */\n  bubVector bs(nJ);\n  computeGradient(bs);\n  sotDEBUG(15) << \"bs = \" << (MATLAB)bs << std::endl;\n  /* bs <- Qh' Js' (es - Js.u) */\n  /* ms <- Mh' Js' (es - Js.u) */\n  bub::vector_range<bubVector> Mbs = Qh.multiplyRangeLeft(bs, 0, freeRank);\n  sotDEBUG(45) << \"Qbs = \" << (MATLAB)bs << std::endl;\n  sotDEBUG(45) << \"Mbs = \" << (MATLAB)Mbs << std::endl;\n  Mbs *= -1;\n  /* Mbs <- R0^-1 Mh' Js' (-es + Js.u) */\n  sotDEBUG(45) << \"Rh = \" << (MATLAB)accessRhConst() << std::endl;\n  bub::lu_substitute(accessRhConst(), Mbs);\n  sotDEBUG(45) << \"RMbs = \" << (MATLAB)Mbs << std::endl;\n\n  lagrangian.resize(Mbs.size(), false);\n  for (ConstraintList::iterator iter = constraintH.begin();\n       iter != constraintH.end(); ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.active && cs.rankIncreaser) {\n      const unsigned int range = cs.range;\n      if (cs.activeSide & ConstraintMem::BOUND_INF) {\n        lagrangian(range) = Mbs(range);\n      } else if (cs.activeSide & ConstraintMem::BOUND_SUP) {\n        lagrangian(range) = -Mbs(range);\n      }\n    }\n  }\n  // lagrangian.assign(Mbs);\n  sotDEBUG(5) << \"lagrangian = \" << (MATLAB)lagrangian << std::endl;\n}\n\n/* ---------------------------------------------------------- */\nbool SolverHierarchicalInequalities::selecActivationHierarchic(double &tau) {\n  tau = 1 - THRESHOLD_ZERO;\n  unsigned int constraintRef = 0;\n  bool res = false;\n  for (ConstraintList::iterator iter = constraintH.begin();\n       iter != constraintH.end(); ++iter, ++constraintRef) {\n    ConstraintMem &cs = *iter;\n    if (!(cs.active || cs.notToBeConsidered)) {\n      cs.Ju = bub::inner_prod(cs.Ji, u0);\n      cs.Jdu = bub::inner_prod(cs.Ji, du);\n      /* Activation Inf. */\n      if (cs.Jdu < -THRESHOLD_ZERO &&\n          (cs.boundSide & ConstraintMem::BOUND_INF)) {\n        const double taui = (cs.eiInf - cs.Ju) / cs.Jdu;\n        if (taui < tau) // If not: activate i.\n        {\n          tau = taui;\n          HactivationRef = constraintRef;\n          HactivationSide = ConstraintMem::BOUND_INF;\n          res = true;\n        }\n      }\n      /* Activation Sup. */\n      if (cs.Jdu > THRESHOLD_ZERO &&\n          (cs.boundSide & ConstraintMem::BOUND_SUP)) {\n        const double taui = (cs.eiSup - cs.Ju) / cs.Jdu;\n        if (taui < tau) // If not: activate i.\n        {\n          tau = taui;\n          HactivationRef = constraintRef;\n          HactivationSide = ConstraintMem::BOUND_SUP;\n          res = true;\n        }\n      }\n    }\n  }\n  if (res) {\n    sotDEBUG(1) << \"Activation H <\" << HactivationSide << HactivationRef << \">\"\n                << std::endl;\n  }\n  return res;\n}\nbool SolverHierarchicalInequalities::selecInactivationHierarchic(void) {\n  bool res = false;\n  double HinactivationScore = -THRESHOLD_ZERO;\n  for (ConstraintList::iterator iter = constraintH.begin();\n       iter != constraintH.end(); ++iter) {\n    ConstraintMem &cs = *iter;\n    if (cs.active && (!cs.equality) && cs.rankIncreaser) {\n      const double &l = cs.lagrangian = lagrangian(cs.range);\n      if (l < HinactivationScore) {\n        HinactivationScore = l;\n        res = true;\n        HinactivationRef = cs.constraintRow;\n      }\n    }\n    sotDEBUG(45) << cs << std::endl;\n  }\n  if (res) {\n    sotDEBUG(1) << \"Inactivation H <\"\n                << constraintH[HinactivationRef].activeSide << HinactivationRef\n                << \">\" << constraintH[HinactivationRef] << std::endl;\n  }\n  return res;\n}\n/* The slack w = es-Js.u should be negative. */\nbool SolverHierarchicalInequalities::selecActivationSlack(void) {\n  unsigned int row = 0;\n  SactivationScore = THRESHOLD_ZERO;\n  for (ConstraintList::const_iterator iter = constraintS.begin();\n       iter != constraintS.end(); ++iter, ++row) {\n    // Slack should be negative\n    if ((!iter->equality) && (!iter->active)) {\n      if (slackInf(row) > SactivationScore) {\n        SactivationRef = row;\n        SactivationScore = slackInf(row);\n        SactivationSide = ConstraintMem::BOUND_INF;\n      }\n      if (slackSup(row) > SactivationScore) {\n        SactivationRef = row;\n        SactivationScore = slackSup(row);\n        SactivationSide = ConstraintMem::BOUND_SUP;\n      }\n    }\n  }\n  if (SactivationScore > THRESHOLD_ZERO) {\n    sotDEBUG(1) << \"Activation S <\" << SactivationSide << SactivationRef << \">\"\n                << std::endl;\n  }\n  return SactivationScore > THRESHOLD_ZERO;\n}\n/* The slack should be negative. If strickly negative: unactivate. */\nbool SolverHierarchicalInequalities::selecInactivationSlack(void) {\n  unsigned int row = 0;\n  SinactivationScore = -THRESHOLD_ZERO;\n  for (ConstraintList::const_iterator iter = constraintS.begin();\n       iter != constraintS.end(); ++iter, ++row) {\n    if ((!iter->equality) && (iter->active)) {\n      if ((iter->activeSide & ConstraintMem::BOUND_INF) &&\n          (slackInf(row) < SinactivationScore)) {\n        SinactivationRef = row;\n        SinactivationScore = slackInf(row);\n      }\n      if ((iter->activeSide & ConstraintMem::BOUND_SUP) &&\n          (slackSup(row) < SinactivationScore)) {\n        SinactivationRef = row;\n        SinactivationScore = slackSup(row);\n      }\n    }\n  }\n  if (SinactivationScore < -THRESHOLD_ZERO) {\n    sotDEBUG(1) << \"Inactivation S <\"\n                << constraintS[SinactivationRef].activeSide << SinactivationRef\n                << \">\" << std::endl;\n  }\n  return (SinactivationScore < -THRESHOLD_ZERO); // TODO\n}\n\n/* ---------------------------------------------------------- */\nvoid SolverHierarchicalInequalities::pushBackSlackToHierarchy(void) {\n  if (freeRank > 0) {\n    /* Pe is the range of the actual column of QR in the original\n     * matrix: QR[:,i] == Jse'[:,pe(i)]. */\n    // sotDEBUG(15) << \"pe = \" << orderSe << std::endl;\n    /* Ps is the range of the columns of Rs in the QR matrix:\n     * R[:,i]=QR[:,ps(i)]. */\n    sotDEBUG(15) << \"ps = \" << (MATLAB)orderS << std::endl;\n    sotDEBUG(15) << \"ranks = \" << ranks << std::endl;\n\n    /* Push back S constraints. */\n    for (ConstraintList::iterator iter = constraintS.begin();\n         iter != constraintS.end(); ++iter) {\n      ConstraintMem &cs = *iter;\n      if (cs.active) {\n        const unsigned int nbcInJ = cs.constraintRow;\n        if (!cs.equality) {\n          if (cs.activeSide == ConstraintMem::BOUND_INF)\n            cs.equality = (slackInf(nbcInJ) > THRESHOLD_ZERO);\n          if (cs.activeSide == ConstraintMem::BOUND_SUP)\n            cs.equality = (slackSup(nbcInJ) > THRESHOLD_ZERO);\n        }\n      }\n      cs.constraintRow = constraintH.size();\n      constraintH.push_back(cs);\n      sotDEBUG(15) << \"Add S cs: \" << cs << std::endl;\n    }\n\n    /* Push back Rs. */\n    sotRotationComposed Qlast;\n    for (unsigned int i = 0; i < ranks; ++i) {\n      typedef bub::matrix_column<bubMatrixQRWide> bubQJsCol;\n      bubQJsCol QJk(QhJs, orderS(i));\n      Qlast.multiplyLeft(QJk);\n      sotDEBUG(45) << \"QhJs_\" << i << \" = \" << (MATLAB)QJk << std::endl;\n      bub::vector_range<bubQJsCol> Ftdown(QJk, freerange());\n      double beta;\n      double normSignFt = sotRotationSimpleHouseholder::householderExtraction(\n          Ftdown, beta, THRESHOLD_ZERO);\n      sotDEBUG(45) << \"Ft_\" << i << \" = \" << (MATLAB)Ftdown << std::endl;\n      sotDEBUG(45) << \"b_\" << i << \" = \" << beta << std::endl;\n      if (fabs(beta) > THRESHOLD_ZERO) {\n        Qlast.pushBack(sotRotationSimpleHouseholder(Ftdown, beta));\n      }\n\n      bub::matrix_column<bubMatrix> Rhk(Rh, rankh);\n      bub::project(Rhk, rangeh()).assign(bub::project(QJk, rangeh()));\n      bub::project(Rhk, freerange()).assign(bub::zero_vector<double>(freeRank));\n      Rh(rankh, rankh) = normSignFt;\n      sotDEBUG(45) << \"Rh_\" << i << \" = \" << (MATLAB)Rhk << std::endl;\n\n      const unsigned int colInH = constraintSactive[orderS(i)]->constraintRow;\n      constraintH[colInH].range = rankh;\n      sotDEBUG(15) << \"Constraint S \" << i << \" (rangeS=\" << orderS(i)\n                   << \") set in H \" << rankh << \": \" << constraintH[colInH]\n                   << std::endl;\n      rankh++;\n      freeRank--;\n    }\n    Qh.pushBack(Qlast);\n\n  } else {\n    for (ConstraintList::iterator iter = constraintS.begin();\n         iter != constraintS.end(); ++iter) {\n      ConstraintMem &cs = *iter;\n      cs.rankIncreaser = false;\n      cs.constraintRow = constraintH.size();\n      constraintH.push_back(cs);\n      sotDEBUG(15) << \"Add rank-void cs: \" << constraintH.back() << std::endl;\n    }\n  }\n\n  if (rankh + freeRank != nJ) {\n    std::cerr << \"Error: ( rankh+freeRank!=nJ ). \" << std::endl;\n    throw \"Error: ( rankh+freeRank!=nJ ). \";\n  }\n\n  sotDEBUG(15) << \"Qh = \" << Qh << std::endl;\n  sotDEBUG(15) << \"Rh = \" << (MATLAB)accessRhConst() << std::endl;\n}\n\ndouble SolverHierarchicalInequalities::THRESHOLD_ZERO = 1e-6;\n", "meta": {"hexsha": "46a68213dda7e952d4483e3fa5bdf9ec59e69fb1", "size": 72362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sot/solver-hierarchical-inequalities.cpp", "max_stars_repo_name": "florent-lamiraux/sot-core", "max_stars_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "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/sot/solver-hierarchical-inequalities.cpp", "max_issues_repo_name": "florent-lamiraux/sot-core", "max_issues_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "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/sot/solver-hierarchical-inequalities.cpp", "max_forks_repo_name": "florent-lamiraux/sot-core", "max_forks_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "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": 36.7133434805, "max_line_length": 108, "alphanum_fraction": 0.573436334, "num_tokens": 21933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.18248227404489661}}
{"text": "\n#include <iostream>\n\n#include <openqube/molecule.h>\n#include <openqube/atom.h>\n\n#include <Eigen/Geometry>\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nusing OpenQube::Atom;\nusing OpenQube::Molecule;\n\nusing Eigen::Vector3d;\n\nnamespace {\n\ntemplate<typename A, typename B>\nvoid checkResult(const A& result, const B& expected, bool &error)\n{\n  if (result != expected) {\n    cerr << \"Error, expected result \" << expected << \", got \" << result << endl;\n    error = true;\n  }\n}\n\n}\n\nshort testAtomConst(const Molecule& mol, size_t index)\n{\n  return mol.atom(index).atomicNumber();\n}\n\nint testatom(int , char *[])\n{\n  bool error = false;\n  cout << \"Testing the atom class...\" << endl;\n\n  Molecule mol;\n  Atom a = mol.addAtom(Vector3d(0.0, 1.0, 0.0), 1);\n\n  checkResult(a.isValid(), true, error);\n  checkResult(a.isHydrogen(), true, error);\n  checkResult(a.atomicNumber(), 1, error);\n  a.setAtomicNumber(69);\n  checkResult(a.isHydrogen(), false, error);\n  checkResult(a.atomicNumber(), 69, error);\n  checkResult(a.pos(), Vector3d(0.0, 1.0, 0.0), error);\n  a.setPos(Vector3d(1.0, 1.0, 1.0));\n  checkResult(a.pos(), Vector3d(1.0, 1.0, 1.0), error);\n\n  Atom a2 = mol.atom(1);\n  checkResult(a2.isValid(), false, error);\n  checkResult(a2.isHydrogen(), false, error);\n  a2.setAtomicNumber(1);\n  checkResult(a2.isHydrogen(), false, error);\n  a2.setPos(Vector3d(1.0, 1.0, 1.0));\n  checkResult(a2.pos(), Vector3d::Zero(), error);\n\n  cout << \"Number of atoms = \" << mol.numAtoms() << endl;\n\n  Atom carbon = mol.addAtom(Vector3d::Zero(), 6);\n\n  cout << \"Number of atoms = \" << mol.numAtoms() << endl;\n\n  const Atom carbonCopy = mol.atom(1);\n  checkResult(carbon.atomicNumber(), carbonCopy.atomicNumber(), error);\n  checkResult(carbon.atomicNumber(), testAtomConst(mol, 1), error);\n  carbon.setAtomicNumber(7);\n  checkResult(carbon.atomicNumber(), carbonCopy.atomicNumber(), error);\n\n  mol.print();\n\n  return error ? 1 : 0;\n}\n", "meta": {"hexsha": "9758a9719e4fec47c6d0eb4501ade7763f26887c", "size": 1913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openqube/testing/testatom.cpp", "max_stars_repo_name": "OpenChemistry/openqube", "max_stars_repo_head_hexsha": "dc396bcf6c74cbfd9fb94201312e70bb377b0805", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T19:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T12:27:40.000Z", "max_issues_repo_path": "openqube/testing/testatom.cpp", "max_issues_repo_name": "OpenChemistry/openqube", "max_issues_repo_head_hexsha": "dc396bcf6c74cbfd9fb94201312e70bb377b0805", "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": "openqube/testing/testatom.cpp", "max_forks_repo_name": "OpenChemistry/openqube", "max_forks_repo_head_hexsha": "dc396bcf6c74cbfd9fb94201312e70bb377b0805", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:25:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T17:47:47.000Z", "avg_line_length": 24.5256410256, "max_line_length": 80, "alphanum_fraction": 0.6649242028, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.18231697478251419}}
{"text": "// Copyright (c) 2021 The Pingvincoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <boost/random/uniform_int.hpp>\n\n\n#include \"policy/policy.h\"\n#include \"arith_uint256.h\"\n#include \"pingvincoin.h\"\n#include \"txmempool.h\"\n#include \"util.h\"\n#include \"validation.h\"\n#include \"pingvincoin-fees.h\"\n#include \"amount.h\"\n#ifdef ENABLE_WALLET\n#include \"wallet/wallet.h\"\n#endif\n\n#ifdef ENABLE_WALLET\n\nCFeeRate GetPingvincoinFeeRate(int priority)\n{\n    switch(priority)\n    {\n    case SUCH_EXPENSIVE:\n        return CFeeRate(COIN / 100 * 521); // 5.21 DOGE, but very carefully avoiding floating point maths\n    case MANY_GENEROUS:\n        return CFeeRate(CWallet::minTxFee.GetFeePerK() * 100);\n    case AMAZE:\n        return CFeeRate(CWallet::minTxFee.GetFeePerK() * 10);\n    case WOW:\n        return CFeeRate(CWallet::minTxFee.GetFeePerK() * 5);\n    case MORE:\n        return CFeeRate(CWallet::minTxFee.GetFeePerK() * 2);\n    case MINIMUM:\n    default:\n        break;\n    }\n    return CWallet::minTxFee;\n}\n\nconst std::string GetPingvincoinPriorityLabel(int priority)\n{\n    switch(priority)\n    {\n    case SUCH_EXPENSIVE:\n        return _(\"Such expensive\");\n    case MANY_GENEROUS:\n        return _(\"Many generous\");\n    case AMAZE:\n        return _(\"Amaze\");\n    case WOW:\n        return _(\"Wow\");\n    case MORE:\n        return _(\"More\");\n    case MINIMUM:\n        return _(\"Minimum\");\n    default:\n        break;\n    }\n    return _(\"Default\");\n}\n\n#endif\n\nCAmount GetPingvincoinMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)\n{\n    {\n        LOCK(mempool.cs);\n        uint256 hash = tx.GetHash();\n        double dPriorityDelta = 0;\n        CAmount nFeeDelta = 0;\n        mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);\n        if (dPriorityDelta > 0 || nFeeDelta > 0)\n            return 0;\n    }\n\n    CAmount nMinFee = ::minRelayTxFeeRate.GetFee(nBytes);\n    nMinFee += GetPingvincoinDustFee(tx.vout, nDustLimit);\n\n    if (fAllowFree)\n    {\n        // There is a free transaction area in blocks created by most miners,\n        // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000\n        //   to be considered to fall into this category. We don't want to encourage sending\n        //   multiple transactions instead of one big transaction to avoid fees.\n        if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))\n            nMinFee = 0;\n    }\n\n    if (!MoneyRange(nMinFee))\n        nMinFee = MAX_MONEY;\n    return nMinFee;\n}\n\nCAmount GetPingvincoinDustFee(const std::vector<CTxOut> &vout, const CAmount dustLimit) {\n    CAmount nFee = 0;\n\n    // To limit dust spam, add the dust limit for each output\n    // less than the (soft) dustlimit\n    BOOST_FOREACH(const CTxOut& txout, vout)\n        if (txout.IsDust(dustLimit))\n            nFee += dustLimit;\n\n    return nFee;\n}\n", "meta": {"hexsha": "b1b675cec93e7d26bb4ef5df14f695ee6905164c", "size": 2946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pingvincoin-fees.cpp", "max_stars_repo_name": "vashshawn/Pingvin-master", "max_stars_repo_head_hexsha": "faa58e4f9adac4d7452309a73bdbfc39b7238db1", "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/pingvincoin-fees.cpp", "max_issues_repo_name": "vashshawn/Pingvin-master", "max_issues_repo_head_hexsha": "faa58e4f9adac4d7452309a73bdbfc39b7238db1", "max_issues_repo_licenses": ["MIT"], "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/pingvincoin-fees.cpp", "max_forks_repo_name": "vashshawn/Pingvin-master", "max_forks_repo_head_hexsha": "faa58e4f9adac4d7452309a73bdbfc39b7238db1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-19T19:39:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T19:39:25.000Z", "avg_line_length": 27.2777777778, "max_line_length": 105, "alphanum_fraction": 0.6564833673, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.1823169711481739}}
{"text": "/*\n//\n// DEKAF(tm): Lighter, Faster, Smarter(tm)\n//\n// Copyright (c) 2017, Ridgeware, Inc.\n//\n// +-------------------------------------------------------------------------+\n// | /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\|\n// |/+---------------------------------------------------------------------+/|\n// |/|                                                                     |/|\n// |\\|  ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE **  |\\|\n// |/|                                                                     |/|\n// |\\|   OPEN SOURCE LICENSE                                               |\\|\n// |/|                                                                     |/|\n// |\\|   Permission is hereby granted, free of charge, to any person       |\\|\n// |/|   obtaining a copy of this software and associated                  |/|\n// |\\|   documentation files (the \"Software\"), to deal in the              |\\|\n// |/|   Software without restriction, including without limitation        |/|\n// |\\|   the rights to use, copy, modify, merge, publish,                  |\\|\n// |/|   distribute, sublicense, and/or sell copies of the Software,       |/|\n// |\\|   and to permit persons to whom the Software is furnished to        |\\|\n// |/|   do so, subject to the following conditions:                       |/|\n// |\\|                                                                     |\\|\n// |/|   The above copyright notice and this permission notice shall       |/|\n// |\\|   be included in all copies or substantial portions of the          |\\|\n// |/|   Software.                                                         |/|\n// |\\|                                                                     |\\|\n// |/|   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY         |/|\n// |\\|   KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE        |\\|\n// |/|   WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR           |/|\n// |\\|   PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS        |\\|\n// |/|   OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR          |/|\n// |\\|   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR        |\\|\n// |/|   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE         |/|\n// |\\|   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.            |\\|\n// |/|                                                                     |/|\n// |/+---------------------------------------------------------------------+/|\n// |\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ |\n// +-------------------------------------------------------------------------+\n//\n*/\n\n#include <boost/archive/iterators/base64_from_binary.hpp>\n#include <boost/archive/iterators/binary_from_base64.hpp>\n#include <boost/archive/iterators/insert_linebreaks.hpp>\n#include <boost/archive/iterators/transform_width.hpp>\n#include <boost/archive/iterators/remove_whitespace.hpp>\n\n#include \"kbase64.h\"\n#include \"klog.h\"\n\nnamespace dekaf2 {\n\n//-----------------------------------------------------------------------------\nKString KBase64::Encode(KStringView sInput, bool bWithLinebreaks)\n//-----------------------------------------------------------------------------\n{\n\tusing namespace boost::archive::iterators;\n\tusing iterator_type = KStringView::const_iterator;\n\tusing base64_enc_lf = insert_linebreaks<base64_from_binary<transform_width<iterator_type, 6, 8> >, 76>;\n\tusing base64_enc    = base64_from_binary<transform_width<iterator_type, 6, 8> >;\n\n\tKString out;\n\n\t// calculate final size for encoded string\n\tKString::size_type iSize = sInput.size() * 8 / 6 + sInput.size() % 3;\n\t// add linefeeds\n\tiSize += iSize / 76;\n\t// and reserve buffer to avoid reallocations\n\tout.reserve(iSize);\n\n\t// transform to base64\n\tif (bWithLinebreaks)\n\t{\n\t\tout.assign(base64_enc_lf(sInput.begin()), base64_enc_lf(sInput.end()));\n\t}\n\telse\n\t{\n\t\tout.assign(base64_enc(sInput.begin()), base64_enc(sInput.end()));\n\t}\n\n\t// append the padding\n\tout.append((3 - sInput.size() % 3) % 3, '=');\n\n\treturn out;\n\n} // Encode\n\n//-----------------------------------------------------------------------------\nKString KBase64::Decode(KStringView sInput)\n//-----------------------------------------------------------------------------\n{\n\tusing namespace boost::archive::iterators;\n\tusing iterator_type = KStringView::const_iterator;\n\tusing base64_dec    = transform_width<binary_from_base64<remove_whitespace<iterator_type> >, 8, 6>;\n\n\tKString out;\n\n\tDEKAF2_TRY\n\t{\n\t\t// calculate approximate size for decoded string (input may contain whitespace)\n\t\tKString::size_type iSize = sInput.size() * 6 / 8;\n\t\t// and reserve buffer to avoid reallocations\n\t\tout.reserve(iSize);\n\n\t\t// transform from base64\n\t\tout.assign(base64_dec(sInput.begin()), base64_dec(sInput.end()));\n\n\t\t// remove the padding\n\t\tKStringView::size_type len = sInput.size();\n\t\tif (len > 2 && out.size() > 1)\n\t\t{\n\t\t\t// a padded sInput has at least 3 chars\n\t\t\tif (sInput[len-1] == '=')\n\t\t\t{\n\t\t\t\tif (sInput[len-2] == '=')\n\t\t\t\t{\n\t\t\t\t\tout.erase(out.size()-2, 2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tout.erase(out.size()-1, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tDEKAF2_CATCH(const std::exception& ex)\n\t{\n#ifdef DEKAF2_IS_WINDOWS\n\t\tex.what();\n#endif\n\t\tkDebug(1, \"invalid base64: {}..\", sInput.Left(40));\n\t\tout.clear();\n\t}\n\n\treturn out;\n\n} // Decode\n\n\n// copied from boost, adapted for URL safe character set\n// https://www.boost.org/doc/libs/1_68_0/boost/archive/iterators/base64_from_binary.hpp\n\nnamespace detail {\n\ntemplate<class CharType>\nstruct from_6_bit_url {\n    typedef CharType result_type;\n    CharType operator()(CharType t) const{\n        static const char * lookup_table =\n            \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n            \"abcdefghijklmnopqrstuvwxyz\"\n            \"0123456789\"\n            \"-_\";\n        BOOST_ASSERT(t < 64);\n        return lookup_table[static_cast<size_t>(t)];\n    }\n};\n\ntemplate<\n    class Base,\n    class CharType = typename boost::iterator_value<Base>::type\n>\nclass base64url_from_binary :\n\tpublic boost::transform_iterator<\n        detail::from_6_bit_url<CharType>,\n        Base\n    >\n{\n    friend class boost::iterator_core_access;\n\ttypedef boost::transform_iterator<\n        typename detail::from_6_bit_url<CharType>,\n        Base\n    > super_t;\n\npublic:\n    template<class T>\n    base64url_from_binary(T start) :\n        super_t(\n            Base(static_cast< T >(start)),\n            detail::from_6_bit_url<CharType>()\n        )\n    {}\n    base64url_from_binary(const base64url_from_binary & rhs) :\n        super_t(\n            Base(rhs.base_reference()),\n            detail::from_6_bit_url<CharType>()\n        )\n    {}\n};\n\n} // namespace detail (end of copy from boost)\n\n\n//-----------------------------------------------------------------------------\nKString KBase64Url::Encode(KStringView sInput)\n//-----------------------------------------------------------------------------\n{\n\tusing namespace boost::archive::iterators;\n\tusing iterator_type = KStringView::const_iterator;\n\tusing base64_enc    = detail::base64url_from_binary<transform_width<iterator_type, 6, 8> >;\n\n\tKString out;\n\n\t// calculate final size for encoded string\n\tKString::size_type iSize = sInput.size() * 8 / 6;\n\t// and reserve buffer to avoid reallocations\n\tout.reserve(iSize);\n\n\t// transform to base64\n\tout.assign(base64_enc(sInput.begin()), base64_enc(sInput.end()));\n\n\treturn out;\n\n} // Encode\n\n// copied from boost, adapted for URL safe character set (works with\n// both character sets actually)\n// https://www.boost.org/doc/libs/1_68_0/boost/archive/iterators/binary_from_base64.hpp\n\t\nnamespace detail {\n\ntemplate<class CharType>\nstruct to_6_bit_url {\n    typedef CharType result_type;\n    CharType operator()(CharType t) const{\n        static const signed char lookup_table[] = {\n            -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n            -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n            -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,62,-1,63,\n            52,53,54,55,56,57,58,59,60,61,-1,-1,-1, 0,-1,-1, // render '=' as 0\n            -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,\n            15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,63,\n            -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,\n            41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1\n        };\n        signed char value = -1;\n        if((unsigned)t <= 127)\n            value = lookup_table[(unsigned)t];\n        if(-1 == value)\n            boost::serialization::throw_exception(\n\t\t\t\tboost::archive::iterators::dataflow_exception(boost::archive::iterators::dataflow_exception::invalid_base64_character)\n            );\n        return value;\n    }\n};\n\ntemplate<\n    class Base,\n    class CharType = typename boost::iterator_value<Base>::type\n>\nclass binary_from_base64url : public\n\tboost::transform_iterator<\n        detail::to_6_bit_url<CharType>,\n        Base\n    >\n{\n    friend class boost::iterator_core_access;\n\ttypedef boost::transform_iterator<\n        detail::to_6_bit_url<CharType>,\n        Base\n    > super_t;\npublic:\n    template<class T>\n    binary_from_base64url(T  start) :\n        super_t(\n            Base(static_cast< T >(start)),\n            detail::to_6_bit_url<CharType>()\n        )\n    {}\n    binary_from_base64url(const binary_from_base64url & rhs) :\n        super_t(\n            Base(rhs.base_reference()),\n            detail::to_6_bit_url<CharType>()\n        )\n    {}\n};\n\n} // namespace detail (end of copy from boost)\n\n//-----------------------------------------------------------------------------\nKString KBase64Url::Decode(KStringView sInput)\n//-----------------------------------------------------------------------------\n{\n\tusing namespace boost::archive::iterators;\n\tusing iterator_type = KStringView::const_iterator;\n\tusing base64_dec    = transform_width<detail::binary_from_base64url<remove_whitespace<iterator_type> >, 8, 6>;\n\n\tKString out;\n\n\tDEKAF2_TRY\n\t{\n\t\t// calculate approximate size for decoded string (input may contain whitespace)\n\t\tKString::size_type iSize = sInput.size() * 6 / 8;\n\t\t// and reserve buffer to avoid reallocations\n\t\tout.reserve(iSize);\n\n\t\t// transform from base64\n\t\tout.assign(base64_dec(sInput.begin()), base64_dec(sInput.end()));\n\n\t\t// remove the padding if any\n\t\tKStringView::size_type len = sInput.size();\n\t\tif (len > 2 && out.size() > 1)\n\t\t{\n\t\t\t// a padded sInput has at least 3 chars\n\t\t\tif (sInput[len-1] == '=')\n\t\t\t{\n\t\t\t\tif (sInput[len-2] == '=')\n\t\t\t\t{\n\t\t\t\t\tout.erase(out.size()-2, 2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tout.erase(out.size()-1, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tDEKAF2_CATCH(const std::exception& ex)\n\t{\n#ifdef DEKAF2_IS_WINDOWS\n\t\tex.what();\n#endif\n\t\tkDebug(1, \"invalid base64: {}..\", sInput.Left(40));\n\t\tout.clear();\n\t}\n\n\treturn out;\n\n} // Decode\n\n} // end of namespace dekaf2\n\n", "meta": {"hexsha": "456f1564d418e2588722bb25effc9a94c1726899", "size": 10766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kbase64.cpp", "max_stars_repo_name": "ridgeware/dekaf2", "max_stars_repo_head_hexsha": "b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33", "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": "kbase64.cpp", "max_issues_repo_name": "ridgeware/dekaf2", "max_issues_repo_head_hexsha": "b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kbase64.cpp", "max_forks_repo_name": "ridgeware/dekaf2", "max_forks_repo_head_hexsha": "b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T16:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T16:15:01.000Z", "avg_line_length": 32.2335329341, "max_line_length": 122, "alphanum_fraction": 0.5365038083, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.18231696751383372}}
{"text": "/******************************************************************************\n * Copyright 2017 The Apollo 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\n#include \"modules/localization/msf/local_gnss/gnss_positioning.h\"\n#include <Eigen/Eigen>\n#include <vector>\n#include \"modules/localization/msf/local_gnss/atmosphere.h\"\n#include \"modules/localization/msf/local_gnss/gnss_utility.hpp\"\n\nnamespace apollo {\nnamespace localization {\nnamespace local_gnss {\n\nint GnssDualAntSolver::UpdateBaseCoor(const EpochObservation& rover_obs,\n                                        const EpochObservation& baser_obs) {\n  bool valid_base_coor = baser_obs.has_position_x() &&\n                         baser_obs.has_position_y() &&\n                         baser_obs.has_position_z();\n  strict_synch_ = false;\n  if (!valid_base_coor) {\n    return 0;\n  }\n  // for dual-antenna, the master antenna is moving, update baser coor\n  SetBaserCoordinate(baser_obs.position_x(), baser_obs.position_y(),\n                       baser_obs.position_z());\n  double sec_per_week = apollo::localization::local_gnss::SECOND_PER_WEEK;\n  double t_rover =\n      rover_obs.gnss_week() * sec_per_week + rover_obs.gnss_second_s();\n  double t_baser =\n      baser_obs.gnss_week() * sec_per_week + baser_obs.gnss_second_s();\n  if (fabs(t_rover - t_baser) < GetSynchTimeGapThreshold()) {\n    strict_synch_ = true;\n  }\n  return 1;\n}\n\ndouble GnssDualAntSolver::CorrectYaw(const double& yaw) {\n  // input yaw should be positive in east by north\n  if (yaw > 2 * PI) {\n    return yaw - 2 * PI;\n  } else if (yaw < -2 * PI) {\n    return yaw + 2 * PI;\n  } else {\n    return yaw;\n  }\n}\n\nbool GnssDualAntSolver::CaculateHeading(const PointThreeDim& ant_base,\n                                       const PointThreeDim& ant_slave,\n                                       const PointThreeDim& phase_std) {\n  if (!dual_antenna_mode_) {\n    return false;\n  }\n  double bs_len = gnss_utility::GetDistance(ant_base, ant_slave);\n  if (fabs(bs_len / dual_ant_baseline_len_ - 1.0) / PI * 180.0 >\n      max_heading_std_) {\n    return false;\n  }\n  PointThreeDim dxyz(ant_slave.x - ant_base.x, ant_slave.y - ant_base.y,\n                     ant_slave.z - ant_base.z);\n  PointThreeDim denu = dxyz;\n  gnss_utility::dxyz2enu(ant_base, dxyz, &denu);\n\n  // heading\n  heading_dual_ant_ = atan2(-1.0 * denu.x, denu.y) - rotation_dual_ant_;\n\n  // std of heading\n  dxyz = phase_std;\n  gnss_utility::dxyz2enu(ant_base, dxyz, &denu);\n  double std_level = sqrt(denu.x * denu.x + denu.y * denu.y + denu.z * denu.z);\n\n  // a simple and conservative way for yaw\n  std_heading_ = std_level / dual_ant_baseline_len_;\n\n  return true;\n}\n\nbool GnssDualAntSolver::GetHeadingWithDualAntenna(double* heading,\n                                                      double* hd_std) {\n  *heading = CorrectYaw(-1.0 * heading_dual_ant_ + 2 * PI);\n  *hd_std = std_heading_;\n  return GetFixStatus();\n}\n\nvoid GnssDualAntSolver::SetDualAntennaMode(bool dual_antenna_mode) {\n  dual_antenna_mode_ = dual_antenna_mode;\n}\n\nbool GnssDualAntSolver::SetDualAntLeverArm(\n    const PointThreeDim& ant_primary, const PointThreeDim& ant_secondary) {\n  relative_lever_arm_.x = ant_secondary.x - ant_primary.x;\n  relative_lever_arm_.y = ant_secondary.y - ant_primary.y;\n  relative_lever_arm_.z = ant_secondary.z - ant_primary.z;\n  dual_ant_baseline_len_ = 0.0;\n  dual_ant_baseline_len_ = gnss_utility::GetDistance(ant_primary,\n                          ant_secondary);\n  rotation_dual_ant_ =\n      atan2(-1.0 * relative_lever_arm_.x, relative_lever_arm_.y);\n\n  // dual antennas located strictly in vertical are not supported\n  if (sqrt(relative_lever_arm_.x * relative_lever_arm_.x +\n           relative_lever_arm_.y * relative_lever_arm_.y) < 0.1) {\n    return false;\n  }\n  return true;\n}\n\nint GnssDualAntSolver::SolveHeading(\n    const EpochObservation& rover_obs,\n    GnssPntResult* rover_pnt, double* heading,\n    double* hd_std, bool* valid_heading) {\n  // To do: deal with rover comes earlier than baser\n  strict_synch_ = false;\n  int flag_pnt = -1;\n  flag_pnt = Solve(rover_obs, rover_pnt);\n  // automaticly call update_heading\n  GetHeadingWithDualAntenna(heading, hd_std);\n  *valid_heading = strict_synch_;\n  return flag_pnt;\n}\n\nint GnssDualAntSolver::SolveHeadingWithBaser(\n    const EpochObservation& rover_obs,\n    const EpochObservation& baser_obs,\n    GnssPntResult* rover_pnt, double* heading,\n    double* hd_std, bool* valid_heading) {\n  strict_synch_ = false;\n  int flag_pnt = -1;\n  UpdateBaseCoor(rover_obs, baser_obs);\n  flag_pnt = SolveWithBaser(rover_obs, baser_obs, true, rover_pnt);\n  // automaticly call update_heading\n  GetHeadingWithDualAntenna(heading, hd_std);\n  *valid_heading = strict_synch_;\n  return flag_pnt;\n}\n\n}  // namespace local_gnss\n}  // namespace localization\n}  // namespace apollo\n", "meta": {"hexsha": "b115e729398ed844f98566ea77a04a7dd7d182bf", "size": 5428, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/localization/msf/local_gnss/gnss_heading.cc", "max_stars_repo_name": "renlancai/apollo", "max_stars_repo_head_hexsha": "400c00d28526b21b71dfe699dc38ee7fdfb3e9f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-07T02:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-07T02:40:16.000Z", "max_issues_repo_path": "modules/localization/msf/local_gnss/gnss_heading.cc", "max_issues_repo_name": "renlancai/apollo", "max_issues_repo_head_hexsha": "400c00d28526b21b71dfe699dc38ee7fdfb3e9f8", "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": "modules/localization/msf/local_gnss/gnss_heading.cc", "max_forks_repo_name": "renlancai/apollo", "max_forks_repo_head_hexsha": "400c00d28526b21b71dfe699dc38ee7fdfb3e9f8", "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.477124183, "max_line_length": 79, "alphanum_fraction": 0.6783345615, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.18227752681919396}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_ISEA_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_ISEA_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// This code was entirely written by Nathan Wagner\n// and is in the public domain.\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 isea\n    {\n\n            static const double E = 52.62263186;\n            static const double F = 10.81231696;\n            static const double DEG60 = 1.04719755119659774614;\n            static const double DEG120 = 2.09439510239319549229;\n            static const double DEG72 = 1.25663706143591729537;\n            static const double DEG90 = 1.57079632679489661922;\n            static const double DEG144 = 2.51327412287183459075;\n            static const double DEG36 = 0.62831853071795864768;\n            static const double DEG108 = 1.88495559215387594306;\n            static const double DEG180 = geometry::math::pi<double>();\n            static const double ISEA_SCALE = 0.8301572857837594396028083;\n            static const double V_LAT = 0.46364760899944494524;\n            static const double E_RAD = 0.91843818702186776133;\n            static const double F_RAD = 0.18871053072122403508;\n            static const double TABLE_G = 0.6615845383;\n            static const double TABLE_H = 0.1909830056;\n            static const double RPRIME = 0.91038328153090290025;\n            static const double PRECISION = 0.0000000000005;\n            static const double ISEA_STD_LAT = 1.01722196792335072101;\n            static const double ISEA_STD_LON = .19634954084936207740;\n\n            #define DOWNTRI(tri) (((tri - 1) / 5) % 2 == 1)\n\n            /*\n             * Proj 4 provides its own entry points into\n             * the code, so none of the library functions\n             * need to be global\n             */\n\n            struct hex {\n                    int iso;\n                    int x, y, z;\n            };\n\n            /* y *must* be positive down as the xy /iso conversion assumes this */\n            static\n            int hex_xy(struct hex *h) {\n                if (!h->iso) return 1;\n                if (h->x >= 0) {\n                    h->y = -h->y - (h->x+1)/2;\n                } else {\n                    /* need to round toward -inf, not toward zero, so x-1 */\n                    h->y = -h->y - h->x/2;\n                }\n                h->iso = 0;\n\n                return 1;\n            }\n\n            static\n            int hex_iso(struct hex *h) {\n                if (h->iso) return 1;\n\n                if (h->x >= 0) {\n                    h->y = (-h->y - (h->x+1)/2);\n                } else {\n                    /* need to round toward -inf, not toward zero, so x-1 */\n                    h->y = (-h->y - (h->x)/2);\n                }\n\n                h->z = -h->x - h->y;\n                h->iso = 1;\n                return 1;\n            }\n\n            static\n            int hexbin2(int horizontal, double width, double x, double y,\n                            int *i, int *j) {\n                double z, rx, ry, rz;\n                double abs_dx, abs_dy, abs_dz;\n                int ix, iy, iz, s;\n                struct hex h;\n\n                x = x / cos(30 * geometry::math::d2r<double>()); /* rotated X coord */\n                y = y - x / 2.0; /* adjustment for rotated X */\n\n                /* adjust for actual hexwidth */\n                x /= width;\n                y /= width;\n\n                z = -x - y;\n\n                ix = rx = floor(x + 0.5);\n                iy = ry = floor(y + 0.5);\n                iz = rz = floor(z + 0.5);\n\n                s = ix + iy + iz;\n\n                if (s) {\n                    abs_dx = fabs(rx - x);\n                    abs_dy = fabs(ry - y);\n                    abs_dz = fabs(rz - z);\n\n                    if (abs_dx >= abs_dy && abs_dx >= abs_dz) {\n                        ix -= s;\n                    } else if (abs_dy >= abs_dx && abs_dy >= abs_dz) {\n                        iy -= s;\n                    } else {\n                        iz -= s;\n                    }\n                }\n                h.x = ix;\n                h.y = iy;\n                h.z = iz;\n                h.iso = 1;\n\n                hex_xy(&h);\n                *i = h.x;\n                *j = h.y;\n                    return ix * 100 + iy;\n            }\n\n            enum isea_poly { ISEA_NONE, ISEA_ICOSAHEDRON = 20 };\n            enum isea_topology { ISEA_HEXAGON=6, ISEA_TRIANGLE=3, ISEA_DIAMOND=4 };\n            enum isea_address_form { ISEA_GEO, ISEA_Q2DI, ISEA_SEQNUM, ISEA_INTERLEAVE,\n                ISEA_PLANE, ISEA_Q2DD, ISEA_PROJTRI, ISEA_VERTEX2DD, ISEA_HEX\n            };\n\n            struct isea_dgg {\n                int    polyhedron; /* ignored, icosahedron */\n                double    o_lat, o_lon, o_az; /* orientation, radians */\n                int    pole; /* true if standard snyder */\n                int    topology; /* ignored, hexagon */\n                int    aperture; /* valid values depend on partitioning method */\n                int    resolution;\n                double    radius; /* radius of the earth in meters, ignored 1.0 */\n                int    output; /* an isea_address_form */\n                int    triangle; /* triangle of last transformed point */\n                int    quad; /* quad of last transformed point */\n                unsigned long serial;\n            };\n\n            struct isea_pt {\n                double x, y;\n            };\n\n            struct isea_geo {\n                double lon, lat;\n            };\n\n            struct isea_address {\n                int    type; /* enum isea_address_form */\n                int    number;\n                double    x,y; /* or i,j or lon,lat depending on type */\n            };\n\n            /* ENDINC */\n\n            enum snyder_polyhedron {\n                SNYDER_POLY_HEXAGON, SNYDER_POLY_PENTAGON,\n                SNYDER_POLY_TETRAHEDRON, SNYDER_POLY_CUBE,\n                SNYDER_POLY_OCTAHEDRON, SNYDER_POLY_DODECAHEDRON,\n                SNYDER_POLY_ICOSAHEDRON\n            };\n\n            struct snyder_constants {\n                double          g, G, theta, ea_w, ea_a, ea_b, g_w, g_a, g_b;\n            };\n\n            /* TODO put these in radians to avoid a later conversion */\n            static\n            struct snyder_constants constants[] = {\n                {23.80018260, 62.15458023, 60.0, 3.75, 1.033, 0.968, 5.09, 1.195, 1.0},\n                {20.07675127, 55.69063953, 54.0, 2.65, 1.030, 0.983, 3.59, 1.141, 1.027},\n                {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},\n                {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},\n                {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},\n                {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},\n                {37.37736814, 36.0, 30.0, 17.27, 1.163, 0.860, 13.14, 1.584, 1.0},\n            };\n\n\n            /* sqrt(5)/M_PI */\n\n            /* 26.565051177 degrees */\n\n\n            static\n            struct isea_geo vertex[] = {\n                {0.0, DEG90},\n                {DEG180, V_LAT},\n                {-DEG108, V_LAT},\n                {-DEG36, V_LAT},\n                {DEG36, V_LAT},\n                {DEG108, V_LAT},\n                {-DEG144, -V_LAT},\n                {-DEG72, -V_LAT},\n                {0.0, -V_LAT},\n                {DEG72, -V_LAT},\n                {DEG144, -V_LAT},\n                {0.0, -DEG90}\n            };\n\n            /* TODO make an isea_pt array of the vertices as well */\n\n            static int      tri_v1[] = {0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 2, 3, 4, 5, 1, 11, 11, 11, 11, 11};\n\n            /* 52.62263186 */\n\n            /* 10.81231696 */\n\n            /* triangle Centers */\n            struct isea_geo icostriangles[] = {\n                {0.0, 0.0},\n                {-DEG144, E_RAD},\n                {-DEG72, E_RAD},\n                {0.0, E_RAD},\n                {DEG72, E_RAD},\n                {DEG144, E_RAD},\n                {-DEG144, F_RAD},\n                {-DEG72, F_RAD},\n                {0.0, F_RAD},\n                {DEG72, F_RAD},\n                {DEG144, F_RAD},\n                {-DEG108, -F_RAD},\n                {-DEG36, -F_RAD},\n                {DEG36, -F_RAD},\n                {DEG108, -F_RAD},\n                {DEG180, -F_RAD},\n                {-DEG108, -E_RAD},\n                {-DEG36, -E_RAD},\n                {DEG36, -E_RAD},\n                {DEG108, -E_RAD},\n                {DEG180, -E_RAD},\n            };\n\n            static double\n            az_adjustment(int triangle)\n            {\n                double          adj;\n\n                struct isea_geo v;\n                struct isea_geo c;\n\n                v = vertex[tri_v1[triangle]];\n                c = icostriangles[triangle];\n\n                /* TODO looks like the adjustment is always either 0 or 180 */\n                /* at least if you pick your vertex carefully */\n                adj = atan2(cos(v.lat) * sin(v.lon - c.lon),\n                        cos(c.lat) * sin(v.lat)\n                        - sin(c.lat) * cos(v.lat) * cos(v.lon - c.lon));\n                return adj;\n            }\n\n            /* R tan(g) sin(60) */\n\n            /* H = 0.25 R tan g = */\n\n\n            static\n            struct isea_pt\n            isea_triangle_xy(int triangle)\n            {\n                struct isea_pt  c;\n                double Rprime = 0.91038328153090290025;\n\n                triangle = (triangle - 1) % 20;\n\n                c.x = TABLE_G * ((triangle % 5) - 2) * 2.0;\n                if (triangle > 9) {\n                    c.x += TABLE_G;\n                }\n                switch (triangle / 5) {\n                case 0:\n                    c.y = 5.0 * TABLE_H;\n                    break;\n                case 1:\n                    c.y = TABLE_H;\n                    break;\n                case 2:\n                    c.y = -TABLE_H;\n                    break;\n                case 3:\n                    c.y = -5.0 * TABLE_H;\n                    break;\n                default:\n                    /* should be impossible */\n                    throw proj_exception();\n                };\n                c.x *= Rprime;\n                c.y *= Rprime;\n\n                return c;\n            }\n\n            /* snyder eq 14 */\n            static double\n            sph_azimuth(double f_lon, double f_lat, double t_lon, double t_lat)\n            {\n                double          az;\n\n                az = atan2(cos(t_lat) * sin(t_lon - f_lon),\n                       cos(f_lat) * sin(t_lat)\n                       - sin(f_lat) * cos(t_lat) * cos(t_lon - f_lon)\n                    );\n                return az;\n            }\n\n            /* coord needs to be in radians */\n            static\n            int\n            isea_snyder_forward(struct isea_geo * ll, struct isea_pt * out)\n            {\n                int             i;\n\n                /*\n                 * spherical distance from center of polygon face to any of its\n                 * vertexes on the globe\n                 */\n                double          g;\n\n                /*\n                 * spherical angle between radius vector to center and adjacent edge\n                 * of spherical polygon on the globe\n                 */\n                double          G;\n\n                /*\n                 * plane angle between radius vector to center and adjacent edge of\n                 * plane polygon\n                 */\n                double          theta;\n\n                /* additional variables from snyder */\n                double          q, Rprime, H, Ag, Azprime, Az, dprime, f, rho,\n                                x, y;\n\n                /* variables used to store intermediate results */\n                double          cot_theta, tan_g, az_offset;\n\n                /* how many multiples of 60 degrees we adjust the azimuth */\n                int             Az_adjust_multiples;\n\n                struct snyder_constants c;\n\n                /*\n                 * TODO by locality of reference, start by trying the same triangle\n                 * as last time\n                 */\n\n                /* TODO put these constants in as radians to begin with */\n                c = constants[SNYDER_POLY_ICOSAHEDRON];\n                theta = c.theta * geometry::math::d2r<double>();\n                g = c.g * geometry::math::d2r<double>();\n                G = c.G * geometry::math::d2r<double>();\n\n                for (i = 1; i <= 20; i++) {\n                    double          z;\n                    struct isea_geo center;\n\n                    center = icostriangles[i];\n\n                    /* step 1 */\n            #if 0\n                    z = sph_distance(center.lon, center.lat, ll->lon, ll->lat);\n            #else\n                    z = acos(sin(center.lat) * sin(ll->lat)\n                         + cos(center.lat) * cos(ll->lat) * cos(ll->lon - center.lon));\n            #endif\n\n                    /* not on this triangle */\n                    if (z > g + 0.000005) { /* TODO DBL_EPSILON */\n                        continue;\n                    }\n                    Az = sph_azimuth(ll->lon, ll->lat, center.lon, center.lat);\n\n                    Az = atan2(cos(ll->lat) * sin(ll->lon - center.lon),\n                           cos(center.lat) * sin(ll->lat)\n                    - sin(center.lat) * cos(ll->lat) * cos(ll->lon - center.lon)\n                        );\n\n                    /* step 2 */\n\n                    /* This calculates \"some\" vertex coordinate */\n                    az_offset = az_adjustment(i);\n\n                    Az -= az_offset;\n\n                    /* TODO I don't know why we do this.  It's not in snyder */\n                    /* maybe because we should have picked a better vertex */\n                    if (Az < 0.0) {\n                        Az += geometry::math::two_pi<double>();\n                    }\n                    /*\n                     * adjust Az for the point to fall within the range of 0 to\n                     * 2(90 - theta) or 60 degrees for the hexagon, by\n                     * and therefore 120 degrees for the triangle\n                     * of the icosahedron\n                     * subtracting or adding multiples of 60 degrees to Az and\n                     * recording the amount of adjustment\n                     */\n\n                    Az_adjust_multiples = 0;\n                    while (Az < 0.0) {\n                        Az += DEG120;\n                        Az_adjust_multiples--;\n                    }\n                    while (Az > DEG120 + DBL_EPSILON) {\n                        Az -= DEG120;\n                        Az_adjust_multiples++;\n                    }\n\n                    /* step 3 */\n                    cot_theta = 1.0 / tan(theta);\n                    tan_g = tan(g);    /* TODO this is a constant */\n\n                    /* Calculate q from eq 9. */\n                    /* TODO cot_theta is cot(30) */\n                    q = atan2(tan_g, cos(Az) + sin(Az) * cot_theta);\n\n                    /* not in this triangle */\n                    if (z > q + 0.000005) {\n                        continue;\n                    }\n                    /* step 4 */\n\n                    /* Apply equations 5-8 and 10-12 in order */\n\n                    /* eq 5 */\n                    /* Rprime = 0.9449322893 * R; */\n                    /* R' in the paper is for the truncated */\n                    Rprime = 0.91038328153090290025;\n\n                    /* eq 6 */\n                    H = acos(sin(Az) * sin(G) * cos(g) - cos(Az) * cos(G));\n\n                    /* eq 7 */\n                    /* Ag = (Az + G + H - DEG180) * M_PI * R * R / DEG180; */\n                    Ag = Az + G + H - DEG180;\n\n                    /* eq 8 */\n                    Azprime = atan2(2.0 * Ag, Rprime * Rprime * tan_g * tan_g - 2.0 * Ag * cot_theta);\n\n                    /* eq 10 */\n                    /* cot(theta) = 1.73205080756887729355 */\n                    dprime = Rprime * tan_g / (cos(Azprime) + sin(Azprime) * cot_theta);\n\n                    /* eq 11 */\n                    f = dprime / (2.0 * Rprime * sin(q / 2.0));\n\n                    /* eq 12 */\n                    rho = 2.0 * Rprime * f * sin(z / 2.0);\n\n                    /*\n                     * add back the same 60 degree multiple adjustment from step\n                     * 2 to Azprime\n                     */\n\n                    Azprime += DEG120 * Az_adjust_multiples;\n\n                    /* calculate rectangular coordinates */\n\n                    x = rho * sin(Azprime);\n                    y = rho * cos(Azprime);\n\n                    /*\n                     * TODO\n                     * translate coordinates to the origin for the particular\n                     * hexagon on the flattened polyhedral map plot\n                     */\n\n                    out->x = x;\n                    out->y = y;\n\n                    return i;\n                }\n\n                /*\n                 * should be impossible, this implies that the coordinate is not on\n                 * any triangle\n                 */\n\n                fprintf(stderr, \"impossible transform: %f %f is not on any triangle\\n\",\n                    ll->lon * geometry::math::r2d<double>(), ll->lat * geometry::math::r2d<double>());\n\n                throw proj_exception();\n\n                /* not reached */\n                return 0;        /* supresses a warning */\n            }\n\n            /*\n             * return the new coordinates of any point in orginal coordinate system.\n             * Define a point (newNPold) in orginal coordinate system as the North Pole in\n             * new coordinate system, and the great circle connect the original and new\n             * North Pole as the lon0 longitude in new coordinate system, given any point\n             * in orginal coordinate system, this function return the new coordinates.\n             */\n\n\n            /* formula from Snyder, Map Projections: A working manual, p31 */\n            /*\n             * old north pole at np in new coordinates\n             * could be simplified a bit with fewer intermediates\n             *\n             * TODO take a result pointer\n             */\n            static\n            struct isea_geo\n            snyder_ctran(struct isea_geo * np, struct isea_geo * pt)\n            {\n                struct isea_geo npt;\n                double          alpha, phi, lambda, lambda0, beta, lambdap, phip;\n                double          sin_phip;\n                double          lp_b;    /* lambda prime minus beta */\n                double          cos_p, sin_a;\n\n                phi = pt->lat;\n                lambda = pt->lon;\n                alpha = np->lat;\n                beta = np->lon;\n                lambda0 = beta;\n\n                cos_p = cos(phi);\n                sin_a = sin(alpha);\n\n                /* mpawm 5-7 */\n                sin_phip = sin_a * sin(phi) - cos(alpha) * cos_p * cos(lambda - lambda0);\n\n                /* mpawm 5-8b */\n\n                /* use the two argument form so we end up in the right quadrant */\n                lp_b = atan2(cos_p * sin(lambda - lambda0),\n                   (sin_a * cos_p * cos(lambda - lambda0) + cos(alpha) * sin(phi)));\n\n                lambdap = lp_b + beta;\n\n                /* normalize longitude */\n                /* TODO can we just do a modulus ? */\n                lambdap = fmod(lambdap, geometry::math::two_pi<double>());\n                while (lambdap > geometry::math::pi<double>())\n                    lambdap -= geometry::math::two_pi<double>();\n                while (lambdap < -geometry::math::pi<double>())\n                    lambdap += geometry::math::two_pi<double>();\n\n                phip = asin(sin_phip);\n\n                npt.lat = phip;\n                npt.lon = lambdap;\n\n                return npt;\n            }\n\n            static\n            struct isea_geo\n            isea_ctran(struct isea_geo * np, struct isea_geo * pt, double lon0)\n            {\n                struct isea_geo npt;\n\n                np->lon += geometry::math::pi<double>();\n                npt = snyder_ctran(np, pt);\n                np->lon -= geometry::math::pi<double>();\n\n                npt.lon -= (geometry::math::pi<double>() - lon0 + np->lon);\n\n                /*\n                 * snyder is down tri 3, isea is along side of tri1 from vertex 0 to\n                 * vertex 1 these are 180 degrees apart\n                 */\n                npt.lon += geometry::math::pi<double>();\n                /* normalize longitude */\n                npt.lon = fmod(npt.lon, geometry::math::two_pi<double>());\n                while (npt.lon > geometry::math::pi<double>())\n                    npt.lon -= geometry::math::two_pi<double>();\n                while (npt.lon < -geometry::math::pi<double>())\n                    npt.lon += geometry::math::two_pi<double>();\n\n                return npt;\n            }\n\n            /* in radians */\n\n            /* fuller's at 5.2454 west, 2.3009 N, adjacent at 7.46658 deg */\n\n            static\n            int\n            isea_grid_init(struct isea_dgg * g)\n            {\n                if (!g)\n                    return 0;\n\n                g->polyhedron = 20;\n                g->o_lat = ISEA_STD_LAT;\n                g->o_lon = ISEA_STD_LON;\n                g->o_az = 0.0;\n                g->aperture = 4;\n                g->resolution = 6;\n                g->radius = 1.0;\n                g->topology = 6;\n\n                return 1;\n            }\n\n            static\n            int\n            isea_orient_isea(struct isea_dgg * g)\n            {\n                if (!g)\n                    return 0;\n                g->o_lat = ISEA_STD_LAT;\n                g->o_lon = ISEA_STD_LON;\n                g->o_az = 0.0;\n                return 1;\n            }\n\n            static\n            int\n            isea_orient_pole(struct isea_dgg * g)\n            {\n                if (!g)\n                    return 0;\n                g->o_lat = geometry::math::half_pi<double>();\n                g->o_lon = 0.0;\n                g->o_az = 0;\n                return 1;\n            }\n\n            static\n            int\n            isea_transform(struct isea_dgg * g, struct isea_geo * in,\n                       struct isea_pt * out)\n            {\n                struct isea_geo i, pole;\n                int             tri;\n\n                pole.lat = g->o_lat;\n                pole.lon = g->o_lon;\n\n                i = isea_ctran(&pole, in, g->o_az);\n\n                tri = isea_snyder_forward(&i, out);\n                out->x *= g->radius;\n                out->y *= g->radius;\n                g->triangle = tri;\n\n                return tri;\n            }\n\n\n            static\n            void\n            isea_rotate(struct isea_pt * pt, double degrees)\n            {\n                double          rad;\n\n                double          x, y;\n\n                rad = -degrees * geometry::math::d2r<double>();\n                while (rad >= geometry::math::two_pi<double>()) rad -= geometry::math::two_pi<double>();\n                while (rad <= -geometry::math::two_pi<double>()) rad += geometry::math::two_pi<double>();\n\n                x = pt->x * cos(rad) + pt->y * sin(rad);\n                y = -pt->x * sin(rad) + pt->y * cos(rad);\n\n                pt->x = x;\n                pt->y = y;\n            }\n\n            static\n            int isea_tri_plane(int tri, struct isea_pt *pt, double radius) {\n                struct isea_pt tc; /* center of triangle */\n\n                if (DOWNTRI(tri)) {\n                    isea_rotate(pt, 180.0);\n                }\n                tc = isea_triangle_xy(tri);\n                tc.x *= radius;\n                tc.y *= radius;\n                pt->x += tc.x;\n                pt->y += tc.y;\n\n                return tri;\n            }\n\n            /* convert projected triangle coords to quad xy coords, return quad number */\n            static\n            int\n            isea_ptdd(int tri, struct isea_pt *pt) {\n                int             downtri, quad;\n\n                downtri = (((tri - 1) / 5) % 2 == 1);\n                boost::ignore_unused(downtri);\n                quad = ((tri - 1) % 5) + ((tri - 1) / 10) * 5 + 1;\n\n                isea_rotate(pt, downtri ? 240.0 : 60.0);\n                if (downtri) {\n                    pt->x += 0.5;\n                    /* pt->y += cos(30.0 * M_PI / 180.0); */\n                    pt->y += .86602540378443864672;\n                }\n                return quad;\n            }\n\n            static\n            int\n            isea_dddi_ap3odd(struct isea_dgg *g, int quad, struct isea_pt *pt, struct isea_pt *di)\n            {\n                struct isea_pt  v;\n                double          hexwidth;\n                double          sidelength;    /* in hexes */\n                int             d, i;\n                int             maxcoord;\n                struct hex      h;\n\n                /* This is the number of hexes from apex to base of a triangle */\n                sidelength = (pow(2.0, g->resolution) + 1.0) / 2.0;\n\n                /* apex to base is cos(30deg) */\n                hexwidth = cos(geometry::math::pi<double>() / 6.0) / sidelength;\n\n                /* TODO I think sidelength is always x.5, so\n                 * (int)sidelength * 2 + 1 might be just as good\n                 */\n                maxcoord = (int) (sidelength * 2.0 + 0.5);\n\n                v = *pt;\n                hexbin2(0, hexwidth, v.x, v.y, &h.x, &h.y);\n                h.iso = 0;\n                hex_iso(&h);\n\n                d = h.x - h.z;\n                i = h.x + h.y + h.y;\n\n                /*\n                 * you want to test for max coords for the next quad in the same\n                 * \"row\" first to get the case where both are max\n                 */\n                if (quad <= 5) {\n                    if (d == 0 && i == maxcoord) {\n                        /* north pole */\n                        quad = 0;\n                        d = 0;\n                        i = 0;\n                    } else if (i == maxcoord) {\n                        /* upper right in next quad */\n                        quad += 1;\n                        if (quad == 6)\n                            quad = 1;\n                        i = maxcoord - d;\n                        d = 0;\n                    } else if (d == maxcoord) {\n                        /* lower right in quad to lower right */\n                        quad += 5;\n                        d = 0;\n                    }\n                } else if (quad >= 6) {\n                    if (i == 0 && d == maxcoord) {\n                        /* south pole */\n                        quad = 11;\n                        d = 0;\n                        i = 0;\n                    } else if (d == maxcoord) {\n                        /* lower right in next quad */\n                        quad += 1;\n                        if (quad == 11)\n                            quad = 6;\n                        d = maxcoord - i;\n                        i = 0;\n                    } else if (i == maxcoord) {\n                        /* upper right in quad to upper right */\n                        quad = (quad - 4) % 5;\n                        i = 0;\n                    }\n                }\n\n                di->x = d;\n                di->y = i;\n\n                g->quad = quad;\n                return quad;\n            }\n\n            static\n            int\n            isea_dddi(struct isea_dgg *g, int quad, struct isea_pt *pt, struct isea_pt *di) {\n                struct isea_pt  v;\n                double          hexwidth;\n                int             sidelength;    /* in hexes */\n                struct hex      h;\n\n                if (g->aperture == 3 && g->resolution % 2 != 0) {\n                    return isea_dddi_ap3odd(g, quad, pt, di);\n                }\n                /* todo might want to do this as an iterated loop */\n                if (g->aperture >0) {\n                    sidelength = (int) (pow(static_cast<double>(g->aperture), g->resolution / 2.0) + 0.5);\n                } else {\n                    sidelength = g->resolution;\n                }\n\n                hexwidth = 1.0 / sidelength;\n\n                v = *pt;\n                isea_rotate(&v, -30.0);\n                hexbin2(0, hexwidth, v.x, v.y, &h.x, &h.y);\n                h.iso = 0;\n                hex_iso(&h);\n\n                /* we may actually be on another quad */\n                if (quad <= 5) {\n                    if (h.x == 0 && h.z == -sidelength) {\n                        /* north pole */\n                        quad = 0;\n                        h.z = 0;\n                        h.y = 0;\n                        h.x = 0;\n                    } else if (h.z == -sidelength) {\n                        quad = quad + 1;\n                        if (quad == 6)\n                            quad = 1;\n                        h.y = sidelength - h.x;\n                        h.z = h.x - sidelength;\n                        h.x = 0;\n                    } else if (h.x == sidelength) {\n                        quad += 5;\n                        h.y = -h.z;\n                        h.x = 0;\n                    }\n                } else if (quad >= 6) {\n                    if (h.z == 0 && h.x == sidelength) {\n                        /* south pole */\n                        quad = 11;\n                        h.x = 0;\n                        h.y = 0;\n                        h.z = 0;\n                    } else if (h.x == sidelength) {\n                        quad = quad + 1;\n                        if (quad == 11)\n                            quad = 6;\n                        h.x = h.y + sidelength;\n                        h.y = 0;\n                        h.z = -h.x;\n                    } else if (h.y == -sidelength) {\n                        quad -= 4;\n                        h.y = 0;\n                        h.z = -h.x;\n                    }\n                }\n                di->x = h.x;\n                di->y = -h.z;\n\n                g->quad = quad;\n                return quad;\n            }\n\n            static\n            int isea_ptdi(struct isea_dgg *g, int tri, struct isea_pt *pt,\n                           struct isea_pt *di) {\n                struct isea_pt  v;\n                int             quad;\n\n                v = *pt;\n                quad = isea_ptdd(tri, &v);\n                quad = isea_dddi(g, quad, &v, di);\n                return quad;\n            }\n\n            /* q2di to seqnum */\n            static\n            int isea_disn(struct isea_dgg *g, int quad, struct isea_pt *di) {\n                int             sidelength;\n                int             sn, height;\n                int             hexes;\n\n                if (quad == 0) {\n                    g->serial = 1;\n                    return g->serial;\n                }\n                /* hexes in a quad */\n                hexes = (int) (pow(static_cast<double>(g->aperture), g->resolution) + 0.5);\n                if (quad == 11) {\n                    g->serial = 1 + 10 * hexes + 1;\n                    return g->serial;\n                }\n                if (g->aperture == 3 && g->resolution % 2 == 1) {\n                    height = (int) (pow(static_cast<double>(g->aperture), (g->resolution - 1) / 2.0));\n                    sn = ((int) di->x) * height;\n                    sn += ((int) di->y) / height;\n                    sn += (quad - 1) * hexes;\n                    sn += 2;\n                } else {\n                    sidelength = (int) (pow(static_cast<double>(g->aperture), g->resolution / 2.0) + 0.5);\n                    sn = (quad - 1) * hexes + sidelength * di->x + di->y + 2;\n                }\n\n                g->serial = sn;\n                return sn;\n            }\n\n            /* TODO just encode the quad in the d or i coordinate\n             * quad is 0-11, which can be four bits.\n             * d' = d << 4 + q, d = d' >> 4, q = d' & 0xf\n             */\n            /* convert a q2di to global hex coord */\n            static\n            int isea_hex(struct isea_dgg *g, int tri,\n                    struct isea_pt *pt, struct isea_pt *hex) {\n                struct isea_pt v;\n                int sidelength;\n                int d, i, x, y, quad;\n\n                quad = isea_ptdi(g, tri, pt, &v);\n\n                hex->x = ((int)v.x << 4) + quad;\n                hex->y = v.y;\n\n                return 1;\n\n                d = v.x;\n                i = v.y;\n\n                /* Aperture 3 odd resolutions */\n                if (g->aperture == 3 && g->resolution % 2 != 0) {\n                    int offset = (int)(pow(3.0, g->resolution - 1) + 0.5);\n\n                    d += offset * ((g->quad-1) % 5);\n                    i += offset * ((g->quad-1) % 5);\n\n                    if (quad == 0) {\n                        d = 0;\n                        i = offset;\n                    } else if (quad == 11) {\n                        d = 2 * offset;\n                        i = 0;\n                    } else if (quad > 5) {\n                        d += offset;\n                    }\n\n                    x = (2*d - i) /3;\n                    y = (2*i - d) /3;\n\n                    hex->x = x + offset / 3;\n                    hex->y = y + 2 * offset / 3;\n                    return 1;\n                }\n\n                /* aperture 3 even resolutions and aperture 4 */\n                sidelength = (int) (pow(static_cast<double>(g->aperture), g->resolution / 2.0) + 0.5);\n                if (g->quad == 0) {\n                    hex->x = 0;\n                    hex->y = sidelength;\n                } else if (g->quad == 11) {\n                    hex->x = sidelength * 2;\n                    hex->y = 0;\n                } else {\n                    hex->x = d + sidelength * ((g->quad-1) % 5);\n                    if (g->quad > 5) hex->x += sidelength;\n                    hex->y = i + sidelength * ((g->quad-1) % 5);\n                }\n\n                return 1;\n            }\n\n            static\n            struct isea_pt\n            isea_forward(struct isea_dgg *g, struct isea_geo *in)\n            {\n                int             tri, downtri;\n                struct isea_pt  out, coord;\n\n                tri = isea_transform(g, in, &out);\n\n                downtri = (((tri - 1) / 5) % 2 == 1);\n                boost::ignore_unused(downtri);\n\n                if (g->output == ISEA_PLANE) {\n                    isea_tri_plane(tri, &out, g->radius);\n                    return out;\n                }\n\n                /* convert to isea standard triangle size */\n                out.x = out.x / g->radius * ISEA_SCALE;\n                out.y = out.y / g->radius * ISEA_SCALE;\n                out.x += 0.5;\n                out.y += 2.0 * .14433756729740644112;\n\n                switch (g->output) {\n                case ISEA_PROJTRI:\n                    /* nothing to do, already in projected triangle */\n                    break;\n                case ISEA_VERTEX2DD:\n                    g->quad = isea_ptdd(tri, &out);\n                    break;\n                case ISEA_Q2DD:\n                    /* Same as above, we just don't print as much */\n                    g->quad = isea_ptdd(tri, &out);\n                    break;\n                case ISEA_Q2DI:\n                    g->quad = isea_ptdi(g, tri, &out, &coord);\n                    return coord;\n                    break;\n                case ISEA_SEQNUM:\n                    isea_ptdi(g, tri, &out, &coord);\n                    /* disn will set g->serial */\n                    isea_disn(g, g->quad, &coord);\n                    return coord;\n                    break;\n                case ISEA_HEX:\n                    isea_hex(g, tri, &out, &coord);\n                    return coord;\n                    break;\n                }\n\n                return out;\n            }\n            /*\n             * Proj 4 integration code follows\n             */\n\n            struct par_isea\n            {\n                struct isea_dgg dgg;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_isea_spheroid : public base_t_f<base_isea_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_isea m_proj_parm;\n\n                inline base_isea_spheroid(const Parameters& par)\n                    : base_t_f<base_isea_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)\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                    struct isea_pt out;\n                    struct isea_geo in;\n\n                    in.lon = lp_lon;\n                    in.lat = lp_lat;\n\n                    isea_dgg copy = this->m_proj_parm.dgg;\n                    out = isea_forward(&copy, &in);\n\n                    xy_x = out.x;\n                    xy_y = out.y;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"isea_spheroid\";\n                }\n\n            };\n\n            // Icosahedral Snyder Equal Area\n            template <typename Parameters>\n            void setup_isea(Parameters& par, par_isea& proj_parm)\n            {\n                std::string opt;\n\n                    isea_grid_init(&proj_parm.dgg);\n\n                    proj_parm.dgg.output = ISEA_PLANE;\n            /*        proj_parm.dgg.radius = par.a; / * otherwise defaults to 1 */\n                /* calling library will scale, I think */\n\n                opt = pj_param(par.params, \"sorient\").s;\n                if (! opt.empty()) {\n                    if (opt == std::string(\"isea\")) {\n                        isea_orient_isea(&proj_parm.dgg);\n                    } else if (opt == std::string(\"pole\")) {\n                        isea_orient_pole(&proj_parm.dgg);\n                    } else {\n                        throw proj_exception(-34);\n                    }\n                }\n\n                if (pj_param(par.params, \"tazi\").i) {\n                    proj_parm.dgg.o_az = pj_param(par.params, \"razi\").f;\n                }\n\n                if (pj_param(par.params, \"tlon_0\").i) {\n                    proj_parm.dgg.o_lon = pj_param(par.params, \"rlon_0\").f;\n                }\n\n                if (pj_param(par.params, \"tlat_0\").i) {\n                    proj_parm.dgg.o_lat = pj_param(par.params, \"rlat_0\").f;\n                }\n\n                if (pj_param(par.params, \"taperture\").i) {\n                    proj_parm.dgg.aperture = pj_param(par.params, \"iaperture\").i;\n                }\n\n                if (pj_param(par.params, \"tresolution\").i) {\n                    proj_parm.dgg.resolution = pj_param(par.params, \"iresolution\").i;\n                }\n\n                opt = pj_param(par.params, \"smode\").s;\n                if (! opt.empty()) {\n                    if (opt == std::string(\"plane\")) {\n                        proj_parm.dgg.output = ISEA_PLANE;\n                    } else if (opt == std::string(\"di\")) {\n                        proj_parm.dgg.output = ISEA_Q2DI;\n                    }\n                    else if (opt == std::string(\"dd\")) {\n                        proj_parm.dgg.output = ISEA_Q2DD;\n                    }\n                    else if (opt == std::string(\"hex\")) {\n                        proj_parm.dgg.output = ISEA_HEX;\n                    }\n                    else {\n                        /* TODO verify error code.  Possibly eliminate magic */\n                        throw proj_exception(-34);\n                    }\n                }\n\n                if (pj_param(par.params, \"trescale\").i) {\n                    proj_parm.dgg.radius = ISEA_SCALE;\n                }\n\n                if (pj_param(par.params, \"tresolution\").i) {\n                    proj_parm.dgg.resolution = pj_param(par.params, \"iresolution\").i;\n                } else {\n                    proj_parm.dgg.resolution = 4;\n                }\n\n                if (pj_param(par.params, \"taperture\").i) {\n                    proj_parm.dgg.aperture = pj_param(par.params, \"iaperture\").i;\n                } else {\n                    proj_parm.dgg.aperture = 3;\n                }\n            }\n\n        }} // namespace detail::isea\n    #endif // doxygen\n\n    /*!\n        \\brief Icosahedral Snyder Equal Area 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         - Spheroid\n        \\par Projection parameters\n         - orient (string)\n         - azi: Azimuth (or Gamma) (degrees)\n         - lon_0: Central meridian (degrees)\n         - lat_0: Latitude of origin (degrees)\n         - aperture (integer)\n         - resolution (integer)\n         - mode (string)\n         - rescale\n        \\par Example\n        \\image html ex_isea.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct isea_spheroid : public detail::isea::base_isea_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline isea_spheroid(const Parameters& par) : detail::isea::base_isea_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::isea::setup_isea(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 isea_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_f<isea_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void isea_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"isea\", new isea_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_ISEA_HPP\n\n", "meta": {"hexsha": "b4fc25a2c69aca48dc4d8b6458e761255462d6a2", "size": 44773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/isea.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/isea.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/isea.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": 35.8184, "max_line_length": 131, "alphanum_fraction": 0.4183771469, "num_tokens": 10364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.1822775147205193}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2020-2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, 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_STRATEGIES_GEOGRAPHIC_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_HPP\n\n\n#include <boost/geometry/strategies/area/geographic.hpp>\n#include <boost/geometry/strategies/azimuth/geographic.hpp>\n#include <boost/geometry/strategies/convex_hull/geographic.hpp>\n#include <boost/geometry/strategies/envelope/geographic.hpp>\n#include <boost/geometry/strategies/expand/geographic.hpp>\n#include <boost/geometry/strategies/io/geographic.hpp>\n#include <boost/geometry/strategies/index/geographic.hpp>\n#include <boost/geometry/strategies/relate/geographic.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n    \nnamespace strategies\n{\n\n\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    std::size_t SeriesOrder = strategy::default_order<FormulaPolicy>::value,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic\n    // derived from the umbrella strategy defining the most strategies\n    : public index::geographic<FormulaPolicy, SeriesOrder, Spheroid, CalculationType>\n{\n    using base_t = index::geographic<FormulaPolicy, SeriesOrder, Spheroid, CalculationType>;\n\npublic:\n    geographic()\n        : base_t()\n    {}\n\n    explicit geographic(Spheroid const& spheroid)\n        : base_t(spheroid)\n    {}\n\n    auto azimuth() const\n    {\n        return strategy::azimuth::geographic\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    auto point_order() const\n    {\n        return strategy::point_order::geographic\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n};\n\n\n} // namespace strategies\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_HPP\n", "meta": {"hexsha": "815f1e3f3f4997745375472900e1858852706a99", "size": 2028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic.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/geometry/strategies/geographic.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/geometry/strategies/geographic.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": 25.6708860759, "max_line_length": 92, "alphanum_fraction": 0.7214003945, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3380771308191989, "lm_q1q2_score": 0.1822179008097833}}
{"text": "/*=========================================================================\n* GPU accelerated motion compensation for MRI\n*\n* Copyright (c) 2016 Bernhard Kainz, Amir Alansary, Maria Kuklisova-Murgasova,\n* Kevin Keraudren, Markus Steinberger\n* (b.kainz@imperial.ac.uk)\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#define NOMINMAX\n#define _USE_MATH_DEFINES\n\n#include <irtkReconstructionGPU.h>\n#include <irtkResampling.h>\n#include <irtkRegistration.h>\n#include <irtkImageRigidRegistration.h>\n#include <irtkImageRigidRegistrationWithPadding.h>\n#include <irtkImageFunction.h>\n#include <irtkTransformation.h>\n//#include <irtkMeanShift.h>\n//#include <irtkCRF.h>\n#include <math.h>\n#include <stdlib.h>\n#include <irtkDilation.h>\n\n#include <boost/filesystem.hpp>\nusing namespace boost::filesystem;\n\n#if HAVE_CULA\n#include <cula.h>\n#endif\n\n/* Auxiliary functions (not reconstruction specific) */\n\nvoid bbox(irtkRealImage &stack,\n  irtkRigidTransformation &transformation,\n  double &min_x,\n  double &min_y,\n  double &min_z,\n  double &max_x,\n  double &max_y,\n  double &max_z) {\n\n  cout << \"bbox\" << endl;\n\n  min_x = voxel_limits<irtkRealPixel>::max();\n  min_y = voxel_limits<irtkRealPixel>::max();\n  min_z = voxel_limits<irtkRealPixel>::max();\n  max_x = voxel_limits<irtkRealPixel>::min();\n  max_y = voxel_limits<irtkRealPixel>::min();\n  max_z = voxel_limits<irtkRealPixel>::min();\n  double x, y, z;\n  for (int i = 0; i <= stack.GetX(); i += stack.GetX())\n    for (int j = 0; j <= stack.GetY(); j += stack.GetY())\n      for (int k = 0; k <= stack.GetZ(); k += stack.GetZ()) {\n    x = i;\n    y = j;\n    z = k;\n    stack.ImageToWorld(x, y, z);\n    // FIXME!!!\n    transformation.Transform(x, y, z);\n    //transformation.Inverse( x, y, z );\n    if (x < min_x)\n      min_x = x;\n    if (y < min_y)\n      min_y = y;\n    if (z < min_z)\n      min_z = z;\n    if (x > max_x)\n      max_x = x;\n    if (y > max_y)\n      max_y = y;\n    if (z > max_z)\n      max_z = z;\n      }\n}\n\nvoid bboxCrop(irtkRealImage &image) {\n  int min_x, min_y, min_z, max_x, max_y, max_z;\n  min_x = image.GetX() - 1;\n  min_y = image.GetY() - 1;\n  min_z = image.GetZ() - 1;\n  max_x = 0;\n  max_y = 0;\n  max_z = 0;\n  for (int i = 0; i < image.GetX(); i++)\n    for (int j = 0; j < image.GetY(); j++)\n      for (int k = 0; k < image.GetZ(); k++) {\n    if (image.Get(i, j, k) > 0) {\n      if (i < min_x)\n        min_x = i;\n      if (j < min_y)\n        min_y = j;\n      if (k < min_z)\n        min_z = k;\n      if (i > max_x)\n        max_x = i;\n      if (j > max_y)\n        max_y = j;\n      if (k > max_z)\n        max_z = k;\n    }\n      }\n\n  //Cut region of interest\n  image = image.GetRegion(min_x, min_y, min_z,\n    max_x + 1, max_y + 1, max_z + 1);\n}\n\nvoid centroid(irtkRealImage &image,\n  double &x,\n  double &y,\n  double &z) {\n  double sum_x = 0;\n  double sum_y = 0;\n  double sum_z = 0;\n  double norm = 0;\n  double v;\n  for (int i = 0; i < image.GetX(); i++)\n    for (int j = 0; j < image.GetY(); j++)\n      for (int k = 0; k < image.GetZ(); k++) {\n    v = image.Get(i, j, k);\n    if (v <= 0)\n      continue;\n    sum_x += v*i;\n    sum_y += v*j;\n    sum_z += v*k;\n    norm += v;\n      }\n\n  x = sum_x / norm;\n  y = sum_y / norm;\n  z = sum_z / norm;\n\n  image.ImageToWorld(x, y, z);\n\n  std::cout << \"CENTROID:\" << x << \",\" << y << \",\" << z << \"\\n\\n\";\n}\n\n/*   end of auxiliary functions */\n\nirtkReconstruction::irtkReconstruction(std::vector<int> dev, bool useCPUReg)\n{\n  _step = 0.0001;\n  _debug = false;\n  _quality_factor = 2;\n  _sigma_bias = 12;\n  _sigma_s_cpu = 0.025f;\n  _sigma_s_gpu = 0.025f;\n  _sigma_s2_cpu = 0.025f;\n  _sigma_s2_gpu = 0.025f;\n  _mix_s_cpu = 0.9f;\n  _mix_s_gpu = 0.9f;\n  _mix_cpu = 0.9f;\n  _mix_gpu = 0.9f;\n  _delta = 1;\n  _lambda = 0.1f;\n  _alpha = (0.05f / _lambda) * _delta * _delta;\n  _template_created = false;\n  _have_mask = false;\n  _low_intensity_cutoff = 0.01f;\n  _global_bias_correction = false;\n  _adaptive = false;\n  _patchBased = false;\n  _disableBiasC = false;\n  _useNMI = false;\n  //--------------------------------------------------------------------------------------------\n  // superpixel (spx)\n   _superpixelBased = false;\n  //--------------------------------------------------------------------------------------------\n\n  int directions[13][3] = {\n      { 1, 0, -1 },\n      { 0, 1, -1 },\n      { 1, 1, -1 },\n      { 1, -1, -1 },\n      { 1, 0, 0 },\n      { 0, 1, 0 },\n      { 1, 1, 0 },\n      { 1, -1, 0 },\n      { 1, 0, 1 },\n      { 0, 1, 1 },\n      { 1, 1, 1 },\n      { 1, -1, 1 },\n      { 0, 0, 1 }\n  };\n  for (int i = 0; i < 13; i++)\n    for (int j = 0; j < 3; j++)\n      _directions[i][j] = directions[i][j];\n\n  _useCPUReg = useCPUReg;\n  //FIXXME\n  //TODO as possible workaround, but ugly -- dactiveates multithreading in cu\n // reconstructionGPU = new Reconstruction(dev, !_useCPUReg);\n  /*if (_useCPUReg)\n  {\n    reconstructionGPU = new Reconstruction(dev, false); //workaround\n  }\n  else\n  {*/\n    reconstructionGPU = new Reconstruction(dev, true); //to produce the error for CPUReg and multithreaded GPUs\n  //}\n    reconstructionGPU->_useCPUReg = _useCPUReg;\n}\n\n\nirtkReconstruction::~irtkReconstruction(){ }\n\n\nvoid irtkReconstruction::Set_debugGPU(bool val)\n{\n  _debugGPU = val;\n  reconstructionGPU->_debugGPU = val;\n}\n\n\nvoid irtkReconstruction::disableBiasCorrection()\n{\n  _disableBiasC = true;\n  reconstructionGPU->_disableBiasC = _disableBiasC;\n}\n\n\n//////////////////////////////////////////////////////////////////////////////////\n//GPU helpers\nvoid irtkReconstruction::updateStackSizes(std::vector<uint3> stack_sizes_)\n{\n  reconstructionGPU->updateStackSizes(stack_sizes_);\n}\n\n\nvoid irtkReconstruction::SyncGPU()\n{\n  irtkGenericImage<float> mask_float_ = _mask; //check this\n  std::cout << \"SyncGPU()\" << std::endl;\n  reconstructionGPU->InitReconstructionVolume(make_uint3(_reconstructed.GetX(), _reconstructed.GetY(), _reconstructed.GetZ()),\n    make_float3(_reconstructed.GetXSize(), _reconstructed.GetYSize(), _reconstructed.GetZSize()), _reconstructed_gpu.GetPointerToVoxels(), _sigma_bias);\n  reconstructionGPU->setMask(make_uint3(_mask.GetX(), _mask.GetY(), _mask.GetZ()), make_float3(_mask.GetXSize(), _mask.GetYSize(), _mask.GetZSize()),\n    mask_float_.GetPointerToVoxels(), _sigma_bias);\n  if (_debugGPU)\n  {\n    irtkGenericImage<float> smask;\n\n    smask.Initialize(_mask.GetImageAttributes());\n    reconstructionGPU->debugSmoothMask(smask.GetPointerToVoxels());\n    char buffer[256];\n    sprintf(buffer, \"smaskGPU%i.nii\", 0);\n    smask.Write(buffer);\n    _mask.Write(\"maskCPUGPU.nii\");\n  }\n\n  reqVDims = make_uint3(INT_MIN, INT_MIN, 0);\n  uint3 wasteVDims = make_uint3(INT_MAX, INT_MAX, 0);\n\n  for (int i = 0; i < _slices.size(); i++)\n  {\n    reqVDims = make_uint3(max((int)reqVDims.x, _slices[i].GetX()), max((int)reqVDims.y, _slices[i].GetY()), _slices.size());\n    wasteVDims = make_uint3(min((int)wasteVDims.x, _slices[i].GetX()), min((int)wasteVDims.y, _slices[i].GetY()), _slices.size());\n  }\n\n  double waste = (((reqVDims.x - wasteVDims.x) * (reqVDims.y - wasteVDims.y) * _slices.size())*sizeof(double)*5.0) / 1024.0;\n  printf(\"GPU memory waste approx: %f KB with %d %d %d %d\\n\", waste, reqVDims.x, reqVDims.y, wasteVDims.x, wasteVDims.y);\n\n\n  irtkGenericImage<float> combinedStacks(reqVDims.x, reqVDims.y, reqVDims.z);\n  //combinedStacks.Clear();\n\n  //all the same dimensions\n  reconstructionGPU->initStorageVolumes(reqVDims, make_float3(_slices[0].GetXSize(), _slices[0].GetYSize(), _slices[0].GetZSize()));\n  vector<int> sizesX;\n  vector<int> sizesY;\n  std::vector<float3> slice_dims;\n  combinedStacks = -1.0;\n\n\n  float* ptr = combinedStacks.GetPointerToVoxels();\n  for (int i = 0; i < _slices.size(); i++)\n  {\n    irtkRealImage slice = _slices[i];\n    //We need to do this line wise because of different cropping sizes\n    for (int y = 0; y < slice.GetY(); y++)\n    {\n      for (int x = 0; x < slice.GetX(); x++)\n      {\n        combinedStacks(x, y, i) = (float)slice(x, y, 0);\n      }\n      ptr += combinedStacks.GetX();\n    }\n    ptr += abs(combinedStacks.GetY() - slice.GetY())*combinedStacks.GetX();\n    //TODO - set slice sizes\n    sizesX.push_back(slice.GetX());\n    sizesY.push_back(slice.GetY());\n    slice_dims.push_back(make_float3(_slices[i].GetXSize(), _slices[i].GetYSize(), _slices[i].GetZSize()));\n  }\n  //combinedStacks.Write(\"combinedStacks.nii\");\n\n  reconstructionGPU->FillSlices(combinedStacks.GetPointerToVoxels(), sizesX, sizesY);\n\n  reconstructionGPU->setSliceDims(slice_dims, _quality_factor);\n  reconstructionGPU->reconstructedVoxelSize = (float)_reconstructed.GetXSize();\n  //\treconstructionGPU->UpdateScaleVector(_scale_gpu, _slice_weight_gpu);\n\n  if(_debugGPU)\n  {\n    irtkGenericImage<float> debugSlices(reqVDims.x, reqVDims.y, reqVDims.z);\n    reconstructionGPU->getSlicesVol_debug(debugSlices.GetPointerToVoxels());\n    printf(\"debugSlices dimensions %d %d %d\\n\", debugSlices.GetX(), debugSlices.GetY(), debugSlices.GetZ());\n    debugSlices.Write(\"debugSlices.nii\");\n    cudaDeviceSynchronize();\n}\n}\n\nMatrix4 irtkReconstruction::toMatrix4(irtkMatrix mat)\n{\n  Matrix4 mmat;\n  /*mmat.data[0] = make_double4(mat(0,0), mat(0,1), mat(0,2), mat(0,3));\n  mmat.data[1] = make_double4(mat(1,0), mat(1,1), mat(1,2), mat(1,3));\n  mmat.data[2] = make_double4(mat(2,0), mat(2,1), mat(2,2), mat(2,3));\n  mmat.data[3] = make_double4(mat(3,0), mat(3,1), mat(3,2), mat(3,3));*/\n  mmat.data[0] = make_float4(mat(0, 0), mat(0, 1), mat(0, 2), mat(0, 3));\n  mmat.data[1] = make_float4(mat(1, 0), mat(1, 1), mat(1, 2), mat(1, 3));\n  mmat.data[2] = make_float4(mat(2, 0), mat(2, 1), mat(2, 2), mat(2, 3));\n  mmat.data[3] = make_float4(mat(3, 0), mat(3, 1), mat(3, 2), mat(3, 3));\n  return mmat;\n}\n\nirtkMatrix irtkReconstruction::fromMatrix4(Matrix4 mat)\n{\n  irtkMatrix mmat;\n  mmat.Initialize(4, 4);\n  mmat.Ident();\n  mmat.Put(0, 0, mat.data[0].x);\n  mmat.Put(0, 1, mat.data[0].y);\n  mmat.Put(0, 2, mat.data[0].z);\n  mmat.Put(0, 3, mat.data[0].w);\n\n  mmat.Put(1, 0, mat.data[1].x);\n  mmat.Put(1, 1, mat.data[1].y);\n  mmat.Put(1, 2, mat.data[1].z);\n  mmat.Put(1, 3, mat.data[1].w);\n\n  mmat.Put(2, 0, mat.data[2].x);\n  mmat.Put(2, 1, mat.data[2].y);\n  mmat.Put(2, 2, mat.data[2].z);\n  mmat.Put(2, 3, mat.data[2].w);\n\n  mmat.Put(3, 0, mat.data[3].x);\n  mmat.Put(3, 1, mat.data[3].y);\n  mmat.Put(3, 2, mat.data[3].z);\n  mmat.Put(3, 3, mat.data[3].w);\n\n  return mmat;\n}\n\nstd::vector<irtkMatrix> irtkReconstruction::UpdateGPUTranformationMatrices()\n{\n\n  std::vector<Matrix4> sI2W;\n  std::vector<Matrix4> sW2I;\n  std::vector<Matrix4> sI2Winit;\n  std::vector<Matrix4> sW2Iinit;\n  std::vector<irtkMatrix> transformations_;\n  std::vector<Matrix4> sliceTransforms_;\n  std::vector<Matrix4> invsliceTransforms_;\n  for (int i = 0; i < _slices.size(); i++)\n  {\n    //_transformations[i].UpdateMatrix();\n    sI2Winit.push_back(toMatrix4(_slices[i].GetImageToWorldMatrix()));\n    sW2Iinit.push_back(toMatrix4(_slices[i].GetWorldToImageMatrix()));\n    sW2I.push_back(toMatrix4(_slices[i].GetWorldToImageMatrix()));\n    sI2W.push_back(toMatrix4(_slices[i].GetImageToWorldMatrix()));\n    sliceTransforms_.push_back(toMatrix4(_transformations_gpu[i].GetMatrix()));\n    irtkMatrix invTrans = _transformations_gpu[i].GetMatrix();\n    invTrans.Invert();\n    invsliceTransforms_.push_back(toMatrix4(invTrans));\n\n    transformations_.push_back(_transformations_gpu[i].GetMatrix());\n  }\n\n  reconstructionGPU->SetSliceMatrices(sliceTransforms_, invsliceTransforms_, sI2W, sW2I, sI2Winit, sW2Iinit,\n    toMatrix4(_reconstructed.GetImageToWorldMatrix()), toMatrix4(_reconstructed.GetWorldToImageMatrix()));\n\n  return transformations_;\n}\n\n//GPU helpers end\n//////////////////////////////////////////////////////////////////////////////////\n\n\n\nvoid irtkReconstruction::CenterStacks(vector<irtkRealImage>& stacks,\n  vector<irtkRigidTransformation>& stack_transformations,\n  int templateNumber) {\n  // template center\n  double x0, y0, z0;\n  irtkRealImage mask;\n  mask = stacks[templateNumber] != -1;\n  centroid(mask, x0, y0, z0);\n\n  double x, y, z;\n  irtkMatrix m1, m2;\n  for (unsigned int i = 0; i < stacks.size(); i++) {\n    if (i == templateNumber)\n      continue;\n\n    mask = stacks[i] != -1;\n    centroid(mask, x, y, z);\n\n    irtkRigidTransformation translation;\n    translation.PutTranslationX(x0 - x);\n    translation.PutTranslationY(y0 - y);\n    translation.PutTranslationZ(z0 - z);\n\n    std::cout << \"TRANSLATION:\\n\";\n    translation.Print();\n    std::cout << \"\\n\\n\\n\";\n\n\n    m1 = stack_transformations[i].GetMatrix();\n    m2 = translation.GetMatrix();\n    stack_transformations[i].PutMatrix(m2*m1);\n  }\n\n}\n\nclass ParallelAverage{\n  irtkReconstruction* reconstructor;\n  vector<irtkRealImage> &stacks;\n  vector<irtkRigidTransformation> &stack_transformations;\n\n  /// Padding value in target (voxels in the target image with this\n  /// value will be ignored)\n  double targetPadding;\n\n  /// Padding value in source (voxels outside the source image will\n  /// be set to this value)\n  double sourcePadding;\n\n  double background;\n\n  // Volumetric registrations are stack-to-template while slice-to-volume \n  // registrations are actually performed as volume-to-slice\n  // (reasons: technicalities of implementation)\n  // so transformations need to be inverted beforehand.\n\n  bool linear;\n\npublic:\n  irtkRealImage average;\n  irtkRealImage weights;\n\n  void operator()(const blocked_range<size_t>& r) {\n    for (size_t i = r.begin(); i < r.end(); ++i) {\n      irtkImageTransformation imagetransformation;\n      irtkImageFunction *interpolator;\n      if (linear)\n        interpolator = new irtkLinearInterpolateImageFunction;\n      else\n        interpolator = new irtkNearestNeighborInterpolateImageFunction;\n\n      irtkRealImage s = stacks[i];\n      irtkRigidTransformation t = stack_transformations[i];\n      imagetransformation.SetInput(&s, &t);\n      irtkRealImage image(reconstructor->_reconstructed.GetImageAttributes());\n      image = 0;\n\n      imagetransformation.SetOutput(&image);\n      imagetransformation.PutTargetPaddingValue(targetPadding);\n      imagetransformation.PutSourcePaddingValue(sourcePadding);\n      imagetransformation.PutInterpolator(interpolator);\n      imagetransformation.Run();\n\n      irtkRealPixel *pa = average.GetPointerToVoxels();\n      irtkRealPixel *pi = image.GetPointerToVoxels();\n      irtkRealPixel *pw = weights.GetPointerToVoxels();\n      for (int p = 0; p < average.GetNumberOfVoxels(); p++) {\n        if (*pi != background) {\n          *pa += *pi;\n          *pw += 1;\n        }\n        pa++;\n        pi++;\n        pw++;\n      }\n      delete interpolator;\n    }\n  }\n\n  ParallelAverage(ParallelAverage& x, split) :\n    reconstructor(x.reconstructor),\n    stacks(x.stacks),\n    stack_transformations(x.stack_transformations)\n  {\n    average.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    average = 0;\n    weights.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    weights = 0;\n    targetPadding = x.targetPadding;\n    sourcePadding = x.sourcePadding;\n    background = x.background;\n    linear = x.linear;\n  }\n\n  void join(const ParallelAverage& y) {\n    average += y.average;\n    weights += y.weights;\n  }\n\n  ParallelAverage(irtkReconstruction *reconstructor,\n    vector<irtkRealImage>& _stacks,\n    vector<irtkRigidTransformation>& _stack_transformations,\n    double _targetPadding,\n    double _sourcePadding,\n    double _background,\n    bool _linear = false) :\n    reconstructor(reconstructor),\n    stacks(_stacks),\n    stack_transformations(_stack_transformations)\n  {\n    average.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    average = 0;\n    weights.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    weights = 0;\n    targetPadding = _targetPadding;\n    sourcePadding = _sourcePadding;\n    background = _background;\n    linear = _linear;\n  }\n\n  // execute\n  void operator() () {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_reduce(blocked_range<size_t>(0, stacks.size()),\n      *this);\n    init.terminate();\n  }\n};\n\nclass ParallelSliceAverage{\n  irtkReconstruction* reconstructor;\n  vector<irtkRealImage> &slices;\n  vector<irtkRigidTransformation> &slice_transformations;\n  irtkRealImage &average;\n  irtkRealImage &weights;\n\npublic:\n\n  void operator()(const blocked_range<size_t>& r) const {\n    for (size_t k0 = r.begin(); k0 < r.end(); k0++) {\n      for (int j0 = 0; j0 < average.GetY(); j0++) {\n        for (int i0 = 0; i0 < average.GetX(); i0++) {\n          double x0 = i0;\n          double y0 = j0;\n          double z0 = k0;\n          // Transform point into world coordinates\n          average.ImageToWorld(x0, y0, z0);\n          for (int inputIndex = 0; inputIndex < slices.size(); inputIndex++) {\n            double x = x0;\n            double y = y0;\n            double z = z0;\n            // Transform point\n            slice_transformations[inputIndex].Transform(x, y, z);\n            // Transform point into image coordinates\n            slices[inputIndex].WorldToImage(x, y, z);\n            int i = round(x);\n            int j = round(y);\n            int k = round(z);\n            // Check whether transformed point is in FOV of input\n            if ((i >= 0) && (i < slices[inputIndex].GetX()) &&\n              (j >= 0) && (j < slices[inputIndex].GetY()) &&\n              (k >= 0) && (k < slices[inputIndex].GetZ())) {\n              if (slices[inputIndex](i, j, k) > 0) {\n                average.PutAsDouble(i0, j0, k0, 0, average(i0, j0, k0) + slices[inputIndex](i, j, k));\n                weights.PutAsDouble(i0, j0, k0, 0, weights(i0, j0, k0) + 1);\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  ParallelSliceAverage(irtkReconstruction *reconstructor,\n    vector<irtkRealImage>& _slices,\n    vector<irtkRigidTransformation>& _slice_transformations,\n    irtkRealImage &_average,\n    irtkRealImage &_weights) :\n    reconstructor(reconstructor),\n    slices(_slices),\n    slice_transformations(_slice_transformations),\n    average(_average),\n    weights(_weights)\n  {\n    average.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    average = 0;\n    weights.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    weights = 0;\n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, average.GetZ()),\n      *this);\n    init.terminate();\n  }\n};\n\nirtkRealImage irtkReconstruction::CreateAverage(vector<irtkRealImage>& stacks,\n  vector<irtkRigidTransformation>& stack_transformations)\n{\n  if (!_template_created) {\n    cerr << \"Please create the template before calculating the average of the stacks.\" << endl;\n    exit(1);\n  }\n\n  InvertStackTransformations(stack_transformations);\n  ParallelAverage parallelAverage(this,\n    stacks,\n    stack_transformations,\n    -1, 0, 0, // target/source/background\n    true);\n  parallelAverage();\n  irtkRealImage average = parallelAverage.average;\n  irtkRealImage weights = parallelAverage.weights;\n  average /= weights;\n  InvertStackTransformations(stack_transformations);\n  return average;\n}\n\ndouble irtkReconstruction::CreateTemplate(irtkRealImage stack, double resolution)\n{\n  double dx, dy, dz, d;\n\n  //Get image attributes - image size and voxel size\n  irtkImageAttributes attr = stack.GetImageAttributes();\n\n  //enlarge stack in z-direction in case top of the head is cut off\n  attr._z += 2;\n\n  //create enlarged image\n  irtkRealImage enlarged(attr);\n\n  //determine resolution of volume to reconstruct\n  if (resolution <= 0) {\n    //resolution was not given by user\n    // set it to min of res in x or y direction\n    stack.GetPixelSize(&dx, &dy, &dz);\n    if ((dx <= dy) && (dx <= dz))\n      d = dx;\n    else if (dy <= dz)\n      d = dy;\n    else\n      d = dz;\n  }\n  else\n    d = resolution;\n\n  cout << \"Constructing volume with isotropic voxel size \" << d << endl;\n\n  //resample \"enlarged\" to resolution \"d\"\n  irtkNearestNeighborInterpolateImageFunction interpolator;\n  irtkResampling<irtkRealPixel> resampling(d, d, d);\n  resampling.SetInput(&enlarged);\n  resampling.SetOutput(&enlarged);\n  resampling.SetInterpolator(&interpolator);\n  resampling.Run();\n\n  //initialize recontructed volume\n  _reconstructed = enlarged;\n\n  _reconstructed_gpu.Initialize(_reconstructed.GetImageAttributes());\n  _template_created = true;\n\n  //return resulting resolution of the template image\n  return d;\n}\n\nirtkRealImage irtkReconstruction::CreateMaskFromOverlap(std::vector<irtkRealImage>& stacks)\n{\n  std::cout << \"creating mask from overlap \" << std::endl;\n  //calculated the non-zero union of the input stacks\n\n  irtkRealImage avImage = stacks[0];\n  avImage = 0;\n\n  for (int z = 0; z < avImage.GetZ(); z++)\n  {\n    for (int y = 0; y < avImage.GetY(); y++)\n    {\n      for (int x = 0; x < avImage.GetX(); x++)\n      {\n        double xx = x;\n        double yy = y;\n        double zz = z;\n\n        avImage.ImageToWorld(xx, yy, zz);\n        bool inside = true;\n        for (int i = 0; i < stacks.size(); i++)\n        {\n          double xx1 = xx;\n          double yy1 = yy;\n          double zz1 = zz;\n          stacks[i].WorldToImage(xx1, yy1, zz1);\n          if (!(xx1 >= 0 && yy1 >= 0 && zz1 >= 0 && xx1 < stacks[i].GetX() && yy1 < stacks[i].GetY() && zz1 < stacks[i].GetZ()))\n          {\n            inside = false;\n          }\n        }\n        if (inside) avImage(x, y, z) = 1;\n\n      }\n    }\n  }\n\n  return avImage;\n}\n\nirtkRealImage irtkReconstruction::CreateMask(irtkRealImage image)\n{\n  //binarize mask\n  irtkRealPixel* ptr = image.GetPointerToVoxels();\n  for (int i = 0; i < image.GetNumberOfVoxels(); i++) {\n    if (*ptr > 0.0)\n      *ptr = 1;\n    else\n      *ptr = 0;\n    ptr++;\n  }\n  return image;\n}\n\nvoid irtkReconstruction::SetMask(irtkRealImage * mask, double sigma, double threshold)\n{\n  if (!_template_created) {\n    cerr\n      << \"Please create the template before setting the mask, so that the mask can be resampled to the correct dimensions.\"\n      << endl;\n    exit(1);\n  }\n\n  _mask = _reconstructed;\n\n  if (mask != NULL) {\n    //if sigma is nonzero first smooth the mask\n    if (sigma > 0) {\n      //blur mask\n      irtkGaussianBlurring<irtkRealPixel> gb(sigma);\n      gb.SetInput(mask);\n      gb.SetOutput(mask);\n      gb.Run();\n\n      //binarize mask\n      irtkRealPixel* ptr = mask->GetPointerToVoxels();\n      for (int i = 0; i < mask->GetNumberOfVoxels(); i++) {\n        if (*ptr > threshold)\n          *ptr = 1;\n        else\n          *ptr = 0;\n        ptr++;\n      }\n    }\n\n    //resample the mask according to the template volume using identity transformation\n    irtkRigidTransformation transformation;\n    irtkImageTransformation imagetransformation;\n    irtkNearestNeighborInterpolateImageFunction interpolator;\n    imagetransformation.SetInput(mask, &transformation);\n    imagetransformation.SetOutput(&_mask);\n    //target is zero image, need padding -1\n    imagetransformation.PutTargetPaddingValue(-1);\n    //need to fill voxels in target where there is no info from source with zeroes\n    imagetransformation.PutSourcePaddingValue(0);\n    imagetransformation.PutInterpolator(&interpolator);\n    imagetransformation.Run();\n  }\n  else {\n    //fill the mask with ones\n    _mask = 1;\n  }\n  //set flag that mask was created\n  _have_mask = true;\n\n  if (_debug)\n    _mask.Write(\"mask.nii\");\n}\n\nvoid irtkReconstruction::TransformMask(irtkRealImage& image, irtkRealImage& mask,\n  irtkRigidTransformation& transformation)\n{\n  //transform mask to the space of image\n  irtkImageTransformation imagetransformation;\n  irtkNearestNeighborInterpolateImageFunction interpolator;\n  imagetransformation.SetInput(&mask, &transformation);\n  irtkRealImage m = image;\n  imagetransformation.SetOutput(&m);\n  //target contains zeros and ones image, need padding -1\n  imagetransformation.PutTargetPaddingValue(-1);\n  //need to fill voxels in target where there is no info from source with zeroes\n  imagetransformation.PutSourcePaddingValue(0);\n  imagetransformation.PutInterpolator(&interpolator);\n  imagetransformation.Run();\n  mask = m;\n}\n\nvoid irtkReconstruction::ResetOrigin(irtkGreyImage &image, irtkRigidTransformation& transformation)\n{\n  double ox, oy, oz;\n  image.GetOrigin(ox, oy, oz);\n  image.PutOrigin(0, 0, 0);\n  transformation.PutTranslationX(ox);\n  transformation.PutTranslationY(oy);\n  transformation.PutTranslationZ(oz);\n  transformation.PutRotationX(0);\n  transformation.PutRotationY(0);\n  transformation.PutRotationZ(0);\n}\n\nvoid irtkReconstruction::ResetOrigin(irtkRealImage &image, irtkRigidTransformation& transformation)\n{\n  double ox, oy, oz;\n  image.GetOrigin(ox, oy, oz);\n  image.PutOrigin(0, 0, 0);\n  transformation.PutTranslationX(ox);\n  transformation.PutTranslationY(oy);\n  transformation.PutTranslationZ(oz);\n  transformation.PutRotationX(0);\n  transformation.PutRotationY(0);\n  transformation.PutRotationZ(0);\n}\n\nclass ParallelStackRegistrations {\n  irtkReconstruction *reconstructor;\n  vector<irtkRealImage>& stacks;\n  vector<irtkRigidTransformation>& stack_transformations;\n  int templateNumber;\n  irtkGreyImage& target;\n  irtkRigidTransformation& offset;\n  bool _externalTemplate;\n\npublic:\n  ParallelStackRegistrations(irtkReconstruction *_reconstructor,\n    vector<irtkRealImage>& _stacks,\n    vector<irtkRigidTransformation>& _stack_transformations,\n    int _templateNumber,\n    irtkGreyImage& _target,\n    irtkRigidTransformation& _offset,\n    bool externalTemplate = false) :\n    reconstructor(_reconstructor),\n    stacks(_stacks),\n    stack_transformations(_stack_transformations),\n    target(_target),\n    offset(_offset) {\n    templateNumber = _templateNumber,\n      _externalTemplate = externalTemplate;\n  }\n\n  void operator() (const blocked_range<size_t> &r) const {\n    for (size_t i = r.begin(); i != r.end(); ++i) {\n\n      //do not perform registration for template\n      if (i == templateNumber)\n        continue;\n\n      //rigid registration object\n      irtkImageRigidRegistrationWithPadding registration;\n      //irtkRigidTransformation transformation = stack_transformations[i];\n\n      //set target and source (need to be converted to irtkGreyImage)\n      irtkGreyImage source = stacks[i];\n\n      //include offset in trasformation   \n      irtkMatrix mo = offset.GetMatrix();\n      irtkMatrix m = stack_transformations[i].GetMatrix();\n      m = m*mo;\n      stack_transformations[i].PutMatrix(m);\n\n      //perform rigid registration\n      registration.SetInput(&target, &source);\n      registration.SetOutput(&stack_transformations[i]);\n      if (_externalTemplate)\n      {\n        registration.GuessParameterThickSlicesNMI();\n      }\n      else\n      {\n        registration.GuessParameterThickSlices();\n      }\n      registration.SetTargetPadding(0);\n      registration.Run();\n\n      mo.Invert();\n      m = stack_transformations[i].GetMatrix();\n      m = m*mo;\n      stack_transformations[i].PutMatrix(m);\n\n      //stack_transformations[i] = transformation;            \n\n      //save volumetric registrations\n      if (reconstructor->_debug) {\n        //buffer to create the name\n        char buffer[256];\n        registration.irtkImageRegistration::Write((char *) \"parout-volume.rreg\");\n        sprintf(buffer, \"stack-transformation%i.dof.gz\", i);\n        stack_transformations[i].irtkTransformation::Write(buffer);\n        target.Write(\"target.nii.gz\");\n        sprintf(buffer, \"stack%i.nii.gz\", i);\n        stacks[i].Write(buffer);\n      }\n    }\n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, stacks.size()),\n      *this);\n    init.terminate();\n  }\n\n};\n\nvoid irtkReconstruction::StackRegistrations(vector<irtkRealImage>& stacks,\n  vector<irtkRigidTransformation>& stack_transformations, int templateNumber, bool useExternalTarget)\n{\n  if (_debug)\n    cout << \"StackRegistrations\" << endl;\n\n  InvertStackTransformations(stack_transformations);\n\n  //template is set as the target\n  irtkGreyImage target;\n  if (!useExternalTarget)\n  {\n    target = stacks[templateNumber];\n  }\n  else\n  {\n    target = externalRegistrationTargetImage;\n  }\n\n  //target needs to be masked before registration\n  if (_have_mask) {\n    double x, y, z;\n    for (int i = 0; i < target.GetX(); i++)\n      for (int j = 0; j < target.GetY(); j++)\n        for (int k = 0; k < target.GetZ(); k++) {\n      //image coordinates of the target\n      x = i;\n      y = j;\n      z = k;\n      //change to world coordinates\n      target.ImageToWorld(x, y, z);\n      //change to mask image coordinates - mask is aligned with target\n      _mask.WorldToImage(x, y, z);\n      x = round(x);\n      y = round(y);\n      z = round(z);\n      //if the voxel is outside mask ROI set it to -1 (padding value)\n      if ((x >= 0) && (x < _mask.GetX()) && (y >= 0) && (y < _mask.GetY()) && (z >= 0)\n        && (z < _mask.GetZ())) {\n        if (_mask(x, y, z) == 0)\n          target(i, j, k) = 0;\n      }\n      else\n        target(i, j, k) = 0;\n        }\n  }\n\n  irtkRigidTransformation offset;\n  ResetOrigin(target, offset);\n\n  //register all stacks to the target\n  ParallelStackRegistrations registration(this,\n    stacks,\n    stack_transformations,\n    templateNumber,\n    target,\n    offset,\n    useExternalTarget);\n  registration();\n\n  InvertStackTransformations(stack_transformations);\n}\n\nvoid irtkReconstruction::RestoreSliceIntensities()\n{\n  if (_debug)\n    cout << \"Restoring the intensities of the slices. \" << endl;\n\n  unsigned int inputIndex;\n  int i;\n  double factor;\n  irtkRealPixel *p;\n\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    //calculate scaling factor\n    factor = _stack_factor[_stack_index[inputIndex]];//_average_value;\n\n    // read the pointer to current slice\n    p = _slices[inputIndex].GetPointerToVoxels();\n    for (i = 0; i < _slices[inputIndex].GetNumberOfVoxels(); i++) {\n      if (*p>0) *p = *p / factor;\n      p++;\n    }\n  }\n}\n\nvoid irtkReconstruction::RestoreSliceIntensitiesGPU()\n{\n  //TODO\n  //_stack_factor\n  reconstructionGPU->RestoreSliceIntensities(_stack_factor, _stack_index);\n\n}\n\nvoid irtkReconstruction::ScaleVolume()\n{\n  if (_debug)\n    cout << \"Scaling volume: \";\n\n  unsigned int inputIndex;\n  int i, j;\n  double scalenum = 0, scaleden = 0;\n\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    // alias for the current slice\n    irtkRealImage& slice = _slices[inputIndex];\n\n    //alias for the current weight image\n    irtkRealImage& w = _weights[inputIndex];\n\n    // alias for the current simulated slice\n    irtkRealImage& sim = _simulated_slices[inputIndex];\n\n    for (i = 0; i < slice.GetX(); i++)\n      for (j = 0; j < slice.GetY(); j++)\n        if (slice(i, j, 0) != -1) {\n      //scale - intensity matching\n      if (_simulated_weights[inputIndex](i, j, 0) > 0.99) {\n        scalenum += w(i, j, 0) * _slice_weight_cpu[inputIndex] * slice(i, j, 0) * sim(i, j, 0);\n        scaleden += w(i, j, 0) * _slice_weight_cpu[inputIndex] * sim(i, j, 0) * sim(i, j, 0);\n      }\n        }\n  } //end of loop for a slice inputIndex\n\n  //calculate scale for the volume\n  double scale = scalenum / scaleden;\n  printf(\"Volume scale CPU: %f\\n\", scale);\n\n  if (_debug)\n    cout << \" scale = \" << scale;\n\n  irtkRealPixel *ptr = _reconstructed.GetPointerToVoxels();\n  for (i = 0; i < _reconstructed.GetNumberOfVoxels(); i++) {\n    if (*ptr>0) *ptr = *ptr * scale;\n    ptr++;\n  }\n  cout << endl;\n}\n\n\n\nvoid irtkReconstruction::ScaleVolumeGPU()\n{\n  if (_debug)\n    cout << \"Scaling volume: \";\n\n  //TODO\n  reconstructionGPU->ScaleVolume();\n}\n\nclass ParallelSimulateSlices {\n  irtkReconstruction *reconstructor;\n\npublic:\n  ParallelSimulateSlices(irtkReconstruction *_reconstructor) :\n    reconstructor(_reconstructor) { }\n\n  void operator() (const blocked_range<size_t> &r) const {\n    for (size_t inputIndex = r.begin(); inputIndex != r.end(); ++inputIndex) {\n      //Calculate simulated slice\n      reconstructor->_simulated_slices[inputIndex].Initialize(reconstructor->_slices[inputIndex].GetImageAttributes());\n      reconstructor->_simulated_slices[inputIndex] = 0;\n\n      reconstructor->_simulated_weights[inputIndex].Initialize(reconstructor->_slices[inputIndex].GetImageAttributes());\n      reconstructor->_simulated_weights[inputIndex] = 0;\n\n      reconstructor->_simulated_inside[inputIndex].Initialize(reconstructor->_slices[inputIndex].GetImageAttributes());\n      reconstructor->_simulated_inside[inputIndex] = 0;\n\n      reconstructor->_slice_inside_cpu[inputIndex] = false;\n\n      POINT3D p;\n      for (int i = 0; i < reconstructor->_slices[inputIndex].GetX(); i++)\n        for (int j = 0; j < reconstructor->_slices[inputIndex].GetY(); j++)\n          if (reconstructor->_slices[inputIndex](i, j, 0) != -1) {\n        double weight = 0;\n        size_t n = reconstructor->_volcoeffs[inputIndex][i][j].size();\n        for (int k = 0; k < n; k++) {\n          p = reconstructor->_volcoeffs[inputIndex][i][j][k];\n          reconstructor->_simulated_slices[inputIndex](i, j, 0) += p.value * reconstructor->_reconstructed(p.x, p.y, p.z);\n          weight += p.value;\n          if (reconstructor->_mask(p.x, p.y, p.z) == 1) {\n            reconstructor->_simulated_inside[inputIndex](i, j, 0) = 1;\n            reconstructor->_slice_inside_cpu[inputIndex] = true;\n          }\n        }\n        if (weight > 0) {\n          reconstructor->_simulated_slices[inputIndex](i, j, 0) /= weight;\n          reconstructor->_simulated_weights[inputIndex](i, j, 0) = weight;\n        }\n          }\n\n    }\n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n\n};\n\n\nvoid irtkReconstruction::SimulateSlices()\n{\n  if (_debug)\n    cout << \"Simulating slices.\" << endl;\n\n  ParallelSimulateSlices parallelSimulateSlices(this);\n  parallelSimulateSlices();\n\n  if (_debug)\n    cout << \"done.\" << endl;\n  if(_debugGPU)\n  {\n    _simulated_weights[40].Write(\"testsimweights40.nii\");\n    _simulated_slices[40].Write(\"testsimslices40.nii\");\n}\n}\n\nvoid irtkReconstruction::SimulateSlicesGPU()\n{\n  if (_slice_inside_gpu.size() == 0)\n  {\n    _slice_inside_gpu.clear();\n    _slice_inside_gpu.resize(_slices.size());\n  }\n\n  //debug sync\n  //reconstructionGPU->syncGPUrecon(_reconstructed.GetPointerToVoxels());\n\n  reconstructionGPU->SimulateSlices(_slice_inside_gpu);\n\n  //debug sync\n  //SyncSimSlicesGPU2CPU();\n  if(_debugGPU)\n  {\n    cudaDeviceSynchronize();\n\n    irtkGenericImage<float> simslicesV(reconstructionGPU->v_simulated_slices.size.x, reconstructionGPU->v_simulated_slices.size.y, reconstructionGPU->v_simulated_slices.size.z);\n    irtkGenericImage<float> simweightsV(reconstructionGPU->v_simulated_slices.size.x, reconstructionGPU->v_simulated_slices.size.y, reconstructionGPU->v_simulated_slices.size.z);\n\n    reconstructionGPU->debugSimslices(simslicesV.GetPointerToVoxels());\n    simslicesV.Write(\"simslicesV.nii\");\n\n\n    reconstructionGPU->debugSimweights(simweightsV.GetPointerToVoxels());\n    simweightsV.Write(\"simweightsV.nii.gz\");\n\n    irtkGenericImage<char> siminsideV(reconstructionGPU->v_simulated_slices.size.x, reconstructionGPU->v_simulated_slices.size.y, reconstructionGPU->v_simulated_slices.size.z);\n    reconstructionGPU->debugSiminside(siminsideV.GetPointerToVoxels());\n    siminsideV.Write(\"siminsideV.nii.gz\");\n\n    std::cout << \"_slice_inside_gpu: \";\n    for (int i = 0; i < _slice_inside_gpu.size(); i++)\n    {\n      std::cout << _slice_inside_gpu[i] << \" \";\n    }\n    std::cout << std::endl;\n}\n}\n\nvoid irtkReconstruction::SimulateStacks(vector<irtkRealImage>& stacks)\n{\n  if (_debug)\n    cout << \"Simulating stacks.\" << endl;\n\n  unsigned int inputIndex;\n  int i, j, k, n;\n  irtkRealImage sim;\n  POINT3D p;\n  double weight;\n\n  int z, current_stack;\n  z = -1;//this is the z coordinate of the stack\n  current_stack = -1; //we need to know when to start a new stack\n\n\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n\n\n    // read the current slice\n    irtkRealImage& slice = _slices[inputIndex];\n\n    //Calculate simulated slice\n    sim.Initialize(slice.GetImageAttributes());\n    sim = 0;\n\n    //do not simulate excluded slice\n    if (_slice_weight_cpu[inputIndex]>0.5)\n    {\n      for (i = 0; i < slice.GetX(); i++)\n        for (j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        weight = 0;\n        n = _volcoeffs[inputIndex][i][j].size();\n        for (k = 0; k < n; k++) {\n          p = _volcoeffs[inputIndex][i][j][k];\n          sim(i, j, 0) += p.value * _reconstructed(p.x, p.y, p.z);\n          weight += p.value;\n        }\n        if (weight>0)\n          sim(i, j, 0) /= weight;\n          }\n    }\n\n    if (_stack_index[inputIndex] == current_stack)\n      z++;\n    else {\n      current_stack = _stack_index[inputIndex];\n      z = 0;\n    }\n\n    for (i = 0; i < sim.GetX(); i++)\n      for (j = 0; j < sim.GetY(); j++) {\n      stacks[_stack_index[inputIndex]](i, j, z) = sim(i, j, 0);\n      }\n    //end of loop for a slice inputIndex\n  }\n}\n\nvoid irtkReconstruction::MatchStackIntensities(vector<irtkRealImage>& stacks,\n  vector<irtkRigidTransformation>& stack_transformations, double averageValue, bool together)\n{\n  if (_debug)\n    cout << \"Matching intensities of stacks. \";\n\n  //Calculate the averages of intensities for all stacks\n  double sum, num;\n  char buffer[256];\n  unsigned int ind;\n  int i, j, k;\n  double x, y, z;\n  vector<double> stack_average;\n\n  //remember the set average value\n  _average_value = averageValue;\n\n  //averages need to be calculated only in ROI\n  for (ind = 0; ind < stacks.size(); ind++) {\n    sum = 0;\n    num = 0;\n    for (i = 0; i < stacks[ind].GetX(); i++)\n      for (j = 0; j < stacks[ind].GetY(); j++)\n        for (k = 0; k < stacks[ind].GetZ(); k++) {\n      //image coordinates of the stack voxel\n      x = i;\n      y = j;\n      z = k;\n      //change to world coordinates\n      stacks[ind].ImageToWorld(x, y, z);\n      //transform to template (and also _mask) space\n      stack_transformations[ind].Transform(x, y, z);\n      //change to mask image coordinates - mask is aligned with template\n      _mask.WorldToImage(x, y, z);\n      x = round(x);\n      y = round(y);\n      z = round(z);\n      //if the voxel is inside mask ROI include it\n      // if ((x >= 0) && (x < _mask.GetX()) && (y >= 0) && (y < _mask.GetY()) && (z >= 0)\n      //      && (z < _mask.GetZ()))\n      //      {\n      //if (_mask(x, y, z) == 1)\n      if (stacks[ind](i, j, k) > 0) {\n        sum += stacks[ind](i, j, k);\n        num++;\n      }\n      //}\n        }\n    //calculate average for the stack\n    if (num > 0)\n      stack_average.push_back(sum / num);\n    else {\n      cerr << \"Stack \" << ind << \" has no overlap with ROI\" << endl;\n      exit(1);\n    }\n  }\n\n  double global_average;\n  if (together) {\n    global_average = 0;\n    for (i = 0; i < stack_average.size(); i++)\n      global_average += stack_average[i];\n    global_average /= stack_average.size();\n  }\n\n  if (_debug) {\n    cout << \"Stack average intensities are \";\n    for (ind = 0; ind < stack_average.size(); ind++)\n      cout << stack_average[ind] << \" \";\n    cout << endl;\n    cout << \"The new average value is \" << averageValue << endl;\n  }\n\n  //Rescale stacks\n  irtkRealPixel *ptr;\n  double factor;\n  for (ind = 0; ind < stacks.size(); ind++) {\n    if (together) {\n      factor = averageValue / global_average;\n      _stack_factor.push_back((float)factor);\n    }\n    else {\n      factor = averageValue / stack_average[ind];\n      _stack_factor.push_back((float)factor);\n\n    }\n\n    ptr = stacks[ind].GetPointerToVoxels();\n    for (i = 0; i < stacks[ind].GetNumberOfVoxels(); i++) {\n      if (*ptr > 0)\n        *ptr *= factor;\n      ptr++;\n    }\n  }\n\n  if (_debug) {\n    for (ind = 0; ind < stacks.size(); ind++) {\n      sprintf(buffer, \"rescaled-stack%i.nii.gz\", ind);\n      stacks[ind].Write(buffer);\n    }\n\n    cout << \"Slice intensity factors are \";\n    for (ind = 0; ind < stack_average.size(); ind++)\n      cout << _stack_factor[ind] << \" \";\n    cout << endl;\n    cout << \"The new average value is \" << averageValue << endl;\n  }\n\n}\n\n\nvoid irtkReconstruction::MatchStackIntensitiesWithMasking(vector<irtkRealImage>& stacks,\n  vector<irtkRigidTransformation>& stack_transformations, double averageValue, bool together)\n{\n  if (_debug)\n    cout << \"Matching intensities of stacks. \";\n\n  //Calculate the averages of intensities for all stacks\n  double sum, num;\n  char buffer[256];\n  unsigned int ind;\n  int i, j, k;\n  double x, y, z;\n  vector<double> stack_average;\n  irtkRealImage m;\n\n  //remember the set average value\n  _average_value = averageValue;\n\n  //averages need to be calculated only in ROI\n  for (ind = 0; ind < stacks.size(); ind++) {\n    m = stacks[ind];\n    sum = 0;\n    num = 0;\n    for (i = 0; i < stacks[ind].GetX(); i++)\n      for (j = 0; j < stacks[ind].GetY(); j++)\n        for (k = 0; k < stacks[ind].GetZ(); k++) {\n      //image coordinates of the stack voxel\n      x = i;\n      y = j;\n      z = k;\n      //change to world coordinates\n      stacks[ind].ImageToWorld(x, y, z);\n      //transform to template (and also _mask) space\n      stack_transformations[ind].Transform(x, y, z);\n      //change to mask image coordinates - mask is aligned with template\n      _mask.WorldToImage(x, y, z);\n      x = round(x);\n      y = round(y);\n      z = round(z);\n      //if the voxel is inside mask ROI include it\n      if ((x >= 0) && (x < _mask.GetX()) && (y >= 0) && (y < _mask.GetY()) && (z >= 0)\n        && (z < _mask.GetZ()))\n      {\n        if (_mask(x, y, z) == 1)\n        {\n          m(i, j, k) = 1;\n          sum += stacks[ind](i, j, k);\n          num++;\n        }\n        else\n          m(i, j, k) = 0;\n      }\n        }\n    if (_debug)\n    {\n      sprintf(buffer, \"mask-for-matching%i.nii.gz\", ind);\n      m.Write(buffer);\n    }\n    //calculate average for the stack\n    if (num > 0)\n      stack_average.push_back(sum / num);\n    else {\n      cerr << \"Stack \" << ind << \" has no overlap with ROI\" << endl;\n      exit(1);\n    }\n  }\n\n  double global_average;\n  if (together) {\n    global_average = 0;\n    for (i = 0; i < stack_average.size(); i++)\n      global_average += stack_average[i];\n    global_average /= stack_average.size();\n  }\n\n  if (_debug) {\n    cout << \"Stack average intensities are \";\n    for (ind = 0; ind < stack_average.size(); ind++)\n      cout << stack_average[ind] << \" \";\n    cout << endl;\n    cout << \"The new average value is \" << averageValue << endl;\n  }\n\n  //Rescale stacks\n  irtkRealPixel *ptr;\n  double factor;\n  for (ind = 0; ind < stacks.size(); ind++) {\n    if (together) {\n      factor = averageValue / global_average;\n      _stack_factor.push_back((float)factor);\n    }\n    else {\n      factor = averageValue / stack_average[ind];\n      _stack_factor.push_back((float)factor);\n\n    }\n\n    ptr = stacks[ind].GetPointerToVoxels();\n    for (i = 0; i < stacks[ind].GetNumberOfVoxels(); i++) {\n      if (*ptr > 0)\n        *ptr *= factor;\n      ptr++;\n    }\n  }\n\n  if (_debug) {\n    for (ind = 0; ind < stacks.size(); ind++) {\n      sprintf(buffer, \"rescaled-stack%i.nii.gz\", ind);\n      stacks[ind].Write(buffer);\n    }\n\n    cout << \"Slice intensity factors are \";\n    for (ind = 0; ind < stack_average.size(); ind++)\n      cout << _stack_factor[ind] << \" \";\n    cout << endl;\n    cout << \"The new average value is \" << averageValue << endl;\n  }\n\n}\n\n\nvoid irtkReconstruction::generatePSFVolume()\n{\n  double dx, dy, dz;\n  //currentlz just a test function\n  _slices[_slices.size() - 1].GetPixelSize(&dx, &dy, &dz);\n\n  //sigma of 3D Gaussian (sinc with FWHM=dx or dy in-plane, Gaussian with FWHM = dz through-plane)\n  //double psfSigma = 2.3548*((double)PSF_SIZE/2.0);\n  double psfSigma = 2.3548;\n\n  double size = _reconstructed.GetXSize() / _quality_factor;\n\n  //TODO TUne until same as CPU\n  //number of voxels in each direction\n  //the ROI is 2*voxel dimension\n\n  int xDim = PSF_SIZE;//round(2 * dx / size);\n  int yDim = PSF_SIZE;\n  int zDim = PSF_SIZE;\n\n  double ldim;\n  ldim = xDim;\n  ldim = (ldim > yDim) ? ldim : yDim;\n  ldim = (ldim > zDim) ? ldim : zDim;\n  double xsize = xDim / ldim;\n  double ysize = yDim / ldim;\n  double zsize = zDim / ldim;\n\n  //psfSigma = psfSigma + psfSigma/xsize;\n\n  //printf(\"%f %f %f\\n\",xsize, ysize, zsize);\n\n  double sigmax = (1.2) * (dx) / (psfSigma);\n  double sigmay = (1.2)  * (dy) / (psfSigma);\n  double sigmaz = (1.0) * (dz) / (psfSigma);\n  //printf(\"Sigmas orig: %f %f %f\\n\",sigmax, sigmay, sigmaz);\n\n  //image corresponding to PSF\n  irtkImageAttributes attr;\n  attr._x = xDim;\n  attr._y = yDim;\n  attr._z = zDim;\n  attr._dx = _reconstructed.GetXSize();\n  attr._dy = _reconstructed.GetYSize();\n  attr._dz = _reconstructed.GetZSize();\n  //attr._dx = size;\n  //attr._dy = size;\n  //attr._dz = size;\n  irtkGenericImage<float> PSF(attr);\n\n  //centre of PSF\n  double cx, cy, cz;\n  cx = 0.5 * (attr._x - 1);\n  cy = 0.5 * (attr._y - 1);\n  cz = 0.5 * (attr._z - 1);\n  PSF.ImageToWorld(cx, cy, cz);\n  //PSF.GetImageToWorldMatrix().Print();\n  //printf(\"%d %d %d \\n\\n\", xDim, yDim, zDim);\n\n  double x, y, z;\n  double sum = 0;\n  int i, j, k;\n  for (i = 0; i < attr._x; i++)\n    for (j = 0; j < attr._y; j++)\n      for (k = 0; k < attr._z; k++) {\n    x = i;\n    y = j;\n    z = k;\n\n    //printf(\"%f %f %f \\n\", x, y, z);\n    PSF.ImageToWorld(x, y, z);\n    //printf(\"%f %f %f \\n\", x, y, z);\n\n    x -= cx;\n    y -= cy;\n    z -= cz;\n\n#if 0\n    //Gauss\n    PSF(i, j, k) = exp(-x * x / (2.0 * sigmax * sigmax) - y * y / (2.0 * sigmay * sigmay)\n      - z * z / (2.0 * sigmaz * sigmaz));\n#endif\n#if 0\n    //sinc\n    double R = sqrt(x * x / (2 * sigmax * sigmax) + y * y / (2 * sigmay * sigmay)\n      + z * z / (2 * sigmaz * sigmaz));\n    PSF(i, j, k) = sin(R) / (R);\n#endif\n#if 1\n    //sinc gauss\n    double R = sqrt(x * x / (2 * sigmax * sigmax) + y * y / (2 * sigmay * sigmay)\n      + z * z / (2 * sigmaz * sigmaz));\n    PSF(i, j, k) = (float)(sin(R) / (R)* exp(-x * x / (2 * sigmax * sigmax) - y * y / (2 * sigmay * sigmay)\n      - z * z / (2 * sigmaz * sigmaz)));\n#endif\n    sum += PSF(i, j, k);\n      }\n  PSF /= sum;\n\n\n  // PSF.Write(\"PSFtest.nii\");\n  if (_debugGPU)\n  {\n    PSF.Write(\"PSFtest.nii\");\n    PSF.GetWorldToImageMatrix().Print();\n    PSF.GetImageToWorldMatrix().Print();\n  }\n\n  //PSF = PSFn;\n  reconstructionGPU->generatePSFVolume(PSF.GetPointerToVoxels(),\n    make_uint3(PSF.GetX(), PSF.GetY(), PSF.GetZ()),\n    make_float3(_slices[0].GetXSize(), _slices[0].GetYSize(), _slices[0].GetZSize()),\n    make_float3(PSF.GetXSize(), PSF.GetYSize(), PSF.GetZSize()), toMatrix4(PSF.GetImageToWorldMatrix()),\n    toMatrix4(PSF.GetWorldToImageMatrix()), _quality_factor);\n}\n\nvoid irtkReconstruction::CreateSlicesAndTransformationsPatchBased(int patchSize, int stride,  vector<irtkRealImage> &stacks,\n                                                        vector<irtkRigidTransformation> &stack_transformations,\n                                                        vector<double> &thickness,\n                                                        const vector<irtkRealImage> &probability_maps)\n{\n  if (_debug)\n    cout << \"CreateSlicesAndTransformations\" << endl;\n\n  double estimatedBytes = 0;\n\n  std::vector<uint3> stack_sizes_;\n  //for each stack\n  for (unsigned int i = 0; i < stacks.size(); i++) {\n    //image attributes contain image and voxel size\n    irtkImageAttributes attr = stacks[i].GetImageAttributes();\n    //printf(\"stack sizes z: %d \\n\", attr._z);\n    stack_sizes_.push_back(make_uint3(attr._x, attr._y, attr._z));\n    //attr._z is number of slices in the stack\n    for (int j = 0; j < attr._z; j++) {\n      //create slice by selecting the appropriate region of the stack\n      irtkRealImage slice = stacks[i].GetRegion(0, 0, j, attr._x, attr._y, j + 1);\n\n      //TODO split in patches\n      //how many patches in one slice?\n      //int pX =  divup(slice.GetX(), patchSize);\n      //int pY =  divup(slice.GetY(), patchSize);\n\n      for(int yi = 0; yi < slice.GetY()-patchSize; yi+=stride)\n      {\n        for(int xi = 0; xi < slice.GetX()-patchSize; xi+=stride)\n        {\n          if(xi+patchSize < slice.GetX() && yi+patchSize < slice.GetY())\n          {\n            irtkRealImage patch = slice.GetRegion(xi, yi, 0, xi+patchSize, yi+patchSize, 1);\n\n            estimatedBytes += sizeof(float) * patchSize * patchSize;\n\n            //set correct voxel size in the stack. Z size is equal to slice thickness.\n            patch.PutPixelSize(attr._dx, attr._dy, thickness[i]);\n            //remember the slice\n            _slices.push_back(patch);\n            _simulated_slices.push_back(patch);\n            _simulated_weights.push_back(patch);\n            _simulated_inside.push_back(patch);\n            //remeber stack index for this slice\n            _stack_index.push_back(i);\n            //initialize slice transformation with the stack transformation\n            _transformations.push_back(stack_transformations[i]);\n            _transformations_gpu.push_back(stack_transformations[i]);\n\n          }\n        }\n      }\n\n    }\n    estimatedBytes *= 4;\n    estimatedBytes /= 1024;\n    estimatedBytes /= 1024;\n  }\n  reconstructionGPU->updateStackSizes(stack_sizes_);\n\n  cout << \"Number of slices: \" << _slices.size() << endl;\n  std::cout << \"new memory consumption: \" << estimatedBytes << \" MB\" << std::endl;\n\n}\n//--------------------------------------------------------------------------------------------\n//--------------------------------------------------------------------------------------------\n// superpixel (spx)\nvoid irtkReconstruction::CreateSlicesAndTransformationsSuperpixelBased(vector<irtkRealImage>& sStacks,  vector<irtkRealImage> &stacks,\n                                                        vector<irtkRigidTransformation> &stack_transformations,\n                                                        vector<double> &thickness,\n                                                        const vector<irtkRealImage> &probability_maps)\n{\n  if (_debug)\n    cout << \"CreateSlicesAndTransformations\" << endl;\n\n  double estimatedBytes = 0;\n  irtkRealPixel minLbl, maxLbl;\n\n  int diter = 8;\n  irtkDilation<irtkRealPixel> dilation;\n  dilation.SetConnectivity(CONNECTIVITY_18);\n\n  std::vector<uint3> stack_sizes_;\n  //for each stack\n  for (unsigned int i = 0; i < stacks.size(); i++) {\n    //image attributes contain image and voxel size\n    irtkImageAttributes attr  = stacks[i].GetImageAttributes();\n    //printf(\"stack sizes z: %d \\n\", attr._z);\n    stack_sizes_.push_back(make_uint3(attr._x, attr._y, attr._z));\n    //attr._z is number of slices in the stack\n    for (int j = 0; j < attr._z; j++) {\n      //create slice by selecting the appropriate region of the stack\n      irtkRealImage slice   = stacks[i].GetRegion(0, 0, j, attr._x, attr._y, j + 1);\n     // printf(\"1\\n\");\n      irtkRealImage sSlice  = sStacks[i].GetRegion(0, 0, j, attr._x, attr._y, j + 1);\n      //printf(\"2\\n\");\n      sSlice.GetMinMax(&minLbl, &maxLbl);\n      //TODO split in patches\n      //how many patches in one slice?\n      //int pX =  divup(slice.GetX(), patchSize);\n      //int pY =  divup(slice.GetY(), patchSize);\n\n      // create \n      for (int idxLbl = int(minLbl); idxLbl < int(maxLbl); idxLbl++)\n      {   \n        // intialize region box \n        int xMin = INT_MAX, yMin = INT_MAX, xMax = INT_MIN, yMax = INT_MIN;\n        bool lblExists = false;\n        //extract a boudry box around \n        for (int xi =0; xi<slice.GetX(); xi++)\n        {\n          for (int yi =0; yi<slice.GetY(); yi++)\n          {\n            if ((int)(sSlice(xi,yi,0))==idxLbl)\n            {\n             // printf(\"%f \", sSlice(xi,yi,0));\n              if (xi<xMin)  xMin = xi;\n              if (xi>xMax)  xMax = xi;\n              if (yi<yMin)  yMin = yi;\n              if (yi>yMax)  yMax = yi;\n              lblExists = true;\n            }\n          }\n        }\n\n        if (!lblExists || (xMax - xMin) < 8 || (yMax - yMin) < 8) continue; //min 8x8 size\n        //printf(\"%d %d %d %d -- %d %d -- %d \\n\", xMin, yMin, xMax, yMax, slice.GetX(), slice.GetY(), idxLbl);\n        int extend = 8;\n\n        if (xMin - extend < 0) xMin = 0; else xMin -= extend;\n        if (yMin - extend < 0) yMin = 0; else  yMin -= extend;\n        if (xMax + extend > slice.GetX()) xMax = slice.GetX(); else xMax += extend;\n        if (yMax + extend > slice.GetY()) yMax = slice.GetY(); else yMax += extend;\n\n        // create current label patch\n        irtkRealImage patch = slice.GetRegion(xMin, yMin, 0, xMax, yMax, 1);\n        //printf(\"3\\n\");\n        irtkRealImage spatch = sSlice.GetRegion(xMin, yMin, 0, xMax, yMax, 1);\n         \n        //make binary mask\n        for (int xi = 0; xi < patch.GetX(); xi++)\n        {\n          for (int yi = 0; yi < patch.GetY(); yi++)\n          {\n            if (spatch(xi, yi, 0) != idxLbl)\n            {\n              spatch(xi, yi, 0) = -1;\n            }\n            else\n            {\n              spatch(xi, yi, 0) = 1;\n            }\n          }\n        }\n\n        dilation.SetInput(&spatch);\n        dilation.SetOutput(&spatch);\n        for (int i = 0; i < diter; i++)\n        {\n          dilation.Run();\n        }\n\n       // printf(\"4\\n\");\n        //extract a boudry box around \n        for (int xi =0; xi<patch.GetX(); xi++)\n        {\n          for (int yi =0; yi<patch.GetY(); yi++)\n          {\n            if (spatch(xi,yi,0)!=1)\n            {\n              patch(xi,yi,0) = -1;\n            }\n          }\n        }\n        estimatedBytes += sizeof(float) * (xMax-xMin) * (yMax-yMin);\n        //set correct voxel size in the stack. Z size is equal to slice thickness.\n        patch.PutPixelSize(attr._dx, attr._dy, thickness[i]);\n        //remember the slice\n        _slices.push_back(patch);\n        _simulated_slices.push_back(patch);\n        _simulated_weights.push_back(patch);\n        _simulated_inside.push_back(patch);\n        //remeber stack index for this slice\n        _stack_index.push_back(i);\n        //initialize slice transformation with the stack transformation\n        _transformations.push_back(stack_transformations[i]);\n        _transformations_gpu.push_back(stack_transformations[i]);\n      }\n    }\n    estimatedBytes *= 4;\n    estimatedBytes /= 1024;\n    estimatedBytes /= 1024;\n  }\n  reconstructionGPU->updateStackSizes(stack_sizes_);\n\n  cout << \"Number of slices: \" << _slices.size() << endl;\n  std::cout << \"new memory consumption: \" << estimatedBytes << \" MB\" << std::endl;\n}\n//--------------------------------------------------------------------------------------------\n//--------------------------------------------------------------------------------------------\n\nvoid irtkReconstruction::CreateSlicesAndTransformations(vector<irtkRealImage> &stacks,\n  vector<irtkRigidTransformation> &stack_transformations,\n  vector<double> &thickness,\n  const vector<irtkRealImage> &probability_maps)\n{\n  if (_debug)\n    cout << \"CreateSlicesAndTransformations\" << endl;\n\n  std::vector<uint3> stack_sizes_;\n  //for each stack\n  for (unsigned int i = 0; i < stacks.size(); i++) {\n    //image attributes contain image and voxel size\n    irtkImageAttributes attr = stacks[i].GetImageAttributes();\n    //printf(\"stack sizes z: %d \\n\", attr._z);\n    stack_sizes_.push_back(make_uint3(attr._x, attr._y, attr._z));\n    //attr._z is number of slices in the stack\n    for (int j = 0; j < attr._z; j++) {\n      //create slice by selecting the appropreate region of the stack\n      irtkRealImage slice = stacks[i].GetRegion(0, 0, j, attr._x, attr._y, j + 1);\n      //set correct voxel size in the stack. Z size is equal to slice thickness.\n      slice.PutPixelSize(attr._dx, attr._dy, thickness[i]);\n      //remember the slice\n      _slices.push_back(slice);\n      _simulated_slices.push_back(slice);\n      _simulated_weights.push_back(slice);\n      _simulated_inside.push_back(slice);\n      //remeber stack index for this slice\n      _stack_index.push_back(i);\n      //initialize slice transformation with the stack transformation\n      _transformations.push_back(stack_transformations[i]);\n      _transformations_gpu.push_back(stack_transformations[i]);\n    }\n  }\n  reconstructionGPU->updateStackSizes(stack_sizes_);\n\n  cout << \"Number of slices: \" << _slices.size() << endl;\n}\n\nvoid irtkReconstruction::ResetSlices(vector<irtkRealImage>& stacks,\n  vector<double>& thickness)\n{\n  if (_debug)\n    cout << \"ResetSlices\" << endl;\n\n  _slices.clear();\n\n  //for each stack\n  for (unsigned int i = 0; i < stacks.size(); i++) {\n    //image attributes contain image and voxel size\n    irtkImageAttributes attr = stacks[i].GetImageAttributes();\n\n    //attr._z is number of slices in the stack\n    for (int j = 0; j < attr._z; j++) {\n      //create slice by selecting the appropreate region of the stack\n      irtkRealImage slice = stacks[i].GetRegion(0, 0, j, attr._x, attr._y, j + 1);\n      //set correct voxel size in the stack. Z size is equal to slice thickness.\n      slice.PutPixelSize(attr._dx, attr._dy, thickness[i]);\n      //remember the slice\n      _slices.push_back(slice);\n    }\n  }\n  cout << \"Number of slices: \" << _slices.size() << endl;\n\n  for (int i = 0; i < _slices.size(); i++) {\n    _bias[i].Initialize(_slices[i].GetImageAttributes());\n    _weights[i].Initialize(_slices[i].GetImageAttributes());\n  }\n}\n\nvoid irtkReconstruction::SetSlicesAndTransformations(vector<irtkRealImage>& slices,\n  vector<irtkRigidTransformation>& slice_transformations,\n  vector<int>& stack_ids,\n  vector<double>& thickness)\n{\n  _slices.clear();\n  _stack_index.clear();\n  _transformations.clear();\n  _transformations_gpu.clear();\n  _slices.clear();\n  _simulated_slices.clear();\n  _simulated_weights.clear();\n  _simulated_inside.clear();\n\n  //for each slice\n  for (unsigned int i = 0; i < slices.size(); i++) {\n    //get slice\n    irtkRealImage slice = slices[i];\n    //std::cout << \"setting slice \" << i << \"\\n\";\n    //slice.Print();\n    //set correct voxel size in the stack. Z size is equal to slice thickness.\n    slice.PutPixelSize(slice.GetXSize(), slice.GetYSize(), thickness[i]);\n    //remember the slice\n    _slices.push_back(slice);\n    _simulated_slices.push_back(slice);\n    _simulated_weights.push_back(slice);\n    _simulated_inside.push_back(slice);\n    //remember stack index for this slice\n    _stack_index.push_back(stack_ids[i]);\n    //get slice transformation\n    _transformations.push_back(slice_transformations[i]);\n    _transformations_gpu.push_back(slice_transformations[i]);\n  }\n}\n\nvoid irtkReconstruction::UpdateSlices(vector<irtkRealImage>& stacks, vector<double>& thickness)\n{\n  _slices.clear();\n  //for each stack\n  for (unsigned int i = 0; i < stacks.size(); i++) {\n    //image attributes contain image and voxel size\n    irtkImageAttributes attr = stacks[i].GetImageAttributes();\n\n    //attr._z is number of slices in the stack\n    for (int j = 0; j < attr._z; j++) {\n      //create slice by selecting the appropreate region of the stack\n      irtkRealImage slice = stacks[i].GetRegion(0, 0, j, attr._x, attr._y, j + 1);\n      //set correct voxel size in the stack. Z size is equal to slice thickness.\n      slice.PutPixelSize(attr._dx, attr._dy, thickness[i]);\n      //remember the slice\n      _slices.push_back(slice);\n    }\n  }\n  cout << \"Number of slices: \" << _slices.size() << endl;\n\n}\n\nvoid irtkReconstruction::MaskSlices()\n{\n  cout << \"Masking slices ... \";\n\n  double x, y, z;\n  int i, j;\n\n  //Check whether we have a mask\n  if (!_have_mask) {\n    cout << \"Could not mask slices because no mask has been set.\" << endl;\n    return;\n  }\n  printf(\"%d %d \\n\", _slices.size(), _transformations.size());\n  //_mask.Write(\"mask.nii\");\n\n  //mask slices\n  for (int unsigned inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    irtkRealImage& slice = _slices[inputIndex];\n    for (i = 0; i < slice.GetX(); i++)\n      for (j = 0; j < slice.GetY(); j++) {\n      //if the value is smaller than 1 assume it is padding\n      if (slice(i, j, 0) < 0.01)\n        slice(i, j, 0) = -1;\n      //image coordinates of a slice voxel\n      x = i;\n      y = j;\n      z = 0;\n      //change to world coordinates in slice space\n      slice.ImageToWorld(x, y, z);\n      //world coordinates in volume space\n      _transformations[inputIndex].Transform(x, y, z);\n      //image coordinates in volume space\n      _mask.WorldToImage(x, y, z);\n      x = round(x);\n      y = round(y);\n      z = round(z);\n      //if the voxel is outside mask ROI set it to -1 (padding value)\n      if ((x >= 0) && (x < _mask.GetX()) && (y >= 0) && (y < _mask.GetY()) && (z >= 0)\n        && (z < _mask.GetZ())) {\n        if (_mask(x, y, z) == 0)\n          slice(i, j, 0) = -1;\n      }\n      else\n        slice(i, j, 0) = -1;\n      }\n  }\n\n  cout << \"done.\" << endl;\n}\n\n\n//TODO implement non rigid registration and its evaluation in cuda...\nclass ParallelSliceToVolumeRegistration {\npublic:\n  irtkReconstruction *reconstructor;\n\n  ParallelSliceToVolumeRegistration(irtkReconstruction *_reconstructor) :\n    reconstructor(_reconstructor) { }\n\n  void operator() (const blocked_range<size_t> &r) const {\n\n    irtkImageAttributes attr = reconstructor->_reconstructed.GetImageAttributes();\n\n    for (size_t inputIndex = r.begin(); inputIndex != r.end(); ++inputIndex) {\n      irtkImageRigidRegistrationWithPadding registration;\n      irtkGreyPixel smin, smax;\n      irtkGreyImage target;\n      irtkRealImage slice, w, b, t;\n      irtkResamplingWithPadding<irtkRealPixel> resampling(attr._dx, attr._dx, attr._dx, -1);\n      // irtkReconstruction dummy_reconstruction; // this also creats an unwanted instance of the GPU reconstruction\n\n      //target = _slices[inputIndex];\n      t = reconstructor->_slices[inputIndex];\n      resampling.SetInput(&reconstructor->_slices[inputIndex]);\n      resampling.SetOutput(&t);\n      resampling.Run();\n      target = t;\n\n      target.GetMinMax(&smin, &smax);\n\n      if (smax > -1) {\n        //put origin to zero\n        irtkRigidTransformation offset;\n        //dummy_reconstruction.ResetOrigin(target,offset);\n        irtkReconstruction::ResetOrigin(target, offset);\n        irtkMatrix mo = offset.GetMatrix();\n        irtkMatrix m = reconstructor->_transformations[inputIndex].GetMatrix();\n        m = m*mo;\n        reconstructor->_transformations[inputIndex].PutMatrix(m);\n        //std::cout << \" ofsMatrix: \" << inputIndex << std::endl;\n        //reconstructor->_transformations[inputIndex].GetMatrix().Print();\n\n        irtkGreyImage source = reconstructor->_reconstructed;\n        registration.SetInput(&target, &source);\n        registration.SetOutput(&reconstructor->_transformations[inputIndex]);\n        registration.GuessParameterSliceToVolume(reconstructor->_useNMI);\n        registration.SetTargetPadding(-1);\n        registration.Run();\n\n        reconstructor->_slices_regCertainty[inputIndex] = registration.last_similarity;\n        //undo the offset\n        mo.Invert();\n        m = reconstructor->_transformations[inputIndex].GetMatrix();\n        m = m*mo;\n        reconstructor->_transformations[inputIndex].PutMatrix(m);\n      }\n\n      printf(\".\");\n    }\n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n\n};\n\n\nvoid irtkReconstruction::setPatchBased(bool value, bool _cpu)\n{\n  _patchBased = value;\n  if (_cpu)\n  {\n    reconstructionGPU->setPachBased(value);\n  }\n}\n\n//--------------------------------------------------------------------------------------------\n// superpixel (spx)\nvoid irtkReconstruction::setSuperpixelBased(bool value, bool _cpu)\n{\n  \n  _superpixelBased = value;\n  if (_cpu)\n  {\n    reconstructionGPU->setSupepixelBased(value);\n  }\n}\n//--------------------------------------------------------------------------------------------\n\nvoid irtkReconstruction::testCPURegGPU()\n{\n  if (_debugGPU)\n  {\n    std::vector<Matrix4> transf;\n    for (int i = 0; i < _transformations_gpu.size(); i++)\n    {\n      transf.push_back(toMatrix4(_transformations_gpu[i].GetMatrix()));\n    }\n\n    reconstructionGPU->testCPUReg(transf);\n    cudaDeviceSynchronize();\n\n    irtkGenericImage<float> regTest(reconstructionGPU->regSlices.size.x, reconstructionGPU->regSlices.size.y, reconstructionGPU->regSlices.size.z);\n    reconstructionGPU->debugRegSlicesVolume(regTest.GetPointerToVoxels());\n    regTest.Write(\"regTestCPU.nii\");\n  }\n\n}\n\n\nvoid irtkReconstruction::PrepareRegistrationSlices()\n{\n  irtkImageAttributes attr = _reconstructed.GetImageAttributes();\n  irtkResamplingWithPadding<irtkRealPixel> resampling(attr._dx, attr._dx, attr._dx, -1);\n\n  vector<Matrix4> slices_resampledI2W;\n  for (int inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n  {\n    irtkRealImage t = _slices[inputIndex];\n    resampling.SetInput(&_slices[inputIndex]);\n    resampling.SetOutput(&t);\n    resampling.Run();\n    _slices_resampled.push_back(t);\n    slices_resampledI2W.push_back(toMatrix4(t.GetImageToWorldMatrix()));\n  }\n\n\n  uint3 reqVDims = make_uint3(INT_MIN, INT_MIN, 0);\n  uint3 wasteVDims = make_uint3(INT_MAX, INT_MAX, 0);\n\n  for (int i = 0; i < _slices_resampled.size(); i++)\n  {\n    reqVDims = make_uint3(max((int)reqVDims.x, _slices_resampled[i].GetX()), max((int)reqVDims.y, _slices_resampled[i].GetY()), _slices_resampled.size());\n    wasteVDims = make_uint3(min((int)wasteVDims.x, _slices_resampled[i].GetX()), min((int)wasteVDims.y, _slices_resampled[i].GetY()), _slices_resampled.size());\n  }\n\n  double waste = (((reqVDims.x - wasteVDims.x) * (reqVDims.y - wasteVDims.y) * _slices_resampled.size())*sizeof(double)*5.0) / 1024.0;\n  printf(\"GPU memory waste approx RegSlices: %f KB with %d %d %d %d\\n\", waste, reqVDims.x, reqVDims.y, wasteVDims.x, wasteVDims.y);\n\n  irtkGenericImage<float> combinedStacks(reqVDims.x, reqVDims.y, reqVDims.z);\n  float* ptr = combinedStacks.GetPointerToVoxels();\n\n  //all the same dimensions\n  reconstructionGPU->initRegStorageVolumes(reqVDims, make_float3(_slices_resampled[0].GetXSize(), _slices_resampled[0].GetYSize(), _slices_resampled[0].GetZSize()));\n  vector<int> sizesX;\n  vector<int> sizesY;\n  std::vector<float3> slice_dims;\n  combinedStacks = -1.0;\n\n  for (int i = 0; i < _slices_resampled.size(); i++)\n  {\n    irtkRealImage slice = _slices_resampled[i];\n    //We need to do this line wise because of different cropping sizes\n    for (int y = 0; y < slice.GetY(); y++)\n    {\n      for (int x = 0; x < slice.GetX(); x++)\n      {\n        combinedStacks(x, y, i) = (float)slice(x, y, 0);\n      }\n      ptr += combinedStacks.GetX();\n    }\n    ptr += abs(combinedStacks.GetY() - slice.GetY())*combinedStacks.GetX();\n    //TODO - set slice sizes\n    sizesX.push_back(slice.GetX());\n    sizesY.push_back(slice.GetY());\n    slice_dims.push_back(make_float3(_slices_resampled[i].GetXSize(), _slices_resampled[i].GetYSize(), _slices_resampled[i].GetZSize()));\n  }\n  //combinedStacks.Write(\"combinedStacks.nii\");\n\n  reconstructionGPU->FillRegSlices(combinedStacks.GetPointerToVoxels(), slices_resampledI2W);\n  //std::cin.get();\n  //reconstructionGPU->setSliceDims(slice_dims, _quality_factor);\n  //reconstructionGPU->reconstructedVoxelSize = _reconstructed.GetXSize();\n  //reconstructionGPU->UpdateScaleVector(_scale_gpu, _slice_weight_gpu);\n\n\n  if (_debugGPU)\n  {\n    irtkGenericImage<float> debugSlices(reqVDims.x, reqVDims.y, reqVDims.z);\n    reconstructionGPU->getRegSlicesVol_debug(debugSlices.GetPointerToVoxels());\n    debugSlices.Write(\"debugRegistrationSlices.nii\");\n    cudaDeviceSynchronize();\n  }\n\n}\nclass ParallelSliceToVolumeRegistrationGPU {\npublic:\n  irtkReconstruction *reconstructor;\n\n  ParallelSliceToVolumeRegistrationGPU(irtkReconstruction *_reconstructor) :\n    reconstructor(_reconstructor) { }\n\n  void operator() (const blocked_range<size_t> &r) const {\n\n    irtkImageAttributes attr = reconstructor->_reconstructed.GetImageAttributes();\n\n    unsigned int devslice = 0;\n    for (size_t inputIndex = r.begin(); inputIndex != r.end(); ++inputIndex) {\n\n      //TODO poll until GPU is free, then do\n      //TODO get current thread number, assign to stream\n      //execute registration for single slice with streams\n      size_t alls = reconstructor->_slices.size();\n      int curid = (int)inputIndex%reconstructor->reconstructionGPU->devicesToUse.size(); //TODO improve. find number of CPUs\n      printf(\"current proc ID %d dev_slice %d inputIndex %d\\n\", curid, devslice, inputIndex);\n      printf(\"ERROR NOT WORKING ANYMORE\\n\");\n      exit(-4646);\n      //reconstructor->reconstructionGPU->registerSliceToVolume(reconstructor->_transf[inputIndex], inputIndex, devslice, curid);\n      devslice++;\n    }\n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(reconstructor->reconstructionGPU->devicesToUse.size());\n    //tbb_no_threads\n    parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n\n};\n\nvoid irtkReconstruction::SliceToVolumeRegistrationGPU()\n{\n  if (_debug)\n    cout << \"SliceToVolumeRegistration\" << endl;\n\n  std::vector<irtkMatrix> mos;\n  std::vector<double3> oofs;\n  std::vector<Matrix4> ofsSlice;\n  for (int i = 0; i < _slices_resampled.size(); i++)\n  {\n    irtkRigidTransformation offset;\n    //dummy_reconstruction.ResetOrigin(target,offset);\n    double ox, oy, oz;\n    _slices_resampled[i].GetOrigin(ox, oy, oz);\n    oofs.push_back(make_double3(ox, oy, oz));\n    _slices_resampled[i].PutOrigin(0, 0, 0);\n    offset.PutTranslationX(ox);\n    offset.PutTranslationY(oy);\n    offset.PutTranslationZ(oz);\n    offset.PutRotationX(0);\n    offset.PutRotationY(0);\n    offset.PutRotationZ(0);\n\n    irtkMatrix mo = offset.GetMatrix(); \n    irtkMatrix m = _transformations_gpu[i].GetMatrix();\n    m = m*mo;\n    mos.push_back(mo);\n    _transf.push_back(toMatrix4(m));\n    ofsSlice.push_back(toMatrix4(_slices_resampled[i].GetImageToWorldMatrix()));\n  }\n  reconstructionGPU->updateResampledSlicesI2W(ofsSlice);\n\n  reconstructionGPU->prepareSliceToVolumeReg();\n  //slightly different results. investigate this\n#if 0\n  ParallelSliceToVolumeRegistrationGPU registration(this);\n  registration();\n#else\n  reconstructionGPU->registerSlicesToVolume(_transf);\n#endif\n  //cudaDeviceSynchronize();\n\n  //TODO update sliceTransforms_, Matrix4 to irtkTransform\n  for (int i = 0; i < _transformations_gpu.size(); i++)\n  {\n    irtkMatrix mat = fromMatrix4(_transf[i]);\n    irtkMatrix mo = mos[i];\n    mo.Invert();\n    mat = mat*mo;\n    _transformations_gpu[i].PutMatrix(mat);\n\n    double3 oofs_ = oofs[i];\n    _slices_resampled[i].PutOrigin(oofs_.x, oofs_.y, oofs_.z);\n  }\n\n  for (int i = 0; i < _transformations.size(); i++)\n  {\n    std::cout << \"CPU: \";\n    _transformations[i].Print();\n    std::cout << \"GPU: \";\n    _transformations_gpu[i].Print();\n  }\n\n  if (_debugGPU)\n  {\n    irtkGenericImage<float> regTest(reconstructionGPU->regSlices.size.x, reconstructionGPU->regSlices.size.y, reconstructionGPU->regSlices.size.z);\n    reconstructionGPU->debugRegSlicesVolume(regTest.GetPointerToVoxels());\n    regTest.Write(\"regTestGPU.nii\");\n}\n\n}\n\n\nvoid irtkReconstruction::SliceToVolumeRegistration()\n{\n  if (_slices_regCertainty.size() == 0) _slices_regCertainty.resize(_slices.size());\n  if (_debug)\n    cout << \"SliceToVolumeRegistration\" << endl;\n  ParallelSliceToVolumeRegistration registration(this);\n  registration();\n  if (_useCPUReg)\n  {\n    _transformations_gpu = _transformations;\n  }\n  printf(\"\\n\");\n}\n\nclass ParallelCoeffInit {\npublic:\n  irtkReconstruction *reconstructor;\n\n  ParallelCoeffInit(irtkReconstruction *_reconstructor) :\n    reconstructor(_reconstructor) { }\n\n  void operator() (const blocked_range<size_t> &r) const {\n\n    for (size_t inputIndex = r.begin(); inputIndex != r.end(); ++inputIndex) {\n\n      bool slice_inside;\n\n      //current slice\n      //irtkRealImage slice;\n\n      //get resolution of the volume\n      double vx, vy, vz;\n      reconstructor->_reconstructed.GetPixelSize(&vx, &vy, &vz);\n      //volume is always isotropic\n      double res = vx;\n\n      //start of a loop for a slice inputIndex\n      cout << inputIndex << \" \";\n\n      //read the slice\n      irtkRealImage& slice = reconstructor->_slices[inputIndex];\n\n      //prepare structures for storage\n      POINT3D p;\n      VOXELCOEFFS empty;\n      SLICECOEFFS slicecoeffs(slice.GetX(), vector < VOXELCOEFFS >(slice.GetY(), empty));\n\n      //to check whether the slice has an overlap with mask ROI\n      slice_inside = false;\n\n      //PSF will be calculated in slice space in higher resolution\n\n      //get slice voxel size to define PSF\n      double dx, dy, dz;\n      slice.GetPixelSize(&dx, &dy, &dz);\n\n      //sigma of 3D Gaussian (sinc with FWHM=dx or dy in-plane, Gaussian with FWHM = dz through-plane)\n      double sigmax = 1.2 * dx / 2.3548;\n      double sigmay = 1.2 * dy / 2.3548;\n      double sigmaz = dz / 2.3548;\n      /*\n      cout<<\"Original sigma\"<<sigmax<<\" \"<<sigmay<<\" \"<<sigmaz<<endl;\n\n      //readjust for resolution of the volume\n      //double sigmax,sigmay,sigmaz;\n      double sigmamin = res/(3*2.3548);\n\n      if((dx-res)>sigmamin)\n      sigmax = 1.2 * sqrt(dx*dx-res*res) / 2.3548;\n      else sigmax = sigmamin;\n\n      if ((dy-res)>sigmamin)\n      sigmay = 1.2 * sqrt(dy*dy-res*res) / 2.3548;\n      else\n      sigmay=sigmamin;\n      if ((dz-1.2*res)>sigmamin)\n      sigmaz = sqrt(dz*dz-1.2*1.2*res*res) / 2.3548;\n      else sigmaz=sigmamin;\n\n      cout<<\"Adjusted sigma:\"<<sigmax<<\" \"<<sigmay<<\" \"<<sigmaz<<endl;\n      */\n\n      //calculate discretized PSF\n\n      //isotropic voxel size of PSF - derived from resolution of reconstructed volume\n      double size = res / reconstructor->_quality_factor;\n\n      //number of voxels in each direction\n      //the ROI is 2*voxel dimension\n\n      int xDim = round(2 * dx / size);\n      int yDim = round(2 * dy / size);\n      int zDim = round(2 * dz / size);\n\n      //image corresponding to PSF\n      irtkImageAttributes attr;\n      attr._x = xDim;\n      attr._y = yDim;\n      attr._z = zDim;\n      attr._dx = size;\n      attr._dy = size;\n      attr._dz = size;\n      irtkRealImage PSF(attr);\n\n      //centre of PSF\n      double cx, cy, cz;\n      cx = 0.5 * (xDim - 1);\n      cy = 0.5 * (yDim - 1);\n      cz = 0.5 * (zDim - 1);\n      PSF.ImageToWorld(cx, cy, cz);\n\n      double x, y, z;\n      double sum = 0;\n      int i, j, k;\n      for (i = 0; i < xDim; i++)\n        for (j = 0; j < yDim; j++)\n          for (k = 0; k < zDim; k++) {\n        x = i;\n        y = j;\n        z = k;\n        PSF.ImageToWorld(x, y, z);\n        x -= cx;\n        y -= cy;\n        z -= cz;\n        //continuous PSF does not need to be normalized as discrete will be\n        PSF(i, j, k) = exp(\n          -x * x / (2 * sigmax * sigmax) - y * y / (2 * sigmay * sigmay)\n          - z * z / (2 * sigmaz * sigmaz));\n        sum += PSF(i, j, k);\n          }\n      PSF /= sum;\n\n      if (reconstructor->_debug)\n        if (inputIndex == 0)\n          PSF.Write(\"PSF.nii.gz\");\n\n      //prepare storage for PSF transformed and resampled to the space of reconstructed volume\n      //maximum dim of rotated kernel - the next higher odd integer plus two to accound for rounding error of tx,ty,tz.\n      //Note conversion from PSF image coordinates to tPSF image coordinates *size/res\n      int dim = (floor(ceil(sqrt(double(xDim * xDim + yDim * yDim + zDim * zDim)) * size / res) / 2))\n        * 2 + 1 + 2;\n      //prepare image attributes. Voxel dimension will be taken from the reconstructed volume\n      attr._x = dim;\n      attr._y = dim;\n      attr._z = dim;\n      attr._dx = res;\n      attr._dy = res;\n      attr._dz = res;\n      //create matrix from transformed PSF\n      irtkRealImage tPSF(attr);\n      //calculate centre of tPSF in image coordinates\n      int centre = (dim - 1) / 2;\n\n      //for each voxel in current slice calculate matrix coefficients\n      int ii, jj, kk;\n      int tx, ty, tz;\n      int nx, ny, nz;\n      int l, m, n;\n      double weight;\n      for (i = 0; i < slice.GetX(); i++)\n        for (j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        //calculate centrepoint of slice voxel in volume space (tx,ty,tz)\n        x = i;\n        y = j;\n        z = 0;\n        slice.ImageToWorld(x, y, z);\n        reconstructor->_transformations[inputIndex].Transform(x, y, z);\n        reconstructor->_reconstructed.WorldToImage(x, y, z);\n        tx = round(x);\n        ty = round(y);\n        tz = round(z);\n\n        //Clear the transformed PSF\n        for (ii = 0; ii < dim; ii++)\n          for (jj = 0; jj < dim; jj++)\n            for (kk = 0; kk < dim; kk++)\n              tPSF(ii, jj, kk) = 0;\n\n        //for each POINT3D of the PSF\n        for (ii = 0; ii < xDim; ii++)\n          for (jj = 0; jj < yDim; jj++)\n            for (kk = 0; kk < zDim; kk++) {\n          //Calculate the position of the POINT3D of\n          //PSF centered over current slice voxel                            \n          //This is a bit complicated because slices\n          //can be oriented in any direction \n\n          //PSF image coordinates\n          x = ii;\n          y = jj;\n          z = kk;\n          //change to PSF world coordinates - now real sizes in mm\n          PSF.ImageToWorld(x, y, z);\n          //centre around the centrepoint of the PSF\n          x -= cx;\n          y -= cy;\n          z -= cz;\n\n          //Need to convert (x,y,z) to slice image\n          //coordinates because slices can have\n          //transformations included in them (they are\n          //nifti)  and those are not reflected in\n          //PSF. In slice image coordinates we are\n          //sure that z is through-plane \n\n          //adjust according to voxel size\n          x /= dx;\n          y /= dy;\n          z /= dz;\n          //center over current voxel\n          x += i;\n          y += j;\n\n          //convert from slice image coordinates to world coordinates\n          slice.ImageToWorld(x, y, z);\n\n          //x+=(vx-cx); y+=(vy-cy); z+=(vz-cz);\n          //Transform to space of reconstructed volume\n          reconstructor->_transformations[inputIndex].Transform(x, y, z);\n          //Change to image coordinates\n          reconstructor->_reconstructed.WorldToImage(x, y, z);\n\n          //determine coefficients of volume voxels for position x,y,z\n          //using linear interpolation\n\n          //Find the 8 closest volume voxels\n\n          //lowest corner of the cube\n          nx = (int)floor(x);\n          ny = (int)floor(y);\n          nz = (int)floor(z);\n\n          //not all neighbours might be in ROI, thus we need to normalize\n          //(l,m,n) are image coordinates of 8 neighbours in volume space\n          //for each we check whether it is in volume\n          sum = 0;\n          //to find wether the current slice voxel has overlap with ROI\n          bool inside = false;\n          for (l = nx; l <= nx + 1; l++)\n            if ((l >= 0) && (l < reconstructor->_reconstructed.GetX()))\n              for (m = ny; m <= ny + 1; m++)\n                if ((m >= 0) && (m < reconstructor->_reconstructed.GetY()))\n                  for (n = nz; n <= nz + 1; n++)\n                    if ((n >= 0) && (n < reconstructor->_reconstructed.GetZ())) {\n            weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));\n            sum += weight;\n            if (reconstructor->_mask(l, m, n) == 1) {\n              inside = true;\n              slice_inside = true;\n            }\n                    }\n          //if there were no voxels do nothing\n          if ((sum <= 0) || (!inside))\n            continue;\n          //now calculate the transformed PSF\n          for (l = nx; l <= nx + 1; l++)\n            if ((l >= 0) && (l < reconstructor->_reconstructed.GetX()))\n              for (m = ny; m <= ny + 1; m++)\n                if ((m >= 0) && (m < reconstructor->_reconstructed.GetY()))\n                  for (n = nz; n <= nz + 1; n++)\n                    if ((n >= 0) && (n < reconstructor->_reconstructed.GetZ())) {\n            weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));\n\n            //image coordinates in tPSF\n            //(centre,centre,centre) in tPSF is aligned with (tx,ty,tz)\n            int aa, bb, cc;\n            aa = l - tx + centre;\n            bb = m - ty + centre;\n            cc = n - tz + centre;\n\n            //resulting value\n            double value = PSF(ii, jj, kk) * weight / sum;\n\n            //Check that we are in tPSF\n            if ((aa < 0) || (aa >= dim) || (bb < 0) || (bb >= dim) || (cc < 0)\n              || (cc >= dim)) {\n              cerr << \"Error while trying to populate tPSF. \" << aa << \" \" << bb\n                << \" \" << cc << endl;\n              cerr << l << \" \" << m << \" \" << n << endl;\n              cerr << tx << \" \" << ty << \" \" << tz << endl;\n              cerr << centre << endl;\n              tPSF.Write(\"tPSF.nii\");\n              exit(1);\n            }\n            else\n              //update transformed PSF\n              tPSF(aa, bb, cc) += value;\n                    }\n            } //end of the loop for PSF points\n\n        //store tPSF values\n        for (ii = 0; ii < dim; ii++)\n          for (jj = 0; jj < dim; jj++)\n            for (kk = 0; kk < dim; kk++)\n              if (tPSF(ii, jj, kk) > 0) {\n          p.x = ii + tx - centre;\n          p.y = jj + ty - centre;\n          p.z = kk + tz - centre;\n          p.value = (float)tPSF(ii, jj, kk);\n          slicecoeffs[i][j].push_back(p);\n              }\n        //cout << \" n = \" << slicecoeffs[i][j].size() << std::endl;\n          } //end of loop for slice voxels\n\n      //tPSF.Write(\"tPSF.nii\");\n      //PSF.Write(\"PSF.nii\");\n\n\n      reconstructor->_volcoeffs[inputIndex] = slicecoeffs;\n      reconstructor->_slice_inside_cpu[inputIndex] = slice_inside;\n\n    }  //end of loop through the slices                            \n\n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n\n};\n\nvoid irtkReconstruction::CoeffInit()\n{\n  if (_debug)\n    cout << \"CoeffInit\" << endl;\n\n  //clear slice-volume matrix from previous iteration\n  _volcoeffs.clear();\n  _volcoeffs.resize(_slices.size());\n\n  //clear indicator of slice having and overlap with volumetric mask\n  _slice_inside_cpu.clear();\n  _slice_inside_cpu.resize(_slices.size());\n\n  cout << \"Initialising matrix coefficients...\";\n  ParallelCoeffInit coeffinit(this);\n  coeffinit();\n  cout << \" ... done.\" << endl;\n\n  //prepare image for volume weights, will be needed for Gaussian Reconstruction\n  _volume_weights.Initialize(_reconstructed.GetImageAttributes());\n  _volume_weights = 0;\n\n  int inputIndex, i, j, n, k;\n  POINT3D p;\n  for (inputIndex = 0; inputIndex < _slices.size(); ++inputIndex) {\n    for (i = 0; i < _slices[inputIndex].GetX(); i++)\n      for (j = 0; j < _slices[inputIndex].GetY(); j++) {\n      n = _volcoeffs[inputIndex][i][j].size();\n      for (k = 0; k < n; k++) {\n        p = _volcoeffs[inputIndex][i][j][k];\n        _volume_weights(p.x, p.y, p.z) += p.value;\n      }\n      }\n  }\n  if (_debug || _debugGPU)\n    _volume_weights.Write(\"volume_weightsCPU.nii\");\n\n  //find average volume weight to modify alpha parameters accordingly\n  irtkRealPixel *ptr = _volume_weights.GetPointerToVoxels();\n  irtkRealPixel *pm = _mask.GetPointerToVoxels();\n  double sum = 0;\n  int num = 0;\n  for (int i = 0; i < _volume_weights.GetNumberOfVoxels(); i++) {\n    if (*pm == 1) {\n      sum += *ptr;\n      num++;\n    }\n    ptr++;\n    pm++;\n  }\n  _average_volume_weight = sum / num;\n\n  if (_debug) {\n    cout << \"Average volume weight is \" << _average_volume_weight << endl;\n  }\n\n}  //end of CoeffInit()\n\nvoid irtkReconstruction::SyncCPU()\n{\n  irtkGenericImage<float> trecon = _reconstructed_gpu;\n\n\n  reconstructionGPU->syncCPU(trecon.GetPointerToVoxels());\n  _reconstructed = trecon;\n  printf(\"Sync done. ready for more...\\n\");\n}\n\nirtkRealImage irtkReconstruction::GetReconstructedGPU()\n{\n  irtkGenericImage<float> trecon = _reconstructed_gpu;\n\n  //debug only\n  reconstructionGPU->syncCPU(trecon.GetPointerToVoxels());\n\n  return trecon;\n}\n\nvoid irtkReconstruction::GaussianReconstructionGPU()\n{\n\n  cout << \"Gaussian reconstruction ... \";\n  vector<int> voxel_num_gpu;\n  reconstructionGPU->GaussianReconstruction(voxel_num_gpu);\n  //irtkRealImage trecon = _reconstructed;\n  //debug only\n  //reconstructionGPU->syncCPU(trecon.GetPointerToVoxels());\n  //trecon.Write(\"GaussianRecon_Test2.nii\");\n\n  int slice_vox_num = 0;\n  cout << \"done.\" << endl;\n\n  if (_debug)\n    _reconstructed.Write(\"init.nii.gz\");\n\n  //now find slices with small overlap with ROI and exclude them.\n\n  vector<int> voxel_num_tmp;\n  for (int i = 0; i < voxel_num_gpu.size(); i++)\n    voxel_num_tmp.push_back(voxel_num_gpu[i]);\n\n  //find median\n  sort(voxel_num_tmp.begin(), voxel_num_tmp.end());\n  int median = voxel_num_tmp[round(voxel_num_tmp.size()*0.5)];\n\n  //remember slices with small overlap with ROI\n  _small_slices.clear();\n  for (int i = 0; i < voxel_num_gpu.size(); i++)\n    if (voxel_num_gpu[i] < 0.1*median)\n      _small_slices.push_back(i);\n\n  if (_debug || _debugGPU) {\n    cout << \"Small slices GPU:\";\n    for (int i = 0; i < _small_slices.size(); i++)\n      cout << \" \" << _small_slices[i];\n    cout << endl;\n  }\n\n  if (_debugGPU)\n  {\n    irtkGenericImage<float> bweights;\n    bweights.Initialize(_reconstructed.GetImageAttributes());\n    //irtkRealImage bweights(reconstructionGPU->reconstructed_volWeigths.size.x, reconstructionGPU->reconstructed_volWeigths.size.y, reconstructionGPU->reconstructed_volWeigths.size.z);\n    reconstructionGPU->getVolWeights(bweights.GetPointerToVoxels());\n    bweights.Write(\"volume_weightsGPU.nii\");\n\n    irtkGenericImage<float> weightnorm(reconstructionGPU->v_PSF_sums_.size.x, reconstructionGPU->v_PSF_sums_.size.y, reconstructionGPU->v_PSF_sums_.size.z);\n    reconstructionGPU->debugv_PSF_sums(weightnorm.GetPointerToVoxels());\n    weightnorm.Write(\"v_PSF_sums_.nii\");\n  }\n\n  //registration test\n#if 0\n  //TODO improve and copy transformations back\n  //finally, leave on device, init slice trans only for init once\n  std::vector<Matrix4> transf;\n  reconstructionGPU->registerSlicesToVolume(transf);\n  irtkGenericImage<float> regTest(reconstructionGPU->regSlices.size.x, reconstructionGPU->regSlices.size.y, reconstructionGPU->regSlices.size.z);\n  reconstructionGPU->debugRegSlicesVolume(regTest.GetPointerToVoxels());\n  regTest.Write(\"regTest.nii\");\n\n  //printf(\"second test\\n\");\n  //reconstructionGPU->registerSlicesToVolume();\n#endif\n\n}\n\n\nvoid irtkReconstruction::GaussianReconstruction()\n{\n  //vector<int> voxel_num_;  \n  //reconstructionGPU->GaussianReconstruction(voxel_num_);\n\n  cout << \"Gaussian reconstruction ... \";\n  unsigned int inputIndex;\n  int i, j, k, n;\n  irtkRealImage slice;\n  double scale;\n  POINT3D p;\n  vector<int> voxel_num;\n  int slice_vox_num;\n\n  //clear _reconstructed image\n  _reconstructed = 0;\n\n  //std::cout << \"voxel_num CPU: \";\n  //CPU\n  for (inputIndex = 0; inputIndex < _slices.size(); ++inputIndex) {\n    //copy the current slice\n    slice = _slices[inputIndex];\n    //alias the current bias image\n    irtkRealImage& b = _bias[inputIndex];\n    //read current scale factor\n    scale = _scale_cpu[inputIndex];\n\n    slice_vox_num = 0;\n\n    //Distribute slice intensities to the volume\n    for (i = 0; i < slice.GetX(); i++)\n      for (j = 0; j < slice.GetY(); j++)\n        if (slice(i, j, 0) != -1) {\n      //biascorrect and scale the slice\n      slice(i, j, 0) *= exp(-b(i, j, 0)) * scale;\n\n      //number of volume voxels with non-zero coefficients\n      //for current slice voxel\n      n = _volcoeffs[inputIndex][i][j].size();\n\n      //if given voxel is not present in reconstructed volume at all,\n      //pad it\n\n      //if (n == 0)\n      //_slices[inputIndex].PutAsDouble(i, j, 0, -1);\n      //calculate num of vox in a slice that have overlap with roi\n      if (n > 0)\n        slice_vox_num++;\n\n      //add contribution of current slice voxel to all voxel volumes\n      //to which it contributes\n      for (k = 0; k < n; k++) {\n        p = _volcoeffs[inputIndex][i][j][k];\n        _reconstructed(p.x, p.y, p.z) += p.value * slice(i, j, 0);\n      }\n      //debug\n      //p = _volcoeffs[inputIndex][i][j][0];\n      //_reconstructed(p.x, p.y, p.z) += slice(i, j, 0);\n        }\n    voxel_num.push_back(slice_vox_num);\n    //std::cout << voxel_num[inputIndex] << \" \";\n    //end of loop for a slice inputIndex\n  }\n\n  //normalize the volume by proportion of contributing slice voxels\n  //for each volume voxe\n  _reconstructed /= _volume_weights;\n\n  cout << \"done.\" << endl;\n\n  if (_debug)\n    _reconstructed.Write(\"init.nii.gz\");\n\n  //now find slices with small overlap with ROI and exclude them.\n\n  vector<int> voxel_num_tmp;\n  for (i = 0; i < voxel_num.size(); i++)\n    voxel_num_tmp.push_back(voxel_num[i]);\n\n  //find median\n  sort(voxel_num_tmp.begin(), voxel_num_tmp.end());\n  int median = voxel_num_tmp[round(voxel_num_tmp.size()*0.5)];\n\n  //remember slices with small overlap with ROI\n  _small_slices.clear();\n  for (i = 0; i < voxel_num.size(); i++)\n    if (voxel_num[i] < 0.1*median)\n      _small_slices.push_back(i);\n\n  if (_debug || _debugGPU) {\n    cout << \"Small slices CPU:\";\n    for (i = 0; i < _small_slices.size(); i++)\n      cout << \" \" << _small_slices[i];\n    cout << endl;\n  }\n}\n\nvoid irtkReconstruction::InitializeEM()\n{\n  if (_debug)\n    cout << \"InitializeEM\" << endl;\n\n  _weights.clear();\n  _bias.clear();\n  _scale_cpu.clear();\n  _slice_weight_cpu.clear();\n\n  for (unsigned int i = 0; i < _slices.size(); i++) {\n    //Create images for voxel weights and bias fields\n    _weights.push_back(_slices[i]);\n    _bias.push_back(_slices[i]);\n\n    //Create and initialize scales\n    _scale_cpu.push_back(1);\n    //_scale_gpu.push_back(1);\n\n    //Create and initialize slice weights\n    _slice_weight_cpu.push_back(1);\n    //_slice_weight_gpu.push_back(1);\n  }\n\n  //TODO CUDA\n  //Find the range of intensities\n  _max_intensity = voxel_limits<irtkRealPixel>::min();\n  _min_intensity = voxel_limits<irtkRealPixel>::max();\n  for (unsigned int i = 0; i < _slices.size(); i++) {\n    //to update minimum we need to exclude padding value\n    irtkRealPixel *ptr = _slices[i].GetPointerToVoxels();\n    for (int ind = 0; ind < _slices[i].GetNumberOfVoxels(); ind++) {\n      if (*ptr > 0) {\n        if (*ptr > _max_intensity)\n          _max_intensity = *ptr;\n        if (*ptr < _min_intensity)\n          _min_intensity = *ptr;\n      }\n      ptr++;\n    }\n  }\n}\n\nvoid irtkReconstruction::InitializeEMValuesGPU()\n{\n  if (_debug)\n    cout << \"InitializeEMValues\" << endl;\n\n  _scale_gpu.clear();\n  _slice_weight_gpu.clear();\n\n  _slice_weight_gpu.assign(_slices.size(), 1);\n  _scale_gpu.assign(_slices.size(), 1);\n  reconstructionGPU->UpdateScaleVector(_scale_gpu, _slice_weight_gpu);\n\n  reconstructionGPU->InitializeEMValues();\n\n}\n\nvoid irtkReconstruction::InitializeEMGPU()\n{\n  if (_debug)\n    cout << \"InitializeEM\" << endl;\n\n  _scale_gpu.clear();\n  _slice_weight_gpu.clear();\n\n  _slice_weight_gpu.assign(_slices.size(), 1);\n  _scale_gpu.assign(_slices.size(), 1);\n  reconstructionGPU->UpdateScaleVector(_scale_gpu, _slice_weight_gpu);\n\n  reconstructionGPU->InitializeEMValues();\n\n  //TODO CUDA\n  //Find the range of intensities\n  _max_intensity = voxel_limits<irtkRealPixel>::min();\n  _min_intensity = voxel_limits<irtkRealPixel>::max();\n  for (unsigned int i = 0; i < _slices.size(); i++) {\n    //to update minimum we need to exclude padding value\n    irtkRealPixel *ptr = _slices[i].GetPointerToVoxels();\n    for (int ind = 0; ind < _slices[i].GetNumberOfVoxels(); ind++) {\n      if (*ptr > 0) {\n        if (*ptr > _max_intensity)\n          _max_intensity = *ptr;\n        if (*ptr < _min_intensity)\n          _min_intensity = *ptr;\n      }\n      ptr++;\n    }\n  }\n\n}\n\nvoid irtkReconstruction::InitializeEMValues()\n{\n  if (_debug)\n    cout << \"InitializeEMValues\" << endl;\n\n  for (unsigned int i = 0; i < _slices.size(); i++) {\n    //Initialise voxel weights and bias values\n    irtkRealPixel *pw = _weights[i].GetPointerToVoxels();\n    irtkRealPixel *pb = _bias[i].GetPointerToVoxels();\n    irtkRealPixel *pi = _slices[i].GetPointerToVoxels();\n    for (int j = 0; j < _weights[i].GetNumberOfVoxels(); j++) {\n      if (*pi != -1) {\n        *pw = 1;\n        *pb = 0;\n      }\n      else {\n        *pw = 0;\n        *pb = 0;\n      }\n      pi++;\n      pw++;\n      pb++;\n    }\n\n    //Initialise slice weights\n    _slice_weight_cpu[i] = 1;\n\n    //Initialise scaling factors for intensity matching\n    _scale_cpu[i] = 1;\n  }\n}\n\n\nvoid irtkReconstruction::InitializeRobustStatisticsGPU()\n{\n  if (_debug)\n    cout << \"InitializeRobustStatistics\" << endl;\n\n  reconstructionGPU->InitializeRobustStatistics(_sigma_gpu);\n\n  for (unsigned int inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    //if slice does not have an overlap with ROI, set its weight to zero\n    if (!_slice_inside_gpu[inputIndex])\n      _slice_weight_gpu[inputIndex] = 0;\n  }\n  //Force exclusion of slices predefined by user\n  for (unsigned int i = 0; i < _force_excluded.size(); i++)\n    _slice_weight_gpu[_force_excluded[i]] = 0;\n\n\n  //initialize sigma for slice-wise robust statistics\n  _sigma_s_gpu = 0.025f;\n  //initialize mixing proportion for inlier class in voxel-wise robust statistics\n  _mix_gpu = 0.9f;\n  //initialize mixing proportion for outlier class in slice-wise robust statistics\n  _mix_s_gpu = 0.9f;\n  //Initialise value for uniform distribution according to the range of intensities\n  _m_gpu = (float)(1.0f / (2.1f * _max_intensity - 1.9f * _min_intensity));\n\n  if (_debug || _debugGPU)\n    cout << \"Initializing robust statistics GPU: \" << \"sigma=\" << sqrt(_sigma_gpu) << \" \" << \"m=\" << _m_gpu\n    << \" \" << \"mix=\" << _mix_gpu << \" \" << \"mix_s=\" << _mix_s_gpu << endl;\n\n  reconstructionGPU->UpdateScaleVector(_scale_gpu, _slice_weight_gpu);\n\n}\n\nvoid irtkReconstruction::InitializeRobustStatistics()\n{\n  if (_debug)\n    cout << \"InitializeRobustStatistics\" << endl;\n\n  //Initialise parameter of EM robust statistics\n  int i, j;\n  irtkRealImage slice, sim;\n  double sigma = 0;\n  int num = 0;\n\n  //for each slice\n  for (unsigned int inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    slice = _slices[inputIndex];\n\n    //Voxel-wise sigma will be set to stdev of volumetric errors\n    //For each slice voxel\n    for (i = 0; i < slice.GetX(); i++)\n      for (j = 0; j < slice.GetY(); j++)\n        if (slice(i, j, 0) != -1) {\n      //calculate stev of the errors\n      if ((_simulated_inside[inputIndex](i, j, 0) == 1)\n        && (_simulated_weights[inputIndex](i, j, 0) > 0.99)) {\n        slice(i, j, 0) -= _simulated_slices[inputIndex](i, j, 0);\n        sigma += slice(i, j, 0) * slice(i, j, 0);\n        num++;\n      }\n        }\n\n    //if slice does not have an overlap with ROI, set its weight to zero\n    if (!_slice_inside_cpu[inputIndex])\n      _slice_weight_cpu[inputIndex] = 0;\n  }\n\n  //Force exclusion of slices predefined by user\n  for (unsigned int i = 0; i < _force_excluded.size(); i++)\n    _slice_weight_cpu[_force_excluded[i]] = 0;\n\n  //initialize sigma for voxelwise robust statistics\n  _sigma_cpu = sigma / num;\n  //initialize sigma for slice-wise robust statistics\n  _sigma_s_cpu = 0.025;\n  //initialize mixing proportion for inlier class in voxel-wise robust statistics\n  _mix_cpu = 0.9;\n  //initialize mixing proportion for outlier class in slice-wise robust statistics\n  _mix_s_cpu = 0.9;\n  //Initialise value for uniform distribution according to the range of intensities\n  _m_cpu = 1 / (2.1 * _max_intensity - 1.9 * _min_intensity);\n\n  if (_debug || _debugGPU)\n    cout << \"Initializing robust statistics CPU: \" << \"sigma=\" << sqrt(_sigma_cpu) << \" \" << \"m=\" << _m_cpu\n    << \" \" << \"mix=\" << _mix_cpu << \" \" << \"mix_s=\" << _mix_s_cpu << endl;\n}\n\nclass ParallelEStep {\n  irtkReconstruction* reconstructor;\n  vector<double> &slice_potential;\n\npublic:\n\n  void operator()(const blocked_range<size_t>& r) const {\n    for (size_t inputIndex = r.begin(); inputIndex < r.end(); ++inputIndex) {\n      // read the current slice\n      irtkRealImage slice = reconstructor->_slices[inputIndex];\n\n      //read current weight image\n      reconstructor->_weights[inputIndex] = 0;\n\n      //alias the current bias image\n      irtkRealImage& b = reconstructor->_bias[inputIndex];\n\n      //identify scale factor\n      double scale = reconstructor->_scale_cpu[inputIndex];\n\n      double num = 0;\n      //Calculate error, voxel weights, and slice potential\n      for (int i = 0; i < slice.GetX(); i++)\n        for (int j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        //bias correct and scale the slice\n        slice(i, j, 0) *= exp(-b(i, j, 0)) * scale;\n\n        //number of volumetric voxels to which\n        // current slice voxel contributes\n        size_t n = reconstructor->_volcoeffs[inputIndex][i][j].size();\n\n        // if n == 0, slice voxel has no overlap with volumetric ROI,\n        // do not process it\n\n        if ((n>0) &&\n          (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0)) {\n          slice(i, j, 0) -= reconstructor->_simulated_slices[inputIndex](i, j, 0);\n\n          //calculate norm and voxel-wise weights\n\n          //Gaussian distribution for inliers (likelihood)\n          double g = reconstructor->G(slice(i, j, 0), reconstructor->_sigma_cpu);\n          //Uniform distribution for outliers (likelihood)\n          double m = reconstructor->M(reconstructor->_m_cpu);\n\n          //voxel_wise posterior\n          double weight = g * reconstructor->_mix_cpu / (g *reconstructor->_mix_cpu + m * (1 - reconstructor->_mix_cpu));\n          reconstructor->_weights[inputIndex].PutAsDouble(i, j, 0, weight);\n\n          //calculate slice potentials\n          if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {\n            slice_potential[inputIndex] += (1.0 - weight) * (1.0 - weight);\n            num++;\n          }\n        }\n        else\n          reconstructor->_weights[inputIndex].PutAsDouble(i, j, 0, 0);\n          }\n\n      //evaluate slice potential\n      if (num > 0)\n      {\n        slice_potential[inputIndex] = sqrt(slice_potential[inputIndex] / num);\n        //std::cout <<  num  << \" \";\n      }\n      else\n        slice_potential[inputIndex] = -1; // slice has no unpadded voxels\n    }\n  }\n\n  ParallelEStep(irtkReconstruction *reconstructor,\n    vector<double> &slice_potential) :\n    reconstructor(reconstructor), slice_potential(slice_potential)\n  { }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n\n};\n\nirtkGenericImage<float> irtkReconstruction::getVolWeights()\n{\n  int dev = reconstructionGPU->devicesToUse[0];\n  irtkGenericImage<float> bweights(reconstructionGPU->dev_reconstructed_[dev].size.x, reconstructionGPU->dev_reconstructed_[dev].size.y, reconstructionGPU->dev_reconstructed_[dev].size.z);\n  reconstructionGPU->getVolWeights(bweights.GetPointerToVoxels());\n\n  return bweights;\n}\n\nirtkGenericImage<float> irtkReconstruction::getWeights()\n{\n  \n  //bweights = 0;\n  irtkGenericImage<float> bweights = _reconstructed;\n  reconstructionGPU->combineWeights(bweights.GetPointerToVoxels());\n\n  //irtkGenericImage<float> bweights(reconstructionGPU->v_weights.size.x, reconstructionGPU->v_weights.size.y, reconstructionGPU->v_weights.size.z);// _reconstructed;\n  //reconstructionGPU->debugWeights(bweights.GetPointerToVoxels());\n  \n  return bweights;\n}\n\nvoid irtkReconstruction::EStepGPU()\n{\n  //EStep performs calculation of voxel-wise and slice-wise posteriors (weights)\n  if (_debug)\n    cout << \"EStep: \" << endl;\n\n  unsigned int inputIndex;\n  vector<float> slice_potential_gpu(_slices.size(), 0);\n  reconstructionGPU->EStep(_m_gpu, _sigma_gpu, _mix_gpu, slice_potential_gpu);\n\n  if (_debugGPU)\n  {\n    irtkGenericImage<float> bweights(reconstructionGPU->v_weights.size.x, reconstructionGPU->v_weights.size.y, reconstructionGPU->v_weights.size.z);\n    reconstructionGPU->debugWeights(bweights.GetPointerToVoxels());\n    bweights.Write(\"testweightGPU.nii\");\n  }\n\n  //can stay on CPU\n\n  //To force-exclude slices predefined by a user, set their potentials to -1\n  for (unsigned int i = 0; i < _force_excluded.size(); i++)\n    slice_potential_gpu[_force_excluded[i]] = -1;\n\n  //exclude slices identified as having small overlap with ROI, set their potentials to -1\n  for (unsigned int i = 0; i < _small_slices.size(); i++)\n    slice_potential_gpu[_small_slices[i]] = -1;\n\n  //these are unrealistic scales pointing at misregistration - exclude the corresponding slices\n  for (inputIndex = 0; inputIndex < slice_potential_gpu.size(); inputIndex++)\n    if ((_scale_gpu[inputIndex] < 0.2) || (_scale_gpu[inputIndex]>5)) {\n    slice_potential_gpu[inputIndex] = -1;\n    }\n\n  // exclude unrealistic transformations\n  /*\n  int current_stack = 0;\n  int nb_stacks = _stack_index[_stack_index.size()-1];\n  double tx,ty,tz,rx,ry,rz, nb;\n  for ( int i = 0; i < nb_stacks; i++ ) {\n  tx = 0;\n  ty = 0;\n  tz = 0;\n  rx = 0;\n  ry = 0;\n  rz = 0;\n  nb = 0;\n  for ( int j = 0; j < _slices.size(); j++ ) {\n  if ( _stack_index[j] != i )\n  continue;\n  if ( slice_potential[j] == -1 )\n  continue;\n  tx += _transformations[j].GetTranslationX();\n  ty += _transformations[j].GetTranslationY();\n  tz += _transformations[j].GetTranslationZ();\n  rx += _transformations[j].GetRotationX();\n  ry += _transformations[j].GetRotationY();\n  rz += _transformations[j].GetRotationZ();\n  nb++;\n  }\n  tx /= nb;\n  ty /= nb;\n  tz /= nb;\n  rx /= nb;\n  ry /= nb;\n  rz /= nb;\n  for ( int j = 0; j < _slices.size(); j++ ) {\n  if ( _stack_index[j] != i )\n  continue;\n  if ( slice_potential[j] == -1 )\n  continue;\n  if ( abs( tx - _transformations[j].GetTranslationX() ) > 20\n  || abs( ty - _transformations[j].GetTranslationY() ) > 20\n  || abs( tz - _transformations[j].GetTranslationZ() ) > 20\n  || abs( rx - _transformations[j].GetRotationX() ) > 5\n  || abs( ry - _transformations[j].GetRotationY() ) > 5\n  || abs( rz - _transformations[j].GetRotationZ() ) > 5 )\n  slice_potential[j] = -1;\n  }\n  }\n  */\n  if (_debug || _debugGPU) {\n    cout << setprecision(4);\n    cout << endl << \"Slice potentials GPU: \";\n    for (inputIndex = 0; inputIndex < slice_potential_gpu.size(); inputIndex++)\n      cout << slice_potential_gpu[inputIndex] << \" \";\n    cout << endl << \"Slice weights GPU: \";\n    for (inputIndex = 0; inputIndex < _slice_weight_gpu.size(); inputIndex++)\n      cout << _slice_weight_gpu[inputIndex] << \" \";\n    cout << endl;\n  }\n\n\n  //Calulation of slice-wise robust statistics parameters.\n  //This is theoretically M-step,\n  //but we want to use latest estimate of slice potentials\n  //to update the parameters\n\n  //Calculate means of the inlier and outlier potentials\n  double sum = 0, den = 0, sum2 = 0, den2 = 0, maxs = 0, mins = 1;\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n    if (slice_potential_gpu[inputIndex] >= 0) {\n    //calculate means\n    sum += slice_potential_gpu[inputIndex] * _slice_weight_gpu[inputIndex];\n    den += _slice_weight_gpu[inputIndex];\n    sum2 += slice_potential_gpu[inputIndex] * (1.0 - _slice_weight_gpu[inputIndex]);\n    den2 += (1.0 - _slice_weight_gpu[inputIndex]);\n\n    //calculate min and max of potentials in case means need to be initalized\n    if (slice_potential_gpu[inputIndex] > maxs)\n      maxs = slice_potential_gpu[inputIndex];\n    if (slice_potential_gpu[inputIndex] < mins)\n      mins = slice_potential_gpu[inputIndex];\n    }\n\n  if (den > 0)\n    _mean_s_gpu = (float)(sum / den);\n  else\n    _mean_s_gpu = (float)mins;\n\n  if (den2 > 0)\n    _mean_s2_gpu = (float)(sum2 / den2);\n  else\n    _mean_s2_gpu = (float)((maxs + _mean_s_gpu) / 2.0);\n\n  //Calculate the variances of the potentials\n  sum = 0;\n  den = 0;\n  sum2 = 0;\n  den2 = 0;\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n    if (slice_potential_gpu[inputIndex] >= 0) {\n    sum += (slice_potential_gpu[inputIndex] - _mean_s_gpu) * (slice_potential_gpu[inputIndex] - _mean_s_gpu)\n      * _slice_weight_gpu[inputIndex];\n    den += _slice_weight_gpu[inputIndex];\n\n    sum2 += (slice_potential_gpu[inputIndex] - _mean_s2_gpu) * (slice_potential_gpu[inputIndex] - _mean_s2_gpu)\n      * (1 - _slice_weight_gpu[inputIndex]);\n    den2 += (1 - _slice_weight_gpu[inputIndex]);\n\n    }\n\n  //_sigma_s\n  if ((sum > 0) && (den > 0)) {\n    _sigma_s_gpu = (float)(sum / den);\n    //do not allow too small sigma\n    if (_sigma_s_gpu < _step * _step / 6.28)\n      _sigma_s_gpu = (float)(_step * _step / 6.28);\n  }\n  else {\n    _sigma_s_gpu = 0.025f;\n    if (_debug) {\n      if (sum <= 0)\n        cout << \"All slices are equal. \";\n      if (den < 0) //this should not happen\n        cout << \"All slices are outliers. \";\n      cout << \"Setting sigma to \" << sqrt(_sigma_s_gpu) << endl;\n    }\n  }\n\n  //sigma_s2\n  if ((sum2 > 0) && (den2 > 0)) {\n    _sigma_s2_gpu = (float)(sum2 / den2);\n    //do not allow too small sigma\n    if (_sigma_s2_gpu < _step * _step / 6.28)\n      _sigma_s2_gpu = (float)(_step * _step / 6.28);\n  }\n  else {\n    _sigma_s2_gpu = (_mean_s2_gpu - _mean_s_gpu) * (_mean_s2_gpu - _mean_s_gpu) / 4;\n    //do not allow too small sigma\n    if (_sigma_s2_gpu < _step * _step / 6.28)\n      _sigma_s2_gpu = (float)(_step * _step / 6.28);\n\n    if (_debug) {\n      if (sum2 <= 0)\n        cout << \"All slices are equal. \";\n      if (den2 <= 0)\n        cout << \"All slices inliers. \";\n      cout << \"Setting sigma_s2 to \" << sqrt(_sigma_s2_gpu) << endl;\n    }\n  }\n\n  //Calculate slice weights\n  double gs1, gs2;\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    //Slice does not have any voxels in volumetric ROI\n    if (slice_potential_gpu[inputIndex] == -1) {\n      _slice_weight_gpu[inputIndex] = 0;\n      continue;\n    }\n\n    //All slices are outliers or the means are not valid\n    if ((den <= 0) || (_mean_s2_gpu <= _mean_s_gpu)) {\n      _slice_weight_gpu[inputIndex] = 1;\n      continue;\n    }\n\n    //likelihood for inliers\n    if (slice_potential_gpu[inputIndex] < _mean_s2_gpu)\n      gs1 = G(slice_potential_gpu[inputIndex] - _mean_s_gpu, _sigma_s_gpu);\n    else\n      gs1 = 0;\n\n    //likelihood for outliers\n    if (slice_potential_gpu[inputIndex] > _mean_s_gpu)\n      gs2 = G(slice_potential_gpu[inputIndex] - _mean_s2_gpu, _sigma_s2_gpu);\n    else\n      gs2 = 0;\n\n    //calculate slice weight\n    double likelihood = gs1 * _mix_s_gpu + gs2 * (1 - _mix_s_gpu);\n    if (likelihood > 0)\n      _slice_weight_gpu[inputIndex] = (float)(gs1 * _mix_s_gpu / likelihood);\n    else {\n      if (slice_potential_gpu[inputIndex] <= _mean_s_gpu)\n        _slice_weight_gpu[inputIndex] = 1;\n      if (slice_potential_gpu[inputIndex] >= _mean_s2_gpu)\n        _slice_weight_gpu[inputIndex] = 0;\n      if ((slice_potential_gpu[inputIndex] < _mean_s2_gpu) && (slice_potential_gpu[inputIndex] > _mean_s_gpu)) //should not happen\n        _slice_weight_gpu[inputIndex] = 1;\n    }\n  }\n\n  //Update _mix_s this should also be part of MStep\n  sum = 0;\n  int num = 0;\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n    if (slice_potential_gpu[inputIndex] >= 0) {\n    sum += _slice_weight_gpu[inputIndex];\n    num++;\n    }\n\n  if (num > 0)\n    _mix_s_gpu = (float)(sum / num);\n  else {\n    cout << \"All slices are outliers. Setting _mix_s to 0.9.\" << endl;\n    _mix_s_gpu = 0.9f;\n  }\n\n  if (_debug || _debugGPU) {\n    cout << setprecision(3);\n    cout << \"Slice robust statistics parameters GPU: \";\n    cout << \"means: \" << _mean_s_gpu << \" \" << _mean_s2_gpu << \"  \";\n    cout << \"sigmas: \" << sqrt(_sigma_s_gpu) << \" \" << sqrt(_sigma_s2_gpu) << \"  \";\n    cout << \"proportions: \" << _mix_s_gpu << \" \" << 1 - _mix_s_gpu << endl;\n    cout << \"Slice weights GPU: \";\n    for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n      cout << _slice_weight_gpu[inputIndex] << \" \";\n    /*cout << \"Slice potential: \";\n    for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n    cout << slice_potential[inputIndex] << \" \";*/\n    cout << endl;\n  }\n\n  //TODO only slice weight\n  reconstructionGPU->UpdateSliceWeights(_slice_weight_gpu);\n\n}\n\nvoid irtkReconstruction::EStep()\n{\n  //EStep performs calculation of voxel-wise and slice-wise posteriors (weights)\n  if (_debug)\n    cout << \"EStep: \" << endl;\n\n  unsigned int inputIndex;\n  irtkRealImage slice, w, b, sim;\n  int num = 0;\n  vector<double> slice_potential_cpu(_slices.size(), 0);\n  //std::cout << \"num Estp CPU: \";\n  ParallelEStep parallelEStep(this, slice_potential_cpu);\n  parallelEStep();\n\n  if(_debugGPU)\n  {\n    _weights[40].Write(\"testweightCPU.nii\");\n}\n\n  //To force-exclude slices predefined by a user, set their potentials to -1\n  for (unsigned int i = 0; i < _force_excluded.size(); i++)\n    slice_potential_cpu[_force_excluded[i]] = -1;\n\n  //exclude slices identified as having small overlap with ROI, set their potentials to -1\n  for (unsigned int i = 0; i < _small_slices.size(); i++)\n    slice_potential_cpu[_small_slices[i]] = -1;\n\n  //these are unrealistic scales pointing at misregistration - exclude the corresponding slices\n  for (inputIndex = 0; inputIndex < slice_potential_cpu.size(); inputIndex++)\n    if ((_scale_cpu[inputIndex] < 0.2) || (_scale_cpu[inputIndex]>5)) {\n    slice_potential_cpu[inputIndex] = -1;\n    }\n\n  // exclude unrealistic transformations\n  /*\n  int current_stack = 0;\n  int nb_stacks = _stack_index[_stack_index.size()-1];\n  double tx,ty,tz,rx,ry,rz, nb;\n  for ( int i = 0; i < nb_stacks; i++ ) {\n  tx = 0;\n  ty = 0;\n  tz = 0;\n  rx = 0;\n  ry = 0;\n  rz = 0;\n  nb = 0;\n  for ( int j = 0; j < _slices.size(); j++ ) {\n  if ( _stack_index[j] != i )\n  continue;\n  if ( slice_potential[j] == -1 )\n  continue;\n  tx += _transformations[j].GetTranslationX();\n  ty += _transformations[j].GetTranslationY();\n  tz += _transformations[j].GetTranslationZ();\n  rx += _transformations[j].GetRotationX();\n  ry += _transformations[j].GetRotationY();\n  rz += _transformations[j].GetRotationZ();\n  nb++;\n  }\n  tx /= nb;\n  ty /= nb;\n  tz /= nb;\n  rx /= nb;\n  ry /= nb;\n  rz /= nb;\n  for ( int j = 0; j < _slices.size(); j++ ) {\n  if ( _stack_index[j] != i )\n  continue;\n  if ( slice_potential[j] == -1 )\n  continue;\n  if ( abs( tx - _transformations[j].GetTranslationX() ) > 20\n  || abs( ty - _transformations[j].GetTranslationY() ) > 20\n  || abs( tz - _transformations[j].GetTranslationZ() ) > 20\n  || abs( rx - _transformations[j].GetRotationX() ) > 5\n  || abs( ry - _transformations[j].GetRotationY() ) > 5\n  || abs( rz - _transformations[j].GetRotationZ() ) > 5 )\n  slice_potential[j] = -1;\n  }\n  }\n  */\n  if (_debug || _debugGPU) {\n    cout << setprecision(4);\n    cout << endl << \"Slice potentials CPU: \";\n    for (inputIndex = 0; inputIndex < slice_potential_cpu.size(); inputIndex++)\n      cout << slice_potential_cpu[inputIndex] << \" \";\n    cout << endl << \"Slice weights CPU: \";\n    for (inputIndex = 0; inputIndex < _slice_weight_cpu.size(); inputIndex++)\n      cout << _slice_weight_cpu[inputIndex] << \" \";\n    cout << endl;\n  }\n\n\n  //Calulation of slice-wise robust statistics parameters.\n  //This is theoretically M-step,\n  //but we want to use latest estimate of slice potentials\n  //to update the parameters\n\n  //Calculate means of the inlier and outlier potentials\n  double sum = 0, den = 0, sum2 = 0, den2 = 0, maxs = 0, mins = 1;\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n    if (slice_potential_cpu[inputIndex] >= 0) {\n    //calculate means\n    sum += slice_potential_cpu[inputIndex] * _slice_weight_cpu[inputIndex];\n    den += _slice_weight_cpu[inputIndex];\n    sum2 += slice_potential_cpu[inputIndex] * (1 - _slice_weight_cpu[inputIndex]);\n    den2 += (1 - _slice_weight_cpu[inputIndex]);\n\n    //calculate min and max of potentials in case means need to be initalized\n    if (slice_potential_cpu[inputIndex] > maxs)\n      maxs = slice_potential_cpu[inputIndex];\n    if (slice_potential_cpu[inputIndex] < mins)\n      mins = slice_potential_cpu[inputIndex];\n    }\n\n  if (den > 0)\n    _mean_s_cpu = sum / den;\n  else\n    _mean_s_cpu = mins;\n\n  if (den2 > 0)\n    _mean_s2_cpu = sum2 / den2;\n  else\n    _mean_s2_cpu = (maxs + _mean_s_cpu) / 2;\n\n  //Calculate the variances of the potentials\n  sum = 0;\n  den = 0;\n  sum2 = 0;\n  den2 = 0;\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n    if (slice_potential_cpu[inputIndex] >= 0) {\n    sum += (slice_potential_cpu[inputIndex] - _mean_s_cpu) * (slice_potential_cpu[inputIndex] - _mean_s_cpu)\n      * _slice_weight_cpu[inputIndex];\n    den += _slice_weight_cpu[inputIndex];\n\n    sum2 += (slice_potential_cpu[inputIndex] - _mean_s2_cpu) * (slice_potential_cpu[inputIndex] - _mean_s2_cpu)\n      * (1 - _slice_weight_cpu[inputIndex]);\n    den2 += (1 - _slice_weight_cpu[inputIndex]);\n\n    }\n\n  //_sigma_s\n  if ((sum > 0) && (den > 0)) {\n    _sigma_s_cpu = sum / den;\n    //do not allow too small sigma\n    if (_sigma_s_cpu < _step * _step / 6.28)\n      _sigma_s_cpu = _step * _step / 6.28;\n  }\n  else {\n    _sigma_s_cpu = 0.025;\n    if (_debug) {\n      if (sum <= 0)\n        cout << \"All slices are equal. \";\n      if (den < 0) //this should not happen\n        cout << \"All slices are outliers. \";\n      cout << \"Setting sigma to \" << sqrt(_sigma_s_cpu) << endl;\n    }\n  }\n\n  //sigma_s2\n  if ((sum2 > 0) && (den2 > 0)) {\n    _sigma_s2_cpu = sum2 / den2;\n    //do not allow too small sigma\n    if (_sigma_s2_cpu < _step * _step / 6.28)\n      _sigma_s2_cpu = _step * _step / 6.28;\n  }\n  else {\n    _sigma_s2_cpu = (_mean_s2_cpu - _mean_s_cpu) * (_mean_s2_cpu - _mean_s_cpu) / 4;\n    //do not allow too small sigma\n    if (_sigma_s2_cpu < _step * _step / 6.28)\n      _sigma_s2_cpu = _step * _step / 6.28;\n\n    if (_debug) {\n      if (sum2 <= 0)\n        cout << \"All slices are equal. \";\n      if (den2 <= 0)\n        cout << \"All slices inliers. \";\n      cout << \"Setting sigma_s2 to \" << sqrt(_sigma_s2_cpu) << endl;\n    }\n  }\n\n  //Calculate slice weights\n  double gs1, gs2;\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    //Slice does not have any voxels in volumetric ROI\n    if (slice_potential_cpu[inputIndex] == -1) {\n      _slice_weight_cpu[inputIndex] = 0;\n      continue;\n    }\n\n    //All slices are outliers or the means are not valid\n    if ((den <= 0) || (_mean_s2_cpu <= _mean_s_cpu)) {\n      _slice_weight_cpu[inputIndex] = 1;\n      continue;\n    }\n\n    //likelihood for inliers\n    if (slice_potential_cpu[inputIndex] < _mean_s2_cpu)\n      gs1 = G(slice_potential_cpu[inputIndex] - _mean_s_cpu, _sigma_s_cpu);\n    else\n      gs1 = 0;\n\n    //likelihood for outliers\n    if (slice_potential_cpu[inputIndex] > _mean_s_cpu)\n      gs2 = G(slice_potential_cpu[inputIndex] - _mean_s2_cpu, _sigma_s2_cpu);\n    else\n      gs2 = 0;\n\n    //calculate slice weight\n    double likelihood = gs1 * _mix_s_cpu + gs2 * (1 - _mix_s_cpu);\n    if (likelihood > 0)\n      _slice_weight_cpu[inputIndex] = gs1 * _mix_s_cpu / likelihood;\n    else {\n      if (slice_potential_cpu[inputIndex] <= _mean_s_cpu)\n        _slice_weight_cpu[inputIndex] = 1;\n      if (slice_potential_cpu[inputIndex] >= _mean_s2_cpu)\n        _slice_weight_cpu[inputIndex] = 0;\n      if ((slice_potential_cpu[inputIndex] < _mean_s2_cpu) && (slice_potential_cpu[inputIndex] > _mean_s_cpu)) //should not happen\n        _slice_weight_cpu[inputIndex] = 1;\n    }\n  }\n\n  //Update _mix_s this should also be part of MStep\n  sum = 0;\n  num = 0;\n  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n    if (slice_potential_cpu[inputIndex] >= 0) {\n    sum += _slice_weight_cpu[inputIndex];\n    num++;\n    }\n\n  if (num > 0)\n    _mix_s_cpu = sum / num;\n  else {\n    cout << \"All slices are outliers. Setting _mix_s to 0.9.\" << endl;\n    _mix_s_cpu = 0.9;\n  }\n\n  if (_debug || _debugGPU) {\n    cout << setprecision(3);\n    cout << \"Slice robust statistics parameters CPU: \";\n    cout << \"means: \" << _mean_s_cpu << \" \" << _mean_s2_cpu << \"  \";\n    cout << \"sigmas: \" << sqrt(_sigma_s_cpu) << \" \" << sqrt(_sigma_s2_cpu) << \"  \";\n    cout << \"proportions: \" << _mix_s_cpu << \" \" << 1 - _mix_s_cpu << endl;\n    cout << \"Slice weights  CPU: \";\n    for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n      cout << _slice_weight_cpu[inputIndex] << \" \";\n    /*cout << \"Slice potential: \";\n    for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n    cout << slice_potential[inputIndex] << \" \";*/\n    cout << endl;\n  }\n\n}\n\nclass ParallelScale {\n  irtkReconstruction *reconstructor;\n\npublic:\n  ParallelScale(irtkReconstruction *_reconstructor) :\n    reconstructor(_reconstructor)\n  { }\n\n  void operator() (const blocked_range<size_t> &r) const {\n    for (size_t inputIndex = r.begin(); inputIndex != r.end(); ++inputIndex) {\n\n      // alias the current slice\n      irtkRealImage& slice = reconstructor->_slices[inputIndex];\n\n      //alias the current weight image\n      irtkRealImage& w = reconstructor->_weights[inputIndex];\n\n      //alias the current bias image\n      irtkRealImage& b = reconstructor->_bias[inputIndex];\n\n      //initialise calculation of scale\n      double scalenum = 0;\n      double scaleden = 0;\n\n      for (int i = 0; i < slice.GetX(); i++)\n        for (int j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {\n          //scale - intensity matching\n          double eb = exp(-b(i, j, 0));\n          scalenum += w(i, j, 0) * slice(i, j, 0) * eb * reconstructor->_simulated_slices[inputIndex](i, j, 0);\n          scaleden += w(i, j, 0) * slice(i, j, 0) * eb * slice(i, j, 0) * eb;\n        }\n          }\n\n      //calculate scale for this slice\n      if (scaleden > 0)\n        reconstructor->_scale_cpu[inputIndex] = scalenum / scaleden;\n      else\n        reconstructor->_scale_cpu[inputIndex] = 1;\n\n    } //end of loop for a slice inputIndex  \n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n\n};\n\nvoid irtkReconstruction::ScaleGPU()\n{\n  if (_debug)\n    cout << \"Scale\" << endl;\n\n  reconstructionGPU->CalculateScaleVector(_scale_gpu);\n  //_scale_gpu = reconstructionGPU->h_scales;\n // if (_debug || _debugGPU) {\n    cout << setprecision(3);\n    cout << \"Slice scale GPU= \";\n    for (unsigned int inputIndex = 0; inputIndex < _slices.size(); ++inputIndex)\n      cout << inputIndex << \":\" << _scale_gpu[inputIndex] << \" \";\n    cout << endl;\n  //}\n}\n\nvoid irtkReconstruction::Scale()\n{\n  if (_debug)\n    cout << \"Scale\" << endl;\n\n  ParallelScale parallelScale(this);\n  parallelScale();\n\n  //Normalise scales by setting geometric mean to 1\n  // now abandoned\n  //if (!_global_bias_correction)\n  //{\n  //  double product = 1;\n  //  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n  //      product *= _scale[inputIndex];\n  //  product = pow(product, 1.0 / _slices.size());\n  //  for (inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n  //      _scale[inputIndex] /= product;\n  //}\n\n  if (_debug || _debugGPU) {\n    cout << setprecision(3);\n    cout << \"Slice scale CPU= \";\n    for (unsigned int inputIndex = 0; inputIndex < _slices.size(); ++inputIndex)\n      cout << inputIndex << \":\" << _scale_cpu[inputIndex] << \" \";\n    cout << endl;\n  }\n}\n\nclass ParallelBias {\n  irtkReconstruction* reconstructor;\n\npublic:\n\n  void operator()(const blocked_range<size_t>& r) const {\n    for (size_t inputIndex = r.begin(); inputIndex < r.end(); ++inputIndex) {\n      // read the current slice\n      irtkRealImage slice = reconstructor->_slices[inputIndex];\n\n      //alias the current weight image\n      irtkRealImage& w = reconstructor->_weights[inputIndex];\n\n      //alias the current bias image\n      irtkRealImage b = reconstructor->_bias[inputIndex];\n\n      //identify scale factor\n      double scale = reconstructor->_scale_cpu[inputIndex];\n\n      //prepare weight image for bias field\n      irtkRealImage wb = w;\n\n      //simulated slice\n      // irtkRealImage sim;\n      // sim.Initialize( slice.GetImageAttributes() );\n      // sim = 0;\n      irtkRealImage wresidual(slice.GetImageAttributes());\n      wresidual = 0;\n\n      for (int i = 0; i < slice.GetX(); i++)\n        for (int j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {\n          //bias-correct and scale current slice\n          double eb = exp(-b(i, j, 0));\n          slice(i, j, 0) *= (eb * scale);\n\n          //calculate weight image\n          wb(i, j, 0) = w(i, j, 0) * slice(i, j, 0);\n\n          //calculate weighted residual image\n          //make sure it is far from zero to avoid numerical instability\n          //if ((sim(i,j,0)>_low_intensity_cutoff*_max_intensity)&&(slice(i,j,0)>_low_intensity_cutoff*_max_intensity))\n          if ((reconstructor->_simulated_slices[inputIndex](i, j, 0) > 1) && (slice(i, j, 0) > 1)) {\n            wresidual(i, j, 0) = log(slice(i, j, 0) / reconstructor->_simulated_slices[inputIndex](i, j, 0)) * wb(i, j, 0);\n          }\n        }\n        else {\n          //do not take into account this voxel when calculating bias field\n          wresidual(i, j, 0) = 0;\n          wb(i, j, 0) = 0;\n        }\n          }\n\n      //calculate bias field for this slice\n      irtkGaussianBlurring<irtkRealPixel> gb(reconstructor->_sigma_bias);\n      //smooth weighted residual\n      gb.SetInput(&wresidual);\n      gb.SetOutput(&wresidual);\n      gb.Run();\n\n      //smooth weight image\n      gb.SetInput(&wb);\n      gb.SetOutput(&wb);\n      gb.Run();\n\n      //update bias field\n      double sum = 0;\n      double num = 0;\n      for (int i = 0; i < slice.GetX(); i++)\n        for (int j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        if (wb(i, j, 0) > 0)\n          b(i, j, 0) += wresidual(i, j, 0) / wb(i, j, 0);\n        sum += b(i, j, 0);\n        num++;\n          }\n\n      //normalize bias field to have zero mean\n      if (!reconstructor->_global_bias_correction) {\n        double mean = 0;\n        if (num > 0)\n          mean = sum / num;\n        for (int i = 0; i < slice.GetX(); i++)\n          for (int j = 0; j < slice.GetY(); j++)\n            if ((slice(i, j, 0) != -1) && (num > 0)) {\n          b(i, j, 0) -= mean;\n            }\n      }\n\n      reconstructor->_bias[inputIndex] = b;\n    }\n  }\n\n  ParallelBias(irtkReconstruction *reconstructor) :\n    reconstructor(reconstructor)\n  { }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n\n};\n\nvoid irtkReconstruction::BiasGPU()\n{\n\n  if (_debug)\n    cout << \"Correcting bias ...\";\n\n  if (_global_bias_correction)\n    printf(\"_global_bias_correction is not yet fully implemented in CUDA\\n\");\n\n  reconstructionGPU->CorrectBias(_sigma_bias, _global_bias_correction); //assuming globally constant pixel size\n  if(_debugGPU)\n  {\n    irtkGenericImage<float> bimg(reconstructionGPU->v_bias.size.x, reconstructionGPU->v_bias.size.y, reconstructionGPU->v_bias.size.z);\n    reconstructionGPU->debugBias(bimg.GetPointerToVoxels());\n    bimg.Write(\"biasFieldGPU.nii\");\n  }\n\n  if (_debug)\n    cout << \"done. \" << endl;\n}\n\n\nvoid irtkReconstruction::Bias()\n{\n  if (_debug)\n    cout << \"Correcting bias ...\";\n\n  ParallelBias parallelBias(this);\n  parallelBias();\n\n  _bias[79].Write(\"biasField79CPU.nii\");\n\n  if (_debug)\n    cout << \"done. \" << endl;\n}\n\nclass ParallelSuperresolution {\n  \n  irtkReconstruction* reconstructor;\npublic:\n  irtkRealImage confidence_map;\n  irtkRealImage addon;\n\n  void operator()(const blocked_range<size_t>& r) {\n    for (size_t inputIndex = r.begin(); inputIndex < r.end(); ++inputIndex) {\n      // read the current slice\n      irtkRealImage slice = reconstructor->_slices[inputIndex];\n\n      //read the current weight image\n      irtkRealImage& w = reconstructor->_weights[inputIndex];\n\n      //read the current bias image\n      irtkRealImage& b = reconstructor->_bias[inputIndex];\n\n      //identify scale factor\n      double scale = reconstructor->_scale_cpu[inputIndex];\n\n      //Update reconstructed volume using current slice\n\n      //Distribute error to the volume\n      POINT3D p;\n      for (int i = 0; i < slice.GetX(); i++)\n        for (int j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        //bias correct and scale the slice\n        slice(i, j, 0) *= exp(-b(i, j, 0)) * scale;\n\n        if (reconstructor->_simulated_slices[inputIndex](i, j, 0) > 0)\n          slice(i, j, 0) -= reconstructor->_simulated_slices[inputIndex](i, j, 0);\n        else\n          slice(i, j, 0) = 0;\n\n        size_t n = reconstructor->_volcoeffs[inputIndex][i][j].size();\n        for (int k = 0; k < n; k++) {\n          p = reconstructor->_volcoeffs[inputIndex][i][j][k];\n          addon(p.x, p.y, p.z) += p.value * slice(i, j, 0) * w(i, j, 0) * reconstructor->_slice_weight_cpu[inputIndex];\n          confidence_map(p.x, p.y, p.z) += p.value * w(i, j, 0) * reconstructor->_slice_weight_cpu[inputIndex];\n        }\n          }\n    } //end of loop for a slice inputIndex\n  }\n\n  ParallelSuperresolution(ParallelSuperresolution& x, split) :\n    reconstructor(x.reconstructor)\n  {\n    //Clear addon\n    addon.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    addon = 0;\n\n    //Clear confidence map\n    confidence_map.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    confidence_map = 0;\n  }\n\n  void join(const ParallelSuperresolution& y) {\n    addon += y.addon;\n    confidence_map += y.confidence_map;\n  }\n\n  ParallelSuperresolution(irtkReconstruction *reconstructor) :\n    reconstructor(reconstructor)\n  {\n    //Clear addon\n    addon.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    addon = 0;\n\n    //Clear confidence map\n    confidence_map.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    confidence_map = 0;\n  }\n\n  // execute\n  void operator() () {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n};\n\nvoid irtkReconstruction::SuperresolutionGPU(int iter)\n{\n  if (_debug)\n    cout << \"Superresolution \" << iter << endl;\n\n  int i, j, k;\n  irtkRealImage addon, original;\n  //Remember current reconstruction for edge-preserving smoothing\n  original = _reconstructed;\n\n  reconstructionGPU->Superresolution(iter, _slice_weight_gpu, _adaptive, _alpha, _min_intensity, _max_intensity, _delta,\n    _lambda, _global_bias_correction, _sigma_bias, _low_intensity_cutoff); //assuming isotrop constant voxel size\n\n  //TODO debug confidence map and addon\n  if(_debugGPU)\n  {\n    char buffer[256];\n    irtkGenericImage<float> addonDB;\n    addonDB.Initialize(_reconstructed.GetImageAttributes());\n    reconstructionGPU->debugAddon(addonDB.GetPointerToVoxels());\n    sprintf(buffer, \"addonGPU%i.nii\", iter - 1);\n    addonDB.Write(buffer);\n    irtkGenericImage<float> cmap;\n    cmap.Initialize(_reconstructed.GetImageAttributes());\n    reconstructionGPU->debugConfidenceMap(cmap.GetPointerToVoxels());\n    sprintf(buffer, \"cmapGPU%i.nii\", iter - 1);\n    cmap.Write(buffer);\n}\n\n}\n\nvoid irtkReconstruction::Superresolution(int iter)\n{\n  if (_debug)\n    cout << \"Superresolution \" << iter << endl;\n\n  int i, j, k;\n  irtkRealImage addon, original;\n\n  //Remember current reconstruction for edge-preserving smoothing\n  original = _reconstructed;\n\n  ParallelSuperresolution parallelSuperresolution(this);\n  parallelSuperresolution();\n  addon = parallelSuperresolution.addon;\n  _confidence_map = parallelSuperresolution.confidence_map;\n  //_confidence4mask = _confidence_map;\n\n  if (_debug) {\n    char buffer[256];\n    sprintf(buffer, \"confidence-map%i.nii.gz\", iter);\n    _confidence_map.Write(buffer);\n    sprintf(buffer, \"addon%i.nii.gz\", iter);\n    addon.Write(buffer);\n  }\n\n  if (!_adaptive)\n    for (i = 0; i < addon.GetX(); i++)\n      for (j = 0; j < addon.GetY(); j++)\n        for (k = 0; k < addon.GetZ(); k++)\n          if (_confidence_map(i, j, k) > 0) {\n    // ISSUES if _confidence_map(i, j, k) is too small leading\n    // to bright pixels\n    addon(i, j, k) /= _confidence_map(i, j, k);\n    //this is to revert to normal (non-adaptive) regularisation\n    _confidence_map(i, j, k) = 1;\n          }\n\n  _reconstructed += addon * _alpha; //_average_volume_weight;\n\n  //bound the intensities\n  for (i = 0; i < _reconstructed.GetX(); i++)\n    for (j = 0; j < _reconstructed.GetY(); j++)\n      for (k = 0; k < _reconstructed.GetZ(); k++) {\n    if (_reconstructed(i, j, k) < _min_intensity * 0.9)\n      _reconstructed(i, j, k) = _min_intensity * 0.9;\n    if (_reconstructed(i, j, k) > _max_intensity * 1.1)\n      _reconstructed(i, j, k) = _max_intensity * 1.1;\n      }\n\n  //Smooth the reconstructed image\n  AdaptiveRegularization(iter, original);\n  //Remove the bias in the reconstructed volume compared to previous iteration\n  if (_global_bias_correction)\n    BiasCorrectVolume(original);\n\n  if(_debugGPU)\n  {\n    char buffer[256];\n    sprintf(buffer, \"addonCPU%i.nii\", iter - 1);\n    addon.Write(buffer);\n\n    sprintf(buffer, \"cmapCPU%i.nii\", iter - 1);\n    _confidence_map.Write(buffer);\n}\n}\n\nclass ParallelMStep{\n  irtkReconstruction* reconstructor;\npublic:\n  double sigma;\n  double mix;\n  double num;\n  double min;\n  double max;\n\n  void operator()(const blocked_range<size_t>& r) {\n    for (size_t inputIndex = r.begin(); inputIndex < r.end(); ++inputIndex) {\n      // read the current slice\n      irtkRealImage slice = reconstructor->_slices[inputIndex];\n\n      //alias the current weight image\n      irtkRealImage& w = reconstructor->_weights[inputIndex];\n\n      //alias the current bias image\n      irtkRealImage& b = reconstructor->_bias[inputIndex];\n\n      //identify scale factor\n      double scale = reconstructor->_scale_cpu[inputIndex];\n\n      //calculate error\n      for (int i = 0; i < slice.GetX(); i++)\n        for (int j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        //bias correct and scale the slice\n        slice(i, j, 0) *= exp(-b(i, j, 0)) * scale;\n\n        //otherwise the error has no meaning - it is equal to slice intensity\n        if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {\n\n          slice(i, j, 0) -= reconstructor->_simulated_slices[inputIndex](i, j, 0);\n\n          //sigma and mix\n          double e = slice(i, j, 0);\n          sigma += e * e * w(i, j, 0);\n          mix += w(i, j, 0);\n\n          //_m\n          if (e < min)\n            min = e;\n          if (e > max)\n            max = e;\n\n          num++;\n        }\n          }\n    } //end of loop for a slice inputIndex\n  }\n\n  ParallelMStep(ParallelMStep& x, split) :\n    reconstructor(x.reconstructor)\n  {\n    sigma = 0;\n    mix = 0;\n    num = 0;\n    min = 0;\n    max = 0;\n  }\n\n  void join(const ParallelMStep& y) {\n    if (y.min < min)\n      min = y.min;\n    if (y.max > max)\n      max = y.max;\n\n    sigma += y.sigma;\n    mix += y.mix;\n    num += y.num;\n  }\n\n  ParallelMStep(irtkReconstruction *reconstructor) :\n    reconstructor(reconstructor)\n  {\n    sigma = 0;\n    mix = 0;\n    num = 0;\n    min = voxel_limits<irtkRealPixel>::max();\n    max = voxel_limits<irtkRealPixel>::min();\n  }\n\n  // execute\n  void operator() () {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n};\n\n\nvoid irtkReconstruction::MStepGPU(int iter)\n{\n  reconstructionGPU->MStep(iter, _step, _sigma_gpu, _mix_gpu, _m_gpu);\n  std::cout.precision(10);\n  if (_debug || _debugGPU) {\n    cout << \"Voxel-wise robust statistics parameters GPU: \";\n    cout << \"sigma = \" << sqrt(_sigma_gpu) << \" mix = \" << _mix_gpu << \" \";\n    cout << \" m = \" << _m_gpu << endl;\n  }\n\n}\n\nvoid irtkReconstruction::MStep(int iter)\n{\n  if (_debug)\n    cout << \"MStep\" << endl;\n\n  ParallelMStep parallelMStep(this);\n  parallelMStep();\n  double sigma = parallelMStep.sigma;\n  double mix = parallelMStep.mix;\n  double num = parallelMStep.num;\n  double min = parallelMStep.min;\n  double max = parallelMStep.max;\n  //printf(\"CPU sigma %f, mix %f, num %f, min_ %f, max_ %f\\n\", sigma, mix, num, min, max);\n  std::cout.precision(6);\n  std::cout << \"CPU sigma \" << sigma << \" mix \" << mix << \" num \" << num << \" min_ \" << min << \" max_ \" << max << std::endl;\n  //Calculate sigma and mix\n  if (mix > 0) {\n    _sigma_cpu = sigma / mix;\n  }\n  else {\n    cerr << \"Something went wrong: sigma=\" << sigma << \" mix=\" << mix << endl;\n    exit(1);\n  }\n  if (_sigma_cpu < _step * _step / 6.28)\n    _sigma_cpu = _step * _step / 6.28;\n  if (iter > 1)\n    _mix_cpu = mix / num;\n\n  //Calculate m\n  _m_cpu = 1 / (max - min);\n\n  if (_debug || _debugGPU) {\n    cout << \"Voxel-wise robust statistics parameters CPU: \";\n    cout << \"sigma = \" << sqrt(_sigma_cpu) << \" mix = \" << _mix_cpu << \" \";\n    cout << \" m = \" << _m_cpu << endl;\n  }\n\n}\n\nclass ParallelAdaptiveRegularization1 {\n  irtkReconstruction *reconstructor;\n  vector<irtkRealImage> &b;\n  vector<double> &factor;\n  irtkRealImage &original;\n\npublic:\n  ParallelAdaptiveRegularization1(irtkReconstruction *_reconstructor,\n    vector<irtkRealImage> &_b,\n    vector<double> &_factor,\n    irtkRealImage &_original) :\n    reconstructor(_reconstructor),\n    b(_b),\n    factor(_factor),\n    original(_original) { }\n\n  void operator() (const blocked_range<size_t> &r) const {\n    int dx = reconstructor->_reconstructed.GetX();\n    int dy = reconstructor->_reconstructed.GetY();\n    int dz = reconstructor->_reconstructed.GetZ();\n    for (size_t i = r.begin(); i != r.end(); ++i) {\n      //b[i] = reconstructor->_reconstructed;\n      // b[i].Initialize( reconstructor->_reconstructed.GetImageAttributes() );\n\n      int x, y, z, xx, yy, zz;\n      double diff;\n      for (x = 0; x < dx; x++)\n        for (y = 0; y < dy; y++)\n          for (z = 0; z < dz; z++) {\n        xx = x + reconstructor->_directions[i][0];\n        yy = y + reconstructor->_directions[i][1];\n        zz = z + reconstructor->_directions[i][2];\n        if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)\n          && (reconstructor->_confidence_map(x, y, z) > 0) && (reconstructor->_confidence_map(xx, yy, zz) > 0)) {\n          diff = (original(xx, yy, zz) - original(x, y, z)) * sqrt(factor[i]) / reconstructor->_delta;\n          b[i](x, y, z) = factor[i] / sqrt(1 + diff * diff);\n\n        }\n        else\n          b[i](x, y, z) = 0;\n          }\n    }\n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, 13),\n      *this);\n    init.terminate();\n  }\n\n};\n\nclass ParallelAdaptiveRegularization2 {\n  irtkReconstruction *reconstructor;\n  vector<irtkRealImage> &b;\n  vector<double> &factor;\n  irtkRealImage &original;\n\npublic:\n  ParallelAdaptiveRegularization2(irtkReconstruction *_reconstructor,\n    vector<irtkRealImage> &_b,\n    vector<double> &_factor,\n    irtkRealImage &_original) :\n    reconstructor(_reconstructor),\n    b(_b),\n    factor(_factor),\n    original(_original) { }\n\n  void operator() (const blocked_range<size_t> &r) const {\n    int dx = reconstructor->_reconstructed.GetX();\n    int dy = reconstructor->_reconstructed.GetY();\n    int dz = reconstructor->_reconstructed.GetZ();\n    for (size_t x = r.begin(); x != r.end(); ++x) {\n      int xx, yy, zz;\n      for (int y = 0; y < dy; y++)\n        for (int z = 0; z < dz; z++) {\n        double val = 0;\n        double valW = 0;\n        double sum = 0;\n        for (int i = 0; i < 13; i++) {\n          xx = x + reconstructor->_directions[i][0];\n          yy = y + reconstructor->_directions[i][1];\n          zz = z + reconstructor->_directions[i][2];\n          if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)) {\n            val += b[i](x, y, z) * original(xx, yy, zz) * reconstructor->_confidence_map(xx, yy, zz);\n            valW += b[i](x, y, z) * reconstructor->_confidence_map(xx, yy, zz);\n            sum += b[i](x, y, z);\n          }\n        }\n\n        for (int i = 0; i < 13; i++) {\n          xx = x - reconstructor->_directions[i][0];\n          yy = y - reconstructor->_directions[i][1];\n          zz = z - reconstructor->_directions[i][2];\n          if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)) {\n            val += b[i](xx, yy, zz) * original(xx, yy, zz) * reconstructor->_confidence_map(xx, yy, zz);\n            valW += b[i](xx, yy, zz) * reconstructor->_confidence_map(xx, yy, zz);\n            sum += b[i](xx, yy, zz);\n          }\n        }\n\n        val -= sum * original(x, y, z) * reconstructor->_confidence_map(x, y, z);\n        valW -= sum * reconstructor->_confidence_map(x, y, z);\n        val = original(x, y, z) * reconstructor->_confidence_map(x, y, z)\n          + reconstructor->_alpha * reconstructor->_lambda / (reconstructor->_delta * reconstructor->_delta) * val;\n        valW = reconstructor->_confidence_map(x, y, z) + reconstructor->_alpha * reconstructor->_lambda / (reconstructor->_delta * reconstructor->_delta) * valW;\n\n        if (valW > 0) {\n          reconstructor->_reconstructed(x, y, z) = val / valW;\n        }\n        else\n          reconstructor->_reconstructed(x, y, z) = 0;\n        }\n\n    }\n  }\n\n  // execute\n  void operator() () const {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_for(blocked_range<size_t>(0, reconstructor->_reconstructed.GetX()),\n      *this);\n    init.terminate();\n  }\n\n};\n\nvoid irtkReconstruction::AdaptiveRegularization(int iter, irtkRealImage& original)\n{\n  if (_debug)\n    cout << \"AdaptiveRegularization\" << endl;\n\n  vector<double> factor(13, 0);\n  for (int i = 0; i < 13; i++) {\n    for (int j = 0; j < 3; j++)\n      factor[i] += fabs(double(_directions[i][j]));\n    factor[i] = 1 / factor[i];\n  }\n\n  vector<irtkRealImage> b;//(13);\n  for (int i = 0; i < 13; i++)\n    b.push_back(_reconstructed);\n\n  ParallelAdaptiveRegularization1 parallelAdaptiveRegularization1(this,\n    b,\n    factor,\n    original);\n  parallelAdaptiveRegularization1();\n\n  irtkRealImage original2 = _reconstructed;\n  ParallelAdaptiveRegularization2 parallelAdaptiveRegularization2(this,\n    b,\n    factor,\n    original2);\n  parallelAdaptiveRegularization2();\n\n  if (_alpha * _lambda / (_delta * _delta) > 0.068) {\n    cerr\n      << \"Warning: regularization might not have smoothing effect! Ensure that alpha*lambda/delta^2 is below 0.068.\"\n      << endl;\n  }\n}\n\nvoid irtkReconstruction::BiasCorrectVolume(irtkRealImage& original)\n{\n  //remove low-frequancy component in the reconstructed image which might have accured due to overfitting of the biasfield\n  irtkRealImage residual = _reconstructed;\n  irtkRealImage weights = _mask;\n\n  //_reconstructed.Write(\"super-notbiascor.nii.gz\");\n\n  //calculate weighted residual\n  irtkRealPixel *pr = residual.GetPointerToVoxels();\n  irtkRealPixel *po = original.GetPointerToVoxels();\n  irtkRealPixel *pw = weights.GetPointerToVoxels();\n  for (int i = 0; i < _reconstructed.GetNumberOfVoxels(); i++) {\n    //second and term to avoid numerical problems\n    if ((*pw == 1) && (*po > _low_intensity_cutoff * _max_intensity)\n      && (*pr > _low_intensity_cutoff * _max_intensity)) {\n      *pr /= *po;\n      *pr = log(*pr);\n    }\n    else {\n      *pw = 0;\n      *pr = 0;\n    }\n    pr++;\n    po++;\n    pw++;\n  }\n  //residual.Write(\"residual.nii.gz\");\n  //blurring needs to be same as for slices\n  irtkGaussianBlurring<irtkRealPixel> gb(_sigma_bias);\n  //blur weigted residual\n  gb.SetInput(&residual);\n  gb.SetOutput(&residual);\n  gb.Run();\n  //blur weight image\n  gb.SetInput(&weights);\n  gb.SetOutput(&weights);\n  gb.Run();\n\n  //calculate the bias field\n  pr = residual.GetPointerToVoxels();\n  pw = weights.GetPointerToVoxels();\n  irtkRealPixel *pm = _mask.GetPointerToVoxels();\n  irtkRealPixel *pi = _reconstructed.GetPointerToVoxels();\n  for (int i = 0; i < _reconstructed.GetNumberOfVoxels(); i++) {\n\n    if (*pm == 1) {\n      //weighted gaussian smoothing\n      *pr /= *pw;\n      //exponential to recover multiplicative bias field\n      *pr = exp(*pr);\n      //bias correct reconstructed\n      *pi /= *pr;\n      //clamp intensities to allowed range\n      if (*pi < _min_intensity * 0.9)\n        *pi = _min_intensity * 0.9;\n      if (*pi > _max_intensity * 1.1)\n        *pi = _max_intensity * 1.1;\n    }\n    else {\n      *pr = 0;\n    }\n    pr++;\n    pw++;\n    pm++;\n    pi++;\n  }\n\n  //residual.Write(\"biasfield.nii.gz\");\n  //_reconstructed.Write(\"super-biascor.nii.gz\");\n\n}\n\nvoid irtkReconstruction::EvaluateGPU(int iter)\n{\n  cout << \"Iteration \" << iter << \": \" << endl;\n\n  cout << \"Included slices GPU: \";\n  int sum = 0;\n  unsigned int i;\n  for (i = 0; i < _slices.size(); i++) {\n    if ((_slice_weight_gpu[i] >= 0.5) && (_slice_inside_gpu[i])) {\n      cout << i << \" \";\n      sum++;\n    }\n  }\n  cout << endl << \"Total GPU: \" << sum << endl;\n\n  cout << \"Excluded slices  GPU: \";\n  sum = 0;\n  for (i = 0; i < _slices.size(); i++) {\n    if ((_slice_weight_gpu[i] < 0.5) && (_slice_inside_gpu[i])) {\n      cout << i << \" \";\n      sum++;\n    }\n  }\n  cout << endl << \"Total GPU: \" << sum << endl;\n\n  cout << \"Outside slices GPU: \";\n  sum = 0;\n  for (i = 0; i < _slices.size(); i++) {\n    if (!(_slice_inside_gpu[i])) {\n      cout << i << \" \";\n      sum++;\n    }\n  }\n  cout << endl << \"Total GPU: \" << sum << endl;\n\n}\n\nvoid irtkReconstruction::Evaluate(int iter)\n{\n  cout << \"Iteration \" << iter << \": \" << endl;\n\n  cout << \"Included slices CPU: \";\n  int sum = 0;\n  unsigned int i;\n  for (i = 0; i < _slices.size(); i++) {\n    if ((_slice_weight_cpu[i] >= 0.5) && (_slice_inside_cpu[i])) {\n      cout << i << \" \";\n      sum++;\n    }\n  }\n  cout << endl << \"Total: \" << sum << endl;\n\n  cout << \"Excluded slices CPU: \";\n  sum = 0;\n  for (i = 0; i < _slices.size(); i++) {\n    if ((_slice_weight_cpu[i] < 0.5) && (_slice_inside_cpu[i])) {\n      cout << i << \" \";\n      sum++;\n    }\n  }\n  cout << endl << \"Total CPU: \" << sum << endl;\n\n  cout << \"Outside slices CPU: \";\n  sum = 0;\n  for (i = 0; i < _slices.size(); i++) {\n    if (!(_slice_inside_cpu[i])) {\n      cout << i << \" \";\n      sum++;\n    }\n  }\n  cout << endl << \"Total CPU: \" << sum << endl;\n\n}\n\n\nclass ParallelNormaliseBias{\n  irtkReconstruction* reconstructor;\npublic:\n  irtkRealImage bias;\n\n  void operator()(const blocked_range<size_t>& r) {\n    for (size_t inputIndex = r.begin(); inputIndex < r.end(); ++inputIndex) {\n\n      if (reconstructor->_debug) {\n        cout << inputIndex << \" \";\n      }\n\n      // alias the current slice\n      irtkRealImage& slice = reconstructor->_slices[inputIndex];\n\n      //read the current bias image\n      irtkRealImage b = reconstructor->_bias[inputIndex];\n\n      //read current scale factor\n      double scale = reconstructor->_scale_cpu[inputIndex];\n\n      irtkRealPixel *pi = slice.GetPointerToVoxels();\n      irtkRealPixel *pb = b.GetPointerToVoxels();\n      for (int i = 0; i<slice.GetNumberOfVoxels(); i++) {\n        if ((*pi>-1) && (scale > 0))\n          *pb -= log(scale);\n        pb++;\n        pi++;\n      }\n\n      //Distribute slice intensities to the volume\n      POINT3D p;\n      for (int i = 0; i < slice.GetX(); i++)\n        for (int j = 0; j < slice.GetY(); j++)\n          if (slice(i, j, 0) != -1) {\n        //number of volume voxels with non-zero coefficients for current slice voxel\n        size_t n = reconstructor->_volcoeffs[inputIndex][i][j].size();\n        //add contribution of current slice voxel to all voxel volumes\n        //to which it contributes\n        for (int k = 0; k < n; k++) {\n          p = reconstructor->_volcoeffs[inputIndex][i][j][k];\n          bias(p.x, p.y, p.z) += p.value * b(i, j, 0);\n        }\n          }\n      //end of loop for a slice inputIndex                \n    }\n  }\n\n  ParallelNormaliseBias(ParallelNormaliseBias& x, split) :\n    reconstructor(x.reconstructor)\n  {\n    bias.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    bias = 0;\n  }\n\n  void join(const ParallelNormaliseBias& y) {\n    bias += y.bias;\n  }\n\n  ParallelNormaliseBias(irtkReconstruction *reconstructor) :\n    reconstructor(reconstructor)\n  {\n    bias.Initialize(reconstructor->_reconstructed.GetImageAttributes());\n    bias = 0;\n  }\n\n  // execute\n  void operator() () {\n    task_scheduler_init init(tbb_no_threads);\n    parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()),\n      *this);\n    init.terminate();\n  }\n};\n\nvoid irtkReconstruction::NormaliseBiasGPU(int iter)\n{\n  reconstructionGPU->NormaliseBias(iter, _sigma_bias);\n\n  if(_debugGPU)\n  {\n    char buffer[256];\n    irtkGenericImage<float> nbias;\n    nbias.Initialize(_reconstructed.GetImageAttributes());\n    reconstructionGPU->debugNormalizeBias(nbias.GetPointerToVoxels());\n    sprintf(buffer, \"nbiasGPU%i.nii\", iter);\n    nbias.Write(buffer);\n\n    irtkGenericImage<float> smask;\n\n    smask.Initialize(_mask.GetImageAttributes());\n    reconstructionGPU->debugSmoothMask(smask.GetPointerToVoxels());\n    sprintf(buffer, \"smaskGPU%i.nii\", iter);\n    smask.Write(buffer);\n}\n}\n\nvoid irtkReconstruction::NormaliseBias(int iter)\n{\n  if (_debug)\n    cout << \"Normalise Bias ... \";\n\n  ParallelNormaliseBias parallelNormaliseBias(this);\n  parallelNormaliseBias();\n  irtkRealImage bias = parallelNormaliseBias.bias;\n\n  // normalize the volume by proportion of contributing slice voxels for each volume voxel\n  bias /= _volume_weights;\n\n  if (_debug)\n    cout << \"done.\" << endl;\n\n  MaskImage(bias, 0);\n  irtkRealImage m = _mask;\n  irtkGaussianBlurring<irtkRealPixel> gb(_sigma_bias);\n  gb.SetInput(&bias);\n  gb.SetOutput(&bias);\n  gb.Run();\n  gb.SetInput(&m);\n  gb.SetOutput(&m);\n  gb.Run();\n  bias /= m;\n\n  if (_debugGPU)\n  {\n    char buffer_[256];\n    sprintf(buffer_, \"smaskCPU%i.nii\", iter);\n    m.Write(buffer_);\n  }\n\n  if (_debug) {\n    char buffer[256];\n    sprintf(buffer, \"averagebias%i.nii.gz\", iter);\n    bias.Write(buffer);\n  }\n\n  irtkRealPixel *pi, *pb;\n  pi = _reconstructed.GetPointerToVoxels();\n  pb = bias.GetPointerToVoxels();\n  for (int i = 0; i < _reconstructed.GetNumberOfVoxels(); i++) {\n    if (*pi != -1)\n      *pi /= exp(-(*pb));\n    pi++;\n    pb++;\n  }\n  if (_debugGPU)\n  {\n    char buffer[256];\n    sprintf(buffer, \"nbiasCPU%i.nii\", iter);\n    bias.Write(buffer);\n  }\n}\n\n/* Set/Get/Save operations */\n\nvoid irtkReconstruction::ReadTransformation(char* folder)\n{\n  size_t n = _slices.size();\n  char name[256];\n  char path[256];\n  irtkTransformation *transformation;\n  irtkRigidTransformation *rigidTransf;\n\n  if (n == 0) {\n    cerr << \"Please create slices before reading transformations!\" << endl;\n    exit(1);\n  }\n  cout << \"Reading transformations:\" << endl;\n\n  _transformations.clear();\n  _transformations_gpu.clear();\n  for (int i = 0; i < n; i++) {\n    if (folder != NULL) {\n      sprintf(name, \"/transformation%i.dof\", i);\n      strcpy(path, folder);\n      strcat(path, name);\n    }\n    else {\n      sprintf(path, \"transformation%i.dof\", i);\n    }\n    transformation = irtkTransformation::New(path);\n    rigidTransf = dynamic_cast<irtkRigidTransformation*>(transformation);\n    _transformations.push_back(*rigidTransf);\n    _transformations_gpu.push_back(*rigidTransf);\n    delete transformation;\n    cout << path << endl;\n  }\n}\n\nvoid irtkReconstruction::replaceSlices(string folder)\n{\n  //replaces slices with already transformed slices\n  //renders every stack operation before useless -- TODO \n\n  //stack Id and transformations are preserved\n  //The slices have to be in the correct order in the folder!\n\n  //get file list from boost\n  path p(folder);\n  if (exists(p))\n  {\n    vector<path> files;\n    copy(directory_iterator(p), directory_iterator(), back_inserter(files));\n\n    vector<irtkRealImage> newSlices;\n    vector<double> thickness;\n    vector<int> stackId;\n    vector<irtkRigidTransformation> transforms;\n\n    //TODO ITK IRTK orientation mismatch?\n    std::cout << \"replacing every slice!!! \" << std::endl;\n    for (int i = 0; i < files.size()/*files.size()*/; i++)\n    {\n      //std::cout << files[i] << std::endl;\n      irtkRealImage newSlice;\n      newSlice.Read(files[i].string().c_str());\n      //newSlice.Write(files[i].string().c_str());\n      //newSlice.Read(files[i].string().c_str());\n      //double axis[3];\n      /*newSlice.GetOrientation(&axis[0], &axis[1], &axis[2]);\n      axis[0] *= -1;\n      axis[1] *= -1;\n      axis[2] *= -1;\n      newSlice.PutOrientation(&axis[0], &axis[1], &axis[2]);*/\n\n      newSlices.push_back(newSlice);\n      stackId.push_back(0); //TODO\n\n      thickness.push_back(4.0);\n      irtkTransformation *transformation = new irtkRigidTransformation;\n      irtkRigidTransformation *rigidTransf = dynamic_cast<irtkRigidTransformation*> (transformation);\n      // rigidTransf->Print();\n      transforms.push_back(*rigidTransf);\n      delete rigidTransf;\n    }\n\n    SetSlicesAndTransformations(newSlices, transforms, stackId, thickness);\n\n  }\n  else\n  {\n    cout << p << \" does not exist\\n\";\n  }\n\n}\n\nvoid irtkReconstruction::transformManualMaskwithPSF(irtkRealImage manualMask, irtkGenericImage<float>* transformedManualMask)\n{\n\n  irtkGenericImage<float> padMask(reqVDims.x, reqVDims.y, manualMask.GetZ());\n  //this might crash if called before slices have been generated\n  irtkImageAttributes sattr = _slices[0].GetImageAttributes();\n\n  float* ptr = padMask.GetPointerToVoxels();\n  irtkImageAttributes attr = manualMask.GetImageAttributes();\n\n  for (int z = 0; z < attr._z; z++) {\n    irtkRealImage maskslice = manualMask.GetRegion(0, 0, z, attr._x, attr._y, z + 1);\n    maskslice.PutPixelSize(attr._dx, attr._dy, sattr._dz);\n\n    for (int y = 0; y < maskslice.GetY(); y++)\n    {\n      for (int x = 0; x < maskslice.GetX(); x++)\n      {\n        padMask(x, y, z) = (float)(maskslice(x, y, 0));\n      }\n      ptr += padMask.GetX();\n    }\n    ptr += abs(padMask.GetY() - maskslice.GetY())*padMask.GetX();\n  }\n\n  reconstructionGPU->transformManualMaskGPU(padMask.GetPointerToVoxels(),padMask.GetZ(),make_uint2(padMask.GetX(),padMask.GetY()),transformedManualMask->GetPointerToVoxels());\n}\n\nvoid irtkReconstruction::SetReconstructed(irtkRealImage &reconstructed)\n{\n  _reconstructed = reconstructed;\n  _template_created = true;\n}\n\nvoid irtkReconstruction::SetTransformations(vector<irtkRigidTransformation>& transformations)\n{\n  _transformations.clear();\n  _transformations_gpu.clear();\n  for (int i = 0; i < transformations.size(); i++)\n  {\n    _transformations.push_back(transformations[i]);\n    _transformations_gpu.push_back(transformations[i]);\n  }\n\n}\n\nvoid irtkReconstruction::SaveBiasFields()\n{\n  char buffer[256];\n  for (unsigned int inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    sprintf(buffer, \"bias%i.nii.gz\", inputIndex);\n    _bias[inputIndex].Write(buffer);\n  }\n}\n\nvoid irtkReconstruction::SaveConfidenceMap()\n{\n  _confidence_map.Write(\"confidence-map.nii.gz\");\n}\n\nvoid irtkReconstruction::SaveSlices()\n{\n  char buffer[256];\n  for (unsigned int inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n  {\n    sprintf(buffer, \"slice%i.nii.gz\", inputIndex);\n    _slices[inputIndex].Write(buffer);\n  }\n}\n\nvoid irtkReconstruction::SaveWeights()\n{\n  char buffer[256];\n  for (unsigned int inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    sprintf(buffer, \"weights%i.nii.gz\", inputIndex);\n    _weights[inputIndex].Write(buffer);\n  }\n}\n\nvoid irtkReconstruction::SaveTransformations()\n{\n  char buffer[256];\n  for (unsigned int inputIndex = 0; inputIndex < _slices.size(); inputIndex++) {\n    irtkRigidTransformation *t = new irtkRigidTransformation;\n    t->PutMatrix(_reconstructed.GetWorldToImageMatrix() * _transformations[inputIndex].GetMatrix() * _slices[inputIndex].GetImageToWorldMatrix());\n\n    sprintf(buffer, \"croppedSliceTransformation%i.dof\", inputIndex);\n    _transformations[inputIndex].irtkTransformation::Write(buffer);\n\n    sprintf(buffer, \"croppedSliceToVolumeTransformation%i.dof\", inputIndex);\n    t->irtkTransformation::Write(buffer);\n\n    //sprintf(buffer, \"sliceTransformation_gpu%i.dof\", inputIndex);\n    //_transformations_gpu[inputIndex].irtkTransformation::Write(buffer);\n  }\n}\n\nvoid irtkReconstruction::GetTransformations(vector<irtkRigidTransformation> &transformations)\n{\n  transformations.clear();\n  for (unsigned int inputIndex = 0; inputIndex < _slices.size(); inputIndex++)\n  {\n    transformations.push_back(_transformations[inputIndex]);\n  }\n}\n\nvoid irtkReconstruction::GetSlices(vector<irtkRealImage> &slices)\n{\n  slices.clear();\n  for (unsigned int i = 0; i < _slices.size(); i++)\n    slices.push_back(_slices[i]);\n}\n\nvoid irtkReconstruction::SlicesInfo(const char* filename)\n{\n  std::ofstream info;\n  info.open(filename);\n\n  // header\n  info << \"stack_index\" << \"\\t\"\n    << \"included\" << \"\\t\" // Included slices\n    << \"excluded\" << \"\\t\"  // Excluded slices\n    << \"outside\" << \"\\t\"  // Outside slices\n    << \"weight\" << \"\\t\"\n    << \"scale\" << \"\\t\"\n    // << _stack_factor[i] << \"\\t\"\n    << \"TranslationX\" << \"\\t\"\n    << \"TranslationY\" << \"\\t\"\n    << \"TranslationZ\" << \"\\t\"\n    << \"RotationX\" << \"\\t\"\n    << \"RotationY\" << \"\\t\"\n    << \"RotationZ\" << endl;\n\n  for (int i = 0; i < _slices.size(); i++) {\n    irtkRigidTransformation& t = _transformations[i];\n    info << _stack_index[i] << \"\\t\"\n      << (((_slice_weight_cpu[i] >= 0.5) && (_slice_inside_cpu[i])) ? 1 : 0) << \"\\t\" // Included slices\n      << (((_slice_weight_cpu[i] < 0.5) && (_slice_inside_cpu[i])) ? 1 : 0) << \"\\t\"  // Excluded slices\n      << ((!(_slice_inside_cpu[i])) ? 1 : 0) << \"\\t\"  // Outside slices\n      << _slice_weight_cpu[i] << \"\\t\"\n      << _scale_cpu[i] << \"\\t\"\n      // << _stack_factor[i] << \"\\t\"\n      << t.GetTranslationX() << \"\\t\"\n      << t.GetTranslationY() << \"\\t\"\n      << t.GetTranslationZ() << \"\\t\"\n      << t.GetRotationX() << \"\\t\"\n      << t.GetRotationY() << \"\\t\"\n      << t.GetRotationZ() << endl;\n  }\n\n  info.close();\n}\n\n/* end Set/Get/Save operations */\n\n/* Package specific functions */\nvoid irtkReconstruction::SplitImage(irtkRealImage image, int packages, vector<irtkRealImage>& stacks)\n{\n  irtkImageAttributes attr = image.GetImageAttributes();\n\n  //slices in package\n  int pkg_z = attr._z / packages;\n  double pkg_dz = attr._dz*packages;\n  cout << \"packages: \" << packages << \"; slices: \" << attr._z << \"; slices in package: \" << pkg_z << endl;\n  cout << \"slice thickness \" << attr._dz << \"; slickess thickness in package: \" << pkg_dz << endl;\n\n  char buffer[256];\n  int i, j, k, l;\n  double x, y, z, sx, sy, sz, ox, oy, oz;\n  for (l = 0; l < packages; l++) {\n    attr = image.GetImageAttributes();\n    if ((pkg_z*packages + l) < attr._z)\n      attr._z = pkg_z + 1;\n    else\n      attr._z = pkg_z;\n    attr._dz = pkg_dz;\n\n    cout << \"split image \" << l << \" has \" << attr._z << \" slices.\" << endl;\n\n    //fill values in each stack\n    irtkRealImage stack(attr);\n    stack.GetOrigin(ox, oy, oz);\n\n    cout << \"Stack \" << l << \":\" << endl;\n    for (k = 0; k < stack.GetZ(); k++)\n      for (j = 0; j < stack.GetY(); j++)\n        for (i = 0; i < stack.GetX(); i++)\n          stack.Put(i, j, k, image(i, j, k*packages + l));\n\n    //adjust origin\n\n    //original image coordinates\n    x = 0; y = 0; z = l;\n    image.ImageToWorld(x, y, z);\n    cout << \"image: \" << x << \" \" << y << \" \" << z << endl;\n    //stack coordinates\n    sx = 0; sy = 0; sz = 0;\n    stack.PutOrigin(ox, oy, oz); //adjust to original value\n    stack.ImageToWorld(sx, sy, sz);\n    cout << \"stack: \" << sx << \" \" << sy << \" \" << sz << endl;\n    //adjust origin\n    cout << \"adjustment needed: \" << x - sx << \" \" << y - sy << \" \" << z - sz << endl;\n    stack.PutOrigin(ox + (x - sx), oy + (y - sy), oz + (z - sz));\n    sx = 0; sy = 0; sz = 0;\n    stack.ImageToWorld(sx, sy, sz);\n    cout << \"adjusted: \" << sx << \" \" << sy << \" \" << sz << endl;\n\n    //sprintf(buffer,\"stack%i.nii.gz\",l);\n    //stack.Write(buffer);\n    stacks.push_back(stack);\n  }\n  cout << \"done.\" << endl;\n\n}\n\nvoid irtkReconstruction::SplitImageEvenOdd(irtkRealImage image, int packages, vector<irtkRealImage>& stacks)\n{\n  vector<irtkRealImage> packs;\n  vector<irtkRealImage> packs2;\n  cout << \"Split Image Even Odd: \" << packages << \" packages.\" << endl;\n\n  stacks.clear();\n  SplitImage(image, packages, packs);\n  for (int i = 0; i < packs.size(); i++) {\n    cout << \"Package \" << i << \": \" << endl;\n    packs2.clear();\n    SplitImage(packs[i], 2, packs2);\n    stacks.push_back(packs2[0]);\n    stacks.push_back(packs2[1]);\n  }\n\n  cout << \"done.\" << endl;\n}\n\nvoid irtkReconstruction::SplitImageEvenOddHalf(irtkRealImage image, int packages, vector<irtkRealImage>& stacks, int iter)\n{\n  vector<irtkRealImage> packs;\n  vector<irtkRealImage> packs2;\n\n  cout << \"Split Image Even Odd Half \" << iter << endl;\n  stacks.clear();\n  if (iter>1)\n    SplitImageEvenOddHalf(image, packages, packs, iter - 1);\n  else\n    SplitImageEvenOdd(image, packages, packs);\n  for (int i = 0; i < packs.size(); i++) {\n    packs2.clear();\n    HalfImage(packs[i], packs2);\n    for (int j = 0; j < packs2.size(); j++)\n      stacks.push_back(packs2[j]);\n  }\n}\n\n\nvoid irtkReconstruction::HalfImage(irtkRealImage image, vector<irtkRealImage>& stacks)\n{\n  irtkRealImage tmp;\n  irtkImageAttributes attr = image.GetImageAttributes();\n  stacks.clear();\n\n  //We would not like single slices - that is reserved for slice-to-volume\n  if (attr._z >= 4) {\n    tmp = image.GetRegion(0, 0, 0, attr._x, attr._y, attr._z / 2);\n    stacks.push_back(tmp);\n    tmp = image.GetRegion(0, 0, attr._z / 2, attr._x, attr._y, attr._z);\n    stacks.push_back(tmp);\n  }\n  else\n    stacks.push_back(image);\n}\n\n\nvoid irtkReconstruction::PackageToVolume(vector<irtkRealImage>& stacks, vector<int> &pack_num, bool evenodd, bool half, int half_iter)\n{\n  irtkImageRigidRegistrationWithPadding rigidregistration;\n  irtkGreyImage t, s;\n  //irtkRigidTransformation transformation;\n  vector<irtkRealImage> packages;\n  char buffer[256];\n\n  int firstSlice = 0;\n  cout << \"Package to volume: \" << endl;\n  for (unsigned int i = 0; i < stacks.size(); i++) {\n    cout << \"Stack \" << i << \": First slice index is \" << firstSlice << endl;\n\n    packages.clear();\n    if (evenodd) {\n      if (half)\n        SplitImageEvenOddHalf(stacks[i], pack_num[i], packages, half_iter);\n      else\n        SplitImageEvenOdd(stacks[i], pack_num[i], packages);\n    }\n    else\n      SplitImage(stacks[i], pack_num[i], packages);\n\n    for (unsigned int j = 0; j < packages.size(); j++) {\n      cout << \"Package \" << j << \" of stack \" << i << endl;\n      if (_debug) {\n        sprintf(buffer, \"package%i-%i.nii.gz\", i, j);\n        packages[j].Write(buffer);\n      }\n\n      t = packages[j];\n      s = _reconstructed;\n\n      //find existing transformation\n      double x, y, z;\n      x = 0; y = 0; z = 0;\n      packages[j].ImageToWorld(x, y, z);\n      stacks[i].WorldToImage(x, y, z);\n\n      int firstSliceIndex = round(z) + firstSlice;\n      cout << \"First slice index for package \" << j << \" of stack \" << i << \" is \" << firstSliceIndex << endl;\n      //transformation = _transformations[sliceIndex];\n\n      //put origin in target to zero\n      irtkRigidTransformation offset;\n      ResetOrigin(t, offset);\n      irtkMatrix mo = offset.GetMatrix();\n      irtkMatrix m = _transformations[firstSliceIndex].GetMatrix();\n      m = m*mo;\n      _transformations[firstSliceIndex].PutMatrix(m);\n\n      rigidregistration.SetInput(&t, &s);\n      rigidregistration.SetOutput(&_transformations[firstSliceIndex]);\n      rigidregistration.GuessParameterSliceToVolume(_useNMI);\n      if (_debug)\n        rigidregistration.Write(\"par-packages.rreg\");\n      rigidregistration.Run();\n\n      //undo the offset\n      mo.Invert();\n      m = _transformations[firstSliceIndex].GetMatrix();\n      m = m*mo;\n      _transformations[firstSliceIndex].PutMatrix(m);\n\n      if (_debug) {\n        sprintf(buffer, \"transformation%i-%i.dof\", i, j);\n        _transformations[firstSliceIndex].irtkTransformation::Write(buffer);\n      }\n\n\n      //set the transformation to all slices of the package\n      cout << \"Slices of the package \" << j << \" of the stack \" << i << \" are: \";\n      for (int k = 0; k < packages[j].GetZ(); k++) {\n        x = 0; y = 0; z = k;\n        packages[j].ImageToWorld(x, y, z);\n        stacks[i].WorldToImage(x, y, z);\n        int sliceIndex = round(z) + firstSlice;\n        cout << sliceIndex << \" \" << endl;\n\n        if (sliceIndex >= _transformations.size()) {\n          cerr << \"irtkRecnstruction::PackageToVolume: sliceIndex out of range.\" << endl;\n          cerr << sliceIndex << \" \" << _transformations.size() << endl;\n          exit(1);\n        }\n\n        if (sliceIndex != firstSliceIndex) {\n          _transformations[sliceIndex].PutTranslationX(_transformations[firstSliceIndex].GetTranslationX());\n          _transformations[sliceIndex].PutTranslationY(_transformations[firstSliceIndex].GetTranslationY());\n          _transformations[sliceIndex].PutTranslationZ(_transformations[firstSliceIndex].GetTranslationZ());\n          _transformations[sliceIndex].PutRotationX(_transformations[firstSliceIndex].GetRotationX());\n          _transformations[sliceIndex].PutRotationY(_transformations[firstSliceIndex].GetRotationY());\n          _transformations[sliceIndex].PutRotationZ(_transformations[firstSliceIndex].GetRotationZ());\n          _transformations[sliceIndex].UpdateMatrix();\n        }\n      }\n\n\n    }\n    cout << \"End of stack \" << i << endl << endl;\n\n    firstSlice += stacks[i].GetZ();\n  }\n}\n\n\n/* end Package specific functions */\n\n/* Utility functions */\n\nvoid irtkReconstruction::CropImage(irtkRealImage& image, irtkRealImage& mask)\n{\n  //Crops the image according to the mask\n\n  int i, j, k;\n  //ROI boundaries\n  int x1, x2, y1, y2, z1, z2;\n\n  //Original ROI\n  x1 = 0;\n  y1 = 0;\n  z1 = 0;\n  x2 = image.GetX();\n  y2 = image.GetY();\n  z2 = image.GetZ();\n\n  //upper boundary for z coordinate\n  int sum = 0;\n  for (k = image.GetZ() - 1; k >= 0; k--) {\n    sum = 0;\n    for (j = image.GetY() - 1; j >= 0; j--)\n      for (i = image.GetX() - 1; i >= 0; i--)\n        if (mask.Get(i, j, k) > 0)\n          sum++;\n    if (sum > 0)\n      break;\n  }\n  z2 = k;\n\n  //lower boundary for z coordinate\n  sum = 0;\n  for (k = 0; k <= image.GetZ() - 1; k++) {\n    sum = 0;\n    for (j = image.GetY() - 1; j >= 0; j--)\n      for (i = image.GetX() - 1; i >= 0; i--)\n        if (mask.Get(i, j, k) > 0)\n          sum++;\n    if (sum > 0)\n      break;\n  }\n  z1 = k;\n\n  //upper boundary for y coordinate\n  sum = 0;\n  for (j = image.GetY() - 1; j >= 0; j--) {\n    sum = 0;\n    for (k = image.GetZ() - 1; k >= 0; k--)\n      for (i = image.GetX() - 1; i >= 0; i--)\n        if (mask.Get(i, j, k) > 0)\n          sum++;\n    if (sum > 0)\n      break;\n  }\n  y2 = j;\n\n  //lower boundary for y coordinate\n  sum = 0;\n  for (j = 0; j <= image.GetY() - 1; j++) {\n    sum = 0;\n    for (k = image.GetZ() - 1; k >= 0; k--)\n      for (i = image.GetX() - 1; i >= 0; i--)\n        if (mask.Get(i, j, k) > 0)\n          sum++;\n    if (sum > 0)\n      break;\n  }\n  y1 = j;\n\n  //upper boundary for x coordinate\n  sum = 0;\n  for (i = image.GetX() - 1; i >= 0; i--) {\n    sum = 0;\n    for (k = image.GetZ() - 1; k >= 0; k--)\n      for (j = image.GetY() - 1; j >= 0; j--)\n        if (mask.Get(i, j, k) > 0)\n          sum++;\n    if (sum > 0)\n      break;\n  }\n  x2 = i;\n\n  //lower boundary for x coordinate\n  sum = 0;\n  for (i = 0; i <= image.GetX() - 1; i++) {\n    sum = 0;\n    for (k = image.GetZ() - 1; k >= 0; k--)\n      for (j = image.GetY() - 1; j >= 0; j--)\n        if (mask.Get(i, j, k) > 0)\n          sum++;\n    if (sum > 0)\n      break;\n  }\n\n  x1 = i;\n\n  if (_debug)\n    cout << \"Region of interest is \" << x1 << \" \" << y1 << \" \" << z1 << \" \" << x2 << \" \" << y2\n    << \" \" << z2 << endl;\n\n  //Cut region of interest\n  image = image.GetRegion(x1, y1, z1, x2 + 1, y2 + 1, z2 + 1);\n}\n\nvoid irtkReconstruction::InvertStackTransformations(vector<irtkRigidTransformation>& stack_transformations)\n{\n  //for each stack\n  for (unsigned int i = 0; i < stack_transformations.size(); i++) {\n    //invert transformation for the stacks\n    stack_transformations[i].Invert();\n    stack_transformations[i].UpdateParameter();\n  }\n}\n\n\nvoid irtkReconstruction::MaskVolumeGPU()\n{\n  reconstructionGPU->maskVolume();\n}\n\n\nvoid irtkReconstruction::MaskVolume()\n{\n  irtkRealPixel *pr = _reconstructed.GetPointerToVoxels();\n  irtkRealPixel *pm = _mask.GetPointerToVoxels();\n  for (int i = 0; i < _reconstructed.GetNumberOfVoxels(); i++) {\n    if (*pm == 0)\n      *pr = -1;\n    pm++;\n    pr++;\n  }\n}\n\nvoid irtkReconstruction::MaskImage(irtkRealImage& image, double padding)\n{\n  if (image.GetNumberOfVoxels() != _mask.GetNumberOfVoxels()) {\n    cerr << \"Cannot mask the image - different dimensions\" << endl;\n    exit(1);\n  }\n  irtkRealPixel *pr = image.GetPointerToVoxels();\n  irtkRealPixel *pm = _mask.GetPointerToVoxels();\n  for (int i = 0; i < image.GetNumberOfVoxels(); i++) {\n    if (*pm == 0)\n      *pr = padding;\n    pm++;\n    pr++;\n  }\n}\n\n/// Like PutMinMax but ignoring negative values (mask)\nvoid irtkReconstruction::Rescale(irtkRealImage &img, double max)\n{\n  int i, n;\n  irtkRealPixel *ptr, min_val, max_val;\n\n  // Get lower and upper bound\n  img.GetMinMax(&min_val, &max_val);\n\n  n = img.GetNumberOfVoxels();\n  ptr = img.GetPointerToVoxels();\n  for (i = 0; i < n; i++)\n    if (ptr[i] > 0)\n      ptr[i] = double(ptr[i]) / double(max_val) * max;\n}\n/* end Utility functions */\n", "meta": {"hexsha": "60fd5e1d21c73bc6c8d1eb568a01cedac7ce6f22", "size": 166099, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/reconstructionGPU2/irtkReconstructionGPU.cc", "max_stars_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_stars_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_stars_repo_licenses": ["Zlib", "Unlicense", "Intel", "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/reconstructionGPU2/irtkReconstructionGPU.cc", "max_issues_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_issues_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_issues_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "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/reconstructionGPU2/irtkReconstructionGPU.cc", "max_forks_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_forks_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_forks_repo_licenses": ["Zlib", "Unlicense", "Intel", "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.936673496, "max_line_length": 188, "alphanum_fraction": 0.619780974, "num_tokens": 47742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.18221789939724778}}
{"text": "//! @file pfr1d.cpp \n//! Provides an plug-flow reactor model in 1d.\n\n// This file is part of Hetero_ct. \n// Source is adapted from CanteraPFR codebase.\n//#include <boost/math/interpolators/barycentric_rational_interpolation.hpp>\n#include <boost/range/adaptors.hpp>\n\n#include \"pfr1d.h\"\n#include \"cantera/numerics/ResidJacEval.h\"\n\nusing namespace std;\nusing namespace Cantera;\n\n\nnamespace OpenMKM \n{\n\nPFR1d::PFR1d(IdealGasMix *gas, vector<InterfaceKinetics*> surf_kins,\n             vector<SurfPhase*> surf_phases, double area, double cat_abyv,\n             double inlet_gas_velocity) \n   : ResidJacEval{}, m_gas(gas), m_surf_kins(surf_kins), \n     m_surf_phases(surf_phases), m_Ac(area), m_cat_abyv(cat_abyv), \n     m_u0(inlet_gas_velocity), m_T_interp(nullptr)\n{\n   \n    suppress_thermo_warnings(SUPPRESS_WARNINGS);\n\n    cout << boolalpha\n         //<< setw(16) << \"\\nReactor Model:  \" << \"PFR\"\n         << setw(16) << \"\\nUsing Sundials? \" << CT_SUNDIALS_VERSION\n         << setw(16) << \"\\nUsing LAPACK?   \" << bool(CT_SUNDIALS_USE_LAPACK)\n         << endl;\n\n    m_rho_ref = m_gas->density();\n    cout << boolalpha << setw(16) << \"Energy enabled? \" << energyEnabled() << endl;\n    m_nsp = m_gas->nSpecies();\n    if (energyEnabled()) \n        m_neqs_extra = 4;\n    else\n        m_neqs_extra = 3;\n\n    neq_ = m_nsp + m_neqs_extra;\n    //cout << \"neq \" << neq_ << endl;\n    for (const auto s_ph : m_surf_phases) {\n        neq_ += s_ph->nSpecies();\n    }\n\n    m_W.resize(m_nsp);\n    m_gas->getMolecularWeights(m_W.data());\n    m_wdot.resize(m_nsp);\n    fill(m_wdot.begin(), m_wdot.end(), 0.0);\n    m_sdot.resize(m_nsp);\n    fill(m_sdot.begin(), m_sdot.end(), 0.0);\n\n    //m_var.resize(neq_ - m_neqs_extra);\n    //m_var = m_gas->speciesNames();\n    //m_var.resize(neq_);\n    m_var.clear();\n    m_var.push_back(\"Velocity(m/s)\");\n    m_var.push_back(\"Density\");\n    m_var.push_back(\"Pressure(Pa)\");\n    if (energyEnabled())\n        m_var.push_back(\"Temperature(K)\");\n    auto sp_names = m_gas->speciesNames();\n    for (auto i = 0; i < sp_names.size(); i++){\n        m_var.push_back(sp_names[i]);\n    }\n    for (const auto s_ph : m_surf_phases) {\n        auto sp_nm = s_ph->speciesNames();\n        for (auto i = 0; i < sp_nm.size(); i++){\n            m_var.push_back(sp_nm[i]);\n        }\n    }\n\n    m_T0 = gas->temperature();\n    m_P0 = gas->pressure();\n    cout << setw(16) << \"External heat supplied: \" << getHeat(m_T0) << endl;\n}   \n\nvoid PFR1d::reinit()\n{\n\n    m_rho_ref = m_gas->density();\n\n    cout << boolalpha << \"Energy enabled? \" << energyEnabled() << endl;\n    m_nsp = m_gas->nSpecies();\n    if (energyEnabled())\n        m_neqs_extra = 4;\n    else\n        m_neqs_extra = 3;\n    //cout << \"m_neqs_extra: \" << m_neqs_extra << endl;\n\n    neq_ = m_nsp + m_neqs_extra;\n    //cout << \"neq \" << neq_ << endl;\n    for (const auto s_ph : m_surf_phases) {\n        neq_ += s_ph->nSpecies();\n    }\n    //cout << \"neq \" << neq_ << endl;\n\n    m_W.resize(m_nsp);\n    m_gas->getMolecularWeights(m_W.data());\n    m_wdot.resize(m_nsp);\n    fill(m_wdot.begin(), m_wdot.end(), 0.0);\n    m_sdot.resize(m_nsp);\n    fill(m_sdot.begin(), m_sdot.end(), 0.0);\n\n    //m_var.resize(neq_);\n    m_var.clear();\n    m_var.push_back(\"Velocity(m/s)\");\n    m_var.push_back(\"Density\");\n    m_var.push_back(\"Pressure(Pa)\");\n    if (energyEnabled())\n        m_var.push_back(\"Temperature(K)\");\n    auto sp_names = m_gas->speciesNames();\n    //m_var.insert(m_var.end(), sp_names.begin(), sp_names.end());\n    for (auto i = 0; i < sp_names.size(); i++){\n        m_var.push_back(sp_names[i]);\n    }\n    for (const auto s_ph : m_surf_phases) {\n        auto sp_nm = s_ph->speciesNames();\n        for (auto i = 0; i < sp_nm.size(); i++){\n            m_var.push_back(sp_nm[i]);\n        }\n    }\n\n    m_T0 = m_gas->temperature();\n    m_P0 = m_gas->pressure();\n}\n\nvoid PFR1d::setConstraints()\n{\n    cout << boolalpha << \"Constraints Enabled: \" << true << endl;\n    constrain(0, c_GT_ZERO);\n    constrain(1, c_GT_ZERO);\n    constrain(2, c_GT_ZERO);\n    if (energyEnabled()) {\n        constrain(3, c_GT_ZERO);\n    }\n    for (size_t i = 0; i < m_nsp; i++){\n        auto k = i + m_neqs_extra;\n        constrain(k, c_GE_ZERO);\n    }\n    auto loc = m_nsp + m_neqs_extra;\n    for (const auto s_ph : m_surf_phases) {\n        auto nSpecies = s_ph->nSpecies();\n        for (size_t i = 0; i < nSpecies; i++){\n            auto k = i + loc;\n            constrain(k, c_GE_ZERO);\n        }\n        loc += nSpecies;\n    }\n}\n\nint PFR1d::getInitialConditions(const double t0,\n                                double *const y, \n                                double *const ydot)\n{\n    //const double P0 = m_gas->pressure();\n    const double rho0 = m_gas->density();\n    const double Wavg = m_gas->meanMolecularWeight();\n    const double RT = m_T0 * GasConstant;\n    //const double Rrho = rho0 * GasConstant;\n\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(m_nsp + m_neqs_extra, \n                                              m_nsp + m_neqs_extra);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(m_nsp + m_neqs_extra);\n\n    y[0] = m_u0;\n    y[1] = rho0;\n    y[2] = m_P0;\n    /*\n    cout << 0 << \" y \" << y[0] << endl\n         << 1 << \" y \" << y[1] << endl\n         << 2 << \" y \" << y[2] << endl;*/\n    //int gas_start_loc;\n    if (energyEnabled()) {\n        y[3] = m_T0;\n        //cout << 3 << \" y \" << y[3] << endl;\n    }\n\n    m_gas->getMassFractions(y + m_neqs_extra);\n    /*\n    for (size_t i = 0; i < m_nsp; i++){\n        cout << i << \" y \" << y[i + m_neqs_extra] << endl;\n    }*/\n\n    auto loc = m_nsp + m_neqs_extra;\n    for (const auto s_ph : m_surf_phases) {\n        s_ph->getCoverages(y + loc);\n        loc += s_ph->nSpecies();\n    }\n\n    // Continuity equation elements.\n    A(0, 0) = rho0;           // u'\n    A(0, 1) = m_u0;           // rho'\n    A(0, 2) = 0;              // p'\n    if (energyEnabled())\n        A(0, 3) = 0;          // T'\n    for (unsigned k = m_neqs_extra; k < m_nsp + m_neqs_extra; ++k)\n        A(0, k) = 0.0;\n\n    // Momentum equation elements.\n    A(1, 0) = 2* rho0 * m_u0; // u'\n    A(1, 1) = m_u0 * m_u0;    // rho'\n    A(1, 2) = 1;              // p'\n    if (energyEnabled())\n        A(1, 3) = 0;          // T'\n    for (unsigned k = m_neqs_extra; k < m_nsp + m_neqs_extra; ++k)\n        A(1, k) = 0.0;\n\n    // State equation elements.\n    A(2, 0) = 0;              // u'\n    A(2, 1) = RT;             // rho'\n    A(2, 2) = -Wavg;          // p'\n    if (energyEnabled())\n        //A(2, 3) = Rrho;       // T'   // This is the source of the difference\n        A(2, 3) = 0;       // T'   // This is the source of the difference\n    // Yk' for other equations, exceptionally here!\n    for (unsigned k = m_neqs_extra; k < m_nsp + m_neqs_extra; ++k)\n        A(2, k) = m_P0 * Wavg * Wavg / m_W[k - m_neqs_extra];\n\n    double mdot_surf = evalSurfaces();\n    m_gas->getNetProductionRates(&m_wdot[0]);\n\n    if (energyEnabled()) {\n        //vector<double> cpr_k(m_nsp);\n        //m_gas->getCp_R(cpr_k.data());\n        //double cpr = 0.0;\n        //for (size_t i = 0; i < m_nsp; i++){\n            //cpr += cpr_k[i] * y[i + m_neqs_extra];\n        //}\n        //cout << \"cp\" << cpr*GasConstant << endl;\n        auto cp = m_gas->cp_mass();\n\n        A(3,0) = 0;            // u'\n        A(3,1) = 0;            // rho'\n        A(3,2) = 0;            // p'\n        A(3,3) = rho0 * m_u0 * cp;// * GasConstant;            // T'\n        //cout << \"A(3,3) \" << A(3, 3) << endl;\n\n        vector<double> H_rt(m_nsp);\n        m_gas->getEnthalpy_RT(H_rt.data());\n        b(3) = 0;                          // RHS energy\n        for (size_t i = 0; i < m_nsp; i++){\n            //b(3) -= (m_wdot[i] + m_sdot[i] * m_cat_abyv) * m_W[i] * cpr_k[i];\n            b(3) -= (m_wdot[i] + m_sdot[i] * m_cat_abyv) *  H_rt[i];\n            /*cout << i << \" msdot \" << m_sdot[i] << endl\n                 //<< i << \" m_W \" << m_W[i] << endl\n                 << i << \" H_rt \" <<  H_rt[i] << endl;\n            cout << \"Running b(3) \" << b(3) << endl;\n            cout << m_cat_abyv << endl;\n            */\n        }\n\n        //cout << \"b(3) before multiplication : \" << b(3) << endl;\n        //b(3) *= m_T0;\n        b(3) *= RT;\n        //cout << \"b(3) after multiplication : \" << b(3) << endl;\n        b(3) += getHeat(m_T0);///GasConstant;\n        //cout << \"get heat: \" << getHeat(m_T0) << endl;\n        //cout << \"b(3): \" << b(3) << endl;\n    }\n\n\n    b(0) = m_cat_abyv * mdot_surf;          // RHS continuity\n    //cout << \"b(0): \" << b(0) << endl;\n    b(1) = 0;                               // RHS momentum\n    b(2) = 0;                               // RHS state\n    //if (energyEnabled()){\n    //}\n\n    // Gas phase species\n    for (unsigned k = m_neqs_extra; k < m_nsp + m_neqs_extra; ++k)\n    {\n        //cout << \" y[k] \" << y[k] << endl;\n        auto i = k - m_neqs_extra;\n        // For species equations.\n        A(k, k) = rho0 * m_u0;\n        b(k) = (m_wdot[i] + m_sdot[i] * m_cat_abyv) * m_W[i] -\n               y[k] * mdot_surf * m_cat_abyv;\n        //cout << k << \" b(k) \" << b(k) << endl; \n\n    }\n    \n    Eigen::VectorXd x = A.fullPivLu().solve(b);\n    Eigen::VectorXd::Map(ydot, x.rows()) = x;\n    /*\n    for (size_t i = 0; i < neq_; i++)\n        cout << \"i \" << i << \" ydot[i] \" << ydot[i] << endl;*/\n\n    return 0;\n}\n\nint PFR1d::evalResidNJ(const double t, const double delta_t, \n                       const double* const y, const double* const ydot, \n                       double* const resid, \n                       const Cantera::ResidEval_Type_Enum evalType, \n                       const int id_x, const double delta_x)\n{\n    applySensitivity();//m_sens_params.data());\n    const double u = y[0];       // Flow rate\n    const double r = y[1];       // Density\n    const double p = y[2];       // Pressure\n    const double temp = energyEnabled() ? y[3] : getT(t);   // Temperature\n    double RT = GasConstant * temp;\n\n    const double dudz = ydot[0];\n    const double drdz = ydot[1];\n    const double dpdz = ydot[2];\n    double dtempdz = energyEnabled() ? ydot[3] : 0;\n\n    m_gas->setMassFractions_NoNorm(y + m_neqs_extra);\n    m_gas->setState_TP(temp, p);\n\n    auto loc = m_neqs_extra + m_nsp;\n    for (auto s_ph : m_surf_phases) {\n        s_ph->setState_TP(temp, p);\n        s_ph->setCoveragesNoNorm(y + loc);\n        loc += s_ph->nSpecies();\n    }\n\n    // Get species production rates\n    m_gas->getNetProductionRates(&m_wdot[0]);\n    //double mdot_surf = s();\n    vector_fp work(m_nsp);\n    fill(m_sdot.begin(), m_sdot.end(), 0.0);\n    double mdot_surf = 0.0; // net mass flux from surface\n\n    loc = m_nsp;\n    for (size_t i = 0; i < m_surf_phases.size(); i++) {\n        double cov_sum = 0.0;\n        InterfaceKinetics* kin = m_surf_kins[i];\n        SurfPhase* surf = m_surf_phases[i];\n        work.resize(kin->nTotalSpecies());\n\n        kin->getNetProductionRates(work.data());\n        for (size_t k = m_nsp + 1; k < kin->nTotalSpecies() - 1; k++){ // Gas + bulk + surface species\n            resid[m_neqs_extra + loc + k - m_nsp - 1] = work[k];\n            cov_sum += y[loc + m_neqs_extra + k - m_nsp -1];\n        }\n        loc += surf->nSpecies();\n        cov_sum += y[loc + m_neqs_extra - 1];\n        resid[loc + m_neqs_extra - 1] = 1.0 - cov_sum; \n\n        for (size_t k = 0; k < m_nsp; k++) {\n            m_sdot[k] += work[k];\n            mdot_surf += m_sdot[k] * m_W[k];\n        }\n    }\n\n\n    resid[0] = u * drdz + r * dudz - m_cat_abyv * mdot_surf;\n    resid[1] = 2 * r * u * dudz + u *u * drdz + dpdz;\n    resid[2] = m_gas->density() - r;  // Density is set as pW/RT\n\n    if (energyEnabled()){\n        /*\n        vector<double> cpr(m_nsp);\n        m_gas->getCp_R(cpr.data());\n        double cp;\n        for (size_t i = 0; i < m_nsp; i++){\n            cp += cpr[i] * y[i + m_neqs_extra];\n        }\n        */\n        auto cp = m_gas->cp_mass();\n        resid[3] = cp *  r * u * dtempdz;\n\n        double h_term  = 0;                          \n        vector<double> H_rt(m_nsp);\n        m_gas->getEnthalpy_RT(H_rt.data());\n        for (size_t i = 0; i < m_nsp; i++){\n            //h_term += (m_wdot[i] + m_sdot[i] * m_cat_abyv) * m_W[i] * cpr[i];\n            h_term += (m_wdot[i] + m_sdot[i] * m_cat_abyv)  * H_rt[i];\n        }\n        //resid[3] += h_term * temp;\n        resid[3] += h_term * RT;\n        resid[3] -= getHeat(temp);///GasConstant;\n    }\n\n    for (unsigned k = 0; k < m_nsp; ++k)\n    {\n        auto k1 = k + m_neqs_extra;\n        resid[k1] = u * r * ydot[k1] + y[k1] * mdot_surf * m_cat_abyv - \n                    (m_wdot[k] + m_sdot[k] * m_cat_abyv) * m_W[k];\n    }\n\n    resetSensitivity();\n    return 0;\n}\n\n// This function is used to compute Fisher Information Matrix\n// using all the reactions participating in the kinetics\nint PFR1d::evalQuadRhs(const double t, const double* const y, \n                       const double* const ydot, double* const rhsQ)\n{\n    size_t loc = 0;\n    m_gas->getNetRatesOfProgress(rhsQ);\n    loc += m_gas->nReactions();\n    \n    for (auto kin : m_surf_kins) {\n        kin->getNetRatesOfProgress(rhsQ + loc);\n        loc += kin->nReactions();\n    }\n    return 0;\n}\n\n/*\nvoid PFR1d::setTProfile(map<double, double> T_profile)\n{\n    if (T_profile.begin()->first > 0)\n        m_T_profile_iind = -1;\n    else\n        m_T_profile_iind = 0;\n\n    m_T_profile.resize(T_profile.size());\n    m_T_profile_ind.resize(T_profile.size());\n    auto i = 0;\n    for (const auto& dist_Tprof : T_profile) {\n        m_T_profile_ind[i] = dist_Tprof.first;\n        m_T_profile[i++] = dist_Tprof.second;\n    }\n}\n\ndouble PFR1d::getT(double z)\n{\n    if (!m_T_profile.size()){\n        return m_T0;\n    }\n\n    if (m_T_profile_iind >= 0 && z == m_T_profile_ind[m_T_profile_iind])\n        return  m_T_profile[m_T_profile_iind];\n    if (m_T_profile_iind < m_T_profile_ind.size() - 1  &&\n        z == m_T_profile_ind[m_T_profile_iind + 1])\n        return  m_T_profile[m_T_profile_iind + 1];  \n    if (m_T_profile_iind == m_T_profile_ind.size() - 1 && \n        z > m_T_profile_ind[m_T_profile_iind])\n        return m_T_profile[m_T_profile_iind];\n\n    if (m_T_profile_iind < m_T_profile_ind.size() - 1 && \n        z > m_T_profile_ind[m_T_profile_iind + 1]){\n        m_T_profile_iind += 1;\n    }\n \n    double lz, lT, hz, hT;\n    if (m_T_profile_iind < 0) {\n        lz = 0;\n        lT = m_T0;\n    } else {\n        lz = m_T_profile_ind[m_T_profile_iind];\n        lT = m_T_profile[m_T_profile_iind];\n    }\n    hz = m_T_profile_ind[m_T_profile_iind + 1];\n    hT = m_T_profile[m_T_profile_iind + 1];\n    \n    return lT + (hT - lT) / (hz - lz) * (z - lz); \n}\n*/\n\n/* Even this complexity is not needed \nvoid PFR1d::setTProfile(const map<double, double>& T_profile)\n{\n    // The profile given as map in the input is stored two \n    // vectors for boost library interpolators \n    // Clear the existing profile\n    if (m_T_profile_ind.size())\n        m_T_profile_ind.clear();\n    if (m_T_profile.size())\n        m_T_profile.clear();\n\n    // If T @ z=0 is not given, use inlet T\n    if (T_profile.begin()->first > 0){\n        m_T_profile_ind.push_back(0);\n        m_T_profile.push_back(m_T0);\n    }\n    for (const auto& dist_Tprof : T_profile) {\n        m_T_profile_ind.push_back(dist_Tprof.first);\n        m_T_profile.push_back(dist_Tprof.second);\n    }\n\n    m_T_interp = make_shared<boost::math::barycentric_rational<double>>(m_T_profile_ind, m_T_profile, m_T_profile.size());\n}\n*/\n\nvoid PFR1d::setTProfile(const map<double, double>& T_profile)\n{\n    /*\n    // The profile given as map in the input is temporarily stored into two \n    // vectors for boost library interpolators \n    // Clear the existing profile\n    vector<double> Ts, Zs;\n\n    // If T @ z=0 is not given, use inlet T\n    if (T_profile.begin()->first > 0){\n        Zs.push_back(0);\n        Ts.push_back(m_T0);\n    }\n    for (const auto& dist_Tprof : T_profile) {\n        Zs.push_back(dist_Tprof.first);\n        Ts.push_back(dist_Tprof.second);\n    }\n    */\n    auto Zs = boost::adaptors::keys(T_profile);\n    auto Ts = boost::adaptors::values(T_profile);\n\n    //if (m_T_interp != nullptr){\n    //    m_T_interp = nullptr;\n        m_T_interp = make_shared<boost::math::barycentric_rational<double>>(\n                Zs.begin(), Zs.end(), Ts.begin());\n    //}\n}\n\ndouble PFR1d::getT(double z)\n{\n    if (m_T_interp == nullptr){\n        return m_T0;\n    } else{\n        return m_T_interp->operator()(z);\n    }\n}\n\ndouble PFR1d::evalSurfaces() \n{\n    vector_fp work(m_nsp);\n    fill(m_sdot.begin(), m_sdot.end(), 0.0);\n    double mdot_surf = 0.0; // net mass flux from surface\n\n\n    for (size_t i = 0; i < m_surf_phases.size(); i++) {\n        InterfaceKinetics* kin = m_surf_kins[i];\n        //SurfPhase* surf = m_surf_phases[i];\n        work.resize(kin->nTotalSpecies());\n        fill(work.begin(), work.end(), 0.0);\n\n        kin->getNetProductionRates(work.data());\n\n        for (size_t k = 0; k < m_nsp; k++) {\n            m_sdot[k] += work[k];\n            mdot_surf += m_sdot[k] * m_W[k];\n        }\n    }\n\n    return mdot_surf;\n}\n\nvoid PFR1d::getSurfaceProductionRates(double* y)\n{\n    for (size_t i=0; i < m_nsp; i++) {\n        y[i] = m_sdot[i];\n    }\n}\n\nvoid PFR1d::getSurfaceInitialConditions(double* y)\n{\n    size_t loc = 0;\n    for (const auto s_ph : m_surf_phases) {\n        s_ph->getCoverages(y+loc);\n        loc += s_ph->nSpecies();\n    }\n}\n\nvoid PFR1d::setHeatTransfer(double htc, double Text, double wall_abyv)\n{\n    m_heat = true;\n    m_htc = htc;\n    m_Text = Text;\n    m_surf_ext_abyv = wall_abyv;\n}\n\ndouble PFR1d::getHeat(double Tint) const\n{\n    if (m_heat)\n        return m_htc * (m_Text - Tint) * m_surf_ext_abyv;\n    else \n        return 0;\n   \n}\n\nvoid PFR1d::addSensitivityReaction(std::string& rxn_id)\n{\n    // Find the kinetics to which the reaction id belongs to\n    // Start with GasKinetics\n    int kin_no = -1, rxn_no = -1;\n    cout << \"rxn id \" << rxn_id << \" added to sensitivity list \" << endl;\n    for (size_t i = 0; i < m_gas->nReactions(); i++){\n        if (m_gas->reaction(i)->id == rxn_id){\n            kin_no = 0;\n            rxn_no = i;\n            break;\n        }\n    }\n    if (kin_no < 0){\n        for (size_t j = 0; j < m_surf_phases.size(); j++) {\n            auto kin = m_surf_kins[j];\n            for (size_t i = 0; i < kin->nReactions(); i++){\n                if (kin->reaction(i)->id == rxn_id){\n                    kin_no = j + 1;\n                    rxn_no = i;\n                    break;\n                }\n            }\n            if (kin_no > 0)\n                break;\n        }\n    }\n    if (kin_no < 0){\n        throw CanteraError(\"PFR1d::addSensitivityReaction\",\n                           \"Reaction ({}) not found \", rxn_id);\n    }\n    addSensitivityReaction(kin_no, rxn_no);\n    /*\n     *\n    if (!m_chem || rxn >= m_kin->nReactions()) {\n    }\n\n    size_t p = network().registerSensitivityParameter(\n        name()+\": \"+m_kin->reactionString(rxn), 1.0, 1.0);\n    m_sensParams.emplace_back(\n        SensitivityParameter{rxn, p, 1.0, SensParameterType::reaction});\n        */\n}\n\n\nvoid PFR1d::addSensitivityReaction(size_t kin_ind, size_t rxn)\n{\n    Kinetics* kin = nullptr;\n    if (!kin_ind) {\n        kin = m_gas;\n    } else {\n        kin = m_surf_kins[kin_ind-1];\n    }\n\n    //Chemistry enabling option not added to PFR\n    //if (!m_chem || rxn >= kin->nReactions()) { \n    if (rxn >= kin->nReactions()) {\n        throw CanteraError(\"Reactor::addSensitivityReaction\",\n                           \"Reaction number out of range ({})\", rxn);\n    }\n\n    m_paramNames.push_back(kin->reactionString(rxn)); \n    m_sens_params.push_back(1.0);\n    m_paramScales.push_back(1.0);\n\n    if (kin_ind >= m_sensParams.size()){\n        for (size_t i = 0; i <= kin_ind - m_sensParams.size() + 1; i++){\n            vector<SensitivityParameter> sensParams;\n            m_sensParams.emplace_back(sensParams);\n        }\n    }\n    //vector<SensitivityParameter> curr_sensParams = m_sensParams[kin_ind];\n    m_sensParams[kin_ind].emplace_back(\n            SensitivityParameter{rxn, m_sens_params.size()-1, 1.0,\n                                 SensParameterType::reaction});\n\n    /*\n    size_t p = network().registerSensitivityParameter(\n        name()+\": \"+m_kin->reactionString(rxn), 1.0, 1.0);\n    m_sensParams.emplace_back(\n        SensitivityParameter{rxn, p, 1.0, SensParameterType::reaction});\n    */\n}\n\nvoid PFR1d::addSensitivitySpecies(std::string& species_name)\n{\n    // Find the phase to which the species belongs to\n    // Start with gas phase\n    int ph_no = -1;\n    cout << \"species \" << species_name << \" added to sensitivity list \" << endl;\n    auto sp_ind = m_gas->speciesIndex(species_name);\n    if (sp_ind < m_gas->nSpecies()){// Found in gas phase\n        ph_no = 0;\n        addSensitivitySpeciesEnthalpy(ph_no, sp_ind);\n    } else {\n        for (size_t j = 0; j < m_surf_phases.size(); j++) {\n            auto phase = m_surf_phases[j];\n            sp_ind = phase->speciesIndex(species_name);\n            if (sp_ind < phase->nSpecies()){\n                ph_no = j+1;\n                addSensitivitySpeciesEnthalpy(ph_no, sp_ind);\n                break;\n            }\n        }\n    }\n    if (ph_no < 0){\n        throw CanteraError(\"PFR1d::addSensitivitySpecies\",\n                           \"Species {} not found \", species_name);\n    }\n}\n\nvoid PFR1d::addSensitivitySpeciesEnthalpy(size_t ph_ind, size_t sp_ind)\n{\n    ThermoPhase* ph = nullptr;\n    if (!ph_ind) {\n        ph = m_gas;\n    } else {\n        ph = m_surf_phases[ph_ind-1];\n    }\n\n    //Chemistry enabling option not added to PFR\n    if (sp_ind >= ph->nSpecies()) {\n        throw CanteraError(\"Reactor::addSensitivitySpeciesEnthalpy\",\n                           \"Species number out of range ({})\", sp_ind);\n    }\n\n    m_paramNames.push_back(ph->speciesName(sp_ind)); \n    m_sens_params.push_back(0.0);\n    m_paramScales.push_back(GasConstant * 298.15);\n\n    if (ph_ind >= m_sensParams.size()){\n        for (size_t i = 0; i <= ph_ind - m_sensParams.size() + 1; i++){\n            vector<SensitivityParameter> sensParams;\n            m_sensParams.emplace_back(sensParams);\n        }\n    }\n    //vector<SensitivityParameter> curr_sensParams = m_sensParams[kin_ind];\n    m_sensParams[ph_ind].emplace_back(\n            SensitivityParameter{sp_ind, m_sens_params.size()-1, \n                                 ph->Hf298SS(sp_ind),\n                                 SensParameterType::enthalpy});\n\n    /*\n    size_t p = network().registerSensitivityParameter(\n        name()+\": \"+m_kin->reactionString(rxn), 1.0, 1.0);\n    m_sensParams.emplace_back(\n        SensitivityParameter{rxn, p, 1.0, SensParameterType::reaction});\n    */\n}\n\n\n/*\nvoid PFR1d::addSensitivitySpeciesEnthalpy(size_t k)\n{\n    if (k >= m_thermo->nSpecies()) {\n        throw CanteraError(\"Reactor::addSensitivitySpeciesEnthalpy\",\n                           \"Species index out of range ({})\", k);\n    }\n\n    size_t p = network().registerSensitivityParameter(\n        name() + \": \" + m_thermo->speciesName(k) + \" enthalpy\",\n        0.0, GasConstant * 298.15);\n    m_sensParams.emplace_back(\n        SensitivityParameter{k, p, m_thermo->Hf298SS(k),\n                             SensParameterType::enthalpy});\n}\n*/\n\nsize_t PFR1d::nSensParams()\n{\n    return m_sensParams.size();\n}\n\n//void PFR1d::applySensitivity(double* params)\nvoid PFR1d::applySensitivity()\n{\n    if (!nparams()) {\n        return;\n    }       \n    \n    for (auto& p : m_sensParams[0]) {\n        if (p.type == SensParameterType::reaction) {\n            p.value = m_gas->multiplier(p.local);\n            //double bias = ((params[p.global] == 1.0) ? 0.0 : 0.05);\n            //double bias = 0.0 ;\n            //m_gas->setMultiplier(p.local, p.value * (params[p.global] + bias));\n            //m_gas->setMultiplier(p.local, p.value * params[p.global]);\n            m_gas->setMultiplier(p.local, p.value * sensitivityParameter(p.global));\n        } else if (p.type == SensParameterType::enthalpy) {\n            m_gas->modifyOneHf298SS(p.local, p.value + sensitivityParameter(p.global));\n            //m_gas->modifyOneHf298SS(p.local, p.value + params[p.global]);\n        }       \n    }\n\n    for (size_t i = 0; i < m_surf_kins.size(); i++){\n        for (auto& p : m_sensParams[i+1]) {\n            if (p.type == SensParameterType::reaction) {\n                p.value = m_surf_kins[i]->multiplier(p.local);\n                //double bias = ((params[p.global] == 1.0) ? 0.0 : 0.05);\n                //double bias = 0.0 ;\n                //m_surf_kins[i]->setMultiplier(p.local, p.value * (params[p.global] + bias));\n                //m_surf_kins[i]->setMultiplier(p.local, p.value * params[p.global]);\n                m_surf_kins[i]->setMultiplier(p.local, p.value * sensitivityParameter(p.global));\n            } else if (p.type == SensParameterType::enthalpy) {\n                m_gas->modifyOneHf298SS(p.local, p.value + sensitivityParameter(p.global));\n            }\n        }\n    }\n\n    (dynamic_cast<Phase *>(m_gas))->invalidateCache();\n    //if (m_gas) {\n        (dynamic_cast<Kinetics *>(m_gas))->invalidateCache();\n    //}   \n}\n\nvoid PFR1d::resetSensitivity()\n{\n    if (!nparams()) {\n        return;\n    }   \n    for (auto& p : m_sensParams[0]) {\n        if (p.type == SensParameterType::reaction) {\n            m_gas->setMultiplier(p.local, p.value);\n        } else if (p.type == SensParameterType::enthalpy) {\n            m_gas->resetHf298(p.local);\n        }   \n    }           \n\n    for (size_t i = 0; i < m_surf_kins.size(); i++){\n        for (auto& p : m_sensParams[i+1]) {\n            m_surf_kins[i]->setMultiplier(p.local, p.value);\n        }\n    }\n\n    (dynamic_cast<Phase *>(m_gas))->invalidateCache();\n    //if (m_gas) {\n        (dynamic_cast<Kinetics *>(m_gas))->invalidateCache();\n    //}   \n}\n\n\n}\n", "meta": {"hexsha": "1725402da2b428a9392d2be87413cdc9eb0de264", "size": 25669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pfr1d.cpp", "max_stars_repo_name": "wittregr/openmkm", "max_stars_repo_head_hexsha": "58efabaffb4235641c079b86fe05afe356b3620d", "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/pfr1d.cpp", "max_issues_repo_name": "wittregr/openmkm", "max_issues_repo_head_hexsha": "58efabaffb4235641c079b86fe05afe356b3620d", "max_issues_repo_licenses": ["MIT"], "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/pfr1d.cpp", "max_forks_repo_name": "wittregr/openmkm", "max_forks_repo_head_hexsha": "58efabaffb4235641c079b86fe05afe356b3620d", "max_forks_repo_licenses": ["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.2274939173, "max_line_length": 122, "alphanum_fraction": 0.5452880907, "num_tokens": 7744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.18221789002603403}}
{"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// File generated at Thu 10 May 2018 14:30:07\n\n/**\n * @file MSSMatMGUT_mAmu_mass_eigenstates.hpp\n *\n * @brief contains class for model with routines needed to solve boundary\n *        value problem using the two_scale solver by solving EWSB\n *        and determine the pole masses and mixings\n *\n * This file was generated at Thu 10 May 2018 14:30:07 with FlexibleSUSY\n * 2.0.1 (git commit: unknown) and SARAH 4.12.2 .\n */\n\n#ifndef MSSMatMGUT_mAmu_MASS_EIGENSTATES_H\n#define MSSMatMGUT_mAmu_MASS_EIGENSTATES_H\n\n#include \"MSSMatMGUT_mAmu_info.hpp\"\n#include \"MSSMatMGUT_mAmu_physical.hpp\"\n#include \"MSSMatMGUT_mAmu_soft_parameters.hpp\"\n#include \"loop_corrections.hpp\"\n#include \"threshold_corrections.hpp\"\n#include \"error.hpp\"\n#include \"problems.hpp\"\n#include \"config.h\"\n\n#include <iosfwd>\n#include <memory>\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass MSSMatMGUT_mAmu_ewsb_solver_interface;\n/**\n * @class MSSMatMGUT_mAmu_mass_eigenstates\n * @brief model class with routines for determing masses and mixinga and EWSB\n */\nclass MSSMatMGUT_mAmu_mass_eigenstates : public MSSMatMGUT_mAmu_soft_parameters {\npublic:\n   explicit MSSMatMGUT_mAmu_mass_eigenstates(const MSSMatMGUT_mAmu_input_parameters& input_ = MSSMatMGUT_mAmu_input_parameters());\n   MSSMatMGUT_mAmu_mass_eigenstates(const MSSMatMGUT_mAmu_mass_eigenstates&) = default;\n   MSSMatMGUT_mAmu_mass_eigenstates(MSSMatMGUT_mAmu_mass_eigenstates&&) = default;\n   virtual ~MSSMatMGUT_mAmu_mass_eigenstates() = default;\n   MSSMatMGUT_mAmu_mass_eigenstates& operator=(const MSSMatMGUT_mAmu_mass_eigenstates&) = default;\n   MSSMatMGUT_mAmu_mass_eigenstates& operator=(MSSMatMGUT_mAmu_mass_eigenstates&&) = default;\n\n   /// number of EWSB equations\n   static const int number_of_ewsb_equations = 2;\n\n   void calculate_DRbar_masses();\n   void calculate_pole_masses();\n   void check_pole_masses_for_tachyons();\n   virtual void clear() override;\n   void clear_DRbar_parameters();\n   Eigen::ArrayXd get_DRbar_masses() const;\n   Eigen::ArrayXd get_DRbar_masses_and_mixings() const;\n   Eigen::ArrayXd get_extra_parameters() const;\n   void do_calculate_sm_pole_masses(bool);\n   bool do_calculate_sm_pole_masses() const;\n   void do_calculate_bsm_pole_masses(bool);\n   bool do_calculate_bsm_pole_masses() const;\n   void do_force_output(bool);\n   bool do_force_output() const;\n   void reorder_DRbar_masses();\n   void reorder_pole_masses();\n   void set_ewsb_iteration_precision(double);\n   void set_ewsb_loop_order(int);\n   void set_loop_corrections(const Loop_corrections&);\n   const Loop_corrections& get_loop_corrections() const;\n   void set_threshold_corrections(const Threshold_corrections&);\n   const Threshold_corrections& get_threshold_corrections() const;\n   void set_DRbar_masses(const Eigen::ArrayXd&);\n   void set_DRbar_masses_and_mixings(const Eigen::ArrayXd&);\n   void set_extra_parameters(const Eigen::ArrayXd&);\n   void set_pole_mass_loop_order(int);\n   int get_pole_mass_loop_order() const;\n   void set_physical(const MSSMatMGUT_mAmu_physical&);\n   double get_ewsb_iteration_precision() const;\n   double get_ewsb_loop_order() const;\n   const MSSMatMGUT_mAmu_physical& get_physical() const;\n   MSSMatMGUT_mAmu_physical& get_physical();\n   const Problems& get_problems() const;\n   Problems& get_problems();\n   void set_ewsb_solver(const std::shared_ptr<MSSMatMGUT_mAmu_ewsb_solver_interface>&);\n   int solve_ewsb_tree_level();\n   int solve_ewsb_one_loop();\n   int solve_ewsb();            ///< solve EWSB at ewsb_loop_order level\n\n   void calculate_spectrum();\n   void clear_problems();\n   std::string name() const;\n   void run_to(double scale, double eps = -1.0) override;\n   void print(std::ostream& out = std::cerr) const override;\n   void set_precision(double);\n   double get_precision() const;\n\n   double get_lsp(MSSMatMGUT_mAmu_info::Particles&) const;\n\n   double get_MVG() const { return MVG; }\n   double get_MGlu() const { return MGlu; }\n   const Eigen::Array<double,3,1>& get_MFv() const { return MFv; }\n   double get_MFv(int i) const { return MFv(i); }\n   const Eigen::Array<double,6,1>& get_MSd() const { return MSd; }\n   double get_MSd(int i) const { return MSd(i); }\n   const Eigen::Array<double,3,1>& get_MSv() const { return MSv; }\n   double get_MSv(int i) const { return MSv(i); }\n   const Eigen::Array<double,6,1>& get_MSu() const { return MSu; }\n   double get_MSu(int i) const { return MSu(i); }\n   const Eigen::Array<double,6,1>& get_MSe() const { return MSe; }\n   double get_MSe(int i) const { return MSe(i); }\n   const Eigen::Array<double,2,1>& get_Mhh() const { return Mhh; }\n   double get_Mhh(int i) const { return Mhh(i); }\n   const Eigen::Array<double,2,1>& get_MAh() const { return MAh; }\n   double get_MAh(int i) const { return MAh(i); }\n   const Eigen::Array<double,2,1>& get_MHpm() const { return MHpm; }\n   double get_MHpm(int i) const { return MHpm(i); }\n   const Eigen::Array<double,4,1>& get_MChi() const { return MChi; }\n   double get_MChi(int i) const { return MChi(i); }\n   const Eigen::Array<double,2,1>& get_MCha() const { return MCha; }\n   double get_MCha(int i) const { return MCha(i); }\n   const Eigen::Array<double,3,1>& get_MFe() const { return MFe; }\n   double get_MFe(int i) const { return MFe(i); }\n   const Eigen::Array<double,3,1>& get_MFd() const { return MFd; }\n   double get_MFd(int i) const { return MFd(i); }\n   const Eigen::Array<double,3,1>& get_MFu() const { return MFu; }\n   double get_MFu(int i) const { return MFu(i); }\n   double get_MVWm() const { return MVWm; }\n   double get_MVP() const { return MVP; }\n   double get_MVZ() const { return MVZ; }\n\n   \n   Eigen::Array<double,1,1> get_MChargedHiggs() const;\n\n   Eigen::Array<double,1,1> get_MPseudoscalarHiggs() const;\n\n   const Eigen::Matrix<double,6,6>& get_ZD() const { return ZD; }\n   double get_ZD(int i, int k) const { return ZD(i,k); }\n   const Eigen::Matrix<double,3,3>& get_ZV() const { return ZV; }\n   double get_ZV(int i, int k) const { return ZV(i,k); }\n   const Eigen::Matrix<double,6,6>& get_ZU() const { return ZU; }\n   double get_ZU(int i, int k) const { return ZU(i,k); }\n   const Eigen::Matrix<double,6,6>& get_ZE() const { return ZE; }\n   double get_ZE(int i, int k) const { return ZE(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZH() const { return ZH; }\n   double get_ZH(int i, int k) const { return ZH(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZA() const { return ZA; }\n   double get_ZA(int i, int k) const { return ZA(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZP() const { return ZP; }\n   double get_ZP(int i, int k) const { return ZP(i,k); }\n   const Eigen::Matrix<std::complex<double>,4,4>& get_ZN() const { return ZN; }\n   std::complex<double> get_ZN(int i, int k) const { return ZN(i,k); }\n   const Eigen::Matrix<std::complex<double>,2,2>& get_UM() const { return UM; }\n   std::complex<double> get_UM(int i, int k) const { return UM(i,k); }\n   const Eigen::Matrix<std::complex<double>,2,2>& get_UP() const { return UP; }\n   std::complex<double> get_UP(int i, int k) const { return UP(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZEL() const { return ZEL; }\n   std::complex<double> get_ZEL(int i, int k) const { return ZEL(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZER() const { return ZER; }\n   std::complex<double> get_ZER(int i, int k) const { return ZER(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZDL() const { return ZDL; }\n   std::complex<double> get_ZDL(int i, int k) const { return ZDL(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZDR() const { return ZDR; }\n   std::complex<double> get_ZDR(int i, int k) const { return ZDR(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZUL() const { return ZUL; }\n   std::complex<double> get_ZUL(int i, int k) const { return ZUL(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ZUR() const { return ZUR; }\n   std::complex<double> get_ZUR(int i, int k) const { return ZUR(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZZ() const { return ZZ; }\n   double get_ZZ(int i, int k) const { return ZZ(i,k); }\n\n   void set_PhaseGlu(std::complex<double> PhaseGlu_) { PhaseGlu = PhaseGlu_; }\n   std::complex<double> get_PhaseGlu() const { return PhaseGlu; }\n\n\n\n   double get_mass_matrix_VG() const;\n   void calculate_MVG();\n   double get_mass_matrix_Glu() const;\n   void calculate_MGlu();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fv() const;\n   void calculate_MFv();\n   Eigen::Matrix<double,6,6> get_mass_matrix_Sd() const;\n   void calculate_MSd();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Sv() const;\n   void calculate_MSv();\n   Eigen::Matrix<double,6,6> get_mass_matrix_Su() const;\n   void calculate_MSu();\n   Eigen::Matrix<double,6,6> get_mass_matrix_Se() const;\n   void calculate_MSe();\n   Eigen::Matrix<double,2,2> get_mass_matrix_hh() const;\n   void calculate_Mhh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Ah() const;\n   void calculate_MAh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Hpm() const;\n   void calculate_MHpm();\n   Eigen::Matrix<double,4,4> get_mass_matrix_Chi() const;\n   void calculate_MChi();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Cha() const;\n   void calculate_MCha();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fe() const;\n   void calculate_MFe();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fd() const;\n   void calculate_MFd();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fu() const;\n   void calculate_MFu();\n   double get_mass_matrix_VWm() const;\n   void calculate_MVWm();\n   Eigen::Matrix<double,2,2> get_mass_matrix_VPVZ() const;\n   void calculate_MVPVZ();\n\n   double get_ewsb_eq_hh_1() const;\n   double get_ewsb_eq_hh_2() const;\n\n   std::complex<double> CpUSdconjUSdVZVZ(int gO1, int gO2) const;\n   double CpUSdconjUSdconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUSdconjUSd(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSdconjUSd(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSdconjHpmconjUSd(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSdSvconjUSdconjSv(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpChaFuconjUSdPR(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpChaFuconjUSdPL(int gI2, int gI1, int gO1) const;\n   std::complex<double> CpChiFdconjUSdPR(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpChiFdconjUSdPL(int gI2, int gI1, int gO1) const;\n   std::complex<double> CpUSdconjUSdconjSdSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSdconjUSdconjSuSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSdSeconjUSdconjSe(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhSdconjUSd(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSdconjUSd(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpHpmSuconjUSd(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpGluFdconjUSdPR(int gI2, int gO2) const;\n   std::complex<double> CpGluFdconjUSdPL(int gI2, int gO1) const;\n   std::complex<double> CpSdconjUSdVG(int gI2, int gO2) const;\n   std::complex<double> CpSdconjUSdVP(int gI2, int gO2) const;\n   std::complex<double> CpSdconjUSdVZ(int gI2, int gO2) const;\n   std::complex<double> CpSuconjUSdVWm(int gI2, int gO2) const;\n   std::complex<double> CpUSvconjUSvVZVZ(int gO1, int gO2) const;\n   double CpUSvconjUSvconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUSvconjUSv(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSvconjUSv(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSvconjHpmconjUSv(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpbarChaFeconjUSvPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarChaFeconjUSvPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpSeconjHpmconjUSv(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSvUSvconjSvconjUSv(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CphhSvconjUSv(int gI2, int gI1, int gO2) const;\n   double CpChiFvconjUSvPR(int , int , int ) const;\n   std::complex<double> CpChiFvconjUSvPL(int gI2, int gI1, int gO1) const;\n   std::complex<double> CpSdUSvconjSdconjUSv(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSeUSvconjSeconjUSv(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSuUSvconjSuconjUSv(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSvconjUSvVZ(int gI2, int gO2) const;\n   std::complex<double> CpSeconjUSvconjVWm(int gI2, int gO2) const;\n   std::complex<double> CpUSuconjUSuVZVZ(int gO1, int gO2) const;\n   double CpUSuconjUSuconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUSuconjUSu(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSuconjUSu(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSuconjHpmconjUSu(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpbarChaFdconjUSuPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarChaFdconjUSuPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpSdconjHpmconjUSu(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpUSuSvconjUSuconjSv(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpChiFuconjUSuPR(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpChiFuconjUSuPL(int gI2, int gI1, int gO1) const;\n   std::complex<double> CpSeUSuconjSeconjUSu(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSuconjUSuconjSdSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSuconjUSuconjSuSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpAhSuconjUSu(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSuconjUSu(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpGluFuconjUSuPR(int gI2, int gO2) const;\n   std::complex<double> CpGluFuconjUSuPL(int gI2, int gO1) const;\n   std::complex<double> CpSdconjUSuconjVWm(int gI2, int gO2) const;\n   std::complex<double> CpSuconjUSuVG(int gI2, int gO2) const;\n   std::complex<double> CpSuconjUSuVP(int gI2, int gO2) const;\n   std::complex<double> CpSuconjUSuVZ(int gI2, int gO2) const;\n   std::complex<double> CpUSeconjUSeVZVZ(int gO1, int gO2) const;\n   double CpUSeconjUSeconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUSeconjUSe(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSeconjUSe(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSeconjHpmconjUSe(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSeSvconjUSeconjSv(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpHpmSvconjUSe(int gI2, int gI1, int gO2) const;\n   double CpChaFvconjUSePR(int , int , int ) const;\n   std::complex<double> CpChaFvconjUSePL(int gI2, int gI1, int gO1) const;\n   std::complex<double> CpChiFeconjUSePR(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpChiFeconjUSePL(int gI2, int gI1, int gO1) const;\n   std::complex<double> CpSdUSeconjSdconjUSe(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSeUSeconjSeconjUSe(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSeSuconjUSeconjSu(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhSeconjUSe(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSeconjUSe(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSvconjUSeVWm(int gI2, int gO2) const;\n   std::complex<double> CpSeconjUSeVP(int gI2, int gO2) const;\n   std::complex<double> CpSeconjUSeVZ(int gI2, int gO2) const;\n   std::complex<double> CpbargWmgWmUhh(int gO1) const;\n   std::complex<double> CpbargWmCgWmCUhh(int gO1) const;\n   std::complex<double> CpbargZgZUhh(int gO1) const;\n   std::complex<double> CpUhhVZVZ(int gO2) const;\n   std::complex<double> CpUhhconjVWmVWm(int gO2) const;\n   std::complex<double> CpUhhUhhVZVZ(int gO1, int gO2) const;\n   std::complex<double> CpUhhUhhconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUhhUhh(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUhhUhh(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpUhhUhhHpmconjHpm(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpAhAhUhh(int gI1, int gI2, int gO2) const;\n   std::complex<double> CphhhhUhh(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpUhhHpmconjHpm(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarChaChaUhhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarChaChaUhhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpUhhUhhSvconjSv(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhSvconjSv(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFdFdUhhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarFdFdUhhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpbarFeFeUhhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarFeFeUhhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpbarFuFuUhhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarFuFuUhhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpChiChiUhhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpChiChiUhhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpUhhUhhSdconjSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhSeconjSe(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhSuconjSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhSdconjSd(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhSeconjSe(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhSuconjSu(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpAhUhhVZ(int gI2, int gO2) const;\n   std::complex<double> CpUhhHpmconjVWm(int gO2, int gI2) const;\n   std::complex<double> CpbargWmgWmUAh(int gO1) const;\n   std::complex<double> CpbargWmCgWmCUAh(int gO1) const;\n   std::complex<double> CpUAhUAhVZVZ(int gO1, int gO2) const;\n   std::complex<double> CpUAhUAhconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUAhUAh(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpUAhUAhhhhh(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhHpmconjHpm(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpAhUAhhh(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpUAhHpmconjHpm(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarChaChaUAhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarChaChaUAhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpUAhUAhSvconjSv(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarFdFdUAhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarFdFdUAhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpbarFeFeUAhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarFeFeUAhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpbarFuFuUAhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarFuFuUAhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpChiChiUAhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpChiChiUAhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpUAhUAhSdconjSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhSeconjSe(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhSuconjSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhSdconjSd(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhSeconjSe(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhSuconjSu(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhhhVZ(int gO2, int gI2) const;\n   std::complex<double> CpUAhHpmconjVWm(int gO2, int gI2) const;\n   std::complex<double> CpbargWmgZUHpm(int gO2) const;\n   std::complex<double> CpbargZgWmconjUHpm(int gO1) const;\n   std::complex<double> CpbargWmCgZconjUHpm(int gO1) const;\n   std::complex<double> CpbargZgWmCUHpm(int gO2) const;\n   std::complex<double> CpconjUHpmVPVWm(int gO2) const;\n   std::complex<double> CpconjUHpmVWmVZ(int gO2) const;\n   std::complex<double> CpUHpmconjUHpmVZVZ(int gO1, int gO2) const;\n   std::complex<double> CpUHpmconjUHpmconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUHpmconjUHpm(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUHpmconjUHpm(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUHpmconjHpmconjUHpm(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpAhHpmconjUHpm(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhHpmconjUHpm(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpUHpmSvconjUHpmconjSv(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpbarFuFdconjUHpmPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarFuFdconjUHpmPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpbarFvFeconjUHpmPR(int gI1, int gI2, int gO2) const;\n   double CpbarFvFeconjUHpmPL(int , int , int ) const;\n   std::complex<double> CpSeconjUHpmconjSv(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpChiChaconjUHpmPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpChiChaconjUHpmPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpUHpmSdconjUHpmconjSd(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmSeconjUHpmconjSe(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmSuconjUHpmconjSu(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpSdconjUHpmconjSu(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpAhconjUHpmVWm(int gI2, int gO2) const;\n   std::complex<double> CphhconjUHpmVWm(int gI2, int gO2) const;\n   std::complex<double> CpHpmconjUHpmVP(int gI2, int gO2) const;\n   std::complex<double> CpHpmconjUHpmVZ(int gI2, int gO2) const;\n   std::complex<double> CpVGVGVG() const;\n   std::complex<double> CpbargGgGVG() const;\n   double CpbarFdFdVGPL(int gI1, int gI2) const;\n   double CpbarFdFdVGPR(int gI1, int gI2) const;\n   double CpbarFuFuVGPL(int gI1, int gI2) const;\n   double CpbarFuFuVGPR(int gI1, int gI2) const;\n   double CpSdconjSdVGVG(int gI1, int gI2) const;\n   double CpSuconjSuVGVG(int gI1, int gI2) const;\n   double CpSdconjSdVG(int gI2, int gI1) const;\n   double CpSuconjSuVG(int gI2, int gI1) const;\n   std::complex<double> CpGluGluVGPL() const;\n   std::complex<double> CpGluGluVGPR() const;\n   double CpVGVGVGVG1() const;\n   double CpVGVGVGVG2() const;\n   double CpVGVGVGVG3() const;\n   double CpbargWmgWmVP() const;\n   double CpbargWmCgWmCVP() const;\n   double CpconjVWmVPVWm() const;\n   std::complex<double> CpHpmconjHpmVPVP(int gI1, int gI2) const;\n   double CpHpmconjHpmVP(int gI2, int gI1) const;\n   std::complex<double> CpbarChaChaVPPL(int gI1, int gI2) const;\n   std::complex<double> CpbarChaChaVPPR(int gI1, int gI2) const;\n   double CpbarFdFdVPPL(int gI1, int gI2) const;\n   double CpbarFdFdVPPR(int gI1, int gI2) const;\n   double CpbarFeFeVPPL(int gI1, int gI2) const;\n   double CpbarFeFeVPPR(int gI1, int gI2) const;\n   double CpbarFuFuVPPL(int gI1, int gI2) const;\n   double CpbarFuFuVPPR(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSeconjSeVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSuconjSuVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdVP(int gI2, int gI1) const;\n   std::complex<double> CpSeconjSeVP(int gI2, int gI1) const;\n   std::complex<double> CpSuconjSuVP(int gI2, int gI1) const;\n   std::complex<double> CpHpmconjVWmVP(int gI2) const;\n   double CpconjVWmVPVPVWm1() const;\n   double CpconjVWmVPVPVWm2() const;\n   double CpconjVWmVPVPVWm3() const;\n   double CpbargWmgWmVZ() const;\n   double CpbargWmCgWmCVZ() const;\n   double CpconjVWmVWmVZ() const;\n   std::complex<double> CpAhAhVZVZ(int gI1, int gI2) const;\n   std::complex<double> CphhhhVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpHpmconjHpmVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpAhhhVZ(int gI2, int gI1) const;\n   double CpHpmconjHpmVZ(int gI2, int gI1) const;\n   std::complex<double> CpbarChaChaVZPL(int gI1, int gI2) const;\n   std::complex<double> CpbarChaChaVZPR(int gI1, int gI2) const;\n   std::complex<double> CpSvconjSvVZVZ(int gI1, int gI2) const;\n   double CpSvconjSvVZ(int gI2, int gI1) const;\n   double CpbarFdFdVZPL(int gI1, int gI2) const;\n   double CpbarFdFdVZPR(int gI1, int gI2) const;\n   double CpbarFeFeVZPL(int gI1, int gI2) const;\n   double CpbarFeFeVZPR(int gI1, int gI2) const;\n   double CpbarFuFuVZPL(int gI1, int gI2) const;\n   double CpbarFuFuVZPR(int gI1, int gI2) const;\n   double CpbarFvFvVZPL(int gI1, int gI2) const;\n   double CpbarFvFvVZPR(int , int ) const;\n   std::complex<double> CpChiChiVZPL(int gI1, int gI2) const;\n   std::complex<double> CpChiChiVZPR(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSeconjSeVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSuconjSuVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdVZ(int gI2, int gI1) const;\n   std::complex<double> CpSeconjSeVZ(int gI2, int gI1) const;\n   std::complex<double> CpSuconjSuVZ(int gI2, int gI1) const;\n   std::complex<double> CphhVZVZ(int gI2) const;\n   std::complex<double> CpHpmconjVWmVZ(int gI2) const;\n   double CpconjVWmVWmVZVZ1() const;\n   double CpconjVWmVWmVZVZ2() const;\n   double CpconjVWmVWmVZVZ3() const;\n   double CpbargPgWmconjVWm() const;\n   double CpbargWmCgPconjVWm() const;\n   double CpbargWmCgZconjVWm() const;\n   double CpbargZgWmconjVWm() const;\n   std::complex<double> CpAhAhconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CphhhhconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpHpmconjHpmconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpAhHpmconjVWm(int gI2, int gI1) const;\n   std::complex<double> CphhHpmconjVWm(int gI2, int gI1) const;\n   double CpSvconjSvconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpbarFuFdconjVWmPL(int gI1, int gI2) const;\n   double CpbarFuFdconjVWmPR(int , int ) const;\n   std::complex<double> CpbarFvFeconjVWmPL(int gI1, int gI2) const;\n   double CpbarFvFeconjVWmPR(int , int ) const;\n   std::complex<double> CpSeconjSvconjVWm(int gI2, int gI1) const;\n   std::complex<double> CpChiChaconjVWmPL(int gI1, int gI2) const;\n   std::complex<double> CpChiChaconjVWmPR(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSeconjSeconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSuconjSuconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSuconjVWm(int gI2, int gI1) const;\n   std::complex<double> CphhconjVWmVWm(int gI2) const;\n   double CpconjVWmconjVWmVWmVWm1() const;\n   double CpconjVWmconjVWmVWmVWm2() const;\n   double CpconjVWmconjVWmVWmVWm3() const;\n   std::complex<double> CpbarChaUChiHpmPL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpbarChaUChiHpmPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpUChiChaconjHpmPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUChiChaconjHpmPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpChiUChihhPL(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpChiUChihhPR(int gI2, int gO1, int gI1) const;\n   std::complex<double> CpbarChaUChiVWmPL(int gI1, int gO2) const;\n   std::complex<double> CpbarChaUChiVWmPR(int gI1, int gO1) const;\n   double CpbarFvUChiSvPL(int , int , int ) const;\n   std::complex<double> CpbarFvUChiSvPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpUChiFvconjSvPL(int gO2, int gI2, int gI1) const;\n   double CpUChiFvconjSvPR(int , int , int ) const;\n   std::complex<double> CpbarFdUChiSdPL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpbarFdUChiSdPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpbarFeUChiSePL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpbarFeUChiSePR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpbarFuUChiSuPL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpbarFuUChiSuPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpChiUChiAhPL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpChiUChiAhPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpUChiFdconjSdPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUChiFdconjSdPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpUChiFeconjSePL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUChiFeconjSePR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpUChiFuconjSuPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUChiFuconjSuPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpUChiChaconjVWmPR(int gO2, int gI2) const;\n   std::complex<double> CpUChiChaconjVWmPL(int gO1, int gI2) const;\n   std::complex<double> CpChiUChiVZPL(int gI2, int gO2) const;\n   std::complex<double> CpChiUChiVZPR(int gI2, int gO1) const;\n   std::complex<double> CpbarUChaChaAhPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarUChaChaAhPR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarUChaChahhPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaChahhPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaChiHpmPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaChiHpmPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaFeconjSvPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaFeconjSvPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUChabarFuSdPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarUChabarFuSdPR(int gO1, int gI1, int gI2) const;\n   double CpbarUChabarFvSePL(int , int , int ) const;\n   std::complex<double> CpbarUChabarFvSePR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarUChaFdconjSuPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaFdconjSuPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaChaVPPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUChaChaVPPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUChaChaVZPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUChaChaVZPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUChaChiVWmPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUChaChiVWmPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeFehhPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFeFehhPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFeFvHpmPL(int gO2, int gI2, int gI1) const;\n   double CpbarUFeFvHpmPR(int , int , int ) const;\n   std::complex<double> CpbarUFeChaSvPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFeChaSvPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFeFeAhPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarUFeFeAhPR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarUFeChiSePL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFeChiSePR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFeFeVPPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFeFeVPPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeFeVZPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFeFeVZPL(int gO1, int gI2) const;\n   double CpbarUFeFvVWmPR(int , int ) const;\n   double CpbarUFeFvVWmPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdFdhhPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFdFdhhPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFdFuHpmPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFdFuHpmPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFdFdAhPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarUFdFdAhPR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarUFdChaSuPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFdChaSuPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFdChiSdPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFdChiSdPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFdGluSdPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUFdGluSdPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUFdFdVGPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdFdVGPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdFdVPPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdFdVPPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdFdVZPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdFdVZPL(int gO1, int gI2) const;\n   double CpbarUFdFuVWmPR(int , int ) const;\n   std::complex<double> CpbarUFdFuVWmPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFdconjHpmPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFuFdconjHpmPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFuFuhhPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFuFuhhPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarChabarUFuSdPL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpbarChabarUFuSdPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuAhPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarUFuFuAhPR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarUFuChiSuPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUFuChiSuPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUFuGluSuPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUFuGluSuPR(int gO1, int gI1) const;\n   double CpbarUFuFdconjVWmPR(int , int ) const;\n   std::complex<double> CpbarUFuFdconjVWmPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuVGPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuFuVGPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuVPPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuFuVPPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuVZPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuFuVZPL(int gO1, int gI2) const;\n   std::complex<double> CpbarFdGluSdPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFdGluSdPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFuGluSuPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFuGluSuPR(int gI1, int gI2) const;\n   std::complex<double> CpGluFdconjSdPL(int gI2, int gI1) const;\n   std::complex<double> CpGluFdconjSdPR(int gI2, int gI1) const;\n   std::complex<double> CpGluFuconjSuPL(int gI2, int gI1) const;\n   std::complex<double> CpGluFuconjSuPR(int gI2, int gI1) const;\n   double CpbarFvFeconjHpmPL(int , int , int ) const;\n   std::complex<double> CpbarFvFeconjHpmPR(int gO1, int gI2, int gI1) const;\n   double CpbarChabarFvSePL(int , int , int ) const;\n   std::complex<double> CpbarChabarFvSePR(int gI1, int gO1, int gI2) const;\n   double CpbarFvChiSvPL(int , int , int ) const;\n   std::complex<double> CpbarFvChiSvPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarFeFehhPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFeFehhPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarFeFvHpmPL(int gO2, int gI2, int gI1) const;\n   double CpbarFeFvHpmPR(int , int , int ) const;\n   std::complex<double> CpbarFeChaSvPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFeChaSvPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarFeFeAhPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarFeFeAhPR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarFeChiSePL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFeChiSePR(int gO1, int gI2, int gI1) const;\n   double CpbarFeFvVWmPR(int , int ) const;\n   std::complex<double> CpbarFeFvVWmPL(int gO1, int gI2) const;\n   std::complex<double> CpbarFdFdhhPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFdFdhhPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarFdFuHpmPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFdFuHpmPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarFdFdAhPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarFdFdAhPR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarFdChaSuPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFdChaSuPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarFdChiSdPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFdChiSdPR(int gO1, int gI2, int gI1) const;\n   double CpbarFdFuVWmPR(int , int ) const;\n   std::complex<double> CpbarFdFuVWmPL(int gO1, int gI2) const;\n   std::complex<double> CpbarFuFdconjHpmPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFuFdconjHpmPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarFuFuhhPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFuFuhhPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarChabarFuSdPL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpbarChabarFuSdPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpbarFuFuAhPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarFuFuAhPR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarFuChiSuPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarFuChiSuPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> self_energy_Sd_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,6,6> self_energy_Sd_1loop(double p) const;\n   std::complex<double> self_energy_Sv_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Sv_1loop(double p) const;\n   std::complex<double> self_energy_Su_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,6,6> self_energy_Su_1loop(double p) const;\n   std::complex<double> self_energy_Se_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,6,6> self_energy_Se_1loop(double p) const;\n   std::complex<double> self_energy_hh_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_hh_1loop(double p) const;\n   std::complex<double> self_energy_Ah_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Ah_1loop(double p) const;\n   std::complex<double> self_energy_Hpm_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Hpm_1loop(double p) const;\n   std::complex<double> self_energy_VG_1loop(double p ) const;\n   std::complex<double> self_energy_VP_1loop(double p ) const;\n   std::complex<double> self_energy_VZ_1loop(double p ) const;\n   std::complex<double> self_energy_VWm_1loop(double p ) const;\n   std::complex<double> self_energy_Chi_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,4,4> self_energy_Chi_1loop_1(double p) const;\n   std::complex<double> self_energy_Chi_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,4,4> self_energy_Chi_1loop_PR(double p) const;\n   std::complex<double> self_energy_Chi_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,4,4> self_energy_Chi_1loop_PL(double p) const;\n   std::complex<double> self_energy_Cha_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Cha_1loop_1(double p) const;\n   std::complex<double> self_energy_Cha_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Cha_1loop_PR(double p) const;\n   std::complex<double> self_energy_Cha_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Cha_1loop_PL(double p) const;\n   std::complex<double> self_energy_Fe_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_1(double p) const;\n   std::complex<double> self_energy_Fe_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PR(double p) const;\n   std::complex<double> self_energy_Fe_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PL(double p) const;\n   std::complex<double> self_energy_Fd_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_1(double p) const;\n   std::complex<double> self_energy_Fd_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PR(double p) const;\n   std::complex<double> self_energy_Fd_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PL(double p) const;\n   std::complex<double> self_energy_Fu_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_1(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PR(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PL(double p) const;\n   std::complex<double> self_energy_Glu_1loop_1(double p ) const;\n   std::complex<double> self_energy_Glu_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Glu_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fv_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fv_1loop_1(double p) const;\n   std::complex<double> self_energy_Fv_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fv_1loop_PR(double p) const;\n   std::complex<double> self_energy_Fv_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fv_1loop_PL(double p) const;\n   std::complex<double> self_energy_Fe_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_1_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fe_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PR_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fe_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PL_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fd_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_1_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fd_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PR_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fd_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PL_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fu_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_1_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PR_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PL_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fu_1loop_1_heavy(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_1_heavy(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PR_heavy(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PR_heavy(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PL_heavy(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PL_heavy(double p) const;\n   std::complex<double> tadpole_hh_1loop(int gO1) const;\n\n\n   /// calculates the tadpoles at current loop order\n   void tadpole_equations(double[number_of_ewsb_equations]) const;\n   /// calculates the tadpoles at current loop order\n   Eigen::Matrix<double,number_of_ewsb_equations,1> tadpole_equations() const;\n   /// calculates the tadpoles divided by VEVs at current loop order\n   Eigen::Matrix<double,number_of_ewsb_equations,1> tadpole_equations_over_vevs() const;\n\n   void calculate_MSu_2nd_generation(double&, double&, double&) const;\n   void calculate_MSd_2nd_generation(double&, double&, double&) const;\n   void calculate_MSv_2nd_generation(double&, double&, double&) const;\n   void calculate_MSe_2nd_generation(double&, double&, double&) const;\n\n   void calculate_MSu_3rd_generation(double&, double&, double&) const;\n   void calculate_MSd_3rd_generation(double&, double&, double&) const;\n   void calculate_MSv_3rd_generation(double&, double&, double&) const;\n   void calculate_MSe_3rd_generation(double&, double&, double&) const;\n\n   Eigen::Matrix<double,2,2> self_energy_hh_2loop() const;\n   Eigen::Matrix<double,2,2> self_energy_Ah_2loop() const;\n\n   Eigen::Matrix<double,2,1> tadpole_hh_2loop() const;\n\n\n   void calculate_MVG_pole();\n   void calculate_MGlu_pole();\n   void calculate_MFv_pole();\n   void calculate_MVP_pole();\n   void calculate_MVZ_pole();\n   void calculate_MSd_pole();\n   void calculate_MSv_pole();\n   void calculate_MSu_pole();\n   void calculate_MSe_pole();\n   void calculate_Mhh_pole();\n   void calculate_MAh_pole();\n   void calculate_MHpm_pole();\n   void calculate_MChi_pole();\n   void calculate_MCha_pole();\n   void calculate_MFe_pole();\n   void calculate_MFd_pole();\n   void calculate_MFu_pole();\n   void calculate_MVWm_pole();\n   double calculate_MVWm_pole(double);\n   double calculate_MVZ_pole(double);\n\n   double calculate_MFv_DRbar(double, int) const;\n   double calculate_MFe_DRbar(double, int) const;\n   double calculate_MFu_DRbar(double, int) const;\n   double calculate_MFd_DRbar(double, int) const;\n   double calculate_MVP_DRbar(double);\n   double calculate_MVZ_DRbar(double);\n   double calculate_MVWm_DRbar(double);\n\n   double v() const;\n   double Betax() const;\n   double Alpha() const;\n   double ThetaW() const;\n\n\nprivate:\n   int ewsb_loop_order{2};           ///< loop order for EWSB\n   int pole_mass_loop_order{2};      ///< loop order for pole masses\n   bool calculate_sm_pole_masses{false};  ///< switch to calculate the pole masses of the Standard Model particles\n   bool calculate_bsm_pole_masses{true};  ///< switch to calculate the pole masses of the BSM particles\n   bool force_output{false};              ///< switch to force output of pole masses\n   double precision{1.e-3};               ///< RG running precision\n   double ewsb_iteration_precision{1.e-5};///< precision goal of EWSB solution\n   MSSMatMGUT_mAmu_physical physical{}; ///< contains the pole masses and mixings\n   Problems problems{MSSMatMGUT_mAmu_info::model_name,\n                     &MSSMatMGUT_mAmu_info::particle_names_getter,\n                     &MSSMatMGUT_mAmu_info::parameter_names_getter}; ///< problems\n   Loop_corrections loop_corrections{}; ///< used pole mass corrections\n   std::shared_ptr<MSSMatMGUT_mAmu_ewsb_solver_interface> ewsb_solver{};\n   Threshold_corrections threshold_corrections{}; ///< used threshold corrections\n\n   int get_number_of_ewsb_iterations() const;\n   int get_number_of_mass_iterations() const;\n   int solve_ewsb_tree_level_custom();\n   void copy_DRbar_masses_to_pole_masses();\n\n   // Passarino-Veltman loop functions\n   double A0(double) const noexcept;\n   double B0(double, double, double) const noexcept;\n   double B1(double, double, double) const noexcept;\n   double B00(double, double, double) const noexcept;\n   double B22(double, double, double) const noexcept;\n   double H0(double, double, double) const noexcept;\n   double F0(double, double, double) const noexcept;\n   double G0(double, double, double) const noexcept;\n\n   // DR-bar masses\n   double MVG{};\n   double MGlu{};\n   Eigen::Array<double,3,1> MFv{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,6,1> MSd{Eigen::Array<double,6,1>::Zero()};\n   Eigen::Array<double,3,1> MSv{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,6,1> MSu{Eigen::Array<double,6,1>::Zero()};\n   Eigen::Array<double,6,1> MSe{Eigen::Array<double,6,1>::Zero()};\n   Eigen::Array<double,2,1> Mhh{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MAh{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MHpm{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,4,1> MChi{Eigen::Array<double,4,1>::Zero()};\n   Eigen::Array<double,2,1> MCha{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,3,1> MFe{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,3,1> MFd{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,3,1> MFu{Eigen::Array<double,3,1>::Zero()};\n   double MVWm{};\n   double MVP{};\n   double MVZ{};\n\n   // DR-bar mixing matrices\n   Eigen::Matrix<double,6,6> ZD{Eigen::Matrix<double,6,6>::Zero()};\n   Eigen::Matrix<double,3,3> ZV{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,6,6> ZU{Eigen::Matrix<double,6,6>::Zero()};\n   Eigen::Matrix<double,6,6> ZE{Eigen::Matrix<double,6,6>::Zero()};\n   Eigen::Matrix<double,2,2> ZH{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZA{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZP{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,4,4> ZN{Eigen::Matrix<std::complex<double>,4,4>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UM{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UP{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZEL{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZER{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZDL{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZDR{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZUL{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZUR{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<double,2,2> ZZ{Eigen::Matrix<double,2,2>::Zero()};\n\n   // phases\n   std::complex<double> PhaseGlu{1.,0.};\n\n   // extra parameters\n\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMatMGUT_mAmu_mass_eigenstates&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "1021e108bd134ded66051e75c23816470e919770", "size": 52195, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMatMGUT_mAmu/MSSMatMGUT_mAmu_mass_eigenstates.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMatMGUT_mAmu/MSSMatMGUT_mAmu_mass_eigenstates.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMatMGUT_mAmu/MSSMatMGUT_mAmu_mass_eigenstates.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 59.5153933865, "max_line_length": 130, "alphanum_fraction": 0.7290353482, "num_tokens": 18845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.18216083458438734}}
{"text": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n\n#include <boost/asio/post.hpp>\n\n#include <koinos/bigint.hpp>\n#include <koinos/block_production/pow_producer.hpp>\n#include <koinos/contracts/pow/pow.pb.h>\n#include <koinos/crypto/elliptic.hpp>\n#include <koinos/crypto/multihash.hpp>\n#include <koinos/protocol/protocol.pb.h>\n#include <koinos/rpc/chain/chain_rpc.pb.h>\n#include <koinos/util/conversion.hpp>\n#include <koinos/util/services.hpp>\n\nconst uint32_t get_difficulty_entrypoint = 1249216561;\n\nusing namespace std::chrono_literals;\n\nnamespace koinos::block_production {\n\nnamespace hashrate\n{\n   constexpr double terahash = 1.0e12;\n   constexpr double gigahash = 1.0e9;\n   constexpr double megahash = 1.0e6;\n   constexpr double kilohash = 1.0e3;\n\n   constexpr std::chrono::seconds update_interval = 2s;\n}\n\npow_producer::pow_producer(\n   crypto::private_key signing_key,\n   boost::asio::io_context& main_context,\n   boost::asio::io_context& production_context,\n   std::shared_ptr< mq::client > rpc_client,\n   int64_t production_threshold,\n   uint64_t resources_lower_bound,\n   uint64_t resources_upper_bound,\n   uint64_t max_inclusion_attempts,\n   contract_id_type pow_contract_id,\n   std::size_t worker_groups ) :\n      block_producer(\n         signing_key,\n         main_context,\n         production_context,\n         rpc_client,\n         production_threshold,\n         resources_lower_bound,\n         resources_upper_bound,\n         max_inclusion_attempts\n      ),\n      _pow_contract_id( pow_contract_id ),\n      _update_timer( _main_context ),\n      _error_timer( _production_context ),\n      _num_worker_groups( worker_groups )\n{\n   constexpr uint512_t max_nonce = std::numeric_limits< uint256_t >::max();\n   for ( std::size_t worker_index = 0; worker_index < _num_worker_groups; worker_index++ )\n   {\n      uint512_t start = max_nonce * worker_index / _num_worker_groups;\n      uint512_t end   = max_nonce * ( worker_index + 1 ) / _num_worker_groups;\n\n      _worker_groups.emplace_back( start.convert_to< uint256_t >(), end.convert_to< uint256_t >() );\n      _worker_hashrate[ worker_index ].store( 0 );\n\n      LOG(info) << \"Work group \" << worker_index << \": [\" << start.convert_to< uint256_t >() << \", \" << end.convert_to< uint256_t >() << \"]\";\n   }\n}\n\npow_producer::~pow_producer() = default;\n\nvoid pow_producer::display_hashrate( const boost::system::error_code& ec )\n{\n   if ( ec == boost::asio::error::operation_aborted )\n      return;\n\n   if ( _hashing )\n   {\n      double total_hashes = 0;\n      for ( auto it = _worker_hashrate.begin(); it != _worker_hashrate.end(); ++it )\n         total_hashes += it->second.load();\n\n      total_hashes /= hashrate::update_interval.count();\n\n      LOG(info) << \"Hashrate: \" << hashrate_to_string( total_hashes );\n   }\n\n   _update_timer.expires_from_now( hashrate::update_interval );\n   _update_timer.async_wait( std::bind( &pow_producer::display_hashrate, this, std::placeholders::_1 ) );\n}\n\nvoid pow_producer::produce( const boost::system::error_code& ec )\n{\n   if ( ec == boost::asio::error::operation_aborted )\n      return;\n\n   auto done  = std::make_shared< std::atomic< bool > >( false );\n   auto nonce = std::make_shared< std::optional< uint256_t > >();\n\n   try\n   {\n      auto block = next_block();\n\n      do\n      {\n         auto diff_meta = get_difficulty_meta();\n         auto target = util::converter::to< uint256_t >( diff_meta.target() );\n\n         block.set_id( util::converter::as< std::string >( crypto::hash( crypto::multicodec::sha2_256, block.header() ) ) );\n\n         LOG(info) << \"Difficulty target: 0x\" << std::setfill( '0' ) << std::setw( 64 ) << std::hex << target;\n         LOG(info) << \"Network hashrate: \" << compute_network_hashrate( diff_meta );\n\n         for ( std::size_t worker_index = 0; worker_index < _worker_groups.size(); worker_index++ )\n         {\n            const auto& [ start, end ] = _worker_groups.at( worker_index );\n            boost::asio::post(\n               _production_context,\n               std::bind(\n                  &pow_producer::find_nonce,\n                  this,\n                  worker_index++,\n                  block,\n                  target,\n                  start,\n                  end,\n                  nonce,\n                  done\n               )\n            );\n         }\n\n         {\n            auto lock = std::unique_lock< std::mutex >( _cv_mutex );\n\n            bool service_was_halted = false;\n            bool block_is_stale     = false;\n\n            _hashing = true;\n\n            while ( !_cv.wait_for( lock, 1s, [&]()\n            {\n               service_was_halted = _production_context.stopped() || _halted;\n               block_is_stale     = _last_known_height >= block.header().height();\n\n               return *done || service_was_halted || block_is_stale;\n            } ) );\n\n            _hashing = false;\n\n            if ( service_was_halted )\n               return;\n\n            if ( block_is_stale )\n            {\n               LOG(info) << \"Block is stale, retrieving new head\";\n               *done = true;\n               boost::asio::post( _production_context, std::bind( &pow_producer::produce, this, boost::system::error_code{} ) );\n               return;\n            }\n         }\n\n         KOINOS_ASSERT( nonce->has_value(), nonce_failure, \"expected nonce to contain a value\" );\n\n         auto block_nonce = nonce->value();\n\n         LOG(info) << \"Found nonce: 0x\" << std::setfill( '0' ) << std::setw( 64 ) << std::hex << block_nonce;\n         LOG(info) << \"Proof: \" << crypto::hash( crypto::multicodec::sha2_256, block_nonce, block.id() );\n\n         contracts::pow::pow_signature_data pow_data;\n         pow_data.set_nonce( util::converter::as< std::string >( block_nonce ) );\n         pow_data.set_recoverable_signature( util::converter::as< std::string >( _signing_key.sign_compact( util::converter::to< crypto::multihash >( block.id() ) ) ) );\n\n         block.set_signature( util::converter::as< std::string >( pow_data ) );\n      }\n      while( submit_block( block ) );\n\n      _error_wait_time = 5s;\n   }\n   catch ( const std::exception& e )\n   {\n      *done = true;\n      _hashing = false;\n\n      LOG(warning) << e.what() << \", retrying in \" << _error_wait_time.load().count() << \"s\";\n\n      _error_timer.expires_from_now( _error_wait_time.load() );\n      _error_timer.async_wait( std::bind( &pow_producer::produce, this, std::placeholders::_1 ) );\n\n      // Exponential backoff, max wait time 30 seconds\n      auto next_wait_time = std::min( uint64_t( _error_wait_time.load().count() * 2 ), uint64_t( 30 ) );\n      _error_wait_time = std::chrono::seconds( next_wait_time );\n      return;\n   }\n\n   boost::asio::post( _production_context, std::bind( &pow_producer::produce, this, boost::system::error_code{} ) );\n}\n\nvoid pow_producer::find_nonce(\n   std::size_t worker_index,\n   const protocol::block& block,\n   uint256_t target,\n   uint256_t start,\n   uint256_t end,\n   std::shared_ptr< std::optional< uint256_t > > nonce,\n   std::shared_ptr< std::atomic< bool > > done )\n{\n   auto begin_time  = std::chrono::steady_clock::now();\n   auto begin_nonce = start;\n   auto id = util::converter::to< crypto::multihash >( block.id() );\n\n   for ( uint256_t current_nonce = start; current_nonce < end; current_nonce++ )\n   {\n      if ( *done || _production_context.stopped() || _halted )\n         break;\n\n      auto proof = hash( crypto::multicodec::sha2_256, current_nonce, id );\n\n      if ( target_met( proof, target ) )\n      {\n         std::unique_lock< std::mutex > lock( _cv_mutex );\n         if ( !*done )\n         {\n            *nonce = current_nonce;\n            *done  = true;\n            _cv.notify_one();\n         }\n      }\n\n      if ( auto now = std::chrono::steady_clock::now(); now - begin_time > hashrate::update_interval )\n      {\n         auto hashes = current_nonce - begin_nonce;\n         begin_time  = now;\n         begin_nonce = current_nonce;\n         _worker_hashrate[ worker_index ] = hashes.convert_to< uint64_t >();\n      }\n   }\n}\n\ncontracts::pow::difficulty_metadata pow_producer::get_difficulty_meta()\n{\n   rpc::chain::chain_request req;\n   auto read_contract = req.mutable_read_contract();\n   read_contract->set_contract_id( _pow_contract_id );\n   read_contract->set_entry_point( get_difficulty_entrypoint );\n\n   auto future = _rpc_client->rpc( util::service::chain, req.SerializeAsString() );\n\n   rpc::chain::chain_response resp;\n   resp.ParseFromString( future.get() );\n\n   if ( resp.has_error() )\n   {\n      KOINOS_THROW( rpc_failure, \"error while retrieving difficulty from the pow contract: ${e}\", (\"e\", resp.error().message()) );\n   }\n\n   KOINOS_ASSERT( resp.has_read_contract(), rpc_failure, \"unexpected RPC response when retrieving difficulty: ${r}\", (\"r\", resp) );\n\n   contracts::pow::get_difficulty_metadata_result meta;\n   meta.ParseFromString( resp.read_contract().result() );\n   return meta.value();\n}\n\nbool pow_producer::target_met( const crypto::multihash& hash, uint256_t target )\n{\n   if ( util::converter::to< uint256_t >( hash.digest() ) <= target )\n      return true;\n\n   return false;\n}\n\nvoid pow_producer::on_block_accept( const protocol::block& b )\n{\n   block_producer::on_block_accept( b );\n\n   {\n      std::unique_lock< std::mutex > lock( _cv_mutex );\n      _last_known_height = b.header().height();\n      _cv.notify_one();\n   }\n}\n\nstd::string pow_producer::hashrate_to_string( double hashrate )\n{\n   std::string suffix = \"H/s\";\n\n   if ( hashrate > hashrate::terahash )\n   {\n      hashrate /= hashrate::terahash;\n      suffix = \"TH/s\";\n   }\n   else if ( hashrate > hashrate::gigahash )\n   {\n      hashrate /= hashrate::gigahash;\n      suffix = \"GH/s\";\n   }\n   else if ( hashrate > hashrate::megahash )\n   {\n      hashrate /= hashrate::megahash;\n      suffix = \"MH/s\";\n   }\n   else if ( hashrate > hashrate::kilohash )\n   {\n      hashrate /= hashrate::kilohash;\n      suffix = \"KH/s\";\n   }\n\n   return std::to_string( hashrate ) + \" \" + suffix;\n}\n\nstd::string pow_producer::compute_network_hashrate( const contracts::pow::difficulty_metadata& meta )\n{\n   auto hashrate = util::converter::to< uint256_t >( meta.difficulty() ) / meta.target_block_interval();\n   return hashrate_to_string( double( hashrate ) );\n}\n\nvoid pow_producer::commence()\n{\n   boost::asio::post( _production_context, std::bind( &pow_producer::produce, this, boost::system::error_code{} ) );\n   _update_timer.expires_from_now( hashrate::update_interval + 2500ms );\n   _update_timer.async_wait( std::bind( &pow_producer::display_hashrate, this, std::placeholders::_1 ) );\n}\n\nvoid pow_producer::halt()\n{\n   _update_timer.cancel();\n}\n\n\n} // koinos::block_production\n", "meta": {"hexsha": "80a15e25b3cd50156e42d7e88bf00f5af7bafff5", "size": 10664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/block_production/pow_producer.cpp", "max_stars_repo_name": "koinos/koinos-block-producer", "max_stars_repo_head_hexsha": "b6b15542e0f02fc97119920ab6b0d76dbfd3d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T08:45:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T08:45:26.000Z", "max_issues_repo_path": "libraries/block_production/pow_producer.cpp", "max_issues_repo_name": "koinos/koinos-block-producer", "max_issues_repo_head_hexsha": "b6b15542e0f02fc97119920ab6b0d76dbfd3d6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2021-04-27T06:49:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T23:48:31.000Z", "max_forks_repo_path": "libraries/block_production/pow_producer.cpp", "max_forks_repo_name": "koinos/koinos-block-producer", "max_forks_repo_head_hexsha": "b6b15542e0f02fc97119920ab6b0d76dbfd3d6a8", "max_forks_repo_licenses": ["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.9281437126, "max_line_length": 169, "alphanum_fraction": 0.6289384846, "num_tokens": 2739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.18216083148661172}}
{"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_TIGER_POLICY_HPP\n#define CRYPTO3_TIGER_POLICY_HPP\n\n#include <boost/crypto3/hash/detail/tiger/tiger_functions.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<std::size_t DigestBits, std::size_t Passes>\n                struct tiger_policy : public tiger_functions<DigestBits> {\n                    typedef typename tiger_functions<DigestBits>::byte_type byte_type;\n\n                    constexpr static const std::size_t word_bits = tiger_functions<DigestBits>::word_bits;\n                    typedef typename tiger_functions<DigestBits>::word_type word_type;\n\n                    constexpr static const std::size_t passes = Passes;\n\n                    typedef typename stream_endian::little_octet_big_bit digest_endian;\n\n                    constexpr static const std::size_t digest_bits = DigestBits;\n                    typedef static_digest<DigestBits> digest_type;\n\n                    constexpr static const std::size_t state_bits = tiger_functions<DigestBits>::state_bits;\n                    constexpr static const std::size_t state_words = tiger_functions<DigestBits>::state_words;\n                    typedef typename tiger_functions<DigestBits>::state_type state_type;\n\n                    struct iv_generator {\n                        state_type const &operator()() const {\n                            constexpr static const state_type H0 = {\n                                {0x0123456789ABCDEF, 0xFEDCBA9876543210, 0xF096A5B4C3B2E187}};\n                            return H0;\n                        }\n                    };\n                };\n            }    // namespace detail\n        }        // namespace hashes\n    }            // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_TIGER_POLICY_HPP\n", "meta": {"hexsha": "3ed48f7eb30a516c8b016c08e4702095dfd61d53", "size": 2212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/detail/tiger/tiger_policy.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_policy.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_policy.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": 44.24, "max_line_length": 110, "alphanum_fraction": 0.5650994575, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.1820559275385114}}
{"text": "// Copyright (c) 2011-2016 The Bitcoin Core developers\n// Copyright (c) 2017-2020 The Bitcoin developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <miner.h>\n\n#include <chain.h>\n#include <chainparams.h>\n#include <coins.h>\n#include <config.h>\n#include <consensus/consensus.h>\n#include <consensus/merkle.h>\n#include <consensus/tx_verify.h>\n#include <consensus/validation.h>\n#include <policy/policy.h>\n#include <pubkey.h>\n#include <script/standard.h>\n#include <txmempool.h>\n#include <uint256.h>\n#include <util/strencodings.h>\n#include <util/system.h>\n#include <validation.h>\n\n#include <test/setup_common.h>\n\n#include <boost/test/unit_test.hpp>\n\n#include <memory>\n\n\n#include <protocol.h>\n#include <rpc/protocol.h>\n#include <univalue.h>\n#include <streams.h>\n#include <primitives/block.h>\n#include <pow.h>\n// we need increased inflation to have larger coinbase\nstruct TestnetSetup : public TestingSetup {\n    TestnetSetup() : TestingSetup(CBaseChainParams::TESTNET) {}\n};\nBOOST_FIXTURE_TEST_SUITE(miner_tests, TestnetSetup)\n\n// BOOST_CHECK_EXCEPTION predicates to check the specific validation error\nclass HasReason {\npublic:\n    explicit HasReason(const std::string &reason) : m_reason(reason) {}\n    bool operator()(const std::runtime_error &e) const {\n        return std::string(e.what()).find(m_reason) != std::string::npos;\n    };\n\nprivate:\n    const std::string m_reason;\n};\n\nstatic CFeeRate blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE_PER_KB);\n\nstatic BlockAssembler AssemblerForTest(const CChainParams &params,\n                                       const CTxMemPool &mempool) {\n    BlockAssembler::Options options;\n    options.blockMinFeeRate = blockMinFeeRate;\n    return BlockAssembler(params, mempool, options);\n}\n\nstatic struct {\n    uint8_t extranonce;\n    uint32_t nonce;\n} blockinfo[] = {\n    {4, 0xa4a3e223}, {2, 0x15c32f9e}, {1, 0x0375b547}, {1, 0x7004a8a5},\n    {2, 0xce440296}, {2, 0x52cfe198}, {1, 0x77a72cd0}, {2, 0xbb5d6f84},\n    {2, 0x83f30c2c}, {1, 0x48a73d5b}, {1, 0xef7dcd01}, {2, 0x6809c6c4},\n    {2, 0x0883ab3c}, {1, 0x087bbbe2}, {2, 0x2104a814}, {2, 0xdffb6daa},\n    {1, 0xee8a0a08}, {2, 0xba4237c1}, {1, 0xa70349dc}, {1, 0x344722bb},\n    {3, 0xd6294733}, {2, 0xec9f5c94}, {2, 0xca2fbc28}, {1, 0x6ba4f406},\n    {2, 0x015d4532}, {1, 0x6e119b7c}, {2, 0x43e8f314}, {2, 0x27962f38},\n    {2, 0xb571b51b}, {2, 0xb36bee23}, {2, 0xd17924a8}, {2, 0x6bc212d9},\n    {1, 0x630d4948}, {2, 0x9a4c4ebb}, {2, 0x554be537}, {1, 0xd63ddfc7},\n    {2, 0xa10acc11}, {1, 0x759a8363}, {2, 0xfb73090d}, {1, 0xe82c6a34},\n    {1, 0xe33e92d7}, {3, 0x658ef5cb}, {2, 0xba32ff22}, {5, 0x0227a10c},\n    {1, 0xa9a70155}, {5, 0xd096d809}, {1, 0x37176174}, {1, 0x830b8d0f},\n    {1, 0xc6e3910e}, {2, 0x823f3ca8}, {1, 0x99850849}, {1, 0x7521fb81},\n    {1, 0xaacaabab}, {1, 0xd645a2eb}, {5, 0x7aea1781}, {5, 0x9d6e4b78},\n    {1, 0x4ce90fd8}, {1, 0xabdc832d}, {6, 0x4a34f32a}, {2, 0xf2524c1c},\n    {2, 0x1bbeb08a}, {1, 0xad47f480}, {1, 0x9f026aeb}, {1, 0x15a95049},\n    {2, 0xd1cb95b2}, {2, 0xf84bbda5}, {1, 0x0fa62cd1}, {1, 0xe05f9169},\n    {1, 0x78d194a9}, {5, 0x3e38147b}, {5, 0x737ba0d4}, {1, 0x63378e10},\n    {1, 0x6d5f91cf}, {2, 0x88612eb8}, {2, 0xe9639484}, {1, 0xb7fabc9d},\n    {2, 0x19b01592}, {1, 0x5a90dd31}, {2, 0x5bd7e028}, {2, 0x94d00323},\n    {1, 0xa9b9c01a}, {1, 0x3a40de61}, {1, 0x56e7eec7}, {5, 0x859f7ef6},\n    {1, 0xfd8e5630}, {1, 0x2b0c9f7f}, {1, 0xba700e26}, {1, 0x7170a408},\n    {1, 0x70de86a8}, {1, 0x74d64cd5}, {1, 0x49e738a1}, {2, 0x6910b602},\n    {0, 0x643c565f}, {1, 0x54264b3f}, {2, 0x97ea6396}, {2, 0x55174459},\n    {2, 0x03e8779a}, {1, 0x98f34d8f}, {1, 0xc07b2b07}, {1, 0xdfe29668},\n    {1, 0x3141c7c1}, {1, 0xb3b595f4}, {1, 0x735abf08}, {5, 0x623bfbce},\n    {2, 0xd351e722}, {1, 0xf4ca48c9}, {1, 0x5b19c670}, {1, 0xa164bf0e},\n    {2, 0xbbbeb305}, {2, 0xfe1c810a},\n};\n\nusing CBlockIndexPtr = std::unique_ptr<CBlockIndex>;\n\nstatic CBlockIndexPtr CreateBlockIndex(int nHeight) {\n    CBlockIndexPtr index(new CBlockIndex);\n    index->nHeight = nHeight;\n    index->pprev = ::ChainActive().Tip();\n    return index;\n}\n\nstatic bool TestSequenceLocks(const CTransaction &tx, int flags)\n    EXCLUSIVE_LOCKS_REQUIRED(cs_main) {\n    LOCK(::g_mempool.cs);\n    return CheckSequenceLocks(::g_mempool, tx, flags);\n}\n\n// Test suite for ancestor feerate transaction selection.\n// Implemented as an additional function, rather than a separate test case, to\n// allow reusing the blockchain created in CreateNewBlock_validity.\nstatic void TestPackageSelection(const CChainParams &chainparams,\n                                 const CScript &scriptPubKey,\n                                 const std::vector<CTransactionRef> &txFirst)\n    EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::g_mempool.cs) {\n    // Test the ancestor feerate transaction selection.\n    TestMemPoolEntryHelper entry;\n\n    // Test that a medium fee transaction will be selected after a higher fee\n    // rate package with a low fee rate parent.\n    CMutableTransaction tx;\n    tx.vin.resize(1);\n    tx.vin[0].scriptSig = CScript() << OP_1;\n    tx.vin[0].prevout = COutPoint(txFirst[0]->GetId(), 0);\n    tx.vout.resize(1);\n    tx.vout[0].nValue = int64_t(5000000000LL - 1000) * FIXOSHI;\n    // This tx has a low fee: 1000 satoshis.\n    // Save this txid for later use.\n    TxId parentTxId = tx.GetId();\n    g_mempool.addUnchecked(entry.Fee(1000 * FIXOSHI)\n                               .Time(GetTime())\n                               .SpendsCoinbase(true)\n                               .FromTx(tx));\n\n    // This tx has a medium fee: 10000 satoshis.\n    tx.vin[0].prevout = COutPoint(txFirst[1]->GetId(), 0);\n    tx.vout[0].nValue = int64_t(5000000000LL - 10000) * FIXOSHI;\n    TxId mediumFeeTxId = tx.GetId();\n    g_mempool.addUnchecked(entry.Fee(10000 * FIXOSHI)\n                               .Time(GetTime())\n                               .SpendsCoinbase(true)\n                               .FromTx(tx));\n\n    // This tx has a high fee, but depends on the first transaction.\n    tx.vin[0].prevout = COutPoint(parentTxId, 0);\n    // 50k satoshi fee.\n    tx.vout[0].nValue = int64_t(5000000000LL - 1000 - 50000) * FIXOSHI;\n    TxId highFeeTxId = tx.GetId();\n    g_mempool.addUnchecked(entry.Fee(50000 * FIXOSHI)\n                               .Time(GetTime())\n                               .SpendsCoinbase(false)\n                               .FromTx(tx));\n\n    std::unique_ptr<CBlockTemplate> pblocktemplate =\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey);\n    BOOST_CHECK(pblocktemplate->block.vtx[1]->GetId() == parentTxId);\n    BOOST_CHECK(pblocktemplate->block.vtx[2]->GetId() == highFeeTxId);\n    BOOST_CHECK(pblocktemplate->block.vtx[3]->GetId() == mediumFeeTxId);\n\n    // Test that a package below the block min tx fee doesn't get included\n    tx.vin[0].prevout = COutPoint(highFeeTxId, 0);\n    // 0 fee.\n    tx.vout[0].nValue = int64_t(5000000000LL - 1000 - 50000) * FIXOSHI;\n    TxId freeTxId = tx.GetId();\n    g_mempool.addUnchecked(entry.Fee(Amount::zero()).FromTx(tx));\n    size_t freeTxSize = GetSerializeSize(tx, PROTOCOL_VERSION);\n\n    // Calculate a fee on child transaction that will put the package just\n    // below the block min tx fee (assuming 1 child tx of the same size).\n    Amount feeToUse = blockMinFeeRate.GetFee(2 * freeTxSize) - FIXOSHI;\n\n    tx.vin[0].prevout = COutPoint(freeTxId, 0);\n    tx.vout[0].nValue =\n        int64_t(5000000000LL - 1000 - 50000) * FIXOSHI - feeToUse;\n    TxId lowFeeTxId = tx.GetId();\n    g_mempool.addUnchecked(entry.Fee(feeToUse).FromTx(tx));\n    pblocktemplate =\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey);\n    // Verify that the free tx and the low fee tx didn't get selected.\n    for (const auto &txn : pblocktemplate->block.vtx) {\n        BOOST_CHECK(txn->GetId() != freeTxId);\n        BOOST_CHECK(txn->GetId() != lowFeeTxId);\n    }\n\n    // Test that packages above the min relay fee do get included, even if one\n    // of the transactions is below the min relay fee. Remove the low fee\n    // transaction and replace with a higher fee transaction\n    g_mempool.removeRecursive(CTransaction(tx));\n    // Now we should be just over the min relay fee.\n    tx.vout[0].nValue -= 2 * FIXOSHI;\n    lowFeeTxId = tx.GetId();\n    g_mempool.addUnchecked(entry.Fee(feeToUse + 2 * FIXOSHI).FromTx(tx));\n    pblocktemplate =\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey);\n    BOOST_CHECK(pblocktemplate->block.vtx[4]->GetId() == freeTxId);\n    BOOST_CHECK(pblocktemplate->block.vtx[5]->GetId() == lowFeeTxId);\n\n    // Test that transaction selection properly updates ancestor fee\n    // calculations as ancestor transactions get included in a block. Add a\n    // 0-fee transaction that has 2 outputs.\n    tx.vin[0].prevout = COutPoint(txFirst[2]->GetId(), 0);\n    tx.vout.resize(2);\n    tx.vout[0].nValue = int64_t(5000000000LL - 100000000) * FIXOSHI;\n    // 1BCC output.\n    tx.vout[1].nValue = 100000000 * FIXOSHI;\n    TxId freeTxId2 = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(Amount::zero()).SpendsCoinbase(true).FromTx(tx));\n\n    // This tx can't be mined by itself.\n    tx.vin[0].prevout = COutPoint(freeTxId2, 0);\n    tx.vout.resize(1);\n    feeToUse = blockMinFeeRate.GetFee(freeTxSize);\n    tx.vout[0].nValue = int64_t(5000000000LL - 100000000) * FIXOSHI - feeToUse;\n    TxId lowFeeTxId2 = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(feeToUse).SpendsCoinbase(false).FromTx(tx));\n    pblocktemplate =\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey);\n\n    // Verify that this tx isn't selected.\n    for (const auto &txn : pblocktemplate->block.vtx) {\n        BOOST_CHECK(txn->GetId() != freeTxId2);\n        BOOST_CHECK(txn->GetId() != lowFeeTxId2);\n    }\n\n    // This tx will be mineable, and should cause lowFeeTxId2 to be selected as\n    // well.\n    tx.vin[0].prevout = COutPoint(freeTxId2, 1);\n    // 10k satoshi fee.\n    tx.vout[0].nValue = (100000000 - 10000) * FIXOSHI;\n    g_mempool.addUnchecked(entry.Fee(10000 * FIXOSHI).FromTx(tx));\n    pblocktemplate =\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey);\n    BOOST_CHECK(pblocktemplate->block.vtx[8]->GetId() == lowFeeTxId2);\n}\n\nvoid TestCoinbaseMessageEB(uint64_t eb, const std::string &cbmsg) {\n    GlobalConfig config;\n    config.SetExcessiveBlockSize(eb);\n\n    CScript scriptPubKey =\n        CScript() << ParseHex(\"04678afdb0fe5548271967f1a67130b7105cd6a828e03909\"\n                              \"a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112\"\n                              \"de5c384df7ba0b8d578a4c702b6bf11d5f\")\n                  << OP_CHECKSIG;\n\n    std::unique_ptr<CBlockTemplate> pblocktemplate =\n        BlockAssembler(config, g_mempool).CreateNewBlock(scriptPubKey);\n\n    CBlock *pblock = &pblocktemplate->block;\n\n    // IncrementExtraNonce creates a valid coinbase and merkleRoot\n    unsigned int extraNonce = 0;\n    IncrementExtraNonce(pblock, ::ChainActive().Tip(), config.GetExcessiveBlockSize(),\n                        extraNonce);\n    unsigned int nHeight = ::ChainActive().Tip()->nHeight + 1;\n    std::vector<uint8_t> vec(cbmsg.begin(), cbmsg.end());\n    BOOST_CHECK(pblock->vtx[0]->vin[0].scriptSig ==\n                ((CScript() << nHeight << CScriptNum(extraNonce) << vec) +\n                 COINBASE_FLAGS));\n}\n\n// Coinbase scriptSig has to contains the correct EB value\n// converted to MB, rounded down to the first decimal\nBOOST_AUTO_TEST_CASE(CheckCoinbase_EB) {\n    TestCoinbaseMessageEB(1000001, \"/EB1.0/\");\n    TestCoinbaseMessageEB(2000000, \"/EB2.0/\");\n    TestCoinbaseMessageEB(8000000, \"/EB8.0/\");\n    TestCoinbaseMessageEB(8320000, \"/EB8.3/\");\n}\n\n#include <event2/buffer.h>\n#include <event2/bufferevent.h>\n#include <event2/event.h>\n#include <event2/thread.h>\n#include <event2/http.h>\n#include <event2/util.h>\n\nstatic uint8_t lastExtraNonce = 0;\nstatic std::map<uint256, uint8_t> merkleRootToExtraNonce;\nstatic event_base *mine_event_base;\nstatic size_t blockIdx = 0;\n\nvoid updateExtraNonce(CBlock *pblock, uint8_t extraNonce) {\n    CMutableTransaction txCoinbase(*pblock->vtx[0]);\n    txCoinbase.nVersion = 1;\n    txCoinbase.vin[0].scriptSig[0] = extraNonce;\n    pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));\n    pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);\n}\n\nstatic void mine_request_cb(struct evhttp_request *req, void *arg) {\n    CBlock *pblock = (CBlock *)arg;\n    struct evbuffer *buf = evhttp_request_get_input_buffer(req);\n    if (!buf) {\n        return;\n    }\n    size_t size = evbuffer_get_length(buf);\n    const char *data = (const char *)evbuffer_pullup(buf, size);\n    if (!data) {\n        return;\n    }\n    std::string body(data, size);\n    evbuffer_drain(buf, size);\n    UniValue jsonBody;\n    jsonBody.read(body);\n    BOOST_TEST_MESSAGE(\"d not empty \" << UniValue::stringify(jsonBody));\n    const UniValue::Array &d = jsonBody[\"params\"].get_array();\n    std::string reply;\n    bool stop = false;\n\n    if (!d.empty()) {\n        BOOST_TEST_MESSAGE(\"d not empty \" << UniValue::stringify(d));\n        std::vector<uint8_t> powData = ParseHex(d[0].get_str());\n        BOOST_TEST_MESSAGE(\"Reading d\");\n        std::vector<uint8_t> headerData(powData.begin(), powData.begin() + 80);\n        for (size_t idx = 0; idx < headerData.size(); idx += 4) {\n            std::reverse(headerData.begin() + idx, headerData.begin() + idx + 4);\n        }\n        CDataStream headerStream(headerData, SER_NETWORK, PROTOCOL_VERSION);\n        CBlockHeader header;\n        headerStream >> header;\n        LogPrintf(\"Got hash: %s\\n\", header.GetHash());\n        BOOST_TEST_MESSAGE(\"Got hash: \" << header.GetHash());\n        std::map<uint256, uint8_t>::iterator nonceEntry = merkleRootToExtraNonce.find(header.hashMerkleRoot);\n        if (nonceEntry != merkleRootToExtraNonce.end()) {\n            LogPrintf(\"Got PoW: extranonce=%d, nonce=%d\\n\", nonceEntry->second, header.nNonce);\n            pblock->nNonce = header.nNonce;\n            updateExtraNonce(pblock, nonceEntry->second);\n            LogPrintf(\"Merkle roots: pblock=%s, header=%s\\n\", pblock->hashMerkleRoot.ToString(), header.hashMerkleRoot.ToString());\n            if (pblock->hashMerkleRoot != header.hashMerkleRoot) {\n                reply = \"{\\\"result\\\":false}\";\n            } else {\n                reply = \"{\\\"result\\\":true}\";\n                stop = true;\n                blockinfo[blockIdx] = {nonceEntry->second, header.nNonce};\n                LogPrintf(\"New blockinfo: \\n\");\n                for (size_t i = 0; i < sizeof(blockinfo) / sizeof(*blockinfo); ++i) {\n                    LogPrintf(\"{%d, 0x%x},\\n\", blockinfo[i].extranonce, blockinfo[i].nonce);\n                }\n            }\n        } else {\n            LogPrintf(\"Unknown merkle root: %s\\n\", header.hashMerkleRoot.ToString());\n            reply = \"{\\\"result\\\":false}\";\n        }\n    } else {\n        lastExtraNonce++;\n        updateExtraNonce(pblock, lastExtraNonce);\n        merkleRootToExtraNonce[pblock->hashMerkleRoot] = lastExtraNonce;\n        CDataStream headerStream(SER_NETWORK, PROTOCOL_VERSION);\n        headerStream << pblock->GetBlockHeader();\n        for (size_t idx = 0; idx < headerStream.size(); idx += 4) {\n            std::reverse(headerStream.begin() + idx, headerStream.begin() + idx + 4);\n        }\n\n        arith_uint256 bnTarget;\n        bool fNegative;\n        bool fOverflow;\n        bnTarget.SetCompact(pblock->nBits, &fNegative, &fOverflow);\n\n        std::ostringstream replyStream;\n        replyStream << \"{\\\"result\\\":{\\\"data\\\":\\\"\";\n        replyStream << HexStr(headerStream);\n        replyStream << \"000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000\";\n        replyStream << \"\\\",\\\"target\\\":\\\"\";\n        replyStream << HexStr(ArithToUint256(bnTarget));\n        replyStream << \"\\\"},\\\"error\\\": null}\";\n\n        reply = replyStream.str();\n    }\n\n    struct evbuffer *evb = evhttp_request_get_output_buffer(req);\n    assert(evb);\n    evbuffer_add(evb, reply.data(), reply.size());\n    evhttp_send_reply(req, 200, nullptr, nullptr);\n    if (stop) {\n        sleep(1);\n        event_base_loopbreak(mine_event_base);\n    }\n}\n\n/** libevent event log callback */\nstatic void libevent_log_cb(int severity, const char *msg) {\n#ifndef EVENT_LOG_WARN\n// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.\n#define EVENT_LOG_WARN _EVENT_LOG_WARN\n#endif\n    // Log warn messages and higher without debug category.\n    if (severity >= EVENT_LOG_WARN) {\n        LogPrintf(\"libevent: %s\\n\", msg);\n    } else {\n        LogPrint(BCLog::LIBEVENT, \"libevent: %s\\n\", msg);\n    }\n}\n\n// NOTE: These tests rely on CreateNewBlock doing its own self-validation!\nBOOST_AUTO_TEST_CASE(CreateNewBlock_validity) {\n    BOOST_TEST_MESSAGE(\"Validity test\\n\");\n    // Note that by default, these tests run with size accounting enabled.\n    GlobalConfig config;\n    const CChainParams &chainparams = config.GetChainParams();\n    CScript scriptPubKey =\n        CScript() << ParseHex(\"04678afdb0fe5548271967f1a67130b7105cd6a828e03909\"\n                              \"a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112\"\n                              \"de5c384df7ba0b8d578a4c702b6bf11d5f\")\n                  << OP_CHECKSIG;\n    std::unique_ptr<CBlockTemplate> pblocktemplate;\n    CMutableTransaction tx;\n    CScript script;\n    TestMemPoolEntryHelper entry;\n    entry.nFee = 11 * FIXOSHI;\n    entry.nHeight = 11;\n\n    fCheckpointsEnabled = false;\n    // Simple block creation, nothing special yet:\n    BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool)\n                                     .CreateNewBlock(scriptPubKey));\n\n\n    // We can't make transactions until we have inputs.\n    // Therefore, load 110 blocks :)\n    int baseheight = 0;\n    std::vector<CTransactionRef> txFirst;\n    for (size_t i = 0; i < sizeof(blockinfo) / sizeof(*blockinfo); ++i) {\n        blockIdx = i;\n        // pointer for convenience.\n        CBlock *pblock = &pblocktemplate->block;\n        {\n            LOCK(cs_main);\n            pblock->nVersion = 1;\n            pblock->nTime = ::ChainActive().Tip()->GetMedianTimePast() + 1;\n            CMutableTransaction txCoinbase(*pblock->vtx[0]);\n            txCoinbase.nVersion = 1;\n            txCoinbase.vin[0].scriptSig = CScript();\n            txCoinbase.vin[0].scriptSig.push_back(blockinfo[i].extranonce);\n            txCoinbase.vin[0].scriptSig.push_back(::ChainActive().Height());\n            txCoinbase.vout.resize(1);\n            txCoinbase.vout[0].scriptPubKey = CScript();\n            CBlockHeader header = pblock->GetBlockHeader();\n            pblock->nBits = GetNextWorkRequired(::ChainActive().Tip(), &header, chainparams.GetConsensus());\n            txCoinbase.vout[0].nValue = GetBlockSubsidy(pblock->nBits, 0, chainparams.GetConsensus());\n            pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));\n            if (txFirst.size() == 0) {\n                baseheight = ::ChainActive().Height();\n            }\n            if (txFirst.size() < 4) {\n                txFirst.push_back(pblock->vtx[0]);\n            }\n            BOOST_TEST_MESSAGE(\"nBits  \"<< pblock->nBits);\n            pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);\n            pblock->nNonce = blockinfo[i].nonce;\n\n\n        }\n        arith_uint256 bnTarget;\n        bool fNegative;\n        bool fOverflow;\n        bnTarget.SetCompact(pblock->nBits, &fNegative, &fOverflow);\n        bool alreadyValid;\n        alreadyValid = UintToArith256(pblock->GetHash()) <= bnTarget;\n        if(!alreadyValid) {\n            event_set_log_callback(&libevent_log_cb);\n            evthread_use_pthreads();\n            mine_event_base = event_base_new();\n            evhttp *mine_http = evhttp_new(mine_event_base);\n            evhttp_set_gencb(mine_http, mine_request_cb, pblock);\n            //run an old cgminer to GPU mine those blocks\n            evhttp_bind_socket(mine_http, \"127.0.0.1\", 3000);\n            BOOST_TEST_MESSAGE(\"Waiting for getwork requests...\\n\");\n            LogPrintf(\"Waiting for getwork requests...\\n\");\n            event_base_dispatch(mine_event_base);\n            merkleRootToExtraNonce.clear();\n            lastExtraNonce = 0;\n            evhttp_free(mine_http);\n            event_base_free(mine_event_base);\n        }\n        std::shared_ptr<const CBlock> shared_pblock =\n            std::make_shared<const CBlock>(*pblock);\n        CDataStream headerStream(SER_NETWORK, PROTOCOL_VERSION);\n        headerStream << shared_pblock->GetBlockHeader();\n        LogPrintf(\"Made header: %s\\n\", HexStr(headerStream));\n        ProcessNewBlock(config, shared_pblock, true, nullptr);\n        pblock->hashPrevBlock = pblock->GetHash();\n    }\n\n    LOCK(cs_main);\n    LOCK(::g_mempool.cs);\n\n    // Just to make sure we can still make simple blocks.\n    BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool)\n                                     .CreateNewBlock(scriptPubKey));\n    CBlock *pblock = &pblocktemplate->block;\n    const Amount BLOCKSUBSIDY = GetBlockSubsidy(pblock->nBits, 0, chainparams.GetConsensus());\n    const Amount LOWFEE = CENT;\n    const Amount HIGHFEE = COIN;\n    const Amount HIGHERFEE = 4 * COIN;\n\n    // block size > limit\n    tx.vin.resize(1);\n    tx.vin[0].scriptSig = CScript();\n    // 18 * (520char + DROP) + OP_1 = 9433 bytes\n    std::vector<uint8_t> vchData(520);\n    for (unsigned int i = 0; i < 18; ++i) {\n        tx.vin[0].scriptSig << vchData << OP_DROP;\n    }\n\n    tx.vin[0].scriptSig << OP_1;\n    tx.vin[0].prevout = COutPoint(txFirst[0]->GetId(), 0);\n    tx.vout.resize(1);\n    tx.vout[0].nValue = BLOCKSUBSIDY;\n    BOOST_TEST_MESSAGE(\"BLOCKSUBSIDY \" << BLOCKSUBSIDY);\n    BOOST_TEST_MESSAGE(\"LOWFEE \" << LOWFEE);\n    for (unsigned int i = 0; i < 1; ++i) {\n        tx.vout[0].nValue -= LOWFEE;\n        const TxId txid = tx.GetId();\n        // Only first tx spends coinbase.\n        bool spendsCoinbase = i == 0;\n        g_mempool.addUnchecked(entry.Fee(LOWFEE)\n                                   .Time(GetTime())\n                                   .SpendsCoinbase(spendsCoinbase)\n                                   .FromTx(tx));\n        tx.vin[0].prevout = COutPoint(txid, 0);\n    }\n\n    BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool)\n                                     .CreateNewBlock(scriptPubKey));\n    g_mempool.clear();\n\n    // Orphan in mempool, template creation fails.\n    g_mempool.addUnchecked(entry.Fee(LOWFEE).Time(GetTime()).FromTx(tx));\n    BOOST_CHECK_EXCEPTION(\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey),\n        std::runtime_error, HasReason(\"bad-txns-inputs-missingorspent\"));\n    g_mempool.clear();\n\n    // Child with higher priority than parent.\n    tx.vin[0].scriptSig = CScript() << OP_1;\n    tx.vin[0].prevout = COutPoint(txFirst[1]->GetId(), 0);\n    tx.vout[0].nValue = BLOCKSUBSIDY - HIGHFEE;\n    TxId txid = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));\n    tx.vin[0].prevout = COutPoint(txid, 0);\n    tx.vin.resize(2);\n    tx.vin[1].scriptSig = CScript() << OP_1;\n    tx.vin[1].prevout = COutPoint(txFirst[0]->GetId(), 0);\n    // First txn output + fresh coinbase - new txn fee.\n    tx.vout[0].nValue = tx.vout[0].nValue + BLOCKSUBSIDY - HIGHERFEE;\n    txid = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(HIGHERFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));\n    BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool)\n                                     .CreateNewBlock(scriptPubKey));\n    g_mempool.clear();\n\n    // Coinbase in mempool, template creation fails.\n    tx.vin.resize(1);\n    tx.vin[0].prevout = COutPoint();\n    tx.vin[0].scriptSig = CScript() << OP_0 << OP_1;\n    tx.vout[0].nValue = Amount::zero();\n    txid = tx.GetId();\n    // Give it a fee so it'll get mined.\n    g_mempool.addUnchecked(\n        entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));\n    // Should throw bad-tx-coinbase\n    BOOST_CHECK_EXCEPTION(\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey),\n        std::runtime_error, HasReason(\"bad-tx-coinbase\"));\n    g_mempool.clear();\n\n    // Double spend txn pair in mempool, template creation fails.\n    tx.vin[0].prevout = COutPoint(txFirst[0]->GetId(), 0);\n    tx.vin[0].scriptSig = CScript() << OP_1;\n    tx.vout[0].nValue = BLOCKSUBSIDY - HIGHFEE;\n    tx.vout[0].scriptPubKey = CScript() << OP_1;\n    txid = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));\n    tx.vout[0].scriptPubKey = CScript() << OP_2;\n    txid = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));\n    BOOST_CHECK_EXCEPTION(\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey),\n        std::runtime_error, HasReason(\"bad-txns-inputs-missingorspent\"));\n    g_mempool.clear();\n\n    // Subsidy changing.\n    int nHeight = ::ChainActive().Height();\n    // Create an actual 209999-long block chain (without valid blocks).\n    while (::ChainActive().Tip()->nHeight < 209999) {\n        CBlockIndex *prev = ::ChainActive().Tip();\n        CBlockIndex *next = new CBlockIndex();\n        next->phashBlock = new BlockHash(InsecureRand256());\n        pcoinsTip->SetBestBlock(next->GetBlockHash());\n        next->pprev = prev;\n        next->nHeight = prev->nHeight + 1;\n        next->BuildSkip();\n        ::ChainActive().SetTip(next);\n    }\n    BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool)\n                                     .CreateNewBlock(scriptPubKey));\n    // Extend to a 210000-long block chain.\n    while (::ChainActive().Tip()->nHeight < 210000) {\n        CBlockIndex *prev = ::ChainActive().Tip();\n        CBlockIndex *next = new CBlockIndex();\n        next->phashBlock = new BlockHash(InsecureRand256());\n        pcoinsTip->SetBestBlock(next->GetBlockHash());\n        next->pprev = prev;\n        next->nHeight = prev->nHeight + 1;\n        next->BuildSkip();\n        ::ChainActive().SetTip(next);\n    }\n\n    BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool)\n                                     .CreateNewBlock(scriptPubKey));\n\n    // Invalid p2sh txn in mempool, template creation fails\n    tx.vin[0].prevout = COutPoint(txFirst[0]->GetId(), 0);\n    tx.vin[0].scriptSig = CScript() << OP_1;\n    tx.vout[0].nValue = BLOCKSUBSIDY - LOWFEE;\n    script = CScript() << OP_0;\n    tx.vout[0].scriptPubKey = GetScriptForDestination(CScriptID(script));\n    txid = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));\n    tx.vin[0].prevout = COutPoint(txid, 0);\n    tx.vin[0].scriptSig = CScript()\n                          << std::vector<uint8_t>(script.begin(), script.end());\n    tx.vout[0].nValue -= LOWFEE;\n    txid = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));\n    // Should throw blk-bad-inputs\n    BOOST_CHECK_EXCEPTION(\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey),\n        std::runtime_error, HasReason(\"blk-bad-inputs\"));\n    g_mempool.clear();\n\n    // Delete the dummy blocks again.\n    while (::ChainActive().Tip()->nHeight > nHeight) {\n        CBlockIndex *del = ::ChainActive().Tip();\n        ::ChainActive().SetTip(del->pprev);\n        pcoinsTip->SetBestBlock(del->pprev->GetBlockHash());\n        delete del->phashBlock;\n        delete del;\n    }\n\n    // non-final txs in mempool\n    SetMockTime(::ChainActive().Tip()->GetMedianTimePast() + 1);\n    uint32_t flags = LOCKTIME_VERIFY_SEQUENCE | LOCKTIME_MEDIAN_TIME_PAST;\n    // height map\n    std::vector<int> prevheights;\n\n    // Relative height locked.\n    tx.nVersion = 2;\n    tx.vin.resize(1);\n    prevheights.resize(1);\n    // Only 1 transaction.\n    tx.vin[0].prevout = COutPoint(txFirst[0]->GetId(), 0);\n    tx.vin[0].scriptSig = CScript() << OP_1;\n    // txFirst[0] is the 2nd block\n    tx.vin[0].nSequence = ::ChainActive().Tip()->nHeight + 1;\n    prevheights[0] = baseheight + 1;\n    tx.vout.resize(1);\n    tx.vout[0].nValue = BLOCKSUBSIDY - HIGHFEE;\n    tx.vout[0].scriptPubKey = CScript() << OP_1;\n    tx.nLockTime = 0;\n    txid = tx.GetId();\n    g_mempool.addUnchecked(\n        entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));\n\n    const Consensus::Params &params = chainparams.GetConsensus();\n\n    {\n        // Locktime passes.\n        CValidationState state;\n        BOOST_CHECK(ContextualCheckTransactionForCurrentBlock(\n            params, CTransaction(tx), state, flags));\n    }\n\n    // Sequence locks fail.\n    BOOST_CHECK(!TestSequenceLocks(CTransaction(tx), flags));\n    // Sequence locks pass on 2nd block.\n    BOOST_CHECK(\n        SequenceLocks(CTransaction(tx), flags, &prevheights,\n                      *CreateBlockIndex(::ChainActive().Tip()->nHeight + 2)));\n\n    // Relative time locked.\n    tx.vin[0].prevout = COutPoint(txFirst[1]->GetId(), 0);\n    // txFirst[1] is the 3rd block.\n    tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG |\n                          (((::ChainActive().Tip()->GetMedianTimePast() + 1 -\n                             ::ChainActive()[1]->GetMedianTimePast()) >>\n                            CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) +\n                           1);\n    prevheights[0] = baseheight + 2;\n    txid = tx.GetId();\n    g_mempool.addUnchecked(entry.Time(GetTime()).FromTx(tx));\n\n    {\n        // Locktime passes.\n        CValidationState state;\n        BOOST_CHECK(ContextualCheckTransactionForCurrentBlock(\n            params, CTransaction(tx), state, flags));\n    }\n\n    // Sequence locks fail.\n    BOOST_CHECK(!TestSequenceLocks(CTransaction(tx), flags));\n\n    for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) {\n        // Trick the MedianTimePast.\n        ::ChainActive()\n            .Tip()\n            ->GetAncestor(::ChainActive().Tip()->nHeight - i)\n            ->nTime += 512;\n    }\n    // Sequence locks pass 512 seconds later.\n    BOOST_CHECK(\n        SequenceLocks(CTransaction(tx), flags, &prevheights,\n                      *CreateBlockIndex(::ChainActive().Tip()->nHeight + 1)));\n    for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) {\n        // Undo tricked MTP.\n        ::ChainActive()\n            .Tip()\n            ->GetAncestor(::ChainActive().Tip()->nHeight - i)\n            ->nTime -= 512;\n    }\n\n    // Absolute height locked.\n    tx.vin[0].prevout = COutPoint(txFirst[2]->GetId(), 0);\n    tx.vin[0].nSequence = CTxIn::SEQUENCE_FINAL - 1;\n    prevheights[0] = baseheight + 3;\n    tx.nLockTime = ::ChainActive().Tip()->nHeight + 1;\n    txid = tx.GetId();\n    g_mempool.addUnchecked(entry.Time(GetTime()).FromTx(tx));\n\n    {\n        // Locktime fails.\n        CValidationState state;\n        BOOST_CHECK(!ContextualCheckTransactionForCurrentBlock(\n            params, CTransaction(tx), state, flags));\n        BOOST_CHECK_EQUAL(state.GetRejectReason(), \"bad-txns-nonfinal\");\n    }\n\n    // Sequence locks pass.\n    BOOST_CHECK(TestSequenceLocks(CTransaction(tx), flags));\n\n    {\n        // Locktime passes on 2nd block.\n        CValidationState state;\n        int64_t nMedianTimePast = ::ChainActive().Tip()->GetMedianTimePast();\n        BOOST_CHECK(ContextualCheckTransaction(\n            params, CTransaction(tx), state, ::ChainActive().Tip()->nHeight + 2,\n            nMedianTimePast, nMedianTimePast));\n    }\n\n    // Absolute time locked.\n    tx.vin[0].prevout = COutPoint(txFirst[3]->GetId(), 0);\n    tx.nLockTime = ::ChainActive().Tip()->GetMedianTimePast();\n    prevheights.resize(1);\n    prevheights[0] = baseheight + 4;\n    txid = tx.GetId();\n    g_mempool.addUnchecked(entry.Time(GetTime()).FromTx(tx));\n\n    {\n        // Locktime fails.\n        CValidationState state;\n        BOOST_CHECK(!ContextualCheckTransactionForCurrentBlock(\n            params, CTransaction(tx), state, flags));\n        BOOST_CHECK_EQUAL(state.GetRejectReason(), \"bad-txns-nonfinal\");\n    }\n\n    // Sequence locks pass.\n    BOOST_CHECK(TestSequenceLocks(CTransaction(tx), flags));\n\n    {\n        // Locktime passes 1 second later.\n        CValidationState state;\n        int64_t nMedianTimePast =\n            ::ChainActive().Tip()->GetMedianTimePast() + 1;\n        BOOST_CHECK(ContextualCheckTransaction(\n            params, CTransaction(tx), state, ::ChainActive().Tip()->nHeight + 1,\n            nMedianTimePast, nMedianTimePast));\n    }\n\n    // mempool-dependent transactions (not added)\n    tx.vin[0].prevout = COutPoint(txid, 0);\n    prevheights[0] = ::ChainActive().Tip()->nHeight + 1;\n    tx.nLockTime = 0;\n    tx.vin[0].nSequence = 0;\n\n    {\n        // Locktime passes.\n        CValidationState state;\n        BOOST_CHECK(ContextualCheckTransactionForCurrentBlock(\n            params, CTransaction(tx), state, flags));\n    }\n\n    // Sequence locks pass.\n    BOOST_CHECK(TestSequenceLocks(CTransaction(tx), flags));\n    tx.vin[0].nSequence = 1;\n    // Sequence locks fail.\n    BOOST_CHECK(!TestSequenceLocks(CTransaction(tx), flags));\n    tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;\n    // Sequence locks pass.\n    BOOST_CHECK(TestSequenceLocks(CTransaction(tx), flags));\n    tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | 1;\n    // Sequence locks fail.\n    BOOST_CHECK(!TestSequenceLocks(CTransaction(tx), flags));\n\n    pblocktemplate =\n        AssemblerForTest(chainparams, g_mempool).CreateNewBlock(scriptPubKey);\n    BOOST_CHECK(pblocktemplate);\n\n    // None of the of the absolute height/time locked tx should have made it\n    // into the template because we still check IsFinalTx in CreateNewBlock, but\n    // relative locked txs will if inconsistently added to g_mempool. For now\n    // these will still generate a valid template until BIP68 soft fork.\n    BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3UL);\n    // However if we advance height by 1 and time by 512, all of them should be\n    // mined.\n    for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) {\n        // Trick the MedianTimePast.\n        ::ChainActive()\n            .Tip()\n            ->GetAncestor(::ChainActive().Tip()->nHeight - i)\n            ->nTime += 512;\n    }\n    ::ChainActive().Tip()->nHeight++;\n    SetMockTime(::ChainActive().Tip()->GetMedianTimePast() + 1);\n\n    BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool)\n                                     .CreateNewBlock(scriptPubKey));\n    BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 5UL);\n\n    ::ChainActive().Tip()->nHeight--;\n    SetMockTime(0);\n    g_mempool.clear();\n\n    TestPackageSelection(chainparams, scriptPubKey, txFirst);\n\n    fCheckpointsEnabled = true;\n}\n\nvoid CheckBlockMaxSize(const Config &config, uint64_t size, uint64_t expected) {\n    gArgs.ForceSetArg(\"-blockmaxsize\", std::to_string(size));\n\n    BlockAssembler ba(config, g_mempool);\n    BOOST_CHECK_EQUAL(ba.GetMaxGeneratedBlockSize(), expected);\n}\n\nBOOST_AUTO_TEST_CASE(BlockAssembler_construction) {\n    GlobalConfig config;\n\n    // We are working on a fake chain and need to protect ourselves.\n    LOCK(cs_main);\n\n    // Test around historical 1MB (plus one byte because that's mandatory)\n    config.SetExcessiveBlockSize(ONE_MEGABYTE + 1);\n    CheckBlockMaxSize(config, 0, 1000);\n    CheckBlockMaxSize(config, 1000, 1000);\n    CheckBlockMaxSize(config, 1001, 1001);\n    CheckBlockMaxSize(config, 12345, 12345);\n\n    CheckBlockMaxSize(config, ONE_MEGABYTE - 1001, ONE_MEGABYTE - 1001);\n    CheckBlockMaxSize(config, ONE_MEGABYTE - 1000, ONE_MEGABYTE - 1000);\n    CheckBlockMaxSize(config, ONE_MEGABYTE - 999, ONE_MEGABYTE - 999);\n    CheckBlockMaxSize(config, ONE_MEGABYTE, ONE_MEGABYTE - 999);\n\n    // Test around default cap\n    config.SetExcessiveBlockSize(DEFAULT_EXCESSIVE_BLOCK_SIZE);\n\n    // Now we can use the default max block size.\n    CheckBlockMaxSize(config, DEFAULT_EXCESSIVE_BLOCK_SIZE - 1001,\n                      DEFAULT_EXCESSIVE_BLOCK_SIZE - 1001);\n    CheckBlockMaxSize(config, DEFAULT_EXCESSIVE_BLOCK_SIZE - 1000,\n                      DEFAULT_EXCESSIVE_BLOCK_SIZE - 1000);\n    CheckBlockMaxSize(config, DEFAULT_EXCESSIVE_BLOCK_SIZE - 999,\n                      DEFAULT_EXCESSIVE_BLOCK_SIZE - 1000);\n    CheckBlockMaxSize(config, DEFAULT_EXCESSIVE_BLOCK_SIZE,\n                      DEFAULT_EXCESSIVE_BLOCK_SIZE - 1000);\n\n    // If the parameter is not specified, we use\n    // DEFAULT_MAX_GENERATED_BLOCK_SIZE\n    {\n        gArgs.ClearArg(\"-blockmaxsize\");\n        BlockAssembler ba(config, g_mempool);\n        BOOST_CHECK_EQUAL(ba.GetMaxGeneratedBlockSize(),\n                          DEFAULT_MAX_GENERATED_BLOCK_SIZE);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(TestCBlockTemplateEntry) {\n    CTransactionRef txRef = MakeTransactionRef();\n    CBlockTemplateEntry txEntry(txRef, 1 * FIXOSHI, 10);\n    BOOST_CHECK_MESSAGE(txEntry.tx == txRef, \"Transactions did not match\");\n    BOOST_CHECK_EQUAL(txEntry.fees, 1 * FIXOSHI);\n    BOOST_CHECK_EQUAL(txEntry.sigOpCount, 10);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e8e4cc76c200c9b7df2cf8eac6a3b3609678b875", "size": 37173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/miner_tests.cpp", "max_stars_repo_name": "cculianu/Bitcoin-Static", "max_stars_repo_head_hexsha": "158a585287c5d48a8a53b4b7f59860532f9d98af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-06T12:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T13:40:39.000Z", "max_issues_repo_path": "src/test/miner_tests.cpp", "max_issues_repo_name": "baby636/Bitcoin-Static", "max_issues_repo_head_hexsha": "8b19e8a83990d20bc25ef138a5050b23591fbb80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-07T19:44:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T19:44:52.000Z", "max_forks_repo_path": "src/test/miner_tests.cpp", "max_forks_repo_name": "baby636/Bitcoin-Static", "max_forks_repo_head_hexsha": "8b19e8a83990d20bc25ef138a5050b23591fbb80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-04T10:39:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T08:08:50.000Z", "avg_line_length": 40.8943894389, "max_line_length": 131, "alphanum_fraction": 0.6426707557, "num_tokens": 10838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.18205592404314616}}
{"text": "#include \"skadi/sample.h\"\n\n#include <cmath>\n#include <cstddef>\n#include <fstream>\n#include <future>\n#include <limits>\n#include <list>\n#include <mutex>\n#include <regex>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n\n#include <boost/optional.hpp>\n#include <lz4frame.h>\n#include <sys/stat.h>\n\n#include \"baldr/compression_utils.h\"\n#include \"filesystem.h\"\n#include \"midgard/logging.h\"\n#include \"midgard/pointll.h\"\n#include \"midgard/sequence.h\"\n\nnamespace {\n// srtmgl1 holds 1x1 degree tiles but oversamples the egde of the tile\n// by .5 seconds on all sides. that means that the center of pixel 0 is\n// located at the tiles lat,lon (which is important for bilinear filtering)\n// it also means that there are 3601 pixels per row and per column\nconstexpr size_t HGT_DIM = 3601;\nconstexpr size_t HGT_PIXELS = HGT_DIM * HGT_DIM;\nconstexpr size_t HGT_BYTES = sizeof(int16_t) * HGT_PIXELS;\nconstexpr int16_t NO_DATA_VALUE = -32768;\nconstexpr int16_t NO_DATA_HIGH = 16384;\nconstexpr int16_t NO_DATA_LOW = -16384;\nconstexpr size_t TILE_COUNT = 180 * 360;\nconstexpr int8_t UNPACKED_TILES_COUNT = 50;\n\n// macro is faster than inline function for this..\n#define out_of_range(v) v > NO_DATA_HIGH || v < NO_DATA_LOW\n\nstd::vector<std::string> get_files(const std::string& root_dir) {\n  std::vector<std::string> files;\n  if (filesystem::exists(root_dir) && filesystem::is_directory(root_dir)) {\n    for (filesystem::recursive_directory_iterator i(root_dir), end; i != end; ++i) {\n      if (i->is_regular_file() || i->is_symlink()) {\n        files.push_back(i->path().string());\n      }\n    }\n  }\n  // couldn't get data\n  if (files.empty()) {\n    LOG_WARN(root_dir + \" currently has no elevation tiles\");\n  }\n  return files;\n}\n\nint16_t flip(int16_t value) {\n  return ((value & 0xFF) << 8) | ((value >> 8) & 0xFF);\n}\n\nuint64_t file_size(const std::string& file_name) {\n  // TODO: detect gzip and actually validate the uncompressed size?\n  struct stat s {};\n  int rc = stat(file_name.c_str(), &s);\n  return rc == 0 ? s.st_size : -1;\n}\n\n} // namespace\n\nnamespace valhalla {\nnamespace skadi {\n\nenum class format_t { UNKNOWN = 0, RAW = 1, GZIP = 2, LZ4 = 3 };\n\nclass cache_item_t {\nprivate:\n  format_t format;\n  valhalla::midgard::mem_map<char> data;\n  int usages;\n  const char* unpacked;\n\npublic:\n  cache_item_t() : format(format_t::UNKNOWN), usages(0), unpacked(nullptr) {\n  }\n  cache_item_t(cache_item_t&&) = default;\n  ~cache_item_t() {\n    free((void*)unpacked);\n  }\n\n  bool init(const std::string& path, format_t format) {\n    auto size = file_size(path);\n    if (format == format_t::RAW && size != HGT_BYTES) {\n      return false;\n    }\n    this->format = format;\n    data.map(path, size, POSIX_MADV_SEQUENTIAL, true);\n    return true;\n  }\n\n  inline const char* get_data() const {\n    return data.get();\n  }\n\n  inline format_t get_format() const {\n    return format;\n  }\n\n  inline int& get_usages() {\n    return usages;\n  }\n\n  inline const char* get_unpacked() {\n    return unpacked;\n  }\n\n  inline const char* detach_unpacked() {\n    auto rv = unpacked;\n    unpacked = nullptr;\n    return rv;\n  }\n\n  bool unpack(const char* unpacked) {\n    this->unpacked = unpacked;\n\n    if (format == format_t::GZIP) {\n      // for setting where to read compressed data from\n      auto src_func = [this](z_stream& s) -> void {\n        s.next_in = static_cast<Byte*>(static_cast<void*>(data.get()));\n        s.avail_in = static_cast<unsigned int>(data.size());\n      };\n\n      // for setting where to write the uncompressed data to\n      auto dst_func = [this](z_stream& s) -> int {\n        s.next_out = (Byte*)(this->unpacked);\n        s.avail_out = HGT_BYTES;\n        return Z_FINISH; // we know the output will hold all the input\n      };\n\n      // we have to unzip it\n      if (!baldr::inflate(src_func, dst_func)) {\n        LOG_WARN(\"Corrupt gzip elevation data\");\n        format = format_t::UNKNOWN;\n        return false;\n      }\n    } else if (format == format_t::LZ4) {\n      LZ4F_decompressionContext_t decode;\n      LZ4F_decompressOptions_t options;\n      LZ4F_createDecompressionContext(&decode, LZ4F_VERSION);\n\n      // Take these two values locally, since LZ4F_decompress expects pointers...\n      size_t src_size = data.size();\n      size_t dest_size = HGT_BYTES;\n      size_t result;\n\n      do {\n        result = LZ4F_decompress(decode, const_cast<char*>(this->unpacked), &dest_size, data.get(),\n                                 &src_size, &options);\n        if (LZ4F_isError(result)) {\n          LZ4F_freeDecompressionContext(decode);\n          LOG_WARN(\"Corrupt lz4 elevation data\");\n          format = format_t::UNKNOWN;\n          return false;\n        }\n      } while (result != 0);\n\n      LZ4F_freeDecompressionContext(decode);\n    } else {\n      LOG_WARN(\"Corrupt elevation data of unknown type\");\n      format = format_t::UNKNOWN;\n      return false;\n    }\n\n    return true;\n  }\n\n  static boost::optional<std::pair<uint16_t, format_t>> parse_hgt_name(const std::string& name) {\n    std::smatch m;\n    std::regex e(\".*/([NS])([0-9]{2})([WE])([0-9]{3})\\\\.hgt(\\\\.(gz|lz4))?$\");\n    if (std::regex_search(name, m, e)) {\n      // enum class format_t{ UNKNOWN = 0, GZIP = 1, RAW = 3, LZ4 = 4 };\n      format_t fmt;\n      if (m[5].matched) {\n        if (m[5] == \".gz\") {\n          fmt = format_t::GZIP;\n        } else if (m[5] == \".lz4\") {\n          fmt = format_t::LZ4;\n        } else {\n          fmt = format_t::UNKNOWN;\n        }\n      } else {\n        fmt = format_t::RAW;\n      }\n\n      auto lon = std::stoi(m[4]) * (m[3] == \"E\" ? 1 : -1) + 180;\n      auto lat = std::stoi(m[2]) * (m[1] == \"N\" ? 1 : -1) + 90;\n      if (lon >= 0 && lon < 360 && lat >= 0 && lat < 180) {\n        return std::make_pair(uint16_t(lat * 360 + lon), fmt);\n      }\n    }\n    return boost::none;\n  }\n};\n\n// tile_data object holds unpacked elevation tile data\nclass tile_data {\nprivate:\n  cache_t* c;\n  const int16_t* data;\n  uint16_t index;\n  bool reusable;\n\npublic:\n  tile_data() : c(nullptr), index(0), reusable(false), data(nullptr) {\n  }\n\n  tile_data(const tile_data& other) : c(nullptr) {\n    *this = other;\n  }\n\n  tile_data(cache_t* c, uint16_t index, bool reusable, const int16_t* data);\n  ~tile_data();\n  tile_data& operator=(const tile_data& other);\n\n  tile_data& operator=(tile_data&& other) {\n    std::swap(c, other.c);\n    std::swap(data, other.data);\n    std::swap(index, other.index);\n    std::swap(reusable, other.reusable);\n\n    return *this;\n  }\n\n  inline explicit operator bool() const {\n    return data != nullptr;\n  }\n\n  double get(double u, double v) const {\n    // integer pixel\n    size_t x = std::floor(u);\n    size_t y = std::floor(v);\n\n    // coefficients\n    double u_ratio = u - x;\n    double v_ratio = v - y;\n    double u_inv = 1 - u_ratio;\n    double v_inv = 1 - v_ratio;\n    double a_coef = u_inv * v_inv;\n    double b_coef = u_ratio * v_inv;\n    double c_coef = u_inv * v_ratio;\n    double d_coef = u_ratio * v_ratio;\n\n    // values\n    double adjust = 0;\n    auto a = flip(data[y * HGT_DIM + x]);\n    auto b = flip(data[y * HGT_DIM + x + 1]);\n    if (out_of_range(a)) {\n      a_coef = 0;\n    }\n    if (out_of_range(b)) {\n      b_coef = 0;\n    }\n\n    // first part of the bilinear interpolation\n    auto value = a * a_coef + b * b_coef;\n    adjust += a_coef + b_coef;\n    // LOG_INFO('{' + std::to_string(y * HGT_DIM + x) + ',' + std::to_string(a) + '}');\n    // LOG_INFO('{' + std::to_string(y * HGT_DIM + x + 1) + ',' + std::to_string(b) + '}');\n    // only need the second part if you aren't right on the row\n    // this also protects from a corner case where you sample past the end of the image\n    if (y < HGT_DIM - 1) {\n      auto c = flip(data[(y + 1) * HGT_DIM + x]);\n      auto d = flip(data[(y + 1) * HGT_DIM + x + 1]);\n      if (out_of_range(c)) {\n        c_coef = 0;\n      }\n      if (out_of_range(d)) {\n        d_coef = 0;\n      }\n      // LOG_INFO('{' + std::to_string((y + 1) * HGT_DIM + x) + ',' + std::to_string(c) + '}');\n      // LOG_INFO('{' + std::to_string((y + 1) * HGT_DIM + x + 1) + ',' + std::to_string(d) + '}');\n      value += c * c_coef + d * d_coef;\n      adjust += c_coef + d_coef;\n    }\n    // if we are missing everything then give up\n    if (adjust == 0) {\n      return NO_DATA_VALUE;\n    }\n    // if we were missing some we need to adjust by that\n    return value / adjust;\n  }\n};\n\nstruct cache_t {\n  // Cached tiles\n  std::vector<cache_item_t> cache;\n  // Set of reusable tile indexes\n  std::unordered_set<uint16_t> reusable;\n  // Map of pending tiles. No matter how many requests received, only one inflate job per tile\n  // started.\n  std::unordered_map<uint16_t, std::shared_future<tile_data>> pending_tiles;\n  // Guards access to the pending_tiles\n  std::recursive_mutex mutex;\n  // Elevation tile path\n  std::string data_source;\n\n  void increment_usages(uint16_t index) {\n    std::lock_guard<std::recursive_mutex> lock(mutex);\n    cache[index].get_usages()++;\n  }\n\n  void decrement_usages(uint16_t index) {\n    std::lock_guard<std::recursive_mutex> lock(mutex);\n    cache[index].get_usages()--;\n  }\n\n  tile_data source(uint16_t index);\n};\n\ntile_data::tile_data(cache_t* c, uint16_t index, bool reusable, const int16_t* data)\n    : c(c), data(data), index(index), reusable(reusable) {\n  if (reusable)\n    c->increment_usages(index);\n}\n\ntile_data::~tile_data() {\n  if (reusable)\n    c->decrement_usages(index);\n}\n\ntile_data& tile_data::operator=(const tile_data& other) {\n  if (c && reusable)\n    c->decrement_usages(index);\n\n  c = other.c;\n  data = other.data;\n  index = other.index;\n  reusable = other.reusable;\n\n  if (c && reusable)\n    c->increment_usages(index);\n  return *this;\n}\n\ntile_data cache_t::source(uint16_t index) {\n  // bail if it's out of bounds\n  if (index >= TILE_COUNT) {\n    return {};\n  }\n\n  // if we don't have anything maybe it's lazy loaded\n  auto& item = cache[index];\n  if (item.get_data() == nullptr) {\n    auto f = data_source + sample::get_hgt_file_name(index);\n    item.init(f, format_t::RAW);\n  }\n\n  // it wasn't in cache and when we tried to load it the file was of unknown type\n  if (item.get_format() == format_t::UNKNOWN) {\n    return {};\n  }\n\n  // we have it raw or we don't\n  if (item.get_format() == format_t::RAW) {\n    return {this, index, false, (const int16_t*)item.get_data()};\n  }\n\n  // we were able to load it but the format wasn't RAW, which only leaves compressed formats\n  mutex.lock();\n  auto it = pending_tiles.find(index);\n  if (it != pending_tiles.end()) {\n    auto future = it->second;\n    mutex.unlock();\n    return future.get();\n  }\n\n  // item in cache is already unpacked\n  const char* unpacked = item.get_unpacked();\n  if (unpacked) {\n    auto rv = tile_data(this, index, true, (const int16_t*)unpacked);\n    mutex.unlock();\n    return rv;\n  }\n\n  std::promise<tile_data> promise;\n  it = pending_tiles.emplace(index, promise.get_future()).first;\n\n  if (reusable.size() >= UNPACKED_TILES_COUNT) {\n    for (auto i : reusable) {\n      if (cache[i].get_usages() <= 0) {\n        reusable.erase(i);\n        unpacked = cache[i].detach_unpacked();\n        break;\n      }\n    }\n  }\n\n  if (!unpacked) {\n    unpacked = (char*)malloc(HGT_BYTES);\n  }\n  reusable.insert(index);\n  auto rv = tile_data(this, index, true, (const int16_t*)unpacked);\n  mutex.unlock();\n\n  if (!item.unpack(unpacked)) {\n    rv = tile_data();\n  }\n\n  mutex.lock();\n  promise.set_value(rv);\n  pending_tiles.erase(it);\n  mutex.unlock();\n  return rv;\n}\n\nsample::sample(const std::string& data_source) {\n  cache_ = new cache_t();\n  cache_->data_source = data_source;\n\n  // messy but needed\n  while (!cache_->data_source.empty() &&\n         cache_->data_source.back() == filesystem::path::preferred_separator) {\n    cache_->data_source.pop_back();\n  }\n\n  // If data_source is empty, do not allocate/resize mapped cache.\n  if (data_source.empty()) {\n    LOG_DEBUG(\"No elevation data_source was provided\");\n    return;\n  }\n  cache_->cache.resize(TILE_COUNT);\n\n  // check the directory for files that look like what we need\n  auto files = get_files(data_source);\n  for (const auto& f : files) {\n    // make sure its a valid index\n    auto data = cache_item_t::parse_hgt_name(f);\n    if (data && data->second != format_t::UNKNOWN) {\n      if (!cache_->cache[data->first].init(f, data->second)) {\n        LOG_WARN(\"Corrupt elevation data: \" + f);\n      }\n    }\n  }\n}\n\nsample::~sample() {\n  delete cache_;\n}\n\ntemplate <class coord_t> double sample::get(const coord_t& coord) {\n  // check the cache and load\n  auto lon = std::floor(coord.first);\n  auto lat = std::floor(coord.second);\n  auto index = static_cast<uint16_t>(lat + 90) * 360 + static_cast<uint16_t>(lon + 180);\n\n  // get the proper source of the data\n  const auto& tile = cache_->source(index);\n  if (!tile) {\n    return NO_DATA_VALUE;\n  }\n\n  // figure out what row and column we need from the array of data\n  // NOTE: data is arranged from upper left to bottom right, so y is flipped\n\n  // fractional pixel\n  double u = (coord.first - lon) * (HGT_DIM - 1);\n  double v = (1.0 - (coord.second - lat)) * (HGT_DIM - 1);\n\n  return tile.get(u, v);\n}\n\ntemplate <class coords_t> std::vector<double> sample::get_all(const coords_t& coords) {\n  std::vector<double> values;\n  values.reserve(coords.size());\n  uint16_t curIndex = TILE_COUNT;\n  tile_data tile(cache_, TILE_COUNT, false, nullptr);\n  for (const auto& coord : coords) {\n    auto lon = std::floor(coord.first);\n    auto lat = std::floor(coord.second);\n    auto index = static_cast<uint16_t>(lat + 90) * 360 + static_cast<uint16_t>(lon + 180);\n\n    if (index != curIndex) {\n      tile = cache_->source(index);\n      curIndex = index;\n    }\n\n    double value = NO_DATA_VALUE;\n    if (tile) {\n      double u = (coord.first - lon) * (HGT_DIM - 1);\n      double v = (1.0 - (coord.second - lat)) * (HGT_DIM - 1);\n      value = tile.get(u, v);\n    }\n\n    values.emplace_back(value);\n  }\n  return values;\n}\n\ndouble sample::get_no_data_value() {\n  return NO_DATA_VALUE;\n}\n\ntemplate <class coord_t> uint16_t sample::get_tile_index(const coord_t& coord) {\n  auto lon = std::floor(coord.first);\n  auto lat = std::floor(coord.second);\n  return static_cast<uint16_t>(lat + 90) * 360 + static_cast<uint16_t>(lon + 180);\n}\n\nvoid sample::add_single_tile(const std::string& path) {\n  cache_->cache.front().init(path, format_t::RAW);\n}\n\nstd::string sample::get_hgt_file_name(uint16_t index) {\n  auto x = (index % 360) - 180;\n  auto y = (index / 360) - 90;\n\n  std::string name(y < 0 ? \"/S\" : \"/N\");\n  y = std::abs(y);\n  if (y < 10) {\n    name.push_back('0');\n  }\n  name.append(std::to_string(y));\n  name.append(name);\n\n  name.append(x < 0 ? \"W\" : \"E\");\n  x = std::abs(x);\n  if (x < 100) {\n    name.push_back('0');\n  }\n  if (x < 10) {\n    name.push_back('0');\n  }\n  name.append(std::to_string(x));\n  name.append(\".hgt\");\n\n  return name;\n}\n\n// explicit instantiations for templated get\ntemplate double sample::get<std::pair<double, double>>(const std::pair<double, double>&);\ntemplate double sample::get<std::pair<float, float>>(const std::pair<float, float>&);\ntemplate double sample::get<midgard::PointLL>(const midgard::PointLL&);\ntemplate double sample::get<midgard::Point2>(const midgard::Point2&);\ntemplate std::vector<double>\nsample::get_all<std::list<std::pair<double, double>>>(const std::list<std::pair<double, double>>&);\ntemplate std::vector<double> sample::get_all<std::vector<std::pair<double, double>>>(\n    const std::vector<std::pair<double, double>>&);\ntemplate std::vector<double>\nsample::get_all<std::list<std::pair<float, float>>>(const std::list<std::pair<float, float>>&);\ntemplate std::vector<double>\nsample::get_all<std::vector<std::pair<float, float>>>(const std::vector<std::pair<float, float>>&);\ntemplate std::vector<double>\nsample::get_all<std::list<midgard::PointLL>>(const std::list<midgard::PointLL>&);\ntemplate std::vector<double>\nsample::get_all<std::vector<midgard::PointLL>>(const std::vector<midgard::PointLL>&);\ntemplate std::vector<double>\nsample::get_all<std::list<midgard::Point2>>(const std::list<midgard::Point2>&);\ntemplate std::vector<double>\nsample::get_all<std::vector<midgard::Point2>>(const std::vector<midgard::Point2>&);\ntemplate uint16_t\nsample::get_tile_index<std::pair<double, double>>(const std::pair<double, double>& coord);\ntemplate uint16_t\nsample::get_tile_index<std::pair<float, float>>(const std::pair<float, float>& coord);\ntemplate uint16_t sample::get_tile_index<midgard::PointLL>(const midgard::PointLL& coord);\ntemplate uint16_t sample::get_tile_index<midgard::Point2>(const midgard::Point2& coord);\n\n} // namespace skadi\n} // namespace valhalla\n", "meta": {"hexsha": "e72682ffeccb2011c6ce95450ef673aec34eb67e", "size": 16586, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/skadi/sample.cc", "max_stars_repo_name": "TimMcCauley/valhalla", "max_stars_repo_head_hexsha": "67c6a605a015d2737bb0822c2c3695a7326578e0", "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/skadi/sample.cc", "max_issues_repo_name": "TimMcCauley/valhalla", "max_issues_repo_head_hexsha": "67c6a605a015d2737bb0822c2c3695a7326578e0", "max_issues_repo_licenses": ["MIT"], "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/skadi/sample.cc", "max_forks_repo_name": "TimMcCauley/valhalla", "max_forks_repo_head_hexsha": "67c6a605a015d2737bb0822c2c3695a7326578e0", "max_forks_repo_licenses": ["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.098245614, "max_line_length": 99, "alphanum_fraction": 0.6381285421, "num_tokens": 4671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18205591355705053}}
{"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_IEEE_FUNCTIONS_PREDECESSOR_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_PREDECESSOR_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\n\nnamespace boost { namespace simd { namespace tag\n  {\n   /*!\n     @brief predecessor generic tag\n\n     Represents the predecessor function in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    struct predecessor_ : ext::elementwise_<predecessor_>\n    {\n      /// @brief Parent hierarchy\n      typedef ext::elementwise_<predecessor_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_predecessor_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n   template<class Site>\n   BOOST_FORCEINLINE generic_dispatcher<tag::predecessor_, Site> dispatching_predecessor_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n   {\n     return generic_dispatcher<tag::predecessor_, Site>();\n   }\n   template<class... Args>\n   struct impl_predecessor_;\n  }\n  /*!\n    With one parameter it is equivalent to \\c prev\n    It is in the type \\c A0, the greatest  \\c A0 elementwise strictly less than  \\c a0.\n    \\par\n    With two parameters, the second is an integer value  \\c n\n    and the result is equivalent to applying \\c prev \\c abs(n) times to  \\c a0.\n\n    @par Semantic:\n\n    @code\n    T r = predecessor(x);\n    @endcode\n\n    computes the greatest value strictly less than x in its type\n\n    @param a0\n\n    @return a value of same type as the inputs\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::predecessor_, predecessor, 1)\n  /*!\n    Returns the n-th greatest element strictly less than the parameter\n\n    @par Semantic:\n\n    @code\n    T r = predecessor(x,n);\n    @endcode\n\n    computes the @c n-th greatest value strictly less than x in its type.\n    n must be positive or null.\n    For integer it saturate at Valmin, for floating point numbers Minf\n    strict predecessors are Nan\n\n    @param a0\n\n    @param a1\n\n    @return a value of same type as the inputs\n  **/\n    BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::predecessor_, predecessor, 2)\n} }\n\n#endif\n", "meta": {"hexsha": "3d62c5a2e26647ae777a5455ddc2c0697b466bf5", "size": 2727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/ieee/functions/predecessor.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/ieee/functions/predecessor.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/ieee/functions/predecessor.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": 30.9886363636, "max_line_length": 145, "alphanum_fraction": 0.6464979831, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3451052844289766, "lm_q1q2_score": 0.181979723912125}}
{"text": "\ufeff#include <iostream>\n#include <boost/format.hpp>\n#include <vector>\n\n#include <boost/range/algorithm_ext/erase.hpp>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <unordered_map>\n#include <data_type.hpp>\n#include <image_algorithm/compare.hpp>\n#include <image_algorithm/adjacent.hpp>\n#include <image_algorithm/Murakami.hpp>\n#include <./gui.hpp>\n#include <boost/timer.hpp>\nMurakami::Murakami(question_raw_data const& data, compared_type const& comp,bool const w_mode)\n\t: data_(data), comp_(comp)\n{\n}\n/*\u84ee\u30e1\u30ea\u3061\u3085\u3063\u3061\u3085*/\nstd::vector<answer_type_y> Murakami::operator() (){\n\tbool const w_mode = true;\n\tauto const width = data_.split_num.first;\n\tauto const height = data_.split_num.second;\n\t//sort_compare();//sorted_comparation\u4f5c\u6210\n\t/*\n\t#ifdef _OPENMP\n\t//OpenMP\u3092\u4f7f\u3063\u305f\u30b3\u30fc\u30c9\n\tstd::cout << \"use openMP\" << std::endl;\n\t#else\n\t//OpenMP\u3092\u4f7f\u308f\u306a\u3044\u5834\u5408\u306e\u30b3\u30fc\u30c9\n\tstd::cout << \"no use openMP\" << std::endl;\n\t#endif\n\t*/\n\tmake_sorted_comparation();\n\t//boost::timer t;\n\tstd::vector<block_data_> block_list(height * width);\n\tunsigned int unique_number_cnt = 0;\n\t//\u30d6\u30ed\u30c3\u30af\u306e\u5de6\u4e0a\u306b\u5206\u5272\u753b\u50cf\u3092\u914d\u7f6e\u3059\u308b\u30eb\u30fc\u30d7\n\tfor (int i = 0; i < height; i++){\n\t\tfor (int j = 0; j < width; j++){\n\t\t\t//block_list[i * width + j][0][0].y = i;\n\t\t\t//block_list[i * width + j][0][0].x = j;\n\t\t\tblock_list[i * width + j].block = { { { j, i } } };//std::vector < std::vector<point_type> > {std::vector < point_type > {point_type{ j, i } }};\n\t\t\tblock_list[i * width + j].u_this_number = unique_number_cnt;\n\t\t\tunique_number_cnt++;\n\t\t}\n\t}\n\t\t//std::cout << \"a\";\n\t\t//block_combination b;\n\tfor (int i = 0; i < block_list.size(); i++){//\u30d6\u30ed\u30c3\u30af\u6bd4\u8f03\u30eb\u30fc\u30d7\u6539\u826f\n\t\tblock_combination b;\n\t\tfor (int j = i; j < block_list.size(); j++){\n\t\t\tif (i == j) continue;\n\t\t\tb = w_mode ? eval_block(block_list[i].block, block_list[j].block) : eval_block2(block_list[i].block, block_list[j].block);\n\t\t\tblock_list[i].score_data_[block_list[j].u_this_number] = std::move(score_data{ b.score, b.shift_x, b.shift_y });\n\t\t}\n\t}\n\tint a;//\u30c7\u30d0\u30c3\u30b0\u7528\u306e\u5909\u6570\n\ttry{\n\t\twhile (block_list.size() != 1){//\u30e1\u30a4\u30f3\u30eb\u30fc\u30d7\n\t\t\ta = block_list.size();\n\t\t\tblock_combination best_block_combination;//\u4e00\u756a\u3044\u3044block\u306e\u7d44\u307f\u5408\u308f\u305b\u3044\u308c\u308b\u3068\u3053\u308d\n\t\t\tbest_block_combination.score = std::numeric_limits<bigint>::min();\n\t\t\tblock_combination b;\n\t\t\tfor (int i = 0; i < block_list.size(); i++){//\u30d6\u30ed\u30c3\u30af\u6bd4\u8f03\u30eb\u30fc\u30d7\u6539\u826f\n\t\t\t\tfor (int j = i; j < block_list.size(); j++){\n\t\t\t\t\tif (i == j) continue;\n\t\t\t\t\tstd::unordered_map<unsigned int, score_data>::iterator m_it = block_list[i].score_data_.find(block_list[j].u_this_number);\n\t\t\t\t\tif (m_it != block_list[i].score_data_.end()){\n\t\t\t\t\t\t//TODO \u3053\u3053\u3092\u53c2\u7167\u6e21\u3057\u306b\u3059\u308b\n\t\t\t\t\t\tb.block1 = block_list[i].block;\n\t\t\t\t\t\tb.block2 = block_list[j].block;\n\t\t\t\t\t\tb.score = block_list[i].score_data_[m_it->first].score;\n\t\t\t\t\t\tb.shift_x = block_list[i].score_data_[m_it->first].shift_x;\n\t\t\t\t\t\tb.shift_y = block_list[i].score_data_[m_it->first].shift_y;\n\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tb = w_mode ? eval_block(block_list[i].block, block_list[j].block) : eval_block2(block_list[i].block, block_list[j].block);\n\t\t\t\t\t}\n\t\t\t\t\tif (best_block_combination.score < b.score)best_block_combination = std::move(b);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (best_block_combination.score == std::numeric_limits<bigint>::min()){\n\t\t\t\t//std::cout << \"\u672c\u5f53\u306b\u7d50\u5408\u3059\u308b\u30d6\u30ed\u30c3\u30af\u304c\u306a\u304b\u3063\u305f\u306e\u3067\u89e3\u3092\u51fa\u3055\u305a\u306bMurakami\u306f\u7d42\u4e86\u3057\u307e\u3059\";\n\t\t\t\tthrow std::runtime_error(\"Murakami_runtime_error\");\n\t\t\t}\n\t\t\tblock_type combined_block = std::move(combine_block(best_block_combination));//\u30d6\u30ed\u30c3\u30af\u3092\u7d50\u5408\u3059\u308b\n\t\t\tboost::remove_erase_if(block_list, [&best_block_combination](block_data_ it){//block_list\u304b\u3089\u7d50\u5408\u3059\u308b\u524d\u306e\u30d6\u30ed\u30c3\u30af\u3092\u6d88\u3059\n\t\t\t\treturn (it.block == best_block_combination.block1 || it.block == best_block_combination.block2);\n\t\t\t});\n\t\t\tblock_data_ p_b;\n\t\t\tp_b.block = combined_block;\n\t\t\tblock_list.push_back(p_b);//\u7d50\u5408\u3057\u305f\u306e\u3092\u5165\u308c\u308b\n\t\t\t//std::cout << \"***\" << block_list.size() << \"***\" << \"\\r\" << std::flush;\n\n\t\t\t/*\n\t\t\tfor (const auto& i : block_list){\n\t\t\tfor (const auto& j : i.block){\n\t\t\tfor (const auto& k : j){\n\t\t\t//std::cout << k.x << \",\" << k.y << \" \";\n\t\t\tstd::cout << boost::format(\"(%2d,%2d)\") % k.x % k.y;\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t\t}\n\t\t\t*/\n\t\t\t/*\u30c7\u30d0\u30c3\u30b0\u753b\u50cf\u8868\u793a\n\t\t\tstd::vector<std::vector<std::vector<point_type>>> raw_block_list;\n\t\t\tfor (auto const& block_it : block_list){\n\t\t\traw_block_list.push_back(block_it.block);\n\t\t\t}\n\t\t\tgui::combine_show_image(data_, comp_, raw_block_list);\n\t\t\t*/\n\t\t}\n\t}catch (...){\n\t\tstd::cerr << \"\u30c0\u30e1_Murakami_\u3060\u3081\" << std::endl;\n\t\t\t//std::cout << t.elapsed() << \"s\u7d4c\u904e\u3057\u305f(Murakami\u5185\u3067\u8a08\u6e2c)\" << std::endl;\n\t\t\tstd::vector<std::vector<point_type>>exception_array;\n\t\t\tstd::vector<block_type> temp_array;\n\t\t\tfor (auto hoge : block_list){\n\t\t\t\ttemp_array.push_back(hoge.block);\n\t\t\t}\n\t\t\texception_array = std::move(force_combine_block(temp_array));\n\t\t\treturn std::vector<answer_type_y>{ { std::move(exception_array), 0, cv::Mat() } }; \n\n\t\t}\n\t\t//std::cout << t.elapsed() << \"s\u7d4c\u904e\u3057\u305f(Murakami\u5185\u3067\u8a08\u6e2c)\" << std::endl;\n\t\t/*\u30c7\u30d0\u30c3\u30b0\u8868\u793a\n\t\tfor (int i = 0; i < height; i++){\n\t\t\tfor (int j = 0; j < width; j++){\n\t\t\t\tstd::cout << block_list[0].block[i][j].x << \",\" << block_list[0].block[i][j].y << \"|\";\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n\t\t*/\n\t\treturn std::vector<answer_type_y>{ { block_list.at(0).block, 0, cv::Mat() } };\n\n}\nMurakami::block_combination Murakami::eval_block(const block_type& block1, const block_type& block2){\n\n\tauto const width = data_.split_num.first;\n\tauto const height = data_.split_num.second;\n\tint const b1_width = block1[0].size();\n\tint const b1_height = block1.size();\n\tint const b2_width = block2[0].size();\n\tint const b2_height = block2.size();\n\t\n\tauto const block1_exists = [b1_height, b1_width, &block1](int y, int x){\n\t\treturn ((x >= 0 && x < b1_width && y >= 0 && y < b1_height) && (block1[y][x].x != -1 || block1[y][x].y != -1));\n\t};\n\tauto const block2_exists = [b2_height, b2_width, &block2](int y, int x){\n\t\treturn ((x >= 0 && x < b2_width && y >= 0 && y < b2_height) && (block2[y][x].x != -1 || block2[y][x].y != -1));\n\n\t};\n\tauto const block_size_check = [b1_width, b1_height, b2_width, b2_height, width, height](int shift_y,int shift_x){\n\t\treturn (std::max(b1_width, shift_x + b2_width) - std::min(0, shift_x) <= width && std::max(b1_height, shift_y + b2_height) - std::min(0, shift_y) <= height);\n\t};\n\tbigint best_block_c = std::numeric_limits<bigint>::min();\n\n\tint best_shift_i = std::numeric_limits<int>::min();\n\tint best_shift_j = std::numeric_limits<int>::min();\n\tfor (int i = -b2_height -1; i <= b1_height + b2_height + 1; i++){\n\t\tfor (int j = -b2_width -1; j <= b1_width + b2_width + 1; j++){\n\t\t\tbool confliction = false;\n\t\t\tif (!block_size_check(i, j)){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbigint block_c = 0;\n\t\t\tbool empty_block_c = true;\n\t\t\tint rank1_num = 0;\n\t\t\tfor (int k = 0; k < b1_height; k++){\n\t\t\t\tfor (int l = 0; l < b1_width; l++){\n\t\t\t\t\tif (block2_exists(k - i, l - j) && block1_exists(k, l)){\n\t\t\t\t\t\t\tconfliction = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}else if (block1_exists(k, l) && !block2_exists(k - i, l - j)){\n\t\t\t\t\t\t//int_fast64_t piece_c = 0;\n\t\t\t\t\t\tif (block2_exists(k - i - 1, l - j)){//\u4e0a\n\t\t\t\t\t\t\tblock_c += eval_piece(block1[k][l], block2[k - i - 1][l - j], up);\n\t\t\t\t\t\t\tempty_block_c = false;\n\t\t\t\t\t\t\tif (sorted_comparation[block1[k][l]][up][1] == block2[k - i - 1][l - j]) rank1_num++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block2_exists(k - i, l - j - 1)){//\u5de6\n\t\t\t\t\t\t\tblock_c += eval_piece(block1[k][l], block2[k - i][l - j - 1], left);\n\t\t\t\t\t\t\tempty_block_c = false;\n\t\t\t\t\t\t\tif (sorted_comparation[block1[k][l]][left][1] == block2[k - i][l - j - 1]) rank1_num++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block2_exists(k - i + 1, l - j)){//\u4e0b\n\t\t\t\t\t\t\tblock_c += eval_piece(block1[k][l], block2[k - i + 1][l - j], down);\n\t\t\t\t\t\t\tempty_block_c = false;\n\t\t\t\t\t\t\tif (sorted_comparation[block1[k][l]][down][1] == block2[k - i + 1][l - j]) rank1_num++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block2_exists(k - i, l - j + 1)){//\u53f3\n\t\t\t\t\t\t\tblock_c += eval_piece(block1[k][l], block2[k - i][l - j + 1], right);\n\t\t\t\t\t\t\tempty_block_c = false;\n\t\t\t\t\t\t\tif (sorted_comparation[block1[k][l]][right][1] == block2[k - i][l - j + 1]) rank1_num++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (confliction)break;\n\t\t\t}\n\t\t\tif (!confliction && !empty_block_c){\n\t\t\t\t++rank1_num;\n\t\t\t\t//block_c *= rank1_num; //0\u3092\u639b\u3051\u308b\u306e\u306f\u6016\u3044\n\t\t\t\tif(block_c < 0)block_c = -pow(block_c, rank1_num);\n\t\t\t\tif (block_c > 0)block_c = pow(block_c, rank1_num);\n\t\t\t\tif (block_c >= best_block_c){\n\t\t\t\t\t//block_size_check(i, j)\n\t\t\t\t\tbest_block_c = block_c;\n\t\t\t\t\tbest_shift_i = i;\n\t\t\t\t\tbest_shift_j = j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/*\n\tif (best_shift_i == std::numeric_limits<int>::min()){\n\t\tstd::cout << \"\u7d50\u5408\u3059\u3079\u304d\u30d6\u30ed\u30c3\u30af\u304c\u306a\u304b\u3063\u305f\" << std::endl;\n\t}\n\t*/\n\tblock_combination return_struct{\n\t\tstd::move(block1),\n\t\tstd::move(block2),\n\t\tbest_shift_j,\n\t\tbest_shift_i,\n\t\tbest_block_c\n\t};\n\treturn std::move(return_struct);\n}\nMurakami::block_combination Murakami::eval_block2(const block_type& block1, const block_type& block2){\n\n\tauto const width = data_.split_num.first;\n\tauto const height = data_.split_num.second;\n\tint const b1_width = block1[0].size();\n\tint const b1_height = block1.size();\n\tint const b2_width = block2[0].size();\n\tint const b2_height = block2.size();\n\n\tauto const block1_exists = [b1_height, b1_width, &block1](int y, int x){\n\t\treturn ((x >= 0 && x < b1_width && y >= 0 && y < b1_height) && (block1[y][x].x != -1 || block1[y][x].y != -1));\n\t};\n\tauto const block2_exists = [b2_height, b2_width, &block2](int y, int x){\n\t\treturn ((x >= 0 && x < b2_width && y >= 0 && y < b2_height) && (block2[y][x].x != -1 || block2[y][x].y != -1));\n\n\t};\n\tauto const block_size_check = [b1_width, b1_height, b2_width, b2_height, width, height](int shift_y, int shift_x){\n\t\treturn (std::max(b1_width, shift_x + b2_width) - std::min(0, shift_x) <= width && std::max(b1_height, shift_y + b2_height) - std::min(0, shift_y) <= height);\n\t};\n\tbigint best_block_c = std::numeric_limits<bigint>::min();\n\n\tint best_shift_i = std::numeric_limits<int>::min();\n\tint best_shift_j = std::numeric_limits<int>::min();\n\tfor (int i = -b2_height - 1; i <= b1_height + b2_height + 1; i++){\n\t\tfor (int j = -b2_width - 1; j <= b1_width + b2_width + 1; j++){\n\t\t\tbool confliction = false;\n\t\t\tif (!block_size_check(i, j)){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbigint block_c = 0;\n\t\t\tbool empty_block_c = true;\n\t\t\tint rank1_num = 0;\n\t\t\tfor (int k = 0; k < b1_height; k++){\n\t\t\t\tfor (int l = 0; l < b1_width; l++){\n\t\t\t\t\tif (block2_exists(k - i, l - j) && block1_exists(k, l)){\n\t\t\t\t\t\tconfliction = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse if (block1_exists(k, l) && !block2_exists(k - i, l - j)){\n\t\t\t\t\t\t//int_fast64_t piece_c = 0;\n\t\t\t\t\t\tif (block2_exists(k - i - 1, l - j)){//\u4e0a\n\t\t\t\t\t\t\tblock_c += eval_piece(block1[k][l], block2[k - i - 1][l - j], up);\n\t\t\t\t\t\t\tempty_block_c = false;\n\t\t\t\t\t\t\tif (sorted_comparation[block1[k][l]][up][1] == block2[k - i - 1][l - j]) rank1_num++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block2_exists(k - i, l - j - 1)){//\u5de6\n\t\t\t\t\t\t\tblock_c += eval_piece(block1[k][l], block2[k - i][l - j - 1], left);\n\t\t\t\t\t\t\tempty_block_c = false;\n\t\t\t\t\t\t\tif (sorted_comparation[block1[k][l]][left][1] == block2[k - i][l - j - 1]) rank1_num++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block2_exists(k - i + 1, l - j)){//\u4e0b\n\t\t\t\t\t\t\tblock_c += eval_piece(block1[k][l], block2[k - i + 1][l - j], down);\n\t\t\t\t\t\t\tempty_block_c = false;\n\t\t\t\t\t\t\tif (sorted_comparation[block1[k][l]][down][1] == block2[k - i + 1][l - j]) rank1_num++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block2_exists(k - i, l - j + 1)){//\u53f3\n\t\t\t\t\t\t\tblock_c += eval_piece(block1[k][l], block2[k - i][l - j + 1], right);\n\t\t\t\t\t\t\tempty_block_c = false;\n\t\t\t\t\t\t\tif (sorted_comparation[block1[k][l]][right][1] == block2[k - i][l - j + 1]) rank1_num++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (confliction)break;\n\t\t\t}\n\t\t\tif (!confliction && !empty_block_c){\n\t\t\t\t++rank1_num;\n\t\t\t\tblock_c *= rank1_num; //0\u3092\u639b\u3051\u308b\u306e\u306f\u6016\u3044\n\t\t\t\t//if (block_c < 0)block_c = -pow(block_c, rank1_num);\n\t\t\t\t//if (block_c > 0)block_c = pow(block_c, rank1_num);\n\t\t\t\tif (block_c >= best_block_c){\n\t\t\t\t\t//block_size_check(i, j)\n\t\t\t\t\tbest_block_c = block_c;\n\t\t\t\t\tbest_shift_i = i;\n\t\t\t\t\tbest_shift_j = j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/*\n\tif (best_shift_i == std::numeric_limits<int>::min()){\n\tstd::cout << \"\u7d50\u5408\u3059\u3079\u304d\u30d6\u30ed\u30c3\u30af\u304c\u306a\u304b\u3063\u305f\" << std::endl;\n\t}\n\t*/\n\tblock_combination return_struct{\n\t\tstd::move(block1),\n\t\tstd::move(block2),\n\t\tbest_shift_j,\n\t\tbest_shift_i,\n\t\tbest_block_c\n\t};\n\treturn std::move(return_struct);\n}\nstd::int_fast64_t Murakami::eval_piece(const point_type& p1, const point_type& p2, direction dir){\n\tint_fast64_t score = 0;\n\tMurakami::direction dir2;\n\tswitch (dir)\n\t{\n\tcase Murakami::up:\n\t\tdir2 = Murakami::down;\n\t\tbreak;\n\tcase Murakami::right:\n\t\tdir2 = Murakami::left;\n\t\tbreak;\n\tcase Murakami::down:\n\t\tdir2 = Murakami::up;\n\t\tbreak;\n\tcase Murakami::left:\n\t\tdir2 = Murakami::right;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\tscore += eval_comp_(p1, p2, dir);\n\tscore += eval_comp_(p2, p1, dir2);\n\treturn score;\n}\nstd::int_fast64_t Murakami::eval_comp_(const point_type& p1, const point_type& p2, direction dir){\n\tint rank = 0;\n\tstd::int_fast64_t score = 0;\n\t/*\u3053\u306e\u65b9\u304c\u304b\u3063\u3053\u3044\u3044\u3051\u3069\u3061\u3087\u3063\u3068\u9045\u3044\n\tstd::vector<point_type>::iterator it = find(sorted_comparation[p1][dir].begin(), sorted_comparation[p1][dir].end(), p2);\n\trank = it - sorted_comparation[p1][dir].begin();\n\t*/\n\t\n\tfor (const auto& it : sorted_comparation[p1][dir]){\n\t\tif (it == p2)break;\n\t\trank++;\n\t}\n\t\n\tif (rank == 0)throw std::runtime_error(\"\u65ad\u7247\u753b\u50cf\u304c\u91cd\u8907\u3057\u3066\u3044\u307e\u3059\");\n\tif (rank == 1){\n\t\tswitch (dir)\n\t\t{\n\t\tcase Murakami::up:\n\t\t\tscore = comp_[p1.y][p1.x][sorted_comparation[p1][up][2].y][sorted_comparation[p1][up][2].x].up - comp_[p1.y][p1.x][p2.y][p2.x].up;\n\t\t\tbreak;\n\t\tcase Murakami::right:\n\t\t\tscore = comp_[p1.y][p1.x][sorted_comparation[p1][right][2].y][sorted_comparation[p1][right][2].x].right - comp_[p1.y][p1.x][p2.y][p2.x].right;\n\t\t\tbreak;\n\t\tcase Murakami::down:\n\t\t\tscore = comp_[p1.y][p1.x][sorted_comparation[p1][down][2].y][sorted_comparation[p1][down][2].x].down - comp_[p1.y][p1.x][p2.y][p2.x].down;\n\t\t\tbreak;\n\t\tcase Murakami::left:\n\t\t\tscore = comp_[p1.y][p1.x][sorted_comparation[p1][left][2].y][sorted_comparation[p1][left][2].x].left - comp_[p1.y][p1.x][p2.y][p2.x].left;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\telse if (rank > 1){\n\t\tswitch (dir)\n\t\t{\n\t\tcase Murakami::up:\n\t\t\tscore = comp_[p1.y][p1.x][sorted_comparation[p1][up][1].y][sorted_comparation[p1][up][1].x].up - comp_[p1.y][p1.x][p2.y][p2.x].up;\n\t\t\tbreak;\n\t\tcase Murakami::right:\n\t\t\tscore = comp_[p1.y][p1.x][sorted_comparation[p1][right][1].y][sorted_comparation[p1][right][1].x].right - comp_[p1.y][p1.x][p2.y][p2.x].right;\n\t\t\tbreak;\n\t\tcase Murakami::down:\n\t\t\tscore = comp_[p1.y][p1.x][sorted_comparation[p1][down][1].y][sorted_comparation[p1][down][1].x].down - comp_[p1.y][p1.x][p2.y][p2.x].down;\n\t\t\tbreak;\n\t\tcase Murakami::left:\n\t\t\tscore = comp_[p1.y][p1.x][sorted_comparation[p1][left][1].y][sorted_comparation[p1][left][1].x].left - comp_[p1.y][p1.x][p2.y][p2.x].left;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\telse{\n\n\t}\n\treturn score;\n}\n\n\nvoid Murakami::make_sorted_comparation(){\n\tauto width = data_.split_num.first;\n\tauto height = data_.split_num.second;\n\tstruct point_type_score{\n\t\tpoint_type point;\n\t\tint_fast64_t score;\n\t\tbool operator<(const point_type_score& right) const {\n\t\t\treturn (score < right.score);\n\t\t}\n\t};\n\n\tstd::unordered_map<point_type, std::vector<std::vector<point_type>>> sorted_point_score_dir_point;\n\tfor (int k = 0; k < height; k++){\n\t\tfor (int l = 0; l < width; l++){\n\t\t\tpoint_type point_k_l{ l, k };\n\t\t\tstd::vector<std::vector<point_type>> sorted_point_score_dir;\n\t\t\tfor (int dir_l = 0; dir_l < 4; dir_l++){\n\t\t\t\tstd::vector<point_type_score> sorted_point_score;\n\t\t\t\tfor (int i = 0; i < height; i++){\n\t\t\t\t\tfor (int j = 0; j < width; j++){\n\t\t\t\t\t\tpoint_type p{ j, i };\n\t\t\t\t\t\tpoint_type_score t;\n\t\t\t\t\t\tt.point = p;\n\t\t\t\t\t\tswitch (dir_l)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase up:\n\t\t\t\t\t\t\tt.score = comp_[k][l][i][j].up;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase right:\n\t\t\t\t\t\t\tt.score = comp_[k][l][i][j].right;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase down:\n\t\t\t\t\t\t\tt.score = comp_[k][l][i][j].down;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase left:\n\t\t\t\t\t\t\tt.score = comp_[k][l][i][j].left;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsorted_point_score.push_back(t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstd::sort(sorted_point_score.begin(), sorted_point_score.end());\n\t\t\t\tstd::vector<point_type> p_vec;\n\t\t\t\tfor (int a = 0; a < height * width; a++){\n\t\t\t\t\tp_vec.push_back(sorted_point_score[a].point);\n\t\t\t\t}\n\t\t\t\tsorted_point_score_dir.push_back(p_vec);\n\t\t\t}\n\t\t\tsorted_point_score_dir_point[point_k_l] = sorted_point_score_dir;\n\t\t}\n\n\t}\n\n\tsorted_comparation = std::move(sorted_point_score_dir_point);\n}\nMurakami::block_type Murakami::combine_block(const block_combination& block_comb){\n\n\tif (block_comb.block1.size() == 0)throw std::runtime_error(\"\u7d50\u5408\u4e88\u5b9a\u30d6\u30ed\u30c3\u30af\u306e\u30b5\u30a4\u30ba\u304c0\u3067\u3059,block1\");\n\tif (block_comb.block2.size() == 0)throw std::runtime_error(\"\u7d50\u5408\u4e88\u5b9a\u30d6\u30ed\u30c3\u30af\u306e\u30b5\u30a4\u30ba\u304c0\u3067\u3059,block2\");\n\tint const b1_width = block_comb.block1[0].size();\n\tint const b1_height = block_comb.block1.size();\n\tint const b2_width = block_comb.block2[0].size();\n\tint const b2_height = block_comb.block2.size();\n\tpoint_type lu, rd; //lu left_up,\u5de6\u4e0a rd right_down,\u53f3\u4e0b\n\tlu.x = std::min(0, block_comb.shift_x);\n\tlu.y = std::min(0, block_comb.shift_y);\n\trd.x = std::max(b1_width, block_comb.shift_x + b2_width);\n\trd.y = std::max(b1_height, block_comb.shift_y + b2_height);\n\tblock_size_type comb_block_size = rd - lu;\n\tauto const block1_exists = [b1_height, b1_width, &block_comb](int y, int x){\n\t\treturn ((x >= 0 && x < b1_width && y >= 0 && y < b1_height) && (block_comb.block1[y][x].x != -1 || block_comb.block1[y][x].y != -1));\n\t};\n\tauto const block2_exists = [b2_height, b2_width, &block_comb](int y, int x){\n\t\treturn ((x >= 0 && x < b2_width && y >= 0 && y < b2_height) && (block_comb.block2[y][x].x != -1 || block_comb.block2[y][x].y != -1));\n\n\t};\n\tauto const width = data_.split_num.first;\n\tauto const height = data_.split_num.second;\n\tint l_x = 0, l_y = 0;\n\tif (block_comb.shift_x < 0)l_x = -block_comb.shift_x;\n\tif (block_comb.shift_y < 0)l_y = -block_comb.shift_y;\n\tstd::vector<std::vector<point_type>> return_combined_block(comb_block_size.y, std::vector<point_type>(comb_block_size.x, { -1, -1 }));\n\n\tfor (int i = lu.y; i < rd.y; i++){\n\t\tfor (int j = lu.x; j < rd.x; j++){\n\t\t\tif (block1_exists(i,j)){\n\t\t\t\treturn_combined_block[i + l_y][j + l_x] = block_comb.block1[i][j];\n\t\t\t}else if (block2_exists(i - block_comb.shift_y, j - block_comb.shift_x)){\n\t\t\t\treturn_combined_block[i + l_y][j + l_x] = block_comb.block2[i - block_comb.shift_y][j - block_comb.shift_x];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn return_combined_block;\n\n}\n\nMurakami::block_type Murakami::force_combine_block(std::vector<Murakami::block_type>& block_list){\n\tauto max_block_it = std::max_element(block_list.begin(), block_list.end(), [](const block_type& a, const block_type& b){\n\t\treturn(a.size() + a[0].size() < b.size() + b[0].size());\n\t});\n\tblock_type max_block = (*max_block_it);\n\n\tboost::remove_erase_if(block_list, [&max_block](block_type it){//block_list\u304b\u3089\u7d50\u5408\u3059\u308b\u524d\u306e\u30d6\u30ed\u30c3\u30af\u3092\u6d88\u3059\n\t\treturn (it == max_block);\n\t});\n\n\tstd::for_each(\n\t\tmax_block.begin(), max_block.end(),\n\t\t[this](std::vector<point_type>& elem)\n\t\t{\n\t\t\telem.resize(data_.split_num.first, point_type{ -1, -1 });\n\t\t});\n\n\tmax_block.resize(data_.split_num.second, std::vector<point_type>(data_.split_num.first, point_type{-1,-1}));\n\n\tfor (auto &i : max_block){\n\t\tfor (auto &j : i){\n\t\t\tif (j.x == -1 || j.y == -1){\n\t\t\t\tfor (auto &list_i : block_list){\n\t\t\t\t\tfor (auto &list_j : list_i){\n\t\t\t\t\t\tfor (auto &list_k : list_j){\n\t\t\t\t\t\t\tif (list_k.x != -1 || list_k.y != -1){\n\t\t\t\t\t\t\t\tj = list_k;\n\t\t\t\t\t\t\t\tlist_k.x = -1;\n\t\t\t\t\t\t\t\tlist_k.y = -1;\n\t\t\t\t\t\t\t\tgoto KIRISAME_MARISA;\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\tKIRISAME_MARISA:;\n\t\t}\n\t}\n\n\treturn max_block;\n\t/*\n\tauto pick_up_without_it = [&block_list](const block_type){\n\t\t\n\t};\n\tfor (auto i : (*max_block_it)){\n\t\tfor (auto j : i){\n\t\t\tif (!(j.x == -1) || !(j.y == -1))continue;\n\t\t\tpick_up_without_it(max_block_it);\n\t\t}\n\t}\n\t*/\n}\n", "meta": {"hexsha": "4ac69e9e0afeabaaa01bf4214cf8ac5f34426a6f", "size": 19429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clammbon/src/image_algorithm/Murakami.cpp", "max_stars_repo_name": "tnct-spc/procon2014", "max_stars_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-02T08:42:05.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-02T08:42:05.000Z", "max_issues_repo_path": "clammbon/src/image_algorithm/Murakami.cpp", "max_issues_repo_name": "tnct-spc/procon2014", "max_issues_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clammbon/src/image_algorithm/Murakami.cpp", "max_forks_repo_name": "tnct-spc/procon2014", "max_forks_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_forks_repo_licenses": ["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.632798574, "max_line_length": 159, "alphanum_fraction": 0.6261773637, "num_tokens": 6612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.18197971878500463}}
{"text": "// Gazebo hardware interface\n// Author: Max Schwarz <max.schwarz@uni-bonn.de>\n\n#include <robotcontrol/hw/gazebointerface.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <eigen_conversions/eigen_msg.h>\n#include <tf_conversions/tf_eigen.h>\n#include <pluginlib/class_list_macros.h>\n\nnamespace robotcontrol\n{\n\nGazeboInterface::GazeboInterface()\n{\n}\n\nGazeboInterface::~GazeboInterface()\n{\n}\n\nbool GazeboInterface::init(RobotModel* model)\n{\n\tm_model = model;\n\n\tif(!ROSControlInterface::init(model))\n\t\treturn false;\n\n\tros::NodeHandle nh(\"~\");\n\tif(!nh.getParam(\"modelName\", m_modelName))\n\t{\n\t\tROS_FATAL(\"modelName parameter is mandatory for GazeboInterface!\");\n\t\treturn false;\n\t}\n\n\tnh.param(\"/gazebo_perfect_odometry\", m_publishOdom, false);\n\n\tm_sub_modelStates = nh.subscribe(\"/gazebo/model_states\", 1, &GazeboInterface::handleModelStates, this);\n\n\tm_initTime = ros::Time::now();\n\n\treturn true;\n}\n\nvoid GazeboInterface::handleModelStates(const gazebo_msgs::ModelStatesConstPtr& ms)\n{\n\t// Sadly, gazebo does not provide a stamp.\n\tm_last_modelStatesStamp = ros::Time::now();\n\tm_last_modelStates = ms;\n}\n\ndouble signedAngleBetween(const Eigen::Vector3d& dir1, const Eigen::Vector3d& dir2, const Eigen::Vector3d& norm)\n{\n\tdouble dot = dir1.dot(dir2);\n\n\tif(dot < -1.0)\n\t\tdot = -1.0;\n\tif(dot > 1.0)\n\t\tdot = 1.0;\n\n\tdouble angle = acos(dot);\n\n\tEigen::Vector3d cross = dir1.cross(dir2);\n\tdouble sign = norm.dot(cross);\n\tif(sign < 0)\n\t\tangle *= -1.0;\n\n\treturn angle;\n}\n\nbool GazeboInterface::readJointStates()\n{\n\tif(!ROSControlInterface::readJointStates())\n\t\treturn false;\n\n\tif(m_last_modelStates)\n\t{\n\t\tstd::vector<std::string>::const_iterator it = std::find(\n\t\t\tm_last_modelStates->name.begin(), m_last_modelStates->name.end(),\n\t\t\tm_modelName\n\t\t);\n\n\t\tif(it != m_last_modelStates->name.end())\n\t\t{\n\t\t\tint idx = it - m_last_modelStates->name.begin();\n\n\t\t\t//\n\t\t\t// Orientation feedback\n\t\t\t//\n\n\t\t\t// Retrieve the robot pose\n\t\t\tconst geometry_msgs::Pose& pose = m_last_modelStates->pose[idx];\n\n\t\t\t// Set the robot orientation\n\t\t\tEigen::Quaterniond quat;\n\t\t\ttf::quaternionMsgToEigen(pose.orientation, quat);\n\t\t\tquat.normalize();\n\t\t\tm_model->setRobotOrientation(quat);\n\n\t\t\t// Provide /odom if wanted. Convention: /odom is on the floor.\n\t\t\tif(m_publishOdom && m_last_modelStatesStamp - m_initTime > ros::Duration(3.0))\n\t\t\t{\n\t\t\t\ttf::StampedTransform trans;\n\t\t\t\ttrans.frame_id_ = \"/odom\";\n\t\t\t\ttrans.child_frame_id_ = \"/ego_rot\";\n\t\t\t\ttrans.stamp_ = m_last_modelStatesStamp;\n\t\t\t\ttrans.setIdentity();\n\n\t\t\t\ttf::Vector3 translation;\n\t\t\t\ttf::pointMsgToTF(pose.position, translation);\n\n\t\t\t\ttrans.setOrigin(translation);\n\n\t\t\t\tEigen::Quaterniond rot;\n\t\t\t\trot = Eigen::AngleAxisd(m_model->robotEYaw(), Eigen::Vector3d::UnitZ());\n\n\t\t\t\ttf::Quaternion quat;\n\t\t\t\ttf::quaternionEigenToTF(rot, quat);\n\n\t\t\t\ttrans.setRotation(quat);\n\n\t\t\t\tROS_DEBUG(\"robot pos: Z = %f, yaw: %f, stamp: %f\", translation.z(), m_model->robotEYaw(), trans.stamp_.toSec());\n\t\t\t\tROS_DEBUG(\"robot pos tf: %f %f %f %f %f %f %f\",\n\t\t\t\t\ttrans.getOrigin().x(), trans.getOrigin().y(), trans.getOrigin().z(),\n\t\t\t\t\ttrans.getRotation().w(), trans.getRotation().x(), trans.getRotation().y(), trans.getRotation().z()\n\t\t\t\t);\n\n\t\t\t\tm_pub_tf.sendTransform(trans);\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Angular velocity feedback\n\t\t\t//\n\n\t\t\t// Retrieve the robot twist\n\t\t\tconst geometry_msgs::Twist& twist = m_last_modelStates->twist[idx];\n\n\t\t\t// Retrieve the robot angular velocity in global coordinates\n\t\t\tEigen::Vector3d globalAngularVelocity;\n\t\t\ttf::vectorMsgToEigen(twist.angular, globalAngularVelocity);\n\n\t\t\t// Set the measured angular velocity (local coordinates)\n\t\t\tm_model->setRobotAngularVelocity(quat.conjugate() * globalAngularVelocity);\n\n\t\t\t//\n\t\t\t// Acceleration feedback\n\t\t\t//\n\n\t\t\t// We'd need an extra Gazebo plugin for acceleration sensing.\n\t\t\t// For now we can do without and simply calculate the current\n\t\t\t// acceleration due to gravity (neglect inertial accelerations).\n\t\t\tEigen::Vector3d globalGravityAcceleration(0.0, 0.0, 9.81);\n\n\t\t\t// Set the measured acceleration (local coordinates)\n\t\t\tm_model->setAccelerationVector(quat.conjugate() * globalGravityAcceleration);\n\n\t\t\t//\n\t\t\t// Magnetic field vector feedback\n\t\t\t//\n\n\t\t\t// We assume that north is positive X. The values of 0.20G (horiz)\n\t\t\t// and 0.44G (vert) are approximately valid for central europe.\n\t\t\tEigen::Vector3d globalMagneticVector(0.20, 0.00, -0.44); // In gauss\n\n\t\t\t// Set the measured magnetic field vector (local coordinates)\n\t\t\tm_model->setMagneticFieldVector(quat.conjugate() * globalMagneticVector);\n\t\t}\n\t}\n\n\t// Return success\n\treturn true;\n}\n\n}\n\nPLUGINLIB_EXPORT_CLASS(robotcontrol::GazeboInterface, robotcontrol::HardwareInterface)\n", "meta": {"hexsha": "2fcb1f5384fd9676368979e737173dba52970970", "size": 4631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/hardware/robotcontrol/src/hw/gazebointerface.cpp", "max_stars_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_stars_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T01:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T05:37:42.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/hardware/robotcontrol/src/hw/gazebointerface.cpp", "max_issues_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_issues_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T08:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-22T08:34:34.000Z", "max_forks_repo_path": "src/nimbro_robotcontrol/hardware/robotcontrol/src/hw/gazebointerface.cpp", "max_forks_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_forks_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T14:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:50:47.000Z", "avg_line_length": 26.1638418079, "max_line_length": 116, "alphanum_fraction": 0.7069747355, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18197971168146881}}
{"text": "// Copyright \u00a9 2011, Universit\u00e9 catholique de Louvain\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// *  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\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#ifndef __BOOSTENVBIGINT_DECL_H\n#define __BOOSTENVBIGINT_DECL_H\n\n#include \"boostenv-decl.hh\"\n\n#ifdef USE_GMP\n#include <boost/multiprecision/gmp.hpp>\n#else\n#include <boost/multiprecision/cpp_int.hpp>\n#endif\n\nnamespace mozart { namespace boostenv {\n\n#ifdef USE_GMP\ntypedef boost::multiprecision::mpz_int mp_int;\n#else\ntypedef boost::multiprecision::cpp_int mp_int;\n#endif\n\nclass BoostBigInt : public BigIntImplem {\npublic:\n  BoostBigInt(nativeint value) : _value(value) {};\n  BoostBigInt(double value) : _value(value) {};\n  BoostBigInt(const std::string& value) : _value(value) {};\n  BoostBigInt(const mp_int& value) : _value(value) {};\n\n  BoostBigInt(const BoostBigInt& src) = delete; // prevent copy\n\n  mp_int value() { return _value; }\n\n  inline\n  std::shared_ptr<BigIntImplem> operator-();\n\n  inline\n  std::shared_ptr<BigIntImplem> operator+(std::shared_ptr<BigIntImplem> b);\n\n  inline\n  std::shared_ptr<BigIntImplem> operator+(nativeint b);\n\n  inline\n  std::shared_ptr<BigIntImplem> operator-(std::shared_ptr<BigIntImplem> b);\n\n  inline\n  std::shared_ptr<BigIntImplem> operator*(std::shared_ptr<BigIntImplem> b);\n\n  inline\n  std::shared_ptr<BigIntImplem> operator/(std::shared_ptr<BigIntImplem> b);\n\n  inline\n  std::shared_ptr<BigIntImplem> operator%(std::shared_ptr<BigIntImplem> b);\n\n  inline\n  int compare(nativeint b);\n\n  inline\n  int compare(std::shared_ptr<BigIntImplem> b);\n\n  inline\n  nativeint nativeintValue();\n\n  inline\n  double doubleValue();\n\n  inline\n  std::string str();\n\n  inline\n  void printReprToStream(VM vm, std::ostream& out, int depth, int width);\n\npublic:\n  template <class T>\n  static std::shared_ptr<BigIntImplem> make_shared_ptr(const T& value) {\n    return std::static_pointer_cast<BigIntImplem>(std::make_shared<BoostBigInt>(value));\n  }\n\nprivate:\n  static std::shared_ptr<BoostBigInt> cast(std::shared_ptr<BigIntImplem> b) {\n    return std::static_pointer_cast<BoostBigInt>(b);\n  }\n\nprivate:\n  mp_int _value;\n};\n\n} }\n\n#endif // __BOOSTENVBIGINT_DECL_H\n", "meta": {"hexsha": "0956edb0d270e5257ab43071cffb4c9226e871f1", "size": 3368, "ext": "hh", "lang": "C++", "max_stars_repo_path": "vm/boostenv/main/boostenvbigint-decl.hh", "max_stars_repo_name": "dianacgr/mozart2", "max_stars_repo_head_hexsha": "005f700dced4a739771d1104f2904c89f03ae879", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-10T01:56:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-10T01:56:34.000Z", "max_issues_repo_path": "vm/boostenv/main/boostenvbigint-decl.hh", "max_issues_repo_name": "dianacgr/mozart2", "max_issues_repo_head_hexsha": "005f700dced4a739771d1104f2904c89f03ae879", "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": "vm/boostenv/main/boostenvbigint-decl.hh", "max_forks_repo_name": "dianacgr/mozart2", "max_forks_repo_head_hexsha": "005f700dced4a739771d1104f2904c89f03ae879", "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": 30.0714285714, "max_line_length": 88, "alphanum_fraction": 0.7535629454, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.18197970457793308}}
{"text": "\n//  Copyright 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// This tests two things: that multiprecision::number meets our\n// conceptual requirements, and that we can instantiate\n// all our distributions and special functions on this type.\n//\n#define BOOST_MATH_ASSERT_UNDEFINED_POLICY false\n#define TEST_GROUP_15\n\n#ifdef _MSC_VER\n#  pragma warning(disable:4800)\n#  pragma warning(disable:4512)\n#  pragma warning(disable:4127)\n#  pragma warning(disable:4512)\n#  pragma warning(disable:4503) // decorated name length exceeded, name was truncated\n#endif\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"compile_test/instantiate.hpp\"\n\nusing namespace boost::multiprecision;\n\ntypedef number<cpp_dec_float<50>, et_on> test_type;\n\n// We get sporadic internal compiler errors from gcc-7.x when CI testing\n// that don't appear to be reproducible locally.  gcc-6.x and gcc-8.x are fine\n// so for now it's a <shrug> and move on...\n#if ! (defined(BOOST_GCC) && (__GNUC__ == 7))\n\nvoid foo()\n{\n   instantiate(test_type());\n}\n\n#endif\n\nint main()\n{\n   //BOOST_CONCEPT_ASSERT((boost::math::concepts::RealTypeConcept<test_type>));\n}\n\n\n", "meta": {"hexsha": "6dcfcaaeda7f0011828ce2ce9c56a2c99923bfac", "size": 1300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/multiprc_concept_check_10.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": "test/multiprc_concept_check_10.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": "Libs/boost_1_76_0/libs/math/test/multiprc_concept_check_10.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "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": 27.0833333333, "max_line_length": 85, "alphanum_fraction": 0.7484615385, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.18197970457793308}}
{"text": "#ifndef HOPS_LINEARPROGRAMGUROBIIMPL_HPP\n#define HOPS_LINEARPROGRAMGUROBIIMPL_HPP\n\n#include \"LinearProgram.hpp\"\n#include <Eigen/Core>\n\n#ifdef HOPS_GUROBI_FOUND\n\n#include <gurobi_c++.h>\n#include <memory>\n\nnamespace hops {\n    class LinearProgramGurobiImpl : public LinearProgram {\n    public:\n        LinearProgramGurobiImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b);\n\n        LinearProgramGurobiImpl(const LinearProgramGurobiImpl &other);\n\n        LinearProgramGurobiImpl &operator=(const LinearProgramGurobiImpl &other);\n\n        [[nodiscard]] LinearProgramSolution solve(const Eigen::VectorXd &objective) const override;\n\n        std::tuple<Eigen::MatrixXd, Eigen::VectorXd> removeRedundantConstraints(double tolerance) override;\n\n        [[nodiscard]] LinearProgramSolution computeChebyshevCenter() const override;\n\n        [[nodiscard]] std::vector<long> computeUnconstrainedDimensions() const override;\n\n        std::tuple<Eigen::MatrixXd, Eigen::VectorXd>\n        addBoxConstraintsToUnconstrainedDimensions(double lb, double ub) override;\n\n    private:\n        std::unique_ptr<GRBModel> model;\n        std::vector<GRBVar> variables;\n    };\n}\n\n#else //HOPS_GUROBI_FOUND\n\nnamespace hops {\n    class LinearProgramGurobiImpl : public LinearProgram {\n    public:\n        LinearProgramGurobiImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b) : LinearProgram(A, b) {\n            throw std::runtime_error(\"HOPS did not find gurobi during compilation.\");\n        }\n\n        [[nodiscard]] LinearProgramSolution solve(const Eigen::VectorXd &) const override {\n            throw std::runtime_error(\"HOPS did not find gurobi during compilation.\");\n        }\n\n        std::tuple<Eigen::MatrixXd, Eigen::VectorXd> removeRedundantConstraints(double) override {\n            throw std::runtime_error(\"HOPS did not find gurobi during compilation.\");\n        }\n\n        [[nodiscard]] LinearProgramSolution computeChebyshevCenter() const override {\n            throw std::runtime_error(\"HOPS did not find gurobi during compilation.\");\n        }\n\n        [[nodiscard]] std::vector<long> computeUnconstrainedDimensions() const override {\n            throw std::runtime_error(\"HOPS did not find gurobi during compilation.\");\n        }\n\n        std::tuple<Eigen::MatrixXd, Eigen::VectorXd>\n        addBoxConstraintsToUnconstrainedDimensions(double, double) override {\n            throw std::runtime_error(\"HOPS did not find gurobi during compilation.\");\n        }\n    };\n}\n\n#endif //HOPS_GUROBI_FOUND\n#endif //HOPS_LINEARPROGRAMGUROBIIMPL_HPP\n", "meta": {"hexsha": "9b95633ad46a31ec33375c1587ea71ed01a4d968", "size": 2540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/LinearProgram/LinearProgramGurobiImpl.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/LinearProgram/LinearProgramGurobiImpl.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/LinearProgram/LinearProgramGurobiImpl.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": 35.2777777778, "max_line_length": 107, "alphanum_fraction": 0.7062992126, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101154203231, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18178764595774338}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <list>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n#include <boost/algorithm/clamp.hpp>\n#include <random>\n#include<opencv2/opencv.hpp>\n#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include \"tensorflow/core/util/work_sharder.h\"\n#include <boost/algorithm/clamp.hpp>\n#include <boost/mpl/map.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/at.hpp>\n#include \"bboxes.h\"\n#include <future>\n#include \"wtoolkit.h\"\n\nusing namespace tensorflow;\nusing namespace std;\nnamespace ba=boost::algorithm;\nnamespace bm=boost::mpl;\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n\n/*\n * \n * masks:[batch_size,Nr,h,w]\n * labels: [batch_size,Nr]\n * lens:[batch_size]\n * output_bboxes:[batch_size,nr,4] (ymin,xmin,ymax,xmax)\n * output_labels:[batch_size,nr]\n * output_lens:[batch_size]\n * output_ids:[batch_size,nr] \u7528\u4e8e\u8868\u793a\u5b9e\u4f8b\u7684\u7f16\u53f7\uff0c\u5982\u7b2c\u4e00\u4e2abatch\u4e2d\u7684\u7b2c\u4e8c\u4e2a\u5b9e\u4f8b\u6240\u751f\u6210\u7684\u6240\u6709\u7684box\u7684ids\u4e3a3(id\u7684\u7f16\u53f7\u4ece1\u5f00\u59cb)\n */\nREGISTER_OP(\"MaskLineBboxes\")\n    .Attr(\"T: {int64,int32}\")\n\t.Attr(\"max_output_nr:int\")\n    .Input(\"mask: uint8\")\n    .Input(\"labels: T\")\n    .Input(\"lens: int32\")\n\t.Output(\"output_bboxes:float\")\n\t.Output(\"output_labels:T\")\n\t.Output(\"output_lens:int32\")\n\t.Output(\"output_ids:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n            int        nr = -1;\n\n            c->GetAttr(\"max_output_nr\",&nr);\n\n            const auto batch_size = c->Value(c->Dim(c->input(0),0));\n            const auto shape0     = c->MakeShape({batch_size,nr,4});\n            const auto shape1     = c->Matrix(batch_size,nr);\n            const auto shape2     = c->Vector(batch_size);\n\n\t\t\tc->set_output(0, shape0);\n\t\t\tc->set_output(1, shape1);\n\t\t\tc->set_output(2, shape2);\n\t\t\tc->set_output(3, shape1);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device,typename T>\nclass MaskLineBboxesOp: public OpKernel {\n    private:\n        using bbox_t = tuple<float,float,float,float>;\n\tpublic:\n\t\texplicit MaskLineBboxesOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"max_output_nr\", &max_output_nr_));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"MaskLineBboxes\");\n\t\t\tconst Tensor &_mask= context->input(0);\n\t\t\tconst Tensor &_labels= context->input(1);\n\t\t\tconst Tensor &_lens = context->input(2);\n\t\t\tauto mask= _mask.template tensor<uint8_t,4>();\n            auto labels = _labels.template tensor<T,2>();\n            auto lens = _lens.template tensor<int32_t,1>();\n\n\t\t\tOP_REQUIRES(context, _mask.dims() == 4, errors::InvalidArgument(\"mask data must be 4-dimensional\"));\n\t\t\tOP_REQUIRES(context, _labels.dims() == 2, errors::InvalidArgument(\"labels data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, _lens.dims() == 1, errors::InvalidArgument(\"lens data must be 1-dimensional\"));\n\n\t\t\tconst auto     batch_size = _mask.dim_size(0);\n\t\t\tconst auto     data_nr   = _mask.dim_size(1);\n            list<vector<bbox_t>> out_bboxes;\n            list<vector<int>> out_labels;\n            list<vector<int>> out_ids;\n\n            for(auto i=0; i<batch_size; ++i) {\n                vector<bbox_t> res;\n                vector<int> res_labels;\n                vector<int> res_ids;\n                res.reserve(1024);\n                for(auto j=0; j<lens(i); ++j) {\n                    const auto label = labels(i,j);\n                    auto res0 = get_bboxes(mask.chip(i,0).chip(j,0));\n                    if(!res0.empty()) {\n                        res.insert(res.end(),res0.begin(),res0.end());\n                        res_labels.insert(res_labels.end(),res0.size(),label);\n                        res_ids.insert(res_ids.end(),res0.size(),j+1);\n                    }\n                }\n\t\t\t    OP_REQUIRES(context, res.size() == res_labels.size(), errors::InvalidArgument(\"size of bboxes should equal size of labels.\"));\n                out_bboxes.push_back(std::move(res));\n                out_labels.push_back(std::move(res_labels));\n                out_ids.push_back(std::move(res_ids));\n            }\n\n            auto output_nr = max_output_nr_;\n\n            if(output_nr<=0) {\n                auto it = max_element(out_labels.begin(),out_labels.end(),[](const auto& v0,const auto& v1){ return v0.size()<v1.size();});\n                output_nr = it->size();\n            } \n\n\t\t\tint dims_3d[3] = {batch_size,output_nr,4};\n\t\t\tint dims_2d[2] = {batch_size,output_nr};\n\t\t\tint dims_1d[1] = {batch_size};\n\t\t\tTensorShape  outshape0;\n\t\t\tTensorShape  outshape1;\n\t\t\tTensorShape  outshape2;\n\t\t\tTensor      *output_bbox   = NULL;\n\t\t\tTensor      *output_labels = NULL;\n\t\t\tTensor      *output_lens   = NULL;\n\t\t\tTensor      *output_ids    = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_3d, 3, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape1);\n\t\t\tTensorShapeUtils::MakeShape(dims_1d, 1, &outshape2);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_bbox));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_labels));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape2, &output_lens));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(3, outshape1, &output_ids));\n\n\t\t\tauto obbox   = output_bbox->template tensor<float,3>();\n\t\t\tauto olabels = output_labels->template tensor<T,2>();\n\t\t\tauto olens   = output_lens->template tensor<int32_t,1>();\n\t\t\tauto oids    = output_ids->template tensor<int32_t,2>();\n\n            obbox.setZero();\n            olabels.setZero();\n            auto itb = out_bboxes.begin();\n            auto itl = out_labels.begin();\n            auto iti = out_ids.begin();\n\n\t\t\tfor(int i=0; i<batch_size; ++i,++itb,++itl,++iti) {\n                olens(i) = itl->size();\n                for(auto j=0; j<olens(i); ++j) {\n                    obbox(i,j,0) = std::get<0>((*itb)[j]);\n                    obbox(i,j,1) = std::get<1>((*itb)[j]);\n                    obbox(i,j,2) = std::get<2>((*itb)[j]);\n                    obbox(i,j,3) = std::get<3>((*itb)[j]);\n                    olabels(i,j) = (*itl)[j];\n                    oids(i,j) = (*iti)[j];\n                }\n\t\t\t}\n\t\t}\n        /*\n         * mask: [h,w]\n         */\n        vector<bbox_t> get_bboxes(const Eigen::Tensor<uint8_t,2,Eigen::RowMajor>& mask) {\n            const auto h = mask.dimension(0);\n            const auto w = mask.dimension(1);\n            const auto y_delta = 1.0/h;\n            const auto x_delta = 1.0/w;\n            vector<bbox_t> res;\n            res.reserve(256);\n\n            for(auto i=0; i<h; ++i) {\n                const auto ymin = i*y_delta;\n                const auto ymax = (i+1)*y_delta;\n                for(auto j=0; j<w; ++j) {\n                    if(mask(i,j)<1) continue;\n                    auto begin_j = j;\n                    while((mask(i,j)>0) && (j<w))++j;\n                    const auto xmin = begin_j*x_delta;\n                    const auto xmax = (j==w)?1.0:j*x_delta;\n                    res.emplace_back(ymin,xmin,ymax,xmax);\n                }\n            }\n            return res;\n        }\n\tprivate:\n        int max_output_nr_ = 0;\n};\nREGISTER_KERNEL_BUILDER(Name(\"MaskLineBboxes\").Device(DEVICE_CPU).TypeConstraint<int32_t>(\"T\"), MaskLineBboxesOp<CPUDevice,int32_t>);\nREGISTER_KERNEL_BUILDER(Name(\"MaskLineBboxes\").Device(DEVICE_CPU).TypeConstraint<tensorflow::int64>(\"T\"), MaskLineBboxesOp<CPUDevice,tensorflow::int64>);\n\n/*\n * \n * masks:[Nr,h,w]\n * bboxes:[Nr,4]\n * size:[2]={H,W}\n * output_masks:[Nr,H,W]\n */\nREGISTER_OP(\"FullSizeMask\")\n    .Attr(\"T: {float32,uint8}\")\n    .Input(\"mask: T\")\n    .Input(\"bboxes: float32\")\n    .Input(\"size: int32\")\n\t.Output(\"output_masks:T\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n            const auto nr = c->Value(c->Dim(c->input(0),0));\n            const auto shape0     = c->MakeShape({nr,-1,-1});\n\t\t\tc->set_output(0, shape0);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device,typename T>\nclass FullSizeMaskOp: public OpKernel {\n    private:\n        using bbox_t = tuple<float,float,float,float>;\n        using type_to_int = bm::map<\n              bm::pair<uint8_t,bm::int_<CV_8UC1>>\n                  , bm::pair<float,bm::int_<CV_32FC1>>\n             >;\n        using tensor_t = Eigen::Tensor<T,2,Eigen::RowMajor>;\n        using tensor_map_t = Eigen::TensorMap<tensor_t>;\n\tpublic:\n\t\texplicit FullSizeMaskOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n\t\t\tconst Tensor &_mask= context->input(0);\n\t\t\tconst Tensor &_bboxes = context->input(1);\n\t\t\tconst Tensor &_size= context->input(2);\n\n\t\t\tOP_REQUIRES(context, _mask.dims() == 3, errors::InvalidArgument(\"mask data must be 3-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bboxes.dims() == 2, errors::InvalidArgument(\"bboxes data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, _size.dims() == 1, errors::InvalidArgument(\"size data must be 1-dimensional\"));\n\n\t\t\tauto         mask        = _mask.template flat<T>();\n\t\t\tauto         bboxes      = _bboxes.template tensor<float,2>();\n\t\t\tauto         size        = _size.template tensor<int,1>();\n\t\t\tconst auto   mh          = _mask.dim_size(1);\n\t\t\tconst auto   mw          = _mask.dim_size(2);\n\t\t\tconst auto   H           = size(0);\n\t\t\tconst auto   W           = size(1);\n\t\t\tconst auto   data_nr     = _mask.dim_size(0);\n\t\t\tint          dims_3d[3]  = {data_nr,H,W};\n\t\t\tTensor      *output_mask = NULL;\n\t\t\tTensorShape  outshape0;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_3d, 3, &outshape0);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_mask));\n\n            auto o_tensor = output_mask->template tensor<T,3>();\n            const auto H_max = H-1;\n            const auto W_max = W-1;\n            constexpr auto kMinSize = 1e-3;\n\n            o_tensor.setZero();\n\n            for(auto i=0; i<data_nr; ++i) {\n                if((fabs(bboxes(i,3)-bboxes(i,1))<kMinSize)\n                    || (fabs(bboxes(i,2)-bboxes(i,0))<kMinSize))\n                    continue;\n\n                long xmin = ba::clamp(bboxes(i,1)*W_max,0,W_max);\n                long ymin = ba::clamp(bboxes(i,0)*H_max,0,H_max);\n                long xmax = ba::clamp(bboxes(i,3)*W_max,0,W_max);\n                long ymax = ba::clamp(bboxes(i,2)*H_max,0,H_max);\n                const cv::Mat input_mask(mh,mw,bm::at<type_to_int,T>::type::value,(void*)(mask.data()+i*mh*mw));\n                cv::Mat dst_mask(ymax-ymin+1,xmax-xmin+1,bm::at<type_to_int,T>::type::value);\n\n                cv::resize(input_mask,dst_mask,cv::Size(xmax-xmin+1,ymax-ymin+1),0,0,cv::INTER_LINEAR);\n\n\n                tensor_map_t src_map((T*)dst_mask.data,dst_mask.rows,dst_mask.cols);\n                Eigen::array<long,2> offset = {ymin,xmin};\n                Eigen::array<long,2> extents = {dst_mask.rows,dst_mask.cols};\n\n                o_tensor.chip(i,0).slice(offset,extents) = src_map;\n\n                /*if(((xmax-xmin>mw) || (ymax-ymin>mh)) && (xmax>xmin) && (ymax>ymin)) {\n                    cv::Mat dst_mask(H,W,bm::at<type_to_int,T>::type::value,output_mask->template flat<T>().data()+H*W*i);\n                    cv::Mat src_mask = dst_mask.clone();\n                    const auto k = max<int>(3,sqrt((xmax-xmin)*(ymax-ymin)/(mh*mw))+1);\n                    cv::medianBlur(src_mask,dst_mask,(k/2)*2+1);\n                }*/\n                \n            }\n\t\t}\n};\nREGISTER_KERNEL_BUILDER(Name(\"FullSizeMask\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), FullSizeMaskOp<CPUDevice,float>);\nREGISTER_KERNEL_BUILDER(Name(\"FullSizeMask\").Device(DEVICE_CPU).TypeConstraint<uint8_t>(\"T\"), FullSizeMaskOp<CPUDevice,uint8_t>);\n\n/*\n * \u5bf9mask [Nr,H,W] \u65cb\u8f6c\u6307\u5b9a\u89d2\u5ea6\uff0c\u540c\u65f6\u8fd4\u56de\u76f8\u5e94instance\u7684bbox\n * bbox [N,4],[ymin,xmin,ymax,xmax], \u7edd\u5bf9\u5750\u6807\n */\nREGISTER_OP(\"MaskRotate\")\n    .Attr(\"T: {uint8,float}\")\n    .Input(\"mask: T\")\n    .Input(\"angle: float\")\n\t.Output(\"o_image:T\")\n    .SetShapeFn([](shape_inference::InferenceContext* c){\n            auto input_shape0 = c->input(0);\n            c->set_output(0, input_shape0);\n\t\t\treturn Status::OK();\n            });\n\ntemplate <typename Device, typename T>\nclass MaskRotateOp: public OpKernel {\n    private:\n        using Tensor3D = Eigen::Tensor<T,3,Eigen::RowMajor>;\n        using type_to_int = bm::map<\n              bm::pair<uint8_t,bm::int_<CV_8UC1>>\n                  , bm::pair<float,bm::int_<CV_32FC1>>\n             >;\n\tpublic:\n\t\texplicit MaskRotateOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t}\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"RotateMask\");\n\t\t\tconst Tensor &_input_img = context->input(0);\n\t\t\tconst Tensor &_angle = context->input(1);\n\n\t\t\tOP_REQUIRES(context, _input_img.dims() == 3, errors::InvalidArgument(\"tensor must be a 3-dimensional tensor\"));\n\t\t\tOP_REQUIRES(context, _angle.dims() == 0, errors::InvalidArgument(\"angle be a 0-dimensional tensor\"));\n\n            auto         input_img     = _input_img.template flat<T>().data();\n            auto         angle         = _angle.template flat<float>().data()[0];\n            const auto   img_channel   = _input_img.dim_size(0);\n            const auto   img_height    = _input_img.dim_size(1);\n            const auto   img_width     = _input_img.dim_size(2);\n            Tensor      *output_tensor = nullptr;\n\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, _input_img.shape(), &output_tensor));\n\n            auto          o_tensor     = output_tensor->template flat<T>().data();\n            const cv::Point2f cp(img_width/2,img_height/2);\n            const cv::Mat r            = cv::getRotationMatrix2D(cp,angle,1.0);\n            const auto    cv_type      = bm::at<type_to_int,T>::type::value;\n            auto fn  = [img_height,img_width,cv_type,r](T* i_data,T* o_data) {\n                cv::Mat i_img(img_height,img_width,cv_type,i_data);\n                cv::Mat o_img(img_height,img_width,cv_type,o_data);\n\n                cv::warpAffine(i_img,o_img,r,cv::Size(img_width,img_height));\n            };\n            list<future<void>> futures;\n\n            for(auto i=0; i<img_channel; ++i) {\n                auto i_data = input_img+i *img_width *img_height;\n                auto o_data = o_tensor+i *img_width *img_height;\n                futures.emplace_back(async(launch::async,fn,(T*)i_data,o_data));\n                if(futures.size()>8)\n                    futures.pop_front();\n            }\n            futures.clear();\n        }\n};\nREGISTER_KERNEL_BUILDER(Name(\"MaskRotate\").Device(DEVICE_CPU).TypeConstraint<uint8_t>(\"T\"), MaskRotateOp<CPUDevice, uint8_t>);\nREGISTER_KERNEL_BUILDER(Name(\"MaskRotate\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), MaskRotateOp<CPUDevice, float>);\n\n/*\n * mask [Nr,H,W] \u4e2d\u67e5\u627e\u76ee\u6807instance\u7684bbox\n * bbox [N,4],[ymin,xmin,ymax,xmax], \u7edd\u5bf9\u5750\u6807\n */\nREGISTER_OP(\"GetBboxesFromMask\")\n    .Attr(\"T: {uint8,float}\")\n    .Input(\"mask: T\")\n\t.Output(\"bbox:float\")\n    .SetShapeFn([](shape_inference::InferenceContext* c){\n            auto input_shape0 = c->input(0);\n            auto data_nr = c->Dim(input_shape0,0);\n            auto output_shape = c->MakeShape({data_nr,4});\n            c->set_output(0, output_shape);\n\t\t\treturn Status::OK();\n            });\n\ntemplate <typename Device, typename T>\nclass GetBboxesFromMaskOp: public OpKernel {\n    private:\n        using Tensor3D = Eigen::Tensor<T,3,Eigen::RowMajor>;\n        using type_to_int = bm::map<\n              bm::pair<uint8_t,bm::int_<CV_8UC1>>\n                  , bm::pair<float,bm::int_<CV_32FC1>>\n             >;\n\tpublic:\n\t\texplicit GetBboxesFromMaskOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t}\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"GetBboxesFromMask\");\n\t\t\tconst Tensor &_input_img = context->input(0);\n\n\t\t\tOP_REQUIRES(context, _input_img.dims() == 3, errors::InvalidArgument(\"tensor must be a 3-dimensional tensor\"));\n\n            auto         input_img     = _input_img.template flat<T>().data();\n            const auto   img_channel   = _input_img.dim_size(0);\n            const auto   img_height    = _input_img.dim_size(1);\n            const auto   img_width     = _input_img.dim_size(2);\n            const int    dim2d[]       = {img_channel,4};\n            TensorShape  output_shape;\n            Tensor      *output_bbox   = nullptr;\n\n            TensorShapeUtils::MakeShape(dim2d,2,&output_shape);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_bbox));\n\n            auto          o_bbox       = output_bbox->template flat<float>().data();\n            const auto    cv_type      = bm::at<type_to_int,T>::type::value;\n            auto fn  = [img_height,img_width,cv_type](T* i_data,float* bbox) {\n                cv::Mat i_img(img_height,img_width,cv_type,i_data);\n                getBBox(i_img,bbox);\n            };\n            list<future<void>> futures;\n\n            for(auto i=0; i<img_channel; ++i) {\n                auto i_data = input_img+i *img_width *img_height;\n                auto bbox   = o_bbox+i *4;\n                futures.emplace_back(async(launch::async,fn,(T*)i_data,bbox));\n                if(futures.size()>8)\n                    futures.pop_front();\n            }\n            futures.clear();\n        }\n\n        static void getBBox(const cv::Mat& img,float* bbox)\n        {\n            vector<vector<cv::Point>> contours;\n            vector<cv::Vec4i> hierarchy;\n            vector<cv::Point> points;\n            const auto    cv_type      = bm::at<type_to_int,T>::type::value;\n            cv::Mat dst_img(img.rows,img.cols,cv_type);\n\n\n            if(cv_type == CV_32FC1) {\n                cv::threshold(img,dst_img,0.5,255,cv::THRESH_BINARY);\n                cv::Mat dst_img1;\n                dst_img.convertTo(dst_img1,CV_8UC1);\n                cv::findContours(dst_img1, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE, cv::Point(0,0));\n            } else {\n                cv::threshold(img,dst_img,127,255,cv::THRESH_BINARY);\n                cv::findContours(dst_img, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE, cv::Point(0,0));\n            }\n\n            for (auto &cont:contours) \n                points.insert(points.end(),cont.begin(),cont.end());\n\n            if(points.size()<2) {\n               memset(bbox,0,sizeof(float)*4);\n               return;\n            }\n\n            const auto rect = cv::boundingRect(points);\n\n            bbox[0] = rect.y;\n            bbox[1] = rect.x;\n            bbox[2] = rect.y+rect.height;\n            bbox[3] = rect.x+rect.width;\n        }\n};\nREGISTER_KERNEL_BUILDER(Name(\"GetBboxesFromMask\").Device(DEVICE_CPU).TypeConstraint<uint8_t>(\"T\"), GetBboxesFromMaskOp<CPUDevice, uint8_t>);\nREGISTER_KERNEL_BUILDER(Name(\"GetBboxesFromMask\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), GetBboxesFromMaskOp<CPUDevice, float>);\n/*\n * \u8f93\u5165mask[H,W,N]\n * \u8f93\u5165labels[N]\n * set_background:\u5982\u679c\u4e00\u4e2a\u4f4d\u7f6e\u6ca1\u6709\u6807\u7b7e\uff0c\u5219\u9ed8\u8ba4\u4e3a\u80cc\u666f\n * attr:num_classes\n * \u8f93\u51famask[W,H,num_classes]\n */\nREGISTER_OP(\"SparseMaskToDense\")\n    .Attr(\"T: {int32,bool,int8,uint8}\")\n\t.Attr(\"num_classes:int\")\n\t.Attr(\"set_background:bool\")\n    .Input(\"mask: T\")\n    .Input(\"labels: int32\")\n\t.Output(\"data:T\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tint num_classes = 0;\n\t\t\tc->GetAttr(\"num_classes\",&num_classes);\n\t\t\tauto w = c->Value(c->Dim(c->input(0),0));\n\t\t\tauto h = c->Value(c->Dim(c->input(0),1));\n            auto output_shape = c->MakeShape({h, w, num_classes});\n\t\t\tc->set_output(0,output_shape);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass SparseMaskToDenseOp: public OpKernel {\n\tpublic:\n\t\texplicit SparseMaskToDenseOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context,\n\t\t\t\t\tcontext->GetAttr(\"num_classes\", &num_classes_));\n\t\t\tOP_REQUIRES_OK(context,\n\t\t\t\t\tcontext->GetAttr(\"set_background\", &set_background_));\n\t\t}\n\t\tvoid Compute(OpKernelContext* context) override\n        {\n            const Tensor &_mask   = context->input(0);\n            const Tensor &_labels = context->input(1);\n            auto          mask    = _mask.template tensor<T,3>();\n            auto          labels  = _labels.template flat<int>().data();\n            auto          h       = _mask.dim_size(0);\n            auto          w       = _mask.dim_size(1);\n            auto          nr      = _mask.dim_size(2);\n            auto          nr1     = _labels.dim_size(0);\n\n            OP_REQUIRES(context, _labels.dims()==1, errors::InvalidArgument(\"labels must be 1-dimensional\"));\n            OP_REQUIRES(context, _mask.dims()==3, errors::InvalidArgument(\"mask must be 3-dimensional\"));\n            OP_REQUIRES(context, nr==nr1, errors::InvalidArgument(\"size unmatch.\"));\n\n            int          dims3d[]     = {int(h),int(w),num_classes_};\n            Tensor      *output_data  = NULL;\n            TensorShape  output_shape;\n\n            TensorShapeUtils::MakeShape(dims3d, 3, &output_shape);\n\n            OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_data));\n\n            auto      oq_tensor = output_data->template tensor<T,3>();\n            oq_tensor.setZero();\n\t\t\tusing tensor_t = Eigen::Tensor<T,2,Eigen::RowMajor>;\n\n            for(auto i=0; i<nr; ++i) {\n\t\t\t\tconst auto label = labels[i];\n\t\t\t\tif((label<0) || (label>=num_classes_)) {\n\t\t\t\t\tcout<<\"Error label \"<<label<<\", not in range [0,\"<<num_classes_<<\")\"<<endl;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n                auto t = oq_tensor.chip(label,2);\n                t = (t||mask.chip(i,2)).template cast<T>();\n            }\n\n\t\t\tif(!set_background_) return;\n\n\t\t\tfor(auto i=0; i<h; ++i) {\n\t\t\t\tfor(auto j=0; j<w; ++j) {\n\t\t\t\t\tbool have_label = false;\n\t\t\t\t\tfor(auto k=0; k<nr; ++k) {\n\t\t\t\t\t\tconst auto label = labels[k];\n\n\t\t\t\t\t\tif((label<0) || (label>=num_classes_)) continue;\n\n\t\t\t\t\t\tif(mask(i,j,k) != 0) {\n\t\t\t\t\t\t\thave_label = true;\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(have_label) continue;\n\n\t\t\t\t\toq_tensor(i,j,0) = T(true);\n\t\t\t\t}\n\t\t\t}\n        }\n\tprivate:\n\t\tint num_classes_ = 0;\n\t\tbool set_background_ = false;\n};\nREGISTER_KERNEL_BUILDER(Name(\"SparseMaskToDense\").Device(DEVICE_CPU).TypeConstraint<int32_t>(\"T\"), SparseMaskToDenseOp<CPUDevice, int32_t>);\nREGISTER_KERNEL_BUILDER(Name(\"SparseMaskToDense\").Device(DEVICE_CPU).TypeConstraint<bool>(\"T\"), SparseMaskToDenseOp<CPUDevice, bool>);\nREGISTER_KERNEL_BUILDER(Name(\"SparseMaskToDense\").Device(DEVICE_CPU).TypeConstraint<int8_t>(\"T\"), SparseMaskToDenseOp<CPUDevice, int8_t>);\nREGISTER_KERNEL_BUILDER(Name(\"SparseMaskToDense\").Device(DEVICE_CPU).TypeConstraint<uint8_t>(\"T\"), SparseMaskToDenseOp<CPUDevice, uint8_t>);\n\n/*\n * mask_size: \u8f93\u51fa\u7684mask\u50cf\u7d20\u5927\u5c0f\n * masks:[Nr,h,w]\n * test_threshold: \u8ddd\u79bb\u5c0f\u4e8etest_threshold\u7684bbox\u624d\u8fdb\u884c\u662f\u5426\u53ef\u4ee5\u5408\u5e76\u7684\u68c0\u6d4b\n * kerner_size: \u95ed\u8fd0\u7b97kernel\u5927\u5c0f\n * bboxes:[Nr,4] absolute coordinate\n * labels:[Nr]\n * mask:[Nr,H,W]\n * output:\n * out_bboxes: [out_Nr,4]\n * out_labels: [out_Nr]\n * out_masks: [out_Nr,mask_size,mask_size]\n * out_indices: [Nr] \u76f8\u540c\u7684\u503c\u8868\u793a\u76f8\u5e94\u4f4d\u7f6e\u7684\u8f93\u5165\u5408\u5e76\u5728\u4e86\u4e00\u8d77\n */\nREGISTER_OP(\"MergeInstanceByMask\")\n    .Attr(\"T: {float32,uint8}\")\n    .Attr(\"mask_size:int=63\")\n    .Attr(\"test_threshold:int=8\")\n    .Attr(\"kernel_size:int=3\")\n    .Input(\"bboxes: T\")\n    .Input(\"labels: int32\")\n    .Input(\"probability: T\")\n    .Input(\"mask: uint8\")\n\t.Output(\"out_bboxes:T\")\n\t.Output(\"out_labels:int32\")\n\t.Output(\"out_probability:T\")\n\t.Output(\"out_masks:uint8\")\n\t.Output(\"out_indices:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n            int mask_size = 0;\n            c->GetAttr(\"mask_size\",&mask_size);\n            const auto nr = c->Value(c->Dim(c->input(0),0));\n            const auto shape0     = c->MakeShape({-1,4});\n            const auto shape1     = c->MakeShape({-1});\n            const auto shape2     = c->MakeShape({nr});\n            const auto shape3     = c->MakeShape({-1,mask_size,mask_size});\n\t\t\tc->set_output(0, shape0);\n\t\t\tc->set_output(1, shape1);\n\t\t\tc->set_output(2, shape1);\n\t\t\tc->set_output(3, shape3);\n\t\t\tc->set_output(4, shape2);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device,typename T>\nclass MergeInstanceByMaskOp: public OpKernel {\n    private:\n        using bbox_t = Eigen::Tensor<T,1,Eigen::RowMajor>;\n        using mask_t = Eigen::Tensor<uint8_t,2,Eigen::RowMajor>;\n    public:\n        explicit MergeInstanceByMaskOp(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"mask_size\", &mask_size_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"test_threshold\", &test_threshold_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"kernel_size\", &kerner_size_));\n        }\n\n        void Compute(OpKernelContext* context) override\n        {\n            const Tensor &_bboxes = context->input(0);\n            const Tensor &_labels= context->input(1);\n            const Tensor &_probability = context->input(2);\n            const Tensor &_mask= context->input(3);\n\n            OP_REQUIRES(context, _mask.dims() == 3, errors::InvalidArgument(\"mask data must be 3-dimensional\"));\n            OP_REQUIRES(context, _bboxes.dims() == 2, errors::InvalidArgument(\"bboxes data must be 2-dimensional\"));\n            OP_REQUIRES(context, _labels.dims() == 1, errors::InvalidArgument(\"labels data must be 1-dimensional\"));\n            OP_REQUIRES(context, _probability.dims() == 1, errors::InvalidArgument(\"probability data must be 1-dimensional\"));\n\n            auto       mask        = _mask.template tensor<uint8_t,3>();\n            auto       bboxes      = _bboxes.template tensor<T,2>();\n            auto       labels      = _labels.template tensor<int,1>();\n            auto       probability = _probability.template tensor<T,1>();\n            const auto data_nr     = _mask.dim_size(0);\n\n            bool is_merged = false;\n            vector<bbox_t> in_bboxes_data;\n            vector<int> in_labels_data;\n            vector<mask_t> in_mask_data;\n            vector<int> in_indices_data;\n            vector<T> in_probability;\n            vector<bool> need_remove(data_nr,false);\n\n            for(auto i=0; i<data_nr; ++i) {\n                in_bboxes_data.push_back(bboxes.chip(i,0));\n                in_labels_data.push_back(labels(i));\n                in_mask_data.push_back(mask.chip(i,0));\n                in_indices_data.push_back(i);\n                in_probability.push_back(probability(i));\n            }\n\n            do {\n                is_merged = false;\n                if(in_bboxes_data.size()>1) {\n                    for(auto i=0; i<in_bboxes_data.size()-1; ++i) {\n                        if(need_remove[i])\n                            continue;\n                        auto& bbox0 = in_bboxes_data[i];\n                        for(auto j=i+1; j<in_bboxes_data.size(); ++j) {\n                            if(need_remove[j])\n                                continue;\n                            if(in_labels_data[i] != in_labels_data[j]) \n                                continue;\n\n                            auto &bbox1 = in_bboxes_data[j];\n                            auto  dis   = bboxes_distance(in_bboxes_data[i],in_bboxes_data[j]);\n\n                            if(dis > test_threshold_)\n                                continue;\n\n                            try {\n                                auto res = merge_bboxes({bbox0,bbox1},{in_mask_data[i],in_mask_data[j]});\n\n                                in_mask_data[i] = get<1>(res);\n                                in_bboxes_data[i] = get<0>(res);\n                                in_indices_data[j] = in_indices_data[i];\n                                in_probability[i] = max(in_probability[i],in_probability[j]);\n                                need_remove[j] = true;\n                                is_merged = true;\n                            }catch(...) {\n                            }\n                        }\n                    }\n                }\n            }while(is_merged);\n\n            auto         total_nr           = count(need_remove.begin(),need_remove.end(),false);\n            int          dims_1d[1]         = {total_nr};\n            int          dims_2d[2]         = {total_nr,4};\n            int          dims_1d2[1]        = {data_nr};\n            int          dims_3d[3]         = {total_nr,mask_size_,mask_size_};\n            TensorShape  outshape0;\n            TensorShape  outshape1;\n            TensorShape  outshape2;\n            TensorShape  outshape3;\n            Tensor      *output_bboxes      = NULL;\n            Tensor      *output_labels      = NULL;\n            Tensor      *output_probability = NULL;\n            Tensor      *output_mask        = NULL;\n            Tensor      *output_indices     = NULL;\n\n            TensorShapeUtils::MakeShape(dims_1d, 1, &outshape0);\n            TensorShapeUtils::MakeShape(dims_2d, 2, &outshape1);\n            TensorShapeUtils::MakeShape(dims_1d2, 1, &outshape2);\n            TensorShapeUtils::MakeShape(dims_3d, 3, &outshape3);\n\n            OP_REQUIRES_OK(context, context->allocate_output(0, outshape1, &output_bboxes));\n            OP_REQUIRES_OK(context, context->allocate_output(1, outshape0, &output_labels));\n            OP_REQUIRES_OK(context, context->allocate_output(2, outshape0, &output_probability));\n            OP_REQUIRES_OK(context, context->allocate_output(3, outshape3, &output_mask));\n            OP_REQUIRES_OK(context, context->allocate_output(4, outshape2, &output_indices));\n\n            auto o_mask        = output_mask->template tensor<uint8_t,3>();\n            auto o_bboxes      = output_bboxes->template tensor<T,2>();\n            auto o_labels      = output_labels->template tensor<int,1>();\n            auto o_probability = output_probability->template tensor<T,1>();\n            auto o_indices     = output_indices->template tensor<int,1>();\n\n            for(auto i=0,j=0; i<data_nr; ++i) {\n                o_indices(i) = in_indices_data[i];\n                if(need_remove[i])\n                    continue;\n                o_bboxes.chip(j,0) = in_bboxes_data[i];\n                o_labels(j) = in_labels_data[i];\n                o_probability(j) = in_probability[i];\n                if(in_mask_data[i].dimension(0) == mask_size_) {\n                    o_mask.chip(j,0) = in_mask_data[i];\n                } else {\n                    o_mask.chip(j,0) = resize_mask(in_mask_data[i],mask_size_);\n                }\n                ++j;\n            }\n        }\n        mask_t resize_mask(const mask_t& msk,size_t size) {\n            const cv::Mat input_mask(msk.dimension(0),msk.dimension(1),CV_8UC1,(void*)(msk.data()));\n            cv::Mat dst_mask(size,size,CV_8UC1);\n            mask_t res_mask(size,size);\n\n            cv::resize(input_mask,dst_mask,cv::Size(size,size),0,0,cv::INTER_LINEAR);\n            memcpy(res_mask.data(),dst_mask.data,size*size);\n\n            return res_mask;\n        }\n        static vector<bbox_t> make_around_bboxes(const bbox_t& box0,const bbox_t& box1) {\n\n            bbox_t res_box0(4);\n            bbox_t res_box1(4);\n            bbox_t res_box2(4);\n            bbox_t res_box3(4);\n\n            res_box0(0) = box0(0)-(box1(2)-box1(0));\n            res_box0(1) = box0(1);\n            res_box0(2) = box0(0);\n            res_box0(3) = box0(3);\n\n            res_box1(0) = box0(0);\n            res_box1(1) = box0(3);\n            res_box1(2) = box0(2);\n            res_box1(3) = box0(3)+(box1(3)-box1(1));\n\n            res_box2(0) = box0(2);\n            res_box2(1) = box0(1);\n            res_box2(2) = box0(2)+(box1(2)-box1(0));;\n            res_box2(3) = box0(3);\n\n            res_box3(0) = box0(0);\n            res_box3(1) = box0(1)-(box1(3)-box1(1));\n            res_box3(2) = box0(2);\n            res_box3(3) = box0(1);\n            return {box0,res_box0,res_box1,res_box2,res_box3};\n            \n        }\n        float bboxes_distance(const bbox_t& box0,const bbox_t& box1) {\n            auto  bboxes  = make_around_bboxes(box0,box1);\n            int   index   = -1;\n            float max_iou = -1.0;\n\n            for(auto i=0; i<bboxes.size(); ++i) {\n                auto v0 = bboxes_jaccard_of_box0v1(bboxes[i],box1);\n                auto v1 = bboxes_jaccard_of_box0v1(box1,bboxes[i]);\n                auto v = max(v0,v1);\n\n                if(v>max_iou) {\n                    max_iou = v;\n                    index = i;\n                }\n            }\n            if(max_iou<0.4)\n                return 1e8;\n            switch(index) {\n                case 0:\n                    return 0;\n                case 1:\n                    return fabs(box1(2)-box0(0));\n                case 2:\n                    return fabs(box1(1)-box0(3));\n                case 3:\n                    return fabs(box1(0)-box0(2));\n                case 4:\n                    return fabs(box1(3)-box0(1));\n                default:\n                    cout<<\"Error type.\"<<endl;\n                    return 1e8;\n            }\n        }\n        void show_box(const bbox_t& box) {\n            cout<<box(0)<<\",\"<<box(1)<<\",\"<<box(2)<<\",\"<<box(3)<<endl;\n        }\n        static cv::Mat to_mat(const mask_t& msk) \n        {\n            cv::Mat res(msk.dimension(0),msk.dimension(1),CV_8UC1,(void*)msk.data());\n            return res.clone();\n        }\n        tuple<bbox_t,mask_t> merge_bboxes(const vector<bbox_t>& boxes,const vector<mask_t>& masks) noexcept(false)\n        {\n            bbox_t  env_bbox(4);\n            cv::Mat res_mask = cv::Mat::zeros(mask_size_,mask_size_,CV_8UC1);\n            cv::Mat res_mask1 = cv::Mat::zeros(mask_size_,mask_size_,CV_8UC1);\n            int total_nr = 0;\n\n            bboxes_envelope(boxes[0],boxes[1],env_bbox);\n\n            const auto env_bbox_w = env_bbox(3)-env_bbox(1);\n            const auto env_bbox_h = env_bbox(2)-env_bbox(0);\n\n            for(auto i=0; i<boxes.size(); ++i) {\n                vector<vector<cv::Point>> contours;\n                vector<vector<cv::Point>> new_contours;\n                vector<cv::Vec4i> hierarchy;\n                vector<cv::Point> points;\n                cv::Mat dst_img = to_mat(masks[i]);\n                const auto cur_bbox = boxes[i];\n                const auto cur_mask_h = masks[i].dimension(0);\n                const auto cur_mask_w = masks[i].dimension(1);\n                const auto cur_bbox_w = cur_bbox(3)-cur_bbox(1);\n                const auto cur_bbox_h = cur_bbox(2)-cur_bbox(0);\n\n                cv::findContours(dst_img, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE, cv::Point(0,0));\n\n                if(contours.size()==0) {\n                    cout<<\"Error contours size.\"<<endl;\n                    throw std::runtime_error(\"error contours size.\");\n                }\n\n                for(auto& points:contours) {\n                    vector<cv::Point> new_points;\n                    for(auto& p:points) {\n                        auto x = (p.x*cur_bbox_w/cur_mask_w+cur_bbox(1)-env_bbox(1))*mask_size_/env_bbox_w;\n                        auto y = (p.y*cur_bbox_h/cur_mask_h+cur_bbox(0)-env_bbox(0))*mask_size_/env_bbox_h;\n                        new_points.push_back(cv::Point(x,y));\n                    }\n                    new_contours.push_back(new_points);\n                }\n                cv::drawContours(res_mask,new_contours,-1,cv::Scalar(1),cv::FILLED,8,hierarchy);\n\n                total_nr += contours.size();\n            }\n\n            vector<vector<cv::Point>> contours;\n            vector<vector<cv::Point>> new_contours;\n            vector<cv::Vec4i> hierarchy;\n            cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(kerner_size_, kerner_size_), cv::Point(-1, -1));\n\n            cv::morphologyEx(res_mask, res_mask1, cv::MORPH_CLOSE, kernel);\n            cv::findContours(res_mask1.clone(), contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE, cv::Point(0,0));\n\n            if((contours.size()==1)\n                    || (contours.size()<total_nr-2)) {\n                mask_t r_mask(mask_size_,mask_size_);\n                memcpy(r_mask.data(),res_mask1.data,mask_size_*mask_size_);\n                return make_tuple(env_bbox,r_mask);\n            }\n            throw std::runtime_error(\"merge faild.\");\n        }\n    private:\n        int mask_size_      = 63;\n        int test_threshold_ = 8;\n        int kerner_size_    = 3;\n};\nREGISTER_KERNEL_BUILDER(Name(\"MergeInstanceByMask\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), MergeInstanceByMaskOp<CPUDevice,float>);\n", "meta": {"hexsha": "1feccae4865215d2b5edae6852bb1244b668ac82", "size": 36299, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tfop/mask.cc", "max_stars_repo_name": "vghost2008/wml", "max_stars_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-10T17:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T01:00:35.000Z", "max_issues_repo_path": "tfop/mask.cc", "max_issues_repo_name": "vghost2008/wml", "max_issues_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T16:16:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T05:21:19.000Z", "max_forks_repo_path": "tfop/mask.cc", "max_forks_repo_name": "vghost2008/wml", "max_forks_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-07T09:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T04:58:10.000Z", "avg_line_length": 40.7396184063, "max_line_length": 153, "alphanum_fraction": 0.5672332571, "num_tokens": 9498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18178764146215337}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_IMW_P_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IMW_P_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// 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/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#include <boost/geometry/extensions/gis/projections/impl/pj_mlfn.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace imw_p\n    {\n\n            static const double TOL = 1e-10;\n            static const double EPS = 1e-10;\n\n            struct XY { double x, y; }; // specific for IMW_P\n\n            struct par_imw_p\n            {\n                double    P, Pp, Q, Qp, R_1, R_2, sphi_1, sphi_2, C2;\n                double    phi_1, phi_2, lam_1;\n                double    en[EN_SIZE];\n                int    mode; /* = 0, phi_1 and phi_2 != 0, = 1, phi_1 = 0, = -1 phi_2 = 0 */\n            };\n\n            template <typename Parameters>\n                static int\n            phi12(Parameters& par, par_imw_p& proj_parm, double *del, double *sig) {\n                int err = 0;\n\n                if (!pj_param(par.params, \"tlat_1\").i ||\n                    !pj_param(par.params, \"tlat_2\").i) {\n                    err = -41;\n                } else {\n                    proj_parm.phi_1 = pj_param(par.params, \"rlat_1\").f;\n                    proj_parm.phi_2 = pj_param(par.params, \"rlat_2\").f;\n                    *del = 0.5 * (proj_parm.phi_2 - proj_parm.phi_1);\n                    *sig = 0.5 * (proj_parm.phi_2 + proj_parm.phi_1);\n                    err = (fabs(*del) < EPS || fabs(*sig) < EPS) ? -42 : 0;\n                }\n                return err;\n            }\n            template <typename Parameters>\n                static XY\n            loc_for(double const& lp_lam, double const& lp_phi, Parameters const& par, par_imw_p const& proj_parm, double *yc) {\n                XY xy;\n\n                if (! lp_phi) {\n                    xy.x = lp_lam;\n                    xy.y = 0.;\n                } else {\n                    double xa, ya, xb, yb, xc, D, B, m, sp, t, R, C;\n\n                    sp = sin(lp_phi);\n                    m = pj_mlfn(lp_phi, sp, cos(lp_phi), proj_parm.en);\n                    xa = proj_parm.Pp + proj_parm.Qp * m;\n                    ya = proj_parm.P + proj_parm.Q * m;\n                    R = 1. / (tan(lp_phi) * sqrt(1. - par.es * sp * sp));\n                    C = sqrt(R * R - xa * xa);\n                    if (lp_phi < 0.) C = - C;\n                    C += ya - R;\n                    if (proj_parm.mode < 0) {\n                        xb = lp_lam;\n                        yb = proj_parm.C2;\n                    } else {\n                        t = lp_lam * proj_parm.sphi_2;\n                        xb = proj_parm.R_2 * sin(t);\n                        yb = proj_parm.C2 + proj_parm.R_2 * (1. - cos(t));\n                    }\n                    if (proj_parm.mode > 0) {\n                        xc = lp_lam;\n                        *yc = 0.;\n                    } else {\n                        t = lp_lam * proj_parm.sphi_1;\n                        xc = proj_parm.R_1 * sin(t);\n                        *yc = proj_parm.R_1 * (1. - cos(t));\n                    }\n                    D = (xb - xc)/(yb - *yc);\n                    B = xc + D * (C + R - *yc);\n                    xy.x = D * sqrt(R * R * (1 + D * D) - B * B);\n                    if (lp_phi > 0)\n                        xy.x = - xy.x;\n                    xy.x = (B + xy.x) / (1. + D * D);\n                    xy.y = sqrt(R * R - xy.x * xy.x);\n                    if (lp_phi > 0)\n                        xy.y = - xy.y;\n                    xy.y += C + R;\n                }\n                return (xy);\n            }\n            template <typename Parameters>\n                static void\n            xy(Parameters const& par, par_imw_p const& proj_parm, double phi, double *x, double *y, double *sp, double *R) {\n                double F;\n\n                *sp = sin(phi);\n                *R = 1./(tan(phi) * sqrt(1. - par.es * *sp * *sp ));\n                F = proj_parm.lam_1 * *sp;\n                *y = *R * (1 - cos(F));\n                *x = *R * sin(F);\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_imw_p_ellipsoid : public base_t_fi<base_imw_p_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_imw_p m_proj_parm;\n\n                inline base_imw_p_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_imw_p_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(e_forward)  ellipsoid\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 yc = 0;\n                    XY xy = loc_for(lp_lon, lp_lat, this->m_par, m_proj_parm, &yc);\n                    xy_x = xy.x; xy_y = xy.y;\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\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                    XY t;\n                    double yc = 0;\n\n                    lp_lat = this->m_proj_parm.phi_2;\n                    lp_lon = xy_x / cos(lp_lat);\n                    do {\n                        t = loc_for(lp_lon, lp_lat, this->m_par, m_proj_parm, &yc);\n                        lp_lat = ((lp_lat - this->m_proj_parm.phi_1) * (xy_y - yc) / (t.y - yc)) + this->m_proj_parm.phi_1;\n                        lp_lon = lp_lon * xy_x / t.x;\n                    } while (fabs(t.x - xy_x) > TOL || fabs(t.y - xy_y) > TOL);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"imw_p_ellipsoid\";\n                }\n\n            };\n\n            // International Map of the World Polyconic\n            template <typename Parameters>\n            void setup_imw_p(Parameters& par, par_imw_p& proj_parm)\n            {\n                double del, sig, s, t, x1, x2, T2, y1, m1, m2, y2;\n                int i;\n\n                if (!pj_enfn(par.es, proj_parm.en)) throw proj_exception(0);\n                if( (i = phi12(par, proj_parm, &del, &sig)) != 0)\n                    throw proj_exception(i);\n                if (proj_parm.phi_2 < proj_parm.phi_1) { /* make sure proj_parm.phi_1 most southerly */\n                    del = proj_parm.phi_1;\n                    proj_parm.phi_1 = proj_parm.phi_2;\n                    proj_parm.phi_2 = del;\n                }\n                if (pj_param(par.params, \"tlon_1\").i)\n                    proj_parm.lam_1 = pj_param(par.params, \"rlon_1\").f;\n                else { /* use predefined based upon latitude */\n                    sig = fabs(sig * geometry::math::r2d<double>());\n                    if (sig <= 60)        sig = 2.;\n                    else if (sig <= 76) sig = 4.;\n                    else                sig = 8.;\n                    proj_parm.lam_1 = sig * geometry::math::d2r<double>();\n                }\n                proj_parm.mode = 0;\n                if (proj_parm.phi_1) xy(par, proj_parm, proj_parm.phi_1, &x1, &y1, &proj_parm.sphi_1, &proj_parm.R_1);\n                else {\n                    proj_parm.mode = 1;\n                    y1 = 0.;\n                    x1 = proj_parm.lam_1;\n                }\n                if (proj_parm.phi_2) xy(par, proj_parm, proj_parm.phi_2, &x2, &T2, &proj_parm.sphi_2, &proj_parm.R_2);\n                else {\n                    proj_parm.mode = -1;\n                    T2 = 0.;\n                    x2 = proj_parm.lam_1;\n                }\n                m1 = pj_mlfn(proj_parm.phi_1, proj_parm.sphi_1, cos(proj_parm.phi_1), proj_parm.en);\n                m2 = pj_mlfn(proj_parm.phi_2, proj_parm.sphi_2, cos(proj_parm.phi_2), proj_parm.en);\n                t = m2 - m1;\n                s = x2 - x1;\n                y2 = sqrt(t * t - s * s) + y1;\n                proj_parm.C2 = y2 - T2;\n                t = 1. / t;\n                proj_parm.P = (m2 * y1 - m1 * y2) * t;\n                proj_parm.Q = (y2 - y1) * t;\n                proj_parm.Pp = (m2 * x1 - m1 * x2) * t;\n                proj_parm.Qp = (x2 - x1) * t;\n            }\n\n        }} // namespace detail::imw_p\n    #endif // doxygen\n\n    /*!\n        \\brief International Map of the World Polyconic 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         - Mod. Polyconic\n         - Ellipsoid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel\n         - lat_2: Latitude of second standard parallel\n         - lon_1 (degrees)\n        \\par Example\n        \\image html ex_imw_p.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct imw_p_ellipsoid : public detail::imw_p::base_imw_p_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline imw_p_ellipsoid(const Parameters& par) : detail::imw_p::base_imw_p_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::imw_p::setup_imw_p(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 imw_p_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<imw_p_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void imw_p_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"imw_p\", new imw_p_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMW_P_HPP\n\n", "meta": {"hexsha": "0f6476303b220dc335ee9db1992f230ef51e99cd", "size": 12752, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/imw_p.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/imw_p.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/imw_p.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": 42.936026936, "max_line_length": 133, "alphanum_fraction": 0.5249372647, "num_tokens": 3102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.18168239874923292}}
{"text": "//---------------------------------------------------------------------------//\n//  MIT License\n//\n//  Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\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 FILECOIN_SEAL_API_POST_HPP\n#define FILECOIN_SEAL_API_POST_HPP\n\n#include <iostream>\n\n#include <boost/filesystem/file_status.hpp>\n\n#include <nil/filecoin/storage/proofs/core/btree/map.hpp>\n#include <nil/filecoin/storage/proofs/core/proof/compound_proof.hpp>\n#include <nil/filecoin/storage/proofs/core/cache_key.hpp>\n#include <nil/filecoin/storage/proofs/core/sector.hpp>\n\n#include <nil/filecoin/proofs/api/utilities.hpp>\n\n#include <nil/filecoin/proofs/types/post_config.hpp>\n\n#include <nil/filecoin/proofs/parameters.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        /// The minimal information required about a replica, in order to be able to generate\n        /// a PoSt over it.\n        template<typename MerkleTreeType>\n        struct PrivateReplicaInfo {\n            PrivateReplicaInfo(const boost::filesystem::path &replica, const commitment_type &comm_r,\n                               const boost::filesystem::path &cache_dir) :\n                cache_dir(cache_dir),\n                replica(replica), comm_r(comm_r) {\n                assert((\"Invalid all zero commitment (comm_r)\",\n                        !std::accumulate(comm_r.begin(), comm_r.end(), false,\n                                         [&](bool state, typename commitment_type::value_type &v) -> bool {\n                                             return state * (v != 0);\n                                         })));\n\n                boost::filesystem::path f_aux_path = cache_dir / std::to_string(cache_key::PAux);\n                std::ifstream file;\n                file.open(f_aux_path.string(), std::ios::binary);\n                std::streamsize size = file.tellg();\n                file.seekg(0, std::ios::beg);\n\n                std::vector<char> aux_bytes(size);\n                if (file.read(aux_bytes.data(), size)) {\n                    aux = deserialize(aux_bytes);\n                }\n\n                assert((\"Sealed replica does not exist\", boost::filesystem::exists(replica.status())));\n            }\n\n            boost::filesystem::path cache_dir_path() const {\n                return cache_dir;\n            }\n\n            boost::filesystem::path replica_path() const {\n                return replica;\n            }\n\n            typename MerkleTreeType::hash_type::digest_type safe_comm_r() const {\n                return as_safe_commitment(comm_r, \"comm_r\");\n            }\n\n            typename MerkleTreeType::hash_type::digest_type safe_comm_c() const {\n                return aux.comm_c;\n            }\n\n            typename MerkleTreeType::hash_type::digest_type safe_comm_r_last() const {\n                return aux.comm_r_last;\n            }\n\n            /// Generate the merkle tree of this particular replica.\n            MerkleTreeWrapper<typename MerkleTreeType::hash_type, MerkleTreeType::Store, MerkleTreeType::base_arity,\n                              MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>\n                merkle_tree(sector_size_type sector_size) {\n                std::size_t base_tree_size = get_base_tree_size<MerkleTreeType>(sector_size);\n                std::size_t base_tree_leafs = get_base_tree_leafs<MerkleTreeType>(base_tree_size);\n\n                StoreConfg config(cache_dir_path(), std::to_string(cache_key::CommRLastTree),\n                                  default_rows_to_discard(base_tree_leafs, MerkleTreeType::base_arity));\n                config.size = base_tree_size;\n\n                std::size_t tree_count = get_base_tree_count<MerkleTreeType>();\n                let(configs, replica_config) =\n                    split_config_and_replica(config, replica_path().to_path_buf(), base_tree_leafs, tree_count);\n\n                return create_tree<MerkleTreeType>(base_tree_size, configs, replica_config);\n            }\n\n            /// Path to the replica.\n            boost::filesystem::path replica;\n            /// The replica commitment.\n            commitment_type comm_r;\n            /// Persistent Aux.\n            PersistentAux<typename MerkleTreeType::hash_type::digest_type> aux;\n            /// Contains sector-specific (e.g. merkle trees) assets\n            boost::filesystem::path cache_dir;\n        };    // namespace filecoin\n    }         // namespace filecoin\n}    // namespace nil\n\nnamespace std {\n    template<typename MerkleTreeType>\n    struct hash<nil::filecoin::PrivateReplicaInfo<MerkleTreeType>> {\n        int operator()(const nil::filecoin::PrivateReplicaInfo<MerkleTreeType> &v) {\n            return hash()(v.replica) ^ hash()(v.comm_r) ^ hash()(v.aux) ^ hash()(v.cache_dir);\n        }\n    };\n}    // namespace std\n\nnamespace nil {\n    namespace filecoin {\n\n        /// The minimal information required about a replica, in order to be able to verify\n        /// a PoSt over it.\n        struct PublicReplicaInfo {\n            PublicReplicaInfo(const commitment_type &comm_r);\n\n            template<typename Domain>\n            Domain safe_comm_r() const {\n                return as_safe_commitment(comm_r, \"comm_r\");\n            }\n\n            /// The replica commitment.\n            commitment_type comm_r;\n        };\n\n        // Ensure that any associated cached data persisted is discarded.\n        template<typename MerkleTreeType>\n        void clear_cache(const boost::filesystem::path &cache_dir) {\n            info !(\"clear_cache:start\");\n\n            TemporaryAux<MerkleTreeType> t_aux;\n            boost::filesystem::path f_aux_path = cache_dir / std::to_string(cache_key::TAux);\n            std::vector<std::uint8_t> aux_bytes =\n                std::fs::read(&f_aux_path).with_context(|| format !(\"could not read from path={:?}\", f_aux_path));\n\n            deserialize(aux_bytes);\n\n            TemporaryAux<MerkleTreeType> result = TemporaryAux<MerkleTreeType, DefaultPieceHasher>::clear_temp(t_aux);\n\n            return result;\n        }    // namespace filecoin\n\n        // Ensure that any associated cached data persisted is discarded.\n        template<typename MerkleTreeType>\n        void clear_caches(const btree::map<sector_id_type, PrivateReplicaInfo<MerkleTreeType>> &replicas) {\n            for (const typename btree::map<sector_id_type, PrivateReplicaInfo<MerkleTreeType>>::value_type &replica :\n                 replicas) {\n                clear_cache<MerkleTreeType>(replica.second().cache_dir.as_path());\n            }\n        }\n\n        typedef std::vector<std::uint8_t> SnarkProof;\n\n        /// Generates a Winning proof-of-spacetime.\n        template<typename MerkleTreeType>\n        SnarkProof generate_winning_post(const post_config &config, const challenge_seed_type &randomness,\n                                         const btree::map<sector_id_type, PrivateReplicaInfo<MerkleTreeType>> &replicas,\n                                         prover_id_type prover_id) {\n            assert((\"invalid post config type\", config.typ == post_type::Winning));\n            assert((\"invalid amount of replicas\", replicas.size() == post_config.sector_count));\n\n            typename MerkleTreeType::hash_type::digest_type randomness_safe =\n                as_safe_commitment(randomness, \"randomness\");\n            typename MerkleTreeType::hash_type::digest_type prover_id_safe =\n                as_safe_commitment(&prover_id, \"prover_id\");\n\n            WinningPostSetupParams vanilla_params = winning_post_setup_params(config);\n            std::size_t param_sector_count = vanilla_params.sector_count;\n\n            compound_proof::SetupParams setup_params {vanilla_params, partitions : None, config.priority};\n\n            compound_proof::PublicParams<fallback::FallbackPoSt<MerkleTreeType>> pub_params =\n                fallback::FallbackPoStCompound::setup(setup_params);\n            let groth_params = get_post_params<MerkleTreeType>(config);\n\n            for (typename btree::map<sector_id_type, PrivateReplicaInfo<MerkleTreeType>>)\n\n                let trees = replicas.iter()\n                                .map(| (_, replica) | replica.merkle_tree(config.sector_size))\n                                .collect::<Result<Vec<_>>>();\n\n            std::vector<fallback::PublicSector> pub_sectors(param_sector_count);\n            std::vector<fallback::PrivateSector> priv_sectors(param_sector_count);\n\n            for (int i = 0; i < param_sector_count; i++) {\n                for (((id, replica), tree) : replicas.iter().zip(trees.iter())) {\n                    typename MerkleTreeType::hash_type::digest_type comm_r = replica.safe_comm_r();\n                    typename MerkleTreeType::hash_type::digest_type comm_c = replica.safe_comm_c();\n                    typename MerkleTreeType::hash_type::digest_type comm_r_last = replica.safe_comm_r_last();\n\n                    pub_sectors.push_back(\n                        fallback::PublicSector<typename MerkleTreeType::hash_type::digest_type> {id : *id, comm_r});\n                    priv_sectors.push_back(fallback::PrivateSector {tree, comm_c, comm_r_last});\n                }\n            }\n\n            fallback::PublicInputs<typename MerkleTreeType::hash_type::digest_type> pub_inputs =\n                {randomness_safe, prover_id_safe, pub_sectors, k : None};\n\n            fallback::PrivateInputs<MerkleTreeType> priv_inputs = {priv_sectors};\n\n            let proof = fallback::FallbackPoStCompound<MerkleTreeType>::prove(pub_params, pub_inputs, priv_inputs,\n                                                                              groth_params);\n            let proof = proof.to_vec();\n\n            return proof;\n        }\n\n        /// Given some randomness and a the length of available sectors, generates the challenged sector.\n        ///\n        /// The returned values are indicies in the range of `0..sector_set_size`, requiring the caller\n        /// to match the index to the correct sector.\n        template<typename MerkleTreeType>\n        std::vector<std::uint64_t>\n            generate_winning_post_sector_challenge(const post_config &config, const challenge_seed_type &randomness,\n                                                   std::uint64_t sector_set_size, const commitment_type &prover_id) {\n            assert(sector_set_size != 0, \"empty sector set is invalid\");\n            assert(post_config.typ == PoStType::Winning, \"invalid post config type\");\n\n            typename MerkleTreeType::hash_type::digest_type prover_id_safe = as_safe_commitment(prover_id, \"prover_id\");\n\n            typename MerkleTreeType::hash_type::digest_type randomness_safe =\n                as_safe_commitment(randomness, \"randomness\");\n            std::vector<std::uint64_t> result = fallback::generate_sector_challenges(\n                randomness_safe, config.sector_count, sector_set_size, prover_id_safe);\n\n            return result;\n        }\n\n        /// Verifies a winning proof-of-spacetime.\n        ///\n        /// The provided `replicas` must be the same ones as passed to `generate_winning_post`, and be based on\n        /// the indices generated by `generate_winning_post_sector_challenge`. It is the responsibility of the\n        /// caller to ensure this.\n        template<typename MerkleTreeType>\n        bool verify_winning_post(const post_config &config, const challenge_seed_type &randomness,\n                                 const btree::map<sector_id_type, PublicReplicaInfo> &replicas,\n                                 prover_id_type prover_id, const std::vector<std::uint8_t> &proof) {\n            assert((\"invalid post config type\", config.typ == PoStType::Winning));\n            assert((\"invalid amount of replicas provided\", config.sector_count == replicas.size()));\n\n            typename MerkleTreeType::hash_type::digest_type randomness_safe =\n                as_safe_commitment(randomness, \"randomness\");\n            typename MerkleTreeType::hash_type::digest_type prover_id_safe = as_safe_commitment(prover_id, \"prover_id\");\n\n            WinningPostSetupParams vanilla_params = winning_post_setup_params(config);\n            std::size_t param_sector_count = vanilla_params.sector_count;\n\n            compound_proof::SetupParams setup_params = {vanilla_params, partitions : None, priority : false};\n            compound_proof::PublicParams<fallback::FallbackPoSt<MerkleTreeType>> pub_params =\n                fallback::FallbackPoStCompound::setup(&setup_params);\n\n            let verifying_key = get_post_verifying_key<MerkleTreeType>(config);\n\n            MultiProof proof = MultiProof::new_from_reader(None, &proof[..], &verifying_key);\n            if (proof.size() != 1) {\n                return false;\n            }\n\n            std::vector<fallback::PublicSector> pub_sectors(param_sector_count);\n            for (int i = 0; i < param_sector_count; i++) {\n                for ((id, replica) : replicas.iter()) {\n                    typename MerkleTreeType::hash_type::digest_type comm_r = replica.safe_comm_r();\n                    pub_sectors.push_back({*id, comm_r});\n                }\n            }\n\n            fallback::PublicInputs pub_inputs =\n                {randomness : randomness_safe, prover_id : prover_id_safe, sectors : pub_sectors, k : None};\n\n            bool is_valid = fallback::FallbackPoStCompound::verify(pub_params, pub_inputs, proof,\n                                                                   {config.challenge_count * config.sector_count});\n\n            if (!is_valid) {\n                return false;\n            }\n\n            return true;\n        }\n\n        /// Generates a Window proof-of-spacetime.\n        template<typename MerkleTreeType>\n        SnarkProof generate_window_post(const post_config &config, const challenge_seed_type &randomness,\n                                        const btree::map<sector_id_type, PrivateReplicaInfo<MerkleTreeType>> &replicas,\n                                        prover_id_type prover_id) {\n            assert((\"invalid post config type\", post_config.typ == PoStType::Window));\n\n            typename MerkleTreeType::hash_type::digest_type randomness_safe =\n                as_safe_commitment(randomness, \"randomness\");\n            typename MerkleTreeType::hash_type::digest_type prover_id_safe = as_safe_commitment(prover_id, \"prover_id\");\n\n            let vanilla_params = window_post_setup_params(config);\n            let partitions = get_partitions_for_window_post(replicas.size(), config);\n\n            std::size_t sector_count = vanilla_params.sector_count;\n            compound_proof::SetupParams setup_params = {vanilla_params, partitions, priority : config.priority};\n\n            compound_proof::PublicParams<fallback::FallbackPoSt<MerkleTreeType>> pub_params =\n                fallback::FallbackPoStCompound::setup(setup_params);\n            let groth_params = get_post_params<MerkleTreeType>(config);\n\n            std::vector<MerkleTreeType> trees =\n                replicas.iter().map(| (_id, replica) | replica.merkle_tree(config.sector_size)).collect::<Result<_>>();\n\n            std::vector<fallback::PublicSector> pub_sectors(sector_count);\n            std::vector<fallback::PrivateSector> priv_sectors(sector_count);\n\n            for (((sector_id, replica), tree) : replicas.iter().zip(trees.iter())) {\n                typename MerkleTreeType::hash_type::digest_type comm_r = replica.safe_comm_r();\n                typename MerkleTreeType::hash_type::digest_type comm_c = replica.safe_comm_c();\n                typename MerkleTreeType::hash_type::digest_type comm_r_last = replica.safe_comm_r_last();\n\n                pub_sectors.push_back(fallback::PublicSector {id : *sector_id, comm_r});\n                priv_sectors.push_back(fallback::PrivateSector {tree, comm_c, comm_r_last});\n            }\n\n            fallback::PublicInputs pub_inputs =\n                {randomness : randomness_safe, prover_id : prover_id_safe, sectors : pub_sectors, k : None};\n\n            fallback::PrivateInputs<MerkleTreeType> priv_inputs = {sectors : priv_sectors};\n\n            let proof = fallback::FallbackPoStCompound::prove(&pub_params, &pub_inputs, &priv_inputs, &groth_params, );\n\n            return proof.to_vec();\n        }\n\n        /// Verifies a window proof-of-spacetime.\n        template<typename MerkleTreeType>\n        bool verify_window_post(const post_config &config,\n                                const challenge_seed_type &randomness,\n                                const btree::map<sector_id_type, PublicReplicaInfo> &replicas,\n                                prover_id_type prover_id,\n                                const std::vector<std::uint8_t> &proof) {\n            assert((\"invalid post config type\", post_config.typ == PoStType::Window));\n\n            typename MerkleTreeType::hash_type::digest_type randomness_safe =\n                as_safe_commitment(randomness, \"randomness\");\n            typename MerkleTreeType::hash_type::digest_type prover_id_safe = as_safe_commitment(prover_id, \"prover_id\");\n\n            WindowPostSetupParams vanilla_params = window_post_setup_params(config);\n            let partitions = get_partitions_for_window_post(replicas.size(), config);\n\n            compound_proof::SetupParams setup_params = {vanilla_params, partitions, priority : false};\n            compound_proof::PublicParams<fallback::FallbackPoSt<Tree>> pub_params =\n                fallback::FallbackPoStCompound::setup(setup_params);\n\n            let verifying_key = get_post_verifying_key<MerkleTreeType>(config);\n\n            MultiProof proof = MultiProof::new_from_reader(partitions, &proof[..], &verifying_key);\n\n            std::vector<PublicSector> pub_sectors = replicas.iter()\n                                                        .map(| (sector_id, replica) |\n                                                             {\n                                                                 let comm_r = replica.safe_comm_r() ? ;\n                                                                 Ok(fallback::PublicSector {\n                                                                     id : *sector_id,\n                                                                     comm_r,\n                                                                 })\n                                                             })\n                                                        .collect::<Result<_>>();\n\n            fallback::PublicInputs pub_inputs = {\n                .randomness = randomness_safe, .prover_id = prover_id_safe, .sectors = pub_sectors, .k = None};\n\n            bool is_valid =\n                fallback::FallbackPoStCompound::verify(pub_params, pub_inputs, proof, fallback::ChallengeRequirements {\n                    minimum_challenge_count : post_config.challenge_count * post_config.sector_count\n                });\n\n            if (!is_valid) {\n                return false;\n            }\n\n            return true;\n        }\n\n        boost::optional<std::size_t> get_partitions_for_window_post(std::size_t total_sector_count,\n                                                                    const post_config &config);\n    }    // namespace filecoin\n}    // namespace nil\n\n#endif    // FILECOIN_SEAL_HPP\n", "meta": {"hexsha": "1481259516dbed16ed32bc5ce6a29ec5a97caba5", "size": 20375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/filecoin/include/nil/filecoin/proofs/api/post.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/filecoin/include/nil/filecoin/proofs/api/post.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/filecoin/include/nil/filecoin/proofs/api/post.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": 50.184729064, "max_line_length": 120, "alphanum_fraction": 0.6062822086, "num_tokens": 4090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.1816363311446792}}
{"text": "#include <Eigen/Dense>\n#include \"space.h\"\n#include \"reactioncoordinate.h\"\n\nnamespace Faunus {\nnamespace ReactionCoordinate {\n\nvoid ReactionCoordinateBase::_to_json(json &) const {}\n\ndouble ReactionCoordinateBase::normalize(double) const { return 1.; }\n\ndouble ReactionCoordinateBase::operator()() {\n    assert(f != nullptr);\n    return f();\n}\n\nbool ReactionCoordinateBase::inRange(double coord) const { return (coord >= min && coord <= max); }\n\nvoid to_json(json &j, const ReactionCoordinateBase &r) {\n    j = {{\"range\", {r.min, r.max}}, {\"resolution\", r.binwidth}};\n    r._to_json(j);\n}\n\nvoid from_json(const json &j, ReactionCoordinateBase &r) {\n    r.binwidth = j.value(\"resolution\", 0.5);\n    auto range = j.value(\"range\", std::vector<double>({0, 0}));\n    if (range.size() == 2)\n        if (range[0] <= range[1]) {\n            r.min = range[0];\n            r.max = range[1];\n            return;\n        }\n    throw std::runtime_error(r.name + \": 'range' require two numbers: [min, max>=min]\");\n}\n\nvoid SystemProperty::_to_json(json &j) const { j[\"property\"] = property; }\nSystemProperty::SystemProperty(const json &j, Space &spc) {\n    name = \"system\";\n    from_json(j, *this);\n    property = j.at(\"property\").get<std::string>();\n    if (property == \"V\")\n        f = [&g = spc.geo]() { return g.getVolume(); };\n    else if (property == \"Lx\")\n        f = [&g = spc.geo]() { return g.getLength().x(); };\n    else if (property == \"Ly\")\n        f = [&g = spc.geo]() { return g.getLength().y(); };\n    else if (property == \"Lz\" or property == \"height\")\n        f = [&g = spc.geo]() { return g.getLength().z(); };\n    else if (property == \"radius\") {\n        if (spc.geo.type == Geometry::CUBOID or spc.geo.type == Geometry::SLIT)\n            std::cerr << \"`radius` coordinate unavailable for geometry\" << endl;\n        else\n            f = [&g = spc.geo]() { return 0.5 * g.getLength().x(); };\n    } else if (property == \"Q\") // system net charge\n        f = [&groups = spc.groups]() {\n            double charge_sum = 0;\n            for (auto &g : groups) // loops over groups\n                for (auto &p : g)  // loop over particles\n                    charge_sum += p.charge;\n            return charge_sum;\n        };\n    else if (property == \"N\") // number of particles\n        f = [&groups = spc.groups]() {\n            int N_sum = 0;\n            for (auto &g : groups) // loops over groups\n                N_sum += g.size();\n            return N_sum;\n        };\n    if (f == nullptr)\n        throw std::runtime_error(name + \": unknown property '\" + property + \"'\" + usageTip[\"coords=[system]\"]);\n}\n\nvoid AtomProperty::_to_json(json &j) const {\n    j[\"property\"] = property;\n    j[\"index\"] = index;\n    if (dir.squaredNorm() > 1e-9)\n        j[\"dir\"] = dir;\n}\nAtomProperty::AtomProperty(const json &j, Space &spc) {\n    name = \"atom\";\n    from_json(j, *this);\n    index = j.at(\"index\");\n    property = j.at(\"property\").get<std::string>();\n    if (property == \"x\")\n        f = [&p = spc.p, i = index]() { return p[i].pos.x(); };\n    else if (property == \"y\")\n        f = [&p = spc.p, i = index]() { return p[i].pos.y(); };\n    else if (property == \"z\")\n        f = [&p = spc.p, i = index]() { return p[i].pos.z(); };\n    else if (property == \"R\")\n        f = [&p = spc.p, i = index]() { return p[i].pos.norm(); };\n    else if (property == \"q\")\n        f = [&p = spc.p, i = index]() { return p[i].charge; };\n    else if (property == \"N\") // number of atom of id=index\n        f = [&groups = spc.groups, i = index]() {\n            int N_sum = 0;\n            for (auto &g : groups) // loops over groups\n                for (auto &p : g)  // loops over particles\n                    if (p.id == i)\n                        N_sum++;\n            return N_sum;\n        };\n    if (f == nullptr)\n        throw std::runtime_error(name + \": unknown property '\" + property + \"'\" + usageTip[\"coords=[atom]\"]);\n}\n\nvoid MoleculeProperty::_to_json(json &j) const {\n    j[\"property\"] = property;\n    j[\"index\"] = index;\n    if (dir.squaredNorm() > 1e-9)\n        j[\"dir\"] = dir;\n    if (indexes.size() >= 2)\n        j[\"indexes\"] = indexes;\n}\nMoleculeProperty::MoleculeProperty(const json &j, Space &spc) {\n    typedef typename Space::Tparticle Tparticle;\n    name = \"molecule\";\n    from_json(j, *this);\n    index = j.value(\"index\", 0);\n    auto b = spc.geo.getBoundaryFunc();\n    property = j.at(\"property\").get<std::string>();\n\n    if (property == \"confid\")\n        f = [&g = spc.groups, i = index]() { return g[i].confid; };\n    else if (property == \"com_x\")\n        f = [&g = spc.groups, i = index]() { return g[i].cm.x(); };\n    else if (property == \"com_y\")\n        f = [&g = spc.groups, i = index]() { return g[i].cm.y(); };\n    else if (property == \"com_z\")\n        f = [&g = spc.groups, i = index]() { return g[i].cm.z(); };\n    else if (property == \"N\")\n        f = [&g = spc.groups, i = index]() { return g[i].size(); };\n    else if (property == \"Q\")\n        f = [&g = spc.groups, i = index]() { return Geometry::monopoleMoment(g[i].begin(), g[i].end()); };\n\n    else if (property == \"mu_x\")\n        f = [&g = spc.groups, i = index, b]() { return Geometry::dipoleMoment(g[i].begin(), g[i].end(), b).x(); };\n\n    else if (property == \"mu_y\")\n        f = [&g = spc.groups, i = index, b]() { return Geometry::dipoleMoment(g[i].begin(), g[i].end(), b).y(); };\n\n    else if (property == \"mu_z\")\n        f = [&g = spc.groups, i = index, b]() { return Geometry::dipoleMoment(g[i].begin(), g[i].end(), b).z(); };\n\n    else if (property == \"mu\")\n        f = [&g = spc.groups, i = index, b]() { return Geometry::dipoleMoment(g[i].begin(), g[i].end(), b).norm(); };\n\n    else if (property == \"end2end\")\n        f = [&spc, i = index]() {\n            assert(spc.groups[i].size() > 1);\n            return std::sqrt(spc.geo.sqdist(spc.groups[i].begin()->pos, (spc.groups[i].end() - 1)->pos));\n        };\n\n    else if (property == \"muangle\") {\n        dir = j.at(\"dir\").get<Point>().normalized();\n        if (not spc.groups.at(index).atomic)\n            f = [&g = spc.groups, i = index, b, &dir = dir]() {\n                Point mu = Geometry::dipoleMoment(g[i].begin(), g[i].end(), b);\n                return std::acos(mu.dot(dir)) * 180 / pc::pi;\n            };\n    }\n\n    else if (property == \"atomatom\") {\n        dir = j.at(\"dir\");\n        indexes = j.at(\"indexes\").get<decltype(indexes)>();\n        if (indexes.size() != 2)\n            throw std::runtime_error(\"exactly two indices expected\");\n        f = [&spc, &dir = dir, i = indexes[0], j = indexes[1]]() {\n            auto &pos1 = spc.p.at(i).pos;\n            auto &pos2 = spc.p.at(j).pos;\n            return spc.geo.vdist(pos1, pos2).cwiseProduct(dir.cast<double>()).norm();\n        };\n    }\n\n    else if (property == \"cmcm_z\") {\n        indexes = j.value(\"indexes\", decltype(indexes)());\n        if (indexes.size() != 4)\n            throw std::runtime_error(\"exactly four indices expected\");\n        f = [&spc, dir = dir, i = indexes[0], j = indexes[1] + 1, k = indexes[2], l = indexes[3] + 1]() {\n            auto cm1 = Geometry::massCenter(spc.p.begin() + i, spc.p.begin() + j, spc.geo.getBoundaryFunc());\n            auto cm2 = Geometry::massCenter(spc.p.begin() + k, spc.p.begin() + l, spc.geo.getBoundaryFunc());\n            return spc.geo.vdist(cm1, cm2).z();\n        };\n    }\n\n    else if (property == \"cmcm\") {\n        dir = j.at(\"dir\");\n        indexes = j.value(\"indexes\", decltype(indexes)());\n        assert(indexes.size() == 4 && \"An array of 4 indexes should be specified.\");\n        f = [&spc, dir = dir, i = indexes[0], j = indexes[1] + 1, k = indexes[2], l = indexes[3] + 1]() {\n            auto cm1 = Geometry::massCenter(spc.p.begin() + i, spc.p.begin() + j, spc.geo.getBoundaryFunc());\n            auto cm2 = Geometry::massCenter(spc.p.begin() + k, spc.p.begin() + l, spc.geo.getBoundaryFunc());\n            return spc.geo.vdist(cm1, cm2).cwiseProduct(dir.cast<double>()).norm();\n        };\n    }\n\n    else if (property == \"L/R\") {\n        dir = j.at(\"dir\");\n        indexes = j.value(\"indexes\", decltype(indexes)());\n        assert(indexes.size() == 2 && \"An array of 2 indexes should be specified.\");\n        f = [&spc, &dir = dir, i = indexes[0], j = indexes[1]]() {\n            Average<double> Rj, Rin, Rout;\n            Group<Tparticle> g(spc.p.begin(), spc.p.end());\n            auto slicei = g.find_id(i);\n            auto cm = Geometry::massCenter(slicei.begin(), slicei.end(), spc.geo.getBoundaryFunc());\n            auto slicej = g.find_id(j);\n            for (auto p : slicej)\n                Rj += spc.geo.vdist(p.pos, cm).cwiseProduct(dir.cast<double>()).norm();\n            double Rjavg = Rj.avg();\n            for (auto p : slicei) {\n                double d = spc.geo.vdist(p.pos, cm).cwiseProduct(dir.cast<double>()).norm();\n                if (d < Rjavg)\n                    Rin += d;\n                else if (d > Rjavg)\n                    Rout += d;\n            }\n            return 2 * spc.geo.getLength().z() / (Rin.avg() + Rout.avg());\n        };\n    }\n\n    else if (property == \"angle\") {\n        dir = j.at(\"dir\").get<Point>().normalized();\n        if (not spc.groups.at(index).atomic) {\n            f = [&spc, &dir = dir, i = index]() {\n                auto &cm = spc.groups[i].cm;\n                auto S = Geometry::gyration(spc.groups[i].begin(), spc.groups[i].end(), spc.geo.getBoundaryFunc(), cm);\n                Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> esf(S);\n                Point eivals = esf.eigenvalues();\n                std::ptrdiff_t i_eival;\n                eivals.minCoeff(&i_eival);\n                Point vec = esf.eigenvectors().col(i_eival).real();\n                double cosine = vec.dot(dir);\n                double angle = std::acos(std::fabs(cosine)) * 180. / pc::pi;\n                return angle;\n            };\n        }\n    }\n\n    if (f == nullptr)\n        throw std::runtime_error(name + \": unknown or impossible property '\" + property + \"'\" +\n                                 usageTip[\"coords=[molecule]\"]);\n}\n\ndouble MassCenterSeparation::normalize(double coord) const {\n    int dim = dir.sum();\n    if (dim == 2)\n        return 1 / (2 * pc::pi * coord);\n    if (dim == 3)\n        return 1 / (4 * pc::pi * coord * coord);\n    return 1.0;\n}\n\nvoid MassCenterSeparation::_to_json(json &j) const {\n    j[\"dir\"] = dir;\n    j[\"indexes\"] = indexes;\n    j[\"type\"] = type;\n}\nMassCenterSeparation::MassCenterSeparation(const json &j, Space &spc) {\n    typedef typename Space::Tparticle Tparticle;\n    name = \"cmcm\";\n    from_json(j, *this);\n    dir = j.value(\"dir\", dir);\n    indexes = j.value(\"indexes\", decltype(indexes)());\n    type = j.value(\"type\", decltype(type)());\n    if (indexes.size() == 4) {\n        f = [&spc, dir = dir, i = indexes[0], j = indexes[1] + 1, k = indexes[2], l = indexes[3] + 1]() {\n            auto cm1 = Geometry::massCenter(spc.p.begin() + i, spc.p.begin() + j, spc.geo.getBoundaryFunc());\n            auto cm2 = Geometry::massCenter(spc.p.begin() + k, spc.p.begin() + l, spc.geo.getBoundaryFunc());\n            return spc.geo.vdist(cm1, cm2).cwiseProduct(dir.cast<double>()).norm();\n        };\n    } else if (type.size() == 2) {\n        f = [&spc, dir = dir, type1 = type[0], type2 = type[1]]() {\n            Group<Tparticle> g(spc.p.begin(), spc.p.end());\n            auto slice1 = g.find_id(findName(atoms, type1)->id());\n            auto slice2 = g.find_id(findName(atoms, type2)->id());\n            auto cm1 = Geometry::massCenter(slice1.begin(), slice1.end(), spc.geo.getBoundaryFunc());\n            auto cm2 = Geometry::massCenter(slice2.begin(), slice2.end(), spc.geo.getBoundaryFunc());\n            return spc.geo.vdist(cm1, cm2).cwiseProduct(dir.cast<double>()).norm();\n        };\n    } else\n        throw std::runtime_error(name + \": specify 4 indexes or two atom types\");\n}\n\n} // namespace ReactionCoordinate\n} // namespace Faunus\n", "meta": {"hexsha": "cf4790fded7e0e9dae48d4b5824a38ba5b1643de", "size": 11884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reactioncoordinate.cpp", "max_stars_repo_name": "vaspelin/faunus_new", "max_stars_repo_head_hexsha": "f0650a7f1c0d4e1e4c1c15f0d024ba5250347923", "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/reactioncoordinate.cpp", "max_issues_repo_name": "vaspelin/faunus_new", "max_issues_repo_head_hexsha": "f0650a7f1c0d4e1e4c1c15f0d024ba5250347923", "max_issues_repo_licenses": ["MIT"], "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/reactioncoordinate.cpp", "max_forks_repo_name": "vaspelin/faunus_new", "max_forks_repo_head_hexsha": "f0650a7f1c0d4e1e4c1c15f0d024ba5250347923", "max_forks_repo_licenses": ["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.5524475524, "max_line_length": 119, "alphanum_fraction": 0.5240659711, "num_tokens": 3345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.1816363261955486}}
{"text": "/**\n * Copyright (c) 2019, Arjan van der Velde, Weng Lab\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#pragma once\n\n#include \"Exception.hpp\"\n#include \"TransformLigand.hpp\"\n#include \"TransformMultimer.hpp\"\n#include \"ZDOCK.hpp\"\n#include <Eigen/Dense>\n#include <string>\n\nnamespace zdock {\n\n/**\n * @brief Perform RMSD based pruning on (M-)ZDOCK output\n */\nclass Pruning {\nprivate:\n  typedef Eigen::Transform<double, 3, Eigen::Affine> Transform;\n  typedef Eigen::Matrix<double, 3, Eigen::Dynamic> Matrix;\n\n  ZDOCK zdock_;                 // zdock output\n  const double cutoff_;         // cutoff\n  const TransformLigand txl_;   // ligand tranfomation class\n  const TransformMultimer txm_; // multimertranfomation class\n  std::string strucfn_;         // receptor and ligand filenames\n  const bool getclusters_;      // return all w/ cluster number in score\n\n  // results\n  std::vector<int> clusters_; // cluster assignments\n  size_t strucsize_;          // structure size\n  int nclusters_;             // number of clusters\n\npublic:\n  /**\n   * @brief Constructor\n   *\n   * @param zdockoutput ZDOCK or M-ZDOCK output file name\n   * @param cutoff RMSD cutoff\n   * @param structurefn Structure PDB file name\n   * @param getclusters Toggle return for full (M-)ZDOCK output with cluster numbers for scores\n   */\n  Pruning(\n      const std::string &zdockoutput, const double cutoff,\n      const std::string &structurefn = \"\", // or grab from zdock.out\n      const bool getclusters = false // return all w/ cluster number in score\n  );\n\n  /**\n   * @brief Actually perform pruning\n   */\n  void prune();\n  /**\n   * @brief Get cluster assignments\n   *\n   * @return vector of cluster numbers, one for each prediction\n   */\n  const std::vector<int> &clusters() const { return clusters_; }\n  /**\n   * @brief Get number of clusters\n   *\n   * @return number of clusters found\n   */\n  int nclusters() const { return nclusters_; }\n  /**\n   * @brief Get ZDOCK output with cluster numbers for scores\n   *\n   * @return ZDOCK output with cluster numbers for scores\n   */\n  const ZDOCK &zdock() const { return zdock_; }\n};\n\n/**\n * @brief General exception during pruning\n */\nclass PruningException : public Exception {\npublic:\n  PruningException(const std::string &msg) : Exception(msg) {}\n};\n\n} // namespace zdock\n", "meta": {"hexsha": "e1465d90997919f3120a87f962764123384cae17", "size": 3572, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Pruning.hpp", "max_stars_repo_name": "weng-lab/libzdock", "max_stars_repo_head_hexsha": "a634d5b179e7064ac26f6a8a2550e14901732ebe", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-27T18:12:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T11:36:24.000Z", "max_issues_repo_path": "src/Pruning.hpp", "max_issues_repo_name": "hardhary/libzdock", "max_issues_repo_head_hexsha": "a634d5b179e7064ac26f6a8a2550e14901732ebe", "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/Pruning.hpp", "max_forks_repo_name": "hardhary/libzdock", "max_forks_repo_head_hexsha": "a634d5b179e7064ac26f6a8a2550e14901732ebe", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T00:21:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T00:21:34.000Z", "avg_line_length": 33.6981132075, "max_line_length": 95, "alphanum_fraction": 0.7102463606, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.18163632484840786}}
{"text": "#pragma once\n\n#include <Epetra_CrsMatrix.h>\n#include <Epetra_MultiVector.h>\n#include <Epetra_Operator.h>\n#include <deal.II/base/conditional_ostream.h>\n#include \"aux/message.hpp\"\n#include \"aux/timer.hpp\"\n#include \"boundary_conditions.hpp\"\n\nnamespace boltzmann {\nnamespace otf_bc {\n\ntemplate <typename METHOD, typename APP>\nclass SystemMatrix : public ::Epetra_Operator\n{\n private:\n  typedef ::boltzmann::BoundaryConditions<METHOD, APP, impl::BdFacesManager> B_t;\n\n public:\n  SystemMatrix(const ::Epetra_CrsMatrix& A, const B_t& B)\n      : A_(A)\n      , B_(B)\n      , pcout(std::cout, ::dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)\n  {\n    /* empty */\n  }\n\n  int Apply(const ::Epetra_MultiVector& X, ::Epetra_MultiVector& Y) const;\n  int ApplyInverse(const ::Epetra_MultiVector& X, ::Epetra_MultiVector& Y) const;\n  double NormInf() const;\n  const char* Label() const;\n  int SetUseTranspose(bool f);\n  bool UseTranspose() const;\n  bool HasNormInf() const;\n  const ::Epetra_Comm& Comm() const;\n  const ::Epetra_Map& OperatorDomainMap() const;\n  const ::Epetra_Map& OperatorRangeMap() const;\n\n private:\n  const ::Epetra_CrsMatrix& A_;\n  const B_t& B_;\n\n  mutable Timer<> timer;\n  mutable ::dealii::ConditionalOStream pcout;\n};\n\ntemplate <typename METHOD, typename APP>\nint\nSystemMatrix<METHOD, APP>::Apply(const ::Epetra_MultiVector& X, ::Epetra_MultiVector& Y) const\n{\n  //  timer.start();\n  int retA = A_.Apply(X, Y);\n  //  print_timer(timer.stop(), \"A*x\", pcout);\n\n  // timer.start();\n  B_.apply(Y, X);\n  // print_timer(timer.stop(), \"B*x\", pcout);\n\n  return retA;\n}\n\ntemplate <typename METHOD, typename APP>\nint\nSystemMatrix<METHOD, APP>::ApplyInverse(const ::Epetra_MultiVector& X,\n                                        ::Epetra_MultiVector& Y) const\n{\n  throw std::runtime_error(\"not implemented\");\n}\n\ntemplate <typename METHOD, typename APP>\ndouble\nSystemMatrix<METHOD, APP>::NormInf() const\n{\n  throw std::runtime_error(\"not implemented\");\n}\n\ntemplate <typename METHOD, typename APP>\nbool\nSystemMatrix<METHOD, APP>::HasNormInf() const\n{\n  return false;\n}\n\ntemplate <typename METHOD, typename APP>\nconst char*\nSystemMatrix<METHOD, APP>::Label() const\n{\n  return A_.Label();\n}\n\ntemplate <typename METHOD, typename APP>\nint\nSystemMatrix<METHOD, APP>::SetUseTranspose(bool f)\n{\n  std::runtime_error(\"not implemented\");\n  return -1;\n}\n\ntemplate <typename METHOD, typename APP>\nbool\nSystemMatrix<METHOD, APP>::UseTranspose() const\n{\n  return false;\n}\n\ntemplate <typename METHOD, typename APP>\nconst ::Epetra_Comm&\nSystemMatrix<METHOD, APP>::Comm() const\n{\n  return A_.Comm();\n}\n\ntemplate <typename METHOD, typename APP>\nconst ::Epetra_Map&\nSystemMatrix<METHOD, APP>::OperatorDomainMap() const\n{\n  return A_.OperatorDomainMap();\n}\n\ntemplate <typename METHOD, typename APP>\nconst ::Epetra_Map&\nSystemMatrix<METHOD, APP>::OperatorRangeMap() const\n{\n  return A_.OperatorRangeMap();\n}\n\n}  // end namespace otf_bc\n}  // end namespace boltzmann\n", "meta": {"hexsha": "81c000efdf7d139f4fc48b97eb2dcdf1f7adae9f", "size": 2956, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/bc/matrix_wrapper.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/matrix/bc/matrix_wrapper.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/matrix/bc/matrix_wrapper.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": 22.7384615385, "max_line_length": 94, "alphanum_fraction": 0.7107577808, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1816363225935586}}
{"text": "#include <Eigen/Core>\n#include <memory>\n#include <unordered_map>\n#include <vector>\n\n#include \"MarchingCubesConst.h\"\n#include \"VDBVolume.h\"\n\nnamespace openvdb {\nstatic const openvdb::Coord shift[8] = {\n    openvdb::Coord(0, 0, 0), openvdb::Coord(1, 0, 0), openvdb::Coord(1, 1, 0),\n    openvdb::Coord(0, 1, 0), openvdb::Coord(0, 0, 1), openvdb::Coord(1, 0, 1),\n    openvdb::Coord(1, 1, 1), openvdb::Coord(0, 1, 1),\n};\n}\n\n// Taken from <open3d/utility/Eigen.h>\nnamespace {\ntemplate <typename T>\nstruct hash_eigen {\n    std::size_t operator()(T const& matrix) const {\n        size_t seed = 0;\n        for (int i = 0; i < (int)matrix.size(); i++) {\n            auto elem = *(matrix.data() + i);\n            seed ^= std::hash<typename T::Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n        }\n        return seed;\n    }\n};\n}  // namespace\n\nnamespace vdbfusion {\nstd::tuple<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3i>>\nVDBVolume::ExtractTriangleMesh(bool fill_holes, float min_weight) const {\n    // implementation of marching cubes, based on Open3D\n    std::vector<Eigen::Vector3d> vertices;\n    std::vector<Eigen::Vector3i> triangles;\n\n    double half_voxel_length = voxel_size_ * 0.5;\n    // Map of \"edge_index = (x, y, z, 0) + edge_shift\" to \"global vertex index\"\n    std::unordered_map<Eigen::Vector4i, int, hash_eigen<Eigen::Vector4i>, std::equal_to<>,\n                       Eigen::aligned_allocator<std::pair<const Eigen::Vector4i, int>>>\n        edgeindex_to_vertexindex;\n    int edge_to_index[12];\n\n    auto tsdf_acc = tsdf_->getAccessor();\n    auto weights_acc = weights_->getAccessor();\n    for (auto iter = tsdf_->beginValueOn(); iter; ++iter) {\n        int cube_index = 0;\n        float f[8];\n        const openvdb::Coord& voxel = iter.getCoord();\n        const int32_t x = voxel.x();\n        const int32_t y = voxel.y();\n        const int32_t z = voxel.z();\n        for (int i = 0; i < 8; i++) {\n            openvdb::Coord idx = voxel + openvdb::shift[i];\n            if (!fill_holes) {\n                if (weights_acc.getValue(idx) == 0.0f) {\n                    cube_index = 0;\n                    break;\n                }\n            }\n            if (weights_acc.getValue(idx) < min_weight) {\n                cube_index = 0;\n                break;\n            }\n            f[i] = tsdf_acc.getValue(idx);\n            if (f[i] < 0.0f) {\n                cube_index |= (1 << i);\n            }\n        }\n        if (cube_index == 0 || cube_index == 255) {\n            continue;\n        }\n        for (int i = 0; i < 12; i++) {\n            if ((edge_table[cube_index] & (1 << i)) != 0) {\n                Eigen::Vector4i edge_index = Eigen::Vector4i(x, y, z, 0) + edge_shift[i];\n                if (edgeindex_to_vertexindex.find(edge_index) == edgeindex_to_vertexindex.end()) {\n                    edge_to_index[i] = (int)vertices.size();\n                    edgeindex_to_vertexindex[edge_index] = (int)vertices.size();\n                    Eigen::Vector3d pt(half_voxel_length + voxel_size_ * edge_index(0),\n                                       half_voxel_length + voxel_size_ * edge_index(1),\n                                       half_voxel_length + voxel_size_ * edge_index(2));\n                    double f0 = std::abs((double)f[edge_to_vert[i][0]]);\n                    double f1 = std::abs((double)f[edge_to_vert[i][1]]);\n                    pt(edge_index(3)) += f0 * voxel_size_ / (f0 + f1);\n                    vertices.push_back(pt /* + origin_*/);\n                } else {\n                    edge_to_index[i] = edgeindex_to_vertexindex.find(edge_index)->second;\n                }\n            }\n        }\n        for (int i = 0; tri_table[cube_index][i] != -1; i += 3) {\n            triangles.emplace_back(edge_to_index[tri_table[cube_index][i]],\n                                   edge_to_index[tri_table[cube_index][i + 2]],\n                                   edge_to_index[tri_table[cube_index][i + 1]]);\n        }\n    }\n    return std::make_tuple(vertices, triangles);\n}\n\n}  // namespace vdbfusion\n", "meta": {"hexsha": "af84acf5fd34480b1d2e65a652cbb8c855dfb308", "size": 4049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vdbfusion/vdbfusion/MarchingCubes.cpp", "max_stars_repo_name": "Willyzw/vdbfusion", "max_stars_repo_head_hexsha": "ca9107a3f44e43629b149ea80c9cd21d9f274baa", "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/MarchingCubes.cpp", "max_issues_repo_name": "arenas7307979/vdbfusion", "max_issues_repo_head_hexsha": "7ed8d3142b4b6e164633516f0ed435e1065e5212", "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/MarchingCubes.cpp", "max_forks_repo_name": "arenas7307979/vdbfusion", "max_forks_repo_head_hexsha": "7ed8d3142b4b6e164633516f0ed435e1065e5212", "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": 39.3106796117, "max_line_length": 99, "alphanum_fraction": 0.5349469005, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.18163632259355858}}
{"text": "/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy ( DOE ). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n/*! \n* \\file logbroyden.cpp\n* \\ingroup objects\n* \\brief LogBroyden class (Broyden's method solver) source file\n* \\author Robert Link\n*/\n\n\n#include \"util/base/include/definitions.h\"\n#include <string>\n#include <algorithm>\n#include <iomanip>\n#include <math.h>\n#include <xercesc/dom/DOMNode.hpp>\n#include <xercesc/dom/DOMNodeList.hpp>\n\n#include \"solution/solvers/include/solver_component.h\"\n#include \"solution/solvers/include/logbroyden.hpp\"\n#include \"solution/util/include/calc_counter.h\"\n#include \"marketplace/include/marketplace.h\"\n#include \"containers/include/world.h\"\n#include \"solution/util/include/solution_info_set.h\"\n#include \"solution/util/include/solution_info.h\"\n#include \"solution/util/include/solver_library.h\"\n#include \"util/base/include/util.h\"\n#include \"util/base/include/configuration.h\"\n#include \"util/logger/include/ilogger.h\"\n#include \"util/base/include/xml_helper.h\"\n#include \"solution/util/include/solution_info_filter_factory.h\"\n#include \"solution/util/include/solvable_nr_solution_info_filter.h\"\n\n#include \"solution/util/include/functor-subs.hpp\"\n#include \"solution/util/include/linesearch.hpp\"\n#include \"solution/util/include/fdjac.hpp\" \n#include \"solution/util/include/edfun.hpp\"\n#include \"solution/util/include/ublas-helpers.hpp\"\n#include \"util/base/include/fltcmp.hpp\"\n#include \"solution/util/include/jacobian-precondition.hpp\"\n\n#if USE_LAPACK\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/bindings/lapack/gesvd.hpp>\n#include \"solution/util/include/svd_invert_solve.hpp\"\n#else\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#endif \n\n#include \"util/base/include/timer.h\"\n\nusing namespace xercesc;\n\nstd::string LogBroyden::SOLVER_NAME = \"broyden-solver-component\";\n\n#if USE_LAPACK\n#define UBMATRIX boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major>\n#else\n#define UBMATRIX boost::numeric::ublas::matrix<double>\n#endif\n#define UBVECTOR boost::numeric::ublas::vector<double>\n\n\nnamespace {\n  // helper functions for the std::transform algorithm\n  inline double SI2lgprice (const SolutionInfo &si) {\n    double p = std::max(si.getPrice(), util::getTinyNumber());\n    return log( p );\n  }\n  inline double SI2price (const SolutionInfo &si) {return si.getPrice();}\n\n  // read-only accessor for solutionInfoSet (used to prepare log outputs)\n  const SolutionInfoSet *cSolInfo=0;\n\n  // utility function for finding the minimimum and maximum absolute\n  // value entries in a vector.\n  void locate_vector_minmax(const UBVECTOR &v, double &vmax, double &vmin, int &imax, int &imin)\n  {\n    vmax = vmin = fabs(v[0]);\n    imax = imin = 0;\n    for(int i=1; i<v.size(); ++i) {\n      double vabs = fabs(v[i]);\n      if(vabs < vmin) {\n        vmin = vabs;\n        imin = i;\n      }\n      if(vabs > vmax) {\n        vmax = vabs;\n        imax = i;\n      }\n    }\n  } \n}\n\nint LogBroyden::mLastPer = 0;\nint LogBroyden::mPerIter = 0;\n\nbool LogBroyden::XMLParse( const DOMNode* aNode ) {\n    // assume we were passed a valid node.\n    assert( aNode );\n    \n    // get the children of the node.\n    DOMNodeList* nodeList = aNode->getChildNodes();\n    \n    // loop through the children\n    for ( unsigned int i = 0; i < nodeList->getLength(); ++i ){\n        DOMNode* curr = nodeList->item( i );\n        std::string nodeName = XMLHelper<std::string>::safeTranscode( curr->getNodeName() );\n        \n        if( nodeName == \"#text\" ) {\n            continue;\n        }\n        else if( nodeName == \"max-iterations\" ) {\n            mMaxIter = XMLHelper<unsigned int>::getValue( curr );\n        }\n        else if( nodeName == \"ftol\" ) {\n            mFTOL = XMLHelper<double>::getValue( curr );\n        }\n        else if( nodeName == \"solution-info-filter\" ) {\n            mSolutionInfoFilter.reset(\n                                      SolutionInfoFilterFactory::createSolutionInfoFilterFromString( XMLHelper<std::string>::getValue( curr ) ) );\n        }\n        else if(nodeName == \"linear-price\") {\n          mLogPricep = false;\n        }\n        else if(nodeName == \"log-price\") {\n          mLogPricep = true;    // not strictly necessary, as this is the default.\n        }\n        else if( SolutionInfoFilterFactory::hasSolutionInfoFilter( nodeName ) ) {\n            mSolutionInfoFilter.reset( SolutionInfoFilterFactory::createAndParseSolutionInfoFilter( nodeName, curr ) );\n        }\n        else {\n            ILogger& mainLog = ILogger::getLogger( \"main_log\" );\n            mainLog.setLevel( ILogger::WARNING );\n            mainLog << \"Unrecognized text string: \" << nodeName << \" found while parsing \"\n                    << getXMLName() << \".\" << std::endl;\n        }\n    }\n    return true;\n}\n\n\n/*! \\brief Broyden's method solver. \n * \\details Attempts to solve the selected markets using Broyden's\n * method (see Numerical Recipes sectn. 9.7).  Broyden's method is\n * broadly similar to the Newton-Raphson Method.  At each iteration we\n * solve B . dx = -F to get the solution step for that iteration, we\n * backtrack as necessary to ensure that F . F decreases at each step,\n * and we iterate to convergence.  The difference is that in place of\n * the exact Jacobian, J, we use an approximate Jacobian, B.  At each\n * iteration we update B using Broyden's secant condition: B(i+1) =\n * B( i ) + ((dF( i ) - B( i ) . dx( i )) X dx( i )) / (dx . dx).  Since this\n * update does not require any model evaluations, it is *much* faster\n * than computing finite-difference Jacobians.\n *\n * We still need an initial approximation to the Jacobian.  Whenever\n * possible we'll get that from estimates of derivatives that we've\n * previously squirreled away in the SolutionInfo objects.  When we\n * add a new market to the solution set, we may not have good\n * derivatives for the newcomer.  In that case we'll do finite\n * difference approximations for the new column, and we'll zero the\n * off-diagonal terms of the new row.\n *\n * The solver can run in either log-log mode or linear-linear mode.\n *\n * \\author Robert Link \n * \\param solnset An initial set of SolutionInfo objects representing all of the markets we will attempt to solve\n * \\param period Model time period\n * \\return Status code indicating whether the algorithm was successful or not.\n */\nSolverComponent::ReturnCode LogBroyden::solve(SolutionInfoSet &solnset, int period) {\n  ReturnCode code = SolverComponent::ORIGINAL_STATE;\n\n    // If all markets are solved, then return with success code.\n    if( solnset.isAllSolved() ){\n        return code = SolverComponent::SUCCESS;\n    }\n    \n    startMethod();\n    if(period != mLastPer) {\n        // reset our internal counters\n        mPerIter = 0;\n        mLastPer = period;\n    }\n    \n    // Update the solution vector for the correct markets to solve.\n    // Need to update solvable status before starting solution (Ignore return code)\n    solnset.updateSolvable( mSolutionInfoFilter.get() );\n\n    ILogger& solverLog = ILogger::getLogger( \"solver_log\" );\n    solverLog.setLevel( ILogger::NOTICE );\n    solverLog << \"Beginning Broyden solution for period \" << period\n              << \"Solving \" << solnset.getNumSolvable() << \"markets.\\n\";\n    if( mLogPricep ) {\n      solverLog << \"Log price in effect\\n\";\n    }\n    else {\n      solverLog << \"Linear price in effect\\n\";\n    }\n    \n    ILogger& worstMarketLog = ILogger::getLogger( \"worst_market_log\" );\n    worstMarketLog.setLevel( ILogger::DEBUG );\n    ILogger& singleLog = ILogger::getLogger( \"single_market_log\" );\n    singleLog.setLevel( ILogger::DEBUG );\n    \n    size_t nsolv = solnset.getNumSolvable(); \n    if( nsolv == 0 ){\n      solverLog << \"No markets were assigned to this solver.  Exiting.\" << std::endl;\n        return SUCCESS;\n    }\n    \n    solverLog << \"Initial market state:\\nmkt    \\tprice   \\tsupply  \\tdemand\\n\";\n    std::vector<SolutionInfo> solvables = solnset.getSolvableSet();\n    for(size_t i=0; i<solvables.size(); ++i) {\n        solverLog << std::setw( 8 ) << i << \"\\t\"\n                  << std::setw( 8 ) << solvables[i].getPrice() << \"\\t\"\n                  << std::setw( 8 ) << solvables[i].getSupply() << \"\\t\"\n                  << std::setw( 8 ) << solvables[i].getDemand()\n                  << \"\\t\\t\" << solvables[i].getName() << \"\\n\"; \n    } \n\n    Timer& solverTimer = TimerRegistry::getInstance().getTimer( TimerRegistry::SOLVER );\n    solverTimer.start();\n    \n    UBVECTOR x( nsolv ), fx( nsolv );\n    int neval = 0;\n\n    // set our initial x from the solutionInfoSet\n    std::vector<SolutionInfo> smkts(solnset.getSolvableSet());\n    if( mLogPricep ) {\n      std::transform(smkts.begin(), smkts.end(), x.begin(), SI2lgprice);\n    }\n    else {\n      std::transform(smkts.begin(), smkts.end(), x.begin(), SI2price);\n    }\n\n    \n    // This is the closure that will evaluate the ED function\n    LogEDFun F(solnset, world, marketplace, period, mLogPricep); \n    // check the assumptions:  narg==nrtn==nsolv\n    if(F.narg() != nsolv || F.nrtn() != nsolv) {\n      solverLog.setLevel(ILogger::SEVERE);\n      solverLog << \"size mismatch in logbroyden:  nsolv= \" << F.narg()\n                << \"  nrtn= \" << F.nrtn()\n                << \"  nsolv= \" << nsolv\n                << std::endl;\n      abort();\n    }\n\n    // scale the initial guess for use in the solver algorithm\n    F.scaleInitInputs( x );\n    \n    // Call F( x ), store the result in fx\n    F(x,fx);\n\n    solverLog.setLevel(ILogger::DEBUG);\n    solverLog << \"Initial guess:\\n\" << x << \"\\nInitial F( x ):\\n\" << fx << \"\\n\";\n    solnset.printMarketInfo(\"Broyden-initial\", calcCounter->getPeriodCount(), singleLog);\n\n    // Precondition the x values to avoid singular columns in the Jacobian\n    solverLog.setLevel(ILogger::DEBUG);\n    UBMATRIX J(F.narg(), F.nrtn());\n    fdjac(F, x, fx, J, true);\n\n    solverLog << \">>>> Main loop jacobian called.\\n\";\n    int pcfail = jacobian_precondition(x, fx, J, F, &solverLog, mLogPricep);\n\n    if( pcfail ) {\n      solverLog.setLevel(ILogger::WARNING);\n      solverLog << \"Unable to find nonsingular initial guess for one or more markets.  bsolve() will probably fail.\\n\";\n      solverLog.setLevel(ILogger::DEBUG);\n    }\n    else {\n      solverLog << \"Revised guess:\\n\" << x << \"\\nRevised F( x ):\\n\" << fx << \"\\n\";\n    }\n    solnset.printMarketInfo(\"Broyden-preconditioned\", calcCounter->getPeriodCount(), singleLog);\n    cSolInfo = &solnset;        // make available for log outputs\n\n    // call the solver\n    int bstatus = bsolve(F, x, fx, J, neval);\n    mPerIter++;                 // increment the iteration count.  This should produce a visible gap in the trace plots.\n\n    solverTimer.stop(); \n\n    solverLog.setLevel(ILogger::NOTICE);\n    solverLog << \"Broyden solver:  neval= \" << neval << \"\\nResult:  \";\n    if(bstatus == 0) {\n        solverLog << \"Broyden solution success.\\n\";\n        code = SUCCESS;\n    }\n    else if(bstatus == -1) {\n        code = FAILURE_ITER_MAX_REACHED;\n        solverLog << \"Broyden solution failed: Iteration max reached.\\n\";\n    }\n    else if(bstatus == -3) {\n        code = FAILURE_ZERO_GRADIENT;\n        solverLog << \"Broyden solution failed:  Encountered zero gradient in F*F.\\n\";\n    }\n    else if(bstatus == -4) {\n        code = FAILURE_POOR_PROGRESS;\n        solverLog << \"Broyden solution failed:  repeated poor progress.\\n\";\n    }\n    else if(bstatus > 0) {\n        code = FAILURE_SINGULAR_MATRIX;\n        int singrow = bstatus-1; // L-U decomp returns row number as 1..N numbering\n        solverLog << \"Broyden solution failed:  Encountered singular matrix (row \" << singrow << \").\\n\";\n        solverLog << smkts[singrow] << std::endl;\n    }\n    else {\n        code = FAILURE_UNKNOWN;\n        solverLog << \"Broyden solution failed for unknown reason.\\n\";\n    }\n    if(!solnset.isAllSolved()) {\n        solverLog << \"The following markets were not solved:\\n\";\n        solnset.printUnsolved( solverLog );\n    }\n\n    solverLog << std::endl;\n\n    // log some final debugging info\n    const SolutionInfo* maxred = solnset.getWorstSolutionInfo();\n    addIteration(maxred->getName(), maxred->getRelativeED());\n    if( mLogPricep ) {\n      worstMarketLog << \"###Broyden-end-logPrice:  \" << *maxred << std::endl;\n    }\n    else {\n      worstMarketLog << \"###Broyden-end-linearPrice:  \" << *maxred << std::endl;\n    }\n\n    solnset.printMarketInfo(\"Broyden-end \", calcCounter->getPeriodCount(), singleLog);\n    singleLog << std::endl;\n\n    return code;\n}\n\nint LogBroyden::bsolve(VecFVec<double,double> &F, UBVECTOR &x, UBVECTOR &fx,\n                       UBMATRIX & B, int &neval)\n{\n#if !USE_LAPACK\n  using boost::numeric::ublas::permutation_matrix;\n  using boost::numeric::ublas::lu_factorize;\n  using boost::numeric::ublas::lu_substitute;\n#endif\n  using boost::numeric::ublas::axpy_prod;\n  using boost::numeric::ublas::inner_prod;\n  int nrow = B.size1(), ncol = B.size2();\n  int ageB = 0;   // number of iterations since the last reset on B\n  // svd decomposition elements (note nrow == ncol)\n#if USE_LAPACK\n  UBMATRIX Usv(nrow,ncol),VTsv(ncol,ncol);\n  UBVECTOR Ssv( ncol );\n#else\n  permutation_matrix<int> p(F.narg()); // permutation vector for pivoting in L-U decomposition\n#endif\n\n  UBMATRIX Btmp(nrow, ncol);\n  ILogger &solverLog = ILogger::getLogger(\"solver_log\");\n  ILogger& worstMarketLog = ILogger::getLogger( \"worst_market_log\" );\n  worstMarketLog.setLevel( ILogger::DEBUG );\n  ILogger& singleLog = ILogger::getLogger( \"single_market_log\" );\n  singleLog.setLevel( ILogger::DEBUG );\n\n  // market ids and solvable flag for just the solvable markets\n  std::vector<int> mktids_solv;\n  cSolInfo->getMarketIDs(mktids_solv,true);\n  std::vector<bool> issolvable_solv(mktids_solv.size(), true);\n  // market ids and solvable flag for all markets (solvable and unsolvable)\n  std::vector<int> mktids_all;\n  cSolInfo->getMarketIDs(mktids_all, false);\n  std::vector<bool> issolvable_all(mktids_all.size());\n  for(unsigned i=0; i<issolvable_solv.size(); ++i) { // solvable markets are at the beginning; set their flag to true\n      issolvable_all[i] = true;\n  }\n  for(unsigned i=issolvable_solv.size(); i<issolvable_all.size(); ++i) {\n      // unsolvable markets at the end of the array; set their flag to false\n      issolvable_all[i] = false;\n  }\n  // working space for variables that will be printed for solvable and unsolvable markets\n  UBVECTOR rptvec_all(mktids_all.size());\n  \n  F(x,fx);\n\n  solverLog.setLevel(ILogger::DEBUG);\n  \n  neval += 1 + x.size();        // initial function evaluation + jacobian calculations\n\n  const double FTINY = mFTOL*mFTOL;\n\n  UBVECTOR dx(F.narg());\n  UBVECTOR xnew(F.narg());\n  UBVECTOR gx(F.narg());\n  assert(F.nrtn() == F.narg());\n  assert(x.size() == F.narg());\n  assert(fx.size() == F.nrtn());\n  UBVECTOR jdiag(F.narg());\n  // do the asserts manually, since we can't turn on normal assertions\n  // (GCAM is riddled with asserts that fail under normal\n  // circumstances).\n  if(F.nrtn() != F.narg() || x.size() != F.narg() || fx.size() != F.nrtn()) {\n    solverLog.setLevel(ILogger::SEVERE);\n    solverLog << \"size mismatch:  nrtn= \" << F.nrtn()\n              << \"  narg= \" << F.narg()\n              << \"  x.size= \" << x.size()\n              << \"  fx.size= \" << fx.size()\n              << std::endl;\n    abort();\n  }\n\n  // We create a functor that computes f( x ) = F( x )*F( x ).  It also\n  // stores the value of F that it produces as an intermediate.\n  FdotF<double,double> fnorm( F );\n  double f0 = inner_prod(fx,fx); // already have a value of F on input, so no need to call fnorm yet\n  if(f0 < FTINY) {\n    // Guard against F=0 since it can cause a NaN in our solver.  This\n    // is a more stringent test than our regular convergence test\n    return 0;\n  }\n\n  bool lsfail = false;        // flag indicating whether we have had a line-search failure\n  for(int iter=0; iter<mMaxIter; ++iter) {\n    // log some debug info\n    \n    solverLog << \"Broyden iter= \" << iter << \"\\tneval= \" << neval << \"\\n\";\n    solverLog << \"Internal iteration count ( mPerIter )= \" << mPerIter << \"\\n\";\n    cSolInfo->printMarketInfo(\"Broyden \", calcCounter->getPeriodCount(), singleLog);\n    for(int j=0;j<F.narg();++j) {\n      // double bjj= B(j,j);\n      // jdiag[j] = bjj;\n      jdiag[j] = B(j,j);\n    }\n    static_cast<LogEDFun&>(F).setSlope(jdiag);\n    double jdmax=0.0, jdmin=0.0;\n    int jdjmax=0, jdjmin=0;\n    locate_vector_minmax(jdiag, jdmax, jdmin, jdjmax, jdjmin);\n    solverLog << \"diag( B ):\\n\" << jdiag << \"\\n\";\n    solverLog << \"maxval= \" << jdmax << \" jmax= \" << jdjmax << \"  \"\n              << \"minval= \" << jdmin << \"  jmin= \" << jdjmin << \"\\n\";\n    \n    axpy_prod(fx,B,gx);         // compute the gradient of F*F (= fx^T * B == B^T * fx)\n                                // axpy_prod clears gx on entry, so we don't have to do it.\n                                // NB: the order of fx and B in that last call is significant!\n\n    // Check for zero gradient.  This indicates a local minimum in f,\n    // from which we are unlikely to escape.  We will need to try\n    // again with a different initial guess.  (This should be very\n    // uncommon)\n    double gmag2 = inner_prod(gx,gx);\n    if(gmag2 / (f0+FTINY) < mFTOL) {\n      solverLog << \"**** ||gx|| = 0.  Returning.\\n\";\n      return -3;\n    }\n\n    Btmp = B;                   // save the jacobian approximant\n#if USE_LAPACK /* Solve using SVD */\n    int ierr = boost::numeric::bindings::lapack::gesvd('O','A','A', // control parameters\n                                                       B,           // input matrix\n                                                       Ssv,Usv,VTsv); // outputs\n    if(ierr>0) {\n      // svd failed.  It's not even clear under what circumstances\n      // this can happen\n      solverLog.setLevel(ILogger::SEVERE);\n      solverLog << \"****************SVD failed.  This shouldn't happen.  It can't mean anything good.\\n\";\n      return ierr;\n    }\n\n    // At this point, U, S, and VT contain the SVD of the original Jacobian\n    solverLog.setLevel(ILogger::DEBUG);\n    dx = -1.0*fx; \n    int nsing = svdInvertSolve(Usv,Ssv,VTsv,dx, solverLog);\n\n    solverLog << \"\\nIteration \" << iter << \"\\nf0= \" << f0\n              << \"\\tnsing= \" << nsing\n              << \"\\nx: \" << x << \"\\nF( x ): \" << fx << \"\\ndx: \" << dx << \"\\n\";\n\n#else /* No USE_LAPACK.  Solve using L-U decomposition */\n    int itrial = 0;\n    /* If the L-U decomposition fails the first time around, we will\n       invoke the jacobian preconditioner and try again.  If it fails\n       a second time, we bail out */\n    do {\n      for(size_t i=0; i<p.size(); ++i) {\n        p[i] = i;\n      }\n      int sing = lu_factorize(B,p);\n      if(sing>0) {\n        int fail=1;\n        B = Btmp;           // restore Jacobian\n        if(itrial == 0) {\n            solverLog << \"Salvaging Jacobian.\\n\";\n            fail = jacobian_precondition(x, fx, B, F, &solverLog, mLogPricep);\n            f0 = inner_prod(fx,fx);\n\n            // log the diagonal of the new jacobian\n            for(int j=0; j<F.narg(); ++j) {\n                jdiag[j] = B(j,j); \n            }\n            solverLog << \"After jacobian salvage.  diag( B )=\\n\" << jdiag << \"\\n\";\n\n        }\n        \n        if( fail ) {\n            solverLog.setLevel(ILogger::WARNING);\n            solverLog << \"Singular Jacobian:\\n\" << B << \"\\n\";\n            return sing;\n        }\n      }\n      else {\n        // L-U decomp was successful.  Continue with the next phase of the algorithm.\n        break;\n      }\n    } while(++itrial < 2);\n    \n    // J now holds the L-U decomposition of the Jacobian.  Attempt backsubstitution\n    dx = -1.0*fx;\n    try {\n      lu_substitute(B,p,dx);    // solve dx = J^-1 F\n    }\n    catch (const boost::numeric::ublas::internal_logic &err) {\n      // This error seems to be thrown when the Jacobian is\n      // ill-conditioned.  We let it go because often the solver will\n      // muddle through to a solution.  If not, then it will\n      // eventually stop with a genuinely singular matrix.\n    }\n    solverLog << \"dx: \" << dx << \"\\n\"; \n#endif /* USE_LAPACK */\n\n    // log the proposal step\n    solverLog << \"Proposal step magnitude dxmag= \" << sqrt(inner_prod(dx,dx)) << \"\\n\\n\";\n    reportVec(\"dxprop\", dx, mktids_solv, issolvable_solv);    \n\n    \n    // dx now holds the newton step.  Execute the line search along\n    // that direction.\n    double fnew;\n    int lserr = linesearch(fnorm,x,f0,gx,dx, xnew,fnew, neval, &solverLog);\n\n    if(lserr != 0) {\n      // line search failed.  There are a couple of things that could\n      // be happening here.\n\n      // 1) B is not a descent direction.  If this is the first\n      // failure starting from this x value, try a finite difference\n      // jacobian\n      if(!lsfail) {\n        solverLog << \"**Failed line search. Evaluating fdjac\\n\";\n        lsfail = true;\n        // call fdjac such that it re-calculates the model at x as linesearch will\n        // have left off on some other price vector thus we could have bad state\n        // data from which we calculate derivatives\n        fdjac(F,x,B);\n        neval += x.size();\n        ageB = 0;  // reset the age on B\n\n        // Log the diagonal of the new jacobian after the failed line search\n        for(int j=0; j<F.narg(); ++j) {\n            jdiag[j] = B(j,j);\n        }\n        solverLog << \"New Jacobian: diag( B )=\\n\" << jdiag << \"\\n\";\n        static_cast<LogEDFun&>(F).setSlope(jdiag);\n\n        // start the next iteration *without* updating x\n        continue;\n      }\n\n      // 2) The descent only continues for a very short distance\n      // (roughly TOL*x0).  Maybe we're really close to a solution and\n      // generating very tiny dx values.  Make a relaxed convergence\n      // test and return if we have a \"close enough\" solution.\n      double msf = f0/fx.size();\n      if(msf < mFTOL) {\n        // basically, we're letting ourselves converge to the sqrt of\n        // our intended tolerance.\n        return 0;\n      }\n\n      // 3) Neither of the above.  The most likely way for this to\n      // happen is if we're close to a discontinuity in (probably\n      // several components of) the Jacobian.  Using smoother supply\n      // and/or demand functions might help here.\n\n      // We're not close enough to the solution, and we don't have a\n      // good descent direction.  There are no good options at this point\n      // so kick out and hope that the preconditioner can set us straight.\n      solverLog << \"linesearch failure\\n\";\n      return -4;\n    }\n    else {\n      // reset the line search fail flag\n      lsfail = false;\n    }\n\n    UBVECTOR xstep(xnew-x);    // step in x eventually taken\n    double lambda = fabs(dx[0]) > 0.0 ? xstep[0] / dx[0] : 0.0;\n    solverLog << \"################Return from linesearch\\nfold= \" << f0 << \"\\tfnew= \" << fnew\n              << \"\\tlambda= \" << lambda << \"\\n\";\n\n    UBVECTOR fxnew(fx.size());\n    fnorm.lastF( fxnew );            // get the last value of big-F\n    solverLog << \"\\nxnew: \" << xnew << \"\\nfxnew: \" << fxnew << \"\\n\";\n    UBVECTOR fxstep(fxnew -fx); // change in F( x ).  We will need this for the secant update\n\n    // log the worst market info\n    const SolutionInfo* maxred = cSolInfo->getWorstSolutionInfo();\n    addIteration(maxred->getName(), maxred->getRelativeED());\n    if( mLogPricep ) {\n      worstMarketLog << \"Broyden-logPrice:  \" << *maxred << \"\\n\";\n    }\n    else {\n      worstMarketLog << \"Broyden-linearPrice:  \" << *maxred << \"\\n\";\n    }\n\n    // test for convergence\n    double maxval = fabs(fxnew[0]);\n    double imaxval = 0;\n    for(size_t i=1; i<fxnew.size(); ++i) {\n      double val = fabs(fxnew[i]);\n      if(val > maxval) {\n        maxval = val;\n        imaxval = i;\n      }\n    }\n\n    solverLog << \"Convergence test maxval: \" << maxval << \"  imaxval= \" << imaxval << \"\\n\";\n    solverLog << \"\\tx[i]= \" << xnew[imaxval] << \"  dx[i]= \" << dx[imaxval] << \"  xstep[i]= \"\n              << xstep[imaxval] << \"\\n\";\n    if(maxval <= mFTOL) {\n      solverLog << \"Solution successful.\\n\";\n      x = xnew;\n      fx = fxnew;\n      return 0;                 // SUCCESS \n    }\n\n#if 0\n    // secondary convergence test based on an estimated change in the\n    // price vector.  Only test this if we have a \"fresh\" jacobian\n    if(ageB == 0)  {\n        maxval = fabs(fxnew[0]) / (util::getSmallNumber() + fabs(Btmp(0,0)));\n        imaxval = 0;\n        for(size_t i=1; i<fxnew.size(); ++i) {\n            double val = fabs(fxnew[i]) / (util::getSmallNumber() + fabs(Btmp(i,i)));\n            if(val > maxval) {\n                maxval = val;\n                imaxval = i;\n            }\n        }\n        solverLog << \"Secondary convergence test maxval:  \" << maxval << \"  imaxval= \" << imaxval << \"\\n\";\n        if(maxval <= mFTOL) {   // XXX should put an x-tolerance in here\n            solverLog << \"Solved using secondary criterion.\\n\";\n            x = xnew;\n            fx = fxnew;\n            return 0; \n        }\n    }\n#endif\n    \n    // update B for next iteration\n    double fratio_cutoff = 1.0 - 1.0/nrow;\n    if(fnew/f0 < fratio_cutoff) { // making adequate progress with the Broyden formula\n      double dx2 = inner_prod(xstep,xstep);\n      UBVECTOR Bdx(F.nrtn());\n      B = Btmp;\n      fxstep -= axpy_prod(B, xstep, Bdx);\n      fxstep /= dx2;\n      B += outer_prod(fxstep, xstep);\n      ageB++;                // increment the age of B\n    }\n    else {\n      // Progress using the Broyden formula is anemic.  This usually\n      // happens near discontinuities in the Jacobian matrix.  If B is\n      // old, try a finite-difference jacobian to get us back on track.\n      if(ageB > 0) {\n        solverLog << \"Insufficient progress with Broyden formula.  Resetting the Jacobian.\\n(f0= \" << f0 << \", fnew= \" << fnew << \")\\n\";\n        // just in case call fdjac such that it re-calculates the model at xnew\n        // otherwise we could have bad state data from which we calculate derivatives\n        fdjac(F,xnew,B);\n        neval += x.size();\n        ageB = 0;\n\n        // Log the results of the Jacobian reset\n        for(int j=0; j<F.narg(); ++j) {\n            jdiag[j] = B(j,j);\n        }\n            \n        solverLog << \"New Jacobian:  diag( B )=\\n\" << jdiag << \"\\n\";\n        static_cast<LogEDFun&>(F).setSlope(jdiag);\n        \n      }\n      else {\n        // just did a reset, and it didn't help us.  Probably we've\n        // got a very ill-behaved value in one of the variables.  Kick\n        // it out and see if the bracketing routine can fix it.\n        solverLog << \"Repeated poor progress in Broyden solver.  Returning.\\n\";\n        return -4;\n      }\n    }\n\n    // log the data trace before we do the update\n    reportVec(\"x\", xnew, mktids_solv, issolvable_solv);\n    reportVec(\"fx\", fxnew, mktids_solv, issolvable_solv);\n    reportVec(\"deltax\", xnew-x, mktids_solv, issolvable_solv);    // xstep may have been modified above\n    reportVec(\"deltafx\", fxnew-fx, mktids_solv, issolvable_solv); // fxstep definitely modified above\n    reportVec(\"diagB\", jdiag, mktids_solv, issolvable_solv);\n    reportPSD(rptvec_all, mktids_all, issolvable_all);                // report price, supply, and demand.  \n    mPerIter++;\n\n    // update x, fx, f0 for next iteration\n    f0 = fnew;\n    x  = xnew;\n    fx = fxnew;\n\n  }\n\n  // if we get here, then we didn't converge in the number of\n  // iterations allowed us.  Return an error code\n  solverLog << \"\\n****************Maximum solver iterations exceeded.\\nlastx: \" << x\n            << \"\\nlastF: \" << fx << \"\\n\";\n  return -1;\n}\n\n/*! \\brief Write a vector into the solver data log\n *\n *  \\details We write the solver data log in \"long\" format; i.e., with\n *           one completely-specified data item per line.  This allows\n *           us to simply skip variables that we don't have data for\n *           (vs. filling in NaN values), and we don't have to commit\n *           to a fixed number of variables; e.g., we could have more\n *           variables for price, supply, and demand.\n *\n *           The output columns are:\n *           period, iteration, variable name, market id, solvable (T/F), value\n *\n */\nvoid LogBroyden::reportVec(const std::string &aname, const UBVECTOR &av, const std::vector<int> &amktids,\n                           const std::vector<bool> &aissolvable)\n{\n    ILogger &datalog = ILogger::getLogger(\"solver-data-log\");\n    datalog.setLevel(ILogger::DEBUG);\n    // Skip preparing the output if it won't be printed\n    if(!datalog.wouldPrint(ILogger::DEBUG)) {\n        return;\n    }\n\n    for(unsigned int i=0; i<av.size(); ++i) {\n        datalog << mLastPer <<  \" , \" << mPerIter\n                << \",\\\"\" << aname << \"\\\"\"\n                << \", \" << amktids[i]\n                << (aissolvable[i] ? \", T\" : \", F\")\n                << \", \" << av[i] << \"\\n\";\n    }\n}\n\nvoid LogBroyden::reportPSD(UBVECTOR &arptvec, const std::vector<int> &amktids, const std::vector<bool> &aissolvable)\n{\n    // Skip preparing the log output if we're not going to print it anyhow \n    if(!ILogger::getLogger(\"solver-data-log\").wouldPrint(ILogger::DEBUG)) {\n        return;\n    }\n\n    if(!cSolInfo) {\n        ILogger &solverlog = ILogger::getLogger(\"solver_log\");\n        ILogger::WarningLevel olvl = solverlog.setLevel(ILogger::ERROR);\n        solverlog << \"cSolInfo is not set.  Data log will not include price, supply, or demand.\" << std::endl;\n        solverlog.setLevel( olvl );\n        return;\n    }\n\n    std::vector<SolutionInfo> solvable = cSolInfo->getSolvableSet();\n    std::vector<SolutionInfo> unsolvable = cSolInfo->getUnsolvableSet();\n\n    unsigned int i;\n    unsigned int j;\n    // log prices\n    for(i=0; i<solvable.size(); ++i) {\n        arptvec[i] = solvable[i].getPrice();\n    }\n    for(i=0,j=solvable.size(); i<unsolvable.size(); ++i,++j) {\n        arptvec[j] = unsolvable[i].getPrice();\n    }\n        \n    reportVec(\"price\", arptvec, amktids, aissolvable);\n\n    // log supply\n    for(i=0; i<solvable.size(); ++i) {\n        arptvec[i] = solvable[i].getSupply();\n    }\n    for(i=0,j=solvable.size(); i<unsolvable.size(); ++i,++j) {\n        arptvec[j] = unsolvable[i].getSupply();\n    }\n    reportVec(\"supply\", arptvec, amktids, aissolvable);\n\n    // log demand\n    for(i=0; i<solvable.size(); ++i) {\n        arptvec[i] = solvable[i].getDemand();\n    }\n    for(i=0,j=solvable.size(); i<unsolvable.size(); ++i,++j) {\n        arptvec[j] = unsolvable[i].getDemand();\n    }\n    reportVec(\"demand\", arptvec, amktids, aissolvable);\n\n}\n\n    \n", "meta": {"hexsha": "bace74441fbeb89f800a3f87529b24bb8fe13b43", "size": 32004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/solution/solvers/source/logbroyden.cpp", "max_stars_repo_name": "ypwong22/gcam-core", "max_stars_repo_head_hexsha": "f8138153e52b5e875b1775406d2de70868587149", "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": "cvs/objects/solution/solvers/source/logbroyden.cpp", "max_issues_repo_name": "ypwong22/gcam-core", "max_issues_repo_head_hexsha": "f8138153e52b5e875b1775406d2de70868587149", "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": "cvs/objects/solution/solvers/source/logbroyden.cpp", "max_forks_repo_name": "ypwong22/gcam-core", "max_forks_repo_head_hexsha": "f8138153e52b5e875b1775406d2de70868587149", "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.2822966507, "max_line_length": 146, "alphanum_fraction": 0.6148606424, "num_tokens": 8720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.18163631764442806}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2011 - 2013   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_FORWARD_ALIGNED_ARRAY_HPP_INCLUDED\n#define BOOST_SIMD_FORWARD_ALIGNED_ARRAY_HPP_INCLUDED\n\n#include <boost/simd/sdk/config/arch.hpp>\n#include <boost/simd/meta/prev_power_of_2.hpp>\n\n#if !defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  template< class T\n          , std::size_t N\n          , std::size_t Align = (BOOST_SIMD_ARCH_ALIGNMENT > (N*sizeof(T)))\n                              ? meta::prev_power_of_2_c< N*sizeof(T) >::value\n                              : BOOST_SIMD_ARCH_ALIGNMENT\n          >\n  struct aligned_array;\n} }\n\n#endif\n\n#endif\n", "meta": {"hexsha": "ca058e0b5f63e969e9faa8f37c99181a3f8a3690", "size": 1132, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/forward/aligned_array.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/sdk/include/boost/simd/forward/aligned_array.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/sdk/include/boost/simd/forward/aligned_array.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": 36.5161290323, "max_line_length": 80, "alphanum_fraction": 0.5432862191, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1816022601890156}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2020 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_ALGORITHMS_DETAIL_BUFFER_PIECE_BORDER_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_PIECE_BORDER_HPP\n\n\n#include <boost/array.hpp>\n#include <boost/core/addressof.hpp>\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/config.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/algorithms/comparable_distance.hpp>\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/algorithms/expand.hpp>\n#include <boost/geometry/algorithms/detail/buffer/buffer_box.hpp>\n#include <boost/geometry/algorithms/detail/buffer/buffer_policies.hpp>\n#include <boost/geometry/algorithms/detail/expand_by_epsilon.hpp>\n#include <boost/geometry/strategies/cartesian/turn_in_ring_winding.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\ntemplate <typename It, typename T, typename Compare>\ninline bool get_range_around(It begin, It end, T const& value, Compare const& compare, It& lower, It& upper)\n{\n    lower = end;\n    upper = end;\n\n    // Get first element not smaller than value\n    if (begin == end)\n    {\n        return false;\n    }\n    if (compare(value, *begin))\n    {\n        // The value is smaller than the first item, therefore not in range\n        return false;\n    }\n    // *(begin + std::distance(begin, end) - 1))\n    if (compare(*(end - 1), value))\n    {\n        // The last item is larger than the value, therefore not in range\n        return false;\n    }\n\n    // Assign the iterators.\n    // lower >= begin and lower < end\n    // upper > lower and upper <= end\n    // lower_bound points to first element NOT LESS than value - but because\n    // we want the first value LESS than value, we decrease it\n    lower = std::lower_bound(begin, end, value, compare);\n    // upper_bound points to first element of which value is LESS\n    upper = std::upper_bound(begin, end, value, compare);\n\n    if (lower != begin)\n    {\n        --lower;\n    }\n    if (upper != end)\n    {\n        ++upper;\n    }\n    return true;\n}\n\n}\n\n\nnamespace detail { namespace buffer\n{\n\n//! Contains the border of the piece, consisting of 4 parts:\n//! 1: the part of the offsetted ring (referenced, not copied)\n//! 2: the part of the original (one or two points)\n//! 3: the left part (from original to offsetted)\n//! 4: the right part (from offsetted to original)\n//! Besides that, it contains some properties of the piece(border);\n//!   - convexity\n//!   - envelope\n//!   - monotonicity of the offsetted ring\n//!   - min/max radius of a point buffer\n//!   - if it is a \"reversed\" piece (linear features with partly negative buffers)\ntemplate <typename Ring, typename Point>\nstruct piece_border\n{\n    typedef typename geometry::coordinate_type<Point>::type coordinate_type;\n    typedef typename default_comparable_distance_result<Point>::type radius_type;\n    typedef typename geometry::strategy::buffer::turn_in_ring_winding<coordinate_type>::state_type state_type;\n\n    bool m_reversed;\n\n    // Points from the offsetted ring. They are not copied, this structure\n    // refers to those points\n    Ring const* m_ring;\n    std::size_t m_begin;\n    std::size_t m_end;\n\n    // Points from the original (one or two, depending on piece shape)\n    // Note, if there are 2 points, they are REVERSED w.r.t. the original\n    // Therefore here we can walk in its order.\n    boost::array<Point, 2> m_originals;\n    std::size_t m_original_size;\n\n    geometry::model::box<Point> m_envelope;\n    bool m_has_envelope;\n\n    // True if piece is determined as \"convex\"\n    bool m_is_convex;\n\n    // True if offsetted part is monotonically changing in x-direction\n    bool m_is_monotonic_increasing;\n    bool m_is_monotonic_decreasing;\n\n    radius_type m_min_comparable_radius;\n    radius_type m_max_comparable_radius;\n\n    piece_border()\n        : m_reversed(false)\n        , m_ring(NULL)\n        , m_begin(0)\n        , m_end(0)\n        , m_original_size(0)\n        , m_has_envelope(false)\n        , m_is_convex(false)\n        , m_is_monotonic_increasing(false)\n        , m_is_monotonic_decreasing(false)\n        , m_min_comparable_radius(0)\n        , m_max_comparable_radius(0)\n    {\n    }\n\n    // Only used for debugging (SVG)\n    Ring get_full_ring() const\n    {\n        Ring result;\n        if (ring_or_original_empty())\n        {\n            return result;\n        }\n        std::copy(m_ring->begin() + m_begin,\n                  m_ring->begin() + m_end,\n                  std::back_inserter(result));\n        std::copy(m_originals.begin(),\n                  m_originals.begin() + m_original_size,\n                  std::back_inserter(result));\n        // Add the closing point\n        result.push_back(*(m_ring->begin() + m_begin));\n\n        return result;\n    }\n\n    void get_properties_of_border(bool is_point_buffer, Point const& center)\n    {\n        m_has_envelope = calculate_envelope(m_envelope);\n        if (m_has_envelope)\n        {\n            // Take roundings into account, enlarge box\n            geometry::detail::expand_by_epsilon(m_envelope);\n        }\n        if (! ring_or_original_empty() && is_point_buffer)\n        {\n            // Determine min/max radius\n            calculate_radii(center, m_ring->begin() + m_begin, m_ring->begin() + m_end);\n        }\n    }\n\n    template <typename SideStrategy>\n    void get_properties_of_offsetted_ring_part(SideStrategy const& strategy)\n    {\n        if (! ring_or_original_empty())\n        {\n            m_is_convex = is_convex(strategy);\n            check_monotonicity(m_ring->begin() + m_begin, m_ring->begin() + m_end);\n        }\n    }\n\n    void set_offsetted(Ring const& ring, std::size_t begin, std::size_t end)\n    {\n        BOOST_GEOMETRY_ASSERT(begin <= end);\n        BOOST_GEOMETRY_ASSERT(begin < boost::size(ring));\n        BOOST_GEOMETRY_ASSERT(end <= boost::size(ring));\n\n        m_ring = boost::addressof(ring);\n        m_begin = begin;\n        m_end = end;\n    }\n\n    void add_original_point(Point const& point)\n    {\n        BOOST_GEOMETRY_ASSERT(m_original_size < 2);\n        m_originals[m_original_size++] = point;\n    }\n\n    template <typename Box>\n    bool calculate_envelope(Box& envelope) const\n    {\n        geometry::assign_inverse(envelope);\n        if (ring_or_original_empty())\n        {\n            return false;\n        }\n        expand_envelope(envelope, m_ring->begin() + m_begin, m_ring->begin() + m_end);\n        expand_envelope(envelope, m_originals.begin(), m_originals.begin() + m_original_size);\n        return true;\n    }\n\n\n    // Whatever the return value, the state should be checked.\n    template <typename TurnPoint, typename State>\n    bool point_on_piece(TurnPoint const& point,\n                        bool one_sided, bool is_linear_end_point,\n                        State& state) const\n    {\n        if (ring_or_original_empty())\n        {\n            return false;\n        }\n\n        // Walk over the different parts of the ring, in clockwise order\n        // For performance reasons: start with the helper part (one segment)\n        // then the original part (one segment, if any), then the other helper\n        // part (one segment), and only then the offsetted part\n        // (probably more segments, check monotonicity)\n        geometry::strategy::buffer::turn_in_ring_winding<coordinate_type> tir;\n\n        Point const offsetted_front = *(m_ring->begin() + m_begin);\n        Point const offsetted_back = *(m_ring->begin() + m_end - 1);\n\n        // For onesided buffers, or turns colocated with linear end points,\n        // the place on the ring is changed to offsetted (because of colocation)\n        geometry::strategy::buffer::place_on_ring_type const por_original\n            = adapted_place_on_ring(geometry::strategy::buffer::place_on_ring_original,\n                                    one_sided, is_linear_end_point);\n        geometry::strategy::buffer::place_on_ring_type const por_from_offsetted\n            = adapted_place_on_ring(geometry::strategy::buffer::place_on_ring_from_offsetted,\n                                    one_sided, is_linear_end_point);\n        geometry::strategy::buffer::place_on_ring_type const por_to_offsetted\n            = adapted_place_on_ring(geometry::strategy::buffer::place_on_ring_to_offsetted,\n                                    one_sided, is_linear_end_point);\n\n        bool continue_processing = true;\n        if (m_original_size == 1)\n        {\n            // One point. Walk from last offsetted to point, and from point to first offsetted\n            continue_processing = step(point, offsetted_back, m_originals[0], tir, por_from_offsetted, state)\n                && step(point, m_originals[0], offsetted_front, tir, por_to_offsetted, state);\n        }\n        else if (m_original_size == 2)\n        {\n            // Two original points. Walk from last offsetted point to first original point,\n            // then along original, then from second oginal to first offsetted point\n            continue_processing = step(point, offsetted_back, m_originals[0], tir, por_from_offsetted, state)\n                    && step(point, m_originals[0], m_originals[1], tir, por_original, state)\n                    && step(point, m_originals[1], offsetted_front, tir, por_to_offsetted, state);\n        }\n\n        if (continue_processing)\n        {\n            // Check the offsetted ring (in rounded joins, these might be\n            // several segments)\n            walk_offsetted(point, m_ring->begin() + m_begin, m_ring->begin() + m_end,\n                           tir, state);\n        }\n\n        return true;\n    }\n\n    //! Returns true if empty (no ring, or no points, or no original)\n    bool ring_or_original_empty() const\n    {\n        return m_ring == NULL || m_begin >= m_end || m_original_size == 0;\n    }\n\nprivate :\n\n    static geometry::strategy::buffer::place_on_ring_type\n        adapted_place_on_ring(geometry::strategy::buffer::place_on_ring_type target,\n                              bool one_sided, bool is_linear_end_point)\n    {\n        return one_sided || is_linear_end_point\n               ? geometry::strategy::buffer::place_on_ring_offsetted\n               : target;\n    }\n\n    template <typename TurnPoint, typename Iterator, typename Strategy, typename State>\n    bool walk_offsetted(TurnPoint const& point, Iterator begin, Iterator end, Strategy const & strategy, State& state) const\n    {\n        Iterator it = begin;\n        Iterator beyond = end;\n\n        // Move iterators if the offsetted ring is monotonic increasing or decreasing\n        if (m_is_monotonic_increasing)\n        {\n            if (! get_range_around(begin, end, point, geometry::less<Point, 0>(), it, beyond))\n            {\n                return true;\n            }\n        }\n        else if (m_is_monotonic_decreasing)\n        {\n            if (! get_range_around(begin, end, point, geometry::greater<Point, 0>(), it, beyond))\n            {\n                return true;\n            }\n        }\n\n        for (Iterator previous = it++ ; it != beyond ; ++previous, ++it )\n        {\n            if (! step(point, *previous, *it, strategy,\n                 geometry::strategy::buffer::place_on_ring_offsetted, state))\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    template <typename TurnPoint, typename Strategy, typename State>\n    bool step(TurnPoint const& point, Point const& p1, Point const& p2, Strategy const & strategy,\n              geometry::strategy::buffer::place_on_ring_type place_on_ring, State& state) const\n    {\n        // A step between original/offsetted ring is always convex\n        // (unless the join strategy generates points left of it -\n        //  future: convexity might be added to the buffer-join-strategy)\n        // Therefore, if the state count > 0, it means the point is left of it,\n        // and because it is convex, we can stop\n\n        typedef typename geometry::coordinate_type<Point>::type coordinate_type;\n        typedef geometry::detail::distance_measure<coordinate_type> dm_type;\n        dm_type const dm = geometry::detail::get_distance_measure(point, p1, p2);\n        if (m_is_convex && dm.measure > 0)\n        {\n            // The point is left of this segment of a convex piece\n            state.m_count = 0;\n            return false;\n        }\n        // Call strategy, and if it is on the border, return false\n        // to stop further processing.\n        return strategy.apply(point, p1, p2, dm, place_on_ring, state);\n    }\n\n    template <typename It, typename Box>\n    void expand_envelope(Box& envelope, It begin, It end) const\n    {\n        typedef typename strategy::expand::services::default_strategy\n            <\n                point_tag, typename cs_tag<Box>::type\n            >::type expand_strategy_type;\n\n        for (It it = begin; it != end; ++it)\n        {\n            geometry::expand(envelope, *it, expand_strategy_type());\n        }\n    }\n\n    template <typename SideStrategy>\n    bool is_convex(SideStrategy const& strategy) const\n    {\n        if (ring_or_original_empty())\n        {\n            // Convexity is undetermined, and for this case it does not matter,\n            // because it is only used for optimization in point_on_piece,\n            // but that is not called if the piece border is not valid\n            return false;\n        }\n\n        if (m_end - m_begin <= 2)\n        {\n            // The offsetted ring part of this piece has only two points.\n            // If this is true, and the original ring part has only one point,\n            // a triangle and it is convex. If the original ring part has two\n            // points, it is a rectangle and theoretically could be concave,\n            // but because of the way the buffer is generated, that is never\n            // the case.\n            return true;\n        }\n\n        // The offsetted ring part of thie piece has at least three points\n        // (this is often the case in a piece marked as \"join\")\n\n        // We can assume all points of the offset ring are different, and also\n        // that all points on the original are different, and that the offsetted\n        // ring is different from the original(s)\n        Point const offsetted_front = *(m_ring->begin() + m_begin);\n        Point const offsetted_second = *(m_ring->begin() + m_begin + 1);\n\n        // These two points will be reassigned in every is_convex call\n        Point previous = offsetted_front;\n        Point current = offsetted_second;\n\n        // Verify the offsetted range (from the second point on), the original,\n        // and loop through the first two points of the offsetted range\n        bool const result = is_convex(previous, current, m_ring->begin() + m_begin + 2, m_ring->begin() + m_end, strategy)\n            && is_convex(previous, current, m_originals.begin(), m_originals.begin() + m_original_size, strategy)\n            && is_convex(previous, current, offsetted_front, strategy)\n            && is_convex(previous, current, offsetted_second, strategy);\n\n        return result;\n    }\n\n    template <typename It, typename SideStrategy>\n    bool is_convex(Point& previous, Point& current, It begin, It end, SideStrategy const& strategy) const\n    {\n        for (It it = begin; it != end; ++it)\n        {\n            if (! is_convex(previous, current, *it, strategy))\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    template <typename SideStrategy>\n    bool is_convex(Point& previous, Point& current, Point const& next, SideStrategy const& strategy) const\n    {\n        typename SideStrategy::equals_point_point_strategy_type const\n            eq_pp_strategy = strategy.get_equals_point_point_strategy();\n\n        int const side = strategy.apply(previous, current, next);\n        if (side == 1)\n        {\n            // Next is on the left side of clockwise ring: piece is not convex\n            return false;\n        }\n        if (! equals::equals_point_point(current, next, eq_pp_strategy))\n        {\n            previous = current;\n            current = next;\n        }\n        return true;\n    }\n\n    template <int Direction>\n    inline void step_for_monotonicity(Point const& current, Point const& next)\n    {\n        if (geometry::get<Direction>(current) >= geometry::get<Direction>(next))\n        {\n            m_is_monotonic_increasing = false;\n        }\n        if (geometry::get<Direction>(current) <= geometry::get<Direction>(next))\n        {\n            m_is_monotonic_decreasing = false;\n        }\n    }\n\n    template <typename It>\n    void check_monotonicity(It begin, It end)\n    {\n        m_is_monotonic_increasing = true;\n        m_is_monotonic_decreasing = true;\n\n        if (begin == end || begin + 1 == end)\n        {\n            return;\n        }\n\n        It it = begin;\n        for (It previous = it++; it != end; ++previous, ++it)\n        {\n            step_for_monotonicity<0>(*previous, *it);\n        }\n    }\n\n    template <typename It>\n    inline void calculate_radii(Point const& center, It begin, It end)\n    {\n        typedef geometry::model::referring_segment<Point const> segment_type;\n\n        bool first = true;\n\n        // An offsetted point-buffer ring around a point is supposed to be closed,\n        // therefore walking from start to end is fine.\n        It it = begin;\n        for (It previous = it++; it != end; ++previous, ++it)\n        {\n            segment_type const s(*previous, *it);\n            radius_type const d = geometry::comparable_distance(center, s);\n\n            if (first || d < m_min_comparable_radius)\n            {\n                m_min_comparable_radius = d;\n            }\n            if (first || d > m_max_comparable_radius)\n            {\n                m_max_comparable_radius = d;\n            }\n            first = false;\n        }\n    }\n\n};\n\n}} // namespace detail::buffer\n#endif // DOXYGEN_NO_DETAIL\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_PIECE_BORDER_HPP\n", "meta": {"hexsha": "7393b19866c2dab45c4ebfd1aae9009ac69ab968", "size": 18348, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/geometry/algorithms/detail/buffer/piece_border.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/geometry/algorithms/detail/buffer/piece_border.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/geometry/algorithms/detail/buffer/piece_border.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": 35.627184466, "max_line_length": 124, "alphanum_fraction": 0.6256267713, "num_tokens": 4171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18160225842012245}}
{"text": "#ifdef USE_CAFFE\n\n#include <boost/filesystem.hpp>\n#include <boost/make_shared.hpp>\n#include <fstream>\n#include <glog/logging.h>\n#include <opencv2/opencv.hpp>\n\n#include \"nexus/backend/caffe_densecap_model.h\"\n#include \"nexus/common/image.h\"\n#include \"nexus/common/util.h\"\n// Caffe headers\n#include \"caffe/layers/slice_layer.hpp\"\n#include \"caffe/util/nms.hpp\"\n\nnamespace nexus {\nnamespace backend {\n\nnamespace fs = boost::filesystem;\n\nCaffeDenseCapModel::CaffeDenseCapModel(int gpu_id,\n                                       const ModelInstanceConfig& config) :\n    ModelInstance(gpu_id, config) {\n  CHECK(model_info_[\"feature_prototxt\"]) << \"Missing feature_prototxt in \" <<\n      \"the config\";\n  CHECK(model_info_[\"rnn_prototxt\"]) << \"Missing rnn_prototxt in the config\";\n  CHECK(model_info_[\"embed_prototxt\"]) << \"Missing embed_prototxt in \" <<\n      \"the config\";\n  CHECK(model_info_[\"model_file\"]) << \"Missing model_file in the config\";\n  CHECK(model_info_[\"vocab_file\"]) << \"Missing vocab_file in the config\";\n  CHECK(model_info_[\"mean_value\"]) << \"Missing mean_value in the config\";\n  CHECK_EQ(model_info_[\"mean_value\"].size(), 3);\n  // load config\n  max_boxes_ = model_info_[\"max_boxes\"].as<int>();\n  max_timestep_ = model_info_[\"max_timestep\"].as<int>();\n  nms_threshold_ = model_info_[\"nms_threshold\"].as<float>();\n  score_threshold_ = model_info_[\"score_threshold\"].as<float>();\n  for (uint i = 0; i < model_info_[\"mean_value\"].size(); ++i) {\n    mean_values_.push_back(model_info_[\"mean_value\"][i].as<float>());\n  }\n  for (uint i = 0; i < model_info_[\"bbox_mean\"].size(); ++i) {\n    bbox_mean_.push_back(model_info_[\"bbox_mean\"][i].as<float>());\n  }\n  for (uint i = 0; i < model_info_[\"bbox_stds\"].size(); ++i) {\n    bbox_stds_.push_back(model_info_[\"bbox_stds\"][i].as<float>());\n  }\n  // init gpu device\n  caffe::Caffe::SetDevice(gpu_id);\n  caffe::Caffe::set_mode(caffe::Caffe::GPU);\n  // load caffe model\n  fs::path model_dir = fs::path(model_info_[\"model_dir\"].as<std::string>());\n  fs::path feature_prototxt = model_dir / model_info_[\"feature_prototxt\"].\n                              as<std::string>();\n  fs::path rnn_prototxt = model_dir / model_info_[\"rnn_prototxt\"].\n                          as<std::string>();\n  fs::path embed_prototxt = model_dir / model_info_[\"embed_prototxt\"].\n                            as<std::string>();\n  fs::path model_file = model_dir / model_info_[\"model_file\"].as<std::string>();\n  feature_net_.reset(new caffe::ServeNet<float>(\n      feature_prototxt.string(), max_batch_));\n  rnn_net_.reset(new caffe::ServeNet<float>(\n      rnn_prototxt.string(), max_batch_ * max_boxes_, 1));\n  embed_net_.reset(new caffe::ServeNet<float>(\n      embed_prototxt.string(), max_batch_ * max_boxes_, 1));\n  caffe::NetParameter caffemodel;\n  caffe::ReadNetParamsFromBinaryFileOrDie(model_file.string(), &caffemodel);\n  feature_net_->CopyTrainedLayersFrom(caffemodel);\n  rnn_net_->CopyTrainedLayersFrom(caffemodel);\n  embed_net_->CopyTrainedLayersFrom(caffemodel);\n  // set up input and output size\n  image_height_ = model_session_.image_height();\n  image_width_ = model_session_.image_width();\n  /*\n  int target_size = model_info_[\"target_size\"].as<int>();\n  int max_size = model_info_[\"max_size\"].as<int>();\n  float aspect_ratio = model_info_[\"aspect_ratio\"].as<float>();\n  if (aspect_ratio > 1) {\n    input_width_ = (int) round(\n        std::min((float) max_size, target_size * aspect_ratio));\n    input_height_ = (int) round(input_width_ / aspect_ratio);\n  } else {\n    input_height_ = (int) round(\n        std::min((float) max_size, target_size / aspect_ratio));\n    input_width_ = (int) round(input_height_ * aspect_ratio);\n  }*/\n  LOG(INFO) << \"input shape: \" << image_height_ << \" x \" << image_width_;\n  \n  input_shape_.set_dims({max_batch_, 3, image_height_, image_width_});\n  input_size_ = input_shape_.NumElements(1);\n  feature_net_input_idx_ = feature_net_->input_blob_indices()[0];\n  // Reshape the input blob and feature_net according to our input size\n  feature_net_->input_blobs()[0]->Reshape(input_shape_.dims());\n  feature_net_->Reshape();\n  // load vocabulary\n  fs::path vocab_file = model_dir / model_info_[\"vocab_file\"].as<std::string>();\n  LoadVocabulary(vocab_file.string());\n  // set helper buffer\n  multiplier_.reset(new caffe::Blob<float>({max_boxes_}));\n  caffe::caffe_gpu_set(max_boxes_, (float) 1., multiplier_->mutable_gpu_data());\n  best_words_.resize(max_batch_ * max_boxes_);\n\n  output_shapes_.emplace(\"rois\", Shape({max_batch_, max_boxes_, 5}));\n  output_shapes_.emplace(\"bbox_offsets\", Shape({max_batch_, max_boxes_, 4}));\n  output_shapes_.emplace(\"captions\",\n                        Shape({max_batch_, max_boxes_, max_timestep_}));\n  output_shapes_.emplace(\"scores\", Shape({max_batch_, max_boxes_, 2}));\n}\n\nShape CaffeDenseCapModel::InputShape() {\n  return input_shape_;\n}\n\nstd::unordered_map<std::string, Shape> CaffeDenseCapModel::OutputShapes() {\n  return output_shapes_;\n}\n\nArrayPtr CaffeDenseCapModel::CreateInputGpuArray() {\n  boost::shared_ptr<caffe::Blob<float> > blob;\n  if (input_blobs_.empty()) {\n    blob = feature_net_->blobs()[feature_net_input_idx_];\n  } else {\n    blob = boost::make_shared<caffe::Blob<float> >(input_shape_.dims());\n  }\n  size_t nfloats = max_batch_ * input_size_;\n  auto buf = std::make_shared<Buffer>(blob->mutable_gpu_data(),\n                                      nfloats * sizeof(float),\n                                      gpu_device_);\n  auto arr = std::make_shared<Array>(DT_FLOAT, nfloats, buf);\n  arr->set_tag(input_blobs_.size());\n  input_blobs_.push_back(blob);\n  return arr;\n}\n\nstd::unordered_map<std::string, ArrayPtr> CaffeDenseCapModel::GetOutputGpuArrays() {\n  // Currently doesn't support in-place output in GPU memory\n  return {};\n}\n\nvoid CaffeDenseCapModel::Preprocess(std::shared_ptr<Task> task) {\n  const auto& query = task->query;\n  const auto& input_data = query.input();\n  if (input_data.data_type() != DT_IMAGE) {\n    task->result.set_status(INPUT_TYPE_INCORRECT);\n    task->result.set_error_message(\"Input type incorrect: \" +\n                                   DataType_Name(input_data.data_type()));\n    return;\n  }\n  cv::Mat cv_img_bgr = DecodeImage(input_data.image(), CO_BGR);\n  cv::Mat img;\n  cv_img_bgr.convertTo(img, CV_32FC3);\n  for (cv::Point3_<float>& p : cv::Mat_<cv::Point3_<float> >(img)) {\n    p.x -= mean_values_[0];\n    p.y -= mean_values_[1];\n    p.z -= mean_values_[2];\n  }\n  int origin_height = cv_img_bgr.rows;\n  int origin_width = cv_img_bgr.cols;\n  cv::Mat resized;\n  cv::resize(img, resized, cv::Size(image_width_, image_height_));\n  float scale_h = float(image_height_) / origin_height;\n  float scale_w = float(image_width_) / origin_width;\n  // set the attributes\n  task->attrs[\"im_height\"] = origin_height;\n  task->attrs[\"im_width\"] = origin_width;\n  task->attrs[\"scale_h\"] = scale_h;\n  task->attrs[\"scale_w\"] = scale_w;\n  // transpose the image\n  const float* im_data = (const float*) resized.data;\n  auto in_arr = std::make_shared<Array>(DT_FLOAT, input_size_, cpu_device_);\n  float* input = in_arr->Data<float>();\n  for (int h = 0; h < image_height_; ++h) {\n    for (int w = 0; w < image_width_; ++w) {\n      for (int c = 0; c < 3; ++c) {\n        int idx = (c * image_height_ + h) * image_width_ + w;\n        input[idx] = im_data[(h * image_width_ + w) * 3 + c];\n      }\n    }\n  }\n  task->AppendInput(in_arr);\n}\n\nvoid CaffeDenseCapModel::Forward(std::shared_ptr<BatchTask> batch_task) {\n  // Get all output arrays\n  auto rois_arr = batch_task->GetOutputArray(\"rois\");\n  auto bbox_offsets_arr = batch_task->GetOutputArray(\"bbox_offsets\");\n  auto captions_arr = batch_task->GetOutputArray(\"captions_arr\");\n  auto scores_arr = batch_task->GetOutputArray(\"scores\");\n  \n  auto t1 = std::chrono::high_resolution_clock::now();\n  // Prepare image blob\n  auto blob = input_blobs_[batch_task->GetInputArray()->tag()];\n  int batch = batch_task->batch_size();\n  std::vector<int> input_shape = input_shape_.dims();\n  input_shape[0] = batch;\n  blob->Reshape(input_shape);\n  feature_net_->set_blob(feature_net_input_idx_, blob);\n  \n  // Prepare im_info blob\n  auto im_info_blob = feature_net_->input_blobs()[1];\n  float* im_info = im_info_blob->mutable_cpu_data();\n  im_info[0] = image_height_;  // input image height\n  im_info[1] = image_width_;  // input image width\n  im_info[2] = batch_task->inputs()[0]->task->attrs[\"scale_h\"].as<float>();\n  \n  // set the slice points\n  auto split_fc7_layer = dynamic_cast<caffe::SliceLayer<float>*>(\n      feature_net_->layer_by_name(\"split_fc7\").get());\n  auto split_fc8_layer = dynamic_cast<caffe::SliceLayer<float>*>(\n      feature_net_->layer_by_name(\"split_fc8\").get());\n  split_fc7_layer->SetSlicePoints({batch});\n  split_fc8_layer->SetSlicePoints({batch});\n  // forward feature_net_\n  feature_net_->Forward();\n  \n  // get outputs from feature_net_\n  auto num_proposals_blob = feature_net_->blob_by_name(\"num_proposals\");\n  auto rois_blob = feature_net_->blob_by_name(\"rois\");\n  auto scores_blob = feature_net_->blob_by_name(\"cls_probs\");\n  int total_proposals = scores_blob->shape(0);\n\n  // Copy outputs of feature_net from GPU to CPU\n  float* num_proposals = new float[batch];\n  float* rois = rois_arr->Data<float>();\n  float* scores = scores_arr->Data<float>();\n  Memcpy(num_proposals, cpu_device_, num_proposals_blob->gpu_data(),\n         gpu_device_, batch * sizeof(float));\n  // add offset batch is because [0 - batch-1] rois are global rois\n  Memcpy(rois, rois_arr->device(),\n         rois_blob->gpu_data() + rois_blob->offset(batch), gpu_device_,\n         total_proposals * 5 * sizeof(float));\n  Memcpy(scores, scores_arr->device(), scores_blob->gpu_data(), gpu_device_,\n         total_proposals * 2 * sizeof(float));\n  auto t2 = std::chrono::high_resolution_clock::now();\n  //LOG(INFO) << *num_proposals;\n  //LOG(INFO) << total_proposals;\n\n  // Get all blobs needed for RNN\n  // outputs from feature_net_\n  auto _global_features_blob = feature_net_->blob_by_name(\"global_features\");\n  auto region_features_blob = feature_net_->blob_by_name(\"region_features\");\n  // inputs to rnn_net_\n  auto global_features_blob = rnn_net_->blob_by_name(\"global_features\");\n  auto cont_sentence_blob = rnn_net_->blob_by_name(\"cont_sentence\");\n  // outputs from rnn_net_\n  auto word_probs_blob = rnn_net_->blob_by_name(\"probs\");\n  auto bbox_pred_blob = rnn_net_->blob_by_name(\"bbox_pred\");\n  // input to embed_net_\n  auto input_sentence_blob = embed_net_->input_blobs()[0];\n  // output from embed_net_\n  auto embedded_sentence_blob = embed_net_->blob_by_name(\"embedded_sentence\");\n  int nfeat = _global_features_blob->shape(2);\n  int nwords = word_probs_blob->shape(2);\n  \n  // prepare inputs to rnn_net_\n  global_features_blob->Reshape({global_features_blob->shape(0),\n          total_proposals, global_features_blob->shape(2)});\n  int offset = 0;\n  // broadcase global features to same dimension as region features\n  for (int i = 0; i < batch; ++i) {\n    caffe::caffe_gpu_gemm(\n        CblasNoTrans, CblasNoTrans, num_proposals[i], nfeat, 1,\n        (float)1., multiplier_->gpu_data(), _global_features_blob->gpu_data(),\n        (float)0., global_features_blob->mutable_gpu_data() + offset);\n    offset += int(num_proposals[i]) * nfeat;\n  }\n  rnn_net_->set_blob(\"input_features\", region_features_blob);\n  cont_sentence_blob->Reshape({1, total_proposals});\n  // init cont_sentence with 0 first\n  caffe::caffe_gpu_set(total_proposals, (float) 0.,\n                       cont_sentence_blob->mutable_gpu_data());\n  \n  // pass the image features throught rnn_net_ first\n  rnn_net_->Forward();\n  \n  // Prepare the inputs to embed_net_ and rnn_net_\n  // reset cont_sentence to 1\n  caffe::caffe_gpu_set(total_proposals, (float) 1.,\n                       cont_sentence_blob->mutable_gpu_data());\n  input_sentence_blob->Reshape({1, total_proposals});\n  // start with EOS for all sentences\n  caffe::caffe_gpu_set(total_proposals, (float) 0.,\n                       input_sentence_blob->mutable_gpu_data());\n  // hook the output of embed_net_ to rnn_net_\n  rnn_net_->set_blob(\"input_features\", embedded_sentence_blob);\n  rnn_net_->set_blob(\"global_features\", embedded_sentence_blob);\n  \n  // Get the output buffers\n  float* bbox_offsets = bbox_offsets_arr->Data<float>();\n  // TODO: current assume captions array allocated in CPU only\n  float* captions = captions_arr->Data<float>();\n\n  // forward rnn_net_\n  for (int step = 0; step < max_timestep_; ++step) {\n    embed_net_->Forward();\n    rnn_net_->Forward();\n    const float* word_prob = word_probs_blob->cpu_data();\n    int finished = 0;\n    for (int i = 0; i < total_proposals; ++i) {\n      int max_idx = -1;\n      float max_prob = 0.;\n      for (int j = 0; j < nwords; ++j) {\n        if (word_prob[j] > max_prob) {\n          max_prob = word_prob[j];\n          max_idx = j;\n        }\n      }\n      // LOG(INFO) << \"proposal \" << i << \": \" << max_idx << \" \" << max_prob;\n      if (step == 0 || captions[i * max_timestep_ + step - 1] != 0) {\n        if (max_idx == 0) {\n          ++finished;\n        }\n        best_words_[i] = max_idx;\n        captions[i * max_timestep_ + step] = max_idx;\n        Memcpy(bbox_offsets + i * 4, bbox_offsets_arr->device(),\n               bbox_pred_blob->gpu_data() + i * 4, gpu_device_,\n               4 * sizeof(float));\n      } else {\n        ++finished;\n        best_words_[i] = 0.;\n        captions[i * max_timestep_ + step] = 0;\n      }\n      word_prob += nwords;\n    }\n    if (finished == total_proposals) {\n      break;\n    }\n    // copy the best words to input_sentence gpu data\n    Memcpy(input_sentence_blob->mutable_gpu_data(), gpu_device_,\n           best_words_.data(), cpu_device_, total_proposals * sizeof(float));\n  }\n\n  auto t3 = std::chrono::high_resolution_clock::now();\n  auto feature_lat = std::chrono::duration_cast<std::chrono::milliseconds>(\n      t2 - t1);\n  auto caption_lat = std::chrono::duration_cast<std::chrono::milliseconds>(\n      t3 - t2);\n  LOG(INFO) << \"feature latency: \" << feature_lat.count() << \" ms, caption \" <<\n      \" latency: \" << caption_lat.count() << \" ms\";\n\n  // Slice output\n  std::unordered_map<std::string, Slice> slices{\n    {\"rois\", Slice(batch, num_proposals, 5)},\n    {\"bbox_offsets\", Slice(batch, num_proposals, 4)},\n    {\"captions\", Slice(batch, num_proposals, max_timestep_)},\n    {\"scores\", Slice(batch, num_proposals, 2)},\n  };\n  batch_task->SliceOutputBatch(slices);\n  delete[] num_proposals;\n}\n\nvoid CaffeDenseCapModel::Postprocess(std::shared_ptr<Task> task) {\n  const QueryProto& query = task->query;\n  QueryResultProto* result = &task->result;\n  std::vector<std::string> output_fields(query.output_field().begin(),\n                                         query.output_field().end());\n  if (output_fields.size() == 0) {\n    output_fields.push_back(\"rect\");\n    output_fields.push_back(\"caption\");\n  }\n  \n  auto& output = task->outputs[0];\n  int nboxes = output->arrays.at(\"rois\")->num_elements() / 5;\n  float* rois = output->arrays.at(\"rois\")->Data<float>();\n  float* boxes = rois;\n  float* bbox_offsets = output->arrays.at(\"bbox_offsets\")->Data<float>();\n  float* captions = output->arrays.at(\"captions\")->Data<float>();\n  float* scores = output->arrays.at(\"scores\")->Data<float>();\n  // get attributes\n  int im_height = task->attrs[\"im_height\"].as<int>();\n  int im_width = task->attrs[\"im_width\"].as<int>();\n  float scale = task->attrs[\"scale_h\"].as<float>();\n  int* order = new int[nboxes];\n  for (int i = 0; i < nboxes; ++i) {\n    order[i] = i;\n    // transform bbox offsets\n    for (int j = 0; j < 4; ++j) {\n      bbox_offsets[i * 4 + j] = bbox_offsets[i * 4 + j] * bbox_stds_[j] +\n                                bbox_mean_[j];\n    }\n  }\n  TransformBbox(im_height, im_width, scale, nboxes, rois, bbox_offsets, boxes);\n  std::sort(order, order + nboxes, [&](int a, int b) {\n      return scores[b * 2 + 1] < scores[a * 2 + 1];\n    });\n  int num_out;\n  int* keep_out = new int[nboxes];\n  caffe::nms_cpu(boxes, order, nboxes, nms_threshold_, keep_out, &num_out);\n\n  int total_boxes = 0;\n  for (int i = 0; i < num_out; ++i) {\n    int idx = keep_out[i];\n    if (scores[idx * 2 + 1] <= score_threshold_) {\n      continue;\n    }\n    std::string sentence;\n    for (int step = 0; step < max_timestep_; ++step) {\n      int word = (int) captions[idx * max_timestep_ + step];\n      if (word == 0) {\n        break;\n      }\n      sentence += vocabulary_[word] + \" \";\n    }\n    float* box = boxes + idx * 4;\n    // Add caption result\n    auto record = result->add_output();\n    for (auto field : output_fields) {\n      if (field == \"rect\") {\n        auto value = record->add_named_value();\n        value->set_name(\"rect\");\n        value->set_data_type(DT_RECT);\n        auto rect = value->mutable_rect();\n        rect->set_left(int(round(box[0])));\n        rect->set_top(int(round(box[1])));\n        rect->set_right(int(round(box[2])));\n        rect->set_bottom(int(round(box[3])));\n      } else if (field == \"caption\") {\n        auto value = record->add_named_value();\n        value->set_name(\"caption\");\n        value->set_data_type(DT_STRING);\n        value->set_s(sentence);\n      } else if (field == \"score\") {\n        auto value = record->add_named_value();\n        value->set_name(\"score\");\n        value->set_data_type(DT_FLOAT);\n        value->set_f(scores[idx * 2 + 1]);\n      }\n    }\n    ++total_boxes;\n  }\n  //LOG(INFO) << \"total boxes: \" << total_boxes;\n  delete[] order;\n  delete[] keep_out;\n}\n\nvoid CaffeDenseCapModel::LoadVocabulary(const std::string& filename) {\n  std::ifstream fin(filename);\n  vocabulary_.push_back(\"<EOS>\");\n  std::string line;\n  while (std::getline(fin, line)) {\n    vocabulary_.push_back(line);\n  }\n  fin.close();\n  LOG(INFO) << \"Load \" << vocabulary_.size() << \" vocabs from \" << filename;\n}\n\nvoid CaffeDenseCapModel::TransformBbox(\n    int im_height, int im_width, float scale, int nboxes, const float* rois,\n    const float* bbox_deltas, float* out) {\n  for (int i = 0; i < nboxes; ++i) {\n    float x1 = rois[i * 5 + 1] / scale;\n    float y1 = rois[i * 5 + 2] / scale;\n    float x2 = rois[i * 5 + 3] / scale;\n    float y2 = rois[i * 5 + 4] / scale;\n    float width = x2 - x1 + 1;\n    float height = y2 - y1 + 1;\n    float ctr_x = x1 + 0.5 * width;\n    float ctr_y = y1 + 0.5 * height;\n    float dx = bbox_deltas[i * 4];\n    float dy = bbox_deltas[i * 4 + 1];\n    float dw = bbox_deltas[i * 4 + 2];\n    float dh = bbox_deltas[i * 4 + 3];\n    ctr_x += dx * width;\n    ctr_y += dy * height;\n    width *= exp(dw);\n    height *= exp(dh);\n    out[i * 4] = std::max(std::min(ctr_x - 0.5 * width, im_width - 1.), 0.);\n    out[i * 4 + 1] = std::max(std::min(ctr_y - 0.5 * height, im_height - 1.),\n                              0.);\n    out[i * 4 + 2] = std::max(std::min(ctr_x + 0.5 * width, im_width - 1.), 0.);\n    out[i * 4 + 3] = std::max(std::min(ctr_y + 0.5 * height, im_height - 1.),\n                              0.);\n  }\n}\n\n} // namespace backend\n} // namespace nexus\n\n#endif // USE_CAFFE\n", "meta": {"hexsha": "7026ff6787bc571cd6a4c5a148c97dd5d2fa1d26", "size": 18941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nexus/backend/caffe_densecap_model.cpp", "max_stars_repo_name": "levulinh/NCL-nexus", "max_stars_repo_head_hexsha": "bffb80c00cd57a66ce4bbb47d7b60cce1d49fdb4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2018-09-27T23:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T03:55:38.000Z", "max_issues_repo_path": "src/nexus/backend/caffe_densecap_model.cpp", "max_issues_repo_name": "levulinh/NCL-nexus", "max_issues_repo_head_hexsha": "bffb80c00cd57a66ce4bbb47d7b60cce1d49fdb4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-02-10T21:33:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T04:25:45.000Z", "max_forks_repo_path": "src/nexus/backend/caffe_densecap_model.cpp", "max_forks_repo_name": "levulinh/NCL-nexus", "max_forks_repo_head_hexsha": "bffb80c00cd57a66ce4bbb47d7b60cce1d49fdb4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T21:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T03:55:24.000Z", "avg_line_length": 39.5427974948, "max_line_length": 84, "alphanum_fraction": 0.6520775038, "num_tokens": 5222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.18160225668302213}}
{"text": "#include \"validation.h\"\n#include \"lelantus.h\"\n#include \"timedata.h\"\n#include \"chainparams.h\"\n#include \"util.h\"\n#include \"base58.h\"\n#include \"definition.h\"\n#include \"txmempool.h\"\n#include \"wallet/wallet.h\"\n#include \"wallet/walletdb.h\"\n#include \"crypto/sha256.h\"\n#include \"liblelantus/coin.h\"\n#include \"liblelantus/schnorr_prover.h\"\n#include \"liblelantus/schnorr_verifier.h\"\n#include \"primitives/mint_spend.h\"\n#include \"liblelantus/challenge_generator_impl.h\"\n#include \"policy/policy.h\"\n#include \"coins.h\"\n#include \"batchproof_container.h\"\n\n#include <atomic>\n#include <sstream>\n#include <chrono>\n\n#include <boost/foreach.hpp>\n#include <boost/scope_exit.hpp>\n\n#include <ios>\n\nnamespace lelantus {\n\nstatic CLelantusState lelantusState;\n\nstatic bool CheckLelantusSpendSerial(\n        CValidationState &state,\n        CLelantusTxInfo *lelantusTxInfo,\n        const Scalar &serial,\n        int nHeight,\n        bool fConnectTip) {\n    // check for Lelantus transaction in this block as well\n    if (lelantusTxInfo &&\n            !lelantusTxInfo->fInfoIsComplete &&\n            lelantusTxInfo->spentSerials.find(serial) != lelantusTxInfo->spentSerials.end())\n        return state.DoS(0, error(\"CTransaction::CheckTransaction() : two or more joinsplits with same serial in the same block\"));\n\n    // check for used serials in lelantusState\n    if (lelantusState.IsUsedCoinSerial(serial)) {\n        // Proceed with checks ONLY if we're accepting tx into the memory pool or connecting block to the existing blockchain\n        if (nHeight == INT_MAX || fConnectTip) {\n            return state.DoS(0, error(\"CTransaction::CheckTransaction() : The lelantus JoinSplit serial has been used\"));\n        }\n    }\n    return true;\n}\n\n\nstd::vector<unsigned char> GetAnonymitySetHash(CBlockIndex *index, int group_id, bool generation = false) {\n    std::vector<unsigned char> out_hash;\n\n    CLelantusState::LelantusCoinGroupInfo coinGroup;\n    if (!lelantusState.GetCoinGroupInfo(group_id, coinGroup))\n        return out_hash;\n\n    if ((coinGroup.firstBlock == coinGroup.lastBlock && generation) || (coinGroup.nCoins == 0))\n        return out_hash;\n\n    while (index != coinGroup.firstBlock) {\n        if (index->anonymitySetHash.count(group_id) > 0) {\n            out_hash = index->anonymitySetHash[group_id];\n            break;\n        }\n        index = index->pprev;\n    }\n    return out_hash;\n}\n\nbool IsLelantusAllowed()\n{\n    LOCK(cs_main);\n    return IsLelantusAllowed(chainActive.Height());\n}\n\nbool IsLelantusAllowed(int height)\n{\n\treturn height >= ::Params().GetConsensus().nLelantusStartBlock;\n}\n\nbool IsAvailableToMint(const CAmount& amount)\n{\n    return amount <= ::Params().GetConsensus().nMaxValueLelantusMint;\n}\n\nvoid GenerateMintSchnorrProof(const lelantus::PrivateCoin& coin, CDataStream&  serializedSchnorrProof)\n{\n    auto params = lelantus::Params::get_default();\n\n    LOCK(cs_main);\n    SchnorrProof schnorrProof;\n\n    // after nLelantusFixesStartBlock block start to pass whole data to transcript\n    bool afterFixes = chainActive.Height() >= ::Params().GetConsensus().nLelantusFixesStartBlock;\n    SchnorrProver schnorrProver(params->get_g(), params->get_h0(), afterFixes);\n    Scalar v = coin.getVScalar();\n    secp_primitives::GroupElement commit = coin.getPublicCoin().getValue();\n    secp_primitives::GroupElement comm = commit + (params->get_h1() * v.negate());\n\n    std::unique_ptr<ChallengeGenerator> challengeGenerator;\n    if (afterFixes) {\n        // start to use CHash256 which is more secure\n        challengeGenerator = std::make_unique<ChallengeGeneratorImpl<CHash256>>(1);\n    }  else {\n        challengeGenerator = std::make_unique<ChallengeGeneratorImpl<CSHA256>>(0);\n    }\n\n    // commit (G^s*H1^v*H2^r), comm (G^s*H2^r), and H1^v are used in challenge generation if nLelantusFixesStartBlock is passed\n    schnorrProver.proof(coin.getSerialNumber(), coin.getRandomness(), comm, commit, (params->get_h1() * v), challengeGenerator, schnorrProof);\n\n    serializedSchnorrProof << schnorrProof;\n}\n\nbool VerifyMintSchnorrProof(const uint64_t& v, const secp_primitives::GroupElement& commit, const SchnorrProof& schnorrProof)\n{\n    auto params = lelantus::Params::get_default();\n\n    LOCK(cs_main);\n    // after nLelantusFixesStartBlock block start to pass whole data to transcript\n    bool afterFixes = chainActive.Height() >= ::Params().GetConsensus().nLelantusFixesStartBlock;\n    secp_primitives::GroupElement comm = commit + (params->get_h1() * Scalar(v).negate());\n    SchnorrVerifier verifier(params->get_g(), params->get_h0(), afterFixes);\n    std::unique_ptr<ChallengeGenerator> challengeGenerator;\n    if (afterFixes) {\n        // start to use CHash256 which is more secure\n        challengeGenerator = std::make_unique<ChallengeGeneratorImpl<CHash256>>(1);\n    }  else {\n        challengeGenerator = std::make_unique<ChallengeGeneratorImpl<CSHA256>>(0);\n    }\n\n    // commit (G^s*H1^v*H2^r), comm (G^s*H2^r), and H1^v are used in challenge generation if nLelantusFixesStartBlock is passed\n    return verifier.verify(comm, commit, (params->get_h1() * Scalar(v)), schnorrProof, challengeGenerator);\n}\n\nvoid ParseLelantusMintScript(const CScript& script, secp_primitives::GroupElement& pubcoin,  SchnorrProof& schnorrProof, uint256& mintTag)\n{\n    if (script.size() < 1) {\n        throw std::invalid_argument(\"Script is not a valid Lelantus mint\");\n    }\n\n    std::vector<unsigned char> serialized(script.begin() + 1, script.end());\n    if (serialized.size() < (pubcoin.memoryRequired() + schnorrProof.memoryRequired())) {\n        throw std::invalid_argument(\"Script is not a valid Lelantus mint\");\n    }\n\n    bool skipTag = serialized.size() == (pubcoin.memoryRequired() + schnorrProof.memoryRequired());\n\n    pubcoin.deserialize(serialized.data());\n\n    CDataStream stream(\n            std::vector<unsigned char>(serialized.begin() + pubcoin.memoryRequired(), serialized.end()),\n            SER_NETWORK,\n            PROTOCOL_VERSION\n    );\n\n    stream >> schnorrProof;\n    if(!skipTag)\n        stream >> mintTag;\n}\n\nvoid ParseLelantusJMintScript(const CScript& script, secp_primitives::GroupElement& pubcoin, std::vector<unsigned char>& encryptedValue)\n{\n    uint256 mintTag;\n    ParseLelantusJMintScript(script, pubcoin, encryptedValue, mintTag);\n}\n\nvoid ParseLelantusJMintScript(const CScript& script, secp_primitives::GroupElement& pubcoin, std::vector<unsigned char>& encryptedValue, uint256& mintTag)\n{\n    if (script.size() < 1) {\n        throw std::invalid_argument(\"Script is not a valid Lelantus jMint\");\n    }\n\n    std::vector<unsigned char> serialized(script.begin() + 1, script.end());\n    // 16 is the size of encrypted mint value, 32 is size of mintTag\n    if (serialized.size() < (pubcoin.memoryRequired() + 16)) {\n        throw std::invalid_argument(\"Script is not a valid Lelantus jMint\");\n    }\n\n    bool skipTag = serialized.size() == (pubcoin.memoryRequired() + 16);\n\n    pubcoin.deserialize(serialized.data());\n    encryptedValue.insert(encryptedValue.begin(), serialized.begin() + pubcoin.memoryRequired(), serialized.end());\n    CDataStream stream(\n            std::vector<unsigned char>(serialized.begin() + pubcoin.memoryRequired() + 16, serialized.end()),\n            SER_NETWORK,\n            PROTOCOL_VERSION\n    );\n    if(!skipTag)\n        stream >> mintTag;\n}\n\n\nvoid ParseLelantusMintScript(const CScript& script, secp_primitives::GroupElement& pubcoin)\n{\n    uint256 mintTag;\n    if(script.IsLelantusMint()) {\n        SchnorrProof schnorrProof;\n        ParseLelantusMintScript(script, pubcoin, schnorrProof, mintTag);\n    } else if (script.IsLelantusJMint()) {\n        std::vector<unsigned char> encryptedValue;\n        ParseLelantusJMintScript(script, pubcoin, encryptedValue, mintTag);\n    }\n}\n\nstd::unique_ptr<JoinSplit> ParseLelantusJoinSplit(const CTransaction &tx)\n{\n    if (tx.vin.size() != 1 || tx.vin[0].scriptSig.size() < 1) {\n        throw CBadTxIn();\n    }\n\n    CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION);\n\n    if (tx.vin[0].scriptSig[0] == OP_LELANTUSJOINSPLIT) {\n        serialized.write((const char *)tx.vin[0].scriptSig.data()+1, tx.vin[0].scriptSig.size()-1);\n    }\n    else if (tx.vin[0].scriptSig[0] == OP_LELANTUSJOINSPLITPAYLOAD && tx.nVersion >= 3 && tx.nType == TRANSACTION_LELANTUS) {\n        serialized.write((const char *)tx.vExtraPayload.data(), tx.vExtraPayload.size());\n    }\n    else\n        throw CBadTxIn();\n\n    return std::make_unique<lelantus::JoinSplit>(lelantus::Params::get_default(), serialized);\n}\n\nbool CheckLelantusBlock(CValidationState &state, const CBlock& block) {\n    auto& consensus = ::Params().GetConsensus();\n\n    size_t blockSpendsAmount = 0;\n    CAmount blockSpendsValue(0);\n\n    for (const auto& tx : block.vtx) {\n        auto txSpendsValue =  GetSpendTransparentAmount(*tx);\n        size_t txSpendNumber = GetSpendInputs(*tx);\n\n        if (txSpendNumber > consensus.nMaxLelantusInputPerTransaction) {\n            return state.DoS(100, false, REJECT_INVALID,\n                \"bad-txns-lelantus-spend-invalid\");\n        }\n\n        if (txSpendsValue > consensus.nMaxValueLelantusSpendPerTransaction) {\n            return state.DoS(100, false, REJECT_INVALID,\n                             \"bad-txns-lelantus-spend-invalid\");\n        }\n\n        blockSpendsAmount += txSpendNumber;\n        blockSpendsValue += txSpendsValue;\n    }\n\n    if (blockSpendsAmount > consensus.nMaxLelantusInputPerBlock) {\n        return state.DoS(100, false, REJECT_INVALID,\n            \"bad-txns-lelantus-spend-invalid\");\n    }\n\n    if (blockSpendsValue > consensus.nMaxValueLelantusSpendPerBlock) {\n        return state.DoS(100, false, REJECT_INVALID,\n                         \"bad-txns-lelantus-spend-invalid\");\n    }\n\n    return true;\n}\n\nbool CheckLelantusJMintTransaction(\n        const CTxOut &txout,\n        CValidationState &state,\n        uint256 hashTx,\n        bool fStatefulSigmaCheck,\n        std::vector<PublicCoin>& Cout,\n        CLelantusTxInfo* lelantusTxInfo) {\n\n    LogPrintf(\"CheckLelantusJMintTransaction txHash = %s\\n\", txout.GetHash().ToString());\n\n    secp_primitives::GroupElement pubCoinValue;\n    uint256 mintTag;\n    std::vector<unsigned char> encryptedValue;\n    try {\n        ParseLelantusJMintScript(txout.scriptPubKey, pubCoinValue, encryptedValue, mintTag);\n    } catch (std::invalid_argument&) {\n        return state.DoS(100,\n            false,\n            PUBCOIN_NOT_VALIDATE,\n            \"CTransaction::CheckTransaction() : Mint parsing failure.\");\n    }\n\n    lelantus::PublicCoin pubCoin(pubCoinValue);\n\n    //checking whether commitment is valid\n    if(!pubCoin.validate())\n        return state.DoS(100,\n                         false,\n                         PUBCOIN_NOT_VALIDATE,\n                         \"CheckLelantusMintTransaction : PubCoin validation failed\");\n\n    bool hasCoin = lelantusState.HasCoin(pubCoin);\n\n    if (!hasCoin && lelantusTxInfo && !lelantusTxInfo->fInfoIsComplete) {\n        BOOST_FOREACH(const auto& mint, lelantusTxInfo->mints) {\n            if (mint.first == pubCoin) {\n                hasCoin = true;\n                break;\n            }\n        }\n    }\n\n    if (hasCoin && fStatefulSigmaCheck) {\n       LogPrintf(\"CheckLelantusMintTransaction: double mint, tx=%s\\n\",\n                txout.GetHash().ToString());\n        return state.DoS(100,\n                false,\n                PUBCOIN_NOT_VALIDATE,\n                \"CheckLelantusMintTransaction: double mint\");\n    }\n\n    uint64_t amount = 0;\n#ifdef ENABLE_WALLET\n    if (!GetBoolArg(\"-disablewallet\", false)) {\n        if (!pwalletMain->DecryptMintAmount(encryptedValue, pubCoinValue, amount))\n            amount = 0;\n    }\n#endif\n    if (lelantusTxInfo != NULL && !lelantusTxInfo->fInfoIsComplete) {\n\n        // Update public coin list in the info\n        lelantusTxInfo->mints.push_back(std::make_pair(pubCoin, std::make_pair(amount, mintTag)));\n        lelantusTxInfo->zcTransactions.insert(hashTx);\n    }\n\n    Cout.push_back(pubCoin);\n\n    return true;\n}\n\nbool CheckLelantusJoinSplitTransaction(\n        const CTransaction &tx,\n        CValidationState &state,\n        uint256 hashTx,\n        bool isVerifyDB,\n        int nHeight,\n        int realHeight,\n        bool isCheckWallet,\n        bool fStatefulSigmaCheck,\n        sigma::CSigmaTxInfo* sigmaTxInfo,\n        CLelantusTxInfo* lelantusTxInfo) {\n    std::unordered_set<Scalar, sigma::CScalarHash> txSerials;\n\n    Consensus::Params const & params = ::Params().GetConsensus();\n\n    if(tx.vin.size() != 1 || !tx.vin[0].scriptSig.IsLelantusJoinSplit()) {\n        // mixing lelantus spend input with non-lelantus inputs is prohibited\n        return state.DoS(100, false,\n                         REJECT_MALFORMED,\n                         \"CheckLelantusJoinSplitTransaction: can't mix lelantus spend input with other tx types or have more than one spend\");\n    }\n\n    int height = nHeight == INT_MAX ? chainActive.Height()+1 : nHeight;\n    if (!isVerifyDB) {\n        if (height >= params.nLelantusV3PayloadStartBlock) {\n            // data should be moved to v3 payload\n            if (tx.nVersion < 3 || tx.nType != TRANSACTION_LELANTUS)\n                return state.DoS(100, false, NSEQUENCE_INCORRECT,\n                        \"CheckLelantusJoinSplitTransaction: lelantus data should reside in transaction payload\");\n        }\n        else {\n            if (tx.nVersion >= 3 && tx.nType != TRANSACTION_NORMAL)\n                return state.DoS(100, false, NSEQUENCE_INCORRECT,\n                        \"CheckLelantusJoinSplitTransaction: network hasn't yet switched over to lelantus payload data\");\n        }\n    }\n    const CTxIn &txin = tx.vin[0];\n    std::unique_ptr<lelantus::JoinSplit> joinsplit;\n\n    try {\n        joinsplit = ParseLelantusJoinSplit(tx);\n    }\n    catch (CBadTxIn&) {\n        return state.DoS(100,\n            false,\n            REJECT_MALFORMED,\n            \"CheckLelantusJoinSplitTransaction: invalid joinsplit transaction\");\n    }\n\n    int jSplitVersion = joinsplit->getVersion();\n\n    if (jSplitVersion < LELANTUS_TX_VERSION_4 ||\n        (!isVerifyDB &&\n        ((height >= params.nLelantusFixesStartBlock && height < params.nLelantusV3PayloadStartBlock && jSplitVersion != LELANTUS_TX_VERSION_4_5 && jSplitVersion != SIGMA_TO_LELANTUS_JOINSPLIT_FIXED) ||\n        (height >= params.nLelantusV3PayloadStartBlock && jSplitVersion != LELANTUS_TX_TPAYLOAD && jSplitVersion != SIGMA_TO_LELANTUS_TX_TPAYLOAD)))) {\n        return state.DoS(100,\n                         false,\n                         NSEQUENCE_INCORRECT,\n                         \"CTransaction::CheckLelantusJoinSplitTransaction() : Error: incorrect joinsplit transaction verion\");\n    }\n\n    uint256 txHashForMetadata;\n\n    // Obtain the hash of the transaction sans the zerocoin part\n    CMutableTransaction txTemp = tx;\n    txTemp.vin[0].scriptSig.clear();\n    txTemp.vExtraPayload.clear();\n\n    txHashForMetadata = txTemp.GetHash();\n\n    LogPrintf(\"CheckLelantusJoinSplitTransaction: tx version=%d, tx metadata hash=%s\\n\",\n              jSplitVersion, txHashForMetadata.ToString());\n\n    if (!fStatefulSigmaCheck) {\n        return true;\n    }\n\n    bool passVerify = false;\n    std::map<uint32_t, std::vector<PublicCoin>> anonymity_sets;\n    std::vector<PublicCoin> Cout;\n    uint64_t Vout = 0;\n\n    for (const CTxOut &txout : tx.vout) {\n        if (!txout.scriptPubKey.empty() && txout.scriptPubKey.IsLelantusJMint()) {\n            if (!CheckLelantusJMintTransaction(txout, state, hashTx, fStatefulSigmaCheck, Cout, lelantusTxInfo))\n                return false;\n        } else if(txout.scriptPubKey.IsLelantusMint()) {\n            return false; //putting regular mints at JoinSplit transactions is not allowed\n        } else {\n            Vout += txout.nValue;\n        }\n    }\n\n    std::vector<std::vector<unsigned char>> anonymity_set_hashes;\n\n    for (auto& idAndHash : joinsplit->getIdAndBlockHashes()) {\n        auto& anonymity_set = anonymity_sets[idAndHash.first];\n        int coinGroupId = idAndHash.first % (CENT / 1000);\n        int64_t intDenom = (idAndHash.first - coinGroupId);\n        intDenom *= 1000;\n\n        sigma::CoinDenomination denomination;\n        if (joinsplit->isSigmaToLelantus() && sigma::IntegerToDenomination(intDenom, denomination)) {\n\n            sigma::CSigmaState::SigmaCoinGroupInfo coinGroup;\n            sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState();\n            if (!sigmaState->GetCoinGroupInfo(denomination, coinGroupId, coinGroup))\n                return state.DoS(100, false, NO_MINT_ZEROCOIN,\n                                 \"CheckSigmaSpendTransaction: Error: no coins were minted with such parameters\");\n\n            CBlockIndex *index = coinGroup.lastBlock;\n\n            // find index for block with hash of accumulatorBlockHash or set index to the coinGroup.firstBlock if not found\n            while (index != coinGroup.firstBlock && index->GetBlockHash() != idAndHash.second)\n                index = index->pprev;\n\n            std::pair<sigma::CoinDenomination, int> denominationAndId = std::make_pair(denomination, coinGroupId);\n\n            auto lelantusParams = lelantus::Params::get_default();\n            while (true) {\n                if (index->sigmaMintedPubCoins.count(denominationAndId) > 0) {\n                    BOOST_FOREACH(\n                    const sigma::PublicCoin &pubCoinValue,\n                    index->sigmaMintedPubCoins[denominationAndId]) {\n                        if (::Params().GetConsensus().sigmaBlacklist.count(pubCoinValue.getValue()) > 0) {\n                            continue;\n                        }\n                        lelantus::PublicCoin publicCoin(pubCoinValue.getValue() + lelantusParams->get_h1() * intDenom);\n                        anonymity_set.push_back(publicCoin);\n                    }\n                }\n                if (index == coinGroup.firstBlock)\n                    break;\n                index = index->pprev;\n            }\n        } else {\n            CLelantusState::LelantusCoinGroupInfo coinGroup;\n            if (!lelantusState.GetCoinGroupInfo(idAndHash.first, coinGroup))\n                return state.DoS(100, false, NO_MINT_ZEROCOIN,\n                                 \"CheckLelantusJoinSplitTransaction: Error: no coins were minted with such parameters\");\n\n            CBlockIndex *index = coinGroup.lastBlock;\n\n\n            // find index for block with hash of accumulatorBlockHash or set index to the coinGroup.firstBlock if not found\n            while (index != coinGroup.firstBlock && index->GetBlockHash() != idAndHash.second)\n                index = index->pprev;\n\n            // take the hash from last block of anonymity set, it is used at challenge generation if nLelantusFixesStartBlock is passed\n            if (nHeight >= params.nLelantusFixesStartBlock) {\n                std::vector<unsigned char> set_hash = GetAnonymitySetHash(index, idAndHash.first);\n                if (!set_hash.empty())\n                    anonymity_set_hashes.push_back(set_hash);\n            }\n            // Build a vector with all the public coins with given id before\n            // the block on which the spend occured.\n            // This list of public coins is required by function \"Verify\" of JoinSplit.\n\n            while (true) {\n                if(index->lelantusMintedPubCoins.count(idAndHash.first) > 0) {\n                    BOOST_FOREACH(\n                    const auto& pubCoinValue,\n                    index->lelantusMintedPubCoins[idAndHash.first]) {\n                        // skip mints from blacklist if nLelantusFixesStartBlock is passed\n                        if (chainActive.Height() >= ::Params().GetConsensus().nLelantusFixesStartBlock) {\n                            if (::Params().GetConsensus().lelantusBlacklist.count(pubCoinValue.first.getValue()) > 0) {\n                                continue;\n                            }\n                        }\n                        anonymity_set.push_back(pubCoinValue.first);\n                    }\n                }\n                if (index == coinGroup.firstBlock)\n                    break;\n                index = index->pprev;\n            }\n        }\n        anonymity_sets[idAndHash.first] = anonymity_set;\n    }\n\n    BatchProofContainer* batchProofContainer = BatchProofContainer::get_instance();\n    bool useBatching = batchProofContainer->fCollectProofs && !isVerifyDB && !isCheckWallet && lelantusTxInfo && !lelantusTxInfo->fInfoIsComplete;\n\n    Scalar challenge;\n    // if we are collecting proofs, skip verification and collect proofs\n    passVerify = joinsplit->Verify(anonymity_sets, anonymity_set_hashes, Cout, Vout, txHashForMetadata, challenge, useBatching);\n\n    // add proofs into container\n    if(useBatching) {\n        std::map<uint32_t, size_t> idAndSizes;\n\n        for(auto itr : anonymity_sets)\n            idAndSizes[itr.first] = itr.second.size();\n\n        batchProofContainer->add(joinsplit.get(), idAndSizes, challenge, nHeight >= params.nLelantusFixesStartBlock);\n    }\n\n    if (passVerify) {\n        const std::vector<Scalar>& serials = joinsplit->getCoinSerialNumbers();\n        const std::vector<uint32_t> &ids = joinsplit->getCoinGroupIds();\n\n        if (serials.size() != ids.size()) {\n            return state.DoS(100,\n                             error(\"CheckLelantusJoinSplitTransaction: sized of serials and group ids don't match.\"));\n        }\n\n        // do not check for duplicates in case we've seen exact copy of this tx in this block before\n        if (!(sigmaTxInfo && sigmaTxInfo->zcTransactions.count(hashTx) > 0) && !(lelantusTxInfo && lelantusTxInfo->zcTransactions.count(hashTx) > 0)) {\n            for (size_t i = 0; i < serials.size(); ++i) {\n                int coinGroupId = ids[i] % (CENT / 1000);\n                int64_t intDenom = (ids[i] - coinGroupId);\n                intDenom *= 1000;\n                sigma::CoinDenomination denomination;\n\n                if (realHeight < params.nLelantusV3PayloadStartBlock || (joinsplit->isSigmaToLelantus() && sigma::IntegerToDenomination(intDenom, denomination))) {\n                    if (!sigma::CheckSigmaSpendSerial(\n                            state, sigmaTxInfo, serials[i], nHeight, false)) {\n                        LogPrintf(\"CheckSigmaSpendTransaction: serial check failed, serial=%s\\n\", serials[i]);\n                        return false;\n                    } else if (!CheckLelantusSpendSerial(\n                            state, lelantusTxInfo, serials[i], nHeight, false)) {\n                        LogPrintf(\"CheckLelantusJoinSplitTransaction: serial check failed, serial=%s\\n\", serials[i]);\n                        return false;\n\n                    }\n                } else {\n                    if (!CheckLelantusSpendSerial(\n                            state, lelantusTxInfo, serials[i], nHeight, false)) {\n                        LogPrintf(\"CheckLelantusJoinSplitTransaction: serial check failed, serial=%s\\n\", serials[i]);\n                        return false;\n                    }\n                }\n            }\n        }\n\n        // check duplicated serials in same transaction.\n        for (const auto &serial : serials) {\n            if (!txSerials.insert(serial).second) {\n                return state.DoS(100,\n                                 error(\"CheckLelantusJoinSplitTransaction: two or more spends with same serial in the same transaction\"));\n            }\n        }\n\n        if (!isVerifyDB && !isCheckWallet) {\n            // add spend information to the index\n            if (joinsplit->isSigmaToLelantus()) {\n                if (sigmaTxInfo && !sigmaTxInfo->fInfoIsComplete) {\n                    for (size_t i = 0; i < serials.size(); i++) {\n                        int coinGroupId = ids[i] % (CENT / 1000);\n                        int64_t intDenom = (ids[i] - coinGroupId);\n                        intDenom *= 1000;\n                        sigma::CoinDenomination denomination;\n                        if(!sigma::IntegerToDenomination(intDenom, denomination) && lelantusTxInfo && !lelantusTxInfo->fInfoIsComplete)\n                            lelantusTxInfo->spentSerials.insert(std::make_pair(serials[i], ids[i]));\n                        else\n                            sigmaTxInfo->spentSerials.insert(std::make_pair(\n                                    serials[i], sigma::CSpendCoinInfo::make(denomination, coinGroupId)));\n                    }\n                }\n            } else {\n                if (lelantusTxInfo && !lelantusTxInfo->fInfoIsComplete) {\n                    for (size_t i = 0; i < serials.size(); i++) {\n                        lelantusTxInfo->spentSerials.insert(std::make_pair(serials[i], ids[i]));\n                    }\n                }\n            }\n        }\n    }\n    else {\n        LogPrintf(\"CheckLelantusJoinSplitTransaction: verification failed at block %d\\n\", nHeight);\n        return false;\n    }\n\n    if(!isVerifyDB && !isCheckWallet) {\n        if (lelantusTxInfo && !lelantusTxInfo->fInfoIsComplete) {\n            lelantusTxInfo->zcTransactions.insert(hashTx);\n        }\n    }\n\n    return true;\n}\n\nbool CheckLelantusMintTransaction(\n        const CTxOut &txout,\n        CValidationState &state,\n        uint256 hashTx,\n        bool fStatefulSigmaCheck,\n        CLelantusTxInfo* lelantusTxInfo) {\n    secp_primitives::GroupElement pubCoinValue;\n    uint256 mintTag;\n    SchnorrProof schnorrProof;\n\n    LogPrintf(\"CheckLelantusMintTransaction txHash = %s\\n\", txout.GetHash().ToString());\n    LogPrintf(\"nValue = %d\\n\", txout.nValue);\n    if(txout.nValue > ::Params().GetConsensus().nMaxValueLelantusMint)\n        return state.DoS(100,\n                         false,\n                         REJECT_INVALID,\n                         \"CTransaction::CheckTransaction() : Mint is out of limit.\");\n\n    try {\n        ParseLelantusMintScript(txout.scriptPubKey, pubCoinValue, schnorrProof, mintTag);\n    } catch (std::invalid_argument&) {\n        return state.DoS(100,\n            false,\n            PUBCOIN_NOT_VALIDATE,\n            \"CTransaction::CheckTransaction() : Mint parsing failure.\");\n    }\n\n    lelantus::PublicCoin pubCoin(pubCoinValue);\n\n    //checking whether commitment is valid\n    if(!VerifyMintSchnorrProof(txout.nValue, pubCoinValue, schnorrProof) || !pubCoin.validate())\n        return state.DoS(100,\n                         false,\n                         PUBCOIN_NOT_VALIDATE,\n                         \"CheckLelantusMintTransaction : PubCoin validation failed\");\n\n\n    bool hasCoin = lelantusState.HasCoin(pubCoin);\n\n    if (!hasCoin && lelantusTxInfo && !lelantusTxInfo->fInfoIsComplete) {\n        BOOST_FOREACH(const auto& mint, lelantusTxInfo->mints) {\n            if (mint.first == pubCoin) {\n                hasCoin = true;\n                break;\n            }\n        }\n    }\n\n    if (hasCoin && fStatefulSigmaCheck) {\n       LogPrintf(\"CheckLelantusMintTransaction: double mint, tx=%s\\n\",\n                txout.GetHash().ToString());\n        return state.DoS(100,\n                false,\n                PUBCOIN_NOT_VALIDATE,\n                \"CheckLelantusMintTransaction: double mint\");\n    }\n\n    if (lelantusTxInfo != NULL && !lelantusTxInfo->fInfoIsComplete) {\n        // Update public coin list in the info\n        lelantusTxInfo->mints.push_back(std::make_pair(pubCoin, std::make_pair(txout.nValue, mintTag)));\n        lelantusTxInfo->zcTransactions.insert(hashTx);\n    }\n\n    return true;\n}\n\nbool CheckLelantusTransaction(\n        const CTransaction &tx,\n        CValidationState &state,\n        uint256 hashTx,\n        bool isVerifyDB,\n        int nHeight,\n        bool isCheckWallet,\n        bool fStatefulSigmaCheck,\n        sigma::CSigmaTxInfo* sigmaTxInfo,\n        CLelantusTxInfo* lelantusTxInfo)\n{\n    Consensus::Params const & consensus = ::Params().GetConsensus();\n\n\n    if(tx.IsLelantusJoinSplit()) {\n        CAmount nFees;\n        try {\n            nFees = lelantus::ParseLelantusJoinSplit(tx)->getFee();\n        }\n        catch (CBadTxIn&) {\n            return state.DoS(0, false, REJECT_INVALID, \"unable to parse joinsplit\");\n        }\n\n    }\n\n    int realHeight = nHeight;\n\n    if (realHeight == INT_MAX) {\n        LOCK(cs_main);\n        realHeight = chainActive.Height();\n    }\n\n    bool const allowLelantus = (realHeight >= consensus.nLelantusStartBlock);\n\n    if (!isVerifyDB && !isCheckWallet) {\n        if (allowLelantus && lelantusState.IsSurgeConditionDetected()) {\n            return state.DoS(100, false,\n                REJECT_INVALID,\n                \"Lelantus surge protection is ON.\");\n        }\n    }\n\n    // Check Mint Lelantus Transaction\n    if (allowLelantus && !isVerifyDB) {\n        for (const CTxOut &txout : tx.vout) {\n            if (!txout.scriptPubKey.empty() && txout.scriptPubKey.IsLelantusMint()) {\n                if (!CheckLelantusMintTransaction(txout, state, hashTx, fStatefulSigmaCheck, lelantusTxInfo))\n                    return false;\n            }\n        }\n    }\n\n    // Check Lelantus JoinSplit Transaction\n    if(tx.IsLelantusJoinSplit()) {\n        // First check number of inputs does not exceed transaction limit\n        if (GetSpendInputs(tx) > consensus.nMaxLelantusInputPerTransaction) {\n            return state.DoS(100, false,\n                REJECT_INVALID,\n                \"bad-txns-spend-invalid\");\n        }\n\n        if (GetSpendTransparentAmount(tx) > consensus.nMaxValueLelantusSpendPerTransaction) {\n            return state.DoS(100, false,\n                             REJECT_INVALID,\n                             \"bad-txns-spend-invalid\");\n        }\n\n        if (!isVerifyDB) {\n            if (!CheckLelantusJoinSplitTransaction(\n                tx, state, hashTx, isVerifyDB, nHeight, realHeight,\n                isCheckWallet, fStatefulSigmaCheck, sigmaTxInfo, lelantusTxInfo)) {\n                    return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid RemoveLelantusJoinSplitReferencingBlock(CTxMemPool& pool, CBlockIndex* blockIndex) {\n    LOCK2(cs_main, pool.cs);\n    std::vector<CTransaction> txn_to_remove;\n    for (CTxMemPool::txiter mi = pool.mapTx.begin(); mi != pool.mapTx.end(); ++mi) {\n        const CTransaction& tx = mi->GetTx();\n        if (tx.IsLelantusJoinSplit()) {\n            // Run over all the inputs, check if their CoinGroup block hash is equal to\n            // block removed. If any one is equal, remove txn from mempool.\n            for (const CTxIn& txin : tx.vin) {\n                if (txin.IsLelantusJoinSplit()) {\n                    std::unique_ptr<lelantus::JoinSplit> joinsplit;\n\n                    try {\n                        joinsplit = ParseLelantusJoinSplit(tx);\n                    }\n                    catch (const std::ios_base::failure &) {\n                        txn_to_remove.push_back(tx);\n                        break;\n                    }\n\n                    const std::vector<std::pair<uint32_t, uint256>>& coinGroupIdAndBlockHash = joinsplit->getIdAndBlockHashes();\n                    for(const auto& idAndHash : coinGroupIdAndBlockHash) {\n                        if (idAndHash.second == blockIndex->GetBlockHash()) {\n                        // Do not remove transaction immediately, that will invalidate iterator mi.\n                        txn_to_remove.push_back(tx);\n                        break;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    for (const CTransaction& tx: txn_to_remove) {\n        // Remove txn from mempool.\n        pool.removeRecursive(tx);\n        LogPrintf(\"DisconnectTipLelantus: removed lelantus joinsplit which referenced a removed blockchain tip.\");\n    }\n}\n\nvoid DisconnectTipLelantus(CBlock& block, CBlockIndex *pindexDelete) {\n    lelantusState.RemoveBlock(pindexDelete);\n\n    // Also remove from mempool lelantus joinsplits that reference given block hash.\n    RemoveLelantusJoinSplitReferencingBlock(mempool, pindexDelete);\n    RemoveLelantusJoinSplitReferencingBlock(txpools.getStemTxPool(), pindexDelete);\n}\n\nstd::vector<Scalar> GetLelantusJoinSplitSerialNumbers(const CTransaction &tx, const CTxIn &txin) {\n    if (!tx.IsLelantusJoinSplit())\n        return std::vector<Scalar>();\n\n    try {\n        return ParseLelantusJoinSplit(tx)->getCoinSerialNumbers();\n    }\n    catch (const std::ios_base::failure &) {\n        return std::vector<Scalar>();\n    }\n}\n\nstd::vector<uint32_t> GetLelantusJoinSplitIds(const CTransaction &tx, const CTxIn &txin) {\n    if (!tx.IsLelantusJoinSplit())\n        return std::vector<uint32_t>();\n\n    try {\n        return ParseLelantusJoinSplit(tx)->getCoinGroupIds();\n    }\n    catch (const std::ios_base::failure &) {\n        return std::vector<uint32_t>();\n    }\n}\n\nsize_t GetSpendInputs(const CTransaction &tx, const CTxIn& in) {\n    return in.IsLelantusJoinSplit() ?\n        GetLelantusJoinSplitSerialNumbers(tx, in).size() : 0;\n}\n\nsize_t GetSpendInputs(const CTransaction &tx) {\n    size_t sum = 0;\n    for (const auto& vin : tx.vin) {\n        sum += GetSpendInputs(tx, vin);\n    }\n    return sum;\n}\n\nCAmount GetSpendTransparentAmount(const CTransaction& tx) {\n    CAmount result = 0;\n    if(!tx.IsLelantusJoinSplit())\n        return 0;\n\n    for (const CTxOut &txout : tx.vout)\n        result += txout.nValue;\n    return result;\n}\n\n/**\n * Connect a new ZCblock to chainActive. pblock is either NULL or a pointer to a CBlock\n * corresponding to pindexNew, to bypass loading it again from disk.\n */\nbool ConnectBlockLelantus(\n        CValidationState &state,\n        const CChainParams &chainparams,\n        CBlockIndex *pindexNew,\n        const CBlock *pblock,\n        bool fJustCheck) {\n    // Add lelantus transaction information to index\n    if (pblock && pblock->lelantusTxInfo) {\n        if (!fJustCheck) {\n            pindexNew->lelantusMintedPubCoins.clear();\n            pindexNew->lelantusSpentSerials.clear();\n            pindexNew->anonymitySetHash.clear();\n        }\n\n        if (!CheckLelantusBlock(state, *pblock)) {\n            return false;\n        }\n\n        BOOST_FOREACH(auto& serial, pblock->lelantusTxInfo->spentSerials) {\n            if (!CheckLelantusSpendSerial(\n                    state,\n                    pblock->lelantusTxInfo.get(),\n                    serial.first,\n                    pindexNew->nHeight,\n                    true /* fConnectTip */\n                    )) {\n                return false;\n            }\n\n            if (!fJustCheck) {\n                pindexNew->lelantusSpentSerials.insert(serial);\n                lelantusState.AddSpend(serial.first, serial.second);\n            }\n        }\n\n        if (fJustCheck)\n            return true;\n\n        auto& params = ::Params().GetConsensus();\n        CHash256 hash;\n        std::vector<unsigned char> data(GroupElement::serialize_size);\n        bool updateHash = false;\n\n        // create first anonymity set hash with whole existing set, at HF block\n        if (pindexNew->nHeight == params.nLelantusFixesStartBlock) {\n            updateHash = true;\n            std::vector<lelantus::PublicCoin> coins;\n            lelantusState.GetAnonymitySet(1, false, coins);\n            for (auto &coin : coins) {\n                coin.getValue().serialize(data.data());\n                hash.Write(data.data(), data.size());\n            }\n        }\n\n        if (!pblock->lelantusTxInfo->mints.empty()) {\n            lelantusState.AddMintsToStateAndBlockIndex(pindexNew, pblock);\n            int latestCoinId  = lelantusState.GetLatestCoinID();\n            // add  coins into hasher, for generating set hash\n            // if this is HF block just add mint from this block too,\n            // else hasher is supposed to be empty, so add previous hash first, then coins\n            if (pindexNew->nHeight >= params.nLelantusFixesStartBlock) {\n                updateHash = true;\n\n                if (pindexNew->nHeight > params.nLelantusFixesStartBlock) {\n                    // get previous hash of the set, if there is no such, don't write anything\n                    std::vector<unsigned char> prev_hash = GetAnonymitySetHash(pindexNew->pprev, latestCoinId, true);\n                    if (!prev_hash.empty())\n                        hash.Write(prev_hash.data(), 32);\n                }\n\n                for (auto &coin : pindexNew->lelantusMintedPubCoins[latestCoinId]) {\n                    coin.first.getValue().serialize(data.data());\n                    hash.Write(data.data(), data.size());\n                }\n            }\n        }\n\n        // generate hash if we need it\n        if (updateHash) {\n            unsigned char hash_result[CSHA256::OUTPUT_SIZE];\n            hash.Finalize(hash_result);\n            auto &out_hash = pindexNew->anonymitySetHash[lelantusState.GetLatestCoinID()];\n            out_hash.clear();\n            out_hash.insert(out_hash.begin(), std::begin(hash_result), std::end(hash_result));\n        }\n    }\n    else if (!fJustCheck) {\n        lelantusState.AddBlock(pindexNew);\n    }\n    return true;\n}\n\nbool GetOutPointFromBlock(COutPoint& outPoint, const GroupElement &pubCoinValue, const CBlock &block) {\n    secp_primitives::GroupElement txPubCoinValue;\n    // cycle transaction hashes, looking for this pubcoin.\n    BOOST_FOREACH(CTransactionRef tx, block.vtx){\n        uint32_t nIndex = 0;\n        for (const CTxOut &txout: tx->vout) {\n            if (txout.scriptPubKey.IsLelantusMint() || txout.scriptPubKey.IsLelantusJMint()) {\n                ParseLelantusMintScript(txout.scriptPubKey, txPubCoinValue);\n                if(pubCoinValue==txPubCoinValue){\n                    outPoint = COutPoint(tx->GetHash(), nIndex);\n                    return true;\n                }\n            }\n            nIndex++;\n        }\n    }\n\n    return false;\n}\n\nbool GetOutPoint(COutPoint& outPoint, const lelantus::PublicCoin &pubCoin) {\n\n    lelantus::CLelantusState *lelantusState = lelantus::CLelantusState::GetState();\n    auto mintedCoinHeightAndId = lelantusState->GetMintedCoinHeightAndId(pubCoin);\n    int mintHeight = mintedCoinHeightAndId.first;\n    int coinId = mintedCoinHeightAndId.second;\n\n    if(mintHeight==-1 && coinId==-1)\n        return false;\n\n    // get block containing mint\n    CBlockIndex *mintBlock = chainActive[mintHeight];\n    CBlock block;\n    if(!ReadBlockFromDisk(block, mintBlock, ::Params().GetConsensus()))\n        LogPrintf(\"can't read block from disk.\\n\");\n\n    return GetOutPointFromBlock(outPoint, pubCoin.getValue(), block);\n}\n\nbool GetOutPoint(COutPoint& outPoint, const GroupElement &pubCoinValue) {\n    lelantus::PublicCoin pubCoin(pubCoinValue);\n\n    return GetOutPoint(outPoint, pubCoin);\n}\n\nbool GetOutPoint(COutPoint& outPoint, const uint256 &pubCoinValueHash) {\n    GroupElement pubCoinValue;\n    lelantus::CLelantusState *lelantusState = lelantus::CLelantusState::GetState();\n    if(!lelantusState->HasCoinHash(pubCoinValue, pubCoinValueHash)){\n        return false;\n    }\n\n    return GetOutPoint(outPoint, pubCoinValue);\n}\n\nbool GetOutPointFromMintTag(COutPoint& outPoint, const uint256 &pubCoinTag) {\n    GroupElement pubCoinValue;\n    lelantus::CLelantusState *lelantusState = lelantus::CLelantusState::GetState();\n    if(!lelantusState->HasCoinTag(pubCoinValue, pubCoinTag)){\n        return false;\n    }\n\n    return GetOutPoint(outPoint, pubCoinValue);\n}\n\nbool BuildLelantusStateFromIndex(CChain *chain) {\n    for (CBlockIndex *blockIndex = chain->Genesis(); blockIndex; blockIndex=chain->Next(blockIndex))\n    {\n        lelantusState.AddBlock(blockIndex);\n    }\n    // DEBUG\n    LogPrintf(\n        \"Latest ID for Lelantus coin group  %d\\n\",\n        lelantusState.GetLatestCoinID());\n    return true;\n}\n\n// CLelantusTxInfo\nvoid CLelantusTxInfo::Complete() {\n    // We need to sort mints lexicographically by serialized value of pubCoin. That's the way old code\n    // works, we need to stick to it.\n    sort(mints.begin(), mints.end(),\n            [](decltype(mints)::const_reference m1, decltype(mints)::const_reference m2)->bool {\n            CDataStream ds1(SER_DISK, CLIENT_VERSION), ds2(SER_DISK, CLIENT_VERSION);\n            ds1 << m1;\n            ds2 << m2;\n            return ds1.str() < ds2.str();\n            });\n\n    // Mark this info as complete\n    fInfoIsComplete = true;\n}\n\n/*\n * Util funtions\n */\nsize_t CountCoinInBlock(CBlockIndex *index, int id) {\n    return index->lelantusMintedPubCoins.count(id) > 0\n        ? index->lelantusMintedPubCoins[id].size() : 0;\n}\n\n/******************************************************************************/\n// CLelantusState::Containers\n/******************************************************************************/\n\nCLelantusState::Containers::Containers(std::atomic<bool> & surgeCondition)\n: surgeCondition(surgeCondition)\n{}\n\nvoid CLelantusState::Containers::AddMint(lelantus::PublicCoin const & pubCoin, CMintedCoinInfo const & coinInfo, const uint256& tag) {\n    mintedPubCoins.insert(std::make_pair(pubCoin, coinInfo));\n    tagToPublicCoin.insert(std::make_pair(tag, pubCoin));\n    mintMetaInfo[coinInfo.coinGroupId] += 1;\n    CheckSurgeCondition();\n}\n\nvoid CLelantusState::Containers::RemoveMint(lelantus::PublicCoin const & pubCoin) {\n    mint_info_container::const_iterator iter = mintedPubCoins.find(pubCoin);\n    if (iter != mintedPubCoins.end()) {\n        for(auto hashPair =  tagToPublicCoin.begin(); hashPair !=  tagToPublicCoin.end(); hashPair++)\n            if(hashPair->second == pubCoin) {\n                tagToPublicCoin.erase(hashPair);\n                break;\n            }\n\n        mintMetaInfo[iter->second.coinGroupId] -= 1;\n        mintedPubCoins.erase(iter);\n        CheckSurgeCondition();\n    }\n}\n\nvoid CLelantusState::Containers::AddSpend(Scalar const & serial, int coinGroupId) {\n    if (!mintMetaInfo.count(coinGroupId)) {\n        throw std::invalid_argument(\"group id doesn't exist\");\n    }\n\n    usedCoinSerials[serial] = coinGroupId;\n    spendMetaInfo[coinGroupId] += 1;\n    CheckSurgeCondition();\n}\n\nvoid CLelantusState::Containers::RemoveSpend(Scalar const & serial) {\n    auto iter = usedCoinSerials.find(serial);\n    if (iter != usedCoinSerials.end()) {\n        spendMetaInfo[iter->second] -= 1;\n        usedCoinSerials.erase(iter);\n        CheckSurgeCondition();\n    }\n}\n\nvoid CLelantusState::Containers::AddExtendedMints(int group, size_t mints) {\n    extendedMintMetaInfo[group] = mints;\n    CheckSurgeCondition();\n}\n\nvoid CLelantusState::Containers::RemoveExtendedMints(int group) {\n    extendedMintMetaInfo.erase(group);\n    CheckSurgeCondition();\n}\n\nmint_info_container const & CLelantusState::Containers::GetMints() const {\n    return mintedPubCoins;\n}\n\nstd::unordered_map<uint256, lelantus::PublicCoin>&  CLelantusState::Containers::GetTagToPublicCoin() {\n    return tagToPublicCoin;\n}\n\nstd::unordered_map<Scalar, int> const & CLelantusState::Containers::GetSpends() const {\n    return usedCoinSerials;\n}\n\nbool CLelantusState::Containers::IsSurgeCondition() const {\n    return surgeCondition;\n}\n\nvoid CLelantusState::Containers::Reset() {\n    mintedPubCoins.clear();\n    usedCoinSerials.clear();\n    mintMetaInfo.clear();\n    spendMetaInfo.clear();\n    tagToPublicCoin.clear();\n    surgeCondition = false;\n}\n\nvoid CLelantusState::Containers::CheckSurgeCondition() {\n    bool result = false;\n\n    // find a range of groups that sum of serials larger than sum of mints\n    size_t serials = 0;\n    size_t mints = 0;\n    int start = 0;\n\n    for (auto it = mintMetaInfo.begin(); it != mintMetaInfo.end(); it++) {\n        auto id = it->first;\n\n        // include serials and mints to accumulators\n        serials += spendMetaInfo.count(id) ? spendMetaInfo[id] : 0;\n        mints += it->second;\n\n        // serials exceed mints then trigger\n        if (serials > mints) {\n            result = true;\n\n            std::ostringstream ostr;\n            ostr << \"Turning Lelantus surge protection ON: in group range: \" << start << \" - \" << id << '\\n';\n            error(ostr.str().c_str());\n\n            break;\n        }\n\n        auto extendedMints = extendedMintMetaInfo.count(id + 1) ?\n            extendedMintMetaInfo[id + 1] : 0;\n\n        if (serials <= mints - extendedMints) {\n            start = id + 1;\n            serials = 0;\n            mints = extendedMints;\n        }\n    }\n\n    surgeCondition = result;\n}\n\n/******************************************************************************/\n// CLelantusState\n/******************************************************************************/\n\nCLelantusState::CLelantusState(\n    size_t maxCoinInGroup,\n    size_t startGroupSize)\n    :\n    maxCoinInGroup(maxCoinInGroup),\n    startGroupSize(startGroupSize),\n    containers(surgeCondition)\n{\n    Reset();\n}\n\nvoid CLelantusState::AddMintsToStateAndBlockIndex(\n        CBlockIndex *index,\n        const CBlock* pblock) {\n\n    std::vector<std::pair<lelantus::PublicCoin, uint256>> blockMints;\n    for (const auto& mint : pblock->lelantusTxInfo->mints) {\n        blockMints.push_back(std::make_pair(mint.first, mint.second.second));\n    }\n\n    latestCoinId = std::max(1, latestCoinId);\n\n    auto &coinGroup = coinGroups[latestCoinId];\n\n    if (coinGroup.nCoins + blockMints.size() <= maxCoinInGroup) {\n        if (coinGroup.nCoins == 0) {\n            // first group of coins\n            assert(coinGroup.firstBlock == nullptr);\n            assert(coinGroup.lastBlock == nullptr);\n\n            coinGroup.firstBlock = coinGroup.lastBlock = index;\n        } else {\n            assert(coinGroup.firstBlock != nullptr);\n            assert(coinGroup.lastBlock != nullptr);\n            assert(coinGroup.lastBlock->nHeight <= index->nHeight);\n\n            coinGroup.lastBlock = index;\n        }\n        coinGroup.nCoins += blockMints.size();\n    } else {\n        auto& newCoinGroup = coinGroups[++latestCoinId];\n\n        CBlockIndex *first;\n        auto coins = CountLastNCoins(latestCoinId - 1, startGroupSize, first);\n        newCoinGroup.firstBlock = first ? first : index;\n        newCoinGroup.lastBlock = index;\n        newCoinGroup.nCoins = coins + blockMints.size();\n\n        containers.AddExtendedMints(latestCoinId, coins);\n    }\n\n    for (const auto& mint : blockMints) {\n        containers.AddMint(mint.first, CMintedCoinInfo::make(latestCoinId, index->nHeight), mint.second);\n\n        LogPrintf(\"AddMintsToStateAndBlockIndex: Lelantus mint added id=%d\\n\", latestCoinId);\n        index->lelantusMintedPubCoins[latestCoinId].push_back(mint);\n    }\n}\n\nvoid CLelantusState::AddSpend(const Scalar &serial, int coinGroupId) {\n    containers.AddSpend(serial, coinGroupId);\n}\n\nvoid CLelantusState::AddBlock(CBlockIndex *index) {\n    for (auto const &pubCoins : index->lelantusMintedPubCoins) {\n\n        if (pubCoins.second.empty())\n            continue;\n\n        auto &coinGroup = coinGroups[pubCoins.first];\n\n        if (coinGroup.firstBlock == nullptr) {\n            coinGroup.firstBlock = index;\n\n            if (pubCoins.first > 1) {\n                CBlockIndex *first;\n                coinGroup.nCoins = CountLastNCoins(pubCoins.first - 1, startGroupSize, first);\n                coinGroup.firstBlock = first ? first : index;\n\n                containers.AddExtendedMints(pubCoins.first, coinGroup.nCoins);\n            }\n        }\n        coinGroup.lastBlock = index;\n        coinGroup.nCoins += pubCoins.second.size();\n\n        latestCoinId = pubCoins.first;\n        for (auto const &coin : pubCoins.second) {\n            containers.AddMint(coin.first, CMintedCoinInfo::make(pubCoins.first, index->nHeight), coin.second);\n        }\n    }\n\n    for (auto const &serial : index->lelantusSpentSerials) {\n        AddSpend(serial.first, serial.second);\n    }\n}\n\nvoid CLelantusState::RemoveBlock(CBlockIndex *index) {\n    // roll back coin group updates\n    for (auto &coins : index->lelantusMintedPubCoins)\n    {\n        if (coinGroups.count(coins.first) == 0) {\n            throw std::invalid_argument(\"Group Id does not exist\");\n        }\n\n        LelantusCoinGroupInfo& coinGroup = coinGroups[coins.first];\n        auto nMintsToForget = coins.second.size();\n\n        if (nMintsToForget == 0)\n            continue;\n\n        assert(coinGroup.nCoins >= nMintsToForget);\n        auto isExtended = coins.first > 1;\n        coinGroup.nCoins -= nMintsToForget;\n\n        // if `index` is edged block we need to erase group\n        auto isEdgedBlock = false;\n        if (isExtended) {\n            auto prevBlockContainMints = index;\n            size_t prevGroupCount = 0;\n\n            // find block that contain some Lelantus mints\n            do {\n                prevBlockContainMints = prevBlockContainMints->pprev;\n            } while (prevBlockContainMints\n                && CountCoinInBlock(prevBlockContainMints, coins.first) == 0\n                && (prevGroupCount = CountCoinInBlock(prevBlockContainMints, coins.first - 1)) == 0);\n\n            isEdgedBlock = prevGroupCount > 0 && (coinGroup.nCoins - prevGroupCount) < startGroupSize;\n        }\n\n        if ((!isExtended && coinGroup.nCoins == 0) || (isExtended && isEdgedBlock)) {\n            // all the coins of this group have been erased, remove the group altogether\n            coinGroups.erase(coins.first);\n            // decrease pubcoin id\n            latestCoinId--;\n            // erase from containers\n            containers.RemoveExtendedMints(coins.first);\n        } else {\n            // roll back lastBlock to previous position\n            assert(coinGroup.lastBlock == index);\n\n            do {\n                assert(coinGroup.lastBlock != coinGroup.firstBlock);\n                coinGroup.lastBlock = coinGroup.lastBlock->pprev;\n            } while (coinGroup.lastBlock->lelantusMintedPubCoins.count(coins.first) == 0);\n        }\n    }\n\n    // roll back mints\n    for (auto const &pubCoins : index->lelantusMintedPubCoins) {\n        for (auto const &coin : pubCoins.second) {\n            auto coins = containers.GetMints().equal_range(coin.first);\n            auto coinIt = find_if(\n                coins.first, coins.second,\n                [&pubCoins](const mint_info_container::value_type &v) {\n                    return v.second.coinGroupId == pubCoins.first;\n                });\n            assert(coinIt != coins.second);\n            containers.RemoveMint(coinIt->first);\n        }\n    }\n\n    // roll back spends\n    for (auto const &serial : index->lelantusSpentSerials) {\n        containers.RemoveSpend(serial.first);\n    }\n}\n\nbool CLelantusState::GetCoinGroupInfo(\n        int group_id,\n        LelantusCoinGroupInfo& result) {\n    if (coinGroups.count(group_id) == 0)\n        return false;\n\n    result = coinGroups[group_id];\n    return true;\n}\n\nbool CLelantusState::IsUsedCoinSerial(const Scalar &coinSerial) {\n    return containers.GetSpends().count(coinSerial) != 0;\n}\n\nbool CLelantusState::IsUsedCoinSerialHash(Scalar &coinSerial, const uint256 &coinSerialHash) {\n    for ( auto it = GetSpends().begin(); it != GetSpends().end(); ++it ){\n        if(primitives::GetSerialHash(it->first)==coinSerialHash){\n            coinSerial = it->first;\n            return true;\n        }\n    }\n    return false;\n}\n\nbool CLelantusState::HasCoin(const lelantus::PublicCoin& pubCoin) {\n    return containers.GetMints().find(pubCoin) != containers.GetMints().end();\n}\n\nbool CLelantusState::HasCoinHash(GroupElement &pubCoinValue, const uint256 &pubCoinValueHash) {\n    for ( auto it = GetMints().begin(); it != GetMints().end(); ++it ){\n        const lelantus::PublicCoin & pubCoin = (*it).first;\n        if(pubCoin.getValueHash()==pubCoinValueHash){\n            pubCoinValue = pubCoin.getValue();\n            return true;\n        }\n    }\n    return false;\n}\n\nbool CLelantusState::HasCoinTag(GroupElement& pubCoinValue, const uint256& pubCoinTag) {\n    auto const& mints = containers.GetTagToPublicCoin();\n    if(mints.count(pubCoinTag) > 0) {\n        pubCoinValue = mints.at(pubCoinTag).getValue();\n        return true;\n    }\n    return false;\n}\n\nint CLelantusState::GetCoinSetForSpend(\n    CChain *chain,\n    int maxHeight,\n    int coinGroupID,\n    uint256& blockHash_out,\n    std::vector<lelantus::PublicCoin>& coins_out,\n    std::vector<unsigned char>& setHash_out) {\n\n    coins_out.clear();\n\n    if (coinGroups.count(coinGroupID) == 0) {\n        return 0;\n    }\n\n    LelantusCoinGroupInfo &coinGroup = coinGroups[coinGroupID];\n\n    int numberOfCoins = 0;\n    for (CBlockIndex *block = coinGroup.lastBlock;; block = block->pprev) {\n\n        // ignore block heigher than max height\n        if (block->nHeight > maxHeight) {\n            continue;\n        }\n\n        // check coins in group coinGroupID - 1 in the case that using coins from prev group.\n        int id = 0;\n        if (CountCoinInBlock(block, coinGroupID)) {\n            id = coinGroupID;\n        } else if (CountCoinInBlock(block, coinGroupID - 1)) {\n            id = coinGroupID - 1;\n        }\n\n        if (id) {\n            if (numberOfCoins == 0) {\n                // latest block satisfying given conditions\n                // remember block hash and set hash\n                blockHash_out = block->GetBlockHash();\n                setHash_out =  GetAnonymitySetHash(block, id);\n            }\n            numberOfCoins += block->lelantusMintedPubCoins[id].size();\n            if (block->lelantusMintedPubCoins.count(id) > 0) {\n                for (const auto &coin : block->lelantusMintedPubCoins[id]) {\n                    LOCK(cs_main);\n                    // skip mints from blacklist if nLelantusFixesStartBlock is passed\n                    if (chainActive.Height() >= ::Params().GetConsensus().nLelantusFixesStartBlock) {\n                        if (::Params().GetConsensus().lelantusBlacklist.count(coin.first.getValue()) > 0) {\n                            continue;\n                        }\n                    }\n                    coins_out.push_back(coin.first);\n                }\n            }\n        }\n\n        if (block == coinGroup.firstBlock) {\n            break ;\n        }\n    }\n\n    return numberOfCoins;\n}\n\nvoid CLelantusState::GetAnonymitySet(\n        int coinGroupID,\n        bool fStartLelantusBlacklist,\n        std::vector<lelantus::PublicCoin>& coins_out) {\n\n    coins_out.clear();\n\n    if (coinGroups.count(coinGroupID) == 0) {\n        return;\n    }\n\n    LelantusCoinGroupInfo &coinGroup = coinGroups[coinGroupID];\n    auto params = ::Params().GetConsensus();\n    LOCK(cs_main);\n    int maxHeight = fStartLelantusBlacklist ? (chainActive.Height() - (ZC_MINT_CONFIRMATIONS - 1)) : (params.nLelantusFixesStartBlock - 1);\n\n    for (CBlockIndex *block = coinGroup.lastBlock;; block = block->pprev) {\n\n        // ignore block heigher than max height\n        if (block->nHeight > maxHeight) {\n            continue;\n        }\n\n        // check coins in group coinGroupID - 1 in the case that using coins from prev group.\n        int id = 0;\n        if (CountCoinInBlock(block, coinGroupID)) {\n            id = coinGroupID;\n        } else if (CountCoinInBlock(block, coinGroupID - 1)) {\n            id = coinGroupID - 1;\n        }\n\n        if (id) {\n            if(block->lelantusMintedPubCoins.count(id) > 0) {\n                for (const auto &coin : block->lelantusMintedPubCoins[id]) {\n                    if (fStartLelantusBlacklist &&\n                        chainActive.Height() >= ::Params().GetConsensus().nLelantusFixesStartBlock) {\n                        std::vector<unsigned char> vch = coin.first.getValue().getvch();\n                        if (::Params().GetConsensus().lelantusBlacklist.count(coin.first.getValue()) > 0) {\n                            continue;\n                        }\n                    }\n                    coins_out.push_back(coin.first);\n                }\n            }\n        }\n\n        if (block == coinGroup.firstBlock) {\n            break ;\n        }\n    }\n}\n\nstd::pair<int, int> CLelantusState::GetMintedCoinHeightAndId(\n        const lelantus::PublicCoin& pubCoin) {\n    auto coinIt = containers.GetMints().find(pubCoin);\n\n    if (coinIt != containers.GetMints().end()) {\n        return std::make_pair(coinIt->second.nHeight, coinIt->second.coinGroupId);\n    }\n    return std::make_pair(-1, -1);\n}\n\nbool CLelantusState::AddSpendToMempool(const std::vector<Scalar> &coinSerials, uint256 txHash) {\n    LOCK(mempool.cs);\n    BOOST_FOREACH(const Scalar& coinSerial, coinSerials){\n        if (IsUsedCoinSerial(coinSerial) || mempool.lelantusState.HasCoinSerial(coinSerial))\n            return false;\n\n        mempool.lelantusState.AddSpendToMempool(coinSerial, txHash);\n    }\n\n    return true;\n}\n\nvoid CLelantusState::RemoveSpendFromMempool(const std::vector<Scalar> &coinSerials) {\n    LOCK(mempool.cs);\n    BOOST_FOREACH(const Scalar& coinSerial, coinSerials) {\n        mempool.lelantusState.RemoveSpendFromMempool(coinSerial);\n    }\n}\n\nvoid CLelantusState::AddMintsToMempool(const std::vector<GroupElement>& pubCoins) {\n    LOCK(mempool.cs);\n    BOOST_FOREACH(const GroupElement& pubCoin, pubCoins) {\n        mempool.lelantusState.AddMintToMempool(pubCoin);\n    }\n}\n\nvoid CLelantusState::RemoveMintFromMempool(const GroupElement& pubCoin) {\n    LOCK(mempool.cs);\n    mempool.lelantusState.RemoveMintFromMempool(pubCoin);\n}\n\nuint256 CLelantusState::GetMempoolConflictingTxHash(const Scalar& coinSerial) {\n    LOCK(mempool.cs);\n    return mempool.lelantusState.GetMempoolConflictingTxHash(coinSerial);\n}\n\nbool CLelantusState::CanAddSpendToMempool(const Scalar& coinSerial) {\n    LOCK(mempool.cs);    \n    return !IsUsedCoinSerial(coinSerial) && !mempool.lelantusState.HasCoinSerial(coinSerial);\n}\n\nbool CLelantusState::CanAddMintToMempool(const GroupElement& pubCoin){\n    LOCK(mempool.cs);\n    return !HasCoin(pubCoin) && !mempool.lelantusState.HasMint(pubCoin);\n}\n\nvoid CLelantusState::Reset() {\n    coinGroups.clear();\n    latestCoinId = 0;\n    containers.Reset();\n}\n\nCLelantusState* CLelantusState::GetState() {\n    return &lelantusState;\n}\n\nint CLelantusState::GetLatestCoinID() const {\n    return latestCoinId;\n}\n\nbool CLelantusState::IsSurgeConditionDetected() const {\n    return surgeCondition;\n}\n\nmint_info_container const & CLelantusState::GetMints() const {\n    return containers.GetMints();\n}\n\nstd::unordered_map<Scalar, int> const & CLelantusState::GetSpends() const {\n    return containers.GetSpends();\n}\n\nstd::unordered_map<int, CLelantusState::LelantusCoinGroupInfo> const & CLelantusState::GetCoinGroups() const {\n    return coinGroups;\n}\n\nstd::unordered_map<Scalar, uint256, sigma::CScalarHash> const & CLelantusState::GetMempoolCoinSerials() const {\n    LOCK(mempool.cs);\n    return mempool.lelantusState.GetMempoolCoinSerials();\n}\n\n// private\nsize_t CLelantusState::CountLastNCoins(int groupId, size_t required, CBlockIndex* &first) {\n    first = nullptr;\n    size_t coins = 0;\n\n    if (coinGroups.count(groupId)) {\n        auto &group = coinGroups[groupId];\n\n        for (auto block = group.lastBlock\n            ; coins < required && block\n            ; block = block->pprev) {\n\n            size_t inBlock;\n            if (block->lelantusMintedPubCoins.count(groupId)\n                && (inBlock = block->lelantusMintedPubCoins[groupId].size())) {\n\n                coins += inBlock;\n                first = block;\n            }\n        }\n    }\n\n    return coins;\n}\n\n// CLelantusMempoolState\n\nbool CLelantusMempoolState::HasCoinSerial(const Scalar& coinSerial) {\n    return mempoolCoinSerials.count(coinSerial) > 0;\n}\n\nbool CLelantusMempoolState::HasMint(const GroupElement& pubCoin) {\n    return mempoolMints.count(pubCoin) > 0;\n}\n\nbool CLelantusMempoolState::AddSpendToMempool(const Scalar &coinSerial, uint256 txHash) {\n    return mempoolCoinSerials.insert({coinSerial, txHash}).second;\n}\n\nvoid CLelantusMempoolState::AddMintToMempool(const GroupElement& pubCoin) {\n    mempoolMints.insert(pubCoin);\n}\n\nvoid CLelantusMempoolState::RemoveMintFromMempool(const GroupElement& pubCoin) {\n    mempoolMints.erase(pubCoin);\n}\n\nuint256 CLelantusMempoolState::GetMempoolConflictingTxHash(const Scalar& coinSerial) {\n    if (mempoolCoinSerials.count(coinSerial) == 0)\n        return uint256();\n\n    return mempoolCoinSerials[coinSerial];\n}\n\nvoid CLelantusMempoolState::RemoveSpendFromMempool(const Scalar &coinSerial) {\n    mempoolCoinSerials.erase(coinSerial);\n}\n\nvoid CLelantusMempoolState::Reset() {\n    mempoolCoinSerials.clear();\n    mempoolMints.clear();\n}\n\n\n} // end of namespace lelantus.\n", "meta": {"hexsha": "78819bdbdd66ce9beeda7e5e5290d48f60547509", "size": 60106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lelantus.cpp", "max_stars_repo_name": "lyricidal/firo", "max_stars_repo_head_hexsha": "029e935c60c46a1db77b09da7c81250882114711", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 159.0, "max_stars_repo_stars_event_min_datetime": "2020-11-09T22:39:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:14:57.000Z", "max_issues_repo_path": "src/lelantus.cpp", "max_issues_repo_name": "notshillo/firo", "max_issues_repo_head_hexsha": "9b0714e65cd69448819cbbe10e6272ccd3e69dc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 188.0, "max_issues_repo_issues_event_min_datetime": "2020-11-09T09:47:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T09:08:07.000Z", "max_forks_repo_path": "src/lelantus.cpp", "max_forks_repo_name": "notshillo/firo", "max_forks_repo_head_hexsha": "9b0714e65cd69448819cbbe10e6272ccd3e69dc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2020-11-17T14:40:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:45:58.000Z", "avg_line_length": 35.9916167665, "max_line_length": 201, "alphanum_fraction": 0.6236315842, "num_tokens": 15175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3522017820478897, "lm_q1q2_score": 0.1816022531770288}}
{"text": "// Copyright (c) 2014 The Bitcoin Core developers\n// Copyright (c) 2014-2015 The Dash developers\n// Copyright (c) 2015-2017 The KORE 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 \"main.h\"\n#include \"miner.h\"\n#include \"primitives/transaction.h\"\n\n#include \"utilmoneystr.h\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(main_tests)\n\n// We are unable to test pre-fork supply beacause it doesn't use a fixed amount.\n// For test purpose we consider the fork to happen on block 429033.\n// The money supply on block 429032 is 2,141,450.338583.\nBOOST_AUTO_TEST_CASE(subsidy_limit_test_post_fork)\n{\n    SelectParams(CBaseChainParams::MAIN);\n\n    int nHeight = 470499;  \n    CAmount nMoneySupply = 215594083152340;\n    CAmount nlastSubsidy = 103008606;\n    CAmount nSubsidy = 0;\n\n    // Represents block 470498\n    CBlockIndex pindexPrev;\n    pindexPrev.nHeight = 470498;\n    pindexPrev.nMoneySupply = nMoneySupply;\n\n    for (nHeight; nHeight <= 20433096; nHeight++) {\n        /* PoS */\n        nSubsidy = GetBlockReward(&pindexPrev);\n        BOOST_CHECK(nSubsidy <= nlastSubsidy);\n        nlastSubsidy = nSubsidy;\n        if(!MoneyRange(nSubsidy))\n            printf(\"%d, %s\", nHeight, FormatMoney(nSubsidy).c_str());\n        BOOST_CHECK(MoneyRange(nSubsidy));\n        nMoneySupply += nSubsidy;\n        BOOST_CHECK(nMoneySupply <= MAX_MONEY);\n        pindexPrev.nMoneySupply = nMoneySupply;\n        pindexPrev.nHeight++;\n    }\n    BOOST_ASSERT(pindexPrev.nMoneySupply == MAX_MONEY);\n\n    // Try to call it again after the limit was reached\n    nSubsidy = GetBlockReward(&pindexPrev);\n    BOOST_ASSERT(nSubsidy == 0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "46f2a38c08911a1144f5524a8b669febbdf7777b", "size": 1769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/main_tests.cpp", "max_stars_repo_name": "Kore-Core/Kore", "max_stars_repo_head_hexsha": "d0bb166f6ad69b09ef305cdedc2a799cd3f874c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-02-02T15:18:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-27T06:00:26.000Z", "max_issues_repo_path": "src/test/main_tests.cpp", "max_issues_repo_name": "Kore-Core/Kore", "max_issues_repo_head_hexsha": "d0bb166f6ad69b09ef305cdedc2a799cd3f874c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-07-05T12:05:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-09T06:25:45.000Z", "max_forks_repo_path": "src/test/main_tests.cpp", "max_forks_repo_name": "Kore-Core/Kore", "max_forks_repo_head_hexsha": "d0bb166f6ad69b09ef305cdedc2a799cd3f874c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-01-14T14:14:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-16T03:39:05.000Z", "avg_line_length": 32.1636363636, "max_line_length": 80, "alphanum_fraction": 0.7066139062, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18160224967103544}}
{"text": "#define BOOST_TEST_DYN_LINK\n\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n#include <string>\n#include \"token.hpp\"\n#include \"parser.hpp\"\n#include \"context_methods.hpp\"\n#include \"lang_parser_base.hpp\"\n\nusing namespace cuttle;\nusing namespace cuttle::lang;\n\nstruct context_init_fixture {\n    context_t context;\n    call_tree_t tree;\n\n    void setup() {\n        initialize(context);\n        get_parser_base(context);\n    }\n};\n\nBOOST_FIXTURE_TEST_SUITE(lang_parser_math_suite, context_init_fixture)\n\n    BOOST_AUTO_TEST_CASE(plus) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"2\", 1, 1},\n                token_t {token_type::atom, \"+\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(minus) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"7\", 1, 1},\n                token_t {token_type::atom, \"-\", 1, 3},\n                token_t {token_type::number, \"1\", 1, 5}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(multiply) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"123\", 1, 1},\n                token_t {token_type::atom, \"*\", 1, 5},\n                token_t {token_type::number, \"5\", 1, 7}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(divide) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"7\", 1, 1},\n                token_t {token_type::atom, \"/\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(plus_and_minus) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"1\", 1, 1},\n                token_t {token_type::atom, \"+\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5},\n                token_t {token_type::atom, \"-\", 1, 7},\n                token_t {token_type::number, \"8\", 1, 9}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1, 4}, {}, {3} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(multiply_and_divide) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"7\", 1, 1},\n                token_t {token_type::atom, \"*\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5},\n                token_t {token_type::atom, \"/\", 1, 7},\n                token_t {token_type::number, \"8\", 1, 9}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1, 4}, {}, {3} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(multiply_and_plus) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"7\", 1, 1},\n                token_t {token_type::atom, \"*\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5},\n                token_t {token_type::atom, \"+\", 1, 7},\n                token_t {token_type::number, \"8\", 1, 9}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1, 4}, {}, {3} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(divide_and_plus) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"7\", 1, 1},\n                token_t {token_type::atom, \"/\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5},\n                token_t {token_type::atom, \"+\", 1, 7},\n                token_t {token_type::number, \"8\", 1, 9}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1, 4}, {}, {3} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(multiply_and_minus) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"7\", 1, 1},\n                token_t {token_type::atom, \"*\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5},\n                token_t {token_type::atom, \"+\", 1, 7},\n                token_t {token_type::number, \"8\", 1, 9}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1, 4}, {}, {3} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(divide_and_minus) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"7\", 1, 1},\n                token_t {token_type::atom, \"/\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5},\n                token_t {token_type::atom, \"-\", 1, 7},\n                token_t {token_type::number, \"8\", 1, 9}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1, 4}, {}, {3} }));\n    }\n\n    BOOST_AUTO_TEST_CASE(divide_minus_and_multiply) {\n        std::vector<token_t> tokens = {\n                token_t {token_type::number, \"7\", 1, 1},\n                token_t {token_type::atom, \"/\", 1, 3},\n                token_t {token_type::number, \"2\", 1, 5},\n                token_t {token_type::atom, \"-\", 1, 7},\n                token_t {token_type::number, \"8\", 1, 9},\n                token_t {token_type::atom, \"*\", 1, 11},\n                token_t {token_type::number, \"8\", 1, 13}\n        };\n        parse(tokens, tree, context);\n        BOOST_CHECK(tree.src == (tree_src_t{ {}, {0, 2}, {}, {1, 5}, {}, {4, 6}, {}, {3} }));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "edf9f1914bc0b98229f453bb900c5882cb9a647c", "size": 5668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_lang_parser_math.cpp", "max_stars_repo_name": "cuttle-system/cuttle-lang", "max_stars_repo_head_hexsha": "1b3ba8d81d2300dff1369801da2f712b77dcb6f4", "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/test_lang_parser_math.cpp", "max_issues_repo_name": "cuttle-system/cuttle-lang", "max_issues_repo_head_hexsha": "1b3ba8d81d2300dff1369801da2f712b77dcb6f4", "max_issues_repo_licenses": ["MIT"], "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/test_lang_parser_math.cpp", "max_forks_repo_name": "cuttle-system/cuttle-lang", "max_forks_repo_head_hexsha": "1b3ba8d81d2300dff1369801da2f712b77dcb6f4", "max_forks_repo_licenses": ["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.2894736842, "max_line_length": 93, "alphanum_fraction": 0.4996471418, "num_tokens": 1638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18160224967103542}}
{"text": "#include <string.h>\n#include <vector>\n#include <iostream>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <ros/ros.h>\n#include <urdf_model/link.h>\n#include <urdf/model.h>\n\n/*\n#include <tf/transform_listener.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/tf.h>\n#include <tf_conversions/tf_kdl.h>\n#include <sensor_msgs/JointState.h>\n*/\n\n#include <rbdl/addons/rbdlUrdfParser.h>\n\nusing namespace std;\nusing namespace RigidBodyDynamics;\nusing namespace RigidBodyDynamics::Math;\n\ntypedef boost::shared_ptr<urdf::Link> LinkPtr;\ntypedef boost::shared_ptr<urdf::Joint> JointPtr;\n\n/* Check if the specified link is inside this urdf submodel */\nbool isLinkInUrdfModel(LinkPtr link, std::string tip){\n  if(tip == link->name){\n    return true;\n  }\n  else{\n    if(link->child_links.empty()){\n      return false;\n    }\n    else{\n      bool found = false;\n      for(unsigned int i=0; i<link->child_links.size() && !found; ++i){\n        found = found || isLinkInUrdfModel(link->child_links[i], tip);\n      }\n      return found;\n    }\n  }\n}\n\n/*This function will be called recursively adding the Links from the urdf to rbdl */\nvoid constructRBDLfromURDF(Model &rbdl_model, LinkPtr urdf_link, int parent_id,\n                           bool floating_base,\n                           bool planar_floating_base){\n\n  int new_id = 0;\n  if(urdf_link->parent_joint.get()){\n    JointPtr urdf_joint = urdf_link->parent_joint;\n    // create the joint\n    Joint rbdl_joint;\n    if (urdf_joint->type == urdf::Joint::REVOLUTE || urdf_joint->type == urdf::Joint::CONTINUOUS) {\n      rbdl_joint = Joint (SpatialVector (urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z, 0., 0., 0.));\n\n    }\n    else if (urdf_joint->type == urdf::Joint::PRISMATIC) {\n      rbdl_joint = Joint (SpatialVector (0., 0., 0., urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z));\n    }\n    else if (urdf_joint->type == urdf::Joint::FIXED) {\n      rbdl_joint = Joint (JointTypeFixed);\n    }\n\n    // compute the joint transformation\n    Vector3d joint_rpy;\n    Vector3d joint_translation;\n    urdf_joint->parent_to_joint_origin_transform.rotation.getRPY (joint_rpy[0], joint_rpy[1], joint_rpy[2]);\n    joint_translation.set (\n          urdf_joint->parent_to_joint_origin_transform.position.x,\n          urdf_joint->parent_to_joint_origin_transform.position.y,\n          urdf_joint->parent_to_joint_origin_transform.position.z\n          );\n    SpatialTransform rbdl_joint_frame =\n        Xrot (joint_rpy[0], Vector3d (1., 0., 0.))\n        * Xrot (joint_rpy[1], Vector3d (0., 1., 0.))\n        * Xrot (joint_rpy[2], Vector3d (0., 0., 1.))\n        * Xtrans (Vector3d (\n                    joint_translation\n                    ));\n\n    // assemble the body\n    Vector3d link_inertial_position;\n    Vector3d link_inertial_rpy;\n    Matrix3d link_inertial_inertia = Matrix3d::Zero();\n    double link_inertial_mass;\n\n    // but only if we actually have inertial data\n    if (urdf_link->inertial) {\n      link_inertial_mass = urdf_link->inertial->mass;\n\n      link_inertial_position.set (\n            urdf_link->inertial->origin.position.x,\n            urdf_link->inertial->origin.position.y,\n            urdf_link->inertial->origin.position.z\n            );\n      urdf_link->inertial->origin.rotation.getRPY (link_inertial_rpy[0], link_inertial_rpy[1], link_inertial_rpy[2]);\n\n      link_inertial_inertia(0,0) = urdf_link->inertial->ixx;\n      link_inertial_inertia(0,1) = urdf_link->inertial->ixy;\n      link_inertial_inertia(0,2) = urdf_link->inertial->ixz;\n\n      link_inertial_inertia(1,0) = urdf_link->inertial->ixy;\n      link_inertial_inertia(1,1) = urdf_link->inertial->iyy;\n      link_inertial_inertia(1,2) = urdf_link->inertial->iyz;\n\n      link_inertial_inertia(2,0) = urdf_link->inertial->ixz;\n      link_inertial_inertia(2,1) = urdf_link->inertial->iyz;\n      link_inertial_inertia(2,2) = urdf_link->inertial->izz;\n\n\n      if (link_inertial_rpy != Vector3d (0., 0., 0.)) {\n        cerr << \"Error while processing body '\" << urdf_link->name <<\n                \"': rotation of body frames not yet supported. Please rotate the joint frame instead.\" << endl;\n      }\n    }\n    Body rbdl_body = Body (link_inertial_mass, link_inertial_position, link_inertial_inertia);\n\n    new_id = rbdl_model.AddBody (parent_id, rbdl_joint_frame, rbdl_joint, rbdl_body, urdf_link->name);\n  }\n  else\n    //If a floating base is desired we need to compute the inertia data of the floating base link,\n    //if the floating base has no inertial details, then it makes no sense to make it floating\n    //base (Like kdl). (The root is the only link allowed to be floating base\n\n    if(floating_base){\n      double link_inertial_mass;\n      Vector3d link_inertial_position;\n      Vector3d link_inertial_rpy;\n      Matrix3d link_inertial_inertia = Matrix3d::Zero();\n\n      if (urdf_link->inertial) {\n        link_inertial_mass = urdf_link->inertial->mass;\n\n        link_inertial_position.set (\n              urdf_link->inertial->origin.position.x,\n              urdf_link->inertial->origin.position.y,\n              urdf_link->inertial->origin.position.z\n              );\n        urdf_link->inertial->origin.rotation.getRPY (link_inertial_rpy[0], link_inertial_rpy[1], link_inertial_rpy[2]);\n\n        link_inertial_inertia(0,0) = urdf_link->inertial->ixx;\n        link_inertial_inertia(0,1) = urdf_link->inertial->ixy;\n        link_inertial_inertia(0,2) = urdf_link->inertial->ixz;\n\n        link_inertial_inertia(1,0) = urdf_link->inertial->ixy;\n        link_inertial_inertia(1,1) = urdf_link->inertial->iyy;\n        link_inertial_inertia(1,2) = urdf_link->inertial->iyz;\n\n        link_inertial_inertia(2,0) = urdf_link->inertial->ixz;\n        link_inertial_inertia(2,1) = urdf_link->inertial->iyz;\n        link_inertial_inertia(2,2) = urdf_link->inertial->izz;\n\n\n        if (link_inertial_rpy != Vector3d (0., 0., 0.)) {\n          cerr << \"Error while processing body '\" << urdf_link->name <<\n                  \"': rotation of body frames not yet supported. Please rotate the joint frame instead.\" << endl;\n        }\n      }\n\n      Body base = Body (link_inertial_mass, link_inertial_position, link_inertial_inertia);\n      //make floating base\n      if(planar_floating_base){\n        new_id = rbdl_model.SetPlanarFloatingBaseBody(base, urdf_link->name);\n      }\n      else{\n        new_id = rbdl_model.SetFloatingBaseBody(base, urdf_link->name);\n      }\n    }\n\n  for(unsigned int i=0; i< urdf_link->child_links.size(); ++i){\n    constructRBDLfromURDF(rbdl_model, urdf_link->child_links[i], new_id, floating_base, planar_floating_base);\n  }\n}\n\n/*This function will be called recursively adding the Links from the urdf to rbdl, But only with the tips that are specified inside\n  the tips vectors*/\n\nvoid constructRBDLfromURDF(Model &rbdl_model, LinkPtr urdf_link,\n                           int parent_id,\n                           const std::vector<std::string> &tips,\n                           bool floating_base,\n                           bool planar_floating_base){\n\n  int new_id = 0;\n  if(urdf_link->parent_joint.get()){\n    JointPtr urdf_joint = urdf_link->parent_joint;\n    // create the joint\n    Joint rbdl_joint;\n    if (urdf_joint->type == urdf::Joint::REVOLUTE || urdf_joint->type == urdf::Joint::CONTINUOUS) {\n      rbdl_joint = Joint (SpatialVector (urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z, 0., 0., 0.));\n    }\n    else if (urdf_joint->type == urdf::Joint::PRISMATIC) {\n      rbdl_joint = Joint (SpatialVector (0., 0., 0., urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z));\n    }\n    else if (urdf_joint->type == urdf::Joint::FIXED) {\n      rbdl_joint = Joint (JointTypeFixed);\n    }\n\n    // compute the joint transformation\n    Vector3d joint_rpy;\n    Vector3d joint_translation;\n    urdf_joint->parent_to_joint_origin_transform.rotation.getRPY (joint_rpy[0], joint_rpy[1], joint_rpy[2]);\n    joint_translation.set (\n          urdf_joint->parent_to_joint_origin_transform.position.x,\n          urdf_joint->parent_to_joint_origin_transform.position.y,\n          urdf_joint->parent_to_joint_origin_transform.position.z\n          );\n    SpatialTransform rbdl_joint_frame =\n        Xrot (joint_rpy[0], Vector3d (1., 0., 0.))\n        * Xrot (joint_rpy[1], Vector3d (0., 1., 0.))\n        * Xrot (joint_rpy[2], Vector3d (0., 0., 1.))\n        * Xtrans (Vector3d (\n                    joint_translation\n                    ));\n\n    // assemble the body\n    Vector3d link_inertial_position;\n    Vector3d link_inertial_rpy;\n    Matrix3d link_inertial_inertia = Matrix3d::Zero();\n    double link_inertial_mass;\n\n    // but only if we actually have inertial data\n    if (urdf_link->inertial) {\n      link_inertial_mass = urdf_link->inertial->mass;\n\n      link_inertial_position.set (\n            urdf_link->inertial->origin.position.x,\n            urdf_link->inertial->origin.position.y,\n            urdf_link->inertial->origin.position.z\n            );\n      urdf_link->inertial->origin.rotation.getRPY (link_inertial_rpy[0], link_inertial_rpy[1], link_inertial_rpy[2]);\n\n      link_inertial_inertia(0,0) = urdf_link->inertial->ixx;\n      link_inertial_inertia(0,1) = urdf_link->inertial->ixy;\n      link_inertial_inertia(0,2) = urdf_link->inertial->ixz;\n\n      link_inertial_inertia(1,0) = urdf_link->inertial->ixy;\n      link_inertial_inertia(1,1) = urdf_link->inertial->iyy;\n      link_inertial_inertia(1,2) = urdf_link->inertial->iyz;\n\n      link_inertial_inertia(2,0) = urdf_link->inertial->ixz;\n      link_inertial_inertia(2,1) = urdf_link->inertial->iyz;\n      link_inertial_inertia(2,2) = urdf_link->inertial->izz;\n\n\n      if (link_inertial_rpy != Vector3d (0., 0., 0.)) {\n        cerr << \"Error while processing body '\" << urdf_link->name <<\n                \"': rotation of body frames not yet supported. Please rotate the joint frame instead.\" << endl;\n      }\n    }\n    Body rbdl_body = Body (link_inertial_mass, link_inertial_position, link_inertial_inertia);\n\n    new_id = rbdl_model.AddBody (parent_id, rbdl_joint_frame, rbdl_joint, rbdl_body, urdf_link->name);\n  }\n  else\n    //If a floating base is desired we need to compute the inertia data of the floating base link,\n    //if the floating base has no inertial details, then it makes no sense to make it floating\n    //base (Like kdl). (The root is the only link allowed to be floating base\n\n    if(floating_base){\n      double link_inertial_mass;\n      Vector3d link_inertial_position;\n      Vector3d link_inertial_rpy;\n      Matrix3d link_inertial_inertia = Matrix3d::Zero();\n\n      if (urdf_link->inertial) {\n        link_inertial_mass = urdf_link->inertial->mass;\n\n        link_inertial_position.set (\n              urdf_link->inertial->origin.position.x,\n              urdf_link->inertial->origin.position.y,\n              urdf_link->inertial->origin.position.z\n              );\n        urdf_link->inertial->origin.rotation.getRPY (link_inertial_rpy[0], link_inertial_rpy[1], link_inertial_rpy[2]);\n\n        link_inertial_inertia(0,0) = urdf_link->inertial->ixx;\n        link_inertial_inertia(0,1) = urdf_link->inertial->ixy;\n        link_inertial_inertia(0,2) = urdf_link->inertial->ixz;\n\n        link_inertial_inertia(1,0) = urdf_link->inertial->ixy;\n        link_inertial_inertia(1,1) = urdf_link->inertial->iyy;\n        link_inertial_inertia(1,2) = urdf_link->inertial->iyz;\n\n        link_inertial_inertia(2,0) = urdf_link->inertial->ixz;\n        link_inertial_inertia(2,1) = urdf_link->inertial->iyz;\n        link_inertial_inertia(2,2) = urdf_link->inertial->izz;\n\n\n        if (link_inertial_rpy != Vector3d (0., 0., 0.)) {\n          cerr << \"Error while processing body '\" << urdf_link->name <<\n                  \"': rotation of body frames not yet supported. Please rotate the joint frame instead.\" << endl;\n        }\n      }\n\n      Body base = Body (link_inertial_mass, link_inertial_position, link_inertial_inertia);\n      //make floating base\n      if(planar_floating_base){\n        new_id = rbdl_model.SetPlanarFloatingBaseBody(base, urdf_link->name);\n      }\n      else{\n        new_id = rbdl_model.SetFloatingBaseBody(base, urdf_link->name);\n      }\n    }\n\n  /* The current link is a desired tip */\n  bool tip_found = false;\n  for(unsigned int i=0; i<tips.size() && !tip_found; ++i){\n    if(tips[i] == urdf_link->name){\n      tip_found = true;\n    }\n  }\n\n  if(!tip_found){\n    for(unsigned int i=0; i< urdf_link->child_links.size(); ++i){\n      /* Check that the branch contains atleast on of the specified links */\n      bool found = false;\n      for(unsigned int j=0; j<tips.size() && !found; ++j){\n        found = isLinkInUrdfModel(urdf_link->child_links[i], tips[j]);\n      }\n      if(found){\n        constructRBDLfromURDF(rbdl_model, urdf_link->child_links[i], new_id, tips, floating_base, planar_floating_base);\n      }\n    }\n  }\n}\n\n\n// WTF Happened here, that in was not found in the .so when linked?\nbool parseUrdf(urdf::Model &urdf_model, Model &rbdl_model,\n               const std::vector<std::string> &tips,\n               bool floating_base,\n               bool planar_floating_base) {\n\n  boost::shared_ptr<urdf::Link> root(boost::const_pointer_cast<urdf::Link>(urdf_model.getRoot()));\n  constructRBDLfromURDF(rbdl_model, root, 0, tips, floating_base, planar_floating_base);\n\n  return true;\n}\n\nbool parseUrdf(urdf::Model &urdf_model, Model &rbdl_model,\n               bool floating_base,\n               bool planar_floating_base) {\n\n  boost::shared_ptr<urdf::Link> root(boost::const_pointer_cast<urdf::Link>(urdf_model.getRoot()));\n  constructRBDLfromURDF(rbdl_model, root, 0, floating_base, planar_floating_base);\n  return true;\n}\n\nbool parseUrdfParamServer(RigidBodyDynamics::Model &rbdl_model,\n                          std::vector<std::string> &joint_names,\n                          bool floating_base,\n                          bool planar_floating_base){\n\n  ros::NodeHandle n;\n  std::string urdf_name, full_urdf_xml;\n\n  n.param(\"urdf_xml_model\",urdf_name,std::string(\"robot_description\"));\n  n.searchParam(urdf_name,full_urdf_xml);\n\n  urdf::Model urdf_model;\n  if (!urdf_model.initParam(full_urdf_xml)){\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n  ROS_INFO(\"Successfully parsed urdf file\");\n  bool res = parseUrdf(urdf_model, rbdl_model, floating_base, planar_floating_base);\n  //We need a link->name to joint->name map;\n  for(unsigned int i=0; i< rbdl_model.dof_count; ++i){\n    boost::shared_ptr<urdf::Link> urdf_link;\n    //As the joints, the bodyes with movable joints start ad +1\n    //Since the movable bodies have a small numbering and the fixed bodyes have\n    //a high numbering will get n joint names in the lower numbers\n    std::string body_name = rbdl_model.GetBodyName(i+1);\n    urdf_model.getLink(body_name, urdf_link);\n    joint_names.push_back(urdf_link->parent_joint->name);\n  }\n\n  ROS_INFO_STREAM(\"parsed the urdf into rbdl succesfully\");\n  return res;\n}\n\nbool parseUrdfParamServerParameters(RigidBodyDynamics::Model &rbdl_model,\n                                    bool floating_base,\n                                    bool planar_floating_base){\n  ros::NodeHandle n;\n  std::string urdf_name, full_urdf_xml;\n\n\n  n.param(\"urdf_xml_model\",urdf_name,std::string(\"robot_description\"));\n  n.searchParam(urdf_name,full_urdf_xml);\n  urdf::Model urdf_model;\n\n  if (!urdf_model.initParam(full_urdf_xml)){\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n\n  bool res = parseUrdf(urdf_model, rbdl_model, floating_base, planar_floating_base);\n  return res;\n}\n\nbool parseUrdfString(RigidBodyDynamics::Model &rbdl_model,\n                     bool floating_base,\n                     const std::string &robot_description,\n                     bool planar_floating_base){\n\n  urdf::Model urdf_model;\n\n  if (!urdf_model.initString(robot_description)){\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n\n  bool res = parseUrdf(urdf_model, rbdl_model, floating_base, planar_floating_base);\n  return res;\n}\n\nbool parseUrdfParamServerParameters(RigidBodyDynamics::Model &rbdl_model, const std::vector<std::string> &tips,\n                                    bool floating_base, bool planar_floating_base){\n  ros::NodeHandle n;\n  std::string urdf_name, full_urdf_xml;\n\n  ROS_INFO_STREAM(\"parsing urdf into rbdl from param server\");\n\n  n.param(\"urdf_xml_model\",urdf_name,std::string(\"robot_description\"));\n  n.searchParam(urdf_name,full_urdf_xml);\n  urdf::Model urdf_model;\n\n  if (!urdf_model.initParam(full_urdf_xml)){\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n\n  ROS_INFO(\"Successfully parsed urdf file\");\n  bool res = parseUrdf(urdf_model, rbdl_model, tips, floating_base, planar_floating_base);\n  return res;\n}\n\n\nbool parseUrdfParamServerParameters(RigidBodyDynamics::Model &rbdl_model, std::vector<std::string> &joint_names,\n                                    std::vector<double> &position_min,  std::vector<double> &position_max,\n                                    std::vector<double> &vel_min,  std::vector<double> &vel_max,\n                                    std::vector<double> &damping, std::vector<double> &friction,\n                                    std::vector<double> &max_effort,\n                                    bool floating_base,\n                                    bool planar_floating_base){\n\n  ros::NodeHandle n;\n  std::string urdf_name, full_urdf_xml;\n\n  ROS_INFO_STREAM(\"parsing urdf into rbdl from param server\");\n\n  n.param(\"urdf_xml_model\",urdf_name,std::string(\"robot_description\"));\n  n.searchParam(urdf_name,full_urdf_xml);\n  urdf::Model urdf_model;\n\n  if (!urdf_model.initParam(full_urdf_xml)){\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n\n  ROS_INFO(\"Successfully parsed urdf file\");\n  bool res = parseUrdf(urdf_model, rbdl_model, floating_base, planar_floating_base);\n\n  //We need a link->name to joint->name map;\n\n  unsigned int i=0;\n  if(floating_base){\n    if(planar_floating_base){\n      i = 3;\n    }\n    else{\n      i=6; //Floating base has been added\n    }\n  }\n\n  for(; i< rbdl_model.dof_count; ++i){\n    boost::shared_ptr<urdf::Link> urdf_link;\n    //As the joints, the bodyes with movable joints start ad +1\n    //Since the movable bodies have a small numbering and the fixed bodyes have\n    //a high numbering will get n joint names in the lower numbers\n    std::string body_name = rbdl_model.GetBodyName(i+1);\n\n    ROS_DEBUG_STREAM(\"rbdl body name: \"<<body_name);\n\n    urdf_model.getLink(body_name, urdf_link);\n    joint_names.push_back(urdf_link->parent_joint->name);\n    ROS_DEBUG_STREAM(\" names \"<<urdf_link->parent_joint->name);\n    //Store the joint limits position\n    if ( urdf_link->parent_joint->type != urdf::Joint::CONTINUOUS ) {\n      position_min.push_back(urdf_link->parent_joint->limits->lower);\n      position_max.push_back(urdf_link->parent_joint->limits->upper);\n    }\n    else{\n      position_min.push_back(-3.14);\n      position_max.push_back(3.14);\n    }\n    //Store the joint limits velocity\n    if ( urdf_link->parent_joint->type != urdf::Joint::CONTINUOUS ) {\n      vel_min.push_back(-urdf_link->parent_joint->limits->velocity);\n      vel_max.push_back(urdf_link->parent_joint->limits->velocity);\n    }\n    else{\n      /// Random high value\n      vel_min.push_back(-100.0);\n      vel_max.push_back(100.0);\n    }\n    //Store joint damping\n    if (urdf_link->parent_joint->dynamics) {\n      damping.push_back(urdf_link->parent_joint->dynamics->damping);\n    }\n    else{\n      damping.push_back(0.0);\n    }\n    //Store joint friction\n    if (urdf_link->parent_joint->dynamics) {\n      friction.push_back(urdf_link->parent_joint->dynamics->friction);\n    }\n    else{\n      friction.push_back(0.0);\n    }\n    //Store joint max_effor\n    if (urdf_link->parent_joint->limits) {\n      max_effort.push_back(urdf_link->parent_joint->limits->effort);\n    }\n    else{\n      max_effort.push_back(0.0);\n    }\n\n  }\n  ROS_INFO_STREAM(\"parsed the urdf into rbdl succesfully\");\n  return res;\n\n}\n\n\nbool parseUrdfParamServerParameters(RigidBodyDynamics::Model &rbdl_model, std::vector<std::string> &joint_names,\n                                    std::vector<double> &position_min,  std::vector<double> &position_max,\n                                    std::vector<double> &vel_min,  std::vector<double> &vel_max,\n                                    std::vector<double> &damping, std::vector<double> &friction,\n                                    std::vector<double> &max_effort,\n                                    bool floating_base,\n                                    const std::vector<string> &tip_links,\n                                    bool planar_floating_base){\n\n  ros::NodeHandle n;\n  std::string urdf_name, full_urdf_xml;\n\n  ROS_INFO_STREAM(\"parsing urdf into rbdl from param server\");\n\n  n.param(\"urdf_xml_model\",urdf_name,std::string(\"robot_description\"));\n  n.searchParam(urdf_name,full_urdf_xml);\n  urdf::Model urdf_model;\n\n  if (!urdf_model.initParam(full_urdf_xml)){\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n\n  ROS_INFO(\"Successfully parsed urdf file\");\n  bool res = parseUrdf(urdf_model, rbdl_model, tip_links, floating_base, planar_floating_base);\n\n  //We need a link->name to joint->name map;\n\n  unsigned int i=0;\n  if(floating_base){\n    if(planar_floating_base){\n      i = 3;\n    }\n    else{\n      i = 6; //Floating base has been added\n    }\n  }\n\n  for(; i< rbdl_model.dof_count; ++i){\n    boost::shared_ptr<urdf::Link> urdf_link;\n    //As the joints, the bodyes with movable joints start ad +1\n    //Since the movable bodies have a small numbering and the fixed bodyes have\n    //a high numbering will get n joint names in the lower numbers\n    std::string body_name = rbdl_model.GetBodyName(i+1);\n\n    ROS_DEBUG_STREAM(\"rbdl body name: \"<<body_name);\n\n    urdf_model.getLink(body_name, urdf_link);\n    joint_names.push_back(urdf_link->parent_joint->name);\n    ROS_DEBUG_STREAM(\" names \"<<urdf_link->parent_joint->name);\n    //Store the joint limits position\n    if ( urdf_link->parent_joint->type != urdf::Joint::CONTINUOUS ) {\n      position_min.push_back(urdf_link->parent_joint->limits->lower);\n      position_max.push_back(urdf_link->parent_joint->limits->upper);\n    }\n    else{\n      position_min.push_back(-3.14);\n      position_max.push_back(3.14);\n    }\n    //Store the joint limits velocity\n    if ( urdf_link->parent_joint->type != urdf::Joint::CONTINUOUS ) {\n      vel_min.push_back(-urdf_link->parent_joint->limits->velocity);\n      vel_max.push_back(urdf_link->parent_joint->limits->velocity);\n    }\n    else{\n      /// Random high value\n      vel_min.push_back(-100.0);\n      vel_max.push_back(100.0);\n    }\n    //Store joint damping\n    if (urdf_link->parent_joint->dynamics) {\n      damping.push_back(urdf_link->parent_joint->dynamics->damping);\n    }\n    else{\n      damping.push_back(0.0);\n    }\n    //Store joint friction\n    if (urdf_link->parent_joint->dynamics) {\n      friction.push_back(urdf_link->parent_joint->dynamics->friction);\n    }\n    else{\n      friction.push_back(0.0);\n    }\n    //Store joint max_effor\n    if (urdf_link->parent_joint->limits) {\n      max_effort.push_back(urdf_link->parent_joint->limits->effort);\n    }\n    else{\n      max_effort.push_back(0.0);\n    }\n\n  }\n  ROS_INFO_STREAM(\"parsed the urdf into rbdl succesfully\");\n  return res;\n\n}\n\nbool parseUrdfFromFile(RigidBodyDynamics::Model &rbdl_model,\n                       std::string file_path,\n                       bool floating_base,\n                       bool planar_floating_base){\n  ROS_INFO_STREAM(\"parsing urdf into rbdl from file\");\n\n  urdf::Model urdf_model;\n  if (!urdf_model.initFile(file_path)){\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n  ROS_INFO(\"Successfully parsed urdf file\");\n\n  return parseUrdf(urdf_model, rbdl_model, floating_base, planar_floating_base);\n\n}\n\nbool parseUrdfFromFile(RigidBodyDynamics::Model &rbdl_model, std::vector<std::string> &joint_names,\n                       std::vector<double> &position_min,  std::vector<double> &position_max,\n                       std::vector<double> &vel_min, std::vector<double> &vel_max,\n                       std::vector<double> &damping, std::vector<double> &friction,\n                       std::vector<double> &max_effort,\n                       bool floating_base,\n                       std::string file_path,\n                       bool planar_floating_base){\n\n  ROS_INFO_STREAM(\"parsing urdf into rbdl from file\");\n\n  urdf::Model urdf_model;\n\n  if (!urdf_model.initFile(file_path)){\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return false;\n  }\n\n  ROS_INFO(\"Successfully parsed urdf file\");\n  bool res = parseUrdf(urdf_model, rbdl_model, floating_base, planar_floating_base);\n\n  unsigned int i=0;\n  if(floating_base){\n    if(planar_floating_base){\n      i = 3;\n    }\n    else{\n      i = 6; //Floating base has been added\n    }\n  }\n  for(; i< rbdl_model.dof_count; ++i){\n    boost::shared_ptr<urdf::Link> urdf_link;\n    //As the joints, the bodyes with movable joints start ad +1\n    //Since the movable bodies have a small numbering and the fixed bodyes have\n    //a high numbering will get n joint names in the lower numbers\n    std::string body_name = rbdl_model.GetBodyName(i+1);\n\n    ROS_DEBUG_STREAM(\"rbdl body name: \"<<body_name);\n\n    urdf_model.getLink(body_name, urdf_link);\n    joint_names.push_back(urdf_link->parent_joint->name);\n    ROS_DEBUG_STREAM(\" names \"<<urdf_link->parent_joint->name);\n    //Store the joint limits position\n    if ( urdf_link->parent_joint->type != urdf::Joint::CONTINUOUS ) {\n      position_min.push_back(urdf_link->parent_joint->limits->lower);\n      position_max.push_back(urdf_link->parent_joint->limits->upper);\n    }\n    else{\n      position_min.push_back(-3.14);\n      position_max.push_back(3.14);\n    }\n    //Store the joint limits velocity\n    if ( urdf_link->parent_joint->type != urdf::Joint::CONTINUOUS ) {\n      vel_min.push_back(-urdf_link->parent_joint->limits->velocity);\n      vel_max.push_back(urdf_link->parent_joint->limits->velocity);\n    }\n    else{\n      /// Random high value\n      vel_min.push_back(-100.0);\n      vel_max.push_back(100.0);\n    }\n    //Store joint damping\n    if (urdf_link->parent_joint->dynamics) {\n      damping.push_back(urdf_link->parent_joint->dynamics->damping);\n    }\n    else{\n      damping.push_back(0.0);\n    }\n    //Store joint friction\n    if (urdf_link->parent_joint->dynamics) {\n      friction.push_back(urdf_link->parent_joint->dynamics->friction);\n    }\n    else{\n      friction.push_back(0.0);\n    }\n    //Store joint max_effor\n    if (urdf_link->parent_joint->limits) {\n      max_effort.push_back(urdf_link->parent_joint->limits->effort);\n    }\n    else{\n      max_effort.push_back(0.0);\n    }\n\n  }\n  ROS_INFO_STREAM(\"parsed the urdf into rbdl succesfully\");\n  return res;\n\n}\n\n\nRigidBodyDynamics::Model getSubTree(RigidBodyDynamics::Model &rbdl_model, const std::vector<string> &tips, std::string root){\n  RigidBodyDynamics::Model subtree;\n\n  ROS_ERROR_STREAM(\"not implemented\");\n\n  return subtree;\n}\n\n/* Function to publish the poses of all the links inside the model */\n/*\nvoid publish_link_poses(RigidBodyDynamics::Model &model){\n   ros::NodeHandle n;\n  static tf::TransformBroadcaster br;\n\n  VectorNd Q (VectorNd::Zero(model.dof_count));\n // UpdateKinematicsCustom (model, &Q, NULL, NULL);\n\n  for (unsigned int body_id = 0; body_id < model.mBodies.size(); body_id++) {\n    std::string body_name = model.GetBodyName (body_id);\n    if (body_name.size() == 0)\n      continue;\n\n    Vector3d position = CalcBodyToBaseCoordinates (model, Q, body_id, Vector3d (0., 0., 0.), false);\n    Eigen::Matrix3d orientation = RigidBodyDynamics::CalcBodyWorldOrientation(model, Q, body_id,  false).transpose();\n    Eigen::Quaterniond quaternion (orientation);\n\n\n    tf::Transform transform;\n    transform.setOrigin( tf::Vector3(position[0],\n                                     position[1],\n                                     position[2]) );\n\n    transform.setRotation( tf::Quaternion(quaternion.x(),\n                                          quaternion.y(),\n                                          quaternion.z(),\n                                          quaternion.w()) );\n    br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), \"world\", body_name + \"rbdl\"));\n\n  }\n}\n\n\nvoid publish_link_com_poses(RigidBodyDynamics::Model &model){\n   ros::NodeHandle n;\n  static tf::TransformBroadcaster br;\n\n  VectorNd Q (VectorNd::Zero(model.dof_count));\n // UpdateKinematicsCustom (model, &Q, NULL, NULL);\n\n  for (unsigned int body_id = 0; body_id < model.mBodies.size(); body_id++) {\n    std::string body_name = model.GetBodyName (body_id);\n    if (body_name.size() == 0)\n      continue;\n\n    Vector3d position = RigidBodyDynamics::CalcBodyToBaseCoordinates(model, Q, body_id, model.mBodies[body_id].mCenterOfMass, false);\n\n    //Vector3d position = CalcBodyToBaseCoordinates (model, Q, body_id, Vector3d (0., 0., 0.), false);\n    Eigen::Matrix3d orientation = RigidBodyDynamics::CalcBodyWorldOrientation(model, Q, body_id,  false).transpose();\n    Eigen::Quaterniond quaternion (orientation);\n\n\n    tf::Transform transform;\n    transform.setOrigin( tf::Vector3(position[0],\n                                     position[1],\n                                     position[2]) );\n\n    transform.setRotation( tf::Quaternion(quaternion.x(),\n                                          quaternion.y(),\n                                          quaternion.z(),\n                                          quaternion.w()) );\n    br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), \"world\", body_name + \"_COM_rbdl\"));\n\n  }\n}\n*/\n", "meta": {"hexsha": "96ff564a26f047ef2d133266377efb26e21f5fdd", "size": 29660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/urdfreader/RBDL_URDFParser.cpp", "max_stars_repo_name": "pal-robotics-forks/rbdl", "max_stars_repo_head_hexsha": "5fb8ecc02bad3b2533e4b2957fea7378728f8f40", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T13:27:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T14:33:08.000Z", "max_issues_repo_path": "addons/urdfreader/RBDL_URDFParser.cpp", "max_issues_repo_name": "pal-robotics-forks/rbdl", "max_issues_repo_head_hexsha": "5fb8ecc02bad3b2533e4b2957fea7378728f8f40", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "addons/urdfreader/RBDL_URDFParser.cpp", "max_forks_repo_name": "pal-robotics-forks/rbdl", "max_forks_repo_head_hexsha": "5fb8ecc02bad3b2533e4b2957fea7378728f8f40", "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": 36.1266747868, "max_line_length": 133, "alphanum_fraction": 0.6552258935, "num_tokens": 7968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18160224616504209}}
{"text": "/*\n\nCopyright (c) 2005-2017, 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 CorriasBuistSMCModified_HPP_\n#define CorriasBuistSMCModified_HPP_\n\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"AbstractCardiacCell.hpp\"\n#include \"AbstractStimulusFunction.hpp\"\n/**\n * This class is a modified version of the model of a gastric\n * Smooth Muscle Cell.\n *\n * Reference publication is:\n *\n * Corrias A, Buist ML.\n * \"A quantitative model of gastric smooth muscle cellular activation.\"\n * Ann Biomed Eng. 2007 Sep;35(9):1595-607. Epub 2007 May 8.\n *\n * Modifications include:\n * - ability to include/exclude built-in fake ICC stimulus\n * - ability to set K+ channels-affecting CO concentrations\n */\nclass CorriasBuistSMCModified : public AbstractCardiacCell\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<AbstractCardiacCell >(*this);\n    }\n\nprivate:\n\n    /**\n     * Scale factor for CO-affected currents\n     * Note that this the number that multiply the currents, hence it is not [CO],\n     * but a function of [CO] (for example, 2.8*[CO] - 0.1)\n     */\n    double mScaleFactorCarbonMonoxide;\n\n    /**\n     * True if the fake built-in ICC stimulus is present\n     */\n    bool mFakeIccStimulusPresent;\n\n    double Cm;/**< membrane capacitance, pF*/\n\n    double Asurf_in_cm_square;/**< Surface area in cm^2*/\n    double Asurf;/**< surface area (mm^2)*/\n\n    double VolCell;/**< cell volume (mm^3)*/\n    double hCa;/**< conc for half inactivation of fCa */\n    double sCa;/**< lope factor for inactivation of fCa */\n\n    /* concentrations */\n    double Ki;       /**< intra K conc (mM)*/\n    double Nai;        /**< intra Na conc (mM)*/\n    double ACh;       /**< acetylcholine conc (mM)*/\n    double CaiRest;     /**< baseline Ca conc (mM)*/\n\n    /* maximum conductances*/\n    double gLVA_max; /**< max conductance of ILVA*/                 // (0.18 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double gCaL_max; /**< max conductance of ICaL*/                 // (65.0 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double gBK_max; /**< max conductance of IBK)*/                 // (45.7 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double gKb_max; /**< max conductance of IKb*/                  // (0.0144 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double gKA_max; /**< max conductance of IKA*/                  // (9.0  nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double gKr_max; /**< max conductance of IKr*/                  // (35.0 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double gNa_max;  /**< max conductance of INa*/                  // (3.0  nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double gnsCC_max; /**< max conductance of InsCC*/                // (50.0 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double gcouple;   /**<  coupling conductance bewteen fake ICC and SMC*/        // 1.3 nS * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n    double JCaExt_max;     /**< max flux of CaSR (mM/ms)*/\n\n    /* Temperature corrections */\n    double Q10Ca;         /**< (dim)*/\n    double Q10K;         /**< (dim)*/ //1.365\n    double Q10Na;        /**< (dim)*/\n    double Texp;       /**< (degK)*/\n\n    double T_correct_Ca ;/**< temperature correction for Ca (dim)*/\n    double T_correct_K ;  /**< temperature correction for K (dim)*/\n    double T_correct_Na;/**< temperature correction for Na (dim)*/\n    double T_correct_gBK; /**< temperature correction for gBK*/  // (nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2\n\n    /* Nernst potentials */\n    double EK;                  /**< Nernst potential for K (mV)*/\n    double ENa ;               /**< Nernst potential for Na (mV)*/\n    double EnsCC;                          /**< Nernst potential for nsCC (mV)*/\n\n    double Ca_o;         /**<  mM */\n    double K_o;          /**< mM */\n    double Na_o;         /**< mM */\n\n    /* Nernst parameters */\n    double R;    /**<  pJ/nmol/K*/\n    double T;       /**<  degK*/\n    double F;     /**<  nC/nmol*/\n    double FoRT;     /**<  1/mV*/\n    double RToF;    /**<  mV*/\n\npublic:\n\n    /**\n     * Constructor\n     *\n     * @param pSolver is a pointer to the ODE solver\n     * @param pIntracellularStimulus is a pointer to the intracellular stimulus\n     */\n    CorriasBuistSMCModified(boost::shared_ptr<AbstractIvpOdeSolver> pSolver, boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus);\n\n    /**\n     * Destructor\n     */\n    ~CorriasBuistSMCModified();\n\n    /**\n     * Now empty\n     */\n    void VerifyStateVariables();\n\n    /**\n     * Calculates the ionic current\n     *\n     * @param pStateVariables the state variables of this model\n     * @return the total ionic current\n     */\n    double GetIIonic(const std::vector<double>* pStateVariables=NULL);\n\n    /**\n     * Compute the RHS of the FitHugh-Nagumo system of ODEs\n     *\n     * @param time  the current time, in milliseconds\n     * @param rY  current values of the state variables\n     * @param rDY  to be filled in with derivatives\n     */\n    void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY);\n\n\n    /**\n     * Set whether we want the fake ICC stimulus or not.\n     * It changes the member variable mFakeIccStimulusPresent (which is true by default).\n     *\n     * @param present - true if we want the fake ICC stimulus, false otherwise\n     */\n    void SetFakeIccStimulusPresent(bool present);\n\n    /**\n     * @return true if the fake ICC stimulus is present\n     */\n    bool GetFakeIccStimulusPresent();\n\n    /**\n     * @return the Carbon Monoxide scale for\n     */\n    double SetCarbonMonoxideScaleFactor();\n\n    /**\n     * Set the carbon monoxide scale factor.\n     * This will multiply the following currents: I_kr, I_Ka, Ibk\n     *\n     * @param scaleFactor the scale factor that multiply the currents.\n     */\n    void SetCarbonMonoxideScaleFactor(double scaleFactor);\n\n    /**\n     * @return the Carbon Monoxide scale factor\n     */\n    double GetCarbonMonoxideScaleFactor();\n};\n\n// Needs to be included last\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(CorriasBuistSMCModified)\n\nnamespace boost\n{\n    namespace serialization\n    {\n        template<class Archive>\n        inline void save_construct_data(\n            Archive & ar, const CorriasBuistSMCModified * t, const unsigned int fileVersion)\n        {\n            const boost::shared_ptr<AbstractIvpOdeSolver> p_solver = t->GetSolver();\n            const boost::shared_ptr<AbstractStimulusFunction> p_stimulus = t->GetStimulusFunction();\n            ar << p_solver;\n            ar << p_stimulus;\n        }\n\n        template<class Archive>\n        inline void load_construct_data(\n            Archive & ar, CorriasBuistSMCModified * t, const unsigned int fileVersion)\n        {\n            boost::shared_ptr<AbstractIvpOdeSolver> p_solver;\n            boost::shared_ptr<AbstractStimulusFunction> p_stimulus;\n            ar >> p_solver;\n            ar >> p_stimulus;\n            ::new(t)CorriasBuistSMCModified(p_solver, p_stimulus);\n        }\n    }\n}\n\n#endif // CorriasBuistSMCModified_HPP_\n", "meta": {"hexsha": "a3731f4deb0b3663ff540ec5c59f85736d3f5dc9", "size": 9077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/odes/ionicmodels/noncardiac/CorriasBuistSMCModified.hpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": "heart/src/odes/ionicmodels/noncardiac/CorriasBuistSMCModified.hpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": "heart/src/odes/ionicmodels/noncardiac/CorriasBuistSMCModified.hpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "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": 37.2008196721, "max_line_length": 145, "alphanum_fraction": 0.6477911204, "num_tokens": 2371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18160224616504209}}
{"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// File generated at Sat 27 Aug 2016 12:48:00\n\n#ifndef MSSMatMGUT_INPUT_PARAMETERS_H\n#define MSSMatMGUT_INPUT_PARAMETERS_H\n\n#include <complex>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nstruct MSSMatMGUT_input_parameters {\n   double TanBeta;\n   int SignMu;\n   double mHd2IN;\n   double mHu2IN;\n   Eigen::Matrix<double,3,3> Aeij;\n   Eigen::Matrix<double,3,3> Adij;\n   Eigen::Matrix<double,3,3> Auij;\n   Eigen::Matrix<double,3,3> mq2Input;\n   Eigen::Matrix<double,3,3> ml2Input;\n   Eigen::Matrix<double,3,3> md2Input;\n   Eigen::Matrix<double,3,3> mu2Input;\n   Eigen::Matrix<double,3,3> me2Input;\n   double MassBInput;\n   double MassWBInput;\n   double MassGInput;\n\n   MSSMatMGUT_input_parameters()\n      : TanBeta(0), SignMu(1), mHd2IN(0), mHu2IN(0), Aeij(Eigen::Matrix<double,3,3\n   >::Zero()), Adij(Eigen::Matrix<double,3,3>::Zero()), Auij(Eigen::Matrix<\n   double,3,3>::Zero()), mq2Input(Eigen::Matrix<double,3,3>::Zero()), ml2Input(\n   Eigen::Matrix<double,3,3>::Zero()), md2Input(Eigen::Matrix<double,3,3>::Zero\n   ()), mu2Input(Eigen::Matrix<double,3,3>::Zero()), me2Input(Eigen::Matrix<\n   double,3,3>::Zero()), MassBInput(0), MassWBInput(0), MassGInput(0)\n\n   {}\n\n   Eigen::ArrayXd get() const;\n   void set(const Eigen::ArrayXd&);\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMatMGUT_input_parameters&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "6097e17a30ed96314413be398542631503c1c000", "size": 2194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMatMGUT/MSSMatMGUT_input_parameters.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/models/MSSMatMGUT/MSSMatMGUT_input_parameters.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/models/MSSMatMGUT/MSSMatMGUT_input_parameters.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": 33.7538461538, "max_line_length": 82, "alphanum_fraction": 0.6649954421, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.18159080642804998}}
{"text": "#include \"engine/routing_algorithms/alternative_path.hpp\"\n#include \"engine/routing_algorithms/routing_base_ch.hpp\"\n\n#include \"util/integer_range.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <algorithm>\n#include <iterator>\n#include <memory>\n#include <unordered_set>\n#include <vector>\n\nnamespace osrm\n{\nnamespace engine\n{\nnamespace routing_algorithms\n{\n\n// Unqualified calls below are from the ch namespace.\n// This alternative implementation works only for ch.\nusing namespace ch;\n\nnamespace\n{\nconst double constexpr VIAPATH_ALPHA = 0.25;   // alternative is local optimum on 25% sub-paths\nconst double constexpr VIAPATH_EPSILON = 0.15; // alternative at most 15% longer\nconst double constexpr VIAPATH_GAMMA = 0.75;   // alternative shares at most 75% with the shortest.\n\nusing QueryHeap = SearchEngineData<Algorithm>::QueryHeap;\nusing SearchSpaceEdge = std::pair<NodeID, NodeID>;\n\nstruct RankedCandidateNode\n{\n    RankedCandidateNode(const NodeID node, const EdgeWeight weight, const EdgeWeight sharing)\n        : node(node), weight(weight), sharing(sharing)\n    {\n    }\n\n    NodeID node;\n    EdgeWeight weight;\n    EdgeWeight sharing;\n\n    bool operator<(const RankedCandidateNode &other) const\n    {\n        return (2 * weight + sharing) < (2 * other.weight + other.sharing);\n    }\n};\n\n// todo: reorder parameters\ntemplate <bool DIRECTION>\nvoid alternativeRoutingStep(const DataFacade<Algorithm> &facade,\n                            QueryHeap &heap1,\n                            QueryHeap &heap2,\n                            NodeID *middle_node,\n                            EdgeWeight *upper_bound_to_shortest_path_weight,\n                            std::vector<NodeID> &search_space_intersection,\n                            std::vector<SearchSpaceEdge> &search_space,\n                            const EdgeWeight min_edge_offset)\n{\n    QueryHeap &forward_heap = DIRECTION == FORWARD_DIRECTION ? heap1 : heap2;\n    QueryHeap &reverse_heap = DIRECTION == FORWARD_DIRECTION ? heap2 : heap1;\n\n    const NodeID node = forward_heap.DeleteMin();\n    const EdgeWeight weight = forward_heap.GetKey(node);\n\n    const auto scaled_weight =\n        static_cast<EdgeWeight>((weight + min_edge_offset) / (1. + VIAPATH_EPSILON));\n    if ((INVALID_EDGE_WEIGHT != *upper_bound_to_shortest_path_weight) &&\n        (scaled_weight > *upper_bound_to_shortest_path_weight))\n    {\n        forward_heap.DeleteAll();\n        return;\n    }\n\n    search_space.emplace_back(forward_heap.GetData(node).parent, node);\n\n    if (reverse_heap.WasInserted(node))\n    {\n        search_space_intersection.emplace_back(node);\n        const EdgeWeight new_weight = reverse_heap.GetKey(node) + weight;\n        if (new_weight < *upper_bound_to_shortest_path_weight)\n        {\n            if (new_weight >= 0)\n            {\n                *middle_node = node;\n                *upper_bound_to_shortest_path_weight = new_weight;\n            }\n            else\n            {\n                // check whether there is a loop present at the node\n                const auto loop_weight = std::get<0>(getLoopWeight<false>(facade, node));\n                const EdgeWeight new_weight_with_loop = new_weight + loop_weight;\n                if (loop_weight != INVALID_EDGE_WEIGHT &&\n                    new_weight_with_loop <= *upper_bound_to_shortest_path_weight)\n                {\n                    *middle_node = node;\n                    *upper_bound_to_shortest_path_weight = loop_weight;\n                }\n            }\n        }\n    }\n\n    for (auto edge : facade.GetAdjacentEdgeRange(node))\n    {\n        const auto &data = facade.GetEdgeData(edge);\n        if (DIRECTION == FORWARD_DIRECTION ? data.forward : data.backward)\n        {\n            const NodeID to = facade.GetTarget(edge);\n            const EdgeWeight edge_weight = data.weight;\n\n            BOOST_ASSERT(edge_weight > 0);\n            const EdgeWeight to_weight = weight + edge_weight;\n\n            // New Node discovered -> Add to Heap + Node Info Storage\n            if (!forward_heap.WasInserted(to))\n            {\n                forward_heap.Insert(to, to_weight, node);\n            }\n            // Found a shorter Path -> Update weight\n            else if (to_weight < forward_heap.GetKey(to))\n            {\n                // new parent\n                forward_heap.GetData(to).parent = node;\n                // decreased weight\n                forward_heap.DecreaseKey(to, to_weight);\n            }\n        }\n    }\n}\n\nvoid retrievePackedAlternatePath(const QueryHeap &forward_heap1,\n                                 const QueryHeap &reverse_heap1,\n                                 const QueryHeap &forward_heap2,\n                                 const QueryHeap &reverse_heap2,\n                                 const NodeID s_v_middle,\n                                 const NodeID v_t_middle,\n                                 std::vector<NodeID> &packed_path)\n{\n    // fetch packed path [s,v)\n    std::vector<NodeID> packed_v_t_path;\n    retrievePackedPathFromHeap(forward_heap1, reverse_heap2, s_v_middle, packed_path);\n    packed_path.pop_back(); // remove middle node. It's in both half-paths\n\n    // fetch patched path [v,t]\n    retrievePackedPathFromHeap(forward_heap2, reverse_heap1, v_t_middle, packed_v_t_path);\n\n    packed_path.insert(packed_path.end(), packed_v_t_path.begin(), packed_v_t_path.end());\n}\n\n// TODO: reorder parameters\n// compute and unpack <s,..,v> and <v,..,t> by exploring search spaces\n// from v and intersecting against queues. only half-searches have to be\n// done at this stage\nvoid computeWeightAndSharingOfViaPath(SearchEngineData<Algorithm> &engine_working_data,\n                                      const DataFacade<Algorithm> &facade,\n                                      const NodeID via_node,\n                                      EdgeWeight *real_weight_of_via_path,\n                                      EdgeWeight *sharing_of_via_path,\n                                      const std::vector<NodeID> &packed_shortest_path,\n                                      const EdgeWeight min_edge_offset)\n{\n    engine_working_data.InitializeOrClearSecondThreadLocalStorage(facade.GetNumberOfNodes());\n\n    auto &existing_forward_heap = *engine_working_data.forward_heap_1;\n    auto &existing_reverse_heap = *engine_working_data.reverse_heap_1;\n    auto &new_forward_heap = *engine_working_data.forward_heap_2;\n    auto &new_reverse_heap = *engine_working_data.reverse_heap_2;\n\n    std::vector<NodeID> packed_s_v_path;\n    std::vector<NodeID> packed_v_t_path;\n\n    std::vector<NodeID> partially_unpacked_shortest_path;\n    std::vector<NodeID> partially_unpacked_via_path;\n\n    NodeID s_v_middle = SPECIAL_NODEID;\n    EdgeWeight upper_bound_s_v_path_weight = INVALID_EDGE_WEIGHT;\n    new_reverse_heap.Insert(via_node, 0, via_node);\n    // compute path <s,..,v> by reusing forward search from s\n    while (!new_reverse_heap.Empty())\n    {\n        routingStep<REVERSE_DIRECTION>(facade,\n                                       new_reverse_heap,\n                                       existing_forward_heap,\n                                       s_v_middle,\n                                       upper_bound_s_v_path_weight,\n                                       min_edge_offset,\n                                       DO_NOT_FORCE_LOOPS,\n                                       DO_NOT_FORCE_LOOPS);\n    }\n    // compute path <v,..,t> by reusing backward search from node t\n    NodeID v_t_middle = SPECIAL_NODEID;\n    EdgeWeight upper_bound_of_v_t_path_weight = INVALID_EDGE_WEIGHT;\n    new_forward_heap.Insert(via_node, 0, via_node);\n    while (!new_forward_heap.Empty())\n    {\n        routingStep<FORWARD_DIRECTION>(facade,\n                                       new_forward_heap,\n                                       existing_reverse_heap,\n                                       v_t_middle,\n                                       upper_bound_of_v_t_path_weight,\n                                       min_edge_offset,\n                                       DO_NOT_FORCE_LOOPS,\n                                       DO_NOT_FORCE_LOOPS);\n    }\n    *real_weight_of_via_path = upper_bound_s_v_path_weight + upper_bound_of_v_t_path_weight;\n\n    if (SPECIAL_NODEID == s_v_middle || SPECIAL_NODEID == v_t_middle)\n    {\n        return;\n    }\n\n    // retrieve packed paths\n    retrievePackedPathFromHeap(\n        existing_forward_heap, new_reverse_heap, s_v_middle, packed_s_v_path);\n    retrievePackedPathFromHeap(\n        new_forward_heap, existing_reverse_heap, v_t_middle, packed_v_t_path);\n\n    // partial unpacking, compute sharing\n    // First partially unpack s-->v until paths deviate, note length of common path.\n    const auto s_v_min_path_size =\n        std::min(packed_s_v_path.size(), packed_shortest_path.size()) - 1;\n    for (const auto current_node : util::irange<std::size_t>(0UL, s_v_min_path_size))\n    {\n        if (packed_s_v_path[current_node] == packed_shortest_path[current_node] &&\n            packed_s_v_path[current_node + 1] == packed_shortest_path[current_node + 1])\n        {\n            EdgeID edgeID = facade.FindEdgeInEitherDirection(packed_s_v_path[current_node],\n                                                             packed_s_v_path[current_node + 1]);\n            *sharing_of_via_path += facade.GetEdgeData(edgeID).weight;\n        }\n        else\n        {\n            if (packed_s_v_path[current_node] == packed_shortest_path[current_node])\n            {\n                unpackEdge(facade,\n                           packed_s_v_path[current_node],\n                           packed_s_v_path[current_node + 1],\n                           partially_unpacked_via_path);\n                unpackEdge(facade,\n                           packed_shortest_path[current_node],\n                           packed_shortest_path[current_node + 1],\n                           partially_unpacked_shortest_path);\n                break;\n            }\n        }\n    }\n    // traverse partially unpacked edge and note common prefix\n    const int64_t packed_path_length =\n        static_cast<int64_t>(\n            std::min(partially_unpacked_via_path.size(), partially_unpacked_shortest_path.size())) -\n        1;\n    for (int64_t current_node = 0; (current_node < packed_path_length) &&\n                                   (partially_unpacked_via_path[current_node] ==\n                                        partially_unpacked_shortest_path[current_node] &&\n                                    partially_unpacked_via_path[current_node + 1] ==\n                                        partially_unpacked_shortest_path[current_node + 1]);\n         ++current_node)\n    {\n        EdgeID selected_edge =\n            facade.FindEdgeInEitherDirection(partially_unpacked_via_path[current_node],\n                                             partially_unpacked_via_path[current_node + 1]);\n        *sharing_of_via_path += facade.GetEdgeData(selected_edge).weight;\n    }\n\n    // Second, partially unpack v-->t in reverse order until paths deviate and note lengths\n    int64_t via_path_index = static_cast<int64_t>(packed_v_t_path.size()) - 1;\n    int64_t shortest_path_index = static_cast<int64_t>(packed_shortest_path.size()) - 1;\n    for (; via_path_index > 0 && shortest_path_index > 0; --via_path_index, --shortest_path_index)\n    {\n        if (packed_v_t_path[via_path_index - 1] == packed_shortest_path[shortest_path_index - 1] &&\n            packed_v_t_path[via_path_index] == packed_shortest_path[shortest_path_index])\n        {\n            EdgeID edgeID = facade.FindEdgeInEitherDirection(packed_v_t_path[via_path_index - 1],\n                                                             packed_v_t_path[via_path_index]);\n            *sharing_of_via_path += facade.GetEdgeData(edgeID).weight;\n        }\n        else\n        {\n            if (packed_v_t_path[via_path_index] == packed_shortest_path[shortest_path_index])\n            {\n                unpackEdge(facade,\n                           packed_v_t_path[via_path_index - 1],\n                           packed_v_t_path[via_path_index],\n                           partially_unpacked_via_path);\n                unpackEdge(facade,\n                           packed_shortest_path[shortest_path_index - 1],\n                           packed_shortest_path[shortest_path_index],\n                           partially_unpacked_shortest_path);\n                break;\n            }\n        }\n    }\n\n    via_path_index = static_cast<int64_t>(partially_unpacked_via_path.size()) - 1;\n    shortest_path_index = static_cast<int64_t>(partially_unpacked_shortest_path.size()) - 1;\n    for (; via_path_index > 0 && shortest_path_index > 0; --via_path_index, --shortest_path_index)\n    {\n        if (partially_unpacked_via_path[via_path_index - 1] ==\n                partially_unpacked_shortest_path[shortest_path_index - 1] &&\n            partially_unpacked_via_path[via_path_index] ==\n                partially_unpacked_shortest_path[shortest_path_index])\n        {\n            EdgeID edgeID =\n                facade.FindEdgeInEitherDirection(partially_unpacked_via_path[via_path_index - 1],\n                                                 partially_unpacked_via_path[via_path_index]);\n            *sharing_of_via_path += facade.GetEdgeData(edgeID).weight;\n        }\n        else\n        {\n            break;\n        }\n    }\n    // finished partial unpacking spree! Amount of sharing is stored to appropriate pointer\n    // variable\n}\n\n// conduct T-Test\nbool viaNodeCandidatePassesTTest(SearchEngineData<Algorithm> &engine_working_data,\n                                 const DataFacade<Algorithm> &facade,\n                                 QueryHeap &existing_forward_heap,\n                                 QueryHeap &existing_reverse_heap,\n                                 QueryHeap &new_forward_heap,\n                                 QueryHeap &new_reverse_heap,\n                                 const RankedCandidateNode &candidate,\n                                 const EdgeWeight weight_of_shortest_path,\n                                 EdgeWeight *weight_of_via_path,\n                                 NodeID *s_v_middle,\n                                 NodeID *v_t_middle,\n                                 const EdgeWeight min_edge_offset)\n{\n    new_forward_heap.Clear();\n    new_reverse_heap.Clear();\n    std::vector<NodeID> packed_s_v_path;\n    std::vector<NodeID> packed_v_t_path;\n\n    *s_v_middle = SPECIAL_NODEID;\n    EdgeWeight upper_bound_s_v_path_weight = INVALID_EDGE_WEIGHT;\n    // compute path <s,..,v> by reusing forward search from s\n    new_reverse_heap.Insert(candidate.node, 0, candidate.node);\n    while (new_reverse_heap.Size() > 0)\n    {\n        routingStep<REVERSE_DIRECTION>(facade,\n                                       new_reverse_heap,\n                                       existing_forward_heap,\n                                       *s_v_middle,\n                                       upper_bound_s_v_path_weight,\n                                       min_edge_offset,\n                                       DO_NOT_FORCE_LOOPS,\n                                       DO_NOT_FORCE_LOOPS);\n    }\n\n    if (INVALID_EDGE_WEIGHT == upper_bound_s_v_path_weight)\n    {\n        return false;\n    }\n\n    // compute path <v,..,t> by reusing backward search from t\n    *v_t_middle = SPECIAL_NODEID;\n    EdgeWeight upper_bound_of_v_t_path_weight = INVALID_EDGE_WEIGHT;\n    new_forward_heap.Insert(candidate.node, 0, candidate.node);\n    while (new_forward_heap.Size() > 0)\n    {\n        routingStep<FORWARD_DIRECTION>(facade,\n                                       new_forward_heap,\n                                       existing_reverse_heap,\n                                       *v_t_middle,\n                                       upper_bound_of_v_t_path_weight,\n                                       min_edge_offset,\n                                       DO_NOT_FORCE_LOOPS,\n                                       DO_NOT_FORCE_LOOPS);\n    }\n\n    if (INVALID_EDGE_WEIGHT == upper_bound_of_v_t_path_weight)\n    {\n        return false;\n    }\n\n    *weight_of_via_path = upper_bound_s_v_path_weight + upper_bound_of_v_t_path_weight;\n\n    // retrieve packed paths\n    retrievePackedPathFromHeap(\n        existing_forward_heap, new_reverse_heap, *s_v_middle, packed_s_v_path);\n\n    retrievePackedPathFromHeap(\n        new_forward_heap, existing_reverse_heap, *v_t_middle, packed_v_t_path);\n\n    NodeID s_P = *s_v_middle, t_P = *v_t_middle;\n    if (SPECIAL_NODEID == s_P)\n    {\n        return false;\n    }\n\n    if (SPECIAL_NODEID == t_P)\n    {\n        return false;\n    }\n    const EdgeWeight T_threshold = static_cast<EdgeWeight>(VIAPATH_ALPHA * weight_of_shortest_path);\n    EdgeWeight unpacked_until_weight = 0;\n\n    std::stack<SearchSpaceEdge> unpack_stack;\n    // Traverse path s-->v\n    for (std::size_t i = packed_s_v_path.size() - 1; (i > 0) && unpack_stack.empty(); --i)\n    {\n        const EdgeID current_edge_id =\n            facade.FindEdgeInEitherDirection(packed_s_v_path[i - 1], packed_s_v_path[i]);\n        const EdgeWeight weight_of_current_edge = facade.GetEdgeData(current_edge_id).weight;\n        if ((weight_of_current_edge + unpacked_until_weight) >= T_threshold)\n        {\n            unpack_stack.emplace(packed_s_v_path[i - 1], packed_s_v_path[i]);\n        }\n        else\n        {\n            unpacked_until_weight += weight_of_current_edge;\n            s_P = packed_s_v_path[i - 1];\n        }\n    }\n\n    while (!unpack_stack.empty())\n    {\n        const SearchSpaceEdge via_path_edge = unpack_stack.top();\n        unpack_stack.pop();\n        EdgeID edge_in_via_path_id =\n            facade.FindEdgeInEitherDirection(via_path_edge.first, via_path_edge.second);\n\n        if (SPECIAL_EDGEID == edge_in_via_path_id)\n        {\n            return false;\n        }\n\n        const auto &current_edge_data = facade.GetEdgeData(edge_in_via_path_id);\n        const bool current_edge_is_shortcut = current_edge_data.shortcut;\n        if (current_edge_is_shortcut)\n        {\n            const NodeID via_path_middle_node_id = current_edge_data.turn_id;\n            const EdgeID second_segment_edge_id =\n                facade.FindEdgeInEitherDirection(via_path_middle_node_id, via_path_edge.second);\n            const auto second_segment_weight = facade.GetEdgeData(second_segment_edge_id).weight;\n            // attention: !unpacking in reverse!\n            // Check if second segment is the one to go over treshold? if yes add second segment\n            // to stack, else push first segment to stack and add weight of second one.\n            if (unpacked_until_weight + second_segment_weight >= T_threshold)\n            {\n                unpack_stack.emplace(via_path_middle_node_id, via_path_edge.second);\n            }\n            else\n            {\n                unpacked_until_weight += second_segment_weight;\n                unpack_stack.emplace(via_path_edge.first, via_path_middle_node_id);\n            }\n        }\n        else\n        {\n            // edge is not a shortcut, set the start node for T-Test to end of edge.\n            unpacked_until_weight += current_edge_data.weight;\n            s_P = via_path_edge.first;\n        }\n    }\n\n    EdgeWeight t_test_path_weight = unpacked_until_weight;\n    unpacked_until_weight = 0;\n    // Traverse path s-->v\n    BOOST_ASSERT(!packed_v_t_path.empty());\n    for (unsigned i = 0, packed_path_length = static_cast<unsigned>(packed_v_t_path.size() - 1);\n         (i < packed_path_length) && unpack_stack.empty();\n         ++i)\n    {\n        const EdgeID edgeID =\n            facade.FindEdgeInEitherDirection(packed_v_t_path[i], packed_v_t_path[i + 1]);\n        auto weight_of_current_edge = facade.GetEdgeData(edgeID).weight;\n        if (weight_of_current_edge + unpacked_until_weight >= T_threshold)\n        {\n            unpack_stack.emplace(packed_v_t_path[i], packed_v_t_path[i + 1]);\n        }\n        else\n        {\n            unpacked_until_weight += weight_of_current_edge;\n            t_P = packed_v_t_path[i + 1];\n        }\n    }\n\n    while (!unpack_stack.empty())\n    {\n        const SearchSpaceEdge via_path_edge = unpack_stack.top();\n        unpack_stack.pop();\n        EdgeID edge_in_via_path_id =\n            facade.FindEdgeInEitherDirection(via_path_edge.first, via_path_edge.second);\n        if (SPECIAL_EDGEID == edge_in_via_path_id)\n        {\n            return false;\n        }\n\n        const auto &current_edge_data = facade.GetEdgeData(edge_in_via_path_id);\n        const bool IsViaEdgeShortCut = current_edge_data.shortcut;\n        if (IsViaEdgeShortCut)\n        {\n            const NodeID middleOfViaPath = current_edge_data.turn_id;\n            EdgeID edgeIDOfFirstSegment =\n                facade.FindEdgeInEitherDirection(via_path_edge.first, middleOfViaPath);\n            auto weightOfFirstSegment = facade.GetEdgeData(edgeIDOfFirstSegment).weight;\n            // Check if first segment is the one to go over treshold? if yes first segment to\n            // stack, else push second segment to stack and add weight of first one.\n            if (unpacked_until_weight + weightOfFirstSegment >= T_threshold)\n            {\n                unpack_stack.emplace(via_path_edge.first, middleOfViaPath);\n            }\n            else\n            {\n                unpacked_until_weight += weightOfFirstSegment;\n                unpack_stack.emplace(middleOfViaPath, via_path_edge.second);\n            }\n        }\n        else\n        {\n            // edge is not a shortcut, set the start node for T-Test to end of edge.\n            unpacked_until_weight += current_edge_data.weight;\n            t_P = via_path_edge.second;\n        }\n    }\n\n    t_test_path_weight += unpacked_until_weight;\n    // Run actual T-Test query and compare if weight equal.\n    engine_working_data.InitializeOrClearThirdThreadLocalStorage(facade.GetNumberOfNodes());\n\n    QueryHeap &forward_heap3 = *engine_working_data.forward_heap_3;\n    QueryHeap &reverse_heap3 = *engine_working_data.reverse_heap_3;\n    EdgeWeight upper_bound = INVALID_EDGE_WEIGHT;\n    NodeID middle = SPECIAL_NODEID;\n\n    forward_heap3.Insert(s_P, 0, s_P);\n    reverse_heap3.Insert(t_P, 0, t_P);\n    // exploration from s and t until deletemin/(1+epsilon) > _lengt_oO_sShortest_path\n    while ((forward_heap3.Size() + reverse_heap3.Size()) > 0)\n    {\n        if (!forward_heap3.Empty())\n        {\n            routingStep<FORWARD_DIRECTION>(facade,\n                                           forward_heap3,\n                                           reverse_heap3,\n                                           middle,\n                                           upper_bound,\n                                           min_edge_offset,\n                                           DO_NOT_FORCE_LOOPS,\n                                           DO_NOT_FORCE_LOOPS);\n        }\n        if (!reverse_heap3.Empty())\n        {\n            routingStep<REVERSE_DIRECTION>(facade,\n                                           reverse_heap3,\n                                           forward_heap3,\n                                           middle,\n                                           upper_bound,\n                                           min_edge_offset,\n                                           DO_NOT_FORCE_LOOPS,\n                                           DO_NOT_FORCE_LOOPS);\n        }\n    }\n    return (upper_bound <= t_test_path_weight);\n}\n} // namespace\n\nInternalManyRoutesResult alternativePathSearch(SearchEngineData<Algorithm> &engine_working_data,\n                                               const DataFacade<Algorithm> &facade,\n                                               const PhantomNodes &phantom_node_pair,\n                                               unsigned /*number_of_alternatives*/)\n{\n    InternalRouteResult primary_route;\n    InternalRouteResult secondary_route;\n\n    primary_route.segment_end_coordinates = {phantom_node_pair};\n    secondary_route.segment_end_coordinates = {phantom_node_pair};\n\n    std::vector<NodeID> alternative_path;\n    std::vector<NodeID> via_node_candidate_list;\n    std::vector<SearchSpaceEdge> forward_search_space;\n    std::vector<SearchSpaceEdge> reverse_search_space;\n\n    // Init queues, semi-expensive because access to TSS invokes a sys-call\n    engine_working_data.InitializeOrClearFirstThreadLocalStorage(facade.GetNumberOfNodes());\n    engine_working_data.InitializeOrClearSecondThreadLocalStorage(facade.GetNumberOfNodes());\n    engine_working_data.InitializeOrClearThirdThreadLocalStorage(facade.GetNumberOfNodes());\n\n    auto &forward_heap1 = *engine_working_data.forward_heap_1;\n    auto &reverse_heap1 = *engine_working_data.reverse_heap_1;\n    auto &forward_heap2 = *engine_working_data.forward_heap_2;\n    auto &reverse_heap2 = *engine_working_data.reverse_heap_2;\n\n    EdgeWeight upper_bound_to_shortest_path_weight = INVALID_EDGE_WEIGHT;\n    NodeID middle_node = SPECIAL_NODEID;\n    const EdgeWeight min_edge_offset =\n        std::min(phantom_node_pair.source_phantom.forward_segment_id.enabled\n                     ? -phantom_node_pair.source_phantom.GetForwardWeightPlusOffset()\n                     : 0,\n                 phantom_node_pair.source_phantom.reverse_segment_id.enabled\n                     ? -phantom_node_pair.source_phantom.GetReverseWeightPlusOffset()\n                     : 0);\n\n    insertNodesInHeaps(forward_heap1, reverse_heap1, phantom_node_pair);\n\n    // search from s and t till new_min/(1+epsilon) > weight_of_shortest_path\n    while (0 < (forward_heap1.Size() + reverse_heap1.Size()))\n    {\n        if (0 < forward_heap1.Size())\n        {\n            alternativeRoutingStep<FORWARD_DIRECTION>(facade,\n                                                      forward_heap1,\n                                                      reverse_heap1,\n                                                      &middle_node,\n                                                      &upper_bound_to_shortest_path_weight,\n                                                      via_node_candidate_list,\n                                                      forward_search_space,\n                                                      min_edge_offset);\n        }\n        if (0 < reverse_heap1.Size())\n        {\n            alternativeRoutingStep<REVERSE_DIRECTION>(facade,\n                                                      forward_heap1,\n                                                      reverse_heap1,\n                                                      &middle_node,\n                                                      &upper_bound_to_shortest_path_weight,\n                                                      via_node_candidate_list,\n                                                      reverse_search_space,\n                                                      min_edge_offset);\n        }\n    }\n\n    if (INVALID_EDGE_WEIGHT == upper_bound_to_shortest_path_weight)\n    {\n        return InternalManyRoutesResult{std::move(primary_route)};\n    }\n\n    std::sort(begin(via_node_candidate_list), end(via_node_candidate_list));\n    auto unique_end = std::unique(begin(via_node_candidate_list), end(via_node_candidate_list));\n    via_node_candidate_list.resize(unique_end - begin(via_node_candidate_list));\n\n    std::vector<NodeID> packed_forward_path;\n    std::vector<NodeID> packed_reverse_path;\n\n    const bool path_is_a_loop =\n        upper_bound_to_shortest_path_weight !=\n        forward_heap1.GetKey(middle_node) + reverse_heap1.GetKey(middle_node);\n    if (path_is_a_loop)\n    {\n        // Self Loop\n        packed_forward_path.push_back(middle_node);\n        packed_forward_path.push_back(middle_node);\n    }\n    else\n    {\n\n        retrievePackedPathFromSingleHeap(forward_heap1, middle_node, packed_forward_path);\n        retrievePackedPathFromSingleHeap(reverse_heap1, middle_node, packed_reverse_path);\n    }\n\n    // this set is is used as an indicator if a node is on the shortest path\n    std::unordered_set<NodeID> nodes_in_path(packed_forward_path.size() +\n                                             packed_reverse_path.size());\n    nodes_in_path.insert(packed_forward_path.begin(), packed_forward_path.end());\n    nodes_in_path.insert(middle_node);\n    nodes_in_path.insert(packed_reverse_path.begin(), packed_reverse_path.end());\n\n    std::unordered_map<NodeID, EdgeWeight> approximated_forward_sharing;\n    std::unordered_map<NodeID, EdgeWeight> approximated_reverse_sharing;\n\n    // sweep over search space, compute forward sharing for each current edge (u,v)\n    for (const SearchSpaceEdge &current_edge : forward_search_space)\n    {\n        const NodeID u = current_edge.first;\n        const NodeID v = current_edge.second;\n\n        if (nodes_in_path.find(v) != nodes_in_path.end())\n        {\n            // current_edge is on shortest path => sharing(v):=queue.GetKey(v);\n            approximated_forward_sharing.emplace(v, forward_heap1.GetKey(v));\n        }\n        else\n        {\n            // current edge is not on shortest path. Check if we know a value for the other\n            // endpoint\n            const auto sharing_of_u_iterator = approximated_forward_sharing.find(u);\n            if (sharing_of_u_iterator != approximated_forward_sharing.end())\n            {\n                approximated_forward_sharing.emplace(v, sharing_of_u_iterator->second);\n            }\n        }\n    }\n\n    // sweep over search space, compute backward sharing\n    for (const SearchSpaceEdge &current_edge : reverse_search_space)\n    {\n        const NodeID u = current_edge.first;\n        const NodeID v = current_edge.second;\n        if (nodes_in_path.find(v) != nodes_in_path.end())\n        {\n            // current_edge is on shortest path => sharing(u):=queue.GetKey(u);\n            approximated_reverse_sharing.emplace(v, reverse_heap1.GetKey(v));\n        }\n        else\n        {\n            // current edge is not on shortest path. Check if we know a value for the other\n            // endpoint\n            const auto sharing_of_u_iterator = approximated_reverse_sharing.find(u);\n            if (sharing_of_u_iterator != approximated_reverse_sharing.end())\n            {\n                approximated_reverse_sharing.emplace(v, sharing_of_u_iterator->second);\n            }\n        }\n    }\n\n    std::vector<NodeID> preselected_node_list;\n    for (const NodeID node : via_node_candidate_list)\n    {\n        if (node == middle_node)\n            continue;\n        const auto fwd_iterator = approximated_forward_sharing.find(node);\n        const EdgeWeight fwd_sharing =\n            (fwd_iterator != approximated_forward_sharing.end()) ? fwd_iterator->second : 0;\n        const auto rev_iterator = approximated_reverse_sharing.find(node);\n        const EdgeWeight rev_sharing =\n            (rev_iterator != approximated_reverse_sharing.end()) ? rev_iterator->second : 0;\n\n        const EdgeWeight approximated_sharing = fwd_sharing + rev_sharing;\n        const EdgeWeight approximated_weight =\n            forward_heap1.GetKey(node) + reverse_heap1.GetKey(node);\n        const bool weight_passes =\n            (approximated_weight < upper_bound_to_shortest_path_weight * (1 + VIAPATH_EPSILON));\n        const bool sharing_passes =\n            (approximated_sharing <= upper_bound_to_shortest_path_weight * VIAPATH_GAMMA);\n        const bool stretch_passes =\n            (approximated_weight - approximated_sharing) <\n            ((1. + VIAPATH_EPSILON) * (upper_bound_to_shortest_path_weight - approximated_sharing));\n\n        if (weight_passes && sharing_passes && stretch_passes)\n        {\n            preselected_node_list.emplace_back(node);\n        }\n    }\n\n    std::vector<NodeID> &packed_shortest_path = packed_forward_path;\n    if (!path_is_a_loop)\n    {\n        std::reverse(packed_shortest_path.begin(), packed_shortest_path.end());\n        packed_shortest_path.emplace_back(middle_node);\n        packed_shortest_path.insert(\n            packed_shortest_path.end(), packed_reverse_path.begin(), packed_reverse_path.end());\n    }\n    std::vector<RankedCandidateNode> ranked_candidates_list;\n\n    // prioritizing via nodes for deep inspection\n    for (const NodeID node : preselected_node_list)\n    {\n        EdgeWeight weight_of_via_path = 0, sharing_of_via_path = 0;\n        computeWeightAndSharingOfViaPath(engine_working_data,\n                                         facade,\n                                         node,\n                                         &weight_of_via_path,\n                                         &sharing_of_via_path,\n                                         packed_shortest_path,\n                                         min_edge_offset);\n        const EdgeWeight maximum_allowed_sharing =\n            static_cast<EdgeWeight>(upper_bound_to_shortest_path_weight * VIAPATH_GAMMA);\n        if (sharing_of_via_path <= maximum_allowed_sharing &&\n            weight_of_via_path <= upper_bound_to_shortest_path_weight * (1 + VIAPATH_EPSILON))\n        {\n            ranked_candidates_list.emplace_back(node, weight_of_via_path, sharing_of_via_path);\n        }\n    }\n    std::sort(ranked_candidates_list.begin(), ranked_candidates_list.end());\n\n    NodeID selected_via_node = SPECIAL_NODEID;\n    EdgeWeight weight_of_via_path = INVALID_EDGE_WEIGHT;\n    NodeID s_v_middle = SPECIAL_NODEID, v_t_middle = SPECIAL_NODEID;\n    for (const RankedCandidateNode &candidate : ranked_candidates_list)\n    {\n        if (viaNodeCandidatePassesTTest(engine_working_data,\n                                        facade,\n                                        forward_heap1,\n                                        reverse_heap1,\n                                        forward_heap2,\n                                        reverse_heap2,\n                                        candidate,\n                                        upper_bound_to_shortest_path_weight,\n                                        &weight_of_via_path,\n                                        &s_v_middle,\n                                        &v_t_middle,\n                                        min_edge_offset))\n        {\n            // select first admissable\n            selected_via_node = candidate.node;\n            break;\n        }\n    }\n\n    // Unpack shortest path and alternative, if they exist\n    if (INVALID_EDGE_WEIGHT != upper_bound_to_shortest_path_weight)\n    {\n        BOOST_ASSERT(!packed_shortest_path.empty());\n        primary_route.unpacked_path_segments.resize(1);\n        primary_route.source_traversed_in_reverse.push_back(\n            (packed_shortest_path.front() !=\n             phantom_node_pair.source_phantom.forward_segment_id.id));\n        primary_route.target_traversed_in_reverse.push_back((\n            packed_shortest_path.back() != phantom_node_pair.target_phantom.forward_segment_id.id));\n\n        unpackPath(facade,\n                   // -- packed input\n                   packed_shortest_path.begin(),\n                   packed_shortest_path.end(),\n                   // -- start of route\n                   phantom_node_pair,\n                   // -- unpacked output\n                   primary_route.unpacked_path_segments.front());\n        primary_route.shortest_path_weight = upper_bound_to_shortest_path_weight;\n    }\n\n    if (SPECIAL_NODEID != selected_via_node)\n    {\n        std::vector<NodeID> packed_alternate_path;\n        // retrieve alternate path\n        retrievePackedAlternatePath(forward_heap1,\n                                    reverse_heap1,\n                                    forward_heap2,\n                                    reverse_heap2,\n                                    s_v_middle,\n                                    v_t_middle,\n                                    packed_alternate_path);\n\n        secondary_route.unpacked_path_segments.resize(1);\n        secondary_route.source_traversed_in_reverse.push_back(\n            (packed_alternate_path.front() !=\n             phantom_node_pair.source_phantom.forward_segment_id.id));\n        secondary_route.target_traversed_in_reverse.push_back(\n            (packed_alternate_path.back() !=\n             phantom_node_pair.target_phantom.forward_segment_id.id));\n\n        // unpack the alternate path\n        unpackPath(facade,\n                   packed_alternate_path.begin(),\n                   packed_alternate_path.end(),\n                   phantom_node_pair,\n                   secondary_route.unpacked_path_segments.front());\n\n        secondary_route.shortest_path_weight = weight_of_via_path;\n    }\n    else\n    {\n        BOOST_ASSERT(secondary_route.shortest_path_weight == INVALID_EDGE_WEIGHT);\n    }\n\n    return InternalManyRoutesResult{{std::move(primary_route), std::move(secondary_route)}};\n}\n\n} // namespace routing_algorithms\n} // namespace engine\n} // namespace osrm\n", "meta": {"hexsha": "107e98ea96251cfc1b6bd2e4e3313115aed9cf2a", "size": 36787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/engine/routing_algorithms/alternative_path_ch.cpp", "max_stars_repo_name": "systemed/osrm-backend", "max_stars_repo_head_hexsha": "370081ec1413bf512d39a204cdb29a541aa7e45b", "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/engine/routing_algorithms/alternative_path_ch.cpp", "max_issues_repo_name": "systemed/osrm-backend", "max_issues_repo_head_hexsha": "370081ec1413bf512d39a204cdb29a541aa7e45b", "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/engine/routing_algorithms/alternative_path_ch.cpp", "max_forks_repo_name": "systemed/osrm-backend", "max_forks_repo_head_hexsha": "370081ec1413bf512d39a204cdb29a541aa7e45b", "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.9253208868, "max_line_length": 100, "alphanum_fraction": 0.595183081, "num_tokens": 7247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.18159080275245187}}
{"text": "// All content Copyright (C) 2018 Genomics plc\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"io/read.hpp\"\n#include \"io/readIntervalTree.hpp\"\n#include \"io/readRange.hpp\"\n#include \"io/readSummaries.hpp\"\n#include \"caller/diploid/referenceCalling.hpp\"\n#include \"vcf/field.hpp\"\n#include <cmath>\n\nusing Read = wecall::io::Read;\nusing Cigar = wecall::alignment::Cigar;\nusing wecall::caller::Region;\nusing wecall::caller::Call;\nusing wecall::io::RegionsReads;\nusing wecall::utils::BasePairSequence;\nusing wecall::caller::model::buildRefCall;\nusing Annotation = wecall::caller::Annotation;\nusing wecall::vcf::info::DP_key;\n\nBOOST_AUTO_TEST_CASE( shouldCallRefFor1ReadAnd1Sample )\n{\n    Region region = Region( \"1\", 0, 5 );\n    auto refSequence = std::make_shared< wecall::utils::ReferenceSequence >( region, std::string( 5, 'A' ) );\n\n    const int64_t startPos = 0;\n    const auto read1 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    wecall::io::readIntervalTree_t readContainer( 0, 100 );\n    readContainer.insert( read1 );\n\n    RegionsReads regionSetReads( region, readContainer.getFullRange(), 0 );\n\n    wecall::io::perSampleRegionsReads_t perSampleReads = {{\"sample1\", regionSetReads}};\n\n    const auto refCalls = buildRefCall( region, perSampleReads, 10, {2}, 0.2 );\n\n    BOOST_REQUIRE_EQUAL( refCalls.size(), 2 );\n\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::BEG ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::END ), 4 );\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::LEN ), 4 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[0].getAnnotation( Annotation::MIN_DP ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[0].getAnnotation( Annotation::FORMAT_DP ), 1 );\n    BOOST_CHECK_CLOSE( refCalls[0].samples[0].getAnnotation( Annotation::GQ ), 3.0103, 1 );\n\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::BEG ), 5 );\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::END ), 5 );\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::LEN ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[0].getAnnotation( Annotation::MIN_DP ), 0 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[0].getAnnotation( Annotation::FORMAT_DP ), 0 );\n    BOOST_CHECK_EQUAL( std::isnan( refCalls[1].samples[0].getAnnotation( Annotation::GQ ) ), true );\n}\n\nBOOST_AUTO_TEST_CASE( shouldCallRefFor2OverlappingReadsAnd1Sample )\n{\n    Region region = Region( \"1\", 0, 5 );\n    auto refSequence = std::make_shared< wecall::utils::ReferenceSequence >( region, std::string( 5, 'A' ) );\n\n    const int64_t startPos = 0;\n    const auto read1 = std::make_shared< Read >( BasePairSequence( 3, 'A' ), std::string( 3, 'Q' ), \"0\", Cigar( \"3M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read2 = std::make_shared< Read >( BasePairSequence( 3, 'A' ), std::string( 3, 'Q' ), \"0\", Cigar( \"3M\" ),\n                                                 0, startPos + 2, 0, 0, 0, 0, 0, refSequence );\n\n    wecall::io::readIntervalTree_t readContainer( 0, 100 );\n    readContainer.insert( read1 );\n    readContainer.insert( read2 );\n\n    RegionsReads regionSetReads( region, readContainer.getFullRange(), 0 );\n\n    wecall::io::perSampleRegionsReads_t perSampleReads = {{\"sample1\", regionSetReads}};\n\n    const auto refCalls = buildRefCall( region, perSampleReads, 10, {2}, 0.2 );\n\n    BOOST_REQUIRE_EQUAL( refCalls.size(), 3 );\n\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::BEG ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::END ), 2 );\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::LEN ), 2 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[0].getAnnotation( Annotation::MIN_DP ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[0].getAnnotation( Annotation::FORMAT_DP ), 1 );\n    BOOST_CHECK_CLOSE( refCalls[0].samples[0].getAnnotation( Annotation::GQ ), 3.0103, 1 );\n\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::BEG ), 3 );\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::END ), 3 );\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::LEN ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[0].getAnnotation( Annotation::MIN_DP ), 2 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[0].getAnnotation( Annotation::FORMAT_DP ), 2 );\n    BOOST_CHECK_CLOSE( refCalls[1].samples[0].getAnnotation( Annotation::GQ ), 5.9159, 1 );\n\n    BOOST_CHECK_EQUAL( refCalls[2].getAnnotation( Annotation::BEG ), 4 );\n    BOOST_CHECK_EQUAL( refCalls[2].getAnnotation( Annotation::END ), 5 );\n    BOOST_CHECK_EQUAL( refCalls[2].getAnnotation( Annotation::LEN ), 2 );\n    BOOST_CHECK_EQUAL( refCalls[2].samples[0].getAnnotation( Annotation::MIN_DP ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[2].samples[0].getAnnotation( Annotation::FORMAT_DP ), 1 );\n    BOOST_CHECK_CLOSE( refCalls[2].samples[0].getAnnotation( Annotation::GQ ), 3.0103, 1 );\n}\n\nBOOST_AUTO_TEST_CASE( shouldCallRefForManyReadsFor1Sample )\n{\n    Region region = Region( \"1\", 0, 5 );\n    auto refSequence = std::make_shared< wecall::utils::ReferenceSequence >( region, std::string( 5, 'A' ) );\n\n    const int64_t startPos = 0;\n    const auto read1 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read2 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read3 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read4 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read5 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read6 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read7 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read8 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read9 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read10 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                  0, startPos + 1, 0, 0, 0, 0, 0, refSequence );\n\n    wecall::io::readIntervalTree_t readContainer( 0, 100 );\n    readContainer.insert( read1 );\n    readContainer.insert( read2 );\n    readContainer.insert( read3 );\n    readContainer.insert( read4 );\n    readContainer.insert( read5 );\n    readContainer.insert( read6 );\n    readContainer.insert( read7 );\n    readContainer.insert( read8 );\n    readContainer.insert( read9 );\n    readContainer.insert( read10 );\n\n    RegionsReads regionSetReads( region, readContainer.getFullRange(), 0 );\n\n    wecall::io::perSampleRegionsReads_t perSampleReads = {{\"sample1\", regionSetReads}};\n\n    const auto refCalls = buildRefCall( region, perSampleReads, 10, {2}, 0.1 );\n\n    BOOST_REQUIRE_EQUAL( refCalls.size(), 2 );\n\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::BEG ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::END ), 4 );\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::LEN ), 4 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[0].getAnnotation( Annotation::MIN_DP ), 9 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[0].getAnnotation( Annotation::FORMAT_DP ), 10 );  // rounded 9.75\n    BOOST_CHECK_CLOSE( refCalls[0].samples[0].getAnnotation( Annotation::GQ ), 23.85277, 1 );\n\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::BEG ), 5 );\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::END ), 5 );\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::LEN ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[0].getAnnotation( Annotation::MIN_DP ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[0].getAnnotation( Annotation::FORMAT_DP ), 1 );\n    BOOST_CHECK_CLOSE( refCalls[1].samples[0].getAnnotation( Annotation::GQ ), 3.0103, 1 );\n}\n\nBOOST_AUTO_TEST_CASE( shouldCallRefFor1ReadsFor2Samples )\n{\n    Region region = Region( \"1\", 0, 5 );\n    auto refSequence = std::make_shared< wecall::utils::ReferenceSequence >( region, std::string( 5, 'A' ) );\n\n    const int64_t startPos = 0;\n    const auto read1 = std::make_shared< Read >( BasePairSequence( 3, 'A' ), std::string( 3, 'Q' ), \"0\", Cigar( \"3M\" ),\n                                                 0, startPos, 0, 0, 0, 0, 0, refSequence );\n\n    const auto read2 = std::make_shared< Read >( BasePairSequence( 4, 'A' ), std::string( 4, 'Q' ), \"0\", Cigar( \"4M\" ),\n                                                 0, startPos + 1, 0, 0, 0, 0, 0, refSequence );\n\n    wecall::io::readIntervalTree_t readContainer1( 0, 100 );\n    readContainer1.insert( read1 );\n    RegionsReads regionSetReads1( region, readContainer1.getFullRange(), 0 );\n\n    wecall::io::readIntervalTree_t readContainer2( 0, 100 );\n    readContainer2.insert( read2 );\n    RegionsReads regionSetReads2( region, readContainer2.getFullRange(), 0 );\n\n    wecall::io::perSampleRegionsReads_t perSampleReads = {{\"sample1\", regionSetReads1}, {\"sample2\", regionSetReads2}};\n\n    const auto refCalls = buildRefCall( region, perSampleReads, 10, {2, 2}, 0.2 );\n\n    BOOST_REQUIRE_EQUAL( refCalls.size(), 3 );\n\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::BEG ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::END ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].getAnnotation( Annotation::LEN ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[0].getAnnotation( Annotation::MIN_DP ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[0].getAnnotation( Annotation::FORMAT_DP ), 1 );\n    BOOST_CHECK_CLOSE( refCalls[0].samples[0].getAnnotation( Annotation::GQ ), 3.0103, 1 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[1].getAnnotation( Annotation::MIN_DP ), 0 );\n    BOOST_CHECK_EQUAL( refCalls[0].samples[1].getAnnotation( Annotation::FORMAT_DP ), 0 );\n    BOOST_CHECK_EQUAL( std::isnan( refCalls[0].samples[1].getAnnotation( Annotation::GQ ) ), true );\n\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::BEG ), 2 );\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::END ), 3 );\n    BOOST_CHECK_EQUAL( refCalls[1].getAnnotation( Annotation::LEN ), 2 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[0].getAnnotation( Annotation::MIN_DP ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[0].getAnnotation( Annotation::FORMAT_DP ), 1 );\n    BOOST_CHECK_CLOSE( refCalls[1].samples[0].getAnnotation( Annotation::GQ ), 3.0103, 1 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[1].getAnnotation( Annotation::MIN_DP ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[1].samples[1].getAnnotation( Annotation::FORMAT_DP ), 1 );\n    BOOST_CHECK_CLOSE( refCalls[1].samples[1].getAnnotation( Annotation::GQ ), 3.0103, 1 );\n\n    BOOST_CHECK_EQUAL( refCalls[2].getAnnotation( Annotation::BEG ), 4 );\n    BOOST_CHECK_EQUAL( refCalls[2].getAnnotation( Annotation::END ), 5 );\n    BOOST_CHECK_EQUAL( refCalls[2].getAnnotation( Annotation::LEN ), 2 );\n    BOOST_CHECK_EQUAL( refCalls[2].samples[0].getAnnotation( Annotation::MIN_DP ), 0 );\n    BOOST_CHECK_EQUAL( refCalls[2].samples[0].getAnnotation( Annotation::FORMAT_DP ), 0 );\n    BOOST_CHECK_EQUAL( std::isnan( refCalls[2].samples[0].getAnnotation( Annotation::GQ ) ), true );\n    BOOST_CHECK_EQUAL( refCalls[2].samples[1].getAnnotation( Annotation::MIN_DP ), 1 );\n    BOOST_CHECK_EQUAL( refCalls[2].samples[1].getAnnotation( Annotation::FORMAT_DP ), 1 );\n    BOOST_CHECK_CLOSE( refCalls[2].samples[1].getAnnotation( Annotation::GQ ), 3.0103, 1 );\n}\n", "meta": {"hexsha": "9943f09a6a4e989c350f94d8f994b6b2f8cd2f7a", "size": 12773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/test/ioTest/io/testBuildRefCall.cpp", "max_stars_repo_name": "dylex/wecall", "max_stars_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T15:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:13:05.000Z", "max_issues_repo_path": "cpp/test/ioTest/io/testBuildRefCall.cpp", "max_issues_repo_name": "dylex/wecall", "max_issues_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T12:32:56.000Z", "max_forks_repo_path": "cpp/test/ioTest/io/testBuildRefCall.cpp", "max_forks_repo_name": "dylex/wecall", "max_forks_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:28:33.000Z", "avg_line_length": 55.5347826087, "max_line_length": 120, "alphanum_fraction": 0.6473811947, "num_tokens": 3806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.18145183411272972}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/timing.h\"\n#include \"dynet/rnn.h\"\n#include \"dynet/gru.h\"\n#include \"dynet/lstm.h\"\n#include \"dynet/fast-lstm.h\"\n#include \"dynet/expr.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <type_traits>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/program_options.hpp>\n\n#include \"s2s/dynet/dict.h\"\n#include \"s2s/corpus/options.hpp\"\n#include \"s2s/corpus/corpora.hpp\"\n#include \"s2s/corpus/dicts.hpp\"\n#include \"s2s/corpus/batch.hpp\"\n#include \"s2s/nn/encdec.hpp\"\n\n#ifndef INCLUDE_GUARD_ENCODER_DECODER_LAHAN_HPP\n#define INCLUDE_GUARD_ENCODER_DECODER_LAHAN_HPP\n\nnamespace s2s {\n\nclass encoder_decoder_slahan : public encoder_decoder {\n\npublic:\n\n    dynet::Parameter p_Wad;\n    dynet::Parameter p_Uad;\n    dynet::Parameter p_vad;\n\n    dynet::Parameter p_Wctx;\n    dynet::Parameter p_bctx;\n    \n    std::vector<dynet::Parameter> p_Wahf;\n\n    std::vector<dynet::Parameter> p_Wahb;\n\n    dynet::Parameter p_select_W; // {rnn_size*2,rnn_size*7}\n    dynet::Parameter p_select_b; // {rnn_size*2}\n\n    std::vector<dynet::Expression> h_bi;\n    std::vector<std::vector<dynet::Expression> > f_alpha_d;\n    std::vector<std::vector<dynet::Expression> > b_alpha_d;\n\n    dynet::Expression i_h_enc;\n    dynet::Expression i_h_fin;\n    dynet::Expression i_feed;\n\n    // for visualization\n    std::vector<dynet::Expression> gate_list;\n\n    explicit encoder_decoder_slahan(dynet::ParameterCollection& model, const s2s_options& opts, dicts& d) : encoder_decoder(model,opts,d) {\n\n        flag_drop_out = true;\n\n        unsigned int dec_context_size = 0;\n        unsigned int dec_feeding_size = 0;\n\n        assert(opts.dec_feature_vocab_size.size() == opts.dec_feature_vec_size.size());\n\n        unsigned int cell_ratio = 2; // In GRU, cell_ratio = 1;\n\n        p_dec_init_w.resize(opts.num_layers * cell_ratio);\n        for(unsigned int i = 0; i < opts.num_layers * cell_ratio; i++){\n            p_dec_init_w[i] = model.add_parameters({opts.rnn_size, opts.rnn_size});\n        }\n        p_dec_init_bias.resize(opts.num_layers * cell_ratio);\n        for(unsigned int i = 0; i < opts.num_layers * cell_ratio; i++){\n            p_dec_init_bias[i] = model.add_parameters({opts.rnn_size});\n        }\n        \n        p_Wad = model.add_parameters({opts.att_size, opts.rnn_size * 2});\n        p_Uad = model.add_parameters({opts.att_size, opts.rnn_size * 2});\n        p_vad = model.add_parameters({opts.att_size});\n\n        p_Wctx = model.add_parameters({opts.rnn_size, opts.rnn_size*5});\n        p_bctx = model.add_parameters({opts.rnn_size});\n\n        for(unsigned int d = 0; d < opts.rec_attn_dep.size(); d++){\n            p_Wahf.push_back(model.add_parameters({opts.rnn_size, opts.rnn_size * 2}));\n        }\n\n        for(unsigned int d = 0; d < opts.rec_attn_dep.size(); d++){\n            p_Wahb.push_back(model.add_parameters({opts.rnn_size, opts.rnn_size * 2}));\n        }\n\n        if(opts.context_type == \"both\"){\n            p_select_W = model.add_parameters({opts.rnn_size*2, opts.rnn_size*5});\n            p_select_b = model.add_parameters({opts.rnn_size*2});\n            dec_context_size = opts.rnn_size * 5;\n        }else if(opts.context_type == \"parent\" or opts.context_type == \"child\"){\n            p_select_W = model.add_parameters({opts.rnn_size*2, opts.rnn_size*3});\n            p_select_b = model.add_parameters({opts.rnn_size*2});\n            dec_context_size = opts.rnn_size * 5;\n        }else{\n            assert(false);\n        }\n        \n        if(opts.additional_output_layer == true){\n            dec_feeding_size = opts.rnn_size;\n            p_add_W = model.add_parameters({dec_feeding_size, dec_context_size});\n            p_add_bias = model.add_parameters({dec_feeding_size});\n            p_out_R = model.add_parameters({d.dict_set_trg.d_word.size(), dec_feeding_size});\n            p_out_bias = model.add_parameters({d.dict_set_trg.d_word.size()});\n        }else{\n            dec_feeding_size = dec_context_size;\n            p_out_R = model.add_parameters({d.dict_set_trg.d_word.size(), dec_feeding_size});\n            p_out_bias = model.add_parameters({d.dict_set_trg.d_word.size()});\n        }\n\n        dec_builder = dynet::VanillaLSTMBuilder(\n            opts.num_layers,\n            (rev_enc_builder.input_dim + dec_feeding_size + 3),\n            opts.rnn_size,\n            model\n        );\n    }\n\n    encoder_decoder_slahan(const encoder_decoder_slahan&) = delete;\n    encoder_decoder_slahan& operator=(const encoder_decoder_slahan&) = delete;\n    ~encoder_decoder_slahan() = default;\n\n    void init_feed(const batch &batch_local, dynet::ComputationGraph& cg){\n        i_feed = dynet::zeroes(cg, dynet::Dim({p_out_R.dim().d[1]}, batch_local.batch_size()));\n    }\n\n    void encoder(const batch &batch_local, dynet::ComputationGraph& cg) {\n        // initialize\n        init(batch_local, cg);\n        // embedding\n        embedding(batch_local, cg);\n        init_feed(batch_local, cg);\n        gate_list.clear();\n\n        std::vector<dynet::Expression> h_fwd(slen);\n        std::vector<dynet::Expression> h_bwd(slen);\n        h_bi.resize(slen);\n        // forward encoder\n        fwd_enc_builder.new_graph(cg);\n        fwd_enc_builder.start_new_sequence();\n        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){\n            fwd_enc_builder.set_dropout_masks(batch_size);\n        }\n        for (unsigned int t_i = 0; t_i < slen; ++t_i) {\n            fwd_enc_builder.add_input(h_lookup[t_i]);\n            h_fwd[t_i] = fwd_enc_builder.back();\n        }\n        // backward encoder\n        rev_enc_builder.new_graph(cg);\n        rev_enc_builder.start_new_sequence();\n        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){\n            rev_enc_builder.set_dropout_masks(batch_size);\n        }\n        for (unsigned int ind = 0; ind < slen; ++ind) {\n            unsigned int t_i = (slen - 1) - ind;\n            rev_enc_builder.add_input(h_lookup[t_i]);\n            h_bwd[t_i] = rev_enc_builder.back();\n        }\n        // bidirectional encoding\n        h_bi[0] = dynet::zeroes(cg, dynet::Dim({opts.rnn_size * 2}, batch_size));\n        for (unsigned int t_i = 1; t_i < slen; ++t_i) {\n            h_bi[t_i] = concatenate(std::vector<dynet::Expression>({h_fwd[t_i], h_bwd[t_i]}));\n        }\n        i_h_enc = concatenate_cols(h_bi);\n        i_h_fin = concatenate(std::vector<dynet::Expression>({rev_enc_builder.h.back().back(), fwd_enc_builder.h.back().back()}));\n        // Initialize decoder\n        std::vector<dynet::Expression> vec_enc_final_state;\n        vec_enc_final_state = rev_enc_builder.final_s();\n        dec_builder.new_graph(cg);\n        if(opts.additional_connect_layer){\n            std::vector<dynet::Expression> vec_dec_init_state;\n            for (unsigned int i = 0; i < vec_enc_final_state.size(); i++){\n                dynet::Expression i_dec_init_w = parameter(cg, p_dec_init_w[i]);\n                dynet::Expression i_dec_init_bias = parameter(cg, p_dec_init_bias[i]);\n                vec_dec_init_state.push_back(tanh(i_dec_init_w * vec_enc_final_state[i] + i_dec_init_bias));\n            }\n            dec_builder.start_new_sequence(vec_dec_init_state);\n        }else{\n            dec_builder.start_new_sequence(vec_enc_final_state);\n        }\n        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){\n            dec_builder.set_dropout_masks(batch_size);\n        }\n    }\n\n    std::vector<dynet::Expression> attention(dynet::ComputationGraph& cg, const batch &batch_local){\n        if(opts.self_attn_type == \"given\"){\n            return given_attention(cg, batch_local);\n        }else if(opts.self_attn_type == \"self\"){\n            return self_attention(cg, batch_local);\n        }else{\n            std::cerr << \"Attention type does not match.\" << std::endl;\n            assert(false);\n        }\n    }\n\n    std::vector<dynet::Expression> given_attention(dynet::ComputationGraph& cg, const batch &batch_local){\n        std::vector<dynet::Expression> h_att_self(slen);\n        for(unsigned int child_pos = 0; child_pos < slen; child_pos++){\n            std::vector<dynet::real> mask_real_zero_one(batch_size * slen);\n            std::vector<dynet::real> mask_real_zero_min_flt_max(batch_size * slen);\n            for(unsigned int batch_id = 0; batch_id < batch_size; batch_id++){\n                for(unsigned int parent_pos = 0; parent_pos < slen; parent_pos++){\n                    unsigned int v_idx = slen * batch_id + parent_pos;\n                    if(parent_pos == batch_local.align[child_pos][batch_id]){\n                        mask_real_zero_one[v_idx] = 0.0f;\n                        mask_real_zero_min_flt_max[v_idx] = 0.0f;\n                    }else{\n                        mask_real_zero_one[v_idx] = 0.0f;\n                        mask_real_zero_min_flt_max[v_idx] = opts.dummy_flt_min;\n                    }\n                }\n            }\n            h_att_self[child_pos] = dynet::input(cg, dynet::Dim({slen}, batch_size), mask_real_zero_one);\n            h_att_self[child_pos] = h_att_self[child_pos] + dynet::input(cg, dynet::Dim({slen}, batch_size), mask_real_zero_min_flt_max);\n        }\n        return h_att_self;\n    }\n\n    std::vector<dynet::Expression> self_attention(dynet::ComputationGraph& cg, const batch &batch_local){\n        std::vector<dynet::Expression> h_att_self(slen);\n        dynet::Expression i_vad = parameter(cg, p_vad);\n        dynet::Expression i_Wad = parameter(cg, p_Wad);\n        dynet::Expression i_Uad = parameter(cg, p_Uad);\n        dynet::Expression i_Uadhj = i_Uad * i_h_enc;\n        for(unsigned int child_pos = 0; child_pos < slen; child_pos++){\n            std::vector<dynet::real> mask_real_zero_one(batch_size * slen);\n            std::vector<dynet::real> mask_real_zero_min_flt_max(batch_size * slen);\n            for(unsigned int batch_id = 0; batch_id < batch_size; batch_id++){\n                for(unsigned int parent_pos = 0; parent_pos < slen; parent_pos++){\n                    unsigned int v_idx = slen * batch_id + parent_pos;\n                    if(child_pos > 0 && parent_pos == child_pos){\n                        mask_real_zero_one[v_idx] = 0.0f;\n                        mask_real_zero_min_flt_max[v_idx] = opts.dummy_flt_min;\n                    }else if(child_pos > 0 && parent_pos != child_pos){\n                        mask_real_zero_one[v_idx] = 1.0f;\n                        mask_real_zero_min_flt_max[v_idx] = 0.0f;\n                    }else if(child_pos == 0 && parent_pos == child_pos){\n                        mask_real_zero_one[v_idx] = 1.0f;\n                        mask_real_zero_min_flt_max[v_idx] = 0.0f;\n                    }else if(child_pos == 0 && parent_pos != child_pos){\n                        mask_real_zero_one[v_idx] = 0.0f;\n                        mask_real_zero_min_flt_max[v_idx] = opts.dummy_flt_min;\n                    }\n                }\n            }\n            dynet::Expression i_wadh = i_Wad * h_bi[child_pos];\n            dynet::Expression i_Wadh = concatenate_cols(std::vector<dynet::Expression>(slen, i_wadh));\n            dynet::Expression i_att = transpose(tanh(i_Wadh + i_Uadhj)) * i_vad;\n            h_att_self[child_pos] = cmult(i_att, dynet::input(cg, dynet::Dim({slen}, batch_size), mask_real_zero_one));\n            h_att_self[child_pos] = h_att_self[child_pos] + dynet::input(cg, dynet::Dim({slen}, batch_size), mask_real_zero_min_flt_max);\n        }\n        return h_att_self;\n    }\n\n    void recursive_attention(dynet::ComputationGraph& cg, std::vector<dynet::Expression>& h_att_self){\n        // initialize forward and backward attention at d=0\n        f_alpha_d.resize(opts.rec_attn_dep.back());\n        b_alpha_d.resize(opts.rec_attn_dep.back());\n        f_alpha_d[0].resize(slen);\n        b_alpha_d[0].resize(slen);\n        std::vector<dynet::Expression> i_f_alpha_d(opts.rec_attn_dep.back());\n        for(unsigned int child_pos = 0; child_pos < slen; child_pos++){\n            f_alpha_d[0][child_pos] = softmax(h_att_self[child_pos]);\n        }\n        i_f_alpha_d[0] = concatenate_cols(f_alpha_d[0]);\n        for(unsigned int child_pos = 0; child_pos < slen; child_pos++){\n            b_alpha_d[0][child_pos] = pick(i_f_alpha_d[0], child_pos, 0);\n        }\n        // calculate recursive attentions\n        for(unsigned int d = 1; d < opts.rec_attn_dep.back(); d++){\n            // To avoid the rounding errors\n            unsigned int order = d + 1;\n            unsigned int d_left = (order / 2 + order % 2) - 1;\n            unsigned int d_right = order / 2 - 1;\n            i_f_alpha_d[d] = i_f_alpha_d[d_left] * i_f_alpha_d[d_right];\n            f_alpha_d[d].resize(slen);\n            b_alpha_d[d].resize(slen);\n            for(unsigned int child_pos = 0; child_pos < slen; child_pos++){\n                f_alpha_d[d][child_pos] = pick(i_f_alpha_d[d], child_pos, 1);\n                b_alpha_d[d][child_pos] = pick(i_f_alpha_d[d], child_pos, 0);\n            }\n        }\n    }\n\n    dynet::Expression decoder_output(dynet::ComputationGraph& cg, const unsigned int t, const std::vector<unsigned int>& prev){\n        return decoder_output(cg, t, prev, dec_builder.state());\n    }\n\n    dynet::Expression decoder_output(dynet::ComputationGraph& cg, const unsigned int t, const std::vector<unsigned int>& prev, const dynet::RNNPointer pointer_prev){\n        // t should be always larger than 0.\n        assert(t > 0);\n        // convert previous label to the bit features.\n        std::vector<dynet::real> bit_features;\n        const unsigned int start_id = d.dict_set_trg.start_id_word;\n        const unsigned int kep_id = d.dict_set_trg.keep_id_word;\n        const unsigned int del_id = d.dict_set_trg.delete_id_word;\n        for(unsigned int batch_id = 0; batch_id < prev.size(); batch_id++){\n            // start\n            if(prev[batch_id] == start_id){\n                bit_features.push_back(opts.bit_size_flt);\n            }else{\n                bit_features.push_back(0.0f);\n            }\n            // keep\n            if(prev[batch_id] == kep_id){\n                bit_features.push_back(opts.bit_size_flt);\n            }else{\n                bit_features.push_back(0.0f);\n            }\n            // delete\n            if(prev[batch_id] == del_id){\n                bit_features.push_back(opts.bit_size_flt);\n            }else{\n                bit_features.push_back(0.0f);\n            }\n        }\n        // construct vectors for decoder feeding\n        dynet::Expression i_x_t = dynet::input(cg, dynet::Dim({3}, batch_size), bit_features);\n        dynet::Expression i_dec_input = concatenate(std::vector<dynet::Expression>({i_x_t, i_feed}));\n        i_dec_input = concatenate(std::vector<dynet::Expression>({i_dec_input, h_lookup[t]}));\n        // update decoder states\n        dec_builder.add_input(pointer_prev, i_dec_input);\n        dynet::Expression i_h_dec = dec_builder.h.back().back();\n        // create a current state vector\n        dynet::Expression i_h_ctx = concatenate(std::vector<dynet::Expression>({i_h_dec, i_h_fin}));\n        i_h_ctx = concatenate(std::vector<dynet::Expression>({i_h_ctx, h_bi[t]}));\n        dynet::Expression i_Wctx = parameter(cg, p_Wctx);\n        dynet::Expression i_bctx = parameter(cg, p_bctx);\n        dynet::Expression i_h_ctx_attn = tanh(i_Wctx * i_h_ctx + i_bctx);\n        // extract encoder hidden states from a forward attention layer\n        dynet::Expression i_f_c_t = forward_attention(cg, t, i_h_ctx_attn);\n        // extract encoder hidden states from a backward attention layer\n        dynet::Expression i_b_c_t = backward_attention(cg, t, i_h_ctx_attn);\n        // balance gate\n        dynet::Expression i_c_t = balance_layer(cg, i_f_c_t, i_b_c_t, i_h_ctx_attn);\n        // final context\n        i_c_t = concatenate(std::vector<dynet::Expression>({h_bi[t], i_c_t}));\n        i_c_t = concatenate(std::vector<dynet::Expression>({i_h_dec, i_c_t}));\n        // to output layer\n        if(opts.additional_output_layer){\n            dynet::Expression i_add_W = parameter(cg, p_add_W);\n            dynet::Expression i_add_bias = parameter(cg, p_add_bias);\n            i_feed = tanh(i_add_W * i_c_t + i_add_bias);\n        }else{\n            i_feed = i_c_t;\n        }\n        // output layer\n        dynet::Expression i_out_R = parameter(cg, p_out_R);\n        dynet::Expression i_out_bias = parameter(cg, p_out_bias);\n        dynet::Expression i_out_pred_t = i_out_R * i_feed + i_out_bias;\n        \n        return i_out_pred_t;\n    }\n\n    // forward attention layer\n    dynet::Expression forward_attention(dynet::ComputationGraph& cg, const unsigned int t, dynet::Expression& i_h_ctx_attn){\n        std::vector<dynet::Expression> f_c_t(opts.rec_attn_dep.size());\n        std::vector<dynet::Expression> h_f(opts.rec_attn_dep.size());\n        for(unsigned int d = 0; d < opts.rec_attn_dep.size(); d++){\n            f_c_t[d] = i_h_enc * f_alpha_d[opts.rec_attn_dep[d]-1][t];\n            h_f[d] = parameter(cg, p_Wahf[d]) * f_c_t[d];\n        }\n        dynet::Expression i_h_f_a = concatenate_cols(h_f);\n        // hierarchical general attention\n        dynet::Expression i_f_alpha_t = softmax(transpose(i_h_f_a) * i_h_ctx_attn);\n        dynet::Expression i_f_c_t = concatenate_cols(f_c_t);\n        i_f_c_t = i_f_c_t * i_f_alpha_t;\n        return i_f_c_t;\n    }\n\n    // backward attention layer\n    dynet::Expression backward_attention(dynet::ComputationGraph& cg, const unsigned int t, dynet::Expression& i_h_ctx_attn){\n        std::vector<dynet::Expression> b_c_t(opts.rec_attn_dep.size());\n        std::vector<dynet::Expression> h_b(opts.rec_attn_dep.size());\n        for(unsigned int d = 0; d < opts.rec_attn_dep.size(); d++){\n            // reflect recursive attention weights\n            dynet::Expression i_filtered = cmult(transpose(b_alpha_d[opts.rec_attn_dep[d]-1][t]), i_h_enc);\n            // general attention\n            b_c_t[d] = maxpooling2d(i_filtered, std::vector<unsigned>({1,slen}), std::vector<unsigned>({1,slen}));\n            h_b[d] = parameter(cg, p_Wahb[d]) * b_c_t[d];\n        }\n        dynet::Expression i_h_b_a = concatenate_cols(h_b);\n        // hierarchical general attention\n        dynet::Expression i_b_alpha_t = softmax(transpose(i_h_b_a) * i_h_ctx_attn);\n        // output\n        dynet::Expression i_b_c_t = concatenate_cols(b_c_t);\n        i_b_c_t = i_b_c_t * i_b_alpha_t;\n        return i_b_c_t;\n    }\n\n    // balance gate\n    dynet::Expression balance_layer(dynet::ComputationGraph& cg, dynet::Expression& i_f_c_t, dynet::Expression& i_b_c_t, dynet::Expression& i_h_ctx_attn){\n        dynet::Expression i_c_t;\n        dynet::Expression i_select_W = parameter(cg, p_select_W);\n        dynet::Expression i_select_b = parameter(cg, p_select_b);\n        if(opts.context_type == \"both\"){\n            dynet::Expression i_fb_c_t = concatenate(std::vector<dynet::Expression>({i_f_c_t, i_b_c_t}));\n            if(opts.selective_gate == true){\n                dynet::Expression i_fb = dynet::affine_transform({i_select_b, i_select_W, concatenate(std::vector<dynet::Expression>({i_fb_c_t, i_h_ctx_attn}))});\n                dynet::Expression i_s = logistic(i_fb);\n                gate_list.push_back(i_s);\n                i_c_t = cmult(i_s, i_f_c_t) + cmult(1.f - i_s, i_b_c_t);\n            }else{\n                i_c_t = (i_f_c_t + i_b_c_t) / 2.f;\n            }\n        }else if(opts.context_type == \"parent\"){\n            if(opts.selective_gate == true){\n                dynet::Expression i_f = dynet::affine_transform({i_select_b, i_select_W, concatenate(std::vector<dynet::Expression>({i_f_c_t, i_h_ctx_attn}))});\n                dynet::Expression i_s = logistic(i_f);\n                gate_list.push_back(i_s);\n                i_c_t = cmult(i_s, i_f_c_t);\n            }else{\n                i_c_t = i_f_c_t;\n            }\n        }else if(opts.context_type == \"child\"){\n            if(opts.selective_gate == true){\n                dynet::Expression i_b = dynet::affine_transform({i_select_b, i_select_W, concatenate(std::vector<dynet::Expression>({i_b_c_t, i_h_ctx_attn}))});\n                dynet::Expression i_s = logistic(i_b);\n                gate_list.push_back(i_s);\n                i_c_t = cmult(i_s, i_b_c_t);\n            }else{\n                i_c_t = i_b_c_t;\n            }\n        }else{\n            assert(false);\n        }\n        return i_c_t;\n    }\n\n    void disable_dropout(){\n        fwd_char_enc_builder.disable_dropout();\n        rev_char_enc_builder.disable_dropout();\n        fwd_enc_builder.disable_dropout();\n        rev_enc_builder.disable_dropout();\n        dec_builder.disable_dropout();\n        flag_drop_out = false;\n    }\n\n    void enable_dropout(){\n        fwd_char_enc_builder.set_dropout(opts.dropout_rate_lstm_char, 0.f);\n        rev_char_enc_builder.set_dropout(opts.dropout_rate_lstm_char, 0.f);\n        fwd_enc_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);\n        rev_enc_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);\n        dec_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);\n        flag_drop_out = true;\n    }\n\nprivate:\n    friend class boost::serialization::access;\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version) {\n        ar & p_word_enc;\n        ar & p_char_enc;\n        ar & p_feat_enc;\n        ar & p_dec_init_bias;\n        ar & p_dec_init_w;\n        ar & p_select_W;\n        ar & p_select_b;\n        ar & p_Wad;\n        ar & p_Uad;\n        ar & p_vad;\n        ar & p_Wctx;\n        ar & p_bctx;\n        ar & p_Wahf;\n        ar & p_Wahb;\n        ar & p_layer_w;\n        ar & p_add_W;\n        ar & p_add_bias;\n        ar & p_out_R;\n        ar & p_out_bias;\n        ar & dec_builder;\n        ar & rev_char_enc_builder;\n        ar & fwd_char_enc_builder;\n        ar & rev_enc_builder;\n        ar & fwd_enc_builder;\n    }\n\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "bf842af9ddc707657456f4844935ef19582cd703", "size": 21922, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "compressor/include/s2s/nn/slahan.hpp", "max_stars_repo_name": "kamigaito/SLAHAN", "max_stars_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-05-24T16:03:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T21:52:32.000Z", "max_issues_repo_path": "compressor/include/s2s/nn/slahan.hpp", "max_issues_repo_name": "kamigaito/SLAHAN", "max_issues_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-31T18:41:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T16:16:22.000Z", "max_forks_repo_path": "compressor/include/s2s/nn/slahan.hpp", "max_forks_repo_name": "kamigaito/SLAHAN", "max_forks_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-05-26T01:53:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T07:13:31.000Z", "avg_line_length": 44.2868686869, "max_line_length": 165, "alphanum_fraction": 0.6174619104, "num_tokens": 5538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.18145183260309986}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2015 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 \"order_facets_around_edges.h\"\n#include \"order_facets_around_edge.h\"\n#include \"../../sort_angles.h\"\n#include <Eigen/Geometry>\n#include <type_traits>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\ntemplate<\n    typename DerivedV,\n    typename DerivedF,\n    typename DerivedN,\n    typename DeriveduE,\n    typename uE2EType,\n    typename uE2oEType,\n    typename uE2CType >\nIGL_INLINE\ntypename std::enable_if<!std::is_same<typename DerivedV::Scalar,\ntypename CGAL::Exact_predicates_exact_constructions_kernel::FT>::value, void>::type\nigl::copyleft::cgal::order_facets_around_edges(\n        const Eigen::PlainObjectBase<DerivedV>& V,\n        const Eigen::PlainObjectBase<DerivedF>& F,\n        const Eigen::PlainObjectBase<DerivedN>& N,\n        const Eigen::PlainObjectBase<DeriveduE>& uE,\n        const std::vector<std::vector<uE2EType> >& uE2E,\n        std::vector<std::vector<uE2oEType> >& uE2oE,\n        std::vector<std::vector<uE2CType > >& uE2C ) {\n\n    typedef Eigen::Matrix<typename DerivedN::Scalar, 3, 1> Vector3F;\n    const typename DerivedV::Scalar EPS = 1e-12;\n    const size_t num_faces = F.rows();\n    const size_t num_undirected_edges = uE.rows();\n\n    auto edge_index_to_face_index = [&](size_t ei) { return ei % num_faces; };\n    auto edge_index_to_corner_index = [&](size_t ei) { return ei / num_faces; };\n\n    uE2oE.resize(num_undirected_edges);\n    uE2C.resize(num_undirected_edges);\n\n    for(size_t ui = 0;ui<num_undirected_edges;ui++)\n    {\n        const auto& adj_edges = uE2E[ui];\n        const size_t edge_valance = adj_edges.size();\n        assert(edge_valance > 0);\n\n        const auto ref_edge = adj_edges[0];\n        const auto ref_face = edge_index_to_face_index(ref_edge);\n        Vector3F ref_normal = N.row(ref_face);\n\n        const auto ref_corner_o = edge_index_to_corner_index(ref_edge);\n        const auto ref_corner_s = (ref_corner_o+1)%3;\n        const auto ref_corner_d = (ref_corner_o+2)%3;\n\n        const typename DerivedF::Scalar o = F(ref_face, ref_corner_o);\n        const typename DerivedF::Scalar s = F(ref_face, ref_corner_s);\n        const typename DerivedF::Scalar d = F(ref_face, ref_corner_d);\n\n        Vector3F edge = V.row(d) - V.row(s);\n        auto edge_len = edge.norm();\n        bool degenerated = edge_len < EPS;\n        if (degenerated) {\n            if (edge_valance <= 2) {\n                // There is only one way to order 2 or less faces.\n                edge.setZero();\n            } else {\n                edge.setZero();\n                Eigen::Matrix<typename DerivedN::Scalar, Eigen::Dynamic, 3>\n                    normals(edge_valance, 3);\n                for (size_t fei=0; fei<edge_valance; fei++) {\n                    const auto fe = adj_edges[fei];\n                    const auto f = edge_index_to_face_index(fe);\n                    normals.row(fei) = N.row(f);\n                }\n                for (size_t i=0; i<edge_valance; i++) {\n                    size_t j = (i+1) % edge_valance;\n                    Vector3F ni = normals.row(i);\n                    Vector3F nj = normals.row(j);\n                    edge = ni.cross(nj);\n                    edge_len = edge.norm();\n                    if (edge_len >= EPS) {\n                        edge.normalize();\n                        break;\n                    }\n                }\n\n                // Ensure edge direction are consistent with reference face.\n                Vector3F in_face_vec = V.row(o) - V.row(s);\n                if (edge.cross(in_face_vec).dot(ref_normal) < 0) {\n                    edge *= -1;\n                }\n\n                if (edge.norm() < EPS) {\n                    std::cerr << \"=====================================\" << std::endl;\n                    std::cerr << \"  ui: \" << ui << std::endl;\n                    std::cerr << \"edge: \" << ref_edge << std::endl;\n                    std::cerr << \"face: \" << ref_face << std::endl;\n                    std::cerr << \"  vs: \" << V.row(s) << std::endl;\n                    std::cerr << \"  vd: \" << V.row(d) << std::endl;\n                    std::cerr << \"adj face normals: \" << std::endl;\n                    std::cerr << normals << std::endl;\n                    std::cerr << \"Very degenerated case detected:\" << std::endl;\n                    std::cerr << \"Near zero edge surrounded by \"\n                        << edge_valance << \" neearly colinear faces\" <<\n                        std::endl;\n                    std::cerr << \"=====================================\" << std::endl;\n                }\n            }\n        } else {\n            edge.normalize();\n        }\n\n        Eigen::MatrixXd angle_data(edge_valance, 3);\n        std::vector<bool> cons(edge_valance);\n\n        for (size_t fei=0; fei<edge_valance; fei++) {\n            const auto fe = adj_edges[fei];\n            const auto f = edge_index_to_face_index(fe);\n            const auto c = edge_index_to_corner_index(fe);\n            cons[fei] = (d == F(f, (c+1)%3));\n            assert( cons[fei] ||  (d == F(f,(c+2)%3)));\n            assert(!cons[fei] || (s == F(f,(c+2)%3)));\n            assert(!cons[fei] || (d == F(f,(c+1)%3)));\n            Vector3F n = N.row(f);\n            angle_data(fei, 0) = ref_normal.cross(n).dot(edge);\n            angle_data(fei, 1) = ref_normal.dot(n);\n            if (cons[fei]) {\n                angle_data(fei, 0) *= -1;\n                angle_data(fei, 1) *= -1;\n            }\n            angle_data(fei, 0) *= -1; // Sort clockwise.\n            angle_data(fei, 2) = (cons[fei]?1.:-1.)*(f+1);\n        }\n\n        Eigen::VectorXi order;\n        igl::sort_angles(angle_data, order);\n\n        auto& ordered_edges = uE2oE[ui];\n        auto& consistency = uE2C[ui];\n\n        ordered_edges.resize(edge_valance);\n        consistency.resize(edge_valance);\n        for (size_t fei=0; fei<edge_valance; fei++) {\n            ordered_edges[fei] = adj_edges[order[fei]];\n            consistency[fei] = cons[order[fei]];\n        }\n    }\n}\n\ntemplate<\n    typename DerivedV,\n    typename DerivedF,\n    typename DerivedN,\n    typename DeriveduE,\n    typename uE2EType,\n    typename uE2oEType,\n    typename uE2CType >\nIGL_INLINE\ntypename std::enable_if<std::is_same<typename DerivedV::Scalar,\ntypename CGAL::Exact_predicates_exact_constructions_kernel::FT>::value, void>::type\nigl::copyleft::cgal::order_facets_around_edges(\n        const Eigen::PlainObjectBase<DerivedV>& V,\n        const Eigen::PlainObjectBase<DerivedF>& F,\n        const Eigen::PlainObjectBase<DerivedN>& N,\n        const Eigen::PlainObjectBase<DeriveduE>& uE,\n        const std::vector<std::vector<uE2EType> >& uE2E,\n        std::vector<std::vector<uE2oEType> >& uE2oE,\n        std::vector<std::vector<uE2CType > >& uE2C ) {\n\n    typedef Eigen::Matrix<typename DerivedN::Scalar, 3, 1> Vector3F;\n    typedef Eigen::Matrix<typename DerivedV::Scalar, 3, 1> Vector3E;\n    const typename DerivedV::Scalar EPS = 1e-12;\n    const size_t num_faces = F.rows();\n    const size_t num_undirected_edges = uE.rows();\n\n    auto edge_index_to_face_index = [&](size_t ei) { return ei % num_faces; };\n    auto edge_index_to_corner_index = [&](size_t ei) { return ei / num_faces; };\n\n    uE2oE.resize(num_undirected_edges);\n    uE2C.resize(num_undirected_edges);\n\n    for(size_t ui = 0;ui<num_undirected_edges;ui++)\n    {\n        const auto& adj_edges = uE2E[ui];\n        const size_t edge_valance = adj_edges.size();\n        assert(edge_valance > 0);\n\n        const auto ref_edge = adj_edges[0];\n        const auto ref_face = edge_index_to_face_index(ref_edge);\n        Vector3F ref_normal = N.row(ref_face);\n\n        const auto ref_corner_o = edge_index_to_corner_index(ref_edge);\n        const auto ref_corner_s = (ref_corner_o+1)%3;\n        const auto ref_corner_d = (ref_corner_o+2)%3;\n\n        const typename DerivedF::Scalar o = F(ref_face, ref_corner_o);\n        const typename DerivedF::Scalar s = F(ref_face, ref_corner_s);\n        const typename DerivedF::Scalar d = F(ref_face, ref_corner_d);\n\n        Vector3E exact_edge = V.row(d) - V.row(s);\n        exact_edge.array() /= exact_edge.squaredNorm();\n        Vector3F edge(\n                CGAL::to_double(exact_edge[0]),\n                CGAL::to_double(exact_edge[1]),\n                CGAL::to_double(exact_edge[2]));\n        edge.normalize();\n\n        Eigen::MatrixXd angle_data(edge_valance, 3);\n        std::vector<bool> cons(edge_valance);\n\n        for (size_t fei=0; fei<edge_valance; fei++) {\n            const auto fe = adj_edges[fei];\n            const auto f = edge_index_to_face_index(fe);\n            const auto c = edge_index_to_corner_index(fe);\n            cons[fei] = (d == F(f, (c+1)%3));\n            assert( cons[fei] ||  (d == F(f,(c+2)%3)));\n            assert(!cons[fei] || (s == F(f,(c+2)%3)));\n            assert(!cons[fei] || (d == F(f,(c+1)%3)));\n            Vector3F n = N.row(f);\n            angle_data(fei, 0) = ref_normal.cross(n).dot(edge);\n            angle_data(fei, 1) = ref_normal.dot(n);\n            if (cons[fei]) {\n                angle_data(fei, 0) *= -1;\n                angle_data(fei, 1) *= -1;\n            }\n            angle_data(fei, 0) *= -1; // Sort clockwise.\n            angle_data(fei, 2) = (cons[fei]?1.:-1.)*(f+1);\n        }\n\n        Eigen::VectorXi order;\n        igl::sort_angles(angle_data, order);\n\n        auto& ordered_edges = uE2oE[ui];\n        auto& consistency = uE2C[ui];\n\n        ordered_edges.resize(edge_valance);\n        consistency.resize(edge_valance);\n        for (size_t fei=0; fei<edge_valance; fei++) {\n            ordered_edges[fei] = adj_edges[order[fei]];\n            consistency[fei] = cons[order[fei]];\n        }\n    }\n}\n\ntemplate<\n    typename DerivedV,\n    typename DerivedF,\n    typename DeriveduE,\n    typename uE2EType,\n    typename uE2oEType,\n    typename uE2CType >\nIGL_INLINE void igl::copyleft::cgal::order_facets_around_edges(\n        const Eigen::PlainObjectBase<DerivedV>& V,\n        const Eigen::PlainObjectBase<DerivedF>& F,\n        const Eigen::PlainObjectBase<DeriveduE>& uE,\n        const std::vector<std::vector<uE2EType> >& uE2E,\n        std::vector<std::vector<uE2oEType> >& uE2oE,\n        std::vector<std::vector<uE2CType > >& uE2C ) {\n\n    //typedef Eigen::Matrix<typename DerivedV::Scalar, 3, 1> Vector3E;\n    const size_t num_faces = F.rows();\n    const size_t num_undirected_edges = uE.rows();\n\n    auto edge_index_to_face_index = [&](size_t ei) { return ei % num_faces; };\n    auto edge_index_to_corner_index = [&](size_t ei) { return ei / num_faces; };\n\n    uE2oE.resize(num_undirected_edges);\n    uE2C.resize(num_undirected_edges);\n\n    for(size_t ui = 0;ui<num_undirected_edges;ui++)\n    {\n        const auto& adj_edges = uE2E[ui];\n        const size_t edge_valance = adj_edges.size();\n        assert(edge_valance > 0);\n\n        const auto ref_edge = adj_edges[0];\n        const auto ref_face = edge_index_to_face_index(ref_edge);\n\n        const auto ref_corner_o = edge_index_to_corner_index(ref_edge);\n        const auto ref_corner_s = (ref_corner_o+1)%3;\n        const auto ref_corner_d = (ref_corner_o+2)%3;\n\n        //const typename DerivedF::Scalar o = F(ref_face, ref_corner_o);\n        const typename DerivedF::Scalar s = F(ref_face, ref_corner_s);\n        const typename DerivedF::Scalar d = F(ref_face, ref_corner_d);\n\n        std::vector<bool> cons(edge_valance);\n        std::vector<int> adj_faces(edge_valance);\n        for (size_t fei=0; fei<edge_valance; fei++) {\n            const auto fe = adj_edges[fei];\n            const auto f = edge_index_to_face_index(fe);\n            const auto c = edge_index_to_corner_index(fe);\n            cons[fei] = (d == F(f, (c+1)%3));\n            adj_faces[fei] = (f+1) * (cons[fei] ? 1:-1);\n\n            assert( cons[fei] ||  (d == F(f,(c+2)%3)));\n            assert(!cons[fei] || (s == F(f,(c+2)%3)));\n            assert(!cons[fei] || (d == F(f,(c+1)%3)));\n        }\n\n        Eigen::VectorXi order;\n        order_facets_around_edge(V, F, s, d, adj_faces, order);\n        assert((size_t)order.size() == edge_valance);\n\n        auto& ordered_edges = uE2oE[ui];\n        auto& consistency = uE2C[ui];\n\n        ordered_edges.resize(edge_valance);\n        consistency.resize(edge_valance);\n        for (size_t fei=0; fei<edge_valance; fei++) {\n            ordered_edges[fei] = adj_edges[order[fei]];\n            consistency[fei] = cons[order[fei]];\n        }\n    }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n// generated by autoexplicit.sh\ntemplate void igl::copyleft::cgal::order_facets_around_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>, int, int, bool>(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&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > const&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&, std::vector<std::vector<bool, std::allocator<bool> >, std::allocator<std::vector<bool, std::allocator<bool> > > >&);\n// generated by autoexplicit.sh\ntemplate std::enable_if<!(std::is_same<Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, CGAL::Lazy_exact_nt<CGAL::Gmpq> >::value), void>::type igl::copyleft::cgal::order_facets_around_edges<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<int, -1, -1, 0, -1, -1>, int, int, bool>(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<int, -1, -1, 0, -1, -1> > const&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > const&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&, std::vector<std::vector<bool, std::allocator<bool> >, std::allocator<std::vector<bool, std::allocator<bool> > > >&);\ntemplate void igl::copyleft::cgal::order_facets_around_edges<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 2, 0, -1, 2>, long, long, bool>(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 2, 0, -1, 2> > const&, std::vector<std::vector<long, std::allocator<long> >, std::allocator<std::vector<long, std::allocator<long> > > > const&, std::vector<std::vector<long, std::allocator<long> >, std::allocator<std::vector<long, std::allocator<long> > > >&, std::vector<std::vector<bool, std::allocator<bool> >, std::allocator<std::vector<bool, std::allocator<bool> > > >&);\ntemplate void igl::copyleft::cgal::order_facets_around_edges<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 2, 0, -1, 2>, long, long, bool>(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<int, -1, 2, 0, -1, 2> > const&, std::vector<std::vector<long, std::allocator<long> >, std::allocator<std::vector<long, std::allocator<long> > > > const&, std::vector<std::vector<long, std::allocator<long> >, std::allocator<std::vector<long, std::allocator<long> > > >&, std::vector<std::vector<bool, std::allocator<bool> >, std::allocator<std::vector<bool, std::allocator<bool> > > >&);\ntemplate void igl::copyleft::cgal::order_facets_around_edges<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 2, 0, -1, 2>, long, long, bool>(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, 2, 0, -1, 2> > const&, std::vector<std::vector<long, std::allocator<long> >, std::allocator<std::vector<long, std::allocator<long> > > > const&, std::vector<std::vector<long, std::allocator<long> >, std::allocator<std::vector<long, std::allocator<long> > > >&, std::vector<std::vector<bool, std::allocator<bool> >, std::allocator<std::vector<bool, std::allocator<bool> > > >&);\ntemplate void igl::copyleft::cgal::order_facets_around_edges<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 2, 0, -1, 2>, long, long, bool>(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 2, 0, -1, 2> > const&, std::vector<std::vector<long, std::allocator<long> >, std::allocator<std::vector<long, std::allocator<long> > > > const&, std::vector<std::vector<long, std::allocator<long> >, std::allocator<std::vector<long, std::allocator<long> > > >&, std::vector<std::vector<bool, std::allocator<bool> >, std::allocator<std::vector<bool, std::allocator<bool> > > >&);\n#ifdef WIN32\ntemplate void igl::copyleft::cgal::order_facets_around_edges<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>,-1,-1,0,-1,-1>,class Eigen::Matrix<int,-1,-1,0,-1,-1>,class Eigen::Matrix<int,-1,2,0,-1,2>,__int64,__int64,bool>(class Eigen::PlainObjectBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>,-1,-1,0,-1,-1> > const &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,-1,0,-1,-1> > const &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,2,0,-1,2> > const &,class std::vector<class std::vector<__int64,class std::allocator<__int64> >,class std::allocator<class std::vector<__int64,class std::allocator<__int64> > > > const &,class std::vector<class std::vector<__int64,class std::allocator<__int64> >,class std::allocator<class std::vector<__int64,class std::allocator<__int64> > > > &,class std::vector<class std::vector<bool,class std::allocator<bool> >,class std::allocator<class std::vector<bool,class std::allocator<bool> > > > &);\ntemplate void igl::copyleft::cgal::order_facets_around_edges<class Eigen::Matrix<double,-1,-1,0,-1,-1>,class Eigen::Matrix<int,-1,-1,0,-1,-1>,class Eigen::Matrix<int,-1,2,0,-1,2>,__int64,__int64,bool>(class Eigen::PlainObjectBase<class Eigen::Matrix<double,-1,-1,0,-1,-1> > const &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,-1,0,-1,-1> > const &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,2,0,-1,2> > const &,class std::vector<class std::vector<__int64,class std::allocator<__int64> >,class std::allocator<class std::vector<__int64,class std::allocator<__int64> > > > const &,class std::vector<class std::vector<__int64,class std::allocator<__int64> >,class std::allocator<class std::vector<__int64,class std::allocator<__int64> > > > &,class std::vector<class std::vector<bool,class std::allocator<bool> >,class std::allocator<class std::vector<bool,class std::allocator<bool> > > > &);\ntemplate void igl::copyleft::cgal::order_facets_around_edges<class Eigen::Matrix<double,-1,3,0,-1,3>,class Eigen::Matrix<int,-1,3,0,-1,3>,class Eigen::Matrix<int,-1,2,0,-1,2>,__int64,__int64,bool>(class Eigen::PlainObjectBase<class Eigen::Matrix<double,-1,3,0,-1,3> > const &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,3,0,-1,3> > const &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,2,0,-1,2> > const &,class std::vector<class std::vector<__int64,class std::allocator<__int64> >,class std::allocator<class std::vector<__int64,class std::allocator<__int64> > > > const &,class std::vector<class std::vector<__int64,class std::allocator<__int64> >,class std::allocator<class std::vector<__int64,class std::allocator<__int64> > > > &,class std::vector<class std::vector<bool,class std::allocator<bool> >,class std::allocator<class std::vector<bool,class std::allocator<bool> > > > &);\n#endif\n#endif\n", "meta": {"hexsha": "a7d45b8dfaae037ee6a636281181c0114e2a82f9", "size": 20556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/copyleft/cgal/order_facets_around_edges.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/copyleft/cgal/order_facets_around_edges.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/copyleft/cgal/order_facets_around_edges.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": 60.8165680473, "max_line_length": 1005, "alphanum_fraction": 0.6157812804, "num_tokens": 6092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1814518326030998}}
{"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 <string>\n#include <iostream>\n#include <limits>\n#include <typeinfo>\n#include <fstream>\n#include <unordered_map>\n\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/ptr_container/ptr_vector.hpp>\n#include <boost/bind.hpp>\n#include <boost/foreach.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n\n#include \"config/package_revision_autogenerated.hpp\"\n\n#include \"appcontext/CmdLineOptionProcessor.hpp\"\n#include \"appcontext/ApplicationContext.hpp\"\n\n#include \"genfile/SNPDataSource.hpp\"\n#include \"genfile/SNPDataSourceChain.hpp\"\n#include \"genfile/ThreshholdingSNPDataSource.hpp\"\n#include \"genfile/ToGP.hpp\"\n#include \"genfile/CommonSNPFilter.hpp\"\n#include \"genfile/VariantIdentifyingDataFilteringSNPDataSource.hpp\"\n#include \"genfile/CrossCohortCovariateValueMapping.hpp\"\n#include \"genfile/SampleFilter.hpp\"\n#include \"genfile/SampleFilteringSNPDataSource.hpp\"\n#include \"genfile/SampleFilteringCohortIndividualSource.hpp\"\n#include \"genfile/CompoundSampleFilter.hpp\"\n#include \"genfile/SampleFilterNegation.hpp\"\n#include \"genfile/VariableInSetSampleFilter.hpp\"\n#include \"genfile/GPThresholdingGTSetter.hpp\"\n#include \"genfile/db/Error.hpp\"\n#include \"genfile/CartesianProductVisitor.hpp\"\n\n#include \"metro/constants.hpp\"\n#include \"metro/regression/Design.hpp\"\n#include \"metro/SampleRange.hpp\"\n#include \"metro/intersect_ranges.hpp\"\n#include \"metro/count_range.hpp\"\n#include \"metro/regression/BinomialLogistic.hpp\"\n#include \"metro/regression/ThreadedLogLikelihood.hpp\"\n#include \"metro/regression/IndependentNormalWeightedLogLikelihood.hpp\"\n#include \"metro/regression/IndependentLogFWeightedLogLikelihood.hpp\"\n#include \"metro/regression/LogPosteriorDensity.hpp\"\n#include \"metro/ValueStabilisesStoppingCondition.hpp\"\n#include \"metro/Snptest25StoppingCondition.hpp\"\n#include \"metro/maximisation.hpp\"\n#include \"metro/fit_model.hpp\"\n#include \"metro/CholeskyStepper.hpp\"\n#include \"metro/FishersExactTest.hpp\"\n\n#include \"qcdb/MultiVariantStorage.hpp\"\n#include \"qcdb/FlatTableDBOutputter.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include \"Eigen/Eigenvalues\"\n\n// #define DEBUG 1\n\nnamespace globals {\n\tstd::string const program_name = \"ldbird\" ;\n\tstd::string const program_version = package_version ;\n\tstd::string const program_revision =  std::string( package_revision ).substr( 0, 7 ) ;\n}\n\nnamespace {\n\tstd::vector< std::string > collect_unique_ids( std::vector< std::string > const& ids_or_filenames ) {\n\t\tstd::vector< std::string > result ;\n\t\tfor( auto elt: ids_or_filenames ) {\n\t\t\tif( boost::filesystem::exists( elt )) {\n\t\t\t\tstd::ifstream f( elt ) ;\n\t\t\t\tstd::copy(\n\t\t\t\t\tstd::istream_iterator< std::string >( f ),\n\t\t\t\t\tstd::istream_iterator< std::string >(),\n\t\t\t\t\tstd::back_inserter< std::vector< std::string > >( result )\n\t\t\t\t) ;\n\t\t\t} else {\n\t\t\t\tresult.push_back( elt ) ;\n\t\t\t}\n\t\t}\n\t\t// now sort and uniqueify them...\n\t\tstd::sort( result.begin(), result.end() ) ;\n\t\tstd::vector< std::string >::const_iterator newBack = std::unique( result.begin(), result.end() ) ;\n\t\tresult.resize( newBack - result.begin() ) ;\n\t\treturn result ;\n\t}\n\n}\n\nstruct CorrelatorOptions: public appcontext::CmdLineOptionProcessor\n{\npublic:\n\tstd::string get_program_name() const { return globals::program_name ; }\n\n\tvoid declare_options( appcontext::OptionProcessor& options ) {\n\t\t// Meta-options\n\t\toptions.set_help_option( \"-help\" ) ;\n\t\toptions.set_spec_option( \"-spec\" ) ;\n\n\t\t// File options\n\t\toptions.declare_group( \"Input file options\" ) ;\n\t\toptions[ \"-g1\" ]\n\t\t\t.set_description( \t\"Path to first genotype file.\"\n\t\t\t\t\t\t\t\t\"The given filename may contain the wildcard character '#', which expands to match a\"\n\t\t\t\t\t\t\t\t\"one- or two-character chromosome identifier.\" )\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 1 )\n\t\t\t.set_maximum_multiplicity( 1 ) ;\n\t\toptions[ \"-g1-incl-rsids\" ]\n\t\t\t.set_description( \"Exclude all SNPs whose RSID is not in the given file(s) from the analysis.\")\n\t\t\t.set_takes_values_until_next_option()\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-g1-incl-range\" ]\n\t\t\t.set_description( \"Specify a range of SNPs (or comma-separated list of ranges of SNPs) to operate on. \"\n\t\t\t\t\"Each range should be in the format CC:xxxx-yyyy where CC is the chromosome and xxxx and yyyy are the \"\n\t\t\t\t\"start and end coordinates, or just xxxx-yyyy which matches that range from all chromosomes. \"\n\t\t\t\t\"You can also omit either of xxxx or yyyy to get all SNPs from the start or to the end of a chromosome.\" )\n\t\t\t.set_takes_values_until_next_option() ;\n\n\t\toptions.option_implies_option( \"-g1-incl-range\", \"-g1\" ) ;\n\t\toptions.option_implies_option( \"-g1-incl-rsids\", \"-g1\" ) ;\n\n\t\toptions[ \"-g2\" ]\n\t\t\t.set_description( \t\"Path to second genotype file.  If not given the first genotype file will be used.\"\n\t\t\t\t\t\t\t\t\"The given filename may contain the wildcard character '#', which expands to match a\"\n\t\t\t\t\t\t\t\t\"one- or two-character chromosome identifier.\" )\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 1 ) ;\n\n\t\toptions[ \"-g2-incl-rsids\" ]\n\t\t\t.set_description( \"Exclude all SNPs whose RSID is not in the given file(s) from the analysis.\")\n\t\t\t.set_takes_values_until_next_option()\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-g2-incl-range\" ]\n\t\t\t.set_description( \"Specify a range of SNPs (or comma-separated list of ranges of SNPs) to operate on. \"\n\t\t\t\t\"Each range should be in the format CC:xxxx-yyyy where CC is the chromosome and xxxx and yyyy are the \"\n\t\t\t\t\"start and end coordinates, or just xxxx-yyyy which matches that range from all chromosomes. \"\n\t\t\t\t\"You can also omit either of xxxx or yyyy to get all SNPs from the start or to the end of a chromosome.\" )\n\t\t\t.set_takes_values_until_next_option() ;\n\n\t\toptions.option_implies_option( \"-g2-incl-range\", \"-g2\" ) ;\n\t\toptions.option_implies_option( \"-g2-incl-rsids\", \"-g2\" ) ;\n\n\t\toptions[ \"-s\" ]\n\t\t\t.set_description( \"Path of sample file\" )\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 1 )\n\t\t\t.set_maximum_multiplicity( 1 ) ;\n\n\t\toptions.declare_group( \"Output file options\" ) ;\n\t\toptions[ \"-o\" ]\n\t\t\t.set_description( \"Output file\" )\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 1 )\n\t\t\t.set_maximum_multiplicity( 1 ) ;\n\t\toptions[ \"-details\" ]\n\t\t\t.set_description( \"Output counts and a Fisher's exact test P-value. \"\n\t\t\t\t\"Currently only supported if genotypes are haploid.\" ) ;\n\t\t\n\t\toptions.declare_group( \"Model options\" ) ;\n\t\toptions[ \"-incl-samples\"]\n\t\t\t.set_description( \"Filter out samples whose sample ID does not lie in the given file(s).\")\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-excl-samples\"]\n\t\t\t.set_description( \"Filter out samples whose sample ID lies in the given file.\")\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-incl-samples-where\"]\n\t\t\t.set_description( \"Include samples by specifying conditions on the values of columns in the sample file.\")\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-excl-samples-where\"]\n\t\t\t.set_description( \"Exclude samples by specifying conditions on the values of columns in the sample file.\")\n\t\t\t.set_takes_single_value()\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-min-r2\" ]\n\t\t\t.set_description( \"Do not output results where r^2 is lower than this threshold. \"\n\t\t\t\t\t\" (These values are still computed and contribute to the histogram.)\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( 0.05 ) ;\n\t\toptions[ \"-min-maf\" ]\n\t\t\t.set_description( \"Do not compute correlation results where the maf of either variant is lower than this threshold.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( 0 ) ;\n\t\toptions[ \"-min-N\" ]\n\t\t\t.set_description( \"Do not compute results where the total number of pairwise non-missing genotypes is below this threshold.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( 0 ) ;\n\t\toptions[ \"-min-N-propn\" ]\n\t\t\t.set_description( \"Ignore (do not compute or output) results where the propn of pairwise non-missing genotypes is below this threshold.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( 0.0 ) ;\n\t\toptions[ \"-min-distance\" ]\n\t\t\t.set_description( \"Ignore (do not compute or output) results where the variants are on the same chromosome and closer than this physical distance.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( 0 ) ;\n\t\toptions[ \"-assume-haploid\" ]\n\t\t\t.set_description( \"Convert all data to haploid calls.  This converts homozygous calls\"\n\t\t\t\t\" to haploid calls, and treats any heterozygous calls as missing.\")\n\t\t;\n\t\toptions[ \"-prior-weight\" ]\n\t\t\t.set_description( \"Specify a prior weight for samples.  \"\n\t\t\t\t\" This augments data with one of each of the four possible haploid genotype combinations \"\n\t\t\t\t\" for each pairwise comparison, with the total weight given.\"\n\t\t\t\t\" For example, a value of 1 indicates each haplotype is given 1/4 weight.\"\n\t\t\t)\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( \"0\" )\n\t\t;\n\t\toptions.declare_group( \"Miscellaneous options\" ) ;\n\t\toptions[ \"-analysis-name\" ]\n\t\t\t.set_description( \"Specify a name to label results from this analysis with.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( \"ldbird analysis\" ) ;\n\t\toptions[ \"-analysis-chunk\" ]\n\t\t\t.set_description( \"Specify a name denoting the current genomic region or chunk on which this is run.  This is intended for use in parallel environments.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( genfile::MissingValue() ) ;\n\t\toptions[ \"-analysis-id\" ]\n\t\t\t.set_description( \"Specify an integer ID for the current analysis.\" )\n\t\t\t.set_takes_single_value() ;\n\t\toptions[ \"-table-prefix\" ]\n\t\t\t.set_description( \"Specify a prefix to add to tables.  They will be called <prefix>Frequency and <prefix>R.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( \"\" ) ;\n\t\toptions[ \"-threshold\" ]\n\t\t\t.set_description( \"The threshold to apply to genotype probabilities, if necessary, to make calls.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( 0.9 ) ;\n\t\toptions.declare_group( \"Miscellaneous options\" ) ;\n\t\toptions[ \"-debug\" ]\n\t\t\t.set_description( \"Output debugging information.\" ) ;\n\t}\n} ;\n\n\nnamespace {\n\tstruct ProbSetter: public genfile::VariantDataReader::PerSampleSetter {\n\t\ttypedef std::vector< metro::SampleRange > SampleRanges ;\n\n\t\tProbSetter(\n\t\t\tEigen::MatrixXd* genotypes,\n\t\t\tEigen::VectorXi* ploidy,\n\t\t\tSampleRanges* nonmissing_samples\n\t\t):\n\t\t\tm_genotypes( genotypes ),\n\t\t\tm_ploidy( ploidy ),\n\t\t\tm_nonmissing_samples( nonmissing_samples ),\n\t\t\tm_sample_i(0)\n\t\t{\n\t\t\tassert( genotypes != 0 && nonmissing_samples != 0 && ploidy != 0 ) ;\n\t\t}\n\n\t\tvoid initialise( std::size_t nSamples, std::size_t nAlleles ) {\n\t\t\tif( nAlleles != 2 ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"ProbSetter::initialise()\",\n\t\t\t\t\t\"nAlleles=\" + genfile::string_utils::to_string( nAlleles ),\n\t\t\t\t\t\"I only support biallelic variants\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tm_genotypes->resize( nSamples, 3 ) ;\n\t\t\tm_genotypes->setZero() ;\n\t\t\tm_ploidy->resize( nSamples ) ;\n\t\t\tm_ploidy->setZero() ;\n\t\t\t\n\t\t\tm_nonmissing_samples->clear() ;\n\t\t\tm_last_nonmissing_sample_i = 0 ;\n\t\t}\n\n\t\tbool set_sample( std::size_t n ) {\n\t\t\tm_sample_i = n ;\n\t\t\treturn true ;\n\t\t}\n\n\t\tvoid set_number_of_entries(\n\t\t\tuint32_t ploidy, std::size_t n,\n\t\t\tgenfile::OrderType const order_type,\n\t\t\tgenfile::ValueType const value_type\n\t\t) {\n\t\t\tif( value_type != genfile::eProbability ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::set_number_of_entries()\",\n\t\t\t\t\t\"value_type=\" + genfile::string_utils::to_string( value_type ),\n\t\t\t\t\t\"Expected genotype call probabilities (e.g. GP field).\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tif( order_type != genfile::ePerUnorderedGenotype ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::set_number_of_entries()\",\n\t\t\t\t\t\"order_type=\" + genfile::string_utils::to_string( order_type ),\n\t\t\t\t\t\"Expected genotype call probabilities (e.g. GP field).\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tif( ploidy != 2 ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::set_number_of_entries()\",\n\t\t\t\t\t\"order_type=\" + genfile::string_utils::to_string( order_type ),\n\t\t\t\t\t\"Expected a diploid sample.\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\t(*m_ploidy)(m_sample_i) = ploidy ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, genfile::MissingValue const value ) {\n\t\t\t// This sample has missing data, end our current sample range here.\n\t\t\tif( m_sample_i > m_last_nonmissing_sample_i ) {\n\t\t\t\tm_nonmissing_samples->push_back(\n\t\t\t\t\tmetro::SampleRange( m_last_nonmissing_sample_i, m_sample_i )\n\t\t\t\t) ;\n\t\t\t}\n\t\t\t// Skip this sample for next range.\n\t\t\tm_last_nonmissing_sample_i = m_sample_i + 1 ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, Integer const value ) {\n\t\t\tassert(0) ; // expected a probabilty\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, double const value ) {\n\t\t\tif( m_sample_i >= m_last_nonmissing_sample_i ) {\n\t\t\t\t(*m_genotypes)(m_sample_i, entry_i) = value ;\n\t\t\t}\n\t\t}\n\n\t\tvoid finalise() {\n\t\t\t// Add the final sample range if needed.\n\t\t\tif( (m_sample_i+1) > m_last_nonmissing_sample_i ) {\n\t\t\t\tm_nonmissing_samples->push_back(\n\t\t\t\t\tmetro::SampleRange( m_last_nonmissing_sample_i, m_sample_i+1 )\n\t\t\t\t) ;\n\t\t\t}\n\t\t\t\n\t\t\t// For probability data, we need to handle the case of missingness encoded as zero probabilities.\n\t\t\t// Do that now by inspecting the genotypes.\n\t\t\t{\n\t\t\t\tstd::vector< metro::SampleRange > ranges ;\n\t\t\t\tstd::size_t last_nonmissing_sample_i = 0 ;\n\t\t\t\tstd::size_t i = 0 ;\n\t\t\t\tfor( ; i < m_genotypes->rows(); ++i ) {\n\t\t\t\t\tif( m_genotypes->row(i).sum() == 0.0 ) {\n\t\t\t\t\t\tif( i > last_nonmissing_sample_i ) {\n\t\t\t\t\t\t\tranges.push_back( metro::SampleRange( last_nonmissing_sample_i, i )) ;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlast_nonmissing_sample_i = i+1 ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif( i > last_nonmissing_sample_i ) {\n\t\t\t\t\tranges.push_back( metro::SampleRange( last_nonmissing_sample_i, i )) ;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t*m_nonmissing_samples = metro::impl::intersect_ranges( *m_nonmissing_samples, ranges ) ;\n\t\t\t}\n\t\t}\n\t\t\n\tprivate:\n\t\tEigen::MatrixXd* m_genotypes ;\n\t\tEigen::VectorXi* m_ploidy ;\n\t\tSampleRanges* m_nonmissing_samples ;\n\t\tstd::size_t m_last_nonmissing_sample_i ;\n\t\tstd::size_t m_sample_i ;\n\t} ;\n}\n\nstruct LDbirdApplication: public appcontext::ApplicationContext\n{\npublic:\n\t\n\ttypedef Eigen::MatrixXd Matrix ;\n\ttypedef Eigen::VectorXd Vector ;\n\ttypedef Eigen::VectorXi IntegerVector ;\n\ttypedef Eigen::RowVectorXd RowVector ;\n\t\npublic:\n\tLDbirdApplication( int argc, char** argv ):\n\t\tappcontext::ApplicationContext(\n\t\t\tglobals::program_name,\n\t\t\tglobals::program_version + \", revision \" + globals::program_revision,\n\t\t\tstd::auto_ptr< appcontext::OptionProcessor >( new CorrelatorOptions ),\n\t\t\targc,\n\t\t\targv,\n\t\t\t\"-log\"\n\t\t)\n\t{\n\t\tprocess() ;\n\t}\n\t\nprivate:\n\tvoid process() {\n\t\ttry {\n\t\t\tunsafe_process() ;\n\t\t}\n\t\tcatch( genfile::InputError const& e ) {\n\t\t\tget_ui_context().logger() << \"!! Error (\" << e.what() << \"): \" << e.format_message() << \".\\n\" ;\n\t\t\tthrow appcontext::HaltProgramWithReturnCode( -1 ) ;\n\t\t}\n\t\tcatch( genfile::FileNotFoundError const& e ) {\n\t\t\tget_ui_context().logger() << \"\\nError: No file matching \\\"\" << e.filespec() << \"\\\" could be found.\\n\" ;\n\t\t\tthrow appcontext::HaltProgramWithReturnCode( -1 ) ;\n\t\t}\n\t\tcatch( genfile::db::Error const& e ) {\n\t\t\tget_ui_context().logger() << \"!! Error (\" << e.what() << \") with the following statement: \\\"\"\n\t\t\t\t<< e.sql()\n\t\t\t\t<< \"\\\".\\n\" ;\n\t\t\tthrow appcontext::HaltProgramWithReturnCode( -1 ) ;\n\t\t}\n\t}\n\t\n\tvoid unsafe_process() {\n\t\tusing genfile::string_utils::to_string ;\n\t\t\n\t\tgenfile::SampleFilterConjunction::UniquePtr sample_filter = get_sample_filter() ;\n\n\t\tgenfile::CohortIndividualSource::UniquePtr\n\t\t\tsamples = genfile::CohortIndividualSource::create( options().get< std::string >( \"-s\" ) ) ;\n\n\t\tstd::set< std::size_t > const excluded_samples = compute_excluded_samples( *sample_filter, *samples ) ;\n\t\tif( excluded_samples.size() > 0 ) {\n\t\t\tsamples.reset(\n\t\t\t\tgenfile::SampleFilteringCohortIndividualSource::create( samples, excluded_samples ).release()\n\t\t\t) ;\n\t\t}\n\n\t\tgenfile::SNPDataSource::UniquePtr g1 = open_genotype_data_sources(\n\t\t\toptions().get< std::string >( \"-g1\" ),\n\t\t\tget_variant_filter(\n\t\t\t\t\"-g1-incl-range\",\n\t\t\t\t\"-g1-incl-rsids\"\n\t\t\t),\n\t\t\texcluded_samples\n\t\t) ;\n\n\t\tgenfile::SNPDataSource::UniquePtr g2 ;\n\t\tif( options().check( \"-g2\" )) {\n\t\t\t// Two files given, we'll do a full carThis mechanism chooses a full cartesian product or a lower triangle implementation.\n\t\t\t// TODO: make this more obvious / cleaner.\n\t\t\tg2 = open_genotype_data_sources(\n\t\t\t\toptions().get< std::string >( \"-g2\" ),\n\t\t\t\tget_variant_filter(\n\t\t\t\t\t\"-g2-incl-range\",\n\t\t\t\t\t\"-g2-incl-rsids\"\n\t\t\t\t),\n\t\t\t\texcluded_samples\n\t\t\t) ;\n\t\t} else {\n\t\t\tg2 = open_genotype_data_sources(\n\t\t\t\toptions().get< std::string >( \"-g1\" ),\n\t\t\t\tget_variant_filter(\n\t\t\t\t\t\"-g1-incl-range\",\n\t\t\t\t\t\"-g1-incl-rsids\"\n\t\t\t\t),\n\t\t\t\texcluded_samples\n\t\t\t) ;\n\t\t}\n\t\t\n\t\tstd::size_t const N = samples->size() ;\n\t\tif( g1->number_of_samples() != N ) {\n\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\"LDbirdApplication::unsafe_process()\",\n\t\t\t\t\"-g1 \\\"\" + options().get< std::string >( \"-g1\" ) + \"\\\"\",\n\t\t\t\t\"Wrong number of samples (\" + to_string(g1->number_of_samples()) + \", expected \" + to_string(N) + \")\"\n\t\t\t) ;\n\t\t}\n\t\tif( g2->number_of_samples() != N ) {\n\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\"LDbirdApplication::unsafe_process()\",\n\t\t\t\t\"-g2 \\\"\" + options().get< std::string >( \"-g2\" ) + \"\\\"\",\n\t\t\t\t\"Wrong number of samples (\" + to_string(g2->number_of_samples()) + \", expected \" + to_string(N) + \")\"\n\t\t\t) ;\n\t\t}\n\t\t\n\t\twrite_preamble( *g1, *g2, *samples ) ;\n\t\t\n\t\tstd::vector< int64_t > histogram( 2049, 0 ) ;\n\t\t\n\t\tboost::optional< genfile::db::Connection::RowId > analysis_id ;\n\t\tif( options().check( \"-analysis-id\" ) ) {\n\t\t\tanalysis_id = options().get< genfile::db::Connection::RowId >( \"-analysis-id\" ) ;\n\t\t}\n\n\t\tstd::string const fileSpec = options().get< std::string > ( \"-o\" ) ;\n\t\tstd::string const tablePrefix = options().get< std::string > ( \"-table-prefix\" ) ;\n\n\t\t{\n\t\t\tqcdb::Storage::UniquePtr frequencyStorage = qcdb::Storage::create(\n\t\t\t\tfileSpec + \":\" + tablePrefix + \"Frequency\",\n\t\t\t\toptions().get< std::string > ( \"-analysis-name\" ),\n\t\t\t\toptions().get< std::string > ( \"-analysis-chunk\" ),\n\t\t\t\tget_application_metadata(),\n\t\t\t\t\"position,alleles\",\n\t\t\t\tanalysis_id\n\t\t\t) ;\n\t\t\tanalysis_id = frequencyStorage->analysis_id() ;\n\n\t\t\tfrequencyStorage->add_variable( \"number_of_haplotypes\" ) ;\n\t\t\tfrequencyStorage->add_variable( \"frequency\" ) ;\n\t\t\t//frequencyStorage->set_variant_names( std::vector< std::string >({ \"g1\", \"g2\" })) ;\n\n\t\t\tqcdb::MultiVariantStorage::UniquePtr correlationStorage = qcdb::MultiVariantStorage::create(\n\t\t\t\tfileSpec + \":\" + tablePrefix + \"R+without rowid\",\n\t\t\t\t2,\n\t\t\t\toptions().get< std::string > ( \"-analysis-name\" ),\n\t\t\t\toptions().get< std::string > ( \"-analysis-chunk\" ),\n\t\t\t\tget_application_metadata(),\n\t\t\t\t\"position,alleles\",\n\t\t\t\tanalysis_id\n\t\t\t) ;\n\n\t\t\tcorrelationStorage->set_variant_names( std::vector< std::string >({ \"g1\", \"g2\" })) ;\n\t\t\tcorrelationStorage->add_variable( \"N\" ) ;\n\t\t\tcorrelationStorage->add_variable( \"encoded_r\" ) ;\n\n\t\t\tif( options().check( \"-details\" )) {\n\t\t\t\tfor( int i = 0; i < 2; ++i ) {\n\t\t\t\t\tfor( int j = 0; j < 2; ++j ) {\n\t\t\t\t\t\tcorrelationStorage->add_variable( \"n_\" + to_string(i) + to_string(j) ) ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcorrelationStorage->add_variable( \"fet_pvalue\" ) ;\n\t\t\t}\n\t\t\t// This mechanism chooses a full cartesian product or a lower triangle implementation\n\t\t\t// TODO: make this more obvious / cleaner.\n\t\t\tgenfile::CartesianProductVisitor visitor( !options().check( \"-g2\" ) ) ;\n\t\t\tvisitor.add_source( \"g1\", g1.get() ) ;\n\t\t\tvisitor.add_source( \"g2\", g2.get() ) ;\n\n\t\t\tif( options().check( \"-min-distance\" )) {\n\t\t\t\tvisitor.set_min_distance( options().get< int64_t >( \"-min-distance\" )) ;\n\t\t\t}\n\n\t\t\trun( visitor, *samples, *frequencyStorage, *correlationStorage, &histogram ) ;\n\n\t\t\tfrequencyStorage->finalise() ;\n\t\t\tcorrelationStorage->finalise() ;\n\t\t}\n\t\t\n\t\t{\n\t\t\tqcdb::MultiVariantStorage::UniquePtr histogramStorage = qcdb::MultiVariantStorage::create(\n\t\t\t\tfileSpec + \":\" + tablePrefix + \"Histogram\",\n\t\t\t\t0,\n\t\t\t\toptions().get< std::string > ( \"-analysis-name\" ),\n\t\t\t\toptions().get< std::string > ( \"-analysis-chunk\" ),\n\t\t\t\tget_application_metadata(),\n\t\t\t\t\"position,alleles\",\n\t\t\t\tanalysis_id\n\t\t\t) ;\n\t\t\thistogramStorage->add_variable( \"encoded_r\" ) ;\n\t\t\thistogramStorage->add_variable( \"count\" ) ;\n\t\t\tqcdb::MultiVariantStorage::Key const key ;\n\t\t\tfor( std::size_t i = 0; i < histogram.size(); ++i ) {\n\t\t\t\thistogramStorage->create_new_key( key ) ;\n\t\t\t\thistogramStorage->store_data_for_key( key, \"encoded_r\", int64_t(i) ) ;\n\t\t\t\thistogramStorage->store_data_for_key( key, \"count\", histogram[i] ) ;\n\t\t\t}\n\t\t\thistogramStorage->finalise() ;\n\t\t}\n\t}\n\t\n\tgenfile::CommonSNPFilter::UniquePtr get_variant_filter(\n\t\tstd::string const& incl_range_option,\n\t\tstd::string const& incl_ids_option\n\t) const {\n\t\tgenfile::CommonSNPFilter::UniquePtr result ;\n\t\tif( options().check( incl_range_option ) || options().check( incl_ids_option ) ) {\n\t\t\tresult.reset( new genfile::CommonSNPFilter() ) ;\n\t\t\tif( options().check( incl_range_option )) {\n\t\t\t\tstd::vector< std::string > specs = collect_unique_ids( options().get_values< std::string >( incl_range_option ) ) ;\n\t\t\t\tfor ( std::size_t i = 0; i < specs.size(); ++i ) {\n\t\t\t\t\tresult->include_snps_in_range(\n\t\t\t\t\t\tgenfile::GenomePositionRange::parse( specs[i] )\n\t\t\t\t\t) ;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif( options().check( incl_ids_option )) {\n\t\t\t\tstd::vector< std::string > files = collect_unique_ids( options().get_values< std::string > ( incl_ids_option ) ) ;\n\t\t\t\tresult->include_snps_in_set(\n\t\t\t\t\tstd::set< std::string >( files.begin(), files.end() ),\n\t\t\t\t\tgenfile::CommonSNPFilter::RSIDs\n\t\t\t\t) ;\n\t\t\t}\n\t\t}\n\t\treturn result ;\n\t}\n\t\n\tgenfile::SampleFilterConjunction::UniquePtr get_sample_filter() const {\n\t\tgenfile::SampleFilterConjunction::UniquePtr filter( new genfile::SampleFilterConjunction() ) ;\n\t\tgenfile::SampleFilterDisjunction::UniquePtr sample_inclusion_filter( new genfile::SampleFilterDisjunction() ) ;\n\n\t\tif( options().check_if_option_was_supplied( \"-incl-samples\" ) ) {\n\t\t\tgenfile::SampleFilter::UniquePtr id1_filter = get_sample_id_filter(\n\t\t\t\toptions().get_values< std::string >( \"-incl-samples\" )\n\t\t\t) ;\n\t\t\tsample_inclusion_filter->add_clause( genfile::SampleFilter::UniquePtr( id1_filter.release() ) ) ;\n\t\t}\n\n\t\tif( options().check_if_option_was_supplied( \"-excl-samples\" ) ) {\n\t\t\tgenfile::SampleFilter::UniquePtr id1_filter = get_sample_id_filter(\n\t\t\t\toptions().get_values< std::string >( \"-excl-samples\" )\n\t\t\t) ;\n\t\t\tfilter->add_clause(\n\t\t\t\tgenfile::SampleFilter::UniquePtr(\n\t\t\t\t\tnew genfile::SampleFilterNegation(\n\t\t\t\t\t\tid1_filter\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t) ;\n\t\t}\n\n\t\tif( options().check_if_option_was_supplied( \"-incl-samples-where\" ) ) {\n\t\t\tstd::vector< std::string > conditions = options().get_values< std::string >( \"-incl-samples-where\" ) ;\n\t\t\t// we OR together different WHERE clauses.\n\t\t\tfor( std::size_t i = 0; i < conditions.size(); ++i ) {\n\t\t\t\tsample_inclusion_filter->add_clause( genfile::SampleFilter::create( conditions[i] )) ;\n\t\t\t}\n\t\t}\n\n\t\tif( options().check_if_option_was_supplied( \"-excl-samples-where\" ) ) {\n\t\t\tstd::vector< std::string > conditions = options().get_values< std::string >( \"-excl-samples-where\" ) ;\n\t\t\t// we AND together different WHERE clauses.\n\t\t\tgenfile::SampleFilterDisjunction::UniquePtr where( new genfile::SampleFilterDisjunction() ) ;\n\t\t\tfor( std::size_t i = 0; i < conditions.size(); ++i ) {\n\t\t\t\twhere->add_clause( genfile::SampleFilter::create( conditions[i] )) ;\n\t\t\t}\n\t\t\tfilter->add_clause(\n\t\t\t\tgenfile::SampleFilter::UniquePtr(\n\t\t\t\t\tnew genfile::SampleFilterNegation(\n\t\t\t\t\t\tgenfile::SampleFilter::UniquePtr( where.release() )\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t) ;\n\t\t}\n\t\tif( sample_inclusion_filter->number_of_clauses() > 0 ) {\n\t\t\tfilter->add_clause( genfile::SampleFilter::UniquePtr( sample_inclusion_filter.release() ) ) ;\n\t\t}\n\n\t\treturn filter ;\n\t}\n\n\tstd::set< std::size_t > compute_excluded_samples( genfile::SampleFilter const& filter, genfile::CohortIndividualSource const& samples ) const {\n\t\tstd::vector< std::size_t > included_samples ;\n\t\tvoid(std::vector<std::size_t>::*push_back)(std::size_t const&) = &std::vector<std::size_t>::push_back ;\n\t\tfilter.test(\n\t\t\tsamples,\n\t\t\tboost::bind(\n\t\t\t\tpush_back,\n\t\t\t\t&included_samples,\n\t\t\t\t_1\n\t\t\t)\n\t\t) ;\n\t\tstd::set< std::size_t > excluded_samples(\n\t\t\tboost::counting_iterator< std::size_t >(0),\n\t\t\tboost::counting_iterator< std::size_t >( samples.get_number_of_individuals() )\n\t\t) ;\n\t\tfor( std::size_t i = 0; i < included_samples.size(); ++i ) {\n\t\t\texcluded_samples.erase( included_samples[i] ) ;\n\t\t}\n\t\treturn excluded_samples ;\n\t}\n\n\tgenfile::SampleFilter::UniquePtr get_sample_id_filter( std::vector< std::string > const& filenames ) const {\n\t\tgenfile::VariableInSetSampleFilter::UniquePtr result( new genfile::VariableInSetSampleFilter( \"ID_1\" )) ;\n\t\tfor( std::size_t i = 0; i < filenames.size(); ++i ) {\n\t\t\tstd::string elt ;\n\t\t\tstd::ifstream is( filenames[i].c_str() ) ;\n\t\t\twhile( is >> elt ) {\n\t\t\t\tresult->add_level( elt ) ;\n\t\t\t}\n\t\t}\n\t\treturn genfile::SampleFilter::UniquePtr( result.release() ) ;\n\t}\n\t\n\tgenfile::SNPDataSource::UniquePtr open_genotype_data_sources(\n\t\tstd::string const& filename,\n\t\tgenfile::CommonSNPFilter::UniquePtr filter,\n\t\tstd::set< std::size_t > const& excluded_samples,\n\t\tbool threshold = false\n\t) {\n\t\tstd::vector< genfile::wildcard::FilenameMatch > filenames\n\t\t\t= genfile::wildcard::find_files_by_chromosome(\n\t\t\t\tfilename,\n\t\t\t\tgenfile::wildcard::eALL_CHROMOSOMES\n\t\t\t) ;\n\n\t\tgenfile::SNPDataSource::UniquePtr source( \n\t\t\tgenfile::SNPDataSourceChain::create(\n\t\t\t\tfilenames\n\t\t\t).release()\n\t\t) ;\n\t\tif( filter.get() ) {\n\t\t\tsource.reset(\n\t\t\t\tgenfile::VariantIdentifyingDataFilteringSNPDataSource::create(\n\t\t\t\t\tsource,\n\t\t\t\t\tgenfile::VariantIdentifyingDataTest::UniquePtr( filter.release() )\n\t\t\t\t).release()\n\t\t\t) ;\n\t\t}\n\t\tif( threshold ) {\n\t\t\tsource.reset(\n\t\t\t\tnew genfile::ThreshholdingSNPDataSource( source, 0.9 )\n\t\t\t) ;\n\t\t}\n\t\tif( excluded_samples.size() > 0 ) {\n\t\t\tsource.reset(\n\t\t\t\tnew genfile::SampleFilteringSNPDataSource( source, excluded_samples )\n\t\t\t) ;\n\t\t}\n\t\treturn source ;\n\t}\n\n\tvoid write_preamble(\n\t\tgenfile::SNPDataSource const& host,\n\t\tgenfile::SNPDataSource const& para,\n\t\tgenfile::CohortIndividualSource const& samples\n\t) {\n\t\tget_ui_context().logger() << \"Loaded data for \" << samples.size() << \" samples.\\n\" ;\n\t\tget_ui_context().logger() << \"  First dataset:\\n\" << host.get_summary() << \"\\n\" ;\n\t\tget_ui_context().logger() << \" Second dataset:\\n\" << para.get_summary() << \"\\n\" ;\n\t}\n\n\n\tvoid run(\n\t\tgenfile::MultiSourceVisitor& visitor,\n\t\tgenfile::CohortIndividualSource const& samples,\n\t\tqcdb::Storage& frequencyOutput,\n\t\tqcdb::MultiVariantStorage& correlationOutput,\n\t\tstd::vector< int64_t >* histogram\n\t) {\n\t\tappcontext::UIContext::ProgressContext progress_context = get_ui_context().get_progress_context( \"Testing\" ) ;\n\t\thistogram->resize( 2049 ) ;\n\t\tstd::fill( histogram->begin(), histogram->end(), 0 ) ;\n\t\tfor(\n\t\t\tstd::size_t count = 0;\n\t\t\tvisitor.step(\n\t\t\t\t[this,&frequencyOutput,&correlationOutput,&histogram](\n\t\t\t\t\tstd::vector< int > const& changed,\n\t\t\t\t\tstd::vector< genfile::VariantIdentifyingData > const& variants,\n\t\t\t\t\tstd::vector< genfile::VariantDataReader::SharedPtr > const& readers\n\t\t\t\t) {\n\t\t\t\t\tthis->process_one(\n\t\t\t\t\t\tchanged,\n\t\t\t\t\t\tvariants,\n\t\t\t\t\t\treaders,\n\t\t\t\t\t\tfrequencyOutput,\n\t\t\t\t\t\tcorrelationOutput,\n\t\t\t\t\t\thistogram\n\t\t\t\t\t) ;\n\t\t\t\t}\n\t\t\t) ;\n\t\t\t++count\n\t\t) {\n\t\t\tprogress_context( count, visitor.count() ) ;\n\t\t} ;\n\t\tprogress_context.finish() ;\n\t}\n\t\n\tvoid process_one(\n\t\tstd::vector< int > const& changed,\n\t\tstd::vector< genfile::VariantIdentifyingData > const& variants,\n\t\tstd::vector< genfile::VariantDataReader::SharedPtr > const& readers,\n\t\tqcdb::Storage& frequencyOutput,\n\t\tqcdb::MultiVariantStorage& correlationOutput,\n\t\tstd::vector< int64_t >* histogram\n\t) {\n\t\tusing genfile::string_utils::to_string ;\n\n\t\tif( m_dosages.size() != changed.size() ) {\n\t\t\tm_dosages.resize( changed.size() ) ;\n\t\t\tm_ploidy.resize( changed.size() ) ;\n\t\t\tm_nonmissingness.resize( changed.size() ) ;\n\t\t}\n\t\tdouble const prior_weight = options().get< double >( \"-prior-weight\" ) ;\n\t\tdouble min_maf = 0.5 ;\n\t\tfor( std::size_t i = 0; i < changed.size(); ++i ) {\n\t\t\tif( changed[i] == 1 ) {\n\t\t\t\tDosageSetter setter( &(m_dosages[i]), &(m_ploidy[i]), &(m_nonmissingness[i]), options().check( \"-assume-haploid\" )) ;\n\t\t\t\treaders[i]->get( \":genotypes:\", genfile::to_GP_unphased( setter )) ;\n\t\t\t}\n\t\t\t\n#if DEBUG\n\t\t\tstd::cerr << globals::program_name + \":process_one(): variant \" << i << \": \" << variants[i] << \":\\n\" ;\n\t\t\tstd::cerr << \"Loaded data with nonmissingness: \" << m_nonmissingness[i] << \".\\n\" ;\n#endif\n\n\t\t\tFrequencyStore::const_iterator where = m_frequencies.find( variants[i] ) ;\n\t\t\tdouble frequency = 0.0 ;\n\t\t\tif( where != m_frequencies.end() ) {\n\t\t\t\tfrequency = where->second ;\n\t\t\t} else {\n\t\t\t\tstd::pair< double, int64_t > computedFrequency = compute_regularised_frequency( m_dosages[i], m_ploidy[i], m_nonmissingness[i], prior_weight ) ;\n\t\t\t\tfrequency = computedFrequency.first ;\n\t\t\t\t\n\t\t\t\t// not yet computed, so store it\n\t\t\t\tm_frequencies[ variants[i] ] = frequency ;\n\t\t\t\t// Output the sample count and the frequency\n\t\t\t\tfrequencyOutput.store_per_variant_data(\n\t\t\t\t\tvariants[i],\n\t\t\t\t\t\"number_of_haplotypes\",\n\t\t\t\t\tcomputedFrequency.second\n\t\t\t\t) ;\n\t\t\t\tfrequencyOutput.store_per_variant_data(\n\t\t\t\t\tvariants[i],\n\t\t\t\t\t\"frequency\",\n\t\t\t\t\tfrequency\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tmin_maf = std::min( min_maf, std::min( frequency, 1.0 - frequency )) ;\n\t\t}\n\t\t\n\t\t// Bail out if any of the variants are too rare\n\t\tif( min_maf < options().get< double >( \"-min-maf\" )) {\n\t\t\treturn ;\n\t\t}\n\t\t\n\t\tint const total_number_of_samples = m_dosages[0].size() ;\n\t\tstd::vector< metro::SampleRange > included_samples( 1, metro::SampleRange( 0, total_number_of_samples )) ;\n\t\tfor( std::size_t i = 0; i < changed.size(); ++i ) {\n\t\t\tincluded_samples = metro::impl::intersect_ranges( included_samples, m_nonmissingness[i] ) ;\n\t\t}\n\t\t\n\t\t// Bail out if there aren't enough samples in the pairwise comparison\n\t\t{\n\t\t\tstd::size_t count = metro::impl::count_range( included_samples ) ;\n\t\t\tif(\n\t\t\t\t(count < options().get< double >( \"-min-N\" ))\n\t\t\t \t   || (( double(count)/total_number_of_samples ) < options().get< double >( \"-min-N-propn\" ))\n\t\t\t) {\n\t\t\t\treturn ;\n\t\t\t}\n\t\t}\n\n\t\tdouble covariance = 0.0, correlation = 0.0, N = 0.0 ;\n\t\t\n\t\tcompute_regularised_correlation(\n\t\t\tm_dosages, m_ploidy, included_samples,\n\t\t\t&covariance, &correlation, &N,\n\t\t\tprior_weight\n\t\t) ;\n\t\t\n\t\t// ints in sqlite use only 2 bytes if up to +ve integer 2287.\n\t\t// We map -1...1 to 0...2048, such that the transformation\n\t\t//\n\t\t// correlation = (stored_value / 1024) - 1.0\n\t\t// or\n\t\t// correlation = (stored_value - 1024.0) / 1024.0\n\t\t// maps back to correlation space.\n\t\t//\n\t\tint64_t const encoded_r = ( std::round((correlation + 1.0) * 1024 )) ;\n\t\t++((*histogram)[ encoded_r ]) ;\n\n\t\tif( ( correlation * correlation ) >= options().get< double >( \"-min-r2\" ) ) {\n\t\t\tcorrelationOutput.store_data_for_key(\n\t\t\t\tvariants,\n\t\t\t\t\"N\",\n\t\t\t\tint64_t(N)\n\t\t\t) ;\n\t\t\t// We store correlations as integers on the scale -16384 to 16384.\n\t\t\t// This is because sqlite has compression for integer storage, such that\n\t\t\t// reals take 8 bytes but integers take\n\t\t\tcorrelationOutput.store_data_for_key(\n\t\t\t\tvariants,\n\t\t\t\t\"encoded_r\",\n\t\t\t\tencoded_r\n\t\t\t) ;\n\t\t\t\n\t\t\tif( options().check( \"-details\" )) {\n\t\t\t\tEigen::MatrixXd const table = tabulate( m_dosages, m_ploidy, included_samples ) ;\n\t\t\t\tfor( int i = 0; i < table.rows(); ++i ) {\n\t\t\t\t\tfor( int j = 0; j < table.cols(); ++j ) {\n\t\t\t\t\t\tcorrelationOutput.store_data_for_key(\n\t\t\t\t\t\t\tvariants,\n\t\t\t\t\t\t\t\"n_\" + to_string(i) + to_string(j),\n\t\t\t\t\t\t\ttable(i,j)\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\tif( m_ploidy[0].maxCoeff() == 1 ) {\n\t\t\t\t\tmetro::FishersExactTest test( table ) ;\n\t\t\t\t\tdouble pvalue = test.get_pvalue( metro::FishersExactTest::eTwoSided ) ;\n\t\t\t\t\tcorrelationOutput.store_data_for_key(\n\t\t\t\t\t\tvariants,\n\t\t\t\t\t\t\"fet_pvalue\",\n\t\t\t\t\t\tpvalue\n\t\t\t\t\t) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#if DEBUG\n\t\tstd::cerr << globals::program_name + \":process_one():\\n\" ;\n\t\tstd::cerr << \"dosage1: \" << m_dosages[0].head( 15 ).transpose() << \"...\\n\" ; \n\t\tstd::cerr << \"dosage2: \" << m_dosages[1].head( 15 ).transpose() << \"...\\n\" ; \n\t\tstd::cerr << \"N: \" << N << \".\\n\" ;\n\t\tstd::cerr << \"covariance: \" << covariance << \".\\n\" ;\n\t\tstd::cerr << \"correlation: \" << correlation << \".\\n\" ;\n\t\tstd::cerr << \"included: \" << included_samples << \".\\n\" ;\n#endif\n\t\t\t\n\t}\n\t\nprivate:\n\tstd::vector< Eigen::VectorXd > m_dosages ;\n\tstd::vector< Eigen::VectorXd > m_ploidy ;\n\tstd::vector< std::vector< metro::SampleRange > > m_nonmissingness ;\n\ttypedef std::map< genfile::VariantIdentifyingData, double > FrequencyStore ;\n\tFrequencyStore m_frequencies ;\n\t\nprivate:\n\t\n\tstd::pair< double, int64_t > compute_regularised_frequency(\n\t\tEigen::VectorXd const& dosages,\n\t\tEigen::VectorXd const& ploidy,\n\t\tstd::vector< metro::SampleRange > const& included_samples,\n\t\tdouble prior_weight = 1.0\n\t) {\n\t\tdouble result = 0.0 ;\n\t\tdouble N = 0.0 ;\n\t\tfor( std::size_t i = 0; i < included_samples.size(); ++i ) {\n\t\t\tmetro::SampleRange const& range = included_samples[i] ;\n\t\t\tresult += dosages.segment( range.begin(), range.size() ).sum() ;\n\t\t\tN += ploidy.segment( range.begin(), range.size() ).sum() ;\n\t\t}\n\t\t// Assume we have additional data adding up to prior_weight haploid samples\n\t\t// evenly split between both alleles\n\t\tresult += prior_weight / 2 ;\n\t\tN += prior_weight ;\n\t\treturn std::make_pair( result / N, int64_t( N ) ) ;\n\t}\n\n\tvoid compute_regularised_correlation(\n\t\tstd::vector< Eigen::VectorXd > const& dosages,\n\t\tstd::vector< Eigen::VectorXd > const& ploidy,\n\t\tstd::vector< metro::SampleRange > const& included_samples,\n\t\tdouble* covariance,\n\t\tdouble* correlation,\n\t\tdouble* number_of_samples,\n\t\tdouble const prior_weight = 1.0\n\t) {\n\t\tassert( dosages.size() == 2 ) ;\n\t\tassert( covariance ) ;\n\t\tassert( correlation ) ;\n\t\tassert( number_of_samples ) ;\n\t\tassert( ploidy[0] == ploidy[1] ) ;\n\t\tstd::vector< double > frequencies( dosages.size(), 0.0 ) ;\n\n\t\ttypedef Eigen::VectorBlock< Eigen::VectorXd const > ConstBlock ;\n\t\ttypedef Eigen::VectorBlock< Eigen::VectorXi const > ConstIntegerBlock ;\n\n\t\t// Although frequencies are computed above, we recompute here because the\n\t\t// number of included samples may differ for the pairwise test.\n\t\tfor( std::size_t v = 0; v < frequencies.size(); ++v ) {\n\t\t\tfrequencies[v] = compute_regularised_frequency(\n\t\t\t\tdosages[v], ploidy[v], included_samples, prior_weight\n\t\t\t).first ;\n\t\t}\n\n\t\tdouble result = 0.0 ;\n\t\tdouble N = 0.0 ;\n\t\tstd::vector< double > variances( dosages.size(), 0.0 ) ;\n\t\tfor( std::size_t i = 0; i < included_samples.size(); ++i ) {\n\t\t\tmetro::SampleRange const& range = included_samples[i] ;\n\t\t\tConstBlock d0 = dosages[0].segment( range.begin(), range.size() ) ;\n\t\t\tConstBlock d1 = dosages[1].segment( range.begin(), range.size() ) ;\n\t\t\tConstBlock p = ploidy[0].segment( range.begin(), range.size() ) ;\n\t\t\tresult += (\n\t\t\t\t( d0 - p * frequencies[0] ).array()\n\t\t\t\t* ( d1 - p * frequencies[1] ).array()\n\t\t\t).sum() ;\n\t\t\tN += p.array().sum() ;\n\t\t\tfor( std::size_t v = 0; v < frequencies.size(); ++v ) {\n\t\t\t\tConstBlock d = dosages[v].segment( range.begin(), range.size() ) ;\n\t\t\t\tConstBlock p = ploidy[v].segment( range.begin(), range.size() ) ;\n\t\t\t\tvariances[v] += ( d - p * frequencies[v] ).array().square().sum() ;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Add regularising information consisting of a total of\n\t\t// prior_weight haploid samples, split evenly between\n\t\t// the four possible genotype combinations\n\t\tresult += (0 - frequencies[0]) * (0 - frequencies[1] ) * (prior_weight / 4) ;\n\t\tresult += (0 - frequencies[0]) * (1 - frequencies[1] ) * (prior_weight / 4) ;\n\t\tresult += (1 - frequencies[0]) * (0 - frequencies[1] ) * (prior_weight / 4) ;\n\t\tresult += (1 - frequencies[0]) * (1 - frequencies[1] ) * (prior_weight / 4) ;\n\t\tfor( std::size_t v = 0; v < frequencies.size(); ++v ) {\n\t\t\tvariances[v] += ( 0 - frequencies[v] ) * ( 0 - frequencies[v] ) * (prior_weight / 2.0) ;\n\t\t\tvariances[v] += ( 1 - frequencies[v] ) * ( 1 - frequencies[v] ) * (prior_weight / 2.0) ;\n\t\t}\n\t\tN += prior_weight ;\n\n\t\t*covariance = result / N ;\n\t\t*correlation = result / (std::sqrt( variances[0] ) * std::sqrt( variances[1] )) ;\n\t\t*number_of_samples = N ;\n\t}\n\t\n\tEigen::MatrixXd tabulate(\n\t\tstd::vector< Eigen::VectorXd > const& dosages,\n\t\tstd::vector< Eigen::VectorXd > const& ploidy,\n\t\tstd::vector< metro::SampleRange > const& included_samples\n\t) const {\n\t\ttypedef Eigen::VectorBlock< Eigen::VectorXd const > ConstBlock ;\n\t\ttypedef Eigen::VectorBlock< Eigen::VectorXi const > ConstIntegerBlock ;\n\n\t\tint maxPloidy0 = 0 ;\n\t\tint maxPloidy1 = 0 ;\n\t\tfor( std::size_t i = 0; i < included_samples.size(); ++i ) {\n\t\t\tmetro::SampleRange const& range = included_samples[i] ;\n\t\t\tmaxPloidy0 = std::max( maxPloidy0, int( ploidy[0].segment( range.begin(), range.size() ).array().maxCoeff()) ) ;\n\t\t\tmaxPloidy1 = std::max( maxPloidy1, int( ploidy[1].segment( range.begin(), range.size() ).array().maxCoeff()) ) ;\n\t\t}\n\t\tEigen::MatrixXd result = Eigen::MatrixXd::Zero( maxPloidy0 + 1, maxPloidy1 + 1 ) ;\n\t\tfor( std::size_t i = 0; i < included_samples.size(); ++i ) {\n\t\t\tmetro::SampleRange const& range = included_samples[i] ;\n\t\t\tfor( int j = range.begin(); j < range.end(); ++j ) {\n\t\t\t\t++result( dosages[0][j], dosages[1][j] ) ;\n\t\t\t}\n\t\t}\n\t\treturn result ;\n\t}\n\n\tstruct DosageSetter: public genfile::VariantDataReader::PerSampleSetter {\n\t\ttypedef std::vector< metro::SampleRange > SampleRanges ;\n\n\t\tDosageSetter(\n\t\t\tEigen::VectorXd* dosages,\n\t\t\tEigen::VectorXd* ploidy,\n\t\t\tSampleRanges* nonmissing_samples,\n\t\t\tbool treat_as_haploid = false\n\t\t):\n\t\t\tm_dosages( dosages ),\n\t\t\tm_ploidy( ploidy ),\n\t\t\tm_total_prob(0.0),\n\t\t\tm_treat_as_haploid( treat_as_haploid ),\n\t\t\tm_number_of_entries( 0 ),\n\t\t\tm_nonmissing_samples( nonmissing_samples ),\n\t\t\tm_sample_i(0)\n\t\t{\n\t\t\tassert( dosages != 0 && nonmissing_samples != 0 && ploidy != 0 ) ;\n\t\t}\n\n\t\tvoid initialise( std::size_t nSamples, std::size_t nAlleles ) {\n\t\t\tif( nAlleles != 2 ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"ProbSetter::initialise()\",\n\t\t\t\t\t\"nAlleles=\" + genfile::string_utils::to_string( nAlleles ),\n\t\t\t\t\t\"I only support biallelic variants\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tm_dosages->resize( nSamples ) ;\n\t\t\tm_dosages->setZero() ;\n\t\t\tm_ploidy->resize( nSamples ) ;\n\t\t\tm_ploidy->setZero() ;\n\t\t\t\n\t\t\tm_nonmissing_samples->clear() ;\n\t\t\tm_last_nonmissing_sample_i = 0 ;\n\t\t}\n\n\t\tbool set_sample( std::size_t n ) {\n\t\t\tm_sample_i = n ;\n\t\t\treturn true ;\n\t\t}\n\n\t\tvoid set_number_of_entries(\n\t\t\tuint32_t ploidy, std::size_t n,\n\t\t\tgenfile::OrderType const order_type,\n\t\t\tgenfile::ValueType const value_type\n\t\t) {\n\t\t\tif( value_type != genfile::eProbability ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::set_number_of_entries()\",\n\t\t\t\t\t\"value_type=\" + genfile::string_utils::to_string( value_type ),\n\t\t\t\t\t\"Expected genotype call probabilities (e.g. GP field).\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tif( order_type != genfile::ePerUnorderedGenotype ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::set_number_of_entries()\",\n\t\t\t\t\t\"order_type=\" + genfile::string_utils::to_string( order_type ),\n\t\t\t\t\t\"Expected genotype call probabilities (e.g. GP field).\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tif( m_treat_as_haploid ) {\n\t\t\t\t(*m_ploidy)(m_sample_i) = 1 ;\n\t\t\t} else {\n\t\t\t\t(*m_ploidy)(m_sample_i) = ploidy ;\n\t\t\t}\n\t\t\tm_number_of_entries = n ;\n\t\t\tm_total_prob = 0.0 ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, genfile::MissingValue const value ) {\n\t\t\t// This sample has missing data, end our current sample range here.\n\t\t\tif( m_sample_i > m_last_nonmissing_sample_i ) {\n\t\t\t\tm_nonmissing_samples->push_back(\n\t\t\t\t\tmetro::SampleRange( m_last_nonmissing_sample_i, m_sample_i )\n\t\t\t\t) ;\n#if DEBUG > 2\n\t\t\t\tstd::cerr << \"DosageSetter::set_value(): added sample range: \" << m_nonmissing_samples->back() << \".\\n\" ;\n#endif\n\t\t\t}\n\t\t\t// Skip this sample for next range.\n\t\t\tm_last_nonmissing_sample_i = m_sample_i + 1 ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, Integer const value ) {\n\t\t\tassert(0) ; // expected a probabilty\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, double const value ) {\n\t\t\tif( !sample_recorded_missing() ) {\n\t\t\t\tbool const last_entry = ((entry_i+1) == m_number_of_entries ) ;\n\t\t\t\t// we assume two alleles, so entry_i is also the count of the B allele \n\t\t\t\t// in the genotype.\n\t\t\t\tif( m_treat_as_haploid ) {\n\t\t\t\t\t// only homozygous genotypes are counted, others are assumed missing\n\t\t\t\t\t// entry_i == 0 contributes 0 dosage anyway so just count the last entry\n\t\t\t\t\t//\n\t\t\t\t\t// Sample considered missing if has nonzero probability on non-homozygous genotype\n\t\t\t\t\t// (caught here), or if it has total 0 probability on homozygous genotypes (handled below).\n\t\t\t\t\tif( entry_i == 0 || last_entry ) {\n\t\t\t\t\t\t(*m_dosages)(m_sample_i) += ( last_entry ? value : 0.0 );\n\t\t\t\t\t\tm_total_prob += value ;\n\t\t\t\t\t} else if( value != 0 ) {\n\t\t\t\t\t\trecord_missing_sample() ;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t(*m_dosages)(m_sample_i) += value * entry_i ;\n\t\t\t\t\tm_total_prob += value ;\n\t\t\t\t}\n\n\t\t\t\t// handle missing data encoded as zeroes\n\t\t\t\tif( last_entry && m_total_prob == 0.0 ) {\n\t\t\t\t\trecord_missing_sample() ;\n\t\t\t\t}\n\t\t\t\t\n#if DEBUG > 2\n\t\t\t\tstd::cerr << \"DosageSetter::set_value(): added value \" << (value * entry_i) << \" to entry \" << entry_i << \" for sample \" << m_sample_i << \".\\n\" ;\n#endif\n\t\t\t}\n\t\t}\n\n\t\tvoid finalise() {\n\t\t\t// Add the final sample range if needed.\n\t\t\tif( (m_sample_i+1) > m_last_nonmissing_sample_i ) {\n\t\t\t\tm_nonmissing_samples->push_back(\n\t\t\t\t\tmetro::SampleRange( m_last_nonmissing_sample_i, m_sample_i+1 )\n\t\t\t\t) ;\n#if DEBUG > 2\n\t\t\t\tstd::cerr << \"DosageSetter::finalise(): added sample range: \" << m_nonmissing_samples->back() << \".\\n\" ;\n#endif\n\t\t\t}\n#if DEBUG > 2\n\t\t\t\tstd::cerr << \"DosageSetter::finalise(): complete.\\n\" ;\n#endif\n\t\t}\n\t\t\n\tprivate:\n\t\tEigen::VectorXd* m_dosages ;\n\t\tEigen::VectorXd* m_ploidy ;\n\t\tdouble m_total_prob ;\n\t\tbool m_treat_as_haploid ;\n\n\t\tstd::size_t m_number_of_entries ;\n\t\tSampleRanges* m_nonmissing_samples ;\n\t\tstd::size_t m_last_nonmissing_sample_i ;\n\t\tstd::size_t m_sample_i ;\n\tprivate:\n\t\t\n\t\tbool sample_recorded_missing() const {\n\t\t\treturn m_sample_i < m_last_nonmissing_sample_i ;\n\t\t}\n\n\t\tvoid record_missing_sample() {\n\t\t\t// missing\n\t\t\tm_nonmissing_samples->push_back(\n\t\t\t\tmetro::SampleRange( m_last_nonmissing_sample_i, m_sample_i )\n\t\t\t) ;\n\t\t\t// Skip this sample for next range.\n\t\t\tm_last_nonmissing_sample_i = m_sample_i + 1 ;\n\t\t}\n\t} ;\n} ;\n\nint main( int argc, char** argv ) {\n    try {\n\t\tLDbirdApplication app( argc, argv ) ;\n    }\n\tcatch( appcontext::HaltProgramWithReturnCode const& e ) {\n\t\treturn e.return_code() ;\n\t}\n\treturn 0 ;\n}\n\n", "meta": {"hexsha": "bdf7210fb2640b9f73fe02515b2e637e61966a46", "size": 42591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/ldbird.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": "apps/ldbird.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": "apps/ldbird.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": 35.1701073493, "max_line_length": 158, "alphanum_fraction": 0.6719494729, "num_tokens": 12293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18145183055221467}}
{"text": "\ufeff#include \"myObject.h\"\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#define GLM_FORCE_RADIANS\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp> \n#include <glm/gtc/type_ptr.hpp>\n#include <glm/gtx/intersect.hpp>\n#include \"helperFunctions.h\"\n#include \"errors.h\"\n\n#include <boost/filesystem.hpp>\nnamespace fs = boost::filesystem;\nusing namespace std;\n\nmyObject::myObject()\n{\n    model_matrix = glm::mat4(1.0f);\n    vao = nullptr;\n    name = \"default\";\n}\n\nmyObject::~myObject()\n{\n    clear();\n}\n\nvoid myObject::clear()\n{\n    if (vao) delete vao;\n\n    for (std::unordered_multimap<std::string, mySubObject*>::iterator it = objects.begin(); it != objects.end(); ++it)\n        delete it->second;\n    objects.clear();\n\n    vector<glm::vec3> empty; vertices.swap(empty);\n    normals.swap(empty);\n    vector<glm::ivec3> empty2; indices.swap(empty2);\n}\n\nstd::vector<myObject*> myObject::createFromThis(size_t num, bool createVAO) const\n{\n    std::vector<myObject*> res(num, nullptr);\n    for (size_t i = 0; i < num; ++i)\n    {\n        res[i] = new myObject();\n        res[i]->vertices = this->vertices;\n        res[i]->indices = this->indices;\n        res[i]->normals = this->normals;\n        res[i]->texturecoordinates = this->texturecoordinates;\n        res[i]->tangents = this->tangents;\n        res[i]->model_matrix = this->model_matrix;\n        res[i]->name = this->name;\n\n        for (std::unordered_multimap<std::string, mySubObject*>::const_iterator it = this->objects.begin(); it != this->objects.end(); ++it)\n        {\n            auto name = it->first;\n            auto obj = it->second;\n            mySubObject* o = new mySubObject(obj->material, obj->start, obj->end, obj->name);\n\n            o->textures = obj->textures; // I guess textures may be the same object?\n            res[i]->objects.emplace(name, o);\n        }\n\n        if (createVAO)\n            res[i]->createmyVAO();\n    }\n    return res;\n}\n\nvoid myObject::readMaterials(std::string mtlfilename, unordered_map<string, myMaterial*>& materials, unordered_map<string, myTexture*>& textures)\n{\n    ifstream mtlfin(mtlfilename);\n\n    if (!mtlfin.is_open())\n    {\n        cout << \"Error! Unable to open mtl file: \" << mtlfilename << \"\\n\";\n        return;\n    }\n\n    string v;\n    myMaterial* curr_mat = nullptr;\n\n    while (mtlfin >> v)\n    {\n        if (v == \"newmtl\")\n        {\n            curr_mat = new myMaterial();\n            mtlfin >> curr_mat->mat_name;\n\n            materials.emplace(curr_mat->mat_name, curr_mat);\n        }\n        else if (v == \"Ns\") mtlfin >> curr_mat->specular_coefficient;\n        else if (v == \"Ka\") mtlfin >> curr_mat->ka.r >> curr_mat->ka.g >> curr_mat->ka.b;\n        else if (v == \"Kd\") mtlfin >> curr_mat->kd.r >> curr_mat->kd.g >> curr_mat->kd.b;\n        else if (v == \"Ks\") mtlfin >> curr_mat->ks.r >> curr_mat->ks.g >> curr_mat->ks.b;\n        else if (v == \"map_Kd\")\n        {\n            string t;\n            mtlfin >> t;\n            fs::path texfilename = fs::path(mtlfilename).remove_filename() / t;\n            if (!fs::exists(texfilename))\n                texfilename = fs::path(t); // try raw absolute path\n\n            textures.emplace(curr_mat->mat_name, new myTexture(texfilename.string()));\n        }\n    }\n\n\n\n    mtlfin.close();\n}\n\nbool myObject::readObjects(std::string filename, bool individualvertices_per_face, bool tonormalize)\n{\n    clear();\n\n    string s, t;\n    string mtlfilename;\n\n    fs::path filenameP(filename);\n    if (!fs::exists(filenameP) || !fs::is_regular_file(filenameP))\n        return false;\n\n    name = filenameP.filename().replace_extension().string();\n\n    ifstream fin(filename);\n    if (!fin.is_open()) return false;\n\n    size_t curr_start = 0; size_t curr_end;\n    string curr_name = \"noname\";\n    myMaterial* curr_mat = nullptr;\n    myTexture* curr_texture = nullptr;\n\n    unordered_map<string, myMaterial*> materials;\n    unordered_map<string, myTexture*> textures;\n\n    vector<glm::vec3> tmp_vertices;\n    vector<glm::vec2> tmp_texturecoordinates;\n    vector<glm::vec3> tmp_normals;\n\n    while (getline(fin, s))\n    {\n        stringstream myline(s);\n        myline >> t;\n        if (t == \"g\" || t == \"o\")\n        {\n            curr_end = indices.size();\n            mySubObject* o = new mySubObject(curr_mat, curr_start, curr_end, curr_name);\n            o->setTexture(curr_texture, mySubObject::COLORMAP);\n            objects.emplace(curr_name, o);\n\n            curr_start = curr_end;\n            myline >> curr_name;\n        }\n        else if (t == \"v\")\n        {\n            float x, y, z;\n            myline >> x >> y >> z;\n            tmp_vertices.push_back(glm::vec3(x, y, z));\n        }\n        else if (t == \"vn\")\n        {\n            float x, y, z;\n            myline >> x >> y >> z;\n            tmp_normals.push_back(glm::vec3(x, y, z));\n        }\n        else if (t == \"vt\")\n        {\n            float _s, _t;\n            myline >> _s >> _t;\n            tmp_texturecoordinates.push_back(glm::vec2(_s, 1.0f - _t));\n        }\n        else if (t == \"mtllib\")\n        {\n            myline >> mtlfilename;\n\n            fs::path mtlpath = filenameP.remove_filename() / mtlfilename;\n            readMaterials(mtlpath.string(), materials, textures);\n        }\n        else if (t == \"usemtl\")\n        {\n            curr_end = indices.size();\n            mySubObject* o = new mySubObject(curr_mat, curr_start, curr_end, curr_name);\n            o->setTexture(curr_texture, mySubObject::COLORMAP);\n            objects.emplace(curr_name, o);\n\n            curr_start = curr_end;\n\n            string u;\n            myline >> u;\n            //curr_name = u;\n\n            if (materials.count(u) != 0)\n                curr_mat = materials[u];\n            else curr_mat = nullptr;\n\n            if (textures.count(u) != 0)\n                curr_texture = textures[u];\n            else curr_texture = nullptr;\n        }\n        else if (t == \"s\") {}\n        else if (t == \"f\")\n        {\n            unsigned int vertex_index1, vertex_index2, vertex_index3;\n            unsigned int texture_index1, texture_index2, texture_index3;\n            unsigned int normal_index1, normal_index2, normal_index3;\n\n            myline >> t;\n            parseObjFace(t, vertex_index1, texture_index1, normal_index1);\n\n            myline >> t;\n            parseObjFace(t, vertex_index2, texture_index2, normal_index2);\n\n            while (myline >> t)\n            {\n                parseObjFace(t, vertex_index3, texture_index3, normal_index3);\n\n                if (individualvertices_per_face)\n                {\n                    vertices.push_back(tmp_vertices[vertex_index1]);\n                    if (texture_index1 < tmp_texturecoordinates.size())\n                        texturecoordinates.push_back(tmp_texturecoordinates[texture_index1]);\n                    else texturecoordinates.push_back(glm::vec2(0, 0));\n                    if (normal_index1 < tmp_normals.size())\n                        normals.push_back(tmp_normals[normal_index1]);\n                    else normals.push_back(glm::vec3(0, 0, 0));\n\n                    vertices.push_back(tmp_vertices[vertex_index2]);\n                    if (texture_index2 < tmp_texturecoordinates.size())\n                        texturecoordinates.push_back(tmp_texturecoordinates[texture_index2]);\n                    else texturecoordinates.push_back(glm::vec2(0, 0));\n                    if (normal_index2 < tmp_normals.size())\n                        normals.push_back(tmp_normals[normal_index2]);\n                    else normals.push_back(glm::vec3(0, 0, 0));\n\n                    vertices.push_back(tmp_vertices[vertex_index3]);\n                    if (texture_index3 < tmp_texturecoordinates.size())\n                        texturecoordinates.push_back(tmp_texturecoordinates[texture_index3]);\n                    else texturecoordinates.push_back(glm::vec2(0, 0));\n                    if (normal_index3 < tmp_normals.size())\n                        normals.push_back(tmp_normals[normal_index3]);\n                    else normals.push_back(glm::vec3(0, 0, 0));\n\n                    indices.push_back(glm::ivec3(vertices.size() - 3, vertices.size() - 2, vertices.size() - 1));\n                }\n                else\n                    indices.push_back(glm::ivec3(vertex_index1, vertex_index2, vertex_index3));\n\n                vertex_index2 = vertex_index3;\n                texture_index2 = texture_index3;\n                normal_index2 = normal_index3;\n            }\n        }\n        s.clear();\n        t.clear();\n    }\n\n    curr_end = indices.size();\n    mySubObject* o = new mySubObject(curr_mat, curr_start, curr_end, curr_name);\n    o->setTexture(curr_texture, mySubObject::COLORMAP);\n    objects.emplace(curr_name, o);\n\n    if (!individualvertices_per_face)\n    {\n        vertices = tmp_vertices;\n        computeNormals();\n    }\n\n    if (tonormalize) normalize();\n\n    return true;\n}\n\nvoid myObject::normalize()\n{\n    unsigned int tmpxmin = 0, tmpymin = 0, tmpzmin = 0, tmpxmax = 0, tmpymax = 0, tmpzmax = 0;\n\n    for (unsigned i = 0; i < vertices.size(); i++) {\n        if (vertices[i].x < vertices[tmpxmin].x) tmpxmin = i;\n        if (vertices[i].x > vertices[tmpxmax].x) tmpxmax = i;\n\n        if (vertices[i].y < vertices[tmpymin].y) tmpymin = i;\n        if (vertices[i].y > vertices[tmpymax].y) tmpymax = i;\n\n        if (vertices[i].z < vertices[tmpzmin].z) tmpzmin = i;\n        if (vertices[i].z > vertices[tmpzmax].z) tmpzmax = i;\n    }\n\n    float xmin = vertices[tmpxmin].x, xmax = vertices[tmpxmax].x,\n        ymin = vertices[tmpymin].y, ymax = vertices[tmpymax].y,\n        zmin = vertices[tmpzmin].z, zmax = vertices[tmpzmax].z;\n\n    float scale = ((xmax - xmin) <= (ymax - ymin)) ? (xmax - xmin) : (ymax - ymin);\n    scale = (scale >= (zmax - zmin)) ? scale : (zmax - zmin);\n\n    for (unsigned int i = 0; i < vertices.size(); i++) {\n        vertices[i].x -= (xmax + xmin) / 2;\n        vertices[i].y -= (ymax + ymin) / 2;\n        vertices[i].z -= (zmax + zmin) / 2;\n\n        vertices[i].x /= scale;\n        vertices[i].y /= scale;\n        vertices[i].z /= scale;\n    }\n}\n\nvoid myObject::computeNormals()\n{\n    normals.assign(vertices.size(), glm::vec3(0.0f, 0.0f, 0.0f));\n    for (unsigned int i = 0; i < indices.size(); i++)\n    {\n        glm::vec3 face_normal = glm::cross(vertices[indices[i][1]] - vertices[indices[i][0]], vertices[indices[i][2]] - vertices[indices[i][1]]);\n        normals[indices[i][0]] += face_normal;\n        normals[indices[i][1]] += face_normal;\n        normals[indices[i][2]] += face_normal;\n    }\n    for (unsigned int i = 0; i < vertices.size(); i++)  normals[i] = glm::normalize(normals[i]);\n}\n\nvoid myObject::createmyVAO()\n{\n    if (vao != nullptr) delete vao;\n    vao = new myVAO();\n\n    if (vertices.size()) vao->storePositions(vertices, 0);\n    if (normals.size()) vao->storeNormals(normals, 1);\n    if (texturecoordinates.size()) vao->storeTexturecoordinates(texturecoordinates, 2);\n    if (tangents.size()) vao->storeTangents(tangents, 3);\n\n    if (indices.size()) vao->storeIndices(indices);\n}\n\nvoid myObject::displayObjects(myShader* shader, glm::mat4 view_matrix, const std::map<string, bool>& exclude)\n{\n    myassert(vao != nullptr);\n    shader->setUniform(\"mymodel_matrix\", model_matrix);\n    shader->setUniform(\"mynormal_matrix\", glm::transpose(glm::inverse(glm::mat3(view_matrix) * glm::mat3(model_matrix))));\n\n    if (exclude.size() == 0)\n    {\n        for (std::unordered_multimap<string, mySubObject*>::iterator it = objects.begin(), end = objects.end(); it != end; ++it)\n            it->second->displaySubObject(vao, shader);\n    }\n    else\n    {\n        for (std::unordered_multimap<string, mySubObject*>::iterator it = objects.begin(), end = objects.end(); it != end; ++it)\n            if (!exclude.at(it->first))\n                it->second->displaySubObject(vao, shader);\n    }\n\n}\n\nvoid myObject::displayObjects(myShader* shader, glm::mat4 view_matrix, std::string name)\n{\n    if (vao == nullptr)\n    {\n        cout << \"myVAO is empty. Nothing to draw.\\n\";\n        return;\n    }\n    shader->setUniform(\"mymodel_matrix\", model_matrix);\n    shader->setUniform(\"mynormal_matrix\", glm::transpose(glm::inverse(glm::mat3(view_matrix) * glm::mat3(model_matrix))));\n\n    auto st = objects.equal_range(name);\n    for (std::unordered_multimap<std::string, mySubObject*>::iterator it = st.first; it != st.second; ++it)\n        it->second->displaySubObject(vao, shader);\n}\n\nvoid myObject::displayNormals(myShader* shader)\n{\n}\n\nglm::vec3 myObject::closestVertex(glm::vec3 ray, glm::vec3 starting_point)\n{\n    float min = std::numeric_limits<float>::max();\n    unsigned int min_index = 0;\n\n    ray = glm::normalize(ray);\n    for (unsigned int i = 0; i < vertices.size(); i++)\n    {\n        float dotp = glm::dot(ray, vertices[i] - starting_point);\n        if (dotp < 0) continue;\n\n        float oq = glm::distance(starting_point, vertices[i]);\n        float d = oq * oq - dotp * dotp;\n        if (d < min)\n        {\n            min = d;\n            min_index = i;\n        }\n    }\n    return vertices[min_index];\n}\n\nglm::vec3 myObject::objectAverage() const\n{\n    glm::vec3 avg(0., 0., 0.);\n    for (unsigned int i = 0; i < vertices.size(); i++)\n    {\n        avg += vertices[i];\n    }\n    return (avg / ((float)(vertices.size())));\n}\n\n\nvoid myObject::locate(float x, float y, float z)\n{\n    model_matrix = glm::translate(model_matrix, glm::vec3(x, y, z));\n    //model_matrix[0][3] = x;\n    //model_matrix[1][3] = y;\n    //model_matrix[2][3] = z;\n}\n\nvoid myObject::translate(float x, float y, float z)\n{\n    glm::mat4 tmp = glm::translate(glm::mat4(1.0f), glm::vec3(x, y, z));\n    model_matrix = tmp * model_matrix;\n}\n\nvoid myObject::scale(float x, float y, float z)\n{\n    glm::mat4 tmp = glm::scale(glm::mat4(1.0f), glm::vec3(x, y, z));\n    model_matrix = tmp * model_matrix;\n}\n\nvoid myObject::rotate(float axis_x, float axis_y, float axis_z, float angle)\n{\n    if (axis_x == 0.0f && axis_y == 0.0f && axis_z == 0.0f)\n    {\n        std::cout << \"Error: rotation vector almost zero\" << std::endl;\n        return;\n    }\n\n    glm::mat4 tmp = glm::rotate(glm::mat4(1.0f), static_cast<float>(angle), glm::vec3(axis_x, axis_y, axis_z));\n    model_matrix = tmp * model_matrix;\n}\n\nvoid myObject::locate(glm::vec3 t)\n{\n    locate(t.x, t.y, t.z);\n}\n\nvoid myObject::translate(glm::vec3 v)\n{\n    translate(v.x, v.y, v.z);\n}\n\nvoid myObject::scale(glm::vec3 v)\n{\n    scale(v.x, v.y, v.z);\n}\n\nvoid myObject::rotate(glm::vec3 v, float angle)\n{\n    rotate(v.x, v.y, v.z, angle);\n}\n\nglm::vec3 myObject::getPos() const\n{\n    return glm::vec3(model_matrix[3]);\n}\n\nvoid myObject::computeTexturecoordinates_plane()\n{\n    texturecoordinates.assign(vertices.size(), glm::vec2(0.0f, 0.0f));\n    for (unsigned int i = 0; i < vertices.size(); i++)\n    {\n        texturecoordinates[i].s = vertices[i].x / 10.0f;\n        texturecoordinates[i].t = vertices[i].y / 10.0f;\n    }\n}\n\nvoid myObject::computeTexturecoordinates_cylinder()\n{\n    texturecoordinates.assign(vertices.size(), glm::vec2(0.0f, 0.0f));\n    for (unsigned int i = 0; i < vertices.size(); i++)\n    {\n        float x = vertices[i].x;\n        float y = vertices[i].y;\n        float z = vertices[i].z;\n\n        texturecoordinates[i].t = y - 0.5f;\n        texturecoordinates[i].s = static_cast<float>((z >= 0.0f) ? atan2(z, x) / (M_PI) : (-atan2(z, x)) / (M_PI));\n    }\n}\n\nvoid myObject::computeTexturecoordinates_sphere()\n{\n    texturecoordinates.assign(vertices.size(), glm::vec2(0.0f, 0.0f));\n    for (unsigned int i = 0; i < vertices.size(); i++)\n    {\n        glm::vec3 v = glm::normalize(vertices[i]);\n\n        texturecoordinates[i].t = static_cast<float>(-(atan2(2 * v.y, 2 * v.x) + M_PI) / (2 * M_PI));\n        texturecoordinates[i].s = static_cast<float>(acos(v.z) / M_PI);\n    }\n}\n\nvoid myObject::computeTangents()\n{\n    tangents.assign(vertices.size(), glm::vec3(0.0f, 0.0f, 0.0f));\n    for (unsigned int i = 0; i < indices.size(); i++)\n    {\n        glm::vec2 t10 = texturecoordinates[indices[i][1]] - texturecoordinates[indices[i][0]];\n        glm::vec2 t20 = texturecoordinates[indices[i][2]] - texturecoordinates[indices[i][0]];\n        float f = t10.s * t20.t - t10.t * t20.s;\n        if (f == 0) continue;\n        f = 1.0f / f;\n        glm::vec3 v10 = vertices[indices[i][1]] - vertices[indices[i][0]];\n        glm::vec3 v20 = vertices[indices[i][2]] - vertices[indices[i][0]];\n        glm::vec3 t(f * (t20.t * v10.x - t10.t * v20.x), f * (t20.t * v10.y - t10.t * v20.y),\n            f * (t20.t * v10.z - t10.t * v20.z));\n\n        tangents[indices[i][0]] += t;\n        tangents[indices[i][1]] += t;\n        tangents[indices[i][2]] += t;\n    }\n    for (unsigned int i = 0; i < vertices.size(); i++)  tangents[i] = glm::normalize(tangents[i]);\n}\n\n\nvoid myObject::setTexture(myTexture* tex, mySubObject::TEXTURE_TYPE type)\n{\n    for (std::unordered_multimap<std::string, mySubObject*>::iterator it = objects.begin(); it != objects.end(); ++it)\n        it->second->setTexture(tex, type);\n}\n\n\nfloat myObject::closestTriangle(glm::vec3 ray, glm::vec3 origin, size_t& picked_triangle)\n{\n    mySubObject* tmp;\n    return closestTriangle(ray, origin, picked_triangle, tmp);\n}\n\nfloat myObject::closestTriangle(glm::vec3 ray, glm::vec3 origin, size_t& picked_triangle, mySubObject*& picked_object)\n{\n    float min_t = std::numeric_limits<float>::max();\n    picked_triangle = 0;\n    picked_object = nullptr;\n\n    for (std::unordered_multimap<std::string, mySubObject*>::iterator it = objects.begin(); it != objects.end(); ++it)\n    {\n        mySubObject* obj = it->second;\n        for (size_t i = obj->start; i < obj->end; i++)\n        {\n            glm::vec2 intersection_point;\n            vector<glm::vec3> verts(3);\n            for (unsigned int j : {0, 1, 2})\n            {\n                glm::vec4 t = model_matrix * glm::vec4(vertices[indices[i][j]], 1.0f);\n                verts[j] = glm::vec3(t.x / t.w, t.y / t.w, t.z / t.w);\n            }\n            float dst;\n            bool intersect = glm::intersectRayTriangle(origin, ray, verts[0], verts[1], verts[2], intersection_point, dst);\n            if (intersect)\n            {\n                float t = dst;//intersection_point.z;\n                if (t >= 0 && t < min_t)\n                {\n                    min_t = t;\n                    picked_triangle = i;\n                    picked_object = obj;\n                }\n            }\n        }\n    }\n\n    if (picked_triangle == 0) return -1;\n    else return min_t;\n}\n", "meta": {"hexsha": "4fb73f449c69290fe1fb1a23e58eb3a11019b758", "size": 18518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "myproj/myObject.cpp", "max_stars_repo_name": "crownedone/PipeDreamMidiPlayer", "max_stars_repo_head_hexsha": "83b7d7ae3d54eb87914d9a42aaf9f27c0627242c", "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": "myproj/myObject.cpp", "max_issues_repo_name": "crownedone/PipeDreamMidiPlayer", "max_issues_repo_head_hexsha": "83b7d7ae3d54eb87914d9a42aaf9f27c0627242c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "myproj/myObject.cpp", "max_forks_repo_name": "crownedone/PipeDreamMidiPlayer", "max_forks_repo_head_hexsha": "83b7d7ae3d54eb87914d9a42aaf9f27c0627242c", "max_forks_repo_licenses": ["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.1493055556, "max_line_length": 145, "alphanum_fraction": 0.5753861108, "num_tokens": 4957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1814518290425848}}
{"text": "// ROS includes.\n#include <ros/ros.h>\n#include <ros/time.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <image_transport/image_transport.h>\n#include <image_transport/subscriber_filter.h>\n#include <sensor_msgs/CameraInfo.h>\n#include <cv_bridge/cv_bridge.h>\n\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <math.h>\n\n#include <boost/thread.hpp>\n\n#include \"fovis.hpp\"\n\n#include \"rwth_perception_people_msgs/VisualOdometry.h\"\n\n\n\nusing namespace std;\nusing namespace sensor_msgs;\nusing namespace message_filters;\nusing namespace rwth_perception_people_msgs;\n\nros::Publisher pub_message;\nfovis::VisualOdometry* odom = NULL;\nfovis::CameraIntrinsicsParameters cam_params;\n\ncv::Mat img_depth_;\ncv_bridge::CvImagePtr cv_depth_ptr;\t// cv_bridge for depth image\n\nbool recover = false;\nbool first = true;\n\nvoid callback(const ImageConstPtr &image, const ImageConstPtr &depth, const CameraInfoConstPtr &info)\n{\n    // Initialising odomometry at first callback call or for recovery\n    if(odom == NULL)\n    {\n        // Only needs to be done once at startup and not for recovery\n        if(first) {\n            first = false;\n            memset(&cam_params, 0, sizeof(fovis::CameraIntrinsicsParameters));\n            cam_params.width = info->width;\n            cam_params.height = info->height;\n            cam_params.fx = info->K[0];\n            cam_params.fy = info->K[4];\n            cam_params.cx = info->K[2];\n            cam_params.cy = info->K[5];\n        }\n\n        fovis::Rectification* fovis_rect;\n\n        fovis_rect = new fovis::Rectification(cam_params);\n        fovis::VisualOdometryOptions options = fovis::VisualOdometry::getDefaultOptions();\n        odom = new fovis::VisualOdometry(fovis_rect, options);\n    }\n\n    cv_depth_ptr = cv_bridge::toCvCopy(depth);\n    img_depth_ = cv_depth_ptr->image;\n\n    ros::WallTime start_time = ros::WallTime::now();\n    fovis::DepthImage* fv_dp = new fovis::DepthImage(cam_params,info->width,info->height);\n    fv_dp->setDepthImage((float*)(img_depth_.data));\n\n    odom->processFrame(&image->data[0], fv_dp);\n\n    Eigen::Isometry3d cam_to_local = odom->getPose();\n    Eigen::Matrix4d m1 = cam_to_local.matrix().inverse();\n\n    VisualOdometry fovis_info_msg;\n    fovis_info_msg.header = image->header;\n\n    fovis_info_msg.change_reference_frame = odom->getChangeReferenceFrames();\n    fovis_info_msg.fast_threshold = odom->getFastThreshold();\n    const fovis::OdometryFrame* frame = odom->getTargetFrame();\n    fovis_info_msg.num_total_detected_keypoints = frame->getNumDetectedKeypoints();\n    fovis_info_msg.num_total_keypoints = frame->getNumKeypoints();\n    fovis_info_msg.num_detected_keypoints.resize(frame->getNumLevels());\n    fovis_info_msg.num_keypoints.resize(frame->getNumLevels());\n    for (int i = 0; i < frame->getNumLevels(); ++i)\n    {\n        fovis_info_msg.num_detected_keypoints[i] = frame->getLevel(i)->getNumDetectedKeypoints();\n        fovis_info_msg.num_keypoints[i] = frame->getLevel(i)->getNumKeypoints();\n    }\n    const fovis::MotionEstimator* estimator = odom->getMotionEstimator();\n    fovis_info_msg.motion_estimate_status_code = estimator->getMotionEstimateStatus();\n    fovis_info_msg.motion_estimate_status = fovis::MotionEstimateStatusCodeStrings[fovis_info_msg.motion_estimate_status_code];\n    fovis_info_msg.num_matches = estimator->getNumMatches();\n    fovis_info_msg.num_inliers = estimator->getNumInliers();\n    fovis_info_msg.num_reprojection_failures = estimator->getNumReprojectionFailures();\n    fovis_info_msg.motion_estimate_valid = estimator->isMotionEstimateValid();\n    ros::WallDuration time_elapsed = ros::WallTime::now() - start_time;\n    fovis_info_msg.runtime = time_elapsed.toSec();\n\n\n    fovis_info_msg.transformation_matrix.resize(4*4);\n    for(int i = 0; i < 4*4; i++)\n    {\n        fovis_info_msg.transformation_matrix[i] = m1.data()[i];\n        if(isnan(m1.data()[i])) { // Detected nan values and trigger recovery\n            recover = true;\n        }\n    }\n\n    pub_message.publish(fovis_info_msg);\n    delete fv_dp;\n\n    // delete odometry and reset at next callback call.\n    if(recover) {\n        ROS_WARN(\"Detected 'nan' values in motion matrix. Will try to auto recover by resetting visual odometry.\");\n        recover = false;\n        delete odom;\n        odom = NULL;\n    }\n}\n\n// Connection callback that unsubscribes from the tracker if no one is subscribed.\nvoid connectCallback(message_filters::Subscriber<CameraInfo> &sub_cam,\n                     image_transport::SubscriberFilter &sub_mon,\n                     image_transport::SubscriberFilter &sub_dep,\n                     image_transport::ImageTransport &it){\n    if(!pub_message.getNumSubscribers()) {\n        ROS_DEBUG(\"Visual Odometry: No subscribers. Unsubscribing.\");\n        sub_cam.unsubscribe();\n        sub_mon.unsubscribe();\n        sub_dep.unsubscribe();\n    } else {\n        ROS_DEBUG(\"Visual Odometry: New subscribers. Subscribing.\");\n        sub_cam.subscribe();\n        sub_mon.subscribe(it,sub_mon.getTopic().c_str(),1);\n        sub_dep.subscribe(it,sub_dep.getTopic().c_str(),1);\n    }\n}\n\nint main(int argc, char **argv)\n{\n    // Set up ROS.\n    ros::init(argc, argv, \"visual_odometry\");\n    ros::NodeHandle n;\n\n    // Declare variables that can be modified by launch file or command line.\n    int queue_size;\n    string cam_ns;\n    string pub_topic;\n\n    // Initialize node parameters from launch file or command line.\n    // Use a private node handle so that multiple instances of the node can be run simultaneously\n    // while using different parameters.\n    ros::NodeHandle private_node_handle_(\"~\");\n    private_node_handle_.param(\"queue_size\", queue_size, int(5));\n    private_node_handle_.param(\"camera_namespace\", cam_ns, string(\"/head_xtion\"));\n\n    string topic_image_mono = cam_ns + \"/rgb/image_mono\";\n    string topic_depth_image = cam_ns + \"/depth/image\";\n    string topic_camera_info = cam_ns + \"/rgb/camera_info\";\n\n    ROS_DEBUG(\"visual_odometry: Queue size for synchronisation is set to: %i\", queue_size);\n\n    // Image transport handle\n    image_transport::ImageTransport it(private_node_handle_);\n\n    // Create a subscriber.\n    // Set queue size to 1 because generating a queue here will only pile up images and delay the output by the amount of queued images\n    image_transport::SubscriberFilter subscriber_mono;\n    subscriber_mono.subscribe(it, topic_image_mono.c_str(), 1); subscriber_mono.unsubscribe();\n    image_transport::SubscriberFilter subscriber_depth;\n    subscriber_depth.subscribe(it, topic_depth_image.c_str(), 1); subscriber_depth.unsubscribe();\n    Subscriber<CameraInfo> subscriber_camera_info(n, topic_camera_info.c_str(), 1); subscriber_camera_info.unsubscribe();\n\n    ros::SubscriberStatusCallback con_cb = boost::bind(&connectCallback,\n                                                       boost::ref(subscriber_camera_info),\n                                                       boost::ref(subscriber_mono),\n                                                       boost::ref(subscriber_depth),\n                                                       boost::ref(it));\n\n    //The real queue size for synchronisation is set here.\n    sync_policies::ApproximateTime<Image, Image, CameraInfo> MySyncPolicy(queue_size);\n    MySyncPolicy.setAgePenalty(1000); //set high age penalty to publish older data faster even if it might not be correctly synchronized.\n\n    const sync_policies::ApproximateTime<Image, Image, CameraInfo> MyConstSyncPolicy = MySyncPolicy;\n\n    Synchronizer< sync_policies::ApproximateTime<Image, Image, CameraInfo> > sync(MyConstSyncPolicy,\n                                                                                  subscriber_mono, subscriber_depth, subscriber_camera_info);\n\n    sync.registerCallback(boost::bind(&callback, _1, _2, _3));\n    // Create a topic publisher\n    private_node_handle_.param(\"motion_parameters\", pub_topic, string(\"/visual_odometry/motion_matrix\"));\n    pub_message = n.advertise<VisualOdometry>(pub_topic.c_str(), 10, con_cb, con_cb);\n\n    ros::spin();\n\n    return 0;\n}\n\n", "meta": {"hexsha": "f981bd91c0b1824aa986f6b6310d398fda1f655e", "size": 8178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/src/main.cpp", "max_stars_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_stars_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-07T06:24:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T06:24:27.000Z", "max_issues_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/src/main.cpp", "max_issues_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_issues_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/src/main.cpp", "max_forks_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_forks_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_forks_repo_licenses": ["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.6865671642, "max_line_length": 141, "alphanum_fraction": 0.6930789924, "num_tokens": 1845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18145182548206984}}
{"text": "/***************************************************************************************************************************\n* px4_pos_controller.cpp\n*\n* Author: Qyp\n*\n* Update Time: 2019.5.9\n*\n* Introduction:  PX4 Position Controller using cascade PID method or PD+UDE or passivity\n*         1. Subscribe command.msg from upper nodes (e.g. Target_tracking.cpp)\n*         2. Calculate the accel_sp using pos_controller_PID.h(pos_controller_UDE.h pos_controller_passivity.h)\n*         3. Send command to mavros package using command_to_mavros.h (mavros package will send the message to PX4 as Mavlink msg)\n*         4. PX4 firmware will recieve the Mavlink msg by mavlink_receiver.cpp in mavlink module.\n***************************************************************************************************************************/\n#include <ros/ros.h>\n\n#include <command_to_mavros.h>\n#include <px4_command/command.h>\n#include <mavros_msgs/AttitudeTarget.h>\n#include <pos_controller_PID.h>\n#include <pos_controller_UDE.h>\n#include <pos_controller_Passivity.h>\n#include <pos_controller_NE.h>\n\n#include <fstream>\n\n#include <Eigen/Eigen>\n\nusing namespace std;\n\nusing namespace namespace_command_to_mavros;\nusing namespace namespace_PID;\nusing namespace namespace_UDE;\nusing namespace namespace_passivity;\nusing namespace namespace_NE;\n\n//\u6ce8\u610f\uff1a\u4ee3\u7801\u4e2d\uff0c\u53c2\u4e0e\u8fd0\u7b97\u7684\u89d2\u5ea6\u5747\u662f\u4ee5rad\u4e3a\u5355\u4f4d\uff0c\u4f46\u662f\u6d89\u53ca\u5230\u663e\u793a\u65f6\u6216\u8005\u9700\u8981\u624b\u52a8\u8f93\u5165\u65f6\u5747\u4ee5deg\u4e3a\u5355\u4f4d\u3002\n//\u81ea\u5b9a\u4e49\u7684Command\u53d8\u91cf\n//\u76f8\u5e94\u7684\u547d\u4ee4\u5206\u522b\u4e3a \u5f85\u673a,\u8d77\u98de\uff0c\u79fb\u52a8(\u60ef\u6027\u7cfbENU)\uff0c\u79fb\u52a8(\u673a\u4f53\u7cfb)\uff0c\u60ac\u505c\uff0c\u964d\u843d\uff0c\u4e0a\u9501\uff0c\u7d27\u6025\u964d\u843d\nenum Command\n{\n    Idle,\n    Takeoff,\n    Move_ENU,\n    Move_Body,\n    Hold,\n    Land,\n    Disarm,\n    Failsafe_land,\n};\n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u53d8\u91cf\u58f0\u660e<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nEigen::Vector3d pos_sp(0,0,0);\nEigen::Vector3d vel_sp(0,0,0);\nEigen::Vector3d accel_sp(0,0,0);\nEigen::Quaterniond q_sp;\nEigen::Vector3d att_sp(0,0,0);\nfloat thrust_sp;\ndouble yaw_sp = 0;\n\nint flag_att_sp;\n\nfloat Takeoff_height;\nfloat Disarm_height;\n\nEigen::Vector3d Takeoff_position = Eigen::Vector3d(0.0,0.0,0.0);\n\npx4_command::command Command_Now;                      //\u65e0\u4eba\u673a\u5f53\u524d\u6267\u884c\u547d\u4ee4\npx4_command::command Command_Last;                     //\u65e0\u4eba\u673a\u4e0a\u4e00\u6761\u6267\u884c\u547d\u4ee4\n\nEigen::Vector3d pos_drone_mocap;                       //\u65e0\u4eba\u673a\u5f53\u524d\u4f4d\u7f6e (vicon)\nfloat thrust_read;\n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u51fd\u6570\u58f0\u660e<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nfloat get_ros_time(ros::Time begin);\nvoid prinft_command_state();\nvoid rotation_yaw(float yaw_angle, float input[2], float output[2]);\n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u56de\u8c03\u51fd\u6570<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nvoid Command_cb(const px4_command::command::ConstPtr& msg)\n{\n    Command_Now = *msg;\n}\n/*\nvoid setpoint_attitude_cb(const mavros_msgs::AttitudeTarget::ConstPtr& msg)\n{\n    thrust_read = msg->thrust;\n}\nvoid optitrack_cb(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n    //\u4f4d\u7f6e -- optitrack\u7cfb \u5230 ENU\u7cfb\n    int optitrack_frame = 0; //Frame convention 0: Z-up -- 1: Y-up\n    // Read the Drone Position from the Vrpn Package [Frame: Vicon]  (Vicon to ENU frame)\n    Eigen::Vector3d pos_drone_mocap_enu(-msg->pose.position.x,msg->pose.position.z,msg->pose.position.y);\n\n    pos_drone_mocap = pos_drone_mocap_enu;\n}\n*/\n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u4e3b \u51fd \u6570<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"px4_pos_controller\");\n    ros::NodeHandle nh(\"~\");\n\n    // \u3010\u8ba2\u9605\u3011\u6307\u4ee4\n    //  \u672c\u8bdd\u9898\u6765\u81ea\u6839\u636e\u9700\u6c42\u81ea\u5b9a\u4e49\u7684\u4e0a\u5c42\u6a21\u5757\uff0c\u6bd4\u5982track_land.cpp \u6bd4\u5982move.cpp\n    ros::Subscriber Command_sub = nh.subscribe<px4_command::command>(\"/px4/command\", 10, Command_cb);\n\n    //ros::Subscriber Thrust_sub = nh.subscribe<mavros_msgs::AttitudeTarget>(\"/mavros/setpoint_raw/attitude\", 10, setpoint_attitude_cb);\n\n    //ros::Subscriber optitrack_sub = nh.subscribe<geometry_msgs::PoseStamped>(\"/vrpn_client_node/UAV/pose\", 1000, optitrack_cb);\n\n    // \u53c2\u6570\u8bfb\u53d6\n    nh.param<float>(\"Takeoff_height\", Takeoff_height, 1.0);\n    nh.param<float>(\"Disarm_height\", Disarm_height, 0.15);\n    nh.param<int>(\"flag_att_sp\", flag_att_sp, 0);\n\n    cout << \"Takeoff_height: \"<< Takeoff_height<<\" [m] \"<<endl;\n    cout << \"Disarm_height : \"<< Disarm_height <<\" [m] \"<<endl;\n    cout << \"flag_att_sp : \"<< flag_att_sp <<\"  \"<<endl;\n\n    ros::Rate rate(50.0);\n    //\u7528\u4e8e\u4e0emavros\u901a\u8baf\u7684\u7c7b\n    command_to_mavros pos_controller;\n\n    pos_controller.printf_param();\n\n    //\u4f4d\u7f6e\u63a7\u5236\u7c7b - \u6839\u636eswitch_ude\u9009\u62e9\u5176\u4e2d\u4e00\u4e2a\u4f7f\u7528\uff0c\u9ed8\u8ba4\u4e3aPID\n    pos_controller_PID pos_controller_pid;\n    pos_controller_UDE pos_controller_ude;\n    pos_controller_passivity pos_controller_ps;\n    pos_controller_NE pos_controller_ne;\n\n    // \u9009\u62e9\u63a7\u5236\u7387\n    int switch_ude;\n    cout << \"Please choose the controller: 0 for PID,1 for UDE,2 for passivity, 3 for NE: \"<<endl;\n    cin >> switch_ude;\n\n    if(switch_ude == 0)\n    {\n        pos_controller_pid.printf_param();\n    }else if(switch_ude == 1)\n    {\n        pos_controller_ude.printf_param();\n    }else if(switch_ude == 2)\n    {\n        pos_controller_ps.printf_param();\n    }else if(switch_ude == 3)\n    {\n        pos_controller_ne.printf_param();\n    }\n\n\n    int check_flag;\n    // \u8fd9\u4e00\u6b65\u662f\u4e3a\u4e86\u7a0b\u5e8f\u8fd0\u884c\u524d\u68c0\u67e5\u4e00\u4e0b\u53c2\u6570\u662f\u5426\u6b63\u786e\n    // \u8f93\u51651,\u7ee7\u7eed\uff0c\u5176\u4ed6\uff0c\u9000\u51fa\u7a0b\u5e8f\n    cout << \"Please check the parameter and setting\uff0c1 for go on\uff0c else for quit: \"<<endl;\n    cin >> check_flag;\n\n    if(check_flag != 1)\n    {\n        return -1;\n    }\n\n    // \u7b49\u5f85\u548c\u98de\u63a7\u7684\u8fde\u63a5\n    while(ros::ok() && pos_controller.current_state.connected)\n    {\n        ros::spinOnce();\n        rate.sleep();\n        ROS_INFO(\"Not Connected\");\n    }\n\n    // \u8fde\u63a5\u6210\u529f\n    ROS_INFO(\"Connected!!\");\n\n    // \u5148\u8bfb\u53d6\u4e00\u4e9b\u98de\u63a7\u7684\u6570\u636e\n    int i =0;\n    for(i=0;i<50;i++)\n    {\n        ros::spinOnce();\n        rate.sleep();\n    }\n\n    //Set the takeoff position\n    Takeoff_position = pos_controller.pos_drone_fcu;\n\n    //NE\u9700\u8981\u8bbe\u7f6e\u8d77\u98de\u521d\u59cb\u503c\n    if(switch_ude == 3)\n    {\n        pos_controller_ne.set_initial_pos(pos_controller.pos_drone_fcu);\n    }\n\n    //\u521d\u59cb\u5316\u547d\u4ee4-\n    // \u9ed8\u8ba4\u8bbe\u7f6e\uff1aIdle\u6a21\u5f0f \u7535\u673a\u6020\u901f\u65cb\u8f6c \u7b49\u5f85\u6765\u81ea\u4e0a\u5c42\u7684\u63a7\u5236\u6307\u4ee4\n    Command_Now.comid = 0;\n    Command_Now.command = Takeoff;\n    Command_Now.sub_mode = 0;\n    Command_Now.pos_sp[0] = pos_controller.pos_drone_fcu[0];\n    Command_Now.pos_sp[1] = pos_controller.pos_drone_fcu[1];\n    Command_Now.pos_sp[2] = pos_controller.pos_drone_fcu[2];\n    Command_Now.vel_sp[0] = 0;\n    Command_Now.vel_sp[1] = 0;\n    Command_Now.vel_sp[2] = 0;\n    Command_Now.yaw_sp = 0;\n\n\n    // \u8bb0\u5f55\u542f\u63a7\u65f6\u95f4\n    ros::Time begin_time = ros::Time::now();\n    float last_time = get_ros_time(begin_time);\n    float dt = 0;\n\n    // write into files\n    ofstream ofile;\n    ofile.open(\"/home/amov/fly_logs/command_fuzzy.txt\");\n        \n//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u4e3b  \u5faa  \u73af<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n    while(ros::ok())\n    {\n        //\u6267\u884c\u56de\u8c03\u51fd\u6570\n        ros::spinOnce();\n\n        // \u5f53\u524d\u65f6\u95f4\n        float cur_time = get_ros_time(begin_time);\n        dt = cur_time  - last_time;\n\n        dt = constrain_function2(dt, 0.005, 0.03);\n\n        last_time = cur_time;\n\n        //Check for geo fence: If drone is out of the geo fence, it will land now.\n        if(pos_controller.check_failsafe() == 1)\n        {\n            Command_Now.command = Land;\n        }\n\n        //Printf the drone state\n        //pos_controller.prinft_drone_state_full(cur_time);\n        pos_controller.prinft_drone_state(cur_time);\n\n        //Printf the command state\n        prinft_command_state();\n\n        if(switch_ude == 0)\n        {\n            pos_controller_pid.printf_result();\n        }else if(switch_ude == 1)\n        {\n            pos_controller_ude.printf_result();\n        }else if(switch_ude == 2)\n        {\n            pos_controller_ps.printf_result();\n        }else if(switch_ude == 3)\n        {\n            pos_controller_ne.printf_result();\n        }\n\n\n        //\u65e0\u4eba\u673a\u4e00\u65e6\u63a5\u53d7\u5230Land\u6307\u4ee4\uff0c\u5219\u4f1a\u5c4f\u853d\u5176\u4ed6\u6307\u4ee4\n        if(Command_Last.command == Land)\n        {\n            Command_Now.command = Land;\n        }\n\n        switch (Command_Now.command)\n        {\n        // \u3010Idle\u3011 \u6020\u901f\u65cb\u8f6c\uff0c\u6b64\u65f6\u53ef\u4ee5\u5207\u5165offboard\u6a21\u5f0f\uff0c\u4f46\u4e0d\u4f1a\u8d77\u98de\u3002\n        case Idle:\n            pos_controller.idle();\n            break;\n\n        // \u3010Takeoff\u3011 \u4ece\u6446\u653e\u521d\u59cb\u4f4d\u7f6e\u539f\u5730\u8d77\u98de\u81f3\u6307\u5b9a\u9ad8\u5ea6\uff0c\u504f\u822a\u89d2\u4e5f\u4fdd\u6301\u5f53\u524d\u89d2\u5ea6\n        case Takeoff:\n            pos_sp = Eigen::Vector3d(Takeoff_position[0],Takeoff_position[1],Takeoff_position[2]+Takeoff_height);\n            vel_sp = Eigen::Vector3d(0.0,0.0,0.0);\n            yaw_sp = pos_controller.euler_fcu[2]; //rad\n\n            if(switch_ude == 0)\n            {\n                accel_sp = pos_controller_pid.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, vel_sp, Command_Now.sub_mode, dt);\n            }else if(switch_ude == 1)\n            {\n                accel_sp = pos_controller_ude.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }else if(switch_ude == 2)\n            {\n                accel_sp = pos_controller_ps.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }else if(switch_ude == 3)\n            {\n                accel_sp = pos_controller_ps.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }\n\n            if(flag_att_sp == 0)\n            {\n                pos_controller.send_accel_setpoint(accel_sp, yaw_sp);\n            }else\n            {\n                q_sp =  thrustToAttitude(accel_sp, yaw_sp);\n\n                //att_sp =  quaternion_to_euler(q_sp);\n\n                thrust_sp = accel_sp.norm();\n\n                //cout << \"thrust_sp: \" << thrust_sp <<endl;\n\n                //cout << \"Attitude_sp0 [R P Y] : \" << att_sp[0] * 180/M_PI <<\" [deg] \"<<att_sp[1] * 180/M_PI << \" [deg] \"<< att_sp[2] * 180/M_PI<<\" [deg] \"<<endl;\n\n                pos_controller.send_attitude_setpoint(q_sp, thrust_sp);\n            }\n\n            break;\n\n        // \u3010Move_ENU\u3011 ENU\u7cfb\u79fb\u52a8\u3002\u53ea\u6709PID\u7b97\u6cd5\u4e2d\u624d\u6709\u8ffd\u8e2a\u901f\u5ea6\u7684\u9009\u9879\uff0c\u5176\u4ed6\u63a7\u5236\u53ea\u80fd\u8ffd\u8e2a\u4f4d\u7f6e\n        case Move_ENU:\n            pos_sp = Eigen::Vector3d(Command_Now.pos_sp[0],Command_Now.pos_sp[1],Command_Now.pos_sp[2]);\n            vel_sp = Eigen::Vector3d(Command_Now.vel_sp[0],Command_Now.vel_sp[1],Command_Now.vel_sp[2]);\n            yaw_sp = Command_Now.yaw_sp;\n\n            if(switch_ude == 0)\n            {\n                accel_sp = pos_controller_pid.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, vel_sp, Command_Now.sub_mode, dt);\n            }else if(switch_ude == 1)\n            {\n                accel_sp = pos_controller_ude.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }else if(switch_ude == 2)\n            {\n                accel_sp = pos_controller_ps.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n                //accel_sp = pos_controller_ps.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }else if(switch_ude == 3)\n            {\n                accel_sp = pos_controller_ne.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n                //accel_sp = pos_controller_ps.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }\n\n            if(flag_att_sp == 0)\n            {\n                pos_controller.send_accel_setpoint(accel_sp, yaw_sp);\n            }else\n            {\n                q_sp =  thrustToAttitude(accel_sp, yaw_sp);\n\n                //att_sp =  quaternion_to_euler(q_sp);\n\n                thrust_sp = accel_sp.norm();\n\t\tofile << cur_time << \"\t\" << accel_sp[0] << \"\t\" << accel_sp[1] << endl;\n\n                //cout << \"thrust_sp: \" << thrust_sp <<endl;\n\n                //cout << \"Attitude_sp0 [R P Y] : \" << att_sp[0] * 180/M_PI <<\" [deg] \"<<att_sp[1] * 180/M_PI << \" [deg] \"<< att_sp[2] * 180/M_PI<<\" [deg] \"<<endl;\n\n                pos_controller.send_attitude_setpoint(q_sp, thrust_sp);\n            }\n\n\n            break;\n\n        // \u3010Move_Body\u3011 \u673a\u4f53\u7cfb\u79fb\u52a8\u3002\u53ea\u6709PID\u7b97\u6cd5\u4e2d\u624d\u6709\u8ffd\u8e2a\u901f\u5ea6\u7684\u9009\u9879\uff0c\u5176\u4ed6\u63a7\u5236\u53ea\u80fd\u8ffd\u8e2a\u4f4d\u7f6e\n        case Move_Body:\n            //\u53ea\u6709\u5728comid\u589e\u52a0\u65f6\u624d\u4f1a\u8fdb\u5165\u89e3\u7b97\n            if( Command_Now.comid  >  Command_Last.comid )\n            {\n                //xy velocity mode\n                if( Command_Now.sub_mode & 0b10 )\n                {\n                    float d_vel_body[2] = {Command_Now.vel_sp[0], Command_Now.vel_sp[1]};         //the desired xy velocity in Body Frame\n                    float d_vel_enu[2];                                                           //the desired xy velocity in NED Frame\n\n                    rotation_yaw(pos_controller.euler_fcu[2], d_vel_body, d_vel_enu);\n                    vel_sp[0] = d_vel_enu[0];\n                    vel_sp[1] = d_vel_enu[1];\n                }\n                //xy position mode\n                else\n                {\n                    float d_pos_body[2] = {Command_Now.pos_sp[0], Command_Now.pos_sp[1]};         //the desired xy position in Body Frame\n                    float d_pos_enu[2];                                                           //the desired xy position in enu Frame (The origin point is the drone)\n                    rotation_yaw(pos_controller.euler_fcu[2], d_pos_body, d_pos_enu);\n\n                    pos_sp[0] = pos_controller.pos_drone_fcu[0] + d_pos_enu[0];\n                    pos_sp[1] = pos_controller.pos_drone_fcu[1] + d_pos_enu[1];\n                }\n\n                //z velocity mode\n                if( Command_Now.sub_mode & 0b01 )\n                {\n                    vel_sp[2] = Command_Now.vel_sp[2];\n                }\n                //z posiiton mode\n                {\n                    pos_sp[2] = pos_controller.pos_drone_fcu[2] + Command_Now.pos_sp[2];\n                }\n\n                yaw_sp = pos_controller.euler_fcu[2] + Command_Now.yaw_sp;\n\n            }\n\n            if(switch_ude == 0)\n            {\n                accel_sp = pos_controller_pid.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, vel_sp, Command_Now.sub_mode, dt);\n            }else if(switch_ude == 1)\n            {\n                accel_sp = pos_controller_ude.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }else if(switch_ude == 2)\n            {\n                accel_sp = pos_controller_ps.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }else if(switch_ude == 3)\n            {\n                accel_sp = pos_controller_ne.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }\n\n            if(flag_att_sp == 0)\n            {\n                pos_controller.send_accel_setpoint(accel_sp, yaw_sp);\n            }else\n            {\n                q_sp =  thrustToAttitude(accel_sp, yaw_sp);\n\n                //att_sp =  quaternion_to_euler(q_sp);\n\n                thrust_sp = accel_sp.norm();\n\n                //cout << \"thrust_sp: \" << thrust_sp <<endl;\n\n                //cout << \"Attitude_sp0 [R P Y] : \" << att_sp[0] * 180/M_PI <<\" [deg] \"<<att_sp[1] * 180/M_PI << \" [deg] \"<< att_sp[2] * 180/M_PI<<\" [deg] \"<<endl;\n\n                pos_controller.send_attitude_setpoint(q_sp, thrust_sp);\n            }\n\n            break;\n\n        // \u3010Hold\u3011 \u60ac\u505c\u3002\u5f53\u524d\u4f4d\u7f6e\u60ac\u505c\n        case Hold:\n            if (Command_Last.command != Hold)\n            {\n                pos_sp = Eigen::Vector3d(pos_controller.pos_drone_fcu[0],pos_controller.pos_drone_fcu[1],pos_controller.pos_drone_fcu[2]);\n                yaw_sp = pos_controller.euler_fcu[2];\n            }\n\n            if(switch_ude == 0)\n            {\n                accel_sp = pos_controller_pid.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, vel_sp, Command_Now.sub_mode, dt);\n            }else if(switch_ude == 1)\n            {\n                accel_sp = pos_controller_ude.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }else if(switch_ude == 2)\n            {\n                accel_sp = pos_controller_ps.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }else if(switch_ude == 3)\n            {\n                accel_sp = pos_controller_ne.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n            }\n\n            if(flag_att_sp == 0)\n            {\n                pos_controller.send_accel_setpoint(accel_sp, yaw_sp);\n            }else\n            {\n                q_sp =  thrustToAttitude(accel_sp, yaw_sp);\n\n                //att_sp =  quaternion_to_euler(q_sp);\n\n                thrust_sp = accel_sp.norm();\n\n                //cout << \"thrust_sp: \" << thrust_sp <<endl;\n\n                //cout << \"Attitude_sp0 [R P Y] : \" << att_sp[0] * 180/M_PI <<\" [deg] \"<<att_sp[1] * 180/M_PI << \" [deg] \"<< att_sp[2] * 180/M_PI<<\" [deg] \"<<endl;\n\n                pos_controller.send_attitude_setpoint(q_sp, thrust_sp);\n            }\n\n            break;\n\n        // \u3010Land\u3011 \u964d\u843d\u3002\u5f53\u524d\u4f4d\u7f6e\u539f\u5730\u964d\u843d\uff0c\u964d\u843d\u540e\u4f1a\u81ea\u52a8\u4e0a\u9501\uff0c\u4e14\u5207\u6362\u4e3amannual\u6a21\u5f0f\n        case Land:\n            if (Command_Last.command != Land)\n            {\n                pos_sp = Eigen::Vector3d(pos_controller.pos_drone_fcu[0],pos_controller.pos_drone_fcu[1],Takeoff_position[2]);\n                yaw_sp = pos_controller.euler_fcu[2];\n            }\n\n            //\u5982\u679c\u8ddd\u79bb\u8d77\u98de\u9ad8\u5ea6\u5c0f\u4e8e10\u5398\u7c73\uff0c\u5219\u76f4\u63a5\u4e0a\u9501\u5e76\u5207\u6362\u4e3a\u624b\u52a8\u6a21\u5f0f\uff1b\n            if(abs(pos_controller.pos_drone_fcu[2] - 0.2) < Disarm_height)\n            {\n                if(pos_controller.current_state.mode == \"OFFBOARD\")\n                {\n                    pos_controller.mode_cmd.request.custom_mode = \"MANUAL\";\n                    pos_controller.set_mode_client.call(pos_controller.mode_cmd);\n                }\n\n                if(pos_controller.current_state.armed)\n                {\n                    pos_controller.arm_cmd.request.value = false;\n                    pos_controller.arming_client.call(pos_controller.arm_cmd);\n\n                }\n\n                if (pos_controller.arm_cmd.response.success)\n                {\n                    cout<<\"Disarm successfully!\"<<endl;\n                }\n            }else\n            {\n\n                if(switch_ude == 0)\n                {\n                    accel_sp = pos_controller_pid.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, vel_sp, 0b00, dt);\n                }else if(switch_ude == 1)\n                {\n                    accel_sp = pos_controller_ude.pos_controller(pos_controller.pos_drone_fcu, pos_controller.vel_drone_fcu, pos_sp, dt);\n                }else if(switch_ude == 2)\n                {\n                    accel_sp = pos_controller_ps.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n                }else if(switch_ude == 3)\n                {\n                    accel_sp = pos_controller_ne.pos_controller(pos_drone_mocap, pos_controller.vel_drone_fcu, pos_sp, dt);\n                }\n\n                if(flag_att_sp == 0)\n                {\n                    pos_controller.send_accel_setpoint(accel_sp, yaw_sp);\n                }else\n                {\n                    q_sp =  thrustToAttitude(accel_sp, yaw_sp);\n\n                    //att_sp =  quaternion_to_euler(q_sp);\n\n                    thrust_sp = accel_sp.norm();\n\n                    //cout << \"thrust_sp: \" << thrust_sp <<endl;\n\n                    //cout << \"Attitude_sp0 [R P Y] : \" << att_sp[0] * 180/M_PI <<\" [deg] \"<<att_sp[1] * 180/M_PI << \" [deg] \"<< att_sp[2] * 180/M_PI<<\" [deg] \"<<endl;\n\n                    pos_controller.send_attitude_setpoint(q_sp, thrust_sp);\n                }\n            }\n\n            break;\n\n        // \u3010Disarm\u3011 \u7d27\u6025\u4e0a\u9501\u3002\u76f4\u63a5\u4e0a\u9501\uff0c\u4e0d\u5efa\u8bae\u4f7f\u7528\uff0c\u5371\u9669\u3002\n        case Disarm:\n            if(pos_controller.current_state.mode == \"OFFBOARD\")\n            {\n                pos_controller.mode_cmd.request.custom_mode = \"MANUAL\";\n                pos_controller.set_mode_client.call(pos_controller.mode_cmd);\n            }\n\n            if(pos_controller.current_state.armed)\n            {\n                pos_controller.arm_cmd.request.value = false;\n                pos_controller.arming_client.call(pos_controller.arm_cmd);\n\n            }\n\n            if (pos_controller.arm_cmd.response.success)\n            {\n                cout<<\"Disarm successfully!\"<<endl;\n            }\n\n            break;\n\n        // \u3010Failsafe_land\u3011 \u6682\u7a7a\u3002\u53ef\u8fdb\u884c\u81ea\u5b9a\u4e49\n        case Failsafe_land:\n            break;\n\n        }\n\n        Command_Last = Command_Now;\n\n        rate.sleep();\n    }\n\n    ofile.close();\n    return 0;\n\n}\n\n// \u3010\u83b7\u53d6\u5f53\u524d\u65f6\u95f4\u51fd\u6570\u3011 \u5355\u4f4d\uff1a\u79d2\nfloat get_ros_time(ros::Time begin)\n{\n    ros::Time time_now = ros::Time::now();\n    float currTimeSec = time_now.sec-begin.sec;\n    float currTimenSec = time_now.nsec / 1e9 - begin.nsec / 1e9;\n    return (currTimeSec + currTimenSec);\n}\n// \u3010\u6253\u5370\u63a7\u5236\u6307\u4ee4\u51fd\u6570\u3011\nvoid prinft_command_state()\n{\n    cout <<\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Command State<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" <<endl;\n\n    int sub_mode;\n    sub_mode = Command_Now.sub_mode;\n\n    switch(Command_Now.command)\n    {\n    case Move_ENU:\n        cout << \"Command: [ Move_ENU ] \" <<endl;\n\n        if((sub_mode & 0b10) == 0) //xy channel\n        {\n            cout << \"Submode: xy position control \"<<endl;\n            cout << \"X_setpoint   : \" << Command_Now.pos_sp[0] << \" [ m ]\"  << \"  Y_setpoint : \"<< Command_Now.pos_sp[1] << \" [ m ]\"<<endl;\n        }\n        else{\n            cout << \"Submode: xy velocity control \"<<endl;\n            cout << \"X_setpoint   : \" << Command_Now.vel_sp[0] << \" [m/s]\" << \"  Y_setpoint : \"<< Command_Now.vel_sp[1] << \" [m/s]\" <<endl;\n        }\n\n        if((sub_mode & 0b01) == 0) //z channel\n        {\n            cout << \"Submode:  z position control \"<<endl;\n            cout << \"Z_setpoint   : \"<< Command_Now.pos_sp[2] << \" [ m ]\" << endl;\n        }\n        else\n        {\n            cout << \"Submode:  z velocity control \"<<endl;\n            cout << \"Z_setpoint   : \"<< Command_Now.vel_sp[2] << \" [m/s]\" <<endl;\n        }\n\n        cout << \"Yaw_setpoint : \"  << Command_Now.yaw_sp* 180/M_PI << \" [deg] \" <<endl;\n\n        break;\n    case Move_Body:\n        cout << \"Command: [ Move_Body ] \" <<endl;\n\n        if((sub_mode & 0b10) == 0) //xy channel\n        {\n            cout << \"Submode: xy position control \"<<endl;\n            cout << \"X_setpoint   : \" << Command_Now.pos_sp[0] << \" [ m ]\"  << \"  Y_setpoint : \"<< Command_Now.pos_sp[1] << \" [ m ]\"<<endl;\n        }\n        else{\n            cout << \"Submode: xy velocity control \"<<endl;\n            cout << \"X_setpoint   : \" << Command_Now.vel_sp[0] << \" [m/s]\" << \"  Y_setpoint : \"<< Command_Now.vel_sp[1] << \" [m/s]\" <<endl;\n        }\n\n        if((sub_mode & 0b01) == 0) //z channel\n        {\n            cout << \"Submode:  z position control \"<<endl;\n            cout << \"Z_setpoint   : \"<< Command_Now.pos_sp[2] << \" [ m ]\" << endl;\n        }\n        else\n        {\n            cout << \"Submode:  z velocity control \"<<endl;\n            cout << \"Z_setpoint   : \"<< Command_Now.vel_sp[2] << \" [m/s]\" <<endl;\n        }\n\n        cout << \"Yaw_setpoint : \"  << Command_Now.yaw_sp * 180/M_PI<< \" [deg] \" <<endl;\n\n        break;\n\n    case Hold:\n        cout << \"Command: [ Hold ] \" <<endl;\n        cout << \"Hold Position [X Y Z] : \" << pos_sp[0] << \" [ m ] \"<< pos_sp[1]<<\" [ m ] \"<< pos_sp[2]<<\" [ m ] \"<<endl;\n        cout << \"Yaw_setpoint : \"  << yaw_sp* 180/M_PI << \" [deg] \" <<endl;\n        break;\n\n    case Land:\n        cout << \"Command: [ Land ] \" <<endl;\n        cout << \"Land Position [X Y Z] : \" << pos_sp[0] << \" [ m ] \"<< pos_sp[1]<<\" [ m ] \"<< pos_sp[2]<<\" [ m ] \"<<endl;\n        cout << \"Yaw_setpoint : \"  << yaw_sp* 180/M_PI << \" [deg] \" <<endl;\n        break;\n\n    case Disarm:\n        cout << \"Command: [ Disarm ] \" <<endl;\n        break;\n\n    case Failsafe_land:\n        cout << \"Command: [ Failsafe_land ] \" <<endl;\n        break;\n\n    case Idle:\n        cout << \"Command: [ Idle ] \" <<endl;\n        break;\n\n    case Takeoff:\n        cout << \"Command: [ Takeoff ] \" <<endl;\n        cout << \"Takeoff Position [X Y Z] : \" << pos_sp[0] << \" [ m ] \"<< pos_sp[1]<<\" [ m ] \"<< pos_sp[2]<<\" [ m ] \"<<endl;\n        cout << \"Yaw_setpoint : \"  << yaw_sp* 180/M_PI << \" [deg] \" <<endl;\n        break;\n    }\n\n\n\n}\n// \u3010\u5750\u6807\u7cfb\u65cb\u8f6c\u51fd\u6570\u3011- \u673a\u4f53\u7cfb\u5230enu\u7cfb\n// input\u662f\u673a\u4f53\u7cfb,output\u662f\u60ef\u6027\u7cfb\uff0cyaw_angle\u662f\u5f53\u524d\u504f\u822a\u89d2\nvoid rotation_yaw(float yaw_angle, float input[2], float output[2])\n{\n    output[0] = input[0] * cos(yaw_angle) - input[1] * sin(yaw_angle);\n    output[1] = input[0] * sin(yaw_angle) + input[1] * cos(yaw_angle);\n}\n", "meta": {"hexsha": "b4cda4984d5bb835e25609ae4a316f31503b8c7b", "size": 24094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/px4_pos_controller.cpp", "max_stars_repo_name": "UAV-Power-Group/uav_pendulum", "max_stars_repo_head_hexsha": "c8fa40f1730b92fc508327bf39e4c8cfed0018ac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T12:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T12:55:25.000Z", "max_issues_repo_path": "src/px4_pos_controller.cpp", "max_issues_repo_name": "UAV-Power-Group/uav_pendulum", "max_issues_repo_head_hexsha": "c8fa40f1730b92fc508327bf39e4c8cfed0018ac", "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/px4_pos_controller.cpp", "max_forks_repo_name": "UAV-Power-Group/uav_pendulum", "max_forks_repo_head_hexsha": "c8fa40f1730b92fc508327bf39e4c8cfed0018ac", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-06T12:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T12:55:27.000Z", "avg_line_length": 35.1737226277, "max_line_length": 168, "alphanum_fraction": 0.5479787499, "num_tokens": 6678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1814518254820698}}
{"text": "//\n// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)\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// Official repository: https://github.com/cppalliance/json\n//\n\n#ifndef BOOST_JSON_DETAIL_NUMBER_CAST_HPP\n#define BOOST_JSON_DETAIL_NUMBER_CAST_HPP\n\n#include <boost/json/value.hpp>\n#include <boost/json/error.hpp>\n#include <limits>\n#include <type_traits>\n\nBOOST_JSON_NS_BEGIN\nnamespace detail {\n\ntemplate<class T>\nusing is_signed_integral =\n    std::integral_constant<bool,\n        std::is_signed<T>::value &&\n        ! std::is_floating_point<T>::value>;\n\ntemplate<class T>\nusing is_unsigned_integral =\n    std::integral_constant<bool,\n        std::is_unsigned<T>::value &&\n        ! std::is_same<T, bool>::value>;\n\ntemplate<class T>\nT\nnumber_cast(\n    value const& jv,\n    error_code& ec,\n    typename std::enable_if<\n        is_signed_integral<T>::value\n            >::type* = 0) noexcept\n{\n    T result{};\n    if(jv.kind() == kind::int64)\n    {\n        auto const i = jv.get_int64();\n        if( i > (std::numeric_limits<T>::max)() ||\n            i < (std::numeric_limits<T>::min)())\n        {\n            ec = error::not_exact;\n        }\n        else\n        {\n            result = static_cast<T>(i);\n        }\n    }\n    else if(jv.kind() == kind::uint64)\n    {\n        auto const u = jv.get_uint64();\n        if(u > static_cast<std::uint64_t>((\n            std::numeric_limits<T>::max)()))\n        {\n            ec = error::not_exact;\n        }\n        else\n        {\n            result = static_cast<T>(u);\n        }\n    }\n    else\n    {\n        BOOST_ASSERT(jv.kind() == kind::double_);\n        auto const d = jv.get_double();\n        if( d > (std::numeric_limits<T>::max)() ||\n            d < (std::numeric_limits<T>::min)() ||\n            static_cast<T>(d) != d)\n        {\n            ec = error::not_exact;\n        }\n        else\n        {\n            result = static_cast<T>(d);\n        }\n    }\n    return result;\n}\n\ntemplate<class T>\nT\nnumber_cast(\n    value const& jv,\n    error_code& ec,\n    typename std::enable_if<\n        is_unsigned_integral<T>::value\n            >::type* = 0\n    ) noexcept\n{\n    T result{};\n    if(jv.kind() == kind::int64)\n    {\n        auto const i = jv.get_int64();\n        if( i < 0 || static_cast<std::uint64_t>(i) >\n            (std::numeric_limits<T>::max)())\n        {\n            ec = error::not_exact;\n        }\n        else\n        {\n            result = static_cast<T>(i);\n        }\n    }\n    else if(jv.kind() == kind::uint64)\n    {\n        auto const u = jv.get_uint64();\n        if(u > (std::numeric_limits<T>::max)())\n        {\n            ec = error::not_exact;\n        }\n        else\n        {\n            result = static_cast<T>(u);\n        }\n    }\n    else\n    {\n        BOOST_ASSERT(jv.kind() == kind::double_);\n        auto const d = jv.get_double();\n        if( d < 0 ||\n            d > (std::numeric_limits<T>::max)() ||\n            static_cast<T>(d) != d)\n        {\n            ec = error::not_exact;\n        }\n        else\n        {\n            result = static_cast<T>(d);\n        }\n    }\n    return result;\n}\n\ntemplate<class T>\nT\nnumber_cast(\n    value const& jv,\n    error_code&,\n    typename std::enable_if<\n        std::is_floating_point<T>::value\n            >::type* = 0\n    ) noexcept\n{\n    if(jv.kind() == kind::int64)\n        return static_cast<T>(jv.get_int64());\n\n    if(jv.kind() == kind::uint64)\n        return static_cast<T>(jv.get_uint64());\n\n    BOOST_ASSERT(jv.kind() == kind::double_);\n    return static_cast<T>(jv.get_double());\n}\n\n} // detail\nBOOST_JSON_NS_END\n\n#endif\n", "meta": {"hexsha": "9c25df97908e254a475639f30ff00bb7872e70dc", "size": 3673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/json/detail/number_cast.hpp", "max_stars_repo_name": "djarek/json", "max_stars_repo_head_hexsha": "e1bd8083ed547de26b567e7eef02a6f1142a9128", "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/json/detail/number_cast.hpp", "max_issues_repo_name": "djarek/json", "max_issues_repo_head_hexsha": "e1bd8083ed547de26b567e7eef02a6f1142a9128", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T16:41:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T16:41:13.000Z", "max_forks_repo_path": "include/boost/json/detail/number_cast.hpp", "max_forks_repo_name": "cppalliance-bot/json", "max_forks_repo_head_hexsha": "085069be8132d2494fd61363c58dc5f124c44ad7", "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": 22.2606060606, "max_line_length": 79, "alphanum_fraction": 0.5232779744, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.18145182192155482}}
{"text": "#ifndef _RSA_FACE_DETECTED_HPP_\r\n#define _RSA_FACE_DETECTED_HPP_\r\n \r\n#include <vector>\r\n#include <string>\r\n#include <boost/smart_ptr.hpp>\r\n#include <boost/make_shared.hpp>\r\n\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n#include \"caffe/caffe.hpp\"\r\n#include \"config.hpp\"\r\n#include <glog/logging.h>\r\n\r\n#include \"inf_rsa_face_detection_api.hh\"\r\n\r\nclass RsaFaceDetector {\r\n    public:\r\n        explicit RsaFaceDetector(unsigned int gpuId, \\\r\n                    const std::string & sfnNet, const std::string & sfnWeight, \\\r\n                    const std::string & rsaNet, const std::string & rsaWeight, \\\r\n                    const std::string & lrnNet, const std::string & lrnWeight);\r\n        ~RsaFaceDetector() {};\r\n        imgsFaceLandmarkList detect_(std::vector<cv::Mat> iamges);\r\n        facesLandmarkPerImg detect_(cv::Mat image);\r\n        void sfnProcess_(const std::vector<cv::Mat> images);\r\n        void sfnProcess_(const cv::Mat & img);\r\n        void rsaProcess_(void);\r\n        void lrnProcess_(imgsFaceLandmarkList & faceResult);\r\n        void lrnProcess_(facesLandmarkPerImg & faceResult);\r\n\r\n    private:\r\n        std::string sfnNetDef_;\r\n        std::string sfnNetWeight_;\r\n        std::string rsaNetDef_;\r\n        std::string rsaNetWeight_;\r\n        std::string lrnNetDef_;\r\n        std::string lrnNetWeight_;\r\n        unsigned int gpuId_;\r\n\r\n        std::vector<std::shared_ptr<caffe::Blob<float>>> transFeatMaps_;\r\n        caffe::Blob<float> *sfnNetOutput_;\r\n        caffe::Blob<float> *inputLayer_;\r\n        caffe::Blob<float> *rsaInputLayer_;\r\n        caffe::Blob<float> *lrnInputLayer_;\r\n        std::vector<cv::Mat> inputChannels_;\r\n\r\n        double resizeFactor_;\r\n        std::vector<float> anchorBoxLen_;\r\n        double threshScore_;\r\n        double stride_;\r\n        double anchorCenter_;\r\n        std::vector<int> scale_;\r\n        std::shared_ptr<caffe::Net<float>> sfnNet_;\r\n        std::shared_ptr<caffe::Net<float>> rsaNet_;\r\n        std::shared_ptr<caffe::Net<float>> lrnNet_;\r\n};\r\n\r\n#endif", "meta": {"hexsha": "768594bf0c564001e71f933a6fd76be0368e082e", "size": 2089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rsa_face_detection.hpp", "max_stars_repo_name": "ZhouKai90/RSA_face_detection", "max_stars_repo_head_hexsha": "9ea05884006f740c09f97271435413c0bc45cbb3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-12T05:04:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-12T05:04:53.000Z", "max_issues_repo_path": "src/rsa_face_detection.hpp", "max_issues_repo_name": "ZhouKai90/RSA_face_detection", "max_issues_repo_head_hexsha": "9ea05884006f740c09f97271435413c0bc45cbb3", "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/rsa_face_detection.hpp", "max_forks_repo_name": "ZhouKai90/RSA_face_detection", "max_forks_repo_head_hexsha": "9ea05884006f740c09f97271435413c0bc45cbb3", "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.8166666667, "max_line_length": 81, "alphanum_fraction": 0.6366682623, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.18145182041192495}}
{"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// File generated at Thu 10 May 2018 14:56:07\n\n/**\n * @file CMSSMNoFV_two_scale_ewsb_solver.hpp\n *\n * @brief contains class for solving EWSB when two-scale algorithm is used\n *\n * This file was generated at Thu 10 May 2018 14:56:07 with FlexibleSUSY\n * 2.0.1 (git commit: unknown) and SARAH 4.12.2 .\n */\n\n#ifndef CMSSMNoFV_TWO_SCALE_EWSB_SOLVER_H\n#define CMSSMNoFV_TWO_SCALE_EWSB_SOLVER_H\n\n#include \"CMSSMNoFV_ewsb_solver.hpp\"\n#include \"CMSSMNoFV_ewsb_solver_interface.hpp\"\n#include \"error.hpp\"\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\nclass Two_scale;\n\nclass CMSSMNoFV_mass_eigenstates;\n\ntemplate<>\nclass CMSSMNoFV_ewsb_solver<Two_scale> : public CMSSMNoFV_ewsb_solver_interface {\npublic:\n   CMSSMNoFV_ewsb_solver() = default;\n   CMSSMNoFV_ewsb_solver(const CMSSMNoFV_ewsb_solver&) = default;\n   CMSSMNoFV_ewsb_solver(CMSSMNoFV_ewsb_solver&&) = default;\n   virtual ~CMSSMNoFV_ewsb_solver() {}\n   CMSSMNoFV_ewsb_solver& operator=(const CMSSMNoFV_ewsb_solver&) = default;\n   CMSSMNoFV_ewsb_solver& operator=(CMSSMNoFV_ewsb_solver&&) = default;\n\n   virtual void set_loop_order(int l) override { loop_order = l; }\n   virtual void set_number_of_iterations(int n) override { number_of_iterations = n; }\n   virtual void set_precision(double p) override { precision = p; }\n\n   virtual int get_loop_order() const override { return loop_order; }\n   virtual int get_number_of_iterations() const override { return number_of_iterations; }\n   virtual double get_precision() const override { return precision; }\n\n   virtual int solve(CMSSMNoFV_mass_eigenstates&) override;\nprivate:\n   static const int number_of_ewsb_equations = 2;\n   using EWSB_vector_t = Eigen::Matrix<double,number_of_ewsb_equations,1>;\n\n   class EEWSBStepFailed : public Error {\n   public:\n      virtual ~EEWSBStepFailed() {}\n      virtual std::string what() const { return \"Could not perform EWSB step.\"; }\n   };\n\n   int number_of_iterations{100}; ///< maximum number of iterations\n   int loop_order{2};             ///< loop order to solve EWSB at\n   double precision{1.e-5};       ///< precision goal\n\n   void set_ewsb_solution(CMSSMNoFV_mass_eigenstates&, const EWSB_solver*);\n   template <typename It> void set_best_ewsb_solution(CMSSMNoFV_mass_eigenstates&, It, It);\n\n   int solve_tree_level(CMSSMNoFV_mass_eigenstates&);\n   int solve_iteratively(CMSSMNoFV_mass_eigenstates&);\n   int solve_iteratively_at(CMSSMNoFV_mass_eigenstates&, int);\n   int solve_iteratively_with(CMSSMNoFV_mass_eigenstates&, EWSB_solver*, const EWSB_vector_t&);\n\n   EWSB_vector_t initial_guess(const CMSSMNoFV_mass_eigenstates&) const;\n   EWSB_vector_t tadpole_equations(const CMSSMNoFV_mass_eigenstates&) const;\n   EWSB_vector_t ewsb_step(const CMSSMNoFV_mass_eigenstates&) const;\n};\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "92a6a64011a626fa5674265487038cd802b12517", "size": 3622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/CMSSMNoFV/CMSSMNoFV_two_scale_ewsb_solver.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/CMSSMNoFV/CMSSMNoFV_two_scale_ewsb_solver.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/CMSSMNoFV/CMSSMNoFV_two_scale_ewsb_solver.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 38.1263157895, "max_line_length": 95, "alphanum_fraction": 0.7355052457, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.18136273416684703}}
{"text": "//Tencent is pleased to support the open source community by making FeatherCNN available.\n\n//Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.\n\n//Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n//in compliance with the License. You may obtain a copy of the License at\n//\n//https://opensource.org/licenses/BSD-3-Clause\n//\n//Unless required by applicable law or agreed to in writing, software distributed\n//under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n//CONDITIONS OF ANY KIND, either express or implied. See the License for the\n//specific language governing permissions and limitations under the License.\n\n\n#include <booster/depthwise.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <assert.h>\n\n//#include <arm_neon.h>\n\n#ifdef __APPLE__\n#else\n#include <omp.h>\n#endif\n\n\ntemplate <bool fuseBias, bool fuseRelu>\nvoid globalDwConv(float *output, const float *input, int input_channels, int inw, int inh, float *kernel, int group, int nThreads, float *bias_arr)\n{\n    assert(group > 0 || input_channels % group == 0);\n    int step = inw * inh;\n    int block = input_channels / group;\n    int groupKernelSize = inw * inh * group;\n\n    for (int i = 0; i < input_channels; i++)\n    {\n        int k = i / group, u = i % group;\n        output[i] = 0;\n        for (int j = 0; j < step; j++)\n        {\n            output[i] += input[i * step + j] * kernel[k * groupKernelSize + u * step + j];\n        }\n        if (fuseBias)\n        {\n            output[i] += bias_arr[i];\n        }\n        if (fuseRelu)\n        {\n            output[i] = (output[i] > 0.f) ? output[i] : 0.f;\n        }\n    }\n\n    /*\n    int kw = inw, kh = inh;\n    int width = kw * kh;\n    int widthAligned = width & 0xFFFFFFFC;\n    int widthRem = width & 0x03; // int widthRem = width & 0x11;\n    int height = group;\n    int heightAligned = group & 0xFFFFFFFC;\n    int heightRem = height & 0x03; // int heightRem = height & 0x11;\n    float ext[8];\n    for(int i = 0; i < heightAligned; i += 4)\n    {\n        float32x4_t sum = vdupq_n_f32(0.f);\n        float* p0 = const_cast<float *>(input) + width * i;\n        float* p1 = p0 + width;\n        float* p2 = p1 + width;\n        float* p3 = p2 + width;\n        float* k0 = kernel + width * i;\n        float* k1 = k0 + width;\n        float* k2 = k1 + width;\n        float* k3 = k2 + width;\n\n        for(int j = 0; j < widthAligned; j += 4)\n        {\n            float32x4_t v0 = vld1q_f32(p0);\n            p0 += 4;\n            float32x4_t v1 = vld1q_f32(p1);\n            p1 += 4;\n            float32x4_t v2 = vld1q_f32(p2);\n            p2 += 4;\n            float32x4_t v3 = vld1q_f32(p3);\n            p3 += 4;\n\n            float32x4_t r0 = vld1q_f32(k0);\n            k0 += 4;\n            float32x4_t r1 = vld1q_f32(k1);\n            k1 += 4;\n            float32x4_t r2 = vld1q_f32(k2);\n            k2 += 4;\n            float32x4_t r3 = vld1q_f32(k3);\n            k3 += 4;\n\n            float32x4x2_t row01 = vtrnq_f32(v0, v1);\n            float32x4x2_t row23 = vtrnq_f32(v2, v3);\n\n    //           * row0 = ( x00 x10 x20 x30 )\n    //           * row1 = ( x01 x11 x21 x31 )\n    //           * row2 = ( x02 x12 x22 x32 )\n    //           * row3 = ( x03 x13 x23 x33 )\n\n            v0 = vcombine_f32(vget_low_f32(row01.val[0]), vget_low_f32(row23.val[0]));\n            v1 = vcombine_f32(vget_low_f32(row01.val[1]), vget_low_f32(row23.val[1]));\n            v2 = vcombine_f32(vget_high_f32(row01.val[0]), vget_high_f32(row23.val[0]));\n            v3 = vcombine_f32(vget_high_f32(row01.val[1]), vget_high_f32(row23.val[1]));\n            row01 = vtrnq_f32(r0, r1);\n            row23 = vtrnq_f32(r2, r3);\n            r0 = vcombine_f32(vget_low_f32(row01.val[0]), vget_low_f32(row23.val[0]));\n            r1 = vcombine_f32(vget_low_f32(row01.val[1]), vget_low_f32(row23.val[1]));\n            r2 = vcombine_f32(vget_high_f32(row01.val[0]), vget_high_f32(row23.val[0]));\n            r3 = vcombine_f32(vget_high_f32(row01.val[1]), vget_high_f32(row23.val[1]));\n    #ifdef __aarch64__\n            sum = vfmaq_f32(sum, v0, r0);\n            sum = vfmaq_f32(sum, v1, r1);\n            sum = vfmaq_f32(sum, v2, r2);\n            sum = vfmaq_f32(sum, v3, r3);\n    #else\n            sum = vmlaq_f32(sum, v0, r0);\n            sum = vmlaq_f32(sum, v1, r1);\n            sum = vmlaq_f32(sum, v2, r2);\n            sum = vmlaq_f32(sum, v3, r3);\n    #endif\n        }\n        if(widthRem){\n            for(int j = 0; j < widthRem; ++j)\n            {\n                ext[0] = p0[j];\n                ext[1] = p1[j];\n                ext[2] = p2[j];\n                ext[3] = p3[j];\n                ext[4] = k0[j];\n                ext[5] = k1[j];\n                ext[6] = k2[j];\n                ext[7] = k3[j];\n    #ifdef __aarch64__\n                sum = vfmaq_f32(sum, vld1q_f32(ext + 4), vld1q_f32(ext));\n    #else\n                sum = vmlaq_f32(sum, vld1q_f32(ext + 4), vld1q_f32(ext));\n    #endif\n            }\n        }\n        vst1q_f32(output + i, sum);\n    }\n    for(int i = heightAligned; i < height; ++i)\n    {\n        float* p = const_cast<float *>(input) + i * width;\n        float* k = kernel + i * width;\n        float sum = 0.f;\n        for(int j = 0; j < width; ++j)\n        {\n            sum += p[j] * k[j];\n        }\n        output[i] = sum; // output[heightAligned + i] = sum;\n    }\n    */\n}\n\ntemplate <bool fuseBias, bool fuseRelu>\nvoid dwConv_template(float *output, float *input, int input_channels, int inw, int inh, int stridew, int strideh, float *kernel, int kw, int kh, int group, int nThreads, float *bias_arr)\n{\n    if ((kw == inw) && (kh == inh))\n    {\n        globalDwConv<fuseBias, fuseRelu>(output, input, input_channels, inw, inh, kernel, group, nThreads, bias_arr);\n    }\n    else\n    {\n        int outw = (inw - kw) / stridew + 1; //for strided case in odd dimensions, should take the floor value as output dim.\n        int outh = (inh - kh) / strideh + 1;\n\n// #pragma omp parallel for num_threads(nThreads) schedule(static)\n        //printf(\"dw param %d kernel %d %d stride %d %d input %d %d %d output %d %d\\n\", group, kh, kw, strideh, stridew, input_channels, inh, inw, outh, outw);\n        for (int g = 0; g < group; ++g)\n        {\n            float *kp = kernel + kw * kh * g;\n            float *outg = output + g * outw * outh;\n            float *ing = input + g * inw * inh;\n            for (int i = 0; i < outh; ++i)\n            {\n                for (int j = 0; j < outw; ++j)\n                {\n                    float *inp = ing + inw * (i * stridew) + (j * strideh);\n                    float convSum = 0.f;\n                    for (int m = 0; m < kh; m++)\n                    {\n                        for (int n = 0; n < kw; n++)\n                        {\n                            convSum += inp[m * inw + n] * kp[m * kw + n];\n                        }\n                    }\n                    if (fuseBias)\n                    {\n                        convSum += bias_arr[g];\n                    }\n                    if (fuseRelu)\n                    {\n                        convSum = (convSum > 0.f) ? convSum : 0.f;\n                    }\n                    outg[j] = convSum;\n                }\n                outg += outw;\n            }\n        }\n    }\n}\n\ntemplate void dwConv_template<false, false>(float *, float *, int, int, int, int, int, float *, int, int, int, int, float *);\ntemplate void dwConv_template<false,  true>(float *, float *, int, int, int, int, int, float *, int, int, int, int, float *);\ntemplate void dwConv_template<true,  false>(float *, float *, int, int, int, int, int, float *, int, int, int, int, float *);\ntemplate void dwConv_template<true,   true>(float *, float *, int, int, int, int, int, float *, int, int, int, int, float *);\n", "meta": {"hexsha": "b105dea984e0954158749ed356abf4abac8d5b09", "size": 7810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/booster/avx/depthwise.cpp", "max_stars_repo_name": "chenaili6/FeatherCNN", "max_stars_repo_head_hexsha": "52cd8c8749ed584461a88b1f04749bb35a48f9a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-14T09:00:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:11:54.000Z", "max_issues_repo_path": "src/booster/avx/depthwise.cpp", "max_issues_repo_name": "nihui/FeatherCNN", "max_issues_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "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/booster/avx/depthwise.cpp", "max_forks_repo_name": "nihui/FeatherCNN", "max_forks_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "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.6666666667, "max_line_length": 186, "alphanum_fraction": 0.5113956466, "num_tokens": 2395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.18136273045926926}}
{"text": "#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <set>\n#include <stdexcept>\n#include <utility>\n#include <boost/scoped_ptr.hpp>\n#include <opengm/inference/lpcplex.hxx>\n#include <opengm/datastructures/marray/marray.hxx>\n\n#include \"pgmlink/pgm.h\"\n#include \"pgmlink/hypotheses.h\"\n#include \"pgmlink/log.h\"\n#include \"pgmlink/pgm_chaingraph.h\"\n#include \"pgmlink/traxels.h\"\n\n//#include <ostream>\n\nusing namespace std;\n\nnamespace pgmlink {\n  namespace pgm {\n    namespace chaingraph {\n    ////\n    //// class chaingraph::Model\n    ////\n    Model::Model() : opengm_model( new OpengmModel() ) {\n      init();\n    }\n\n    Model::Model(shared_ptr<OpengmModel> m,\n\t\t\t\t     const node_var_map& node_var,\n\t\t\t\t     const arc_var_map& arc_var\n\t\t\t\t     )\n      : opengm_model(m) {\n      node_var_.left = node_var;\n      arc_var_.left = arc_var;\n      init();\n      }\n\n    const Model::node_var_map& Model::var_of_node() const {\n      return node_var_.left;\n    }\n\n    const Model::var_node_map& Model::node_of_var() const {\n      return node_var_.right;\n    }\n\n    const Model::arc_var_map& Model::var_of_arc() const {\n      return arc_var_.left;\n    }\n\n    const Model::var_arc_map& Model::arc_of_var() const\n    {\n      return arc_var_.right;      \n    }\n\n    Model::var_t Model::var_of_node(node_t e) const {\n      node_var_map::const_iterator it = var_of_node().find(e);\n      if(it!=var_of_node().end()) {\n\treturn it->second;\n      } else {\n\tthrow std::out_of_range(\"chaingraph::Model::var_of_node(): key does not exist\");\n      }\n    }\n\n    Model::var_t Model::var_of_arc(arc_t e) const {\n      arc_var_map::const_iterator it = var_of_arc().find(e);\n      if(it!=var_of_arc().end()) {\n\treturn it->second;\n      } else {\n\tthrow std::out_of_range(\"ChaingraphModel::var_of_arc(): key does not exist\");\n      }\n    }\n\n    Model::node_t Model::node_of_var(var_t e) const {\n      var_node_map::const_iterator it = node_of_var().find(e);\n      if(it!=node_of_var().end()) {\n\treturn it->second;\n      } else {\n\tthrow std::out_of_range(\"ChaingraphModel::node_of_var(): key does not exist\");\n      }\n    }\n\n    Model::arc_t Model::arc_of_var(var_t e) const {\n      var_arc_map::const_iterator it = arc_of_var().find(e);\n      if(it!=arc_of_var().end()) {\n\treturn it->second;\n      } else {\n\tthrow std::out_of_range(\"ChaingraphModel::arc_of_var(): key does not exist\");\n      }\n    }\n\n    Model::VarCategory Model::var_category(var_t e) const {\n      if(arc_of_var().count(e)) {\n\treturn Model::arc_var;\n      } else if(node_of_var().count(e)) {\n\treturn Model::node_var;\n      } else {\n\tthrow std::out_of_range(\"ChaingraphModel::var_category(): key does not exist\");\n      }\n    }\n\n\n    void Model::init() {\n      weight_map[det_weight] = vector<OpengmModel::IndexType>();\n      weight_map[mov_weight] = vector<OpengmModel::IndexType>();\n      weight_map[div_weight] = vector<OpengmModel::IndexType>();\n      weight_map[app_weight] = vector<OpengmModel::IndexType>();\n      weight_map[dis_weight] = vector<OpengmModel::IndexType>();\n      weight_map[opp_weight] = vector<OpengmModel::IndexType>();\n    }\n\n    \n    ////\n    //// class ModelBuilder\n    ////\n    ModelBuilder& ModelBuilder::appearance( function<double (const Traxel&)> f ) {\n      if(!f) {\n\tthrow invalid_argument(\"ChaingraphModelBuilder::appearance(): empty function\");\n      }\n      appearance_ = f;\n      return *this;\n    }\n\n    ModelBuilder& ModelBuilder::disappearance( function<double (const Traxel&)> f ) {\n      if(!f) {\n\tthrow invalid_argument(\"ChaingraphModelBuilder::disappearance(): empty function\");\n      }\n      disappearance_ = f;\n      return *this;\n    }\n\n    ModelBuilder& ModelBuilder::move( function<double (const Traxel&,const Traxel&)> f ) {\n      if(!f) {\n\tthrow invalid_argument(\"ChaingraphModelBuilder::move(): empty function\");\n      }\n      move_ = f;\n      return *this;\n    }\n\n    ModelBuilder& ModelBuilder::with_detection_vars( function<double (const Traxel&)> detection,\n\t\t\t\t\t\t\t\t\t function<double (const Traxel&)> non_detection) {\n      if(!(detection && non_detection)) {\n\tthrow invalid_argument(\"ChaingraphModelBuilder::with_detection_vars(): empty function\");\n      }\n\n      with_detection_vars_ = true;\n      detection_ = detection;\n      non_detection_ = non_detection;\n      return *this;\n    }\n\n    ModelBuilder& ModelBuilder::without_detection_vars() {\n      with_detection_vars_ = false;\n      detection_ = NULL;\n      non_detection_ = NULL;\n      return *this;\n    }\n\n    ModelBuilder& ModelBuilder::with_divisions( function<double (const Traxel&,const Traxel&,const Traxel&)> division) {\n      if(!division) {\n\tthrow invalid_argument(\"ChaingraphModelBuilder::division(): empty function\");\n      }\n      with_divisions_ = true;\n      division_ = division;\n      return *this;\n    }\n\n    ModelBuilder& ModelBuilder::without_divisions() {\n      with_divisions_ = false;\n      division_ = NULL;\n      return *this;\n    }\n\n      namespace {\n\tinline size_t cplex_id(size_t opengm_id) {\n\t  return 2*opengm_id + 1;\n\t}\n      }\n      void ModelBuilder::add_hard_constraints( const Model& m, const HypothesesGraph& hypotheses, OpengmLPCplex& cplex ) {\n\tLOG(logDEBUG) << \"Chaingraph::add_constraints: entered\";\n\t////\n\t//// outgoing transitions\n\t////\n\tLOG(logDEBUG) << \"Chaingraph::add_constraints: outgoing transitions\";\n\tfor(HypothesesGraph::NodeIt n(hypotheses); n!=lemon::INVALID; ++n) {\n\t  // couple detection and transitions\n\t  if(has_detection_vars()) {\n\t    for(HypothesesGraph::OutArcIt a(hypotheses, n); a!=lemon::INVALID; ++a) {\n\t      couple(m, n, a, cplex);\n\t    }\n\t  }\n\t\n\t  // couple assignments\n\t  vector<size_t> cplex_idxs;\n\t  for(HypothesesGraph::OutArcIt a(hypotheses, n); a!=lemon::INVALID; ++a) {\n\t    cplex_idxs.push_back(cplex_id(m.var_of_arc(a)));\n\t  }\n\t  if( cplex_idxs.size() > 0 ) {\n\t    vector<int> coeffs(cplex_idxs.size(), 1);\n\t    // 0 <= 1*transition + ... + 1*transition <= 2 [div] or 1 [no div]\n\t    const size_t max_on = has_divisions() ? 2 : 1;\n\t    cplex.addConstraint(cplex_idxs.begin(), cplex_idxs.end(), coeffs.begin(), 0, max_on);\n\t  }\n\t}\n      \n\t////\n\t//// incoming transitions\n\t////\n\tLOG(logDEBUG) << \"Chaingraph::add_constraints: incoming transitions\";\n\tfor(HypothesesGraph::NodeIt n(hypotheses); n!=lemon::INVALID; ++n) {\n\t  // couple detection and transitions\n\t  if(has_detection_vars()) {\n\t    for(HypothesesGraph::InArcIt a(hypotheses, n); a!=lemon::INVALID; ++a) {\n\t      couple(m, n, a, cplex);\n\t    }\n\t  }\n\t    \n\t  // couple transitions\n\t  vector<size_t> cplex_idxs;\n\t  for(HypothesesGraph::InArcIt a(hypotheses, n); a!=lemon::INVALID; ++a) {\n\t    cplex_idxs.push_back(cplex_id(m.var_of_arc(a)));\n\t  }\n\t  if(cplex_idxs.size() > 0) {\n\t    vector<int> coeffs(cplex_idxs.size(), 1);\n\t    // 0 <= 1*transition + ... + 1*transition <= 1\n\t    cplex.addConstraint(cplex_idxs.begin(), cplex_idxs.end(), coeffs.begin(), 0, 1);\n\t  }\n\t}\n      }\n\n      void ModelBuilder::fix_detections( const Model& m, const HypothesesGraph& g, OpengmLPCplex& cplex ) {\n\tif(!has_detection_vars()) {\n\t  throw std::runtime_error(\"chaingraph::ModelBuilder::fix_detections(): called without has_detection_vars()\");\n\t}\n\tfor(HypothesesGraph::NodeIt n(g); n!=lemon::INVALID; ++n) {\n\t  vector<size_t> cplex_idxs; \n\t  cplex_idxs.push_back(cplex_id(m.var_of_node(n)));\n\t  vector<int> coeffs;\n\t  coeffs.push_back(1);\n\t  // 1 <= 1*detection <= 1\n\t  cplex.addConstraint(cplex_idxs.begin(), cplex_idxs.end(), coeffs.begin() , 1, 1);\n\t}\n      }\n\n      inline void ModelBuilder::add_detection_vars( const HypothesesGraph& hypotheses, Model& m ) const {\n\tif(!has_detection_vars()) {\n\t  throw std::runtime_error(\"chaingraph::ModelBuilder::add_detection_vars(): called without has_detection_vars()\");\n\t}\n\n\tfor(HypothesesGraph::NodeIt n(hypotheses); n!=lemon::INVALID; ++n) {\n\t  m.opengm_model->addVariable(2);\n\t  m.node_var_.left.insert(Model::node_var_map::value_type(n, m.opengm_model->numberOfVariables() - 1));\n\t}\n      }\n\n      inline void ModelBuilder::add_assignment_vars( const HypothesesGraph& hypotheses, Model& m ) const {\n\tfor(HypothesesGraph::ArcIt a(hypotheses); a!=lemon::INVALID; ++a) {\n\t  m.opengm_model->addVariable(2);\n\t  m.arc_var_.left.insert(Model::arc_var_map::value_type(a, m.opengm_model->numberOfVariables() - 1));\n\t}\n      }\n\n      vector<OpengmModel::IndexType> ModelBuilder::vars_for_outgoing_factor( const HypothesesGraph& hypotheses,\n\t\t\t\t\t\t\t\t\t     const Model& m,\n\t\t\t\t\t\t\t\t\t     const HypothesesGraph::Node& n) const {\n\tvector<OpengmModel::IndexType> vi; // opengm variable indices; can be empty if there are no det vars\n\tif(has_detection_vars()) {\n\t  vi.push_back(m.var_of_node(n)); // first detection node, remaining will be assignment vars\n\t}\n\tfor(HypothesesGraph::OutArcIt a(hypotheses, n); a != lemon::INVALID; ++a) {\n\t  vi.push_back(m.var_of_arc(a));\n\t}\n\treturn vi;\n      }\n\n      vector<OpengmModel::IndexType> ModelBuilder::vars_for_incoming_factor( const HypothesesGraph& hypotheses,\n\t\t\t\t\t\t\t\t\t     const Model& m,\n\t\t\t\t\t\t\t\t\t     const HypothesesGraph::Node& n) const {\n\tvector<OpengmModel::IndexType> vi; // opengm variable indices; can be empty if there are no det vars\n\tif(has_detection_vars()) {\n\t  vi.push_back(m.var_of_node(n)); // detection var, remaining will be assignment vars\n\t}\n\tfor(HypothesesGraph::InArcIt a(hypotheses, n); a != lemon::INVALID; ++a) {\n\t  vi.push_back(m.var_of_arc(a));\n\t}\n\tstd::reverse(vi.begin(), vi.end()); // det var should be the first index to be consistent with vars_for_outgoing_factor()\n\treturn vi;\n      }\n\n      void ModelBuilder::couple(const Model& m, const HypothesesGraph::Node& n, const HypothesesGraph::Arc& a, OpengmLPCplex& cplex ) {\n\tvector<size_t> cplex_idxs; \n\tcplex_idxs.push_back(cplex_id(m.var_of_node(n)));\n\tcplex_idxs.push_back(cplex_id(m.var_of_arc(a)));\n\tvector<int> coeffs;\n\tcoeffs.push_back(1);\n\tcoeffs.push_back(-1);\n\t// 0 <= 1*detection - 1*transition <= 1\n\tcplex.addConstraint(cplex_idxs.begin(), cplex_idxs.end(), coeffs.begin() , 0, 1);\n      }\n\n\n\n    ////\n    //// class TrainableChaingraphModelBuilder\n    ////\n    TrainableModelBuilder* TrainableModelBuilder::clone() const {\n      return new TrainableModelBuilder(*this);\n    }\n\n    Model* TrainableModelBuilder::build(const HypothesesGraph& hypotheses) const {\n      //// setup the model\n      Model* model( new Model() );\n\n      // assign the weight ids to event types\n      assert(model->opengm_model->numberOfWeights() == 0);\n      model->opengm_model->increaseNumberOfWeights(3);\n      model->weight_map[Model::mov_weight].push_back(0);\n      model->weight_map[Model::app_weight].push_back(1);\n      model->weight_map[Model::dis_weight].push_back(2);\n\n      if(has_divisions()) {\n\tmodel->opengm_model->increaseNumberOfWeights(1);\n\tmodel->weight_map[Model::div_weight].push_back(3);\n      }\n      if(has_detection_vars()) {\n\tmodel->opengm_model->increaseNumberOfWeights(2);\n\tmodel->weight_map[Model::det_weight].push_back(4);\n\tmodel->weight_map[Model::opp_weight].push_back(5);\n      }\n\n      \n      if( has_detection_vars() ) {\n\tadd_detection_vars( hypotheses, *model );\n      }\n      add_assignment_vars( hypotheses, *model );\n\n      if( has_detection_vars() ) {\n      \tfor(HypothesesGraph::NodeIt n(hypotheses); n!=lemon::INVALID; ++n) {\n      \t  add_detection_factor( hypotheses, *model, n );\n      \t}\n      }\n\n      for(HypothesesGraph::NodeIt n(hypotheses); n!=lemon::INVALID; ++n) {\n      \tadd_outgoing_factor( hypotheses, *model, n );\n      \tadd_incoming_factor( hypotheses, *model, n );\n      }\n\n      return model;\n    }\n\n    void TrainableModelBuilder::add_detection_factor( const HypothesesGraph& hypotheses, Model& m, const HypothesesGraph::Node& n ) const {\n      property_map<node_traxel, HypothesesGraph::base_graph>::type& traxel_map = hypotheses.get(node_traxel());\n      std::vector<size_t> var_indices;\n      var_indices.push_back(m.var_of_node(n));\n      size_t shape[] = {2};\n\n      size_t indicate[] = {0};\n      OpengmWeightedFeature<OpengmModel::ValueType>(var_indices, shape, shape+1, indicate, non_detection()(traxel_map[n]) )\n      \t.add_as_feature_to( *(m.opengm_model), m.weight_map[Model::det_weight].front() );\n\n      indicate[0] = 1;\n      OpengmWeightedFeature<OpengmModel::ValueType>(var_indices, shape, shape+1, indicate, detection()(traxel_map[n]) )\n      \t.add_as_feature_to( *(m.opengm_model), m.weight_map[Model::det_weight].front() );\n    }\n\n    namespace {\n      std::vector<size_t> DecToBin(size_t number)\n      {\n\tif ( number == 0 ) return std::vector<size_t>(1,0);\n\tif ( number == 1 ) return std::vector<size_t>(1,1);\n\t\n\tif ( number % 2 == 0 ) {\n\t  std::vector<size_t> ret = DecToBin(number / 2);\n\t  ret.push_back(0);\n\t  return ret;\n\t}\n\telse {\n\t  std::vector<size_t> ret = DecToBin(number / 2);\n\t  ret.push_back(1);\n\t  return ret;\n\t}\n      }\n\n      int BinToDec(std::vector<size_t> number)\n      {\n\tint result = 0, pow = 1;\n\tfor ( int i = number.size() - 1; i >= 0; --i, pow <<= 1 )\n\t  result += number[i] * pow;\n\treturn result;\n      }\n    }\n\n    inline void TrainableModelBuilder::add_outgoing_factor( const HypothesesGraph& hypotheses,\n\t\t\t\t\t\t\t    Model& m, \n\t\t\t\t\t\t\t    const HypothesesGraph::Node& n) const {\n      using namespace std;\n      property_map<node_traxel, HypothesesGraph::base_graph>::type& traxel_map = hypotheses.get(node_traxel());\n\n      LOG(logDEBUG) << \"TrainableModelBuilder::add_outgoing_factor(): entered\";\n      // setup node and arc var indices\n      const vector<size_t> vi = vars_for_outgoing_factor(hypotheses, m, n); // one or zero det vars and zero or more assignment vars\n      if(vi.size() == 0) {\n\t// nothing to do here, get out!\n\t// happens in case of no det vars and no outgoing arcs\n\treturn;\n      }\n\n      // collect outgoing arcs for use in the feature functions further down\n      vector<HypothesesGraph::Arc> arcs; \n      for(HypothesesGraph::OutArcIt a(hypotheses, n); a != lemon::INVALID; ++a) {\n\tarcs.push_back(a);\n      }\n\n      // construct factor\n      const size_t table_dim = vi.size();\n      assert(table_dim > 0);\n      const std::vector<size_t> shape(table_dim, 2);\n      std::vector<size_t> coords;\n\n      std::set<size_t > entries;\n      for(size_t i = 0; i < static_cast<size_t>(std::pow(2., static_cast<int>(table_dim))); ++i) {\n\tentries.insert( entries.end(), i );\n      }\n\t\n      // opportunity configuration; only in case of detection vars\n      if(has_detection_vars()) {\n\tcoords = std::vector<size_t>(table_dim, 0); // (0,0,...,0)\n\tsize_t check = entries.erase(BinToDec(coords));\n\tassert(check == 1);\n\tOpengmWeightedFeature<OpengmModel::ValueType>(vi, shape.begin(), shape.end(), coords.begin(), opportunity_cost() )\n\t  .add_as_feature_to( *(m.opengm_model), m.weight_map[Model::opp_weight].front() );\n      }\n\n      // disappearance configuration\n      { \n\tcoords = std::vector<size_t>(table_dim, 0);\n\tif(has_detection_vars()){\n\t  coords[0] = 1; // (1,0,...,0)\n\t}\n\tsize_t check = entries.erase(BinToDec(coords));\n\tassert(check == 1);\n\tOpengmWeightedFeature<OpengmModel::ValueType>(vi, shape.begin(), shape.end(), coords.begin(), disappearance()(traxel_map[n]) )\n\t  .add_as_feature_to( *(m.opengm_model), m.weight_map[Model::dis_weight].front() );\n      }\n\n      // move configurations\n      {\n\tcoords = std::vector<size_t>(table_dim, 0);\n\tsize_t assignment_begin = 0;\n\tif(has_detection_vars()) {\n\t  coords[0] = 1;\n\t  assignment_begin = 1;\n\t}\n\t// (1  ,0,0,0,1,0,0)\n\tfor(size_t i = assignment_begin; i < table_dim; ++i) {\n\t  coords[i] = 1; \n\t  size_t check = entries.erase(BinToDec(coords));\n\t  assert(check == 1);\n\t  OpengmWeightedFeature<OpengmModel::ValueType>(vi, shape.begin(), shape.end(), coords.begin(), move()(traxel_map[n], traxel_map[hypotheses.target(arcs[i-assignment_begin])]) )\n\t    .add_as_feature_to( *(m.opengm_model), m.weight_map[Model::mov_weight].front() );\n\t  coords[i] = 0; // reset coords\n\t}\n      }\n      \n      // division configurations\n      if(has_divisions()) {\n\tcoords = std::vector<size_t>(table_dim, 0);\n\tsize_t assignment_begin = 0;\n\tif(has_detection_vars()) {\n\t  coords[0] = 1;\n\t  assignment_begin = 1;\n\t}\n\n\t// (1   ,0,0,1,0,1,0,0) \n\tfor(unsigned int i = assignment_begin; i < table_dim - 1; ++i) {\n\t  for(unsigned int j = i+1; j < table_dim; ++j) {\n\t    coords[i] = 1;\n\t    coords[j] = 1;\n\t    size_t check = entries.erase(BinToDec(coords));\n\t    assert(check == 1);\n\t    OpengmModel::ValueType value = division()(traxel_map[n],\n\t\t\t\t\t\t\ttraxel_map[hypotheses.target(arcs[i-assignment_begin])],\n\t\t\t\t\t\t\ttraxel_map[hypotheses.target(arcs[j-assignment_begin])]);\n\t    OpengmWeightedFeature<OpengmModel::ValueType>(vi, shape.begin(), shape.end(), coords.begin(), value)\n\t      .add_as_feature_to( *(m.opengm_model), m.weight_map[Model::div_weight].front() );\n\t    // reset\n\t    coords[i] = 0;\n\t    coords[j] = 0;\n\t  }\n\t}\n      }\n\n      // forbidden configurations\n      {\n\tfor(std::set<size_t>::iterator it = entries.begin(); it != entries.end(); ++it) {\n\t  coords = DecToBin(*it);\n\t  // pad with zeros up to coordinate size\n\t  if(coords.size() < table_dim ) {\n\t    coords.insert(coords.begin(), table_dim-coords.size(), 0);\n\t  }\n\t  assert( coords.size() == table_dim );\n\t  OpengmWeightedFeature<OpengmModel::ValueType>(vi, shape.begin(), shape.end(), coords.begin(), forbidden_cost())\n\t    .add_to( *(m.opengm_model) );\n\t}\n      }\n\n      LOG(logDEBUG) << \"TrainableChaingraphModelBuilder::add_outgoing_factor(): leaving\";\n    }\n\n    inline void TrainableModelBuilder::add_incoming_factor( const HypothesesGraph& hypotheses,\n\t\t\t\t\t\t\t\t      Model& m,\n\t\t\t\t\t\t\t\t      const HypothesesGraph::Node& n ) const {\n      using namespace std;\n      property_map<node_traxel, HypothesesGraph::base_graph>::type& traxel_map = hypotheses.get(node_traxel());\n\n      LOG(logDEBUG) << \"TrainableModelBuilder::add_incoming_factor(): entered\";\n      // collect and count incoming arcs\n      const vector<size_t> vi = vars_for_incoming_factor(hypotheses, m, n); // one or zero det vars and zero or more assignment vars\n      if(vi.size() == 0) {\n\t// nothing to do here, get out!\n\t// happens in case of no det vars and no incoming arcs\n\treturn;\n      }\n    \n      //// construct factor\n      const size_t table_dim = vi.size();\n      const std::vector<size_t> shape(table_dim, 2);\n      std::vector<size_t> coords;\n      \n      std::set<size_t > entries;\n      for(size_t i = 0; i < static_cast<size_t>(std::pow(2., static_cast<int>(table_dim))); ++i) {\n\tentries.insert( entries.end(), i );\n      }\n\n      // allow opportunity configuration\n      // (0,0,...,0)\n      if(has_detection_vars()) {\n\tcoords = std::vector<size_t>(table_dim, 0);\n\tsize_t check = entries.erase(BinToDec(coords));\n\tassert(check == 1);\n      }\n\n      // appearance configuration\n      coords = std::vector<size_t>(table_dim, 0);\n      if(has_detection_vars()) {\n\tcoords[0] = 1; // (1,0,...,0)\n      }\n      size_t check = entries.erase(BinToDec(coords));\n      assert(check == 1);\n      OpengmWeightedFeature<OpengmModel::ValueType>(vi, shape.begin(), shape.end(), coords.begin(), appearance()(traxel_map[n]) )\n\t.add_as_feature_to( *(m.opengm_model), m.weight_map[Model::app_weight].front() );\n\n      // allow move configurations\n      // (1,0,0,0,1,0,0)\n      coords = std::vector<size_t>(table_dim, 0);\n      size_t assignment_begin = 0;\n      if(has_detection_vars()) {\n\tcoords[0] = 1;\n\tassignment_begin = 1;\n      }\n      for(size_t i = assignment_begin; i < table_dim; ++i) {\n\tcoords[i] = 1; \n\tsize_t check = entries.erase(BinToDec(coords));\n\tassert(check == 1);\n\tcoords[i] = 0; // reset coords\n      }\n\n      // forbidden configurations\n      for(std::set<size_t>::iterator it = entries.begin(); it != entries.end(); ++it) {\n\tcoords = DecToBin(*it);\n\t// zero padding up to table dim\n\tif(coords.size() < table_dim ) {\n\t  coords.insert(coords.begin(), table_dim-coords.size(), 0);\n\t}\n\tassert( coords.size() == table_dim );\n\tOpengmWeightedFeature<OpengmModel::ValueType>(vi, shape.begin(), shape.end(), coords.begin(), forbidden_cost())\n\t  .add_to( *(m.opengm_model) );\n      }\n      \n      LOG(logDEBUG) << \"TrainableModelBuilder::add_incoming_factor(): leaving\";\n    }\n\n\n\n    ////\n    //// class ECCV12ModelBuilder\n    ////\n    ECCV12ModelBuilder* ECCV12ModelBuilder::clone() const {\n      return new ECCV12ModelBuilder(*this);\n    }\n\n    Model* ECCV12ModelBuilder::build(const HypothesesGraph& hypotheses) const {\n      using boost::shared_ptr;\n      using std::map;\n\n      LOG(logDEBUG) << \"ECCV12ModelBuilder::build: entered\";\n      if( !has_detection_vars() ) {\n\tthrow std::runtime_error(\"ECCV12ModelBuilder::build(): option without detection vars not yet implemented\");\n      }\n//      if( !has_divisions() ) {\n//\tthrow std::runtime_error(\"ECCV12ModelBuilder::build(): option without divisions not yet implemented\");\n//      }\n\n      Model* model( new Model() );\n      \n      if( has_detection_vars() ) {\n\tadd_detection_vars( hypotheses, *model );\n      }\n      add_assignment_vars( hypotheses, *model );\n\n\n      if( has_detection_vars() ) {\n\tfor(HypothesesGraph::NodeIt n(hypotheses); n!=lemon::INVALID; ++n) {\n\t  add_detection_factor( hypotheses, *model, n );\n\t}\n      }\n\n      for(HypothesesGraph::NodeIt n(hypotheses); n!=lemon::INVALID; ++n) {\n\tadd_outgoing_factor( hypotheses, *model, n );\n \tadd_incoming_factor( hypotheses, *model, n );\n      }\n\n      return model;\n    }\n\n    void ECCV12ModelBuilder::add_detection_factor( const HypothesesGraph& hypotheses, Model& m, const HypothesesGraph::Node& n) const {\n      property_map<node_traxel, HypothesesGraph::base_graph>::type& traxel_map = hypotheses.get(node_traxel());\n\n      size_t vi[] = {m.var_of_node(n)};\n      vector<size_t> coords(1,0);\n      OpengmExplicitFactor<double> table( vi, vi+1 );\n\n      coords[0] = 0;\n      table.set_value( coords, non_detection()(traxel_map[n]) ); \n\n      coords[0] = 1;\n      table.set_value( coords, detection()(traxel_map[n]) );\n\n      table.add_to( *(m.opengm_model) );\n    }\n\n    inline void ECCV12ModelBuilder::add_outgoing_factor( const HypothesesGraph& hypotheses,\n\t\t\t\t\t\t\t\t   Model& m, \n\t\t\t\t\t\t\t\t   const HypothesesGraph::Node& n\n\t\t\t\t\t\t\t\t   ) const {\n      using namespace std;\n      property_map<node_traxel, HypothesesGraph::base_graph>::type& traxel_map = hypotheses.get(node_traxel());\n\n      LOG(logDEBUG) << \"ECCV12ModelBuilder::add_outgoing_factor(): entered\";\n      // collect and count outgoing arcs\n      vector<HypothesesGraph::Arc> arcs; \n      vector<size_t> vi; \t\t// opengm variable indeces\n      vi.push_back(m.var_of_node(n)); // first detection node, remaining will be transition nodes\n      int count = 0;\n      for(HypothesesGraph::OutArcIt a(hypotheses, n); a != lemon::INVALID; ++a) {\n\tarcs.push_back(a);\n\tvi.push_back(m.var_of_arc(a));\n\t++count;\n      }\n\n      // construct factor\n      if(count == 0) {\n\t// build value table\n\tsize_t table_dim = 1; \t\t// only one detection var\n\tstd::vector<size_t> coords;\n\tOpengmExplicitFactor<double> table( vi );\n\n\t// opportunity\n\tcoords = std::vector<size_t>(table_dim, 0); \t\t// (0)\n\ttable.set_value( coords, opportunity_cost() );\n\n\t// disappearance \n\tcoords = std::vector<size_t>(table_dim, 0);\n\tcoords[0] = 1; \t\t\t\t\t\t// (1)\n\ttable.set_value( coords, disappearance()(traxel_map[n]) );\n\n\ttable.add_to( *m.opengm_model );\n\n      } else if(count == 1) {\n\t// no division possible\n\tsize_t table_dim = 2; \t\t// detection var + 1 * transition var\n\tstd::vector<size_t> coords;\n\tOpengmExplicitFactor<double> table( vi, forbidden_cost() );\n\n\t// opportunity configuration\n\tcoords = std::vector<size_t>(table_dim, 0); // (0,0)\n\ttable.set_value( coords, opportunity_cost() );\n\n\t// disappearance configuration\n\tcoords = std::vector<size_t>(table_dim, 0);\n\tcoords[0] = 1; // (1,0)\n\ttable.set_value( coords, disappearance()(traxel_map[n]) );\n\n\t// move configurations\n\tcoords = std::vector<size_t>(table_dim, 1);\n\t// (1,1)\n\ttable.set_value( coords, move()(traxel_map[n], traxel_map[hypotheses.target(arcs[0])]) );\n\n\ttable.add_to( *m.opengm_model );\n\n      } else {\n\t// build value table\n\tsize_t table_dim = count + 1; \t\t// detection var + n * transition var\n\tstd::vector<size_t> coords;\n\tOpengmExplicitFactor<double> table( vi, forbidden_cost() );\n\n\t// opportunity configuration\n\tcoords = std::vector<size_t>(table_dim, 0); // (0,0,...,0)\n\ttable.set_value( coords, opportunity_cost() );\n\n\t// disappearance configuration\n\tcoords = std::vector<size_t>(table_dim, 0);\n\tcoords[0] = 1; // (1,0,...,0)\n\ttable.set_value( coords, disappearance()(traxel_map[n]) );\n\n\t// move configurations\n\tcoords = std::vector<size_t>(table_dim, 0);\n\tcoords[0] = 1;\n\t// (1,0,0,0,1,0,0)\n\tfor(size_t i = 1; i < table_dim; ++i) {\n\t  coords[i] = 1; \n\t  table.set_value( coords, move()(traxel_map[n], traxel_map[hypotheses.target(arcs[i-1])]) );\n\t  coords[i] = 0; // reset coords\n\t}\n      \n\t// division configurations\n\tif (has_divisions()) {\n\t\tcoords = std::vector<size_t>(table_dim, 0);\n\t\tcoords[0] = 1;\n\t\t// (1,0,0,1,0,1,0,0)\n\t\tfor(unsigned int i = 1; i < table_dim - 1; ++i) {\n\t\t  for(unsigned int j = i+1; j < table_dim; ++j) {\n\t\t\tcoords[i] = 1;\n\t\t\tcoords[j] = 1;\n\t\t\ttable.set_value(coords, division()(traxel_map[n],\n\t\t\t\t\t\t\t  traxel_map[hypotheses.target(arcs[i-1])],\n\t\t\t\t\t\t\t  traxel_map[hypotheses.target(arcs[j-1])]\n\t\t\t\t\t\t\t  ));\n\n\t\t\t// reset\n\t\t\tcoords[i] = 0;\n\t\t\tcoords[j] = 0;\n\t\t  }\n\t\t}\n\t}\n\n\ttable.add_to( *m.opengm_model );      \n\n      }   \n      LOG(logDEBUG) << \"ChaingraphECCV12ModelBuilder::add_outgoing_factor(): leaving\";\n    }\n\n    inline void ECCV12ModelBuilder::add_incoming_factor( const HypothesesGraph& hypotheses,\n\t\t\t\t\t\t\t\t   Model& m,\n\t\t\t\t\t\t\t\t   const HypothesesGraph::Node& n) const {\n      using namespace std;\n      property_map<node_traxel, HypothesesGraph::base_graph>::type& traxel_map = hypotheses.get(node_traxel());\n\n      LOG(logDEBUG) << \"ECCV12ModelBuilder::add_incoming_factor(): entered\";\n      // collect and count incoming arcs\n      vector<size_t> vi; // opengm variable indeces\n      int count = 0;\n      for(HypothesesGraph::InArcIt a(hypotheses, n); a != lemon::INVALID; ++a) {\n\tvi.push_back(m.var_of_arc(a));\n\t++count;\n      }\n      vi.push_back(m.var_of_node(n)); \n      std::reverse(vi.begin(), vi.end());\n    \n      //// construct factor\n      // build value table\n      size_t table_dim = count + 1; // detection var + n * transition var\n      OpengmExplicitFactor<double> table( vi, forbidden_cost() );\n      std::vector<size_t> coords;\n\n      // allow opportunity configuration\n      // (0,0,...,0)\n      coords = std::vector<size_t>(table_dim, 0);\n      table.set_value( coords, 0 );\n\n      // appearance configuration\n      coords = std::vector<size_t>(table_dim, 0);\n      coords[0] = 1; // (1,0,...,0)\n      table.set_value( coords, appearance()(traxel_map[n]) );\n      assert(table.get_value( coords ) == appearance()(traxel_map[n]));\n\n      // allow move configurations\n      coords = std::vector<size_t>(table_dim, 0);\n      coords[0] = 1;\n      // (1,0,0,0,1,0,0)\n      for(size_t i = 1; i < table_dim; ++i) {\n\tcoords[i] = 1; \n\ttable.set_value( coords, 0 );\n\tcoords[i] = 0; // reset coords\n      }\n\n      table.add_to( *m.opengm_model );\n      LOG(logDEBUG) << \"ECCV12ModelBuilder::add_incoming_factor(): leaving\";\n    }\n\n    } /* namespace chaingraph */\n  } /* namespace pgm */\n} /* namespace pgmlink */ \n", "meta": {"hexsha": "0ad8a64f77c8402cffc4794cff1b2fb27c4cdf7a", "size": 27129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pgm_chaingraph.cpp", "max_stars_repo_name": "chaubold/pgmlink", "max_stars_repo_head_hexsha": "9dfa90dbd2fdeb026fd0b2837155164c17cb848d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-08-06T08:26:07.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-06T01:11:30.000Z", "max_issues_repo_path": "src/pgm_chaingraph.cpp", "max_issues_repo_name": "chaubold/pgmlink", "max_issues_repo_head_hexsha": "9dfa90dbd2fdeb026fd0b2837155164c17cb848d", "max_issues_repo_licenses": ["MIT"], "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/pgm_chaingraph.cpp", "max_forks_repo_name": "chaubold/pgmlink", "max_forks_repo_head_hexsha": "9dfa90dbd2fdeb026fd0b2837155164c17cb848d", "max_forks_repo_licenses": ["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.658808933, "max_line_length": 177, "alphanum_fraction": 0.6474989863, "num_tokens": 7594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.18136272589196828}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Point Cloud Library (PCL) - www.pointclouds.org\n *  Copyright (c) 2011, Willow Garage, Inc.\n *\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 <pcl/gpu/kinfu_large_scale/tsdf_volume.h>\n#include \"internal.h\"\n#include <algorithm>\n#include <Eigen/Core>\n\n#include <iostream>\n\nusing namespace pcl;\nusing namespace pcl::gpu;\nusing namespace Eigen;\nusing pcl::device::kinfuLS::device_cast;\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\npcl::gpu::kinfuLS::TsdfVolume::TsdfVolume(const Vector3i& resolution) : resolution_(resolution), volume_host_ (new std::vector<float>), weights_host_ (new std::vector<short>)\n{\n  int volume_x = resolution_(0);\n  int volume_y = resolution_(1);\n  int volume_z = resolution_(2);\n\n  volume_.create (volume_y * volume_z, volume_x);\n  \n  const Vector3f default_volume_size = Vector3f::Constant (3.f); //meters\n  const float    default_tranc_dist  = 0.03f; //meters\n\n  setSize(default_volume_size);\n  setTsdfTruncDist(default_tranc_dist);\n\n  reset();\n  \n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::setSize(const Vector3f& size)\n{  \n  size_ = size;\n  setTsdfTruncDist(tranc_dist_);\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::setTsdfTruncDist (float distance)\n{\n  float cx = size_(0) / resolution_(0);\n  float cy = size_(1) / resolution_(1);\n  float cz = size_(2) / resolution_(2);\n\n  tranc_dist_ = std::max (distance, 2.1f * std::max (cx, std::max (cy, cz)));  \n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\npcl::gpu::DeviceArray2D<int> \npcl::gpu::kinfuLS::TsdfVolume::data() const\n{\n  return volume_;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst Eigen::Vector3f&\npcl::gpu::kinfuLS::TsdfVolume::getSize() const\n{\n    return size_;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst Eigen::Vector3i&\npcl::gpu::kinfuLS::TsdfVolume::getResolution() const\n{\n  return resolution_;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst Eigen::Vector3f\npcl::gpu::kinfuLS::TsdfVolume::getVoxelSize() const\n{    \n  return size_.array () / resolution_.array().cast<float>();\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfloat\npcl::gpu::kinfuLS::TsdfVolume::getTsdfTruncDist () const\n{\n  return tranc_dist_;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid \npcl::gpu::kinfuLS::TsdfVolume::reset()\n{\n  pcl::device::kinfuLS::initVolume(volume_);\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::fetchCloudHost (PointCloud<PointXYZI>& cloud, bool connected26) const\n{\n  PointCloud<PointXYZ>::Ptr cloud_ptr_ = PointCloud<PointXYZ>::Ptr (new PointCloud<PointXYZ>);\n  PointCloud<PointIntensity>::Ptr cloud_i_ptr_ = PointCloud<PointIntensity>::Ptr (new PointCloud<PointIntensity>);\n  fetchCloudHost(*cloud_ptr_);\n  pcl::concatenateFields (*cloud_ptr_, *cloud_i_ptr_, cloud);\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::fetchCloudHost (PointCloud<PointType>& cloud, bool connected26) const\n{\n  int volume_x = resolution_(0);\n  int volume_y = resolution_(1);\n  int volume_z = resolution_(2);\n\n  int cols;\n  std::vector<int> volume_host;\n  volume_.download (volume_host, cols);\n\n  cloud.points.clear ();\n  cloud.points.reserve (10000);\n\n  const int DIVISOR = pcl::device::kinfuLS::DIVISOR; // SHRT_MAX;\n\n#define FETCH(x, y, z) volume_host[(x) + (y) * volume_x + (z) * volume_y * volume_x]\n\n  Array3f cell_size = getVoxelSize();\n\n  for (int x = 1; x < volume_x-1; ++x)\n  {\n    for (int y = 1; y < volume_y-1; ++y)\n    {\n      for (int z = 0; z < volume_z-1; ++z)\n      {\n        int tmp = FETCH (x, y, z);\n        int W = reinterpret_cast<short2*>(&tmp)->y;\n        int F = reinterpret_cast<short2*>(&tmp)->x;\n\n        if (W == 0 || F == DIVISOR)\n          continue;\n\n        Vector3f V = ((Array3f(x, y, z) + 0.5f) * cell_size).matrix ();\n\n        if (connected26)\n        {\n          int dz = 1;\n          for (int dy = -1; dy < 2; ++dy)\n            for (int dx = -1; dx < 2; ++dx)\n            {\n              int tmp = FETCH (x+dx, y+dy, z+dz);\n\n              int Wn = reinterpret_cast<short2*>(&tmp)->y;\n              int Fn = reinterpret_cast<short2*>(&tmp)->x;\n              if (Wn == 0 || Fn == DIVISOR)\n                continue;\n\n              if ((F > 0 && Fn < 0) || (F < 0 && Fn > 0))\n              {\n                Vector3f Vn = ((Array3f (x+dx, y+dy, z+dz) + 0.5f) * cell_size).matrix ();\n                Vector3f point = (V * abs (Fn) + Vn * abs (F)) / (abs (F) + abs (Fn));\n\n                pcl::PointXYZ xyz;\n                xyz.x = point (0);\n                xyz.y = point (1);\n                xyz.z = point (2);\n\n                cloud.points.push_back (xyz);\n              }\n            }\n          dz = 0;\n          for (int dy = 0; dy < 2; ++dy)\n            for (int dx = -1; dx < dy * 2; ++dx)\n            {\n              int tmp = FETCH (x+dx, y+dy, z+dz);\n\n              int Wn = reinterpret_cast<short2*>(&tmp)->y;\n              int Fn = reinterpret_cast<short2*>(&tmp)->x;\n              if (Wn == 0 || Fn == DIVISOR)\n                continue;\n\n              if ((F > 0 && Fn < 0) || (F < 0 && Fn > 0))\n              {\n                Vector3f Vn = ((Array3f (x+dx, y+dy, z+dz) + 0.5f) * cell_size).matrix ();\n                Vector3f point = (V * abs(Fn) + Vn * abs(F))/(abs(F) + abs (Fn));\n\n                pcl::PointXYZ xyz;\n                xyz.x = point (0);\n                xyz.y = point (1);\n                xyz.z = point (2);\n\n                cloud.points.push_back (xyz);\n              }\n            }\n        }\n        else /* if (connected26) */\n        {\n          for (int i = 0; i < 3; ++i)\n          {\n            int ds[] = {0, 0, 0};\n            ds[i] = 1;\n\n            int dx = ds[0];\n            int dy = ds[1];\n            int dz = ds[2];\n\n            int tmp = FETCH (x+dx, y+dy, z+dz);\n\n            int Wn = reinterpret_cast<short2*>(&tmp)->y;\n            int Fn = reinterpret_cast<short2*>(&tmp)->x;\n            if (Wn == 0 || Fn == DIVISOR)\n              continue;\n\n            if ((F > 0 && Fn < 0) || (F < 0 && Fn > 0))\n            {\n              Vector3f Vn = ((Array3f (x+dx, y+dy, z+dz) + 0.5f) * cell_size).matrix ();\n              Vector3f point = (V * abs (Fn) + Vn * abs (F)) / (abs (F) + abs (Fn));\n\n              pcl::PointXYZ xyz;\n              xyz.x = point (0);\n              xyz.y = point (1);\n              xyz.z = point (2);\n\n              cloud.points.push_back (xyz);\n            }\n          }\n        } /* if (connected26) */\n      }\n    }\n  }\n#undef FETCH\n  cloud.width  = (int)cloud.points.size ();\n  cloud.height = 1;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\npcl::gpu::DeviceArray<pcl::gpu::kinfuLS::TsdfVolume::PointType>\npcl::gpu::kinfuLS::TsdfVolume::fetchCloud (DeviceArray<PointType>& cloud_buffer) const\n{\n  if (cloud_buffer.empty ())\n    cloud_buffer.create (DEFAULT_CLOUD_BUFFER_SIZE);\n\n  float3 device_volume_size = device_cast<const float3> (size_);\n  size_t size = pcl::device::kinfuLS::extractCloud (volume_, device_volume_size, cloud_buffer);\n  return (DeviceArray<PointType> (cloud_buffer.ptr (), size));\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::fetchNormals (const DeviceArray<PointType>& cloud, DeviceArray<PointType>& normals) const\n{\n  normals.create (cloud.size ());\n  const float3 device_volume_size = device_cast<const float3> (size_);\n  pcl::device::kinfuLS::extractNormals (volume_, device_volume_size, cloud, (pcl::device::kinfuLS::PointType*)normals.ptr ());\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid \npcl::gpu::kinfuLS::TsdfVolume::pushSlice (PointCloud<PointXYZI>::Ptr existing_data_cloud, const pcl::gpu::kinfuLS::tsdf_buffer* buffer) const\n{\n  size_t gpu_array_size = existing_data_cloud->points.size ();\n\n  if(gpu_array_size == 0)\n  {\n    //std::cout << \"[KinfuTracker](pushSlice) Existing data cloud has no points\\n\";//CREATE AS PCL MESSAGE\n    return;\n  }\n\n  const pcl::PointXYZI *first_point_ptr = &(existing_data_cloud->points[0]);\n\n  pcl::gpu::DeviceArray<pcl::PointXYZI> cloud_gpu;\n  cloud_gpu.upload (first_point_ptr, gpu_array_size);\n\n  DeviceArray<float4>& cloud_cast = (DeviceArray<float4>&) cloud_gpu;\n  //volume().pushCloudAsSlice (cloud_cast, &buffer_);\n  pcl::device::kinfuLS::pushCloudAsSliceGPU (volume_, cloud_cast, buffer);\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nsize_t\npcl::gpu::kinfuLS::TsdfVolume::fetchSliceAsCloud (DeviceArray<PointType>& cloud_buffer_xyz, DeviceArray<float>& cloud_buffer_intensity, const pcl::gpu::kinfuLS::tsdf_buffer* buffer, int shiftX, int shiftY, int shiftZ ) const\n{\n  if (cloud_buffer_xyz.empty ())\n    cloud_buffer_xyz.create (DEFAULT_CLOUD_BUFFER_SIZE/2);\n\n  if (cloud_buffer_intensity.empty ()) {\n    cloud_buffer_intensity.create (DEFAULT_CLOUD_BUFFER_SIZE/2);  \n  }\n\n  float3 device_volume_size = device_cast<const float3> (size_);\n  \n  size_t size = pcl::device::kinfuLS::extractSliceAsCloud (volume_, device_volume_size, buffer, shiftX, shiftY, shiftZ, cloud_buffer_xyz, cloud_buffer_intensity);\n  \n  std::cout << \" SIZE IS \" << size << std::endl;\n  \n  return (size);\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::fetchNormals (const DeviceArray<PointType>& cloud, DeviceArray<NormalType>& normals) const\n{\n  normals.create (cloud.size ());\n  const float3 device_volume_size = device_cast<const float3> (size_);\n  pcl::device::kinfuLS::extractNormals (volume_, device_volume_size, cloud, (pcl::device::kinfuLS::float8*)normals.ptr ());\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::convertToTsdfCloud ( pcl::PointCloud<pcl::PointXYZI>::Ptr &cloud,\n                                                    const unsigned step) const\n{\n  int sx = header_.resolution(0);\n  int sy = header_.resolution(1);\n  int sz = header_.resolution(2);\n\n  const int cloud_size = static_cast<int> (header_.getVolumeSize() / (step*step*step));\n\n  cloud->clear();\n  cloud->reserve (std::min (cloud_size/10, 500000));\n\n  int volume_idx = 0, cloud_idx = 0;\n  // #pragma omp parallel for // if used, increment over idx not possible! use index calculation\n  for (int z = 0; z < sz; z+=step)\n    for (int y = 0; y < sy; y+=step)\n      for (int x = 0; x < sx; x+=step, ++cloud_idx)\n      {\n        volume_idx = sx*sy*z + sx*y + x;\n        // pcl::PointXYZI &point = cloud->points[cloud_idx];\n\n        if (weights_host_->at(volume_idx) == 0 || volume_host_->at(volume_idx) > 0.98 )\n          continue;\n\n        pcl::PointXYZI point;\n        point.x = x; point.y = y; point.z = z;//*64;\n        point.intensity = volume_host_->at(volume_idx);\n        cloud->push_back (point);\n      }\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::downloadTsdf (std::vector<float>& tsdf) const\n{\n  tsdf.resize (volume_.cols() * volume_.rows());\n  volume_.download(&tsdf[0], volume_.cols() * sizeof(int));\n\n#pragma omp parallel for\n  for(int i = 0; i < (int) tsdf.size(); ++i)\n  {\n    float tmp = reinterpret_cast<short2*>(&tsdf[i])->x;\n    tsdf[i] = tmp/pcl::device::kinfuLS::DIVISOR;\n  }\n}\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::downloadTsdfLocal () const\n{\n  pcl::gpu::kinfuLS::TsdfVolume::downloadTsdf (*volume_host_);\n}\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::downloadTsdfAndWeights (std::vector<float>& tsdf, std::vector<short>& weights) const\n{\n  int volumeSize = volume_.cols() * volume_.rows();\n  tsdf.resize (volumeSize);\n  weights.resize (volumeSize);\n  volume_.download(&tsdf[0], volume_.cols() * sizeof(int));\n  \n  #pragma omp parallel for\n  for(int i = 0; i < (int) tsdf.size(); ++i)\n  {\n    short2 elem = *reinterpret_cast<short2*>(&tsdf[i]);\n    tsdf[i] = (float)(elem.x)/pcl::device::kinfuLS::DIVISOR;    \n    weights[i] = (short)(elem.y);    \n  }\n}\n\n\nvoid\npcl::gpu::kinfuLS::TsdfVolume::downloadTsdfAndWeightsLocal () const\n{\n  pcl::gpu::kinfuLS::TsdfVolume::downloadTsdfAndWeights (*volume_host_, *weights_host_);\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nbool\npcl::gpu::kinfuLS::TsdfVolume::save (const std::string &filename, bool binary) const\n{\n  pcl::console::print_info (\"Saving TSDF volume to \"); pcl::console::print_value (\"%s ... \", filename.c_str());\n  std::cout << std::flush;\n\n  std::ofstream file (filename.c_str(), binary ? std::ios_base::binary : std::ios_base::out);\n\n  if (file.is_open())\n  {\n    if (binary)\n    {\n      // HEADER\n      // write resolution and size of volume\n      file.write ((char*) &header_, sizeof (Header));\n      /* file.write ((char*) &header_.resolution, sizeof(Eigen::Vector3i));\n      file.write ((char*) &header_.volume_size, sizeof(Eigen::Vector3f));\n      // write  element size\n      int volume_element_size = sizeof(VolumeT);\n      file.write ((char*) &volume_element_size, sizeof(int));\n      int weights_element_size = sizeof(WeightT);\n      file.write ((char*) &weights_element_size, sizeof(int)); */\n\n      // DATA\n      // write data\n      file.write ((char*) &(volume_host_->at(0)), volume_host_->size()*sizeof(float));\n      file.write ((char*) &(weights_host_->at(0)), weights_host_->size()*sizeof(short));\n    }\n    else\n    {\n      // write resolution and size of volume and element size\n      file << header_.resolution(0) << \" \" << header_.resolution(1) << \" \" << header_.resolution(2) << std::endl;\n      file << header_.volume_size(0) << \" \" << header_.volume_size(1) << \" \" << header_.volume_size(2) << std::endl;\n      file << sizeof (float) << \" \" << sizeof(short) << std::endl;\n\n      // write data\n      for (std::vector<float>::const_iterator iter = volume_host_->begin(); iter != volume_host_->end(); ++iter)\n        file << *iter << std::endl;\n    }\n\n    file.close();\n  }\n  else\n  {\n    pcl::console::print_error (\"[saveTsdfVolume] Error: Couldn't open file %s.\\n\", filename.c_str());\n    return false;\n  }\n\n  pcl::console::print_info (\"done [%d voxels]\\n\", this->size ());\n\n  return true;\n}\n\n\nbool\npcl::gpu::kinfuLS::TsdfVolume::load (const std::string &filename, bool binary)\n{\n  pcl::console::print_info (\"Loading TSDF volume from \"); pcl::console::print_value (\"%s ... \", filename.c_str());\n  std::cout << std::flush;\n\n  std::ifstream file (filename.c_str());\n\n  if (file.is_open())\n  {\n    if (binary)\n    {\n      // read HEADER\n      file.read ((char*) &header_, sizeof (Header));\n      /* file.read (&header_.resolution, sizeof(Eigen::Array3i));\n      file.read (&header_.volume_size, sizeof(Eigen::Vector3f));\n      file.read (&header_.volume_element_size, sizeof(int));\n      file.read (&header_.weights_element_size, sizeof(int)); */\n\n      // check if element size fits to data\n      if (header_.volume_element_size != sizeof(float))\n      {\n        pcl::console::print_error (\"[TSDFVolume::load] Error: Given volume element size (%d) doesn't fit data (%d)\", sizeof(float), header_.volume_element_size);\n        return false;\n      }\n      if ( header_.weights_element_size != sizeof(short))\n      {\n        pcl::console::print_error (\"[TSDFVolume::load] Error: Given weights element size (%d) doesn't fit data (%d)\", sizeof(short), header_.weights_element_size);\n        return false;\n      }\n\n      // read DATA\n      int num_elements = header_.getVolumeSize();\n      volume_host_->resize (num_elements);\n      weights_host_->resize (num_elements);\n      file.read ((char*) &(*volume_host_)[0], num_elements * sizeof(float));\n      file.read ((char*) &(*weights_host_)[0], num_elements * sizeof(short));\n    }\n    else\n    {\n      pcl::console::print_error (\"[TSDFVolume::load] Error: ASCII loading not implemented.\\n\");\n    }\n\n    file.close ();\n  }\n  else\n  {\n    pcl::console::print_error (\"[TSDFVolume::load] Error: Cloudn't read file %s.\\n\", filename.c_str());\n    return false;\n  }\n\n  const Eigen::Vector3i &res = this->gridResolution();\n  pcl::console::print_info (\"done [%d voxels, res %dx%dx%d]\\n\", this->size(), res[0], res[1], res[2]);\n\n  return true;\n}\n", "meta": {"hexsha": "73e25120e00650398948c9112405d1a9031874a4", "size": 18914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dockerfiles/gaas_tutorial_2/GAAS/software/SLAM/ygz_slam_ros/Thirdparty/PCL/gpu/kinfu_large_scale/src/tsdf_volume.cpp", "max_stars_repo_name": "hddxds/scripts_from_gi", "max_stars_repo_head_hexsha": "afb8977c001b860335f9062464e600d9115ea56e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-10T14:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-29T03:41:58.000Z", "max_issues_repo_path": "software/SLAM/ygz_slam_ros/Thirdparty/PCL/gpu/kinfu_large_scale/src/tsdf_volume.cpp", "max_issues_repo_name": "glider54321/GAAS", "max_issues_repo_head_hexsha": "5c3b8c684e72fdf7f62c5731a260021e741069e7", "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": "software/SLAM/ygz_slam_ros/Thirdparty/PCL/gpu/kinfu_large_scale/src/tsdf_volume.cpp", "max_forks_repo_name": "glider54321/GAAS", "max_forks_repo_head_hexsha": "5c3b8c684e72fdf7f62c5731a260021e741069e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-20T06:54:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T06:54:41.000Z", "avg_line_length": 34.4517304189, "max_line_length": 224, "alphanum_fraction": 0.5465792535, "num_tokens": 4674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.1811285886329533}}
{"text": "/*    Copyright (c) 2010-2018, 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#define BOOST_TEST_MAIN\n\n#include <string>\n#include <thread>\n\n#include <limits>\n\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/SimulationSetup/tudatEstimationHeader.h\"\n#include \"Tudat/Astrodynamics/OrbitDetermination/EstimatableParameters/directTidalTimeLag.h\"\n\n\nnamespace tudat\n{\nnamespace unit_tests\n{\nBOOST_AUTO_TEST_SUITE( test_arcwise_environment )\n\n//Using declarations.\nusing namespace tudat::observation_models;\nusing namespace tudat::orbit_determination;\nusing namespace tudat::estimatable_parameters;\nusing namespace tudat::interpolators;\nusing namespace tudat::numerical_integrators;\nusing namespace tudat::spice_interface;\nusing namespace tudat::simulation_setup;\nusing namespace tudat::orbital_element_conversions;\nusing namespace tudat::ephemerides;\nusing namespace tudat::propagators;\nusing namespace tudat::basic_astrodynamics;\nusing namespace tudat::coordinate_conversions;\nusing namespace tudat::ground_stations;\nusing namespace tudat::observation_models;\n\n\n//! Unit test to check if tidal time lag parameters are estimated correctly\nBOOST_AUTO_TEST_CASE( test_ArcwiseEnvironmentParameters )\n{\n    //Load spice kernels.\n    spice_interface::loadStandardSpiceKernels( );\n\n    // Define bodies in simulation\n    std::vector< std::string > bodyNames;\n    bodyNames.push_back( \"Earth\" );\n    bodyNames.push_back( \"Sun\" );\n\n    // Specify initial time\n    double initialEphemerisTime = double( 1.0E7 );\n    double finalEphemerisTime = initialEphemerisTime + 1.0 * 86400.0;\n\n    // Create bodies needed in simulation\n    std::map< std::string, std::shared_ptr< BodySettings > > bodySettings =\n            getDefaultBodySettings( bodyNames );\n\n    NamedBodyMap bodyMap = createBodies( bodySettings );\n    bodyMap[ \"Vehicle\" ] = std::make_shared< Body >( );\n    bodyMap[ \"Vehicle\" ]->setConstantBodyMass( 400.0 );\n\n    // Create aerodynamic coefficient interface settings.\n    double referenceArea = 4.0;\n    double aerodynamicCoefficient = 1.2;\n    std::shared_ptr< AerodynamicCoefficientSettings > aerodynamicCoefficientSettings =\n            std::make_shared< ConstantAerodynamicCoefficientSettings >(\n                referenceArea, aerodynamicCoefficient * ( Eigen::Vector3d( ) << 1.2, -0.01, 0.1 ).finished( ), 1, 1 );\n\n    // Create and set aerodynamic coefficients object\n    bodyMap[ \"Vehicle\" ]->setAerodynamicCoefficientInterface(\n                createAerodynamicCoefficientInterface( aerodynamicCoefficientSettings, \"Vehicle\" ) );\n\n    // Create radiation pressure settings\n    double referenceAreaRadiation = 4.0;\n    double radiationPressureCoefficient = 1.2;\n    std::vector< std::string > occultingBodies;\n    occultingBodies.push_back( \"Earth\" );\n    std::shared_ptr< RadiationPressureInterfaceSettings > asterixRadiationPressureSettings =\n            std::make_shared< CannonBallRadiationPressureInterfaceSettings >(\n                \"Sun\", referenceAreaRadiation, radiationPressureCoefficient, occultingBodies );\n\n    // Create and set radiation pressure settings\n    bodyMap[ \"Vehicle\" ]->setRadiationPressureInterface(\n                \"Sun\", createRadiationPressureInterface(\n                    asterixRadiationPressureSettings, \"Vehicle\", bodyMap ) );\n\n    bodyMap[ \"Vehicle\" ]->setEphemeris( std::make_shared< TabulatedCartesianEphemeris< > >(\n                                            std::shared_ptr< interpolators::OneDimensionalInterpolator\n                                            < double, Eigen::Vector6d > >( ), \"Earth\", \"ECLIPJ2000\" ) );\n\n    setGlobalFrameBodyEphemerides( bodyMap, \"SSB\", \"ECLIPJ2000\" );\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ///////////////////////            CREATE ACCELERATIONS          //////////////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Set accelerations on Vehicle that are to be taken into account.\n    SelectedAccelerationMap accelerationMap;\n    std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfVehicle;\n    accelerationsOfVehicle[ \"Earth\" ].push_back( std::make_shared< AccelerationSettings >(\n                                                     basic_astrodynamics::central_gravity ) );\n    accelerationsOfVehicle[ \"Sun\" ].push_back( std::make_shared< AccelerationSettings >(\n                                                   basic_astrodynamics::cannon_ball_radiation_pressure ) );\n    accelerationsOfVehicle[ \"Earth\" ].push_back( std::make_shared< AccelerationSettings >(\n                                                     basic_astrodynamics::aerodynamic ) );\n    accelerationMap[ \"Vehicle\" ] = accelerationsOfVehicle;\n\n    // Set bodies for which initial state is to be estimated and integrated.\n    std::vector< std::string > bodiesToIntegrate;\n    std::vector< std::string > centralBodies;\n    bodiesToIntegrate.push_back( \"Vehicle\" );\n    centralBodies.push_back( \"Earth\" );\n\n    // Create acceleration models\n    AccelerationMap accelerationModelMap = createAccelerationModelsMap(\n                bodyMap, accelerationMap, bodiesToIntegrate, centralBodies );\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ///////////////////////             CREATE PROPAGATION SETTINGS            ////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Set Keplerian elements for Asterix.\n    Eigen::Vector6d asterixInitialStateInKeplerianElements;\n    asterixInitialStateInKeplerianElements( semiMajorAxisIndex ) = 7200.0E3;\n    asterixInitialStateInKeplerianElements( eccentricityIndex ) = 0.05;\n    asterixInitialStateInKeplerianElements( inclinationIndex ) = unit_conversions::convertDegreesToRadians( 85.3 );\n    asterixInitialStateInKeplerianElements( argumentOfPeriapsisIndex ) = unit_conversions::convertDegreesToRadians( 235.7 );\n    asterixInitialStateInKeplerianElements( longitudeOfAscendingNodeIndex ) = unit_conversions::convertDegreesToRadians( 23.4 );\n    asterixInitialStateInKeplerianElements( trueAnomalyIndex ) = unit_conversions::convertDegreesToRadians( 139.87 );\n\n    double earthGravitationalParameter = bodyMap.at( \"Earth\" )->getGravityFieldModel( )->getGravitationalParameter( );\n\n    // Set (perturbed) initial state.\n    Eigen::Matrix< double, 6, 1 > systemInitialState = convertKeplerianToCartesianElements(\n                asterixInitialStateInKeplerianElements, earthGravitationalParameter );\n\n    // Create propagator settings\n    std::shared_ptr< DependentVariableSaveSettings > dependentVariableSaveSettings;\n    std::vector< std::shared_ptr< SingleDependentVariableSaveSettings > > dependentVariables;\n    dependentVariables.push_back(\n                std::make_shared< SingleDependentVariableSaveSettings >(\n                    aerodynamic_force_coefficients_dependent_variable, \"Vehicle\", \"Earth\" ) );\n    dependentVariables.push_back(\n                std::make_shared< SingleDependentVariableSaveSettings >(\n                    radiation_pressure_coefficient_dependent_variable, \"Vehicle\", \"Sun\" ) );\n    dependentVariableSaveSettings = std::make_shared< DependentVariableSaveSettings >( dependentVariables );\n\n    std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings =\n            std::make_shared< TranslationalStatePropagatorSettings< double > >(\n                centralBodies, accelerationModelMap, bodiesToIntegrate, systemInitialState, double( finalEphemerisTime ),\n                cowell, dependentVariableSaveSettings);\n\n    // Create integrator settings\n    std::shared_ptr< IntegratorSettings< double > > integratorSettings =\n            std::make_shared< RungeKuttaVariableStepSizeSettingsScalarTolerances< double > >(\n                double( initialEphemerisTime ), 90.0,\n                RungeKuttaCoefficients::CoefficientSets::rungeKuttaFehlberg78,\n                90.0, 90.0, 1.0, 1.0 );\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ///////////////////////             CREATE OBSERVATION SETTINGS            ////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    LinkEnds linkEnds;\n    linkEnds[ observed_body ] = std::make_pair( \"Vehicle\", \"\" );\n    observation_models::ObservationSettingsMap observationSettingsMap;\n    observationSettingsMap.insert(\n                std::make_pair( linkEnds, std::make_shared< ObservationSettings >( position_observable ) ) );\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ///////////////////////    DEFINE PARAMETERS THAT ARE TO BE ESTIMATED      ////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Define list of parameters to estimate.\n    std::vector< std::shared_ptr< EstimatableParameterSettings > > parameterNames;\n    parameterNames.push_back( std::make_shared< InitialTranslationalStateEstimatableParameterSettings< double > >(\n                                  \"Vehicle\", systemInitialState, \"Earth\" ) );\n\n    std::vector< double > arcStartTimeList =\n    { initialEphemerisTime, initialEphemerisTime + 0.33 * 86400.0, initialEphemerisTime + 0.66 * 86400.0 };\n    parameterNames.push_back(\n                std::make_shared< ArcWiseDragCoefficientEstimatableParameterSettings >( \"Vehicle\", arcStartTimeList ) );\n    parameterNames.push_back(\n                std::make_shared< ArcWiseRadiationPressureCoefficientEstimatableParameterSettings >( \"Vehicle\", arcStartTimeList ) );\n\n    // Create parameters\n    std::shared_ptr< estimatable_parameters::EstimatableParameterSet< double > > parametersToEstimate =\n            createParametersToEstimate( parameterNames, bodyMap );\n\n    // Print identifiers and indices of parameters to terminal.\n    printEstimatableParameterEntries( parametersToEstimate );\n\n    Eigen::VectorXd truthParameters = parametersToEstimate->getFullParameterValues< double >( );\n    truthParameters( 7 ) += 0.1;\n    truthParameters( 8 ) += 0.2;\n\n    truthParameters( 10 ) += 0.1;\n    truthParameters( 11 ) += 0.2;\n\n    parametersToEstimate->resetParameterValues( truthParameters );\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ///////////////////////          INITIALIZE ORBIT DETERMINATION OBJECT     ////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Create orbit determination object (propagate orbit, create observation models)\n    OrbitDeterminationManager< double, double > orbitDeterminationManager =\n            OrbitDeterminationManager< double, double >(\n                bodyMap, parametersToEstimate, observationSettingsMap,\n                integratorSettings, propagatorSettings );\n\n    std::map< double, Eigen::VectorXd > dependentVariableData =\n            orbitDeterminationManager.getVariationalEquationsSolver( )->getDynamicsSimulatorBase(\n                )->getDependentVariableNumericalSolutionBase( )[ 0 ];\n\n    // Test whether arc-wise coefficients are correctly used.\n    double testDragCoefficient = 0.0;\n    double testRadiationPressureCoefficient = 0.0;\n    for( auto variableIterator : dependentVariableData )\n    {\n        double currentTime = variableIterator.first;\n\n        if( currentTime < arcStartTimeList.at( 1 ) )\n        {\n            testDragCoefficient = truthParameters( 6 );\n            testRadiationPressureCoefficient = truthParameters( 9 );\n        }\n        else if( currentTime < arcStartTimeList.at( 2 ) )\n        {\n            testDragCoefficient = truthParameters( 7 );\n            testRadiationPressureCoefficient = truthParameters( 10 );\n        }\n        else\n        {\n            testDragCoefficient = truthParameters( 8 );\n            testRadiationPressureCoefficient = truthParameters( 11 );\n        }\n\n        BOOST_CHECK_EQUAL( testDragCoefficient, variableIterator.second( 0 ) );\n        BOOST_CHECK_EQUAL( aerodynamicCoefficient * -0.01, variableIterator.second( 1 ) );\n        BOOST_CHECK_EQUAL( aerodynamicCoefficient * 0.1, variableIterator.second( 2 ) );\n        BOOST_CHECK_EQUAL( testRadiationPressureCoefficient, variableIterator.second( 3 ) );\n\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ///////////////////////          SIMULATE OBSERVATIONS                     ////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Define time of first observation\n    double observationTimeStart = initialEphemerisTime + 1000.0;\n\n    // Define time between two observations\n    double  observationInterval = 30.0;\n\n    // Simulate observations for 3 days\n    std::vector< double > baseTimeList;\n    double currentTime = initialEphemerisTime + 3600.0;\n    while( currentTime < finalEphemerisTime - 3600.0 )\n    {\n        baseTimeList.push_back( currentTime );\n        currentTime += observationInterval;\n    }\n\n    // Create measureement simulation input\n    std::map< ObservableType, std::map< LinkEnds, std::pair< std::vector< double >, LinkEndType > > > measurementSimulationInput;\n    measurementSimulationInput[ position_observable ][ linkEnds ] =\n            std::make_pair( baseTimeList, observed_body );\n\n    // Set typedefs for POD input (observation types, observation link ends, observation values, associated times with\n    // reference link ends.\n    typedef Eigen::Matrix< double, Eigen::Dynamic, 1 > ObservationVectorType;\n    typedef std::map< LinkEnds, std::pair< ObservationVectorType, std::pair< std::vector< double >, LinkEndType > > >\n            SingleObservablePodInputType;\n    typedef std::map< ObservableType, SingleObservablePodInputType > PodInputDataType;\n\n    // Simulate observations\n    PodInputDataType observationsAndTimes = simulateObservations< double, double >(\n                measurementSimulationInput, orbitDeterminationManager.getObservationSimulators( ) );\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //////////////////    PERTURB PARAMETER VECTOR AND ESTIMATE PARAMETERS     ////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Perturb parameter estimate\n    Eigen::Matrix< double, Eigen::Dynamic, 1 > parameterPerturbation =\n            Eigen::Matrix< double, Eigen::Dynamic, 1 >::Zero( truthParameters.rows( ) );\n    parameterPerturbation.segment( 0, 3 ) = Eigen::Vector3d::Constant( 10.0 );\n    parameterPerturbation.segment( 3, 3 ) = Eigen::Vector3d::Constant( 1.0E-2 );\n    parameterPerturbation.segment( 6, 6 ) = Eigen::VectorXd::Constant( 6, 1.0 );\n    Eigen::Matrix< double, Eigen::Dynamic, 1 > initialParameterEstimate = truthParameters;\n    initialParameterEstimate += parameterPerturbation;\n\n\n    // Define estimation input\n    std::shared_ptr< PodInput< double, double > > podInput =\n            std::make_shared< PodInput< double, double > >(\n                observationsAndTimes, initialParameterEstimate.rows( ),\n                Eigen::MatrixXd::Zero( truthParameters.rows( ), truthParameters.rows( ) ),\n                initialParameterEstimate - truthParameters );\n    podInput->defineEstimationSettings( true, true, false, true );\n\n    // Perform estimation\n    std::shared_ptr< PodOutput< double > > podOutput = orbitDeterminationManager.estimateParameters(\n                podInput, std::make_shared< EstimationConvergenceChecker >( 4 ) );\n    Eigen::VectorXd parameterEstimate = podOutput->parameterEstimate_ - truthParameters;\n\n    for( int i = 0; i < 3; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( parameterEstimate( i ) ), 1.0E-2 );\n        BOOST_CHECK_SMALL( std::fabs( parameterEstimate( i + 3 ) ), 1.0E-4 );\n        BOOST_CHECK_SMALL( std::fabs( parameterEstimate( i + 6 ) ), 1.0E-5 );\n        BOOST_CHECK_SMALL( std::fabs( parameterEstimate( i + 9 ) ), 1.0E-4 );\n\n\n    }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n}\n\n}\n", "meta": {"hexsha": "c1b9c13591e5aa12832060b814dcfcd9367f983a", "size": 17187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/OrbitDetermination/UnitTests/unitTestArcwiseEnvironmentParameters.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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/OrbitDetermination/UnitTests/unitTestArcwiseEnvironmentParameters.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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/OrbitDetermination/UnitTests/unitTestArcwiseEnvironmentParameters.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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.4580838323, "max_line_length": 133, "alphanum_fraction": 0.6132542038, "num_tokens": 3583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.1811285886329533}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_TOOLBOX_SWAR_FUNCTIONS_CUMPROD_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_SWAR_FUNCTIONS_CUMPROD_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n#include <boost/simd/toolbox/operator/functions/multiplies.hpp>\n#include <boost/simd/toolbox/constant/constants/one.hpp>\n\n\n/*!\n * \\ingroup boost_simd_swar\n * \\defgroup boost_simd_swar_cumprod cumprod\n *\n * \\par Description\n * compute the cumulate prod of the vector elements\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/cumprod.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class A0>\n *     meta::call<tag::cumprod_(A0)>::type\n *     cumprod(const A0 & a0);\n * }\n * \\endcode\n *\n * \\param a0 the unique parameter of cumprod\n *\n * \\return a value of the same type as the parameter\n *\n * \\par Notes\n * \\par\n * This is a swar operation. As such it has not real interest outside\n * SIMD mode.\n * \\par\n * Such an operation is a transform of an SIMD vector, that will return\n * vectors obtained on a non necessarily elementwise basis from the inputs\n * elements\n * \\par\n * If usable and used in scalar mode, it reduces to the operation\n * on a one element vector.\n *\n**/\n\nnamespace boost { namespace simd { namespace tag\n  {\n    /*!\n     * \\brief Define the tag cumprod_ of functor cumprod\n     *        in namespace boost::simd::tag for toolbox boost.simd.swar\n    **/\n    struct cumprod_ : ext::cumulative_<cumprod_, tag::multiplies_, tag::One>\n    {\n      typedef ext::cumulative_<cumprod_, tag::multiplies_, tag::One> parent;\n    };\n  }\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::cumprod_, cumprod, 1)\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::cumprod_, cumprod, 2)\n} }\n\n#endif\n\n// modified by jt the 25/12/2010\n", "meta": {"hexsha": "7737292d7b3784add134184ea01b0b08b5b5b4dc", "size": 2327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/swar/include/boost/simd/toolbox/swar/functions/cumprod.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/swar/include/boost/simd/toolbox/swar/functions/cumprod.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/swar/include/boost/simd/toolbox/swar/functions/cumprod.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": 28.7283950617, "max_line_length": 80, "alphanum_fraction": 0.6407391491, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.1811285816008579}}
{"text": "#include <iostream>\n#include <string>\n#include <boost/algorithm/string.hpp>\n\nconst std::string input = R\"(cpy a b\ndec b\ncpy a d\ncpy 0 a\ncpy b c\ninc a\ndec c\njnz c -2\ndec d\njnz d -5\ndec b\ncpy b c\ncpy c d\ndec d\ninc c\njnz d -2\ntgl c\ncpy -16 c\njnz 1 c\ncpy 77 c\njnz 73 d\ninc a\ninc d\njnz d -2\ninc c\njnz c -5)\";\n\nstruct Argument\n{\n    int index;\n    bool is_register;\n\n    Argument(int _index, bool _is_register)\n        : index(_index)\n        , is_register(_is_register)\n    {\n    }\n};\n\nstruct Instruction\n{\n    std::string code;\n    std::vector<Argument> args;\n\n    void parse(const std::string &str)\n    {\n        std::vector<std::string> parts;\n        boost::split(parts, str, boost::is_any_of(\" \"));\n\n        code = parts[0];\n        args.clear();\n        for (int i = 1; i < parts.size(); ++i)\n        {\n            int index = 0;\n            bool is_register = false;\n\n            if ((parts[i].size() == 1)\n                && (parts[i][0] >= 'a')\n                && (parts[i][0] <= 'd'))\n            {\n                index = parts[i][0] - 'a';\n                is_register = true;\n            }\n            else\n            {\n                index = atoi(parts[i].c_str());\n                is_register = false;\n            }\n\n            args.push_back(Argument(index, is_register));\n        }\n    }\n};\n\nstruct ComputerState\n{\n    int pc;\n    int64_t registers[4];\n    bool complete;\n\n    ComputerState()\n        : pc(0)\n        , complete(false)\n    {\n        for (int i = 0; i < 4; ++i)\n            registers[i] = 0;\n    }\n\n    void set(const Argument &arg, int value)\n    {\n        assert(arg.is_register);\n        registers[arg.index] = value;\n    }\n\n    int get(const Argument &arg) const\n    {\n        if (arg.is_register)\n            return registers[arg.index];\n        else\n            return arg.index;\n    }\n\n    void update(std::vector<Instruction> &instructions)\n    {\n        if (!complete\n            && (pc < instructions.size())\n            && (pc >= 0))\n        {\n            const Instruction &inst = instructions[pc];\n\n            if (inst.code == \"cpy\")\n            {\n                assert(inst.args.size() == 2);\n\n                if (inst.args[1].is_register)\n                {\n                    set(inst.args[1], get(inst.args[0]));\n                }\n\n                pc += 1;\n            }\n            else if (inst.code == \"inc\")\n            {\n                assert(inst.args.size() == 1);\n\n                if (inst.args[0].is_register)\n                {\n                    set(inst.args[0], get(inst.args[0]) + 1);\n                }\n\n                pc += 1;\n            }\n            else if (inst.code == \"dec\")\n            {\n                assert(inst.args.size() == 1);\n\n                if (inst.args[0].is_register)\n                {\n                    set(inst.args[0], get(inst.args[0]) - 1);\n                }\n\n                pc += 1;\n            }\n            else if (inst.code == \"jnz\")\n            {\n                assert(inst.args.size() == 2);\n\n                int test = get(inst.args[0]);\n                int distance = get(inst.args[1]);\n\n                if (test != 0)\n                    pc = pc + distance;\n                else\n                    pc += 1;\n            }\n            else if (inst.code == \"tgl\")\n            {\n                int target_inst_index = pc + get(inst.args[0]);\n\n                if ((target_inst_index >= 0)\n                    && (target_inst_index < instructions.size()))\n                {\n                    Instruction &target_inst = instructions[target_inst_index];\n\n                    if (target_inst.args.size() == 1)\n                    {\n                        if (target_inst.code == \"inc\")\n                            target_inst.code = \"dec\";\n                        else\n                            target_inst.code = \"inc\";\n                    }\n                    else // 2-argument instructions\n                    {\n                        if (target_inst.code == \"jnz\")\n                            target_inst.code = \"cpy\";\n                        else\n                            target_inst.code = \"jnz\";\n                    }\n                }\n\n                pc += 1;\n            }\n            else\n            {\n                assert(false);\n            }\n        }\n\n        if ((pc >= instructions.size())\n            || (pc < 0))\n        {\n            complete = true;\n        }\n    }\n\n    void print() const\n    {\n        std::cout << \"pc=\" << pc << \", reg=\"\n            << registers[0] << \",\"\n            << registers[1] << \",\"\n            << registers[2] << \",\"\n            << registers[3] << std::endl;\n    }\n};\n\nint run_with_arg(int init)\n{\n    std::vector<std::string> lines;\n    boost::split(lines, input, boost::is_any_of(\"\\n\"));\n\n    std::vector<Instruction> instructions;\n\n    for (const std::string &line : lines)\n    {\n        instructions.emplace_back();\n        instructions.back().parse(line);\n    }\n\n    ComputerState state;\n\n    state.registers[0] = init;\n\n    while (!state.complete)\n    {\n        state.update(instructions);\n\n        //state.print();\n    }\n\n    return state.registers[0];\n}\n\nint main(int argc, char *argv[])\n{\n    int answer1 = run_with_arg(7);\n\n    std::cout << \"Answer #1: \" << answer1 << std::endl;\n\n    std::cout << \"Answer #2: Calculate f(12) based on these values:\" << std::endl;\n    for (int i = 7; i <= 10; ++i)\n    {\n        std::cout << \"   f(\" << i << \") = \" << run_with_arg(i) << std::endl;\n    }\n    std::cout << std::endl;\n    std::cout << \"For my input, it looks like f(x) = 5621 + factorial(x)\" << std::endl;\n    std::cout << \"  so f(12) = 5621 + 12! = 5621 = 479007221\" << std::endl;\n}\n", "meta": {"hexsha": "480c93672bcb7a2bee06b3550d1242e041517a1b", "size": 5655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2016/23.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/23.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/23.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.4404761905, "max_line_length": 87, "alphanum_fraction": 0.4201591512, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18112858160085787}}
{"text": "// Copyright (c) 2011-2017 The Bitcoin Core developers\n// Copyright (c) 2020 The Gapcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <cstddef>\n#include <ostream>\n#include <sstream>\n#include <stdio.h>\n\n\n#include <amount.h>\n#include <base58.h>\n#include <blockencodings.h>\n#include <chainparams.h>\n#include <chainparamsbase.h>\n#include <coins.h>\n#include <consensus/consensus.h>\n#include <consensus/merkle.h>\n#include <consensus/tx_verify.h>\n#include <consensus/validation.h>\n#include <miner.h>\n#include <policy/policy.h>\n#include <PoWCore/src/PoW.h>\n#include <PoWCore/src/PoWProcessor.h>\n#include <PoWCore/src/PoWUtils.h>\n#include <PoWCore/src/Sieve.h>\n#include <primitives/block.h>\n#include <primitives/transaction.h>\n#include <pubkey.h>\n#include <random.h>\n#include <script/standard.h>\n#include <txmempool.h>\n#include <uint256.h>\n#include <util.h>\n#include <utilstrencodings.h>\n#include <validation.h>\n#include <wallet/rpcwallet.h>\n#include <wallet/wallet.h>\n\n#include <test/test_bitcoin.h>\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(gapblock_tests, TestingSetup)\n\nstatic PoWUtils *powUtils = new PoWUtils();\n\n//class BlockProcessor : public PoWProcessor {\n//public:\n//    BlockProcessor(CBlock *pblock, CReserveScript coinbasescript) : PoWProcessor() {\n//        this->pblock = pblock;\n//        this->script = coinbasescript;\n//    }\n\n//    bool process(PoW *pow) {\n//        pow->get_adder(&pblock->nAdd);\n//        bool ret = CheckWork(pblock, script);\n//        return !ret;\n//    }\n\n//private:\n//    CBlock *pblock;\n//    CReserveScript script;\n//};\n\nclass BlockProcessor : public PoWProcessor {\n\n  public:\n\n    BlockProcessor(CBlock *pblock, std::shared_ptr<CReserveScript> coinbase_script) : PoWProcessor() {\n      this->pblock = pblock;\n      this->script = coinbase_script;\n    }\n\n    bool process(PoW *pow) {\n      pow->get_adder(&pblock->nAdd);\n      bool ret = CheckWork(pblock, script);\n      return !ret;\n    }\n\n  private:\n\n    CBlock *pblock;\n    std::shared_ptr<CReserveScript> script;\n\n};\n\n//CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)\n//{\n//    CKey coinbaseKey; // private/public key needed to spend coinbase transactions\n//    UpdateVersionBitsParameters(Consensus::DEPLOYMENT_SEGWIT, 0, Consensus::BIP9Deployment::NO_TIMEOUT);\n//    coinbaseKey.MakeNewKey(true);\n//    CScript scriptPubKey = CScript() <<  ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;\n//    return CreateNewBlock(scriptPubKey);\n//}\n\n//bool CheckWork(CBlock* pblock, CReserveKey& reservekey)\n//{\n//    uint256 hash = pblock->GetHash();\n//    PoW pow(new std::vector<uint8_t>(hash.begin(), hash.end()),\n//            pblock->nShift,\n//            &pblock->nAdd,\n//            pblock->nDifficulty);\n\n//    uint64_t nDifficulty = pow.difficulty();\n\n//    if (nDifficulty < pblock->nDifficulty)\n//        return false;\n\n//    //// debug print\n//    LogPrintf(\"GapcoinMiner:\\n\");\n//    LogPrintf(\"proof-of-work found  \\ndifficulty: %\" PRIu64 \"  \\ntarget: %\" PRIu64 \"\\n\", nDifficulty, pblock->nDifficulty);\n//    pblock->print();\n//    LogPrintf(\"generated %s\\n\", FormatMoney(pblock->vtx[0].vout[0].nValue));\n\n//    // Found a solution\n//    {\n//        LOCK(cs_main);\n//        if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())\n//            return error(\"GapcoinMiner : generated block is stale\");\n\n//        // Remove key from key pool\n//        reservekey.KeepKey();\n\n//        // Track how many getdata requests this block gets\n//        {\n//            LOCK(wallet.cs_wallet);\n//            wallet.mapRequestCount[pblock->GetHash()] = 0;\n//        }\n\n//        // Process this block the same as if we had received it from another node\n//        CValidationState state;\n//        if (!ProcessBlock(state, NULL, pblock))\n//            return error(\"GapcoinMiner : ProcessBlock, block not accepted\");\n//    }\n\n//    return true;\n//}\n\nstatic CFeeRate blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);\n\nstatic BlockAssembler AssemblerForTest(const CChainParams& params) {\n    BlockAssembler::Options options;\n\n    options.nBlockMaxWeight = MAX_BLOCK_WEIGHT;\n    options.blockMinFeeRate = blockMinFeeRate;\n    return BlockAssembler(params, options);\n}\n\nvoid static GapcoinMiner()\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    const CChainParams& chainparams = *chainParams;\n    std::unique_ptr<CBlockTemplate> pblocktemplate;\n\n    CTxDestination destination = DecodeDestination(\"Gg6zcf8yLbPdy1b14T135QzhjhZXQTSVW2\");\n    BOOST_CHECK(IsValidDestination(destination));\n\n    std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>();\n    coinbaseScript->reserveScript = GetScriptForDestination(destination);\n\n    unsigned int nExtraNonce = 0;\n    uint256 hashTarget = uint256S(\"0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n\n    uint64_t nMiningSieveSize = 1000;\n    uint64_t nMiningPrimes = 1000;\n    uint16_t nMiningShift = 15;\n\n    Sieve sieve(NULL, nMiningPrimes, nMiningSieveSize);\n    std::cout << \"Sieve initialised.\" << std::endl;\n\n    try {\n        // Create new block\n        CBlockIndex* pindexPrev = chainActive.Tip();\n\n        std::cout << \"Creating template.\" << std::endl;\n        // std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));\n        BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(coinbaseScript->reserveScript));\n\n        if (!pblocktemplate.get()) {\n            std::cout << \"Template creation failed.\" << std::endl;\n            return;\n        }\n        std::cout << \"Template created.\" << std::endl;\n\n        // std::cout << \"pblock\" << std::endl;\n        // const std::vector<unsigned char>::size_type Z(pblocktemplate->block.nAdd.size());\n        // std::cout << \"{\";\n        // for (size_t i=0; i<Z; i++)\n        // {\n        //     std::cout << static_cast<unsigned int>(pblocktemplate->block.nAdd[i]) << \",\";\n        // }\n        // std::cout << \"}\" << std::endl;\n        // std::cout << \"shift: \" << pblocktemplate->block.nShift << std::endl;\n        // std::cout << \"difficulty: \" << pblocktemplate->block.nDifficulty << std::endl;\n        // std::cout << \"nonce: \" << pblocktemplate->block.nNonce << std::endl;\n\n        CBlock *pblock = &pblocktemplate->block;\n        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);\n\n        pblock->nDifficulty = PoWUtils::min_test_difficulty;\n        uint8_t nAdd[]      = { 25, 1 };\n        pblock->nAdd.assign(nAdd, nAdd + sizeof(nAdd) / sizeof(uint8_t));\n\n        const std::vector<unsigned char>::size_type T(pblock->nAdd.size());\n        std::cout << \"pblock\" << std::endl;\n        std::cout << \"{\";\n        for (size_t i=0; i<T; i++)\n        {\n            std::cout << static_cast<unsigned int>(pblock->nAdd[i]) << \",\";\n        }\n        std::cout << \"}\" << std::endl;\n        std::cout << \"shift: \" << pblock->nShift << std::endl;\n        std::cout << \"difficulty: \" << pblock->nDifficulty << std::endl;\n        std::cout << \"nonce: \" << pblock->nNonce << std::endl;\n\n        // Search\n        BlockProcessor processor(pblock, coinbaseScript);\n        // std::cout << \"PoW processor initialised.\" << std::endl;\n        sieve.set_pprocessor(&processor);\n        // std::cout << \"PoW processor bound to sieve.\" << std::endl;\n\n        // int64_t nStart = GetTime();\n\n        pblock->nNonce = 0;\n\n        while (true)\n        {\n            /* header hash has to be greater than 2^255 - 1 */\n            // std::cout << \"pblock->GetHash()\" << pblock->GetHash().ToString() << \" hashTarget: \" << hashTarget << std::endl;\n            while (pblock->GetHash() < hashTarget) {\n                pblock->nNonce += 1;\n                if (pblock->nNonce % 1000 == 0)\n                    std::cout << \"pblock->nNonce = \" << pblock->nNonce << std::endl;\n\n                uint256 hash = pblock->GetHash();\n                std::vector<uint8_t> vHash(hash.begin(), hash.end());\n\n                PoW pow(&vHash, pblock->nShift, &pblock->nAdd, pblock->nDifficulty);\n                sieve.run_sieve(&pow, NULL);\n                if (pow.valid()) {\n                    // std::cout << \"Run with pow processor \" << pow.to_s() << std::endl;\n                    break;\n                }\n            }\n            std::cout << \"pblock: \" << pblock->ToString() << std::endl;\n            const std::vector<unsigned char>::size_type N(pblock->nAdd.size());\n            std::cout << \"{\";\n            for (size_t i=0; i<N; i++)\n            {\n                std::cout << static_cast<unsigned int>(pblock->nAdd[i]) << \",\";\n            }\n            std::cout << \"}\" << std::endl;\n            std::cout << \"shift: \" << pblock->nShift << std::endl;\n            std::cout << \"difficulty: \" << pblock->nDifficulty << std::endl;\n            std::cout << \"nonce: \" << pblock->nNonce << std::endl;\n        }\n    }\n    catch (boost::thread_interrupted)\n    {\n        LogPrintf(\"GapcoinMiner terminated\\n\");\n        throw;\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(one)\n{\n    BOOST_TEST_MESSAGE(strprintf(\"nMiningSieveSize=%s, nMiningPrimes=%s, nMiningShift=%s.\", nMiningSieveSize, nMiningPrimes, nMiningShift));\n    /* FIXME: diabled, pro tem\n    GapcoinMiner();\n    */\n    BOOST_TEST_MESSAGE(strprintf(\"Done\"));\n}\n\n//static CBlock BuildBlockTestCase() {\n//    CBlock block;\n//    CMutableTransaction tx;\n//    tx.vin.resize(1);\n//    tx.vin[0].scriptSig.resize(10);\n//    tx.vout.resize(1);\n//    tx.vout[0].nValue = 42;\n\n//    block.vtx.resize(3);\n//    block.vtx[0] = MakeTransactionRef(tx);\n//    block.nVersion = 42;\n//    block.hashPrevBlock = InsecureRand256();\n//    block.nDifficulty = PoWUtils::min_difficulty;\n//    uint8_t nAdd[]      = { 25, 1 };\n//    block.nAdd.assign(nAdd, nAdd + sizeof(nAdd) / sizeof(uint8_t));\n//    tx.vin[0].prevout.hash = InsecureRand256();\n//    tx.vin[0].prevout.n = 0;\n//    block.vtx[1] = MakeTransactionRef(tx);\n\n//    tx.vin.resize(10);\n//    for (size_t i = 0; i < tx.vin.size(); i++) {\n//        tx.vin[i].prevout.hash = InsecureRand256();\n//        tx.vin[i].prevout.n = 0;\n//    }\n\n//    block.vtx[2] = MakeTransactionRef(tx);\n\n//    bool mutated;\n//    block.hashMerkleRoot = BlockMerkleRoot(block, &mutated);\n//    assert(!mutated);\n//    while (!CheckProofOfWork(block.GetHash(), block.nShift, &block.nAdd, block.nDifficulty, Params().GetConsensus())) ++block.nNonce;\n//    return block;\n//}\n\n//static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint64_t nDifficulty, int32_t nVersion, const CAmount& genesisReward)\n//{\n//    CMutableTransaction txNew;\n//    txNew.nVersion = 1;\n//    txNew.vin.resize(1);\n//    txNew.vout.resize(1);\n//    txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));\n//    txNew.vout[0].nValue = genesisReward;\n//    txNew.vout[0].scriptPubKey = genesisOutputScript;\n\n//    CBlock genesis;\n//    genesis.nTime    = nTime;\n//    genesis.nNonce   = nNonce;\n//    genesis.nVersion = nVersion;\n//    genesis.nShift = 20;\n//    genesis.nDifficulty = nDifficulty;\n//    uint8_t nAdd[] = { 233, 156, 15 };\n//    genesis.nAdd.assign(nAdd, nAdd + sizeof(nAdd) / sizeof(uint8_t));\n//    genesis.vtx.push_back(MakeTransactionRef(std::move(txNew)));\n//    genesis.hashPrevBlock.SetNull();\n//    genesis.hashMerkleRoot = BlockMerkleRoot(genesis);\n//    return genesis;\n//}\n\n//static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint64_t nDifficulty, int32_t nVersion, const CAmount& genesisReward)\n//{\n//    const char* pszTimestamp = \"The Times 15/Oct/2014 US data sends global stocks into tail-spin\";\n//    const CScript genesisOutputScript = CScript() << ParseHex(\"044588d54931b7de2f9faaa5a3c1fde654114ae51273754e1f3f9720127f8977af6bfaa1f33e22e80e4b83f5269921501b411d254929faf1b10d2174ded28ac59d\") << OP_CHECKSIG;\n//    return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nDifficulty, nVersion, genesisReward);\n//}\n\n//static bool CheckPoW(const uint256 hash, const uint16_t nShift, const std::vector<uint8_t> *const nAdd, const uint64_t nDifficulty)\n//{\n//    std::vector<uint8_t> vHash(hash.begin(), hash.end());\n  \n//    PoW pow(&vHash, nShift, nAdd, nDifficulty);\n\n//    // Check proof of work matches claimed amount\n//    if (!pow.valid())\n//        return error(\"CheckProofOfWork() : hash does not match nDifficulty\");\n\n//    return true;\n//}\n\n//static CBlock ReBuildGensisBlock() {\n//    CBlock genesis = CreateGenesisBlock(1413914400, 13370, PoWUtils::min_difficulty, 1, 0 * COIN);\n//    return genesis;\n//}\n\n//BOOST_AUTO_TEST_CASE(ReadHashTest, *boost::unit_test::disabled() *boost::unit_test::label(\"readhash\") *boost::unit_test::description(\"Test skipped\"))\n//{\n//    // head -c 298 blocks/blk00000.dat | tail -c +9 | hexdump -v -e '/1 \"%02x\"'\n//    string genesisraw  = \"01000000000000000000000000000000000000000000000000000000000000000000000094110eb4e3b9c2b70df4b71df19d5405cca21e55c2565e356ae22aadcf101026209f465400000000000010003a340000140003e99c0f0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4804ffff001d0104405468652054696d65732031352f4f63742f3230313420555320646174612073656e647320676c6f62616c2073746f636b7320696e746f207461696c2d7370696effffffff0100000000000000004341044588d54931b7de2f9faaa5a3c1fde654114ae51273754e1f3f9720127f8977af6bfaa1f33e22e80e4b83f5269921501b411d254929faf1b10d2174ded28ac59dac00000000\";\n//    CBlock block;\n//    CDataStream stream(ParseHex(genesisraw), SER_NETWORK, PROTOCOL_VERSION);\n//    stream >> block;\n//    BOOST_CHECK_EQUAL(block.GetHash().ToString(), \"e798f3ae4f57adcf25740fe43100d95ec4fd5d43a1568bc89e2b25df89ff6cb0\");\n//    BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), \"261010cfad2ae26a355e56c2551ea2cc05549df11db7f40db7c2b9e3b40e1194\");\n//}\n\n//BOOST_AUTO_TEST_CASE(SimpleHashTest, *boost::unit_test::disabled() *boost::unit_test::description(\"test skipped\"))\n//{\n//    CBlock block = getBlock0();\n//    block.GetHash();\n//    BOOST_CHECK_EQUAL(block.GetHash().ToString(), \"e798f3ae4f57adcf25740fe43100d95ec4fd5d43a1568bc89e2b25df89ff6cb0\");\n//    BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), \"261010cfad2ae26a355e56c2551ea2cc05549df11db7f40db7c2b9e3b40e1194\");\n//}\n\n//BOOST_AUTO_TEST_CASE(ReadGenesisTest, *boost::unit_test::disabled() *boost::unit_test::description(\"test skipped\"))\n//{\n//    CBlock block = ReBuildGensisBlock();\n//    block.GetHash();\n//    BOOST_CHECK_EQUAL(block.GetHash().ToString(), \"e798f3ae4f57adcf25740fe43100d95ec4fd5d43a1568bc89e2b25df89ff6cb0\");\n//    BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), \"261010cfad2ae26a355e56c2551ea2cc05549df11db7f40db7c2b9e3b40e1194\");\n//}\n\n//BOOST_AUTO_TEST_CASE(powcheck, *boost::unit_test::disabled() *boost::unit_test::description(\"test skipped\"))\n//{\n//    // uint256 hash = pindex->GetBlockHash();\n//    // std::vector<uint8_t> vHash(hash.begin(), hash.end());\n//    // PoW pow(&vHash, pindex->nShift, &pindex->nAdd, pindex->nDifficulty);\n\n//}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "cdd8bd42bea199475c24c09fc5d9184a36a95489", "size": 15242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/gapblock_tests.cpp", "max_stars_repo_name": "attilaolah/gapcoin", "max_stars_repo_head_hexsha": "6828bdebf2f07367799e41b04e081de24e322057", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-07T01:18:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T15:49:28.000Z", "max_issues_repo_path": "src/test/gapblock_tests.cpp", "max_issues_repo_name": "attilaolah/gapcoin", "max_issues_repo_head_hexsha": "6828bdebf2f07367799e41b04e081de24e322057", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-20T12:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-09T09:36:08.000Z", "max_forks_repo_path": "src/test/gapblock_tests.cpp", "max_forks_repo_name": "attilaolah/gapcoin", "max_forks_repo_head_hexsha": "6828bdebf2f07367799e41b04e081de24e322057", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-02-03T14:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T11:56:21.000Z", "avg_line_length": 38.4898989899, "max_line_length": 610, "alphanum_fraction": 0.6604776276, "num_tokens": 4399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18112858160085787}}
{"text": "// Copyright (c) 2016-2020 The ZCash developers\n// Copyright (c) 2020 The PIVX developers\n// Copyright (c) 2020 The Supernode Coin developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"wallet/test/wallet_test_fixture.h\"\n\n#include \"sapling/util.h\"\n#include \"sapling/address.hpp\"\n#include \"wallet/wallet.h\"\n#include \"wallet/walletdb.h\"\n#include \"util.h\"\n#include <boost/test/unit_test.hpp>\n\n/**\n * This test covers methods on CWallet\n * GenerateNewZKey()\n * AddZKey()\n * LoadZKey()\n * LoadZKeyMetadata()\n */\n\nBOOST_FIXTURE_TEST_SUITE(wallet_zkeys_tests, WalletTestingSetup)\n\n/**\n  * This test covers Sapling methods on CWallet\n  * GenerateNewSaplingZKey()\n  * AddSaplingZKey()\n  * LoadSaplingZKey()\n  * LoadSaplingZKeyMetadata()\n  */\nBOOST_AUTO_TEST_CASE(StoreAndLoadSaplingZkeys) {\n    SelectParams(CBaseChainParams::MAIN);\n\n    CWallet wallet;\n    LOCK(wallet.cs_wallet);\n    // wallet should be empty\n    std::set<libzcash::SaplingPaymentAddress> addrs;\n    wallet.GetSaplingPaymentAddresses(addrs);\n    BOOST_CHECK_EQUAL(0, addrs.size());\n\n    // No HD seed in the wallet\n    BOOST_CHECK_THROW(wallet.GenerateNewSaplingZKey(), std::runtime_error);\n\n    // Random seed\n    CKey seed;\n    seed.MakeNewKey(true);\n    wallet.AddKeyPubKey(seed, seed.GetPubKey());\n    wallet.GetSaplingScriptPubKeyMan()->SetHDSeed(seed.GetPubKey(), false, true);\n\n    // wallet should have one key\n    auto address = wallet.GenerateNewSaplingZKey();\n    wallet.GetSaplingPaymentAddresses(addrs);\n    BOOST_CHECK_EQUAL(1, addrs.size());\n\n    // verify wallet has incoming viewing key for the address\n    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(address));\n\n    // manually add new spending key to wallet\n    HDSeed seed1(seed.GetPrivKey());\n    auto m = libzcash::SaplingExtendedSpendingKey::Master(seed1);\n    auto sk = m.Derive(0);\n    BOOST_CHECK(wallet.AddSaplingZKey(sk, sk.DefaultAddress()));\n\n    // verify wallet did add it\n    auto fvk = sk.expsk.full_viewing_key();\n    BOOST_CHECK(wallet.HaveSaplingSpendingKey(fvk));\n\n    // verify spending key stored correctly\n    libzcash::SaplingExtendedSpendingKey keyOut;\n    wallet.GetSaplingSpendingKey(fvk, keyOut);\n    BOOST_CHECK(sk == keyOut);\n\n    // verify there are two keys\n    wallet.GetSaplingPaymentAddresses(addrs);\n    BOOST_CHECK_EQUAL(2, addrs.size());\n    BOOST_CHECK_EQUAL(1, addrs.count(address));\n    BOOST_CHECK_EQUAL(1, addrs.count(sk.DefaultAddress()));\n\n    // Generate a diversified address different to the default\n    // If we can't get an early diversified address, we are very unlucky\n    blob88 diversifier;\n    diversifier.begin()[0] = 10;\n    auto dpa = sk.ToXFVK().Address(diversifier).get().second;\n\n    // verify wallet only has the default address\n    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress()));\n    BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa));\n\n    // manually add a diversified address\n    auto ivk = fvk.in_viewing_key();\n    BOOST_CHECK(wallet.AddSaplingIncomingViewingKeyW(ivk, dpa));\n\n    // verify wallet did add it\n    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress()));\n    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa));\n\n    // Load a third key into the wallet\n    auto sk2 = m.Derive(1);\n    BOOST_CHECK(wallet.LoadSaplingZKey(sk2));\n\n    // attach metadata to this third key\n    auto ivk2 = sk2.expsk.full_viewing_key().in_viewing_key();\n    int64_t now = GetTime();\n    CKeyMetadata meta(now);\n    BOOST_CHECK(wallet.LoadSaplingZKeyMetadata(ivk2, meta));\n\n    // check metadata is the same\n    BOOST_CHECK_EQUAL(wallet.GetSaplingScriptPubKeyMan()->mapSaplingZKeyMetadata[ivk2].nCreateTime, now);\n\n    // Load a diversified address for the third key into the wallet\n    auto dpa2 = sk2.ToXFVK().Address(diversifier).get().second;\n    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk2.DefaultAddress()));\n    BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa2));\n    BOOST_CHECK(wallet.LoadSaplingPaymentAddress(dpa2, ivk2));\n    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa2));\n}\n\n/**\n  * This test covers methods on CWalletDB to load/save crypted sapling z keys.\n  */\nBOOST_AUTO_TEST_CASE(WriteCryptedSaplingZkeyDirectToDb) {\n    SelectParams(CBaseChainParams::TESTNET);\n\n    BOOST_CHECK(!pwalletMain->HasSaplingSPKM());\n    assert(pwalletMain->SetupSPKM(true));\n\n    // wallet should be empty\n    std::set<libzcash::SaplingPaymentAddress> addrs;\n    pwalletMain->GetSaplingPaymentAddresses(addrs);\n    BOOST_CHECK_EQUAL(0, addrs.size());\n\n    // Add random key to the wallet\n    auto address = pwalletMain->GenerateNewSaplingZKey();\n\n    // wallet should have one key\n    pwalletMain->GetSaplingPaymentAddresses(addrs);\n    BOOST_CHECK_EQUAL(1, addrs.size());\n\n    // encrypt wallet\n    SecureString strWalletPass;\n    strWalletPass.reserve(100);\n    strWalletPass = \"hello\";\n    BOOST_CHECK(pwalletMain->EncryptWallet(strWalletPass));\n\n    // adding a new key will fail as the wallet is locked\n    BOOST_CHECK_THROW(pwalletMain->GenerateNewSaplingZKey(), std::runtime_error);\n\n    // unlock wallet and then add\n    pwalletMain->Unlock(strWalletPass);\n    libzcash::SaplingPaymentAddress address2 = pwalletMain->GenerateNewSaplingZKey();\n\n    // Create a new wallet from the existing wallet path\n    bool fFirstRun;\n    CWallet wallet2(pwalletMain->strWalletFile);\n    BOOST_CHECK_EQUAL(DB_LOAD_OK, wallet2.LoadWallet(fFirstRun));\n\n    // Confirm it's not the same as the other wallet\n    BOOST_CHECK(pwalletMain != &wallet2);\n    BOOST_CHECK(wallet2.HasSaplingSPKM());\n\n    // wallet should have two keys\n    wallet2.GetSaplingPaymentAddresses(addrs);\n    BOOST_CHECK_EQUAL(2, addrs.size());\n\n    //check we have entries for our payment addresses\n    BOOST_CHECK(addrs.count(address));\n    BOOST_CHECK(addrs.count(address2));\n\n    // spending key is crypted, so we can't extract valid payment address\n    libzcash::SaplingExtendedSpendingKey keyOut;\n    BOOST_CHECK(!wallet2.GetSaplingExtendedSpendingKey(address, keyOut));\n\n    // unlock wallet to get spending keys and verify payment addresses\n    wallet2.Unlock(strWalletPass);\n\n    BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address, keyOut));\n    BOOST_CHECK(address == keyOut.DefaultAddress());\n\n    BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address2, keyOut));\n    BOOST_CHECK(address2 == keyOut.DefaultAddress());\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4f85040edcb43083bcf3382ea3f1a2e425557c79", "size": 6500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/librust/wallet_zkeys_tests.cpp", "max_stars_repo_name": "Supernode-SUNO/SUNO", "max_stars_repo_head_hexsha": "6b34a154671597b6e072eeecf336d2d3d38ee6bb", "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/test/librust/wallet_zkeys_tests.cpp", "max_issues_repo_name": "Supernode-SUNO/SUNO", "max_issues_repo_head_hexsha": "6b34a154671597b6e072eeecf336d2d3d38ee6bb", "max_issues_repo_licenses": ["MIT"], "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/librust/wallet_zkeys_tests.cpp", "max_forks_repo_name": "Supernode-SUNO/SUNO", "max_forks_repo_head_hexsha": "6b34a154671597b6e072eeecf336d2d3d38ee6bb", "max_forks_repo_licenses": ["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.7593582888, "max_line_length": 105, "alphanum_fraction": 0.7384615385, "num_tokens": 1677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.18108581712782226}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Regression\n\n#include <fstream>\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n\n#include <xolotl/core/flux/W111FitFluxHandler.h>\n#include <xolotl/core/network/PSIReactionNetwork.h>\n#include <xolotl/options/Options.h>\n#include <xolotl/test/CommandLine.h>\n#include <xolotl/util/MPIUtils.h>\n\nusing namespace std;\nusing namespace xolotl;\nusing namespace core;\nusing namespace flux;\n\nusing Kokkos::ScopeGuard;\nBOOST_GLOBAL_FIXTURE(ScopeGuard);\n\n/**\n * The test suite is responsible for testing the W111FitFluxHandler.\n */\nBOOST_AUTO_TEST_SUITE(W111FitFluxHandlerTester_testSuite)\n\nBOOST_AUTO_TEST_CASE(checkComputeIncidentFlux)\n{\n\t// Create the option to create a network\n\txolotl::options::Options opts;\n\t// Create a good parameter file\n\tstd::string parameterFile = \"param.txt\";\n\tstd::ofstream paramFile(parameterFile);\n\tparamFile << \"netParam=9 0 0 0 0\" << std::endl;\n\tparamFile.close();\n\n\t// Create a fake command line to read the options\n\ttest::CommandLine<2> cl{{\"fakeXolotlAppNameForTests\", parameterFile}};\n\tutil::mpiInit(cl.argc, cl.argv);\n\topts.readParams(cl.argc, cl.argv);\n\n\tstd::remove(parameterFile.c_str());\n\n\t// Create a grid\n\tstd::vector<double> grid;\n\tfor (int l = 0; l < 7; l++) {\n\t\tgrid.push_back((double)l * 1.25);\n\t}\n\t// Specify the surface position\n\tint surfacePos = 0;\n\n\t// Create the network\n\tusing NetworkType =\n\t\tnetwork::PSIReactionNetwork<network::PSIFullSpeciesList>;\n\tNetworkType::AmountType maxV = opts.getMaxV();\n\tNetworkType::AmountType maxI = opts.getMaxI();\n\tNetworkType::AmountType maxHe = opts.getMaxImpurity();\n\tNetworkType::AmountType maxD = opts.getMaxD();\n\tNetworkType::AmountType maxT = opts.getMaxT();\n\tNetworkType network({maxHe, maxD, maxT, maxV, maxI}, grid.size(), opts);\n\tnetwork.syncClusterDataOnHost();\n\tnetwork.getSubpaving().syncZones(plsm::onHost);\n\t// Get its size\n\tconst int dof = network.getDOF();\n\n\t// Create the W111 flux handler\n\tauto testFitFlux = make_shared<W111FitFluxHandler>(opts);\n\t// Set the flux amplitude\n\ttestFitFlux->setFluxAmplitude(1.0);\n\t// Initialize the flux handler\n\ttestFitFlux->initializeFluxHandler(network, surfacePos, grid);\n\n\t// Create a time\n\tdouble currTime = 1.0;\n\n\t// The array of concentration\n\tdouble newConcentration[5 * dof];\n\n\t// Initialize their values\n\tfor (int i = 0; i < 5 * dof; i++) {\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// The pointer to the grid point we want\n\tdouble* updatedConc = &newConcentration[0];\n\tdouble* updatedConcOffset = updatedConc + dof;\n\n\t// Update the concentrations at some grid points\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 1, surfacePos);\n\tupdatedConcOffset = updatedConc + 2 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 2, surfacePos);\n\tupdatedConcOffset = updatedConc + 3 * dof;\n\ttestFitFlux->computeIncidentFlux(\n\t\tcurrTime, updatedConcOffset, 3, surfacePos);\n\n\t// Check the value at some grid points\n\tBOOST_REQUIRE_CLOSE(newConcentration[9], 0.3168967, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[18], 0.306857, 0.01);\n\tBOOST_REQUIRE_CLOSE(newConcentration[27], 0.1762458, 0.01);\n\n\t// Finalize MPI\n\tMPI_Finalize();\n\n\treturn;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "81988ab4c132984d50d63addec303915a0b8f0d3", "size": 3191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/flux/W111FitFluxHandlerTester.cpp", "max_stars_repo_name": "ORNL-Fusion/xolotl", "max_stars_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-06-13T18:08:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T02:39:01.000Z", "max_issues_repo_path": "test/core/flux/W111FitFluxHandlerTester.cpp", "max_issues_repo_name": "ORNL-Fusion/xolotl", "max_issues_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2018-02-14T15:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T16:29:48.000Z", "max_forks_repo_path": "test/core/flux/W111FitFluxHandlerTester.cpp", "max_forks_repo_name": "ORNL-Fusion/xolotl", "max_forks_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-02-13T20:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T14:54:16.000Z", "avg_line_length": 28.7477477477, "max_line_length": 73, "alphanum_fraction": 0.7499216547, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1810858171278222}}
{"text": "/*\n * Copyright (c) 2011-2021, 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#pragma once\n\n#include \"dart/math/TriMesh.hpp\"\n\n#include <Eigen/Geometry>\n\n#include \"dart/math/Geometry.hpp\"\n\nnamespace dart {\nnamespace math {\n\n//==============================================================================\ntemplate <typename S>\nTriMesh<S>::TriMesh()\n{\n  // Do nothing\n}\n\n//==============================================================================\ntemplate <typename S>\nvoid TriMesh<S>::setTriangles(\n    const Vertices& vertices, const Triangles& triangles)\n{\n  clear();\n\n  this->mVertices = vertices;\n  mTriangles = triangles;\n}\n\n//==============================================================================\ntemplate <typename S>\nvoid TriMesh<S>::computeVertexNormals()\n{\n  computeTriangleNormals();\n\n  this->mVertexNormals.clear();\n  this->mVertexNormals.resize(this->mVertices.size(), Vector3::Zero());\n\n  for (auto i = 0u; i < mTriangles.size(); ++i)\n  {\n    auto& triangle = mTriangles[i];\n    this->mVertexNormals[triangle[0]] += mTriangleNormals[i];\n    this->mVertexNormals[triangle[1]] += mTriangleNormals[i];\n    this->mVertexNormals[triangle[2]] += mTriangleNormals[i];\n  }\n\n  this->normalizeVertexNormals();\n}\n\n//==============================================================================\ntemplate <typename S>\nbool TriMesh<S>::hasTriangles() const\n{\n  return !mTriangles.empty();\n}\n\n//==============================================================================\ntemplate <typename S>\nbool TriMesh<S>::hasTriangleNormals() const\n{\n  return hasTriangles() && mTriangles.size() == mTriangleNormals.size();\n}\n\n//==============================================================================\ntemplate <typename S>\nconst typename TriMesh<S>::Triangles& TriMesh<S>::getTriangles() const\n{\n  return mTriangles;\n}\n\n//==============================================================================\ntemplate <typename S>\nconst typename TriMesh<S>::Normals& TriMesh<S>::getTriangleNormals() const\n{\n  return mTriangleNormals;\n}\n\n//==============================================================================\ntemplate <typename S>\nvoid TriMesh<S>::clear()\n{\n  mTriangles.clear();\n  mTriangleNormals.clear();\n  Base::clear();\n}\n\n//==============================================================================\ntemplate <typename S>\nTriMesh<S> TriMesh<S>::operator+(const TriMesh& other) const\n{\n  return (TriMesh(*this) += other);\n}\n\n//==============================================================================\ntemplate <typename S>\nTriMesh<S>& TriMesh<S>::operator+=(const TriMesh& other)\n{\n  if (other.isEmpty())\n    return *this;\n\n  const auto oldNumVertices = this->mVertices.size();\n  const auto oldNumTriangles = mTriangles.size();\n\n  Base::operator+=(other);\n\n  // Insert triangle normals if both meshes have normals. Otherwise, clean the\n  // triangle normals.\n  if ((!hasTriangles() || hasTriangleNormals()) && other.hasTriangleNormals())\n  {\n    mTriangleNormals.insert(\n        mTriangleNormals.end(),\n        other.mTriangleNormals.begin(),\n        other.mTriangleNormals.end());\n  }\n  else\n  {\n    mTriangleNormals.clear();\n  }\n\n  const Triangle offset = Triangle::Constant(oldNumVertices);\n  mTriangles.resize(mTriangles.size() + other.mTriangles.size());\n  for (auto i = 0u; i < other.mTriangles.size(); ++i)\n  {\n    mTriangles[i + oldNumTriangles] = other.mTriangles[i] + offset;\n  }\n\n  return *this;\n}\n\n//==============================================================================\ntemplate <typename S>\nstd::shared_ptr<TriMesh<S>> TriMesh<S>::generateConvexHull(bool optimize) const\n{\n  auto triangles = Triangles();\n  auto vertices = Vertices();\n  std::tie(vertices, triangles)\n      = computeConvexHull3D<S, Index>(this->mVertices, optimize);\n\n  auto mesh = std::make_shared<TriMesh<S>>();\n  mesh->setTriangles(vertices, triangles);\n\n  return mesh;\n}\n\n//==============================================================================\ntemplate <typename S>\nvoid TriMesh<S>::computeTriangleNormals()\n{\n  mTriangleNormals.resize(mTriangles.size());\n\n  for (auto i = 0u; i < mTriangles.size(); ++i)\n  {\n    auto& triangle = mTriangles[i];\n    const Vector3 v01\n        = this->mVertices[triangle[1]] - this->mVertices[triangle[0]];\n    const Vector3 v02\n        = this->mVertices[triangle[2]] - this->mVertices[triangle[0]];\n    mTriangleNormals[i] = v01.cross(v02);\n  }\n\n  normalizeTriangleNormals();\n}\n\n//==============================================================================\ntemplate <typename S>\nvoid TriMesh<S>::normalizeTriangleNormals()\n{\n  for (auto& normal : mTriangleNormals)\n  {\n    normal.normalize();\n  }\n}\n\n} // namespace math\n} // namespace dart\n", "meta": {"hexsha": "10335343276031b027b622807725f572b057db08", "size": 6240, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/math/detail/TriMesh-impl.hpp", "max_stars_repo_name": "lakshmipathyarjun6/dart", "max_stars_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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": "dart/math/detail/TriMesh-impl.hpp", "max_issues_repo_name": "lakshmipathyarjun6/dart", "max_issues_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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/detail/TriMesh-impl.hpp", "max_forks_repo_name": "lakshmipathyarjun6/dart", "max_forks_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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": 30.0, "max_line_length": 80, "alphanum_fraction": 0.5860576923, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18108581021308356}}
{"text": "#ifndef MODEL_TRACKER_HPP\n#define MODEL_TRACKER_HPP\n\n#include <set>\n#include <boost/lexical_cast.hpp>\n\n#include \"../exrpc/exrpc.hpp\"\n/*\n#include \"frovedis/ml/glm/linear_model.hpp\"\n#include \"frovedis/ml/recommendation/matrix_factorization_model.hpp\"\n#include \"frovedis/ml/clustering/kmeans.hpp\"\n#include \"frovedis/ml/tree/tree_model.hpp\"\n#include \"frovedis/ml/fm/model.hpp\"\n#include \"frovedis/ml/nb/nb_model.hpp\"\n#include \"frovedis/ml/fpm/fp_growth_model.hpp\"\n#include \"frovedis/ml/clustering/spectral_clustering.hpp\"\n#include \"frovedis/ml/clustering/agglomerative.hpp\"\n*/\n\nusing namespace frovedis;\n\nenum MODEL_KIND {\n  GLM = 0,\n  LR,\n  SVM,\n  LNRM,\n  MFM,\n  KMEANS,\n  DTM,\n  NBM,\n  FMM,\n  FPM,\n  FPR,\n  ACM,\n  SCM,\n  SEM,\n  SPARSE_CONV_INFO,\n  W2V,\n  DBSCAN,\n  KNN,\n  KNC,\n  KNR,\n  LDA,\n  LDASP,\n  RFM,\n  GBT,\n  SVR,\n  KSVC,\n  RR,\n  LSR,\n  GMM,\n  STANDARDSCALER    \n};\n\nenum MAT_KIND {\n  RMJR = 1,\n  CMJR = 2,\n  BCLC = 3,\n  SCRS = 4,\n  SCCS = 5,\n  SELL = 6,\n  SHYBRID = 7,\n  RMJR_L = 101,\n  CMJR_L = 102,\n  BCLC_L = 103,\n  SCRS_L = 104,\n  SCCS_L = 105,\n  SELL_L = 106,\n  SHYBRID_L = 107\n};\n\nenum DTYPE {\n  INT = 1,\n  LONG = 2,\n  FLOAT = 3,\n  DOUBLE = 4,\n  STRING = 5,\n  BOOL = 6,\n  ULONG = 7,\n  WORDS = 8\n};\n\nenum OPTYPE {\n  // --- conditional ---\n  EQ = 1,\n  NE = 2,\n  GT = 3,\n  GE = 4,\n  LT = 5,\n  LE = 6,\n  // --- special conditional ---\n  AND = 11,\n  OR = 12,\n  NOT = 13,\n  LIKE = 14,\n  NLIKE = 15,\n  ISNULL = 16,\n  ISNOTNULL = 17,\n  // --- mathematical ---\n  ADD = 21,\n  SUB = 22,\n  MUL = 23,\n  IDIV = 24,\n  FDIV = 25,\n  MOD = 26,\n  POW = 27,\n  // --- aggregator ---\n  aMAX = 41,\n  aMIN = 42,\n  aSUM = 43,\n  aAVG = 44,\n  aVAR = 45,\n  aSEM = 46,\n  aSTD = 47,\n  aMAD = 48,\n  aCNT = 49,\n  aSIZE = 50,\n};\n\n// [MODEL_ID] => [MODEL_KIND, MODEL_PTR]\nextern std::map<int,std::pair<MODEL_KIND,exrpc_ptr_t>> model_table;\nextern std::set<int> deleted_model_tracker;\nextern std::set<int> under_training_model_tracker;\n\nvoid register_model(int mid, MODEL_KIND m, exrpc_ptr_t mptr);\nvoid register_for_train(int mid);\nvoid unregister_from_train(int mid);\nbool is_deleted(int mid);\nbool is_registered_model(int mid);\nbool is_under_training(int mid);\n\nvoid finalize_model_table();\nvoid finalize_trackers();\nvoid cleanup_frovedis_server();\nint get_numeric_dtype(const std::string& dt);\nstd::string get_string_dtype(short dt);\n\n// retuns the model head for the requested registered model id\ntemplate <class M>\nM* get_model_ptr(int mid) {\n  //std::cout<<\"inside get model ptr \\n\\n\";\n  if(model_table.find(mid) == model_table.end()) { // if not registered\n \n  //std::cout<<\"not registered \\n\\n\";\n    if(!is_under_training(mid)) { // if not under training\n     // std::cout<<\"not under training\\n\\n\";\n      std::string message = \"request for either non-registered or deleted model: [\";\n      message += boost::lexical_cast<std::string>(mid) + \" ]\\n\";\n      REPORT_ERROR(USER_ERROR, message);\n    }\n    else while(is_under_training(mid)); // waits until training is completed\n  }\n  auto p = model_table[mid];\n  return reinterpret_cast<M*>(p.second);\n}\n\n// convert a numeric string to number\ntemplate <class T>\nT do_cast (const std::string& data) {\n  T c_data = 0;\n  try {\n    c_data = boost::lexical_cast<T>(data);\n  }\n  catch (const boost::bad_lexical_cast &excpt) {\n    REPORT_ERROR(USER_ERROR, \"invalid type for casting: \" + data);\n  }\n  return c_data;\n}\n\ntemplate <>\nbool do_cast<bool>(const std::string& data);\n\n#endif\n", "meta": {"hexsha": "62b750e6cd1bf2f31f2a02ae7b8d92f166073e3e", "size": 3407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/foreign_if/server/model_tracker.hpp", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "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/foreign_if/server/model_tracker.hpp", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "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/foreign_if/server/model_tracker.hpp", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "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": 19.5804597701, "max_line_length": 84, "alphanum_fraction": 0.6515996478, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.18108580675571428}}
{"text": "#include <objectif-lune/Singleton.hpp>\n#include <iostream>\n#include <math.h>\n#include <boost/thread.hpp>\n\nint main(int argc, char *argv[])\n{\n\tstd::cout << \"starting example server\" << std::endl;\n\t\n\tobjectifLune::Server* server = objectifLune::Singleton::Get();\n\tserver->waitForConnections();\n\t\n\tfloat magic = 42;\n\t\n\tserver->registerVariable(\"tweak-me-variable\", &magic, 0, 100, \"pretty please\");\n\tserver->registerVariable(\"pure-magic\", &magic, 0, 100, \"asdfasdfasdf\");\n\t\n\tint delay = 50;\n\tunsigned long frameCounter = 0;\n\twhile(true)\n\t{\n\t\tserver->scalar(\"magic value\", magic);\n//\t\tserver->scalar(\"frame time\", 20.0f + (rand() & 100) / 20);\n//\t\tserver->scalar(\"long time field\", 2000.0f + (rand() & 1000) / 20);\n//\t\tserver->scalar(\"textures loaded\", (rand() & 9));\n//\t\tserver->scalar(\"lucky number\", (rand() & 99));\n//\t\tserver->scalar(\"fraction of a whole\", (float)(rand() & 99) /3.0f);\n//\t\t\n//\t\tserver->info(\"Uh, everything's under control. Situation normal.\");\n\t\t\n//\t\tfor (unsigned int i = 0; i < 10; i++) {\n//\t\t\tserver->data(frameCounter, \"acceleration\", sin(frameCounter / 100.0f));\t\t\t\n//\t\t\t\t\t\tserver->data(frameCounter, \"frame time\", (float)(rand() % 999999) / 100.0f);\n//\t\t\tserver->data(frameCounter, \"ASDFYygj/\", sin(frameCounter / 100.0f) + 1.2f);\t\t\t\n//\t\t\tserver->data(frameCounter, \"long name is looooooooooooooooong\", sin(frameCounter / 100.0f));\t\t\t\n//\t\t\tframeCounter++;\n//\t\t}\n\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(delay));\n\n//\t\tserver->trace(\"1 this is a trace message\");\n//\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(delay));\n//\t\tserver->debug(\"2 This debug message is a tad longer than the other messages, because it is very important and hence needs the extra space to express its meaning, position in the universe, and everything else.\");\n//\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(delay));\n//\t\tserver->info(\"3 This service is kindly provided by the intergallactic time traveling agency\");\n//\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(delay));\n//\t\tserver->warn(\"4 Final Warning!\");\n//\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(delay));\n//\t\tserver->error(\"5 There is an error in this message\");\n//\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(delay));\n//\t\tserver->fatal(\"6 Fatal message is fatal\");\n//\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(delay));\n\t}\n}\n", "meta": {"hexsha": "00d9da54c7aee4d123a13bb3ceaa6655a505f320", "size": 2393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "server/examples/example-server.cpp", "max_stars_repo_name": "SimonWallner/objectif-lune", "max_stars_repo_head_hexsha": "d8e4a49786c175d3071847564adbce694f50ebf2", "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": "server/examples/example-server.cpp", "max_issues_repo_name": "SimonWallner/objectif-lune", "max_issues_repo_head_hexsha": "d8e4a49786c175d3071847564adbce694f50ebf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/examples/example-server.cpp", "max_forks_repo_name": "SimonWallner/objectif-lune", "max_forks_repo_head_hexsha": "d8e4a49786c175d3071847564adbce694f50ebf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-22T22:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-22T22:18:21.000Z", "avg_line_length": 44.3148148148, "max_line_length": 215, "alphanum_fraction": 0.680317593, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.18103580663893926}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n#include \"ClStackWorkload.hpp\"\n#include \"ClWorkloadUtils.hpp\"\n#include <aclCommon/ArmComputeTensorUtils.hpp>\n#include <backendsCommon/CpuTensorHandle.hpp>\n#include <cl/ClTensorHandle.hpp>\n#include <cl/ClLayerSupport.hpp>\n\n#include <arm_compute/core/Types.h>\n\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/polymorphic_pointer_cast.hpp>\n\nnamespace armnn\n{\nusing namespace armcomputetensorutils;\n\nnamespace\n{\nint CalcAxis(const unsigned int axis, const unsigned int inputDimensions)\n{\n    const int intAxis = boost::numeric_cast<int>(axis);\n    return boost::numeric_cast<int>(inputDimensions) - intAxis;\n}\n} //namespace\n\narm_compute::Status ClStackWorkloadValidate(const std::vector<const TensorInfo*>& inputs,\n                                            const TensorInfo& output,\n                                            const StackDescriptor& descriptor)\n{\n    std::vector<arm_compute::ITensorInfo*> aclInputPtrs;\n    arm_compute::TensorInfo aclInputInfo;\n    for (const TensorInfo* input : inputs)\n    {\n        aclInputInfo = BuildArmComputeTensorInfo(*input);\n        aclInputPtrs.emplace_back(&aclInputInfo);\n    }\n    const arm_compute::TensorInfo aclOutputInfo = BuildArmComputeTensorInfo(output);\n\n    int aclAxis = CalcAxis(descriptor.m_Axis, descriptor.m_InputShape.GetNumDimensions());\n\n    return arm_compute::CLStackLayer::validate(aclInputPtrs, aclAxis, &aclOutputInfo);\n}\n\nClStackWorkload::ClStackWorkload(const StackQueueDescriptor& descriptor, const WorkloadInfo& info)\n: BaseWorkload<StackQueueDescriptor>(descriptor, info)\n{\n    std::vector<arm_compute::ICLTensor*> aclInputs;\n    for (auto input : m_Data.m_Inputs)\n    {\n        arm_compute::ICLTensor& aclInput = boost::polymorphic_pointer_downcast<IClTensorHandle>(input)->GetTensor();\n        aclInputs.emplace_back(&aclInput);\n    }\n    arm_compute::ICLTensor& output = boost::polymorphic_pointer_downcast<IClTensorHandle>(\n                                                                         m_Data.m_Outputs[0])->GetTensor();\n\n    m_Layer.reset(new arm_compute::CLStackLayer());\n    int aclAxis = CalcAxis(descriptor.m_Parameters.m_Axis, descriptor.m_Parameters.m_InputShape.GetNumDimensions());\n    m_Layer->configure(aclInputs, aclAxis, &output);\n}\n\nvoid ClStackWorkload::Execute() const\n{\n    if (m_Layer)\n    {\n        ARMNN_SCOPED_PROFILING_EVENT_CL(\"ClStackWorkload_Execute\");\n        m_Layer->run();\n    }\n}\n\n} //namespace armnn", "meta": {"hexsha": "3ba698ec4d194bd155ef20e20fdccd0a07de3741", "size": 2520, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/cl/workloads/ClStackWorkload.cpp", "max_stars_repo_name": "VinayKarnam/armnn", "max_stars_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-19T20:19:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-19T20:19:10.000Z", "max_issues_repo_path": "src/backends/cl/workloads/ClStackWorkload.cpp", "max_issues_repo_name": "VinayKarnam/armnn", "max_issues_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_issues_repo_licenses": ["MIT"], "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/backends/cl/workloads/ClStackWorkload.cpp", "max_forks_repo_name": "VinayKarnam/armnn", "max_forks_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T04:31:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T04:31:21.000Z", "avg_line_length": 34.0540540541, "max_line_length": 116, "alphanum_fraction": 0.7079365079, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.18103580174798345}}
{"text": "#include <mw/mmr/MMRUtil.h>\n#include <mw/crypto/Hasher.h>\n#include <mw/util/BitUtil.h>\n\n#include <boost/dynamic_bitset.hpp>\n#include <cmath>\n\nusing namespace mmr;\n\nmw::Hash MMRUtil::CalcParentHash(const Index& index, const mw::Hash& left_hash, const mw::Hash& right_hash)\n{\n    return Hasher()\n        .Append<uint64_t>(index.GetPosition())\n        .Append(left_hash)\n        .Append(right_hash)\n        .hash();\n}\n\nBitSet MMRUtil::BuildCompactBitSet(const uint64_t num_leaves, const BitSet& unspent_leaf_indices)\n{\n    BitSet compactable_node_indices(num_leaves * 2);\n\n    boost::dynamic_bitset<> prunable_nodes(num_leaves * 2);\n\n    LeafIndex leaf_idx = LeafIndex::At(0);\n    while (leaf_idx.Get() < num_leaves) {\n        if (unspent_leaf_indices.size() > leaf_idx.Get() && !unspent_leaf_indices.test(leaf_idx.Get())) {\n            prunable_nodes.set(leaf_idx.GetPosition());\n        }\n\n        leaf_idx = leaf_idx.Next();\n    }\n\n    LeafIndex next_leaf = LeafIndex::At(num_leaves);\n    Index last_node = Index::At(next_leaf.GetPosition() - 1);\n\n    uint64_t height = 1;\n    while ((std::pow(2, height + 1) - 2) <= next_leaf.GetPosition()) {\n        SiblingIter iter(height, last_node);\n        while (iter.Next()) {\n            Index right_child = iter.Get().GetRightChild();\n            if (prunable_nodes.test(right_child.GetPosition())) {\n                Index left_child = iter.Get().GetLeftChild();\n                if (prunable_nodes.test(left_child.GetPosition())) {\n                    compactable_node_indices.set(right_child.GetPosition());\n                    compactable_node_indices.set(left_child.GetPosition());\n                    prunable_nodes.set(iter.Get().GetPosition());\n                }\n            }\n        }\n\n        ++height;\n    }\n\n    return compactable_node_indices;\n}\n\nBitSet MMRUtil::DiffCompactBitSet(const BitSet& prev_compact, const BitSet& new_compact)\n{\n    BitSet diff;\n\n    for (size_t i = 0; i < new_compact.size(); i++) {\n        if (prev_compact.size() > i && prev_compact.test(i)) {\n            assert(new_compact.test(i));\n            continue;\n        }\n\n        diff.bitset.push_back(new_compact.test(i));\n    }\n\n    return diff;\n}\n\n/// <summary>\n/// An MMR can be rebuilt from the leaves and a small set of carefully chosen parent hashes.\n/// This calculates the positions of those parent hashes.\n/// </summary>\n/// <param name=\"unspent_leaf_indices\">The unspent leaf indices.</param>\n/// <returns>The pruned parent positions.</returns>\nBitSet MMRUtil::CalcPrunedParents(const BitSet& unspent_leaf_indices)\n{\n    BitSet ret(unspent_leaf_indices.size() * 2);\n\n    LeafIndex leaf_idx = LeafIndex::At(0);\n    while (leaf_idx.Get() < unspent_leaf_indices.size()) {\n        if (!unspent_leaf_indices.test(leaf_idx.Get())) {\n            ret.set(leaf_idx.GetPosition());\n        }\n\n        leaf_idx = leaf_idx.Next();\n    }\n\n    Index last_node = LeafIndex::At(unspent_leaf_indices.size()).GetNodeIndex();\n\n    uint64_t height = 1;\n    while ((std::pow(2, height + 1) - 2) <= last_node.GetPosition()) {\n        SiblingIter iter(height, last_node);\n        while (iter.Next()) {\n            Index right_child = iter.Get().GetRightChild();\n            if (ret.test(right_child.GetPosition())) {\n                Index left_child = iter.Get().GetLeftChild();\n                if (ret.test(left_child.GetPosition())) {\n                    ret.set(right_child.GetPosition(), false);\n                    ret.set(left_child.GetPosition(), false);\n                    ret.set(iter.Get().GetPosition());\n                }\n            }\n        }\n\n        ++height;\n    }\n\n\n    return ret;\n}\n\nSiblingIter::SiblingIter(const uint64_t height, const Index& last_node)\n    : m_height(height),\n    m_lastNode(last_node),\n    m_baseInc((uint64_t)std::pow(2, height + 1) - 1),\n    m_siblingNum(0),\n    m_next()\n{\n}\n\nbool SiblingIter::Next()\n{\n    if (m_siblingNum == 0) {\n        m_next = Index(m_baseInc - 1, m_height);\n    } else {\n        uint64_t increment = m_baseInc + BitUtil::CountRightmostZeros(m_siblingNum);\n        m_next = Index(m_next.GetPosition() + increment, m_height);\n    }\n\n    ++m_siblingNum;\n    return m_next <= m_lastNode;\n};", "meta": {"hexsha": "fb64b01f4523b2545fb4187fb09ac618bcc4c61c", "size": 4173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libmw/src/mmr/MMRUtil.cpp", "max_stars_repo_name": "litecoin-foundation/litecoin", "max_stars_repo_head_hexsha": "de61fa1580d0465edb16251a4db5267f6b1cd047", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2020-10-02T23:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T02:49:42.000Z", "max_issues_repo_path": "src/libmw/src/mmr/MMRUtil.cpp", "max_issues_repo_name": "litecoin-foundation/litecoin", "max_issues_repo_head_hexsha": "de61fa1580d0465edb16251a4db5267f6b1cd047", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2020-10-01T11:23:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-02T04:40:31.000Z", "max_forks_repo_path": "src/libmw/src/mmr/MMRUtil.cpp", "max_forks_repo_name": "litecoin-foundation/litecoin", "max_forks_repo_head_hexsha": "de61fa1580d0465edb16251a4db5267f6b1cd047", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-10-06T22:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T12:09:01.000Z", "avg_line_length": 30.4598540146, "max_line_length": 107, "alphanum_fraction": 0.6170620657, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.18103579453038132}}
{"text": "/* Authors: Lutong Wang and Bangqi Xu */\n/*\n * Copyright (c) 2019, The Regents of the University of California\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 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 REGENTS BE LIABLE FOR ANY DIRECT,\n * 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 <algorithm>\n#include <boost/polygon/polygon.hpp>\n#include <chrono>\n#include <random>\n#include <sstream>\n\n#include \"db/gcObj/gcNet.h\"\n#include \"db/gcObj/gcPin.h\"\n#include \"dr/FlexDR.h\"\n#include \"dr/FlexDR_graphics.h\"\n#include \"frProfileTask.h\"\n#include \"gc/FlexGC.h\"\n\nusing namespace std;\nusing namespace fr;\nnamespace gtl = boost::polygon;\n\n\nint beginDebugIter = std::numeric_limits<int>().max();\nstatic frSquaredDistance pt2boxDistSquare(const Point& pt, const Rect& box)\n\n{\n  frCoord dx = max(max(box.xMin() - pt.x(), pt.x() - box.xMax()), 0);\n  frCoord dy = max(max(box.yMin() - pt.y(), pt.y() - box.yMax()), 0);\n  return (frSquaredDistance) dx * dx + (frSquaredDistance) dy * dy;\n}\n\nstatic frSquaredDistance pt2ptDistSquare(const Point& pt1, const Point& pt2)\n{\n  frCoord dx = abs(pt1.x() - pt2.x());\n  frCoord dy = abs(pt1.y() - pt2.y());\n  return (frSquaredDistance) dx * dx + (frSquaredDistance) dy * dy;\n}\n\n// prlx = -dx, prly = -dy\n// dx > 0 : disjoint in x; dx = 0 : touching in x; dx < 0 : overlap in x\nstatic frSquaredDistance box2boxDistSquareNew(const Rect& box1,\n                                              const Rect& box2,\n                                              frCoord& dx,\n                                              frCoord& dy)\n{\n  dx = max(box1.xMin(), box2.xMin()) - min(box1.xMax(), box2.xMax());\n  dy = max(box1.yMin(), box2.yMin()) - min(box1.yMax(), box2.yMax());\n  return (frSquaredDistance) max(dx, 0) * max(dx, 0)\n         + (frSquaredDistance) max(dy, 0) * max(dy, 0);\n}\n\nvoid FlexDRWorker::modViaForbiddenThrough(const FlexMazeIdx& bi,\n                                          const FlexMazeIdx& ei,\n                                          ModCostType type)\n{\n  bool isHorz = (bi.y() == ei.y());\n\n  bool isLowerViaForbidden\n      = getTech()->isViaForbiddenThrough(bi.z(), true, isHorz);\n  bool isUpperViaForbidden\n      = getTech()->isViaForbiddenThrough(bi.z(), false, isHorz);\n\n  if (isHorz) {\n    for (int xIdx = bi.x(); xIdx < ei.x(); xIdx++) {\n      if (isLowerViaForbidden) {\n        switch (type) {\n          case subRouteShape:\n            gridGraph_.subRouteShapeCostVia(\n                xIdx, bi.y(), bi.z() - 1);  // safe access\n            break;\n          case addRouteShape:\n            gridGraph_.addRouteShapeCostVia(\n                xIdx, bi.y(), bi.z() - 1);  // safe access\n            break;\n          case subFixedShape:\n            gridGraph_.subFixedShapeCostVia(\n                xIdx, bi.y(), bi.z() - 1);  // safe access\n            break;\n          case addFixedShape:\n            gridGraph_.addFixedShapeCostVia(\n                xIdx, bi.y(), bi.z() - 1);  // safe access\n            break;\n          default:;\n        }\n      }\n\n      if (isUpperViaForbidden) {\n        switch (type) {\n          case subRouteShape:\n            gridGraph_.subRouteShapeCostVia(\n                xIdx, bi.y(), bi.z());  // safe access\n            break;\n          case addRouteShape:\n            gridGraph_.addRouteShapeCostVia(\n                xIdx, bi.y(), bi.z());  // safe access\n            break;\n          case subFixedShape:\n            gridGraph_.subFixedShapeCostVia(\n                xIdx, bi.y(), bi.z());  // safe access\n            break;\n          case addFixedShape:\n            gridGraph_.addFixedShapeCostVia(\n                xIdx, bi.y(), bi.z());  // safe access\n            break;\n          default:;\n        }\n      }\n    }\n  } else {\n    for (int yIdx = bi.y(); yIdx < ei.y(); yIdx++) {\n      if (isLowerViaForbidden) {\n        switch (type) {\n          case subRouteShape:\n            gridGraph_.subRouteShapeCostVia(\n                bi.x(), yIdx, bi.z() - 1);  // safe access\n            break;\n          case addRouteShape:\n            gridGraph_.addRouteShapeCostVia(\n                bi.x(), yIdx, bi.z() - 1);  // safe access\n            break;\n          case subFixedShape:\n            gridGraph_.subFixedShapeCostVia(\n                bi.x(), yIdx, bi.z() - 1);  // safe access\n            break;\n          case addFixedShape:\n            gridGraph_.addFixedShapeCostVia(\n                bi.x(), yIdx, bi.z() - 1);  // safe access\n            break;\n          default:;\n        }\n      }\n\n      if (isUpperViaForbidden) {\n        switch (type) {\n          case subRouteShape:\n            gridGraph_.subRouteShapeCostVia(\n                bi.x(), yIdx, bi.z());  // safe access\n            break;\n          case addRouteShape:\n            gridGraph_.addRouteShapeCostVia(\n                bi.x(), yIdx, bi.z());  // safe access\n            break;\n          case subFixedShape:\n            gridGraph_.subFixedShapeCostVia(\n                bi.x(), yIdx, bi.z());  // safe access\n            break;\n          case addFixedShape:\n            gridGraph_.addFixedShapeCostVia(\n                bi.x(), yIdx, bi.z());  // safe access\n            break;\n          default:;\n        }\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::modBlockedPlanar(const Rect& box, frMIdx z, bool setBlock)\n{\n  FlexMazeIdx mIdx1;\n  FlexMazeIdx mIdx2;\n  gridGraph_.getIdxBox(mIdx1, mIdx2, box);\n  for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n    for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n      if (setBlock) {\n        gridGraph_.setBlocked(i, j, z, frDirEnum::E);\n        gridGraph_.setBlocked(i, j, z, frDirEnum::N);\n        gridGraph_.setBlocked(i, j, z, frDirEnum::W);\n        gridGraph_.setBlocked(i, j, z, frDirEnum::S);\n      } else {\n        gridGraph_.resetBlocked(i, j, z, frDirEnum::E);\n        gridGraph_.resetBlocked(i, j, z, frDirEnum::N);\n        gridGraph_.resetBlocked(i, j, z, frDirEnum::W);\n        gridGraph_.resetBlocked(i, j, z, frDirEnum::S);\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::modBlockedVia(const Rect& box, frMIdx z, bool setBlock)\n{\n  FlexMazeIdx mIdx1;\n  FlexMazeIdx mIdx2;\n  gridGraph_.getIdxBox(mIdx1, mIdx2, box);\n  for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n    for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n      if (setBlock) {\n        gridGraph_.setBlocked(i, j, z, frDirEnum::U);\n        gridGraph_.setBlocked(i, j, z, frDirEnum::D);\n      } else {\n        gridGraph_.resetBlocked(i, j, z, frDirEnum::U);\n        gridGraph_.resetBlocked(i, j, z, frDirEnum::D);\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::modCornerToCornerSpacing_helper(const Rect& box,\n                                                   frMIdx z,\n                                                   ModCostType type)\n{\n  FlexMazeIdx p1, p2;\n  gridGraph_.getIdxBox(p1, p2, box, FlexGridGraph::isEnclosed);\n  for (int i = p1.x(); i <= p2.x(); i++) {\n    for (int j = p1.y(); j <= p2.y(); j++) {\n      switch (type) {\n        case subRouteShape:\n            gridGraph_.subRouteShapeCostPlanar(i, j, z);\n            break;\n        case addRouteShape:\n            gridGraph_.addRouteShapeCostPlanar(i, j, z);\n            break;\n        case subFixedShape:\n            gridGraph_.subFixedShapeCostPlanar(i, j, z);\n            break;\n        case addFixedShape:\n            gridGraph_.addFixedShapeCostPlanar(i, j, z);\n            break;\n        default:;\n      }\n    }\n  }\n}\nvoid FlexDRWorker::modCornerToCornerSpacing(const Rect& box,\n                                            frMIdx z,\n                                            ModCostType type)\n{\n  auto lNum = gridGraph_.getLayerNum(z);\n  frCoord halfwidth2 = getTech()->getLayer(lNum)->getWidth() / 2;\n  // spacing value needed\n  frCoord bloatDist = 0;\n  auto& cons = getTech()->getLayer(lNum)->getLef58CornerSpacingConstraints();\n  Rect bx;\n  for (auto& c : cons) {\n    bloatDist = c->findMax() + halfwidth2 - 1;\n    bx.init(box.xMin() - bloatDist,\n            box.yMin() - bloatDist,\n            box.xMin(),\n            box.yMin());  // ll box corner\n    modCornerToCornerSpacing_helper(bx, z, type);\n    bx.init(box.xMin() - bloatDist,\n            box.yMax(),\n            box.xMin(),\n            box.yMax() + bloatDist);  // ul box corner\n    modCornerToCornerSpacing_helper(bx, z, type);\n    bx.init(box.xMax(),\n            box.yMax(),\n            box.xMax() + bloatDist,\n            box.yMax() + bloatDist);  // ur box corner\n    modCornerToCornerSpacing_helper(bx, z, type);\n    bx.init(box.xMax(),\n            box.yMin() - bloatDist,\n            box.xMax() + bloatDist,\n            box.yMin());  // lr box corner\n    modCornerToCornerSpacing_helper(bx, z, type);\n    }\n}\n\nvoid FlexDRWorker::modMinSpacingCostPlanar(const Rect& box,\n                                           frMIdx z,\n                                           ModCostType type,\n                                           bool isBlockage,\n                                           frNonDefaultRule* ndr,\n                                           bool isMacroPin)\n{\n  auto lNum = gridGraph_.getLayerNum(z);\n  frCoord width1 = box.minDXDY();\n  frCoord length1 = box.maxDXDY();\n  // layer default width\n  frCoord width2 = getTech()->getLayer(lNum)->getWidth();\n  frCoord halfwidth2 = width2 / 2;\n  // spacing value needed\n  frCoord bloatDist = 0;\n  auto con = getTech()->getLayer(lNum)->getMinSpacing();\n  if (con) {\n    if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {\n      bloatDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();\n    } else if (con->typeId()\n               == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {\n      bloatDist\n          = (isBlockage && USEMINSPACING_OBS)\n                ? static_cast<frSpacingTablePrlConstraint*>(con)->findMin()\n                : static_cast<frSpacingTablePrlConstraint*>(con)->find(\n                    max(width1, width2), length1);\n    } else if (con->typeId()\n               == frConstraintTypeEnum::frcSpacingTableTwConstraint) {\n      bloatDist = (isBlockage && USEMINSPACING_OBS)\n                      ? static_cast<frSpacingTableTwConstraint*>(con)->findMin()\n                      : static_cast<frSpacingTableTwConstraint*>(con)->find(\n                          width1, width2, length1);\n    } else {\n      cout << \"Warning: min spacing rule not supporterd\" << endl;\n      return;\n    }\n  } else {\n    cout << \"Warning: no min spacing rule\" << endl;\n    return;\n  }\n  if (ndr)\n    bloatDist = max(bloatDist, ndr->getSpacing(z));\n  frSquaredDistance bloatDistSquare = bloatDist;\n  bloatDistSquare *= bloatDist;\n\n  FlexMazeIdx mIdx1, mPinLL;\n  FlexMazeIdx mIdx2, mPinUR;\n  // assumes width always > 2\n  Rect bx(box.xMin() - bloatDist - halfwidth2 + 1,\n           box.yMin() - bloatDist - halfwidth2 + 1,\n           box.xMax() + bloatDist + halfwidth2 - 1,\n           box.yMax() + bloatDist + halfwidth2 - 1);\n  gridGraph_.getIdxBox(mIdx1, mIdx2, bx);\n  if (isMacroPin && type == ModCostType::resetBlocked) {\n    Rect sBox(box.xMin() + width2/2, box.yMin() + width2/2, box.xMax() - width2/2, box.yMax() - width2/2);\n    gridGraph_.getIdxBox(mPinLL, mPinUR, sBox);\n  }\n  Point pt, pt1, pt2, pt3, pt4;\n  frSquaredDistance distSquare = 0;\n  int cnt = 0;\n  for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n    for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n      gridGraph_.getPoint(pt, i, j);\n      pt1.set(pt.x() + halfwidth2, pt.y() - halfwidth2);\n      pt2.set(pt.x() + halfwidth2, pt.y() + halfwidth2);\n      pt3.set(pt.x() - halfwidth2, pt.y() - halfwidth2);\n      pt4.set(pt.x() - halfwidth2, pt.y() + halfwidth2);\n      distSquare = min(pt2boxDistSquare(pt1, box), pt2boxDistSquare(pt2, box));\n      distSquare = min(pt2boxDistSquare(pt3, box), distSquare);\n      distSquare = min(pt2boxDistSquare(pt4, box), distSquare);\n      if (distSquare < bloatDistSquare) {\n        switch (type) {\n          case subRouteShape:\n            gridGraph_.subRouteShapeCostPlanar(i, j, z);  // safe access\n            break;\n          case addRouteShape:\n            gridGraph_.addRouteShapeCostPlanar(i, j, z);  // safe access\n            break;\n          case subFixedShape:\n            gridGraph_.subFixedShapeCostPlanar(i, j, z);  // safe access\n            break;\n          case addFixedShape:\n            gridGraph_.addFixedShapeCostPlanar(i, j, z);  // safe access\n            break;\n          case resetFixedShape:\n            gridGraph_.setFixedShapeCostPlanar(i, j, z, 0);  // safe access\n            break;\n          case setFixedShape:\n            gridGraph_.setFixedShapeCostPlanar(i, j, z, 1);  // safe access\n            break;\n          case resetBlocked:\n            if (isMacroPin) {\n              if (j >= mPinLL.y() && j <= mPinUR.y()) {\n                gridGraph_.resetBlocked(i, j, z, frDirEnum::E); \n                if (i == 0)\n                  gridGraph_.resetBlocked(i, j, z, frDirEnum::W); \n              }\n              if (i >= mPinLL.x() && i <= mPinUR.x()) {\n                gridGraph_.resetBlocked(i, j, z, frDirEnum::N); \n                if (j == 0)\n                  gridGraph_.resetBlocked(i, j, z, frDirEnum::S); \n              }\n            } else {\n              gridGraph_.resetBlocked(i, j, z, frDirEnum::E); \n              gridGraph_.resetBlocked(i, j, z, frDirEnum::N); \n              if (i == 0)\n                gridGraph_.resetBlocked(i, j, z, frDirEnum::W); \n              if (j == 0)\n                gridGraph_.resetBlocked(i, j, z, frDirEnum::S); \n            }\n            break;\n          case setBlocked:  // set blocked\n            gridGraph_.setBlocked(i, j, z, frDirEnum::E); \n            gridGraph_.setBlocked(i, j, z, frDirEnum::N); \n            if (i == 0)\n              gridGraph_.setBlocked(i, j, z, frDirEnum::W); \n            if (j == 0)\n              gridGraph_.setBlocked(i, j, z, frDirEnum::S); \n            break;\n          default:;\n        }\n        cnt++;\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::modMinSpacingCostVia_eol_helper(const Rect& box,\n                                                   const Rect& testBox,\n                                                   ModCostType type,\n                                                   bool isUpperVia,\n                                                   frMIdx i,\n                                                   frMIdx j,\n                                                   frMIdx z)\n{\n  frMIdx zIdx = isUpperVia ? z : z - 1;\n  if (testBox.overlaps(box)) {\n    switch (type) {\n      case subRouteShape:\n        gridGraph_.subRouteShapeCostVia(i, j, zIdx);\n        break;\n      case addRouteShape:\n        gridGraph_.addRouteShapeCostVia(i, j, zIdx);\n        break;\n      case subFixedShape:\n        gridGraph_.subFixedShapeCostVia(i, j, zIdx);  // safe access\n        break;\n      case addFixedShape:\n        gridGraph_.addFixedShapeCostVia(i, j, zIdx);  // safe access\n        break;\n      default:;\n    }\n  }\n}\n\nvoid FlexDRWorker::modMinSpacingCostVia_eol(const Rect& box,\n                                            const Rect& tmpBx,\n                                            ModCostType type,\n                                            bool isUpperVia,\n                                            const drEolSpacingConstraint& drCon,\n                                            frMIdx i,\n                                            frMIdx j,\n                                            frMIdx z)\n{\n  if (drCon.eolSpace == 0)\n    return;\n  Rect testBox;\n  frCoord eolSpace = drCon.eolSpace;\n  frCoord eolWidth = drCon.eolWidth;\n  frCoord eolWithin = drCon.eolWithin;\n  // eol to up and down\n  if (tmpBx.xMax() - tmpBx.xMin() <= eolWidth) {\n    testBox.init(tmpBx.xMin() - eolWithin,\n                 tmpBx.yMax(),\n                 tmpBx.xMax() + eolWithin,\n                 tmpBx.yMax() + eolSpace);\n    modMinSpacingCostVia_eol_helper(box, testBox, type, isUpperVia, i, j, z);\n\n    testBox.init(tmpBx.xMin() - eolWithin,\n                 tmpBx.yMin() - eolSpace,\n                 tmpBx.xMax() + eolWithin,\n                 tmpBx.yMin());\n    modMinSpacingCostVia_eol_helper(box, testBox, type, isUpperVia, i, j, z);\n  }\n  // eol to left and right\n  if (tmpBx.yMax() - tmpBx.yMin() <= eolWidth) {\n    testBox.init(tmpBx.xMax(),\n                 tmpBx.yMin() - eolWithin,\n                 tmpBx.xMax() + eolSpace,\n                 tmpBx.yMax() + eolWithin);\n    modMinSpacingCostVia_eol_helper(box, testBox, type, isUpperVia, i, j, z);\n\n    testBox.init(tmpBx.xMin() - eolSpace,\n                 tmpBx.yMin() - eolWithin,\n                 tmpBx.xMin(),\n                 tmpBx.yMax() + eolWithin);\n    modMinSpacingCostVia_eol_helper(box, testBox, type, isUpperVia, i, j, z);\n  }\n}\n\nvoid FlexDRWorker::modMinimumcutCostVia(const Rect& box,\n                                        frMIdx z,\n                                        ModCostType type,\n                                        bool isUpperVia)\n{\n  auto lNum = gridGraph_.getLayerNum(z);\n  frCoord width1 = box.minDXDY();\n  frCoord length1 = box.maxDXDY();\n  // default via dimension\n  frViaDef* viaDef = nullptr;\n  if (isUpperVia) {\n    viaDef = (lNum < getTech()->getTopLayerNum())\n                 ? getTech()->getLayer(lNum + 1)->getDefaultViaDef()\n                 : nullptr;\n  } else {\n    viaDef = (lNum > getTech()->getBottomLayerNum())\n                 ? getTech()->getLayer(lNum - 1)->getDefaultViaDef()\n                 : nullptr;\n  }\n  if (viaDef == nullptr) {\n    return;\n  }\n  frVia via(viaDef);\n  Rect viaBox(0, 0, 0, 0);\n  if (isUpperVia) {\n    via.getCutBBox(viaBox);\n  } else {\n    via.getCutBBox(viaBox);\n  }\n\n  FlexMazeIdx mIdx1, mIdx2;\n  Rect bx, tmpBx, sViaBox;\n  dbTransform xform;\n  Point pt;\n  frCoord dx, dy;\n  frVia sVia;\n  frMIdx zIdx = isUpperVia ? z : z - 1;\n  for (auto& con : getTech()->getLayer(lNum)->getMinimumcutConstraints()) {\n    // check via2cut to box\n    // check whether via can be placed on the pin\n    if ((!con->hasLength() || (con->hasLength() && length1 > con->getLength()))\n        && width1 > con->getWidth()) {\n      bool checkVia2 = false;\n      if (!con->hasConnection()) {\n        checkVia2 = true;\n      } else {\n        if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE\n            && isUpperVia) {\n          checkVia2 = true;\n        } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW\n                   && !isUpperVia) {\n          checkVia2 = true;\n        }\n      }\n      if (!checkVia2) {\n        continue;\n      }\n      // block via on pin\n      frCoord dist = 0;\n      if (con->hasLength()) {\n        dist = con->getDistance();\n        // conservative for macro pin\n        // TODO: revert the += to be more accurate and check qor change\n        dist += getTech()->getLayer(lNum)->getPitch();\n      }\n      // assumes width always > 2\n      bx.init(box.xMin() - dist - (viaBox.xMax() - 0) + 1,\n              box.yMin() - dist - (viaBox.yMax() - 0) + 1,\n              box.xMax() + dist + (0 - viaBox.xMin()) - 1,\n              box.yMax() + dist + (0 - viaBox.yMin()) - 1);\n      gridGraph_.getIdxBox(mIdx1, mIdx2, bx);\n\n      for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n        for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n          gridGraph_.getPoint(pt, i, j);\n          xform.setOffset(pt);\n          tmpBx = viaBox;\n          if (gridGraph_.isSVia(i, j, zIdx)) {\n            auto sViaDef = apSVia_[FlexMazeIdx(i, j, zIdx)]->getAccessViaDef();\n            sVia.setViaDef(sViaDef);\n            if (isUpperVia) {\n              sVia.getCutBBox(sViaBox);\n            } else {\n              sVia.getCutBBox(sViaBox);\n            }\n            tmpBx = sViaBox;\n          }\n          xform.apply(tmpBx);\n          box2boxDistSquareNew(box, tmpBx, dx, dy);\n          if (!con->hasLength()) {\n            if (dx <= 0 && dy <= 0) {\n              ;\n            } else {\n              continue;\n            }\n          } else {\n            if (dx > 0 && dy > 0 && dx + dy < dist) {\n              ;\n            } else {\n              continue;\n            }\n          }\n          switch (type) {\n            case subRouteShape:\n              gridGraph_.subRouteShapeCostVia(i, j, zIdx);  // safe access\n              break;\n            case addRouteShape:\n              gridGraph_.addRouteShapeCostVia(i, j, zIdx);  // safe access\n              break;\n            case subFixedShape:\n              gridGraph_.subFixedShapeCostVia(i, j, zIdx);  // safe access\n              break;\n            case addFixedShape:\n              gridGraph_.addFixedShapeCostVia(i, j, zIdx);  // safe access\n              break;\n            default:;\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::modMinSpacingCostVia(const Rect& box,\n                                        frMIdx z,\n                                        ModCostType type,\n                                        bool isUpperVia,\n                                        bool isCurrPs,\n                                        bool isBlockage,\n                                        frNonDefaultRule* ndr)\n{\n  auto lNum = gridGraph_.getLayerNum(z);\n  frCoord width1 = box.minDXDY();\n  frCoord length1 = box.maxDXDY();\n  // default via dimension\n  frViaDef* viaDef = nullptr;\n  if (isUpperVia) {\n    viaDef = (lNum < getTech()->getTopLayerNum())\n                 ? getTech()->getLayer(lNum + 1)->getDefaultViaDef()\n                 : nullptr;\n  } else {\n    viaDef = (lNum > getTech()->getBottomLayerNum())\n                 ? getTech()->getLayer(lNum - 1)->getDefaultViaDef()\n                 : nullptr;\n  }\n  if (viaDef == nullptr) {\n    return;\n  }\n  frVia via(viaDef);\n  Rect viaBox(0, 0, 0, 0);\n  if (isUpperVia) {\n    via.getLayer1BBox(viaBox);\n  } else {\n    via.getLayer2BBox(viaBox);\n  }\n  frCoord width2 = viaBox.minDXDY();\n  frCoord length2 = viaBox.maxDXDY();\n\n  // via prl should check min area patch metal if not fat via\n  frCoord defaultWidth = getTech()->getLayer(lNum)->getWidth();\n  bool isH\n      = (getTech()->getLayer(lNum)->getDir() == dbTechLayerDir::HORIZONTAL);\n  bool isFatVia = (isH) ? (viaBox.yMax() - viaBox.yMin() > defaultWidth)\n                        : (viaBox.xMax() - viaBox.xMin() > defaultWidth);\n\n  frCoord length2_mar = length2;\n  frCoord patchLength = 0;\n  if (!isFatVia) {\n    auto minAreaConstraint = getTech()->getLayer(lNum)->getAreaConstraint();\n    auto minArea = minAreaConstraint ? minAreaConstraint->getMinArea() : 0;\n    patchLength = frCoord(ceil(1.0 * minArea / defaultWidth\n                               / getTech()->getManufacturingGrid()))\n                  * frCoord(getTech()->getManufacturingGrid());\n    length2_mar = max(length2_mar, patchLength);\n  }\n\n  // spacing value needed\n  frCoord bloatDist = 0;\n  auto con = getTech()->getLayer(lNum)->getMinSpacing();\n  if (con) {\n    if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {\n      bloatDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();\n    } else if (con->typeId()\n               == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {\n      bloatDist\n          = (isBlockage && USEMINSPACING_OBS && !isFatVia)\n                ? static_cast<frSpacingTablePrlConstraint*>(con)->findMin()\n                : static_cast<frSpacingTablePrlConstraint*>(con)->find(\n                    max(width1, width2),\n                    isCurrPs ? (length2_mar) : min(length1, length2_mar));\n    } else if (con->typeId()\n               == frConstraintTypeEnum::frcSpacingTableTwConstraint) {\n      bloatDist = (isBlockage && USEMINSPACING_OBS && !isFatVia)\n                      ? static_cast<frSpacingTableTwConstraint*>(con)->findMin()\n                      : static_cast<frSpacingTableTwConstraint*>(con)->find(\n                          width1,\n                          width2,\n                          isCurrPs ? (length2_mar) : min(length1, length2_mar));\n    } else {\n      cout << \"Warning: min spacing rule not supporterd\" << endl;\n      return;\n    }\n  } else {\n    cout << \"Warning: no min spacing rule\" << endl;\n    return;\n  }\n  drEolSpacingConstraint drCon;\n  if (ndr) {\n    bloatDist = max(bloatDist, ndr->getSpacing(z));\n    drCon = ndr->getDrEolSpacingConstraint(z);\n  }\n  // other obj eol spc to curr obj\n  // no need to bloat eolWithin because eolWithin always < minSpacing\n  frCoord bloatDistEolX = 0;\n  frCoord bloatDistEolY = 0;\n  if (drCon.eolWidth == 0)\n    drCon = getTech()->getLayer(lNum)->getDrEolSpacingConstraint();\n  if (viaBox.xMax() - viaBox.xMin() <= drCon.eolWidth) {\n    bloatDistEolY = max(bloatDistEolY, drCon.eolSpace);\n  }\n  // eol left and right\n  if (viaBox.yMax() - viaBox.yMin() <= drCon.eolWidth) {\n    bloatDistEolX = max(bloatDistEolX, drCon.eolSpace);\n  }\n\n  FlexMazeIdx mIdx1;\n  FlexMazeIdx mIdx2;\n  // assumes width always > 2\n  Rect bx(\n      box.xMin() - max(bloatDist, bloatDistEolX) - (viaBox.xMax() - 0) + 1,\n      box.yMin() - max(bloatDist, bloatDistEolY) - (viaBox.yMax() - 0) + 1,\n      box.xMax() + max(bloatDist, bloatDistEolX) + (0 - viaBox.xMin()) - 1,\n      box.yMax() + max(bloatDist, bloatDistEolY) + (0 - viaBox.yMin()) - 1);\n  gridGraph_.getIdxBox(mIdx1, mIdx2, bx);\n  Point pt;\n  Rect tmpBx;\n  frSquaredDistance distSquare = 0;\n  frCoord dx, dy, prl;\n  dbTransform xform;\n  frCoord reqDist = 0;\n  Rect sViaBox;\n  frVia sVia;\n  frMIdx zIdx = isUpperVia ? z : z - 1;\n  for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n    for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n      gridGraph_.getPoint(pt, i, j);\n      xform.setOffset(pt);\n      tmpBx = viaBox;\n      if (gridGraph_.isSVia(i, j, zIdx)) {\n        auto sViaDef = apSVia_[FlexMazeIdx(i, j, zIdx)]->getAccessViaDef();\n        sVia.setViaDef(sViaDef);\n        if (isUpperVia) {\n          sVia.getLayer1BBox(sViaBox);\n        } else {\n          sVia.getLayer2BBox(sViaBox);\n        }\n        tmpBx = sViaBox;\n      }\n      xform.apply(tmpBx);\n      distSquare = box2boxDistSquareNew(box, tmpBx, dx, dy);\n      prl = max(-dx, -dy);\n      // curr is ps\n      if (isCurrPs) {\n        if (-dy >= 0 && prl == -dy) {\n          prl = viaBox.yMax() - viaBox.yMin();\n          // ignore svia effect here...\n          if (!isH && !isFatVia) {\n            prl = max(prl, patchLength);\n          }\n        } else if (-dx >= 0 && prl == -dx) {\n          prl = viaBox.xMax() - viaBox.xMin();\n          if (isH && !isFatVia) {\n            prl = max(prl, patchLength);\n          }\n        }\n      } else {\n        ;\n      }\n      if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {\n        reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();\n      } else if (con->typeId()\n                 == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {\n        reqDist\n            = (isBlockage && USEMINSPACING_OBS && !isFatVia)\n                  ? static_cast<frSpacingTablePrlConstraint*>(con)->findMin()\n                  : static_cast<frSpacingTablePrlConstraint*>(con)->find(\n                      max(width1, width2), prl);\n      } else if (con->typeId()\n                 == frConstraintTypeEnum::frcSpacingTableTwConstraint) {\n        reqDist = (isBlockage && USEMINSPACING_OBS && !isFatVia)\n                      ? static_cast<frSpacingTableTwConstraint*>(con)->findMin()\n                      : static_cast<frSpacingTableTwConstraint*>(con)->find(\n                          width1, width2, prl);\n      }\n      if (ndr)\n        reqDist = max(reqDist, ndr->getSpacing(z));\n      if (distSquare < (frSquaredDistance) reqDist * reqDist) {\n          switch (type) {\n            case subRouteShape:\n              gridGraph_.subRouteShapeCostVia(i, j, zIdx);  // safe access\n              break;\n            case addRouteShape:\n              gridGraph_.addRouteShapeCostVia(i, j, zIdx);  // safe access\n              break;\n            case subFixedShape:\n              gridGraph_.subFixedShapeCostVia(i, j, zIdx);  // safe access\n              break;\n            case addFixedShape:\n              gridGraph_.addFixedShapeCostVia(i, j, zIdx);  // safe access\n              break;\n            default:;\n          }\n      }\n      // eol, other obj to curr obj\n      modMinSpacingCostVia_eol(box, tmpBx, type, isUpperVia, drCon, i, j, z);\n    }\n  }\n}\n\n// eolType == 0: planer\n// eolType == 1: down\n// eolType == 2: up\nvoid FlexDRWorker::modEolSpacingCost_helper(const Rect& testbox,\n                                            frMIdx z,\n                                            ModCostType type,\n                                            int eolType)\n{\n  auto lNum = gridGraph_.getLayerNum(z);\n  Rect bx;\n  if (eolType == 0) {\n    // layer default width\n    frCoord width2 = getTech()->getLayer(lNum)->getWidth();\n    frCoord halfwidth2 = width2 / 2;\n    // assumes width always > 2\n    bx.init(testbox.xMin() - halfwidth2 + 1,\n            testbox.yMin() - halfwidth2 + 1,\n            testbox.xMax() + halfwidth2 - 1,\n            testbox.yMax() + halfwidth2 - 1);\n  } else {\n    // default via dimension\n    frViaDef* viaDef = nullptr;\n    if (eolType == 1) {\n      viaDef = (lNum > getTech()->getBottomLayerNum())\n                   ? getTech()->getLayer(lNum - 1)->getDefaultViaDef()\n                   : nullptr;\n    } else if (eolType == 2) {\n      viaDef = (lNum < getTech()->getTopLayerNum())\n                   ? getTech()->getLayer(lNum + 1)->getDefaultViaDef()\n                   : nullptr;\n    }\n    if (viaDef == nullptr) {\n      return;\n    }\n    frVia via(viaDef);\n    Rect viaBox(0, 0, 0, 0);\n    if (eolType == 2) {  // upper via\n      via.getLayer1BBox(viaBox);\n    } else {\n      via.getLayer2BBox(viaBox);\n    }\n    // assumes via bbox always > 2\n    bx.init(testbox.xMin() - (viaBox.xMax() - 0) + 1,\n            testbox.yMin() - (viaBox.yMax() - 0) + 1,\n            testbox.xMax() + (0 - viaBox.xMin()) - 1,\n            testbox.yMax() + (0 - viaBox.yMin()) - 1);\n  }\n\n  FlexMazeIdx mIdx1;\n  FlexMazeIdx mIdx2;\n  gridGraph_.getIdxBox(mIdx1, mIdx2, bx);  // >= bx\n\n  frVia sVia;\n  Rect sViaBox;\n  dbTransform xform;\n  Point pt;\n\n  for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n    for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n      if (eolType == 0) {\n        switch (type) {\n          case subRouteShape:\n            gridGraph_.subRouteShapeCostPlanar(i, j, z);  // safe access\n            break;\n          case addRouteShape:\n            gridGraph_.addRouteShapeCostPlanar(i, j, z);  // safe access\n            break;\n          case subFixedShape:\n            gridGraph_.subFixedShapeCostPlanar(i, j, z);  // safe access\n            break;\n          case addFixedShape:\n            gridGraph_.addFixedShapeCostPlanar(i, j, z);  // safe access\n            break;\n          case resetFixedShape:\n            gridGraph_.setFixedShapeCostPlanar(i, j, z, 0);  // safe access\n            break;\n          case setFixedShape:\n            gridGraph_.setFixedShapeCostPlanar(i, j, z, 1);  // safe access\n            break;\n          default:;\n        }\n      } else if (eolType == 1) {\n        if (gridGraph_.isSVia(i, j, z - 1)) {\n          gridGraph_.getPoint(pt, i, j);\n          auto sViaDef = apSVia_[FlexMazeIdx(i, j, z - 1)]->getAccessViaDef();\n          sVia.setViaDef(sViaDef);\n          sVia.setOrigin(pt);\n          sVia.getLayer2BBox(sViaBox);\n          if (!sViaBox.overlaps(testbox)) {\n            continue;\n          }\n        }\n        switch (type) {\n          case subRouteShape:\n            gridGraph_.subRouteShapeCostVia(i, j, z - 1);  // safe access\n            break;\n          case addRouteShape:\n            gridGraph_.addRouteShapeCostVia(i, j, z - 1);  // safe access\n            break;\n          case subFixedShape:\n            gridGraph_.subFixedShapeCostVia(i, j, z - 1);  // safe access\n            break;\n          case addFixedShape:\n            gridGraph_.addFixedShapeCostVia(i, j, z - 1);  // safe access\n            break;\n          default:;\n        }\n      } else if (eolType == 2) {\n        if (gridGraph_.isSVia(i, j, z)) {\n          gridGraph_.getPoint(pt, i, j);\n          auto sViaDef = apSVia_[FlexMazeIdx(i, j, z)]->getAccessViaDef();\n          sVia.setViaDef(sViaDef);\n          sVia.setOrigin(pt);\n          sVia.getLayer1BBox(sViaBox);\n          if (!sViaBox.overlaps(testbox)) {\n            continue;\n          }\n        }\n        switch (type) {\n          case subRouteShape:\n            gridGraph_.subRouteShapeCostVia(i, j, z);  // safe access\n            break;\n          case addRouteShape:\n            gridGraph_.addRouteShapeCostVia(i, j, z);  // safe access\n            break;\n          case subFixedShape:\n            gridGraph_.subFixedShapeCostVia(i, j, z);  // safe access\n            break;\n          case addFixedShape:\n            gridGraph_.addFixedShapeCostVia(i, j, z);  // safe access\n            break;\n          default:;\n        }\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::modEolSpacingRulesCost(const Rect& box,\n                                          frMIdx z,\n                                          ModCostType type,\n                                          bool isSkipVia,\n                                          frNonDefaultRule* ndr)\n{\n  auto layer = getTech()->getLayer(gridGraph_.getLayerNum(z));\n  drEolSpacingConstraint drCon;\n  if (ndr != nullptr)\n    drCon = ndr->getDrEolSpacingConstraint(z);\n  if (drCon.eolWidth == 0)\n    drCon = layer->getDrEolSpacingConstraint();\n  frCoord eolSpace, eolWidth, eolWithin;\n  eolSpace = drCon.eolSpace;\n  eolWithin = drCon.eolWithin;\n  eolWidth = drCon.eolWidth;\n  if (eolSpace == 0)\n    return;\n  Rect testBox;\n  if (box.xMax() - box.xMin() <= eolWidth) {\n    testBox.init(box.xMin() - eolWithin,\n                 box.yMax(),\n                 box.xMax() + eolWithin,\n                 box.yMax() + eolSpace);\n    // if (!isInitDR()) {\n    modEolSpacingCost_helper(testBox, z, type, 0);\n    if (!isSkipVia) {\n      modEolSpacingCost_helper(testBox, z, type, 1);\n      modEolSpacingCost_helper(testBox, z, type, 2);\n    }\n    testBox.init(box.xMin() - eolWithin,\n                 box.yMin() - eolSpace,\n                 box.xMax() + eolWithin,\n                 box.yMin());\n    modEolSpacingCost_helper(testBox, z, type, 0);\n    if (!isSkipVia) {\n      modEolSpacingCost_helper(testBox, z, type, 1);\n      modEolSpacingCost_helper(testBox, z, type, 2);\n    }\n  }\n  // eol to left and right\n  if (box.yMax() - box.yMin() <= eolWidth) {\n    testBox.init(box.xMax(),\n                 box.yMin() - eolWithin,\n                 box.xMax() + eolSpace,\n                 box.yMax() + eolWithin);\n    modEolSpacingCost_helper(testBox, z, type, 0);\n    if (!isSkipVia) {\n      modEolSpacingCost_helper(testBox, z, type, 1);\n      modEolSpacingCost_helper(testBox, z, type, 2);\n    }\n    testBox.init(box.xMin() - eolSpace,\n                 box.yMin() - eolWithin,\n                 box.xMin(),\n                 box.yMax() + eolWithin);\n    modEolSpacingCost_helper(testBox, z, type, 0);\n    if (!isSkipVia) {\n      modEolSpacingCost_helper(testBox, z, type, 1);\n      modEolSpacingCost_helper(testBox, z, type, 2);\n    }\n  }\n}\n\n// forbid via if it would trigger violation\nvoid FlexDRWorker::modAdjCutSpacingCost_fixedObj(const frDesign* design,\n                                                 const Rect& origCutBox,\n                                                 frVia* origVia)\n{\n  if (!origVia->getNet()->getType().isSupply()) {\n    return;\n  }\n  auto lNum = origVia->getViaDef()->getCutLayerNum();\n  for (auto con : getTech()->getLayer(lNum)->getCutSpacing()) {\n    if (con->getAdjacentCuts() == -1) {\n      continue;\n    }\n    bool hasFixedViol = false;\n\n    gtl::point_data<frCoord> origCenter(\n        (origCutBox.xMin() + origCutBox.xMax()) / 2,\n        (origCutBox.yMin() + origCutBox.yMax()) / 2);\n    gtl::rectangle_data<frCoord> origCutRect(origCutBox.xMin(),\n                                             origCutBox.yMin(),\n                                             origCutBox.xMax(),\n                                             origCutBox.yMax());\n\n    Rect viaBox;\n    origVia->getCutBBox(viaBox);\n\n    frSquaredDistance reqDistSquare = con->getCutSpacing();\n    reqDistSquare *= reqDistSquare;\n\n    auto cutWithin = con->getCutWithin();\n    Rect queryBox;\n    viaBox.bloat(cutWithin, queryBox);\n\n    frRegionQuery::Objects<frBlockObject> result;\n    design->getRegionQuery()->query(queryBox, lNum, result);\n\n    for (auto& [box, obj] : result) {\n      if (obj->typeId() == frcVia) {\n        auto via = static_cast<frVia*>(obj);\n        if (!via->getNet()->getType().isSupply()) {\n          continue;\n        }\n        if (origCutBox == box) {\n          continue;\n        }\n\n        gtl::rectangle_data<frCoord> cutRect(\n            box.xMin(), box.yMin(), box.xMax(), box.yMax());\n        gtl::point_data<frCoord> cutCenterPt((box.xMin() + box.xMax()) / 2,\n                                             (box.yMin() + box.yMax()) / 2);\n\n        frSquaredDistance distSquare = 0;\n        if (con->hasCenterToCenter()) {\n          distSquare = gtl::distance_squared(origCenter, cutCenterPt);\n        } else {\n          distSquare = gtl::square_euclidean_distance(origCutRect, cutRect);\n        }\n\n        if (distSquare < reqDistSquare) {\n          hasFixedViol = true;\n          break;\n        }\n      }\n    }\n\n    // block adjacent via idx if will trigger violation\n    // pessimistic since block a box\n    if (hasFixedViol) {\n      FlexMazeIdx mIdx1, mIdx2;\n      Rect spacingBox;\n      auto reqDist = con->getCutSpacing();\n      auto cutWidth = getTech()->getLayer(lNum)->getWidth();\n      if (con->hasCenterToCenter()) {\n        spacingBox.init(origCenter.x() - reqDist,\n                        origCenter.y() - reqDist,\n                        origCenter.x() + reqDist,\n                        origCenter.y() + reqDist);\n      } else {\n        origCutBox.bloat(reqDist + cutWidth / 2, spacingBox);\n      }\n      gridGraph_.getIdxBox(mIdx1, mIdx2, spacingBox);\n\n      frMIdx zIdx\n          = gridGraph_.getMazeZIdx(origVia->getViaDef()->getLayer1Num());\n      for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n        for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n          gridGraph_.setBlocked(i, j, zIdx, frDirEnum::U);\n        }\n      }\n    }\n  }\n}\n\n/*inline*/ void FlexDRWorker::modCutSpacingCost(const Rect& box,\n                                                frMIdx z,\n                                                ModCostType type,\n                                                bool isBlockage,\n                                                int avoidI,\n                                                int avoidJ)\n{\n  auto lNum = gridGraph_.getLayerNum(z) + 1;\n  auto cutLayer = getTech()->getLayer(lNum);\n  if (!cutLayer->hasCutSpacing()\n      && !cutLayer->hasLef58DiffNetCutSpcTblConstraint()) {\n    return;\n  }\n  // obj1 = curr obj\n  // obj2 = other obj\n  // default via dimension\n  frViaDef* viaDef = cutLayer->getDefaultViaDef();\n  frVia via(viaDef);\n  Rect viaBox(0, 0, 0, 0);\n  via.getCutBBox(viaBox);\n\n  // spacing value needed\n  frCoord bloatDist = 0;\n  for (auto con : cutLayer->getCutSpacing()) {\n    bloatDist = max(bloatDist, con->getCutSpacing());\n    if (con->getAdjacentCuts() != -1 && isBlockage) {\n      bloatDist = max(bloatDist, con->getCutWithin());\n    }\n  }\n  frLef58CutSpacingTableConstraint* lef58con = nullptr;\n  std::pair<frCoord, frCoord> lef58conSpc;\n  if (cutLayer->hasLef58DiffNetCutSpcTblConstraint())\n    lef58con = cutLayer->getLef58DiffNetCutSpcTblConstraint();\n\n  if (lef58con != nullptr) {\n    lef58conSpc = lef58con->getDefaultSpacing();\n    bloatDist = max(bloatDist, std::max(lef58conSpc.first, lef58conSpc.second));\n  }\n\n  FlexMazeIdx mIdx1;\n  FlexMazeIdx mIdx2;\n  // assumes width always > 2\n  Rect bx(box.xMin() - bloatDist - (viaBox.xMax() - 0) + 1,\n           box.yMin() - bloatDist - (viaBox.yMax() - 0) + 1,\n           box.xMax() + bloatDist + (0 - viaBox.xMin()) - 1,\n           box.yMax() + bloatDist + (0 - viaBox.yMin()) - 1);\n  gridGraph_.getIdxBox(mIdx1, mIdx2, bx);\n\n  Point pt;\n  Rect tmpBx;\n  frSquaredDistance distSquare = 0;\n  frSquaredDistance c2cSquare = 0;\n  frCoord dx, dy, prl;\n  dbTransform xform;\n  frSquaredDistance reqDistSquare = 0;\n  Point boxCenter, tmpBxCenter;\n  boxCenter.set((box.xMin() + box.xMax()) / 2, (box.yMin() + box.yMax()) / 2);\n  frSquaredDistance currDistSquare = 0;\n  bool hasViol;\n  for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n    for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n        if (i == avoidI && j == avoidJ)\n            continue;\n      for (auto& uFig : via.getViaDef()->getCutFigs()) {\n        auto obj = static_cast<frRect*>(uFig.get());\n        gridGraph_.getPoint(pt, i, j);\n        xform.setOffset(pt);\n        obj->getBBox(tmpBx);\n        xform.apply(tmpBx);\n        tmpBxCenter.set((tmpBx.xMin() + tmpBx.xMax()) / 2,\n                        (tmpBx.yMin() + tmpBx.yMax()) / 2);\n        distSquare = box2boxDistSquareNew(box, tmpBx, dx, dy);\n        c2cSquare = pt2ptDistSquare(boxCenter, tmpBxCenter);\n        prl = max(-dx, -dy);\n        hasViol = false;\n        for (auto con : cutLayer->getCutSpacing()) {\n          reqDistSquare = con->getCutSpacing();\n          reqDistSquare *= con->getCutSpacing();\n          currDistSquare = con->hasCenterToCenter() ? c2cSquare : distSquare;\n          if (con->hasSameNet()) {\n            continue;\n          }\n          if (con->isLayer()) {\n            ;\n          } else if (con->isAdjacentCuts()) {\n            // OBS always count as within distance instead of cut spacing\n            if (isBlockage) {\n              reqDistSquare = con->getCutWithin();\n              reqDistSquare *= con->getCutWithin();\n            }\n            if (currDistSquare < reqDistSquare) {\n              hasViol = true;\n              // should disable hasViol and modify this part to new grid graph\n            }\n          } else if (con->isParallelOverlap()) {\n            if (prl > 0 && currDistSquare < reqDistSquare) {\n              hasViol = true;\n            }\n          } else if (con->isArea()) {\n            auto currArea = max(box.maxDXDY() * box.minDXDY(),\n                                tmpBx.maxDXDY() * tmpBx.minDXDY());\n            if (currArea >= con->getCutArea()\n                && currDistSquare < reqDistSquare) {\n              hasViol = true;\n            }\n          } else if (currDistSquare < reqDistSquare) {\n            hasViol = true;\n          }\n          if (hasViol)\n            break;\n        }\n        if (!hasViol && lef58con != nullptr) {\n          bool center2center = false;\n          if (prl > 0)\n            reqDistSquare = lef58conSpc.second;\n          else\n            reqDistSquare = lef58conSpc.first;\n          if (lef58con->getDefaultCenterAndEdge())\n            if ((frCoord) reqDistSquare\n                == std::max(lef58conSpc.first, lef58conSpc.second))\n              center2center = true;\n          if (lef58con->getDefaultCenterToCenter())\n            center2center = true;\n          reqDistSquare *= reqDistSquare;\n          if (center2center)\n            currDistSquare = c2cSquare;\n          else\n            currDistSquare = distSquare;\n          if (currDistSquare < reqDistSquare)\n            hasViol = true;\n        }\n\n        if (hasViol) {\n          switch (type) {\n            case subRouteShape:\n              gridGraph_.subRouteShapeCostVia(i, j, z);  // safe access\n              break;\n            case addRouteShape:\n              gridGraph_.addRouteShapeCostVia(i, j, z);  // safe access\n              break;\n            case subFixedShape:\n              gridGraph_.subFixedShapeCostVia(i, j, z);  // safe access\n              break;\n            case addFixedShape:\n              gridGraph_.addFixedShapeCostVia(i, j, z);  // safe access\n              break;\n            default:;\n          }\n          break;\n        }\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::modInterLayerCutSpacingCost(const Rect& box,\n                                               frMIdx z,\n                                               ModCostType type,\n                                               bool isUpperVia,\n                                               bool isBlockage)\n{\n  auto cutLayerNum1 = gridGraph_.getLayerNum(z) + 1;\n  auto cutLayerNum2 = isUpperVia ? cutLayerNum1 + 2 : cutLayerNum1 - 2;\n  auto z2 = isUpperVia ? z + 1 : z - 1;\n  if (cutLayerNum2 > getTech()->getTopLayerNum()\n      || cutLayerNum2 < getTech()->getBottomLayerNum())\n    return;\n  frLayer* layer1 = getTech()->getLayer(cutLayerNum1);\n  frLayer* layer2 = getTech()->getLayer(cutLayerNum2);\n\n  frViaDef* viaDef = nullptr;\n  viaDef = layer2->getDefaultViaDef();\n\n  if (viaDef == nullptr) {\n    return;\n  }\n  frCutSpacingConstraint* con\n      = layer1->getInterLayerCutSpacing(cutLayerNum2, false);\n  if (con == nullptr) {\n    con = layer2->getInterLayerCutSpacing(cutLayerNum1, false);\n  }\n  // LEF58_SPACINGTABLE START\n  frLef58CutSpacingTableConstraint* lef58con;\n  std::pair<frCoord, frCoord> lef58conSpc;\n  if (!isUpperVia)\n    lef58con = layer1->getLef58DefaultInterCutSpcTblConstraint();\n  else\n    lef58con = layer2->getLef58DefaultInterCutSpcTblConstraint();\n\n  if (lef58con != nullptr) {\n    auto dbRule = lef58con->getODBRule();\n    if (!isUpperVia && dbRule->getSecondLayer()->getName() != layer2->getName())\n      lef58con = nullptr;\n    if (isUpperVia && dbRule->getSecondLayer()->getName() != layer1->getName())\n      lef58con = nullptr;\n  }\n  // LEF58_SPACINGTABLE END\n  if (con == nullptr && lef58con == nullptr)\n    return;\n\n  // obj1 = curr obj\n  // obj2 = other obj\n  // default via dimension\n  frVia via(viaDef);\n  Rect viaBox(0, 0, 0, 0);\n  via.getCutBBox(viaBox);\n\n  // spacing value needed\n  frCoord bloatDist = 0;\n  if (con != nullptr)\n    bloatDist = con->getCutSpacing();\n  if (lef58con != nullptr) {\n    lef58conSpc = lef58con->getDefaultSpacing();\n    bloatDist\n        = std::max(bloatDist, std::max(lef58conSpc.first, lef58conSpc.second));\n  }\n\n  FlexMazeIdx mIdx1;\n  FlexMazeIdx mIdx2;\n  // assumes width always > 2\n  Rect bx(box.xMin() - bloatDist - (viaBox.xMax() - 0) + 1,\n           box.yMin() - bloatDist - (viaBox.yMax() - 0) + 1,\n           box.xMax() + bloatDist + (0 - viaBox.xMin()) - 1,\n           box.yMax() + bloatDist + (0 - viaBox.yMin()) - 1);\n  gridGraph_.getIdxBox(mIdx1, mIdx2, bx);\n\n  Point pt;\n  Rect tmpBx;\n  frSquaredDistance distSquare = 0;\n  frSquaredDistance c2cSquare = 0;\n  frCoord prl, dx, dy;\n  dbTransform xform;\n  frSquaredDistance reqDistSquare = 0;\n  Point boxCenter, tmpBxCenter;\n  boxCenter.set((box.xMin() + box.xMax()) / 2, (box.yMin() + box.yMax()) / 2);\n  frSquaredDistance currDistSquare = 0;\n  bool hasViol = false;\n  for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {\n    for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {\n      for (auto& uFig : via.getViaDef()->getCutFigs()) {\n        auto obj = static_cast<frRect*>(uFig.get());\n        gridGraph_.getPoint(pt, i, j);\n        xform.setOffset(pt);\n        obj->getBBox(tmpBx);\n        xform.apply(tmpBx);\n        tmpBxCenter.set((tmpBx.xMin() + tmpBx.xMax()) / 2,\n                        (tmpBx.yMin() + tmpBx.yMax()) / 2);\n        distSquare = box2boxDistSquareNew(box, tmpBx, dx, dy);\n        c2cSquare = pt2ptDistSquare(boxCenter, tmpBxCenter);\n        prl = max(-dx, -dy);\n        hasViol = false;\n        if (con != nullptr) {\n          reqDistSquare = con->getCutSpacing();\n          reqDistSquare *= reqDistSquare;\n          currDistSquare = con->hasCenterToCenter() ? c2cSquare : distSquare;\n          if (currDistSquare < reqDistSquare)\n            hasViol = true;\n        }\n        if (!hasViol && lef58con != nullptr) {\n          bool center2center = false;\n          if (prl > 0)\n            reqDistSquare = lef58conSpc.second;\n          else\n            reqDistSquare = lef58conSpc.first;\n          if (lef58con->getDefaultCenterAndEdge())\n            if ((frCoord) reqDistSquare\n                == std::max(lef58conSpc.first, lef58conSpc.second))\n              center2center = true;\n          if (lef58con->getDefaultCenterToCenter())\n            center2center = true;\n          reqDistSquare *= reqDistSquare;\n          currDistSquare = center2center ? c2cSquare : distSquare;\n          if (currDistSquare < reqDistSquare)\n            hasViol = true;\n        }\n\n        if (hasViol) {\n          switch (type) {\n            case subRouteShape:\n              gridGraph_.subRouteShapeCostVia(i, j, z2);  // safe access\n              break;\n            case addRouteShape:\n              gridGraph_.addRouteShapeCostVia(i, j, z2);  // safe access\n              break;\n            case subFixedShape:\n              gridGraph_.subFixedShapeCostVia(i, j, z2);  // safe access\n              break;\n            case addFixedShape:\n              gridGraph_.addFixedShapeCostVia(i, j, z2);  // safe access\n              break;\n            default:;\n          }\n          break;\n        }\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::addPathCost(drConnFig* connFig, bool modEol, bool modCutSpc)\n{\n  modPathCost(connFig, ModCostType::addRouteShape, modEol, modCutSpc);\n}\n\nvoid FlexDRWorker::subPathCost(drConnFig* connFig, bool modEol, bool modCutSpc)\n{\n  modPathCost(connFig, ModCostType::subRouteShape, modEol, modCutSpc);\n}\n\nvoid FlexDRWorker::modPathCost(drConnFig* connFig,\n                               ModCostType type,\n                               bool modEol,\n                               bool modCutSpc)\n{\n  frNonDefaultRule* ndr = nullptr;\n  if (connFig->typeId() == drcPathSeg) {\n    auto obj = static_cast<drPathSeg*>(connFig);\n    FlexMazeIdx bi, ei;\n    obj->getMazeIdx(bi, ei);\n    // new\n    Rect box;\n    obj->getBBox(box);\n    ndr = !obj->isTapered() ? connFig->getNet()->getFrNet()->getNondefaultRule()\n                            : nullptr;\n    modMinSpacingCostPlanar(box, bi.z(), type, false, ndr);\n    modMinSpacingCostVia(box, bi.z(), type, true, true, false, ndr);\n    modMinSpacingCostVia(box, bi.z(), type, false, true, false, ndr);\n    modViaForbiddenThrough(bi, ei, type);\n    if (modEol) {\n      // wrong way wire cannot have eol problem: (1) with via at end, then via\n      // will add eol cost; (2) with pref-dir wire, then not eol edge\n      bool isHLayer\n          = (getTech()->getLayer(gridGraph_.getLayerNum(bi.z()))->getDir()\n             == dbTechLayerDir::HORIZONTAL);\n      if (isHLayer == (bi.y() == ei.y())) {\n        modEolSpacingRulesCost(box, bi.z(), type, false, ndr);\n      }\n    }\n  } else if (connFig->typeId() == drcPatchWire) {\n    auto obj = static_cast<drPatchWire*>(connFig);\n    frMIdx zIdx = gridGraph_.getMazeZIdx(obj->getLayerNum());\n    Rect box;\n    obj->getBBox(box);\n    ndr = connFig->getNet()->getFrNet()->getNondefaultRule();\n    modMinSpacingCostPlanar(box, zIdx, type, false, ndr);\n    modMinSpacingCostVia(box, zIdx, type, true, true, false, ndr);\n    modMinSpacingCostVia(box, zIdx, type, false, true, false, ndr);\n    if (modEol)\n        modEolSpacingRulesCost(box, zIdx, type);\n  } else if (connFig->typeId() == drcVia) {\n    auto obj = static_cast<drVia*>(connFig);\n    FlexMazeIdx bi, ei;\n    obj->getMazeIdx(bi, ei);\n    // new\n\n    Rect box;\n    obj->getLayer1BBox(box);  // assumes enclosure for via is always rectangle\n    ndr = connFig->getNet()->getFrNet()->getNondefaultRule();\n    modMinSpacingCostPlanar(box, bi.z(), type, false, ndr);\n    modMinSpacingCostVia(box, bi.z(), type, true, false, false, ndr);\n    modMinSpacingCostVia(box, bi.z(), type, false, false, false, ndr);\n    if (modEol)\n      modEolSpacingRulesCost(box, bi.z(), type, false, ndr);\n\n    obj->getLayer2BBox(box);  // assumes enclosure for via is always rectangle\n\n    modMinSpacingCostPlanar(box, ei.z(), type, false, ndr);\n    modMinSpacingCostVia(box, ei.z(), type, true, false, false, ndr);\n    modMinSpacingCostVia(box, ei.z(), type, false, false, false, ndr);\n    if (modEol)\n      modEolSpacingRulesCost(box, ei.z(), type, false, ndr);\n\n    dbTransform xform;\n    Point pt;\n    obj->getOrigin(pt);\n    xform.setOffset(pt);\n    for (auto& uFig : obj->getViaDef()->getCutFigs()) {\n      auto rect = static_cast<frRect*>(uFig.get());\n      rect->getBBox(box);\n      xform.apply(box);\n      if (modCutSpc)\n        modCutSpacingCost(box, bi.z(), type);\n      modInterLayerCutSpacingCost(box, bi.z(), type, true);\n      modInterLayerCutSpacingCost(box, bi.z(), type, false);\n    }\n  }\n}\n\nbool FlexDRWorker::mazeIterInit_sortRerouteNets(int mazeIter,\n                                                vector<drNet*>& rerouteNets)\n{\n  auto rerouteNetsComp = [](drNet* const& a, drNet* const& b) {\n    if (a->getFrNet()->getAbsPriorityLvl() > b->getFrNet()->getAbsPriorityLvl())\n      return true;\n    if (a->getFrNet()->getAbsPriorityLvl() < b->getFrNet()->getAbsPriorityLvl())\n      return false;\n    Rect boxA, boxB;\n    a->getPinBox(boxA);\n    b->getPinBox(boxB);\n    auto areaA = boxA.area();\n    auto areaB = boxB.area();\n    return (a->getNumPinsIn() == b->getNumPinsIn()\n                ? (areaA == areaB ? a->getId() < b->getId() : areaA < areaB)\n                : a->getNumPinsIn() < b->getNumPinsIn());\n  };\n  // sort\n  if (mazeIter == 0) {\n    sort(rerouteNets.begin(), rerouteNets.end(), rerouteNetsComp);\n    // to be removed\n    if (OR_SEED != -1 && rerouteNets.size() >= 2) {\n      uniform_int_distribution<int> distribution(0, rerouteNets.size() - 1);\n      default_random_engine generator(OR_SEED);\n      int numSwap = (double) (rerouteNets.size()) * OR_K;\n      for (int i = 0; i < numSwap; i++) {\n        int idx = distribution(generator);\n        swap(rerouteNets[idx], rerouteNets[(idx + 1) % rerouteNets.size()]);\n      }\n    }\n  }\n  return true;\n}\n\nvoid FlexDRWorker::mazeNetInit(drNet* net)\n{\n  gridGraph_.resetStatus();\n  gridGraph_.setNDR(net->getFrNet()->getNondefaultRule());\n  // sub term / instterm cost when net is about to route\n  initMazeCost_terms(net->getFrNetTerms(), false, true);\n  // sub via access cost when net is about to route\n  // route_queue does not need to reserve\n  if (isFollowGuide()) {\n    initMazeCost_guide_helper(net, true);\n  }\n  // add minimum cut cost from objs in ext ring when the net is about to route\n  initMazeCost_minCut_helper(net, true);\n  initMazeCost_ap_helper(net, false);\n  initMazeCost_boundary_helper(net, false);\n}\n\nvoid FlexDRWorker::mazeNetEnd(drNet* net)\n{\n  // add term / instterm cost back when net is about to end\n  initMazeCost_terms(net->getFrNetTerms(), true, true);\n  if (isFollowGuide()) {\n    initMazeCost_guide_helper(net, false);\n  }\n  // sub minimum cut cost from vias in ext ring when the net is about to end\n  initMazeCost_minCut_helper(net, false);\n  initMazeCost_ap_helper(net, true);\n  initMazeCost_boundary_helper(net, true);\n  gridGraph_.setNDR(nullptr);\n  gridGraph_.setDstTaperBox(nullptr);\n}\n\nvoid FlexDRWorker::route_queue()\n{\n  queue<RouteQueueEntry> rerouteQueue;\n\n  if (needRecheck_) {\n    gcWorker_->main();\n    setMarkers(gcWorker_->getMarkers());\n  }\n  if (getDRIter() >= beginDebugIter) {\n    logger_->info(DRT,\n                  2001,\n                  \"Starting worker ({} {}) ({} {}) with {} markers\",\n                  getRouteBox().ll().x(),\n                  getRouteBox().ll().y(),\n                  getRouteBox().ur().x(),\n                  getRouteBox().ur().y(),\n                  markers_.size());\n    for (auto& marker : markers_) {\n      cout << marker << \"\\n\";\n    }\n    if (needRecheck_)\n      cout << \"(Needs recheck)\\n\";\n  }\n\n  // init net status\n  route_queue_resetRipup();\n  // init marker cost\n  route_queue_addMarkerCost();\n  // init reroute queue\n  // route_queue_init_queue(rerouteNets);\n  route_queue_init_queue(rerouteQueue);\n\n  if (graphics_ && !rerouteQueue.empty()) {\n    graphics_->startWorker(this);\n  }\n\n  // route\n  route_queue_main(rerouteQueue);\n  // end\n  gcWorker_->resetTargetNet();\n  gcWorker_->setEnableSurgicalFix(true);\n  gcWorker_->main();\n  // write back GC patches\n  for (auto& pwire : gcWorker_->getPWires()) {\n    auto net = pwire->getNet();\n    if (!net) {\n      cout << \"Error: pwire with no net\\n\";\n      exit(1);\n    }\n    auto tmpPWire = make_unique<drPatchWire>();\n    tmpPWire->setLayerNum(pwire->getLayerNum());\n    Point origin;\n    pwire->getOrigin(origin);\n    tmpPWire->setOrigin(origin);\n    Rect box;\n    pwire->getOffsetBox(box);\n    tmpPWire->setOffsetBox(box);\n    tmpPWire->addToNet(net);\n\n    unique_ptr<drConnFig> tmp(std::move(tmpPWire));\n    auto& workerRegionQuery = getWorkerRegionQuery();\n    workerRegionQuery.add(tmp.get());\n    net->addRoute(std::move(tmp));\n  }\n\n  gcWorker_->end();\n\n  setMarkers(gcWorker_->getMarkers());\n\n  for (auto& net : nets_) {\n    net->setBestRouteConnFigs();\n  }\n  setBestMarkers();\n  if (graphics_) {\n    graphics_->show(true);\n  }\n  \n  if (getDRIter() >= 7 && getDRIter() <= 30)\n    identifyCongestionLevel();\n}\n\nvoid FlexDRWorker::identifyCongestionLevel() {\n    vector<drNet*> bpNets;\n    for (auto& uNet : nets_) {\n        drNet* net = uNet.get();\n        bool bpLow = false, bpHigh = false;\n        for (auto& uPin : net->getPins()) {\n            drPin* pin = uPin.get();\n            if (pin->hasFrTerm())\n                continue;\n            for (auto& uAP : pin->getAccessPatterns()) {\n                drAccessPattern* ap = uAP.get();\n                if (design_->isVerticalLayer(ap->getBeginLayerNum())) {\n                    if (ap->getPoint().y() == getRouteBox().yMin())\n                        bpLow = true;\n                    else if (ap->getPoint().y() == getRouteBox().yMax())\n                        bpHigh = true;\n                } else {\n                    if (ap->getPoint().x() == getRouteBox().xMin())\n                        bpLow = true;\n                    else if (ap->getPoint().x() == getRouteBox().xMax())\n                        bpHigh = true;\n                }\n            }\n        }\n        if (bpLow && bpHigh)\n             bpNets.push_back(net);\n    }\n    vector<int> nLowBorderCross(gridGraph_.getLayerCount(), 0);\n    vector<int> nHighBorderCross(gridGraph_.getLayerCount(), 0);\n    for (drNet*net : bpNets) {\n        for (auto& uPin : net->getPins()) {\n            drPin* pin = uPin.get();\n            if (pin->hasFrTerm())\n                continue;\n            for (auto& uAP : pin->getAccessPatterns()) {\n                drAccessPattern* ap = uAP.get();\n                frMIdx z = gridGraph_.getMazeZIdx(ap->getBeginLayerNum());\n                if (z < 4) \n                \tcontinue;\n                if (design_->isVerticalLayer(ap->getBeginLayerNum())) {\n                    if (ap->getPoint().y() == getRouteBox().yMin())\n                        nLowBorderCross[z]++;\n                    else if (ap->getPoint().y() == getRouteBox().yMax())\n                        nHighBorderCross[z]++;\n                } else {\n                    if (ap->getPoint().x() == getRouteBox().xMin())\n                        nLowBorderCross[z]++;\n                    else if (ap->getPoint().x() == getRouteBox().xMax())\n                        nHighBorderCross[z]++;\n                }\n            }\n        }\n    }\n    for (int z = 0; z < gridGraph_.getLayerCount(); z++) {\n        frLayerNum lNum = gridGraph_.getLayerNum(z);\n        auto& trackPatterns = design_->getTopBlock()->getTrackPatterns(lNum);\n        frTrackPattern* tp = nullptr;\n        int workerSize;\n        if (design_->isHorizontalLayer(lNum)) { \n            for (auto& utp : trackPatterns) {\n                if (!utp->isHorizontal()) //reminder: trackPattern isHorizontal means vertical tracks\n                    tp = utp.get();\n            }\n            workerSize = getRouteBox().dy();\n        } else {\n            for (auto& utp : trackPatterns) {\n                if (utp->isHorizontal())\n                    tp = utp.get();\n            }\n            workerSize = getRouteBox().dx();\n        }\n        if (tp == nullptr)\n            continue;\n        int nTracks = workerSize/tp->getTrackSpacing(); //1 track error margin\n        float congestionFactorLow = nLowBorderCross[z]/(float)nTracks;\n        float congestionFactorHigh = nHighBorderCross[z]/(float)nTracks;\n        float finalFactor = max(congestionFactorLow, congestionFactorHigh);\n        if (finalFactor >= CONGESTION_THRESHOLD) {\n            isCongested_ = true;\n            return;\n        }\n    }\n}\n\nvoid FlexDRWorker::route_queue_main(queue<RouteQueueEntry>& rerouteQueue)\n{\n  auto& workerRegionQuery = getWorkerRegionQuery();\n  while (!rerouteQueue.empty()) {\n    auto& entry = rerouteQueue.front();\n    frBlockObject* obj = entry.block;\n    bool doRoute = entry.doRoute;\n    int numReroute = entry.numReroute;\n\n    rerouteQueue.pop();\n    bool didRoute = false;\n    bool didCheck = false;\n\n    if (obj->typeId() == drcNet && doRoute) {\n      auto net = static_cast<drNet*>(obj);\n      if (numReroute != net->getNumReroutes()) {\n        continue;\n      }\n      // init\n      net->setModified(true);\n      if (net->getFrNet()) {\n        net->getFrNet()->setModified(true);\n      }\n      net->setNumMarkers(0);\n      if (graphics_)\n        graphics_->startNet(net);\n      for (auto& uConnFig : net->getRouteConnFigs()) {\n        subPathCost(uConnFig.get());\n        workerRegionQuery.remove(uConnFig.get());  // worker region query\n      }\n      modEolCosts_poly(gcWorker_->getNet(net->getFrNet()),\n                       ModCostType::subRouteShape);\n      // route_queue need to unreserve via access if all nets are ripupped\n      // (i.e., not routed) see route_queue_init_queue this\n      // is unreserve via via is reserved only when drWorker starts from nothing\n      // and via is reserved\n      if (net->getNumReroutes() == 0 && getRipupMode() == 1) {\n        initMazeCost_via_helper(net, false);\n      }\n      net->clear();\n      if (getDRIter() >= beginDebugIter)\n        logger_->info(DRT, 2002, \"Routing net {}\", net->getFrNet()->getName());\n      // route\n      mazeNetInit(net);\n      bool isRouted = routeNet(net);\n      if (isRouted == false) {\n        if (OUT_MAZE_FILE == string(\"\")) {\n          if (VERBOSE > 0) {\n            cout << \"Waring: no output maze log specified, skipped writing \"\n                    \"maze log\"\n                 << endl;\n          }\n        } else {\n          gridGraph_.print();\n        }\n        if (graphics_) {\n          graphics_->show(false);\n        }\n        // TODO Rect can't be logged directly\n        stringstream routeBoxStringStream;\n        routeBoxStringStream << getRouteBox();\n        logger_->error(DRT,\n                       255,\n                       \"Maze Route cannot find path of net {} in \"\n                       \"worker of routeBox {}.\",\n                       net->getFrNet()->getName(),\n                       routeBoxStringStream.str());\n      }\n      mazeNetEnd(net);\n      net->addNumReroutes();\n      didRoute = true;\n      // gc\n      if (gcWorker_->setTargetNet(net->getFrNet())) {\n        gcWorker_->updateDRNet(net);\n        gcWorker_->setEnableSurgicalFix(true);\n        gcWorker_->main();\n        modEolCosts_poly(gcWorker_->getTargetNet(), ModCostType::addRouteShape);\n        // write back GC patches\n        for (auto& pwire : gcWorker_->getPWires()) {\n          auto net = pwire->getNet();\n          auto tmpPWire = make_unique<drPatchWire>();\n          tmpPWire->setLayerNum(pwire->getLayerNum());\n          Point origin;\n          pwire->getOrigin(origin);\n          tmpPWire->setOrigin(origin);\n          Rect box;\n          pwire->getOffsetBox(box);\n          tmpPWire->setOffsetBox(box);\n          tmpPWire->addToNet(net);\n\n          unique_ptr<drConnFig> tmp(std::move(tmpPWire));\n          auto& workerRegionQuery = getWorkerRegionQuery();\n          workerRegionQuery.add(tmp.get());\n          net->addRoute(std::move(tmp));\n        }\n        if (getDRIter() >= beginDebugIter && !getGCWorker()->getMarkers().empty()) {\n          logger_->info(DRT,\n                        2003,\n                        \"Ending net {} with markers:\",\n                        net->getFrNet()->getName());\n          for (auto& marker : getGCWorker()->getMarkers()) {\n            cout << *marker << \"\\n\";\n          }\n        }\n        didCheck = true;\n      } else {\n        logger_->error(DRT, 1006, \"failed to setTargetNet\");\n      }\n    } else {\n      gcWorker_->setEnableSurgicalFix(false);\n      if (obj->typeId() == frcNet) {\n        auto net = static_cast<frNet*>(obj);\n        if (gcWorker_->setTargetNet(net)) {\n          gcWorker_->main();\n          didCheck = true;\n        }\n      } else {\n        if (gcWorker_->setTargetNet(obj)) {\n          gcWorker_->main();\n          didCheck = true;\n        }\n      }\n    }\n    // end\n    if (didCheck) {\n      route_queue_update_queue(gcWorker_->getMarkers(), rerouteQueue);\n    }\n    if (didRoute) {\n      route_queue_markerCostDecay();\n    }\n    if (didCheck) {\n      route_queue_addMarkerCost(gcWorker_->getMarkers());\n    }\n\n    if (graphics_) {\n      if (obj->typeId() == drcNet && doRoute) {\n        auto net = static_cast<drNet*>(obj);\n        graphics_->endNet(net);\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::modEolCosts_poly(gcPin* shape,\n                                    frLayer* layer,\n                                    ModCostType modType)\n{\n  auto eol = layer->getDrEolSpacingConstraint();\n  if (eol.eolSpace == 0)\n    return;\n  for (auto& edges : shape->getPolygonEdges()) {\n    for (auto& edge : edges) {\n      if (edge->length() >= eol.eolWidth)\n        continue;\n      frCoord low, high, line;\n      bool innerDirIsIncreasing;  // x: increases to the east, y: increases to\n                                  // the north\n      if (edge->isVertical()) {\n        low = min(edge->low().y(), edge->high().y());\n        high = max(edge->low().y(), edge->high().y());\n        line = edge->low().x();\n        innerDirIsIncreasing = edge->getInnerDir() == frDirEnum::E;\n      } else {\n        low = min(edge->low().x(), edge->high().x());\n        high = max(edge->low().x(), edge->high().x());\n        line = edge->low().y();\n        innerDirIsIncreasing = edge->getInnerDir() == frDirEnum::N;\n      }\n      modEolCost(low,\n                 high,\n                 line,\n                 edge->isVertical(),\n                 innerDirIsIncreasing,\n                 layer,\n                 modType);\n    }\n  }\n}\n//mods eol cost for an eol edge\nvoid FlexDRWorker::modEolCost(frCoord low,\n                              frCoord high,\n                              frCoord line,\n                              bool isVertical,\n                              bool innerDirIsIncreasing,\n                              frLayer* layer,\n                              ModCostType modType)\n{\n  Rect testBox;\n  auto eol = layer->getDrEolSpacingConstraint();\n  if (isVertical) {\n    if (innerDirIsIncreasing)\n      testBox.init(line - eol.eolSpace, low - eol.eolWithin, line, high + eol.eolWithin);\n    else \n      testBox.init(line, low - eol.eolWithin, line + eol.eolSpace, high + eol.eolWithin);\n  } else {\n    if (innerDirIsIncreasing)\n      testBox.init(low - eol.eolWithin, line - eol.eolSpace, high + eol.eolWithin, line);\n    else \n      testBox.init(low - eol.eolWithin, line, high + eol.eolWithin, line + eol.eolSpace);\n  }\n  frMIdx z = gridGraph_.getMazeZIdx(layer->getLayerNum());\n  modEolSpacingCost_helper(testBox, z, modType, 0);\n  modEolSpacingCost_helper(testBox, z, modType, 1);\n  modEolSpacingCost_helper(testBox, z, modType, 2);\n}\n\nvoid FlexDRWorker::cleanUnneededPatches_poly(gcNet* drcNet, drNet* net)\n{\n    vector<vector<float>> areaMap(getTech()->getTopLayerNum()+1);\n    vector<drPatchWire*> patchesToRemove;\n    for (auto& shape : net->getRouteConnFigs()) {\n        if (shape->typeId() != frBlockObjectEnum::drcPatchWire)\n            continue;\n        drPatchWire* patch = static_cast<drPatchWire*>(shape.get());\n        gtl::point_data<frCoord> pt(patch->getOrigin().x(), patch->getOrigin().y());\n        frLayerNum lNum = patch->getLayerNum();\n        frCoord minArea = getTech()->getLayer(lNum)->getAreaConstraint()->getMinArea();\n        if (areaMap[lNum].empty())\n            areaMap[lNum].assign(drcNet->getPins(lNum).size(), -1);\n        for (int i = 0; i < drcNet->getPins(lNum).size(); i++) {\n            auto& pin = drcNet->getPins(lNum)[i];\n            if (!gtl::contains(*pin->getPolygon(), pt))\n                continue;\n            frCoord area;\n            if (areaMap[lNum][i] == -1)\n                areaMap[lNum][i] = gtl::area(*pin->getPolygon());\n            area = areaMap[lNum][i];\n            if (area - patch->getOffsetBox().area() >= minArea) {\n                patchesToRemove.push_back(patch);\n                areaMap[lNum][i] -= patch->getOffsetBox().area();\n            }\n        }\n    }\n    for (auto patch : patchesToRemove) {\n        getWorkerRegionQuery().remove(patch);\n        net->removeShape(patch);\n    }\n}\n\nvoid FlexDRWorker::modEolCosts_poly(gcNet* net, ModCostType modType)\n{\n  for (int lNum = getTech()->getBottomLayerNum();\n       lNum <= getTech()->getTopLayerNum();\n       lNum++) {\n    auto layer = getTech()->getLayer(lNum);\n    if (layer->getType() != dbTechLayerType::ROUTING)\n      continue;\n    for (auto& pin : net->getPins(lNum)) {\n      modEolCosts_poly(pin.get(), layer, modType);\n    }\n  }\n}\n\nvoid FlexDRWorker::routeNet_prep(\n    drNet* net,\n    set<drPin*, frBlockObjectComp>& unConnPins,\n    map<FlexMazeIdx, set<drPin*, frBlockObjectComp>>& mazeIdx2unConnPins,\n    set<FlexMazeIdx>& apMazeIdx,\n    set<FlexMazeIdx>& realPinAPMazeIdx,\n    map<FlexMazeIdx, frBox3D*>& mazeIdx2Tbox,\n    list<pair<drPin*, frBox3D>>& pinTaperBoxes)\n{\n  frBox3D* tbx = nullptr;\n  if (getDRIter() >= beginDebugIter)\n    logger_->info(DRT, 2005, \"Creating dest search points from pins:\");\n  for (auto& pin : net->getPins()) {\n    if (getDRIter() >= beginDebugIter)\n      logger_->info(DRT, 2006, \"Pin {}\", pin->getName());\n    unConnPins.insert(pin.get());\n    if (gridGraph_.getNDR()) {\n      if (AUTO_TAPER_NDR_NETS\n          && pin->isInstPin()) {  // create a taper box for each pin\n        FlexMazeIdx l, h;\n        pin->getAPBbox(l, h);\n        frMIdx z;\n        frCoord pitch\n            = getTech()->getLayer(gridGraph_.getLayerNum(l.z()))->getPitch(),\n            r;\n        r = TAPERBOX_RADIUS;\n        l.set(gridGraph_.getMazeXIdx(gridGraph_.xCoord(l.x()) - r * pitch),\n              gridGraph_.getMazeYIdx(gridGraph_.yCoord(l.y()) - r * pitch),\n              l.z());\n        h.set(gridGraph_.getMazeXIdx(gridGraph_.xCoord(h.x()) + r * pitch),\n              gridGraph_.getMazeYIdx(gridGraph_.yCoord(h.y()) + r * pitch),\n              h.z());\n        z = l.z() == 0 ? 1 : h.z();\n        pinTaperBoxes.push_back(std::make_pair(\n            pin.get(), frBox3D(l.x(), l.y(), h.x(), h.y(), l.z(), z)));\n        tbx = &std::prev(pinTaperBoxes.end())->second;\n        for (z = tbx->zLow(); z <= tbx->zHigh();\n             z++) {  // populate the map from points to taper boxes\n          for (int x = tbx->xMin(); x <= tbx->xMax(); x++)\n            for (int y = tbx->yMin(); y <= tbx->yMax(); y++)\n              mazeIdx2Tbox[FlexMazeIdx(x, y, z)] = tbx;\n        }\n      }\n    }\n    for (auto& ap : pin->getAccessPatterns()) {\n      FlexMazeIdx mi;\n      ap->getMazeIdx(mi);\n      if (getDRIter() >= beginDebugIter) {\n        logger_->info(DRT,\n                      2007,\n                      \"({} {} {} coords: {} {} {}\\n\",\n                      mi.x(),\n                      mi.y(),\n                      mi.z(),\n                      ap->getPoint().x(),\n                      ap->getPoint().y(),\n                      ap->getBeginLayerNum());\n      }\n      mazeIdx2unConnPins[mi].insert(pin.get());\n      if (pin->hasFrTerm()) {\n        realPinAPMazeIdx.insert(mi);\n      }\n      apMazeIdx.insert(mi);\n      gridGraph_.setDst(mi);\n    }\n  }\n}\n\nvoid FlexDRWorker::routeNet_setSrc(\n    set<drPin*, frBlockObjectComp>& unConnPins,\n    map<FlexMazeIdx, set<drPin*, frBlockObjectComp>>& mazeIdx2unConnPins,\n    vector<FlexMazeIdx>& connComps,\n    FlexMazeIdx& ccMazeIdx1,\n    FlexMazeIdx& ccMazeIdx2,\n    Point& centerPt)\n{\n  frMIdx xDim, yDim, zDim;\n  gridGraph_.getDim(xDim, yDim, zDim);\n  ccMazeIdx1.set(xDim - 1, yDim - 1, zDim - 1);\n  ccMazeIdx2.set(0, 0, 0);\n  // first pin selection algorithm goes here\n  // choose the center pin\n  centerPt.set(0, 0);\n  int totAPCnt = 0;\n  frCoord totX = 0;\n  frCoord totY = 0;\n  frCoord totZ = 0;\n  FlexMazeIdx mi;\n  Point bp;\n  for (auto& pin : unConnPins) {\n    for (auto& ap : pin->getAccessPatterns()) {\n      ap->getMazeIdx(mi);\n      ap->getPoint(bp);\n      totX += bp.x();\n      totY += bp.y();\n      centerPt.set(centerPt.x() + bp.x(), centerPt.y() + bp.y());\n      totZ += gridGraph_.getZHeight(mi.z());\n      totAPCnt++;\n      break;\n    }\n  }\n  totX /= totAPCnt;\n  totY /= totAPCnt;\n  totZ /= totAPCnt;\n  centerPt.set(centerPt.x() / totAPCnt, centerPt.y() / totAPCnt);\n\n  // select the farmost pin\n  drPin* currPin = nullptr;\n\n  frCoord currDist = 0;\n  for (auto& pin : unConnPins) {\n    for (auto& ap : pin->getAccessPatterns()) {\n      ap->getMazeIdx(mi);\n      ap->getPoint(bp);\n      frCoord dist = abs(totX - bp.x()) + abs(totY - bp.y())\n                     + abs(totZ - gridGraph_.getZHeight(mi.z()));\n      if (dist >= currDist) {\n        currDist = dist;\n        currPin = pin;\n      }\n    }\n  }\n\n  unConnPins.erase(currPin);\n  // first pin selection algorithm ends here\n  for (auto& ap : currPin->getAccessPatterns()) {\n    ap->getMazeIdx(mi);\n    connComps.push_back(mi);\n    if (getDRIter() >= beginDebugIter) {\n      logger_->info(DRT,\n                    2000,\n                    \"({} {} {} coords: {} {} {}\\n\",\n                    mi.x(),\n                    mi.y(),\n                    mi.z(),\n                    ap->getPoint().x(),\n                    ap->getPoint().y(),\n                    ap->getBeginLayerNum());\n    }\n    ccMazeIdx1.set(min(ccMazeIdx1.x(), mi.x()),\n                   min(ccMazeIdx1.y(), mi.y()),\n                   min(ccMazeIdx1.z(), mi.z()));\n    ccMazeIdx2.set(max(ccMazeIdx2.x(), mi.x()),\n                   max(ccMazeIdx2.y(), mi.y()),\n                   max(ccMazeIdx2.z(), mi.z()));\n    auto it = mazeIdx2unConnPins.find(mi);\n    if (it == mazeIdx2unConnPins.end()) {\n      continue;\n    }\n    auto it2 = it->second.find(currPin);\n    if (it2 == it->second.end()) {\n      continue;\n    }\n    it->second.erase(it2);\n\n    gridGraph_.setSrc(mi);\n    // remove dst label only when no other pins share the same loc\n    if (it->second.empty()) {\n      mazeIdx2unConnPins.erase(it);\n      gridGraph_.resetDst(mi);\n    }\n  }\n}\n\ndrPin* FlexDRWorker::routeNet_getNextDst(\n    FlexMazeIdx& ccMazeIdx1,\n    FlexMazeIdx& ccMazeIdx2,\n    map<FlexMazeIdx, set<drPin*, frBlockObjectComp>>& mazeIdx2unConnPins,\n    list<pair<drPin*, frBox3D>>& pinTaperBoxes)\n{\n  Point pt;\n  Point ll, ur;\n  gridGraph_.getPoint(ll, ccMazeIdx1.x(), ccMazeIdx1.y());\n  gridGraph_.getPoint(ur, ccMazeIdx2.x(), ccMazeIdx2.y());\n  frCoord currDist = std::numeric_limits<frCoord>::max();\n  drPin* nextDst = nullptr;\n  if (!nextDst)\n    for (auto& [mazeIdx, setS] : mazeIdx2unConnPins) {\n      gridGraph_.getPoint(pt, mazeIdx.x(), mazeIdx.y());\n      frCoord dx = max(max(ll.x() - pt.x(), pt.x() - ur.x()), 0);\n      frCoord dy = max(max(ll.y() - pt.y(), pt.y() - ur.y()), 0);\n      frCoord dz = max(max(gridGraph_.getZHeight(ccMazeIdx1.z())\n                               - gridGraph_.getZHeight(mazeIdx.z()),\n                           gridGraph_.getZHeight(mazeIdx.z())\n                               - gridGraph_.getZHeight(ccMazeIdx2.z())),\n                       0);\n      if (dx + dy + dz < currDist) {\n        currDist = dx + dy + dz;\n        nextDst = *(setS.begin());\n      }\n      if (currDist == 0) {\n        break;\n      }\n    }\n  if (gridGraph_.getNDR()) {\n    if (AUTO_TAPER_NDR_NETS) {\n      for (auto& a : pinTaperBoxes) {\n        if (a.first == nextDst) {\n          gridGraph_.setDstTaperBox(&a.second);\n          break;\n        }\n      }\n    }\n  }\n  return nextDst;\n}\n\nvoid FlexDRWorker::mazePinInit()\n{\n  gridGraph_.resetPrevNodeDir();\n}\n\nvoid FlexDRWorker::routeNet_postAstarUpdate(\n    vector<FlexMazeIdx>& path,\n    vector<FlexMazeIdx>& connComps,\n    set<drPin*, frBlockObjectComp>& unConnPins,\n    map<FlexMazeIdx, set<drPin*, frBlockObjectComp>>& mazeIdx2unConnPins,\n    bool isFirstConn)\n{\n  // first point is dst\n  set<FlexMazeIdx> localConnComps;\n  if (!path.empty()) {\n    auto mi = path[0];\n    vector<drPin*> tmpPins;\n    for (auto pin : mazeIdx2unConnPins[mi]) {\n      tmpPins.push_back(pin);\n    }\n    for (auto pin : tmpPins) {\n      unConnPins.erase(pin);\n      for (auto& ap : pin->getAccessPatterns()) {\n        FlexMazeIdx mi;\n        ap->getMazeIdx(mi);\n        auto it = mazeIdx2unConnPins.find(mi);\n        if (it == mazeIdx2unConnPins.end()) {\n          continue;\n        }\n        auto it2 = it->second.find(pin);\n        if (it2 == it->second.end()) {\n          continue;\n        }\n        it->second.erase(it2);\n        if (it->second.empty()) {\n          mazeIdx2unConnPins.erase(it);\n          gridGraph_.resetDst(mi);\n        }\n        if (ALLOW_PIN_AS_FEEDTHROUGH) {\n          localConnComps.insert(mi);\n          gridGraph_.setSrc(mi);\n        }\n      }\n    }\n  } else {\n    cout << \"Error: routeNet_postAstarUpdate path is empty\" << endl;\n  }\n  // must be before comment line ABC so that the used actual src is set in\n  // gridgraph\n  if (isFirstConn && (!ALLOW_PIN_AS_FEEDTHROUGH)) {\n    for (auto& mi : connComps) {\n      gridGraph_.resetSrc(mi);\n    }\n    connComps.clear();\n    if ((int) path.size() == 1) {\n      connComps.push_back(path[0]);\n      gridGraph_.setSrc(path[0]);\n    }\n  }\n  // line ABC\n  // must have >0 length\n  for (int i = 0; i < (int) path.size() - 1; ++i) {\n    auto start = path[i];\n    auto end = path[i + 1];\n    auto startX = start.x(), startY = start.y(), startZ = start.z();\n    auto endX = end.x(), endY = end.y(), endZ = end.z();\n    // horizontal wire\n    if (startX != endX && startY == endY && startZ == endZ) {\n      for (auto currX = std::min(startX, endX); currX <= std::max(startX, endX);\n           ++currX) {\n        localConnComps.insert(FlexMazeIdx(currX, startY, startZ));\n        gridGraph_.setSrc(currX, startY, startZ);\n      }\n      // vertical wire\n    } else if (startX == endX && startY != endY && startZ == endZ) {\n      for (auto currY = std::min(startY, endY); currY <= std::max(startY, endY);\n           ++currY) {\n        localConnComps.insert(FlexMazeIdx(startX, currY, startZ));\n        gridGraph_.setSrc(startX, currY, startZ);\n      }\n      // via\n    } else if (startX == endX && startY == endY && startZ != endZ) {\n      for (auto currZ = std::min(startZ, endZ); currZ <= std::max(startZ, endZ);\n           ++currZ) {\n        localConnComps.insert(FlexMazeIdx(startX, startY, currZ));\n        gridGraph_.setSrc(startX, startY, currZ);\n      }\n      // zero length\n    } else if (startX == endX && startY == endY && startZ == endZ) {\n      std::cout << \"Warning: zero-length path in updateFlexPin\\n\";\n    } else {\n      std::cout << \"Error: non-colinear path in updateFlexPin\\n\";\n    }\n  }\n  for (auto& mi : localConnComps) {\n    if (isFirstConn && !ALLOW_PIN_AS_FEEDTHROUGH) {\n      connComps.push_back(mi);\n    } else {\n      if (!(mi == *(path.cbegin()))) {\n        connComps.push_back(mi);\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::routeNet_postAstarWritePath(\n    drNet* net,\n    vector<FlexMazeIdx>& points,\n    const set<FlexMazeIdx>& realPinApMazeIdx,\n    map<FlexMazeIdx, frBox3D*>& mazeIdx2TaperBox,\n    const set<FlexMazeIdx>& apMazeIdx)\n{\n  if (points.empty()) {\n    return;\n  }\n  auto& workerRegionQuery = getWorkerRegionQuery();\n  frBox3D *srcBox = nullptr, *dstBox = nullptr;\n  auto it = mazeIdx2TaperBox.find(points[0]);\n  if (it != mazeIdx2TaperBox.end())\n    dstBox = it->second;\n  it = mazeIdx2TaperBox.find(points.back());\n  if (it != mazeIdx2TaperBox.end())\n    srcBox = it->second;\n  if (points.size() == 1) {\n      if (net->getFrAccessPoint(gridGraph_.xCoord(points[0].x()), \n                                gridGraph_.yCoord(points[0].y()),\n                                gridGraph_.getLayerNum(points[0].z())))\n          addApPathSegs(points[0], net);\n  }\n  for (int i = 0; i < (int) points.size() - 1; ++i) {\n    FlexMazeIdx start, end;\n    if (points[i + 1] < points[i]) {\n      start = points[i + 1];\n      end = points[i];\n    } else {\n      start = points[i];\n      end = points[i + 1];\n    }\n    auto startX = start.x(), startY = start.y(), startZ = start.z();\n    auto endX = end.x(), endY = end.y(), endZ = end.z();\n    if (startZ == endZ\n        && ((startX != endX && startY == endY)\n            || (startX == endX && startY != endY))) {\n      frMIdx midX, midY;\n      bool taper = false;\n      if (splitPathSeg(midX,\n                       midY,\n                       taper,\n                       startX,\n                       startY,\n                       endX,\n                       endY,\n                       startZ,\n                       srcBox,\n                       dstBox,\n                       net)) {\n        processPathSeg(startX,\n                       startY,\n                       midX,\n                       midY,\n                       startZ,\n                       realPinApMazeIdx,\n                       net,\n                       startX == endX,\n                       taper,\n                       i,\n                       points,\n                       apMazeIdx);\n        startX = midX;\n        startY = midY;\n        if (splitPathSeg(midX,\n                         midY,\n                         taper,\n                         startX,\n                         startY,\n                         endX,\n                         endY,\n                         startZ,\n                         srcBox,\n                         dstBox,\n                         net)) {\n          processPathSeg(startX,\n                         startY,\n                         midX,\n                         midY,\n                         startZ,\n                         realPinApMazeIdx,\n                         net,\n                         startX == endX,\n                         taper,\n                         i,\n                         points,\n                         apMazeIdx);\n          startX = midX;\n          startY = midY;\n          taper = true;\n        }\n      }\n      processPathSeg(startX,\n                     startY,\n                     endX,\n                     endY,\n                     startZ,\n                     realPinApMazeIdx,\n                     net,\n                     startX == endX,\n                     taper,\n                     i,\n                     points,\n                     apMazeIdx);\n    } else if (startX == endX && startY == endY && startZ != endZ) {  // via\n      for (auto currZ = startZ; currZ < endZ; ++currZ) {\n        Point loc;\n        frLayerNum startLayerNum = gridGraph_.getLayerNum(currZ);\n        gridGraph_.getPoint(loc, startX, startY);\n        FlexMazeIdx mi(startX, startY, currZ);\n        auto via = getTech()->getLayer(startLayerNum + 1)->getDefaultViaDef();\n        if (net->getFrNet()->getNondefaultRule()\n            && net->getFrNet()->getNondefaultRule()->getPrefVia(currZ))\n          via = net->getFrNet()->getNondefaultRule()->getPrefVia(currZ);\n        if (gridGraph_.isSVia(startX, startY, currZ)) {\n          via = apSVia_.find(mi)->second->getAccessViaDef();\n        }\n        auto currVia = make_unique<drVia>(via);\n        if (net->hasNDR() && AUTO_TAPER_NDR_NETS) {\n          if (isInsideTaperBox(endX, endY, startZ, endZ, mazeIdx2TaperBox)) {\n            currVia->setTapered(true);\n          }\n        }\n        currVia->setOrigin(loc);\n        FlexMazeIdx mzIdxBot(startX, startY, currZ);\n        FlexMazeIdx mzIdxTop(startX, startY, currZ + 1);\n        currVia->setMazeIdx(mzIdxBot, mzIdxTop);\n        currVia->addToNet(net);\n        /*update access point (AP) connectivity info. If it is over a boundary\n        pin may still be over an unseen AP (this is checked by\n        checkViaConnectivity) */\n        if (realPinApMazeIdx.find(mzIdxBot) != realPinApMazeIdx.end()) {\n            if (!addApPathSegs(mzIdxBot, net)) \n                currVia->setBottomConnected(true);\n        } else {\n          checkViaConnectivityToAP(\n              currVia.get(), true, net->getFrNet(), apMazeIdx, mzIdxBot);\n        }\n        if (realPinApMazeIdx.find(mzIdxTop) != realPinApMazeIdx.end()) {\n            if (!addApPathSegs(mzIdxTop, net)) \n                currVia->setTopConnected(true);\n        } else {\n          checkViaConnectivityToAP(\n              currVia.get(), false, net->getFrNet(), apMazeIdx, mzIdxTop);\n        }\n        unique_ptr<drConnFig> tmp(std::move(currVia));\n        workerRegionQuery.add(tmp.get());\n        net->addRoute(std::move(tmp));\n        if (gridGraph_.hasRouteShapeCostAdj(startX, startY, currZ, frDirEnum::U)) {\n          net->addMarker();\n        }\n      }\n      // zero length\n    } else if (startX == endX && startY == endY && startZ == endZ) {\n      std::cout << \"Warning: zero-length path in updateFlexPin\\n\";\n    } else {\n      std::cout << \"Error: non-colinear path in updateFlexPin\\n\";\n    }\n  }\n}\nbool FlexDRWorker::addApPathSegs(const FlexMazeIdx& apIdx, drNet* net) {\n    frCoord x = gridGraph_.xCoord(apIdx.x());\n    frCoord y = gridGraph_.yCoord(apIdx.y());\n    frLayerNum lNum = gridGraph_.getLayerNum(apIdx.z());\n    frBlockObject* owner = nullptr;\n    frAccessPoint* ap = net->getFrAccessPoint(x, y, lNum, &owner);\n    if (!ap)    //on-the-fly ap\n        return false;\n    assert(owner != nullptr);\n    frInst* inst = nullptr;\n    if (owner->typeId() == frBlockObjectEnum::frcInstTerm)\n        inst = static_cast<frInstTerm*>(owner)->getInst();\n    assert(ap != nullptr);\n    if (ap->getPathSegs().empty())\n        return false; \n    for (auto& ps : ap->getPathSegs()) {\n        unique_ptr<drPathSeg> drPs = make_unique<drPathSeg>();\n        Point begin = ps.getBeginPoint();\n        Point end = ps.getEndPoint();\n        Point* connecting = nullptr;\n        if (ps.getBeginStyle() == frEndStyle(frcTruncateEndStyle))\n            connecting = &begin;\n        else if (ps.getEndStyle() == frEndStyle(frcTruncateEndStyle))\n            connecting = &end;\n        if (inst) {\n            dbTransform trans;\n            inst->getTransform(trans);\n            trans.apply(begin);\n            trans.apply(end);\n            if (end < begin) { //if rotation swaped order, correct it\n                if (connecting == &begin)\n                    connecting = &end;\n                else \n                    connecting = &begin;\n                Point tmp = begin;\n                begin = end;\n                end = tmp;\n            }\n        }\n        drPs->setPoints(begin, end);\n        drPs->setLayerNum(lNum);\n        drPs->addToNet(net);\n        auto currStyle = getTech()->getLayer(lNum)->getDefaultSegStyle();\n        if (connecting == &begin)\n            currStyle.setBeginStyle(frcTruncateEndStyle, 0);\n        else if (connecting == &end)\n            currStyle.setEndStyle(frcTruncateEndStyle, 0);\n\n        if (net->getFrNet()->getNondefaultRule()) \n            drPs->setTapered(true); //these tiny access pathsegs should all be tapered\n        drPs->setStyle(currStyle);\n        FlexMazeIdx startIdx, endIdx;\n        gridGraph_.getMazeIdx(startIdx, begin, lNum);\n        gridGraph_.getMazeIdx(endIdx, end, lNum);\n        drPs->setMazeIdx(startIdx, endIdx);\n        getWorkerRegionQuery().add(drPs.get());\n        net->addRoute(std::move(drPs));\n    }\n    return true;\n}\nbool FlexDRWorker::splitPathSeg(frMIdx& midX,\n                                frMIdx& midY,\n                                bool& taperFirstPiece,\n                                frMIdx startX,\n                                frMIdx startY,\n                                frMIdx endX,\n                                frMIdx endY,\n                                frMIdx z,\n                                frBox3D* srcBox,\n                                frBox3D* dstBox,\n                                drNet* net)\n{\n  taperFirstPiece = false;\n  if (!net->hasNDR() || !AUTO_TAPER_NDR_NETS) {\n    return false;\n  }\n  frBox3D* bx = nullptr;\n  if (srcBox && srcBox->contains(startX, startY, z)) {\n    bx = srcBox;\n  } else if (dstBox && dstBox->contains(startX, startY, z)) {\n    bx = dstBox;\n  }\n  if (bx) {\n    taperFirstPiece = true;\n    if (bx->contains(endX, endY, z, 1, 1)) {\n      return false;\n    } else {\n      if (startX == endX) {\n        midX = startX;\n        midY = bx->yMax() + 1;\n      } else {\n        midX = bx->xMax() + 1;\n        midY = startY;\n      }\n      return true;\n    }\n  } else {\n    if (srcBox && srcBox->contains(endX, endY, z)) {\n      bx = srcBox;\n    } else if (dstBox && dstBox->contains(endX, endY, z)) {\n      bx = dstBox;\n    }\n    if (bx) {\n      if (bx->contains(startX, startY, z, 1, 1)) {\n        taperFirstPiece = true;\n        return false;\n      } else {\n        if (startX == endX) {\n          midX = startX;\n          midY = bx->yMin() - 1;\n        } else {\n          midX = bx->xMin() - 1;\n          midY = startY;\n        }\n        return true;\n      }\n    }\n  }\n  return false;\n}\nvoid FlexDRWorker::processPathSeg(frMIdx startX,\n                                  frMIdx startY,\n                                  frMIdx endX,\n                                  frMIdx endY,\n                                  frMIdx z,\n                                  const set<FlexMazeIdx>& realApMazeIdx,\n                                  drNet* net,\n                                  bool vertical,\n                                  bool taper,\n                                  int i,\n                                  vector<FlexMazeIdx>& points,\n                                  const set<FlexMazeIdx>& apMazeIdx)\n{\n  Point startLoc, endLoc;\n  frLayerNum currLayerNum = gridGraph_.getLayerNum(z);\n  gridGraph_.getPoint(startLoc, startX, startY);\n  gridGraph_.getPoint(endLoc, endX, endY);\n  auto currPathSeg = make_unique<drPathSeg>();\n  currPathSeg->setPoints(startLoc, endLoc);\n  currPathSeg->setLayerNum(currLayerNum);\n  currPathSeg->addToNet(net);\n  FlexMazeIdx start(startX, startY, z), end(endX, endY, z);\n  auto currStyle = getTech()->getLayer(currLayerNum)->getDefaultSegStyle();\n  if (realApMazeIdx.find(start) != realApMazeIdx.end()) {\n      if (!addApPathSegs(start, net))\n            currStyle.setBeginStyle(frcTruncateEndStyle, 0);\n  } else {\n    checkPathSegStyle(currPathSeg.get(), true, currStyle, apMazeIdx, start);\n  }\n  if (realApMazeIdx.find(end) != realApMazeIdx.end()) {\n      if (!addApPathSegs(end, net))\n            currStyle.setEndStyle(frcTruncateEndStyle, 0);\n  } else {\n    checkPathSegStyle(currPathSeg.get(), false, currStyle, apMazeIdx, end);\n  }\n  if (net->getFrNet()->getNondefaultRule()) {\n    if (taper)\n      currPathSeg->setTapered(true);\n    else\n      setNDRStyle(net,\n                  currStyle,\n                  startX,\n                  endX,\n                  startY,\n                  endY,\n                  z,\n                  i - 1 >= 0 ? &points[i - 1] : nullptr,\n                  i + 2 < (int) points.size() ? &points[i + 2] : nullptr);\n  }\n  currPathSeg->setStyle(currStyle);\n  currPathSeg->setMazeIdx(start, end);\n  unique_ptr<drConnFig> tmp(std::move(currPathSeg));\n  getWorkerRegionQuery().add(tmp.get());\n  net->addRoute(std::move(tmp));\n\n  // quick drc cnt\n  bool prevHasCost = false;\n  int endI = vertical ? endY : endX;\n  for (int i = (vertical ? startY : startX); i < endI; i++) {\n    if ((vertical && gridGraph_.hasRouteShapeCostAdj(startX, i, z, frDirEnum::E))\n        || (!vertical\n            && gridGraph_.hasRouteShapeCostAdj(i, startY, z, frDirEnum::N))) {\n      if (!prevHasCost) {\n        net->addMarker();\n        prevHasCost = true;\n      }\n    } else {\n      prevHasCost = false;\n    }\n  }\n}\nbool FlexDRWorker::isInWorkerBorder(frCoord x, frCoord y) const\n{\n  return (x == getRouteBox().xMin() &&  // left\n          y <= getRouteBox().yMax() && y >= getRouteBox().yMin())\n         || (x == getRouteBox().xMax() &&  // right\n             y <= getRouteBox().yMax() && y >= getRouteBox().yMin())\n         || (y == getRouteBox().yMin() &&  // bottom\n             x <= getRouteBox().xMax() && x >= getRouteBox().xMin())\n         || (y == getRouteBox().yMax() &&  // top\n             x <= getRouteBox().xMax() && x >= getRouteBox().xMin());\n}\n// checks whether the path segment is connected to an access point and update\n// connectivity info (stored in frSegStyle)\nvoid FlexDRWorker::checkPathSegStyle(drPathSeg* ps,\n                                     bool isBegin,\n                                     frSegStyle& style,\n                                     const set<FlexMazeIdx>& apMazeIdx,\n                                     const FlexMazeIdx& idx)\n{\n  const Point& pt = (isBegin ? ps->getBeginPoint() : ps->getEndPoint());\n  if (apMazeIdx.find(idx) == apMazeIdx.end()\n      && !isInWorkerBorder(pt.x(), pt.y()))\n    return;\n  if (hasAccessPoint(pt, ps->getLayerNum(), ps->getNet()->getFrNet())) {\n      if (!addApPathSegs(idx, ps->getNet())) {\n        if (isBegin)\n          style.setBeginStyle(frEndStyle(frEndStyleEnum::frcTruncateEndStyle), 0);\n        else\n          style.setEndStyle(frEndStyle(frEndStyleEnum::frcTruncateEndStyle), 0);\n      }\n  }\n}\n\nbool FlexDRWorker::hasAccessPoint(const Point& pt, frLayerNum lNum, frNet* net)\n{\n  frRegionQuery::Objects<frBlockObject> result;\n  Rect bx(pt.x(), pt.y(), pt.x(), pt.y());\n  design_->getRegionQuery()->query(bx, lNum, result);\n  for (auto& rqObj : result) {\n    switch (rqObj.second->typeId()) {\n      case frcInstTerm: {\n        auto instTerm = static_cast<frInstTerm*>(rqObj.second);\n        if (instTerm->getNet() == net\n            && instTerm->hasAccessPoint(pt.x(), pt.y(), lNum))\n          return true;\n        break;\n      }\n      case frcBTerm: {\n        auto term = static_cast<frBTerm*>(rqObj.second);\n        if (term->getNet() == net\n            && term->hasAccessPoint(pt.x(), pt.y(), lNum, 0))\n          return true;\n        break;\n      }\n      default:\n        break;\n    }\n  }\n  return false;\n}\n// checks whether the via is connected to an access point and update\n// connectivity info\nvoid FlexDRWorker::checkViaConnectivityToAP(drVia* via,\n                                            bool isBottom,\n                                            frNet* net,\n                                            const set<FlexMazeIdx>& apMazeIdx,\n                                            const FlexMazeIdx& idx)\n{\n  if (apMazeIdx.find(idx) == apMazeIdx.end()\n      && !isInWorkerBorder(via->getOrigin().x(), via->getOrigin().y()))\n    return;\n  if (isBottom) {\n    if (hasAccessPoint(via->getOrigin(), via->getViaDef()->getLayer1Num(), net)) {\n        if (!addApPathSegs(idx, via->getNet())) \n            via->setBottomConnected(true);\n    }\n  } else {\n    if (hasAccessPoint(via->getOrigin(), via->getViaDef()->getLayer2Num(), net)) {\n        if (!addApPathSegs(idx, via->getNet())) \n            via->setTopConnected(true);\n    }\n  }\n}\nvoid FlexDRWorker::setNDRStyle(drNet* net,\n                               frSegStyle& currStyle,\n                               frMIdx startX,\n                               frMIdx endX,\n                               frMIdx startY,\n                               frMIdx endY,\n                               frMIdx z,\n                               FlexMazeIdx* prev,\n                               FlexMazeIdx* next)\n{\n  frNonDefaultRule* ndr = net->getFrNet()->getNondefaultRule();\n  if (ndr->getWidth(z) > (int) currStyle.getWidth()) {\n    currStyle.setWidth(ndr->getWidth(z));\n    currStyle.setBeginExt(ndr->getWidth(z) / 2);\n    currStyle.setEndExt(ndr->getWidth(z) / 2);\n  }\n  if (ndr->getWireExtension(z) > 0) {\n    bool hasBeginExt = false, hasEndExt = false;\n    if (!prev && !next) {\n      hasBeginExt = hasEndExt = true;\n    } else if (!prev) {\n      if (abs(next->x() - startX) + abs(next->y() - startY)\n          < abs(next->x() - endX) + abs(next->y() - endY))\n        hasEndExt = true;\n      else\n        hasBeginExt = true;\n    } else if (!next) {\n      if (abs(prev->x() - startX) + abs(prev->y() - startY)\n          < abs(prev->x() - endX) + abs(prev->y() - endY))\n        hasEndExt = true;\n      else\n        hasBeginExt = true;\n    }\n    if (prev && prev->z() != z && prev->x() == startX && prev->y() == startY) {\n      hasBeginExt = true;\n    } else if (next && next->z() != z && next->x() == startX\n               && next->y() == startY) {\n      hasBeginExt = true;\n    }\n    if (prev && prev->z() != z && prev->x() == endX && prev->y() == endY) {\n      hasEndExt = true;\n    } else if (next && next->z() != z && next->x() == endX\n               && next->y() == endY) {\n      hasEndExt = true;\n    }\n    frEndStyle es(frEndStyleEnum::frcVariableEndStyle);\n    if (hasBeginExt)\n      currStyle.setBeginStyle(\n          es,\n          max((int) currStyle.getBeginExt(), (int) ndr->getWireExtension(z)));\n    if (hasEndExt)\n      currStyle.setEndStyle(\n          es, max((int) currStyle.getEndExt(), (int) ndr->getWireExtension(z)));\n  }\n}\n\nbool FlexDRWorker::isInsideTaperBox(\n    frMIdx x,\n    frMIdx y,\n    frMIdx startZ,\n    frMIdx endZ,\n    map<FlexMazeIdx, frBox3D*>& mazeIdx2TaperBox)\n{\n  FlexMazeIdx idx(x, y, startZ);\n  auto it = mazeIdx2TaperBox.find(idx);\n  if (it != mazeIdx2TaperBox.end())\n    return true;\n  idx.setZ(endZ);\n  it = mazeIdx2TaperBox.find(idx);\n  return it != mazeIdx2TaperBox.end();\n}\n\nvoid FlexDRWorker::routeNet_postRouteAddPathCost(drNet* net)\n{\n  int cnt = 0;\n  for (auto& connFig : net->getRouteConnFigs()) {\n    addPathCost(connFig.get());\n    cnt++;\n  }\n}\n\nvoid FlexDRWorker::routeNet_AddCutSpcCost(vector<FlexMazeIdx>& path)\n{\n  if (path.size() <= 1)\n    return;\n  for (unsigned long i = 1; i < path.size(); i++) {\n    if (path[i].z() != path[i-1].z()) {\n      frMIdx z = min (path[i].z(), path[i-1].z());\n      frViaDef* viaDef = design_->getTech()->getLayer(gridGraph_.getLayerNum(z)+1)->getDefaultViaDef();\n      int x = gridGraph_.xCoord(path[i].x());\n      int y = gridGraph_.yCoord(path[i].y());\n      dbTransform xform(Point(x, y));\n      Rect box;\n      for (auto& uFig : viaDef->getCutFigs()) {\n        auto rect = static_cast<frRect*>(uFig.get());\n        rect->getBBox(box);\n        xform.apply(box);\n        modCutSpacingCost(box,\n                          z,\n                          ModCostType::addRouteShape,\n                          false,\n                          path[i].x(),\n                          path[i].y());\n      }\n    }\n  }\n}\n\nvoid FlexDRWorker::routeNet_prepAreaMap(drNet* net,\n                                        map<FlexMazeIdx, frCoord>& areaMap)\n{\n  FlexMazeIdx mIdx;\n  for (auto& pin : net->getPins()) {\n    for (auto& ap : pin->getAccessPatterns()) {\n      ap->getMazeIdx(mIdx);\n      auto it = areaMap.find(mIdx);\n      if (it != areaMap.end()) {\n        it->second = max(it->second, ap->getBeginArea());\n      } else {\n        areaMap[mIdx] = ap->getBeginArea();\n      }\n    }\n  }\n}\n\nbool FlexDRWorker::routeNet(drNet* net)\n{\n  //  ProfileTask profile(\"DR:routeNet\");\n\n  if (net->getPins().size() <= 1) {\n    return true;\n  }\n  if (graphics_)\n    graphics_->show(true);\n  set<drPin*, frBlockObjectComp> unConnPins;\n  map<FlexMazeIdx, set<drPin*, frBlockObjectComp>> mazeIdx2unConnPins;\n  map<FlexMazeIdx, frBox3D*>\n      mazeIdx2TaperBox;  // access points -> taper box: used to efficiently know\n                         // what points are in what taper boxes\n  list<pair<drPin*, frBox3D>> pinTaperBoxes;\n  set<FlexMazeIdx> apMazeIdx;\n  set<FlexMazeIdx> realPinAPMazeIdx;\n  routeNet_prep(net,\n                unConnPins,\n                mazeIdx2unConnPins,\n                apMazeIdx,\n                realPinAPMazeIdx,\n                mazeIdx2TaperBox,\n                pinTaperBoxes);\n  // prep for area map\n  map<FlexMazeIdx, frCoord> areaMap;\n  if (ENABLE_BOUNDARY_MAR_FIX) {\n    routeNet_prepAreaMap(net, areaMap);\n  }\n\n  FlexMazeIdx ccMazeIdx1, ccMazeIdx2;  // connComps ll, ur flexmazeidx\n  Point centerPt;\n  vector<FlexMazeIdx> connComps;\n  routeNet_setSrc(unConnPins,\n                  mazeIdx2unConnPins,\n                  connComps,\n                  ccMazeIdx1,\n                  ccMazeIdx2,\n                  centerPt);\n\n  vector<FlexMazeIdx> path;  // astar must return with >= 1 idx\n  bool isFirstConn = true;\n  bool searchSuccess = true;\n  while (!unConnPins.empty()) {\n    mazePinInit();\n    auto nextPin = routeNet_getNextDst(\n        ccMazeIdx1, ccMazeIdx2, mazeIdx2unConnPins, pinTaperBoxes);\n    path.clear();\n    if (gridGraph_.search(connComps,\n                          nextPin,\n                          path,\n                          ccMazeIdx1,\n                          ccMazeIdx2,\n                          centerPt,\n                          mazeIdx2TaperBox)) {\n      routeNet_postAstarUpdate(\n          path, connComps, unConnPins, mazeIdx2unConnPins, isFirstConn);\n      routeNet_postAstarWritePath(\n          net, path, realPinAPMazeIdx, mazeIdx2TaperBox, apMazeIdx);\n      routeNet_postAstarPatchMinAreaVio(net, path, areaMap);\n      routeNet_AddCutSpcCost(path);\n      isFirstConn = false;\n    } else {\n      searchSuccess = false;\n      logger_->report(\"Failed to find a path between pin \" + nextPin->getName()\n                      + \" and source aps:\");\n      for (FlexMazeIdx& mi : connComps) {\n        logger_->report(\"( {} {} {} ) (Idx) / ( {} {} ) (coords)\",\n                        mi.x(),\n                        mi.y(),\n                        mi.z(),\n                        gridGraph_.xCoord(mi.x()),\n                        gridGraph_.yCoord(mi.y()));\n      }\n      break;\n    }\n  }\n  if (searchSuccess) {\n    if (CLEAN_PATCHES) {\n      gcWorker_->setTargetNet(net->getFrNet());\n      gcWorker_->updateDRNet(net);\n      gcWorker_->setEnableSurgicalFix(true);\n      gcWorker_->updateGCWorker();\n      cleanUnneededPatches_poly(gcWorker_->getTargetNet(), net);\n    }\n    routeNet_postRouteAddPathCost(net);\n  }\n  return searchSuccess;\n}\n\nvoid FlexDRWorker::routeNet_postAstarPatchMinAreaVio(\n    drNet* net,\n    const vector<FlexMazeIdx>& path,\n    const map<FlexMazeIdx, frCoord>& areaMap)\n{\n  if (path.empty()) {\n    return;\n  }\n  // get path with separated (stacked vias)\n  vector<FlexMazeIdx> points;\n  for (int i = 0; i < (int) path.size() - 1; ++i) {\n    auto currIdx = path[i];\n    auto nextIdx = path[i + 1];\n    if (currIdx.z() == nextIdx.z()) {\n      points.push_back(currIdx);\n    } else {\n      if (currIdx.z() < nextIdx.z()) {\n        for (auto z = currIdx.z(); z < nextIdx.z(); ++z) {\n          FlexMazeIdx tmpIdx(currIdx.x(), currIdx.y(), z);\n          points.push_back(tmpIdx);\n        }\n      } else {\n        for (auto z = currIdx.z(); z > nextIdx.z(); --z) {\n          FlexMazeIdx tmpIdx(currIdx.x(), currIdx.y(), z);\n          points.push_back(tmpIdx);\n        }\n      }\n    }\n  }\n  points.push_back(path.back());\n\n  auto layerNum = gridGraph_.getLayerNum(points.front().z());\n  auto minAreaConstraint = getTech()->getLayer(layerNum)->getAreaConstraint();\n\n  frArea currArea = 0;\n  if (ENABLE_BOUNDARY_MAR_FIX) {\n    if (areaMap.find(points[0]) != areaMap.end()) {\n      currArea = areaMap.find(points[0])->second;\n    } else {\n      currArea = (minAreaConstraint) ? minAreaConstraint->getMinArea() : 0;\n    }\n  } else {\n    currArea = (minAreaConstraint) ? minAreaConstraint->getMinArea() : 0;\n  }\n  frCoord startViaHalfEncArea = 0, endViaHalfEncArea = 0;\n  FlexMazeIdx prevIdx = points[0], currIdx;\n  int i;\n  int prev_i = 0;  // path start point\n  for (i = 1; i < (int) points.size(); ++i) {\n    currIdx = points[i];\n    // check minAreaViolation when change layer, or last segment\n    if (currIdx.z() != prevIdx.z()) {\n      layerNum = gridGraph_.getLayerNum(prevIdx.z());\n      minAreaConstraint = getTech()->getLayer(layerNum)->getAreaConstraint();\n      frArea reqArea\n          = (minAreaConstraint) ? minAreaConstraint->getMinArea() : 0;\n      // add next via enclosure\n      if (currIdx.z() < prevIdx.z()) {\n        currArea += getHalfViaEncArea(\n            prevIdx.z() - 1, false, net->getFrNet()->getNondefaultRule());\n        endViaHalfEncArea = getHalfViaEncArea(\n            prevIdx.z() - 1, false, net->getFrNet()->getNondefaultRule());\n      } else {\n        currArea += getHalfViaEncArea(\n            prevIdx.z(), true, net->getFrNet()->getNondefaultRule());\n        endViaHalfEncArea = getHalfViaEncArea(\n            prevIdx.z(), true, net->getFrNet()->getNondefaultRule());\n      }\n      // push to minArea violation\n      if (currArea < reqArea) {\n        FlexMazeIdx bp, ep;\n        frArea gapArea = reqArea\n                         - (currArea - startViaHalfEncArea - endViaHalfEncArea)\n                         - std::min(startViaHalfEncArea, endViaHalfEncArea);\n        // new\n        bool bpPatchStyle = true;  // style 1: left only; 0: right only\n        bool epPatchStyle = false;\n        // stack via\n        if (i - 1 == prev_i) {\n          bp = points[i - 1];\n          ep = points[i - 1];\n          bpPatchStyle = true;\n          epPatchStyle = false;\n          // planar\n        } else {\n          bp = points[prev_i];\n          ep = points[i - 1];\n          if (getTech()->getLayer(layerNum)->getDir()\n              == dbTechLayerDir::HORIZONTAL) {\n            if (points[prev_i].x() < points[prev_i + 1].x()) {\n              bpPatchStyle = true;\n            } else if (points[prev_i].x() > points[prev_i + 1].x()) {\n              bpPatchStyle = false;\n            } else {\n              if (points[prev_i].x() < points[i - 1].x()) {\n                bpPatchStyle = true;\n              } else {\n                bpPatchStyle = false;\n              }\n            }\n            if (points[i - 1].x() < points[i - 2].x()) {\n              epPatchStyle = true;\n            } else if (points[i - 1].x() > points[i - 2].x()) {\n              epPatchStyle = false;\n            } else {\n              if (points[i - 1].x() < points[prev_i].x()) {\n                epPatchStyle = true;\n              } else {\n                epPatchStyle = false;\n              }\n            }\n          } else {\n            if (points[prev_i].y() < points[prev_i + 1].y()) {\n              bpPatchStyle = true;\n            } else if (points[prev_i].y() > points[prev_i + 1].y()) {\n              bpPatchStyle = false;\n            } else {\n              if (points[prev_i].y() < points[i - 1].y()) {\n                bpPatchStyle = true;\n              } else {\n                bpPatchStyle = false;\n              }\n            }\n            if (points[i - 1].y() < points[i - 2].y()) {\n              epPatchStyle = true;\n            } else if (points[i - 1].y() > points[i - 2].y()) {\n              epPatchStyle = false;\n            } else {\n              if (points[i - 1].y() < points[prev_i].y()) {\n                epPatchStyle = true;\n              } else {\n                epPatchStyle = false;\n              }\n            }\n          }\n        }\n        auto patchWidth = getTech()->getLayer(layerNum)->getWidth();\n        routeNet_postAstarAddPatchMetal(\n            net, bp, ep, gapArea, patchWidth, bpPatchStyle, epPatchStyle);\n      }\n      // init for next path\n      if (currIdx.z() < prevIdx.z()) {\n        currArea = getHalfViaEncArea(\n            prevIdx.z() - 1, true, net->getFrNet()->getNondefaultRule());\n        startViaHalfEncArea = getHalfViaEncArea(\n            prevIdx.z() - 1, true, net->getFrNet()->getNondefaultRule());\n      } else {\n        currArea = getHalfViaEncArea(\n            prevIdx.z(), false, net->getFrNet()->getNondefaultRule());\n        currArea = getHalfViaEncArea(\n            prevIdx.z(), false, net->getFrNet()->getNondefaultRule());\n        startViaHalfEncArea = gridGraph_.getHalfViaEncArea(prevIdx.z(), false);\n      }\n      prev_i = i;\n    }\n    // add the wire area\n    else {\n      layerNum = gridGraph_.getLayerNum(prevIdx.z());\n      minAreaConstraint = getTech()->getLayer(layerNum)->getAreaConstraint();\n      frArea reqArea\n          = (minAreaConstraint) ? minAreaConstraint->getMinArea() : 0;\n      auto pathWidth = getTech()->getLayer(layerNum)->getWidth();\n      Point bp, ep;\n      gridGraph_.getPoint(bp, prevIdx.x(), prevIdx.y());\n      gridGraph_.getPoint(ep, currIdx.x(), currIdx.y());\n      frCoord pathLength = abs(bp.x() - ep.x()) + abs(bp.y() - ep.y());\n      if (currArea < reqArea) {\n        currArea += pathLength * pathWidth;\n      }\n    }\n    prevIdx = currIdx;\n  }\n  // add boundary area for last segment\n  if (ENABLE_BOUNDARY_MAR_FIX) {\n    layerNum = gridGraph_.getLayerNum(prevIdx.z());\n    minAreaConstraint = getTech()->getLayer(layerNum)->getAreaConstraint();\n    frArea reqArea = (minAreaConstraint) ? minAreaConstraint->getMinArea() : 0;\n    if (areaMap.find(prevIdx) != areaMap.end()) {\n      currArea += areaMap.find(prevIdx)->second;\n    }\n    endViaHalfEncArea = 0;\n    if (currArea < reqArea) {\n      FlexMazeIdx bp, ep;\n      frArea gapArea = reqArea\n                       - (currArea - startViaHalfEncArea - endViaHalfEncArea)\n                       - std::min(startViaHalfEncArea, endViaHalfEncArea);\n      // new\n      bool bpPatchStyle = true;  // style 1: left only; 0: right only\n      bool epPatchStyle = false;\n      // stack via\n      if (i - 1 == prev_i) {\n        bp = points[i - 1];\n        ep = points[i - 1];\n        bpPatchStyle = true;\n        epPatchStyle = false;\n        // planar\n      } else {\n        bp = points[prev_i];\n        ep = points[i - 1];\n        if (getTech()->getLayer(layerNum)->getDir()\n            == dbTechLayerDir::HORIZONTAL) {\n          if (points[prev_i].x() < points[prev_i + 1].x()) {\n            bpPatchStyle = true;\n          } else if (points[prev_i].x() > points[prev_i + 1].x()) {\n            bpPatchStyle = false;\n          } else {\n            if (points[prev_i].x() < points[i - 1].x()) {\n              bpPatchStyle = true;\n            } else {\n              bpPatchStyle = false;\n            }\n          }\n          if (points[i - 1].x() < points[i - 2].x()) {\n            epPatchStyle = true;\n          } else if (points[i - 1].x() > points[i - 2].x()) {\n            epPatchStyle = false;\n          } else {\n            if (points[i - 1].x() < points[prev_i].x()) {\n              epPatchStyle = true;\n            } else {\n              epPatchStyle = false;\n            }\n          }\n        } else {\n          if (points[prev_i].y() < points[prev_i + 1].y()) {\n            bpPatchStyle = true;\n          } else if (points[prev_i].y() > points[prev_i + 1].y()) {\n            bpPatchStyle = false;\n          } else {\n            if (points[prev_i].y() < points[i - 1].y()) {\n              bpPatchStyle = true;\n            } else {\n              bpPatchStyle = false;\n            }\n          }\n          if (points[i - 1].y() < points[i - 2].y()) {\n            epPatchStyle = true;\n          } else if (points[i - 1].y() > points[i - 2].y()) {\n            epPatchStyle = false;\n          } else {\n            if (points[i - 1].y() < points[prev_i].y()) {\n              epPatchStyle = true;\n            } else {\n              epPatchStyle = false;\n            }\n          }\n        }\n      }\n      auto patchWidth = getTech()->getLayer(layerNum)->getWidth();\n      routeNet_postAstarAddPatchMetal(\n          net, bp, ep, gapArea, patchWidth, bpPatchStyle, epPatchStyle);\n    }\n  }\n}\n\nfrCoord FlexDRWorker::getHalfViaEncArea(frMIdx z,\n                                        bool isLayer1,\n                                        frNonDefaultRule* ndr)\n{\n  if (!ndr || !ndr->getPrefVia(z))\n    return gridGraph_.getHalfViaEncArea(z, isLayer1);\n  frVia via(ndr->getPrefVia(z));\n  Rect box;\n  if (isLayer1)\n    via.getLayer1BBox(box);\n  else\n    via.getLayer2BBox(box);\n  return box.minDXDY() * box.maxDXDY() / 2;\n}\n// assumes patchWidth == defaultWidth\n// the cost checking part is sensitive to how cost is stored (1) planar + via;\n// or (2) N;E;U\nint FlexDRWorker::routeNet_postAstarAddPathMetal_isClean(\n    const FlexMazeIdx& bpIdx,\n    bool isPatchHorz,\n    bool isPatchLeft,\n    frCoord patchLength)\n{\n  int cost = 0;\n  Point origin, patchEnd;\n  gridGraph_.getPoint(origin, bpIdx.x(), bpIdx.y());\n  frLayerNum layerNum = gridGraph_.getLayerNum(bpIdx.z());\n  if (isPatchHorz) {\n    if (isPatchLeft) {\n      patchEnd.set(origin.x() - patchLength, origin.y());\n    } else {\n      patchEnd.set(origin.x() + patchLength, origin.y());\n    }\n  } else {\n    if (isPatchLeft) {\n      patchEnd.set(origin.x(), origin.y() - patchLength);\n    } else {\n      patchEnd.set(origin.x(), origin.y() + patchLength);\n    }\n  }\n  // for wire, no need to bloat width\n  Point patchLL = min(origin, patchEnd);\n  Point patchUR = max(origin, patchEnd);\n  if (!getRouteBox().intersects(patchEnd)) {\n    cost = std::numeric_limits<int>::max();\n  } else {\n    FlexMazeIdx startIdx, endIdx;\n    startIdx.set(0, 0, layerNum);\n    endIdx.set(0, 0, layerNum);\n    Rect patchBox(patchLL, patchUR);\n    gridGraph_.getIdxBox(startIdx, endIdx, patchBox, FlexGridGraph::enclose);\n    if (isPatchHorz) {\n      // in gridgraph, the planar cost is checked for xIdx + 1\n      for (auto xIdx = max(0, startIdx.x() - 1); xIdx < endIdx.x(); ++xIdx) {\n        if (gridGraph_.hasRouteShapeCostAdj(\n                xIdx, bpIdx.y(), bpIdx.z(), frDirEnum::E)) {\n          cost += gridGraph_.getEdgeLength(\n                      xIdx, bpIdx.y(), bpIdx.z(), frDirEnum::E)\n                  * workerDRCCost_;\n        }\n        if (gridGraph_.hasFixedShapeCostAdj(\n                xIdx, bpIdx.y(), bpIdx.z(), frDirEnum::E)) {\n          cost += gridGraph_.getEdgeLength(\n                      xIdx, bpIdx.y(), bpIdx.z(), frDirEnum::E)\n                  * FIXEDSHAPECOST;\n        }\n        if (gridGraph_.hasMarkerCostAdj(\n                xIdx, bpIdx.y(), bpIdx.z(), frDirEnum::E)) {\n          cost += gridGraph_.getEdgeLength(\n                      xIdx, bpIdx.y(), bpIdx.z(), frDirEnum::E)\n                  * workerMarkerCost_;\n        }\n      }\n    } else {\n      // in gridgraph, the planar cost is checked for yIdx + 1\n      for (auto yIdx = max(0, startIdx.y() - 1); yIdx < endIdx.y(); ++yIdx) {\n        if (gridGraph_.hasRouteShapeCostAdj(\n                bpIdx.x(), yIdx, bpIdx.z(), frDirEnum::N)) {\n          cost += gridGraph_.getEdgeLength(\n                      bpIdx.x(), yIdx, bpIdx.z(), frDirEnum::N)\n                  * workerDRCCost_;\n        }\n        if (gridGraph_.hasFixedShapeCostAdj(\n                bpIdx.x(), yIdx, bpIdx.z(), frDirEnum::N)) {\n          cost += gridGraph_.getEdgeLength(\n                      bpIdx.x(), yIdx, bpIdx.z(), frDirEnum::N)\n                  * FIXEDSHAPECOST;\n        }\n        if (gridGraph_.hasMarkerCostAdj(\n                bpIdx.x(), yIdx, bpIdx.z(), frDirEnum::N)) {\n          cost += gridGraph_.getEdgeLength(\n                      bpIdx.x(), yIdx, bpIdx.z(), frDirEnum::N)\n                  * workerMarkerCost_;\n        }\n      }\n    }\n  }\n  return cost;\n}\n\nvoid FlexDRWorker::routeNet_postAstarAddPatchMetal_addPWire(\n    drNet* net,\n    const FlexMazeIdx& bpIdx,\n    bool isPatchHorz,\n    bool isPatchLeft,\n    frCoord patchLength,\n    frCoord patchWidth)\n{\n  Point origin, patchEnd;\n  gridGraph_.getPoint(origin, bpIdx.x(), bpIdx.y());\n  frLayerNum layerNum = gridGraph_.getLayerNum(bpIdx.z());\n  // actual offsetbox\n  Point patchLL, patchUR;\n  if (isPatchHorz) {\n    if (isPatchLeft) {\n      patchLL.set(0 - patchLength, 0 - patchWidth / 2);\n      patchUR.set(0, 0 + patchWidth / 2);\n    } else {\n      patchLL.set(0, 0 - patchWidth / 2);\n      patchUR.set(0 + patchLength, 0 + patchWidth / 2);\n    }\n  } else {\n    if (isPatchLeft) {\n      patchLL.set(0 - patchWidth / 2, 0 - patchLength);\n      patchUR.set(0 + patchWidth / 2, 0);\n    } else {\n      patchLL.set(0 - patchWidth / 2, 0);\n      patchUR.set(0 + patchWidth / 2, 0 + patchLength);\n    }\n  }\n\n  auto tmpPatch = make_unique<drPatchWire>();\n  tmpPatch->setLayerNum(layerNum);\n  tmpPatch->setOrigin(origin);\n  tmpPatch->setOffsetBox(Rect(patchLL, patchUR));\n  tmpPatch->addToNet(net);\n  unique_ptr<drConnFig> tmp(std::move(tmpPatch));\n  auto& workerRegionQuery = getWorkerRegionQuery();\n  workerRegionQuery.add(tmp.get());\n  net->addRoute(std::move(tmp));\n}\n\nvoid FlexDRWorker::routeNet_postAstarAddPatchMetal(drNet* net,\n                                                   const FlexMazeIdx& bpIdx,\n                                                   const FlexMazeIdx& epIdx,\n                                                   frCoord gapArea,\n                                                   frCoord patchWidth,\n                                                   bool bpPatchLeft,\n                                                   bool epPatchLeft)\n{\n  bool isPatchHorz;\n  // bool isLeftClean = true;\n  frLayerNum layerNum = gridGraph_.getLayerNum(bpIdx.z());\n  frCoord patchLength = frCoord(ceil(1.0 * gapArea / patchWidth\n                                     / getTech()->getManufacturingGrid()))\n                        * getTech()->getManufacturingGrid();\n\n  // always patch to pref dir\n  if (getTech()->getLayer(layerNum)->getDir() == dbTechLayerDir::HORIZONTAL) {\n    isPatchHorz = true;\n  } else {\n    isPatchHorz = false;\n  }\n\n  auto costL = routeNet_postAstarAddPathMetal_isClean(\n      bpIdx, isPatchHorz, bpPatchLeft, patchLength);\n  auto costR = routeNet_postAstarAddPathMetal_isClean(\n      epIdx, isPatchHorz, epPatchLeft, patchLength);\n  if (costL <= costR) {\n    routeNet_postAstarAddPatchMetal_addPWire(\n        net, bpIdx, isPatchHorz, bpPatchLeft, patchLength, patchWidth);\n  } else {\n    routeNet_postAstarAddPatchMetal_addPWire(\n        net, epIdx, isPatchHorz, epPatchLeft, patchLength, patchWidth);\n  }\n}\n", "meta": {"hexsha": "3bb8b9fbb03dc459ee2f7943d41cc632fee180f9", "size": 118623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/drt/src/dr/FlexDR_maze.cpp", "max_stars_repo_name": "minghungumich/OpenROAD", "max_stars_repo_head_hexsha": "df7206d2fd2949cc0e19b7ff30630ab945e7d571", "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/drt/src/dr/FlexDR_maze.cpp", "max_issues_repo_name": "minghungumich/OpenROAD", "max_issues_repo_head_hexsha": "df7206d2fd2949cc0e19b7ff30630ab945e7d571", "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/drt/src/dr/FlexDR_maze.cpp", "max_forks_repo_name": "minghungumich/OpenROAD", "max_forks_repo_head_hexsha": "df7206d2fd2949cc0e19b7ff30630ab945e7d571", "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.2939601309, "max_line_length": 106, "alphanum_fraction": 0.5416993332, "num_tokens": 32563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.1810357945303813}}
{"text": "/** svd.cc\n    Jeremy Barnes, 16 December 2014\n    Copyright (c) 2014 mldb.ai inc.  All rights reserved.\n\n    This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n    Implementation of an SVD algorithm for embedding of a dataset.\n*/\n\n#include \"svd.h\"\n#include \"mldb/builtin/matrix.h\"\n#include \"mldb/core/mldb_engine.h\"\n#include \"mldb/core/dataset.h\"\n#include \"mldb/utils/distribution.h\"\n#include <boost/multi_array.hpp>\n#include \"mldb/base/scope.h\"\n#include \"mldb/base/parallel.h\"\n#include \"mldb/utils/pair_utils.h\"\n#include \"mldb/arch/timers.h\"\n#include \"mldb/arch/simd_vector.h\"\n#include \"mldb/builtin/intersection_utils.h\"\n#include \"mldb/utils/vector_utils.h\"\n#include \"mldb/ext/svdlibc/svdlib.h\"\n#include \"mldb/types/basic_value_descriptions.h\"\n#include \"mldb/types/distribution_description.h\"\n#include \"mldb/types/optional_description.h\"\n#include \"mldb/sql/sql_expression.h\"\n#include \"mldb/builtin/sql_config_validator.h\"\n#include \"mldb/vfs/fs_utils.h\"\n#include \"mldb/types/map_description.h\"\n#include \"mldb/types/any_impl.h\"\n#include \"mldb/types/annotated_exception.h\"\n#include \"mldb/types/hash_wrapper_description.h\"\n#include \"mldb/vfs/filter_streams.h\"\n#include \"mldb/utils/progress.h\"\n#include \"mldb/utils/log.h\"\n#include <sstream>\n\nusing namespace std;\n\nnamespace MLDB {\n\n// jsonDecode implementation for any type which:\n// 1) has a default description;\ntemplate<typename T>\nT jsonDecodeFile(const std::string & filename, T * = 0)\n{\n    T result;\n\n    MLDB::filter_istream stream(filename);\n\n    static auto desc = MLDB::getDefaultDescriptionSharedT<T>();\n    MLDB::StreamingJsonParsingContext context(filename, stream);\n    desc->parseJson(&result, context);\n    return result;\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(SvdConfig);\n\nSvdConfigDescription::\nSvdConfigDescription()\n{\n    Optional<PolyConfigT<Dataset> > optionalOutputDataset;\n    optionalOutputDataset.emplace(PolyConfigT<Dataset>().\n                                  withType(SvdConfig::defaultOutputDatasetType));\n\n    addField(\"trainingData\", &SvdConfig::trainingData,\n             \"Specification of the data for input to the SVD Procedure.  This should be \"\n             \"organized as an embedding, with each selected row containing the same \"\n             \"set of columns with numeric values to be used as coordinates.  The select statement \"\n             \"does not support groupby and having clauses.\");\n    addField(\"columnOutputDataset\", &SvdConfig::columnOutput,\n             \"Output dataset for embedding (column singular vectors go here)\",\n             optionalOutputDataset);\n    addField(\"rowOutputDataset\", &SvdConfig::rowOutput,\n             \"Output dataset for embedding (row singular vectors go here)\",\n             optionalOutputDataset);\n    addField(\"numSingularValues\", &SvdConfig::numSingularValues,\n             \"Maximum number of singular values to work with.  \"\n             \"If there are not enough \"\n             \"degrees of freedom in the dataset (it is rank-deficient), then \"\n             \"less than this number may be used\", 100);\n    addField(\"numDenseBasisVectors\", &SvdConfig::numDenseBasisVectors,\n             \"Maximum number of dense basis vectors to use for the SVD.  \"\n             \"This parameter gives the number of dimensions into which the \"\n             \"projection is made.  Higher values may allow the SVD to model \"\n             \"slightly more diverse behaviour.  \"\n             \"The runtime goes up with the square of this parameter, \"\n             \"in other words 10 times as many is 100 times as long to run.\",\n             2000);\n    addField(\"outputColumn\", &SvdConfig::outputColumn,\n             \"Base name of the column that will be written by the SVD.  \"\n             \"It will be an embedding with numSingularValues elements.\",\n             PathElement(\"embedding\"));\n    addField(\"modelFileUrl\", &SvdConfig::modelFileUrl,\n             \"URL where the model file (with extension '.svd') should be saved. \"\n             \"This file can be loaded by the ![](%%doclink svd.embedRow function). \"\n             \"This parameter is optional unless the `functionName` parameter is used.\");\n    addField(\"functionName\", &SvdConfig::functionName,\n             \"If specified, an instance of the ![](%%doclink svd.embedRow function) of this name will be created using \"\n             \"the trained model. Note that to use this parameter, the `modelFileUrl` must \"\n             \"also be provided.\");\n    addParent<ProcedureConfig>();\n\n    onPostValidate = chain(validateQuery(&SvdConfig::trainingData,\n                                         NoGroupByHaving(),\n                                         MustContainFrom()),\n                           validateFunction<SvdConfig>());\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(SimpleIntersectionEntry);\n\nSimpleIntersectionEntryDescription::\nSimpleIntersectionEntryDescription()\n{\n    addParent<ColumnSpec>();\n    addField(\"singularVector\", &SimpleIntersectionEntry::singularVector,\n             \"Singular vector for this column\");\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(SvdColumnIndexEntry);\n\nSvdColumnIndexEntryDescription::\nSvdColumnIndexEntryDescription()\n{\n    addField(\"columnName\", &SvdColumnIndexEntry::columnName,\n             \"Name of the column\");\n    addField(\"values\", &SvdColumnIndexEntry::values,\n             \"Values of fields for this column\");\n}\n\n/** Given the other column, project it onto the basis. */\ndistribution<float>\nSvdBasis::\nrightSingularVector(const ColumnIndexEntries & basisColumns,\n                    const ColumnIndexEntry & column,\n                    shared_ptr<spdlog::logger> logger) const\n{\n    // For each basis vector, calculate the overlap\n    distribution<float> result(singularValues.size());\n\n    for (unsigned i = 0;  i < columns.size();  ++i) {\n        double overlap = column.correlation(basisColumns.at(i));\n        if (overlap == 0.0)\n            continue;\n        result += overlap * columns[i].singularVector;\n    }\n\n    result /= singularValues * singularValues;\n\n    if (logger->should_log(spdlog::level::trace) && (result == 0.0).all()) {\n        logger->trace() <<  \"all zero projection\"\n                        << \"column \" << column.columnName;\n\n        for (unsigned i = 0;  i < columns.size();  ++i) {\n            double overlap = column.correlation(basisColumns.at(i));\n            logger->trace() << \"overlap with \" << columns[i].columnName\n                            << \" is \" << overlap;\n        }\n        \n    }\n    \n    return result;\n}\n\ndistribution<float>\nSvdBasis::\nrightSingularVectorForColumn(ColumnHash col, const CellValue & value,\n                             int maxValues,\n                             bool acceptUnknownValues,\n                             shared_ptr<spdlog::logger> logger) const\n{\n    if (maxValues < 0 || maxValues > singularValues.size())\n        maxValues = singularValues.size();\n\n    // 1.  Find the columns involved with the index\n    auto it = columnIndex.find(col);\n    if (it == columnIndex.end()) {\n        TRACE_MSG(logger) << \"column \" << col << \" not found in \"\n                          << columnIndex.size() << \" entries\";\n        return distribution<float>();\n    }\n\n    // 2.  Look up the value of the cell\n    const SvdColumnIndexEntry & columnEntry = it->second;\n\n    auto it2 = columnEntry.values.find(value);\n    if (it2 == columnEntry.values.end()) {\n        // Extract the cell value...\n        if (value.isNumeric()) {\n            double d = value.toDouble();\n\n            TRACE_MSG(logger) << \"looking into \" << columnEntry.values.size() << \" values\"\n                              << \" for column \" << it->second.columnName;\n\n            for (auto & e: columnEntry.values) {\n                if (logger->should_log(spdlog::level::trace)) {\n                    logger->trace() << \"e.first = \" << jsonEncodeStr(e.first);\n                    logger->trace() << \"e.first.cellType() = \" << jsonEncodeStr(e.first.cellType());\n                    logger->trace() << \"e.second = \" << e.second;\n                }\n\n                if (!e.first.empty() && e.first != value)\n                    continue;\n                int columnNum = e.second;\n                auto & col = columns[columnNum];\n                distribution<float> result = col.singularVector;\n                result.resize(maxValues);\n\n                double oldd = d;\n\n                d += col.offset;\n                d *= col.scale;\n\n                TRACE_MSG(logger) << \"value \" << oldd << \" transformed to \" << d;\n\n                result *= d;\n                return result;\n            }\n\n            if (columnEntry.values.size() == 1) {\n                // MLDB-687\n                // We saw only a single value in training, which makes it\n                // essentially a \"has value\" or \"doesn't have value\"\n                // feature.  Take the output for the one and only value\n                // seen in training.\n\n                auto & col = columns[columnEntry.values.begin()->second];\n\n                distribution<float> result = col.singularVector;\n                result.resize(maxValues);\n\n                double oldd = d;\n\n                d += col.offset;\n                d *= col.scale;\n\n                TRACE_MSG(logger) << \"value \" << oldd << \" transformed to \" << d;\n\n                result *= d;\n                return result;\n            }\n\n        }\n\n        if (acceptUnknownValues) {\n            DEBUG_MSG(logger) << \"Numeric value not found\";\n            return distribution<float>();\n        }\n\n        Json::Value details;\n        details[\"columnName\"] = jsonEncode(it->second.columnName);\n        details[\"columnValueNotFound\"] = jsonEncode(value);\n        details[\"columnValueNotFoundType\"] = jsonEncode(value.cellType());\n\n        auto & vals = details[\"firstTenknownColumnValues\"];\n\n        bool expectedNumber = false;\n        bool onlyNumber = true;\n        for (auto & v: it->second.values) {\n            if (vals.size() >= 10)\n                break;\n\n            auto & col = columns.at(v.second);\n\n            Json::Value thisVal;\n            if (col.op == COL_VALUE) {\n                thisVal = \"<<any number>>\";\n                expectedNumber = true;\n            }\n            else {\n                thisVal = jsonEncode(v.first);\n                onlyNumber = false;\n            }\n\n            vals.append(thisVal);\n        }\n\n        Utf8String message;\n        if (value.isNumeric()) {\n            message = \"Column '\" + it->second.columnName.toUtf8String()\n                + \"' was a string in training but has numeric value \"\n                + jsonEncodeUtf8(value) + \" when passed to SVD\";\n        }\n        else if (expectedNumber && onlyNumber) {\n            message = \"Column '\" + it->second.columnName.toUtf8String()\n                + \"' passed as a string value \" + jsonEncodeUtf8(value)\n                + \" but only numbers were seen in training\";\n        }\n        else {\n            message = \"Column '\" + it->second.columnName.toUtf8String()\n                + \"' passed a value \" + jsonEncodeUtf8(value)\n                + \" that was never seen in training when passed to SVD\";\n        }\n\n        DEBUG_MSG(logger) << details;\n\n        throw AnnotatedException(400, message, details);\n    }\n\n    distribution<float> result = columns[it2->second].singularVector;\n    result.resize(maxValues);\n    return result;\n}\n\nstd::pair<distribution<float>, Date>\nSvdBasis::\nleftSingularVector(const std::vector<std::tuple<ColumnPath, CellValue, Date> > & row,\n                   int maxValues,\n                   bool acceptUnknownValues,\n                   shared_ptr<spdlog::logger> logger) const\n{\n    return doLeftSingularVector(row, maxValues, acceptUnknownValues, logger);\n}\n\nstd::pair<distribution<float>, Date>\nSvdBasis::\nleftSingularVector(const std::vector<std::tuple<ColumnHash, CellValue, Date> > & row,\n                   int maxValues,\n                   bool acceptUnknownValues,\n                   shared_ptr<spdlog::logger> logger) const\n{\n    return doLeftSingularVector(row, maxValues, acceptUnknownValues, logger);\n}\n\ntemplate<typename Tuple>\nstd::pair<distribution<float>, Date>\nSvdBasis::\ndoLeftSingularVector(const std::vector<Tuple> & row,\n                     int maxValues,\n                     bool acceptUnknownValues,\n                     shared_ptr<spdlog::logger> logger) const\n{\n    if (maxValues < 0 || maxValues > singularValues.size())\n        maxValues = singularValues.size();\n\n    Date ts = modelTs;\n    distribution<float> result(maxValues);\n\n    for (auto & v: row) {\n        ColumnHash column;\n        CellValue value;\n        Date columnTs;\n\n        std::tie(column, value, columnTs) = v;\n\n        const distribution<float> & rsv\n            = rightSingularVectorForColumn(column, value, maxValues, acceptUnknownValues, logger);\n\n        // If it was excluded, it will have an empty vector calculated\n        if (rsv.empty())\n            continue;\n        result += rsv;\n        ts.setMax(columnTs);\n    }\n\n    for (unsigned i = 0;  i < result.size();  ++i)\n        result[i] /= singularValues[i];\n\n    return make_pair(std::move(result), ts);\n}\n\nvoid\nSvdBasis::\nvalidate()\n{\n    for (unsigned i = 0;  i < columns.size();  ++i) {\n        auto & c = columns[i];\n        ExcAssert(columnIndex.count(c.columnName));\n        ExcAssert(columnIndex[c.columnName].values.count(c.cellValue));\n        ExcAssertEqual(columnIndex[c.columnName].columnName, c.columnName);\n        ExcAssertEqual(columnIndex[c.columnName].values[c.cellValue], i);\n        if (c.op == COL_VALUE)\n            ExcAssertEqual(c.cellValue, CellValue());\n    }\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(SvdBasis);\n\nSvdBasisDescription::\nSvdBasisDescription()\n{\n    addField(\"columns\", &SvdBasis::columns, \"Columns of SVD\");\n    addField(\"singularValues\", &SvdBasis::singularValues,\n             \"Singular values of SVD\");\n    addField(\"columnIndex\", &SvdBasis::columnIndex, \"Index of columns\");\n    addField(\"modelTs\", &SvdBasis::modelTs, \"Timestamp of latest information incorporated into model\");\n}\n\nstruct SvdTrainer {\n    static SvdBasis calcSvdBasis(const ColumnCorrelations & correlations,\n                                 int numSingularValues,\n                                 shared_ptr<spdlog::logger> logger);\n\n    static SvdBasis calcRightSingular(const ClassifiedColumns & columns,\n                                      const ColumnIndexEntries & columnIndex,\n                                      const SvdBasis & svd,\n                                      shared_ptr<spdlog::logger> logger);\n};\n\nSvdBasis\nSvdTrainer::\ncalcSvdBasis(const ColumnCorrelations & correlations,\n             int numSingularValues,\n             shared_ptr<spdlog::logger> logger)\n{\n#if 0\n    static int n = 0;\n    {\n        INFO_MSG(logger) << \"saving correlations \" << n;\n        filter_ostream stream(MLDB::format(\"correlations-%d.json\", n++));\n        stream << jsonEncode(correlations.columns);\n        for (unsigned i = 0;  i < correlations.correlations.shape()[0];  ++i) {\n            for (unsigned j = 0;  j < correlations.correlations.shape()[1];  ++j) {\n                stream << i << \" \" << j << \" \" << correlations.correlations[i][j]\n                       << endl;\n            }\n        }\n        INFO_MSG(logger) << \"done saving correlations \";\n    }\n#endif\n\n    int ndims = correlations.columnCount();\n\n    Timer timer;\n\n    if (logger->should_log(spdlog::level::trace)) {\n        for (unsigned i = 0;  i < ndims;  ++i) {\n            logger->trace() << \"correlation between \" << 0 << \" and \"\n                            << i << \" is \" << correlations.correlations[0][i];\n        }\n    }\n\n    /**************************************************************\n     * multiplication of matrix B by vector x, where B = A'A,     *\n     * and A is nrow by ncol (nrow >> ncol). Hence, B is of order *\n     * n = ncol (y stores product vector).\t\t              *\n     **************************************************************/\n\n    auto opb_fn = [&] (const double * x, double * y)\n    {\n        for (unsigned i = 0; i != ndims; i++) {\n            y[i] = MLDB::SIMD::vec_dotprod_dp(&correlations.correlations[i][0], x, ndims);\n        }\n    };\n\n    SVDParams params;\n    params.opb = opb_fn;\n    params.ierr = 0;\n    params.nrows = ndims;\n    params.ncols = ndims;\n    params.nvals = 0;\n    params.doU = false;\n    params.calcPrecision(params.ncols);\n\n    svdrec * svdResult = svdLAS2A(numSingularValues, params);\n    Scope_Exit(svdFreeSVDRec(svdResult));\n\n    INFO_MSG(logger) << \"done SVD \" << timer.elapsed();\n\n    // It doesn't clean up the ones that didn't converge properly... do it ourselves\n    // We go until we get a NaN or one with too small a ratio.\n    // Eg, seen in the wild:\n    // svalues = { 3.06081 2.01797 1.91045 1.39165 1.20556 1.0859 1.01295 0.973041 0.96686 0.795663 0.787847 0.753074 0.663018 0.58732 0.566861 0.53674 0.507972 0.481893 0.476135 0.451054 0.434212 0.428739 0.406749 0.396502 0.388368 0.383147 0.381553 0.34724 0.322744 0.311273 0.297784 0.285271 0.275972 0.272025 0.271609 0.265779 0.254749 0.244108 0.234286 0.229235 0.21586 0.208849 0.207129 0.194427 0.186311 0.184302 0.18284 0.170876 0.1612 0.153722 0.145908 0.145039 0.139881 0.136478 0.134853 0.131319 0.124427 0.112027 0.0839514 0.0766772 0.0687135 0.0484199 0.0354719 0.034498 9.62614e-05 7.98612e-05 7.48308e-05 6.6479e-05 5.5881e-05 5.00391e-05 4.59796e-05 4.33525e-05 3.0214e-05 2.67698e-05 2.66379e-05 1.749e-05 1.64916e-05 1.20429e-05 5.02268e-08 -nan -nan -nan -nan 2.46486e-09 -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan 1.61711e-08 }\n\n    unsigned realD = 0;\n    while (realD < svdResult->d\n           && isfinite(svdResult->S[realD])\n           && svdResult->S[realD] / svdResult->S[0] > 1e-9)\n        ++realD;\n\n    INFO_MSG(logger) << \"skipped \" << svdResult->d - realD << \" bad singular values\";\n    ExcAssertLessEqual(realD, svdResult->d);\n    ExcAssertLessEqual(realD, numSingularValues);\n    svdResult->d = realD;\n\n    INFO_MSG(logger) << \"got \" << svdResult->d << \" singular values\";\n\n    numSingularValues = svdResult->d;\n\n    TRACE_MSG(logger) << \"Vt rows \" << svdResult->Vt->rows;\n    TRACE_MSG(logger) << \"Vt cols \" << svdResult->Vt->cols;\n\n    SvdBasis result;\n    result.modelTs = correlations.modelTs;\n    result.singularValues.resize(numSingularValues);\n    std::copy(svdResult->S, svdResult->S + numSingularValues,\n              result.singularValues.begin());\n\n    INFO_MSG(logger) << \"svalues = \" << result.singularValues;\n\n    result.columns.resize(ndims);\n    std::copy(correlations.columns.begin(), correlations.columns.end(),\n              result.columns.begin());\n\n#if 1\n    // Extract the singular vectors for the dense behaviours\n    for (unsigned i = 0;  i < ndims;  ++i) {\n\n        distribution<float> & d = result.columns[i].singularVector;\n        d.resize(numSingularValues);\n        for (unsigned j = 0;  j < numSingularValues;  ++j)\n            d[j] = svdResult->Vt->value[j][i];\n\n        ColumnPath columnName = result.columns[i].columnName;\n        CellValue cellValue = result.columns[i].cellValue;\n\n        result.columnIndex[columnName].values[cellValue] = i;\n        result.columnIndex[columnName].columnName = columnName;\n\n\n        //std::copy(svdResult->Vt->value[i],\n        //          svdResult->Vt->value[i] + numSingularValues,\n        //          d.begin());\n    }\n#endif\n\n    TRACE_MSG(logger) << \"result.columnIndex.size() = \" << result.columnIndex.size();\n    TRACE_MSG(logger) << \"ndims = \" << ndims;\n\n    for (auto & i: result.columnIndex)\n        ExcAssertNotEqual(i.second.columnName, ColumnPath());\n\n    if (logger->should_log(spdlog::level::trace)) {\n        logger->trace() << \"Testing the orthonormal-ness of the singular vectors\";\n\n        for (unsigned i = 0;  i < ndims;  ++i) {\n            const auto & v = result.columns[i].singularVector;\n              logger->trace() << \"dim \" << i << \": two_norm = \" << v.two_norm() << \" min \" << v.min()\n                              << \" max \" << v.max() << \" one_norm \" << v.total();\n        }\n\n        for (unsigned i = 0;  i < ndims;  ++i) {\n              logger->trace() << \"dim 0 with dim \" << i << \": two_norm = \"\n                              << result.columns[i].singularVector.dotprod(result.columns[0].singularVector);\n        }\n    }\n\n    return result;\n}\n\nSvdBasis\nSvdTrainer::\ncalcRightSingular(const ClassifiedColumns & columns,\n                  const ColumnIndexEntries & columnIndex,\n                  const SvdBasis & svd,\n                  shared_ptr<spdlog::logger> logger)\n\n{\n    DEBUG_MSG(logger) << \"project extra \" << columns.continuousColumns.size() - svd.columns.size()\n                      << \" continuous columns onto basis\";\n    DEBUG_MSG(logger) << \"projecting \" << columns.sparseColumns.size()\n                      << \" discrete columns onto basis\";\n\n    Timer timer;\n\n    std::atomic<int> numDone(0);\n    double lastSeconds = 0.0;\n\n    size_t totalColumns = columns.continuousColumns.size() + columns.sparseColumns.size();\n\n    SvdBasis result(svd);\n    result.modelTs = svd.modelTs;\n    result.columns.resize(totalColumns);\n\n    auto outputFirstRightSingular = [&svd, logger](const ColumnIndexEntries & columnIndex) {\n        stringstream output;\n\n        // Calc the right singular of the first continuous column\n        auto vec0 = svd.rightSingularVector(columnIndex, columnIndex[0], logger);\n        auto svec = svd.columns[0].singularVector;\n\n        vec0.resize(10);\n        svec.resize(10);\n\n        output << \"vec0 = \" << vec0 << \" svec = \" << svec;\n        return output.str();\n    };\n\n    if (logger->should_log(spdlog::level::debug) && svd.columns.size() > 0)\n        logger->debug() << outputFirstRightSingular(columnIndex);\n\n    auto calcRightSingular = [&] (int i)\n        {\n            int done = numDone.fetch_add(1);\n\n            // If we've already done it, then skip\n            if (!result.columns[i].singularVector.empty())\n                return;\n\n            auto vec = svd.rightSingularVector(columnIndex, columnIndex[i], logger);\n\n            SimpleIntersectionEntry column;\n            column = columnIndex[i];\n            column.singularVector = std::move(vec);\n\n            result.columns[i] = std::move(column);\n\n            if (done % 1000 == 0) {\n                double seconds = timer.elapsed_wall();\n                INFO_MSG(logger) << \"done \" << done << \" of \" << totalColumns\n                     << \" in \" << timer.elapsed();\n                INFO_MSG(logger) << \"Average \" << done / seconds << \" per second; inst \"\n                     << 1000 / (seconds - lastSeconds) << \" per second\";\n                lastSeconds = seconds;\n            }\n        };\n\n    parallelMap(0, totalColumns, calcRightSingular);\n\n    for (unsigned i = 0;  i < totalColumns;  ++i) {\n        ColumnPath columnName = result.columns[i].columnName;\n        CellValue cellValue = result.columns[i].cellValue;\n        if (result.columns[i].op == COL_VALUE)\n            ExcAssertEqual(cellValue, CellValue());\n\n        TRACE_MSG(logger) << \"column \" << i << \" name \" << columnName\n                          << \" value \" << jsonEncodeStr(cellValue) << \" op \"\n                          << result.columns[i].op;\n\n        result.columnIndex[columnName].values[cellValue] = i;\n        result.columnIndex[columnName].columnName = columnName;\n    }\n\n    for (auto & i: result.columnIndex) {\n        ExcAssertNotEqual(i.second.columnName, ColumnPath());\n        for (auto & v: i.second.values) {\n            auto col = result.columns.at(v.second);\n            auto val = v.first;\n\n            ExcAssertEqual(val, col.cellValue);\n            ExcAssertEqual(i.second.columnName, col.columnName);\n\n            if (col.op == COL_VALUE)\n                ExcAssertEqual(val, CellValue());\n        }\n    }\n\n    ExcAssertLessEqual(result.columnIndex.size(), result.columns.size());\n\n    for (auto & c: result.columns) {\n        ExcAssertNotEqual(c.columnName, ColumnPath());\n    }\n\n    return result;\n}\n\n\n/*****************************************************************************/\n/* SVD PROCEDURE                                                              */\n/*****************************************************************************/\n\nSvdProcedure::\nSvdProcedure(MldbEngine * owner,\n            PolyConfig config,\n            const std::function<bool (const Json::Value &)> & onProgress)\n    : Procedure(owner)\n{\n    this->svdConfig = config.params.convert<SvdConfig>();\n}\n\nAny\nSvdProcedure::\ngetStatus() const\n{\n    return Any();\n}\n\nRunOutput\nSvdProcedure::\nrun(const ProcedureRunConfig & run,\n      const std::function<bool (const Json::Value &)> & onProgress) const\n{\n    auto runProcConf = applyRunConfOverProcConf(svdConfig, run);\n\n    if (runProcConf.outputColumn.null()) {\n        throw AnnotatedException\n            (400, \"SVD training procedure requires a non-empty output column name\",\n             \"config\", runProcConf);\n    }\n\n    if (!runProcConf.modelFileUrl.empty()) {\n        checkWritability(runProcConf.modelFileUrl.toDecodedString(), \"modelFileUrl\");\n    }\n\n    int numBasisVectors = runProcConf.numDenseBasisVectors;\n    \n    SqlExpressionMldbScope context(engine);\n    \n    ConvertProgressToJson convertProgressToJson(onProgress);\n    auto dataset = runProcConf.trainingData.stm->from->bind(context, convertProgressToJson).dataset;\n\n    Progress svdProgress;\n    std::shared_ptr<Step> classificationStep = svdProgress.steps({\n            make_pair(\"classifying columns\", \"percentile\"), \n            make_pair(\"extracting features\", \"percentile\"),\n            make_pair(\"inverting features\", \"percentile\"),\n            make_pair(\"calculating correlations\", \"percentile\")\n            });\n\n\n    ClassifiedColumns columns = classifyColumns(runProcConf.trainingData.stm->select,\n                                                *dataset,\n                                                runProcConf.trainingData.stm->when,\n                                                *runProcConf.trainingData.stm->where,\n                                                runProcConf.trainingData.stm->orderBy,\n                                                runProcConf.trainingData.stm->offset,\n                                                runProcConf.trainingData.stm->limit,\n                                                logger,\n                                                convertProgressToJson);\n\n    auto outputColumns = [](const ClassifiedColumns & columns) {\n        stringstream output;\n        output << \"continuous columns are:\" << endl;\n        for (auto & c: columns.continuousColumns) {\n            output << \"name \" << c.columnName << \" val \" << c.cellValue << \" op \" << c.op\n                   << \" rowCount \" << c.rowCount << endl;;\n        }\n        output << \"sparse columns are:\" << endl;\n        for (auto & c: columns.sparseColumns) {\n            output << \"name \" << c.columnName << \" val \" << c.cellValue << \" op \" << c.op\n                   << \" rowCount \" << c.rowCount << endl;\n        }\n        return output.str();\n    };\n\n    DEBUG_MSG(logger) <<  \"classified columns: \" << columns.continuousColumns.size()\n                      << \" continuous columns, \" << columns.sparseColumns.size()\n                      << \" sparse columns\";\n    DEBUG_MSG(logger) << outputColumns(columns);\n\n    auto extractionStep = classificationStep->nextStep(1);\n\n    FeatureBuckets extractedFeatures = extractFeaturesFromRows(runProcConf.trainingData.stm->select,\n                                                               *dataset,\n                                                               runProcConf.trainingData.stm->when,\n                                                               runProcConf.trainingData.stm->where,\n                                                               runProcConf.trainingData.stm->orderBy,\n                                                               runProcConf.trainingData.stm->offset,\n                                                               runProcConf.trainingData.stm->limit,\n                                                               columns,\n                                                               logger,\n                                                               convertProgressToJson);\n\n    auto inversionStep = extractionStep->nextStep(1);\n\n    ColumnIndexEntries columnIndex = invertFeatures(columns, extractedFeatures, logger, convertProgressToJson);\n\n    ColumnCorrelations correlations = calculateCorrelations(columnIndex, numBasisVectors, logger);\n    SvdBasis svd = SvdTrainer::calcSvdBasis(correlations,\n                                            runProcConf.numSingularValues,\n                                            logger);\n\n    auto outputSvdColumns = [](const SvdBasis & basis) {\n        stringstream output;\n         for (auto & c: basis.columns) {\n             output << \"name \" << c.columnName << \" val \" << c.cellValue << \" op \" << c.op << endl;\n         }\n        return output.str();\n    };\n\n    DEBUG_MSG(logger) << \"----------- SVD columns\";\n    DEBUG_MSG(logger) << outputSvdColumns(svd);\n   \n    SvdBasis allSvd = SvdTrainer::calcRightSingular(columns, columnIndex, svd, logger);\n\n    DEBUG_MSG(logger) << \"----------- ALL SVD columns\";\n    DEBUG_MSG(logger) << outputSvdColumns(allSvd);\n\n    if (!runProcConf.modelFileUrl.empty()) {\n        makeUriDirectory(runProcConf.modelFileUrl.toDecodedString());\n        filter_ostream stream(runProcConf.modelFileUrl);\n        jsonEncodeToStream(allSvd, stream);\n    }\n\n    Date ts;  // TODO: actually fill this in...\n\n    // Save the column embedding to a dataset if we ask for it\n    if (runProcConf.columnOutput) {\n\n        PolyConfigT<Dataset> columnOutput = *runProcConf.columnOutput;\n        if (columnOutput.type.empty())\n            columnOutput.type = SvdConfig::defaultOutputDatasetType;\n\n        auto onProgress2 = [&] (const Json::Value & progress) {\n            Json::Value value;\n            value[\"dataset\"] = progress;\n            return onProgress(value);\n        };\n\n        auto output = createDataset(engine, columnOutput, onProgress2, true /*overwrite*/);\n\n        auto doColumn = [&] (size_t i)\n            {\n                auto & col = allSvd.columns[i];\n\n                if (i % 10000 == 0)\n                    INFO_MSG(logger) << \"saving column \" << i << \" of \" << allSvd.columns.size();\n\n                ColumnPath outputName = col.columnName;\n\n                if (col.op == COL_EQUAL) {\n                    if (col.cellValue.empty()) {\n                        outputName = outputName + PathElement(\"isNull\");\n                    }\n                    else if (col.cellValue.isNumber()) {\n                        outputName = outputName + PathElement(\"numberEquals\")\n                            + col.cellValue.toUtf8String();\n                    }\n                    else if (col.cellValue.isString()) {\n                        if (col.cellValue.toUtf8String().empty()) {\n                            outputName = outputName + PathElement(\"stringEmpty\");\n                        }\n                        else {\n                            outputName = outputName + PathElement(\"stringEquals\")\n                                + col.cellValue.toUtf8String();\n                        }\n                    }\n#if 0\n                    else if (col.cellValue.isTimestamp()) {\n                    }\n                    else if (col.cellValue.isTimeinterval()) {\n                    }\n                    else if (col.cellValue.isBlob()) {\n                    }\n#endif\n                    else {\n                        throw AnnotatedException\n                            (400,\"Can't apply an SVD to a column that's not \"\n                             \"numeric or categorical (string)\",\n                             \"columnValue\", col.cellValue,\n                             \"columnName\", col.columnName);\n                    }\n                }\n                else if (col.op == COL_VALUE) {\n                    outputName = outputName + PathElement(\"numericValue\");\n                }\n                try {\n                    StructValue cols;\n                    cols.emplace_back(runProcConf.outputColumn,\n                                      ExpressionValue(col.singularVector, ts));\n                    output->recordRowExpr(outputName, std::move(cols));\n                } catch (const std::exception & exc) {\n                    rethrowException(-1, \"Error adding SVD column '\" + outputName.toUtf8String() + \"' to output: \"\n                                         + exc.what(),\n                                         \"columnName\", outputName);\n                }\n            };\n\n        parallelMap(0, allSvd.columns.size(), doColumn);\n\n        output->commit();\n    }\n\n    // Save the row embedding to a dataset.  This is optional (it's not actually\n    // needed to apply the SVD).\n\n    if (runProcConf.rowOutput) {\n\n        PolyConfigT<Dataset> rowOutput = *runProcConf.rowOutput;\n        if (rowOutput.type.empty())\n            rowOutput.type = SvdConfig::defaultOutputDatasetType;\n\n        auto onProgress2 = [&] (const Json::Value & progress) {\n            Json::Value value;\n            value[\"dataset\"] = progress;\n            return onProgress(value);\n        };\n        auto output = createDataset(engine, rowOutput, onProgress2, true /*overwrite*/);\n\n        // getRowPaths can return row names in an arbitrary order as long as it is deterministic.\n        auto rows = dataset->getMatrixView()->getRowPaths(0, -1);\n\n        DEBUG_MSG(logger) << \"writing embeddings for \" << rows.size() << \" rows to dataset \"\n                          << runProcConf.rowOutput->id;\n\n        int numSingularValues = allSvd.numSingularValues();\n\n        auto doRow = [&] (int rowNum)\n            {\n                if (rowNum % 10000 == 0)\n                    INFO_MSG(logger) << \"saving row \" << rowNum << \" of \" << rows.size();\n\n                auto row = dataset->getMatrixView()->getRow(rows[rowNum]);\n\n                distribution<float> embedding;\n                Date ts;\n\n                std::tie(embedding, ts)\n                = allSvd.leftSingularVector(row.columns, numSingularValues,\n                                            false /* acceptUnknownValues*/,\n                                            logger);\n\n                StructValue cols;\n                cols.emplace_back(runProcConf.outputColumn,\n                                  ExpressionValue(std::move(embedding), ts));\n                output->recordRowExpr(row.rowName, std::move(cols));\n            };\n\n        parallelMap(0, rows.size(), doRow);\n\n        output->commit();\n    }\n\n    if(!runProcConf.functionName.empty()) {\n        PolyConfig svdFuncPC;\n        svdFuncPC.type = \"svd.embedRow\";\n        svdFuncPC.id = runProcConf.functionName;\n        svdFuncPC.params = SvdEmbedConfig(runProcConf.modelFileUrl);\n\n        createFunction(engine, svdFuncPC, onProgress, true);\n    }\n\n    return Any();\n}\n\n\n/*****************************************************************************/\n/* SVD EMBED ROW                                                             */\n/*****************************************************************************/\n\nDEFINE_STRUCTURE_DESCRIPTION(SvdEmbedConfig);\n\nSvdEmbedConfigDescription::\nSvdEmbedConfigDescription()\n{\n    addField(\"modelFileUrl\", &SvdEmbedConfig::modelFileUrl,\n             \"URL of the model file (with extension '.svd') to load. \"\n             \"This file is created by the ![](%%doclink svd.train procedure).\");\n    addField(\"maxSingularValues\", &SvdEmbedConfig::maxSingularValues,\n             \"Maximum number of singular values to use (-1 = all)\", -1);\n    addField(\"acceptUnknownValues\", &SvdEmbedConfig::acceptUnknownValues,\n             \"This parameter (which defaults to false) tells us whether or \"\n             \"not unknown values should be accepted by the SVD.  An unknown \"\n             \"value occurs when a column that was always a number in training \"\n             \"is presented with a string value, or vice versa, or when a \"\n             \"string valued column is presented with a value unknown in \"\n             \"training.  If its value is true, an unknown value will be \"\n             \"silently ignored.  If its value is false, an unknown value \"\n             \"will return an error when the function is applied.\",\n             false);\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(SvdInput);\n\nSvdInputDescription::\nSvdInputDescription()\n{\n    addField(\"row\", &SvdInput::row,\n             \"Row to apply SVD to.  The embedding will be the average of \"\n             \"the SVD of each of the keys of the row.\");\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(SvdOutput);\n\nSvdOutputDescription::\nSvdOutputDescription()\n{\n    addField(\"embedding\", &SvdOutput::embedding,\n             \"Embedding of the row into the vector space defined by the \"\n             \"SVD.  There will be a number of coordinates equal to the \"\n             \"`maxSingluarValues` value of the configuration, or if not \"\n             \"set, the number of SVD coordinates available in the SVD model \"\n             \"file.  PathElementinates will have simple numerical names.\");\n}\n\n\nSvdEmbedRow::\nSvdEmbedRow(MldbEngine * owner,\n            PolyConfig config,\n            const std::function<bool (const Json::Value &)> & onProgress)\n    : BaseT(owner, config)\n{\n    functionConfig = config.params.convert<SvdEmbedConfig>();\n    svd = jsonDecodeFile<SvdBasis>(functionConfig.modelFileUrl.toDecodedString());\n\n    std::map<ColumnHash, SvdColumnIndexEntry> columnIndex2;\n\n    // Deal with the older version of the file\n    for (auto & c: svd.columnIndex) {\n        columnIndex2[c.second.columnName] = std::move(c.second);\n    }\n\n    svd.columnIndex = std::move(columnIndex2);\n\n    svd.validate();\n\n    nsv = functionConfig.maxSingularValues;\n    if (nsv < 0 || nsv > svd.numSingularValues())\n        nsv = svd.numSingularValues();\n}\n\nSvdOutput\nSvdEmbedRow::\ncall(SvdInput input) const\n{\n    RowValue row;\n    input.row.mergeToRowDestructive(row);\n    \n    distribution<float> embedding;\n    Date ts;\n\n    std::tie(embedding, ts)\n        = svd.leftSingularVector(row, nsv,\n                                 functionConfig.acceptUnknownValues,\n                                 logger);\n\n    DEBUG_MSG(logger) << \"nsv = \" << nsv;\n    DEBUG_MSG(logger) << \"embedding = \" << embedding;\n\n    // TODO: what to do when no embedding is returned?\n    if (embedding.empty())\n        embedding.resize(nsv);\n\n    SvdOutput result;\n    result.embedding = ExpressionValue(std::move((vector<float> &)embedding), ts);\n    \n    return result;\n}\n\nnamespace {\n\nRegisterProcedureType<SvdProcedure, SvdConfig>\nregSvd(builtinPackage(),\n       \"Train a SVD to convert rows or columns to embedding coordinates\",\n       \"procedures/Svd.md.html\");\n\nRegisterFunctionType<SvdEmbedRow, SvdEmbedConfig>\nregSvdEmbedRow(builtinPackage(),\n               \"svd.embedRow\",\n               \"Apply a trained SVD to embed a row into a coordinate space\",\n               \"functions/SvdEmbedRow.md.html\");\n\nstruct InitSvdParallelMap {\n    InitSvdParallelMap()\n    {\n        svdParallelMap = &MLDB::parallelMap;\n    }\n    \n} initSvdParallelMap;\n\n} // file scope\n\n} // namespace MLDB\n\n", "meta": {"hexsha": "473d49c1437649f8767cfea0744b2dca36b91c5e", "size": 39132, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/embedding/svd.cc", "max_stars_repo_name": "mldbai/mldb", "max_stars_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 665.0, "max_stars_repo_stars_event_min_datetime": "2015-12-09T17:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:46:46.000Z", "max_issues_repo_path": "plugins/embedding/svd.cc", "max_issues_repo_name": "mldbai/mldb", "max_issues_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 797.0, "max_issues_repo_issues_event_min_datetime": "2015-12-09T19:48:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T02:19:47.000Z", "max_forks_repo_path": "plugins/embedding/svd.cc", "max_forks_repo_name": "mldbai/mldb", "max_forks_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 103.0, "max_forks_repo_forks_event_min_datetime": "2015-12-25T04:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T02:55:22.000Z", "avg_line_length": 37.4110898662, "max_line_length": 859, "alphanum_fraction": 0.5691250128, "num_tokens": 8840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.18103578963942565}}
{"text": "\n#ifndef CUFFT_DOUBLE_PRECSION\n#define CUFFT_DOUBLE_PRECISION 1\n#endif\n#include <cudatbx/cufft/cufft.hpp>\n\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\nnamespace cudatbx { namespace cufft {\n\n  void wrap_cufft_double_precision ()\n  {\n    using namespace boost::python;\n    def(\"real_to_complex_3d_in_place_dp\", real_to_complex_3d_in_place, (\n      arg(\"data\")));\n    def(\"complex_to_complex_3d_in_place_dp\", complex_to_complex_3d_in_place, (\n      arg(\"data\"),\n      arg(\"direction\")));\n    def(\"complex_to_real_3d_in_place_dp\", complex_to_real_3d_in_place, (\n      arg(\"data\"),\n      arg(\"n\")));\n  }\n\n}} // namespace cudatbx::cufft\n", "meta": {"hexsha": "3381a6fcd3c80383cbdb81c6a7b965477148a051", "size": 794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cudatbx/cufft/ext_double.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": "cudatbx/cufft/ext_double.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": "cudatbx/cufft/ext_double.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": 27.3793103448, "max_line_length": 78, "alphanum_fraction": 0.7329974811, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.18103578731277928}}
{"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_PREDICATES_FUNCTIONS_OPTIMIZE_IS_NOT_GREATER_EQUAL_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_PREDICATES_FUNCTIONS_OPTIMIZE_IS_NOT_GREATER_EQUAL_HPP_INCLUDED\n\n#include <boost/simd/toolbox/predicates/functions/is_not_greater_equal.hpp>\n#include <boost/simd/toolbox/operator/functions/is_greater_equal.hpp>\n#include <boost/simd/toolbox/operator/functions/logical_not.hpp>\n#include <boost/dispatch/dsl/category.hpp>\n#include <boost/dispatch/functor/preprocessor/call.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::logical_not_\n                                   , tag::formal_, (D)(A0)(Arity)\n                                   , ((node_<A0, boost::simd::tag::is_greater_equal_, Arity, D>))\n                                   )\n  {\n    BOOST_DISPATCH_RETURNS(1, (A0 const& a0),\n      is_not_greater_equal(boost::proto::child_c<0>(a0))\n    )\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "4b4dd13ef08885086fc23fa5dc9be3ee20b0e2b0", "size": 1454, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/predicates/include/boost/simd/toolbox/predicates/functions/optimize/is_not_greater_equal.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/predicates/include/boost/simd/toolbox/predicates/functions/optimize/is_not_greater_equal.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/predicates/include/boost/simd/toolbox/predicates/functions/optimize/is_not_greater_equal.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": 45.4375, "max_line_length": 97, "alphanum_fraction": 0.6011004127, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.1810293794159809}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2015-2017.\r\n// Modifications copyright (c) 2015-2017 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_STRATEGIES_GEOGRAPHIC_THOMAS_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_THOMAS_HPP\r\n\r\n\r\n#include <boost/geometry/strategies/geographic/distance.hpp>\r\n#include <boost/geometry/strategies/geographic/parameters.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace distance\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 second order terms.\r\n\\ingroup distance\r\n\\tparam Spheroid The reference spheroid model\r\n\\tparam CalculationType \\tparam_calculation\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<\r\n    typename Spheroid = srs::spheroid<double>,\r\n    typename CalculationType = void\r\n>\r\nclass thomas\r\n    : public strategy::distance::geographic\r\n        <\r\n            strategy::thomas, Spheroid, CalculationType\r\n        >\r\n{\r\n    typedef strategy::distance::geographic\r\n        <\r\n            strategy::thomas, Spheroid, CalculationType\r\n        > base_type;\r\n\r\npublic :\r\n    inline thomas()\r\n        : base_type()\r\n    {}\r\n\r\n    explicit inline thomas(Spheroid const& spheroid)\r\n        : base_type(spheroid)\r\n    {}\r\n};\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct tag<thomas<Spheroid, CalculationType> >\r\n{\r\n    typedef strategy_tag_distance_point_point type;\r\n};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\r\nstruct return_type<thomas<Spheroid, CalculationType>, P1, P2>\r\n    : thomas<Spheroid, CalculationType>::template calculation_type<P1, P2>\r\n{};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct comparable_type<thomas<Spheroid, CalculationType> >\r\n{\r\n    typedef thomas<Spheroid, CalculationType> type;\r\n};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct get_comparable<thomas<Spheroid, CalculationType> >\r\n{\r\n    static inline thomas<Spheroid, CalculationType> apply(thomas<Spheroid, CalculationType> const& input)\r\n    {\r\n        return input;\r\n    }\r\n};\r\n\r\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\r\nstruct result_from_distance<thomas<Spheroid, CalculationType>, P1, P2 >\r\n{\r\n    template <typename T>\r\n    static inline typename return_type<thomas<Spheroid, CalculationType>, P1, P2>::type\r\n        apply(thomas<Spheroid, CalculationType> const& , T const& value)\r\n    {\r\n        return value;\r\n    }\r\n};\r\n\r\n\r\n} // namespace services\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n}} // namespace strategy::distance\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_THOMAS_HPP\r\n", "meta": {"hexsha": "79fb59fb90b3e4474e1f9c7dae45dd8a6126b20f", "size": 3475, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/strategies/geographic/distance_thomas.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/geographic/distance_thomas.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/geographic/distance_thomas.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": 28.4836065574, "max_line_length": 106, "alphanum_fraction": 0.7220143885, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.18102937465024435}}
{"text": "#ifndef LM_NEURAL_WORDVECS_H\n#define LM_NEURAL_WORDVECS_H\n\n#include \"util/scoped.hh\"\n#include \"lm/vocab.hh\"\n\n#include <Eigen/Dense>\n\nnamespace util { class FilePiece; }\n\nnamespace lm {\nnamespace neural {\n\nclass WordVecs {\n  public:\n    // Columns of the matrix are word vectors.  The column index is the word.\n    typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> Storage;\n\n    /* The file should begin with a line stating the number of word vectors and\n     * the length of the vectors.  Then it's followed by lines containing a\n     * word followed by floating-point values.\n     */\n    explicit WordVecs(util::FilePiece &in);\n\n    const Storage &Vectors() const { return vecs_; }\n\n    WordIndex Index(StringPiece str) const { return vocab_.Index(str); }\n\n  private:\n    util::scoped_malloc vocab_backing_;\n    ngram::ProbingVocabulary vocab_;\n\n    Storage vecs_;\n};\n\n}} // namespaces\n\n#endif // LM_NEURAL_WORDVECS_H\n", "meta": {"hexsha": "921a2b22cfcc9c174daee807948984230cbdd4b6", "size": 947, "ext": "hh", "lang": "C++", "max_stars_repo_path": "kenlm/include/lm/neural/wordvecs.hh", "max_stars_repo_name": "pokey/w2ldecode", "max_stars_repo_head_hexsha": "03f9995a48c5c1043be309fe5b20c6126851a9ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 114.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T05:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T03:47:12.000Z", "max_issues_repo_path": "Part 02/001_LM/ngram_lm_lab/kenlm/include/lm/neural/wordvecs.hh", "max_issues_repo_name": "Kabongosalomon/AMMI-NLP", "max_issues_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T01:00:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-25T06:04:02.000Z", "max_forks_repo_path": "Part 02/001_LM/ngram_lm_lab/kenlm/include/lm/neural/wordvecs.hh", "max_forks_repo_name": "Kabongosalomon/AMMI-NLP", "max_forks_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T13:48:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-07T09:45:11.000Z", "avg_line_length": 24.2820512821, "max_line_length": 90, "alphanum_fraction": 0.7138331573, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3073580041760868, "lm_q1q2_score": 0.18099978791379143}}
{"text": "/*=============================================================================\nCopyright 2018 Pranam Lashkari <plashkari628@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_COORDINATE_ALT_AZ_HPP\n#define BOOST_ASTRONOMY_COORDINATE_ALT_AZ_HPP\n\n#include <type_traits>\n#include <tuple>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si/base.hpp>\n#include <boost/units/systems/si/pressure.hpp>\n#include <boost/units/systems/temperature/celsius.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/units/systems/si/volume.hpp>\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/astronomy/detail/is_base_template_of.hpp>\n#include <boost/astronomy/coordinate/ref_frame/base_frame.hpp>\n#include <boost/astronomy/coordinate/rep/representation.hpp>\n#include <boost/astronomy/coordinate/diff/differential.hpp>\n\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\ntemplate <typename Representation, typename Differential>\nstruct alt_az : public base_frame<Representation, Differential>\n{\n    ///@cond INTERNAL\n    BOOST_STATIC_ASSERT_MSG((std::is_base_of\n        <spherical_representation<typename Representation::type,\n        typename Representation::quantity1, typename Representation::quantity2,\n        typename Representation::quantity3>, Representation>::value),\n        \"argument type is expected to be a spherical_representation class\");\n    BOOST_STATIC_ASSERT_MSG((std::is_base_of\n        <spherical_coslat_differential<typename Differential::type,\n        typename Differential::quantity1, typename Differential::quantity2,\n        typename Differential::quantity3>, Differential>::value),\n        \"argument type is expected to be a spherical_coslat_differential class\");\n    ///@endcond\n\nprotected:\n    //frame parameters\n    spherical_equatorial_representation\n        <\n            double,\n            bu::quantity<bu::degree::plane_angle>,\n            bu::quantity<bu::degree::plane_angle>\n        > earth_location;\n\n    bu::quantity<bu::si::pressure> pressure = 0.0 * bu::si::pascals;\n    bu::quantity<bu::celsius::temperature> temperature = 0.0 * bu::celsius::degrees;\n    boost::posix_time::ptime obs_time;\n    bu::quantity<bu::si::dimensionless> relative_humidity = 0.0;\n\npublic:\n    alt_az() {}\n\n    template <typename OtherRepresentation>\n    alt_az(OtherRepresentation const& representation_data)\n    {\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n         <boost::astronomy::coordinate::base_representation, OtherRepresentation>::value),\n         \"Invalid representation class\");\n\n        auto temp = make_spherical_representation\n            <\n            typename Representation::type,\n            typename Representation::quantity1,\n            typename Representation::quantity2,\n            typename Representation::quantity3,\n            typename OtherRepresentation::type,\n            typename OtherRepresentation::quantity1,\n            typename OtherRepresentation::quantity2,\n            typename OtherRepresentation::quantity3\n            >(representation_data);\n\n        this->data = temp;\n    }\n\n    alt_az\n    (\n        typename Representation::quantity1 const& alt,\n        typename Representation::quantity2 const& az,\n        typename Representation::quantity3 const& distance\n    )\n    {\n        this->data.set_lat_lon_dist(alt, az, distance);\n    }\n\n    alt_az\n    (\n        typename Representation::quantity1 const& alt,\n        typename Representation::quantity2 const& az,\n        typename Representation::quantity3 const& distance,\n        typename Differential::quantity1 const& pm_alt,\n        typename Differential::quantity2 const& pm_az_cosalt,\n        typename Differential::quantity3 const& radial_velocity) :\n        alt_az(alt, az, distance)\n    {\n        this->motion.set_dlat_dlon_coslat_ddist(pm_alt, pm_az_cosalt, radial_velocity);\n    }\n\n    template <typename OtherRepresentation, typename OtherDifferential>\n    alt_az\n    (\n        OtherRepresentation const& representation_data,\n        OtherDifferential const& differential_data\n    )\n    {\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n         <boost::astronomy::coordinate::base_representation, OtherRepresentation>::value),\n         \"argument type is expected to be a representation class\");\n\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n          <boost::astronomy::coordinate::base_differential, OtherDifferential>::value),\n            \"argument type is expected to be a differential class\");\n\n        auto rep_temp = make_spherical_representation\n            <\n            typename Representation::type,\n            typename Representation::quantity1,\n            typename Representation::quantity2,\n            typename Representation::quantity3,\n            typename OtherRepresentation::type,\n            typename OtherRepresentation::quantity1,\n            typename OtherRepresentation::quantity2,\n            typename OtherRepresentation::quantity3\n            >(representation_data);\n        this->data = rep_temp;\n\n        auto dif_temp = make_spherical_coslat_differential\n            <\n            typename Differential::type,\n            typename Differential::quantity1,\n            typename Differential::quantity2,\n            typename Differential::quantity3,\n            typename OtherDifferential::type,\n            typename OtherDifferential::quantity1,\n            typename OtherDifferential::quantity2,\n            typename OtherDifferential::quantity3\n            >(differential_data);\n        this->motion = dif_temp;\n    }\n\n    alt_az(alt_az<Representation, Differential> const& other)\n    {\n        this->data = other.get_data();\n        this->motion = other.get_differential();\n        this->earth_location = other.get_location();\n        this->obs_time = other.get_obs_time();\n        this->pressure = other.get_pressure();\n        this->temperature = other.get_temprature();\n        this->relative_humidity = other.get_relative_humidity();\n    }\n\n    //!returns altitude component of the coordinate\n    typename Representation::quantity1 get_alt() const\n    {\n        return this->data.get_lat();\n    }\n\n    //!returns azimuth component of the coordinate\n    typename Representation::quantity2 get_az() const\n    {\n        return this->data.get_lon();\n    }\n\n    //!returns distance component of the coordinate\n    typename Representation::quantity3 get_distance() const\n    {\n        return this->data.get_dist();\n    }\n\n    //!returns the (alt, az, dist) in the form of tuple\n    std::tuple\n    <\n        typename Representation::quantity1,\n        typename Representation::quantity2,\n        typename Representation::quantity3\n    > get_alt_az_dist() const\n    {\n        return this->data.get_lat_lon_dist();\n    }\n\n    //!returns proper motion in altitude\n    typename Differential::quantity1 get_pm_alt() const\n    {\n        return this->motion.get_dlat();\n    }\n\n    //!returns proper motion in azimuth including cos(alt)\n    typename Differential::quantity2 get_pm_az_cosalt() const\n    {\n        return this->motion.get_dlon_coslat();\n    }\n\n    //!returns radial_velocity\n    typename Differential::quantity3 get_radial_velocity() const\n    {\n        return this->motion.get_ddist();\n    }\n\n    //!returns the proper motion in tuple form\n    std::tuple\n    <\n        typename Differential::quantity1,\n        typename Differential::quantity2,\n        typename Differential::quantity3\n    > get_pm_alt_az_radial() const\n    {\n        return this->motion.get_dlat_dlon_coslat_ddist();\n    }\n\n    //!sets value of altitude component of the coordinate\n    void set_alt(typename Representation::quantity1 const& alt)\n    {\n        this->data.set_lat(alt);\n    }\n\n    //!sets value of azimuth component of the coordinate\n    void set_az(typename Representation::quantity3 const& az)\n    {\n        this->data.set_lon(az);\n    }\n\n    //!sets value of distance component of the coordinate\n    void set_distance(typename Representation::quantity3 const& distance)\n    {\n        this->data.set_dist(distance);\n    }\n\n    //!sets value of all component of the coordinate including cos(alt)\n    void set_alt_az_dist\n    (\n        typename Representation::quantity1 const& alt,\n        typename Representation::quantity2 const& az,\n        typename Representation::quantity3 const& dist)\n    {\n        this->data.set_lat_lon_dist(alt, az, dist);\n    }\n\n    //!sets the proper motion in altitude\n    void set_pm_alt(typename Differential::quantity1 const& pm_alt)\n    {\n        this->motion.set_dlat(pm_alt);\n    }\n\n    //!sets the proper motion in azimuth including cos(alt)\n    void set_pm_az_cosalt(typename Differential::quantity2 const& pm_az_cosalt)\n    {\n        this->motion.set_dlon_coslat(pm_az_cosalt);\n    }\n\n    //!sets the radial_velocity\n    void set_radial_velocity(typename Differential::quantity3 const& radial_velocity)\n    {\n        this->motion.set_ddist(radial_velocity);\n    }\n\n    //!set value of motion\n    void set_pm_alt_az_radial\n    (\n        typename Differential::quantity1 const& pm_alt,\n        typename Differential::quantity2 const& pm_az_cosalt,\n        typename Differential::quantity3 const& radial_velocity\n    )\n    {\n        this->motion.set_dlat_dlon_coslat_ddist(pm_alt, pm_az_cosalt, radial_velocity);\n    }\n\n    //!set all the perameters of current frame object\n    void set_frame_parameters\n    (\n        spherical_equatorial_representation\n        <\n            double,\n            bu::quantity<bu::degree::plane_angle>,\n            bu::quantity<bu::degree::plane_angle>\n        > const& location,\n        bu::quantity<bu::si::pressure> const& pressure,\n        bu::quantity<bu::celsius::temperature> const& temperature,\n        boost::posix_time::ptime const& obs_time,\n        bu::quantity<bu::si::dimensionless> const& relative_humidity\n    )\n    {\n        this->earth_location = location;\n        this->pressure = pressure;\n        this->temperature = temperature;\n        this->obs_time = obs_time;\n        this->relative_humidity = relative_humidity;\n    }\n\n    //!get all the perameters of current frame object\n    std::tuple<\n        spherical_equatorial_representation\n        <\n            double,\n            bu::quantity<bu::degree::plane_angle>,\n            bu::quantity<bu::degree::plane_angle>\n        >,\n        bu::quantity<bu::si::pressure>,\n        bu::quantity<bu::celsius::temperature>,\n        boost::posix_time::ptime,\n        bu::quantity<bu::si::dimensionless>\n    > get_frame_parameters() const\n    {\n        return std::make_tuple\n        (\n            this->earth_location,\n            this->pressure,\n            this->temperature,\n            this->obs_time,\n            this->relative_humidity\n        );\n    }\n\n    //!get earth location of the current object\n    spherical_equatorial_representation\n    <\n        double,\n        bu::quantity<bu::degree::plane_angle>,\n        bu::quantity<bu::degree::plane_angle>\n    > get_location() const\n    {\n        return this->earth_location;\n    }\n\n    //!set earth location of the current object\n    void set_location\n    (\n        spherical_equatorial_representation\n        <\n            double,\n            bu::quantity<bu::degree::plane_angle>,\n            bu::quantity<bu::degree::plane_angle>\n        > const& location\n    )\n    {\n        this->earth_location = location;\n    }\n\n    //!get atmospheric pressure\n    bu::quantity<bu::si::pressure> get_pressure() const\n    {\n        return this->pressure;\n    }\n\n    //!set atmospheric pressure\n    void set_pressure(bu::quantity<bu::si::pressure> const& pressure)\n    {\n        this->pressure = pressure;\n    }\n\n    //!get temperature of the location\n    bu::quantity<bu::celsius::temperature> get_temprature() const\n    {\n        return this->temperature;\n    }\n\n    //!set temperature of the location\n    void set_temprature(bu::quantity<bu::celsius::temperature> const& temperature)\n    {\n        this->temperature = temperature;\n    }\n\n    //!get observation time\n    boost::posix_time::ptime get_obs_time() const\n    {\n        return this->obs_time;\n    }\n\n    //!set observation time\n    void set_obs_time(boost::posix_time::ptime const& time)\n    {\n        this->obs_time = time;\n    }\n\n    //!get relative humidity\n    bu::quantity<bu::si::dimensionless> get_relative_humidity() const\n    {\n        return this->relative_humidity;\n    }\n\n    //!set relative humidity\n    void set_relative_humidity(bu::quantity<bu::si::dimensionless> const& humidity)\n    {\n        this->relative_humidity = humidity;\n    }\n};\n}}} //namespace boost::astronomy::cordinate\n#endif // !BOOST_ASTRONOMY_COORDINATE_ALT_AZ_HPP\n\n", "meta": {"hexsha": "02d1150584329236701afcaf6747ed57a9acaa21", "size": 13164, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/coord_sys/alt_az.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/alt_az.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/coordinate/coord_sys/alt_az.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": 32.5841584158, "max_line_length": 90, "alphanum_fraction": 0.6599817685, "num_tokens": 2829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.18090453788727195}}
{"text": "/* decision_tree_xor_test.cc\n   Jeremy Barnes, 25 February 2008\n   Copyright (c) 2008 Jeremy Barnes.  All rights reserved.\n\n   Test of the decision tree class.\n*/\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include <boost/thread.hpp>\n#include <boost/thread/barrier.hpp>\n#include <boost/bind.hpp>\n#include <vector>\n#include <stdint.h>\n#include <iostream>\n\n#include \"jml/boosting/decision_tree_generator.h\"\n#include \"jml/boosting/training_data.h\"\n#include \"jml/boosting/dense_features.h\"\n#include \"jml/boosting/feature_info.h\"\n#include \"jml/utils/smart_ptr_utils.h\"\n#include \"jml/utils/vector_utils.h\"\n\nusing namespace ML;\nusing namespace std;\n\nusing boost::unit_test::test_suite;\n\nstatic const char * config_options = \"\\\ntrace=0\\n\\\n\";\n\nBOOST_AUTO_TEST_CASE( test_decision_tree_multithreaded_binary )\n{\n    /* Create the dataset */\n\n    Dense_Feature_Space fs;\n    fs.add_feature(\"LABEL\", Feature_Info(BOOLEAN, false, true));\n    fs.add_feature(\"feature1\", REAL);\n    fs.add_feature(\"feature2\", REAL);\n    fs.add_feature(\"feature3\", REAL);\n\n    std::shared_ptr<Dense_Feature_Space> fsp(make_unowned_sp(fs));\n\n    Training_Data data(fsp);\n    \n    int nfv = 10000;\n\n    for (unsigned i = 0;  i < nfv;  ++i) {\n        distribution<float> features;\n        features.push_back(i % 2);\n        features.push_back(i);\n        features.push_back(i);\n        features.push_back(i);\n\n        //features.push_back(random());\n        //features.push_back(random());\n        //features.push_back(random());\n\n        std::shared_ptr<Feature_Set> fset\n            = fs.encode(features);\n\n        data.add_example(fset);\n    }\n\n    /* Create the decision tree generator */\n    Configuration config;\n    config.parse_string(config_options, \"inbuilt config file\");\n\n    Decision_Tree_Generator generator;\n    generator.configure(config);\n    generator.init(fsp, fs.features()[0]);\n\n    distribution<float> training_weights(nfv, 1);\n\n    vector<Feature> features = fs.features();\n    features.erase(features.begin(), features.begin() + 1);\n\n    Thread_Context context;\n\n    generator.generate(context, data, training_weights, features);\n}\n\nBOOST_AUTO_TEST_CASE( test_decision_tree_multithreaded_regression )\n{\n    /* Create the dataset */\n\n    Dense_Feature_Space fs;\n    fs.add_feature(\"LABEL\", Feature_Info(REAL, false, true));\n    fs.add_feature(\"feature1\", REAL);\n    fs.add_feature(\"feature2\", REAL);\n    fs.add_feature(\"feature3\", REAL);\n\n    std::shared_ptr<Dense_Feature_Space> fsp(make_unowned_sp(fs));\n\n    Training_Data data(fsp);\n    \n    int nfv = 10000;\n\n    for (unsigned i = 0;  i < nfv;  ++i) {\n        distribution<float> features;\n        features.push_back(i % 2);\n        features.push_back(i);\n        features.push_back(i);\n        features.push_back(i);\n\n        //features.push_back(random());\n        //features.push_back(random());\n        //features.push_back(random());\n\n        std::shared_ptr<Feature_Set> fset\n            = fs.encode(features);\n\n        data.add_example(fset);\n    }\n\n    /* Create the decision tree generator */\n    Configuration config;\n    config.parse_string(config_options, \"inbuilt config file\");\n\n    Decision_Tree_Generator generator;\n    generator.configure(config);\n    generator.init(fsp, fs.features()[0]);\n\n    distribution<float> training_weights(nfv, 1);\n\n    vector<Feature> features = fs.features();\n    features.erase(features.begin(), features.begin() + 1);\n\n    Thread_Context context;\n\n    generator.generate(context, data, training_weights, features);\n}\n", "meta": {"hexsha": "7414448f29844a53d737f3e25cf0a319a2e4ac64", "size": 3552, "ext": "cc", "lang": "C++", "max_stars_repo_path": "jml/boosting/testing/decision_tree_unlimited_depth_test.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/boosting/testing/decision_tree_unlimited_depth_test.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/boosting/testing/decision_tree_unlimited_depth_test.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": 26.1176470588, "max_line_length": 67, "alphanum_fraction": 0.6810247748, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.18090453431859735}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n/// RGBD_RTK\n#include <config_loader.h>\n#include <marker_finder.h>\n#include <reconstruction_visualizer.h>\n/// ROS\n#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include <actionlib/client/simple_action_client.h>\n#include <cv_bridge/cv_bridge.h>\n#include <image_transport/image_transport.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <message_filters/time_synchronizer.h>\n#include <move_base_msgs/MoveBaseAction.h>\n#include <ros/ros.h>\n#include <sensor_msgs/Image.h>\n#include <tf/transform_broadcaster.h>\n/// Opencv\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <opencv2/highgui/highgui.hpp>\n// Aruco\n#include <aruco/aruco.h>\n#include <aruco/cvdrawingutils.h>\n// Autonomous Robot\n#include <goal.h>\n#include <handleFiles.h>\n#include <structures.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace aruco;\n\n// ROS Variables\ntypedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;\ntf::TransformBroadcaster *br;\n\nMarkerDetector marker_detector;\nMarkerFinder marker_finder;\n\nfloat aruco_max_distance, aruco_offset_distance;\nstring aruco_poses_file;\nvector<Pose> all_markers;\ncv::Mat rgb;\n\nGoal goal;\nHandleFiles handleFiles;\n\nvoid imageCallback(const sensor_msgs::ImageConstPtr &msg);\n// void markerGetCloser(int marker_id);\nvoid listenKeyboardGoal(const std_msgs::String::ConstPtr &msg);\nbool moveToGoal(Eigen::Quaternionf orientation, Eigen::Affine3f pose);\nvoid loadMarkers(string aruco_poses_file);\nvoid initRos(int argc, char **argv, string rgb_topic);\nvoid loadParams();\nvoid publishArucoTF();\n\nint main(int argc, char **argv) {\n    string camera_calibration_file, aruco_dic, rgb_topic;\n    float aruco_marker_size;\n\n    // Loading config variables\n    ConfigLoader param_loader(\"../../../src/ros_autonomous_robot/config_files/ConfigFile.yaml\");\n    param_loader.checkAndGetString(\"camera_calibration_file\", camera_calibration_file);\n    param_loader.checkAndGetString(\"aruco_dic\", aruco_dic);\n    param_loader.checkAndGetString(\"rgb_topic\", rgb_topic);\n    param_loader.checkAndGetString(\"aruco_poses_file\", aruco_poses_file);\n    param_loader.checkAndGetFloat(\"aruco_offset_distance\", aruco_offset_distance);\n    param_loader.checkAndGetFloat(\"aruco_marker_size\", aruco_marker_size);\n    param_loader.checkAndGetFloat(\"aruco_max_distance\", aruco_max_distance);\n\n    marker_finder.markerParam(camera_calibration_file, aruco_marker_size, aruco_dic);\n\n    initRos(argc, argv, rgb_topic);\n\n    return 0;\n}\n/**\n * Ros Listener to rgb topic\n * @params reads a rgb message type ImageConstPtr\n */\nvoid imageCallback(const sensor_msgs::ImageConstPtr &msgRGB) {\n\n    cv_bridge::CvImageConstPtr cv_ptrRGB;\n    try {\n        cv_ptrRGB = cv_bridge::toCvShare(msgRGB);\n    } catch (cv_bridge::Exception &e) {\n        ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n        return;\n    }\n    rgb = cv_ptrRGB->image;\n    publishArucoTF();\n\n    // Detect and get pose of all aruco markers\n    marker_finder.detectMarkersPoses(rgb, Eigen::Affine3f::Identity(), aruco_max_distance);\n\n    cv::imshow(\"OPENCV_WINDOW\", rgb); // showing rgb image\n    cv::waitKey(1);\n}\n\n/**\n * Listen to a marker number and send a goal to the robot goes to marker position\n * @Params Keeps listen to any string message sent in ROS\n */\nvoid sendGoal(const std_msgs::String::ConstPtr &msg) {\n    string listen_id;\n    int marker_id_asked;\n\n    handleFiles.loadPoses(aruco_poses_file, aruco_offset_distance); // loading markers\n    listen_id = msg->data.c_str();\n    string::size_type sz;\n\n    try {\n        marker_id_asked = stoi(listen_id, &sz); // converting string to int\n    } catch (std::invalid_argument &e) {\n        cout << listen_id << \" is not a number\\n\" << endl;\n    }\n    for (auto pose : all_markers) {\n        // validing a marker(a marker is valid if it was detected in any frame)\n        if (pose.id == marker_id_asked) {\n            ROS_INFO(\"[%s] is a valid marker\", msg->data.c_str());\n            goal.send2dGoal(pose.x, pose.y, Eigen::Quaterniond(1, 0, 0, 0));\n\n        } else\n            ROS_INFO(\"[%s] is not a valid marker\", msg->data.c_str());\n    }\n}\n\n/**\n * This function publishes the aruco markers tf related to 0,0\n */\nvoid publishArucoTF() {\n    br = new tf::TransformBroadcaster();\n    tf::Transform transform;\n    for (auto pose : all_markers) {\n        // set the xyz and rotation pose\n        transform.setOrigin(tf::Vector3(pose.x, pose.y, pose.z));\n        transform.setRotation(\n            tf::Quaternion(pose.w_rotation, pose.x_rotation, pose.y_rotation, pose.z_rotation));\n        string aruco_tf = \"aruco\" + to_string(pose.id); // set aruco name\n        // broadcasting to tf related to odom\n        br->sendTransform(tf::StampedTransform(transform, ros::Time::now(), \"odom\", aruco_tf));\n    }\n}\n\n/**\n * Initialize ROS\n */\nvoid initRos(int argc, char **argv, string rgb_topic) {\n    ros::init(argc, argv, \"autonomous_robot\");\n    ros::start();\n\n    ros::NodeHandle n;\n    ros::Subscriber sub = n.subscribe(\"marker_goal\", 1000, sendGoal);\n\n    ros::NodeHandle nh;\n    image_transport::ImageTransport it(nh);\n    image_transport::Subscriber rgb_sub = it.subscribe(rgb_topic, 1, imageCallback);\n\n    ros::spin(); //\"while true\"\n}\n", "meta": {"hexsha": "899f08769c71b4a02737145ee2fc839406dbab10", "size": 5305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/autonomous_robot.cpp", "max_stars_repo_name": "RodrigoSarmento/ros_guide_robot", "max_stars_repo_head_hexsha": "48fc6a1389cb10b449c2b946254fc468332d0362", "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/autonomous_robot.cpp", "max_issues_repo_name": "RodrigoSarmento/ros_guide_robot", "max_issues_repo_head_hexsha": "48fc6a1389cb10b449c2b946254fc468332d0362", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-12-18T17:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T00:12:56.000Z", "max_forks_repo_path": "src/autonomous_robot.cpp", "max_forks_repo_name": "RodrigoSarmento/ros_guide_robot", "max_forks_repo_head_hexsha": "48fc6a1389cb10b449c2b946254fc468332d0362", "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.1515151515, "max_line_length": 96, "alphanum_fraction": 0.7185673893, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18088620275326966}}
{"text": "#ifndef PROFILE_PROPERTIES_HPP\n#define PROFILE_PROPERTIES_HPP\n\n#include <boost/numeric/conversion/cast.hpp>\n\nnamespace osrm\n{\nnamespace extractor\n{\n\nconst constexpr auto DEFAULT_MAX_SPEED = 180 / 3.6; // 180kmph -> m/s\n\nstruct ProfileProperties\n{\n    ProfileProperties()\n        : traffic_signal_penalty(0), u_turn_penalty(0),\n          max_speed_for_map_matching(DEFAULT_MAX_SPEED), continue_straight_at_waypoint(true),\n          use_turn_restrictions(false), left_hand_driving(false)\n    {\n    }\n\n    double GetUturnPenalty() const { return u_turn_penalty / 10.; }\n\n    void SetUturnPenalty(const double u_turn_penalty_)\n    {\n        u_turn_penalty = boost::numeric_cast<int>(u_turn_penalty_ * 10.);\n    }\n\n    double GetTrafficSignalPenalty() const { return traffic_signal_penalty / 10.; }\n\n    void SetTrafficSignalPenalty(const double traffic_signal_penalty_)\n    {\n        traffic_signal_penalty = boost::numeric_cast<int>(traffic_signal_penalty_ * 10.);\n    }\n\n    double GetMaxSpeedForMapMatching() const { return max_speed_for_map_matching; }\n\n    void SetMaxSpeedForMapMatching(const double max_speed_for_map_matching_)\n    {\n        max_speed_for_map_matching = max_speed_for_map_matching_;\n    }\n\n    //! penalty to cross a traffic light in deci-seconds\n    int traffic_signal_penalty;\n    //! penalty to do a uturn in deci-seconds\n    int u_turn_penalty;\n    double max_speed_for_map_matching;\n    bool continue_straight_at_waypoint;\n    bool use_turn_restrictions;\n    bool left_hand_driving;\n};\n}\n}\n\n#endif\n", "meta": {"hexsha": "d53bb04f336660166d69ae411795951ae44adafd", "size": 1523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/extractor/profile_properties.hpp", "max_stars_repo_name": "jhermsmeier/osrm-backend", "max_stars_repo_head_hexsha": "7b11cd3a11c939c957eeff71af7feddaa86e7f82", "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/extractor/profile_properties.hpp", "max_issues_repo_name": "jhermsmeier/osrm-backend", "max_issues_repo_head_hexsha": "7b11cd3a11c939c957eeff71af7feddaa86e7f82", "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/extractor/profile_properties.hpp", "max_forks_repo_name": "jhermsmeier/osrm-backend", "max_forks_repo_head_hexsha": "7b11cd3a11c939c957eeff71af7feddaa86e7f82", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-19T08:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T08:51:11.000Z", "avg_line_length": 27.1964285714, "max_line_length": 93, "alphanum_fraction": 0.7393302692, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.18088619539399342}}
{"text": "// Copyright (c) 2015-2018 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 \"downsampler.hpp\"\n\n#include <vector>\n#include <deque>\n#include <functional>\n#include <iterator>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cassert>\n\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\n#include \"basics/mappable_reference_wrapper.hpp\"\n#include \"concepts/mappable_range.hpp\"\n#include \"utils/mappable_algorithms.hpp\"\n#include \"utils/read_algorithms.hpp\"\n#include \"utils/append.hpp\"\n\n// Use boost distributions as std distributions not guaranteed to be deterministic across compilers.\n// Generators are however.\n// https://stackoverflow.com/questions/48730363/if-we-seed-c11-mt19937-as-the-same-on-different-machines-will-we-get-the-same.\n\nnamespace octopus { namespace readpipe {\n\nDownsampler::Report::DownsampleRegion::DownsampleRegion(GenomicRegion region, std::size_t num_reads)\n: region_ {std::move(region)}\n, num_reads_ {num_reads}\n{}\n\nnamespace {\n\nusing ReadWrapper = MappableReferenceWrapper<const AlignedRead>;\n\nusing PositionCoverages = std::vector<unsigned>;\n\nbool has_minimum_coverage(const PositionCoverages& required_coverage)\n{\n    return std::all_of(std::cbegin(required_coverage), std::cend(required_coverage),\n                       [] (const auto coverage) noexcept { return coverage == 0; });\n}\n\ntemplate <typename ForwardIt>\nauto calculate_minimum_coverages(const ForwardIt first, const ForwardIt last,\n                                 const GenomicRegion& region, const unsigned min_coverage)\n{\n    auto result = calculate_positional_coverage(first, last, region);\n    std::transform(std::cbegin(result), std::cend(result), std::begin(result),\n                   [min_coverage] (const auto coverage) noexcept {\n                       return std::min(coverage, min_coverage);\n                   });\n    return result;\n}\n\nauto sample(const PositionCoverages& required_coverage)\n{\n    static std::mt19937 generator {42};\n    // TODO: Do we really need to keep regenerating this distribution?\n    boost::random::discrete_distribution<std::size_t> dist {std::cbegin(required_coverage), std::cend(required_coverage)};\n    return dist(generator);\n}\n\ntemplate <typename BidirIt>\nBidirIt random_sample(const BidirIt first, const BidirIt last)\n{\n    static std::mt19937 generator {42};\n    boost::random::uniform_int_distribution<std::size_t> dist(0, std::distance(first, last) - 1);\n    return std::next(first, dist(generator));\n}\n\ntemplate <typename T>\nauto random_sample(const OverlapRange<T>& range)\n{\n    return random_sample(std::begin(range), std::end(range)).base();\n}\n\ntemplate <typename BidirIt>\nauto pick_sample(BidirIt first_unsampled, BidirIt last_unsampled,\n                 const std::vector<GenomicRegion>& positions,\n                 const PositionCoverages& required_coverage,\n                 const AlignedRead::MappingDomain::Size max_read_size)\n{\n    assert(first_unsampled < last_unsampled);\n    const auto candidates = overlap_range(first_unsampled, last_unsampled,\n                                          positions[sample(required_coverage)],\n                                          max_read_size);\n    assert(!candidates.empty());\n    return random_sample(candidates);\n}\n\nvoid reduce(PositionCoverages& coverages, const ReadWrapper& read, const GenomicRegion& region)\n{\n    assert(!begins_before(read, region));\n    const auto read_offset = begin_distance(region, read);\n    const auto first = std::next(std::begin(coverages), read_offset);\n    auto last = std::next(first, region_size(read));\n    if (last > std::end(coverages)) last = std::end(coverages);\n    std::transform(first, last, first, [] (const auto x) noexcept { return (x > 0) ? x - 1 : 0; });\n}\n\ntemplate <typename ForwardIt>\nForwardIt shift_left(ForwardIt first, ForwardIt last)\n{\n    return std::rotate(first, std::next(first), last);\n}\n\ntemplate <typename BidirIt>\nBidirIt shift_right(BidirIt first, BidirIt last)\n{\n    const auto rfirst = std::make_reverse_iterator(last);\n    const auto rlast  = std::make_reverse_iterator(first);\n    return std::rotate(rfirst, std::next(rfirst), rlast).base();\n}\n\ntemplate <typename BidirIt>\nvoid remove_sample(BidirIt& first, BidirIt sample, BidirIt& last)\n{\n    assert(first <= sample && sample < last);\n    // rotating is linear time so it's cheaper to shift the sample into the closer of the\n    // two sampled groups.\n    if (std::distance(first, sample) < std::distance(sample, last)) {\n        if (sample != first) {\n            shift_right(first, std::next(sample));\n        }\n        ++first;\n    } else {\n        if (sample != std::prev(last)) {\n            shift_left(sample, last);\n        }\n        --last;\n    }\n}\n\nauto extract_sampled(std::vector<ReadWrapper>& reads,\n                     std::vector<ReadWrapper>::iterator first_unsampled,\n                     std::vector<ReadWrapper>::iterator last_unsampled)\n{\n    reads.erase(first_unsampled, last_unsampled);\n    std::sort(std::begin(reads), std::end(reads));\n    std::vector<AlignedRead> result {};\n    result.reserve(reads.size());\n    std::transform(std::begin(reads), std::end(reads), std::back_inserter(result),\n                   [] (const auto& wrapper) -> AlignedRead { return wrapper.get(); });\n    return result;\n}\n\n} // namespace\n\ntemplate <typename InputIt>\nauto sample(const InputIt first_read, const InputIt last_read, const GenomicRegion& region,\n            const unsigned target_coverage)\n{\n    if (first_read == last_read) return std::vector<AlignedRead> {};\n    const auto positions = decompose(region);\n    auto required_coverage = calculate_minimum_coverages(first_read, last_read, region, target_coverage);\n    assert(positions.size() == required_coverage.size());\n    std::vector<ReadWrapper> reads {first_read, last_read};\n    const auto max_read_size = size(largest_region(reads)); // for efficient overlap detection\n    // The reads are partitioned into three groups: sampled | unsampled | sampled\n    // which allows a sampled read to be optimally moved out of the unsampled partition\n    auto first_unsampled_itr = std::begin(reads);\n    auto last_unsampled_itr  = std::end(reads);\n    while (!has_minimum_coverage(required_coverage)) {\n        const auto sampled_itr = pick_sample(first_unsampled_itr, last_unsampled_itr,\n                                             positions, required_coverage, max_read_size);\n        reduce(required_coverage, *sampled_itr, region);\n        remove_sample(first_unsampled_itr, sampled_itr, last_unsampled_itr);\n    }\n    return extract_sampled(reads, first_unsampled_itr, last_unsampled_itr);\n}\n\nnamespace {\n\n// Look for regions with coverage above max_coverage interconnected by positions\n// with coverage abouve min_coverage. The idea being samples are better taken from the\n// larger joined regions.\nauto find_target_regions(const ReadContainer& reads, const unsigned max_coverage, const unsigned min_coverage)\n{\n    const auto above_max_coverage_regions = find_high_coverage_regions(reads, max_coverage);\n    std::vector<GenomicRegion> result {};\n    if (above_max_coverage_regions.empty()) return result;\n    result.reserve(above_max_coverage_regions.size());\n    auto above_min_coverage_regions = find_high_coverage_regions(reads, min_coverage);\n    std::copy_if(std::make_move_iterator(std::begin(above_min_coverage_regions)),\n                 std::make_move_iterator(std::end(above_min_coverage_regions)),\n                 std::back_inserter(result),\n                 [&above_max_coverage_regions] (const auto& region) {\n                     return has_contained(std::cbegin(above_max_coverage_regions), std::cend(above_max_coverage_regions), region);\n                 });\n    return result;\n}\n\n} // namespace\n\nDownsampler::Report sample(ReadContainer& reads, const unsigned trigger_coverage, const unsigned target_coverage)\n{\n    using std::begin; using std::end; using std::make_move_iterator;\n    \n    Downsampler::Report result {};\n    \n    if (reads.empty()) return result;\n    const auto targets = find_target_regions(reads, trigger_coverage, target_coverage);\n    if (targets.empty()) return result;\n    \n    // We avoid using ReadContainers member methods for inserting sampled reads as they are order\n    //  N log(size() + N) + N * size(). This is because they assume the input range is unsorted,\n    // and must therefore to a binary search for every read inserted. We can avoid this as\n    // we know the reads are originally sorted, and we sample reads in non-overlapping blocks.\n    // The blocks are themselves sorted, so no comparisons are required.\n    std::vector<std::deque<AlignedRead>> sampled_read_blocks {};\n    sampled_read_blocks.reserve(targets.size());\n    std::vector<std::vector<AlignedRead>> unsampled_read_blocks {};\n    unsampled_read_blocks.reserve(targets.size());\n    std::size_t num_reads {0};\n    \n    // Downsample in reverse order because erasing near back of MappableFlatMultiSet is much\n    // cheaper than erasing near front.\n    std::for_each(std::crbegin(targets), std::crend(targets), [&] (const auto& region) {\n        const auto contained = bases(contained_range(begin(reads), end(reads), region));\n        num_reads += std::distance(end(contained), end(reads));\n        unsampled_read_blocks.emplace_back(make_move_iterator(end(contained)), make_move_iterator(end(reads)));\n        auto sampled_reads = sample(begin(contained), end(contained), region, target_coverage);\n        num_reads += sampled_reads.size();\n        const auto num_reads_in_target = size(contained);\n        assert(num_reads_in_target >= sampled_reads.size());\n        const auto num_reads_removed = num_reads_in_target - sampled_reads.size();\n        result.downsampled_regions.emplace(region, num_reads_removed);\n        sampled_read_blocks.emplace_back(make_move_iterator(begin(sampled_reads)), make_move_iterator(end(sampled_reads)));\n        reads.erase(begin(contained), end(reads));\n        reads.shrink_to_fit();\n    });\n    \n    num_reads += reads.size();\n    std::vector<AlignedRead> buffer {};\n    buffer.reserve(num_reads);\n    buffer.assign(make_move_iterator(begin(reads)), make_move_iterator(end(reads)));\n    reads.clear();\n    reads.shrink_to_fit();\n    for (auto i = static_cast<int>(targets.size()) - 1; i >= 0; --i) {\n        utils::append(std::move(sampled_read_blocks[i]), buffer);\n        utils::append(std::move(unsampled_read_blocks[i]), buffer);\n    }\n    reads = ReadContainer {make_move_iterator(begin(buffer)), make_move_iterator(end(buffer))};\n    return result;\n}\n\n// Downsampler\n\nDownsampler::Downsampler(const unsigned trigger_coverage, const unsigned target_coverage)\n: trigger_coverage_ {trigger_coverage}\n, target_coverage_ {target_coverage}\n{\n    if (target_coverage > trigger_coverage) {\n        target_coverage_ = trigger_coverage;\n    }\n}\n\nDownsampler::Report Downsampler::downsample(ReadContainer& reads) const\n{\n    return sample(reads, trigger_coverage_, target_coverage_);\n}\n\nstd::size_t count_downsampled_reads(const DownsamplerReportMap& reports)\n{\n    return std::accumulate(std::cbegin(reports), std::cend(reports), std::size_t {0},\n                           [] (auto curr, const auto& p) {\n                               return curr + std::accumulate(std::cbegin(p.second.downsampled_regions),\n                                                             std::cend(p.second.downsampled_regions), std::size_t {0},\n                                                             [] (auto curr, const auto& target) {\n                                   return curr + target.num_reads(); });\n                           });\n}\n\nstd::size_t count_downsampled_reads(const DownsamplerReportMap& reports, const GenomicRegion& region)\n{\n    return std::accumulate(std::cbegin(reports), std::cend(reports), std::size_t {0},\n                           [&region] (auto curr, const auto& p) {\n                               const auto overlapped = overlap_range(p.second.downsampled_regions, region);\n                               return curr + std::accumulate(std::cbegin(overlapped), std::cend(overlapped), std::size_t {0},\n                                                             [] (auto curr, const auto& target) {\n                                                                 return curr + target.num_reads(); });\n                           });\n}\n\n} // namespace readpipe\n} // namespace octopus\n", "meta": {"hexsha": "9d07a4b35db589b462f63ad4a43ab2a6c5d1076c", "size": 12485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/readpipe/downsampling/downsampler.cpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "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/readpipe/downsampling/downsampler.cpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/readpipe/downsampling/downsampler.cpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.9037800687, "max_line_length": 130, "alphanum_fraction": 0.6800961153, "num_tokens": 2713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.18088619539399337}}
{"text": "#include \"poseg2.h\"\n#include \"features.h\"\n#include \"math_modules.h\"\n#include \"utilities.h\"\n#include <Eigen/src/Core/Matrix.h>\n#include <Open3D/Geometry/PointCloud.h>\n#include <Open3D/Visualization/Utility/DrawGeometry.h>\n#include <boost/core/use_default.hpp>\n#include <cstdint>\n#include <functional>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/core/types.hpp>\n#include <stdexcept>\n#include <string>\n#include <sys/types.h>\n#include <utility>\n#include <vector>\n\n/**\n *  TODO:\n *      - cache landmark descriptors, update only when added to landmark\n *      - compute pointcloud scale as soon as possible\n *          --> can use metric units\n */\n\nnamespace stitcher3d\n{\n    PoseGraph::PoseGraph() :\n        cameras(std::vector<Camera*>()),\n        // f_matcher(std::make_unique<cv::BFMatcher>(cv::BFMatcher(cv::NORM_HAMMING)))\n        // NORM_HAMMING for ORB, AKAZE. NORM_L2 for SIFT\n        f_matcher_crosscheck(std::make_unique<cv::BFMatcher>(*cv::BFMatcher::create(cv::NORM_L2, true))),\n        f_matcher(std::make_unique<cv::BFMatcher>(*cv::BFMatcher::create(cv::NORM_L2, false)))\n    { }\n\n    PoseGraph::~PoseGraph()\n    {\n        for (Camera* cam : cameras)\n            delete cam;\n    }\n\n    Camera* PoseGraph::add_camera(const Eigen::Vector3d& position, const Eigen::Matrix3d& rotation,\n        const std::shared_ptr<o3d::geometry::Image>& rgb, const std::shared_ptr<o3d::geometry::Image>& depth,\n        const o3d::camera::PinholeCameraIntrinsic& intr, const std::vector<double>& distortion_coeffs,\n        const std::string rgb_name, const std::string depth_name, const bool offline)\n    {\n        // const auto [cv_keypoints, descriptor] = features::detect_akaze_features(rgb, &intr, &distortion_coeffs);\n        Camera* tcam;\n\n        auto cv_rgb = nullptr; //std::make_shared<cv::Mat>(rgbd::o3d_image_to_cv_image(rgb));\n        auto cv_depth = nullptr; //std::make_shared<cv::Mat>(rgbd::o3d_image_to_cv_image(depth, true));\n\n        // cv::imshow(\"depth\", *cv_depth);\n        // cv::waitKey(0);\n\n        if (!offline)\n        {\n            tcam = new Camera (\n                position,\n                rotation,\n                UNIT_SCALE,\n                position,\n                rotation,\n                Eigen::Matrix4d::Identity(),\n                intr.intrinsic_matrix_ * Eigen::Matrix<double, 3, 4>::Identity(),\n                distortion_coeffs,\n                nullptr,\n                std::vector<cv::KeyPoint>(),\n                cv::Mat(),\n                rgb,\n                depth,\n                cv_rgb,\n                cv_depth,\n                intr,\n                NOT_SET_CAM_ID,\n                0.0f,\n                rgb_name,\n                depth_name\n            );\n        }\n        else\n        {\n            throw std::runtime_error(\"unsupported feature, aborting\");\n        }\n        \n        // dR.transpose(), -dR.transpose() * dt\n        // set_camera_T_and_P(tcam, Eigen::Matrix3d::Identity().transpose(), -Eigen::Matrix3d::Identity().transpose() * Eigen::Vector3d::Zero());\n\n        cameras.push_back(tcam);\n        cameras.back()->id = cameras.size() - 1;\n        return cameras.back();\n    }\n\n    void PoseGraph::add_camera_offline(const std::shared_ptr<o3d::geometry::Image>& rgb, const std::shared_ptr<o3d::geometry::Image>& depth,\n        const o3d::camera::PinholeCameraIntrinsic& intr, const std::vector<double>& distortion_coeffs,\n        const std::string rgb_name, const std::string depth_name)\n    {\n        Camera* cam = add_camera(Eigen::Vector3d::Zero(), Eigen::Matrix3d::Identity(), \n            rgb, depth, intr, distortion_coeffs, rgb_name, depth_name, true);\n\n        const auto [cv_keypoints, descriptor] = features::detect_features(rgb, reg_params.max_feature_count, &intr, &distortion_coeffs);\n        cam->kp_features = cv_keypoints;\n        cam->feature_descriptors = descriptor;\n    }\n\n    bool PoseGraph::add_camera_and_compute_pose_realtime(const std::shared_ptr<o3d::geometry::Image>& rgb, const std::shared_ptr<o3d::geometry::Image>& depth,\n        const o3d::camera::PinholeCameraIntrinsic& intr, const std::vector<double>& distortion_coeffs,\n        const uint32_t time_id, const std::string rgb_name, const std::string depth_name)\n    {\n        // if (landmarks.size() > 200000)\n        //     visualize_tracks();\n\n        Timer t;\n\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"\\n\";\n        #endif\n\n        Camera* cam = add_camera(Eigen::Vector3d::Zero(), Eigen::Matrix3d::Identity(), rgb, depth, intr, distortion_coeffs, rgb_name, depth_name);\n\n        const auto [cv_keypoints, descriptor] = features::detect_features(rgb, reg_params.max_feature_count, &intr, &distortion_coeffs);\n        cam->kp_features = cv_keypoints;\n        cam->feature_descriptors = descriptor;\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"feature detection\");\n        #endif\n\n        if (cameras.size() == 2)\n        {\n            #ifdef DEBUG_VERBOSE\n        \tstd::cout << \"less than 3 cameras, using essential matrix\\n\";\n            #endif\n\n        \tconst bool status = compute_initial_pose(cam, cameras.at(0));\n\n            #ifdef DEBUG_VERBOSE\n        \tt.stop(\"computing initial pose\");\n            #endif\n\n            if (status)\n                pose_predictor.add_good_pose(time_id, cameras.back()->position, cameras.back()->rotation);\n\n        \treturn status;\n        }\n        else if (cameras.size() == 1)\n        {\n            #ifdef DEBUG_VERBOSE\n            std::cout << \"only one camera, returning\\n\";\n            #endif\n\n            pose_predictor.add_good_pose(time_id, cam->position, cam->rotation);\n            return true;\n        }\n        // visualize_tracks();\n\n        const bool status = compute_pose_realtime(cam, time_id);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"computing the entire pose\");\n        #endif\n\n        if (!status)\n        {\n            #ifdef DEBUG_VERBOSE\n            std::cout << \"adding camera failed, removing\\n\";\n            #endif\n\n            remove_last_camera(cameras.back());\n        }\n\n        return status;\n    }\n\n    void PoseGraph::compute_camera_poses_accurate()\n    {\n        if (cameras.size() < 2)\n            throw std::runtime_error(\"not enough cameras to compute poses, aborting\");\n\n        Timer t;\n\n        // pair-wise match all cameras\n        for (int ii = 0; ii < cameras.size(); ii++)\n        {\n            OfflineCamera* refcam = dynamic_cast<OfflineCamera*>(cameras.at(ii));\n\n            for (int jj = ii + 1; jj < cameras.size(); jj++)\n            {\n                OfflineCamera* cam = dynamic_cast<OfflineCamera*>(cameras.at(jj));\n\n                const std::vector<std::pair<uint32_t, uint32_t>> rc_corr = \n                    match_features_hgraphy(refcam->feature_descriptors, cam->feature_descriptors, refcam, cam);\n\n                    // DEBUG_visualize_matches(refcam, cam, rc_corr);\n\n                // loop through matches and add to Camera match-map for each feature index (fi)\n                for (int fi = 0; fi < rc_corr.size(); fi++)\n                {\n                    // add feature chains\n                    refcam->kp_match_index_map[rc_corr[fi].first][jj] = rc_corr[fi].second;\n                    cam->kp_match_index_map[rc_corr[fi].second][ii] = rc_corr[fi].first;\n                }\n            }\n        }\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"pair-wise correspondences and feature matches\");\n        #endif\n\n        /**\n         *  TODO:\n         *      - find corresponding candidates in each image, pair-wise -> map\n         *      - loop through all cameras, for each: loop through all matched frames\n         *      - after local pose recovery, triangulate points\n         *      - scale points \n         *      - global pose recovery\n         *      - triangulate good points\n         *      - average landmarks\n         *          - fix camera poses with PnP?\n         * \n         *  ALGORITHM:\n         *      - pairwise match features and add to corresponding frame lookups\n         *      - fix 0th camera as origin\n         *      - iterate cameras:\n         *          - recover pose\n         *          - when featurecount < threshold (0.5?), stop and set as unit transformation\n         *          - this is makes a fragment, a camera sequence\n         *      - refcam +1 and repeat\n         *      - match fragments\n         *          - 2nd of first, 1st of second are the same frame\n         *          - set 1st of 2nd transformation\n         *          - propagate transformations (relative to 1st of 2nd)\n         */\n\n        std::vector<FrameFragment> frame_fragments;\n\n\n        cv::Mat intr_cv;\n        cv::eigen2cv(cameras.at(0)->intr.intrinsic_matrix_, intr_cv);\n\n        /**\n         *  ii is the fragment's 1st camera\n         *  jj is the fragment's last camera\n         */\n        for (int ii = 0; ii < cameras.size() - 1; ii++)\n        {\n            OfflineCamera* refcam = dynamic_cast<OfflineCamera*>(cameras.at(ii));\n\n            // set the refcam to be at origin, dealing with relative fragments\n            set_camera_T_and_P(refcam, Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero());\n\n            const uint32_t next_cam_id = refcam->id + 1;\n            \n            // <feature index, indexes in consequent frames>\n            // feature must be present in all of them, otherwise delete\n            std::map<uint32_t, std::vector<uint32_t>> feature_tracks;\n\n            // for (int i = 0; i < refcam->kp_match_index_map.size(); i++)\n\n            // construct feature trails\n\n            // populate reference feature id lookup\n            for (auto a : refcam->kp_match_index_map)\n            {\n                if (a.second.count(next_cam_id) != 0)\n                {\n                    feature_tracks[a.first] = { a.second.at(next_cam_id) };\n                }\n            }\n\n            uint32_t next_cam_loop_id = next_cam_id;\n            std::map<uint32_t, std::map<uint32_t, uint32_t>>& frame_kp_matches = dynamic_cast<OfflineCamera*>(cameras.at(next_cam_loop_id))->kp_match_index_map;\n            uint32_t current_match_count = feature_tracks.size();\n            const uint32_t initial_match_count = feature_tracks.size();\n\n            while ((float)current_match_count > (float)initial_match_count * MATCH_RATIO_TRAIL_THRESHOLD )\n                // || current_match_count > MATCH_COUNT_TRAIL_THRESHOLD)\n            {\n                std::vector<uint32_t> to_remove_tracks;\n\n                for (auto& track : feature_tracks)\n                {\n                    const uint32_t ref_f_id = track.first;\n                    const uint32_t fid = track.second.back();\n\n                    // check if feature f is found also in the next_cam's matches\n                    if (frame_kp_matches.at(fid).count(next_cam_loop_id + 1) != 0)\n                    {\n                        track.second.push_back(frame_kp_matches[fid][next_cam_loop_id + 1]);\n                    }\n                    // feature doesn't exist in next, mark for delete\n                    else\n                        to_remove_tracks.push_back(ref_f_id);\n                }\n\n                // remove tracks which weren't long enough \n                for (uint32_t to_remove_id : to_remove_tracks)\n                    feature_tracks.erase(to_remove_id);\n\n                current_match_count = feature_tracks.size();\n\n                // NOTE: throw away the last frame, should be fixed at some point\n                // if (next_cam_loop_id >= cameras.size() - 1)\n                //     break;\n\n                next_cam_loop_id++;\n                frame_kp_matches = dynamic_cast<OfflineCamera*>(cameras.at(next_cam_loop_id))->kp_match_index_map;\n\n                // std::cout << \"next camera: \" << next_cam_loop_id << \", track size: \" \n                //     << current_match_count << \", out of \" << initial_match_count << \"\\n\";\n            }\n\n            std::cout << \"feature trail feature count: \" << feature_tracks.size() << \n                \" and length: \" << (feature_tracks.size() > 0 ? feature_tracks.begin()->second.size() : 0) << \"\\n\";\n\n            // for (auto a : feature_tracks)\n            // {\n            //     for (auto b : a.second)\n            //         std::cout << b << \" \";\n            //     std::cout << \"\\n\";\n            // }\n\n            // recover relative poses between frames\n            // for (int jj = ii + 1; jj < cameras.size(); jj++)\n\n            OfflineCamera* cam = dynamic_cast<OfflineCamera*>(cameras.at(ii + feature_tracks.begin()->second.size()));\n\n            const std::vector<uint32_t> refcam_track_features = utilities::get_keys_as_vec(feature_tracks);\n            const std::vector<uint32_t> cam_track_features = utilities::get_column_values_at_as_vec(feature_tracks.begin()->second.size() - 1, feature_tracks);\n\n            /**\n             *  - get 2d cv points \n             *  - recover poses for first and last\n             *  - triangulate\n             *  - PnP for mid frames\n             */\n\n            std::vector<cv::Point2f> ref_points, cam_points;\n            ref_points.reserve(refcam_track_features.size());\n            cam_points.reserve(cam_track_features.size());\n\n            std::vector<std::pair<uint32_t, uint32_t>> fmatches;\n\n            for (int i = 0; i < refcam_track_features.size(); i++)\n            {\n                const cv::Point2f ref_pt = refcam->kp_features[refcam_track_features[i]].pt;\n                const cv::Point2f cam_pt = cam->kp_features[cam_track_features[i]].pt;\n\n                fmatches.push_back(std::make_pair(refcam_track_features[i], cam_track_features[i]));\n\n                ref_points.push_back(ref_pt);\n                cam_points.push_back(cam_pt);\n\n                // std::cout << ref_pt << \" : \" << cam_pt << \"\\n\";\n            }\n\n            cv::Mat good_feature_mask;\n\n            const cv::Mat essential = cv::findEssentialMat(ref_points, cam_points, intr_cv, cv::RANSAC, 0.999, 1.0, good_feature_mask);\n            cv::Mat R_local, t_local;\n            cv::recoverPose(essential, ref_points, cam_points, intr_cv, R_local, t_local, good_feature_mask);\n\n            Eigen::Matrix3d dR;\n            Eigen::Vector3d dt;\n            cv::cv2eigen(R_local, dR);\n            cv::cv2eigen(t_local, dt);\n\n            cam->dR = dR;\n            cam->dt = dt;\n\n            // DEBUG_visualize_matches(refcam, cam, fmatches);\n\n            set_camera_T_and_P(cam, dR.transpose(), -dR.transpose() * dt);\n            set_camera_T_and_P(cam, refcam->T * cam->T);\n\n            // std::cout << cam->rotation << \"\\n\\n\" << cam->position.transpose() << \"\\n\\n\";\n\n            cv::Mat refcam_P, cam_P;\n            cv::eigen2cv(refcam->P, refcam_P);\n            cv::eigen2cv(cam->P, cam_P);\n\n            cv::Mat p4d;\n            cv::triangulatePoints(refcam_P, cam_P, ref_points, cam_points, p4d);\n\n            std::vector<Eigen::Vector3d> points3d;\n\n            std::vector<cv::Point3f> new_points, existing_points;\n\n            // don't scale the points if no landmarks are found\n            if (landmarks.size() != 0)\n            {\n                for (int jj = 0; jj < ref_points.size(); jj++)\n                {\n                    const cv::Point3f p3d (\n                        p4d.at<float>(0, jj) / p4d.at<float>(3, jj),\n                        p4d.at<float>(1, jj) / p4d.at<float>(3, jj),\n                        p4d.at<float>(2, jj) / p4d.at<float>(3, jj));\n\n\n                    if (good_feature_mask.at<uint32_t>(jj))\n                    {\n                        // points3d.push_back(Eigen::Vector3d(p3d.x, p3d.y, p3d.z));\n\n                        // landmark\n\n                        const uint32_t ref_f_id = refcam_track_features[jj];\n                        // const uint32_t cam_f_id = cam_track_features[jj];\n\n                        // check if landmark exists -> add to / create new\n                        if (refcam->landmark_kp_exists(ref_f_id) && refcam->match_exists(ref_f_id, ii))\n                        {\n                            const uint32_t lm_id = refcam->landmark_lookup[ref_f_id];\n                            const cv::Point3f avg_3d = landmarks[lm_id].sum_point / (float)(landmarks[lm_id].view_data.size() - 1);\n\n                            // save the points for scale calculations\n                            new_points.push_back(p3d);\n                            existing_points.push_back(avg_3d);\n                        }\n                    }\n                }\n\n                // calculate the scale\n\n                double scale = 0.0;\n                uint32_t count = 0;\n\n                for (uint32_t jj = 0; jj < new_points.size() - 1; jj++)\n                {\n                    for (uint32_t kk = jj + 1; kk < new_points.size(); kk++)\n                    {\n                        const double denominator = norm(new_points[jj] - new_points[kk]);\n                        if (math::is_close(denominator, 0.f))\n                            continue;\n\n                        const double s = norm(existing_points[jj] - existing_points[kk]) / denominator;\n\n                        scale += s;\n                        count++;\n                    }\n                }\n\n                assert(count);\n\n                scale /= (double)count;\n                std::cout << \"for image \" << ii << \" final scale is \" << scale << \"\\n\";\n\n                dt *= scale;\n\n                cam->dR = dR;\n                cam->dt = dt;\n\n                // DEBUG_visualize_matches(refcam, cam, fmatches);\n\n                set_camera_T_and_P(cam, dR.transpose(), -dR.transpose() * dt);\n                set_camera_T_and_P(cam, refcam->T * cam->T);\n                cv::eigen2cv(cam->P, cam_P);\n\n                // re-triangulate with new projection matrix\n                cv::triangulatePoints(refcam_P, cam_P, ref_points, cam_points, p4d);\n            }\n\n            std::vector<cv::Point3f> tr_3d_points;\n\n            for (int jj = 0; jj < ref_points.size(); jj++)\n            {\n                const cv::Point3f p3d (\n                    p4d.at<float>(0, jj) / p4d.at<float>(3, jj),\n                    p4d.at<float>(1, jj) / p4d.at<float>(3, jj),\n                    p4d.at<float>(2, jj) / p4d.at<float>(3, jj));\n\n                // add to or create new landmarks\n                if (good_feature_mask.at<uint32_t>(jj))\n                {\n                    points3d.push_back(Eigen::Vector3d(p3d.x, p3d.y, p3d.z));\n                    tr_3d_points.push_back(p3d);\n\n                    const uint32_t ref_f_id = refcam_track_features[jj];\n                    const uint32_t cam_f_id = cam_track_features[jj];\n\n                    // landmark exists, add to it\n                    if (refcam->landmark_kp_exists(ref_f_id))\n                    {\n                        cam->landmark_lookup[cam_f_id] = refcam->landmark_lookup[ref_f_id];\n\n                        Landmark& lm = landmarks[cam->landmark_lookup[cam_f_id]];\n                        lm.add_view_simple(cam->id, cam_f_id, p3d);\n                    }\n                    // landmark doesn't exist, create new\n                    else\n                    {\n                        Landmark lm;\n                        lm.add_view_simple(refcam->id, ref_f_id, p3d);\n                        lm.add_view_simple(cam->id, cam_f_id, p3d);\n\n                        landmarks.emplace_back(lm);\n\n                        refcam->landmark_lookup[ref_f_id] = landmarks.size() - 1;\n                        cam->landmark_lookup[cam_f_id] = landmarks.size() - 1;\n                    }\n                }\n            }\n\n\n            std::shared_ptr<o3d::geometry::TriangleMesh> camera_mesh = std::make_shared<o3d::geometry::TriangleMesh>(o3d::geometry::TriangleMesh());\n            o3d::io::ReadTriangleMeshFromOBJ(reg_params.assets_path + DEBUG_CAMERA_PATH, *camera_mesh, false);\n            camera_mesh->Transform(cam->T);\n\n            auto cloud = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(points3d));\n            o3d::visualization::DrawGeometries({ cloud, camera_mesh });\n\n            // create frame fragment, lambdas ftw\n            frame_fragments.push_back(FrameFragment {\n                [&]{ std::vector<Camera*> cams; for (int i = ii; i < ii + feature_tracks.begin()->second.size(); i++) cams.push_back(cameras[i]); return cams; } (),\n                feature_tracks,\n                [&] { std::vector<Eigen::Matrix4d> ts; for (int i = ii; i < ii + feature_tracks.begin()->second.size(); i++) ts.push_back(cameras[i]->T); return ts; }(),\n                tr_3d_points\n            });\n        }\n\n        // PnP for first fragment\n        FrameFragment& initial = frame_fragments[0];\n        for (int ii = 1; ii < initial.frag_cameras.size() - 2; ii++)\n        {\n            // take 2d feature points, PnP to initial.tr_3d_points\n            const auto f_ids = utilities::get_column_values_at_as_vec(ii, initial.frag_feature_tracks);\n\n            Camera* cam = initial.frag_cameras[ii];\n\n            std::vector<cv::Point2f> view_features_points;\n\n            for (int jj = 0; jj < f_ids.size(); jj++)\n                view_features_points.push_back(cam->kp_features[f_ids[jj]].pt);\n\n            const cv::Mat cv_intr = [&]{\n                cv::Mat intr;\n                cv::eigen2cv(cam->intr.intrinsic_matrix_, intr);\n                return intr;\n            }();\n\n            cv::Mat rcv, tcv;\n            cv::solvePnPRansac(initial.feature_3d_points, view_features_points, cv_intr, cam->distortion_coeffs, rcv, tcv, true, 1000, 4.0, 0.987);\n\n            Eigen::Matrix4d R;\n            Eigen::Vector3d t;\n\n            cv::cv2eigen(rcv, R);\n            cv::cv2eigen(tcv, t);\n\n            // NOTE: this doesn't work anymore!\n            assert(false);\n            // set_camera_T_and_P(cam, R.transpose(), -R.transpose() * t);\n        }\n\n        // match fragments and propagate transformations\n\n        // 0th fragment is origin, skip it\n        for (int ii = 1; ii < frame_fragments.size(); ii++)\n        {\n            // take the 1st of the previous fragment, and the 0th of the ii fragment\n            // and use PnP to match them\n        }\n\n\n        // average landmarks\n\n\n        // PnP to average landmarks\n\n\n        /**\n         *  e.g.\n         * \n         *   0-4\n         *   1-5\n         *   2-7\n         *   3-8\n         * \n         *  - edges with essential\n         *  - intraframes with PnP\n         *  - match fragments 0:1 -> 1:0\n         * \n         *  - lastly, PnP to averaged landmarks\n         */\n\n        for (Landmark& lm : landmarks)\n        {\n            if (lm.view_data.size() >= 3)\n                lm.point3d = lm.sum_point / float(lm.view_data.size() - 1);\n        }\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"camera motion recovery\");\n        #endif\n    }\n\n    bool PoseGraph::compute_initial_pose(Camera* cam, const Camera* ref_cam)\n    {\n    \t/**\n\t\t * \t- first 2 frames special case\n    \t * \t\t* essential matrix, same as before\n    \t * \t\t* reject 2nd if over 50% features not over threshold\n    \t *\n    \t * \tTODO: more early termination reasons?\n         *\n         *  TODO: currently only-manual initial checking, \n         *          can essential matrix be used?\n         * \n         *  TODO: add pointcloud registration for the initial cloud\n    \t */\n    \t\n    \t// const auto rc_corr = correspondence_between_cameras(refcam, cam);\n    \t// std::pair<std::vector<uint32_t>, std::vector<uint32_t>> rc_corr =\n        std::vector<std::pair<uint32_t, uint32_t>> rc_corr =\n    \t\tmatch_features_hgraphy(ref_cam->feature_descriptors, cam->feature_descriptors, ref_cam, cam);\n            // match_features_bf_knn(ref_cam->feature_descriptors, cam->feature_descriptors);\n\n        // DEBUG_visualize_feature_matches_custom(ref_cam, cam, rc_corr);\n\n        /*         \n        {\n            std::vector<cv::KeyPoint> inliers1, inliers2;\n            std::vector<uint32_t> inliers1_i, inliers2_i;\n            std::vector<cv::DMatch> good_matches;\n\n            for (int i = 0; i < rc_corr.size(); i++)\n            {\n                inliers1.emplace_back(ref_cam->kp_features[rc_corr[i].first]);\n                inliers2.emplace_back(cam->kp_features[rc_corr[i].second]);\n\n                good_matches.emplace_back(cv::DMatch(i, i, 0));\n            }\n\n            cv::Mat matchimg;\n            cv::drawMatches(features::o3d_image_to_cv_image(ref_cam->rgb), inliers1, features::o3d_image_to_cv_image(cam->rgb), inliers2, good_matches, matchimg);\n            cv::imshow(\"img\", matchimg);\n            cv::waitKey(0);\n        }\n        */\n\n    \tif (rc_corr.size() < MIN_FEATURE_COUNT)\n        {\n            #ifdef DEBUG_VERBOSE\n            std::cout << \"not enough matches: \" << rc_corr.size() << \", aborting!\\n\";\n            #endif\n\n            remove_last_camera(cam);\n    \t\treturn false;\n        }\n\n    \trelative_pose_for_camera(ref_cam, cam, rc_corr);\n\n        // refine_pose_with_ICP(cam, ref_cam);\n    \tlandmarks_from_feature_matches(rc_corr, ref_cam, cam);\n\n        const std::vector<uint32_t> features_negative = \n            create_match_negative(rc_corr, cam->kp_features.size());\n\n        // camera_candidates.insert(std::make_pair(cam->id, features_negative));\n        candidates_from_unmatched(features_negative, cam);\n\n    \treturn true;\n    }\n\n    void PoseGraph::refine_pose_with_ICP(Camera* cam, const Camera* ref_cam)\n    {\n        // this method doesn't work correctly!\n        assert(false);\n\n        auto cam_cloud = rgbd::create_pcloud_from_rgbd(*cam->rgb, *cam->depth, DEFAULT_DEPTH_SCALE, DEFAULT_CLOUD_FAR_CLIP, false, cam->intr);\n        // cam_cloud->Scale(pointcloud_scale, false);\n        cam_cloud->Transform(cam->T);\n\n        auto ref_cam_cloud = rgbd::create_pcloud_from_rgbd(*ref_cam->rgb, *ref_cam->depth, DEFAULT_DEPTH_SCALE, DEFAULT_CLOUD_FAR_CLIP, false, ref_cam->intr);\n        // ref_cam_cloud->Scale(pointcloud_scale, false);\n        ref_cam_cloud->Transform(ref_cam->T);\n\n\n        // Colored ICP refinement\n        const float voxel_size = ICP_VOXEL_SIZE;\n        const float radius = ICP_NORMAL_RADIUS;\n\n        const float distance_threshold = voxel_size * 0.4f;\n        const Eigen::Matrix4d initial_transform = cam->T;\n\n        auto cam_cloud_downsampled = cam_cloud->VoxelDownSample(voxel_size);\n        auto ref_cam_cloud_downsampled = ref_cam_cloud->VoxelDownSample(voxel_size);\n\n        cam_cloud_downsampled->EstimateNormals(o3d::geometry::KDTreeSearchParamHybrid(radius, 30));\n        ref_cam_cloud_downsampled->EstimateNormals(o3d::geometry::KDTreeSearchParamHybrid(radius, 30));\n\n        // o3d::visualization::DrawGeometries({cam_cloud_downsampled, ref_cam_cloud_downsampled});\n\n        auto result = o3d::registration::RegistrationICP(\n            *cam_cloud_downsampled, *ref_cam_cloud_downsampled, distance_threshold, initial_transform,\n            o3d::registration::TransformationEstimationPointToPoint()); //,\n            // o3d::registration::ICPConvergenceCriteria(1e-6, 1e-6, ICP_ITER_COUNT));\n\n        if (result.fitness_ >= ICP_FITNESS_THRESHOLD)\n        {\n            set_camera_T_and_P(cam, result.transformation_);\n            std::cout << \"camera transform differences: \\n\" << result.transformation_ << \"\\n\\n\" << initial_transform << \"\\n\\n\" << result.fitness_ << \"\\n\\n\";\n        }\n        else\n        {\n            // cam_cloud_downsampled->Transform(result.transformation_);\n            // o3d::visualization::DrawGeometries({cam_cloud_downsampled, ref_cam_cloud_downsampled});\n            std::cout << \"bad fitness: \" << result.fitness_ << \"\\n\";\n        }\n    }\n\n    std::vector<uint32_t> PoseGraph::create_match_negative(\n        const std::vector<std::pair<uint32_t, uint32_t>> matched_features,\n        const uint32_t all_features_count) const\n    {\n        std::vector<uint32_t> feature_negative;\n        feature_negative.reserve(all_features_count - matched_features.size());\n\n        std::vector<uint32_t> matched;\n        matched.reserve(matched_features.size());\n\n        for (int i = 0; i < matched_features.size(); i++)\n        {\n            matched.emplace_back(matched_features[i].second);\n        }\n        // std::sort(matched.begin(), matched.end());\n\n        std::vector<uint32_t> all_features;\n        all_features.reserve(all_features_count);\n        for (uint32_t i = 0; i < all_features_count; i++)\n        {\n            all_features.emplace_back(i);\n        }\n\n        // // https://stackoverflow.com/questions/15758680/get-all-vector-elements-that-dont-belong-to-another-vector\n        // std::remove_copy_if(all_features.begin(), all_features.end(), std::back_inserter(feature_negative),\n        //     [&matched](const uint32_t& arg)\n        //     { return (std::find(matched.begin(), matched.end(), arg) != matched.end());});\n\n        // std::cout << \"all features: \" << all_features_count << \", fnegative: \" << feature_negative.size() << \", matched. \" << matched_features.size() << \"\\n\";\n\n        return set_negative_intersection(matched, all_features);\n    }\n\n    void PoseGraph::candidates_from_unmatched(const std::vector<uint32_t> unmatched_features, const Camera* cam)\n    {\n        const uint32_t cam_id = cam->id;\n        const std::vector<cv::KeyPoint> keypoints = cam->kp_features;\n        const cv::Mat descriptors = cam->feature_descriptors;\n        cv::Mat cam_P;\n        cv::eigen2cv(cam->P, cam_P);\n\n        for (int i = 0; i < unmatched_features.size(); i++)\n        {\n            Landmark lm;\n            lm.add_as_candidate(\n                cam_id,\n                unmatched_features[i],\n                keypoints[unmatched_features[i]],\n                descriptors.row(unmatched_features[i]),\n                cam_P\n            );\n\n            candidates.push_back(lm);\n        }\n    }\n\n    std::vector<cv::Point3f> PoseGraph::triangulate_matches(\n        const std::vector<std::pair<uint32_t, uint32_t>> matches,\n        const std::vector<uint32_t> first_cams, const Camera* second_cam) const\n    {\n        std::vector<cv::Point3f> triangulated;\n        triangulated.reserve(matches.size());\n\n        const std::vector<cv::KeyPoint> second_kps = second_cam->kp_features;\n        const cv::Mat second_cam_P = [&]\n        {\n            cv::Mat p;\n            cv::eigen2cv(second_cam->P, p);\n            return p;\n        }();\n\n        for (int i = 0; i < matches.size(); i++)\n        {\n            const std::vector<cv::Point2f> x1 { cameras[first_cams[i]]->kp_features[matches[i].first].pt };\n            const std::vector<cv::Point2f> x2 { second_kps[matches[i].second].pt };\n\n            cv::Mat first_cam_P;\n            cv::eigen2cv(cameras[first_cams[i]]->P, first_cam_P);\n\n            cv::Mat p4d;\n            cv::triangulatePoints(first_cam_P, second_cam_P, x1, x2, p4d);\n\n            triangulated.emplace_back(cv::Point3f(\n                p4d.at<float>(0, 0) / p4d.at<float>(3, 0),\n                p4d.at<float>(1, 0) / p4d.at<float>(3, 0),\n                p4d.at<float>(2, 0) / p4d.at<float>(3, 0)\n            ));\n        }\n\n        // debug visualization stuff\n        // std::vector<Eigen::Vector3d> points;\n        // for (int i = 0; i < triangulated.size(); i++)\n        //     points.emplace_back(Eigen::Vector3d(triangulated[i].x, triangulated[i].y, triangulated[i].z));\n\n        // auto pcloud = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(points));\n        // const auto a = o3d::geometry::TriangleMesh::CreateCoordinateFrame();\n        // o3d::visualization::DrawGeometries( { pcloud, a } );\n        // std::exit(0);\n        \n        return triangulated;\n    }\n\n    void PoseGraph::landmarks_from_feature_matches(\n        const std::vector<std::pair<uint32_t, uint32_t>> matches,\n        const Camera* first_cam, const Camera* second_cam)\n    {\n        /**\n         *  triangulate matches and create new landmarks \n         */\n\n\n        // std::vector<cv::DMatch> good_matches;\n        // std::vector<cv::KeyPoint> inliers1, inliers2;\n        // for (int i = 0; i < matches.size(); i++)\n        // {\n        //     inliers1.emplace_back(first_cam->kp_features[matches[i].first]);\n        //     inliers2.emplace_back(second_cam->kp_features[matches[i].second]);\n\n        //     good_matches.emplace_back(cv::DMatch(i, i, 0));\n        // }\n\n        // cv::Mat matchimg;\n        // cv::drawMatches(features::o3d_image_to_cv_image(first_cam->rgb), inliers1, features::o3d_image_to_cv_image(second_cam->rgb), inliers2, good_matches, matchimg);\n        // cv::imshow(\"img\", matchimg);\n        // cv::waitKey(0);\n\n        // std::vector<Eigen::Vector3d> trpoints;\n\n        landmarks.reserve(matches.size());\n\n        // extend the vector to be of the same size\n        const std::vector<uint32_t> first_cam_extended (matches.size(), (uint32_t)first_cam->id);\n        const std::vector<cv::Point3f> triangulated = triangulate_matches(matches, first_cam_extended, second_cam);\n\n        cv::Mat fcam_P, scam_P;\n        cv::eigen2cv(first_cam->P, fcam_P);\n        cv::eigen2cv(second_cam->P, scam_P);\n\n        const std::vector<uint32_t> valid_points = filter_points_behind_camera(second_cam, triangulated);\n\n        // create new landmarks\n        for (int j = 0; j < valid_points.size(); j++)\n        {\n            const uint32_t i = valid_points[j];\n\n            const cv::Point3f p3d = triangulated[i];\n            \n            const uint32_t ref_feature_id = matches[i].first;\n            const uint32_t feature_id = matches[i].second;\n\n            const uint32_t ref_cam_id = first_cam->id;\n            const uint32_t cam_id = second_cam->id;\n\n            const cv::KeyPoint ref_keypoint = first_cam->kp_features[ref_feature_id];\n            const cv::KeyPoint keypoint = second_cam->kp_features[feature_id];\n\n            const cv::Mat ref_descriptor = first_cam->feature_descriptors.row(ref_feature_id);\n            const cv::Mat descriptor = second_cam->feature_descriptors.row(feature_id);\n\n            Landmark lm;\n\n            lm.add_view(ref_cam_id, ref_feature_id, ref_keypoint, ref_descriptor, fcam_P);\n            lm.add_view(cam_id, feature_id, keypoint, descriptor, scam_P);\n            lm.set_3d_point(p3d);\n            lm.triangulation_view_pair = std::make_pair(0, 1);\n\n            landmarks.emplace_back(lm);\n\n            // trpoints.emplace_back(Eigen::Vector3d(p3d.x, p3d.y, p3d.z));\n        }\n\n        // auto cloud = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(trpoints));\n        // o3d::visualization::DrawGeometries({ cloud });\n    }\n\n    std::vector<uint32_t> PoseGraph::filter_points_behind_camera(const Camera* cam, const std::vector<cv::Point3f> points3d) const\n    {\n        std::vector<uint32_t> valid_points;\n        valid_points.reserve(points3d.size());\n\n        // depth test\n        // return (R*X)(2) + t(2);\n\n        for (int i = 0; i < points3d.size(); i++)\n        {\n            const cv::Point3f pcv = points3d[i];\n            const Eigen::Vector3d p = Eigen::Vector3d(pcv.x, pcv.y, pcv.z);\n            const Eigen::Vector3d pp = (cam->rotation * p) + cam->position;\n\n            // if point has the depth of < 0 or is distance outlier\n            if (pp(2) <= 0 || pp(2) > DEPTH_DISTANCE_OUTLIER)\n                continue;\n\n            valid_points.push_back(i);\n        }\n\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"valid points: \" << valid_points.size() << \"; original points: \" << points3d.size() << \"\\n\";\n        #endif\n\n        return valid_points;\n    }\n\n    std::tuple<Eigen::Matrix3d, Eigen::Vector3d> PoseGraph::relative_pose_for_camera(const Camera* ref_cam, Camera* cam,\n        const std::vector<std::pair<uint32_t, uint32_t>> feature_matches)\n    {\n        /**\n         *  NOTE: for some reason x1 and x2 are flipped, i.e. feature_matches\n         *      order is inverted.\n         */\n\n        std::vector<cv::Point2f> x1, x2;\n        x1.reserve(feature_matches.size());\n        x2.reserve(feature_matches.size());\n\n        for (int i = 0; i < feature_matches.size(); i++)\n        {\n            const cv::KeyPoint& kp0 = ref_cam->kp_features.at(feature_matches[i].first);\n            const cv::KeyPoint& kp1 = cam->kp_features.at(feature_matches[i].second);\n\n            x1.emplace_back(kp0.pt);\n            x2.emplace_back(kp1.pt);\n        }\n\n        cv::Mat mask;\n        cv::Mat cv_intr;\n        cv::eigen2cv(cam->intr.intrinsic_matrix_, cv_intr);\n\n        cv::Mat E = cv::findEssentialMat(x1, x2, cv_intr, cv::RANSAC, 0.999, 0.11, mask);\n\n        cv::Mat local_R, local_t;\n        cv::recoverPose(E, x1, x2, cv_intr, local_R, local_t, mask);\n\n        Eigen::Matrix3d dR;\n        Eigen::Vector3d dt;\n        cv::cv2eigen(local_R, dR);\n        cv::cv2eigen(local_t, dt);\n\n        // dt *= 0.31505707;\n\n        cam->dR = dR;\n        cam->dt = dt;\n\n        set_camera_T_and_P(cam, dR.transpose(), -dR.transpose() * dt);\n\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"\\033[1;31m\";\n\n        std::cout << \"relative dR and dt for camera: \" << ref_cam->id << \"->\" << cam->id << \"\\n\";\n        std::cout << \"dt: \" << dt.transpose() << \"\\n\";\n        #endif\n\n        Eigen::AngleAxisd ax(dR);\n\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"rodrigues axis: \" << ax.axis().transpose() << \", angle: \" << ax.angle() * (180.0/3.14159);\n        #endif\n\n        cam->rodriques_angle = ax.angle() * (180.0/3.14159);\n\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"\\033[0m\\n\\n\";\n        #endif\n\n        return std::make_tuple(cam->dR, cam->dt);\n    }\n\n    bool PoseGraph::compute_pose_realtime(Camera* cam, const uint32_t time_id)\n    {\n        Timer t;\n\n        std::map<std::pair<uint32_t, uint32_t>, cv::Mat> camera_homography_pairs;\n\n        // match features against landmarks, <landmark_id, feature_id>\n        std::vector<std::pair<uint32_t, uint32_t>> landmarks_in_view =\n            find_landmarks_in_view(cam, camera_homography_pairs);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"find landmarks in view\");\n        #endif\n\n        #ifdef DEBUG_VISUALIZE\n        DEBUG_visualize_landmark_matches_against_last(cam, landmarks_in_view, 1);\n        #endif\n        // t.stop(\"draw matches visualization\");\n\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"landmarks in view: \" << landmarks_in_view.size() << \"\\n\";\n        std::cout << \"landmarks: \" << landmarks.size() << \"\\n\";\n        std::cout << \"candidates: \" << candidates.size() << \"\\n\";\n        #endif\n\n        // create 3d-2d correspondences\n        std::vector<cv::Point3f> landmark_points;\n        std::vector<cv::Point2f> view_features;\n        landmark_points.reserve(landmarks_in_view.size());\n        view_features.reserve(landmarks_in_view.size());\n\n        // std::vector<Eigen::Vector3d> lmdebug;\n\n        if (landmarks_in_view.size() < reg_params.landmark_min_count)\n        {\n            #ifdef DEBUG_VERBOSE\n            std::cout << \"\\033[1;31m\";\n            std::cout << \"not enough landmarks in view: \" << landmarks_in_view.size() << \", returning false\\n\";\n            std::cout << \"\\033[0m\\n\";\n            #endif\n\n            return false;\n        }\n\n        for (int i = 0; i < landmarks_in_view.size(); i++)\n        {\n            landmark_points.emplace_back(landmarks[landmarks_in_view[i].first].point3d);\n            view_features.emplace_back(cam->kp_features[landmarks_in_view[i].second].pt);\n\n            // lmdebug.push_back(Eigen::Vector3d(landmark_points.back().x, landmark_points.back().y, landmark_points.back().z));\n        }\n\n        // const auto debug = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(lmdebug));\n        // o3d::visualization::DrawGeometries({ debug });\n\n        const cv::Mat cv_intr = [&]{\n            cv::Mat intr;\n            cv::eigen2cv(cam->intr.intrinsic_matrix_, intr);\n            return intr;\n        }();\n\n        // DEBUG_visualize_landmarks(landmark_points);\n\n        cv::Mat rcv, tcv, rcv_mat;\n        std::vector<int> inliers;\n        try\n        {\n            // use last frame as a guess\n            const Camera* refcam = cameras.at(cam->id - 1);\n            const auto [t_pred, r_pred, confidence] = pose_predictor.predict_next_pose(time_id);\n            cv::eigen2cv(r_pred, rcv);\n            cv::eigen2cv(t_pred, tcv);\n            // these parameters have been figured out by painstakingly trial-and-erroring\n            cv::solvePnPRansac(landmark_points, view_features, cv_intr, cam->distortion_coeffs, rcv, tcv, true, 1000, 4.0, 0.987, inliers);\n        }\n        catch (cv::Exception& e) {\n            #ifdef DEBUG_VERBOSE\n            std::cout << e.msg << \"\\n\";\n            std::cout << \"lm points: \" << landmark_points.size() << \", view_features: \" << view_features.size() << \"\\n\";\n            for (int i = 0; i < landmark_points.size(); i++)\n            {\n                std::cout << landmark_points[i] << \", \" << view_features[i] << \"\\n\";\n            }\n            #endif\n\n            visualize_tracks();\n            std::exit(0);\n        }\n        \n        #ifdef DEBUG_VERBOSE\n        t.stop(\"PnPRansac\");\n        std::cout << \"inliers size: \" << inliers.size() << \", original size: \" << view_features.size() << \"\\n\";\n        #endif\n\n        if (inliers.size() < reg_params.landmark_min_count)\n        {\n            #ifdef DEBUG_VERBOSE\n            std::cout << \"\\033[1;31m\";\n            std::cout << \"adding camera failed, not enough PnP inliers for camera \" << cam->id << \"\\n\";\n            std::cout << \"\\033[0m\\n\";\n            #endif\n\n            return false;\n        }\n\n        std::vector<cv::Point3f> inlier_points;\n        std::vector<cv::Point2f> inlier_features;\n        std::vector<std::pair<uint32_t, uint32_t>> good_lms_in_view;\n\n        inlier_points.reserve(inliers.size());\n        inlier_features.reserve(inliers.size());\n        good_lms_in_view.reserve(inliers.size());\n\n        for (int i : inliers)\n        {\n            inlier_points.push_back(landmark_points[i]);\n            inlier_features.push_back(view_features[i]);\n            good_lms_in_view.push_back(landmarks_in_view[i]);\n        }\n\n        // cv::solvePnPRefineLM(inlier_points, inlier_features, cv_intr, {}, rcv, tcv);\n        // t.stop(\"Levenberg-Marquardt refinement\");\n\n        // extract and set the camera R and t\n        {\n            Eigen::Matrix3d R;\n            Eigen::Vector3d t;\n\n            cv::Rodrigues(rcv, rcv_mat);\n            cv::cv2eigen(rcv_mat, R);\n            cv::cv2eigen(tcv, t);\n\n            set_camera_T_and_P(cam, R.transpose(), -R.transpose() * t);\n\n            #ifdef DEBUG_VERBOSE\n            std::cout << \"\\033[1;32m\";\n            std::cout << \"absolute world position for camera PnP: \" << cam->id << \"\\n\";\n            std::cout << \"t: \" << cam->position.transpose() << \", t norm: \" << cam->position.norm() << \"\\n\";\n            #endif\n\n            Eigen::AngleAxisd ax(cam->rotation);\n\n            #ifdef DEBUG_VERBOSE\n            std::cout << \"rodrigues axis: \" << ax.axis().transpose() << \", angle: \" << ax.angle() * (180.0/3.14159) << \"\\n\";\n            std::cout << \"\\033[0m\\n\";\n            #endif\n\n            cam->rodriques_angle = ax.angle() * (180.0/3.14159);\n        }\n\n        const auto [pose_score, pose_confidence]  = pose_predictor.verify_pose(time_id, cam->position, cam->rotation);\n\n        /**\n         *  low score & high confidence --> discard\n         *  high score & high confidence --> keep\n         * \n         *  low score & low confidence --> abort\n         *  high score & low confidence --> abort\n         * \n         *  reject also if pose difference is too great, compared to 1st camera position\n         *      --> rejects occasional outliers due to projection error\n         */\n        if ((pose_score < MIN_POSE_SCORE && pose_confidence >= POSE_CONFIDENCE_THRESHOLD) ||\n            (pose_confidence < POSE_CONFIDENCE_THRESHOLD) ||\n            (cam->position - cameras.at(cam->id - 1)->position).norm() > cameras.at(1)->position.norm() * CAMERA_POSITION_OUTLIER_MULTIPLIER)\n        {\n            #ifdef DEBUG_MINIMAL\n            std::cout << \"\\033[1;31m\";\n            std::cout << \"adding camera failed. pose score: \" << pose_score << \", pose confidence: \" << pose_confidence << \"\\n\";\n            std::cout << \"\\033[0m\\n\";\n            #endif\n\n            return false;\n        }\n\n        pose_predictor.add_good_pose(time_id, cam->position, cam->rotation);\n\n        // append landmark-feature matches to landmarks\n        add_track_to_landmarks(cam, landmarks_in_view, landmark_points, inliers);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"add track to landmarks\");\n        #endif\n\n        // retriangulate_landmarks(good_lms_in_view);\n        // t.stop(\"retriangulate landmarks\");\n\n        /**\n         *  NOTE:\n         *      track current candidates\n         *          - find unmatched non-lm features\n         *          - match against candidates\n         *              - add matched to candidates\n         *          - remove old candidates (no track for N frames), if cannot be triangulated\n         *          - triangulate succesful candidates and add to lms\n         *          - add all the rest unmatched features to candidates\n         */\n\n        const std::vector<uint32_t> unmatched =\n            create_match_negative(landmarks_in_view, cam->kp_features.size());\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"create match negative\");\n        #endif\n\n        /**\n         *  TODO:\n         *      optimize:\n         *      - match_features_against_candidates                 (234 ms)\n         *          - candidate match_features_bf since last took   (180 ms)\n         *      - handle_feature_candidate_matches                  (264 ms)\n         *          - to_landmark\n         */\n\n        // std::vector<uint32_t>* unmatched_features = new std::vector<uint32_t>();\n        // <candidate id, current cam feature id>\n        const std::vector<std::pair<uint32_t, uint32_t>> feature_candidates =\n            match_features_against_candidates(cam, unmatched, camera_homography_pairs);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"match features against candidates\");\n        #endif\n\n        /**\n         *  TODO:\n         *      track candidates until no match\n         *          --> create landmark if enough views\n         *          --> delete if invalid\n         */\n\n        handle_feature_candidate_matches(feature_candidates, cam, false);\n        remove_old_candidates(cam->id);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"handling candidates\");\n        #endif\n        \n        // collect the subset features not yet used anywhere\n        std::vector<uint32_t> subset;\n        {\n            subset.reserve(feature_candidates.size());\n            for (const auto& elem : feature_candidates)\n                subset.push_back(elem.second);\n        }\n        \n        const std::vector<uint32_t> new_candidate_features = set_negative_intersection(subset, unmatched);\n        candidates_from_unmatched(new_candidate_features, cam);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"candidate intersection and new\");\n        #endif\n\n        return true;\n    }\n\n    void PoseGraph::DEBUG_visualize_landmarks(const std::vector<cv::Point3f> points) const\n    {\n        if (points.size() < 3)\n            return;\n\n        std::vector<Eigen::Vector3d> epoints;\n        epoints.reserve(points.size());\n        for (const auto p : points)\n        {\n            epoints.emplace_back(Eigen::Vector3d(p.x, p.y, p.z));\n            std::cout << \"point: \" << epoints.back().transpose() << \"\\n\";\n        }\n\n        const auto debug_cloud = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(epoints));\n        o3d::visualization::DrawGeometries({ debug_cloud });\n    }\n\n    void PoseGraph::DEBUG_visualize_landmarks(const std::vector<uint32_t> lms) const\n    {\n        if (lms.size() == 0)\n            return;\n\n        std::vector<cv::Point3f> points;\n        points.reserve(lms.size());\n\n        for (uint32_t i : lms)\n        {\n            const Landmark& lm = landmarks[i];\n            points.emplace_back(lm.point3d);\n        }\n\n        DEBUG_visualize_landmarks(points);\n    }\n\n    std::vector<uint32_t> PoseGraph::set_negative_intersection(const std::vector<uint32_t> subset, const std::vector<uint32_t> all) const\n    {\n        if (subset.size() > all.size())\n            throw std::runtime_error(\"subset was larger than all, aborting\");\n        \n        std::vector<uint32_t> ret_set = all;\n\n        for (const uint32_t s : subset)\n        {\n            auto iter = std::find(ret_set.begin(), ret_set.end(), s);\n            if (iter != ret_set.end())\n                ret_set.erase(iter);\n        }\n\n        return ret_set;\n    }\n\n    void PoseGraph::all_candidates_to_landmarks()\n    {\n        for (Landmark lm : candidates)\n        {\n            lm.to_landmark(cameras);\n            lm.retriangulate_full(cameras, 0.0);\n            landmarks.emplace_back(lm);\n        }\n    }\n\n    void PoseGraph::retriangulate_landmarks(const std::vector<std::pair<uint32_t, uint32_t>> landmark_features)\n    {\n        const double lm_avg_magnitude = landmark_average_magnitude();\n        \n        #ifdef _OPENMP\n        #pragma omp parallel for\n        #endif\n        for (int i = 0; i < landmark_features.size(); i++)\n        {\n            Landmark& lm = landmarks[landmark_features[i].first];\n            lm.retriangulate_full(cameras, lm_avg_magnitude);\n        }\n\n/* \n        for (int i = 0; i < landmark_features.size(); i++)\n        {\n            Landmark& lm = landmarks[landmark_features[i].first];\n            cv::Point3f sum_point(0.f, 0.f, 0.f);\n            int count = 0;\n\n            for (int j = 0; j < lm.view_data.size(); j++)\n            {\n                const Camera* cam = cameras.at(lm.view_data[j].camera_id);\n\n                for (int k = j; k < lm.view_data.size(); k++)\n                {\n                    const cv::Point3f p3d = lm.get_triangulated(j, k);\n\n                    // point is out of bounds\n                    // if (sqrt(p3d.dot(p3d)) > TRIANGULATED_POINT_OUTLIER_NORM)\n                    // const double point_depth = math::depth_from_RtX(cam->rotation, cam->position, Eigen::Vector3d(p3d.x, p3d.y, p3d.z));\n                    // if (point_depth <= 0 || point_depth > DEPTH_DISTANCE_OUTLIER)\n                    //     continue;\n\n                    if (!lm.to_landmark(cameras, lm_avg_magnitude))\n                    {\n                        continue;\n                    }\n\n                    sum_point += p3d;\n                    count++;\n                }\n            }\n\n            if (count > 0)\n            {\n                // std::cout << \"original: \" << lm.point3d << \"; new point: \" << sum_point / (float)count << \"\\n\";\n                lm.set_3d_point(sum_point / (float)count);\n            }\n        } */\n    }\n\n    void PoseGraph::retriangulate_landmarks()\n    {\n        const double lm_avg_3d = landmark_average_magnitude();\n\n        #ifdef _OPENMP\n        #pragma omp parallel for\n        #endif\n        for (int i = 0; i < landmarks.size(); i++)\n        {\n            landmarks[i].retriangulate_full(cameras, lm_avg_3d);\n        }\n    }\n\n    void PoseGraph::remove_old_candidates(const uint32_t cam_id)\n    {\n        std::vector<uint32_t> to_remove_candidates;\n        std::vector<uint32_t> debug_landmarks;\n\n        const double lm_avg_dist = landmark_average_magnitude();\n\n        for (int i = 0; i < candidates.size(); i++)\n        {\n            Landmark& cd = candidates[i];\n\n            // candidate lost tracking and didn't reach required length --> delete\n            if (abs((int)cd.view_data.back().camera_id - (int)cam_id) >= INVALID_CANDIDATE_CAMERA_TEMPORAL_DIFF &&\n                cd.view_data.size() < reg_params.candidate_chain_len)\n            {\n                to_remove_candidates.push_back(i);\n            }\n            // candidate lost tracking but reached the required length --> to landmark\n            // or enough movement between first and last\n            else if ((abs((int)cd.view_data.back().camera_id - (int)cam_id) >= INVALID_CANDIDATE_CAMERA_TEMPORAL_DIFF &&\n                cd.view_data.size() >= reg_params.candidate_chain_len) ||\n                candidate_movement_large_enough(cd))\n            {\n                cd.to_landmark(cameras);\n                cd.retriangulate_full(cameras, lm_avg_dist);\n                landmarks.push_back(cd);\n                debug_landmarks.push_back(landmarks.size() - 1);\n                \n                // const cv::Point2f front_pt = cd.view_data.front().feature_kp.pt;\n                // const cv::Point2f back_pt = cd.view_data.back().feature_kp.pt;\n\n                // // triangulate and create a landmark\n                // if (cd.to_landmark(cameras, lm_avg_dist))\n                // {\n                //     cd.retriangulate_full(cameras, lm_avg_dist);\n                //     landmarks.push_back(cd);\n                //     debug_landmarks.push_back(landmarks.size() - 1);\n                // }\n\n                to_remove_candidates.push_back(i);\n            }\n        }\n\n        // DEBUG_visualize_majority_candidate_matches(debug_landmarks, 100, false);\n        // DEBUG_visualize_landmarks(debug_landmarks);\n        remove_candidates(to_remove_candidates);\n    }\n\n    void PoseGraph::handle_feature_candidate_matches(const std::vector<std::pair<uint32_t, uint32_t>> matches, const Camera* cam, const bool check_for_lm)\n    {\n        cv::Mat cam_P;\n        cv::eigen2cv(cam->P, cam_P);\n        const uint32_t cam_id = cam->id;\n\n        std::vector<uint32_t> to_remove_candidates;\n        if (check_for_lm)\n            to_remove_candidates.reserve(matches.size());\n\n        std::vector<uint32_t> debug_landmarks;\n\n        const double lm_avg_dist = landmark_average_magnitude();\n\n        for (int i = 0; i < matches.size(); i++)\n        {\n            const uint32_t candidate_id = matches[i].first;\n            const uint32_t feature_id = matches[i].second;\n\n            Landmark& cd = candidates[candidate_id];\n            cd.add_view(\n                cam_id,\n                feature_id,\n                cam->kp_features[feature_id],\n                cam->feature_descriptors.row(feature_id),\n                cam_P,\n                cameras,\n                lm_avg_dist,\n                false\n            );\n\n\n            if (cd.view_data.size() >= reg_params.candidate_chain_len && check_for_lm)\n            {\n                cd.to_landmark(cameras);\n                cd.retriangulate_full(cameras, lm_avg_dist);\n                landmarks.push_back(cd);\n                debug_landmarks.push_back(landmarks.size() - 1);\n\n                // const cv::Point2f front_pt = cd.view_data.front().feature_kp.pt;\n                // const cv::Point2f back_pt = cd.view_data.back().feature_kp.pt;\n\n                // // const float feature_diff_magnitude = sqrt((back_pt - front_pt).dot(back_pt - front_pt));\n\n                // // triangulate and create a landmark\n                // if (cd.to_landmark(cameras))\n                // {\n                //     landmarks.push_back(cd);\n                //     debug_landmarks.push_back(landmarks.size() - 1);\n                // }\n\n                // either way, the candidate will be removed\n                to_remove_candidates.push_back(matches[i].first);\n            }\n        }\n\n        // DEBUG_visualize_majority_candidate_matches(debug_landmarks);\n        // DEBUG_visualize_landmarks(debug_landmarks);\n\n        if (check_for_lm)\n            remove_candidates(to_remove_candidates);\n    }\n\n    std::vector<std::pair<uint32_t, uint32_t>> PoseGraph::filter_candidate_matches_homography(\n        const std::vector<std::pair<uint32_t, uint32_t>> unfiltered,\n        const Camera* cam)\n    {\n        // group the candidate by camera (min n (4) lms per view?), compute homography matrix\n        // by-view, filter outliers by-view\n\n        // <camera_id, <corresponding candidate_match_ids>>\n        // the indexes in .second are indexes to unfiltered\n        std::map<uint32_t, std::vector<uint32_t>> cam_grouped_matches;\n\n        // if any candidate's views camera in cam_grouped_matches\n        // --> add, else create from 0th\n        for (uint32_t i = 0; i < unfiltered.size(); i++)\n        {\n            const Landmark& lm = candidates[unfiltered[i].first];\n\n            std::map<uint32_t, std::vector<uint32_t>>::iterator cam_iter =\n                cam_grouped_matches.find(lm.view_data.front().camera_id);\n            \n            // found, append the candidate_id \n            if (cam_iter != cam_grouped_matches.end())\n            {\n                cam_iter->second.push_back(i);\n            }\n            // not found, create new\n            else\n            {\n                cam_grouped_matches.insert(\n                    std::pair<uint32_t, std::vector<uint32_t>>(\n                        lm.view_data.front().camera_id,\n                        { i }\n                    )\n                );   \n            }\n        }\n\n        std::vector<std::pair<uint32_t, uint32_t>> filtered_matches;\n        filtered_matches.reserve(unfiltered.size());\n\n        // filter with homography\n        for (const auto it : cam_grouped_matches)\n        {\n            if (it.second.size() < INVALID_CANDIDATE_CAMERA_TEMPORAL_DIFF)\n                continue;\n\n            std::vector<cv::Point2f> fpoints1, fpoints2;\n            fpoints1.reserve(it.second.size());\n            fpoints2.reserve(it.second.size());\n\n            std::vector<cv::DMatch> good_matches;\n            std::vector<cv::KeyPoint> fkp1, fkp2;\n\n            // collect fpoints1 and fpoints2\n            for (uint32_t i : it.second)\n            {\n                fpoints1.push_back(candidates[unfiltered[i].first].view_data.front().feature_kp.pt);\n                fpoints2.push_back(cam->kp_features[unfiltered[i].second].pt);\n\n                fkp1.push_back(candidates[unfiltered[i].first].view_data.front().feature_kp);\n                fkp2.push_back(cam->kp_features[unfiltered[i].second]);\n            }\n\n            cv::Mat inlier_mask, homography;\n            std::vector<cv::DMatch> inlier_matches;\n\n            homography = findHomography(fpoints1, fpoints2, cv::RANSAC, ransac_thresh, inlier_mask);\n\n            int l_i = 0;\n            for (size_t i = 0; i < fpoints1.size(); i++)\n            {\n                cv::Mat col = cv::Mat::ones(3, 1, CV_64F);\n                col.at<double>(0) = fpoints1[i].x;\n                col.at<double>(1) = fpoints2[i].y;\n                col = homography * col;\n                col /= col.at<double>(2);\n\n                const double dist = sqrt(pow(col.at<double>(0) - fpoints2[i].x, 2) + pow(col.at<double>(1) - fpoints2[i].y, 2));\n                if (dist < CANDIDATE_INLIER_THRESHOLD)\n                {\n                    filtered_matches.push_back(unfiltered[it.second[i]]);\n\n                    good_matches.emplace_back(cv::DMatch(i, i, 0));\n                    l_i++;\n                }\n            }\n\n            // debug visualize matches\n            {\n                if (good_matches.size() == 0)\n                    continue;\n\n                auto ref_rgb = cameras[it.first]->rgb;\n\n                cv::Mat matchimg;\n                cv::drawMatches(rgbd::o3d_image_to_cv_image(ref_rgb), fkp1, rgbd::o3d_image_to_cv_image(cam->rgb), fkp2, good_matches, matchimg);\n                cv::imshow(\"img\", matchimg);\n                cv::waitKey(0);\n            }\n        }\n\n        filtered_matches.shrink_to_fit();\n\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"sizes : \" << filtered_matches.size() << \", \" << unfiltered.size() << \"\\n\";\n        #endif\n\n        return filtered_matches;\n    }\n\n    std::vector<uint32_t> PoseGraph::find_negative_features_from_unmatched(\n            const std::vector<std::pair<uint32_t, uint32_t>> feature_candidate_matches,\n            const std::vector<uint32_t> landmark_unmatched_features) const\n    {\n        /**\n         *  finds the features not in landmark_unmatched_features but in \n         *  feature_candidate_matches\n         * \n         *  feature_candidate_matches should always be smaller\n         */\n\n        if (landmark_unmatched_features.size() < feature_candidate_matches.size())\n        {\n            std::cout << \"lm unmatched features size: \" << landmark_unmatched_features.size() << \", fcm size: \" << feature_candidate_matches.size() << \"\\n\"; \n            throw std::runtime_error(\"landmark_unmatched_features was larger than feature_candidate_matches, impossible case! aborting\");\n        }\n\n        std::vector<uint32_t> negative;\n        negative.reserve(landmark_unmatched_features.size() - feature_candidate_matches.size());\n\n        std::vector<uint32_t> feature_candidate_matches_collected;\n        feature_candidate_matches_collected.reserve(feature_candidate_matches.size());\n        for (int i = 0; i < feature_candidate_matches.size(); i++)\n            feature_candidate_matches_collected.emplace_back(feature_candidate_matches[i].second);\n\n        // https://stackoverflow.com/questions/15758680/get-all-vector-elements-that-dont-belong-to-another-vector\n        std::remove_copy_if(landmark_unmatched_features.begin(), landmark_unmatched_features.end(), std::back_inserter(negative),\n            [&feature_candidate_matches_collected](const uint32_t& arg)\n            { return (std::find(feature_candidate_matches_collected.begin(), feature_candidate_matches_collected.end(), arg) != feature_candidate_matches_collected.end());});\n\n        return negative;\n    }\n\n    void PoseGraph::remove_candidates(std::vector<uint32_t> matched_candidates)\n    {\n        // sort and reverse the candidates for easier removing\n        std::sort(matched_candidates.begin(), matched_candidates.end());\n        std::reverse(matched_candidates.begin(), matched_candidates.end());\n\n        for (int i : matched_candidates)\n            candidates.erase(candidates.begin() + i);\n    }\n\n    std::vector<uint32_t> PoseGraph::add_landmarks_from_candidates(const Camera* cam,\n        const std::vector<std::pair<uint32_t, uint32_t>> candidate_matches)\n    {\n        /**\n         *  if possible, triangulate and add to landmarks\n         *  else add view to landmark\n         */\n\n        std::vector<uint32_t> succesfull_candidates;\n        succesfull_candidates.reserve(candidate_matches.size());\n\n        const cv::Mat cam_P = [&]{\n            cv::Mat p;\n            cv::eigen2cv(cam->P, p);\n            return p;\n        }();\n        const uint32_t cam_id = cam->id;\n\n        std::vector<Eigen::Vector3d> debug_points;\n        std::vector<cv::Point2f> debug_features;\n\n        const double lm_avg_magnitude = landmark_average_magnitude();\n\n        for (int i = 0; i < candidate_matches.size(); i++)\n        {\n            const uint32_t candidate_id = candidate_matches[i].first;\n            Landmark& candidate = candidates[candidate_id];\n            const uint32_t feature_id = candidate_matches[i].second;\n\n            const std::vector<cv::Point2f> x1 = { candidate.view_data[0].feature_kp.pt };\n            const std::vector<cv::Point2f> x2 = { cam->kp_features[feature_id].pt };\n\n            // skip triangulation and do not add if deviation not big enough\n            if (abs(x1[0].x - x2[0].x) < FEATURE_TRIANGULATION_MIN_DIFF && \n                abs(x1[0].y - x2[0].y) < FEATURE_TRIANGULATION_MIN_DIFF)\n            {\n                candidate.add_view(\n                    cam_id,\n                    feature_id,\n                    cam->kp_features[feature_id],\n                    cam->feature_descriptors.row(feature_id),\n                    cam_P,\n                    cameras,\n                    lm_avg_magnitude,\n                    true\n                );\n                continue;\n            }\n            succesfull_candidates.emplace_back(candidate_id);\n\n            const cv::Mat firstcam_P = candidate.view_data[0].camera_P;\n            \n            // std::cout << \"id: \" << candidate.view_data[0].camera_id << \"\\n\" << firstcam_P << \"\\n\\n\" << cam_P << \"\\n\\n\\n\";\n            \n            cv::Mat p4d;\n            cv::triangulatePoints(firstcam_P, cam_P, x1, x2, p4d);\n\n            const cv::Point3f p3d(\n                p4d.at<float>(0, 0) / p4d.at<float>(3, 0),\n                p4d.at<float>(1, 0) / p4d.at<float>(3, 0),\n                p4d.at<float>(2, 0) / p4d.at<float>(3, 0)\n            );\n\n            // discard the candidate/landmark if triangulation failed\n            if (sqrt(p3d.dot(p3d)) > TRIANGULATED_POINT_OUTLIER_NORM)\n                continue;\n\n            Landmark lm = candidate;\n\n            lm.add_view(\n                cam_id,\n                feature_id,\n                cam->kp_features[feature_id],\n                cam->feature_descriptors.row(feature_id),\n                cam_P,\n                cameras,\n                lm_avg_magnitude,\n                true\n            );\n\n            lm.set_3d_point(p3d);\n            landmarks.emplace_back(lm);\n\n            debug_points.emplace_back(Eigen::Vector3d(p3d.x, p3d.y, p3d.z));\n            debug_features.emplace_back(x2[0]);\n        }\n\n        /* if (debug_points.size() > 10)\n        {\n            auto debug_cloud = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(debug_points));\n            std::shared_ptr<o3d::geometry::TriangleMesh> camera_mesh = std::make_shared<o3d::geometry::TriangleMesh>(o3d::geometry::TriangleMesh());\n            o3d::io::ReadTriangleMeshFromOBJ(reg_params.assets_path + DEBUG_CAMERA_PATH, *camera_mesh, false);\n            camera_mesh->Transform(cam->T);\n            DEBUG_visualize_features(cam->rgb, debug_features);\n            o3d::visualization::DrawGeometries({debug_cloud, camera_mesh});\n        } */\n\n        succesfull_candidates.shrink_to_fit();\n        return succesfull_candidates;\n    }\n\n    std::vector<std::pair<uint32_t, uint32_t>> PoseGraph::match_features_against_candidates(const Camera* cam,\n        const std::vector<uint32_t> matches_negative,\n        std::map<std::pair<uint32_t, uint32_t>, cv::Mat>& camera_hgraphy_pairs) const\n    {\n        if (candidates.size() == 0 || matches_negative.size() == 0)\n            return std::vector<std::pair<uint32_t, uint32_t>>();\n\n        // create candidate descriptors\n        const cv::Mat candidate_descriptors = create_candidate_descriptor();\n\n        // check for empty\n        if (candidate_descriptors.rows == 0)\n            return std::vector<std::pair<uint32_t, uint32_t>>();\n\n        // collect unmatched feature descriptors\n        cv::Mat unmatched_descriptors (matches_negative.size(), cam->feature_descriptors.cols, CV_32F);\n        const cv::Mat cam_kp_descriptors = cam->feature_descriptors;\n\n        for (int i = 0; i < matches_negative.size(); i++)\n        {\n            const float* const vaptr = cam_kp_descriptors.ptr<float>(matches_negative[i], 0);\n            \n            float* fptr = unmatched_descriptors.ptr<float>(i, 0);\n            for (int j = 0; j < unmatched_descriptors.cols; j++)\n            {\n                fptr[j] = vaptr[j];\n            }\n        }\n\n        Timer t;\n        // <candidate_id, index in matches_negative>\n        std::vector<std::pair<uint32_t, uint32_t>> candidate_matches = \n            match_features_bf(candidate_descriptors, unmatched_descriptors);\n        \n        #ifdef DEBUG_VERBOSE\n        t.stop(\"candidate match_features_bf\");\n        #endif\n\n        // unravel candidate_matches to be \n        // <candidate_id, feature_id>\n        for (int i = 0; i < candidate_matches.size(); i++)\n        {\n            const uint32_t second_id = candidate_matches[i].second;\n            candidate_matches[i].second = matches_negative[second_id];\n        }\n\n        // homography filtering. Marginally slower, but yields consistently more robust results\n        const auto good_matches = cdlm_pairwise_homography_filter(cam, candidate_matches, candidates, camera_hgraphy_pairs);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"candidate hgraphy filtering\");\n        #endif\n        // DEBUG_visualize_candidate_matches(cam, good_matches, 1);\n\n        return good_matches;\n    }\n\n    cv::Mat PoseGraph::create_candidate_descriptor() const\n    {\n        cv::Mat descriptor (candidates.size(), candidates[0].view_data[0].feature_descriptor.cols, CV_32F);\n\n        // set the descriptor rows to be landmark descriptors\n        for (int i = 0; i < candidates.size(); i++)\n        {\n            const cv::Mat view_descriptor = candidates[i].view_data.back().feature_descriptor;\n            const float* vaptr = view_descriptor.ptr<float>(0, 0);\n            \n            float* fptr = descriptor.ptr<float>(i, 0);\n            for (int j = 0; j < descriptor.cols; j++)\n            {\n                fptr[j] = vaptr[j];\n            }\n        }\n\n        return descriptor;\n    }\n\n    void PoseGraph::add_track_to_landmarks(const Camera* cam,\n        const std::vector<std::pair<uint32_t, uint32_t>> landmarks_in_view,\n        const std::vector<cv::Point3f> points3d,\n        const std::vector<int> inliers)\n    {\n        const uint32_t cam_id = cam->id;\n        cv::Mat cam_P;\n        cv::eigen2cv(cam->P, cam_P);\n\n        const double lm_avg_magnitude = landmark_average_magnitude();\n\n        for (int i : inliers)\n        {\n            const uint32_t landmark_id = landmarks_in_view[i].first;\n            const uint32_t feature_id = landmarks_in_view[i].second;\n            // const cv::Point3f p3d = points3d[i];\n            const cv::KeyPoint kpf = cam->kp_features[feature_id];\n            const cv::Mat descriptor = cam->feature_descriptors.row(feature_id);\n\n            landmarks.at(landmark_id).add_view(\n                cam_id,\n                feature_id,\n                kpf,\n                descriptor,\n                cam_P,\n                cameras,\n                lm_avg_magnitude,\n                true\n            );\n        }\n    }\n\n    std::vector<std::pair<uint32_t, uint32_t>> \n        PoseGraph::find_landmarks_in_view(const Camera* cam,\n        std::map<std::pair<uint32_t, uint32_t>, cv::Mat>& camera_hgraphy_pairs,\n        const uint32_t view_offset) const\n    {\n        Timer t;\n        \n        const cv::Mat landmark_descriptor = create_landmark_descriptor(view_offset);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"create landmark descriptor\");\n        #endif\n\n        // < lm_id, f_id >\n        const std::vector<std::pair<uint32_t, uint32_t>> landmarks_in_view = \n            match_features_bf(landmark_descriptor, cam->feature_descriptors);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"match landmarks against features\");\n        #endif\n\n        const auto good_landmarks_in_view = cdlm_pairwise_homography_filter(cam, landmarks_in_view, landmarks, camera_hgraphy_pairs, true);\n\n        #ifdef DEBUG_VERBOSE\n        t.stop(\"landmark homography filtering\");\n        #endif\n\n        return good_landmarks_in_view;\n    }\n\n    cv::Mat PoseGraph::create_landmark_descriptor(const uint32_t view_offset) const\n    {\n        if (landmarks.size() == 0)\n        {\n            throw std::runtime_error(\"cannot create a descriptor because there are no landmarks!\");\n        }\n\n        cv::Mat descriptor (landmarks.size(), landmarks[0].view_data[0].feature_descriptor.cols, CV_32F);\n\n        // set the descriptor rows to be landmark descriptors\n        for (int i = 0; i < landmarks.size(); i++)\n        {\n\n            const cv::Mat view_average_desc = landmarks[i].view_data[landmarks[i].view_data.size() - 1 - \n                (landmarks[i].view_data.size() > view_offset ? view_offset : 0)\n            ].feature_descriptor;\n                // compute_view_average_descriptor();\n            const float* vaptr = view_average_desc.ptr<float>(0, 0);\n            \n            float* fptr = descriptor.ptr<float>(i, 0);\n            for (int j = 0; j < descriptor.cols; j++)\n            {\n                fptr[j] = vaptr[j];\n            }\n        }\n\n        return descriptor;\n    }\n\n    std::shared_ptr<o3d::geometry::PointCloud> PoseGraph::landmarks_to_pointcloud() const\n    {\n        std::vector<Eigen::Vector3d> points3d, colors;\n        points3d.reserve(landmarks.size());\n        colors.reserve(landmarks.size());\n\n        for (int i = 0; i < landmarks.size(); i++)\n        {\n            const cv::Point3f p3d = landmarks[i].point3d;\n            const Eigen::Vector3d p3de (p3d.x, p3d.y, p3d.z);\n\n            // if (p3de.norm() > 30.0)\n            //     continue;\n            \n            points3d.emplace_back(p3de);\n            colors.emplace_back(landmarks[i].point_color);\n        }\n\n        auto cloud = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(points3d));\n        cloud->colors_ = colors;\n        return cloud;\n    }\n\n    void PoseGraph::create_pointclouds_from_depths(const bool only_scale)\n    {\n        if (cameras.empty())\n            throw std::runtime_error(\"cannot create pointclouds from non-existent cameras!\");\n        \n        if (!only_scale)\n            depth_pointclouds.clear();\n\n        // calculate scale for depthclouds\n    \t// gather all landmarks which have .front().camera_index  == 0\n        std::vector<cv::Point3f> zero_view_points;\n        std::vector<cv::Point2f> zero_view_features;\n        for (int i = 0; i < landmarks.size(); i++)\n        {\n            const Landmark& lm = landmarks[i];\n            if (lm.view_data.front().camera_id == 0)\n            {\n                zero_view_features.push_back(lm.view_data.front().feature_kp.pt);\n                zero_view_points.push_back(lm.point3d);\n            }\n        }\n\n        uint32_t count = 0;\n        double cloud_scale = 0.0;\n\n        const Camera* cam = cameras.at(0);\n\n        for (int i = 0; i < zero_view_points.size(); i++)\n        {\n            const double depth = (double)(*cam->depth->PointerAt<uint16_t>(\n                (int)zero_view_features[i].x, (int)zero_view_features[i].y)) / 1000.0;\n            \n            // do not account for occluded pixels\n            if (depth < DEPTH_NEAR_CLIPPING)\n                continue;\n\n            const Eigen::Vector3d depth_point = rgbd::triangulate_point(\n                Eigen::Vector2d(zero_view_features[i].x, zero_view_features[i].y),\n                depth, cam->intr);\n            \n            const Eigen::Vector4d depth_point_transformed = cam->T * Eigen::Vector4d(depth_point.x(), depth_point.y(), depth_point.z(), 0.0);\n            const Eigen::Vector3d dpoint (depth_point_transformed.x(), depth_point_transformed.y(), depth_point_transformed.z());\n\n            cloud_scale += \n                Eigen::Vector3d(zero_view_points[i].x, zero_view_points[i].y, zero_view_points[i].z).norm() / \n                dpoint.norm();\n\n            count++;\n        }\n\n        this->pointcloud_scale = cloud_scale / (double)count;\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"pointcloud scale: \" << pointcloud_scale << \"\\n\";\n        #endif\n\n        if (only_scale)\n            return;\n\n        // project depth images to pointclouds\n        for (int i = 0; i < cameras.size(); i++)\n        {\n            if (cameras[i]->depth == nullptr || cameras[i]->position.hasNaN() || cameras[i]->position.norm() > 1000.0)\n                continue;\n\n            auto cloud = rgbd::create_pcloud_from_rgbd(*cameras[i]->rgb, *cameras[i]->depth, DEFAULT_DEPTH_SCALE, reg_params.depth_far_clip, false, cameras[i]->intr);\n\n            if (cloud->points_.size() == 0)\n            {\n                std::cout << \"skip camera \" << i << \" due to no points\\n\";\n                continue;\n            }\n\n            cloud->Scale(this->pointcloud_scale, false);\n            cloud->Transform(cameras[i]->T);\n\n            depth_pointclouds.emplace_back(cloud);\n        }\n    }\n\n    void PoseGraph::remove_last_camera(Camera* cam)\n    {\n        const uint32_t cam_id = cam->id;\n        if (cameras.back()->id == cam_id)\n        {\n            cameras.pop_back();\n        }\n    }\n\n    std::vector<std::shared_ptr<Camera>> PoseGraph::get_cameras_copy() const\n    {\n        std::vector<std::shared_ptr<Camera>> rcameras;\n\n        for (const auto c : cameras)\n        {\n            rcameras.emplace_back(std::make_shared<Camera>(Camera(*c)));\n        }\n\n        return rcameras;\n    }\n\n    void PoseGraph::bundle_adjust()\n    {\n        /**\n         *  MAYBE:\n         *      http://docs.ros.org/en/melodic/api/gtsam/html/SFMExample__SmartFactor_8cpp_source.html\n         *      https://github.com/nghiaho12/SFM_example/blob/3b95176d9758752cbb1ebb7fa0050ded0b85e950/src/main.cpp#L352\n         * \n         */\n        \n        #ifdef DEBUG_MINIMAL\n        std::cout << \"begin bundle adjustment \\n\";\n        #endif\n\n        gtsam::Values result;\n\n        // add camera calibration matrix\n\n        const double cx = cameras.front()->intr.intrinsic_matrix_.coeff(0, 2);\n        const double cy = cameras.front()->intr.intrinsic_matrix_.coeff(1, 2);\n        const double fx = cameras.front()->intr.intrinsic_matrix_.coeff(0, 0);\n        const double fy = cameras.front()->intr.intrinsic_matrix_.coeff(1, 1);\n\n        gtsam::Cal3_S2 K(fx ,fy, 0, cx, cy);\n        const gtsam::noiseModel::Isotropic::shared_ptr measurement_noise = gtsam::noiseModel::Isotropic::Sigma(2, ADJUST_2DPOINT_NOISE);\n\n        gtsam::NonlinearFactorGraph graph;\n        gtsam::Values initial;\n\n        // add camera indexes and transformations (R, t)\n        for (int i = 0; i < cameras.size(); i++)\n        {\n            const Camera* cam = cameras.at(i);\n\n            const gtsam::Rot3 R (\n                cam->T.coeff(0, 0), cam->T.coeff(0, 1), cam->T.coeff(0, 2),\n                cam->T.coeff(1, 0), cam->T.coeff(1, 1), cam->T.coeff(1, 2),\n                cam->T.coeff(2, 0), cam->T.coeff(2, 1), cam->T.coeff(2, 2)\n            );\n\n            const gtsam::Point3 t (\n                cam->T.coeff(0, 3),\n                cam->T.coeff(1, 3),\n                cam->T.coeff(2, 3)\n            );\n\n            const gtsam::Pose3 pose (R, t);\n\n            if (i == 0)\n            {\n                gtsam::noiseModel::Diagonal::shared_ptr pose_noise = gtsam::noiseModel::Diagonal::Sigmas(\n                    (gtsam::Vector(6) << gtsam::Vector3::Constant(ADJUST_3DPOINT_NOISE), gtsam::Vector3::Constant(ADJUST_3DPOINT_NOISE)).finished());\n\n                graph.emplace_shared<gtsam::PriorFactor<gtsam::Pose3>>(gtsam::Symbol('x', 0), pose, pose_noise);\n            }\n\n            initial.insert(gtsam::Symbol('x', cam->id), pose);\n        }\n\n        // add landmarks\n        for (int i = 0; i < landmarks.size(); i++)\n        {\n            const Landmark& lm = landmarks[i];\n\n            for (int j = 0; j < lm.view_data.size(); j++)\n            {\n                const cv::Point2f& ptcv = lm.view_data[j].feature_kp.pt;\n                const gtsam::Point2 pt (ptcv.x, ptcv.y);\n\n                graph.emplace_shared<gtsam::GeneralSFMFactor2<gtsam::Cal3_S2>>(pt, measurement_noise, gtsam::Symbol('x', lm.view_data[j].camera_id),\n                    gtsam::Symbol('l', i), gtsam::Symbol('K', 0));\n            }\n        }\n\n        initial.insert(gtsam::Symbol('K', 0), K);\n\n        gtsam::noiseModel::Diagonal::shared_ptr cal_noise = gtsam::noiseModel::Diagonal::Sigmas((gtsam::Vector(5) << 0.0, 0.0, 0, 0.0, 0.0).finished());\n        graph.emplace_shared<gtsam::PriorFactor<gtsam::Cal3_S2>>(gtsam::Symbol('K', 0), K, cal_noise);\n\n        for (int i = 0; i < landmarks.size(); i++)\n        {\n            const Landmark& lm = landmarks[i];\n\n            const cv::Point3f p = lm.point3d;\n            initial.insert<gtsam::Point3>(gtsam::Symbol('l', i), gtsam::Point3(p.x, p.y, p.z));\n\n            if (i == 0)\n            {\n                // maximum noise for pose, 0.3m -> 30cm (assumed)\n                // gtsam::noiseModel::Isotropic::shared_ptr point_noise = gtsam::noiseModel::Isotropic::Sigma(3, ADJUST_3DPOINT_NOISE);\n                gtsam::noiseModel::Isotropic::shared_ptr point_noise = gtsam::noiseModel::Isotropic::Sigma(3, ADJUST_3DPOINT_NOISE);\n                graph.emplace_shared<gtsam::PriorFactor<gtsam::Point3>>(gtsam::Symbol('l', i), gtsam::Point3(p.x, p.y, p.z), point_noise);\n            }\n        }\n\n        #ifdef DEBUG_MINIMAL\n        std::cout << \"data added to bundle adjustment, adjusting...\\n\";\n        #endif\n\n        result = gtsam::LevenbergMarquardtOptimizer(graph, initial).optimize();\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"\\n\" << \"initial graph error: \" << graph.error(initial) << \"\\n\" << \"final graph error: \" << graph.error(result) << \"\\n\";\n        #endif\n\n        // std::vector<Eigen::Vector3d> old_positions;\n\n        // set new camera poses\n        for (int i = 0; i < cameras.size(); i++)\n        {\n            const Eigen::Matrix3d R = result.at<gtsam::Pose3>(gtsam::Symbol('x', i)).rotation().matrix();\n            const Eigen::Vector3d t = result.at<gtsam::Pose3>(gtsam::Symbol('x', i)).translation();\n\n            // std::cout << \"camera adjust movement: \" << (cameras[i]->position - (-R.transpose() * t)).norm() << \"\\n\";\n            // old_positions.push_back(cameras[i]->position);\n\n            set_camera_T_and_P(cameras[i], R, t);\n        }\n\n        // for (int i = 0; i < old_positions.size(); i++)\n        // {\n        //     std::cout << \"old: \" << old_positions[i].transpose() << \", new: \" << cameras[i]->position.transpose() << \"\\n\";\n        // }\n\n        // retriangulate_landmarks();\n    }\n\n    void PoseGraph::recompute_camera_poses_landmark_PnP()\n    {\n        /**\n         *  for each cameras, collect applying 2d-3d feature-landmark \n         *  correspondences, PnP\n         */\n\n        for (int ii = 0; ii < cameras.size(); ii++)\n        {\n            Camera* cam = cameras.at(ii);\n\n            std::map<std::pair<uint32_t, uint32_t>, cv::Mat> camera_homography_pairs;\n\n            // match features against landmarks, <landmark_id, feature_id>\n            std::vector<std::pair<uint32_t, uint32_t>> landmarks_in_view =\n                find_landmarks_in_view(cam, camera_homography_pairs);\n\n            // collect 3d landmarks and 2d feature points\n            std::vector<cv::Point2f> view_features;\n            std::vector<cv::Point3f> landmark_points;\n\n            std::vector<Eigen::Vector3d> points3d;\n\n            for (const auto& lfpair : landmarks_in_view)\n            {\n                const auto p3d = landmarks.at(lfpair.first).point3d;\n                if (p3d == cv::Point3f(0.0, 0.0, 0.0))\n                    continue;\n\n                landmark_points.push_back(p3d);\n                view_features.push_back(cam->kp_features[lfpair.second].pt);\n                points3d.push_back(Eigen::Vector3d(p3d.x, p3d.y, p3d.z));\n\n                // std::cout << view_features.back() << \" : \" << landmark_points.back() << \"\\n\";\n            }\n\n            // DEBUG_visualize_features(cam->rgb, view_features);\n            // DEBUG_visualize_landmarks(landmark_points);\n\n            // {\n            //     std::shared_ptr<o3d::geometry::TriangleMesh> camera_mesh = std::make_shared<o3d::geometry::TriangleMesh>(o3d::geometry::TriangleMesh());\n            //             o3d::io::ReadTriangleMeshFromOBJ(reg_params.assets_path + DEBUG_CAMERA_PATH, *camera_mesh, false);\n            //             camera_mesh->Transform(cam->T);\n            \n            //     auto cloud = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(points3d));\n            //     o3d::visualization::DrawGeometries({ cloud, camera_mesh });\n            // }\n\n            const cv::Mat cv_intr = [&]{\n                cv::Mat intr;\n                cv::eigen2cv(cam->intr.intrinsic_matrix_, intr);\n                return intr;\n            }();\n\n            cv::Mat rcv_rodr, rcv, tcv, inliers;\n            // cv::eigen2cv(cam->rotation, rcv);\n            // cv::eigen2cv(cam->position, tcv);\n\n            // these parameters have been figured out by painstakingly trial-and-erroring\n            const bool retval = cv::solvePnPRansac(landmark_points, view_features, cv_intr, cam->distortion_coeffs, rcv, tcv, false, 1000, 4.0, 0.987, inliers);\n\n\n            Eigen::Matrix3d R;\n            Eigen::Vector3d t;\n\n            cv::Rodrigues(rcv, rcv_rodr);\n            cv::cv2eigen(rcv_rodr, R);\n            cv::cv2eigen(tcv, t);\n\n            // std::cout << \"inliers: \" << inliers.size << \" and retval \" << retval << \" t \" << t.transpose() <<  \"\\n\";\n\n            // const Eigen::Matrix3d old_rot = cam->rotation;\n\n            set_camera_T_and_P(cam, R.transpose(), -R.transpose() * t);\n\n            // std::cout << cam->rotation << \"\\n\\n\" << old_rot << \"\\n\\n\" << cam->position.transpose() << \"\\n\";\n\n            // {\n            //     std::shared_ptr<o3d::geometry::TriangleMesh> camera_mesh = std::make_shared<o3d::geometry::TriangleMesh>(o3d::geometry::TriangleMesh());\n            //             o3d::io::ReadTriangleMeshFromOBJ(reg_params.assets_path + DEBUG_CAMERA_PATH, *camera_mesh, false);\n            //             camera_mesh->Transform(cam->T);\n            \n            //     auto cloud = std::make_shared<o3d::geometry::PointCloud>(o3d::geometry::PointCloud(points3d));\n            //     o3d::visualization::DrawGeometries({ cloud, camera_mesh });\n            // }\n        }\n    }\n\n    void PoseGraph::visualize_tracks() const\n    {\n        std::vector<std::shared_ptr<o3d::geometry::TriangleMesh>> camera_meshes;\n        std::vector<std::shared_ptr<const o3d::geometry::Geometry>> world_meshes;\n        for (int i = 0; i < cameras.size(); i++)\n        {\n            const Camera* c = cameras.at(i);\n\n            if (c->position.hasNaN() || c->position.norm() > 200)\n                continue;\n\n            std::shared_ptr<o3d::geometry::TriangleMesh> camera_mesh = std::make_shared<o3d::geometry::TriangleMesh>(o3d::geometry::TriangleMesh());\n            o3d::io::ReadTriangleMeshFromOBJ(reg_params.assets_path + DEBUG_CAMERA_PATH, *camera_mesh, false);\n            \n            if (pointcloud_scale == 0.0f)\n                camera_mesh->Scale(1.0f);\n            else\n                camera_mesh->Scale(pointcloud_scale * CAMERA_SCALE);\n\n            camera_mesh->Transform(c->T);\n\n            // camera_mesh->texture_.Clear();\n            // camera_mesh->PaintUniformColor(index2color(i));\n\n            camera_meshes.push_back(camera_mesh);\n            world_meshes.push_back(camera_mesh);\n\n            #ifdef DEBUG_MINIMAL\n            std::cout << \"camera \" << c->id << \" position: \" << c->position.transpose() << \"\\n\";\n            #endif\n        }\n\n        #ifdef DEBUG_VERBOSE\n        std::cout << \"triangulated clouds size: \" << ptrclouds.size() << \", depth clouds: \" << depth_pointclouds.size() << \"\\n\";\n        #endif\n\n        /* \n        for (int i = 0; i < ptrclouds.size(); i++)\n        {\n            break;\n\n            auto cloud = ptrclouds[i];\n            if (cloud->points_.size() < 10)\n                continue;\n\n            std::cout << \"cloud points: \" << cloud->points_.size() << \"\\n\";\n\n            if (cloud->colors_.size() == 0)\n            {\n                std::cout << \"featurecloud colors painted\\n\";\n                cloud->PaintUniformColor(Eigen::Vector3d(1.0, 0.0, 0.0));\n            }\n\n            for (int p3d_i = 0; p3d_i < cloud->points_.size(); p3d_i++)\n            {\n                if (cloud->points_.at(p3d_i).norm() > 60.0)\n                    cloud->points_.at(p3d_i) = Eigen::Vector3d::Zero();\n            }\n\n            world_meshes.push_back(cloud);\n        }\n        */\n\n        for (int i = 0; i < depth_pointclouds.size(); i++)\n        {\n            // break;\n\n            auto temp_cloud = depth_pointclouds[i];\n            world_meshes.push_back(temp_cloud);\n        }\n\n        const auto lm_cloud = landmarks_to_pointcloud();\n        // world_meshes.push_back(lm_cloud);\n\n        world_meshes.push_back(o3d::geometry::TriangleMesh::CreateCoordinateFrame());\n\n        o3d::visualization::DrawGeometries(world_meshes, \"camera track\", 1920, 1080, 180, 120);\n    }\n}\n", "meta": {"hexsha": "5be1133be9d7d61cda0bd12cd590c9fc0a6ed727", "size": 87468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/poseg2.cpp", "max_stars_repo_name": "ultravideo/Open3DGen", "max_stars_repo_head_hexsha": "6e3bcca874ba903c89594f075d4178c75fa1eb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T10:28:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:58:26.000Z", "max_issues_repo_path": "src/poseg2.cpp", "max_issues_repo_name": "zengletian1491/Open3DGen", "max_issues_repo_head_hexsha": "6e3bcca874ba903c89594f075d4178c75fa1eb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-11-01T08:11:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T05:25:56.000Z", "max_forks_repo_path": "src/poseg2.cpp", "max_forks_repo_name": "zengletian1491/Open3DGen", "max_forks_repo_head_hexsha": "6e3bcca874ba903c89594f075d4178c75fa1eb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2022-01-10T03:07:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T02:57:35.000Z", "avg_line_length": 37.9141742523, "max_line_length": 174, "alphanum_fraction": 0.561771162, "num_tokens": 21114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.2974699550610674, "lm_q1q2_score": 0.1807615315953299}}
{"text": "// Copyright 2020 The Defold Foundation\n// Licensed under the Defold License version 1.0 (the \"License\"); you may not use\n// this file except in compliance with the License.\n// \n// You may obtain a copy of the License, together with FAQs at\n// https://www.defold.com/license\n// \n// Unless required by applicable law or agreed to in writing, software distributed\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n// specific language governing permissions and limitations under the License.\n\n#include <string.h>\n#include <stdint.h>\n#include <float.h>\n#include <algorithm>\n#include <dlib/hash.h>\n#include <dlib/log.h>\n#include <dlib/math.h>\n#include <dlib/vmath.h>\n#include <dlib/profile.h>\n#include <dlib/time.h>\n\n#include \"particle.h\"\n#include \"particle_private.h\"\n\nnamespace dmParticle\n{\n    using namespace dmParticleDDF;\n    using namespace Vectormath::Aos;\n\n    const static float EPSILON = 0.0001f;\n    const static Vector3 PARTICLE_LOCAL_BASE_DIR = Vector3::yAxis();\n    const static Vector3 ACCELERATION_LOCAL_DIR = Vector3::yAxis();\n    const static Vector3 DRAG_LOCAL_DIR = Vector3::xAxis();\n    const static Vector3 VORTEX_LOCAL_AXIS = Vector3::zAxis();\n    // Should be set to positive rotation around VORTEX_LOCAL_AXIS\n    const static Vector3 VORTEX_LOCAL_START_DIR = -Vector3::xAxis();\n\n    /// Config key to use for tweaking maximum number of instances in a context.\n    const char* MAX_INSTANCE_COUNT_KEY          = \"particle_fx.max_count\";\n    /// Config key to use for tweaking the total maximum number of particles in a context.\n    const char* MAX_PARTICLE_COUNT_KEY          = \"particle_fx.max_particle_count\";\n\n    /// Used for degree to radian conversion\n    const float DEG_RAD = (float) (M_PI / 180.0);\n\n    /// Simulate motion blur at 60 fps with a 180 deg shutter\n    const static float STRETCH_SCALING = (1.0f/60.0f) * 0.5f;\n\n    AnimationData::AnimationData()\n    {\n        memset(this, 0, sizeof(*this));\n    }\n\n    void ResetEmitterStateChangedData(Instance* instance)\n    {\n        // Deallocate callback data if it is present\n        if(instance->m_EmitterStateChangedData.m_UserData != 0x0)\n        {\n            free(instance->m_EmitterStateChangedData.m_UserData);\n            instance->m_EmitterStateChangedData.m_UserData = 0x0;\n            instance->m_NumAwakeEmitters = 0;\n        }\n    }\n\n    HParticleContext CreateContext(uint32_t max_instance_count, uint32_t max_particle_count)\n    {\n        return new Context(max_instance_count, max_particle_count);\n    }\n\n    void DestroyContext(HParticleContext context)\n    {\n        uint32_t lingering = 0;\n        for (uint32_t i=0; i < context->m_Instances.Size(); ++i)\n        {\n            Instance* instance = context->m_Instances[i];\n            if (instance != 0x0)\n            {\n                ++lingering;\n                ResetEmitterStateChangedData(instance);\n            }\n            delete instance;\n        }\n        if (lingering > 0)\n            dmLogWarning(\"Destroyed %d instances (this might indicate leakage).\", lingering);\n        delete context;\n    }\n\n    uint32_t GetContextMaxParticleCount(HParticleContext context)\n    {\n        return context->m_MaxParticleCount;\n    }\n\n    void SetContextMaxParticleCount(HParticleContext context, uint32_t max_particle_count)\n    {\n        context->m_MaxParticleCount = max_particle_count;\n    }\n\n    static Instance* GetInstance(HParticleContext context, HInstance instance)\n    {\n        if (instance == INVALID_INSTANCE)\n            return 0x0;\n        uint16_t version = instance >> 16;\n        Instance* i = context->m_Instances[instance & 0xffff];\n\n        if (version != i->m_VersionNumber)\n        {\n            dmLogError(\"Stale instance handle\");\n            return 0;\n        }\n        return i;\n    }\n\n    float Hermite(float x0, float x1, float t0, float t1, float t) {\n        return (2 * t * t * t - 3 * t * t + 1) * x0 +\n               (t * t * t - 2 * t * t + t) * t0 +\n               (- 2 * t * t * t + 3 * t * t) * x1 +\n               (t * t * t - t * t) * t1;\n    }\n\n    float GetValue(const dmParticleDDF::SplinePoint* segments, int segment, float t)\n    {\n        SplinePoint p0 = segments[segment];\n        SplinePoint p1 = segments[segment + 1];\n        float dx = p1.m_X - p0.m_X;\n\n        float py0 = p0.m_Y;\n        float py1 = p1.m_Y;\n        float pt0 = dx * p0.m_TY / p0.m_TX;\n        float pt1 = dx * p1.m_TY / p1.m_TX;\n\n        return Hermite(py0, py1, pt0, pt1, t);\n    }\n\n    float GetY(const dmParticleDDF::SplinePoint* segments, uint32_t segment_count, float x)\n    {\n        if (segment_count == 1)\n        {\n            // Fall-back to linear interpolation\n            const SplinePoint& p = *segments;\n            return p.m_Y + (x - p.m_X) * p.m_TY / p.m_TX;\n        }\n        uint32_t segment_index = 0;\n        float t = 0;\n        for (uint32_t s = 0; s < segment_count - 1; ++s) {\n            const SplinePoint& p0 = segments[s];\n            const SplinePoint& p1 = segments[s + 1];\n            // break when we found the appropriate segemnt, or the last one\n            if ((x >= p0.m_X && x < p1.m_X) || s == segment_count - 2) {\n                t = (x - p0.m_X) / (p1.m_X - p0.m_X);\n                segment_index = s;\n                break;\n            }\n        }\n\n        return GetValue(segments, segment_index, t);\n    }\n\n    void SampleProperty(const dmParticleDDF::SplinePoint* segments, uint32_t segments_count, LinearSegment* out_segments)\n    {\n        float dx = 1.0f / PROPERTY_SAMPLE_COUNT;\n        float x0 = 0.0f;\n        float y0 = GetY(segments, segments_count, x0);\n        for (uint32_t j = 0; j < PROPERTY_SAMPLE_COUNT; ++j)\n        {\n            float y1 = GetY(segments, segments_count, x0 + dx);\n            out_segments[j].m_X = x0;\n            out_segments[j].m_Y = y0;\n            out_segments[j].m_K = (y1 - y0) * PROPERTY_SAMPLE_COUNT;\n            x0 += dx;\n            y0 = y1;\n        }\n    }\n\n    static void InitEmitter(Emitter* emitter, dmParticleDDF::Emitter* emitter_ddf, uint32_t original_seed)\n    {\n        emitter->m_Id = dmHashString64(emitter_ddf->m_Id);\n        uint32_t particle_count = emitter_ddf->m_MaxParticleCount;\n        emitter->m_Particles.SetCapacity(particle_count);\n        emitter->m_OriginalSeed = original_seed;\n\n        uint32_t seed = original_seed;\n        emitter->m_Duration = emitter_ddf->m_Duration + dmMath::Rand11(&seed) * emitter_ddf->m_DurationSpread;\n        emitter->m_StartDelay = emitter_ddf->m_StartDelay + dmMath::Rand11(&seed) * emitter_ddf->m_StartDelaySpread;\n        emitter->m_SpawnRateSpread = dmMath::Rand11(&seed) * ((dmParticleDDF::Emitter::Property&)emitter_ddf->m_Properties[EMITTER_KEY_SPAWN_RATE]).m_Spread;\n    }\n\n    static void ResetEmitter(Emitter* emitter);\n    void UpdateEmitterRenderData(HInstance instance, uint32_t emitter_index, Instance* inst, Emitter* emitter, dmParticleDDF::Emitter* ddf);\n    void ReHashEmitter(Emitter* e);\n\n    HInstance CreateInstance(HParticleContext context, HPrototype prototype, EmitterStateChangedData* emitter_state_changed_data)\n    {\n        if (context->m_InstanceIndexPool.Remaining() == 0)\n        {\n            dmLogError(\"Instance could not be created since the buffer is full (%d). Tweak \\\"%s\\\" in the config file.\", context->m_Instances.Capacity(), MAX_INSTANCE_COUNT_KEY);\n            return 0;\n        }\n        dmParticleDDF::ParticleFX* ddf = prototype->m_DDF;\n        uint32_t emitter_count = ddf->m_Emitters.m_Count;\n        Instance* instance = new Instance;\n        uint16_t index = context->m_InstanceIndexPool.Pop();\n\n        // Avoid zero in order to ensure that HInstance != INVALID_INSTANCE for valid handles.\n        if (context->m_NextVersionNumber == INVALID_INSTANCE) context->m_NextVersionNumber++;\n        instance->m_VersionNumber = context->m_NextVersionNumber++;\n\n        context->m_Instances[index] = instance;\n\n        instance->m_Prototype = prototype;\n\n        if(emitter_state_changed_data != 0x0 && emitter_state_changed_data->m_UserData != 0x0)\n        {\n            instance->m_EmitterStateChangedData = *emitter_state_changed_data;\n        }\n\n        instance->m_Emitters.SetCapacity(emitter_count);\n        instance->m_Emitters.SetSize(emitter_count);\n        uint32_t instance_handle = instance->m_VersionNumber << 16 | index;\n\n        uint32_t seed_base = (uint32_t)dmTime::GetTime();\n        memset(instance->m_Emitters.Begin(), 0, emitter_count * sizeof(Emitter));\n        for (uint32_t i = 0; i < emitter_count; ++i)\n        {\n            Emitter* emitter = &instance->m_Emitters[i];\n            uint32_t original_seed = seed_base + i;\n\n            // Add the context seed (and increase it) to avoid\n            // instances spawned the same frame to be identical.\n            original_seed += context->m_InstanceSeeding++;\n\n            InitEmitter(emitter, &ddf->m_Emitters[i], original_seed);\n            emitter->m_Seed = original_seed;\n\n            UpdateEmitterRenderData(instance_handle, i, instance, emitter, &ddf->m_Emitters[i]);\n            ReHashEmitter(emitter);\n        }\n\n        return instance_handle;\n    }\n\n    void DestroyInstance(HParticleContext context, HInstance instance)\n    {\n        if (instance == INVALID_INSTANCE) return;\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        ResetEmitterStateChangedData(i);\n        uint32_t index = instance & 0xffff;\n        context->m_InstanceIndexPool.Push(index);\n        context->m_Instances[index] = 0;\n        uint32_t emitter_count = i->m_Emitters.Size();\n        for (uint32_t emitter_i = 0; emitter_i < emitter_count; ++emitter_i)\n        {\n            Emitter* emitter = &i->m_Emitters[emitter_i];\n            emitter->m_Particles.SetCapacity(0);\n            emitter->m_RenderConstants.SetCapacity(0);\n        }\n        delete i;\n    }\n\n    void SetEmitterState(Instance* instance, Emitter* emitter, EmitterState state)\n    {\n        EmitterState old_emitter_state = emitter->m_State;\n        emitter->m_State = state;\n\n        if(state != old_emitter_state && instance->m_EmitterStateChangedData.m_UserData != 0x0)\n        {\n            if(state == EMITTER_STATE_PRESPAWN)\n            {\n                instance->m_NumAwakeEmitters += 1;\n            }\n            else if(state == EMITTER_STATE_SLEEPING)\n            {\n                instance->m_NumAwakeEmitters -= 1;\n            }\n\n            instance->m_EmitterStateChangedData.m_StateChangedCallback(\n                instance->m_NumAwakeEmitters,\n                emitter->m_Id,\n                emitter->m_State,\n                instance->m_EmitterStateChangedData.m_UserData);\n        }\n    }\n\n    static bool IsSleeping(Emitter* emitter);\n    static void UpdateEmitter(Prototype* prototype, Instance* instance, EmitterPrototype* emitter_prototype, Emitter* emitter, dmParticleDDF::Emitter* emitter_ddf, float dt);\n\n    static void StartEmitter(Instance* instance, Emitter* emitter)\n    {\n        // TODO: Fix auto-start\n        SetEmitterState(instance, emitter, EMITTER_STATE_PRESPAWN);\n        emitter->m_Retiring = 0;\n    }\n\n    static void StopEmitter(Instance* instance, Emitter* emitter)\n    {\n        if(emitter->m_State != EMITTER_STATE_SLEEPING)\n            SetEmitterState(instance, emitter, EMITTER_STATE_POSTSPAWN);\n\n        emitter->m_Retiring = 0;\n    }\n\n    static void RetireEmitter(Emitter* emitter)\n    {\n        emitter->m_Retiring = 1;\n    }\n\n    // Emitters are looping when play mode is looping, except for when retiring\n    static bool IsEmitterLooping(Emitter* emitter, dmParticleDDF::Emitter* emitter_ddf)\n    {\n        return emitter->m_Retiring == 0 && emitter_ddf->m_Mode == PLAY_MODE_LOOP;\n    }\n\n    static void FastForwardEmitter(Prototype* prototype, Instance* instance, EmitterPrototype* emitter_prototype, Emitter* emitter, dmParticleDDF::Emitter* emitter_ddf, float time)\n    {\n        StartEmitter(instance, emitter);\n        float timer = 0.0f;\n        // Hard coded for now\n        float dt = 1.0f / 60.0f;\n        while (timer < time)\n        {\n            UpdateEmitter(prototype, instance, emitter_prototype, emitter, emitter_ddf, dt);\n            timer += dt;\n        }\n    }\n\n    static float CalculateReplayTime(float duration, float start_delay, float max_particle_life_time, float play_time)\n    {\n        float time = play_time;\n        // In case play time is big we need to cut it down, but retain the position relative the duration\n        if (play_time > duration + max_particle_life_time + start_delay)\n        {\n            float inv_duration = 1.0f / duration;\n            float emitter_time = (play_time - start_delay) * inv_duration;\n            float frac = emitter_time - (uint32_t)emitter_time;\n            uint32_t iterations = 1 + (uint32_t)(max_particle_life_time * inv_duration);\n            time = start_delay + duration * (iterations + frac);\n        }\n        return time;\n    }\n\n    void ReloadInstance(HParticleContext context, HInstance instance, bool replay)\n    {\n        if (instance == INVALID_INSTANCE) return;\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        ResetEmitterStateChangedData(i);\n        dmArray<Emitter>& emitters = i->m_Emitters;\n        uint32_t emitter_count = emitters.Size();\n        Prototype* prototype = i->m_Prototype;\n        dmParticleDDF::ParticleFX* ddf = prototype->m_DDF;\n        uint32_t prototype_emitter_count = prototype->m_Emitters.Size();\n\n        if (emitter_count != prototype_emitter_count)\n        {\n            // Deallocate particle data if we are shrinking\n            if (prototype_emitter_count < emitter_count)\n            {\n                for (uint32_t emitter_i = prototype_emitter_count; emitter_i < emitter_count; ++emitter_i)\n                {\n                    emitters[emitter_i].m_Particles.SetCapacity(0);\n                }\n            }\n            emitters.SetCapacity(prototype_emitter_count);\n            emitters.SetSize(prototype_emitter_count);\n            // memset new emitters if we have grown\n            if (emitter_count < prototype_emitter_count)\n            {\n                memset(&emitters[emitter_count], 0, (prototype_emitter_count - emitter_count) * sizeof(Emitter));\n                // Set seeds\n                uint32_t seed_base = (uint32_t)dmTime::GetTime();\n                for (uint32_t emitter_i = emitter_count; emitter_i < prototype_emitter_count; ++emitter_i)\n                {\n                    Emitter* emitter = &emitters[emitter_i];\n                    uint32_t original_seed = seed_base + emitter_i + context->m_InstanceSeeding++;\n                    InitEmitter(emitter, &ddf->m_Emitters[emitter_i], original_seed);\n                    emitter->m_Seed = original_seed;\n                }\n            }\n        }\n        uint32_t old_emitter_count = dmMath::Min(emitter_count, prototype_emitter_count);\n        for (uint32_t emitter_i = 0; emitter_i < old_emitter_count; ++emitter_i)\n        {\n            Emitter* emitter = &emitters[emitter_i];\n            InitEmitter(emitter, &ddf->m_Emitters[emitter_i], emitter->m_OriginalSeed);\n        }\n        if (replay)\n        {\n            float max_play_time = 0.0f;\n            // Reload id and replay emitters\n            uint32_t count = i->m_Emitters.Size();\n            for (uint32_t emitter_i = 0; emitter_i < count; ++emitter_i)\n            {\n                Emitter* emitter = &emitters[emitter_i];\n                EmitterPrototype* emitter_prototype = &prototype->m_Emitters[emitter_i];\n                float time = CalculateReplayTime(emitter->m_Duration, emitter->m_StartDelay, emitter_prototype->m_MaxParticleLifeTime, i->m_PlayTime);\n                max_play_time = dmMath::Max(max_play_time, time);\n            }\n            i->m_PlayTime = max_play_time;\n            for (uint32_t emitter_i = 0; emitter_i < count; ++emitter_i)\n            {\n                Emitter* emitter = &emitters[emitter_i];\n                EmitterPrototype* emitter_prototype = &prototype->m_Emitters[emitter_i];\n                dmParticleDDF::Emitter* emitter_ddf = &prototype->m_DDF->m_Emitters[emitter_i];\n                ResetEmitter(emitter);\n                FastForwardEmitter(prototype, i, emitter_prototype, emitter, emitter_ddf, i->m_PlayTime);\n            }\n        }\n\n        ReHash(context, instance);\n    }\n\n    void StartInstance(HParticleContext context, HInstance instance)\n    {\n        if (instance == INVALID_INSTANCE) return;\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        dmArray<Emitter>& emitters = i->m_Emitters;\n        uint32_t emitter_count = emitters.Size();\n        Prototype* prototype = i->m_Prototype;\n        for (uint32_t emitter_i = 0; emitter_i < emitter_count; ++emitter_i)\n        {\n            dmParticleDDF::Emitter* emitter_ddf = &prototype->m_DDF->m_Emitters[emitter_i];\n            if (emitter_ddf->m_StartOffset < EPSILON)\n            {\n                StartEmitter(i, &emitters[emitter_i]);\n            }\n            else\n            {\n                Emitter* emitter = &emitters[emitter_i];\n                EmitterPrototype* emitter_prototype = &prototype->m_Emitters[emitter_i];\n\n                float playtime = dmMath::Max(0.0f, dmMath::Min(emitter_ddf->m_StartOffset, emitter_prototype->m_MaxParticleLifeTime));\n                FastForwardEmitter(prototype, i, emitter_prototype, emitter, emitter_ddf, playtime);\n            }\n        }\n    }\n\n    void StopInstance(HParticleContext context, HInstance instance)\n    {\n        if (instance == INVALID_INSTANCE) return;\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        dmArray<Emitter>& emitters = i->m_Emitters;\n        uint32_t emitter_count = emitters.Size();\n        for (uint32_t emitter_i = 0; emitter_i < emitter_count; ++emitter_i)\n        {\n            Emitter* emitter = &emitters[emitter_i];\n            StopEmitter(i, emitter);\n        }\n    }\n\n    void RetireInstance(HParticleContext context, HInstance instance)\n    {\n        if (instance == INVALID_INSTANCE) return;\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        dmArray<Emitter>& emitters = i->m_Emitters;\n        uint32_t emitter_count = emitters.Size();\n        for (uint32_t emitter_i = 0; emitter_i < emitter_count; ++emitter_i)\n        {\n            Emitter* emitter = &emitters[emitter_i];\n            RetireEmitter(emitter);\n        }\n    }\n\n    static void ResetEmitter(Emitter* emitter)\n    {\n        // Save particles array and id\n        dmArray<Particle> tmp;\n        tmp.Swap(emitter->m_Particles);\n        dmhash_t id = emitter->m_Id;\n        uint32_t original_seed = emitter->m_OriginalSeed;\n        float duration = emitter->m_Duration;\n        float start_delay = emitter->m_StartDelay;\n        float spawn_rate_spread = emitter->m_SpawnRateSpread;\n\n        // Clear emitter\n        memset(emitter, 0, sizeof(Emitter));\n\n        // Restore particles and id\n        tmp.Swap(emitter->m_Particles);\n        emitter->m_Id = id;\n\n        // Remove living particles\n        emitter->m_Particles.SetSize(0);\n\n        // Restore values\n        emitter->m_OriginalSeed = original_seed;\n        emitter->m_Seed = original_seed;\n        emitter->m_Duration = duration;\n        emitter->m_StartDelay = start_delay;\n        emitter->m_SpawnRateSpread = spawn_rate_spread;\n    }\n\n    void ResetInstance(HParticleContext context, HInstance instance)\n    {\n        if (instance == INVALID_INSTANCE) return;\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        i->m_PlayTime = 0.0f;\n        dmArray<Emitter>& emitters = i->m_Emitters;\n        uint32_t emitter_count = emitters.Size();\n        for (uint32_t emitter_i = 0; emitter_i < emitter_count; ++emitter_i)\n        {\n            ResetEmitter(&emitters[emitter_i]);\n        }\n    }\n\n    void SetPosition(HParticleContext context, HInstance instance, const Point3& position)\n    {\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        i->m_WorldTransform.SetTranslation(Vector3(position));\n    }\n\n    void SetRotation(HParticleContext context, HInstance instance, const Quat& rotation)\n    {\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        i->m_WorldTransform.SetRotation(rotation);\n    }\n\n    void SetScale(HParticleContext context, HInstance instance, float scale)\n    {\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        i->m_WorldTransform.SetScale(scale);\n    }\n\n    void SetScaleAlongZ(HParticleContext context, HInstance instance, bool scale_along_z)\n    {\n        Instance* i = GetInstance(context, instance);\n        if (!i) return;\n        i->m_ScaleAlongZ = scale_along_z;\n    }\n\n    Vector3 GetPosition(HParticleContext context, HInstance instance)\n    {\n        Instance* i = GetInstance(context, instance);\n        if (!i) return Vector3(0);\n        return i->m_WorldTransform.GetTranslation();\n    }\n\n    static bool IsSleeping(Emitter* emitter)\n    {\n        return emitter->m_State == EMITTER_STATE_SLEEPING;\n    }\n\n    bool IsSleeping(Instance* instance)\n    {\n        // Consider 0x0 instances as sleeping\n        if (!instance) return true;\n        bool is_sleeping = true;\n        dmArray<Emitter>& emitters = instance->m_Emitters;\n        uint32_t emitter_count = emitters.Size();\n        for (uint32_t emitter_i = 0; emitter_i < emitter_count; ++emitter_i)\n        {\n            if (!IsSleeping(&emitters[emitter_i]))\n            {\n                is_sleeping = false;\n                break;\n            }\n        }\n        return is_sleeping;\n    }\n\n    bool IsSleeping(HParticleContext context, HInstance instance)\n    {\n        return IsSleeping(GetInstance(context, instance));\n    }\n\n    // helper functions in update\n    static void FetchAnimation(Emitter* emitter, EmitterPrototype* prototype, FetchAnimationCallback fetch_animation_callback);\n    static void UpdateParticles(Instance* instance, Emitter* emitter, dmParticleDDF::Emitter* emitter_ddf, float dt);\n    static void UpdateEmitterState(Instance* instance, Emitter* emitter, EmitterPrototype* emitter_prototype, dmParticleDDF::Emitter* emitter_ddf, float dt);\n    static void EvaluateEmitterProperties(Emitter* emitter, Property* emitter_properties, float duration, float properties[EMITTER_KEY_COUNT]);\n    static void EvaluateParticleProperties(Emitter* emitter, Property* particle_properties, dmParticleDDF::Emitter* emitter_ddf, float dt);\n    static uint32_t UpdateRenderData(HParticleContext context, Instance* instance, Emitter* emitter, dmParticleDDF::Emitter* ddf, const Vector4& color, uint32_t vertex_index, void* vertex_buffer, uint32_t vertex_buffer_size, float dt, ParticleVertexFormat format);\n    static void GenerateKeys(Emitter* emitter, float max_particle_life_time);\n    static void SortParticles(Emitter* emitter);\n    static void Simulate(Instance* instance, Emitter* emitter, EmitterPrototype* prototype, dmParticleDDF::Emitter* ddf, float dt);\n\n    static void UpdateEmitter(Prototype* prototype, Instance* instance, EmitterPrototype* emitter_prototype, Emitter* emitter, dmParticleDDF::Emitter* emitter_ddf, float dt)\n    {\n        // Don't update emitter if time is standing still\n        if (IsSleeping(emitter) || dt <= 0.0f)\n            return;\n\n        UpdateParticles(instance, emitter, emitter_ddf, dt);\n\n        UpdateEmitterState(instance, emitter, emitter_prototype, emitter_ddf, dt);\n\n        GenerateKeys(emitter, emitter_prototype->m_MaxParticleLifeTime);\n        SortParticles(emitter);\n\n        Simulate(instance, emitter, emitter_prototype, emitter_ddf, dt);\n    }\n\n    static void UpdateEmitterVelocity(Instance* instance, Emitter* emitter, dmParticleDDF::Emitter* emitter_ddf, float dt)\n    {\n        // Update emitter velocity (1-frame estimate)\n\n        Point3 world_position = dmTransform::Apply(instance->m_WorldTransform, emitter_ddf->m_Position);\n        if (emitter->m_LastPositionSet)\n        {\n            if (dt > 0.0f)\n            {\n                Vector3 diff = world_position - emitter->m_LastPosition;\n                emitter->m_Velocity = diff * (1.0f/dt);\n            }\n        }\n        else\n        {\n            emitter->m_LastPositionSet = 1;\n        }\n        emitter->m_LastPosition = world_position;\n    }\n\n    void GenerateVertexData(HParticleContext context, float dt, HInstance instance, uint32_t emitter_index, const Vector4& color, void* vertex_buffer, uint32_t vertex_buffer_size, uint32_t* out_vertex_buffer_size, ParticleVertexFormat vertex_format)\n    {\n        DM_PROFILE(Particle, \"GenerateVertexData\");\n        if (instance == INVALID_INSTANCE)\n            return;\n\n        Instance* inst = GetInstance(context, instance);\n\n        if (IsSleeping(inst))\n            return;\n\n        uint32_t vertex_size = sizeof(Vertex);\n\n        if (vertex_format == PARTICLE_GUI)\n        {\n            vertex_size = sizeof(ParticleGuiVertex);\n        }\n\n        // vertex buffer index for each emitter\n        uint32_t vertex_index = 0;\n\n        vertex_index = *out_vertex_buffer_size / vertex_size;\n        Prototype* prototype = inst->m_Prototype;\n        Emitter* emitter = &inst->m_Emitters[emitter_index];\n        dmParticleDDF::Emitter* emitter_ddf = &prototype->m_DDF->m_Emitters[emitter_index];\n        if (vertex_buffer != 0x0 && vertex_buffer_size > 0)\n        {\n            vertex_index += UpdateRenderData(context, inst, emitter, emitter_ddf, color, vertex_index, vertex_buffer, vertex_buffer_size, dt, vertex_format);\n        }\n\n        *out_vertex_buffer_size = vertex_index * vertex_size;\n\n\n        context->m_Stats.m_Particles = vertex_index / 6; // Debug data for editor playback\n    }\n\n    void Update(HParticleContext context, float dt, FetchAnimationCallback fetch_animation_callback)\n    {\n        DM_PROFILE(Particle, \"Update\");\n\n        uint32_t size = context->m_Instances.Size();\n        uint32_t TotalAliveParticles = 0;\n        for (uint32_t i = 0; i < size; i++)\n        {\n            Instance* instance = context->m_Instances[i];\n\n            // empty slot\n            if (instance == 0x0) continue;\n            // don't update sleeping instances\n            if (IsSleeping(instance))\n            {\n                // update velocity and clear vertex count (don't render)\n                uint32_t emitter_count = instance->m_Emitters.Size();\n                for (uint32_t emitter_i = 0; emitter_i < emitter_count; ++emitter_i)\n                {\n                    Emitter* emitter = &instance->m_Emitters[emitter_i];\n                    emitter->m_VertexCount = 0;\n                    dmParticleDDF::Emitter* emitter_ddf = &instance->m_Prototype->m_DDF->m_Emitters[emitter_i];\n                    UpdateEmitterVelocity(instance, emitter, emitter_ddf, dt);\n                }\n                continue;\n            }\n            uint32_t instance_handle = instance->m_VersionNumber << 16 | i;\n            instance->m_PlayTime += dt;\n            Prototype* prototype = instance->m_Prototype;\n            uint32_t emitter_count = instance->m_Emitters.Size();\n            for (uint32_t emitter_i = 0; emitter_i < emitter_count; ++emitter_i)\n            {\n                Emitter* emitter = &instance->m_Emitters[emitter_i];\n                EmitterPrototype* emitter_prototype = &prototype->m_Emitters[emitter_i];\n                dmParticleDDF::Emitter* emitter_ddf = &prototype->m_DDF->m_Emitters[emitter_i];\n\n                UpdateEmitterVelocity(instance, emitter, emitter_ddf, dt);\n                UpdateEmitter(prototype, instance, emitter_prototype, emitter, emitter_ddf, dt);\n                TotalAliveParticles += (uint32_t)emitter->m_Particles.Size();\n                FetchAnimation(emitter, emitter_prototype, fetch_animation_callback);\n                UpdateEmitterRenderData(instance_handle, emitter_i, instance, emitter, emitter_ddf);\n\n                if (emitter->m_ReHash)\n                    ReHashEmitter(emitter);\n            }\n        }\n\n        DM_COUNTER(\"Particles alive\", TotalAliveParticles);\n    }\n\n    static void FetchAnimation(Emitter* emitter, EmitterPrototype* prototype, FetchAnimationCallback fetch_animation_callback)\n    {\n        DM_PROFILE(Particle, \"FetchAnimation\");\n\n        // Needed to avoid autoread of AnimationData when calling java through JNA\n        memset(&emitter->m_AnimationData, 0, sizeof(AnimationData));\n        if (fetch_animation_callback != 0x0 && prototype->m_TileSource)\n        {\n            FetchAnimationResult result = fetch_animation_callback(prototype->m_TileSource, prototype->m_Animation, &emitter->m_AnimationData);\n            if (result != FETCH_ANIMATION_OK)\n            {\n                if (!emitter->m_FetchAnimWarning)\n                {\n                    emitter->m_FetchAnimWarning = 1;\n                    dmLogWarning(\"The animation '%s' could not be found\", dmHashReverseSafe64(prototype->m_Animation));\n                }\n            } else {\n                assert(emitter->m_AnimationData.m_StructSize == sizeof(AnimationData) && \"AnimationData::m_StructSize has an invalid size\");\n                emitter->m_FetchAnimWarning = 0;\n            }\n        }\n    }\n\n    static void UpdateParticles(Instance* instance, Emitter* emitter, dmParticleDDF::Emitter* emitter_ddf, float dt)\n    {\n        DM_PROFILE(Particle, \"UpdateParticles\");\n\n        // Step particle life, prune dead particles\n        uint32_t particle_count = emitter->m_Particles.Size();\n        uint32_t j = 0;\n        while (j < particle_count)\n        {\n            Particle* p = &emitter->m_Particles[j];\n            p->SetTimeLeft(p->GetTimeLeft() - dt);\n            if (p->GetTimeLeft() < 0.0f)\n            {\n                // TODO Handle death-action\n                emitter->m_Particles.EraseSwap(j);\n                --particle_count;\n            } else {\n                ++j;\n            }\n        }\n    }\n\n    static void SpawnParticle(dmArray<Particle>& particles, uint32_t* seed, dmParticleDDF::Emitter* ddf, const dmTransform::TransformS1& emitter_transform, Vector3 emitter_velocity, float emitter_properties[EMITTER_KEY_COUNT], float dt);\n\n    static void UpdateEmitterState(Instance* instance, Emitter* emitter, EmitterPrototype* emitter_prototype, dmParticleDDF::Emitter* emitter_ddf, float dt)\n    {\n        DM_PROFILE(Particle, \"UpdateEmitterState\");\n\n        if (emitter->m_State == EMITTER_STATE_PRESPAWN)\n        {\n            if (emitter->m_Timer >= emitter->m_StartDelay)\n            {\n                SetEmitterState(instance, emitter, EMITTER_STATE_SPAWNING);\n                emitter->m_Timer -= emitter->m_StartDelay;\n            }\n        }\n        // Step emitter life\n        emitter->m_Timer += dt;\n        if (emitter->m_State != EMITTER_STATE_PRESPAWN) {\n            // never go above duration\n            emitter->m_Timer = dmMath::Min(emitter->m_Timer, emitter->m_Duration);\n        }\n        if (emitter->m_State == EMITTER_STATE_SPAWNING)\n        {\n            // wrap looping emitters when they reach the end\n            if (IsEmitterLooping(emitter, emitter_ddf) && emitter->m_Timer >= emitter->m_Duration)\n            {\n                emitter->m_Timer -= emitter->m_Duration;\n            }\n\n            // Evaluate spawn delay every frame while spawning (it might change)\n            float original_emitter_properties[EMITTER_KEY_COUNT];\n            float emitter_properties[EMITTER_KEY_COUNT];\n            EvaluateEmitterProperties(emitter, emitter_prototype->m_Properties, emitter->m_Duration, original_emitter_properties);\n            float spawn_rate = dmMath::Max(original_emitter_properties[EMITTER_KEY_SPAWN_RATE] + emitter->m_SpawnRateSpread, 0.0f);\n            emitter->m_ParticlesToSpawn += spawn_rate * dt;\n\n            uint32_t spawn_count = (uint32_t)emitter->m_ParticlesToSpawn;\n            emitter->m_ParticlesToSpawn -= spawn_count;\n            uint32_t count = dmMath::Min(emitter->m_Particles.Remaining(), spawn_count);\n            dmTransform::TransformS1 emitter_transform(Vector3(emitter_ddf->m_Position), emitter_ddf->m_Rotation, 1.0f);\n            Vector3 emitter_velocity(0.0f);\n            if (emitter_ddf->m_Space == EMISSION_SPACE_WORLD)\n            {\n                if (instance->m_ScaleAlongZ)\n                    emitter_transform = dmTransform::Mul(instance->m_WorldTransform, emitter_transform);\n                else\n                    emitter_transform = dmTransform::MulNoScaleZ(instance->m_WorldTransform, emitter_transform);\n                emitter_velocity = emitter->m_Velocity * emitter_ddf->m_InheritVelocity;\n            }\n            for (uint32_t i = 0; i < count; ++i)\n            {\n                for (uint32_t i = 0; i < EMITTER_KEY_COUNT; ++i)\n                {\n                    // Apply spread per particle\n                    float r = dmMath::Rand11(&emitter->m_Seed);\n                    emitter_properties[i] = original_emitter_properties[i] + r * emitter_prototype->m_Properties[i].m_Spread;\n                }\n                SpawnParticle(emitter->m_Particles, &emitter->m_Seed, emitter_ddf, emitter_transform, emitter_velocity, emitter_properties, dt);\n            }\n\n            if (!IsEmitterLooping(emitter, emitter_ddf) && emitter->m_Timer >= emitter->m_Duration)\n                StopEmitter(instance, emitter);\n        }\n        if (emitter->m_State == EMITTER_STATE_POSTSPAWN)\n        {\n            if (emitter->m_Particles.Empty())\n                SetEmitterState(instance, emitter, EMITTER_STATE_SLEEPING);\n        }\n    }\n\n    uint32_t GetEmitterVertexCount(HParticleContext context, HInstance instance, uint32_t emitter_index)\n    {\n        Instance* inst = GetInstance(context, instance);\n        Emitter* emitter = &inst->m_Emitters[emitter_index];\n        const uint32_t vertices_per_particle = 6;\n        uint32_t particle_count = emitter->m_Particles.Size();\n\n        return particle_count * vertices_per_particle;\n    }\n\n    static void SpawnParticle(dmArray<Particle>& particles, uint32_t* seed, dmParticleDDF::Emitter* ddf, const dmTransform::TransformS1& emitter_transform, Vector3 emitter_velocity, float emitter_properties[EMITTER_KEY_COUNT], float dt)\n    {\n        DM_PROFILE(Particle, \"Spawn\");\n\n        uint32_t particle_count = particles.Size();\n        particles.SetSize(particle_count + 1);\n        Particle *particle = &particles[particle_count];\n        memset(particle, 0, sizeof(Particle));\n\n        // TODO Handle birth-action\n\n        particle->SetMaxLifeTime(emitter_properties[EMITTER_KEY_PARTICLE_LIFE_TIME]);\n        particle->SetooMaxLifeTime(1.0f / particle->GetMaxLifeTime());\n        // Include dt since already existing particles have already been advanced\n        particle->SetTimeLeft(particle->GetMaxLifeTime() - dt);\n        particle->SetSpreadFactor(dmMath::Rand11(seed));\n        particle->SetSourceSize(emitter_properties[EMITTER_KEY_PARTICLE_SIZE] * emitter_transform.GetScale());\n        particle->SetSourceColor(Vector4(\n                emitter_properties[EMITTER_KEY_PARTICLE_RED],\n                emitter_properties[EMITTER_KEY_PARTICLE_GREEN],\n                emitter_properties[EMITTER_KEY_PARTICLE_BLUE],\n                emitter_properties[EMITTER_KEY_PARTICLE_ALPHA]));\n\n        dmTransform::TransformS1 transform;\n        transform.SetIdentity();\n        Vector3 dir(0.0f, 0.0f, 0.0f);\n\n        switch (ddf->m_Type)\n        {\n            case EMITTER_TYPE_SPHERE:\n            {\n                // Direction is sampled uniformly over the unit-sphere surface\n                // http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/\n                float z = dmMath::Rand11(seed);\n                float angle = 2.0f * ((float) M_PI) * dmMath::RandOpen01(seed);\n                float r = sqrtf(1.0f - z * z);\n                dir = Vector3(r * cosf(angle), r * sinf(angle), z);\n                // Pick radius to give uniform dist. over volume, surface area of sub-spheres grows quadratic wrt radius\n                float radius = sqrtf(dmMath::RandOpen01(seed));\n                radius *= 0.5f * emitter_properties[EMITTER_KEY_SIZE_X];\n                transform.SetTranslation(dir * radius);\n\n                break;\n            }\n\n            case EMITTER_TYPE_CIRCLE:\n            {\n                // Direction is sampled uniformly over the unit-sphere surface\n                // http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/\n                float angle = 2.0f * ((float) M_PI) * dmMath::RandOpen01(seed);\n                dir = Vector3(cosf(angle), sinf(angle), 0);\n                // Pick radius to give uniform dist. over volume, surface area of sub-spheres grows quadratic wrt radius\n                float radius = sqrtf(dmMath::RandOpen01(seed));\n                radius *= 0.5f * emitter_properties[EMITTER_KEY_SIZE_X];\n                transform.SetTranslation(dir * radius);\n\n                break;\n            }\n\n            case EMITTER_TYPE_CONE:\n            {\n                // Direction is sampled uniformly over the unit-circle (cone-top) surface\n                // http://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly\n                float angle = 2.0f * ((float) M_PI) * dmMath::RandOpen01(seed);\n                float u = dmMath::Rand01(seed) + dmMath::Rand01(seed);\n                float r = dmMath::Select(u - 1.0f, 2.0f - u, u);\n\n                // Pick height to give uniform dist. over volume, surface area of sub-circles grows quadratic wrt height\n                float h = sqrtf(dmMath::Rand01(seed));\n                float height = h * emitter_properties[EMITTER_KEY_SIZE_Y];\n                float radius = h * r * 0.5f * emitter_properties[EMITTER_KEY_SIZE_X];\n\n                Vector3 local_position(radius * cosf(angle), height, radius * sinf(angle));\n                transform.SetTranslation(local_position);\n\n                // Finally normalize dir\n                if (lengthSqr(local_position) != 0.0f)\n                    dir = normalize(local_position);\n                else\n                    dir = Vector3(0.0f, 1.0f, 0.0f);\n\n                break;\n            }\n\n            case EMITTER_TYPE_2DCONE:\n            {\n                float width = emitter_properties[EMITTER_KEY_SIZE_X];\n                float height = emitter_properties[EMITTER_KEY_SIZE_Y];\n\n                float u = dmMath::Rand01(seed);\n                float v = dmMath::Rand01(seed);\n\n                /*\n                 * Create samples in a parallelogram\n                 * See http://mathworld.wolfram.com/TrianglePointPicking.html\n                 * for more information\n                 * Effectively we get two triangles with total height 2 * height\n                 */\n\n                /*\n                 * The triangle is comprised of the vertices (0,0), v1 and v2\n                 *  p = (x, y) = v1 * u + v2 * v\n                 *\n                 *  p is a point in the parallelogram\n                 */\n                float x = -width * 0.5f * u + width * 0.5f * v;\n                float y = height * u + height * v;\n                // Mirror points outside triangle\n                y = dmMath::Select(height - y, y, 2 * height - y);\n\n                Vector3 local_position(x, y, 0.0f);\n                transform.SetTranslation(local_position);\n                if (lengthSqr(local_position) != 0.0f)\n                    dir = normalize(local_position);\n                else\n                    dir = Vector3(0.0f, 1.0f, 0.0f);\n\n                break;\n            }\n\n            case EMITTER_TYPE_BOX:\n            {\n                Vector3 p(dmMath::Rand11(seed), dmMath::Rand11(seed), dmMath::Rand11(seed));\n                while (lengthSqr(p) == 0.0f)\n                    p = Vector3(dmMath::Rand11(seed), dmMath::Rand11(seed), dmMath::Rand11(seed));\n                dir = Vector3::yAxis();\n\n                Vector3 extent(0.5f * emitter_properties[EMITTER_KEY_SIZE_X],\n                        0.5f * emitter_properties[EMITTER_KEY_SIZE_Y],\n                        0.5f * emitter_properties[EMITTER_KEY_SIZE_Z]);\n                transform.SetTranslation(mulPerElem(p, extent));\n\n                break;\n            }\n\n            default:\n                dmLogWarning(\"Unknown emitter type (%d), particle is spawned at emitter.\", ddf->m_Type);\n                transform.SetTranslation(Vector3(0.0f, 0.0f, 0.0f));\n                break;\n        }\n\n        Vector3 velocity = dir * emitter_properties[EMITTER_KEY_PARTICLE_SPEED];\n        Quat rotation;\n        switch (ddf->m_ParticleOrientation)\n        {\n        case PARTICLE_ORIENTATION_DEFAULT:\n        case PARTICLE_ORIENTATION_MOVEMENT_DIRECTION:\n        case PARTICLE_ORIENTATION_ANGULAR_VELOCITY:\n            // rotation is already identity\n            // or will be defined in simulation\n            break;\n        case PARTICLE_ORIENTATION_INITIAL_DIRECTION:\n            transform.SetRotation(Quat::rotation(Vector3::yAxis(), dir));\n            break;\n        }\n\n        transform = dmTransform::Mul(emitter_transform, transform);\n        particle->SetPosition(Point3(transform.GetTranslation()));\n        if (ddf->m_ParticleOrientation == PARTICLE_ORIENTATION_MOVEMENT_DIRECTION) {\n            particle->SetSourceRotation(dmVMath::QuatFromAngle(2, DEG_RAD * emitter_properties[EMITTER_KEY_PARTICLE_ROTATION]));\n        } else {\n            particle->SetSourceRotation(transform.GetRotation() * dmVMath::QuatFromAngle(2, DEG_RAD * emitter_properties[EMITTER_KEY_PARTICLE_ROTATION]));\n        }\n        particle->SetRotation(particle->GetSourceRotation());\n        particle->SetVelocity(dmTransform::Apply(emitter_transform, velocity) + emitter_velocity);\n        particle->m_SourceStretchFactorX = emitter_properties[EMITTER_KEY_PARTICLE_STRETCH_FACTOR_X];\n        particle->m_StretchFactorX = particle->m_SourceStretchFactorX;\n        particle->m_SourceStretchFactorY = emitter_properties[EMITTER_KEY_PARTICLE_STRETCH_FACTOR_Y];\n        particle->m_StretchFactorY = particle->m_SourceStretchFactorY;\n        particle->m_SourceAngularVelocity = emitter_properties[EMITTER_KEY_PARTICLE_ANGULAR_VELOCITY];\n    }\n\n    static float unit_tex_coords[] =\n    {\n            0.0f,1.0f, 0.0f,0.0f, 1.0f,0.0f, 1.0f,1.0f\n    };\n\n    static uint32_t UpdateRenderData(HParticleContext context, Instance* instance, Emitter* emitter, dmParticleDDF::Emitter* ddf, const Vector4& color, uint32_t vertex_index, void* vertex_buffer, uint32_t vertex_buffer_size, float dt, ParticleVertexFormat format)\n    {\n        DM_PROFILE(Particle, \"UpdateRenderData\");\n        static int tex_coord_order[] = {\n            0,1,2,2,3,0,\n            3,2,1,1,0,3,\t//h\n            1,0,3,3,2,1,\t//v\n            2,3,0,0,1,2\t\t//hv\n        };\n\n        uint32_t vertex_size = sizeof(Vertex);\n\n        if (format == PARTICLE_GUI)\n            vertex_size = sizeof(ParticleGuiVertex);\n\n        emitter->m_VertexIndex = vertex_index;\n        emitter->m_VertexCount = 0;\n\n        const AnimationData& anim_data = emitter->m_AnimationData;\n        // texture animation\n        uint32_t start_tile = anim_data.m_StartTile;\n        uint32_t end_tile = anim_data.m_EndTile;\n        uint32_t interval = end_tile - start_tile;\n        uint32_t tile_count = interval;\n        AnimPlayback playback = anim_data.m_Playback;\n        float* tex_coords = anim_data.m_TexCoords;\n        float* tex_dims = anim_data.m_TexDims;\n        bool hFlip = anim_data.m_HFlip != 0;\n        bool vFlip = anim_data.m_VFlip != 0;\n        bool anim_playing = playback != ANIM_PLAYBACK_NONE && tile_count > 1;\n        bool anim_auto_size = (ddf->m_SizeMode == SIZE_MODE_AUTO) && (anim_data.m_TexDims != 0x0) && anim_playing;\n        bool anim_once = playback == ANIM_PLAYBACK_ONCE_FORWARD || playback == ANIM_PLAYBACK_ONCE_BACKWARD || playback == ANIM_PLAYBACK_ONCE_PINGPONG;\n        bool anim_bwd = playback == ANIM_PLAYBACK_ONCE_BACKWARD || playback == ANIM_PLAYBACK_LOOP_BACKWARD;\n        bool anim_ping_pong = playback == ANIM_PLAYBACK_ONCE_PINGPONG || playback == ANIM_PLAYBACK_LOOP_PINGPONG;\n        if (anim_ping_pong) {\n            tile_count = dmMath::Max(1u, tile_count * 2 - 2);\n        }\n        float inv_anim_length = anim_data.m_FPS / (float)tile_count;\n        // Used to sample anim tiles in the \"frame center\"\n        float half_dt = dt * 0.5f;\n\n        if (tex_coords == 0x0)\n        {\n            tex_coords = unit_tex_coords;\n            start_tile = 0;\n            end_tile = 1;\n            tile_count = 1;\n        }\n\n        // calculate emission space\n        dmTransform::TransformS1 emission_transform;\n        dmTransform::Transform particle_transform;\n        emission_transform.SetIdentity();\n        if (ddf->m_Space == EMISSION_SPACE_EMITTER)\n        {\n            emission_transform = instance->m_WorldTransform;\n        }\n\n        uint32_t max_vertex_count = vertex_buffer_size / vertex_size;\n        uint32_t particle_count = emitter->m_Particles.Size();\n        uint32_t j;\n\n        float width_factor = 1.0f;\n        float height_factor = 1.0f;\n        if(!anim_auto_size)\n        {\n            if (anim_data.m_TileWidth > anim_data.m_TileHeight)\n            {\n                height_factor = anim_data.m_TileHeight / (float)anim_data.m_TileWidth;\n            }\n            else if (anim_data.m_TileHeight > 0)\n            {\n                width_factor = anim_data.m_TileWidth / (float)anim_data.m_TileHeight;\n            }\n            // Extent for each vertex, scale by half\n            width_factor *= 0.5f;\n            height_factor *= 0.5f;\n        }\n\n        for (j = 0; j < particle_count && vertex_index + 6 <= max_vertex_count; j++)\n        {\n            Particle* particle = &emitter->m_Particles[j];\n            // Evaluate anim frame\n            uint32_t tile = 0;\n            Vector3 size;\n            if (anim_playing)\n            {\n                float anim_cursor = particle->GetMaxLifeTime() - particle->GetTimeLeft() - half_dt;\n                float anim_t = 0.0f;\n                if (anim_once) // stretch over particle life\n                {\n                    anim_t = anim_cursor * particle->GetooMaxLifeTime();\n                }\n                else // use anim FPS\n                {\n                    anim_t = anim_cursor * inv_anim_length;\n                }\n                tile = (uint32_t)(tile_count * anim_t);\n                tile = tile % tile_count;\n                if (tile >= interval) {\n                    tile = (interval-1) * 2 - tile;\n                }\n                if (anim_bwd)\n                    tile = tile_count - tile - 1;\n\n                size = particle->GetScale();\n                if(anim_auto_size)\n                {\n                    const float* td = &tex_dims[(start_tile + tile) << 1];\n                    width_factor = td[0] * 0.5;\n                    height_factor = td[1] * 0.5;\n                }\n                else\n                {\n                    size *= particle->GetSourceSize();\n                }\n            }\n            else\n            {\n                size = particle->GetScale() * particle->GetSourceSize();\n            }\n            tile += start_tile;\n            float* tex_coord = &tex_coords[tile << 3];\n\n            particle_transform.SetTranslation(Vector3(particle->GetPosition()));\n            particle_transform.SetRotation(particle->GetRotation());\n            particle_transform.SetScale(size);\n            particle_transform.SetRotation(emission_transform.GetRotation() * particle_transform.GetRotation());\n            particle_transform.SetTranslation(Vector3(Apply(emission_transform, Point3(particle_transform.GetTranslation()))));\n            particle_transform.SetScale(emission_transform.GetScale() * particle_transform.GetScale());\n\n            Vector3 x = dmTransform::Apply(particle_transform, Vector3(width_factor, 0.0f, 0.0f));\n            Vector3 y = dmTransform::Apply(particle_transform, Vector3(0.0f, height_factor, 0.0f));\n\n            Vector3 p0 = -x - y + particle_transform.GetTranslation();\n            Vector3 p1 = -x + y + particle_transform.GetTranslation();\n            Vector3 p2 = x - y + particle_transform.GetTranslation();\n            Vector3 p3 = x + y + particle_transform.GetTranslation();\n\n            uint32_t flip_flag = 0;\n            if (hFlip)\n            {\n                flip_flag = 1;\n            }\n            if (vFlip)\n            {\n                flip_flag |= 2;\n            }\n            const int* tex_lookup = &tex_coord_order[flip_flag * 6];\n\n            Vector4 c = particle->GetColor();\n            c = Vector4(mulPerElem(c.getXYZ(), color.getXYZ()), c.getW() * color.getW());\n\n            if (format == PARTICLE_GO)\n            {\n                Vertex* vertex = &((Vertex*)vertex_buffer)[vertex_index];\n\n#define SET_VERTEX_GO(vertex, p, c, u, v)\\\n    vertex->m_X = p.getX();\\\n    vertex->m_Y = p.getY();\\\n    vertex->m_Z = p.getZ();\\\n    vertex->m_Red = c.getX();\\\n    vertex->m_Green = c.getY();\\\n    vertex->m_Blue = c.getZ();\\\n    vertex->m_Alpha = c.getW();\\\n    vertex->m_U = u;\\\n    vertex->m_V = v;\n\n                SET_VERTEX_GO(vertex, p0, c, tex_coord[tex_lookup[0] * 2], tex_coord[tex_lookup[0] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GO(vertex, p1, c, tex_coord[tex_lookup[1] * 2], tex_coord[tex_lookup[1] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GO(vertex, p3, c, tex_coord[tex_lookup[2] * 2], tex_coord[tex_lookup[2] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GO(vertex, p3, c, tex_coord[tex_lookup[3] * 2], tex_coord[tex_lookup[3] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GO(vertex, p2, c, tex_coord[tex_lookup[4] * 2], tex_coord[tex_lookup[4] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GO(vertex, p0, c, tex_coord[tex_lookup[5] * 2], tex_coord[tex_lookup[5] * 2 + 1])\n\n#undef SET_VERTEX_GO\n            }\n            else if (format == PARTICLE_GUI)\n            {\n                ParticleGuiVertex* vertex = &((ParticleGuiVertex*)vertex_buffer)[vertex_index];\n\n#define SET_VERTEX_GUI(vertex, p, c, u, v)\\\n    vertex->m_Position[0] = p.getX();\\\n    vertex->m_Position[1] = p.getY();\\\n    vertex->m_Position[2] = p.getZ();\\\n    vertex->m_Color[0] = c.getX(); \\\n    vertex->m_Color[1] = c.getY(); \\\n    vertex->m_Color[2] = c.getZ(); \\\n    vertex->m_Color[3] = c.getW(); \\\n    vertex->m_UV[0] = u;\\\n    vertex->m_UV[1] = v;\n\n                SET_VERTEX_GUI(vertex, p0, c, tex_coord[tex_lookup[0] * 2], tex_coord[tex_lookup[0] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GUI(vertex, p1, c, tex_coord[tex_lookup[1] * 2], tex_coord[tex_lookup[1] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GUI(vertex, p3, c, tex_coord[tex_lookup[2] * 2], tex_coord[tex_lookup[2] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GUI(vertex, p3, c, tex_coord[tex_lookup[3] * 2], tex_coord[tex_lookup[3] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GUI(vertex, p2, c, tex_coord[tex_lookup[4] * 2], tex_coord[tex_lookup[4] * 2 + 1])\n                ++vertex;\n                SET_VERTEX_GUI(vertex, p0, c, tex_coord[tex_lookup[5] * 2], tex_coord[tex_lookup[5] * 2 + 1])\n#undef SET_VERTEX_GUI\n            }\n\n            vertex_index += 6;\n        }\n        if (j < particle_count)\n        {\n            if (emitter->m_RenderWarning == 0)\n            {\n                const char* config_key = MAX_PARTICLE_COUNT_KEY;\n\n                if (format == PARTICLE_GUI)\n                    config_key = \"gui.max_particle_count\";\n\n                dmLogWarning(\"Maximum number of particles (%d) exceeded, particles will not be rendered. Change \\\"%s\\\" in the config file.\", context->m_MaxParticleCount, config_key);\n                emitter->m_RenderWarning = 1;\n            }\n        }\n        emitter->m_VertexCount = vertex_index - emitter->m_VertexIndex;\n        return emitter->m_VertexCount;\n    }\n\n    struct SortPred\n    {\n        inline bool operator () (const Particle& p1, const Particle& p2)\n        {\n            return p1.GetSortKey().m_Key < p2.GetSortKey().m_Key;\n        }\n\n    };\n\n    void GenerateKeys(Emitter* emitter, float max_particle_life_time)\n    {\n        dmArray<Particle>& particles = emitter->m_Particles;\n        uint32_t n = particles.Size();\n\n        float range = 1.0f / max_particle_life_time;\n\n        Particle* first = particles.Begin();\n        for (uint32_t i = 0; i < n; ++i)\n        {\n            Particle* p = &particles[i];\n            uint32_t index = p - first;\n\n            float life_time = (1.0f - p->GetTimeLeft() * range) * 65535;\n            life_time = dmMath::Clamp(life_time, 0.0f, 65535.0f);\n            uint16_t lt = (uint16_t) life_time;\n            SortKey key;\n            key.m_LifeTime = lt;\n            key.m_Index = index;\n            p->SetSortKey(key);\n        }\n    }\n\n    void SortParticles(Emitter* emitter)\n    {\n        DM_PROFILE(Particle, \"Sort\");\n\n        std::sort(emitter->m_Particles.Begin(), emitter->m_Particles.End(), SortPred());\n    }\n\n#define SAMPLE_PROP(segment, x, target)\\\n    {\\\n        const LinearSegment* s = &segment;\\\n        target = (x - s->m_X) * s->m_K + s->m_Y;\\\n    }\\\n\n    void EvaluateEmitterProperties(Emitter* emitter, Property* emitter_properties, float duration, float properties[EMITTER_KEY_COUNT])\n    {\n        float x = dmMath::Select(-duration, 0.0f, emitter->m_Timer / duration);\n        uint32_t segment_index = dmMath::Min((uint32_t)(x * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n        for (uint32_t i = 0; i < EMITTER_KEY_COUNT; ++i)\n        {\n            SAMPLE_PROP(emitter_properties[i].m_Segments[segment_index], x, properties[i])\n        }\n    }\n\n    void EvaluateParticleProperties(Emitter* emitter, Property* particle_properties, dmParticleDDF::Emitter* emitter_ddf, float dt)\n    {\n        float properties[PARTICLE_KEY_COUNT];\n        // TODO Optimize this\n        dmArray<Particle>& particles = emitter->m_Particles;\n        uint32_t count = particles.Size();\n        for (uint32_t i = 0; i < count; ++i)\n        {\n            Particle* particle = &particles[i];\n            float x = dmMath::Select(-particle->GetMaxLifeTime(), 0.0f, 1.0f - particle->GetTimeLeft() * particle->GetooMaxLifeTime());\n            uint32_t segment_index = dmMath::Min((uint32_t)(x * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n\n            SAMPLE_PROP(particle_properties[PARTICLE_KEY_SCALE].m_Segments[segment_index], x, properties[PARTICLE_KEY_SCALE])\n            SAMPLE_PROP(particle_properties[PARTICLE_KEY_RED].m_Segments[segment_index], x, properties[PARTICLE_KEY_RED])\n            SAMPLE_PROP(particle_properties[PARTICLE_KEY_GREEN].m_Segments[segment_index], x, properties[PARTICLE_KEY_GREEN])\n            SAMPLE_PROP(particle_properties[PARTICLE_KEY_BLUE].m_Segments[segment_index], x, properties[PARTICLE_KEY_BLUE])\n            SAMPLE_PROP(particle_properties[PARTICLE_KEY_ALPHA].m_Segments[segment_index], x, properties[PARTICLE_KEY_ALPHA])\n            SAMPLE_PROP(particle_properties[PARTICLE_KEY_STRETCH_FACTOR_X].m_Segments[segment_index], x, properties[PARTICLE_KEY_STRETCH_FACTOR_X])\n            SAMPLE_PROP(particle_properties[PARTICLE_KEY_STRETCH_FACTOR_Y].m_Segments[segment_index], x, properties[PARTICLE_KEY_STRETCH_FACTOR_Y])\n            Vector4 c = particle->GetSourceColor();\n            particle->SetScale(Vector3(properties[PARTICLE_KEY_SCALE]));\n            particle->SetColor(Vector4(dmMath::Clamp(c.getX() * properties[PARTICLE_KEY_RED], 0.0f, 1.0f),\n                    dmMath::Clamp(c.getY() * properties[PARTICLE_KEY_GREEN], 0.0f, 1.0f),\n                    dmMath::Clamp(c.getZ() * properties[PARTICLE_KEY_BLUE], 0.0f, 1.0f),\n                    dmMath::Clamp(c.getW() * properties[PARTICLE_KEY_ALPHA], 0.0f, 1.0f)));\n            particle->m_StretchFactorX = particle->m_SourceStretchFactorX + (properties[PARTICLE_KEY_STRETCH_FACTOR_X]);\n            particle->m_StretchFactorY = particle->m_SourceStretchFactorY + (properties[PARTICLE_KEY_STRETCH_FACTOR_Y]);\n        }\n\n        if (emitter_ddf->m_ParticleOrientation == PARTICLE_ORIENTATION_MOVEMENT_DIRECTION) {\n            for (uint32_t i = 0; i < count; ++i)\n            {\n                Particle* particle = &particles[i];\n                float x = dmMath::Select(-particle->GetMaxLifeTime(), 0.0f, 1.0f - particle->GetTimeLeft() * particle->GetooMaxLifeTime());\n                uint32_t segment_index = dmMath::Min((uint32_t)(x * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n                SAMPLE_PROP(particle_properties[PARTICLE_KEY_ROTATION].m_Segments[segment_index], x, properties[PARTICLE_KEY_ROTATION])\n                particle->SetRotation(particle->GetSourceRotation() * dmVMath::QuatFromAngle(2, DEG_RAD * properties[PARTICLE_KEY_ROTATION]));\n                if (lengthSqr(particle->m_Velocity) > EPSILON)\n                {\n                    Vector3 vel_norm = normalize(particle->m_Velocity);\n                    float y_dot = dot(Vector3::yAxis(), vel_norm);\n                    // Corner case, https://gamedev.stackexchange.com/questions/61672/align-a-rotation-to-a-direction\n                    Quat q_vel = (dmMath::Abs(y_dot + 1.0f) > EPSILON) ? Quat::rotation(Vector3::yAxis(), vel_norm) : Quat(0.0, 0.0, 1.0, 0.0);\n                    Quat q = particle->GetRotation() * q_vel;\n                    particle->SetRotation(q);\n                }\n            }\n\n        } else if (emitter_ddf->m_ParticleOrientation == PARTICLE_ORIENTATION_ANGULAR_VELOCITY) {\n            for (uint32_t i = 0; i < count; ++i)\n            {\n                Particle* particle = &particles[i];\n                float x = dmMath::Select(-particle->GetMaxLifeTime(), 0.0f, 1.0f - particle->GetTimeLeft() * particle->GetooMaxLifeTime());\n                uint32_t segment_index = dmMath::Min((uint32_t)(x * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n                SAMPLE_PROP(particle_properties[PARTICLE_KEY_ANGULAR_VELOCITY].m_Segments[segment_index], x, properties[PARTICLE_KEY_ANGULAR_VELOCITY])\n                particle->SetRotation(particle->GetRotation() * Quat::rotationZ(DEG_RAD * (particle->m_SourceAngularVelocity * (properties[PARTICLE_KEY_ANGULAR_VELOCITY])) * dt));\n            }\n\n        } else {\n            for (uint32_t i = 0; i < count; ++i)\n            {\n                Particle* particle = &particles[i];\n                float x = dmMath::Select(-particle->GetMaxLifeTime(), 0.0f, 1.0f - particle->GetTimeLeft() * particle->GetooMaxLifeTime());\n                uint32_t segment_index = dmMath::Min((uint32_t)(x * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n                SAMPLE_PROP(particle_properties[PARTICLE_KEY_ROTATION].m_Segments[segment_index], x, properties[PARTICLE_KEY_ROTATION])\n                particle->SetRotation(particle->GetSourceRotation() * dmVMath::QuatFromAngle(2, DEG_RAD * properties[PARTICLE_KEY_ROTATION]));\n            }\n        }\n\n    }\n\n    void ApplyAcceleration(dmArray<Particle>& particles, Property* modifier_properties, const Quat& rotation, float scale, float emitter_t, float dt)\n    {\n        uint32_t particle_count = particles.Size();\n        Vector3 acc_step = rotate(rotation, ACCELERATION_LOCAL_DIR) * dt * scale;\n        const Property& magnitude_property = modifier_properties[MODIFIER_KEY_MAGNITUDE];\n        uint32_t segment_index = dmMath::Min((uint32_t)(emitter_t * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n        float magnitude;\n        SAMPLE_PROP(magnitude_property.m_Segments[segment_index], emitter_t, magnitude)\n        float mag_spread = magnitude_property.m_Spread;\n        for (uint32_t i = 0; i < particle_count; ++i)\n        {\n            Particle* particle = &particles[i];\n            particle->SetVelocity(particle->GetVelocity() + acc_step * (magnitude + mag_spread * particle->GetSpreadFactor()));\n        }\n    }\n\n    void ApplyDrag(dmArray<Particle>& particles, Property* modifier_properties, dmParticleDDF::Modifier* modifier_ddf, const Quat& rotation, float emitter_t, float dt)\n    {\n        uint32_t particle_count = particles.Size();\n        Vector3 direction = rotate(rotation, DRAG_LOCAL_DIR);\n        const Property& magnitude_property = modifier_properties[MODIFIER_KEY_MAGNITUDE];\n        uint32_t segment_index = dmMath::Min((uint32_t)(emitter_t * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n        float magnitude;\n        SAMPLE_PROP(magnitude_property.m_Segments[segment_index], emitter_t, magnitude)\n        float mag_spread = magnitude_property.m_Spread;\n        for (uint32_t i = 0; i < particle_count; ++i)\n        {\n            Particle* particle = &particles[i];\n            Vector3 v = particle->GetVelocity();\n            if (modifier_ddf->m_UseDirection)\n                v = projection(Point3(particle->GetVelocity()), direction) * direction;\n            // Applied drag > 1 means the particle would travel in the reverse direction\n            float applied_drag = dmMath::Min((magnitude + mag_spread * particle->GetSpreadFactor()) * dt, 1.0f);\n            particle->SetVelocity(particle->GetVelocity() - v * applied_drag);\n        }\n    }\n\n    static Vector3 GetParticleDir(Particle* particle)\n    {\n        return rotate(particle->GetRotation(), PARTICLE_LOCAL_BASE_DIR);\n    }\n\n    static Vector3 NonZeroVector3(Vector3 v, float sq_length, Vector3 fallback)\n    {\n        Vector3 result;\n        float neg_sq_length = -sq_length;\n        result.setX(dmMath::Select(neg_sq_length, fallback.getX(), v.getX()));\n        result.setY(dmMath::Select(neg_sq_length, fallback.getY(), v.getY()));\n        result.setZ(dmMath::Select(neg_sq_length, fallback.getZ(), v.getZ()));\n        return result;\n    }\n\n    void ApplyRadial(dmArray<Particle>& particles, Property* modifier_properties, const Point3& position, float scale, float emitter_t, float dt)\n    {\n        uint32_t particle_count = particles.Size();\n        const Property& magnitude_property = modifier_properties[MODIFIER_KEY_MAGNITUDE];\n        const Property& max_distance_property = modifier_properties[MODIFIER_KEY_MAX_DISTANCE];\n        uint32_t segment_index = dmMath::Min((uint32_t)(emitter_t * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n        float magnitude;\n        SAMPLE_PROP(magnitude_property.m_Segments[segment_index], emitter_t, magnitude)\n        float mag_spread = magnitude_property.m_Spread;\n        // We temporarily only sample the first frame until we have decided what to animate over\n        float max_distance = max_distance_property.m_Segments[0].m_Y * scale;\n        float max_sq_distance = max_distance * max_distance;\n        float applied_factor = dt * scale;\n        for (uint32_t i = 0; i < particle_count; ++i)\n        {\n            Particle* particle = &particles[i];\n            Vector3 delta = particle->GetPosition() - position;\n            float delta_sq_len = lengthSqr(delta);\n            float applied_magnitude = magnitude + mag_spread * particle->GetSpreadFactor();\n            // 0 acc delta lies outside max dist\n            float a = dmMath::Select(max_sq_distance - delta_sq_len, applied_magnitude, 0.0f);\n            Vector3 dir = normalize(NonZeroVector3(delta, delta_sq_len, GetParticleDir(particle)));\n            particle->SetVelocity(particle->GetVelocity() + dir * a * applied_factor);\n        }\n    }\n\n    void ApplyVortex(dmArray<Particle>& particles, Property* modifier_properties, const Point3& position, const Quat& rotation, float scale, float emitter_t, float dt)\n    {\n        uint32_t particle_count = particles.Size();\n        const Property& magnitude_property = modifier_properties[MODIFIER_KEY_MAGNITUDE];\n        const Property& max_distance_property = modifier_properties[MODIFIER_KEY_MAX_DISTANCE];\n        uint32_t segment_index = dmMath::Min((uint32_t)(emitter_t * PROPERTY_SAMPLE_COUNT), PROPERTY_SAMPLE_COUNT - 1);\n        float magnitude;\n        SAMPLE_PROP(magnitude_property.m_Segments[segment_index], emitter_t, magnitude)\n        float mag_spread = magnitude_property.m_Spread;\n        // We temporarily only sample the first frame until we have decided what to animate over\n        float max_distance = max_distance_property.m_Segments[0].m_Y * scale;\n        float max_sq_distance = max_distance * max_distance;\n        Vector3 axis = rotate(rotation, VORTEX_LOCAL_AXIS);\n        Vector3 start = rotate(rotation, VORTEX_LOCAL_START_DIR);\n        float applied_factor = dt * scale;\n        for (uint32_t i = 0; i < particle_count; ++i)\n        {\n            Particle* particle = &particles[i];\n            // delta from vortex position\n            Vector3 delta = particle->GetPosition() - position;\n            // normal from vortex axis (non-unit)\n            Vector3 normal = delta - projection(Point3(delta), axis) * axis;\n            // tangent is the direction of the vortex acceleration\n            Vector3 tangent = cross(axis, normal);\n            // In case the particle is directed along the axis, give it a guaranteed orthogonal start\n            tangent = NonZeroVector3(tangent, lengthSqr(tangent), start);\n            // tangent is now guaranteed to be non-zero\n            tangent = normalize(tangent);\n            // use normal for max distance test\n            float normal_sq_len = lengthSqr(normal);\n            float acceleration = dmMath::Select(max_sq_distance - normal_sq_len, magnitude + mag_spread * particle->GetSpreadFactor(), 0.0f);\n            particle->SetVelocity(particle->GetVelocity() + tangent * acceleration * applied_factor);\n        }\n    }\n\n#undef SAMPLE_PROP\n\n    static Point3 CalculateModifierPosition(Instance* instance, dmParticleDDF::Emitter* emitter_ddf, dmParticleDDF::Modifier* modifier_ddf)\n    {\n        Point3 position(modifier_ddf->m_Position);\n        position = emitter_ddf->m_Position + rotate(emitter_ddf->m_Rotation, Vector3(position));\n        if (emitter_ddf->m_Space == EMISSION_SPACE_WORLD)\n        {\n            if (instance->m_ScaleAlongZ)\n                position = dmTransform::Apply(instance->m_WorldTransform, position);\n            else\n                position = dmTransform::ApplyNoScaleZ(instance->m_WorldTransform, position);\n        }\n        return Point3(position);\n    }\n\n    static Quat CalculateModifierRotation(Instance* instance, dmParticleDDF::Emitter* emitter_ddf, dmParticleDDF::Modifier* modifier_ddf)\n    {\n        return emitter_ddf->m_Rotation * modifier_ddf->m_Rotation;\n    }\n\n    void Simulate(Instance* instance, Emitter* emitter, EmitterPrototype* prototype, dmParticleDDF::Emitter* ddf, float dt)\n    {\n        DM_PROFILE(Particle, \"Simulate\");\n\n        dmArray<Particle>& particles = emitter->m_Particles;\n        EvaluateParticleProperties(emitter, prototype->m_ParticleProperties, ddf, dt);\n        float emitter_t = dmMath::Select(-ddf->m_Duration, 0.0f, emitter->m_Timer / ddf->m_Duration);\n        float scale = 1.0f;\n        if (ddf->m_Space == EMISSION_SPACE_WORLD)\n            scale = instance->m_WorldTransform.GetScale();\n        // Apply modifiers\n        uint32_t modifier_count = prototype->m_Modifiers.Size();\n        for (uint32_t i = 0; i < modifier_count; ++i)\n        {\n            ModifierPrototype* modifier = &prototype->m_Modifiers[i];\n            dmParticleDDF::Modifier* modifier_ddf = &ddf->m_Modifiers[i];\n            switch (modifier_ddf->m_Type)\n            {\n            case dmParticleDDF::MODIFIER_TYPE_ACCELERATION:\n                {\n                    Quat rotation = CalculateModifierRotation(instance, ddf, modifier_ddf);\n                    ApplyAcceleration(particles, modifier->m_Properties, rotation, scale, emitter_t, dt);\n                }\n                break;\n            case dmParticleDDF::MODIFIER_TYPE_DRAG:\n                {\n                    Quat rotation = CalculateModifierRotation(instance, ddf, modifier_ddf);\n                    ApplyDrag(particles, modifier->m_Properties, modifier_ddf, rotation, emitter_t, dt);\n                }\n                break;\n            case dmParticleDDF::MODIFIER_TYPE_RADIAL:\n                {\n                    Point3 position = CalculateModifierPosition(instance, ddf, modifier_ddf);\n                    ApplyRadial(particles, modifier->m_Properties, position, scale, emitter_t, dt);\n                }\n                break;\n            case dmParticleDDF::MODIFIER_TYPE_VORTEX:\n                {\n                    Point3 position = CalculateModifierPosition(instance, ddf, modifier_ddf);\n                    Quat rotation = CalculateModifierRotation(instance, ddf, modifier_ddf);\n                    ApplyVortex(particles, modifier->m_Properties, position, rotation, scale, emitter_t, dt);\n                }\n                break;\n            }\n        }\n        uint32_t particle_count = particles.Size();\n        for (uint32_t i = 0; i < particle_count; ++i)\n        {\n            Particle* p = &particles[i];\n            // NOTE This velocity integration has a larger error than normal since we don't use the velocity at the\n            // beginning of the frame, but it's ok since particle movement does not need to be very exact\n            p->SetPosition(p->GetPosition() + p->m_Velocity * dt);\n\n            p->m_Scale[0] += p->m_Scale[0] * p->m_StretchFactorX;\n            if (!ddf->m_StretchWithVelocity)\n                p->m_Scale[1] += p->m_Scale[1] * p->m_StretchFactorY;\n            else\n                p->m_Scale[1] += p->m_Scale[1] * p->m_StretchFactorY * length(p->m_Velocity) * STRETCH_SCALING;\n        }\n    }\n\n    void DebugRender(HParticleContext context, void* user_context, RenderLineCallback render_line_callback)\n    {\n        uint32_t instance_count = context->m_Instances.Size();\n        for (uint32_t i = 0; i < instance_count; ++i)\n        {\n            Instance* instance = context->m_Instances[i];\n            if (instance == 0x0) continue;\n            Prototype* prototype = instance->m_Prototype;\n\n            uint32_t emitter_count = instance->m_Emitters.Size();\n            for (uint32_t j = 0; j < emitter_count; j++)\n            {\n                Emitter* e = &instance->m_Emitters[j];\n\n                dmParticleDDF::Emitter* ddf = &prototype->m_DDF->m_Emitters[j];\n                Vectormath::Aos::Vector4 color(0.0f, 1.0f, 0.0f, 1.0f);\n                if (IsSleeping(e))\n                {\n                    color.setY(0.0f);\n                    color.setZ(1.0f);\n                }\n                else if (!IsEmitterLooping(e, ddf))\n                {\n                    float t = dmMath::Select(-ddf->m_Duration, 0.0f, e->m_Timer / ddf->m_Duration);\n                    color.setY(1.0f - t);\n                    color.setZ(t);\n                }\n                dmTransform::TransformS1 transform(Vector3(ddf->m_Position), ddf->m_Rotation, 1.0f);\n                if (instance->m_ScaleAlongZ)\n                    transform = dmTransform::Mul(instance->m_WorldTransform, transform);\n                else\n                    transform = dmTransform::MulNoScaleZ(instance->m_WorldTransform, transform);\n\n                switch (ddf->m_Type)\n                {\n                case EMITTER_TYPE_SPHERE:\n                {\n                    const float radius = 0.5f * ddf->m_Properties[EMITTER_KEY_SIZE_X].m_Points[0].m_Y;\n\n                    const uint32_t segment_count = 16;\n                    Point3 vertices[segment_count + 1][3];\n                    for (uint32_t j = 0; j < segment_count + 1; ++j)\n                    {\n                        float angle = 2.0f * ((float) M_PI) * j / segment_count;\n                        vertices[j][0] = Point3(radius * cos(angle), radius * sin(angle), 0.0f);\n                        vertices[j][1] = Point3(0.0f, radius * cos(angle), radius * sin(angle));\n                        vertices[j][2] = Point3(radius * cos(angle), 0.0f, radius * sin(angle));\n                    }\n                    for (uint32_t j = 1; j < segment_count + 1; ++j)\n                    {\n                        for (uint32_t k = 0; k < 3; ++k)\n                            render_line_callback(user_context, dmTransform::Apply(transform, vertices[j-1][k]), dmTransform::Apply(transform, vertices[j][k]), color);\n                    }\n                    break;\n                }\n                case EMITTER_TYPE_CONE:\n                {\n                    const float radius = 0.5f * ddf->m_Properties[EMITTER_KEY_SIZE_X].m_Points[0].m_Y;\n                    const float height = ddf->m_Properties[EMITTER_KEY_SIZE_Y].m_Points[0].m_Y;\n\n                    // 4 pillars\n                    render_line_callback(user_context, Point3(transform.GetTranslation()), dmTransform::Apply(transform, Point3(radius, 0.0f, height)), color);\n                    render_line_callback(user_context, Point3(transform.GetTranslation()), dmTransform::Apply(transform, Point3(-radius, 0.0f, height)), color);\n                    render_line_callback(user_context, Point3(transform.GetTranslation()), dmTransform::Apply(transform, Point3(0.0f, radius, height)), color);\n                    render_line_callback(user_context, Point3(transform.GetTranslation()), dmTransform::Apply(transform, Point3(0.0f, -radius, height)), color);\n                    // circle\n                    const uint32_t segment_count = 16;\n                    Point3 vertices[segment_count];\n                    for (uint32_t j = 0; j < segment_count; ++j)\n                    {\n                        float angle = 2.0f * ((float) M_PI) * j / segment_count;\n                        vertices[j] = Point3(radius * cos(angle), radius * sin(angle), height);\n                    }\n                    for (uint32_t j = 1; j < segment_count; ++j)\n                    {\n                        render_line_callback(user_context, dmTransform::Apply(transform, vertices[j-1]), dmTransform::Apply(transform, vertices[j]), color);\n                    }\n                    render_line_callback(user_context, dmTransform::Apply(transform, vertices[segment_count - 1]), dmTransform::Apply(transform, vertices[0]), color);\n                    break;\n                }\n                case EMITTER_TYPE_BOX:\n                {\n                    const float x_ext = 0.5f * ddf->m_Properties[EMITTER_KEY_SIZE_X].m_Points[0].m_Y;\n                    const float y_ext = 0.5f * ddf->m_Properties[EMITTER_KEY_SIZE_Y].m_Points[0].m_Y;\n                    const float z_ext = 0.5f * ddf->m_Properties[EMITTER_KEY_SIZE_Z].m_Points[0].m_Y;\n\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(-x_ext, -y_ext, -z_ext)), dmTransform::Apply(transform, Point3(x_ext, -y_ext, -z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(x_ext, -y_ext, -z_ext)), dmTransform::Apply(transform, Point3(x_ext, y_ext, -z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(x_ext, y_ext, -z_ext)), dmTransform::Apply(transform, Point3(-x_ext, y_ext, -z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(-x_ext, y_ext, -z_ext)), dmTransform::Apply(transform, Point3(-x_ext, -y_ext, -z_ext)), color);\n\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(-x_ext, -y_ext, z_ext)), dmTransform::Apply(transform, Point3(x_ext, -y_ext, z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(x_ext, -y_ext, z_ext)), dmTransform::Apply(transform, Point3(x_ext, y_ext, z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(x_ext, y_ext, z_ext)), dmTransform::Apply(transform, Point3(-x_ext, y_ext, z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(-x_ext, y_ext, z_ext)), dmTransform::Apply(transform, Point3(-x_ext, -y_ext, z_ext)), color);\n\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(-x_ext, -y_ext, -z_ext)), dmTransform::Apply(transform, Point3(-x_ext, -y_ext, z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(x_ext, -y_ext, -z_ext)), dmTransform::Apply(transform, Point3(x_ext, -y_ext, z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(x_ext, y_ext, -z_ext)), dmTransform::Apply(transform, Point3(x_ext, y_ext, z_ext)), color);\n                    render_line_callback(user_context, dmTransform::Apply(transform, Point3(-x_ext, y_ext, -z_ext)), dmTransform::Apply(transform, Point3(-x_ext, y_ext, z_ext)), color);\n\n                    break;\n                }\n\n                    default:\n                        break;\n                }\n            }\n        }\n    }\n\n    void LoadResources(Prototype* prototype, dmParticleDDF::ParticleFX* ddf)\n    {\n        uint32_t emitter_count = ddf->m_Emitters.m_Count;\n        if (prototype->m_DDF != 0x0)\n        {\n            dmDDF::FreeMessage(prototype->m_DDF);\n        }\n        prototype->m_DDF = ddf;\n        prototype->m_Emitters.SetCapacity(emitter_count);\n        prototype->m_Emitters.SetSize(emitter_count);\n\n        memset(prototype->m_Emitters.Begin(), 0, emitter_count * sizeof(EmitterPrototype));\n        for (uint32_t i = 0; i < emitter_count; ++i)\n        {\n            dmParticleDDF::Emitter* emitter_ddf = &ddf->m_Emitters[i];\n            // Add-alpha is deprecated because of premultiplied alpha and replaced by Add\n            if (emitter_ddf->m_BlendMode == dmParticleDDF::BLEND_MODE_ADD_ALPHA)\n                emitter_ddf->m_BlendMode = dmParticleDDF::BLEND_MODE_ADD;\n            EmitterPrototype* emitter = &prototype->m_Emitters[i];\n            emitter->m_Animation = dmHashString64(emitter_ddf->m_Animation);\n            emitter->m_BlendMode = emitter_ddf->m_BlendMode;\n            // Approximate splines with linear segments\n            memset(emitter->m_Properties, 0, sizeof(emitter->m_Properties));\n            memset(emitter->m_ParticleProperties, 0, sizeof(emitter->m_ParticleProperties));\n            uint32_t prop_count = emitter_ddf->m_Properties.m_Count;\n            for (uint32_t j = 0; j < prop_count; ++j)\n            {\n                const dmParticleDDF::Emitter::Property& p = emitter_ddf->m_Properties[j];\n                if (p.m_Key < dmParticleDDF::EMITTER_KEY_COUNT)\n                {\n                    Property& property = emitter->m_Properties[p.m_Key];\n                    SampleProperty(p.m_Points.m_Data, p.m_Points.m_Count, property.m_Segments);\n                    property.m_Spread = p.m_Spread;\n                }\n                else\n                {\n                    dmLogWarning(\"The key %d is not a valid emitter key.\", p.m_Key);\n                }\n            }\n            // Calculate max life time\n            const Property& life_time = emitter->m_Properties[dmParticleDDF::EMITTER_KEY_PARTICLE_LIFE_TIME];\n            float max_life_time = 0.0f;\n            for (uint32_t j = 0; j < PROPERTY_SAMPLE_COUNT; ++j)\n            {\n                const LinearSegment& s = life_time.m_Segments[j];\n                max_life_time = dmMath::Max(dmMath::Select(s.m_K, s.m_Y + s.m_K, s.m_Y), max_life_time);\n            }\n            emitter->m_MaxParticleLifeTime = max_life_time;\n            // particle properties\n            prop_count = emitter_ddf->m_ParticleProperties.m_Count;\n            for (uint32_t i = 0; i < prop_count; ++i)\n            {\n                const dmParticleDDF::Emitter::ParticleProperty& p = emitter_ddf->m_ParticleProperties[i];\n                if (p.m_Key < dmParticleDDF::PARTICLE_KEY_COUNT)\n                {\n                    SampleProperty(p.m_Points.m_Data, p.m_Points.m_Count, emitter->m_ParticleProperties[p.m_Key].m_Segments);\n                }\n                else\n                {\n                    dmLogWarning(\"The key %d is not a valid particle key.\", p.m_Key);\n                }\n            }\n            uint32_t modifier_count = emitter_ddf->m_Modifiers.m_Count;\n            emitter->m_Modifiers.SetCapacity(modifier_count);\n            emitter->m_Modifiers.SetSize(modifier_count);\n            memset(emitter->m_Modifiers.Begin(), 0, modifier_count * sizeof(ModifierPrototype));\n            for (uint32_t i = 0; i < modifier_count; ++i)\n            {\n                ModifierPrototype& modifier = emitter->m_Modifiers[i];\n                const dmParticleDDF::Modifier& modifier_ddf = emitter_ddf->m_Modifiers[i];\n                prop_count = modifier_ddf.m_Properties.m_Count;\n                for (uint32_t j = 0; j < prop_count; ++j)\n                {\n                    const dmParticleDDF::Modifier::Property& p = modifier_ddf.m_Properties[j];\n                    if (p.m_Key < dmParticleDDF::MODIFIER_KEY_COUNT)\n                    {\n                        Property& property = modifier.m_Properties[p.m_Key];\n                        SampleProperty(p.m_Points.m_Data, p.m_Points.m_Count, property.m_Segments);\n                        property.m_Spread = p.m_Spread;\n                    }\n                    else\n                    {\n                        dmLogWarning(\"The key %d is not a valid modifier key.\", p.m_Key);\n                    }\n                }\n            }\n        }\n    }\n\n    Prototype* NewPrototype(const void* buffer, uint32_t buffer_size)\n    {\n        dmParticleDDF::ParticleFX* ddf = 0;\n        dmDDF::Result r = dmDDF::LoadMessage<dmParticleDDF::ParticleFX>(buffer, buffer_size, &ddf);\n        if (r == dmDDF::RESULT_OK)\n        {\n            return NewPrototypeFromDDF(ddf);\n        }\n        dmLogError(\"Failed to load particle data\");\n        return 0x0;\n    }\n\n    Prototype* NewPrototypeFromDDF(dmParticleDDF::ParticleFX* message)\n    {\n        Prototype* prototype = new Prototype();\n        LoadResources(prototype, message);\n        return prototype;\n    }\n\n    void DeletePrototype(HPrototype prototype)\n    {\n        uint32_t emitter_count = prototype->m_Emitters.Size();\n        for (uint32_t i = 0; i < emitter_count; ++i)\n        {\n            prototype->m_Emitters[i].m_Modifiers.SetCapacity(0);\n        }\n        dmDDF::FreeMessage(prototype->m_DDF);\n        delete prototype;\n    }\n\n    bool ReloadPrototype(HPrototype prototype, const void* buffer, uint32_t buffer_size)\n    {\n        dmParticleDDF::ParticleFX* ddf = 0;\n        dmDDF::Result r = dmDDF::LoadMessage<dmParticleDDF::ParticleFX>(buffer, buffer_size, &ddf);\n        if (r == dmDDF::RESULT_OK)\n        {\n            LoadResources(prototype, ddf);\n            return true;\n        }\n        return false;\n    }\n\n    uint32_t GetEmitterCount(HPrototype prototype)\n    {\n        return prototype->m_Emitters.Size();\n    }\n\n    uint32_t GetInstanceEmitterCount(HParticleContext context, HInstance instance)\n    {\n        Instance* inst = GetInstance(context, instance);\n        return (inst != 0x0) ? inst->m_Emitters.Size() : 0;\n    }\n\n    void RenderEmitter(Instance* instance, uint32_t emitter_index, void* usercontext, RenderEmitterCallback render_emitter_callback);\n    void RenderEmitter(HParticleContext context, HInstance instance, uint32_t emitter_index, void* user_context, RenderEmitterCallback render_instance_callback)\n    {\n        Instance* inst = GetInstance(context, instance);\n        if (inst != 0x0 && emitter_index < inst->m_Emitters.Size())\n        {\n            RenderEmitter(GetInstance(context, instance), emitter_index, user_context, render_instance_callback);\n        }\n        else if (inst == 0x0)\n        {\n            dmLogError(\"The particlefx instance could not be found when rendering.\");\n        }\n        else\n        {\n            dmLogError(\"The particlefx emitter could not be found when rendering.\");\n        }\n    }\n\n    void RenderEmitter(Instance* instance, uint32_t emitter_index, void* user_context, RenderEmitterCallback render_emitter_callback)\n    {\n        Emitter* emitter = &instance->m_Emitters[emitter_index];\n        if (!emitter || emitter->m_VertexCount == 0) return;\n\n        dmParticleDDF::Emitter* ddf = &instance->m_Prototype->m_DDF->m_Emitters[emitter_index];\n        dmTransform::TransformS1 transform(Vector3(ddf->m_Position), ddf->m_Rotation, 1.0f);\n        if (instance->m_ScaleAlongZ)\n            transform = dmTransform::Mul(instance->m_WorldTransform, transform);\n        else\n            transform = dmTransform::MulNoScaleZ(instance->m_WorldTransform, transform);\n        Vectormath::Aos::Matrix4 world = dmTransform::ToMatrix4(transform);\n        dmParticle::EmitterPrototype* emitter_proto = &instance->m_Prototype->m_Emitters[emitter_index];\n\n        render_emitter_callback(user_context, emitter_proto->m_Material, emitter->m_AnimationData.m_Texture, world, emitter_proto->m_BlendMode, emitter->m_VertexIndex, emitter->m_VertexCount, emitter->m_RenderConstants.Begin(), emitter->m_RenderConstants.Size());\n    }\n\n    // Update render data for the emitter at the specified index\n    void UpdateEmitterRenderData(HInstance instance, uint32_t emitter_index, Instance* inst, Emitter* emitter, dmParticleDDF::Emitter* ddf)\n    {\n        EmitterRenderData& render_data = emitter->m_RenderData;\n\n        dmTransform::TransformS1 transform(Vector3(ddf->m_Position), ddf->m_Rotation, 1.0f);\n        if (inst->m_ScaleAlongZ)\n            transform = dmTransform::Mul(inst->m_WorldTransform, transform);\n        else\n            transform = dmTransform::MulNoScaleZ(inst->m_WorldTransform, transform);\n        Vectormath::Aos::Matrix4 world = dmTransform::ToMatrix4(transform);\n        dmParticle::EmitterPrototype* emitter_proto = &inst->m_Prototype->m_Emitters[emitter_index];\n\n        render_data.m_Transform = world;\n        render_data.m_Material = emitter_proto->m_Material;\n        render_data.m_BlendMode = emitter_proto->m_BlendMode;\n        render_data.m_Texture = emitter->m_AnimationData.m_Texture;\n        render_data.m_RenderConstants = emitter->m_RenderConstants.Begin();\n        render_data.m_RenderConstantsSize = emitter->m_RenderConstants.Size();\n        render_data.m_Instance = instance;\n        render_data.m_EmitterIndex = emitter_index;\n    }\n\n    // Update render data for all emitters on an instance\n    void UpdateRenderData(HParticleContext context, HInstance instance, uint32_t emitter_index)\n    {\n        Instance* inst = GetInstance(context, instance);\n\n        if (inst != 0x0)\n        {\n            uint32_t emitter_count = inst->m_Emitters.Size();\n            for (uint32_t i = 0; i < emitter_count; ++i)\n            {\n                Emitter* emitter = &inst->m_Emitters[i];\n                dmParticleDDF::Emitter* emitter_ddf = &inst->m_Prototype->m_DDF->m_Emitters[i];\n                UpdateEmitterRenderData(instance, i, inst, emitter, emitter_ddf);\n            }\n        }\n    }\n\n    void GetEmitterRenderData(HParticleContext context, HInstance instance, uint32_t emitter_index, EmitterRenderData** data)\n    {\n        Instance* inst = GetInstance(context, instance);\n\n        if (inst != 0x0 && emitter_index < inst->m_Emitters.Size())\n        {\n            Emitter* emitter = &inst->m_Emitters[emitter_index];\n\n            if (emitter && data != 0x0)\n            {\n                *data = &emitter->m_RenderData;\n                return;\n            }\n        }\n\n        *data = 0x0;\n    }\n\n    const char* GetMaterialPath(HPrototype prototype, uint32_t emitter_index)\n    {\n        return prototype->m_DDF->m_Emitters[emitter_index].m_Material;\n    }\n\n    const char* GetTileSourcePath(HPrototype prototype, uint32_t emitter_index)\n    {\n        return prototype->m_DDF->m_Emitters[emitter_index].m_TileSource;\n    }\n\n    void* GetMaterial(HPrototype prototype, uint32_t emitter_index)\n    {\n        return prototype->m_Emitters[emitter_index].m_Material;\n    }\n\n    void* GetTileSource(HPrototype prototype, uint32_t emitter_index)\n    {\n        return prototype->m_Emitters[emitter_index].m_TileSource;\n    }\n\n    void SetMaterial(HPrototype prototype, uint32_t emitter_index, void* material)\n    {\n        prototype->m_Emitters[emitter_index].m_Material = material;\n    }\n\n    void SetTileSource(HPrototype prototype, uint32_t emitter_index, void* tile_source)\n    {\n        prototype->m_Emitters[emitter_index].m_TileSource = tile_source;\n    }\n\n    void SetRenderConstant(HParticleContext context, HInstance instance, dmhash_t emitter_id, dmhash_t name_hash, Vector4 value)\n    {\n        Instance* inst = GetInstance(context, instance);\n        uint32_t count = inst->m_Emitters.Size();\n        for (uint32_t i = 0; i < count; ++i)\n        {\n            Emitter* e = &inst->m_Emitters[i];\n            if (e->m_Id == emitter_id)\n            {\n                RenderConstant* c = 0x0;\n                dmArray<RenderConstant>& constants = e->m_RenderConstants;\n                uint32_t constant_count = constants.Size();\n                for (uint32_t constant_i = 0; constant_i < constant_count; ++constant_i)\n                {\n                    RenderConstant* constant = &constants[constant_i];\n                    if (constant->m_NameHash == name_hash)\n                    {\n                        c = constant;\n                        break;\n                    }\n                }\n                if (c == 0x0)\n                {\n                    if (constants.Full())\n                    {\n                        constants.SetCapacity(constants.Capacity() + 4);\n                    }\n                    constants.SetSize(constant_count + 1);\n                    c = &constants[constant_count];\n                    c->m_NameHash = name_hash;\n                }\n                c->m_Value = value;\n                e->m_ReHash = 1;\n            }\n        }\n    }\n\n    void ResetRenderConstant(HParticleContext context, HInstance instance, dmhash_t emitter_id, dmhash_t name_hash)\n    {\n        Instance* inst = GetInstance(context, instance);\n        uint32_t count = inst->m_Emitters.Size();\n        for (uint32_t i = 0; i < count; ++i)\n        {\n            Emitter* e = &inst->m_Emitters[i];\n            if (e->m_Id == emitter_id)\n            {\n                dmArray<RenderConstant>& constants = e->m_RenderConstants;\n                uint32_t constant_count = constants.Size();\n                for (uint32_t constant_i = 0; constant_i < constant_count; ++constant_i)\n                {\n                    if (constants[constant_i].m_NameHash == name_hash)\n                    {\n                        constants.EraseSwap(constant_i);\n                        e->m_ReHash = 1;\n                        break;\n                    }\n                }\n                // Don't break here, look for more\n            }\n        }\n    }\n\n    void GetStats(HParticleContext context, Stats* stats)\n    {\n        assert(stats->m_StructSize == sizeof(*stats));\n        *stats = context->m_Stats;\n        stats->m_MaxParticles = context->m_MaxParticleCount;\n    }\n\n    void GetInstanceStats(HParticleContext context, HInstance instance, InstanceStats* stats)\n    {\n        assert(stats->m_StructSize == sizeof(*stats));\n        Instance* i = GetInstance(context, instance);\n        stats->m_Time = i->m_PlayTime;\n    }\n\n    uint32_t GetVertexBufferSize(uint32_t particle_count, ParticleVertexFormat vertex_format)\n    {\n        uint32_t vertex_size = sizeof(Vertex);\n\n        if (vertex_format == PARTICLE_GUI)\n            vertex_size = sizeof(ParticleGuiVertex);\n\n        return particle_count * 6 * vertex_size;\n    }\n\n    uint32_t GetMaxVertexBufferSize(HParticleContext context, ParticleVertexFormat vertex_format)\n    {\n        return GetVertexBufferSize(context->m_MaxParticleCount, vertex_format);\n    }\n\n    void ReHashEmitter(Emitter* e)\n    {\n        EmitterRenderData& data = e->m_RenderData;\n\n        if (data.m_Material == 0x0 || data.m_Texture == 0x0)\n        {\n            e->m_ReHash = 1;\n            return;\n        }\n\n        HashState32 state;\n        HashState32 state_no_material;\n        bool reverse = false;\n        dmHashInit32(&state, reverse);\n        dmHashUpdateBuffer32(&state, &data.m_Texture, sizeof(data.m_Texture));\n        dmHashUpdateBuffer32(&state, &data.m_BlendMode, sizeof(data.m_BlendMode));\n\n        dmParticle::RenderConstant* constants = data.m_RenderConstants;\n        uint32_t size = data.m_RenderConstantsSize;\n        for (uint32_t j = 0; j < size; ++j)\n        {\n            dmParticle::RenderConstant& c = constants[j];\n            dmHashUpdateBuffer32(&state, &c.m_NameHash, sizeof(uint64_t));\n            dmHashUpdateBuffer32(&state, &c.m_Value, sizeof(Vector4));\n        }\n        memcpy(&state_no_material, &state, sizeof(HashState32));\n        data.m_MixedHashNoMaterial = dmHashFinal32(&state_no_material);\n\n        dmHashUpdateBuffer32(&state, &data.m_Material, sizeof(data.m_Material));\n        data.m_MixedHash = dmHashFinal32(&state);\n        e->m_ReHash = 0;\n    }\n\n    void ReHash(HParticleContext context, HInstance instance)\n    {\n        Instance* inst = GetInstance(context, instance);\n        uint32_t count = inst->m_Emitters.Size();\n        for (uint32_t i = 0; i < count; ++i)\n        {\n            Emitter* e = &inst->m_Emitters[i];\n            ReHashEmitter(e);\n        }\n    }\n\n\n#define DM_PARTICLE_TRAMPOLINE1(ret, name, t1) \\\n    ret Particle_##name(t1 a1)\\\n    {\\\n        return name(a1);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE2(ret, name, t1, t2) \\\n    ret Particle_##name(t1 a1, t2 a2)\\\n    {\\\n        return name(a1, a2);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE3(ret, name, t1, t2, t3) \\\n    ret Particle_##name(t1 a1, t2 a2, t3 a3)\\\n    {\\\n        return name(a1, a2, a3);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE4(ret, name, t1, t2, t3, t4) \\\n    ret Particle_##name(t1 a1, t2 a2, t3 a3, t4 a4)\\\n    {\\\n        return name(a1, a2, a3, a4);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE5(ret, name, t1, t2, t3, t4, t5) \\\n    ret Particle_##name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5)\\\n    {\\\n        return name(a1, a2, a3, a4, a5);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE6(ret, name, t1, t2, t3, t4, t5, t6) \\\n    ret Particle_##name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6)\\\n    {\\\n        return name(a1, a2, a3, a4, a5, a6);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE7(ret, name, t1, t2, t3, t4, t5, t6, t7) \\\n    ret Particle_##name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7)\\\n    {\\\n        return name(a1, a2, a3, a4, a5, a6, a7);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE8(ret, name, t1, t2, t3, t4, t5, t6, t7, t8) \\\n    ret Particle_##name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7, t8 a8)\\\n    {\\\n        return name(a1, a2, a3, a4, a5, a6, a7, a8);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE9(ret, name, t1, t2, t3, t4, t5, t6, t7, t8, t9) \\\n    ret Particle_##name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7, t8 a8, t9 a9)\\\n    {\\\n        return name(a1, a2, a3, a4, a5, a6, a7, a8, a9);\\\n    }\\\n\n#define DM_PARTICLE_TRAMPOLINE10(ret, name, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10) \\\n    ret Particle_##name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7, t8 a8, t9 a9, t10 a10)\\\n    {\\\n        return name(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);\\\n    }\\\n\n    DM_PARTICLE_TRAMPOLINE2(HParticleContext, CreateContext, uint32_t, uint32_t);\n    DM_PARTICLE_TRAMPOLINE1(void, DestroyContext, HParticleContext);\n    DM_PARTICLE_TRAMPOLINE1(uint32_t, GetContextMaxParticleCount, HParticleContext);\n    DM_PARTICLE_TRAMPOLINE2(void, SetContextMaxParticleCount, HParticleContext, uint32_t);\n\n    DM_PARTICLE_TRAMPOLINE3(HInstance, CreateInstance, HParticleContext, HPrototype, EmitterStateChangedData*);\n    DM_PARTICLE_TRAMPOLINE2(void, DestroyInstance, HParticleContext, HInstance);\n    DM_PARTICLE_TRAMPOLINE3(void, ReloadInstance, HParticleContext, HInstance, bool);\n\n    DM_PARTICLE_TRAMPOLINE2(void, StartInstance, HParticleContext, HInstance);\n    DM_PARTICLE_TRAMPOLINE2(void, StopInstance, HParticleContext, HInstance);\n    DM_PARTICLE_TRAMPOLINE2(void, ResetInstance, HParticleContext, HInstance);\n    DM_PARTICLE_TRAMPOLINE3(void, SetPosition, HParticleContext, HInstance, const Point3&);\n    DM_PARTICLE_TRAMPOLINE3(void, SetRotation, HParticleContext, HInstance, const Quat&);\n    DM_PARTICLE_TRAMPOLINE3(void, SetScale, HParticleContext, HInstance, float);\n    DM_PARTICLE_TRAMPOLINE3(void, SetScaleAlongZ, HParticleContext, HInstance, bool);\n\n    DM_PARTICLE_TRAMPOLINE2(bool, IsSleeping, HParticleContext, HInstance);\n    DM_PARTICLE_TRAMPOLINE3(void, Update, HParticleContext, float, FetchAnimationCallback);\n    DM_PARTICLE_TRAMPOLINE9(void, GenerateVertexData, HParticleContext, float, HInstance, uint32_t, const Vector4&, void*, uint32_t, uint32_t*, ParticleVertexFormat);\n\n    DM_PARTICLE_TRAMPOLINE2(HPrototype, NewPrototype, const void*, uint32_t);\n    DM_PARTICLE_TRAMPOLINE1(HPrototype, NewPrototypeFromDDF, dmParticleDDF::ParticleFX*);\n    DM_PARTICLE_TRAMPOLINE1(void, DeletePrototype, HPrototype);\n    DM_PARTICLE_TRAMPOLINE3(bool, ReloadPrototype, HPrototype, const void*, uint32_t);\n\n    DM_PARTICLE_TRAMPOLINE1(uint32_t, GetEmitterCount, HPrototype);\n    DM_PARTICLE_TRAMPOLINE5(void, RenderEmitter, HParticleContext, HInstance, uint32_t, void*, RenderEmitterCallback);\n    DM_PARTICLE_TRAMPOLINE2(const char*, GetMaterialPath, HPrototype, uint32_t);\n    DM_PARTICLE_TRAMPOLINE2(const char*, GetTileSourcePath, HPrototype, uint32_t);\n    DM_PARTICLE_TRAMPOLINE2(void*, GetMaterial, HPrototype, uint32_t);\n    DM_PARTICLE_TRAMPOLINE2(void*, GetTileSource, HPrototype, uint32_t);\n    DM_PARTICLE_TRAMPOLINE3(void, SetMaterial, HPrototype, uint32_t, void*);\n    DM_PARTICLE_TRAMPOLINE3(void, SetTileSource, HPrototype, uint32_t, void*);\n\n    DM_PARTICLE_TRAMPOLINE5(void, SetRenderConstant, HParticleContext, HInstance, dmhash_t, dmhash_t, Vector4);\n    DM_PARTICLE_TRAMPOLINE4(void, ResetRenderConstant, HParticleContext, HInstance, dmhash_t, dmhash_t);\n\n    DM_PARTICLE_TRAMPOLINE2(void, GetStats, HParticleContext, Stats*);\n    DM_PARTICLE_TRAMPOLINE3(void, GetInstanceStats, HParticleContext, HInstance, InstanceStats*);\n\n    DM_PARTICLE_TRAMPOLINE2(uint32_t, GetVertexBufferSize, uint32_t, ParticleVertexFormat);\n\n    dmhash_t Particle_Hash(const char* value)\n    {\n        return dmHashString64(value);\n    }\n}\n", "meta": {"hexsha": "abd00d7928e795d1579cc6ece82ec5de6fe3bb6b", "size": 98178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "engine/particle/src/particle.cpp", "max_stars_repo_name": "Krzlfx/defold", "max_stars_repo_head_hexsha": "ce38de254c08d0f3c63fabee07b44cbf1433a428", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 2231.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T08:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:51:23.000Z", "max_issues_repo_path": "engine/particle/src/particle.cpp", "max_issues_repo_name": "Krzlfx/defold", "max_issues_repo_head_hexsha": "ce38de254c08d0f3c63fabee07b44cbf1433a428", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 1485.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T10:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:12:42.000Z", "max_forks_repo_path": "engine/particle/src/particle.cpp", "max_forks_repo_name": "Krzlfx/defold", "max_forks_repo_head_hexsha": "ce38de254c08d0f3c63fabee07b44cbf1433a428", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 197.0, "max_forks_repo_forks_event_min_datetime": "2020-05-19T10:20:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:52:13.000Z", "avg_line_length": 45.0564479119, "max_line_length": 264, "alphanum_fraction": 0.618030516, "num_tokens": 23866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.18076152869575465}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@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#define BOOST_TEST_MODULE crypto3_marshalling_r1cs_gg_ppzksnark_verification_key_test\n\n#include <boost/test/unit_test.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <iostream>\n#include <iomanip>\n\n#include <nil/marshalling/status_type.hpp>\n#include <nil/marshalling/field_type.hpp>\n#include <nil/marshalling/endianness.hpp>\n\n#include <nil/crypto3/multiprecision/cpp_int.hpp>\n#include <nil/crypto3/multiprecision/number.hpp>\n\n#include <nil/crypto3/algebra/random_element.hpp>\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/curves/detail/marshalling.hpp>\n#include <nil/crypto3/algebra/pairing/bls12.hpp>\n#include <nil/crypto3/algebra/pairing/mnt4.hpp>\n#include <nil/crypto3/algebra/pairing/mnt6.hpp>\n\n#include <nil/crypto3/zk/snark/sparse_vector.hpp>\n#include <nil/crypto3/zk/snark/accumulation_vector.hpp>\n\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/verification_key.hpp>\n\ntemplate<typename TIter>\nvoid print_byteblob(TIter iter_begin, TIter iter_end) {\n    for (TIter it = iter_begin; it != iter_end; it++) {\n        std::cout << std::hex << int(*it) << std::endl;\n    }\n}\n\ntemplate<typename FpCurveGroupElement>\nvoid print_fp_curve_group_element(FpCurveGroupElement e) {\n    std::cout << e.X.data << \" \" << e.Y.data << \" \" << e.Z.data << std::endl;\n}\n\ntemplate<typename Fp2CurveGroupElement>\nvoid print_fp2_curve_group_element(Fp2CurveGroupElement e) {\n    std::cout << \"(\" << e.X.data[0].data << \" \" << e.X.data[1].data << \") (\" << e.Y.data[0].data << \" \"\n              << e.Y.data[1].data << \") (\" << e.Z.data[0].data << \" \" << e.Z.data[1].data << \")\" << std::endl;\n}\n\ntemplate<typename Endianness, typename VerificationKeyMarshaling, typename VerificationKey,\n         typename CurveType = typename VerificationKey::curve_type>\nvoid test_verification_key(const VerificationKey &val) {\n\n    using namespace nil::crypto3::marshalling;\n\n    std::size_t units_bits = 8;\n    using unit_type = unsigned char;\n    using verification_key_marshaling_type = VerificationKeyMarshaling;\n\n    verification_key_marshaling_type filled_val =\n        types::fill_r1cs_gg_ppzksnark_verification_key<VerificationKey, Endianness>(val);\n\n    VerificationKey constructed_val =\n        types::make_r1cs_gg_ppzksnark_verification_key<VerificationKey, Endianness>(filled_val);\n    BOOST_CHECK(val == constructed_val);\n\n    std::size_t unitblob_size = filled_val.length();\n\n    std::vector<unit_type> cv;\n    cv.resize(unitblob_size, 0x00);\n\n    auto write_iter = cv.begin();\n\n    nil::marshalling::status_type status = filled_val.write(write_iter, cv.size());\n\n    verification_key_marshaling_type test_val_read;\n\n    auto read_iter = cv.begin();\n    status = test_val_read.read(read_iter, cv.size());\n\n    VerificationKey constructed_val_read =\n        types::make_r1cs_gg_ppzksnark_verification_key<VerificationKey, Endianness>(test_val_read);\n\n    BOOST_CHECK(val == constructed_val_read);\n}\n\n// TODO: move to pubkey marshling\ntemplate<typename Endianness, typename KeyMarshaling, typename Key,\n         typename CurveType = typename Key::scheme_type::curve_type>\nvoid test_pubkey(const Key &val) {\n\n    using namespace nil::crypto3::marshalling;\n\n    std::size_t units_bits = 8;\n    using unit_type = unsigned char;\n    using key_marshaling_type = KeyMarshaling;\n\n    key_marshaling_type filled_val = types::fill_public_key<Key, Endianness>(val);\n\n    Key constructed_val = types::make_public_key<Key, Endianness>(filled_val);\n    BOOST_CHECK(val == constructed_val);\n\n    std::size_t unitblob_size = filled_val.length();\n\n    std::vector<unit_type> cv;\n    cv.resize(unitblob_size, 0x00);\n\n    auto write_iter = cv.begin();\n\n    nil::marshalling::status_type status = filled_val.write(write_iter, cv.size());\n\n    key_marshaling_type test_val_read;\n\n    auto read_iter = cv.begin();\n    status = test_val_read.read(read_iter, cv.size());\n\n    Key constructed_val_read = types::make_public_key<Key, Endianness>(test_val_read);\n\n    BOOST_CHECK(val == constructed_val_read);\n}\n\ntemplate<typename VerificationKey, typename VerificationKeyMarshaling, typename Endianness, std::size_t TSize,\n         typename CurveType = typename VerificationKey::curve_type>\ntypename std::enable_if<\n    std::is_same<nil::crypto3::zk::snark::r1cs_gg_ppzksnark_verification_key<CurveType>, VerificationKey>::value>::type\n    test_verification_key() {\n    using g1_type = typename CurveType::template g1_type<>;\n    using g2_type = typename CurveType::template g2_type<>;\n    using gt_type = typename CurveType::gt_type;\n\n    std::cout << std::hex;\n    std::cerr << std::hex;\n    for (unsigned i = 0; i < 128; ++i) {\n        if (!(i % 16) && i) {\n            std::cout << std::dec << i << \" tested\" << std::endl;\n        }\n        typename g1_type::value_type first = nil::crypto3::algebra::random_element<g1_type>();\n        std::vector<typename g1_type::value_type> rest;\n        for (std::size_t i = 0; i < TSize; i++) {\n            rest.push_back(nil::crypto3::algebra::random_element<g1_type>());\n        }\n        test_verification_key<Endianness, VerificationKeyMarshaling>(VerificationKey(\n            nil::crypto3::algebra::random_element<gt_type>(),\n            nil::crypto3::algebra::random_element<g2_type>(),\n            nil::crypto3::algebra::random_element<g2_type>(),\n            std::move(nil::crypto3::zk::snark::accumulation_vector<g1_type>(std::move(first), std::move(rest)))));\n    }\n}\n\ntemplate<typename VerificationKey, typename VerificationKeyMarshaling, typename Endianness, std::size_t TSize,\n         typename CurveType = typename VerificationKey::curve_type>\ntypename std::enable_if<std::is_same<nil::crypto3::zk::snark::r1cs_gg_ppzksnark_extended_verification_key<CurveType>,\n                                     VerificationKey>::value>::type\n    test_verification_key() {\n    using g1_type = typename CurveType::template g1_type<>;\n    using g2_type = typename CurveType::template g2_type<>;\n    using gt_type = typename CurveType::gt_type;\n\n    std::cout << std::hex;\n    std::cerr << std::hex;\n    for (unsigned i = 0; i < 128; ++i) {\n        if (!(i % 16) && i) {\n            std::cout << std::dec << i << \" tested\" << std::endl;\n        }\n        typename g1_type::value_type first = nil::crypto3::algebra::random_element<g1_type>();\n        std::vector<typename g1_type::value_type> rest;\n        for (std::size_t i = 0; i < TSize; i++) {\n            rest.push_back(nil::crypto3::algebra::random_element<g1_type>());\n        }\n        test_verification_key<Endianness, VerificationKeyMarshaling>(VerificationKey(\n            nil::crypto3::algebra::random_element<gt_type>(),\n            nil::crypto3::algebra::random_element<g2_type>(),\n            nil::crypto3::algebra::random_element<g2_type>(),\n            nil::crypto3::algebra::random_element<g1_type>(),\n            std::move(nil::crypto3::zk::snark::accumulation_vector<g1_type>(std::move(first), std::move(rest))),\n            nil::crypto3::algebra::random_element<g1_type>()));\n    }\n}\n\n// TODO: move to pubkey marshling\ntemplate<typename PublicKey, typename PublicKeyMarshaling, typename Endianness, std::size_t TSize,\n         typename CurveType = typename PublicKey::scheme_type::curve_type>\ntypename std::enable_if<\n    std::is_same<nil::crypto3::pubkey::public_key<nil::crypto3::pubkey::elgamal_verifiable<\n                     typename PublicKey::scheme_type::curve_type, PublicKey::scheme_type::block_bits>>,\n                 PublicKey>::value>::type\n    test_pubkey() {\n    using g1_type = typename PublicKey::g1_type;\n    using g2_type = typename PublicKey::g2_type;\n\n    std::cout << std::hex;\n    std::cerr << std::hex;\n    for (unsigned i = 0; i < 128; ++i) {\n        if (!(i % 16) && i) {\n            std::cout << std::dec << i << \" tested\" << std::endl;\n        }\n        std::vector<typename g1_type::value_type> delta_s_g1;\n        std::vector<typename g1_type::value_type> t_g1;\n        std::vector<typename g2_type::value_type> t_g2;\n        for (std::size_t i = 0; i < TSize; i++) {\n            delta_s_g1.push_back(nil::crypto3::algebra::random_element<g1_type>());\n            t_g1.push_back(nil::crypto3::algebra::random_element<g1_type>());\n            t_g2.push_back(nil::crypto3::algebra::random_element<g2_type>());\n        }\n        t_g2.push_back(nil::crypto3::algebra::random_element<g2_type>());\n        test_pubkey<Endianness, PublicKeyMarshaling>(PublicKey(\n            nil::crypto3::algebra::random_element<g1_type>(), std::move(delta_s_g1), std::move(t_g1), std::move(t_g2),\n            nil::crypto3::algebra::random_element<g1_type>(), nil::crypto3::algebra::random_element<g1_type>()));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE(verification_key_test_suite)\n\nBOOST_AUTO_TEST_CASE(r1cs_gg_ppzksnark_verification_key_bls12_381_be) {\n    using endianness = nil::marshalling::option::big_endian;\n    using key_type =\n        nil::crypto3::zk::snark::r1cs_gg_ppzksnark_verification_key<nil::crypto3::algebra::curves::bls12<381>>;\n    using key_marshaling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_verification_key<nil::marshalling::field_type<endianness>,\n                                                                             key_type>;\n    std::cout << \"BLS12-381 r1cs_gg_ppzksnark verification key big-endian test started\" << std::endl;\n    test_verification_key<key_type, key_marshaling_type, endianness, 5>();\n    std::cout << \"BLS12-381 r1cs_gg_ppzksnark verification key big-endian test finished\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(r1cs_gg_ppzksnark_extended_verification_key_bls12_381_be) {\n    using endianness = nil::marshalling::option::big_endian;\n    using key_type =\n        nil::crypto3::zk::snark::r1cs_gg_ppzksnark_extended_verification_key<nil::crypto3::algebra::curves::bls12<381>>;\n    using key_marshaling_type = nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_extended_verification_key<\n        nil::marshalling::field_type<endianness>, key_type>;\n    std::cout << \"BLS12-381 r1cs_gg_ppzksnark extended verification key big-endian test started\" << std::endl;\n    test_verification_key<key_type, key_marshaling_type, endianness, 5>();\n    std::cout << \"BLS12-381 r1cs_gg_ppzksnark extended verification key big-endian test finished\" << std::endl;\n}\n\n// TODO: move to pubkey marshling\nBOOST_AUTO_TEST_CASE(elgamal_verifiable_public_key_bls12_381_be) {\n    using endianness = nil::marshalling::option::big_endian;\n    using key_type = nil::crypto3::pubkey::public_key<\n        nil::crypto3::pubkey::elgamal_verifiable<nil::crypto3::algebra::curves::bls12<381>>>;\n    using key_marshaling_type =\n        nil::crypto3::marshalling::types::elgamal_verifiable_public_key<nil::marshalling::field_type<endianness>,\n                                                                        key_type>;\n    std::cout << \"BLS12-381 r1cs_gg_ppzksnark extended verification key big-endian test started\" << std::endl;\n    test_pubkey<key_type, key_marshaling_type, endianness, 5>();\n    std::cout << \"BLS12-381 r1cs_gg_ppzksnark extended verification key big-endian test finished\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(r1cs_gg_ppzksnark_extended_verification_key_bls12_381_be_error_length) {\n    using endianness = nil::marshalling::option::big_endian;\n    using curve_type = nil::crypto3::algebra::curves::bls12<381>;\n    using key_type = nil::crypto3::zk::snark::r1cs_gg_ppzksnark_extended_verification_key<curve_type>;\n    using key_marshaling_type = nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_extended_verification_key<\n        nil::marshalling::field_type<endianness>, key_type>;\n\n    using g1_type = typename curve_type::template g1_type<>;\n    using g2_type = typename curve_type::template g2_type<>;\n    using gt_type = typename curve_type::gt_type;\n\n    using gt_marshalling_type =\n        nil::crypto3::marshalling::types::field_element<nil::marshalling::field_type<endianness>, gt_type>;\n    using g2_marshalling_type =\n        nil::crypto3::marshalling::types::curve_element<nil::marshalling::field_type<endianness>, g2_type>;\n    using g1_marshalling_type =\n        nil::crypto3::marshalling::types::curve_element<nil::marshalling::field_type<endianness>, g1_type>;\n    using accumulation_vector_marshalling_type =\n        nil::crypto3::marshalling::types::accumulation_vector<nil::marshalling::field_type<endianness>,\n                                                              nil::crypto3::zk::snark::accumulation_vector<g1_type>>;\n    gt_marshalling_type gt_marshaling;\n    std::cout << \"Not ok: \" << gt_marshaling.length() << std::endl;\n    gt_marshalling_type filled_gt = nil::crypto3::marshalling::types::fill_field_element<gt_type, endianness>(\n        nil::crypto3::algebra::random_element<gt_type>());\n    std::cout << \"Ok only after initialization: \" << filled_gt.length() << std::endl;\n\n    g2_marshalling_type g2_marshaling;\n    std::cout << \"Ok: \" << g2_marshaling.length() << std::endl;\n\n    g1_marshalling_type g1_marshaling;\n    std::cout << \"Ok: \" << g1_marshaling.length() << std::endl;\n\n    accumulation_vector_marshalling_type accumulation_vector_marshalling;\n    std::cout << \"Seems ok, full information about size should be available after initialization: \"\n              << accumulation_vector_marshalling.length() << std::endl;\n    typename g1_type::value_type first = nil::crypto3::algebra::random_element<g1_type>();\n    std::vector<typename g1_type::value_type> rest;\n    for (std::size_t i = 0; i < 5; i++) {\n        rest.push_back(nil::crypto3::algebra::random_element<g1_type>());\n    }\n    nil::crypto3::zk::snark::accumulation_vector<g1_type> acc_vec(std::move(first), std::move(rest));\n    accumulation_vector_marshalling_type filled_acc_vec = nil::crypto3::marshalling::types::fill_accumulation_vector<\n        nil::crypto3::zk::snark::accumulation_vector<g1_type>, endianness>(acc_vec);\n    std::cout << \"Ok: \" << filled_acc_vec.length() << std::endl;\n\n    // key_type key(nil::crypto3::algebra::random_element<gt_type>(),\n    //              nil::crypto3::algebra::random_element<g2_type>(),\n    //              nil::crypto3::algebra::random_element<g2_type>(),\n    //              nil::crypto3::algebra::random_element<g1_type>(),\n    //              std::move(zk::snark::accumulation_vector<g1_type>(std::move(first), std::move(rest))),\n    //              nil::crypto3::algebra::random_element<g1_type>());\n}\n\n// BOOST_AUTO_TEST_CASE(sparse_vector_bls12_381_le) {\n//     std::cout << \"BLS12-381 r1cs_gg_ppzksnark verification key little-endian test started\" << std::endl;\n//     test_verification_key<nil::crypto3::algebra::curves::bls12<381>, nil::marshalling::option::little_endian, 5>();\n//     std::cout << \"BLS12-381 r1cs_gg_ppzksnark verification key little-endian test finished\" << std::endl;\n// }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b33a4f165bb10e44fb2d18e64d1b9fc8102463a4", "size": 16313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/r1cs_gg_ppzksnark_verification_key.cpp", "max_stars_repo_name": "NilFoundation/crypto3-zk-marshalling", "max_stars_repo_head_hexsha": "796b6c86c93e8f657a51e726679061c6fded7614", "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/r1cs_gg_ppzksnark_verification_key.cpp", "max_issues_repo_name": "NilFoundation/crypto3-zk-marshalling", "max_issues_repo_head_hexsha": "796b6c86c93e8f657a51e726679061c6fded7614", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-11-08T22:27:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T11:39:02.000Z", "max_forks_repo_path": "test/r1cs_gg_ppzksnark_verification_key.cpp", "max_forks_repo_name": "NilFoundation/crypto3-zk-marshalling", "max_forks_repo_head_hexsha": "796b6c86c93e8f657a51e726679061c6fded7614", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-19T14:42:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-19T14:42:56.000Z", "avg_line_length": 48.987987988, "max_line_length": 120, "alphanum_fraction": 0.6938637896, "num_tokens": 4248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.1806667154075853}}
{"text": "//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology\n//Licensed under the terms of the MIT License, as described in the file:\n//   license.txt   (http://opensource.org/licenses/MIT)\n\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n\nnamespace sim_mob\n{\nnamespace simple_password\n{\nvoid encryptionFunc(std::string &nString)\n{\n    const int KEY = 23;                       // Key used for XOR operation\n    int strLen = (nString.length());          // Grab string length for iterating thru string\n    char *cString = (char*)(nString.c_str()); // Convert string to C string so we can actually iterate through it(std::string will treat it as one full object :()\n\n    for (int i = 0; i < strLen; i++)          // time to iterate thru string and XOR each individual char.\n    {\n     *(cString+i) = (*(cString+i) ^ KEY);     // ^ is the binary operator for XOR\n    }\n}\n\nvoid decryptionFunc(std::string &nString)    // Time to undo what we did from above :D\n{\n    const int KEY = 23;\n    int strLen = (nString.length());\n    char *cString = (char*)(nString.c_str());\n\n    for (int i = 0; i < strLen; i++)\n    {\n     *(cString+i) = (*(cString+i) ^ KEY);\n    }\n}\nvoid saveBinary(std::string value)\n{\n  std::ofstream file(\"shared/password/password\");\n  boost::archive::binary_oarchive oa(file);\n  oa << value;\n}\n\n\nvoid loadBinary(std::string & value)\n{\n    try\n    {\n        std::ifstream file(\"shared/password/password\");\n        boost::archive::binary_iarchive ia(file);\n        ia >> value;\n    }\n    catch(...)\n    {\n\n    }\n}\n\nvoid save(std::string source)\n{\n\n    encryptionFunc(source);\n    saveBinary(source);\n}\n\nstd::string load(std::string dest)\n{\n\n    loadBinary(dest);\n    decryptionFunc(dest);\n    return dest;\n}\n\n}//simple_password\n}//sim_mob\n\n\n//int main(int argc, char * argv[])\n//{\n//  std::ostringstream out;\n//  out << argv[1];\n//  std::string source = out.str();\n//    std::string dest;\n//    loadBinary(dest);\n//    decryptionFunc(dest);\n//    std::cout << dest << std::endl;\n//\n//\n//}\n", "meta": {"hexsha": "057a7f3c37be121626a25f5fda23fd3161c01f4b", "size": 2130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dev/Basic/shared/password/password.cpp", "max_stars_repo_name": "gusugusu1018/simmobility-prod", "max_stars_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2018-12-21T08:21:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T09:47:59.000Z", "max_issues_repo_path": "dev/Basic/shared/password/password.cpp", "max_issues_repo_name": "gusugusu1018/simmobility-prod", "max_issues_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T13:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-13T04:11:45.000Z", "max_forks_repo_path": "dev/Basic/shared/password/password.cpp", "max_forks_repo_name": "gusugusu1018/simmobility-prod", "max_forks_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-11-28T07:30:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T02:22:26.000Z", "avg_line_length": 23.152173913, "max_line_length": 162, "alphanum_fraction": 0.6258215962, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18066671193889206}}
{"text": "#include \"drake/systems/sensors/rgbd_sensor.h\"\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <utility>\n\n#include <Eigen/Dense>\n\n#include \"drake/common/text_logging.h\"\n#include \"drake/geometry/scene_graph.h\"\n#include \"drake/math/rigid_transform.h\"\n#include \"drake/math/rotation_matrix.h\"\n#include \"drake/systems/framework/diagram_builder.h\"\n#include \"drake/systems/primitives/zero_order_hold.h\"\n#include \"drake/systems/rendering/pose_vector.h\"\n#include \"drake/systems/sensors/camera_info.h\"\n#include \"drake/systems/sensors/image.h\"\n\nnamespace drake {\nnamespace systems {\nnamespace sensors {\n\nusing Eigen::Translation3d;\nusing geometry::FrameId;\nusing geometry::QueryObject;\nusing geometry::SceneGraph;\nusing geometry::render::ColorRenderCamera;\nusing geometry::render::DepthRange;\nusing geometry::render::DepthRenderCamera;\nusing math::RigidTransformd;\nusing std::make_pair;\nusing std::move;\nusing std::pair;\n\nRgbdSensor::RgbdSensor(FrameId parent_id, const RigidTransformd& X_PB,\n                       const DepthRenderCamera& depth_camera,\n                       bool show_color_window)\n    : RgbdSensor(parent_id, X_PB,\n                 ColorRenderCamera(depth_camera.core(), show_color_window),\n                 depth_camera) {}\n\nRgbdSensor::RgbdSensor(FrameId parent_id, const RigidTransformd& X_PB,\n                       ColorRenderCamera color_camera,\n                       DepthRenderCamera depth_camera)\n    : parent_frame_id_(parent_id),\n      color_camera_(move(color_camera)),\n      depth_camera_(move(depth_camera)),\n      X_PB_(X_PB) {\n  const CameraInfo& color_intrinsics = color_camera_.core().intrinsics();\n  const CameraInfo& depth_intrinsics = depth_camera_.core().intrinsics();\n\n  query_object_input_port_ = &this->DeclareAbstractInputPort(\n      \"geometry_query\", Value<geometry::QueryObject<double>>{});\n\n  ImageRgba8U color_image(color_intrinsics.width(), color_intrinsics.height());\n  color_image_port_ = &this->DeclareAbstractOutputPort(\n      \"color_image\", color_image, &RgbdSensor::CalcColorImage);\n\n  ImageDepth32F depth32(depth_intrinsics.width(), depth_intrinsics.height());\n  depth_image_32F_port_ = &this->DeclareAbstractOutputPort(\n      \"depth_image_32f\", depth32, &RgbdSensor::CalcDepthImage32F);\n\n  ImageDepth16U depth16(depth_intrinsics.width(), depth_intrinsics.height());\n  depth_image_16U_port_ = &this->DeclareAbstractOutputPort(\n      \"depth_image_16u\", depth16, &RgbdSensor::CalcDepthImage16U);\n\n  ImageLabel16I label_image(color_intrinsics.width(),\n                            color_intrinsics.height());\n  label_image_port_ = &this->DeclareAbstractOutputPort(\n      \"label_image\", label_image, &RgbdSensor::CalcLabelImage);\n\n  X_WB_pose_port_ = &this->DeclareVectorOutputPort(\n      \"X_WB\", rendering::PoseVector<double>(), &RgbdSensor::CalcX_WB);\n\n  // The depth_16U represents depth in *millimeters*. With 16 bits there is\n  // an absolute limit on the farthest distance it can register. This tests to\n  // see if the user has specified a maximum depth value that exceeds that\n  // value.\n  const float kMaxValidDepth16UInM =\n      (std::numeric_limits<uint16_t>::max() - 1) / 1000.;\n  const double max_depth = depth_camera_.depth_range().max_depth();\n  if (max_depth > kMaxValidDepth16UInM) {\n    drake::log()->warn(\n        \"Specified max depth is {} m > max valid depth for 16 bits {} m. \"\n        \"depth_image_16u might not be able to capture the full depth range.\",\n        max_depth, kMaxValidDepth16UInM);\n  }\n}\n\nconst InputPort<double>& RgbdSensor::query_object_input_port() const {\n  return *query_object_input_port_;\n}\n\nconst OutputPort<double>& RgbdSensor::color_image_output_port() const {\n  return *color_image_port_;\n}\n\nconst OutputPort<double>& RgbdSensor::depth_image_32F_output_port() const {\n  return *depth_image_32F_port_;\n}\n\nconst OutputPort<double>& RgbdSensor::depth_image_16U_output_port() const {\n  return *depth_image_16U_port_;\n}\n\nconst OutputPort<double>& RgbdSensor::label_image_output_port() const {\n  return *label_image_port_;\n}\n\nconst OutputPort<double>& RgbdSensor::X_WB_output_port() const {\n  return *X_WB_pose_port_;\n}\n\nvoid RgbdSensor::CalcColorImage(const Context<double>& context,\n                                ImageRgba8U* color_image) const {\n  const QueryObject<double>& query_object = get_query_object(context);\n  query_object.RenderColorImage(\n      color_camera_, parent_frame_id_,\n      X_PB_ * color_camera_.core().sensor_pose_in_camera_body(), color_image);\n}\n\nvoid RgbdSensor::CalcDepthImage32F(const Context<double>& context,\n                                   ImageDepth32F* depth_image) const {\n  const QueryObject<double>& query_object = get_query_object(context);\n  query_object.RenderDepthImage(\n      depth_camera_, parent_frame_id_,\n      X_PB_ * depth_camera_.core().sensor_pose_in_camera_body(), depth_image);\n}\n\nvoid RgbdSensor::CalcDepthImage16U(const Context<double>& context,\n                                   ImageDepth16U* depth_image) const {\n  ImageDepth32F depth32(depth_image->width(), depth_image->height());\n  CalcDepthImage32F(context, &depth32);\n  ConvertDepth32FTo16U(depth32, depth_image);\n}\n\nvoid RgbdSensor::CalcLabelImage(const Context<double>& context,\n                                ImageLabel16I* label_image) const {\n  const QueryObject<double>& query_object = get_query_object(context);\n  query_object.RenderLabelImage(\n      color_camera_, parent_frame_id_,\n      X_PB_ * color_camera_.core().sensor_pose_in_camera_body(), label_image);\n}\n\nvoid RgbdSensor::CalcX_WB(const Context<double>& context,\n                          rendering::PoseVector<double>* pose_vector) const {\n  // Calculates X_WB.\n  RigidTransformd X_WB;\n  if (parent_frame_id_ == SceneGraph<double>::world_frame_id()) {\n    X_WB = X_PB_;\n  } else {\n    const QueryObject<double>& query_object = get_query_object(context);\n    X_WB = query_object.GetPoseInWorld(parent_frame_id_) * X_PB_;\n  }\n\n  Translation3d trans{X_WB.translation()};\n  pose_vector->set_translation(trans);\n\n  pose_vector->set_rotation(X_WB.rotation().ToQuaternion());\n}\n\nvoid RgbdSensor::ConvertDepth32FTo16U(const ImageDepth32F& d32,\n                                      ImageDepth16U* d16) {\n  // Convert to mm and 16bits.\n  const float kDepth16UOverflowDistance =\n      std::numeric_limits<uint16_t>::max() / 1000.;\n  for (int w = 0; w < d16->width(); w++) {\n    for (int h = 0; h < d16->height(); h++) {\n      const double dist = std::min(d32.at(w, h)[0], kDepth16UOverflowDistance);\n      d16->at(w, h)[0] = static_cast<uint16_t>(dist * 1000);\n    }\n  }\n}\n\n// Note: Ideally, this would be inlined. However, inlining this caused GCC\n// to do something weird with GeometryState such that the rgbd_sensor_test.cc\n// was unable to instantiate an GeometryStateTester that GCC recognized as a\n// friend to GeometryState.\nconst geometry::QueryObject<double>& RgbdSensor::get_query_object(\n    const Context<double>& context) const {\n  return query_object_input_port().Eval<geometry::QueryObject<double>>(context);\n}\n\nRgbdSensorDiscrete::RgbdSensorDiscrete(std::unique_ptr<RgbdSensor> camera,\n                                       double period, bool render_label_image)\n    : camera_(camera.get()), period_(period) {\n  const auto& color_camera_info = camera->color_camera_info();\n  const auto& depth_camera_info = camera->depth_camera_info();\n\n  DiagramBuilder<double> builder;\n  builder.AddSystem(move(camera));\n  query_object_port_ =\n      builder.ExportInput(camera_->query_object_input_port(), \"geometry_query\");\n\n  // Color image.\n  const Value<ImageRgba8U> image_color(color_camera_info.width(),\n                                       color_camera_info.height());\n  const auto* const zoh_color =\n      builder.AddSystem<ZeroOrderHold>(period_, image_color);\n  builder.Connect(camera_->color_image_output_port(),\n                  zoh_color->get_input_port());\n  output_port_color_image_ =\n      builder.ExportOutput(zoh_color->get_output_port(), \"color_image\");\n\n  // Depth images.\n  const Value<ImageDepth32F> image_depth_32F(depth_camera_info.width(),\n                                             depth_camera_info.height());\n  const auto* const zoh_depth_32F =\n      builder.AddSystem<ZeroOrderHold>(period_, image_depth_32F);\n  builder.Connect(camera_->depth_image_32F_output_port(),\n                  zoh_depth_32F->get_input_port());\n  output_port_depth_image_32F_ =\n      builder.ExportOutput(zoh_depth_32F->get_output_port(), \"depth_image_32f\");\n\n  // Depth images.\n  const Value<ImageDepth16U> image_depth_16U(depth_camera_info.width(),\n                                             depth_camera_info.height());\n  const auto* const zoh_depth_16U =\n      builder.AddSystem<ZeroOrderHold>(period_, image_depth_16U);\n  builder.Connect(camera_->depth_image_16U_output_port(),\n                  zoh_depth_16U->get_input_port());\n  output_port_depth_image_16U_ =\n      builder.ExportOutput(zoh_depth_16U->get_output_port(), \"depth_image_16u\");\n\n  // Label image.\n  if (render_label_image) {\n    const Value<ImageLabel16I> image_label(color_camera_info.width(),\n                                           color_camera_info.height());\n    const auto* const zoh_label =\n        builder.AddSystem<ZeroOrderHold>(period_, image_label);\n    builder.Connect(camera_->label_image_output_port(),\n                    zoh_label->get_input_port());\n    output_port_label_image_ =\n        builder.ExportOutput(zoh_label->get_output_port(), \"label_image\");\n  }\n\n  // No need to place a ZOH on pose output.\n  X_WB_output_port_ = builder.ExportOutput(camera_->X_WB_output_port(), \"X_WB\");\n\n  builder.BuildInto(this);\n}\n\n}  // namespace sensors\n}  // namespace systems\n}  // namespace drake\n", "meta": {"hexsha": "92e660d087fa892d27b4352ef5439c97eb1aea0f", "size": 9679, "ext": "cc", "lang": "C++", "max_stars_repo_path": "systems/sensors/rgbd_sensor.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": "systems/sensors/rgbd_sensor.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": "systems/sensors/rgbd_sensor.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": 39.1862348178, "max_line_length": 80, "alphanum_fraction": 0.7119537142, "num_tokens": 2326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.18066670847019883}}
{"text": "\n#ifdef __i386__\n  #pragma message(\"i386 Architecture detected, disabling EIGEN VECTORIZATION\")\n  #define EIGEN_DONT_VECTORIZE\n  #define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT\n#else\n  #pragma message(\"64bit Architecture detected, enabling EIGEN VECTORIZATION\")\n#endif\n\n\n\n#include <ros/ros.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/point_cloud_conversion.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/ros/conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/common/centroid.h>\n#include <pcl_ros/transforms.h>\n#include <pcl/segmentation/extract_polygonal_prism_data.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/surface/convex_hull.h>\n#include <pcl/common/common.h>\n#include <boost/make_shared.hpp>\n#include <tf_conversions/tf_eigen.h>\n#include <tf/transform_listener.h>\n#include <tf/transform_broadcaster.h>\n#include <collision_avoidance_pick_and_place/GetTargetPose.h>\n#include <math.h>\n\n// alias\ntypedef pcl::PointCloud<pcl::PointXYZ> Cloud;\ntypedef boost::shared_ptr<tf::TransformListener> TransformListenerPtr;\n\n// constants\nconst std::string SENSOR_CLOUD_TOPIC = \"sensor_cloud\";\nconst std::string FILTERED_CLOUD_TOPIC = \"filtered_cloud\";\nconst std::string TARGET_RECOGNITION_SERVICE = \"target_recognition\";\n\n// defaults\nconst double BOX_SCALE = 1.2f;\nconst double ANGLE_TOLERANCE = 0.1f* (M_PI/180.0f);\n\n\nclass TargetRecognition\n{\npublic:\n\tTargetRecognition():\n\t\tbox_filter_scale_(BOX_SCALE),\n\t\tangle_tolerance_(ANGLE_TOLERANCE)\n\t{\n\n\t}\n\n\t~TargetRecognition()\n\t{\n\n\t}\n\n\tbool init()\n\t{\n\t\tros::NodeHandle nh;\n\t\tros::NodeHandle ph(\"~\");\n\n\t\t// read parameters\n\t\tif(ph.getParam(\"box_filter_scale\",box_filter_scale_) &&\n\t\t\t\tph.getParam(\"angle_tolerance\",angle_tolerance_))\n\t\t{\n\t\t\tROS_INFO_STREAM(\"target recognition read parameters successfully\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tROS_WARN_STREAM(\"target recognition did not find one or more parameters, using defaults\");\n\t\t}\n\n\t\t// initializing service server\n\t\ttarget_detection_server = nh.advertiseService(TARGET_RECOGNITION_SERVICE,&TargetRecognition::target_recognition_callback,this);\n\n\t\t// initializing publisher\n\t\tfiltered_cloud_publisher = nh.advertise<sensor_msgs::PointCloud2>(FILTERED_CLOUD_TOPIC,1);\n\n\t\t// initializing subscriber\n\t\tpoint_cloud_subscriber = nh.subscribe(SENSOR_CLOUD_TOPIC,1,&TargetRecognition::point_cloud_callback,this);\n\n\t\t// initializing transform listener\n\t\ttransform_listener_ptr = TransformListenerPtr(new tf::TransformListener(nh,ros::Duration(1.0f)));\n\n\t\t// initializing cloud messages\n\t\tfiltered_cloud_msg_ = sensor_msgs::PointCloud2();\n\n\t\treturn true;\n\n\t}\n\n\tvoid run()\n\t{\n\n\t\twhile(ros::ok())\n\t\t{\n\t\t\tros::Duration(0.2f).sleep();\n\t\t\tros::spinOnce();\n\t\t}\n\t}\n\nprotected:\n\n\tbool grab_sensor_snapshot(sensor_msgs::PointCloud2& msg)\n\t{\n\t\t// grab sensor data snapshot\n\t\tros::NodeHandle nh;\n\t\tsensor_msgs::PointCloud2ConstPtr msg_ptr =\n\t\t\t\tros::topic::waitForMessage<sensor_msgs::PointCloud2>(SENSOR_CLOUD_TOPIC,nh,\n\t\t\t\t\t\tros::Duration(5.0f));\n\n\t\t// check for empty message\n\t\tif(msg_ptr != sensor_msgs::PointCloud2ConstPtr())\n\t\t{\n\n\t\t\tmsg = *msg_ptr;\n\t\t}\n\n\t\treturn msg_ptr != sensor_msgs::PointCloud2ConstPtr();\n\t}\n\n\tvoid point_cloud_callback(const sensor_msgs::PointCloud2ConstPtr msg)\n\t{\n\t\tsensor_cloud_msg_ = sensor_msgs::PointCloud2(*msg);\n\t}\n\n\tbool target_recognition_callback(collision_avoidance_pick_and_place::GetTargetPose::Request& req,\n\t\t\tcollision_avoidance_pick_and_place::GetTargetPose::Response& res)\n\t{\n\t\t// transforms\n\t\ttf::StampedTransform world_to_sensor_tf;\n\t\ttf::Transform world_to_box_pick_tf;\n\t\ttf::Transform world_to_ar_tf;\n\t\ttf::Vector3 box_pick_position;\n\n\t\t// updating global variables\n\t\tbox_length_ = req.shape.dimensions[0];\n\t\tbox_width_ = req.shape.dimensions[1];\n\t\tbox_height_ = req.shape.dimensions[2];\n\t\tworld_frame_id_ = req.world_frame_id;\n\t\tar_frame_id_ = req.ar_tag_frame_id;\n\n\t\t// get point cloud message\n\t\tsensor_msgs::PointCloud2 msg = sensor_cloud_msg_;\n\t\tif(msg.data.size() == 0)\n\t\t{\n\t\t\t\tROS_ERROR_STREAM(\"Cloud message is invalid, returning detection failure\");\n\t\t\t\tres.succeeded = false;\n\t\t\t\treturn true;\n\t\t}\n\n\t\t// looking up transforms\n\t\tif(get_transform(world_frame_id_ , ar_frame_id_,world_to_ar_tf) &&\n\t\t\t\tget_transform(world_frame_id_,msg.header.frame_id,world_to_sensor_tf))\n\t\t{\n\n\n\t\t\t// convert from message to point cloud\n\t\t\tCloud::Ptr sensor_cloud_ptr(new Cloud());\n\t\t\tpcl::fromROSMsg<pcl::PointXYZ>(msg,*sensor_cloud_ptr);\n\n\t\t\t// applying statistical removal\n\t\t\tpcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor;\n\t\t\tsor.setInputCloud (sensor_cloud_ptr);\n\t\t\tsor.setMeanK (50);\n\t\t\tsor.setStddevMulThresh (1.0);\n\t\t\tsor.filter (*sensor_cloud_ptr);\n\n\t\t\t// creating cloud message for publisher\n\t\t\tCloud::Ptr filtered_cloud_ptr(new Cloud());\n\n\t\t\t// converting to world coordinates\n\t\t\tEigen::Affine3d eigen_3d;\n\t\t\ttf::transformTFToEigen(world_to_sensor_tf,eigen_3d);\n\t\t\tEigen::Affine3f eigen_3f(eigen_3d);\n\t\t\tpcl::transformPointCloud(*sensor_cloud_ptr,*sensor_cloud_ptr,eigen_3f);\n\n\t\t\t// find height of box top surface\n\t\t\tdouble height;\n\t\t\tif(!detect_box_height(*sensor_cloud_ptr,world_to_ar_tf,height) )\n\t\t\t{\n\t\t\t\tROS_ERROR_STREAM(\"Target height detection failed\");\n\t\t\t\tres.succeeded = false;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// updating box pick transform\n\t\t\tworld_to_box_pick_tf = world_to_ar_tf;\n\t\t\tbox_pick_position = world_to_box_pick_tf.getOrigin();\n\t\t\tbox_pick_position.setZ(height);\n\t\t\tworld_to_box_pick_tf.setOrigin(box_pick_position);\n\n\t\t\t// filtering box from sensor cloud\n\t\t\tfilter_box(world_to_sensor_tf,\n\t\t\t\t\tworld_to_box_pick_tf,*sensor_cloud_ptr,*filtered_cloud_ptr);\n\n\t\t\t// filter box at requested locations\n\t\t\tfor(unsigned int i =0;i < req.remove_at_poses.size();i++)\n\t\t\t{\n\t\t\t\ttf::Transform world_to_box;\n\t\t\t\ttf::poseMsgToTF(req.remove_at_poses[i],world_to_box);\n\n\t\t\t\t// copying last filter cloud\n\t\t\t\tpcl::copyPointCloud(*filtered_cloud_ptr,*sensor_cloud_ptr);\n\n\t\t\t\t// filter box from last computed cloud\n\t\t\t\tfilter_box(world_to_sensor_tf,world_to_box,*sensor_cloud_ptr,*filtered_cloud_ptr);\n\t\t\t}\n\n\t\t\t// transforming to world frame\n\t\t\tpcl::transformPointCloud(*filtered_cloud_ptr,*filtered_cloud_ptr,eigen_3f.inverse());\n\n\t\t\t// converting to message\n\t\t\tfiltered_cloud_msg_ = sensor_msgs::PointCloud2();\n\t\t\tpcl::toROSMsg(*filtered_cloud_ptr,filtered_cloud_msg_);\n\n\t\t\t// populating response\n\t\t\ttf::poseTFToMsg(world_to_box_pick_tf,res.target_pose);\n\t\t\tres.succeeded = true ;\n\n\t\t\t// publishing cloud\n\t\t\tfiltered_cloud_msg_.header.stamp = ros::Time::now()-ros::Duration(0.5f);\n\t\t\tfiltered_cloud_publisher.publish(filtered_cloud_msg_);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres.succeeded = false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool get_transform(std::string target,std::string source,tf::Transform& trg_to_src_tf)\n\t{\n\t\t// create tf listener and broadcaster\n\t\t//static tf::TransformListener tf_listener;\n\t\ttf::StampedTransform trg_to_src_stamped;\n\n\t\t// find ar tag transform\n\t\ttry\n\t\t{\n\t\t\ttransform_listener_ptr->waitForTransform(target,source,ros::Time::now(),ros::Duration(4.0f));\n\t\t\ttransform_listener_ptr->lookupTransform(target,source,ros::Time::now() - ros::Duration(0.2f),trg_to_src_stamped);\n\n\t\t\t// copying transform data\n\t\t\ttrg_to_src_tf.setRotation( trg_to_src_stamped.getRotation());\n\t\t\ttrg_to_src_tf.setOrigin(trg_to_src_stamped.getOrigin());\n\n\t\t}\n\t\tcatch(tf::LookupException &e)\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"transform lookup for '\"<<ar_frame_id_<<\"' failed\");\n\t\t\treturn false;\n\t\t}\n\t\tcatch(tf::ExtrapolationException &e)\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"transform lookup for '\"<<ar_frame_id_<<\"' failed\");\n\t\t\treturn false;\n\t\t}\n\t\tcatch(tf::TransformException &e)\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"transform lookup for '\"<<ar_frame_id_<<\"' failed\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool detect_box_height(const Cloud& cloud,\n\t\t\tconst tf::Transform &world_to_ar_tf,double& height )\n\t{\n\t\t// cloud objects\n\t\tCloud::Ptr cloud_ptr= boost::make_shared<Cloud>(cloud);\n\t\tCloud::Ptr filtered_cloud_ptr(new Cloud);\n\n\t\t// applying filter in x axis\n\t\tfloat min = world_to_ar_tf.getOrigin().x() - 0.2f*box_length_;\n\t\tfloat max = world_to_ar_tf.getOrigin().x() + 0.2f*box_length_;\n\t\tpcl::PassThrough<pcl::PointXYZ> filter;\n\t\tfilter.setInputCloud(cloud_ptr);\n\t\tfilter.setFilterFieldName(\"x\");\n\t\tfilter.setFilterLimits(min,max);\n\t\tfilter.filter(*filtered_cloud_ptr);\n\n\t\t// applying filter in y axis\n\t\tmin = world_to_ar_tf.getOrigin().y()- 0.2f*box_width_;\n\t\tmax = world_to_ar_tf.getOrigin().y() + 0.2f*box_width_;;\n\t\tfilter.setInputCloud(filtered_cloud_ptr);\n\t\tfilter.setFilterFieldName(\"y\");\n\t\tfilter.setFilterLimits(min,max);\n\t\tfilter.filter(*filtered_cloud_ptr);\n\n\t\t// computing centroid\n\t\tEigen::Vector4f centroid;\n\t\tint count = pcl::compute3DCentroid(*filtered_cloud_ptr,centroid);\n\t\theight = centroid[2];\n\n\t\tROS_INFO_STREAM(\"Detected height is: \"<<centroid[2]);\n\n\t\t// return z value\n\t\treturn count != 0;\n\t}\n\n\tvoid filter_box(const tf::Transform& world_to_sensor_tf,\n\t\tconst tf::Transform& world_to_box_pick_tf,const Cloud &sensor_cloud,\n\t\tCloud& filtered_cloud)\n{\n\t// creating surface with center at box pick location\n\tCloud::Ptr pick_surface_cloud_ptr(new Cloud());\n\n\t// adding surface points to cloud\n\tpick_surface_cloud_ptr->width = 5;\n\tpick_surface_cloud_ptr->height = 1;\n\tpick_surface_cloud_ptr->points.resize(5);\n\n\tpick_surface_cloud_ptr->points[0].x = 0.5f*box_filter_scale_*box_length_;\n\tpick_surface_cloud_ptr->points[0].y = 0.5f*box_filter_scale_*box_width_;\n\tpick_surface_cloud_ptr->points[0].z = 0;\n\n\tpick_surface_cloud_ptr->points[1].x = -0.5f*box_filter_scale_*box_length_;\n\tpick_surface_cloud_ptr->points[1].y = 0.5f*box_filter_scale_*box_width_;\n\tpick_surface_cloud_ptr->points[1].z = 0;\n\n\tpick_surface_cloud_ptr->points[2].x = -0.5f*box_filter_scale_*box_length_;\n\tpick_surface_cloud_ptr->points[2].y = -0.5f*box_filter_scale_*box_width_;\n\tpick_surface_cloud_ptr->points[2].z = 0;\n\n\tpick_surface_cloud_ptr->points[3].x = 0.5f*box_filter_scale_*box_length_;\n\tpick_surface_cloud_ptr->points[3].y = -0.5f*box_filter_scale_*box_width_;\n\tpick_surface_cloud_ptr->points[3].z = 0;\n\n\tpick_surface_cloud_ptr->points[4].x = 0.5f*box_filter_scale_*box_length_;\n\tpick_surface_cloud_ptr->points[4].y = 0.5f*box_filter_scale_*box_width_;\n\tpick_surface_cloud_ptr->points[4].z = 0;\n\n\tROS_INFO_STREAM(\"Points in surface: \"<<pick_surface_cloud_ptr->points.size());\n\n\t// finding angle between world z and box z vectors\n\ttf::Vector3 z_world_vect(0,0,1);\n\ttf::Vector3 z_box_vect = world_to_box_pick_tf.getBasis().getColumn(2);\n\tdouble angle  = z_world_vect.angle(z_box_vect);\n\tROS_INFO_STREAM(\"Angle between z vectors : \"<<angle);\n\n\n\t// transforming cloud to match orientation of box (rectify in the z direction)\n\ttf::Vector3 axis = z_world_vect.cross(z_box_vect);\n\ttf::Transform world_to_rectified_box_tf = world_to_box_pick_tf;\n\tEigen::Affine3d eigen3d;\n\tif(std::abs(angle) > angle_tolerance_)\n\t{\n\t\tROS_INFO_STREAM(\"Rectifying pick pose z direction\");\n\t\tworld_to_rectified_box_tf.setRotation(world_to_box_pick_tf.getRotation() * tf::Quaternion(axis,-angle)) ;\n\t}\n\n\ttf::transformTFToEigen(world_to_rectified_box_tf,eigen3d);\n\tpcl::transformPointCloud(*pick_surface_cloud_ptr,*pick_surface_cloud_ptr,Eigen::Affine3f(eigen3d));\n\n\n\t// extracting points in extruded volume\n\tCloud::Ptr sensor_cloud_ptr = boost::make_shared<Cloud>(sensor_cloud);\n\tpcl::ExtractPolygonalPrismData<pcl::PointXYZ> prism;\n\tpcl::ExtractIndices<pcl::PointXYZ> extract;\n\tpcl::PointIndices::Ptr inliers(new pcl::PointIndices());\n\n\tROS_INFO_STREAM(\"Sensor cloud points: \"<<sensor_cloud_ptr->points.size());\n\n\ttf::Vector3 viewpoint = world_to_sensor_tf.getOrigin();\n\tprism.setInputCloud(sensor_cloud_ptr);\n\tprism.setInputPlanarHull( pick_surface_cloud_ptr);\n\tprism.setHeightLimits(-10,10);\n\t//prism.setViewPoint(viewpoint.x(),viewpoint.y(),viewpoint.z());\n\tprism.segment(*inliers);\n\n\t//pcl::copyPointCloud(*sensor_cloud_ptr,indices.indices,filtered_cloud);\n\t// extracting remaining points\n\textract.setInputCloud(sensor_cloud_ptr);\n\textract.setIndices(inliers);\n\textract.setNegative(true);\n\textract.filter(filtered_cloud);\n\n\tROS_INFO_STREAM(\"Filtered cloud points: \"<<filtered_cloud.points.size());\n\n}\n\nprotected:\n\n\t// members\n\tstd::string ar_frame_id_;\n\tstd::string world_frame_id_;\n\tfloat box_width_;\n\tfloat box_length_;\n\tfloat box_height_;\n\tsensor_msgs::PointCloud2 filtered_cloud_msg_;\n\tsensor_msgs::PointCloud2 sensor_cloud_msg_;\n\n\t// ros parameter\n\tdouble box_filter_scale_;\n\tdouble angle_tolerance_;\n\n\t// ros service server\n\tros::ServiceServer target_detection_server;\n\n\t// ros subscriber\n\tros::Subscriber point_cloud_subscriber;\n\n\t// ros publishers and subscribers\n\tros::Publisher filtered_cloud_publisher;\n\n\t// transform listener\n\tTransformListenerPtr transform_listener_ptr;\n\n};\n// main program\nint main(int argc,char** argv)\n{\n\tros::init(argc,argv,\"target_recognition_node\");\n\n\tTargetRecognition tg;\n\tif(tg.init())\n\t{\n\t\ttg.run();\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "0b1262a447adcb164de1f4e3502cac10f49a3d3b", "size": 12864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "training/work/demo_manipulation/src/collision_avoidance_pick_and_place/src/services/target_recognition_service.cpp", "max_stars_repo_name": "asct/industrial_training", "max_stars_repo_head_hexsha": "f69c54cad966382ce93b34138696a99abc66f444", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-11-30T12:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T07:43:54.000Z", "max_issues_repo_path": "training/work/demo_manipulation/src/collision_avoidance_pick_and_place/src/services/target_recognition_service.cpp", "max_issues_repo_name": "asct/industrial_training", "max_issues_repo_head_hexsha": "f69c54cad966382ce93b34138696a99abc66f444", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-03T03:29:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T03:29:15.000Z", "max_forks_repo_path": "training/work/demo_manipulation/src/collision_avoidance_pick_and_place/src/services/target_recognition_service.cpp", "max_forks_repo_name": "asct/industrial_training", "max_forks_repo_head_hexsha": "f69c54cad966382ce93b34138696a99abc66f444", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T15:24:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T01:05:37.000Z", "avg_line_length": 29.7777777778, "max_line_length": 129, "alphanum_fraction": 0.7586287313, "num_tokens": 3432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.3451052844289766, "lm_q1q2_score": 0.1806351335267709}}
{"text": "//\n// Created by System Administrator on 2019-07-29.\n//\n\n\n\n\n#include <tins/tins.h>\n#include <unordered_map>\n#include <unordered_set>\n#include <boost/functional/hash.hpp>\n\n\n#include <maths/stopping_points_t.hpp>\n#include <node_t.hpp>\n\n\nusing namespace Tins;\n\nint main(int argc, char ** argv){\n\n    uint8_t max_ttl = 8;\n\n    // Edges\n    using edges_t = std::unordered_set<std::pair<uint32_t , uint32_t >, boost::hash<std::pair<uint32_t , uint32_t >>>;\n\n    // In memory structure for the MDA. Tree structure with probabilities of each node to get reached.\n    using probability_tree_t = std::vector<std::unordered_map<uint32_t, node_t>>;\n    probability_tree_t probability_tree(max_ttl);\n\n    PacketSender sender{NetworkInterface::default_interface()};\n\n    for (uint8_t ttl = 2; ttl < max_ttl; ++ttl){\n        // BFS into the tree.\n        bool is_ttl_done = false;\n        while(!is_ttl_done){\n            // Dispatch the probes into different prefixes according to the distribution\n            std::vector<IP> probes;\n\n            for (const auto & reply_ip_routing_table : probability_tree[ttl]){\n\n                // Each prefix of the routing table is considered as a possible source of multiple paths.\n                // As far as new paths are found within a prefix, we split the prefix in smaller prefixes.\n                // The stopping condition occurs when a prefix reach some statistical guarantees?\n                const auto & routing_table_distribution = reply_ip_routing_table.second.routing_table_distribution;\n                for (const auto & prefix_tracenodes : routing_table_distribution){\n                    // Extract number of successors\n                    const auto & tracenodes = prefix_tracenodes.second;\n                    std::unordered_set<uint32_t> successors;\n                    std::transform(tracenodes.begin(), tracenodes.end(), std::inserter(successors, successors.begin()), [](const auto & tracenode){\n                        return tracenode.reply_ip;\n                    });\n\n                    auto n_successors = successors.size();\n                    if (tracenodes.size() < mda_maths::nks95[])\n\n\n                }\n\n\n            }\n\n            // Update the graph routing table after receiving the answers.\n\n\n        }\n\n\n\n    }\n\n}", "meta": {"hexsha": "4c03e7b8167fa591deabd755209bc63e15fe5a0d", "size": 2278, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_probabilistic.cpp", "max_stars_repo_name": "dioptra-io/diamond-miner-cpp", "max_stars_repo_head_hexsha": "8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5", "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_probabilistic.cpp", "max_issues_repo_name": "dioptra-io/diamond-miner-cpp", "max_issues_repo_head_hexsha": "8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5", "max_issues_repo_licenses": ["MIT"], "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_probabilistic.cpp", "max_forks_repo_name": "dioptra-io/diamond-miner-cpp", "max_forks_repo_head_hexsha": "8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-03T14:51:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-03T14:51:43.000Z", "avg_line_length": 31.6388888889, "max_line_length": 147, "alphanum_fraction": 0.6303775241, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.18063511429348428}}
{"text": "#include <array>\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <cstdlib>\n#include <iostream>\n#include <random>\n#include <set>\n\nusing namespace std;\n\nnamespace tetris {\nconst int BOARD_WIDTH = 10;\nconst int BOARD_HEIGHT = 20;\nconst int PIECE_SIZE = 4;\nconst int ROTATIONS = 4;\nconst int NUM_SHAPES = 8;\n\n// Scores for 0, 1, 2, ..., n line clears with a single placement\nconst array<int, 5> SCORES = {{0, 40, 100, 300, 1200}};\n\nconst array<array<bool, PIECE_SIZE>, PIECE_SIZE> BLANK_SHAPE = {\n    {{false, false, false, false},\n     {false, false, false, false},\n     {false, false, false, false},\n     {false, false, false, false}}};\nconst array<array<bool, PIECE_SIZE>, PIECE_SIZE> STRAIGHT_SHAPE = {\n    {{false, false, false, false},\n     {true, true, true, true},\n     {false, false, false, false},\n     {false, false, false, false}}};\nconst array<array<bool, PIECE_SIZE>, PIECE_SIZE> L_SHAPE = {\n    {{false, false, false, false},\n     {false, true, true, false},\n     {false, true, false, false},\n     {false, true, false, false}}};\nconst array<array<bool, PIECE_SIZE>, PIECE_SIZE> FLIPPED_L_SHAPE = {\n    {{false, false, false, false},\n     {false, true, true, false},\n     {false, false, true, false},\n     {false, false, true, false}}};\nconst array<array<bool, PIECE_SIZE>, PIECE_SIZE> ZIG_ZAG_SHAPE = {\n    {{false, false, true, false},\n     {false, true, true, false},\n     {false, true, false, false},\n     {false, false, false, false}}};\nconst array<array<bool, PIECE_SIZE>, PIECE_SIZE> FLIPPED_ZIG_ZAG_SHAPE = {\n    {{false, true, false, false},\n     {false, true, true, false},\n     {false, false, true, false},\n     {false, false, false, false}}};\nconst array<array<bool, PIECE_SIZE>, PIECE_SIZE> SQUARE_SHAPE = {\n    {{false, false, false, false},\n     {false, true, true, false},\n     {false, true, true, false},\n     {false, false, false, false}}};\nconst array<array<bool, PIECE_SIZE>, PIECE_SIZE> T_SHAPE = {\n    {{false, false, false, false},\n     {true, true, true, false},\n     {false, true, false, false},\n     {false, false, false, false}}};\n\nconst array<array<array<bool, PIECE_SIZE>, PIECE_SIZE>, NUM_SHAPES> SHAPES = {\n    BLANK_SHAPE,   STRAIGHT_SHAPE,        L_SHAPE,      FLIPPED_L_SHAPE,\n    ZIG_ZAG_SHAPE, FLIPPED_ZIG_ZAG_SHAPE, SQUARE_SHAPE, T_SHAPE};\n}\n\nusing namespace tetris;\n\ntypedef vector<int> VectorInt;\ntypedef vector<bool> VectorBool;\n\nclass Piece {\n private:\n  array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape = {{false}};\n  int row;\n  int col;\n  int rot;\n  int pieceIndex;\n\n public:\n  explicit Piece(array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape)\n      : Piece(shape, 0, 3) {}\n\n  explicit Piece(array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape, int row,\n                 int col) {\n    this->shape = shape;\n    this->row = row;\n    this->col = col;\n    this->rot = 0;\n  }\n\n  explicit Piece(int pieceIndex, int row, int col, int rot) {\n    this->pieceIndex = pieceIndex;\n    this->row = row;\n    this->col = col;\n    this->rot = rot;\n  }\n\n  explicit Piece() {}\n\n  void rotate() {\n    for (int r = 0; r < PIECE_SIZE / 2; r++) {\n      int rowInverse = PIECE_SIZE - r - 1;\n      for (int c = r; c < rowInverse; c++) {\n        int colInverse = PIECE_SIZE - c - 1;\n\n        int temp = shape[r][c];\n        shape[r][c] = shape[c][rowInverse];\n\n        shape[c][rowInverse] = shape[rowInverse][colInverse];\n\n        shape[rowInverse][colInverse] =\n            shape[colInverse][r];\n\n        shape[colInverse][r] = temp;\n      }\n    }\n\n    rot = (rot + 1) % ROTATIONS;\n  }\n\n  array<array<bool, PIECE_SIZE>, PIECE_SIZE> getShape() { return shape; }\n\n  int getRow() { return row; }\n\n  int getCol() { return col; }\n\n  void setRow(int newRow) { row = newRow; }\n\n  void setCol(int newCol) { col = newCol; }\n\n  void setPos(int newRow, int newCol) {\n    setRow(newRow);\n    setCol(newCol);\n  }\n\n  void setRot(int newRot) {\n    while (rot != newRot) rotate();\n  }\n};\n\nclass Board {\n private:\n  vector<VectorInt> currentMoves;\n  Piece* pieces[7] = {};\n  bool board[BOARD_HEIGHT][BOARD_WIDTH] = {{false}};\n  // bool board[BOARD_HEIGHT][BOARD_WIDTH] = {false};\n  int score = 0;\n  // Keeps track of visited branches (prevents infinite recursion)\n  bool visited[BOARD_HEIGHT + PIECE_SIZE][BOARD_WIDTH + PIECE_SIZE][ROTATIONS] =\n      {{false}};\n  // Keeps track of which branches are valid: 0 means not yet determined, -1\n  // means invalid, 1 means valid\n  int memo[BOARD_HEIGHT + PIECE_SIZE][BOARD_WIDTH + PIECE_SIZE][ROTATIONS] = {\n      {0}};\n\n  set<array<int, 3>> getMoves(Piece *piece, int row, int col, int rot) {\n    resetVisited();\n    piece->setRot(rot);\n\n    array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape = piece->getShape();\n\n    set<array<int, 3>> moves;\n\n    for (int r = 0; r < PIECE_SIZE; r++) {\n      for (int c = 0; c < PIECE_SIZE; c++) {\n        if (shape[r][c]) {\n          if (isMoveValid(piece, row - r, col - c, rot)) {\n            moves.insert({{row - r, col - c, rot}});\n          }\n\n          resetVisited();\n          piece->setRot(rot);\n        }\n      }\n    }\n\n    return moves;\n  }\n\n  void resetMemo() {\n    for (int i = 0; i < BOARD_HEIGHT + PIECE_SIZE; i++) {\n      for (int j = 0; j < BOARD_WIDTH + PIECE_SIZE; j++) {\n        for (int k = 0; k < ROTATIONS; k++) {\n          memo[i][j][k] = 0;\n        }\n      }\n    }\n  }\n\n  void resetVisited() {\n    for (int i = 0; i < BOARD_HEIGHT + PIECE_SIZE; i++) {\n      for (int j = 0; j < BOARD_WIDTH + PIECE_SIZE; j++) {\n        for (int k = 0; k < ROTATIONS; k++) {\n          visited[i][j][k] = false;\n        }\n      }\n    }\n  }\n\n  // Recursively checks if the piece would be able to reach the given position\n  // from the starting position (0, 3)\n  bool isMoveValid(Piece *piece, int row, int col, int rot) {\n    // Already visited this branch, terminate\n    if (visited[row + PIECE_SIZE][col + PIECE_SIZE][rot])\n      return false;\n    else if (memo[row + PIECE_SIZE][col + PIECE_SIZE][rot] < 0)\n      return false;\n    else if (memo[row + PIECE_SIZE][col + PIECE_SIZE][rot] > 0)\n      return true;\n\n    visited[row + PIECE_SIZE][col + PIECE_SIZE][rot] = true;\n\n    array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape = piece->getShape();\n\n    for (int r = 0; r < PIECE_SIZE; r++) {\n      for (int c = 0; c < PIECE_SIZE; c++) {\n        if (shape[r][c] &&\n            (isOutOfBounds(row + r, col + c) || board[row + r][col + c])) {\n          memo[row + PIECE_SIZE][col + PIECE_SIZE][rot] = -1;\n          return false;\n        }\n      }\n    }\n\n    bool foundFirstBlock = false;\n    for (int r = 0; r < PIECE_SIZE; r++) {\n        for (int c = 0; c < PIECE_SIZE; c++) {\n            if (shape[r][c]) {\n                // This is where the piece always starts in Tetris\n                if (!foundFirstBlock && row + r == 0 && col + c == 3) {\n                    memo[row + PIECE_SIZE][col + PIECE_SIZE][rot] = 1;\n                    return true;\n                }\n                foundFirstBlock = true;\n            }\n        }\n    }\n\n    bool canAccess = isMoveValid(piece, row - 1, col, rot) ||\n                     isMoveValid(piece, row, col - 1, rot) ||\n                     isMoveValid(piece, row, col + 1, rot);\n\n    if (canAccess) {\n      memo[row + PIECE_SIZE][col + PIECE_SIZE][rot] = 1;\n      return true;\n    }\n\n    for (int n = 1; n < ROTATIONS; n++) {\n      int newRot = (rot + n) % ROTATIONS;\n      piece->setRot(newRot);\n      if (isMoveValid(piece, row, col, newRot)) {\n        memo[row + PIECE_SIZE][col + PIECE_SIZE][rot] = 1;\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  void deleteRow(int row) {\n    for (int r = row; r > 0; r--) {\n      for (int c = 0; c < BOARD_WIDTH; c++) {\n        board[r][c] = board[r - 1][c];\n      }\n    }\n  }\n\n  bool isRowCompleted(int row) {\n    for (int c = 0; c < BOARD_WIDTH; c++) {\n      if (!board[row][c]) return false;\n    }\n\n    return true;\n  }\n\n  static bool isOutOfBounds(int row, int col) {\n    return row < 0 || row >= BOARD_HEIGHT || col < 0 || col >= BOARD_WIDTH;\n  }\n\n public:\n  Board() {\n    int i = 0;\n    pieces[i++] = new Piece(STRAIGHT_SHAPE);\n    pieces[i++] = new Piece(L_SHAPE);\n    pieces[i++] = new Piece(FLIPPED_L_SHAPE);\n    pieces[i++] = new Piece(ZIG_ZAG_SHAPE);\n    pieces[i++] = new Piece(FLIPPED_ZIG_ZAG_SHAPE);\n    pieces[i++] = new Piece(SQUARE_SHAPE);\n    pieces[i++] = new Piece(T_SHAPE);\n  }\n\n  // Returns a set of possible moves in format: (row, col, rot)\n  set<array<int, 3>> getMoves(Piece *piece) {\n    resetMemo();\n\n    set<array<int, 3>> moves;\n\n    for (int r = 0; r < BOARD_HEIGHT; r++) {\n      for (int c = 0; c < BOARD_WIDTH; c++) {\n        if (!board[r][c] && (r + 1 >= BOARD_HEIGHT || board[r + 1][c])) {\n          for (int rot = 0; rot < ROTATIONS; rot++) {\n            set<array<int, 3>> partialMoves = getMoves(piece, r, c, rot);\n            moves.insert(partialMoves.begin(), partialMoves.end());\n          }\n        }\n      }\n    }\n\n    return moves;\n  }\n\n  // Returns a set of possible moves in format: (pieceIndex, row, col, rot)\n  set<array<int, 4>> getMoves(array<Piece *, 7> pieces) {\n    set<array<int, 4>> moves;\n\n    int i = 0;\n    for (Piece *piece : pieces) {\n      set<array<int, 3>> partialMoves = getMoves(piece);\n      for (array<int, 3> move : partialMoves) {\n        moves.insert({i, move[0], move[1], move[2]});\n      }\n      i++;\n    }\n\n    return moves;\n  }\n\n  void place(Piece *piece) {\n    array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape = piece->getShape();\n    int row = piece->getRow();\n    int col = piece->getCol();\n\n    int rowsCompleted = 0;\n    for (int r = 0; r < PIECE_SIZE; r++) {\n      for (int c = 0; c < PIECE_SIZE; c++) {\n        if (!isOutOfBounds(row + r, col + c))\n            board[row + r][col + c] |= shape[r][c];\n      }\n\n      if (isRowCompleted(row + r)) {\n        deleteRow(row + r);\n        rowsCompleted++;\n      }\n    }\n\n    score += SCORES[rowsCompleted];\n  }\n\n  void render(Piece *piece) {\n    array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape = piece->getShape();\n    int row = piece->getRow();\n    int col = piece->getCol();\n\n    for (int r = 0; r < BOARD_HEIGHT; r++) {\n      for (int c = 0; c < BOARD_WIDTH; c++) {\n        bool renderPiece = r - row >= 0 && r - row < PIECE_SIZE &&\n                           c - col >= 0 && c - col < PIECE_SIZE &&\n                           shape[r - row][c - col];\n\n        if (renderPiece) {\n          cout << \"O\";\n        } else if (board[r][c]) {\n          cout << \"X\";\n        } else {\n          cout << \"-\";\n        }\n      }\n      cout << \"\\n\";\n    }\n    cout << endl;\n  }\n\n  // wrap\n  vector<VectorInt> getMoves() {\n    currentMoves.clear();\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> distribution(0, 6);\n    int randomIndex = distribution(gen);\n    auto *piece = pieces[randomIndex];\n\n    // vector<VectorInt> moves;\n    set<array<int, 3>> partialMoves = getMoves(piece);\n\n    for (array<int, 3> move : partialMoves) {\n      currentMoves.push_back({randomIndex, move[0], move[1], move[2]});\n    }\n\n    return currentMoves;\n  }\n\n  int getNumberOfMoves() { return currentMoves.size(); }\n\n  // wrap\n  void printMoves(const vector<VectorInt> &vvi) {\n    for (int i = 0; i < vvi.size(); i++) {\n      for (int j = 0; j < vvi[i].size(); j++) {\n        cout << vvi[i][j] << \" \";\n      }\n      cout << endl;\n    }\n  }\n\n  // wrap\n  void place(int pieceIndex, int row, int col, int rot) {\n    auto *piece = pieces[pieceIndex];\n    piece->setRow(row);\n    piece->setCol(col);\n    piece->setRot(rot);\n    place(piece);\n  }\n\n  // wrap\n  vector<VectorBool> rend(int pieceIndex, int row, int col, int rot) {\n    auto *piece = pieces[pieceIndex];\n    piece->setRot(rot);\n    array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape = piece->getShape();\n\n    vector<VectorBool> newBoard;\n    VectorBool vb;\n\n    for (int r = 0; r < BOARD_HEIGHT; r++) {\n      for (int c = 0; c < BOARD_WIDTH; c++) {\n        bool renderPiece = r - row >= 0 && r - row < PIECE_SIZE &&\n                           c - col >= 0 && c - col < PIECE_SIZE &&\n                           shape[r - row][c - col];\n\n        vb.push_back(renderPiece || board[r][c]);\n      }\n      newBoard.push_back(vb);\n      vb.clear();\n    }\n\n    return newBoard;\n  }\n\n  int getValueOfVectorInts(vector<VectorInt> &vvi, int i, int j) {\n    return vvi[i][j];\n  }\n\n  bool getValueOfVectorBools(vector<VectorBool> &vvb, int i, int j) {\n    return vvb[i][j];\n  }\n\n  int getScore() { return score; }\n\n  void reset() {\n    resetMemo();\n    resetVisited();\n    score = 0;\n\n    for (int row = 0; row < BOARD_HEIGHT; row++) {\n      for (int col = 0; col < BOARD_WIDTH; col++) {\n        board[row][col] = false;\n      }\n    }\n  }\n\n  // Returns true if piece can fit on board\n  bool isValid(Piece *piece) {\n    array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape = piece->getShape();\n    int row = piece->getRow();\n    int col = piece->getCol();\n\n    for (int r = 0; r < PIECE_SIZE; r++) {\n      for (int c = 0; c < PIECE_SIZE; c++) {\n        if (shape[r][c] &&\n            (isOutOfBounds(row + r, col + c) || board[row + r][col + c])) {\n          return false;\n        }\n      }\n    }\n\n    return true;\n  }\n\n  // Returns true if piece can fit on board\n  bool isValid(int pieceIndex, int row, int col, int rot) {\n    auto *piece = pieces[pieceIndex];\n    piece->setRow(row);\n    piece->setCol(col);\n    piece->setRot(rot);\n    return isValid(piece);\n  }\n\n  // wrap\n  void printRend(const vector<VectorBool> &vvb) {\n    for (int i = 0; i < vvb.size(); i++) {\n      for (int j = 0; j < vvb[i].size(); j++) {\n        // cout << \"vvb[\" << i << \"][\" << j << \"] = \" << vvb[i][j] << \" \";\n        cout << vvb[i][j] << \" \";\n      }\n      cout << endl;\n    }\n  }\n};\n\nint main() {\n  srand(23477846);\n\n  auto *board = new Board;\n  auto *blankPiece = new Piece(BLANK_SHAPE);\n  auto *straightPiece = new Piece(STRAIGHT_SHAPE);\n  auto *lPiece = new Piece(L_SHAPE);\n  auto *flippedLPiece = new Piece(FLIPPED_L_SHAPE);\n  auto *zigZagPiece = new Piece(ZIG_ZAG_SHAPE);\n  auto *flippedZigZagPiece = new Piece(FLIPPED_ZIG_ZAG_SHAPE);\n  auto *squarePiece = new Piece(SQUARE_SHAPE);\n  auto *tPiece = new Piece(T_SHAPE);\n\n  array<Piece *, 7> pieces = {\n      straightPiece,      lPiece,      flippedLPiece, zigZagPiece,\n      flippedZigZagPiece, squarePiece, tPiece};\n\n  board->render(blankPiece);\n\n  for (int n = 0; n < 10; n++) {\n    set<array<int, 4>> moves = board->getMoves(pieces);\n    if (moves.empty()) break;\n    int selectedMove = rand() % moves.size();\n    int i = 0;\n    for (array<int, 4> move : moves) {\n      if (i++ == selectedMove) {\n        cout << move[0] << \", \" << move[1] << \", \" << move[2] << \", \" << move[3]\n             << \"\\n\";\n        pieces[move[0]]->setPos(move[1], move[2]);\n        pieces[move[0]]->setRot(move[3]);\n        board->place(pieces[move[0]]);\n        array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape =\n            pieces[move[0]]->getShape();\n        for (int r = 0; r < PIECE_SIZE; r++) {\n          for (int c = 0; c < PIECE_SIZE; c++) {\n            cout << (shape[r][c] ? \"X\" : \"-\");\n          }\n          cout << \"\\n\";\n        }\n        board->render(pieces[move[0]]);\n        break;\n      }\n    }\n  }\n\n  cout << \"\\n\"\n       << \"\\n\"\n       << \"\\n\"\n       << \"Next moves:\\n\";\n  set<array<int, 4>> moves = board->getMoves(pieces);\n  for (array<int, 4> move : moves) {\n    cout << move[0] << \", \" << move[1] << \", \" << move[2] << \", \" << move[3]\n         << \"\\n\";\n    pieces[move[0]]->setPos(move[1], move[2]);\n    pieces[move[0]]->setRot(move[3]);\n    array<array<bool, PIECE_SIZE>, PIECE_SIZE> shape =\n        straightPiece->getShape();\n    for (int r = 0; r < PIECE_SIZE; r++) {\n      for (int c = 0; c < PIECE_SIZE; c++) {\n        cout << (shape[r][c] ? \"X\" : \"-\");\n      }\n      cout << \"\\n\";\n    }\n    board->render(pieces[move[0]]);\n  }\n\n  return 0;\n}\n\nBOOST_PYTHON_MODULE(tetris_boost) {\n  using namespace boost::python;\n\n  void (Board::*place)(int pieceIndex, int row, int col, int rot) =\n      &Board::place;\n\n  vector<VectorInt> (Board::*getMoves)() = &Board::getMoves;\n\n  bool (Board::*isValid)(int pieceIndex, int row, int col, int rot) =\n      &Board::isValid;\n\n  class_<vector<VectorBool>>(\"vector<VectorBool>\")\n      .def(vector_indexing_suite<vector<VectorBool>>());\n\n  class_<vector<VectorInt>>(\"vector<VectorInt>\")\n      .def(vector_indexing_suite<vector<VectorInt>>());\n\n  class_<Board>(\"Board\")\n      .def(\"place\", place)\n      .def(\"getMoves\", getMoves)\n      .def(\"rend\", &Board::rend)\n      .def(\"printRend\", &Board::printRend)\n      .def(\"printMoves\", &Board::printMoves)\n      .def(\"getValueOfVectorInts\", &Board::getValueOfVectorInts)\n      .def(\"getValueOfVectorBools\", &Board::getValueOfVectorBools)\n      .def(\"getScore\", &Board::getScore)\n      .def(\"reset\", &Board::reset)\n      .def(\"isValid\", isValid)\n      .def(\"getNumberOfMoves\", &Board::getNumberOfMoves);\n}\n", "meta": {"hexsha": "c2d0c05d05642750aad41e32defb4726c7e7adf8", "size": 16836, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/tetris_boost.cpp", "max_stars_repo_name": "TylerWasniowski/tetris", "max_stars_repo_head_hexsha": "8be9fdbf46d134c89e2e5d450c5148cfa6ad76de", "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": "boost/tetris_boost.cpp", "max_issues_repo_name": "TylerWasniowski/tetris", "max_issues_repo_head_hexsha": "8be9fdbf46d134c89e2e5d450c5148cfa6ad76de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:36:48.000Z", "max_forks_repo_path": "boost/tetris_boost.cpp", "max_forks_repo_name": "TylerWasniowski/tetris", "max_forks_repo_head_hexsha": "8be9fdbf46d134c89e2e5d450c5148cfa6ad76de", "max_forks_repo_licenses": ["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.1538461538, "max_line_length": 80, "alphanum_fraction": 0.5564861012, "num_tokens": 5037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.18041657988430193}}
{"text": "// Copyright 2009-2010 Green Code 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#include <cmath>\n#include <iostream>\n\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"Algorithm.h\"\n#include \"DuplicatePoints.h\"\n#include \"IPoint.h\"\n#include \"IRasterSurface.h\"\n#include \"ISurfaceInterpolation.h\"\n#include \"IUnclassifiedPoints.h\"\n#include \"LineIndent.h\"\n#include \"PointCanopyHeightFile.h\"\n#include \"StackedPoints.h\"\n#include \"UnclassifiedPoints.h\"\n\n\nnamespace mcc\n{\n  Algorithm::Algorithm(ISurfaceInterpolation & surfaceInterpolation,\n                       bool                    writeNongroundPts,\n                       bool                    writeRasterSurfaces)\n    : surfaceInterpolation_(surfaceInterpolation),\n      writeNongroundPts_(writeNongroundPts),\n      writeRasterSurfaces_(writeRasterSurfaces)\n  {\n  }\n\n  //---------------------------------------------------------------------------\n\n  const double Algorithm::tension = 1.5;\n\n  //---------------------------------------------------------------------------\n\n  void Algorithm::classifyPoints(UnclassifiedPoints & points,\n                                 double                scaleDomain2Spacing,\n                                 double                curvatureThreshold)\n  {\n    // curvature thresholds for scale domains\n    double t[4];  // array[0] not used; allow use of indexes in range of 1 to 3\n    t[1] = curvatureThreshold;\n    t[2] = t[1] + 0.1;\n    t[3] = t[2] + 0.1;\n\n     // cell resolutions for scale domains\n    double CR[4];\n    CR[2] = scaleDomain2Spacing;\n    CR[1] = 0.5 * CR[2];\n    CR[3] = 1.5 * CR[2];\n\n    // percentage of points classified during a pass that represents convergence\n    // for each scale domain\n    double convergencePercent[4];\n    convergencePercent[1] = 0.01;    // 1%\n    convergencePercent[2] = 0.001;   // 0.1%\n    convergencePercent[3] = 0.0001;  // 0.01%\n\n    // points not yet classified\n\n    IUnclassifiedPoints & U = points;\n    UnclassifiedPoints splinePoints(points);\n\n    // Locate points that are vertically stacked (at same x,y coordinates), and\n    // within each stack, classify all points but the lowest one as non-ground.\n    std::cout << \"Searching for points with the same x,y coordinates...\" << std::endl;\n    std::vector<IPoint *> unclassifiedDuplicates;\n    StackedPoints::classifyPointsAtSameXY(splinePoints, unclassifiedDuplicates);\n    int nClassified = splinePoints.removeClassified();\n    std::cout << \"  \" << nClassified << \" points classified as non-ground\" << std::endl;\n\n    DuplicatePoints duplicatePoints(unclassifiedDuplicates);\n    std::string pluralEnding = (duplicatePoints.setCount() == 1) ? \"\" : \"s\";\n    std::cout << \"Identified \" << duplicatePoints.setCount() << \" set\" << pluralEnding << \" of unclassified duplicate points\" << std::endl;\n    int nDuplicatesPutAside = duplicatePoints.putAsideAllButOnePointPerSet();\n    nDuplicatesPutAside = splinePoints.removeClassified();\n\n    LineIndent indent(\"  \");\n\n    const int maxPasses = 100;  // max # of passes per scale domain\n    int nDigitsForPass = (int) std::log10((double) maxPasses) + 1;\n    std::string passFormat = boost::str(boost::format(\"0%d\") % nDigitsForPass);\n\n    for (int SD = 1; SD <= 3; SD++) {\n      std::cout << \"Scale domain: \" << SD << \" (cell resolution: \" << CR[SD] << \")\" << std::endl;\n      int nPoints;\n      int nClassified;\n      double percentClassified;\n      int pass = 0;\n      do {\n        pass++;\n        if (pass > maxPasses) {\n          std::cout << \"Maximum # of passes reached for scale domain \" << SD << std::endl;\n          break;\n        }\n        std::cout << \"SD \" << SD << \" - Pass \" << pass << std::endl\n                  << indent << \"Interpolating \" << splinePoints.count() << \" points:\" << std::endl;\n        boost::shared_ptr<IRasterSurface> rasterSurface = surfaceInterpolation_(splinePoints, CR[SD], tension);\n\n        std::cout << indent << \"Averaging raster surface...\" << std::endl;\n        rasterSurface->average(3);  // kernel = 3x3\n\n        if (writeRasterSurfaces_) {\n          boost::format rasterNameFmt(\"surface_sd%d_p%|\" + passFormat + \"|.asc\");\n          std::string rasterName = boost::str(rasterNameFmt % SD % pass);\n          std::cout << indent << \"Writing raster surface to file \\\"\" << rasterName  << \"\\\"...\" << std::endl;\n          rasterSurface->writeAsciiGrid(rasterName);\n        }\n\n        std::cout << indent << \"Identifying non-ground points:\" << std::endl;\n        PointCanopyHeightFile nongroundPtsFile;\n        if (writeNongroundPts_) {\n          boost::format fileName(\"nonground_sd%d_p%|\" + passFormat + \"|.csv\");\n          nongroundPtsFile.open(boost::str(fileName % SD % pass));\n        }\n        nPoints = U.count();\n        std::cout << \"Number of Points: \" << nPoints << std::endl;\n        BOOST_FOREACH( IPoint & point, U) {\n          Coordinate surfaceHeight = (*rasterSurface)(point.x(), point.y());\n          if (point.z() > surfaceHeight + t[SD]) {\n            point.classifyAs(NonGround);\n            if (nongroundPtsFile) {\n              Coordinate canopyHeight = point.z() - surfaceHeight;\n              nongroundPtsFile.writeRow(point, canopyHeight);\n            }\n          }\n        }\n\n        nClassified = U.removeClassified();\n        percentClassified = nClassified / double(nPoints);\n        boost::format percentFormat(\"%|.2|%%\");\n        std::string percentClassifiedStr = boost::str(percentFormat % (percentClassified * 100));\n        std::cout << indent << \"  \" << nClassified << \" points (\" << percentClassifiedStr << \") classified as non-ground\" << std::endl;\n        if (nongroundPtsFile) {\n          nongroundPtsFile.close();\n          std::cout << indent << \"  Wrote points to file \\\"\" << nongroundPtsFile.path() << \"\\\"\" << std::endl;\n        }\n      } while ((percentClassified >= convergencePercent[SD]) && (U.count() > 0)); // until (n_C < convergence_% * n) or no more points\n\n      if (U.count() == 0)\n        break;\n    }\n\n    // Classify all the remaining points as ground\n    std::cout << \"Classifying \" << U.count() << \" points as ground...\" << std::endl;\n    BOOST_FOREACH( IPoint & point, U) {\n      point.classifyAs(Ground);\n    }\n\n    pluralEnding = (nDuplicatesPutAside == 1) ? \"\" : \"s\";\n    std::cout << \"Copying classifications to \" << nDuplicatesPutAside << \" duplicate point\" << pluralEnding << \"...\" << std::endl;\n    duplicatePoints.copyClassificationAmongPointsInSet();\n  }\n\n\n\n  // Additions by GEH:\n\n  void Algorithm::labelPointsUsingPass(UnclassifiedPoints & points,\n                                 double                scaleDomainSpacing)\n  {\n\n    // points not yet classified\n\n    IUnclassifiedPoints & U = points;\n    UnclassifiedPoints splinePoints(points);\n\n    // Locate points that are vertically stacked (at same x,y coordinates), and\n    // within each stack, classify all points but the lowest one as non-ground.\n    std::cout << \"Searching for points with the same x,y coordinates...\" << std::endl;\n    std::vector<IPoint *> unclassifiedDuplicates;\n    StackedPoints::classifyPointsAtSameXY(splinePoints, unclassifiedDuplicates);\n    int nClassified = splinePoints.removeClassified();\n    std::cout << \"  \" << nClassified << \" points classified as non-ground\" << std::endl;\n\n    DuplicatePoints duplicatePoints(unclassifiedDuplicates);\n    std::string pluralEnding = (duplicatePoints.setCount() == 1) ? \"\" : \"s\";\n    std::cout << \"Identified \" << duplicatePoints.setCount() << \" set\" << pluralEnding << \" of unclassified duplicate points\" << std::endl;\n    int nDuplicatesPutAside = duplicatePoints.putAsideAllButOnePointPerSet();\n    nDuplicatesPutAside = splinePoints.removeClassified();\n\n\n    LineIndent indent(\"  \");\n\n    std::cout << \"Scale domain: \" << scaleDomainSpacing << std::endl;\n\n    std::cout << \"Interpolating \" << splinePoints.count() << \" points:\" << std::endl;\n    boost::shared_ptr<IRasterSurface> rasterSurface = surfaceInterpolation_(splinePoints, scaleDomainSpacing, tension);\n\n    std::cout << indent << \"Averaging raster surface...\" << std::endl;\n    rasterSurface->average(3);  // kernel = 3x3\n\n    if (writeRasterSurfaces_) {\n      boost::format rasterNameFmt(\"surface_sd%d_p%.asc\");\n      std::string rasterName = boost::str(rasterNameFmt % scaleDomainSpacing);\n      std::cout << indent << \"Writing raster surface to file \\\"\" << rasterName  << \"\\\"...\" << std::endl;\n      rasterSurface->writeAsciiGrid(rasterName);\n    }\n\n    std::cout << indent << \"Identifying non-ground points:\" << std::endl;\n    PointCanopyHeightFile nongroundPtsFile;\n\n    BOOST_FOREACH( IPoint & point, U) {\n      Coordinate surfaceHeight = (*rasterSurface)(point.x(), point.y());\n      point.setH(point.z() - surfaceHeight);\n      point.classifyAs(Ground);\n    }\n\n  }\n\n}\n", "meta": {"hexsha": "3c1a3966afe16013dd1b1e42282d95c4e0012edc", "size": 9282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libmcc_lidar/Algorithm.cpp", "max_stars_repo_name": "rmsare/pymcc", "max_stars_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-07-20T10:09:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T14:12:00.000Z", "max_issues_repo_path": "libmcc_lidar/Algorithm.cpp", "max_issues_repo_name": "rmsare/pymcc", "max_issues_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-25T00:30:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-10T17:32:48.000Z", "max_forks_repo_path": "libmcc_lidar/Algorithm.cpp", "max_forks_repo_name": "rmsare/pymcc", "max_forks_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T19:46:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-27T19:46:11.000Z", "avg_line_length": 40.8898678414, "max_line_length": 139, "alphanum_fraction": 0.6242189183, "num_tokens": 2265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.18041657988430193}}
{"text": "// Copyright (C) 2015, Pawel Tomulik <ptomulik@meil.pw.edu.pl>\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#define BOOST_TEST_MODULE test_txpl_vm_eval_binary_minus\n\n#include <txpl/test_config.hpp>\n#include <boost/test/unit_test.hpp>\n\n#ifndef TXPL_TEST_SKIP_VM_EVAL_BINARY_MINUS\n\n#include <txpl/vm/eval_binary_op.hpp>\n#include <txpl/vm/basic_types.hpp>\n#include <txpl/vm/value.hpp>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/get.hpp>\n\nusing namespace txpl::vm;\ntypedef basic_types<>::char_type   char_type;\ntypedef basic_types<>::int_type    int_type;\ntypedef basic_types<>::bool_type   bool_type;\ntypedef basic_types<>::real_type   real_type;\ntypedef basic_types<>::string_type string_type;\ntypedef basic_types<>::regex_type  regex_type;\ntypedef basic_types<>::blank_type  blank_type;\ntypedef array<value<> >            array_type;\ntypedef object<value<> >           object_type;\n\nBOOST_AUTO_TEST_CASE(char__minus__char)\n{\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = char_type{'\\2'};\n    const value<> v2 = char_type{'\\4'};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (char_type{'\\2'} - char_type{'\\4'}));\n  }\n}\nBOOST_AUTO_TEST_CASE(char__minus__int)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = char_type{'\\2'};\n    const value<> v2 = int_type{4};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (char_type{'\\2'} - int_type{4}));\n  }\n}\nBOOST_AUTO_TEST_CASE(char__minus__bool)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = char_type{'\\3'};\n    const value<> v2 = bool_type{true};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (char_type{'\\3'} - bool_type{true}));\n  }\n}\nBOOST_AUTO_TEST_CASE(char__minus__real)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = char_type{'\\2'};\n    const value<> v2 = real_type{2.1};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    real_type x = real_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<real_type>(r));\n    BOOST_CHECK(x == (char_type{'\\2'} - real_type{2.1}));\n  }\n}\nBOOST_AUTO_TEST_CASE(char__minus__string)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = char_type{'a'};\n    const value<> v2 = string_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(char__minus__regex)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = char_type{'a'};\n    const value<> v2 = regex_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(char__minus__array)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = char_type{'a'};\n    const value<> v2 = array_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(char__minus__object)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = char_type{'a'};\n    const value<> v2 = object_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(int__minus__char)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = int_type{2};\n    const value<> v2 = char_type{'\\3'};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (int_type{2} - char_type{'\\3'}));\n  }\n}\nBOOST_AUTO_TEST_CASE(int__minus__int)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = int_type{2};\n    const value<> v2 = int_type{3};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (int_type{2} - int_type{3}));\n  }\n}\nBOOST_AUTO_TEST_CASE(int__minus__bool)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = int_type{3};\n    const value<> v2 = bool_type{true};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (int_type{3} - bool_type{true}));\n  }\n}\nBOOST_AUTO_TEST_CASE(int__minus__real)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = int_type{12};\n    const value<> v2 = real_type{3.21};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    real_type x = real_type{.654};\n    BOOST_CHECK_NO_THROW(x = boost::get<real_type>(r));\n    BOOST_CHECK(x == (int_type{12} - real_type{3.21}));\n  }\n}\nBOOST_AUTO_TEST_CASE(int__minus__string)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = int_type{0};\n    const value<> v2 = string_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(int__minus__regex)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = int_type{0};\n    const value<> v2 = regex_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(int__minus__array)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = int_type{0};\n    const value<> v2 = array_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(int__minus__object)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = int_type{0};\n    const value<> v2 = object_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(bool__minus__char)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = bool_type{true};\n    const value<> v2 = char_type{'\\3'};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (bool_type{true} - char_type{'\\3'}));\n  }\n}\nBOOST_AUTO_TEST_CASE(bool__minus__int)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = bool_type{true};\n    const value<> v2 = int_type{3};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (bool_type{true} - int_type{3}));\n  }\n}\nBOOST_AUTO_TEST_CASE(bool__minus__bool)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = bool_type{true};\n    const value<> v2 = bool_type{true};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    int_type x = int_type{654};\n    BOOST_CHECK_NO_THROW(x = boost::get<int_type>(r));\n    BOOST_CHECK(x == (bool_type{true} - bool_type{true}));\n  }\n}\nBOOST_AUTO_TEST_CASE(bool__minus__real)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = bool_type{true};\n    const value<> v2 = real_type{2.12};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    real_type x = real_type{.654};\n    BOOST_CHECK_NO_THROW(x = boost::get<real_type>(r));\n    BOOST_CHECK(x == (bool_type{true} - real_type{2.12}));\n  }\n}\nBOOST_AUTO_TEST_CASE(bool__minus__string)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = bool_type{false};\n    const value<> v2 = string_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(bool__minus__regex)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = bool_type{false};\n    const value<> v2 = regex_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(bool__minus__array)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = bool_type{false};\n    const value<> v2 = array_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(bool__minus__object)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = bool_type{false};\n    const value<> v2 = object_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(real__minus__char)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = real_type{1.2};\n    const value<> v2 = char_type{'\\3'};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    real_type x = real_type{.654};\n    BOOST_CHECK_NO_THROW(x = boost::get<real_type>(r));\n    BOOST_CHECK(x == (real_type{1.2} - char_type{'\\3'}));\n  }\n}\nBOOST_AUTO_TEST_CASE(real__minus__int)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = real_type{1.2};\n    const value<> v2 = int_type{3};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    real_type x = real_type{.654};\n    BOOST_CHECK_NO_THROW(x = boost::get<real_type>(r));\n    BOOST_CHECK(x == (real_type{1.2} - int_type{3}));\n  }\n}\nBOOST_AUTO_TEST_CASE(real__minus__bool)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = real_type{1.2};\n    const value<> v2 = bool_type{true};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    real_type x = real_type{.654};\n    BOOST_CHECK_NO_THROW(x = boost::get<real_type>(r));\n    BOOST_CHECK(x == (real_type{1.2} - bool_type{true}));\n  }\n}\nBOOST_AUTO_TEST_CASE(real__minus__real)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = real_type{1.2};\n    const value<> v2 = real_type{3.4};\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    real_type x = real_type{.654};\n    BOOST_CHECK_NO_THROW(x = boost::get<real_type>(r));\n    BOOST_CHECK(x == (real_type{1.2} - real_type{3.4}));\n  }\n}\nBOOST_AUTO_TEST_CASE(real__minus__string)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = real_type{0.0};\n    const value<> v2 = string_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(real__minus__regex)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = real_type{0.0};\n    const value<> v2 = regex_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(real__minus__array)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = real_type{0.0};\n    const value<> v2 = array_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(real__minus__object)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = real_type{0.0};\n    const value<> v2 = object_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(string__minus__char)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = string_type();\n    const value<> v2 = char_type{'a'};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(string__minus__int)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = string_type();\n    const value<> v2 = int_type{0};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(string__minus__bool)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = string_type();\n    const value<> v2 = bool_type{false};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(string__minus__real)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = string_type();\n    const value<> v2 = real_type{0.0};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(string__minus__string)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = string_type(\"asd\");\n    const value<> v2 = string_type{\"qwer\"};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(string__minus__regex)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = string_type();\n    const value<> v2 = regex_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(string__minus__array)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = string_type();\n    const value<> v2 = array_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(string__minus__object)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = string_type();\n    const value<> v2 = object_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(regex__minus__char)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = regex_type();\n    const value<> v2 = char_type{'\\0'};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(regex__minus__int)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = regex_type();\n    const value<> v2 = int_type{0};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(regex__minus__bool)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = regex_type();\n    const value<> v2 = bool_type{false};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(regex__minus__real)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = regex_type();\n    const value<> v2 = real_type{0.0};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(regex__minus__string)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = regex_type();\n    const value<> v2 = string_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(regex__minus__regex)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = regex_type();\n    const value<> v2 = regex_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(regex__minus__array)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = regex_type();\n    const value<> v2 = array_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(regex__minus__object)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = regex_type();\n    const value<> v2 = object_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(array__minus__char)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = array_type();\n    const value<> v2 = char_type{'\\0'};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(array__minus__int)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = array_type();\n    const value<> v2 = int_type{0};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(array__minus__bool)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = array_type();\n    const value<> v2 = bool_type{false};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(array__minus__real)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = array_type();\n    const value<> v2 = real_type{0.0};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(array__minus__string)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = array_type();\n    const value<> v2 = string_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(array__minus__regex)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = array_type();\n    const value<> v2 = regex_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(array__minus__array)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = array_type();\n    const value<> v2 = array_type();\n    r = blank_type();\n    BOOST_CHECK(boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<array_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(array__minus__object)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = array_type();\n    const value<> v2 = object_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(object__minus__char)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = object_type();\n    const value<> v2 = char_type{'\\0'};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(object__minus__int)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = object_type();\n    const value<> v2 = int_type{0};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(object__minus__bool)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = object_type();\n    const value<> v2 = bool_type{false};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(object__minus__real)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = object_type();\n    const value<> v2 = real_type{0.0};\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(object__minus__string)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = object_type();\n    const value<> v2 = string_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(object__minus__regex)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = object_type();\n    const value<> v2 = regex_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(object__minus__array)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = object_type();\n    const value<> v2 = array_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\nBOOST_AUTO_TEST_CASE(object__minus__object)\n{\n  using namespace txpl::vm;\n  value<> r;\n  auto op = eval_binary_op<op_t::minus_>(r);\n  {\n    const value<> v1 = object_type();\n    const value<> v2 = object_type();\n    r = blank_type();\n    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));\n    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));\n  }\n}\n\n#else\nBOOST_AUTO_TEST_CASE(dummy)\n{\n  BOOST_CHECK(true);\n}\n#endif\n", "meta": {"hexsha": "291b5c07fdf5e417b7c0b6a535d931a3b24ed165", "size": 24465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/txpl/vm/eval_binary_minus_test.cpp", "max_stars_repo_name": "ptomulik/txpl", "max_stars_repo_head_hexsha": "109b5847abe0d46c598ada46f411f98ebe8dc4c8", "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/txpl/vm/eval_binary_minus_test.cpp", "max_issues_repo_name": "ptomulik/txpl", "max_issues_repo_head_hexsha": "109b5847abe0d46c598ada46f411f98ebe8dc4c8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-03-02T14:02:32.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-17T21:50:30.000Z", "max_forks_repo_path": "test/txpl/vm/eval_binary_minus_test.cpp", "max_forks_repo_name": "ptomulik/txpl", "max_forks_repo_head_hexsha": "109b5847abe0d46c598ada46f411f98ebe8dc4c8", "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.97353914, "max_line_length": 62, "alphanum_fraction": 0.6591048437, "num_tokens": 7381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1803581926565589}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SCALAR_SINCOSD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SCALAR_SINCOSD_HPP_INCLUDED\n\n#include <boost/simd/function/definition/sincosd.hpp>\n#include <boost/simd/arch/common/generic/function/sincosd.hpp>\n#include <boost/simd/arch/common/scalar/function/sincosd.hpp>\n\n#endif\n", "meta": {"hexsha": "89bb2e7e37c9aa1bc023c238a18eceb070e0d7a2", "size": 684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/scalar/sincosd.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/scalar/sincosd.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/scalar/sincosd.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.0, "max_line_length": 100, "alphanum_fraction": 0.5701754386, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1803380996101987}}
{"text": "/*\n * Collision sphere file\n * \n * This file is part of the \"SoftPixel Engine\" (Copyright (c) 2008 by Lukas Hermanns)\n * See \"SoftPixelEngine.hpp\" for license information.\n */\n\n#include \"SceneGraph/Collision/spCollisionCapsule.hpp\"\n#include \"SceneGraph/Collision/spCollisionSphere.hpp\"\n#include \"SceneGraph/Collision/spCollisionBox.hpp\"\n#include \"SceneGraph/Collision/spCollisionPlane.hpp\"\n#include \"SceneGraph/Collision/spCollisionMesh.hpp\"\n\n#include <boost/foreach.hpp>\n\n\nnamespace sp\n{\nnamespace scene\n{\n\n\nCollisionCapsule::CollisionCapsule(\n    CollisionMaterial* Material, SceneNode* Node, f32 Radius, f32 Height) :\n    CollisionLineBased(Material, Node, COLLISION_CAPSULE, Radius, Height)\n{\n}\nCollisionCapsule::~CollisionCapsule()\n{\n}\n\ns32 CollisionCapsule::getSupportFlags() const\n{\n    return COLLISIONSUPPORT_SPHERE | COLLISIONSUPPORT_CAPSULE | COLLISIONSUPPORT_BOX | COLLISIONSUPPORT_PLANE | COLLISIONSUPPORT_MESH;\n}\n\nbool CollisionCapsule::checkIntersection(const dim::line3df &Line, SIntersectionContact &Contact) const\n{\n    dim::vector3df PointP, PointQ;\n    const dim::line3df CapsuleLine(getLine());\n    \n    /* Make an intersection test with both lines */\n    const f32 DistanceSq = math::CollisionLibrary::getLineLineDistanceSq(CapsuleLine, Line, PointP, PointQ);\n    \n    if (DistanceSq < math::pow2(getRadius()))\n    {\n        Contact.Normal  = (PointQ - PointP).normalize();\n        Contact.Point   = PointP + Contact.Normal * getRadius();\n        Contact.Object  = this;\n        return true;\n    }\n    \n    return false;\n}\n\nbool CollisionCapsule::checkIntersection(const dim::line3df &Line, bool ExcludeCorners) const\n{\n    /* Make an intersection test with both lines */\n    dim::vector3df PointP, PointQ;\n    \n    if (math::CollisionLibrary::getLineLineDistanceSq(getLine(), Line, PointP, PointQ) < math::pow2(getRadius()))\n    {\n        if (ExcludeCorners)\n        {\n            dim::vector3df Dir(PointQ - PointP);\n            Dir.setLength(getRadius());\n            return checkCornerExlusion(Line, PointP + Dir);\n        }\n        return true;\n    }\n    \n    return false;\n}\n\n\n/*\n * ======= Private: =======\n */\n\nbool CollisionCapsule::checkCollisionToSphere(const CollisionSphere* Rival, SCollisionContact &Contact) const\n{\n    if (!Rival)\n        return false;\n    \n    /* Store transformation */\n    const dim::vector3df SpherePos(Rival->getPosition());\n    const dim::line3df CapsuleLine(getLine());\n    \n    const f32 MaxRadius = Radius_ + Rival->getRadius();\n    \n    /* Get the closest point from this sphere to the capsule */\n    const dim::vector3df ClosestPoint = CapsuleLine.getClosestPoint(SpherePos);\n    \n    /* Check if this object and the other collide with each other */\n    if (math::getDistanceSq(SpherePos, ClosestPoint) < math::pow2(MaxRadius))\n        return setupCollisionContact(ClosestPoint, SpherePos, MaxRadius, Rival->getRadius(), Contact);\n    \n    return false;\n}\n\nbool CollisionCapsule::checkCollisionToCapsule(const CollisionCapsule* Rival, SCollisionContact &Contact) const\n{\n    if (!Rival)\n        return false;\n    \n    /* Store transformation */\n    const dim::vector3df SpherePos(Rival->getPosition());\n    const dim::line3df CapsuleLine(getLine());\n    \n    const f32 MaxRadius = Radius_ + Rival->getRadius();\n    \n    /* Get the closest points between this and the rival capsule */\n    dim::vector3df PointP, PointQ;\n    const f32 DistanceSq = math::CollisionLibrary::getLineLineDistanceSq(getLine(), Rival->getLine(), PointP, PointQ);\n    \n    /* Check if this object and the other collide with each other */\n    if (DistanceSq < math::pow2(MaxRadius))\n        return setupCollisionContact(PointP, PointQ, MaxRadius, Rival->getRadius(), Contact);\n    \n    return false;\n}\n\nbool CollisionCapsule::checkCollisionToBox(const CollisionBox* Rival, SCollisionContact &Contact) const\n{\n    if (!Rival)\n        return false;\n    \n    /* Store transformation */\n    const dim::matrix4f Mat(Rival->getTransformation().getPositionRotationMatrix());\n    const dim::matrix4f InvMat(Mat.getInverse());\n    \n    const dim::aabbox3df Box(Rival->getBox().getScaled(Rival->getScale()));\n    const dim::line3df CapsuleLine(getLine());\n    const dim::line3df CapsuleLineInv(\n        InvMat * CapsuleLine.Start, InvMat * CapsuleLine.End\n    );\n    \n    /* Get the closest point from this capsule and the box */\n    if (Box.isPointInside(CapsuleLineInv.Start) || Box.isPointInside(CapsuleLineInv.End))\n        return false;\n    \n    const dim::line3df Line = math::CollisionLibrary::getClosestLine(Box, CapsuleLineInv);\n    \n    /* Check if this object and the other collide with each other */\n    if (math::getDistanceSq(Line.Start, Line.End) < math::pow2(getRadius()))\n    {\n        Contact.Point = Mat * Line.Start;\n        \n        /* Compute normal and impact together to avoid calling square-root twice */\n        Contact.Normal = (Mat * Line.End) - Contact.Point;\n        Contact.Impact = Contact.Normal.getLength();\n        \n        if (Contact.Impact < math::ROUNDING_ERROR)\n            return false;\n        \n        Contact.Normal *= (1.0f / Contact.Impact);\n        Contact.Impact = getRadius() - Contact.Impact;\n        \n        return true;\n    }\n    \n    return false;\n}\n\nbool CollisionCapsule::checkCollisionToPlane(const CollisionPlane* Rival, SCollisionContact &Contact) const\n{\n    if (!Rival)\n        return false;\n    \n    /* Store transformation */\n    const dim::line3df CapsuleLine(getLine());\n    const dim::plane3df RivalPlane(\n        Rival->getTransformation().getPositionRotationMatrix() * Rival->getPlane()\n    );\n    \n    /* Check if this object and the other collide with each other */\n    const f32 DistA = RivalPlane.getPointDistance(CapsuleLine.Start);\n    const f32 DistB = RivalPlane.getPointDistance(CapsuleLine.End);\n    \n    if ( DistA > 0.0f && DistB > 0.0f && ( DistA < getRadius() || DistB < getRadius() ) )\n    {\n        Contact.Normal  = RivalPlane.Normal;\n        Contact.Point   = Contact.Normal;\n        \n        if (DistA <= DistB)\n        {\n            Contact.Point *= -DistA;\n            Contact.Point += CapsuleLine.Start;\n            \n            Contact.Impact = getRadius() - DistA;\n        }\n        else\n        {\n            Contact.Point *= -DistB;\n            Contact.Point += CapsuleLine.End;\n            \n            Contact.Impact = getRadius() - DistB;\n        }\n        \n        return true;\n    }\n    \n    return false;\n}\n\nbool CollisionCapsule::checkCollisionToMesh(const CollisionMesh* Rival, SCollisionContact &Contact) const\n{\n    if (!Rival)\n        return false;\n    \n    /* Check if rival mesh has a tree-hierarchy */\n    KDTreeNode* RootTreeNode = Rival->getRootTreeNode();\n    \n    if (!RootTreeNode)\n        return false;\n    \n    /* Store transformation */\n    const dim::line3df CapsuleLine(getLine());\n    const video::EFaceTypes CollFace(Rival->getCollFace());\n    \n    const dim::matrix4f RivalMat(Rival->getTransformation());\n    const dim::matrix4f RivalMatInv(RivalMat.getInverse());\n    \n    const dim::line3df CapsuleLineInv(\n        RivalMatInv * CapsuleLine.Start, RivalMatInv * CapsuleLine.End\n    );\n    \n    f32 DistanceSq = math::pow2(getRadius());\n    SCollisionFace* ClosestFace = 0;\n    dim::vector3df ClosestPoint;\n    \n    #ifndef _DEB_NEW_KDTREE_\n    std::map<SCollisionFace*, bool> FaceMap;\n    #endif\n    \n    /* Get tree node list */\n    std::list<const TreeNode*> TreeNodeList;\n    \n    RootTreeNode->findLeafList(\n        TreeNodeList, CapsuleLineInv, (RivalMatInv.getScale() * getRadius()).getMax()\n    );\n    \n    /* Check collision with triangles of each tree-node */\n    foreach (const TreeNode* Node, TreeNodeList)\n    {\n        /* Get tree node data */\n        CollisionMesh::TreeNodeDataType* TreeNodeData = static_cast<CollisionMesh::TreeNodeDataType*>(Node->getUserData());\n        \n        if (!TreeNodeData)\n            continue;\n        \n        /* Check collision with each triangle */\n        #ifndef _DEB_NEW_KDTREE_\n        foreach (SCollisionFace* Face, *TreeNodeData)\n        #else\n        foreach (SCollisionFace &NodeFace, *TreeNodeData)\n        #endif\n        {\n            #ifndef _DEB_NEW_KDTREE_\n            /* Check for unique usage */\n            if (FaceMap.find(Face) != FaceMap.end())\n                continue;\n            \n            FaceMap[Face] = true;\n            #else\n            SCollisionFace* Face = &NodeFace;\n            #endif\n            \n            /* Check for face-culling */\n            if (Face->isBackFaceCulling(CollFace, CapsuleLineInv))\n                continue;\n            \n            /* Make sphere-triangle collision test */\n            const dim::line3df CurClosestLine(\n                math::CollisionLibrary::getClosestLine(RivalMat * Face->Triangle, CapsuleLine)\n            );\n            \n            /* Check if this is a potentially new closest face */\n            const f32 CurDistSq = math::getDistanceSq(CurClosestLine.Start, CurClosestLine.End);\n            \n            if (CurDistSq < DistanceSq)\n            {\n                /* Store link to new closest face */\n                DistanceSq      = CurDistSq;\n                ClosestPoint    = CurClosestLine.Start;\n                ClosestFace     = Face;\n            }\n        }\n    }\n    \n    /* Check if a collision has been detected */\n    if (ClosestFace)\n    {\n        Contact.Normal  = (RivalMat * ClosestFace->Triangle).getNormal();\n        Contact.Point   = ClosestPoint;\n        Contact.Face    = ClosestFace;\n        return true;\n    }\n    \n    return false;\n}\n\nbool CollisionCapsule::checkAnyCollisionToMesh(const CollisionMesh* Rival) const\n{\n    if (!Rival)\n        return false;\n    \n    /* Check if rival mesh has a tree-hierarchy */\n    KDTreeNode* RootTreeNode = Rival->getRootTreeNode();\n    \n    if (!RootTreeNode)\n        return false;\n    \n    /* Store transformation */\n    const dim::line3df CapsuleLine(getLine());\n    const video::EFaceTypes CollFace(Rival->getCollFace());\n    \n    const dim::matrix4f RivalMat(Rival->getTransformation());\n    const dim::matrix4f RivalMatInv(RivalMat.getInverse());\n    \n    const dim::line3df CapsuleLineInv(\n        RivalMatInv * CapsuleLine.Start, RivalMatInv * CapsuleLine.End\n    );\n    \n    const f32 RadiusSq = math::pow2(getRadius());\n    \n    #ifndef _DEB_NEW_KDTREE_\n    std::map<SCollisionFace*, bool> FaceMap;\n    #endif\n    \n    /* Get tree node list */\n    std::list<const TreeNode*> TreeNodeList;\n    \n    RootTreeNode->findLeafList(\n        TreeNodeList, CapsuleLineInv, (RivalMatInv.getScale() * getRadius()).getMax()\n    );\n    \n    /* Check collision with triangles of each tree-node */\n    foreach (const TreeNode* Node, TreeNodeList)\n    {\n        /* Get tree node data */\n        CollisionMesh::TreeNodeDataType* TreeNodeData = static_cast<CollisionMesh::TreeNodeDataType*>(Node->getUserData());\n        \n        if (!TreeNodeData)\n            continue;\n        \n        /* Check collision with each triangle */\n        #ifndef _DEB_NEW_KDTREE_\n        foreach (SCollisionFace* Face, *TreeNodeData)\n        #else\n        foreach (SCollisionFace &NodeFace, *TreeNodeData)\n        #endif\n        {\n            #ifndef _DEB_NEW_KDTREE_\n            /* Check for unique usage */\n            if (FaceMap.find(Face) != FaceMap.end())\n                continue;\n            \n            FaceMap[Face] = true;\n            #else\n            SCollisionFace* Face = &NodeFace;\n            #endif\n            \n            /* Check for face-culling */\n            if (Face->isBackFaceCulling(CollFace, CapsuleLineInv))\n                continue;\n            \n            /* Make sphere-triangle collision test */\n            const dim::line3df CurClosestLine(\n                math::CollisionLibrary::getClosestLine(Face->Triangle, CapsuleLineInv)\n            );\n            \n            /* Check if the first collision has been detected and return on succeed */\n            if (math::getDistanceSq(CurClosestLine.Start, CurClosestLine.End) < RadiusSq)\n                return true;\n        }\n    }\n    \n    return false;\n}\n\nvoid CollisionCapsule::performCollisionResolvingToSphere(const CollisionSphere* Rival)\n{\n    SCollisionContact Contact;\n    if (checkCollisionToSphere(Rival, Contact))\n        performDetectedContact(Rival, Contact);\n}\n\nvoid CollisionCapsule::performCollisionResolvingToCapsule(const CollisionCapsule* Rival)\n{\n    SCollisionContact Contact;\n    if (checkCollisionToCapsule(Rival, Contact))\n        performDetectedContact(Rival, Contact);\n}\n\nvoid CollisionCapsule::performCollisionResolvingToBox(const CollisionBox* Rival)\n{\n    SCollisionContact Contact;\n    if (checkCollisionToBox(Rival, Contact))\n        performDetectedContact(Rival, Contact);\n}\n\nvoid CollisionCapsule::performCollisionResolvingToPlane(const CollisionPlane* Rival)\n{\n    SCollisionContact Contact;\n    if (checkCollisionToPlane(Rival, Contact))\n        performDetectedContact(Rival, Contact);\n}\n\nvoid CollisionCapsule::performCollisionResolvingToMesh(const CollisionMesh* Rival)\n{\n    if (!Rival)\n        return;\n    \n    /* Check if rival mesh has a tree-hierarchy */\n    KDTreeNode* RootTreeNode = Rival->getRootTreeNode();\n    \n    if (!RootTreeNode)\n        return;\n    \n    /* Store transformation */\n    const video::EFaceTypes CollFace(Rival->getCollFace());\n    \n    const dim::matrix4f RivalMat(Rival->getTransformation());\n    const dim::matrix4f RivalMatInv(RivalMat.getInverse());\n    \n    dim::line3df CapsuleLine(getLine());\n    dim::line3df CapsuleLineInv(\n        RivalMatInv * CapsuleLine.Start, RivalMatInv * CapsuleLine.End\n    );\n    \n    dim::line3df ClosestLine;\n    const f32 RadiusSq = math::pow2(getRadius());\n    \n    #ifndef _DEB_NEW_KDTREE_\n    std::map<SCollisionFace*, bool> FaceMap, EdgeFaceMap;\n    #endif\n    \n    /* Get tree node list */\n    std::list<const TreeNode*> TreeNodeList;\n    \n    RootTreeNode->findLeafList(\n        TreeNodeList, CapsuleLineInv, (RivalMatInv.getScale() * getRadius()).getMax()\n    );\n    \n    /* Check collision with triangle faces of each tree-node */\n    foreach (const TreeNode* Node, TreeNodeList)\n    {\n        /* Get tree node data */\n        CollisionMesh::TreeNodeDataType* TreeNodeData = static_cast<CollisionMesh::TreeNodeDataType*>(Node->getUserData());\n        \n        if (!TreeNodeData)\n            continue;\n        \n        /* Check collision with each triangle face */\n        #ifndef _DEB_NEW_KDTREE_\n        foreach (SCollisionFace* Face, *TreeNodeData)\n        #else\n        foreach (SCollisionFace &NodeFace, *TreeNodeData)\n        #endif\n        {\n            #ifndef _DEB_NEW_KDTREE_\n            /* Check for unique usage */\n            if (FaceMap.find(Face) != FaceMap.end())\n                continue;\n            \n            FaceMap[Face] = true;\n            #else\n            SCollisionFace* Face = &NodeFace;\n            #endif\n            \n            /* Check for face-culling */\n            if (Face->isBackFaceCulling(CollFace, CapsuleLineInv))\n                continue;\n            \n            /* Make capsule-triangle collision test */\n            const dim::triangle3df Triangle(RivalMat * Face->Triangle);\n            \n            if (!math::CollisionLibrary::getClosestLineStraight(Triangle, CapsuleLine, ClosestLine))\n                continue;\n            \n            /* Check if this is a potentially new closest face */\n            if (math::getDistanceSq(ClosestLine.Start, ClosestLine.End) < RadiusSq)\n            {\n                /* Perform detected collision contact */\n                SCollisionContact Contact;\n                {\n                    Contact.Point       = ClosestLine.Start;\n                    Contact.Normal      = Triangle.getNormal();\n                    Contact.Impact      = getRadius() - (ClosestLine.End - Contact.Point).getLength();\n                    Contact.Triangle    = Triangle;\n                    Contact.Face        = Face;\n                }\n                performDetectedContact(Rival, Contact);\n                \n                if (getFlags() & COLLISIONFLAG_RESOLVE)\n                {\n                    /* Update capsule position */\n                    CapsuleLine             = getLine();\n                    CapsuleLineInv.Start    = RivalMatInv * CapsuleLine.Start;\n                    CapsuleLineInv.End      = RivalMatInv * CapsuleLine.End;\n                }\n            }\n        }\n    }\n    \n    /* Check collision with triangle edges of each tree-node */\n    foreach (const TreeNode* Node, TreeNodeList)\n    {\n        /* Get tree node data */\n        CollisionMesh::TreeNodeDataType* TreeNodeData = static_cast<CollisionMesh::TreeNodeDataType*>(Node->getUserData());\n        \n        if (!TreeNodeData)\n            continue;\n        \n        /* Check collision with each triangle edge */\n        #ifndef _DEB_NEW_KDTREE_\n        foreach (SCollisionFace* Face, *TreeNodeData)\n        #else\n        foreach (SCollisionFace &NodeFace, *TreeNodeData)\n        #endif\n        {\n            #ifndef _DEB_NEW_KDTREE_\n            /* Check for unique usage */\n            if (EdgeFaceMap.find(Face) != EdgeFaceMap.end())\n                continue;\n            \n            EdgeFaceMap[Face] = true;\n            #else\n            SCollisionFace* Face = &NodeFace;\n            #endif\n            \n            /* Check for face-culling */\n            if (Face->isBackFaceCulling(CollFace, CapsuleLineInv))\n                continue;\n            \n            /* Make capsule-triangle collision test */\n            const dim::triangle3df Triangle(RivalMat * Face->Triangle);\n            \n            ClosestLine = math::CollisionLibrary::getClosestLine(Triangle, CapsuleLine);\n            \n            /* Check if this is a potentially new closest face */\n            if (math::getDistanceSq(ClosestLine.Start, ClosestLine.End) < RadiusSq)\n            {\n                /* Perform detected collision contact */\n                SCollisionContact Contact;\n                {\n                    Contact.Point = ClosestLine.Start;\n                    \n                    Contact.Normal = ClosestLine.End;\n                    Contact.Normal -= ClosestLine.Start;\n                    Contact.Normal.normalize();\n                    \n                    Contact.Impact      = getRadius() - (ClosestLine.End - Contact.Point).getLength();\n                    Contact.Triangle    = Triangle;\n                    Contact.Face        = Face;\n                }\n                performDetectedContact(Rival, Contact);\n                \n                if (getFlags() & COLLISIONFLAG_RESOLVE)\n                {\n                    /* Update capsule position */\n                    CapsuleLine             = getLine();\n                    CapsuleLineInv.Start    = RivalMatInv * CapsuleLine.Start;\n                    CapsuleLineInv.End      = RivalMatInv * CapsuleLine.End;\n                }\n            }\n        }\n    }\n}\n\nbool CollisionCapsule::setupCollisionContact(\n    const dim::vector3df &PointP, const dim::vector3df &PointQ,\n    f32 MaxRadius, f32 RivalRadius, SCollisionContact &Contact) const\n{\n    /* Compute normal and impact together to avoid calling square-root twice */\n    Contact.Normal = PointP;\n    Contact.Normal -= PointQ;\n    \n    Contact.Impact = Contact.Normal.getLength();\n    \n    if (Contact.Impact < math::ROUNDING_ERROR)\n        return false;\n    \n    Contact.Normal *= (1.0f / Contact.Impact);\n    Contact.Impact = MaxRadius - Contact.Impact;\n    \n    Contact.Point = Contact.Normal;\n    Contact.Point *= RivalRadius;\n    Contact.Point += PointQ;\n    \n    return true;\n}\n\n\n} // /namespace scene\n\n} // /namespace sp\n\n\n\n// ================================================================================\n", "meta": {"hexsha": "2fb59d9b2cee9e409976fff49c37cb2504d4b1a1", "size": 19696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/SceneGraph/Collision/spCollisionCapsule.cpp", "max_stars_repo_name": "rontrek/softpixel", "max_stars_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-08-16T21:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-21T17:22:01.000Z", "max_issues_repo_path": "sources/SceneGraph/Collision/spCollisionCapsule.cpp", "max_issues_repo_name": "rontrek/softpixel", "max_issues_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/SceneGraph/Collision/spCollisionCapsule.cpp", "max_forks_repo_name": "rontrek/softpixel", "max_forks_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-15T09:17:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T14:10:40.000Z", "avg_line_length": 32.6633499171, "max_line_length": 134, "alphanum_fraction": 0.6020004062, "num_tokens": 4473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.18033809603395354}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <stdexcept>\n#include <functional>\n#include <random>\n#include <Eigen/Geometry>\n#include <visualization_msgs/Marker.h>\n#include \"arc_utilities/eigen_helpers.hpp\"\n#include \"arc_utilities/eigen_helpers_conversions.hpp\"\n#include \"arc_utilities/pretty_print.hpp\"\n#include \"arc_utilities/voxel_grid.hpp\"\n#include \"arc_utilities/simple_rrt_planner.hpp\"\n#include \"uncertainty_planning_core/simple_pid_controller.hpp\"\n#include \"uncertainty_planning_core/simple_uncertainty_models.hpp\"\n#include \"uncertainty_planning_core/uncertainty_contact_planning.hpp\"\n#include \"uncertainty_planning_core/simple_robot_models.hpp\"\n#include \"uncertainty_planning_core/simple_samplers.hpp\"\n#include \"uncertainty_planning_core/uncertainty_planning_core.hpp\"\n#include \"fast_kinematic_simulator/fast_kinematic_simulator.hpp\"\n#include \"fast_kinematic_simulator/simulator_environment_builder.hpp\"\n#include \"uncertainty_planning_examples/config_common.hpp\"\n\n#ifndef SE3_COMMON_CONFIG_HPP\n#define SE3_COMMON_CONFIG_HPP\n\nnamespace se3_common_config\n{\n    inline uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS GetDefaultOptions()\n    {\n        uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS options;\n        options.clustering_type = uncertainty_contact_planning::CONVEX_REGION_SIGNATURE;\n        options.planner_time_limit = 300.0;\n        options.goal_bias = 0.1;\n        options.step_size = 24.0 * 0.125;\n        options.step_duration = 10.0;\n        options.goal_probability_threshold = 0.51;\n        options.goal_distance_threshold = 5.0 * 0.125;\n        options.connect_after_first_solution = 0.0;\n        options.signature_matching_threshold = 0.75;\n        options.distance_clustering_threshold = 15.0 * 0.125;\n        options.feasibility_alpha = 0.75;\n        options.variance_alpha = 0.75;\n        options.edge_attempt_count = 50u;\n        options.num_particles = 24u;\n        options.use_contact = true;\n        options.use_reverse = true;\n        options.use_spur_actions = true;\n        options.max_exec_actions = 1000u;\n        options.max_policy_exec_time = 300.0;\n        options.num_policy_simulations = 0u;\n        options.num_policy_executions = 1u;\n        options.policy_action_attempt_count = 100u;\n        options.debug_level = 0;\n        options.planner_log_file = \"/tmp/se3_planner_log.txt\";\n        options.policy_log_file = \"/tmp/se3_policy_log.txt\";\n        options.planned_policy_file = \"/tmp/se3_planned_policy.policy\";\n        options.executed_policy_file = \"/dev/null\";\n        return options;\n    }\n\n    inline uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS GetOptions()\n    {\n        return uncertainty_planning_core::GetOptions(GetDefaultOptions());\n    }\n\n    inline config_common::TASK_CONFIG_PARAMS GetDefaultExtraOptions()\n    {\n        return config_common::TASK_CONFIG_PARAMS(0.125, 10.0, 0.0, 0.125, \"peg_in_hole\");\n    }\n\n    inline config_common::TASK_CONFIG_PARAMS GetExtraOptions()\n    {\n        return config_common::GetOptions(GetDefaultExtraOptions());\n    }\n\n    inline simple_robot_models::SE3_ROBOT_CONFIG GetDefaultRobotConfig(const config_common::TASK_CONFIG_PARAMS& options)\n    {\n        const double kp = 1.0; //0.1\n        const double ki = 0.0;\n        const double kd = 0.0; //0.01;\n        const double i_clamp = 0.0;\n        const double velocity_limit = 1.0; //0.25; // 1.0;\n        const double angular_velocity_limit = velocity_limit * 0.25;\n        const double max_sensor_noise = options.sensor_error;\n        const double max_angular_sensor_noise = max_sensor_noise * 0.25;\n        const double max_actuator_noise = options.actuator_error;\n        const double max_angular_actuator_noise = max_actuator_noise * 0.25;\n        const simple_robot_models::SE3_ROBOT_CONFIG robot_config(kp, ki, kd, i_clamp, velocity_limit, max_sensor_noise, max_actuator_noise, kp, ki, kd, i_clamp, angular_velocity_limit, max_angular_sensor_noise, max_angular_actuator_noise);\n        return robot_config;\n    }\n\n    inline Eigen::Isometry3d MakeConfig(const Eigen::Translation3d& translation, const Eigen::Quaterniond& rotation)\n    {\n        const Eigen::Isometry3d config = translation * rotation;\n        return config;\n    }\n\n    inline std::pair<Eigen::Isometry3d, Eigen::Isometry3d> GetStartAndGoal()\n    {\n        // Define the goals of the plan\n        const Eigen::Isometry3d start = MakeConfig(Eigen::Translation3d(9.0, 9.0, 9.0), Eigen::Quaterniond::Identity());\n        const Eigen::Isometry3d goal = MakeConfig(Eigen::Translation3d(2.25, 2.25, 0.625), Eigen::Quaterniond::Identity());\n        return std::make_pair(start, goal);\n    }\n\n    inline std::shared_ptr<EigenHelpers::VectorVector4d> GetRobotPoints()\n    {\n        std::shared_ptr<EigenHelpers::VectorVector4d> robot_points(new EigenHelpers::VectorVector4d());\n        const std::vector<double> x_pos = {-0.1875, -0.0625, 0.0625, 0.1875};\n        const std::vector<double> y_pos = {-0.1875, -0.0625, 0.0625, 0.1875};\n        const std::vector<double> z_pos = {-0.4375, -0.3125, -0.1875, -0.0625, 0.0625, 0.1875, 0.3125, 0.4375};\n        for (size_t xpdx = 0; xpdx < x_pos.size(); xpdx++)\n        {\n            for (size_t ypdx = 0; ypdx < y_pos.size(); ypdx++)\n            {\n                for (size_t zpdx = 0; zpdx < z_pos.size(); zpdx++)\n                {\n                    robot_points->push_back(Eigen::Vector4d(x_pos[xpdx], y_pos[ypdx], z_pos[zpdx], 1.0));\n                }\n            }\n        }\n        return robot_points;\n    }\n\n    inline simple_robot_models::SimpleSE3Robot GetRobot(const simple_robot_models::SE3_ROBOT_CONFIG& robot_config)\n    {\n        // Make the actual robot\n        const Eigen::Isometry3d initial_config = Eigen::Isometry3d::Identity();\n        simple_robot_models::SimpleSE3Robot robot(GetRobotPoints(), initial_config, robot_config);\n        return robot;\n    }\n\n    inline uncertainty_planning_core::SE3SamplerPtr GetSampler()\n    {\n        const double env_resolution = 0.125;\n        const double env_min_x = 0.0 + (env_resolution);\n        const double env_max_x = 10.0 - (env_resolution);\n        const double env_min_y = 0.0 + (env_resolution);\n        const double env_max_y = 10.0 - (env_resolution);\n        const double env_min_z = 0.0 + (env_resolution);\n        const double env_max_z = 10.0 - (env_resolution);\n        // Make the sampler\n        return uncertainty_planning_core::SE3SamplerPtr(new simple_samplers::SimpleSE3BaseSampler<uncertainty_planning_core::PRNG>(std::pair<double, double>(env_min_x, env_max_x), std::pair<double, double>(env_min_y, env_max_y), std::pair<double, double>(env_min_z, env_max_z)));\n    }\n\n    inline uncertainty_planning_core::SE3SimulatorPtr GetSimulator(const config_common::TASK_CONFIG_PARAMS& options, const int32_t debug_level)\n    {\n        const int32_t real_debug_level = std::max(0, debug_level - 1);\n        const simulator_environment_builder::EnvironmentComponents environment_components = simulator_environment_builder::BuildCompleteEnvironment(options.environment_id, options.environment_resolution);\n        const fast_kinematic_simulator::SolverParameters solver_params = fast_kinematic_simulator::GetDefaultSolverParameters();\n        return fast_kinematic_simulator::MakeSE3Simulator(environment_components.GetEnvironment(), environment_components.GetEnvironmentSDF(), environment_components.GetSurfaceNormalsGrid(), solver_params, options.simulation_controller_frequency, real_debug_level);\n    }\n}\n\n#endif // SE3_COMMON_CONFIG_HPP\n", "meta": {"hexsha": "a25c8f76af72ec74a2c723bb54f9c8cf5a7aace5", "size": 7623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uncertainty_planning_examples/se3_common_config.hpp", "max_stars_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_stars_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T05:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T02:12:02.000Z", "max_issues_repo_path": "include/uncertainty_planning_examples/se3_common_config.hpp", "max_issues_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_issues_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "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/uncertainty_planning_examples/se3_common_config.hpp", "max_forks_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_forks_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-04-17T03:08:47.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-04T13:08:59.000Z", "avg_line_length": 47.0555555556, "max_line_length": 279, "alphanum_fraction": 0.7182211728, "num_tokens": 1893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1803380910784898}}
{"text": "#include <idmlib/resys/context/FactorizationMachine.h>\n\n#include <am/graphchi/engine/dynamic_graphs/graphchi_dynamicgraph_engine.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/random.hpp>\n\n#include <util/ClockTimer.h>\n#include <boost/timer.hpp>\n\n#include <list>\n#include <string>\n\n#include <cmath>\n\n\nusing namespace graphchi;\nusing namespace idmlib::recommender;\n\nnamespace bfs = boost::filesystem;\n\nconst char* TEST_DIR_STR = \"fm\";\n\nBOOST_AUTO_TEST_SUITE(FactorizationMachineTest)\n\nBOOST_AUTO_TEST_CASE(factorInmemTest)\n{\n    bfs::path fmPath(TEST_DIR_STR);\n    boost::filesystem::remove_all(fmPath);\n    bfs::create_directories(fmPath);\n\n    std::string filename = fmPath.string() + \"/fmdb\";\n    typedef vertex_data<20> VertexDataType;\n    typedef FactorContainerInMem<VertexDataType> FactorContainerType;\n    unsigned size = 100;\n    {\n        FactorContainerType db(filename);\n        db.Init(size);\n        for(unsigned i = 0; i < size; ++i)\n        {\n            VertexDataType& v = db[i];\n            v.bias = i;\n        }\n    }\n    FactorContainerType db(filename);\t\n    db.Init(size);\n    for(unsigned i = 0; i < size; ++i)\n    {\n        VertexDataType& v = db[i];\n        BOOST_CHECK_EQUAL(v.bias, i);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(factorDBTest)\n{\n    bfs::path fmPath(TEST_DIR_STR);\n    boost::filesystem::remove_all(fmPath);\n    bfs::create_directories(fmPath);\n\n    std::string filename = fmPath.string() + \"/fmdb\";\n    typedef vertex_data<20> VertexDataType;\n    typedef FactorContainerDB<VertexDataType> FactorContainerType;\n    unsigned size = 100;\n    {\n        FactorContainerType db(filename, sizeof(VertexDataType)*10);\n        db.Init(size);\n        for(unsigned i = 0; i < size; ++i)\n        {\n            VertexDataType& v = db[i];\n            v.bias = i;\n        }\n    }\n    FactorContainerType db(filename, sizeof(VertexDataType)*10);\n    db.Init(size);\n    for(unsigned i = 0; i < size; ++i)\n    {\n        VertexDataType& v = db[i];\n        BOOST_CHECK_EQUAL(v.bias, i);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(smokeTest)\n{\n#if 0\n    bfs::path fmPath(TEST_DIR_STR);\n    boost::filesystem::remove_all(fmPath);\n    bfs::create_directories(fmPath);\n\n    metrics m(\"fm\");\n\n    typedef vertex_data<20> VertexDataType;\n    typedef edge_data<0> EdgeDataType;\n\n    typedef FactorizationMachine<20, VertexDataType, EdgeDataType > FMType;\n    typedef FactorizationMachine<20, VertexDataType, EdgeDataType, true > ImplicitFMType;\n\n    std::string filename = fmPath.string() + \"/graphchi_fm\";\n    \n    int niters = 4; // Number of iterations\n    bool scheduler = false;                       // Whether to use selective scheduling\n\n    /* Detect the number of shards or preprocess an input to creae them */\n    int nshards = convert_if_notexists<EdgeDataType >(filename, \n                                                              get_option_string(\"nshards\", \"auto\"));\n\n    /* Run */\n    graphchi_engine<VertexDataType, EdgeDataType > engine(filename, nshards, scheduler, m); \n    engine.set_disable_vertexdata_storage();  \n    engine.set_modifies_outedges(false);\n    engine.set_modifies_inedges(false); // Improves I/O performance.\n    std::string factor_db = filename + \"/fmdb\";\n    FMType fm(factor_db,1,0.1,0.1,0.1);\n    engine.run(fm, niters);\n    ImplicitFMType fm2(factor_db,1,0.1,0.1,0.1);\n\n    metrics_report(m);\n#endif\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4558f789f51e60e3908c800bbd4c773fd83ed33f", "size": 3450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/resys/t_FactorizationMachine.cpp", "max_stars_repo_name": "izenecloud/idmlib", "max_stars_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T06:37:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-14T06:37:25.000Z", "max_issues_repo_path": "test/resys/t_FactorizationMachine.cpp", "max_issues_repo_name": "izenecloud/idmlib", "max_issues_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "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/resys/t_FactorizationMachine.cpp", "max_forks_repo_name": "izenecloud/idmlib", "max_forks_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-09-06T05:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T06:11:24.000Z", "avg_line_length": 27.8225806452, "max_line_length": 100, "alphanum_fraction": 0.66, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1803380910784898}}
{"text": "// Copyright (c) 2014-2015 DiMS dev-team\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 <math.h>\n#include \"util.h\"\n\n#include <boost/foreach.hpp>\n\n#include \"common/actionHandler.h\"\n#include \"common/authenticationProvider.h\"\n\n#include \"monitor/rankingDatabase.h\"\n#include \"monitor/controller.h\"\n#include \"monitor/admitTrackerAction.h\"\n#include \"monitor/reputationTracer.h\"\n#include \"monitor/activityControllerAction.h\"\n#include \"monitor/pingAction.h\"\n#include \"monitor/updateNetworkDataAction.h\"\n#include \"monitor/reputationControlAction.h\"\n\nnamespace common\n{\nstd::vector< uint256 > deleteList;\n}\n\nnamespace monitor\n{\ndouble const PreviousReptationRatio = 0.99;// I want  to preserve  a lot\n\ndouble const TriggerExtendRatio = 0.1;\ndouble const RelativeToMax = 0.3;\nunsigned int const OneTransactionGain = 10;\nunsigned int const BoostForServicesAlone = 10;\n\n\n// allow some  deviation for  other monitors\n\nuint64_t const CReputationTracker::m_recalculateTime = 60;// seconds, this  time is  vital how frequent it should be???\n\nCReputationTracker::CReputationTracker()\n{\n\tstd::map< uint160, common::CTrackerData > trackers;\n\tCRankingDatabase::getInstance()->loadIdentificationDatabase( trackers );\n\n\tstd::map< uint160, common::CTrackerData >::const_iterator iterator = trackers.begin();\n\n\twhile( iterator != trackers.end() )\n\t{\n\t\taddTracker( iterator->second );\n\t\taddNodeToSynch( iterator->second.m_publicKey.GetID() );\n\t\titerator++;\n\t}\n}\n\nCReputationTracker*\nCReputationTracker::getInstance()\n{\n\tif ( !ms_instance )\n\t{\n\t\tms_instance = new CReputationTracker();\n\t};\n\treturn dynamic_cast<CReputationTracker *>( ms_instance );\n}\n\nvoid\nCReputationTracker::calculateReputation()\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tunsigned int  maxTransactionNumber = 0;\n\tBOOST_FOREACH( TransactionsAddmited::value_type & transactionIndicator, m_transactionsAddmited )\n\t{\n\t\tif ( maxTransactionNumber < transactionIndicator.second )\n\t\t{\n\t\t\tmaxTransactionNumber = transactionIndicator.second;\n\t\t}\n\t}\n\n\tunsigned int boostForAll = ( maxTransactionNumber + BoostForServicesAlone )* OneTransactionGain * RelativeToMax;\n\n\tBOOST_FOREACH( PAIRTYPE( uint160 const, common::CTrackerData ) & tracker, m_registeredTrackers )\n\t{\n\t\ttracker.second.m_reputation *= PreviousReptationRatio;\n\t\tif ( m_presentNodes.find( tracker.first ) != m_presentNodes.end() )\n\t\t{\n\t\t\ttracker.second.m_reputation += boostForAll;\n\t\t}\n\t}\n\n\tBOOST_FOREACH( TransactionsAddmited::value_type & transactionIndicator, m_transactionsAddmited )\n\t{\n\t\tstd::map< uint160, common::CTrackerData >::iterator iterator = m_registeredTrackers.find( transactionIndicator.first );\n\n\t\tif ( m_registeredTrackers.end() != iterator )\n\t\t{\n\t\t\titerator->second.m_reputation += transactionIndicator.second * OneTransactionGain;\n\t\t}\n\t}\n\n\tm_transactionsAddmited.clear();\n}\n\nvoid\nCReputationTracker::loop()\n{\n\twhile( 1 )\n\t{\n\t\tstd::list< uint160 > toBeRemoved;\n\t\t{\n\t\t\tboost::lock_guard<boost::mutex> lock( m_lock );\n\n\t\t\tBOOST_FOREACH( PAIRTYPE( uint160 const, common::CTrackerData ) & tracker, m_registeredTrackers )\n\t\t\t{\n\t\t\t\tint64_t timePassed = GetTime() - tracker.second.m_contractTime;\n\t\t\t\tint64_t timeLeft = tracker.second.m_networkTime - timePassed;\n\n\t\t\t\tif ( timeLeft < 0 )\n\t\t\t\t{\n\t\t\t\t\tCRankingDatabase::getInstance()->eraseTrackerData( tracker.second.m_publicKey );\n\t\t\t\t\ttoBeRemoved.push_back( tracker.second.m_publicKey.GetID() );\n\t\t\t\t\tm_allowSynchronization.erase( tracker.second.m_publicKey.GetID() );\n\t\t\t\t}\n\t\t\t\telse if ( timeLeft < CController::getInstance()->getPeriod() * TriggerExtendRatio )\n\t\t\t\t{\n\t\t\t\t\tif ( !isExtendInProgress( tracker.second.m_publicKey ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tsetExtendInProgress( tracker.second.m_publicKey );\n\t\t\t\t\t\tcommon::CActionHandler::getInstance()->executeAction( new CAdmitTrackerAction(tracker.second.m_publicKey) );\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\tif ( isExtendInProgress( tracker.second.m_publicKey ) )\n\t\t\t\t\t\tm_extendInProgress.erase( tracker.second.m_publicKey );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tBOOST_FOREACH( uint160 const & id, toBeRemoved )\n\t\t\t{\n\t\t\t\tm_registeredTrackers.erase( id );\n\t\t\t}\n\n\t\t}\n\n\t\t// outside of  lock  scope\n\t\tcommon::CRankingFullInfo rankingFullInfo(\n\t\t\t\t\tgetAllyTrackers()\n\t\t\t\t\t, getAllyMonitors()\n\t\t\t\t\t, getTrackers()\n\t\t\t\t\t, getSynchronizedTrackers()\n\t\t\t\t\t, getMeasureReputationTime()\n\t\t\t\t\t, CReputationControlAction::getInstance() ? CReputationControlAction::getInstance()->getActionKey() : uint256() );\n\n\t\tif ( !toBeRemoved.empty() )\n\t\t{\n\t\t\tcommon::CActionHandler::getInstance()->executeAction( new CUpdateNetworkDataAction( rankingFullInfo, common::CMediumKinds::DimsNodes ) );\n\t\t}\n\n\t\tMilliSleep( 1000 );\n\t}\n}\n\nvoid\nCReputationTracker::storeCurrentRanking()\n{\n\tBOOST_FOREACH( PAIRTYPE( uint160 const, common::CTrackerData ) & tracker, m_registeredTrackers )\n\t{\n\t\tCRankingDatabase::getInstance()->writeTrackerData( tracker.second );\n\t}\n}\n\nvoid\nCReputationTracker::loadCurrentRanking()\n{\n\tCRankingDatabase::getInstance()->loadIdentificationDatabase( m_registeredTrackers );\n}\n\nvoid\nCReputationTracker::setNodeInfo( common::CValidNodeInfo const & _validNodeInfo, common::CRole::Enum _role )\n{\n\tswitch( _role )\n\t{\n\tcase common::CRole::Seed:\n\t\tbreak;\n\tcase common::CRole::Tracker:\n\t\tm_knownTrackers.insert( _validNodeInfo );\n\t\tbreak;\n\tcase common::CRole::Monitor:\n\t\tm_knownMonitors.insert( _validNodeInfo );\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid\nCReputationTracker::clearTransactions()\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tm_transactionsAddmited.clear();\n}\n\nvoid\nCReputationTracker::recalculateReputation()\n{\n\tm_measureReputationTime += m_recalculateTime;\n\tcalculateReputation();\n}\n\nvoid\nCReputationTracker::checkValidity( common::CAllyTrackerData const & _allyTrackerData )\n{\n}\n\nstd::set< common::CTrackerData >\nCReputationTracker::getTrackers() const\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tstd::set< common::CTrackerData >trackers;\n\n\tBOOST_FOREACH( PAIRTYPE( uint160, common::CTrackerData ) const & tracker, m_registeredTrackers )\n\t{\n\t\ttrackers.insert( tracker.second );\n\t}\n\treturn trackers;\n}\n\nstd::set< common::CAllyMonitorData >\nCReputationTracker::getAllyMonitors() const\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tstd::set< common::CAllyMonitorData > monitors;\n\n\tBOOST_FOREACH( PAIRTYPE( uint160, common::CAllyMonitorData ) const & monitor, m_allyMonitors )\n\t{\n\t\tmonitors.insert( monitor.second );\n\t}\n\n\treturn monitors;\n}\n\nstd::set< common::CAllyTrackerData >\nCReputationTracker::getAllyTrackers() const\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tstd::set< common::CAllyTrackerData > trackers;\n\n\tBOOST_FOREACH( PAIRTYPE( uint160, common::CAllyTrackerData ) const & tracker, m_allyTrackersRankings )\n\t{\n\t\ttrackers.insert( tracker.second );\n\t}\n\n\treturn trackers;\n}\n\nstd::list< common::CMedium *>\nCReputationTracker::provideConnection( common::CMediumFilter const & _mediumFilter )\n{\n\tstd::list< common::CMedium*> mediums = common::CNodesManager::provideConnection( _mediumFilter );\n\n\tif ( !mediums.empty() )\n\t\treturn mediums;\n\n\treturn _mediumFilter.getMediums( this );\n}\n\nstd::list< common::CMedium *>\nCReputationTracker::getNodesByClass( common::CMediumKinds::Enum _nodesClass ) const\n{\n\tstd::list< common::CMedium *> mediums;\n\n\tuintptr_t nodeIndicator;\n\n\tif ( !CController::getInstance()->isAdmitted() )\n\t{\n\t\tif ( _nodesClass == common::CMediumKinds::DimsNodes\n\t\t\t || _nodesClass == common::CMediumKinds::Monitors\n\t\t\t || _nodesClass == common::CMediumKinds::Trackers\n\t\t\t )\n\t\t{\n\t\t\tif ( _nodesClass != common::CMediumKinds::Trackers )\n\t\t\t{\n\t\t\t\tBOOST_FOREACH( common::CValidNodeInfo const & validNode, m_knownMonitors )\n\t\t\t\t{\n\t\t\t\t\t// in case  of  fail  do  something ??\n\t\t\t\t\tif ( getKeyToNode( validNode.m_publicKey.GetID(), nodeIndicator) )\n\t\t\t\t\t{\n\t\t\t\t\t\tcommon::CMedium * medium = findNodeMedium( nodeIndicator );\n\t\t\t\t\t\tif ( medium )\n\t\t\t\t\t\t\tmediums.push_back( medium );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( _nodesClass != common::CMediumKinds::Monitors )\n\t\t\t{\n\t\t\t\tBOOST_FOREACH( common::CValidNodeInfo const & validNode, m_knownTrackers )\n\t\t\t\t{\n\t\t\t\t\tif ( getKeyToNode( validNode.m_publicKey.GetID(), nodeIndicator) )\n\t\t\t\t\t{\n\t\t\t\t\t\tcommon::CMedium * medium = findNodeMedium( nodeIndicator );\n\t\t\t\t\t\tif ( medium )\n\t\t\t\t\t\t\tmediums.push_back( medium );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mediums;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif ( _nodesClass == common::CMediumKinds::DimsNodes\n\t\t\t || _nodesClass == common::CMediumKinds::Monitors\n\t\t\t || _nodesClass == common::CMediumKinds::Trackers\n\t\t\t )\n\t\t{\n\t\t\tif ( _nodesClass != common::CMediumKinds::Monitors )\n\t\t\t{\n\n\t\t\t\tBOOST_FOREACH( PAIRTYPE( uint160, common::CTrackerData ) const & trackerData, m_registeredTrackers )\n\t\t\t\t{\n\t\t\t\t\tif ( m_presentNodes.find( trackerData.first ) != m_presentNodes.end() && m_synchronizedTrackers.find( trackerData.first ) != m_synchronizedTrackers.end() )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( !getKeyToNode( trackerData.second.m_publicKey.GetID(), nodeIndicator) )\n\t\t\t\t\t\t\tassert( !\"something wrong\" );\n\n\t\t\t\t\t\tcommon::CMedium * medium = findNodeMedium( nodeIndicator );\n\n\t\t\t\t\t\tif ( !medium )\n\t\t\t\t\t\t\tassert( !\"something wrong\" );\n\t\t\t\t\t\tmediums.push_back( medium );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tBOOST_FOREACH( PAIRTYPE( uint160, common::CAllyTrackerData ) const & trackerData, m_allyTrackersRankings )\n\t\t\t\t{\n\t\t\t\t\tif ( m_presentNodes.find( trackerData.first ) != m_presentNodes.end() && m_synchronizedTrackers.find( trackerData.first ) != m_synchronizedTrackers.end() )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( !getKeyToNode( trackerData.second.m_publicKey.GetID(), nodeIndicator) )\n\t\t\t\t\t\t\tassert( !\"something wrong\" );\n\n\t\t\t\t\t\tcommon::CMedium * medium = findNodeMedium( nodeIndicator );\n\n\t\t\t\t\t\tif ( !medium )\n\t\t\t\t\t\t\tassert( !\"something wrong\" );\n\t\t\t\t\t\tmediums.push_back( medium );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( _nodesClass != common::CMediumKinds::Trackers )\n\t\t\t{\n\t\t\t\tBOOST_FOREACH( PAIRTYPE( uint160, common::CAllyMonitorData ) const & monitorData, m_allyMonitors )\n\t\t\t\t{\n\t\t\t\t\tif ( m_presentNodes.find( monitorData.first ) != m_presentNodes.end() )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( !getKeyToNode( monitorData.second.m_publicKey.GetID(), nodeIndicator) )\n\t\t\t\t\t\t\tassert( !\"something wrong\" );\n\n\t\t\t\t\t\tcommon::CMedium * medium = findNodeMedium( nodeIndicator );\n\n\t\t\t\t\t\tif ( !medium )\n\t\t\t\t\t\t\tassert( !\"something wrong\" );\n\t\t\t\t\t\tmediums.push_back( medium );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn mediums;\n}\n\nvoid\nCReputationTracker::setKeyToNode( CPubKey const & _pubKey, uintptr_t _nodeIndicator)\n{\n\tm_pubKeyToNodeIndicator.erase(_pubKey);\n\tm_pubKeyToNodeIndicator.insert( std::make_pair( _pubKey, _nodeIndicator ) );\n}\n\nbool\nCReputationTracker::getKeyToNode( uint160 const & _pubKeyId, uintptr_t & _nodeIndicator) const\n{\n\tstd::map< CPubKey, uintptr_t >::const_iterator iterator =\n\t\t\tm_pubKeyToNodeIndicator.begin();\n\n\twhile( iterator != m_pubKeyToNodeIndicator.end() )\n\t{\n\t\tif ( iterator->first.GetID() == _pubKeyId )\n\t\t\tbreak;\n\t\titerator++;\n\t}\n\n\n\tif ( iterator != m_pubKeyToNodeIndicator.end() )\n\t\t_nodeIndicator = iterator->second;\n\n\treturn iterator != m_pubKeyToNodeIndicator.end();\n}\n\nbool\nCReputationTracker::getNodeToKey( uintptr_t _nodeIndicator, CPubKey & _pubKey )const\n{\n\tBOOST_FOREACH( PAIRTYPE(CPubKey, uintptr_t) const & keyToIndicator, m_pubKeyToNodeIndicator )\n\t{\n\t\tif ( keyToIndicator.second == _nodeIndicator )\n\t\t{\n\t\t\t_pubKey = keyToIndicator.first;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nstd::set< uint160 >\nCReputationTracker::getPresentAndSynchronizedTrackers() const\n{\n\tstd::set< common::CTrackerData > trackers = getTrackers();\n\n\tstd::set< uint160 > presentTrackers;\n\tBOOST_FOREACH( common::CTrackerData const & trackerData, trackers )\n\t{\n\t\tif ( isPresentNode( trackerData.m_publicKey.GetID() ) && isTrackerSynchronized( trackerData.m_publicKey.GetID() ) )\n\t\t\tpresentTrackers.insert( trackerData.m_publicKey.GetID() );\n\t}\n\n\tstd::set< common::CAllyTrackerData > allyTrackers = getAllyTrackers();\n\n\tBOOST_FOREACH( common::CAllyTrackerData const & allyTracker, allyTrackers )\n\t{\n\t\tif ( isPresentNode( allyTracker.m_publicKey.GetID() ) && isTrackerSynchronized( allyTracker.m_publicKey.GetID() ) )\n\t\t\tpresentTrackers.insert( allyTracker.m_publicKey.GetID() );\n\t}\n\n\treturn presentTrackers;\n}\n\nvoid\nCReputationTracker::eraseMedium( uintptr_t _nodePtr )\n{\n\tCPubKey key;\n\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\n\tif ( !getNodeToKey( _nodePtr, key ) )\n\t\treturn;\n\n\tCKeyID keyId = key.GetID();\n\n\tm_candidates.erase( keyId );\n\n\tm_transactionsAddmited.erase( keyId );\n\n\tm_presentNodes.erase( keyId );\n\n\tm_pubKeyToNodeIndicator.erase( key );\n\n\tCAddress address;\n\tif ( getAddress( _nodePtr, address ) )\n\t{\n\t\terasePubKey( address );\n\n\t\tcommon::CNodesManager::eraseMedium( _nodePtr );\n\n\t\tcommon::CActionHandler::getInstance()->executeAction( new CActivityControllerAction( key, address, CActivitySatatus::Inactive ) );\n\t}\n}\n\nvoid\nCReputationTracker::evaluateNode( common::CSelfNode * _selfNode )\n{\n\tCPubKey pubKey;\n\tif ( getPublicKey( _selfNode->addr, pubKey ) )\n\t{\n\t\tcommon::CActionHandler::getInstance()->executeAction( new CPingAction( _selfNode ) );\n\t}\n\telse\n\t{\n\t\t_selfNode->fDisconnect = true;  // for seed  and unknown\n\t}\n}\nstd::set< common::CValidNodeInfo > const\nCReputationTracker::getNodesInfo( common::CRole::Enum _role ) const\n{\n\tstd::set< common::CValidNodeInfo > nodesInfo;\n\tif ( _role == common::CRole::Tracker )\n\t{\n\t\tBOOST_FOREACH( PAIRTYPE( uint160 const, common::CTrackerData ) const & tracker, m_registeredTrackers )\n\t\t{\n\t\t\tuintptr_t nodePtr;\n\t\t\tgetKeyToNode( tracker.second.m_publicKey.GetID(), nodePtr );\n\n\t\t\tCAddress address;\n\t\t\tgetAddress( nodePtr, address );\n\n\t\t\tnodesInfo.insert( common::CValidNodeInfo( tracker.second.m_publicKey, address ) );\n\t\t}\n\t}\n\telse if ( _role == common::CRole::Monitor )\n\t{\n\t\tBOOST_FOREACH( PAIRTYPE( uint160, common::CAllyMonitorData ) const & monitor, m_allyMonitors )\n\t\t{\n\t\t\tuintptr_t nodePtr;\n\t\t\tgetKeyToNode( monitor.second.m_publicKey.GetID(), nodePtr );\n\n\t\t\tCAddress address;\n\t\t\tgetAddress( nodePtr, address );\n\n\t\t\tnodesInfo.insert( common::CValidNodeInfo( monitor.second.m_publicKey, address ) );\n\t\t}\n\t}\n\treturn nodesInfo;\n}\n\nbool\nCReputationTracker::checkForTracker( uint160 const & _pubKeyId, common::CTrackerData & _trackerData, CPubKey & _controllingMonitor )const\n{\n\tstd::map< uint160, common::CTrackerData >::const_iterator iterator = m_registeredTrackers.find( _pubKeyId );\n\n\tif ( iterator != m_registeredTrackers.end() )\n\t{\n\t\t_trackerData = iterator->second;\n\t\t_controllingMonitor = common::CAuthenticationProvider::getInstance()->getMyKey();\n\n\t\treturn true;\n\t}\n\n\tstd::map< uint160, common::CAllyTrackerData >::const_iterator allyIterator = m_allyTrackersRankings.find( _pubKeyId );\n\n\tif ( allyIterator == m_allyTrackersRankings.end() )\n\t\treturn  false;\n\n\t_trackerData = dynamic_cast<common::CTrackerData const&>( allyIterator->second );\n\n\t_controllingMonitor = allyIterator->second.m_allyMonitorKey;\n\n\treturn true;\n}\n\nvoid\nCReputationTracker::setExtendInProgress( CPubKey const & _pubKey )\n{\n\t\tm_extendInProgress.insert( _pubKey );\n}\n\nbool\nCReputationTracker::isExtendInProgress( CPubKey const & _pubKey )\n{\n\treturn m_extendInProgress.find(_pubKey) != m_extendInProgress.end();\n}\n\nbool\nCReputationTracker::eraseExtendInProgress( CPubKey const & _pubKey )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tm_extendInProgress.erase(_pubKey);\n\n\treturn true;\n}\n\nbool\nCReputationTracker::isAddmitedMonitor( uint160 const & _pubKeyId )\n{\n\treturn m_allyMonitors.find( _pubKeyId ) != m_allyMonitors.end();\n}\n\nbool\nCReputationTracker::isRegisteredTracker( uint160 const & _pubKeyId )\n{\n\tif ( m_registeredTrackers.find( _pubKeyId ) != m_registeredTrackers.end() )\n\t\treturn true;\n\n\treturn m_allyTrackersRankings.find( _pubKeyId ) != m_allyTrackersRankings.end();\n\n}\n\nvoid\nCReputationTracker::addTracker( common::CTrackerData const & _trackerData )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tm_registeredTrackers.erase( _trackerData.m_publicKey.GetID() );\n\tm_registeredTrackers.insert( std::make_pair( _trackerData.m_publicKey.GetID(), _trackerData ) );\n}\n\nbool\nCReputationTracker::getTracker( uint160 const & _pubKeyId, common::CTrackerData & _trackerData ) const\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tstd::map< uint160, common::CTrackerData >::const_iterator iterator =\n\t\t\tm_registeredTrackers.find( _pubKeyId );\n\n\tif ( iterator != m_registeredTrackers.end() )\n\t{\n\t\t_trackerData = (*iterator).second;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid\nCReputationTracker::removeTracker( uint160 const & _pubKeyId )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tm_registeredTrackers.find( _pubKeyId );\n}\n\nvoid\nCReputationTracker::addAllyTracker( common::CAllyTrackerData const & _trackerData )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\n\tm_allyTrackersRankings.erase( _trackerData.m_publicKey.GetID() );\n\tm_allyTrackersRankings.insert( make_pair( _trackerData.m_publicKey.GetID(), _trackerData ) );\n\n\tm_trackerToMonitor.erase( _trackerData.m_publicKey.GetID() );\n\tm_trackerToMonitor.insert( std::make_pair( _trackerData.m_publicKey.GetID(), _trackerData.m_allyMonitorKey.GetID() ) );\n}\n\nvoid\nCReputationTracker::removeAllyTracker( uint160 const & _pubKeyId )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tm_allyTrackersRankings.erase( _pubKeyId );\n\tm_trackerToMonitor.erase( _pubKeyId );\n}\n\nvoid\nCReputationTracker::addAllyMonitor( common::CAllyMonitorData const & _monitorData )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tif ( !(common::CAuthenticationProvider::getInstance()->getMyKey() == _monitorData.m_publicKey) )\n\t{\n\t\tm_allyMonitors.insert( std::make_pair( _monitorData.m_publicKey.GetID(), _monitorData ) );\n\t}\n}\n\nvoid\nCReputationTracker::removeAllyMonitor( uint160 const & _pubKeyId )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\n\tm_allyMonitors.erase( _pubKeyId );\n}\n\nvoid\nCReputationTracker::clearRankingData()\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tm_trackerToMonitor.clear();\n\tm_registeredTrackers.clear();\n\tm_allyTrackersRankings.clear();\n\tm_allyMonitors.clear();\n\tm_presentNodes.clear();\n\tm_extendInProgress.clear();\n\n\tCRankingDatabase::getInstance()->resetDb();\n}\n\nbool\nCReputationTracker::isSynchronizationAllowed( uint160 const & _pubKeyId )const\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\treturn m_allowSynchronization.find( _pubKeyId ) != m_allowSynchronization.end();\n}\n\nvoid\nCReputationTracker::removeNodeFromSynch( uint160 const & _pubKeyId )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tm_allowSynchronization.erase( _pubKeyId );\n}\n\nvoid\nCReputationTracker::addNodeToSynch( uint160 const & _pubKeyId )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tm_allowSynchronization.insert( _pubKeyId );\n}\n\nbool\nCReputationTracker::getAddresFromKey( uint160 const & _pubKeyId, CAddress & _address )const\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\tuintptr_t nodeIndicator;\n\tif ( !getKeyToNode( _pubKeyId, nodeIndicator ) )\n\t\treturn false;\n\n\treturn getAddress( nodeIndicator, _address );\n}\n\nvoid\nCReputationTracker::updateRankingInfo( CPubKey const & _pubKey, common::CRankingFullInfo const & _rankingFullInfo )\n{\n\tboost::lock_guard<boost::mutex> lock( m_lock );\n\t// sanity, TODO: later react if wrong\n\n\tif ( m_allyMonitors.find( _pubKey.GetID() ) == m_allyMonitors.end() )\n\t\treturn;\n\n\tBOOST_FOREACH( common::CAllyTrackerData const & allyTrackerData, _rankingFullInfo.m_allyTrackers )\n\t{\n\t\tif (\n\t\t\t\t\tm_registeredTrackers.find( allyTrackerData.m_publicKey.GetID() ) == m_registeredTrackers.end()\n\t\t\t\t&& m_allyTrackersRankings.find( allyTrackerData.m_publicKey.GetID() ) == m_allyTrackersRankings.end()\n\t\t\t\t\t)\n\t\t{\n\t\t\t//assert( !\"react  to  this\" );\n\t\t\t//  problem  here  but  work on it  another  day\n\t\t}\n\t}\n\n\tBOOST_FOREACH( common::CAllyMonitorData const & allyMonitorData, _rankingFullInfo.m_allyMonitors )\n\t{\n\t\tif ( m_knownMonitors.find( common::CValidNodeInfo( allyMonitorData.m_publicKey, allyMonitorData.m_address ) ) == m_knownMonitors.end() )\n\t\t\t;//create  connect  action ??\n\n\t\tif ( m_allyMonitors.find( allyMonitorData.m_publicKey.GetID() ) == m_allyMonitors.end() )\n\t\t{\n\t\t\tif ( !(common::CAuthenticationProvider::getInstance()->getMyKey() == allyMonitorData.m_publicKey) )\n\t\t\t{\n\t\t\t\tm_allyMonitors.insert( std::make_pair( allyMonitorData.m_publicKey.GetID(), allyMonitorData ) );\n\t\t\t}\n\t\t}\n\t}\n\n\t//add new tracker data, if any\n\n\tstd::set< uint160 > presentTrackers;\n\n\tBOOST_FOREACH( common::CTrackerData const & trackerData, _rankingFullInfo.m_trackers )\n\t{\n\t\tpresentTrackers.insert( trackerData.m_publicKey.GetID() );\n\n\t\tif ( m_allyTrackersRankings.find( trackerData.m_publicKey.GetID() ) == m_allyTrackersRankings.end() )\n\t\t{\n\t\t\tif ( m_knownTrackers.find( common::CValidNodeInfo( trackerData.m_publicKey, trackerData.m_address ) ) == m_knownTrackers.end() )\n\t\t\t\t;//create  connect  action ??\n\n\t\t\tm_allyTrackersRankings.insert( make_pair( trackerData.m_publicKey.GetID(), common::CAllyTrackerData( trackerData, _pubKey ) ) );\n\t\t\tm_trackerToMonitor.insert( std::make_pair( trackerData.m_publicKey.GetID(), _pubKey.GetID() ) );\n\t\t}\n\t}\n\n\tstd::list< uint160 > deleteTrackersList;\n\n\t// gather  all tracker   with  this  monitor\n\tBOOST_FOREACH( PAIRTYPE( uint160, uint160 ) const & trackerToMonitor, m_trackerToMonitor )\n\t{\n\t\tif ( trackerToMonitor.second == _pubKey.GetID() )\n\t\t{\n\t\t\tif ( presentTrackers.find( trackerToMonitor.first ) == presentTrackers.end() )\n\t\t\t{\n\t\t\t\tdeleteTrackersList.push_back( trackerToMonitor.first );\n\t\t\t}\n\t\t}\n\t}\n\n\tBOOST_FOREACH( uint160 const & trackerKey, deleteTrackersList )\n\t{\n\t\t\tm_allyTrackersRankings.erase( trackerKey );\n\t\t\tm_trackerToMonitor.erase( trackerKey );\n\t\t\tm_synchronizedTrackers.erase( trackerKey );\n\t}\n\n\tBOOST_FOREACH( uint160 const & keyId, _rankingFullInfo.m_synchronizedTrackers )\n\t{\n\t\tm_synchronizedTrackers.insert( keyId );\n\t}\n\t// popagate  ranking ??\n}\n\n}\n", "meta": {"hexsha": "d306c857ead38bb8c615a197447cbf6d6c61efb8", "size": 21671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/monitor/reputationTracer.cpp", "max_stars_repo_name": "salarii/dims", "max_stars_repo_head_hexsha": "b8008c49edd10a9ca50923b89e3b469c342d9cee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T11:22:19.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-22T11:22:19.000Z", "max_issues_repo_path": "src/monitor/reputationTracer.cpp", "max_issues_repo_name": "salivan-ratcoin-dev-team/dims", "max_issues_repo_head_hexsha": "b8008c49edd10a9ca50923b89e3b469c342d9cee", "max_issues_repo_licenses": ["MIT"], "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/monitor/reputationTracer.cpp", "max_forks_repo_name": "salivan-ratcoin-dev-team/dims", "max_forks_repo_head_hexsha": "b8008c49edd10a9ca50923b89e3b469c342d9cee", "max_forks_repo_licenses": ["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.9987080103, "max_line_length": 160, "alphanum_fraction": 0.7316229062, "num_tokens": 5863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.1802533617717944}}
{"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/base/cards.h\"\n#include \"ps/support/command.h\"\n#include \"ps/detail/print.h\"\n#include \"ps/eval/class_cache.h\"\n#include \"ps/eval/holdem_class_vector_cache.h\"\n#include \"app/pretty_printer.h\"\n#include \"app/serialization_util.h\"\n#include \"ps/detail/graph.h\"\n\n#include \"ps/sim/computer.h\"\n#include \"ps/sim/game_tree.h\"\n#include \"ps/sim/computer_factory.h\"\n#include \"ps/sim/_extra.h\"\n#include \"ps/sim/solver.h\"\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n\nnamespace bpt = boost::property_tree;\n\n#include <numeric>\n\n\n#include <boost/timer/timer.hpp>\n\nnamespace ps{\nnamespace sim{\n        struct DeltaSequence : Solver{\n                DeltaSequence(std::shared_ptr<GameTree> gt_, GraphColouring<AggregateComputer> AG_, StateType state0_, double factor_, double epsilon_, size_t stride_)\n                        :gt(gt_),\n                        AG(AG_),\n                        state0(state0_),\n                        factor(factor_),\n                        epsilon(epsilon_),\n                        stride(stride_)\n                {}\n                virtual boost::optional<StateType> Execute(SolverContext& ctx)override\n                {\n                        auto root   = gt->Root();\n                        \n                        double delta = 0.1;\n                        \n                        auto S = state0;\n\n\n                        SequenceConsumer sc;\n\n                        std::vector<StateType> ledger;\n                        enum{ MaxFails = 1 };\n                        for(size_t fails=0;fails!=MaxFails;){\n                                PS_LOG(trace) << \"delta => \" << delta;\n                                size_t counter = 0;\n                                size_t max_counter = 1000;\n                                for(;counter<max_counter;++counter){\n                                        auto S_counter = computation_kernel::CounterStrategy(gt, AG, S, delta);\n                                        computation_kernel::InplaceLinearCombination(S, S_counter, 1 - factor );\n                                        if( S_counter == S ){\n                                                break;\n                                        }\n                                        if( counter % stride == 0 ){\n                                                computation_kernel::InplaceClamp(S, ClampEpsilon);\n                                        }\n                                }\n                                if( counter != max_counter ){\n                                        if( ledger.size() > 4 ){\n                                                if( ledger[ledger.size()-1] == S &&\n                                                    ledger[ledger.size()-2] == S &&\n                                                    ledger[ledger.size()-3] == S ){\n                                                        return S;\n                                                }\n                                        }\n                                        ledger.push_back(S);\n                                        delta /= 2.0;\n                                        continue;\n                                }\n                                PS_LOG(trace) << \"delta=\" << delta << \" failed\";\n                                ++fails;\n                                delta /= 2.0;\n\n                        }\n                        return S;\n                        if( ledger.size() ){\n                                return ledger.back();\n                        }\n                        ctx.Message(\"Failed to converge :(889yh\");\n                        return {};\n                }\n        private:\n                std::shared_ptr<GameTree> gt;\n                GraphColouring<AggregateComputer> AG;\n                StateType state0;\n                double factor;\n                double epsilon;\n                size_t stride;\n                double ClampEpsilon{1e-6};\n        };\n\n        struct DeltaSequenceDecl : SolverDecl{\n                virtual void Accept(ArgumentVisitor& V)const override{\n                        double const default_factor  = 0.05;\n                        double const default_epsilon = 0.00001;\n                        size_t const default_stride  = 10;\n\n                        V.DeclArgument(\"factor\" , default_factor, \"used for taking linear product\");\n                        V.DeclArgument(\"epsilon\", default_epsilon, \"used for stoppage condition\");\n                        V.DeclArgument(\"stride\" , default_stride,\n                                       \"used for how many iterations before checking stoppage condition\");\n                }\n                virtual std::shared_ptr<Solver> Make( std::shared_ptr<GameTree> gt,\n                                                      GraphColouring<AggregateComputer> AG,\n                                                      StateType const& inital_state,\n                                                      bpt::ptree const& args)const override\n                {\n                        double factor  = args.get<double>(\"factor\");\n                        double epsilon = args.get<double>(\"epsilon\");\n                        size_t stride  = args.get<size_t>(\"stride\");\n\n                        return std::make_shared<DeltaSequence>(gt, AG, inital_state, factor, epsilon, stride);\n                }\n        };\n\n        static SolverRegister<DeltaSequenceDecl> DeltaSequenceReg(\"delta-seq\");\n\n} // end namespace sim\n} // end namespace ps\n", "meta": {"hexsha": "a7c594c42d8afaa8eb7dc91273ded57a5a9ff7cd", "size": 6654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/sim/delta_sequence.cpp", "max_stars_repo_name": "mastermind88/CandyPoker", "max_stars_repo_head_hexsha": "37b502ce6ea8733ce0b70476fcf32930961923a8", "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": "lib/sim/delta_sequence.cpp", "max_issues_repo_name": "mastermind88/CandyPoker", "max_issues_repo_head_hexsha": "37b502ce6ea8733ce0b70476fcf32930961923a8", "max_issues_repo_licenses": ["MIT"], "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/sim/delta_sequence.cpp", "max_forks_repo_name": "mastermind88/CandyPoker", "max_forks_repo_head_hexsha": "37b502ce6ea8733ce0b70476fcf32930961923a8", "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": 42.9290322581, "max_line_length": 167, "alphanum_fraction": 0.4809137361, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1802275122845415}}
{"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 ored/utilities/indexparser.cpp\n    \\brief\n    \\ingroup utilities\n*/\n\n#include <boost/algorithm/string.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/regex.hpp>\n#include <map>\n#include <ored/configuration/conventions.hpp>\n#include <ored/utilities/indexparser.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ql/errors.hpp>\n#include <ql/indexes/all.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/all.hpp>\n#include <qle/indexes/bmaindexwrapper.hpp>\n#include <qle/indexes/cacpi.hpp>\n#include <qle/indexes/commodityindex.hpp>\n#include <qle/indexes/dkcpi.hpp>\n#include <qle/indexes/equityindex.hpp>\n#include <qle/indexes/fxindex.hpp>\n#include <qle/indexes/genericiborindex.hpp>\n#include <qle/indexes/ibor/audbbsw.hpp>\n#include <qle/indexes/ibor/brlcdi.hpp>\n#include <qle/indexes/ibor/chfsaron.hpp>\n#include <qle/indexes/ibor/chftois.hpp>\n#include <qle/indexes/ibor/clpcamara.hpp>\n#include <qle/indexes/ibor/copibr.hpp>\n#include <qle/indexes/ibor/corra.hpp>\n#include <qle/indexes/ibor/czkpribor.hpp>\n#include <qle/indexes/ibor/demlibor.hpp>\n#include <qle/indexes/ibor/dkkcibor.hpp>\n#include <qle/indexes/ibor/dkkois.hpp>\n#include <qle/indexes/ibor/ester.hpp>\n#include <qle/indexes/ibor/hkdhibor.hpp>\n#include <qle/indexes/ibor/hufbubor.hpp>\n#include <qle/indexes/ibor/idridrfix.hpp>\n#include <qle/indexes/ibor/idrjibor.hpp>\n#include <qle/indexes/ibor/ilstelbor.hpp>\n#include <qle/indexes/ibor/inrmiborois.hpp>\n#include <qle/indexes/ibor/inrmifor.hpp>\n#include <qle/indexes/ibor/krwcd.hpp>\n#include <qle/indexes/ibor/krwkoribor.hpp>\n#include <qle/indexes/ibor/mxntiie.hpp>\n#include <qle/indexes/ibor/myrklibor.hpp>\n#include <qle/indexes/ibor/noknibor.hpp>\n#include <qle/indexes/ibor/nowa.hpp>\n#include <qle/indexes/ibor/nzdbkbm.hpp>\n#include <qle/indexes/ibor/phpphiref.hpp>\n#include <qle/indexes/ibor/plnpolonia.hpp>\n#include <qle/indexes/ibor/plnwibor.hpp>\n#include <qle/indexes/ibor/primeindex.hpp>\n#include <qle/indexes/ibor/rubmosprime.hpp>\n#include <qle/indexes/ibor/saibor.hpp>\n#include <qle/indexes/ibor/seksior.hpp>\n#include <qle/indexes/ibor/sekstibor.hpp>\n#include <qle/indexes/ibor/sgdsibor.hpp>\n#include <qle/indexes/ibor/sgdsor.hpp>\n#include <qle/indexes/ibor/skkbribor.hpp>\n#include <qle/indexes/ibor/thbbibor.hpp>\n#include <qle/indexes/ibor/tonar.hpp>\n#include <qle/indexes/ibor/twdtaibor.hpp>\n#include <qle/indexes/secpi.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace std;\nusing ore::data::Convention;\n\nnamespace ore {\nnamespace data {\n\n// Helper base class to build an IborIndex with a specific period and term structure given an instance of the same\n// IborIndex\nclass IborIndexParser {\npublic:\n    virtual ~IborIndexParser() {}\n    virtual boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const = 0;\n    virtual string family() const = 0;\n};\n\n// General case\ntemplate <class T> class IborIndexParserWithPeriod : public IborIndexParser {\npublic:\n    boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {\n        return boost::make_shared<T>(p, h);\n    }\n    string family() const override { return T(3 * Months).familyName(); }\n};\n\n// MXN TIIE\n// If tenor equates to 28 Days, i.e. tenor is 4W or 28D, ensure that the index is created\n// with a tenor of 4W under the hood. Things work better this way especially cap floor stripping.\n// We do the same with 91D -> 3M (a la KRW CD below)\ntemplate <> class IborIndexParserWithPeriod<MXNTiie> : public IborIndexParser {\npublic:\n    boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {\n        if (p.units() == Days && p.length() == 28) {\n            return boost::make_shared<MXNTiie>(4 * Weeks, h);\n        } else if (p.units() == Days && p.length() == 91) {\n            return boost::make_shared<MXNTiie>(3 * Months, h);\n        } else {\n            return boost::make_shared<MXNTiie>(p, h);\n        }\n    }\n\n    string family() const override { return MXNTiie(4 * Weeks).familyName(); }\n};\n\n// KRW CD\n// If tenor equates to 91 Days, ensure that the index is created with a tenor of 3M under the hood.\ntemplate <> class IborIndexParserWithPeriod<KRWCd> : public IborIndexParser {\npublic:\n    boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {\n        if (p.units() == Days && p.length() == 91) {\n            return boost::make_shared<KRWCd>(3 * Months, h);\n        } else {\n            return boost::make_shared<KRWCd>(p, h);\n        }\n    }\n\n    string family() const override { return KRWCd(3 * Months).familyName(); }\n};\n\n// Helper function to check that index name to index object is a one-to-one mapping\nvoid checkOneToOne(const map<string, boost::shared_ptr<OvernightIndex>>& onIndices,\n                   const map<string, boost::shared_ptr<IborIndexParser>>& iborIndices) {\n\n    // Should not attempt to add the same family name to the set if the provided mappings are one to one\n    set<string> familyNames;\n\n    for (const auto& kv : onIndices) {\n        auto p = familyNames.insert(kv.second->familyName());\n        QL_REQUIRE(p.second, \"Duplicate mapping for overnight index family \" << *p.first << \" not allowed\");\n    }\n\n    for (const auto& kv : iborIndices) {\n        auto p = familyNames.insert(kv.second->family());\n        QL_REQUIRE(p.second, \"Duplicate mapping for ibor index family \" << *p.first << \" not allowed\");\n    }\n}\n\nboost::shared_ptr<FxIndex> parseFxIndex(const string& s, const Handle<Quote>& fxSpot,\n                                        const Handle<YieldTermStructure>& sourceYts,\n                                        const Handle<YieldTermStructure>& targetYts) {\n    std::vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n    QL_REQUIRE(tokens.size() == 4, \"four tokens required in \" << s << \": FX-TAG-CCY1-CCY2\");\n    QL_REQUIRE(tokens[0] == \"FX\", \"expected first token to be FX\");\n    return boost::make_shared<FxIndex>(tokens[0] + \"/\" + tokens[1], 0, parseCurrency(tokens[2]),\n                                       parseCurrency(tokens[3]), NullCalendar(), fxSpot, sourceYts, targetYts);\n}\n\nboost::shared_ptr<EquityIndex> parseEquityIndex(const string& s) {\n    std::vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n    QL_REQUIRE(tokens.size() == 2, \"two tokens required in \" << s << \": EQ-NAME\");\n    QL_REQUIRE(tokens[0] == \"EQ\", \"expected first token to be EQ\");\n    return boost::make_shared<EquityIndex>(tokens[1], NullCalendar(), Currency());\n}\n\nbool tryParseIborIndex(const string& s, boost::shared_ptr<IborIndex>& index, const boost::shared_ptr<Convention>& c) {\n    try {\n        index = parseIborIndex(s, Handle<YieldTermStructure>(), c);\n    } catch (...) {\n        return false;\n    }\n    return true;\n}\n\nboost::shared_ptr<IborIndex> parseIborIndex(const string& s, const Handle<YieldTermStructure>& h,\n                                            const boost::shared_ptr<Convention>& c) {\n    string dummy;\n    return parseIborIndex(s, dummy, h, c);\n}\n\nboost::shared_ptr<IborIndex> parseIborIndex(const string& s, string& tenor, const Handle<YieldTermStructure>& h,\n                                            const boost::shared_ptr<Convention>& c) {\n\n    // Check the index string is of the required form before doing anything\n    vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n    QL_REQUIRE(tokens.size() == 2 || tokens.size() == 3,\n               \"Two or three tokens required in \" << s << \": CCY-INDEX or CCY-INDEX-TERM\");\n\n    // Variables used below\n    string indexStem = tokens[0] + \"-\" + tokens[1];\n    if (tokens.size() == 3) {\n        tenor = tokens[2];\n    } else {\n        tenor = \"\";\n    }\n\n    // if we have a convention given, set up the index using this convention, this overrides the parsing from\n    // hardcoded strings below if there is an overlap\n    if (c) {\n        QL_REQUIRE(c->id() == s, \"ibor index convention id ('\"\n                                     << c->id() << \"') not matching ibor index string to parse ('\" << s << \"'\");\n        Currency ccy = parseCurrency(tokens[0]);\n        if (auto conv = boost::dynamic_pointer_cast<OvernightIndexConvention>(c)) {\n            QL_REQUIRE(tenor.empty(), \"no tenor allowed for convention based overnight index ('\" << s << \"')\");\n            return boost::make_shared<OvernightIndex>(tokens[1], conv->settlementDays(), ccy,\n                                                      parseCalendar(conv->fixingCalendar()),\n                                                      parseDayCounter(conv->dayCounter()), h);\n\n        } else if (auto conv = boost::dynamic_pointer_cast<IborIndexConvention>(c)) {\n            QL_REQUIRE(!tenor.empty(), \"no tenor given for convention based Ibor index ('\" << s << \"'\");\n            return boost::make_shared<IborIndex>(tokens[1], parsePeriod(tenor), conv->settlementDays(), ccy,\n                                                 parseCalendar(conv->fixingCalendar()),\n                                                 parseBusinessDayConvention(conv->businessDayConvention()),\n                                                 conv->endOfMonth(), parseDayCounter(conv->dayCounter()), h);\n        } else {\n            QL_FAIL(\"invalid convention passed to parseIborIndex(): expected OvernightIndexConvention or \"\n                    \"IborIndexConvention\");\n        }\n    }\n\n    // if we do not have a convention, look up the index in the hardcoded maps below\n\n    // Map from our _unique internal name_ to an overnight index\n    static map<string, boost::shared_ptr<OvernightIndex>> onIndices = {\n        {\"EUR-EONIA\", boost::make_shared<Eonia>()},        {\"EUR-ESTER\", boost::make_shared<Ester>()},\n        {\"GBP-SONIA\", boost::make_shared<Sonia>()},        {\"JPY-TONAR\", boost::make_shared<Tonar>()},\n        {\"CHF-TOIS\", boost::make_shared<CHFTois>()},       {\"CHF-SARON\", boost::make_shared<CHFSaron>()},\n        {\"USD-FedFunds\", boost::make_shared<FedFunds>()},  {\"USD-SOFR\", boost::make_shared<Sofr>()},\n        {\"USD-Prime\", boost::make_shared<PrimeIndex>()},   {\"AUD-AONIA\", boost::make_shared<Aonia>()},\n        {\"CAD-CORRA\", boost::make_shared<CORRA>()},        {\"DKK-DKKOIS\", boost::make_shared<DKKOis>()},\n        {\"SEK-SIOR\", boost::make_shared<SEKSior>()},       {\"COP-IBR\", boost::make_shared<COPIbr>()},\n        {\"BRL-CDI\", boost::make_shared<BRLCdi>()},         {\"NOK-NOWA\", boost::make_shared<Nowa>()},\n        {\"CLP-CAMARA\", boost::make_shared<CLPCamara>()},   {\"NZD-OCR\", boost::make_shared<Nzocr>()},\n        {\"PLN-POLONIA\", boost::make_shared<PLNPolonia>()}, {\"INR-MIBOROIS\", boost::make_shared<INRMiborOis>()}};\n\n    // Map from our _unique internal name_ to an ibor index (the period does not matter here)\n    static map<string, boost::shared_ptr<IborIndexParser>> iborIndices = {\n        {\"AUD-BBSW\", boost::make_shared<IborIndexParserWithPeriod<AUDbbsw>>()},\n        {\"AUD-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<AUDLibor>>()},\n        {\"EUR-EURIBOR\", boost::make_shared<IborIndexParserWithPeriod<Euribor>>()},\n        {\"EUR-EURIBOR365\", boost::make_shared<IborIndexParserWithPeriod<Euribor365>>()},\n        {\"CAD-CDOR\", boost::make_shared<IborIndexParserWithPeriod<Cdor>>()},\n        {\"CNY-SHIBOR\", boost::make_shared<IborIndexParserWithPeriod<Shibor>>()},\n        {\"CZK-PRIBOR\", boost::make_shared<IborIndexParserWithPeriod<CZKPribor>>()},\n        {\"EUR-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<EURLibor>>()},\n        {\"USD-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<USDLibor>>()},\n        {\"GBP-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<GBPLibor>>()},\n        {\"JPY-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<JPYLibor>>()},\n        {\"JPY-TIBOR\", boost::make_shared<IborIndexParserWithPeriod<Tibor>>()},\n        {\"CAD-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<CADLibor>>()},\n        {\"CHF-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<CHFLibor>>()},\n        {\"SEK-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<SEKLibor>>()},\n        {\"SEK-STIBOR\", boost::make_shared<IborIndexParserWithPeriod<SEKStibor>>()},\n        {\"NOK-NIBOR\", boost::make_shared<IborIndexParserWithPeriod<NOKNibor>>()},\n        {\"HKD-HIBOR\", boost::make_shared<IborIndexParserWithPeriod<HKDHibor>>()},\n        {\"SAR-SAIBOR\", boost::make_shared<IborIndexParserWithPeriod<SAibor>>()},\n        {\"SGD-SIBOR\", boost::make_shared<IborIndexParserWithPeriod<SGDSibor>>()},\n        {\"SGD-SOR\", boost::make_shared<IborIndexParserWithPeriod<SGDSor>>()},\n        {\"DKK-CIBOR\", boost::make_shared<IborIndexParserWithPeriod<DKKCibor>>()},\n        {\"DKK-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<DKKLibor>>()},\n        {\"HUF-BUBOR\", boost::make_shared<IborIndexParserWithPeriod<HUFBubor>>()},\n        {\"IDR-IDRFIX\", boost::make_shared<IborIndexParserWithPeriod<IDRIdrfix>>()},\n        {\"IDR-JIBOR\", boost::make_shared<IborIndexParserWithPeriod<IDRJibor>>()},\n        {\"ILS-TELBOR\", boost::make_shared<IborIndexParserWithPeriod<ILSTelbor>>()},\n        {\"INR-MIFOR\", boost::make_shared<IborIndexParserWithPeriod<INRMifor>>()},\n        {\"MXN-TIIE\", boost::make_shared<IborIndexParserWithPeriod<MXNTiie>>()},\n        {\"PLN-WIBOR\", boost::make_shared<IborIndexParserWithPeriod<PLNWibor>>()},\n        {\"SKK-BRIBOR\", boost::make_shared<IborIndexParserWithPeriod<SKKBribor>>()},\n        {\"NZD-BKBM\", boost::make_shared<IborIndexParserWithPeriod<NZDBKBM>>()},\n        {\"TRY-TRLIBOR\", boost::make_shared<IborIndexParserWithPeriod<TRLibor>>()},\n        {\"TWD-TAIBOR\", boost::make_shared<IborIndexParserWithPeriod<TWDTaibor>>()},\n        {\"MYR-KLIBOR\", boost::make_shared<IborIndexParserWithPeriod<MYRKlibor>>()},\n        {\"KRW-CD\", boost::make_shared<IborIndexParserWithPeriod<KRWCd>>()},\n        {\"KRW-KORIBOR\", boost::make_shared<IborIndexParserWithPeriod<KRWKoribor>>()},\n        {\"ZAR-JIBAR\", boost::make_shared<IborIndexParserWithPeriod<Jibar>>()},\n        {\"RUB-MOSPRIME\", boost::make_shared<IborIndexParserWithPeriod<RUBMosprime>>()},\n        {\"THB-BIBOR\", boost::make_shared<IborIndexParserWithPeriod<THBBibor>>()},\n        {\"PHP-PHIREF\", boost::make_shared<IborIndexParserWithPeriod<PHPPhiref>>()},\n        {\"RON-ROBOR\", boost::make_shared<IborIndexParserWithPeriod<Robor>>()},\n        {\"DEM-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<DEMLibor>>()}};\n\n    // Check (once) that we have a one-to-one mapping\n    static bool checked = false;\n    if (!checked) {\n        checkOneToOne(onIndices, iborIndices);\n        checked = true;\n    }\n\n    // Simple single case for USD-SIFMA (i.e. BMA)\n    if (indexStem == \"USD-SIFMA\") {\n        QL_REQUIRE(tenor.empty(), \"A tenor is not allowed with USD-SIFMA as it is implied\");\n        return boost::make_shared<BMAIndexWrapper>(boost::make_shared<BMAIndex>(h));\n    }\n\n    // Overnight indices\n    auto onIt = onIndices.find(indexStem);\n    if (onIt != onIndices.end()) {\n        QL_REQUIRE(tenor.empty(),\n                   \"A tenor is not allowed with the overnight index \" << indexStem << \" as it is implied\");\n        return onIt->second->clone(h);\n    }\n\n    // Ibor indices with a tenor\n    auto it = iborIndices.find(indexStem);\n    if (it != iborIndices.end()) {\n        Period p = parsePeriod(tenor);\n        return it->second->build(p, h);\n    }\n\n    // GENERIC indices\n    if (tokens[1] == \"GENERIC\") {\n        Period p = parsePeriod(tenor);\n        auto ccy = parseCurrency(tokens[0]);\n        return boost::make_shared<GenericIborIndex>(p, ccy, h);\n    }\n\n    QL_FAIL(\"parseIborIndex \\\"\" << s << \"\\\" not recognized\");\n}\n\nbool isGenericIndex(const string& indexName) { return indexName.find(\"-GENERIC-\") != string::npos; }\n\nbool isInflationIndex(const string& indexName) {\n    try {\n        // Currently, only way to have an inflation index is to have a ZeroInflationIndex\n        parseZeroInflationIndex(indexName);\n    } catch (...) {\n        return false;\n    }\n    return true;\n}\n\n// Swap Index Parser base\nclass SwapIndexParser {\npublic:\n    virtual ~SwapIndexParser() {}\n    virtual boost::shared_ptr<SwapIndex> build(Period p, const Handle<YieldTermStructure>& f,\n                                               const Handle<YieldTermStructure>& d) const = 0;\n};\n\n// We build with both a forwarding and discounting curve\ntemplate <class T> class SwapIndexParserDualCurve : public SwapIndexParser {\npublic:\n    boost::shared_ptr<SwapIndex> build(Period p, const Handle<YieldTermStructure>& f,\n                                       const Handle<YieldTermStructure>& d) const override {\n        return boost::make_shared<T>(p, f, d);\n    }\n};\n\nboost::shared_ptr<SwapIndex> parseSwapIndex(const string& s, const Handle<YieldTermStructure>& f,\n                                            const Handle<YieldTermStructure>& d,\n                                            boost::shared_ptr<Convention> convention) {\n\n    boost::shared_ptr<data::IRSwapConvention> irSwapConvention;\n    if (convention) {\n        irSwapConvention = boost::dynamic_pointer_cast<IRSwapConvention>(convention);\n        QL_REQUIRE(irSwapConvention, \"expected swap convention in parseSwapIndex() for '\" << convention->id() << \"'\");\n    }\n\n    std::vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n\n    QL_REQUIRE(tokens.size() == 3 || tokens.size() == 4,\n               \"three or four tokens required in \" << s << \": CCY-CMS-TENOR or CCY-CMS-TAG-TENOR\");\n    QL_REQUIRE(tokens[0].size() == 3, \"invalid currency code in \" << s);\n    QL_REQUIRE(tokens[1] == \"CMS\", \"expected CMS as middle token in \" << s);\n\n    Period p = parsePeriod(tokens.back());\n\n    // if no tag is given use LiborSwapIsdaFix as an (arbitrary) standard name\n    string familyName = tokens.size() == 4 ? tokens[0] + \"-CMS-\" + tokens[2] : tokens[0] + \"LiborSwapIsdaFix\";\n    Currency ccy = parseCurrency(tokens[0]);\n\n    boost::shared_ptr<IborIndex> index =\n        f.empty() || !convention ? boost::shared_ptr<IborIndex>() : irSwapConvention->index()->clone(f);\n    QuantLib::Natural settlementDays = index ? index->fixingDays() : 0;\n    QuantLib::Calendar calender = convention ? irSwapConvention->fixedCalendar() : NullCalendar();\n    Period fixedLegTenor = convention ? Period(irSwapConvention->fixedFrequency()) : Period(1, Months);\n    BusinessDayConvention fixedLegConvention = convention ? irSwapConvention->fixedConvention() : ModifiedFollowing;\n    DayCounter fixedLegDayCounter = convention ? irSwapConvention->fixedDayCounter() : ActualActual();\n\n    if (d.empty())\n        return boost::make_shared<SwapIndex>(familyName, p, settlementDays, ccy, calender, fixedLegTenor,\n                                             fixedLegConvention, fixedLegDayCounter, index);\n    else\n        return boost::make_shared<SwapIndex>(familyName, p, settlementDays, ccy, calender, fixedLegTenor,\n                                             fixedLegConvention, fixedLegDayCounter, index, d);\n}\n\n// Zero Inflation Index Parser\nclass ZeroInflationIndexParserBase {\npublic:\n    virtual ~ZeroInflationIndexParserBase() {}\n    virtual boost::shared_ptr<ZeroInflationIndex> build(bool isInterpolated,\n                                                        const Handle<ZeroInflationTermStructure>& h) const = 0;\n};\n\ntemplate <class T> class ZeroInflationIndexParser : public ZeroInflationIndexParserBase {\npublic:\n    boost::shared_ptr<ZeroInflationIndex> build(bool isInterpolated,\n                                                const Handle<ZeroInflationTermStructure>& h) const override {\n        return boost::make_shared<T>(isInterpolated, h);\n    }\n};\n\nboost::shared_ptr<ZeroInflationIndex> parseZeroInflationIndex(const string& s, bool isInterpolated,\n                                                              const Handle<ZeroInflationTermStructure>& h) {\n\n    static map<string, boost::shared_ptr<ZeroInflationIndexParserBase>> m = {\n        {\"EUHICP\", boost::make_shared<ZeroInflationIndexParser<EUHICP>>()},\n        {\"EU HICP\", boost::make_shared<ZeroInflationIndexParser<EUHICP>>()},\n        {\"EUHICPXT\", boost::make_shared<ZeroInflationIndexParser<EUHICPXT>>()},\n        {\"EU HICPXT\", boost::make_shared<ZeroInflationIndexParser<EUHICPXT>>()},\n        {\"FRHICP\", boost::make_shared<ZeroInflationIndexParser<FRHICP>>()},\n        {\"FR HICP\", boost::make_shared<ZeroInflationIndexParser<FRHICP>>()},\n        {\"UKRPI\", boost::make_shared<ZeroInflationIndexParser<UKRPI>>()},\n        {\"UK RPI\", boost::make_shared<ZeroInflationIndexParser<UKRPI>>()},\n        {\"USCPI\", boost::make_shared<ZeroInflationIndexParser<USCPI>>()},\n        {\"US CPI\", boost::make_shared<ZeroInflationIndexParser<USCPI>>()},\n        {\"ZACPI\", boost::make_shared<ZeroInflationIndexParser<ZACPI>>()},\n        {\"ZA CPI\", boost::make_shared<ZeroInflationIndexParser<ZACPI>>()},\n        {\"SECPI\", boost::make_shared<ZeroInflationIndexParser<SECPI>>()},\n        {\"DKCPI\", boost::make_shared<ZeroInflationIndexParser<DKCPI>>()},\n        {\"CACPI\", boost::make_shared<ZeroInflationIndexParser<CACPI>>()}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second->build(isInterpolated, h);\n    } else {\n        QL_FAIL(\"parseZeroInflationIndex: \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nboost::shared_ptr<BondIndex> parseBondIndex(const string& s) {\n    std::vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n    QL_REQUIRE(tokens.size() == 2, \"two tokens required in \" << s << \": BOND-SECURITY\");\n    QL_REQUIRE(tokens[0] == \"BOND\", \"expected first token to be BOND\");\n    return boost::make_shared<BondIndex>(tokens[1]);\n}\n\nboost::shared_ptr<QuantExt::CommodityIndex> parseCommodityIndex(const string& name, const Calendar& cal,\n                                                                const Handle<PriceTermStructure>& ts) {\n\n    // Make sure the prefix is correct\n    string prefix = name.substr(0, 5);\n    QL_REQUIRE(prefix == \"COMM-\", \"A commodity index string must start with 'COMM-' but got \" << prefix);\n\n    // Now take the remainder of the string\n    // for spot indices, this should just be the commodity name (possibly containing hyphens)\n    // for future indices, this is of the form NAME-YYYY-MM or NAME-YYYY-MM-DD where NAME is the commodity name\n    // (possibly containing hyphens) and YYYY-MM(-DD) is the expiry date of the futures contract\n    Date expiry;\n    string nameWoPrefix = name.substr(5);\n    string commName = nameWoPrefix;\n\n    // Check for form NAME-YYYY-MM-DD\n    if (nameWoPrefix.size() > 10) {\n        string test = nameWoPrefix.substr(nameWoPrefix.size() - 10);\n        if (boost::regex_match(test, boost::regex(\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"))) {\n            expiry = parseDate(test);\n            commName = nameWoPrefix.substr(0, nameWoPrefix.size() - test.size() - 1);\n        }\n    }\n\n    // Check for form NAME-YYYY-MM if NAME-YYYY-MM-DD failed\n    if (expiry == Date() && nameWoPrefix.size() > 7) {\n        string test = nameWoPrefix.substr(nameWoPrefix.size() - 7);\n        if (boost::regex_match(test, boost::regex(\"\\\\d{4}-\\\\d{2}\"))) {\n            expiry = parseDate(test + \"-01\");\n            commName = nameWoPrefix.substr(0, nameWoPrefix.size() - test.size() - 1);\n        }\n    }\n\n    // Create and return the required future index\n    if (expiry != Date()) {\n        return boost::make_shared<CommodityFuturesIndex>(commName, expiry, cal, ts);\n    } else {\n        return boost::make_shared<CommoditySpotIndex>(commName, cal, ts);\n    }\n}\n\nboost::shared_ptr<Index> parseIndex(const string& s, const data::Conventions& conventions) {\n    boost::shared_ptr<QuantLib::Index> ret_idx;\n    // if we have an ibor index convention we parse s using this (and throw if we don't succeed)\n    if (conventions.has(s, Convention::Type::IborIndex) || conventions.has(s, Convention::Type::OvernightIndex)) {\n        ret_idx = parseIborIndex(s, Handle<YieldTermStructure>(), conventions.get(s));\n    } else {\n        // otherwise we try to parse the ibor index without conventions\n        try {\n            ret_idx = parseIborIndex(s, Handle<YieldTermStructure>(), nullptr);\n        } catch (...) {\n        }\n    }\n    if (!ret_idx) {\n        // if we have a swap index convention we parse s using this (and throw if we don't succeed)\n        if (conventions.has(s, Convention::Type::SwapIndex)) {\n            auto c = boost::dynamic_pointer_cast<SwapIndexConvention>(conventions.get(s));\n            QL_REQUIRE(conventions.has(c->conventions(), Convention::Type::Swap),\n                       \"do not have swap conventions for '\" << c->conventions()\n                                                            << \"', required from swap index convention '\" << s << \"'\");\n            ret_idx = parseSwapIndex(s, Handle<YieldTermStructure>(), Handle<YieldTermStructure>(),\n                                     conventions.get(c->conventions()));\n        } else {\n            // otherwise try to parse a swap index without conventions\n            try {\n                ret_idx = parseSwapIndex(s, Handle<YieldTermStructure>(), Handle<YieldTermStructure>(), nullptr);\n            } catch (...) {\n            }\n        }\n    }\n    if (!ret_idx) {\n        try {\n            ret_idx = parseZeroInflationIndex(s);\n        } catch (...) {\n        }\n    }\n    if (!ret_idx) {\n        try {\n            ret_idx = parseFxIndex(s);\n        } catch (...) {\n        }\n    }\n    if (!ret_idx) {\n        try {\n            ret_idx = parseEquityIndex(s);\n        } catch (...) {\n        }\n    }\n    if (!ret_idx) {\n        try {\n            ret_idx = parseBondIndex(s);\n        } catch (...) {\n        }\n    }\n    if (!ret_idx) {\n        try {\n            ret_idx = parseCommodityIndex(s);\n        } catch (...) {\n        }\n    }\n    QL_REQUIRE(ret_idx, \"parseIndex \\\"\" << s << \"\\\" not recognized\");\n    return ret_idx;\n}\n\nbool isOvernightIndex(const string& indexName, const Conventions& conventions) {\n\n    boost::shared_ptr<IborIndex> index;\n    if (tryParseIborIndex(indexName, index,\n                          conventions.has(indexName, Convention::Type::OvernightIndex) ? conventions.get(indexName)\n                                                                                       : nullptr)) {\n        auto onIndex = boost::dynamic_pointer_cast<OvernightIndex>(index);\n        if (onIndex)\n            return true;\n    }\n\n    return false;\n}\n\nstring internalIndexName(const string& indexName) {\n\n    // Check that the indexName string is of the required form\n    vector<string> tokens;\n    split(tokens, indexName, boost::is_any_of(\"-\"));\n    QL_REQUIRE(tokens.size() == 2 || tokens.size() == 3,\n               \"Two or three tokens required in \" << indexName << \": CCY-INDEX or CCY-INDEX-TERM\");\n\n    // Static map of allowable alternative external names to our unique internal name\n    static map<string, string> m = {{\"DKK-TNR\", \"DKK-DKKOIS\"}, {\"EUR-EURIB\", \"EUR-EURIBOR\"}, {\"CAD-BA\", \"CAD-CDOR\"}};\n\n    // Is start of indexName covered by the map? If so, update it.\n    string tmpName = tokens[0] + \"-\" + tokens[1];\n    if (m.count(tmpName) == 1) {\n        tmpName = m.at(tmpName);\n    }\n\n    // If there were only two tokens, return the possibly updated two tokens.\n    if (tokens.size() == 2) {\n        return tmpName;\n    }\n\n    // Check if we have an overnight index\n    // This covers cases like USD-FedFunds-1D and returns USD-FedFunds\n    // (no need to check convention based overnight indices, they are always of the form CCY-INDEX)\n    if (isOvernightIndex(tmpName)) {\n        Period p = parsePeriod(tokens[2]);\n        QL_REQUIRE(p == 1 * Days,\n                   \"The period \" << tokens[2] << \" is not compatible with the overnight index \" << tmpName);\n        return tmpName;\n    }\n\n    // Allow USD-SIFMA-1W or USD-SIFMA-7D externally. USD-SIFMA is used internally.\n    if (tmpName == \"USD-SIFMA\" && (tokens[2] == \"1W\" || tokens[2] == \"7D\")) {\n        return tmpName;\n    }\n\n    return tmpName + \"-\" + tokens[2];\n}\n\nbool isFxIndex(const std::string& indexName) {\n    std::vector<string> tokens;\n    split(tokens, indexName, boost::is_any_of(\"-\"));\n    return tokens.size() == 4 && tokens[0] == \"FX\";\n}\n\nstd::string inverseFxIndex(const std::string& indexName) {\n    std::vector<string> tokens;\n    split(tokens, indexName, boost::is_any_of(\"-\"));\n    QL_REQUIRE(tokens.size() == 4 && tokens[0] == \"FX\", \"no fx index given (\" << indexName << \")\");\n    return \"FX-\" + tokens[1] + \"-\" + tokens[3] + \"-\" + tokens[2];\n}\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "ef24a318555e64dcd871d622794ad042922da343", "size": 29219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/utilities/indexparser.cpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "OREData/ored/utilities/indexparser.cpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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": "OREData/ored/utilities/indexparser.cpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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": 46.3058637084, "max_line_length": 119, "alphanum_fraction": 0.6410212533, "num_tokens": 7691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18022750008030256}}
{"text": "#ifndef BOOST_SAFE_FLOAT_POLICY_CHECK_ADDITION_INEXACT_HPP\n#define BOOST_SAFE_FLOAT_POLICY_CHECK_ADDITION_INEXACT_HPP\n#include <boost/safe_float/policy/check_base_policy.hpp>\n\n#ifdef FENV_AVAILABLE\n#pragma STDC FENV_ACCESS ON\n#include <fenv.h>\n#endif\n\nnamespace boost {\nnamespace safe_float{\nnamespace policy{\n\ntemplate<class FP>\nclass check_addition_inexact : public check_policy<FP> {\n#ifndef FENV_AVAILABLE\n    FP prev_l=0;\n    FP prev_r=0;\n#endif\npublic:\n    bool pre_addition_check(const FP& lhs, const FP& rhs){\n#ifndef FENV_AVAILABLE\n        prev_l = lhs;\n        prev_r = rhs;\n        return true;\n#else\n        return ! std::feclearexcept(FE_INEXACT);\n#endif\n    }\n\n    bool post_addition_check(const FP& rhs){\n#ifndef FENV_AVAILABLE\n        return ((rhs - prev_r) == prev_l) && ((rhs - prev_l) == prev_r); //this check is not completely safe, need to do some math to get a proper implementation...\n#else\n        return ! std::fetestexcept(FE_INEXACT);\n#endif\n    }\n\n    std::string addition_failure_message(){\n        return std::string(\"Non reversible addition applied\");\n    }\n\n};\n\n}\n}\n}\n#endif // BOOST_SAFE_FLOAT_POLICY_CHECK_ADDITION_INEXACT_HPP\n", "meta": {"hexsha": "a327c75f612f39ab9ef5cb5d2a4a069dc6043d07", "size": 1161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/safe_float/policy/check_addition_inexact.hpp", "max_stars_repo_name": "aTom3333/safefloat", "max_stars_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-08T01:24:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T01:24:16.000Z", "max_issues_repo_path": "include/boost/safe_float/policy/check_addition_inexact.hpp", "max_issues_repo_name": "aTom3333/safefloat", "max_issues_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "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/safe_float/policy/check_addition_inexact.hpp", "max_forks_repo_name": "aTom3333/safefloat", "max_forks_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T11:31:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-12T21:55:25.000Z", "avg_line_length": 23.693877551, "max_line_length": 164, "alphanum_fraction": 0.7226528854, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.18022750008030253}}
{"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_BOOLEAN_FUNCTIONS_SIMD_COMMON_IF_ZERO_ELSE_ONE_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_BOOLEAN_FUNCTIONS_SIMD_COMMON_IF_ZERO_ELSE_ONE_HPP_INCLUDED\n\n#include <boost/simd/toolbox/boolean/functions/if_zero_else_one.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/constants/zero.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::if_zero_else_one_\n                                      , tag::cpu_\n                                      , (A0)(X)\n                                      , ((simd_<fundamental_<A0>,X>))\n                                )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return if_else(a0, Zero<A0>(), One<A0>());\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::if_zero_else_one_\n                                      , tag::cpu_\n                                      , (A0)(X)\n                                      , ((simd_<logical_<A0>,X>))\n                                )\n  {\n    typedef typename A0::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return if_else(a0, Zero<A0>(), One<A0>());\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "333c5a2a2692334503c502d4c697dab5bd44abd3", "size": 1790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/boolean/include/boost/simd/toolbox/boolean/functions/simd/common/if_zero_else_one.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/boolean/include/boost/simd/toolbox/boolean/functions/simd/common/if_zero_else_one.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/boolean/include/boost/simd/toolbox/boolean/functions/simd/common/if_zero_else_one.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": 38.085106383, "max_line_length": 86, "alphanum_fraction": 0.5206703911, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18022749312139755}}
{"text": "/*  \n*   Copyright 2017-2018 Simon Raschke\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#pragma once\n\n#include \"definitions.hpp\"\n#include \"enhance/math_utility.hpp\"\n#include <cmath>\n#include <tbb/tbb.h>\n#if __has_include(<Eigen/Core>)\n#include <Eigen/Core>\n#elif __has_include(<eigen3/Eigen/Core>)\n#include <eigen3/Eigen/Core>\n#endif\n#if __has_include(<Eigen/Core>)\n#include <Eigen/Geometry>\n#elif __has_include(<eigen3/Eigen/Core>)\n#include <eigen3/Eigen/Geometry>\n#endif\n\n\n\nstruct Geometry\n{\n    typedef PARTICLERANGE::value_type::element_type::cartesian cartesian;\n\n    virtual ~Geometry() = default;\n    virtual void generate() = 0;\n    virtual void scale(const cartesian&) = 0;\n    virtual void shift(const cartesian&) = 0;\n\n    tbb::concurrent_vector<cartesian> points {};\n\nprotected:\n    Geometry() = default;\n};", "meta": {"hexsha": "58eab6aeec0912e07c855dbe76291ca7b64d6677", "size": 1342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometries/geometry.hpp", "max_stars_repo_name": "simonraschke/vesicle", "max_stars_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T17:24:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T17:24:52.000Z", "max_issues_repo_path": "src/geometries/geometry.hpp", "max_issues_repo_name": "simonraschke/vesicle", "max_issues_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "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/geometries/geometry.hpp", "max_forks_repo_name": "simonraschke/vesicle", "max_forks_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "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.387755102, "max_line_length": 76, "alphanum_fraction": 0.7257824143, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.18019534574676407}}
{"text": "#include \"config.h\"\n#include <algorithm>\n#include <cassert>\n#include <list>\n#include <set>\n#include <iostream>\n#include <fstream>\n#include <memory>\n#include <cmath>\n#include <array>\n#include <thread>\n#include <boost/utility.hpp>\n#include <boost/format.hpp>\n\n#ifdef USE_CAFFE\n#include <caffe/proto/caffe.pb.h>\n#include <caffe/util/db.hpp>\n#include <caffe/util/io.hpp>\n#include <caffe/blob.hpp>\n\nusing namespace caffe;\n#endif\n#include \"Im2Col.h\"\n#ifdef __APPLE__\n#include <Accelerate/Accelerate.h>\n#endif\n#ifdef USE_MKL\n#include <mkl.h>\n#endif\n#ifdef USE_OPENBLAS\n#include <cblas.h>\n#ifdef USE_ONEDNN\n#include <dnnl.h>\n#endif\n#endif\n#ifdef USE_OPENCL\n#include \"OpenCL.h\"\n#include \"UCTNode.h\"\n#endif\n\n#include \"SGFTree.h\"\n#include \"SGFParser.h\"\n#include \"Utils.h\"\n#include \"FastBoard.h\"\n#include \"Random.h\"\n#include \"Network.h\"\n#include \"GTP.h\"\n#include \"Utils.h\"\n\nusing namespace Utils;\n\nNetwork* Network::s_Net = nullptr;\n#ifdef USE_CAFFE\nstd::unique_ptr<caffe::Net> Network::s_net;\n#endif\n\n#ifdef USE_OPENCL\nextern const std::array<float, 102400> conv1_w;\nextern const std::array<float, 128> conv1_b;\nextern const std::array<float, 221184> conv2_w;\nextern const std::array<float, 192> conv2_b;\nextern const std::array<float, 331776> conv3_w;\nextern const std::array<float, 192> conv3_b;\nextern const std::array<float, 331776> conv4_w;\nextern const std::array<float, 192> conv4_b;\nextern const std::array<float, 331776> conv5_w;\nextern const std::array<float, 192> conv5_b;\nextern const std::array<float, 331776> conv6_w;\nextern const std::array<float, 192> conv6_b;\nextern const std::array<float, 331776> conv7_w;\nextern const std::array<float, 192> conv7_b;\nextern const std::array<float, 331776> conv8_w;\nextern const std::array<float, 192> conv8_b;\nextern const std::array<float, 331776> conv9_w;\nextern const std::array<float, 192> conv9_b;\nextern const std::array<float, 331776> conv10_w;\nextern const std::array<float, 192> conv10_b;\nextern const std::array<float, 331776> conv11_w;\nextern const std::array<float, 192> conv11_b;\nextern const std::array<float, 331776> conv12_w;\nextern const std::array<float, 192> conv12_b;\nextern const std::array<float, 1728> conv13_w;\nextern const std::array<float, 1> conv13_b;\n#else\nextern const std::array<float, 76800> conv1_w;\nextern const std::array<float, 96> conv1_b;\nextern const std::array<float, 110592> conv2_w;\nextern const std::array<float, 128> conv2_b;\nextern const std::array<float, 147456> conv3_w;\nextern const std::array<float, 128> conv3_b;\nextern const std::array<float, 147456> conv4_w;\nextern const std::array<float, 128> conv4_b;\nextern const std::array<float, 147456> conv5_w;\nextern const std::array<float, 128> conv5_b;\nextern const std::array<float, 147456> conv6_w;\nextern const std::array<float, 128> conv6_b;\nextern const std::array<float, 147456> conv7_w;\nextern const std::array<float, 128> conv7_b;\nextern const std::array<float, 147456> conv8_w;\nextern const std::array<float, 128> conv8_b;\nextern const std::array<float, 147456> conv9_w;\nextern const std::array<float, 128> conv9_b;\nextern const std::array<float, 147456> conv10_w;\nextern const std::array<float, 128> conv10_b;\nextern const std::array<float, 147456> conv11_w;\nextern const std::array<float, 128> conv11_b;\nextern const std::array<float, 147456> conv12_w;\nextern const std::array<float, 128> conv12_b;\nextern const std::array<float, 1152> conv13_w;\nextern const std::array<float, 1> conv13_b;\n#endif\n\nextern const std::array<float, 51200> val_conv1_w;\nextern const std::array<float, 64> val_conv1_b;\nextern const std::array<float, 36864> val_conv2_w;\nextern const std::array<float, 64> val_conv2_b;\nextern const std::array<float, 36864> val_conv3_w;\nextern const std::array<float, 64> val_conv3_b;\nextern const std::array<float, 36864> val_conv4_w;\nextern const std::array<float, 64> val_conv4_b;\nextern const std::array<float, 36864> val_conv5_w;\nextern const std::array<float, 64> val_conv5_b;\nextern const std::array<float, 36864> val_conv6_w;\nextern const std::array<float, 64> val_conv6_b;\nextern const std::array<float, 36864> val_conv7_w;\nextern const std::array<float, 64> val_conv7_b;\nextern const std::array<float, 36864> val_conv8_w;\nextern const std::array<float, 64> val_conv8_b;\nextern const std::array<float, 36864> val_conv9_w;\nextern const std::array<float, 64> val_conv9_b;\nextern const std::array<float, 36864> val_conv10_w;\nextern const std::array<float, 64> val_conv10_b;\nextern const std::array<float, 36864> val_conv11_w;\nextern const std::array<float, 64> val_conv11_b;\nextern const std::array<float, 576> val_conv12_w;\nextern const std::array<float, 1> val_conv12_b;\nextern const std::array<float, 92416> val_ip13_w;\nextern const std::array<float, 256> val_ip13_b;\nextern const std::array<float, 256> val_ip14_w;\nextern const std::array<float, 1> val_ip14_b;\n\nNetwork * Network::get_Network(void) {\n    if (!s_Net) {\n        s_Net = new Network();\n        s_Net->initialize();\n    }\n    return s_Net;\n}\n\nvoid Network::benchmark(FastState * state) {\n    {\n        // Policy\n        int BENCH_AMOUNT = 2000;\n        int cpus = cfg_num_threads;\n        int iters_per_thread = (BENCH_AMOUNT + (cpus - 1)) / cpus;\n\n        Time start;\n\n        ThreadGroup tg(thread_pool);\n        for (int i = 0; i < cpus; i++) {\n            tg.add_task([iters_per_thread, state]() {\n                FastState mystate = *state;\n                for (int loop = 0; loop < iters_per_thread; loop++) {\n                    auto vec = get_scored_moves(&mystate, Ensemble::RANDOM_ROTATION);\n                }\n            });\n        };\n        tg.wait_all();\n\n        Time end;\n\n        myprintf(\"%5d predictions in %5.2f seconds -> %d p/s\\n\",\n                 BENCH_AMOUNT,\n                 (float)Time::timediff(start,end)/100.0,\n                 (int)((float)BENCH_AMOUNT/((float)Time::timediff(start,end)/100.0)));\n    }\n    {\n        // Value\n        int BENCH_AMOUNT = 10000;\n        int cpus = cfg_num_threads;\n        int iters_per_thread = (BENCH_AMOUNT + (cpus - 1)) / cpus;\n\n        Time start;\n        ThreadGroup tg(thread_pool);\n        for (int i = 0; i < cpus; i++) {\n            tg.add_task([iters_per_thread, state]() {\n                FastState mystate = *state;\n                for (int loop = 0; loop < iters_per_thread; loop++) {\n                    auto vec = get_value(&mystate, Ensemble::RANDOM_ROTATION);\n                }\n            });\n        };\n        tg.wait_all();\n\n        Time end;\n\n        myprintf(\"%5d evaluations in %5.2f seconds -> %d p/s\\n\",\n                 BENCH_AMOUNT,\n                 (float)Time::timediff(start,end)/100.0,\n                 (int)((float)BENCH_AMOUNT/((float)Time::timediff(start,end)/100.0)));\n    }\n}\n\nvoid Network::initialize(void) {\n#ifdef USE_OPENCL\n    myprintf(\"Initializing OpenCL\\n\");\n    opencl.initialize();\n    myprintf(\"Transferring weights to GPU...\");\n    opencl_policy_net.push_convolve(5, conv1_w, conv1_b);\n    opencl_policy_net.push_convolve(3, conv2_w, conv2_b);\n    opencl_policy_net.push_convolve(3, conv3_w, conv3_b);\n    opencl_policy_net.push_convolve(3, conv4_w, conv4_b);\n    opencl_policy_net.push_convolve(3, conv5_w, conv5_b);\n    opencl_policy_net.push_convolve(3, conv6_w, conv6_b);\n    opencl_policy_net.push_convolve(3, conv7_w, conv7_b);\n    opencl_policy_net.push_convolve(3, conv8_w, conv8_b);\n    opencl_policy_net.push_convolve(3, conv9_w, conv9_b);\n    opencl_policy_net.push_convolve(3, conv10_w, conv10_b);\n    opencl_policy_net.push_convolve(3, conv11_w, conv11_b);\n    opencl_policy_net.push_convolve(3, conv12_w, conv12_b);\n    opencl_policy_net.push_convolve(3, conv13_w, conv13_b);\n\n    opencl_value_net.push_convolve(5, val_conv1_w, val_conv1_b);\n    opencl_value_net.push_convolve(3, val_conv2_w, val_conv2_b);\n    opencl_value_net.push_convolve(3, val_conv3_w, val_conv3_b);\n    opencl_value_net.push_convolve(3, val_conv4_w, val_conv4_b);\n    opencl_value_net.push_convolve(3, val_conv5_w, val_conv5_b);\n    opencl_value_net.push_convolve(3, val_conv6_w, val_conv6_b);\n    opencl_value_net.push_convolve(3, val_conv7_w, val_conv7_b);\n    opencl_value_net.push_convolve(3, val_conv8_w, val_conv8_b);\n    opencl_value_net.push_convolve(3, val_conv9_w, val_conv9_b);\n    opencl_value_net.push_convolve(3, val_conv10_w, val_conv10_b);\n    opencl_value_net.push_convolve(3, val_conv11_w, val_conv11_b);\n    opencl_value_net.push_convolve(3, val_conv12_w, val_conv12_b);\n    opencl_value_net.push_innerproduct(val_ip13_w, val_ip13_b);\n    opencl_value_net.push_innerproduct(val_ip14_w, val_ip14_b);\n    myprintf(\"done\\n\");\n#endif\n#ifdef USE_BLAS\n#ifndef __APPLE__\n#ifdef USE_OPENBLAS\n    openblas_set_num_threads(1);\n    myprintf(\"BLAS Core: %s\\n\", openblas_get_corename());\n#endif\n#ifdef USE_MKL\n    //mkl_set_threading_layer(MKL_THREADING_SEQUENTIAL);\n    mkl_set_num_threads(1);\n    MKLVersion Version;\n    mkl_get_version(&Version);\n    myprintf(\"BLAS core: MKL %s\\n\", Version.Processor);\n#endif\n#endif\n#endif\n#ifdef USE_CAFFE\n    myprintf(\"Initializing DCNN...\");\n    Caffe::set_mode(Caffe::GPU);\n\n    s_net.reset(new Net(\"model_5722.txt\", TEST));\n    s_net->CopyTrainedLayersFrom(\"model_5779.caffemodel\");\n\n    myprintf(\"Inputs: %d Outputs: %d\\n\",\n        s_net->num_inputs(), s_net->num_outputs());\n\n    Blob* input_layer = s_net->input_blobs()[0];\n    int num_channels = input_layer->channels();\n    int width = input_layer->width();\n    int height = input_layer->height();\n    myprintf(\"Input: channels=%d, width=%d, height=%d\\n\", num_channels, width, height);\n\n    for (int i = 0; i < s_net->num_outputs(); i++) {\n        Blob* output_layer = s_net->output_blobs()[i];\n        int num_out_channels = output_layer->channels();\n        width = output_layer->width();\n        height = output_layer->height();\n        myprintf(\"Output: channels=%d, width=%d, height=%d\\n\", num_out_channels, width, height);\n    }\n\n//#define WRITE_WEIGHTS\n#ifdef WRITE_WEIGHTS\n    std::ofstream out(\"weights.txt\");\n    out << \"#include <array>\" << std::endl << std::endl;\n#endif\n\n    int total_weights = 0;\n    auto & layers = s_net->layers();\n    myprintf(\"%d layers:\\n\", layers.size());\n    int layer_num = 1;\n#ifdef WRITE_WEIGHTS\n    int conv_count = 0;\n#endif\n    for (auto it = layers.begin(); it != layers.end(); ++it, ++layer_num) {\n        myprintf(\"layer %d (%s)\", layer_num, (*it)->type());\n        auto & blobs = (*it)->blobs();\n        if (blobs.size() > 0) myprintf(\" = \");\n        for (auto pars = blobs.begin(); pars != blobs.end(); ++pars) {\n            const Blob & blob = *(*pars);\n            total_weights += blob.count();\n            myprintf(\"%s \", blob.shape_string().c_str());\n            if (boost::next(pars) != blobs.end()) myprintf(\"+ \");\n\n#ifdef WRITE_WEIGHTS\n            out << \"// \" << blob.shape_string() << std::endl;\n            if (strcmp((*it)->type(), \"Convolution\") == 0) {\n                if (pars == blobs.begin()) {\n                    conv_count++;\n                    out << \"std::array<float, \" << blob.count()\n                        << \"> val_conv\" << conv_count << \"_w = {{\" << std::endl;\n                } else {\n                    out << \"std::array<float, \" << blob.count()\n                        << \"> val_conv\" << conv_count << \"_b = {{\" << std::endl;\n                }\n            } else if (strcmp((*it)->type(), \"BatchNorm\") == 0) {\n                out << \"std::array<float, \" << blob.count()\n                    << \"> val_bn\" << conv_count << \"_w\" << (pars - blobs.begin()) + 1\n                    << \" = {{\" << std::endl;\n            } else if (strcmp((*it)->type(), \"InnerProduct\") == 0) {\n                if (pars == blobs.begin()) {\n                    conv_count++;\n                    out << \"std::array<float, \" << blob.count()\n                        << \"> val_ip\" << conv_count << \"_w = {{\" << std::endl;\n                } else {\n                    out << \"std::array<float, \" << blob.count()\n                        << \"> val_ip\" << conv_count << \"_b = {{\" << std::endl;\n                }\n            } else {\n                out << \"std::array<float, \" << blob.count()\n                    << \"> val_sc\" << conv_count << \"_w\" << (pars - blobs.begin()) + 1\n                    << \" = {{\" << std::endl;\n            }\n            for (int idx = 0; idx < blob.count(); idx++) {\n                out << blob.cpu_data<float>()[idx];\n                if (idx != blob.count() - 1) out << \", \";\n                else out << \" }};\" << std::endl;\n            }\n            out << std::endl;\n#endif\n        }\n        myprintf(\"\\n\");\n    }\n#ifdef WRITE_WEIGHTS\n    out.close();\n#endif\n    myprintf(\"%d total DCNN weights\\n\", total_weights);\n#endif\n}\n\n#ifdef USE_BLAS\ntemplate<unsigned int filter_size,\n         unsigned int channels, unsigned int outputs,\n         size_t W, size_t B>\nvoid convolve(std::vector<float>& input,\n              const std::array<float, W>& weights,\n              const std::array<float, B>& biases,\n              std::vector<float>& output) {\n    // fixed for 19x19\n    constexpr unsigned int width = 19;\n    constexpr unsigned int height = 19;\n    constexpr unsigned int spatial_out = width * height;\n\n    constexpr unsigned int filter_len = filter_size * filter_size;\n    constexpr unsigned int filter_dim = filter_len * channels;\n\n    std::vector<float> col(filter_dim * width * height);\n    im2col<channels, filter_size>(input, col);\n\n    // Weight shape (output, input, filter_size, filter_size)\n    // 96 22 5 5\n    // outputs[96,19x19] = weights[96,22x9] x col[22x9,19x19]\n    // C\u2190\u03b1AB + \u03b2C\n    // M Number of rows in matrices A and C.\n    // N Number of columns in matrices B and C.\n    // K Number of columns in matrix A; number of rows in matrix B.\n    // lda The size of the first dimention of matrix A; if you are\n    // passing a matrix A[m][n], the value should be m.\n    //    cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n    //                ldb, beta, C, N);\n\n#ifdef USE_ONEDNN\n    dnnl_sgemm('N', 'N',\n                outputs, spatial_out, filter_dim,\n                1.0f, &weights[0], filter_dim,\n                &col[0], spatial_out,\n                0.0f, &output[0], spatial_out);\n#else\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n                // M        N            K\n                outputs, spatial_out, filter_dim,\n                1.0f, &weights[0], filter_dim,\n                &col[0], spatial_out,\n                0.0f, &output[0], spatial_out);\n#endif\n\n    auto lambda_ELU = [](float val) { return (val > 0.0f) ?\n                                      val : 1.0f * (std::exp(val) - 1.0f); };\n    //auto lambda_ReLU = [](float val) { return (val > 0.0f) ?\n    //                                   val : 0.0f; };\n\n    for (unsigned int o = 0; o < outputs; o++) {\n        for (unsigned int b = 0; b < spatial_out; b++) {\n            output[(o * spatial_out) + b] =\n                lambda_ELU(biases[o] + output[(o * spatial_out) + b]);\n        }\n    }\n}\n\ntemplate<unsigned int inputs,\n         unsigned int outputs,\n         size_t W, size_t B>\nvoid innerproduct(std::vector<float>& input,\n                  const std::array<float, W>& weights,\n                  const std::array<float, B>& biases,\n                  std::vector<float>& output) {\n    assert(B == outputs);\n\n    cblas_sgemv(CblasRowMajor, CblasNoTrans,\n                // M     K\n                outputs, inputs,\n                1.0f, &weights[0], inputs,\n                &input[0], 1,\n                0.0f, &output[0], 1);\n\n    auto lambda_ELU = [](float val) { return (val > 0.0f) ?\n                                      val : 1.0f * (std::exp(val) - 1.0f); };\n    //auto lambda_ReLU = [](float val) { return (val > 0.0f) ?\n    //                                   val : 0.0f; };\n\n    for (unsigned int o = 0; o < outputs; o++) {\n        float val = biases[o] + output[o];\n        if (outputs > 1) {\n            val = lambda_ELU(val);\n        }\n        output[o] = val;\n    }\n}\n\ntemplate<unsigned int channels,\n         unsigned int spatial_size>\nvoid batchnorm(std::vector<float>& input,\n               std::array<float, channels>& means,\n               std::array<float, channels>& variances,\n               std::array<float, 1> scale,\n               std::vector<float>& output)\n{\n    constexpr float epsilon = 1e-5;\n\n    for (unsigned int c = 0; c < channels; ++c) {\n        float mean = means[c] / scale[0];\n        float variance = variances[c] / scale[0];\n        variance += epsilon;\n        float scale_stddiv = 1.0f / std::sqrt(variance);\n\n        float * out = &output[c * spatial_size];\n        float const * in  = &input[c * spatial_size];\n        for (unsigned int b = 0; b < spatial_size; b++) {\n            out[b] = scale_stddiv * (in[b] - mean);\n        }\n    }\n}\n#endif\n\nvoid Network::softmax(std::vector<float>& input,\n                      std::vector<float>& output,\n                      float temperature) {\n    assert(&input != &output);\n\n    float alpha = *std::max_element(input.begin(),\n                                    input.begin() + output.size());\n    alpha /= temperature;\n\n    float denom = 0.0f;\n    std::vector<float> helper(output.size());\n    for (size_t i = 0; i < output.size(); i++) {\n        float val  = std::exp((input[i]/temperature) - alpha);\n        helper[i]  = val;\n        denom     += val;\n    }\n    for (size_t i = 0; i < output.size(); i++) {\n        output[i] = helper[i] / denom;\n    }\n}\n\n#ifdef USE_OPENCL\nclass CallbackData {\npublic:\n    std::atomic<int> * m_nodecount;\n    FastState m_state;\n    UCTNode * m_node;\n    int m_rotation;\n    std::atomic<int> * m_thread_results_outstanding;\n    std::vector<float> m_output_data;\n    std::vector<float> m_input_data;\n    Network::BoardPlane m_ladder;\n};\n\nextern \"C\" void CL_CALLBACK forward_cb(cl_event event, cl_int status,\n                                       void* data) {\n    CallbackData * cb_data = static_cast<CallbackData*>(data);\n\n    // Mark the kernels as available\n    cb_data->m_thread_results_outstanding->fetch_sub(1, std::memory_order_release);\n\n    constexpr int width = 19;\n    constexpr int height = 19;\n    std::vector<float> softmax_data(width * height);\n    Network::softmax(cb_data->m_output_data, softmax_data, cfg_softmax_temp);\n    std::vector<float>& outputs = softmax_data;\n\n    Network::Netresult result;\n\n    for (size_t idx = 0; idx < outputs.size(); idx++) {\n        int rot_idx = Network::rev_rotate_nn_idx(idx, cb_data->m_rotation);\n        float val = outputs[rot_idx];\n        int x = idx % 19;\n        int y = idx / 19;\n        int vtx = cb_data->m_state.board.get_vertex(x, y);\n        if (cb_data->m_state.board.get_square(vtx) == FastBoard::EMPTY) {\n            result.push_back(std::make_pair(val, vtx));\n        }\n    }\n\n    /* prune losing ladders completely */\n    for (auto & sm : result) {\n        std::pair<int, int> xy = cb_data->m_state.board.get_xy(sm.second);\n        int bitmappos = (xy.second * 19) + xy.first;\n        if (cb_data->m_ladder[bitmappos]) {\n            //myprintf(\"Ladder at %s (%d) score %f\\n\",\n            //         state->board.move_to_text(sm.second).c_str(),\n            //         sm.second,\n            //         sm.first);\n            sm.first = 0.0f;\n        }\n    }\n\n    // Network::show_heatmap(&cb_data->m_state, result, false);\n\n    cb_data->m_node->scoring_cb(cb_data->m_nodecount, cb_data->m_state,\n                                result, false);\n\n    delete cb_data;\n\n    // Reduce the count of things having pointers to UCTNodes\n    // or UCTSearch. We cannot destroy the search till these\n    // have finished.\n    opencl.callback_finished();\n}\n\nvoid Network::async_scored_moves(std::atomic<int> * nodecount,\n                                 FastState * state,\n                                 UCTNode * node,\n                                 Ensemble ensemble,\n                                 int rotation) {\n    if (state->board.get_boardsize() != 19) {\n        return;\n    }\n\n    assert(ensemble == DIRECT || ensemble == RANDOM_ROTATION);\n    if (ensemble == RANDOM_ROTATION) {\n        assert(rotation == -1);\n        rotation = Random::get_Rng()->randfix<8>();\n    } else {\n        assert(ensemble == DIRECT);\n    }\n\n    CallbackData * cb_data = new CallbackData();\n\n    NNPlanes planes;\n    BoardPlane *ladder;\n    gather_features_policy(state, planes, &ladder);\n\n    constexpr int width = 19;\n    constexpr int height = 19;\n\n    cb_data->m_nodecount = nodecount;\n    cb_data->m_state = *state;\n    cb_data->m_node = node;\n    cb_data->m_input_data.resize(Network::MAX_CHANNELS * 19 * 19);\n    cb_data->m_output_data.resize(Network::MAX_CHANNELS * 19 * 19);\n    cb_data->m_thread_results_outstanding = opencl.get_thread_results_outstanding();\n    //assert(cb_data->m_thread_result_outstanding.load(boost::memory_order_acquire) == 0);\n    cb_data->m_rotation = rotation;\n    cb_data->m_ladder = *ladder;\n\n    for (int c = 0; c < Network::POLICY_CHANNELS; ++c) {\n        for (int h = 0; h < height; ++h) {\n            for (int w = 0; w < width; ++w) {\n                int vtx = rotate_nn_idx(h * 19 + w, rotation);\n                cb_data->m_input_data[(c * height + h) * width + w] =\n                    (float)planes[c][vtx];\n            }\n        }\n    }\n\n    void * data = static_cast<void*>(cb_data);\n\n    opencl_policy_net.forward(cb_data->m_input_data,\n                                    cb_data->m_output_data,\n                                    forward_cb, data);\n}\n#endif\n\nfloat Network::get_value(FastState * state, Ensemble ensemble) {\n    if (state->board.get_boardsize() != 19) {\n        assert(false);\n        return 0.5f;\n    }\n\n    NNPlanes planes;\n    gather_features_value(state, planes);\n    float result;\n\n    if (ensemble == DIRECT) {\n        result = get_value_internal(state, planes, 0);\n    } else if (ensemble == RANDOM_ROTATION) {\n        int rotation = Random::get_Rng()->randfix<8>();\n        result = get_value_internal(state, planes, rotation);\n    } else {\n        assert(ensemble == AVERAGE_ALL);\n        result = get_value_internal(state, planes, 0);\n        //myprintf(\"%5.4f \", result);\n        for (int r = 1; r < 8; r++) {\n            float sum_res = get_value_internal(state, planes, r);\n            //myprintf(\"%5.4f \", sum_res);\n            result += sum_res;\n        }\n        result /= 8.0f;\n    }\n\n    //if (ensemble == AVERAGE_ALL || ensemble == DIRECT) {\n    //    myprintf(\"==> %5.4f\\n\", result);\n    //}\n\n    return result;\n}\n\nNetwork::Netresult Network::get_scored_moves(\n    FastState * state, Ensemble ensemble, int rotation) {\n    Netresult result;\n    if (state->board.get_boardsize() != 19) {\n        return result;\n    }\n\n    NNPlanes planes;\n    BoardPlane* ladder;\n    gather_features_policy(state, planes, &ladder);\n\n    if (ensemble == DIRECT) {\n        assert(rotation >= 0 && rotation <= 7);\n        result = get_scored_moves_internal(state, planes, rotation);\n    } else if (ensemble == RANDOM_ROTATION) {\n        assert(rotation == -1);\n        int rand_rot = Random::get_Rng()->randfix<8>();\n        result = get_scored_moves_internal(state, planes, rand_rot);\n    } else {\n        assert(ensemble == AVERAGE_ALL);\n        result = get_scored_moves_internal(state, planes, 0);\n        for (int r = 1; r < 8; r++) {\n            auto sum_res = get_scored_moves_internal(state, planes, r);\n            for (size_t i = 0; i < sum_res.size(); i++) {\n                assert(result[i].second == sum_res[i].second);\n                result[i].first += sum_res[i].first;\n            }\n        }\n        std::for_each(result.begin(), result.end(),\n                      [](scored_node & sn){ sn.first /= 8.0f; });\n    }\n\n    /* prune losing ladders completely */\n    for (auto & sm : result) {\n        std::pair<int, int> xy = state->board.get_xy(sm.second);\n        int bitmappos = (xy.second * 19) + xy.first;\n        if ((*ladder)[bitmappos]) {\n            //myprintf(\"Ladder at %s (%d) score %f\\n\",\n            //         state->board.move_to_text(sm.second).c_str(),\n            //         sm.second,\n            //         sm.first);\n            sm.first = 0.0f;\n        }\n    }\n\n    // if (ensemble == AVERAGE_ALL || ensemble == DIRECT) {\n    //     show_heatmap(state, result, true);\n    // }\n\n    return result;\n}\n\nfloat Network::get_value_internal(\n    FastState * state, NNPlanes & planes, int rotation) {\n    assert(rotation >= 0 && rotation <= 7);\n    float result;\n\n    constexpr int channels = VALUE_CHANNELS;\n    constexpr int width = 19;\n    constexpr int height = 19;\n    constexpr int max_channels = MAX_VALUE_CHANNELS;\n    std::vector<float> orig_input_data(planes.size() * width * height);\n    std::vector<float> input_data(max_channels * width * height);\n    std::vector<float> output_data(max_channels * width * height);\n    std::vector<float> winrate_data(256);\n    std::vector<float> winrate_out(1);\n\n    for (int c = 0; c < channels; ++c) {\n        for (int h = 0; h < height; ++h) {\n            for (int w = 0; w < width; ++w) {\n                int vtx = rotate_nn_idx(h * 19 + w, rotation);\n                orig_input_data[(c * height + h) * width + w] =\n                    (float)planes[c][vtx];\n            }\n        }\n    }\n#ifdef USE_OPENCL\n    std::copy(orig_input_data.begin(), orig_input_data.end(), input_data.begin());\n    opencl_value_net.forward(input_data, output_data, nullptr, nullptr);\n    // Sigmoid\n    float winrate_sig = (1.0f + std::tanh(output_data[0])) / 2.0f;\n    result = winrate_sig;\n#elif defined(USE_BLAS)\n    std::copy(orig_input_data.begin(), orig_input_data.end(), input_data.begin());\n\n    convolve<5, 32, 64>(input_data, val_conv1_w, val_conv1_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv2_w, val_conv2_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv3_w, val_conv3_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv4_w, val_conv4_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv5_w, val_conv5_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv6_w, val_conv6_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv7_w, val_conv7_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv8_w, val_conv8_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv9_w, val_conv9_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv10_w, val_conv10_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64, 64>(input_data, val_conv11_w, val_conv11_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 64,  1>(input_data, val_conv12_w, val_conv12_b, output_data);\n    // Now get the score\n    innerproduct<361, 256>(output_data, val_ip13_w, val_ip13_b, winrate_data);\n    innerproduct<256, 1>(winrate_data, val_ip14_w, val_ip14_b, winrate_out);\n    // Sigmoid\n    float winrate_sig = (1.0f + std::tanh(winrate_out[0])) / 2.0f;\n    result = winrate_sig;\n #endif\n    return result;\n}\n\nNetwork::Netresult Network::get_scored_moves_internal(\n    FastState * state, NNPlanes & planes, int rotation) {\n    Netresult result;\n    assert(rotation >= 0 && rotation <= 7);\n#ifdef USE_CAFFE\n    Blob* input_layer = s_net->input_blobs()[0];\n    int channels = input_layer->channels();\n    int width = input_layer->width();\n    int height = input_layer->height();\n    assert(channels == (int)planes.size());\n    assert(width == state->board.get_boardsize());\n    assert(height == state->board.get_boardsize());\n    float* orig_input_data = input_layer->mutable_cpu_data<float>();\n#else\n    constexpr int channels = POLICY_CHANNELS;\n    constexpr int width = 19;\n    constexpr int height = 19;\n    constexpr int max_channels = MAX_CHANNELS;\n    std::vector<float> orig_input_data(planes.size() * width * height);\n    std::vector<float> input_data(max_channels * width * height);\n    std::vector<float> output_data(max_channels * width * height);\n    std::vector<float> softmax_data(width * height);\n#endif\n    for (int c = 0; c < channels; ++c) {\n        for (int h = 0; h < height; ++h) {\n            for (int w = 0; w < width; ++w) {\n                int vtx = rotate_nn_idx(h * 19 + w, rotation);\n                orig_input_data[(c * height + h) * width + w] =\n                    (float)planes[c][vtx];\n            }\n        }\n    }\n#ifdef USE_OPENCL\n    std::copy(orig_input_data.begin(), orig_input_data.end(), input_data.begin());\n    opencl_policy_net.forward(input_data, output_data, nullptr, nullptr);\n    softmax(output_data, softmax_data, cfg_softmax_temp);\n    std::vector<float>& outputs = softmax_data;\n#elif defined(USE_BLAS)\n    // XXX really only need the first 24\n    std::copy(orig_input_data.begin(), orig_input_data.end(), input_data.begin());\n\n    convolve<5,  32,  96>(input_data, conv1_w, conv1_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3,  96, 128>(input_data, conv2_w, conv2_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv3_w, conv3_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv4_w, conv4_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv5_w, conv5_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv6_w, conv6_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv7_w, conv7_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv8_w, conv8_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv9_w, conv9_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv10_w, conv10_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv11_w, conv11_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128, 128>(input_data, conv12_w, conv12_b, output_data);\n    std::swap(input_data, output_data);\n    convolve<3, 128,   1>(input_data, conv13_w, conv13_b, output_data);\n    softmax(output_data, softmax_data, cfg_softmax_temp);\n\n    // Move scores\n    std::vector<float>& outputs = softmax_data;\n#endif\n#ifdef USE_CAFFE\n    s_net->Forward();\n    Blob* output_layer = s_net->output_blobs()[0];\n    const float* begin = output_layer->cpu_data<float>();\n    const float* end = begin + output_layer->channels();\n    auto outputs = std::vector<float>(begin, end);\n#endif\n    for (size_t idx = 0; idx < outputs.size(); idx++) {\n        int rot_idx = rev_rotate_nn_idx(idx, rotation);\n        float val = outputs[rot_idx];\n        int x = idx % 19;\n        int y = idx / 19;\n        int vtx = state->board.get_vertex(x, y);\n        if (state->board.get_square(vtx) == FastBoard::EMPTY) {\n            result.push_back(std::make_pair(val, vtx));\n        }\n    }\n\n    return result;\n}\n\nvoid Network::show_heatmap(FastState * state, Netresult& result, bool topmoves) {\n    auto moves = result;\n    std::vector<std::string> display_map;\n    std::string line;\n\n    for (unsigned int y = 0; y < 19; y++) {\n        for (unsigned int x = 0; x < 19; x++) {\n            int vtx = state->board.get_vertex(x, y);\n\n            auto item = std::find_if(moves.cbegin(), moves.cend(),\n                [&vtx](scored_node const & item) {\n                return item.second == vtx;\n            });\n\n            float score = 0.0f;\n            // Non-empty squares won't be scored\n            if (item != moves.end()) {\n                score = item->first;\n                assert(vtx == item->second);\n            }\n\n            line += boost::str(boost::format(\"%3d \") % int(score * 1000));\n            if (x == 18) {\n                display_map.push_back(line);\n                line.clear();\n            }\n        }\n    }\n\n    for (int i = display_map.size() - 1; i >= 0; --i) {\n        myprintf(\"%s\\n\", display_map[i].c_str());\n    }\n\n    if (topmoves) {\n    std::stable_sort(moves.rbegin(), moves.rend());\n\n    float cum = 0.0f;\n    size_t tried = 0;\n    while (cum < 0.85f && tried < moves.size()) {\n        if (moves[tried].first < 0.01f) break;\n        myprintf(\"%1.3f (%s)\\n\",\n                 moves[tried].first,\n                 state->board.move_to_text(moves[tried].second).c_str());\n        cum += moves[tried].first;\n        tried++;\n    }\n    }\n}\n\nvoid Network::gather_features_policy(FastState * state, NNPlanes & planes,\n                                     BoardPlane** ladder_out) {\n    planes.resize(32);\n    BoardPlane& empt_color   = planes[0];\n    BoardPlane& move_color   = planes[1];\n    BoardPlane& othr_color   = planes[2];\n    BoardPlane& libs_1       = planes[3];\n    BoardPlane& libs_2       = planes[4];\n    BoardPlane& libs_3       = planes[5];\n    BoardPlane& libs_4       = planes[6];\n    BoardPlane& libs_5p      = planes[7];\n    BoardPlane& libs_1_e     = planes[8];\n    BoardPlane& libs_2_e     = planes[9];\n    BoardPlane& libs_3_e     = planes[10];\n    BoardPlane& libs_4_e     = planes[11];\n    BoardPlane& libs_5p_e    = planes[12];\n    BoardPlane& after_1      = planes[13];\n    BoardPlane& after_2      = planes[14];\n    BoardPlane& after_3      = planes[15];\n    BoardPlane& after_4      = planes[16];\n    BoardPlane& after_5      = planes[17];\n    BoardPlane& after_6p     = planes[18];\n    BoardPlane& after_1_e    = planes[19];\n    BoardPlane& after_2_e    = planes[20];\n    BoardPlane& after_3_e    = planes[21];\n    BoardPlane& after_4_e    = planes[22];\n    BoardPlane& after_5_e    = planes[23];\n    BoardPlane& after_6p_e   = planes[24];\n    BoardPlane& ladder       = planes[25];\n    BoardPlane& ladder_win   = planes[26];\n    BoardPlane& komove       = planes[27];\n    BoardPlane& movehist1    = planes[28];\n    BoardPlane& movehist2    = planes[29];\n    BoardPlane& has_komi     = planes[30];\n    BoardPlane& line_3       = planes[31];\n\n    if (ladder_out) {\n        *ladder_out = &ladder;\n    }\n\n    bool white_has_komi = true;\n    if (std::fabs(state->get_komi()) <= 0.75f) {\n        white_has_komi = false;\n    }\n\n    int tomove = state->get_to_move();\n    // collect white, black occupation planes\n    for (int j = 0; j < 19; j++) {\n        for(int i = 0; i < 19; i++) {\n            int vtx = state->board.get_vertex(i, j);\n            FastBoard::square_t color =\n                state->board.get_square(vtx);\n            int idx = j * 19 + i;\n            if (i == 2 || i == 16 || j == 2 || j == 16) {\n                line_3[idx] = true;\n            }\n            if (color != FastBoard::EMPTY) {\n                // White gets extra points in scoring\n                if (color == FastBoard::WHITE && white_has_komi) {\n                    has_komi[idx] = true;\n                }\n                if (color == tomove) {\n                    move_color[idx] = true;\n                } else {\n                    othr_color[idx] = true;\n                }\n                int rlibs = state->board.count_rliberties(vtx);\n                if (rlibs == 1) {\n                    if (color == tomove) {\n                        libs_1[idx] = true;\n                    } else {\n                        libs_1_e[idx] = true;\n                    }\n                } else if (rlibs == 2) {\n                    if (color == tomove) {\n                        libs_2[idx] = true;\n                    } else {\n                        libs_2_e[idx] = true;\n                    }\n                } else if (rlibs == 3) {\n                    if (color == tomove) {\n                        libs_3[idx] = true;\n                    } else {\n                        libs_3_e[idx] = true;\n                    }\n                } else if (rlibs == 4) {\n                    if (color == tomove) {\n                        libs_4[idx] = true;\n                    } else {\n                        libs_4_e[idx] = true;\n                    }\n                } else if (rlibs >= 5) {\n                    if (color == tomove) {\n                        libs_5p[idx] = true;\n                    } else {\n                        libs_5p_e[idx] = true;\n                    }\n                }\n            } else {\n                empt_color[idx] = true;\n\n                std::pair<int, int> p =\n                    state->board.after_liberties(tomove, vtx);\n                int al = p.first;\n                if (al == 1) {\n                    after_1[idx] = true;\n                } else if (al == 2) {\n                    after_2[idx] = true;\n                } else if (al == 3) {\n                    after_3[idx] = true;\n                } else if (al == 4) {\n                    after_4[idx] = true;\n                } else if (al == 5) {\n                    after_5[idx] = true;\n                } else if (al >= 6) {\n                    after_6p[idx] = true;\n                }\n                int at = p.second;\n                if (at == 1) {\n                    after_1_e[idx] = true;\n                } else if (at == 2) {\n                    after_2_e[idx] = true;\n                } else if (at == 3) {\n                    after_3_e[idx] = true;\n                } else if (at == 4) {\n                    after_4_e[idx] = true;\n                } else if (at == 5) {\n                    after_5_e[idx] = true;\n                } else if (at >= 6) {\n                    after_6p_e[idx] = true;\n                }\n\n                int ae = state->board.count_pliberties(vtx);\n                if (ae == 2) {\n                    int ss = state->board.saving_size(tomove, vtx);\n                    if (ss > 0) {\n                        bool ll = state->board.check_losing_ladder(tomove, vtx);\n                        ladder[idx] = ll;\n                    }\n                }\n                if (state->board.check_winning_ladder(tomove, vtx)) {\n                    ladder_win[idx] = true;\n                }\n            }\n        }\n    }\n\n    if (state->get_last_move() > 0) {\n        std::pair<int, int> lastmove = state->board.get_xy(state->get_last_move());\n        int idx = lastmove.second * 19 + lastmove.first;\n        movehist1[idx] = true;\n        if (state->get_prevlast_move() > 0) {\n            std::pair<int, int> prevlast = state->board.get_xy(state->get_prevlast_move());\n            int idxp = prevlast.second * 19 + prevlast.first;\n            movehist2[idxp] = true;\n        }\n    }\n\n    if (state->get_komove() > 0) {\n        std::pair<int, int> kosq = state->board.get_xy(state->get_komove());\n        int idx = kosq.second * 19 + kosq.first;\n        komove[idx] = true;\n    }\n}\n\nvoid Network::gather_features_value(FastState * state, NNPlanes & planes) {\n    planes.resize(32);\n    BoardPlane& empt_color   = planes[0];\n    BoardPlane& move_color   = planes[1];\n    BoardPlane& othr_color   = planes[2];\n    BoardPlane& libs_1       = planes[3];\n    BoardPlane& libs_2       = planes[4];\n    BoardPlane& libs_3       = planes[5];\n    BoardPlane& libs_4       = planes[6];\n    BoardPlane& libs_5       = planes[7];\n    BoardPlane& libs_6p      = planes[8];\n    BoardPlane& libs_1_e     = planes[9];\n    BoardPlane& libs_2_e     = planes[10];\n    BoardPlane& libs_3_e     = planes[11];\n    BoardPlane& libs_4_e     = planes[12];\n    BoardPlane& libs_5_e     = planes[13];\n    BoardPlane& libs_6p_e    = planes[14];\n    BoardPlane& after_1      = planes[15];\n    BoardPlane& after_2      = planes[16];\n    BoardPlane& after_3      = planes[17];\n    BoardPlane& after_4      = planes[18];\n    BoardPlane& after_5      = planes[19];\n    BoardPlane& after_6p     = planes[20];\n    BoardPlane& after_1_e    = planes[21];\n    BoardPlane& after_2_e    = planes[22];\n    BoardPlane& after_3_e    = planes[23];\n    BoardPlane& after_4_e    = planes[24];\n    BoardPlane& after_5_e    = planes[25];\n    BoardPlane& after_6p_e   = planes[26];\n    BoardPlane& ladder       = planes[27];\n    BoardPlane& ladder_win   = planes[28];\n    BoardPlane& has_komi     = planes[29];\n    BoardPlane& line_3       = planes[30];\n    BoardPlane& komove       = planes[31];\n\n    bool white_has_komi = true;\n    if (std::fabs(state->get_komi()) <= 0.75f) {\n        white_has_komi = false;\n    }\n\n    int tomove = state->get_to_move();\n    // collect white, black occupation planes\n    for (int j = 0; j < 19; j++) {\n        for(int i = 0; i < 19; i++) {\n            int vtx = state->board.get_vertex(i, j);\n            FastBoard::square_t color =\n                state->board.get_square(vtx);\n            int idx = j * 19 + i;\n            if (i == 2 || i == 16 || j == 2 || j == 16) {\n                line_3[idx] = true;\n            }\n            if (color != FastBoard::EMPTY) {\n                // White gets extra points in scoring\n                if (color == FastBoard::WHITE && white_has_komi) {\n                    has_komi[idx] = true;\n                }\n                if (color == tomove) {\n                    move_color[idx] = true;\n                } else {\n                    othr_color[idx] = true;\n                }\n                int rlibs = state->board.count_rliberties(vtx);\n                if (rlibs == 1) {\n                    if (color == tomove) {\n                        libs_1[idx] = true;\n                    } else {\n                        libs_1_e[idx] = true;\n                    }\n                } else if (rlibs == 2) {\n                    if (color == tomove) {\n                       libs_2[idx] = true;\n                    } else {\n                        libs_2_e[idx] = true;\n                    }\n                } else if (rlibs == 3) {\n                    if (color == tomove) {\n                        libs_3[idx] = true;\n                    } else {\n                        libs_3_e[idx] = true;\n                    }\n                } else if (rlibs == 4) {\n                    if (color == tomove) {\n                        libs_4[idx] = true;\n                    } else {\n                        libs_4_e[idx] = true;\n                    }\n                } else if (rlibs == 5) {\n                    if (color == tomove) {\n                        libs_5[idx] = true;\n                    } else {\n                        libs_5_e[idx] = true;\n                    }\n                }  else if (rlibs >= 6) {\n                    if (color == tomove) {\n                        libs_6p[idx] = true;\n                    } else {\n                        libs_6p_e[idx] = true;\n                    }\n                }\n            } else {\n                empt_color[idx] = true;\n\n                std::pair<int, int> p =\n                    state->board.after_liberties(tomove, vtx);\n                int al = p.first;\n                if (al == 1) {\n                    after_1[idx] = true;\n                } else if (al == 2) {\n                    after_2[idx] = true;\n                } else if (al == 3) {\n                    after_3[idx] = true;\n                } else if (al == 4) {\n                    after_4[idx] = true;\n                } else if (al == 5) {\n                    after_5[idx] = true;\n                } else if (al >= 6) {\n                    after_6p[idx] = true;\n                }\n                int at = p.second;\n                if (at == 1) {\n                    after_1_e[idx] = true;\n                } else if (at == 2) {\n                    after_2_e[idx] = true;\n                } else if (at == 3) {\n                    after_3_e[idx] = true;\n                } else if (at == 4) {\n                    after_4_e[idx] = true;\n                } else if (at == 5) {\n                    after_5_e[idx] = true;\n                } else if (at >= 6) {\n                    after_6p_e[idx] = true;\n                }\n\n                int ss = state->board.saving_size(tomove, vtx);\n                int ae = state->board.count_pliberties(vtx);\n                if (ae == 2) {\n                    if (ss > 0) {\n                        bool ll = state->board.check_losing_ladder(tomove, vtx);\n                        ladder[idx] = ll;\n                    }\n                }\n                if (state->board.check_winning_ladder(tomove, vtx)) {\n                    ladder_win[idx] = true;\n                }\n            }\n        }\n    }\n\n    if (state->get_komove() > 0) {\n        std::pair<int, int> kosq = state->board.get_xy(state->get_komove());\n        int idx = kosq.second * 19 + kosq.first;\n        komove[idx] = true;\n    }\n}\n\nvoid Network::gather_traindata(std::string filename, TrainVector& data) {\n    std::vector<std::string> games = SGFParser::chop_all(filename);\n    int gametotal = games.size();\n    int gamecount = 0;\n\n    size_t train_pos = 0;\n    size_t test_pos = 0;\n\n    myprintf(\"Total games in file: %d\\n\", gametotal);\n    myprintf(\"Shuffling...\\n\");\n    std::random_shuffle(games.begin(), games.end());\n\n    while (gamecount < gametotal) {\n        std::unique_ptr<SGFTree> sgftree(new SGFTree);\n\n        try {\n            sgftree->load_from_string(games[gamecount]);\n        } catch (...) {\n        };\n\n        SGFTree * treewalk = &(*sgftree);\n        size_t counter = 0;\n\n        size_t movecount = sgftree->count_mainline_moves();\n        std::vector<int> tree_moves = sgftree->get_mainline();\n        int who_won = sgftree->get_winner();\n        int handicap = sgftree->get_state()->get_handicap();\n        //float komi = sgftree->get_state()->get_komi();\n        if (handicap) {\n            goto skipnext;\n        }\n        // 5.5, 6.5, 7.5\n        //if (std::abs(komi) > 0.75f && (std::abs(komi) < 5.25f || std::abs(komi) > 7.75f)) {\n        //    goto skipnext;\n        //}\n        if (who_won != FastBoard::BLACK && who_won != FastBoard::WHITE) {\n            goto skipnext;\n        }\n\n        while (counter < movecount) {\n            assert(treewalk != NULL);\n            assert(treewalk->get_state() != NULL);\n            if (treewalk->get_state()->board.get_boardsize() != 19)\n                break;\n\n            KoState * state = treewalk->get_state();\n            int tomove = state->get_to_move();\n            int move;\n\n            if (treewalk->get_child(0) != NULL) {\n                move = treewalk->get_child(0)->get_move(tomove);\n                if (move == SGFTree::EOT) {\n                    break;\n                }\n            } else {\n                break;\n            }\n\n            assert(move == tree_moves[counter]);\n            int this_move = -1;\n\n            std::vector<int> moves = state->generate_moves(tomove);\n            bool moveseen = false;\n            for(auto it = moves.begin(); it != moves.end(); ++it) {\n                if (*it == move) {\n                    if (move != FastBoard::PASS) {\n                        // get x y coords for actual move\n                        std::pair<int, int> xy = state->board.get_xy(move);\n                        this_move = (xy.second * 19) + xy.first;\n                    }\n                    moveseen = true;\n                }\n            }\n\n            bool has_next_moves = counter + 2 < tree_moves.size();\n            if (!has_next_moves) {\n                goto skipnext;\n            }\n\n            has_next_moves  = tree_moves[counter + 1] != FastBoard::PASS;\n            has_next_moves &= tree_moves[counter + 2] != FastBoard::PASS;\n\n            if (!has_next_moves) {\n                goto skipnext;\n            }\n\n            //int skip = Random::get_Rng()->randfix<8>();\n            if (/*skip == 0*/ 1) {\n                if (moveseen && move != FastBoard::PASS && has_next_moves) {\n                    TrainPosition position;\n                    //position.stm_won = (tomove == who_won ? 1.0f : 0.0f);\n                    //position.stm_won_tanh = (tomove == who_won ? 1.0f : -1.0f);\n                    //float frac = (float)counter / (float)movecount;\n                    //position.stm_score = (frac * position.stm_won)\n                        //+ ((1.0f - frac) * 0.5f);\n                    //position.stm_score_tanh = (frac * position.stm_won_tanh)\n                        //+ ((1.0f - frac) * 0.0f);\n                    //gather_features_value(state, position.planes);\n                    position.moves[0] = this_move;\n                    // add next 2 moves to position\n                    // we do not check them for legality\n                    int next_move = tree_moves[counter + 1];\n                    int next_next_move = tree_moves[counter + 2];\n                    std::pair<int, int> xy = state->board.get_xy(next_move);\n                    position.moves[1] = (xy.second * 19) + xy.first;\n                    xy = state->board.get_xy(next_next_move);\n                    position.moves[2] = (xy.second * 19) + xy.first;\n                    gather_features_policy(state, position.planes);\n                    data.push_back(position);\n                } else if (move != FastBoard::PASS) {\n                    myprintf(\"Mainline move not found: %d\\n\", move);\n                    goto skipnext;\n                }\n            }\n\n            counter++;\n            treewalk = treewalk->get_child(0);\n        }\n\nskipnext:\n        gamecount++;\n        if (gamecount % 100 == 0) {\n            myprintf(\"Game %d, %d new positions, %d total\\n\",\n                     gamecount, data.size(), train_pos + data.size());\n        }\n        if (gamecount % (50000) == 0) {\n            train_network(data, train_pos, test_pos);\n        }\n    }\n\n    train_network(data, train_pos, test_pos);\n\n    std::cout << train_pos << \" training positions.\" << std::endl;\n    std::cout << test_pos << \" testing positions.\" << std::endl;\n\n    myprintf(\"Gathering pass done.\\n\");\n}\n\nint Network::rev_rotate_nn_idx(const int vertex, int symmetry) {\n    static const int invert[] = {0, 1, 2, 3, 4, 6, 5, 7};\n    assert(rotate_nn_idx(rotate_nn_idx(vertex, symmetry), invert[symmetry])\n           == vertex);\n    return rotate_nn_idx(vertex, invert[symmetry]);\n}\n\nint Network::rotate_nn_idx(const int vertex, int symmetry) {\n    assert(vertex >= 0 && vertex < 19*19);\n    assert(symmetry >= 0 && symmetry < 8);\n    int x = vertex % 19;\n    int y = vertex / 19;\n    int newx;\n    int newy;\n\n    if (symmetry >= 4) {\n        std::swap(x, y);\n        symmetry -= 4;\n    }\n\n    if (symmetry == 0) {\n        newx = x;\n        newy = y;\n    } else if (symmetry == 1) {\n        newx = x;\n        newy = 19 - y - 1;\n    } else if (symmetry == 2) {\n        newx = 19 - x - 1;\n        newy = y;\n    } else {\n        assert(symmetry == 3);\n        newx = 19 - x - 1;\n        newy = 19 - y - 1;\n    }\n\n    int newvtx = (newy * 19) + newx;\n    assert(newvtx >= 0 && newvtx < 19*19);\n    return newvtx;\n}\n\nvoid Network::train_network(TrainVector& data,\n                            size_t& total_train_pos,\n                            size_t& total_test_pos) {\n#ifdef USE_CAFFE\n    size_t data_size = data.size();\n    size_t traincut = (data_size * 98) / 100;\n\n    size_t train_pos = 0;\n    size_t test_pos = 0;\n\n    std::unique_ptr<caffe::db::DB> train_db(caffe::db::GetDB(\"leveldb\"));\n    std::string dbTrainName(\"leela_train\");\n    train_db->Open(dbTrainName.c_str(), caffe::db::WRITE);\n    std::unique_ptr<caffe::db::DB> train_label_db(caffe::db::GetDB(\"leveldb\"));\n    std::string dbTrainLabelName(\"leela_train_label\");\n    train_label_db->Open(dbTrainLabelName.c_str(), caffe::db::WRITE);\n\n    std::unique_ptr<caffe::db::DB> test_db(caffe::db::GetDB(\"leveldb\"));\n    std::string dbTestName(\"leela_test\");\n    test_db->Open(dbTestName.c_str(), caffe::db::WRITE);\n    std::unique_ptr<caffe::db::DB> test_label_db(caffe::db::GetDB(\"leveldb\"));\n    std::string dbTestLabelName(\"leela_test_label\");\n    test_label_db->Open(dbTestLabelName.c_str(), caffe::db::WRITE);\n\n    std::unique_ptr<caffe::db::Transaction> train_txn(train_db->NewTransaction());\n    std::unique_ptr<caffe::db::Transaction> test_txn(test_db->NewTransaction());\n    std::unique_ptr<caffe::db::Transaction> train_label_txn(train_label_db->NewTransaction());\n    std::unique_ptr<caffe::db::Transaction> test_label_txn(test_label_db->NewTransaction());\n\n    std::cout << \"Shuffling training data...\";\n    std::random_shuffle(data.begin(), data.end());\n    std::cout << \"writing: \";\n\n    size_t data_pos = 0;\n    for (auto it = data.begin(); it != data.end(); ++it) {\n        TrainPosition& position = *it;\n        NNPlanes& nnplanes = position.planes;\n\n        // train data\n        caffe::Datum datum;\n        size_t datum_channels = nnplanes.size();\n        datum.set_channels(datum_channels);\n        datum.set_height(19);\n        datum.set_width(19);\n        std::string buffer(datum_channels * 19 * 19, '\\0');\n        // check whether to rotate the position\n        int symmetry = Random::get_Rng()->randfix<8>();\n        for (size_t p = 0; p < nnplanes.size(); p++) {\n            BoardPlane tmp;\n            for (size_t b = 0; b < nnplanes[p].size(); b++) {\n                float val = nnplanes[p][b];\n                int rot_idx = rotate_nn_idx((int)b, symmetry);\n                tmp[rot_idx] = val;\n            }\n            if (p == 0) {\n                assert(tmp[rot_move] == true);\n            } else if (p == 1 || p == 2) {\n                assert(tmp[rot_move] == false);\n            }\n            for (size_t b = 0; b < tmp.size(); b++) {\n                buffer[(p * (19 * 19)) + b] = (int)tmp[b];\n            }\n        }\n        datum.set_data(buffer);\n        std::string out;\n        datum.SerializeToString(&out);\n\n        // labels\n        caffe::Datum datum_label;\n        datum_label.set_channels(3);\n        datum_label.set_height(1);\n        datum_label.set_width(1);\n\n        int this_move = rotate_nn_idx(position.moves[0], symmetry);\n        int next_move = rotate_nn_idx(position.moves[1], symmetry);\n        int next_next_move = rotate_nn_idx(position.moves[2], symmetry);\n\n        datum_label.add_float_data(this_move);\n        datum_label.add_float_data(next_move);\n        datum_label.add_float_data(next_next_move);\n        //datum_label.add_float_data((float)position.stm_score);\n        //datum_label.add_float_data((float)position.stm_won);\n        //datum_label.add_float_data((float)position.stm_score_tanh);\n        //datum_label.add_float_data((float)position.stm_won_tanh);\n        std::string label_out;\n        datum_label.SerializeToString(&label_out);\n\n        data_pos++;\n        if (data_pos > traincut) {\n            std::stringstream ss;\n            ss << (total_test_pos + test_pos);\n            test_pos++;\n            test_txn->Put(ss.str(), out);\n            test_label_txn->Put(ss.str(), label_out);\n            if (test_pos % 10000 == 0) {\n                std::cout << \"t\";\n                test_txn->Commit();\n                test_label_txn->Commit();\n                test_txn.reset(test_db->NewTransaction());\n                test_label_txn.reset(test_label_db->NewTransaction());\n            }\n        } else {\n            std::stringstream ss;\n            ss << (total_train_pos + train_pos);\n            train_pos++;\n            train_txn->Put(ss.str(), out);\n            train_label_txn->Put(ss.str(), label_out);\n            if (train_pos % 10000 == 0) {\n                std::cout << symmetry;\n                train_txn->Commit();\n                train_label_txn->Commit();\n                train_txn.reset(train_db->NewTransaction());\n                train_label_txn.reset(train_label_db->NewTransaction());\n            }\n        }\n    }\n    data.clear();\n\n    train_txn->Commit();\n    test_txn->Commit();\n    train_label_txn->Commit();\n    test_label_txn->Commit();\n\n    total_train_pos += train_pos;\n    total_test_pos += test_pos;\n\n    std::cout << std::endl;\n#endif\n}\n\nvoid Network::autotune_from_file(std::string filename) {\n#ifdef USE_CAFFE\n#if 0\n    {\n        std::unique_ptr<caffe::db::DB> train_db(caffe::db::GetDB(\"leveldb\"));\n        std::string dbTrainName(\"leela_train\");\n        train_db->Open(dbTrainName.c_str(), caffe::db::NEW);\n        std::unique_ptr<caffe::db::DB> train_label_db(caffe::db::GetDB(\"leveldb\"));\n        std::string dbTrainLabelName(\"leela_train_label\");\n        train_label_db->Open(dbTrainLabelName.c_str(), caffe::db::NEW);\n        std::unique_ptr<caffe::db::DB> test_db(caffe::db::GetDB(\"leveldb\"));\n        std::string dbTestName(\"leela_test\");\n        test_db->Open(dbTestName.c_str(), caffe::db::NEW);\n        std::unique_ptr<caffe::db::DB> test_label_db(caffe::db::GetDB(\"leveldb\"));\n        std::string dbTestLabelName(\"leela_test_label\");\n        test_label_db->Open(dbTestLabelName.c_str(), caffe::db::NEW);\n    }\n#endif\n#endif\n    TrainVector data;\n    gather_traindata(filename, data);\n}\n\nstd::string Network::get_backend() {\n#if defined(USE_OPENCL)\n    return opencl.get_device_name();\n#elif defined(USE_CAFFE)\n    return std::string(\"Caffe\");\n#else\n#ifdef USE_BLAS\n#ifndef __APPLE__\n#ifdef USE_OPENBLAS\n    return std::string(\"BLAS core: \" + std::string(openblas_get_corename()));\n#endif\n#ifdef USE_MKL\n    MKLVersion Version;\n    mkl_get_version(&Version);\n    return std::string(\"BLAS core: \" + std::string(Version.Processor));\n#endif\n#else\n    return std::string(\"BLAS core: Apple Accelerate\");\n#endif\n#endif\n#endif\n    return std::string(\"No BLAS backend active\");\n}\n", "meta": {"hexsha": "3dd5369c1bafb36c67a2e448d79f0d600114655f", "size": 57289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "engine/Network.cpp", "max_stars_repo_name": "MAOmao000/LeelaGUI", "max_stars_repo_head_hexsha": "6dd8d53826008a7d44fe23be975dd0d01282404e", "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": "engine/Network.cpp", "max_issues_repo_name": "MAOmao000/LeelaGUI", "max_issues_repo_head_hexsha": "6dd8d53826008a7d44fe23be975dd0d01282404e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engine/Network.cpp", "max_forks_repo_name": "MAOmao000/LeelaGUI", "max_forks_repo_head_hexsha": "6dd8d53826008a7d44fe23be975dd0d01282404e", "max_forks_repo_licenses": ["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.5363520408, "max_line_length": 96, "alphanum_fraction": 0.5535792211, "num_tokens": 15281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.18019534574676405}}
{"text": "// Copyright (c) 2015-2018 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 \"read_assigner.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <algorithm>\n#include <limits>\n#include <random>\n#include <stdexcept>\n#include <cassert>\n\n#include <boost/optional.hpp>\n\n#include \"utils/maths.hpp\"\n#include \"utils/kmer_mapper.hpp\"\n#include \"core/models/haplotype_likelihood_model.hpp\"\n#include \"core/models/error/error_model_factory.hpp\"\n\nnamespace octopus {\n\nnamespace {\n\nusing HaplotypeLikelihoods = std::vector<std::vector<double>>;\n\nauto vectorise(const std::vector<Haplotype>& haplotypes, const HaplotypeProbabilityMap& priors)\n{\n    std::vector<double> result(haplotypes.size());\n    std::transform(std::cbegin(haplotypes), std::cend(haplotypes), std::begin(result),\n                   [&] (const auto& haplotype) { return priors.at(haplotype); });\n    return result;\n}\n\nauto get_priors(const std::vector<Haplotype>& haplotypes, const HaplotypeProbabilityMap& log_priors)\n{\n    if (log_priors.empty()) {\n        return std::vector<double>(haplotypes.size());\n    } else {\n        return vectorise(haplotypes, log_priors);\n    }\n}\n\nvoid find_map_haplotypes(const std::vector<Haplotype>& haplotypes, const unsigned read,\n                         const HaplotypeLikelihoods& likelihoods, const std::vector<double>& log_priors,\n                         std::vector<unsigned>& result)\n{\n    assert(result.empty());\n    auto max_likelihood = std::numeric_limits<double>::lowest();\n    for (unsigned k {0}; k < haplotypes.size(); ++k) {\n        const auto curr = likelihoods[k][read] + log_priors[k];\n        if (maths::almost_equal(curr, max_likelihood)) {\n            result.push_back(k);\n        } else if (curr > max_likelihood) {\n            result.assign({k});\n            max_likelihood = curr;\n        }\n    }\n    if (result.empty()) {\n        result.resize(haplotypes.size());\n        std::iota(std::begin(result), std::end(result), 0);\n    }\n}\n\ntemplate <typename ForwardIt, typename RandomGenerator>\nForwardIt random_select(ForwardIt first, ForwardIt last, RandomGenerator& g)\n{\n    if (first == last) return first;\n    const auto max = static_cast<std::size_t>(std::distance(first, last));\n    if (max == 1) return first;\n    std::uniform_int_distribution<std::size_t> dist {0, max - 1};\n    std::advance(first, dist(g));\n    return first;\n}\n\ntemplate <typename ForwardIt>\nForwardIt random_select(ForwardIt first, ForwardIt last)\n{\n    static thread_local std::mt19937 generator {42};\n    return random_select(first, last, generator);\n}\n\ntemplate <typename Range>\ndecltype(auto) random_select(const Range& values)\n{\n    assert(!values.empty());\n    return *random_select(std::cbegin(values), std::cend(values));\n}\n\nauto calculate_support(const std::vector<Haplotype>& haplotypes,\n                       const std::vector<AlignedRead>& reads,\n                       const std::vector<double>& log_priors,\n                       const HaplotypeLikelihoods& likelihoods,\n                       boost::optional<AmbiguousReadList&> ambiguous,\n                       const AssignmentConfig& config)\n{\n    HaplotypeSupportMap result {};\n    std::vector<unsigned> top {};\n    top.reserve(haplotypes.size());\n    for (unsigned i {0}; i < reads.size(); ++i) {\n        const auto& read = reads[i];\n        find_map_haplotypes(haplotypes, i, likelihoods, log_priors, top);\n        if (top.size() == 1) {\n            result[haplotypes[top.front()]].push_back(read);\n        } else {\n            using UA = AssignmentConfig::AmbiguousAction;\n            switch (config.ambiguous_action) {\n                case UA::first:\n                    result[haplotypes[top.front()]].push_back(read);\n                    break;\n                case UA::all: {\n                    for (auto idx : top) result[haplotypes[idx]].push_back(read);\n                    break;\n                }\n                case UA::random: {\n                    result[haplotypes[random_select(top)]].push_back(read);\n                    break;\n                }\n                case UA::drop:\n                default:\n                    break;\n            }\n            if (ambiguous) {\n                ambiguous->emplace_back(read);\n                if (config.ambiguous_record != AssignmentConfig::AmbiguousRecord::read_only) {\n                    ambiguous->back().haplotypes = std::vector<Haplotype> {};\n                    ambiguous->back().haplotypes->reserve(top.size());\n                    for (auto idx : top) ambiguous->back().haplotypes->push_back(haplotypes[idx]);\n                }\n            }\n        }\n        top.clear();\n    }\n    return result;\n}\n\ntemplate <typename MappableTp>\nGenomicRegion::Size estimate_max_indel_size(const MappableTp& mappable)\n{\n    const auto p = std::minmax({region_size(mappable), static_cast<GenomicRegion::Size>(sequence_size(mappable))});\n    return p.second - p.first;\n}\n\ntemplate <typename MappableTp>\nauto estimate_max_indel_size(const std::vector<MappableTp>& mappables)\n{\n    GenomicRegion::Size result {0};\n    for (const auto& mappable : mappables) {\n        result = std::max(result, estimate_max_indel_size(mappable));\n    }\n    return result;\n}\n\ntemplate <typename Container>\nauto compute_read_hashes(const Container& reads)\n{\n    static constexpr unsigned char mapperKmerSize {6};\n    std::vector<KmerPerfectHashes> result {};\n    result.reserve(reads.size());\n    std::transform(std::cbegin(reads), std::cend(reads), std::back_inserter(result),\n                   [=] (const AlignedRead& read) { return compute_kmer_hashes<mapperKmerSize>(read.sequence()); });\n    return result;\n}\n\nauto expand_for_alignment(const Haplotype& haplotype, const GenomicRegion& reads_region,\n                          const GenomicRegion::Size indel_factor)\n{\n    const auto min_flank_pad = 2 * HaplotypeLikelihoodModel::pad_requirement();\n    const auto& haplotype_region = mapped_region(haplotype);\n    unsigned min_lhs_expansion {min_flank_pad}, min_rhs_expansion {min_flank_pad};\n    if (begins_before(reads_region, haplotype_region)) {\n        min_lhs_expansion += begin_distance(reads_region, haplotype_region);\n    }\n    if (ends_before(haplotype_region, reads_region)) {\n        min_rhs_expansion += end_distance(haplotype_region, reads_region);\n    }\n    const auto min_expansion = std::max(min_lhs_expansion, min_rhs_expansion) + indel_factor;\n    return expand(haplotype, min_expansion);\n}\n\ntemplate <typename Container>\nauto calculate_likelihoods(const std::vector<Haplotype>& haplotypes, const Container& reads,\n                           HaplotypeLikelihoodModel& model)\n{\n    assert(!haplotypes.empty());\n    const auto reads_region = encompassing_region(reads);\n    const auto read_hashes = compute_read_hashes(reads);\n    static constexpr unsigned char mapperKmerSize {6};\n    auto haplotype_hashes = init_kmer_hash_table<mapperKmerSize>();\n    HaplotypeLikelihoods result {};\n    result.reserve(haplotypes.size());\n    const auto indel_factor = estimate_max_indel_size(haplotypes) + estimate_max_indel_size(reads);\n    for (const auto& haplotype : haplotypes) {\n        const auto expanded_haplotype = expand_for_alignment(haplotype, reads_region, indel_factor);\n        populate_kmer_hash_table<mapperKmerSize>(expanded_haplotype.sequence(), haplotype_hashes);\n        auto haplotype_mapping_counts = init_mapping_counts(haplotype_hashes);\n        model.reset(expanded_haplotype);\n        std::vector<double> likelihoods(reads.size());\n        std::transform(std::cbegin(reads), std::cend(reads), std::cbegin(read_hashes), std::begin(likelihoods),\n                       [&] (const auto& read, const auto& read_hash) {\n                           auto mapping_positions = map_query_to_target(read_hash, haplotype_hashes, haplotype_mapping_counts);\n                           reset_mapping_counts(haplotype_mapping_counts);\n                           return model.evaluate(read, mapping_positions);\n                       });\n        clear_kmer_hash_table(haplotype_hashes);\n        result.push_back(std::move(likelihoods));\n    }\n    return result;\n}\n\n} // namespace\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          const HaplotypeProbabilityMap& log_priors,\n                          HaplotypeLikelihoodModel model,\n                          boost::optional<AmbiguousReadList&> ambiguous,\n                          AssignmentConfig config)\n{\n    if (!reads.empty()) {\n        if (!genotype.is_homozygous()) {\n            const auto unique_haplotypes = genotype.copy_unique();\n            assert(unique_haplotypes.size() > 1);\n            const auto priors = get_priors(unique_haplotypes, log_priors);\n            const auto likelihoods = calculate_likelihoods(unique_haplotypes, reads, model);\n            return calculate_support(unique_haplotypes, reads, priors, likelihoods, ambiguous, config);\n        } else if (config.ambiguous_action != AssignmentConfig::AmbiguousAction::drop) {\n            HaplotypeSupportMap result {};\n            result.emplace(genotype[0], reads);\n            return result;\n        }\n    }\n    return {};\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AmbiguousReadList& ambiguous,\n                          const HaplotypeProbabilityMap& log_priors,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, log_priors, model, ambiguous, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          HaplotypeLikelihoodModel model,\n                          AmbiguousReadList& ambiguous,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, ambiguous, {}, model, config);\n}\n\nstatic HaplotypeLikelihoodModel make_default_haplotype_likelihood_model()\n{\n    HaplotypeLikelihoodModel::Config config {};\n    config.use_mapping_quality = false;\n    return {nullptr, make_indel_error_model(), config};\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AmbiguousReadList& ambiguous,\n                          const HaplotypeProbabilityMap& log_priors,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, log_priors, model, ambiguous, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AmbiguousReadList& ambiguous,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, model, ambiguous, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          const HaplotypeProbabilityMap& log_priors,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, log_priors, model, boost::none, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, model, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, {}, std::move(model), boost::none, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AmbiguousReadList& ambiguous,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, std::move(model), ambiguous, config);\n}\n\nAlleleSupportMap\ncompute_allele_support(const std::vector<Allele>& alleles, const HaplotypeSupportMap& haplotype_support)\n{\n    return compute_allele_support(alleles, haplotype_support,\n                                  [] (const Haplotype& haplotype, const Allele& allele) {\n                                      return haplotype.includes(allele);\n                                  });\n}\n\nauto copy_included(const std::vector<Allele>& alleles, const Haplotype& haplotype)\n{\n    std::vector<Allele> result {};\n    result.reserve(alleles.size());\n    std::copy_if(std::cbegin(alleles), std::cend(alleles), std::back_inserter(result),\n                [&] (const auto& allele) { return haplotype.includes(allele); });\n    return result;\n}\n\nstruct HaveDifferentAlleles\n{\n    bool operator()(const Haplotype& lhs, const Haplotype& rhs) const\n    {\n        const auto lhs_includes = copy_included(alleles, lhs);\n        const auto rhs_includes = copy_included(alleles, rhs);\n        return lhs_includes != rhs_includes;\n    }\n    HaveDifferentAlleles(const std::vector<Allele>& alleles) : alleles {alleles} {}\n    const std::vector<Allele>& alleles;\n};\n\nbool have_common_alleles(const std::vector<Haplotype>& haplotypes, const std::vector<Allele>& alleles)\n{\n    return std::adjacent_find(std::cbegin(haplotypes), std::cend(haplotypes), HaveDifferentAlleles {alleles}) == std::cend(haplotypes);\n}\n\nvoid sort_and_merge(std::deque<AlignedReadConstReference>& src, ReadRefSupportSet& dst)\n{\n    std::sort(std::begin(src), std::end(src));\n    auto itr = dst.insert(std::end(dst), std::begin(src), std::end(src));\n    std::inplace_merge(std::begin(dst), itr, std::end(dst));\n}\n\nstd::size_t\ntry_assign_ambiguous_reads_to_alleles(const std::vector<Allele>& alleles,\n                                      const AmbiguousReadList& ambiguous_reads,\n                                      AlleleSupportMap& allele_support)\n{\n    std::size_t num_assigned {0};\n    std::unordered_map<Allele, std::deque<AlignedReadConstReference>> assigned {};\n    assigned.reserve(alleles.size());\n    for (const auto& ambiguous_read : ambiguous_reads) {\n        if (ambiguous_read.haplotypes && have_common_alleles(*ambiguous_read.haplotypes, alleles)) {\n            const auto supported_alleles = copy_included(alleles, ambiguous_read.haplotypes->front());\n            for (const auto& allele : supported_alleles) {\n                assigned[allele].emplace_back(ambiguous_read.read);\n            }\n        }\n    }\n    for (auto& p : assigned) sort_and_merge(p.second, allele_support[p.first]);\n    return num_assigned;\n}\n\nAlleleSupportMap\ncompute_allele_support(const std::vector<Allele>& alleles,\n                       const HaplotypeSupportMap& haplotype_support,\n                       const AmbiguousReadList& ambiguous_reads)\n{\n    auto result = compute_allele_support(alleles, haplotype_support);\n    try_assign_ambiguous_reads_to_alleles(alleles, ambiguous_reads, result);\n    return result;\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "3bba48fa4ac9eafe6905658c1915df287696f041", "size": 15772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/tools/read_assigner.cpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "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/tools/read_assigner.cpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/tools/read_assigner.cpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.7279596977, "max_line_length": 135, "alphanum_fraction": 0.6504565052, "num_tokens": 3497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.18017838706690534}}
{"text": "#pragma once\n\n// std\n#include <iostream>\n#include <string>\n#include <vector>\n#include <memory>\n#include <cassert>\n#include <tuple>\n#include <unordered_map>\n#include <math.h>\n// ros\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <ros/time.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/time_synchronizer.h>\n#include <message_filters/sync_policies/exact_time.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/CameraInfo.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/PointCloud.h>\n#include <sensor_msgs/point_cloud2_iterator.h>\n#include <cv_bridge/cv_bridge.h>\n#include <image_geometry/pinhole_camera_model.h>\n#include <std_msgs/Float32MultiArray.h>\n#include <std_msgs/MultiArrayDimension.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n// opencv\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/core/matx.hpp>\n#include <opencv2/core/eigen.hpp>\n\n// boost\n#include <boost/shared_ptr.hpp>\n\n// tensorflow\n//#include <tensorflow/c/c_api.h>\n\n// for the PointSegmentedDistribution class\n#include \"PointSegmentedDistribution.hpp\"\n#include \"SegmentationMapping/ImageLabelDistribution.h\"\n\n\n//namespace tf = tensorflow;\n//namespace tf_ops = tensorflow::ops;\n\nnamespace SegmentationMapping {\n\n\n  typedef message_filters::sync_policies::ExactTime\n  <sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo, sensor_msgs::Image, ImageLabelDistribution> sync_pol;\n\n  template <unsigned int NUM_CLASS>\n  class StereoSegmentation {\n  public:\n    StereoSegmentation()\n      : nh_()\n      , color_topic_(\"/camera/color/image_raw\")\n      , depth_topic_(\"/camera/aligned_depth_to_color/image_raw\")\n      , depth_cam_topic_(\"/camera/aligned_depth_to_color/camera_info\")\n      , label_topic_(\"/labeled_image\")\n      , distribution_topic_(\"/distribution_image\")\n    {\n      ros::NodeHandle pnh(\"~\");\n      pnh.getParam(\"color_topic\", color_topic_);\n      pnh.getParam(\"depth_topic\", depth_topic_);\n      pnh.getParam(\"depth_cam_topic\", depth_cam_topic_);\n      pnh.getParam(\"label_topic\", label_topic_);\n      pnh.getParam(\"distribution_topic\", distribution_topic_);\n\n      // init the message filter for image, depth, camera info\n      color_sub_ = new message_filters::Subscriber<sensor_msgs::Image> (pnh, color_topic_, 50);\n      depth_sub_ = new message_filters::Subscriber<sensor_msgs::Image> (pnh, depth_topic_, 50);\n      depth_cam_sub_ = new message_filters::Subscriber<sensor_msgs::CameraInfo> (pnh, depth_cam_topic_, 50);\n      label_sub_ = new message_filters::Subscriber<sensor_msgs::Image> (pnh, label_topic_, 5);\n      distribution_sub_ = new message_filters::Subscriber<ImageLabelDistribution> (pnh, distribution_topic_, 5);\n      sync_ = new message_filters::Synchronizer<sync_pol> (sync_pol(300), *depth_sub_, *color_sub_, *depth_cam_sub_, *label_sub_, *distribution_sub_);\n      \n      sync_->registerCallback(boost::bind(&StereoSegmentation::DepthColorCallback, this,_1, _2, _3, _4, _5));\n      \n      pc1_publisher_ = pnh.advertise<sensor_msgs::PointCloud>(\"/labeled_pointcloud\", 1);\n      pc2_publisher_ = pnh.advertise<sensor_msgs::PointCloud2>(\"/labeled_pointcloud_color_pc2\", 1);\n\n\n      num_skip_frames = pnh.getParam(\"skip_every_k_frame\", num_skip_frames);\n\n      /*\n      // init tensorflow\n      std::string input_tensor_name, output_distribution_tensor_name, output_label_tensor_name;\n      pnh.getParam(\"tf_input_tensor\", input_tensor_name);\n      //pnh.getParam(\"tf_label_output_tensor\", output_label_tensor_name);\n      pnh.getParam(\"tf_distribution_output_tensor\", output_distribution_tensor_name);\n      std::string frozen_graph_path;\n      pnh.getParam(\"tf_frozen_graph_path\", frozen_graph_path );\n      ROS_DEBUG(\"Init tf_Inference....\");\n      tf_infer.reset(new tfInference(frozen_graph_path, input_tensor_name,\n                                   output_label_tensor_name, output_distribution_tensor_name));\n      ROS_DEBUG_STREAM(\"Init tensorflow and revoke frozen graph from \"<<frozen_graph_path);\n      */\n      label2color[2]  =std::make_tuple(250, 250, 250 ); // road\n      label2color[3]  =std::make_tuple(250, 250, 250 ); // sidewalk\n      label2color[5]  =std::make_tuple(250, 128, 0   ); // building\n      label2color[10] =std::make_tuple(192, 192, 192 ); // pole\n      label2color[12] =std::make_tuple(250, 250, 0   ); // sign\n      label2color[6]  =std::make_tuple(0  , 100, 0   ); // vegetation\n      label2color[4]  =std::make_tuple(128, 128, 0   ); // terrain\n      label2color[13] =std::make_tuple(135, 206, 235 ); // sky\n      label2color[1]  =std::make_tuple( 30, 144, 250 ); // water\n      label2color[8]  =std::make_tuple(220, 20,  60  ); // person\n      label2color[7]  =std::make_tuple( 0, 0,142     ); // car\n      label2color[9]  =std::make_tuple(119, 11, 32   ); // bike\n      label2color[11] =std::make_tuple(123, 104, 238 ); // stair\n      label2color[0]  =std::make_tuple(255, 255, 255 ); // background\n      \n    }\n    \n    ~StereoSegmentation() {\n      delete sync_;\n      delete color_sub_;\n      delete depth_sub_;\n      delete depth_cam_sub_;\n    }\n\n    void DepthColorCallback(const sensor_msgs::ImageConstPtr& depth_msg,\n                            const sensor_msgs::ImageConstPtr& color_msg,\n                            const sensor_msgs::CameraInfoConstPtr& camera_info_msg,\n                            const sensor_msgs::ImageConstPtr& labeled_msg,\n                            const ImageLabelDistributionConstPtr & distribution_msg);\n\n    void Depth2PointCloud1(const sensor_msgs::ImageConstPtr& depth_msg,\n                           const sensor_msgs::ImageConstPtr& color_msg,\n                           bool publish_semantic,\n                           const cv::Mat & label_img,\n                           const cv::Mat & distribution_img);\n    void Depth2PointCloud2(const sensor_msgs::ImageConstPtr& depth_msg,\n                           const sensor_msgs::ImageConstPtr& color_msg,\n                           bool publish_semantic,\n                           const cv::Mat & label_img);\n\n    \n  private:\n    ros::NodeHandle nh_;\n    std::string color_topic_;\n    std::string depth_topic_;\n    std::string depth_cam_topic_;\n    std::string label_topic_;\n    std::string distribution_topic_;\n\n    message_filters::Subscriber<sensor_msgs::Image>* color_sub_;\n    message_filters::Subscriber<sensor_msgs::Image> *depth_sub_;\n    message_filters::Subscriber<sensor_msgs::CameraInfo>* depth_cam_sub_;\n    message_filters::Subscriber<sensor_msgs::Image> *label_sub_;\n    message_filters::Subscriber<ImageLabelDistribution> *distribution_sub_;\n    message_filters::Synchronizer<sync_pol>* sync_;\n    //message_filters::TimeSynchronizer<sync_pol>* sync_;\n    //sync_pol* sync_;\n\n    ros::Publisher pc1_publisher_;\n    ros::Publisher pc2_publisher_;\n    // For camera depth to point cloud\n    image_geometry::PinholeCameraModel model_;\n    ros::Subscriber label_sub;\n\n    int num_skip_frames;\n    //std::unique_ptr<tfInference> tf_infer;\n    std::unordered_map<int, std::tuple<uint8_t, uint8_t, uint8_t>> label2color;\n  };\n  \n  template <unsigned int NUM_CLASS>\n  inline void\n  StereoSegmentation<NUM_CLASS>::DepthColorCallback(const sensor_msgs::ImageConstPtr& depth_msg,\n                                                    const sensor_msgs::ImageConstPtr& color_msg,\n                                                    const sensor_msgs::CameraInfoConstPtr& camera_info_msg,\n                                                    const sensor_msgs::ImageConstPtr& labeled_msg,\n                                                    const ImageLabelDistributionConstPtr & distribution_msg) {\n    ros::Time curr_t = ros::Time::now();\n    ROS_DEBUG_STREAM(\"Callback starts at time \"<<uint32_t(curr_t.toSec())<<\". \"<<(uint32_t)curr_t.toNSec() );\n    \n    // std::cout << \"depth: \" << depth_msg->header.stamp << std::endl;\n    // std::cout << \"color: \" << color_msg->header.stamp << std::endl;\n    // std::cout << \"camera_info: \" << camera_info_msg->header.stamp << std::endl;\n    // std::cout << \"labeled_msg: \" << labeled_msg->header.stamp << std::endl;\n    // std::cout << \"distribution_msg: \" << distribution_msg->header.stamp << std::endl;\n\n\n    // std::cout<<\"DepthColorCallback: New callback\"<< depth_msg->header.frame_id <<\"\\n\";\n    // Check for bad inputs\n    if (depth_msg->header.frame_id != color_msg->header.frame_id) {\n      ROS_ERROR(\"Depth iamge frame id [%s] doesn't match color image frame id [%s]\",\n          depth_msg->header.frame_id.c_str(), color_msg->header.frame_id.c_str());\n      return;\n    }\n    \n    // Get rgb and depth images\n    cv_bridge::CvImagePtr color_ptr;\n    cv_bridge::CvImagePtr depth_ptr;\n    cv_bridge::CvImagePtr label_ptr;\n    try{\n      color_ptr = cv_bridge::toCvCopy(color_msg, sensor_msgs::image_encodings::RGB8);\n      depth_ptr = cv_bridge::toCvCopy(depth_msg, sensor_msgs::image_encodings::TYPE_16UC1);\n      label_ptr = cv_bridge::toCvCopy(labeled_msg, sensor_msgs::image_encodings::TYPE_8UC1);\n    } catch (cv_bridge::Exception& e) {\n      ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n      return;\n    }\n    //;cv::Mat color = color_ptr->image;\n    //cv::Mat depth = depth_ptr->image;\n\n    int rows = color_ptr->image.rows;\n    int cols = color_ptr->image.cols;\n    \n    //float * buffer = new float [distribution_msg->distribution.data.layout.dims[0].stride];\n    std::vector<float> data = distribution_msg->distribution.data;\n   \n    //  TensorMap<Tensor<int, 4>> t_4d(storage, 2, 4, 2, 8);\n    //Eigen::Map<Eigen::MatrixXf> mat(data.data(), h, w);\n    //cv::Mat distribution_output = cv::Mat(rows, cols, CV_32FC(uint32_t(distribution_msg->distribution.layout.dim[2].size)), distribution_msg->distribution.data).clone();\n    cv::Mat distribution_output = cv::Mat(rows, cols, CV_32FC(NUM_CLASS), const_cast<float*>(distribution_msg->distribution.data.data())).clone();\n    //std::cout<<\"distribution.data size \"<<distribution_output.total() * distribution_output.elemSize()<<std::endl;\n    \n    //tf_infer->segmentation(color, 20, label_output, distribution_output);\n    \n      \n    // Update camera model\n    this->model_.fromCameraInfo(camera_info_msg);\n\n    Depth2PointCloud1(depth_msg, color_msg, true, label_ptr->image, distribution_output);\n\n    // Debugging\n#ifndef NDEBUG\n    Depth2PointCloud2(depth_msg, color_msg, false, label_ptr->image);\n#endif\n    //curr_t = ros::Time::now();\n    //ROS_DEBUG_STREAM(\"Callback ends at time \"<<uint32_t(curr_t.toSec())<<\". \"<<(uint32_t)curr_t.toNSec() );\n\n\n  }\n\n  \n\n  template <unsigned int NUM_CLASS>\n  inline void\n  StereoSegmentation<NUM_CLASS>::Depth2PointCloud1(const sensor_msgs::ImageConstPtr& depth_msg,\n                                                   const sensor_msgs::ImageConstPtr& color_msg,\n                                                   bool publish_semantic,\n                                                   const cv::Mat & label_img,\n                                                   const cv::Mat & distribution_img) {\n    std::cout<<\"New image with label\\n\";\n    \n    // Set up to-publish cloud msg\n    sensor_msgs::PointCloud::Ptr cloud_msg(new sensor_msgs::PointCloud);\n    cloud_msg->header = depth_msg->header;  // use depth image time stamp\n    sensor_msgs::ChannelFloat32 label_channel;\n    label_channel.name = \"labels\";\n    sensor_msgs::ChannelFloat32 r_channel;\n    r_channel.name = \"r\";\n    sensor_msgs::ChannelFloat32 g_channel;\n    g_channel.name = \"g\";\n    sensor_msgs::ChannelFloat32 b_channel;\n    b_channel.name = \"b\";\n    sensor_msgs::ChannelFloat32 r_original_channel;\n    r_channel.name = \"r_original\";\n    sensor_msgs::ChannelFloat32 g_original_channel;\n    g_channel.name = \"g_original\";\n    sensor_msgs::ChannelFloat32 b_original_channel;\n    b_channel.name = \"b_original\";\n\n    sensor_msgs::ChannelFloat32 distribution_channel[NUM_CLASS];\n\n    // Use correct principal point from camera info\n    float center_x = model_.cx();\n    float center_y = model_.cy();\n\n    // Combine unit conversion with scaling by focal length for computing X, Y\n    double unit_scaling = 0.001f;\n    float constant_x = unit_scaling / model_.fx();\n    float constant_y = unit_scaling / model_.fy();\n    float bad_point = std::numeric_limits<float>::quiet_NaN();\n  \n    const uint16_t* depth_row = reinterpret_cast<const uint16_t*>(&depth_msg->data[0]);\n    int row_step = depth_msg->step / sizeof(uint16_t);\n    const uint8_t* color = &color_msg->data[0];\n    int color_step = 3;  // 1 if mono\n    int color_skip = color_msg->step - color_msg->width * color_step;\n\n    cv::Mat distribution_exp;\n    if (publish_semantic){\n      //cv::cv2eigen(distribution_img, distribution_exp);\n      distribution_exp  = distribution_img;\n      //cv::exp(distribution_img, distribution_exp);\n      std::cout<<\"elemSize: \"<<distribution_exp.elemSize()<<\", total \"<<distribution_exp.total()<<\", channels \"<<distribution_exp.channels()<<std::endl;\n    }\n\n    // Iterate through depth image\n    int i = 0;  // num of point\n    int points_count = 0;\n    for (int v = 0; v < int(depth_msg->height); ++v, depth_row += row_step, color += color_skip){\n      for (int u = 0; u < int(depth_msg->width); ++u, color += color_step, ++i) {\n\n      // Skip the upper half of the image\n      //if (v < int(depth_msg->height / 2))\n      //  continue;\n      \n      uint16_t depth = depth_row[u];\n\n      // Check for invalid measurements\n      // Kaiduo Fang: max_depth = 9;\n      geometry_msgs::Point32 p;\n      if (depth <= 0 ) {\n        p.x = p.y = p.z = bad_point;\n      }\n      else {\n        // Fill in XYZ\n        p.x = (u - center_x) * depth * constant_x;\n        p.y = (v - center_y) * depth * constant_y;\n        p.z = (float) depth * unit_scaling;\n        points_count += 1;\n      }\n\n      if (depth > 0)\n      \tif (sqrt(p.x * p.x + p.y * p.y + p.z * p.z) > 9)\n          p.x = p.y = p.z = bad_point;\n\n      cloud_msg->points.push_back(p);\n\n      if (publish_semantic) {\n\n        // Fill in semantics\n        //cv::Mat dist_cv =distribution_exp(cv::Rect(u, v, 1, 1));\n        cv::Vec<float, NUM_CLASS> dist_class = distribution_exp.at<cv::Vec<float, NUM_CLASS>>(v, u);\n        /*        float sums = cv::sum(dist_class)[0];\n        if (sums < 0.99 || sums > 1.01) {\n\n          std::cerr<<\"Wrong sum out of range: \"<<sums<<std::endl;\n          }*/\n        //Eigen::VectorXf dist;\n        //Eigen::Map<Eigen::Matrix<float, 20, 1> > eigenT( dist_cv.data );\n        //dist = eigenT;\n        //cv::cv2eigen(dist_cv, dist);\n        //Eigen::VectorXf dist = distribution_exp(u, v);\n        //Eigen::VectorXf dist_class = dist.segment(0, NUM_CLASS);\n        /*\n        Eigen::VectorXf dist_background = dist.segment(NUM_CLASS, dist.size()-NUM_CLASS);\n        //assume background is 0\n        float sum_background = dist_background.sum() + dist_class(0);\n        dist_class(0) = sum_background;\n        float sum_all_exp = dist_class.sum();\n        dist_class = (dist_class / sum_all_exp).eval();\n        */\n        int max_ind =0;\n        float max_elem = 0;\n        for (int i = 0; i < NUM_CLASS; i++) {\n          if (dist_class(i) > max_elem) {\n            max_ind = i;\n            max_elem = dist_class(i);\n          }\n          distribution_channel[i].values.push_back( dist_class(i) );\n        }\n        \n        int label = max_ind;\n        //std::cout<<\"label is \"<<label<<std::endl;\n        label_channel.values.push_back(label);\n        r_channel.values.push_back(std::get<0>(label2color[label]));\n        g_channel.values.push_back(std::get<1>(label2color[label]));\n        b_channel.values.push_back(std::get<2>(label2color[label]));\n        r_original_channel.values.push_back(color[0]);\n        g_original_channel.values.push_back(color[1]);\n        b_original_channel.values.push_back(color[2]);\n        \n      } else {\n        // Fill in r g b channels: bgr\n        r_channel.values.push_back(color[0]);\n        g_channel.values.push_back(color[1]);\n        b_channel.values.push_back(color[2]);\n        // Fill in semantics\n        label_channel.values.push_back(1);\n        distribution_channel[0].values.push_back(1);\n        for (int i = 1; i < NUM_CLASS; i++) {\n          distribution_channel[i].values.push_back(0);\n        }\n      }\n    }\n   }\n    std::cout << \"count_points: \" << points_count << std::endl << std::endl;\n\n    \n    cloud_msg->channels.push_back(label_channel);\n    cloud_msg->channels.push_back(r_channel);\n    cloud_msg->channels.push_back(g_channel);\n    cloud_msg->channels.push_back(b_channel);\n    cloud_msg->channels.push_back(r_original_channel );\n    cloud_msg->channels.push_back(g_original_channel);\n    cloud_msg->channels.push_back(b_original_channel);\n    for (int i = 0; i < NUM_CLASS; i++)\n      cloud_msg->channels.push_back(distribution_channel[i]);\n\n    \n    pc1_publisher_.publish(cloud_msg);\n  }\n\n  \n  \n  template <unsigned int NUM_CLASS>\n  inline void\n  StereoSegmentation<NUM_CLASS>::Depth2PointCloud2(const sensor_msgs::ImageConstPtr& depth_msg,\n                                                   const sensor_msgs::ImageConstPtr& color_msg,\n                                                   bool publish_semantic,\n                                                   const cv::Mat & label_img) {\n   // Set up to-publish cloud msg\n   sensor_msgs::PointCloud2::Ptr cloud_msg (new sensor_msgs::PointCloud2);\n   cloud_msg->header = depth_msg->header;  // use depth image time stamp\n   \n   cloud_msg->height = depth_msg->height;\n   cloud_msg->width = depth_msg->width;\n   cloud_msg->is_dense = false;\n   cloud_msg->is_bigendian = false;\n\n   sensor_msgs::PointCloud2Modifier pcd_modifier(*cloud_msg);\n   pcd_modifier.setPointCloud2FieldsByString(2, \"xyz\", \"rgb\");\n\n   // Use correct principal point from camera info\n   float center_x = model_.cx();\n   float center_y = model_.cy();\n\n   // Combine unit conversion with scaling by focal length for computing X,Y\n   double unit_scaling = 0.001f;\n   float constant_x = unit_scaling / model_.fx();\n   float constant_y = unit_scaling / model_.fy();\n   float bad_point = std::numeric_limits<float>::quiet_NaN();\n\n   const uint16_t* depth_row = reinterpret_cast<const uint16_t*>(&depth_msg->data[0]);\n   int row_step = depth_msg->step / sizeof(uint16_t);\n   const uint8_t* color = &color_msg->data[0];\n   int color_step = 3;  // 1 if mono\n   int color_skip = color_msg->step - color_msg->width * color_step;\n\n\n   sensor_msgs::PointCloud2Iterator<float> iter_x(*cloud_msg, \"x\");\n   sensor_msgs::PointCloud2Iterator<float> iter_y(*cloud_msg, \"y\");\n   sensor_msgs::PointCloud2Iterator<float> iter_z(*cloud_msg, \"z\");\n   sensor_msgs::PointCloud2Iterator<uint8_t> iter_r(*cloud_msg, \"r\");\n   sensor_msgs::PointCloud2Iterator<uint8_t> iter_g(*cloud_msg, \"g\");\n   sensor_msgs::PointCloud2Iterator<uint8_t> iter_b(*cloud_msg, \"b\");\n   sensor_msgs::PointCloud2Iterator<uint8_t> iter_a(*cloud_msg, \"a\");\n\n   // Iterate through depth image\n   for (int v = 0 ; v < int(cloud_msg->height); ++v, depth_row += row_step, color += color_skip){\n    for (int u = 0; u < int(cloud_msg->width); ++u, color += color_step, \n        ++iter_x, ++iter_y, ++iter_z, ++iter_a, ++iter_r, ++iter_g, ++iter_b) {\n      \n      // Skip the upper half of the image\n      //if (v < int(cloud_msg->height / 2))\n      // continue;\n\n      uint16_t depth = depth_row[u];\n      \n      // Check for invalid measurements\n      // update by Kaiduo Fang: depth > 9, max_depth;\n      if (depth <= 0)\n        *iter_x = *iter_y = *iter_z = bad_point;\n      else {\n        // Fill in XYZ\n        *iter_x = (u - center_x) * depth * constant_x;\n        *iter_y = (v - center_y) * depth * constant_y;\n        *iter_z = (float) depth * unit_scaling;\n        if (*iter_z > 10)\n        *iter_z = bad_point;\n      }\n      \n\n      // Fill in color\n      //label_channel.values.push_back(label);\n      if (publish_semantic) {\n      uint8_t label = label_img.at<uint8_t>(u, v);\n\n      *iter_a = 255;\n      *iter_r = std::get<0>(label2color[label]);\n      *iter_g = std::get<1>(label2color[label]);\n      *iter_b = std::get<2>(label2color[label]);\n      } else {\n      *iter_a = 255;\n      *iter_r = color[0];\n      *iter_g = color[1];\n      *iter_b = color[2];\n\n      }\n    \n    }\n   }\n    pc2_publisher_.publish(cloud_msg);\n  }\n\n\n\n\n\n  \n}\n\n\n", "meta": {"hexsha": "4d6ed6dcf98163fe05004f08830d98a0f07f68b1", "size": 20287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SegmentationMapping/stereo_segmentation.hpp", "max_stars_repo_name": "UMich-BipedLab/SegmentationMapping", "max_stars_repo_head_hexsha": "b58eec234ae6fd78a2e7ba8b2398ff05fb467e19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T20:47:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T02:49:56.000Z", "max_issues_repo_path": "include/SegmentationMapping/stereo_segmentation.hpp", "max_issues_repo_name": "crankler/SegmentationMapping", "max_issues_repo_head_hexsha": "f4f95fa848ff59e322488d5b17e6ea1bdd15831c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-07T09:22:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-02T19:01:12.000Z", "max_forks_repo_path": "include/SegmentationMapping/stereo_segmentation.hpp", "max_forks_repo_name": "crankler/SegmentationMapping", "max_forks_repo_head_hexsha": "f4f95fa848ff59e322488d5b17e6ea1bdd15831c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-06-23T20:50:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T10:59:12.000Z", "avg_line_length": 40.0138067061, "max_line_length": 171, "alphanum_fraction": 0.6468181594, "num_tokens": 5091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.18016401651049285}}
{"text": "/* Copyright (c) 2016 - 2021, 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 THERMAL_PHYSICS_TEMPLATES_HH\n#define THERMAL_PHYSICS_TEMPLATES_HH\n\n#include <ThermalOperator.hh>\n#if defined(ADAMANTINE_HAVE_CUDA) && defined(__CUDACC__)\n#include <ThermalOperatorDevice.hh>\n#endif\n#include <CubeHeatSource.hh>\n#include <ElectronBeamHeatSource.hh>\n#include <GoldakHeatSource.hh>\n#include <ThermalPhysics.hh>\n\n#include <deal.II/base/geometry_info.h>\n#include <deal.II/distributed/cell_data_transfer.templates.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_nothing.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/filtered_iterator.h>\n#include <deal.II/hp/fe_values.h>\n#include <deal.II/hp/q_collection.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_gmres.h>\n\n#ifdef ADAMANTINE_WITH_CALIPER\n#include <caliper/cali.h>\n#endif\n\n#include <algorithm>\n#include <execution>\n\nnamespace adamantine\n{\nnamespace\n{\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\ndealii::LA::distributed::Vector<double, MemorySpaceType>\nevaluate_thermal_physics_impl(\n    std::shared_ptr<ThermalOperatorBase<dim, MemorySpaceType>> thermal_operator,\n    double const t, double const current_source_height,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n    std::vector<Timer> &timers)\n{\n  timers[evol_time_eval_mat_prop].start();\n  thermal_operator->evaluate_material_properties(y);\n  timers[evol_time_eval_mat_prop].stop();\n\n  timers[evol_time_eval_th_ph].start();\n  thermal_operator->set_time_and_source_height(t, current_source_height);\n\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> value(\n      y.get_partitioner());\n  value = 0.;\n  // Apply the Thermal Operator.\n  thermal_operator->vmult_add(value, y);\n\n  // Multiply by the inverse of the mass matrix.\n  value.scale(*thermal_operator->get_inverse_mass_matrix());\n\n  timers[evol_time_eval_th_ph].stop();\n\n  return value;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\nvoid init_dof_vector(\n    double const value,\n    dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType> &vector)\n{\n  unsigned int const local_size = vector.locally_owned_size();\n  for (unsigned int i = 0; i < local_size; ++i)\n    vector.local_element(i) = value;\n}\n\n#ifdef ADAMANTINE_HAVE_CUDA\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\ndealii::LA::distributed::Vector<double, MemorySpaceType> vmult_and_scale(\n    std::shared_ptr<ThermalOperatorBase<dim, MemorySpaceType>> const\n        &thermal_operator,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n    dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> &value,\n    std::vector<Timer> &timers)\n{\n  dealii::LA::distributed::Vector<double, MemorySpaceType> value_dev(\n      value.get_partitioner());\n  value_dev.import(value, dealii::VectorOperation::insert);\n\n  // Apply the Thermal Operator.\n  thermal_operator->vmult_add(value_dev, y);\n\n  // Multiply by the inverse of the mass matrix.\n  value_dev.scale(*thermal_operator->get_inverse_mass_matrix());\n\n  timers[evol_time_eval_th_ph].stop();\n\n  return value_dev;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\ndealii::LA::distributed::Vector<double, MemorySpaceType>\nevaluate_thermal_physics_impl(\n    std::shared_ptr<ThermalOperatorBase<dim, MemorySpaceType>> const\n        &thermal_operator,\n    dealii::hp::FECollection<dim> const &fe_collection, double const t,\n    dealii::DoFHandler<dim> const &dof_handler,\n    std::vector<std::shared_ptr<HeatSource<dim>>> const &heat_sources,\n    double current_source_height, BoundaryType boundary_type,\n    std::shared_ptr<MaterialProperty<dim>> const &material_properties,\n    dealii::AffineConstraints<double> const &affine_constraints,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n    std::vector<Timer> &timers)\n{\n  timers[evol_time_eval_mat_prop].start();\n  // TODO do this on the GPU\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> y_host(\n      y.get_partitioner());\n  y_host.import(y, dealii::VectorOperation::insert);\n  thermal_operator->evaluate_material_properties(y_host);\n  timers[evol_time_eval_mat_prop].stop();\n\n  timers[evol_time_eval_th_ph].start();\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> source(\n      y.get_partitioner());\n  source = 0.;\n\n  // Compute the source term.\n  dealii::hp::QCollection<dim> source_q_collection;\n  source_q_collection.push_back(dealii::QGauss<dim>(fe_degree + 1));\n  source_q_collection.push_back(dealii::QGauss<dim>(1));\n  dealii::hp::FEValues<dim> hp_fe_values(fe_collection, source_q_collection,\n                                         dealii::update_quadrature_points |\n                                             dealii::update_values |\n                                             dealii::update_JxW_values);\n  unsigned int const dofs_per_cell = fe_collection.max_dofs_per_cell();\n  unsigned int const n_q_points = source_q_collection.max_n_quadrature_points();\n  std::vector<dealii::types::global_dof_index> local_dof_indices(dofs_per_cell);\n  dealii::QGauss<dim - 1> face_quadrature(fe_degree + 1);\n  dealii::FEFaceValues<dim> fe_face_values(\n      fe_collection[0], face_quadrature,\n      dealii::update_values | dealii::update_quadrature_points |\n          dealii::update_JxW_values);\n  unsigned int const n_face_q_points = face_quadrature.size();\n  dealii::Vector<double> cell_source(dofs_per_cell);\n\n  // Loop over the locally owned cells with an active FE index of zero\n  for (auto const &cell : dealii::filter_iterators(\n           dof_handler.active_cell_iterators(),\n           dealii::IteratorFilters::LocallyOwnedCell(),\n           dealii::IteratorFilters::ActiveFEIndexEqualTo(0)))\n  {\n    cell_source = 0.;\n    hp_fe_values.reinit(cell);\n    dealii::FEValues<dim> const &fe_values =\n        hp_fe_values.get_present_fe_values();\n\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n    {\n      for (unsigned int q = 0; q < n_q_points; ++q)\n      {\n        double const inv_rho_cp = thermal_operator->get_inv_rho_cp(cell, q);\n        double quad_pt_source = 0.;\n        dealii::Point<dim> const &q_point = fe_values.quadrature_point(q);\n        for (auto &beam : heat_sources)\n          quad_pt_source += beam->value(q_point, t, current_source_height);\n\n        cell_source[i] += inv_rho_cp * quad_pt_source *\n                          fe_values.shape_value(i, q) * fe_values.JxW(q);\n      }\n    }\n\n    // If we don't have a adiabatic boundary conditions, we need to add boundary\n    // conditions\n    if (!(boundary_type & BoundaryType::adiabatic))\n    {\n      for (unsigned int f = 0; f < dealii::GeometryInfo<dim>::faces_per_cell;\n           ++f)\n      {\n        // We need to add the boundary conditions on the faces on the boundary\n        // but also on the faces at the interface with FE_Nothing\n        auto const &face = cell->face(f);\n        if ((face->at_boundary()) &&\n            ((!face->at_boundary()) &&\n             (cell->neighbor(f)->active_fe_index() != 0)))\n        {\n          double conv_temperature_infty = 0.;\n          double conv_heat_transfer_coef = 0.;\n          double rad_temperature_infty = 0.;\n          double rad_heat_transfer_coef = 0.;\n          if (boundary_type & BoundaryType::convective)\n          {\n            conv_temperature_infty = material_properties->get_cell_value(\n                cell, Property::convection_temperature_infty);\n            conv_heat_transfer_coef = material_properties->get_cell_value(\n                cell, StateProperty::convection_heat_transfer_coef);\n          }\n          if (boundary_type & BoundaryType::radiative)\n          {\n            rad_temperature_infty = material_properties->get_cell_value(\n                cell, Property::radiation_temperature_infty);\n            rad_heat_transfer_coef = material_properties->get_cell_value(\n                cell, StateProperty::radiation_heat_transfer_coef);\n          }\n\n          fe_face_values.reinit(cell, face);\n          for (unsigned int i = 0; i < dofs_per_cell; ++i)\n          {\n            for (unsigned int q = 0; q < n_face_q_points; ++q)\n            {\n              double const inv_rho_cp =\n                  thermal_operator->get_inv_rho_cp(cell, q);\n              cell_source[i] +=\n                  inv_rho_cp *\n                  (conv_heat_transfer_coef * conv_temperature_infty +\n                   rad_heat_transfer_coef * rad_temperature_infty) *\n                  fe_face_values.shape_value(i, q) * fe_face_values.JxW(q);\n            }\n          }\n        }\n      }\n    }\n    cell->get_dof_indices(local_dof_indices);\n    affine_constraints.distribute_local_to_global(cell_source,\n                                                  local_dof_indices, source);\n  }\n\n  source.compress(dealii::VectorOperation::add);\n\n  return vmult_and_scale<dim, fe_degree, MemorySpaceType>(thermal_operator, y,\n                                                          source, timers);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\nvoid init_dof_vector(\n    double const value,\n    dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType> &vector)\n{\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>\n      vector_host(vector.get_partitioner());\n  unsigned int const local_size = vector_host.local_size();\n  for (unsigned int i = 0; i < local_size; ++i)\n    vector_host.local_element(i) = value;\n\n  vector.import(vector_host, dealii::VectorOperation::insert);\n}\n#endif\n} // namespace\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::ThermalPhysics(\n    MPI_Comm const &communicator, boost::property_tree::ptree const &database,\n    Geometry<dim> &geometry)\n    : _boundary_type(BoundaryType::invalid), _geometry(geometry),\n      _dof_handler(_geometry.get_triangulation())\n{\n  // Create the FECollection\n  _fe_collection.push_back(dealii::FE_Q<dim>(fe_degree));\n  _fe_collection.push_back(dealii::FE_Nothing<dim>());\n\n  // Create the QCollection\n  _q_collection.push_back(QuadratureType(fe_degree + 1));\n  _q_collection.push_back(QuadratureType(1));\n\n  // Create the material properties\n  boost::property_tree::ptree const &material_database =\n      database.get_child(\"materials\");\n  _material_properties.reset(new MaterialProperty<dim>(\n      communicator, _geometry.get_triangulation(), material_database));\n\n  // Create the heat sources\n  boost::property_tree::ptree const &source_database =\n      database.get_child(\"sources\");\n  // PropertyTreeInput sources.n_beams\n  unsigned int const n_beams = source_database.get<unsigned int>(\"n_beams\");\n  _heat_sources.resize(n_beams);\n  for (unsigned int i = 0; i < n_beams; ++i)\n  {\n    // PropertyTreeInput sources.beam_X.type\n    boost::property_tree::ptree const &beam_database =\n        source_database.get_child(\"beam_\" + std::to_string(i));\n    std::string type = beam_database.get<std::string>(\"type\");\n    if (type == \"goldak\")\n    {\n      _heat_sources[i] = std::make_shared<GoldakHeatSource<dim>>(beam_database);\n    }\n    else if (type == \"electron_beam\")\n    {\n      _heat_sources[i] =\n          std::make_shared<ElectronBeamHeatSource<dim>>(beam_database);\n    }\n    else if (type == \"cube\")\n    {\n      _heat_sources[i] = std::make_shared<CubeHeatSource<dim>>(beam_database);\n    }\n    else\n    {\n      ASSERT_THROW(false, \"Error: Beam type '\" +\n                              beam_database.get<std::string>(\"type\") +\n                              \"' not recognized.\");\n    }\n  }\n\n  // Create the boundary condition type\n  // PropertyTreeInput boundary.type\n  std::string boundary_type_str = database.get<std::string>(\"boundary.type\");\n  // Parse the string\n  size_t pos_str = 0;\n  std::string boundary;\n  std::string delimiter = \",\";\n  auto parse_boundary_type = [&](std::string const &boundary) {\n    if (boundary == \"adiabatic\")\n    {\n      ASSERT_THROW(_boundary_type == BoundaryType::invalid,\n                   \"Adiabatic condition cannot be combined with another type.\");\n      _boundary_type = BoundaryType::adiabatic;\n    }\n    else\n    {\n      ASSERT_THROW(_boundary_type != BoundaryType::adiabatic,\n                   \"Adiabatic condition cannot be combined with another type.\");\n\n      if (boundary == \"radiative\")\n      {\n        _boundary_type |= BoundaryType::radiative;\n      }\n      else if (boundary == \"convective\")\n      {\n        _boundary_type |= BoundaryType::convective;\n      }\n      else\n      {\n        ASSERT_THROW(false, \"Unknown boundary type.\");\n      }\n    }\n  };\n  while ((pos_str = boundary_type_str.find(delimiter)) != std::string::npos)\n  {\n    boundary = boundary_type_str.substr(0, pos_str);\n    parse_boundary_type(boundary);\n    boundary_type_str.erase(0, pos_str + delimiter.length());\n  }\n  parse_boundary_type(boundary_type_str);\n\n  // Create the thermal operator\n  if (std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value)\n    _thermal_operator =\n        std::make_shared<ThermalOperator<dim, fe_degree, MemorySpaceType>>(\n            communicator, _boundary_type, _material_properties, _heat_sources);\n#if defined(ADAMANTINE_HAVE_CUDA) && defined(__CUDACC__)\n  else\n    _thermal_operator = std::make_shared<\n        ThermalOperatorDevice<dim, fe_degree, MemorySpaceType>>(\n        communicator, _material_properties);\n#endif\n\n  // Create the time stepping scheme\n  boost::property_tree::ptree const &time_stepping_database =\n      database.get_child(\"time_stepping\");\n  // PropertyTreeInput time_stepping.method\n  std::string method = time_stepping_database.get<std::string>(\"method\");\n  std::transform(method.begin(), method.end(), method.begin(),\n                 [](unsigned char c) { return std::tolower(c); });\n  if (method.compare(\"forward_euler\") == 0)\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ExplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::FORWARD_EULER);\n  else if (method.compare(\"rk_third_order\") == 0)\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ExplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::RK_THIRD_ORDER);\n  else if (method.compare(\"rk_fourth_order\") == 0)\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ExplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::RK_CLASSIC_FOURTH_ORDER);\n  else if (method.compare(\"heun_euler\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::HEUN_EULER);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"bogacki_shampine\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::BOGACKI_SHAMPINE);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"dopri\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::DOPRI);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"fehlberg\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::FEHLBERG);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"cash_karp\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::CASH_KARP);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"backward_euler\") == 0)\n  {\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::BACKWARD_EULER);\n    _implicit_method = true;\n  }\n  else if (method.compare(\"implicit_midpoint\") == 0)\n  {\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::IMPLICIT_MIDPOINT);\n    _implicit_method = true;\n  }\n  else if (method.compare(\"crank_nicolson\") == 0)\n  {\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::CRANK_NICOLSON);\n    _implicit_method = true;\n  }\n  else if (method.compare(\"sdirk2\") == 0)\n  {\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::SDIRK_TWO_STAGES);\n    _implicit_method = true;\n  }\n\n  if (_embedded_method == true)\n  {\n    // PropertyTreeInput time_steppping.coarsening_parameter\n    double coarsen_param =\n        time_stepping_database.get(\"coarsening_parameter\", 1.2);\n    // PropertyTreeInput time_steppping.refining_parameter\n    double refine_param = time_stepping_database.get(\"refining_parameter\", 0.8);\n    // PropertyTreeInput time_stepping.min_time_step\n    double min_delta = time_stepping_database.get(\"min_time_step\", 1e-14);\n    // PropertyTreeInput time_stepping.max_time_step\n    double max_delta = time_stepping_database.get(\"max_time_step\", 1e100);\n    // PropertyTreeInput time_stepping.refining_tolerance\n    double refine_tol = time_stepping_database.get(\"refining_tolerance\", 1e-8);\n    // PropertyTreeInput time_stepping.coarsening_tolerance\n    double coarsen_tol =\n        time_stepping_database.get(\"coarsening_tolerance\", 1e-12);\n    dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector> *embedded_rk =\n        static_cast<\n            dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector> *>(\n            _time_stepping.get());\n    embedded_rk->set_time_adaptation_parameters(coarsen_param, refine_param,\n                                                min_delta, max_delta,\n                                                refine_tol, coarsen_tol);\n  }\n\n  // If the time stepping scheme is implicit, set the parameters for the solver\n  // and create the implicit operator.\n  if (_implicit_method == true)\n  {\n    // PropertyTreeInput time_stepping.max_iteration\n    _max_iter = time_stepping_database.get(\"max_iteration\", 1000);\n    // PropertyTreeInput time_stepping.tolerance\n    _tolerance = time_stepping_database.get(\"tolerance\", 1e-12);\n    // PropertyTreeInput time_stepping.right_preconditioning\n    _right_preconditioning =\n        time_stepping_database.get(\"right_preconditioning\", false);\n    // PropertyTreeInput time_stepping.n_tmp_vectors\n    _max_n_tmp_vectors = time_stepping_database.get(\"n_tmp_vectors\", 30);\n    // PropertyTreeInput time_stepping.newton_max_iteration\n    unsigned int newton_max_iter =\n        time_stepping_database.get(\"newton_max_iteration\", 100);\n    // PropertyTreeInput time_stepping.newton_tolerance\n    double newton_tolerance =\n        time_stepping_database.get(\"newton_tolerance\", 1e-6);\n    dealii::TimeStepping::ImplicitRungeKutta<LA_Vector> *implicit_rk =\n        static_cast<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector> *>(\n            _time_stepping.get());\n    implicit_rk->set_newton_solver_parameters(newton_max_iter,\n                                              newton_tolerance);\n\n    // PropertyTreeInput time_stepping.jfnk\n    bool jfnk = time_stepping_database.get(\"jfnk\", false);\n    _implicit_operator = std::make_unique<ImplicitOperator<MemorySpaceType>>(\n        _thermal_operator, jfnk);\n  }\n\n  // Set material on part of the domain\n  // PropertyTreeInput geometry.material_height\n  double const material_height = database.get(\"geometry.material_height\", 1e9);\n  for (auto const &cell :\n       dealii::filter_iterators(_dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    // If the center of the cell is below material_height, it contains material\n    // otherwise it does not.\n    if (cell->center()[axis<dim>::z] < material_height)\n      cell->set_active_fe_index(0);\n    else\n      cell->set_active_fe_index(1);\n  }\n\n  // Set the initial height of the heat source. Right now this is just the\n  // maximum heat source height, which can lead to unexpected behavior for\n  // different sources with different heights.\n  double temp_height = std::numeric_limits<double>::lowest();\n  for (auto const &source : _heat_sources)\n  {\n    temp_height = std::max(temp_height, source->get_current_height(0.0));\n  }\n  _current_source_height = temp_height;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                    QuadratureType>::setup_dofs()\n{\n  _dof_handler.distribute_dofs(_fe_collection);\n  dealii::IndexSet locally_relevant_dofs;\n  dealii::DoFTools::extract_locally_relevant_dofs(_dof_handler,\n                                                  locally_relevant_dofs);\n  _affine_constraints.clear();\n  _affine_constraints.reinit(locally_relevant_dofs);\n  dealii::DoFTools::make_hanging_node_constraints(_dof_handler,\n                                                  _affine_constraints);\n  _affine_constraints.close();\n\n  _thermal_operator->reinit(_dof_handler, _affine_constraints, _q_collection);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                    QuadratureType>::compute_inverse_mass_matrix()\n{\n  _thermal_operator->compute_inverse_mass_matrix(\n      _dof_handler, _affine_constraints, _fe_collection);\n  if (_implicit_method == true)\n    _implicit_operator->set_inverse_mass_matrix(\n        _thermal_operator->get_inverse_mass_matrix());\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    add_material(\n        std::vector<\n            typename dealii::DoFHandler<dim>::active_cell_iterator> const\n            &elements_to_activate,\n        double new_material_temperature,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> &solution)\n{\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_FUNCTION;\n#endif\n  std::vector<dealii::Vector<double>> data_to_transfer;\n  unsigned int const dofs_per_cell = _dof_handler.get_fe().n_dofs_per_cell();\n  dealii::Vector<double> cell_solution(dofs_per_cell);\n  dealii::Vector<double> dummy_cell_solution(dofs_per_cell);\n  for (auto &val : dummy_cell_solution)\n  {\n    val = std::numeric_limits<double>::infinity();\n  }\n  solution.update_ghost_values();\n  std::vector<dealii::types::global_dof_index> dof_indices(dofs_per_cell);\n  for (auto const &cell : _dof_handler.active_cell_iterators())\n  {\n    if ((cell->is_locally_owned()) && (cell->active_fe_index() == 0))\n    {\n      cell->get_dof_values(solution, cell_solution);\n      data_to_transfer.push_back(cell_solution);\n    }\n    else\n    {\n      data_to_transfer.push_back(dummy_cell_solution);\n    }\n  }\n\n  // Activate elements by updating the fe_index\n  for (auto const &cell : elements_to_activate)\n  {\n    cell->set_active_fe_index(0);\n  }\n\n  dealii::parallel::distributed::Triangulation<dim> &triangulation =\n      dynamic_cast<dealii::parallel::distributed::Triangulation<dim> &>(\n          const_cast<dealii::Triangulation<dim> &>(\n              _dof_handler.get_triangulation()));\n  triangulation.prepare_coarsening_and_refinement();\n  dealii::parallel::distributed::CellDataTransfer<\n      dim, dim, std::vector<dealii::Vector<double>>>\n      cell_data_trans(triangulation);\n  cell_data_trans.prepare_for_coarsening_and_refinement(data_to_transfer);\n  triangulation.execute_coarsening_and_refinement();\n\n  setup_dofs();\n\n  // Update MaterialProperty DoFHandler and resize the state vectors\n  _material_properties->reinit_dofs();\n\n  // Recompute the inverse of the mass matrix\n  compute_inverse_mass_matrix();\n\n  initialize_dof_vector(new_material_temperature, solution);\n  std::vector<dealii::Vector<double>> transferred_data(\n      triangulation.n_active_cells(), dealii::Vector<double>(dofs_per_cell));\n  cell_data_trans.unpack(transferred_data);\n\n  unsigned int cell_i = 0;\n  for (auto const &cell : _dof_handler.active_cell_iterators())\n  {\n    if ((cell->is_locally_owned()) && (transferred_data[cell_i][0] !=\n                                       std::numeric_limits<double>::infinity()))\n    {\n      cell->set_dof_values(transferred_data[cell_i], solution);\n    }\n    ++cell_i;\n  }\n\n  // Communicate the results.\n  solution.compress(dealii::VectorOperation::min);\n\n  // Set the value to the newly create DoFs. Here we need to be careful with the\n  // hanging nodes. When there is a hanging node, the dofs at the vertices are\n  // \"doubled\": there is a dof associated to the coarse cell and a dof\n  // associated to the fine cell. The final value is decided by\n  // AffineConstraints. Thus, we need to make sure that the newly activated\n  // cells are at the same level than their neighbors.\n  std::for_each(std::execution::par_unseq, solution.begin(), solution.end(),\n                [&](double &val) {\n                  if (val == std::numeric_limits<double>::infinity())\n                  {\n                    val = new_material_temperature;\n                  }\n                });\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ndouble ThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    evolve_one_time_step(\n        double t, double delta_t,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> &solution,\n        std::vector<Timer> &timers)\n{\n\n  // Update the height of the heat source. Right now this is just the\n  // maximum heat source height, which can lead to unexpected behavior for\n  // different sources with different heights.\n  double temp_height = std::numeric_limits<double>::lowest();\n  for (auto const &source : _heat_sources)\n  {\n    temp_height = std::max(temp_height, source->get_current_height(t));\n  }\n  _current_source_height = temp_height;\n\n  auto eval = [&](double const t, LA_Vector const &y) {\n    return evaluate_thermal_physics(t, y, timers);\n  };\n  auto id_m_Jinv = [&](double const t, double const tau, LA_Vector const &y) {\n    return id_minus_tau_J_inverse(t, tau, y, timers);\n  };\n\n  double time = _time_stepping->evolve_one_time_step(eval, id_m_Jinv, t,\n                                                     delta_t, solution);\n\n  // If the method is embedded, get the next time step. Otherwise, just use the\n  // current time step.\n  if (_embedded_method == false)\n    _delta_t_guess = delta_t;\n  else\n  {\n    dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector> *embedded_rk =\n        static_cast<\n            dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector> *>(\n            _time_stepping.get());\n    _delta_t_guess = embedded_rk->get_status().delta_t_guess;\n  }\n\n  // Return the time at the end of the time step. This may be different than\n  // t+delta_t for embedded methods.\n  return time;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    initialize_dof_vector(\n        dealii::LA::distributed::Vector<double, MemorySpaceType> &vector) const\n{\n  _thermal_operator->initialize_dof_vector(vector);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    initialize_dof_vector(\n        double const value,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> &vector) const\n{\n  // Resize the vector\n  _thermal_operator->initialize_dof_vector(vector);\n\n  init_dof_vector<dim, fe_degree, MemorySpaceType>(value, vector);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                    QuadratureType>::get_state_from_material_properties()\n{\n  _thermal_operator->get_state_from_material_properties();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                    QuadratureType>::set_state_to_material_properties()\n{\n  _thermal_operator->set_state_to_material_properties();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ndealii::LA::distributed::Vector<double, MemorySpaceType>\nThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    evaluate_thermal_physics(\n        double const t,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n        std::vector<Timer> &timers) const\n{\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_FUNCTION;\n#endif\n  if constexpr (std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value)\n  {\n    _thermal_operator->evaluate_material_properties(y);\n    return evaluate_thermal_physics_impl<dim, fe_degree, MemorySpaceType>(\n        _thermal_operator, t, _current_source_height, y, timers);\n  }\n  else\n  {\n    // TODO do this on the GPU\n    dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> y_host(\n        y.get_partitioner());\n    y_host.import(y, dealii::VectorOperation::insert);\n    _thermal_operator->evaluate_material_properties(y_host);\n    return evaluate_thermal_physics_impl<dim, fe_degree, MemorySpaceType>(\n        _thermal_operator, _fe_collection, t, _dof_handler, _heat_sources,\n        _current_source_height, _boundary_type, _material_properties,\n        _affine_constraints, y, timers);\n  }\n\n  // Dummy to silence warning\n  return dealii::LA::distributed::Vector<double, MemorySpaceType>();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ndealii::LA::distributed::Vector<double, MemorySpaceType>\nThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    id_minus_tau_J_inverse(\n        double const /*t*/, double const tau,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n        std::vector<Timer> &timers) const\n{\n  timers[evol_time_J_inv].start();\n  _implicit_operator->set_tau(tau);\n  dealii::LA::distributed::Vector<double, MemorySpaceType> solution(\n      y.get_partitioner());\n\n  // TODO Add a geometric multigrid preconditioner.\n  dealii::PreconditionIdentity preconditioner;\n\n  dealii::SolverControl solver_control(_max_iter, _tolerance * y.l2_norm());\n  // We need to inverse (I - tau M^{-1} J). While M^{-1} and J are SPD,\n  // (I - tau M^{-1} J) is symmetric indefinite in the general case.\n  typename dealii::SolverGMRES<\n      dealii::LA::distributed::Vector<double, MemorySpaceType>>::AdditionalData\n      additional_data(_max_n_tmp_vectors, _right_preconditioning);\n  dealii::SolverGMRES<dealii::LA::distributed::Vector<double, MemorySpaceType>>\n      solver(solver_control, additional_data);\n  solver.solve(*_implicit_operator, solution, y, preconditioner);\n\n  timers[evol_time_J_inv].stop();\n\n  return solution;\n}\n} // namespace adamantine\n\n#endif\n", "meta": {"hexsha": "4a098e9f874018e079a1f3028284d9f39d0022e9", "size": 31887, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/ThermalPhysics.templates.hh", "max_stars_repo_name": "Rombur/adamantine", "max_stars_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T02:08:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T01:26:41.000Z", "max_issues_repo_path": "source/ThermalPhysics.templates.hh", "max_issues_repo_name": "Rombur/adamantine", "max_issues_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74.0, "max_issues_repo_issues_event_min_datetime": "2016-08-31T18:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T01:51:44.000Z", "max_forks_repo_path": "source/ThermalPhysics.templates.hh", "max_forks_repo_name": "Rombur/adamantine", "max_forks_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-12T15:43:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T02:58:56.000Z", "avg_line_length": 38.8392204629, "max_line_length": 80, "alphanum_fraction": 0.6955812714, "num_tokens": 7753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.18016401282742028}}
{"text": "/*\n * do_learning.cpp\n *\n * incrementally learning of objects by\n * transfering object indices from initial cloud to the remaining clouds\n * using given camera poses\n *\n *  Created on: June, 2015\n *      Author: Thomas Faeulhammer\n */\n\n\n#ifndef EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\n#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\n#endif\n\n#include \"v4r/object_modelling/incremental_object_learning.h\"\n\n#include <stdlib.h>\n#include <thread>\n#include <iostream>\n\n#include <pcl/common/transforms.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/recognition/cg/geometric_consistency.h>\n#include <pcl/registration/correspondence_rejection_sample_consensus.h>\n#include <pcl/registration/icp.h>\n#include <pcl/registration/transformation_estimation_svd.h>\n#include <pcl/segmentation/supervoxel_clustering.h>\n\n#include <v4r/common/convertCloud.h>\n#include <v4r/common/convertNormals.h>\n#include <v4r/common/impl/DataMatrix2D.hpp>\n#include <v4r/registration/metrics.h>\n#include <v4r/common/binary_algorithms.h>\n#include <v4r/common/normals.h>\n#include <v4r/common/noise_models.h>\n#include <v4r/common/pcl_visualization_utils.h>\n#include <v4r/io/filesystem.h>\n#include <v4r/io/eigen.h>\n#include <v4r/common/zbuffering.h>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n#ifdef HAVE_SIFTGPU\n    #include <v4r/features/sift_local_estimator.h>\n#else\n    #include <v4r/features/opencv_sift_local_estimator.h>\n#endif\n\nnamespace v4r\n{\nnamespace object_modelling\n{\n\nbool\nIOL::calcSiftFeatures (const pcl::PointCloud<PointT> &cloud_src,\n                       pcl::PointCloud<PointT> &sift_keypoints,\n                       std::vector< size_t > &sift_keypoint_indices,\n                       std::vector<std::vector<float> > &sift_signatures,\n                       std::vector<float> &sift_keypoint_scales)\n{\n    std::vector<int> sift_kp_indices;\n\n#ifdef HAVE_SIFTGPU\n    (void) sift_keypoint_indices;\n    boost::shared_ptr < SIFTLocalEstimation<PointT> > estimator (new SIFTLocalEstimation<PointT>(sift_));\n    bool ret = estimator->estimate (cloud_src, sift_keypoints, sift_signatures, sift_keypoint_scales);\n    estimator->getKeypointIndices( sift_kp_indices );\n#else\n    (void)sift_keypoint_scales; //silences compiler warning of unused variable\n    boost::shared_ptr < OpenCVSIFTLocalEstimation<PointT> > estimator (new OpenCVSIFTLocalEstimation<PointT>);\n    pcl::PointCloud<PointT> processed_foo;\n    bool ret = estimator->estimate (cloud_src, processed_foo, sift_keypoints, sift_signatures);\n    estimator->getKeypointIndices( sift_kp_indices );\n#endif\n    sift_keypoint_indices = convertVecInt2VecSizet(sift_kp_indices);\n    return ret;\n}\n\nvoid\nIOL::estimateViewTransformationBySIFT(const pcl::PointCloud<PointT> &src_cloud,\n                                      const pcl::PointCloud<PointT> &dst_cloud,\n                                      const std::vector<size_t> &src_sift_keypoint_indices,\n                                      const std::vector<size_t> &dst_sift_keypoint_indices,\n                                      const std::vector<std::vector<float> > &src_sift_signatures,\n                                      boost::shared_ptr< flann::Index<DistT> > &dst_flann_index,\n                                      std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > &transformations,\n                                      bool use_gc )\n{\n    const int K = 1;\n    flann::Matrix<int> indices = flann::Matrix<int> ( new int[K], 1, K );\n    flann::Matrix<float> distances = flann::Matrix<float> ( new float[K], 1, K );\n\n    boost::shared_ptr< pcl::PointCloud<PointT> > pSiftKeypointsSrc (new pcl::PointCloud<PointT>);\n    boost::shared_ptr< pcl::PointCloud<PointT> > pSiftKeypointsDst (new pcl::PointCloud<PointT>);\n    pcl::copyPointCloud(src_cloud, src_sift_keypoint_indices, *pSiftKeypointsSrc );\n    pcl::copyPointCloud(dst_cloud, dst_sift_keypoint_indices, *pSiftKeypointsDst);\n\n    pcl::CorrespondencesPtr temp_correspondences ( new pcl::Correspondences );\n    temp_correspondences->resize(pSiftKeypointsSrc->size ());\n\n    for ( size_t keypointId = 0; keypointId < pSiftKeypointsSrc->points.size (); keypointId++ )\n    {\n        nearestKSearch ( dst_flann_index, src_sift_signatures[ keypointId ], K, indices, distances );\n\n        pcl::Correspondence corr;\n        corr.distance = distances[0][0];\n        corr.index_query = keypointId;\n        corr.index_match = indices[0][0];\n        temp_correspondences->at(keypointId) = corr;\n    }\n\n    if(!use_gc)\n    {\n        pcl::registration::CorrespondenceRejectorSampleConsensus<PointT>::Ptr rej;\n        rej.reset (new pcl::registration::CorrespondenceRejectorSampleConsensus<PointT> ());\n        pcl::CorrespondencesPtr after_rej_correspondences (new pcl::Correspondences ());\n\n        rej->setMaximumIterations (50000);\n        rej->setInlierThreshold (0.02);\n        rej->setInputTarget (pSiftKeypointsDst);\n        rej->setInputSource (pSiftKeypointsSrc);\n        rej->setInputCorrespondences (temp_correspondences);\n        rej->getCorrespondences (*after_rej_correspondences);\n\n        Eigen::Matrix4f refined_pose;\n        transformations.push_back( rej->getBestTransformation () );\n        pcl::registration::TransformationEstimationSVD<PointT, PointT> t_est;\n        t_est.estimateRigidTransformation (*pSiftKeypointsSrc, *pSiftKeypointsDst, *after_rej_correspondences, refined_pose);\n        transformations.back() = refined_pose;\n    }\n    else\n    {\n        std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > new_transforms;\n        pcl::GeometricConsistencyGrouping<PointT, PointT> gcg_alg;\n\n        gcg_alg.setGCThreshold (15);\n        gcg_alg.setGCSize (0.01);\n        gcg_alg.setInputCloud(pSiftKeypointsSrc);\n        gcg_alg.setSceneCloud(pSiftKeypointsDst);\n        gcg_alg.setModelSceneCorrespondences(temp_correspondences);\n\n        std::vector<pcl::Correspondences> clustered_corrs;\n        gcg_alg.recognize(new_transforms, clustered_corrs);\n        transformations.insert(transformations.end(), new_transforms.begin(), new_transforms.end());\n    }\n}\n\n\nstd::vector<bool>\nIOL::extractEuclideanClustersSmooth (\n        const pcl::PointCloud<PointT>::ConstPtr &cloud,\n        const pcl::PointCloud<pcl::Normal> &normals,\n        const std::vector<bool> &initial_mask,\n        const std::vector<bool> &bg_mask) const\n{\n    assert (cloud->points.size () == normals.points.size ());\n\n    pcl::octree::OctreePointCloudSearch<PointT> octree(0.005f);\n    octree.setInputCloud ( cloud );\n    octree.addPointsFromInputCloud ();\n\n    // Create a bool vector of processed point indices, and initialize it to false\n    std::vector<bool> to_grow = initial_mask;\n    std::vector<bool> in_cluster = initial_mask;\n\n    bool stop = false;\n    while(!stop)\n    {\n        stop = true;\n        std::vector<bool> is_new_point (cloud->points.size (), false);  // do as long as there is no new point\n        std::vector<int> nn_indices;\n        std::vector<float> nn_distances;\n\n        for (size_t i = 0; i < cloud->points.size (); i++)\n        {\n            if (!to_grow[i])\n                continue;\n\n            if (octree.radiusSearch (cloud->points[i], param_.radius_, nn_indices, nn_distances))\n            {\n                for (size_t j = 0; j < nn_indices.size (); j++) // is nn_indices[0] the same point?\n                {\n                    if( !in_cluster[ nn_indices[j] ] && !bg_mask[ nn_indices[j] ])  // if nearest neighbor is not already an object and is not a point to be neglected (background)\n                    {\n                        //check smoothness constraint\n                        Eigen::Vector3f n1 = normals.points[i].getNormalVector3fMap();\n                        Eigen::Vector3f n2 = normals.points[nn_indices[j]].getNormalVector3fMap();\n                        n1.normalize();\n                        n2.normalize();\n                        float dot_p = n1.dot(n2);\n\n                        if (dot_p >= param_.eps_angle_)\n                        {\n                            stop = false;\n                            is_new_point[ nn_indices[j] ] = true;\n                            in_cluster[ nn_indices[j] ] = true;\n                        }\n                    }\n                }\n            }\n        }\n        to_grow = is_new_point;\n    }\n    return in_cluster;\n}\n\nvoid\nIOL::updatePointNormalsFromSuperVoxels(const pcl::PointCloud<PointT>::Ptr & cloud,\n                                            pcl::PointCloud<pcl::Normal>::Ptr & normals,\n                                            const std::vector<bool> &obj_mask,\n                                            std::vector<bool> &obj_mask_out,\n                                            pcl::PointCloud<pcl::PointXYZRGBA>::Ptr &supervoxel_cloud,\n                                            pcl::PointCloud<pcl::PointXYZRGBA>::Ptr &supervoxel_cloud_organized)\n{\n    assert( cloud->points.size() == normals->points.size() &&\n            cloud->points.size() == obj_mask.size());\n\n    pcl::SupervoxelClustering<PointT> super (param_.voxel_resolution_, param_.seed_resolution_, false);\n    super.setInputCloud (cloud);\n    super.setColorImportance (0.f);\n    super.setSpatialImportance (0.5f);\n    super.setNormalImportance (2.f);\n    super.setNormalCloud(normals);\n    std::map <uint32_t, pcl::Supervoxel<PointT>::Ptr > supervoxel_clusters;\n    super.extract (supervoxel_clusters);\n    super.refineSupervoxels(2, supervoxel_clusters);\n    supervoxel_cloud = super.getColoredVoxelCloud();\n    supervoxel_cloud_organized = super.getColoredCloud();\n    const pcl::PointCloud<pcl::PointXYZL>::Ptr supervoxels_labels_cloud = super.getLabeledCloud();\n\n    std::cout << \"Found \" << supervoxel_clusters.size () << \" supervoxels.\" << std::endl;\n\n    const size_t max_label = super.getMaxLabel();\n//    const pcl::PointCloud<pcl::PointNormal>::Ptr sv_normal_cloud = super.makeSupervoxelNormalCloud (supervoxel_clusters);\n\n//    //count for all labels how many pixels are in the initial indices\n    std::vector<size_t> label_count (max_label+1, 0);\n\n    for(size_t i = 0; i < supervoxels_labels_cloud->points.size(); i++)\n    {\n        const size_t label = static_cast<size_t>(supervoxels_labels_cloud->points[i].label);\n        label_count[ label ]++;\n    }\n\n    obj_mask_out.resize(cloud->points.size());\n\n    for(size_t i = 0; i < cloud->points.size(); i++)\n    {\n        const size_t label = supervoxels_labels_cloud->points[i].label;\n        assert(label<label_count.size());\n\n        if ( !obj_mask[i] || !pcl::isFinite(cloud->points[i]))\n        {\n            obj_mask_out[i] = false;\n            continue;\n        }\n\n        if( obj_mask[i] && label==0)    // label 0 means the point could not be associated to any supervoxel (see supervoxelclustering doc) - we will pass this point therefore by definition\n        {\n            obj_mask_out[i] = true;\n            continue;\n        }\n\n        std::map <uint32_t, pcl::Supervoxel<PointT>::Ptr >::const_iterator it = supervoxel_clusters.find(label);\n        if (it != supervoxel_clusters.end())\n        {\n//            // refine normals\n            const Eigen::Vector3f sv_normal = it->second->normal_.getNormalVector3fMap();\n            normals->points[i].getNormalVector3fMap() = sv_normal;\n\n            const size_t tot_pts_in_supervoxel = it->second->voxels_->points.size();\n            if( label_count[label]  > param_.ratio_supervoxel_ * tot_pts_in_supervoxel)\n                obj_mask_out[i] = true;\n            else\n                obj_mask_out[i] = false;\n        }\n        else\n        {\n            std::cerr << \"Cluster for label does not exist\" << std::endl;\n            obj_mask_out[i] = true;\n        }\n    }\n}\n\nvoid\nIOL::nnSearch(const pcl::PointCloud<PointT> &object_points, const pcl::PointCloud<PointT>::ConstPtr &search_cloud,  std::vector<bool> &obj_mask)\n{\n    pcl::octree::OctreePointCloudSearch<PointT> octree(0.005f);\n    octree.setInputCloud ( search_cloud );\n    octree.addPointsFromInputCloud ();\n    nnSearch(object_points, octree, obj_mask);\n}\n\nvoid\nIOL::nnSearch(const pcl::PointCloud<PointT> &object_points, pcl::octree::OctreePointCloudSearch<PointT> &octree,  std::vector<bool> &obj_mask)\n{\n    //find neighbours from transferred object points\n    std::vector<int> pointIdxRadiusSearch;\n    std::vector<float> pointRadiusSquaredDistance;\n\n    for(size_t i=0; i < object_points.points.size(); i++)\n    {\n        if ( ! pcl::isFinite(object_points.points[i]) )\n        {\n            PCL_WARN (\"Warning: Point is NaN.\\n\");    // not sure if this causes somewhere else a problem. This condition should not be fulfilled.\n            continue;\n        }\n        if ( octree.radiusSearch (object_points.points[i], param_.radius_, pointIdxRadiusSearch, pointRadiusSquaredDistance) > 0)\n        {\n            for( size_t nn_id = 0; nn_id < pointIdxRadiusSearch.size(); nn_id++)\n                obj_mask[ pointIdxRadiusSearch[ nn_id ] ] = true;\n        }\n    }\n}\n\nstd::vector<bool>\nIOL::erodeIndices(const std::vector< bool > &obj_mask, const pcl::PointCloud<PointT> & cloud)\n{\n    assert (obj_mask.size() == cloud.height * cloud.width);\n\n    cv::Mat mask = cv::Mat(cloud.height, cloud.width, CV_8UC1);\n    std::vector<bool> mask_out(obj_mask.size());\n\n    for(size_t i=0; i < obj_mask.size(); i++)\n    {\n        int r,c;\n        r = i / mask.cols;\n        c = i % mask.cols;\n\n        if (obj_mask[i])\n            mask.at<unsigned char>(r,c) = 255;\n        else\n            mask.at<unsigned char>(r,c) = 0;\n    }\n\n    cv::Mat const structure_elem = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5));\n    cv::Mat close_result;\n    cv::morphologyEx(mask, close_result, cv::MORPH_CLOSE, structure_elem);\n\n    cv::Mat mask_dst;\n    cv::erode(close_result, mask_dst, cv::Mat(), cv::Point(-1,-1), 3);\n\n    //        cv::imshow(\"mask\", mask);\n    //        cv::imshow(\"close_result\", close_result);\n    //        cv::imshow(\"mask_dst\", mask_dst);\n    //        cv::waitKey(0);\n\n    for(int r=0; r < mask_dst.rows; r++)\n    {\n        for(int c=0; c< mask_dst.cols; c++)\n        {\n            const int idx = r * mask_dst.cols + c;\n\n            if (mask_dst.at<unsigned char>(r,c) > 0 && pcl::isFinite( cloud.points[idx] ) && cloud.points[idx].z < param_.chop_z_)\n                mask_out[idx] = true;\n            else\n                mask_out[idx] = false;\n        }\n    }\n    return mask_out;\n}\n\nbool\nIOL::write_model_to_disk (const std::string &models_dir, const std::string &model_name, bool save_views)\n{\n    const std::string export_to = models_dir + \"/\" + model_name;\n    io::createDirIfNotExist(export_to);\n    pcl::io::savePCDFileBinary(export_to + \"/3D_model.pcd\", *cloud_normals_oriented_);\n\n    if (save_views) //save recognition data with new poses\n    {\n        io::createDirIfNotExist(export_to + \"/views\");\n\n        for(size_t i=0; i < keyframes_used_.size(); i++)\n        {\n            std::stringstream view_file;\n            view_file << export_to << \"/views/cloud_\" << setfill('0') << setw(8) << i << \".pcd\";\n            pcl::io::savePCDFileBinary (view_file.str (), *keyframes_used_[i]);\n            std::cout << view_file.str() << std::endl;\n\n            std::string path_pose (view_file.str());\n            boost::replace_last (path_pose, \"cloud_\", \"pose_\");\n            boost::replace_last (path_pose, \".pcd\", \".txt\");\n            io::writeMatrixToFile(path_pose, cameras_used_[i]);\n            std::cout << path_pose << std::endl;\n\n            std::string path_obj_indices (view_file.str());\n            boost::replace_last (path_obj_indices, \"cloud_\", \"object_indices_\");\n            boost::replace_last (path_obj_indices, \".pcd\", \".txt\");\n\n            std::ofstream mask_f (path_obj_indices);\n            for(const auto &idx : object_indices_clouds_used_[i])\n                mask_f << idx << std::endl;\n            mask_f.close();\n        }\n    }\n    return true;\n}\n\n\nbool\nIOL::save_model (const std::string &models_dir, const std::string &model_name, bool save_individual_views)\n{\n    size_t num_frames = grph_.size();\n\n    std::vector< pcl::PointCloud<pcl::Normal>::Ptr > normals_used (num_frames);\n    keyframes_used_.resize(num_frames);\n    cameras_used_.resize(num_frames);\n    object_indices_clouds_used_.resize(num_frames);\n\n    // only used keyframes with have object points in them\n    size_t kept_keyframes=0;\n    for (size_t view_id = 0; view_id < grph_.size(); view_id++)\n    {\n        if ( createIndicesFromMask<size_t>(grph_[view_id].obj_mask_step_.back()).size() )\n        {\n            keyframes_used_[ kept_keyframes ] = grph_[view_id].cloud_;\n            normals_used [ kept_keyframes ] = grph_[view_id].normal_;\n            cameras_used_ [ kept_keyframes ] = grph_[view_id].camera_pose_;\n            object_indices_clouds_used_[ kept_keyframes ] = createIndicesFromMask<size_t>( grph_[view_id].obj_mask_step_.back() );\n            kept_keyframes++;\n        }\n    }\n\n    keyframes_used_.resize(kept_keyframes);\n    normals_used.resize(kept_keyframes);\n    cameras_used_.resize(kept_keyframes);\n    object_indices_clouds_used_.resize(kept_keyframes);\n    std::vector<std::vector<std::vector<float> > > pt_properties (kept_keyframes);\n\n    if ( kept_keyframes > 0)\n    {\n        //compute noise weights\n        for(size_t i=0; i < kept_keyframes; i++)\n        {\n            NguyenNoiseModel<PointT>::Parameter nm_param;\n            nm_param.use_depth_edges_ = true;\n            NguyenNoiseModel<PointT> nm (nm_param);\n            nm.setInputCloud(keyframes_used_[i]);\n            nm.setInputNormals(normals_used[i]);\n            nm.compute();\n            pt_properties[i] = nm.getPointProperties();\n        }\n\n        pcl::PointCloud<PointT>::Ptr octree_cloud(new pcl::PointCloud<PointT>);\n        NMBasedCloudIntegration<PointT> nmIntegration (nm_int_param_);\n        nmIntegration.setInputClouds(keyframes_used_);\n        nmIntegration.setTransformations(cameras_used_);\n        nmIntegration.setInputNormals(normals_used);\n        nmIntegration.setIndices( object_indices_clouds_used_ );\n        nmIntegration.setPointProperties( pt_properties );\n        nmIntegration.compute(octree_cloud);\n\n        pcl::PointCloud<pcl::Normal>::Ptr octree_normals;\n        nmIntegration.getOutputNormals(octree_normals);\n\n        pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr filtered_with_normals_oriented (new pcl::PointCloud<pcl::PointXYZRGBNormal>());\n        pcl::concatenateFields(*octree_normals, *octree_cloud, *filtered_with_normals_oriented);\n\n        pcl::StatisticalOutlierRemoval<pcl::PointXYZRGBNormal> sor;\n        sor.setInputCloud (filtered_with_normals_oriented);\n        sor.setMeanK (50);\n        sor.setStddevMulThresh (3.0);\n        sor.filter (*cloud_normals_oriented_);\n\n        std::cout << \"Saving \" << kept_keyframes << \" keyframes from \" << num_frames << \" to \" << models_dir << std::endl;\n        write_model_to_disk(models_dir, model_name, save_individual_views);\n    }\n    return true;\n}\n\nvoid\nIOL::extractPlanePoints(const pcl::PointCloud<PointT>::ConstPtr &cloud,\n                             const pcl::PointCloud<pcl::Normal>::ConstPtr &normals,\n                             std::vector<ClusterNormalsToPlanes::Plane::Ptr> &planes)\n{\n    ClusterNormalsToPlanes pest(p_param_);\n    DataMatrix2D<Eigen::Vector3f>::Ptr kp_cloud( new DataMatrix2D<Eigen::Vector3f>() );\n    DataMatrix2D<Eigen::Vector3f>::Ptr kp_normals( new DataMatrix2D<Eigen::Vector3f>() );\n    convertCloud(*cloud, *kp_cloud);\n    convertNormals(*normals, *kp_normals);\n\n    std::vector<ClusterNormalsToPlanes::Plane::Ptr> all_planes;\n    pest.compute(*kp_cloud, *kp_normals, all_planes);\n    planes.resize(all_planes.size());\n    size_t kept=0;\n    for (size_t cluster_id=0; cluster_id<all_planes.size(); cluster_id++)\n    {\n        float min_z = std::numeric_limits<float>::max();\n        for(size_t cluster_pt_id=0; cluster_pt_id<all_planes[cluster_id]->indices.size(); cluster_pt_id++)\n        {\n            const int id = all_planes[cluster_id]->indices[cluster_pt_id];\n            if ( cloud->points[id].z < min_z ) // do not consider points that are further away than a certain threshold\n                min_z = cloud->points[id].z;\n        }\n        if(min_z < param_.chop_z_)\n        {\n            planes[kept] = all_planes[cluster_id];\n            kept++;\n        }\n    }\n    planes.resize(kept);\n}\n\nbool\nIOL::merging_planes_reasonable(const modelView::SuperPlane &sp1, const modelView::SuperPlane &sp2) const\n{\n    float dist = std::abs(PlaneEstimationRANSAC::normalPointDist(sp1.pt, sp1.normal, sp2.pt));\n    float dot  = sp1.normal.dot(sp2.normal);\n//    std::cout << \"dist: \" << dist << \", dot: \" << dot << std::endl;\n    return (dist < 2 * p_param_.inlDist && dot > 0.95);\n}\n\nvoid\nIOL::computePlaneProperties(const std::vector<ClusterNormalsToPlanes::Plane::Ptr> &planes,\n                                       const std::vector< bool > &object_mask,\n                                       const std::vector< bool > &occlusion_mask,\n                                       const pcl::PointCloud<PointT>::ConstPtr &cloud,\n                                       std::vector<modelView::SuperPlane> &super_planes) const\n{\n//    planes_not_on_object.resize(planes.size());\n    super_planes.resize(planes.size());\n\n//    size_t kept=0;\n    for(size_t cluster_id=0; cluster_id<planes.size(); cluster_id++)\n    {\n        super_planes[cluster_id].pt = planes[cluster_id]->pt;\n        super_planes[cluster_id].normal = planes[cluster_id]->normal;\n        super_planes[cluster_id].is_plane = planes[cluster_id]->is_plane;\n        super_planes[cluster_id].indices = planes[cluster_id]->indices;\n        super_planes[cluster_id].visible_indices.resize( planes[cluster_id]->indices.size() );\n        super_planes[cluster_id].object_indices.resize( planes[cluster_id]->indices.size() );\n        super_planes[cluster_id].within_chop_z_indices.resize( planes[cluster_id]->indices.size() );\n\n        size_t num_obj_pts = 0;\n        size_t num_occluded_pts = 0;\n        size_t num_plane_pts = 0;\n\n        for (size_t cluster_pt_id=0; cluster_pt_id<planes[cluster_id]->indices.size(); cluster_pt_id++)\n        {\n            const int id = planes[cluster_id]->indices[cluster_pt_id];\n            if ( cloud->points[id].z < param_.chop_z_ )\n            {\n                super_planes[cluster_id].within_chop_z_indices[ num_plane_pts++ ] = id;\n\n                if ( object_mask[id] )\n                     super_planes[cluster_id].object_indices[ num_obj_pts++ ] = id;\n\n                if( !occlusion_mask[id] )\n                    super_planes[cluster_id].visible_indices[ num_occluded_pts++ ] = id;\n\n            }\n        }\n        super_planes[cluster_id].visible_indices.resize( num_occluded_pts );\n        super_planes[cluster_id].object_indices.resize( num_obj_pts );\n        super_planes[cluster_id].within_chop_z_indices.resize( num_plane_pts );\n\n\n//        if ( num_plane_pts == 0 ||\n//             ( (double)num_obj_pts/num_plane_pts < param_.ratio_cluster_obj_supported_ && (double)num_occluded_pts/num_plane_pts < param_.ratio_cluster_occluded_) )\n//        {\n//            planes_not_on_object[kept] = planes[cluster_id];\n//            kept++;\n//        }\n    }\n//    planes_not_on_object.resize(kept);\n}\n\nvoid\nIOL::computeAbsolutePosesRecursive (const Graph & grph,\n                              const Vertex start,\n                              const Eigen::Matrix4f &accum,\n                              std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > & absolute_poses,\n                              std::vector<bool> &hop_list)\n{\n    boost::property_map<Graph, boost::edge_weight_t>::type weightmap = boost::get(boost::edge_weight, gs_);\n    boost::graph_traits<Graph>::out_edge_iterator ei, ei_end;\n    for (boost::tie (ei, ei_end) = boost::out_edges (start, grph); ei != ei_end; ++ei)\n    {\n        Vertex targ = boost::target (*ei, grph);\n        size_t target_id = boost::target (*ei, grph);\n\n        if(hop_list[target_id])\n           continue;\n\n        hop_list[target_id] = true;\n        CamConnect my_e = weightmap[*ei];\n        Eigen::Matrix4f intern_accum;\n        Eigen::Matrix4f trans = my_e.transformation_;\n        if( my_e.target_id_ != target_id)\n        {\n            Eigen::Matrix4f trans_inv;\n            trans_inv = trans.inverse();\n            trans = trans_inv;\n        }\n        intern_accum = accum * trans;\n        absolute_poses[target_id] = intern_accum;\n        computeAbsolutePosesRecursive (grph, targ, intern_accum, absolute_poses, hop_list);\n    }\n}\n\nvoid\nIOL::computeAbsolutePoses (const Graph & grph,\n                     std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > & absolute_poses)\n{\n  size_t num_frames = boost::num_vertices(grph);\n  absolute_poses.resize( num_frames );\n  std::vector<bool> hop_list (num_frames, false);\n  Vertex source_view = 0;\n  hop_list[0] = true;\n  Eigen::Matrix4f accum = grph_[0].tracking_pose_;      // CAN IT ALSO BE grph[0] instead of class member?\n  absolute_poses[0] = accum;\n  computeAbsolutePosesRecursive (grph, source_view, accum, absolute_poses, hop_list);\n}\n\nbool\nIOL::learn_object (const pcl::PointCloud<PointT> &cloud, const Eigen::Matrix4f &camera_pose, const std::vector<size_t> &initial_indices)\n{\n    size_t id = grph_.size();\n    std::cout << \"Computing indices for cloud \" << id << std::endl\n              << \"===================================\" << std::endl;\n    grph_.resize(id + 1);\n    modelView& view = grph_.back();\n    pcl::copyPointCloud(cloud, *(view.cloud_));\n    view.id_ = id;\n    view.tracking_pose_ = camera_pose; //common::RotTrans2Mat4f(cloud.sensor_orientation_, cloud.sensor_origin_);\n    view.tracking_pose_set_ = true;\n    view.camera_pose_ = view.tracking_pose_;\n\n    boost::add_vertex(view.id_, gs_);\n\n    pcl::PointCloud<pcl::Normal>::Ptr normals_filtered (new pcl::PointCloud<pcl::Normal>());\n    std::vector<ClusterNormalsToPlanes::Plane::Ptr> planes;\n\n    computeNormals<PointT>(view.cloud_, view.normal_, param_.normal_method_);\n    extractPlanePoints(view.cloud_, view.normal_, planes);\n\n    octree_.setInputCloud ( view.cloud_ );\n    octree_.addPointsFromInputCloud ();\n\n    boost::shared_ptr<flann::Index<DistT> > flann_index;\n\n    if ( param_.do_sift_based_camera_pose_estimation_ )\n    {\n        pcl::PointCloud<PointT> sift_keypoints;\n        std::vector<float> sift_keypoint_scales;\n        try\n        {\n            calcSiftFeatures( *view.cloud_, sift_keypoints, view.sift_keypoint_indices_, view.sift_signatures_, sift_keypoint_scales);\n            convertToFLANN<DistT>(view.sift_signatures_, flann_index );\n        }\n        catch (int e)\n        {\n            param_.do_sift_based_camera_pose_estimation_ = false;\n            std::cerr << \"Something is wrong with the SIFT based camera pose estimation. Turning it off and using the given camera poses only.\" << std::endl;\n        }\n    }\n\n    if (initial_indices.size())   // for first frame use given initial indices and erode them\n    {\n        std::vector<bool> initial_mask = createMaskFromIndices(initial_indices, view.cloud_->points.size());\n        remove_nan_points(*view.cloud_, initial_mask);\n        view.obj_mask_step_.push_back( initial_mask );\n        view.is_pre_labelled_ = true;\n\n        // remove nan values and points further away than chop_z_ parameter\n        std::vector<size_t> initial_indices_wo_nan (initial_indices.size());\n        size_t kept=0;\n        for(size_t idx=0; idx<initial_indices.size(); idx++)\n        {\n            if ( pcl::isFinite( view.cloud_->points[initial_indices[idx]]) && view.cloud_->points[initial_indices[idx]].z < param_.chop_z_)\n            {\n                initial_indices_wo_nan[kept] = initial_indices[idx];\n                kept++;\n            }\n        }\n        initial_indices_wo_nan.resize(kept);\n\n        //erode mask\n        pcl::PointCloud<PointT>::Ptr cloud_filtered (new pcl::PointCloud<PointT>());\n        boost::shared_ptr <std::vector<int> > ObjectIndicesPtr (new std::vector<int>());\n        boost::shared_ptr <const std::vector<int> > FilteredObjectIndicesPtr (new std::vector<int>());\n\n        *ObjectIndicesPtr = convertVecSizet2VecInt(initial_indices_wo_nan);\n\n        pcl::copyPointCloud(*view.cloud_, initial_indices_wo_nan, *cloud_filtered);\n        pcl::StatisticalOutlierRemoval<PointT> sor(true);\n        sor.setInputCloud (view.cloud_);\n        sor.setIndices(ObjectIndicesPtr);\n        sor.setMeanK (sor_params_.meanK_);\n        sor.setStddevMulThresh (sor_params_.std_mul_);\n        sor.filter (*cloud_filtered);\n        FilteredObjectIndicesPtr = sor.getRemovedIndices();\n\n        const std::vector<bool> obj_mask_initial = createMaskFromIndices(initial_indices_wo_nan, view.cloud_->points.size());\n        const std::vector<bool> outlier_mask = createMaskFromIndices(*FilteredObjectIndicesPtr, view.cloud_->points.size());\n        const std::vector<bool> obj_mask_wo_outlier = binary_operation(obj_mask_initial, outlier_mask, BINARY_OPERATOR::AND_N);\n\n        view.obj_mask_step_.push_back( obj_mask_wo_outlier);\n\n        std::vector<bool> obj_mask_eroded = erodeIndices(obj_mask_wo_outlier, *view.cloud_);\n        view.obj_mask_step_.push_back( obj_mask_eroded );\n        computePlaneProperties(planes, view.obj_mask_step_[0],\n                               std::vector<bool>(view.cloud_->points.size(), false),\n                               view.cloud_, view.planes_);\n    }\n    else\n    {\n        if ( param_.do_sift_based_camera_pose_estimation_ )\n        {\n            for (size_t view_id = 0; view_id < grph_.size(); view_id++)\n            {\n                if( view.id_ == grph_[view_id].id_)\n                    continue;\n\n                std::vector<CamConnect> transforms;\n                CamConnect edge;\n                edge.model_name_ = \"camera_tracking\";\n                edge.source_id_ = view.id_;\n                edge.target_id_ = grph_[view_id].id_;\n                edge.transformation_ = view.tracking_pose_.inverse() * grph_[view_id].tracking_pose_ ;\n                transforms.push_back( edge );\n\n                try\n                {\n                    edge.model_name_ = \"sift_background_matching\";\n                    std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > sift_transforms;\n                    estimateViewTransformationBySIFT( *grph_[view_id].cloud_, *view.cloud_,\n                                                      grph_[view_id].sift_keypoint_indices_, view.sift_keypoint_indices_,\n                                                      grph_[view_id].sift_signatures_, flann_index, sift_transforms);\n                    for(size_t sift_tf_id = 0; sift_tf_id < sift_transforms.size(); sift_tf_id++)\n                    {\n                        edge.transformation_ = sift_transforms[sift_tf_id];\n                        transforms.push_back(edge);\n                    }\n                }\n                catch (int e)\n                {\n                    param_.do_sift_based_camera_pose_estimation_ = false;\n                    std::cerr << \"Something is wrong with the SIFT based camera pose estimation. Turning it off and using the given camera poses only.\" << std::endl;\n                }\n\n                size_t best_transform_id = 0;\n                float lowest_edge_weight = std::numeric_limits<float>::max();\n                for ( size_t trans_id = 0; trans_id < transforms.size(); trans_id++ )\n                {\n                    try\n                    {\n                        Eigen::Matrix4f icp_refined_trans;\n                        v4r::calcEdgeWeightAndRefineTf<PointT>( grph_[view_id].cloud_, view.cloud_, transforms[ trans_id ].transformation_, transforms[ trans_id ].edge_weight, icp_refined_trans);\n                        transforms[ trans_id ].transformation_ = icp_refined_trans,\n                        std::cout << \"Edge weight is \" << transforms[ trans_id ].edge_weight << \" for edge connecting vertex \" <<\n                                     transforms[ trans_id ].source_id_ << \" and \" << transforms[ trans_id ].target_id_ << \" by \" <<\n                                     transforms[ trans_id ].model_name_ << std::endl;\n\n                        if(transforms[ trans_id ].edge_weight < lowest_edge_weight)\n                        {\n                            lowest_edge_weight = transforms[ trans_id ].edge_weight;\n                            best_transform_id = trans_id;\n                        }\n                    }\n                    catch (int e)\n                    {\n                        transforms[ trans_id ].edge_weight = std::numeric_limits<float>::max();\n                        param_.do_sift_based_camera_pose_estimation_ = false;\n                        std::cerr << \"Something is wrong with the SIFT based camera pose estimation. Turning it off and using the given camera poses only.\" << std::endl;\n                        break;\n                    }\n                }\n                boost::add_edge (transforms[best_transform_id].source_id_, transforms[best_transform_id].target_id_, transforms[best_transform_id], gs_);\n\n                boost::property_map<Graph, boost::edge_weight_t>::type weightmap = boost::get(boost::edge_weight, gs_);\n                std::vector < Edge > spanning_tree;\n                boost::kruskal_minimum_spanning_tree(gs_, std::back_inserter(spanning_tree));\n\n                Graph grph_mst;\n                std::cout << \"Print the edges in the MST:\" << std::endl;\n                for (std::vector < Edge >::iterator ei = spanning_tree.begin(); ei != spanning_tree.end(); ++ei)\n                {\n                    CamConnect my_e = weightmap[*ei];\n                    std::cout << \"[\" << source(*ei, gs_) << \"->\" << target(*ei, gs_) << \"] with weight \" << my_e.edge_weight << \" by \" << my_e.model_name_ << std::endl;\n                    boost::add_edge(source(*ei, gs_), target(*ei, gs_), weightmap[*ei], grph_mst);\n                }\n\n                std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > absolute_poses;\n                computeAbsolutePoses(grph_mst, absolute_poses);\n\n                for(size_t v_id=0; v_id<absolute_poses.size(); v_id++)\n                {\n                    grph_[ v_id ].camera_pose_ = absolute_poses [ v_id ];\n                }\n            }\n        }\n\n        std::vector<bool> is_occluded;\n        for (size_t view_id = 0; view_id < grph_.size(); view_id++)\n        {\n            if( view.id_ != grph_[view_id].id_)\n            {\n                pcl::PointCloud<PointT>::Ptr new_search_pts, new_search_pts_aligned;\n                new_search_pts.reset(new pcl::PointCloud<PointT>());\n                new_search_pts_aligned.reset(new pcl::PointCloud<PointT>());\n                pcl::copyPointCloud(*grph_[view_id].cloud_, grph_[view_id].obj_mask_step_.back(), *new_search_pts);\n                const Eigen::Matrix4f tf = view.camera_pose_.inverse() * grph_[view_id].camera_pose_;\n                pcl::transformPointCloud(*new_search_pts, *new_search_pts_aligned, tf);\n\n                pcl::IterativeClosestPoint<PointT, PointT> icp;\n                icp.setInputSource(new_search_pts_aligned);\n                icp.setInputTarget(view.cloud_);\n                icp.setMaxCorrespondenceDistance (0.02f);\n                pcl::PointCloud<PointT>::Ptr icp_aligned_cloud (new pcl::PointCloud<PointT>());\n                icp.align(*icp_aligned_cloud, Eigen::Matrix4f::Identity());\n                *view.transferred_cluster_ += *icp_aligned_cloud;\n\n                if (grph_[view_id].is_pre_labelled_)\n                {\n                    std::vector<bool> is_occluded_tmp = computeOccludedPoints(*grph_[view_id].cloud_,\n                                                                                                   *view.cloud_,\n                                                                                                   tf.inverse(),\n                                                                                                        525.f, 0.01f, false);\n                    if( is_occluded.size() == is_occluded_tmp.size())\n                    {\n                        is_occluded = binary_operation(is_occluded, is_occluded_tmp, BINARY_OPERATOR::AND); // is this correct?\n                    }\n                    else\n                    {\n                        is_occluded = is_occluded_tmp;\n                    }\n                }\n            }\n        }\n\n        std::vector<bool> obj_mask_nn_search (view.cloud_->points.size(), false);\n        nnSearch(*view.transferred_cluster_, octree_, obj_mask_nn_search);\n        view.obj_mask_step_.push_back( obj_mask_nn_search);\n\n        computePlaneProperties(planes, obj_mask_nn_search, is_occluded,\n                               view.cloud_, view.planes_);\n    }\n    std::vector<bool> pixel_is_object = view.obj_mask_step_.back();\n\n    // filter cloud based on planes not on object and not occluded in first frame\n    std::vector<bool> pixel_is_neglected (view.cloud_->points.size(), false);\n    for (size_t p_id=0; p_id<view.planes_.size(); p_id++)\n    {\n        for (size_t view_id = 0; view_id < grph_.size(); view_id++)\n        {\n            if( view.id_ != grph_[view_id].id_)\n            {\n                for (size_t p2_id=0; p2_id<grph_[view_id].planes_.size(); p2_id++)\n                {\n//                    std::cout << \"Checking cluster new \" << p_id << \" and cluster old \" <<\n//                                 p2_id << \" from view \" << view_id << std::endl;\n//                    std::cout << merging_planes_reasonable(view.planes_[p_id], grph_[view_id].planes_[p2_id]) << std::endl;\n\n                    // if the planes can be merged (based on normals and distance), then filter new plane if old one has been filtered\n                    if (grph_[view_id].planes_[p2_id].is_filtered && merging_planes_reasonable(view.planes_[p_id], grph_[view_id].planes_[p2_id]) && !plane_has_object(view.planes_[p_id]))\n                        view.planes_[p_id].is_filtered = true;\n                }\n            }\n        }\n        if ( plane_is_filtered( view.planes_[p_id] ) )\n            view.planes_[p_id].is_filtered = true;\n\n        if ( view.planes_[p_id].is_filtered )\n        {\n            for (size_t c_pt_id=0; c_pt_id < view.planes_[p_id].indices.size(); c_pt_id++)\n                pixel_is_neglected [ view.planes_[p_id].indices[ c_pt_id ] ] = true;\n        }\n    }\n    for(size_t pt=0; pt<view.cloud_->points.size(); pt++)\n    {\n        if (view.cloud_->points[pt].z > param_.chop_z_)\n            pixel_is_neglected[pt] = true;\n    }\n\n    view.scene_points_ = createIndicesFromMask<size_t>(pixel_is_neglected, true);\n    view.obj_mask_step_.push_back( binary_operation(pixel_is_object, pixel_is_neglected, BINARY_OPERATOR::AND_N) );\n    pcl::copyPointCloud(*view.normal_, view.scene_points_, *normals_filtered);\n\n    std::vector<bool> obj_mask_enforced_by_supervoxel_consistency;\n    updatePointNormalsFromSuperVoxels(view.cloud_,\n                                      view.normal_,\n                                      view.obj_mask_step_.back(),\n                                      obj_mask_enforced_by_supervoxel_consistency,\n                                      view.supervoxel_cloud_,\n                                      view.supervoxel_cloud_organized_);\n    view.obj_mask_step_.push_back( obj_mask_enforced_by_supervoxel_consistency );\n\n    std::vector<bool> obj_mask_grown_by_smooth_surface = extractEuclideanClustersSmooth(view.cloud_,\n                                                                                           *view.normal_,\n                                                                                           obj_mask_enforced_by_supervoxel_consistency,\n                                                                                           pixel_is_neglected);\n    view.obj_mask_step_.push_back(obj_mask_grown_by_smooth_surface);\n\n    std::vector<bool> obj_mask_eroded = erodeIndices(obj_mask_grown_by_smooth_surface, *view.cloud_);\n    remove_nan_points(*view.cloud_, obj_mask_eroded);\n    view.obj_mask_step_.push_back( obj_mask_eroded );\n\n    for( size_t step_id = 0; step_id<view.obj_mask_step_.size(); step_id++)\n    {\n        std::cout << \"step \" << step_id << \": \" << createIndicesFromMask<size_t>(view.obj_mask_step_[step_id]).size() << \" points.\" << std::endl;\n    }\n\n    if( view.is_pre_labelled_ && createIndicesFromMask<size_t>(view.obj_mask_step_.back()).size() < param_.min_points_for_transferring_)\n    {\n        view.obj_mask_step_.back() = view.obj_mask_step_[0];\n        std::cout << \"After postprocessing the initial frame not enough points are left. Therefore taking the original provided indices.\" << std::endl;\n    }\n//    visualize();\n    return true;\n}\n\nvoid\nIOL::initSIFT ()\n{\n    if (param_.do_sift_based_camera_pose_estimation_)\n    {\n#ifdef HAVE_SIFTGPU\n        //-----Init-SIFT-GPU-Context--------\n        static char kw[][16] = {\"-m\", \"-fo\", \"-1\", \"-s\", \"-v\", \"1\", \"-pack\"};\n        char * argvv[] = {kw[0], kw[1], kw[2], kw[3],kw[4],kw[5],kw[6], NULL};\n\n        int argcc = sizeof(argvv) / sizeof(char*);\n        sift_.reset( new SiftGPU () );\n        sift_->ParseParam (argcc, argvv);\n\n        //create an OpenGL context for computation\n        if (sift_->CreateContextGL () != SiftGPU::SIFTGPU_FULL_SUPPORTED)\n            throw std::runtime_error (\"PSiftGPU::PSiftGPU: No GL support!\");\n#endif\n    }\n}\n\nvoid\nIOL::printParams(std::ostream &ostr) const\n{\n    ostr << \"Started incremental object learning with parameters: \" << std::endl\n         << \"===================================================\" << std::endl\n         << \"radius: \" << param_.radius_ << std::endl\n         << \"eps_angle: \" << param_.eps_angle_ << std::endl\n         << \"dist_threshold_growing_: \" << param_.dist_threshold_growing_ << std::endl\n         << \"voxel resolution: \" << param_.voxel_resolution_ << std::endl\n         << \"seed resolution: \" << param_.seed_resolution_ << std::endl\n         << \"ratio_supervoxel: \" << param_.ratio_supervoxel_ << std::endl\n         << \"max z distance: \" << param_.chop_z_ << std::endl\n         << \"do_erosion: \" << param_.do_erosion_ << std::endl\n         << \"do_sift_based_camera_pose_estimation_: \" << param_.do_sift_based_camera_pose_estimation_ << std::endl\n         << \"transferring object indices from latest frame only: \" << param_.transfer_indices_from_latest_frame_only_ << std::endl\n         << \"min_points_for_transferring_: \" << param_.min_points_for_transferring_ << std::endl\n         << \"normal_method_: \" << param_.normal_method_ << std::endl\n         << \"apply minimimum spanning tree: \" << param_.do_mst_refinement_ << std::endl\n         << \"ratio_cluster_obj_supported_: \" << param_.ratio_cluster_obj_supported_ << std::endl\n         << \"ratio_cluster_occluded_: \" << param_.ratio_cluster_occluded_ << std::endl\n         << \"smooth_clustering_param_inlDist: \" << p_param_.inlDist << std::endl\n         << \"smooth_clustering_param_inlDistSmooth: \" << p_param_.inlDistSmooth << std::endl\n         << \"smooth_clustering_param_least_squares_refinement: \" << p_param_.least_squares_refinement << std::endl\n         << \"smooth_clustering_param_minPoints: \" << p_param_.minPoints << std::endl\n         << \"smooth_clustering_param_minPointsSmooth: \" << p_param_.minPointsSmooth << std::endl\n         << \"smooth_clustering_param_smooth_clustering: \" << p_param_.smooth_clustering << std::endl\n         << \"smooth_clustering_param_thrAngle: \" << p_param_.thrAngle << std::endl\n         << \"smooth_clustering_param_thrAngleSmooth: \" << p_param_.thrAngleSmooth << std::endl\n         << \"statistical_outlier_removal_meanK_: \" << sor_params_.meanK_ << std::endl\n         << \"statistical_outlier_removal_std_mul_: \" << sor_params_.std_mul_ << std::endl\n         << \"===================================================\" << std::endl << std::endl;\n}\n}\n}\n", "meta": {"hexsha": "440da90af67a5c2e6e739929281fd976e5418909", "size": 43975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/object_modelling/src/incremental_object_learning.cpp", "max_stars_repo_name": "byiii/clone_v4r_j", "max_stars_repo_head_hexsha": "628359c7ba19389004618defd6a8d8ab5af35967", "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": "modules/object_modelling/src/incremental_object_learning.cpp", "max_issues_repo_name": "byiii/clone_v4r_j", "max_issues_repo_head_hexsha": "628359c7ba19389004618defd6a8d8ab5af35967", "max_issues_repo_licenses": ["MIT"], "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/object_modelling/src/incremental_object_learning.cpp", "max_forks_repo_name": "byiii/clone_v4r_j", "max_forks_repo_head_hexsha": "628359c7ba19389004618defd6a8d8ab5af35967", "max_forks_repo_licenses": ["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.1952723535, "max_line_length": 195, "alphanum_fraction": 0.6131665719, "num_tokens": 10408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.18012210311996138}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/exec.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/timing.h\"\n#include \"dynet/rnn.h\"\n#include \"dynet/gru.h\"\n#include \"dynet/lstm.h\"\n#include \"dynet/fast-lstm.h\"\n#include \"dynet/expr.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <memory>\n#include <type_traits>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/program_options.hpp>\n\n#include \"s2s/dynet/dict.h\"\n#include \"s2s/nn/attn.hpp\"\n#include \"s2s/nn/base.hpp\"\n#include \"s2s/nn/slahan.hpp\"\n#include \"s2s/nn/lstm.hpp\"\n#include \"s2s/nn/tagger.hpp\"\n#include \"s2s/corpus/comp.hpp\"\n#include \"s2s/corpus/dicts.hpp\"\n#include \"s2s/decode/hypothesis.hpp\"\n\n#ifndef INCLUDE_GUARD_DECODER_GREEDY_HPP\n#define INCLUDE_GUARD_DECODER_GREEDY_HPP\n\nnamespace s2s {\n\n    void greedy_decode_ensemble(const batch& batch_local, std::vector<hypothesis<encoder_decoder_attn>>& hyp_stack, std::vector<std::unique_ptr<encoder_decoder_attn> > &encdec, dicts &d, const s2s_options &opts){\n        dynet::ComputationGraph cg;\n        hyp_stack.resize(1);\n        hyp_stack[0].init(batch_local, d, encdec, cg);\n        for (unsigned int t = 1; t < encdec[0]->slen; ++t) {\n            std::vector<std::vector<float> > output(batch_local.batch_size(), std::vector<float>(d.dict_set_trg.d_word.size(), 0.f));\n            // for each model\n            for(unsigned int model_id = 0; model_id < encdec.size(); model_id++){\n                dynet::Expression i_att_t = encdec[model_id]->decoder_attention(cg, t, hyp_stack[0].prev());\n                dynet::Expression i_out_t = encdec[model_id]->decoder_output(cg, t, i_att_t);\n                dynet::Expression pred_att = softmax(i_att_t);\n                std::vector<dynet::Tensor> results_att = cg.incremental_forward(pred_att).batch_elems();\n                dynet::Expression pred_out = softmax(i_out_t);\n                std::vector<dynet::Tensor> results_out = cg.incremental_forward(pred_out).batch_elems();\n                // for each sentence\n                for(unsigned int sent_id = 0; sent_id < results_out.size(); sent_id++){\n                    hyp_stack[0].dist_att[model_id][sent_id].push_back(as_vector(results_att.at(sent_id)));\n                    hyp_stack[0].dist_out[model_id][sent_id].push_back(as_vector(results_out.at(sent_id)));\n                    for(unsigned int vocab_id = 0; vocab_id < hyp_stack[0].dist_out[model_id][sent_id][t-1].size(); vocab_id++){\n                        output[sent_id][vocab_id] += log(hyp_stack[0].dist_out[model_id][sent_id][t-1][vocab_id]);\n                    }\n                }\n            }\n            // for each sentence\n            for(unsigned int sent_id = 0; sent_id < output.size(); sent_id++){\n                for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                    output[sent_id][vocab_id] /= (float)(encdec.size());\n                }\n            }\n            // output vocab\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                unsigned int w_id = 0;\n                float w_prob = -FLT_MAX;\n                if(t + 1 == batch_local.len_src[sent_id] || hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    w_id = d.dict_set_trg.end_id_word;\n                    w_prob = output[sent_id][d.dict_set_trg.end_id_word];\n                }else{\n                    for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                        if(vocab_id == d.dict_set_trg.end_id_word){\n                            continue;\n                        }\n                        if(output[sent_id][vocab_id] > w_prob){\n                            w_id = vocab_id;\n                            w_prob = output[sent_id][vocab_id];\n                        }\n                    }\n                }\n                hyp_stack[0].prob[sent_id] += w_prob;\n                hyp_stack[0].output[sent_id].push_back(w_id);\n            }\n            // end check\n            unsigned int num_end = 0;\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                if(hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    num_end++;\n                }\n            }\n            if(num_end == hyp_stack[0].output.size()){\n                break;\n            }\n        }\n    }\n    \n    void greedy_decode_ensemble(const batch& batch_local, std::vector<hypothesis<encoder_decoder_base>>& hyp_stack, std::vector<std::unique_ptr<encoder_decoder_base> > &encdec, dicts &d, const s2s_options &opts){\n        dynet::ComputationGraph cg;\n        hyp_stack.resize(1);\n        hyp_stack[0].init(batch_local, d, encdec, cg);\n        for (unsigned int t = 1; t < encdec[0]->slen; ++t) {\n            std::vector<std::vector<float> > output(batch_local.batch_size(), std::vector<float>(d.dict_set_trg.d_word.size(), 0.f));\n            // for each model\n            for(unsigned int model_id = 0; model_id < encdec.size(); model_id++){\n                dynet::Expression i_out_t = encdec[model_id]->decoder_output(cg, hyp_stack[0].prev(), t);\n                dynet::Expression pred_out = softmax(i_out_t);\n                std::vector<dynet::Tensor> results_out = cg.incremental_forward(pred_out).batch_elems();\n                // for each sentence\n                for(unsigned int sent_id = 0; sent_id < results_out.size(); sent_id++){\n                    hyp_stack[0].dist_out[model_id][sent_id].push_back(as_vector(results_out.at(sent_id)));\n                    for(unsigned int vocab_id = 0; vocab_id < hyp_stack[0].dist_out[model_id][sent_id][t-1].size(); vocab_id++){\n                        output[sent_id][vocab_id] += log(hyp_stack[0].dist_out[model_id][sent_id][t-1][vocab_id]);\n                    }\n                }\n            }\n            // for each sentence\n            for(unsigned int sent_id = 0; sent_id < output.size(); sent_id++){\n                for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                    output[sent_id][vocab_id] /= (float)(encdec.size());\n                }\n            }\n            // output vocab\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                unsigned int w_id = 0;\n                float w_prob = -FLT_MAX;\n                if(t + 1 == batch_local.len_src[sent_id] || hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    w_id = d.dict_set_trg.end_id_word;\n                    w_prob = output[sent_id][d.dict_set_trg.end_id_word];\n                }else{\n                    for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                        if(vocab_id == d.dict_set_trg.end_id_word){\n                            continue;\n                        }\n                        if(output[sent_id][vocab_id] > w_prob){\n                            w_id = vocab_id;\n                            w_prob = output[sent_id][vocab_id];\n                        }\n                    }\n                }\n                hyp_stack[0].prob[sent_id] += w_prob;\n                hyp_stack[0].output[sent_id].push_back(w_id);\n            }\n            // end check\n            unsigned int num_end = 0;\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                if(hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    num_end++;\n                }\n            }\n            if(num_end == hyp_stack[0].output.size()){\n                break;\n            }\n        }\n    }\n    \n    void greedy_decode_ensemble(const batch& batch_local, std::vector<hypothesis<encoder_decoder_slahan>>& hyp_stack, std::vector<std::unique_ptr<encoder_decoder_slahan> > &encdec, dicts &d, const s2s_options &opts){\n        dynet::ComputationGraph cg;\n        hyp_stack.resize(1);\n        hyp_stack[0].init(batch_local, d, encdec, cg);\n        std::vector<std::vector<dynet::Expression> > h_att_self_all(encdec.size());\n        for(unsigned int model_id = 0; model_id < encdec.size(); model_id++){\n            h_att_self_all[model_id] = encdec[model_id]->attention(cg, batch_local);\n            encdec[model_id]->recursive_attention(cg, h_att_self_all[model_id]);\n        }\n        for (unsigned int t = 1; t < encdec[0]->slen; ++t) {\n            std::vector<std::vector<float> > output(batch_local.batch_size(), std::vector<float>(d.dict_set_trg.d_word.size(), 0.f));\n            // for each model\n            for(unsigned int model_id = 0; model_id < encdec.size(); model_id++){\n                dynet::Expression i_out_t = encdec[model_id]->decoder_output(cg, t, hyp_stack[0].prev());\n                dynet::Expression pred_out = softmax(i_out_t);\n                std::vector<dynet::Tensor> results_out = cg.incremental_forward(pred_out).batch_elems();\n                dynet::Expression pred_att = softmax(h_att_self_all[model_id][t]);\n                std::vector<dynet::Tensor> results_att = cg.incremental_forward(pred_att).batch_elems();\n                // for each sentence\n                for(unsigned int sent_id = 0; sent_id < results_out.size(); sent_id++){\n                    hyp_stack[0].dist_att[model_id][sent_id].push_back(as_vector(results_att.at(sent_id)));\n                    hyp_stack[0].dist_out[model_id][sent_id].push_back(as_vector(results_out.at(sent_id)));\n                    for(unsigned int vocab_id = 0; vocab_id < hyp_stack[0].dist_out[model_id][sent_id][t-1].size(); vocab_id++){\n                        output[sent_id][vocab_id] += log(hyp_stack[0].dist_out[model_id][sent_id][t-1][vocab_id]);\n                    }\n                }\n            }\n            // for each sentence\n            for(unsigned int sent_id = 0; sent_id < output.size(); sent_id++){\n                for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                    output[sent_id][vocab_id] /= (float)(encdec.size());\n                }\n            }\n            // output vocab\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                unsigned int w_id = 0;\n                float w_prob = -FLT_MAX;\n                if(t + 1 == batch_local.len_src[sent_id] || hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    w_id = d.dict_set_trg.end_id_word;\n                    w_prob = output[sent_id][d.dict_set_trg.end_id_word];\n                }else{\n                    for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                        if(vocab_id == d.dict_set_trg.end_id_word){\n                            continue;\n                        }\n                        if(output[sent_id][vocab_id] > w_prob){\n                            w_id = vocab_id;\n                            w_prob = output[sent_id][vocab_id];\n                        }\n                    }\n                }\n                hyp_stack[0].prob[sent_id] += w_prob;\n                hyp_stack[0].output[sent_id].push_back(w_id);\n            }\n            // end check\n            unsigned int num_end = 0;\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                if(hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    num_end++;\n                }\n            }\n            if(num_end == hyp_stack[0].output.size()){\n                break;\n            }\n        }\n    }\n  \n    void greedy_decode_ensemble(const batch& batch_local, std::vector<hypothesis<encoder_decoder_lstm>>& hyp_stack, std::vector<std::unique_ptr<encoder_decoder_lstm> > &encdec, dicts &d, const s2s_options &opts){\n        dynet::ComputationGraph cg;\n        hyp_stack.resize(1);\n        hyp_stack[0].init(batch_local, d, encdec, cg);\n        for (unsigned int t = 1; t < encdec[0]->slen; ++t) {\n            std::vector<std::vector<float> > output(batch_local.batch_size(), std::vector<float>(d.dict_set_trg.d_word.size(), 0.f));\n            // for each model\n            for(unsigned int model_id = 0; model_id < encdec.size(); model_id++){\n                std::vector<dynet::real> bit_features = encdec[model_id]->bit_features(t, hyp_stack[0].prevs, batch_local.align[t]);\n                dynet::Expression i_out_t = encdec[model_id]->decoder_output(cg, t, batch_local.align[t], bit_features);\n                dynet::Expression pred_out = softmax(i_out_t);\n                std::vector<dynet::Tensor> results_out = cg.incremental_forward(pred_out).batch_elems();\n                // for each sentence\n                for(unsigned int sent_id = 0; sent_id < results_out.size(); sent_id++){\n                    hyp_stack[0].dist_out[model_id][sent_id].push_back(as_vector(results_out.at(sent_id)));\n                    for(unsigned int vocab_id = 0; vocab_id < hyp_stack[0].dist_out[model_id][sent_id][t-1].size(); vocab_id++){\n                        output[sent_id][vocab_id] += log(hyp_stack[0].dist_out[model_id][sent_id][t-1][vocab_id]);\n                    }\n                }\n            }\n            // for each sentence\n            for(unsigned int sent_id = 0; sent_id < output.size(); sent_id++){\n                for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                    output[sent_id][vocab_id] /= (float)(encdec.size());\n                }\n            }\n            // output vocab\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                unsigned int w_id = 0;\n                float w_prob = -FLT_MAX;\n                if(t + 1 == batch_local.len_src[sent_id] || hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    w_id = d.dict_set_trg.end_id_word;\n                    w_prob = output[sent_id][d.dict_set_trg.end_id_word];\n                }else{\n                    for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                        if(vocab_id == d.dict_set_trg.end_id_word){\n                            continue;\n                        }\n                        if(output[sent_id][vocab_id] > w_prob){\n                            w_id = vocab_id;\n                            w_prob = output[sent_id][vocab_id];\n                        }\n                    }\n                }\n                hyp_stack[0].prob[sent_id] += w_prob;\n                hyp_stack[0].output[sent_id].push_back(w_id);\n            }\n            hyp_stack[0].update_prevs();\n            // end check\n            unsigned int num_end = 0;\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                if(hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    num_end++;\n                }\n            }\n            if(num_end == hyp_stack[0].output.size()){\n                break;\n            }\n        }\n    }\n    \n    void greedy_decode_ensemble(const batch& batch_local, std::vector<hypothesis<tagger>>& hyp_stack, std::vector<std::unique_ptr<tagger> > &encdec, dicts &d, const s2s_options &opts){\n        dynet::ComputationGraph cg;\n        hyp_stack.resize(1);\n        hyp_stack[0].init(batch_local, d, encdec, cg);\n        for (unsigned int t = 0; t < encdec[0]->slen; ++t) {\n            std::vector<std::vector<float> > output(batch_local.batch_size(), std::vector<float>(d.dict_set_trg.d_word.size(), 0.f));\n            // for each model\n            for(unsigned int model_id = 0; model_id < encdec.size(); model_id++){\n                dynet::Expression i_out_t = encdec[model_id]->output(cg, t);\n                dynet::Expression pred_out = softmax(i_out_t);\n                std::vector<dynet::Tensor> results_out = cg.incremental_forward(pred_out).batch_elems();\n                // for each sentence\n                for(unsigned int sent_id = 0; sent_id < results_out.size(); sent_id++){\n                    hyp_stack[0].dist_out[model_id][sent_id].push_back(as_vector(results_out.at(sent_id)));\n                    for(unsigned int vocab_id = 0; vocab_id < hyp_stack[0].dist_out[model_id][sent_id][t].size(); vocab_id++){\n                        output[sent_id][vocab_id] += log(hyp_stack[0].dist_out[model_id][sent_id][t][vocab_id]);\n                    }\n                }\n            }\n            // for each sentence\n            for(unsigned int sent_id = 0; sent_id < output.size(); sent_id++){\n                for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                    output[sent_id][vocab_id] /= (float)(encdec.size());\n                }\n            }\n            // output vocab\n            for(unsigned int sent_id = 0; sent_id < hyp_stack[0].output.size(); sent_id++){\n                unsigned int w_id = 0;\n                float w_prob = -FLT_MAX;\n                if(t == 0){\n                    w_id = d.dict_set_trg.start_id_word;\n                    w_prob = output[sent_id][d.dict_set_trg.start_id_word];\n                }else if(t == batch_local.len_src[sent_id] - 1 || hyp_stack[0].output[sent_id].back() == d.dict_set_trg.end_id_word){\n                    w_id = d.dict_set_trg.end_id_word;\n                    w_prob = output[sent_id][d.dict_set_trg.end_id_word];\n                }else{\n                    for(unsigned int vocab_id = 0; vocab_id < output[sent_id].size(); vocab_id++){\n                        if(vocab_id == d.dict_set_trg.end_id_word){\n                            continue;\n                        }\n                        if(output[sent_id][vocab_id] > w_prob){\n                            w_id = vocab_id;\n                            w_prob = output[sent_id][vocab_id];\n                        }\n                    }\n                }\n                hyp_stack[0].prob[sent_id] += w_prob;\n                if(t == 0){\n                    hyp_stack[0].output[sent_id][0] = w_id;\n                }else{\n                    hyp_stack[0].output[sent_id].push_back(w_id);\n                }\n            }\n        }\n    }\n\n    template<class T_EncDec>\n    void greedy_decode_ensemble(const batch& batch_local, std::vector<hypothesis<T_EncDec>>& hyp_stack, std::unique_ptr<T_EncDec>& encdec, dicts &d, const s2s_options &opts){\n        std::vector<std::unique_ptr<T_EncDec> > encdec_vec;\n        encdec_vec.push_back(std::move(encdec));\n        greedy_decode_ensemble(batch_local, hyp_stack, encdec_vec, d, opts);\n        encdec = std::move(encdec_vec[0]);\n    }\n\n};\n\n#endif // INCLUDE_GUARD_DECODER_GREEDY_HPP\n\n", "meta": {"hexsha": "ecceaeb08081f28b4b98a829317684db7060d1c7", "size": 18643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "compressor/include/s2s/decode/greedy.hpp", "max_stars_repo_name": "kamigaito/SLAHAN", "max_stars_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-05-24T16:03:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T21:52:32.000Z", "max_issues_repo_path": "compressor/include/s2s/decode/greedy.hpp", "max_issues_repo_name": "kamigaito/SLAHAN", "max_issues_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-31T18:41:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T16:16:22.000Z", "max_forks_repo_path": "compressor/include/s2s/decode/greedy.hpp", "max_forks_repo_name": "kamigaito/SLAHAN", "max_forks_repo_head_hexsha": "5ef981f1713f4586e2ec42c226555e95d7904147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-05-26T01:53:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T07:13:31.000Z", "avg_line_length": 52.5154929577, "max_line_length": 216, "alphanum_fraction": 0.5432065655, "num_tokens": 4413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.1801220960511163}}
{"text": "/******************************************************************************\n * Copyright (c) 2011\n * Alexey Zakharov, Yury Brodskiy\n *\n *\n * This software is published under a dual-license: GNU Lesser General Public\n * License LGPL 2.1 and BSD license. The dual-license implies that users of this\n * code may choose which terms they prefer.\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 company 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 program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License LGPL as\n * published by the Free Software Foundation, either version 2.1 of the\n * License, or (at your option) any later version or the BSD license.\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 Lesser General Public License LGPL and the BSD license for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License LGPL and BSD license along with this program.\n *\n ******************************************************************************/\n\n\n#include <boost/units/systems/si.hpp>\n#include <boost/units/physical_dimensions.hpp>\n#include <boost/units/io.hpp>\n#include <geometry_msgs/Quaternion.h>\n\n#include \"cartesian_compliance_control.h\"\n#include \"20_sim_cartesian_compliance_control/common/xxmatrix.h\"\n#include \"pluginlib/class_list_macros.h\"\n#include <tf/transform_datatypes.h>\n\nPLUGINLIB_DECLARE_CLASS(youbot_description, CartesianComplianceController, controller::CartesianComplianceController, pr2_controller_interface::Controller)\n\n\nusing namespace std;\n\nnamespace controller {\n\nCartesianComplianceController* CartesianComplianceControllerDebug::getControllerPtr() {\n\treturn dynamic_cast<CartesianComplianceController*> (this->controllerPtr);\n}\n\nvoid CartesianComplianceControllerDebug::toTransformMatrix(double* tf, tf::Transform& trans) {\n\ttrans.setOrigin(tf::Vector3(tf[3], tf[7], tf[11]));\n\ttf::Matrix3x3 rotMatrix(tf[0], tf[1], tf[2],\n\t\t\ttf[4], tf[5], tf[6],\n\t\t\ttf[8], tf[9], tf[10]);\n\ttf::Quaternion quat;\n\trotMatrix.getRotation(quat);\n\ttrans.setRotation(quat);\n}\n\nvoid CartesianComplianceControllerDebug::publishTf(double* tf, string parent, string child) {\n\t/*tf::Transform trans;\n\ttrans.setOrigin(tf::Vector3(tf[3], tf[7], tf[11]));\n\ttf::Matrix3x3 rotMatrix(tf[0], tf[1], tf[2],\n\t\t\ttf[4], tf[5], tf[6],\n\t\t\ttf[8], tf[9], tf[10]);\n\ttf::Quaternion quat;\n\trotMatrix.getRotation(quat);\n\ttrans.setRotation(quat);*/\n\ttf::Transform trans;\n\ttoTransformMatrix(tf, trans);\n\tbr.sendTransform(tf::StampedTransform(trans, ros::Time::now(), parent, child));\n}\n\nvoid CartesianComplianceControllerDebug::init() {\n\n\tros::NodeHandle &nodeHandle = getControllerPtr()->nodeHandle;\n/*\tgazeboJointPositions.reset(new realtime_tools::RealtimePublisher<brics_actuator::JointPositions > (nodeHandle, \"gazebo_joint_positions\", 1));\n\tgazeboJointPositions->lock();\n\tcontrollerJointPositions.reset(new realtime_tools::RealtimePublisher<brics_actuator::JointPositions > (nodeHandle, \"controller_joint_positions\", 1));\n\tcontrollerJointPositions->lock();\n\tgazeboJointTorques.reset(new realtime_tools::RealtimePublisher<brics_actuator::JointTorques > (nodeHandle, \"gazebo_joint_torques\", 1));\n\tgazeboJointTorques->lock();\n\tcontrollerJointTorques.reset(new realtime_tools::RealtimePublisher<brics_actuator::JointTorques > (nodeHandle, \"controller_joint_torques\", 1));\n\tcontrollerJointTorques->lock();\n\tgazeboJointPose.reset(new realtime_tools::RealtimePublisher<brics_actuator::CartesianPose > (nodeHandle, \"gazebo_joint_pose\", 1));\n\tgazeboJointPose->lock();\n\tcontrollerJointPose.reset(new realtime_tools::RealtimePublisher<brics_actuator::CartesianPose > (nodeHandle, \"controller_joint_pose\", 1));\n\tcontrollerJointPose->lock();\n*/\n    currentTipPose.reset(new realtime_tools::RealtimePublisher<brics_actuator::CartesianPose> (nodeHandle, \"current_tip_pose\", 1));\n    targetTipPose.reset(new realtime_tools::RealtimePublisher<brics_actuator::CartesianPose> (nodeHandle, \"target_tip_pose\", 1));\n}\n\nvoid CartesianComplianceControllerDebug::publish() {\n\n\t/*vector <brics_actuator::JointValue> positionsGazebo;\n\tvector <brics_actuator::JointValue> positionsController;\n\tvector <brics_actuator::JointValue> torquesGazebo;*/\n\n\tCartesianComplianceController* ctrlPtr = getControllerPtr();\n\n\t/*unsigned int size = ctrlPtr->joints.size();\n\tpositionsGazebo.resize(size);\n\tpositionsController.resize(size);\n\ttorquesGazebo.resize(size);*/\n\n\n\tXXMatrix* matrix = ctrlPtr->autoGenerated20simController.m_M;\n\tdouble* joint1 = matrix[42].mat;\n\tpublishTf(joint1, \"/odom\", \"/joint1\");\n\tdouble* joint2 = matrix[43].mat;\n\tpublishTf(joint2, \"/odom\", \"/joint2\");\n\tdouble* joint3 = matrix[44].mat;\n\tpublishTf(joint3, \"/odom\", \"/joint3\");\n\tdouble* joint4 = matrix[45].mat;\n\tpublishTf(joint4, \"/odom\", \"/joint4\");\n\tdouble* joint5 = matrix[46].mat;\n\tpublishTf(joint5, \"/odom\", \"/joint5\");\n\tdouble* tip = matrix[2].mat;\n\tpublishTf(tip, \"/odom\", \"/tip\");\n\n//\tstd::vector<pr2_mechanism_model::JointState*>::iterator joinsIterator;\n\n\tusing namespace boost::units;\n\n\n//\tunsigned int j = 0;\n\n/*\tfor (joinsIterator = ctrlPtr->joints.begin(); joinsIterator != ctrlPtr->joints.end(); ++joinsIterator) {\n\t\tpositionsGazebo[j].joint_uri = (*joinsIterator)->joint_->name;\n\t\tpositionsGazebo[j].value = (*joinsIterator)->position_;\n\t\tpositionsGazebo[j].unit = to_string(si::radians);\n\t\tpositionsGazebo[j].timeStamp = ctrlPtr->currentTime;\n\n\t\tpositionsController[j].joint_uri = (*joinsIterator)->joint_->name;\n\t\t//positionsController[j].value = u[28+j]; //CHANGE THAT!\n\t\tpositionsController[j].unit = to_string(si::radians);\n\t\tpositionsController[j].timeStamp = ctrlPtr->currentTime;\n\n\t\ttorquesGazebo[j].joint_uri = (*joinsIterator)->joint_->name;\n\t\ttorquesGazebo[j].value = (*joinsIterator)->commanded_effort_;\n\t\ttorquesGazebo[j].unit = to_string(si::newton_meter);\n\t\ttorquesGazebo[j].timeStamp = ctrlPtr->currentTime;\n\t\t++j;\n\t}\n\n\tgazeboJointPositions->msg_.positions = positionsGazebo;\n\tcontrollerJointPositions->msg_.positions = positionsController;\n\tgazeboJointTorques->msg_.torques = torquesGazebo;\n\n\tgazeboJointPositions->unlockAndPublish();\n\tcontrollerJointPositions->unlockAndPublish();\n\tgazeboJointTorques->unlockAndPublish();\n*/\n//    tf::Transform trans;\n//\ttoTransformMatrix(tf, trans);\n\n\n\n    currentTipPose->msg_ = ctrlPtr->currentTipPose;\n    targetTipPose->msg_ = ctrlPtr->targetTipPose;\n    currentTipPose->unlockAndPublish();\n    targetTipPose->unlockAndPublish();\n}\n\nCartesianComplianceController::CartesianComplianceController()\n: robotPtr(NULL) {\n    locked = true;\n\tloopCount = 0;\n\tthis->position[0] = 0;\n\tthis->position[1] = 0;\n\tthis->position[2] = 0;\n\n\tthis->orientationYPR[0] = 0;\n\tthis->orientationYPR[1] = 0;\n\tthis->orientationYPR[2] = 0;\n#ifdef DEBUG_INFO\n\tdebugInfo = new CartesianComplianceControllerDebug(this);\n\n#else\n\tdebugInfo = new Debug(this);\n#endif\n\n}\n\nCartesianComplianceController::~CartesianComplianceController() {\n\tsubscriber.shutdown();\n\tautoGenerated20simController.Terminate(u, y);\n\tdelete debugInfo;\n}\n\n/*  auto-generated by 20sim;\n\tinitialize the inputs and outputs with correct initial values */\nvoid CartesianComplianceController::init20SimController() {\n\n\t/* initialize the inputs and outputs with correct initial values */\n\t//angles of the joionts\n\tu[0] = 0.0; //is not active\n\tu[1] = 0.0; //is not active\n\tu[2] = 0.0; //is not active\n\tu[3] = -170 * M_PI / 180; //J1\n\tu[4] = -65 * M_PI / 180; //J2\n\tu[5] = -146 * M_PI / 180; //J3\n\tu[6] = -102.5 * M_PI / 180; //J4\n\tu[7] = -167.5 * M_PI / 180; //J5\n\t/* velocities of the joints used for active dumping*/\n\tu[8] = 0.0; //is not active\n\tu[9] = 0.0; //is not active\n\tu[10] = 0.0; //is not active\n\tu[11] = 0.0; //J1\n\tu[12] = 0.0; //J2\n\tu[13] = 0.0; //J3\n\tu[14] = 0.0; //J4\n\tu[15] = 0.0; //J5\n\tu[16] = 0.0; /* xyzrpy *///not tested\n\tu[17] = 0.0;\n\tu[18] = 0.53;\n\tu[19] = 0.0;\n\tu[20] = 0.0;\n\tu[21] = 0.0;\n\n\ty[0] = 0.0; /* output */\n\ty[1] = 0.0;\n\ty[2] = 0.0;\n\ty[3] = 0.0;\n\ty[4] = 0.0;\n\ty[5] = 0.0;\n\ty[6] = 0.0;\n\ty[7] = 0.0;\n\ty[8] = 0.0;\n\ty[9] = 0.0;\n\ty[10] = 0.0;\n\ty[11] = 0.0;\n\ty[12] = 0.0;\n\ty[13] = 0.0;\n\ty[14] = 0.0;\n\ty[15] = 0.0;\n\ty[16] = 0.0; /* p.e */\n\ty[17] = 0.0;\n\ty[18] = 0.0;\n\ty[19] = 0.0;\n\ty[20] = 0.0;\n\ty[21] = 0.0;\n\ty[22] = 0.0;\n\ty[23] = 0.0;\n\n\tROS_INFO(\"20sim init.\\n\");\n\tautoGenerated20simController.Initialize(u, y, 0.0);\n\n}\n\nbool CartesianComplianceController::init(pr2_mechanism_model::RobotState *robotPtr, ros::NodeHandle &nodeHandle) {\n\tusing namespace XmlRpc;\n\tthis->nodeHandle = nodeHandle;\n\tthis->robotPtr = robotPtr;\n\n\tROS_INFO(\"Initializing interaction control for the youbot arm...\\n\");\n\n\t// Gets all of the joint pointers from the RobotState to a joints vector\n\tXmlRpc::XmlRpcValue jointNames;\n\tif (!nodeHandle.getParam(\"joints\", jointNames)) {\n\t\tROS_ERROR(\"No joints given. (namespace: %s)\", nodeHandle.getNamespace().c_str());\n\t\treturn false;\n\t}\n\n\tif (jointNames.getType() != XmlRpc::XmlRpcValue::TypeArray) {\n\t\tROS_ERROR(\"Malformed joint specification.  (namespace: %s)\", nodeHandle.getNamespace().c_str());\n\t\treturn false;\n\t}\n\n\tfor (unsigned int i = 0; i < static_cast<unsigned int> (jointNames.size()); ++i) {\n\t\tXmlRpcValue &name = jointNames[i];\n\t\tif (name.getType() != XmlRpcValue::TypeString) {\n\t\t\tROS_ERROR(\"Array of joint names should contain all strings.  (namespace: %s)\", nodeHandle.getNamespace().c_str());\n\t\t\treturn false;\n\t\t}\n\n\t\tpr2_mechanism_model::JointState *jointStatePtr = robotPtr->getJointState((std::string)name);\n\t\tif (jointStatePtr == NULL) {\n\t\t\tROS_ERROR(\"Joint not found: %s. (namespace: %s)\", ((std::string)name).c_str(), nodeHandle.getNamespace().c_str());\n\t\t\treturn false;\n\t\t}\n\n\t\tjoints.push_back(jointStatePtr);\n\t}\n\n\t// Ensures that all the joints are calibrated.\n\tfor (unsigned int i = 0; i < joints.size(); ++i) {\n\t\tif (!joints[i]->calibrated_) {\n\t\t\tROS_ERROR(\"Joint %s was not calibrated (namespace: %s)\", joints[i]->joint_->name.c_str(), nodeHandle.getNamespace().c_str());\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// Initializing target efforts vector\n\ttargetEfforts.resize(joints.size());\n\n\t// Subscribing for an input pose command\n\tsubscriber = nodeHandle.subscribe(\"command\", 1, &CartesianComplianceController::positionCommand, this);\n\n\t// Initializing 20Sim controller\n\tinit20SimController();\n\n\t// Initializing twist publisher for the base\n\tROS_INFO(\"base_confghfhgtroller/command\\n\");\n\tbaseTwist.reset(new realtime_tools::RealtimePublisher<geometry_msgs::Twist > (nodeHandle, \"base_controller/command\", 1));\n\tbaseTwist->lock();\n\n\tsubscriberOdometry = nodeHandle.subscribe(\"base_odometry/odometry\", 1, &CartesianComplianceController::odometryCommand, this);\n\n\n\t// Initializing debug output\n\tdebugInfo->init();\n\n\treturn true;\n}\n\nvoid CartesianComplianceController::starting() {\n\t// Initializing timer\n\tcurrentTime = robotPtr->getTime();\n\tlastTime = currentTime;\n}\n\nvoid CartesianComplianceController::update20SimControl() {\n\n    if (!locked) {\n        tf::Quaternion quat;\n        tf::quaternionMsgToTF(currentBasePose.orientation, quat);\n\n        double ypr[3];\n        tf::Matrix3x3(quat).getEulerYPR(ypr[0], ypr[1], ypr[2]);\n\n        u[0] = ypr[0]; //is not active\n     //  ROS_INFO(\"X: %f\\n\", u[0]);\n    }\n\n\tu[1] = currentBasePose.position.x; //is not active\n\tu[2] = currentBasePose.position.y; //is not active\n\tu[3] = joints[0]->position_ - 170 * M_PI / 180; // -170 +170, clockwise\n\tu[4] = joints[1]->position_ - 65 * M_PI / 180; // -65  +90,  counterclockwis\n\tu[5] = -joints[2]->position_ - 146 * M_PI / 180; // +146 -151, clockwise\n\t//ROS_INFO(\"joint 3: %f\", u[5]);\n\tu[6] = joints[3]->position_ - 102.5 * M_PI / 180; // -102 +102, counterclockwise\n\tu[7] = joints[4]->position_ - 167.5 * M_PI / 180; // -167 +167, clockwise\n\t/* velocities of the joints used for active dumping*/\n\n\tu[8] = 0.0;//currentBaseTwist.angular.z; //is not active\n\tu[9] = 0.0;//currentBaseTwist.linear.y;//0.0; //is not active\n\tu[10] = 0.0;//currentBaseTwist.linear.x;//0.0; //is not active\n\t//ROS_INFO(\"currentBaseTwist: x=%f, y=%f, z=%f\\n\", u[10], u[9], u[8]);\n\n\tu[11] = 0;//joints[0]->velocity_; //J1\n\tu[12] = 0;//joints[1]->velocity_; //J2\n\tu[13] = 0;//joints[2]->velocity_; //J3\n\tu[14] = 0;//joints[3]->velocity_; //J4\n\tu[15] = 0;//joints[4]->velocity_; //J5\n\n\tu[16] = this->position[0]; //0;0.0;            /* xyzYawPitchRoll *///not tested\n\tu[17] = this->position[1]; //0;0.2;\n\tu[18] = this->position[2]; //0,53;0.4;\n\tu[19] = this->orientationYPR[0];\n\tu[20] = this->orientationYPR[1]; //1.57;1.57;\n\tu[21] = this->orientationYPR[2]; //0.7;-0.7;-0.7\n\n\tautoGenerated20simController.Calculate(u, y);\n\n\ttargetSpeed[0] = y[16]; // rot\n\ttargetSpeed[1] = y[17]; // y\n\ttargetSpeed[2] = y[18]; // x\n    ROS_INFO(\"joint 3: %f\", y[21]);\n\ttargetEfforts[0] = y[19]; // -170 +170, clockwise\n\ttargetEfforts[1] = y[20]; // -65  +90,  counterclockwise\n\ttargetEfforts[2] = y[21]; // +146 -151, clockwise\n\ttargetEfforts[3] = y[22]; // -102 +102, counterclockwise\n\ttargetEfforts[4] = y[23]; // -167 +167, clockwise\n\n}\n\nvoid CartesianComplianceController::update() {\n\n\n\n\tcurrentTime = robotPtr->getTime();\n\tros::Duration dt = currentTime - lastTime;\n\tlastTime = currentTime;\n\n\t// Initializing error vector\n\tif (!locked) //{\n\t\tupdate20SimControl();\n\t//ROS_INFO (\"Current speed is: %f, %f\\n\", currentBaseTwist.angular.z, currentBaseTwist.linear.y);\n\n\t// } else\n\t//   ROS_INFO (\"locked\\n\");\n\n  //  ROS_INFO(\"vel: %f, %f, %f, %f, %f\\n\",joints[0]->velocity_,joints[1]->velocity_,joints[2]->velocity_,joints[3]->velocity_,joints[4]->velocity_);\n\t// Doing control here, calculating and applying the efforts\n\tfor (unsigned int i = 0; i < joints.size(); ++i) {\n\t\tjoints[i]->commanded_effort_ += targetEfforts[i] * 10.0;\n\t}\n\n\t// Sending control comands for the base\n\n\t//gazeboJointPositions->msg_.positions = positionsGazebo;\n\t//baseTwist->msg_ = ;\n\tgeometry_msgs::Twist twist;\n\tbaseTwist->trylock();\n\n\n    twist.linear.x = targetSpeed[2] / 15.0;\n    twist.linear.y = targetSpeed[1] / 15.0;\n\t//twist.angular.x = 0.0;//targetSpeed[2];\n    //twist.angular.y = 0.0;//targetSpeed[1];\n    twist.angular.z = targetSpeed[0] / 15.0 ;\n\n\t//ROS_INFO(\"Speed: %f, %f, %f\\n\", twist.angular.x, twist.angular.y, twist.angular.z);\n\n\tbaseTwist->msg_ = twist;\n\tbaseTwist->unlockAndPublish();\n\n\t// if debug mode is set, publishing debug TFs and controller information\n\tif (loopCount % 10 == 0) {\n\t\tdebugInfo->publish();\n\t}\n\t++loopCount;\n}\n\nvoid CartesianComplianceController::positionCommand(const brics_actuator::CartesianPose &pose) {\n\n\tusing namespace boost::units;\n\n    targetTipPose = pose;\n\n\tbrics_actuator::CartesianVector tipPosition;\n\tgeometry_msgs::Quaternion tipOrientation;\n\ttipPosition = pose.position;\n\ttipOrientation = pose.orientation;\n\n\tif (tipPosition.unit != to_string(si::meter))\n\t\tROS_ERROR(\"Position value is set in the inpcompatible units %s, expecting meters\", tipPosition.unit.c_str());\n\n\tthis->position[0] = tipPosition.x;\n\tthis->position[1] = tipPosition.y;\n\tthis->position[2] = tipPosition.z;\n\n\ttf::Quaternion quaternion;\n\ttf::quaternionMsgToTF(tipOrientation, quaternion);\n\ttf::Matrix3x3(quaternion).getEulerYPR(orientationYPR[0], orientationYPR[1], orientationYPR[2]);\n\n}\n\nvoid CartesianComplianceController::odometryCommand(const nav_msgs::Odometry &odometry) {\n  //  ROS_INFO (\"Odom: %f, %f, %f\\n\", currentBasePose.position.x, currentBasePose.position.y, currentBasePose.position.z);\n  //  ROS_INFO (\"Odom: %f, %f, %f, %f\\n\", currentBasePose.orientation.x, currentBasePose.orientation.y, currentBasePose.orientation.z,  currentBasePose.orientation.w);\n\tlocked = true;\n\tcurrentBaseTwist = odometry.twist.twist;\n\tcurrentBasePose = odometry.pose.pose;\n\tlocked = false;\n\n}\n\n}\n", "meta": {"hexsha": "58fa85c5bdfb7906b6db802eff67bdb7a8ce1ec9", "size": 16295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "resources/youbot_description/src/cartesian_compliance_control.cpp", "max_stars_repo_name": "jihoonl/wviz", "max_stars_repo_head_hexsha": "195b1104191b5699b3f6640d1db1751b2fee28f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-02-22T08:13:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T11:31:56.000Z", "max_issues_repo_path": "resources/youbot_description/src/cartesian_compliance_control.cpp", "max_issues_repo_name": "jihoonl/wviz", "max_issues_repo_head_hexsha": "195b1104191b5699b3f6640d1db1751b2fee28f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-07-06T09:51:23.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-07T07:35:22.000Z", "max_forks_repo_path": "resources/youbot_description/src/cartesian_compliance_control.cpp", "max_forks_repo_name": "jihoonl/wviz", "max_forks_repo_head_hexsha": "195b1104191b5699b3f6640d1db1751b2fee28f3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-07-28T10:57:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T11:31:58.000Z", "avg_line_length": 34.5966029724, "max_line_length": 167, "alphanum_fraction": 0.7016876342, "num_tokens": 4843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.18012208898227125}}
{"text": "\n#include <ros/ros.h>\n#include <sensor_msgs/JointState.h>\n#include <boost/bind.hpp>\n#include <boost/asio.hpp>\n#include <thread>\n#include <string>\n#include <vector>\n#include <functional>\n#include <mutex>\n#include <realtime_tools/realtime_publisher.h>\n#include <std_msgs/Int32MultiArray.h>\n#include <std_msgs/Float32.h>\n#include <eigen3/Eigen/Dense>\n\nusing namespace std;\nusing namespace boost;\n\nusing boost::asio::ip::udp;\n\n\nconst string JOINT_NAME[40] = {\"WaistPitch\",\"WaistYaw\",\n                               \"R_ShoulderPitch\",\"R_ShoulderRoll\",\"R_ShoulderYaw\",\"R_ElbowRoll\",\"R_WristYaw\",\"R_WristRoll\",\"R_HandYaw\",\n                               \"L_ShoulderPitch\",\"L_ShoulderRoll\",\"L_ShoulderYaw\",\"L_ElbowRoll\",\"L_WristYaw\",\"L_WristRoll\",\"L_HandYaw\",\n                               \"R_HipYaw\",\"R_HipRoll\",\"R_HipPitch\",\"R_KneePitch\",\"R_AnklePitch\",\"R_AnkleRoll\",\n                               \"L_HipYaw\",\"L_HipRoll\",\"L_HipPitch\",\"L_KneePitch\",\"L_AnklePitch\",\"L_AnkleRoll\",\n                               \"HeadYaw\", \"HeadPitch\", \"R_Gripper\", \"L_Gripper\"};\n\nconst int LEFT_LEG_START_NUM = 16;\nconst int RIGHT_LEG_START_NUM = 22;\nconst int MAX_JOINT = 32;\n\nconst double CNT_PER_REV = 983040.0;\nconst double CNT_PER_DEG = CNT_PER_REV / 360.0;\nconst double CNT_PER_RAD = CNT_PER_REV / ( M_PI * 2 );\nconst double RAD_PER_CNT = ( M_PI * 2 ) / CNT_PER_REV;\n\nconst double DSP_HZ = 1000.;\n\n\nros::Publisher joint_pub;\n\nenum { max_length = 1024 };\n\nuint8_t data[max_length];\nuint8_t data2[max_length];\nboost::asio::io_service io_service;\nudp::socket udp_socket(io_service, udp::endpoint(udp::v4(), 1107));\nudp::socket udp_socket2(io_service, udp::endpoint(udp::v4(), 1108));\nudp::endpoint sender_endpoint;\nudp::endpoint sender_endpoint2;\n\n\nstd::vector<double> q(12);\nstd::vector<double> qdot(12);\n\nstd::mutex data_mutex;\n\nint32_t make_32s(uint8_t *data)\n{\n  return (data[0] << 8*3) + (data[1] << 8*2) + (data[2] << 8*1) + (data[3] << 8*0);\n}\nuint32_t make_32u(uint8_t *data)\n{\n  return (data[0] << 8*3) + (data[1] << 8*2) + (data[2] << 8*1) + (data[3] << 8*0);\n}\nint16_t make_16s(uint8_t *data)\n{\n  return (data[0] << 8*1) + (data[1] << 8*0);\n}\n\nvoid handle_receive_from(const boost::system::error_code& error,\n    size_t bytes_recvd)\n{\n  if (!error && bytes_recvd > 50)\n  {\n    // SEND\n    int startIndex = -1;\n    if(data[1] == 'L')\n    {\n      // Leg\n      if(data[0] == 'L')\n      {\n        // Left\n        startIndex = 6;\n      }\n      else if(data[0] == 'R')\n      {\n        // Right\n        startIndex = 0;\n      }\n    }\n\n    if(startIndex == -1)\n    {\n      udp_socket.async_receive_from(\n          boost::asio::buffer(data, max_length),\n            sender_endpoint,handle_receive_from);\n      return;\n    }\n\n    unsigned int timeStamp = make_32u(&data[2]);\n    unsigned int seq = make_32u(&data[6]);\n    int length = data[10];\n\n\n    if(length != 6)\n    {\n      ROS_WARN(\"The length of the encoder values is not 6\");\n    }\n\n    // CHECKSUM!!!!!!!!\n    uint32_t checkSum = 0;\n    uint32_t checkSumCalc = 0;\n    for(int i=0; i<16+(length-1)*6; i++)\n    {\n        checkSum += data[i];\n    }\n    checkSumCalc = make_32u(&data[17+(length-1)*6]);\n    if(checkSum != checkSumCalc)\n    {\n        ROS_WARN(\"Checksum error calc = %x, recv = %x\", checkSum, checkSumCalc);\n    }\n    else\n    {\n        data_mutex.lock();\n        for(int i=0; i<length; i++)\n        {\n          int q_cnt = make_32s(&data[11 + i * 6]);\n          int qdot_cnt = make_16s(&data[15 + i * 6]);\n          if (abs(q_cnt*RAD_PER_CNT) > 2.0)\n          {\n              ROS_WARN(\"Too much value idx: %d q: %lf\", i, q_cnt*RAD_PER_CNT);\n              for(int k=0; k<bytes_recvd; k++)\n              {\n                  printf(\"%d \", data[k]);\n              }\n              printf(\"\\n\");\n          }\n          else\n          {\n              q[startIndex + 5 - i] = q_cnt * RAD_PER_CNT;\n              qdot[startIndex + 5 - i] = qdot_cnt * RAD_PER_CNT * DSP_HZ;\n          }\n        }\n        data_mutex.unlock();\n    }\n\n\n  }\n  udp_socket.async_receive_from(\n      boost::asio::buffer(data, max_length),\n        sender_endpoint,handle_receive_from);\n}\n\nvoid handle_receive_from2(const boost::system::error_code& error,\n    size_t bytes_recvd)\n{\n  if (!error && bytes_recvd > 40)\n  {\n      // Protocol Left/Right Leg/Arm\n    // SEND\n    int startIndex = -1;\n    if(data2[1] == 'L')\n    {\n      // Leg\n      if(data2[0] == 'L')\n      {\n        // Left\n        startIndex = 6;\n      }\n      else if(data2[0] == 'R')\n      {\n        // Right\n        startIndex = 0;\n      }\n    }\n\n    if(startIndex == -1)\n    {\n      udp_socket2.async_receive_from(\n          boost::asio::buffer(data2, max_length),\n            sender_endpoint2,handle_receive_from2);\n      return;\n    }\n\n    unsigned int timeStamp = make_32u(&data2[2]);\n    unsigned int seq = make_32u(&data2[6]);\n    int length = data2[10];\n\n\n    if(length != 6)\n    {\n      ROS_WARN(\"The length of the encoder values is not 6\");\n    }\n\n\n    // CHECKSUM!!!!!!!!\n    uint32_t checkSum = 0;\n    uint32_t checkSumCalc = 0;\n    for(int i=0; i<16+(length-1)*6; i++)\n    {\n        checkSum += data2[i];\n    }\n    checkSumCalc = make_32u(&data2[17+(length-1)*6]);\n    if(checkSum != checkSumCalc)\n    {\n        ROS_WARN(\"Checksum error calc = %x, recv = %x\", checkSum, checkSumCalc);\n    }\n    else\n    {\n        data_mutex.lock();\n        for(int i=0; i<length; i++)\n        {\n          int q_cnt = make_32s(&data2[11 + i * 6]);\n          int qdot_cnt = make_16s(&data2[15 + i * 6]);\n          if (abs(q_cnt*RAD_PER_CNT) > 2.0)\n          {\n              ROS_WARN(\"Too much value idx: %d q: %lf\", i, q_cnt*RAD_PER_CNT);\n              for(int k=0; k<bytes_recvd; k++)\n              {\n                  printf(\"%d \", data2[k]);\n              }\n              printf(\"\\n\");\n          }\n          else\n          {\n              q[startIndex + 5 - i] = q_cnt * RAD_PER_CNT;\n              qdot[startIndex + 5 - i] = qdot_cnt * RAD_PER_CNT * DSP_HZ;\n          }\n        }\n        data_mutex.unlock();\n    }\n\n\n  }\n  udp_socket2.async_receive_from(\n      boost::asio::buffer(data2, max_length),\n        sender_endpoint2,handle_receive_from2);\n}\n\nsensor_msgs::JointState joint_msg;\n\nvoid joint_publish()\n{\n  data_mutex.lock();\n  joint_msg.position = q;\n  joint_msg.velocity = qdot;\n  data_mutex.unlock();\n\n  joint_pub.publish(joint_msg);\n\n}\n\n\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"dyros_jet_ext_encoder_udp\");\n    ros::NodeHandle nh(\"~\");\n\n    joint_pub = nh.advertise<sensor_msgs::JointState>(\"/dyros_jet/ext_encoder\", 5);\n    udp_socket.async_receive_from(boost::asio::buffer(data, max_length), sender_endpoint,handle_receive_from);\n    udp_socket2.async_receive_from(boost::asio::buffer(data2, max_length), sender_endpoint2,handle_receive_from2);\n    boost::asio::io_service::work work(io_service);\n    boost::thread thread(boost::bind(&boost::asio::io_service::run, &io_service));\n\n    joint_msg.name.resize(12);\n    joint_msg.position.resize(12);\n    joint_msg.velocity.resize(12);\n\n    for(int i=0; i<12; i++)\n    {\n      joint_msg.name[i] = JOINT_NAME[LEFT_LEG_START_NUM + i];\n    }\n\n    ros::Rate r(200);\n    while(ros::ok())\n    {\n      joint_publish();\n      ros::spinOnce();\n      r.sleep();\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "c6cf114b26b5105dc28f19724ee040b1410ed841", "size": 7233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dyros_jet_ext_encoder/src/udp_client.cpp", "max_stars_repo_name": "DaegyuLim/dyros_jet", "max_stars_repo_head_hexsha": "969233737fb49b42d7fd9e5ec49694953baf4e7d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-02-02T07:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T13:06:54.000Z", "max_issues_repo_path": "dyros_jet_ext_encoder/src/udp_client.cpp", "max_issues_repo_name": "DonghyunSung-MS/dyros_jet_avatar", "max_issues_repo_head_hexsha": "32d04a2bfd55ad5d95cac09fbaa67799dab68fc8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-02-16T23:27:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T04:15:29.000Z", "max_forks_repo_path": "dyros_jet_ext_encoder/src/udp_client.cpp", "max_forks_repo_name": "DonghyunSung-MS/dyros_jet_avatar", "max_forks_repo_head_hexsha": "32d04a2bfd55ad5d95cac09fbaa67799dab68fc8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-02-06T23:34:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T20:50:27.000Z", "avg_line_length": 25.1145833333, "max_line_length": 135, "alphanum_fraction": 0.5707175446, "num_tokens": 2117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.3073580168652638, "lm_q1q2_score": 0.1798355348687964}}
{"text": "// Copyright (c) 2015-2019 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 \"read_assigner.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <algorithm>\n#include <limits>\n#include <stdexcept>\n#include <cassert>\n\n#include <boost/optional.hpp>\n\n#include \"utils/maths.hpp\"\n#include \"utils/kmer_mapper.hpp\"\n#include \"utils/random_select.hpp\"\n#include \"core/models/haplotype_likelihood_model.hpp\"\n#include \"core/models/error/error_model_factory.hpp\"\n\nnamespace octopus {\n\nnamespace {\n\nusing HaplotypeLikelihoods = std::vector<std::vector<double>>;\n\nauto vectorise(const Genotype<Haplotype>& genotype, const HaplotypeProbabilityMap& priors)\n{\n    std::vector<double> result(genotype.ploidy());\n    std::transform(std::cbegin(genotype), std::cend(genotype), std::begin(result),\n                   [&] (const auto& haplotype) { return priors.at(haplotype); });\n    return result;\n}\n\nauto get_priors(const Genotype<Haplotype>& genotype, const HaplotypeProbabilityMap& log_priors)\n{\n    if (log_priors.empty()) {\n        return std::vector<double>(genotype.ploidy());\n    } else {\n        return vectorise(genotype, log_priors);\n    }\n}\n\nvoid find_map_haplotypes(const Genotype<Haplotype>& genotype, const unsigned read,\n                         const HaplotypeLikelihoods& likelihoods, const std::vector<double>& log_priors,\n                         std::vector<unsigned>& result)\n{\n    assert(result.empty());\n    auto max_likelihood = std::numeric_limits<double>::lowest();\n    for (unsigned k {0}; k < genotype.ploidy(); ++k) {\n        const auto curr = likelihoods[k][read] + log_priors[k];\n        if (maths::almost_equal(curr, max_likelihood)) {\n            result.push_back(k);\n        } else if (curr > max_likelihood) {\n            result.assign({k});\n            max_likelihood = curr;\n        }\n    }\n    if (result.empty()) {\n        result.resize(genotype.ploidy());\n        std::iota(std::begin(result), std::end(result), 0);\n    }\n}\n\ntemplate <typename Map, typename Aligned, typename Ambiguous>\nvoid calculate_support(Map& result,\n                       const Genotype<Haplotype>& genotype,\n                       const std::vector<Aligned>& reads,\n                       const std::vector<double>& log_priors,\n                       const HaplotypeLikelihoods& likelihoods,\n                       boost::optional<Ambiguous&> ambiguous,\n                       const AssignmentConfig& config)\n{\n    std::vector<unsigned> top {};\n    top.reserve(genotype.ploidy());\n    std::vector<std::shared_ptr<Haplotype>> haplotype_ptrs {};\n    if (config.ambiguous_record != AssignmentConfig::AmbiguousRecord::read_only) {\n        haplotype_ptrs.resize(genotype.ploidy());\n    }\n    for (unsigned i {0}; i < reads.size(); ++i) {\n        const auto& read = reads[i];\n        find_map_haplotypes(genotype, i, likelihoods, log_priors, top);\n        if (top.size() == 1) {\n            result[genotype[top.front()]].push_back(read);\n        } else {\n            using UA = AssignmentConfig::AmbiguousAction;\n            switch (config.ambiguous_action) {\n                case UA::first:\n                    result[genotype[top.front()]].push_back(read);\n                    break;\n                case UA::all: {\n                    for (auto idx : top) result[genotype[idx]].push_back(read);\n                    break;\n                }\n                case UA::random: {\n                    result[genotype[random_select(top)]].push_back(read);\n                    break;\n                }\n                case UA::drop:\n                default:\n                    break;\n            }\n            if (ambiguous) {\n                ambiguous->emplace_back(read);\n                if (config.ambiguous_record == AssignmentConfig::AmbiguousRecord::haplotypes\n                    || (config.ambiguous_record == AssignmentConfig::AmbiguousRecord::haplotypes_if_three_or_more_options && top.size() >= 3)) {\n                    ambiguous->back().haplotypes.emplace();\n                    ambiguous->back().haplotypes->reserve(top.size());\n                    for (auto idx : top) {\n                        if (!haplotype_ptrs[idx]) haplotype_ptrs[idx] = std::make_shared<Haplotype>(genotype[idx]);\n                        ambiguous->back().haplotypes->push_back(haplotype_ptrs[idx]);\n                    }\n                }\n            }\n        }\n        top.clear();\n    }\n}\n\nauto calculate_support(const Genotype<Haplotype>& genotypes,\n                       const std::vector<AlignedRead>& reads,\n                       const std::vector<double>& log_priors,\n                       const HaplotypeLikelihoods& likelihoods,\n                       boost::optional<AmbiguousReadList&> ambiguous,\n                       const AssignmentConfig& config)\n{\n    HaplotypeSupportMap result {};\n    calculate_support(result, genotypes, reads, log_priors, likelihoods, ambiguous, config);\n    return result;\n}\n\nauto calculate_support(const Genotype<Haplotype>& genotype,\n                       const std::vector<AlignedTemplate>& reads,\n                       const std::vector<double>& log_priors,\n                       const HaplotypeLikelihoods& likelihoods,\n                       boost::optional<AmbiguousTemplateList&> ambiguous,\n                       const AssignmentConfig& config)\n{\n    HaplotypeTemplateSupportMap result {};\n    calculate_support(result, genotype, reads, log_priors, likelihoods, ambiguous, config);\n    return result;\n}\n\ntemplate <typename MappableTp>\nGenomicRegion::Size estimate_max_indel_size_helper(const MappableTp& mappable)\n{\n    const auto p = std::minmax({region_size(mappable), static_cast<GenomicRegion::Size>(sequence_size(mappable))});\n    return p.second - p.first;\n}\n\nGenomicRegion::Size estimate_max_indel_size_helper(const AlignedTemplate& reads)\n{\n    return std::accumulate(std::cbegin(reads), std::cend(reads), GenomicRegion::Size {0},\n                           [] (auto curr, const auto& read) { return curr + estimate_max_indel_size_helper(read); });\n}\n\ntemplate <typename Range>\nauto estimate_max_indel_size(const Range& mappables)\n{\n    GenomicRegion::Size result {0};\n    for (const auto& mappable : mappables) {\n        result = std::max(result, estimate_max_indel_size_helper(mappable));\n    }\n    return result;\n}\n\nauto compute_read_hashes(const std::vector<AlignedRead>& reads)\n{\n    static constexpr unsigned char mapperKmerSize {6};\n    std::vector<KmerPerfectHashes> result {};\n    result.reserve(reads.size());\n    std::transform(std::cbegin(reads), std::cend(reads), std::back_inserter(result),\n                   [=] (const AlignedRead& read) { return compute_kmer_hashes<mapperKmerSize>(read.sequence()); });\n    return result;\n}\n\nauto compute_read_hashes(const std::vector<AlignedTemplate>& templates)\n{\n    static constexpr unsigned char mapperKmerSize {6};\n    std::vector<std::vector<KmerPerfectHashes>> result {};\n    result.reserve(templates.size());\n    for (const auto& reads : templates) {\n        std::vector<KmerPerfectHashes> hashes {};\n        hashes.reserve(reads.size());\n        std::transform(std::cbegin(reads), std::cend(reads), std::back_inserter(hashes),\n                       [=] (const AlignedRead& read) { return compute_kmer_hashes<mapperKmerSize>(read.sequence()); });\n        result.push_back(std::move(hashes));\n    }\n    return result;\n}\n\nauto expand_for_alignment(const Haplotype& haplotype, const GenomicRegion& reads_region,\n                          const GenomicRegion::Size indel_factor, const HaplotypeLikelihoodModel& model)\n{\n    const auto min_flank_pad = 2 * model.pad_requirement();\n    const auto& haplotype_region = mapped_region(haplotype);\n    unsigned min_lhs_expansion {min_flank_pad}, min_rhs_expansion {min_flank_pad};\n    if (begins_before(reads_region, haplotype_region)) {\n        min_lhs_expansion += begin_distance(reads_region, haplotype_region);\n    }\n    if (ends_before(haplotype_region, reads_region)) {\n        min_rhs_expansion += end_distance(haplotype_region, reads_region);\n    }\n    const auto min_expansion = std::max(min_lhs_expansion, min_rhs_expansion) + indel_factor;\n    return expand(haplotype, min_expansion);\n}\n\nauto map_query_to_target_helper(const KmerPerfectHashes& query, const KmerHashTable& target,\n                                MappedIndexCounts& mapping_counts)\n{\n    return map_query_to_target(query, target, mapping_counts);\n}\n\nstd::vector<std::vector<std::size_t>>\nmap_query_to_target_helper(const std::vector<KmerPerfectHashes>& queries, const KmerHashTable& target,\n                           MappedIndexCounts& mapping_counts)\n{\n    std::vector<std::vector<std::size_t>> result {};\n    result.reserve(queries.size());\n    for (const auto& query : queries) {\n        result.push_back(map_query_to_target(query, target, mapping_counts));\n        reset_mapping_counts(mapping_counts);\n    }\n    return result;\n}\n\ntemplate <typename Container>\nauto calculate_likelihoods(const Genotype<Haplotype>& genotype,\n                           const Container& reads,\n                           HaplotypeLikelihoodModel& model)\n{\n    const auto reads_region = encompassing_region(reads);\n    const auto read_hashes = compute_read_hashes(reads);\n    static constexpr unsigned char mapperKmerSize {6};\n    auto haplotype_hashes = init_kmer_hash_table<mapperKmerSize>();\n    HaplotypeLikelihoods result {};\n    result.reserve(genotype.ploidy());\n    const auto indel_factor = estimate_max_indel_size(genotype) + estimate_max_indel_size(reads);\n    for (const auto& haplotype : genotype) {\n        const auto expanded_haplotype = expand_for_alignment(haplotype, reads_region, indel_factor, model);\n        populate_kmer_hash_table<mapperKmerSize>(expanded_haplotype.sequence(), haplotype_hashes);\n        auto haplotype_mapping_counts = init_mapping_counts(haplotype_hashes);\n        model.reset(expanded_haplotype);\n        std::vector<double> likelihoods(reads.size());\n        std::transform(std::cbegin(reads), std::cend(reads), std::cbegin(read_hashes), std::begin(likelihoods),\n                       [&] (const auto& read, const auto& read_hash) {\n                           auto mapping_positions = map_query_to_target_helper(read_hash, haplotype_hashes, haplotype_mapping_counts);\n                           reset_mapping_counts(haplotype_mapping_counts);\n                           return model.evaluate(read, mapping_positions);\n                       });\n        clear_kmer_hash_table(haplotype_hashes);\n        result.push_back(std::move(likelihoods));\n    }\n    return result;\n}\n\ntemplate <typename ReadType, typename AmbiguousReadListType>\nauto\ncompute_haplotype_support_helper2(const Genotype<Haplotype>& genotype,\n                                  const std::vector<ReadType>& reads,\n                                  const HaplotypeProbabilityMap& log_priors,\n                                  HaplotypeLikelihoodModel model,\n                                  boost::optional<AmbiguousReadListType&> ambiguous,\n                                  AssignmentConfig config)\n{\n    assert(genotype.ploidy() > 1);\n    const auto priors = get_priors(genotype, log_priors);\n    const auto likelihoods = calculate_likelihoods(genotype, reads, model);\n    return calculate_support(genotype, reads, priors, likelihoods, ambiguous, config);\n}\n\ntemplate <typename ReadType, typename AmbiguousReadListType>\nauto\ncompute_haplotype_support_helper(const Genotype<Haplotype>& genotype,\n                                 const std::vector<ReadType>& reads,\n                                 const HaplotypeProbabilityMap& log_priors,\n                                 HaplotypeLikelihoodModel model,\n                                 boost::optional<AmbiguousReadListType&> ambiguous,\n                                 AssignmentConfig config)\n{\n    if (is_max_zygosity(genotype)) {\n        return compute_haplotype_support_helper2(genotype, reads, log_priors, std::move(model), ambiguous, std::move(config));\n    } else {\n        return compute_haplotype_support_helper2(collapse(genotype), reads, log_priors, std::move(model), ambiguous, std::move(config));\n    }\n}\n\n} // namespace\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          const HaplotypeProbabilityMap& log_priors,\n                          HaplotypeLikelihoodModel model,\n                          boost::optional<AmbiguousReadList&> ambiguous,\n                          AssignmentConfig config)\n{\n    if (!reads.empty()) {\n        if (is_heterozygous(genotype)) {\n            return compute_haplotype_support_helper(genotype, reads, log_priors, std::move(model), ambiguous, std::move(config));\n        } else if (config.ambiguous_action != AssignmentConfig::AmbiguousAction::drop) {\n            HaplotypeSupportMap result {};\n            result.emplace(genotype[0], reads);\n            return result;\n        }\n    }\n    return {};\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AmbiguousReadList& ambiguous,\n                          const HaplotypeProbabilityMap& log_priors,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, log_priors, model, ambiguous, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          HaplotypeLikelihoodModel model,\n                          AmbiguousReadList& ambiguous,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, ambiguous, {}, model, config);\n}\n\nstatic HaplotypeLikelihoodModel make_default_haplotype_likelihood_model()\n{\n    HaplotypeLikelihoodModel::Config config {};\n    config.max_indel_error = 8;\n    config.use_flank_state = false;\n    config.use_mapping_quality = false;\n    return {config};\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AmbiguousReadList& ambiguous,\n                          const HaplotypeProbabilityMap& log_priors,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, log_priors, model, ambiguous, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AmbiguousReadList& ambiguous,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, model, ambiguous, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          const HaplotypeProbabilityMap& log_priors,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, log_priors, model, boost::none, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, model, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, {}, std::move(model), boost::none, config);\n}\n\nHaplotypeSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedRead>& reads,\n                          AmbiguousReadList& ambiguous,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, std::move(model), ambiguous, config);\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          const HaplotypeProbabilityMap& log_priors,\n                          HaplotypeLikelihoodModel model,\n                          boost::optional<AmbiguousTemplateList&> ambiguous,\n                          AssignmentConfig config)\n{\n    if (!reads.empty()) {\n        if (is_heterozygous(genotype)) {\n            return compute_haplotype_support_helper(genotype, reads, log_priors, std::move(model), ambiguous, std::move(config));\n        } else if (config.ambiguous_action != AssignmentConfig::AmbiguousAction::drop) {\n            HaplotypeTemplateSupportMap result {};\n            result.emplace(genotype[0], reads);\n            return result;\n        }\n    }\n    return {};\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          AmbiguousTemplateList& ambiguous,\n                          const HaplotypeProbabilityMap& log_priors,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, log_priors, model, ambiguous, config);\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          HaplotypeLikelihoodModel model,\n                          AmbiguousTemplateList& ambiguous,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, ambiguous, {}, model, config);\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          AmbiguousTemplateList& ambiguous,\n                          const HaplotypeProbabilityMap& log_priors,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, log_priors, model, ambiguous, config);\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          AmbiguousTemplateList& ambiguous,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, model, ambiguous, config);\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          const HaplotypeProbabilityMap& log_priors,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, log_priors, model, boost::none, config);\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          AssignmentConfig config)\n{\n    auto model = make_default_haplotype_likelihood_model();\n    return compute_haplotype_support(genotype, reads, model, config);\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, {}, std::move(model), boost::none, config);\n}\n\nHaplotypeTemplateSupportMap\ncompute_haplotype_support(const Genotype<Haplotype>& genotype,\n                          const std::vector<AlignedTemplate>& reads,\n                          AmbiguousTemplateList& ambiguous,\n                          HaplotypeLikelihoodModel model,\n                          AssignmentConfig config)\n{\n    return compute_haplotype_support(genotype, reads, std::move(model), ambiguous, config);\n}\n\nAlleleSupportMap\ncompute_allele_support(const std::vector<Allele>& alleles, const HaplotypeSupportMap& haplotype_support)\n{\n    return compute_allele_support(alleles, haplotype_support,\n                                  [] (const Haplotype& haplotype, const Allele& allele) {\n                                      return haplotype.includes(allele);\n                                  });\n}\n\nauto copy_included(const std::vector<Allele>& alleles, const Haplotype& haplotype)\n{\n    std::vector<Allele> result {};\n    result.reserve(alleles.size());\n    std::copy_if(std::cbegin(alleles), std::cend(alleles), std::back_inserter(result),\n                [&] (const auto& allele) { return haplotype.includes(allele); });\n    return result;\n}\n\nstruct HaveDifferentAlleles\n{\n    bool operator()(const std::shared_ptr<Haplotype>& lhs, const std::shared_ptr<Haplotype>& rhs) const\n    {\n        const auto lhs_includes = copy_included(alleles, *lhs);\n        const auto rhs_includes = copy_included(alleles, *rhs);\n        return lhs_includes != rhs_includes;\n    }\n    HaveDifferentAlleles(const std::vector<Allele>& alleles) : alleles {alleles} {}\n    const std::vector<Allele>& alleles;\n};\n\nbool have_common_alleles(const std::vector<std::shared_ptr<Haplotype>>& haplotypes, const std::vector<Allele>& alleles)\n{\n    return std::adjacent_find(std::cbegin(haplotypes), std::cend(haplotypes), HaveDifferentAlleles {alleles}) == std::cend(haplotypes);\n}\n\nvoid sort_and_merge(std::deque<AlignedReadConstReference>& src, ReadRefSupportSet& dst)\n{\n    std::sort(std::begin(src), std::end(src));\n    auto itr = dst.insert(std::end(dst), std::begin(src), std::end(src));\n    std::inplace_merge(std::begin(dst), itr, std::end(dst));\n}\n\nstd::size_t\ntry_assign_ambiguous_reads_to_alleles(const std::vector<Allele>& alleles,\n                                      const AmbiguousReadList& ambiguous_reads,\n                                      AlleleSupportMap& allele_support)\n{\n    std::size_t num_assigned {0};\n    std::unordered_map<Allele, std::deque<AlignedReadConstReference>> assigned {};\n    assigned.reserve(alleles.size());\n    for (const auto& ambiguous_read : ambiguous_reads) {\n        if (ambiguous_read.haplotypes && have_common_alleles(*ambiguous_read.haplotypes, alleles)) {\n            const auto supported_alleles = copy_included(alleles, *ambiguous_read.haplotypes->front());\n            for (const auto& allele : supported_alleles) {\n                if (overlaps(ambiguous_read, allele)) {\n                    assigned[allele].emplace_back(ambiguous_read.read);\n                }\n            }\n        }\n    }\n    for (auto& p : assigned) sort_and_merge(p.second, allele_support[p.first]);\n    return num_assigned;\n}\n\nAlleleSupportMap\ncompute_allele_support(const std::vector<Allele>& alleles,\n                       const HaplotypeSupportMap& haplotype_support,\n                       const AmbiguousReadList& ambiguous_reads)\n{\n    auto result = compute_allele_support(alleles, haplotype_support);\n    try_assign_ambiguous_reads_to_alleles(alleles, ambiguous_reads, result);\n    return result;\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "d71dc68fec2ddd01eb5152d7e9b40f5ae811c95d", "size": 23965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/tools/read_assigner.cpp", "max_stars_repo_name": "gunjanbaid/octopus", "max_stars_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "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/tools/read_assigner.cpp", "max_issues_repo_name": "gunjanbaid/octopus", "max_issues_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_issues_repo_licenses": ["MIT"], "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/tools/read_assigner.cpp", "max_forks_repo_name": "gunjanbaid/octopus", "max_forks_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_forks_repo_licenses": ["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.7508710801, "max_line_length": 144, "alphanum_fraction": 0.6424786146, "num_tokens": 5067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.1798355274443441}}
{"text": "#ifndef CUTSIM_H\n#define CUTSIM\n#include <QObject>\n\n#include <string>\n#include <iostream>\n#include <cmath>\n#include <vector>\n\n\n#include <boost/bind.hpp>\n\n#include <opencamlib/point.hpp>\n#include <opencamlib/triangle.hpp>\n#include <opencamlib/numeric.hpp>\n#include <opencamlib/octree.hpp>\n#include <opencamlib/octnode.hpp>\n\n#include <opencamlib/volume.hpp>\n#include <opencamlib/marching_cubes.hpp>\n#include <opencamlib/gldata.hpp>\n\n/// a Cutsim stores an Octree stock model, uses an iso-surface extraction\n/// algorithm to generate surface triangles, and communicates with\n/// the corresponding GLData surface which is used for rendering\nclass Cutsim : public QObject {\n    Q_OBJECT\n\npublic:\n    // std::cout << ocl::revision() << \"\\n\";\n    // std::cout << \" Experimental C++ cutting simulation.\\n\";\n    // Octree(root_scale, max_depth, cp)\n    Cutsim () {\n        ocl::Point octree_center(0,0,0);\n        unsigned int max_depth = 7;\n        tree = new ocl::Octree(10.0, max_depth, octree_center );\n        std::cout << \" tree before init: \" << tree->str() << \"\\n\";\n        \n        std::cout << \"running init(3) on the octree. this splits the cube three times. \\n\";\n        std::cout << \"we go from 1 cube -> 8 -> 64 -> 512 cubes \\n\";\n        tree->init(3u);\n        tree->debug=false;\n        std::cout << \" tree after init: \" << tree->str() << \"\\n\";\n        ocl::CubeVolume cube;\n        cube.side = 3.5;\n        cube.calcBB();\n        \n        //ocl::PlaneVolume px_plus(true, 0u, -7);\n        //ocl::PlaneVolume px_minus(false, 0u, 7);\n        \n        //ocl::PlaneVolume py_plus(true, 1u, -7);\n        //ocl::PlaneVolume py_minus(false, 1u, 7);\n        \n        //ocl::PlaneVolume pz_plus(true, 2u, -7);\n        //ocl::PlaneVolume pz_minus(false, 2u, 7);\n        \n        tree->diff_negative( &cube);\n        //tree->diff_negative( &px_plus  );\n        //tree->diff_negative( &px_minus );\n        //tree->diff_negative( &py_plus  );\n        //tree->diff_negative( &py_minus );\n        //tree->diff_negative( &pz_plus  );\n        //tree->diff_negative( &pz_minus );\n        std::cout << \" tree after stock-cut: \" << tree->str() << \"\\n\";\n        mc = new ocl::MarchingCubes();\n    } \n    void setGLData(ocl::GLData* gldata) {\n        // this is the GLData that corresponds to the tree\n        g = gldata;\n        g->setTriangles(); // mc: triangles, dual_contour: quads\n        g->setPosition(0,0,0); // position offset (?used)\n        g->setUsageDynamicDraw();\n    }\n    void updateGL() {\n        // traverse the octree and update the GLData correspondingly\n        ocl::Octnode* root = tree->getRoot();\n        updateGL(root);\n    }\n    void updateGL(ocl::Octnode* current) {\n        // starting at current, update the isosurface\n        if ( current->isLeaf() && current->surface() && !current->valid() ) { \n            // this is a leaf and a surface-node\n            // std::vector<ocl::Triangle> node_tris = mc->mc_node(current);\n            BOOST_FOREACH(ocl::Triangle t, mc->mc_node(current) ) {\n                double r=1,gr=0,b=0;\n                std::vector<unsigned int> polyIndexes;\n                for (int m=0;m<3;++m) { // FOUR for quads\n                    //unsigned int vertexId =  g->addVertex( t.p[m].x, t.p[m].y, t.p[m].z, r,gr,b,\n                    //                        boost::bind(&ocl::Octnode::swapIndex, current, _1, _2)) ; // add vertex to GL\n                    unsigned int vertexId =  g->addVertex( t.p[m].x, t.p[m].y, t.p[m].z, r,gr,b, current) ;\n//                        boost::bind(&ocl::Octnode::swapIndex, current, _1, _2)) ; // add vertex to GL\n                                            \n                    g->setNormal( vertexId, t.n.x, t.n.y, t.n.z );\n                    polyIndexes.push_back( vertexId );\n                    current->addIndex( vertexId ); // associate node with vertex\n                }\n                g->addPolygon(polyIndexes); // add poly to GL\n                current->setValid(); // isosurface is now valid for this node!\n            }\n        } else if ( current->isLeaf() && !current->surface() && !current->valid() ) { //leaf, but no surface\n            // remove vertices, if any\n            BOOST_FOREACH(unsigned int vId, current->vertexSet ) {\n                g->removeVertex(vId);\n            }\n            // needed?? // current->clearIndex();\n            current->setValid();\n        }\n        else {\n            for (int m=0;m<8;++m) { // go deeper into tree, if !valid\n                if ( current->hasChild(m) && !current->valid() ) {\n                    updateGL(current->child[m]);\n                }\n            }\n        }\n    }\n    \n    void surf() {\n        // run mc on all nodes\n        // std::vector<Triangle> mc_node(const Octnode* node);\n        \n        tree->updateGL();\n        //tris = mc->mc_tree( tree ); // this gets ALL triangles from the tree and stores them here.\n        //std::cout << \" mc() got \" << tris.size() << \" triangles\\n\";\n    }\n    \n    //std::vector<ocl::Triangle> getTris() {\n    //    return tris;\n    //}\n    \npublic slots:\n    void cut() { // demo slot of doing a cutting operation on the tree with a volume.\n        std::cout << \" cut! called \\n\";\n        ocl::SphereOCTVolume s;\n        s.radius = 3;\n        s.center = ocl::Point(7,7,7);\n        s.calcBB();\n        //std::cout << \" before diff: \" << tree->str() << \"\\n\";\n        tree->diff_negative( &s );\n        //std::cout << \" AFTER diff: \" << tree->str() << \"\\n\";\n\n        updateGL();\n    }\nprivate:\n    ocl::MarchingCubes* mc; // simplest isosurface-extraction algorithm\n    std::vector<ocl::Triangle> tris; // do we need to store all tris here?? no!\n    ocl::Octree* tree; // this is the stock model\n    ocl::GLData* g; // this is the graphics object drawn on the screen\n};\n\n#endif\n", "meta": {"hexsha": "5a005c2abf228a0910d999e881f294c2985c31af", "size": 5771, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/attic/cutsim1/cutsim.hpp", "max_stars_repo_name": "JohnyEngine/CNC", "max_stars_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "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": "opencamlib/src/attic/cutsim1/cutsim.hpp", "max_issues_repo_name": "JohnyEngine/CNC", "max_issues_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "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": "opencamlib/src/attic/cutsim1/cutsim.hpp", "max_forks_repo_name": "JohnyEngine/CNC", "max_forks_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "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.2185430464, "max_line_length": 123, "alphanum_fraction": 0.5425402876, "num_tokens": 1550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.17977896082437378}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef subclone_model_hpp\n#define subclone_model_hpp\n\n#include <vector>\n#include <unordered_map>\n#include <utility>\n\n#include <boost/optional.hpp>\n\n#include \"config/common.hpp\"\n#include \"core/types/haplotype.hpp\"\n#include \"core/types/genotype.hpp\"\n#include \"core/types/cancer_genotype.hpp\"\n#include \"core/models/haplotype_likelihood_array.hpp\"\n#include \"exceptions/unimplemented_feature_error.hpp\"\n#include \"variational_bayes_mixture_model.hpp\"\n#include \"genotype_prior_model.hpp\"\n#include \"cancer_genotype_prior_model.hpp\"\n\nnamespace octopus { namespace model {\n\ntemplate <typename Genotype_, typename GenotypeIndex_, typename GenotypePriorModel_>\nclass SubcloneModelBase\n{\npublic:\n    struct AlgorithmParameters\n    {\n        unsigned max_iterations = 1000;\n        double epsilon          = 0.05;\n        unsigned max_seeds      = 12;\n        boost::optional<MemoryFootprint> target_max_memory = boost::none;\n    };\n    \n    struct Priors\n    {\n        using GenotypeMixturesDirichletAlphas   = std::vector<double>;\n        using GenotypeMixturesDirichletAlphaMap = std::unordered_map<SampleName, GenotypeMixturesDirichletAlphas>;\n        \n        const GenotypePriorModel_& genotype_prior_model;\n        GenotypeMixturesDirichletAlphaMap alphas;\n    };\n    \n    struct Latents\n    {\n        using GenotypeMixturesDirichletAlphas   = std::vector<double>;\n        using GenotypeMixturesDirichletAlphaMap = std::unordered_map<SampleName, GenotypeMixturesDirichletAlphas>;\n        using ProbabilityVector                 = std::vector<double>;\n        \n        ProbabilityVector genotype_probabilities;\n        GenotypeMixturesDirichletAlphaMap alphas;\n    };\n    \n    struct InferredLatents\n    {\n        Latents posteriors;\n        typename Latents::ProbabilityVector genotype_log_priors;\n        double approx_log_evidence;\n    };\n    \n    SubcloneModelBase() = delete;\n    \n    SubcloneModelBase(std::vector<SampleName> samples, Priors priors);\n    SubcloneModelBase(std::vector<SampleName> samples, Priors priors, AlgorithmParameters parameters);\n    \n    SubcloneModelBase(const SubcloneModelBase&)            = default;\n    SubcloneModelBase& operator=(const SubcloneModelBase&) = default;\n    SubcloneModelBase(SubcloneModelBase&&)                 = default;\n    SubcloneModelBase& operator=(SubcloneModelBase&&)      = default;\n    \n    ~SubcloneModelBase() = default;\n    \n    const Priors& priors() const noexcept;\n    \n    void prime(const std::vector<Haplotype>& haplotypes);\n    void unprime() noexcept;\n    bool is_primed() const noexcept;\n    \n    InferredLatents evaluate(const std::vector<Genotype_>& genotypes,\n                             const HaplotypeLikelihoodArray& haplotype_likelihoods) const;\n    \n    InferredLatents evaluate(const std::vector<Genotype_>& genotypes,\n                             const std::vector<GenotypeIndex_>& genotype_indices,\n                             const HaplotypeLikelihoodArray& haplotype_likelihoods) const;\n    \nprivate:\n    std::vector<SampleName> samples_;\n    Priors priors_;\n    AlgorithmParameters parameters_;\n    const std::vector<Haplotype>* haplotypes_;\n};\n\nusing SubcloneModel = SubcloneModelBase<Genotype<Haplotype>, GenotypeIndex, GenotypePriorModel>;\nusing SomaticSubcloneModel = SubcloneModelBase<CancerGenotype<Haplotype>, CancerGenotypeIndex, CancerGenotypePriorModel>;\n\ntemplate <typename G, typename GI, typename GPM>\nSubcloneModelBase<G, GI, GPM>::SubcloneModelBase(std::vector<SampleName> samples, Priors priors)\n: SubcloneModelBase {std::move(samples), std::move(priors), AlgorithmParameters {}}\n{}\n\ntemplate <typename G, typename GI, typename GPM>\nSubcloneModelBase<G, GI, GPM>::SubcloneModelBase(std::vector<SampleName> samples, Priors priors, AlgorithmParameters parameters)\n: samples_ {std::move(samples)}\n, priors_ {std::move(priors)}\n, parameters_ {parameters}\n{}\n\ntemplate <typename G, typename GI, typename GPM>\nconst typename SubcloneModelBase<G, GI, GPM>::Priors& SubcloneModelBase<G, GI, GPM>::priors() const noexcept\n{\n    return priors_;\n}\n\ntemplate <typename G, typename GI, typename GPM>\nvoid SubcloneModelBase<G, GI, GPM>::prime(const std::vector<Haplotype>& haplotypes)\n{\n    haplotypes_ = std::addressof(haplotypes);\n}\n\ntemplate <typename G, typename GI, typename GPM>\nvoid SubcloneModelBase<G, GI, GPM>::unprime() noexcept\n{\n    haplotypes_ = nullptr;\n}\n\ntemplate <typename G, typename GI, typename GPM>\nbool SubcloneModelBase<G, GI, GPM>::is_primed() const noexcept\n{\n    return haplotypes_;\n}\n\nnamespace detail {\n\ntemplate <typename GI>\nstruct IndexData\n{\n    const std::vector<GI>& genotype_indices;\n    const std::vector<Haplotype>* haplotypes;\n};\n\ntemplate <typename G, typename GI, typename GPM>\nauto evaluate_genotype_priors(const std::vector<G>& genotypes,\n                              const typename SubcloneModelBase<G, GI, GPM>::Priors& priors,\n                              const boost::optional<IndexData<GI>> index_data)\n{\n    if (index_data) {\n        return evaluate(index_data->genotype_indices, priors.genotype_prior_model);\n    } else {\n        return evaluate(genotypes, priors.genotype_prior_model);\n    }\n}\n\nstd::vector<LogProbabilityVector>\ngenerate_seeds(const std::vector<SampleName>& samples,\n               const std::vector<Genotype<Haplotype>>& genotypes,\n               const LogProbabilityVector& genotype_log_priors,\n               const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n               const SubcloneModel::Priors& priors,\n               std::size_t max_seeds,\n               boost::optional<IndexData<GenotypeIndex>> index_data = boost::none);\n\nstd::vector<LogProbabilityVector>\ngenerate_seeds(const std::vector<SampleName>& samples,\n               const std::vector<CancerGenotype<Haplotype>>& genotypes,\n               const LogProbabilityVector& genotype_log_priors,\n               const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n               const SomaticSubcloneModel::Priors& priors,\n               std::size_t max_seeds,\n               boost::optional<IndexData<CancerGenotypeIndex>> index_data = boost::none);\n\ntemplate <std::size_t K, typename G, typename GI, typename GPM>\nVBAlpha<K> flatten(const typename SubcloneModelBase<G, GI, GPM>::Priors::GenotypeMixturesDirichletAlphas& alpha)\n{\n    VBAlpha<K> result {};\n    std::copy_n(std::cbegin(alpha), K, std::begin(result));\n    return result;\n}\n\ntemplate <std::size_t K, typename G, typename GI, typename GPM>\nVBAlphaVector<K> flatten(const typename SubcloneModelBase<G, GI, GPM>::Priors::GenotypeMixturesDirichletAlphaMap& alphas,\n                         const std::vector<SampleName>& samples)\n{\n    VBAlphaVector<K> result(samples.size());\n    std::transform(std::cbegin(samples), std::cend(samples), std::begin(result),\n                   [&alphas] (const auto& sample) { return flatten<K, G, GI, GPM>(alphas.at(sample)); });\n    return result;\n}\n\ntemplate <std::size_t K>\nVBGenotype<K>\nflatten(const Genotype<Haplotype>& genotype, const SampleName& sample,\n        const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    VBGenotype<K> result {};\n    std::transform(std::cbegin(genotype), std::cend(genotype), std::begin(result),\n                   [&sample, &haplotype_likelihoods] (const Haplotype& haplotype)\n                   -> std::reference_wrapper<const VBReadLikelihoodArray::BaseType> {\n                       return std::cref(haplotype_likelihoods(sample, haplotype));\n                   });\n    return result;\n}\n\ntemplate <std::size_t K>\nauto copy_cref(const Genotype<Haplotype>& genotype, const SampleName& sample,\n               const HaplotypeLikelihoodArray& haplotype_likelihoods,\n               typename VBGenotype<K>::iterator result_itr)\n{\n    return std::transform(std::cbegin(genotype), std::cend(genotype), result_itr,\n                          [&sample, &haplotype_likelihoods] (const Haplotype& haplotype)\n                          -> std::reference_wrapper<const VBReadLikelihoodArray::BaseType> {\n                              return std::cref(haplotype_likelihoods(sample, haplotype));\n                          });\n}\n\ntemplate <std::size_t K>\nVBGenotype<K>\nflatten(const CancerGenotype<Haplotype>& genotype, const SampleName& sample,\n        const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    VBGenotype<K> result {};\n    assert(genotype.ploidy() == K);\n    auto itr = copy_cref<K>(genotype.germline(), sample, haplotype_likelihoods, std::begin(result));\n    copy_cref<K>(genotype.somatic(), sample, haplotype_likelihoods, itr);\n    return result;\n}\n\ntemplate <std::size_t K, typename G>\nVBGenotypeVector<K>\nflatten(const std::vector<G>& genotypes, const SampleName& sample,\n        const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    VBGenotypeVector<K> result(genotypes.size());\n    std::transform(std::cbegin(genotypes), std::cend(genotypes), std::begin(result),\n                   [&sample, &haplotype_likelihoods] (const auto& genotype) {\n                       return flatten<K>(genotype, sample, haplotype_likelihoods);\n                   });\n    return result;\n}\n\ntemplate <std::size_t K, typename G>\nVBReadLikelihoodMatrix<K>\nflatten(const std::vector<G>& genotypes,\n        const std::vector<SampleName>& samples,\n        const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    VBReadLikelihoodMatrix<K> result {};\n    result.reserve(samples.size());\n    std::transform(std::cbegin(samples), std::cend(samples), std::back_inserter(result),\n                   [&genotypes, &haplotype_likelihoods] (const auto& sample) {\n                       return flatten<K>(genotypes, sample, haplotype_likelihoods);\n                   });\n    return result;\n}\n\ntemplate <std::size_t K, typename G, typename GI, typename GPM>\nauto expand(VBAlpha<K>& alpha)\n{\n    return typename SubcloneModelBase<G, GI, GPM>::Latents::GenotypeMixturesDirichletAlphas(std::begin(alpha), std::end(alpha));\n}\n\ntemplate <std::size_t K, typename G, typename GI, typename GPM>\nauto expand(const std::vector<SampleName>& samples, VBAlphaVector<K>&& alphas)\n{\n    typename SubcloneModelBase<G, GI, GPM>::Latents::GenotypeMixturesDirichletAlphaMap result {};\n    std::transform(std::cbegin(samples), std::cend(samples), std::begin(alphas),\n                   std::inserter(result, std::begin(result)),\n                   [] (const auto& sample, auto&& vb_alpha) {\n                       return std::make_pair(sample, expand<K, G, GI, GPM>(vb_alpha));\n                   });\n    return result;\n}\n\ntemplate <std::size_t K, typename G, typename GI, typename GPM>\ntypename SubcloneModelBase<G, GI, GPM>::InferredLatents\nexpand(const std::vector<SampleName>& samples, VBLatents<K>&& inferred_latents, LogProbabilityVector genotype_log_priors, double evidence)\n{\n    typename SubcloneModelBase<G, GI, GPM>::Latents posterior_latents {std::move(inferred_latents.genotype_posteriors),\n                                                                       expand<K, G, GI, GPM>(samples, std::move(inferred_latents.alphas))};\n    return {std::move(posterior_latents), std::move(genotype_log_priors), evidence};\n}\n\ntemplate <std::size_t K, typename G, typename GI, typename GPM>\ntypename SubcloneModelBase<G, GI, GPM>::InferredLatents\nrun_variational_bayes_helper(const std::vector<SampleName>& samples,\n                             const std::vector<G>& genotypes,\n                             const typename SubcloneModelBase<G, GI, GPM>::Priors::GenotypeMixturesDirichletAlphaMap& prior_alphas,\n                             const LogProbabilityVector& genotype_log_priors,\n                             const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n                             const typename SubcloneModelBase<G, GI, GPM>::AlgorithmParameters& params,\n                             std::vector<LogProbabilityVector>&& seeds)\n{\n    VariationalBayesParameters vb_params {params.epsilon, params.max_iterations};\n    if (params.target_max_memory) {\n        const auto estimated_memory_default = estimate_memory_requirement<K>(samples, haplotype_log_likelihoods, genotypes.size(), vb_params);\n        if (estimated_memory_default > *params.target_max_memory) {\n            vb_params.save_memory = true;\n        }\n    }\n    const auto vb_prior_alphas = flatten<K, G, GI, GPM>(prior_alphas, samples);\n    const auto log_likelihoods = flatten<K>(genotypes, samples, haplotype_log_likelihoods);\n    auto p = octopus::model::run_variational_bayes(vb_prior_alphas, genotype_log_priors, log_likelihoods, vb_params, std::move(seeds));\n    return expand<K, G, GI, GPM>(samples, std::move(p.first), std::move(genotype_log_priors), p.second);\n}\n\ntemplate <typename G, typename GI, typename GPM>\ntypename SubcloneModelBase<G, GI, GPM>::InferredLatents\nrun_variational_bayes_helper(const std::vector<SampleName>& samples,\n                             const std::vector<G>& genotypes,\n                             const typename SubcloneModelBase<G, GI, GPM>::Priors::GenotypeMixturesDirichletAlphaMap& prior_alphas,\n                             LogProbabilityVector genotype_log_priors,\n                             const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n                             const typename SubcloneModelBase<G, GI, GPM>::AlgorithmParameters& params,\n                             std::vector<LogProbabilityVector>&& seeds)\n{\n    using std::move;\n    switch (genotypes.front().ploidy()) {\n        case 1: return run_variational_bayes_helper<1, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 2: return run_variational_bayes_helper<2, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 3: return run_variational_bayes_helper<3, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 4: return run_variational_bayes_helper<4, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 5: return run_variational_bayes_helper<5, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 6: return run_variational_bayes_helper<6, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 7: return run_variational_bayes_helper<7, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 8: return run_variational_bayes_helper<8, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 9: return run_variational_bayes_helper<9, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                   haplotype_log_likelihoods, params, move(seeds));\n        case 10: return run_variational_bayes_helper<10, G, GI, GPM>(samples, genotypes, prior_alphas, move(genotype_log_priors),\n                                                                     haplotype_log_likelihoods, params, move(seeds));\n        default: throw UnimplementedFeatureError {\"ploidies above 10\", \"SubcloneModel\"};\n    }\n}\n\ntemplate <typename G, typename GI, typename GPM>\ntypename SubcloneModelBase<G, GI, GPM>::InferredLatents\nrun_variational_bayes(const std::vector<SampleName>& samples,\n                      const std::vector<G>& genotypes,\n                      const typename SubcloneModelBase<G, GI, GPM>::Priors& priors,\n                      const HaplotypeLikelihoodArray& haplotype_log_likelihoods,\n                      const typename SubcloneModelBase<G, GI, GPM>::AlgorithmParameters& params,\n                      boost::optional<IndexData<GI>> index_data = boost::none)\n{\n    auto genotype_log_priors = evaluate_genotype_priors<G, GI, GPM>(genotypes, priors, index_data);\n    auto seeds = generate_seeds(samples, genotypes, genotype_log_priors, haplotype_log_likelihoods, priors, params.max_seeds, index_data);\n    return run_variational_bayes_helper<G, GI, GPM>(samples, genotypes, priors.alphas, std::move(genotype_log_priors),\n                                                    haplotype_log_likelihoods, params, std::move(seeds));\n}\n\n} // namespace detail\n\ntemplate <typename G, typename GI, typename GPM>\ntypename SubcloneModelBase<G, GI, GPM>::InferredLatents\nSubcloneModelBase<G, GI, GPM>::evaluate(const std::vector<G>& genotypes,\n                                        const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(!genotypes.empty());\n    return detail::run_variational_bayes<G, GI, GPM>(samples_, genotypes, priors_, haplotype_likelihoods, parameters_);\n}\n\ntemplate <typename G, typename GI, typename GPM>\ntypename SubcloneModelBase<G, GI, GPM>::InferredLatents\nSubcloneModelBase<G, GI, GPM>::evaluate(const std::vector<G>& genotypes,\n                                        const std::vector<GI>& genotype_indices,\n                                        const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(!genotypes.empty());\n    assert(genotypes.size() == genotype_indices.size());\n    const detail::IndexData<GI> index_data {genotype_indices, haplotypes_};\n    return detail::run_variational_bayes<G, GI, GPM>(samples_, genotypes, priors_, haplotype_likelihoods, parameters_, index_data);\n}\n\n} // namespace model\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "c94a8b6f2918adef12b21c2f77a5e3bf9495a7cb", "size": 18253, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/genotype/subclone_model.hpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "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/genotype/subclone_model.hpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/genotype/subclone_model.hpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.4103896104, "max_line_length": 142, "alphanum_fraction": 0.6678354243, "num_tokens": 4306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1797789488089663}}
{"text": "#include <boost/python.hpp>\n#include <string>\n#include \"inf_def_visitor.hxx\"\n\n#include <opengm/inference/dynamicprogramming.hxx>\n#include <param/dynamic_programming_param.hxx>\n\n\n#include <opengm/python/opengmpython.hxx>\n#include <opengm/python/converter.hxx>\n#include <opengm/python/numpyview.hxx>\n#include <opengm/python/pythonfunction.hxx>\n\n\n#if PY_MAJOR_VERSION == 2\nstatic void wrap_import_array() {\n    import_array();\n}\n#else\nstatic void * wrap_import_array() {\n    import_array();\n}\n#endif\n\n\ntemplate<class GM,class ACC>\nvoid export_dynp(){\n   using namespace boost::python;\n   wrap_import_array();\n   append_subnamespace(\"solver\");\n   // setup \n   InfSetup setup;\n   setup.algType     = \"dynamic-programming\";\n   setup.guarantees  = \"global optimal\";\n   setup.examples    = \">>> inference = opengm.inference.DynamicProgramming(gm=gm,accumulator='minimizer')\\n\"\n                       \"\\n\\n\"; \n   setup.limitations = \"graphical model must be a tree / must not have loops\";\n\n   // export parameter\n   typedef opengm::DynamicProgramming<GM, ACC>  PyDynamicProgramming;\n   exportInfParam<PyDynamicProgramming>(\"_DynamicProgramming\");\n   // export inference\n   class_< PyDynamicProgramming>(\"_DynamicProgramming\",init<const GM & >())  \n   .def(InfSuite<PyDynamicProgramming,false>(std::string(\"DynamicProgramming\"),setup))\n   ;\n}\n\ntemplate void export_dynp<opengm::python::GmAdder,opengm::Minimizer>();\ntemplate void export_dynp<opengm::python::GmAdder,opengm::Maximizer>();\ntemplate void export_dynp<opengm::python::GmMultiplier,opengm::Minimizer>();\ntemplate void export_dynp<opengm::python::GmMultiplier,opengm::Maximizer>();\n", "meta": {"hexsha": "4ec6c22ba9b05fff9d404fb203e63308b72bb073", "size": 1632, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/interfaces/python/opengm/inference/pyDynp.cxx", "max_stars_repo_name": "lijx10/opengm", "max_stars_repo_head_hexsha": "3ee326e544a54d92e2981f1dd65ca9949b93c220", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-10T08:01:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T03:01:05.000Z", "max_issues_repo_path": "src/interfaces/python/opengm/inference/pyDynp.cxx", "max_issues_repo_name": "lijx10/opengm", "max_issues_repo_head_hexsha": "3ee326e544a54d92e2981f1dd65ca9949b93c220", "max_issues_repo_licenses": ["MIT"], "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/interfaces/python/opengm/inference/pyDynp.cxx", "max_forks_repo_name": "lijx10/opengm", "max_forks_repo_head_hexsha": "3ee326e544a54d92e2981f1dd65ca9949b93c220", "max_forks_repo_licenses": ["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.3846153846, "max_line_length": 109, "alphanum_fraction": 0.7359068627, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.17976838227741557}}
{"text": "#include <cdrm_legged/leg_config_generator.h>\n#include <cdrm_legged/leg_model.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <cdrm/cdrm.h>\n#include <eigen_conversions/eigen_msg.h>\n#include <moveit/move_group_interface/move_group_interface.h>\n#include <moveit/planning_scene_monitor/planning_scene_monitor.h>\n#include <ros/ros.h>\n#include <visualization_msgs/InteractiveMarkerUpdate.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\nstatic const std::string TOPIC = \"/rviz_moveit_motion_planning_display/robot_interaction_interactive_marker_topic/update\";\nstatic const std::string MARKER_NAME = \"JJ:start_base_link\";\n\nclass ContactGeneratorNode\n{\npublic:\n  ContactGeneratorNode()\n    : nh_(\"move_group\")\n    , subscriber_(nh_.subscribe(TOPIC, 100, &ContactGeneratorNode::onMarkerUpdated, this))\n    , publisher_(nh_.advertise<visualization_msgs::MarkerArray>(\"rviz_contacts\", 0))\n    , psm_(new planning_scene_monitor::PlanningSceneMonitor(\"robot_description\"))\n  {\n    psm_->startSceneMonitor();\n\n    loadCdrms();\n    createLegModels();\n  }\n\nprivate:\n  bool loadCdrms()\n  {\n    XmlRpc::XmlRpcValue filenames;\n\n    if (!nh_.getParam(\"cdrms\", filenames))\n    {\n      ROS_ERROR(\"No CDRM filenames specified to load on the parameter server\");\n      return false;\n    }\n\n    cdrms_.clear();\n\n    for (auto it = filenames.begin(); it != filenames.end(); ++it)\n    {\n      const auto &filename = static_cast<std::string &>(it->second);\n      std::unique_ptr<cdrm::Cdrm> cdrm(new cdrm::Cdrm);\n\n      ROS_INFO_STREAM(\"Loading CDRM '\" << it->first << \"' from '\" << filename.c_str() << \"'...\");\n\n      if (cdrm->load(filename))\n        cdrms_[it->first] = std::move(cdrm);\n      else\n        ROS_WARN_STREAM(\"Could not load CDRM '\" << it->first << \"'\");\n    }\n\n    return true;\n  }\n\n  void createLegModels()\n  {\n    planning_scene_monitor::LockedPlanningSceneRW lock(psm_);\n    const auto &robot_model = lock->getRobotModel();\n\n    for (const auto &group_name : robot_model->getJointModelGroupNames())\n    {\n      XmlRpc::XmlRpcValue legs_value;\n\n      if (!nh_.getParam(\"planner_configs/\" + group_name + \"/legs\", legs_value))\n        continue;\n\n      for (auto it = legs_value.begin(); it != legs_value.end(); ++it)\n      {\n        const auto &leg_name = it->first;\n        const auto *leg_group = robot_model->getJointModelGroup(leg_name);\n\n        if (!leg_group)\n        {\n          ROS_WARN(\"Could not find leg joint model group '%s'\", leg_name.c_str());\n          continue;\n        }\n\n        const auto &cdrm_name = static_cast<std::string &>(it->second);\n        const auto cdrm_it = cdrms_.find(cdrm_name);\n\n        if (cdrm_it != cdrms_.end())\n          leg_models_.emplace_back(robot_model, leg_group, cdrm_it->second.get());\n        else\n          ROS_WARN(\"No CDRM '%s' for leg '%s' in group '%s'\", cdrm_name.c_str(), leg_name.c_str(), group_name.c_str());\n      }\n\n      ROS_INFO(\"Created leg models for '%s'\", group_name.c_str());\n    }\n  }\n\n  void onMarkerUpdated(const visualization_msgs::InteractiveMarkerUpdate::ConstPtr &msg)\n  {\n    for (const auto &pose : msg->poses)\n    {\n      if (pose.name != MARKER_NAME)\n        continue;\n\n      Eigen::Isometry3d updated_tf;\n      tf::poseMsgToEigen(pose.pose, updated_tf);\n\n      if (body_tf_.isApprox(updated_tf))\n        continue;\n\n      visualization_msgs::MarkerArray marker_array;\n\n      planning_scene_monitor::LockedPlanningSceneRW lock(psm_);\n      cdrm_legged::LegConfigGenerator generator(lock);\n\n      for (std::size_t i = 0; i < leg_models_.size(); ++i)\n      {\n        const auto &model = leg_models_[i];\n        const auto contacts = generator.generateLegConfigs(updated_tf, model);\n\n        visualization_msgs::Marker marker;\n        marker.header.frame_id = \"odom\";\n        marker.header.stamp = ros::Time();\n        marker.id = i;\n        marker.type = visualization_msgs::Marker::SPHERE_LIST;\n        marker.action = visualization_msgs::Marker::ADD;\n        marker.scale.x = 0.02;\n        marker.scale.y = 0.02;\n        marker.scale.z = 0.02;\n        marker.color.a = 1.0;\n        marker.color.r = 0.5 + (0.25 * i);\n\n        for (const auto vertex : contacts.contacts_)\n        {\n          const Eigen::VectorXd &q = model.cdrm_->getVertexConfig(vertex);\n          const Eigen::Isometry3d contact_tf = updated_tf * model.tf_ * model.getTipTransform(q);\n\n          geometry_msgs::Point point;\n          point.x = contact_tf.translation().x();\n          point.y = contact_tf.translation().y();\n          point.z = contact_tf.translation().z();\n          marker.points.push_back(point);\n        }\n\n        marker_array.markers.push_back(marker);\n      }\n\n      body_tf_ = updated_tf;\n\n      publisher_.publish(marker_array);\n\n      return;\n    }\n  }\n\n  ros::NodeHandle nh_;\n  ros::Subscriber subscriber_;\n  ros::Publisher publisher_;\n  planning_scene_monitor::PlanningSceneMonitorPtr psm_;\n  Eigen::Isometry3d body_tf_;\n\n  std::map<std::string, std::unique_ptr<cdrm::Cdrm>> cdrms_;\n  std::vector<cdrm_legged::LegModel> leg_models_;\n};\n\nint main(int argc, char *argv[])\n{\n  ros::init(argc, argv, \"contact_generator_node\");\n  ContactGeneratorNode node;\n  ros::spin();\n}\n", "meta": {"hexsha": "b141417ee0158beb399d8befa54b16aed94f6af9", "size": 5187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cdrm_legged/src/contact_generator_node.cpp", "max_stars_repo_name": "ajshort/cdrm", "max_stars_repo_head_hexsha": "d5140740555a56c1e17518c3f6ab882275c530d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-04-19T13:03:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-10T04:43:52.000Z", "max_issues_repo_path": "cdrm_legged/src/contact_generator_node.cpp", "max_issues_repo_name": "ajshort/cdrm", "max_issues_repo_head_hexsha": "d5140740555a56c1e17518c3f6ab882275c530d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T08:25:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-31T00:14:11.000Z", "max_forks_repo_path": "cdrm_legged/src/contact_generator_node.cpp", "max_forks_repo_name": "ajshort/cdrm", "max_forks_repo_head_hexsha": "d5140740555a56c1e17518c3f6ab882275c530d7", "max_forks_repo_licenses": ["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.9826589595, "max_line_length": 122, "alphanum_fraction": 0.655484866, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.17976838227741554}}
{"text": "#include <iostream>\n#include \"glog/logging.h\"\n#include <time.h>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <boost/thread/thread.hpp>\n#include <pcl/common/common_headers.h>\n#include <pcl/features/normal_3d.h> \n#include <pcl/io/pcd_io.h>\n#include <pcl/io/obj_io.h>\n#include <pcl/io/vtk_lib_io.h>\n#include <pcl/io/impl/vtk_lib_io.hpp>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/console/parse.h>\n#include <pcl/common/transforms.h>\n#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING\n#include <experimental/filesystem>\n#include \"ceres/ceres.h\"\n#include \"class/data_path.h\"\n#include \"class/data_structure.h\"\n#include \"class/Visualize.h\"\n#include \"class/reconstruction.h\"\n#include \"class/feature_matching.h\"\n#include \"class/ranking_system.h\"\n\n#define TOP_k 5\n#define BRANCH_b 3\n\nusing namespace std;\nusing namespace Eigen;\n\nvector<Geom> shard(SHARD_NUMBER);\n\npcl::visualization::PCLVisualizer::Ptr viewer(new pcl::visualization::PCLVisualizer(\"Pot reconstruction\"));\n\nVisSwitchVariables vis; \n\n\nvoid keyboardEventOccurred(const pcl::visualization::KeyboardEvent& event, void* nothing)\n{\n\tpcl::visualization::PCLVisualizer* viewer = static_cast<pcl::visualization::PCLVisualizer*> (nothing);\n\tstd::string key_string = event.getKeySym();\n\tbool key_down = event.keyDown();\n\tvis.KeyEvent(key_string, key_down);\n}\n\nvoid IinitPairWiseProfileCheck(vector<Geom>& shard, list<LCSIndex> lcs_out)\n{\n\tlist<LCSIndex>::iterator iter = lcs_out.begin();\n\t//########### Pair-wise profile check\n\tvector<bool> pair_true_node(SHARD_NUMBER, false);\n\tfor (; iter != lcs_out.end(); ) {\n\t\tint index = iter->trans_.index_ - 1;\n\t\tint toward = iter->trans_.toward_ - 1;\n\t\tif (shard[index].edge_line_.is_seg_base_ || shard[toward].edge_line_.is_seg_base_) {\n\t\t\titer++;\n\t\t\tcontinue;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tMatrix3d R;\n\t\t\tVector3d t;\n\t\t\titer->trans_.Output(R, t);\n\t\t\tshard[index].Move(R, t);\n\t\t\tvector<Geom*> geom_ptr;\n\t\t\tgeom_ptr.push_back(&shard[index]);\n\t\t\tgeom_ptr.push_back(&shard[toward]);\n\t\t\tRefineAxis(geom_ptr,\n\t\t\t\tshard[toward].edge_line_.axis_point_[0],\n\t\t\t\tshard[toward].edge_line_.axis_norm_[0],\n\t\t\t\t100, NUMBER_OF_THREAD, 0.5, true);\n\t\t\tvector<Geom*>().swap(geom_ptr);\n\t\t\tMatrix3d R_a, R_a_i;\n\t\t\tVector3d t_a, t_a_i;\n\t\t\tAxisAlignment(shard[toward].edge_line_, R_a, t_a);\n\t\t\tshard[index].Move(R_a, t_a);\n\n\t\t\tvector<Vector3d> profile;\n\t\t\tToCylindricalInterpolation(shard[index].sur_in_, profile, false);\n\t\t\tToCylindricalInterpolation(shard[toward].sur_in_, profile, false);\n\t\t\tbool profile_matched = ProfileChecking(profile, 5.0, 10);\t// 50 35\n\n\t\t\t//Count profile curve inlier\n\t\t\tint pc_inlier_A = 1, pc_inlier_B = 1;\n\t\t\tint c_node = toward + 1;\n\t\t\tpair_true_node[index] = true;\n\t\t\tCountPCInlier(pc_inlier_A, pair_true_node, shard, c_node, 5.0, 3.0, false);\n\t\t\tpair_true_node[index] = false;\n\t\t\tpair_true_node[toward] = true;\n\t\t\tc_node = index + 1;\n\t\t\tCountPCInlier(pc_inlier_B, pair_true_node, shard, c_node, 5.0, 3.0, false);\n\t\t\tpair_true_node[toward] = false;\n\t\t\tdouble weight = (pc_inlier_A + pc_inlier_B - 2) / 2 + 1;\n\t\t\titer->inliner_ = iter->inliner_ * weight;\n\t\t\t//Finish count profile curve inlier\n\n\t\t\tR_a_i = R_a.inverse();\n\t\t\tt_a_i = -R_a_i * t_a;\n\t\t\tshard[toward].MoveWOSurface(R_a_i, t_a_i);\n\t\t\tMatrix3d R_i, R_i_total;\n\t\t\tVector3d t_i, t_i_total;\n\t\t\titer->trans_.InvOut(R_i, t_i);\n\t\t\tR_i_total = R_i * R_a_i;\n\t\t\tt_i_total = R_i * t_a_i + t_i;\n\n\t\t\tshard[index].Move(R_i_total, t_i_total);\n\t\t\tshard[toward].edge_line_.axis_norm_[0] = { 0, 0, 1 };\n\t\t\tshard[toward].edge_line_.axis_point_[0] = { 0, 0, 0 };\n\t\t\tif (profile_matched)\n\t\t\t\titer++;\n\t\t\telse if (!profile_matched) {\n\t\t\t\titer = lcs_out.erase(iter);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\t//#################### PCL viewer setting ####################//\n\tdouble calculation_time(0);\n\tint s_time(0), e_time(0);\n\n\tint step_size = shard.size(); \n\tif (argv[1] != NULL) {\n\t\tstep_size = std::atoi(argv[1]);\n\t}\n\t//#################### PCL viewer setting ####################//\n\tviewer->setBackgroundColor(0, 0, 0);\n\tviewer->addCoordinateSystem(1.0);\n\tviewer->initCameraParameters();\n\n\t// Register keyboard callback :\n\tviewer->registerKeyboardCallback(&keyboardEventOccurred, (void*)viewer.get());\n\t \n\tcout << \"#################### Pottery Data load ####################\" << endl;\n\t//#################### Pottery Data load ####################//\n\tint max_breakline_points(0);\n\tfor (int i = 0; i < SHARD_NUMBER; i++) {\n\t\tshard[i].edge_line_.ReadAxis(axis_path[i]);\n\n\t\t// Consider multi-axis shards at the same time\n\t\tif(shard_on_off[i])\t{\n\t\t\tshard[i].edge_line_.ReadPCDFileWithInfo(file_path[i]);\n\t\t\tshard[i].edge_line_.CalculateLineNormal();\n\t\t\tint breakline_points = shard[i].edge_line_.point_.cols();\n\t\t\tmax_breakline_points = max(max_breakline_points, breakline_points);\n\t\t\tshard[i].LoadSurface(surface_in[i], surface_out[i]);\n\t\t\tshard[i].is_matching_ = true;\n\t\t}\n\t}\n\n\tcout << \"#################### Save initial state ####################\" << endl;\n\t//#################### Save initial state ####################//\n\tvector<Visualize> pc_origin(SHARD_NUMBER); \n\tfor (int i = 0; i < SHARD_NUMBER; i++) {\n\t\tif (shard_on_off[i]) {\n\t\t\tstd::string pointName = \"origin_\" + std::to_string(i + 1);\n\t\t\tpc_origin[i].MakePointCloud(shard[i].edge_line_.point_, shard[i].edge_line_.normal_, pointName);\n\t\t\tpointName = \"o_Mesh\" + std::to_string(i + 1);\n\t\t\tpc_origin[i].MakeMesh(obj_path[i], pointName);\n\t\t}\n\t}\n\n\ts_time = clock();\n\n\tcout << \"#################### Change Axis symmetrix to z axis ####################\" << endl;\n\t//#################### Change Axis symmetrix to z axis ####################//\n\tvector<Trans> T_axis(SHARD_NUMBER);\n\tfor (int i = 0; i < SHARD_NUMBER; i++) {\n\t\tif (shard[i].is_matching_) {\n\t\t\tMatrix3d R_d = Matrix3d::Identity();\n\t\t\tVector3d t_d = { 0, 0, 0 };\n\t\t\tT_axis[i].Set(R_d, t_d, i + 1, i + 1);\n\n\t\t\t// Align symmetric axis to z-axis\n\t\t\tAxisAlignment(shard[i].edge_line_, R_d, t_d);\t\n\t\t\tshard[i].SurMove(R_d, t_d);\n\n\t\t\tpc_origin[i].UpdateData(viewer, shard[i].edge_line_.point_, shard[i].edge_line_.normal_);\n\t\t\tpc_origin[i].AddPointCloud(viewer);\n\t\t\tpc_origin[i].MeshTransform(R_d, t_d, viewer);\n\t\t\tT_axis[i].Input(R_d, t_d);\t\t// Save transformation matrix to z-axis\n\n\t\t\t//########## Align all base fragments to same direction\n\t\t\tif (shard[i].edge_line_.is_seg_base_) {\n\t\t\t\tcout << \"Base direction check, shard : \" << i + 1 << \"  \";\n\t\t\t\tdouble direction(0);\n\t\t\t\tint base_counter(0);\n\t\t\t\tVector3d Z_Axis = { 0, 0, 1 };\n\t\t\t\tfor (int j = 0; j < shard[i].sur_in_.normal_.cols(); j++) {\n\t\t\t\t\tdouble axis_angle = acos(Z_Axis.dot(shard[i].sur_in_.normal_.col(j)));\n\t\t\t\t\tif (axis_angle < 0.175 || axis_angle > 3.14159 - 0.175) {\n\t\t\t\t\t\tif (axis_angle < 1.57)\n\t\t\t\t\t\t\tdirection++;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdirection--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (direction > 0) {\n\t\t\t\t\tcout << \": Flip\";\n\t\t\t\t\tshard[i].edge_line_.axis_norm_[0] = -1 * shard[i].edge_line_.axis_norm_[0];\n\t\t\t\t\tAxisAlignment(shard[i].edge_line_, R_d, t_d);\t\n\t\t\t\t\tshard[i].SurMove(R_d, t_d);\n\t\t\t\t\tpc_origin[i].MeshTransform(R_d, t_d, viewer);\n\t\t\t\t\tT_axis[i].Input(R_d, t_d);\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t}\n\n\t\t\tCalculateFeatureAxisless(shard[i]);\n\n\t\t\t//######## Multi axis\n\t\t\tint num_axis = shard[i].edge_line_.axis_norm_.size();\n\t\t\tif (num_axis > 1) {\n\t\t\t\tfor (int j = 1; j < num_axis; j++) {\n\t\t\t\t\tMatrix3d R_a, R_i;\n\t\t\t\t\tVector3d t_a, t_i;\n\t\t\t\t\tAxisAlignment(shard[i].edge_line_, R_a, t_a, j);\n\t\t\t\t\tCalculateFeatureAxisless(shard[i], j);\n\t\t\t\t\tR_i = R_a.inverse();\n\t\t\t\t\tt_i = -R_i * t_a;\n\t\t\t\t\tshard[i].MoveWOSurface(R_i, t_i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//#################### Pottery Surface Data load ####################//\n\tfor (int i = 0; i < SHARD_NUMBER; i++) {\n\t\tif (shard[i].is_matching_) {\n\t\t\tint breakline_points = shard[i].edge_line_.point_.cols();\n\t\t\tdouble suf_weight = (double)breakline_points / (double)max_breakline_points;\n\t\t\tint num_sur_points = (int)(100.0 * suf_weight);\n\t\t\tshard[i].LoadSurface(surface_in[i], surface_out[i], num_sur_points);\n\t\t\tMatrix3d R_d = Matrix3d::Identity();\n\t\t\tVector3d t_d = { 0, 0, 0 };\n\t\t\tT_axis[i].Output(R_d, t_d);\n\t\t\tshard[i].SurMove(R_d, t_d);\n\t\t}\n\t}\n\n\tcout << \"#################### Feature matching ####################\" << endl;\n\t////#################### Feature matching ####################//\n\tlist<LCSIndex> LCS_out;\n\tFeatureComp(shard, LCS_out, 25, MINIMUM_NUMBER, 0);\n\tcout << \"Total number : \" << LCS_out.size() << endl;\n\n\tcout << \"#################### Pairwise pruning ####################\" << endl;\n\tint exclusive_index = 3;\t // rim(index 1) or base(index 2) or fractured base(index 3)\n\tExclusivelyPickEdge(LCS_out, shard, exclusive_index);\n\n\tPairwisePruning(shard, LCS_out);\n\n\tIinitPairWiseProfileCheck(shard, LCS_out);\n\n\tlist<LCSIndex>::iterator iter = LCS_out.begin();\n\tcout << \"Total number pruned : \" << LCS_out.size() << endl;\n\n\tint count_move_state(0);\n\n\tcout << \"#################### Incremental graph building ####################\" << endl;\n\t//////#################### Incremental graph building ####################//\n\tvector<RankingSubgraph> pre_graph;\n\tbool on_base_reconstruction = true;\n\tif (LCS_out.empty())\n\t\ton_base_reconstruction = false;\n\tint base_counter(0);\n\t////#################### First pahse : Reconstruct only fractured base ####################//\n\tlist<LCSIndex> lcs_base = LCS_out;\n\tcout << \"#################### First pahse : Reconstruct only fractured base ####################\" << endl;\n\twhile (on_base_reconstruction) {\n\t\tbase_counter++;\n\t\tcout << \"Reconstruct base : \" << base_counter << endl;\n\t\tRankingManager base_manager(10, 5, shard, LCS_out, step_size, path + \"Graph Log\", exclusive_index);\n\t\tbase_manager.BuildStep();\n\t\tif (!base_manager.out_graph_.empty()) {\n\t\t\tpre_graph.push_back(base_manager.out_graph_[0]);\n\t\t}\n\t\tfor (int i = 0; i < SHARD_NUMBER; i++) {\n\t\t\tif (base_manager.out_graph_[0].node_[i]) {\n\t\t\t\tif (shard[i].edge_line_.is_seg_base_)\n\t\t\t\t\tshard[i].edge_line_.is_seg_base_ = false;\n\t\t\t\telse\n\t\t\t\t\tcout << \"Error in a base reconstruction process\" << endl;\n\t\t\t}\n\t\t}\n\t\tLCS_out.clear();\n\t\tLCS_out = lcs_base;\n\t\tExclusivelyPickEdge(LCS_out, shard, exclusive_index);\n\t\tif (LCS_out.empty())\n\t\t\ton_base_reconstruction = false;\n\t}\n\n\t////#################### Second pahse : Reconstruct all fragments ####################//\n\tcout << \"#################### Second pahse : Reconstruct all fragments ####################\" << endl;\n\tStateManager manager(step_size, path + \"Graph Log\");\n\tmanager.InitializeWithGraph(TOP_k, BRANCH_b, shard, pre_graph);\n\tmanager.BuildStep();\n\n\tint num_total = manager.out_state_.size();\n\n\tvector<Visualize> pc_overlap(num_total);\n\n\te_time = clock();\n\n\tcout << \"Time after data load : \" << (e_time - s_time)/1000 << \"sec\" << endl;\n\n\tbool is_whole_shards_used = false;\n\tcount_move_state = 0;\n\n\titer = LCS_out.begin();\n\tbool is_first_state = false;\n\twhile (!viewer->wasStopped()) {\n\t\tviewer->spinOnce(5);\n\t\tif (vis.first_) {\n\t\t\tfor (int i = 0; i < SHARD_NUMBER; i++) {\n\t\t\t\tpc_origin[i].TurnOffData(viewer);\n\t\t\t}\n\t\t\tif (count_move_state != 0) {\n\t\t\t\tTurnoffandReturn(viewer, pc_origin, manager, count_move_state);\n\t\t\t\tcount_move_state = 0;\n\t\t\t\tcout << \"Go to first result\" << endl;\n\t\t\t}\n\t\t\tif (count_move_state == 0 && !is_first_state) {\n\t\t\t\tVisCurrentState(viewer, pc_origin, manager, count_move_state, pc_overlap, T_axis);\n\t\t\t\tpc_overlap[count_move_state].AddPointCloud(viewer, 255, 0, 0);\n\t\t\t\tis_first_state = true;\n\t\t\t}\n\t\t\tvis.first_ = false;\n\t\t}\n\n\t\telse if (vis.right_) {\n\t\t\tis_first_state = false;\n\t\t\tif (count_move_state >= num_total - 1) {\n\t\t\t\tcout << \"There is no more result. Please press 'spacebar' to go first result\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tTurnoffandReturn(viewer, pc_origin, manager, count_move_state);\n\n\t\t\t\tpc_overlap[count_move_state].AddPointCloud(viewer);\n\t\t\t\tcount_move_state++;\n\t\t\t\tVisCurrentState(viewer, pc_origin, manager, count_move_state, pc_overlap, T_axis);\n\n\t\t\t\tpc_overlap[count_move_state].AddPointCloud(viewer, 255, 0, 0);\n\t\t\t}\n\t\t\tvis.right_ = false;\n\t\t}\n\n\t\telse if (vis.left_) {\n\t\t\tif (count_move_state < 1) {\n\t\t\t\tcout << \"This is first result\" << endl;\n\t\t\t\tis_first_state = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tTurnoffandReturn(viewer, pc_origin, manager, count_move_state);\n\n\t\t\t\tpc_overlap[count_move_state].AddPointCloud(viewer);\n\t\t\t\tcount_move_state--;\n\t\t\t\tVisCurrentState(viewer, pc_origin, manager, count_move_state, pc_overlap, T_axis);\n\n\t\t\t\tpc_overlap[count_move_state].AddPointCloud(viewer, 255, 0, 0);\n\t\t\t}\n\t\t\tvis.left_ = false;\n\t\t}\n\n\t\telse if (vis.obj_) {\n\t\t\tObjVisualize(viewer, pc_origin, manager, count_move_state);\n\t\t\tvis.obj_ = false;\n\t\t}\n\n\t\telse if (vis.save_) {\n\t\t\tstring path_result = path + \"Result/\";\n\t\t\tSaveResult(pc_origin, manager, count_move_state, path_result);\n\t\t\tvis.save_ = false;\n\t\t\tcout << \"#################### Result save finish : \" << path_result << endl;\n\t\t}\n\t}\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "818dccce284676ac51f22de4bfc35b00816dbbd1", "size": 12741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "SeongJong-Yoo/structure-from-sherds", "max_stars_repo_head_hexsha": "2ad938a3e708f0a6d95decb59c3160a4ee389322", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-10-01T19:48:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T05:16:35.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "SeongJong-Yoo/structure-from-sherds", "max_issues_repo_head_hexsha": "2ad938a3e708f0a6d95decb59c3160a4ee389322", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-15T01:31:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T12:41:51.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "SeongJong-Yoo/structure-from-sherds", "max_forks_repo_head_hexsha": "2ad938a3e708f0a6d95decb59c3160a4ee389322", "max_forks_repo_licenses": ["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.0077720207, "max_line_length": 107, "alphanum_fraction": 0.6388038615, "num_tokens": 3706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.17976837529812853}}
{"text": "#include <ros/ros.h>\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <geometry_msgs/PoseArray.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <std_msgs/Float64MultiArray.h>\n\n#include <Eigen/Dense>\n\nclass CollisionDetector\n{\npublic:\n    CollisionDetector(void);\n\n    void process(void);\n    bool detect_collision(geometry_msgs::Pose, geometry_msgs::Pose);\n    geometry_msgs::PoseArray get_obstacles(void);\n\nprivate:\n    double RADIUS;\n    std::string WORLD_FRAME;\n    std::string ROBOT_FRAME;\n    std::string OBS_PREFIX;\n\n    ros::NodeHandle nh;\n    ros::NodeHandle local_nh;\n\n    ros::Publisher collision_pub;\n\n    tf::TransformListener listener;\n\n    double min_distance;\n};\n\nCollisionDetector::CollisionDetector(void)\n:local_nh(\"~\")\n{\n    local_nh.param<double>(\"/dynamic_avoidance/RADIUS\", RADIUS, {0.6});\n    local_nh.param<std::string>(\"/dynamic_avoidance/ROBOT_FRAME\", ROBOT_FRAME, {\"base_link\"});\n    local_nh.param<std::string>(\"/dynamic_avoidance/WORLD_FRAME\", WORLD_FRAME, {\"world\"});\n    local_nh.param<std::string>(\"/dynamic_avoidance/OBSTACLES_FRAME\", OBS_PREFIX, {\"obs\"});\n\n    collision_pub = nh.advertise<std_msgs::Float64MultiArray>(\"/collision_info\", 1);\n\n    min_distance = 1e6;\n}\n\nvoid CollisionDetector::process(void)\n{\n    geometry_msgs::PoseStamped current_robot;\n    current_robot.header.frame_id = WORLD_FRAME;\n\n    ros::Rate loop_rate(10);\n\n    std::cout << \"=== collision detector ===\" << std::endl;\n\n    unsigned int collision_count = 0;\n\n    std::map<int, bool> collision_list;\n\n    while(ros::ok()){\n        bool transformed_flag = false;\n        static Eigen::Vector3d last_robot_position = Eigen::Vector3d::Zero();\n        double robot_speed = 0;\n        try{\n            static double last_transform_time = ros::Time::now().toSec();\n            tf::StampedTransform transform;\n            listener.lookupTransform(WORLD_FRAME, ROBOT_FRAME, ros::Time(0), transform);\n            current_robot.header.stamp = transform.stamp_;\n            double transform_time = current_robot.header.stamp.toSec();\n            tf::poseTFToMsg(transform, current_robot.pose);\n            Eigen::Vector3d robot_position(current_robot.pose.position.x, current_robot.pose.position.y, current_robot.pose.position.z);\n            double dt = transform_time - last_transform_time;\n            if(dt > 0.0){\n                robot_speed = (robot_position - last_robot_position).norm() / dt;\n            }\n            last_robot_position = robot_position;\n            last_transform_time = transform_time;\n            transformed_flag = true;\n        }catch(tf::TransformException& ex){\n            std::cout << ex.what() << std::endl;\n        }\n        if(transformed_flag){\n            geometry_msgs::PoseArray obstacles = get_obstacles();\n            int obs_num = obstacles.poses.size();\n            // std::cout << \"obs num:\" << obs_num << std::endl;\n            for(int i=0;i<obs_num;i++){\n                bool is_collision = detect_collision(current_robot.pose, obstacles.poses[i]);\n                if(is_collision){\n                    ROS_INFO_STREAM(\"\\033[31m\" << \"collision detected with obs\" << std::to_string(i) << \"\\033[0m\");\n                    if(collision_list[i] == false){\n                        // new collision\n                        collision_count++;\n                        std::cout << \"\\033[033m\" << \"collision count: \" << collision_count << \"\\033[0m\" << std::endl;\n                        // std::cout << \"robot speed: \" << sqrt(robot_vel.linear.x * robot_vel.linear.x + robot_vel.linear.y * robot_vel.linear.y) << \"[m/s]\" << std::endl;\n                        std::cout << \"robot speed: \" << robot_speed << \"[m/s]\" << std::endl;\n                        // std::cout << robot_vel << std::endl;\n                    }\n                    collision_list[i] = true;\n                }else{\n                    collision_list[i] = false;\n                }\n            }\n            obstacles.poses.clear();\n            std_msgs::Float64MultiArray data;\n            data.data.push_back(collision_count);\n            data.data.push_back(min_distance);\n            collision_pub.publish(data);\n        }\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n}\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"collision_detector\");\n    CollisionDetector cd;\n    cd.process();\n    return 0;\n}\n\nbool CollisionDetector::detect_collision(geometry_msgs::Pose p0, geometry_msgs::Pose p1)\n{\n    /*\n     * collision->true;\n     */\n    double dx = p0.position.x - p1.position.x;\n    double dy = p0.position.y - p1.position.y;\n    double distance = sqrt(dx*dx + dy*dy);\n    if(distance < min_distance){\n        min_distance = distance;\n        std::cout << \"min distance: \" << min_distance << \"[m]\" << std::endl;\n    }\n    if(distance <= RADIUS){\n        std::cout << distance << \"[m]\" << std::endl;\n        return true;\n    }\n    return false;\n}\n\ngeometry_msgs::PoseArray CollisionDetector::get_obstacles(void)\n{\n    geometry_msgs::PoseArray obstacles;\n    tf::FrameGraph::Request req;\n    tf::FrameGraph::Response res;\n    if(listener.getFrames(req, res)){\n        std::vector<std::string> obs_names;\n        while(1){\n            // std::cout << res.dot_graph << std::endl;\n            int position = res.dot_graph.find(\"-> \\\"\" + OBS_PREFIX);\n            // std::cout << \"position: \" << position << std::endl;\n            if(position != std::string::npos){\n                position = res.dot_graph.find(OBS_PREFIX);\n                res.dot_graph.erase(0, position);\n                int double_quotation_pos = res.dot_graph.find(\"\\\"\");\n                std::string obs_name = res.dot_graph.substr(0, double_quotation_pos);\n                res.dot_graph.erase(0, double_quotation_pos);\n                // std::cout << obs_name << std::endl;\n                obs_names.emplace_back(obs_name);\n            }else{\n                // std::cout << OBS_PREFIX << \" was not found\" << std::endl;\n                break;\n            }\n        }\n        obstacles.header.frame_id = WORLD_FRAME;\n        obstacles.header.stamp = ros::Time::now();\n        for(const auto& obs_name : obs_names){\n            try{\n                tf::StampedTransform transform;\n                listener.lookupTransform(WORLD_FRAME, obs_name, ros::Time(0), transform);\n                obstacles.header.stamp = transform.stamp_;\n                geometry_msgs::Pose pose;\n                pose.position.x = transform.getOrigin().x();\n                pose.position.y = transform.getOrigin().y();\n                pose.position.z = transform.getOrigin().z();\n                tf::quaternionTFToMsg(transform.getRotation(), pose.orientation);\n                obstacles.poses.push_back(pose);\n            }catch(tf::TransformException& ex){\n                std::cout << ex.what() << std::endl;\n            }\n        }\n    }else{\n        std::cout << \"cannot get frames\" << std::endl;\n    }\n    return obstacles;\n}\n", "meta": {"hexsha": "12e2b182fff426e6710499c42137cc58aa2b1a21", "size": 6965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/collision_detector.cpp", "max_stars_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_stars_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2019-08-23T12:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:06:11.000Z", "max_issues_repo_path": "src/collision_detector.cpp", "max_issues_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_issues_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-08-16T03:16:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T14:29:52.000Z", "max_forks_repo_path": "src/collision_detector.cpp", "max_forks_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_forks_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2019-08-06T11:34:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T09:10:49.000Z", "avg_line_length": 36.8518518519, "max_line_length": 171, "alphanum_fraction": 0.5860732233, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1797683752981285}}
{"text": "/*\n * PowerStateGraph.cpp\n *\n *  Created on: 3 Aug 2011\n *      Author: jack\n */\n\n#include \"PowerStateGraph.h\"\n#include \"AggregateData.h\"\n#include <iostream>\n#include <list>\n#include <boost/graph/graphviz.hpp>\n#include <cstdio> // sprintf\n\nusing namespace std;\n\nPowerStateGraph::PowerStateGraph()\n: totalCount(0), aggData(0)\n{\n    using namespace boost;\n\n    // add a vertex to represent \"off\"\n    // uses Statistic's default constructor to make a Statistic with all-zeros\n    offVertex = add_vertex(powerStateGraph);\n\n}\n\nvoid PowerStateGraph::addItemToEdgeHistory(\n        const PSGraph::edge_descriptor& edge\n        )\n{\n    // Check if edge histories are disabled\n    if (EDGE_HISTORY_SIZE == 0)\n        return;\n\n    if (edgeHistory.size() >= EDGE_HISTORY_SIZE)\n        edgeHistory.erase( edgeHistory.begin() );\n\n    edgeHistory.push_back(edge);\n}\n\nconst Statistic< double >& PowerStateGraph::getEnergyConsumption() const\n{\n    return energyConsumption;\n}\n\n/**\n * @brief Update or initialise Power State Graph.\n */\nvoid PowerStateGraph::update(\n        const Signature& sig,\n        const bool verbose\n        )\n{\n    const double energyConsumptionFromSig = sig.getEnergyConsumption();\n    energyConsumption.update( energyConsumptionFromSig );\n    cout << \"Energy consumption from sig\" << sig.getID() << \" = \"\n         << energyConsumptionFromSig / J_PER_KWH << \" kWh\" << endl;\n\n    edgeHistory.clear();\n\n    // get the gradient spikes for the signature\n    list<Signature::Spike> spikes = sig.getDeltaSpikes();\n    list<Signature::Spike>::iterator spike;\n    PSGraph::vertex_descriptor targetVertex, sourceVertex=offVertex;\n    size_t indexOfLastAcceptedSpike = 0;\n    size_t start=0, end=0;\n\n    // for each spike, locate the samples immediately before and immediately after the spike\n    const size_t WINDOW = 8; // how far either side of the spike will we look?\n\n    // take just the top TOP_SLICE_SIZE (whilst ordered by absolute value)\n    const size_t TOP_SLICE_SIZE = 10;\n    if (spikes.size() > TOP_SLICE_SIZE) {\n        list<Signature::Spike>::iterator it = spikes.begin();\n        advance( it, TOP_SLICE_SIZE );\n        spikes.erase( it, spikes.end() );\n    }\n\n    // re-order by index (i.e. by time)\n    spikes.sort( Signature::Spike::compareIndexAsc );\n\n    for (spike = spikes.begin(); spike!=spikes.end(); spike++) {\n\n        // calculate the start index for the 8 pre-spike samples\n        start = ((spike->index > WINDOW) ? (spike->index - WINDOW) : 0 );\n\n        // calculate the end index for the 8 post-spike samples\n        end = spike->index + WINDOW + spike->n + 1;\n        if (end > sig.getSize())\n            end = sig.getSize();\n\n        // Create statistics for pre- and post-spike\n        Statistic<Sample_t> preSpikePowerState(sig, start, spike->index);\n        Statistic<Sample_t> postSpikePowerState(sig, (spike->index + spike->n + 1), end);\n\n        // check to see if spikes needs to be rejected and that the spikes aren't too close\n        if (rejectSpike(preSpikePowerState, postSpikePowerState) || start < indexOfLastAcceptedSpike) {\n            if (verbose) cout << \" REJECT\";\n        } else {\n\n            // Create inter-spike stats\n            Statistic<Sample_t> betweenSpikesPowerState(\n                    sig,\n                    (spike->index + spike->n + 1),\n                    indexOfNextSpike( spikes, spike, sig )\n                    );\n\n            targetVertex =\n                    updateOrInsertVertex(\n                            sig,\n                            postSpikePowerState,\n                            betweenSpikesPowerState\n                            );\n\n            if (sourceVertex != targetVertex) {\n                updateOrInsertEdge( sourceVertex, targetVertex,\n                        (spike->index - indexOfLastAcceptedSpike), spike->delta );\n            }\n\n            if (verbose)\n                printSpikeInfo( spike, start, end, preSpikePowerState, postSpikePowerState, sig);\n\n            sourceVertex = targetVertex;\n            indexOfLastAcceptedSpike = spike->index;\n\n        }\n    }\n}\n\n/**\n * @brief Useful for diagnostics.\n */\nvoid PowerStateGraph::printSpikeInfo(\n        const list<Signature::Spike>::iterator spike,\n        const size_t start,\n        const size_t end,\n        const Statistic<Sample_t>& preSpikePowerState,\n        const Statistic<Sample_t>& postSpikePowerState,\n        const Signature& sig\n        ) const\n{\n\n    cout << endl\n            << \"SPIKE: index=\" << spike->index\n            << \", delta=\" << spike->delta\n            << \", duration=\" << spike->n\n            << endl\n            << \" KEEP\" << endl\n            << \"Before=\" << preSpikePowerState << endl\n            << \"After =\" << postSpikePowerState  << endl;\n\n    for (size_t i=start; i<end; i++ ) {\n        cout << i << \"\\t\" << sig[i];\n        if (i < spike->index)\n            cout << \" before\";\n        else if (i == spike->index)\n            cout << \" <--SPIKE\";\n        else if (i < (spike->index + spike->n))\n            cout << \" <--Spike continues\";\n        else\n            cout << \" after\";\n        cout << endl;\n    }\n\n}\n\n/**\n * @brief Determine the index of the next spike after @c spike\n */\nconst size_t PowerStateGraph::indexOfNextSpike(\n        const list<Signature::Spike>& spikes,\n        list<Signature::Spike>::iterator spike,\n        const Signature& sig\n        ) const\n{\n    list<Signature::Spike>::iterator spikePlusOne = spike;\n    spikePlusOne++;\n    if (spikePlusOne != spikes.end())\n        return spikePlusOne->index;\n    else\n        return sig.getSize() - 1;\n}\n\n/**\n * @brief Decides whether or not to reject this spike based on the\n * @c before and @c after statistics.\n */\nconst bool PowerStateGraph::rejectSpike(\n        const Statistic<Sample_t>& before,\n        const Statistic<Sample_t>& after,\n        const bool verbose\n        ) const\n{\n    // check the stdev isn't too large\n    if ( (before.stdev > fabs(before.mean)) ||\n         ( after.stdev > fabs(after.mean))   ) {\n        if (verbose) cout << \"stdev too big\";\n        return true;\n    }\n\n    // check the means aren't too close\n    if (Utils::within(before.mean, after.mean, Utils::highest(before.stdev, after.stdev)*2) ||\n        Utils::within(before.mean, after.mean, Utils::highest(before.mean, after.mean)*0.2)     ) {\n        if (verbose) cout << \"means too close\";\n        return true;\n    }\n\n    // if we get to here then don't reject\n    return false;\n}\n\n/**\n * @brief Attempts to find an existing vertex which is\n * statistically similar to @c stat.  If an existing similar\n * vertex is found then the vertex's stats are updated\n * with the new data points. If a similar vertex is not found,\n * and new vertex is inserted.  Either way, a vertex_descriptor\n * is returned to the new or existing similar vertex.\n */\nPowerStateGraph::PSGraph::vertex_descriptor PowerStateGraph::updateOrInsertVertex(\n        const Signature& sig, /**< source of the raw data */\n        const Statistic<Sample_t>& postSpikePowerState,\n        const Statistic<Sample_t>& betweenSpikesPowerState,\n        const bool verbose  /**< cout debugging messages? */\n    )\n{\n    bool foundSimilar; // return param for mostSimilarVertex()\n    PSGraph::vertex_descriptor vertex = mostSimilarVertex( &foundSimilar, postSpikePowerState );\n    // mostSimilarVertex() uses a T-Test to find the powerStateGraph\n    // vertex with a mean most similar to postSpikePowerState.\n\n    if (verbose)\n        cout << \" mostSimlar = \" << powerStateGraph[vertex].postSpike << endl;\n\n    if ( foundSimilar ) {\n        if (vertex != offVertex) {\n            // Update an existing vertex\n\n            if (verbose) {\n                cout << endl\n                        << \"Updating existing vertex: \" << endl\n                        << \"    existing vertex = \" << powerStateGraph[vertex].postSpike << endl\n                        << \"    new stat        = \" << postSpikePowerState << endl;\n            }\n\n            powerStateGraph[vertex].postSpike.update( postSpikePowerState );\n            powerStateGraph[vertex].betweenSpikes.update( betweenSpikesPowerState );\n\n            if (verbose)\n                cout << \"    merged          = \" << powerStateGraph[vertex].postSpike << endl;\n        }\n    } else {\n        // Add a new vertex\n        vertex = add_vertex(powerStateGraph);\n        powerStateGraph[vertex].postSpike = postSpikePowerState;\n        powerStateGraph[vertex].betweenSpikes = betweenSpikesPowerState;\n\n        if (verbose) {\n            cout << endl\n                 << \"Adding new vertex: \" << powerStateGraph[vertex].postSpike << endl;\n        }\n\n    }\n    return vertex;\n\n}\n\n/**\n * @brief Find the vertex statistically most similarto @c stat.\n *\n * @return vertex descriptor of best fit.\n *         @c success is also used as a return parameter.\n *\n * @todo remove commented-out code if it proves to be of no use\n */\nPowerStateGraph::PSGraph::vertex_descriptor PowerStateGraph::mostSimilarVertex(\n        bool * success, /**< return parameter.  Did we find a satisfactory match? */\n        const Statistic<Sample_t>& stat, /**< stat to find in graph vertices */\n        const double ALPHA /**< significance level (what constitutes as a \"satisfactory\" match?) */\n    ) const\n{\n    PSGraph::vertex_descriptor vertex=0;\n    std::pair<PSG_vertex_iter, PSG_vertex_iter> vp;\n    double tTest, highestTTest=0;\n\n    // Find the best fit\n    for (vp = boost::vertices(powerStateGraph); vp.first != vp.second; ++vp.first) {\n        // t test\n        tTest = stat.tTest( powerStateGraph[*vp.first].postSpike );\n        if (tTest > highestTTest) {\n            highestTTest = tTest;\n            vertex = *vp.first;\n        }\n\n    }\n\n    // Check whether the best fit is satisfactory\n    if ( (highestTTest > (ALPHA/2)) // T-Test\n       ||  ( Utils::within\n                 (\n                 powerStateGraph[vertex].postSpike.mean,\n                 stat.mean,\n                 (Utils::highest(powerStateGraph[vertex].postSpike.mean, stat.mean) * 0.2)\n                 ) // check if the means are within 20% of each other\n         )\n      )\n        *success = true;\n    else\n        *success = false;\n\n    return vertex;\n}\n\n/**\n * @brief Update or Insert a new edge into powerStateGraph.\n *\n * - If an edge already exists between beforeVertex and afterVertex then\n *     - check all out-edges from beforeVertex\n *     - if any out-edge has the same history as the current history\n *           and the same sign delta then\n *           and and is within 3 stdevs of the existing delta then:\n *         - update that edge's statistics\n *     - else\n *         - create a new edge.\n * - else\n *     - create a new edge\n */\nvoid PowerStateGraph::updateOrInsertEdge(\n        const PSGraph::vertex_descriptor& beforeVertex,\n        const PSGraph::vertex_descriptor& afterVertex,\n        const size_t samplesSinceLastSpike,\n        const double spikeDelta,\n        const bool verbose\n        )\n{\n    totalCount++;\n\n    if (verbose) cout << \"-------------------\" << endl;\n\n    PSGraph::edge_descriptor existingEdge, newEdge;\n    bool edgeExistsAlready;\n    tie(existingEdge, edgeExistsAlready) = boost::edge(beforeVertex, afterVertex, powerStateGraph);\n\n    if (verbose) {\n        if ( edgeExistsAlready ) {\n            cout << \"edgeExistsAlready\" << endl;\n        } else {\n            cout << \"edge does not Exist Already\" << endl;\n        }\n    }\n\n    if ( edgeExistsAlready ) {\n\n        if (verbose) {\n            for (list<PSGraph::edge_descriptor>::iterator edge=edgeHistory.begin(); edge!=edgeHistory.end(); edge++) {\n                cout << \"                              edgeHistory = \" << *edge << endl;\n            }\n            for (list<PSGraph::edge_descriptor>::iterator edge=powerStateGraph[existingEdge].edgeHistory.begin();\n                    edge!=powerStateGraph[existingEdge].edgeHistory.end(); edge++) {\n                cout << \"powerStateGraph[existingEdge].edgeHistory = \" << *edge << endl;\n            }\n            cout << endl;\n        }\n\n        // check if any of the out edges from beforeVertex have the same\n        // history as our current history... if so, update that edge.\n        PSGraph::out_edge_iterator out_e_i, out_e_end;\n        tie(out_e_i, out_e_end) = out_edges(beforeVertex, powerStateGraph);\n        for (; out_e_i != out_e_end; out_e_i++) {\n            // check if the edge has the same history and same sign delta and is within 3 stdevs of the existing delta\n            if ( edgeListsAreEqual(powerStateGraph[*out_e_i].edgeHistory, edgeHistory) &&\n                    Utils::sameSign(powerStateGraph[*out_e_i].delta.mean, spikeDelta ) &&\n                    Utils::within(powerStateGraph[*out_e_i].delta.mean,\n                            spikeDelta, powerStateGraph[*out_e_i].delta.nonZeroStdev()*3 )) {\n\n                if (verbose) {\n                    cout << \"edge histories the same. merging with\" << *out_e_i\n                            << powerStateGraph[*out_e_i].delta << endl;\n                }\n\n                // update existing edge's stats\n                powerStateGraph[*out_e_i].delta.update( spikeDelta );\n                powerStateGraph[*out_e_i].duration.update( samplesSinceLastSpike );\n                powerStateGraph[*out_e_i].count++;\n\n                addItemToEdgeHistory( *out_e_i );\n\n                return;\n            }\n        }\n    }\n\n    // if we get to here then we know that either:\n    //    an edge doesn't already exist between these 2 vertices\n    // or\n    //    an edge does exist but it doesn't share our history.\n    // either way, we need to add a new edge:\n\n    tie(newEdge, edgeExistsAlready) = boost::add_edge(beforeVertex, afterVertex, powerStateGraph);\n    powerStateGraph[newEdge].delta    = Statistic<double>( spikeDelta );\n    powerStateGraph[newEdge].duration = Statistic<size_t>( samplesSinceLastSpike );\n    powerStateGraph[newEdge].count    = 1;\n    powerStateGraph[newEdge].edgeHistory = edgeHistory;\n\n    if (verbose) {\n        cout << \"adding new edge\" << newEdge << endl\n            << \"   delta stats    = \" << powerStateGraph[newEdge].delta << endl\n            << \"   duration stats = \" << powerStateGraph[newEdge].duration << endl;\n    }\n\n    addItemToEdgeHistory( newEdge );\n}\n\n/**\n * @brief Check if edge list @c a and edge list @c b are equal.\n */\nconst bool PowerStateGraph::edgeListsAreEqual(\n        const list< PSGraph::edge_descriptor >& a,\n        const list< PSGraph::edge_descriptor >& b,\n        const bool verbose\n        ) const\n{\n    // Check if edge histories are disabled\n    if (EDGE_HISTORY_SIZE == 0)\n        return true;\n\n    //******************* DIAGNOSTICS *******************\n    if (verbose ) {\n        cout << \"************\" << endl\n                << \"comparing lists:\" << endl;\n\n        for (list< PSGraph::edge_descriptor >::const_iterator i=a.begin(); i!=a.end(); i++) {\n            cout << *i << endl;\n        }\n        cout << \"----\" << endl;\n        for (list< PSGraph::edge_descriptor >::const_iterator i=b.begin(); i!=b.end(); i++) {\n            cout << *i << endl;\n        }\n    }//___________________________________________________\n\n    if (a.size() != b.size()) {\n        if (verbose) cout << \"sizes not equal\" << endl;\n        return false;\n    }\n\n    if (verbose) cout << \"************\" << endl;\n\n    list<PSGraph::edge_descriptor>::const_iterator a_i, b_i;\n\n    a_i = a.begin();\n    b_i = b.begin();\n\n    while (a_i != a.end() && b_i != b.end()) {\n\n        if (verbose) cout << \"*a_i=\" << *a_i << \" *b_i=\" << *b_i << endl;\n\n        if ( source(*a_i, powerStateGraph) != source(*b_i, powerStateGraph) &&\n             target(*a_i, powerStateGraph) != target(*b_i, powerStateGraph)   ) {\n\n            if (verbose) cout << \"edge list are not equal\" << endl << endl;\n\n            return false;\n        }\n\n        a_i++;\n        b_i++;\n    }\n\n    return true;\n}\n\n/**\n * @brief Update (or create) directional edges between power states (vertices)\n *        so the edges are consistent with the observed transitions between\n *        power states in @c sig.\n *\n * Basic strategy is to:\n * <ol>\n *  <li>retrieve gradient spikes from @c sig, extract the most salient\n *      and put the spikes into temporal order.</li>\n *  <li>Create stats for the data points between each spike. Use mostSimilarVertex()\n *      to determine which of the existing power state vertices this belongs to.</li>\n *  <li>Check to see if there's an existing edge representing the power state transition,\n *      if so then check the @c delta and @c duration stats for the edge and update if necessary.\n *      If no edge exists then create one with the necessary @c delta and @c duration,\n *      with a hard-coded stdev.</li>\n * </ol>\n *\n *  @deprecated just leaving this here to illustrate one of the strategies I tried.\n *  This has been superseded by update() (which used to be updateVertices) and updateOrInsertEdge()\n *\n */\nvoid PowerStateGraph::updateEdges( const Signature& sig )\n{\n    Statistic<Sample_t> nextPowerState, prevPowerState;\n    PSGraph::vertex_descriptor mostSimVertex, previousVertex;\n    pair<PSGraph::edge_descriptor, bool> addedEdge;\n    size_t previousIndex;\n\n    // get the gradient spikes for the first signature\n    list<Signature::Spike> spikes = sig.getDeltaSpikes();\n\n    // take just the top ten (whilst ordered by absolute value)\n    if (spikes.size() > 10) {\n        list<Signature::Spike>::iterator it = spikes.begin();\n        advance( it, 10 );\n        spikes.erase( it, spikes.end() );\n    }\n\n    // re-order by index (i.e. by time)\n    spikes.sort( Signature::Spike::compareIndexAsc );\n\n    // calculate stats for the signature's values between start and first spike\n    // as long as the first spike->index > 1\n    previousVertex = offVertex;\n    previousIndex  = 0;\n\n    list<Signature::Spike>::iterator spike, prevSpike;\n    prevSpike = spike = spikes.begin();\n    advance(spike, 1);\n    for (; spike!=spikes.end(); spike++ ) {\n\n        nextPowerState = Statistic<Sample_t>( sig, prevSpike->index+1, prevSpike->index+10); // spike->index);\n\n        bool foundSimilar;\n        mostSimVertex = mostSimilarVertex( &foundSimilar, nextPowerState, 0.1 );\n\n        if (foundSimilar && previousVertex!=mostSimVertex) {\n            /* Add an edge from previousVertex to mostSimVertex.\n             * If an edge already exists then boost::add_edge will\n             * return an edge_descriptor to that edge. */\n            addedEdge = boost::add_edge(previousVertex, mostSimVertex, powerStateGraph);\n\n            if (addedEdge.second) { // then there was not an edge already in the graph\n                powerStateGraph[addedEdge.first].delta =\n                        Statistic<double>( prevSpike->delta );\n                powerStateGraph[addedEdge.first].duration =\n                        Statistic<size_t>( prevSpike->index - previousIndex );\n                powerStateGraph[addedEdge.first].count = 1;\n                totalCount++;\n            } else { // there was an edge already in the graph so update that edge\n                powerStateGraph[addedEdge.first].delta.update( prevSpike->delta );\n                powerStateGraph[addedEdge.first].duration.update( prevSpike->index - previousIndex );\n                powerStateGraph[addedEdge.first].count++;\n                totalCount++;\n            }\n\n            previousIndex  = prevSpike->index;\n            previousVertex = mostSimVertex;\n        }\n        prevSpike = spike;\n    }\n\n    // add the last edge back to \"off\"\n    addedEdge = boost::add_edge(previousVertex, offVertex, powerStateGraph);\n    if (addedEdge.second) { // then there was not an edge already in the graph\n        powerStateGraph[addedEdge.first].delta =\n                Statistic<double>( prevSpike->delta );\n        powerStateGraph[addedEdge.first].duration =\n                Statistic<size_t>( prevSpike->index - previousIndex );\n        powerStateGraph[addedEdge.first].count = 1;\n        totalCount++;\n    } else { // there was an edge already in the graph so update that edge\n        powerStateGraph[addedEdge.first].delta.update( prevSpike->delta );\n        powerStateGraph[addedEdge.first].duration.update( prevSpike->index - previousIndex );\n        powerStateGraph[addedEdge.first].count++;\n        totalCount++;\n    }\n\n}\n\n/**\n * @brief Produce a graphviz output\n */\nvoid PowerStateGraph::writeGraphViz(ostream& out)\n{\n    write_graphviz(\n            out,\n            powerStateGraph,\n            PSG_vertex_writer(powerStateGraph),\n            PSG_edge_writer(powerStateGraph)\n            );\n}\n\n/**\n * @brief This is the main public interface to the disaggregation algorithm\n *\n * Each candidate solution is represented as a\n * tree.  Each vertex\n * on this tree is a spike found in the aggregate data.\n * The edge weights are the mean of the probability density\n * functions for the spike size and the timing.  If an\n * edge described in PowerStateGraph (from training) cannot be found\n * in the aggregate data then this candidate is discarded.  If\n * we successfully get from vertex0 back to vertex0 then the\n * shortest path through the tree is calculated and saved.\n *\n * <ol>\n * <li>Retrieve edge @c e which connects @c vertex0 (offVertex)\n *     to vertex1.  Look through the AggregateData\n *     searching for any spike within a certain number of\n *     standard deviations of @c e.delta.</li>\n * <li>When a spike is found, start a tree structure and\n *     start looking for the subsequent edges learnt during training.</li>\n * <li>Look for the delta corresponding to each out edge from current vertex.\n *     Store the UNIX timestamp of each candidate.  </li>\n * </ol>\n *\n * @return a list of UNIX times when the device starts\n */\nconst list<PowerStateGraph::Fingerprint> PowerStateGraph::disaggregate(\n        const AggregateData& aggregateData, /**< A populated array of AggregateData */\n        const bool keep_overlapping, /**< Should we keep or remove overlapping candidates? */\n        const bool verbose\n        )\n{\n    cout << endl << \"***** TRAINING FINISHED. DISAGGREGATION STARTING. *****\" << endl << endl;\n    cout << \"Finding start deltas...\";\n    cout.flush();\n\n    if (num_vertices( powerStateGraph ) < 2) {\n        Utils::fatalError( \"powerStateGraph is empty. Cannot continue with disaggregation.\" );\n    }\n\n    // Store a pointer to aggregateData for use later.\n    aggData = &aggregateData;\n\n    /* Fingerprint is a struct for bundling start\n     * timestamp, duration, energy and avLikelihood */\n    list<Fingerprint> fingerprintList; // what we return\n    Fingerprint candidateFingerprint;\n\n    /* Load the stats from the first PowerStateGraph edge.\n     * The Boost Graph Lib provides an out_edges() function which returns\n     * a pair of edge iterators: the first iterator points to the first edge;\n     * the second iterator points 1 past the last edge. Dereferencing an\n     * edge iterator returns an edge descriptor. tie() allows easy\n     * access to each element of the pair of edge iterators. */\n    PSG_out_edge_iter out_i, out_end;\n    tie(out_i, out_end) = out_edges(offVertex, powerStateGraph);\n    PowerStateEdge firstEdgeStats = powerStateGraph[*out_i];\n\n    // Search through aggregateData for possible start spikes\n    list<AggregateData::FoundSpike> posStartSpikes\n        = aggregateData.findSpike(firstEdgeStats.delta);\n\n    cout << \" found \" << posStartSpikes.size() << \" possible start deltas. Following through... \" << endl;\n\n    // For each possible start spike in the delta aggregate, attempt\n    // to find all the subsequent spikes specified by powerStateGraph edges.\n    for (list<AggregateData::FoundSpike>::const_iterator posStartSpike=posStartSpikes.begin();\n            posStartSpike!=posStartSpikes.end();\n            posStartSpike++) {\n\n        // Attempt to recursively \"follow through\" from this posStartSpike.\n        // initTraceToEnd() calls the recursive function traceToEnd().\n        candidateFingerprint = initTraceToEnd(\n                *posStartSpike,\n                ( posStartSpike->timestamp - firstEdgeStats.duration.mean ) // time the device probably started\n                );\n\n        // If this start spike was successfully traced all the way to\n        // an off power state then add this item to fingerprintList.\n        if ( candidateFingerprint.avLikelihood != -1 ) {\n            fingerprintList.push_back( candidateFingerprint );\n            if (verbose)\n                cout << endl << \"candidate found at \" << endl << candidateFingerprint << endl;\n            else {\n                cout << \".\";\n                cout.flush();\n            }\n        }\n    }\n\n    cout << endl;\n\n    if ( fingerprintList.empty() ) {\n        cout << \"No signatures found.\" << endl;\n    } else {\n        if (!keep_overlapping) {\n            removeOverlapping( &fingerprintList );\n        }\n\n        displayAndPlotFingerprintList( fingerprintList, aggregateData.getFilename() );\n    }\n\n    return fingerprintList;\n}\n\nvoid PowerStateGraph::displayAndPlotFingerprintList(\n        const list< Fingerprint >& fingerprintList,\n        const string& aggDataFilename\n        ) const\n{\n    cout << \"Displaying disaggregation data and dumping to file for plotting. \" << endl;\n\n    fstream fs;\n    Utils::openFile(fs, DATA_OUTPUT_PATH + \"disagg.dat\", fstream::out);\n    list<Fingerprint>::const_iterator disagItem;\n    size_t count = 0;\n    for (disagItem=fingerprintList.begin(); disagItem!=fingerprintList.end(); disagItem++) {\n        cout << endl << \"Candidate fingerprint found: \" << endl << *disagItem << endl;\n        count++;\n        for (list<TimeAndPower>::const_iterator tap_i=disagItem->timeAndPower.begin();\n                tap_i!=disagItem->timeAndPower.end(); tap_i++) {\n            fs << tap_i->timestamp << \"\\t\" << tap_i->meanPower << endl;\n        }\n    }\n    cout << endl\n            << \"Found \" << count << \" candidate\" << (count==1 ? \". \" : \"s.\" ) << endl;\n\n    // Calculate size of x-axis border\n    const size_t begOfFirstFingerprint = fingerprintList.front().timestamp;\n    const size_t endOfLastFingerprint  = fingerprintList.back().timestamp + fingerprintList.back().duration;\n    const size_t BORDER = (endOfLastFingerprint - begOfFirstFingerprint) / 10;\n\n    // Set Plot variables\n    GNUplot::PlotVars pv;\n    pv.inFilename  = \"disagg\";\n    pv.outFilename = \"disagg\";\n    pv.title       = \"Automatic disaggregation for \" + deviceName;\n    pv.xlabel      = \"time\";\n    pv.ylabel      = \"power (kW)\";\n\n    // set sensible xrange, but only if we're not dealing with synthetic data with a low timecode\n    if (fingerprintList.front().timestamp > BORDER) {\n        const size_t dstOffset = 3600; // to correct for BST\n        pv.plotArgs    = \"[\\\"\" + Utils::size_t_to_s( fingerprintList.front().timestamp - BORDER + dstOffset) + \"\\\":\\\"\"\n                + Utils::size_t_to_s( fingerprintList.back().timestamp + fingerprintList.back().duration + BORDER + dstOffset) + \"\\\"]\";\n    }\n\n    pv.data.push_back(\n            GNUplot::PlotData(\n                    \"disagg\", \"Automatically determined device fingerprint\", \"DISAGG\"));\n    pv.data.push_back(\n            GNUplot::PlotData(\n                      aggDataFilename, \"Aggregate data\", \"AGGDATA\", false));\n\n    GNUplot::plot( pv );\n}\n\n/**\n * Remove any overlapping list entries and leave the one with the highest likelihood\n */\nvoid PowerStateGraph::removeOverlapping(\n        list<Fingerprint> * fingerprintList, /**< Input and output parameter */\n        const bool verbose\n        )\n{\n    list<Fingerprint>::iterator currentDisagItem, prevDisagItem;\n    size_t count = 0;\n\n    currentDisagItem = prevDisagItem = fingerprintList->begin();\n    advance( currentDisagItem, 1 );\n    while ( currentDisagItem != fingerprintList->end() ) {\n\n        // check to see whether the two disag items overlap\n        if ( (prevDisagItem->timestamp + prevDisagItem->duration) >= currentDisagItem->timestamp ) {\n\n            count++;\n\n            if (verbose) {\n                cout << \"Overlap detected between items with start timestamps \"\n                    << prevDisagItem->timestamp << \" and \" << currentDisagItem->timestamp << \" ...\";\n            }\n\n            // they overlap.  so find which needs to be replaced\n            if (prevDisagItem->avLikelihood < currentDisagItem->avLikelihood) {\n                if (verbose) cout << \"erasing item with timestamp \" << prevDisagItem->timestamp << endl;\n                fingerprintList->erase( prevDisagItem );\n                prevDisagItem = currentDisagItem++;\n            } else {\n                if (verbose) cout << \"erasing item with timestamp \" << currentDisagItem->timestamp << endl;\n                fingerprintList->erase( currentDisagItem++ );\n                // don't change prevDisagItem\n            }\n\n        } else {\n            prevDisagItem = currentDisagItem++;\n        }\n    }\n\n    if (count == 0) {\n        cout << \"No candidate fingerprints overlap.\" << endl;\n    } else {\n        cout << \"Removed \" << count << \" overlapping candidate fingerprints.\" << endl;\n    }\n}\n\n/**\n *\n * @return DisaggregatedStruct.likelihood will be set to -1 if\n * this looks like it's not a good candidate match.\n */\nconst PowerStateGraph::Fingerprint PowerStateGraph::initTraceToEnd(\n        const AggregateData::FoundSpike& spike,\n        const size_t deviceStart, /**< The possible time the device started. */\n        const bool verbose\n        )\n{\n    DisagTree disagTree;\n\n    // make the first vertex (which represents \"off\")\n    DisagTree::vertex_descriptor disagOffVertex = add_vertex(disagTree);\n    disagTree[disagOffVertex].timestamp = deviceStart;\n    disagTree[disagOffVertex].meanPower = 0; // this is \"off\"\n    disagTree[disagOffVertex].psgVertex = offVertex;\n\n    // add a vertex to represent the first true power state\n    DisagTree::vertex_descriptor firstVertex = add_vertex(disagTree);\n\n    // retrieve info for firstVertex and for edge between disagOffVertex and firstVertex\n    PSG_out_edge_iter out_e_i, out_e_end;\n    PSG_vertex_iter v_i, v_end;\n    tie(out_e_i, out_e_end) = out_edges(offVertex, powerStateGraph);\n    PowerStateEdge firstEdgeStats = powerStateGraph[*out_e_i];\n    tie(v_i, v_end) = vertices(powerStateGraph);\n    v_i++;\n\n    disagTree[firstVertex].timestamp = spike.timestamp;\n    disagTree[firstVertex].meanPower = powerStateGraph[*v_i].betweenSpikes.mean;\n    disagTree[firstVertex].psgVertex = *v_i;\n    disagTree[firstVertex].psgEdge   = *out_e_i;\n    if (EDGE_HISTORY_SIZE)\n        disagTree[firstVertex].edgeHistory.push_back(*out_e_i);\n\n    // add an edge between disagOffVertex and firstVertex\n    DisagTree::edge_descriptor edge;\n    bool existingEdge;\n    tie(edge, existingEdge) = add_edge(\n            disagOffVertex,   // source vertex\n            firstVertex,      // target vertex\n            spike.likelihood, // edge value\n            disagTree);\n\n    // now recursively trace from this edge to the end\n    traceToEnd( &disagTree, firstVertex, deviceStart );\n\n    if (verbose) {\n        write_graphviz(cout, disagTree,\n            Disag_vertex_writer(disagTree), Disag_edge_writer(disagTree));\n    }\n\n    // find route through the tree with highest average edge likelihoods\n    listOfPaths.clear();\n\n    LikelihoodAndVertex nextLAV;\n    nextLAV.vertex = firstVertex;\n    nextLAV.likelihood = disagTree[edge];\n\n    findListOfPathsThroughDisagTree(\n            disagTree,\n            disagOffVertex,\n            nextLAV);\n\n    // Return the most confident path through the disagTree\n    return findBestPath( disagTree, deviceStart );\n\n}\n\n/**\n * @brief Trace the tree downwards from @c vertex recursively finding\n * every path which successfully completes (i.e. reaches an off state).\n */\nvoid PowerStateGraph::findListOfPathsThroughDisagTree(\n        const DisagTree& disagTree,\n        const DisagTree::vertex_descriptor vertex,\n        const LikelihoodAndVertex lav,\n        list<PowerStateGraph::LikelihoodAndVertex> path /**< Deliberately called-by-value because we want a copy. */\n    )\n{\n    path.push_back( lav );\n\n    // base case = we're at the end\n    if ( vertex != 0 && // check we're not at the first vertex\n            disagTree[ vertex ].meanPower == 0 ) {\n        listOfPaths.push_back( path );\n        return;\n    }\n\n    // iterate through each out-edge\n    Disag_out_edge_iter out_e_i, out_e_end;\n    tie(out_e_i, out_e_end) = out_edges(vertex, disagTree);\n\n    for (; out_e_i!=out_e_end; out_e_i++) {\n\n        DisagTree::vertex_descriptor downstreamVertex = target(*out_e_i, disagTree);\n\n        LikelihoodAndVertex nextLav;\n        nextLav.vertex = downstreamVertex;\n        nextLav.likelihood = disagTree[*out_e_i];\n\n        // we haven't hit the end yet so recursively follow tree downwards.\n        findListOfPathsThroughDisagTree(\n                disagTree,\n                downstreamVertex,\n                nextLav,\n                path );\n\n    }\n    return;\n}\n\n\n/**\n * Trace from startVertex to the off state in PSGraph\n */\nvoid PowerStateGraph::traceToEnd(\n        DisagTree * disagTree_p, /**< input and output parameter */\n        const DisagTree::vertex_descriptor& disagVertex,\n        const size_t prevTimestamp, /**< timestamp of previous vertex */\n        const bool verbose\n        ) const\n{\n\n    if (verbose) cout << \"***traceToEnd... prevTimestamp=\" << prevTimestamp << \" DisagTree startVertex=\" << disagVertex << endl;\n\n    list<AggregateData::FoundSpike> foundSpikes;\n\n    // A handy reference to make the code more readable\n    DisagTree& disagTree = *disagTree_p;\n\n    // base case\n    if ( disagTree[disagVertex].psgVertex == offVertex ) {\n        return;\n    }\n\n    // For each out-edge from disagVertex.psgVertex, retrieve a list of\n    // spikes which match and create a new DisagTree vertex for each match.\n    PSG_out_edge_iter psg_out_i, psg_out_end;\n    tie(psg_out_i, psg_out_end) =\n            out_edges(disagTree[disagVertex].psgVertex, powerStateGraph);\n\n    const size_t WINDOW_FRAME = 8; // number of seconds to widen window by\n\n    for (; psg_out_i!=psg_out_end; psg_out_i++ ) {\n\n        // Commented out alternative strategy for getting edge history. Almost certainly slower than\n        // using disagTree[disagVertex].edgeHistory\n//        std::list< PSGraph::edge_descriptor > eHistory = getEdgeHistoryForVertex(disagTree, disagVertex);\n\n        if ( ! edgeListsAreEqual(\n//                eHistory,\n                disagTree[disagVertex].edgeHistory,\n                powerStateGraph[*psg_out_i].edgeHistory ) ) {\n            if (verbose) cout << \"edge histories not equal\" << endl;\n            continue;\n        }\n\n        size_t begOfSearchWindow, endOfSearchWindow;\n\n        size_t e = powerStateGraph[*psg_out_i].duration.nonZeroStdev();\n\n        if (verbose)  cout << \"disagTree[startVertex].timestamp=\" << disagTree[disagVertex].timestamp << endl;\n\n        begOfSearchWindow = (disagTree[disagVertex].timestamp + powerStateGraph[*psg_out_i].duration.min)\n                - WINDOW_FRAME - e;\n\n        endOfSearchWindow = (disagTree[disagVertex].timestamp + powerStateGraph[*psg_out_i].duration.max)\n                + WINDOW_FRAME + e;\n\n        //********************** DIAGNOSTICS *************************\n        if (verbose) {\n            cout << \"endOfSearchWindow=\" << endOfSearchWindow\n                    << \" disagTree[startVertex].timestamp=\" << disagTree[disagVertex].timestamp\n                    << \" powerStateGraph[*psg_out_i].duration.max=\" << powerStateGraph[*psg_out_i].duration.max\n                    << \" powerStateGraph[*psg_out_i].duration.mean=\" << powerStateGraph[*psg_out_i].duration.mean\n                    << \" powerStateGraph[*psg_out_i].duration.stdev=\" << powerStateGraph[*psg_out_i].duration.stdev\n                    << endl;\n        }//__________________________________________________________\n\n        // ensure we're not looking backwards in time\n        if (begOfSearchWindow <= disagTree[disagVertex].timestamp) {\n            begOfSearchWindow =\n                    disagTree[disagVertex].timestamp\n                    + powerStateGraph[*psg_out_i].duration.min\n                    - (powerStateGraph[*psg_out_i].duration.min / 10);\n        }\n\n        // check that we're not looking past the end of aggData\n        if (endOfSearchWindow > (*aggData)[ (*aggData).getSize() - 1 ].timestamp ) {\n            continue; // we can't process this if we're trying to look past the end of the aggData\n        }\n\n        //************************************************************//\n        // get a list of candidate spikes matching this PSG-out-edge  //\n\n        foundSpikes.clear();\n        foundSpikes = aggData->findSpike(\n                powerStateGraph[*psg_out_i].delta,  // spike stats\n                begOfSearchWindow,\n                endOfSearchWindow\n                );\n\n\n        //***************************************************************//\n        // for each candidate spike, create a new vertex in disagTree   //\n        // and recursively trace this to the end                         //\n\n        for (list<AggregateData::FoundSpike>::const_iterator spike=foundSpikes.begin();\n                spike!=foundSpikes.end();\n                spike++) {\n\n            // ensure that the absolute value of the aggregate data signal\n            // does not drop below the minimum for our current power state\n            if (aggData->readingGoesBelowPowerState(\n                    disagTree[disagVertex].timestamp,\n                    spike->timestamp,\n                    powerStateGraph[ disagTree[disagVertex].psgVertex ].betweenSpikes ) ) {\n\n                continue;\n            }\n\n            double normalisedLikelihoodForTime = powerStateGraph[*psg_out_i].duration.normalisedLikelihood(\n                    spike->timestamp - disagTree[disagVertex].timestamp);\n\n            // merge probability for time and for spike delta\n            double avLikelihood = ( normalisedLikelihoodForTime + spike->likelihood ) / 2;\n\n            // create new vertex\n            DisagTree::vertex_descriptor newVertex=add_vertex( disagTree );\n\n            // create new edge\n            DisagTree::edge_descriptor newEdge;\n            bool existingEdge;\n            tie(newEdge, existingEdge) =\n                    add_edge( disagVertex, newVertex, avLikelihood, disagTree );\n\n            // add details to newVertex\n            disagTree[newVertex].timestamp = spike->timestamp;\n            // get vertex that *psg_out_i points to\n            disagTree[newVertex].psgVertex = target(*psg_out_i, powerStateGraph);\n            disagTree[newVertex].psgEdge   = *psg_out_i;\n            disagTree[newVertex].meanPower =\n                    powerStateGraph[disagTree[newVertex].psgVertex].betweenSpikes.mean;\n\n            if (EDGE_HISTORY_SIZE) {\n                disagTree[newVertex].edgeHistory = disagTree[disagVertex].edgeHistory;\n                disagTree[newVertex].edgeHistory.push_back(*psg_out_i);\n                if (disagTree[newVertex].edgeHistory.size() > EDGE_HISTORY_SIZE) {\n                    disagTree[newVertex].edgeHistory.erase( disagTree[newVertex].edgeHistory.begin() );\n                }\n            }\n\n            // recursively trace to end.\n            traceToEnd(disagTree_p, newVertex, disagTree[disagVertex].timestamp);\n        }\n    }\n}\n\n/**\n * @brief Iterates through each path in @c listOfPaths\n *        to find the one with the highest likelihood.\n *\n * To be called after @c listOfPaths has been populated by findListOfPathsThroughDisagTree().\n *\n * @return details of the best path.  Confidence is set to -1 if no paths are available.\n */\nconst PowerStateGraph::Fingerprint PowerStateGraph::findBestPath(\n        const DisagTree& disagTree,\n        const size_t deviceStart,\n        const bool verbose\n        )\n{\n    Fingerprint fingerprint;\n    fingerprint.timestamp = deviceStart;\n\n    // first check that listOfPaths is populated\n    if ( listOfPaths.empty() ) {\n        fingerprint.avLikelihood = -1; // return error code\n        return fingerprint;\n    }\n\n    fingerprint.avLikelihood = 0;\n\n    list< list<LikelihoodAndVertex> >::const_iterator path_i, bestPath_i;\n    list< LikelihoodAndVertex >::const_iterator lav_i;\n\n    if (verbose) cout << \"path dump:\" << endl;\n\n    double likelihoodAccumulator, avLikelihood;\n    bool foundGoodPath = false;\n\n    // iterate through each path to find the one with the highest likelihood\n    for (path_i=listOfPaths.begin(); path_i!=listOfPaths.end(); path_i++) {\n\n        likelihoodAccumulator = 0;\n        for ( lav_i=path_i->begin(); lav_i!=path_i->end(); lav_i++ ) {\n            if (verbose) cout << \"vertex=\" << lav_i->vertex << \" conf=\" << lav_i->likelihood << \", \";\n            likelihoodAccumulator += lav_i->likelihood;\n        }\n\n        avLikelihood = likelihoodAccumulator / path_i->size();\n\n        // if this is the most confident path we've seen yet then record its details.\n        if ( avLikelihood >= fingerprint.avLikelihood ) {\n            fingerprint.avLikelihood = avLikelihood;\n            bestPath_i = path_i;\n            foundGoodPath = true;\n        }\n\n        if (verbose) cout << endl << endl;\n    }\n\n    // now get energy usage and duration from bestPath_i\n    size_t prevTimestamp, duration;\n    double prevMeanPower = 0;\n\n    fingerprint.energy = 0;\n    fingerprint.duration = 0;\n    duration = 0;\n    prevTimestamp = deviceStart;\n    size_t count = 0;\n    if (foundGoodPath) {\n        for (lav_i=bestPath_i->begin(); lav_i != bestPath_i->end(); lav_i++) {\n\n            // Add to timeAndPower list for read-out later when we plot the power states\n            if ( lav_i != bestPath_i->begin() ) {\n                fingerprint.timeAndPower.push_back( TimeAndPower(\n                        disagTree[ lav_i->vertex ].timestamp-1 ,\n                        (count==1 ? 0 : prevMeanPower)\n                ) );\n                fingerprint.timeAndPower.push_back( TimeAndPower(\n                        disagTree[ lav_i->vertex ].timestamp,\n                        disagTree[ lav_i->vertex ].meanPower) );\n            }\n\n            // Now calculate duration and energy consumption\n            duration = disagTree[ lav_i->vertex ].timestamp - prevTimestamp;\n            fingerprint.energy += prevMeanPower * duration;\n\n            fingerprint.duration += duration;\n\n            prevTimestamp = disagTree[ lav_i->vertex ].timestamp;\n            prevMeanPower = disagTree[ lav_i->vertex ].meanPower;\n            count++;\n        }\n\n        fingerprint.avLikelihood = ( fingerprint.avLikelihood +\n                energyConsumption.normalisedLikelihood(fingerprint.energy) ) / 2;\n    } else {\n        fingerprint.avLikelihood = -1;\n    }\n\n    return fingerprint;\n}\n\n/**\n * @brief Trace the disagTree backwards.\n */\nlist< PowerStateGraph::PSGraph::edge_descriptor > PowerStateGraph::getEdgeHistoryForVertex(\n        const DisagTree& disagTree,\n        const DisagTree::vertex_descriptor& startVertex\n        ) const\n{\n    list< PSGraph::edge_descriptor > eHistory;\n    DisagTree::vertex_descriptor disagVertex = startVertex;\n\n    DisagTree::in_edge_iterator in_e_i, in_e_end;\n\n    while (disagTree[disagVertex].psgVertex != offVertex && eHistory.size() < EDGE_HISTORY_SIZE) {\n        eHistory.push_front( disagTree[disagVertex].psgEdge );\n        tie(in_e_i, in_e_end) = in_edges(disagVertex, disagTree);\n        disagVertex = source( *in_e_i, disagTree ); // the vertex upstream from in_e_i\n    }\n\n    return eHistory;\n}\n\nvoid PowerStateGraph::setDeviceName(const string& _deviceName)\n{\n    deviceName = _deviceName;\n}\n\nstd::ostream& operator<<( std::ostream& o, const PowerStateGraph& psg )\n{\n    PowerStateGraph::PSG_vertex_index_map index = boost::get(boost::vertex_index, psg.powerStateGraph);\n\n    o << \"vertices(graph) = \" << std::endl;\n    std::pair<PowerStateGraph::PSG_vertex_iter, PowerStateGraph::PSG_vertex_iter> vp;\n    for (vp = boost::vertices(psg.powerStateGraph); vp.first != vp.second; ++vp.first) {\n        o << \"vertex\" << index[*vp.first] << \" = {\" << psg.powerStateGraph[*vp.first].postSpike <<  \"}\";\n        if ( *vp.first == psg.offVertex ) {\n            o << \"\\n          (offVertex)\" << std::endl;\n        }\n        o << std::endl;\n    }\n\n    return o;\n}\n", "meta": {"hexsha": "4fe30be59eb4e63676ea897156e9d22f2d774a5a", "size": 44132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PowerStateGraph.cpp", "max_stars_repo_name": "JackKelly/disaggregation_MSc_code", "max_stars_repo_head_hexsha": "55d2113698cd39a5395808ad42a17c6edfd12742", "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/PowerStateGraph.cpp", "max_issues_repo_name": "JackKelly/disaggregation_MSc_code", "max_issues_repo_head_hexsha": "55d2113698cd39a5395808ad42a17c6edfd12742", "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/PowerStateGraph.cpp", "max_forks_repo_name": "JackKelly/disaggregation_MSc_code", "max_forks_repo_head_hexsha": "55d2113698cd39a5395808ad42a17c6edfd12742", "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": 37.0234899329, "max_line_length": 135, "alphanum_fraction": 0.6190745944, "num_tokens": 10264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1797683752981285}}
{"text": "/******************************************************************************\n * Copyright (C) 2020-2021 by\n * The Salk Institute for Biological Studies\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n******************************************************************************/\n\n#include <iostream>\n#include <sstream>\n#include <map>\n\n#include \"bng/ast.h\"\n#include \"bng/bng_engine.h\"\n#include \"bng/elem_mol_type.h\"\n#include \"bng/elem_mol.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/vf2_sub_graph_iso.hpp>\n#include <boost/graph/connected_components.hpp>\n\n#define NAUTY_CPU_DEFINED // silence a warning\n#include \"nauty/traces.h\"\n#include \"nauty/nausparse.h\"\n\n#include \"debug_config.h\"\n\n#include \"bng/cplx.h\"\n#include \"bng/bngl_names.h\"\n#include \"bng/semantic_analyzer.h\" // only for insert_compartment_id_to_set_based_on_type\n\nusing namespace boost;\nusing namespace std;\n\nnamespace BNG {\n\n// ------------------------------------ CplxInstance -------------------------\n\nbool Cplx::is_fully_qualified() const {\n  for (const ElemMol& mi: elem_mols) {\n    if (!mi.is_fully_qualified(*bng_data)) {\n      return false;\n    }\n  }\n  return true;\n}\n\n\nbool Cplx::is_connected() const {\n  assert(is_finalized());\n\n  // simply count connected components\n  size_t num_vertices = boost::num_vertices(graph);\n  vector<int> component_per_vertex(num_vertices);\n  int num_components = boost::connected_components(\n      graph,\n      boost::make_iterator_property_map(\n          component_per_vertex.begin(), boost::get(boost::vertex_index, graph), component_per_vertex[0]\n      )\n  );\n  assert(num_components > 0);\n  return num_components == 1;\n}\n\n\nvoid Cplx::finalize_cplx(const bool init_flags_and_compartments) {\n  if (elem_mols.empty()) {\n    return; // empty complex, ignoring finalization\n  }\n\n  if (init_flags_and_compartments) {\n    // volume or surface type\n    bool surf_type = false;\n    bool reactive_surf_type = false;\n    for (ElemMol& mp: elem_mols) {\n      // need to finalize flags - copy them from molecule type\n      mp.finalize_flags_and_sort_components(*bng_data);\n      // if at least one is a surface molecule then the whole cplx is surface molecule\n      if (mp.is_surf()) {\n        surf_type = true;\n      }\n\n      // if at least one is a reactive surface then the whole cplx is reactive surface\n      if (mp.is_reactive_surface()) {\n        reactive_surf_type = true;\n      }\n    }\n    if (surf_type) {\n      release_assert(!reactive_surf_type && \"Species cannot be both reactive surface and surface molecule.\");\n      set_flag(SPECIES_CPLX_MOL_FLAG_SURF);\n    }\n    else if (reactive_surf_type) {\n      set_flag(SPECIES_CPLX_MOL_FLAG_REACTIVE_SURFACE);\n    }\n\n    // set flag SPECIES_CPLX_FLAG_ONE_MOL_NO_COMPONENTS\n    bool is_simple = true;\n    if (elem_mols.size() > 1) {\n      is_simple = false;\n    }\n    if (is_simple) {\n      for (ElemMol& mi: elem_mols) {\n        if (!mi.components.empty()) {\n          is_simple = false;\n          break;\n        }\n      }\n    }\n    set_flag(SPECIES_CPLX_FLAG_ONE_MOL_NO_COMPONENTS, is_simple);\n  }\n\n  // we need graphs even for simple complexes because they can be used in reaction patterns\n  graph.clear();\n  create_graph();\n\n  set_finalized();\n}\n\n\nvoid Cplx::create_graph() {\n  graph.clear();\n\n  // convert molecule instances and their bonds into the boost graph representation\n\n  map<bond_value_t, small_vector<Graph::vertex_descriptor>> bonds_to_vertices_map;\n\n  // reserve some space for vertices, edges are stored using list\n  graph.m_vertices.reserve(elem_mols.size() * 8);\n\n  // add all molecules with their components and remember how they should be bound\n  for (ElemMol& mi: elem_mols) {\n    Graph::vertex_descriptor mol_desc = boost::add_vertex(MtVertexProperty(Node(&mi)), graph);\n\n    for (Component& ci: mi.components) {\n      // for patterns, only components that were explicitly listed are in component instances\n      Graph::vertex_descriptor comp_desc = boost::add_vertex(MtVertexProperty(Node(&ci)), graph);\n\n      // connect the component to its molecule\n      // TODO OPTIMIZATION:\n      //  - boost::add_edge is pretty slow (25% of time for the SynGAP model)\n      //  - it almost seems that we would need a different graph representation to optimize it,\n      //    the internal adjacency_list's EdgeList must be a list and it cannot be pre-allocated\n      boost::add_edge(mol_desc, comp_desc, graph);\n\n      // and remember its bond\n      if (ci.bond_has_numeric_value()) {\n        bonds_to_vertices_map[ci.bond_value].push_back(comp_desc);\n      }\n    }\n  }\n\n  // connect components\n  for (auto it: bonds_to_vertices_map) {\n    release_assert(it.second.size() == 2 && \"There must be exactly pairs of components connected with numbered bonds.\");\n    boost::add_edge(it.second[0], it.second[1], graph);\n  }\n}\n\n\nvoid Cplx::get_used_compartments(uint_set<compartment_id_t>& compartments) const {\n  compartments.clear();\n\n  assert(elem_mols.size() > 0);\n  for (const ElemMol& em: elem_mols) {\n    compartments.insert(em.compartment_id);\n  }\n}\n\n\ncompartment_id_t Cplx::get_complex_compartment_id(const bool dont_know_elem_mol_types) const {\n#ifndef NDEBUG\n  // consistency check of compartments\n  // similar as in SemanticAnalyzer::convert_cplx\n  bool ignored;\n  bool all_are_none_or_inout = true;\n  uint_set<compartment_id_t> vol_compartments;\n  uint_set<compartment_id_t> surf_compartments;\n\n  assert(elem_mols.size() > 0);\n  for (const ElemMol& em: elem_mols) {\n    insert_compartment_id_to_set_based_on_type(\n        bng_data, em.compartment_id,\n        all_are_none_or_inout, ignored, vol_compartments, surf_compartments);\n  }\n\n  // we might not know whether our compartment is surf or vol, so the check is weaker\n  assert(\n      all_are_none_or_inout ||\n      (vol_compartments.size() == 1 && surf_compartments.empty()) ||\n      (vol_compartments.size() <= 2 && surf_compartments.size() == 1));\n#endif\n\n  if (dont_know_elem_mol_types) {\n    // get the first surface compartment because we do not know the types of elementary molecules\n    // if surface compartment is not used, get the first volume compartment\n    compartment_id_t vol_cid = COMPARTMENT_ID_NONE;\n    for (const ElemMol& em: elem_mols) {\n      compartment_id_t cid = em.compartment_id;\n      if (is_specific_compartment_id(cid)) {\n        if (!bng_data->get_compartment(cid).is_3d) {\n          return cid;\n        }\n        else {\n          if (vol_cid == COMPARTMENT_ID_NONE) {\n            vol_cid = cid;\n          }\n        }\n      }\n    }\n    // no specific surface compartment was set, using the volume compartment if found\n    return vol_cid;\n  }\n  else if (is_surf()) {\n    // get the first set surface elem mol\n    for (const ElemMol& em: elem_mols) {\n      if (em.is_surf() && em.compartment_id != COMPARTMENT_ID_NONE) {\n        return em.compartment_id;\n      }\n    }\n    // no compartment is set\n    return COMPARTMENT_ID_NONE;\n  }\n  else {\n    // all are volume and must have the same compartment but in patterns,\n    // not all need to be set\n    // get the first set surface elem mol\n    for (const ElemMol& em: elem_mols) {\n      if (em.compartment_id != COMPARTMENT_ID_NONE) {\n        return em.compartment_id;\n      }\n    }\n    // no compartment is set\n    return COMPARTMENT_ID_NONE;\n  }\n}\n\n\nbool Cplx::matches_complex_pattern_ignore_orientation(const Cplx& pattern) const {\n\n#ifdef DEBUG_CPLX_MATCHING\n  cout << \"** matches_complex_pattern_ignore_orientation:\\n\";\n  cout << \"pattern:\\n\";\n  pattern.dump(false); cout << \"\\n\";\n  pattern.dump(true); cout << \"\\n\";\n  dump_graph(pattern.graph, bng_data);\n  cout << \"this instance:\\n\";\n  dump(false); cout << \"\\n\";\n  dump(true); cout << \"\\n\";\n  dump_graph(graph, bng_data);\n#endif\n  // this result cannot be cached because it might not be and applicable for other equivalent complexes,\n  // we might need to impose some ordering on elementary molecules and then we can reuse the result when\n  // creating products\n  VertexMappingVector mappings;\n  get_subgraph_isomorphism_mappings(pattern.graph, graph, true, mappings);\n  assert((mappings.size() == 0 || mappings.size() == 1) && \"We are searching only for the first match\");\n\n#ifdef DEBUG_CPLX_MATCHING\n  cout << \"** result: \" << !mappings.empty() << \"\\n\";\n#endif\n  // we need at least one match\n  return !mappings.empty();\n}\n\n\n// sets compartment to all contained elementary molecules\nvoid Cplx::set_compartment_id(const compartment_id_t cid, const bool override_only_compartment_none) {\n  // TODO: here could be some extra checks related to orientation\n  // set compartment to all elementary molecules\n  assert(!elem_mols.empty());\n  for (ElemMol& em: elem_mols) {\n    // we cannot check here whether compartment type (2d/3d matches surf/vol) because\n    // we do not necessarily know the the of the elementary molecules at all times\n    if (!override_only_compartment_none || em.compartment_id == COMPARTMENT_ID_NONE) {\n      em.compartment_id = cid;\n    }\n  }\n}\n\n\nuint Cplx::get_pattern_num_matches(const Cplx& pattern) const {\n  assert(is_finalized() && pattern.is_finalized());\n  VertexMappingVector mappings;\n  get_subgraph_isomorphism_mappings(pattern.graph, graph, false, mappings);\n  return mappings.size();\n}\n\n\nbool Cplx::matches_complex_fully_ignore_orientation(const Cplx& other) const {\n  if (graph.m_vertices.size() != other.graph.m_vertices.size()) {\n    // we need full match\n    return false;\n  }\n\n  VertexMappingVector mappings;\n  get_subgraph_isomorphism_mappings(other.graph, graph, true, mappings);\n  assert((mappings.size() == 0 || mappings.size()) == 1 && \"We are searching only for the first match\");\n\n  if (mappings.size() != 1 || mappings[0].size() != graph.m_vertices.size()) {\n    // no mapping found or not all nodes match\n    return false;\n  }\n\n  // we must also check that compartments are the same,\n  // this must be done separately because the Graph object Node allows only\n  // one type of comparison and the one used considers one graph a pattern,\n  // however we must compare for equality here\n  VertexNameMap graph1_index = boost::get(boost::vertex_name, graph);\n  VertexNameMap graph2_index = boost::get(boost::vertex_name, other.graph);\n\n  // for each molecule instance\n  typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;\n  std::pair<vertex_iter, vertex_iter> graph1_mol_it;\n  for (graph1_mol_it = boost::vertices(graph); graph1_mol_it.first != graph1_mol_it.second; ++graph1_mol_it.first) {\n    vertex_descriptor_t graph1_mol_desc = *graph1_mol_it.first;\n\n    const Node& graph1_mol = graph1_index[graph1_mol_desc];\n    if (!graph1_mol.is_mol) {\n      continue;\n    }\n\n    // get corresponding molecule from the 2nd graph\n    auto graph2_mol_it = mappings[0].find(graph1_mol_desc);\n    assert(graph2_mol_it != mappings[0].end() && \"Mapping must exist\");\n    vertex_descriptor_t graph2_mol_desc = graph2_mol_it->second;\n\n    const Node& graph2_mol = graph2_index[graph2_mol_desc];\n    assert(graph2_mol.is_mol);\n\n    if (graph1_mol.mol->compartment_id != graph2_mol.mol->compartment_id) {\n      return false;\n    }\n  }\n  return true;\n}\n\n\nvoid Cplx::renumber_bonds() {\n  map<bond_value_t, bond_value_t> new_bond_values;\n\n  for (ElemMol& mi: elem_mols) {\n    for (Component& ci: mi.components) {\n      if (ci.bond_has_numeric_value()) {\n        auto it = new_bond_values.find(ci.bond_value);\n        if (it == new_bond_values.end()) {\n          // new bond value, numbering from 1\n          bond_value_t new_value = new_bond_values.size() + 1;\n          new_bond_values[ci.bond_value] = new_value;\n          ci.bond_value = new_value;\n        }\n        else {\n          // we have already seen this bond value, use the new value\n          ci.bond_value = it->second;\n        }\n      }\n    }\n  }\n}\n\n\n// https://computationalcombinatorics.wordpress.com/2012/09/20/canonical-labelings-with-nauty/\nvoid Cplx::canonicalize(const bool sort_components_by_name_do_not_finalize) {\n  if (elem_mols.size() == 1) {\n    canonicalize_w_single_elem_mol(sort_components_by_name_do_not_finalize);\n  }\n  else {\n    canonicalize_complex(sort_components_by_name_do_not_finalize);\n  }\n\n  // update the boost graph representation\n  if (!sort_components_by_name_do_not_finalize) {\n    finalize_cplx();\n  }\n\n  set_flag(SPECIES_CPLX_FLAG_IS_CANONICAL);\n  name = \"\";\n  to_str(name);\n}\n\n\nvoid Cplx::canonicalize_w_single_elem_mol(const bool sort_components_by_name_do_not_finalize) {\n  assert(elem_mols.size() == 1);\n\n  if (!sort_components_by_name_do_not_finalize) {\n    // sort components in molecules to their prescribed form\n    // and in a way that the state name is ascending (we have no bonds here)\n    elem_mols[0].canonicalize(*bng_data);\n  }\n  else {\n    elem_mols[0].sort_components_by_name(*bng_data);\n  }\n}\n\n\nvoid Cplx::canonicalize_complex(const bool sort_components_by_name_do_not_finalize) {\n\n  // we use nauty/traces to construct a canonical version of the graph\n  // we are using only the base BNG API, not the boost graphs to stay independent\n\n  // 1) construct mapping vertex - index -> molecule or component\n  //    and also store information on bonds and other details\n  vector<Node> nodes;\n  // map bond index -> vertex indices\n  map<bond_value_t, vector<int>> bond_index_to_components;\n  // mapping to know to which molecule a component belongs\n  map<int, int> component_to_mol_index;\n  // indexed by index, pair is (molecule index, component index) in this cplx\n  // second value is -1 if the index represents a molecule\n  vector<pair<int, int>> index_to_mol_and_component_index;\n  int index = 0;\n  for (int m_index = 0; m_index < (int)elem_mols.size(); m_index++) {\n    ElemMol& mi = elem_mols[m_index];\n    nodes.push_back(Node(&mi));\n    int mol_index = index;\n    index_to_mol_and_component_index.push_back(make_pair(m_index, -1));\n    index++;\n\n    for (int c_index = 0; c_index < (int)mi.components.size(); c_index++) {\n      Component& ci = mi.components[c_index];\n      nodes.push_back(Node(&ci));\n      component_to_mol_index[index] = mol_index;\n      index_to_mol_and_component_index.push_back(make_pair(m_index, c_index));\n      if (ci.bond_has_numeric_value()) {\n        bond_index_to_components[ci.bond_value].push_back(index);\n      }\n      index++;\n    }\n  }\n\n  // 2) create nauty graph representation\n  vector<size_t> v_edge_indices;\n  vector<int> d_out_degrees;\n  vector<int> e_neighbors;\n  map<string, vector<int>> color_classes;\n\n  for (int index = 0; index < (int)nodes.size(); index++) {\n    const Node& n = nodes[index];\n\n    // the index for this node for neighbors simply starts where the last ended\n    v_edge_indices.push_back(e_neighbors.size());\n\n    // neighbors\n    int num_neighbors = 0;\n    if (n.is_mol) {\n      // for a molecule - neighbors are all edges - the indices directly follow ours\n      for (int i = 0; i < (int)n.mol->components.size(); i++) {\n        e_neighbors.push_back(index + i + 1); // need +1 because the first component is the next one\n        num_neighbors++;\n      }\n\n      // also remember color\n      // use name instead of id so that we are not dependent on the order of declatation in the BNG file\n      color_classes[\"M:\" + bng_data->get_elem_mol_type(n.mol->elem_mol_type_id).name].push_back(index);\n    }\n    else {\n      // index of the component's molecule\n      assert(component_to_mol_index.count(index) != 0);\n      e_neighbors.push_back(component_to_mol_index[index]);\n      num_neighbors++;\n\n      // index of the second component, if connected\n      if (n.component->bond_has_numeric_value()) {\n        assert(bond_index_to_components.count(n.component->bond_value) != 0);\n        vector<int>& bonds = bond_index_to_components[n.component->bond_value];\n        assert(bonds.size() == 2);\n        int second_index = -1;\n        if (bonds[0] == index) {\n          second_index = bonds[1];\n        }\n        else if (bonds[1] == index) {\n          second_index = bonds[0];\n        }\n        else {\n          assert(false);\n        }\n        e_neighbors.push_back(second_index);\n        num_neighbors++;\n      }\n\n      // also remember 'color', we need to distinguish states as well\n      string component_label = \"C:\" + bng_data->get_component_type(n.component->component_type_id).name;\n      if (n.component->state_is_set()) {\n        component_label += \"~\" + bng_data->get_state_name(n.component->state_id);\n      }\n      color_classes[component_label].push_back(index);\n    }\n\n    d_out_degrees.push_back(num_neighbors);\n  }\n\n  // define coloring, nauty has a weird way of assigning colors to nodes:\n  // libs/nauty/nug27.pdf, p. 18:\n  // if ptn[i] = 0, then a cell (colour class) ends at position i.\n  // so let's say I have these data:\n  //   lab: 2 3 5 6 1 0 4 7 8 all vertices in some order\n  //   ptn: 0 0 1 1 1 0 1 1 0 cells end where the zeros are (non-zero value specifies continuation)\n  // it defines these classes\n  //   [{2}, {3}, {0, 1, 5, 6}, {4, 7, 8}].\n\n  vector<int> labels; // vertex indices\n  vector<int> permutations; // ptn in nauty\n\n#ifdef DEBUG_CANONICALIZATION\n  cout << \"Before \" << to_str(*bng_data) << \"\\n\";\n#endif\n\n  // labels.push_back(index); // index of vertices in the colors array\n  for (auto it_color: color_classes) {\n    vector<int>& indices = it_color.second;\n    for (size_t i = 0; i < indices.size(); i++) {\n      labels.push_back(indices[i]);\n      // 1 - there are more, 0 - last of this class\n      if (i != indices.size() - 1) {\n        permutations.push_back(1);\n      }\n      else {\n        permutations.push_back(0);\n      }\n    }\n  }\n\n  // setup sparse graph representation\n  SG_DECL(sg1);\n  int num_verts = v_edge_indices.size();\n  sg1.nde = e_neighbors.size();\n  sg1.nv = num_verts;\n  sg1.d = d_out_degrees.data();\n  sg1.dlen = d_out_degrees.size();\n  sg1.v = v_edge_indices.data();\n  sg1.vlen = num_verts;\n  sg1.e = e_neighbors.data();\n  sg1.elen = e_neighbors.size();\n\n  // 3) get canonical mapping\n  SG_DECL(cg1);\n  //DEFAULTOPTIONS_SPARSEGRAPH(options);\n  //statsblk stats;\n  DEFAULTOPTIONS_TRACES(options);\n  options.getcanon = TRUE;\n  options.defaultptn = FALSE;\n  options.digraph = FALSE;\n  TracesStats stats;\n\n  int* orbits = new int[num_verts]; // unused but must be allocated\n\n  // - do the actual canonicalization, labels define how to reorder molecules and components\n  //   using function Traces instead of sparsenauty or nauty because it does not leave so much\n  //   unfreed memory\n  // - WARNING: Threads function may not be thread safe, nauty uses many globals\n  // - overwrites contents of labels and permutations\n#ifdef DEBUG_CANONICALIZATION\n  dump_container(labels, \"labels before\");\n  dump_container(permutations, \"permutations before\");\n#endif\n\n  Traces(&sg1, labels.data(), permutations.data(), orbits, &options, &stats, &cg1);\n\n#ifdef DEBUG_CANONICALIZATION\n  dump_container(labels, \"labels after\");\n  dump_container(permutations, \"permutations after\");\n#endif\n\n  SG_FREE( cg1 );\n  delete [] orbits;\n  nausparse_freedyn(); // frees allocated thread local storage memory\n\n  // 4) create molecules and components in this complex from scratch\n  // the numeric bonds are still ok\n\n  ElemMolVector new_mol_instances(elem_mols.size());\n  map<int, int> old_to_new_mol_index;\n  // now go by the ordered reverse mapping and create mols\n  int new_mol_index = 0;\n  for (int index: labels) {\n    // is this node a molecule?\n    pair<int, int> orig_mci = index_to_mol_and_component_index[index];\n    if (orig_mci.second == -1) {\n      // copy everything and clear components, they will be added later\n      new_mol_instances[new_mol_index] = elem_mols[orig_mci.first];\n      new_mol_instances[new_mol_index].components.clear();\n      old_to_new_mol_index[orig_mci.first] = new_mol_index;\n      new_mol_index++;\n    }\n  }\n\n  // once we have mols, add also the components\n  for (int index: labels) {\n    // is this node a component?\n    pair<int, int> orig_mci = index_to_mol_and_component_index[index];\n    if (orig_mci.second != -1) {\n      int new_mol_index = old_to_new_mol_index[orig_mci.first];\n      assert(new_mol_index < (int)new_mol_instances.size());\n      // copy components\n      new_mol_instances[new_mol_index].components.push_back(\n          elem_mols[orig_mci.first].components[orig_mci.second]\n      );\n    }\n  }\n\n  // and overwrite\n  elem_mols = new_mol_instances;\n\n  // 5) renumber bonds so that they follow the new molecule ordering\n  renumber_bonds();\n\n  // 6) sort components in molecules back to their prescribed form\n  // and in a way that the bond index is increasing\n  for (ElemMol& mi: elem_mols) {\n    if (!sort_components_by_name_do_not_finalize) {\n      // sort components in molecules to their prescribed form\n      // and in a way that the state name is ascending (we have no bonds here)\n      mi.canonicalize(*bng_data);\n    }\n    else {\n      mi.sort_components_by_name(*bng_data);\n    }\n  }\n\n  // 7) and renumber bonds again\n  renumber_bonds();\n\n#ifdef DEBUG_CANONICALIZATION\n  cout << \"After \" << to_str(*bng_data) << \"\\n\";\n#endif\n}\n\n\nvoid Cplx::remove_compartment_from_elem_mols(BNG::compartment_id_t cid) {\n  if (cid == BNG::COMPARTMENT_ID_NONE) {\n    return;\n  }\n  release_assert(!BNG::is_in_out_compartment_id(cid));\n  for (auto& em: elem_mols) {\n    if (em.compartment_id == cid) {\n      em.compartment_id = BNG::COMPARTMENT_ID_NONE;\n    }\n  }\n}\n\n\nstd::string Cplx::to_str(bool in_surf_reaction, const bool with_orientation) const {\n  std::string res;\n  to_str(res, in_surf_reaction, with_orientation);\n  return res;\n}\n\n\nvoid Cplx::to_str(std::string& res, const bool in_surf_reaction, const bool with_orientation) const {\n\n  uint_set<compartment_id_t> used_compartments;\n  get_used_compartments(used_compartments);\n  bool use_individual_compartments = !(used_compartments.size() == 1) || elem_mols.size() == 1;\n\n  for (size_t i = 0; i < elem_mols.size(); i++) {\n    elem_mols[i].to_str(*bng_data, res, use_individual_compartments);\n\n    if (i != elem_mols.size() - 1) {\n      res += \".\";\n    }\n  }\n\n  if (used_compartments.size() == 1 && *used_compartments.begin() == COMPARTMENT_ID_NONE) {\n    if (with_orientation) {\n      if (orientation == ORIENTATION_UP) {\n        res += \"'\";\n      }\n      else if (orientation == ORIENTATION_DOWN) {\n        res += \",\";\n      }\n      else if (in_surf_reaction && orientation == ORIENTATION_NONE) {\n        res += \";\";\n      }\n    }\n  }\n  else if (!use_individual_compartments) {\n    compartment_id_t single_compartment_id = *used_compartments.begin();\n    // single compartment is used as prefix when all compartments are the same\n    if (is_in_out_compartment_id(single_compartment_id)) {\n      res = \"@\" + compartment_id_to_str(single_compartment_id) + \":\" + res;\n    }\n    else {\n      const string& compartment_name = bng_data->get_compartment(single_compartment_id).name;\n      if (compartment_name != DEFAULT_COMPARTMENT_NAME) {\n        res = \"@\" + bng_data->get_compartment(single_compartment_id).name  + \":\" + res;\n      }\n    }\n  }\n}\n\n\nvoid Cplx::dump(const bool for_diff, const std::string ind) const {\n  if (!for_diff) {\n    cout << ind << to_str();\n  }\n  else {\n    cout << ind << \"orientation: \" << orientation << \"\\n\";\n    cout << ind << \"mol_instances:\\n\";\n    for (size_t i = 0; i < elem_mols.size(); i++) {\n      cout << ind << i << \":\\n\";\n      elem_mols[i].dump(*bng_data, true, ind + \"  \");\n    }\n  }\n}\n\n} /* namespace BNG */\n", "meta": {"hexsha": "2ae237a9f1e2a6aa74ccb9cf760176a318d0e78b", "size": 23397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bng/cplx.cpp", "max_stars_repo_name": "mcellteam/libbng", "max_stars_repo_head_hexsha": "1d9fe00a2cc9a8d223078aec2700e7b86b10426a", "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": "bng/cplx.cpp", "max_issues_repo_name": "mcellteam/libbng", "max_issues_repo_head_hexsha": "1d9fe00a2cc9a8d223078aec2700e7b86b10426a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bng/cplx.cpp", "max_forks_repo_name": "mcellteam/libbng", "max_forks_repo_head_hexsha": "1d9fe00a2cc9a8d223078aec2700e7b86b10426a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-11T21:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T21:13:20.000Z", "avg_line_length": 33.0933521924, "max_line_length": 120, "alphanum_fraction": 0.6790186776, "num_tokens": 6024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17976837529812847}}
{"text": "#include <functional>\n#include <mutex>\n#include <thread>\n#include <string>\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <map_msgs/OccupancyGridUpdate.h>\n#include <nav_msgs/OccupancyGrid.h>\n#include <queue>\n#include <unordered_map>\n// #include <boost>\n#include <time.h>\n#include <random>\n\n#define INF INT_MAX\nusing namespace std;\n\nnamespace frontier_detection\n{\n    class frontierdetection\n    {\n        public:\n            frontierdetection(ros::NodeHandle private_nh)\n            {\n                getCostmap = false;\n                NODE = private_nh;\n                costmap_sub_global_ = private_nh.subscribe<nav_msgs::OccupancyGrid>(\"/map\", 1, &frontierdetection::map_sub, this);\n                costmap_pub_global_=private_nh.advertise<nav_msgs::OccupancyGrid>(\"/sampling_partles_map\", 1);\n                costmap_sub_global_ = private_nh.subscribe<nav_msgs::OccupancyGrid>(\"/sampling_partles_map\", 1, &frontierdetection::CostmapSubCallback_global, this);\n                // frontier_pub_=private_nh.advertise<geometry_msgs::PoseStamped>(\"/frontier/goal\", 1);\n                // robot_position_pub_=private_nh.advertise<geometry_msgs::PoseStamped>(\"/robot_position\", 1);\n            }\n\n\n        private:\n            void map_sub(const nav_msgs::OccupancyGrid::ConstPtr& map)\n            {\n                cout<<\"get map\"<<endl;\n                nav_msgs::OccupancyGrid map_temp=*map;\n                int x_step=10;\n                int y_step=10;\n                for(int i=0;i<map_temp.info.height;i++)\n                {\n                    if(i%y_step==0)\n                    {\n                    for(int j=0;j<map_temp.info.width;j++)\n                        {\n                            if(j%x_step==0&&map_temp.data.at(i*map_temp.info.width+j)==0)\n                                map_temp.data.at(i*map_temp.info.width+j)=80;\n                                particle_indexes.push_back(i*map_temp.info.width+j);\n                        }\n                    }\n                }\n                while(1)\n                {\n                    sleep(1);\n                    costmap_pub_global_.publish(map_temp);\n                }\n            }\n\n            void CostmapSubCallback_global(const nav_msgs::OccupancyGrid::ConstPtr& map)\n            {\n                nav_msgs::OccupancyGrid map_temp=*map;\n                partle_move(map_temp,particle_indexes);\n            }\n            void partle_move(const nav_msgs::OccupancyGrid& map, std::vector<int> indexes)\n            {\n                for(auto index:indexes)\n                {\n                    int mx,my;\n                    indexTomap(map,index,mx,my);\n                    \n                }\n            }\n\n            void collion_check()\n            {\n\n            }\n            void indexTomap(const nav_msgs::OccupancyGrid& map,int index,int& x,int& y)\n            {\n                y=index/map.info.width;\n                x=index%map.info.width;\n            }\n\n\n\n\n    // void find_closest_frontier(const nav_msgs::OccupancyGrid& occupancy_map,int start_idx,int &frontier_idx) \n    // {\n    //     int a[4]={1,(int)occupancy_map.info.width,-1,-(int)occupancy_map.info.width};\n    //     std::unordered_map<int, int> visited, unvisited;\n    //     std::queue<int> id;\n    //     int current;\n    //     if(occupancy_map.data[start_idx]<97)\n    //     {\n    //         id.push(start_idx);\n    //         while (id.size()) \n    //         {\n    //             current = id.front();\n    //             id.pop();\n    //             for(int i=0;i<4;i++)\n    //             {\n    //                 int neighbor_id=current+a[i];\n    //                 if(neighbor_id>=0&&neighbor_id<occupancy_map.info.width*occupancy_map.info.height)\n    //                     {\n    //                             if((occupancy_map.data[neighbor_id]<97)&&!(visited[neighbor_id]))\n    //                             {\n    //                                 if(occupancy_map.data[current]==-1)\n    //                                 {\n    //                                     frontier_idx=current;\n    //                                     id=queue<int>();\n    //                                     break;\n    //                                 }\n    //                                     id.push(neighbor_id);\n    //                                     ++visited[neighbor_id];\n    //                             }\n    //                     }\n    //             }\n    //         }\n    //     }\n    // }\n            \n    //         void GetRobotpose(std::string iden_frame_id,geometry_msgs::PoseStamped& global_pose, ros::Time timestamp)\n    //         {\n    //         tf::StampedTransform transform;\n    //         geometry_msgs::PoseStamped iden_pose;\n    //         iden_pose.header.frame_id = iden_frame_id;\n    //         iden_pose.header.stamp = ros::Time::now(); \n    //         iden_pose.pose.orientation.w = 1;\n    //         tf_listener_.waitForTransform(\"/robot0/map\",iden_frame_id, ros::Time(0), ros::Duration(2.0));\n    //         tf_listener_.lookupTransform( \"/robot0/map\",iden_frame_id, ros::Time(0), transform);\n    //         global_pose.pose.position.x=transform.getOrigin().x();\n    //         global_pose.pose.position.y=transform.getOrigin().y();\n    //         global_pose.pose.position.z=transform.getOrigin().z();\n    //         }\n\n            bool getCostmap;\n            std::vector<int> particle_indexes;\n            ros::NodeHandle NODE;\n            ros::Subscriber costmap_sub_global_;\n            ros::Publisher frontier_pub_;\n            ros::Publisher robot_position_pub_;\n            // ros::Publisher frontier_map_pub_;\n            ros::Publisher costmap_pub_global_;\n            nav_msgs::OccupancyGrid global_costmap;\n            nav_msgs::OccupancyGrid local_costmap;\n            geometry_msgs::PoseStamped global_pose;\n            geometry_msgs::PoseStamped closest_frontier_point;\n            \n\n            std::mutex lock_costmap;\n            std::thread tf_thread_;\n            tf::TransformListener tf_listener_;\n            int robot_index;\n            int seed;\n            int frontier_temp=0;\n            int frontier_count=0;\n            int closest_frontier_idx=0;\n            int resolution=0.2;\n\n            // protected:\n\n    };\n}\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"frontier_detection\");\n    ros::NodeHandle private_nh1(\"~\");\n    frontier_detection::frontierdetection ta(private_nh1);\n    ros::MultiThreadedSpinner spinner;\n    spinner.spin();\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "f35d32a729666cc3458f0a13fcdab3fe4e69423b", "size": 6515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "frontier_detection_using_seed/src/sampling_based_frontier_detection.cpp", "max_stars_repo_name": "citaer/frontier_detection", "max_stars_repo_head_hexsha": "93981f94e419fff9df282df4df75348b2ecc6d5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-04T13:55:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T13:55:18.000Z", "max_issues_repo_path": "frontier_detection_using_seed/src/sampling_based_frontier_detection.cpp", "max_issues_repo_name": "citaer/frontier_detection", "max_issues_repo_head_hexsha": "93981f94e419fff9df282df4df75348b2ecc6d5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frontier_detection_using_seed/src/sampling_based_frontier_detection.cpp", "max_forks_repo_name": "citaer/frontier_detection", "max_forks_repo_head_hexsha": "93981f94e419fff9df282df4df75348b2ecc6d5e", "max_forks_repo_licenses": ["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.6011235955, "max_line_length": 165, "alphanum_fraction": 0.5046815042, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17976837529812847}}
{"text": "// Disable warnings for dlib\n//\n// Note: All additional dlib submodule dependencies should\n// be included here, and all modules dependent on dlib\n// should include this file. The dlib compilation process\n// emits numerous pedantic and variadic macro errors, so this\n// method of header inclusion is used to suppress them\n#pragma GCC system_header\n\n#include <dlib/matrix.h>\n#include <dlib/svm.h>\n", "meta": {"hexsha": "65f1b97ea0526ba17740282405851034a0c6ef43", "size": 395, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libclipper/include/clipper/dlib_dependencies.hpp", "max_stars_repo_name": "DNCoelho/clipper", "max_stars_repo_head_hexsha": "0144078c9da757ee319d60b362d9f51538657ca8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1403.0, "max_stars_repo_stars_event_min_datetime": "2017-01-11T23:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:30:28.000Z", "max_issues_repo_path": "src/libclipper/include/clipper/dlib_dependencies.hpp", "max_issues_repo_name": "DNCoelho/clipper", "max_issues_repo_head_hexsha": "0144078c9da757ee319d60b362d9f51538657ca8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 724.0, "max_issues_repo_issues_event_min_datetime": "2017-01-18T02:06:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-13T19:06:30.000Z", "max_forks_repo_path": "src/libclipper/include/clipper/dlib_dependencies.hpp", "max_forks_repo_name": "DNCoelho/clipper", "max_forks_repo_head_hexsha": "0144078c9da757ee319d60b362d9f51538657ca8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 308.0, "max_forks_repo_forks_event_min_datetime": "2017-01-11T21:32:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:41:02.000Z", "avg_line_length": 32.9166666667, "max_line_length": 61, "alphanum_fraction": 0.7721518987, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451353339457, "lm_q1q2_score": 0.17976837529812845}}
{"text": "#include \"tag_hierarchy/tag_hierarchy.h\"\n\n#include \"models/models.h\"\n\n#include <boost/graph/adj_list_serialize.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/serialization/variant.hpp>\n#include <boost/serialization/vector.hpp>\n\n\n#include <functional>\n#include <tag_hierarchy/commands/command.h>\n\nusing VertexIterator = boost::graph_traits<TagHierarchyGraph>::vertex_iterator;\nusing InEdgeIterator = TagHierarchyGraph::in_edge_iterator;\nusing OutEdgeIterator = TagHierarchyGraph::out_edge_iterator;\n\nusing DispatchFunction =\n    std::function<std::vector<NodeType>(std::vector<NodeType>&)>;\n\n\n\nclass TagHierarchyImpl {\nprivate:\n    TagHierarchyGraph graph_;\n    std::unordered_map<std::string, VertexT> vertices_;\n    std::map<std::string, DispatchFunction> command_func_dispatch_;\n    EdgeLabelMap edge_labels_;\n    VertexT root_;\n\npublic:\n\n    TagHierarchyGraph& GetGraph() {\n        return graph_;\n    }\n\n    std::unordered_map<std::string, VertexT>& GetVertices() {\n        return vertices_;\n    }\n\n    EdgeLabelMap& GetEdgeLabels() {\n        return edge_labels_;\n    }\n\n    VertexT& GetRoot() {\n        return root_;\n    }\n\n    std::map<std::string, DispatchFunction> GetDispatchMap() {\n        return command_func_dispatch_;\n    }\n\n    std::vector<NodeType>\n    Store(std::vector<NodeType>& message) {\n        auto retval = std::vector<NodeType>();\n        std::ostringstream stream;\n        {\n            boost::iostreams::filtering_stream<boost::iostreams::output> f;\n            f.push(boost::iostreams::gzip_compressor());\n            f.push(stream);\n            boost::archive::binary_oarchive archive(f);\n            archive << *this;\n        }\n        retval.push_back({{\"serialized_graph\", stream.str()}});\n        return retval;\n    }\n\n    std::vector<NodeType>\n    Restore(std::vector<NodeType>& message) {\n        ClearGraph();\n        auto retval = std::vector<NodeType>();\n        const std::string graph_state =\n            boost::get<std::string>(message[0][\"serialized_hierarchy\"]);\n        std::istringstream buffer(graph_state);\n        boost::iostreams::filtering_stream<boost::iostreams::input> f;\n        f.push(boost::iostreams::gzip_decompressor());\n        f.push(buffer);\n        boost::archive::binary_iarchive archive(f);\n        archive >> *this;\n        retval.push_back({{\"success\", true}});\n        return retval;\n    }\n\n    std::vector<NodeType>\n    HealthCheck(std::vector<NodeType>& message) {\n        auto retval = std::vector<NodeType>();\n        if (root_ == std::numeric_limits<VertexT>::max()) {\n            retval.push_back({{std::string(\"ok\"), false},\n                              {std::string(\"error\"), std::string(\"Cache not populated\")}});\n            return retval;\n        }\n        retval.push_back({{std::string(\"ok\"), true}});\n        return retval;\n    }\n\n    void\n    ClearGraph() {\n        graph_.clear();\n        vertices_.clear();\n        root_ = std::numeric_limits<VertexT>::max();\n    }\n\n    std::vector<NodeType>\n    Handle(std::vector<NodeType> &message)\n    {\n        auto command_map = message.at(0);\n        std::string command = boost::get<std::string>(command_map[\"command\"]);\n        auto func = command_func_dispatch_[command];\n        auto retval = func(message);\n        return retval; //command_func_dispatch_[command](message);\n    }\n\n    TagHierarchyImpl() : command_func_dispatch_({\n                             {\"store\", [this](std::vector<NodeType> &nodes) -> std::vector<NodeType> {\n                                  return this->Store(nodes);\n                              }},\n                             {\"restore\", [this](std::vector<NodeType> &nodes) -> std::vector<NodeType> {\n                                  return this->Restore(nodes);\n                              }},\n                             {\"flush\", [this](std::vector<NodeType> &nodes) -> std::vector<NodeType> {\n                                  this->ClearGraph();\n                                  return {{{std::string(\"success\"), std::string(\"hierarchy flushed\")}}};\n                              }},\n                             {\"healthcheck\", [this](std::vector<NodeType> &nodes) -> std::vector<NodeType> {\n                                  return this->HealthCheck(nodes);\n                              }},\n                         }),\n                         edge_labels_({{{\"Physical hierarchy\", 0}}}),\n                         root_(std::numeric_limits<VertexT>::max())\n    {\n    };\n    TagHierarchyImpl(const TagHierarchyImpl& in) : command_func_dispatch_(in.command_func_dispatch_) {}\n\n    void Register(Command& in, std::string name) {\n        auto func = in.Function();\n        command_func_dispatch_[name] = func;\n    }\n\n    template<typename Archive>\n    void save(Archive& ar, const unsigned int version) const {\n        ar & graph_;\n        ar & edge_labels_;\n    }\n\n    template<typename Archive>\n    void load(Archive& ar, const unsigned int version) {\n        ar & graph_;\n        ar & edge_labels_;\n        auto [start, end] = boost::vertices(graph_);\n        for (auto iter = start; iter != end; ++iter) {\n            if (graph_[*iter].id == \"root\") {\n                root_ = *iter;\n            }\n            vertices_[graph_[*iter].id] = *iter;\n        }\n    }\n    BOOST_SERIALIZATION_SPLIT_MEMBER()\n};\n\n\nstd::vector<NodeType>\nTagHierarchy::Handle(std::vector<NodeType>& message) {\n    return GetTagHierarchy().Handle(message);\n}\n\nTagHierarchyImpl&\nTagHierarchy::GetTagHierarchy() {\n    static TagHierarchyImpl taghierarchy_impl;\n    return taghierarchy_impl;\n}\n\nTagHierarchyGraph&\nTagHierarchy::GetGraph() {\n    return GetTagHierarchy().GetGraph();\n}\n\nstd::unordered_map<std::string, VertexT>&\nTagHierarchy::GetVertices() {\n    return GetTagHierarchy().GetVertices();\n}\n\nEdgeLabelMap &\nTagHierarchy::GetEdgeLabels() {\n    return GetTagHierarchy().GetEdgeLabels();\n}\n\nVertexT&\nTagHierarchy::GetRoot() {\n    return GetTagHierarchy().GetRoot();\n}\n\nvoid\nTagHierarchy::Register(Command &in, std::string name) {\n    GetTagHierarchy().Register(in, name);\n}\n", "meta": {"hexsha": "868b751b2b92c2389a583a636f88d829a630d80b", "size": 6436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tag_hierarchy/tag_hierarchy.cpp", "max_stars_repo_name": "equinor/ioc-hierarchy-service", "max_stars_repo_head_hexsha": "e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-22T07:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:24:28.000Z", "max_issues_repo_path": "tag_hierarchy/tag_hierarchy.cpp", "max_issues_repo_name": "equinor/ioc-hierarchy-service", "max_issues_repo_head_hexsha": "e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-08-03T13:00:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T10:08:54.000Z", "max_forks_repo_path": "tag_hierarchy/tag_hierarchy.cpp", "max_forks_repo_name": "equinor/ioc-hierarchy-service", "max_forks_repo_head_hexsha": "e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9", "max_forks_repo_licenses": ["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.3951219512, "max_line_length": 108, "alphanum_fraction": 0.6042573027, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.17976836831884152}}
{"text": "#include <merely3d/app.hpp>\n#include <merely3d/window.hpp>\n\n#include <Eigen/Geometry>\n\n#include \"../demo/example_model.hpp\"\n\nusing merely3d::Window;\nusing merely3d::WindowBuilder;\nusing merely3d::Frame;\nusing merely3d::Material;\nusing merely3d::Color;\nusing merely3d::Line;\n\nusing merely3d::renderable;\nusing merely3d::Rectangle;\nusing merely3d::Box;\nusing merely3d::Sphere;\n\nusing Eigen::Vector2f;\nusing Eigen::Vector3f;\nusing Eigen::Quaternionf;\nusing Eigen::AngleAxisf;\n\nmerely3d::StaticMesh load_example_model()\n{\n    // Create a static mesh which we can use when rendering\n    const auto & vn = merely3d::example_model::vertices_and_normals;\n    const auto & idx = merely3d::example_model::indices;\n    const auto model_vertices_normals = std::vector<float>(vn.begin(), vn.end());\n    const auto model_indices = std::vector<unsigned int>(idx.begin(), idx.end());\n    return merely3d::StaticMesh(model_vertices_normals, model_indices);\n}\n\n/// This relatively minimal example is used mainly to test parts of merely3d\n/// for memory errors or undefined behavior with sanitizers such as\n/// -fsanitize=address and/or -fsanitize=undefined\nint main()\n{\n    // Constructing the app first is essential: it makes sure that\n    // GLFW is set up properly. Note that as an alternative, you can call\n    // glfw init/terminate yourself directly, but you must be careful that\n    // any windows are destroyed before calling terminate(). App automatically\n    // takes care of this as long as it outlives any windows.\n    merely3d::App app;\n\n    {\n        auto window = WindowBuilder()\n                .dimensions(1024, 768)\n                .title(\"Hello merely3d!\")\n                .multisampling(8)\n                .build();\n\n        for (int i = 0; i < 100 && !window.should_close(); ++i)\n        {\n            window.render_frame([] (Frame & frame)\n            {\n                frame.draw(renderable(Rectangle(0.5, 0.5))\n                            .with_position(1.0, 0.0, 0.5)\n                            .with_orientation(AngleAxisf(0.78, Vector3f(1.0f, 0.0f, 0.0f)))\n                            .with_material(Material().with_color(Color(0.5, 0.3, 0.3))));\n\n                frame.draw_line(Line(Vector3f(0.0, 0.0, 0.0), Vector3f(10.0, -5.0, 10.0)));\n                frame.draw(renderable(load_example_model()));\n            });\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "7c5d8cbfb75a52d66692e1329b47638d93ec4466", "size": 2361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/minimal/main.cpp", "max_stars_repo_name": "digitalillusions/merely3d", "max_stars_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T12:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-31T04:47:16.000Z", "max_issues_repo_path": "examples/minimal/main.cpp", "max_issues_repo_name": "digitalillusions/merely3d", "max_issues_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T13:54:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-06T13:48:24.000Z", "max_forks_repo_path": "examples/minimal/main.cpp", "max_forks_repo_name": "digitalillusions/merely3d", "max_forks_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-03T19:10:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-05T14:10:15.000Z", "avg_line_length": 33.2535211268, "max_line_length": 91, "alphanum_fraction": 0.6408301567, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.179752752561444}}
{"text": "#include <iostream>\n#include <vector>\n#include <list>\n#include <algorithm>\n#include <chrono>\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::list;\n\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/distributions/normal.hpp>\n\nusing boost::math::students_t;\nusing boost::math::cdf;\nusing boost::math::complement;\nusing boost::math::normal;\nusing boost::math::quantile;\n\n#include \"cycleSlip.hpp\"\n#include \"acsConfig.hpp\"\n#include \"ppp.hpp\"\n\nstatic CSAnalyserSingle\tcsAnalyserL1;\t\t\t///< Cycle slip analysis object for L1. Contains time-series data from multiple epochs\nstatic CSAnalyserSingle\tcsAnalyserL2;\t\t\t///< Cycle slip analysis object for L2. Contains time-series data from multiple epochs\nstatic CSAnalyserCombo\tcsAnalyserLc(calcLc);\t///< Cycle slip analysis object for Lc. Contains time-series data from multiple epochs\nstatic int sEpochNum = 1; \t\t\t\t\t\t///< Epoch number, starting from 1. Used in cycle slip analysis.\ntypedef std::chrono::steady_clock Clock; \t\t///< For measuring program runtime durations\n\n\n/** \\file\n* This software performs cycle slip detection and repair, given prefit residual data.\n*\n* The basic workflow for performing this analysis is:\n* create CSAnalyser objects\n* in epoch 1, initialise internal param's + call init()\n* every epoch, call cycleSlipDetectRepair()\n*/\n\n\n// External functions\n\n\n/** All-in-one function for cycle slip detection + repair\n*/\nbool\tcycleSlipDetectRepair(\n\tCSAnalyserSingle&\t\tcsAnalyserL1,\t///< Object containing cycle-slip-related data for L1 frequency\n\tCSAnalyserSingle&\t\tcsAnalyserL2,\t///< Object containing cycle-slip-related data for L2 frequency\n\tCSAnalyserCombo&\t\tcsAnalyserLc,\t///< Object containing cycle-slip-related data for Lc frequency\n\tconst KFMeasEntryList&\tkfPrefitL1,\t\t///< L1 prefit residuals\n\tconst KFMeasEntryList&\tkfPrefitL2,\t\t///< L2 prefit residuals\n\tconst KFMeasEntryList&\tkfPrefitLc,\t\t///< Lc prefit residuals\n\tint\t\t\t\t\t\tepochNum,\t\t///< Epoch number\n\tKFState&\t\t\t\tkfState,\t\t///< Kalman filter object containing the network state parameters\n\tKFMeasEntryList&\t\tkfMeasEntryList,///< List of input measurements as lists of entries\n\tmap<KFKey, bool>&\t\tmeasuredStates)\t///< Map of measured states in this epoch\n{\n\n\t// Clean prefit data\n\tObsValMap prefitL1 = kfMeasEntryListToObsValMap(kfPrefitL1);\t// Convert KFMeasEntryList to ObsValMap\n\tObsValMap prefitL2 = kfMeasEntryListToObsValMap(kfPrefitL2);\n\tObsValMap prefitLc = kfMeasEntryListToObsValMap(kfPrefitLc);\n\tcsAnalyserL1.adjustAmb(prefitL1, kfState, epochNum);\n\tcsAnalyserL2.adjustAmb(prefitL2, kfState, epochNum);\n\tcsAnalyserL1.cleanData(prefitL1, epochNum);\n\tcsAnalyserL2.cleanData(prefitL2, epochNum);\n\n\t// Detect outliers in L1/L2 that are large enough to be potential cycle slips\n\tcsAnalyserL1.detectOutliers(epochNum);\n\tcsAnalyserL2.detectOutliers(epochNum);\n\n\t// Classify previously marked outliers as either outliers or cycle slips, then estimate + validate int solution\n\tcsAnalyserL1.classifySlips(epochNum);\n\tcsAnalyserL2.classifySlips(epochNum);\n\n\t// Verify L1/L2 int solutions with Lc\n\tcsAnalyserLc.cleanData(prefitLc, epochNum);\n\tObsBoolMap lcValidated = csAnalyserLc.validateSingleSols(csAnalyserL1.slipIntSols, csAnalyserL2.slipIntSols);\n\tcsAnalyserL1.applyExternalSlipValidation(lcValidated);\n\tcsAnalyserL2.applyExternalSlipValidation(lcValidated);\n\n\t// Combine L1/L2 outlier/slip analysis into Lc and apply to KF\n\tcsAnalyserLc.combineSingleSols(csAnalyserL1.slipIntSols, csAnalyserL2.slipIntSols, csAnalyserL1.ambToReinit, csAnalyserL2.ambToReinit, csAnalyserL1.deweightLog, csAnalyserL2.deweightLog);\n\tbool stateModified = csAnalyserLc.applyAdjustmentsToKF(kfState, kfMeasEntryList, measuredStates);\n\n\t// Repair timeseries's within each analyser object for future analysis\n\tcsAnalyserL1.repairInternalTS(); // Adjust internal time-series to account for repaired CS's / reinitialised ambiguities\n\tcsAnalyserL2.repairInternalTS();\n\tcsAnalyserLc.repairInternalTS();\n\n\t// Decrement outlier deweight durations + clear ambiguity repair/reinit queue\n\tcsAnalyserL1.incrementTime();\n\tcsAnalyserL2.incrementTime();\n\tcsAnalyserLc.incrementTime();\n\n\treturn stateModified; // If true, KFState.stateTransition() needs to be rerun to apply changes made to state vector\n}\n\n\n/** Prints a KFMeasList to file\n*/\nvoid\tprintToFile(\n\tconst KFMeasEntryList& kfMeasEntryList,\t\t///< KFMeasEntryList to print\n\tstring\t\t\t\t\tfilename,\t\t\t///< File to print to\n\tint\t\t\t\t\t\tepochNum)\t\t\t///< Epoch number\n{\n\tstd::ofstream out;\n\tout.open(filename, std::ios::app);\n\tfor (auto& meas : kfMeasEntryList)\n\t{\n\t\tout << epochNum << \" \" << meas.obsKey << \" \" << meas.value << \" \" << meas.noise << \" \" << meas.innov << std::endl;\n\t}\n\tout.close();\n}\n\n\n\n// CSAnalyserBase functions\n\n/** Resets debug files\n*/\nvoid\tCSAnalyserBase::resetDebug()\n{\n\tstd::ofstream out;\n\tout.open(freqName + \"-prefit.dbg\", std::ios::out);\t\t\tout << \"Start\" << std::endl;\tout.close();\n\tout.open(freqName + \"-dPrefit.dbg\", std::ios::out);\t\t\tout << \"Start\" << std::endl;\tout.close();\n\tout.open(freqName + \"-dPrefitIqm.dbg\", std::ios::out);\t\tout << \"Start\" << std::endl;\tout.close();\n\tout.open(freqName + \"-dPrefitLessCom.dbg\", std::ios::out);\tout << \"Start\" << std::endl;\tout.close();\n\tout.open(freqName + \"-dPrefitClean.dbg\", std::ios::out);\tout << \"Start\" << std::endl;\tout.close();\n\tout.open(freqName + \"-prefitClean.dbg\", std::ios::out);\t\tout << \"Start\" << std::endl;\tout.close();\n\tout.open(freqName + \"-csTSData.dbg\", std::ios::out);\t\tout << \"Start\" << std::endl;\tout.close();\n}\n\n\n/** Clean prefit resid data\n*/\nvoid\tCSAnalyserBase::cleanData(\n\tconst ObsValMap&\t\tprefit,\t\t///< [in]\tPrefit residuals for each channel\n\tint\t\t\t\t\t\tepochNum)\t///< [in]\tEpoch number, starting from 1\n{\n\tinitClearTimeseries(prefit, prefitTSMap);\t// Prep timeseries for the current epoch - create new timeseries if missing, and clear obsolete\n\tObsValMap dPrefit;\n\tfor (auto& [obsKey, val] : prefit)\n\t{\n\t\t// Add current prefit value to timeseries\n\t\tassert(prefitTSMap.find(obsKey) != prefitTSMap.end()); // Note - entry should be added by initClearTimeseries()\n\t\tprefitTSMap.at(obsKey).push_back(val);\n\n\t\t// Time-difference last 2 time-series values (for each channel)\n\t\tint numPts = prefitTSMap.at(obsKey).size();\n\t\tif (numPts >= 2 + newChannelBreakInDuration)\n\t\t{\n\t\t\tdPrefit[obsKey] = prefitTSMap.at(obsKey).at(numPts - 1) - prefitTSMap.at(obsKey).at(numPts - 2); // diff between last & 2nd-last timeseries value\n\t\t}\n\t}\n\n\t// Calculate common mode\n\tObsValMap dPrefitCom = calcStationCommonModes(dPrefit, commonModeMethod);\n\tinitClearTimeseries(dPrefit, dPrefitLessComTSMap);\n\tinitClearTimeseries(dPrefit, prefitCleanTSMap);\n\n\t// Debugging objects\n\tObsValMap dPrefitLessComMap;\n\tObsValMap dPrefitCleanMap;\n\tObsValMap prefitCleanMap;\n\n\tfor (auto& [obsKey, val] : dPrefit)\n\t{\n\t\t// Subtract common mode + append result to timeseries\n\t\tObsKey recOnlyObsKey = obsKey;\n\t\trecOnlyObsKey.Sat = {};\n\t\tassert(dPrefitCom.find(recOnlyObsKey) != dPrefitCom.end());\n\t\tdouble dPrefitLessCom = val - dPrefitCom.at(recOnlyObsKey);\n\t\tdPrefitLessComMap[obsKey] = dPrefitLessCom;\n\t\tassert(dPrefitLessComTSMap.find(obsKey) != dPrefitLessComTSMap.end());\n\t\tdPrefitLessComTSMap.at(obsKey).push_back(dPrefitLessCom);\n\n\n\t\t// Check that there are sufficient data points to calculate moving average & continue data cleaning\n\t\tif (dPrefitLessComTSMap.at(obsKey).size() >= dMovingAveWin + slipClassifyPostOutlierPts)\n\t\t{\n\n\t\t\t// Calculate moving average\n\t\t\tvector<double> movingAveSample = subVecExclLastN(subVecLastN(dPrefitLessComTSMap.at(obsKey), dMovingAveWin + slipClassifyPostOutlierPts), slipClassifyPostOutlierPts);\n\t\t\tdouble ave = calcMean(movingAveSample);\n\n\n\t\t\t// Subtract moving average + append result to timeseries\n\t\t\tdouble dPrefitClean = dPrefitLessCom - ave;\n\t\t\tdPrefitCleanMap[obsKey] = dPrefitClean; // (for debugging)\n\n\t\t\t// Integrate + append result to timeseries\n\t\t\tassert(prefitCleanTSMap.find(obsKey) != prefitCleanTSMap.end());\n\t\t\tif (prefitCleanTSMap.at(obsKey).size() == 0)\n\t\t\t{\n\t\t\t\tprefitCleanTSMap.at(obsKey).push_back(0);\n\t\t\t}\n\t\t\tdouble prefitClean = prefitCleanTSMap.at(obsKey).back() + dPrefitClean;\n\t\t\tprefitCleanMap[obsKey] = prefitClean;\n\t\t\tprefitCleanTSMap.at(obsKey).push_back(prefitClean);\n\t\t}\n\t}\n\n\n\t// Debugging\n\tif (debug)\n\t{\n\t\tprintToFile(prefit, freqName + \"-prefit.dbg\", epochNum);\n\t\tprintToFile(dPrefit, freqName + \"-dPrefit.dbg\", epochNum);\n\t\tprintToFile(dPrefitCom, freqName + \"-dPrefitCom.dbg\", epochNum);\n\t\tprintToFile(dPrefitLessComMap, freqName + \"-dPrefitLessCom.dbg\", epochNum);\n\t\tprintToFile(dPrefitCleanMap, freqName + \"-dPrefitClean.dbg\", epochNum);\n\t\tprintToFile(prefitCleanMap, freqName + \"-prefitClean.dbg\", epochNum);\n\t}\n}\n\n\n/** Repair internal timeseries' data to account for slip repair + ambiguity reinitialisation\n*/\nvoid\tCSAnalyserBase::repairInternalTS()\n{\n\tlist<ObsKey> slipObsKeys = getSlipSolObsKeys();\n\n\t// Apply cycle slip solution to ambiguity via state transition matrix\n\tfor (auto& obsKey : slipObsKeys)\n\t{\n\t\tdouble ambCorrection = getAmbCorrection(obsKey);\n\n\t\t// prefitTSMap - correct data from outlier to present\n\t\tint tsSize = prefitTSMap.at(obsKey).size();\n\t\tassert(slipClassifyPostOutlierPts <= tsSize);\n\t\tfor (int i = tsSize - slipClassifyPostOutlierPts; i < tsSize; ++i)\n\t\t{\n\t\t\tprefitTSMap.at(obsKey).at(i) -= ambCorrection;\n\t\t}\n\n\t\t// dPrefitLessComTSMap - correct data point at outlier\n\t\ttsSize = dPrefitLessComTSMap.at(obsKey).size();\n\t\tassert(slipClassifyPostOutlierPts <= tsSize);\n\t\tdPrefitLessComTSMap.at(obsKey).at(tsSize - slipClassifyPostOutlierPts) -= ambCorrection;\n\n\t\t// prefitCleanTSMap - correct data from outlier to present\n\t\ttsSize = prefitCleanTSMap.at(obsKey).size();\n\t\tassert(slipClassifyPostOutlierPts <= tsSize);\n\t\tfor (int i = tsSize - slipClassifyPostOutlierPts; i < tsSize; ++i)\n\t\t{\n\t\t\tprefitCleanTSMap.at(obsKey).at(i) -= ambCorrection;\n\t\t}\n\t}\n\n\n\t// Clear timeseries if ambiguity is to be reinitialised\n\tfor (auto& obsKey : ambToReinit)\n\t{\n\t\tassert(prefitTSMap.find(obsKey) != prefitTSMap.end());\n\t\tprefitTSMap.at(obsKey).clear();\n\t\tassert(dPrefitLessComTSMap.find(obsKey) != dPrefitLessComTSMap.end());\n\t\tdPrefitLessComTSMap.at(obsKey).clear();\n\t\tassert(prefitCleanTSMap.find(obsKey) != prefitCleanTSMap.end());\n\t\tprefitCleanTSMap.at(obsKey).clear();\n\t}\n}\n\n\n\n// CSAnalyserSingle functions\n\n/** Set internal config values\n*/\nvoid\tCSAnalyserSingle::init()\n{\n\tassert(isInit == false);\n\tisInit = true;\n\tif (freq == 0)\n\t{\n\t\tstd::cout << \"Error - CSAnalyserSingle.freq = 0. Set to non-zero value before calling init()!\" << std::endl;\n\t\tassert(freq != 0);\n\t}\n\twavelength = 1 / freq * CLIGHT;\n\n\t// Reset debug files\n\tif (debug)\tresetDebug();\n};\n\n\n/** Adjust incoming prefit data by subtracting the accumulated deteted slips on this channel, and adding back the Lc ambiguity (previously subtracted in the prefit calculation)\n*/\nvoid\tCSAnalyserSingle::adjustAmb(\n\tObsValMap&\t\t\t\tprefit,\n\tKFState&\t\t\t\tkfState,\n\tint\t\t\t\t\t\tepochNum)\n{\n\tinitZeroObsIntMap(prefit, accumSlips);\n\tfor (auto& [obsKey, val] : prefit)\n\t{\n\t\t// Subtract previously detected slips on this frequency\n\t\tassert(accumSlips.find(obsKey) != accumSlips.end());\n\t\tval -= accumSlips.at(obsKey) * wavelength;\n\n\t\t// Add back Lc amb\n\t\tKFKey ambiguityKey = { KF::AMBIGUITY, obsKey.Sat,\tobsKey.str, 0, nullptr };\n\t\tdouble ambVal = 0;\n\t\tkfState.getKFValue(ambiguityKey, ambVal);\n\t\tval += ambVal;\n\t}\n}\n\n\n/** Detect outliers in cleaned prefit data\n*/\nvoid\tCSAnalyserSingle::detectOutliers(\n\tint \t\t\t\t\tepochNum)\t///< [in]\tEpoch number, starting from 1\n{\n\t// Perform outlier analysis on cleaned data.\n\tfor (auto& [obsKey, prefitCleanTS] : prefitCleanTSMap)\n\t{\n\t\t// Check that there are sufficient data points to perform outlier analysis\n\t\tif (prefitCleanTS.size() >= outlierDetectMinPts)\n\t\t{\n\t\t\tvector<double> tsData = subVecLastN(prefitCleanTS, outlierDetectMinPts);\n\n\t\t\t// Detect if current data point is an outlier\n\t\t\tvector<double> baseline = subVecExclLastN(tsData, 1);\n\t\t\tdouble curr = tsData.back();\n\t\t\tbool outlierDetected = calcIfOutlier(curr, baseline, outlierPAlpha);\n\n\t\t\tif (outlierDetected)\n\t\t\t{\n\t\t\t\tdouble mean = calcMean(baseline);\n\t\t\t\tdouble stdDev = calcStdDev(baseline);\n\t\t\t\tbool isOutlierLargeEnough = rightTailedTest(wavelength, fabs(curr - mean), stdDev, minSizePAlpha); // If false, an outlier has been detected but it is v. unlikely that it is >= the minimum cycle slip size - ignore these.\n\t\t\t\tif (isOutlierLargeEnough)\n\t\t\t\t{\n\t\t\t\t\t// Mark as outlier to deweight\n\t\t\t\t\tint outlierDeweightDuration = slipClassifyPostOutlierPts - 1;\n\t\t\t\t\tdeweightLog[obsKey] = outlierDeweightDuration;\n\n\t\t\t\t\tif (printActivity)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"Outlier detected -\";\n\t\t\t\t\t\tcout << \" Rec: \" << obsKey.str;\n\t\t\t\t\t\tcout << \" Sat: \" << (string)obsKey.Sat;\n\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n/** Classify previously detected potential slips as either slips or outliers\n*/\nvoid\tCSAnalyserSingle::classifySlips(\n\tint \t\t\t\t\tepochNum)\t///< [in]\tEpoch number, starting from 1\n{\n\n\t// Perform CS analysis on previously marked outliers.\n\tfor (auto& [obsKey, prefitCleanTS] : prefitCleanTSMap)\n\t{\n\t\t// If this channel has just reached the end of its outlier deweighting period, check it for a potential cycle slip\n\t\t// Also check that there are sufficient data points to perform cycle-slip classification\n\t\tauto index = deweightLog.find(obsKey);\n\t\tif (index != deweightLog.end() && index->second == 0 && prefitCleanTS.size() >= slipClassifyMinPts)\n\t\t{\n\t\t\tbool slipFound = false;\n\t\t\tvector<double> tsData = subVecLastN(prefitCleanTS, slipClassifyMinPts);\n\n\t\t\t// Check if pre-split and post-split means are statistically different using Student's t-test\n\t\t\t// Split the dataset into 2 vectors, one excluding the last outlierPtsFromEnd pts, the second including the last outlierPtsFromEnd pts\n\t\t\tint outlierPtsFromEnd = slipClassifyPostOutlierPts;\n\t\t\tint eventEpoch = epochNum - outlierPtsFromEnd + 1;\n\t\t\tvector<double> samplePre = subVecExclLastN(tsData, outlierPtsFromEnd);\n\t\t\tvector<double> samplePost = subVecLastN(tsData, outlierPtsFromEnd);\n\n\t\t\t// Perform Student's t-test on vectors - is there a statistically significant difference in their means?\n\t\t\tbool stepFound = performStudentsTTest(samplePre, samplePost, tAlpha);\n\t\t\tbool isStepLargeEnough = false;\n\t\t\tif (stepFound)\n\t\t\t{\n\t\t\t\tdouble stepEst = calcMean(samplePost) - calcMean(samplePre);\n\t\t\t\tdouble stepEstStdDev = sqrt(pow(calcStdDev(samplePre), 2) / samplePre.size() + pow(calcStdDev(samplePost), 2) / samplePost.size()); //Ref: http://onlinestatbook.com/2/sampling_distributions/samplingdist_diff_means.html\n\n\t\t\t\t// Verify stepEst is large enough to be a cycle slip (e.g. >= 19cm for L1)\n\t\t\t\tisStepLargeEnough = rightTailedTest(wavelength, fabs(stepEst), stepEstStdDev, minSizePAlpha); // If false, a step has been detected but it is v. unlikely that it is >= the minimum cycle slip size - ignore these.\n\t\t\t\tif (isStepLargeEnough)\n\t\t\t\t{\n\t\t\t\t\t// Calculate and validate integer cycle slip solution\n\t\t\t\t\tdouble factor = stepEst / wavelength;\n\t\t\t\t\tdouble factorStdDev = stepEstStdDev / wavelength;\n\t\t\t\t\tint intSol = round(factor);\n\t\t\t\t\tbool isRoundingValid = validateIntSolution(factor, factorStdDev, intSol);\n\t\t\t\t\tslipFound = true;\n\t\t\t\t\tif (isRoundingValid)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Mark as cycle slip to repair\n\t\t\t\t\t\tslipIntSols[obsKey] = intSol;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// Large step change detected but unable to find valid int solution - reinitialise ambiguity\n\t\t\t\t\t\tambToReinit.push_back(obsKey);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (printActivity)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"Previous event classified as cycle slip -\";\n\t\t\t\t\t\tcout << \" Rec: \" << obsKey.str;\n\t\t\t\t\t\tcout << \" Sat: \" << (string)obsKey.Sat;\n\t\t\t\t\t\tcout << \" Slip epoch: \" << eventEpoch;\n\t\t\t\t\t\tcout << \" Factor: \" << factor;\n\t\t\t\t\t\tcout << \" Int soln: \" << intSol;\n\t\t\t\t\t\tcout << \" Rounding valid: \" << isRoundingValid;\n\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//if (printActivity && !slipFound)\n\t\t\t//{\n\t\t\t//\tcout << \"Previous event classified as outlier -\";\n\t\t\t//\tcout << \" Rec: \" << obsKey.str;\n\t\t\t//\tcout << \" Sat: \" << (string)obsKey.Sat;\n\t\t\t//\tcout << \" Outlier epoch: \" << eventEpoch;\n\t\t\t//\tcout << \" Step found: \" << stepFound;\n\t\t\t//\tcout << \" Step large enough: \" << isStepLargeEnough;\n\t\t\t//\tcout << endl;\n\t\t\t//}\n\t\t}\n\t}\n}\n\n\n/** Applies external integer solution validation to solutions. Paired with validateSingleSols()\n*/\nvoid\tCSAnalyserSingle::applyExternalSlipValidation(\n\tconst ObsBoolMap&\t\tvalidMap)\t///< External integer solution validation, produced by validateSingleSols()\n{\n\tfor (auto& [obsKey, isValid] : validMap)\n\t{\n\t\tif (!isValid)\n\t\t{\n\t\t\tslipIntSols.erase(obsKey); // Side-note: map.erase(key) does nothing if map.at(key) does not exist\n\t\t\tambToReinit.push_back(obsKey); // Invalid CS solutions get ambiguities reinitialised instead of being repaired\n\t\t}\n\t}\n}\n\n\n/** Gets list of keys from slipIntSols map\n*/\nlist<ObsKey>\tCSAnalyserSingle::getSlipSolObsKeys()\n{\n\tlist<ObsKey> slipObsKeys;\n\tfor (auto& [obsKey, val] : slipIntSols)\tslipObsKeys.push_back(obsKey);\n\treturn slipObsKeys;\n}\n\n\n/** Calculates ambiguity correction from slipIntSols map\n*/\ndouble\tCSAnalyserSingle::getAmbCorrection(\n\tconst ObsKey&\t\t\tobsKey)\n{\n\treturn -slipIntSols[obsKey] * wavelength;\n}\n\n\n/** Update deweightings + clear logs to be ready for the next epoch\n*/\nvoid\tCSAnalyserSingle::incrementTime()\n{\n\t// Decrement deweight duration of all entries in deweightLog, remove entries with zero duration remaining\n\tfor (auto it = deweightLog.begin(); it != deweightLog.end(); )\n\t{\n\t\tauto obsKey = it->first;\n\t\tauto& duration = it->second;\n\n\t\tif (duration <= 0)\n\t\t{\n\t\t\tit = deweightLog.erase(it);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t--duration;\n\t\t\t++it;\n\t\t}\n\t}\n\n\tfor (auto& [obsKey, slipInt] : slipIntSols)\n\t{\n\t\tassert(accumSlips.find(obsKey) != accumSlips.end());\n\t\taccumSlips.at(obsKey) += slipInt;\n\t}\n\tslipIntSols.clear();\n\tambToReinit.clear();\n}\n\n\n\n// CSAnalyserCombo functions\n\n/** Set internal config values\n*/\nvoid\tCSAnalyserCombo::init()\n{\n\tassert(isInit == false);\n\tisInit = true;\n\tif (freq1 == 0)\n\t{\n\t\tstd::cout << \"Error - CSAnalyserCombo.freq1 == 0. Set to a non-zero value before calling init()!\" << std::endl;\n\t\tassert(freq1 != 0);\n\t}\n\tif (freq2 == 0)\n\t{\n\t\tstd::cout << \"Error - CSAnalyserCombo.freq2 == 0. Set to a non-zero value before calling init()!\" << std::endl;\n\t\tassert(freq2 != 0);\n\t}\n\twavelength1 = 1 / freq1 * CLIGHT;\n\twavelength2 = 1 / freq2 * CLIGHT;\n\n\t// Reset debug files\n\tif (debug)\tresetDebug();\n};\n\n\n/** Validate single frequency (e.g. L1 & L2) integer solutions by comparing against the combination (e.g. Lc) to see if a corresponding jump can be found\n*/\nObsBoolMap\tCSAnalyserCombo::validateSingleSols(\n\tObsIntMap&\t\t\t\tslipIntSols1In,\n\tObsIntMap&\t\t\t\tslipIntSols2In)\n{\n\t// Get list of candidate solution ObsKeys\n\tlist<ObsKey> solObsKeys = getUniqueKeys(slipIntSols1In, slipIntSols2In);\n\n\t// Get expected Lc jumps for each solution\n\tObsValMap expectedLcJumps;\n\tfor (auto& obsKey : solObsKeys)\n\t{\n\t\texpectedLcJumps[obsKey] = getComboVal(slipIntSols1In[obsKey] * wavelength1, freq1, slipIntSols2In[obsKey] * wavelength2, freq2); // Side-note: map[key] creates an entry with value = 0 if entry does not exist\n\t}\n\n\t// Validate L1/L2 candidate solutions against Lc - if\n\tObsBoolMap lcValidated;\n\tfor (auto& [obsKey, expectedLcJump] : expectedLcJumps)\n\t{\n\t\t// Calc jump in Lc\n\t\tvector<double> tsData = subVecLastN(prefitCleanTSMap.at(obsKey), slipClassifyMinPts);\n\n\t\t// Split the dataset into 2 vectors, one excluding the last slipClassifyPostOutlierPts pts, the second including the last slipClassifyPostOutlierPts pts\n\t\tvector<double> samplePre = subVecExclLastN(tsData, slipClassifyPostOutlierPts);\n\t\tvector<double> samplePost = subVecLastN(tsData, slipClassifyPostOutlierPts);\n\t\tdouble actualLcJump = calcMean(samplePost) - calcMean(samplePre);\n\t\tdouble stdDev = sqrt(pow(calcStdDev(samplePre), 2) / samplePre.size() + pow(calcStdDev(samplePost), 2) / samplePost.size()); //Ref: http://onlinestatbook.com/2/sampling_distributions/samplingdist_diff_means.html\n\n\n\t\t// Compare this jump to expected jump\n\t\tbool isOutlier = twoSidedHypothesisTest(expectedLcJump, actualLcJump, stdDev, intValidComboJumpAlpha);\n\t\tlcValidated[obsKey] = !isOutlier; // If not an outlier, Lc validates L1/L2 int solutions\n\n\t\tif (printActivity)\n\t\t{\n\t\t\tcout << \"Lc validation results -\";\n\t\t\tcout << \" Rec: \" << obsKey.str;\n\t\t\tcout << \" Sat: \" << (string)obsKey.Sat;\n\t\t\tcout << \" Lc validated: \" << lcValidated.at(obsKey);\n\t\t\tcout << endl;\n\t\t}\n\t}\n\n\treturn lcValidated;\n}\n\n\n/** Combine single freq (e.g. L1/L2) integer solutions, ambiguities to reinitialise & channels to deweight into the combination (e.g. Lc) equivalents\n*/\nvoid\tCSAnalyserCombo::combineSingleSols(\n\tconst ObsIntMap&\t\tslipIntSols1In,\n\tconst ObsIntMap&\t\tslipIntSols2In,\n\tconst list<ObsKey>&\t\tambToReinit1,\n\tconst list<ObsKey>&\t\tambToReinit2,\n\tObsIntMap\t\t\t\tdeweightLog1,\n\tObsIntMap\t\t\t\tdeweightLog2)\n{\n\tslipIntSols1 = slipIntSols1In;\n\tslipIntSols2 = slipIntSols2In;\n\tambToReinit = ambToReinit1;\n\tambToReinit.insert(ambToReinit.end(), ambToReinit2.begin(), ambToReinit2.end());\n\tambToReinit.sort();\n\tambToReinit.unique();\n\tlist<ObsKey> deweightLogObsKeys = getUniqueKeys(deweightLog1, deweightLog2);\n\tfor (auto& obsKey : deweightLogObsKeys)\n\t{\n\t\tdeweightLog[obsKey] = std::max(deweightLog1[obsKey], deweightLog2[obsKey]); //Side-note: map[key] defaults to 0 if entry doesn't exist\n\t}\n}\n\n\n/** Gets list of keys from slipIntSols1 & slipIntSols2 maps\n*/\nlist<ObsKey>\tCSAnalyserCombo::getSlipSolObsKeys()\n{\n\treturn getUniqueKeys(slipIntSols1, slipIntSols2);\n}\n\n\n/** Calculates ambiguity correction from slipIntSols1 & slipIntSols2 maps\n*/\ndouble\tCSAnalyserCombo::getAmbCorrection(\n\tconst ObsKey&\t\t\tobsKey)\n{\n\treturn -getComboVal(slipIntSols1[obsKey] * wavelength1, freq1, slipIntSols2[obsKey] * wavelength2, freq2); // Side-note: map[key] creates an entry with value = 0 if entry does not exist\n}\n\n\n/** Apply ambiguity adjustment / reinitialisation & channel deweighting to the Kalman filter & measurement weightings\n* Returns true if state vector is adjusted - if so, KFState.stateTransition() needs to be rerun to apply changes made to state vector\n*/\nbool\tCSAnalyserCombo::applyAdjustmentsToKF(\n\tKFState&\t\t\t\tkfState,\t\t\t///< [in/out]\tKalman filter object containing the network state parameters\n\tKFMeasEntryList&\t\tkfMeasEntryList,\t///< [in/out]\tList of input measurements as lists of entries\n\tmap<KFKey, bool>&\t\tmeasuredStates)\t\t///< [in/out]\tMap of measured states in this epoch to compare against. Used to reinitialise ambiguities using removeUnmeasuredAmbiguities() (called separately after calling this function).\n{\n\tbool stateModified = false;\n\tfor (auto it = kfMeasEntryList.begin(); it != kfMeasEntryList.end();  )\n\t{\n\t\tKFMeasEntry& kfMeasEntry = (*it);\n\t\tbool toDelete = false;\n\n\t\t// Deweight outliers\n\t\tauto index = deweightLog.find(kfMeasEntry.obsKey);\n\t\tif (index != deweightLog.end())\n\t\t{\n\t\t\tint epochsRemainingToDeweight = index->second;\n\t\t\tif (epochsRemainingToDeweight > 0)\n\t\t\t{\n\t\t\t\tkfMeasEntry.noise = deweightNoise;\n\t\t\t}\n\t\t}\n\n\t\t\n\t\t// Reinitialise ambiguities (remove amb this epoch, add amb back in next epoch)\n\t\tif (std::find(ambToReinit.begin(), ambToReinit.end(), kfMeasEntry.obsKey) != ambToReinit.end())\n\t\t{\n\t\t\tKFKey ambiguityKey = { KF::AMBIGUITY, kfMeasEntry.obsKey.Sat,\tkfMeasEntry.obsKey.str, 0, nullptr };\n\t\t\tassert(measuredStates.find(ambiguityKey) != measuredStates.end());\n\t\t\tmeasuredStates.at(ambiguityKey) = false;\n\t\t\tstateModified = true;\n\n\t\t\t// Remove corresponding phase measurement from kfMeasList\n\t\t\ttoDelete = true;\n\n\t\t\tif (printActivity)\n\t\t\t{\n\t\t\t\tcout << \"Reinitialising ambiguity -\";\n\t\t\t\tcout << \" Rec: \" << kfMeasEntry.obsKey.str;\n\t\t\t\tcout << \" Sat: \" << (string)kfMeasEntry.obsKey.Sat;\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t}\n\n\t\tif (toDelete)\n\t\t{\n\t\t\tit = kfMeasEntryList.erase(it);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++it;\n\t\t}\n\t}\n\tremoveUnmeasuredAmbiguities(cout, kfState, measuredStates);\n\n\t// Apply cycle slip solution to ambiguity via state transition matrix\n\tlist<ObsKey> slipObsKeysToRepair = getSlipSolObsKeys();\n\tfor (auto& obsKey : slipObsKeysToRepair)\n\t{\n\t\tdouble ambCorrection = getAmbCorrection(obsKey);\n\t\tKFKey ambiguityKey = {KF::AMBIGUITY, obsKey.Sat,\tobsKey.str, 0, nullptr};\n\t\tkfState.setKFTrans(ambiguityKey, {KF::ONE}, ambCorrection);\n\t\tstateModified = true;\n\t\tif (printActivity)\n\t\t{\n\t\t\tcout << \"Adjusting ambiguity -\";\n\t\t\tcout << \" Rec: \" << obsKey.str;\n\t\t\tcout << \" Sat: \" << (string)obsKey.Sat;\n\t\t\tcout << \" Adjustment: \" << ambCorrection;\n\t\t\tcout << endl;\n\t\t}\n\t}\n\n\treturn stateModified;\n}\n\n\n/** Prepare internal data for the following epoch\n*/\nvoid\tCSAnalyserCombo::incrementTime()\n{\n\tslipIntSols1.clear();\n\tslipIntSols2.clear();\n\tambToReinit.clear();\n\tdeweightLog.clear(); // seeded by L1/L2 deweightLog every epoch in combineSingleSols()\n}\n\n\n\n// Statistical functions\n\n/** Calculates mean of sample\n*/\ndouble\tcalcMean(\n\tconst vector<double>&\tsample)\t///< Sample to take mean of\n{\n\tif (sample.size() == 0)\n\t{\n\t\tcout << \"Warning in calcMean(): sample.size() == 0!\" << endl;\n\t\treturn 0;\n\t}\n\tdouble accum = 0;\n\tfor (auto val : sample)\n\t{\n\t\taccum += val;\n\t}\n\treturn accum / sample.size();\n}\n\n\n/** Calculates the median for the given vector\n*/\ndouble\tcalcMed(\n\tvector<double>\t\t\tvec)\n{\n\tdouble med = 0;\n\tif (vec.size() == 0)\n\t{\n\t\tstd::cout << \"Warning: calcMed() given vector of size 0!\" << std::endl;\n\t\tmed = 0;\n\t}\n\telse {\n\t\tsort(vec.begin(), vec.end());\n\n\t\tint size = vec.size();\n\t\tif (size % 2 == 0)\n\t\t{\n\t\t\tmed = (vec.at(size / 2) + vec.at(size / 2 - 1)) / 2.0;\n\t\t}\n\t\telse {\n\t\t\tmed = vec.at((size - 1) / 2);\n\t\t}\n\t}\n\treturn med;\n}\n\n\n/** Calculates the interquartile mean for the given vector\n*  https://en.wikipedia.org/wiki/Interquartile_mean\n*/\ndouble\tcalcIqm(\n\tvector<double>\t\tvec)\n{\n\tdouble iqm = 0;\n\tif (vec.size() == 0)\n\t{\n\t\tstd::cout << \"Warning: calcIqm() given vector of size 0!\" << std::endl;\n\t\tiqm = 0;\n\t}\n\telse if (vec.size() == 1)\n\t{\n\t\tiqm = vec.front(); // note - method below is not suitable for samples of size 1\n\t}\n\telse {\n\t\tsort(vec.begin(), vec.end());\n\t\tdouble quartileSize = vec.size() / 4.0;\n\t\tint cutSize = floor(quartileSize);\n\t\tdouble edgeWeighting = 1 - (quartileSize - cutSize);  // See https://en.wikipedia.org/wiki/Interquartile_mean#Dataset_size_not_divisible_by_four\n\n\t\tdouble accum = 0;\n\t\tfor (int i = cutSize; i < vec.size() - cutSize; ++i)\n\t\t{\n\t\t\tdouble weight = 1;\n\t\t\tif (i == cutSize || i == vec.size() - cutSize - 1)\n\t\t\t{\n\t\t\t\tweight = edgeWeighting;\n\t\t\t}\n\t\t\taccum += weight * vec.at(i);\n\t\t}\n\t\tiqm = accum / (quartileSize * 2);\n\t}\n\treturn iqm;\n}\n\n\n/** Calculates standard deviation of sample\n*/\ndouble\tcalcStdDev(\n\tconst vector<double>&\tsample)\t///< Sample to take std dev of\n{\n\tdouble mean = calcMean(sample);\n\tif (sample.size() < 2)\n\t{\n\t\tcout << \"Warning in calcStdDev(): vector of size \" << sample.size() << \" received!\" << endl;\n\t\treturn -1;\n\t}\n\tdouble var = 0;\n\tfor (auto val : sample)\n\t{\n\t\tvar += pow(val - mean, 2);\n\t}\n\tvar /= sample.size() - 1;\n\treturn sqrt(var);\n}\n\n\n/** Calculate left-tailed p-value of z using a normal distribution N(mean,stdDev)\n*/\ndouble\tcalcLPVal(\n\tdouble\t\t\t\t\tz,\n\tdouble\t\t\t\t\tmean,\n\tdouble\t\t\t\t\tstdDev)\n{\n\tboost::math::normal dist(mean, stdDev);\n\treturn cdf(dist, z);\n}\n\n\n/** Calculate right-tailed p-value of z using a normal distribution N(mean,stdDev)\n*/\ndouble\tcalcRPVal(\n\tdouble\t\t\t\t\tz,\n\tdouble\t\t\t\t\tmean,\n\tdouble\t\t\t\t\tstdDev)\n{\n\tboost::math::normal dist(mean, stdDev);\n\treturn 1 - cdf(dist, z);\n}\n\n\n/** Determines if it is plausible for z to be greater than the mean, using the right-tailed hypothesis test\n* Returns true if z is likely to be greater than the mean; else false.\n*/\nbool\trightTailedTest(\n\tdouble\t\t\t\t\tz,\n\tdouble\t\t\t\t\tmean,\n\tdouble\t\t\t\t\tstdDev,\n\tdouble\t\t\t\t\talpha)\n{\n\tdouble p = calcRPVal(z, mean, stdDev);\n\tbool isGreaterThanMean = (p >= alpha);\n\treturn isGreaterThanMean;\n}\n\n\n/** Perform two-tailed hypothesis test of z using a normal distribution N(mean,stdDev)\n* H0: z == mean\n* Ha: z is significantly != mean\n* Returns true if there is enough support for Ha, i.e. if z is significantly != mean\n*/\nbool\ttwoSidedHypothesisTest(\n\tdouble\t\t\t\t\tz,\n\tdouble\t\t\t\t\tmean,\n\tdouble\t\t\t\t\tstdDev,\n\tdouble\t\t\t\t\talpha)\n{\n\tdouble p = calcLPVal(z, mean, stdDev);\n\tbool isHaSupported = (p < alpha / 2 || p > 1 - alpha / 2);\n\treturn isHaSupported;\n}\n\n\n/** Determines if current value is an outlier compared to baseline values, using a normal p-value test\n*/\nbool\tcalcIfOutlier(\n\tdouble\t\t\t\t\tcurr,\n\tconst vector<double>&\tbaseline,\n\tdouble\t\t\t\t\talpha)\n{\n\tdouble mean = calcMean(baseline);\n\tdouble stdDev = calcStdDev(baseline);\n\tbool isOutlier = twoSidedHypothesisTest(curr, mean, stdDev, alpha);\n\treturn isOutlier;\n}\n\n\n/**\n* Perform Student's t-test (equal variances).\n* H0 - the two samples have the same mean, any difference is due to chance.\n* Ha - the two samples have different means.\n* Returns true if Ha is supported (i.e. means are different); false if H0 is not rejected (i.e. means are equal)\n* Ref: http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm\n*/\nbool\tperformStudentsTTest(\n\tconst vector<double>&\tsample1,\t///< Sample 1\n\tconst vector<double>&\tsample2,\t///< Sample 2\n\tdouble\t\t\t\t\talpha)\t\t\t///< Alpha to use in Student's t-test\n{\n\tdouble mean1 = calcMean(sample1);\n\tdouble mean2 = calcMean(sample2);\n\tdouble std1 = calcStdDev(sample1);\n\tdouble std2 = calcStdDev(sample2);\n\tint n1 = sample1.size();\n\tint n2 = sample2.size();\n\tdouble df = n1 + n2 - 2; // Degrees of freedom\n\tdouble stdPooled = sqrt(((n1 - 1) * std1 * std1 + (n2 - 1) * std2 * std2) / df); // Pooled std dev\n\tdouble tStat = (mean1 - mean2) / (stdPooled * sqrt(1.0 / n1 + 1.0 / n2)); // t-statistic\n\tstudents_t dist(df);\n\tdouble q = cdf(complement(dist, fabs(tStat)));\n\tbool notEqual = (q < alpha / 2); // true if support is found for Ha\n\treturn notEqual;\n}\n\n\n/** Given some measurement of unknown value with given mean and stdDev, calculate how likely the true value == candidate, vs. all other alternative values\n*/\ndouble\tcalcCandidateSuccessVsAlternatives(\n\tdouble\t\t\t\t\tmean,\n\tdouble\t\t\t\t\tstdDev,\n\tdouble\t\t\t\t\tcandidate,\n\tconst vector<double>& alternatives)\n{\n\tnormal s(mean, stdDev);\n\tdouble candidatePd = pdf(s, candidate);\n\tdouble nonCandidatePdSum = 0;\n\tfor (auto val : alternatives)\n\t{\n\t\tnonCandidatePdSum += pdf(s, val);\n\t}\n\treturn candidatePd / (candidatePd + nonCandidatePdSum);\n}\n\n\n/** Validate int solution by considering the factor (unrounded solution) and its stdDev\n*/\nbool\tCSAnalyserSingle::validateIntSolution(\n\tdouble\t\t\t\t\tfactor,\n\tdouble\t\t\t\t\tstdDev,\n\tint\t\t\t\t\t\tintEst)\n{\n\t// Put together list of alternative integer solutions (i.e. all integers != intEst, within a reasonable range)\n\tint halfTestRange = ceil(stdDev * 5); //pdf 5x sigmas away from mean = 1.5E-06 - further out than this is unnecessary\n\tint testMin = intEst - halfTestRange;\n\tint testMax = intEst + halfTestRange;\n\tvector<double> alternatives;\n\tfor (int i = testMin; i < testMax; ++i)\n\t{\n\t\tif (i != intEst)\n\t\t{\n\t\t\talternatives.push_back(i);\n\t\t}\n\t}\n\n\t// Determine if candidate integer is significantly more likely to be the correct integer solution than all other integers\n\tdouble successPc = calcCandidateSuccessVsAlternatives(factor, stdDev, intEst, alternatives);\n\tbool isOutlier = twoSidedHypothesisTest(intEst, factor, stdDev, intValidOutlierAlpha);\n\t//if (printActivity)\n\t//{\n\t//\tcout << \"Rounding verification -\";\n\t//\tcout << \" factor: \" << factor;\n\t//\tcout << \" stdDev: \" << stdDev;\n\t//\tcout << \" successPc: \" << successPc;\n\t//\tcout << \" (successPc > intValidPdfThresh): \" << (successPc > intValidPdfThresh);\n\t//\tcout << \" !isOutlier: \" << !isOutlier;\n\t//\tcout << endl;\n\t//}\n\tbool isRoundingValid = (successPc > intValidPdfThresh) && !isOutlier;\t\n\treturn isRoundingValid;\n}\n\n\n\n// GNSS-related functions\n\n/** Calculate the ionosphere-free combination Lc.\n* Ref: https://gssc.esa.int/navipedia/index.php/Combination_of_GNSS_Measurements\n*/\ndouble\tcalcLc(\n\tdouble\t\t\t\t\tval1,\t///< L1 range value (m)\n\tdouble\t\t\t\t\tfreq1,\t///< L1 freq (Hz)\n\tdouble\t\t\t\t\tval2,\t///< L2 range value (m)\n\tdouble\t\t\t\t\tfreq2)\t///< L2 freq (Hz)\n{\n\tdouble freqSqL1 = pow(freq1, 2);\n\tdouble freqSqL2 = pow(freq2, 2);\n\treturn (freqSqL1 * val1 - freqSqL2 * val2) / (freqSqL1 - freqSqL2);\n}\n\n\n/** Derivative of ObsKey::operator ==(), except it compares satellite strings to compare satellites.\n* Used in insertArtificialSlip() for debugging only.\n*/\nbool\tobsKeysAreEqual (const ObsKey& obsKey1, const ObsKey& obsKey2)\n{\n\tif (obsKey1.str.compare(obsKey2.str)\t!= 0)\t\t\t\t\treturn false;\n\tif ((string)obsKey1.Sat\t\t\t\t\t!= (string)obsKey2.Sat)\treturn false;\n\tif (obsKey1.type.compare(obsKey2.type)\t!= 0)\t\t\t\t\treturn false;\n\telse\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn true;\n}\n\n\n/** Insert an artificial cycle slip at a given epoch in a given channel\n*/\nvoid\tinsertArtificialSlip(\n\tconst ObsKey&\t\t\tobsKeyToInsertSlip,\n\tdouble\t\t\t\t\tslipSize,\n\tint\t\t\t\t\t\tepochToInsertSlip,\n\tKFMeasEntryList&\t\tkfMeasEntryList,\n\tint\t\t\t\t\t\tcurrEpoch)\n{\n\tif (currEpoch >= epochToInsertSlip)\n\t{\n\t\tbool found = false;\n\t\tfor (auto& meas : kfMeasEntryList)\n\t\t{\n\t\t\tbool obsKeysEqual = obsKeysAreEqual(meas.obsKey, obsKeyToInsertSlip);\n\t\t\tif (obsKeysEqual)\n\t\t\t{\n\t\t\t\tmeas.value += slipSize;\n\t\t\t\tfound = true;\n\t\t\t}\n\t\t}\n\t\tif (!found) cout << \"Warning in insertArtificialSlip(): ObsKey \" << obsKeyToInsertSlip.str << \"-\" << (string)obsKeyToInsertSlip.Sat << \" not found at epoch \" << currEpoch << endl;\n\t}\n}\n\n\n/** Returns the interquartile mean of all channels for each station.\n*/\nObsValMap\tcalcStationCommonModes(\n\tconst ObsValMap&\t\tchVals,\t\t\t\t///< Values for each channel\n\tstring\t\t\t\t\tcommonModeMethod)\t///< Method for calculating common mode\n{\n\t// Gather common-rec values together\n\tObsVecMap recChannels;\n\tfor (auto& [obsKey, val] : chVals)\n\t{\n\t\tObsKey obsKeyRecOnly = obsKey;\n\t\tobsKeyRecOnly.Sat = {};\n\t\tauto ind = recChannels.find(obsKeyRecOnly);\n\t\tif (ind != recChannels.end())\n\t\t{\n\t\t\tind->second.push_back(val);\n\t\t}\n\t\telse {\n\t\t\tvector<double> newEntry;\n\t\t\tnewEntry.push_back(val);\n\t\t\trecChannels[obsKeyRecOnly] = newEntry;\n\t\t}\n\t}\n\n\t// Calc common mode for each station\n\tObsValMap commonModes;\n\tfor (auto& [obsKey, vec] : recChannels)\n\t{\n\t\tassert(vec.size() != 0);\n\t\tif \t\t(commonModeMethod == \"iqm\")\t\tcommonModes[obsKey] = calcIqm(vec);\n\t\telse if\t(commonModeMethod == \"median\")\tcommonModes[obsKey] = calcMed(vec);\n\t\telse if\t(commonModeMethod == \"mean\")\tcommonModes[obsKey] = calcMean(vec);\n\t\telse \t\t\t\t\t\t\t\t\tcout << \"Error: invalid method under cycle_slip_filter_parameters.common_mode_method in YAML file!\" << endl;\n\t}\n\treturn commonModes;\n}\n\n\n\n// Other helper functions\n\n/** Convert a KFMeasEntryList values to an ObsValMap.\n* KFMeasEntryList.noise/innov's are discarded.\n*/\nObsValMap\tkfMeasEntryListToObsValMap(\n\tconst KFMeasEntryList&\tkfMeasEntryList)\n{\n\tObsValMap obsValMap;\n\tfor (auto& entry : kfMeasEntryList)\n\t{\n\t\tobsValMap[entry.obsKey] = entry.value;\n\t}\n\treturn obsValMap;\n}\n\n\n/** Preps a ObsVecMap with empty vectors for later use. Also clears vectors not in use.\n*/\nvoid\tinitClearTimeseries(\n\tconst ObsValMap&\t\tcurrEntries,\t///< Data from the current epoch\n\tObsVecMap&\t\t\t\ttimeseriesMap)\t\t///< Timeseries of previous epochs' data\n{\n\t// Initialise timeseries (if missing) for each entry in the current epoch\n\tfor (const auto& [obsKey, meas] : currEntries)\n\t{\n\t\tif (timeseriesMap.find(obsKey) == timeseriesMap.end())\n\t\t{\n\t\t\tvector<double> newVec;\n\t\t\ttimeseriesMap[obsKey] = newVec;\n\t\t}\n\t}\n\n\t// Clear timeseries that don't have entries in the current epoch\n\tfor (auto& [obsKey, vec] : timeseriesMap)\n\t{\n\t\tif (currEntries.find(obsKey) == currEntries.end())\n\t\t{\n\t\t\tvec.clear(); // note - can delete vector entirely, but easier to just clear vector\n\t\t}\n\t}\n}\n\n\n/** Preps a ObsIntMap with zeros for later use. Also zeroes entries not in use.\n*/\nvoid\tinitZeroObsIntMap(\n\tconst ObsValMap&\t\tcurrEntries,\t///< Data from the current epoch\n\tObsIntMap&\t\t\t\tobsIntMap)\t\t\t///< ObsIntMap to initialise/zero\n{\n\t// Initialise + zero ObsIntMap entries (if missing) for each entry in the current epoch\n\tfor (const auto& [obsKey, meas] : currEntries)\n\t{\n\t\tif (obsIntMap.find(obsKey) == obsIntMap.end())\n\t\t{\n\t\t\tobsIntMap[obsKey] = 0;\n\t\t}\n\t}\n\n\t// Zero ObsIntMap entries that don't have corresponding entries in the current epoch\n\tfor (auto& [obsKey, vec] : obsIntMap)\n\t{\n\t\tif (currEntries.find(obsKey) == currEntries.end())\n\t\t{\n\t\t\tobsIntMap.at(obsKey) = 0;\n\t\t}\n\t}\n}\n\n\n/** Returns subvector made up of the last n points.\n* Returns empty vector if n <= 0.\n* Returns original vector if n >= original vector size.\n*/\nvector<double>\tsubVecLastN(\n\tvector<double>\t\t\tvec,\n\tint\t\t\t\t\t\tn)\n{\n\tif (n < 0)\n\t{\n\t\tcout << \"Warning: n < 0 in subVecLastN()\" << endl;\n\t\treturn vector<double>();\n\t}\n\telse if (n > vec.size())\n\t{\n\t\tcout << \"Warning: n > vec.size() in subVecLastN()\" << endl;\n\t\treturn vec;\n\t}\n\tauto first = vec.begin() + vec.size() - n;\n\tauto last = vec.end();\n\treturn vector<double>(first, last);\n}\n\n\n/** Returns subvector that excludes the last n points\n* Returns original vector if n <= 0.\n* Returns empty vector if n >= original vector size.\n*/\nvector<double>\tsubVecExclLastN(\n\tvector<double>\t\t\tvec,\n\tint\t\t\t\t\t\tn)\n{\n\tif (n < 0)\n\t{\n\t\tcout << \"Warning: n < 0 in subVecExclLastN()\" << endl;\n\t\treturn vec;\n\n\t}\n\telse if (n > vec.size())\n\t{\n\t\tcout << \"Warning: n > vec.size() in subVecExclLastN()\" << endl;\n\t\treturn vector<double>();\n\t}\n\n\tauto first = vec.begin();\n\tauto last = vec.end() - n;\n\treturn vector<double>(first, last);\n}\n\n\n/** Prints an ObsValMap to file\n*/\nvoid\tprintToFile(\n\tconst ObsValMap&\t\tobsValMap,\t///< ObsValMap to print\n\tstring\t\t\t\t\tfilename,\t\t///< File to print to\n\tint\t\t\t\t\t\tepochNum)\t\t\t///< Epoch number\n{\n\tstd::ofstream out;\n\tout.open(filename, std::ios::app);\n\tfor (auto& [obsKey, val] : obsValMap)\n\t{\n\t\tout << epochNum << \" \" << obsKey << \" \" << val << endl;\n\t}\n\tout.close();\n}\n\n\n/** Get unique ObsKey's from two given maps\n*/\nlist<ObsKey>\tgetUniqueKeys(\n\tconst ObsIntMap&\t\tobsIntMap1,\n\tconst ObsIntMap&\t\tobsIntMap2)\n{\n\tlist<ObsKey> obsKeys;\n\tfor (auto& [obsKey, val] : obsIntMap1)\tobsKeys.push_back(obsKey);\n\tfor (auto& [obsKey, val] : obsIntMap2)\tobsKeys.push_back(obsKey);\n\tobsKeys.sort();\n\tobsKeys.unique();\n\treturn obsKeys;\n}\n\n\nvoid networkEstimatorCSStuff()\n{\n#if 0\n\t// Cycle slip detection + repair\n\tbool anotherStateTransitionCalcRequired = true;\n\tif (acsConfig.csOpts.enable)\n\t{\n\t\tauto timer = Clock::now();\n\n\t\t// Replicate flow of networkEstimator() with L1/L2/Lc phase measurements, up to the point where prefit residuals are calculated\n\t\tKFMeasEntryList kfMeasEntryListCopy = kfMeasEntryList;\n\t\tKFState kfStatePrior = kfState;\n\t\t//add process noise to existing states as per their initialisations.\n\t\tkfStatePrior.stateTransition(trace, tgap);\n\t\tif (acsConfig.csOpts.timer_debug)\n\t\t{\n\t\t\tif (sEpochNum == 1)\n\t\t\t{\n\t\t\t\tstd::ofstream out(\"csTimer.dbg\", std::ios::out);\t\n\t\t\t\tout << \"Start\" << std::endl;\n\t\t\t}\n\t\t\t\n\t\t\tstd::ofstream out(\"csTimer.dbg\", std::ios::app);\n\t\t\tout << \"Epoch: \" << sEpochNum << \" Section: stateTransition Runtime (s): \" << std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timer).count() / 1000.0 << std::endl;\n\t\t\ttimer = Clock::now();\n\t\t}\n\t\t//combine the measurement list into a single matrix\n\t\tKFMeas combinedMeasCopy = kfStatePrior.combineKFMeasList(kfMeasEntryListCopy);\n\t\tKFMeas combinedMeasL1 \t= kfStatePrior.combineKFMeasList(kfMeasEntryListL1);\n\t\tKFMeas combinedMeasL2 \t= kfStatePrior.combineKFMeasList(kfMeasEntryListL2);\n\t\tKFMeas combinedMeasLc \t= kfStatePrior.combineKFMeasList(kfMeasEntryListLc);\n\t\tauto time = stations.front()->obsList.front().time;\n\t\tcombinedMeasCopy.time \t= time;\n\t\tcombinedMeasL1.time \t= time;\n\t\tcombinedMeasL2.time \t= time;\n\t\tcombinedMeasLc.time \t= time;\n\t\tcorrectRecClocks(trace, kfStatePrior, refRec);\n\t\t\n\t\t//if there are uninitialised state values, estimate them using least squares\n\t\tif (acsConfig.csOpts.timer_debug)\n\t\t{\n\t\t\tstd::ofstream out;\n\t\t\tout.open(\"csTimer.dbg\", std::ios::app);\n\t\t\tout << \"Epoch: \" << sEpochNum << \" Section: combineKFMeasList Runtime (s): \" << std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timer).count() / 1000.0 << std::endl;\n\t\t\ttimer = Clock::now();\n\t\t\tout.close();\n\t\t}\n\t\t\n\t\tKFState kfStatePriorLssq = kfStatePrior;\n\t\tif (kfStatePriorLssq.lsqRequired)\n\t\t{\n\t\t\tkfStatePriorLssq.lsqRequired = false;\n\t\t\tkfStatePriorLssq.leastSquareInitStates(trace, combinedMeasCopy);\n\t\t}\n\t\t\n\t\tif (acsConfig.csOpts.timer_debug)\n\t\t{\n\t\t\tstd::ofstream out(\"csTimer.dbg\", std::ios::app);\n\t\t\tout << \"Epoch: \" << sEpochNum << \" Section: lssq Runtime (s): \" << std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timer).count() / 1000.0 << std::endl;\n\t\t\ttimer = Clock::now();\n\t\t}\n\n\t\t// Calculate prefit residuals & store in a KFMeasEntryList (where .value = prefit residual value)\n\t\tKFMeasEntryList prefitL1 = kfStatePriorLssq.calcPrefitResids(trace, combinedMeasL1);\n\t\tKFMeasEntryList prefitL2 = kfStatePriorLssq.calcPrefitResids(trace, combinedMeasL2);\n\t\tKFMeasEntryList prefitLc = kfStatePriorLssq.calcPrefitResids(trace, combinedMeasLc);\n\t\t\n\t\tif (acsConfig.csOpts.timer_debug)\n\t\t{\n\t\t\tstd::ofstream out(\"csTimer.dbg\", std::ios::app);\n\t\t\tout << \"Epoch: \" << sEpochNum << \" Section: calcPrefitResids Runtime (s): \" << std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timer).count() / 1000.0 << std::endl;\n\t\t\ttimer = Clock::now();\n\t\t}\n\t\t\n\t\t// Insert artificial cycle slips (for debugging/testing)\n\t\tbool insertSlip = false;\n\t\tif (insertSlip)\n\t\t{\n\t\t\tstd::string sat = \"G01\";\n\t\t\tstd::string rec = \"DAV1\";\n\t\t\tint slipL1 = 1; // Number of cycles to slip in L1\n\t\t\tint slipL2 = 1;\n\t\t\tint epoch = 30;\n\n\t\t\tdouble wavelengthL1 = 1 / acsConfig.csOpts.freq_l1 * CLIGHT;\n\t\t\tdouble wavelengthL2 = 1 / acsConfig.csOpts.freq_l2 * CLIGHT;\n\t\t\tdouble jumpL1 = slipL1 * wavelengthL1;\n\t\t\tdouble jumpL2 = slipL2 * wavelengthL2;\n\t\t\tdouble jumpLc = calcLc(jumpL1, acsConfig.csOpts.freq_l1, jumpL2, acsConfig.csOpts.freq_l2);\n\t\t\tObsKey obsKeyToInsertSlipL1 = { sat.c_str(), rec, \"L\" };\n\t\t\tObsKey obsKeyToInsertSlipL2 = { sat.c_str(), rec, \"L\" };\n\t\t\tObsKey obsKeyToInsertSlipLc = { sat.c_str(), rec, \"L\" };\n\t\t\tinsertArtificialSlip(obsKeyToInsertSlipL1, jumpL1,\tepoch, prefitL1, sEpochNum);\n\t\t\tinsertArtificialSlip(obsKeyToInsertSlipL2, jumpL2,\tepoch, prefitL2, sEpochNum);\n\t\t\tinsertArtificialSlip(obsKeyToInsertSlipLc, jumpLc,\tepoch, prefitLc, sEpochNum);\n\t\t}\n\t\t\n\t\tif (insertSlip)\n\t\t{\n\t\t\tstd::string sat = \"G10\";\n\t\t\tstd::string rec = \"QUIN\";\n\t\t\tint slipL1 = 1; // Number of cycles to slip in L1\n\t\t\tint slipL2 = 1;\n\t\t\tint epoch = 40;\n\n\t\t\tdouble wavelengthL1 = 1 / acsConfig.csOpts.freq_l1 * CLIGHT;\n\t\t\tdouble wavelengthL2 = 1 / acsConfig.csOpts.freq_l2 * CLIGHT;\n\t\t\tdouble jumpL1 = slipL1 * wavelengthL1;\n\t\t\tdouble jumpL2 = slipL2 * wavelengthL2;\n\t\t\tdouble jumpLc = calcLc(jumpL1, acsConfig.csOpts.freq_l1, jumpL2, acsConfig.csOpts.freq_l2);\n\t\t\tObsKey obsKeyToInsertSlipL1 = { sat.c_str(), rec, \"L\" };\n\t\t\tObsKey obsKeyToInsertSlipL2 = { sat.c_str(), rec, \"L\" };\n\t\t\tObsKey obsKeyToInsertSlipLc = { sat.c_str(), rec, \"L\" };\n\t\t\tinsertArtificialSlip(obsKeyToInsertSlipL1, jumpL1,\tepoch, prefitL1, sEpochNum);\n\t\t\tinsertArtificialSlip(obsKeyToInsertSlipL2, jumpL2,\tepoch, prefitL2, sEpochNum);\n\t\t\tinsertArtificialSlip(obsKeyToInsertSlipLc, jumpLc,\tepoch, prefitLc, sEpochNum);\n\t\t}\n\n\t\t// Set internal parameters & reset debug files\n\t\tif (sEpochNum == 1)\n\t\t{\n\t\t\tcsAnalyserL1.freqName\t\t\t\t\t= \"L1\";\n\t\t\tcsAnalyserL1.freq\t\t\t\t\t\t= acsConfig.csOpts.freq_l1;\n\t\t\tcsAnalyserL1.printActivity\t\t\t\t= acsConfig.csOpts.print_activity;\n\t\t\tcsAnalyserL1.debug\t\t\t\t\t\t= acsConfig.csOpts.debug;\n\t\t\tcsAnalyserL1.newChannelBreakInDuration\t= acsConfig.csOpts.new_channel_break_in_duration;\n\t\t\tcsAnalyserL1.dMovingAveWin\t\t\t\t= acsConfig.csOpts.d_moving_ave_win;\n\t\t\tcsAnalyserL1.commonModeMethod\t\t\t= acsConfig.csOpts.common_mode_method;\n\t\t\tcsAnalyserL1.slipClassifyMinPts\t\t\t= acsConfig.csOpts.slip_classify_min_pts;\n\t\t\tcsAnalyserL1.slipClassifyPostOutlierPts\t= acsConfig.csOpts.slip_classify_post_outlier_pts;\n\t\t\tcsAnalyserL1.outlierPAlpha\t\t\t\t= acsConfig.csOpts.outlier_p_alpha;\n\t\t\tcsAnalyserL1.tAlpha\t\t\t\t\t\t= acsConfig.csOpts.t_alpha;\n\t\t\tcsAnalyserL1.minSizePAlpha\t\t\t\t= acsConfig.csOpts.min_size_p_alpha;\n\t\t\tcsAnalyserL1.outlierDetectMinPts\t\t= acsConfig.csOpts.outlier_detect_min_pts;\n\t\t\tcsAnalyserL1.intValidPdfThresh\t\t\t= acsConfig.csOpts.int_valid_pdf_thresh;\n\t\t\tcsAnalyserL1.intValidOutlierAlpha\t\t= acsConfig.csOpts.int_valid_outlier_alpha;\n\t\t\tcsAnalyserL1.init();\n\n\t\t\tcsAnalyserL2.freqName\t\t\t\t\t= \"L2\";\n\t\t\tcsAnalyserL2.freq\t\t\t\t\t\t= acsConfig.csOpts.freq_l2;\n\t\t\tcsAnalyserL2.printActivity\t\t\t\t= acsConfig.csOpts.print_activity;\n\t\t\tcsAnalyserL2.debug\t\t\t\t\t\t= acsConfig.csOpts.debug;\n\t\t\tcsAnalyserL2.newChannelBreakInDuration\t= acsConfig.csOpts.new_channel_break_in_duration;\n\t\t\tcsAnalyserL2.dMovingAveWin\t\t\t\t= acsConfig.csOpts.d_moving_ave_win;\n\t\t\tcsAnalyserL2.commonModeMethod\t\t\t= acsConfig.csOpts.common_mode_method;\n\t\t\tcsAnalyserL2.slipClassifyMinPts\t\t\t= acsConfig.csOpts.slip_classify_min_pts;\n\t\t\tcsAnalyserL2.slipClassifyPostOutlierPts\t= acsConfig.csOpts.slip_classify_post_outlier_pts;\n\t\t\tcsAnalyserL2.outlierPAlpha\t\t\t\t= acsConfig.csOpts.outlier_p_alpha;\n\t\t\tcsAnalyserL2.tAlpha\t\t\t\t\t\t= acsConfig.csOpts.t_alpha;\n\t\t\tcsAnalyserL2.minSizePAlpha\t\t\t\t= acsConfig.csOpts.min_size_p_alpha;\n\t\t\tcsAnalyserL2.outlierDetectMinPts\t\t= acsConfig.csOpts.outlier_detect_min_pts;\n\t\t\tcsAnalyserL2.intValidPdfThresh\t\t\t= acsConfig.csOpts.int_valid_pdf_thresh;\n\t\t\tcsAnalyserL2.intValidOutlierAlpha\t\t= acsConfig.csOpts.int_valid_outlier_alpha;\n\t\t\tcsAnalyserL2.init();\n\n\t\t\tcsAnalyserLc.freqName\t\t\t\t\t= \"Lc\";\n\t\t\tcsAnalyserLc.freq1\t\t\t\t\t\t= acsConfig.csOpts.freq_l1;\n\t\t\tcsAnalyserLc.freq2\t\t\t\t\t\t= acsConfig.csOpts.freq_l2;\n\t\t\tcsAnalyserLc.printActivity\t\t\t\t= acsConfig.csOpts.print_activity;\n\t\t\tcsAnalyserLc.debug\t\t\t\t\t\t= acsConfig.csOpts.debug;\n\t\t\tcsAnalyserLc.newChannelBreakInDuration\t= acsConfig.csOpts.new_channel_break_in_duration;\n\t\t\tcsAnalyserLc.dMovingAveWin\t\t\t\t= acsConfig.csOpts.d_moving_ave_win;\n\t\t\tcsAnalyserLc.commonModeMethod\t\t\t= acsConfig.csOpts.common_mode_method;\n\t\t\tcsAnalyserLc.slipClassifyMinPts\t\t\t= acsConfig.csOpts.slip_classify_min_pts;\n\t\t\tcsAnalyserLc.slipClassifyPostOutlierPts\t= acsConfig.csOpts.slip_classify_post_outlier_pts;\n\t\t\tcsAnalyserLc.deweightNoise\t\t\t\t= acsConfig.csOpts.deweight_noise;\n\t\t\tcsAnalyserLc.intValidComboJumpAlpha\t\t= acsConfig.csOpts.int_valid_combo_jump_alpha;\n\t\t\tcsAnalyserLc.init();\n\t\t}\n\n\t\t// Perform cycle slip detection + repair\n\t\tanotherStateTransitionCalcRequired = cycleSlipDetectRepair(csAnalyserL1, csAnalyserL2, csAnalyserLc, prefitL1, prefitL2, prefitLc, sEpochNum, kfState, kfMeasEntryList, measuredStates);\n\t\t\n\t\t// Skip state transition recalculation if no changes to state vector are required\n\t\tif (!anotherStateTransitionCalcRequired)\n\t\t{\n\t\t\tkfState = kfStatePrior;\n\t\t}\n\n\t\t// Debug\n\t\tif (acsConfig.csOpts.timer_debug)\n\t\t{\n\t\t\tstd::ofstream out(\"csTimer.dbg\", std::ios::app);\n\t\t\t// Record slip analysis run-time\n\t\t\tout << \"Epoch: \" << sEpochNum << \" Section: cycleSlipDetectRepair Runtime (s): \" << std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timer).count() / 1000.0 << std::endl;\n\t\t\ttimer = Clock::now();\n\t\t}\n\t\t\n\t\tif (acsConfig.csOpts.debug)\n\t\t{\n\t\t\t// Reset debug files\n\t\t\tif (sEpochNum == 1)\n\t\t\t{\n\t\t\t\tfor (string file : \t{\n\t\t\t\t\t\t\t\t\t\t\"Visibilities.dbg\",\n\t\t\t\t\t\t\t\t\t\t\"KFLcAll.dbg\",\n\t\t\t\t\t\t\t\t\t\t\"KFL1.dbg\",\n\t\t\t\t\t\t\t\t\t\t\"KFL2.dbg\",\n\t\t\t\t\t\t\t\t\t\t\"KFLc.dbg\",\n\t\t\t\t\t\t\t\t\t\t\"KFL1Prefit.dbg\",\n\t\t\t\t\t\t\t\t\t\t\"KFL2Prefit.dbg\",\n\t\t\t\t\t\t\t\t\t\t\"KFLcPrefit.dbg\"\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t{\n\t\t\t\t\tstd::ofstream out(file, std::ios::out);\n\t\t\t\t\t\n\t\t\t\t\tout << \"Start\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Record rec-sat visibilities, OmC's & prefit residuals for L1/L2/Lc\n\t\t\tstd::ofstream out(\"Visibilities.dbg\", std::ios::app);\n\t\t\tfor (auto& meas : kfMeasEntryListL1)\t\n\t\t\t\tout << sEpochNum << \" \" << meas.obsKey.str << \" \" << meas.obsKey.Sat.id() << std::endl;\n\t\t\t\n\t\t\tprintToFile(kfMeasEntryList, \t\"KFLcAll.dbg\",\t\tsEpochNum);\n\t\t\tprintToFile(kfMeasEntryListL1, \t\"KFL1.dbg\",\t\t\tsEpochNum);\n\t\t\tprintToFile(kfMeasEntryListL2, \t\"KFL2.dbg\",\t\t\tsEpochNum);\n\t\t\tprintToFile(kfMeasEntryListLc, \t\"KFLc.dbg\",\t\t\tsEpochNum);\n\t\t\tprintToFile(prefitL1, \t\t\t\"KFL1Prefit.dbg\",\tsEpochNum);\n\t\t\tprintToFile(prefitL2, \t\t\t\"KFL2Prefit.dbg\",\tsEpochNum);\n\t\t\tprintToFile(prefitLc, \t\t\t\"KFLcPrefit.dbg\",\tsEpochNum);\n\t\t}\n\t\t++sEpochNum;\n\t}\n\n\t//add process noise to existing states as per their initialisations.\n\tif (anotherStateTransitionCalcRequired)\n\t{\n\t\tkfState.stateTransition(trace, tgap);\n\t}\n#endif\n}\n", "meta": {"hexsha": "47ff972521bc2c13efae9442ed5958581fca2abb", "size": 48056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/pea/cycleSlip.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/pea/cycleSlip.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/pea/cycleSlip.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": 33.1649413389, "max_line_length": 225, "alphanum_fraction": 0.7080073248, "num_tokens": 14531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17975274897821938}}
{"text": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#ifndef CPPQEDCORE_QUANTUMDATA_TRANSFORMATION_TCC_INCLUDED\n#define CPPQEDCORE_QUANTUMDATA_TRANSFORMATION_TCC_INCLUDED\n\n#include \"Transformation.h\"\n\n#include <boost/fusion/adapted/mpl.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/fusion/view/zip_view.hpp>\n#include <boost/fusion/view/filter_view.hpp>\n#include <boost/mpl/count_if.hpp>\n\n\n\nnamespace quantumdata {\n\nnamespace transformation {\n\n\nnamespace specializations {\n\nusing namespace linalg;\n\nvoid performTransformation(const CMatrix  & trafo, const CVector  & in, CVector  & out);\n\nvoid performTransformation(const CArray<4>& trafo, const CArray<2>& in, CArray<2>& out);\n\n// ... Et caetera.\n\n} // specializations\n\n\n\ntemplate<int TWO_TIMES_RANK>\nvoid\nTraits<CArray<TWO_TIMES_RANK>>::transform(const CArray<TWO_TIMES_RANK>& trafo, const StateVectorLow& in, StateVectorLow& out)\n{\n  specializations::performTransformation(trafo,in,out);\n}\n\n\n\n///////////////////////////\n// Composite transformation\n///////////////////////////\n\n\nnamespace namehider {\n\n\nusing namespace boost::mpl;\nnamespace mpl=boost::mpl;\n\n\ntemplate<typename TRAFO >\nstruct RankThroughTraits :  int_< Traits<TRAFO>::N_RANK     >\n{};\n\n\ntemplate<typename TRAFO >\nstruct NotIdentity : true_\n{};\n\ntemplate<int RANK>\nstruct NotIdentity<Identity<RANK> > : false_\n{};\n\n\ntemplate<typename TRAFOS>\nstruct Algorithm \n  : fold<TRAFOS,\n         pair<tmptools::Vector<>,int_<0> >,\n         pair<if_<NotIdentity<mpl::_2>,\n                  push_back<first<mpl::_1>,second<mpl::_1> >,\n                  first<mpl::_1>\n                  >,\n              plus<second<mpl::_1>,\n                   RankThroughTraits<mpl::_2>\n                   >\n              >\n         >\n{};\n\n\n\n\n\n} // namehider\n\n\n\n\ntemplate<typename TRAFOS>\nclass Composite\n{\npublic:\n  static const int N_RANK=boost::mpl::fold<TRAFOS,\n                                           boost::mpl::int_<0>,\n                                           boost::mpl::plus<boost::mpl::_1,\n                                                            namehider::RankThroughTraits<boost::mpl::_2>\n                                                            >\n                                           >::type::value;\n\n  typedef TRAFOS TrafoTypes;\n  \nprivate:\n  typedef boost::fusion::filter_view<const TrafoTypes,namehider::NotIdentity<boost::mpl::_> > TrafoTypesFilteredView;\n\npublic:\n  typedef typename boost::fusion::result_of::as_vector<TrafoTypesFilteredView>::type FilteredTrafoTypes;\n  // Without Identities. It is important to convert back to a vector.\n\n  typedef typename Types<N_RANK>::StateVectorLow StateVectorLow;\n\n  Composite(const TrafoTypes& t): trafos_(t), filteredTrafos_(TrafoTypesFilteredView(trafos_)) {};\n\n  const TrafoTypes& getTrafos() const {return trafos_;}\n\n\n  void transform(const StateVectorLow& in, StateVectorLow& out) const\n  {\n    doTransform(in,out,boost::mpl::int_<boost::mpl::count_if<TRAFOS,namehider::NotIdentity<boost::mpl::_> >::value>());\n  }\n\n\nprivate:\n\n  const TrafoTypes trafos_;\n\n  // implementation helpers:\n\n  const FilteredTrafoTypes filteredTrafos_;\n\n  DEFINE_TYPED_STATIC_CONST( typename boost::mpl::first<typename namehider::Algorithm<TRAFOS>::type>::type , AuxiliaryVector , auxiliaryVector_ ) ;\n\n  const boost::fusion::zip_view<boost::fusion::tuple<const FilteredTrafoTypes&, const AuxiliaryVector&> >\n  zip() const \n  {\n    return tie(filteredTrafos_,auxiliaryVector_); // implicit conversion to return type\n  }\n\n  template<int COUNT>\n  void doTransform(const StateVectorLow& in, StateVectorLow& out, boost::mpl::int_<COUNT>) const\n  {\n    using namespace boost::fusion;\n    StateVectorLow buf(out.shape());\n    boost::fusion::fold(zip(),in,TransformSubsystem(out,buf));\n  }\n\n  void doTransform(const StateVectorLow& in, StateVectorLow& out, boost::mpl::int_<  1  >) const\n  {\n    using namespace boost::fusion;\n    boost::fusion::fold(zip(),in,TransformSubsystem(out,out));\n  }\n\n  void doTransform(const StateVectorLow& in, StateVectorLow& out, boost::mpl::int_<  0  >) const\n  {\n    out=in;\n  }\n\n\n  class TransformSubsystem\n  {\n  public:\n    typedef const StateVectorLow& result_type;\n\n    TransformSubsystem(StateVectorLow& out, StateVectorLow& buf)\n        : out_(out), buf_(buf) {}\n\n\n    template<typename TUPLE>\n    const StateVectorLow& doIt(const StateVectorLow& in, TUPLE, boost::mpl:: true_)\n    {\n      return in;\n    }\n\n#define TYPEDEF_TRAFO typedef typename tmptools::RemoveConstReference<typename boost::fusion::result_of::at_c<TUPLE,0>::type>::type TRAFO;\n\n    template<typename TUPLE>\n    const StateVectorLow& doIt(const StateVectorLow& in, TUPLE tuple, boost::mpl::false_)\n    {\n      using namespace boost::fusion; using namespace blitzplusplus; using basi::fullRange;\n\n      TYPEDEF_TRAFO ;\n\n      typedef tmptools::Range<Traits<TRAFO>::N_RANK,boost::remove_reference<typename result_of::at_c<TUPLE,1>::type>::type::value> Range;\n\n      cpputils::for_each(fullRange(in,Range()),basi::begin(buf_,Range()),bind(&Traits<TRAFO>::transform,at_c<0>(tuple),_1,_2));\n\n      blitz::swap(buf_,out_); return out_;\n    }\n\n    template<typename TUPLE>\n    const StateVectorLow& operator()(const StateVectorLow& in, TUPLE tuple)\n    {\n      TYPEDEF_TRAFO ;\n\n      return doIt(in,tuple,boost::mpl::bool_<!namehider::NotIdentity<TRAFO>::value>());\n    }\n\n#undef TYPEDEF_TRAFO\n\n  private:\n    StateVectorLow& out_, buf_;\n\n  }; // TransformSubsystems\n\n\n}; // Composite\n\n\n\ntemplate<typename TRAFOS>\nconst typename Composite<TRAFOS>::AuxiliaryVector Composite<TRAFOS>::auxiliaryVector_=Composite<TRAFOS>::AuxiliaryVector();\n\n\n#define COMPOSITE_TRAFO Composite<typename boost::fusion::result_of::as_vector<typename boost::fusion::result_of::join<const typename Traits<TRAFO1>::TrafoTypes,const typename Traits<TRAFO2>::TrafoTypes>::type>::type>\n\ntemplate<typename TRAFO1, typename TRAFO2>\nstruct Compose : boost::mpl::identity<COMPOSITE_TRAFO>\n{\n  static const COMPOSITE_TRAFO compose(const TRAFO1& t1, const TRAFO2& t2)\n  {\n    return COMPOSITE_TRAFO(boost::fusion::as_vector(boost::fusion::join(Traits<TRAFO1>::getTrafos(t1),Traits<TRAFO2>::getTrafos(t2))));\n  }\n};\n\n#undef  COMPOSITE_TRAFO\n\n\n\n\n// Traits specialization for Composite:\n\ntemplate<typename TRAFOS>\nstruct Traits<Composite<TRAFOS> >\n{\n  typedef Composite<TRAFOS> TRAFO;\n\n  static const int N_RANK=TRAFO::N_RANK;\n  \n  typedef typename TRAFO::TrafoTypes     TrafoTypes    ;\n  typedef typename TRAFO::StateVectorLow StateVectorLow;\n\n  static void transform(const TRAFO& trafo, const StateVectorLow& in, StateVectorLow& out) {trafo.transform(in,out);}\n\n  static const TrafoTypes& getTrafos(const TRAFO& trafo) {return trafo.getTrafos();}\n\n};\n\n\n\n\n\n} // transformation\n\n\n} // quantumdata\n\n#endif // CPPQEDCORE_QUANTUMDATA_TRANSFORMATION_TCC_INCLUDED\n", "meta": {"hexsha": "d718a92fd64fcbc81b944e114541988eba67400d", "size": 6855, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/quantumdata/Transformation.tcc", "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": "CPPQEDcore/quantumdata/Transformation.tcc", "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": "CPPQEDcore/quantumdata/Transformation.tcc", "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.2643678161, "max_line_length": 217, "alphanum_fraction": 0.6891320204, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17966914988070495}}
{"text": "#include <jni.h>\n#include <android/log.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include \"include/slam_dunk.h\"\n\n#include <fstream>\n\n#include <boost/timer/timer.hpp>\n#include <boost/scoped_ptr.hpp>\n\n#include <Eigen/StdVector>\n\n#define  LOG_TAG\t\"slamdunk_app\"\n#define  LOGI(...)\t__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)\n#define  LOGE(...)\t__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)\n\n//TODO #include \"kalman/include/KalmanGlobal.h\" ed altri\n\ntypedef std::vector<std::pair<double, Eigen::Isometry3d>, Eigen::aligned_allocator< std::pair<double, Eigen::Isometry3d> > > StampedPoseVector;\n\nextern \"C\"\n{\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_main_SlamDunkNative_init(JNIEnv *env, jobject obj,\n\t\t\tjfloat fx, jfloat fy, jfloat cx, jfloat cy, jint cols, jint rows,\n\t\t\tjint rbaRings, jfloat keyframeOverlapping, jboolean tryLoopInference,\n\t\t\tjfloat activeWindowLength, jboolean debugAlgorithm);\n\tJNIEXPORT jint JNICALL Java_it_unibo_slam_main_SlamDunkNative_execute(JNIEnv *env, jobject obj,\n\t\t\tjdouble timestamp, jlong colorImagePtr, jlong depthImagePtr, jdoubleArray estimatedPose);\n\tJNIEXPORT jint JNICALL Java_it_unibo_slam_main_SlamDunkNative_executeTracking(JNIEnv *env, jobject obj,\n\t\t\tjdouble timestamp, jlong colorImagePtr, jlong depthImagePtr, jdoubleArray estimatedPose);\n\tJNIEXPORT jint JNICALL Java_it_unibo_slam_main_SlamDunkNative_executeOptimization(JNIEnv *env, jobject obj,\n\t\t\tjdoubleArray estimatedPose);\n\tJNIEXPORT jint JNICALL Java_it_unibo_slam_main_SlamDunkNative_getMovedFramesNum(JNIEnv *env, jobject obj);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_main_SlamDunkNative_getMovedFrames(JNIEnv *env, jobject obj,\n\t\t\tjdoubleArray timestamps, jdoubleArray isometries);\n\tJNIEXPORT jfloat JNICALL Java_it_unibo_slam_main_SlamDunkNative_getResidual(JNIEnv *env, jobject obj);\n}\n\n// Global variables accessible only within this source file\nnamespace\n{\n\tboost::scoped_ptr<slamdunk::SlamDunk> slam;\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_main_SlamDunkNative_init(JNIEnv *env, jobject obj,\n\t\tjfloat fx, jfloat fy, jfloat cx, jfloat cy, jint cols, jint rows,\n\t\tjint rbaRings, jfloat keyframeOverlapping, jboolean tryLoopInference,\n\t\tjfloat activeWindowLength, jboolean debugAlgorithm)\n{\n\tEigen::Matrix3f inverseKCam = Eigen::Matrix3f::Identity();\n\tinverseKCam(0,0) = 1.0F / fx;\n\tinverseKCam(1,1) = 1.0F / fy;\n\tinverseKCam(0,2) = cx * (-1.0F / fx);\n\tinverseKCam(1,2) = cy * (-1.0F / fy);\n\n\tslamdunk::SlamDunkParams sdParams = slamdunk::SlamDunkParams();\n\tslamdunk::FeatureTrackerParams ftParams = slamdunk::FeatureTrackerParams();\n\tftParams.outlier_rejection.reset(new slamdunk::RANSAC(true, 0.05));\n\tftParams.active_win_length = activeWindowLength;\n\tsdParams.tracker.reset(new slamdunk::FeatureTracker(inverseKCam, cols, rows, ftParams));\n\tsdParams.rba_rings = rbaRings;\n\tsdParams.kf_overlapping = keyframeOverlapping;\n\tsdParams.try_loop_inference = (bool)(tryLoopInference != JNI_FALSE);\n\t//TODO add debug?\n\n\t//slam = new slamdunk::SlamDunk(inverseKCam, sdParams);\n\tslam.reset(new slamdunk::SlamDunk(inverseKCam, sdParams));\n}\n\nJNIEXPORT jint JNICALL Java_it_unibo_slam_main_SlamDunkNative_execute(JNIEnv *env, jobject obj,\n\t\tjdouble timestamp, jlong colorImagePtr, jlong depthImagePtr, jdoubleArray estimatedPose)\n{\n\tdouble tempEstimatedPose[16];\n\tjdouble* elements = env->GetDoubleArrayElements(estimatedPose, NULL);\n\tfor (int i = 0; i < 16; i++)\n\t\ttempEstimatedPose[i] = elements[i];\n\n\tcv::Mat& colorImage = *(cv::Mat*)colorImagePtr;\n\tcv::Mat_<float>& depthImage = *(cv::Mat_<float>*)depthImagePtr;\n\n\tslamdunk::RGBDFrame frame;\n\tframe.m_color_image = colorImage;\n\tframe.m_depth_image = depthImage;\n\tframe.m_timestamp = timestamp;\n\n\tEigen::Isometry3d estimatedPoseEigen(Eigen::Matrix4d::Map(tempEstimatedPose));\n\n\tint result = (*slam)(frame, estimatedPoseEigen);\n\n\tfor (int i = 0; i < 16; i++)\n\t\telements[i] = estimatedPoseEigen.matrix().data()[i];\n\n\tenv->ReleaseDoubleArrayElements(estimatedPose, elements, 0);\n\n\treturn result;\n}\n\nJNIEXPORT jint JNICALL Java_it_unibo_slam_main_SlamDunkNative_executeTracking(JNIEnv *env, jobject obj,\n\t\tjdouble timestamp, jlong colorImagePtr, jlong depthImagePtr, jdoubleArray estimatedPose)\n{\n\tdouble tempEstimatedPose[16];\n\tjdouble* elements = env->GetDoubleArrayElements(estimatedPose, NULL);\n\tfor (int i = 0; i < 16; i++)\n\t\ttempEstimatedPose[i] = elements[i];\n\n\tcv::Mat& colorImage = *(cv::Mat*)colorImagePtr;\n\tcv::Mat_<float>& depthImage = *(cv::Mat_<float>*)depthImagePtr;\n\n\tslamdunk::RGBDFrame frame;\n\tframe.m_color_image = colorImage;\n\tframe.m_depth_image = depthImage;\n\tframe.m_timestamp = timestamp;\n\n\tEigen::Isometry3d estimatedPoseEigen(Eigen::Matrix4d::Map(tempEstimatedPose));\n\n\tint result = slam->executeTracking(frame, estimatedPoseEigen);\n\n\tfor (int i = 0; i < 16; i++)\n\t\telements[i] = estimatedPoseEigen.matrix().data()[i];\n\n\tenv->ReleaseDoubleArrayElements(estimatedPose, elements, 0);\n\n\treturn result;\n}\n\nJNIEXPORT jint JNICALL Java_it_unibo_slam_main_SlamDunkNative_executeOptimization(JNIEnv *env, jobject obj,\n\t\tjdoubleArray estimatedPose)\n{\n\tdouble tempEstimatedPose[16];\n\tjdouble* elements = env->GetDoubleArrayElements(estimatedPose, NULL);\n\tfor (int i = 0; i < 16; i++)\n\t\ttempEstimatedPose[i] = elements[i];\n\n\tEigen::Isometry3d estimatedPoseEigen(Eigen::Matrix4d::Map(tempEstimatedPose));\n\n\tint result = slam->executeOptimization(estimatedPoseEigen);\n\n\tfor (int i = 0; i < 16; i++)\n\t\telements[i] = estimatedPoseEigen.matrix().data()[i];\n\n\tenv->ReleaseDoubleArrayElements(estimatedPose, elements, 0);\n\n\treturn result;\n}\n\nJNIEXPORT jint JNICALL Java_it_unibo_slam_main_SlamDunkNative_getMovedFramesNum(JNIEnv *env, jobject obj)\n{\n\treturn slam->getMovedFrames().size();\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_main_SlamDunkNative_getMovedFrames(JNIEnv *env, jobject obj,\n\t\tjdoubleArray timestamps, jdoubleArray isometries)\n{\n\tjdouble* timestampsElements = env->GetDoubleArrayElements(timestamps, NULL);\n\tjdouble* isometriesElements = env->GetDoubleArrayElements(isometries, NULL);\n\n\tStampedPoseVector movedFrames = slam->getMovedFrames();\n\tint size = movedFrames.size();\n\n\tfor (int i = 0, k = 0; i < size; i++, k += 16)\n\t{\n\t\ttimestampsElements[i] = movedFrames[i].first;\n\t\tconst double *data = movedFrames[i].second.data();\n\t\tfor (int j = 0; j < 16; j++)\n\t\t\tisometriesElements[j + k] = data[j];\n\t}\n\n\tenv->ReleaseDoubleArrayElements(timestamps, timestampsElements, 0);\n\tenv->ReleaseDoubleArrayElements(isometries, isometriesElements, 0);\n}\n\nJNIEXPORT jfloat JNICALL Java_it_unibo_slam_main_SlamDunkNative_getResidual(JNIEnv *env, jobject obj)\n{\n\treturn slam->getResidual();\n}\n", "meta": {"hexsha": "3c650646084770d25b7341b35f87359c838f3064", "size": 6613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jni/slamdunk/slamdunk_app.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": "jni/slamdunk/slamdunk_app.cpp", "max_issues_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_issues_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_issues_repo_licenses": ["Apache-2.0"], "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": "jni/slamdunk/slamdunk_app.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": 36.7388888889, "max_line_length": 143, "alphanum_fraction": 0.7752910933, "num_tokens": 1827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.1796691462258244}}
{"text": "/**\n * @file\n * @license BSD 3-clause\n * @copyright Copyright (c) 2021, New York University and Max Planck Gesellschaft\n * \n * @brief  Abstract interface to the Teststand robot.\n */\n\n#ifndef TeststandAbstractInterface_H\n#define TeststandAbstractInterface_H\n\n#include <Eigen/Eigen>\n#include \"teststand/utils.hpp\"\n\nnamespace teststand\n{\n/**\n * @brief The class TeststandAbstractInterface is used to define an interface\n * to the Teststand robot dirvers.\n * The robots are composed of a single leg on a vertical rail and a TI force\n * torque sensors and a height sensor.\n */\nclass TeststandAbstractInterface\n{\npublic:\n    /**\n     * @brief This represents the contact sensor\n     */\n    typedef Eigen::Matrix<double, 1, 1> VectorContact;\n    /**\n     * @brief This type define the forces from the ati-FT sensors\n     */\n    typedef Eigen::Matrix<double, 3, 1> VectorAtiForce;\n    /**\n     * @brief This type define the torques from the ati-FT sensors\n     */\n    typedef Eigen::Matrix<double, 3, 1> VectorAtiTorque;\n\n    /**\n     * @brief TeststandAbstractInterface is the constructor of the class.\n     */\n    TeststandAbstractInterface()\n    {\n        motor_inertias_.fill(0.0);\n        motor_torque_constants_.fill(0.0);\n        joint_positions_.fill(0.0);\n        joint_velocities_.fill(0.0);\n        joint_torques_.fill(0.0);\n        joint_target_torques_.fill(0.0);\n        joint_gear_ratios_.fill(0.0);\n        joint_encoder_index_.fill(0.0);\n        joint_zero_positions_.fill(0.0);\n        height_sensors_states_.fill(0.0);\n        motor_max_current_.fill(0.0);\n        motor_enabled_.fill(false);\n        motor_ready_.fill(false);\n        motor_board_enabled_.fill(false);\n        motor_board_errors_.fill(0);\n        ati_force_.fill(0.0);\n        ati_torque_.fill(0.0);\n    }\n\n    /**\n     * @brief Destroy the Teststand Abstract Interface object.\n     */\n    virtual ~TeststandAbstractInterface()\n    {\n    }\n\n    /**\n     * @brief initialize the robot by setting aligning the motors and calibrate\n     * the sensors to 0\n     */\n    virtual void initialize() = 0;\n\n    /**\n     * @brief send_target_torques sends the target currents to the motors\n     */\n    virtual void send_target_joint_torque(\n        const Eigen::Ref<const Eigen::Vector2d> target_joint_torque) = 0;\n\n    /**\n     * @brief acquire_sensors acquire all available sensors, WARNING !!!!\n     * this method has to be called prior to any getter to have up to date data.\n     */\n    virtual bool acquire_sensors() = 0;\n\n    /**\n     * @brief Set max current.\n     *\n     * @param max_current\n     */\n    virtual void set_max_current(double max_current) = 0;\n\n    /**\n     * @brief This function will run a small controller that will move the\n     * joints until the next joint index and reset the joint zero with this\n     * knowledge.\n     *\n     * @return true if success\n     * @return false if failure\n     */\n    virtual void calibrate(const Eigen::Vector2d& home_offset_rad) = 0;\n\n    /** @brief Print all the internal data. */     \n    void print_all()\n    {\n        print_vector(\"motor_inertias:         \", motor_inertias_);\n        print_vector(\"motor_torque_constants: \", motor_torque_constants_);\n        print_vector(\"joint_positions:        \", joint_positions_);\n        print_vector(\"joint_velocities:       \", joint_velocities_);\n        print_vector(\"joint_torques:          \", joint_torques_);\n        print_vector(\"joint_target_torques:   \", joint_target_torques_);\n        print_vector(\"joint_gear_ratios:      \", joint_gear_ratios_);\n        print_vector(\"joint_encoder_index:    \", joint_encoder_index_);\n        print_vector(\"joint_zero_positions:   \", joint_zero_positions_);\n        print_vector(\"height_sensors_states:  \", height_sensors_states_);\n        print_vector(\"motor_max_current:      \", motor_max_current_);\n        print_vector_bool(\"motor_enabled:          \", motor_enabled_);\n        print_vector_bool(\"motor_ready:            \", motor_ready_);\n        print_vector_bool(\"motor_board_enabled:    \", motor_board_enabled_);\n        print_vector_int(\"motor_board_errors:     \", motor_board_errors_);\n        print_vector(\"ati_force:              \", ati_force_);\n        print_vector(\"ati_torque:             \", ati_torque_);\n    }\n\n    /**\n     * @brief get_motor_inertias\n     * @return the motor inertias\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_motor_inertias()\n    {\n        return motor_inertias_;\n    }\n\n    /**\n     * @brief get_motor_torque_constants\n     * @return the torque constants of each motor\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_motor_torque_constants()\n    {\n        return motor_torque_constants_;\n    }\n\n    /**\n     * @brief get_joint_positions\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     *\n     * @return  the joint angle of each module\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_joint_positions()\n    {\n        return joint_positions_;\n    }\n\n    /**\n     * @brief get_joint_velocities\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     *\n     * @return the joint velocities\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_joint_velocities()\n    {\n        return joint_velocities_;\n    }\n\n    /**\n     * @brief get_joint_torques\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     *\n     * @return the joint torques\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_joint_torques()\n    {\n        return joint_torques_;\n    }\n\n    /**\n     * @brief get_joint_torques\n     * @return the target joint torques\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_joint_target_torques()\n    {\n        return joint_target_torques_;\n    }\n\n    /**\n     * @brief get_joint_gear_ratios\n     * @return  the joint gear ratios\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_joint_gear_ratios()\n    {\n        return joint_gear_ratios_;\n    }\n\n    /**\n     * @brief get_joint_encoder_index\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     *\n     * @return The last observed encoder index in joint coordinates.\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_joint_encoder_index()\n    {\n        return joint_encoder_index_;\n    }\n\n    /**\n     * @brief get_zero_positions\n     * @return the position where the robot should be in \"zero\" configuration\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_zero_positions()\n    {\n        return joint_zero_positions_;\n    }\n\n    /**\n     * @brief get_contact_sensors_states\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     *\n     * @return the state of the contacts states\n     */\n    const Eigen::Ref<VectorContact> get_height_sensor()\n    {\n        return height_sensors_states_;\n    }\n\n    /**\n     * @brief get_max_current\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     * @return the max current.\n     */\n    const Eigen::Ref<Eigen::Vector2d> get_max_current()\n    {\n        return motor_max_current_;\n    }\n\n    /**\n     * @brief Get motor enabled.\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     * @return const Eigen::Matrix<bool, 4>&\n     */\n    const Eigen::Matrix<bool, 2, 1>& get_motor_enabled() const\n    {\n        return motor_enabled_;\n    }\n\n    /**\n     * @brief Get motor ready.\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     * @return const Eigen::Matrix<bool, 1, 1>&\n     */\n    const Eigen::Matrix<bool, 2, 1>& get_motor_ready() const\n    {\n        return motor_ready_;\n    }\n\n    /**\n     * @brief Get motor board enabled.\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     * @return const Eigen::Matrix<bool, 1, 1>&\n     */\n    const Eigen::Matrix<bool, 1, 1>& get_motor_board_enabled() const\n    {\n        return motor_board_enabled_;\n    }\n\n    /**\n     * @brief Get motor board errors.\n     * @return const Eigen::Matrix<int, 2>&\n     */\n    const Eigen::Matrix<int, 1, 1>& get_motor_board_errors() const\n    {\n        return motor_board_errors_;\n    }\n\n    /**\n     * @brief Get the ati_force_ object\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     *\n     * @return const Eigen::Ref<VectorAtiForce>\n     */\n    const Eigen::Ref<VectorAtiForce> get_ati_force()\n    {\n        return ati_force_;\n    }\n\n    /**\n     * @brief Get the ati_torque_ object\n     * WARNING !!!! The method acquire_sensors() has to be called prior to\n     * any getter to have up to date data.\n     *\n     * @return const Eigen::Ref<VectorAtiTorque>\n     */\n    const Eigen::Ref<VectorAtiTorque> get_ati_torque()\n    {\n        return ati_torque_;\n    }\n\nprotected:\n    /**\n     * Motor data\n     */\n\n    /**\n     * @brief motor_inertias_\n     */\n    Eigen::Vector2d motor_inertias_;\n    /**\n     * @brief motor_torque_constants_ are the motor torque constants\n     */\n    Eigen::Vector2d motor_torque_constants_;\n\n    /**\n     * Joint data\n     */\n\n    /**\n     * @brief joint_positions_ is the measured data from the onboard card\n     * converted at the joint level.\n     */\n    Eigen::Vector2d joint_positions_;\n    /**\n     * @brief joint_velocities_ is the measured data from the onboard card\n     * converted at the joint level.\n     */\n    Eigen::Vector2d joint_velocities_;\n    /**\n     * @brief joint_torques_ is the measured data from the onboard card\n     * converted at the joint level.\n     */\n    Eigen::Vector2d joint_torques_;\n    /**\n     * @brief joint_target_torques_ is the last given command to be sent.\n     */\n    Eigen::Vector2d joint_target_torques_;\n    /**\n     * @brief joint_gear_ratios are the joint gear ratios\n     */\n    Eigen::Vector2d joint_gear_ratios_;\n    /**\n     * @brief joint_encoder_index_ The last observed encoder_index at the\n     * joints.\n     */\n    Eigen::Vector2d joint_encoder_index_;\n\n    /**\n     * @brief joint_zero_positions_ is the configuration considered as zero\n     * position\n     */\n    Eigen::Vector2d joint_zero_positions_;\n\n    /**\n     * Additional data\n     */\n\n    /**\n     * @brief height_sensors_ is the height position of the base.\n     */\n    VectorContact height_sensors_states_;\n\n    /**\n     * @brief max_current_ is the maximum current that can be sent to the\n     * motors, this a safe guard for development\n     */\n    Eigen::Vector2d motor_max_current_;\n\n    /**\n     * @brief This gives the status (enabled/disabled) of each motors using the\n     * joint ordering convention.\n     */\n    Eigen::Matrix<bool, 2, 1 > motor_enabled_;\n\n    /**\n     * @brief This gives the status (enabled/disabled) of each motors using the\n     * joint ordering convention.\n     */\n    Eigen::Matrix<bool, 2, 1 > motor_ready_;\n\n    /**\n     * @brief This gives the status (enabled/disabled of the onboard control\n     * cards)\n     */\n    Eigen::Matrix<bool, 1, 1> motor_board_enabled_;\n\n    /**\n     * @brief This gives the status (enabled/disabled of the onboard control\n     * cards)\n     */\n    Eigen::Matrix<int, 1, 1> motor_board_errors_;\n\n    /**\n     * @brief 3D linear force from the ATI FT sensor\n     */\n    VectorAtiForce ati_force_;\n\n    /**\n     * @brief 3D torque measured from the ATI FT sensor\n     */\n    VectorAtiTorque ati_torque_;\n};\n\n}  // namespace teststand\n\n#endif  // TeststandAbstractInterface_H\n", "meta": {"hexsha": "ee49222029b8b62c96cacadf7bc83f3ff3b6f9bd", "size": 11720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/teststand/teststand_abstract_interface.hpp", "max_stars_repo_name": "jviereck/teststand", "max_stars_repo_head_hexsha": "c8f46c314f67a7ade73929abed610795dd7959f6", "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/teststand/teststand_abstract_interface.hpp", "max_issues_repo_name": "jviereck/teststand", "max_issues_repo_head_hexsha": "c8f46c314f67a7ade73929abed610795dd7959f6", "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/teststand/teststand_abstract_interface.hpp", "max_forks_repo_name": "jviereck/teststand", "max_forks_repo_head_hexsha": "c8f46c314f67a7ade73929abed610795dd7959f6", "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.2409638554, "max_line_length": 81, "alphanum_fraction": 0.6311433447, "num_tokens": 2907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3380771308191989, "lm_q1q2_score": 0.17958974081446408}}
{"text": "\n#include <fstream>\n\n#include <limits>\n\n#include <boost/lexical_cast.hpp>\n\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"flame/constants.h\"\n\n#include \"flame/moment.h\"\n#include \"flame/moment_sup.h\"\n#include \"flame/rf_cavity.h\"\n#include \"flame/chg_stripper.h\"\n\n#define sqr(x)  ((x)*(x))\n#define cube(x) ((x)*(x)*(x))\n\nnamespace ub = boost::numeric::ublas;\n\nnamespace {\n\n// ARR should be an array-like object (std::vector or or ublas vector or matrix storage)\n// fill 'to' using config.get<>(name)\n// 'T' selects throw error (true) or return boolean (false)\ntemplate<typename ARR>\nbool load_storage(ARR& to, const Config& conf, const std::string& name, bool T=true)\n{\n    try{\n        const std::vector<double>& val(conf.get<std::vector<double> >(name));\n        if(to.size()!=val.size()) {\n            throw std::invalid_argument(SB()<<\"Array \"<<name<<\" must have \"<<to.size()<<\" elements, not \"<<val.size());\n        }\n        std::copy(val.begin(), val.end(), to.begin());\n\n        return true;\n    }catch(std::exception&){\n        if(T)\n            throw std::invalid_argument(name+\" not defined or has wrong type (must be vector)\");\n        else\n            return false;\n        // default to identity\n    }\n}\n\n} // namespace\n\nstd::ostream& operator<<(std::ostream& strm, const Particle& P)\n{\n    strm\n      <<\"IonZ=\"<<std::scientific << std::setprecision(10)<<P.IonZ\n      <<\" IonQ=\"<<P.IonQ\n      <<\" IonEs=\"<<P.IonEs\n      <<\" IonEk=\"<<P.IonEk\n      <<\" SampleIonK=\"<<P.SampleIonK\n      <<\" phis=\"<<P.phis\n      <<\" IonW=\"<<P.IonW\n      <<\" gamma=\"<<P.gamma\n      <<\" beta=\"<<P.beta\n      <<\" bg=\"<<P.bg\n      ;\n    return strm;\n}\n\nMomentState::MomentState(const Config& c)\n    :StateBase(c)\n    ,ref()\n    ,real()\n    ,moment0_env(maxsize, 0e0)\n    ,moment0_rms(maxsize, 0e0)\n    ,moment1_env(boost::numeric::ublas::identity_matrix<double>(maxsize))\n{\n    // hack.  getArray() promises that returned pointers will remain valid for our lifetime.\n    // This may not be true if std::vectors are resized.\n    // Reserve for up to 10 states and hope for the best...\n    // either need to provide real limit to max. states, or change getArray() iface\n    real.reserve(10);\n\n    double icstate_f = 0.0;\n    bool have_cstate = c.tryGet<double>(\"cstate\", icstate_f);\n    size_t icstate = (size_t)icstate_f;\n\n    std::string vectorname(c.get<std::string>(\"vector_variable\", \"moment0\"));\n    std::string matrixname(c.get<std::string>(\"matrix_variable\", \"initial\"));\n\n    std::vector<double> ics, nchg;\n    bool have_ics = c.tryGet<std::vector<double> >(\"IonChargeStates\", ics);\n\n    ref.IonEs      = c.get<double>(\"IonEs\", 0e0),\n    ref.IonEk      = c.get<double>(\"IonEk\", 0e0),\n    ref.SampleFreq = c.get<double>(\"SampleFreq\", SampleFreqDefault);\n    ref.recalc();\n\n    if(!have_ics) {\n        ref.IonZ = c.get<double>(\"IonZ\", 0e0);\n        ref.IonQ = c.get<double>(\"IonQ\", 1e0);\n\n        ics.push_back(ref.IonZ);\n        nchg.push_back(ref.IonQ);\n\n    } else {\n        if(ics.empty())\n            throw std::invalid_argument(\"IonChargeStates w/ length 0\");\n        if(icstate>=ics.size())\n            throw std::invalid_argument(\"IonChargeStates[cstate] is out of bounds\");\n\n        nchg = c.get<std::vector<double> >(\"NCharge\");\n        if(nchg.size()!=ics.size())\n            throw std::invalid_argument(\"NCharge[] and IonChargeStates[] must have equal length\");\n\n        bool have_ionz = c.tryGet<double>(\"IonZ\", ref.IonZ);\n        if(!have_ionz) {\n            ref.IonZ = ics[0];\n        }\n\n        bool have_ionq = c.tryGet<double>(\"IonQ\", ref.IonQ);\n        if(!have_ionq) {\n            ref.IonQ = nchg[0];\n        }\n    }\n\n    /* Possible configurations\n     * 1. Neither 'cstate' nor 'IonChargeStates' defined (empty Config).\n     *    No charge states, must go through source element to be useful\n     * 2. 'IonChargeStates' defined, but not 'cstate'.\n     *    Load all charge states\n     * 3. 'cstate' and 'IonChargeStates' defined.\n     *    Load a single charge state\n     */\n    if(!have_cstate && !have_ics) {\n        // no-op\n    } else if(!have_cstate && have_ics) {\n        // many charge states\n        icstate = 0;\n\n    } else if(have_cstate && have_ics) {\n        // single charge state\n\n        // drop other than selected state\n        ics[0]  = ics[icstate];\n        nchg[0] = nchg[icstate];\n        ics.resize(1);\n        nchg.resize(1);\n\n    } else {\n        throw std::invalid_argument(\"MomentState: must define IonChargeStates and NCharge when cstate is set\");\n    }\n\n    if(have_ics) {\n        real.resize(ics.size());\n        moment0.resize(ics.size());\n        moment1.resize(ics.size());\n        transmat.resize(ics.size());\n\n        for(size_t i=0; i<ics.size(); i++) {\n            std::string num(boost::lexical_cast<std::string>(icstate+i));\n\n            moment0[i].resize(maxsize);\n            moment1[i].resize(maxsize, maxsize);\n            moment1[i] = boost::numeric::ublas::identity_matrix<double>(maxsize);\n            transmat[i].resize(maxsize, maxsize);\n            transmat[i] = boost::numeric::ublas::identity_matrix<double>(maxsize);\n\n            load_storage(moment0[i].data(), c, vectorname+num);\n            load_storage(moment1[i].data(), c, matrixname+num);\n\n            real[i] = ref;\n\n            real[i].IonZ = ics[i];\n            real[i].IonQ = nchg[i];\n\n            real[i].phis      = moment0[i][PS_S];\n            real[i].IonEk    += moment0[i][PS_PS]*MeVtoeV;\n\n            real[i].recalc();\n        }\n    } else {\n        real.resize(1); // hack, ensure at least one element so getArray() can return some pointer\n        real[0] = ref;\n\n        moment0.resize(1);\n        moment1.resize(1);\n        transmat.resize(1);\n        moment0[0].resize(maxsize);\n        moment1[0].resize(maxsize, maxsize);\n        transmat[0].resize(maxsize, maxsize);\n\n        load_storage(moment0[0].data(), c, vectorname, false);\n        load_storage(moment1[0].data(), c, matrixname, false);\n        transmat[0] = boost::numeric::ublas::identity_matrix<double>(maxsize);\n    }\n\n    last_caviphi0 = 0e0;\n    calc_rms();\n}\n\nMomentState::~MomentState() {}\n\nvoid MomentState::calc_rms()\n{\n    assert(real.size()>0);\n    assert(moment0_env.size()==maxsize);\n    assert(moment0_rms.size()==maxsize);\n    assert(moment1_env.size1()==maxsize);\n    assert(moment1_env.size2()==maxsize);\n\n    double totQ = 0.0;\n    for(size_t n=0; n<real.size(); n++) {\n        totQ += real[n].IonQ;\n        if(n==0)\n            noalias(moment0_env)  = moment0[n]*real[n].IonQ;\n        else\n            noalias(moment0_env) += moment0[n]*real[n].IonQ;\n    }\n    moment0_env /= totQ;\n\n    // Zero orbit terms.\n    moment1_env = ub::zero_matrix<double>(state_t::maxsize);\n    boost::numeric::ublas::slice S(0, 1, 6);\n    for(size_t n=0; n<real.size(); n++) {\n        const double Q = real[n].IonQ;\n        state_t::vector_t m0diff(moment0[n]-moment0_env);\n\n        ub::project(moment1_env, S, S) += ub::project(Q*(moment1[n]+ub::outer_prod(m0diff, m0diff)), S, S);\n    }\n    moment1_env /= totQ;\n\n    for(size_t j=0; j<maxsize; j++) {\n        moment0_rms[j] = sqrt(moment1_env(j,j));\n    }\n}\n\nMomentState::MomentState(const MomentState& o, clone_tag t)\n    :StateBase(o, t)\n    ,ref(o.ref)\n    ,real(o.real)\n    ,moment0(o.moment0)\n    ,moment1(o.moment1)\n    ,transmat(o.transmat)\n    ,moment0_env(o.moment0_env)\n    ,moment0_rms(o.moment0_rms)\n    ,moment1_env(o.moment1_env)\n    ,last_caviphi0(o.last_caviphi0)\n{}\n\nvoid MomentState::assign(const StateBase& other)\n{\n    const MomentState *O = dynamic_cast<const MomentState*>(&other);\n    if(!O)\n        throw std::invalid_argument(\"Can't assign State: incompatible types\");\n    ref     = O->ref;\n    real    = O->real;\n    moment0 = O->moment0;\n    moment1 = O->moment1;\n    transmat = O->transmat;\n    moment0_env = O->moment0_env;\n    moment0_rms = O->moment0_rms;\n    moment1_env = O->moment1_env;\n    last_caviphi0 = O->last_caviphi0;\n    StateBase::assign(other);\n}\n\nvoid MomentState::show(std::ostream& strm, int level) const\n{\n    if(real.empty()) {\n        strm<<\"State: empty\";\n        return;\n    }\n\n    if(level<=0) {\n        strm<<\"State: moment0 mean=\"<<moment0_env;\n    }\n    if(level>=1) {\n        strm << std::scientific << std::setprecision(8)\n             << \"\\nState:\\n  energy [eV] =\\n\" << std::setw(20) << real[0].IonEk << \"\\n  moment0 mean =\\n    \";\n        for (size_t k = 0; k < MomentState::maxsize; k++)\n            strm << std::scientific << std::setprecision(10) << std::setw(18) << moment0_env(k) << \",\";\n        strm << std::scientific << std::setprecision(10)\n             << \"\\n  moment0 rms =\\n    \";\n        for (size_t k = 0; k < MomentState::maxsize; k++)\n            strm << std::scientific << std::setprecision(10) << std::setw(18) << moment0_rms(k) << \",\";\n        strm << \"\\n  moment1 mean =\\n\";\n        for (size_t j = 0; j < MomentState::maxsize; j++) {\n            strm << \"    \";\n            for (size_t k = 0; k < MomentState::maxsize; k++) {\n                strm << std::scientific << std::setprecision(10) << std::setw(18) << moment1_env(j, k) << \",\";\n            }\n            if (j < MomentState::maxsize-1) strm << \"\\n\";\n        }\n    }\n    if(level>=2) {\n        strm<< \"\\n  Reference state:\\n    \"<<ref<<\"\\n\";\n        for(size_t k=0; k<size(); k++) {\n            strm<<\"  Charge state \"<<k<<\"\\n\"\n                  \"    \"<<real[k]<<\"\\n\"\n                  \"    moment0 \"<<moment0[k]<<\"\\n\";\n            if(level>=3)\n                strm<<\n                  \"    moment1 \"<<moment1[k]<<\"\\n\";\n        }\n    }\n}\n\nbool MomentState::getArray(unsigned idx, ArrayInfo& Info) {\n    unsigned I=0;\n    if(idx==I++) {\n        Info.name = \"moment1_env\";\n        Info.ptr = &moment1_env(0,0);\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 2;\n        Info.dim[0] = moment1_env.size1();\n        Info.dim[1] = moment1_env.size2();\n        Info.stride[0] = sizeof(double)*moment1_env.size2();\n        Info.stride[1] = sizeof(double);\n        return true;\n    } else if(idx==I++) {\n        /* Slight evilness here\n         * moment0 is vector of ublas::matrix\n         * We assume ublax::matrix uses storage bounded_array<>, and that this storage\n         * is really a C array, which means that everything is part of one big allocation.\n         * Further we assume that all entries in the vector have the same shape.\n         * If this isn't the case, then SIGSEGV here we come...\n         */\n        static_assert(sizeof(moment1[0])>=sizeof(double)*maxsize*maxsize,\n                      \"storage assumption violated\");\n        Info.name = \"moment1\";\n        Info.ptr = &moment1[0](0,0);\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 3;\n        Info.dim[0] = moment1[0].size1();\n        Info.dim[1] = moment1[0].size2();\n        Info.dim[2] = moment1.size();\n        Info.stride[0] = sizeof(double)*moment1_env.size2();\n        Info.stride[1] = sizeof(double);\n        Info.stride[2] = sizeof(moment1[0]);\n        return true;\n    } else if(idx==I++) {\n        static_assert(sizeof(transmat[0])>=sizeof(double)*maxsize*maxsize,\n                      \"storage assumption violated\");\n        Info.name = \"transmat\";\n        Info.ptr = &transmat[0](0,0);\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 3;\n        Info.dim[0] = transmat[0].size1();\n        Info.dim[1] = transmat[0].size2();\n        Info.dim[2] = transmat.size();\n        Info.stride[0] = sizeof(double)*moment1_env.size2();\n        Info.stride[1] = sizeof(double);\n        Info.stride[2] = sizeof(transmat[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"moment0_env\";\n        Info.ptr = &moment0_env(0);\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim[0] = moment0_env.size();\n        Info.stride[0] = sizeof(double);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"moment0_rms\";\n        Info.ptr = &moment0_rms(0);\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim[0] = moment0_rms.size();\n        Info.stride[0] = sizeof(double);\n        return true;\n    } else if(idx==I++) {\n        // more evilness here, see above\n        static_assert(sizeof(moment0[0])>=sizeof(double)*maxsize,\n                \"storage assumption violated\");\n        Info.name = \"moment0\";\n        Info.ptr = &moment0[0][0];\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 2;\n        Info.dim[0] = moment0[0].size();\n        Info.dim[1] = moment0.size();\n        Info.stride[0] = sizeof(double);\n        Info.stride[1] = sizeof(moment0[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_IonZ\";\n        Info.ptr = &ref.IonZ;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_IonQ\";\n        Info.ptr = &ref.IonQ;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_IonEs\";\n        Info.ptr = &ref.IonEs;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_IonW\";\n        Info.ptr = &ref.IonW;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_gamma\";\n        Info.ptr = &ref.gamma;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_beta\";\n        Info.ptr = &ref.beta;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_bg\";\n        Info.ptr = &ref.bg;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_SampleFreq\";\n        Info.ptr = &ref.SampleFreq;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_SampleIonK\";\n        Info.ptr = &ref.SampleIonK;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_phis\";\n        Info.ptr = &ref.phis;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"ref_IonEk\";\n        Info.ptr = &ref.IonEk;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"IonZ\";\n        Info.ptr  = &real[0].IonZ;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        // Note: this array is discontigious as we reference a single member from a Particle[]\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"IonEs\";\n        Info.ptr  = &real[0].IonEs;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"IonW\";\n        Info.ptr  = &real[0].IonW;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"gamma\";\n        Info.ptr  = &real[0].gamma;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"beta\";\n        Info.ptr  = &real[0].beta;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"bg\";\n        Info.ptr  = &real[0].bg;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"SampleFreq\";\n        Info.ptr  = &real[0].SampleFreq;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"SampleIonK\";\n        Info.ptr  = &real[0].SampleIonK;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"phis\";\n        Info.ptr  = &real[0].phis;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"IonEk\";\n        Info.ptr  = &real[0].IonEk;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"IonQ\";\n        Info.ptr  = &real[0].IonQ;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 1;\n        Info.dim   [0] = real.size();\n        Info.stride[0] = sizeof(real[0]);\n        // Note: this array is discontigious as we reference a single member from a Particle[]\n        return true;\n    } else if(idx==I++) {\n        Info.name = \"last_caviphi0\";\n        Info.ptr = &last_caviphi0;\n        Info.type = ArrayInfo::Double;\n        Info.ndim = 0;\n        // driven phase [degree]\n        return true;\n    }\n    return StateBase::getArray(idx-I, Info);\n}\n\nMomentElementBase::MomentElementBase(const Config& c)\n    :ElementVoid(c)\n    ,dx   (c.get<double>(\"dx\",    0e0)*MtoMM)\n    ,dy   (c.get<double>(\"dy\",    0e0)*MtoMM)\n    ,pitch(c.get<double>(\"pitch\", 0e0))\n    ,yaw  (c.get<double>(\"yaw\",   0e0))\n    ,roll (c.get<double>(\"roll\",  0e0))\n    ,skipcache(c.get<double>(\"skipcache\", 0.0)!=0.0)\n    ,scratch(state_t::maxsize, state_t::maxsize)\n{\n}\n\nMomentElementBase::~MomentElementBase() {}\n\nvoid MomentElementBase::assign(const ElementVoid *other)\n{\n    const MomentElementBase *O = static_cast<const MomentElementBase*>(other);\n    last_real_in = O->last_real_in;\n    last_real_out= O->last_real_out;\n    last_ref_in  = O->last_ref_in;\n    last_ref_out = O->last_ref_out;\n    transfer = O->transfer;\n    misalign = O->misalign;\n    misalign_inv = O->misalign_inv;\n    dx = O->dx;\n    dy = O->dy;\n    pitch = O->pitch;\n    yaw   = O->yaw;\n    roll  = O->roll;\n    skipcache = O->skipcache;\n    ElementVoid::assign(other);\n}\n\nvoid MomentElementBase::show(std::ostream& strm, int level) const\n{\n    using namespace boost::numeric::ublas;\n    ElementVoid::show(strm, level);\n    /*\n    strm<<\"Length \"<<length<<\"\\n\"\n          \"Transfer: \"<<transfer<<\"\\n\"\n          \"Mis-align: \"<<misalign<<\"\\n\";\n          */\n}\n\nvoid MomentElementBase::get_misalign(const state_t &ST, const Particle &real, value_t &M, value_t &IM) const\n{\n    state_t::matrix_t R,\n              scl     = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize),\n              scl_inv = scl,\n              T       = scl,\n              T_inv   = scl,\n              R_inv   = scl;\n\n    scl(state_t::PS_S, state_t::PS_S)   /= -real.SampleIonK;\n    scl(state_t::PS_PS, state_t::PS_PS) /= sqr(real.beta)*real.gamma*ST.ref.IonEs/MeVtoeV;\n\n    inverse(scl_inv, scl);\n\n    // Translate to center of element.\n    T(state_t::PS_S,  6) = -length/2e0*MtoMM;\n    T(state_t::PS_PS, 6) = 1e0;\n    inverse(T_inv, T);\n\n    RotMat(dx, dy, pitch, yaw, roll, R);\n\n    M = prod(T, scl);\n    M = prod(R, M);\n    M = prod(T_inv, M);\n    M = prod(scl_inv, M);\n\n    inverse(R_inv, R);\n\n    // Translate to center of element.\n    T(state_t::PS_S,  6) = length/2e0*MtoMM;\n    T(state_t::PS_PS, 6) = 1e0;\n    inverse(T_inv, T);\n\n    IM = prod(T, scl);\n    IM = prod(R_inv, IM);\n    IM = prod(T_inv, IM);\n    IM = prod(scl_inv, IM);\n}\n\nunsigned MomentElementBase::get_flag(const Config& c, const std::string& name, const unsigned& def_value)\n{\n    unsigned read_value;\n    double check_value;\n\n    try {\n        check_value = boost::lexical_cast<double>(c.get<std::string>(name));\n    }catch (std::exception&){\n        try {\n            check_value = c.get<double>(name);\n        }catch (std::exception&){\n            check_value = boost::lexical_cast<double>(def_value);\n        }\n    }\n\n    //Check the value is an unsigned integer\n    try {\n        read_value = boost::lexical_cast<unsigned>(check_value);\n        if (boost::lexical_cast<double>(read_value) != check_value)\n            throw std::runtime_error(SB()<< name << \" must be an unsigned integer\");\n    }catch (std::exception&){\n        throw  std::runtime_error(SB()<< name << \" must be an unsigned integer\");\n    }\n    return read_value;\n}\n\nvoid MomentElementBase::advance(StateBase& s)\n{\n    state_t&  ST = static_cast<state_t&>(s);\n    using namespace boost::numeric::ublas;\n\n    // IonEk is Es + E_state; the latter is set by user.\n    ST.recalc();\n\n    if(!check_cache(ST)){\n        // need to re-calculate energy dependent terms\n        last_ref_in = ST.ref;\n        last_real_in = ST.real;\n        resize_cache(ST);\n\n        recompute_matrix(ST); // updates transfer and last_Kenergy_out\n\n        ST.recalc();\n\n        if(!ST.retreat){\n            ST.ref.phis += ST.ref.SampleIonK*length*MtoMM;\n            for(size_t k=0; k<last_real_in.size(); k++)\n                ST.real[k].phis += ST.real[k].SampleIonK*length*MtoMM;\n        } else {\n            ST.ref.phis -= ST.ref.SampleIonK*length*MtoMM;\n            for(size_t k=0; k<last_real_in.size(); k++)\n                ST.real[k].phis -= ST.real[k].SampleIonK*length*MtoMM;\n        }\n\n        last_ref_out = ST.ref;\n        last_real_out = ST.real;\n    } else {\n        ST.ref = last_ref_out;\n        assert(last_real_out.size()==ST.real.size()); // should be true if check_cache() -> true\n        std::copy(last_real_out.begin(),\n                  last_real_out.end(),\n                  ST.real.begin());\n    }\n\n    if(!ST.retreat){\n        // Forward propagation\n        ST.pos += length;\n\n        for(size_t k=0; k<last_real_in.size(); k++) {\n            ST.moment0[k] = prod(transfer[k], ST.moment0[k]);\n\n            scratch = prod(transfer[k], ST.moment1[k]);\n            ST.moment1[k] = prod(scratch, trans(transfer[k]));\n\n            ST.transmat[k] = transfer[k];\n        }\n    } else {\n        // Backward propagation\n        ST.pos -= length;\n\n        value_t invmat = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n        for(size_t k=0; k<last_real_in.size(); k++) {\n            inverse(invmat, transfer[k]);\n\n            ST.moment0[k] = prod(invmat, ST.moment0[k]);\n\n            scratch = prod(invmat, ST.moment1[k]);\n            ST.moment1[k] = prod(scratch, trans(invmat));\n\n            ST.transmat[k] = invmat;\n        }\n    }\n\n    ST.calc_rms();\n}\n\nbool MomentElementBase::check_cache(const state_t& ST) const\n{\n    return !skipcache\n            && last_real_in.size()==ST.size()\n            && last_ref_in==ST.ref\n            && std::equal(last_real_in.begin(),\n                          last_real_in.end(),\n                          ST.real.begin());\n}\n\nbool MomentElementBase::check_backward(const state_t& ST) const\n{\n    bool reals = true;\n    if (last_real_out.size()==ST.size()) {\n        reals = last_ref_out<=ST.ref;\n        for(size_t k=0; k<last_real_out.size(); k++) {\n            reals &= last_real_out[k]<=ST.real[k];\n        }\n    } else {\n        reals = false;\n    }\n\n    return reals;\n}\n\nvoid MomentElementBase::resize_cache(const state_t& ST)\n{\n    transfer.resize(ST.real.size(), boost::numeric::ublas::identity_matrix<double>(state_t::maxsize));\n    misalign.resize(ST.real.size(), boost::numeric::ublas::identity_matrix<double>(state_t::maxsize));\n    misalign_inv.resize(ST.real.size(), boost::numeric::ublas::identity_matrix<double>(state_t::maxsize));\n}\n\nvoid MomentElementBase::recompute_matrix(state_t& ST)\n{\n    // Default, initialize as no-op\n\n    for(size_t k=0; k<last_real_in.size(); k++) {\n        transfer[k] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n    }\n}\n\nnamespace {\n\nstruct ElementSource : public MomentElementBase\n{\n    typedef ElementSource            self_t;\n    typedef MomentElementBase        base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementSource(const Config& c): base_t(c), istate(c) {}\n\n    virtual void advance(StateBase& s)\n    {\n        state_t& ST = static_cast<state_t&>(s);\n        if (!ST.retreat)\n            // Replace state with our initial values\n            ST.assign(istate);\n    }\n\n    virtual void show(std::ostream& strm, int level) const\n    {\n        ElementVoid::show(strm, level);\n        strm<<\"Initial: \"<<istate.moment0_env<<\"\\n\";\n    }\n\n    state_t istate;\n    // note that 'transfer' is not used by this element type\n\n    virtual ~ElementSource() {}\n\n    virtual const char* type_name() const {return \"source\";}\n\n    virtual void assign(const ElementVoid *other) {\n        base_t::assign(other);\n        const self_t* O=static_cast<const self_t*>(other);\n        istate.assign(O->istate);\n    }\n};\n\nstruct ElementMark : public MomentElementBase\n{\n    // Transport (identity) matrix for Marker.\n    typedef ElementMark            self_t;\n    typedef MomentElementBase     base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementMark(const Config& c): base_t(c) {length = 0e0;}\n    virtual ~ElementMark() {}\n    virtual const char* type_name() const {return \"marker\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n};\n\nstruct ElementBPM : public MomentElementBase\n{\n    // Transport (identity) matrix for BPM.\n    typedef ElementBPM               self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementBPM(const Config& c): base_t(c) {length = 0e0;}\n    virtual ~ElementBPM() {}\n    virtual const char* type_name() const {return \"bpm\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n};\n\nstruct ElementDrift : public MomentElementBase\n{\n    // Transport matrix for Drift.\n    typedef ElementDrift             self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementDrift(const Config& c) : base_t(c) {}\n    virtual ~ElementDrift() {}\n    virtual const char* type_name() const {return \"drift\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n\n    virtual void recompute_matrix(state_t& ST)\n    {\n        // Re-initialize transport matrix.\n\n        const double L = length*MtoMM; // Convert from [m] to [mm].\n\n        for(size_t i=0; i<last_real_in.size(); i++) {\n            transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n            transfer[i](state_t::PS_X, state_t::PS_PX) = L;\n            transfer[i](state_t::PS_Y, state_t::PS_PY) = L;\n            transfer[i](state_t::PS_S, state_t::PS_PS) =\n                -2e0*M_PI/(ST.real[i].SampleLambda*ST.real[i].IonEs/MeVtoeV*cube(ST.real[i].bg))*L;\n        }\n    }\n};\n\nstruct ElementOrbTrim : public MomentElementBase\n{\n    // Transport matrix for Orbit Trim.\n    typedef ElementOrbTrim           self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementOrbTrim(const Config& c) : base_t(c) {length = 0e0;}\n    virtual ~ElementOrbTrim() {}\n    virtual const char* type_name() const {return \"orbtrim\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n\n    virtual void recompute_matrix(state_t& ST)\n    {\n        // Re-initialize transport matrix.\n        double theta_x = conf().get<double>(\"theta_x\", 0e0),\n               theta_y = conf().get<double>(\"theta_y\", 0e0);\n        const double tm_xkick = conf().get<double>(\"tm_xkick\", 0e0),\n                     tm_ykick = conf().get<double>(\"tm_ykick\", 0e0),\n                     xyrotate = conf().get<double>(\"xyrotate\", 0e0)*M_PI/180e0;\n        const bool   realpara = conf().get<double>(\"realpara\", 0e0) == 1e0;\n\n        if (realpara) {\n            double ecpi = ST.ref.IonZ*C0/sqrt(sqr(ST.ref.IonW) - sqr(ST.ref.IonEs));\n            theta_x = tm_xkick*ecpi;\n            theta_y = tm_ykick*ecpi;\n        }\n\n        for(size_t i=0; i<last_real_in.size(); i++) {\n            transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n            transfer[i](state_t::PS_PX, 6) = theta_x*ST.real[i].IonZ/ST.ref.IonZ;\n            transfer[i](state_t::PS_PY, 6) = theta_y*ST.real[i].IonZ/ST.ref.IonZ;\n\n            get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n\n            noalias(scratch)  = prod(transfer[i], misalign[i]);\n            noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n\n            if (xyrotate != 0e0) {\n                state_t::matrix_t R;\n                RotMat(0e0, 0e0, 0e0, 0e0, xyrotate, R);\n                noalias(scratch)  = transfer[i];\n                noalias(transfer[i]) = prod(scratch, R);\n            }\n\n        }\n    }\n};\n\nstruct ElementSBend : public MomentElementBase\n{\n    // Transport matrix for Gradient Sector Bend; with edge focusing (cylindrical coordinates).\n    // Note, TLM only includes energy offset for the orbit; not the transport matrix.\n\n    typedef ElementSBend             self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    unsigned HdipoleFitMode;\n\n    ElementSBend(const Config& c) : base_t(c), HdipoleFitMode(0) {\n\n        HdipoleFitMode = get_flag(c, \"HdipoleFitMode\", 1);\n        if (HdipoleFitMode != 0 && HdipoleFitMode != 1)\n            throw std::runtime_error(SB()<< \"Undefined HdipoleFitMode: \" << HdipoleFitMode);\n    }\n    virtual ~ElementSBend() {}\n    virtual const char* type_name() const {return \"sbend\";}\n\n    virtual void assign(const ElementVoid *other) {\n        base_t::assign(other);\n        const self_t* O=static_cast<const self_t*>(other);\n        HdipoleFitMode = O->HdipoleFitMode;\n    }\n\n    virtual void advance(StateBase& s)\n    {\n        state_t&  ST = static_cast<state_t&>(s);\n        using namespace boost::numeric::ublas;\n\n        // IonEk is Es + E_state; the latter is set by user.\n        ST.recalc();\n\n        if(!check_cache(ST)) {\n            // need to re-calculate energy dependent terms\n            last_ref_in = ST.ref;\n            last_real_in = ST.real;\n            resize_cache(ST);\n\n            recompute_matrix(ST); // updates transfer and last_Kenergy_out\n\n            ST.recalc();\n            last_ref_out = ST.ref;\n            last_real_out = ST.real;\n        } else {\n            ST.ref = last_ref_out;\n            assert(last_real_out.size()==ST.real.size()); // should be true if check_cache() -> true\n            std::copy(last_real_out.begin(),\n                      last_real_out.end(),\n                      ST.real.begin());\n        }\n\n        if(!ST.retreat){\n            // Forward propagation\n            ST.pos += length;\n            ST.ref.phis += ST.ref.SampleIonK*length*MtoMM;\n\n            for(size_t i=0; i<last_real_in.size(); i++) {\n                double phis_temp = ST.moment0[i][state_t::PS_S];\n\n                ST.moment0[i]          = prod(transfer[i], ST.moment0[i]);\n\n                noalias(scratch)       = prod(transfer[i], ST.moment1[i]);\n                noalias(ST.moment1[i]) = prod(scratch, trans(transfer[i]));\n\n                double dphis_temp = ST.moment0[i][state_t::PS_S] - phis_temp;\n\n                ST.real[i].phis  += ST.real[i].SampleIonK*length*MtoMM + dphis_temp;\n                ST.transmat[i] = transfer[i];\n            }\n        } else {\n            // Backward propagation\n            ST.pos -= length;\n            ST.ref.phis -= ST.ref.SampleIonK*length*MtoMM;\n\n            value_t invmat = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n            for(size_t i=0; i<last_real_in.size(); i++) {\n                double phis_temp = ST.moment0[i][state_t::PS_S];\n\n                inverse(invmat, transfer[i]);\n                ST.moment0[i]          = prod(invmat, ST.moment0[i]);\n\n                noalias(scratch)       = prod(invmat, ST.moment1[i]);\n                noalias(ST.moment1[i]) = prod(scratch, trans(invmat));\n\n                double dphis_temp = ST.moment0[i][state_t::PS_S] - phis_temp;\n\n                ST.real[i].phis  -= ST.real[i].SampleIonK*length*MtoMM - dphis_temp;\n                ST.transmat[i] = invmat;\n            }\n        }\n\n        ST.calc_rms();\n    }\n\n    virtual void recompute_matrix(state_t& ST)\n    {\n        // Re-initialize transport matrix.\n\n        double L     = conf().get<double>(\"L\")*MtoMM,\n               phi   = conf().get<double>(\"phi\")*M_PI/180e0,\n               phi1  = conf().get<double>(\"phi1\")*M_PI/180e0,\n               phi2  = conf().get<double>(\"phi2\")*M_PI/180e0,\n               K     = conf().get<double>(\"K\", 0e0)/sqr(MtoMM);\n\n        for(size_t i=0; i<last_real_in.size(); i++) {\n            double qmrel = (ST.real[i].IonZ-ST.ref.IonZ)/ST.ref.IonZ;\n\n            transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n            if (L != 0.0) {\n                if (!HdipoleFitMode) {\n                    double dip_bg    = conf().get<double>(\"bg\"),\n                           // Dipole reference energy.\n                           dip_Ek    = (sqrt(sqr(dip_bg)+1e0)-1e0)*ST.ref.IonEs,\n                           dip_gamma = (dip_Ek+ST.ref.IonEs)/ST.ref.IonEs,\n                           dip_beta  = sqrt(1e0-1e0/sqr(dip_gamma)),\n                           d         = (ST.ref.gamma-dip_gamma)/(sqr(dip_beta)*dip_gamma) - qmrel,\n                           dip_IonK  = 2e0*M_PI/(dip_beta*ST.ref.SampleLambda);\n\n                    GetSBendMatrix(L, phi, phi1, phi2, K, ST.ref.IonEs, ST.ref.gamma, qmrel,\n                                   dip_beta, dip_gamma, d, dip_IonK, transfer[i]);\n                } else\n                    GetSBendMatrix(L, phi, phi1, phi2, K, ST.ref.IonEs, ST.ref.gamma, qmrel,\n                                   ST.ref.beta, ST.ref.gamma, - qmrel, ST.ref.SampleIonK, transfer[i]);\n\n                get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n\n                noalias(scratch)     = prod(transfer[i], misalign[i]);\n                noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n            }\n        }\n    }\n};\n\nstruct ElementQuad : public MomentElementBase\n{\n    // Transport matrix for Quadrupole; K = B2/Brho.\n    typedef ElementQuad              self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementQuad(const Config& c) : base_t(c) {}\n    virtual ~ElementQuad() {}\n    virtual const char* type_name() const {return \"quadrupole\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n\n    virtual void recompute_matrix(state_t& ST)\n    {\n        const double L = conf().get<double>(\"L\")*MtoMM;\n        const unsigned ncurve = get_flag(conf(), \"ncurve\", 0);\n\n        if (ncurve != 0) {\n            std::vector<std::vector<double> > Curves;\n            std::vector<double> Scales;\n            GetCurveData(conf(), ncurve, Scales, Curves);\n\n            for(size_t i=0; i<last_real_in.size(); i++) {\n                double K;\n                double dL = L/double(Curves[0].size()),\n                       Brho = ST.real[i].Brho();\n                transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n                for (size_t j=0; j<Curves[0].size(); j++){\n                    K = 0.0;\n                    for (size_t n=0; n<Curves.size(); n++) K += Scales[n]*Curves[n][j]/Brho/sqr(MtoMM);\n                    value_t tmstep = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n                    GetQuadMatrix(dL,  K, (unsigned)state_t::PS_X, tmstep);\n                    GetQuadMatrix(dL, -K, (unsigned)state_t::PS_Y, tmstep);\n\n                    tmstep(state_t::PS_S, state_t::PS_PS) =\n                        -2e0*M_PI/(ST.real[i].SampleLambda*ST.real[i].IonEs/MeVtoeV*cube(ST.real[i].bg))*dL;\n\n                    transfer[i] = prod(tmstep, transfer[i]);\n                }\n                get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n                noalias(scratch)     = prod(transfer[i], misalign[i]);\n                noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n            }\n\n        } else {\n            const double B2= conf().get<double>(\"B2\");\n            for(size_t i=0; i<last_real_in.size(); i++) {\n                // Re-initialize transport matrix.\n                transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n                double Brho = ST.real[i].Brho(),\n                       K = B2/Brho/sqr(MtoMM);\n\n                // Horizontal plane.\n                GetQuadMatrix(L,  K, (unsigned)state_t::PS_X, transfer[i]);\n                // Vertical plane.\n                GetQuadMatrix(L, -K, (unsigned)state_t::PS_Y, transfer[i]);\n                // Longitudinal plane.\n\n                transfer[i](state_t::PS_S, state_t::PS_PS) =\n                        -2e0*M_PI/(ST.real[i].SampleLambda*ST.real[i].IonEs/MeVtoeV*cube(ST.real[i].bg))*L;\n\n                get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n                noalias(scratch)     = prod(transfer[i], misalign[i]);\n                noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n            }\n        }\n    }\n};\n\nstruct ElementSext : public MomentElementBase\n{\n    // Transport matrix for Sextupole; K = B3/Brho.\n    typedef ElementSext              self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementSext(const Config& c) : base_t(c) {}\n\n    virtual ~ElementSext() {}\n    virtual const char* type_name() const {return \"sextupole\";}\n\n    virtual void assign(const ElementVoid *other) {base_t::assign(other); }\n\n    virtual void advance(StateBase& s)\n    {\n        const double B3= conf().get<double>(\"B3\"),\n                     L = conf().get<double>(\"L\")*MtoMM;\n        const int    step = conf().get<double>(\"step\", 1.0);\n        const bool   thinlens = conf().get<double>(\"thinlens\", 0.0) == 1.0,\n                     dstkick = conf().get<double>(\"dstkick\", 1.0) == 1.0;\n\n        state_t&  ST = static_cast<state_t&>(s);\n        using namespace boost::numeric::ublas;\n\n        ST.recalc();\n\n        last_ref_in = ST.ref;\n        last_real_in = ST.real;\n        resize_cache(ST);\n\n        if(ST.retreat) throw std::runtime_error(SB()<<\n            \"Backward propagation error: Backward propagation does not support sextupole.\");\n\n        const double dL = L/step;\n\n        for(size_t k=0; k<last_real_in.size(); k++) {\n\n            transfer[k] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n            ST.transmat[k] = transfer[k];\n\n            double Brho = ST.real[k].Brho(),\n                   K = B3/Brho/cube(MtoMM);\n\n            get_misalign(ST, ST.real[k], misalign[k], misalign_inv[k]);\n\n            ST.moment0[k] = prod(misalign[k], ST.moment0[k]);\n            scratch = prod(misalign[k], ST.moment1[k]);\n            ST.moment1[k] = prod(scratch, trans(misalign[k]));\n\n            for(int i=0; i<step; i++){\n                double Dx = ST.moment0[k][state_t::PS_X],\n                       Dy = ST.moment0[k][state_t::PS_Y],\n                       D2x = ST.moment1[k](state_t::PS_X, state_t::PS_X),\n                       D2y = ST.moment1[k](state_t::PS_Y, state_t::PS_Y),\n                       D2xy = ST.moment1[k](state_t::PS_X, state_t::PS_Y);\n\n\n                GetSextMatrix(dL, K, Dx, Dy, D2x, D2y, D2xy, thinlens, dstkick, transfer[k]);\n\n                transfer[k](state_t::PS_S, state_t::PS_PS) =\n                        -2e0*M_PI/(ST.real[k].SampleLambda*ST.real[k].IonEs/MeVtoeV*cube(ST.real[k].bg))*dL;\n\n                ST.moment0[k] = prod(transfer[k], ST.moment0[k]);\n\n                scratch = prod(transfer[k], ST.moment1[k]);\n                ST.moment1[k] = prod(scratch, trans(transfer[k]));\n\n                ST.transmat[k] = prod(transfer[k], ST.transmat[k]);\n            }\n            ST.moment0[k] = prod(misalign_inv[k], ST.moment0[k]);\n            scratch = prod(misalign_inv[k], ST.moment1[k]);\n            ST.moment1[k] = prod(scratch, trans(misalign_inv[k]));\n\n            scratch = prod(ST.transmat[k], misalign[k]);\n            ST.transmat[k] = prod(misalign_inv[k], scratch);\n        }\n\n        ST.recalc();\n\n        for(size_t k=0; k<last_real_in.size(); k++)\n            ST.real[k].phis  += ST.real[k].SampleIonK*length*MtoMM;\n        ST.ref.phis   += ST.ref.SampleIonK*length*MtoMM;\n\n        last_ref_out = ST.ref;\n        last_real_out = ST.real;\n\n        ST.pos += length;\n\n        ST.calc_rms();\n    }\n};\n\nstruct ElementSolenoid : public MomentElementBase\n{\n    // Transport (identity) matrix for a Solenoid; K = B/(2 Brho).\n    typedef ElementSolenoid          self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementSolenoid(const Config& c) : base_t(c) {}\n    virtual ~ElementSolenoid() {}\n    virtual const char* type_name() const {return \"solenoid\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n\n    virtual void recompute_matrix(state_t& ST)\n    {\n        const double L = conf().get<double>(\"L\")*MtoMM;      // Convert from [m] to [mm].\n        const unsigned ncurve = get_flag(conf(), \"ncurve\", 0);\n\n        if (ncurve != 0) {\n            std::vector<std::vector<double> > Curves;\n            std::vector<double> Scales;\n            GetCurveData(conf(), ncurve, Scales, Curves);\n\n            for(size_t i=0; i<last_real_in.size(); i++) {\n                double K;\n                double dL = L/double(Curves[0].size()),\n                       Brho = ST.real[i].Brho();\n                transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n                for (size_t j=0; j<Curves[0].size(); j++){\n                    K = 0.0;\n                    for (size_t n=0; n<Curves.size(); n++) K += Scales[n]*Curves[n][j]/(2e0*Brho)/MtoMM;\n                    value_t tmstep = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n                    GetSolMatrix(dL, K, tmstep);\n\n                    tmstep(state_t::PS_S, state_t::PS_PS) =\n                        -2e0*M_PI/(ST.real[i].SampleLambda*ST.real[i].IonEs/MeVtoeV*cube(ST.real[i].bg))*dL;\n\n                    transfer[i] = prod(tmstep, transfer[i]);\n                }\n                get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n                noalias(scratch)     = prod(transfer[i], misalign[i]);\n                noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n            }\n        } else {\n            const double B = conf().get<double>(\"B\");\n            for(size_t i=0; i<last_real_in.size(); i++) {\n                // Re-initialize transport matrix.\n                transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n                double Brho = ST.real[i].Brho(),\n                       K    = B/(2e0*Brho)/MtoMM;\n\n                GetSolMatrix(L, K, transfer[i]);\n\n                transfer[i](state_t::PS_S, state_t::PS_PS) =\n                        -2e0*M_PI/(ST.real[i].SampleLambda*ST.real[i].IonEs/MeVtoeV*cube(ST.real[i].bg))*L;\n\n                get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n\n                noalias(scratch)     = prod(transfer[i], misalign[i]);\n                noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n            }\n        }\n    }\n};\n\nstruct ElementEDipole : public MomentElementBase\n{\n    // Transport matrix for Electrostatic Dipole with edge focusing.\n    typedef ElementEDipole           self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementEDipole(const Config& c) : base_t(c) {}\n    virtual ~ElementEDipole() {}\n    virtual const char* type_name() const {return \"edipole\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n\n    virtual void recompute_matrix(state_t& ST)\n    {\n        // Re-initialize transport matrix.\n\n        //value_mat R;\n\n        bool   ver         = conf().get<double>(\"ver\") == 1.0;\n        double L           = conf().get<double>(\"L\")*MtoMM,\n               phi         = conf().get<double>(\"phi\")*M_PI/180e0,\n               // fit to TLM unit.\n               fringe_x    = conf().get<double>(\"fringe_x\", 0e0)/MtoMM,\n               fringe_y    = conf().get<double>(\"fringe_y\", 0e0)/MtoMM,\n               kappa       = conf().get<double>(\"asym_fac\", 0e0),\n               // spher: cylindrical - 0, spherical - 1.\n               spher       = conf().get<double>(\"spher\"),\n               // magnetic - 0, electrostatic - 1.\n               h           = 1e0,\n               dip_beta    = conf().get<double>(\"beta\", ST.ref.beta);\n\n        unsigned HdipoleFitMode = get_flag(conf(), \"HdipoleFitMode\", 1);\n\n        if (HdipoleFitMode != 0 && HdipoleFitMode != 1)\n            throw std::runtime_error(SB()<< \"Undefined HdipoleFitMode: \" << HdipoleFitMode);\n\n        if (HdipoleFitMode) dip_beta = ST.ref.beta;\n\n        for(size_t i=0; i<last_real_in.size(); i++) {\n            double eta0        = (1e0/sqrt(1e0 - sqr(dip_beta)) - 1e0)/2e0,\n                   Erho        = sqr(ST.real[i].beta)/ST.real[i].IonZ,\n                   Erho0       = sqr(dip_beta)/ST.ref.IonZ,\n                   eL          = Erho/Erho0*L,\n                   rho         = eL/phi,\n                   Kx          = (1e0-spher+sqr(1e0+2e0*eta0))/sqr(rho),\n                   Ky          = spher/sqr(rho),\n                   delta_K     = (Erho/Erho0 - 1e0) - (ST.real[i].IonEk - ST.ref.IonEk)/ST.real[i].IonEk,\n                   delta_KZ    = ST.ref.IonZ/ST.real[i].IonZ - 1e0,\n                   SampleIonK  = 2e0*M_PI/(ST.real[i].beta*ST.real[i].SampleLambda);\n\n            transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n            if (L != 0e0) {\n                GetEBendMatrix(eL, phi, fringe_x, fringe_y, kappa, Kx, Ky, ST.ref.IonEs, ST.real[i].gamma,\n                               eta0, h, delta_K, delta_KZ, SampleIonK, transfer[i]);\n\n                if (ver) {\n                    // Rotate transport matrix by 90 degrees.\n                    value_t\n                    R = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n                    R(state_t::PS_X,  state_t::PS_X)   =  0e0;\n                    R(state_t::PS_PX, state_t::PS_PX)  =  0e0;\n                    R(state_t::PS_Y,  state_t::PS_Y)   =  0e0;\n                    R(state_t::PS_PY, state_t::PS_PY)  =  0e0;\n                    R(state_t::PS_X,  state_t::PS_Y)   = -1e0;\n                    R(state_t::PS_PX, state_t::PS_PY)  = -1e0;\n                    R(state_t::PS_Y,  state_t::PS_X)   =  1e0;\n                    R(state_t::PS_PY,  state_t::PS_PX) =  1e0;\n\n                    noalias(scratch)     = prod(R, transfer[i]);\n                    noalias(transfer[i]) = prod(scratch, trans(R));\n                    //TODO: no-op code?  results are unconditionally overwritten\n                }\n\n                get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n\n                noalias(scratch)     = prod(transfer[i], misalign[i]);\n                noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n            }\n        }\n    }\n};\n\nstruct ElementEQuad : public MomentElementBase\n{\n    // Transport matrix for Electrostatic Quadrupole.\n    typedef ElementEQuad             self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementEQuad(const Config& c) : base_t(c) {}\n    virtual ~ElementEQuad() {}\n    virtual const char* type_name() const {return \"equad\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n\n    virtual void recompute_matrix(state_t& ST)\n    {\n        const double   L      = conf().get<double>(\"L\")*MtoMM;\n        const unsigned ncurve = get_flag(conf(), \"ncurve\", 0);\n\n        if (ncurve != 0) {\n            std::vector<std::vector<double> > Curves;\n            std::vector<double> Scales;\n            GetCurveData(conf(), ncurve, Scales, Curves);\n\n            for(size_t i=0; i<last_real_in.size(); i++) {\n                double K;\n                double dL = L/double(Curves[0].size()),\n                       Brho = ST.real[i].Brho();\n                transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n                for (size_t j=0; j<Curves[0].size(); j++){\n                    K = 0.0;\n                    for (size_t n=0; n<Curves.size(); n++) K += 2e0*Scales[n]*Curves[n][j]/(C0*ST.real[i].beta)/Brho/sqr(MtoMM);\n                    value_t tmstep = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n                    GetQuadMatrix(dL,  K, (unsigned)state_t::PS_X, tmstep);\n                    GetQuadMatrix(dL, -K, (unsigned)state_t::PS_Y, tmstep);\n\n                    tmstep(state_t::PS_S, state_t::PS_PS) =\n                        -2e0*M_PI/(ST.real[i].SampleLambda*ST.real[i].IonEs/MeVtoeV*cube(ST.real[i].bg))*dL;\n\n                    transfer[i] = prod(tmstep, transfer[i]);\n                }\n                get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n                noalias(scratch)     = prod(transfer[i], misalign[i]);\n                noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n            }\n\n        } else {\n            const double V0 = conf().get<double>(\"V\"),\n                         R  = conf().get<double>(\"radius\");\n\n            for(size_t i=0; i<last_real_in.size(); i++) {\n                // Re-initialize transport matrix.\n                // V0 [V] electrode voltage and R [m] electrode half-distance.\n                transfer[i] = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n                double Brho = ST.real[i].Brho(),\n                       K    = 2e0*V0/(C0*ST.real[i].beta*sqr(R))/Brho/sqr(MtoMM);\n\n                // Horizontal plane.\n                GetQuadMatrix(L,  K, (unsigned)state_t::PS_X, transfer[i]);\n                // Vertical plane.\n                GetQuadMatrix(L, -K, (unsigned)state_t::PS_Y, transfer[i]);\n                // Longitudinal plane.\n                //        transfer(state_t::PS_S, state_t::PS_S) = L;\n\n                transfer[i](state_t::PS_S, state_t::PS_PS) =\n                        -2e0*M_PI/(ST.real[i].SampleLambda*ST.real[i].IonEs/MeVtoeV*cube(ST.real[i].bg))*L;\n\n                get_misalign(ST, ST.real[i], misalign[i], misalign_inv[i]);\n\n                noalias(scratch)     = prod(transfer[i], misalign[i]);\n                noalias(transfer[i]) = prod(misalign_inv[i], scratch);\n            }\n        }\n    }\n};\n\nstruct ElementTMatrix : public MomentElementBase\n{\n    // Transport matrix by user input\n    typedef ElementTMatrix          self_t;\n    typedef MomentElementBase       base_t;\n    typedef typename base_t::state_t state_t;\n\n    ElementTMatrix(const Config& c) : base_t(c) {}\n    virtual ~ElementTMatrix() {}\n    virtual const char* type_name() const {return \"tmatrix\";}\n\n    virtual void assign(const ElementVoid *other) { base_t::assign(other); }\n\n    virtual void recompute_matrix(state_t& ST)\n    {\n        for(size_t i=0; i<last_real_in.size(); i++) {\n            load_storage(transfer[i].data(), conf(), \"matrix\");\n        }\n    }\n};\n\n} // namespace\n\nvoid registerMoment()\n{\n    Machine::registerState<MomentState>(\"MomentMatrix\");\n\n    Machine::registerElement<ElementSource                 >(\"MomentMatrix\", \"source\");\n\n    Machine::registerElement<ElementMark                   >(\"MomentMatrix\", \"marker\");\n\n    Machine::registerElement<ElementBPM                    >(\"MomentMatrix\", \"bpm\");\n\n    Machine::registerElement<ElementDrift                  >(\"MomentMatrix\", \"drift\");\n\n    Machine::registerElement<ElementOrbTrim                >(\"MomentMatrix\", \"orbtrim\");\n\n    Machine::registerElement<ElementSBend                  >(\"MomentMatrix\", \"sbend\");\n\n    Machine::registerElement<ElementQuad                   >(\"MomentMatrix\", \"quadrupole\");\n\n    Machine::registerElement<ElementSext                   >(\"MomentMatrix\", \"sextupole\");\n\n    Machine::registerElement<ElementSolenoid               >(\"MomentMatrix\", \"solenoid\");\n\n    Machine::registerElement<ElementRFCavity               >(\"MomentMatrix\", \"rfcavity\");\n\n    Machine::registerElement<ElementStripper               >(\"MomentMatrix\", \"stripper\");\n\n    Machine::registerElement<ElementEDipole                >(\"MomentMatrix\", \"edipole\");\n\n    Machine::registerElement<ElementEQuad                  >(\"MomentMatrix\", \"equad\");\n\n    Machine::registerElement<ElementTMatrix                >(\"MomentMatrix\", \"tmatrix\");\n}\n", "meta": {"hexsha": "6a073e315aec8b2717ccbb192d145dc94b11a0a7", "size": 53007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/moment.cpp", "max_stars_repo_name": "frib-high-level-controls/FLAME", "max_stars_repo_head_hexsha": "bc2526deb57677df8bb3e5a74652fa31e35abfc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-04-04T20:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T22:37:49.000Z", "max_issues_repo_path": "src/moment.cpp", "max_issues_repo_name": "frib-high-level-controls/FLAME", "max_issues_repo_head_hexsha": "bc2526deb57677df8bb3e5a74652fa31e35abfc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2016-04-07T19:23:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T14:31:14.000Z", "max_forks_repo_path": "src/moment.cpp", "max_forks_repo_name": "frib-high-level-controls/FLAME", "max_forks_repo_head_hexsha": "bc2526deb57677df8bb3e5a74652fa31e35abfc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-04-13T13:26:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T01:55:24.000Z", "avg_line_length": 35.432486631, "max_line_length": 128, "alphanum_fraction": 0.5513422755, "num_tokens": 14301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33807713081919877, "lm_q1q2_score": 0.179589740814464}}
{"text": "\n#ifdef ADEPT_PKG\n  #include <Aria.h>\n#else\n  #include <Aria/Aria.h>\n#endif\n\n#include \"LaserPublisher.h\"\n#include \"ArTimeToROSTime.h\"\n\n#include <math.h>\n\n#include <boost/algorithm/string.hpp>\n\n// TODO publish pointcloud of cumulative readings in separate topic?\n// TODO generic pointcloud sensor publisher (seprate point cloud stuff there)\n// TODO make  similar sonar publisher?\n\nLaserPublisher::LaserPublisher(ArLaser *_l, ros::NodeHandle& _n, bool _broadcast_tf, const std::string& _tf_frame, const std::string& _parent_tf_frame, const std::string& _global_tf_frame) :\n  laserReadingsCB(this, &LaserPublisher::readingsCB),\n  node(_n),\n  laser(_l),\n  tfname(_tf_frame),\n  parenttfname(_parent_tf_frame),\n  globaltfname(_global_tf_frame),\n  broadcast_tf(_broadcast_tf)\n{\n  assert(_l);\n  laser->lockDevice();\n  laser->addReadingCB(&laserReadingsCB);\n  laser->unlockDevice();\n  std::string laserscan_name(laser->getName());\n  boost::erase_all(laserscan_name,\".\");\n  laserscan_name += \"_laserscan\";\n  std::string pointcloud_name(laser->getName());\n  boost::erase_all(pointcloud_name,\".\");\n  pointcloud_name += \"_pointcloud\";\n  laserscan_pub = node.advertise<sensor_msgs::LaserScan>(laserscan_name, 20);\n  pointcloud_pub = node.advertise<sensor_msgs::PointCloud>(pointcloud_name, 50);\n\n  tf::Quaternion q;\n  if(laser->hasSensorPosition())\n  {\n    lasertf.setOrigin(tf::Vector3(laser->getSensorPositionX()/1000.0, laser->getSensorPositionY()/1000.0, laser->getSensorPositionZ()/1000.0));\n    q.setRPY(0, 0, ArMath::degToRad(laser->getSensorPositionTh()));\n  }\n  else\n  {\n    lasertf.setOrigin(tf::Vector3(0, 0, 0));\n    q.setRPY(0, 0, 0);\n  }\n  lasertf.setRotation(q);\n  \n\n  laserscan.header.frame_id = \"laser_frame\";\n  laserscan.angle_min = ArMath::degToRad(laser->getStartDegrees());\n  laserscan.angle_max = ArMath::degToRad(laser->getEndDegrees());\n  //laserscan.time_increment = ?\n  laserscan.range_min = 0; //laser->getMinRange() / 1000.0;\n  laserscan.range_max = laser->getMaxRange() / 1000.0;\n  pointcloud.header.frame_id = globaltfname;\n  \n  // Get angle_increment of the laser\n  laserscan.angle_increment = 0;\n  if(laser->canSetIncrement()) {\n    laserscan.angle_increment = laser->getIncrement();\n  }\n  else if(laser->getIncrementChoice() != NULL) {\n    laserscan.angle_increment = laser->getIncrementChoiceDouble();\n  }\n  assert(laserscan.angle_increment > 0);\n  laserscan.angle_increment *= M_PI/180.0;\n\n  //readingsCallbackTime = new ArTime;\n}\n\nLaserPublisher::~LaserPublisher()\n{\n  laser->lockDevice();\n  laser->remReadingCB(&laserReadingsCB);\n  laser->unlockDevice();\n  //delete readingsCallbackTime;\n}\n\nvoid LaserPublisher::readingsCB()\n{\n  //printf(\"readingsCB(): %lu ms since last readingsCB() call.\\n\", readingsCallbackTime->mSecSince());\n  assert(laser);\n  laser->lockDevice();\n  publishLaserScan();\n  publishPointCloud();\n  laser->unlockDevice();\n  if(broadcast_tf)\n    transform_broadcaster.sendTransform(tf::StampedTransform(lasertf, convertArTimeToROS(laser->getLastReadingTime()), parenttfname, tfname));\n  //readingsCallbackTime->setToNow();\n}\n\nvoid LaserPublisher::publishLaserScan()\n{\n  laserscan.header.stamp = convertArTimeToROS(laser->getLastReadingTime());\n  const std::list<ArSensorReading*> *readings = laser->getRawReadings(); \n  assert(readings);\n  //printf(\"laserscan: %lu readings\\n\", readings->size());\n  laserscan.ranges.resize(readings->size());\n  size_t n = 0;\n  if (laser->getFlipped()) {\n    // Reverse the data\n    for(std::list<ArSensorReading*>::const_reverse_iterator r = readings->rbegin(); r != readings->rend(); ++r)\n    {\n      assert(*r);\n      \n      if ((*r)->getIgnoreThisReading()) {\n\tlaserscan.ranges[n] = -1;\n      }\n      else {\n\tlaserscan.ranges[n] = (*r)->getRange() / 1000.0;\n      }\n      \n      ++n;\n    }\n  }\n  else {\n    for(std::list<ArSensorReading*>::const_iterator r = readings->begin(); r != readings->end(); ++r)\n    {\n      assert(*r);\n      \n      if ((*r)->getIgnoreThisReading()) {\n\tlaserscan.ranges[n] = -1;\n      }\n      else {\n\tlaserscan.ranges[n] = (*r)->getRange() / 1000.0;\n      }\n      \n      ++n;\n    }\n  }\n\n  laserscan_pub.publish(laserscan);\n}\n\nvoid LaserPublisher::publishPointCloud()\n{\n  assert(laser);\n  pointcloud.header.stamp = convertArTimeToROS(laser->getLastReadingTime());\n  assert(laser->getCurrentBuffer());\n  const std::list<ArPoseWithTime*> *p = laser->getCurrentRangeBuffer()->getBuffer();\n  assert(p);\n  pointcloud.points.resize(p->size());\n  size_t n = 0;\n  for(std::list<ArPoseWithTime*>::const_iterator i = p->begin(); i != p->end(); ++i)\n  {\n    assert(*i);\n    pointcloud.points[n].x = (*i)->getX() / 1000.0;\n    pointcloud.points[n].y = (*i)->getY() / 1000.0;\n    pointcloud.points[n].z = (laser->hasSensorPosition() ?  laser->getSensorPositionZ() / 1000.0 : 0.0);\n    ++n;\n  }\n  pointcloud_pub.publish(pointcloud);\n}\n  \n  \n", "meta": {"hexsha": "c66081056b585a3ef25fedfe4fa5c182f5f683d3", "size": 4828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rosaria/LaserPublisher.cpp", "max_stars_repo_name": "CogAplex/ROS2CoNA", "max_stars_repo_head_hexsha": "df97ffc06cce22fdf72cc34507695322e99be97e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-07T09:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-07T09:05:38.000Z", "max_issues_repo_path": "src/rosaria/LaserPublisher.cpp", "max_issues_repo_name": "YuJeHyeon/ROS2CoNA-1", "max_issues_repo_head_hexsha": "df97ffc06cce22fdf72cc34507695322e99be97e", "max_issues_repo_licenses": ["MIT"], "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/rosaria/LaserPublisher.cpp", "max_forks_repo_name": "YuJeHyeon/ROS2CoNA-1", "max_forks_repo_head_hexsha": "df97ffc06cce22fdf72cc34507695322e99be97e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-04T03:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T03:11:07.000Z", "avg_line_length": 29.8024691358, "max_line_length": 190, "alphanum_fraction": 0.6857912179, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1795897372717262}}
{"text": "#include <dials/array_family/flex_table.h>\n#include <dials/array_family/reflection_table.h>\n#include <boost/python.hpp>\n#include <boost/python/def.hpp>\n#include <algorithm>\n#include <numeric>\n#include <scitbx/vec3.h>\n#include <scitbx/mat3.h>\n#include <iterator>\n\nusing namespace boost::python;\nusing namespace dials::af;\n\n// Helper classes to speed up calculations in autoreduce.py\n\nnamespace dials { namespace refinement { namespace boost_python {\n  /*\n    Helper class used by the AutoReduce._panel_gp_surplus_reflections function in\n    autoreduce.py\n  */\n  struct pg_surpl_iter {\n    template <typename IntType>\n    pg_surpl_iter(const scitbx::af::shared<IntType>& ref_ids,\n                  const scitbx::af::shared<std::size_t>& panel_id,\n                  const boost::python::list pnl_ids,\n                  const scitbx::af::shared<std::size_t> exp_ids,\n                  const int cutoff) {\n      // Perform python list conversion once; improves read access\n      scitbx::af::shared<std::size_t> pnl_ids_flex;\n      for (int ii = 0; ii < len(pnl_ids); ++ii) {\n        pnl_ids_flex.push_back(boost::python::extract<std::size_t>(pnl_ids[ii]));\n      }\n\n      std::size_t count = 0;\n\n      // Work with raw pointers instead of overloadable objects\n      const std::size_t* ptr_exp_ids = exp_ids.begin();\n      const std::size_t* ptr_panel_id = panel_id.begin();\n\n      // Predefine loop variables\n      std::size_t exp_it, pnl;\n\n      std::pair<const IntType*, const IntType*> refIDRange;\n      std::pair<const std::size_t*, const std::size_t*> panelIDRange;\n      unsigned int data_offset = 0;\n      unsigned int data_range = 0;\n\n      /* Search for the beginning and end indices for the index values and track their\n         pointers. Use these pointers to narow the next search margin and count the\n         range of elements that match. These values indicate the count and can be added\n         to a running total.\n      */\n      for (exp_it = 0; exp_it < exp_ids.size();\n           ++exp_it) {  // Iterate through experiment IDs\n        // Get the pointer indices to the beginning and end of the values with the\n        // requested experimental ID. Performs search in ~2logN\n        refIDRange =\n          std::equal_range(ref_ids.begin(), ref_ids.end(), ptr_exp_ids[exp_it]);\n\n        // Calculate pointer offset for start and end of the data to examine.\n        data_range = refIDRange.second - refIDRange.first;\n        data_offset = refIDRange.first - ref_ids.begin();\n\n        // Taking the previous pointer positions, and perfoming a search within this\n        // range for the matching panel IDs, we then count the pointer range as all\n        // valid entries and add to the accumlator.\n        for (pnl = 0; pnl < pnl_ids_flex.size(); ++pnl) {  // Iterate through panel IDs\n          panelIDRange = std::equal_range(ptr_panel_id + data_offset,\n                                          ptr_panel_id + data_offset + data_range,\n                                          pnl_ids_flex[pnl]);\n          count += (unsigned int)(panelIDRange.second - panelIDRange.first);\n        }\n      }\n      result = count - cutoff;\n    }\n    int result;\n  };\n\n  /*\n    Helper class used by the AutoReduce._unit_cell_surplus_reflections function in\n    autoreduce.py\n  */\n  struct uc_surpl_iter {\n    template <typename IntType>\n    uc_surpl_iter(const scitbx::af::shared<IntType>& ref_ids,\n                  const scitbx::af::shared<cctbx::miller::index<> >& ref_miller,\n                  const scitbx::af::shared<std::size_t>& exp_ids,\n                  const scitbx::af::shared<mat3<double> > F_dbdp) {\n      // Expose pointers for experiment flex arrays\n      const std::size_t* ptr_exp_ids = exp_ids.begin();\n\n      std::size_t exp_it;  // ref_id;\n      std::vector<std::pair<const IntType*, const IntType*> > refIDRange(\n        exp_ids.size());\n\n      std::vector<unsigned int> data_range(exp_ids.size());\n      std::vector<unsigned int> data_offset(exp_ids.size());\n\n      // Perform subselection of data ranges\n      for (exp_it = 0; exp_it < exp_ids.size(); ++exp_it) {\n        refIDRange[exp_it] =\n          std::equal_range(ref_ids.begin(), ref_ids.end(), ptr_exp_ids[exp_it]);\n        data_range[exp_it] = refIDRange[exp_it].second - refIDRange[exp_it].first;\n        data_offset[exp_it] = refIDRange[exp_it].first - ref_ids.begin();\n      }\n\n      // Pre-initialise loop variables and array for storing norms\n      int ii, jj;\n      scitbx::af::shared<double> mul_norm;\n\n      // Calculate L-2 norm of Matrix*Vec operation for each matrix in F_dbdp and each\n      // vec3 miller index across all exp_ids\n      for (jj = 0; jj < F_dbdp.size(); ++jj) {\n        for (unsigned int exp_id_range = 0; exp_id_range < data_range.size();\n             ++exp_id_range) {\n          for (ii = data_offset[exp_id_range];\n               ii < data_offset[exp_id_range] + data_range[exp_id_range];\n               ++ii) {\n            vec3<double> v3(ref_miller[ii]);\n            mul_norm.push_back((F_dbdp[jj] * v3).length());\n          }\n        }\n      }\n\n      // Sum the total offsets to determine each range for splitting of mul_norm to\n      // nref param values with F_dbdp.size() number of partitions\n      int sum_offsets = std::accumulate(data_range.begin(), data_range.end(), 0);\n      scitbx::af::shared<int> nref_each_param;\n      for (ii = 0; ii < F_dbdp.size(); ++ii) {\n        // Count the number of elements greater than 0 from the L-2 norms.\n        nref_each_param.push_back(\n          std::count_if(mul_norm.begin() + ii * sum_offsets,\n                        mul_norm.begin() + (ii + 1) * sum_offsets,\n                        gtZero));\n      }\n\n      // Return the value of the smallest element\n      scitbx::af::shared<int>::iterator it =\n        std::min_element(nref_each_param.begin(), nref_each_param.end());\n      result = *(nref_each_param.begin() + std::distance(nref_each_param.begin(), it));\n    }\n    int result;\n    static bool gtZero(double x) {\n      return ((x > 0.0) == 1);\n    }  // Used for comparison operation\n  };\n\n  struct surpl_iter {\n    template <typename IntType>\n    surpl_iter(scitbx::af::shared<IntType> ref_ids,\n               const scitbx::af::shared<std::size_t> exp_ids) {\n      // Expose pointers for experiment flex arrays\n      const std::size_t* ptr_exp_ids = exp_ids.begin();\n\n      std::size_t exp_it;  // ref_id;\n      std::pair<const IntType*, const IntType*> refIDRange;\n\n      unsigned int data_count = 0;\n      result = 0;\n\n      // Perform subselection of data ranges\n      for (exp_it = 0; exp_it < exp_ids.size(); ++exp_it) {\n        refIDRange =\n          std::equal_range(ref_ids.begin(), ref_ids.end(), ptr_exp_ids[exp_it]);\n        data_count = refIDRange.second - refIDRange.first;\n        result += data_count;\n      }\n    }\n    int result;\n  };\n\n  void export_pg_surpl_iter() {\n    typedef return_value_policy<return_by_value> rbv;\n    // templated constructor for int and size_t flex arrays of id\n    class_<dials::refinement::boost_python::pg_surpl_iter>(\"pg_surpl_iter\", no_init)\n      .def(init<scitbx::af::shared<std::size_t>,\n                const scitbx::af::shared<std::size_t>,\n                const boost::python::list,\n                const scitbx::af::shared<std::size_t>,\n                const int>((boost::python::arg(\"ref_ids\"),\n                            boost::python::arg(\"panel_id\"),\n                            boost::python::arg(\"pnl_ids\"),\n                            boost::python::arg(\"exp_ids\"),\n                            boost::python::arg(\"cutoff\"))))\n      .def(init<scitbx::af::shared<int>,\n                const scitbx::af::shared<std::size_t>,\n                const boost::python::list,\n                const scitbx::af::shared<std::size_t>,\n                const int>((boost::python::arg(\"ref_ids\"),\n                            boost::python::arg(\"panel_id\"),\n                            boost::python::arg(\"pnl_ids\"),\n                            boost::python::arg(\"exp_ids\"),\n                            boost::python::arg(\"cutoff\"))))\n      .add_property(\n        \"result\",\n        make_getter(&dials::refinement::boost_python::pg_surpl_iter::result, rbv()));\n  }\n\n  void export_uc_surpl_iter() {\n    typedef return_value_policy<return_by_value> rbv;\n    class_<dials::refinement::boost_python::uc_surpl_iter>(\"uc_surpl_iter\", no_init)\n      .def(init<const scitbx::af::shared<std::size_t>,\n                const scitbx::af::shared<cctbx::miller::index<> >,\n                const scitbx::af::shared<std::size_t>,\n                const scitbx::af::shared<mat3<double> > >(\n        (boost::python::arg(\"ref_ids\"),\n         boost::python::arg(\"ref_miller\"),\n         boost::python::arg(\"exp_ids\"),\n         boost::python::arg(\"F_dbdp\"))))\n      .def(init<const scitbx::af::shared<int>,\n                const scitbx::af::shared<cctbx::miller::index<> >,\n                const scitbx::af::shared<std::size_t>,\n                const scitbx::af::shared<mat3<double> > >(\n        (boost::python::arg(\"ref_ids\"),\n         boost::python::arg(\"ref_miller\"),\n         boost::python::arg(\"exp_ids\"),\n         boost::python::arg(\"F_dbdp\"))))\n      .add_property(\n        \"result\",\n        make_getter(&dials::refinement::boost_python::uc_surpl_iter::result, rbv()));\n  }\n\n  void export_surpl_iter() {\n    typedef return_value_policy<return_by_value> rbv;\n    class_<dials::refinement::boost_python::surpl_iter>(\"surpl_iter\", no_init)\n      .def(\n        init<scitbx::af::shared<std::size_t>, const scitbx::af::shared<std::size_t> >(\n          (boost::python::arg(\"ref_ids\"), boost::python::arg(\"exp_ids\"))))\n      .def(init<scitbx::af::shared<int>, const scitbx::af::shared<std::size_t> >(\n        (boost::python::arg(\"ref_ids\"), boost::python::arg(\"exp_ids\"))))\n      .add_property(\n        \"result\",\n        make_getter(&dials::refinement::boost_python::surpl_iter::result, rbv()));\n  }\n}}}  // namespace dials::refinement::boost_python\n", "meta": {"hexsha": "6fcc03ec96aad8739f802bbcafcf5a62776fb15c", "size": 9938, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/dials/algorithms/refinement/boost_python/autoreduce_helpers.cc", "max_stars_repo_name": "jorgediazjr/dials-dev20191018", "max_stars_repo_head_hexsha": "77d66c719b5746f37af51ad593e2941ed6fbba17", "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/dials/algorithms/refinement/boost_python/autoreduce_helpers.cc", "max_issues_repo_name": "jorgediazjr/dials-dev20191018", "max_issues_repo_head_hexsha": "77d66c719b5746f37af51ad593e2941ed6fbba17", "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/dials/algorithms/refinement/boost_python/autoreduce_helpers.cc", "max_forks_repo_name": "jorgediazjr/dials-dev20191018", "max_forks_repo_head_hexsha": "77d66c719b5746f37af51ad593e2941ed6fbba17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T15:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T15:39:06.000Z", "avg_line_length": 42.1101694915, "max_line_length": 87, "alphanum_fraction": 0.6072650433, "num_tokens": 2500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.1795897301862506}}
{"text": "/*\n *  Copyright (C) 2018 Naomasa Matsubayashi\n *  Licensed under MIT license, see file LICENSE in this source tree.\n */\n#ifndef UWG_TYPES_HPP\n#define UWG_TYPES_HPP\n#include <functional>\n#include <memory>\n#include <boost/container/static_vector.hpp>\n#include <boost/container/flat_map.hpp>\n#include <boost/asio.hpp>\n#include <boost/asio/system_timer.hpp>\n#include <uwg/defs.hpp>\n#include <uwg/peer_identifier.hpp>\n#include <uwg/window.hpp>\n\nnamespace uwg {\n  enum class result_t {\n    OK,\n    FORBIDDEN,\n    DISCONNECTED,\n    NOT_IMPLEMENTED\n  };\n  using wg_key_type = boost::container::static_vector< unsigned char, wg_key_len >;\n  using wg_tai64n_type = boost::container::static_vector< unsigned char, wg_tai64n_len >;\n  using timer_type = boost::asio::system_timer;\n  using kxcb_type = std::function< void( result_t ) >;\n  struct kx_state {\n    kx_state( boost::asio::io_service &ios ) : timer( new timer_type( ios ) ), cb( []( result_t ){} ) {}\n    wg_key_type self_ephemeral_private;\n    wg_key_type self_ephemeral_public;\n    wg_key_type chain_key;\n    wg_key_type hash_key;\n    wg_key_type cookie;\n    wg_key_type mac1;\n    std::shared_ptr< timer_type > timer;\n    kxcb_type cb;\n  };\n  using kx_states = boost::container::flat_map< peer_identifier, kx_state >;\n  struct responder_state {\n    responder_state() : cookie_since( 0 ) {}\n    wg_key_type cookie;\n    time_t cookie_since;\n  };\n  using responder_states = boost::container::flat_map< peer_identifier, responder_state >;\n  struct key_state {\n    key_state() : since( 0 ), tx_count( 0 ) {}\n    key_state( boost::asio::io_service &ios ) : timer( new timer_type( ios ) ), since( 0 ), tx_count( 0 ) {}\n    wg_key_type send_key;\n    wg_key_type receive_key;\n    std::shared_ptr< timer_type > timer;\n    time_t since;\n    size_t tx_count;\n    uint32_t remote_kxid;\n    window_state window;\n  };\n  using key_ring_t = boost::container::flat_map< peer_identifier, std::shared_ptr< key_state > >;\n  struct peer_state {\n    peer_state() : timestamp( wg_tai64n_len, 0 ) {}\n    peer_state( const wg_tai64n_type &ts ) : timestamp( ts.begin(), ts.end() ) {}\n    wg_tai64n_type timestamp;\n  };\n  struct key_comp {\n    bool operator()( const wg_key_type &l, const  wg_key_type &r ) const {\n      const auto min_size = std::min( l.size(), r.size() );\n      const auto data_diff = memcmp( l.data(), r.data(), min_size );\n      if( data_diff == 0 ) return l.size() < r.size();\n      else return data_diff < 0;\n    }\n  };\n  using peer_states = boost::container::flat_map< wg_key_type, peer_state, key_comp >;\n}\n\n#endif\n", "meta": {"hexsha": "b67630259e5920b937a31e9d64116c76928416d3", "size": 2562, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uwg/types.hpp", "max_stars_repo_name": "Fadis/userspace_wireguard", "max_stars_repo_head_hexsha": "13daa4759c4d96d0e9a112d8c35f680681a6687d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-07-21T04:46:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T06:04:32.000Z", "max_issues_repo_path": "include/uwg/types.hpp", "max_issues_repo_name": "Fadis/userspace_wireguard", "max_issues_repo_head_hexsha": "13daa4759c4d96d0e9a112d8c35f680681a6687d", "max_issues_repo_licenses": ["MIT"], "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/uwg/types.hpp", "max_forks_repo_name": "Fadis/userspace_wireguard", "max_forks_repo_head_hexsha": "13daa4759c4d96d0e9a112d8c35f680681a6687d", "max_forks_repo_licenses": ["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.16, "max_line_length": 108, "alphanum_fraction": 0.6924277908, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17928954658066912}}
{"text": "#include <boost/archive/iterators/base64_from_binary.hpp>\n#include <boost/archive/iterators/binary_from_base64.hpp>\n#include <boost/archive/iterators/ostream_iterator.hpp>\n#include <boost/archive/iterators/transform_width.hpp>\n\n#include <elle/Exception.hh>\n#include <elle/assert.hh>\n#include <elle/format/base64.hh>\n#include <elle/log.hh>\n\nELLE_LOG_COMPONENT(\"elle.format.base64\")\n\nnamespace elle\n{\n  namespace format\n  {\n    namespace base64\n    {\n      using namespace boost::archive::iterators;\n\n      size_t\n      encoded_size(ConstWeakBuffer input)\n      {\n        return (signed(input.size()) + 2) / 3 * 4;\n      }\n\n      Buffer\n      encode(ConstWeakBuffer input)\n      {\n        ELLE_TRACE_SCOPE(\"encode %s\", input);\n        size_t size = encoded_size(input);\n        ELLE_DEBUG(\"previsional size: %s\", size);\n        Buffer res;\n        res.capacity(size);\n        IOStream stream(res.ostreambuf());\n        Stream base64_stream(stream);\n        base64_stream.write(reinterpret_cast<char const*>(input.contents()),\n                            input.size());\n        return res;\n      }\n\n      size_t\n      decoded_size(ConstWeakBuffer encoded)\n      {\n        size_t size = encoded.size();\n        int padding = 0;\n        if (size >= 1 && encoded.contents()[size - 1] == '=')\n          ++padding;\n        if (size >= 2 && encoded.contents()[size - 2] == '=')\n          ++padding;\n        return size / 4 * 3 - padding;\n      }\n\n      Buffer\n      decode(ConstWeakBuffer input)\n      {\n        ELLE_TRACE_SCOPE(\"decode %s\", input);\n        size_t size = decoded_size(input);\n        ELLE_DEBUG(\"previsional size: %s\", size);\n        Buffer res(size);\n        IOStream stream(input.istreambuf());\n        Stream base64_stream(stream);\n        base64_stream.read(reinterpret_cast<char*>(res.mutable_contents()),\n                           size);\n        ELLE_ASSERT_EQ(base64_stream.gcount(), signed(size));\n        ELLE_ASSERT(\n          (base64_stream.read(reinterpret_cast<char*>(\n                                res.mutable_contents()), 1),\n           base64_stream.gcount() == 0));\n\n        return res;\n      }\n\n      using encoder = base64_from_binary<transform_width<const char *, 6, 8>>;\n      template <typename SourceIterator, typename DestinationIterator>\n      void\n      _stream_encode(SourceIterator begin,\n                     SourceIterator end,\n                     DestinationIterator output)\n      {\n        std::copy(encoder(begin), encoder(end), output);\n      }\n\n      using decoder = transform_width<binary_from_base64<char const *>, 8, 6>;\n      template <typename SourceIterator, typename DestinationIterator>\n      void\n      _stream_decode(SourceIterator begin,\n                     SourceIterator end,\n                     DestinationIterator output)\n      {\n        std::copy(decoder(begin), decoder(end), output);\n      }\n\n      /*-------------.\n      | Construction |\n      `-------------*/\n\n      StreamBuffer::StreamBuffer(std::iostream& stream):\n        _stream(stream),\n        _remaining_write(0),\n        _remaining_read(0)\n      {}\n\n      /*-------.\n      | Buffer |\n      `-------*/\n\n      WeakBuffer\n      StreamBuffer::read_buffer()\n      {\n        static auto const size = sizeof(this->_buffer_read) / 3 * 4;\n        ELLE_TRACE_SCOPE(\"%s: decode up to %s bytes\", *this, size);\n        char buffer[size];\n        size_t read;\n        ELLE_DEBUG(\"%s: read up to %s bytes from the backend\", *this, size)\n        {\n          this->_stream.read(buffer, size);\n          read = this->_stream.gcount();\n          ELLE_DUMP(\"%s: got %s bytes\", *this, read);\n          if (read > 0)\n            ELLE_DUMP(\"%s: encoded data: %s\", *this,\n                      elle::WeakBuffer(buffer, read));\n        }\n        this->_remaining_read = read % 4;\n        read = read - this->_remaining_read;\n        size_t decoded_size = read / 4 * 3;\n        if (read > 0)\n        {\n          ELLE_DEBUG_SCOPE(\"%s: decode %s bytes\", *this, read);\n          bool end = buffer[read - 1] == '=';\n          if (end)\n          {\n            read -= 4;\n            decoded_size -= 3;\n          }\n          _stream_decode(buffer, buffer + read, this->_buffer_read);\n          if (end)\n          {\n            ELLE_DEBUG_SCOPE(\"%s: decode last 4 bytes with padding\", *this);\n            ELLE_DUMP(\"%s: remaining bytes: \\\"%s\\\"\", *this,\n                      std::string(buffer + read, 4));\n            auto source = decoder(buffer + read);\n            auto destination = this->_buffer_read + (read / 4 * 3);\n            if (buffer[read + 2] != '=')\n            {\n              *(destination++) = *(source++);\n              ++decoded_size;\n            }\n            *(destination++) = *(source++);\n            ++decoded_size;\n          }\n          if (decoded_size > 0)\n            ELLE_DUMP(\"%s: decoded data: %s\", *this,\n                      elle::WeakBuffer(this->_buffer_read, decoded_size));\n        }\n        if (this->_remaining_read > 0)\n        {\n          ELLE_DEBUG_SCOPE(\"%s: store %s remaining bytes\",\n                           *this, this->_remaining_read);\n        }\n        return WeakBuffer(this->_buffer_read, decoded_size);\n      }\n\n      WeakBuffer\n      StreamBuffer::write_buffer()\n      {\n        return WeakBuffer(this->_buffer_write + this->_remaining_write,\n                          sizeof(_buffer_write) - this->_remaining_write);\n      }\n\n      void\n      StreamBuffer::flush(Size size)\n      {\n        size += this->_remaining_write;\n        ELLE_TRACE_SCOPE(\"%s: encode %s bytes\", *this, size);\n        this->_remaining_write = size % 3;\n        size = size - size % 3;\n        if (size > 0)\n        {\n          ELLE_DEBUG_SCOPE(\"%s: encode %s bytes to the backend\",\n                           *this, size);\n          _stream_encode(this->_buffer_write,\n                         this->_buffer_write + size,\n                         std::ostreambuf_iterator<char>(_stream));\n        }\n        if (size && this->_remaining_write > 0)\n        {\n          ELLE_DEBUG_SCOPE(\"%s: push back %s bytes in the buffer\",\n                           *this, this->_remaining_write);\n          memcpy(this->_buffer_write,\n                 this->_buffer_write + size,\n                 this->_remaining_write);\n        }\n      }\n\n      void\n      StreamBuffer::finalize()\n      {\n        if (this->_remaining_write > 0)\n        {\n          ELLE_DEBUG_SCOPE(\"%s: encode last %s remaining bytes\",\n                           *this, this->_remaining_write);\n          ELLE_ASSERT_LT(this->_remaining_write, 3);\n          _stream_encode(\n            this->_buffer_write,\n            this->_buffer_write + this->_remaining_write,\n            std::ostreambuf_iterator<char>(this->_stream));\n          switch (this->_remaining_write)\n          {\n            case 1:\n              this->_stream << \"==\";\n              break;\n            case 2:\n              this->_stream << \"=\";\n              break;\n            default:\n              elle::unreachable();\n          }\n        }\n      }\n\n      /*----------.\n      | Printable |\n      `----------*/\n\n      void\n      StreamBuffer::print(std::ostream& output) const\n      {\n        output << \"base64::StreamBuffer\";\n      }\n\n      Stream::Stream(std::iostream& underlying):\n        IOStream(this->_buffer = new StreamBuffer(underlying)),\n        _underlying(underlying)\n      {}\n\n      Stream::~Stream()\n      {\n        ELLE_TRACE_SCOPE(\"%s: finalize encoding\", *this->_buffer);\n        this->_buffer->sync();\n        this->_buffer->finalize();\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "216c9cdfa2c8a3f0818f996ddba92d1ddc8ea9f3", "size": 7531, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/elle/format/base64.cc", "max_stars_repo_name": "infinitio/elle", "max_stars_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 124.0, "max_stars_repo_stars_event_min_datetime": "2017-06-22T19:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T21:36:37.000Z", "max_issues_repo_path": "src/elle/format/base64.cc", "max_issues_repo_name": "infinitio/elle", "max_issues_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T15:57:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-10T02:52:35.000Z", "max_forks_repo_path": "src/elle/format/base64.cc", "max_forks_repo_name": "infinitio/elle", "max_forks_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-29T09:15:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-31T12:39:52.000Z", "avg_line_length": 30.6138211382, "max_line_length": 78, "alphanum_fraction": 0.5237020316, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.17928954308140627}}
{"text": "#pragma once\n\n#include <DXFeed.h>\n#include <fmt/format.h>\n\n#include <algorithm>\n#include <boost/multi_index/identity.hpp>\n#include <boost/multi_index/member.hpp>\n#include <boost/multi_index/ordered_index.hpp>\n#include <boost/multi_index/random_access_index.hpp>\n#include <boost/multi_index_container.hpp>\n#include <cassert>\n#include <cmath>\n#include <deque>\n#include <functional>\n#include <limits>\n#include <memory>\n#include <mutex>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"StringConverter.hpp\"\n\nnamespace dxf {\n\nstruct OrderData {\n  dxf_long_t index = 0;\n  double price = std::numeric_limits<double>::quiet_NaN();\n  double size = std::numeric_limits<double>::quiet_NaN();\n  dxf_long_t time = 0;\n  dxf_order_side_t side = dxf_osd_undefined;\n};\n\nstruct PriceLevel {\n  double price = std::numeric_limits<double>::quiet_NaN();\n  double size = std::numeric_limits<double>::quiet_NaN();\n  std::int64_t time = 0;\n\n  friend bool operator<(const PriceLevel& a, const PriceLevel& b) {\n    if (std::isnan(b.price)) return true;\n    if (std::isnan(a.price)) return false;\n\n    return a.price < b.price;\n  }\n};\n\nstruct PriceLevelChanges {\n  std::vector<PriceLevel> asks{};\n  std::vector<PriceLevel> bids{};\n};\n\nstruct PriceLevelChangesSet {\n  PriceLevelChanges additions{};\n  PriceLevelChanges updates{};\n  PriceLevelChanges removals{};\n};\n\nnamespace bmi = boost::multi_index;\n\nusing PriceLevelContainer = bmi::multi_index_container<\n  PriceLevel,\n  bmi::indexed_by<bmi::random_access<>, bmi::ordered_unique<bmi::member<PriceLevel, double, &PriceLevel::price>>>>;\n\nclass PriceLevelBook final {\n  dxf_snapshot_t snapshot_;\n  std::string symbol_;\n  std::string source_;\n  std::size_t levelsNumber_;\n  PriceLevelContainer asks_;\n  PriceLevelContainer bids_;\n  std::unordered_map<dxf_long_t, OrderData> orderDataSnapshot_;\n  bool isValid_;\n  std::mutex mutex_;\n\n  std::function<void(const PriceLevelChanges&)> onNewBook_;\n  std::function<void(const PriceLevelChanges&)> onBookUpdate_;\n  std::function<void(const PriceLevelChangesSet&)> onIncrementalChange_;\n\n  static bool isZeroPriceLevel(const PriceLevel& pl) {\n    return std::abs(pl.size) < std::numeric_limits<double>::epsilon();\n  };\n\n  static bool areEqualPrices(double price1, double price2) {\n    return std::abs(price1 - price2) < std::numeric_limits<double>::epsilon();\n  }\n\n  PriceLevelBook(std::string symbol, std::string source, std::size_t levelsNumber = 0)\n      : snapshot_{nullptr},\n        symbol_{std::move(symbol)},\n        source_{std::move(source)},\n        levelsNumber_{levelsNumber},\n        asks_{},\n        bids_{},\n        orderDataSnapshot_{},\n        isValid_{false},\n        mutex_{} {}\n\n  // Process the tx\\snapshot data, converts it to PL changes. Also, changes the orderDataSnapshot_\n  PriceLevelChanges convertToUpdates(const dxf_snapshot_data_ptr_t snapshotData) {\n    assert(snapshotData->records_count != 0);\n    assert(snapshotData->event_type != dx_eid_order);\n\n    std::set<PriceLevel> askUpdates{};\n    std::set<PriceLevel> bidUpdates{};\n\n    auto orders = reinterpret_cast<const dxf_order_t*>(snapshotData->records);\n\n    auto isOrderRemoval = [](const dxf_order_t& o) {\n      return (o.event_flags & dxf_ef_remove_event) != 0 || o.size == 0 || std::isnan(o.size);\n    };\n\n    auto processOrderAddition = [&bidUpdates, &askUpdates](const dxf_order_t& order) {\n      auto& updatesSide = order.side == dxf_osd_buy ? bidUpdates : askUpdates;\n      auto priceLevelChange = PriceLevel{order.price, order.size, order.time};\n      auto foundPriceLevel = updatesSide.find(priceLevelChange);\n\n      if (foundPriceLevel != updatesSide.end()) {\n        priceLevelChange.size = foundPriceLevel->size + priceLevelChange.size;\n        updatesSide.erase(foundPriceLevel);\n      }\n\n      updatesSide.insert(priceLevelChange);\n    };\n\n    auto processOrderRemoval = [&bidUpdates, &askUpdates](const dxf_order_t& order, const OrderData& foundOrderData) {\n      auto& updatesSide = foundOrderData.side == dxf_osd_buy ? bidUpdates : askUpdates;\n      auto priceLevelChange = PriceLevel{foundOrderData.price, -foundOrderData.size, order.time};\n      auto foundPriceLevel = updatesSide.find(priceLevelChange);\n\n      if (foundPriceLevel != updatesSide.end()) {\n        priceLevelChange.size = foundPriceLevel->size + priceLevelChange.size;\n        updatesSide.erase(foundPriceLevel);\n      }\n\n      if (!isZeroPriceLevel(priceLevelChange)) {\n        updatesSide.insert(priceLevelChange);\n      }\n    };\n\n    for (std::size_t i = 0; i < snapshotData->records_count; i++) {\n      auto order = orders[i];\n\n      fmt::print(\"O:ind={},pr={},sz={},sd={}\\n\", order.index, order.price, order.size,\n                 order.side == dxf_osd_buy ? \"buy\" : \"sell\");\n\n      auto removal = isOrderRemoval(order);\n      auto foundOrderDataIt = orderDataSnapshot_.find(order.index);\n\n      if (foundOrderDataIt == orderDataSnapshot_.end()) {\n        if (removal) {\n          continue;\n        }\n\n        processOrderAddition(order);\n        orderDataSnapshot_[order.index] = OrderData{order.index, order.price, order.size, order.time, order.side};\n      } else {\n        const auto& foundOrderData = foundOrderDataIt->second;\n\n        if (removal) {\n          processOrderRemoval(order, foundOrderData);\n          orderDataSnapshot_.erase(foundOrderData.index);\n        } else {\n          if (order.side != foundOrderData.side) {\n            processOrderRemoval(order, foundOrderData);\n          }\n\n          processOrderAddition(order);\n          orderDataSnapshot_[foundOrderData.index] =\n            OrderData{order.index, order.price, order.size, order.time, order.side};\n        }\n      }\n    }\n\n    return {std::vector<PriceLevel>{askUpdates.begin(), askUpdates.end()},\n            std::vector<PriceLevel>{bidUpdates.rbegin(), bidUpdates.rend()}};\n  }\n\n  // TODO: price levels number\n  PriceLevelChangesSet applyUpdates(const PriceLevelChanges& priceLevelUpdates) {\n    PriceLevelChanges additions{};\n    PriceLevelChanges updates{};\n    PriceLevelChanges removals{};\n\n    // We generate lists of additions, updates, removals\n    for (const auto& updateAsk : priceLevelUpdates.asks) {\n      auto found = std::lower_bound(asks_.begin(), asks_.end(), updateAsk);\n\n      if (found == asks_.end() || !areEqualPrices(found->price, updateAsk.price)) {\n        additions.asks.push_back(updateAsk);\n      } else {\n        auto newPriceLevelChange = *found;\n\n        newPriceLevelChange.size += updateAsk.size;\n        newPriceLevelChange.time = updateAsk.time;\n\n        if (isZeroPriceLevel(newPriceLevelChange)) {\n          removals.asks.push_back(*found);\n        } else {\n          updates.asks.push_back(newPriceLevelChange);\n        }\n      }\n    }\n\n    for (const auto& updateBid : priceLevelUpdates.bids) {\n      auto found = std::lower_bound(bids_.begin(), bids_.end(), updateBid);\n\n      if (found == bids_.end() || !areEqualPrices(found->price, updateBid.price)) {\n        additions.bids.push_back(updateBid);\n      } else {\n        auto newPriceLevelChange = *found;\n\n        newPriceLevelChange.size += updateBid.size;\n        newPriceLevelChange.time = updateBid.time;\n\n        if (isZeroPriceLevel(newPriceLevelChange)) {\n          removals.bids.push_back(*found);\n        } else {\n          updates.bids.push_back(newPriceLevelChange);\n        }\n      }\n    }\n\n    std::set<PriceLevel> askRemovals{};\n    std::set<PriceLevel> bidRemovals{};\n    std::set<PriceLevel> askAdditions{};\n    std::set<PriceLevel> bidAdditions{};\n    std::set<PriceLevel> askUpdates{};\n    std::set<PriceLevel> bidUpdates{};\n\n    for (const auto& askRemoval : removals.asks) {\n      if (asks_.empty()) continue;\n\n      // Determine what will be the removal given the number of price levels.\n      if (levelsNumber_ == 0 || asks_.size() <= levelsNumber_ || askRemoval.price < asks_[levelsNumber_].price) {\n        askRemovals.insert(askRemoval);\n      }\n\n      // Determine what will be the shift in price levels after removal.\n      if (levelsNumber_ != 0 && asks_.size() > levelsNumber_ && askRemoval.price < asks_[levelsNumber_].price) {\n        askAdditions.insert(asks_[levelsNumber_]);\n      }\n\n      // remove price level by price\n      asks_.get<1>().erase(askRemoval.price);\n    }\n\n    for (const auto& askAddition : additions.asks) {\n      // We determine what will be the addition of the price level, taking into account the possible quantity.\n      if (levelsNumber_ == 0 || asks_.size() < levelsNumber_ || askAddition.price < asks_[levelsNumber_ - 1].price) {\n        askAdditions.insert(askAddition);\n      }\n\n      // We determine what will be the shift after adding\n      if (levelsNumber_ != 0 && asks_.size() >= levelsNumber_ && askAddition.price < asks_[levelsNumber_ - 1].price) {\n        const auto& toRemove = asks_[levelsNumber_ - 1];\n\n        // We take into account the possibility that the previously added price level will be deleted.\n        if (askAdditions.contains(toRemove)) {\n          askAdditions.erase(toRemove);\n        } else {\n          askRemovals.insert(toRemove);\n        }\n      }\n\n      asks_.get<1>().insert(askAddition);\n    }\n\n    for (const auto& askUpdate : updates.asks) {\n      if (levelsNumber_ == 0 || asks_.get<1>().count(askUpdate.price) > 0) {\n        askUpdates.insert(askUpdate);\n      }\n\n      asks_.get<1>().erase(askUpdate.price);\n      asks_.get<1>().insert(askUpdate);\n    }\n\n    for (const auto& bidRemoval : removals.bids) {\n      if (bids_.empty()) continue;\n\n      // Determine what will be the removal given the number of price levels.\n      if (levelsNumber_ == 0 || bids_.size() <= levelsNumber_ ||\n          bidRemoval.price > bids_[bids_.size() - 1 - levelsNumber_].price) {\n        bidRemovals.insert(bidRemoval);\n      }\n\n      // Determine what will be the shift in price levels after removal.\n      if (levelsNumber_ != 0 && bids_.size() > levelsNumber_ &&\n          bidRemoval.price > bids_[bids_.size() - 1 - levelsNumber_].price) {\n        bidAdditions.insert(bids_[bids_.size() - 1 - levelsNumber_]);\n      }\n\n      // remove price level by price\n      bids_.get<1>().erase(bidRemoval.price);\n    }\n\n    for (const auto& bidAddition : additions.bids) {\n      // We determine what will be the addition of the price level, taking into account the possible quantity.\n      if (levelsNumber_ == 0 || bids_.size() < levelsNumber_ ||\n          bidAddition.price > bids_[bids_.size() - levelsNumber_].price) {\n        bidAdditions.insert(bidAddition);\n      }\n\n      // We determine what will be the shift after adding\n      if (levelsNumber_ != 0 && bids_.size() >= levelsNumber_ &&\n          bidAddition.price > bids_[bids_.size() - levelsNumber_].price) {\n        const auto& toRemove = bids_[bids_.size() - levelsNumber_];\n\n        // We take into account the possibility that the previously added price level will be deleted.\n        if (bidAdditions.contains(toRemove)) {\n          bidAdditions.erase(toRemove);\n        } else {\n          bidRemovals.insert(toRemove);\n        }\n      }\n\n      bids_.get<1>().insert(bidAddition);\n    }\n\n    for (const auto& bidUpdate : updates.bids) {\n      if (levelsNumber_ == 0 || bids_.get<1>().count(bidUpdate.price) > 0) {\n        bidUpdates.insert(bidUpdate);\n      }\n\n      bids_.get<1>().erase(bidUpdate.price);\n      bids_.get<1>().insert(bidUpdate);\n    }\n\n    return {PriceLevelChanges{std::vector<PriceLevel>{askAdditions.begin(), askAdditions.end()},\n                              std::vector<PriceLevel>{bidAdditions.rbegin(), bidAdditions.rend()}},\n            PriceLevelChanges{std::vector<PriceLevel>{askUpdates.begin(), askUpdates.end()},\n                              std::vector<PriceLevel>{bidUpdates.rbegin(), bidUpdates.rend()}},\n            PriceLevelChanges{std::vector<PriceLevel>{askRemovals.begin(), askRemovals.end()},\n                              std::vector<PriceLevel>{bidRemovals.rbegin(), bidRemovals.rend()}}};\n  }\n\n  [[nodiscard]] std::vector<PriceLevel> getAsks() const {\n    return {asks_.begin(),\n            (levelsNumber_ == 0 || asks_.size() <= levelsNumber_) ? asks_.end() : asks_.begin() + levelsNumber_};\n  }\n\n  [[nodiscard]] std::vector<PriceLevel> getBids() const {\n    return {bids_.rbegin(),\n            (levelsNumber_ == 0 || bids_.size() <= levelsNumber_) ? bids_.rend() : bids_.rbegin() + levelsNumber_};\n  }\n\n public:\n  // TODO: move to another thread\n  void processSnapshotData(const dxf_snapshot_data_ptr_t snapshotData, int newSnapshot) {\n    std::lock_guard<std::mutex> lk(mutex_);\n\n    auto newSnap = newSnapshot != 0;\n\n    if (newSnap) {\n      asks_.clear();\n      bids_.clear();\n      orderDataSnapshot_.clear();\n    }\n\n    if (snapshotData->records_count == 0) {\n      if (newSnap && onNewBook_) {\n        onNewBook_({});\n      }\n\n      return;\n    }\n\n    auto updates = convertToUpdates(snapshotData);\n    auto resultingChangesSet = applyUpdates(updates);\n\n    if (newSnap) {\n      if (onNewBook_) {\n        onNewBook_(PriceLevelChanges{getAsks(), getBids()});\n      }\n    } else {\n      if (onIncrementalChange_) {\n        onIncrementalChange_(resultingChangesSet);\n      }\n\n      if (onBookUpdate_) {\n        onBookUpdate_(PriceLevelChanges{getAsks(), getBids()});\n      }\n    }\n  }\n\n  ~PriceLevelBook() {\n    if (isValid_) {\n      dxf_close_price_level_book(snapshot_);\n    }\n  }\n\n  static std::unique_ptr<PriceLevelBook> create(dxf_connection_t connection, const std::string& symbol,\n                                                const std::string& source, std::size_t levelsNumber) {\n    auto plb = std::unique_ptr<PriceLevelBook>(new PriceLevelBook(symbol, source, levelsNumber));\n    auto wSymbol = StringConverter::utf8ToWString(symbol);\n    dxf_snapshot_t snapshot = nullptr;\n\n    dxf_create_order_snapshot(connection, wSymbol.c_str(), source.c_str(), 0, &snapshot);\n\n    dxf_attach_snapshot_inc_listener(\n      snapshot,\n      [](const dxf_snapshot_data_ptr_t snapshot_data, int new_snapshot, void* user_data) {\n        static_cast<PriceLevelBook*>(user_data)->processSnapshotData(snapshot_data, new_snapshot);\n      },\n      plb.get());\n    plb->isValid_ = true;\n\n    return plb;\n  }\n\n  void setOnNewBook(std::function<void(const PriceLevelChanges&)> onNewBookHandler) {\n    onNewBook_ = std::move(onNewBookHandler);\n  }\n\n  void setOnBookUpdate(std::function<void(const PriceLevelChanges&)> onBookUpdateHandler) {\n    onBookUpdate_ = std::move(onBookUpdateHandler);\n  }\n\n  void setOnIncrementalChange(std::function<void(const PriceLevelChangesSet&)> onIncrementalChangeHandler) {\n    onIncrementalChange_ = std::move(onIncrementalChangeHandler);\n  }\n};\n\n}  // namespace dxf", "meta": {"hexsha": "baadbeeeb937a3e0227a74d978a99031937bba2e", "size": 14629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dxfeed-cxx-api/PriceLevelBook.hpp", "max_stars_repo_name": "ttldtor/dxfeed-c-api-test-tools", "max_stars_repo_head_hexsha": "e137188dc12a5f25c3d014b2cde3774256496e90", "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": "dxfeed-cxx-api/PriceLevelBook.hpp", "max_issues_repo_name": "ttldtor/dxfeed-c-api-test-tools", "max_issues_repo_head_hexsha": "e137188dc12a5f25c3d014b2cde3774256496e90", "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": "dxfeed-cxx-api/PriceLevelBook.hpp", "max_forks_repo_name": "ttldtor/dxfeed-c-api-test-tools", "max_forks_repo_head_hexsha": "e137188dc12a5f25c3d014b2cde3774256496e90", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-19T10:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T10:05:22.000Z", "avg_line_length": 34.4211764706, "max_line_length": 118, "alphanum_fraction": 0.6603322168, "num_tokens": 3633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.17927717104487445}}
{"text": "#include \"stdafx.h\"\n#include \"BodyGraph.h\"\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/log/trivial.hpp>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n#undef _USE_MATH_DEFINES\n\n#include \"nsvr_core_errors.h\"\n\n\n\nconst segment_range segment_range::full = { 0, 1 };\nconst segment_range segment_range::lower_half = { 0, 0.5 };\nconst segment_range segment_range::upper_half = { 0.5, 1.0 };\n\nconst angle_range angle_range::full = { 0, 360 };\nconst angle_range angle_range::left_half = { 180, 360 };\nconst angle_range angle_range::right_half = { 0, 180 };\nconst angle_range angle_range::front_half = { 270, 90 };\nconst angle_range angle_range::back_half = { 90, 270 };\n\nBodyGraph::BodyGraph()\n{\n\tusing region = subregion::shared_region;\n\n\tauto entire_torso = std::shared_ptr<subregion>(new \n\t\tsubregion(region::identifier_torso, segment_range::full, angle_range::full, {\n\t\t\tsubregion(region::identifier_torso_front, segment_range::full, angle_range::front_half,{\n\t\t\t\tsubregion(region::identifier_chest_left,  segment_range{ 0.8, 1.0 }, angle_range{ 340, 360 }),\n\t\t\t\tsubregion(region::identifier_middle_sternum, segment_range{0.45, 0.55}, angle_range{355, 5}),\n\t\t\t\tsubregion(region::identifier_upper_ab_left,  segment_range{ 0.6, 0.8 }, angle_range{ 340, 360 }),\n\t\t\t\tsubregion(region::identifier_middle_ab_left, segment_range{ 0.4, 0.6 }, angle_range{ 340, 360 }),\n\t\t\t\tsubregion(region::identifier_lower_ab_left,  segment_range{ 0.0, 0.4 }, angle_range{ 340, 360 }),\n\t\t\t\tsubregion(region::identifier_chest_right, segment_range{ 0.8, 1.0 }, angle_range{ 0, 20 }),\n\t\t\t\tsubregion(region::identifier_upper_ab_right, segment_range{ 0.6, 0.8 }, angle_range{ 0, 20 }),\n\t\t\t\tsubregion(region::identifier_middle_ab_right, segment_range{ 0.4, 0.6 }, angle_range{ 0, 20 }),\n\t\t\t\tsubregion(region::identifier_lower_ab_right, segment_range{ 0.0, 0.4 }, angle_range{ 0, 20 })\n\t\t\t}),\n\t\t\tsubregion(region::identifier_torso_back, segment_range::full, angle_range::back_half,{\n\t\t\t\tsubregion(region::identifier_upper_back_left,  segment_range{ 0.5, 1.0 }, angle_range{ 180, 270 }),\n\t\t\t\tsubregion(region::identifier_upper_back_right,  segment_range{ 0.5, 1.0 }, angle_range{ 90, 180 })\n\t\t\t}),\n\t\t\tsubregion(region::identifier_torso_left, segment_range::full, angle_range::left_half),\n\t\t\tsubregion(region::identifier_torso_right, segment_range::full, angle_range::right_half)\n\t}));\n\n\n\tauto upper_arm_left = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_upper_arm_left, segment_range::full, angle_range::full, {\n\t\t\tsubregion(region::identifier_shoulder_left, segment_range{ 0.85, 1.0 }, angle_range::full)\n\t\t}));\n\n\n\tauto upper_arm_right = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_upper_arm_right, segment_range::full, angle_range::full, {\n\t\t\tsubregion(region::identifier_shoulder_right, segment_range{ 0.85, 1.0 }, angle_range::full)\n\t\t}));\n\n\n\n\tauto lower_arm_left = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_lower_arm_left, segment_range::full, angle_range::full));\n\n\n\tauto lower_arm_right = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_lower_arm_right, segment_range::full, angle_range::full));\n\t\n\n\tauto upper_leg_left = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_upper_leg_left, segment_range::full, angle_range::full));\n\n\tauto lower_leg_left = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_lower_leg_left, segment_range::full, angle_range::full));\n\n\tauto upper_leg_right = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_upper_leg_right, segment_range::full, angle_range::full));\n\n\tauto lower_leg_right = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_lower_leg_right, segment_range::full, angle_range::full));\n\n\tauto head = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_head, segment_range::full, angle_range::full));\n\t\n\tauto left_palm = std::shared_ptr<subregion>(new\n\t\tsubregion(region::identifier_palm_left, segment_range::full, angle_range::full));\n\nauto right_palm = std::shared_ptr<subregion>(new\n\tsubregion(region::identifier_palm_right, segment_range::full, angle_range::full));\n\n\tm_bodyparts.emplace(nsvr_bodypart_head, Bodypart(nsvr_bodypart_head, 19.03, head));\n\n\tm_bodyparts.emplace(nsvr_bodypart_torso, Bodypart(nsvr_bodypart_torso, 51.9, entire_torso));\n\n\tm_bodyparts.emplace(nsvr_bodypart_upperarm_left, Bodypart(nsvr_bodypart_upperarm_left, 29.41, upper_arm_left));\n\n\tm_bodyparts.emplace(nsvr_bodypart_lowerarm_left, Bodypart(nsvr_bodypart_lowerarm_left, 27.68, lower_arm_left));\n\n\tm_bodyparts.emplace(nsvr_bodypart_upperarm_right, Bodypart(nsvr_bodypart_upperarm_right, 29.41, upper_arm_right));\n\n\tm_bodyparts.emplace(nsvr_bodypart_lowerarm_right, Bodypart(nsvr_bodypart_lowerarm_right, 27.68, lower_arm_right));\n\n\tm_bodyparts.emplace(nsvr_bodypart_lowerarm_right, Bodypart(nsvr_bodypart_lowerarm_right, 27.68, lower_arm_right));\n\n\tm_bodyparts.emplace(nsvr_bodypart_lowerleg_left, Bodypart(nsvr_bodypart_lowerleg_left, 43.25, lower_leg_left));\n\n\tm_bodyparts.emplace(nsvr_bodypart_upperleg_left, Bodypart(nsvr_bodypart_upperleg_left, 43.25, upper_leg_left));\n\n\tm_bodyparts.emplace(nsvr_bodypart_lowerleg_right, Bodypart(nsvr_bodypart_lowerleg_right, 43.25, lower_leg_right));\n\n\tm_bodyparts.emplace(nsvr_bodypart_upperleg_right, Bodypart(nsvr_bodypart_upperleg_right, 43.25, upper_leg_right));\n\n\n\tm_bodyparts.emplace(nsvr_bodypart_palm_left, Bodypart(nsvr_bodypart_palm_left, 10.0, left_palm));\n\tm_bodyparts.emplace(nsvr_bodypart_palm_right, Bodypart(nsvr_bodypart_palm_right, 10.0, right_palm));\n\n\tfor (auto& bp : m_bodyparts) {\n\t\tbp.second.region->init_backlinks();\n\t}\n\n}\n\nsubregion::subregion()\n\t: region(shared_region::identifier_unknown)\n\t, seg{ 0, 0 }\n\t, ang{ 0,0 }\n\t, coords{ 0, 0, 0 }\n\t, children()\n\t, hardware_defined_regions()\n\t, parent(nullptr) {}\n\nsubregion::subregion(shared_region region, segment_range segment_offset, angle_range angle_range)\n\t: region(region)\n\t, seg(segment_offset)\n\t, ang(angle_range)\n\t, children()\n\t, hardware_defined_regions()\n\t, parent(nullptr) {\n\tcalculateCoordinates();\n\n}\n\nsubregion::subregion(shared_region region, segment_range segment_offset, angle_range angle_range, std::vector<subregion> child_regions)\n\t: region(region)\n\t, seg(segment_offset)\n\t, ang(angle_range)\n\t, children(std::move(child_regions))\n\t, hardware_defined_regions()\n\t, parent(nullptr) {\n\n\tcalculateCoordinates();\n\n\n}\nint BodyGraph::CreateNode(const char * name, nsvr_bodygraph_region * pose)\n{\n\t//To create a new node:\n\t\t//First, add a vertex into the graph with the given name.\n\tboost::add_vertex(name, m_nodes);\n\n\t//Then, grab the bodypart corresponding with the given arguments.\n\tauto& bodypart = m_bodyparts[pose->bodypart];\n\n\t//Then ask that bodypart to find the nearest match to the given coordinates.\n\tsubregion::shared_region region = bodypart.region->find_best_match(pose->segment_ratio, pose->rotation).second;\n\n\t//Update the vertex with the information that was found\n\tm_nodes[name] = NodeData(name, *pose, region);\n\n\t//Update the bodypart's subregion that corresponded with the match to have a reference to this graph node.\n\tbodypart.region->find(region)->hardware_defined_regions.emplace_back(name);\n\n\n\n\tBOOST_LOG_TRIVIAL(info) << \"[BodyGraph] Node [\" << name << \"] registered on region \" << region._to_string();\n\treturn 0;\n}\n\n\nint BodyGraph::ConnectNodes(const char* a, const char* b)\n{\n\tif (m_nodes.vertex(a) != LabeledGraph::null_vertex() && m_nodes.vertex(b) != LabeledGraph::null_vertex()) {\n\t\tboost::add_edge_by_label(a, b, m_nodes);\n\t\treturn nsvr_success;\n\t}\n\telse {\n\t\treturn nsvr_error_nosuchnode;\n\t}\n}\n\nint BodyGraph::Associate(const char * node, nsvr_node_id node_id)\n{\n\tif (m_nodes.vertex(node) != LabeledGraph::null_vertex()) {\n\t\tm_nodes[node].addNode(node_id);\n\t\treturn nsvr_success;\n\t}\n\telse {\n\t\treturn nsvr_error_nosuchnode;\n\t}\n\n}\n\t\n\nint BodyGraph::Unassociate(const char * node, nsvr_node_id node_id)\n{\n\tif (m_nodes.vertex(node) != LabeledGraph::null_vertex()) {\n\t\tm_nodes[node].removeNode(node_id);\n\t\treturn nsvr_success;\n\t}\n\telse {\n\t\treturn nsvr_error_nosuchnode;\n\t}\n}\n\n\n\nvoid BodyGraph::ClearAssociations(nsvr_node_id node_id)\n{\n\tBGL_FORALL_VERTICES_T(v, m_nodes, LabeledGraph) {\n\t\tm_nodes.graph()[v].removeNode(node_id);\n\t}\n}\n\n\nstd::vector<nsvr_node_id> BodyGraph::getNodesForNamedRegion(subregion::shared_region region) const\n{\n\tstd::vector<nsvr_node_id> nodes;\n\n\t//Special case for whole body - must refactor, and test these methods better\n\tif (region._value == subregion::shared_region::identifier_body) {\n\t\tconst auto& all = getAllNodes();\n\t\tfor (const auto& kvp : all) {\n\t\t\tnodes.insert(nodes.end(), kvp.second.begin(), kvp.second.end());\n\t\t}\n\t\tstd::sort(nodes.begin(), nodes.end());\n\t\tnodes.erase(std::unique(nodes.begin(), nodes.end()), nodes.end());\n\t\treturn nodes;\n\n\t}\n\n\n\tfor (auto& bp : m_bodyparts) {\n\t\tsubregion* ptr = bp.second.region->find(region);\n\t\tif (ptr != nullptr) {\n\t\t\t\n\t\t\t//If this region doesn't have any devices associated with it,\n\t\t\t//Then we need to traverse upwards until we find one that does!\n\t\t\twhile (ptr->hardware_defined_regions.empty()) {\n\t\t\t\tif (ptr->parent != nullptr) {\n\t\t\t\t\tptr = ptr->parent;\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\t\n\t\t\t//Okay, we found some references - for each one, grab the associated nodes out of the graph\n\t\t\t//and insert into our list.\n\t\t\tfor (const std::string& name : ptr->hardware_defined_regions) {\n\t\t\t\tauto& found = m_nodes[name].nodes;\n\t\t\t\tnodes.insert(nodes.end(), found.begin(), found.end());\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::sort(nodes.begin(), nodes.end());\n\tnodes.erase(std::unique(nodes.begin(), nodes.end()), nodes.end());\n\treturn nodes;\n\t\n}\n\n\nstd::vector<subregion::shared_region::_enumerated> BodyGraph::getRegionsForNode(nsvr_node_id node) const\n{\n\tstd::vector<subregion::shared_region::_enumerated> regions;\n\tBGL_FORALL_VERTICES_T(v, m_nodes, LabeledGraph) {\n\t\tsubregion::shared_region region = m_nodes.graph()[v].computed_region;\n\t\tauto& nodeList = m_nodes.graph()[v].nodes;\n\t\tif (std::find(nodeList.begin(), nodeList.end(), node) != nodeList.end()) {\n\t\t\tregions.push_back(region);\n\t\t}\n\n\t}\n\treturn regions;\n}\n\n\nstd::unordered_map<subregion::shared_region::_enumerated, std::vector<nsvr_node_id>> BodyGraph::getAllNodes() const\n{\n\n\tstd::unordered_map<subregion::shared_region::_enumerated, std::vector<nsvr_node_id>> nodes;\n\n\t//Walk through the graph, and add any nodes that were found to the hashtable\n\tBGL_FORALL_VERTICES_T(v, m_nodes, LabeledGraph) {\n\t\tsubregion::shared_region region = m_nodes.graph()[v].computed_region;\n\t\tauto& nodeList = m_nodes.graph()[v].nodes;\n\t\tauto& currentDevices = nodes[region];\n\t\tcurrentDevices.insert(currentDevices.end(), nodeList.begin(), nodeList.end());\n\t}\n\n\t//make sure each list has no duplicates\n\tfor (auto& kvp : nodes) {\n\t\tauto& list = kvp.second;\n\t\tstd::sort(list.begin(), list.end());\n\t\tlist.erase(std::unique(list.begin(), list.end()), list.end());\n\t}\n\n\treturn nodes;\n}\n\n\n\nvoid BodyGraph::NodeData::addNode(nsvr_node_id id)\n{\n\tauto it = std::find(nodes.begin(), nodes.end(), id);\n\tif (it == nodes.end()) {\n\t\tnodes.push_back(id);\n\t}\n}\n\nvoid BodyGraph::NodeData::removeNode(nsvr_node_id id)\n{\n\tauto it = std::remove(nodes.begin(), nodes.end(), id);\n\tnodes.erase(it, nodes.end());\n}\n\n", "meta": {"hexsha": "981db6b0db5a2fd70cbb7a7a876f7ed18acaab66", "size": 11195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Driver/BodyGraph.cpp", "max_stars_repo_name": "cwaldren/HL-engine", "max_stars_repo_head_hexsha": "0a303759eaed6331e4e0022f59d71fd2cc5c4379", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T04:39:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T01:11:54.000Z", "max_issues_repo_path": "src/Driver/BodyGraph.cpp", "max_issues_repo_name": "cwaldren/HL-engine", "max_issues_repo_head_hexsha": "0a303759eaed6331e4e0022f59d71fd2cc5c4379", "max_issues_repo_licenses": ["MIT"], "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/Driver/BodyGraph.cpp", "max_forks_repo_name": "cwaldren/HL-engine", "max_forks_repo_head_hexsha": "0a303759eaed6331e4e0022f59d71fd2cc5c4379", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-18T21:20:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:34:06.000Z", "avg_line_length": 34.131097561, "max_line_length": 135, "alphanum_fraction": 0.7461366682, "num_tokens": 3059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.17927717104487445}}
{"text": "#include <string>\n#include <vector>\n#include <set>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <memory>\n#include <algorithm>\n#include <libcxx/sort.hpp>\n#include <boost/optional/optional.hpp>\n#include \"getopt_pp/getopt_pp.h\"\n#include \"kmc_api/kmc_file.h\"\n//#include \"omp.h\"\n#include \"io/kmers/mmapped_reader.hpp\"\n#include \"utils/filesystem/path_helper.hpp\"\n#include \"utils/stl_utils.hpp\"\n#include \"utils/ph_map/perfect_hash_map_builder.hpp\"\n#include \"utils/ph_map/storing_traits.hpp\"\n#include \"utils/kmer_mph/kmer_splitters.hpp\"\n#include \"logger.hpp\"\n\nusing std::string;\nusing std::vector;\n\nconst string KMER_PARSED_EXTENSION = \".bin\";\nconst string KMER_SORTED_EXTENSION = \".sorted\";\n\nclass KmerMultiplicityCounter {\n    size_t k_ ;\n    std::string file_prefix_;\n\n    //TODO: get rid of intermediate .bin file\n    string ParseKmc(const string& filename) {\n        CKMCFile kmcFile;\n        kmcFile.OpenForListing(filename);\n        CKmerAPI kmer((unsigned int) k_);\n        uint32 count;\n        std::string parsed_filename = filename + KMER_PARSED_EXTENSION;\n        std::ofstream output(parsed_filename, std::ios::binary);\n        while (kmcFile.ReadNextKmer(kmer, count)) {\n            RtSeq seq(k_, kmer.to_string());\n            seq.BinWrite(output);\n            seq_element_type tmp = count;\n            output.write((char*) &(tmp), sizeof(seq_element_type));\n        }\n        output.close();\n        return parsed_filename;\n    }\n\n    string SortKmersCountFile(const string& filename) {\n        MMappedRecordArrayReader<seq_element_type> ins(filename, RtSeq::GetDataSize(k_) + 1, false);\n        libcxx::sort(ins.begin(), ins.end(), adt::array_less<seq_element_type>());\n        std::string sorted_filename = filename + KMER_SORTED_EXTENSION;\n        std::ofstream out(sorted_filename);\n        out.write((char*) ins.data(), ins.data_size());\n        out.close();\n        remove(filename.c_str());\n        return sorted_filename;\n    }\n\n    bool ReadKmerWithCount(std::ifstream& infile, std::pair<RtSeq, uint32>& res) {\n        RtSeq seq(res.first.size());\n        if (!seq.BinRead(infile)) {\n            return false;\n        }\n        seq_element_type tmp;\n        infile.read((char*) &tmp, sizeof(seq_element_type));\n        res = {seq, (uint32) tmp};\n        return true;\n    }\n\n    fs::TmpFile FilterCombinedKmers(fs::TmpDir workdir, const std::vector<string>& files,\n                                    size_t all_min, size_t min_mult) {\n        size_t n = files.size();\n        vector<std::unique_ptr<ifstream>> infiles;\n        infiles.reserve(n);\n        for (auto fn : files) {\n            INFO(\"Processing \" << fn);\n            auto parsed = ParseKmc(fn);\n            auto sorted = SortKmersCountFile(parsed);\n            infiles.emplace_back(new std::ifstream(sorted));\n        }\n        vector<std::pair<RtSeq, uint32>> top_kmer(n, {RtSeq(k_), 0});\n        vector<bool> alive(n, false);\n\n        for (size_t i = 0; i < n; i++) {\n            alive[i] = ReadKmerWithCount(*infiles[i], top_kmer[i]);\n        }\n\n        auto kmer_file = fs::tmp::make_temp_file(\"kmer\", workdir);\n\n        typedef uint16_t Mpl;\n        std::ofstream output_kmer(*kmer_file, std::ios::binary);\n        std::ofstream mpl_file(file_prefix_ + \".bpr\", std::ios_base::binary);\n\n        RtSeq::less3 kmer_less;\n        while (true) {\n            boost::optional<RtSeq> min_kmer;\n            size_t cnt_min = 0, num_samples = 0;\n            for (size_t i = 0; i < n; ++i) {\n                if (alive[i]) {\n                    RtSeq& cur_kmer = top_kmer[i].first;\n                    if (!min_kmer || kmer_less(cur_kmer, *min_kmer)) {\n                        min_kmer = cur_kmer;\n                        cnt_min = 0;\n                    }\n                    if (cur_kmer == *min_kmer) {\n                        ++cnt_min;\n                    }\n                }\n            }\n            if (!min_kmer) {\n                break;\n            }\n            if (cnt_min >= all_min) {\n                std::vector<uint32> cnt_vector(n, 0);\n                size_t total_cnt = 0;\n                for (size_t i = 0; i < n; ++i) {\n                    if (alive[i] && top_kmer[i].first == *min_kmer) {\n                        auto cnt = top_kmer[i].second;\n                        cnt_vector[i] = cnt;\n                        total_cnt += cnt;\n                    }\n                }\n                if (cnt_min > 1 || total_cnt > min_mult) {\n                    min_kmer.get().BinWrite(output_kmer);\n                    for (size_t mpl : cnt_vector) {\n                        mpl_file.write(reinterpret_cast<char *>(&mpl), sizeof(Mpl));\n                    }\n                }\n            }\n            for (size_t i = 0; i < n; ++i) {\n                if (alive[i] && top_kmer[i].first == *min_kmer) {\n                    alive[i] = ReadKmerWithCount(*infiles[i], top_kmer[i]);\n                }\n            }\n        }\n        return kmer_file;\n    }\n\n    void BuildKmerIndex(fs::TmpDir workdir, fs::TmpFile kmer_file, size_t sample_cnt, size_t nthreads) {\n        INFO(\"Initializing kmer profile index\");\n\n        typedef size_t Offset;\n        using namespace utils;\n\n        using KMerDiskStorage = kmers::KMerDiskStorage<RtSeq>;\n        constexpr size_t read_buffer_size = 0; //FIXME some buffer size\n        DeBruijnKMerKMerSplitter<StoringTypeFilter<InvertableStoring>,\n                                 KMerDiskStorage::kmer_iterator>\n                splitter(workdir, k_, k_, true, read_buffer_size);\n        splitter.AddKMers(adt::make_range(KMerDiskStorage::kmer_iterator(*kmer_file, k_), KMerDiskStorage::kmer_iterator()));\n\n        kmers::KMerDiskCounter<RtSeq> counter(workdir, std::move(splitter));\n        KeyStoringMap<RtSeq, Offset, kmers::kmer_index_traits<RtSeq>, InvertableStoring> kmer_mpl(k_);\n        BuildIndex(kmer_mpl, counter, 16, nthreads);\n        INFO(\"Built index with \" << kmer_mpl.size() << \" kmers\");\n\n        //Building kmer->profile offset index\n        std::ifstream kmers_in(*kmer_file, std::ios::binary);\n        utils::InvertableStoring::trivial_inverter inverter;\n        RtSeq kmer(k_);\n        for (Offset offset = 0; ; offset += sample_cnt) {\n            kmer.BinRead(kmers_in);\n            if (kmers_in.fail()) {\n                break;\n            }\n\n//            VERIFY(kmer_str.length() == k_);\n//            conj_graph_pack::seq_t kmer(k_, kmer_str.c_str());\n//            kmer = gp_.kmer_mapper.Substitute(kmer);\n\n            auto kwh = kmer_mpl.ConstructKWH(kmer);\n            VERIFY(kmer_mpl.valid(kwh));\n            kmer_mpl.put_value(kwh, offset, inverter);\n        }\n\n        std::ofstream map_file(file_prefix_ + \".kmm\", std::ios_base::binary | std::ios_base::out);\n        kmer_mpl.BinWrite(map_file);\n        INFO(\"Saved kmer profile map\");\n    }\n\npublic:\n    KmerMultiplicityCounter(size_t k, std::string file_prefix):\n        k_(k), file_prefix_(std::move(file_prefix)) {\n    }\n\n    void CombineMultiplicities(const vector<string>& input_files, size_t min_samples,\n                               size_t min_mult, const string& tmpdir, size_t nthreads = 1) {\n        auto workdir = fs::tmp::make_temp_dir(tmpdir, \"kmidx\");\n        auto kmer_file = FilterCombinedKmers(workdir, input_files, min_samples, min_mult);\n        BuildKmerIndex(workdir, kmer_file, input_files.size(), nthreads);\n    }\nprivate:\n    DECL_LOGGER(\"KmerMultiplicityCounter\");\n};\n\nvoid PrintUsageInfo() {\n    std::cout << \"Usage: kmer_multiplicity_counter [options] -f files_dir\" << std::endl;\n    std::cout << \"Options:\" << std::endl;\n    std::cout << \"-k - kmer length\" << std::endl;\n    std::cout << \"-n - sample count\" << std::endl;\n    std::cout << \"-o - output file prefix\" << std::endl;\n    std::cout << \"-t - number of threads (default: 1)\" << std::endl;\n    std::cout << \"-s - minimal number of samples to contain kmer\" << std::endl;\n    std::cout << \"-m - minimal multiplicity of single-sample kmers\" << std::endl;\n    std::cout << \"files_dir must contain two files (.kmc_pre and .kmc_suf) with kmer multiplicities for each sample from 1 to n\" << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n    using namespace GetOpt;\n    create_console_logger();\n\n    size_t k, sample_cnt, min_samples, min_mult, nthreads;\n    string output, work_dir;\n\n    try {\n        GetOpt_pp ops(argc, argv);\n        ops.exceptions_all();\n        ops >> Option('k', k)\n            >> Option('n', sample_cnt)\n            >> Option('m', \"min-mult\", min_mult, size_t(5))\n            >> Option('s', min_samples)\n            >> Option('o', output)\n            >> Option('t', \"threads\", nthreads, size_t(1))\n            >> Option('f', work_dir)\n        ;\n    } catch(GetOptEx &ex) {\n        PrintUsageInfo();\n        exit(1);\n    }\n\n    std::vector<string> input_files;\n    for (size_t i = 1; i <= sample_cnt; ++i) {\n        input_files.push_back(work_dir + \"/sample\" + std::to_string(i));\n    }\n\n    KmerMultiplicityCounter kmcounter(k, output);\n    kmcounter.CombineMultiplicities(input_files, min_samples, min_mult, work_dir, nthreads);\n    return 0;\n}\n", "meta": {"hexsha": "a4b12b2892ace4feda5c57ef89dcb40067ce8c1a", "size": 9071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/metaspades/src/projects/mts/kmer_multiplicity_counter.cpp", "max_stars_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_stars_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "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/metaspades/src/projects/mts/kmer_multiplicity_counter.cpp", "max_issues_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_issues_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_issues_repo_licenses": ["MIT"], "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/metaspades/src/projects/mts/kmer_multiplicity_counter.cpp", "max_forks_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_forks_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T07:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T08:02:58.000Z", "avg_line_length": 37.4834710744, "max_line_length": 142, "alphanum_fraction": 0.5768933965, "num_tokens": 2285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.17927716416084485}}
{"text": "#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/CPDInterface.h>\n\n#include <stdexcept>\n#include <sstream>\n\n#include <boost/foreach.hpp>\n\n#include <spatialops/particles/ParticleFieldTypes.h>\n#include <spatialops/Nebo.h>\n\n#include <expression/ClipValue.h>\n\n// expressions we build here\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/L_RHS.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/CPDData.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/C_RHS.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/Gi_RHS.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/Deltai_RHS.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/c0_fun.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/kb.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/kg_i.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/dy_gi.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/MvRHS.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/Mv.h>\n#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/TarProductionRate.h>\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::ostringstream;\nusing std::string;\n\nnamespace CPD{\n\n//------------------------------------------------------------------\n\nvector<string> taglist_names( const Expr::TagList& tags )\n{\n  vector<string> fieldNames;\n  for(  Expr::TagList::const_iterator it=tags.begin(); it!=tags.end(); ++it ){\n    fieldNames.push_back( it->name() );\n  }\n  return fieldNames;\n}\n//------------------------------------------------------------------\n\t\nCPDSpecies gas_dev2cpd( const DEV::DEVSpecies cspec )\n{\n  CPDSpecies s;\n  switch( cspec ){\n    case DEV::CO2:  s=CO2;             break;\n    case DEV::H2O:  s=H2O;             break;\n    case DEV::CO :  s=CO;              break;\n    case DEV::HCN:  s=HCN;             break;\n    case DEV::NH3:  s=NH3;             break;\n    case DEV::CH4:  s=CH4;             break;\n    case DEV::H2 :  s=H2;              break;\n    default:   s=INVALID_SPECIES; break;\n  }\n  return s;\n}\n\t\n//--------------------------------------------------------------------\n\ntemplate< typename FieldT >\nCPDInterface<FieldT>::CPDInterface( GraphCategories& gc,\n                                    const CoalType   coalType,\n                                    const Expr::Tag  pTempTag,\n                                    const Expr::Tag  pMassTag,\n                                    const Expr::Tag  pMass0Tag )\n  : DEV::DevolatilizationBase(),\n    cpdInfo_   ( coalType ),\n    coalComp_  ( cpdInfo_.get_coal_composition() ),\n    c0_        ( c0_fun( coalComp_.get_C(), coalComp_.get_O() )),\n    vMassFrac0_( coalComp_.get_vm() ),\n    tar0_      ( tar_0(cpdInfo_, c0_) ),\n    pTempTag_  ( pTempTag  ),\n    pMassTag_  ( pMassTag  ),\n    pMass0Tag_ ( pMass0Tag ),\n    kbTag_     ( Coal::StringNames::self().cpd_kb, Expr::STATE_NONE ),\n    sNames_    ( Coal::StringNames::self() ),\n    gc_        ( gc )\n{\n  if( pTempTag == Expr::Tag() ){\n    ostringstream msg;\n    msg << __FILE__ << \" : \" << __LINE__ << endl\n        << \"temperature tag is invalid.\" << endl;\n    throw std::runtime_error( msg.str() );\n  }\n\n  haveRegisteredExprs_ = false;\n\n  parse_equations();\n  set_tags();\n  register_expressions();\n}\n\n//----------------------------------------------------------------------\n\ntemplate< typename FieldT >\nvoid\nCPDInterface<FieldT>::\nparse_equations()\n{\n  gEqns_.    clear();\n  deltaEqns_.clear();\n\n  gTags_.    clear();\n  deltaTags_.clear();\n\n  g_rhsTags_.    clear();\n  delta_rhsTags_.clear();\n\n  const vector<double> delta0 = deltai_0(cpdInfo_, c0_ );\n\n  /*\n   * Parse equations for coal functional groups\n   */\n  const int nspec = cpdInfo_.get_nspec();\n  for( int i=0; i<nspec; ++i ){\n    ostringstream name1, name2;\n    name1 << sNames_.cpd_g     << i;\n    name2 << sNames_.cpd_delta << i;\n\n    gEqns_.    push_back( new Coal::CoalEquation(name1.str(), 0.0, gc_) );\n    deltaEqns_.push_back( new Coal::CoalEquation(name2.str(), pMassTag_, delta0[i] , gc_) );\n\n    gTags_.    push_back( gEqns_    [i]->solution_variable_tag() );\n    deltaTags_.push_back( deltaEqns_[i]->solution_variable_tag() );\n\n    g_rhsTags_.    push_back( gEqns_    [i]->rhs_tag() );\n    delta_rhsTags_.push_back( deltaEqns_[i]->rhs_tag() );\n  }\n\n  /*\n   * Parse equations for volatiles, tar, labile bridge, and labile bridge population.\n   */\n  const double lFrac0 = cpdInfo_.get_l0_mass() * vMassFrac0_; // initial mass fraction of labile bridge in the particle.\n\n  volatilesEqn_    = new Coal::CoalEquation( sNames_.dev_mv, pMassTag_, vMassFrac0_*(1.0-c0_), gc_ );\n  tarEqn_          = new Coal::CoalEquation( sNames_.cpd_tar, pMassTag_, vMassFrac0_*tar0_,    gc_ );\n  lbEqn_           = new Coal::CoalEquation( sNames_.cpd_l,  pMassTag_, lFrac0,                gc_ );\n  lbPopulationEqn_ = new Coal::CoalEquation( sNames_.cpd_lbPopulation, cpdInfo_.get_lbPop0(),  gc_ );\n\n\n  // put pointers to equations in a vector\n  eqns_.clear();\n  eqns_.insert( eqns_.end(), gEqns_.begin(),     gEqns_.end()     );\n  eqns_.insert( eqns_.end(), deltaEqns_.begin(), deltaEqns_.end() );\n  eqns_.push_back( volatilesEqn_    );\n  eqns_.push_back( tarEqn_          );\n  eqns_.push_back( lbEqn_           );\n  eqns_.push_back( lbPopulationEqn_ );\n}\n//----------------------------------------------------------------------\ntemplate< typename FieldT >\nvoid\nCPDInterface<FieldT>::\nset_tags()\n{\n  // set tags for functional group rate constants\n  const int nspec = cpdInfo_.get_nspec();\n  for( int i=0; i<nspec; ++i ){\n\n    ostringstream name1;\n    name1 << sNames_.cpd_kg << i;\n    kgTags_.push_back( Expr::Tag(name1.str(),Expr::STATE_NONE) );\n  }\n\n  // set tags for composition and species sources.\n  speciesSrcTags_.clear();\n  const SpeciesSum& specSum = SpeciesSum::self();\n  const int ncomp = specSum.get_ncomp();\n  for( int i=1; i<=ncomp; i++ ){\n\n    ostringstream name2;\n    name2 << sNames_.cpd_dy << i;\n    speciesSrcTags_.push_back( Expr::Tag(name2.str(),Expr::STATE_NONE) );\n  }\n\n  // set tags needed for particle-to-cell source terms (and a few others)\n  charSrcTag_      = Expr::Tag(sNames_.cpd_charProd_rhs, Expr::STATE_NONE);\n\n  lbTag_           = lbEqn_           ->solution_variable_tag();\n  lb_rhsTag_       = lbEqn_           ->rhs_tag();\n\n  lbpTag_          = lbPopulationEqn_->solution_variable_tag();\n  lbp_rhsTag_      = lbPopulationEqn_->rhs_tag();\n\n  tarTag_          = tarEqn_          ->solution_variable_tag();\n  tarSrcTag_       = tarEqn_          ->rhs_tag();\n\n  volatilesTag_    = volatilesEqn_    ->solution_variable_tag();\n  volatilesSrcTag_ = volatilesEqn_    ->rhs_tag();\n}\n\n//----------------------------------------------------------------------\n\ntemplate< typename FieldT >\nvoid\nCPDInterface<FieldT>::\nregister_expressions()\n{\n  Expr::ExpressionFactory& factory = *(gc_[WasatchCore::ADVANCE_SOLUTION]->exprFactory);\n\n  factory.register_expression( new typename kb<FieldT>::\n                                                Builder(kbTag_, pTempTag_, cpdInfo_));\n\n  factory.register_expression( new typename kg_i<FieldT>::\n                                                Builder(kgTags_, gTags_ ,pTempTag_, pMass0Tag_, cpdInfo_) );\n\n  factory.register_expression( new typename TarProductionRate<FieldT>::\n                                                Builder(tarSrcTag_, lbpTag_, lbp_rhsTag_,\n                                                        pMass0Tag_, vMassFrac0_, tar0_, cpdInfo_ ) );\n\n  factory.register_expression( new typename L_RHS<FieldT>::\n                                                Builder(lb_rhsTag_, kbTag_, lbTag_ ) );\n\n  factory.register_expression( new typename C_RHS<FieldT>::\n                                                Builder(charSrcTag_,  kbTag_, lbTag_, cpdInfo_ ));\n\n  factory.register_expression( new typename Gi_RHS<FieldT>::\n                                                Builder(g_rhsTags_, kbTag_, kgTags_,deltaTags_,\n                                                        lbTag_ ,cpdInfo_) );\n\n  factory.register_expression( new typename Deltai_RHS<FieldT>::\n                                                Builder(delta_rhsTags_, kbTag_, kgTags_, deltaTags_,\n                                                        lbTag_ ,cpdInfo_) );\n\n  factory.register_expression( new typename MvRHS<FieldT>::\n                                                Builder(volatilesSrcTag_, charSrcTag_, speciesSrcTags_ ));\n\n  factory.register_expression( new typename dy_gi<FieldT>::\n                                                Builder(speciesSrcTags_, g_rhsTags_ ) );\n\n  factory.register_expression( new typename L_RHS<FieldT>::\n                                                Builder(lbp_rhsTag_, kbTag_, lbpTag_ ) );\n\n  // adds tar production rate to volatiles production rate\n  factory.attach_dependency_to_expression( tarSrcTag_, volatilesSrcTag_ );\n\n  // Ensure non-negative values\n  typedef Expr::ClipValue<FieldT> Clipper;\n  BOOST_FOREACH( Coal::CoalEquation* const& eqn, eqns_ ){\n    Expr::Tag tag = eqn->solution_variable_tag();\n    const Expr::Tag clip( tag.name()+\"_clip\", Expr::STATE_NONE );\n    factory.register_expression( new typename Clipper::Builder( clip, 0.0, 0.0, Clipper::CLIP_MIN_ONLY ) );\n    factory.attach_modifier_expression( clip, tag );\n  }\n\n  haveRegisteredExprs_ = true;\n}\n\n//--------------------------------------------------------------------\n\ntemplate< typename FieldT >\nconst Expr::Tag\nCPDInterface<FieldT>::\ngas_species_src_tag( const DEV::DEVSpecies devspec ) const\n{\n  const CPDSpecies spec = gas_dev2cpd(devspec);\n  if( spec == INVALID_SPECIES ) return Expr::Tag();\n  return speciesSrcTags_[ spec ];\n}\n\n//====================================================================\n// Explicit template instantiation\ntemplate class CPDInterface< SpatialOps::Particle::ParticleField >;\n//====================================================================\n\n} // namespace CPD\n", "meta": {"hexsha": "e0184e010912e2ce6f9d78f3f3791fba4e91870c", "size": 9920, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/CCA/Components/Wasatch/Coal/Devolatilization/CPD/CPDInterface.cc", "max_stars_repo_name": "abagusetty/Uintah", "max_stars_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T08:21:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-23T18:33:16.000Z", "max_issues_repo_path": "src/CCA/Components/Wasatch/Coal/Devolatilization/CPD/CPDInterface.cc", "max_issues_repo_name": "abagusetty/Uintah", "max_issues_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "max_issues_repo_licenses": ["MIT"], "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/CCA/Components/Wasatch/Coal/Devolatilization/CPD/CPDInterface.cc", "max_forks_repo_name": "abagusetty/Uintah", "max_forks_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-30T05:48:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T16:24:16.000Z", "avg_line_length": 36.4705882353, "max_line_length": 120, "alphanum_fraction": 0.5941532258, "num_tokens": 2610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.17914877327385445}}
{"text": "#include \"StdInc.h\"\n\n#include <ClientHttpHandler.h>\n\n#include <ClientRegistry.h>\n#include <GameServer.h>\n\n#include <ServerInstanceBase.h>\n\n#include <ResourceManager.h>\n#include <ResourceEventComponent.h>\n#include <ResourceCallbackComponent.h>\n\n#include <boost/random/random_device.hpp>\n#include <boost/uuid/random_generator.hpp>\n#include <boost/uuid/uuid_io.hpp>\n\n#include <IteratorView.h>\n\n#include <botan/base64.h>\n#include <botan/sha160.h>\n#include <botan/pubkey.h>\n#include <botan/rsa.h>\n#include <botan/ber_dec.h>\n\n#include <ctime>\n\n#include <ClientDeferral.h>\n\n#include <ServerIdentityProvider.h>\n\n#include <MonoThreadAttachment.h>\n\n#include <json.hpp>\n\n#define FOLLY_NO_CONFIG\n\n#ifdef _WIN32\n#undef ssize_t\n#else\n#include <sys/types.h>\n#endif\n\n#include <folly/String.h>\n#include <boost/algorithm/string.hpp>\n\nusing json = nlohmann::json;\n\nstatic std::forward_list<fx::ServerIdentityProviderBase*> g_serverProviders;\nstatic std::map<std::string, fx::ServerIdentityProviderBase*> g_providersByType;\n\nnamespace fx\n{\nvoid RegisterServerIdentityProvider(ServerIdentityProviderBase* provider)\n{\n\tg_serverProviders.push_front(provider);\n\tg_providersByType.insert({ provider->GetIdentifierPrefix(), provider });\n}\n}\n\nstatic std::mutex g_ticketMapMutex;\nstatic std::unordered_set<std::tuple<uint64_t, uint64_t>> g_ticketList;\nstatic std::chrono::milliseconds g_nextTicketGc;\n\nstatic bool VerifyTicket(const std::string& guid, const std::string& ticket, std::string* error = nullptr)\n{\n\tauto ticketData = Botan::base64_decode(ticket);\n\n\t// validate ticket length\n\tif (ticketData.size() < 20 + 4 + 128)\n\t{\n\t\tif (error)\n\t\t{\n\t\t\t*error = \"Invalid ticket length.\";\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tuint32_t length = *(uint32_t*)&ticketData[0];\n\n\tif (length != 16)\n\t{\n\t\tif (error)\n\t\t{\n\t\t\t*error = \"Invalid ticket length. (2)\";\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tuint64_t ticketGuid = *(uint64_t*)&ticketData[4];\n\tuint64_t ticketExpiry = *(uint64_t*)&ticketData[12];\n\n\t// check expiration\n\n\t// get UTC time\n\tstd::time_t timeVal;\n\tstd::time(&timeVal);\n\n\t// verify\n\tif (ticketExpiry < timeVal)\n\t{\n\t\tif (error)\n\t\t{\n\t\t\t*error = \"Ticket expired. Please check your server's system time.\";\n\t\t}\n\n\t\tconsole::DPrintf(\"server\", \"Connecting player: ticket expired\\n\");\n\t\treturn false;\n\t}\n\n\t// check the GUID\n\tuint64_t realGuid = strtoull(guid.c_str(), nullptr, 10);\n\n\tif (realGuid != ticketGuid)\n\t{\n\t\tif (error)\n\t\t{\n\t\t\t*error = \"Mismatching GUID.\";\n\t\t}\n\n\t\tconsole::DPrintf(\"server\", \"Connecting player: ticket GUID not matching\\n\");\n\t\treturn false;\n\t}\n\n\t{\n\t\tstd::unique_lock<std::mutex> _(g_ticketMapMutex);\n\n\t\tif (g_ticketList.find({ ticketExpiry, ticketGuid }) != g_ticketList.end())\n\t\t{\n\t\t\tif (error)\n\t\t\t{\n\t\t\t\t*error = \"Reused ticket.\";\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tif (msec() > g_nextTicketGc)\n\t\t{\n\t\t\tg_ticketList.clear();\n\t\t\tg_nextTicketGc = msec() + std::chrono::minutes(30);\n\t\t}\n\n\t\tg_ticketList.insert({ ticketExpiry, ticketGuid });\n\t}\n\n\t// check the RSA signature\n\tuint32_t sigLength = *(uint32_t*)&ticketData[length + 4];\n\n\tif (sigLength != 128)\n\t{\n\t\tif (error)\n\t\t{\n\t\t\t*error = \"Invalid signature length.\";\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tBotan::SHA_160 hashFunction;\n\tauto result = hashFunction.process(&ticketData[4], length);\n\n\tstd::vector<uint8_t> msg(result.size() + 1);\n\tmsg[0] = 2;\n\tmemcpy(&msg[1], &result[0], result.size());\n\n\tauto modulus = Botan::base64_decode(\"1DNT1go22VUAU3BON+jCfXxs7Ow9Zxwng4ARTX/vrv6I65bsSYbdBrcc\"\n\t\t\t\t\t\t\t\t\t\t\"w/50Fu7AJr8zy8+sXK8wUO4gx00frtA0adaGeZOeBqNq7/K3Gprv98wc\"\n\t\t\t\t\t\t\t\t\t\t\"ftbxWjUv75pVl9Ush5yxpBPbuYUnGR/Nh2+K3GRrIrKxWYpNSF1JZYzE\"\n\t\t\t\t\t\t\t\t\t\t\"+5k=\");\n\n\tauto exponent = Botan::base64_decode(\"AQAB\");\n\n\tBotan::BigInt n(modulus.data(), modulus.size());\n\tBotan::BigInt e(exponent.data(), exponent.size());\n\n\tauto pk = Botan::RSA_PublicKey(n, e);\n\n\tauto signer = std::make_unique<Botan::PK_Verifier>(pk, \"EMSA_PKCS1(SHA-1)\");\n\n\tbool valid = signer->verify_message(msg.data(), msg.size(), &ticketData[length + 4 + 4], sigLength);\n\n\tif (!valid)\n\t{\n\t\tif (error)\n\t\t{\n\t\t\t*error = \"Invalid ticket signature.\";\n\t\t}\n\n\t\tconsole::DPrintf(\"server\", \"Connecting player: ticket RSA signature not matching\\n\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nstruct TicketData\n{\n\tstd::optional<std::array<uint8_t, 20>> entitlementHash;\n\tstd::optional<std::string> extraJson;\n};\n\nstatic std::optional<TicketData> VerifyTicketEx(const std::string& ticket)\n{\n\tauto ticketData = Botan::base64_decode(ticket);\n\n\t// validate ticket length\n\tif (ticketData.size() < 20 + 4 + 128 + 4)\n\t{\n\t\treturn {};\n\t}\n\n\tuint32_t length = *(uint32_t*)&ticketData[20 + 4 + 128];\n\n\t// validate full length\n\tif (ticketData.size() < 20 + 4 + 128 + 4 + length)\n\t{\n\t\treturn {};\n\t}\n\n\t// copy extra data\n\tstd::vector<uint8_t> extraData(length);\n\n\tif (!extraData.empty())\n\t{\n\t\tmemcpy(&extraData[0], &ticketData[20 + 4 + 128 + 4], length);\n\t}\n\n\t// check the RSA signature\n\tuint32_t sigLength = *(uint32_t*)&ticketData[20 + 4 + 128 + 4 + length];\n\n\tif (sigLength != 128)\n\t{\n\t\treturn {};\n\t}\n\n\tBotan::SHA_160 hashFunction;\n\tauto result = hashFunction.process(&ticketData[4], ticketData.size() - 128 - 4 - 4);\n\n\tstd::vector<uint8_t> msg(result.size() + 1);\n\tmsg[0] = 2;\n\tmemcpy(&msg[1], &result[0], result.size());\n\n\tauto modulus = Botan::base64_decode(\"1DNT1go22VUAU3BON+jCfXxs7Ow9Zxwng4ARTX/vrv6I65bsSYbdBrcc\"\n\t\t\"w/50Fu7AJr8zy8+sXK8wUO4gx00frtA0adaGeZOeBqNq7/K3Gprv98wc\"\n\t\t\"ftbxWjUv75pVl9Ush5yxpBPbuYUnGR/Nh2+K3GRrIrKxWYpNSF1JZYzE\"\n\t\t\"+5k=\");\n\n\tauto exponent = Botan::base64_decode(\"AQAB\");\n\n\tBotan::BigInt n(modulus.data(), modulus.size());\n\tBotan::BigInt e(exponent.data(), exponent.size());\n\n\tauto pk = Botan::RSA_PublicKey(n, e);\n\n\tauto signer = std::make_unique<Botan::PK_Verifier>(pk, \"EMSA_PKCS1(SHA-1)\");\n\n\tbool valid = signer->verify_message(msg.data(), msg.size(), &ticketData[length + 4 + 4 + 128 + 20 + 4], sigLength);\n\n\tif (!valid)\n\t{\n\t\tconsole::DPrintf(\"server\", \"Connecting player: ticket RSA signature not matching\\n\");\n\t\treturn {};\n\t}\n\n\tTicketData outData;\n\n\tif (length >= 20)\n\t{\n\t\tstd::array<uint8_t, 20> entitlementHash;\n\t\tmemcpy(entitlementHash.data(), &extraData[0], entitlementHash.size());\n\n\t\toutData.entitlementHash = entitlementHash;\n\t}\n\n\tif (length >= 24)\n\t{\n\t\tuint32_t extraJsonLength = *(uint32_t*)&extraData[20];\n\n\t\tif (length >= (24 + extraJsonLength))\n\t\t{\n\t\t\toutData.extraJson = std::string{ (char*)&extraData[24], extraJsonLength };\n\t\t}\n\t}\n\n\treturn outData;\n}\n\nextern std::shared_ptr<ConVar<bool>> g_oneSyncVar;\nstd::string g_enforcedGameBuild;\n\nstatic InitFunction initFunction([]()\n{\n\tfx::ServerInstanceBase::OnServerCreate.Connect([](fx::ServerInstanceBase* instance)\n\t{\n\t\tauto minTrustVar = instance->AddVariable<int>(\"sv_authMinTrust\", ConVar_None, 1);\n\t\tminTrustVar->GetHelper()->SetConstraints(1, 5);\n\n\t\tauto maxVarianceVar = instance->AddVariable<int>(\"sv_authMaxVariance\", ConVar_None, 5);\n\t\tmaxVarianceVar->GetHelper()->SetConstraints(1, 5);\n\n\t\tauto shVar = instance->AddVariable<bool>(\"sv_scriptHookAllowed\", ConVar_ServerInfo, false);\n\t\tauto ehVar = instance->AddVariable<bool>(\"sv_enhancedHostSupport\", ConVar_ServerInfo, false);\n\n\t\t// list of space-separated endpoints that can but don't have to include a port\n\t\t// for example: sv_endpoints \"123.123.123.123 124.124.124.124\"\n\t\tauto srvEndpoints = instance->AddVariable<std::string>(\"sv_endpoints\", ConVar_None, \"\");\n\t\tauto lanVar = instance->AddVariable<bool>(\"sv_lan\", ConVar_ServerInfo, false);\n\n\t\tg_enforcedGameBuild = \"1604\";\n\t\tauto enforceGameBuildVar = instance->AddVariable<std::string>(\"sv_enforceGameBuild\", ConVar_ReadOnly | ConVar_ServerInfo, \"1604\", &g_enforcedGameBuild);\n\n\t\tinstance->GetComponent<fx::GameServer>()->OnTick.Connect([instance, enforceGameBuildVar]()\n\t\t{\n\t\t\tif (instance->GetComponent<fx::GameServer>()->GetGameName() == fx::GameName::RDR3)\n\t\t\t{\n\t\t\t\tif (g_enforcedGameBuild == \"1604\")\n\t\t\t\t{\n\t\t\t\t\tenforceGameBuildVar->GetHelper()->SetRawValue(\"1311\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauto clientRegistry = instance->GetComponent<fx::ClientRegistry>();\n\n\t\t\tclientRegistry->ForAllClients([](const fx::ClientSharedPtr& client)\n\t\t\t{\n\t\t\t\tauto deferralAny = client->GetData(\"deferralPtr\");\n\n\t\t\t\tif (deferralAny.has_value())\n\t\t\t\t{\n\t\t\t\t\tauto weakDeferral = std::any_cast<std::weak_ptr<fx::ClientDeferral>>(deferralAny);\n\n\t\t\t\t\tif (!weakDeferral.expired())\n\t\t\t\t\t{\n\t\t\t\t\t\tclient->Touch();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tinstance->GetComponent<fx::ClientMethodRegistry>()->AddHandler(\"getEndpoints\", [instance, srvEndpoints](const std::map<std::string, std::string>& postMap, const fwRefContainer<net::HttpRequest>& request, const std::function<void(const json&)>& cb)\n\t\t{\n\t\t\tauto sendError = [=](const std::string& error)\n\t\t\t{\n\t\t\t\tcb(json::object({ { \"error\", error } }));\n\t\t\t\tcb(json(nullptr));\n\t\t\t};\n\n\t\t\tauto tokenIt = postMap.find(\"token\");\n\n\t\t\tif (tokenIt == postMap.end())\n\t\t\t{\n\t\t\t\tsendError(\"fields missing\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tauto clientRegistry = instance->GetComponent<fx::ClientRegistry>();\n\t\t\tauto client = clientRegistry->GetClientByConnectionToken(tokenIt->second);\n\t\t\tif (!client)\n\t\t\t{\n\t\t\t\tcb(false);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tauto endpointList = srvEndpoints->GetValue();\n\t\t\t\tif (endpointList.empty()) \n\t\t\t\t{\n\t\t\t\t\tcb(json::array());\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tjson endpoints;\n\t\t\t\t\tfor (auto item :\n\t\t\t\t\t\tfx::GetIteratorView(\n\t\t\t\t\t\t\tstd::make_pair(\n\t\t\t\t\t\t\t\tboost::algorithm::make_split_iterator(\n\t\t\t\t\t\t\t\t\tendpointList,\n\t\t\t\t\t\t\t\t\tboost::algorithm::token_finder(\n\t\t\t\t\t\t\t\t\t\tboost::algorithm::is_space(),\n\t\t\t\t\t\t\t\t\t\tboost::algorithm::token_compress_on\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\tboost::algorithm::split_iterator<std::string::iterator>()\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\t{\n\t\t\t\t\t\tauto endpoint = folly::range(&*item.begin(), &*item.end());\n\t\t\t\t\t\tendpoints += endpoint;\n\t\t\t\t\t}\n\t\t\t\t\tcb(endpoints);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcb(json(nullptr));\n\t\t});\n\n\t\tinstance->GetComponent<fx::ClientMethodRegistry>()->AddHandler(\"initConnect\", [=](const std::map<std::string, std::string>& postMap, const fwRefContainer<net::HttpRequest>& request, const std::function<void(const json&)>& cb)\n\t\t{\n\t\t\tauto sendError = [=](const std::string& error)\n\t\t\t{\n\t\t\t\tcb(json::object({ { \"error\", error } }));\n\t\t\t\tcb(json(nullptr));\n\t\t\t};\n\n\t\t\tauto gameServer = instance->GetComponent<fx::GameServer>();\n\n\t\t\tif (!gameServer->HasSettled())\n\t\t\t{\n\t\t\t\tsendError(\"The server is starting up.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tauto nameIt = postMap.find(\"name\");\n\t\t\tauto guidIt = postMap.find(\"guid\");\n\t\t\tauto gameBuildIt = postMap.find(\"gameBuild\");\n\t\t\tauto gameNameIt = postMap.find(\"gameName\");\n\n\t\t\tauto protocolIt = postMap.find(\"protocol\");\n\n\t\t\tif (nameIt == postMap.end() || guidIt == postMap.end() || protocolIt == postMap.end())\n\t\t\t{\n\t\t\t\tsendError(\"fields missing\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tauto name = nameIt->second;\n\t\t\tauto guid = guidIt->second;\n\t\t\tauto protocol = atoi(protocolIt->second.c_str());\n\t\t\tauto gameBuild = (gameBuildIt != postMap.end()) ? gameBuildIt->second : \"0\";\n\t\t\tauto gameName = (gameNameIt != postMap.end()) ? gameNameIt->second : \"\";\n\n\t\t\tif (protocol < 6)\n\t\t\t{\n\t\t\t\tsendError(\"Client/server version mismatch.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (fx::IsOneSync())\n\t\t\t{\n\t\t\t\tif (protocol < 11)\n\t\t\t\t{\n\t\t\t\t\tsendError(\"Client/server version mismatch.\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// verify game name\n\t\t\tbool validGameName = false;\n\t\t\tstd::string intendedGameName;\n\n\t\t\tswitch (instance->GetComponent<fx::GameServer>()->GetGameName())\n\t\t\t{\n\t\t\tcase fx::GameName::GTA4:\n\t\t\t\tintendedGameName = \"gta4\";\n\n\t\t\t\tif (gameName == \"gta4\")\n\t\t\t\t{\n\t\t\t\t\tvalidGameName = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase fx::GameName::GTA5:\n\t\t\t\tintendedGameName = \"gta5\";\n\n\t\t\t\tif (gameName.empty() || gameName == \"gta5\")\n\t\t\t\t{\n\t\t\t\t\tvalidGameName = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase fx::GameName::RDR3:\n\t\t\t\tintendedGameName = \"rdr3\";\n\n\t\t\t\tif (gameName == \"rdr3\")\n\t\t\t\t{\n\t\t\t\t\tvalidGameName = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!validGameName)\n\t\t\t{\n\t\t\t\tsendError(fmt::sprintf(\"Client/Server game mismatch: %s/%s\", gameName, intendedGameName));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// limit name length\n\t\t\tif (name.length() >= 200)\n\t\t\t{\n\t\t\t\t// TODO: cut this off at a sane UTF-8 position\n\t\t\t\tname = name.substr(0, 200);\n\t\t\t}\n\n\t\t\tTicketData ticketData;\n\n\t\t\tif (!lanVar->GetValue())\n\t\t\t{\n\t\t\t\tauto ticketIt = postMap.find(\"cfxTicket\");\n\n\t\t\t\tif (ticketIt == postMap.end())\n\t\t\t\t{\n\t\t\t\t\tsendError(\"No authentication ticket was specified.\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tstd::string ticketError;\n\n\t\t\t\t\tif (!VerifyTicket(guid, ticketIt->second, &ticketError))\n\t\t\t\t\t{\n\t\t\t\t\t\tsendError(fmt::sprintf(\"Ticket authorization failed. %s\", ticketError));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tauto optionalTicket = VerifyTicketEx(ticketIt->second);\n\n\t\t\t\t\tif (!optionalTicket)\n\t\t\t\t\t{\n\t\t\t\t\t\tsendError(\"Ticket authorization failed. (2)\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tticketData = *optionalTicket;\n\t\t\t\t}\n\t\t\t\tcatch (const std::exception& e)\n\t\t\t\t{\n\t\t\t\t\tsendError(fmt::sprintf(\"Parsing error while verifying ticket. %s\", e.what()));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::string token = boost::uuids::to_string(boost::uuids::basic_random_generator<boost::random_device>()());\n\n\t\t\tjson data = json::object();\n\t\t\tdata[\"protocol\"] = 5;\n\t\t\tdata[\"bitVersion\"] = 0x202103292050;\n\t\t\tdata[\"sH\"] = shVar->GetValue();\n\t\t\tdata[\"enhancedHostSupport\"] = ehVar->GetValue() && !fx::IsOneSync();\n\t\t\tdata[\"onesync\"] = fx::IsOneSync();\n\t\t\tdata[\"onesync_big\"] = fx::IsBigMode();\n\t\t\tdata[\"onesync_lh\"] = fx::IsLengthHack();\n\t\t\tdata[\"token\"] = token;\n\t\t\tdata[\"gamename\"] = gameName;\n\n\t\t\tauto clientRegistry = instance->GetComponent<fx::ClientRegistry>();\n\n\t\t\tdata[\"netlibVersion\"] = gameServer->GetNetLibVersion();\n\t\t\tdata[\"maxClients\"] = atoi(gameServer->GetVariable(\"sv_maxclients\").c_str());\n\n\t\t\t{\n\t\t\t\tauto oldClient = clientRegistry->GetClientByGuid(guid);\n\n\t\t\t\tif (oldClient)\n\t\t\t\t{\n\t\t\t\t\tgameServer->DropClient(oldClient, \"Reconnecting\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauto ra = request->GetRemoteAddress();\n\n\t\t\tstatic std::atomic<uint32_t> g_tempIds;\n\t\t\tauto tempId = g_tempIds.fetch_add(1);\n\n\t\t\tauto client = clientRegistry->MakeClient(guid);\n\t\t\tclient->SetName(name);\n\t\t\tclient->SetConnectionToken(token);\n\t\t\tclient->SetTcpEndPoint(ra.substr(0, ra.find_last_of(':')));\n\t\t\tclient->SetNetId(0x10000 + tempId);\n\n\t\t\t// add the entitlement hash if needed\n\t\t\tif (ticketData.entitlementHash)\n\t\t\t{\n\t\t\t\tauto& hash = *ticketData.entitlementHash;\n\t\t\t\tclient->SetData(\"entitlementHash\", fmt::sprintf(\"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\",\n\t\t\t\t\thash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7], hash[8], hash[9],\n\t\t\t\t\thash[10], hash[11], hash[12], hash[13], hash[14], hash[15], hash[16], hash[17], hash[18], hash[19]));\n\t\t\t}\n\n\t\t\tbool gameNameMatch = false;\n\n\t\t\tif (ticketData.extraJson)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tjson json = json::parse(*ticketData.extraJson);\n\n\t\t\t\t\tif (json[\"gn\"].is_string())\n\t\t\t\t\t{\n\t\t\t\t\t\tauto sentGameName = json[\"gn\"].get<std::string>();\n\n\t\t\t\t\t\tif (sentGameName == intendedGameName)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tgameNameMatch = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (std::exception& e)\n\t\t\t\t{\n\n\t\t\t\t}\n\n\t\t\t\tclient->SetData(\"entitlementJson\", *ticketData.extraJson);\n\t\t\t}\n\n\t\t\tif (lanVar->GetValue())\n\t\t\t{\n\t\t\t\tgameNameMatch = true;\n\t\t\t}\n\n\t\t\tif (!gameNameMatch)\n\t\t\t{\n\t\t\t\tsendError(\"CitizenFX ticket authorization failed. (3)\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclient->Touch();\n\n\t\t\tauto it = g_serverProviders.begin();\n\n\t\t\tfx::ClientWeakPtr clientWeak{ client };\n\t\t\tauto done = [=]()\n\t\t\t{\n\t\t\t\tauto lockedClient = clientWeak.lock();\n\t\t\t\tif (!lockedClient)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tauto didSucceed = std::make_shared<bool>(false);\n\t\t\t\tauto weakSuccess = std::weak_ptr<bool>(didSucceed);\n\n\t\t\t\tauto allowClient = [=]()\n\t\t\t\t{\n\t\t\t\t\tauto client = clientWeak.lock();\n\n\t\t\t\t\tif (client)\n\t\t\t\t\t{\n\t\t\t\t\t\tclient->SetData(\"deferralPtr\", std::any());\n\t\t\t\t\t\tclient->SetData(\"passedValidation\", true);\n\t\t\t\t\t\tclient->SetData(\"canBeDead\", false);\n\t\t\t\t\t}\n\n\t\t\t\t\tauto success = weakSuccess.lock();\n\n\t\t\t\t\tif (success)\n\t\t\t\t\t{\n\t\t\t\t\t\t*success = true;\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tauto addData = [](json& data, const std::shared_ptr<fx::ClientDeferral>& deferrals)\n\t\t\t\t{\n\t\t\t\t\tjson handoverData = json::object();\n\n\t\t\t\t\tfor (const auto& [ key, value ] : deferrals->GetHandoverData())\n\t\t\t\t\t{\n\t\t\t\t\t\thandoverData[key] = json::parse(value);\n\t\t\t\t\t}\n\n\t\t\t\t\tdata[\"handover\"] = std::move(handoverData);\n\t\t\t\t};\n\n\t\t\t\tint maxTrust = INT_MIN;\n\t\t\t\tint minVariance = INT_MAX;\n\n\t\t\t\tfor (const auto& identifier : lockedClient->GetIdentifiers())\n\t\t\t\t{\n\t\t\t\t\tstd::string idType = identifier.substr(0, identifier.find_first_of(':'));\n\n\t\t\t\t\tauto provider = g_providersByType[idType];\n\n\t\t\t\t\tif (provider)\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxTrust = std::max(provider->GetTrustLevel(), maxTrust);\n\t\t\t\t\t\tminVariance = std::min(provider->GetVarianceLevel(), minVariance);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (maxTrust < minTrustVar->GetValue() || minVariance > maxVarianceVar->GetValue())\n\t\t\t\t{\n\t\t\t\t\tclientRegistry->RemoveClient(lockedClient);\n\n\t\t\t\t\tsendError(\"You can not join this server due to your identifiers being insufficient. Please try starting Steam or another identity provider and try again.\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tauto svGame = instance->GetComponent<fx::GameServer>()->GetGameName();\n\t\t\t\tbool canEnforceBuild = (svGame == fx::GameName::GTA5 || svGame == fx::GameName::RDR3);\n\n\t\t\t\tif (canEnforceBuild && !enforceGameBuildVar->GetValue().empty() && enforceGameBuildVar->GetValue() != gameBuild)\n\t\t\t\t{\n\t\t\t\t\tclientRegistry->RemoveClient(lockedClient);\n\n\t\t\t\t\tsendError(\n\t\t\t\t\t\tfmt::sprintf(\n\t\t\t\t\t\t\t\"This server requires a different game build (%s) from the one you're using (%s).%s\",\n\t\t\t\t\t\t\tenforceGameBuildVar->GetValue(),\n\t\t\t\t\t\t\tgameBuild,\n\t\t\t\t\t\t\t(svGame == fx::GameName::GTA5) ? \" Tell the server owner to remove this check.\" : \"\"\n\t\t\t\t\t\t)\n\t\t\t\t\t);\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tauto resman = instance->GetComponent<fx::ResourceManager>();\n\t\t\t\tauto eventManager = resman->GetComponent<fx::ResourceEventManagerComponent>();\n\t\t\t\tauto cbComponent = resman->GetComponent<fx::ResourceCallbackComponent>();\n\n\t\t\t\t// TODO: replace with event stacks once implemented\n\t\t\t\tauto noReason = std::make_shared<std::shared_ptr<std::string>>();\n\t\t\t\t*noReason = std::make_shared<std::string>(\"Resource prevented connection.\");\n\t\t\t\t\n\t\t\t\tauto deferrals = std::make_shared<std::shared_ptr<fx::ClientDeferral>>();\n\t\t\t\t*deferrals = std::make_shared<fx::ClientDeferral>(instance, lockedClient);\n\n\t\t\t\tlockedClient->SetData(\"deferralPtr\", std::weak_ptr<fx::ClientDeferral>(*deferrals));\n\n\t\t\t\t// *copy* the callback into a *shared* reference\n\t\t\t\tauto cbRef = std::make_shared<std::shared_ptr<std::decay_t<decltype(cb)>>>(std::make_shared<std::decay_t<decltype(cb)>>(cb));\n\n\t\t\t\t(*deferrals)->SetMessageCallback([cbRef](const std::string& message)\n\t\t\t\t{\n\t\t\t\t\tauto ref1 = *cbRef;\n\n\t\t\t\t\tif (ref1)\n\t\t\t\t\t{\n\t\t\t\t\t\t(*ref1)(json::object({ { \"defer\", true }, { \"message\", message }, { \"deferVersion\", 2 } }));\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t(*deferrals)->SetCardCallback([cbRef, token](const std::string& card)\n\t\t\t\t{\n\t\t\t\t\tauto ref1 = *cbRef;\n\n\t\t\t\t\tif (ref1)\n\t\t\t\t\t{\n\t\t\t\t\t\t(*ref1)(json::object({ { \"defer\", true }, { \"card\", card }, { \"token\", token }, { \"deferVersion\", 2 } }));\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t(*deferrals)->SetResolveCallback([addData, data, deferrals, cbRef, allowClient]()\n\t\t\t\t{\n\t\t\t\t\tallowClient();\n\n\t\t\t\t\tjson dataNew = data;\n\n\t\t\t\t\tif (deferrals && *deferrals)\n\t\t\t\t\t{\n\t\t\t\t\t\taddData(dataNew, *deferrals);\n\t\t\t\t\t}\n\n\t\t\t\t\tauto ref1 = *cbRef;\n\n\t\t\t\t\tif (ref1)\n\t\t\t\t\t{\n\t\t\t\t\t\t(**cbRef)(dataNew);\n\t\t\t\t\t\t(**cbRef)(json(nullptr));\n\t\t\t\t\t}\n\n\t\t\t\t\t*cbRef = nullptr;\n\t\t\t\t\t*deferrals = nullptr;\n\t\t\t\t});\n\n\t\t\t\tauto earlyReject = std::make_shared<bool>(false);\n\t\t\t\tauto weakEarlyReject = std::weak_ptr(earlyReject);\n\t\t\t\tauto weakNoReason = std::weak_ptr(noReason);\n\n\t\t\t\t(*deferrals)->SetRejectCallback([deferrals, cbRef, clientWeak, clientRegistry, weakEarlyReject, weakNoReason](const std::string& message)\n\t\t\t\t{\n\t\t\t\t\tauto earlyReject = weakEarlyReject.lock();\n\t\t\t\t\tauto noReason = weakNoReason.lock();\n\n\t\t\t\t\tif (earlyReject && noReason)\n\t\t\t\t\t{\n\t\t\t\t\t\t*noReason = std::make_shared<std::string>(message);\n\t\t\t\t\t\t*earlyReject = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tauto newLockedClient = clientWeak.lock();\n\t\t\t\t\tif (newLockedClient)\n\t\t\t\t\t{\n\t\t\t\t\t\tclientRegistry->RemoveClient(newLockedClient);\n\n\t\t\t\t\t\tauto ref1 = *cbRef;\n\n\t\t\t\t\t\tif (ref1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t(**cbRef)(json::object({ { \"error\", message } }));\n\t\t\t\t\t\t\t(**cbRef)(json(nullptr));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t*cbRef = nullptr;\n\t\t\t\t\t*deferrals = nullptr;\n\t\t\t\t});\n\n\t\t\t\trequest->SetCancelHandler([cbRef, deferrals, clientWeak, clientRegistry, didSucceed]()\n\t\t\t\t{\n\t\t\t\t\tauto newLockedClient = clientWeak.lock();\n\t\t\t\t\tif (!*didSucceed && newLockedClient)\n\t\t\t\t\t{\n\t\t\t\t\t\tclientRegistry->RemoveClient(newLockedClient);\n\t\t\t\t\t}\n\n\t\t\t\t\t*cbRef = nullptr;\n\t\t\t\t\t*deferrals = nullptr;\n\t\t\t\t});\n\n\t\t\t\tgscomms_execute_callback_on_main_thread([=]\n\t\t\t\t{\n\t\t\t\t\tauto deferralsRef = *deferrals;\n\n\t\t\t\t\t/*NETEV playerConnecting SERVER\n\t\t\t\t\t/#*\n\t\t\t\t\t * A server-side event that is triggered when a player is trying to connect.\n\t\t\t\t\t *\n\t\t\t\t\t * This event can be canceled to reject the player *instantly*, assuming you haven't yielded.\n\t\t\t\t\t *\n\t\t\t\t\t * @param playerName - The display name of the player connecting.\n\t\t\t\t\t * @param setKickReason - A function used to set a reason message for when the event is canceled.\n\t\t\t\t\t * @param deferrals - An object to control deferrals.\n\t\t\t\t\t * @param source - The player's *temporary* NetID (a number in Lua/JS), **not a real argument, use [FromSource] or source**.\n\t\t\t\t\t #/\n\t\t\t\t\tdeclare function playerConnecting(playerName: string, setKickReason: (reason: string) => void, deferrals: {\n\t\t\t\t\t\t/#*\n\t\t\t\t\t\t * `deferrals.defer` will initialize deferrals for the current resource. It is required to wait for at least a tick after calling defer before calling `update`, `presentCard` or `done`.\n\t\t\t\t\t\t #/\n\t\t\t\t\t\tdefer(): void,\n\n\t\t\t\t\t\t/#*\n\t\t\t\t\t\t * `deferrals.update` will send a progress message to the connecting client.\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * @param message - The string to send to the client.\n\t\t\t\t\t\t #/\n\t\t\t\t\t\tupdate(message: string): void,\n\n\t\t\t\t\t\t/#*\n\t\t\t\t\t\t * `deferrals.presentCard` will send an [Adaptive Card](https://adaptivecards.io/) to the client.\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * @param card - An object containing card data, or a serialized JSON string with the card information.\n\t\t\t\t\t\t * @param cb - If present, will be invoked on an `Action.Submit` event from the Adaptive Card.\n\t\t\t\t\t\t #/\n\t\t\t\t\t\tpresentCard(\n\t\t\t\t\t\t\tcard: object | string,\n\t\t\t\t\t\t\tcb?:\n\t\t\t\t\t\t\t/#*\n\t\t\t\t\t\t\t * A callback to be invoked for `Action.Submit`.\n\t\t\t\t\t\t\t *\n\t\t\t\t\t\t\t * @param data - A parsed version of the data sent from the card.\n\t\t\t\t\t\t\t * @param rawData - A JSON string containing the data sent from the card.\n\t\t\t\t\t\t\t #/\n\t\t\t\t\t\t\t  (data: any, rawData: string) => void\n\t\t\t\t\t\t): void,\n\n\t\t\t\t\t\t/#*\n\t\t\t\t\t\t * `deferrals.done` finalizes a deferral. It is required to wait for at least a tick before calling `done` after calling a prior deferral method.\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * @param failureReason - If specified, the connection will be refused, and the user will see the specified message as a result. If this is not specified, the user will be allowed to connect.\n\t\t\t\t\t\t #/\n\t\t\t\t\t\tdone(failureReason?: string): void,\n\n\t\t\t\t\t\t/#*\n\t\t\t\t\t\t * `deferrals.handover` adds handover data for the client to be able to use at a later point.\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * @param data - Data to pass to the connecting client.\n\t\t\t\t\t\t #/\n\t\t\t\t\t\thandover(data: { [key: string]: any }): void,\n\t\t\t\t\t}, source: string): void;\n\t\t\t\t\t*/\n\t\t\t\t\tbool shouldAllow = (deferralsRef) ? (eventManager->TriggerEvent2(\"playerConnecting\", { fmt::sprintf(\"internal-net:%d\", lockedClient->GetNetId()) }, lockedClient->GetName(), cbComponent->CreateCallback([noReason](const msgpack::unpacked& unpacked)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto obj = unpacked.get().as<std::vector<msgpack::object>>();\n\n\t\t\t\t\t\tif (obj.size() == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t**noReason = obj[0].as<std::string>();\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t\tdeferralsRef->GetCallbacks())) : false;\n\n\t\t\t\t\tif (!shouldAllow)\n\t\t\t\t\t{\n\t\t\t\t\t\tclientRegistry->RemoveClient(lockedClient);\n\n\t\t\t\t\t\tsendError(**noReason);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (*earlyReject)\n\t\t\t\t\t{\n\t\t\t\t\t\tclientRegistry->RemoveClient(lockedClient);\n\n\t\t\t\t\t\tsendError(**noReason);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// was the deferral already completed/canceled this frame? if so, just don't respond at all\n\t\t\t\t\tif (!deferralsRef)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!deferralsRef->IsDeferred())\n\t\t\t\t\t{\n\t\t\t\t\t\tallowClient();\n\n\t\t\t\t\t\tjson dataNew = data;\n\t\t\t\t\t\taddData(dataNew, *deferrals);\n\n\t\t\t\t\t\t*cbRef = nullptr;\n\t\t\t\t\t\t*deferrals = nullptr;\n\n\t\t\t\t\t\tcb(dataNew);\n\t\t\t\t\t\tcb(json(nullptr));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\n\t\t\t// seriously C++?\n\t\t\tauto runOneIdentifier = std::make_shared<std::unique_ptr<std::function<void(decltype(g_serverProviders.begin()))>>>();\n\t\t\t*runOneIdentifier = std::make_unique<std::function<void(decltype(g_serverProviders.begin()))>>([=](auto it)\n\t\t\t{\n\t\t\t\tif (it == g_serverProviders.end())\n\t\t\t\t{\n\t\t\t\t\tdone();\n\n\t\t\t\t\t// unset the callback\n\t\t\t\t\t*runOneIdentifier = nullptr;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto auth = (*it);\n\t\t\t\t\tauto thisIt = ++it;\n\n\t\t\t\t\t// if the client randomly disconnects, let's just bail\n\t\t\t\t\tauto clientLocked = clientWeak.lock();\n\t\t\t\t\tif (!clientLocked)\n\t\t\t\t\t{\n\t\t\t\t\t\t// unset the callback\n\t\t\t\t\t\t*runOneIdentifier = nullptr;\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tauth->RunAuthentication(clientLocked, request, postMap, [=](boost::optional<std::string> err)\n\t\t\t\t\t{\n\t\t\t\t\t\t// if the client randomly disconnects, let's just bail (again)\n\t\t\t\t\t\tauto newClientLocked = clientWeak.lock();\n\t\t\t\t\t\tif (!newClientLocked)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// unset the callback\n\t\t\t\t\t\t\t*runOneIdentifier = nullptr;\n\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if an auth method fails, bail\n\t\t\t\t\t\tif (err)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclientRegistry->RemoveClient(newClientLocked);\n\n\t\t\t\t\t\t\tsendError(*err);\n\n\t\t\t\t\t\t\t// unset the callback\n\t\t\t\t\t\t\t*runOneIdentifier = nullptr;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t(**runOneIdentifier)(thisIt);\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(**runOneIdentifier)(it);\n\t\t});\n\n\t\tinstance->GetComponent<fx::ClientMethodRegistry>()->AddHandler(\"submitCard\", [=](const std::map<std::string, std::string>& postMap, const fwRefContainer<net::HttpRequest>& request, const std::function<void(const json&)>& cb)\n\t\t{\n\t\t\tauto dataIt = postMap.find(\"data\");\n\t\t\tauto tokenIt = postMap.find(\"token\");\n\n\t\t\tif (dataIt == postMap.end() || tokenIt == postMap.end())\n\t\t\t{\n\t\t\t\tcb(json::object({ {\"error\", \"fields missing\"} }));\n\t\t\t\tcb(json(nullptr));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tauto clientRegistry = instance->GetComponent<fx::ClientRegistry>();\n\t\t\tauto client = clientRegistry->GetClientByConnectionToken(tokenIt->second);\n\n\t\t\tif (!client)\n\t\t\t{\n\t\t\t\tcb(json::object({ {\"error\", \"no client\"} }));\n\t\t\t\tcb(json(nullptr));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tauto deferralRef = client->GetData(\"deferralPtr\");\n\n\t\t\tif (deferralRef.has_value())\n\t\t\t{\n\t\t\t\tauto deferralPtr = std::any_cast<std::weak_ptr<fx::ClientDeferral>>(deferralRef);\n\t\t\t\tauto deferrals = deferralPtr.lock();\n\n\t\t\t\tif (deferrals)\n\t\t\t\t{\n\t\t\t\t\tdeferrals->HandleCardResponse(dataIt->second);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcb(json::object({ { \"result\", \"ok\" } }));\n\t\t\tcb(json(nullptr));\n\t\t});\n\t}, 50);\n});\n", "meta": {"hexsha": "29e3080585ee60262b32efb628d41974aea6cea5", "size": 26762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/components/citizen-server-impl/src/InitConnectMethod.cpp", "max_stars_repo_name": "mkljczk/fivem", "max_stars_repo_head_hexsha": "187b2e5f922297bcbde5cfb1db70815223c53680", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T00:40:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T09:46:21.000Z", "max_issues_repo_path": "code/components/citizen-server-impl/src/InitConnectMethod.cpp", "max_issues_repo_name": "big-rip/fivem-1", "max_issues_repo_head_hexsha": "c08af22110802e77816dfdde29df1662f8dea563", "max_issues_repo_licenses": ["MIT"], "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/components/citizen-server-impl/src/InitConnectMethod.cpp", "max_forks_repo_name": "big-rip/fivem-1", "max_forks_repo_head_hexsha": "c08af22110802e77816dfdde29df1662f8dea563", "max_forks_repo_licenses": ["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.2115572968, "max_line_length": 251, "alphanum_fraction": 0.6382183693, "num_tokens": 7549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616831, "lm_q2_score": 0.2720245392906821, "lm_q1q2_score": 0.17910571725121427}}
{"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 2013, 2014.\n// Modifications copyright (c) 2013, 2014 Oracle and/or its affiliates.\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// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP\n\n\n#include <cstddef>\n\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/static_visitor.hpp>\n#include <boost/variant/variant_fwd.hpp>\n\n#include <boost/geometry/algorithms/not_implemented.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n\n#include <boost/geometry/strategies/cartesian/point_in_box.hpp>\n#include <boost/geometry/strategies/cartesian/box_in_box.hpp>\n#include <boost/geometry/strategies/default_strategy.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace covered_by {\n\nstruct use_point_in_geometry\n{\n    template <typename Geometry1, typename Geometry2, typename Strategy>\n    static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& strategy)\n    {\n        return detail::within::point_in_geometry(geometry1, geometry2, strategy) >= 0;\n    }\n};\n\nstruct use_relate\n{\n    template <typename Geometry1, typename Geometry2, typename Strategy>\n    static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& /*strategy*/)\n    {\n        return Strategy::apply(geometry1, geometry2);\n    }\n};\n\n}} // namespace detail::covered_by\n#endif // DOXYGEN_NO_DETAIL\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\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 covered_by\n    : not_implemented<Tag1, Tag2>\n{};\n\n\ntemplate <typename Point, typename Box>\nstruct covered_by<Point, Box, point_tag, box_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(Point const& point, Box const& box, Strategy const& strategy)\n    {\n        ::boost::ignore_unused_variable_warning(strategy);\n        return strategy.apply(point, box);\n    }\n};\n\ntemplate <typename Box1, typename Box2>\nstruct covered_by<Box1, Box2, box_tag, box_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(Box1 const& box1, Box2 const& box2, Strategy const& strategy)\n    {\n        assert_dimension_equal<Box1, Box2>();\n        ::boost::ignore_unused_variable_warning(strategy);\n        return strategy.apply(box1, box2);\n    }\n};\n\n\n// P/P\n\ntemplate <typename Point1, typename Point2>\nstruct covered_by<Point1, Point2, point_tag, point_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename MultiPoint>\nstruct covered_by<Point, MultiPoint, point_tag, multi_point_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\n// P/L\n\ntemplate <typename Point, typename Segment>\nstruct covered_by<Point, Segment, point_tag, segment_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename Linestring>\nstruct covered_by<Point, Linestring, point_tag, linestring_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename MultiLinestring>\nstruct covered_by<Point, MultiLinestring, point_tag, multi_linestring_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\n// P/A\n\ntemplate <typename Point, typename Ring>\nstruct covered_by<Point, Ring, point_tag, ring_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename Polygon>\nstruct covered_by<Point, Polygon, point_tag, polygon_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename MultiPolygon>\nstruct covered_by<Point, MultiPolygon, point_tag, multi_polygon_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\n// L/L\n\ntemplate <typename Linestring1, typename Linestring2>\nstruct covered_by<Linestring1, Linestring2, linestring_tag, linestring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Linestring, typename MultiLinestring>\nstruct covered_by<Linestring, MultiLinestring, linestring_tag, multi_linestring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring, typename Linestring>\nstruct covered_by<MultiLinestring, Linestring, multi_linestring_tag, linestring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring1, typename MultiLinestring2>\nstruct covered_by<MultiLinestring1, MultiLinestring2, multi_linestring_tag, multi_linestring_tag>\n    : public detail::covered_by::use_relate\n{};\n\n// L/A\n\ntemplate <typename Linestring, typename Ring>\nstruct covered_by<Linestring, Ring, linestring_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring, typename Ring>\nstruct covered_by<MultiLinestring, Ring, multi_linestring_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Linestring, typename Polygon>\nstruct covered_by<Linestring, Polygon, linestring_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring, typename Polygon>\nstruct covered_by<MultiLinestring, Polygon, multi_linestring_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Linestring, typename MultiPolygon>\nstruct covered_by<Linestring, MultiPolygon, linestring_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring, typename MultiPolygon>\nstruct covered_by<MultiLinestring, MultiPolygon, multi_linestring_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\n// A/A\n\ntemplate <typename Ring1, typename Ring2>\nstruct covered_by<Ring1, Ring2, ring_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Ring, typename Polygon>\nstruct covered_by<Ring, Polygon, ring_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Polygon, typename Ring>\nstruct covered_by<Polygon, Ring, polygon_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Polygon1, typename Polygon2>\nstruct covered_by<Polygon1, Polygon2, polygon_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Ring, typename MultiPolygon>\nstruct covered_by<Ring, MultiPolygon, ring_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiPolygon, typename Ring>\nstruct covered_by<MultiPolygon, Ring, multi_polygon_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Polygon, typename MultiPolygon>\nstruct covered_by<Polygon, MultiPolygon, polygon_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiPolygon, typename Polygon>\nstruct covered_by<MultiPolygon, Polygon, multi_polygon_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiPolygon1, typename MultiPolygon2>\nstruct covered_by<MultiPolygon1, MultiPolygon2, multi_polygon_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy {\n\nstruct covered_by\n{\n    template <typename Geometry1, typename Geometry2, typename Strategy>\n    static inline bool apply(Geometry1 const& geometry1,\n                             Geometry2 const& geometry2,\n                             Strategy const& strategy)\n    {\n        concept::within::check\n            <\n                typename tag<Geometry1>::type,\n                typename tag<Geometry2>::type,\n                typename tag_cast<typename tag<Geometry2>::type, areal_tag>::type,\n                Strategy\n            >();\n        concept::check<Geometry1 const>();\n        concept::check<Geometry2 const>();\n        assert_dimension_equal<Geometry1, Geometry2>();\n\n        return dispatch::covered_by<Geometry1, Geometry2>::apply(geometry1,\n                                                                 geometry2,\n                                                                 strategy);\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    static inline bool apply(Geometry1 const& geometry1,\n                             Geometry2 const& geometry2,\n                             default_strategy)\n    {\n        typedef typename point_type<Geometry1>::type point_type1;\n        typedef typename point_type<Geometry2>::type point_type2;\n\n        typedef typename strategy::covered_by::services::default_strategy\n            <\n                typename tag<Geometry1>::type,\n                typename tag<Geometry2>::type,\n                typename tag<Geometry1>::type,\n                typename tag_cast<typename tag<Geometry2>::type, areal_tag>::type,\n                typename tag_cast\n                    <\n                        typename cs_tag<point_type1>::type, spherical_tag\n                    >::type,\n                typename tag_cast\n                    <\n                        typename cs_tag<point_type2>::type, spherical_tag\n                    >::type,\n                Geometry1,\n                Geometry2\n            >::type strategy_type;\n\n        return covered_by::apply(geometry1, geometry2, strategy_type());\n    }\n};\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_variant {\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct covered_by\n{\n    template <typename Strategy>\n    static inline bool apply(Geometry1 const& geometry1,\n                             Geometry2 const& geometry2,\n                             Strategy const& strategy)\n    {\n        return resolve_strategy::covered_by\n                               ::apply(geometry1, geometry2, strategy);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T), typename Geometry2>\nstruct covered_by<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2>\n{\n    template <typename Strategy>\n    struct visitor: boost::static_visitor<bool>\n    {\n        Geometry2 const& m_geometry2;\n        Strategy const& m_strategy;\n\n        visitor(Geometry2 const& geometry2, Strategy const& strategy)\n        : m_geometry2(geometry2), m_strategy(strategy) {}\n\n        template <typename Geometry1>\n        bool operator()(Geometry1 const& geometry1) const\n        {\n            return covered_by<Geometry1, Geometry2>\n                   ::apply(geometry1, m_geometry2, m_strategy);\n        }\n    };\n\n    template <typename Strategy>\n    static inline bool\n    apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry1,\n          Geometry2 const& geometry2,\n          Strategy const& strategy)\n    {\n        return boost::apply_visitor(visitor<Strategy>(geometry2, strategy), geometry1);\n    }\n};\n\ntemplate <typename Geometry1, BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct covered_by<Geometry1, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    template <typename Strategy>\n    struct visitor: boost::static_visitor<bool>\n    {\n        Geometry1 const& m_geometry1;\n        Strategy const& m_strategy;\n\n        visitor(Geometry1 const& geometry1, Strategy const& strategy)\n        : m_geometry1(geometry1), m_strategy(strategy) {}\n\n        template <typename Geometry2>\n        bool operator()(Geometry2 const& geometry2) const\n        {\n            return covered_by<Geometry1, Geometry2>\n                   ::apply(m_geometry1, geometry2, m_strategy);\n        }\n    };\n\n    template <typename Strategy>\n    static inline bool\n    apply(Geometry1 const& geometry1,\n          boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry2,\n          Strategy const& strategy)\n    {\n        return boost::apply_visitor(visitor<Strategy>(geometry1, strategy), geometry2);\n    }\n};\n\ntemplate <\n    BOOST_VARIANT_ENUM_PARAMS(typename T1),\n    BOOST_VARIANT_ENUM_PARAMS(typename T2)\n>\nstruct covered_by<\n    boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)>,\n    boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)>\n>\n{\n    template <typename Strategy>\n    struct visitor: boost::static_visitor<bool>\n    {\n        Strategy const& m_strategy;\n\n        visitor(Strategy const& strategy): m_strategy(strategy) {}\n\n        template <typename Geometry1, typename Geometry2>\n        bool operator()(Geometry1 const& geometry1,\n                        Geometry2 const& geometry2) const\n        {\n            return covered_by<Geometry1, Geometry2>\n                   ::apply(geometry1, geometry2, m_strategy);\n        }\n    };\n\n    template <typename Strategy>\n    static inline bool\n    apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const& geometry1,\n          boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const& geometry2,\n          Strategy const& strategy)\n    {\n        return boost::apply_visitor(visitor<Strategy>(strategy), geometry1, geometry2);\n    }\n};\n\n} // namespace resolve_variant\n\n\n/*!\n\\brief \\brief_check12{is inside or on border}\n\\ingroup covered_by\n\\details \\details_check12{covered_by, is inside or on border}.\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\param geometry1 \\param_geometry which might be inside or on the border of the second geometry\n\\param geometry2 \\param_geometry which might cover the first geometry\n\\return true if geometry1 is inside of or on the border of geometry2,\n    else false\n\\note The default strategy is used for covered_by detection\n\n\\qbk{[include reference/algorithms/covered_by.qbk]}\n\n */\ntemplate<typename Geometry1, typename Geometry2>\ninline bool covered_by(Geometry1 const& geometry1, Geometry2 const& geometry2)\n{\n    return resolve_variant::covered_by<Geometry1, Geometry2>\n                          ::apply(geometry1, geometry2, default_strategy());\n}\n\n/*!\n\\brief \\brief_check12{is inside or on border} \\brief_strategy\n\\ingroup covered_by\n\\details \\details_check12{covered_by, is inside or on border}, \\brief_strategy. \\details_strategy_reasons\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\param geometry1 \\param_geometry which might be inside or on the border of the second geometry\n\\param geometry2 \\param_geometry which might cover the first geometry\n\\param strategy strategy to be used\n\\return true if geometry1 is inside of or on the border of geometry2,\n    else false\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/covered_by.qbk]}\n\n*/\ntemplate<typename Geometry1, typename Geometry2, typename Strategy>\ninline bool covered_by(Geometry1 const& geometry1, Geometry2 const& geometry2,\n        Strategy const& strategy)\n{\n    return resolve_variant::covered_by<Geometry1, Geometry2>\n                          ::apply(geometry1, geometry2, strategy);\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP\n", "meta": {"hexsha": "eb8e732409957c328d579cebe5fe5e30177e02c9", "size": 15326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/algorithms/covered_by.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/geometry/algorithms/covered_by.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": 39.0, "max_issues_repo_issues_event_min_datetime": "2019-07-06T02:51:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T11:48:33.000Z", "max_forks_repo_path": "deps/cinder/include/boost/geometry/algorithms/covered_by.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": 275.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T08:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:06:07.000Z", "avg_line_length": 32.3333333333, "max_line_length": 114, "alphanum_fraction": 0.7132324155, "num_tokens": 3427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.17903828069916697}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/map.hpp>\n#include <stf.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n\nSTF_CASE(\"map TO DO\")\n{\n  STF_FAIL(\"TO DO\");\n\n}\n\n", "meta": {"hexsha": "29460a6eaed0fc55209d9396409799e72dbccf82", "size": 781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/map.cpp", "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": "test/function/scalar/map.cpp", "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": "test/function/scalar/map.cpp", "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": 30.0384615385, "max_line_length": 100, "alphanum_fraction": 0.5505761844, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17896254398853456}}
{"text": "#include \"sim_map.h\"\n#include \"sim_robot.h\"\n#include \"sim_lidar.h\"\n#include \"sim_window.h\"\n#include \"pfilter.h\"\n#include \"sim_landmark.h\"\n#include <cstdio>\n#include <armadillo>\n#include <SDL2/SDL.h>\n#include <cassert>\n#include <iostream>\n#include <cstdlib>\n\nusing namespace std;\nusing namespace arma;\n\n// This is a simpler landmark extractor with the goal of extracting the location of the landmarks easily\nvoid sim_tag_extract(mat &tag_landmarks,\n    mat &sensor_vals,\n    vector<sim_landmark> &landmarks,\n    sim_robot &robot,\n    sim_map &map) {\n  tag_landmarks = mat(2, landmarks.size());\n  for (int lid = 0; lid < landmarks.size(); lid++) {\n    tag_landmarks.col(lid) = landmarks[lid].sense(robot);\n  }\n}\n\nicube doubleImageSize(icube &image) {\n  icube newframe(image.n_rows/2, image.n_cols/2, 3);\n  for (uword i = 0; i < image.n_rows / 2; i++) {\n    for (uword j = 0; j < image.n_cols / 2; j++) {\n      newframe(i, j, 0) = (image(i*2, j*2, 0) + image(i*2+1, j*2, 0) + image(i*2, j*2+1, 0) + image(i*2+1, j*2+1, 0)) / 4;\n      newframe(i, j, 1) = (image(i*2, j*2, 1) + image(i*2+1, j*2, 1) + image(i*2, j*2+1, 1) + image(i*2+1, j*2+1, 1)) / 4;\n      newframe(i, j, 2) = (image(i*2, j*2, 2) + image(i*2+1, j*2, 2) + image(i*2, j*2+1, 2) + image(i*2+1, j*2+1, 2)) / 4;\n    }\n  }\n  return newframe;\n}\n\nicube partial_frame(icube frame, int x, int y, int width, int height) {\n  icube partial_frame(height, width, 3, fill::zeros);\n  for (int i = 0; i < (int)partial_frame.n_rows; i++) {\n    for (int j = 0; j < (int)partial_frame.n_cols; j++) {\n      int x_ = x - width/2 + j;\n      int y_ = y - height/2 + i;\n      if (x_ < 0 || x_ >= (int)frame.n_cols ||\n          y_ < 0 || y_ >= (int)frame.n_rows) {\n        continue;\n      }\n      partial_frame(i, j, 0) = frame(y_, x_, 0);\n      partial_frame(i, j, 1) = frame(y_, x_, 1);\n      partial_frame(i, j, 2) = frame(y_, x_, 2);\n    }\n  }\n  return partial_frame;\n}\n\nint main() {\n  srand(getpid());\n\n  // load the map (custom)\n  sim_map map;\n  map.load(\"bengC.jpg\");\n\n  // create the landmarks (custom)\n  vector<sim_landmark> landmarks;\n  landmarks.push_back(sim_landmark(88, 202));\n  landmarks.push_back(sim_landmark(601, 617));\n  landmarks.push_back(sim_landmark(0, 171));\n  landmarks.push_back(sim_landmark(98, 627));\n  landmarks.push_back(sim_landmark(384, 627));\n  landmarks.push_back(sim_landmark(1225, 627));\n  landmarks.push_back(sim_landmark(3400, 513));\n  landmarks.push_back(sim_landmark(3442, 583));\n  landmarks.push_back(sim_landmark(1961, 539));\n  landmarks.push_back(sim_landmark(762, 539));\n\n  // load the robot\n  sim_robot robot(&map);\n  robot.set_size(8);\n  robot.set_pose(70, 48, M_PI_2);\n  robot.set_noise(0.2, 0.05);\n\n  // load the lidar\n  sim_lidar lidar(&robot);\n  lidar.set_noise(1.0, 0.1);\n\n/////////////////////////\n//  START OF THE BOT\n/////////////////////////\n\n  // create the particle filter\n  pfilter pf(1000, &map, landmarks, 70, 48, M_PI_2);\n  pf.set_size(12);\n  pf.set_noise(0.2, 0.05);\n  \n  // start up the window\n  SDL_Surface *screen = sim_window::init(400, 400);\n  icube frame(map.n_rows, map.n_cols, 3, fill::zeros), newframe;\n  bool forward = false;\n  bool backward = false;\n  bool turn_left = false;\n  bool turn_right = false;\n  bool strafe_left = false;\n  bool strafe_right = false;\n\n  for (;;) {\n    // see if something is about to quit\n    SDL_Event *e;\n    bool done = false;\n    while ((e = sim_window::get_event())) {\n      if (e->type == SDL_QUIT) {\n        done = true;\n      } else if (e->type == SDL_KEYDOWN) {\n        // attempt to see if the user wants to make the robot move\n        if (e->key.keysym.sym == SDLK_w)  { forward = true; }\n        if (e->key.keysym.sym == SDLK_s)  { backward = true; }\n        if (e->key.keysym.sym == SDLK_q)  { turn_left = true; }\n        if (e->key.keysym.sym == SDLK_e)  { turn_right = true; }\n        if (e->key.keysym.sym == SDLK_a)  { strafe_left = true; }\n        if (e->key.keysym.sym == SDLK_d)  { strafe_right = true; }\n      } else if (e->type == SDL_KEYUP) {\n        if (e->key.keysym.sym == SDLK_w)  { forward = false; }\n        if (e->key.keysym.sym == SDLK_s)  { backward = false; }\n        if (e->key.keysym.sym == SDLK_q)  { turn_left = false; }\n        if (e->key.keysym.sym == SDLK_e)  { turn_right = false; }\n        if (e->key.keysym.sym == SDLK_a)  { strafe_left = false; }\n        if (e->key.keysym.sym == SDLK_d)  { strafe_right = false; }\n      }\n    }\n    if (done) {\n      break;\n    }\n\n    // update the robot\n    robot.move((strafe_right - strafe_left) * 4, (forward - backward) * 4, (turn_left - turn_right) * .1);\n    pf.move((strafe_right - strafe_left) * 4, (forward - backward) * 4, (turn_left - turn_right) * .1);\n    mat sensor_values = lidar.sense();\n    mat tag_landmarks;\n    sim_tag_extract(tag_landmarks, sensor_values, landmarks, robot, map);\n    pf.observe(tag_landmarks);\n\n    // predict the position\n    vec mu;\n    mat sigma;\n    pf.predict(mu, sigma);\n    cout << \"position: \" << mu(0) << \", \" << mu(1) << \", angle: \" << mu(2) * 180 / M_PI << \", error: \\n\" << sigma << endl;\n\n    // put stuff on the screen\n    map.blit(frame);\n    for (sim_landmark &lm : landmarks) {\n      lm.blit(frame);\n    }\n    //lidar.blit(frame);\n    pf.blit(frame);\n    //robot.blit(frame);\n    newframe = partial_frame(frame, (int)round(robot.x), (int)round(robot.y), screen->w, screen->h);\n    sim_window::blit(screen, newframe);\n    SDL_Delay(25);\n\n    // draw the screen\n    sim_window::update();\n  }\n\n  // clean up\n  sim_window::destroy();\n}\n", "meta": {"hexsha": "bd83ee5fd0c5b2a876ef67ab4154a8166237f4d9", "size": 5501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slam/particle_filter/sim.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "slam/particle_filter/sim.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slam/particle_filter/sim.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["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.550295858, "max_line_length": 122, "alphanum_fraction": 0.5997091438, "num_tokens": 1797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.17885224699709887}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2009-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NGT platform is licensed under the Apache License, Version 2.0 (the\n//  \"License\"); you may not use this file except in compliance with the\n//  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\n#include <vw/Math/EulerAngles.h>\n#include <vw/Camera/CameraSolve.h>\n#include <asp/Core/StereoSettings.h>\n#include <asp/Camera/RPCModel.h>\n#include <asp/Camera/RPC_XML.h>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\nnamespace asp {\n\n// -----------------------------------------------------------------\n// LinescanDGModel class functions\n\ntemplate <class PositionFuncT, class PoseFuncT>\nvw::camera::PinholeModel LinescanDGModel<PositionFuncT, PoseFuncT>::linescan_to_pinhole(double y) const {\n\n  double t = this->m_time_func( y );\n  return vw::camera::PinholeModel(this->m_position_func(t),  this->m_pose_func(t).rotation_matrix(),\n\t\t\t\t  this->m_focal_length, -this->m_focal_length,\n\t\t\t\t  -this->m_detector_origin[0], y - this->m_detector_origin[1]\n\t\t\t\t  );\n}\n\n\ntemplate <class PositionFuncT, class PoseFuncT>\nvw::Vector3 LinescanDGModel<PositionFuncT, PoseFuncT>::get_local_pixel_vector(vw::Vector2 const& pix) const {\n  vw::Vector3 local_vec(pix[0]+m_detector_origin[0], m_detector_origin[1], m_focal_length);\n  return normalize(local_vec);\n}\n\n\n\n// Here we use an initial guess for the line number\ntemplate <class PositionFuncT, class PoseFuncT>\nvw::Vector2 LinescanDGModel<PositionFuncT, PoseFuncT>::point_to_pixel(vw::Vector3 const& point, double starty) const {\n\n  // Use the uncorrected function to get a fast but good starting seed.\n  vw::camera::CameraGenericLMA model( this, point );\n  int status;\n  vw::Vector2 start = point_to_pixel_uncorrected(point, starty);\n\n  // Run the solver\n  vw::Vector3 objective(0, 0, 0);\n  const double ABS_TOL = 1e-16;\n  const double REL_TOL = 1e-16;\n  const int    MAX_ITERATIONS = 1e+5;\n  vw::Vector2 solution = vw::math::levenberg_marquardtFixed<vw::camera::CameraGenericLMA, 2,3>(model, start, objective, status,\n                                                       ABS_TOL, REL_TOL, MAX_ITERATIONS);\n  VW_ASSERT( status > 0,\n          vw::camera::PointToPixelErr() << \"Unable to project point into LinescanDG model\" );\n\n  return solution;\n}\n\n// Computing the uncorrected pixel location is much faster.\ntemplate <class PositionFuncT, class PoseFuncT>\nvw::Vector2 LinescanDGModel<PositionFuncT, PoseFuncT>::point_to_pixel_uncorrected(vw::Vector3 const& point, double starty) const {\n\n  // Solve for the correct line number to use\n  LinescanLMA model( this, point );\n  int status;\n  vw::Vector<double> objective(1), start(1);\n  start[0] = m_image_size.y()/2; \n  // Use a refined guess, if available, otherwise the center line.\n  if (starty >= 0)\n    start[0] = starty;\n\n  // Run the solver\n  const double ABS_TOL = 1e-16;\n  const double REL_TOL = 1e-16;\n  const int    MAX_ITERATIONS = 1e+5;\n  vw::Vector<double> solution = vw::math::levenberg_marquardt(model, start, objective, status,\n                                                              ABS_TOL, REL_TOL, MAX_ITERATIONS);\n\n  VW_ASSERT( status > 0, vw::camera::PointToPixelErr() << \"Unable to project point into LinescanDG model\" );\n\n  // Solve for sample location now that we know the correct line\n  double      t  = m_time_func( solution[0] );\n  vw::Vector3 pt = inverse( m_pose_func(t) ).rotate( point - m_position_func(t) );\n  pt *= m_focal_length / pt.z();\n\n  return vw::Vector2(pt.x() - m_detector_origin[0], solution[0]);\n}\n\n\n\n\n\n\n\n\n\n\n// -----------------------------------------------------------------\n// LinescanDGModel solver functions\n\n// Function to minimize with the no-correction LMA optimizer.\ntemplate <class PositionFuncT, class PoseFuncT>\ntypename LinescanDGModel<PositionFuncT, PoseFuncT>::LinescanLMA::result_type\nLinescanDGModel<PositionFuncT, PoseFuncT>::LinescanLMA::operator()( domain_type const& y ) const {\n  double       t        = m_model->get_time_at_line(y[0]);\n  vw::Quat     pose     = m_model->get_camera_pose_at_time(t);\n  vw::Vector3  position = m_model->m_position_func(t);\n\n  // Get point in camera's frame and rescale to pixel units\n  vw::Vector3 pt = vw::camera::point_to_camera_coord(position, pose, m_point);\n  pt *= m_model->m_focal_length / pt.z();\n  result_type result(1);\n  result[0] = pt.y() - m_model->m_detector_origin[1]; // Error against the location of the detector\n  return result;\n}\n\n\n// -----------------------------------------------------------------\n// LinescanDGModel supporting functions\n\nclass SecondsFrom\n{\n  boost::posix_time::ptime m_reference;\npublic:\n  inline SecondsFrom( boost::posix_time::ptime const& time ) : m_reference(time) {}\n\n  inline double operator()( boost::posix_time::ptime const& time ) const {\n    return double( (time - m_reference).total_microseconds() ) / 1e6;\n  }\n};\n\ninline boost::posix_time::ptime parse_time(std::string str)\n{\n  try{\n    return boost::posix_time::time_from_string(str);\n  }catch(...){\n    vw::vw_throw(vw::ArgumentErr() << \"Failed to parse time from string: \" << str\n\t\t << \". If you are not using Digital Globe images, you may need to specify the session type, such as -t rpc, -t rpcmaprpc, -t aster, etc.\\n\");\n  }\n  return boost::posix_time::time_from_string(str); // Never reached!\n}\n\nboost::shared_ptr<DGCameraModel> load_dg_camera_model_from_xml(std::string const& path)\n{\n  //vw_out() << \"DEBUG - Loading DG camera file: \" << camera_file << std::endl;\n\n  // Parse the Digital Globe XML file\n  GeometricXML geo;\n  AttitudeXML  att;\n  EphemerisXML eph;\n  ImageXML     img;\n  RPCXML       rpc;\n\n  try {\n    read_xml( path, geo, att, eph, img, rpc );\n  } catch ( const std::exception& e ){\n    vw::vw_throw(vw::ArgumentErr() << \"Invalid Digital Globe XML file: \" << path\n\t\t << \". If you are not using Digital Globe images, you may need to specify the session type, such as -t rpc, -t rpcmaprpc, -t aster, etc.\\n\"\n\t\t << e.what() << \"\\n\");\n  }\n  \n  // Get an estimate of the surface elevation from the corners specified in the file.\n  // - Not every file has this information, in which case we will just use zero.\n  double mean_ground_elevation = 0;\n  vw::BBox3 bbox = rpc.get_lon_lat_height_box();\n  if (!bbox.empty())\n    mean_ground_elevation = (bbox.min()[2] + bbox.max()[2]) / 2.0;\n  \n  // Convert measurements in millimeters to pixels.\n  geo.principal_distance /= geo.detector_pixel_pitch;\n  geo.detector_origin    /= geo.detector_pixel_pitch;\n\n  // Convert all time measurements to something that boost::date_time can read.\n  boost::replace_all( eph.start_time,            \"T\", \" \" );\n  boost::replace_all( img.tlc_start_time,        \"T\", \" \" );\n  boost::replace_all( img.first_line_start_time, \"T\", \" \" );\n  boost::replace_all( att.start_time,            \"T\", \" \" );\n\n  // Convert UTC time measurements to line measurements. Ephemeris\n  // start time will be our reference frame to calculate seconds against.\n  SecondsFrom convert( parse_time( eph.start_time ) );\n\n  // I'm going make the assumption that EPH and ATT are sampled at the same rate and time.\n  VW_ASSERT( eph.position_vec.size() == att.quat_vec.size(),\n\t     vw::MathErr() << \"Ephemeris and Attitude don't have the same number of samples.\" );\n  VW_ASSERT( eph.start_time == att.start_time && eph.time_interval == att.time_interval,\n\t     vw::MathErr() << \"Ephemeris and Attitude don't seem to sample with the same t0 or dt.\" );\n\n  // Convert ephemeris to be position of camera. Change attitude to\n  // be the rotation from camera frame to world frame. We also add an\n  // additional rotation to the camera frame so X is the horizontal\n  // direction to the picture and +Y points down the image (in the direction of flight).\n  vw::Quat sensor_coordinate = vw::math::euler_xyz_to_quaternion(vw::Vector3(0,0,geo.detector_rotation - M_PI/2));\n  for ( size_t i = 0; i < eph.position_vec.size(); i++ ) {\n    eph.position_vec[i] += att.quat_vec[i].rotate( geo.perspective_center );\n    att.quat_vec[i] = att.quat_vec[i] * geo.camera_attitude * sensor_coordinate;\n  }\n\n  //vw::vw_out() << \"DG model load - sensor_coordinate = \" << sensor_coordinate << std::endl;\n  //geo.printDebugInfo(); // DEBUG INFO\n\n  // Load up the time interpolation class. If the TLCList only has\n  // one entry ... then we have to manually drop in the slope and offset.\n  if ( img.tlc_vec.size() == 1 ) {\n    double direction = 1;\n    if ( boost::to_lower_copy( img.scan_direction ) != \"forward\" ) {\n      direction = -1;\n    }\n    img.tlc_vec.push_back( std::make_pair(img.tlc_vec.front().first +\n\t\t\t\t\t  img.avg_line_rate, direction) );\n  }\n\n  // Build the TLCTimeInterpolation object and do a quick sanity check.\n  vw::camera::TLCTimeInterpolation tlc_time_interpolation( img.tlc_vec,\n\t\t\t\t\t\t\t       convert( parse_time( img.tlc_start_time ) ) );\n  VW_ASSERT( fabs( convert( parse_time( img.first_line_start_time ) ) -\n  tlc_time_interpolation( 0 ) ) < fabs( 1.0 / (10.0 * img.avg_line_rate ) ),\n\t     vw::MathErr()\n\t     << \"First Line Time and output from TLC lookup table \"\n\t     << \"do not agree of the ephemeris time for the first line of the image. \"\n\t     << \"If your XML camera files are not from the WorldView satellites, \"\n\t     << \"you may try the switch -t rpc to use the RPC camera model.\\n\"\n\t     << \"The first image line ephemeris time is: \"\n  \t     << convert( parse_time( img.first_line_start_time ) ) << \".\\n\"\n\t     << \"The TLC look up table time is: \" << tlc_time_interpolation( 0 ) << \".\\n\"\n\t     << \"Maximum allowed difference is 1/10 of avg line rate, which is: \"\n\t     << fabs( 1.0 / (10.0 * img.avg_line_rate ))\n\t     << \".\\n\"\n    );\n   \n  vw::Vector2 final_detector_origin\n    = subvector(inverse(sensor_coordinate).rotate(vw::Vector3(geo.detector_origin[0],\n\t\t\t\t\t\t\t      geo.detector_origin[1],\n\t\t\t\t\t\t\t      0)), 0, 2);\n\n  double et0 = convert( parse_time( eph.start_time ) );\n  double at0 = convert( parse_time( att.start_time ) );\n  double edt = eph.time_interval;\n  double adt = att.time_interval;\n\n  // This is where we could set the Earth radius if we have that info.\n\n  typedef boost::shared_ptr<DGCameraModel> CameraModelPtr;\n  return CameraModelPtr(new DGCameraModel(vw::camera::PiecewiseAPositionInterpolation(eph.position_vec, eph.velocity_vec, et0, edt ),\n\t\t\t\t\t                                vw::camera::LinearPiecewisePositionInterpolation(eph.velocity_vec, et0, edt),\n\t\t\t\t\t                                vw::camera::SLERPPoseInterpolation(att.quat_vec, at0, adt),\n\t\t\t\t\t                                tlc_time_interpolation, img.image_size,\n\t\t\t\t\t                                final_detector_origin,\n\t\t\t\t\t                                geo.principal_distance,\n\t\t\t\t\t                                mean_ground_elevation,\n\t\t\t\t\t                                !stereo_settings().disable_correct_velocity_aberration,\n\t\t\t\t\t                                !stereo_settings().disable_correct_atmospheric_refraction)\n\t\t    );\n} // End function load_dg_camera_model()\n\n\n} // end namespace asp\n\n", "meta": {"hexsha": "d9d00b9b31cd3d08717ca21ad2d2071e6f6b8859", "size": 11481, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "src/asp/Camera/LinescanDGModel.tcc", "max_stars_repo_name": "AndrewAnnex/StereoPipeline", "max_stars_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "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/asp/Camera/LinescanDGModel.tcc", "max_issues_repo_name": "AndrewAnnex/StereoPipeline", "max_issues_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "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/asp/Camera/LinescanDGModel.tcc", "max_forks_repo_name": "AndrewAnnex/StereoPipeline", "max_forks_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "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.0549450549, "max_line_length": 143, "alphanum_fraction": 0.6697151816, "num_tokens": 2995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.17885224699709887}}
{"text": "#include \"sim_inter.h\"\n#include <Eigen/Geometry>\n#include <gflags/gflags.h>\n\nDEFINE_double(starttime, 0, \"Process time at which to start the simulation\");\nDEFINE_double(endtime, 9999, \"Process time at which to end the simulation\");\n\nnamespace {\nconstexpr double kAirmarOffset = -.0;\n\n};\n\nnamespace sailbot {\nnamespace sim {\n\nSimulatorNode::SimulatorNode(double reset_period, bool set_pos)\n    : Node(dt),\n      reset_period_(reset_period),\n      set_pos_(set_pos),\n      // impl_(new SimulatorSaoud2013(dt)),\n      impl_(new TrivialDynamics(dt)), sdot_(0), rdot_(0), bdot_(0),\n      state_queue_(\"sim_true_boat_state\", true),\n      state_msg_(AllocateMessage<msg::BoatState>()),\n      wind_queue_(\"sim_true_wind\", true),\n      wind_msg_(AllocateMessage<msg::Vector3f>()) {\n    RegisterHandler<msg::SailCmd>(\n        \"sail_cmd\",\n        std::bind(&SimulatorNode::ProcessSail, this, std::placeholders::_1));\n    RegisterHandler<msg::RudderCmd>(\n        \"rudder_cmd\",\n        std::bind(&SimulatorNode::ProcessRudder, this, std::placeholders::_1));\n    RegisterHandler<msg::BallastCmd>(\n        \"ballast_cmd\",\n        std::bind(&SimulatorNode::ProcessBallast, this, std::placeholders::_1));\n    RegisterHandler<msg::Vector3f>(\"sim_set_wind\",\n                                   [this](const msg::Vector3f &msg) {\n      set_wind(msg.x(), msg.y(), msg.z());\n      // Don't actually need to correct for airmar, because this is the true,\n      // not apparent, wind.\n      // float ang = std::atan2(msg.y(), msg.x());\n      // float speed = std::sqrt(msg.x() * msg.x() + msg.y() * msg.y());\n      // ang -= kAirmarOffset; // not sure of sign\n      // set_wind(ang, speed);\n    });\n    // For when doing log replay, retrieve logged state.\n    // And set sail appropriately.\n    RegisterHandler<msg::BoatState>(\"orig_boat_state\",\n                                    [this](const msg::BoatState &msg) {\n      std::unique_lock<std::mutex> lck(last_state_mutex_);\n      last_state_ = msg;\n      last_state_.mutable_euler()->set_yaw(msg.euler().yaw() - kAirmarOffset);\n\n      deltas_ = msg.internal().sail();\n    });\n}\n\nvoid SimulatorNode::ProcessSail(const msg::SailCmd& cmd) {\n  if (cmd.has_vel() && !std::isnan(cmd.vel())) {\n    sdot_ = cmd.vel();\n  } else if (cmd.has_pos() && !std::isnan(cmd.pos())) {\n    double pos = cmd.pos();\n    sdot_ = impl_->get_sdot_for_goal(pos);\n  }\n}\n\nvoid SimulatorNode::ProcessRudder(const msg::RudderCmd& cmd) {\n  deltar_ = cmd.pos();\n  if (cmd.has_vel() && !std::isnan(cmd.vel())) {\n    rdot_ = cmd.vel();\n  } else if (cmd.has_pos() && !std::isnan(cmd.pos())) {\n    rdot_ = impl_->get_rdot_for_goal(cmd.pos());\n  }\n}\n\nvoid SimulatorNode::ProcessBallast(const msg::BallastCmd& cmd) {\n  if (cmd.has_vel() && !std::isnan(cmd.vel())) {\n    bdot_ = cmd.vel();\n  } else if (cmd.has_voltage()) {\n    bdot_ = cmd.voltage() / 12.0;\n  }\n}\n\nvoid SimulatorNode::Run() {\n  std::thread t_internal(&FakeInternalSensors::Run, &internal_sensors_);\n  std::thread t_airmar(&FakeAirmar::Run, &fake_airmar_);\n  Node::Run();\n  t_airmar.join();\n  t_internal.join();\n}\n\nvoid SimulatorNode::Iterate() {\n  const double systime =\n      std::chrono::nanoseconds(util::monotonic_clock::now().time_since_epoch())\n          .count() /\n      1e9;\n  if (systime < FLAGS_starttime) {\n    return;\n  }\n  if (systime > FLAGS_endtime) {\n    util::RaiseShutdown();\n    return;\n  }\n  if (reset_period_ > 0 && systime > next_reset_) {\n    started_ = false;\n    next_reset_ = systime + reset_period_;\n  }\n  if (!started_) {\n    std::unique_lock<std::mutex> lck(last_state_mutex_);\n    impl_->set_from_state(last_state_);\n    if (last_state_.has_pos()) {\n      fake_airmar_.set_gps_zero(last_state_.pos().y(), last_state_.pos().x());\n    } else {\n      fake_airmar_.set_gps_zero(42.276126, -71.756934);\n    }\n    started_ = true;\n  }\n  usleep(dt * 1e6 / 2.);\n  static float time = 0;\n  VLOG(2) << \"Time: \" << (time += dt);\n  VLOG(1) << \"s, r: \" << sdot_ << \", \" << rdot_;\n  //if (time > .05) std::exit(0);\n  if (set_pos_) {\n    impl_->Update(deltas_, deltar_);\n  } else {\n    impl_->Update(sdot_, rdot_, bdot_);\n  }\n  Eigen::Vector3d omega = impl_->get_omega();\n  Eigen::Vector3d x = impl_->get_x();\n  Eigen::Vector3d v = impl_->get_v();\n  Eigen::Quaternion<double> rot(impl_->get_RBI());\n\n  Eigen::Vector3d rollpitchyaw = util::GetRollPitchYaw(impl_->get_RBI());\n\n  msg::Vector3d *pos = state_msg_->mutable_pos();\n  pos->set_x(x(0));\n  pos->set_y(x(1));\n  pos->set_z(x(2));\n\n  msg::Vector3f *vel = state_msg_->mutable_vel();\n  vel->set_x(v(0));\n  vel->set_y(v(1));\n  vel->set_z(v(2));\n\n  msg::Vector3f *wmsg = state_msg_->mutable_omega();\n  wmsg->set_x(omega(0));\n  wmsg->set_y(omega(1));\n  wmsg->set_z(omega(2));\n\n  msg::Quaternion *qmsg = state_msg_->mutable_orientation();\n  qmsg->set_w(rot.w());\n  qmsg->set_x(rot.x());\n  qmsg->set_y(rot.y());\n  qmsg->set_z(rot.z());\n\n  msg::EulerAngles *euler = state_msg_->mutable_euler();\n  euler->set_roll(rollpitchyaw(0, 0));\n  euler->set_pitch(rollpitchyaw(1, 0));\n  euler->set_yaw(rollpitchyaw(2, 0));\n\n  state_msg_->mutable_internal()->set_sail(std::abs(impl_->get_deltas()));\n  // XXX(james): Resolve abs vs. not for deltas\n  state_msg_->mutable_internal()->set_sail(impl_->get_deltas());\n  state_msg_->mutable_internal()->set_rudder(impl_->get_deltar());\n  state_msg_->mutable_internal()->set_ballast(impl_->get_deltab());\n  state_msg_->mutable_internal()->set_saildot(sdot_);\n  state_msg_->mutable_internal()->set_rudderdot(rdot_);\n  state_msg_->mutable_internal()->set_ballastdot(bdot_);\n\n  state_queue_.send(state_msg_);\n}\n\n}  // sim\n}  // sailbot\n", "meta": {"hexsha": "9cbe3708589297a95b35ab512811cc65759994b2", "size": 5579, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sim/sim_inter.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": "sim/sim_inter.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": "sim/sim_inter.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": 32.0632183908, "max_line_length": 80, "alphanum_fraction": 0.6384656749, "num_tokens": 1648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.17885224354419688}}
{"text": "\n#ifndef DEEPQCACLA_HPP\n#define DEEPQCACLA_HPP\n\n#include <vector>\n#include <string>\n#include <boost/serialization/list.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/deque.hpp>\n\n#include \"nn/MLP.hpp\"\n#include \"nn/DevMLP.hpp\"\n#include \"nn/DODevMLP.hpp\"\n#include \"arch/AACAgent.hpp\"\n#include \"bib/Seed.hpp\"\n#include \"bib/Utils.hpp\"\n#include <bib/MetropolisHasting.hpp>\n#include <bib/XMLEngine.hpp>\n\n\n#define DOUBLE_COMPARE_PRECISION 1e-9\n\ntypedef struct _sample {\n  std::vector<double> s;\n  std::vector<double> pure_a;\n  std::vector<double> a;\n  std::vector<double> next_s;\n  double r;\n  bool goal_reached;\n\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive& ar, const unsigned int) {\n    ar& BOOST_SERIALIZATION_NVP(s);\n    ar& BOOST_SERIALIZATION_NVP(pure_a);\n    ar& BOOST_SERIALIZATION_NVP(a);\n    ar& BOOST_SERIALIZATION_NVP(next_s);\n    ar& BOOST_SERIALIZATION_NVP(r);\n    ar& BOOST_SERIALIZATION_NVP(goal_reached);\n  }\n\n  //Used to store all sample into a tree, might be stochastic\n  //only pure_a is negligate\n  bool operator< (const _sample& b) const {\n    for (uint i = 0; i < s.size(); i++) {\n      if(fabs(s[i] - b.s[i])>=DOUBLE_COMPARE_PRECISION)\n        return s[i] < b.s[i];\n    }\n    \n    for (uint i = 0; i < a.size(); i++) {\n      if(fabs(a[i] - b.a[i])>=DOUBLE_COMPARE_PRECISION)\n        return a[i] < b.a[i];\n    }\n    \n    for (uint i = 0; i < next_s.size(); i++) {\n      if(fabs(next_s[i] - b.next_s[i])>=DOUBLE_COMPARE_PRECISION)\n        return next_s[i] < b.next_s[i];\n    }\n    \n    if(fabs(r - b.r)>=DOUBLE_COMPARE_PRECISION)\n        return r < b.r;\n\n    return goal_reached < b.goal_reached;\n  }\n  \n  typedef double value_type;\n\n  inline double operator[](size_t const N) const{\n        return s[N];\n  }\n  \n  bool same_state(const _sample& b) const{\n    for (uint i = 0; i < s.size(); i++) {\n      if(fabs(s[i] - b.s[i])>=DOUBLE_COMPARE_PRECISION)\n        return false;\n    }\n    \n    return true;\n  }\n\n} sample;\n\ntemplate<typename NN = MLP>\nclass DeepQCaclaAg : public arch::AACAgent<MLP, arch::AgentGPUProgOptions> {\n public:\n  typedef MLP PolicyImpl;\n   \n  DeepQCaclaAg(unsigned int _nb_motors, unsigned int _nb_sensors)\n    : arch::AACAgent<MLP, arch::AgentGPUProgOptions>(_nb_motors, _nb_sensors), nb_sensors(_nb_sensors) {\n\n  }\n\n  virtual ~DeepQCaclaAg() {\n    delete qnn;\n    delete ann;\n    \n    delete qnn_target;\n    delete ann_target;\n    \n    delete ann_testing;\n    \n    delete hidden_unit_q;\n    delete hidden_unit_a;\n  }\n\n  const std::vector<double>& _run(double reward, const std::vector<double>& sensors,\n                                 bool learning, bool goal_reached, bool) override {\n\n    // protect batch norm from testing data and poor data\n    double* weights = new double[ann->number_of_parameters(false)];\n    ann->copyWeightsTo(weights, false);\n    ann_testing->copyWeightsFrom(weights, false);\n    delete[] weights;\n    vector<double>* next_action = ann_testing->computeOut(sensors);\n    \n    if (last_action.get() != nullptr && learning){\n      sample sa = {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached};\n      insertSample(sa);\n    }\n\n    last_pure_action.reset(new vector<double>(*next_action));\n    if(learning) {\n      if(gaussian_policy){\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise);\n        delete next_action;\n        next_action = randomized_action;\n      } else if(bib::Utils::rand01() < noise){ //e-greedy\n        for (uint i = 0; i < next_action->size(); i++)\n          next_action->at(i) = bib::Utils::randin(-1.f, 1.f);\n      }\n    }\n    last_action.reset(next_action);\n\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    last_trajectory_a.push_back(*next_action);\n    \n    return *next_action;\n  }\n\n  void insertSample(const sample& sa){\n    if(trajectory.size() >= replay_memory)\n      trajectory.pop_front();\n    trajectory.push_back(sa);\n      \n    end_episode(true);\n  }\n\n  void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map* command_args) override {\n    hidden_unit_q           = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_q\"));\n    hidden_unit_a           = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_a\"));\n    noise                   = pt->get<double>(\"agent.noise\");\n    gaussian_policy         = pt->get<bool>(\"agent.gaussian_policy\");\n    kMinibatchSize          = pt->get<uint>(\"agent.mini_batch_size\");\n    replay_memory           = pt->get<uint>(\"agent.replay_memory\");\n    inverting_grad          = pt->get<bool>(\"agent.inverting_grad\");\n    force_more_update       = pt->get<uint>(\"agent.force_more_update\");\n    tau_soft_update         = pt->get<double>(\"agent.tau_soft_update\");\n    alpha_a                 = pt->get<double>(\"agent.alpha_a\");\n    alpha_v                 = pt->get<double>(\"agent.alpha_v\");\n    decay_v                 = pt->get<double>(\"agent.decay_v\");\n    batch_norm_critic       = pt->get<uint>(\"agent.batch_norm_critic\");\n    batch_norm_actor        = pt->get<uint>(\"agent.batch_norm_actor\");\n    actor_output_layer_type = pt->get<uint>(\"agent.actor_output_layer_type\");\n    hidden_layer_type       = pt->get<uint>(\"agent.hidden_layer_type\");\n    bool test_net           = pt->get<bool>(\"agent.test_net\");\n    bn_adapt                = pt->get<bool>(\"agent.bn_adapt\");\n    uint momentum           = pt->get<uint>(\"agent.momentum\");\n    qac_target              = pt->get<bool>(\"agent.qac_target\");\n    aac_target              = pt->get<bool>(\"agent.aac_target\");\n    qac_sample              = pt->get<uint>(\"agent.qac_sample\");\n    qnextac_sample          = pt->get<uint>(\"agent.qnextac_sample\");\n    recompute_next_ac       = pt->get<bool>(\"agent.recompute_next_ac\");\n    onpolac                 = pt->get<bool>(\"agent.onpolac\");\n    qmu                     = pt->get<bool>(\"agent.qmu\");\n    \n    if(recompute_next_ac && aac_target) {\n      LOG_DEBUG(\"recompute_next_ac useless\");\n      exit(1);\n    }\n    \n#ifdef CAFFE_CPU_ONLY\n    LOG_INFO(\"CPU mode\");\n    (void) command_args;\n#else\n    if(command_args->count(\"gpu\") == 0 || command_args->count(\"cpu\") > 0){\n      caffe::Caffe::set_mode(caffe::Caffe::Brew::CPU);\n      LOG_INFO(\"CPU mode\");\n    } else {\n      caffe::Caffe::set_mode(caffe::Caffe::Brew::GPU);\n      caffe::Caffe::SetDevice(0);\n      LOG_INFO(\"GPU mode\");\n    }\n#endif\n    \n    ann = new NN(nb_sensors, *hidden_unit_a, nb_motors, alpha_a, kMinibatchSize, \n                 hidden_layer_type, actor_output_layer_type, batch_norm_actor, false, momentum);\n    if(std::is_same<NN, DevMLP>::value)\n      ann->exploit(pt, static_cast<DeepQCaclaAg *>(old_ag)->ann);\n    else if(std::is_same<NN, DODevMLP>::value)\n      ann->exploit(pt, nullptr);\n    \n    if(test_net)\n      ann_target = new NN(*ann, false, ::caffe::Phase::TEST);\n    else\n      ann_target = new NN(*ann, false);\n    \n    ann_testing = new NN(*ann, false, ::caffe::Phase::TEST);\n    ann_testing->increase_batchsize(1);\n    \n    qnn = new NN(nb_sensors + nb_motors, nb_sensors, *hidden_unit_q, alpha_v, kMinibatchSize, \n                 decay_v, hidden_layer_type, batch_norm_critic, false, momentum);\n    if(std::is_same<NN, DevMLP>::value)\n      qnn->exploit(pt, static_cast<DeepQCaclaAg *>(old_ag)->qnn);\n    else if(std::is_same<NN, DODevMLP>::value)\n      qnn->exploit(pt, ann);\n    \n    if(test_net)\n      qnn_target = new NN(*qnn, false, ::caffe::Phase::TEST);\n    else\n      qnn_target = new NN(*qnn, false);\n  }\n\n  void _start_episode(const std::vector<double>& sensors, bool) override {\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    last_action = nullptr;\n    last_pure_action = nullptr;\n    \n    last_trajectory_a.clear();\n    \n    valid_advantage = 0;\n    invalid_advantage = 0;\n  }\n  \n  void sample_transition(std::vector<sample>& traj, const std::deque<sample>& from){\n     for(uint i=0;i<traj.size();i++){\n       int r = std::uniform_int_distribution<int>(0, from.size() - 1)(*bib::Seed::random_engine());\n       traj[i] = from[r];\n     }\n  }\n  \n  void end_episode(bool learning) override {\n    \n    if(!learning || trajectory.size() < 250 || trajectory.size() < kMinibatchSize)\n      return;\n    \n    for(uint fupd=0;fupd<1+force_more_update;fupd++) {\n      std::vector<sample> traj(kMinibatchSize);\n      sample_transition(traj, trajectory);\n      \n      //compute \\pi(s_{t+1})\n      std::vector<double> all_next_states(traj.size() * nb_sensors);\n      std::vector<double> all_states(traj.size() * nb_sensors);\n      std::vector<double> all_actions(traj.size() * nb_motors);\n      std::vector<bool> disable_back(traj.size() * this->nb_motors, false);\n      const std::vector<bool> disable_back_ac(this->nb_motors, true);\n      std::vector<double> deltas(traj.size());\n      uint i=0;\n      for (auto it : traj){\n        std::copy(it.next_s.begin(), it.next_s.end(), all_next_states.begin() + i * nb_sensors);\n        std::copy(it.s.begin(), it.s.end(), all_states.begin() + i * nb_sensors);\n        std::copy(it.a.begin(), it.a.end(), all_actions.begin() + i * nb_motors);\n        i++;\n      }\n\n      auto all_next_actions = ann_target->computeOutBatch(all_next_states);\n        \n      //compute next q\n      std::vector<double>* q_targets;\n      if(!qmu)\n        q_targets = qnn_target->computeOutVFBatch(all_next_states, *all_next_actions);\n      else {\n        q_targets = new std::vector<double>(traj.size(), 0.f);\n        for(uint j=0;j<7;j++){\n          vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*all_next_actions, noise);\n          auto local_all_nextV = qnn_target->computeOutVFBatch(all_next_states, *randomized_action);\n          std::transform(q_targets->begin(), q_targets->end(), local_all_nextV->begin(), q_targets->begin(), std::plus<double>());\n          delete local_all_nextV;\n          delete randomized_action;\n        }\n        double factor_ = 1.f/((double)7.);\n        std::transform(q_targets->begin(), q_targets->end(), q_targets->begin(), std::bind1st(std::multiplies<double>(), factor_));\n      }\n      \n      //adjust q_targets\n      i=0;\n      for (auto it : traj){\n        if(it.goal_reached)\n          q_targets->at(i) = it.r;\n        else \n          q_targets->at(i) = it.r + gamma * q_targets->at(i);\n        \n        i++;\n      }\n      \n      //Update critic\n      qnn->learn_batch(all_states, all_actions, *q_targets, 1);\n      \n      //Update actor\n      qnn->ZeroGradParameters();\n      ann->ZeroGradParameters();\n      \n      auto all_actions_outputs = ann->computeOutBatch(all_states);\n      if(batch_norm_actor != 0 && bn_adapt){\n        delete all_actions_outputs;\n        ann_testing->increase_batchsize(kMinibatchSize);\n        all_actions_outputs = ann_testing->computeOutBatch(all_states);\n        ann_testing->increase_batchsize(1);\n      }\n      \n      MLP* qnn_worker = qnn;\n      if(qac_target)\n        qnn_worker = qnn_target;\n      \n      MLP* ann_worker = ann;\n      if(aac_target)\n        ann_worker = ann_target;\n      \n      // pre-compute delta\n      std::vector<double>* all_mine, *all_nextV;\n      \n      std::vector<double>* current_all_actions = all_actions_outputs;\n      if(onpolac)\n        current_all_actions = &all_actions;\n      \n      if(qac_sample <= 1)\n        all_mine = qnn->computeOutVFBatch(all_states, *current_all_actions);\n      else {\n        all_mine = new std::vector<double>(traj.size(), 0.f);\n        for(uint j=0;j<qac_sample;j++){\n          vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*current_all_actions, noise);\n          auto local_all_mine = qnn_worker->computeOutVFBatch(all_states, *randomized_action);\n          std::transform(all_mine->begin(), all_mine->end(), local_all_mine->begin(), all_mine->begin(), std::plus<double>());\n          delete local_all_mine;\n          delete randomized_action;\n        }\n        double factor_ = 1.f/((double)qac_sample);\n        std::transform(all_mine->begin(), all_mine->end(), all_mine->begin(), std::bind1st(std::multiplies<double>(), factor_));\n      }\n\n      std::vector<double>* current_all_next_actions = all_next_actions;\n      if(recompute_next_ac)\n        current_all_next_actions = ann_worker->computeOutBatch(all_next_states);\n      \n      if(qnextac_sample <= 1){\n        all_nextV = qnn_target->computeOutVFBatch(all_next_states, *current_all_next_actions);\n      } else {\n        all_nextV = new std::vector<double>(traj.size(), 0.f);\n        for(uint j=0;j<qnextac_sample;j++){\n          vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*current_all_next_actions, noise);\n          auto local_all_nextV = qnn_worker->computeOutVFBatch(all_next_states, *randomized_action);\n          std::transform(all_nextV->begin(), all_nextV->end(), local_all_nextV->begin(), all_nextV->begin(), std::plus<double>());\n          delete local_all_nextV;\n          delete randomized_action;\n        }\n        double factor_ = 1.f/((double)qnextac_sample);\n        std::transform(all_nextV->begin(), all_nextV->end(), all_nextV->begin(), std::bind1st(std::multiplies<double>(), factor_));\n      }\n      \n      if(recompute_next_ac)\n        delete current_all_next_actions;\n      \n      // compute delta\n      i=0;\n      for (auto it : traj) {\n        double v_target = it.r;\n        if (!it.goal_reached) {\n          double nextV = all_nextV->at(i);\n          v_target += this->gamma * nextV;\n        }\n        \n        deltas[i] = v_target - all_mine->at(i);\n        ++i;\n      }\n      \n      // compute disable_back\n      i=0;\n      for(auto it : traj) {\n        if(deltas[i] <= 0.0000000000f){\n          std::copy(disable_back_ac.begin(), disable_back_ac.end(), disable_back.begin() + i * this->nb_motors);\n          invalid_advantage++;\n        } else \n          valid_advantage++;\n        i++;\n      }\n      \n      // unless deter update\n      qnn->ZeroGradParameters();\n      ann->ZeroGradParameters();\n      \n//       delete qnn->computeOutVFBatch(all_states, *all_actions_outputs);\n//       const auto q_values_blob = qnn->getNN()->blob_by_name(MLP::q_values_blob_name);\n//       double* q_values_diff = q_values_blob->mutable_cpu_diff();\n//       i=0;\n//       for (auto it : traj)\n//         q_values_diff[q_values_blob->offset(i++,0,0,0)] = -1.0f;\n//       qnn->critic_backward();\n//       const auto critic_action_blob = qnn->getNN()->blob_by_name(MLP::actions_blob_name);\n//       const double* critic_action_diff = critic_action_blob->cpu_diff();\n      \n      const auto actor_actions_blob = ann->getNN()->blob_by_name(MLP::actions_blob_name);\n      auto ac_diff = actor_actions_blob->mutable_cpu_diff();\n      for(i=0; i<(uint) actor_actions_blob->count(); i++) {\n        if(disable_back[i]) {\n//           ac_diff[i] = critic_action_diff[i];\n          ac_diff[i] = 0.f;\n        } else {\n          double x = all_actions[i] - all_actions_outputs->at(i);\n          ac_diff[i] = -x;\n        }\n      }\n      \n      if(inverting_grad){\n\n        for (uint n = 0; n < traj.size(); ++n) {\n          for (uint h = 0; h < nb_motors; ++h) {\n            int offset = actor_actions_blob->offset(n,h,0,0);\n            double diff = ac_diff[offset];\n            double output = all_actions_outputs->at(offset);\n            double min = -1.0; \n            double max = 1.0;\n            if (diff < 0) {\n              diff *= (max - output) / (max - min);\n            } else if (diff > 0) {\n              diff *= (output - min) / (max - min);\n            }\n            ac_diff[offset] = diff;\n          }\n        }\n      }\n      \n      ann->actor_backward();\n      ann->getSolver()->ApplyUpdate();\n      ann->getSolver()->set_iter(ann->getSolver()->iter() + 1);\n      \n      // Soft update of targets networks\n      qnn_target->soft_update(*qnn, tau_soft_update);\n      ann_target->soft_update(*ann, tau_soft_update);\n      \n      delete q_targets;\n      delete all_actions_outputs;\n      delete all_next_actions;\n      \n      delete all_nextV;\n      delete all_mine;\n    }\n  \n  }\n  \n  double criticEval(const std::vector<double>& perceptions, const std::vector<double>& actions) override {\n      return qnn->computeOutVF(perceptions, actions);\n  }\n  \n  arch::Policy<MLP>* getCopyCurrentPolicy() override {\n    return new arch::Policy<MLP>(new MLP(*ann, true) , gaussian_policy ? arch::policy_type::GAUSSIAN : arch::policy_type::GREEDY, noise, decision_each);\n  }\n\n  void save(const std::string& path, bool, bool) override {\n//     if(save_best && best_population.size() > 0){\n//       auto it = best_population.begin();\n//       bib::XMLEngine::save(it->trajectory_a, \"trajectory_a\", \"best_trajectory_a.data\");\n//     } else {\n      ann->save(path+\".actor\");\n      qnn->save(path+\".critic\");\n//     }\n  }\n\n  void load(const std::string& path) override {\n    ann->load(path+\".actor\");\n    qnn->load(path+\".critic\");\n    \n    delete qnn_target;\n    delete ann_target;\n    \n    qnn_target = new MLP(*qnn, false, ::caffe::Phase::TEST);\n    ann_target = new MLP(*ann, false, ::caffe::Phase::TEST);\n  }\n\n protected:\n  void _display(std::ostream& out) const override {\n    out << std::setw(12) << std::fixed << std::setprecision(10) << sum_weighted_reward \n    << \" \" << std::setprecision(3) << ((float)(valid_advantage)/((float)(valid_advantage+invalid_advantage)))\n//     #ifndef NDEBUG\n//     << \" \" << std::setw(8) << std::fixed << std::setprecision(5) << noise \n//     << \" \" << trajectory.size() \n//     << \" \" << ann->weight_l1_norm() \n//     << \" \" << std::fixed << std::setprecision(7) << qnn->error() \n//     << \" \" << qnn->weight_l1_norm()\n//     #endif\n    ;\n  }\n\n  void _dump(std::ostream& out) const override {\n    out << std::setw(25) << std::fixed << std::setprecision(22) <<\n        sum_weighted_reward << \" \" << std::setw(8) << std::fixed <<\n        std::setprecision(5) << trajectory.size() << \" \" << std::setprecision(3) <<\n        ((float)(valid_advantage)/((float)(valid_advantage+invalid_advantage)));\n  }\n  \n\n private:\n  uint nb_sensors;\n\n  double noise;\n  double tau_soft_update;\n  double alpha_a; \n  double alpha_v;\n  double decay_v;\n  \n  bool gaussian_policy;\n  std::vector<uint>* hidden_unit_q;\n  std::vector<uint>* hidden_unit_a;\n  uint kMinibatchSize;\n  uint replay_memory;\n  uint force_more_update;\n  uint batch_norm_actor, batch_norm_critic;\n  uint actor_output_layer_type, hidden_layer_type;\n  \n  bool inverting_grad, bn_adapt;\n\n  std::shared_ptr<std::vector<double>> last_action;\n  std::shared_ptr<std::vector<double>> last_pure_action;\n  std::vector<double> last_state;\n\n  std::deque<sample> trajectory;\n  std::deque<std::vector<double>> last_trajectory_a;\n  \n  bool qac_target, aac_target, recompute_next_ac, onpolac, qmu;\n  uint qac_sample, qnextac_sample;\n  \n  uint episode = 0;\n  uint valid_advantage, invalid_advantage;\n  \n  struct my_pol_dpmt{\n    MLP* ann;\n    MLP* qnn;\n    double J;\n    std::deque<std::vector<double>> trajectory_a;\n    \n    bool operator< (const my_pol_dpmt& b) const {\n      return J > b.J;\n    }\n  };\n  \n  MLP* ann, *ann_target;\n  MLP* qnn, *qnn_target;\n  MLP* ann_testing;\n  \n  struct algo_state {\n    uint episode;\n    double J;\n    std::deque<std::vector<double>> best_trajectory_a;\n    \n    friend class boost::serialization::access;\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int) {\n      ar& BOOST_SERIALIZATION_NVP(episode);\n      ar& BOOST_SERIALIZATION_NVP(J);\n      ar& BOOST_SERIALIZATION_NVP(best_trajectory_a);\n    }\n  };\n};\n\n#endif\n\n", "meta": {"hexsha": "0be6080fb09f9a2632359c66cf6fb979fb8af5ca", "size": 19737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "agent/deepqn/include/DeepQCaclaAg.hpp", "max_stars_repo_name": "matthieu637/ddrl", "max_stars_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T09:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T13:50:23.000Z", "max_issues_repo_path": "agent/deepqn/include/DeepQCaclaAg.hpp", "max_issues_repo_name": "matthieu637/ddrl", "max_issues_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-10-09T14:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T15:01:00.000Z", "max_forks_repo_path": "agent/deepqn/include/DeepQCaclaAg.hpp", "max_forks_repo_name": "matthieu637/ddrl", "max_forks_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T09:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T14:35:40.000Z", "avg_line_length": 34.5052447552, "max_line_length": 152, "alphanum_fraction": 0.6192430461, "num_tokens": 5217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.17879124314196967}}
{"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 <iostream>\n#include <string>\n\n#include <pinocchio/fwd.hpp>  // forward declarations must be included first.\n\n#include <pinocchio/algorithm/frames.hpp>\n#include <pinocchio/algorithm/jacobian.hpp>\n#include <pinocchio/algorithm/kinematics.hpp>\n\n#include \"ocs2_legged_robot/LeggedRobotInterface.h\"\n\n#include <ocs2_centroidal_model/AccessHelperFunctions.h>\n#include <ocs2_centroidal_model/CentroidalModelPinocchioMapping.h>\n#include <ocs2_centroidal_model/ModelHelperFunctions.h>\n#include <ocs2_core/misc/Display.h>\n#include <ocs2_core/soft_constraint/StateInputSoftConstraint.h>\n#include <ocs2_oc/synchronized_module/SolverSynchronizedModule.h>\n#include <ocs2_pinocchio_interface/PinocchioEndEffectorKinematicsCppAd.h>\n\n#include \"ocs2_legged_robot/LeggedRobotPreComputation.h\"\n#include \"ocs2_legged_robot/constraint/FrictionConeConstraint.h\"\n#include \"ocs2_legged_robot/constraint/NormalVelocityConstraintCppAd.h\"\n#include \"ocs2_legged_robot/constraint/ZeroForceConstraint.h\"\n#include \"ocs2_legged_robot/constraint/ZeroVelocityConstraintCppAd.h\"\n#include \"ocs2_legged_robot/cost/LeggedRobotStateInputQuadraticCost.h\"\n#include \"ocs2_legged_robot/dynamics/LeggedRobotDynamicsAD.h\"\n\n// Boost\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/path.hpp>\n\nnamespace ocs2 {\nnamespace legged_robot {\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nLeggedRobotInterface::LeggedRobotInterface(const std::string& taskFile, const std::string& urdfFile, const std::string& referenceFile) {\n  // check that task file exists\n  boost::filesystem::path taskFilePath(taskFile);\n  if (boost::filesystem::exists(taskFilePath)) {\n    std::cerr << \"[LeggedRobotInterface] Loading task file: \" << taskFilePath << std::endl;\n  } else {\n    throw std::invalid_argument(\"[LeggedRobotInterface] Task file not found: \" + taskFilePath.string());\n  }\n  // check that urdf file exists\n  boost::filesystem::path urdfFilePath(urdfFile);\n  if (boost::filesystem::exists(urdfFilePath)) {\n    std::cerr << \"[LeggedRobotInterface] Loading Pinocchio model from: \" << urdfFilePath << std::endl;\n  } else {\n    throw std::invalid_argument(\"[LeggedRobotInterface] URDF file not found: \" + urdfFilePath.string());\n  }\n  // check that targetCommand file exists\n  boost::filesystem::path referenceFilePath(referenceFile);\n  if (boost::filesystem::exists(referenceFilePath)) {\n    std::cerr << \"[LeggedRobotInterface] Loading target command settings from: \" << referenceFilePath << std::endl;\n  } else {\n    throw std::invalid_argument(\"[LeggedRobotInterface] targetCommand file not found: \" + referenceFilePath.string());\n  }\n\n  bool verbose;\n  loadData::loadCppDataType(taskFile, \"legged_robot_interface.verbose\", verbose);\n\n  // load setting from loading file\n  modelSettings_ = loadModelSettings(taskFile, \"model_settings\", verbose);\n  ddpSettings_ = ddp::loadSettings(taskFile, \"ddp\", verbose);\n  mpcSettings_ = mpc::loadSettings(taskFile, \"mpc\", verbose);\n  rolloutSettings_ = rollout::loadSettings(taskFile, \"rollout\", verbose);\n  sqpSettings_ = multiple_shooting::loadSettings(taskFile, \"multiple_shooting\", verbose);\n\n  // OptimalConrolProblem\n  setupOptimalConrolProblem(taskFile, urdfFile, referenceFile, verbose);\n\n  // initial state\n  initialState_.setZero(centroidalModelInfo_.stateDim);\n  loadData::loadEigenMatrix(taskFile, \"initialState\", initialState_);\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nvoid LeggedRobotInterface::setupOptimalConrolProblem(const std::string& taskFile, const std::string& urdfFile,\n                                                     const std::string& referenceFile, bool verbose) {\n  // PinocchioInterface\n  pinocchioInterfacePtr_.reset(new PinocchioInterface(centroidal_model::createPinocchioInterface(urdfFile, modelSettings_.jointNames)));\n\n  // CentroidalModelInfo\n  centroidalModelInfo_ = centroidal_model::createCentroidalModelInfo(\n      *pinocchioInterfacePtr_, centroidal_model::loadCentroidalType(taskFile),\n      centroidal_model::loadDefaultJointState(pinocchioInterfacePtr_->getModel().nq - 6, referenceFile), modelSettings_.contactNames3DoF,\n      modelSettings_.contactNames6DoF);\n\n  // Swing trajectory planner\n  std::unique_ptr<SwingTrajectoryPlanner> swingTrajectoryPlanner(\n      new SwingTrajectoryPlanner(loadSwingTrajectorySettings(taskFile, \"swing_trajectory_config\", verbose), 4));\n\n  // Mode schedule manager\n  referenceManagerPtr_ =\n      std::make_shared<SwitchedModelReferenceManager>(loadGaitSchedule(referenceFile, verbose), std::move(swingTrajectoryPlanner));\n\n  // Optimal control problem\n  problemPtr_.reset(new OptimalControlProblem);\n\n  // Dynamics\n  bool useAnalyticalGradientsDynamics = false;\n  loadData::loadCppDataType(taskFile, \"legged_robot_interface.useAnalyticalGradientsDynamics\", useAnalyticalGradientsDynamics);\n  std::unique_ptr<SystemDynamicsBase> dynamicsPtr;\n  if (useAnalyticalGradientsDynamics) {\n    throw std::runtime_error(\"[LeggedRobotInterface::setupOptimalConrolProblem] The analytical dynamics class is not yet implemented!\");\n  } else {\n    const std::string modelName = \"dynamics\";\n    dynamicsPtr.reset(new LeggedRobotDynamicsAD(*pinocchioInterfacePtr_, centroidalModelInfo_, modelName, modelSettings_));\n  }\n\n  problemPtr_->dynamicsPtr = std::move(dynamicsPtr);\n\n  // Cost terms\n  problemPtr_->costPtr->add(\"baseTrackingCost\", getBaseTrackingCost(taskFile, centroidalModelInfo_, false));\n\n  // Constraint terms\n  // friction cone settings\n  scalar_t frictionCoefficient = 0.7;\n  RelaxedBarrierPenalty::Config barrierPenaltyConfig;\n  std::tie(frictionCoefficient, barrierPenaltyConfig) = loadFrictionConeSettings(taskFile, verbose);\n\n  bool useAnalyticalGradientsConstraints = false;\n  loadData::loadCppDataType(taskFile, \"legged_robot_interface.useAnalyticalGradientsConstraints\", useAnalyticalGradientsConstraints);\n  for (size_t i = 0; i < centroidalModelInfo_.numThreeDofContacts; i++) {\n    const std::string& footName = modelSettings_.contactNames3DoF[i];\n\n    std::unique_ptr<EndEffectorKinematics<scalar_t>> eeKinematicsPtr;\n    if (useAnalyticalGradientsConstraints) {\n      throw std::runtime_error(\n          \"[LeggedRobotInterface::setupOptimalConrolProblem] The analytical end-effector linear constraint is not implemented!\");\n    } else {\n      const auto infoCppAd = centroidalModelInfo_.toCppAd();\n      const CentroidalModelPinocchioMappingCppAd pinocchioMappingCppAd(infoCppAd);\n      auto velocityUpdateCallback = [&infoCppAd](const ad_vector_t& state, PinocchioInterfaceCppAd& pinocchioInterfaceAd) {\n        const ad_vector_t q = centroidal_model::getGeneralizedCoordinates(state, infoCppAd);\n        updateCentroidalDynamics(pinocchioInterfaceAd, infoCppAd, q);\n      };\n      eeKinematicsPtr.reset(new PinocchioEndEffectorKinematicsCppAd(*pinocchioInterfacePtr_, pinocchioMappingCppAd, {footName},\n                                                                    centroidalModelInfo_.stateDim, centroidalModelInfo_.inputDim,\n                                                                    velocityUpdateCallback, footName, modelSettings_.modelFolderCppAd,\n                                                                    modelSettings_.recompileLibrariesCppAd, modelSettings_.verboseCppAd));\n    }\n\n    problemPtr_->softConstraintPtr->add(footName + \"_frictionCone\",\n                                        getFrictionConeConstraint(i, frictionCoefficient, barrierPenaltyConfig));\n    problemPtr_->equalityConstraintPtr->add(footName + \"_zeroForce\", getZeroForceConstraint(i));\n    problemPtr_->equalityConstraintPtr->add(footName + \"_zeroVelocity\",\n                                            getZeroVelocityConstraint(*eeKinematicsPtr, i, useAnalyticalGradientsConstraints));\n    problemPtr_->equalityConstraintPtr->add(footName + \"_normalVelocity\",\n                                            getNormalVelocityConstraint(*eeKinematicsPtr, i, useAnalyticalGradientsConstraints));\n  }\n\n  // Pre-computation\n  problemPtr_->preComputationPtr.reset(new LeggedRobotPreComputation(*pinocchioInterfacePtr_, centroidalModelInfo_,\n                                                                     *referenceManagerPtr_->getSwingTrajectoryPlanner(), modelSettings_));\n\n  // Rollout\n  rolloutPtr_.reset(new TimeTriggeredRollout(*problemPtr_->dynamicsPtr, rolloutSettings_));\n\n  // Initialization\n  constexpr bool extendNormalizedMomentum = true;\n  initializerPtr_.reset(new LeggedRobotInitializer(centroidalModelInfo_, *referenceManagerPtr_, extendNormalizedMomentum));\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nstd::shared_ptr<GaitSchedule> LeggedRobotInterface::loadGaitSchedule(const std::string& file, bool verbose) const {\n  const auto initModeSchedule = loadModeSchedule(file, \"initialModeSchedule\", false);\n  const auto defaultModeSequenceTemplate = loadModeSequenceTemplate(file, \"defaultModeSequenceTemplate\", false);\n\n  const auto defaultGait = [&] {\n    Gait gait{};\n    gait.duration = defaultModeSequenceTemplate.switchingTimes.back();\n    // Events: from time -> phase\n    std::for_each(defaultModeSequenceTemplate.switchingTimes.begin() + 1, defaultModeSequenceTemplate.switchingTimes.end() - 1,\n                  [&](double eventTime) { gait.eventPhases.push_back(eventTime / gait.duration); });\n    // Modes:\n    gait.modeSequence = defaultModeSequenceTemplate.modeSequence;\n    return gait;\n  }();\n\n  // display\n  if (verbose) {\n    std::cerr << \"\\n#### Modes Schedule: \";\n    std::cerr << \"\\n#### =============================================================================\\n\";\n    std::cerr << \"Initial Modes Schedule: \\n\" << initModeSchedule;\n    std::cerr << \"Default Modes Sequence Template: \\n\" << defaultModeSequenceTemplate;\n    std::cerr << \"#### =============================================================================\\n\";\n  }\n\n  return std::make_shared<GaitSchedule>(initModeSchedule, defaultModeSequenceTemplate, modelSettings_.phaseTransitionStanceTime);\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nmatrix_t LeggedRobotInterface::initializeInputCostWeight(const std::string& taskFile, const CentroidalModelInfo& info) {\n  const size_t totalContactDim = 3 * info.numThreeDofContacts;\n\n  vector_t initialState(centroidalModelInfo_.stateDim);\n  loadData::loadEigenMatrix(taskFile, \"initialState\", initialState);\n\n  const auto& model = pinocchioInterfacePtr_->getModel();\n  auto& data = pinocchioInterfacePtr_->getData();\n  const auto q = centroidal_model::getGeneralizedCoordinates(initialState, centroidalModelInfo_);\n  pinocchio::computeJointJacobians(model, data, q);\n  pinocchio::updateFramePlacements(model, data);\n\n  matrix_t baseToFeetJacobians(totalContactDim, info.actuatedDofNum);\n  for (size_t i = 0; i < info.numThreeDofContacts; i++) {\n    matrix_t jacobianWorldToContactPointInWorldFrame = matrix_t::Zero(6, info.generalizedCoordinatesNum);\n    pinocchio::getFrameJacobian(model, data, model.getBodyId(modelSettings_.contactNames3DoF[i]), pinocchio::LOCAL_WORLD_ALIGNED,\n                                jacobianWorldToContactPointInWorldFrame);\n\n    baseToFeetJacobians.block(3 * i, 0, 3, info.actuatedDofNum) =\n        jacobianWorldToContactPointInWorldFrame.block(0, 6, 3, info.actuatedDofNum);\n  }\n\n  matrix_t R_taskspace(totalContactDim + totalContactDim, totalContactDim + totalContactDim);\n  loadData::loadEigenMatrix(taskFile, \"R\", R_taskspace);\n\n  matrix_t R = matrix_t::Zero(info.inputDim, info.inputDim);\n  // Contact Forces\n  R.topLeftCorner(totalContactDim, totalContactDim) = R_taskspace.topLeftCorner(totalContactDim, totalContactDim);\n  // Joint velocities\n  R.bottomRightCorner(info.actuatedDofNum, info.actuatedDofNum) =\n      baseToFeetJacobians.transpose() * R_taskspace.bottomRightCorner(totalContactDim, totalContactDim) * baseToFeetJacobians;\n  return R;\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nstd::unique_ptr<StateInputCost> LeggedRobotInterface::getBaseTrackingCost(const std::string& taskFile, const CentroidalModelInfo& info,\n                                                                          bool verbose) {\n  matrix_t Q(info.stateDim, info.stateDim);\n  loadData::loadEigenMatrix(taskFile, \"Q\", Q);\n  matrix_t R = initializeInputCostWeight(taskFile, info);\n\n  if (verbose) {\n    std::cerr << \"\\n #### Base Tracking Cost Coefficients: \";\n    std::cerr << \"\\n #### =============================================================================\\n\";\n    std::cerr << \"Q:\\n\" << Q << \"\\n\";\n    std::cerr << \"R:\\n\" << R << \"\\n\";\n    std::cerr << \" #### =============================================================================\\n\";\n  }\n\n  return std::unique_ptr<StateInputCost>(new LeggedRobotStateInputQuadraticCost(std::move(Q), std::move(R), info, *referenceManagerPtr_));\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nstd::pair<scalar_t, RelaxedBarrierPenalty::Config> LeggedRobotInterface::loadFrictionConeSettings(const std::string& taskFile,\n                                                                                                  bool verbose) const {\n  boost::property_tree::ptree pt;\n  boost::property_tree::read_info(taskFile, pt);\n  const std::string prefix = \"frictionConeSoftConstraint.\";\n\n  scalar_t frictionCoefficient = 1.0;\n  RelaxedBarrierPenalty::Config barrierPenaltyConfig;\n  if (verbose) {\n    std::cerr << \"\\n #### Friction Cone Settings: \";\n    std::cerr << \"\\n #### =============================================================================\\n\";\n  }\n  loadData::loadPtreeValue(pt, frictionCoefficient, prefix + \"frictionCoefficient\", verbose);\n  loadData::loadPtreeValue(pt, barrierPenaltyConfig.mu, prefix + \"mu\", verbose);\n  loadData::loadPtreeValue(pt, barrierPenaltyConfig.delta, prefix + \"delta\", verbose);\n  if (verbose) {\n    std::cerr << \" #### =============================================================================\\n\";\n  }\n\n  return {frictionCoefficient, std::move(barrierPenaltyConfig)};\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nstd::unique_ptr<StateInputCost> LeggedRobotInterface::getFrictionConeConstraint(size_t contactPointIndex, scalar_t frictionCoefficient,\n                                                                                const RelaxedBarrierPenalty::Config& barrierPenaltyConfig) {\n  FrictionConeConstraint::Config frictionConeConConfig(frictionCoefficient);\n  std::unique_ptr<FrictionConeConstraint> frictionConeConstraintPtr(\n      new FrictionConeConstraint(*referenceManagerPtr_, std::move(frictionConeConConfig), contactPointIndex, centroidalModelInfo_));\n\n  std::unique_ptr<PenaltyBase> penalty(new RelaxedBarrierPenalty(barrierPenaltyConfig));\n\n  return std::unique_ptr<StateInputCost>(new StateInputSoftConstraint(std::move(frictionConeConstraintPtr), std::move(penalty)));\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nstd::unique_ptr<StateInputConstraint> LeggedRobotInterface::getZeroForceConstraint(size_t contactPointIndex) {\n  return std::unique_ptr<StateInputConstraint>(new ZeroForceConstraint(*referenceManagerPtr_, contactPointIndex, centroidalModelInfo_));\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nstd::unique_ptr<StateInputConstraint> LeggedRobotInterface::getZeroVelocityConstraint(const EndEffectorKinematics<scalar_t>& eeKinematics,\n                                                                                      size_t contactPointIndex,\n                                                                                      bool useAnalyticalGradients) {\n  auto eeZeroVelConConfig = [](scalar_t positionErrorGain) {\n    EndEffectorLinearConstraint::Config config;\n    config.b.setZero(3);\n    config.Av.setIdentity(3, 3);\n    if (!numerics::almost_eq(positionErrorGain, 0.0)) {\n      config.Ax.setZero(3, 3);\n      config.Ax(2, 2) = positionErrorGain;\n    }\n    return config;\n  };\n\n  if (useAnalyticalGradients) {\n    throw std::runtime_error(\n        \"[LeggedRobotInterface::getZeroVelocityConstraint] The analytical end-effector zero velocity constraint is not implemented!\");\n  } else {\n    return std::unique_ptr<StateInputConstraint>(new ZeroVelocityConstraintCppAd(*referenceManagerPtr_, eeKinematics, contactPointIndex,\n                                                                                 eeZeroVelConConfig(modelSettings_.positionErrorGain)));\n  }\n}\n\n/******************************************************************************************************/\n/******************************************************************************************************/\n/******************************************************************************************************/\nstd::unique_ptr<StateInputConstraint> LeggedRobotInterface::getNormalVelocityConstraint(const EndEffectorKinematics<scalar_t>& eeKinematics,\n                                                                                        size_t contactPointIndex,\n                                                                                        bool useAnalyticalGradients) {\n  if (useAnalyticalGradients) {\n    throw std::runtime_error(\n        \"[LeggedRobotInterface::getNormalVelocityConstraint] The analytical end-effector normal velocity constraint is not implemented!\");\n  } else {\n    return std::unique_ptr<StateInputConstraint>(new NormalVelocityConstraintCppAd(*referenceManagerPtr_, eeKinematics, contactPointIndex));\n  }\n}\n\n}  // namespace legged_robot\n}  // namespace ocs2\n", "meta": {"hexsha": "29815cf882c5e6327311c6b647abf0a36dbe3f7d", "size": 21403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ocs2_robotic_examples/ocs2_legged_robot/src/LeggedRobotInterface.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_robotic_examples/ocs2_legged_robot/src/LeggedRobotInterface.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_robotic_examples/ocs2_legged_robot/src/LeggedRobotInterface.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": 57.3806970509, "max_line_length": 140, "alphanum_fraction": 0.6026725225, "num_tokens": 4132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1787912310465456}}
{"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#include <boost/simd/function/shuffle.hpp>\n#include <boost/simd/pack.hpp>\n#include <simd_test.hpp>\n#include \"reference.hpp\"\n\nusing namespace boost::simd;\n\nSTF_CASE_TPL( \"Cardinal 4 shuffles resolving as AVX permute2f\"\n            , (double)(std::int64_t)(std::uint64_t)\n            )\n{\n  bs::pack<T,4> a{ Valmax<T>(), T(42), T(13), Valmin<T>() };\n  bs::pack<T,4> b{ T(69), Valmin<T>(), T(37), T(0) };\n\n  STF_ALL_EQUAL( (shuffle<2, 3, 0, 1>(a))  , ( unary_ref<2, 3, 0, 1>(a)  )  );\n\n  STF_ALL_EQUAL( (shuffle<2, 3, 0, 1>(a,b)), (binary_ref<2, 3, 0, 1>(a,b))  );\n  STF_ALL_EQUAL( (shuffle<4, 5, 0, 1>(a,b)), (binary_ref<4, 5, 0, 1>(a,b))  );\n  STF_ALL_EQUAL( (shuffle<6, 7, 0, 1>(a,b)), (binary_ref<6, 7, 0, 1>(a,b))  );\n  STF_ALL_EQUAL( (shuffle<6, 7, 2, 3>(a,b)), (binary_ref<6, 7, 2, 3>(a,b))  );\n  STF_ALL_EQUAL( (shuffle<0, 1, 4, 5>(a,b)), (binary_ref<0, 1, 4, 5>(a,b))  );\n  STF_ALL_EQUAL( (shuffle<2, 3, 4, 5>(a,b)), (binary_ref<2, 3, 4, 5>(a,b))  );\n  STF_ALL_EQUAL( (shuffle<6, 7, 4, 5>(a,b)), (binary_ref<6, 7, 4, 5>(a,b))  );\n  STF_ALL_EQUAL( (shuffle<2, 3, 6, 7>(a,b)), (binary_ref<2, 3, 6, 7>(a,b))  );\n}\n", "meta": {"hexsha": "6ae28f1878653cb6f603623e6e6ca0b7f3da59a6", "size": 1499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/shuffle/cardinal.4.avx.perm2.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/function/simd/shuffle/cardinal.4.avx.perm2.cpp", "max_issues_repo_name": "dendisuhubdy/boost.simd", "max_issues_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "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/function/simd/shuffle/cardinal.4.avx.perm2.cpp", "max_forks_repo_name": "dendisuhubdy/boost.simd", "max_forks_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "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": 44.0882352941, "max_line_length": 100, "alphanum_fraction": 0.5063375584, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.17879122753823784}}
{"text": "#pragma once\n#include <boost/rational.hpp>\n#include <cstddef>\n#include <memory>\n#include <string>\n\n#include \"ear/metadata.hpp\"\n\nnamespace bear {\n\nstruct ConfigImpl;\nstruct ListenerImpl;\nclass RendererImpl;\n\n/// configuration for the renderer\nclass Config {\n public:\n  Config();\n  Config(const Config &c);\n  ~Config();\n\n  Config &operator=(const Config &c);\n\n  /// set the number of Objects channels (default 0)\n  void set_num_objects_channels(size_t num_channels);\n  size_t get_num_objects_channels() const;\n\n  /// set the number of DirectSpeakers channels (default 0)\n  void set_num_direct_speakers_channels(size_t num_channels);\n  size_t get_num_direct_speakers_channels() const;\n\n  /// set the number of HOA channels (default 0)\n  void set_num_hoa_channels(size_t num_channels);\n  size_t get_num_hoa_channels() const;\n\n  /// set the number of samples in a period (no default, must be set)\n  void set_period_size(size_t num_samples);\n  size_t get_period_size() const;\n\n  /// set the sample rate (default: 48kHz)\n  void set_sample_rate(size_t sample_rate);\n  size_t get_sample_rate() const;\n\n  /// set the path to the data file (no default, must be set)\n  void set_data_path(const std::string &path);\n  const std::string &get_data_path() const;\n\n  /// set the FFT implementation to use (default: a built-in implementation)\n  void set_fft_implementation(const std::string &fft_implementation);\n  const std::string &get_fft_implementation() const;\n\n  /// check that the configuration is valid; raises exceptions for missing or\n  /// incorrect values\n  void validate() const;\n\n  ConfigImpl &get_impl();\n  const ConfigImpl &get_impl() const;\n\n private:\n  std::unique_ptr<ConfigImpl> impl;\n};\n\nusing Sample = float;\n// time in seconds\nusing Time = boost::rational<int64_t>;\n\n/// interface for specifying distance behaviour.\nclass DistanceBehaviour {\n public:\n  virtual ~DistanceBehaviour() {}\n  /// given the distance to an object and the absoluteDistance parameter, get a\n  /// linear gain to be applied\n  ///\n  /// if absoluteDistance is set, distance is the distance parameter multiplied\n  /// by the absoluteDistance in metres, accounting for the listener head\n  /// position\n  ///\n  /// if it's not set, distance is just the distance parameter\n  ///\n  /// For standard behaviour, this should return 1.0 (or a constant value) if\n  /// absoluteDistance is not provided, as BS.2076-2 says:\n  ///\n  ///   If absoluteDistance is negative or undefined, distance based binaural\n  ///   rendering is not intended.\n  virtual double get_gain(double distance, boost::optional<double> absoluteDistance) = 0;\n};\n\nstruct AudioPackFormatData {\n  boost::optional<double> absoluteDistance;\n};\n\nstruct MetadataInput {\n  boost::optional<Time> rtime;\n  boost::optional<Time> duration;\n  AudioPackFormatData audioPackFormat_data;\n};\n\nstruct ObjectsInput : public MetadataInput {\n  ear::ObjectsTypeMetadata type_metadata;\n  boost::optional<Time> interpolationLength;\n  /// distance behaviour; there is no distance-dependant gain if null\n  std::shared_ptr<DistanceBehaviour> distance_behaviour = nullptr;\n};\n\nstruct DirectSpeakersInput : public MetadataInput {\n  ear::DirectSpeakersTypeMetadata type_metadata;\n};\n\nstruct HOAInput : public MetadataInput {\n  ear::HOATypeMetadata type_metadata;\n  std::vector<size_t> channels;\n};\n\n/// Representation of the listener position and head orientation.\n///\n/// The ADM Cartesian coordinate system is used, as defined in section 8 of\n/// BS.2076-2.\nclass Listener {\n public:\n  Listener();\n  ~Listener();\n  Listener(const Listener &);\n\n  /// ADM-format Cartesian position of the listener relative to the origin in\n  /// metres\n  void set_position_cart(std::array<double, 3>);\n  std::array<double, 3> get_position_cart() const;\n\n  /// orientation of the listener; this translates from world coordinates to\n  /// listener coordinates, so:\n  ///     position_rel_listener = orientation * position\n  ///     position = orientation' * position_rel_listener\n  /// quaternion in order {w, x, y, z}, with the coordinate axes from the ADM\n  /// Cartesian system\n  void set_orientation_quaternion(std::array<double, 4>);\n  std::array<double, 4> get_orientation_quaternion() const;\n\n  Listener &operator=(const Listener &other);\n\n  /// methods intended for testing rotation mappings\n\n  /// the ADM-format Cartesian vector that the listener is looking along\n  std::array<double, 3> look() const;\n  /// the ADM-format Cartesian vector to the right of the listener\n  std::array<double, 3> right() const;\n  /// the ADM-format Cartesian vector pointing up from the listener\n  std::array<double, 3> up() const;\n\n  const ListenerImpl &get_impl() const;\n\n private:\n  std::unique_ptr<ListenerImpl> impl;\n};\n\nclass Renderer {\n public:\n  Renderer(const Config &config);\n  Renderer(Renderer &&r);\n  Renderer();\n  ~Renderer();\n\n  Renderer &operator=(Renderer &&r);\n\n  /// process period_size samples\n  ///\n  /// @param objects_input num_objects_channels pointers to period_size samples\n  ///     of objects input audio\n  /// @param direct_speakers_input num_direct_speakers_channels pointers to\n  ///     period_size samples of direct speakers input audio\n  /// @param hoa_input num_hoa_channels pointers to period_size samples of HOA\n  ///     input audio\n  /// @param output 2 pointers to period_size samples to store the output audio\n  void process(const Sample *const *objects_input,\n               const Sample *const *direct_speakers_input,\n               const Sample *const *hoa_input,\n               Sample *const *output);\n\n  /// Add some objects metadata to be rendered. This returns true if the\n  /// metadata was stored, or false if it was added too early and should be\n  /// pushed after processing more samples.\n  ///\n  /// timing behaviour:\n  /// - If metadata contains an rtime equal to the rtime+duration of the\n  ///   previous block, there will be interpolation from the previous block\n  ///   over the interpolationLength (or the full block if that is not\n  ///   specified), followed by constant rendering for the rest of the block.\n  /// - If metadata contains an rtime greater than to the rtime+duration of the\n  ///   previous block (or it is the first block), the rendering will be\n  ///   constant over the length of the block. Between the end of the previous\n  ///   block (or the start of the audio processing) and the start of this\n  ///   block, there will be silence.\n  /// - If the rtime is less than the rtime+duration of the previous block, and\n  ///   the rtime is greater than or equal to block_start_time, then the\n  ///   samples during the previous block will not be affected, but the\n  ///   interpolation during the current block will be smooth. this means that\n  ///   this sequence:\n  ///\n  ///       add(a, 0..100)\n  ///       add(b, 100..200)\n  ///       add(c, 150..200)\n  ///\n  ///   results in these interpolation points:\n  ///\n  ///       time   value\n  ///       0      a\n  ///       100    a\n  ///       150    (a + b) / 2\n  ///       200    c\n  ///\n  ///   If the rtime is less than block_start_time, the result is not\n  ///   specified, except that the interpolation at the end of the block uses\n  ///   the specified metadata; this can be used to reset the renderer to a\n  ///   known state, for example to start rendering half way through a block\n  ///   after seeking or when rendering a block which has been changed.\n  /// @param channel channel in objects_input that this metadata corresponds to\n  bool add_objects_block(size_t channel, ObjectsInput metadata);\n\n  /// Add direct speakers metadata; the semantics are the same as\n  /// add_objects_block, except that no interpolation occurs.\n  ///\n  /// @param channel channel in direct_speakers_input that this metadata\n  ///     applies to\n  bool add_direct_speakers_block(size_t channel, DirectSpeakersInput metadata);\n\n  /// Add HOA metadata; the semantics are the same as\n  /// add_direct_speakers_block, except because HOA metadata refers to multiple\n  /// channels, a stream identifier is used rather than a channel number.\n  /// @param stream arbitrary value used to identify which HOA stream this\n  ///     metadata applies to\n  bool add_hoa_block(size_t stream, HOAInput metadata);\n\n  /// start time of the first sample in the next block\n  Time get_block_start_time() const;\n\n  /// set the start time of the first sample in the next block\n  ///\n  /// note that this is purely convenience to apply an offset to the rtimes of\n  /// the added blocks at the time they are pushed; the specified timing\n  /// behaviour still applies\n  void set_block_start_time(const Time &time);\n\n  /// get the delay added by the renderer\n  Time get_delay() const;\n\n  /// set the listener position and orientation in the next frame. If\n  /// interpolation_time is specified, then the change will possibly be\n  /// interpolated over more than one frame; this may be useful if the head\n  /// position update rate is slower than the frame rate.\n  ///\n  /// note that we don't keep a reference to Listener; you should call this\n  /// every frame (or so).\n  void set_listener(const Listener &l, const boost::optional<Time> &interpolation_time = {});\n\n private:\n  std::unique_ptr<RendererImpl> impl;\n};\n\n};  // namespace bear\n", "meta": {"hexsha": "0e5d101917458ecf99b2ec11c47dd27754821d7e", "size": 9209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "visr_bear/include/bear/api.hpp", "max_stars_repo_name": "ebu/bear", "max_stars_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2022-02-01T16:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T11:24:59.000Z", "max_issues_repo_path": "visr_bear/include/bear/api.hpp", "max_issues_repo_name": "ebu/bear", "max_issues_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-03T06:49:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:10:43.000Z", "max_forks_repo_path": "visr_bear/include/bear/api.hpp", "max_forks_repo_name": "ebu/bear", "max_forks_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "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.555984556, "max_line_length": 93, "alphanum_fraction": 0.7163644261, "num_tokens": 2152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.1787912275382378}}
{"text": "/*!\n * Copyright (c) 2021 Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See LICENSE file in the project root for\n * license information.\n */\n#include \"RangeReduceExpression.h\"\n\n#include <boost/make_shared.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <sstream>\n\n#include \"BinaryOperator.h\"\n#include \"Conditional.h\"\n#include \"FreeForm2Assert.h\"\n#include \"LiteralExpression.h\"\n#include \"OperatorExpression.h\"\n#include \"RefExpression.h\"\n#include \"SimpleExpressionOwner.h\"\n#include \"TypeUtil.h\"\n#include \"UnaryOperator.h\"\n#include \"Visitor.h\"\n\nnamespace {\n// This method creates the following precondition expression:\n//    (max(low, high) - abs(step) < max(low, high))\n// && (min(low, high) + abs(step) > min(low, high))\n// && ((step > 0) == (high > low))\n// && step != 0)\n// and the following loop condition:\n// (step > 0 ? loopVar <= high - step\n//           : loopVar >= high - step).\n\nboost::tuple<const FreeForm2::Expression *, const FreeForm2::Expression *>\nCreateGenericLoopConditions(\n    const std::pair<const FreeForm2::Expression *,\n                    const FreeForm2::Expression *> &p_range,\n    const FreeForm2::Expression &p_step, const FreeForm2::Expression &p_loopVar,\n    FreeForm2::SimpleExpressionOwner &p_owner,\n    FreeForm2::TypeManager &p_typeManager) {\n  using namespace FreeForm2;\n\n  // Common expressions.\n  auto zero =\n      boost::make_shared<LiteralInt32Expression>(p_loopVar.GetAnnotations(), 0);\n  p_owner.AddExpression(zero);\n  auto stepSign =\n      BinaryOperatorExpression::Alloc(p_loopVar.GetAnnotations(), p_step, *zero,\n                                      BinaryOperator::gt, p_typeManager);\n  p_owner.AddExpression(stepSign);\n\n  // Create the precondition\n  const Expression *precondition = nullptr;\n  {\n    auto high = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *p_range.first, *p_range.second,\n        BinaryOperator::max, p_typeManager);\n    p_owner.AddExpression(high);\n    auto low = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *p_range.first, *p_range.second,\n        BinaryOperator::min, p_typeManager);\n    p_owner.AddExpression(low);\n    auto step = boost::make_shared<UnaryOperatorExpression>(\n        p_loopVar.GetAnnotations(), p_step, UnaryOperator::abs);\n    p_owner.AddExpression(step);\n    auto highMinusStep = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *high, *step, BinaryOperator::minus,\n        p_typeManager);\n    p_owner.AddExpression(highMinusStep);\n    auto lowPlusStep =\n        BinaryOperatorExpression::Alloc(p_loopVar.GetAnnotations(), *low, *step,\n                                        BinaryOperator::plus, p_typeManager);\n    p_owner.AddExpression(lowPlusStep);\n    auto underflowCheck = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *highMinusStep, *high, BinaryOperator::lt,\n        p_typeManager);\n    p_owner.AddExpression(underflowCheck);\n    auto overflowCheck = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *lowPlusStep, *low, BinaryOperator::gt,\n        p_typeManager);\n    p_owner.AddExpression(overflowCheck);\n    auto stepMoving = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), p_step, *zero, BinaryOperator::neq,\n        p_typeManager);\n    p_owner.AddExpression(stepMoving);\n    auto rangeSign = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *p_range.second, *p_range.first,\n        BinaryOperator::gt, p_typeManager);\n    p_owner.AddExpression(rangeSign);\n    auto rangeCheck = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *stepSign, *rangeSign, BinaryOperator::eq,\n        p_typeManager);\n    p_owner.AddExpression(rangeCheck);\n    auto and1 = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *underflowCheck, *overflowCheck,\n        BinaryOperator::_and, p_typeManager);\n    p_owner.AddExpression(and1);\n    auto and2 = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *and1, *rangeCheck, BinaryOperator::_and,\n        p_typeManager);\n    p_owner.AddExpression(and2);\n    auto and3 = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *and2, *stepMoving, BinaryOperator::_and,\n        p_typeManager);\n    p_owner.AddExpression(and3);\n    precondition = and3.get();\n  }\n\n  // Create the loop condition.\n  const Expression *condition = nullptr;\n  {\n    auto endMinusStep = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *p_range.second, p_step,\n        BinaryOperator::minus, p_typeManager);\n    p_owner.AddExpression(endMinusStep);\n    auto incRange = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), p_loopVar, *endMinusStep,\n        BinaryOperator::lte, p_typeManager);\n    p_owner.AddExpression(incRange);\n    auto decRange = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), p_loopVar, *endMinusStep,\n        BinaryOperator::gte, p_typeManager);\n    p_owner.AddExpression(decRange);\n    auto cond = boost::make_shared<ConditionalExpression>(\n        p_loopVar.GetAnnotations(), *stepSign, *incRange, *decRange);\n    p_owner.AddExpression(cond);\n    condition = cond.get();\n  }\n\n  return boost::make_tuple(precondition, condition);\n}\n\nboost::tuple<const FreeForm2::Expression *, const FreeForm2::Expression *>\nCreateConditionsForKnownStep(\n    const std::pair<const FreeForm2::Expression *,\n                    const FreeForm2::Expression *> &p_range,\n    const FreeForm2::Expression &p_step, const FreeForm2::Expression &p_loopVar,\n    FreeForm2::SimpleExpressionOwner &p_owner,\n    FreeForm2::TypeManager &p_typeManager) {\n  using namespace FreeForm2;\n  FF2_ASSERT(p_step.IsConstant() &&\n             p_step.GetConstantValue().GetInt(p_step.GetType()) != 0);\n  const Result::IntType stepVal =\n      p_step.GetConstantValue().GetInt(p_step.GetType());\n  const bool isIncreasing = stepVal > 0;\n\n  // For increasing ranges, create the expression:\n  // ((high - step < high) && (low + step > low) && high > low)\n  // For decreasing ranges, create the expression:\n  // ((high - step > high) && (low + step < low) && high < low)\n  const Expression *precondition = nullptr;\n  {\n    const Expression &low = *p_range.first;\n    const Expression &high = *p_range.second;\n    auto highMinusStep = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), high, p_step, BinaryOperator::minus,\n        p_typeManager);\n    p_owner.AddExpression(highMinusStep);\n    auto lowPlusStep =\n        BinaryOperatorExpression::Alloc(p_loopVar.GetAnnotations(), low, p_step,\n                                        BinaryOperator::plus, p_typeManager);\n    p_owner.AddExpression(lowPlusStep);\n    const BinaryOperator::Operation check1Op =\n        isIncreasing ? BinaryOperator::lt : BinaryOperator::gt;\n    auto check1 = BinaryOperatorExpression::Alloc(p_loopVar.GetAnnotations(),\n                                                  *highMinusStep, high,\n                                                  check1Op, p_typeManager);\n    p_owner.AddExpression(check1);\n    const BinaryOperator::Operation check2Op =\n        isIncreasing ? BinaryOperator::gt : BinaryOperator::lt;\n    auto check2 = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *lowPlusStep, low, check2Op, p_typeManager);\n    p_owner.AddExpression(check2);\n    const BinaryOperator::Operation rangeOp =\n        isIncreasing ? BinaryOperator::gt : BinaryOperator::lt;\n    auto rangeCheck = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), high, low, rangeOp, p_typeManager);\n    p_owner.AddExpression(rangeCheck);\n    auto and1 = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *check1, *check2, BinaryOperator::_and,\n        p_typeManager);\n    p_owner.AddExpression(and1);\n    auto and2 = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), *and1, *rangeCheck, BinaryOperator::_and,\n        p_typeManager);\n    p_owner.AddExpression(and2);\n    precondition = and2.get();\n  }\n\n  // For increasing ranges, create the expression: loopVar <= high - step.\n  // For decreasing ranges, create the expression: loopVar >= high - step.\n  const Expression *condition = nullptr;\n  {\n    const Expression &high = *p_range.second;\n    auto highMinusStep = BinaryOperatorExpression::Alloc(\n        p_loopVar.GetAnnotations(), high, p_step, BinaryOperator::minus,\n        p_typeManager);\n    p_owner.AddExpression(highMinusStep);\n    const BinaryOperator::Operation compareOp =\n        isIncreasing ? BinaryOperator::lte : BinaryOperator::gte;\n    auto compare = BinaryOperatorExpression::Alloc(p_loopVar.GetAnnotations(),\n                                                   p_loopVar, *highMinusStep,\n                                                   compareOp, p_typeManager);\n    p_owner.AddExpression(compare);\n    condition = compare.get();\n  }\n\n  return boost::make_tuple(precondition, condition);\n}\n}  // namespace\n\nFreeForm2::RangeReduceExpression::RangeReduceExpression(\n    const Annotations &p_annotations, const Expression &p_low,\n    const Expression &p_high, const Expression &p_initial,\n    const Expression &p_reduce, VariableID p_stepId, VariableID p_reduceId)\n    : Expression(p_annotations),\n      m_low(p_low),\n      m_high(p_high),\n      m_initial(p_initial),\n      m_reduce(p_reduce),\n      m_stepId(p_stepId),\n      m_reduceId(p_reduceId),\n      m_type(InferType()) {}\n\nconst FreeForm2::TypeImpl &FreeForm2::RangeReduceExpression::InferType() const {\n  if (!m_low.GetType().IsIntegerType() || !m_high.GetType().IsIntegerType()) {\n    std::ostringstream err;\n    err << \"Expected low range and high range arguments to be of compatible \"\n           \"integer types;\"\n        << \" got \" << m_low.GetType() << \", \" << m_high.GetType()\n        << \" respectively.\";\n    throw ParseError(err.str(), GetSourceLocation());\n  }\n\n  if (!(m_initial.GetType().IsSameAs(m_reduce.GetType(), true))) {\n    std::ostringstream err;\n    err << \"Expected initial reduction argument to range-reduce to \"\n           \"be of the same type as the reduction expression.  Got \"\n        << m_initial.GetType() << \" and \" << m_reduce.GetType()\n        << \" respectively.\";\n    throw ParseError(err.str(), GetSourceLocation());\n  }\n\n  if (m_reduce.GetType().Primitive() == Type::Array) {\n    std::ostringstream err;\n    err << \"An array cannot be the result of a looping expression, \"\n           \"such as range-reduce, as our array representation \"\n           \"relies on reusing array space (and thus uses constant \"\n           \"space).  If arrays were the result of loops using this \"\n           \"representation, dangling pointers would result.\";\n    throw ParseError(err.str(), GetSourceLocation());\n  }\n  return m_reduce.GetType().AsConstType();\n}\n\nsize_t FreeForm2::RangeReduceExpression::GetNumChildren() const { return 4; }\n\nvoid FreeForm2::RangeReduceExpression::Accept(Visitor &p_visitor) const {\n  size_t stackSize = p_visitor.StackSize();\n\n  if (!p_visitor.AlternativeVisit(*this)) {\n    m_initial.Accept(p_visitor);\n    m_high.Accept(p_visitor);\n    m_low.Accept(p_visitor);\n    m_reduce.Accept(p_visitor);\n\n    p_visitor.Visit(*this);\n  }\n\n  FF2_ASSERT(p_visitor.StackSize() == stackSize + p_visitor.StackIncrement());\n}\n\nconst FreeForm2::TypeImpl &FreeForm2::RangeReduceExpression::GetType() const {\n  return m_type;\n}\n\nconst FreeForm2::Expression &FreeForm2::RangeReduceExpression::GetLow() const {\n  return m_low;\n}\n\nconst FreeForm2::Expression &FreeForm2::RangeReduceExpression::GetHigh() const {\n  return m_high;\n}\n\nconst FreeForm2::Expression &FreeForm2::RangeReduceExpression::GetInitial()\n    const {\n  return m_initial;\n}\n\nconst FreeForm2::Expression &\nFreeForm2::RangeReduceExpression::GetReduceExpression() const {\n  return m_reduce;\n}\n\nFreeForm2::VariableID FreeForm2::RangeReduceExpression::GetReduceId() const {\n  return m_reduceId;\n}\n\nFreeForm2::VariableID FreeForm2::RangeReduceExpression::GetStepId() const {\n  return m_stepId;\n}\n\nFreeForm2::ForEachLoopExpression::ForEachLoopExpression(\n    const Annotations &p_annotations,\n    const std::pair<const Expression *, const Expression *> &p_bounds,\n    const Expression &p_next, const Expression &p_body, VariableID p_iteratorId,\n    size_t p_version, LoopHint p_hint, TypeManager &p_typeManager)\n    : Expression(p_annotations),\n      m_begin(*p_bounds.first),\n      m_end(*p_bounds.second),\n      m_next(p_next),\n      m_body(p_body),\n      m_iteratorType(nullptr),\n      m_iteratorId(p_iteratorId),\n      m_version(p_version),\n      m_hint(p_hint) {\n  FF2_ASSERT(p_bounds.first && p_bounds.second);\n  m_iteratorType = &TypeUtil::Unify(m_begin.GetType(), m_end.GetType(),\n                                    p_typeManager, false, true);\n  m_iteratorType = &TypeUtil::Unify(m_next.GetType(), *m_iteratorType,\n                                    p_typeManager, false, true);\n\n  if (!m_iteratorType->IsValid()) {\n    std::ostringstream err;\n    err << \"For-each bounds must have unifiable types. Got \"\n        << m_begin.GetType() << \", \" << m_end.GetType() << \", and \"\n        << m_next.GetType()\n        << \" for beginning, ending, and step values respectively.\";\n    throw ParseError(err.str(), GetSourceLocation());\n  }\n}\n\nsize_t FreeForm2::ForEachLoopExpression::GetNumChildren() const { return 4; }\n\nvoid FreeForm2::ForEachLoopExpression::Accept(Visitor &p_visitor) const {\n  size_t stackSize = p_visitor.StackSize();\n\n  if (!p_visitor.AlternativeVisit(*this)) {\n    m_begin.Accept(p_visitor);\n    m_end.Accept(p_visitor);\n    m_next.Accept(p_visitor);\n    m_body.Accept(p_visitor);\n\n    p_visitor.Visit(*this);\n  }\n\n  FF2_ASSERT(p_visitor.StackSize() == stackSize + p_visitor.StackIncrement());\n}\n\nconst FreeForm2::TypeImpl &FreeForm2::ForEachLoopExpression::GetType() const {\n  return TypeImpl::GetVoidInstance();\n}\n\nconst FreeForm2::Expression &FreeForm2::ForEachLoopExpression::GetBegin()\n    const {\n  return m_begin;\n}\n\nconst FreeForm2::Expression &FreeForm2::ForEachLoopExpression::GetEnd() const {\n  return m_end;\n}\n\nconst FreeForm2::Expression &FreeForm2::ForEachLoopExpression::GetNext() const {\n  return m_next;\n}\n\nconst FreeForm2::Expression &FreeForm2::ForEachLoopExpression::GetBody() const {\n  return m_body;\n}\n\nconst FreeForm2::TypeImpl &FreeForm2::ForEachLoopExpression::GetIteratorType()\n    const {\n  return *m_iteratorType;\n}\n\nFreeForm2::VariableID FreeForm2::ForEachLoopExpression::GetIteratorId() const {\n  return m_iteratorId;\n}\n\nsize_t FreeForm2::ForEachLoopExpression::GetVersion() const {\n  return m_version;\n}\n\nFreeForm2::ForEachLoopExpression::LoopHint\nFreeForm2::ForEachLoopExpression::GetHint() const {\n  return m_hint;\n}\n\nFreeForm2::ComplexRangeLoopExpression::ComplexRangeLoopExpression(\n    const Annotations &p_annotations,\n    const std::pair<const Expression *, const Expression *> &p_range,\n    const Expression &p_step, const Expression &p_body,\n    const Expression &p_precondition, const Expression &p_loopCondition,\n    const TypeImpl &p_stepType, VariableID p_stepId, size_t p_version)\n    : Expression(p_annotations),\n      m_low(*p_range.first),\n      m_high(*p_range.second),\n      m_step(p_step),\n      m_body(p_body),\n      m_precondition(p_precondition),\n      m_loopCondition(p_loopCondition),\n      m_stepType(p_stepType),\n      m_stepId(p_stepId),\n      m_version(p_version) {\n  FF2_ASSERT(p_range.first && p_range.second);\n  FF2_ASSERT(p_stepId != VariableID::c_invalidID);\n  if (!p_range.first->GetType().IsIntegerType() ||\n      !p_range.second->GetType().IsIntegerType() ||\n      !p_step.GetType().IsIntegerType()) {\n    std::ostringstream err;\n    err << \"Range bounds and step value must all be integral types. Got \"\n        << p_range.first->GetType() << \", \" << p_range.second->GetType()\n        << \", and \" << p_step.GetType()\n        << \" for low, high, and step respectively.\";\n    throw ParseError(err.str(), GetSourceLocation());\n  }\n\n  if (p_precondition.GetType().Primitive() != Type::Bool ||\n      p_loopCondition.GetType().Primitive() != Type::Bool) {\n    std::ostringstream err;\n    err << \"Loop conditions must evaluate to boolean types. Got \"\n        << p_precondition.GetType() << \" and \" << p_loopCondition.GetType()\n        << \" for the precondition and loop condition respectively.\";\n    throw ParseError(err.str(), GetSourceLocation());\n  }\n}\n\nconst FreeForm2::ComplexRangeLoopExpression &\nFreeForm2::ComplexRangeLoopExpression::Create(\n    const Annotations &p_annotations,\n    const std::pair<const Expression *, const Expression *> &p_range,\n    const Expression &p_step, const Expression &p_body,\n    const Expression &p_loopVar, VariableID p_stepId, size_t p_version,\n    SimpleExpressionOwner &p_owner, TypeManager &p_typeManager) {\n  FF2_ASSERT(p_range.first && p_range.second);\n  const TypeImpl *stepType =\n      &TypeUtil::Unify(p_range.first->GetType(), p_range.second->GetType(),\n                       p_typeManager, false, true);\n  stepType =\n      &TypeUtil::Unify(*stepType, p_step.GetType(), p_typeManager, false, true);\n\n  if (!p_range.first->GetType().IsIntegerType() ||\n      !p_range.second->GetType().IsIntegerType() ||\n      !p_step.GetType().IsIntegerType() ||\n      !p_loopVar.GetType().IsIntegerType() ||\n      !TypeUtil::IsAssignable(p_loopVar.GetType(), *stepType)) {\n    std::ostringstream err;\n    err << \"Range bounds, step value, and loop variable must all be integral \"\n           \"types. Got \"\n        << p_range.first->GetType() << \", \" << p_range.second->GetType() << \", \"\n        << p_step.GetType() << \", and \" << p_loopVar.GetType()\n        << \" for low, high, and step respectively.\";\n    throw ParseError(err.str(), p_annotations.m_sourceLocation);\n  }\n\n  const Expression *precondition = nullptr;\n  const Expression *condition = nullptr;\n  if (p_step.IsConstant()) {\n    boost::tie(precondition, condition) = CreateConditionsForKnownStep(\n        p_range, p_step, p_loopVar, p_owner, p_typeManager);\n  } else {\n    boost::tie(precondition, condition) = CreateGenericLoopConditions(\n        p_range, p_step, p_loopVar, p_owner, p_typeManager);\n  }\n\n  FF2_ASSERT(precondition && condition);\n  auto loop = boost::make_shared<ComplexRangeLoopExpression>(\n      p_annotations, p_range, p_step, p_body, *precondition, *condition,\n      p_loopVar.GetType(), p_stepId, p_version);\n  p_owner.AddExpression(loop);\n  return *loop;\n}\n\nsize_t FreeForm2::ComplexRangeLoopExpression::GetNumChildren() const {\n  return 6;\n}\n\nvoid FreeForm2::ComplexRangeLoopExpression::Accept(Visitor &p_visitor) const {\n  size_t stackSize = p_visitor.StackSize();\n\n  if (!p_visitor.AlternativeVisit(*this)) {\n    m_precondition.Accept(p_visitor);\n    m_low.Accept(p_visitor);\n    m_high.Accept(p_visitor);\n    m_step.Accept(p_visitor);\n    m_body.Accept(p_visitor);\n    m_loopCondition.Accept(p_visitor);\n\n    p_visitor.Visit(*this);\n  }\n\n  FF2_ASSERT(p_visitor.StackSize() == stackSize + p_visitor.StackIncrement());\n}\n\nconst FreeForm2::TypeImpl &FreeForm2::ComplexRangeLoopExpression::GetType()\n    const {\n  return TypeImpl::GetVoidInstance();\n}\n\nconst FreeForm2::Expression &\nFreeForm2::ComplexRangeLoopExpression::GetPrecondition() const {\n  return m_precondition;\n}\n\nconst FreeForm2::Expression &FreeForm2::ComplexRangeLoopExpression::GetLow()\n    const {\n  return m_low;\n}\n\nconst FreeForm2::Expression &FreeForm2::ComplexRangeLoopExpression::GetHigh()\n    const {\n  return m_high;\n}\n\nconst FreeForm2::Expression &FreeForm2::ComplexRangeLoopExpression::GetStep()\n    const {\n  return m_step;\n}\n\nconst FreeForm2::Expression &FreeForm2::ComplexRangeLoopExpression::GetBody()\n    const {\n  return m_body;\n}\n\nconst FreeForm2::Expression &\nFreeForm2::ComplexRangeLoopExpression::GetLoopCondition() const {\n  return m_loopCondition;\n}\n\nconst FreeForm2::TypeImpl &FreeForm2::ComplexRangeLoopExpression::GetStepType()\n    const {\n  return m_stepType;\n}\n\nFreeForm2::VariableID FreeForm2::ComplexRangeLoopExpression::GetStepId() const {\n  return m_stepId;\n}\n\nsize_t FreeForm2::ComplexRangeLoopExpression::GetVersion() const {\n  return m_version;\n}\n", "meta": {"hexsha": "6a97f09c42e6ddf838ce00a59f380e3e6948cac5", "size": 20056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DynamicRank.FreeForm.Library/libs/Expression/RangeReduceExpression.cpp", "max_stars_repo_name": "ltxtech/lightgbm-transform", "max_stars_repo_head_hexsha": "ca3bdaae4e594c1bf74503c5ec151f2b794f855c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2021-11-02T13:52:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T07:43:38.000Z", "max_issues_repo_path": "src/DynamicRank.FreeForm.Library/libs/Expression/RangeReduceExpression.cpp", "max_issues_repo_name": "ltxtech/lightgbm-transform", "max_issues_repo_head_hexsha": "ca3bdaae4e594c1bf74503c5ec151f2b794f855c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-01-23T16:15:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T15:54:34.000Z", "max_forks_repo_path": "src/DynamicRank.FreeForm.Library/libs/Expression/RangeReduceExpression.cpp", "max_forks_repo_name": "ltxtech/lightgbm-transform", "max_forks_repo_head_hexsha": "ca3bdaae4e594c1bf74503c5ec151f2b794f855c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-21T09:42:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T09:42:59.000Z", "avg_line_length": 37.0720887246, "max_line_length": 80, "alphanum_fraction": 0.6973972876, "num_tokens": 4702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.17879122753823776}}
{"text": "// THIDFaceDeepFeat.cpp : Defines the exported functions for the DLL application.\n//\n\n#include <cstring>\n#include <map>\n#include <string>\n#include <vector>\n#include <memory>\n#include <fstream>\n\n#define GLOG_NO_ABBREVIATED_SEVERITIES\n\n#include \"glog/logging.h\"\n#include <boost/algorithm/string.hpp>\n#include \"caffe/caffe.hpp\"\n#include \"caffe/util/upgrade_proto.hpp\"\n#include <boost/algorithm/string.hpp>\n#include \"autoarray.h\"\n#include \"caffe/face_recognition/face_recognition.hpp\"\n#include \"AlgorithmUtils.h\"\n\nusing caffe::Blob;\nusing caffe::Caffe;\nusing caffe::Net;\nusing caffe::Layer;\nusing caffe::shared_ptr;\nusing caffe::Timer;\nusing caffe::vector;\n\n#ifndef _WIN32\n#define _MAX_PATH 260\n#endif\n\nnamespace\n{\n    char g_szFaceRecognitionSDKPath[_MAX_PATH] = { 0 };\n}\n\nint __stdcall InnerFaceRecognition(RecognitionHandle handle, const unsigned char *pNormImage, int batchSize, int channels,\n    int imageHeight, int imageWidth, float *pFeatures)\n{\n    int nRet = 0;\n    try\n    {\n        Net<float> *pCaffeNet = reinterpret_cast<Net<float> *>(handle);\n        int length = batchSize * channels * imageHeight * imageWidth;\n        AutoArray<float> normRealImage(length);\n        for (int i = 0; i < batchSize; ++i)\n        {\n            for (int j = 0; j < channels; ++j)\n            {\n                for (int h = 0; h < imageHeight; ++h)\n                {\n                    for (int w = 0; w < imageWidth; ++w)\n                    {\n                        int index = i * channels * imageHeight * imageWidth + j * imageHeight * imageWidth + h * imageWidth + w;\n                        int ori_idx = i * channels * imageHeight * imageWidth + h * imageWidth * channels + w * channels + j;\n                        normRealImage[index] = (static_cast<float>(pNormImage[ori_idx]) - 127.5) * 0.0078125;\n                    }\n                    \n                }\n            }\n        }\n\n        std::vector<caffe::Blob<float>*> bottom_vec;\n        bottom_vec.push_back(new caffe::Blob<float>);\n        bottom_vec[0]->Reshape(batchSize, channels, imageHeight, imageWidth);\n        bottom_vec[0]->set_cpu_data(normRealImage);\n\n        float iter_loss;\n        const vector<Blob<float>*>& result = pCaffeNet->Forward(bottom_vec, &iter_loss);\n\n        for (int i = 0; i < result[0]->count(); ++i)\n        {\n            pFeatures[i] = result[0]->cpu_data()[i];\n        }\n\n        delete bottom_vec[0];\n    }\n    catch (const std::bad_alloc &)\n    {\n        nRet = -2;\n    }\n    catch (const int &errCode)\n    {\n        nRet = errCode;\n    }\n    catch (...)\n    {\n        nRet = -3;\n    }\n\n    return nRet;\n}\n\n\nint __stdcall SetFaceRecognitionLibPath(const char *szLibPath)\n{\n\tif (szLibPath == NULL)\n\t\treturn -1;\n\n#ifdef _WIN32\n\tstrcpy_s(g_szFaceRecognitionSDKPath, _MAX_PATH, szLibPath);\n#else\n    strncpy(g_szFaceRecognitionSDKPath, szLibPath, _MAX_PATH);\n#endif\n\t\n\tsize_t len = strlen(g_szFaceRecognitionSDKPath);\n\tif (len != 0)\n\t{\n\t#ifdef _WIN32\n\t\tif (g_szFaceRecognitionSDKPath[len - 1] != '\\\\')\n\t\t\tstrcat_s(g_szFaceRecognitionSDKPath, \"\\\\\");\n\t#else\n\t    if (g_szFaceRecognitionSDKPath[len - 1] != '/')\n\t        strncat(g_szFaceRecognitionSDKPath, \"/\", _MAX_PATH);\n\t#endif\n\t}\n\n\treturn 0;\n}\n\nint __stdcall InitFaceRecognition(const char *szResName, int gpuID,\n    RecognitionHandle *pHandle)\n{\n\tif (pHandle == NULL)\n\t\treturn -1;\n\t\n\t// initialize deep face network\n\t*pHandle = NULL;\n\tstd::locale::global(std::locale(\"\"));\n\n\tint retValue = 0;\n\n#ifndef _WIN32\t\n\tif (strlen(g_szFaceRecognitionSDKPath) == 0)\n\t\tstrncpy(g_szFaceRecognitionSDKPath, \"./\", _MAX_PATH);\n#endif\n\n\ttry\n\t{\n\t\tstd::string strDllPath;\n\t\tstrDllPath = g_szFaceRecognitionSDKPath;\n        strDllPath += szResName;\n\n        std::fstream fileModel;\n        fileModel.open(strDllPath.c_str(), std::fstream::in | std::fstream::binary);\n        if (false == fileModel.is_open())\n          return 1;\n          \n        fileModel.seekg(0, std::fstream::end);\n        int dataSize = int(fileModel.tellg());\n        fileModel.seekg(0, std::fstream::beg);\n       \n\t\t//CMyFile fileModel(strDllPath.c_str(), CMyFile::modeRead);\n\t\t//int dataSize = static_cast<int>(fileModel.GetLength());\n\t\tAutoArray<char> encryptedData(dataSize);\n\t\t//fileModel.Read(encryptedData, dataSize);\n\t\tfileModel.read(encryptedData, dataSize);\n\t\t//fileModel.Close();\n\t\tfileModel.close();\n\n\t\tint *pBuffer = reinterpret_cast<int *>(encryptedData.begin());\n\t\t// encrypt data by shift left\t\t\n\t\tint numOfData = dataSize / sizeof(pBuffer[0]);\n\t\tfor (int i = 0; i < numOfData; ++i)\n\t\t{\n\t\t\tint tempData = pBuffer[i];\n\t\t\tpBuffer[i] = hzx::ror(static_cast<unsigned int>(tempData), \n                hzx::g_shiftBits);\n\t\t}\n\n        const int modelnumber = pBuffer[0];\n        std::vector<int> protoTxtLen, modelSize;\n        for (int i = 0; i < modelnumber; ++i)\n        {\n            protoTxtLen.push_back(pBuffer[2 * i + 1]);\n            modelSize.push_back(pBuffer[2 * i + 2]);\n        }\n        unsigned char *pDataBuf = reinterpret_cast<unsigned char *>(encryptedData.begin()) + sizeof(int) * (2 * modelnumber + 1);\n\n\t\tFLAGS_minloglevel = 2;\t// INFO(=0)<WARNING(=1)<ERROR(=2)<FATAL(=3)\n\n\t\t// initialize network structure\n#ifdef CPU_ONLY\n        Caffe::set_mode(Caffe::CPU);\n#else\n        if (gpuID < 0)\n            Caffe::set_mode(Caffe::CPU);\n        else {\n            Caffe::set_mode(Caffe::GPU);\n            Caffe::SetDevice(gpuID);\n        }\n#endif\n\t\tcaffe::NetParameter net_param;\n        caffe::NetParameter weight_param;\n\n\t\tretValue = caffe::ReatNetParamsFromBuffer(\n            pDataBuf, protoTxtLen[0], &net_param);\n        CHECK_EQ(retValue, 0) << \"Read net structure from buffer error, code: \" << retValue;\n        CHECK(caffe::UpgradeNetAsNeeded(\"<memory>\", &net_param));\n        retValue = caffe::ReatNetParamsFromBuffer(\n            pDataBuf + protoTxtLen[0], modelSize[0], &weight_param);\n        CHECK_EQ(retValue, 0) << \"Read net structure from buffer error, code: \" << retValue;\n        CHECK(caffe::UpgradeNetAsNeeded(\"<memory>\", &weight_param));\n\n        net_param.mutable_state()->set_phase(caffe::TEST);\n\t\tNet<float> *pCaffeNet = new Net<float>(net_param);\n\n\t\t// initialize network parameters\t\t\n\t\tpCaffeNet->CopyTrainedLayersFrom(weight_param);\n\t\t*pHandle = reinterpret_cast<RecognitionHandle>(pCaffeNet);\n\t}\n\tcatch (const std::bad_alloc &)\n\t{\n\t\tretValue = -2;\n\t}\n\tcatch (const int &errCode)\n\t{\n\t\tretValue = errCode;\n\t}\n\tcatch (...)\n\t{\n\t\tretValue = -3;\n\t}\n\n\treturn retValue;\n}\n\nint __stdcall UninitFaceRecognition(RecognitionHandle handle)\n{\n\tNet<float> *pCaffeNet = reinterpret_cast<Net<float> *>(handle);\n\tdelete pCaffeNet;\n\n\treturn 0;\n}\n\nint __stdcall GetFaceRecognitionSize(RecognitionHandle handle)\n{\n\tNet<float> *pCaffeNet = reinterpret_cast<Net<float> *>(handle);\n\tconst vector<Blob<float>*>& result = pCaffeNet->output_blobs();\n\tint len = result[0]->count() * sizeof(float);\n\treturn len;\n}\n", "meta": {"hexsha": "81e0e5f435a810ce89297defd2e81b43673209d1", "size": 6841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/face_recognition/face_recognition.cpp", "max_stars_repo_name": "soccergame/caffe-windows", "max_stars_repo_head_hexsha": "6119495e8f174077fd6485c4d44ba63d7575f8c5", "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/face_recognition/face_recognition.cpp", "max_issues_repo_name": "soccergame/caffe-windows", "max_issues_repo_head_hexsha": "6119495e8f174077fd6485c4d44ba63d7575f8c5", "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/face_recognition/face_recognition.cpp", "max_forks_repo_name": "soccergame/caffe-windows", "max_forks_repo_head_hexsha": "6119495e8f174077fd6485c4d44ba63d7575f8c5", "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.9224489796, "max_line_length": 129, "alphanum_fraction": 0.6313404473, "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.17866816436732086}}
{"text": "//\n// Created by fjh on 17-11-3. Copyright (c) 2017 ThinkForce, Inc. All Rights Reserved\n//\n\n#include \"layer/DetectionOutput_layer.h\"\n#include <boost/shared_ptr.hpp>\nnamespace mdl{\n    DetectionOutput_layer::DetectionOutput_layer(const Json& config):Layer(config){\n        auto &param=config[\"param\"];\n        num_classes_ = param[\"num_classes\"].number_value();\n        share_location_ = true;\n        num_loc_classes_ = share_location_ ? 1 : num_classes_;\n        background_label_id_ = param[\"background_label_id\"].int_value();\n        code_type_ = CodeType::PriorBoxParameter_CodeType_CENTER_SIZE;\n        variance_encoded_in_target_ =\n                param[\"variance_encoded_in_target\"].bool_value();\n        keep_top_k_ = param[\"keep_top_k\"].int_value();\n        confidence_threshold_ = param[\"confidence_threshold\"].is_null() ?\n                                -FLT_MAX:param[\"confidence_threshold\"].number_value() ;\n        // Parameters used in nms.\n        nms_threshold_ = 0.45;//param[\"nms_threshold\"].number_value();\n        CHECK_GE(nms_threshold_, 0.) << \"nms_threshold must be non negative.\";\n        eta_ = 1.0;\n        //CHECK_GT(eta_, 0.);\n        //CHECK_LE(eta_, 1.);\n        top_k_ = -1;\n        if (!param[\"top_k\"].is_null()) {\n            top_k_ = 400;//param[\"top_k\"].number_value();\n        }\n        top_k_ = 400;\n       \n    }\n    template <typename T>\n    bool SortScorePairDescend(const std::pair<float, T>& pair1,\n                              const std::pair<float, T>& pair2) {\n        return pair1.first > pair2.first;\n    }\n\n// Explicit initialization.\n    template bool SortScorePairDescend(const std::pair<float, int>& pair1,\n                                       const std::pair<float, int>& pair2);\n    template bool SortScorePairDescend(const std::pair<float, std::pair<int, int> >& pair1,\n                                       const std::pair<float, std::pair<int, int> >& pair2);\n    DetectionOutput_layer::~DetectionOutput_layer() {}\n    void DetectionOutput_layer::forward(int numthread) {\n        const Mtype* loc_data = _input[0]->get_data();\n        const Mtype* conf_data = _input[1]->get_data();\n        const Mtype* prior_data = _input[2]->get_data();\n        const int num = _output[0]->dimension(0);\n        num_priors_ = (_input[2]->dimension(2)) / 4;\n        // Retrieve all location predictions.\n        vector<LabelBBox> all_loc_preds;\n        GetLocPredictions(loc_data, num, num_priors_, num_loc_classes_,\n                          share_location_, &all_loc_preds);\n\n        // Retrieve all confidences.\n        std::vector<std::map<int, vector<float> > > all_conf_scores;\n        GetConfidenceScores(conf_data, num, num_priors_, num_classes_,\n                            &all_conf_scores);\n\n        // Retrieve all prior bboxes. It is same within a batch since we assume all\n        // images in a batch are of same dimension.\n        vector<NormalizedBBox> prior_bboxes;\n        vector<vector<float> > prior_variances;\n        GetPriorBBoxes(prior_data, num_priors_, &prior_bboxes, &prior_variances);\n\n        // Decode all loc predictions to bboxes.\n        vector<LabelBBox> all_decode_bboxes;\n        const bool clip_bbox = false;\n        DecodeBBoxesAll(all_loc_preds, prior_bboxes, prior_variances, num,\n                        share_location_, num_loc_classes_, background_label_id_,\n                        code_type_, variance_encoded_in_target_, clip_bbox,\n                        &all_decode_bboxes);\n\n        int num_kept = 0;\n        vector<map<int, vector<int> > > all_indices;\n        for (int i = 0; i < num; ++i) {\n            const LabelBBox& decode_bboxes = all_decode_bboxes[i];\n            const map<int, vector<float> >& conf_scores = all_conf_scores[i];\n            map<int, vector<int> > indices;\n            int num_det = 0;\n            for (int c = 0; c < num_classes_; ++c) {\n                if (c == background_label_id_) {\n                    // Ignore background class.\n                    continue;\n                }\n                if (conf_scores.find(c) == conf_scores.end()) {\n                    // Something bad happened if there are no predictions for current label.\n                    LOG(FATAL) << \"Could not find confidence predictions for label \" << c;\n                }\n                const vector<float>& scores = conf_scores.find(c)->second;\n                int label = share_location_ ? -1 : c;\n                if (decode_bboxes.find(label) == decode_bboxes.end()) {\n                    // Something bad happened if there are no predictions for current label.\n                    LOG(FATAL) << \"Could not find location predictions for label \" << label;\n                    continue;\n                }\n                const vector<NormalizedBBox>& bboxes = decode_bboxes.find(label)->second;\n                ApplyNMSFast(bboxes, scores, confidence_threshold_, nms_threshold_, eta_,\n                             top_k_, &(indices[c]));\n                num_det += indices[c].size();\n            }\n            if (keep_top_k_ > -1 && num_det > keep_top_k_) {\n                std::vector<std::pair<float, std::pair<int, int> > > score_index_pairs;\n                for (map<int, vector<int> >::iterator it = indices.begin();\n                     it != indices.end(); ++it) {\n                    int label = it->first;\n                    const vector<int>& label_indices = it->second;\n                    if (conf_scores.find(label) == conf_scores.end()) {\n                        // Something bad happened for current label.\n                        LOG(FATAL) << \"Could not find location predictions for \" << label;\n                        continue;\n                    }\n                    const vector<float>& scores = conf_scores.find(label)->second;\n                    for (int j = 0; j < label_indices.size(); ++j) {\n                        int idx = label_indices[j];\n                        CHECK_LT(idx, scores.size());\n                        score_index_pairs.push_back(std::make_pair(\n                                scores[idx], std::make_pair(label, idx)));\n                    }\n                }\n                // Keep top k results per image.\n                std::sort(score_index_pairs.begin(), score_index_pairs.end(),\n                          SortScorePairDescend<std::pair<int, int> >);\n                score_index_pairs.resize(keep_top_k_);\n                // Store the new indices.\n                map<int, vector<int> > new_indices;\n                for (int j = 0; j < score_index_pairs.size(); ++j) {\n                    int label = score_index_pairs[j].second.first;\n                    int idx = score_index_pairs[j].second.second;\n                    new_indices[label].push_back(idx);\n                }\n                all_indices.push_back(new_indices);\n                num_kept += keep_top_k_;\n            } else {\n                all_indices.push_back(indices);\n                num_kept += num_det;\n            }\n        }\n\n        vector<int> top_shape(2, 1);\n        top_shape.push_back(num_kept);\n        top_shape.push_back(7);\n        Mtype* top_data;\n        if (num_kept == 0) {\n            LOG(INFO) << \"Couldn't find any detections\";\n            top_shape[2] = num;\n            _output[0]->resize(top_shape);\n            top_data = _output[0]->get_data();\n            for(int i=0;i<_output[0]->count(0);i++){\n                top_data[i]=-1;\n            }\n            // Generate fake results per image.\n            for (int i = 0; i < num; ++i) {\n                top_data[0] = i;\n                top_data += 7;\n            }\n        } else {\n            _output[0]->resize(top_shape);\n            top_data = _output[0]->get_data();\n        }\n\n        int count = 0;\n        for (int i = 0; i < num; ++i) {\n            const map<int, vector<float> >& conf_scores = all_conf_scores[i];\n            const LabelBBox& decode_bboxes = all_decode_bboxes[i];\n            for (map<int, vector<int> >::iterator it = all_indices[i].begin();\n                 it != all_indices[i].end(); ++it) {\n                int label = it->first;\n                if (conf_scores.find(label) == conf_scores.end()) {\n                    // Something bad happened if there are no predictions for current label.\n                    LOG(FATAL) << \"Could not find confidence predictions for \" << label;\n                    continue;\n                }\n                const vector<float>& scores = conf_scores.find(label)->second;\n                int loc_label = share_location_ ? -1 : label;\n                if (decode_bboxes.find(loc_label) == decode_bboxes.end()) {\n                    // Something bad happened if there are no predictions for current label.\n                    LOG(FATAL) << \"Could not find location predictions for \" << loc_label;\n                    continue;\n                }\n                const vector<NormalizedBBox>& bboxes =\n                        decode_bboxes.find(loc_label)->second;\n                vector<int>& indices = it->second;\n                for (int j = 0; j < indices.size(); ++j) {\n                    int idx = indices[j];\n                    top_data[count * 7] = i;\n                    top_data[count * 7 + 1] = label;\n                    top_data[count * 7 + 2] = scores[idx];\n                    const NormalizedBBox& bbox = bboxes[idx];\n                    top_data[count * 7 + 3] = bbox.xmin();\n                    top_data[count * 7 + 4] = bbox.ymin();\n                    top_data[count * 7 + 5] = bbox.xmax();\n                    top_data[count * 7 + 6] = bbox.ymax();\n\n                    ++count;\n                }\n            }\n\n        }\n\n    }\n}", "meta": {"hexsha": "7c49692074127f87c2ec3b65be9e9a2014fd89de", "size": 9621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layer/DetectionOutput_layer.cpp", "max_stars_repo_name": "superFJH/robbin_site", "max_stars_repo_head_hexsha": "c72ff2615cdbdb39fd2c7a8a34d8a93004ea97a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-09T20:53:07.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-09T20:53:07.000Z", "max_issues_repo_path": "src/layer/DetectionOutput_layer.cpp", "max_issues_repo_name": "superFJH/robbin_site", "max_issues_repo_head_hexsha": "c72ff2615cdbdb39fd2c7a8a34d8a93004ea97a6", "max_issues_repo_licenses": ["MIT"], "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/layer/DetectionOutput_layer.cpp", "max_forks_repo_name": "superFJH/robbin_site", "max_forks_repo_head_hexsha": "c72ff2615cdbdb39fd2c7a8a34d8a93004ea97a6", "max_forks_repo_licenses": ["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.39408867, "max_line_length": 92, "alphanum_fraction": 0.5274919447, "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.17866815776182707}}
{"text": "#pragma once\n#include \"field.hpp\"\n#include <boost/hana/tuple.hpp>\n\nnamespace reg\n{\n    template<std::uint8_t count, std::uint8_t stride> struct RepMask {};\n    template<std::uint8_t count, std::uint8_t stride> struct RepLocation {};\n\n    template<class _Location, class _Mask, class _RWPolicy, class _RepeatMask, class _RepeatLocation, class ValueType> \n    struct MultiField;\n\n    template<class T, class _Owner, class TOffset, TOffset baseOffset,\n        T maskShift, std::uint8_t maskSize, class _RWPolicy,\n        std::uint8_t maskCount, std::uint8_t maskStride,\n        std::uint8_t locationCount, std::uint8_t locationStride, class ValueType>\n    struct MultiField<\n        FieldLocation<T, _Owner, FieldOffset<TOffset, baseOffset>>, \n        BitMask<T, maskShift, maskSize>, \n        _RWPolicy, \n        RepMask<maskCount, maskStride>, \n        RepLocation<locationCount, locationStride>,\n        ValueType>\n    {\n        constexpr MultiField() = default;\n\n        template<class U, U indx>\n        constexpr auto operator[](hana::integral_constant<U, indx>) const \n        {\n            static_assert(indx < (maskCount*locationCount), \"Bit mask index out of range\");\n\n            constexpr auto offset = integral_c<TOffset, baseOffset> + integral_c<TOffset, (indx / maskCount)> * integral_c<TOffset, locationStride>;\n            constexpr auto mask = integral_c<T, maskShift> + integral_c<T, (indx % maskCount)> * integral_c<T, maskStride>;\n\n            using Loc = FieldLocation<T, _Owner, FieldOffset<TOffset, hana::value(offset)>>;\n            using Mask = BitMask<T, hana::value(mask), maskSize>;\n\n            return Field<Loc, Mask, _RWPolicy, ValueType>{};\n        }\n    };\n\n    template<class _Location, class _Mask, class _RepMask, class _RepLoc, class Type = typename _Location::Value>\n    using RWMultiField = MultiField<_Location, _Mask, detail::RWPolicy, _RepMask, _RepLoc, Type>;\n\n    template<class _Location, class _Mask, class _RepMask, class _RepLoc, class Type = typename _Location::Value>\n    using ROMultiField = MultiField<_Location, _Mask, detail::ROPolicy, _RepMask, _RepLoc, Type>;\n\n    template<class _Location, class _Mask, class _RepMask, class _RepLoc, class Type = typename _Location::Value>\n    using WOMultiField = MultiField<_Location, _Mask, detail::WOPolicy, _RepMask, _RepLoc, Type>;   \n}", "meta": {"hexsha": "f4dfa215a28a7334571023cc1f41c5b5dacd76a8", "size": 2331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/reg/multi_field.hpp", "max_stars_repo_name": "niclasberg/asfw", "max_stars_repo_head_hexsha": "f836de1c0d6350541e3253863dedab6a3eb81df7", "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": "lib/include/reg/multi_field.hpp", "max_issues_repo_name": "niclasberg/asfw", "max_issues_repo_head_hexsha": "f836de1c0d6350541e3253863dedab6a3eb81df7", "max_issues_repo_licenses": ["MIT"], "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/include/reg/multi_field.hpp", "max_forks_repo_name": "niclasberg/asfw", "max_forks_repo_head_hexsha": "f836de1c0d6350541e3253863dedab6a3eb81df7", "max_forks_repo_licenses": ["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.62, "max_line_length": 148, "alphanum_fraction": 0.6932646933, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.17852640603698272}}
{"text": "/****\n   Copyright 2005-2007, Moshe Looks\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 \"enf.h\"\n#include <boost/iterator/transform_iterator.hpp>\n\nnamespace rewrite {\n  namespace enf {\n    using namespace std;\n    using namespace boost;\n    using namespace id;\n\n    bool consistent(const Set& s) {\n      Set::const_iterator pos=find_if(s.begin(),s.end(),\n\t\t\t\t      bind(greater<Constraint>(),_1,0));\n      return has_empty_intersection\n\t(make_transform_iterator(Set::reverse_iterator(pos),\n\t\t\t\t negate<Constraint>()),\n\t make_transform_iterator(s.rend(),negate<Constraint>()),pos,s.end());\n    }\n\n    bool reduce_to_elegance::and_cut(sib_it child) {\n      bool adopted=false;\n      for (sib_it gchild=child.begin();gchild!=child.end();)\n\tif (gchild.number_of_children()==1 && guard_set(*gchild).empty()) {\n\t  _tr.erase(_tr.flatten(gchild.begin()));\n\t  if (!adopted) //is child adopting a terminal 1-constrant AND, x?\n\t    for (sib_it x=gchild.begin();x!=gchild.end();++x)\n\t      if (x.begin()==x.end() && guard_set(*x).size()==1) {\n\t\tadopted=true;\n\t\tbreak;\n\t      }\n\t  gchild=_tr.erase(_tr.flatten(gchild));\n\t} else {\n\t  ++gchild;\n\t}\n      return adopted;\n    }\n    void reduce_to_elegance::or_cut(sib_it current) {\n      for (sib_it child=current.begin();child!=current.end();)\n\tif (child.number_of_children()==1) {\n\t  union2(guard_set(*current),guard_set(*child.begin()));\n\t  _tr.erase(_tr.flatten(child.begin()));\n\t  child=_tr.erase(_tr.flatten(child));\n\t} else {\n\t  ++child;\n\t}\n    }\n\n    Result reduce_to_elegance::reduce(pre_it current,\n\t\t\t\t      const Set& dominant,const Set& command) {\n      if (is_and(*current)) {\n\tdifference2(guard_set(*current),dominant);\n\n\tset_difference\n\t  (guard_set(*current),\n\t   make_transform_iterator(command.rbegin(),negate<Constraint>()),\n\t   make_transform_iterator(command.rend(),negate<Constraint>()));\n\t\n\tif (current.begin()==current.end() && guard_set(*current).empty())\n\t  return Disconnect; //0subsume\n\t\n\tif (!has_empty_intersection(guard_set(*current).begin(),\n\t\t\t\t    guard_set(*current).end(),\n\t\t\t\t    command.begin(),command.end()))\n\t  return Delete;     //1subsume\n\t\n\tSet prev_guard_set;\n\tdo {\n\t  prev_guard_set=guard_set(*current);\n\n\t  Set handle_set;\n\t  set_union(dominant.begin(),dominant.end(),\n\t\t    guard_set(*current).begin(),guard_set(*current).end(),\n\t\t    inserter(handle_set,handle_set.begin()));\n\t  \n\t  if (!consistent(handle_set))\n\t    return Delete;\n\n\t  for (sib_it child=current.begin();child!=current.end();) {\n\t    switch(reduce(child,handle_set,command)) {\n\t    case Delete:\n\t      return Delete; //since current is in all selections with child\n\t    case Disconnect:\n\t      child=_tr.erase(child);\n\t      break;\n\t    case Keep:\n\t      assert(child.begin()!=child.end()); //not sure if this is ok..\n\t      //make result_set the union of child's children's guard sets\n\t      Set result_set(guard_set(*child.begin()));\n\t      for_each\n\t\t(++child.begin(),child.end(),\n\t\t bind(intersection2<Set>,ref(result_set),bind(guard_set,_1)));\n\t      if (!result_set.empty()) {\n\t\tunion2(guard_set(*current),result_set);\n\t\tfor_each\n\t\t  (child.begin(),child.end(),\n\t\t   bind(difference2<Set>,bind(guard_set,_1),result_set));\n\t\t//try to apply and-cut to child's children\n\t\tand_cut(child.begin());\n\t\t//guard_set has been enlarged, so we need to reprocess all kids\n\t\tchild=current.begin();\n\t      } else {\n\t\tif (!and_cut(child)) //if child is adopting a terminal \n\t\t  ++child;           //1-constrant AND, need to reprocess it\n\t      }\n\t    }\n\t  }\n\t  //try to apply or-cut to current's children\n\t  or_cut(current);\n\t} while (prev_guard_set!=guard_set(*current));\n\tif (current.begin()==current.end() && guard_set(*current).empty())\n\t  return Disconnect; //0-subsumption\n      } else {\n\tassert(is_or(*current));\n\t\n\tfor (sib_it child=current.begin();child!=current.end();) {\n\t  Set child_command(command);\n\t  for (sib_it sib=current.begin();sib!=current.end();++sib)\n\t    if (sib!=child && sib.begin()==sib.end() && \n\t\tguard_set(*sib).size()==1)\n\t      child_command.insert(*guard_set(*sib).begin());\n\t  switch(reduce(child,dominant,child_command)) {\n\t  case Delete:\n\t    if (current.number_of_children()>1)\n\t      child=_tr.erase(child);\n\t    else\n\t      return Delete;\n\t    break;\n\t  case Disconnect:\n\t    return Disconnect;\n\t  case Keep:\n\t    ++child;\n\t  }\n\t}\n      }\n      return Keep;\n    }\n  } //~namespace enf\n} //~namespace rewrite\n\nstd::ostream& operator<<(std::ostream& out,const rewrite::enf::Node& x) {\n  if (x.first) {\n    out << \"[ \";\n    for (rewrite::enf::Set::const_iterator it=x.second.begin();\n\t it!=x.second.end();++it)\n      out << *it << \" \";\n    out << \"]\";\n  } else {\n    out << \"o\";\n  }\n  return out;\n}\n\n", "meta": {"hexsha": "de659e7d534577df6defeaf639317fcc49e0e7c0", "size": 5196, "ext": "cc", "lang": "C++", "max_stars_repo_path": "moses/rewrite/enf.cc", "max_stars_repo_name": "moshelooks/moses", "max_stars_repo_head_hexsha": "81568276877f24c2cb1ca5649d44e22fba6f44b2", "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": "moses/rewrite/enf.cc", "max_issues_repo_name": "moshelooks/moses", "max_issues_repo_head_hexsha": "81568276877f24c2cb1ca5649d44e22fba6f44b2", "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": "moses/rewrite/enf.cc", "max_forks_repo_name": "moshelooks/moses", "max_forks_repo_head_hexsha": "81568276877f24c2cb1ca5649d44e22fba6f44b2", "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.9285714286, "max_line_length": 75, "alphanum_fraction": 0.6501154734, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.17852640244157625}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2019 Aleksey Moskvin <zerg1996@yandex.ru>\n// Copyright (c) 2020 Nikita Kaskov <nbering@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_ACCUMULATORS_HASH_HPP\n#define CRYPTO3_ACCUMULATORS_HASH_HPP\n\n#include <boost/parameter/value_type.hpp>\n\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n\n#include <boost/container/static_vector.hpp>\n\n#include <boost/crypto3/detail/make_array.hpp>\n#include <boost/crypto3/detail/static_digest.hpp>\n#include <boost/crypto3/detail/endian_shift.hpp>\n#include <boost/crypto3/detail/inject.hpp>\n\n#include <boost/crypto3/hash/accumulators/bits_count.hpp>\n\n#include <boost/crypto3/hash/accumulators/parameters/bits.hpp>\n\n#include <boost/accumulators/statistics/count.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace accumulators {\n            namespace impl {\n                template<typename Hash>\n                struct hash_impl : boost::accumulators::accumulator_base {\n                protected:\n                    typedef Hash hash_type;\n                    typedef typename hash_type::construction::type construction_type;\n                    typedef typename hash_type::construction::params_type params_type;\n\n                    typedef typename params_type::digest_endian endian_type;\n\n                    constexpr static const std::size_t word_bits = construction_type::word_bits;\n                    typedef typename construction_type::word_type word_type;\n\n                    constexpr static const std::size_t block_bits = construction_type::block_bits;\n                    constexpr static const std::size_t block_words = construction_type::block_words;\n                    typedef typename construction_type::block_type block_type;\n\n                    constexpr static const std::size_t length_bits = params_type::length_bits;\n                    // FIXME: do something more intelligent than capping at 64\n                    constexpr static const std::size_t length_type_bits =\n                        length_bits < word_bits ? word_bits : length_bits > 64 ? 64 : length_bits;\n                    typedef typename boost::uint_t<length_type_bits>::least length_type;\n                    constexpr static const std::size_t length_words = length_bits / word_bits;\n                    BOOST_STATIC_ASSERT(!length_bits || length_bits % word_bits == 0);\n\n                    typedef ::boost::crypto3::detail::injector<endian_type, word_bits, block_words, block_bits>\n                        injector_type;\n\n                public:\n                    typedef typename hash_type::digest_type result_type;\n\n                    // The constructor takes an argument pack.\n                    hash_impl(boost::accumulators::dont_care) : filled(false), total_seen(0) {\n                    }\n\n                    template<typename ArgumentPack>\n                    inline void operator()(const ArgumentPack &args) {\n                        resolve_type(args[boost::accumulators::sample],\n                                     args[::boost::crypto3::accumulators::bits | std::size_t()]);\n                    }\n\n                    inline result_type result(boost::accumulators::dont_care) const {\n                        construction_type res = construction;\n                        return res.digest(cache, total_seen);\n                    }\n\n                protected:\n                    inline void resolve_type(const block_type &value, std::size_t bits) {\n                        // total_seen += bits == 0 ? block_bits : bits;\n                        process(value, bits == 0 ? block_bits : bits);\n                    }\n\n                    inline void resolve_type(const word_type &value, std::size_t bits) {\n                        // total_seen += bits == 0 ? word_bits : bits;\n                        process(value, bits == 0 ? word_bits : bits);\n                    }\n\n                    inline void process(const block_type &value, std::size_t value_seen) {\n                        using namespace ::boost::crypto3::detail;\n\n                        if (filled) {\n                            construction.process_block(cache, total_seen);\n                            filled = false;\n                        }\n\n                        std::size_t cached_bits = total_seen % block_bits;\n\n                        if (cached_bits != 0) {\n                            // If there are already any bits in the cache\n\n                            std::size_t needed_to_fill_bits = block_bits - cached_bits;\n                            std::size_t new_bits_to_append =\n                                (needed_to_fill_bits > value_seen) ? value_seen : needed_to_fill_bits;\n\n                            injector_type::inject(value, new_bits_to_append, cache, cached_bits);\n                            total_seen += new_bits_to_append;\n\n                            if (cached_bits == block_bits) {\n                                // If there are enough bits in the incoming value to fill the block\n                                filled = true;\n\n                                if (value_seen > new_bits_to_append) {\n\n                                    construction.process_block(cache, total_seen);\n                                    filled = false;\n\n                                    // If there are some remaining bits in the incoming value - put them into the cache,\n                                    // which is now empty\n\n                                    cached_bits = 0;\n\n                                    injector_type::inject(\n                                        value, value_seen - new_bits_to_append, cache, cached_bits, new_bits_to_append);\n\n                                    total_seen += value_seen - new_bits_to_append;\n                                }\n                            }\n\n                        } else {\n\n                            total_seen += value_seen;\n\n                            // If there are no bits in the cache\n                            if (value_seen == block_bits) {\n                                // The incoming value is a full block\n                                filled = true;\n\n                                std::move(value.begin(), value.end(), cache.begin());\n\n                            } else {\n                                // The incoming value is not a full block\n                                std::move(value.begin(),\n                                          value.begin() + value_seen / word_bits + (value_seen % word_bits ? 1 : 0),\n                                          cache.begin());\n                            }\n                        }\n                    }\n\n                    inline void process(const word_type &value, std::size_t value_seen) {\n                        using namespace ::boost::crypto3::detail;\n\n                        if (filled) {\n                            construction.process_block(cache, total_seen);\n                            filled = false;\n                        }\n\n                        std::size_t cached_bits = total_seen % block_bits;\n\n                        if (cached_bits % word_bits != 0) {\n                            std::size_t needed_to_fill_bits = block_bits - cached_bits;\n                            std::size_t new_bits_to_append =\n                                (needed_to_fill_bits > value_seen) ? value_seen : needed_to_fill_bits;\n\n                            injector_type::inject(value, new_bits_to_append, cache, cached_bits);\n                            total_seen += new_bits_to_append;\n\n                            if (cached_bits == block_bits) {\n                                // If there are enough bits in the incoming value to fill the block\n\n                                filled = true;\n\n                                if (value_seen > new_bits_to_append) {\n\n                                    construction.process_block(cache, total_seen);\n                                    filled = false;\n\n                                    // If there are some remaining bits in the incoming value - put them into the cache,\n                                    // which is now empty\n                                    cached_bits = 0;\n\n                                    injector_type::inject(\n                                        value, value_seen - new_bits_to_append, cache, cached_bits, new_bits_to_append);\n\n                                    total_seen += value_seen - new_bits_to_append;\n                                }\n                            }\n\n                        } else {\n                            cache[cached_bits / word_bits] = value;\n\n                            total_seen += value_seen;\n                        }\n                    }\n\n                    bool filled;\n                    std::size_t total_seen;\n                    block_type cache;\n                    construction_type construction;\n                };\n            }    // namespace impl\n\n            namespace tag {\n                template<typename Hash>\n                struct hash : boost::accumulators::depends_on<bits_count> {\n                    typedef Hash hash_type;\n\n                    /// INTERNAL ONLY\n                    ///\n\n                    typedef boost::mpl::always<accumulators::impl::hash_impl<Hash>> impl;\n                };\n            }    // namespace tag\n\n            namespace extract {\n                template<typename Hash, typename AccumulatorSet>\n                typename boost::mpl::apply<AccumulatorSet, tag::hash<Hash>>::type::result_type\n                    hash(const AccumulatorSet &acc) {\n                    return boost::accumulators::extract_result<tag::hash<Hash>>(acc);\n                }\n            }    // namespace extract\n        }        // namespace accumulators\n    }            // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_ACCUMULATORS_HASH_HPP\n", "meta": {"hexsha": "d26f7744eea305daf4da7477ea345b2b4a01de4f", "size": 10405, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/accumulators/hash.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/accumulators/hash.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/accumulators/hash.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": 44.849137931, "max_line_length": 120, "alphanum_fraction": 0.4937049495, "num_tokens": 1738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17846799216019069}}
{"text": "/**\n * Copyright (c) 2017 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#ifndef vtslibs_vts_geomextents_hpp\n#define vtslibs_vts_geomextents_hpp\n\n#include <limits>\n\n#include <boost/variant.hpp>\n\n#include \"math/geometry_core.hpp\"\n#include \"math/transform.hpp\"\n\n#include \"half/half.hpp\"\n\n#include \"../storage/range.hpp\"\n\ntypedef half_float::half hfloat;\n\nnamespace vtslibs { namespace vts {\n\nstruct GeomExtents {\n    using ZRange = storage::Range<float>;\n    using Extents = math::Extents2_<float>;\n\n    /** (SDS) height range.\n     */\n    ZRange z;\n\n    /** (SDS) surrogate value (i.e. representative height of tile)\n     */\n    float surrogate;\n\n    /** Horizontal extents. Might be invalid if dealing with older datasets.\n     */\n    Extents extents;\n\n    GeomExtents()\n        : z(ZRange::emptyRange()), surrogate(invalidSurrogate)\n        , extents(math::InvalidExtents{})\n    {}\n\n    GeomExtents(float min, float max, float surrogate)\n        : z(min, max), surrogate(surrogate)\n        , extents(math::InvalidExtents{})\n    {}\n\n    /** Compute surrogate as average from height range.\n     */\n    void makeAverageSurrogate() {\n        surrogate = (z.min + z.max) / 2.f;\n    }\n\n    static constexpr float invalidSurrogate\n        = -std::numeric_limits<float>::infinity();\n\n    static bool validSurrogate(float surrogate) {\n        return surrogate != invalidSurrogate;\n    }\n\n    bool validSurrogate() const { return validSurrogate(surrogate); }\n};\n\n/** Invalid vertical extent.\n */\ninline bool empty(const GeomExtents &ge) { return ge.z.empty(); }\n\n/** Extents are incomplete (either invalid vertical extent\n *  or horizonal extents)\n */\ninline bool incomplete(const GeomExtents &ge) {\n    return ge.z.empty() || !math::valid(ge.extents);\n}\n\ninline bool complete(const GeomExtents &ge) {\n    return !incomplete(ge);\n}\n\ninline void update(GeomExtents &ge, float value) {\n    update(ge.z, value);\n}\n\ntemplate <typename T>\ninline void update(GeomExtents &ge, const math::Point3_<T> &p) {\n    update(ge.z, float(p(2)));\n    math::update(ge.extents, float(p(0)), float(p(1)));\n}\n\ninline void update(GeomExtents &ge, const GeomExtents &update) {\n    ge.z = unite(ge.z, update.z);\n    math::update(ge.extents, update.extents);\n}\n\ninline void update(GeomExtents &ge, const GeomExtents::Extents &update) {\n    math::update(ge.extents, update);\n}\n\ntemplate <typename T>\ninline GeomExtents geomExtents(const math::Matrix4 &trafo\n                               , const std::vector<math::Point3_<T>> &vs)\n{\n    GeomExtents ge;\n    for (const auto &v : vs) { update(ge, math::transform(trafo, v)); }\n    return ge;\n}\n\n} } // namespace vtslibs::vts\n\n#endif // vtslibs_vts_geomextents_hpp\n\n", "meta": {"hexsha": "37db73e60abbdbbacf17f1de6ab1d613cb42d70f", "size": 3968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vts-libs/vts/geomextents.hpp", "max_stars_repo_name": "melowntech/vts-libs", "max_stars_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-20T01:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T06:54:51.000Z", "max_issues_repo_path": "vts-libs/vts/geomextents.hpp", "max_issues_repo_name": "melowntech/vts-libs", "max_issues_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T15:21:29.000Z", "max_forks_repo_path": "vts-libs/vts/geomextents.hpp", "max_forks_repo_name": "melowntech/vts-libs", "max_forks_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:10:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:10:07.000Z", "avg_line_length": 29.8345864662, "max_line_length": 78, "alphanum_fraction": 0.6980846774, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.17846798369850123}}
{"text": "/*\n Copyright (C) 2020 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 <ored/model/inflation/infjybuilder.hpp>\n#include <ored/model/calibrationinstruments/cpicapfloor.hpp>\n#include <ored/model/calibrationinstruments/yoycapfloor.hpp>\n#include <ored/model/calibrationinstruments/yoyswap.hpp>\n#include <ored/model/utilities.hpp>\n#include <ored/utilities/dategrid.hpp>\n#include <ored/utilities/log.hpp>\n#include <qle/models/cpicapfloorhelper.hpp>\n#include <qle/models/fxbsconstantparametrization.hpp>\n#include <qle/models/fxbspiecewiseconstantparametrization.hpp>\n#include <qle/models/infjyparameterization.hpp>\n#include <qle/models/irlgm1fpiecewiseconstanthullwhiteadaptor.hpp>\n#include <qle/models/irlgm1fpiecewiseconstantparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiselinearparametrization.hpp>\n#include <qle/models/yoycapfloorhelper.hpp>\n#include <qle/models/yoyswaphelper.hpp>\n#include <qle/pricingengines/inflationcapfloorengines.hpp>\n#include <qle/pricingengines/cpiblackcapfloorengine.hpp>\n#include <qle/utilities/inflation.hpp>\n#include <ql/cashflows/yoyinflationcoupon.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <boost/range/join.hpp>\n\nusing QuantExt::CPIBlackCapFloorEngine;\nusing QuantExt::CpiCapFloorHelper;\nusing QuantExt::FxBsParametrization;\nusing QuantExt::inflationTime;\nusing QuantExt::Lgm1fParametrization;\nusing QuantExt::YoYCapFloorHelper;\nusing QuantExt::YoYInflationUnitDisplacedBlackCapFloorEngine;\nusing QuantExt::YoYInflationBachelierCapFloorEngine;\nusing QuantExt::YoYInflationBlackCapFloorEngine;\nusing QuantExt::YoYSwapHelper;\nusing QuantLib::DiscountingSwapEngine;\nusing QuantLib::Thirty360;\nusing QuantLib::YoYInflationCoupon;\nusing std::lower_bound;\nusing std::set;\nusing std::string;\n\nnamespace {\n\n// Used as comparator in various sets below.\nstruct CloseCmp {\n    bool operator() (QuantLib::Time s, QuantLib::Time t) const {\n        return s < t && !QuantLib::close(s, t);\n    }\n};\n\n}\n\nnamespace ore {\nnamespace data {\n\nusing Helpers = InfJyBuilder::Helpers;\n\nInfJyBuilder::InfJyBuilder(\n    const boost::shared_ptr<Market>& market,\n    const boost::shared_ptr<InfJyData>& data,\n    const string& configuration,\n    const string& referenceCalibrationGrid)\n    : market_(market),\n    configuration_(configuration),\n    data_(data),\n    referenceCalibrationGrid_(referenceCalibrationGrid),\n    marketObserver_(boost::make_shared<MarketObserver>()),\n    zeroInflationIndex_(*market_->zeroInflationIndex(data_->index(), configuration_)) {\n\n    LOG(\"InfJyBuilder: building model for inflation index \" << data_->index());\n\n    // Get rate curve\n    rateCurve_ = market_->discountCurve(zeroInflationIndex_->currency().code(), configuration_);\n\n    // Register with market observables except volatilities\n    marketObserver_->registerWith(zeroInflationIndex_);\n    marketObserver_->registerWith(rateCurve_);\n    initialiseMarket();\n\n    // Register the model builder with the market observer\n    registerWith(marketObserver_);\n\n    // Notify observers of all market data changes, not only when not calculated\n    alwaysForwardNotifications();\n\n    // Build the calibration instruments\n    buildCalibrationBaskets();\n\n    // Create the JY parameterisation.\n    parameterization_ = boost::make_shared<QuantExt::InfJyParameterization>(\n        createRealRateParam(), createIndexParam(), zeroInflationIndex_);\n}\n\nstring InfJyBuilder::inflationIndex() const {\n    return data_->index();\n}\n\nboost::shared_ptr<QuantExt::InfJyParameterization> InfJyBuilder::parameterization() const {\n    calculate();\n    return parameterization_;\n}\n\nHelpers InfJyBuilder::realRateBasket() const {\n    calculate();\n    return realRateBasket_;\n}\n\nHelpers InfJyBuilder::indexBasket() const {\n    calculate();\n    return indexBasket_;\n}\n\nbool InfJyBuilder::requiresRecalibration() const {\n    return (data_->realRateVolatility().calibrate() ||\n        data_->realRateReversion().calibrate() ||\n        data_->indexVolatility().calibrate()) &&\n        (marketObserver_->hasUpdated(false) ||\n            forceCalibration_ ||\n            pricesChanged(false));\n}\n\nvoid InfJyBuilder::performCalculations() const {\n    if (requiresRecalibration()) {\n        marketObserver_->hasUpdated(true);\n        buildCalibrationBaskets();\n        pricesChanged(true);\n    }\n}\n\nvoid InfJyBuilder::forceRecalculate() {\n    forceCalibration_ = true;\n    ModelBuilder::forceRecalculate();\n    forceCalibration_ = false;\n}\n\nvoid InfJyBuilder::buildCalibrationBaskets() const {\n\n    // If calibration type is None, don't build any baskets.\n    if (data_->calibrationType() == CalibrationType::None) {\n        DLOG(\"InfJyBuilder: calibration type is None so no calibration baskets built.\");\n        return;\n    }\n\n    const auto& cbs = data_->calibrationBaskets();\n\n    // If calibration type is BestFit, check that we have at least one calibration basket. Build up to a maximum of \n    // two calibration baskets. Log a warning if more than two are given. Arbitrarily assign the built baskets to \n    // the realRateBasket_ and indexBasket_ members. They will be combined again in any case for BestFit calibration.\n    if (data_->calibrationType() == CalibrationType::BestFit) {\n        QL_REQUIRE(cbs.size() > 0, \"InfJyBuilder: calibration type is BestFit but no calibration baskets provided.\");\n        rrInstActive_ = vector<bool>(cbs[0].instruments().size(), false);\n        realRateBasket_ = buildCalibrationBasket(cbs[0], rrInstActive_, rrInstExpiries_);\n        if (cbs.size() > 1) {\n            indexInstActive_ = vector<bool>(cbs[1].instruments().size(), false);\n            indexBasket_ = buildCalibrationBasket(cbs[1], indexInstActive_, indexInstExpiries_);\n        }\n        if (cbs.size() > 2)\n            WLOG(\"InfJyBuilder: only 2 calibration baskets can be processed but \" << cbs.size() <<\n                \" were supplied. The extra baskets are ignored.\");\n        return;\n    }\n\n    // Make sure that the calibration type is now Bootstrap.\n    QL_REQUIRE(data_->calibrationType() == CalibrationType::Bootstrap, \"InfJyBuilder: expected the calibration \" <<\n        \"type to be one of None, BestFit or Bootstrap.\");\n\n    const VolatilityParameter& idxVolatility = data_->indexVolatility();\n    const ReversionParameter& rrReversion = data_->realRateReversion();\n    const VolatilityParameter& rrVolatility = data_->realRateVolatility();\n\n    // Firstly, look at the inflation index portion i.e. are we calibrating it.\n    if (idxVolatility.calibrate()) {\n\n        DLOG(\"InfJyBuilder: building calibration basket for JY index bootstrap calibration.\");\n\n        // If we are not calibrating the real rate portion, then we expect exactly one calibration basket. Otherwise \n        // we need to find a basket with the 'Index' parameter.\n        if (!rrReversion.calibrate() && !rrVolatility.calibrate()) {\n            QL_REQUIRE(cbs.size() == 1, \"InfJyBuilder: calibrating only JY index volatility using Bootstrap so \" <<\n                \"expected exactly one basket but got \" << cbs.size() << \".\");\n            const auto& cb = cbs[0];\n            if (!cb.parameter().empty() && cb.parameter() != \"Index\") {\n                WLOG(\"InfJyBuilder: calibrating only JY index volatility using Bootstrap so expected the \" <<\n                    \"calibration basket parameter to be 'Index' but got '\" << cb.parameter() << \"'.\");\n            }\n            indexInstActive_ = vector<bool>(cb.instruments().size(), false);\n            indexBasket_ = buildCalibrationBasket(cb, indexInstActive_, indexInstExpiries_);\n        } else {\n            DLOG(\"InfJyBuilder: need a calibration basket with parameter equal to 'Index'.\");\n            const auto& cb = calibrationBasket(\"Index\");\n            indexInstActive_ = vector<bool>(cb.instruments().size(), false);\n            indexBasket_ = buildCalibrationBasket(cb, indexInstActive_, indexInstExpiries_);\n        }\n    }\n\n    // Secondly, look at the real rate portion i.e. are we calibrating it.\n    if (rrReversion.calibrate() || rrVolatility.calibrate()) {\n\n        DLOG(\"InfJyBuilder: building calibration basket for JY real rate bootstrap calibration.\");\n        QL_REQUIRE(!(rrReversion.calibrate() && rrVolatility.calibrate()), \"InfJyBuilder: calibrating both the \" <<\n            \"real rate reversion and real rate volatility using Bootstrap is not supported.\");\n\n        // If we are not calibrating the index portion, then we expect exactly one calibration basket. Otherwise \n        // we need to find a basket with the 'RealRate' parameter.\n        if (!idxVolatility.calibrate()) {\n            QL_REQUIRE(cbs.size() == 1, \"InfJyBuilder: calibrating only JY real rate using Bootstrap so \" <<\n                \"expected exactly one basket but got \" << cbs.size() << \".\");\n            const auto& cb = cbs[0];\n            if (!cb.parameter().empty() && cb.parameter() != \"RealRate\") {\n                WLOG(\"InfJyBuilder: calibrating only JY real rate using Bootstrap so expected the \" <<\n                    \"calibration basket parameter to be 'RealRate' but got '\" << cb.parameter() << \"'.\");\n            }\n            rrInstActive_ = vector<bool>(cb.instruments().size(), false);\n            realRateBasket_ = buildCalibrationBasket(cb, rrInstActive_, rrInstExpiries_, rrReversion.calibrate());\n        } else {\n            DLOG(\"InfJyBuilder: need a calibration basket with parameter equal to 'RealRate'.\");\n            const auto& cb = calibrationBasket(\"RealRate\");\n            rrInstActive_ = vector<bool>(cb.instruments().size(), false);\n            realRateBasket_ = buildCalibrationBasket(cb, rrInstActive_, rrInstExpiries_, rrReversion.calibrate());\n        }\n    }\n\n}\n\nHelpers InfJyBuilder::buildCalibrationBasket(const CalibrationBasket& cb,\n    vector<bool>& active, Array& expiries, bool forRealRateReversion) const {\n\n    QL_REQUIRE(!cb.empty(), \"InfJyBuilder: calibration basket should not be empty.\");\n\n    const auto& ci = cb.instruments();\n    QL_REQUIRE(ci.size() == active.size(), \"InfJyBuilder: expected the active instruments vector \" <<\n        \"size to equal the number of calibration instruments\");\n    fill(active.begin(), active.end(), false);\n\n    if (cb.instrumentType() == \"CpiCapFloor\") {\n        return buildCpiCapFloorBasket(cb, active, expiries);\n    } else if (cb.instrumentType() == \"YoYCapFloor\") {\n        return buildYoYCapFloorBasket(cb, active, expiries);\n    } else if (cb.instrumentType() == \"YoYSwap\") {\n        return buildYoYSwapBasket(cb, active, expiries, forRealRateReversion);\n    } else {\n        QL_FAIL(\"InfJyBuilder: expected calibration instrument to be one of CpiCapFloor, YoYCapFloor or YoYSwap\");\n    }\n}\n\nHelpers InfJyBuilder::buildCpiCapFloorBasket(const CalibrationBasket& cb,\n    vector<bool>& active, Array& expiries) const {\n\n    DLOG(\"InfJyBuilder: start building the CPI cap floor calibration basket.\");\n\n    QL_REQUIRE(!cpiVolatility_.empty(), \"InfJyBuilder: need a non-empty CPI cap floor volatility structure \" <<\n        \"to build a CPI cap floor calibration basket.\");\n\n    // Procedure is to create a CPI cap floor as described by each instrument in the calibration basket. We then value \n    // each of the CPI cap floor instruments using market data and an engine and pass the NPV as the market premium to \n    // helper that we create.\n\n    Helpers helpers;\n\n    // Create the engine\n    auto zts = zeroInflationIndex_->zeroInflationTermStructure();\n    auto engine = boost::make_shared<CPIBlackCapFloorEngine>(rateCurve_, cpiVolatility_);\n\n    // CPI cap floor calibration instrument details. Assumed to equal those from the index and market structures.\n    // Some of these should possibly come from conventions.\n    // Also some variables used in the loop below.\n    auto calendar = zeroInflationIndex_->fixingCalendar();\n    auto baseDate = zts->baseDate();\n    auto baseCpi = zeroInflationIndex_->fixing(baseDate);\n    auto bdc = cpiVolatility_->businessDayConvention();\n    auto obsLag = cpiVolatility_->observationLag();\n    Handle<ZeroInflationIndex> inflationIndex(zeroInflationIndex_);\n    Date today = Settings::instance().evaluationDate();\n    Real nominal = 1.0;\n\n    // Avoid instruments with duplicate expiry times in the loop below\n    set<Time, CloseCmp> expiryTimes;\n\n    // Reference calibration dates if any. If they are given, we only include one calibration instrument from each \n    // period in the grid. Logic copied from other builders.\n    auto rcDates = referenceCalibrationDates();\n    auto prevRcDate = Date::minDate();\n\n    // Add calibration instruments to the helpers vector.\n    const auto& ci = cb.instruments();\n    for (Size i = 0; i < ci.size(); ++i) {\n\n        auto cpiCapFloor = boost::dynamic_pointer_cast<CpiCapFloor>(ci[i]);\n        QL_REQUIRE(cpiCapFloor, \"InfJyBuilder: expected CpiCapFloor calibration instrument.\");\n        auto maturity = optionMaturity(cpiCapFloor->maturity(), calendar);\n\n        // Deal with reference calibration date grid stuff.\n        auto rcDate = lower_bound(rcDates.begin(), rcDates.end(), maturity);\n        if (!(rcDate == rcDates.end() || *rcDate > prevRcDate)) {\n            active[i] = false;\n            continue;\n        }\n\n        if (rcDate != rcDates.end())\n            prevRcDate = *rcDate;\n\n        // Build the CPI calibration instrument in order to calculate its NPV.\n\n        /* FIXME - the maturity date is not adjusted on eval date changes even if given as a tenor\n                 - if the strike is atm, the value will not be updated on eval date changes */\n        Real strikeValue =\n            cpiCapFloorStrikeValue(cpiCapFloor->strike(), *zeroInflationIndex_->zeroInflationTermStructure(), maturity);\n        Option::Type capfloor = cpiCapFloor->type() == CapFloor::Cap ? Option::Call : Option::Put;\n        auto inst = boost::make_shared<CPICapFloor>(capfloor, nominal, today, baseCpi, maturity, calendar,\n                bdc, calendar, bdc, strikeValue, inflationIndex, obsLag);\n        inst->setPricingEngine(engine);\n\n        // Build the helper using the NPV as the premium.\n        auto premium = inst->NPV();\n        auto helper = boost::make_shared<CpiCapFloorHelper>(capfloor, baseCpi, maturity, calendar, bdc,\n            calendar, bdc, strikeValue, inflationIndex, obsLag, premium);\n\n\n        // Add the helper's time to expiry.\n        auto fixingDate = helper->instrument()->fixingDate();\n        auto t = inflationTime(fixingDate, *zts);\n        auto p = expiryTimes.insert(t);\n        QL_REQUIRE(data_->ignoreDuplicateCalibrationExpiryTimes() || p.second,\n                   \"InfJyBuilder: a CPI cap floor calibration \"\n                       << \"instrument with the expiry time, \" << t << \", was already added.\");\n\n        if(p.second)\n            helpers.push_back(helper);\n\n        TLOG(\"InfJyBuilder: \" << (p.second ?\n                                  \"added CPICapFloor helper\" :\n                                  \"skipped CPICapFloor helper due to duplicate expiry time (\" + std::to_string(t) + \")\") <<\n             \": index = \" << data_->index() <<\n             \", type = \" << cpiCapFloor->type() <<\n             \", expiry = \" << io::iso_date(maturity) <<\n             \", base CPI = \" << baseCpi <<\n             \", strike = \" << strikeValue <<\n             \", obs lag = \" << obsLag <<\n             \", market premium = \" << premium);\n    }\n\n    // Populate the expiry times array with the unique sorted expiry times.\n    expiries = Array(expiryTimes.begin(), expiryTimes.end());\n\n    DLOG(\"InfJyBuilder: finished building the CPI cap floor calibration basket.\");\n\n    return helpers;\n}\n\nHelpers InfJyBuilder::buildYoYCapFloorBasket(const CalibrationBasket& cb, vector<bool>& active, Array& expiries) const {\n\n    DLOG(\"InfJyBuilder: start building the YoY cap floor calibration basket.\");\n\n    // Initial checks.\n    QL_REQUIRE(yoyInflationIndex_, \"InfJyBuilder: need a valid year on year inflation index \"\n                                       << \"to build a year on year cap floor calibration basket.\");\n    auto yoyTs = yoyInflationIndex_->yoyInflationTermStructure();\n    QL_REQUIRE(!yoyTs.empty(), \"InfJyBuilder: need a valid year on year term structure \"\n                                   << \"to build a year on year cap floor calibration basket.\");\n    QL_REQUIRE(!yoyVolatility_.empty(), \"InfJyBuilder: need a valid year on year volatility \"\n                                            << \"structure to build a year on year cap floor calibration basket.\");\n\n    // Procedure is to create a YoY cap floor as described by each instrument in the calibration basket. We then value\n    // each of the YoY cap floor instruments using market data and an engine and pass the NPV as the market premium to\n    // helper that we create.\n\n    Helpers helpers;\n\n    // Create the engine which depends on the type of the YoY volatility and the shift.\n    boost::shared_ptr<PricingEngine> engine;\n    auto ovsType = yoyVolatility_->volatilityType();\n    if (ovsType == Normal)\n        engine = boost::make_shared<YoYInflationBachelierCapFloorEngine>(yoyInflationIndex_, yoyVolatility_, rateCurve_);\n    else if (ovsType == ShiftedLognormal && close(yoyVolatility_->displacement(), 0.0))\n        engine = boost::make_shared<YoYInflationBlackCapFloorEngine>(yoyInflationIndex_, yoyVolatility_, rateCurve_);\n    else if (ovsType == ShiftedLognormal)\n        engine =\n            boost::make_shared<YoYInflationUnitDisplacedBlackCapFloorEngine>(yoyInflationIndex_, yoyVolatility_, rateCurve_);\n    else\n        QL_FAIL(\"InfJyBuilder: can't create engine with yoy volatility type, \" << ovsType << \".\");\n\n    // YoY cap floor calibration instrument details. Assumed to equal those from the index and market structures.\n    // Some of these should possibly come from conventions. Also some variables used in the loop below.\n    Natural settlementDays = 2;\n    auto calendar = yoyInflationIndex_->fixingCalendar();\n    DayCounter dc = Thirty360();\n    auto bdc = Following;\n    auto obsLag = yoyVolatility_->observationLag();\n\n    // Avoid instruments with duplicate expiry times in the loop below\n    set<Time, CloseCmp> expiryTimes;\n\n    // Reference calibration dates if any. If they are given, we only include one calibration instrument from each \n    // period in the grid. Logic copied from other builders.\n    auto rcDates = referenceCalibrationDates();\n    auto prevRcDate = Date::minDate();\n\n    // Add calibration instruments to the helpers vector.\n    const auto& ci = cb.instruments();\n    for (Size i = 0; i < ci.size(); ++i) {\n\n        auto yoyCapFloor = boost::dynamic_pointer_cast<YoYCapFloor>(ci[i]);\n        QL_REQUIRE(yoyCapFloor, \"InfJyBuilder: expected YoYCapFloor calibration instrument.\");\n\n        /*! Get the configured strike.\n            FIXME If the strike is atm, the value will not be updated on evaluation date changes */\n        Date today = Settings::instance().evaluationDate();\n        Date maturityDate = calendar.advance(calendar.advance(today, settlementDays * Days), yoyCapFloor->tenor(), bdc);\n        Real strikeValue = yoyCapFloorStrikeValue(yoyCapFloor->strike(), *yoyTs, maturityDate);\n\n        // Build the YoY cap floor helper.\n        auto quote = boost::make_shared<SimpleQuote>(0.01);\n        auto helper = boost::make_shared<YoYCapFloorHelper>(Handle<Quote>(quote), yoyCapFloor->type(), strikeValue,\n            settlementDays, yoyCapFloor->tenor(), yoyInflationIndex_, obsLag, calendar, bdc, dc, calendar, bdc);\n\n        // Deal with reference calibration date grid stuff based on maturity of helper instrument.\n        auto helperInst = helper->yoyCapFloor();\n        auto maturity = helperInst->maturityDate();\n        auto rcDate = lower_bound(rcDates.begin(), rcDates.end(), maturity);\n        if (!(rcDate == rcDates.end() || *rcDate > prevRcDate)) {\n            active[i] = false;\n            continue;\n        }\n\n        if (rcDate != rcDates.end())\n            prevRcDate = *rcDate;\n\n        // Price the underlying helper instrument to get its fair premium.\n        helperInst->setPricingEngine(engine);\n\n        // Update the helper's market quote with the fair rate.\n        quote->setValue(helperInst->NPV());\n\n        // Add the helper's time to expiry.\n        auto fixingDate = helperInst->lastYoYInflationCoupon()->fixingDate();\n        auto t = inflationTime(fixingDate, *yoyTs);\n        auto p = expiryTimes.insert(t);\n        QL_REQUIRE(data_->ignoreDuplicateCalibrationExpiryTimes() || p.second,\n                   \"InfJyBuilder: a YoY cap floor calibration \"\n                       << \"instrument with the expiry time, \" << t << \", was already added.\");\n\n        // Add the helper to the calibration helpers.\n        if(p.second)\n            helpers.push_back(helper);\n\n        TLOG(\"InfJyBuilder: \" << (p.second ?\n                                  \"added YoYCapFloor helper\" :\n                                  \"skipped YoYCapFloor helper due to duplicate expiry time (\" + std::to_string(t) + \")\") <<\n            \": index = \" << data_->index() <<\n            \", type = \" << yoyCapFloor->type() <<\n            \", expiry = \" << io::iso_date(maturity) <<\n            \", strike = \" << strikeValue <<\n            \", obs lag = \" << obsLag <<\n            \", market premium = \" << quote->value());\n    }\n\n    // Populate the expiry times array with the unique sorted expiry times.\n    expiries = Array(expiryTimes.begin(), expiryTimes.end());\n\n    DLOG(\"InfJyBuilder: finished building the YoY cap floor calibration basket.\");\n\n    return helpers;\n}\n\nHelpers InfJyBuilder::buildYoYSwapBasket(const CalibrationBasket& cb,\n    vector<bool>& active, Array& expiries, bool forRealRateReversion) const {\n\n    DLOG(\"InfJyBuilder: start building the YoY swap calibration basket.\");\n\n    // Initial checks.\n    QL_REQUIRE(yoyInflationIndex_, \"InfJyBuilder: need a valid year on year inflation index \" <<\n        \"to build a year on year swap calibration basket.\");\n    auto yoyTs = yoyInflationIndex_->yoyInflationTermStructure();\n    QL_REQUIRE(!yoyTs.empty(), \"InfJyBuilder: need a valid year on year term structure \" <<\n        \"to build a year on year swap calibration basket.\");\n\n    // Procedure is to create a YoY cap floor as described by each instrument in the calibration basket. We then value \n    // each of the YoY cap floor instruments using market data and an engine and pass the NPV as the market premium to \n    // helper that we create.\n\n    Helpers helpers;\n\n    // Create the engine\n    auto engine = boost::make_shared<DiscountingSwapEngine>(rateCurve_);\n\n    // YoY swap calibration instrument details. Assumed to equal those from the index and market structures.\n    // Some of these should possibly come from conventions. Hardcoded some common values here.\n    // Also some variables used in the loop below.\n    Natural settlementDays = 2;\n    auto calendar = yoyInflationIndex_->fixingCalendar();\n    auto dc = Thirty360();\n    auto bdc = Following;\n    auto obsLag = yoyTs->observationLag();\n\n    // Avoid instruments with duplicate expiry times in the loop below\n    set<Time, CloseCmp> expiryTimes;\n\n    // Reference calibration dates if any. If they are given, we only include one calibration instrument from each \n    // period in the grid. Logic copied from other builders.\n    auto rcDates = referenceCalibrationDates();\n    auto prevRcDate = Date::minDate();\n\n    // Add calibration instruments to the helpers vector.\n    const auto& ci = cb.instruments();\n    for (Size i = 0; i < ci.size(); ++i) {\n\n        auto yoySwap = boost::dynamic_pointer_cast<YoYSwap>(ci[i]);\n        QL_REQUIRE(yoySwap, \"InfJyBuilder: expected YoYSwap calibration instrument.\");\n\n        // Build the YoY helper.\n        auto quote = boost::make_shared<SimpleQuote>(0.01);\n        auto helper = boost::make_shared<YoYSwapHelper>(Handle<Quote>(quote), settlementDays, yoySwap->tenor(),\n                                                        yoyInflationIndex_, rateCurve_, obsLag, calendar, bdc, dc,\n                                                        calendar, bdc, dc, calendar, bdc);\n\n        // Deal with reference calibration date grid stuff based on maturity of helper instrument.\n        auto helperInst = helper->yoySwap();\n        auto maturity = helperInst->maturityDate();\n        auto rcDate = lower_bound(rcDates.begin(), rcDates.end(), maturity);\n        if (!(rcDate == rcDates.end() || *rcDate > prevRcDate)) {\n            active[i] = false;\n            continue;\n        }\n\n        if (rcDate != rcDates.end())\n            prevRcDate = *rcDate;\n\n        // Price the underlying helper instrument to get its fair rate.\n        helperInst->setPricingEngine(engine);\n\n        // Update the helper's market quote with the fair rate.\n        quote->setValue(helperInst->fairRate());\n\n        // For JY calibration to YoY swaps, the parameter's time depends on whether you are calibrating the real rate \n        // reversion or the real rate volatility (probably don't want to calibrate the inflation index vol to YoY \n        // swaps as it only shows up via the drift). If you are calibrating to real rate reversion, you want the time \n        // to the numerator index fixing date on the last YoY swaplet on the YoY leg. If you are calibrating to real \n        // rate volatility, you want the time to the denominator index fixing date on the last YoY swaplet on the YoY \n        // leg. We use numerator fixing date - 1 * Years here for this. You can see this from the parameter \n        // dependencies in the YoY swaplet formula in Section 13 of the book (i.e. T vs. S).\n        // If t is not positive, we log a message and skip this helper.\n        Time t = 0.0;\n        QL_REQUIRE(!helperInst->yoyLeg().empty(), \"InfJyBuilder: expected YoYSwap to have non-empty YoY leg.\");\n        auto finalYoYCoupon = boost::dynamic_pointer_cast<YoYInflationCoupon>(helperInst->yoyLeg().back());\n        Date numFixingDate = finalYoYCoupon->fixingDate();\n        if (forRealRateReversion) {\n            t = inflationTime(numFixingDate, *yoyTs);\n        } else {\n            auto denFixingDate = numFixingDate - 1 * Years;\n            t = inflationTime(denFixingDate, *yoyTs);\n        }\n\n        if (t <= 0) {\n            DLOG(\"The year on year swap with maturity tenor, \" << yoySwap->tenor() << \", and date, \" << maturity <<\n                \", has a non-positive parameter time, \" << t << \", so skipping this as a calibration instrument.\");\n            continue;\n        }\n\n        // Add the helper to the calibration helpers.\n        helpers.push_back(helper);\n\n        auto p = expiryTimes.insert(t);\n        QL_REQUIRE(p.second, \"InfJyBuilder: a YoY swap calibration instrument with the expiry \" <<\n            \"time, \" << t << \", was already added.\");\n\n        TLOG(\"InfJyBuilder: added year on year swap helper\" <<\n            \": index = \" << data_->index() <<\n            \", maturity = \" << io::iso_date(maturity) <<\n            \", obs lag = \" << obsLag <<\n            \", market rate = \" << quote->value());\n    }\n\n    // Populate the expiry times array with the unique sorted expiry times.\n    expiries = Array(expiryTimes.begin(), expiryTimes.end());\n\n    DLOG(\"InfJyBuilder: finished building the YoY swap calibration basket.\");\n\n    return helpers;\n}\n\nconst CalibrationBasket& InfJyBuilder::calibrationBasket(const string& parameter) const {\n\n    for (const auto& cb : data_->calibrationBaskets()) {\n        if (cb.parameter() == parameter) {\n            return cb;\n        }\n    }\n\n    QL_FAIL(\"InfJyBuilder: unable to find calibration basket with parameter value equal to '\" << parameter << \"'.\");\n}\n\nboost::shared_ptr<Lgm1fParametrization<ZeroInflationTermStructure>> InfJyBuilder::createRealRateParam() const {\n\n    DLOG(\"InfJyBuilder: start creating the real rate parameterisation.\");\n\n    // Initial parameter setup as provided by the data_.\n    const ReversionParameter& rrReversion = data_->realRateReversion();\n    const VolatilityParameter& rrVolatility = data_->realRateVolatility();\n    Array rrVolatilityTimes(rrVolatility.times().begin(), rrVolatility.times().end());\n    Array rrVolatilityValues(rrVolatility.values().begin(), rrVolatility.values().end());\n    Array rrReversionTimes(rrReversion.times().begin(), rrReversion.times().end());\n    Array rrReversionValues(rrReversion.values().begin(), rrReversion.values().end());\n\n    // Perform checks and in the event of bootstrap calibration, may need to restructure the parameters.\n    setupParams(rrReversion, rrReversionTimes, rrReversionValues, rrInstExpiries_, \"RealRate reversion\");\n    setupParams(rrVolatility, rrVolatilityTimes, rrVolatilityValues, rrInstExpiries_, \"RealRate volatility\");\n\n    // Create the JY parameterization.\n    using RT = LgmData::ReversionType;\n    using VT = LgmData::VolatilityType;\n\n    // Real rate parameter constraints\n    const auto& cc = data_->calibrationConfiguration();\n    auto rrVolConstraint = cc.constraint(\"RealRateVolatility\");\n    auto rrRevConstraint = cc.constraint(\"RealRateReversion\");\n\n    // Create the real rate portion of the parameterization\n    using QuantLib::ZeroInflationTermStructure;\n    boost::shared_ptr<QuantExt::Lgm1fParametrization<ZeroInflationTermStructure>> realRateParam;\n    if (rrReversion.reversionType() == RT::HullWhite && rrVolatility.volatilityType() == VT::HullWhite) {\n        using QuantExt::Lgm1fPiecewiseConstantHullWhiteAdaptor;\n        DLOG(\"InfJyBuilder: real rate parameterization is Lgm1fPiecewiseConstantHullWhiteAdaptor\");\n        realRateParam = boost::make_shared<Lgm1fPiecewiseConstantHullWhiteAdaptor<ZeroInflationTermStructure>>(\n            zeroInflationIndex_->currency(), zeroInflationIndex_->zeroInflationTermStructure(), rrVolatilityTimes,\n            rrVolatilityValues, rrReversionTimes, rrReversionValues, data_->index(), rrVolConstraint, rrRevConstraint);\n    } else if (rrReversion.reversionType() == RT::HullWhite && rrVolatility.volatilityType() == VT::Hagan) {\n        using QuantExt::Lgm1fPiecewiseConstantParametrization;\n        DLOG(\"InfJyBuilder: real rate parameterization is Lgm1fPiecewiseConstantParametrization\");\n        realRateParam = boost::make_shared<Lgm1fPiecewiseConstantParametrization<ZeroInflationTermStructure>>(\n            zeroInflationIndex_->currency(), zeroInflationIndex_->zeroInflationTermStructure(), rrVolatilityTimes,\n            rrVolatilityValues, rrReversionTimes, rrReversionValues, data_->index(), rrVolConstraint, rrRevConstraint);\n    } else if (rrReversion.reversionType() == RT::Hagan && rrVolatility.volatilityType() == VT::Hagan) {\n        using QuantExt::Lgm1fPiecewiseLinearParametrization;\n        DLOG(\"InfJyBuilder: real rate parameterization is Lgm1fPiecewiseLinearParametrization\");\n        realRateParam = boost::make_shared<Lgm1fPiecewiseLinearParametrization<ZeroInflationTermStructure>>(\n            zeroInflationIndex_->currency(), zeroInflationIndex_->zeroInflationTermStructure(), rrVolatilityTimes,\n            rrVolatilityValues, rrReversionTimes, rrReversionValues, data_->index(), rrVolConstraint, rrRevConstraint);\n    } else {\n        QL_FAIL(\"InfJyBuilder: reversion type Hagan and volatility type HullWhite not supported.\");\n    }\n\n    Time horizon = data_->reversionTransformation().horizon();\n    if (horizon >= 0.0) {\n        DLOG(\"InfJyBuilder: apply shift horizon \" << horizon << \" to the JY real rate parameterisation for index \" <<\n            data_->index() << \".\");\n        realRateParam->shift() = horizon;\n    } else {\n        WLOG(\"InfJyBuilder: ignoring negative horizon, \" << horizon <<\n            \", passed to the JY real rate parameterisation for index \" << data_->index() << \".\");\n    }\n\n    Real scaling = data_->reversionTransformation().scaling();\n    if (scaling > 0.0) {\n        DLOG(\"InfJyBuilder: apply scaling \" << scaling << \" to the JY real rate parameterisation for index \" <<\n            data_->index() << \".\");\n        realRateParam->scaling() = scaling;\n    } else {\n        WLOG(\"Ignoring non-positive scaling, \" << scaling <<\n            \", passed to the JY real rate parameterisation for index \" << data_->index() << \".\");\n    }\n\n    DLOG(\"InfJyBuilder: finished creating the real rate parameterisation.\");\n\n    return realRateParam;\n}\n\nboost::shared_ptr<FxBsParametrization> InfJyBuilder::createIndexParam() const {\n\n    DLOG(\"InfJyBuilder: start creating the index parameterisation.\");\n\n    // Initial parameter setup as provided by the data_.\n    const VolatilityParameter& idxVolatility = data_->indexVolatility();\n    Array idxVolatilityTimes(idxVolatility.times().begin(), idxVolatility.times().end());\n    Array idxVolatilityValues(idxVolatility.values().begin(), idxVolatility.values().end());\n\n    // Perform checks and in the event of bootstrap calibration, may need to restructure the parameters.\n    setupParams(idxVolatility, idxVolatilityTimes, idxVolatilityValues, indexInstExpiries_, \"Index volatility\");\n\n    // Create the index portion of the parameterization\n    boost::shared_ptr<QuantExt::FxBsParametrization> indexParam;\n\n    Handle<Quote> baseCpiQuote(boost::make_shared<SimpleQuote>(\n        zeroInflationIndex_->fixing(zeroInflationIndex_->zeroInflationTermStructure()->baseDate())));\n\n    // Index volatility parameter constraints\n    const auto& cc = data_->calibrationConfiguration();\n    auto idxVolConstraint = cc.constraint(\"IndexVolatility\");\n\n    if (idxVolatility.type() == ParamType::Piecewise) {\n        using QuantExt::FxBsPiecewiseConstantParametrization;\n        DLOG(\"InfJyBuilder: index volatility parameterization is FxBsPiecewiseConstantParametrization\");\n        indexParam = boost::make_shared<FxBsPiecewiseConstantParametrization>(\n            zeroInflationIndex_->currency(), baseCpiQuote, idxVolatilityTimes, idxVolatilityValues, idxVolConstraint);\n    } else if (idxVolatility.type() == ParamType::Constant) {\n        using QuantExt::FxBsConstantParametrization;\n        DLOG(\"InfJyBuilder: index volatility parameterization is FxBsConstantParametrization\");\n        indexParam = boost::make_shared<FxBsConstantParametrization>(\n            zeroInflationIndex_->currency(), baseCpiQuote, idxVolatilityValues[0]);\n    } else {\n        QL_FAIL(\"InfJyBuilder: index volatility parameterization needs to be Piecewise or Constant.\");\n    }\n\n    DLOG(\"InfJyBuilder: finished creating the index parameterisation.\");\n\n    return indexParam;\n}\n\nvoid InfJyBuilder::setupParams(const ModelParameter& param, Array& times, Array& values,\n    const Array& expiries, const string& paramName) const {\n\n    DLOG(\"InfJyBuilder: start setting up parameters for \" << paramName);\n\n    if (param.type() == ParamType::Constant) {\n        QL_REQUIRE(param.times().size() == 0, \"InfJyBuilder: parameter is constant so empty times expected\");\n        QL_REQUIRE(param.values().size() == 1, \"InfJyBuilder: parameter is constant so initial value array \" <<\n            \"should have 1 element.\");\n    } else if (param.type() == ParamType::Piecewise) {\n\n        if (param.calibrate() && data_->calibrationType() == CalibrationType::Bootstrap) {\n            QL_REQUIRE(!expiries.empty(), \"InfJyBuilder: calibration instrument expiries are empty.\");\n            QL_REQUIRE(!values.empty(), \"InfJyBuilder: expected at least one initial value.\");\n            DLOG(\"InfJyBuilder: overriding initial times \" << times << \" with option calibration instrument \" <<\n                \"expiries \" << expiries << \".\");\n            times = Array(expiries.begin(), expiries.end() - 1);\n            values = Array(times.size() + 1, values[0]);\n        } else {\n            QL_REQUIRE(values.size() == times.size() + 1, \"InfJyBuilder: size of values grid, \" << values.size() <<\n                \", should be 1 greater than the size of the times grid, \" << times.size() << \".\");\n        }\n\n    } else {\n        QL_FAIL(\"Expected \" << paramName << \" parameter to be Constant or Piecewise.\");\n    }\n\n    DLOG(\"InfJyBuilder: finished setting up parameters for \" << paramName);\n}\n\nvector<Date> InfJyBuilder::referenceCalibrationDates() const {\n\n    TLOG(\"InfJyBuilder: start building reference date grid '\" << referenceCalibrationGrid_ << \"'.\");\n    \n    vector<Date> res;\n    if (!referenceCalibrationGrid_.empty())\n        res = DateGrid(referenceCalibrationGrid_).dates();\n\n    TLOG(\"InfJyBuilder: finished building reference date grid.\");\n\n    return res;\n}\n\nvoid InfJyBuilder::initialiseMarket() {\n\n    TLOG(\"InfJyBuilder: start initialising market data members.\");\n\n    // Try catches are not nice but Market does not have a method for checking if a structure exists so it is \n    // unfortunately necessary.\n    try {\n        cpiVolatility_ = market_->cpiInflationCapFloorVolatilitySurface(data_->index(), configuration_);\n    } catch (...) {\n        DLOG(\"InfJyBuilder: the market does not have a CPI cap floor volatility surface.\");\n    }\n\n    try {\n        yoyInflationIndex_ = *market_->yoyInflationIndex(data_->index(), configuration_);\n        marketObserver_->registerWith(yoyInflationIndex_);\n    } catch (...) {\n        DLOG(\"InfJyBuilder: the market does not have a YoY inflation index.\");\n    }\n\n    try {\n        yoyVolatility_ = market_->yoyCapFloorVol(data_->index(), configuration_);\n    } catch (...) {\n        DLOG(\"InfJyBuilder: the market does not have a YoY cap floor volatility surface.\");\n    }\n\n    TLOG(\"InfJyBuilder: finished initialising market data members.\");\n}\n\nbool InfJyBuilder::pricesChanged(bool updateCache) const {\n\n    // Build the calibration instruments again before checking the market price below.\n    // Don't need to do this if updateCache is true, because only called above after buildCalibrationBaskets().\n    if (!updateCache)\n        buildCalibrationBaskets();\n\n    // Resize the cache to match the number of calibration instruments\n    auto numInsts = realRateBasket_.size() + indexBasket_.size();\n    if (priceCache_.size() != numInsts)\n        priceCache_ = vector<Real>(numInsts, Null<Real>());\n\n    // Check if any market prices have changed. Return true if they have and false if they have not.\n    // If asked to update the cached prices, via updateCache being true, update the prices, if necessary.\n    bool result = false;\n    Size ctr = 0;\n    for (const auto& ci : boost::range::join(realRateBasket_, indexBasket_)) {\n        auto mp = marketPrice(ci);\n        if (!close_enough(priceCache_[ctr], mp)) {\n            if (updateCache)\n                priceCache_[ctr] = mp;\n            result = true;\n        }\n        ctr++;\n    }\n\n    return result;\n}\n\nReal InfJyBuilder::marketPrice(const boost::shared_ptr<CalibrationHelper>& helper) const {\n\n    if (auto h = boost::dynamic_pointer_cast<CpiCapFloorHelper>(helper)) {\n        return h->marketValue();\n    }\n\n    if (auto h = boost::dynamic_pointer_cast<YoYCapFloorHelper>(helper)) {\n        return h->marketValue();\n    }\n\n    if (boost::shared_ptr<YoYSwapHelper> h = boost::dynamic_pointer_cast<YoYSwapHelper>(helper)) {\n        return h->marketRate();\n    }\n\n    QL_FAIL(\"InfJyBuilder: unrecognised calibration instrument for JY calibration.\");\n}\n\n}\n}\n", "meta": {"hexsha": "d02950dd24e6fdc6ed4f3f6513703320e74db844", "size": 39722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/model/inflation/infjybuilder.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": "OREData/ored/model/inflation/infjybuilder.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": "OREData/ored/model/inflation/infjybuilder.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": 47.0082840237, "max_line_length": 125, "alphanum_fraction": 0.6817380797, "num_tokens": 9373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.17846798014088738}}
{"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_EXT_GIS_IO_SHAPELIB_SHP_READ_OBJECT_HPP\n#define BOOST_GEOMETRY_EXT_GIS_IO_SHAPELIB_SHP_READ_OBJECT_HPP\n\n\n#include <boost/mpl/assert.hpp>\n#include <boost/range.hpp>\n#include <boost/scoped_array.hpp>\n\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n#include <boost/geometry/core/ring_type.hpp>\n#include <boost/geometry/algorithms/num_points.hpp>\n\n\n// Should be somewhere in your include path\n#include \"shapefil.h\"\n\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace shp_read_object\n{\n\n\ntemplate <typename Pair>\nstruct sort_on_area_desc\n{\n    inline bool operator()(Pair const& left, Pair const& right)\n    {\n        return left.second > right.second;\n    }\n};\n\n\n\ntemplate <typename LineString>\nstruct read_linestring\n{\n    static inline SHPObject* apply(LineString const& linestring)\n    {\n        typedef typename geometry::point_type<Linestring>::type point_type;\n\n        if (shape.nSHPType == SHPT_ARCZ && shape.nParts == 1)\n        {\n            double* const x = shape.padfX;\n            double* const y = shape.padfY;\n\n            for (int i = 0; i < shape.nVertices; i++)\n            {\n                point_type point;\n                geometry::set<0>(point, x[i]);\n                geometry::set<1>(point, y[i]);\n\n                linestring.push_back(point);\n            }\n            return true;\n        }\n        return false;\n\n    }\n};\n\n\ntemplate <typename Polygon>\nstruct read_polygon\n{\n    static inline SHPObject* apply(Polygon const& polygon)\n    {\n        typedef typename geometry::point_type<Polygon>::type point_type;\n        typedef typename geometry::ring_type<Polygon>::type ring_type;\n\n        if (shape.nSHPType == SHPT_POLYGON)\n        {\n            //std::cout << shape.nParts << \" \" << shape.nVertices << std::endl;\n\n            double* const x = shape.padfX;\n            double* const y = shape.padfY;\n\n            typedef std::pair<ring_type, double> ring_plus_area;\n            std::vector<ring_plus_area> rings;\n            rings.resize(shape.nParts);\n\n            int v = 0;\n            for (int p = 0; p < shape.nParts; p++)\n            {\n                int const first = shape.panPartStart[p];\n                int const last = p + 1 < shape.nParts\n                    ? shape.panPartStart[p + 1]\n                    : shape.nVertices;\n\n                for (v = first; v < last; v++)\n                {\n                    point_type point;\n                    geometry::set<0>(point, x[v]);\n                    geometry::set<1>(point, y[v]);\n                    rings[p].first.push_back(point);\n                }\n                rings[p].second = geometry::math::abs(geometry::area(rings[p].first));\n            }\n\n            if (rings.size() > 1)\n            {\n                // Sort rings on area\n                std::sort(rings.begin(), rings.end(),\n                        sort_on_area_desc<ring_plus_area>());\n                // Largest area (either positive or negative) is outer ring\n                // Rest of the rings are holes\n                geometry::exterior_ring(polygon) = rings.front().first;\n                for (int i = 1; i < rings.size(); i++)\n                {\n                    geometry::interior_rings(polygon).push_back(rings[i].first);\n                    if (! geometry::within(rings[i].first.front(), geometry::exterior_ring(polygon))\n                        && ! geometry::within(rings[i].first.at(1), geometry::exterior_ring(polygon))\n                        )\n                    {\n    #if ! defined(NDEBUG)\n                        std::cout << \"Error: inconsistent ring!\" << std::endl;\n                        BOOST_FOREACH(ring_plus_area const& r, rings)\n                        {\n                            std::cout << geometry::area(r.first) << \" \"\n                                << geometry::wkt(r.first.front()) << \" \"\n                                << std::endl;\n                        }\n    #endif\n                    }\n                }\n            }\n            else if (rings.size() == 1)\n            {\n                geometry::exterior_ring(polygon) = rings.front().first;\n            }\n            return true;\n        }\n        return false;\n    }\n};\n\n\n\n}} // namespace detail::shp_read_object\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\ntemplate <typename Tag, typename Geometry>\nstruct shp_read_object\n{\n    BOOST_MPL_ASSERT_MSG\n        (\n            false, NOT_OR_NOT_YET_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPE\n            , (Geometry)\n        );\n};\n\n\ntemplate <typename LineString>\nstruct shp_read_object<linestring_tag, LineString>\n    : detail::shp_read_object::read_linestring<LineString>\n{};\n\n\n\n\ntemplate <typename Polygon>\nstruct shp_read_object<polygon_tag, Polygon>\n    : detail::shp_read_object::read_polygon<Polygon>\n{};\n\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\ntemplate <typename Geometry>\ninline void read_shapefile(std::string const& filename,\n                    std::vector<Geometry>& geometries)\n{\n\n    try\n    {\n        // create shape_reader\n\n        for (int i = 0; i < shape_reader.Count(); i++)\n        {\n            SHPObject* psShape = SHPReadObject(shp_handle, i);\n            Geometry geometry;\n            if (dispatch::shp_read_object<Geometry>(*psShape, geometry))\n            {\n                geometries.push_back(geometry);\n            }\n            SHPDestroyObject( psShape );\n        }\n\n    }\n    catch(std::string s)\n    {\n        throw s;\n    }\n    catch(...)\n    {\n        throw std::string(\"Other exception\");\n    }\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_EXT_GIS_IO_SHAPELIB_SHP_READ_OBJECT_HPP\n", "meta": {"hexsha": "73204a95366fa663b32e1ecaf990323573d5a831", "size": 6035, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/gis/io/shapelib/shp_read_object.hpp", "max_stars_repo_name": "yumetodo/OpenSiv3D", "max_stars_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-04-26T11:06:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T16:42:31.000Z", "max_issues_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/gis/io/shapelib/shp_read_object.hpp", "max_issues_repo_name": "yumetodo/OpenSiv3D", "max_issues_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T13:25:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T12:34:44.000Z", "max_forks_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/gis/io/shapelib/shp_read_object.hpp", "max_forks_repo_name": "yumetodo/OpenSiv3D", "max_forks_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 26.703539823, "max_line_length": 101, "alphanum_fraction": 0.5613918807, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.17846797523681193}}
{"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_GENERIC_FUNCTION_AUTOFOLD_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_AUTOFOLD_HPP_INCLUDED\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/detail/diagnostic.hpp>\n#include <boost/simd/function/extract.hpp>\n#include <boost/simd/arch/common/tags.hpp>\n#include <boost/simd/as.hpp>\n#include <boost/dispatch/hierarchy/functions.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  BOOST_DISPATCH_OVERLOAD_FALLBACK (  ( typename F, typename BinOp, typename NeutralElement\n                                      , typename Arg, typename Ext\n                                      )\n                                   , bd::reduction_<F,BinOp,NeutralElement>\n                                   , bs::simd_\n                                   , bs::pack_<bd::unspecified_<Arg>, Ext>\n                                   )\n  {\n    using value_t  = typename Arg::value_type;\n    using result_t = decltype( bd::functor<F>()( std::declval<value_t>() ) );\n\n    template<typename K, typename N>\n    BOOST_FORCEINLINE result_t fold_(Arg const& a0, brigand::list<N> const&, K const&) const\n    {\n      bd::functor<BinOp> bop;\n      bd::functor<NeutralElement> ne;\n      auto r = bop( ne( as_<result_t>{} ), bs::extract<0>(a0) );\n\n      return bd::functor<F>()( r );\n    }\n\n    template<typename K, typename N0, typename N1, typename... N>\n    BOOST_FORCEINLINE result_t fold_(Arg const& a0, brigand::list<N0,N1,N...> const&, K const&) const\n    {\n      bd::functor<BinOp> bop;\n      bd::functor<NeutralElement> ne;\n\n      auto r = bop( ne( as_<result_t>{} ), bs::extract<0>(a0) );\n           r = bop( r                    , bs::extract<1>(a0) );\n\n      (void)std::initializer_list<bool> { ((r = bop(r, bs::extract<N::value>(a0))),true)... };\n      return bd::functor<F>{}(r);\n    }\n\n    template<typename N0, typename N1, typename... N>\n    BOOST_FORCEINLINE result_t fold_( Arg const& a0, brigand::list<N0,N1,N...> const&\n                                    , aggregate_storage const&\n                                    ) const\n    {\n      bd::functor<BinOp> bop;\n      bd::functor<NeutralElement> ne;\n      using presult_t = typename Arg::substorage_type::template rebind<result_t>;\n\n      auto r = bop( ne( as_<presult_t>{} ), a0.storage()[0]);\n           r = bop( r                     , a0.storage()[1]);\n\n      return bd::functor<F>{}(r);\n    }\n\n    BOOST_FORCEINLINE result_t operator()(Arg const& a0) const\n    {\n      BOOST_SIMD_DIAG(\"autofold for: \" << *this);\n\n      return fold_( a0, typename Arg::traits::static_range{}, typename Arg::storage_kind{} );\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "eec89f40a79ec5106c8028c51d568367be033a51", "size": 3177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/autofold.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/autofold.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/autofold.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.5172413793, "max_line_length": 101, "alphanum_fraction": 0.5561850803, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1784495789903773}}
{"text": "/*\n * Copyright (C) 2018 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#ifndef IGNITION_PHYSICS_TEST_MOCKCENTEROFMASS_HH_\n#define IGNITION_PHYSICS_TEST_MOCKCENTEROFMASS_HH_\n\n#include <ignition/physics/FeatureList.hh>\n#include <Eigen/Geometry>\n\nnamespace mock\n{\n  /////////////////////////////////////////////////\n  // TODO(MXG): Offer an ignition::physics::Vector class that accepts a\n  // FeaturePolicy type.\n  template <typename FeaturePolicyT>\n  using Vector = Eigen::Matrix<\n      typename FeaturePolicyT::Scalar, FeaturePolicyT::Dim, 1>;\n\n\n  /////////////////////////////////////////////////\n  struct MockLinkCenterOfMass : public ignition::physics::Feature\n  {\n    using Identity = ignition::physics::Identity;\n\n    template <typename PolicyT, typename FeaturesT>\n    class Link : public virtual Feature::Link<PolicyT, FeaturesT>\n    {\n      /// \\brief Get the center of mass of this Link\n      public: Vector<PolicyT> CenterOfMass() const;\n    };\n\n    template <typename PolicyT>\n    class Implementation : public virtual Feature::Implementation<PolicyT>\n    {\n      public: virtual Vector<PolicyT> GetLinkCenterOfMass(\n          const Identity &_id) const = 0;\n    };\n  };\n\n  /////////////////////////////////////////////////\n  struct MockModelCenterOfMass : public ignition::physics::Feature\n  {\n    using Identity = ignition::physics::Identity;\n\n    template <typename PolicyT, typename FeaturesT>\n    class Model : public virtual Feature::Model<PolicyT, FeaturesT>\n    {\n      /// \\brief Get the center of mass of this Model\n      public: Vector<PolicyT> CenterOfMass() const;\n    };\n\n    template <typename PolicyT>\n    class Implementation : public virtual Feature::Implementation<PolicyT>\n    {\n      public: virtual Vector<PolicyT> GetModelCenterOfMass(\n          const Identity &_id) const = 0;\n    };\n  };\n\n  using MockCenterOfMass = ignition::physics::FeatureList<\n      MockLinkCenterOfMass,\n      MockModelCenterOfMass\n  >;\n\n  // ---------------------- Implementations ----------------------\n\n  /////////////////////////////////////////////////\n  template <typename PolicyT, typename FeaturesT>\n  Vector<PolicyT> MockLinkCenterOfMass::Link<PolicyT, FeaturesT>::\n  CenterOfMass() const\n  {\n    return this->template Interface<MockLinkCenterOfMass>()->\n        GetLinkCenterOfMass(this->identity);\n  }\n\n  /////////////////////////////////////////////////\n  template <typename PolicyT, typename FeaturesT>\n  Vector<PolicyT> MockModelCenterOfMass::Model<PolicyT, FeaturesT>::\n  CenterOfMass() const\n  {\n    return this->template Interface<MockModelCenterOfMass>()->\n        GetModelCenterOfMass(this->identity);\n  }\n}\n\n#endif\n", "meta": {"hexsha": "bea4099511c584697cf439bf5f2f0178fbdd8cbe", "size": 3193, "ext": "hh", "lang": "C++", "max_stars_repo_path": "test/MockCenterOfMass.hh", "max_stars_repo_name": "diegoferigo/ign-physics", "max_stars_repo_head_hexsha": "8f0d8ce3229f53fbf4e05cb0273530169e6d9fef", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2020-04-15T16:56:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T19:53:01.000Z", "max_issues_repo_path": "test/MockCenterOfMass.hh", "max_issues_repo_name": "diegoferigo/ign-physics", "max_issues_repo_head_hexsha": "8f0d8ce3229f53fbf4e05cb0273530169e6d9fef", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 265.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T22:46:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:34:29.000Z", "max_forks_repo_path": "test/MockCenterOfMass.hh", "max_forks_repo_name": "diegoferigo/ign-physics", "max_forks_repo_head_hexsha": "8f0d8ce3229f53fbf4e05cb0273530169e6d9fef", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T08:08:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T07:47:34.000Z", "avg_line_length": 31.6138613861, "max_line_length": 75, "alphanum_fraction": 0.650798622, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.17840750836293742}}
{"text": "#ifndef BOOST_METAPARSE_V1_CPP11_NTH_OF_C_HPP\n#define BOOST_METAPARSE_V1_CPP11_NTH_OF_C_HPP\n\n// Copyright Abel Sinkovics (abel@sinkovics.hu)  2017.\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 <boost/metaparse/v1/cpp11/impl/nth_of_c.hpp>\n\n#include <boost/metaparse/v1/fail.hpp>\n#include <boost/metaparse/v1/error/index_out_of_range.hpp>\n\n#include <type_traits>\n\nnamespace boost\n{\n  namespace metaparse\n  {\n    namespace v1\n    {\n      template <int N, class... Ps>\n      struct nth_of_c\n      {\n        typedef nth_of_c type;\n\n        template <class S, class Pos>\n        struct apply :\n          std::conditional<\n            (0 <= N && N < sizeof...(Ps)),\n            impl::nth_of_c<N, S, Pos, Ps...>,\n            typename fail<error::index_out_of_range<0, sizeof...(Ps) - 1, N>>\n              ::template apply<S, Pos>\n          >::type\n        {};\n      };\n\n      template <int N>\n      struct nth_of_c<N> : fail<error::index_out_of_range<0, -1, N>> {};\n    }\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "c8cc51dc93cd15c8b6c64509d0a66e0b83f9491b", "size": 1112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/metaparse/v1/cpp11/nth_of_c.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/metaparse/v1/cpp11/nth_of_c.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/metaparse/v1/cpp11/nth_of_c.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": 24.1739130435, "max_line_length": 77, "alphanum_fraction": 0.6169064748, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.17840749797325814}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ 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 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#ifndef bempp_grid_function_hpp\n#define bempp_grid_function_hpp\n\n#include \"../common/common.hpp\"\n\n#include \"../common/armadillo_fwd.hpp\"\n#include \"../common/deprecated.hpp\"\n#include \"../common/shared_ptr.hpp\"\n\n#include \"../grid/vtk_writer.hpp\"\n#include \"../fiber/quadrature_strategy.hpp\"\n#include \"../fiber/scalar_traits.hpp\"\n\n#include <boost/mpl/set.hpp>\n#include <boost/mpl/has_key.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <memory>\n\nnamespace Fiber\n{\n\n/** \\cond FORWARD_DECL */\ntemplate <typename ValueType> class Basis;\ntemplate <typename ResultType> class LocalAssemblerForGridFunctions;\ntemplate <typename ValueType> class Function;\n/** \\endcond */\n\n} // namespace Fiber\n\nnamespace Bempp\n{\n\n/** \\cond FORWARD_DECL */\nclass AssemblyOptions;\nclass GeometryFactory;\nclass Grid;\ntemplate <int codim> class Entity;\ntemplate <typename BasisFunctionType> class Space;\ntemplate <typename BasisFunctionType, typename ResultType> class Context;\n/** \\endcond */\n\nusing Fiber::Function;\n\n/** \\ingroup assembly_functions\n *  \\brief Function defined on a grid.\n *\n *  This class represents a function defined on a grid and expanded in a\n *  particular function space. */\ntemplate <typename BasisFunctionType, typename ResultType>\nclass GridFunction\n{\npublic:\n    typedef typename Fiber::ScalarTraits<ResultType>::RealType CoordinateType;\n    typedef typename Fiber::ScalarTraits<ResultType>::RealType MagnitudeType;\n\n    enum DataType { COEFFICIENTS, PROJECTIONS };\n\n    // Recommended constructors\n\n    /** \\brief Constructor.\n     *\n     *  Construct an uninitialized grid function. The only way to\n     *  initialize it later is using the assignment operator. */\n    GridFunction();\n\n    /** Constructor.\n     *\n     *  \\param[in] context      Assembly context from which a quadrature\n     *                          strategy can be retrieved.\n     *  \\param[in] space        Function space to expand the grid function in.\n     *  \\param[in] coefficients\n     *    %Vector of length <tt>space.globalDofCount()</tt> containing the expansion\n     *    coefficients of the grid function in the space \\p space.\n     *\n     *  This constructor builds a grid function from its coefficients in a\n     *  function space.\n     */\n    GridFunction(const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n                 const shared_ptr<const Space<BasisFunctionType> >& space,\n                 const arma::Col<ResultType>& coefficients);\n\n    /** Constructor.\n     *\n     *  \\param[in] context      Assembly context from which a quadrature\n     *                          strategy can be retrieved.\n     *  \\param[in] space        Function space to expand the grid function in.\n     *  \\param[in] dualSpace    Function space dual to \\p space.\n     *  \\param[in] projections\n     *    %Vector of length <tt>dualSpace.globalDofCount()</tt> containing the\n     *    scalar products of the grid function and the basis functions of the\n     *    space \\p dualSpace.\n     *\n     *  This constructor builds a grid function expanded in the basis of the\n     *  space \\p space from the projections of this function on the basis\n     *  functions of another space \\p dualSpace. Both spaces must be defined on\n     *  the same grid. */\n    GridFunction(const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n                 const shared_ptr<const Space<BasisFunctionType> >& space,\n                 const shared_ptr<const Space<BasisFunctionType> >& dualSpace,\n                 const arma::Col<ResultType>& projections);\n\n    /** \\brief Constructor.\n     *\n     *  \\param[in] context      Assembly context from which a quadrature\n     *                          strategy can be retrieved.\n     *  \\param[in] space        Function space to expand the grid function in.\n     *  \\param[in] dualSpace    Function space dual to \\p space.\n     *  \\param[in] function     Function object whose values on\n     *                          <tt>space.grid()</tt> will be used to construct\n     *                          the new grid function.\n     *\n     *  This constructor builds a grid function belonging to the space\n     *  \\p space and approximating the function \\f$f\\f$ defined by the\n     *  object \\p function. The approximate coefficients \\f$\\{f_i\\}\\f$\n     *  of \\p function in the basis \\f$\\{\\phi_i\\}\\f$ of \\p space are\n     *  determined by solving the equation\n     *  \\f[ \\sum_j \\langle \\psi_i, \\phi_j \\rangle f_i =\n     *      \\langle \\psi_i, f \\rangle \\f]\n     *  in the least-squares sense, with \\f$\\{\\psi_i\\}\\f$ denoting the\n     *  set of basis functions of \\p dualSpace. The two spaces must be\n     *  defined on the same grid. */\n    GridFunction(const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n                 const shared_ptr<const Space<BasisFunctionType> >& space,\n                 const shared_ptr<const Space<BasisFunctionType> >& dualSpace,\n                 const Function<ResultType>& function);\n\n    // Deprecated constructors\n\n    /** \\brief Constructor.\n     *\n     *  \\param[in] context      Assembly context from which a quadrature\n     *                          strategy can be retrieved.\n     *  \\param[in] space        Function space to expand the grid function in.\n     *  \\param[in] dualSpace    Function space dual to \\p space.\n     *  \\param[in] data\n     *    If <tt>dataType == COEFFICIENTS</tt>, the vector \\p data should have\n     *    length <tt>space.globalDofCount()</tt> and contain the expansion\n     *    coefficients of the grid function in the space \\p space. Otherwise,\n     *    if <tt>dataType == PROJECTIONS</tt>, \\p data should have length\n     *    <tt>dualSpace.globalDofCount()</tt> contain the scalar products of\n     *    the grid function and the basis functions of the space \\p dualSpace.\n     *  \\param[in] dataType     Interpretation of the vector\n     *                          passed via the argument \\p data.\n     *\n     *  This constructor builds a grid function from either its coefficients in\n     *  a function space or from its projections on the basis functions of\n     *  another (dual) function space. If the other type of data turns out to\n     *  be needed later (for example, the projections vector if coefficients\n     *  were supplied in the constructor), it is calculated automatically. The\n     *  Context object given in the constructor is then used to determine the\n     *  strategy for evaluating any necessary integrals.\n     *\n     *  \\p space and \\p dualSpace must be defined on the same grid.\n     *\n     *  \\deprecated This constructor is deprecated. In new code, use one of\n     *  the other constructors. */\n    BEMPP_DEPRECATED\n    GridFunction(const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n                 const shared_ptr<const Space<BasisFunctionType> >& space,\n                 const shared_ptr<const Space<BasisFunctionType> >& dualSpace,\n                 const arma::Col<ResultType>& data,\n                 DataType dataType);\n\n    /** \\brief Constructor.\n     *\n     *  \\param[in] context      Assembly context from which a quadrature\n     *                          strategy can be retrieved.\n     *  \\param[in] space        Function space to expand the grid function in.\n     *  \\param[in] dualSpace    Function space dual to \\p space.\n     *  \\param[in] coefficients %Vector of length <tt>space.globalDofCount()</tt>\n     *                          containing the expansion coefficients of the grid\n     *                          function in the space \\p space.\n     *  \\param[in] projections  %Vector of length <tt>dualSpace.globalDofCount()</tt>\n     *                          containing the scalar products of the grid\n     *                          function and the basis functions of the space\n     *                          \\p dualSpace.\n     *\n     *  \\p space and \\p dualSpace must be defined on the same grid.\n     *\n     *  \\deprecated This constructor is deprecated. In new code, use one of\n     *  the other constructors. */\n    BEMPP_DEPRECATED\n    GridFunction(const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n                 const shared_ptr<const Space<BasisFunctionType> >& space,\n                 const shared_ptr<const Space<BasisFunctionType> >& dualSpace,\n                 const arma::Col<ResultType>& coefficients,\n                 const arma::Col<ResultType>& projections);\n\n    // Member functions\n\n    /** \\brief Return whether this function has been properly initialized. */\n    bool isInitialized() const;\n\n    /** \\brief Grid on which this function is defined.\n     *\n     * \\note An exception is thrown if this function is called on an\n     * uninitialized GridFunction object. */\n    shared_ptr<const Grid> grid() const;\n\n    /** \\brief Space in which this function is expanded. */\n    shared_ptr<const Space<BasisFunctionType> > space() const;\n\n    /** \\brief Space dual to the space in which this function is expanded.\n     *\n     *  \\deprecated This function is provided only for backward compatibility\n     *  reasons. It returns the shared pointer to the dual space of the\n     *  GridFunction, if one was supplied during the construction of the\n     *  latter, or a null pointer otherwise. */\n    shared_ptr<const Space<BasisFunctionType> > dualSpace() const;\n\n    /** \\brief Assembly context used to retrieve the strategy for evaluating\n     *  any necessary integrals. */\n    shared_ptr<const Context<BasisFunctionType, ResultType> > context() const;\n\n    /** \\brief Number of components of this function.\n     *\n     * \\note An exception is thrown if this function is called on an\n     * uninitialized GridFunction object. */\n    int componentCount() const;\n\n    /** \\brief %Vector of expansion coefficients of this function in the basis\n     *  of its expansion space.\n     *\n     *  An exception is thrown if this function is called on an uninitialized\n     *  GridFunction object (one constructed with the default constructor). */\n    const arma::Col<ResultType>& coefficients() const;\n\n    /** \\brief %Vector of scalar products of this function with the basis\n     *  functions of \\p dualSpace.\n     *\n     *  \\p dualSpace must be defined on the same grid as the space in which the\n     *  GridFunction is expanded.\n     *\n     *  An exception is thrown if this function is called on an uninitialized\n     *  GridFunction object (one constructed with the default constructor). */\n    arma::Col<ResultType> projections(\n            const Space<BasisFunctionType>& dualSpace_) const;\n\n    /** \\brief %Vector of scalar products of this function with the basis\n     *  functions of its dual space.\n     *\n     *  \\deprecated This function is provided only for backward compatibility\n     *  purposes. It works only if the dual space was specified during the\n     *  construction of the GridFunction. In new code the other overload of\n     *  projections() should be used.\n     *\n     *  An exception is thrown if this function is called on an uninitialized\n     *  GridFunction object (one constructed with the default constructor). */\n    BEMPP_DEPRECATED arma::Col<ResultType> projections() const;\n\n    /** \\brief Reset the expansion coefficients of this function in the basis\n     *  of its primal space.\n     *\n     *  As a side effect, any internally stored vector of the projections of\n     *  this grid function on the basis functions of its dual space is marked as\n     *  invalid and recalculated on the next call to projections(). */\n    void setCoefficients(const arma::Col<ResultType>& coeffs);\n\n    /** \\brief Reinitialize the function by specifying the vector of its scalar\n     *  products with the basis functions of \\p dualSpace.\n     *\n     *  \\p dualSpace must be defined on the same grid as the space in which the\n     *  GridFunction is expanded. */\n    void setProjections(\n            const Space<BasisFunctionType>& dualSpace_,\n            const arma::Col<ResultType>& projects);\n\n    /** \\brief Reset the vector of scalar products of this function with the\n     *  basis functions of its dual space.\n     *\n     *  \\deprecated This function is provided only for backward compatibility\n     *  purposes. It works only if the dual space was specified during the\n     *  construction of the GridFunction. In new code the other overload of\n     *  setProjections() should be used. */\n    BEMPP_DEPRECATED void setProjections(const arma::Col<ResultType>& projects);\n\n    /** \\brief Return the \\f$L^2\\f$-norm of the grid function.\n     *\n     *  \\note For better accuracy, prefer to use L2NormOfDifference() or\n     *  estimateL2Error() to calculate the norm of the difference between a grid\n     *  function and a function defined by an analytical expression.\n     */\n    MagnitudeType L2Norm() const;\n\n    const Fiber::Basis<BasisFunctionType>& basis(const Entity<0>& element) const;\n\n    /** \\brief Retrieve the expansion coefficients of this function on a single element.\n     *\n     *  \\param[in] element An element belonging to the grid <tt>space.grid()</tt>.\n     *  \\param[out] coeffs %Vector of the expansion coefficients of this function\n     *                     corresponding to the basis functions of the primal space\n     *                     living on element \\p element.\n     *\n     *  \\note The results of calling this function on an uninitialized\n     *  GridFunction object are undefined. */\n    void getLocalCoefficients(const Entity<0>& element,\n                              std::vector<ResultType>& coeffs) const;\n\n    /** \\brief Export this function to a VTK file.\n\n      \\param[in] dataType\n        Determines whether data are attaches to vertices or cells.\n\n      \\param[in] dataLabel\n        Label used to identify the function in the VTK file.\n\n      \\param[in] fileNamesBase\n        Base name of the output files. It should not contain any directory\n        part or filename extensions.\n\n      \\param[in] filesPath\n        Output directory. Can be set to NULL, in which case the files are\n        output in the current directory.\n\n      \\param[in] type\n        Output type (default: ASCII). See Dune reference manual for more\n        details.\n\n      \\note An exception is thrown if this function is called on an\n        uninitialized GridFunction object. */\n    void exportToVtk(VtkWriter::DataType dataType,\n                     const char* dataLabel,\n                     const char* fileNamesBase, const char* filesPath = 0,\n                     VtkWriter::OutputType type = VtkWriter::ASCII) const;\n\n    /** \\brief Evaluate function at either vertices or barycentres.\n     *\n     *  \\note The results of calling this function on an uninitialized\n     *  GridFunction object are undefined. */\n    void evaluateAtSpecialPoints(\n            VtkWriter::DataType dataType, arma::Mat<ResultType>& result_) const;\n    void evaluateAtSpecialPoints(\n            VtkWriter::DataType dataType,\n            arma::Mat<CoordinateType>& points, arma::Mat<ResultType>& values) const;\n\nprivate:\n    void initializeFromCoefficients(\n            const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n            const shared_ptr<const Space<BasisFunctionType> >& space,\n            const arma::Col<ResultType>& coefficients);\n    void initializeFromProjections(\n            const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n            const shared_ptr<const Space<BasisFunctionType> >& space,\n            const shared_ptr<const Space<BasisFunctionType> >& dualSpace,\n            const arma::Col<ResultType>& projections);\n\nprivate:\n    shared_ptr<const Context<BasisFunctionType, ResultType> > m_context;\n    shared_ptr<const Space<BasisFunctionType> > m_space;\n    shared_ptr<const Space<BasisFunctionType> > m_dualSpace;\n    mutable shared_ptr<const arma::Col<ResultType> > m_coefficients;\n    // mutable shared_ptr<const arma::Col<ResultType> > m_projections;\n};\n\n// Overloaded operators\n\n/** \\brief Return a copy of the passed function \\p g. */\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType> operator+(\n        const GridFunction<BasisFunctionType, ResultType>& g);\n\n/** \\brief Return the grid function representing the function \\p g\n *  multipled by -1.\n *\n *  \\note An exception is thrown if \\p g is uninitialized. */\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType> operator-(\n        const GridFunction<BasisFunctionType, ResultType>& g);\n\n/** \\brief Return a grid function representing the sum of the operands.\n *\n *  \\note Both operands must be initialized and their primal and dual\n *  spaces must be identical, otherwise an exception is thrown. */\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType> operator+(\n        const GridFunction<BasisFunctionType, ResultType>& g1,\n        const GridFunction<BasisFunctionType, ResultType>& g2);\n\n/** \\brief Return a grid function representing the difference of the operands.\n *\n *  \\note Both operands must be initialized and their primal and dual\n *  spaces must be identical, otherwise an exception is thrown. */\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType> operator-(\n        const GridFunction<BasisFunctionType, ResultType>& g1,\n        const GridFunction<BasisFunctionType, ResultType>& g2);\n\n/** \\brief Return the grid function representing the function \\p g\n *  multiplied by \\p scalar.\n *\n *  \\note An exception is thrown if \\p g is uninitialized. */\ntemplate <typename BasisFunctionType, typename ResultType, typename ScalarType>\nGridFunction<BasisFunctionType, ResultType> operator*(\n        const GridFunction<BasisFunctionType, ResultType>& g, const ScalarType& scalar);\n\n// This type machinery is needed to disambiguate between this operator and\n// the one taking a AbstractBoundaryOperator and a GridFunction\n/** \\brief Return the grid function representing the function \\p g\n *  multiplied by \\p scalar.\n *\n *  \\note An exception is thrown if \\p g is uninitialized. */\ntemplate <typename BasisFunctionType, typename ResultType, typename ScalarType>\ntypename boost::enable_if<\n    typename boost::mpl::has_key<\n        boost::mpl::set<float, double, std::complex<float>, std::complex<double> >,\n        ScalarType>,\n    GridFunction<BasisFunctionType, ResultType> >::type\noperator*(\n        const ScalarType& scalar, const GridFunction<BasisFunctionType, ResultType>& g);\n\n/** \\brief Return the grid function representing the function \\p g\n *  divided by \\p scalar.\n *\n *  \\note An exception is thrown if \\p g is uninitialized. */\ntemplate <typename BasisFunctionType, typename ResultType, typename ScalarType>\nGridFunction<BasisFunctionType, ResultType> operator/(\n        const GridFunction<BasisFunctionType, ResultType>& g1, const ScalarType& scalar);\n\n} // namespace Bempp\n\n#endif\n", "meta": {"hexsha": "36ca95ad0d7dda241802b2fb74aa8c658abf58c5", "size": 20028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/grid_function.hpp", "max_stars_repo_name": "UCL/bempp", "max_stars_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T13:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T13:35:20.000Z", "max_issues_repo_path": "lib/assembly/grid_function.hpp", "max_issues_repo_name": "UCL/bempp", "max_issues_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "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": "lib/assembly/grid_function.hpp", "max_forks_repo_name": "UCL/bempp", "max_forks_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "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.2099322799, "max_line_length": 90, "alphanum_fraction": 0.6828440184, "num_tokens": 4412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17827365876364862}}
{"text": "#include <wx/wx.h>\r\n#include <wx/progdlg.h>\r\n#include <wx/filedlg.h>\r\n#include <wx/textdlg.h>\r\n#include \"passcrypt.h\"\r\n\r\n#include <string>\r\n#include <cctype>\r\n\r\n#include <boost/filesystem/fstream.hpp>\r\n\r\n#include <cryptopp/serpent.h>\r\n#include <cryptopp/files.h>\r\n#include <cryptopp/modes.h>\r\n#include <cryptopp/sha.h>\r\n#include <cryptopp/gzip.h>\r\n\r\nIMPLEMENT_APP_NO_MAIN(wxApp)\r\n\r\nint main(int argc,char*argv[])\r\n{\r\n    //std::cout << \"Hello World!\" << std::endl;\r\n    wxEntryStart(argc,argv);\r\n    {\r\n\r\n\r\n        wxFileDialog objFileDlg(NULL,wxT(\"nxCrypt File Selection\"));\r\n        objFileDlg.Centre();\r\n        objFileDlg.ShowModal();\r\n\r\n        std::wstring strFName(objFileDlg.GetFilename().wc_str());\r\n        std::wstring strInFile(std::wstring(objFileDlg.GetDirectory().wc_str()) + L\"/\" + strFName);\r\n        bool bEncrypt=true;\r\n        if (!strFName.empty())\r\n        {\r\n            if (strFName.size() > 4)\r\n            {\r\n                const wchar_t *ptExtension = strInFile.c_str()+strInFile.size()-4;\r\n                if (    (               ptExtension[0]  == L'.') &&\r\n                        (std::tolower(  ptExtension[1]) == L'n') &&\r\n                        (std::tolower(  ptExtension[2]) == L'x') &&\r\n                        (std::tolower(  ptExtension[3]) == L'z') )\r\n                        bEncrypt=false;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            return 0;\r\n        }\r\n        std::wstring strOutFile;\r\n        if (bEncrypt)\r\n            strOutFile = strInFile+L\".nxz\";\r\n        else\r\n            strOutFile = strInFile.substr(0,strInFile.size()-4);\r\n\r\n        boost::filesystem::ifstream ifs(strInFile,std::ios::binary);\r\n        boost::filesystem::ofstream ofs(strOutFile,std::ios::binary|std::ios::out);\r\n        if (!ifs)\r\n        {\r\n            wxMessageBox(wxT(\"Error opening the input file\"));\r\n            wxMessageBox(strInFile.c_str());\r\n            return 1;\r\n        }\r\n        if (!ofs)\r\n        {\r\n            wxMessageBox(wxT(\"Error opening the output file\"));\r\n            wxMessageBox(strOutFile.c_str());\r\n            return 1;\r\n        }\r\n\r\n        std::wstring strPassword;\r\n\r\n        while (true)\r\n        {\r\n            {\r\n                wxPasswordEntryDialog objPassword(NULL,wxT(\"Enter the password\"),wxT(\"nxCrypt Password Entry\"));\r\n                objPassword.Centre();\r\n                if (objPassword.ShowModal() != wxID_OK)\r\n                    return 2;\r\n                strPassword = objPassword.GetValue().wc_str();\r\n            }\r\n\r\n            {\r\n                wxPasswordEntryDialog objPassword(NULL,wxT(\"Confirm the password\"),wxT(\"nxCrypt Password Confirmation\"));\r\n                objPassword.Centre();\r\n                if (objPassword.ShowModal() != wxID_OK)\r\n                    continue;\r\n                if (strPassword != objPassword.GetValue().wc_str())\r\n                {\r\n                    wxMessageBox(wxT(\"ERROR: Passwords didn't match\"),wxT(\"nxCrypt - Error\"));\r\n                    continue;\r\n                }\r\n            }\r\n            break;\r\n        }\r\n\r\n        typedef CryptoPP::SHA512 HashType;\r\n        typedef CryptoPP::CBC_Mode<CryptoPP::Serpent> CryptType;\r\n        try\r\n        {\r\n            CryptoPP::member_ptr<CryptoPP::FileSource> ptFileCrypt;\r\n            boost::uintmax_t uFileBlock = boost::filesystem::file_size(strInFile)/100;\r\n            if (!uFileBlock) ++uFileBlock;\r\n            int uProgress=0;\r\n\r\n            if (bEncrypt)\r\n                ptFileCrypt.reset(new CryptoPP::FileSource( ifs, false,\r\n                    new CryptoPP::Gzip(\r\n                        new CryptoPP::PassphrasedEncrypt<HashType,CryptType>((byte*)strPassword.c_str(),strPassword.size()*sizeof(wchar_t),\r\n                                new CryptoPP::FileSink(\r\n                                    ofs\r\n                                )\r\n                        ),\r\n                        CryptoPP::Gzip::MAX_DEFLATE_LEVEL\r\n                    )\r\n                ));\r\n            else\r\n                ptFileCrypt.reset(new CryptoPP::FileSource( ifs, false,\r\n                    new CryptoPP::PassphrasedDecrypt<HashType,CryptType>((byte*)strPassword.c_str(),strPassword.size()*sizeof(wchar_t),\r\n                        new CryptoPP::Gunzip(\r\n                                new CryptoPP::FileSink(\r\n                                    ofs\r\n                                )\r\n                        )\r\n                    )\r\n                ));\r\n            //ptFileCrypt->PumpAll();\r\n            wxProgressDialog objProgress((bEncrypt?wxT(\"nxCrypt - Encryption\"):wxT(\"nxCrypt - Decryption\")),wxT(\"Processing file...\"),100,NULL,wxPD_AUTO_HIDE|wxPD_SMOOTH|wxPD_REMAINING_TIME|wxPD_ELAPSED_TIME);\r\n            while (ptFileCrypt->Pump(uFileBlock))\r\n            {\r\n                if (uProgress < 99)\r\n                    objProgress.Update(++uProgress);\r\n                else\r\n                {\r\n                    ptFileCrypt->PumpAll();\r\n                    objProgress.Update(100);\r\n                    break;\r\n                }\r\n            }\r\n            wxMessageBox(wxT(\"Operation successful!\"));\r\n        } catch (...)\r\n        {\r\n            wxMessageBox(wxT(\"Error performing operation.\"));\r\n        }\r\n    }\r\n    wxEntryCleanup();\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "2de5cf0ff07313c0db3f538e4821a3cd54521514", "size": 5271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nxCrypt/main.cpp", "max_stars_repo_name": "nacitar/old-projects", "max_stars_repo_head_hexsha": "e5af376f868124b9828196df1f55adb682969f3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-05-04T04:22:42.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-04T04:22:42.000Z", "max_issues_repo_path": "nxCrypt/main.cpp", "max_issues_repo_name": "nacitar/old-projects", "max_issues_repo_head_hexsha": "e5af376f868124b9828196df1f55adb682969f3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nxCrypt/main.cpp", "max_forks_repo_name": "nacitar/old-projects", "max_forks_repo_head_hexsha": "e5af376f868124b9828196df1f55adb682969f3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-05-04T04:23:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-30T22:32:43.000Z", "avg_line_length": 35.3758389262, "max_line_length": 210, "alphanum_fraction": 0.4833997344, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17827365374094342}}
{"text": "#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <tr1/unordered_map>\n\n#include <boost/functional/hash.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"sampler.h\"\n#include \"filelib.h\"\n#include \"stringlib.h\"\n#include \"weights.h\"\n#include \"scorer.h\"\n#include \"inside_outside.h\"\n#include \"hg_io.h\"\n#include \"kbest.h\"\n#include \"viterbi.h\"\n\n// This is Figure 4 (Algorithm Sampler) from Hopkins&May (2011)\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nstruct ApproxVectorHasher {\n  static const size_t MASK = 0xFFFFFFFFull;\n  union UType {\n    double f;\n    size_t i;\n  };\n  static inline double round(const double x) {\n    UType t;\n    t.f = x;\n    size_t r = t.i & MASK;\n    if ((r << 1) > MASK)\n      t.i += MASK - r + 1;\n    else\n      t.i &= (1ull - MASK);\n    return t.f;\n  }\n  size_t operator()(const SparseVector<double>& x) const {\n    size_t h = 0x573915839;\n    for (SparseVector<double>::const_iterator it = x.begin(); it != x.end(); ++it) {\n      UType t;\n      t.f = it->second;\n      if (t.f) {\n        size_t z = (t.i >> 32);\n        boost::hash_combine(h, it->first);\n        boost::hash_combine(h, z);\n      }\n    }\n    return h;\n  }\n};\n\nstruct ApproxVectorEquals {\n  bool operator()(const SparseVector<double>& a, const SparseVector<double>& b) const {\n    SparseVector<double>::const_iterator bit = b.begin();\n    for (SparseVector<double>::const_iterator ait = a.begin(); ait != a.end(); ++ait) {\n      if (bit == b.end() ||\n          ait->first != bit->first ||\n          ApproxVectorHasher::round(ait->second) != ApproxVectorHasher::round(bit->second))\n        return false;\n      ++bit;\n    }\n    if (bit != b.end()) return false;\n    return true;\n  }\n};\n\nboost::shared_ptr<MT19937> rng;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"reference,r\",po::value<vector<string> >(), \"[REQD] Reference translation (tokenized text)\")\n        (\"weights,w\",po::value<string>(), \"[REQD] Weights files from current iterations\")\n        (\"kbest_repository,K\",po::value<string>()->default_value(\"./kbest\"),\"K-best list repository (directory)\")\n        (\"input,i\",po::value<string>()->default_value(\"-\"), \"Input file to map (- is STDIN)\")\n        (\"source,s\",po::value<string>()->default_value(\"\"), \"Source file (ignored, except for AER)\")\n        (\"loss_function,l\",po::value<string>()->default_value(\"ibm_bleu\"), \"Loss function being optimized\")\n        (\"kbest_size,k\",po::value<unsigned>()->default_value(1500u), \"Top k-hypotheses to extract\")\n        (\"candidate_pairs,G\", po::value<unsigned>()->default_value(5000u), \"Number of pairs to sample per hypothesis (Gamma)\")\n        (\"best_pairs,X\", po::value<unsigned>()->default_value(50u), \"Number of pairs, ranked by magnitude of objective delta, to retain (Xi)\")\n        (\"random_seed,S\", po::value<uint32_t>(), \"Random seed (if not specified, /dev/random will be used)\")\n        (\"help,h\", \"Help\");\n  po::options_description dcmdline_options;\n  dcmdline_options.add(opts);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  bool flag = false;\n  if (!conf->count(\"reference\")) {\n    cerr << \"Please specify one or more references using -r <REF.TXT>\\n\";\n    flag = true;\n  }\n  if (!conf->count(\"weights\")) {\n    cerr << \"Please specify weights using -w <WEIGHTS.TXT>\\n\";\n    flag = true;\n  }\n  if (flag || conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nstruct HypInfo {\n  HypInfo() : g_(-100.0) {}\n  HypInfo(const vector<WordID>& h, const SparseVector<double>& feats) : hyp(h), g_(-100.0), x(feats) {}\n\n  // lazy evaluation\n  double g(const SentenceScorer& scorer) const {\n    if (g_ == -100.0)\n      g_ = scorer.ScoreCandidate(hyp)->ComputeScore();\n    return g_;\n  }\n  vector<WordID> hyp;\n  mutable double g_;\n  SparseVector<double> x;\n};\n\nstruct HypInfoCompare {\n  bool operator()(const HypInfo& a, const HypInfo& b) const {\n    ApproxVectorEquals comp;\n    return (a.hyp == b.hyp && comp(a.x,b.x));\n  }\n};\n\nstruct HypInfoHasher {\n  size_t operator()(const HypInfo& x) const {\n    boost::hash<vector<WordID> > hhasher;\n    ApproxVectorHasher vhasher;\n    size_t ha = hhasher(x.hyp);\n    boost::hash_combine(ha, vhasher(x.x));\n    return ha;\n  }\n};\n\nvoid WriteKBest(const string& file, const vector<HypInfo>& kbest) {\n  WriteFile wf(file);\n  ostream& out = *wf.stream();\n  out.precision(10);\n  for (int i = 0; i < kbest.size(); ++i) {\n    out << TD::GetString(kbest[i].hyp) << endl;\n    out << kbest[i].x << endl;\n  }\n}\n\nvoid ParseSparseVector(string& line, size_t cur, SparseVector<double>* out) {\n  SparseVector<double>& x = *out;\n  size_t last_start = cur;\n  size_t last_comma = string::npos;\n  while(cur <= line.size()) {\n    if (line[cur] == ' ' || cur == line.size()) {\n      if (!(cur > last_start && last_comma != string::npos && cur > last_comma)) {\n        cerr << \"[ERROR] \" << line << endl << \"  position = \" << cur << endl;\n        exit(1);\n      }\n      const int fid = FD::Convert(line.substr(last_start, last_comma - last_start));\n      if (cur < line.size()) line[cur] = 0;\n      const double val = strtod(&line[last_comma + 1], NULL);\n      x.set_value(fid, val);\n\n      last_comma = string::npos;\n      last_start = cur+1;\n    } else {\n      if (line[cur] == '=')\n        last_comma = cur;\n    }\n    ++cur;\n  }\n}\n\nvoid ReadKBest(const string& file, vector<HypInfo>* kbest) {\n  //cerr << \"Reading from \" << file << endl;\n  ReadFile rf(file);\n  istream& in = *rf.stream();\n  string cand;\n  string feats;\n  while(getline(in, cand)) {\n    getline(in, feats);\n    assert(in);\n    kbest->push_back(HypInfo());\n    TD::ConvertSentence(cand, &kbest->back().hyp);\n    ParseSparseVector(feats, 0, &kbest->back().x);\n  }\n  //cerr << \"  read \" << kbest->size() << \" hypotheses\\n\";\n}\n\nvoid Dedup(vector<HypInfo>* h) {\n  // cerr << \"Dedup in=\" << h->size();\n  tr1::unordered_set<HypInfo, HypInfoHasher, HypInfoCompare> u;\n  while(h->size() > 0) {\n    u.insert(h->back());\n    h->pop_back();\n  }\n  tr1::unordered_set<HypInfo, HypInfoHasher, HypInfoCompare>::iterator it = u.begin();\n  while (it != u.end()) {\n    h->push_back(*it);\n    it = u.erase(it);\n  }\n  //cerr << \"  out=\" << h->size() << endl;\n}\n\nstruct ThresholdAlpha {\n  explicit ThresholdAlpha(double t = 0.05) : threshold(t) {}\n  double operator()(double mag) const {\n    if (mag < threshold) return 0.0; else return 1.0;\n  }\n  const double threshold;\n};\n\nstruct TrainingInstance {\n  TrainingInstance(const SparseVector<double>& feats, bool positive, double diff) : x(feats), y(positive), gdiff(diff) {}\n  SparseVector<double> x;\n#undef DEBUGGING_PRO\n#ifdef DEBUGGING_PRO\n  vector<WordID> a;\n  vector<WordID> b;\n#endif\n  bool y;\n  double gdiff;\n};\n#ifdef DEBUGGING_PRO\nostream& operator<<(ostream& os, const TrainingInstance& d) {\n  return os << d.gdiff << \" y=\" << d.y << \"\\tA:\" << TD::GetString(d.a) << \"\\n\\tB: \" << TD::GetString(d.b) << \"\\n\\tX: \" << d.x;\n}\n#endif\n\nstruct DiffOrder {\n  bool operator()(const TrainingInstance& a, const TrainingInstance& b) const {\n    return a.gdiff > b.gdiff;\n  }\n};\n\nvoid Sample(const unsigned gamma, const unsigned xi, const vector<HypInfo>& J_i, const SentenceScorer& scorer, const bool invert_score, vector<TrainingInstance>* pv) {\n  vector<TrainingInstance> v1, v2;\n  double avg_diff = 0;\n  for (unsigned i = 0; i < gamma; ++i) {\n    const size_t a = rng->inclusive(0, J_i.size() - 1)();\n    const size_t b = rng->inclusive(0, J_i.size() - 1)();\n    if (a == b) continue;\n    double ga = J_i[a].g(scorer);\n    double gb = J_i[b].g(scorer);\n    bool positive = gb < ga;\n    if (invert_score) positive = !positive;\n    const double gdiff = fabs(ga - gb);\n    if (!gdiff) continue;\n    avg_diff += gdiff;\n    SparseVector<double> xdiff = (J_i[a].x - J_i[b].x).erase_zeros();\n    if (xdiff.empty()) {\n      cerr << \"Empty diff:\\n  \" << TD::GetString(J_i[a].hyp) << endl << \"x=\" << J_i[a].x << endl;\n      cerr << \"  \" << TD::GetString(J_i[b].hyp) << endl << \"x=\" << J_i[b].x << endl;\n      continue;\n    }\n    v1.push_back(TrainingInstance(xdiff, positive, gdiff));\n#ifdef DEBUGGING_PRO\n    v1.back().a = J_i[a].hyp;\n    v1.back().b = J_i[b].hyp;\n    cerr << \"N: \" << v1.back() << endl;\n#endif\n  }\n  avg_diff /= v1.size();\n\n  for (unsigned i = 0; i < v1.size(); ++i) {\n    double p = 1.0 / (1.0 + exp(-avg_diff - v1[i].gdiff));\n    // cerr << \"avg_diff=\" << avg_diff << \"  gdiff=\" << v1[i].gdiff << \"  p=\" << p << endl;\n    if (rng->next() < p) v2.push_back(v1[i]);\n  }\n  vector<TrainingInstance>::iterator mid = v2.begin() + xi;\n  if (xi > v2.size()) mid = v2.end();\n  partial_sort(v2.begin(), mid, v2.end(), DiffOrder());\n  copy(v2.begin(), mid, back_inserter(*pv));\n#ifdef DEBUGGING_PRO\n  if (v2.size() >= 5) {\n    for (int i =0; i < (mid - v2.begin()); ++i) {\n      cerr << v2[i] << endl;\n    }\n    cerr << pv->back() << endl;\n  }\n#endif\n}\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  if (conf.count(\"random_seed\"))\n    rng.reset(new MT19937(conf[\"random_seed\"].as<uint32_t>()));\n  else\n    rng.reset(new MT19937);\n  const string loss_function = conf[\"loss_function\"].as<string>();\n\n  ScoreType type = ScoreTypeFromString(loss_function);\n  DocScorer ds(type, conf[\"reference\"].as<vector<string> >(), conf[\"source\"].as<string>());\n  cerr << \"Loaded \" << ds.size() << \" references for scoring with \" << loss_function << endl;\n  Hypergraph hg;\n  string last_file;\n  ReadFile in_read(conf[\"input\"].as<string>());\n  istream &in=*in_read.stream();\n  const unsigned kbest_size = conf[\"kbest_size\"].as<unsigned>();\n  const unsigned gamma = conf[\"candidate_pairs\"].as<unsigned>();\n  const unsigned xi = conf[\"best_pairs\"].as<unsigned>();\n  string weightsf = conf[\"weights\"].as<string>();\n  vector<double> weights;\n  {\n    Weights w;\n    w.InitFromFile(weightsf);\n    w.InitVector(&weights);\n  }\n  string kbest_repo = conf[\"kbest_repository\"].as<string>();\n  MkDirP(kbest_repo);\n  while(in) {\n    vector<TrainingInstance> v;\n    string line;\n    getline(in, line);\n    if (line.empty()) continue;\n    istringstream is(line);\n    int sent_id;\n    string file;\n    // path-to-file (JSON) sent_id\n    is >> file >> sent_id;\n    ReadFile rf(file);\n    ostringstream os;\n    vector<HypInfo> J_i;\n    os << kbest_repo << \"/kbest.\" << sent_id << \".txt.gz\";\n    const string kbest_file = os.str();\n    // read k-best hypotheses from previous iterations\n    if (FileExists(kbest_file))\n      ReadKBest(kbest_file, &J_i);\n    // extract k-best for this iteration\n    HypergraphIO::ReadFromJSON(rf.stream(), &hg);\n    hg.Reweight(weights);\n    KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(hg, kbest_size);\n\n    for (int i = 0; i < kbest_size; ++i) {\n      const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d =\n        kbest.LazyKthBest(hg.nodes_.size() - 1, i);\n      if (!d) break;\n      J_i.push_back(HypInfo(d->yield, d->feature_values));\n    }\n    Dedup(&J_i);\n    WriteKBest(kbest_file, J_i);\n\n    Sample(gamma, xi, J_i, *ds[sent_id], (type == TER), &v);\n    for (unsigned i = 0; i < v.size(); ++i) {\n      const TrainingInstance& vi = v[i];\n      cout << vi.y << \"\\t\" << vi.x << endl;\n      cout << (!vi.y) << \"\\t\" << (vi.x * -1.0) << endl;\n    }\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "1b1ecec9cceed0db2a97ab6624cdcc266346e867", "size": 11430, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pro-train/mr_pro_map.cc", "max_stars_repo_name": "jhclark/cdec", "max_stars_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T00:44:01.000Z", "max_issues_repo_path": "pro-train/mr_pro_map.cc", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "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": "pro-train/mr_pro_map.cc", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "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.2881355932, "max_line_length": 167, "alphanum_fraction": 0.6157480315, "num_tokens": 3326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17827365374094334}}
{"text": "#include <pbcopper/data/FrameEncoders.h>\n\n#include <cassert>\n#include <cmath>\n#include <cstddef>\n#include <cstdint>\n\n#include <algorithm>\n#include <limits>\n\n#include <boost/algorithm/string/join.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n\nnamespace PacBio {\nnamespace Data {\nnamespace {\n\nstatic std::vector<uint16_t> framepoints;\nstatic std::vector<uint8_t> frameToCode;\nstatic uint16_t maxFramepoint;\n\nstatic int InitIpdDownsampling()\n{\n    if (!framepoints.empty()) {\n        return 0;\n    }\n\n    // liftover from kineticsTools\n\n    const int B = 2;\n    const int t = 6;\n    const double T = std::pow(B, t);\n\n    int next = 0;\n    double grain;\n    const int end = 256 / T;\n    for (int i = 0; i < end; ++i) {\n        grain = std::pow(B, i);\n        std::vector<uint16_t> nextOnes;\n        for (double j = 0; j < T; ++j) {\n            nextOnes.push_back(j * grain + next);\n        }\n        next = nextOnes.back() + grain;\n        framepoints.insert(framepoints.end(), nextOnes.cbegin(), nextOnes.cend());\n    }\n    assert(framepoints.size() - 1 <= std::numeric_limits<uint8_t>::max());\n\n    const uint16_t maxElement = (*std::max_element(framepoints.cbegin(), framepoints.cend()));\n    frameToCode.assign(maxElement + 1, 0);\n\n    const int fpEnd = framepoints.size() - 1;\n    uint8_t i = 0;\n    uint16_t fl = 0;\n    uint16_t fu = 0;\n    for (; i < fpEnd; ++i) {\n        fl = framepoints[i];\n        fu = framepoints[i + 1];\n        if (fu > fl + 1) {\n            const int middle = (fl + fu) / 2;\n            for (int f = fl; f < middle; ++f) {\n                frameToCode[f] = i;\n            }\n            for (int f = middle; f < fu; ++f) {\n                frameToCode[f] = i + 1;\n            }\n        } else {\n            frameToCode[fl] = i;\n        }\n    }\n\n    // this next line differs from the python implementation (there, it's \"i+1\")\n    // our C++ for loop has incremented our index counter one more time than the indexes from python enumerate(...)\n    frameToCode[fu] = i;\n    maxFramepoint = fu;\n\n    return 0;\n}\n\nstatic const int initV1Frames = InitIpdDownsampling();\n\n}  // namespace\n\n// ----------------\n// V1 frame codec\n// ----------------\n\nFrames V1FrameEncoder::Decode(const std::vector<uint8_t>& encodedFrames) const\n{\n    std::vector<uint16_t> rawFrames;\n    rawFrames.reserve(encodedFrames.size());\n    std::transform(encodedFrames.cbegin(), encodedFrames.cend(), std::back_inserter(rawFrames),\n                   [&](uint8_t code) { return framepoints[code]; });\n    return rawFrames;\n}\n\nstd::vector<uint8_t> V1FrameEncoder::Encode(const std::vector<uint16_t>& rawFrames) const\n{\n    std::vector<uint8_t> encoded;\n    encoded.reserve(rawFrames.size());\n    std::transform(rawFrames.cbegin(), rawFrames.cend(), std::back_inserter(encoded),\n                   [&](uint16_t frame) { return frameToCode[std::min(maxFramepoint, frame)]; });\n    return encoded;\n}\n\nstd::string V1FrameEncoder::Name() const { return \"CodecV1\"; }\n\n// ----------------\n// V2 frame codec\n// ----------------\n\nV2FrameEncoder::V2FrameEncoder(int exponentBits, int mantissaBits)\n    : exponentBits_{exponentBits}\n    , mantissaBits_{mantissaBits}\n    , base_(std::pow(2, mantissaBits_))\n    , max_((1 << (exponentBits_ + mantissaBits_)) - 1)\n{\n}\n\nFrames V2FrameEncoder::Decode(const std::vector<uint8_t>& encodedFrames) const\n{\n    std::vector<uint16_t> decoded;\n    decoded.reserve(encodedFrames.size());\n    std::transform(encodedFrames.cbegin(), encodedFrames.cend(), std::back_inserter(decoded),\n                   [&](uint8_t x) -> uint16_t {\n                       if (x > max_) {\n                           throw std::runtime_error{\"[pbcopper] invalid frame encoding ERROR: \" +\n                                                    std::to_string(x) + \" is out of range [0,\" +\n                                                    std::to_string(max_) + ']'};\n                       }\n                       const uint8_t mantissa = x & static_cast<uint8_t>((base_ - 1));\n                       const uint8_t exponent = (x ^ mantissa) >> mantissaBits_;\n                       return (base_ * (std::pow(2, exponent) - 1)) +\n                              ((std::pow(2, exponent)) * mantissa);\n                   });\n    return Frames{decoded};\n}\n\nstd::vector<uint8_t> V2FrameEncoder::Encode(const std::vector<uint16_t>& rawFrames) const\n{\n    // NOTE: nothing compressed here yet in output bytes, regardless of bitsPerPulse\n\n    std::vector<uint8_t> encoded;\n    encoded.reserve(rawFrames.size());\n    std::transform(\n        rawFrames.cbegin(), rawFrames.cend(), std::back_inserter(encoded), [&](uint16_t x) {\n            const int exponent = std::log2(x / base_ + 1);\n            const int mantissa =\n                (x - base_ * (static_cast<uint8_t>(std::pow(2, exponent)) - 1)) >> exponent;\n            const uint8_t result = (exponent << mantissaBits_) | mantissa;\n            return std::min(result, max_);\n        });\n    return encoded;\n}\n\nint V2FrameEncoder::MantissaBits() const { return mantissaBits_; }\n\nstd::string V2FrameEncoder::Name() const\n{\n    return \"CodecV2/\" + std::to_string(exponentBits_) + '/' + std::to_string(mantissaBits_);\n}\n\n}  // namespace Data\n}  // namespace PacBio\n", "meta": {"hexsha": "494a342a3e09d27eea327891a9b987f491bace90", "size": 5208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/data/FrameEncoders.cpp", "max_stars_repo_name": "PacificBiosciences/pbcopper", "max_stars_repo_head_hexsha": "ba98ddd79371c2218ca5110d07d5f881c995ff93", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-01-15T13:40:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T18:28:30.000Z", "max_issues_repo_path": "src/data/FrameEncoders.cpp", "max_issues_repo_name": "PacificBiosciences/pbcopper", "max_issues_repo_head_hexsha": "ba98ddd79371c2218ca5110d07d5f881c995ff93", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-09-20T20:25:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-22T19:21:49.000Z", "max_forks_repo_path": "src/data/FrameEncoders.cpp", "max_forks_repo_name": "PacificBiosciences/pbcopper", "max_forks_repo_head_hexsha": "ba98ddd79371c2218ca5110d07d5f881c995ff93", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-05-15T08:47:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T18:38:09.000Z", "avg_line_length": 31.756097561, "max_line_length": 115, "alphanum_fraction": 0.5816052227, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17827365374094334}}
{"text": "#pragma once\n\n#include <vector>\n#include <boost/graph/graph_concepts.hpp>\n#include <caffe/ultinous/ImageClassificationModel.h>\n#include <caffe/ultinous/FeatureMap.hpp>\n#include <caffe/ultinous/AbstractTripletGenerator.hpp>\n#include <caffe/ultinous/FeatureCollectorTripletGenerator.hpp>\n#include \"caffe/proto/caffe.pb.h\"\n\nnamespace caffe {\nnamespace ultinous {\n\ntemplate <typename Dtype>\nclass HardTripletGenerator : public AbstractTripletGenerator\n{\npublic:\n  HardTripletGenerator(HardTripletParameter const &htp, BasicModel const &basicModel)\n    : m_sampler(basicModel)\n    , m_classesInSample(htp.sampledclasses())\n    , m_imagesInSampleClass(htp.sampledpictures())\n    , m_margin(htp.margin())\n    , m_indexInSample(m_classesInSample*m_imagesInSampleClass)\n    , m_featureMap(FeatureMapContainer<Dtype>::instance(htp.featuremapid()))\n    , m_tooHardTriplets(htp.toohardtriplets())\n    , m_hardestPositive(htp.hardestpositive())\n    , m_hardestNegative(htp.hardestnegative())\n    , m_isLastTripletHard(false)\n  {\n    CHECK_GT( m_classesInSample, 0 );\n    CHECK_GT( m_imagesInSampleClass, 0 );\n    ImageSampler::initSample( m_classesInSample, m_imagesInSampleClass, m_sample );\n\n    for( size_t i = 0; i < m_classesInSample*m_imagesInSampleClass; ++i)\n      m_shuffle.push_back(i);\n\n    m_numImagesInModel = 0;\n    for( int i = 0; i < basicModel.size(); ++i )\n      m_numImagesInModel += basicModel[i].images.size();\n\n    m_featureMap.resize( m_numImagesInModel );\n    FeatureCollectorTripletGenerator<Dtype>::init( basicModel );\n  }\nprivate:\n  typedef size_t ImageIndex;\n  typedef size_t ClassIndex;\n  typedef size_t SampleIndex;\n  typedef ImageClassificationModel::ImageIndexes ImageIndexes;\npublic:\n\n  Triplet nextTriplet()\n  {\n    static bool featuresCollected = false;\n\n    if( !featuresCollected )\n    {\n      if( m_featureMap.numFeatures() != m_numImagesInModel )\n      {\n        m_isLastTripletHard = true;\n        return FeatureCollectorTripletGenerator<Dtype>::getInstance().nextTriplet();\n      }\n\n      LOG(INFO) << \"All features are collected!\";\n      featuresCollected = true;\n    }\n\n    if(classIndex(m_indexInSample) >= m_classesInSample)\n      resample();\n\n    Triplet t;\n    m_isLastTripletHard = false;\n\n    SampleIndex anchorIndex = m_shuffle[m_indexInSample];\n\n    t.push_back(image(anchorIndex)); // anchor\n\n    const Vec& dvec = m_distances[anchorIndex];\n    SampleIndex posSampleBegin = classIndex(anchorIndex)*m_imagesInSampleClass;\n    SampleIndex posSampleEnd = posSampleBegin + m_imagesInSampleClass;\n    SampleIndex posIndex = 0;\n\n    if( m_hardestPositive )\n    {\n      Dtype maxPosDistance = 0;\n      for(size_t posSample = posSampleBegin; posSample<posSampleEnd; ++posSample)\n      {\n        if(posSample==anchorIndex)\n          continue;\n        if(dvec[posSample] > maxPosDistance)\n        {\n          maxPosDistance = dvec[posSample];\n          posIndex = posSample;\n        }\n      }\n    }\n    else\n    {\n      posIndex = 1+anchorIndex;\n      if( (posIndex % m_imagesInSampleClass) == 0 )\n        posIndex = posSampleBegin;\n    }\n\n    t.push_back(image(posIndex)); // hard positive\n\n    Dtype posDistance = dvec[posIndex];\n    Dtype posDistanceWithMargin = posDistance+m_margin;\n\n    size_t nSample = m_classesInSample*m_imagesInSampleClass;\n    Dtype closeNegDistance = std::numeric_limits<Dtype>::max();\n    size_t negIndex = std::numeric_limits<size_t>::max();\n\n    std::vector<size_t> hardNegIndices;\n\n    for(size_t negSample = 0; negSample<nSample; ++negSample)\n    {\n      if( negSample == posSampleBegin )\n      {\n        negSample = posSampleEnd-1;\n        continue;\n      }\n\n      if(negIndex == std::numeric_limits<size_t>::max())\n        negIndex = negSample; // the first negative selected as \"random\"\n\n      if( dvec[negSample] >= posDistance && dvec[negSample] < posDistanceWithMargin )\n      {\n          m_isLastTripletHard = true;\n          if( m_hardestNegative )\n          {\n            if( dvec[negSample] < closeNegDistance )\n            {\n              closeNegDistance = dvec[negSample];\n              negIndex = negSample;\n            }\n          }\n          else\n          {\n            hardNegIndices.push_back( negSample );\n          }\n      }\n    }\n\n    if( m_tooHardTriplets && !m_isLastTripletHard )\n    {\n      closeNegDistance = 0;\n      for(size_t negSample = 0; negSample<nSample; ++negSample)\n      {\n        if( negSample == posSampleBegin )\n        {\n          negSample = posSampleEnd-1;\n          continue;\n        }\n\n        if( dvec[negSample] < posDistance )\n        {\n          m_isLastTripletHard = true;\n          if( m_hardestNegative )\n          {\n            if( dvec[negSample] > closeNegDistance )\n            {\n              closeNegDistance = dvec[negSample];\n              negIndex = negSample;\n            }\n          }\n          else\n          {\n            hardNegIndices.push_back( negSample );\n          }\n        }\n      }\n    }\n\n    if( !m_hardestNegative )\n    {\n      if( hardNegIndices.size() > 0 )\n      {\n        negIndex = hardNegIndices[rand()%hardNegIndices.size()];\n        m_isLastTripletHard = true;\n      }\n      else\n      {\n        negIndex = rand()%(nSample-m_imagesInSampleClass);\n        if( negIndex >= posSampleBegin )\n          negIndex += m_imagesInSampleClass;\n        m_isLastTripletHard = false;\n      }\n    }\n\n    t.push_back(image(negIndex)); // hard negative\n\n    ++m_indexInSample;\n\n    return t;\n  }\n\n  bool isLastTripletHard( ) const\n  {\n    return m_isLastTripletHard;\n  }\n\n  const FeatureMap<Dtype>& getFeatureMap( ) const\n  {\n    return m_featureMap;\n  }\n\n  Dtype getMargin( ) const\n  {\n    return m_margin;\n  }\nprivate:\n  ClassIndex classIndex(SampleIndex idx) const { return idx/m_imagesInSampleClass; }\n  ImageIndex imageIndex(SampleIndex idx) const { return idx%m_imagesInSampleClass; }\n  const ImageIndexes& images(SampleIndex idx) const { return m_sample[classIndex(idx)].images; }\n  ImageIndex image(SampleIndex idx) const { return images(idx)[imageIndex(idx)]; }\nprivate:\n  void resample()\n  {\n    m_sampler.sample(m_sample);\n    recalcDistances();\n    shuffle( m_shuffle.begin(), m_shuffle.end() );\n    m_indexInSample = 0;\n  }\n\n  void recalcDistancesGPU(); // src/caffe/ultinous/HardTripletGenerator.cu\n\n  void recalcDistancesCPU()\n  {\n    size_t const nSample = m_classesInSample * m_imagesInSampleClass;\n\n    typename FeatureMap<Dtype>::FeatureVec sqr;\n\n    for( size_t i = 0; i < nSample-1; i++ )\n    {\n      const typename FeatureMap<Dtype>::FeatureVec& feat1 = m_featureMap.getFeatureVec( image(i) );\n      CHECK_GT( feat1.size(), 0);\n\n      sqr.resize( feat1.size() );\n\n      for( size_t j = i+1; j < nSample; j++ )\n      {\n        const typename FeatureMap<Dtype>::FeatureVec& feat2 = m_featureMap.getFeatureVec( image(j) );\n\n        CHECK_GT( feat2.size(), 0 );\n        CHECK_EQ( feat1.size(), feat2.size() );\n\n        caffe_sub( feat1.size(), &(feat1[0]), &(feat2[0]), &(sqr[0]) );\n        Dtype dist = caffe_cpu_dot( sqr.size(), &(sqr[0]), &(sqr[0]) );\n\n        m_distances[i][j] = dist;\n        m_distances[j][i] = dist;\n      }\n    }\n  }\n  void recalcDistances()\n  {\n    size_t const nSample = m_classesInSample * m_imagesInSampleClass;\n\n    CHECK_GT( nSample, 0 );\n\n    if( m_distances.size() != nSample )\n      m_distances = Mat( nSample, Vec(nSample, 0) );\n\n    CHECK_EQ( m_distances.size(), nSample );\n    for( size_t i = 0; i < nSample; i++ )\n      CHECK_EQ( m_distances[i].size(), nSample );\n\n    #ifdef CPU_ONLY\n    recalcDistancesCPU();\n    #else\n    recalcDistancesGPU();\n    #endif\n  }\n\nprivate:\n  typedef std::vector<Dtype> Vec;\n  typedef std::vector<Vec> Mat;\n  typedef ImageSampler::Sample Sample;\nprivate:\n  ImageSampler m_sampler;\n  size_t m_classesInSample;\n  size_t m_imagesInSampleClass;\n  Mat m_distances;\n  Dtype m_margin;\n  Sample m_sample;\n  SampleIndex m_indexInSample;\n  FeatureMap<Dtype>& m_featureMap;\n  bool m_tooHardTriplets;\n  bool m_hardestPositive;\n  bool m_hardestNegative;\n  bool m_isLastTripletHard;\n\n  std::vector<SampleIndex> m_shuffle;\n\n  shared_ptr<SyncedMemory> m_syncedFeatures;\n  shared_ptr<SyncedMemory> m_syncedDistances;\n\n  size_t m_numImagesInModel;\n};\n\n} // namespace ultinous\n} // namespace caffe\n", "meta": {"hexsha": "fe3fdab0145ace0785c06bb20537dcf19af052d1", "size": 8197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/caffe/ultinous/HardTripletGenerator.hpp", "max_stars_repo_name": "Ultinous/caffe", "max_stars_repo_head_hexsha": "6b26a5889f6ea9681c4981daafe55d7530cf53ca", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-05T15:54:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-05T15:54:16.000Z", "max_issues_repo_path": "include/caffe/ultinous/HardTripletGenerator.hpp", "max_issues_repo_name": "Ultinous/caffe", "max_issues_repo_head_hexsha": "6b26a5889f6ea9681c4981daafe55d7530cf53ca", "max_issues_repo_licenses": ["Intel", "BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-25T12:58:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T12:58:01.000Z", "max_forks_repo_path": "include/caffe/ultinous/HardTripletGenerator.hpp", "max_forks_repo_name": "Ultinous/caffe", "max_forks_repo_head_hexsha": "6b26a5889f6ea9681c4981daafe55d7530cf53ca", "max_forks_repo_licenses": ["Intel", "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.142384106, "max_line_length": 101, "alphanum_fraction": 0.6504818836, "num_tokens": 2152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17827365374094334}}
{"text": "/* Author: Mincheul Kang */\n\n#include <boost/chrono.hpp>\n#include <boost/foreach.hpp>\n#include <ompl/base/SpaceInformation.h>\n\n#include <harmonious_sampling/StateSpaces.h>\n\nStateValidityChecker::StateValidityChecker(const ompl::base::SpaceInformationPtr &si,\n                                                   planning_scene::PlanningScenePtr& planning_scene,\n                                                   std::string planning_group,\n                                                   std::string collision_check_group):\n        ompl::base::StateValidityChecker(si),\n        state_space_(si->getStateSpace().get())\n{\n    planning_scene_ = planning_scene;\n    planning_group_ = planning_group;\n\n    collision_request_.group_name = collision_check_group;\n    collision_request_.contacts = true;\n    collision_request_.max_contacts = 100;\n    collision_request_.max_contacts_per_pair = 1;\n    collision_request_.verbose = false;\n}\n\nbool StateValidityChecker::isValid(const ompl::base::State *state) const {\n    std::map<std::string, double> configuration;\n    collision_detection::CollisionResult collision_result;\n    std::vector<double> values;\n    state_space_->copyToReals(values, state);\n\n    collision_result.clear();\n\n    robot_state::RobotState robot_state = planning_scene_->getCurrentStateNonConst();\n    robot_state.setJointGroupPositions(planning_group_, values);\n    planning_scene_->checkCollision(collision_request_, collision_result, robot_state);\n\n    return !collision_result.collision;\n}", "meta": {"hexsha": "ca5a496f15cb7e4c05c047aaed95f01e3d389275", "size": 1508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "harmonious_sampling/src/StateSpaces.cpp", "max_stars_repo_name": "cheulkang/HarmoniousSampling", "max_stars_repo_head_hexsha": "40a5f89ab1f4a680160a61b13daba09cdf661b8b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-11-06T06:01:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T04:46:19.000Z", "max_issues_repo_path": "harmonious_sampling/src/StateSpaces.cpp", "max_issues_repo_name": "cheulkang/HarmoniousSampling", "max_issues_repo_head_hexsha": "40a5f89ab1f4a680160a61b13daba09cdf661b8b", "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": "harmonious_sampling/src/StateSpaces.cpp", "max_forks_repo_name": "cheulkang/HarmoniousSampling", "max_forks_repo_head_hexsha": "40a5f89ab1f4a680160a61b13daba09cdf661b8b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-01T12:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T07:33:42.000Z", "avg_line_length": 38.6666666667, "max_line_length": 100, "alphanum_fraction": 0.6962864721, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17827365022416772}}
{"text": "// Copyright (c) 2017 - 2019 - The SmartCash Developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"consensus/consensus.h\"\n#include \"init.h\"\n#include \"smartrewards/rewards.h\"\n#include \"smartrewards/rewardspayments.h\"\n#include \"smarthive/hive.h\"\n#include \"smartnode/spork.h\"\n#include \"smartnode/smartnodepayments.h\"\n#include \"ui_interface.h\"\n#include \"validation.h\"\n\n#include <boost/thread.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n\nCSmartRewards *prewards = NULL;\n\nCCriticalSection cs_rewardsdb;\nCCriticalSection cs_rewardrounds;\n\n// Used for time conversions.\nboost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));\n\n// Estimate or return the current block height.\nint GetBlockHeight(const CBlockIndex *index)\n{\n    int64_t syncDiff = std::time(0) - index->GetBlockTime();\n    int64_t firstTxDiff;\n    if( MainNet() ) firstTxDiff = std::time(0) - nStartRewardTime; // Diff from the reward blocks start till now on mainnet.\n    else firstTxDiff = std::time(0) - nFirstTxTimestamp_Testnet; // Diff from the first transaction till now on testnet.\n    return syncDiff > 1200 ? firstTxDiff / 55 : index->nHeight; // If we are 20 minutes near now use the current height.\n}\n\nint ParseScript(const CScript &script, std::vector<CSmartAddress> &ids){\n\n    std::vector<CTxDestination> addresses;\n    txnouttype type;\n    int nRequired;\n\n    if (!ExtractDestinations(script, type, addresses, nRequired)) {\n        return 0;\n    }\n\n    BOOST_FOREACH(const CTxDestination &d, addresses)\n    {\n        ids.push_back(CSmartAddress(d));\n    }\n\n    return nRequired;\n}\n\nvoid CalculateRewardRatio(CSmartRewardRound &round)\n{\n    int64_t time = GetTime();\n    int64_t start = round.startBlockHeight;\n    round.rewards = 0;\n\n    while( start <= round.endBlockHeight) round.rewards += GetBlockValue(start++,0,time) * 0.15;\n\n    round.percent = double(round.rewards) / ( round.eligibleSmart - round.disqualifiedSmart );\n}\n\nbool CSmartRewards::Verify()\n{\n    LOCK(cs_rewardsdb);\n    return pdb->Verify(rewardHeight);\n}\n\n\nvoid CSmartRewards::UpdatePayoutParameter(CSmartRewardRound &round)\n{\n\n    int64_t nPayeeCount = round.eligibleEntries - round.disqualifiedEntries;\n    int nFirst_1_3_Round = MainNet() ? nRewardsFirst_1_3_Round : nRewardsFirst_1_3_Round_Testnet;\n\n    if( round.number < nFirst_1_3_Round ){\n\n        round.nBlockPayees = nRewardPayouts_1_2_BlockPayees;\n        round.nBlockInterval = nRewardPayouts_1_2_BlockInterval;\n\n        if( TestNet() ){\n            if( round.number < 68 ){\n                round.nBlockPayees = nRewardPayoutsPerBlock_1_Testnet;\n                round.nBlockInterval = nRewardPayoutBlockInterval_1_Testnet;\n            }else{\n                round.nBlockPayees = nRewardPayoutsPerBlock_2_Testnet;\n                round.nBlockInterval = nRewardPayoutBlockInterval_2_Testnet;\n            }\n        }\n\n    }else{\n\n        int64_t nBlockStretch = MainNet() ? nRewardPayouts_1_3_BlockStretch :\n                                   nRewardPayouts_1_3_BlockStretch_Testnet;\n        int64_t nBlocksPerRound = MainNet() ? nRewardsBlocksPerRound_1_3 :\n                                   nRewardsBlocksPerRound_1_3_Testnet;\n        int64_t nBlockPayees = MainNet() ? nRewardPayouts_1_3_BlockPayees :\n                                           nRewardPayouts_1_3_BlockPayees_Testnet;\n\n        round.nBlockPayees = std::max<int>(nBlockPayees, (nPayeeCount / nBlockStretch * nBlockPayees) + 1);\n\n        int64_t nStartDelayBlocks = MainNet() ? nRewardPayoutStartDelay : nRewardPayoutStartDelay_Testnet;\n        int64_t nBlocksTarget = nStartDelayBlocks + nBlocksPerRound;\n        round.nBlockInterval = ((nBlockStretch * round.nBlockPayees) / nPayeeCount) + 1;\n        int64_t nStretchedLength = nPayeeCount / round.nBlockPayees * (round.nBlockInterval);\n\n        if( nStretchedLength > nBlocksTarget ){\n            round.nBlockInterval--;\n        }else if( nStretchedLength < nBlockStretch ){\n            round.nBlockInterval++;\n        }\n    }\n}\n\nbool CSmartRewards::Update(CBlockIndex *pindexNew, const CChainParams& chainparams, const int nCurrentRound, CSmartRewardsUpdateResult &result) {\n\n    CSmartRewardEntry *rEntry = nullptr;\n    CBlock block;\n    int nHeight = pindexNew->nHeight;\n    int nFirst1_3_Round = MainNet() ? nRewardsFirst_1_3_Round : nRewardsFirst_1_3_Round_Testnet;\n    ReadBlockFromDisk(block, pindexNew, chainparams.GetConsensus());\n\n    BOOST_FOREACH(const CTransaction &tx, block.vtx) {\n\n        CSmartRewardTransaction testTx;\n#ifdef DEBUG_LOCKORDER\n        int nTime1 = GetTimeMicros();\n#endif\n        // First check if the transaction hash did already come up in the past.\n        if( GetTransaction(tx.GetHash(),testTx)){\n            // If yes we want to ignore it!\n            LogPrintf(\"[%s] Double appearance! First in %d - Now in %d\\n\",testTx.hash.ToString(), testTx.blockHeight, pindexNew->nHeight);\n            continue;\n        }else{\n            // If not save add it to the database.\n            CSmartRewardTransaction saveTx(pindexNew->nHeight, tx.GetHash());\n            AddTransaction(saveTx);\n        }\n\n        CSmartAddress *voteKeyRegistrationCheck = nullptr;\n\n        // No reason to check the input here for new coins.\n        if( !tx.IsCoinBase() ){\n\n            CTransaction rTx;\n            uint256 rBlockHash;\n\n            BOOST_FOREACH(const CTxIn &in, tx.vin) {\n\n                if( in.scriptSig.IsZerocoinSpend() ) continue;\n\n                if(!::GetTransaction(in.prevout.hash,rTx,chainparams.GetConsensus(),rBlockHash)){\n                    return error(\"%s: GetTransaction - %s\\n Input: %s\", __func__, tx.ToString(),in.prevout.hash.ToString());\n                }\n\n                CTxOut rOut = rTx.vout[in.prevout.n];\n\n                std::vector<CSmartAddress> ids;\n\n                int required = ParseScript(rOut.scriptPubKey ,ids);\n\n                if( !required || required > 1 || ids.size() > 1 ){\n                    LogPrint(\"smartrewards\", \"Process Inputs: Could't parse CSmartAddress: %s\\n\",rOut.ToString());\n                    continue;\n                }\n\n                if(!GetCachedRewardEntry(ids.at(0),rEntry)){\n\n                    rEntry = new CSmartRewardEntry(ids.at(0));\n\n                    if(!ReadRewardEntry(rEntry->id, *rEntry)){\n                        delete rEntry;\n                        LogPrintf(\"%s: Spend without previous receive - %s\", __func__, tx.ToString());\n                        continue;\n                    }\n\n                    rewardEntries.insert(make_pair(ids.at(0), rEntry));\n                }\n\n                rEntry->balance -= rOut.nValue;\n\n                if( rEntry->IsEligible() ){\n\n                    // If its a votekey registration not instantly make the\n                    // balance ineligible. First check if the change is sent back\n                    // to the address or not to avoid exploiting fund sending\n                    // with votekey registration transactions\n                    if( nCurrentRound >= nFirst1_3_Round && tx.IsVoteKeyRegistration()  )\n                        voteKeyRegistrationCheck = new CSmartAddress(rEntry->id);\n                    else{\n                        rEntry->fBalanceEligible = false;\n                        result.disqualifiedEntries++;\n                        result.disqualifiedSmart += rEntry->balanceOnStart;\n                    }\n\n                }\n\n                if(rEntry->balance < 0 ){\n                    LogPrintf(\"%s: Negative amount?! - %s\", __func__, rEntry->ToString());\n                    rEntry->balance = 0;\n                }\n\n            }\n        }\n\n#ifdef DEBUG_LOCKORDER\n        int nTime2 = GetTimeMicros();\n#endif\n\n        BOOST_FOREACH(const CTxOut &out, tx.vout) {\n\n            if(out.scriptPubKey.IsZerocoinMint() ) continue;\n\n            std::vector<CSmartAddress> ids;\n            int required = ParseScript(out.scriptPubKey ,ids);\n\n            if( !required || required > 1 || ids.size() > 1 ){\n                LogPrint(\"smartrewards\", \"Process Outputs: Could't parse CSmartAddress: %s\\n\",out.ToString());\n                continue;\n            }else{\n\n                if(!GetCachedRewardEntry(ids.at(0),rEntry)){\n                    rEntry = new CSmartRewardEntry(ids.at(0));\n                    ReadRewardEntry(rEntry->id, *rEntry);\n                    rewardEntries.insert(make_pair(ids.at(0), rEntry));\n                }\n\n                if( voteKeyRegistrationCheck ){\n\n                    if( tx.IsVoteKeyRegistration() &&\n                        !out.IsVoteKeyRegistrationData() &&\n                        !(*voteKeyRegistrationCheck == rEntry->id) ){\n\n                        CSmartRewardEntry *vkEntry = nullptr;\n\n                        if(!GetCachedRewardEntry(*voteKeyRegistrationCheck,vkEntry)){\n                            vkEntry = new CSmartRewardEntry(*voteKeyRegistrationCheck);\n                            ReadRewardEntry(vkEntry->id, *vkEntry);\n                            rewardEntries.insert(make_pair(vkEntry->id, vkEntry));\n                        }\n\n                        // Finally invalidate the balance since the change output went not\n                        // back to the registered transaction! We don't want to allow\n                        // a exploit to send around funds withouht breaking smartrewards.\n                        vkEntry->fBalanceEligible = false;\n                        result.disqualifiedEntries++;\n                        result.disqualifiedSmart += vkEntry->balanceOnStart;\n                    }\n\n                    delete voteKeyRegistrationCheck;\n                }\n\n                rEntry->balance += out.nValue;\n\n                // If we are in the 1.3 cycles check for node rewards to remove node addresses from lists\n                if( nCurrentRound >= nFirst1_3_Round && tx.IsCoinBase() ){\n\n                    int nInterval = SmartNodePayments::PayoutInterval(nHeight);\n                    int nPayoutsPerBlock = SmartNodePayments::PayoutsPerBlock(nHeight);\n                    // Just to avoid potential zero divisions\n                    nPayoutsPerBlock = std::max(1,nPayoutsPerBlock);\n\n                    CAmount nNodeReward = SmartNodePayments::Payment(nHeight) / nPayoutsPerBlock;\n\n                    // If we have an interval check if this is a node payout block\n                    if( nInterval && !(nHeight % nInterval) ){\n\n                        // If the amount matches and the entry is not yet marked as node do it\n                        if( abs(out.nValue - nNodeReward ) < 2 && !rEntry->fIsSmartNode ){\n\n                            // If it is currently eligible adjust the round's results\n                            if( rEntry->IsEligible() ){\n                                result.disqualifiedEntries++;\n                                result.disqualifiedSmart += rEntry->balanceOnStart;\n                            }\n\n                            rEntry->fIsSmartNode = true;\n                        }\n                    }\n                }\n            }\n        }\n\n#ifdef DEBUG_LOCKORDER\n        int nTime3 = GetTimeMicros();\n        int nTimeTx = nTime3 - nTime1;\n\n        if( nTimeTx > 500000){\n            LogPrint(\"smartrewards\", \"CSmartRewards::Update TX %s - %.2fms\\n\",HexStr(tx.GetHash()), nTimeTx * 0.001);\n            LogPrint(\"smartrewards\", \" inputs - %.2fms\\n\", (nTime2 - nTime1) * 0.001);\n            LogPrint(\"smartrewards\", \" outputs - %.2fms\\n\", (nTime3 - nTime2) * 0.001);\n        }\n#endif\n\n    }\n\n    uint256 blockHash = block.GetHash();\n    result.block = CSmartRewardBlock(pindexNew->nHeight, blockHash, block.GetBlockTime());\n\n    // Synt the data all nCacheEntires to the db.\n    int preparedEntries = rewardEntries.size() + transactionEntries.size();\n\n    return AddBlock(result.block, preparedEntries > nCacheEntires );\n}\n\nvoid CSmartRewards::EvaluateRound(CSmartRewardRound &current, CSmartRewardRound &next, CSmartRewardEntryList &entries, CSmartRewardSnapshotList &snapshots)\n{\n    LOCK(cs_rewardsdb);\n    snapshots.clear();\n\n    UpdatePayoutParameter(current);\n\n    BOOST_FOREACH(CSmartRewardEntry &entry, entries) {\n\n        if( current.number ) snapshots.push_back(CSmartRewardSnapshot(entry, current));\n\n        entry.balanceOnStart = entry.balance;\n        // Reset SmartNode flag with every cycle in case a node was shut down during the cycle.\n        entry.fIsSmartNode = false;\n        // Reset the voted flag with every cycle to force a new vote for eligibility\n        entry.fVoteProved = false;\n        // Evaluate the balance eligibilty\n        entry.fBalanceEligible = entry.balanceOnStart >= SMART_REWARDS_MIN_BALANCE && !SmartHive::IsHive(entry.id);\n\n        if( entry.IsEligible() ){\n            ++next.eligibleEntries;\n            next.eligibleSmart += entry.balanceOnStart;\n        }\n    }\n}\n\nbool CSmartRewards::StartFirstRound(const CSmartRewardRound &first, const CSmartRewardEntryList &entries)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->StartFirstRound(first,entries);\n}\n\nbool CSmartRewards::FinalizeRound(const CSmartRewardRound &current, const CSmartRewardRound &next, const CSmartRewardEntryList &entries, const CSmartRewardSnapshotList &snapshots)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->FinalizeRound(current, next, entries, snapshots);\n}\n\nbool CSmartRewards::GetRewardSnapshots(const int16_t round, CSmartRewardSnapshotList &snapshots)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardSnapshots(round, snapshots);\n}\n\nbool CSmartRewards::GetRewardPayouts(const int16_t round, CSmartRewardSnapshotList &payouts)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardPayouts(round, payouts);\n}\n\nbool CSmartRewards::GetRewardPayouts(const int16_t round, CSmartRewardSnapshotPtrList &payouts)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardPayouts(round, payouts);\n}\n\n\n// --- TBD ---\nbool CSmartRewards::RestoreSnapshot(const int16_t round)\n{\n//    LOCK(cs_rewardsdb);\n\n//    CSmartRewardRound restore;\n//    CSmartRewardEntryList entries;\n\n//    if( !pdb->ReadRound(round, restore) ) return false;\n//    if( !pdb->ReadRewardSnapshots(round, entries) ) return false;\n//    if( history.number != round) return false;\n\n//    restore.disqualifiedEntries = 0;\n//    restore.disqualifiedSmart = 0;\n//    restore.rewards = 0;\n//    restore.percent = 0;\n\n//    CalculateRewardRatio(restore);\n\n//    return pdb->ResetToRound(round, restore, entries);\n    return false;\n}\n\nbool CSmartRewards::GetCachedRewardEntry(const CSmartAddress &id, CSmartRewardEntry *&entry)\n{\n    LOCK(cs_rewardsdb);\n\n    // Return the entry if its already in cache.\n    auto findResult = rewardEntries.find(id);\n\n    if( findResult != rewardEntries.end() ){\n        entry = findResult->second;\n        return true;\n    }\n\n    return false;\n}\n\nbool CSmartRewards::ReadRewardEntry(const CSmartAddress &id, CSmartRewardEntry &entry)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardEntry(id,entry);\n}\n\nbool CSmartRewards::GetRewardEntry(const CSmartAddress &id, CSmartRewardEntry &entry)\n{\n    LOCK(cs_rewardsdb);\n\n    CSmartRewardEntry * pReadEntry;\n\n    if( GetCachedRewardEntry(id,pReadEntry) ){\n        entry = *pReadEntry;\n        return true;\n    }\n\n    return ReadRewardEntry(id,entry);\n}\n\nbool CSmartRewards::GetRewardEntries(CSmartRewardEntryList &entries)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardEntries(entries);\n}\n\nbool CSmartRewards::SyncPrepared()\n{\n    LOCK2(cs_rewardsdb, cs_rewardrounds);\n\n    bool ret =  pdb->SyncBlocks(blockEntries,currentRound, rewardEntries, transactionEntries);\n\n    for( std::pair<CSmartAddress, CSmartRewardEntry*> it : rewardEntries ){\n        delete it.second;\n    }\n\n    rewardEntries.clear();\n    blockEntries.clear();\n    transactionEntries.clear();\n\n    return ret;\n}\n\nbool CSmartRewards::IsSynced()\n{\n    int nSyncDistance = MainNet() ? nRewardsSyncDistance : nRewardsSyncDistance_Testnet;\n    return (chainHeight - rewardHeight) <= nSyncDistance - 1;\n}\n\ndouble CSmartRewards::GetProgress()\n{\n    int nSyncDistance = MainNet() ? nRewardsSyncDistance : nRewardsSyncDistance_Testnet;\n    double progress = chainHeight > nSyncDistance ? double(rewardHeight) / double(chainHeight - nSyncDistance) : 0.0;\n    return progress > 1 ? 1 : progress;\n}\n\nint CSmartRewards::GetLastHeight()\n{\n    return rewardHeight;\n}\n\nint CSmartRewards::GetBlocksPerRound(const int nRound)\n{\n    LOCK(cs_rewardrounds);\n\n    if( MainNet() ){\n\n        if( nRound < nRewardsFirst_1_3_Round )\n            return nRewardsBlocksPerRound_1_2;\n        else\n            return nRewardsBlocksPerRound_1_3;\n\n    }else{\n\n        if( nRound < nRewardsFirst_1_3_Round_Testnet )\n            return nRewardsBlocksPerRound_1_2_Testnet;\n        else\n            return nRewardsBlocksPerRound_1_3_Testnet;\n\n    }\n\n}\n\nbool CSmartRewards::AddBlock(const CSmartRewardBlock &block, bool sync)\n{\n    blockEntries.push_back(block);\n\n#ifdef DEBUG_LOCKORDER\n    int nTime1 = GetTimeMicros();\n#endif\n\n    if(sync) return SyncPrepared();\n\n#ifdef DEBUG_LOCKORDER\n    int nTimeSync = GetTimeMicros() - nTime1;\n    if( nTimeSync > 300000){\n        LogPrint(\"smartrewards\", \"CSmartRewards::AddBlock - Sync - Block: %d - Progress %.2fms\\n\",block.nHeight, nTimeSync * 0.001);\n    }\n#endif\n\n    return true;\n}\n\nvoid CSmartRewards::AddTransaction(const CSmartRewardTransaction &transaction)\n{\n    LOCK(cs_rewardsdb);\n    transactionEntries.push_back(transaction);\n}\n\nCSmartRewards::CSmartRewards(CSmartRewardsDB *prewardsdb)  : pdb(prewardsdb)\n{\n    LOCK(cs_rewardsdb);\n\n    // Get the last written block of the rewards database.\n    if(!pdb->ReadLastBlock(currentBlock)){\n        // If there is no one available yet\n        // Use 0 to get 1 as start below.\n        currentBlock.nHeight = 0;\n        currentBlock.blockHash = uint256();\n        currentBlock.blockTime = 0;\n    }\n\n    pdb->ReadRounds(finishedRounds);\n\n    std::sort(finishedRounds.begin(), finishedRounds.end());\n\n    if( finishedRounds.size() ){\n        lastRound = finishedRounds.back();\n    }\n\n    pdb->ReadCurrentRound(currentRound);\n}\n\nvoid CSmartRewards::Lock()\n{\n    LOCK(cs_rewardsdb);\n    pdb->Lock();\n}\n\nbool CSmartRewards::IsLocked()\n{\n    LOCK(cs_rewardsdb);\n    return pdb->IsLocked();\n}\n\nvoid CSmartRewards::CatchUp()\n{\n    const CChainParams& chainparams = Params();\n    CBlockIndex* pHighestIndex = chainActive.Tip();\n    CBlockIndex* pLastIndex = pHighestIndex;\n    if( !pLastIndex ) return;\n    // If the rewards db is higher than the chain.\n    if( pLastIndex->nHeight <= currentBlock.nHeight ) return;\n\n    // Search the index of the next missing bock in the\n    // rewards database.\n    while( pLastIndex->nHeight != currentBlock.nHeight + 1){\n        pLastIndex = pLastIndex->pprev;\n    }\n\n    int nMinConfirmations = MainNet() ? nRewardsConfirmations : nRewardsConfirmations_Testnet;\n\n    while( pLastIndex && ( currentBlock.nHeight - pLastIndex->nHeight ) < nMinConfirmations)\n    {\n        if( ShutdownRequested() ){\n            SyncPrepared();\n            return;\n        }\n\n        if( !(currentBlock.nHeight % 100) ){\n            uiInterface.InitMessage(_(\"Creating SmartRewards database: \") + strprintf(\"%d/%d\",currentBlock.nHeight, pHighestIndex->nHeight));\n        }\n\n        ProcessBlock(pLastIndex, chainparams);\n\n        pLastIndex = chainActive.Next(pLastIndex);\n\n    }\n\n    prewards->UpdateHeights(GetBlockHeight(pHighestIndex), currentBlock.nHeight);\n}\n\nbool CSmartRewards::GetLastBlock(CSmartRewardBlock &block)\n{\n    LOCK(cs_rewardsdb);\n    // Read the last block stored in the rewards database.\n    return pdb->ReadLastBlock(block);\n}\n\nbool CSmartRewards::GetTransaction(const uint256 hash, CSmartRewardTransaction &transaction)\n{\n    // If the transaction is already in the cache use this one.\n    BOOST_FOREACH(CSmartRewardTransaction t, transactionEntries) {\n        if(t.hash == hash){\n            transaction = t;\n            return true;\n        }\n    }\n\n    return pdb->ReadTransaction(hash, transaction);\n}\n\nconst CSmartRewardRound& CSmartRewards::GetCurrentRound()\n{\n    return currentRound;\n}\n\nconst CSmartRewardRound& CSmartRewards::GetLastRound()\n{\n    return lastRound;\n}\n\nconst CSmartRewardRoundList& CSmartRewards::GetRewardRounds()\n{\n    return finishedRounds;\n}\n\nvoid CSmartRewards::UpdateHeights(const int nHeight, const int nRewardHeight)\n{\n    chainHeight = nHeight;\n    rewardHeight = nRewardHeight;\n}\n\nvoid CSmartRewards::ProcessBlock(CBlockIndex* pLastIndex, const CChainParams& chainparams)\n{\n    int64_t nTime1 = 0, nTime2 = 0, nTime3 = 0;\n    static int64_t nTimeTotal = 0;\n    static int64_t nTimeUpdateRewardsTotal = 0;\n    static int64_t nCountUpdateRewards = 0;\n\n    if(pLastIndex->nHeight > sporkManager.GetSporkValue(SPORK_15_SMARTREWARDS_BLOCKS_ENABLED)){\n        return;\n    }\n\n    int nMinConfirmations = MainNet() ? nRewardsConfirmations : nRewardsConfirmations_Testnet;\n\n    if( ( pLastIndex->nHeight - currentBlock.nHeight ) > nMinConfirmations){\n\n        int nCurrentRound;\n\n        {\n            LOCK(cs_rewardrounds);\n            nCurrentRound = currentRound.number;\n        }\n\n        CBlockIndex* pNextIndex = pLastIndex;\n\n        while(pNextIndex && pNextIndex->nHeight != currentBlock.nHeight + 1 ) pNextIndex = pNextIndex->pprev;\n\n        if(!pNextIndex || pNextIndex->nHeight != currentBlock.nHeight + 1 ) throw runtime_error(\"Failed to find next block index!\");\n\n        nTime1 = GetTimeMicros();\n\n        // Result of the block processing.\n        CSmartRewardsUpdateResult result;\n        // Process the block!\n        if(!Update(pNextIndex, chainparams, nCurrentRound, result)) throw runtime_error(std::string(__func__) + \": rewards update failed\");\n\n        // Update the current block to the processed one\n        currentBlock = result.block;\n\n        nTime2 = GetTimeMicros();\n\n        nTimeUpdateRewardsTotal += nTime2 - nTime1;\n        ++nCountUpdateRewards;\n\n        // For the first round we have special parameter..\n        if( !currentRound.number ){\n\n            if( (MainNet() && pNextIndex->GetBlockTime() > nFirstRoundStartTime) ||\n                (TestNet() && pNextIndex->nHeight >= nFirstRoundStartBlock_Testnet) ){\n\n                if( !SyncPrepared() ) throw runtime_error(\"Failed to sync current prepared entries!\");\n\n                // Create the very first smartrewards round.\n                CSmartRewardRound first;\n                first.number = 1;\n                first.startBlockTime = pNextIndex->GetBlockTime();\n                first.startBlockHeight = MainNet() ? nFirstRoundStartBlock : nFirstRoundStartBlock_Testnet;\n                first.endBlockTime = MainNet() ? nFirstRoundEndTime : nFirstRoundEndTime_Testnet;\n                // Estimate the block, gets updated on the end of the round to the real one.\n                first.endBlockHeight = MainNet() ? nFirstRoundEndBlock : nFirstRoundEndBlock_Testnet;\n\n                CSmartRewardEntryList entries;\n                CSmartRewardSnapshotList snapshots;\n\n                // Get the current entries\n                if( !GetRewardEntries(entries) ) throw runtime_error(\"Failed to read all reward entries!\");\n\n                // Evaluate the round and update the next rounds parameter.\n                EvaluateRound(currentRound, first, entries, snapshots );\n\n                CalculateRewardRatio(first);\n\n                if( !StartFirstRound(first, entries) ) throw runtime_error(\"Failed to finalize round!\");\n\n                currentRound = first;\n            }\n\n        }else if( result.disqualifiedEntries || result.disqualifiedSmart ){\n\n            // If there were disqualification during the last block processing\n            // update the current round stats.\n\n            currentRound.disqualifiedEntries += result.disqualifiedEntries;\n            currentRound.disqualifiedSmart += result.disqualifiedSmart;\n\n            CalculateRewardRatio(currentRound);\n        }\n\n        // If just hit the next round threshold\n        if( ( MainNet() && currentRound.number < nRewardsFirstAutomatedRound - 1 && pNextIndex->GetBlockTime() > currentRound.endBlockTime ) ||\n            ( ( TestNet() || currentRound.number >= nRewardsFirstAutomatedRound - 1 ) && pNextIndex->nHeight >= currentRound.endBlockHeight ) ){\n\n            if( !SyncPrepared() ) throw runtime_error(\"Failed to sync current prepared entries!\");\n\n            // Write the round to the history\n            currentRound.endBlockHeight = pNextIndex->nHeight;\n            currentRound.endBlockTime = pNextIndex->GetBlockTime();\n\n            CSmartRewardEntryList entries;\n            CSmartRewardSnapshotList snapshots;\n\n            // Create the next round.\n            CSmartRewardRound next;\n            next.number = currentRound.number + 1;\n            next.startBlockTime = currentRound.endBlockTime;\n            next.startBlockHeight = currentRound.endBlockHeight + 1;\n\n            int nBlocksPerRound = GetBlocksPerRound(next.number);\n            time_t startTime = (time_t)next.startBlockTime;\n\n            if( MainNet() ){\n\n                if( next.number == nRewardsFirstAutomatedRound - 1 ){\n                    // Let the round 12 end at height 574099 so that round 13 starts at 574100\n                    next.endBlockHeight = HF_V1_2_SMARTREWARD_HEIGHT - 1;\n                    next.endBlockTime = startTime + ( (next.endBlockHeight - next.startBlockHeight) * 55 );\n                }else if(next.number < nRewardsFirstAutomatedRound){\n\n                    boost::gregorian::date endDate = boost::posix_time::from_time_t(startTime).date();\n\n                    endDate += boost::gregorian::months(1);\n                    // End date at 00:00:00 + 25200 seconds (7 hours) to match the date at 07:00 UTC\n                    next.endBlockTime = time_t((boost::posix_time::ptime(endDate, boost::posix_time::seconds(25200)) - epoch).total_seconds());\n                    next.endBlockHeight = next.startBlockHeight + ( (next.endBlockTime - next.startBlockTime) / 55 );\n                }else{\n                    next.endBlockHeight = next.startBlockHeight + nBlocksPerRound - 1;\n                    next.endBlockTime = startTime + nBlocksPerRound * 55;\n                }\n\n            }else{\n                next.endBlockHeight = next.startBlockHeight + nBlocksPerRound - 1;\n                next.endBlockTime = startTime + nBlocksPerRound * 55;\n            }\n\n            if( !SyncPrepared() ) throw runtime_error(\"Failed to sync current prepared entries!\");\n\n            // Get the current entries\n            if( !GetRewardEntries(entries) ) throw runtime_error(\"Failed to read all reward entries!\");\n\n            CalculateRewardRatio(currentRound);\n\n            // Evaluate the round and update the next rounds parameter.\n            EvaluateRound(currentRound, next, entries, snapshots);\n\n            CalculateRewardRatio(next);\n\n            if( !FinalizeRound(currentRound, next, entries, snapshots) ) throw runtime_error(\"Failed to finalize round!\");\n\n            LOCK(cs_rewardrounds);\n\n            finishedRounds.push_back(currentRound);\n            lastRound = currentRound;\n            currentRound = next;\n        }\n\n        prewards->UpdateHeights(GetBlockHeight(pLastIndex), currentBlock.nHeight);\n\n        nTime3 = GetTimeMicros(); nTimeTotal += nTime3 - nTime1;\n        int nTimeUpdateMean = nTimeUpdateRewardsTotal/nCountUpdateRewards;\n        int nTimeUpdate = nTime2 - nTime1;\n\n        if( nTimeUpdate > nTimeUpdateMean * 100){\n            LogPrint(\"smartrewards\", \"Round %d - Block: %d - Progress %d%%\\n\",currentRound.number, currentBlock.nHeight, int(prewards->GetProgress() * 100));\n            LogPrint(\"smartrewards\", \"  Update rewards: %.2fms [%.2fms]\\n\", nTimeUpdate * 0.001, (nTimeUpdateMean) * 0.001);\n            LogPrint(\"smartrewards\", \"  Evaluate round: %.2fms\\n\", (nTime3 - nTime2) * 0.001);\n            LogPrint(\"smartrewards\", \"  Total: %.2fms [%.2fs]\\n\", (nTime3 - nTime1) * 0.001, nTimeTotal * 0.000001);\n        }\n        // If we are synced notify the UI on each new block.\n        // If not notify the UI every nRewardsUISyncUpdateRate blocks to let it update the\n        // loading screen.\n        if( IsSynced() || !(currentBlock.nHeight % nRewardsUISyncUpdateRate) )\n            uiInterface.NotifySmartRewardUpdate();\n    }\n}\n", "meta": {"hexsha": "60b0f0111928beac778c9a2716a2b00e04b90c27", "size": 28270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/smartrewards/rewards.cpp", "max_stars_repo_name": "trappist/Core-Smart", "max_stars_repo_head_hexsha": "a87b46c911e7e8bddccecd6c3c930d9086759eb7", "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/smartrewards/rewards.cpp", "max_issues_repo_name": "trappist/Core-Smart", "max_issues_repo_head_hexsha": "a87b46c911e7e8bddccecd6c3c930d9086759eb7", "max_issues_repo_licenses": ["MIT"], "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/smartrewards/rewards.cpp", "max_forks_repo_name": "trappist/Core-Smart", "max_forks_repo_head_hexsha": "a87b46c911e7e8bddccecd6c3c930d9086759eb7", "max_forks_repo_licenses": ["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.3375, "max_line_length": 179, "alphanum_fraction": 0.6365405023, "num_tokens": 6742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.17827364168468707}}
{"text": "// Copyright (c) 2016 The Gulden developers\n// Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)\n// Distributed under the GULDEN software license, see the accompanying\n// file COPYING\n\n#include \"account.h\"\n#include \"wallet/wallet.h\"\n#include <Gulden/mnemonic.h>\n#include \"base58.h\"\n#include \"wallet/walletdb.h\"\n#include \"wallet/crypter.h\"\n\n#include <map>\n\n#include <boost/uuid/random_generator.hpp>\n#include <boost/uuid/nil_generator.hpp>\n\nCHDSeed::CHDSeed()\n    : m_nAccountIndex(HDDesktopStartIndex)\n    , m_nAccountIndexMobi(HDMobileStartIndex)\n    , encrypted(false)\n    , m_readOnly(false)\n{\n}\n\nCHDSeed::CHDSeed(SecureString mnemonic, SeedType type)\n    : m_type(type)\n    , m_UUID(boost::uuids::nil_generator()())\n    , m_nAccountIndex(HDDesktopStartIndex)\n    , m_nAccountIndexMobi(HDMobileStartIndex)\n    , encrypted(false)\n    , m_readOnly(false)\n{\n\n    unencryptedMnemonic = mnemonic;\n    Init();\n}\n\nCHDSeed::CHDSeed(CExtPubKey& pubkey, SeedType type)\n    : m_type(type)\n    , m_UUID(boost::uuids::nil_generator()())\n    , m_nAccountIndex(HDDesktopStartIndex)\n    , m_nAccountIndexMobi(HDMobileStartIndex)\n    , encrypted(false)\n    , m_readOnly(true)\n{\n    unencryptedMnemonic = \"\";\n    masterKeyPub = pubkey;\n\n    masterKeyPriv.GetMutableKey().MakeNewKey(true);\n    assert(masterKeyPriv.key.IsValid());\n    cointypeKeyPriv.GetMutableKey().MakeNewKey(true);\n    purposeKeyPriv.GetMutableKey().MakeNewKey(true);\n\n    InitReadOnly();\n}\n\nvoid CHDSeed::Init()\n{\n    unsigned char* seed = seedFromMnemonic(unencryptedMnemonic);\n    static const std::vector<unsigned char> hashkey = { 'G', 'u', 'l', 'd', 'e', 'n', ' ', 'b', 'i', 'p', '3', '2' };\n    static const std::vector<unsigned char> hashkeylegacy = { 'B', 'i', 't', 'c', 'o', 'i', 'n', ' ', 's', 'e', 'e', 'd' };\n\n    if (m_type == BIP32Legacy || m_type == BIP44External) {\n        masterKeyPriv.SetMaster(hashkeylegacy, seed, 64);\n    } else {\n        masterKeyPriv.SetMaster(hashkey, seed, 64);\n    }\n\n    switch (m_type) {\n    case BIP32:\n    case BIP32Legacy:\n        masterKeyPriv.Derive(purposeKeyPriv, 100 | BIP32_HARDENED_KEY_LIMIT); //Unused - but we generate anyway so that we don't save predictable/blank encrypted data to disk (tiny security precaution)\n        purposeKeyPriv.Derive(cointypeKeyPriv, 100 | BIP32_HARDENED_KEY_LIMIT); //Unused - but we generate anyway so that we don't save predictable/blank encrypted data to disk (tiny security precaution)\n        break;\n    case BIP44: {\n        masterKeyPriv.Derive(purposeKeyPriv, 44 | BIP32_HARDENED_KEY_LIMIT); //m/44'\n        purposeKeyPriv.Derive(cointypeKeyPriv, 87 | BIP32_HARDENED_KEY_LIMIT); //m/44'/87'\n    } break;\n    case BIP44NoHardening: {\n        masterKeyPriv.Derive(purposeKeyPriv, 44); //m/44\n        purposeKeyPriv.Derive(cointypeKeyPriv, 87); //m/44/87\n    } break;\n    default:\n        assert(0);\n    }\n    masterKeyPub = masterKeyPriv.Neuter();\n    purposeKeyPub = purposeKeyPriv.Neuter();\n    cointypeKeyPub = cointypeKeyPriv.Neuter();\n\n    if (m_UUID.is_nil()) {\n        m_UUID = boost::uuids::random_generator()();\n    }\n}\n\nvoid CHDSeed::InitReadOnly()\n{\n    assert(m_type == BIP44NoHardening);\n    masterKeyPub.Derive(purposeKeyPub, 44); //m/44\n    purposeKeyPub.Derive(cointypeKeyPub, 87); //m/44/87\n\n    if (m_UUID.is_nil()) {\n        m_UUID = boost::uuids::random_generator()();\n    }\n}\n\nCAccountHD* CHDSeed::GenerateAccount(AccountSubType type, CWalletDB* Db)\n{\n    if (IsLocked())\n        return NULL;\n\n    CAccountHD* account = NULL;\n    switch (type) {\n    case Desktop:\n        assert(m_nAccountIndex <= 99999);\n        account = GenerateAccount(m_nAccountIndex++);\n        break;\n    case Mobi:\n        account = GenerateAccount(m_nAccountIndexMobi++);\n        break;\n    default:\n        assert(0);\n        return NULL;\n    }\n\n    if (Db) {\n\n        Db->WriteHDSeed(*this);\n    }\n\n    account->m_SubType = type;\n    if (IsCrypted()) {\n        account->Encrypt(vMasterKey);\n    }\n    return account;\n}\n\nCAccountHD* CHDSeed::GenerateAccount(int nAccountIndex)\n{\n    if (IsLocked())\n        return NULL;\n\n    CExtKey accountKey;\n    if (IsReadOnly()) {\n        CExtPubKey accountKeyPub;\n        cointypeKeyPub.Derive(accountKeyPub, nAccountIndex); // m/44/87/n (BIP44)\n        return new CAccountHD(accountKeyPub, m_UUID);\n    } else {\n        switch (m_type) {\n        case BIP32:\n        case BIP32Legacy:\n            masterKeyPriv.Derive(accountKey, nAccountIndex | BIP32_HARDENED_KEY_LIMIT); // m/n' (BIP32)\n            break;\n        case BIP44:\n        case BIP44External:\n            cointypeKeyPriv.Derive(accountKey, nAccountIndex | BIP32_HARDENED_KEY_LIMIT); // m/44'/87'/n' (BIP44)\n            break;\n        case BIP44NoHardening:\n            cointypeKeyPriv.Derive(accountKey, nAccountIndex); // m/44'/87'/n (BIP44 without hardening (for read only sync))\n            break;\n        default:\n            assert(0);\n        }\n        return new CAccountHD(accountKey, m_UUID);\n    }\n}\n\nstd::string CHDSeed::getUUID() const\n{\n    return boost::uuids::to_string(m_UUID);\n}\n\nSecureString CHDSeed::getMnemonic()\n{\n    return unencryptedMnemonic;\n}\n\nSecureString CHDSeed::getPubkey()\n{\n    return CBitcoinSecretExt<CExtPubKey>(masterKeyPub).ToString().c_str();\n}\n\nbool CHDSeed::IsLocked() const\n{\n    if (unencryptedMnemonic.size() > 0 || m_readOnly) {\n        return false;\n    }\n    return true;\n}\n\nbool CHDSeed::IsCrypted() const\n{\n    return encrypted;\n}\n\nbool CHDSeed::Lock()\n{\n\n    unencryptedMnemonic = \"\";\n\n    masterKeyPriv = CExtKey();\n    purposeKeyPriv = CExtKey();\n    cointypeKeyPriv = CExtKey();\n\n    vMasterKey.clear();\n\n    return true;\n}\n\nbool CHDSeed::Unlock(const CKeyingMaterial& vMasterKeyIn)\n{\n\n    assert(sizeof(m_UUID) == WALLET_CRYPTO_IV_SIZE);\n    CKeyingMaterial vchMnemonic;\n    if (!DecryptSecret(vMasterKeyIn, encryptedMnemonic, std::vector<unsigned char>(m_UUID.begin(), m_UUID.end()), vchMnemonic))\n        return false;\n    unencryptedMnemonic = SecureString(vchMnemonic.begin(), vchMnemonic.end());\n\n    CKeyingMaterial vchMasterKeyPrivEncoded;\n    if (!DecryptSecret(vMasterKeyIn, masterKeyPrivEncrypted, masterKeyPub.pubkey.GetHash(), vchMasterKeyPrivEncoded))\n        return false;\n    masterKeyPriv.Decode(vchMasterKeyPrivEncoded.data());\n\n    CKeyingMaterial vchPurposeKeyPrivEncoded;\n    if (!DecryptSecret(vMasterKeyIn, purposeKeyPrivEncrypted, purposeKeyPub.pubkey.GetHash(), vchPurposeKeyPrivEncoded))\n        return false;\n    purposeKeyPriv.Decode(vchPurposeKeyPrivEncoded.data());\n\n    CKeyingMaterial vchCoinTypeKeyPrivEncoded;\n    if (!DecryptSecret(vMasterKeyIn, cointypeKeyPrivEncrypted, cointypeKeyPub.pubkey.GetHash(), vchCoinTypeKeyPrivEncoded))\n        return false;\n    cointypeKeyPriv.Decode(vchCoinTypeKeyPrivEncoded.data());\n\n    vMasterKey = vMasterKeyIn;\n\n    return true;\n}\n\nbool CHDSeed::Encrypt(CKeyingMaterial& vMasterKeyIn)\n{\n\n    assert(sizeof(m_UUID) == WALLET_CRYPTO_IV_SIZE);\n    encryptedMnemonic.clear();\n    if (!EncryptSecret(vMasterKeyIn, CKeyingMaterial(unencryptedMnemonic.begin(), unencryptedMnemonic.end()), std::vector<unsigned char>(m_UUID.begin(), m_UUID.end()), encryptedMnemonic))\n        return false;\n\n    SecureUnsignedCharVector masterKeyPrivEncoded(BIP32_EXTKEY_SIZE);\n    masterKeyPriv.Encode(masterKeyPrivEncoded.data());\n    if (!EncryptSecret(vMasterKeyIn, CKeyingMaterial(masterKeyPrivEncoded.begin(), masterKeyPrivEncoded.end()), masterKeyPub.pubkey.GetHash(), masterKeyPrivEncrypted))\n        return false;\n\n    SecureUnsignedCharVector purposeKeyPrivEncoded(BIP32_EXTKEY_SIZE);\n    purposeKeyPriv.Encode(purposeKeyPrivEncoded.data());\n    if (!EncryptSecret(vMasterKeyIn, CKeyingMaterial(purposeKeyPrivEncoded.begin(), purposeKeyPrivEncoded.end()), purposeKeyPub.pubkey.GetHash(), purposeKeyPrivEncrypted))\n        return false;\n\n    SecureUnsignedCharVector cointypeKeyPrivEncoded(BIP32_EXTKEY_SIZE);\n    cointypeKeyPriv.Encode(cointypeKeyPrivEncoded.data());\n    if (!EncryptSecret(vMasterKeyIn, CKeyingMaterial(cointypeKeyPrivEncoded.begin(), cointypeKeyPrivEncoded.end()), cointypeKeyPub.pubkey.GetHash(), cointypeKeyPrivEncrypted))\n        return false;\n\n    encrypted = true;\n    vMasterKey = vMasterKeyIn;\n\n    return true;\n}\n\nCAccountHD::CAccountHD(CExtKey accountKey_, boost::uuids::uuid seedID)\n    : CAccount()\n    , m_SeedID(seedID)\n    , m_nIndex(accountKey_.nChild)\n    , m_nNextChildIndex(0)\n    , m_nNextChangeIndex(0)\n    , encrypted(false)\n    , accountKeyPriv(accountKey_)\n{\n    accountKeyPriv.Derive(primaryChainKeyPriv, 0); //a/0\n    accountKeyPriv.Derive(changeChainKeyPriv, 1); //a/1\n    primaryChainKeyPub = primaryChainKeyPriv.Neuter();\n    changeChainKeyPub = changeChainKeyPriv.Neuter();\n}\n\nCAccountHD::CAccountHD(CExtPubKey accountKey_, boost::uuids::uuid seedID)\n    : CAccount()\n    , m_SeedID(seedID)\n    , m_nIndex(accountKey_.nChild)\n    , m_nNextChildIndex(0)\n    , m_nNextChangeIndex(0)\n    , encrypted(false)\n{\n\n    accountKeyPriv.GetMutableKey().MakeNewKey(true);\n    primaryChainKeyPriv.GetMutableKey().MakeNewKey(true);\n    changeChainKeyPriv.GetMutableKey().MakeNewKey(true);\n\n    accountKey_.Derive(primaryChainKeyPub, 0); //a/0\n    accountKey_.Derive(changeChainKeyPub, 1); //a/1\n    m_readOnly = true;\n}\n\nvoid CAccountHD::GetKey(CExtKey& childKey, int nChain)\n{\n    assert(!m_readOnly);\n    if (nChain == KEYCHAIN_EXTERNAL) {\n        primaryChainKeyPriv.Derive(childKey, m_nNextChildIndex++);\n    } else {\n        changeChainKeyPriv.Derive(childKey, m_nNextChangeIndex++);\n    }\n}\n\nbool CAccountHD::GetKey(const CKeyID& keyID, CKey& key) const\n{\n    if (IsLocked())\n        return false;\n\n    assert(!m_readOnly);\n\n    int64_t nKeyIndex = -1;\n    CExtKey privKey;\n    if (externalKeyStore.GetKey(keyID, nKeyIndex)) {\n        primaryChainKeyPriv.Derive(privKey, nKeyIndex);\n        if (privKey.Neuter().pubkey.GetID() != keyID)\n            assert(0);\n        key = privKey.key;\n        return true;\n    }\n    if (internalKeyStore.GetKey(keyID, nKeyIndex)) {\n        changeChainKeyPriv.Derive(privKey, nKeyIndex);\n        if (privKey.Neuter().pubkey.GetID() != keyID)\n            assert(0);\n        key = privKey.key;\n        return true;\n    }\n    return false;\n}\n\nbool CAccountHD::GetKey(const CKeyID& address, std::vector<unsigned char>& encryptedKeyOut) const\n{\n    assert(0);\n}\n\nvoid CAccountHD::GetPubKey(CExtPubKey& childKey, int nChain) const\n{\n    if (nChain == KEYCHAIN_EXTERNAL) {\n        primaryChainKeyPub.Derive(childKey, m_nNextChildIndex++);\n    } else {\n        changeChainKeyPub.Derive(childKey, m_nNextChangeIndex++);\n    }\n}\n\nbool CAccountHD::GetPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const\n{\n    int64_t nKeyIndex = -1;\n    if (externalKeyStore.GetKey(address, nKeyIndex)) {\n        CExtPubKey extPubKey;\n        primaryChainKeyPub.Derive(extPubKey, nKeyIndex);\n        vchPubKeyOut = extPubKey.pubkey;\n        return true;\n    }\n    if (internalKeyStore.GetKey(address, nKeyIndex)) {\n        CExtPubKey extPubKey;\n        changeChainKeyPub.Derive(extPubKey, nKeyIndex);\n        vchPubKeyOut = extPubKey.pubkey;\n        return true;\n    }\n    return false;\n}\n\nbool CAccountHD::Lock()\n{\n    if (!IsReadOnly()) {\n        return true;\n    }\n\n    if (!encrypted)\n        return false;\n\n    accountKeyPriv = CExtKey();\n    primaryChainKeyPriv = CExtKey();\n    changeChainKeyPriv = CExtKey();\n\n    return true;\n}\n\nbool CAccountHD::Unlock(const CKeyingMaterial& vMasterKeyIn)\n{\n    assert(sizeof(accountUUID) == WALLET_CRYPTO_IV_SIZE);\n\n    if (IsReadOnly()) {\n        return true;\n    }\n\n    CKeyingMaterial vchAccountKeyPrivEncoded;\n    if (!DecryptSecret(vMasterKeyIn, accountKeyPrivEncrypted, std::vector<unsigned char>(accountUUID.begin(), accountUUID.end()), vchAccountKeyPrivEncoded))\n        return false;\n    accountKeyPriv.Decode(vchAccountKeyPrivEncoded.data());\n\n    CKeyingMaterial vchPrimaryChainKeyPrivEncoded;\n    if (!DecryptSecret(vMasterKeyIn, primaryChainKeyEncrypted, primaryChainKeyPub.pubkey.GetHash(), vchPrimaryChainKeyPrivEncoded))\n        return false;\n    primaryChainKeyPriv.Decode(vchPrimaryChainKeyPrivEncoded.data());\n\n    CKeyingMaterial vchChangeChainKeyPrivEncoded;\n    if (!DecryptSecret(vMasterKeyIn, changeChainKeyEncrypted, changeChainKeyPub.pubkey.GetHash(), vchChangeChainKeyPrivEncoded))\n        return false;\n    changeChainKeyPriv.Decode(vchChangeChainKeyPrivEncoded.data());\n\n    return true;\n}\n\nbool CAccountHD::Encrypt(CKeyingMaterial& vMasterKeyIn)\n{\n    assert(sizeof(accountUUID) == WALLET_CRYPTO_IV_SIZE);\n\n    if (IsReadOnly()) {\n        return true;\n    }\n\n    SecureUnsignedCharVector accountKeyPrivEncoded(BIP32_EXTKEY_SIZE);\n    accountKeyPriv.Encode(accountKeyPrivEncoded.data());\n    if (!EncryptSecret(vMasterKeyIn, CKeyingMaterial(accountKeyPrivEncoded.begin(), accountKeyPrivEncoded.end()), std::vector<unsigned char>(accountUUID.begin(), accountUUID.end()), accountKeyPrivEncrypted))\n        return false;\n\n    SecureUnsignedCharVector primaryChainKeyPrivEncoded(BIP32_EXTKEY_SIZE);\n    primaryChainKeyPriv.Encode(primaryChainKeyPrivEncoded.data());\n    if (!EncryptSecret(vMasterKeyIn, CKeyingMaterial(primaryChainKeyPrivEncoded.begin(), primaryChainKeyPrivEncoded.end()), primaryChainKeyPub.pubkey.GetHash(), primaryChainKeyEncrypted))\n        return false;\n\n    SecureUnsignedCharVector changeChainKeyPrivEncoded(BIP32_EXTKEY_SIZE);\n    changeChainKeyPriv.Encode(changeChainKeyPrivEncoded.data());\n    if (!EncryptSecret(vMasterKeyIn, CKeyingMaterial(changeChainKeyPrivEncoded.begin(), changeChainKeyPrivEncoded.end()), changeChainKeyPub.pubkey.GetHash(), changeChainKeyEncrypted))\n        return false;\n\n    encrypted = true;\n\n    return true;\n}\n\nbool CAccountHD::IsCrypted() const\n{\n    return encrypted;\n}\n\nbool CAccountHD::IsLocked() const\n{\n    return !accountKeyPriv.key.IsValid();\n}\n\nbool CAccountHD::AddKeyPubKey(const CKey& key, const CPubKey& pubkey, int keyChain)\n{\n\n    assert(0);\n    return true;\n}\n\nbool CAccountHD::AddKeyPubKey(int64_t HDKeyIndex, const CPubKey& pubkey, int keyChain)\n{\n    if (keyChain == KEYCHAIN_EXTERNAL)\n        return externalKeyStore.AddKeyPubKey(HDKeyIndex, pubkey);\n    else\n        return internalKeyStore.AddKeyPubKey(HDKeyIndex, pubkey);\n}\n\nCPubKey CAccountHD::GenerateNewKey(CWallet& wallet, int keyChain)\n{\n    CExtPubKey childKey;\n    do {\n        GetPubKey(childKey, keyChain);\n    } while (wallet.HaveKey(childKey.pubkey.GetID())); ///\n\n    LogPrintf(\"CAccount::GenerateNewKey(): NewHDKey [%s]\\n\", CBitcoinAddress(childKey.pubkey.GetID()).ToString());\n\n    if (!wallet.AddKeyPubKey(childKey.nChild, childKey.pubkey, *this, keyChain))\n        throw std::runtime_error(\"CAccount::GenerateNewKey(): AddKeyPubKey failed\");\n\n    return childKey.pubkey;\n}\n\nCExtKey* CAccountHD::GetAccountMasterPrivKey()\n{\n    if (IsLocked())\n        return NULL;\n\n    return &accountKeyPriv;\n}\n\nSecureString CAccountHD::GetAccountMasterPubKeyEncoded()\n{\n    if (IsLocked())\n        return NULL;\n\n    return CBitcoinSecretExt<CExtPubKey>(accountKeyPriv.Neuter()).ToString().c_str();\n}\n\nstd::string CAccountHD::getSeedUUID() const\n{\n    return boost::uuids::to_string(m_SeedID);\n}\n\nuint32_t CAccountHD::getIndex()\n{\n    return m_nIndex;\n}\n\nCAccount::CAccount()\n{\n    SetNull();\n\n    earliestPossibleCreationTime = GetTime();\n    accountUUID = boost::uuids::random_generator()();\n    parentUUID = boost::uuids::nil_generator()();\n    m_Type = AccountType::Normal;\n    m_SubType = AccountSubType::Desktop;\n    m_readOnly = false;\n}\n\nvoid CAccount::SetNull()\n{\n    vchPubKey = CPubKey();\n}\n\nCPubKey CAccount::GenerateNewKey(CWallet& wallet, int keyChain)\n{\n    CKey secret;\n    secret.MakeNewKey(true);\n\n    CPubKey pubkey = secret.GetPubKey();\n    assert(secret.VerifyPubKey(pubkey));\n\n    if (!wallet.AddKeyPubKey(secret, pubkey, *this, keyChain))\n        throw std::runtime_error(\"CAccount::GenerateNewKey(): AddKeyPubKey failed\");\n\n    return pubkey;\n}\n\nbool CAccount::HaveWalletTx(const CTransaction& tx)\n{\n    for (const CTxOut& txout : tx.vout) {\n        isminetype ret = isminetype::ISMINE_NO;\n        for (auto keyChain : { KEYCHAIN_EXTERNAL, KEYCHAIN_CHANGE }) {\n            isminetype temp = (keyChain == KEYCHAIN_EXTERNAL ? IsMine(externalKeyStore, txout.scriptPubKey) : IsMine(internalKeyStore, txout.scriptPubKey));\n            if (temp > ret)\n                ret = temp;\n        }\n        if (ret >= isminetype::ISMINE_NO)\n            return true;\n    }\n    for (const CTxIn& txin : tx.vin) {\n        isminetype ret = isminetype::ISMINE_NO;\n        std::map<uint256, CWalletTx>::const_iterator mi = pwalletMain->mapWallet.find(txin.prevout.hash);\n        if (mi != pwalletMain->mapWallet.end()) {\n            const CWalletTx& prev = (*mi).second;\n            if (txin.prevout.n < prev.vout.size()) {\n                for (const CTxOut& txout : prev.vout) {\n                    for (auto keyChain : { KEYCHAIN_EXTERNAL, KEYCHAIN_CHANGE }) {\n                        isminetype temp = (keyChain == KEYCHAIN_EXTERNAL ? IsMine(externalKeyStore, txout.scriptPubKey) : IsMine(internalKeyStore, txout.scriptPubKey));\n                        if (temp > ret)\n                            ret = temp;\n                    }\n                }\n            }\n        }\n        if (ret >= isminetype::ISMINE_NO)\n            return true;\n    }\n    return false;\n}\n\nbool CAccount::HaveKey(const CKeyID& address) const\n{\n    return externalKeyStore.HaveKey(address) || internalKeyStore.HaveKey(address);\n}\n\nbool CAccount::HaveWatchOnly(const CScript& dest) const\n{\n    return externalKeyStore.HaveWatchOnly(dest) || internalKeyStore.HaveWatchOnly(dest);\n}\n\nbool CAccount::HaveWatchOnly() const\n{\n    return externalKeyStore.HaveWatchOnly() || internalKeyStore.HaveWatchOnly();\n}\n\nbool CAccount::HaveCScript(const CScriptID& hash) const\n{\n    return externalKeyStore.HaveCScript(hash) || internalKeyStore.HaveCScript(hash);\n}\n\nbool CAccount::GetCScript(const CScriptID& hash, CScript& redeemScriptOut) const\n{\n    return externalKeyStore.GetCScript(hash, redeemScriptOut) || internalKeyStore.GetCScript(hash, redeemScriptOut);\n}\n\nbool CAccount::IsLocked() const\n{\n    return externalKeyStore.IsLocked() || internalKeyStore.IsLocked();\n}\n\nbool CAccount::IsCrypted() const\n{\n    return externalKeyStore.IsCrypted() || internalKeyStore.IsCrypted();\n}\n\nbool CAccount::Lock()\n{\n\n    vMasterKey.clear();\n\n    return externalKeyStore.Lock() && internalKeyStore.Lock();\n}\n\nbool CAccount::Unlock(const CKeyingMaterial& vMasterKeyIn)\n{\n    vMasterKey = vMasterKeyIn;\n\n    return externalKeyStore.Unlock(vMasterKeyIn) && internalKeyStore.Unlock(vMasterKeyIn);\n}\n\nbool CAccount::GetKey(const CKeyID& keyID, CKey& key) const\n{\n    return externalKeyStore.GetKey(keyID, key) || internalKeyStore.GetKey(keyID, key);\n}\n\nbool CAccount::GetKey(const CKeyID& address, std::vector<unsigned char>& encryptedKeyOut) const\n{\n    return externalKeyStore.GetKey(address, encryptedKeyOut) || internalKeyStore.GetKey(address, encryptedKeyOut);\n}\n\nvoid CAccount::GetKeys(std::set<CKeyID>& setAddress) const\n{\n    std::set<CKeyID> setExternal;\n    externalKeyStore.GetKeys(setExternal);\n    std::set<CKeyID> setInternal;\n    internalKeyStore.GetKeys(setInternal);\n    setAddress.clear();\n    setAddress.insert(setExternal.begin(), setExternal.end());\n    setAddress.insert(setInternal.begin(), setInternal.end());\n}\n\nbool CAccount::EncryptKeys(CKeyingMaterial& vMasterKeyIn)\n{\n    if (!externalKeyStore.EncryptKeys(vMasterKeyIn))\n        return false;\n    if (!internalKeyStore.EncryptKeys(vMasterKeyIn))\n        return false;\n\n    if (pwalletMain) {\n        if (!pwalletMain->fFileBacked)\n            return true;\n        {\n            std::set<CKeyID> setAddress;\n            GetKeys(setAddress);\n\n            LOCK(pwalletMain->cs_wallet);\n            for (const auto& keyID : setAddress) {\n                CPubKey pubKey;\n                if (!GetPubKey(keyID, pubKey)) {\n                    LogPrintf(\"CAccount::EncryptKeys(): Failed to get pubkey\");\n                    return false;\n                }\n                if (pwalletMain->pwalletdbEncryption)\n                    pwalletMain->pwalletdbEncryption->EraseKey(pubKey);\n                else\n                    CWalletDB(pwalletMain->strWalletFile).EraseKey(pubKey);\n\n                std::vector<unsigned char> secret;\n                if (!GetKey(keyID, secret)) {\n                    LogPrintf(\"CAccount::EncryptKeys(): Failed to get crypted key\");\n                    return false;\n                }\n                if (pwalletMain->pwalletdbEncryption) {\n                    if (!pwalletMain->pwalletdbEncryption->WriteCryptedKey(pubKey, secret, pwalletMain->mapKeyMetadata[keyID], getUUID(), KEYCHAIN_EXTERNAL)) {\n                        LogPrintf(\"CAccount::EncryptKeys(): Failed to write key\");\n                        return false;\n                    }\n                } else {\n                    if (!CWalletDB(pwalletMain->strWalletFile).WriteCryptedKey(pubKey, secret, pwalletMain->mapKeyMetadata[keyID], getUUID(), KEYCHAIN_EXTERNAL)) {\n                        LogPrintf(\"CAccount::EncryptKeys(): Failed to write key\");\n                        return false;\n                    }\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool CAccount::Encrypt(CKeyingMaterial& vMasterKeyIn)\n{\n    return EncryptKeys(vMasterKeyIn) /*&& SetCrypted()*/;\n}\n\nbool CAccount::GetPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const\n{\n    return externalKeyStore.GetPubKey(address, vchPubKeyOut) || internalKeyStore.GetPubKey(address, vchPubKeyOut);\n}\n\nbool CAccount::AddKeyPubKey(const CKey& key, const CPubKey& pubkey, int keyChain)\n{\n    std::vector<unsigned char> encryptedKeyOut;\n    if (keyChain == KEYCHAIN_EXTERNAL) {\n        return externalKeyStore.AddKeyPubKey(key, pubkey);\n        /*if (externalKeyStore.AddKeyPubKey(key, pubkey))\n        {\n            if (externalKeyStore.GetKey(pubkey.GetID(), encryptedKeyOut))\n            {\n                return AddCryptedKey(pubkey, encryptedKeyOut, keyChain);\n            }\n        }\n        return false;*/\n    } else {\n        return internalKeyStore.AddKeyPubKey(key, pubkey);\n    }\n}\n\nbool CAccount::AddKeyPubKey(int64_t HDKeyIndex, const CPubKey& pubkey, int keyChain)\n{\n\n    assert(0);\n    return true;\n}\n\nbool CAccount::AddWatchOnly(const CScript& dest)\n{\n\n    assert(0);\n    return externalKeyStore.AddWatchOnly(dest);\n}\n\nbool CAccount::RemoveWatchOnly(const CScript& dest)\n{\n\n    assert(0);\n    return externalKeyStore.RemoveWatchOnly(dest) || internalKeyStore.RemoveWatchOnly(dest);\n}\n\nbool CAccount::AddCScript(const CScript& redeemScript)\n{\n    return externalKeyStore.AddCScript(redeemScript);\n}\n\nbool CAccount::AddCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, int64_t nKeyChain)\n{\n\n    assert(!IsHD());\n\n    if (nKeyChain == KEYCHAIN_EXTERNAL) {\n        if (!externalKeyStore.AddCryptedKey(vchPubKey, vchCryptedSecret))\n            return false;\n    } else {\n        if (!internalKeyStore.AddCryptedKey(vchPubKey, vchCryptedSecret))\n            return false;\n    }\n\n    if (pwalletMain) {\n        if (!pwalletMain->fFileBacked)\n            return true;\n        {\n            LOCK(pwalletMain->cs_wallet);\n            if (pwalletMain->pwalletdbEncryption)\n                return pwalletMain->pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, pwalletMain->mapKeyMetadata[vchPubKey.GetID()], getUUID(), nKeyChain);\n            else\n                return CWalletDB(pwalletMain->strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, pwalletMain->mapKeyMetadata[vchPubKey.GetID()], getUUID(), nKeyChain);\n        }\n    } else {\n        return true;\n    }\n    return false;\n}\n\nvoid CAccount::AddChild(CAccount* childAccount)\n{\n    childAccount->parentUUID = accountUUID;\n}\n\nvoid CAccount::possiblyUpdateEarliestTime(uint64_t creationTime, CWalletDB* Db)\n{\n    if (creationTime < earliestPossibleCreationTime)\n        earliestPossibleCreationTime = creationTime;\n\n    if (Db) {\n        Db->WriteAccount(getUUID(), this);\n    }\n}\n\nuint64_t CAccount::getEarliestPossibleCreationTime()\n{\n    return earliestPossibleCreationTime;\n}\n\nunsigned int CAccount::GetKeyPoolSize()\n{\n    AssertLockHeld(cs_keypool); // setKeyPool\n    return setKeyPoolExternal.size();\n}\n\nstd::string CAccount::getLabel() const\n{\n    return accountLabel;\n}\n\nvoid CAccount::setLabel(const std::string& label, CWalletDB* Db)\n{\n    accountLabel = label;\n    if (Db) {\n        Db->EraseAccountLabel(getUUID());\n        Db->WriteAccountLabel(getUUID(), label);\n    }\n}\n\nstd::string CAccount::getUUID() const\n{\n    return boost::uuids::to_string(accountUUID);\n}\n\nvoid CAccount::setUUID(const std::string& stringUUID)\n{\n    accountUUID = boost::lexical_cast<boost::uuids::uuid>(stringUUID);\n}\n\nstd::string CAccount::getParentUUID() const\n{\n    if (parentUUID == boost::uuids::nil_generator()())\n        return \"\";\n    return boost::uuids::to_string(parentUUID);\n}\n", "meta": {"hexsha": "a5ec158ee652ba3ff1ce422aab98e2c787da6c4a", "size": 24926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/account.cpp", "max_stars_repo_name": "guldenchain/gulden-unofficial", "max_stars_repo_head_hexsha": "b2d91788d2ba3387cf7dead1d26389f3a6747ec8", "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/account.cpp", "max_issues_repo_name": "guldenchain/gulden-unofficial", "max_issues_repo_head_hexsha": "b2d91788d2ba3387cf7dead1d26389f3a6747ec8", "max_issues_repo_licenses": ["MIT"], "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/account.cpp", "max_forks_repo_name": "guldenchain/gulden-unofficial", "max_forks_repo_head_hexsha": "b2d91788d2ba3387cf7dead1d26389f3a6747ec8", "max_forks_repo_licenses": ["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.1402660218, "max_line_length": 207, "alphanum_fraction": 0.6812164005, "num_tokens": 6509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.1782418560078695}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SIMD_FNMA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIMD_FNMA_HPP_INCLUDED\n\n#include <boost/simd/function/scalar/fnma.hpp>\n#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>\n#include <boost/simd/arch/common/simd/function/fnma.hpp>\n\n#if defined(BOOST_HW_SIMD_X86_OR_AMD_AVAILABLE)\n#  if BOOST_HW_SIMD_X86_AMD_FMA4\n#    include <boost/simd/arch/x86/fma4/simd/function/fnma.hpp>\n#  endif\n#  if BOOST_HW_SIMD_X86_FMA3\n#    include <boost/simd/arch/x86/fma3/simd/function/fnma.hpp>\n#  endif\n#endif\n\n#endif\n", "meta": {"hexsha": "ac688e62a26f64477ba89df437798f710cb1f801", "size": 931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/simd/fnma.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/simd/fnma.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/simd/fnma.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": 34.4814814815, "max_line_length": 100, "alphanum_fraction": 0.619763695, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.1782386626285055}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <scitbx/array_family/boost_python/flex_wrapper.h>\n#include <scitbx/array_family/boost_python/flex_pickle_double_buffered.h>\n#include <scitbx/array_family/boost_python/ref_pickle_double_buffered.h>\n#include <boost/python/args.hpp>\n#include <boost/python/return_internal_reference.hpp>\n\n#include <spotfinder/core_toolbox/distl.h>\n\nnamespace scitbx { namespace af { namespace boost_python {\n\nnamespace {\n\n  struct to_string_ir : pickle_double_buffered::to_string\n  {\n    using pickle_double_buffered::to_string::operator<<;\n\n    to_string_ir()\n    {\n      int version = 1;\n      *this << version;\n    }\n\n    to_string_ir& operator<<(Distl::icering const& val)\n    {\n      *this << val.lowerr2\n            << val.upperr2\n            << val.lowerresol\n            << val.upperresol\n            << val.strength;\n      return *this;\n    }\n  };\n\n  struct from_string_ir : pickle_double_buffered::from_string\n  {\n    from_string_ir(const char* str_ptr)\n    : pickle_double_buffered::from_string(str_ptr)\n    {\n          *this >> version;\n    }\n\n    using pickle_double_buffered::from_string::operator>>;\n\n    from_string_ir& operator>>(Distl::icering& val)\n    {\n      Distl::point lpeak;\n\n      *this >> val.lowerr2\n            >> val.upperr2\n            >> val.lowerresol\n            >> val.upperresol\n            >> val.strength;\n      return *this;\n    }\n\n    int version;\n  };\n\n  struct to_string : pickle_double_buffered::to_string\n  {\n    using pickle_double_buffered::to_string::operator<<;\n\n    to_string()\n    {\n      int version = 2; //Current version for flex_distl_spot\n      //printf(\"Pickle flex_distl_spot; version: %d\\n\", version);\n      *this << version;\n    }\n\n    to_string& operator<<(scitbx::vec2<double> const& vec)\n    {\n      //special time saver for 2D profiles:  ignore z-direction\n      *this << (float)vec[0] << (float)vec[1];\n      return *this;\n    }\n\n    to_string& operator<<(spotfinder::distltbx::w_spot const& val)\n    {\n      *this << val.max_pxl_x()\n            << val.max_pxl_y()\n            << val.peakintensity\n            << val.bodypixels.size();\n\n      for (int i=0; i<val.bodypixels.size(); ++i){\n      *this << val.bodypixels[i].x\n            << val.bodypixels[i].y;\n      }\n\n      *this << val.total_mass;\n      to_string::operator<<(val.model_m->center_of_mass());\n      *this << (float)val.model_m->eigenvalue(0)\n            << (float)val.model_m->eigenvalue(1);\n\n      to_string::operator<<(val.model_m->eigenvector(0));\n      to_string::operator<<(val.model_m->eigenvector(1));\n\n      return *this;\n    }\n  };\n\n  struct from_string : pickle_double_buffered::from_string\n  {\n    from_string(const char* str_ptr)\n    : pickle_double_buffered::from_string(str_ptr)\n    {\n      *this >> version;\n      //printf(\"Unpickle flex_distl_spot; version: %d\\n\", version);\n    }\n\n    from_string& operator>>(scitbx::vec2<double>& vec)\n    {\n      //special time saver for 2D profiles:  ignore z-direction\n      float a,b;\n      *this >> a >> b;\n      vec[0] = (double)a; vec[1] = (double)b;\n      return *this;\n    }\n\n    using pickle_double_buffered::from_string::operator>>;\n\n    from_string& operator>>(spotfinder::distltbx::w_spot& val)\n    {\n      int iptx,ipty,bodylen;\n      Distl::point lpeak;\n\n      *this >> iptx\n            >> ipty;\n      lpeak = Distl::point(iptx,ipty);\n      *this >> val.peakintensity\n            >> bodylen;\n\n      val.bodypixels = scitbx::af::shared<Distl::point>();\n      for (int i=0; i<bodylen; ++i){\n      *this >> iptx\n            >> ipty;\n        val.bodypixels.push_back(Distl::point(iptx,ipty));\n      }\n\n      val.setstate(lpeak);\n      if (version == 2) {\n        double mass;\n        *this >> mass;\n        scitbx::vec2<double> com,value,axis0,axis1;\n        float a,b;\n        from_string::operator>>(com);\n        *this >> a >> b;\n        value[0] = (double)a; value[1] = (double)b;\n        from_string::operator>>(axis0);\n        from_string::operator>>(axis1);\n        val.ss_setstate(com,value,axis0,axis1,mass);\n      }\n      return *this;\n    }\n\n    int version;\n  };\n\n}}}} // namespace scitbx::af::boost_python::<anonymous>\n\n\nnamespace scitbx { namespace af { namespace boost_python {\n\n  void wrap_flex_icering()\n  {\n    flex_wrapper<Distl::icering,\n                 boost::python::return_internal_reference<>\n                 >::plain(\"distl_icering\")\n    .def_pickle(flex_pickle_double_buffered<\n                 Distl::icering, to_string_ir, from_string_ir>())\n    ;\n  }\n\n  af::shared<double>\n  ctr_mass_distances_from_direct_beam(\n    af::const_ref<spotfinder::distltbx::w_spot> const& spots,\n    scitbx::vec2<double> detector_size,\n    scitbx::vec2<int> detector_pixels,\n    scitbx::vec2<double> xy_beam)\n  {\n    af::shared<double> result(\n      spots.size(),\n      af::init_functor_null<double>());\n    scitbx::vec2<double> sop;\n    for(std::size_t i=0;i<2;i++) {\n      sop[i] = detector_size[i] / detector_pixels[i];\n    }\n    double const* b = xy_beam.begin();\n    for(std::size_t i=0;i<spots.size();i++) {\n      spotfinder::distltbx::w_spot const& spot = spots[i];\n      double dx = spot.ctr_mass_x() * sop[0] - b[0];\n      double dy = spot.ctr_mass_y() * sop[1] - b[1];\n      result[i] = std::sqrt(dx*dx + dy*dy);\n    }\n    return result;\n  }\n\n  void wrap_flex_w_spot()\n  {\n    using boost::python::arg;\n    flex_wrapper<spotfinder::distltbx::w_spot,\n                 boost::python::return_internal_reference<>\n                 >::plain(\"distl_spot\")\n    .def_pickle(flex_pickle_double_buffered<\n                 spotfinder::distltbx::w_spot, to_string, from_string>())\n    .def(\"ctr_mass_distances_from_direct_beam\",\n      ctr_mass_distances_from_direct_beam, (\n        arg(\"detector_size\"),\n        arg(\"detector_pixels\"),\n        arg(\"xy_beam\")))\n    ;\n  }\n\n  void wrap_flex_point()\n  {\n    flex_wrapper<Distl::point>::plain(\"distl_point\");\n  }\n\n}}} // namespace scitbx::af::boost_python\n", "meta": {"hexsha": "82f308d2d08e7afe899807b1f6db128e53b56e83", "size": 5932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spotfinder/array_family/flex_distl_spot.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/array_family/flex_distl_spot.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/array_family/flex_distl_spot.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": 26.8416289593, "max_line_length": 73, "alphanum_fraction": 0.6058664869, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.17823865983460205}}
{"text": "#include \"crypto_highlevel.h\"\n\n#include \"JsonStringQueue.h\"\n#include \"hash.h\"\n#include <boost/algorithm/hex.hpp>\n#include <boost/algorithm/string.hpp>\n#include <openssl/err.h>\n#include <openssl/rand.h>\n#include <openssl/sha.h>\n\nCHL::Bytes Crypto_HighLevel::XSalsa20poly1305_EncryptBlock(\n    const CHL::Bytes&                                                              msg,\n    const std::array<unsigned char, crypto_secretbox_xsalsa20poly1305_NONCEBYTES>& nonce,\n    const SecureArray<unsigned char, crypto_secretbox_xsalsa20poly1305_KEYBYTES>&  key)\n{\n    if (msg.size() == 0) {\n        throw std::runtime_error(\"Cannot encrypt an empty message\");\n    }\n\n    const int msg_nacl_input_size = msg.size() + crypto_secretbox_ZEROBYTES;\n    // the message passed to nacl is expected to be:\n    // 32 bytes (zeros) + X bytes (message)\n    if (msg.size() + crypto_secretbox_ZEROBYTES > MAX_CRYPTOSECRETBOX_MSG_SIZE) {\n        throw std::runtime_error(\n            \"NaCl message size is larger than max: \" +\n            std::to_string(MAX_CRYPTOSECRETBOX_MSG_SIZE - crypto_secretbox_ZEROBYTES));\n    }\n    std::array<unsigned char, MAX_CRYPTOSECRETBOX_MSG_SIZE> msg_for_nacl;\n    memset(&msg_for_nacl.front(), 0, crypto_secretbox_ZEROBYTES); // reset first bytes\n    std::copy(msg.cbegin(), msg.cend(), msg_for_nacl.begin() + crypto_secretbox_ZEROBYTES);\n    std::array<unsigned char, MAX_CRYPTOSECRETBOX_MSG_SIZE> cipher;\n    memset(&cipher.front(), 0, cipher.size());\n    if (int r = crypto_secretbox_xsalsa20poly1305((unsigned char*)&cipher.front(),\n                                                  (const unsigned char*)&msg_for_nacl.front(),\n                                                  msg_nacl_input_size, nonce.data(), key.data())) {\n        throw std::runtime_error(\"crypto_secretbox_xsalsa20poly1305() returned a non-zero value: \" +\n                                 std::to_string(r));\n    }\n\n    CHL::Bytes res;\n    std::move(cipher.begin() + crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES,\n              cipher.begin() + crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES +\n                  crypto_secretbox_xsalsa20poly1305_MACBYTES + msg.size(),\n              std::back_inserter(res));\n    return res;\n}\n\nCHL::Bytes Crypto_HighLevel::XSalsa20poly1305_DecryptBlock(\n    const CHL::Bytes&                                                              cipher,\n    const std::array<unsigned char, crypto_secretbox_xsalsa20poly1305_NONCEBYTES>& nonce,\n    const SecureArray<unsigned char, crypto_secretbox_xsalsa20poly1305_KEYBYTES>&  key)\n{\n    // the cipher is expected to be:\n    // 16 bytes (MAC) + X bytes (cipher)\n    if (cipher.size() <= crypto_secretbox_MACBYTES) {\n        throw std::runtime_error(\"Very short cipher provided; it must be larger than \" +\n                                 std::to_string(crypto_secretbox_MACBYTES));\n    }\n\n    const int cipher_nacl_input_size = cipher.size() + crypto_secretbox_BOXZEROBYTES;\n    // the cipher passed to nacl is expected to be:\n    // 16 bytes (zeros) + 16 bytes (MAC) + X bytes (cipher)\n\n    if (cipher_nacl_input_size > MAX_CRYPTOSECRETBOX_MSG_SIZE) {\n        throw std::runtime_error(\n            \"NaCl cipher size is larger than max: \" +\n            std::to_string(MAX_CRYPTOSECRETBOX_MSG_SIZE - crypto_secretbox_BOXZEROBYTES));\n    }\n    std::array<unsigned char, MAX_CRYPTOSECRETBOX_MSG_SIZE> cipher_for_nacl;\n    memset(&cipher_for_nacl.front(), 0, crypto_secretbox_BOXZEROBYTES); // reset first bytes\n    std::copy(cipher.cbegin(), cipher.cend(), cipher_for_nacl.begin() + crypto_secretbox_BOXZEROBYTES);\n    std::array<unsigned char, MAX_CRYPTOSECRETBOX_MSG_SIZE> msg_output;\n    if (int r = crypto_secretbox_xsalsa20poly1305_open(\n            (unsigned char*)&msg_output, (const unsigned char*)&cipher_for_nacl.front(),\n            cipher_nacl_input_size, nonce.data(), key.data())) {\n        throw std::runtime_error(\"crypto_secretbox_xsalsa20poly1305_open() returned a non-zero value: \" +\n                                 std::to_string(r));\n    }\n\n    CHL::Bytes res;\n    std::move(msg_output.begin() + crypto_secretbox_ZEROBYTES,\n              msg_output.begin() + crypto_secretbox_ZEROBYTES + cipher.size() -\n                  crypto_secretbox_BOXZEROBYTES,\n              std::back_inserter(res));\n    return res;\n}\n\nstd::array<unsigned char, crypto_secretbox_xsalsa20poly1305_NONCEBYTES>\nCrypto_HighLevel::GenSalsa20poly1305RandomNonce()\n{\n    std::array<unsigned char, crypto_secretbox_xsalsa20poly1305_NONCEBYTES> res;\n    CHL::Bytes randomBytes = CHL::RandomBytes(crypto_secretbox_xsalsa20poly1305_NONCEBYTES);\n    std::move(randomBytes.begin(), randomBytes.end(), res.begin());\n    return res;\n}\n\nCHL::SecureArray<unsigned char, crypto_secretbox_xsalsa20poly1305_KEYBYTES>\nCrypto_HighLevel::GetCanonicalSalsa20poly1305Key(const SecureBytes& key, const std::string& algoName)\n{\n    if (key.size() != crypto_secretbox_xsalsa20poly1305_KEYBYTES) {\n        throw std::runtime_error(\"Invalid key size for algorithm: \" + algoName);\n    }\n    SecureArray<unsigned char, crypto_secretbox_xsalsa20poly1305_KEYBYTES> keyIn;\n    std::copy(key.cbegin(), key.cend(), keyIn.begin());\n    return keyIn;\n}\n\nCHL::Bytes Crypto_HighLevel::XSalsa20poly1305_EncryptLongMsg_CTR(\n    const Crypto_HighLevel::Bytes&                                                msg,\n    std::array<unsigned char, crypto_secretbox_xsalsa20poly1305_NONCEBYTES>       nonce,\n    const SecureArray<unsigned char, crypto_secretbox_xsalsa20poly1305_KEYBYTES>& key)\n{\n    static_assert(std::tuple_size<decltype(nonce)>::value ==\n                      crypto_secretbox_xsalsa20poly1305_NONCEBYTES,\n                  \"nonce size sould be equal to 24 (crypto_secretbox_xsalsa20poly1305_NONCEBYTES)\");\n    static_assert(crypto_secretbox_xsalsa20poly1305_NONCEBYTES == 24,\n                  \"crypto_secretbox_xsalsa20poly1305_NONCEBYTES is expected to have size 24 bytes\");\n\n    if (msg.empty()) {\n        throw std::runtime_error(\"Cannot encrypt empty message\");\n    }\n    if (msg.size() >= std::numeric_limits<uint32_t>::max()) {\n        throw std::runtime_error(\"Message too big to encrypt, even in chain\");\n    }\n    CHL::Bytes res;\n    uint32_t   ptr = 0;\n\n    // write the nonce to the result (24 bytes)\n    std::copy(nonce.begin(), nonce.end(), std::back_inserter(res));\n\n    while (msg.size() > ptr) {\n        uint32_t currSize = msg.size() - ptr > CHL::MAX_CRYPTOSECRETBOX_ENCRYPTABLE_MSG_SIZE\n                                ? CHL::MAX_CRYPTOSECRETBOX_ENCRYPTABLE_MSG_SIZE\n                                : msg.size() - ptr;\n        CHL::Bytes toEnc(msg.cbegin() + ptr, msg.cbegin() + ptr + currSize);\n        CHL::Bytes cipher = CHL::XSalsa20poly1305_EncryptBlock(toEnc, nonce, key);\n        ptr += currSize;\n        static_assert(sizeof(currSize) == 4, \"\");\n        // copy size to result\n        uint32_t sizeToStore = currSize + crypto_secretbox_MACBYTES;\n        assert(sizeToStore == cipher.size());\n        auto sizeToStoreRaw = SerializeSimple(sizeToStore);\n        std::copy((unsigned char*)&sizeToStoreRaw,\n                  (unsigned char*)&sizeToStoreRaw + sizeof(sizeToStoreRaw), std::back_inserter(res));\n        std::copy(cipher.begin(), cipher.end(), std::back_inserter(res));\n        IncrementNonce(nonce);\n    }\n    return res;\n}\n\nstd::array<uint8_t, crypto_onetimeauth_poly1305_BYTES> Crypto_HighLevel::Poly1305AuthenticateMessage(\n    const Crypto_HighLevel::Bytes&                                          msg,\n    const SecureArray<unsigned char, crypto_onetimeauth_poly1305_KEYBYTES>& key)\n{\n    std::array<uint8_t, crypto_onetimeauth_poly1305_BYTES> result;\n    if (crypto_onetimeauth_poly1305(result.data(), msg.data(), msg.size(), key.data()) != 0) {\n        throw std::runtime_error(\"Authentication tag creation failed\");\n    }\n    return result;\n}\n\nbool Crypto_HighLevel::Poly1305VerifyMessage(\n    const Crypto_HighLevel::Bytes&                                          msg,\n    const std::array<uint8_t, crypto_onetimeauth_poly1305_BYTES>&           tag,\n    const SecureArray<unsigned char, crypto_onetimeauth_poly1305_KEYBYTES>& key)\n{\n    if (crypto_onetimeauth_verify(tag.data(), msg.data(), msg.size(), key.data()) == 0) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\nCrypto_HighLevel::Bytes Crypto_HighLevel::XSalsa20poly1305_DecryptLongMsg_CTR(\n    const Crypto_HighLevel::Bytes&                                                cipher,\n    const SecureArray<unsigned char, crypto_secretbox_xsalsa20poly1305_KEYBYTES>& key)\n{\n    std::array<unsigned char, crypto_secretbox_xsalsa20poly1305_NONCEBYTES> nonce;\n    static_assert(std::tuple_size<decltype(nonce)>::value ==\n                      crypto_secretbox_xsalsa20poly1305_NONCEBYTES,\n                  \"nonce size sould be equal to 24 (crypto_secretbox_xsalsa20poly1305_NONCEBYTES)\");\n    static_assert(crypto_secretbox_xsalsa20poly1305_NONCEBYTES == 24,\n                  \"crypto_secretbox_xsalsa20poly1305_NONCEBYTES is expected to have size 24 bytes\");\n    if (cipher.size() <= crypto_secretbox_xsalsa20poly1305_NONCEBYTES + 4) {\n        throw std::runtime_error(\"Cipher too small\");\n    }\n\n    CHL::Bytes res;\n    uint32_t   ptr = 0;\n\n    std::copy(cipher.cbegin(), cipher.cbegin() + crypto_secretbox_xsalsa20poly1305_NONCEBYTES,\n              nonce.begin());\n    ptr += crypto_secretbox_xsalsa20poly1305_NONCEBYTES;\n    while (cipher.size() > ptr) {\n        static constexpr const int sizeOfSize = 4;\n        // deserialize the size\n        std::array<uint8_t, sizeOfSize> currSizeRaw;\n        std::memcpy(currSizeRaw.data(), &cipher.front() + ptr, sizeOfSize);\n        ptr += sizeof(sizeOfSize);\n        uint32_t currSize = DeserializeSimple<uint32_t>(currSizeRaw);\n        // ensure current size is valid\n        if (currSize > CHL::MAX_CRYPTOSECRETBOX_MSG_SIZE) {\n            throw std::runtime_error(\"Chunk is larger than allowed limit\");\n        }\n        if (currSize > static_cast<int64_t>(cipher.size()) - static_cast<int64_t>(ptr)) {\n            throw std::runtime_error(\"Remaining size of cipher not enough to cover the next chunk size\");\n        }\n        // decrypt\n        CHL::Bytes toDec;\n        std::copy(cipher.begin() + ptr, cipher.begin() + ptr + currSize, std::back_inserter(toDec));\n        CHL::Bytes msg = CHL::XSalsa20poly1305_DecryptBlock(toDec, nonce, key);\n        ptr += currSize;\n        std::copy(msg.cbegin(), msg.cend(), std::back_inserter(res));\n        IncrementNonce(nonce);\n    }\n    return res;\n}\n\nCHL::SecureArray<unsigned char, crypto_secretbox_xsalsa20poly1305_KEYBYTES>\nCrypto_HighLevel::GenXSalsa20poly1305RandomKey()\n{\n    SecureBytes d = RandomBytes_Secure(crypto_secretbox_xsalsa20poly1305_KEYBYTES);\n    SecureArray<unsigned char, crypto_secretbox_xsalsa20poly1305_KEYBYTES> res;\n    std::memcpy(res.data(), d.data(), res.size());\n    return res;\n}\n\nCrypto_HighLevel::String Crypto_HighLevel::GetOpenSSLErrorMsg()\n{\n    std::vector<char> errorMsgChars;\n    errorMsgChars.resize(120);\n    std::fill(errorMsgChars.begin(), errorMsgChars.end(), ' ');\n    ERR_load_crypto_strings();\n    ERR_load_ERR_strings();\n    ERR_error_string_n(ERR_get_error(), &errorMsgChars.front(), errorMsgChars.size());\n    // remove extra spaces\n    errorMsgChars.erase(std::find_if(errorMsgChars.rbegin(), errorMsgChars.rend(),\n                                     std::not1(std::ptr_fun<int, int>(std::isspace)))\n                            .base(),\n                        errorMsgChars.end());\n    std::string errMsg(errorMsgChars.begin(), errorMsgChars.end());\n    return errMsg;\n}\n\nCrypto_HighLevel::Bytes Crypto_HighLevel::RandomBytes(uint64_t length)\n{\n    if (length <= 0) {\n        throw std::invalid_argument(\"Length should be positive\");\n    }\n    Bytes result(length);\n    if (RAND_bytes(result.data(), result.size()) != 1) {\n        std::string msg = GetOpenSSLErrorMsg();\n        throw std::runtime_error(\"Error generating a good random number: \" + msg);\n    }\n    return result;\n}\n\nCrypto_HighLevel::SecureBytes Crypto_HighLevel::RandomBytes_Secure(uint64_t length)\n{\n    if (length <= 0) {\n        throw std::invalid_argument(\"Length should be positive\");\n    }\n    SecureBytes result(length);\n    if (RAND_bytes(result.data(), result.size()) != 1) {\n        std::string msg = GetOpenSSLErrorMsg();\n        throw std::runtime_error(\"Error generating a good random number: \" + msg);\n    }\n    return result;\n}\n\nboost::optional<std::string>\nCrypto_HighLevel::GetEncryptionAlgoName(Crypto_HighLevel::EncryptionAlgorithm algo)\n{\n    switch (algo) {\n    case CHL::EncryptionAlgorithm::Enc_XSalsa20Poly1305:\n        return std::string(XSalsa20Poly1305AlgoName);\n    case CHL::EncryptionAlgorithm::Enc_Size:\n        return boost::none;\n    }\n    return boost::none;\n}\n\nCrypto_HighLevel::EncryptionAlgorithm Crypto_HighLevel::GetEncryptionAlgoFromName(const StringViewT name)\n{\n    if (name == XSalsa20Poly1305AlgoName) {\n        return EncryptionAlgorithm::Enc_XSalsa20Poly1305;\n    } else {\n        throw std::domain_error(\"Unknown encryption algorithm with name: \" + name.to_string());\n    }\n}\n\nboost::optional<uint64_t> Crypto_HighLevel::GetEncryptionAlgoKeyLength(EncryptionAlgorithm algo)\n{\n    switch (algo) {\n    case CHL::EncryptionAlgorithm::Enc_XSalsa20Poly1305:\n        return crypto_secretbox_xsalsa20poly1305_KEYBYTES;\n    case CHL::EncryptionAlgorithm::Enc_Size:\n        return boost::none;\n    }\n    return boost::none;\n}\n\nboost::optional<std::string>\nCrypto_HighLevel::GetRatchetAlgoName(Crypto_HighLevel::AuthKeyRatchetAlgorithm algo)\n{\n    switch (algo) {\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha256:\n        return std::string(Sha256RatchetName);\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha384:\n        return std::string(Sha384RatchetName);\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha512:\n        return std::string(Sha512RatchetName);\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Size:\n        return boost::none;\n    }\n    return boost::none;\n}\n\nCrypto_HighLevel::AuthKeyRatchetAlgorithm\nCrypto_HighLevel::GetRatchetAlgoFromName(const StringViewT name)\n{\n    if (name == Sha256RatchetName) {\n        return AuthKeyRatchetAlgorithm::Ratchet_Sha256;\n    } else if (name == Sha384RatchetName) {\n        return AuthKeyRatchetAlgorithm::Ratchet_Sha384;\n    } else if (name == Sha512RatchetName) {\n        return AuthKeyRatchetAlgorithm::Ratchet_Sha512;\n    } else {\n        throw std::domain_error(\"Unknown key ratchet algorithm with name: \" + name.to_string());\n    }\n}\n\nboost::optional<uint64_t>\nCrypto_HighLevel::GetRatchetAlgoOutputLength(Crypto_HighLevel::AuthKeyRatchetAlgorithm algo)\n{\n    switch (algo) {\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha256:\n        return SHA256_DIGEST_LENGTH;\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha384:\n        return SHA384_DIGEST_LENGTH;\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha512:\n        return SHA512_DIGEST_LENGTH;\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Size:\n        return boost::none;\n    }\n    return boost::none;\n}\n\nboost::optional<uint64_t>\nCrypto_HighLevel::GetAuthAlgoKeyLength(Crypto_HighLevel::AuthenticationAlgorithm algo)\n{\n    switch (algo) {\n    case CHL::AuthenticationAlgorithm::Auth_Poly1305:\n        return crypto_onetimeauth_poly1305_KEYBYTES;\n    case CHL::AuthenticationAlgorithm::Auth_Size:\n        return boost::none;\n    }\n    return boost::none;\n}\n\nboost::optional<std::string>\nCrypto_HighLevel::GetAuthAlgoName(Crypto_HighLevel::AuthenticationAlgorithm algo)\n{\n    switch (algo) {\n    case CHL::AuthenticationAlgorithm::Auth_Poly1305:\n        return std::string(Poly1305AlgoName);\n    case CHL::AuthenticationAlgorithm::Auth_Size:\n        return boost::none;\n    }\n    return boost::none;\n}\n\nCrypto_HighLevel::AuthenticationAlgorithm Crypto_HighLevel::GetAuthAlgoFromName(StringViewT name)\n{\n    if (name == XSalsa20Poly1305AlgoName) {\n        return AuthenticationAlgorithm::Auth_Poly1305;\n    } else {\n        throw std::domain_error(\"Unknown authentication algorithm with name: \" + name.to_string());\n    }\n}\n\nCHL::SecureBytes CHL::CalculateKeyRatchet(CHL::AuthKeyRatchetAlgorithm keyRatchetAlgo,\n                                          const SecureBytes&           key,\n                                          boost::optional<uint64_t>    authenticationAlgoKeyLen)\n{\n    CHL::SecureBytes authKey;\n\n    switch (keyRatchetAlgo) {\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha256: {\n        Sha256Calculator calc;\n        calc.push_data(std::vector<unsigned char>(key.cbegin(), key.cend()));\n        authKey = ToSecureBytes(calc.getHashAndReset());\n        break;\n    }\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha384: {\n        Sha384Calculator calc;\n        calc.push_data(std::vector<unsigned char>(key.cbegin(), key.cend()));\n        authKey = ToSecureBytes(calc.getHashAndReset());\n        break;\n    }\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Sha512: {\n        Sha512Calculator calc;\n        calc.push_data(std::vector<unsigned char>(key.cbegin(), key.cend()));\n        authKey = ToSecureBytes(calc.getHashAndReset());\n        break;\n    }\n    case CHL::AuthKeyRatchetAlgorithm::Ratchet_Size: {\n        throw std::logic_error(\"Size enum element used as auth key ratchet algorithm\");\n    }\n    }\n\n    if (authenticationAlgoKeyLen.is_initialized()) {\n        // reduce the key size to the appropriate key size\n        assert(authKey.size() >= authenticationAlgoKeyLen.get());\n        authKey.resize(authenticationAlgoKeyLen.get());\n    }\n\n    return authKey;\n}\n\nCHL::EncryptMessageOutput CHL::EncryptMessage(const CHL::Bytes& message, const SecureBytes& key,\n                                              EncryptionAlgorithm     encAlgo,\n                                              AuthKeyRatchetAlgorithm keyRatchetAlgo,\n                                              AuthenticationAlgorithm authAlgo)\n{\n    EncryptMessageOutput result;\n\n    json_spirit::Value resultJsonDescriptor;\n\n    const boost::optional<std::string> encryptionAlgoName       = GetEncryptionAlgoName(encAlgo);\n    const boost::optional<uint64_t>    encryptionKeyLen         = GetEncryptionAlgoKeyLength(encAlgo);\n    const boost::optional<std::string> authenticationAlgoName   = GetAuthAlgoName(authAlgo);\n    const boost::optional<uint64_t>    authenticationAlgoKeyLen = GetAuthAlgoKeyLength(authAlgo);\n    const boost::optional<std::string> keyRatchetAlgoName       = GetRatchetAlgoName(keyRatchetAlgo);\n    const boost::optional<uint64_t> authKeyRatchetOutputLen = GetRatchetAlgoOutputLength(keyRatchetAlgo);\n\n    if (!encryptionAlgoName.is_initialized()) {\n        throw std::runtime_error(\"Invalid encryption algorithm with index: \" + std::to_string(encAlgo));\n    }\n    if (!encryptionKeyLen.is_initialized()) {\n        throw std::runtime_error(\"Failed to retrieve encryption algorithm key length for index: \" +\n                                 std::to_string(encAlgo));\n    }\n    if (!authenticationAlgoName.is_initialized()) {\n        throw std::runtime_error(\"Invalid authentication algorithm with index: \" +\n                                 std::to_string(authAlgo));\n    }\n    if (!authenticationAlgoKeyLen.is_initialized()) {\n        throw std::runtime_error(\"Invalid authentication algorithm key length found with index: \" +\n                                 std::to_string(authAlgo));\n    }\n    if (!keyRatchetAlgoName.is_initialized()) {\n        throw std::runtime_error(\"Invalid key ratchet algorithm name with index: \" +\n                                 std::to_string(keyRatchetAlgo));\n    }\n    if (!authKeyRatchetOutputLen.is_initialized()) {\n        throw std::runtime_error(\"Invalid key ratchet algorithm output length with index: \" +\n                                 std::to_string(keyRatchetAlgo));\n    }\n    if (key.size() != encryptionKeyLen.get()) {\n        throw std::runtime_error(\"Invalid encryption key length for algorithm \" +\n                                 encryptionAlgoName.get() + \"; Given length is \" +\n                                 std::to_string(key.size()) +\n                                 \"; must be: \" + std::to_string(encryptionKeyLen.get()));\n    }\n\n    if (authKeyRatchetOutputLen.get() < authenticationAlgoKeyLen.get()) {\n        throw std::runtime_error(\n            \"The key ratchet algorithm given has an output length smaller than the \"\n            \"required authentication key length. Please choose another ratcheting algorithm.\");\n    }\n\n    result.encryptionAlgo = encryptionAlgoName.get();\n    result.authAlgo       = authenticationAlgoName.get();\n    result.keyRatchetAlgo = keyRatchetAlgoName.get();\n\n    switch (encAlgo) {\n    case CHL::EncryptionAlgorithm::Enc_XSalsa20Poly1305: {\n        auto nonce    = GenSalsa20poly1305RandomNonce();\n        auto keyIn    = GetCanonicalSalsa20poly1305Key(key, encryptionAlgoName.get());\n        result.cipher = XSalsa20poly1305_EncryptLongMsg_CTR(message, nonce, keyIn);\n\n        result.nonce = ToBytes(nonce);\n        break;\n    }\n    case CHL::EncryptionAlgorithm::Enc_Size: {\n        throw std::logic_error(\"Size enum element used as encryption algorithm\");\n    }\n    }\n\n    CHL::SecureBytes authKey = CalculateKeyRatchet(keyRatchetAlgo, key, authenticationAlgoKeyLen);\n\n    switch (authAlgo) {\n    case CHL::AuthenticationAlgorithm::Auth_Poly1305: {\n        SecureArray<uint8_t, crypto_onetimeauth_poly1305_KEYBYTES> authKeyArray{};\n        std::copy(authKey.cbegin(), authKey.cend(), authKeyArray.begin());\n        auto authDataArray = Poly1305AuthenticateMessage(result.cipher, authKeyArray);\n        result.authData.clear();\n        std::copy(authDataArray.cbegin(), authDataArray.cend(), std::back_inserter(result.authData));\n        break;\n    }\n    case CHL::AuthenticationAlgorithm::Auth_Size: {\n        throw std::logic_error(\"Size enum element used as authentication algorithm\");\n    }\n    }\n\n    result.assertNoneIsEmpty();\n\n    return result;\n}\n\nCHL::Bytes Crypto_HighLevel::DecryptMessage(const CHL::EncryptMessageOutput& encryptedData,\n                                            const SecureBytes&               key)\n{\n    encryptedData.assertNoneIsEmpty();\n\n    const EncryptionAlgorithm       encAlgo  = GetEncryptionAlgoFromName(encryptedData.encryptionAlgo);\n    const AuthenticationAlgorithm   authAlgo = GetAuthAlgoFromName(encryptedData.authAlgo);\n    const AuthKeyRatchetAlgorithm   ratchetAlgo = GetRatchetAlgoFromName(encryptedData.keyRatchetAlgo);\n    const boost::optional<uint64_t> authenticationAlgoKeyLen = GetAuthAlgoKeyLength(authAlgo);\n    const boost::optional<uint64_t> authKeyRatchetOutputLen  = GetRatchetAlgoOutputLength(ratchetAlgo);\n\n    if (!authenticationAlgoKeyLen.is_initialized()) {\n        throw std::runtime_error(\"Invalid authentication algorithm key length found with index: \" +\n                                 std::to_string(authAlgo));\n    }\n\n    if (authKeyRatchetOutputLen.get() < authenticationAlgoKeyLen.get()) {\n        throw std::runtime_error(\n            \"The key ratchet algorithm given has an output length smaller than the \"\n            \"required authentication key length. Please choose another ratcheting algorithm.\");\n    }\n\n    const SecureBytes authKey = CalculateKeyRatchet(ratchetAlgo, key, authenticationAlgoKeyLen);\n\n    Bytes authData;\n\n    switch (authAlgo) {\n    case CHL::AuthenticationAlgorithm::Auth_Poly1305: {\n        std::array<uint8_t, crypto_onetimeauth_poly1305_BYTES>     authDataArray{};\n        SecureArray<uint8_t, crypto_onetimeauth_poly1305_KEYBYTES> authKeyArray{};\n        std::copy(authKey.cbegin(), authKey.cbegin() + authKeyArray.size(), authKeyArray.begin());\n        std::copy(encryptedData.authData.cbegin(),\n                  encryptedData.authData.cbegin() + authDataArray.size(), authDataArray.begin());\n        if (!Poly1305VerifyMessage(encryptedData.cipher, authDataArray, authKeyArray)) {\n            throw std::runtime_error(\"Message authentication failed\");\n        }\n        break;\n    }\n    case CHL::AuthenticationAlgorithm::Auth_Size: {\n        throw std::logic_error(\"Size enum element used as authentication algorithm\");\n    }\n    }\n\n    Bytes message;\n\n    switch (encAlgo) {\n    case CHL::EncryptionAlgorithm::Enc_XSalsa20Poly1305: {\n        auto keyIn = GetCanonicalSalsa20poly1305Key(key, encryptedData.encryptionAlgo);\n        message    = XSalsa20poly1305_DecryptLongMsg_CTR(encryptedData.cipher, keyIn);\n        break;\n    }\n    case CHL::EncryptionAlgorithm::Enc_Size: {\n        throw std::logic_error(\"Size enum element used as encryption algorithm\");\n    }\n    }\n    return message;\n}\n\nvoid Crypto_HighLevel::EncryptMessageOutput::assertNoneIsEmpty() const\n{\n    if (cipher.empty()) {\n        throw std::invalid_argument(\"Empty cipher\");\n    }\n    if (nonce.empty()) {\n        throw std::invalid_argument(\"Empty nonce\");\n    }\n    if (authData.empty()) {\n        throw std::invalid_argument(\"Empty authentication data\");\n    }\n    if (encryptionAlgo.empty()) {\n        throw std::invalid_argument(\"Empty encryption algorithm name\");\n    }\n    if (keyRatchetAlgo.empty()) {\n        throw std::invalid_argument(\"Empty key ratchet algorithm name\");\n    }\n    if (authAlgo.empty()) {\n        throw std::invalid_argument(\"Empty authentication algorithm name\");\n    }\n}\n\nstd::string GetStrValue_CHL(const json_spirit::Object& obj, const std::string& name)\n{\n    auto v = json_spirit::find_value(obj, name);\n    if (v == json_spirit::Value::null) {\n        throw std::runtime_error(\"Could not find json object: \" + name);\n    }\n    if (v.type() != json_spirit::Value_type::str_type) {\n        throw std::runtime_error(\"For object \" + name +\n                                 \" the expected type is string, but found type with index \" +\n                                 std::to_string(v.type()));\n    }\n    return v.get_str();\n}\n\nint GetIntValue_CHL(const json_spirit::Object& obj, const std::string& name)\n{\n    auto v = json_spirit::find_value(obj, name);\n    if (v == json_spirit::Value::null) {\n        throw std::runtime_error(\"Could not find json object: \" + name);\n    }\n    if (v.type() != json_spirit::Value_type::int_type) {\n        throw std::runtime_error(\"For object \" + name +\n                                 \" the expected type is int, but found type with index \" +\n                                 std::to_string(v.type()));\n    }\n    return v.get_int();\n}\n\nCrypto_HighLevel::Bytes\nCrypto_HighLevel::EncryptMessageOutput::Serialize(const EncryptMessageOutput& cipherData)\n{\n    json_spirit::Object root;\n\n    if (static_cast<int64_t>(cipherData.nonce.size()) >= static_cast<int64_t>(INT_MAX)) {\n        throw std::runtime_error(\"Huge nonce.\");\n    }\n    if (static_cast<int64_t>(cipherData.authData.size()) >= static_cast<int64_t>(INT_MAX)) {\n        throw std::runtime_error(\"Huge authentication data.\");\n    }\n    if (static_cast<int64_t>(cipherData.cipher.size()) >= static_cast<int64_t>(INT_MAX)) {\n        throw std::runtime_error(\"Huge cipher.\");\n    }\n\n    using JPair = json_spirit::Pair;\n    root.push_back(JPair(SER_FIELD__SER_VERSION, 0));\n    root.push_back(JPair(SER_FIELD__ENC_ALGO, cipherData.encryptionAlgo));\n    root.push_back(JPair(SER_FIELD__AUTH_ALGO, cipherData.authAlgo));\n    root.push_back(JPair(SER_FIELD__AUTH_KEY_RATCHET_ALGO, cipherData.keyRatchetAlgo));\n    root.push_back(JPair(SER_FIELD__IV_LENGTH, static_cast<int>(cipherData.nonce.size())));\n    root.push_back(JPair(SER_FIELD__IV_POSITION, 0));\n    root.push_back(JPair(SER_FIELD__AUTH_DATA_LENGTH, static_cast<int>(cipherData.authData.size())));\n    root.push_back(JPair(SER_FIELD__AUTH_DATA_POSITION, 1));\n    root.push_back(JPair(SER_FIELD__CIPHER_LENGTH, static_cast<int>(cipherData.cipher.size())));\n    root.push_back(JPair(SER_FIELD__CIPHER_POSITION, 2));\n\n    std::string result;\n    try {\n        result = json_spirit::write(json_spirit::Value(root));\n    } catch (std::exception& ex) {\n        throw std::runtime_error(\"Failed to export cipher data to json. Error: \" +\n                                 std::string(ex.what()));\n    } catch (...) {\n        throw std::runtime_error(\"Failed to export cipher data to json. Unknown error.\");\n    }\n    boost::trim(result);\n\n    // these have to be in the order put in the json above\n    result.insert(result.end(), cipherData.nonce.cbegin(), cipherData.nonce.cend());\n    result.insert(result.end(), cipherData.authData.cbegin(), cipherData.authData.cend());\n    result.insert(result.end(), cipherData.cipher.cbegin(), cipherData.cipher.cend());\n\n    return ToBytes(std::move(result));\n}\n\nCrypto_HighLevel::EncryptMessageOutput\nCrypto_HighLevel::EncryptMessageOutput::Deserialize(const Crypto_HighLevel::Bytes& data)\n{\n    if (data.empty()) {\n        throw std::runtime_error(\"Requested decryption of empty data\");\n    }\n    if (data[0] != '{') {\n        throw std::runtime_error(\"Unexpected header while attempting to decrypt data\");\n    }\n\n    EncryptMessageOutput result;\n\n    JsonStringQueue jsonStringQueue;\n    jsonStringQueue.pushData(data.cbegin(), data.cend());\n\n    std::string headerJsonStr;\n    {\n        std::vector<std::string> jsonStrVec = jsonStringQueue.pullDataAndClear();\n        if (jsonStrVec.empty()) {\n            throw std::runtime_error(\n                \"Could not pull any index data out of the cipher data. Data is not readable.\");\n        }\n        headerJsonStr = jsonStrVec.front();\n    }\n\n    json_spirit::Value headerJson;\n\n    try {\n        json_spirit::read_or_throw(headerJsonStr, headerJson);\n    } catch (std::exception& ex) {\n        throw std::runtime_error(\"Unable to read json header of encrypted data. Error: \" +\n                                 std::string(ex.what()));\n    } catch (...) {\n        throw std::runtime_error(\"Unable to read json header of encrypted data. Unknown error.\");\n    }\n\n    if (headerJson.type() != json_spirit::Value_type::obj_type) {\n        throw std::runtime_error(\"Invalid encrypted data header json type\");\n    }\n\n    const json_spirit::Object root = headerJson.get_obj();\n\n    int version = GetIntValue_CHL(root, SER_FIELD__SER_VERSION);\n    if (version != 0) {\n        throw std::runtime_error(\n            \"Unknown serialization version for ciphered message given with value: \" +\n            std::to_string(version));\n    }\n\n    result.encryptionAlgo = GetStrValue_CHL(root, SER_FIELD__ENC_ALGO);\n    result.keyRatchetAlgo = GetStrValue_CHL(root, SER_FIELD__AUTH_KEY_RATCHET_ALGO);\n    result.authAlgo       = GetStrValue_CHL(root, SER_FIELD__AUTH_ALGO);\n    int cipherPosition    = GetIntValue_CHL(root, SER_FIELD__CIPHER_POSITION);\n    int cipherLength      = GetIntValue_CHL(root, SER_FIELD__CIPHER_LENGTH);\n    int authDataPosition  = GetIntValue_CHL(root, SER_FIELD__AUTH_DATA_POSITION);\n    int authDataLength    = GetIntValue_CHL(root, SER_FIELD__AUTH_DATA_LENGTH);\n    int ivPosition        = GetIntValue_CHL(root, SER_FIELD__IV_POSITION);\n    int ivLength          = GetIntValue_CHL(root, SER_FIELD__IV_LENGTH);\n\n    // position can't be negative\n    if (cipherPosition < 0) {\n        throw std::runtime_error(\"Negative cipher position in cipher header\");\n    }\n    if (authDataPosition < 0) {\n        throw std::runtime_error(\"Negative authentication data position in cipher header\");\n    }\n    if (ivPosition < 0) {\n        throw std::runtime_error(\"Negative IV position in cipher header\");\n    }\n\n    // size can't be zero or negative\n    if (cipherLength <= 0) {\n        throw std::runtime_error(\"Zero/Negative cipher length in cipher header\");\n    }\n    if (authDataLength <= 0) {\n        throw std::runtime_error(\"Zero/Negative authentication data length in cipher header\");\n    }\n    if (ivLength <= 0) {\n        throw std::runtime_error(\"Zero/Negative IV length in cipher header\");\n    }\n\n    static constexpr const int fieldCount = 3;\n\n    std::map<unsigned, uint64_t> dataSizes;\n    dataSizes[cipherPosition]   = cipherLength;\n    dataSizes[authDataPosition] = authDataLength;\n    dataSizes[ivPosition]       = ivLength;\n\n    if (dataSizes.size() != fieldCount) {\n        throw std::runtime_error(\"The number of readable fields is not what is expected: \" +\n                                 std::to_string(fieldCount));\n    }\n\n    for (unsigned i = 0; i < fieldCount; i++) {\n        auto it = dataSizes.find(i);\n        if (it == dataSizes.cend()) {\n            throw std::runtime_error(\"Could no t find all required components of the ciphered message \"\n                                     \"in the expected positions\");\n        }\n    }\n\n    uint64_t totalBinSize = cipherLength + authDataLength + ivLength;\n    if (data.size() > headerJsonStr.size() + totalBinSize) {\n        throw std::runtime_error(\n            \"The binary blob of the encrypted message doesn't have appropriate size.\");\n    }\n\n    std::size_t currentOffset = headerJsonStr.size();\n    for (int i = 0; i < fieldCount; i++) {\n        std::size_t dataFrontPoint = currentOffset;\n        std::size_t dataEndPoint   = currentOffset + dataSizes.at(i);\n\n        CHL::Bytes currentData(data.begin() + dataFrontPoint, data.cbegin() + dataEndPoint);\n        currentOffset += currentData.size();\n\n        if (i == cipherPosition) {\n            result.cipher = std::move(currentData);\n        } else if (i == authDataPosition) {\n            result.authData = std::move(currentData);\n        } else if (i == ivPosition) {\n            result.nonce = std::move(currentData);\n        } else {\n            throw std::runtime_error(\"An unexpected value position was found in header: \" +\n                                     std::to_string(i));\n        }\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "b050896679dcb4f203aad4996c260d8b21bc873b", "size": 33546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wallet/crypto_highlevel.cpp", "max_stars_repo_name": "HUSKI3/Neblio-Node", "max_stars_repo_head_hexsha": "9bc65b2b2c90f52baf05182aaaeb0260a410a712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138.0, "max_stars_repo_stars_event_min_datetime": "2017-08-13T18:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T04:05:25.000Z", "max_issues_repo_path": "wallet/crypto_highlevel.cpp", "max_issues_repo_name": "HUSKI3/Neblio-Node", "max_issues_repo_head_hexsha": "9bc65b2b2c90f52baf05182aaaeb0260a410a712", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 202.0, "max_issues_repo_issues_event_min_datetime": "2017-07-25T23:09:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T15:01:08.000Z", "max_forks_repo_path": "wallet/crypto_highlevel.cpp", "max_forks_repo_name": "HUSKI3/Neblio-Node", "max_forks_repo_head_hexsha": "9bc65b2b2c90f52baf05182aaaeb0260a410a712", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 65.0, "max_forks_repo_forks_event_min_datetime": "2017-08-22T12:28:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T01:28:00.000Z", "avg_line_length": 42.1962264151, "max_line_length": 105, "alphanum_fraction": 0.6671436237, "num_tokens": 7997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.17822854094807045}}
{"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_OPERATOR_FUNCTIONS_SIMD_COMMON_IF_ELSE_HPP_INCLUDED\n#define BOOST_SIMD_OPERATOR_FUNCTIONS_SIMD_COMMON_IF_ELSE_HPP_INCLUDED\n#include <boost/simd/operator/functions/if_else.hpp>\n#include <boost/simd/include/functions/simd/bitwise_select.hpp>\n#include <boost/simd/include/functions/simd/is_nez.hpp>\n#include <boost/simd/include/functions/simd/genmask.hpp>\n#include <boost/simd/include/functions/simd/logical_or.hpp>\n#include <boost/simd/include/functions/simd/logical_and.hpp>\n#include <boost/simd/include/functions/simd/logical_andnot.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/sdk/meta/is_bitwise_logical.hpp>\n#include <boost/simd/sdk/meta/as_arithmetic.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <boost/utility/enable_if.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( if_else_, tag::cpu_, (A0)(A1)(X)\n                                    , ((simd_< logical_<A0>, X >))\n                                      ((simd_< arithmetic_<A1>, X >))\n                                      ((simd_< arithmetic_<A1>, X >))\n                                    )\n  {\n    typedef A1 result_type;\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1& a1, const A1&a2) const\n    {\n      return bitwise_select(genmask(a0), a1, a2);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( if_else_, tag::cpu_, (A0)(A1)(X)\n                                    , ((simd_< arithmetic_<A0>, X >))\n                                      ((simd_< arithmetic_<A1>, X >))\n                                      ((simd_< arithmetic_<A1>, X >))\n                                    )\n  {\n    typedef A1 result_type;\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1& a1, const A1&a2) const\n    {\n      return if_else( is_nez(a0), a1, a2 );\n    }\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT          ( if_else_, tag::cpu_, (A0)(A1)(X)\n                                    , ((simd_< arithmetic_<A0>, X >))\n                                      ((simd_< logical_<A1>, X >))\n                                      ((simd_< logical_<A1>, X >))\n                                    )\n  {\n    typedef A1 result_type;\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1& a1, const A1&a2) const\n    {\n      return if_else( is_nez(a0), a1, a2 );\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( if_else_, tag::cpu_, (A0)(A1)(X)\n                                    , ((simd_< logical_<A0>, X >))\n                                      ((simd_< logical_<A1>, X >))\n                                      ((simd_< logical_<A1>, X >))\n                                    )\n  {\n    typedef A1 result_type;\n\n    template<class A0_>\n    typename enable_if< meta::is_bitwise_logical<A0_>, result_type>::type\n    BOOST_FORCEINLINE operator()(const A0_& a0, const A1& a1, const A1&a2) const\n    {\n      typedef typename meta::as_arithmetic<A1>::type atype;\n      return bitwise_cast<result_type>(if_else(a0,bitwise_cast<atype>(a1),bitwise_cast<atype>(a2)));\n    }\n\n    template<class A0_>\n    typename disable_if< meta::is_bitwise_logical<A0_>, result_type>::type\n    BOOST_FORCEINLINE operator()(const A0_& a0, const A1& a1, const A1&a2) const\n    {\n      return logical_or(logical_and(a1,a0),logical_andnot(a2,a0));\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "520eeed0a83d9d973e2edf8fb38eb5711c0af88b", "size": 3893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/operator/functions/simd/common/if_else.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/operator/functions/simd/common/if_else.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/operator/functions/simd/common/if_else.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": 41.414893617, "max_line_length": 100, "alphanum_fraction": 0.5489339841, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17794315933730218}}
{"text": "#include <cinttypes>\n#include <cstdint>\n#include <future>\n#include <limits>\n#include <list>\n#include <memory>\n#include <mutex>\n#include <queue>\n#include <thread>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"config.h\"\n\n#include \"baldr/rapidjson_utils.h\"\n#include \"filesystem.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/io/wkt/wkt.hpp>\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\n#include <boost/optional.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <cxxopts.hpp>\n\n#include \"baldr/admininfo.h\"\n#include \"baldr/graphconstants.h\"\n#include \"baldr/graphid.h\"\n#include \"baldr/graphreader.h\"\n#include \"baldr/graphtile.h\"\n#include \"baldr/tilehierarchy.h\"\n#include \"midgard/aabb2.h\"\n#include \"midgard/constants.h\"\n#include \"midgard/distanceapproximator.h\"\n#include \"midgard/logging.h\"\n#include \"midgard/pointll.h\"\n#include \"midgard/util.h\"\n#include \"mjolnir/util.h\"\n\nusing namespace valhalla::midgard;\nusing namespace valhalla::baldr;\n\n// Geometry types for admin queries\ntypedef boost::geometry::model::d2::point_xy<double> point_type;\ntypedef boost::geometry::model::polygon<point_type> polygon_type;\ntypedef boost::geometry::model::multi_polygon<polygon_type> multi_polygon_type;\n\nfilesystem::path config_file_path;\n\nstd::unordered_map<uint32_t, multi_polygon_type>\nGetAdminInfo(sqlite3* db_handle,\n             std::unordered_map<uint32_t, bool>& drive_on_right,\n             const AABB2<PointLL>& aabb) {\n  // Polys (return)\n  std::unordered_map<uint32_t, multi_polygon_type> polys;\n\n  // Form query\n  std::string sql = \"SELECT state.rowid, country.name, state.name, country.iso_code, \";\n  sql += \"state.iso_code, state.drive_on_right, st_astext(state.geom) \";\n  sql += \"from admins state, admins country where \";\n  sql += \"ST_Intersects(state.geom, BuildMBR(\" + std::to_string(aabb.minx()) + \",\";\n  sql += std::to_string(aabb.miny()) + \", \" + std::to_string(aabb.maxx()) + \",\";\n  sql += std::to_string(aabb.maxy()) + \")) and \";\n  sql += \"country.rowid = state.parent_admin and state.admin_level=4 \";\n  sql += \"and state.rowid IN (SELECT rowid FROM SpatialIndex WHERE f_table_name = \";\n  sql += \"'admins' AND search_frame = BuildMBR(\" + std::to_string(aabb.minx()) + \",\";\n  sql += std::to_string(aabb.miny()) + \", \" + std::to_string(aabb.maxx()) + \",\";\n  sql += std::to_string(aabb.maxy()) + \"));\";\n\n  sqlite3_stmt* stmt = 0;\n  uint32_t ret = sqlite3_prepare_v2(db_handle, sql.c_str(), sql.length(), &stmt, 0);\n  if (ret == SQLITE_OK) {\n    uint32_t result = sqlite3_step(stmt);\n    if (result == SQLITE_DONE) {\n      // state/prov not found, try to find country\n      sql = \"SELECT rowid, name, \"\n            \", iso_code, \"\n            \", drive_on_right, st_astext(geom) from \";\n      sql += \" admins where ST_Intersects(geom, BuildMBR(\" + std::to_string(aabb.minx()) + \",\";\n      sql += std::to_string(aabb.miny()) + \", \" + std::to_string(aabb.maxx()) + \",\";\n      sql += std::to_string(aabb.maxy()) + \")) and admin_level=2 \";\n      sql += \"and rowid IN (SELECT rowid FROM SpatialIndex WHERE f_table_name = \";\n      sql += \"'admins' AND search_frame = BuildMBR(\" + std::to_string(aabb.minx()) + \",\";\n      sql += std::to_string(aabb.miny()) + \", \" + std::to_string(aabb.maxx()) + \",\";\n      sql += std::to_string(aabb.maxy()) + \"));\";\n\n      sqlite3_finalize(stmt);\n      stmt = 0;\n      ret = sqlite3_prepare_v2(db_handle, sql.c_str(), sql.length(), &stmt, 0);\n      if (ret == SQLITE_OK) {\n        result = 0;\n        result = sqlite3_step(stmt);\n      }\n    }\n\n    uint32_t index = 1;\n    while (result == SQLITE_ROW) {\n\n      uint32_t id = sqlite3_column_int(stmt, 0);\n      std::string country_name = \"\";\n      std::string state_name = \"\";\n      std::string country_iso = \"\";\n      std::string state_iso = \"\";\n\n      if (sqlite3_column_type(stmt, 1) == SQLITE_TEXT) {\n        country_name = std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1)));\n      }\n\n      if (sqlite3_column_type(stmt, 2) == SQLITE_TEXT) {\n        state_name = std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2)));\n      }\n\n      if (sqlite3_column_type(stmt, 3) == SQLITE_TEXT) {\n        country_iso = std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3)));\n      }\n\n      if (sqlite3_column_type(stmt, 4) == SQLITE_TEXT) {\n        state_iso = std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4)));\n      }\n\n      bool dor = true;\n      if (sqlite3_column_type(stmt, 5) == SQLITE_INTEGER) {\n        dor = sqlite3_column_int(stmt, 5);\n      }\n\n      std::string geom = \"\";\n      if (sqlite3_column_type(stmt, 6) == SQLITE_TEXT) {\n        geom = std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 6)));\n      }\n\n      multi_polygon_type multi_poly;\n      boost::geometry::read_wkt(geom, multi_poly);\n      polys.emplace(index, multi_poly);\n      drive_on_right.emplace(index, dor);\n      index++;\n\n      result = sqlite3_step(stmt);\n    }\n  }\n  if (stmt) {\n    sqlite3_finalize(stmt);\n    stmt = 0;\n  }\n  return polys;\n}\n\n// Benchmark the admin DB access\nvoid Benchmark(const boost::property_tree::ptree& pt) {\n  std::cout << \"In Benchmark\" << std::endl;\n\n  uint32_t counts[128] = {};\n\n  // Initialize the admin DB (if it exists)\n  auto database = pt.get_optional<std::string>(\"admin\");\n\n  sqlite3* db_handle = nullptr;\n  if (filesystem::exists(*database)) {\n    sqlite3_stmt* stmt = 0;\n    uint32_t ret = sqlite3_open_v2((*database).c_str(), &db_handle, SQLITE_OPEN_READONLY, nullptr);\n    if (ret != SQLITE_OK) {\n      LOG_ERROR(\"cannot open \" + *database);\n      sqlite3_close(db_handle);\n      return;\n    }\n\n  } else {\n    LOG_ERROR(\"Admin db \" + *database + \" not found.\");\n    return;\n  }\n  auto admin_conn = valhalla::mjolnir::make_spatialite_cache(db_handle);\n\n  // Graphreader\n  GraphReader reader(pt);\n  auto local_level = TileHierarchy::levels().back().level;\n  auto tiles = TileHierarchy::levels().back().tiles;\n\n  // Iterate through the tiles and perform enhancements\n  std::unordered_map<uint32_t, multi_polygon_type> polys;\n  std::unordered_map<uint32_t, bool> drive_on_right;\n  for (uint32_t id = 0; id < tiles.TileCount(); id++) {\n    // Get the admin polys if there is data for tiles that exist\n    GraphId tile_id(id, local_level, 0);\n    if (reader.DoesTileExist(tile_id)) {\n      polys = GetAdminInfo(db_handle, drive_on_right, tiles.TileBounds(id));\n      LOG_INFO(\"polys: \" + std::to_string(polys.size()));\n      if (polys.size() < 128) {\n        counts[polys.size()]++;\n      }\n    }\n  }\n  for (uint32_t i = 0; i < 128; i++) {\n    if (counts[i] > 0) {\n      LOG_INFO(\"Tiles with \" + std::to_string(i) + \" admin polys: \" + std::to_string(counts[i]));\n    }\n  }\n  sqlite3_close(db_handle);\n}\n\nbool ParseArguments(int argc, char* argv[]) {\n  std::vector<std::string> input_files;\n\n  try {\n    // clang-format off\n    cxxopts::Options options(\"valhalla_benchmark_admins\", \n      \"valhalla_benchmark_admins \" VALHALLA_VERSION \"\\n\\n\"\n      \"valhalla_benchmark_admins is a program to time the admin queries\\n\");\n\n    options.add_options()\n      (\"h,help\", \"Print this help message.\")\n      (\"v,version\", \"Print the version of this software.\")\n      (\"c,config\", \"Path to the json configuration file.\", cxxopts::value<std::string>());\n    // clang-format on\n\n    auto result = options.parse(argc, argv);\n\n    if (result.count(\"version\")) {\n      std::cout << \"valhalla_benchmark_admins \" << VALHALLA_VERSION << \"\\n\";\n      return EXIT_SUCCESS;\n    }\n\n    if (result.count(\"help\")) {\n      std::cout << options.help() << \"\\n\";\n      return EXIT_SUCCESS;\n    }\n\n    if (result.count(\"config\") &&\n        filesystem::is_regular_file(config_file_path =\n                                        filesystem::path(result[\"config\"].as<std::string>()))) {\n      return true;\n    } else {\n      std::cerr << \"Configuration file is required\\n\\n\" << options.help() << \"\\n\\n\";\n    }\n  } catch (const cxxopts::OptionException& e) {\n    std::cout << \"Unable to parse command line options because: \" << e.what() << std::endl;\n  }\n\n  return false;\n}\n\nint main(int argc, char** argv) {\n  if (!ParseArguments(argc, argv)) {\n    return EXIT_FAILURE;\n  }\n\n  // Ccheck what type of input we are getting\n  boost::property_tree::ptree pt;\n  rapidjson::read_json(config_file_path.string(), pt);\n\n  // Configure logging\n  boost::optional<boost::property_tree::ptree&> logging_subtree =\n      pt.get_child_optional(\"mjolnir.logging\");\n  if (logging_subtree) {\n    auto logging_config =\n        valhalla::midgard::ToMap<const boost::property_tree::ptree&,\n                                 std::unordered_map<std::string, std::string>>(logging_subtree.get());\n    valhalla::midgard::logging::Configure(logging_config);\n  }\n\n  auto t1 = std::chrono::high_resolution_clock::now();\n  Benchmark(pt.get_child(\"mjolnir\"));\n  auto t2 = std::chrono::high_resolution_clock::now();\n  uint32_t msecs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n  float secs = msecs * 0.001f;\n  LOG_INFO(\"Time = \" + std::to_string(secs) + \" secs\");\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "41f3c9427a7b2977ea320bfc7ddb482b5fcc2b4d", "size": 9204, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mjolnir/valhalla_benchmark_admins.cc", "max_stars_repo_name": "vinayakkulkarni/valhalla", "max_stars_repo_head_hexsha": "5f38946b6d183b306b6bd89c21e82f57a2861ed2", "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/mjolnir/valhalla_benchmark_admins.cc", "max_issues_repo_name": "vinayakkulkarni/valhalla", "max_issues_repo_head_hexsha": "5f38946b6d183b306b6bd89c21e82f57a2861ed2", "max_issues_repo_licenses": ["MIT"], "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/mjolnir/valhalla_benchmark_admins.cc", "max_forks_repo_name": "vinayakkulkarni/valhalla", "max_forks_repo_head_hexsha": "5f38946b6d183b306b6bd89c21e82f57a2861ed2", "max_forks_repo_licenses": ["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.0888888889, "max_line_length": 102, "alphanum_fraction": 0.6500434594, "num_tokens": 2455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.1779431541998515}}
{"text": "#include <ros/ros.h>\n#include <Eigen/Core>\n#include <grid_map_core/iterators/GridMapIterator.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgproc.hpp>\n\n#include \"bruce_exploration/base/cost_map.h\"\n\nnamespace bruce_exploration\n{\nnamespace base\n{\nconst std::string CostMap::OCCUPANCY_LAYER = \"occupancy\";\n// Don't compare it with NAN; use std::isnan\nconst DataType CostMap::OCCUPANCY_UNKNOWN = NAN;\nconst DataType CostMap::OCCUPANCY_TRUE = 100.0;\nconst DataType CostMap::OCCUPANCY_FALSE = 0.0;\nconst std::string CostMap::OBSTACLE_LAYER = \"obstacle\";\nconst DataType CostMap::OBSTACLE_FALSE = 0.0;\nconst DataType CostMap::OBSTACLE_TRUE = 255.0;\nconst std::string CostMap::CLEARANCE_LAYER = \"clearance\";\nconst DataType CostMap::CLEARANCE_MAX = std::numeric_limits<DataType>::max();\nconst std::string CostMap::REACHABILITY_LAYER = \"reachability\";\nconst DataType CostMap::REACHABILITY_TRUE = 255.0;\nconst DataType CostMap::REACHABILITY_FALSE = 0.0;\n\nCostMap::CostMap() : grid_map::GridMap()\n{\n}\n\nCostMap::CostMap(double xmin, double xmax, double ymin, double ymax, double resolution, double inflation_radius)\n  : grid_map::GridMap()\n{\n  setGeometry(xmin, xmax, ymin, ymax, resolution, inflation_radius);\n}\n\ngrid_map::GridMapIterator CostMap::iterate() const\n{\n  return grid_map::GridMapIterator(*this);\n}\n\nvoid CostMap::setGeometry(double xmin, double xmax, double ymin, double ymax, double resolution,\n                          double inflation_radius)\n{\n  limit_min_ << xmin, ymin;\n  limit_max_ << xmax, ymax;\n  inflation_radius_ = inflation_radius;\n  grid_map::Length length = limit_max_ - limit_min_;\n  Position position = length * 0.5 + limit_min_.array();\n  GridMap::setGeometry(length, resolution, position);\n  add(OCCUPANCY_LAYER, OCCUPANCY_UNKNOWN);\n  add(OBSTACLE_LAYER, OBSTACLE_FALSE);\n  add(CLEARANCE_LAYER, CLEARANCE_MAX);\n  add(REACHABILITY_LAYER, REACHABILITY_FALSE);\n  setBasicLayers({ OCCUPANCY_LAYER });\n  ROS_DEBUG(\"Created cost map with size %f x %f m (%i x %i cells) and origin at \"\n            \"(%f m, %f m).\",\n            getLength().x(), getLength().y(), getSize()(0), getSize()(1), getPosition()(0), getPosition()(1));\n}\n\nvoid CostMap::setOccupancyMap(const nav_msgs::OccupancyGrid &occ_grid)\n{\n  get(OCCUPANCY_LAYER).fill(NAN);\n\n  int width = occ_grid.info.width;\n  int height = occ_grid.info.height;\n  float resolution = occ_grid.info.resolution;\n  float x0 = occ_grid.info.origin.position.x;\n  float y0 = occ_grid.info.origin.position.y;\n\n  const int8_t *data = static_cast<const int8_t *>(&occ_grid.data[0]);\n  cv::Mat mat(height, width, CV_8SC1, (void *)data);\n\n  if (resolution > getResolution())\n  {\n    ROS_WARN_ONCE(\"Resolution of occupancy grid %f > resolution of grid map %f. Upsampling is performed.\", resolution,\n                  getResolution());\n    // Upsample; Otherwise there are gaps between grid map cells.\n    int ratio = (int)std::ceil(resolution / getResolution());\n    resolution /= ratio;\n    width *= ratio;\n    height *= ratio;\n\n    cv::resize(mat, mat, cv::Size(height, width), 0, 0, cv::INTER_NEAREST);\n    data = reinterpret_cast<const int8_t *>(mat.ptr());\n  }\n\n  for (size_t i = 0; i < height; ++i)\n  {\n    DataType y = y0 + (i + 0.5) * resolution;\n    for (size_t j = 0; j < width; ++j)\n    {\n      size_t n = i * width + j;\n      // if (data[n] == -1)\n      //   continue;\n\n      DataType x = x0 + (j + 0.5) * resolution;\n      Position position(x, y);\n      Index index;\n      if (!getIndex(position, index))\n        continue;\n\n      /// Use the following for occupancy values = {-1, 0, 100}\n      // at(CostMap::OCCUPANCY_LAYER, index) =\n      //     data[n] == -1 ? OCCUPANCY_UNKNOWN : (data[n] > 0 ? OCCUPANCY_TRUE : OCCUPANCY_FALSE);\n\n      static const int8_t FREE_THRESH = 45;\n      static const int8_t OCCUPIED_THRESH = 55;\n      DataType &value = at(CostMap::OCCUPANCY_LAYER, index);\n      DataType new_value = data[n] >= OCCUPIED_THRESH ?\n                               OCCUPANCY_TRUE :\n                               (data[n] >= 0 && data[n] <= FREE_THRESH ? OCCUPANCY_FALSE : OCCUPANCY_UNKNOWN);\n      // Use max occupancy when multiple cells are pointint to the same costmap cell\n      value = (std::isnan(value) ? new_value : std::max(value, new_value));\n    }\n  }\n\n  updateCosts();\n}\n\nvoid CostMap::setOrigin(double x, double y, double theta)\n{\n  origin_ << x, y, theta;\n  Index index0;\n  if (!getIndex(Position(x, y), index0))\n  {\n    ROS_ERROR(\"Origin (%f, %f, %f) is out of map\", x, y, theta);\n    return;\n  }\n\n  cv::Mat obs;\n  cv::eigen2cv(get(OBSTACLE_LAYER), obs);\n  cv::Mat rch(obs.rows, obs.cols, CV_8UC1, cv::Scalar(0));\n#ifndef ALLOW_UNKNOWN\n  cv::Mat occ;\n  cv::eigen2cv(get(OCCUPANCY_LAYER), occ);\n  cv::bitwise_or(rch, occ != occ, rch);\n#endif\n  cv::bitwise_or(rch, obs == OBSTACLE_TRUE, rch);\n  cv::floodFill(rch, cv::Point(index0(1), index0(0)), cv::Scalar(100), 0, 0, 10, 8);\n\n  Matrix rch_mat;\n  cv::cv2eigen(rch == 100, rch_mat);\n  get(REACHABILITY_LAYER) = rch_mat;\n}\n\nvoid CostMap::updateCosts()\n{\n  cv::Mat occ;\n  cv::eigen2cv(get(OCCUPANCY_LAYER), occ);\n  cv::Mat obs(occ == OCCUPANCY_TRUE);\n\n  int kernel_size = static_cast<int>(std::ceil(inflation_radius_ / getResolution()));\n  cv::Mat kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2 * kernel_size + 1, 2 * kernel_size + 1),\n                                             cv::Point(kernel_size, kernel_size));\n  cv::dilate(obs, obs, kernel);\n\n  Matrix obs_mat;\n  cv::cv2eigen(obs, obs_mat);\n  get(OBSTACLE_LAYER) = obs_mat;\n\n  cv::Mat clr;\n  cv::bitwise_not(obs, clr);\n  cv::distanceTransform(clr, clr, cv::DIST_L2, 3);\n\n  Matrix clr_mat;\n  cv::cv2eigen(clr, clr_mat);\n  get(CLEARANCE_LAYER) = clr_mat * getResolution();\n}\n\nstd::vector<Index> CostMap::getNeighborIndex4(const grid_map::Index &index) const\n{\n  static std::vector<std::pair<int, int>> inc4 = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };\n\n  std::vector<Index> ret;\n  for (const auto &it : inc4)\n  {\n    Index nh(index(0) + it.first, index(1) + it.second);\n    if (nh(0) >= 0 && nh(0) < getSize()(0) && nh(1) >= 0 && nh(1) < getSize()(1))\n      ret.push_back(nh);\n  }\n  return ret;\n}\n\nstd::vector<Index> CostMap::getNeighborIndex8(const grid_map::Index &index) const\n{\n  static std::vector<std::pair<int, int>> inc8 = { { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, 1 },\n                                                   { 0, -1 }, { 1, 1 },  { 1, 0 },   { 1, -1 } };\n\n  std::vector<Index> ret;\n  for (const auto &it : inc8)\n  {\n    Index nh(index(0) + it.first, index(1) + it.second);\n    if (nh(0) >= 0 && nh(0) < getSize()(0) && nh(1) >= 0 && nh(1) < getSize()(1))\n      ret.push_back(nh);\n  }\n  return ret;\n}\n\nbool CostMap::isOccupancyFree(double x, double y) const\n{\n  Index index;\n  if (getIndex(Position(x, y), index))\n  {\n    return isOccupancyFree(index);\n  }\n  return false;\n}\n\nbool CostMap::isOccupancyUnknown(double x, double y) const\n{\n  Index index;\n  if (getIndex(Position(x, y), index))\n  {\n    return isOccupancyUnknown(index);\n  }\n  return true;\n}\n\nbool CostMap::isCollisionFree(double x, double y) const\n{\n  Index index;\n  if (getIndex(Position(x, y), index))\n  {\n    return isCollisionFree(index);\n  }\n  return true;\n}\n\nbool CostMap::isCollisionFree(double x1, double y1, double x2, double y2) const\n{\n  for (grid_map::LineIterator iterator(*this, Position(x1, y1), Position(x2, y2)); !iterator.isPastEnd(); ++iterator)\n  {\n    if (!isCollisionFree(*iterator))\n      return false;\n  }\n  return true;\n}\n\nbool CostMap::isReachable(double x, double y) const\n{\n  Index index;\n  if (getIndex(Position(x, y), index))\n  {\n    return isReachable(index);\n  }\n  return false;\n}\n\nCostMap::DataType CostMap::getClearance(double x, double y) const\n{\n  Index index;\n  if (getIndex(Position(x, y), index))\n  {\n    return getClearance(index);\n  }\n  return CLEARANCE_MAX;\n}\n\n/// Without validity check\nbool CostMap::isOccupancyFree(const Index &index) const\n{\n  return at(OCCUPANCY_LAYER, index) == OCCUPANCY_FALSE;\n}\n\nbool CostMap::isOccupancyUnknown(const Index &index) const\n{\n  const DataType &v = at(OCCUPANCY_LAYER, index);\n  return std::isnan(v);  // || v == OCCUPANCY_UNKNOWN;\n}\n\nbool CostMap::isCollisionFree(const Index &start, const Index &end) const\n{\n  for (grid_map::LineIterator iterator(*this, start, end); !iterator.isPastEnd(); ++iterator)\n  {\n    if (!isCollisionFree(*iterator))\n      return false;\n  }\n  return true;\n}\n\nbool CostMap::isCollisionFree(const grid_map::Index &index) const\n{\n#ifdef ALLOW_UNKNOWN\n  return at(OBSTACLE_LAYER, index) == OBSTACLE_FALSE;\n#else\n  return !isOccupancyUnknown(index) && at(OBSTACLE_LAYER, index) == OBSTACLE_FALSE;\n#endif\n}\n\nbool CostMap::isReachable(const Index &index) const\n{\n  return at(REACHABILITY_LAYER, index) == REACHABILITY_TRUE;\n}\n\ndouble CostMap::getClearance(const grid_map::Index &index) const\n{\n  return at(CLEARANCE_LAYER, index);\n}\n\nvoid CostMap::clearCells(DataType x, DataType y, double clearing_radius)\n{\n  for (grid_map::CircleIterator iter(*this, grid_map::Position(x, y), clearing_radius); !iter.isPastEnd(); ++iter)\n  {\n    at(OCCUPANCY_LAYER, *iter) = OCCUPANCY_FALSE;\n    at(OBSTACLE_LAYER, *iter) = OBSTACLE_FALSE;\n  }\n}\n\nvoid CostMap::save(std::ostream &os) const\n{\n  const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \" \", \"\\n\");\n  // xmin, xmax, ymin, ymax, # rows, # cols\n  os << limit_min_(0) << \" \" << limit_max_(0) << \" \" << limit_min_(1) << \" \" << limit_max_(1) << \" \" << getSize()(0)\n     << \" \" << getSize()(1) << std::endl;\n  for (const auto &layer : getLayers())\n  {\n    const auto &mat = get(layer);\n    os << layer << std::endl;\n    os << mat.format(CSVFormat) << std::endl;\n  }\n}\n\n}  // namespace base\n}  // namespace bruce_exploration\n", "meta": {"hexsha": "2b16736a6ee38748d1dff6a1475ec597dd4f5b9d", "size": 9703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bruce_exploration/src/bruce_exploration/base/cost_map.cpp", "max_stars_repo_name": "jinkunw/bruce", "max_stars_repo_head_hexsha": "8059222dc79cd160ab844420b379726e7c4ee947", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-02-17T17:14:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T16:02:59.000Z", "max_issues_repo_path": "bruce_exploration/src/bruce_exploration/base/cost_map.cpp", "max_issues_repo_name": "jinkunw/bruce", "max_issues_repo_head_hexsha": "8059222dc79cd160ab844420b379726e7c4ee947", "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": "bruce_exploration/src/bruce_exploration/base/cost_map.cpp", "max_forks_repo_name": "jinkunw/bruce", "max_forks_repo_head_hexsha": "8059222dc79cd160ab844420b379726e7c4ee947", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T17:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T07:07:38.000Z", "avg_line_length": 29.763803681, "max_line_length": 118, "alphanum_fraction": 0.6542306503, "num_tokens": 2894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1779431507268667}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include \"Domain/CoordinateMaps/TimeDependent/ProductMaps.hpp\"\n\n#include <array>\n#include <boost/none.hpp>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <functional>\n#include <pup.h>\n#include <utility>\n\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/CoordinateMaps/CoordinateMapHelpers.hpp\"\n#include \"Utilities/DereferenceWrapper.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace domain {\nnamespace CoordinateMaps {\nnamespace TimeDependent {\nnamespace product_detail {\ntemplate <typename T, size_t Size, typename Map1, typename Map2, size_t... Is,\n          size_t... Js>\nstd::array<tt::remove_cvref_wrap_t<T>, Size> apply_map(\n    const std::array<T, Size>& coords, const Map1& map1, const Map2& map2,\n    const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time,\n    std::integer_sequence<size_t, Is...> /*meta*/,\n    std::integer_sequence<size_t, Js...> /*meta*/) noexcept {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  return {\n      {CoordinateMap_detail::apply_map(\n           map1,\n           std::array<std::reference_wrapper<const UnwrappedT>, sizeof...(Is)>{\n               {coords[Is]...}},\n           time, functions_of_time,\n           domain::is_map_time_dependent_t<Map1>{})[Is]...,\n       CoordinateMap_detail::apply_map(\n           map2,\n           std::array<std::reference_wrapper<const UnwrappedT>, sizeof...(Js)>{\n               {coords[Map1::dim + Js]...}},\n           time, functions_of_time,\n           domain::is_map_time_dependent_t<Map2>{})[Js]...}};\n}\n\ntemplate <size_t Size, typename Map1, typename Map2, size_t... Is, size_t... Js>\nboost::optional<std::array<double, Size>> apply_inverse(\n    const std::array<double, Size>& coords, const Map1& map1, const Map2& map2,\n    const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time,\n    std::integer_sequence<size_t, Is...> /*meta*/,\n    std::integer_sequence<size_t, Js...> /*meta*/) noexcept {\n  auto map1_func = CoordinateMap_detail::apply_inverse_map(\n      map1, std::array<double, sizeof...(Is)>{{coords[Is]...}}, time,\n      functions_of_time, domain::is_map_time_dependent_t<Map1>{});\n  auto map2_func = CoordinateMap_detail::apply_inverse_map(\n      map2, std::array<double, sizeof...(Js)>{{coords[Map1::dim + Js]...}},\n      time, functions_of_time, domain::is_map_time_dependent_t<Map2>{});\n  if (map1_func and map2_func) {\n    return {{{map1_func.get()[Is]..., map2_func.get()[Js]...}}};\n  } else {\n    return boost::none;\n  }\n}\n\ntemplate <typename T, size_t Size, typename Map1, typename Map2, size_t... Is,\n          size_t... Js>\nstd::array<tt::remove_cvref_wrap_t<T>, Size> apply_frame_velocity(\n    const std::array<T, Size>& coords, const Map1& map1, const Map2& map2,\n    const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time,\n    std::integer_sequence<size_t, Is...> /*meta*/,\n    std::integer_sequence<size_t, Js...> /*meta*/) noexcept {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  return {\n      {domain::CoordinateMap_detail::apply_frame_velocity(\n           map1,\n           std::array<std::reference_wrapper<const UnwrappedT>, sizeof...(Is)>{\n               {coords[Is]...}},\n           time, functions_of_time,\n           domain::is_map_time_dependent_t<Map1>{})[Is]...,\n       domain::CoordinateMap_detail::apply_frame_velocity(\n           map2,\n           std::array<std::reference_wrapper<const UnwrappedT>, sizeof...(Js)>{\n               {coords[Map1::dim + Js]...}},\n           time, functions_of_time,\n           domain::is_map_time_dependent_t<Map2>{})[Js]...}};\n}\n\ntemplate <typename T, size_t Size, typename Map1, typename Map2,\n          typename Function, size_t... Is, size_t... Js>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, Size, Frame::NoFrame> apply_jac(\n    const std::array<T, Size>& source_coords, const Map1& map1,\n    const Map2& map2, const Function func,\n    std::integer_sequence<size_t, Is...> /*meta*/,\n    std::integer_sequence<size_t, Js...> /*meta*/) noexcept {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  auto map1_jac = func(\n      std::array<std::reference_wrapper<const UnwrappedT>, sizeof...(Is)>{\n          {source_coords[Is]...}},\n      map1);\n  auto map2_jac = func(\n      std::array<std::reference_wrapper<const UnwrappedT>, sizeof...(Js)>{\n          {source_coords[Map1::dim + Js]...}},\n      map2);\n  tnsr::Ij<UnwrappedT, Size, Frame::NoFrame> jac{\n      make_with_value<UnwrappedT>(dereference_wrapper(source_coords[0]), 0.0)};\n  for (size_t i = 0; i < Map1::dim; ++i) {\n    for (size_t j = 0; j < Map1::dim; ++j) {\n      jac.get(i, j) = std::move(map1_jac.get(i, j));\n    }\n  }\n  for (size_t i = 0; i < Map2::dim; ++i) {\n    for (size_t j = 0; j < Map2::dim; ++j) {\n      jac.get(Map1::dim + i, Map1::dim + j) = std::move(map2_jac.get(i, j));\n    }\n  }\n  return jac;\n}\n}  // namespace product_detail\n\ntemplate <typename Map1, typename Map2>\nProductOf2Maps<Map1, Map2>::ProductOf2Maps(Map1 map1, Map2 map2) noexcept\n    : map1_(std::move(map1)), map2_(std::move(map2)) {}\n\ntemplate <typename Map1, typename Map2>\ntemplate <typename T>\nstd::array<tt::remove_cvref_wrap_t<T>, ProductOf2Maps<Map1, Map2>::dim>\nProductOf2Maps<Map1, Map2>::operator()(\n    const std::array<T, dim>& source_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept {\n  return product_detail::apply_map(source_coords, map1_, map2_, time,\n                                   functions_of_time,\n                                   std::make_index_sequence<Map1::dim>{},\n                                   std::make_index_sequence<Map2::dim>{});\n}\n\ntemplate <typename Map1, typename Map2>\nboost::optional<std::array<double, ProductOf2Maps<Map1, Map2>::dim>>\nProductOf2Maps<Map1, Map2>::inverse(\n    const std::array<double, dim>& target_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept {\n  return product_detail::apply_inverse(target_coords, map1_, map2_, time,\n                                       functions_of_time,\n                                       std::make_index_sequence<Map1::dim>{},\n                                       std::make_index_sequence<Map2::dim>{});\n}\n\ntemplate <typename Map1, typename Map2>\ntemplate <typename T>\nauto ProductOf2Maps<Map1, Map2>::frame_velocity(\n    const std::array<T, dim>& source_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept\n    -> std::array<tt::remove_cvref_wrap_t<T>, dim> {\n  return product_detail::apply_frame_velocity(\n      source_coords, map1_, map2_, time, functions_of_time,\n      std::make_index_sequence<Map1::dim>{},\n      std::make_index_sequence<Map2::dim>{});\n}\n\ntemplate <typename Map1, typename Map2>\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, ProductOf2Maps<Map1, Map2>::dim,\n         Frame::NoFrame>\nProductOf2Maps<Map1, Map2>::inv_jacobian(\n    const std::array<T, dim>& source_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  return product_detail::apply_jac(\n      source_coords, map1_, map2_,\n      [&time, &functions_of_time](const auto& point, const auto& map) noexcept {\n        return CoordinateMap_detail::apply_inverse_jacobian(\n            map, point, time, functions_of_time,\n            domain::is_jacobian_time_dependent_t<\n                std::decay_t<decltype(map)>,\n                std::reference_wrapper<const UnwrappedT>>{});\n      },\n      std::make_index_sequence<Map1::dim>{},\n      std::make_index_sequence<Map2::dim>{});\n}\n\ntemplate <typename Map1, typename Map2>\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, ProductOf2Maps<Map1, Map2>::dim,\n         Frame::NoFrame>\nProductOf2Maps<Map1, Map2>::jacobian(\n    const std::array<T, dim>& source_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  return product_detail::apply_jac(\n      source_coords, map1_, map2_,\n      [&time, &functions_of_time](const auto& point, const auto& map) noexcept {\n        return CoordinateMap_detail::apply_jacobian(\n            map, point, time, functions_of_time,\n            domain::is_jacobian_time_dependent_t<\n                std::decay_t<decltype(map)>,\n                std::reference_wrapper<const UnwrappedT>>{});\n      },\n      std::make_index_sequence<Map1::dim>{},\n      std::make_index_sequence<Map2::dim>{});\n}\n\ntemplate <typename Map1, typename Map2>\nvoid ProductOf2Maps<Map1, Map2>::pup(PUP::er& p) {\n  p | map1_;\n  p | map2_;\n}\n\ntemplate <typename Map1, typename Map2>\nbool operator!=(const ProductOf2Maps<Map1, Map2>& lhs,\n                const ProductOf2Maps<Map1, Map2>& rhs) noexcept {\n  return not(lhs == rhs);\n}\n\ntemplate <typename Map1, typename Map2, typename Map3>\nProductOf3Maps<Map1, Map2, Map3>::ProductOf3Maps(Map1 map1, Map2 map2,\n                                                 Map3 map3) noexcept\n    : map1_(std::move(map1)), map2_(std::move(map2)), map3_(std::move(map3)) {}\n\ntemplate <typename Map1, typename Map2, typename Map3>\ntemplate <typename T>\nstd::array<tt::remove_cvref_wrap_t<T>, ProductOf3Maps<Map1, Map2, Map3>::dim>\nProductOf3Maps<Map1, Map2, Map3>::operator()(\n    const std::array<T, dim>& source_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  return {\n      {CoordinateMap_detail::apply_map(\n           map1_,\n           std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n               {source_coords[0]}},\n           time, functions_of_time, domain::is_map_time_dependent_t<Map1>{})[0],\n       CoordinateMap_detail::apply_map(\n           map2_,\n           std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n               {source_coords[1]}},\n           time, functions_of_time, domain::is_map_time_dependent_t<Map2>{})[0],\n       CoordinateMap_detail::apply_map(\n           map3_,\n           std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n               {source_coords[2]}},\n           time, functions_of_time,\n           domain::is_map_time_dependent_t<Map3>{})[0]}};\n}\n\ntemplate <typename Map1, typename Map2, typename Map3>\nboost::optional<std::array<double, ProductOf3Maps<Map1, Map2, Map3>::dim>>\nProductOf3Maps<Map1, Map2, Map3>::inverse(\n    const std::array<double, dim>& target_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept {\n  const auto c1 = CoordinateMap_detail::apply_inverse_map(\n      map1_, std::array<double, 1>{{target_coords[0]}}, time, functions_of_time,\n      domain::is_map_time_dependent_t<Map1>{});\n  const auto c2 = CoordinateMap_detail::apply_inverse_map(\n      map2_, std::array<double, 1>{{target_coords[1]}}, time, functions_of_time,\n      domain::is_map_time_dependent_t<Map2>{});\n  const auto c3 = CoordinateMap_detail::apply_inverse_map(\n      map3_, std::array<double, 1>{{target_coords[2]}}, time, functions_of_time,\n      domain::is_map_time_dependent_t<Map3>{});\n  if (c1 and c2 and c3) {\n    return {{{c1.get()[0], c2.get()[0], c3.get()[0]}}};\n  } else {\n    return boost::none;\n  }\n}\n\ntemplate <typename Map1, typename Map2, typename Map3>\ntemplate <typename T>\nauto ProductOf3Maps<Map1, Map2, Map3>::frame_velocity(\n    const std::array<T, dim>& source_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept\n    -> std::array<tt::remove_cvref_wrap_t<T>, dim> {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  return {\n      {CoordinateMap_detail::apply_frame_velocity(\n           map1_,\n           std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n               {source_coords[0]}},\n           time, functions_of_time, domain::is_map_time_dependent_t<Map1>{})[0],\n       CoordinateMap_detail::apply_frame_velocity(\n           map2_,\n           std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n               {source_coords[1]}},\n           time, functions_of_time, domain::is_map_time_dependent_t<Map2>{})[0],\n       CoordinateMap_detail::apply_frame_velocity(\n           map3_,\n           std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n               {source_coords[2]}},\n           time, functions_of_time,\n           domain::is_map_time_dependent_t<Map3>{})[0]}};\n}\n\ntemplate <typename Map1, typename Map2, typename Map3>\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, ProductOf3Maps<Map1, Map2, Map3>::dim,\n         Frame::NoFrame>\nProductOf3Maps<Map1, Map2, Map3>::inv_jacobian(\n    const std::array<T, dim>& source_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  tnsr::Ij<UnwrappedT, dim, Frame::NoFrame> inv_jacobian_matrix{\n      make_with_value<UnwrappedT>(dereference_wrapper(source_coords[0]), 0.0)};\n  get<0, 0>(inv_jacobian_matrix) =\n      get<0, 0>(CoordinateMap_detail::apply_inverse_jacobian(\n          map1_,\n          std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n              {source_coords[0]}},\n          time, functions_of_time,\n          domain::is_jacobian_time_dependent_t<\n              Map1, std::reference_wrapper<const UnwrappedT>>{}));\n  get<1, 1>(inv_jacobian_matrix) =\n      get<0, 0>(CoordinateMap_detail::apply_inverse_jacobian(\n          map2_,\n          std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n              {source_coords[1]}},\n          time, functions_of_time,\n          domain::is_jacobian_time_dependent_t<\n              Map2, std::reference_wrapper<const UnwrappedT>>{}));\n  get<2, 2>(inv_jacobian_matrix) =\n      get<0, 0>(CoordinateMap_detail::apply_inverse_jacobian(\n          map3_,\n          std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n              {source_coords[2]}},\n          time, functions_of_time,\n          domain::is_jacobian_time_dependent_t<\n              Map3, std::reference_wrapper<const UnwrappedT>>{}));\n  return inv_jacobian_matrix;\n}\n\ntemplate <typename Map1, typename Map2, typename Map3>\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, ProductOf3Maps<Map1, Map2, Map3>::dim,\n         Frame::NoFrame>\nProductOf3Maps<Map1, Map2, Map3>::jacobian(\n    const std::array<T, dim>& source_coords, const double time,\n    const std::unordered_map<\n        std::string, std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&\n        functions_of_time) const noexcept {\n  using UnwrappedT = tt::remove_cvref_wrap_t<T>;\n  tnsr::Ij<UnwrappedT, dim, Frame::NoFrame> jacobian_matrix{\n      make_with_value<UnwrappedT>(dereference_wrapper(source_coords[0]), 0.0)};\n  get<0, 0>(jacobian_matrix) = get<0, 0>(CoordinateMap_detail::apply_jacobian(\n      map1_,\n      std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n          {source_coords[0]}},\n      time, functions_of_time,\n      domain::is_jacobian_time_dependent_t<\n          Map1, std::reference_wrapper<const UnwrappedT>>{}));\n  get<1, 1>(jacobian_matrix) = get<0, 0>(CoordinateMap_detail::apply_jacobian(\n      map2_,\n      std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n          {source_coords[1]}},\n      time, functions_of_time,\n      domain::is_jacobian_time_dependent_t<\n          Map2, std::reference_wrapper<const UnwrappedT>>{}\n\n      ));\n  get<2, 2>(jacobian_matrix) = get<0, 0>(CoordinateMap_detail::apply_jacobian(\n      map3_,\n      std::array<std::reference_wrapper<const UnwrappedT>, 1>{\n          {source_coords[2]}},\n      time, functions_of_time,\n      domain::is_jacobian_time_dependent_t<\n          Map3, std::reference_wrapper<const UnwrappedT>>{}));\n  return jacobian_matrix;\n}\ntemplate <typename Map1, typename Map2, typename Map3>\nvoid ProductOf3Maps<Map1, Map2, Map3>::pup(PUP::er& p) noexcept {\n  p | map1_;\n  p | map2_;\n  p | map3_;\n}\n\ntemplate <typename Map1, typename Map2, typename Map3>\nbool operator!=(const ProductOf3Maps<Map1, Map2, Map3>& lhs,\n                const ProductOf3Maps<Map1, Map2, Map3>& rhs) noexcept {\n  return not(lhs == rhs);\n}\n}  // namespace TimeDependent\n}  // namespace CoordinateMaps\n}  // namespace domain\n", "meta": {"hexsha": "f5d3893737b411f6d4fd0ea41a69d1f6f7978efe", "size": 17252, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/TimeDependent/ProductMaps.tpp", "max_stars_repo_name": "keefemitman/spectre", "max_stars_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "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/TimeDependent/ProductMaps.tpp", "max_issues_repo_name": "keefemitman/spectre", "max_issues_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "max_issues_repo_licenses": ["MIT"], "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/TimeDependent/ProductMaps.tpp", "max_forks_repo_name": "keefemitman/spectre", "max_forks_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "max_forks_repo_licenses": ["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.0780487805, "max_line_length": 80, "alphanum_fraction": 0.6615464874, "num_tokens": 4581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1779431507268667}}
{"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#ifndef BOOST_UNITS_CODATA_ELECTROMAGNETIC_CONSTANTS_HPP\r\n#define BOOST_UNITS_CODATA_ELECTROMAGNETIC_CONSTANTS_HPP\r\n\r\n///\r\n/// \\file\r\n/// \\brief CODATA recommended values of fundamental electromagnetic constants.\r\n/// \\details CODATA recommended values of the fundamental physical constants: NIST SP 961\r\n///   CODATA 2006 values as of 2007/03/30\r\n///\r\n\r\n#include <boost/units/static_constant.hpp>\r\n\r\n#include <boost/units/systems/detail/constants.hpp>\r\n#include <boost/units/systems/si/conductance.hpp>\r\n#include <boost/units/systems/si/current.hpp>\r\n#include <boost/units/systems/si/electric_charge.hpp>\r\n#include <boost/units/systems/si/electric_potential.hpp>\r\n#include <boost/units/systems/si/energy.hpp>\r\n#include <boost/units/systems/si/frequency.hpp>\r\n#include <boost/units/systems/si/magnetic_flux.hpp>\r\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\r\n#include <boost/units/systems/si/resistance.hpp>\r\n\r\n#include <boost/units/systems/si/codata/typedefs.hpp>\r\n\r\nnamespace boost {\r\n\r\nnamespace units { \r\n\r\nnamespace si {\r\n                            \r\nnamespace constants {\r\n\r\nnamespace codata {\r\n\r\n// ELECTROMAGNETIC\r\n/// elementary charge\r\nBOOST_UNITS_PHYSICAL_CONSTANT(e,quantity<electric_charge>,1.602176487e-19*coulombs,4.0e-27*coulombs);\r\n/// elementary charge to Planck constant ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(e_over_h,quantity<current_over_energy>,2.417989454e14*amperes/joule,6.0e6*amperes/joule);\r\n/// magnetic flux quantum\r\nBOOST_UNITS_PHYSICAL_CONSTANT(Phi_0,quantity<magnetic_flux>,2.067833667e-15*webers,5.2e-23*webers);\r\n/// conductance quantum\r\nBOOST_UNITS_PHYSICAL_CONSTANT(G_0,quantity<conductance>,7.7480917004e-5*siemens,5.3e-14*siemens);\r\n/// Josephson constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(K_J,quantity<frequency_over_electric_potential>,483597.891e9*hertz/volt,1.2e7*hertz/volt);\r\n/// von Klitzing constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(R_K,quantity<resistance>,25812.807557*ohms,1.77e-5*ohms);\r\n/// Bohr magneton\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_B,quantity<energy_over_magnetic_flux_density>,927.400915e-26*joules/tesla,2.3e-31*joules/tesla);\r\n/// nuclear magneton\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_N,quantity<energy_over_magnetic_flux_density>,5.05078324e-27*joules/tesla,1.3e-34*joules/tesla);\r\n\r\n} // namespace codata\r\n\r\n} // namespace constants    \r\n\r\n} // namespace si\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_UNITS_CODATA_ELECTROMAGNETIC_CONSTANTS_HPP\r\n", "meta": {"hexsha": "c8804973f2235fff8912f469953cfa7a319b2acb", "size": 2824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/units/systems/si/codata/electromagnetic_constants.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/units/systems/si/codata/electromagnetic_constants.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/units/systems/si/codata/electromagnetic_constants.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": 37.6533333333, "max_line_length": 130, "alphanum_fraction": 0.7719546742, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17794315072686662}}
{"text": "#include <eosiolib/types.hpp>\n#include <eosiolib/currency.hpp>\n#include <boost/container/flat_map.hpp>\n#include <cmath>\n#include <exchange/market_state.hpp>\n\nnamespace eosio {\n\n   /**\n    *  This contract enables users to create an exchange between any pair of\n    *  standard currency types. A new exchange is created by funding it with\n    *  an equal value of both sides of the order book and giving the issuer\n    *  the initial shares in that orderbook.\n    *\n    *  To prevent excessive rounding errors, the initial deposit should include\n    *  a sizeable quantity of both the base and quote currencies and the exchange\n    *  shares should have a quantity 100x the quantity of the largest initial\n    *  deposit.\n    *\n    *  Users must deposit funds into the exchange before they can trade on the\n    *  exchange.\n    *\n    *  Each time an exchange is created a new currency for that exchanges market\n    *  maker is also created. This currencies supply and symbol must be unique and\n    *  it uses the currency contract's tables to manage it.\n    */\n   class exchange {\n      private:\n         account_name      _this_contract;\n         currency          _excurrencies;\n         exchange_accounts _accounts;\n\n      public:\n         exchange( account_name self )\n         :_this_contract(self),\n          _excurrencies(self),\n          _accounts(self)\n         {}\n\n         void createx( account_name    creator,\n                       asset           initial_supply,\n                       uint32_t        fee,\n                       extended_asset  base_deposit,\n                       extended_asset  quote_deposit\n                     );\n\n         void deposit( account_name from, extended_asset quantity );\n         void withdraw( account_name  from, extended_asset quantity );\n         void lend( account_name lender, symbol_type market, extended_asset quantity );\n\n         void unlend(\n            account_name     lender,\n            symbol_type      market,\n            double           interest_shares,\n            extended_symbol  interest_symbol\n         );\n\n         struct covermargin {\n            account_name     borrower;\n            symbol_type      market;\n            extended_asset   cover_amount;\n         };\n\n         struct upmargin {\n            account_name     borrower;\n            symbol_type      market;\n            extended_asset   delta_borrow;\n            extended_asset   delta_collateral;\n         };\n\n         struct trade {\n            account_name    seller;\n            symbol_type     market;\n            extended_asset  sell;\n            extended_asset  min_receive;\n            uint32_t        expire = 0;\n            uint8_t         fill_or_kill = true;\n         };\n\n         void on( const trade& t    );\n         void on( const upmargin& b );\n         void on( const covermargin& b );\n         void on( const currency::transfer& t, account_name code );\n\n         void apply( account_name contract, account_name act );\n   };\n} // namespace eosio\n", "meta": {"hexsha": "9ee3139e0b0e3f32fa39597e6a69d9b248ddc5e9", "size": 3002, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contracts/exchange/exchange.hpp", "max_stars_repo_name": "qian870/EOS", "max_stars_repo_head_hexsha": "2ad412773d6ccc72045dae760ae3d81cf229c8ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-23T03:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-27T05:42:12.000Z", "max_issues_repo_path": "contracts/exchange/exchange.hpp", "max_issues_repo_name": "qian870/EOS", "max_issues_repo_head_hexsha": "2ad412773d6ccc72045dae760ae3d81cf229c8ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-09-28T16:48:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-24T04:14:10.000Z", "max_forks_repo_path": "contracts/exchange/exchange.hpp", "max_forks_repo_name": "qian870/EOS", "max_forks_repo_head_hexsha": "2ad412773d6ccc72045dae760ae3d81cf229c8ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T13:41:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-15T13:41:44.000Z", "avg_line_length": 34.1136363636, "max_line_length": 87, "alphanum_fraction": 0.5929380413, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.17794314725388188}}
{"text": "\r\n// Copyright 2005-2009 Daniel James.\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// This uses std::rand to generate random values for tests.\r\n// Which is not good as different platforms will be running different tests.\r\n// It would be much better to use Boost.Random, but it doesn't\r\n// support all the compilers that I want to test on.\r\n\r\n#if !defined(BOOST_UNORDERED_TEST_HELPERS_GENERATORS_HEADER)\r\n#define BOOST_UNORDERED_TEST_HELPERS_GENERATORS_HEADER\r\n\r\n#include <string>\r\n#include <utility>\r\n#include <stdexcept>\r\n#include <cstdlib>\r\n#include <boost/type_traits/add_const.hpp>\r\n#include \"./fwd.hpp\"\r\n\r\nnamespace test\r\n{\r\n    struct seed_t {\r\n        seed_t(unsigned int x) {\r\n            using namespace std;\r\n            srand(x);\r\n        }\r\n    };\r\n\r\n    inline int generate(int const*)\r\n    {\r\n        using namespace std;\r\n        return rand();\r\n    }\r\n\r\n    inline char generate(char const*)\r\n    {\r\n        using namespace std;\r\n        return static_cast<char>((rand() >> 1) % (128-32) + 32);\r\n    }\r\n\r\n    inline signed char generate(signed char const*)\r\n    {\r\n        using namespace std;\r\n        return static_cast<signed char>(rand());\r\n    }\r\n\r\n    inline std::string generate(std::string const*)\r\n    {\r\n        using namespace std;\r\n\r\n        char* char_ptr = 0;\r\n\r\n        std::string result;\r\n\r\n        int length = rand() % 10;\r\n        for(int i = 0; i < length; ++i)\r\n            result += generate(char_ptr);\r\n\r\n        return result;\r\n    }\r\n\r\n    float generate(float const*)\r\n    {\r\n        using namespace std;\r\n        return (float) rand() / (float) RAND_MAX;\r\n    }\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "4164ec49016124381653ba00e22dcba1690b24cc", "size": 1734, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/unordered/test/helpers/generators.hpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "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/unordered/test/helpers/generators.hpp", "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/unordered/test/helpers/generators.hpp", "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": 24.4225352113, "max_line_length": 80, "alphanum_fraction": 0.6061130334, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.1779431437808972}}
{"text": "#include <dlib/dnn.h>\n#include <dlib/opencv.h>\n#include <dlib/matrix.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/types_c.h>\n\n#include \"detector.h\"\n\ntemplate <long num_filters, typename SUBNET> using con5d = dlib::con<num_filters,5,5,2,2,SUBNET>;\ntemplate <long num_filters, typename SUBNET> using con5  = dlib::con<num_filters,5,5,1,1,SUBNET>;\n\ntemplate <typename SUBNET> using downsampler  = dlib::relu<dlib::affine<con5d<32, dlib::relu<dlib::affine<con5d<32, dlib::relu<dlib::affine<con5d<16,SUBNET>>>>>>>>>;\ntemplate <typename SUBNET> using rcon5  = dlib::relu<dlib::affine<con5<45,SUBNET>>>;\n\nusing DetectorNet = dlib::loss_mmod<dlib::con<1,9,9,1,1,rcon5<rcon5<rcon5<downsampler<dlib::input_rgb_image_pyramid<dlib::pyramid_down<6>>>>>>>>;\n\nclass Detector {\n\npublic:\n    Detector(const char* model_path) {\n        dlib::deserialize(model_path) >> net;\n    }\n\n    auto detect(const dlib::matrix<dlib::rgb_pixel>& image) {\n        std::lock_guard<std::mutex> lock(net_mutex);\n        return net(image);\n    }\n\n    auto detect(const std::vector<dlib::matrix<dlib::rgb_pixel>>& images) {\n        std::lock_guard<std::mutex> lock(net_mutex);\n        return net(images);\n    }\n\nprivate:\n    DetectorNet net;\n    std::mutex net_mutex;\n};\n\n\n\ndetector_init_result* detector_init(char* model_file_path) {\n    detector_init_result* result = (detector_init_result*)malloc(sizeof(detector_init_result));\n\n    try {\n        Detector* detector = new Detector(model_file_path);\n        result->detector = (void*)detector;\n        result->error_message = NULL;\n    } catch (std::exception& e) {\n        result->detector = NULL;\n        result->error_message = strdup(e.what());\n    }\n\n    return result;\n}\n\nvoid detector_free(void* detector) {\n    delete (Detector*)(detector);\n}\n\ndetector_detect_result* detector_detect(void* detector, void* image) {\n    detector_detect_result* result = (detector_detect_result*)malloc(sizeof(detector_detect_result));\n\n    try {\n        dlib::matrix<dlib::rgb_pixel> dlib_image;\n\n        cv::Mat* opencv_image = (cv::Mat*)image;\n\n        if (opencv_image->channels() > 1) {\n            dlib::assign_image(dlib_image, dlib::cv_image<dlib::bgr_pixel>(*opencv_image));\n        } else {\n            dlib::assign_image(dlib_image, dlib::cv_image<uchar>(*opencv_image));\n        }\n\n        auto detections_raw = ((Detector*)(detector))->detect(dlib_image);\n\n        detection* detections = (detection*)calloc(detections_raw.size(), sizeof(detection));\n    \n        for(long unsigned int i = 0; i < detections_raw.size(); i++) {\n            detections[i].region.min.x = detections_raw[i].rect.left();\n            detections[i].region.min.y = detections_raw[i].rect.top();\n            detections[i].region.max.x = detections_raw[i].rect.right();\n            detections[i].region.max.y = detections_raw[i].rect.bottom();\n            detections[i].confidence = detections_raw[i].detection_confidence;\n        }\n\n        result->detections_count = detections_raw.size();\n        result->detections = detections;\n        result->error_message = NULL;\n\n    } catch (std::exception& e) {\n        result->detections_count = 0;\n        result->detections = NULL;\n        result->error_message = strdup(e.what());\n    }\n\n    return result;\n}\n\ndetector_batch_detect_result* detector_batch_detect(void* detector, void* images, int images_count) {\n    detector_batch_detect_result* result = (detector_batch_detect_result*)malloc(sizeof(detector_batch_detect_result));\n\n    try {\n        std::vector<dlib::matrix<dlib::rgb_pixel>> dlib_images(images_count);\n\n        cv::Mat** opencv_images = (cv::Mat**)images;\n\n        for (int i = 0; i < images_count; i++) {\n            cv::Mat* opencv_image = opencv_images[i];\n            dlib::matrix<dlib::rgb_pixel> dlib_image;\n\n            if (opencv_image->channels() > 1) {\n                dlib::assign_image(dlib_image, dlib::cv_image<dlib::bgr_pixel>(*opencv_image));\n            } else {\n                dlib::assign_image(dlib_image, dlib::cv_image<uchar>(*opencv_image));\n            }\n\n            dlib_images[i] = dlib_image;\n        }\n\n        auto batch_detections_raw = ((Detector*)(detector))->detect(dlib_images);\n\n        batch_detection* batch_detections = (batch_detection*)calloc(batch_detections_raw.size(), sizeof(batch_detection));\n\n        for(unsigned long i = 0; i < batch_detections_raw.size(); i++) {\n\n            detection* detections = (detection*)calloc(batch_detections_raw[i].size(), sizeof(detection));\n\n            for(unsigned long j = 0; j < batch_detections_raw[i].size(); j++) {\n                detections[j].region.min.x = batch_detections_raw[i][j].rect.left();\n                detections[j].region.min.y = batch_detections_raw[i][j].rect.top();\n                detections[j].region.max.x = batch_detections_raw[i][j].rect.right();\n                detections[j].region.max.y = batch_detections_raw[i][j].rect.bottom();\n                detections[j].confidence = batch_detections_raw[i][j].detection_confidence;\n            }\n\n            batch_detections[i].detections = detections;\n            batch_detections[i].detections_count = batch_detections_raw[i].size();\n        }\n\n        result->detections = batch_detections;\n        result->detections_count = batch_detections_raw.size();\n        result->error_message = NULL;\n\n    } catch (std::exception& e) {\n        result->detections = NULL;\n        result->detections_count = 0;\n        result->error_message = strdup(e.what());\n    }\n\n    return result;\n}", "meta": {"hexsha": "702092287fecfa0be24581a0846ccf877e77537a", "size": 5509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "detector.cpp", "max_stars_repo_name": "dimuls/face", "max_stars_repo_head_hexsha": "f40e65cc792cbaee09d996beba995efa0b487e0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T15:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-12T03:00:33.000Z", "max_issues_repo_path": "detector.cpp", "max_issues_repo_name": "dimuls/face", "max_issues_repo_head_hexsha": "f40e65cc792cbaee09d996beba995efa0b487e0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-09T15:43:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T07:17:50.000Z", "max_forks_repo_path": "detector.cpp", "max_forks_repo_name": "dimuls/face", "max_forks_repo_head_hexsha": "f40e65cc792cbaee09d996beba995efa0b487e0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-30T09:14:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T09:14:33.000Z", "avg_line_length": 36.4834437086, "max_line_length": 165, "alphanum_fraction": 0.6463968052, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.17790044865908963}}
{"text": "/*\n * Copyright (C) 2019-2021 LEIDOS.\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\n#include <ros/ros.h>\n#include <string>\n#include <algorithm>\n#include <memory>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <lanelet2_core/geometry/Point.h>\n#include <trajectory_utils/trajectory_utils.h>\n#include <trajectory_utils/conversions/conversions.h>\n#include <sstream>\n#include <carma_utils/containers/containers.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <inlanecruising_plugin/inlanecruising_plugin.h>\n\n\n\n\nusing oss = std::ostringstream;\n\nnamespace inlanecruising_plugin\n{\nInLaneCruisingPlugin::InLaneCruisingPlugin(carma_wm::WorldModelConstPtr wm, InLaneCruisingPluginConfig config,\n                                           PublishPluginDiscoveryCB plugin_discovery_publisher, DebugPublisher debug_publisher)\n  : wm_(wm), config_(config), plugin_discovery_publisher_(plugin_discovery_publisher), debug_publisher_(debug_publisher)\n{\n  plugin_discovery_msg_.name = \"InLaneCruisingPlugin\";\n  plugin_discovery_msg_.versionId = \"v1.0\";\n  plugin_discovery_msg_.available = true;\n  plugin_discovery_msg_.activated = false;\n  plugin_discovery_msg_.type = cav_msgs::Plugin::TACTICAL;\n  plugin_discovery_msg_.capability = \"tactical_plan/plan_trajectory\";\n}\n\nbool InLaneCruisingPlugin::onSpin()\n{\n  plugin_discovery_publisher_(plugin_discovery_msg_);\n  return true;\n}\n\nbool InLaneCruisingPlugin::plan_trajectory_cb(cav_srvs::PlanTrajectoryRequest& req,\n                                              cav_srvs::PlanTrajectoryResponse& resp)\n{\n   ros::WallTime start_time = ros::WallTime::now();  // Start timeing the execution time for planning so it can be logged\n\n  lanelet::BasicPoint2d veh_pos(req.vehicle_state.X_pos_global, req.vehicle_state.Y_pos_global);\n  double current_downtrack = wm_->routeTrackPos(veh_pos).downtrack;\n\n  // Only plan the trajectory for the initial LANE_FOLLOWING maneuver and any immediately sequential maneuvers of the same type\n  std::vector<cav_msgs::Maneuver> maneuver_plan;\n  for(size_t i = req.maneuver_index_to_plan; i < req.maneuver_plan.maneuvers.size(); i++)\n  {\n    if(req.maneuver_plan.maneuvers[i].type == cav_msgs::Maneuver::LANE_FOLLOWING)\n    {\n      maneuver_plan.push_back(req.maneuver_plan.maneuvers[i]);\n      resp.related_maneuvers.push_back(i);\n    }\n    else\n    {\n      break;\n    }\n  }\n\n  basic_autonomy:: waypoint_generation::DetailedTrajConfig wpg_detail_config;\n  basic_autonomy:: waypoint_generation::GeneralTrajConfig wpg_general_config;\n\n  wpg_general_config = basic_autonomy:: waypoint_generation::compose_general_trajectory_config(\"inlanecruising\",\n                                                                              config_.default_downsample_ratio,\n                                                                              config_.turn_downsample_ratio);\n\n  wpg_detail_config = basic_autonomy:: waypoint_generation::compose_detailed_trajectory_config(config_.trajectory_time_length, \n                                                                            config_.curve_resample_step_size, config_.minimum_speed, \n                                                                            config_.max_accel * config_.max_accel_multiplier,\n                                                                            config_.lateral_accel_limit * config_.lat_accel_multiplier, \n                                                                            config_.speed_moving_average_window_size, \n                                                                            config_.curvature_moving_average_window_size, config_.back_distance,\n                                                                            config_.buffer_ending_downtrack);\n  \n  auto points_and_target_speeds = basic_autonomy::waypoint_generation::create_geometry_profile(maneuver_plan, std::max((double)0, current_downtrack - config_.back_distance),\n                                                                         wm_, ending_state_before_buffer_, req.vehicle_state, wpg_general_config, wpg_detail_config);\n\n  ROS_DEBUG_STREAM(\"points_and_target_speeds: \" << points_and_target_speeds.size());\n\n  ROS_DEBUG_STREAM(\"PlanTrajectory\");\n\n  cav_msgs::TrajectoryPlan original_trajectory;\n  original_trajectory.header.frame_id = \"map\";\n  original_trajectory.header.stamp = ros::Time::now();\n  original_trajectory.trajectory_id = boost::uuids::to_string(boost::uuids::random_generator()());\n\n  original_trajectory.trajectory_points = basic_autonomy:: waypoint_generation::compose_lanefollow_trajectory_from_path(points_and_target_speeds, \n                                                                                req.vehicle_state, req.header.stamp, wm_, ending_state_before_buffer_, debug_msg_, \n                                                                                wpg_detail_config); // Compute the trajectory\n  original_trajectory.initial_longitudinal_velocity = std::max(req.vehicle_state.longitudinal_vel, config_.minimum_speed);\n\n  // Set the planning plugin field name\n  for (auto& p : original_trajectory.trajectory_points) {\n    p.planner_plugin_name = plugin_discovery_msg_.name;\n  }\n  \n  \n  if (config_.enable_object_avoidance)\n  {\n    ROS_DEBUG_STREAM(\"Activate Object Avoidance\");\n    if (yield_client_ && yield_client_.exists() && yield_client_.isValid())\n    {\n      ROS_DEBUG_STREAM(\"Yield Client is valid\");\n      cav_srvs::PlanTrajectory yield_srv;\n      yield_srv.request.initial_trajectory_plan = original_trajectory;\n      yield_srv.request.vehicle_state = req.vehicle_state;\n\n      if (yield_client_.call(yield_srv))\n      {\n        ROS_DEBUG_STREAM(\"Received Traj from Yield\");\n        cav_msgs::TrajectoryPlan yield_plan = yield_srv.response.trajectory_plan;\n        if (validate_yield_plan(yield_plan))\n        {\n          ROS_DEBUG_STREAM(\"Yield trajectory validated\");\n          resp.trajectory_plan = yield_plan;\n        }\n        else\n        {\n          throw std::invalid_argument(\"Invalid Yield Trajectory\");\n        }\n      }\n      else\n      {\n        throw std::invalid_argument(\"Unable to Call Yield Plugin\");\n      }\n    }\n    else\n    {\n      throw std::invalid_argument(\"Yield Client is unavailable\");\n    }\n    \n  }\n  else\n  {\n    ROS_DEBUG_STREAM(\"Ignored Object Avoidance\");\n    resp.trajectory_plan = original_trajectory;\n  }\n\n  if (config_.publish_debug) { // Publish the debug message if in debug logging mode\n    debug_msg_.trajectory_plan = resp.trajectory_plan;\n    debug_publisher_(debug_msg_); \n  }\n  \n  resp.maneuver_status.push_back(cav_srvs::PlanTrajectory::Response::MANEUVER_IN_PROGRESS);\n\n  ros::WallTime end_time = ros::WallTime::now();  // Planning complete\n\n  ros::WallDuration duration = end_time - start_time;\n  ROS_DEBUG_STREAM(\"ExecutionTime: \" << duration.toSec());\n\n  return true;\n}\n\nvoid InLaneCruisingPlugin::set_yield_client(ros::ServiceClient& client)\n{\n  yield_client_ = client;\n}\n\nbool InLaneCruisingPlugin::validate_yield_plan(const cav_msgs::TrajectoryPlan& yield_plan)\n{\n  if (yield_plan.trajectory_points.size()>= 2)\n  {\n    ROS_DEBUG_STREAM(\"Yield Trajectory Time\" << (double)yield_plan.trajectory_points[0].target_time.toSec());\n    ROS_DEBUG_STREAM(\"Now:\" << (double)ros::Time::now().toSec());\n    if (yield_plan.trajectory_points[0].target_time + ros::Duration(5.0) > ros::Time::now())\n    {\n      return true;\n    }\n    else\n    {\n      ROS_DEBUG_STREAM(\"Old Yield Trajectory\");\n    }\n  }\n  else\n  {\n    ROS_DEBUG_STREAM(\"Invalid Yield Trajectory\"); \n  }\n  return false;\n}\n\n\n}  // namespace inlanecruising_plugin", "meta": {"hexsha": "f285498d824e793921e91672a2540c1a8e0e11fb", "size": 8164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "inlanecruising_plugin/src/inlanecruising_plugin.cpp", "max_stars_repo_name": "usdot-fhwa-stol/carma-platform", "max_stars_repo_head_hexsha": "d45a1afbf1efdb0b8cd62fcec5a3033b7306df33", "max_stars_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2020-04-27T17:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:27:14.000Z", "max_issues_repo_path": "inlanecruising_plugin/src/inlanecruising_plugin.cpp", "max_issues_repo_name": "usdot-fhwa-stol/carma-platform", "max_issues_repo_head_hexsha": "d45a1afbf1efdb0b8cd62fcec5a3033b7306df33", "max_issues_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_issues_count": 982.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T11:28:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:12:19.000Z", "max_forks_repo_path": "inlanecruising_plugin/src/inlanecruising_plugin.cpp", "max_forks_repo_name": "usdot-fhwa-stol/carma-platform", "max_forks_repo_head_hexsha": "d45a1afbf1efdb0b8cd62fcec5a3033b7306df33", "max_forks_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_forks_count": 57.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T15:48:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T23:31:45.000Z", "avg_line_length": 40.0196078431, "max_line_length": 173, "alphanum_fraction": 0.6743018128, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.17789513494881057}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/list.hpp>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/math/mean_and_variance.h>\n#include <xfel/metrology/legacy_scale/parameters.h>\n#include <xfel/metrology/legacy_scale/bandpass_gaussian.h>\n#include <xfel/metrology/legacy_scale/vector_collection.h>\n#include <xfel/metrology/legacy_scale/a_g_conversion.h>\n#include <xfel/metrology/legacy_scale/quadrants.h>\n\n#include <vector>\n#include <map>\n\nusing namespace boost::python;\nnamespace xfel{\nnamespace boost_python { namespace {\n\n  void\n  xfel_scale_init_module() {\n    using namespace boost::python;\n\n    typedef return_value_policy<return_by_value> rbv;\n    class_<xfel_legacy::parameter::parameter_array>(\n      \"parameter_array\",no_init)\n      .add_property(\"x\",\n       make_getter(&xfel_legacy::parameter::parameter_array::parameters, rbv()))\n      .add_property(\"gradients\",\n       make_getter(&xfel_legacy::parameter::parameter_array::gradients,rbv()))\n      .add_property(\"curvatures\",\n       make_getter(&xfel_legacy::parameter::parameter_array::curvatures,rbv()))\n    ;\n    class_<xfel_legacy::parameter::organizer_base>(\n      \"organizer_base\",init<>())\n      .def(\"register\",&xfel_legacy::parameter::organizer_base::register_array,\n        (arg(\"tag\"),arg(\"ndata\"),arg(\"kdim\")=1,arg(\"data\")))\n      .def(\"register_local\",&xfel_legacy::parameter::organizer_base::register_local_array,\n        (arg(\"tag\"),arg(\"ndata\"),arg(\"kdim\")=1,arg(\"data\")))\n      .def(\"as_x_array\",&xfel_legacy::parameter::organizer_base::as_x_array)\n      .def(\"get_gradient_array\",\n           (xfel_legacy::farray(xfel_legacy::parameter::organizer_base::*)()const)\n           &xfel_legacy::parameter::organizer_base::get_gradient_array)\n      .def(\"set_gradient_array\",&xfel_legacy::parameter::organizer_base::set_gradient_array)\n      .def(\"get_curvature_array\",&xfel_legacy::parameter::organizer_base::get_curvature_array)\n      .def(\"from_x_array\",&xfel_legacy::parameter::organizer_base::from_x_array)\n      .def(\"initialize_gradients_curvatures\",\n         &xfel_legacy::parameter::organizer_base::initialize_gradients_curvatures)\n      .def(\"rezero_gradients_curvatures\",\n         &xfel_legacy::parameter::organizer_base::rezero_gradients_curvatures)\n    ;\n    class_<xfel_legacy::algorithm::mark5_iteration,\n           bases<xfel_legacy::parameter::organizer_base> >(\n      \"mark5_iteration\",init<>())\n      .def(\"set_refined_origins_to_c\",\n         &xfel_legacy::algorithm::mark5_iteration::set_refined_origins_to_c)\n      .def(\"compute_target\",&xfel_legacy::algorithm::mark5_iteration::compute_target,\n        (arg_(\"tox\"),arg_(\"toy\"),\n         arg_(\"spotcx\"),arg_(\"spotcy\"),\n         arg_(\"spotfx\"),arg_(\"spotfy\"),\n         arg_(\"master_tiles\"), arg_(\"frames\"),\n         arg_(\"part_distance\")))\n      .def(\"compute_functional_only\",\n        &xfel_legacy::algorithm::mark5_iteration::compute_functional_only,\n        (arg_(\"tox\"),arg_(\"toy\"),\n         arg_(\"spotcx\"),arg_(\"spotcy\"),\n         arg_(\"spotfx\"),arg_(\"spotfy\"),\n         arg_(\"master_tiles\"), arg_(\"frames\"),\n         arg_(\"part_distance\")))\n      .add_property(\"model_calcx\",\n         make_getter(&xfel_legacy::algorithm::mark5_iteration::model_calcx, rbv()))\n      .add_property(\"model_calcy\",\n         make_getter(&xfel_legacy::algorithm::mark5_iteration::model_calcy, rbv()))\n      .def(\"set_vector_collection\",\n         &xfel_legacy::algorithm::mark5_iteration::set_vector_collection)\n      .def(\"uncorrected_detector_to_laboratory_frame\",\n        &xfel_legacy::algorithm::mark5_iteration::uncorrected_detector_to_laboratory_frame,\n        (arg_(\"tox\"),arg_(\"toy\"),\n         arg_(\"spotfx\"),arg_(\"spotfy\"),\n         arg_(\"master_tiles\")\n        ))\n    ;\n\n    class_<xfel_legacy::parameter::vector_array >(\n      \"vector_array\",init<>())\n      .add_property(\"gradients\",\n       make_getter(&xfel_legacy::parameter::vector_array::gradients,rbv()))\n    ;\n\n    class_<xfel_legacy::parameter::vector_collection >(\n      \"vector_collection\",init<>())\n      .def(init<xfel_legacy::iarray,xfel_legacy::marray>())\n      .def(\"collect_vector_information\",\n        &xfel_legacy::parameter::vector_collection::collect_vector_information)\n      .def(\"register\",\n        &xfel_legacy::parameter::vector_collection::register_tag,(arg_(\"tag\")))\n    ;\n\n    class_<xfel_legacy::parameter::streak_parameters >(\n      \"streak_parameters\",no_init)\n      .add_property(\"rotax\",make_getter(\n         &xfel_legacy::parameter::streak_parameters::rotax, rbv()))\n      .add_property(\"position\",make_getter(\n         &xfel_legacy::parameter::streak_parameters::position, rbv()))\n      .add_property(\"rotax_excursion_rad\",make_getter(\n         &xfel_legacy::parameter::streak_parameters::rotax_excursion_rad, rbv()))\n     ;\n\n    class_<xfel_legacy::parameter::bandpass_gaussian>(\"bandpass_gaussian\",\n      init<rstbx::bandpass::parameters_bp3 const&>(arg(\"parameters\")))\n      .def(\"set_active_areas\", &xfel_legacy::parameter::bandpass_gaussian::set_active_areas)\n      .def(\"set_sensor_model\", &xfel_legacy::parameter::bandpass_gaussian::set_sensor_model,(\n         arg(\"thickness_mm\"), arg(\"mu_rho\"), arg(\"signal_penetration\")))\n      .def(\"picture_fast_slow_force\",\n         &xfel_legacy::parameter::bandpass_gaussian::picture_fast_slow_force)\n      .def(\"gaussian_fast_slow\",\n         &xfel_legacy::parameter::bandpass_gaussian::gaussian_fast_slow)\n      .add_property(\"hi_E_limit\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::hi_E_limit, rbv()))\n      .add_property(\"lo_E_limit\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::lo_E_limit, rbv()))\n      .add_property(\"mean_position\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::mean_position, rbv()))\n      .add_property(\"calc_radial_length\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::calc_radial_length, rbv()))\n      .add_property(\"part_distance\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::part_distance, rbv()))\n      .add_property(\"observed_flag\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::observed_flag, rbv()))\n      .def(\"set_subpixel\", &xfel_legacy::parameter::bandpass_gaussian::set_subpixel)\n      .def(\"set_mosaicity\", &xfel_legacy::parameter::bandpass_gaussian::set_mosaicity)\n      .def(\"set_domain_size\", &xfel_legacy::parameter::bandpass_gaussian::set_domain_size)\n      .def(\"set_bandpass\", &xfel_legacy::parameter::bandpass_gaussian::set_bandpass)\n      .def(\"set_orientation\", &xfel_legacy::parameter::bandpass_gaussian::set_orientation)\n      .def(\"set_detector_origin\",\n         &xfel_legacy::parameter::bandpass_gaussian::set_detector_origin)\n      .def(\"set_distance\", &xfel_legacy::parameter::bandpass_gaussian::set_distance)\n      .def(\"set_vector_output_pointers\",\n         &xfel_legacy::parameter::bandpass_gaussian::set_vector_output_pointers,\n         (arg_(\"vector_collection\"),arg_(\"frame_id\")))\n      .def(\"measure_bandpass_and_mosaic_parameters\", &\n      xfel_legacy::parameter::bandpass_gaussian::measure_bandpass_and_mosaic_parameters\n         ,(arg(\"radial\"), arg(\"azimut\"), arg(\"domain_sz_inv_ang\"),\n           arg(\"lab_frame_obs\")\n          ))\n      .add_property(\"wavelength_fit_ang\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::wavelength_fit_ang, rbv()))\n      .add_property(\"mosaicity_fit_rad\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::mosaicity_fit_rad, rbv()))\n      .add_property(\"wavelength_fit_ang_sigma\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::wavelength_fit_ang_sigma, rbv()))\n      .add_property(\"mosaicity_fit_rad_sigma\",make_getter(\n         &xfel_legacy::parameter::bandpass_gaussian::mosaicity_fit_rad_sigma, rbv()))\n      .def(\"simple_forward_calculation_spot_position\",\n           &xfel_legacy::parameter::bandpass_gaussian::simple_forward_calculation_spot_position,\n           (arg_(\"wavelength\"), arg_(\"observation_no\")))\n      .def(\"simple_part_excursion_part_rotxy\",\n           &xfel_legacy::parameter::bandpass_gaussian::simple_part_excursion_part_rotxy,\n           (arg_(\"wavelength\"), arg_(\"observation_no\"),\n            arg_(\"dA_drotxy\")))\n    ;\n\n    //class_<cctbx::agconvert::AG>(\"AGconvert\", init<>())\n    //  .def(\"forward\", &cctbx::agconvert::AG::forward)\n    //  .def(\"validate_and_setG\", &cctbx::agconvert::AG::validate_and_setG)\n    //  .def(\"back_as_orientation\", &cctbx::agconvert::AG::back_as_orientation)\n    //  .def(\"back\", &cctbx::agconvert::AG::back)\n    //  .add_property(\"G\",make_getter(&cctbx::agconvert::AG::G, rbv()))\n    //;\n    def(\"best_fit_limit\",xfel_legacy::parameter::best_fit_limit);\n    def(\"quadrant_self_correlation\",xfel_legacy::qsc);\n  }\n\n}\n}} // namespace xfel::boost_python::<anonymous>\n\nBOOST_PYTHON_MODULE(xfel_legacy_scale_ext)\n{\n  xfel::boost_python::xfel_scale_init_module();\n\n}\n", "meta": {"hexsha": "c2796574f13a1c126d6739474c783f21de3e0e79", "size": 9070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xfel/metrology/legacy_scale/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": "xfel/metrology/legacy_scale/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": "xfel/metrology/legacy_scale/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": 48.7634408602, "max_line_length": 96, "alphanum_fraction": 0.7054024256, "num_tokens": 2332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.17789513494881057}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2016.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Andreas Bertsch $\n// $Authors: Andreas Bertsch $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/COMPARISON/SPECTRA/SpectrumAlignmentScore.h>\n#include <OpenMS/COMPARISON/SPECTRA/SpectrumAlignment.h>\n#include <OpenMS/DATASTRUCTURES/ListUtils.h>\n#include <cmath>\n\n#include <boost/math/special_functions/erf.hpp>\n\nusing namespace std;\n\nnamespace OpenMS\n{\n  SpectrumAlignmentScore::SpectrumAlignmentScore() :\n    PeakSpectrumCompareFunctor()\n  {\n    setName(SpectrumAlignmentScore::getProductName());\n    defaults_.setValue(\"tolerance\", 0.3, \"Defines the absolute (in Da) or relative (in ppm) tolerance\");\n    defaults_.setValue(\"is_relative_tolerance\", \"false\", \"if true, the tolerance value is interpreted as ppm\");\n    defaults_.setValidStrings(\"is_relative_tolerance\", ListUtils::create<String>(\"true,false\"));\n    defaults_.setValue(\"use_linear_factor\", \"false\", \"if true, the intensities are weighted with the relative m/z difference\");\n    defaults_.setValidStrings(\"use_linear_factor\", ListUtils::create<String>(\"true,false\"));\n    defaults_.setValue(\"use_gaussian_factor\", \"false\", \"if true, the intensities are weighted with the relative m/z difference using a gaussian\");\n    defaults_.setValidStrings(\"use_gaussian_factor\", ListUtils::create<String>(\"true,false\"));\n    defaultsToParam_();\n  }\n\n  SpectrumAlignmentScore::SpectrumAlignmentScore(const SpectrumAlignmentScore & source) :\n    PeakSpectrumCompareFunctor(source)\n  {\n  }\n\n  SpectrumAlignmentScore::~SpectrumAlignmentScore()\n  {\n  }\n\n  SpectrumAlignmentScore & SpectrumAlignmentScore::operator=(const SpectrumAlignmentScore & source)\n  {\n    if (this != &source)\n    {\n      PeakSpectrumCompareFunctor::operator=(source);\n    }\n    return *this;\n  }\n\n  double SpectrumAlignmentScore::operator()(const PeakSpectrum & spec) const\n  {\n    return operator()(spec, spec);\n  }\n\n  double SpectrumAlignmentScore::operator()(const PeakSpectrum & s1, const PeakSpectrum & s2) const\n  {\n    const double tolerance = (double)param_.getValue(\"tolerance\");\n    bool is_relative_tolerance = param_.getValue(\"is_relative_tolerance\").toBool();\n    bool use_linear_factor = param_.getValue(\"use_linear_factor\").toBool();\n    bool use_gaussian_factor = param_.getValue(\"use_gaussian_factor\").toBool();\n\n    if (use_linear_factor && use_gaussian_factor)\n    {\n      cerr << \"Warning: SpectrumAlignmentScore, use either 'use_linear_factor' or 'use_gaussian_factor'!\" << endl;\n    }\n\n    SpectrumAlignment aligner;\n    Param p;\n    p.setValue(\"tolerance\", tolerance);\n    p.setValue(\"is_relative_tolerance\", (String)param_.getValue(\"is_relative_tolerance\"));\n    aligner.setParameters(p);\n\n    vector<pair<Size, Size> > alignment;\n    aligner.getSpectrumAlignment(alignment, s1, s2);\n\n    double score(0), sum(0), sum1(0), sum2(0);\n    for (PeakSpectrum::ConstIterator it1 = s1.begin(); it1 != s1.end(); ++it1)\n    {\n      sum1 += it1->getIntensity() * it1->getIntensity();\n    }\n\n    for (PeakSpectrum::ConstIterator it1 = s2.begin(); it1 != s2.end(); ++it1)\n    {\n      sum2 += it1->getIntensity() * it1->getIntensity();\n    }\n\n    for (vector<pair<Size, Size> >::const_iterator it = alignment.begin(); it != alignment.end(); ++it)\n    {\n      //double factor(0.0);\n      //factor = (epsilon - fabs(s1[it->first].getPosition()[0] - s2[it->second].getPosition()[0])) / epsilon;\n      double mz_tolerance(tolerance);\n\n      if (is_relative_tolerance)\n      {\n        mz_tolerance = mz_tolerance * s1[it->first].getPosition()[0] / 1e6;\n      }\n\n      double mz_difference(fabs(s1[it->first].getPosition()[0] - s2[it->second].getPosition()[0]));\n      double factor = 1.0;\n\n      if (use_linear_factor || use_gaussian_factor)\n      {\n        factor = getFactor_(mz_tolerance, mz_difference, use_gaussian_factor);\n      }\n      sum += sqrt(s1[it->first].getIntensity() * s2[it->second].getIntensity() * factor);\n    }\n\n    score = sum / (sqrt(sum1 * sum2));\n\n    return score;\n  }\n\n  double SpectrumAlignmentScore::getFactor_(double mz_tolerance, double mz_difference, bool is_gaussian) const\n  {\n    double factor(0.0);\n\n    if (is_gaussian)\n    {\n      static const double denominator = mz_tolerance * 3.0 * sqrt(2.0);\n      factor = boost::math::erfc(mz_difference / denominator);\n      //cerr << \"Factor: \" << factor << \" \" << mz_tolerance << \" \" << mz_difference << endl;\n    }\n    else\n    {\n      factor = (mz_tolerance - mz_difference) / mz_tolerance;\n    }\n    return factor;\n  }\n\n}\n", "meta": {"hexsha": "51bf4c2d8a6f647c3b7024780c00a8c26658213b", "size": 6481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/COMPARISON/SPECTRA/SpectrumAlignmentScore.cpp", "max_stars_repo_name": "mrurik/OpenMS", "max_stars_repo_head_hexsha": "3bf48247423dc28a7df7b12b72fbc7751965c321", "max_stars_repo_licenses": ["Zlib", "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/openms/source/COMPARISON/SPECTRA/SpectrumAlignmentScore.cpp", "max_issues_repo_name": "mrurik/OpenMS", "max_issues_repo_head_hexsha": "3bf48247423dc28a7df7b12b72fbc7751965c321", "max_issues_repo_licenses": ["Zlib", "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/openms/source/COMPARISON/SPECTRA/SpectrumAlignmentScore.cpp", "max_forks_repo_name": "mrurik/OpenMS", "max_forks_repo_head_hexsha": "3bf48247423dc28a7df7b12b72fbc7751965c321", "max_forks_repo_licenses": ["Zlib", "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.7610062893, "max_line_length": 146, "alphanum_fraction": 0.6650208301, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.17788593471416328}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <cassert>\n\n#include <ros/message_traits.h>\n#include <ros/serialization.h>\n\n#include <std_msgs/Float64.h>\n\n#include <sel_map_mesh/Defs.hpp>\n#include <Eigen/Dense>\n\n// Minimally define custom types to reduce copies for the message passing\nnamespace sel_map\n{\nnamespace msg_adaptor\n{\n\n  // Wrap a pointer to vertex normals\n  struct VertexNormalsArray\n  {\n    typedef Eigen::Ref<const sel_map::mesh::PointArray_t, Eigen::Aligned16>* _vertex_normals_ptr_type;\n    _vertex_normals_ptr_type vertex_normals_ptr;\n  };\n\n} // namespace msg_adaptor\n} // namespace sel_map\n\n\n// Make it work with ros (direct wraps are not publishable!)\nnamespace ros\n{\nnamespace serialization\n{\n\n  template<>\n  struct Serializer<sel_map::msg_adaptor::VertexNormalsArray>\n  {\n    template<typename Stream>\n    inline static void write(Stream& stream, const sel_map::msg_adaptor::VertexNormalsArray& m)\n    {\n      // For cleanliness\n      typedef std_msgs::Float64::_data_type float64_t;\n\n      // Prepend the OUTER vector length\n      uint32_t num_vertices = m.vertex_normals_ptr->rows();\n      stream.next(num_vertices);\n      // Eigen Map it to store\n      const uint32_t point_len = 3*(uint32_t)sizeof(float64_t);\n      auto res = Eigen::Map<Eigen::Array<float64_t, Eigen::Dynamic, 3, Eigen::RowMajor>,\n                            Eigen::Unaligned>((float64_t*)stream.advance(num_vertices*point_len), num_vertices, 3);\n      res = *m.vertex_normals_ptr;\n    }\n\n    template<typename Stream>\n    inline static void read(Stream& stream, sel_map::msg_adaptor::VertexNormalsArray& m)\n    {\n      // Not planning on considering this, so crash out\n      assert(false);\n    }\n\n    inline static uint32_t serializedLength(const sel_map::msg_adaptor::VertexNormalsArray& m)\n    {\n      // For cleanliness\n      typedef std_msgs::Float64::_data_type float64_t;\n\n      // Match the serialized length as found above\n      return (uint32_t)sizeof(uint32_t) + m.vertex_normals_ptr->rows() * 3 * (uint32_t)sizeof(float64_t);\n    }\n  };\n\n} // namespace serialization\n} // namespace ros", "meta": {"hexsha": "8ebec609fd48498636efd0216b54f7e3c796f354", "size": 2084, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sel_map_mesh_publisher/include/sel_map_mesh_publisher/msg_adaptor/VertexNormalsArrayAdaptor.hpp", "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_publisher/include/sel_map_mesh_publisher/msg_adaptor/VertexNormalsArrayAdaptor.hpp", "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_publisher/include/sel_map_mesh_publisher/msg_adaptor/VertexNormalsArrayAdaptor.hpp", "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": 28.1621621622, "max_line_length": 115, "alphanum_fraction": 0.7077735125, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17775843308769568}}
{"text": "#include \"tsdf_volume.h\"\n\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <Eigen/Geometry>\n#include <opencv2/highgui/highgui.hpp>\n\n\n\nTSDFVolume::TSDFVolume(const Vec3i &dimensions, const Vec3f &size, const Mat3f &K, const float truncationDistance, size_t frameNumber) :\n    m_dim(dimensions),\n    m_gridSize(m_dim[0] * m_dim[1] * m_dim[2]),\n    m_size(size),\n    m_voxelSize(Vec3f(m_size.cwiseQuotient(m_dim.cast<float>()))),\n    m_tsdf(0),\n    m_weights(0),\n    m_colorR(0),\n    m_colorG(0),\n    m_colorB(0),\n    m_weightsColor(0),\n    m_delta(truncationDistance),\n    m_deltaInv(1.0f / truncationDistance),\n    m_K(K),\n    m_frameNumber(frameNumber)\n{\n    init();\n}\n\n\nTSDFVolume::~TSDFVolume()\n{\n    release();\n}\n\n\nbool TSDFVolume::init()\n{\n    try\n    {\n        // allocate and initialize memory\n        m_tsdf = new float[m_gridSize];\n        std::fill_n(m_tsdf, m_gridSize, -1.0f);\n\n        m_weights = new float[m_gridSize];\n        std::fill_n(m_weights, m_gridSize, 0.0f);\n\n        unsigned char defaultColor = 127; //0;\n        m_colorR = new unsigned char[m_gridSize];\n        std::fill_n(m_colorR, m_gridSize, defaultColor);\n        m_colorG = new unsigned char[m_gridSize];\n        std::fill_n(m_colorG, m_gridSize, defaultColor);\n        m_colorB = new unsigned char[m_gridSize];\n        std::fill_n(m_colorB, m_gridSize, defaultColor);\n\n        m_weightsColor = new float[m_gridSize];\n        std::fill_n(m_weightsColor, m_gridSize, 0.0f);\n    }\n    catch (...)\n    {\n        release();\n        return false;\n    }\n    return true;\n}\n\n\nvoid TSDFVolume::release()\n{\n    delete[] m_tsdf;\n    m_tsdf = 0;\n    delete[] m_weights;\n    m_weights = 0;\n    delete[] m_colorR;\n    m_colorR = 0;\n    delete[] m_colorG;\n    m_colorG = 0;\n    delete[] m_colorB;\n    m_colorB = 0;\n    delete[] m_weightsColor;\n    m_weightsColor = 0;\n}\n\n\nfloat TSDFVolume::truncate(float sdf) const\n{\n    float tsdf = sdf;\n    if (tsdf > m_delta)\n        tsdf = m_delta;\n    else if (tsdf < -m_delta)\n        tsdf = -m_delta;\n    return tsdf * m_deltaInv;   // normalize tsdf value to interval [-1.0,...,1.0]\n}\n\n\nvoid TSDFVolume::integrate(const Mat4f &pose, const cv::Mat &color, const cv::Mat &depth, const cv::Mat &normals)\n{\n    Mat3f R = pose.topLeftCorner(3,3);\n    Vec3f t = pose.topRightCorner(3,1);\n\n    const float* ptrDepth = (float*)depth.data;\n    unsigned char* ptrColor = 0;\n    if (!color.empty())\n        ptrColor = (unsigned char*)color.data;\n    int h = depth.rows;\n    int w = depth.cols;\n    float fx = m_K(0, 0);\n    float fy = m_K(1, 1);\n    float cx = m_K(0, 2);\n    float cy = m_K(1, 2);\n\n    // project each voxel into output image\n    for (size_t z = 0; z < m_dim[2]; ++z)\n    {\n        for (size_t y = 0; y < m_dim[1]; ++y)\n        {\n            for (size_t x = 0; x < m_dim[0]; ++x)\n            {\n                size_t off = z*m_dim[0]*m_dim[1] + y*m_dim[0] + x;\n\n                // transform voxel into view\n                Vec3i vx(x, y, z);\n                Vec3f pt = voxelToWorld(vx);\n                Vec3f ptTf = R * pt + t;\n\n                // check if voxel is behind the camera\n                float distVoxel = ptTf[2];\n                if (distVoxel <= 0.0f)\n                    continue;\n\n                // project point into camera and round to nearest integer to avoid smearing out of object boundaries to the background\n                float zInv = 1.0f / ptTf[2];\n                float uf = (fx * ptTf[0] * zInv) + cx;\n                float vf = (fy * ptTf[1] * zInv) + cy;\n                int u = static_cast<int>(uf + 0.5f);\n                int v = static_cast<int>(vf + 0.5f);\n\n                if (u >= 0 && u < w && v >= 0 && v < h)\n                {\n                    size_t idx = v*w + u;\n                    size_t idx3 = idx * 3;\n                    float depthIn = ptrDepth[idx];\n                    if (depthIn == 0.0f || std::isnan(depthIn))\n                    {\n                        continue;\n                    }\n\n                    // compute tsdf value\n                    float sdfVal = ptTf[2] - depthIn;\n\n                    // truncate tsdf value\n                    float tsdfVal = truncate(sdfVal);\n\n                    // compute weight\n                    float wTsdf = 0.0f;\n                    if (sdfVal <= 0)//-m_delta)\n                    {\n                        wTsdf = 1.0f;\n                    }\n                    else if (sdfVal <= m_delta)\n                    {\n                        // constant weighting function\n                        // wTsdf = 1.0f;\n                        // linear weighting function\n                        //  wTsdf = (tsdfVal + 1.0f) / 2.0f;\n                        wTsdf = 1.0f - tsdfVal;\n                    }\n\n                    float wTsdfNew = 0.0f;\n                    if (wTsdf > 0.0f)\n                    {\n                        // average weight\n                        float wTsdfOld = m_weights[off];\n                        float tsdfOld = m_tsdf[off];\n                        // average tsdf value\n                        wTsdfNew = wTsdfOld + wTsdf;\n                        float tsdfNew = (tsdfOld * wTsdfOld + tsdfVal * wTsdf) / wTsdfNew;\n                        m_tsdf[off] = tsdfNew;\n\n                        m_weights[off] = wTsdfNew;\n                    }\n\n#if 1\n                    // separate weighting for colors\n                    float wColorOld = m_weightsColor[off];\n                    if (sdfVal <= m_delta || wColorOld == 0.0f)\n                    {\n                        float wColor = wTsdf;\n                        float wColorNew;\n                        Vec3b c(ptrColor[idx3], ptrColor[idx3+1], ptrColor[idx3+2]);\n                        unsigned char cR = c[2];\n                        unsigned char cG = c[1];\n                        unsigned char cB = c[0];\n                        if (wColorOld == 0.0f)\n                        {\n                            wColorNew = wColor;\n                        }\n                        else\n                        {\n                            // compute color averaging weights\n                            wColorNew = wColorOld + wColor;\n                            float w0 = wColorOld / wColorNew;\n                            float w1 = 1.0f - w0;\n                            // compute average color\n                            cR = (unsigned char)(m_colorR[off] * w0 + cR * w1);\n                            cG = (unsigned char)(m_colorG[off] * w0 + cG * w1);\n                            cB = (unsigned char)(m_colorB[off] * w0 + cB * w1);\n                        }\n                        m_weightsColor[off] = wColorNew;\n\n                        // voxel color\n                        m_colorR[off] = cR;\n                        m_colorG[off] = cG;\n                        m_colorB[off] = cB;\n                    }\n#endif\n                }\n            }\n        }\n    }\n}\n\n\nfloat TSDFVolume::interpolate3(float x, float y, float z) const\n{\n    Vec3f pt(x, y, z);\n    Vec3f voxel = (pt + m_size.cast<float>()*0.5f).cwiseQuotient(m_voxelSize);\n    return interpolate3voxel(voxel[0], voxel[1], voxel[2]);\n}\n\n\nfloat TSDFVolume::interpolate3voxel(float x, float y, float z) const\n{\n    Vec3f voxel(x, y, z);\n    if (voxel[0] < 0.0f || voxel[0] > m_dim[0] - 1 ||\n            voxel[1] < 0.0f || voxel[1] > m_dim[1] - 1 ||\n            voxel[2] < 0.0f || voxel[2] > m_dim[2] - 1)\n        return -1.0f;\n\n    // tri-linear interpolation\n    const int x0 = static_cast<int>(voxel[0]);\n    const int y0 = static_cast<int>(voxel[1]);\n    const int z0 = static_cast<int>(voxel[2]);\n    const int x1 = x0 + 1;\n    const int y1 = y0 + 1;\n    const int z1 = z0 + 1;\n\n    if (x1 >= m_dim[0] || y1 >= m_dim[1] || z1 >= m_dim[2])\n        return m_tsdf[z0 * m_dim[0] * m_dim[1] + y0 * m_dim[0] + x0];\n\n    const float xd = voxel[0] - x0;\n    const float yd = voxel[1] - y0;\n    const float zd = voxel[2] - z0;\n\n    const float sdf000 = m_tsdf[z0 * m_dim[0] * m_dim[1] + y0 * m_dim[0] + x0];\n    const float sdf010 = m_tsdf[z0 * m_dim[0] * m_dim[1] + y1 * m_dim[0] + x0];\n    const float sdf001 = m_tsdf[z1 * m_dim[0] * m_dim[1] + y0 * m_dim[0] + x0];\n    const float sdf011 = m_tsdf[z1 * m_dim[0] * m_dim[1] + y1 * m_dim[0] + x0];\n    const float sdf100 = m_tsdf[z0 * m_dim[0] * m_dim[1] + y0 * m_dim[0] + x1];\n    const float sdf110 = m_tsdf[z0 * m_dim[0] * m_dim[1] + y1 * m_dim[0] + x1];\n    const float sdf101 = m_tsdf[z1 * m_dim[0] * m_dim[1] + y0 * m_dim[0] + x1];\n    const float sdf111 = m_tsdf[z1 * m_dim[0] * m_dim[1] + y1 * m_dim[0] + x1];\n\n    const float c00 = sdf000 * (1.0f - xd) + sdf100 * xd;\n    const float c10 = sdf010 * (1.0f - xd) + sdf110 * xd;\n    const float c01 = sdf001 * (1.0f - xd) + sdf101 * xd;\n    const float c11 = sdf011 * (1.0f - xd) + sdf111 * xd;\n\n    const float c0 = c00 * (1.0f - yd) + c10 * yd;\n    const float c1 = c01 * (1.0f - yd) + c11 * yd;\n\n    return c0 * (1.0f - zd) + c1 * zd;\n}\n\n\nbool TSDFVolume::load(const std::string &filename)\n{\n    std::ifstream inFile(filename.c_str(), std::ios::binary);\n    if (!inFile.is_open())\n        return false;\n\n    release();\n\n    inFile.read((char*)m_dim.data(), sizeof(int) * 3);\n    m_gridSize = m_dim[0] * m_dim[1] * m_dim[2];\n    inFile.read((char*)m_size.data(), sizeof(double) * 3);\n    inFile.read((char*)&m_delta, sizeof(float));\n    m_deltaInv = 1.0f / m_delta;\n\n    bool ok = init();\n\n    inFile.read((char*)m_tsdf, sizeof(float) * m_gridSize);\n    inFile.read((char*)m_weights, sizeof(float) * m_gridSize);\n\n    inFile.read((char*)m_colorR, sizeof(unsigned char) * m_gridSize);\n    inFile.read((char*)m_colorG, sizeof(unsigned char) * m_gridSize);\n    inFile.read((char*)m_colorB, sizeof(unsigned char) * m_gridSize);\n    inFile.read((char*)m_weightsColor, sizeof(float) * m_gridSize);\n\n    inFile.close();\n\n    return ok;\n}\n\n\nbool TSDFVolume::save(const std::string &filename)\n{\n    std::ofstream outFile(filename.c_str(), std::ios::binary);\n    if (!outFile.is_open())\n        return false;\n\n    outFile.write((const char*)m_dim.data(), sizeof(int) * 3);\n    outFile.write((const char*)m_size.data(), sizeof(double) * 3);\n    outFile.write((const char*)&m_delta, sizeof(float));\n    outFile.write((const char*)m_tsdf, sizeof(float) * m_gridSize);\n    outFile.write((const char*)m_weights, sizeof(float) * m_gridSize);\n\n    outFile.write((const char*)m_colorR, sizeof(unsigned char) * m_gridSize);\n    outFile.write((const char*)m_colorG, sizeof(unsigned char) * m_gridSize);\n    outFile.write((const char*)m_colorB, sizeof(unsigned char) * m_gridSize);\n    outFile.write((const char*)m_weightsColor, sizeof(float) * m_gridSize);\n\n    outFile.close();\n}\n\n\nVec3f TSDFVolume::surfaceNormal(int i, int j, int k)\n{\n    Vec3f n = Vec3f::Zero();\n    if (i < 0 || j < 0 || k < 0 ||\n            i >= m_dim[0]-1 || j >= m_dim[1]-1 || k >= m_dim[2]-1)\n        return n;\n\n    size_t idx0 = k * m_dim[0] * m_dim[1] + j * m_dim[0] + i;\n    size_t idx1 = k * m_dim[0] * m_dim[1] + j * m_dim[0] + (i+1);\n    size_t idx2 = k * m_dim[0] * m_dim[1] + (j+1) * m_dim[0] + i;\n    size_t idx3 = (k+1) * m_dim[0] * m_dim[1] + j * m_dim[0] + i;\n\n    float sdf0 = m_tsdf[idx0];\n    n[0] = m_tsdf[idx1] - sdf0;\n    n[1] = m_tsdf[idx2] - sdf0;\n    n[2] = m_tsdf[idx3] - sdf0;\n    if (n.norm() != 0.0f)\n        n.normalize();\n    return n;\n}\n\n\n\nvoid TSDFVolume::bbox(Vec3 &min, Vec3 &max) const\n{\n    min = Vec3(-m_size[0]*0.5, -m_size[1]*0.5, -m_size[2]*0.5);\n    max = Vec3(m_size[0]*0.5, m_size[1]*0.5, m_size[2]*0.5);\n}\n\n\nvoid TSDFVolume::setSize(const Vec3f &size)\n{\n    m_size = size;\n    m_voxelSize = m_size.cwiseQuotient(m_dim.cast<float>());\n}\n\n\nVec3f TSDFVolume::size() const\n{\n    return m_size;\n}\n\n\nVec3i TSDFVolume::dimensions() const\n{\n    return m_dim;\n}\n\n\nVec3f TSDFVolume::voxelToWorld(const Vec3i &voxel) const\n{\n    Vec3f pt = voxel.cast<float>().cwiseProduct(m_voxelSize) - m_size*0.5f;\n    return pt;\n}\n\n\nVec3f TSDFVolume::voxelToWorld(int i, int j, int k) const\n{\n    return voxelToWorld(Vec3i(i, j, k));\n}\n\n\nVec3f TSDFVolume::voxelToWorld(const Vec3f &voxel) const\n{\n    Vec3f pt = voxel.cwiseProduct(m_voxelSize) - m_size*0.5f;\n    return pt;\n}\n\n\nVec3i TSDFVolume::worldToVoxel(const Vec3f &pt) const\n{\n    Vec3f voxelSizeInv(1.0 / m_voxelSize[0], 1.0 / m_voxelSize[1], 1.0 / m_voxelSize[2]);\n    Vec3f voxelF = (pt + 0.5f * m_size).cwiseProduct(voxelSizeInv);\n    Vec3i voxelIdx = voxelF.cast<int>();\n    return voxelIdx;\n}\n\n\nVec3f TSDFVolume::worldToVoxelF(const Vec3f &pt) const\n{\n    Vec3f voxelSizeInv(1.0 / m_voxelSize[0], 1.0 / m_voxelSize[1], 1.0 / m_voxelSize[2]);\n    Vec3f voxelF = (pt + 0.5f * m_size).cwiseProduct(voxelSizeInv);\n    return voxelF;\n}\n", "meta": {"hexsha": "c9554c8cefbccf3d23845f4dbeb20d8ea5764d73", "size": 12652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tsdf_volume.cpp", "max_stars_repo_name": "al093/killingFusionCuda", "max_stars_repo_head_hexsha": "fbcdf54628bb63815d7953b65add08e0a8c5bf6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-03-15T15:24:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T13:37:46.000Z", "max_issues_repo_path": "src/tsdf_volume.cpp", "max_issues_repo_name": "al093/killingFusionCuda", "max_issues_repo_head_hexsha": "fbcdf54628bb63815d7953b65add08e0a8c5bf6b", "max_issues_repo_licenses": ["MIT"], "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/tsdf_volume.cpp", "max_forks_repo_name": "al093/killingFusionCuda", "max_forks_repo_head_hexsha": "fbcdf54628bb63815d7953b65add08e0a8c5bf6b", "max_forks_repo_licenses": ["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.7834549878, "max_line_length": 136, "alphanum_fraction": 0.5247391717, "num_tokens": 3908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.17775842581990478}}
{"text": "//   GAMBIT: Global and Modular BSM Inference Tool\n//   *********************************************\n///  \\file\n///\n///  Declarations of B->Kstar mumu theory error\n///  class.\n///\n///  *********************************************\n///\n///  Authors (add name and date if you modify):\n///\n///  \\author Marcin Chrzaszcz\n///          (mchrzasz@cern.ch)\n///  \\date 2016 August\n///\n///  \\author Pat Scott\n///          (p.scott@imperial.ac.uk)\n///  \\date 2017 Mar\n///\n///  *********************************************\n\n#ifndef __Kstarmumu_theory_err_hpp__\n#define __Kstarmumu_theory_err_hpp__\n\n#include \"gambit/Utils/util_types.hpp\"\n#include <boost/numeric/ublas/matrix.hpp>\n\n\nnamespace Gambit\n{\n\n  namespace FlavBit\n  {\n\n    /// Holder for theory errors for B->K* mumu observables\n    class Kstarmumu_theory_err\n    {\n\n      private:\n\n        int size_obs;\n        std::vector<str> names_obs;\n        std::vector< std::vector< double > >covariance;\n        std::map<str,int> map_kstarmumu;\n\n      public:\n\n        /// Constructor\n        Kstarmumu_theory_err();\n        /// Return theory error covariance matrix for selected observables\n        boost::numeric::ublas::matrix<double> get_th_cov(std::vector<str> observables);\n\n    };\n\n  }\n\n}\n\n#endif //#defined __Kstarmumu_theory_err_hpp__\n", "meta": {"hexsha": "abee1463c878afbee08c42a013d2a6ef325674a6", "size": 1285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "FlavBit/include/gambit/FlavBit/Kstarmumu_theory_err.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "FlavBit/include/gambit/FlavBit/Kstarmumu_theory_err.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "FlavBit/include/gambit/FlavBit/Kstarmumu_theory_err.hpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 21.4166666667, "max_line_length": 87, "alphanum_fraction": 0.5657587549, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17773704742558014}}
{"text": "\n//\u6b64\u6e90\u7801\u88ab\u6e05\u534e\u5b66\u795e\u5c39\u6210\u5927\u9b54\u738b\u4e13\u4e1a\u7ffb\u8bd1\u5206\u6790\u5e76\u4fee\u6539\n//\u5c39\u6210QQ77025077\n//\u5c39\u6210\u5fae\u4fe118510341407\n//\u5c39\u6210\u6240\u5728QQ\u7fa4721929980\n//\u5c39\u6210\u90ae\u7bb1 yinc13@mails.tsinghua.edu.cn\n//\u5c39\u6210\u6bd5\u4e1a\u4e8e\u6e05\u534e\u5927\u5b66,\u5fae\u8f6f\u533a\u5757\u94fe\u9886\u57df\u5168\u7403\u6700\u6709\u4ef7\u503c\u4e13\u5bb6\n//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620\n//\u7248\u6743\u6240\u6709\uff08c\uff092010 Satoshi Nakamoto\n//\u7248\u6743\u6240\u6709\uff08c\uff092009-2018\u6bd4\u7279\u5e01\u6838\u5fc3\u5f00\u53d1\u8005\n//\u6839\u636eMIT\u8f6f\u4ef6\u8bb8\u53ef\u8bc1\u5206\u53d1\uff0c\u8bf7\u53c2\u89c1\u968f\u9644\u7684\n//\u6587\u4ef6\u590d\u5236\u6216http://www.opensource.org/licenses/mit-license.php\u3002\n\n#include <rpc/blockchain.h>\n\n#include <amount.h>\n#include <base58.h>\n#include <chain.h>\n#include <chainparams.h>\n#include <checkpoints.h>\n#include <coins.h>\n#include <consensus/validation.h>\n#include <core_io.h>\n#include <hash.h>\n#include <index/txindex.h>\n#include <key_io.h>\n#include <policy/feerate.h>\n#include <policy/policy.h>\n#include <policy/rbf.h>\n#include <primitives/transaction.h>\n#include <rpc/server.h>\n#include <rpc/util.h>\n#include <script/descriptor.h>\n#include <streams.h>\n#include <sync.h>\n#include <txdb.h>\n#include <txmempool.h>\n#include <util/strencodings.h>\n#include <util/system.h>\n#include <validation.h>\n#include <validationinterface.h>\n#include <versionbitsinfo.h>\n#include <warnings.h>\n\n#include <assert.h>\n#include <stdint.h>\n\n#include <univalue.h>\n\n#include <boost/thread/thread.hpp> //boost\uff1a\uff1a\u7ebf\u7a0b\uff1a\uff1a\u4e2d\u65ad\n\n#include <memory>\n#include <mutex>\n#include <condition_variable>\n\nstruct CUpdatedBlock\n{\n    uint256 hash;\n    int height;\n};\n\nstatic Mutex cs_blockchange;\nstatic std::condition_variable cond_blockchange;\nstatic CUpdatedBlock latestblock;\n\n/*\u8ba1\u7b97\u7ed9\u5b9a\u5757\u7d22\u5f15\u7684\u96be\u5ea6\u3002\n **/\n\ndouble GetDifficulty(const CBlockIndex* blockindex)\n{\n    assert(blockindex);\n\n    int nShift = (blockindex->nBits >> 24) & 0xff;\n    double dDiff =\n        (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);\n\n    while (nShift < 29)\n    {\n        dDiff *= 256.0;\n        nShift++;\n    }\n    while (nShift > 29)\n    {\n        dDiff /= 256.0;\n        nShift--;\n    }\n\n    return dDiff;\n}\n\nstatic int ComputeNextBlockAndDepth(const CBlockIndex* tip, const CBlockIndex* blockindex, const CBlockIndex*& next)\n{\n    next = tip->GetAncestor(blockindex->nHeight + 1);\n    if (next && next->pprev == blockindex) {\n        return tip->nHeight - blockindex->nHeight + 1;\n    }\n    next = nullptr;\n    return blockindex == tip ? 1 : -1;\n}\n\nUniValue blockheaderToJSON(const CBlockIndex* tip, const CBlockIndex* blockindex)\n{\n    UniValue result(UniValue::VOBJ);\n    result.pushKV(\"hash\", blockindex->GetBlockHash().GetHex());\n    const CBlockIndex* pnext;\n    int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);\n    result.pushKV(\"confirmations\", confirmations);\n    result.pushKV(\"height\", blockindex->nHeight);\n    result.pushKV(\"version\", blockindex->nVersion);\n    result.pushKV(\"versionHex\", strprintf(\"%08x\", blockindex->nVersion));\n    result.pushKV(\"merkleroot\", blockindex->hashMerkleRoot.GetHex());\n    result.pushKV(\"time\", (int64_t)blockindex->nTime);\n    result.pushKV(\"mediantime\", (int64_t)blockindex->GetMedianTimePast());\n    result.pushKV(\"nonce\", (uint64_t)blockindex->nNonce);\n    result.pushKV(\"bits\", strprintf(\"%08x\", blockindex->nBits));\n    result.pushKV(\"difficulty\", GetDifficulty(blockindex));\n    result.pushKV(\"chainwork\", blockindex->nChainWork.GetHex());\n    result.pushKV(\"nTx\", (uint64_t)blockindex->nTx);\n\n    if (blockindex->pprev)\n        result.pushKV(\"previousblockhash\", blockindex->pprev->GetBlockHash().GetHex());\n    if (pnext)\n        result.pushKV(\"nextblockhash\", pnext->GetBlockHash().GetHex());\n    return result;\n}\n\nUniValue blockToJSON(const CBlock& block, const CBlockIndex* tip, const CBlockIndex* blockindex, bool txDetails)\n{\n    UniValue result(UniValue::VOBJ);\n    result.pushKV(\"hash\", blockindex->GetBlockHash().GetHex());\n    const CBlockIndex* pnext;\n    int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);\n    result.pushKV(\"confirmations\", confirmations);\n    result.pushKV(\"strippedsize\", (int)::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS));\n    result.pushKV(\"size\", (int)::GetSerializeSize(block, PROTOCOL_VERSION));\n    result.pushKV(\"weight\", (int)::GetBlockWeight(block));\n    result.pushKV(\"height\", blockindex->nHeight);\n    result.pushKV(\"version\", block.nVersion);\n    result.pushKV(\"versionHex\", strprintf(\"%08x\", block.nVersion));\n    result.pushKV(\"merkleroot\", block.hashMerkleRoot.GetHex());\n    UniValue txs(UniValue::VARR);\n    for(const auto& tx : block.vtx)\n    {\n        if(txDetails)\n        {\n            UniValue objTx(UniValue::VOBJ);\n            TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags());\n            txs.push_back(objTx);\n        }\n        else\n            txs.push_back(tx->GetHash().GetHex());\n    }\n    result.pushKV(\"tx\", txs);\n    result.pushKV(\"time\", block.GetBlockTime());\n    result.pushKV(\"mediantime\", (int64_t)blockindex->GetMedianTimePast());\n    result.pushKV(\"nonce\", (uint64_t)block.nNonce);\n    result.pushKV(\"bits\", strprintf(\"%08x\", block.nBits));\n    result.pushKV(\"difficulty\", GetDifficulty(blockindex));\n    result.pushKV(\"chainwork\", blockindex->nChainWork.GetHex());\n    result.pushKV(\"nTx\", (uint64_t)blockindex->nTx);\n\n    if (blockindex->pprev)\n        result.pushKV(\"previousblockhash\", blockindex->pprev->GetBlockHash().GetHex());\n    if (pnext)\n        result.pushKV(\"nextblockhash\", pnext->GetBlockHash().GetHex());\n    return result;\n}\n\nstatic UniValue getblockcount(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            RPCHelpMan{\"getblockcount\",\n                \"\\nReturns the number of blocks in the longest blockchain.\\n\", {}}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"n    (numeric) The current block count\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getblockcount\", \"\")\n            + HelpExampleRpc(\"getblockcount\", \"\")\n        );\n\n    LOCK(cs_main);\n    return chainActive.Height();\n}\n\nstatic UniValue getbestblockhash(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            RPCHelpMan{\"getbestblockhash\",\n                \"\\nReturns the hash of the best (tip) block in the longest blockchain.\\n\", {}}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"\\\"hex\\\"      (string) the block hash, hex-encoded\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getbestblockhash\", \"\")\n            + HelpExampleRpc(\"getbestblockhash\", \"\")\n        );\n\n    LOCK(cs_main);\n    return chainActive.Tip()->GetBlockHash().GetHex();\n}\n\nvoid RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)\n{\n    if(pindex) {\n        std::lock_guard<std::mutex> lock(cs_blockchange);\n        latestblock.hash = pindex->GetBlockHash();\n        latestblock.height = pindex->nHeight;\n    }\n    cond_blockchange.notify_all();\n}\n\nstatic UniValue waitfornewblock(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() > 1)\n        throw std::runtime_error(\n            RPCHelpMan{\"waitfornewblock\",\n                \"\\nWaits for a specific new block and returns useful info about it.\\n\"\n                \"\\nReturns the current block on timeout or exit.\\n\",\n                {\n                    /*\u8d85\u65f6\u201c\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/true\uff0c/*default_val*/\u201d0\u201c\uff0c\u201d\u7b49\u5f85\u54cd\u5e94\u7684\u65f6\u95f4\uff08\u6beb\u79d2\uff09\u30020\u8868\u793a\u6ca1\u6709\u8d85\u65f6\u3002\u201c\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c\uff08JSON\u5bf9\u8c61\\n\u201d\n            \u201c\\\u201d\u54c8\u5e0c\\\u201c\uff1a\uff08\u5b57\u7b26\u4e32\uff09\u5757\u54c8\u5e0c\\n\u201d\n            \u201c\u9ad8\u5ea6\\\u201d\uff1a\uff08int\uff09\u5757\u9ad8\u5ea6\\n\u201d\n            \u201c}\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpExamplecli\uff08\u201cwaitfornewblock\u201d\uff0c\u201c1000\u201d\uff09\u3002\n            +HelpExampleRPC\uff08\u201cWaitForNewBlock\u201d\uff0c\u201c1000\u201d\uff09\u3002\n        \uff1b\n    int\u8d85\u65f6=0\uff1b\n    \u5982\u679c\uff08\uff01\uff09\u8bf7\u6c42.params[0].isNull\uff08\uff09\uff09\n        timeout=request.params[0].get_int\uff08\uff09\uff1b\n\n    CupdatedBlock\u5757\uff1b\n    {\n        \u7b49\u5f85\u9501\u5b9a\uff08cs-blockchange\uff0clock\uff09\uff1b\n        block=\u6700\u65b0block\uff1b\n        \u5982\u679c\uff08\u8d85\u65f6\uff09\n            cond_blockchange.wait_for\uff08lock\uff0cstd:\uff1achrono:\uff1amillises\uff08timeout\uff09\uff0c[&block]\u8fd4\u56delatestblock.height\uff01=block.height latestblock.hash\uff01=block.hash\uff01isrpcrunning\uff08\uff09\uff1b\uff09\uff09\uff1b\n        \u5176\u4ed6\u7684\n            Cond_BlockChange.wait\uff08\u9501\u5b9a\uff0c[&block]\u8fd4\u56delatestblock.height\uff01=block.height latestblock.hash\uff01=block.hash\uff01isrpcrunning\uff08\uff09\uff1b\uff09\uff09\uff1b\n        block=\u6700\u65b0block\uff1b\n    }\n    \u5355\u503cret\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n    ret.pushkv\uff08\u201chash\u201d\uff0cblock.hash.gethex\uff08\uff09\uff09\uff1b\n    ret.pushkv\uff08\u201c\u9ad8\u5ea6\u201d\uff0c\u5757\u9ad8\u5ea6\uff09\uff1b\n    \u8fd4\u56deRET\uff1b\n}\n\n\u9759\u6001\u5355\u503cWaitForBlock\uff08const jsonrpcrequest&request\uff09\n{\n    if\uff08request.fhelp request.params.size\uff08\uff09<1 request.params.size\uff08\uff09>2\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201c\u7b49\u5f85\u963b\u6b62\u201d\uff0c\n                \\n\u7b49\u5f85\u7279\u5b9a\u7684\u65b0\u5757\u5e76\u8fd4\u56de\u6709\u5173\u5b83\u7684\u6709\u7528\u4fe1\u606f\u3002\\n\n                \\n\u5728\u8d85\u65f6\u6216\u9000\u51fa\u65f6\u8fd4\u56de\u5f53\u524d\u5757\u3002\\n\u201c\uff0c\n                {\n                    \u201cblockhash\u201d\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/ false, /* default_val */ \"\", \"Block hash to wait for.\"},\n\n                    /*\u8d85\u65f6\u201c\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/true\uff0c/*default_val*/\u201d0\u201c\uff0c\u201d\u7b49\u5f85\u54cd\u5e94\u7684\u65f6\u95f4\uff08\u6beb\u79d2\uff09\u30020\u8868\u793a\u6ca1\u6709\u8d85\u65f6\u3002\u201c\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c\uff08JSON\u5bf9\u8c61\\n\u201d\n            \u201c\\\u201d\u54c8\u5e0c\\\u201c\uff1a\uff08\u5b57\u7b26\u4e32\uff09\u5757\u54c8\u5e0c\\n\u201d\n            \u201c\u9ad8\u5ea6\\\u201d\uff1a\uff08int\uff09\u5757\u9ad8\u5ea6\\n\u201d\n            \u201c}\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpExamplecli\uff08\u201cwaitForBlock\u201d\uff0c\u201c000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\u201d\uff0c\u201c1000\u201d\uff09\u3002\n            +\u5e2e\u52a9\u793a\u4f8brpc\uff08\u201cWaitForBlock\u201d\uff0c\u201c000000000079F8EF3D2C688C2444EB7A4570B24C9ED7B4A8C619EB02596F8862\u201d\uff0c\u201c1000\u201d\uff09\u3002\n        \uff1b\n    int\u8d85\u65f6=0\uff1b\n\n    uint256\u6563\u5217\uff08parsehashv\uff08request.params[0]\uff0c\u201cblockhash\u201d\uff09\uff09\uff1b\n\n    \u5982\u679c\uff08\uff01\uff09\u8bf7\u6c42.params[1].isNull\uff08\uff09\uff09\n        timeout=request.params[1].get_int\uff08\uff09\uff1b\n\n    CupdatedBlock\u5757\uff1b\n    {\n        \u7b49\u5f85\u9501\u5b9a\uff08cs-blockchange\uff0clock\uff09\uff1b\n        \u5982\u679c\uff08\u8d85\u65f6\uff09\n            cond_blockchange.wait_for\uff08lock\uff0cstd:\uff1achrono:\uff1amillises\uff08timeout\uff09\uff0c[&hash]\u8fd4\u56delatestblock.hash==hash\uff01isrpcrunning\uff08\uff09\uff1b\uff09\uff09\uff1b\n        \u5176\u4ed6\u7684\n            cond_blockchange.wait\uff08lock\uff0c[&hash]\u8fd4\u56delatestblock.hash==hash\uff01isrpcrunning\uff08\uff09\uff1b\uff09\uff09\uff1b\n        block=\u6700\u65b0block\uff1b\n    }\n\n    \u5355\u503cret\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n    ret.pushkv\uff08\u201chash\u201d\uff0cblock.hash.gethex\uff08\uff09\uff09\uff1b\n    ret.pushkv\uff08\u201c\u9ad8\u5ea6\u201d\uff0c\u5757\u9ad8\u5ea6\uff09\uff1b\n    \u8fd4\u56deRET\uff1b\n}\n\n\u9759\u6001\u5355\u503cWaitForBlockHeight\uff08const jsonrpcrequest&request\uff09\n{\n    if\uff08request.fhelp request.params.size\uff08\uff09<1 request.params.size\uff08\uff09>2\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201c\u7b49\u5f85\u9501\u9ad8\u5ea6\u201d\uff0c\n                \\n\u7b49\u5f85\uff08\u81f3\u5c11\uff09\u5757\u9ad8\u5ea6\u5e76\u8fd4\u56de\u9ad8\u5ea6\u548c\u54c8\u5e0c\u503c\\n\n                \u201c\u5f53\u524d\u63d0\u793a\u7684\u5185\u5bb9\u3002\\n\u201d\n                \\n\u5728\u8d85\u65f6\u6216\u9000\u51fa\u65f6\u8fd4\u56de\u5f53\u524d\u5757\u3002\\n\u201c\uff0c\n                {\n                    \u201c\u9ad8\u5ea6\u201d\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/ false, /* default_val */ \"\", \"Block height to wait for.\"},\n\n                    /*\u8d85\u65f6\u201c\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/true\uff0c/*default_val*/\u201d0\u201c\uff0c\u201d\u7b49\u5f85\u54cd\u5e94\u7684\u65f6\u95f4\uff08\u6beb\u79d2\uff09\u30020\u8868\u793a\u6ca1\u6709\u8d85\u65f6\u3002\u201c\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c\uff08JSON\u5bf9\u8c61\\n\u201d\n            \u201c\\\u201d\u54c8\u5e0c\\\u201c\uff1a\uff08\u5b57\u7b26\u4e32\uff09\u5757\u54c8\u5e0c\\n\u201d\n            \u201c\u9ad8\u5ea6\\\u201d\uff1a\uff08int\uff09\u5757\u9ad8\u5ea6\\n\u201d\n            \u201c}\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpexamplecli\uff08\u201cwaitForBlockHeight\u201d\uff0c\u201c100\u201d\uff0c\u201c1000\u201d\uff09\u3002\n            +helpExampleRPC\uff08\u201cwaitForBlockHeight\u201d\uff0c\u201c100\u201d\uff0c\u201c1000\u201d\uff09\u3002\n        \uff1b\n    int\u8d85\u65f6=0\uff1b\n\n    int height=request.params[0].get_int\uff08\uff09\uff1b\n\n    \u5982\u679c\uff08\uff01\uff09\u8bf7\u6c42.params[1].isNull\uff08\uff09\uff09\n        timeout=request.params[1].get_int\uff08\uff09\uff1b\n\n    CupdatedBlock\u5757\uff1b\n    {\n        \u7b49\u5f85\u9501\u5b9a\uff08cs-blockchange\uff0clock\uff09\uff1b\n        \u5982\u679c\uff08\u8d85\u65f6\uff09\n            cond_blockchange.wait_for\uff08lock\uff0cstd:\uff1achrono:\uff1amillises\uff08timeout\uff09\uff0c[&height]return latestblock.height>=height\uff01isrpcrunning\uff08\uff09\uff1b\uff09\uff09\uff1b\n        \u5176\u4ed6\u7684\n            cond_blockchange.wait\uff08lock\uff0c[&height]\u8fd4\u56delatestblock.height>=height\uff01isrpcrunning\uff08\uff09\uff1b\uff09\uff09\uff1b\n        block=\u6700\u65b0block\uff1b\n    }\n    \u5355\u503cret\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n    ret.pushkv\uff08\u201chash\u201d\uff0cblock.hash.gethex\uff08\uff09\uff09\uff1b\n    ret.pushkv\uff08\u201c\u9ad8\u5ea6\u201d\uff0c\u5757\u9ad8\u5ea6\uff09\uff1b\n    \u8fd4\u56deRET\uff1b\n}\n\n\u9759\u6001\u5355\u503c\u540c\u6b65\u4e0evalidationInterfaceQueue\uff08const jsonrpcrequest&request\uff09\n{\n    if\uff08request.fhelp request.params.size\uff08\uff09>0\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201c\u4e0evalidationInterfaceQueue\u540c\u6b65\u201d\uff0c\n                \u201c\\n\u7b49\u5f85\u9a8c\u8bc1\u63a5\u53e3\u961f\u5217\u5728\u6211\u4eec\u8fdb\u5165\u6b64\u51fd\u6570\u65f6\u8d76\u4e0a\u90a3\u91cc\u7684\u6240\u6709\u5185\u5bb9\u3002\\n\u201d\uff0c\n                toSTRIN\uff08\uff09+\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpExamplecli\uff08\u201c\u4e0evalidationInterfaceQueue\u540c\u6b65\u201d\uff0c\u201c\u201d\uff09\n            +helpExampleRpc\uff08\u201c\u4e0evalidationInterfaceQueue\u540c\u6b65\u201d\uff0c\u201c\u201d\uff09\n        \uff1b\n    }\n    \u4e0evalidationInterfaceQueue\uff08\uff09\u540c\u6b65\uff1b\n    \u8fd4\u56denullunivalue\uff1b\n}\n\n\u9759\u6001\u5355\u503c\u83b7\u53d6\u96be\u5ea6\uff08const jsonrpcrequest&request\uff09\n{\n    \u5982\u679c\uff08request.fhelp request.params.size\uff08\uff09\uff01= 0\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201c\u83b7\u53d6\u96be\u5ea6\u201d\uff0c\n                \\n\u5c06\u5de5\u4f5c\u96be\u5ea6\u7684\u8bc1\u660e\u4f5c\u4e3a\u6700\u5c0f\u96be\u5ea6\u7684\u500d\u6570\u8fd4\u56de\u3002\\n\u201c\u201d\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201cN.n n n\uff08\u6570\u5b57\uff09\u4f5c\u4e3a\u6700\u5c0f\u96be\u5ea6\u7684\u500d\u6570\u7684\u5de5\u4f5c\u96be\u5ea6\u8bc1\u660e\u3002\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpExamplecli\uff08\u201cGetDifficulty\u201d\uff0c\u201c\u201d\uff09\n            +helpExampleRpc\uff08\u201c\u83b7\u53d6\u96be\u5ea6\u201d\uff0c\u201c\uff09\n        \uff1b\n\n    \u9501\uff08CSKEMAN\uff09\uff1b\n    \u8fd4\u56degetDifficulty\uff08chainActive.tip\uff08\uff09\uff09\uff1b\n}\n\n\u9759\u6001Std:\uff1aString EntryDescriptionString\uff08\uff09\n{\n    \u8fd4\u56de\u201c\u5927\u5c0f\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09BIP 141\u4e2d\u5b9a\u4e49\u7684\u865a\u62df\u4e8b\u52a1\u5927\u5c0f\u3002\u8fd9\u4e0e\u8bc1\u4eba\u4e8b\u52a1\u7684\u5b9e\u9645\u5e8f\u5217\u5316\u5927\u5c0f\u4e0d\u540c\uff0c\u56e0\u4e3a\u8bc1\u4eba\u6570\u636e\u5df2\u6298\u6263\u3002\\n\u201c\n           \u201c\u8d39\u7528\\\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u4ee5\u201c+\u8d27\u5e01\\\u5355\u4f4d+\u201d\u8868\u793a\u7684\u4ea4\u6613\u8d39\u7528\uff08\u5df2\u5f03\u7528\uff09\\n\u201d\n           \u201c\\\u201dModifiedFee\\\u201c\uff1an\uff0c\uff08\u6570\u5b57\uff09\u7528\u4e8e\u6316\u6398\u4f18\u5148\u7ea7\u7684\u8d39\u7528\u589e\u91cf\u4ea4\u6613\u8d39\uff08\u5df2\u5f03\u7528\uff09\\n\u201d\n           \u201c\u201c\u65f6\u95f4\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u672c\u5730\u65f6\u95f4\u4e8b\u52a1\u81ea1970\u5e741\u67081\u65e5\u683c\u6797\u5a01\u6cbb\u6807\u51c6\u65f6\u95f4\u4ee5\u6765\u4ee5\u79d2\u4e3a\u5355\u4f4d\u8f93\u5165\u6c60\\n\u201d\n           \u201c\u9ad8\u5ea6\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u5f53\u4e8b\u52a1\u8f93\u5165\u6c60\u65f6\u5757\u9ad8\u5ea6\\n\u201d\n           \u201c\u201cDescendantCount\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u5185\u5b58\u6c60\u4e2d\u7684\u540e\u4ee3\u4e8b\u52a1\u6570\uff08\u5305\u62ec\u6b64\u4e8b\u52a1\uff09\\n\u201d\n           \u201c\u201c\u5b50\u4f53\u5927\u5c0f\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u5185\u5b58\u6c60\u5b50\u4f53\uff08\u5305\u62ec\u6b64\u5b50\u4f53\uff09\u7684\u865a\u62df\u4e8b\u52a1\u5927\u5c0f\\n\u201d\n           \u201c\u5b50\u4ee3\u8d39\u7528\\\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u4fee\u6539\u4e86mempool\u5b50\u4ee3\uff08\u5305\u62ec\u6b64\u5b50\u4ee3\uff09\u7684\u8d39\u7528\uff08\u89c1\u4e0a\u6587\uff09\uff08\u5df2\u5f03\u7528\uff09\\n\u201d\n           \u201cAncestorCount\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u5185\u5b58\u6c60\u4e2d\u7684\u7956\u5148\u4e8b\u52a1\u6570\uff08\u5305\u62ec\u6b64\u4e8b\u52a1\uff09\\n\u201d\n           \u201cAncestorSize\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u5185\u5b58\u6c60\u4e2d\u7956\u5148\u7684\u865a\u62df\u4e8b\u52a1\u5927\u5c0f\uff08\u5305\u62ec\u6b64\u4e8b\u52a1\u5927\u5c0f\uff09\\n\u201d\n           \u201cAncestorfees\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u4fee\u6539\u4e86mempool\u7956\u5148\uff08\u5305\u62ec\u6b64\u7956\u5148\uff09\u7684\u8d39\u7528\uff08\u89c1\u4e0a\u6587\uff09\uff08\u5df2\u5f03\u7528\uff09\\n\u201d\n           \u201c\u201cwtxid\u201d\uff1a\u54c8\u5e0c\uff0c\uff08\u5b57\u7b26\u4e32\uff09\u5e8f\u5217\u5316\u4e8b\u52a1\u7684\u54c8\u5e0c\uff0c\u5305\u62ec\u89c1\u8bc1\u6570\u636e\\n\u201d\n           \u201c\u8d39\u7528\\\u201d\uff1a\\n\u201d\n           \u201c\u57fa\u6570\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u4ee5\u201c+\u8d27\u5e01\\\u5355\u4f4d+\u201d\u8868\u793a\u7684\u4ea4\u6613\u8d39\\n\u201d\n           \u201c\\\u201d\u5df2\u4fee\u6539\\\u201c\uff1an\uff0c\uff08\u6570\u5b57\uff09\u4ee5\u201c+\u8d27\u5e01\\\u5355\u4f4d+\u201d\u8868\u793a\u7684\u7528\u4e8e\u6316\u6398\u4f18\u5148\u7ea7\u7684\u8d39\u7528\u589e\u91cf\u7684\u4ea4\u6613\u8d39\u7528\\n\u201d\n           \u201c\u7956\u5148\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u4ee5\u201c+\u8d27\u5e01\\\u5355\u4f4d+\u201d\u8868\u793a\u7684mempool\u7956\u5148\uff08\u5305\u62ec\u6b64\u7956\u5148\uff09\u7684\u4fee\u6539\u8d39\u7528\uff08\u89c1\u4e0a\u6587\uff09\u3002\\n\u201d\n           \u201c\\\u201d\u5b50\u4f53\\\u201c\uff1an\uff0c\uff08\u6570\u5b57\uff09\u4ee5\u201c+\u8d27\u5e01\\\u5355\u4f4d+\u201d\u4fee\u6539\u4e86mempool\u5b50\u4f53\uff08\u5305\u62ec\u6b64\u5b50\u4f53\uff09\u7684\u8d39\u7528\uff08\u89c1\u4e0a\u6587\uff09\u3002\\n\u201d\n           \u201c}\\n\u201d\n           \u201c\u4f9d\u8d56\u4e8e\u201d\uff1a[\uff08\u6570\u7ec4\uff09\u672a\u786e\u8ba4\u7684\u4e8b\u52a1\uff0c\u7528\u4f5c\u6b64\u4e8b\u52a1\u7684\u8f93\u5165\\n\u201d\n           \u201c\\\u201dtransaction id\\\u201c\uff0c\uff08string\uff09\u7236\u4e8b\u52a1id\\n\u201d\n           \u201c\u2026\u2026\u201d\\n\n           \u201c\\\u201dSpentby\\\u201c\uff1a[\uff08\u6570\u7ec4\uff09\u672a\u786e\u8ba4\u7684\u4e8b\u52a1\u652f\u51fa\u6b64\u4e8b\u52a1\u7684\u8f93\u51fa\\n\u201d\n           \u201ctransaction id\\\u201d\uff0c\uff08string\uff09\u5b50\u4e8b\u52a1id \\n\u201d\n           \u201c\u2026\u2026\u201d\\n\n           \u201c\\\u201dbip125 replacement\\\u201d\uff1atrue false\uff0c\uff08\u5e03\u5c14\u503c\uff09\u7531\u4e8ebip125\uff08\u66ff\u6362\u4e3a\u8d39\u7528\uff09\u662f\u5426\u53ef\u4ee5\u66ff\u6362\u6b64\u4e8b\u52a1\\n\u201d\uff1b\n}\n\n\u9759\u6001void entryTojson\uff08univalue&info\uff0cconst ctxmempoolEntry&e\uff09\u9700\u8981\u552f\u4e00\u7684\u9501\uff08\uff1a\uff1amempool.cs\uff09\n{\n    \u65ad\u8a00\u9501\u5b9a\uff08mempool.cs\uff09\uff1b\n\n    \u5355\u503c\u8d39\u7528\uff08\u5355\u503c\uff1a\uff1aVOBJ\uff09\uff1b\n    fees.pushkv\uff08\u201c\u57fa\u7840\u201d\uff0cvaluefromamount\uff08e.getfee\uff08\uff09\uff09\uff1b\n    fees.pushkv\uff08\u201c\u5df2\u4fee\u6539\u201d\uff0cvaluefromamount\uff08e.getModifiedFee\uff08\uff09\uff09\uff1b\n    fees.pushkv\uff08\u201c\u7956\u5148\u201d\uff0cvaluefromamount\uff08e.getmodfeeswith\u7956\u5148\uff08\uff09\uff09\uff1b\n    fees.pushkv\uff08\u201c\u540e\u4ee3\u201d\uff0cvalueFromAmount\uff08e.GetModFeesWithDescendants\uff08\uff09\uff09\uff1b\n    \u4fe1\u606f\uff1apushkv\uff08\u201c\u8d39\u7528\u201d\uff0c\u8d39\u7528\uff09\uff1b\n\n    info.pushkv\uff08\u201c\u5927\u5c0f\u201d\uff0c\uff08int\uff09e.gettxsize\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201c\u8d39\u7528\u201d\uff0cvaluefromamount\uff08e.getfee\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201cmodifiedfee\u201d\uff0cvaluefromamount\uff08e.getmodifiedfee\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201c\u65f6\u95f4\u201d\uff0ce.gettime\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201c\u9ad8\u5ea6\u201d\uff0c\uff08int\uff09e.getheight\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201cDescendantCount\u201d\uff0ce.getCountWithDescendants\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201cDescendantSize\u201d\uff0ce.getSizeWithDescendants\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201cDescendantFees\u201d\uff0ce.getModFeesWithDescendants\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201cAncestorCount\u201d\uff0ce.getCountWithOrights\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201cancestorsize\u201d\uff0ce.getsizewith\u7956\u5148\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201cancestorfees\u201d\uff0ce.getmodfeeswith\u7956\u5148\uff08\uff09\uff09\uff1b\n    info.pushkv\uff08\u201cwtxid\u201d\uff0cmempool.vtxhash[e.vtxhashesidx].first.toString\uff08\uff09\uff09\uff1b\n    const ctransaction&tx=e.gettx\uff08\uff09\uff1b\n    std:\uff1aset<std:\uff1astring>setdepends\uff1b\n    \u7528\u4e8e\uff08const ctxin\u548ctxin:tx.vin\uff09\n    {\n        if\uff08mempool.exists\uff08txin.prevout.hash\uff09\uff09\u3002\n            setDepends.insert\uff08txin.prevout.hash.toString\uff08\uff09\uff09\uff1b\n    }\n\n    \u5355\u503c\u4f9d\u8d56\uff08\u5355\u503c\uff1a\uff1avarr\uff09\uff1b\n    for\uff08const std:\uff1astring&dep:setdepends\uff09\n    {\n        \u89c6\u60c5\u51b5\u800c\u5b9a\u3002\u5411\u540e\u63a8\uff08DEP\uff09\uff1b\n    }\n\n    \u4fe1\u606f\uff1apushkv\uff08\u201c\u53d6\u51b3\u4e8e\u201d\uff0c\u53d6\u51b3\u4e8e\uff09\uff1b\n\n    \u82b1\u8d39\u7684\u5355\u503c\uff08\u5355\u503c\uff1a\uff1avarr\uff09\uff1b\n    const ctxmempool:\uff1atxter&it=mempool.maptx.find\uff08tx.gethash\uff08\uff09\uff09\uff1b\n    const ctxmempool:\uff1asetentries&setchildren=mempool.getmempoolchildren\uff08it\uff09\uff1b\n    \u5bf9\u4e8e\uff08ctxmempool:\uff1atxter childiter:setchildren\uff09\n        speed.push_back\uff08childiter->gettx\uff08\uff09.gethash\uff08\uff09.toString\uff08\uff09\uff09\uff1b\n    }\n\n    \u4fe1\u606f\uff1apushkv\uff08\u201cspentby\u201d\uff0c\u5df2\u7528\uff09\uff1b\n\n    //\u6dfb\u52a0\u9009\u62e9\u52a0\u5165RBF\u72b6\u6001\n    bool rbfstatus=\u5047\uff1b\n    rbftTransactionState rbfstate=isrbfoptin\uff08tx\uff0cmempool\uff09\uff1b\n    if\uff08rbfstate==rbftTransactionState:\uff1aUnknown\uff09\n        throw jsonrpcerror\uff08rpc_misc_error\uff0c\u201ctransaction is not in mempool\u201d\uff09\uff1b\n    else if\uff08rbfstate==rbfttransactionstate:\uff1areplacement_bip125\uff09\n        rbfstatus=\u771f\uff1b\n    }\n\n    \u4fe1\u606fpushkv\uff08\u201cbip125\u53ef\u66ff\u6362\u201d\uff0crbfstatus\uff09\uff1b\n}\n\n\u5355\u503cmempooltokson\uff08bool fverbose\uff09\n{\n    \u5982\u679c\uff08FVBBOSE\uff09\n    {\n        \u9501\uff08mempool.cs\uff09\uff1b\n        \u5355\u503co\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n        \u7528\u4e8e\uff08const ctxmempool entry&e:mempool.maptx\uff09\n        {\n            const uint256&hash=e.gettx\uff08\uff09.gethash\uff08\uff09\uff1b\n            \u5355\u503c\u4fe1\u606f\uff08univalue:\uff1avobj\uff09\uff1b\n            EntryTojson\uff08\u4fe1\u606f\uff0cE\uff09\uff1b\n            o.pushkv\uff08hash.toString\uff08\uff09\uff0c\u4fe1\u606f\uff09\uff1b\n        }\n        \u8fd4\u56deO\uff1b\n    }\n    \u5176\u4ed6\u7684\n    {\n        std:\uff1avector<uint256>vtxid\uff1b\n        mempool.queryhashes\uff08vtxid\uff09\uff1b\n\n        \u5355\u503cA\uff08\u5355\u503c\uff1a\uff1avarr\uff09\uff1b\n        for\uff08const uint256&hash:vtxid\uff09\n            a.\u5411\u540e\u63a8\uff08hash.toString\uff08\uff09\uff09\uff1b\n\n        \u8fd4\u56deA\uff1b\n    }\n}\n\n\u9759\u6001\u5355\u503cgetrawmupool\uff08const-jsonrpcrequest&request\uff09\n{\n    if\uff08request.fhelp request.params.size\uff08\uff09>1\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201cgetrawmempool\u201d\uff0c\n                \\n\u5c06\u5185\u5b58\u6c60\u4e2d\u7684\u6240\u6709\u4e8b\u52a1ID\u4f5c\u4e3a\u5b57\u7b26\u4e32\u4e8b\u52a1ID\u7684JSON\u6570\u7ec4\u8fd4\u56de\u3002\\n\n                \\nhint:\u4f7f\u7528getmempoolentry\u4ecemempool\u4e2d\u63d0\u53d6\u7279\u5b9a\u4e8b\u52a1\u3002\\n\u201c\uff0c\n                {\n                    \u201cverbose\u201d\uff0crpcarg:\uff1atype:\uff1abool\uff0c/*opt*/ true, /* default_val */ \"false\", \"True for a json object, false for array of transaction ids\"},\n\n                }}\n                .ToString() +\n            \"\\nResult: (for verbose = false):\\n\"\n            \"[                     (json array of string)\\n\"\n            \"  \\\"transactionid\\\"     (string) The transaction id\\n\"\n            \"  ,...\\n\"\n            \"]\\n\"\n            \"\\nResult: (for verbose = true):\\n\"\n            \"{                           (json object)\\n\"\n            \"  \\\"transactionid\\\" : {       (json object)\\n\"\n            + EntryDescriptionString()\n            + \"  }, ...\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getrawmempool\", \"true\")\n            + HelpExampleRpc(\"getrawmempool\", \"true\")\n        );\n\n    bool fVerbose = false;\n    if (!request.params[0].isNull())\n        fVerbose = request.params[0].get_bool();\n\n    return mempoolToJSON(fVerbose);\n}\n\nstatic UniValue getmempoolancestors(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {\n        throw std::runtime_error(\n            RPCHelpMan{\"getmempoolancestors\",\n                \"\\nIf txid is in the mempool, returns all in-mempool ancestors.\\n\",\n                {\n                    /*xid\u201c\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/false\uff0c/*default_val*/\u201d\uff0c\u201c\u4e8b\u52a1ID\uff08\u5fc5\u987b\u5728mempool\u4e2d\uff09\u201d\uff0c\n                    \u201cverbose\u201d\uff0crpcarg:\uff1atype:\uff1abool\uff0c/*opt*/ true, /* default_val */ \"false\", \"True for a json object, false for array of transaction ids\"},\n\n                }}\n                .ToString() +\n            \"\\nResult (for verbose = false):\\n\"\n            \"[                       (json array of strings)\\n\"\n            \"  \\\"transactionid\\\"           (string) The transaction id of an in-mempool ancestor transaction\\n\"\n            \"  ,...\\n\"\n            \"]\\n\"\n            \"\\nResult (for verbose = true):\\n\"\n            \"{                           (json object)\\n\"\n            \"  \\\"transactionid\\\" : {       (json object)\\n\"\n            + EntryDescriptionString()\n            + \"  }, ...\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getmempoolancestors\", \"\\\"mytxid\\\"\")\n            + HelpExampleRpc(\"getmempoolancestors\", \"\\\"mytxid\\\"\")\n            );\n    }\n\n    bool fVerbose = false;\n    if (!request.params[1].isNull())\n        fVerbose = request.params[1].get_bool();\n\n    uint256 hash = ParseHashV(request.params[0], \"parameter 1\");\n\n    LOCK(mempool.cs);\n\n    CTxMemPool::txiter it = mempool.mapTx.find(hash);\n    if (it == mempool.mapTx.end()) {\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Transaction not in mempool\");\n    }\n\n    CTxMemPool::setEntries setAncestors;\n    uint64_t noLimit = std::numeric_limits<uint64_t>::max();\n    std::string dummy;\n    mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);\n\n    if (!fVerbose) {\n        UniValue o(UniValue::VARR);\n        for (CTxMemPool::txiter ancestorIt : setAncestors) {\n            o.push_back(ancestorIt->GetTx().GetHash().ToString());\n        }\n\n        return o;\n    } else {\n        UniValue o(UniValue::VOBJ);\n        for (CTxMemPool::txiter ancestorIt : setAncestors) {\n            const CTxMemPoolEntry &e = *ancestorIt;\n            const uint256& _hash = e.GetTx().GetHash();\n            UniValue info(UniValue::VOBJ);\n            entryToJSON(info, e);\n            o.pushKV(_hash.ToString(), info);\n        }\n        return o;\n    }\n}\n\nstatic UniValue getmempooldescendants(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {\n        throw std::runtime_error(\n            RPCHelpMan{\"getmempooldescendants\",\n                \"\\nIf txid is in the mempool, returns all in-mempool descendants.\\n\",\n                {\n                    /*xid\u201c\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/false\uff0c/*default_val*/\u201d\uff0c\u201c\u4e8b\u52a1ID\uff08\u5fc5\u987b\u5728mempool\u4e2d\uff09\u201d\uff0c\n                    \u201cverbose\u201d\uff0crpcarg:\uff1atype:\uff1abool\uff0c/*opt*/ true, /* default_val */ \"false\", \"True for a json object, false for array of transaction ids\"},\n\n                }}\n                .ToString() +\n            \"\\nResult (for verbose = false):\\n\"\n            \"[                       (json array of strings)\\n\"\n            \"  \\\"transactionid\\\"           (string) The transaction id of an in-mempool descendant transaction\\n\"\n            \"  ,...\\n\"\n            \"]\\n\"\n            \"\\nResult (for verbose = true):\\n\"\n            \"{                           (json object)\\n\"\n            \"  \\\"transactionid\\\" : {       (json object)\\n\"\n            + EntryDescriptionString()\n            + \"  }, ...\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getmempooldescendants\", \"\\\"mytxid\\\"\")\n            + HelpExampleRpc(\"getmempooldescendants\", \"\\\"mytxid\\\"\")\n            );\n    }\n\n    bool fVerbose = false;\n    if (!request.params[1].isNull())\n        fVerbose = request.params[1].get_bool();\n\n    uint256 hash = ParseHashV(request.params[0], \"parameter 1\");\n\n    LOCK(mempool.cs);\n\n    CTxMemPool::txiter it = mempool.mapTx.find(hash);\n    if (it == mempool.mapTx.end()) {\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Transaction not in mempool\");\n    }\n\n    CTxMemPool::setEntries setDescendants;\n    mempool.CalculateDescendants(it, setDescendants);\n//ctxmempool:\uff1acalculateDescendants\u5c06\u5305\u62ec\u7ed9\u5b9a\u7684Tx\n    setDescendants.erase(it);\n\n    if (!fVerbose) {\n        UniValue o(UniValue::VARR);\n        for (CTxMemPool::txiter descendantIt : setDescendants) {\n            o.push_back(descendantIt->GetTx().GetHash().ToString());\n        }\n\n        return o;\n    } else {\n        UniValue o(UniValue::VOBJ);\n        for (CTxMemPool::txiter descendantIt : setDescendants) {\n            const CTxMemPoolEntry &e = *descendantIt;\n            const uint256& _hash = e.GetTx().GetHash();\n            UniValue info(UniValue::VOBJ);\n            entryToJSON(info, e);\n            o.pushKV(_hash.ToString(), info);\n        }\n        return o;\n    }\n}\n\nstatic UniValue getmempoolentry(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1) {\n        throw std::runtime_error(\n            RPCHelpMan{\"getmempoolentry\",\n                \"\\nReturns mempool data for given transaction\\n\",\n                {\n                    /*xid\u201c\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/false\uff0c/*default_val*/\u201d\uff0c\u201c\u4e8b\u52a1ID\uff08\u5fc5\u987b\u5728mempool\u4e2d\uff09\u201d\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c\uff08JSON\u5bf9\u8c61\\n\u201d\n            +EntryDescriptionString\uff08\uff09\uff09\n            +\u201c}\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpexamplecli\uff08\u201cgetmempoolentry\u201d\uff0c\u201cmytxid\\\u201d\uff09\n            +helpExampleRpc\uff08\u201cgetmempoolentry\u201d\uff0c\u201cMyTxID\\\u201d\uff09\n        \uff1b\n    }\n\n    uint256 hash=parsehashv\uff08request.params[0]\uff0c\u201c\u53c2\u65701\u201d\uff09\uff1b\n\n    \u9501\uff08mempool.cs\uff09\uff1b\n\n    ctxmempool:\uff1atxter it=mempool.maptx.find\uff08\u54c8\u5e0c\uff09\uff1b\n    if\uff08it==mempool.maptx.end\uff08\uff09\uff09\n        throw jsonrpcerror\uff08rpc_invalid_address_or_key\uff0c\u201ctransaction not in mempool\u201d\uff09\uff1b\n    }\n\n    const ctxmempoolEntry&E=*IT\uff1b\n    \u5355\u503c\u4fe1\u606f\uff08univalue:\uff1avobj\uff09\uff1b\n    EntryTojson\uff08\u4fe1\u606f\uff0cE\uff09\uff1b\n    \u8fd4\u56de\u4fe1\u606f\uff1b\n}\n\n\u9759\u6001\u5355\u503cgetblockhash\uff08const jsonrpcrequest&request\uff09\n{\n    \u5982\u679c\uff08request.fhelp request.params.size\uff08\uff09\uff01= 1\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201cgetblockhash\u201d\uff0c\n                \\n\u8fd4\u56de\u6240\u63d0\u4f9b\u9ad8\u5ea6\u7684\u6700\u4f73\u533a\u5757\u94fe\u4e2d\u533a\u5757\u7684\u54c8\u5e0c\u503c\u3002\\n\u201c\uff0c\n                {\n                    \u201c\u9ad8\u5ea6\u201d\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/ false, /* default_val */ \"\", \"The height index\"},\n\n                }}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"\\\"hash\\\"         (string) The block hash\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getblockhash\", \"1000\")\n            + HelpExampleRpc(\"getblockhash\", \"1000\")\n        );\n\n    LOCK(cs_main);\n\n    int nHeight = request.params[0].get_int();\n    if (nHeight < 0 || nHeight > chainActive.Height())\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Block height out of range\");\n\n    CBlockIndex* pblockindex = chainActive[nHeight];\n    return pblockindex->GetBlockHash().GetHex();\n}\n\nstatic UniValue getblockheader(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)\n        throw std::runtime_error(\n            RPCHelpMan{\"getblockheader\",\n                \"\\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\\n\"\n                \"If verbose is true, returns an Object with information about blockheader <hash>.\\n\",\n                {\n                    /*lockhash\u201c\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/false\uff0c/*\u9ed8\u8ba4\u503c_val*/\u201d\u201c\uff0c\u201c\u5757\u54c8\u5e0c\u201d\uff0c\n                    \u201cverbose\u201d\uff0crpcarg:\uff1atype:\uff1abool\uff0c/*opt*/ true, /* default_val */ \"true\", \"true for a json object, false for the hex-encoded data\"},\n\n                }}\n                .ToString() +\n            \"\\nResult (for verbose = true):\\n\"\n            \"{\\n\"\n            \"  \\\"hash\\\" : \\\"hash\\\",     (string) the block hash (same as provided)\\n\"\n            \"  \\\"confirmations\\\" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\\n\"\n            \"  \\\"height\\\" : n,          (numeric) The block height or index\\n\"\n            \"  \\\"version\\\" : n,         (numeric) The block version\\n\"\n            \"  \\\"versionHex\\\" : \\\"00000000\\\", (string) The block version formatted in hexadecimal\\n\"\n            \"  \\\"merkleroot\\\" : \\\"xxxx\\\", (string) The merkle root\\n\"\n            \"  \\\"time\\\" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"mediantime\\\" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"nonce\\\" : n,           (numeric) The nonce\\n\"\n            \"  \\\"bits\\\" : \\\"1d00ffff\\\", (string) The bits\\n\"\n            \"  \\\"difficulty\\\" : x.xxx,  (numeric) The difficulty\\n\"\n            \"  \\\"chainwork\\\" : \\\"0000...1f3\\\"     (string) Expected number of hashes required to produce the current chain (in hex)\\n\"\n            \"  \\\"nTx\\\" : n,             (numeric) The number of transactions in the block.\\n\"\n            \"  \\\"previousblockhash\\\" : \\\"hash\\\",  (string) The hash of the previous block\\n\"\n            \"  \\\"nextblockhash\\\" : \\\"hash\\\",      (string) The hash of the next block\\n\"\n            \"}\\n\"\n            \"\\nResult (for verbose=false):\\n\"\n            \"\\\"data\\\"             (string) A string that is serialized, hex-encoded data for block 'hash'.\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getblockheader\", \"\\\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\\\"\")\n            + HelpExampleRpc(\"getblockheader\", \"\\\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\\\"\")\n        );\n\n    uint256 hash(ParseHashV(request.params[0], \"hash\"));\n\n    bool fVerbose = true;\n    if (!request.params[1].isNull())\n        fVerbose = request.params[1].get_bool();\n\n    const CBlockIndex* pblockindex;\n    const CBlockIndex* tip;\n    {\n        LOCK(cs_main);\n        pblockindex = LookupBlockIndex(hash);\n        tip = chainActive.Tip();\n    }\n\n    if (!pblockindex) {\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n    }\n\n    if (!fVerbose)\n    {\n        CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);\n        ssBlock << pblockindex->GetBlockHeader();\n        std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());\n        return strHex;\n    }\n\n    return blockheaderToJSON(tip, pblockindex);\n}\n\nstatic CBlock GetBlockChecked(const CBlockIndex* pblockindex)\n{\n    CBlock block;\n    if (IsBlockPruned(pblockindex)) {\n        throw JSONRPCError(RPC_MISC_ERROR, \"Block not available (pruned data)\");\n    }\n\n    if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) {\n//\u5728\u78c1\u76d8\u4e0a\u627e\u4e0d\u5230\u5757\u3002\u8fd9\u53ef\u80fd\u662f\u56e0\u4e3a\u6211\u4eec\u6709\u8857\u533a\n//\u5934\u5728\u7d22\u5f15\u4e2d\uff0c\u4f46\u6ca1\u6709\u5757\uff08\u4f8b\u5982\n//\u975e\u767d\u540d\u5355\u8282\u70b9\u5411\u6211\u4eec\u53d1\u9001\u4e00\u4e2a\u672a\u8bf7\u6c42\u7684\u957f\u6709\u6548\u94fe\n//\u5757\uff0c\u6211\u4eec\u5c06\u5934\u6dfb\u52a0\u5230\u7d22\u5f15\u4e2d\uff0c\u4f46\u4e0d\u63a5\u53d7\n//\u5757\uff09\u3002\n        throw JSONRPCError(RPC_MISC_ERROR, \"Block not found on disk\");\n    }\n\n    return block;\n}\n\nstatic UniValue getblock(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)\n        throw std::runtime_error(\n            RPCHelpMan{\"getblock\",\n                \"\\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\\n\"\n                \"If verbosity is 1, returns an Object with information about block <hash>.\\n\"\n                \"If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \\n\",\n                {\n                    /*lockhash\u201c\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/false\uff0c/*\u9ed8\u8ba4\u503c_val*/\u201d\u201c\uff0c\u201c\u5757\u54c8\u5e0c\u201d\uff0c\n                    \u201c\u5197\u957f\u201d\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/ true, /* default_val */ \"1\", \"0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\"},\n\n                }}\n                .ToString() +\n            \"\\nResult (for verbosity = 0):\\n\"\n            \"\\\"data\\\"             (string) A string that is serialized, hex-encoded data for block 'hash'.\\n\"\n            \"\\nResult (for verbosity = 1):\\n\"\n            \"{\\n\"\n            \"  \\\"hash\\\" : \\\"hash\\\",     (string) the block hash (same as provided)\\n\"\n            \"  \\\"confirmations\\\" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\\n\"\n            \"  \\\"size\\\" : n,            (numeric) The block size\\n\"\n            \"  \\\"strippedsize\\\" : n,    (numeric) The block size excluding witness data\\n\"\n            \"  \\\"weight\\\" : n           (numeric) The block weight as defined in BIP 141\\n\"\n            \"  \\\"height\\\" : n,          (numeric) The block height or index\\n\"\n            \"  \\\"version\\\" : n,         (numeric) The block version\\n\"\n            \"  \\\"versionHex\\\" : \\\"00000000\\\", (string) The block version formatted in hexadecimal\\n\"\n            \"  \\\"merkleroot\\\" : \\\"xxxx\\\", (string) The merkle root\\n\"\n            \"  \\\"tx\\\" : [               (array of string) The transaction ids\\n\"\n            \"     \\\"transactionid\\\"     (string) The transaction id\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"time\\\" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"mediantime\\\" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"nonce\\\" : n,           (numeric) The nonce\\n\"\n            \"  \\\"bits\\\" : \\\"1d00ffff\\\", (string) The bits\\n\"\n            \"  \\\"difficulty\\\" : x.xxx,  (numeric) The difficulty\\n\"\n            \"  \\\"chainwork\\\" : \\\"xxxx\\\",  (string) Expected number of hashes required to produce the chain up to this block (in hex)\\n\"\n            \"  \\\"nTx\\\" : n,             (numeric) The number of transactions in the block.\\n\"\n            \"  \\\"previousblockhash\\\" : \\\"hash\\\",  (string) The hash of the previous block\\n\"\n            \"  \\\"nextblockhash\\\" : \\\"hash\\\"       (string) The hash of the next block\\n\"\n            \"}\\n\"\n            \"\\nResult (for verbosity = 2):\\n\"\n            \"{\\n\"\n            \"  ...,                     Same output as verbosity = 1.\\n\"\n            \"  \\\"tx\\\" : [               (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \\\"tx\\\" result.\\n\"\n            \"         ,...\\n\"\n            \"  ],\\n\"\n            \"  ,...                     Same output as verbosity = 1.\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getblock\", \"\\\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\\\"\")\n            + HelpExampleRpc(\"getblock\", \"\\\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\\\"\")\n        );\n\n    LOCK(cs_main);\n\n    uint256 hash(ParseHashV(request.params[0], \"blockhash\"));\n\n    int verbosity = 1;\n    if (!request.params[1].isNull()) {\n        if(request.params[1].isNum())\n            verbosity = request.params[1].get_int();\n        else\n            verbosity = request.params[1].get_bool() ? 1 : 0;\n    }\n\n    const CBlockIndex* pblockindex = LookupBlockIndex(hash);\n    if (!pblockindex) {\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n    }\n\n    const CBlock block = GetBlockChecked(pblockindex);\n\n    if (verbosity <= 0)\n    {\n        CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());\n        ssBlock << block;\n        std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());\n        return strHex;\n    }\n\n    return blockToJSON(block, chainActive.Tip(), pblockindex, verbosity >= 2);\n}\n\nstruct CCoinsStats\n{\n    int nHeight;\n    uint256 hashBlock;\n    uint64_t nTransactions;\n    uint64_t nTransactionOutputs;\n    uint64_t nBogoSize;\n    uint256 hashSerialized;\n    uint64_t nDiskSize;\n    CAmount nTotalAmount;\n\n    CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nBogoSize(0), nDiskSize(0), nTotalAmount(0) {}\n};\n\nstatic void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)\n{\n    assert(!outputs.empty());\n    ss << hash;\n    ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase ? 1u : 0u);\n    stats.nTransactions++;\n    for (const auto& output : outputs) {\n        ss << VARINT(output.first + 1);\n        ss << output.second.out.scriptPubKey;\n        ss << VARINT(output.second.out.nValue, VarIntMode::NONNEGATIVE_SIGNED);\n        stats.nTransactionOutputs++;\n        stats.nTotalAmount += output.second.out.nValue;\n        /*ts.nbogosize+=32/*txid*/+4/*vout index*/+4/*height+coinbase*/+8/*amount*/+\n                           2/*scriptpubkey\u957f\u5ea6*/ + output.second.out.scriptPubKey.size() /* scriptPubKey */;\n\n    }\n    ss << VARINT(0u);\n}\n\n//\uff01\u8ba1\u7b97\u672a\u5360\u7528\u4e8b\u52a1\u8f93\u51fa\u96c6\u7684\u7edf\u8ba1\u4fe1\u606f\nstatic bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)\n{\n    std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());\n    assert(pcursor);\n\n    CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);\n    stats.hashBlock = pcursor->GetBestBlock();\n    {\n        LOCK(cs_main);\n        stats.nHeight = LookupBlockIndex(stats.hashBlock)->nHeight;\n    }\n    ss << stats.hashBlock;\n    uint256 prevkey;\n    std::map<uint32_t, Coin> outputs;\n    while (pcursor->Valid()) {\n        boost::this_thread::interruption_point();\n        COutPoint key;\n        Coin coin;\n        if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {\n            if (!outputs.empty() && key.hash != prevkey) {\n                ApplyStats(stats, ss, prevkey, outputs);\n                outputs.clear();\n            }\n            prevkey = key.hash;\n            outputs[key.n] = std::move(coin);\n        } else {\n            return error(\"%s: unable to read value\", __func__);\n        }\n        pcursor->Next();\n    }\n    if (!outputs.empty()) {\n        ApplyStats(stats, ss, prevkey, outputs);\n    }\n    stats.hashSerialized = ss.GetHash();\n    stats.nDiskSize = view->EstimateSize();\n    return true;\n}\n\nstatic UniValue pruneblockchain(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            RPCHelpMan{\"pruneblockchain\", \"\",\n                {\n                    /*\u516b\u201c\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/false\uff0c/*default_val*/\u201d\uff0c\u201c\u8981\u4fee\u526a\u5230\u7684\u5757\u9ad8\u5ea6\u3002\u53ef\u4ee5\u8bbe\u7f6e\u4e3a\u79bb\u6563\u9ad8\u5ea6\uff0c\u4e5f\u53ef\u4ee5\u8bbe\u7f6e\u4e3aUnix\u65f6\u95f4\u6233\\n\u201c\n            \u201c\u5220\u9664\u5757\u65f6\u95f4\u81f3\u5c11\u6bd4\u63d0\u4f9b\u7684\u65f6\u95f4\u6233\u65e92\u5c0f\u65f6\u7684\u5757\u3002\u201d\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201cN\uff08\u6570\u5b57\uff09\u6700\u540e\u4e00\u4e2a\u4fee\u526a\u5757\u7684\u9ad8\u5ea6\u3002\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpExamplecli\uff08\u201cpruneblockchain\u201d\uff0c\u201c1000\u201d\uff09\u3002\n            +helpexamplerpc\uff08\u201cpruneblockchain\u201d\uff0c\u201c1000\u201d\uff09\uff1b\n\n    \u5982\u679c\uff08\uff01\uff09FPRONMODED\n        throw jsonrpcerror\uff08rpc_misc_error\uff0c\u201c\u65e0\u6cd5\u4fee\u526a\u5757\uff0c\u56e0\u4e3a\u8282\u70b9\u672a\u5904\u4e8e\u4fee\u526a\u6a21\u5f0f\u3002\u201d\uff09\uff1b\n\n    \u9501\uff08CSKEMAN\uff09\uff1b\n\n    int heightparam=request.params[0].get_int\uff08\uff09\uff1b\n    \u5982\u679c\uff08\u9ad8\u5ea6\u53c2\u6570<0\uff09\n        throw jsonrpcerror\uff08rpc_\u65e0\u6548\u7684_\u53c2\u6570\uff0c\u201c\u8d1f\u5757\u9ad8\u5ea6\u201d\uff09\uff1b\n\n    //\u8d85\u8fc710\u4ebf\u7684\u9ad8\u5ea6\u503c\u592a\u9ad8\uff0c\u65e0\u6cd5\u4f5c\u4e3a\u5757\u9ad8\u5ea6\uff0c\u5e76\u4e14\n    //\u592a\u4f4e\uff0c\u65e0\u6cd5\u4f5c\u4e3a\u5757\u65f6\u95f4\uff08\u5bf9\u5e94\u4e8e2001\u5e749\u6708\u7684\u65f6\u95f4\u6233\uff09\u3002\n    \u5982\u679c\uff08\u9ad8\u5ea6\u53c2\u6570>100000000\uff09\n        //\u6dfb\u52a0\u4e00\u4e2a2\u5c0f\u65f6\u7684\u7f13\u51b2\u533a\u4ee5\u5305\u542b\u53ef\u80fd\u5177\u6709\u65e7\u65f6\u95f4\u6233\u7684\u5757\n        cblockindex*pindex=chainactive.findearliestatleast\uff08heightparam-timestamp_window\uff09\uff1b\n        \u5982\u679c\uff08\uff01\uff09pQueD\uff09{\n            throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201c\u627e\u4e0d\u5230\u81f3\u5c11\u5177\u6709\u6307\u5b9a\u65f6\u95f4\u6233\u7684\u5757\u3002\u201d\uff09\uff1b\n        }\n        heightparam=pindex->nheight\uff1b\n    }\n\n    \u65e0\u7b26\u53f7\u6574\u578b\u9ad8\u5ea6=\uff08\u65e0\u7b26\u53f7\u6574\u578b\uff09\u9ad8\u5ea6\u53c2\u6570\uff1b\n    unsigned int chainheight=\uff08unsigned int\uff09chainactive.height\uff08\uff09\uff1b\n    if\uff08chainheight<params\uff08\uff09.pruneafterheight\uff08\uff09\uff09\n        throw jsonrpcerror\uff08rpc_misc_error\uff0c\u201c\u533a\u5757\u94fe\u592a\u77ed\uff0c\u65e0\u6cd5\u4fee\u526a\u201d\uff09\uff1b\n    \u5426\u5219\uff0c\u5982\u679c\uff08\u9ad8\u5ea6>\u94fe\u9ad8\u5ea6\uff09\n        throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201c\u533a\u5757\u94fe\u77ed\u4e8e\u5c1d\u8bd5\u7684\u4fee\u526a\u9ad8\u5ea6\u201d\uff09\uff1b\n    \u5426\u5219\uff0c\u5982\u679c\uff08\u9ad8\u5ea6>\u94fe\u9ad8-\u6700\u5c0f_\u5757_\u5230\u4fdd\u6301\uff09\n        logprint\uff08bclog:\uff1arpc\uff0c\u201c\u5c1d\u8bd5\u4fee\u526a\u9760\u8fd1\u5c16\u7aef\u7684\u5757\u3002\u4fdd\u7559\u6700\u5c0f\u5757\u6570\u3002\\n\u201d\uff09\u3002\n        \u9ad8\u5ea6=\u94fe\u9ad8-\u6700\u5c0f\\\u5757\\\u4fdd\u6301\uff1b\n    }\n\n    pruneblockfiles\u624b\u52a8\uff08\u9ad8\u5ea6\uff09\uff1b\n    \u8fd4\u56deuint64_t\uff08\u9ad8\u5ea6\uff09\uff1b\n}\n\n\u9759\u6001\u5355\u503cgettxoutsetinfo\uff08const jsonrpcrequest&request\uff09\n{\n    \u5982\u679c\uff08request.fhelp request.params.size\uff08\uff09\uff01= 0\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201cgettxoutsetinfo\u201d\uff0c\n                \\n\u8fd4\u56de\u6709\u5173\u672a\u6682\u505c\u4e8b\u52a1\u8f93\u51fa\u96c6\u7684\u7edf\u8ba1\u4fe1\u606f\u3002\\n\n                \u201c\u6ce8\u610f\uff0c\u6b64\u547c\u53eb\u53ef\u80fd\u9700\u8981\u4e00\u4e9b\u65f6\u95f4\u3002\\n\u201d\uff0c\n                {}\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c{n\u201d\n            \u201c\u201c\u9ad8\u5ea6\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u5f53\u524d\u5757\u9ad8\u5ea6\uff08\u7d22\u5f15\uff09\\n\u201d\n            \u201c\u201cbestblock\\\u201d\uff1a\u201chex\\\u201d\uff0c\uff08string\uff09\u94fe\u9876\u7aef\u7684\u5757\u54c8\u5e0c\\n\u201d\n            \u201c\u201c\u4e8b\u52a1\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u5177\u6709\u672a\u6682\u505c\u8f93\u51fa\u7684\u4e8b\u52a1\u6570\\n\u201d\n            \u201c\u201ctxouts\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u672a\u6682\u505c\u7684\u4e8b\u52a1\u8f93\u51fa\u6570\\n\u201d\n            \u201c\u201cbogosize\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09utxo\u96c6\u5927\u5c0f\u7684\u65e0\u610f\u4e49\u5ea6\u91cf\u503c\\n\u201d\n            \u201c\u54c8\u5e0c\\\u5df2\u5e8f\u5217\u5316\\u 2\\\u201d\uff1a\\\u201c\u54c8\u5e0c\\\u201d\uff0c\uff08string\uff09\u5df2\u5e8f\u5217\u5316\u7684\u54c8\u5e0c\\n\u201d\n            \u201c\u78c1\u76d8\u5927\u5c0f\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u78c1\u76d8\u4e0a\u94fe\u72b6\u6001\u7684\u4f30\u8ba1\u5927\u5c0f\\n\u201d\n            \u201c\u603b\u91d1\u989d\u201d\uff1ax.x x x\uff08\u6570\u5b57\uff09\u603b\u91d1\u989d\\n\u201d\n            \u201c}\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpexamplecli\uff08\u201cgettxoutsetinfo\u201d\uff0c\u201c\u201d\uff09\n            +helpExampleRPC\uff08\u201cgettXoutSetInfo\u201d\uff0c\u201c\u201d\uff09\n        \uff1b\n\n    \u5355\u503cret\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n\n    CCoinstats\u7edf\u8ba1\uff1b\n    flushstatetodisk\uff08\uff09\uff1b\n    if\uff08getutxostats\uff08pcoinsdbview.get\uff08\uff09\uff0cstats\uff09\uff09\n        ret.pushkv\uff08\u201c\u9ad8\u5ea6\u201d\uff0c\uff08int64_t\uff09stats.nheight\uff09\uff1b\n        ret.pushkv\uff08\u201cbestblock\u201d\uff0cstats.hashblock.gethex\uff08\uff09\uff09\uff1b\n        ret.pushkv\uff08\u201c\u4e8b\u52a1\u201d\uff0c\uff08int64_t\uff09stats.ntransactions\uff09\uff1b\n        ret.pushkv\uff08\u201ctxouts\u201d\uff0c\uff08int64_t\uff09stats.ntransactionoutputs\uff09\uff1b\n        ret.pushkv\uff08\u201cbogosize\u201d\uff0c\uff08int64_t\uff09stats.nbogosize\uff09\uff1b\n        ret.pushkv\uff08\u201chash_serialized_2\u201d\uff0cstats.hash serialized.gethex\uff08\uff09\uff09\uff1b\n        ret.pushkv\uff08\u201c\u78c1\u76d8\u5927\u5c0f\u201d\uff0cstats.ndisksize\uff09\uff1b\n        ret.pushkv\uff08\u201c\u603b\u91d1\u989d\u201d\uff0cvaluefromamount\uff08stats.ntotalamount\uff09\uff09\uff1b\n    }\u5426\u5219{\n        throw jsonrpcerror\uff08rpc_internal_error\uff0c\u201cUnable to read utxo set\u201d\uff09\uff1b\n    }\n    \u8fd4\u56deRET\uff1b\n}\n\n\u5355\u503cgettxout\uff08const-jsonrpcrequest&request\uff09\n{\n    if\uff08request.fhelp request.params.size\uff08\uff09<2 request.params.size\uff08\uff09>3\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201cgettxout\u201d\uff0c\n                \u201c\\n\u8fd4\u56de\u6709\u5173\u672a\u6682\u505c\u4e8b\u52a1\u8f93\u51fa\u7684\u8be6\u7ec6\u4fe1\u606f\u3002\\n\u201d\uff0c\n                {\n                    \u201ctxid\u201d\uff0crpcarg:\uff1atype:\uff1astr\uff0c/*opt*/ false, /* default_val */ \"\", \"The transaction id\"},\n\n                    /*\u201c\uff0crpcarg\uff1a\uff1atype\uff1a\uff1anum\uff0c/*opt*/false\uff0c/*\u9ed8\u8ba4\u503c/\u201d\u201c\uff0cvout\u7f16\u53f7\u201d\uff0c\n                    \u201cinclude_mempool\u201d\uff0crpcarg:\uff1atype:\uff1abool\uff0c/*opt*/ true, /* default_val */ \"true\", \"Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear.\"},\n\n                }}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"bestblock\\\":  \\\"hash\\\",    (string) The hash of the block at the tip of the chain\\n\"\n            \"  \\\"confirmations\\\" : n,       (numeric) The number of confirmations\\n\"\n            \"  \\\"value\\\" : x.xxx,           (numeric) The transaction value in \" + CURRENCY_UNIT + \"\\n\"\n            \"  \\\"scriptPubKey\\\" : {         (json object)\\n\"\n            \"     \\\"asm\\\" : \\\"code\\\",       (string) \\n\"\n            \"     \\\"hex\\\" : \\\"hex\\\",        (string) \\n\"\n            \"     \\\"reqSigs\\\" : n,          (numeric) Number of required signatures\\n\"\n            \"     \\\"type\\\" : \\\"pubkeyhash\\\", (string) The type, eg pubkeyhash\\n\"\n            \"     \\\"addresses\\\" : [          (array of string) array of bitcoin addresses\\n\"\n            \"        \\\"address\\\"     (string) bitcoin address\\n\"\n            \"        ,...\\n\"\n            \"     ]\\n\"\n            \"  },\\n\"\n            \"  \\\"coinbase\\\" : true|false   (boolean) Coinbase or not\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            \"\\nGet unspent transactions\\n\"\n            + HelpExampleCli(\"listunspent\", \"\") +\n            \"\\nView the details\\n\"\n            + HelpExampleCli(\"gettxout\", \"\\\"txid\\\" 1\") +\n            \"\\nAs a JSON-RPC call\\n\"\n            + HelpExampleRpc(\"gettxout\", \"\\\"txid\\\", 1\")\n        );\n\n    LOCK(cs_main);\n\n    UniValue ret(UniValue::VOBJ);\n\n    uint256 hash(ParseHashV(request.params[0], \"txid\"));\n    int n = request.params[1].get_int();\n    COutPoint out(hash, n);\n    bool fMempool = true;\n    if (!request.params[2].isNull())\n        fMempool = request.params[2].get_bool();\n\n    Coin coin;\n    if (fMempool) {\n        LOCK(mempool.cs);\n        CCoinsViewMemPool view(pcoinsTip.get(), mempool);\n        if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {\n            return NullUniValue;\n        }\n    } else {\n        if (!pcoinsTip->GetCoin(out, coin)) {\n            return NullUniValue;\n        }\n    }\n\n    const CBlockIndex* pindex = LookupBlockIndex(pcoinsTip->GetBestBlock());\n    ret.pushKV(\"bestblock\", pindex->GetBlockHash().GetHex());\n    if (coin.nHeight == MEMPOOL_HEIGHT) {\n        ret.pushKV(\"confirmations\", 0);\n    } else {\n        ret.pushKV(\"confirmations\", (int64_t)(pindex->nHeight - coin.nHeight + 1));\n    }\n    ret.pushKV(\"value\", ValueFromAmount(coin.out.nValue));\n    UniValue o(UniValue::VOBJ);\n    ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);\n    ret.pushKV(\"scriptPubKey\", o);\n    ret.pushKV(\"coinbase\", (bool)coin.fCoinBase);\n\n    return ret;\n}\n\nstatic UniValue verifychain(const JSONRPCRequest& request)\n{\n    int nCheckLevel = gArgs.GetArg(\"-checklevel\", DEFAULT_CHECKLEVEL);\n    int nCheckDepth = gArgs.GetArg(\"-checkblocks\", DEFAULT_CHECKBLOCKS);\n    if (request.fHelp || request.params.size() > 2)\n        throw std::runtime_error(\n            RPCHelpMan{\"verifychain\",\n                \"\\nVerifies blockchain database.\\n\",\n                {\n                    /*hecklevel\u201c\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/true\uff0c/*default_val*/strprintf\uff08\u201d%d\uff0crange=0-4\u201c\uff0cnchecklevel\uff09\uff0c\u201c\u5757\u9a8c\u8bc1\u7684\u5f7b\u5e95\u6027\u3002\u201d\uff0c\n                    \u201cnblocks\u201d\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/ true, /* default_val */ strprintf(\"%d, 0=all\", nCheckDepth), \"The number of blocks to check.\"},\n\n                }}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"true|false       (boolean) Verified or not\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"verifychain\", \"\")\n            + HelpExampleRpc(\"verifychain\", \"\")\n        );\n\n    LOCK(cs_main);\n\n    if (!request.params[0].isNull())\n        nCheckLevel = request.params[0].get_int();\n    if (!request.params[1].isNull())\n        nCheckDepth = request.params[1].get_int();\n\n    return CVerifyDB().VerifyDB(Params(), pcoinsTip.get(), nCheckLevel, nCheckDepth);\n}\n\n/*\u5177\u6709\u66f4\u597d\u53cd\u9988\u7684\u95ee\u9898\u4f18\u5148\u7ea7\u7684\u5b9e\u73b0*/\nstatic UniValue SoftForkMajorityDesc(int version, const CBlockIndex* pindex, const Consensus::Params& consensusParams)\n{\n    UniValue rv(UniValue::VOBJ);\n    bool activated = false;\n    switch(version)\n    {\n        case 2:\n            activated = pindex->nHeight >= consensusParams.BIP34Height;\n            break;\n        case 3:\n            activated = pindex->nHeight >= consensusParams.BIP66Height;\n            break;\n        case 4:\n            activated = pindex->nHeight >= consensusParams.BIP65Height;\n            break;\n    }\n    rv.pushKV(\"status\", activated);\n    return rv;\n}\n\nstatic UniValue SoftForkDesc(const std::string &name, int version, const CBlockIndex* pindex, const Consensus::Params& consensusParams)\n{\n    UniValue rv(UniValue::VOBJ);\n    rv.pushKV(\"id\", name);\n    rv.pushKV(\"version\", version);\n    rv.pushKV(\"reject\", SoftForkMajorityDesc(version, pindex, consensusParams));\n    return rv;\n}\n\nstatic UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)\n{\n    UniValue rv(UniValue::VOBJ);\n    const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);\n    switch (thresholdState) {\n    case ThresholdState::DEFINED: rv.pushKV(\"status\", \"defined\"); break;\n    case ThresholdState::STARTED: rv.pushKV(\"status\", \"started\"); break;\n    case ThresholdState::LOCKED_IN: rv.pushKV(\"status\", \"locked_in\"); break;\n    case ThresholdState::ACTIVE: rv.pushKV(\"status\", \"active\"); break;\n    case ThresholdState::FAILED: rv.pushKV(\"status\", \"failed\"); break;\n    }\n    if (ThresholdState::STARTED == thresholdState)\n    {\n        rv.pushKV(\"bit\", consensusParams.vDeployments[id].bit);\n    }\n    rv.pushKV(\"startTime\", consensusParams.vDeployments[id].nStartTime);\n    rv.pushKV(\"timeout\", consensusParams.vDeployments[id].nTimeout);\n    rv.pushKV(\"since\", VersionBitsTipStateSinceHeight(consensusParams, id));\n    if (ThresholdState::STARTED == thresholdState)\n    {\n        UniValue statsUV(UniValue::VOBJ);\n        BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id);\n        statsUV.pushKV(\"period\", statsStruct.period);\n        statsUV.pushKV(\"threshold\", statsStruct.threshold);\n        statsUV.pushKV(\"elapsed\", statsStruct.elapsed);\n        statsUV.pushKV(\"count\", statsStruct.count);\n        statsUV.pushKV(\"possible\", statsStruct.possible);\n        rv.pushKV(\"statistics\", statsUV);\n    }\n    return rv;\n}\n\nstatic void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)\n{\n//\u8d85\u65f6\u503c\u4e3a0\u7684\u90e8\u7f72\u88ab\u9690\u85cf\u3002\n//\u8d85\u65f6\u503c\u4e3a0\u53ef\u786e\u4fdd\u6c38\u8fdc\u4e0d\u4f1a\u6fc0\u6d3bSoftFork\u3002\n//\u8fd9\u5728\u5408\u5e76SoftFork\u4ee3\u7801\u800c\u4e0d\u6307\u5b9a\u90e8\u7f72\u8ba1\u5212\u65f6\u4f7f\u7528\u3002\n    if (consensusParams.vDeployments[id].nTimeout > 0)\n        bip9_softforks.pushKV(VersionBitsDeploymentInfo[id].name, BIP9SoftForkDesc(consensusParams, id));\n}\n\nUniValue getblockchaininfo(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            RPCHelpMan{\"getblockchaininfo\",\n                \"Returns an object containing various state info regarding blockchain processing.\\n\", {}}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"chain\\\": \\\"xxxx\\\",              (string) current network name as defined in BIP70 (main, test, regtest)\\n\"\n            \"  \\\"blocks\\\": xxxxxx,             (numeric) the current number of blocks processed in the server\\n\"\n            \"  \\\"headers\\\": xxxxxx,            (numeric) the current number of headers we have validated\\n\"\n            \"  \\\"bestblockhash\\\": \\\"...\\\",       (string) the hash of the currently best block\\n\"\n            \"  \\\"difficulty\\\": xxxxxx,         (numeric) the current difficulty\\n\"\n            \"  \\\"mediantime\\\": xxxxxx,         (numeric) median time for the current best block\\n\"\n            \"  \\\"verificationprogress\\\": xxxx, (numeric) estimate of verification progress [0..1]\\n\"\n            \"  \\\"initialblockdownload\\\": xxxx, (bool) (debug information) estimate of whether this node is in Initial Block Download mode.\\n\"\n            \"  \\\"chainwork\\\": \\\"xxxx\\\"           (string) total amount of work in active chain, in hexadecimal\\n\"\n            \"  \\\"size_on_disk\\\": xxxxxx,       (numeric) the estimated size of the block and undo files on disk\\n\"\n            \"  \\\"pruned\\\": xx,                 (boolean) if the blocks are subject to pruning\\n\"\n            \"  \\\"pruneheight\\\": xxxxxx,        (numeric) lowest-height complete block stored (only present if pruning is enabled)\\n\"\n            \"  \\\"automatic_pruning\\\": xx,      (boolean) whether automatic pruning is enabled (only present if pruning is enabled)\\n\"\n            \"  \\\"prune_target_size\\\": xxxxxx,  (numeric) the target size used by pruning (only present if automatic pruning is enabled)\\n\"\n            \"  \\\"softforks\\\": [                (array) status of softforks in progress\\n\"\n            \"     {\\n\"\n            \"        \\\"id\\\": \\\"xxxx\\\",           (string) name of softfork\\n\"\n            \"        \\\"version\\\": xx,          (numeric) block version\\n\"\n            \"        \\\"reject\\\": {             (object) progress toward rejecting pre-softfork blocks\\n\"\n            \"           \\\"status\\\": xx,        (boolean) true if threshold reached\\n\"\n            \"        },\\n\"\n            \"     }, ...\\n\"\n            \"  ],\\n\"\n            \"  \\\"bip9_softforks\\\": {           (object) status of BIP9 softforks in progress\\n\"\n            \"     \\\"xxxx\\\" : {                 (string) name of the softfork\\n\"\n            \"        \\\"status\\\": \\\"xxxx\\\",       (string) one of \\\"defined\\\", \\\"started\\\", \\\"locked_in\\\", \\\"active\\\", \\\"failed\\\"\\n\"\n            \"        \\\"bit\\\": xx,              (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \\\"started\\\" status)\\n\"\n            \"        \\\"startTime\\\": xx,        (numeric) the minimum median time past of a block at which the bit gains its meaning\\n\"\n            \"        \\\"timeout\\\": xx,          (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\\n\"\n            \"        \\\"since\\\": xx,            (numeric) height of the first block to which the status applies\\n\"\n            \"        \\\"statistics\\\": {         (object) numeric statistics about BIP9 signalling for a softfork (only for \\\"started\\\" status)\\n\"\n            \"           \\\"period\\\": xx,        (numeric) the length in blocks of the BIP9 signalling period \\n\"\n            \"           \\\"threshold\\\": xx,     (numeric) the number of blocks with the version bit set required to activate the feature \\n\"\n            \"           \\\"elapsed\\\": xx,       (numeric) the number of blocks elapsed since the beginning of the current period \\n\"\n            \"           \\\"count\\\": xx,         (numeric) the number of blocks with the version bit set in the current period \\n\"\n            \"           \\\"possible\\\": xx       (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \\n\"\n            \"        }\\n\"\n            \"     }\\n\"\n            \"  }\\n\"\n            \"  \\\"warnings\\\" : \\\"...\\\",           (string) any network and blockchain warnings.\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getblockchaininfo\", \"\")\n            + HelpExampleRpc(\"getblockchaininfo\", \"\")\n        );\n\n    LOCK(cs_main);\n\n    const CBlockIndex* tip = chainActive.Tip();\n    UniValue obj(UniValue::VOBJ);\n    obj.pushKV(\"chain\",                 Params().NetworkIDString());\n    obj.pushKV(\"blocks\",                (int)chainActive.Height());\n    obj.pushKV(\"headers\",               pindexBestHeader ? pindexBestHeader->nHeight : -1);\n    obj.pushKV(\"bestblockhash\",         tip->GetBlockHash().GetHex());\n    obj.pushKV(\"difficulty\",            (double)GetDifficulty(tip));\n    obj.pushKV(\"mediantime\",            (int64_t)tip->GetMedianTimePast());\n    obj.pushKV(\"verificationprogress\",  GuessVerificationProgress(Params().TxData(), tip));\n    obj.pushKV(\"initialblockdownload\",  IsInitialBlockDownload());\n    obj.pushKV(\"chainwork\",             tip->nChainWork.GetHex());\n    obj.pushKV(\"size_on_disk\",          CalculateCurrentUsage());\n    obj.pushKV(\"pruned\",                fPruneMode);\n    if (fPruneMode) {\n        const CBlockIndex* block = tip;\n        assert(block);\n        while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {\n            block = block->pprev;\n        }\n\n        obj.pushKV(\"pruneheight\",        block->nHeight);\n\n//\u5982\u679c\u4e3a0\uff0c\u5219\u6267\u884c\u5c06\u7ed5\u8fc7\u6574\u4e2aif\u5757\u3002\n        bool automatic_pruning = (gArgs.GetArg(\"-prune\", 0) != 1);\n        obj.pushKV(\"automatic_pruning\",  automatic_pruning);\n        if (automatic_pruning) {\n            obj.pushKV(\"prune_target_size\",  nPruneTarget);\n        }\n    }\n\n    const Consensus::Params& consensusParams = Params().GetConsensus();\n    UniValue softforks(UniValue::VARR);\n    UniValue bip9_softforks(UniValue::VOBJ);\n    softforks.push_back(SoftForkDesc(\"bip34\", 2, tip, consensusParams));\n    softforks.push_back(SoftForkDesc(\"bip66\", 3, tip, consensusParams));\n    softforks.push_back(SoftForkDesc(\"bip65\", 4, tip, consensusParams));\n    for (int pos = Consensus::DEPLOYMENT_CSV; pos != Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++pos) {\n        BIP9SoftForkDescPushBack(bip9_softforks, consensusParams, static_cast<Consensus::DeploymentPos>(pos));\n    }\n    obj.pushKV(\"softforks\",             softforks);\n    obj.pushKV(\"bip9_softforks\", bip9_softforks);\n\n    obj.pushKV(\"warnings\", GetWarnings(\"statusbar\"));\n    return obj;\n}\n\n/*\u7528\u4e8e\u5bf9getchaintips\u5934\u6392\u5e8f\u7684\u6bd4\u8f83\u51fd\u6570\u3002*/\nstruct CompareBlocksByHeight\n{\n    bool operator()(const CBlockIndex* a, const CBlockIndex* b) const\n    {\n        /*\u786e\u4fdd\u9ad8\u5ea6\u76f8\u540c\u7684\u4e0d\u76f8\u7b49\u5757\u4e0d\u4f1a\u6bd4\u8f83\n           \u76f8\u7b49\u3002\u4f7f\u7528\u6307\u9488\u672c\u8eab\u8fdb\u884c\u533a\u5206\u3002*/\n\n\n        if (a->nHeight != b->nHeight)\n          return (a->nHeight > b->nHeight);\n\n        return a < b;\n    }\n};\n\nstatic UniValue getchaintips(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            RPCHelpMan{\"getchaintips\",\n                \"Return information about all known tips in the block tree,\"\n                \" including the main chain as well as orphaned branches.\\n\",\n                {}}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"[\\n\"\n            \"  {\\n\"\n            \"    \\\"height\\\": xxxx,         (numeric) height of the chain tip\\n\"\n            \"    \\\"hash\\\": \\\"xxxx\\\",         (string) block hash of the tip\\n\"\n            \"    \\\"branchlen\\\": 0          (numeric) zero for main chain\\n\"\n            \"    \\\"status\\\": \\\"active\\\"      (string) \\\"active\\\" for the main chain\\n\"\n            \"  },\\n\"\n            \"  {\\n\"\n            \"    \\\"height\\\": xxxx,\\n\"\n            \"    \\\"hash\\\": \\\"xxxx\\\",\\n\"\n            \"    \\\"branchlen\\\": 1          (numeric) length of branch connecting the tip to the main chain\\n\"\n            \"    \\\"status\\\": \\\"xxxx\\\"        (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\\n\"\n            \"  }\\n\"\n            \"]\\n\"\n            \"Possible values for status:\\n\"\n            \"1.  \\\"invalid\\\"               This branch contains at least one invalid block\\n\"\n            \"2.  \\\"headers-only\\\"          Not all blocks for this branch are available, but the headers are valid\\n\"\n            \"3.  \\\"valid-headers\\\"         All blocks are available for this branch, but they were never fully validated\\n\"\n            \"4.  \\\"valid-fork\\\"            This branch is not part of the active chain, but is fully validated\\n\"\n            \"5.  \\\"active\\\"                This is the tip of the active main chain, which is certainly valid\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getchaintips\", \"\")\n            + HelpExampleRpc(\"getchaintips\", \"\")\n        );\n\n    LOCK(cs_main);\n\n    /*\n     *\u60f3\u6cd5\uff1a\u94fe\u63d0\u793a\u7684\u96c6\u5408\u662fchainactive.tip\uff0c\u52a0\u4e0a\u5b64\u7acb\u5757\uff0c\u5b83\u4eec\u6ca1\u6709\u5176\u4ed6\u5b64\u7acb\u7684\u6784\u5efa\u3002\n     \uff0a\u7b97\u6cd5\uff1a\n     *-\u901a\u8fc7\u4e00\u6b21mapblockindex\uff0c\u9009\u62e9\u5b64\u7acb\u5757\uff0c\u5e76\u5b58\u50a8\u4e00\u7ec4\u5b64\u7acb\u5757\u7684pprev\u6307\u9488\u3002\n     *-\u904d\u5386\u5b64\u7acb\u5757\u3002\u5982\u679c\u5757\u6ca1\u6709\u88ab\u53e6\u4e00\u4e2a\u5b64\u7acb\u5bf9\u8c61\u6307\u5411\uff0c\u5219\u5b83\u662f\u4e00\u4e2a\u94fe\u5c16\u3002\n     *-\u6dfb\u52a0chainactive.tip\uff08\uff09\u3002\n     **/\n\n    std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;\n    std::set<const CBlockIndex*> setOrphans;\n    std::set<const CBlockIndex*> setPrevs;\n\n    for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)\n    {\n        if (!chainActive.Contains(item.second)) {\n            setOrphans.insert(item.second);\n            setPrevs.insert(item.second->pprev);\n        }\n    }\n\n    for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)\n    {\n        if (setPrevs.erase(*it) == 0) {\n            setTips.insert(*it);\n        }\n    }\n\n//\u59cb\u7ec8\u62a5\u544a\u5f53\u524d\u6d3b\u52a8\u7684\u63d0\u793a\u3002\n    setTips.insert(chainActive.Tip());\n\n    /*\u6784\u9020\u8f93\u51fa\u6570\u7ec4\u3002*/\n    UniValue res(UniValue::VARR);\n    for (const CBlockIndex* block : setTips)\n    {\n        UniValue obj(UniValue::VOBJ);\n        obj.pushKV(\"height\", block->nHeight);\n        obj.pushKV(\"hash\", block->phashBlock->GetHex());\n\n        const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;\n        obj.pushKV(\"branchlen\", branchLen);\n\n        std::string status;\n        if (chainActive.Contains(block)) {\n//\u6b64\u5757\u662f\u5f53\u524d\u6d3b\u52a8\u94fe\u7684\u4e00\u90e8\u5206\u3002\n            status = \"active\";\n        } else if (block->nStatus & BLOCK_FAILED_MASK) {\n//\u6b64\u5757\u6216\u5176\u7956\u5148\u4e4b\u4e00\u65e0\u6548\u3002\n            status = \"invalid\";\n        } else if (!block->HaveTxsDownloaded()) {\n//\u65e0\u6cd5\u8fde\u63a5\u6b64\u5757\uff0c\u56e0\u4e3a\u7f3a\u5c11\u5b83\u6216\u5b83\u7684\u67d0\u4e2a\u7236\u7ea7\u7684\u5b8c\u6574\u5757\u6570\u636e\u3002\n            status = \"headers-only\";\n        } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {\n//\u6b64\u5757\u5df2\u5b8c\u5168\u9a8c\u8bc1\uff0c\u4f46\u4e0d\u518d\u662f\u6d3b\u52a8\u94fe\u7684\u4e00\u90e8\u5206\u3002\u5b83\u53ef\u80fd\u66fe\u7ecf\u662f\u6d3b\u52a8\u5757\uff0c\u4f46\u88ab\u91cd\u65b0\u7ec4\u7ec7\u4e86\u3002\n            status = \"valid-fork\";\n        } else if (block->IsValid(BLOCK_VALID_TREE)) {\n//\u6b64\u5757\u7684\u5934\u6709\u6548\uff0c\u4f46\u5c1a\u672a\u9a8c\u8bc1\u3002\u5b83\u53ef\u80fd\u4ece\u6765\u4e0d\u662f\u5927\u591a\u6570\u5de5\u4f5c\u94fe\u7684\u4e00\u90e8\u5206\u3002\n            status = \"valid-headers\";\n        } else {\n//\u6ca1\u6709\u7ebf\u7d22\u3002\n            status = \"unknown\";\n        }\n        obj.pushKV(\"status\", status);\n\n        res.push_back(obj);\n    }\n\n    return res;\n}\n\nUniValue mempoolInfoToJSON()\n{\n    UniValue ret(UniValue::VOBJ);\n    ret.pushKV(\"size\", (int64_t) mempool.size());\n    ret.pushKV(\"bytes\", (int64_t) mempool.GetTotalTxSize());\n    ret.pushKV(\"usage\", (int64_t) mempool.DynamicMemoryUsage());\n    size_t maxmempool = gArgs.GetArg(\"-maxmempool\", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;\n    ret.pushKV(\"maxmempool\", (int64_t) maxmempool);\n    ret.pushKV(\"mempoolminfee\", ValueFromAmount(std::max(mempool.GetMinFee(maxmempool), ::minRelayTxFee).GetFeePerK()));\n    ret.pushKV(\"minrelaytxfee\", ValueFromAmount(::minRelayTxFee.GetFeePerK()));\n\n    return ret;\n}\n\nstatic UniValue getmempoolinfo(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 0)\n        throw std::runtime_error(\n            RPCHelpMan{\"getmempoolinfo\",\n                \"\\nReturns details on the active state of the TX memory pool.\\n\", {}}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"size\\\": xxxxx,               (numeric) Current tx count\\n\"\n            \"  \\\"bytes\\\": xxxxx,              (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\\n\"\n            \"  \\\"usage\\\": xxxxx,              (numeric) Total memory usage for the mempool\\n\"\n            \"  \\\"maxmempool\\\": xxxxx,         (numeric) Maximum memory usage for the mempool\\n\"\n            \"  \\\"mempoolminfee\\\": xxxxx       (numeric) Minimum fee rate in \" + CURRENCY_UNIT + \"/kB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee\\n\"\n            \"  \\\"minrelaytxfee\\\": xxxxx       (numeric) Current minimum relay fee for transactions\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getmempoolinfo\", \"\")\n            + HelpExampleRpc(\"getmempoolinfo\", \"\")\n        );\n\n    return mempoolInfoToJSON();\n}\n\nstatic UniValue preciousblock(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            RPCHelpMan{\"preciousblock\",\n                \"\\nTreats a block as if it were received before others with the same work.\\n\"\n                \"\\nA later preciousblock call can override the effect of an earlier one.\\n\"\n                \"\\nThe effects of preciousblock are not retained across restarts.\\n\",\n                {\n                    /*lockhash\u201c\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/false\uff0c/*default_val*/\u201d\u201c\uff0c\u201c\u8981\u6807\u8bb0\u4e3a\u8d35\u91cd\u201d\u7684\u5757\u7684\u54c8\u5e0c\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpExamplecli\uff08\u201cpreciousBlock\u201d\uff0c\u201cblockhash\\\u201d\uff09\n            +helpexamplerpc\uff08\u201cpreciousBlock\u201d\uff0c\u201cblockhash\\\u201d\uff09\n        \uff1b\n\n    uint256\u6563\u5217\uff08parsehashv\uff08request.params[0]\uff0c\u201cblockhash\u201d\uff09\uff09\uff1b\n    cblockindex*pblockindex\uff1b\n\n    {\n        \u9501\uff08CSKEMAN\uff09\uff1b\n        pblockindex=lookupblockindex\uff08\u54c8\u5e0c\uff09\uff1b\n        \u5982\u679c\uff08\uff01\uff09P-\u963b\u65ad\u86cb\u767d\uff09\n            throw jsonrpcerror\uff08rpc_invalid_address_or_key\uff0c\u201c\u627e\u4e0d\u5230\u5757\u201d\uff09\uff1b\n        }\n    }\n\n    cvalidationState\u72b6\u6001\uff1b\n    preciousBlock\uff08\u72b6\u6001\uff0cparams\uff08\uff09\uff0cpblockIndex\uff09\uff1b\n\n    \u5982\u679c\uff08\uff01\uff09state.isvalid\uff08\uff09\uff09\n        throw jsonrpcerror\uff08rpc_database_error\uff0cformatStateMessage\uff08state\uff09\uff09\uff1b\n    }\n\n    \u8fd4\u56denullunivalue\uff1b\n}\n\n\u9759\u6001\u5355\u503c\u65e0\u6548\u5757\uff08const-jsonrpcrequest&request\uff09\n{\n    \u5982\u679c\uff08request.fhelp request.params.size\uff08\uff09\uff01= 1\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201c\u65e0\u6548\u5757\u201d\uff0c\n                \\n\u6c38\u4e45\u6027\u5730\u5c06\u5757\u6807\u8bb0\u4e3a\u65e0\u6548\uff0c\u5c31\u50cf\u5b83\u8fdd\u53cd\u4e86\u5171\u8bc6\u89c4\u5219\u4e00\u6837\u3002\\n\u201c\uff0c\n                {\n                    \u201cblockhash\u201d\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/ false, /* default_val */ \"\", \"the hash of the block to mark as invalid\"},\n\n                }}\n                .ToString() +\n            \"\\nResult:\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"invalidateblock\", \"\\\"blockhash\\\"\")\n            + HelpExampleRpc(\"invalidateblock\", \"\\\"blockhash\\\"\")\n        );\n\n    uint256 hash(ParseHashV(request.params[0], \"blockhash\"));\n    CValidationState state;\n\n    {\n        LOCK(cs_main);\n        CBlockIndex* pblockindex = LookupBlockIndex(hash);\n        if (!pblockindex) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n        }\n\n        InvalidateBlock(state, Params(), pblockindex);\n    }\n\n    if (state.IsValid()) {\n        ActivateBestChain(state, Params());\n    }\n\n    if (!state.IsValid()) {\n        throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state));\n    }\n\n    return NullUniValue;\n}\n\nstatic UniValue reconsiderblock(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw std::runtime_error(\n            RPCHelpMan{\"reconsiderblock\",\n                \"\\nRemoves invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\\n\"\n                \"This can be used to undo the effects of invalidateblock.\\n\",\n                {\n                    /*lockhash\u201c\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/false\uff0c/*default_val*/\u201d\uff0c\u201c\u8981\u91cd\u65b0\u8003\u8651\u7684\u5757\u7684\u54c8\u5e0c\u201d\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpexamplecli\uff08\u201c\u91cd\u65b0\u8003\u8651\u5757\u201d\uff0c\u201c\\\u201dblockhash\\\u201d\uff09\n            +helpexamplerpc\uff08\u201c\u91cd\u65b0\u8003\u8651\u5757\u201d\uff0c\u201c\\\u201dblockhash\\\u201d\uff09\n        \uff1b\n\n    uint256\u6563\u5217\uff08parsehashv\uff08request.params[0]\uff0c\u201cblockhash\u201d\uff09\uff09\uff1b\n\n    {\n        \u9501\uff08CSKEMAN\uff09\uff1b\n        cBlockIndex*pbLockIndex=LookupBlockIndex\uff08\u54c8\u5e0c\uff09\uff1b\n        \u5982\u679c\uff08\uff01\uff09P-\u963b\u65ad\u86cb\u767d\uff09\n            throw jsonrpcerror\uff08rpc_invalid_address_or_key\uff0c\u201c\u627e\u4e0d\u5230\u5757\u201d\uff09\uff1b\n        }\n\n        ResetBlockFailureFlags\uff08pbLockIndex\uff09\uff1b\n    }\n\n    cvalidationState\u72b6\u6001\uff1b\n    activateBestChain\uff08\u72b6\u6001\uff0cparams\uff08\uff09\uff09\uff1b\n\n    \u5982\u679c\uff08\uff01\uff09state.isvalid\uff08\uff09\uff09\n        throw jsonrpcerror\uff08rpc_database_error\uff0cformatStateMessage\uff08state\uff09\uff09\uff1b\n    }\n\n    \u8fd4\u56denullunivalue\uff1b\n}\n\n\u9759\u6001\u5355\u503cgetchaintxstats\uff08const jsonrpcrequest&request\uff09\n{\n    if\uff08request.fhelp request.params.size\uff08\uff09>2\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201cgetchaintxstats\u201d\uff0c\n                \\n\u8ba1\u7b97\u94fe\u4e2d\u4e8b\u52a1\u603b\u6570\u548c\u901f\u7387\u7684\u7edf\u8ba1\u4fe1\u606f\u3002\\n\u201c\uff0c\n                {\n                    \u201cnblocks\u201d\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/ true, /* default_val */ \"one month\", \"Size of the window in number of blocks\"},\n\n                    /*lockhash\u201c\uff0crpcarg:\uff1atype:\uff1astr_hex\uff0c/*opt*/true\uff0c/*default_val*/\u201dchain tip\u201c\uff0c\u201d\u7ed3\u675f\u7a97\u53e3\u7684\u5757\u7684\u54c8\u5e0c\u3002\u201d\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c{n\u201d\n            \u201ctime\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u7a97\u53e3\u4e2d\u6700\u540e\u4e00\u4e2a\u5757\u7684\u65f6\u95f4\u6233\uff0c\u91c7\u7528unix\u683c\u5f0f\u3002\\n\u201d\n            \u201c\u201ctxcount\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u5230\u8be5\u70b9\u4e3a\u6b62\u94fe\u4e2d\u7684\u4e8b\u52a1\u603b\u6570\u3002\\n\u201d\n            \u201cwindow\u201dwindow\u201c\u6700\u540e\u4e00\u4e2a\u201dblock\u201chash\\\u201d\uff1a\\\u201c\u2026\\\u201d\uff0c\uff08string\uff09\u7a97\u53e3\u4e2d\u6700\u540e\u4e00\u4e2a\u5757\u7684hash\u3002\\n\u201d\n            \u201c\u7a97\u53e3\\\u5757\\\u8ba1\u6570\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u7a97\u53e3\u7684\u5927\u5c0f\uff08\u4ee5\u5757\u6570\u8ba1\uff09\u3002\\n\u201d\n            \u201c\\\u201dwindow_tx_count\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u7a97\u53e3\u4e2d\u7684\u4e8b\u52a1\u6570\u3002\u4ec5\u5f53\u201c\u7a97\u53e3\u5757\u8ba1\u6570\u201d\u5927\u4e8e0\u65f6\u8fd4\u56de\u3002\\n\n            \u201c\\\u201d\u7a97\u53e3\\\u95f4\u9694\\\u201c\uff1aXXXXX\uff0c\uff08\u6570\u5b57\uff09\u7a97\u53e3\u4e2d\u7684\u5df2\u7528\u65f6\u95f4\uff08\u4ee5\u79d2\u4e3a\u5355\u4f4d\uff09\u3002\u4ec5\u5f53\u201c\u7a97\u53e3\u5757\u8ba1\u6570\u201d\u5927\u4e8e0\u65f6\u8fd4\u56de\u3002\\n\n            \u201c\\\u201dtxRate\\\u201c\uff1ax.x x\uff0c\uff08\u6570\u5b57\uff09\u7a97\u53e3\u4e2d\u6bcf\u79d2\u4e8b\u52a1\u7684\u5e73\u5747\u901f\u7387\u3002\u4ec5\u5f53\u201c\u7a97\u53e3\u95f4\u9694\u201d\u5927\u4e8e0\u65f6\u8fd4\u56de\u3002\\n\n            \u201c}\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpExamplecli\uff08\u201cgetchaintxstats\u201d\uff0c\u201c\u201d\uff09\n            +helpExampleRPC\uff08\u201cgetchaintxstats\u201d\uff0c\u201c2016\u201d\uff09\u3002\n        \uff1b\n\n    \u5e38\u91cfcblockindex*pindex\uff1b\n    int blockcount=30*24*60*60/params\uff08\uff09.getconsensus\uff08\uff09.npowTargetSpacking\uff1b//\u9ed8\u8ba4\u4e3a1\u4e2a\u6708\n\n    if\uff08request.params[1].isNull\uff08\uff09\uff09\n        \u9501\uff08CSKEMAN\uff09\uff1b\n        pindex=chainactive.tip\uff08\uff09\uff1b\n    }\u5426\u5219{\n        uint256\u6563\u5217\uff08parsehashv\uff08request.params[1]\uff0c\u201cblockhash\u201d\uff09\uff09\uff1b\n        \u9501\uff08CSKEMAN\uff09\uff1b\n        pindex=\u67e5\u627e\u5757\u7d22\u5f15\uff08hash\uff09\uff1b\n        \u5982\u679c\uff08\uff01\uff09pQueD\uff09{\n            throw jsonrpcerror\uff08rpc_invalid_address_or_key\uff0c\u201c\u627e\u4e0d\u5230\u5757\u201d\uff09\uff1b\n        }\n        \u5982\u679c\uff08\uff01\uff09chainactive.contains\uff08pindex\uff09\uff09\n            throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201cblock is not in main chain\u201d\uff09\uff1b\n        }\n    }\n\n    \u65ad\u8a00\uff08pCurnor\uff09\uff01= null pTr\uff09\uff1b\n\n    if\uff08request.params[0].isNull\uff08\uff09\uff09\n        blockcount=std:\uff1amax\uff080\uff0cstd:\uff1amin\uff08blockcount\uff0cpindex->nheight-1\uff09\uff09\uff1b\n    }\u5426\u5219{\n        blockCount=request.params[0].get_int\uff08\uff09\uff1b\n\n        if\uff08blockcount<0\uff08blockcount>0&&blockcount>=pindex->nheight\uff09\uff09\n            throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201c\u65e0\u6548\u7684\u5757\u8ba1\u6570\uff1a\u5e94\u4ecb\u4e8e0\u548c\u5757\u7684\u9ad8\u5ea6-1\u4e4b\u95f4\u201d\uff09\uff1b\n        }\n    }\n\n    const cblockindex*pindexpast=pindex->getancestor\uff08pindex->nheight-blockcount\uff09\uff1b\n    int ntimediff=pindex->getmediantimepast\uff08\uff09-pindexpast->getmediantimepast\uff08\uff09\uff1b\n    int ntxdiff=pindex->nchaintx-pindexpass->nchaintx\uff1b\n\n    \u5355\u503cret\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n    ret.pushkv\uff08\u201c\u65f6\u95f4\u201d\uff0c\uff08int64_t\uff09pindex->ntime\uff09\uff1b\n    ret.pushkv\uff08\u201ctxcount\u201d\uff0c\uff08int64_t\uff09pindex->nchaintx\uff09\uff1b\n    ret.pushkv\uff08\u201cwindow_final_block_hash\u201d\uff0cpindex->getblockhash\uff08\uff09.gethex\uff08\uff09\uff09\uff1b\n    ret.pushkv\uff08\u201c\u7a97\u53e3\u5757\u8ba1\u6570\u201d\uff0c\u5757\u8ba1\u6570\uff09\uff1b\n    \u5982\u679c\uff08blockcount>0\uff09\n        ret.pushkv\uff08\u201cwindow_tx_count\u201d\uff0cntxdiff\uff09\uff1b\n        ret.pushkv\uff08\u201c\u7a97\u53e3\u95f4\u9694\u201d\uff0cntimediff\uff09\uff1b\n        \u5982\u679c\uff08ntimediff>0\uff09\n            ret.pushkv\uff08\u201ctxtrate\u201d\uff0c\uff08\uff08\u53cc\uff09ntxdiff\uff09/ntimediff\uff09\uff1b\n        }\n    }\n\n    \u8fd4\u56deRET\uff1b\n}\n\n\u6a21\u677f<typename t>\n\u9759\u6001t calculateTruncatedMedian\uff08std:\uff1avector<t>\u548cscores\uff09\n{\n    size_t size=scores.size\uff08\uff09\uff1b\n    \u5982\u679c\uff08\u5c3a\u5bf8=0\uff09\n        \u8fd4\u56de0\uff1b\n    }\n\n    std\uff1a\uff1asort\uff08scores.begin\uff08\uff09\uff0cscores.end\uff08\uff09\uff09\uff1b\n    \u5982\u679c\uff08\u5927\u5c0f%2==0\uff09\n        \u8fd4\u56de\uff08\u5206\u6570[size/2-1]+\u5206\u6570[size/2]\uff09/2\uff1b\n    }\u5426\u5219{\n        \u8fd4\u56de\u5206\u6570[\u5c3a\u5bf8/2]\uff1b\n    }\n}\n\nvoid calculatePercentilesByweight\uff08camount result[num\u640egetBlockStats_percentiles]\uff0cstd:\uff1avector<std:\uff1apair<camount\uff0cint64_t>>&scores\uff0cint64_t total_weight\uff09\n{\n    if\uff08scores.empty\uff08\uff09\uff09\n        \u8fd4\u56de\uff1b\n    }\n\n    std\uff1a\uff1asort\uff08scores.begin\uff08\uff09\uff0cscores.end\uff08\uff09\uff09\uff1b\n\n    //\u7b2c10\u300125\u300150\u300175\u548c90\u767e\u5206\u4f4d\u91cd\u91cf\u5355\u4f4d\u3002\n    \u5e38\u91cf\u53cc\u6743\u91cd[num_GetBlockStats_Percentiles]=\n        \u603b\u91cd\u91cf/10.0\uff0c\u603b\u91cd\u91cf/4.0\uff0c\u603b\u91cd\u91cf/2.0\uff0c\uff08\u603b\u91cd\u91cf*3.0\uff09/4.0\uff0c\uff08\u603b\u91cd\u91cf*9.0\uff09/10.0\n    }\uff1b\n\n    Int64_t next_percentile_index=0\uff1b\n    Int64_t\u7d2f\u8ba1_\u6743\u91cd=0\uff1b\n    for\uff08const auto&element:\u5206\u6570\uff09\n        \u7d2f\u8ba1_weight+=element.second\uff1b\n        while\uff08next_percentile_index<num_getblockstats_percentiles&&cumulative_weight>=weights[next_percentile_index]\uff09\uff1b\n            \u7ed3\u679c[\u4e0b\u4e00\u4e2a\u767e\u5206\u4f4d\u7d22\u5f15]=element.first\uff1b\n            +\u4e0b\u4e00\u4e2a_\u767e\u5206\u4f4d\u6570_\u6307\u6570\uff1b\n        }\n    }\n\n    //\u7528\u6700\u540e\u4e00\u4e2a\u503c\u586b\u5145\u6240\u6709\u5269\u4f59\u7684\u767e\u5206\u4f4d\u6570\u3002\n    for\uff08int64_t i=next_percentile_index\uff1bi<num_getblockstats_percentiles\uff1bi++\uff09\n        \u7ed3\u679c[i]=scores.back\uff08\uff09.first\uff1b\n    }\n}\n\n\u6a21\u677f<typename t>\n\u9759\u6001\u5185\u8054bool sethaskeys\uff08const std:\uff1aset<t>&set\uff09\u8fd4\u56defalse\uff1b\n\u6a21\u677f<typename t\uff0ctypename tk\uff0ctypename\u2026ARG>\n\u9759\u6001\u5185\u8054bool sethaskeys\uff08const std:\uff1aset<t>&set\uff0cconst tk&key\uff0cconst args&\u2026ARGS\uff09\n{\n    \u8fd4\u56de\uff08set.count\uff08key\uff09\uff01=0\uff09sethaskeys\uff08set\uff0cargs\u2026\uff09\uff1b\n}\n\n//outpoint\uff08utxo\u7d22\u5f15\u9700\u8981\uff09+nheight+fcoinbase\n\u9759\u6001constexpr size_t per_utxo_\u5f00\u9500=sizeof\uff08coutpoint\uff09+sizeof\uff08uint32_t\uff09+sizeof\uff08bool\uff09\uff1b\n\n\u9759\u6001\u5355\u503cgetblockstats\uff08const jsonrpcrequest&request\uff09\n{\n    if\uff08request.fhelp request.params.size\uff08\uff09<1 request.params.size\uff08\uff09>4\uff09\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201cgetblockstats\u201d\uff0c\n                \\n\u8ba1\u7b97\u7ed9\u5b9a\u7a97\u53e3\u7684\u6bcf\u4e2a\u5757\u7684\u7edf\u8ba1\u4fe1\u606f\u3002\u6240\u6709\u91d1\u989d\u5747\u4ee5Satoshis\u4e3a\u5355\u4f4d\u3002\\n\u201c\n                \u201c\u4fee\u526a\u5bf9\u67d0\u4e9b\u9ad8\u5ea6\u4e0d\u8d77\u4f5c\u7528\u3002\\n\u201d\n                \u201c\u5982\u679c\u6ca1\u6709utxo-size_inc\u7684-txindex\u3001*\u8d39\u7528\u6216*feerate\u72b6\u6001\uff0c\u5b83\u5c06\u65e0\u6cd5\u5de5\u4f5c\u3002\\n\u201d\uff0c\n                {\n                    \u201chash_or_height\u201d\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/ false, /* default_val */ \"\", \"The block hash or height of the target block\", \"\", {\"\", \"string or numeric\"}},\n\n                    /*tats\u201c\uff0crpcarg:\uff1atype:\uff1aarr\uff0c/*opt*/true\uff0c/*default_val*/\u201dall values\u201c\uff0c\u201d\u8981\u7ed8\u5236\u7684\u503c\uff08\u8bf7\u53c2\u89c1\u4e0b\u9762\u7684\u7ed3\u679c\uff09\u201d\uff0c\n                        {\n                            \u201c\u9ad8\u5ea6\u201d\uff0crpcarg:\uff1atype:\uff1astr\uff0c/*opt*/ true, /* default_val */ \"\", \"Selected statistic\"},\n\n                            /*\u8f93\u5165\u6cd5\u201c\uff0crpcarg:\uff1atype:\uff1astr\uff0c/*opt*/true\uff0c/*\u9ed8\u8ba4\u503c\u201c/\u201d\uff0c\u201c\u6240\u9009\u7edf\u8ba1\u201d\uff0c\n                        }\n                        \u201c\u7edf\u8ba1\u201d}\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c\uff08JSON\u5bf9\u8c61\\n\u201d\n            \u201cavgfee\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u5757\u4e2d\u7684\u5e73\u5747\u8d39\u7528\\n\u201d\n            \u201cavgfeerate\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u5e73\u5747\u9891\u7387\uff08\u4ee5\u6bcf\u865a\u62df\u5b57\u8282\u7684Satoshis\u4e3a\u5355\u4f4d\uff09\\n\u201d\n            \u201cavgtxsize\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u5e73\u5747\u4e8b\u52a1\u5927\u5c0f\\n\u201d\n            \u201c\\\u201dblock hash\\\u201c\uff1axxxxx\uff0c\uff08string\uff09\u5757\u54c8\u5e0c\uff08\u68c0\u67e5\u6f5c\u5728\u7684\u91cd\u65b0\u6392\u5e8f\uff09\u3002\\n\u201d\n            \u201cfeerate percentiles\u201d\uff1a[\uff08\u6570\u5b57\u6570\u7ec4\uff09feerates at the 10th\u300125th\u300150th\u300175th\u548c90th percentile weight unity\uff08in satoshis per virtual byte\uff09\\n\u201d\n            \u201c\u7b2c10\u4e2a\u767e\u5206\u70b9\u503c\u201d\uff0c\uff08\u6570\u5b57\uff09\u7b2c10\u4e2a\u767e\u5206\u70b9\u503c\\n\u201d\n            \u201c25%\u201d\uff0c\uff08\u6570\u5b57\uff0925%\u201d\uff0c\n            \u201c\u7b2c50\u4e2a\u767e\u5206\u70b9\u503c\u201d\u201c\uff0c\uff08\u6570\u5b57\uff09\u7b2c50\u4e2a\u767e\u5206\u70b9\u503c\\n\u201d\n            \u201c\u7b2c75\u4e2a\u767e\u5206\u70b9\u503c\u201d\u201c\uff0c\uff08\u6570\u5b57\uff09\u7b2c75\u4e2a\u767e\u5206\u70b9\u503c\\n\u201d\n            \u201c\u7b2c90\u4e2a\u767e\u5206\u70b9\u503c\u201d\u201c\uff0c\uff08\u6570\u5b57\uff09\u7b2c90\u4e2a\u767e\u5206\u70b9\u503c\\n\u201d\n            \u201c\u201d\n            \u201c\u201c\u9ad8\u5ea6\u201d\uff1aXXXXX\uff0c\uff08\u6570\u5b57\uff09\u5757\u7684\u9ad8\u5ea6\\n\u201d\n            \u201c\\\u201dins\\\u201c\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u8f93\u5165\u6570\uff08\u4e0d\u5305\u62eccoinbase\uff09\\n\u201d\n            \u201cmaxfee\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u5757\u4e2d\u7684\u6700\u5927\u8d39\u7528\\n\u201d\n            \u201cmaxfeerate\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u6700\u5927feerate\uff08\u4ee5\u6bcf\u4e2a\u865a\u62df\u5b57\u8282\u7684Satoshis\u4e3a\u5355\u4f4d\uff09\\n\u201d\n            \u201c\\\u201dmaxtxsize\\\u201c\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u6700\u5927\u4e8b\u52a1\u5927\u5c0f\\n\u201d\n            \u201cmedian fee\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u5757\u4e2d\u622a\u65ad\u7684\u4e2d\u95f4\u8d39\u7528\\n\u201d\n            \u201c\u201cmedian time\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u8fc7\u53bb\u7684\u5757\u4e2d\u4f4d\u6570\u65f6\u95f4\\n\u201d\n            \u201cmediantxsize\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u622a\u65ad\u7684\u4e2d\u95f4\u4e8b\u52a1\u5927\u5c0f\\n\u201d\n            \u201cminfee\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u5757\u4e2d\u7684\u6700\u4f4e\u8d39\u7528\\n\u201d\n            \u201cminfeerate\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u6700\u5c0ffeerate\uff08\u4ee5\u6bcf\u4e2a\u865a\u62df\u5b57\u8282\u7684Satoshis\u4e3a\u5355\u4f4d\uff09\\n\u201d\n            \u201cmintxsize\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u6700\u5c0f\u4e8b\u52a1\u5927\u5c0f\\n\u201d\n            \u201c\u201cOuts\u201d\uff1aXXXXX\uff0c\uff08\u6570\u5b57\uff09\u8f93\u51fa\u6570\\n\u201d\n            \u201c\u201c\u8865\u8d34\u201d\uff1aXXXXX\uff0c\uff08\u6570\u5b57\uff09\u5757\u8865\u8d34\\n\u201d\n            \u201c\u201cswtotal\u201d\u5927\u5c0f\u201c\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u6240\u6709segwit\u4e8b\u52a1\u7684\u603b\u5927\u5c0f\\n\u201d\n            \u201cswtotal_weight\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u6240\u6709segwit\u4e8b\u52a1\u7684\u603b\u91cd\u91cf\u9664\u4ee5segwit\u6bd4\u4f8b\u56e0\u5b50\uff084\uff09\\n\u201d\n            \u201c\u201cSWTXS\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09segwit\u4e8b\u52a1\u6570\\n\u201d\n            \u201c\u201c\u65f6\u95f4\u201d\uff1aXXXXX\uff0c\uff08\u6570\u5b57\uff09\u5757\u65f6\u95f4\\n\u201d\n            \u201c\\\u201d\u5408\u8ba1\\\u201c\uff1aXXXXX\uff0c\uff08\u6570\u5b57\uff09\u6240\u6709\u8f93\u51fa\u7684\u603b\u91d1\u989d\uff08\u4e0d\u5305\u62ecCoinBase\uff0c\u56e0\u6b64\u5956\u52b1[\u5373\u8865\u8d34+\u603b\u8d39\u7528]\uff09\\n\u201d\n            \u201c\u603b\u8ba1\u5927\u5c0f\u201d\uff1aXXXXX\uff0c\uff08\u6570\u5b57\uff09\u6240\u6709\u975eCoinBase\u4ea4\u6613\u7684\u603b\u8ba1\u5927\u5c0f\\n\u201d\n            \u201c\u603b\u6743\u91cd\u201d\uff1aXXXXX\uff0c\uff08\u6570\u5b57\uff09\u6240\u6709\u975eCoinBase\u4ea4\u6613\u7684\u603b\u6743\u91cd\u9664\u4ee5Segwit\u6bd4\u4f8b\u56e0\u5b50\uff084\uff09\\n\u201d\n            \u201c\\\u201dtotal fee\\\u201c\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u603b\u8d39\u7528\\n\u201d\n            \u201c\u201ctxs\\\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u4e8b\u52a1\u6570\uff08\u4e0d\u5305\u62eccoinbase\uff09\\n\u201d\n            \u201c\u201cutxo\u589e\u52a0\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09\u672a\u6682\u505c\u8f93\u51fa\u6570\u91cf\u7684\u589e\u52a0/\u51cf\u5c11\\n\u201d\n            \u201cutxo-size_inc\u201d\uff1axxxxx\uff0c\uff08\u6570\u5b57\uff09utxo\u7d22\u5f15\u7684\u5927\u5c0f\u589e\u52a0/\u51cf\u5c11\uff08\u4e0d\u6298\u6263opu-return\u548c\u7c7b\u4f3c\u7684\u503c\uff09\\n\u201d\n            \u201c}\\n\u201d\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpExamplecli\uff08\u201cgetblockstats\u201d\uff0c\u201c1000'[\\\u201dminfeerate\\\u201c\uff0c\\\u201davgfeerate\\\u201c]\u201d\uff09\n            +helpExampleRpc\uff08\u201cgetBlockstats\u201d\uff0c\u201c1000'[\\\u201dminfeerate\\\u201c\uff0c\\\u201davgfeerate\\\u201c]\u201d\uff09\n        \uff1b\n    }\n\n    \u9501\uff08CSKEMAN\uff09\uff1b\n\n    cblockindex*\u7d22\u5f15\uff1b\n    if\uff08request.params[0].isnum\uff08\uff09\uff09\n        const int height=request.params[0].get_int\uff08\uff09\uff1b\n        const int current_tip=chainactive.height\uff08\uff09\uff1b\n        \u5982\u679c\uff08\u9ad8\u5ea6<0\uff09\n            throw jsonrpcerror\uff08rpc_\u65e0\u6548\u7684_\u53c2\u6570\uff0cstrprintf\uff08\u201c\u76ee\u6807\u5757\u9ad8\u5ea6%d\u4e3a\u8d1f\u201d\uff0c\u9ad8\u5ea6\uff09\uff09\uff1b\n        }\n        \u5982\u679c\uff08\u9ad8\u5ea6>\u5f53\u524d_\u5c16\uff09\n            throw jsonrpcerror\uff08rpc_\u65e0\u6548\u7684_\u53c2\u6570\uff0cstrprintf\uff08\u201c\u5f53\u524d\u63d0\u793a%d\u4e4b\u540e\u7684\u76ee\u6807\u5757\u9ad8\u5ea6%d\u201d\uff0c\u9ad8\u5ea6\uff0c\u5f53\u524d_\u63d0\u793a\uff09\uff09\uff1b\n        }\n\n        pindex=\u94fe\u6fc0\u6d3b[\u9ad8\u5ea6]\uff1b\n    }\u5426\u5219{\n        const uint256 hash\uff08parsehashv\uff08request.params[0]\uff0c\u201chash_or_height\u201d\uff09\uff09\uff1b\n        pindex=\u67e5\u627e\u5757\u7d22\u5f15\uff08hash\uff09\uff1b\n        \u5982\u679c\uff08\uff01\uff09pQueD\uff09{\n            throw jsonrpcerror\uff08rpc_invalid_address_or_key\uff0c\u201c\u627e\u4e0d\u5230\u5757\u201d\uff09\uff1b\n        }\n        \u5982\u679c\uff08\uff01\uff09chainactive.contains\uff08pindex\uff09\uff09\n            throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0cstrprintf\uff08\u201cblock is not in chain%s\u201d\uff0cparams\uff08\uff09.networkidstring\uff08\uff09\uff09\uff1b\n        }\n    }\n\n    \u65ad\u8a00\uff08pCurnor\uff09\uff01= null pTr\uff09\uff1b\n\n    std:\uff1aset<std:\uff1astring>stats\uff1b\n    \u5982\u679c\uff08\uff01\uff09request.params[1].isNull\uff08\uff09\uff09\n        const univalue stats_univalue=request.params[1].get_array\uff08\uff09\uff1b\n        for\uff08unsigned int i=0\uff1bi<stats_univalue.size\uff08\uff09\uff1bi++\uff09\n            const std:\uff1astring stat=stats_univalue[i].get_str\uff08\uff09\uff1b\n            stats.\u63d2\u5165\uff08stat\uff09\uff1b\n        }\n    }\n\n    const cblock block=getblockchecked\uff08pindex\uff09\uff1b\n\n    const bool do_all=stats.size\uff08\uff09==0\uff1b//\u5982\u679c\u672a\u9009\u62e9\u4efb\u4f55\u5185\u5bb9\uff0c\u5219\u8ba1\u7b97\u6240\u6709\u5185\u5bb9\uff08\u9ed8\u8ba4\uff09\n    const bool do_mediantxsize=\u5168\u90e8stats.count\uff08\u201cmediantxsize\u201d\uff09\uff01\uff1d0\uff1b\n    const bool do_medianfee=\u5168\u90e8stats.count\uff08\u201cmedianfee\u201d\uff09\uff01\uff1d0\uff1b\n    const bool do feerate_percentiles=\u6240\u6709stats.count\uff08\u201cfeerate_percentiles\u201d\uff09\uff01\uff1d0\uff1b\n    const bool loop_inputs=do_all_do_medianfee_do_erate_u percentiles_\n        sethaskeys\uff08stats\uff0c\u201cutxo-size_inc\u201d\uff0c\u201ctotalfee\u201d\uff0c\u201cavgfee\u201d\uff0c\u201cavgfeerate\u201d\uff0c\u201cminfee\u201d\uff0c\u201cmaxfee\u201d\uff0c\u201cminfeerate\u201d\uff0c\u201cmaxfeerate\u201d\uff09\uff1b\n    const bool loop_outputs=do_all_loop_inputs_stats.count\uff08\u201ctotal_out\u201d\uff09\uff1b\n    const bool do_calculate_size=do_mediantxsize_\n        sethaskeys\uff08stats\uff0c\u201ctotal_size\u201d\uff0c\u201cavgtxsize\u201d\uff0c\u201cmintxsize\u201d\uff0c\u201cmaxtxsize\u201d\uff0c\u201cswtotal_size\u201d\uff09\uff1b\n    const bool do_calculate_weight=do_all_sethaskeys\uff08stats\uff0c\u201ctotalou weight\u201d\uff0c\u201cavgfeerate\u201d\uff0c\u201cswtotalou weight\u201d\uff0c\u201cavgfeerate\u201d\uff0c\u201cfeerateou percentiles\u201d\uff0c\u201cminfeerate\u201d\uff0c\u201cmaxfeerate\u201d\uff09\uff1b\n    const bool do_calculate_sw=do_all_sethaskeys\uff08stats\uff0c\u201cswtxs\u201d\uff0c\u201cswtotal_size\u201d\uff0c\u201cswtotal_weight\u201d\uff09\uff1b\n\n    \u5982\u679c\uff08\u5faa\u73af\u8f93\u5165&\uff01GX-TXEXT\uff09{\n        throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201c\u6240\u9009\u7684\u4e00\u4e2a\u6216\u591a\u4e2a\u72b6\u6001\u9700\u8981-txindex enabled\u201d\uff09\uff1b\n    }\n\n    camount maxfee=0\uff1b\n    camount maxfeerate=0\uff1b\n    camount minfee=\u6700\u9ad8\u5956\u91d1\uff1b\n    camount minfeerate=\u6700\u9ad8\u91d1\u989d\uff1b\n    camount total_out=0\uff1b\n    camount totalfee=0\uff1b\n    Int64\u8f93\u5165=0\uff1b\n    Int64_t maxtxsize=0\uff1b\n    int64_t mintxsize=max_block_serialized_size\uff1b\n    Int64\u8f93\u51fa=0\uff1b\n    int64_t swtotal_size=0\uff1b\n    Int64\u603b\u91cd\u91cf=0\uff1b\n    Int64_t SWTXS=0\uff1b\n    Int64\u603b\u5c3a\u5bf8=0\uff1b\n    Int64\u603b\u91cd\u91cf=0\uff1b\n    int64_t utxo_size_inc=0\uff1b\n    std:\uff1avector<camount>fee_array\uff1b\n    std:\uff1avector<std:\uff1apair<camount\uff0cint64_t>>feerate_array\uff1b\n    std:\uff1avector<int64_t>txsize_array\uff1b\n\n    \u7528\u4e8e\uff08const auto&tx:block.vtx\uff09\n        \u8f93\u51fa+=tx->vout.size\uff08\uff09\uff1b\n\n        camount tx_total_out=0\uff1b\n        \u5982\u679c\uff08\u56de\u8def\u8f93\u51fa\uff09\n            for\uff08const ctxout&out:tx->vout\uff09\n                tx_total_out+=out.n\u503c\uff1b\n                utxo_size_inc+=getSerializeSize\uff08out\uff0c\u534f\u8bae_\u7248\u672c\uff09+\u6bcf_utxo_\u5f00\u9500\uff1b\n            }\n        }\n\n        if\uff08tx->iscoinBase\uff08\uff09\uff09\n            \u7ee7\u7eed\uff1b\n        }\n\n        input s+=tx->vin.size\uff08\uff09\uff1b//\u4e0d\u8ba1\u7b97coinbase\u7684\u5047\u8f93\u5165\n        total_out+=tx_total_out\uff1b//\u4e0d\u8ba1\u7b97coinbase\u5956\u52b1\n\n        Int64_t tx_\u5c3a\u5bf8=0\uff1b\n        \u5982\u679c\uff08do_calculate_size\uff09\n\n            tx_size=tx->gettotalize\uff08\uff09\uff1b\n            \u5982\u679c\uff08do mediantxsize\uff09\n                tx size_array.push_back\uff08tx_size\uff09\uff1b\n            }\n            max tx size=std:\uff1amax\uff08max tx size\uff0ctx_\u5927\u5c0f\uff09\uff1b\n            min tx size=std:\uff1amin\uff08min tx size\uff0ctx_\u5927\u5c0f\uff09\uff1b\n            \u603b\u5c3a\u5bf8+=Tx\u5c3a\u5bf8\uff1b\n        }\n\n        Int64_t\u6743\u91cd=0\uff1b\n        \u5982\u679c\uff08do_calculate_weight\uff09\n            \u6743\u91cd=GetTransactionWeight\uff08*Tx\uff09\uff1b\n            \u603b\u91cd\u91cf+=\u91cd\u91cf\uff1b\n        }\n\n        if\uff08do_calculate_sw&&tx->hasWitness\uff08\uff09\uff09\n            +SWTXs\uff1b\n            swtotal_size+=tx_\u5927\u5c0f\uff1b\n            SWtotal_weight+=\u91cd\u91cf\uff1b\n        }\n\n        if\uff08\u56de\u8def\u8f93\u5165\uff09\n            camount tx_total_in=0\uff1b\n            \u7528\u4e8e\uff08const ctxin&in:tx->vin\uff09\n                ctransactionref-tx-in\uff1b\n                uint256\u54c8\u5e0c\u5757\uff1b\n                \u5982\u679c\uff08\uff01\uff09getTransaction\uff08in.prevout.hash\uff0ctx_in\uff0cparams\uff08\uff09.getconsensus\uff08\uff09\uff0chashblock\uff0cfalse\uff09\uff09\n                    throw jsonrpcerror\uff08rpc_internal_error\uff0cstd:\uff1astring\uff08\u201c\u610f\u5916\u7684\u5185\u90e8\u9519\u8bef\uff08Tx\u7d22\u5f15\u4f3c\u4e4e\u5df2\u635f\u574f\uff09\u201d\uff09\uff1b\n                }\n\n                ctxout prevoutput=tx_in->vout[in.prevout.n]\uff1b\n\n                tx_total_in+=\u4e0a\u4e00\u4e2a\u8f93\u51fa\u503c\uff1b\n                utxo-size_inc-=getserializesize\uff08prevoutput\uff0cprotocol_version\uff09+\u6bcf\u4e2autxo_\u5f00\u9500\uff1b\n            }\n\n            camount txfee=tx_total_in-tx_total_out\uff1b\n            \u65ad\u8a00\uff08moneyrange\uff08txfee\uff09\uff09\uff1b\n            \u5982\u679c\uff08do-medianfee\uff09\n                fee_array.push_back\uff08txfee\uff09\uff1b\n            }\n            maxfee=std:\uff1amax\uff08maxfee\uff0ctxfee\uff09\uff1b\n            minfee=std:\uff1amin\uff08minfee\uff0ctxfee\uff09\uff1b\n            \u603b\u8d39\u7528+=txfee\uff1b\n\n            //\u65b0feerate\u4f7f\u7528satoshis per virtual byte\u800c\u4e0d\u662fper serialized byte\n            camount feerate=\u91cd\u91cf\uff1f\uff08txfee*\u89c1\u8bc1\u4eba\u00d7\u6bd4\u4f8b\u7cfb\u6570\uff09/\u91cd\u91cf\uff1a0\uff1b\n            \u5982\u679c\uff08\u505a\u767e\u5206\u6bd4\uff09\n                feerate_array.emplace_back\uff08std\uff1a\uff1amake_pair\uff08feerate\uff0cweight\uff09\uff09\uff1b\n            }\n            max feerate=std:\uff1amax\uff08max feerate\uff0cfeerate\uff09\uff1b\n            min feerate=std:\uff1amin\uff08min feerate\uff0cfeerate\uff09\uff1b\n        }\n    }\n\n    camount feerate_percentiles[num_getblockstats_percentiles]=0_\n    \u8ba1\u7b97\u767e\u5206\u6bd4\u91cd\u91cf\uff08feerate_percentiles\uff0cfeerate_array\uff0ctotal_weight\uff09\uff1b\n\n    \u5355\u503c\u51fd\u6570\uff08univavalue:\uff1avarr\uff09\uff1b\n    for\uff08int64_t i=0\uff1bi<num_getblockstats_percentiles\uff1bi++\uff09\n        feerates.push_back\uff08feerate_percentiles[i]\uff09\uff1b\n    }\n\n    univalue ret_all\uff08univalue:\uff1avobj\uff09\uff1b\n    ret_all.pushkv\uff08\u201cavgfee\u201d\uff0c\uff08block.vtx.size\uff08\uff09>1\uff09\uff1ftotalfee/\uff08block.vtx.size\uff08\uff09-1\uff09\uff1a0\uff09\uff1b\n    ret_all.pushkv\uff08\u201cavgfeereate\u201d\uff0c\u603b\u91cd\u91cf\uff1f\uff08totalfee*witness_scale_factor\uff09/total_weight:0\uff09\uff1b//\u5355\u4f4d\uff1aSat/vByte\n    ret_all.pushkv\uff08\u201cavgtxsize\u201d\uff0c\uff08block.vtx.size\uff08\uff09>1\uff09\uff1f\u603b\u5c3a\u5bf8/\uff08block.vtx.size\uff08\uff09-1\uff09\uff1a0\uff09\uff1b\n    ret_all.pushkv\uff08\u201cblockhash\u201d\uff0cpindex->getblockhash\uff08\uff09.gethex\uff08\uff09\uff09\uff1b\n    ret_all.pushkv\uff08\u201cfeerate_percentiles\u201d\uff0cfeerates_res\uff09\uff1b\n    ret_all.pushkv\uff08\u201c\u9ad8\u5ea6\u201d\uff0c\uff08int64_t\uff09pindex->nheight\uff09\uff1b\n    ret_all.pushkv\uff08\u201cins\u201d\uff0c\u8f93\u5165\uff09\uff1b\n    ret_all.pushkv\uff08\u201cmaxfee\u201d\uff0cmaxfee\uff09\uff1b\n    ret_all.pushkv\uff08\u201cmaxfeerate\u201d\uff0cmaxfeerate\uff09\uff1b\n    ret_all.pushkv\uff08\u201cmaxtxsize\u201d\uff0cmaxtxsize\uff09\uff1b\n    ret_all.pushkv\uff08\u201cmedianfee\u201d\uff0ccalculated truncatedmedian\uff08fee_array\uff09\uff09\uff1b\n    ret_all.pushkv\uff08\u201cmediantime\u201d\uff0cpindex->getmediantimepast\uff08\uff09\uff09\uff1b\n    ret_all.pushkv\uff08\u201cmediantxsize\u201d\uff0ccalculatetruncatedmedian\uff08txsize_array\uff09\uff09\uff1b\n    ret_all.pushkv\uff08\u201cminfee\u201d\uff0c\uff08minfee==max_money\uff09\uff1f0\uff1a\u660e\u8d39\uff09\uff1b\n    ret-all.pushkv\uff08\u201cminfeerate\u201d\uff0c\uff08minfeerate==max\\u money\uff09\uff1f0\uff1a\u5206\u949f\uff09\uff1b\n    ret_all.pushkv\uff08\u201cmintxsize\u201d\uff0cmintxsize==max_block_serialized_size\uff1f\uff1f0\uff1aMimtxSead\uff1b\n    ret_all.pushkv\uff08\u201c\u8f93\u51fa\u201d\uff0c\u8f93\u51fa\uff09\uff1b\n    ret_all.pushkv\uff08\u201c\u8865\u8d34\u201d\uff0cgetBlock\u8865\u8d34\uff08pindex->nheight\uff0cparams\uff08\uff09.getconsensus\uff08\uff09\uff09\uff1b\n    ret_all.pushkv\uff08\u201cswtotal_size\u201d\uff0cswtotal_size\uff09\uff1b\n    ret_all.pushkv\uff08\u201cswtotal_weight\u201d\uff0cswtotal_weight\uff09\uff1b\n    ret_all.pushkv\uff08\u201cSWTXS\u201d\uff0cSWTXS\uff09\uff1b\n    ret_all.pushkv\uff08\u201c\u65f6\u95f4\u201d\uff0cpindex->getBlockTime\uff08\uff09\uff09\uff1b\n    ret_all.pushkv\uff08\u201ctotal_out\u201d\uff0ctotal_out\uff09\uff1b\n    ret_all.pushkv\uff08\u201c\u603b\u5c3a\u5bf8\u201d\uff0c\u603b\u5c3a\u5bf8\uff09\uff1b\n    ret_all.pushkv\uff08\u201c\u603b\u91cd\u91cf\u201d\uff0c\u603b\u91cd\u91cf\uff09\uff1b\n    ret_all.pushkv\uff08\u201ctotalfee\u201d\uff0ctotalfee\uff09\uff1b\n    ret_all.pushkv\uff08\u201ctxs\u201d\uff0c\uff08int64_t\uff09block.vtx.size\uff08\uff09\uff09\uff1b\n    ret_all.pushkv\uff08\u201cutxo_increase\u201d\uff0c\u8f93\u51fa-\u8f93\u5165\uff09\uff1b\n    ret_all.pushkv\uff08\u201cutxo_size_inc\u201d\uff0cutxo_size_inc\uff09\uff1b\n\n    \u5982\u679c\uff08doyALL\uff09{\n        \u8fd4\u56de\u56de\u590d\uff1b\n    }\n\n    \u5355\u503cret\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n    for\uff08const std:\uff1astring&stat:stats\uff09\n        const univalue&value=ret_all[stat]\uff1b\n        if\uff08value.isNull\uff08\uff09\uff09\n            throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0cstrprintf\uff08\u201cinvalid selected statistic%s\u201d\uff0cstat\uff09\uff09\uff1b\n        }\n        ret.pushkv\uff08stat\uff0cvalue\uff09\uff1b\n    }\n    \u8fd4\u56deRET\uff1b\n}\n\n\u9759\u6001\u5355\u503csavemempool\uff08const jsonrpcrequest&request\uff09\n{\n    \u5982\u679c\uff08request.fhelp request.params.size\uff08\uff09\uff01= 0\uff09{\n        throw std:\uff1aruntime_\u9519\u8bef\uff08\n            rpchelpman\u201c\u4fdd\u5b58\u5185\u5b58\u6c60\u201d\uff0c\n                \\n\u5c06\u5185\u5b58\u6c60\u590d\u5236\u5230\u78c1\u76d8\u3002\u5728\u4e0a\u4e00\u4e2a\u8f6c\u50a8\u5b8c\u5168\u52a0\u8f7d\u4e4b\u524d\uff0c\u5b83\u5c06\u5931\u8d25\u3002\\n\u201c\u201d\n                toSTRIN\uff08\uff09+\n            \u201c\\n\u5b9e\u4f8b\uff1a\\n\u201d\n            +helpexamplecli\uff08\u201csavemempool\u201d\uff0c\u201c\u201d\uff09\n            +helpexamplerpc\uff08\u201csavemempool\u201d\uff0c\u201c\u201d\uff09\n        \uff1b\n    }\n\n    \u5982\u679c\uff08\uff01\uff09g_\u662f_mempool_loaded\uff09\n        throw jsonrpcerror\uff08rpc\u201cmisc\u201d\u9519\u8bef\uff0c\u201cmempool\u5c1a\u672a\u52a0\u8f7d\u201d\uff09\uff1b\n    }\n\n    \u5982\u679c\uff08\uff01\uff09dumpmempool\uff08\uff09\uff09\n        throw jsonrpcerror\uff08rpc_misc_error\uff0c\u201cUnable to dump mempool to disk\u201d\uff09\uff1b\n    }\n\n    \u8fd4\u56denullunivalue\uff1b\n}\n\n/ /\uff01\u641c\u7d22\u7ed9\u5b9a\u7684pubkey\u811a\u672c\u96c6\nbool findscriptpubkey\uff08std:\uff1aatomic<int>&scan_progress\uff0cconst std:\uff1aatomic<bool>&shouldaurt\uff0cint64_t&count\uff0cccoinsviewcursor*cursor\uff0cconst std:\uff1aset<cscript>&pines\uff0cstd:\uff1amap<coutpoint\uff0ccoin>out_results\uff09\n    \u626b\u63cf\u8fdb\u5ea6=0\uff1b\n    \u8ba1\u6570\uff1d0\uff1b\n    while\uff08cursor->valid\uff08\uff09\uff09\n        \u5173\u952e\u70b9\uff1b\n        \u786c\u5e01\u786c\u5e01\uff1b\n        \u5982\u679c\uff08\uff01\uff09\u5149\u6807->getkey\uff08key\uff09\uff01cursor->getvalue\uff08coin\uff09\uff09\u8fd4\u56defalse\uff1b\n        \u5982\u679c\uff08++\u8ba1\u6570%8192==0\uff09\n            boost:\uff1athis_thread:\uff1ainterrupt_point\uff08\uff09\uff1b\n            \u5982\u679c\uff08\u5e94\u8be5\u4e2d\u6b62\uff09\n                //\u5141\u8bb8\u901a\u8fc7abort\u5f15\u7528\u4e2d\u6b62\u626b\u63cf\n                \u8fd4\u56de\u9519\u8bef\uff1b\n            }\n        }\n        \u5982\u679c\uff08\u8ba1\u6570%256==0\uff09\n            //\u6bcf256\u9879\u66f4\u65b0\u8fdb\u5ea6\u5f15\u7528\n            uint32_t high=0x100**key.hash.begin\uff08\uff09+*\uff08key.hash.begin\uff08\uff09+1\uff09\uff1b\n            \u626b\u63cf\u8fdb\u5ea6=\uff08int\uff09\uff08\u9ad8*100.0/65536.0+0.5\uff09\uff1b\n        }\n        if\uff08pines.count\uff08coin.out.scriptpubkey\uff09\uff09\n            \u8f93\u51fa\u7ed3\u679c\u3002\u5b89\u653e\uff08\u94a5\u5319\u3001\u786c\u5e01\uff09\uff1b\n        }\n        \u5149\u6807> NEXT\uff08\uff09\uff1b\n    }\n    \u626b\u63cf\u8fdb\u5ea6=100\uff1b\n    \u56de\u5f52\u771f\u5b9e\uff1b\n}\n\n/**raii\u5bf9\u8c61\u9632\u6b62\u626b\u63cftxout\u96c6\u65f6\u51fa\u73b0\u5e76\u53d1\u95ee\u9898*/\n\nstatic std::mutex g_utxosetscan;\nstatic std::atomic<int> g_scan_progress;\nstatic std::atomic<bool> g_scan_in_progress;\nstatic std::atomic<bool> g_should_abort_scan;\nclass CoinsViewScanReserver\n{\nprivate:\n    bool m_could_reserve;\npublic:\n    explicit CoinsViewScanReserver() : m_could_reserve(false) {}\n\n    bool reserve() {\n        assert (!m_could_reserve);\n        std::lock_guard<std::mutex> lock(g_utxosetscan);\n        if (g_scan_in_progress) {\n            return false;\n        }\n        g_scan_in_progress = true;\n        m_could_reserve = true;\n        return true;\n    }\n\n    ~CoinsViewScanReserver() {\n        if (m_could_reserve) {\n            std::lock_guard<std::mutex> lock(g_utxosetscan);\n            g_scan_in_progress = false;\n        }\n    }\n};\n\nUniValue scantxoutset(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)\n        throw std::runtime_error(\n            RPCHelpMan{\"scantxoutset\",\n                \"\\nEXPERIMENTAL warning: this call may be removed or changed in future releases.\\n\"\n                \"\\nScans the unspent transaction output set for entries that match certain output descriptors.\\n\"\n                \"Examples of output descriptors are:\\n\"\n                \"    addr(<address>)                      Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\\n\"\n                \"    raw(<hex script>)                    Outputs whose scriptPubKey equals the specified hex scripts\\n\"\n                \"    combo(<pubkey>)                      P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\\n\"\n                \"    pkh(<pubkey>)                        P2PKH outputs for the given pubkey\\n\"\n                \"    sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\\n\"\n                \"\\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\\n\"\n                /*\u66f4\u591a\u8def\u5f84\u5143\u7d20\u7531\\\u201c/\\\u201d\u5206\u9694\uff0c\u53ef\u9009\u4ee5\\\u201c/*\\\u201d\uff08\u672a\u786c\u5316\uff09\u6216\\\u201c/*'\\\u201d\u6216\\\u201c/*H\\\u201d\uff08\u786c\u5316\uff09\u7ed3\u5c3e\uff0c\u4ee5\u6307\u5b9a\u6240\u6709\\n\n                \u201c\u672a\u786c\u5316\u6216\u786c\u5316\u7684\u5b50\u5bc6\u94a5\u3002\\n\u201d\n                \u5728\u540e\u4e00\u79cd\u60c5\u51b5\u4e0b\uff0c\u5982\u679c\u4e0e1000\u4e0d\u540c\uff0c\u5219\u9700\u8981\u5728\u4e0b\u9762\u6307\u5b9a\u4e00\u4e2a\u8303\u56f4\u3002\\n\n                \u201c\u6709\u5173\u8f93\u51fa\u63cf\u8ff0\u7b26\u7684\u8be6\u7ec6\u4fe1\u606f\uff0c\u8bf7\u53c2\u9605doc/descriptors.md\u6587\u4ef6\u4e2d\u7684\u6587\u6863\u3002\\n\u201d\uff0c\n                {\n                    \u201caction\u201d\uff0crpcarg:\uff1atype:\uff1astr\uff0c/*opt*/ false, /* default_val */ \"\", \"The action to execute\\n\"\n\n            \"                                      \\\"start\\\" for starting a scan\\n\"\n            \"                                      \\\"abort\\\" for aborting the current scan (returns true when abort was successful)\\n\"\n            \"                                      \\\"status\\\" for progress report (in %) of the current scan\"},\n                    /*canObjects\u201c\uff0crpcarg:\uff1atype:\uff1aarr\uff0c/*opt*/false\uff0c/*default_val*/\u201d\u201c\uff0c\u201c\u626b\u63cf\u5bf9\u8c61\u6570\u7ec4\\n\u201d\n            \u201c\u6bcf\u4e2a\u626b\u63cf\u5bf9\u8c61\u90fd\u662f\u5b57\u7b26\u4e32\u63cf\u8ff0\u7b26\u6216\u5bf9\u8c61\uff1a\u201d\uff0c\n                        {\n                            \u201c\u63cf\u8ff0\u7b26\u201d\uff0crpcarg:\uff1atype:\uff1astr\uff0c/*opt*/ true, /* default_val */ \"\", \"An output descriptor\"},\n\n                            /*\uff0crpcarg:\uff1atype:\uff1aobj\uff0c/*opt*/true\uff0c/*default_val*/\u201d\u201c\uff0c\u201c\u5e26\u6709\u8f93\u51fa\u63cf\u8ff0\u7b26\u548c\u5143\u6570\u636e\u7684\u5bf9\u8c61\u201d\uff0c\n                                {\n                                    \u201cdesc\u201d\uff0crpcarg:\uff1atype:\uff1astr\uff0c/*opt*/ false, /* default_val */ \"\", \"An output descriptor\"},\n\n                                    /*ange\u201c\uff0crpcarg:\uff1atype:\uff1anum\uff0c/*opt*/true\uff0c/*default_val*/\u201d1000\u201c\uff0c\u6700\u591a\u53ef\u6d4f\u89c8\u54ea\u4e2a\u5b50\u7d22\u5f15hd\u94fe\u201d\uff0c\n                                }\n                            }\n                        }\n                        \u201c[\u626b\u63cf\u5bf9\u8c61\u2026]\u201d\uff0c\n                }\n                toSTRIN\uff08\uff09+\n            \u201c\\NESRES:\\N\u201d\n            \u201c{n\u201d\n            \u201c\u672a\u4f7f\u7528\u7684\u201d\uff1a[\\n\u201d\n            \u201c{n\u201d\n            \u201ctxid\\\u201d\uff1a\u201ctransaction id\\\u201d\uff0c\uff08string\uff09\u4e8b\u52a1ID \\n\u201d\n            \u201cvout\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09vout\u503c\\n\u201d\n            \u201cscriptpubkey\\\u201d\uff1a\\\u201cscript\\\u201d\uff0c\uff08string\uff09\u811a\u672c\u952e\\n\u201d\n            \u201cdesc\\\u201d\uff1a\u201cdescriptor\\\u201d\uff0c\uff08string\uff09\u5339\u914d\u7684scriptpubkey\u7684\u4e13\u7528\u63cf\u8ff0\u7b26\\n\u201d\n            \u201camount\u201d\uff1ax.x x x\uff0c\uff08\u6570\u5b57\uff09\u672a\u7528\u8f93\u51fa\u7684\u4ee5\u201c+\u8d27\u5e01\u5355\u4f4d+\u201d\u8868\u793a\u7684\u603b\u91d1\u989d\\n\u201d\n            \u201c\u9ad8\u5ea6\u201d\uff1an\uff0c\uff08\u6570\u5b57\uff09\u672a\u6682\u505c\u4e8b\u52a1\u8f93\u51fa\u7684\u9ad8\u5ea6\\n\u201d\n            \u201c}\\n\u201d\n            \u201c\uff0c\u2026\u2026\u201d\n            \u201c\\\u201d\u603b\u91d1\u989d\\\u201c\uff1ax.x x x\uff0c\uff08\u6570\u5b57\uff09\u4ee5\u201c+\u8d27\u5e01\\\u5355\u4f4d+\u201d\u8868\u793a\u7684\u6240\u6709\u672a\u4f7f\u7528\u8f93\u51fa\u7684\u603b\u91d1\u989d\\n\u201d\n            \u201c\\n\u201d\n        \uff1b\n\n    rpctypecheck\uff08request.params\uff0cunivalue:\uff1avstr\uff0cunivalue:\uff1avarr\uff09\uff1b\n\n    \u5355\u503c\u7ed3\u679c\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n    if\uff08request.params[0].get_str\uff08\uff09=\u201c\u72b6\u6001\u201d\uff09\n        coinsviewscanreserver reserver\uff1b\n        if\uff08reserver.reserve\uff08\uff09\uff09\n            //\u6ca1\u6709\u6b63\u5728\u8fdb\u884c\u7684\u626b\u63cf\n            \u8fd4\u56denullunivalue\uff1b\n        }\n        \u7ed3\u679c.pushkv\uff08\u201c\u8fdb\u5ea6\u201d\uff0cg_scan_progress\uff09\uff1b\n        \u8fd4\u56de\u7ed3\u679c\uff1b\n    else if\uff08request.params[0].get_str\uff08\uff09==\u201cabort\u201d\uff09\n        coinsviewscanreserver reserver\uff1b\n        if\uff08reserver.reserve\uff08\uff09\uff09\n            //\u53ef\u4ee5\u4fdd\u7559\uff0c\u8fd9\u610f\u5473\u7740\u6ca1\u6709\u8fd0\u884c\u626b\u63cf\n            \u8fd4\u56de\u9519\u8bef\uff1b\n        }\n        //\u8bbe\u7f6eabort\u6807\u5fd7\n        G_\u5e94_\u4e2d\u6b62_\u626b\u63cf=\u771f\uff1b\n        \u56de\u5f52\u771f\u5b9e\uff1b\n    else if\uff08request.params[0].get_str\uff08\uff09==\u201c\u5f00\u59cb\u201d\uff09\n        coinsviewscanreserver reserver\uff1b\n        \u5982\u679c\uff08\uff01\uff09reserver.reserve\uff08\uff09\uff09\n            throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201cscan already in progress\uff0cuse action \\\u201dabort \\\u201cor \\\u201dstatus \\\u201c\u201d\uff09\uff1b\n        }\n        std:\uff1aset<cscript>\u9488\uff1b\n        std:\uff1amap<cscript\uff0cstd:\uff1astring>\u63cf\u8ff0\u7b26\uff1b\n        camount total_in=0\uff1b\n\n        //\u5faa\u73af\u626b\u63cf\u5bf9\u8c61\n        for\uff08const univalue&scanObject:request.params[1].get_array\uff08\uff09.getValues\uff08\uff09\uff09\n            std\uff1a\uff1a\u5b57\u7b26\u4e32\u63cf\u8ff0\u5b57\u7b26\u4e32\uff1b\n            int\u8303\u56f4=1000\uff1b\n            if\uff08scanObject.isstr\uff08\uff09\uff09\n                desc_str=scanObject.get_str\uff08\uff09\uff1b\n            else if\uff08scanObject.isObject\uff08\uff09\uff09\n                uni value desc_uni=\u67e5\u627e\u503c\uff08scanObject\uff0c\u201cdesc\u201d\uff09\uff1b\n                if\uff08desc_uni.isnull\uff08\uff09\uff09throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201c\u9700\u8981\u5728\u626b\u63cf\u5bf9\u8c61\u4e2d\u63d0\u4f9b\u63cf\u8ff0\u7b26\u201d\uff09\uff1b\n                desc_str=desc_uni.get_str\uff08\uff09\uff1b\n                uni value range_uni=find_value\uff08scanObject\uff0c\u201crange\u201d\uff09\uff1b\n                \u5982\u679c\uff08\uff01\uff09\u8303\u56f4\u201cuni.isNull\uff08\uff09\uff09\u201d\n                    range=range_uni.get_int\uff08\uff09\uff1b\n                    if\uff08range<0_range>1000000\uff09throw jsonrpcerror\uff08rpc_invalid_parameter\uff0c\u201crange out of range\u201d\uff09\uff1b\n                }\n            }\u5426\u5219{\n                throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201c\u626b\u63cf\u5bf9\u8c61\u5fc5\u987b\u662f\u5b57\u7b26\u4e32\u6216\u5bf9\u8c61\u201d\uff09\uff1b\n            }\n\n            FlatsigningProvider\u63d0\u4f9b\u7a0b\u5e8f\uff1b\n            auto desc=\u89e3\u6790\uff08desc_str\uff0cprovider\uff09\uff1b\n            \u5982\u679c\uff08\uff01\uff09DESC\uff09{\n                throw jsonrpcerror\uff08rpc_invalid_address_or_key\uff0cstrprintf\uff08\u201c\u65e0\u6548\u63cf\u8ff0\u7b26'%s'\u201d\uff0cdesc_str\uff09\uff09\uff1b\n            }\n            \u5982\u679c\uff08\uff01\uff09desc->isrange\uff08\uff09\uff09\u8303\u56f4=0\uff1b\n            \u5bf9\u4e8e\uff08int i=0\uff1bi<=range\uff1b++i\uff09\n                std:\uff1avector<cscript>\u811a\u672c\uff1b\n                \u5982\u679c\uff08\uff01\uff09desc->expand\uff08i\uff0cprovider\uff0cscripts\uff0cprovider\uff09\uff09\n                    throw jsonrpcerror\uff08rpc_invalid_address_or_key\uff0cstrprintf\uff08\u201c\u6ca1\u6709\u79c1\u94a5\uff0c\u65e0\u6cd5\u6d3e\u751f\u811a\u672c\uff1a\u201d%s\u201c\uff0cdesc_str\uff09\uff09\uff1b\n                }\n                \u7528\u4e8e\uff08const auto&script:scripts\uff09\n                    std\uff1a\uff1astring\u63a8\u7406=inferDescriptor\uff08script\uff0cprovider\uff09->toString\uff08\uff09\uff1b\n                    \u9488\u3002\u5b89\u653e\uff08\u811a\u672c\uff09\uff1b\n                    descriptors.emplace\uff08std:\uff1amove\uff08\u811a\u672c\uff09\uff0cstd:\uff1amove\uff08\u63a8\u65ad\uff09\uff09\uff1b\n                }\n            }\n        }\n\n        //\u626b\u63cf\u672a\u6682\u505c\u7684\u4e8b\u52a1\u8f93\u51fa\u96c6\u7684\u8f93\u5165\n        \u672a\u4f7f\u7528\u7684\u5355\u503c\uff08\u5355\u503c\uff1a\uff1avarr\uff09\uff1b\n        std:\uff1avector<ctxout>input_Txos\uff1b\n        std:\uff1amap<coutpoint\uff0ccoin>coins\uff1b\n        G_\u5e94_\u4e2d\u6b62_\u626b\u63cf=\u5047\uff1b\n        G_scan_progress=0\uff1b\n        Int64\u8ba1\u6570=0\uff1b\n        std:\uff1aunique_ptr<ccoinsviewcursor>pcursor\uff1b\n        {\n            \u9501\uff08CSKEMAN\uff09\uff1b\n            flushstatetodisk\uff08\uff09\uff1b\n            pcursor=std:\uff1aunique_ptr<ccoinsViewCursor>\uff08pcoinsDBView->Cursor\uff08\uff09\uff09\uff1b\n            \u65ad\u8a00\uff08pcursor\uff09\uff1b\n        }\n        bool res=findscriptpubkey\uff08g_scan_progress\uff0cg_\u5e94\u4e2d\u6b62_scan\uff0ccount\uff0cpcursor.get\uff08\uff09\uff0c\u9488\uff0c\u786c\u5e01\uff09\uff1b\n        \u7ed3\u679c.pushkv\uff08\u201c\u6210\u529f\u201d\uff0cres\uff09\uff1b\n        \u7ed3\u679c.pushkv\uff08\u201c\u641c\u7d22\u9879\u201d\uff0c\u8ba1\u6570\uff09\uff1b\n\n        \u7528\u4e8e\uff08const auto&it:\u786c\u5e01\uff09\n            const coutpoint&outpoint=it.first\uff1b\n            const coin&coin=it.second\uff1b\n            const ctxout&txo=coin.out\uff1b\n            \u8f93\u5165txos.push-back\uff08txo\uff09\uff1b\n            \u603b_in+=txo.n\u503c\uff1b\n\n            \u672a\u4f7f\u7528\u7684\u5355\u503c\uff08\u5355\u503c\uff1a\uff1avobj\uff09\uff1b\n            unpent.pushkv\uff08\u201ctxid\u201d\uff0coutpoint.hash.gethex\uff08\uff09\uff09\uff1b\n            \u672a\u4f7f\u7528\u7684pushkv\uff08\u201cvout\u201d\uff0c\uff08int32_t\uff09outpoint.n\uff09\uff1b\n            unpent.pushkv\uff08\u201cscriptpubkey\u201d\uff0chexstr\uff08txo.scriptpubkey.begin\uff08\uff09\uff0ctxo.scriptpubkey.end\uff08\uff09\uff09\uff1b\n            unspent.pushkv\uff08\u201cdesc\u201d\uff0c\u63cf\u8ff0\u7b26[txo.scriptpubkey]\uff09\uff1b\n            \u672a\u4f7f\u7528\u7684pushkv\uff08\u201c\u91d1\u989d\u201d\uff0cvaluefromamount\uff08txo.nvalue\uff09\uff09\uff1b\n            \u672a\u4f7f\u7528\u7684pushkv\uff08\u201c\u9ad8\u5ea6\u201d\uff0c\uff08int32-t\uff09coin.nheight\uff09\uff1b\n\n            \u677e\u5f00\u3002\u5411\u540e\u63a8\uff08\u672a\u677e\u5f00\uff09\uff1b\n        }\n        \u7ed3\u679c.pushkv\uff08\u201c\u672a\u4f7f\u7528\u201d\uff0c\u672a\u4f7f\u7528\uff09\uff1b\n        result.pushkv\uff08\u201c\u603b\u91d1\u989d\u201d\uff0cvaluefromamount\uff08\u603b\u91d1\u989d\uff09\uff09\uff1b\n    }\u5426\u5219{\n        throw jsonrpcerror\uff08rpc_invalid_\u53c2\u6570\uff0c\u201c\u65e0\u6548\u547d\u4ee4\u201d\uff09\uff1b\n    }\n    \u8fd4\u56de\u7ed3\u679c\uff1b\n}\n\n//\u5173\u95edclang\u683c\u5f0f\n\u9759\u6001const crpccommand\u547d\u4ee4[]\n//\u7c7b\u522b\u540d\u79f0actor\uff08function\uff09argnames\n  ///\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201c\u83b7\u53d6\u533a\u5757\u94fe\u4fe1\u606f\u201d\uff0c&getblockchaininfo\uff0c\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cgetchaintxstats\u201d\uff0c&getchaintxstats\uff0c\u201cnblocks\u201d\uff0c\u201cblockhash\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cGetBlockStats\u201d\uff0c&GetBlockStats\uff0c\u201chash_or_height\u201d\uff0c\u201cstats\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cGetBestBlockHash\u201d\uff0c&GetBestBlockHash\uff0c\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cGetBlockCount\u201d\uff0c&GetBlockCount\uff0c\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cGetBlock\u201d\uff0c&GetBlock\uff0c\u201cBlockHash\u201d\uff0c\u201c\u8be6\u7ec6\u8be6\u7ec6\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cGetBlockHash\u201d\uff0c&GetBlockHash\uff0c\u201c\u9ad8\u5ea6\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cGetBlockHeader\u201d\uff0c&GetBlockHeader\uff0c\u201cBlockHash\u201d\uff0c\u201c\u8be6\u7ec6\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cgetchaintips\u201d\uff0c&getchaintips\uff0c\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\u3001\u201c\u83b7\u53d6\u96be\u5ea6\u201d&\u83b7\u53d6\u96be\u5ea6\uff0c\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cGetMemPooolancestors\u201d\uff0c&GetMemPooolancestors\uff0c\u201ctxid\u201d\uff0c\u201c\u8be6\u7ec6\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cgetmempooldescendants\u201d\uff0c&getmempooldescendants\uff0c\u201ctxid\u201d\uff0c\u201cverbose\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cgetmempoolentry\u201d\uff0c&getmempoolentry\uff0c\u201ctxid\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cgetmempoolinfo\u201d\uff0c&getmempoolinfo\uff0c\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cgetrawmupool\u201d\uff0c&getrawmupool\uff0c\u201c\u8be6\u7ec6\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cgetXout\u201d\uff0c&getXout\uff0c\u201ctxid\u201d\uff0c\u201cn\u201d\uff0c\u201cinclude\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cgetXoutsetInfo\u201d\uff0c&getXoutsetInfo\uff0c\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cpruneblockchain\u201d\uff0c&pruneblockchain\uff0c\u201cheight\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201c\u5b58\u50a8\u5185\u5b58\u6c60\u201d\uff0c&savemempool\uff0c\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\u3001\u201cverifychain\u201d\u3001&verifychain\u3001\u201cchecklevel\u201d\u3001\u201cnblocks\u201d\uff0c\n\n    \u201c\u533a\u5757\u94fe\u201d\uff0c\u201cPreciousBlock\u201d\uff0c&PreciousBlock\uff0c\u201cBlockHash\u201d\uff0c\n    \u201c\u533a\u5757\u94fe\u201d\u3001\u201cscantStartet\u201d\u3001&scantStartet\u3001\u201c\u64cd\u4f5c\u201d\u3001\u201cscanObjects\u201d\uff0c\n\n    /*\u672a\u5728\u5e2e\u52a9\u4e2d\u663e\u793a*/\n\n    { \"hidden\",             \"invalidateblock\",        &invalidateblock,        {\"blockhash\"} },\n    { \"hidden\",             \"reconsiderblock\",        &reconsiderblock,        {\"blockhash\"} },\n    { \"hidden\",             \"waitfornewblock\",        &waitfornewblock,        {\"timeout\"} },\n    { \"hidden\",             \"waitforblock\",           &waitforblock,           {\"blockhash\",\"timeout\"} },\n    { \"hidden\",             \"waitforblockheight\",     &waitforblockheight,     {\"height\",\"timeout\"} },\n    { \"hidden\",             \"syncwithvalidationinterfacequeue\", &syncwithvalidationinterfacequeue, {} },\n};\n//CLAN\u683c\u5f0f\n\nvoid RegisterBlockchainRPCCommands(CRPCTable &t)\n{\n    for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)\n        t.appendCommand(commands[vcidx].name, &commands[vcidx]);\n}\n", "meta": {"hexsha": "ceb9968c55e84709cd727e77cb9f26cd86fb1a06", "size": 87745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rpc/blockchain.cpp", "max_stars_repo_name": "yinchengtsinghua/BitCoinCppChinese", "max_stars_repo_head_hexsha": "76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:36:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T11:20:25.000Z", "max_issues_repo_path": "src/rpc/blockchain.cpp", "max_issues_repo_name": "yinchengtsinghua/BitCoinCppChinese", "max_issues_repo_head_hexsha": "76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a", "max_issues_repo_licenses": ["MIT"], "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/rpc/blockchain.cpp", "max_forks_repo_name": "yinchengtsinghua/BitCoinCppChinese", "max_forks_repo_head_hexsha": "76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-24T07:48:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T13:34:44.000Z", "avg_line_length": 37.7235597592, "max_line_length": 203, "alphanum_fraction": 0.5792010941, "num_tokens": 28177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1777370439009159}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2004 Decillion Pty(Ltd)\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/money.hpp>\n#include <ql/currencies/exchangeratemanager.hpp>\n#include <ql/math/comparison.hpp>\n#include <boost/format.hpp>\n\nnamespace QuantLib {\n\n    namespace {\n\n        void convertTo(Money& m, const Currency& target) {\n            if (m.currency() != target) {\n                ExchangeRate rate =\n                    ExchangeRateManager::instance().lookup(m.currency(),\n                                                           target);\n                m = rate.exchange(m).rounded();\n            }\n        }\n\n        void convertToBase(Money& m) {\n            const auto & base_currency =\n                Money::Settings::instance().baseCurrency();\n            QL_REQUIRE(!base_currency.empty(), \"no base currency set\");\n            convertTo(m, base_currency);\n        }\n\n    }\n\n    Money& Money::operator+=(const Money& m) {\n        const auto & conversion_type = Settings::instance().conversionType();\n        if (currency_ == m.currency_) {\n            value_ += m.value_;\n        } else if (conversion_type == Money::BaseCurrencyConversion) {\n            convertToBase(*this);\n            Money tmp = m;\n            convertToBase(tmp);\n            *this += tmp;\n        } else if (conversion_type == Money::AutomatedConversion) {\n            Money tmp = m;\n            convertTo(tmp, currency_);\n            *this += tmp;\n        } else {\n            QL_FAIL(\"currency mismatch and no conversion specified\");\n        }\n        return *this;\n    }\n\n    Money& Money::operator-=(const Money& m) {\n        const auto & conversion_type = Settings::instance().conversionType();\n        if (currency_ == m.currency_) {\n            value_ -= m.value_;\n        } else if (conversion_type == Money::BaseCurrencyConversion) {\n            convertToBase(*this);\n            Money tmp = m;\n            convertToBase(tmp);\n            *this -= tmp;\n        } else if (conversion_type == Money::AutomatedConversion) {\n            Money tmp = m;\n            convertTo(tmp, currency_);\n            *this -= tmp;\n        } else {\n            QL_FAIL(\"currency mismatch and no conversion specified\");\n        }\n        return *this;\n    }\n\n    Decimal operator/(const Money& m1, const Money& m2) {\n        const auto & conversion_type =\n            Money::Settings::instance().conversionType();\n        if (m1.currency() == m2.currency()) {\n            return m1.value()/m2.value();\n        } else if (conversion_type == Money::BaseCurrencyConversion) {\n            Money tmp1 = m1;\n            convertToBase(tmp1);\n            Money tmp2 = m2;\n            convertToBase(tmp2);\n            return tmp1/tmp2;\n        } else if (conversion_type == Money::AutomatedConversion) {\n            Money tmp = m2;\n            convertTo(tmp, m1.currency());\n            return m1/tmp;\n        } else {\n            QL_FAIL(\"currency mismatch and no conversion specified\");\n        }\n    }\n\n    bool operator==(const Money& m1, const Money& m2) {\n        const auto & conversion_type =\n            Money::Settings::instance().conversionType();\n        if (m1.currency() == m2.currency()) {\n            return m1.value() == m2.value();\n        } else if (conversion_type == Money::BaseCurrencyConversion) {\n            Money tmp1 = m1;\n            convertToBase(tmp1);\n            Money tmp2 = m2;\n            convertToBase(tmp2);\n            return tmp1 == tmp2;\n        } else if (conversion_type == Money::AutomatedConversion) {\n            Money tmp = m2;\n            convertTo(tmp, m1.currency());\n            return m1 == tmp;\n        } else {\n            QL_FAIL(\"currency mismatch and no conversion specified\");\n        }\n    }\n\n    bool operator<(const Money& m1, const Money& m2) {\n        const auto & conversion_type =\n            Money::Settings::instance().conversionType();\n        if (m1.currency() == m2.currency()) {\n            return m1.value() < m2.value();\n        } else if (conversion_type == Money::BaseCurrencyConversion) {\n            Money tmp1 = m1;\n            convertToBase(tmp1);\n            Money tmp2 = m2;\n            convertToBase(tmp2);\n            return tmp1 < tmp2;\n        } else if (conversion_type == Money::AutomatedConversion) {\n            Money tmp = m2;\n            convertTo(tmp, m1.currency());\n            return m1 < tmp;\n        } else {\n            QL_FAIL(\"currency mismatch and no conversion specified\");\n        }\n    }\n\n    bool operator<=(const Money& m1, const Money& m2) {\n        const auto & conversion_type =\n            Money::Settings::instance().conversionType();\n        if (m1.currency() == m2.currency()) {\n            return m1.value() <= m2.value();\n        } else if (conversion_type == Money::BaseCurrencyConversion) {\n            Money tmp1 = m1;\n            convertToBase(tmp1);\n            Money tmp2 = m2;\n            convertToBase(tmp2);\n            return tmp1 <= tmp2;\n        } else if (conversion_type == Money::AutomatedConversion) {\n            Money tmp = m2;\n            convertTo(tmp, m1.currency());\n            return m1 <= tmp;\n        } else {\n            QL_FAIL(\"currency mismatch and no conversion specified\");\n        }\n    }\n\n    bool close(const Money& m1, const Money& m2, Size n) {\n        const auto & conversion_type =\n            Money::Settings::instance().conversionType();\n        if (m1.currency() == m2.currency()) {\n            return close(m1.value(),m2.value(),n);\n        } else if (conversion_type == Money::BaseCurrencyConversion) {\n            Money tmp1 = m1;\n            convertToBase(tmp1);\n            Money tmp2 = m2;\n            convertToBase(tmp2);\n            return close(tmp1,tmp2,n);\n        } else if (conversion_type == Money::AutomatedConversion) {\n            Money tmp = m2;\n            convertTo(tmp, m1.currency());\n            return close(m1,tmp,n);\n        } else {\n            QL_FAIL(\"currency mismatch and no conversion specified\");\n        }\n    }\n\n    bool close_enough(const Money& m1, const Money& m2, Size n) {\n        const auto & conversion_type =\n            Money::Settings::instance().conversionType();\n        if (m1.currency() == m2.currency()) {\n            return close_enough(m1.value(),m2.value(),n);\n        } else if (conversion_type == Money::BaseCurrencyConversion) {\n            Money tmp1 = m1;\n            convertToBase(tmp1);\n            Money tmp2 = m2;\n            convertToBase(tmp2);\n            return close_enough(tmp1,tmp2,n);\n        } else if (conversion_type == Money::AutomatedConversion) {\n            Money tmp = m2;\n            convertTo(tmp, m1.currency());\n            return close_enough(m1,tmp,n);\n        } else {\n            QL_FAIL(\"currency mismatch and no conversion specified\");\n        }\n    }\n\n\n    std::ostream& operator<<(std::ostream& out, const Money& m) {\n        boost::format fmt(m.currency().format());\n        fmt.exceptions(boost::io::all_error_bits ^\n                       boost::io::too_many_args_bit);\n        return out << fmt % m.rounded().value()\n                          % m.currency().code()\n                          % m.currency().symbol();\n    }\n\n\n    const Money::ConversionType & Money::Settings::conversionType() const\n    {\n        return conversionType_;\n    }\n\n    Money::ConversionType & Money::Settings::conversionType()\n    {\n        return conversionType_;\n    }\n\n    const Currency & Money::Settings::baseCurrency() const\n    {\n        return baseCurrency_;\n    }\n\n    Currency & Money::Settings::baseCurrency()\n    {\n        return baseCurrency_;\n    }\n\n    Money::BaseCurrencyProxy& Money::BaseCurrencyProxy::operator=(const Currency& c) {\n        Money::Settings::instance().baseCurrency() = c;\n        return *this;\n    }\n\n    Money::BaseCurrencyProxy::operator Currency() const {\n        return Money::Settings::instance().baseCurrency();\n    }\n\n    Money::ConversionTypeProxy& Money::ConversionTypeProxy::operator=(ConversionType t) {\n        Money::Settings::instance().conversionType() = t;\n        return *this;\n    }\n\n    Money::ConversionTypeProxy::operator Money::ConversionType() const {\n        return Money::Settings::instance().conversionType();\n    }\n\n    Money::BaseCurrencyProxy Money::baseCurrency;\n    Money::ConversionTypeProxy Money::conversionType;\n\n\n}\n", "meta": {"hexsha": "929b9a29b230a049ea3b54f642494dc351adf2d4", "size": 9033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/money.cpp", "max_stars_repo_name": "jiangjiali/QuantLib", "max_stars_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3358.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T02:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:42:47.000Z", "max_issues_repo_path": "ql/money.cpp", "max_issues_repo_name": "jiangjiali/QuantLib", "max_issues_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 965.0, "max_issues_repo_issues_event_min_datetime": "2015-12-21T10:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:47:00.000Z", "max_forks_repo_path": "ql/money.cpp", "max_forks_repo_name": "jiangjiali/QuantLib", "max_forks_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1663.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:58:29.000Z", "avg_line_length": 34.7423076923, "max_line_length": 89, "alphanum_fraction": 0.5678069301, "num_tokens": 1989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.17773704037625168}}
{"text": "#ifndef QUBUS_STATIC_SCHEDULE_HPP\n#define QUBUS_STATIC_SCHEDULE_HPP\n\n#include <qubus/affine_constraints.hpp>\n\n#include <qubus/IR/expression.hpp>\n#include <qubus/IR/macro_expr.hpp>\n#include <qubus/IR/variable_declaration.hpp>\n\n#include <qubus/isl/map.hpp>\n#include <qubus/isl/schedule_node.hpp>\n\n#include <qubus/util/optional_ref.hpp>\n\n#include <boost/optional.hpp>\n\n#include <map>\n#include <memory>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace qubus\n{\n\nstruct static_schedule_statement\n{\n    static_schedule_statement(std::string name, const expression& expr);\n\n    std::string name;\n    std::reference_wrapper<const expression> expr;\n};\n\nclass static_schedule_context\n{\npublic:\n    explicit static_schedule_context(std::shared_ptr<affine_expr_context> affine_ctx_);\n\n    static_schedule_statement& register_statement(const expression& stmt);\n\n    affine_expr_context& affine_ctx();\n\nprivate:\n    std::shared_ptr<affine_expr_context> affine_ctx_;\n\n    std::size_t free_statement_id_ = 0;\n    std::unordered_map<std::string, static_schedule_statement> statement_table_;\n};\n\nclass static_schedule\n{\npublic:\n    explicit static_schedule(std::unordered_map<const expression*, isl::schedule_node> ir_schedule_map_);\n\n    const isl::schedule_node& get_schedule_node(const expression& expr) const;\n\nprivate:\n    std::unordered_map<const expression*, isl::schedule_node> ir_schedule_map_;\n};\n}\n\n#endif\n", "meta": {"hexsha": "1a0cadddd388ccce5dc9497d74b4af8595212956", "size": 1457, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qubus/include/qubus/static_schedule.hpp", "max_stars_repo_name": "qubusproject/Qubus", "max_stars_repo_head_hexsha": "0feb8d6df00459c5af402545dbe7c82ee3ec4b7c", "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": "qubus/include/qubus/static_schedule.hpp", "max_issues_repo_name": "qubusproject/Qubus", "max_issues_repo_head_hexsha": "0feb8d6df00459c5af402545dbe7c82ee3ec4b7c", "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": "qubus/include/qubus/static_schedule.hpp", "max_forks_repo_name": "qubusproject/Qubus", "max_forks_repo_head_hexsha": "0feb8d6df00459c5af402545dbe7c82ee3ec4b7c", "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": 22.4153846154, "max_line_length": 105, "alphanum_fraction": 0.7776252574, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.17747665467161491}}
{"text": "#pragma once\n\n#include <string>\n\n#include <boost/endian/conversion.hpp>\n#include <boost/uuid/uuid.hpp>\n\n#include <common/bits.hpp>\n#include <common/buffer.hpp>\n#include <common/macros.hpp>\n#include <common/span.hpp>\n#include <common/traits.hpp>\n#include <common/types.hpp>\n\nnamespace vitamine::proxyd\n{\n\tnamespace detail\n\t{\n\t\tconstexpr UInt VARINT32_MAX_ENCODED_SIZE = ceildiv(32, 7);\n\n\t\tinline\n\t\tUInt wireSizeVarInt32(Int32 value)\n\t\t{\n\t\t\tswitch(clz(value))\n\t\t\t{\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\tcase 2:\n\t\t\tcase 3:\n\t\t\t\treturn 5;\n\n\t\t\tcase 4:\n\t\t\tcase 5:\n\t\t\tcase 6:\n\t\t\tcase 7:\n\t\t\tcase 8:\n\t\t\tcase 9:\n\t\t\tcase 10:\n\t\t\t\treturn 4;\n\n\t\t\tcase 11:\n\t\t\tcase 12:\n\t\t\tcase 13:\n\t\t\tcase 14:\n\t\t\tcase 15:\n\t\t\tcase 16:\n\t\t\tcase 17:\n\t\t\t\treturn 3;\n\n\t\t\tcase 18:\n\t\t\tcase 19:\n\t\t\tcase 20:\n\t\t\tcase 21:\n\t\t\tcase 22:\n\t\t\tcase 23:\n\t\t\tcase 24:\n\t\t\t\treturn 2;\n\n\t\t\tcase 25:\n\t\t\tcase 26:\n\t\t\tcase 27:\n\t\t\tcase 28:\n\t\t\tcase 29:\n\t\t\tcase 30:\n\t\t\tcase 31:\n\t\t\tcase 32:\n\t\t\t\treturn 1;\n\n\t\t\tdefault: UNREACHABLE\n\t\t\t}\n\t\t}\n\n\t\tinline\n\t\tUInt encodeVarInt32(UInt8* buf, Int32 value)\n\t\t{\n\t\t\tauto v = (UInt32)value;\n\n\t\t\tswitch(clz(value))\n\t\t\t{\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\tcase 2:\n\t\t\tcase 3:\n\t\t\t\tbuf[0] = 0x80u | v;\n\t\t\t\tbuf[1] = 0x80u | v >> 7u;\n\t\t\t\tbuf[2] = 0x80u | v >> 14u;\n\t\t\t\tbuf[3] = 0x80u | v >> 21u;\n\t\t\t\tbuf[4] =         v >> 28u;\n\t\t\t\treturn 5;\n\n\t\t\tcase 4:\n\t\t\tcase 5:\n\t\t\tcase 6:\n\t\t\tcase 7:\n\t\t\tcase 8:\n\t\t\tcase 9:\n\t\t\tcase 10:\n\t\t\t\tbuf[0] = 0x80u | v;\n\t\t\t\tbuf[1] = 0x80u | v >> 7u;\n\t\t\t\tbuf[2] = 0x80u | v >> 14u;\n\t\t\t\tbuf[3] =         v >> 21u;\n\t\t\t\treturn 4;\n\n\t\t\tcase 11:\n\t\t\tcase 12:\n\t\t\tcase 13:\n\t\t\tcase 14:\n\t\t\tcase 15:\n\t\t\tcase 16:\n\t\t\tcase 17:\n\t\t\t\tbuf[0] = 0x80u | v;\n\t\t\t\tbuf[1] = 0x80u | v >> 7u;\n\t\t\t\tbuf[2] =         v >> 14u;\n\t\t\t\treturn 3;\n\n\t\t\tcase 18:\n\t\t\tcase 19:\n\t\t\tcase 20:\n\t\t\tcase 21:\n\t\t\tcase 22:\n\t\t\tcase 23:\n\t\t\tcase 24:\n\t\t\t\tbuf[0] = 0x80u | v;\n\t\t\t\tbuf[1] =         v >> 7u;\n\t\t\t\treturn 2;\n\n\t\t\tcase 25:\n\t\t\tcase 26:\n\t\t\tcase 27:\n\t\t\tcase 28:\n\t\t\tcase 29:\n\t\t\tcase 30:\n\t\t\tcase 31:\n\t\t\tcase 32:\n\t\t\t\tbuf[0] = v;\n\t\t\t\treturn 1;\n\n\t\t\tdefault: UNREACHABLE\n\t\t\t}\n\t\t}\n\t}\n\n\tinline\n\tvoid serializeVarInt(Buffer& buffer, Int32 value)\n\t{\n\t\tUInt8 buf[detail::VARINT32_MAX_ENCODED_SIZE];\n\t\tauto length = detail::encodeVarInt32(buf, value);\n\t\tbuffer.write(buf, length);\n\t}\n\n\ttemplate <typename T>\n\tvoid serializeInt(Buffer& buffer, T value)\n\t{\n\t\tboost::endian::native_to_big_inplace(value);\n\t\tbuffer.write(&value, sizeof value);\n\t}\n\n\tinline\n\tvoid serializeBool(Buffer& buffer, bool value)\n\t{\n\t\tserializeInt(buffer, (UInt8)value);\n\t}\n\n\ttemplate <typename T>\n\tvoid serializeFloat(Buffer& buffer, T value)\n\t{\n\t\ttypename UIntForSize<sizeof(T)>::Type intval;\n\t\tstd::memcpy(&intval, &value, sizeof value);\n\t\tboost::endian::native_to_big_inplace(intval);\n\t\tbuffer.write(&intval, sizeof intval);\n\t}\n\n\tinline\n\tvoid serializeString(Buffer& buffer, Span<Char8 const> str)\n\t{\n\t\tserializeVarInt(buffer, str.size());\n\t\tbuffer.write(str.data(), str.size());\n\t}\n\n\tinline\n\tvoid serializeString(Buffer& buffer, std::string const& str)\n\t{\n\t\tserializeString(buffer, Span<Char8 const>(str.data(), str.size()));\n\t}\n\n\tinline\n\tvoid serializeBytes(Buffer& buffer, Span<UInt8 const> data)\n\t{\n\t\tbuffer.write(data.data(), data.size());\n\t}\n\n\tinline\n\tvoid serializeUuid(Buffer& buffer, boost::uuids::uuid uuid)\n\t{\n\t\tUInt64 lo, hi;\n\t\tstd::memcpy(&lo, uuid.begin(),     8);\n\t\tstd::memcpy(&hi, uuid.begin() + 8, 8);\n\t\tserializeInt(buffer, hi);\n\t\tserializeInt(buffer, lo);\n\t}\n}\n", "meta": {"hexsha": "0d75332de8f41abf81195b0b51ebb81eebec6ca2", "size": 3354, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/proxyd/serialize.hpp", "max_stars_repo_name": "mgrech/vitamine", "max_stars_repo_head_hexsha": "d2fab653a0146b0ad9eb40d62213c968af2a100b", "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/proxyd/serialize.hpp", "max_issues_repo_name": "mgrech/vitamine", "max_issues_repo_head_hexsha": "d2fab653a0146b0ad9eb40d62213c968af2a100b", "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/proxyd/serialize.hpp", "max_forks_repo_name": "mgrech/vitamine", "max_forks_repo_head_hexsha": "d2fab653a0146b0ad9eb40d62213c968af2a100b", "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": 16.603960396, "max_line_length": 69, "alphanum_fraction": 0.5963029219, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1772718628468399}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <server_clib/blowfish.h>\n#include <iostream>\n#include <algorithm>\n\nnamespace server_clib {\n\nBOOST_AUTO_TEST_SUITE(blowfish_tests)\n\nBOOST_AUTO_TEST_CASE(encryption_base_author_check)\n{\n    uint32_t L = 1, R = 2;\n    blowfish_ctx_t ctx;\n\n    blowfish_init(&ctx, (uint8_t*)\"TESTKEY\", 7);\n    blowfish_encrypt_chunk(&ctx, &L, &R);\n    BOOST_REQUIRE(L == 0xDF333FD2L);\n    BOOST_REQUIRE(R == 0x30A71BB4L);\n\n    blowfish_decrypt_chunk(&ctx, &L, &R);\n    BOOST_REQUIRE(L == 1);\n    BOOST_REQUIRE(R == 2);\n}\n\nBOOST_AUTO_TEST_CASE(chunk_encryption_check)\n{\n    const uint32_t initial_L = 12;\n    const uint32_t initial_R = 31;\n\n    uint32_t L = initial_L, R = initial_R;\n    blowfish_ctx_t ctx;\n\n    char key[] = \"password\";\n    char wrong_key[] = \"PASSWORD\";\n\n    BOOST_REQUIRE(blowfish_init(&ctx, (uint8_t*)key, sizeof(key)));\n    BOOST_REQUIRE(blowfish_encrypt_chunk(&ctx, &L, &R));\n    BOOST_REQUIRE(blowfish_destroy(&ctx));\n    BOOST_REQUIRE_EQUAL(ctx.P[0], 0);\n    BOOST_REQUIRE_EQUAL(ctx.S[0][0], 0);\n\n    uint32_t enc_L = L, enc_R = R;\n\n    BOOST_REQUIRE(blowfish_init(&ctx, (uint8_t*)wrong_key, sizeof(wrong_key)));\n    BOOST_REQUIRE(blowfish_decrypt_chunk(&ctx, &L, &R));\n\n    BOOST_REQUIRE_NE(L, initial_L);\n    BOOST_REQUIRE_NE(R, initial_R);\n\n    L = enc_L;\n    R = enc_R;\n\n    BOOST_REQUIRE(blowfish_init(&ctx, (uint8_t*)key, sizeof(key)));\n    BOOST_REQUIRE(blowfish_decrypt_chunk(&ctx, &L, &R));\n    BOOST_REQUIRE(blowfish_destroy(&ctx));\n    BOOST_REQUIRE_EQUAL(ctx.P[0], 0);\n    BOOST_REQUIRE_EQUAL(ctx.S[0][0], 0);\n\n    BOOST_REQUIRE_EQUAL(L, initial_L);\n    BOOST_REQUIRE_EQUAL(R, initial_R);\n}\n\nBOOST_AUTO_TEST_CASE(data_encryption_check)\n{\n    const char input_data[] = \"function1 function2 function3\"\n                              \"function4 function5 function6\";\n    char key[] = \"password\";\n    blowfish_ctx_t ctx;\n\n    auto enc_sz = blowfish_get_stream_output_length(sizeof(input_data));\n    BOOST_REQUIRE_GE(enc_sz, sizeof(input_data));\n    BOOST_REQUIRE_EQUAL(enc_sz % blowfish_get_min_chunk_length(), 0);\n\n    unsigned char* enc_data = (unsigned char*)alloca(enc_sz);\n    BOOST_REQUIRE(blowfish_init(&ctx, (uint8_t*)key, sizeof(key)));\n    BOOST_REQUIRE_EQUAL(\n        blowfish_stream_encrypt(&ctx, (const unsigned char*)input_data, sizeof(input_data), enc_data, enc_sz), enc_sz);\n    BOOST_REQUIRE(blowfish_destroy(&ctx));\n\n    BOOST_REQUIRE(blowfish_init(&ctx, (uint8_t*)key, sizeof(key)));\n    unsigned char* dec_data = (unsigned char*)alloca(enc_sz);\n    BOOST_REQUIRE_EQUAL(blowfish_stream_decrypt(&ctx, enc_data, enc_sz, dec_data, enc_sz), enc_sz);\n    BOOST_REQUIRE(blowfish_destroy(&ctx));\n\n    BOOST_REQUIRE_EQUAL(std::string{ input_data }, std::string{ (char*)dec_data });\n}\n\nBOOST_AUTO_TEST_CASE(data_stream_encryption_check)\n{\n    const char input_data[] = \"function1 function2 function3\"\n                              \"function4 function5 function6\";\n    char key[] = \"password\";\n    blowfish_ctx_t ctx;\n    size_t chuck_sz = sizeof(input_data) / 3;\n\n    BOOST_REQUIRE_GE(chuck_sz, blowfish_get_min_chunk_length());\n\n    BOOST_REQUIRE(blowfish_init(&ctx, (uint8_t*)key, sizeof(key)));\n\n    size_t rest_sz = sizeof(input_data);\n    std::vector<unsigned char> encoded;\n    encoded.reserve(blowfish_get_stream_output_length(rest_sz));\n    std::vector<unsigned char> chunk;\n    chunk.resize(chuck_sz, 0);\n    const unsigned char* p_in_pos = reinterpret_cast<const unsigned char*>(input_data);\n    while (rest_sz > 0)\n    {\n        auto chunk_actial_in = std::min(chuck_sz, rest_sz);\n        auto chunk_actial_out = std::max(chunk_actial_in, static_cast<size_t>(blowfish_get_min_chunk_length()));\n        auto r = blowfish_stream_encrypt(&ctx, p_in_pos, chunk_actial_in, &chunk[0], chunk_actial_out);\n        BOOST_REQUIRE_GT(r, 0);\n        p_in_pos += r;\n        std::copy_n(begin(chunk), r, std::back_inserter(encoded));\n        rest_sz -= (r <= rest_sz) ? r : rest_sz;\n    }\n    BOOST_REQUIRE(blowfish_destroy(&ctx));\n\n    {\n        BOOST_REQUIRE(blowfish_init(&ctx, (uint8_t*)key, sizeof(key)));\n        unsigned char* dec_data = (unsigned char*)alloca(encoded.size());\n        BOOST_REQUIRE_EQUAL(blowfish_stream_decrypt(&ctx, &encoded[0], encoded.size(), dec_data, encoded.size()),\n                            encoded.size());\n        BOOST_REQUIRE(blowfish_destroy(&ctx));\n\n        BOOST_REQUIRE_EQUAL(std::string{ input_data }, std::string{ (char*)dec_data });\n    }\n\n    BOOST_REQUIRE(blowfish_init(&ctx, (uint8_t*)key, sizeof(key)));\n    std::vector<unsigned char> decoded;\n    decoded.reserve(encoded.size());\n    rest_sz = encoded.size();\n    size_t ci = 0;\n    while (rest_sz > 0)\n    {\n        auto chunk_actial_in = std::min(chuck_sz, rest_sz);\n        auto chunk_actial_out = std::max(chunk_actial_in, static_cast<size_t>(blowfish_get_min_chunk_length()));\n        auto r = blowfish_stream_decrypt(&ctx, &encoded[ci], chunk_actial_in, &chunk[0], chunk_actial_out);\n        BOOST_REQUIRE_GT(r, 0);\n        ci += r;\n        std::copy_n(begin(chunk), r, std::back_inserter(decoded));\n        rest_sz -= (r <= rest_sz) ? r : rest_sz;\n    }\n\n    BOOST_REQUIRE_EQUAL(std::string{ input_data }, std::string{ (char*)&decoded[0] });\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n} // namespace server_clib\n", "meta": {"hexsha": "7433708bf9cac409c68ebaac04c40e7b18c8ab63", "size": 5272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/blowfish_tests.cpp", "max_stars_repo_name": "romualdo-bar/barbacoa-server-clib", "max_stars_repo_head_hexsha": "65591dbf5b7d29a22f96654df83b1ee1bb0554fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T21:00:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T21:00:17.000Z", "max_issues_repo_path": "tests/blowfish_tests.cpp", "max_issues_repo_name": "TiamaT1977/barbacoa-server-clib", "max_issues_repo_head_hexsha": "65591dbf5b7d29a22f96654df83b1ee1bb0554fd", "max_issues_repo_licenses": ["MIT"], "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/blowfish_tests.cpp", "max_forks_repo_name": "TiamaT1977/barbacoa-server-clib", "max_forks_repo_head_hexsha": "65591dbf5b7d29a22f96654df83b1ee1bb0554fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-16T13:25:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T13:25:54.000Z", "avg_line_length": 35.1466666667, "max_line_length": 119, "alphanum_fraction": 0.6826631259, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17727186284683988}}
{"text": "/*!\n * *****************************************************************************\n *   \\file faceDepthMapFrom3D_main.cpp\n *   \\author moennen\n *   \\brief\n *   \\date 2018-03-19\n *   *****************************************************************************/\n\n#include \"utils/gl_utils.h\"\n#include \"utils/gl_utils.inline.h\"\n#include \"utils/imgFileLst.h\"\n\n#include \"SDL2/SDL.h\"\n#include \"SDL2/SDL_opengl.h\"\n\n// opengl\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n\n// opencv\n#include \"utils/cv_utils.h\"\n\n// face detector / models\n#include \"externals/face/beFaceMModel.h\"\n#include \"externals/face/beFaceModelInstance.h\"\n\n#include <boost/filesystem.hpp>\n\n#include <memory>\n#include <random>\n#include <iostream>\n\nusing namespace std;\nusing namespace cv;\nusing namespace glm;\nusing namespace boost;\n\nnamespace\n{\nstd::random_device rd{};\nstd::mt19937 rs_gen{rd()};\n\nvoid init()\n{\n   glClearColor( 0.0, 0.0, 0.0, 0.0 );\n   glMatrixMode( GL_PROJECTION );\n   glLoadIdentity();\n   // glOrtho( 0.0, windowSz.x, windowSz.y, 0.0, -10000.0, 10000.0 );\n   // glEnable( GL_BLEND );\n   glEnable( GL_DEPTH_TEST );\n   // glFrontFace( GL_CW );\n   glEnable( GL_TEXTURE_2D );\n   glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n}\n\nvoid drawFaceModel(\n    const gl_utils::TriMeshBuffer& mdFace,\n    const glm::mat4& p,\n    const glm::mat4& mv,\n    const glm::vec3& lightPos,\n    const glm::vec3& lightCol,\n    const float ambient )\n{\n   static gl_utils::RenderProgram faceShader;\n\n   static GLint uniMVP = -1;\n   static GLint uniMV = -1;\n   static GLint uniMVN = -1;\n   static GLint uniLightPos = -1;\n   static GLint uniLightCol = -1;\n   static GLint uniAmbient = -1;\n\n   if ( faceShader._id == -1 )\n   {\n      faceShader.load(\n          \"/mnt/p4/avila/moennen_wkspce/sceneIllEst/faceDepthMapFrom3DMM/shaders/face_frag.glsl\",\n          \"/mnt/p4/avila/moennen_wkspce/sceneIllEst/faceDepthMapFrom3DMM/shaders/face_vtx.glsl\" );\n      uniMVP = faceShader.getUniform( \"mvp\" );\n      uniMV = faceShader.getUniform( \"mv\" );\n      uniMVN = faceShader.getUniform( \"mvn\" );\n      uniLightPos = faceShader.getUniform( \"lightPos\" );\n      uniLightCol = faceShader.getUniform( \"lightColor\" );\n      uniAmbient = faceShader.getUniform( \"ambient\" );\n   }\n\n   faceShader.activate();\n\n   glUniformMatrix4fv( uniMV, 1, 0, value_ptr( mv ) );\n\n   const mat4 mvp = p * mv;\n   glUniformMatrix4fv( uniMVP, 1, 0, value_ptr( mvp ) );\n   const mat4 mvt = transpose( inverse( mv ) );\n   glUniformMatrix4fv( uniMVN, 1, 0, value_ptr( mvt ) );\n   glUniform3fv( uniLightPos, 1, value_ptr( lightPos ) );\n   glUniform3fv( uniLightCol, 1, value_ptr( lightCol ) );\n\n   glUniform1f( uniAmbient, ambient );\n\n   mdFace.draw();\n\n   faceShader.deactivate();\n}\n\nvoid draw( GLuint tex, size_t w, size_t h )\n{\n   // Bind Texture\n   glBindTexture( GL_TEXTURE_2D, tex );\n\n   GLfloat Vertices[] = {(float)0,\n                         (float)0,\n                         0,\n                         (float)0 + w,\n                         (float)0,\n                         0,\n                         (float)0 + (float)w,\n                         (float)0 + (float)h,\n                         0,\n                         (float)0,\n                         (float)0 + (float)h,\n                         0};\n   GLfloat TexCoord[] = {\n       0,\n       0,\n       1,\n       0,\n       1,\n       1,\n       0,\n       1,\n   };\n   GLubyte indices[] = {0,\n                        1,\n                        2,  // first triangle (bottom left - top left - top right)\n                        0,\n                        2,\n                        3};  // second triangle (bottom left - top right - bottom right)\n\n   glEnableClientState( GL_VERTEX_ARRAY );\n   glVertexPointer( 3, GL_FLOAT, 0, Vertices );\n\n   glEnableClientState( GL_TEXTURE_COORD_ARRAY );\n   glTexCoordPointer( 2, GL_FLOAT, 0, TexCoord );\n\n   glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices );\n\n   glDisableClientState( GL_TEXTURE_COORD_ARRAY );\n   glDisableClientState( GL_VERTEX_ARRAY );\n\n   glBindTexture( GL_TEXTURE_2D, 0 );\n}\n\nvoid getOutUVS(\n    const vector<vec2>& iuvs,\n    const vector<uvec3>& ivecIdx,\n    const glm::uvec3* ovecIdx,\n    glm::vec2* ouvs )\n{\n   for ( size_t f = 0; f < ivecIdx.size(); ++f )\n   {\n      ouvs[ovecIdx[f].x] = iuvs[ivecIdx[f].x];\n      ouvs[ovecIdx[f].y] = iuvs[ivecIdx[f].y];\n      ouvs[ovecIdx[f].z] = iuvs[ivecIdx[f].z];\n   }\n}\n}\nconst string keys =\n    \"{help h usage ? |         | print this message   }\"\n    \"{@faceModel     |         | face detection model }\"\n    \"{@faceInstLst   |         | face model instance files list}\"\n    \"{@outDir        |         | output directories   }\";\n\nint main( int argc, char* argv[] )\n{\n   CommandLineParser parser( argc, argv, keys );\n   if ( parser.has( \"help\" ) )\n   {\n      parser.printMessage();\n      return ( 0 );\n   }\n\n   // Load background images\n   ImgNFileLst instLst(2, parser.get<string>( \"@faceInstLst\" ).c_str(), \"\" );\n   if ( instLst.size() == 0 )\n   {\n      cerr << \"Invalid face instances list : \" << parser.get<string>( \"@faceInstLst\" ) << endl;\n      return -1;\n   }\n\n   //------------------------------------------------------------------------- Load model\n   //\n   const string BEfaceModelBin = parser.get<string>( \"@faceModel\" );\n   BEFaceMModel beFaceMMd( BEfaceModelBin.c_str() );\n   if ( !beFaceMMd.initialized() )\n   {\n      std::cerr << \"Cannot import model : \" << BEfaceModelBin << std::endl;\n      return -1;\n   }\n\n   uvec2 imgSz( 256, 256 );\n\n   // SDL init\n   SDL_Init( SDL_INIT_EVERYTHING );\n   SDL_Window* window = SDL_CreateWindow(\n       \"renderFaceMaps\",\n       SDL_WINDOWPOS_CENTERED,\n       SDL_WINDOWPOS_CENTERED,\n       imgSz.x,\n       imgSz.y,\n       SDL_WINDOW_OPENGL );\n   SDL_GLContext glCtx = SDL_GL_CreateContext( window );\n\n   // GLEW init\n   GLenum err = glewInit();\n   if ( GLEW_OK != err )\n   {\n      cerr << \"Error: \" << glewGetErrorString( err ) << endl;\n      return -1;\n   }\n\n   // Common data alloc\n   vector<vec3> vecVtx( BEFaceMModel::NumVertices, vec3( 0.0f ) );\n   vector<vec3> vtxCol( BEFaceMModel::NumVertices, vec3( 0.0f ) );\n   vector<vec3> vtxNorm( BEFaceMModel::NumVertices, vec3( 0.0f ) );\n\n   // Out root path\n   const filesystem::path outRootPath( parser.get<string>( \"@outDir\" ) );\n\n   // Constant render params\n   const float ambient(1.0);\n   const vec3 lightPos(0.0);\n   const vec3 lightCol = vec3(0.1);\n\n   for ( int s = 0; s < instLst.size(); ++s )\n   {\n      Mat instImg = cv_utils::imread32FC4( instLst.filePath(s,0) );\n      if ( instImg.empty() )\n      {\n         std::cerr << \"Cannot load instance image : \" << instLst.filePath(s,0) << std::endl;\n         continue;\n      }\n      imgSz = uvec2( instImg.cols, instImg.rows );\n\n      BEFaceMModelInstance instModel = { instLst.filePath(s,1) };\n      if ( !instModel.initialized() )\n      {\n         std::cerr << \"Cannot load instance model : \" <<  instLst.filePath(s,1) << std::endl;\n         continue;\n      }\n\n      // Set the render buffers\n      gl_utils::RenderTarget renderTarget( imgSz );\n      gl_utils::Texture<gl_utils::RGBA_32FP> faceColorTex( imgSz );\n      gl_utils::Texture<gl_utils::RGBA_32FP> faceUVDepthTex( imgSz );\n      gl_utils::Texture<gl_utils::RGBA_32FP> faceNormalsTex( imgSz );\n      GLuint rTex[3] = {faceColorTex.id, faceUVDepthTex.id, faceNormalsTex.id};\n\n      renderTarget.bind( 3, &rTex[0] );\n      glClear( GL_COLOR_BUFFER_BIT );\n      glClear( GL_DEPTH_BUFFER_BIT );\n      renderTarget.unbind();\n\n      // Load background\n      gl_utils::uploadToTexture( faceColorTex, instImg.ptr() );\n\n      // Create the face geometry\n      beFaceMMd.get(\n          instModel.getShapeCoeffs(),\n          instModel.getExpCoeffs(),\n          instModel.getTexCoeffs(),\n          glm::value_ptr( vecVtx[0] ),\n          glm::value_ptr( vtxCol[0] ),\n          false );\n\n      gl_utils::TriMeshBuffer mdFaceA;\n\n      // vertices\n      mdFaceA.load(\n          vecVtx.size(),\n          vecVtx.empty() ? nullptr : &vecVtx[0],\n          BEFaceMModel::NumFaces,\n          beFaceMMd.getFaces() );\n\n      // color\n      mdFaceA.loadAttrib( 3, value_ptr( vtxCol[0] ) );\n\n      // normals\n      gl_utils::computeNormals(\n          BEFaceMModel::NumFaces,\n          beFaceMMd.getFaces(),\n          BEFaceMModel::NumVertices,\n          &vecVtx[0],\n          &vtxNorm[0] );\n      mdFaceA.loadAttrib( 3, value_ptr( vtxNorm[0] ) );\n\n      // uvs\n      mdFaceA.loadAttrib( 2, value_ptr( beFaceMMd.getUVs()[0] ) );\n\n      //  Camera projection\n      const mat4 camProj = glm::ortho(0.0f, static_cast<float>(imgSz.x), \n        static_cast<float>(imgSz.y), 0.0f, -10000.0f, 10000.0f );\n             \n      // Model view\n      const mat4 modelView;// = instModel.getPose();\n\n      // Draw the face\n      renderTarget.bind( 3, &rTex[0] );\n\n      glEnable( GL_DEPTH_TEST );\n      glEnable( GL_CULL_FACE );\n      glCullFace( GL_BACK );\n\n      drawFaceModel( mdFaceA, camProj, modelView, lightPos, lightCol, ambient );\n\n      renderTarget.unbind();\n\n      // upload and write the maps\n      char sampleId[16];\n      sprintf( sampleId, \"%08d_\", s );\n      const string outBasename( sampleId );\n      const string outBasenameFull = ( outRootPath / filesystem::path( sampleId ) ).string();\n\n      Mat faceColorImg( faceColorTex.sz.y, faceColorTex.sz.x, CV_32FC4 );\n      Mat faceUVDepthImg( faceUVDepthTex.sz.y, faceUVDepthTex.sz.x, CV_32FC4 );\n      Mat faceNormalsImg( faceNormalsTex.sz.y, faceNormalsTex.sz.x, CV_32FC4 );\n      if ( gl_utils::readbackTexture( faceColorTex, faceColorImg.data ) &&\n           gl_utils::readbackTexture( faceUVDepthTex, faceUVDepthImg.data ) &&\n           gl_utils::readbackTexture( faceNormalsTex, faceNormalsImg.data ) )\n      {\n         cvtColor( faceColorImg, faceColorImg, cv::COLOR_RGBA2BGR );\n         cvtColor( faceUVDepthImg, faceUVDepthImg, cv::COLOR_RGBA2BGR );\n         cvtColor( faceNormalsImg, faceNormalsImg, cv::COLOR_RGBA2BGR );\n\n         imwrite( outBasenameFull + \"c.png\", faceColorImg * 255.0 );\n         imwrite( outBasenameFull + \"uvd.exr\", faceUVDepthImg );\n         imwrite( outBasenameFull + \"n.exr\", faceNormalsImg );\n\n         std::cout << outBasename + \"c.png \" << outBasename + \"uvd.exr \" << outBasename + \"n.exr\"\n                   << std::endl;\n\n         imshow( \"color\", faceColorImg );\n         imshow( \"uvdepth\", faceUVDepthImg );\n         imshow( \"normals\", faceNormalsImg );\n         waitKey( 0 );\n      }\n   }\n\n   SDL_Quit();\n\n   return ( 0 );\n}", "meta": {"hexsha": "b756ba21f4362c0f6208da08b4d96c6ddf29a221", "size": 10425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "faceDepthMapFrom3DMM/renderFaceInstMaps.cpp", "max_stars_repo_name": "moennen/sceneIllEst", "max_stars_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-04T09:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-17T07:02:49.000Z", "max_issues_repo_path": "faceDepthMapFrom3DMM/renderFaceInstMaps.cpp", "max_issues_repo_name": "moennen/sceneIllEst", "max_issues_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "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": "faceDepthMapFrom3DMM/renderFaceInstMaps.cpp", "max_forks_repo_name": "moennen/sceneIllEst", "max_forks_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "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.7857142857, "max_line_length": 98, "alphanum_fraction": 0.5826378897, "num_tokens": 2984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.17727185570655818}}
{"text": "#include <ndt_fuser/ndt_fuser_hmt.h>\n#include <ndt_offline/VelodyneBagReader.h>\n#include <ndt_generic/eigen_utils.h>\n#include <ndt_generic/pcl_utils.h>\n// PCL specific includes\n#include <pcl/conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <ndt_map/ndt_map.h>\n#include <ndt_map/ndt_cell.h>\n#include <ndt_map/pointcloud_utils.h>\n#include <tf_conversions/tf_eigen.h>\n#include <cstdio>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <fstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <dirent.h>\n#include <algorithm>\n#include <boost/program_options.hpp>\n#include \"graph_map/graph_map_fuser.h\"\n#include \"graph_map/ndt/ndt_map_param.h\"\n#include \"graph_map/ndt/ndtd2d_reg_type.h\"\n#include \"graph_map/ndt/ndt_map_type.h\"\n#include \"ros/ros.h\"\n#include \"nav_msgs/Odometry.h\"\n#include \"ros/publisher.h\"\n#include \"tf/transform_broadcaster.h\"\n#include \"ndt_generic/eigen_utils.h\"\n#include \"ndt_generic/io.h\"\n#include \"ndt_offline/pointcloudbagreader.h\"\n#include \"ndt_offline/readbagfilegeneric.h\"\n#include <unistd.h>\n#include \"tf_conversions/tf_eigen.h\"\nusing namespace perception_oru;\nusing namespace libgraphMap;\nnamespace po = boost::program_options;\nusing namespace std;\n\n\nstd::string map_dir_name=\"\";\nstd::string output_dir_name=\"\";\nstd::string base_name=\"\";\nstd::string dataset=\"\";\nstd::string bag_reader_type=\"\";\n//map parameters\nint itrs=0;\nint nb_neighbours=0;\nint nb_scan_msgs=0;\nbool use_odometry=true;\nbool visualize=true;\nbool use_multires=false;\nbool beHMT=false;\nbool filter_fov=false;\nbool step_control=false;\nbool check_consistency=true;\nbool registration2d=true;\nbool use_submap=true;\ndouble min_keyframe_dist=0.5;\ndouble min_keyframe_dist_rot_deg=15;\nbool use_keyframe=true;\nbool alive=false;\nbool save_map=true;\nbool gt_mapping=false;\nbool disable_reg=false, do_soft_constraints=false;\nbool pcl_reader=true;\nperception_oru::MotionModel2d::Params motion_params;\nstd::string base_link_id=\"\", gt_base_link_id=\"\", tf_world_frame=\"\";\nstd::string velodyne_config_file=\"\";\nstd::string velodyne_packets_topic=\"\";\nstd::string velodyne_frame_id=\"\";\nstd::string map_type_name=\"\",registration_type_name=\"\";\nstd::string tf_topic=\"\";\ntf::Transform tf_sensor_pose;\nEigen::Affine3d sensor_offset,fuser_pose, odom_pose;//Mapping from base frame to sensor frame\nros::NodeHandle *n_=NULL;\nRegParamPtr regParPtr=NULL;\nMapParamPtr mapParPtr=NULL;\nGraphParamPtr graphParPtr=NULL;\ndouble sensor_time_offset=0;\ndouble map_size_xy=0;\ndouble map_size_z=0;\ndouble resolution_local_factor=0;\ndouble max_range=0, min_range=0;\ndouble maxRotationNorm_=0;\ndouble compound_radius_=0;\ndouble interchange_radius_=0;\ndouble maxTranslationNorm_=0;\ndouble rotationRegistrationDelta_=0;\ndouble sensorRange_=30;\ndouble translationRegistrationDelta_=0;\ndouble resolution=0;\ndouble hori_min=0, hori_max=0;\ndouble min_dist=0, min_rot_in_deg=0;\nunsigned int skip_frame=20;\nros::Publisher *gt_pub,*fuser_pub,*cloud_pub,*odom_pub;\nnav_msgs::Odometry gt_pose_msg,fuser_pose_msg,odom_pose_msg;\n//VelodyneBagReader<pcl::PointXYZ> *vreader;\n//PointCloudBagReader<pcl::PointXYZ> *preader;\n//ReadBagFileGeneric<pcl::PointXYZ> *reader;\nbool use_pointtype_xyzir;\nint min_nb_points_for_gaussian;\nbool keep_min_nb_points;\nbool min_nb_points_set_uniform;\nint nb_measurements=1;\nint max_nb_iters=30;\n\ntemplate<class T> std::string toString (const T& x)\n{\n  std::ostringstream o;\n\n  if (!(o << x))\n    throw std::runtime_error (\"::toString()\");\n\n  return o.str ();\n}\n\nstd::string transformToEvalString(const Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> &T) {\n  std::ostringstream stream;\n  stream << std::setprecision(std::numeric_limits<double>::digits10);\n  Eigen::Quaternion<double> tmp(T.rotation());\n  stream << T.translation().transpose() << \" \" << tmp.x() << \" \" << tmp.y() << \" \" << tmp.z() << \" \" << tmp.w() << std::endl;\n  return stream.str();\n}\nbool GetSensorPose(const std::string &dataset,  Eigen::Vector3d & transl,  Eigen::Vector3d &euler,tf::Transform &tf_sensor){\n\n  tf::Quaternion quat;\n\n  bool found_sensor_pose=false;\n  if(dataset.compare(\"oru-basement\")==0){\n    transl[0]=0.3;\n    transl[1]=0;\n    transl[2]=1.3;\n    euler[0]=0;\n    euler[1]=0;\n    euler[2]=-1.62;\n    found_sensor_pose=true;\n  }\n  else if(dataset.compare(\"default\")==0){\n    transl[0]=0.3;\n    transl[1]=0;\n    transl[2]=0;\n    euler[0]=0;\n    euler[1]=0;\n    euler[2]=-1.62;\n    found_sensor_pose=true;\n  }\n  else if(dataset.compare(\"arla-2012\")==0){\n    transl[0]=1.18;\n    transl[1]=-0.3;\n    transl[2]=2.0;\n    euler[0]=0;\n    euler[1]=0;\n    euler[2]=-1.625;\n    found_sensor_pose=true;\n  }\n  quat.setRPY(euler[0], euler[1], euler[2]);\n  tf::Vector3 trans(transl[0], transl[1], transl[2]);\n  tf_sensor  = tf::Transform(quat,trans);\n  tf::poseTFToEigen(tf_sensor,sensor_offset);\n  return found_sensor_pose;\n}\n\n\n\nbool LocateRosBagFilePaths(const std::string &folder_name,std::vector<std::string> &scanfiles){\n  DIR *dir;\n  struct dirent *ent;\n  if ((dir = opendir (folder_name.c_str())) != NULL) {\n    while ((ent = readdir (dir)) != NULL) {\n      if(ent->d_name[0] == '.') continue;\n      char tmpcname[400];\n      snprintf(tmpcname,399,\"%s/%s\",folder_name.c_str(),ent->d_name);\n      std::string tmpfname = tmpcname;\n      scanfiles.push_back(tmpfname);\n    }\n    closedir (dir);\n  } else {\n    std::cerr<<\"Could not parse dir name\\n\";\n    return false;\n  }\n  sort(scanfiles.begin(),scanfiles.end());\n  {\n    std::cout << \"files to be loaded : \" << std::endl;\n    for (size_t i = 0; i < scanfiles.size(); i++) {\n      std::cout << \" \" << scanfiles[i] << std::flush;\n    }\n    std::cout << std::endl;\n  }\n  return true;\n}\nbool ReadAllParameters(po::options_description &desc,int &argc, char ***argv){\n\n  Eigen::Vector3d transl;\n  Eigen::Vector3d euler;\n\n  // First of all, make sure to advertise all program options\n  desc.add_options()\n      (\"help\", \"produce help message\")\n      (\"map_type_name\", po::value<string>(&map_type_name)->default_value(std::string(\"default\")), \"type of map to use e.g. ndt_map or ndt_dl_map (default it default)\")\n      (\"registration_type_name\", po::value<string>(&registration_type_name)->default_value(std::string(\"ndt_d2d_reg\")), \"type of map to use e.g. ndt_d2d_reg or ndt_dl_reg (default it default)\")\n      (\"visualize\", \"visualize the output\")\n      (\"use-odometry\", \"use initial guess from odometry\")\n      (\"disable-mapping\", \"build maps from cloud data\")\n      (\"no-step-control\", \"use step control in the optimization (default=false)\")\n      (\"base-name\", po::value<string>(&base_name), \"prefix for all generated files\")\n      (\"reader-type\", po::value<string>(&bag_reader_type)->default_value(\"velodyne_reader\"), \"e.g. velodyne_reader or pcl_reader\")\n      (\"data-set\", po::value<string>(&dataset)->default_value(std::string(\"default\")), \"choose which dataset that is currently used, this option will assist with assigning the sensor pose\")\n      (\"dir-name\", po::value<string>(&map_dir_name), \"where to look for ros bags\")\n      (\"output-dir-name\", po::value<string>(&output_dir_name)->default_value(\"/home/daniel/.ros/maps\"), \"where to save the pieces of the map (default it ./map)\")\n      (\"map-size-xy\", po::value<double>(&map_size_xy)->default_value(83.), \"size of submaps\")\n      (\"map-size-z\", po::value<double>(&map_size_z)->default_value(6.0), \"size of submaps\")\n      (\"itrs\", po::value<int>(&itrs)->default_value(30), \"number of iteration in the registration\")\n      (\"fuse-incomplete\", \"fuse in registration estimate even if iterations ran out. may be useful in combination with low itr numbers\")\n      (\"filter-fov\", \"cutoff part of the field of view\")\n      (\"hori-max\", po::value<double>(&hori_max)->default_value(2*M_PI), \"the maximum field of view angle horizontal\")\n      (\"hori-min\", po::value<double>(&hori_min)->default_value(-hori_max), \"the minimum field of view angle horizontal\")\n      (\"do-soft-constraints\", \"if soft constraints from odometry should be used\")\n      (\"Dd\", po::value<double>(&motion_params.Dd)->default_value(1.), \"forward uncertainty on distance traveled\")\n      (\"Dt\", po::value<double>(&motion_params.Dt)->default_value(1.), \"forward uncertainty on rotation\")\n      (\"Cd\", po::value<double>(&motion_params.Cd)->default_value(1.), \"side uncertainty on distance traveled\")\n      (\"Ct\", po::value<double>(&motion_params.Ct)->default_value(1.), \"side uncertainty on rotation\")\n      (\"Td\", po::value<double>(&motion_params.Td)->default_value(1.), \"rotation uncertainty on distance traveled\")\n      (\"Tt\", po::value<double>(&motion_params.Tt)->default_value(1.), \"rotation uncertainty on rotation\")\n      (\"min_dist\", po::value<double>(&min_dist)->default_value(0.2), \"minimum distance traveled before adding cloud\")\n      (\"min_rot_in_deg\", po::value<double>(&min_rot_in_deg)->default_value(5), \"minimum rotation before adding cloud\")\n      (\"tf_base_link\", po::value<std::string>(&base_link_id)->default_value(std::string(\"/odom_base_link\")), \"tf_base_link\")\n      (\"tf_gt_link\", po::value<std::string>(&gt_base_link_id)->default_value(std::string(\"/state_base_link\")), \"tf ground truth link\")\n      (\"velodyne_config_file\", po::value<std::string>(&velodyne_config_file)->default_value(std::string(\"../config/velo32.yaml\")), \"configuration file for the scanner\")\n      (\"tf_world_frame\", po::value<std::string>(&tf_world_frame)->default_value(std::string(\"/world\")), \"tf world frame\")\n      (\"velodyne-packets-topic\", po::value<std::string>(&velodyne_packets_topic)->default_value(std::string(\"/velodyne_packets\")), \"velodyne packets topic used\")\n      (\"velodyne_frame_id\", po::value<std::string>(&velodyne_frame_id)->default_value(std::string(\"/velodyne\")), \"frame_id of the laser sensor\")\n      (\"alive\", \"keep the mapper/visualization running even though it is completed (e.g. to take screen shots etc.\")\n      (\"nb_neighbours\", po::value<int>(&nb_neighbours)->default_value(2), \"number of neighbours used in the registration\")\n      (\"min-range\", po::value<double>(&min_range)->default_value(1.0), \"minimum range used from scanner\")\n      (\"max-range\", po::value<double>(&max_range)->default_value(30), \"minimum range used from scanner\")\n      (\"save-map\", \"saves the graph map at the end of execution\")\n      (\"nb_scan_msgs\", po::value<int>(&nb_scan_msgs)->default_value(1), \"number of scan messages that should be loaded at once from the bag\")\n      (\"disable-keyframe-update\", \"use every scan to update map rather than update map upon distance traveled\")\n      (\"keyframe-min-distance\", po::value<double>(&min_keyframe_dist)->default_value(0.5), \"minimum range used from scanner\")\n      (\"keyframe-min-rot-deg\", po::value<double>(&min_keyframe_dist_rot_deg)->default_value(15), \"minimum range used from scanner\")\n      (\"gt-mapping\", \"disable registration and use ground truth as input to mapping\")\n      (\"tf_topic\", po::value<std::string>(&tf_topic)->default_value(std::string(\"/tf\")), \"tf topic to listen to\")\n      (\"x\", po::value<double>(&transl[0])->default_value(0.), \"sensor pose - translation vector x\")\n      (\"y\", po::value<double>(&transl[1])->default_value(0.), \"sensor pose - translation vector y\")\n      (\"z\", po::value<double>(&transl[2])->default_value(0.), \"sensor pose - translation vector z\")\n      (\"ex\", po::value<double>(&euler[0])->default_value(0.), \"sensor pose - euler angle vector x\")\n      (\"ey\", po::value<double>(&euler[1])->default_value(0.), \"sensor pose - euler angle vector y\")\n      (\"ez\", po::value<double>(&euler[2])->default_value(0.), \"sensor pose - euler angle vector z\")\n      (\"skip-frame\", po::value<unsigned int>(&skip_frame)->default_value(20), \"sframes to skip before plot map etc.\")\n      (\"sensor_time_offset\", po::value<double>(&sensor_time_offset)->default_value(0.), \"timeoffset of the scanner data\")\n      (\"registration3d\",\"registration3d\")\n      (\"check-consistency\", \"if consistency should be checked after registration\")\n      (\"do-soft-constraints\", \"do_soft_constraints_\")\n      (\"disable-registration\", \"Disable Registration\")\n      (\"maxRotationNorm\",po::value<double>(&maxRotationNorm_)->default_value(0.78539816339),\"maxRotationNorm\")\n      (\"maxTranslationNorm\",po::value<double>(&maxTranslationNorm_)->default_value(0.4),\"maxTranslationNorm\")\n      (\"rotationRegistrationDelta\",po::value<double>(&rotationRegistrationDelta_)->default_value(M_PI/6),\"rotationRegistrationDelta\")\n      (\"translationRegistrationDelta\",po::value<double>(&translationRegistrationDelta_)->default_value(1.5),\"sensorRange\")\n      (\"resolution\", po::value<double>(&resolution)->default_value(0.4), \"resolution of the map\")\n      (\"resolution_local_factor\", po::value<double>(&resolution_local_factor)->default_value(1.), \"resolution factor of the local map used in the match and fusing step\")\n      (\"disable-submaps\", \"Adopt the sub-mapping technique which represent the global map as a set of local submaps\")\n      (\"compound-radius\", po::value<double>(&compound_radius_)->default_value(10.0), \"Requires sub-mapping enabled, When creating new sub-lamps, information from previous map is transfered to the new map. The following radius is used to select the map objects to transfer\")\n      (\"interchange-radius\", po::value<double>(&interchange_radius_)->default_value(10.0), \"This radius is used to trigger creation or selection of which submap to use\")\n      (\"use_pointtype_xyzir\", \"If the points to be processed should contain ring and intensity information (velodyne_pointcloud::PointXYZIR)\")\n      (\"min_nb_points_for_gaussian\", po::value<int>(&min_nb_points_for_gaussian)->default_value(6), \"minimum number of points per cell to compute a gaussian\")\n      (\"keep_min_nb_points\", \"If the number of points stored in a NDTCell should be cleared if the number is less than min_nb_points_for_gaussian\")\n      (\"min_nb_points_set_uniform\", \"If the number of points of one cell is less than min_nb_points_for_gaussian, set the distribution to a uniform one (cov = Identity)\")\n      (\"nb_measurements\", po::value<int>(&nb_measurements)->default_value(1), \"number of scans collecte at each read iteration\")\n      (\"max_nb_iters\", po::value<int>(&max_nb_iters)->default_value(30), \"max number of iterations used in the registration\");\n\n  //Boolean parameres are read through notifiers\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    cout << desc << \"\\n\";\n    return false;\n  }\n\n  keep_min_nb_points = vm.count(\"clear_min_nb_points\");\n  min_nb_points_set_uniform = vm.count(\"min_nb_points_set_uniform\");\n  NDTCell::setParameters(0.1, 8*M_PI/18., 1000, min_nb_points_for_gaussian, !keep_min_nb_points, min_nb_points_set_uniform);\n\n  if(GetSensorPose(dataset,transl,euler,tf_sensor_pose)) {\n    cout<<\"sensor pose from dataset utilized [\" << dataset << \"]\" << endl;\n  }\n\n  mapParPtr= GraphFactory::CreateMapParam(map_type_name); //map_type_name\n  regParPtr=GraphFactory::CreateRegParam(registration_type_name);\n  graphParPtr=GraphFactory::CreateGraphParam();\n  if(mapParPtr==NULL || regParPtr==NULL || graphParPtr==NULL)\n    return false;\n\n  use_odometry = vm.count(\"use-odometry\");\n  visualize = vm.count(\"visualize\");\n  filter_fov = vm.count(\"filter-fov\");\n  step_control = (vm.count(\"no-step-control\") == 0);\n  gt_mapping= vm.count(\"gt-mapping\");\n  use_keyframe=!vm.count(\"disable-keyframe-update\");\n  if(gt_mapping)\n    base_link_id=gt_base_link_id;\n  check_consistency=vm.count(\"check-consistency\");\n  alive = vm.count(\"alive\");\n  save_map = vm.count(\"save-map\");\n  registration2d=!vm.count(\"registration3d\");\n  do_soft_constraints=vm.count(\"do-soft-constraints\");\n  regParPtr->do_soft_constraints_ = vm.count(\"do-soft-constraints\");\n  regParPtr->enableRegistration_ = !vm.count(\"disable-registration\") && !gt_mapping;\n  regParPtr->registration2d_=registration2d;\n  regParPtr->maxRotationNorm_=maxRotationNorm_;\n  regParPtr->maxTranslationNorm_=maxTranslationNorm_;\n  regParPtr->rotationRegistrationDelta_=rotationRegistrationDelta_;\n  regParPtr->translationRegistrationDelta_=translationRegistrationDelta_;\n  regParPtr->sensorRange_=max_range;\n  regParPtr->mapSizeZ_= map_size_z;\n  regParPtr->checkConsistency_=check_consistency;\n\n  mapParPtr->sizez_=map_size_z;\n  mapParPtr->max_range_=max_range;\n  mapParPtr->min_range_=min_range;\n  graphParPtr->compound_radius_=compound_radius_;\n  graphParPtr->interchange_radius_=interchange_radius_;\n  cout<<\"use keyframe=\"<<use_keyframe;\n  graphParPtr->use_keyframe_=use_keyframe;\n  graphParPtr->min_keyframe_dist_=min_keyframe_dist;\n  graphParPtr->min_keyframe_rot_deg_=min_keyframe_dist_rot_deg;\n  mapParPtr->enable_mapping_=!vm.count(\"disable-mapping\");\n  mapParPtr->sizey_=map_size_xy;\n  mapParPtr->sizex_=map_size_xy;\n  use_submap=!vm.count(\"disable-submaps\");\n  graphParPtr->use_submap_=use_submap;\n\n  if(  NDTD2DRegParamPtr ndt_reg_ptr=boost::dynamic_pointer_cast<NDTD2DRegParam>(regParPtr)){\n    ndt_reg_ptr->resolution_=resolution;\n    ndt_reg_ptr->resolutionLocalFactor_=resolution_local_factor;\n    ndt_reg_ptr->matcher2D_ITR_MAX = max_nb_iters;\n  }\n  {\n   if(  NDTMapParamPtr ndt_map_ptr=boost::dynamic_pointer_cast<NDTMapParam>(mapParPtr)){\n      ndt_map_ptr->resolution_=resolution;\n    }\n    if (NDTDLMapParamPtr ndt_map_ptr=boost::dynamic_pointer_cast<NDTDLMapParam>(mapParPtr)){\n      ndt_map_ptr->resolution_ = resolution;\n    }\n  }\n\n  //Check if all iputs are assigned\n  if (!vm.count(\"base-name\") || !vm.count(\"dir-name\")){\n    cout << \"Missing base or dir names.\\n\";\n    cout << desc << \"\\n\";\n    return false;\n  }\n  if (vm.count(\"help\")){\n    cout << desc << \"\\n\";\n    return false;\n  }\n\n  use_pointtype_xyzir = vm.count(\"use_pointtype_xyzir\");\n  cout<<\"base-name:\"<<base_name<<endl;\n  cout<<\"dir-name:\"<<map_dir_name<<endl;\n  return true;\n\n\n}\nvoid initializeRosPublishers(){\n  ros::Time::init();\n  srand(time(NULL));\n  gt_pub=new ros::Publisher();\n  fuser_pub=new ros::Publisher();\n  odom_pub=new ros::Publisher();\n  cloud_pub=new ros::Publisher();\n  *gt_pub    =n_->advertise<nav_msgs::Odometry>(\"/GT\", 50);\n  *fuser_pub =n_->advertise<nav_msgs::Odometry>(\"/fuser\", 50);\n  *odom_pub = n_->advertise<nav_msgs::Odometry>(\"/odom\", 50);\n  *cloud_pub = n_->advertise<pcl::PointCloud<pcl::PointXYZ>>(\"/points2\", 1);\n}\nvoid printParameters(){\n  cout<<\"Output directory: \"<<output_dir_name<<endl;\n  if(filter_fov)\n    cout << \"Filtering FOV of sensor to min/max \"<<hori_min<<\" \"<<hori_max<<endl;\n  else\n    cout<<\"No FOV filter.\"<<endl;\n\n}\nstd::string boolToString(bool input){\n  return input?std::string(\"true\"):std::string(\"false\");\n}\n\ntemplate<typename PointT>\nvoid processData() {\n\n  n_=new ros::NodeHandle(\"~\");\n\n  GraphMapFuser *fuser_;\n  stringstream ss;\n  string name= gt_mapping? \"_gt_\":\"_fuser_\";\n  ss<<name<<dataset<<std::string(\"__Sub=\")<<use_submap<<\"_sizexy=\"<<map_size_xy<<\"_Z=\"<<map_size_z<<std::string(\"_intrchR=\")<<interchange_radius_<<std::string(\"_compR=\")<<compound_radius_<<std::string(\"_res=\") <<resolution<<std::string(\"_maxSensd=\") << max_range<<\"_keyF=\"<<use_keyframe<<\"_d=\"<<min_keyframe_dist<<\"_deg=\"<<min_keyframe_dist_rot_deg;\n  base_name+=ss.str();\n  bool dl = (map_type_name == \"ndt_dl_map\");\n  base_name+=\"_dl=\"+toString(dl)+\"_xyzir=\"+toString(use_pointtype_xyzir)+\"_mpsu=\"+toString(min_nb_points_set_uniform)+\"_mnpfg=\"+toString(min_nb_points_for_gaussian)+\"kmnp\"+toString(keep_min_nb_points);\n  ndt_generic::CreateEvalFiles eval_files(output_dir_name,base_name,false);\n  printParameters();\n  initializeRosPublishers();\n  tf::TransformBroadcaster br;\n  gt_pose_msg.header.frame_id=\"/world\";\n  fuser_pose_msg.header.frame_id=\"/world\";\n  odom_pose_msg.header.frame_id=\"/world\";\n\n  std::string tf_interp_link = base_link_id;\n  if(gt_mapping)\n    tf_interp_link = gt_base_link_id;\n\n\n  /// Set up the sensor link\n  tf::StampedTransform sensor_link; ///Link from /odom_base_link -> velodyne\n  sensor_link.child_frame_id_ = velodyne_frame_id;\n  sensor_link.frame_id_ = tf_interp_link;//tf_base_link; //\"/odom_base_link\";\n  sensor_link.setData(tf_sensor_pose);\n\n  std::vector<std::string> ros_bag_paths;\n  if(!LocateRosBagFilePaths(map_dir_name,ros_bag_paths)){\n    cout<<\"couldnt locate ros bags\"<<endl;\n    exit(0);\n  }\n\n  int counter = 0;\n\n  cout<<\"opening bag files\"<<endl;\n  for(int i=0; i<ros_bag_paths.size(); i++) {\n    std::string bagfilename = ros_bag_paths[i];\n    fprintf(stderr,\"Opening %s\\n\",bagfilename.c_str());\n    //char c=getchar();\n    //reader=new ReadBagFileGeneric<pcl::PointXYZ>(bag_reader_type,\n    ReadBagFileGeneric<PointT> reader(bag_reader_type,\n                                             tf_interp_link,\n                                             velodyne_config_file,\n                                             bagfilename,\n                                             velodyne_packets_topic,\n                                             velodyne_frame_id,\n                                             tf_world_frame,\n                                             tf_topic,\n                                             ros::Duration(3600),\n                                             &sensor_link, max_range, min_range,\n                                             sensor_time_offset,\n                                             nb_measurements);\n\n    pcl::PointCloud<PointT> cloud, cloud_nofilter, points2;\n    tf::Transform tf_scan_source;\n    tf::Transform tf_gt_base;\n    Eigen::Affine3d Todom_base_prev,Tgt_base_prev;\n    ros::Time itr=ros::Time::now();\n    ros::Time itr_end=itr;\n    bool found_scan=true;\n\n    while(found_scan){\n\n      //end_of_bag_file=  vreader.readMultipleMeasurements(nb_scan_msgs,cloud_nofilter,tf_scan_source,tf_gt_base,tf_interp_link);\n      //found_scan= preader.readNextMeasurement(cloud_nofilter);\n      found_scan= reader.ReadNextMeasurement(cloud_nofilter);\n      if(!n_->ok())\n        exit(0);\n\n\n     // cout<<\"iteration time=\"<<ros::Time::now()-itr<<endl;\n      itr=ros::Time::now();\n     // cout<<\"time to read bag file=\"<<itr_end-itr<<endl;\n\n      if(cloud_nofilter.size()==0) continue;\n\n      if(filter_fov) {\n        ndt_generic::filter_fov_fun(cloud,cloud_nofilter,hori_min,hori_max);\n      } else {\n        cloud = cloud_nofilter;\n      }\n\n      if (cloud.size() == 0) continue; // Check that we have something to work with depending on the FOV filter here...\n\n      points2 = cloud;\n\n      // reader.getPoseFor(Todom_base, base_link_id);\n      //reader.getPoseFor(Tgt_base, gt_base_link_id);\n      tf::Transform tf_odom_base;\n      reader.getPoseFor(tf_odom_base, base_link_id);\n      reader.getPoseFor(tf_gt_base, gt_base_link_id);\n\n      //  vreader.getPoseFor(tf_odom_base, base_link_id);\n      // vreader.getPoseFor(tf_gt_base, gt_base_link_id);\n\n      Eigen::Affine3d Todom_base,Tgt_base;\n      tf::transformTFToEigen(tf_gt_base,Tgt_base);\n      tf::transformTFToEigen(tf_odom_base,Todom_base);\n\n\n      if(counter == 0){\n        if( found_scan!=true){\n          cout<<\"Problem with bag filel\"<<endl;\n          exit(0);\n        }\n        counter ++;\n        cloud.clear();\n        cloud_nofilter.clear();\n        continue;\n      }\n      if(counter == 1){\n        fuser_pose=Tgt_base;\n        odom_pose=fuser_pose;\n        Tgt_base_prev = Tgt_base;\n        Todom_base_prev = Todom_base;\n        fuser_=new GraphMapFuser(regParPtr,mapParPtr,graphParPtr,Tgt_base,sensor_offset);\n        cout<<\"----------------------PARAMETERS FOR MAPPING--------------------------\"<<endl;\n        cout<<fuser_->ToString()<<endl;\n        cout<<\"----------------------PARAMETERS FOR MAPPING--------------------------\"<<endl;\n        fuser_->Visualize(visualize,plotmarker::point/*plotmarker::sphere*/);\n        counter ++;\n        cloud.clear();\n        cloud_nofilter.clear();\n        continue;\n      }\n      if( found_scan!=true)\n        break;\n      Eigen::Affine3d Tmotion;\n      if(gt_mapping)\n        Tmotion = Tgt_base_prev.inverse()*Tgt_base;\n      else\n        Tmotion = Todom_base_prev.inverse()*Todom_base;\n      Eigen::Vector3d Tmotion_euler = Tmotion.rotation().eulerAngles(0,1,2);\n      ndt_generic::normalizeEulerAngles(Tmotion_euler);\n      //cout<<\"Tmotion:\"<<Tmotion.translation().transpose()<<endl;\n      if(!use_odometry) {\n        Tmotion.setIdentity();\n      }\n      counter++;\n\n      //fuser_pose=fuser_pose*Tmotion;\n      ros::Time tplot=ros::Time::now();\n\n      bool registration_update =fuser_->ProcessFrame<PointT>(cloud,fuser_pose,Tmotion);\n      tf::Transform tf_fuser_pose;\n      tf::poseEigenToTF(fuser_pose,tf_fuser_pose);\n      br.sendTransform(tf::StampedTransform(tf_fuser_pose,tplot,\"/world\",\"/fuser_base_link\"));\n\n      odom_pose = odom_pose*Tmotion;\n      tf::Transform tf_odom_pose;\n      tf::poseEigenToTF(odom_pose,tf_odom_pose);\n      br.sendTransform(tf::StampedTransform(tf_odom_pose,tplot,\"/world\",\"/odom_base_link\"));\n\n\n      if(visualize)\n      {\n\n        br.sendTransform(tf::StampedTransform(tf_gt_base,tplot,   \"/world\", \"/state_base_link\"));\n        br.sendTransform(tf::StampedTransform(tf_sensor_pose,tplot,\"/fuser_base_link\",\"/fuser_laser_link\"));\n\n        if(!gt_mapping){\n          fuser_pose_msg.header.stamp=tplot;\n          tf::poseEigenToMsg(fuser_pose, fuser_pose_msg.pose.pose);\n          fuser_pub->publish(fuser_pose_msg);\n        }\n        gt_pose_msg.header.stamp=tplot;\n        tf::poseEigenToMsg(Tgt_base, gt_pose_msg.pose.pose);\n        gt_pub->publish(gt_pose_msg);\n\n        odom_pose_msg.header.stamp=tplot;\n        tf::poseEigenToMsg(odom_pose, odom_pose_msg.pose.pose);\n        odom_pub->publish(odom_pose_msg);\n\n        if (registration_update) {\n          points2.header.frame_id=\"/world\";\n          pcl_conversions::toPCL(tplot, points2.header.stamp);\n          Eigen::Affine3d tmp = fuser_pose*sensor_offset;\n          perception_oru::transformPointCloudInPlace(tmp, points2);\n          cloud_pub->publish(points2);\n          fuser_->PlotMapType();\n        }\n      }\n      //sleep(1);\n      Tgt_base_prev = Tgt_base;\n      Todom_base_prev = Todom_base;\n      cloud.clear();\n      cloud_nofilter.clear();\n\n      eval_files.Write( reader.getTimeStampOfLastSensorMsg(),Tgt_base,Todom_base,fuser_pose,sensor_offset);\n      itr_end=ros::Time::now();\n    }\n  }\n  eval_files.Close();\n\n  if(save_map && fuser_!=NULL && fuser_->FramesProcessed()>0){\n    char path[1000];\n    snprintf(path,999,\"%s/%s.map\",output_dir_name.c_str(),base_name.c_str());\n    fuser_->SaveGraphMap(path);\n  }\n}\n\n\n/////////////////////////////////////////////////////////////////////////////////7\n/////////////////////////////////////////////////////////////////////////////////7\n/// *!!MAIN!!*\n/////////////////////////////////////////////////////////////////////////////////7\n/////////////////////////////////////////////////////////////////////////////////7\n///\n\nint main(int argc, char **argv){\n  ros::init(argc, argv, \"graph_fuser3d_offline\");\n  po::options_description desc(\"Allowed options\");\n\n  cout<<\"Read params\"<<endl;\n  bool succesfull=ReadAllParameters(desc,argc,&argv);\n  if(!succesfull)\n    exit(0);\n\n  if (use_pointtype_xyzir) {\n    processData<velodyne_pointcloud::PointXYZIR>();\n  }\n  else {\n    processData<pcl::PointXYZ>();\n  }\n\n\n\n\n  if (alive) {\n    while (1) {\n      usleep(1000);\n    }\n  }\n  usleep(1000*1000);\n  std::cout << \"Done.\" << std::endl;\n}\n", "meta": {"hexsha": "48ab3da1b3fdd6bea09ef9eaab252351c92268ff", "size": 27216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_offline/src/graph_fuser3d_offline.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_offline/src/graph_fuser3d_offline.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_offline/src/graph_fuser3d_offline.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": 42.8598425197, "max_line_length": 349, "alphanum_fraction": 0.6825396825, "num_tokens": 6994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17722765278866937}}
{"text": "#include \"StructToRLBotFlatbuffer.hpp\"\n\n\n#define NOMINMAX\n#include <algorithm>\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <rlbot_generated.h>\n\n#include <codecvt>\n#include <cwchar>\n#include <iostream>\n#include <boost/locale/encoding_utf.hpp>\n\n\n\n/*\nNote: The code in this file looks goofy because flatbuffers requires us to construct things 'pre-order',\ni.e. you have to fully create all the sub-objects before you start creating a parent object.\n\nhttps://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp\n\n*/\nnamespace StructToRLBotFlatbuffer\n{\n\tflatbuffers::Offset<rlbot::flat::GameInfo> createGameInfo(flatbuffers::FlatBufferBuilder* builder, GameInfo gameInfo)\n\t{\n\t\treturn rlbot::flat::CreateGameInfo(\n\t\t\t*builder,\n\t\t\tgameInfo.timeSeconds,\n\t\t\tgameInfo.gameTimeRemaining,\n\t\t\tgameInfo.overTime,\n\t\t\tgameInfo.unlimitedTime,\n\t\t\tgameInfo.roundActive,\n\t\t\tgameInfo.kickoffPause,\n\t\t\tgameInfo.matchEnded,\n\t\t\tgameInfo.worldGravityZ,\n\t\t\tgameInfo.gameSpeed);\n\t}\n\n\trlbot::flat::Vector3 createVector3(PyStruct::Vector3 structVec)\n\t{\n\t\treturn rlbot::flat::Vector3(structVec.x, structVec.y, structVec.z);\n\t}\n\n\tfloat convertURot(int rotation)\n\t{\n\t\treturn rotation * M_PI / 32768;\n\t}\n\n\trlbot::flat::Rotator createRotator(PyStruct::Rotator structRot)\n\t{\n\t\treturn rlbot::flat::Rotator(\n\t\t\tconvertURot(structRot.pitch),\n\t\t\tconvertURot(structRot.yaw),\n\t\t\tconvertURot(structRot.roll));\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::BoxShape> createBoxShape(flatbuffers::FlatBufferBuilder & builder, BoxShape boxshape)\n\t{\n\t\treturn rlbot::flat::CreateBoxShape(builder, boxshape.length, boxshape.width, boxshape.height);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::SphereShape> createSphereShape(flatbuffers::FlatBufferBuilder & builder, SphereShape sphereshape)\n\t{\n\t\treturn rlbot::flat::CreateSphereShape(builder, sphereshape.diameter);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::CylinderShape> createCylinderShape(flatbuffers::FlatBufferBuilder & builder, CylinderShape cylindershape)\n\t{\n\t\treturn rlbot::flat::CreateCylinderShape(builder, cylindershape.diameter, cylindershape.height);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::BoostPad> createBoostPad(flatbuffers::FlatBufferBuilder* builder, BoostPad boostPad)\n\t{\n\t\tauto location = createVector3(boostPad.location);\n\t\treturn rlbot::flat::CreateBoostPad(*builder, &location, boostPad.fullBoost);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::BoostPadState> createBoostPadState(flatbuffers::FlatBufferBuilder* builder, BoostInfo gameBoost)\n\t{\n\t\treturn rlbot::flat::CreateBoostPadState(*builder, gameBoost.active, gameBoost.timer);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::DropshotTile> createDropshotTile(flatbuffers::FlatBufferBuilder* builder, TileInfo dropshotTile)\n\t{\n\t\trlbot::flat::TileState state;\n\t\tif (dropshotTile.tileState == 3)\n\t\t\tstate = rlbot::flat::TileState::TileState_Open;\n\t\telse if (dropshotTile.tileState == 2)\n\t\t\tstate = rlbot::flat::TileState::TileState_Damaged;\n\n\t\tstate = rlbot::flat::TileState::TileState_Filled;\n\n\t\treturn rlbot::flat::CreateDropshotTile(*builder, state);\n\t}\n\n\tbool FillFieldInfo(flatbuffers::FlatBufferBuilder* builder, FieldInfo fieldInfo)\n\t{\n\t\tstd::vector<flatbuffers::Offset<rlbot::flat::BoostPad>> boostPads;\n\n\t\tfor (int i = 0; i < fieldInfo.numBoosts; i++)\n\t\t{\n\t\t\tboostPads.push_back(createBoostPad(builder, fieldInfo.boostPads[i]));\n\t\t}\n\n\t\tstd::vector<flatbuffers::Offset<rlbot::flat::GoalInfo>> goals;\n\n\n\n\t\tfor (int i = 0; i < fieldInfo.numGoals; i++)\n\t\t{\n\t\t\tauto location = createVector3(fieldInfo.goals[i].location);\n\t\t\tauto direction = createVector3(fieldInfo.goals[i].direction);\n\t\t\tgoals.push_back(rlbot::flat::CreateGoalInfo(*builder,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfieldInfo.goals[i].teamNum,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t&location,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t&direction,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfieldInfo.goals[i].width,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfieldInfo.goals[i].height));\n\t\t}\n\n\t\tauto fieldInfoBuffer = rlbot::flat::CreateFieldInfo(*builder, builder->CreateVector(boostPads), builder->CreateVector(goals));\n\t\tbuilder->Finish(fieldInfoBuffer);\n\n\t\treturn true;\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::Physics> createPhysics(flatbuffers::FlatBufferBuilder* builder, Physics physics)\n\t{\n\t\tauto location = createVector3(physics.location);\n\t\tauto rotation = createRotator(physics.rotation);\n\t\tauto velocity = createVector3(physics.velocity);\n\t\tauto angular = createVector3(physics.angularVelocity);\n\n\t\treturn rlbot::flat::CreatePhysics(*builder, &location, &rotation, &velocity, &angular);\n\t}\n\n\tstd::string convertString(wchar_t* w)\n\t{\n\t\tstd::wstring ws(w);\n\t\treturn boost::locale::conv::utf_to_utf<char>(ws.c_str(), ws.c_str() + ws.size());\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::PlayerInfo> createPlayerInfo(flatbuffers::FlatBufferBuilder* builder, PlayerInfo playerInfo)\n\t{\n\t\trlbot::flat::ScoreInfoBuilder sib(*builder);\n\n\t\tsib.add_score(playerInfo.score.score);\n\t\tsib.add_goals(playerInfo.score.goals);\n\t\tsib.add_ownGoals(playerInfo.score.ownGoals);\n\t\tsib.add_assists(playerInfo.score.assists);\n\t\tsib.add_saves(playerInfo.score.saves);\n\t\tsib.add_shots(playerInfo.score.shots);\n\t\tsib.add_demolitions(playerInfo.score.demolitions);\n\n\t\tauto scoreInfo = sib.Finish();\n\n\t\tstd::string name = convertString(playerInfo.name);\n\t\tauto flatName = builder->CreateString(name); // Must do this before PlayerInfoBuilder is started.\n\t\tauto physics = createPhysics(builder, playerInfo.physics);\n\t\tauto hitbox = createBoxShape(*builder, playerInfo.hitbox);\n\t\tauto hitboxOffset = createVector3(playerInfo.hitboxOffset);\n\n\t\trlbot::flat::PlayerInfoBuilder pib(*builder);\n\n\t\tpib.add_scoreInfo(scoreInfo);\n\t\tpib.add_isBot(playerInfo.bot);\n\t\tpib.add_name(flatName);\n\t\tpib.add_isDemolished(playerInfo.demolished);\n\t\tpib.add_physics(physics);\n\t\tpib.add_hasWheelContact(playerInfo.onGround);\n\t\tpib.add_isSupersonic(playerInfo.superSonic);\n\t\tpib.add_jumped(playerInfo.jumped);\n\t\tpib.add_doubleJumped(playerInfo.doubleJumped);\n\t\tpib.add_team(playerInfo.team);\n\t\tpib.add_boost(playerInfo.boost);\n\t\tpib.add_hitbox(hitbox);\n\t\tpib.add_hitboxOffset(&hitboxOffset);\n\t\tpib.add_spawnId(playerInfo.spawnId);\n\n\t\treturn pib.Finish();\n\t}\n\n\tflatbuffers::Offset<void> createCollisionShape(flatbuffers::FlatBufferBuilder & builder, CollisionShape collisionShape)\n\t{\n\t\tswitch (collisionShape.type)\n\t\t{\n\t\tcase BoxType:\n\t\t\treturn createBoxShape(builder, collisionShape.box).Union();\n\n\t\tcase SphereType:\n\t\t\treturn createSphereShape(builder, collisionShape.sphere).Union();\n\n\t\tcase CylinderType:\n\t\t\treturn createCylinderShape(builder, collisionShape.cylinder).Union();\n\t\t}\n\t}\n\n\trlbot::flat::CollisionShape createCollisionShapeType(CollisionShapeType collisionShapeType)\n\t{\n\t\tswitch (collisionShapeType)\n\t\t{\n\t\tcase BoxType:\n\t\t\treturn rlbot::flat::CollisionShape_BoxShape;\n\n\t\tcase SphereType:\n\t\t\treturn rlbot::flat::CollisionShape_SphereShape;\n\n\t\tcase CylinderType:\n\t\t\treturn rlbot::flat::CollisionShape_CylinderShape;\n\t\t}\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::BallInfo> createBallInfo(flatbuffers::FlatBufferBuilder* builder, BallInfo ballInfo)\n\t{\n\t\tbool hasTouch = ballInfo.latestTouch.timeSeconds > 0;\n\t\tflatbuffers::Offset<rlbot::flat::Touch> touchOffset;\n\n\t\tif (hasTouch)\n\t\t{\n\t\t\tstd::string name = convertString(ballInfo.latestTouch.playerName);\n\t\t\tauto flatName = builder->CreateString(name); // Must do this before TouchBuilder is started\n\n\t\t\tauto touch = rlbot::flat::TouchBuilder(*builder);\n\t\t\ttouch.add_playerName(flatName);\n\t\t\ttouch.add_gameSeconds(ballInfo.latestTouch.timeSeconds);\n\n\t\t\tauto location = createVector3(ballInfo.latestTouch.hitLocation);\n\t\t\ttouch.add_location(&location);\n\n\t\t\tauto normal = createVector3(ballInfo.latestTouch.hitNormal);\n\t\t\ttouch.add_normal(&normal);\n\n\t\t\ttouch.add_team(ballInfo.latestTouch.team);\n\n\t\t\ttouch.add_playerIndex(ballInfo.latestTouch.playerIndex);\n\n\t\t\ttouchOffset = touch.Finish();\n\t\t}\n\n\t\tauto physics = createPhysics(builder, ballInfo.physics);\n\n\t\tflatbuffers::Offset<rlbot::flat::DropShotBallInfo> dropShotBallOffset;\n\n\t\trlbot::flat::DropShotBallInfoBuilder dbib(*builder);\n\t\tdbib.add_absorbedForce(ballInfo.dropShotInfo.absorbedForce);\n\t\tdbib.add_damageIndex(ballInfo.dropShotInfo.damageIndex);\n\t\tdbib.add_forceAccumRecent(ballInfo.dropShotInfo.forceAccumRecent);\n\n\t\tdropShotBallOffset = dbib.Finish();\n\n\t\tauto collisionshape = createCollisionShape(*builder, ballInfo.collisionShape);\n\n\t\trlbot::flat::BallInfoBuilder bib(*builder);\n\t\tbib.add_physics(physics);\n\n\t\tif (hasTouch)\n\t\t\tbib.add_latestTouch(touchOffset);\n\n\t\tbib.add_dropShotInfo(dropShotBallOffset);\n\t\tbib.add_shape(collisionshape);\n\t\tbib.add_shape_type(createCollisionShapeType(ballInfo.collisionShape.type));\n\n\t\treturn bib.Finish();\n\t}\n\n\tbool FillGameDataPacket(flatbuffers::FlatBufferBuilder* builder, LiveDataPacket liveDataPacket)\n\t{\n\n\t\tstd::vector<flatbuffers::Offset<rlbot::flat::PlayerInfo>> players;\n\t\tflatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<rlbot::flat::PlayerInfo>>> playersOffset;\n\n\n\t\tfor (int i = 0; i < liveDataPacket.numCars; i++)\n\t\t{\n\t\t\tplayers.push_back(createPlayerInfo(builder, liveDataPacket.gameCars[i]));\n\t\t}\n\n\t\tplayersOffset = builder->CreateVector(players);\n\n\n\t\tauto gameInfo = createGameInfo(builder, liveDataPacket.gameInfo);\n\n\t\tstd::vector<flatbuffers::Offset<rlbot::flat::BoostPadState>> boosts;\n\t\tflatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<rlbot::flat::BoostPadState>>> boostsOffset;\n\n\n\t\tfor (int i = 0; i < liveDataPacket.numBoosts; i++)\n\t\t{\n\t\t\tboosts.push_back(createBoostPadState(builder, liveDataPacket.gameBoosts[i]));\n\t\t}\n\n\t\tboostsOffset = builder->CreateVector(boosts);\n\n\t\tstd::vector<flatbuffers::Offset<rlbot::flat::DropshotTile>> tiles;\n\t\tflatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<rlbot::flat::DropshotTile>>> tilesOffset;\n\n\t\tfor (int i = 0; i < liveDataPacket.numTiles; i++)\n\t\t{\n\t\t\ttiles.push_back(createDropshotTile(builder, liveDataPacket.gameTiles[i]));\n\t\t}\n\n\n\t\ttilesOffset = builder->CreateVector(tiles);\n\n\n\t\tflatbuffers::Offset<rlbot::flat::BallInfo> ballOffset;\n\n\t\tballOffset = createBallInfo(builder, liveDataPacket.gameBall);\n\n\t\tstd::vector<flatbuffers::Offset<rlbot::flat::TeamInfo>> teamInfos;\n\t\tteamInfos.push_back(rlbot::flat::CreateTeamInfo(*builder, liveDataPacket.teams[0].teamIndex, liveDataPacket.teams[0].score));\n\t\tteamInfos.push_back(rlbot::flat::CreateTeamInfo(*builder, liveDataPacket.teams[1].teamIndex, liveDataPacket.teams[1].score));\n\t\tauto teamInfosOffset = builder->CreateVector(teamInfos);\n\n\t\trlbot::flat::GameTickPacketBuilder gtb(*builder);\n\t\tgtb.add_gameInfo(gameInfo);\n\n\t\tgtb.add_players(playersOffset);\n\t\tgtb.add_boostPadStates(boostsOffset);\n\t\tgtb.add_tileInformation(tilesOffset);\n\t\tgtb.add_ball(ballOffset);\n\t\tgtb.add_teams(teamInfosOffset);\n\n\t\tbuilder->Finish(gtb.Finish());\n\n\t\treturn true;\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::Color> buildColor(flatbuffers::FlatBufferBuilder* builder, Color structColor)\n\t{\n\t\treturn rlbot::flat::CreateColor(*builder, structColor.a, structColor.r, structColor.g, structColor.b);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::PlayerLoadout> buildPlayerLoadout(flatbuffers::FlatBufferBuilder* builder, PlayerConfiguration structPlayerConfig)\n\t{\n\t\trlbot::flat::LoadoutPaintBuilder paintBuilder(*builder);\n\t\tpaintBuilder.add_carPaintId(structPlayerConfig.carPaintID);\n\t\tpaintBuilder.add_decalPaintId(structPlayerConfig.decalPaintID);\n\t\tpaintBuilder.add_wheelsPaintId(structPlayerConfig.wheelsPaintID);\n\t\tpaintBuilder.add_boostPaintId(structPlayerConfig.boostPaintID);\n\t\tpaintBuilder.add_antennaPaintId(structPlayerConfig.antennaPaintID);\n\t\tpaintBuilder.add_hatPaintId(structPlayerConfig.hatPaintID);\n\t\tpaintBuilder.add_trailsPaintId(structPlayerConfig.trailsPaintID);\n\t\tpaintBuilder.add_goalExplosionPaintId(structPlayerConfig.goalExplosionPaintID);\n\t\tauto paintOffset = paintBuilder.Finish();\n\n\t\tauto primaryColorOffset = buildColor(builder, structPlayerConfig.primaryColorLookup);\n\t\tauto secondaryColorOffset = buildColor(builder, structPlayerConfig.secondaryColorLookup);\n\n\t\trlbot::flat::PlayerLoadoutBuilder loadoutBuilder(*builder);\n\t\tloadoutBuilder.add_teamColorId(structPlayerConfig.teamColorID);\n\t\tloadoutBuilder.add_customColorId(structPlayerConfig.customColorID);\n\t\tloadoutBuilder.add_carId(structPlayerConfig.carID);\n\t\tloadoutBuilder.add_decalId(structPlayerConfig.decalID);\n\t\tloadoutBuilder.add_wheelsId(structPlayerConfig.wheelsID);\n\t\tloadoutBuilder.add_boostId(structPlayerConfig.boostID);\n\t\tloadoutBuilder.add_antennaId(structPlayerConfig.antennaID);\n\t\tloadoutBuilder.add_hatId(structPlayerConfig.hatID);\n\t\tloadoutBuilder.add_paintFinishId(structPlayerConfig.paintFinishID);\n\t\tloadoutBuilder.add_customFinishId(structPlayerConfig.customFinishID);\n\t\tloadoutBuilder.add_engineAudioId(structPlayerConfig.engineAudioID);\n\t\tloadoutBuilder.add_trailsId(structPlayerConfig.trailsID);\n\t\tloadoutBuilder.add_goalExplosionId(structPlayerConfig.goalExplosionID);\n\t\tloadoutBuilder.add_loadoutPaint(paintOffset);\n\t\tif (structPlayerConfig.useRgbLookup)\n\t\t{\n\t\t\tloadoutBuilder.add_primaryColorLookup(primaryColorOffset);\n\t\t\tloadoutBuilder.add_secondaryColorLookup(secondaryColorOffset);\n\t\t}\n\n\t\treturn loadoutBuilder.Finish();\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::PlayerConfiguration> buildPlayerConfiguration(flatbuffers::FlatBufferBuilder* builder, PlayerConfiguration structPlayerConfig)\n\t{\n\t\tauto name = builder->CreateString(convertString(structPlayerConfig.name));\n\t\tauto loadout = buildPlayerLoadout(builder, structPlayerConfig);\n\n\t\tflatbuffers::Offset<void> player;\n\t\trlbot::flat::PlayerClass variety;\n\t\tif (structPlayerConfig.bot)\n\t\t{\n\t\t\tif (structPlayerConfig.rlbotControlled)\n\t\t\t{\n\t\t\t\tvariety = rlbot::flat::PlayerClass_RLBotPlayer;\n\t\t\t\tplayer = rlbot::flat::CreateRLBotPlayer(*builder).Union();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tvariety = rlbot::flat::PlayerClass_PsyonixBotPlayer;\n\t\t\t\tplayer = rlbot::flat::CreatePsyonixBotPlayer(*builder, structPlayerConfig.botSkill).Union();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (structPlayerConfig.rlbotControlled)\n\t\t\t{\n\t\t\t\tvariety = rlbot::flat::PlayerClass_PartyMemberBotPlayer;\n\t\t\t\tplayer = rlbot::flat::CreatePartyMemberBotPlayer(*builder).Union();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tvariety = rlbot::flat::PlayerClass_HumanPlayer;\n\t\t\t\tplayer = rlbot::flat::CreateHumanPlayer(*builder).Union();\n\t\t\t}\n\t\t}\n\n\n\t\trlbot::flat::PlayerConfigurationBuilder configBuilder(*builder);\n\t\tconfigBuilder.add_name(name);\n\t\tconfigBuilder.add_loadout(loadout);\n\t\tconfigBuilder.add_team(structPlayerConfig.team);\n\t\tconfigBuilder.add_variety(player);\n\t\tconfigBuilder.add_variety_type(variety);\n\t\tconfigBuilder.add_spawnId(structPlayerConfig.spawnId);\n\n\t\treturn configBuilder.Finish();\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::MutatorSettings> buildMutatorSettings(flatbuffers::FlatBufferBuilder* builder, MutatorSettings structMutators)\n\t{\n\t\trlbot::flat::MutatorSettingsBuilder mutatorBuilder(*builder);\n\t\t// We rely on the enums in the flatbuffer being in the exact same order as the ones in the struct, and therefore being numbered the same.\n\t\tmutatorBuilder.add_matchLength(static_cast<rlbot::flat::MatchLength>(structMutators.matchLength));\n\t\tmutatorBuilder.add_maxScore(static_cast<rlbot::flat::MaxScore>(structMutators.maxScore));\n\t\tmutatorBuilder.add_overtimeOption(static_cast<rlbot::flat::OvertimeOption>(structMutators.overtimeOptions));\n\t\tmutatorBuilder.add_seriesLengthOption(static_cast<rlbot::flat::SeriesLengthOption>(structMutators.seriesLengthOptions));\n\t\tmutatorBuilder.add_gameSpeedOption(static_cast<rlbot::flat::GameSpeedOption>(structMutators.gameSpeedOptions));\n\t\tmutatorBuilder.add_ballMaxSpeedOption(static_cast<rlbot::flat::BallMaxSpeedOption>(structMutators.ballMaxSpeedOptions));\n\t\tmutatorBuilder.add_ballTypeOption(static_cast<rlbot::flat::BallTypeOption>(structMutators.ballTypeOptions));\n\t\tmutatorBuilder.add_ballWeightOption(static_cast<rlbot::flat::BallWeightOption>(structMutators.ballWeightOptions));\n\t\tmutatorBuilder.add_ballSizeOption(static_cast<rlbot::flat::BallSizeOption>(structMutators.ballSizeOptions));\n\t\tmutatorBuilder.add_ballBouncinessOption(static_cast<rlbot::flat::BallBouncinessOption>(structMutators.ballBouncinessOptions));\n\t\tmutatorBuilder.add_boostOption(static_cast<rlbot::flat::BoostOption>(structMutators.boostOptions));\n\t\tmutatorBuilder.add_rumbleOption(static_cast<rlbot::flat::RumbleOption>(structMutators.rumbleOptions));\n\t\tmutatorBuilder.add_boostStrengthOption(static_cast<rlbot::flat::BoostStrengthOption>(structMutators.boostStrengthOptions));\n\t\tmutatorBuilder.add_gravityOption(static_cast<rlbot::flat::GravityOption>(structMutators.gravityOptions));\n\t\tmutatorBuilder.add_demolishOption(static_cast<rlbot::flat::DemolishOption>(structMutators.demolishOptions));\n\t\tmutatorBuilder.add_respawnTimeOption(static_cast<rlbot::flat::RespawnTimeOption>(structMutators.respawnTimeOptions));\n\t\treturn mutatorBuilder.Finish();\n\t}\n\n\n\tbool BuildStartMatchMessage(flatbuffers::FlatBufferBuilder* builder, MatchSettings matchSettings)\n\t{\n\t\tstd::vector<flatbuffers::Offset<rlbot::flat::PlayerConfiguration>> playerConfigOffsets;\n\n\t\tfor (int i = 0; i < matchSettings.numPlayers; i++)\n\t\t{\n\t\t\tplayerConfigOffsets.push_back(buildPlayerConfiguration(builder, matchSettings.playerConfiguration[i]));\n\t\t}\n\n\t\tauto matchSettingsFlat = rlbot::flat::CreateMatchSettings(\n\t\t\t*builder,\n\t\t\tbuilder->CreateVector(playerConfigOffsets),\n\t\t\tstatic_cast<rlbot::flat::GameMode>(matchSettings.gameMode),\n\t\t\tstatic_cast<rlbot::flat::GameMap>(matchSettings.gameMap),\n\t\t\tmatchSettings.skipReplays,\n\t\t\tmatchSettings.instantStart,\n\t\t\tbuildMutatorSettings(builder, matchSettings.mutatorSettings),\n\t\t\tstatic_cast<rlbot::flat::ExistingMatchBehavior>(matchSettings.existingMatchBehavior),\n\t\t\tmatchSettings.enableLockstep,\n\t\t\tmatchSettings.enableRendering,\n\t\t\tmatchSettings.enableStateSetting,\n\t\t\tmatchSettings.autoSaveReplay);\n\n\t\tbuilder->Finish(matchSettingsFlat);\n\n\t\treturn true;\n\t}\n\n\trlbot::flat::Quaternion createQuaternion(Quaternion structQuaternion)\n\t{\n\t\treturn rlbot::flat::Quaternion(structQuaternion.x, structQuaternion.y, structQuaternion.z, structQuaternion.w);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::RigidBodyState> createRigidBodyState(flatbuffers::FlatBufferBuilder* builder, RigidBodyState state)\n\t{\n\t\tauto location = createVector3(state.location);\n\t\tauto rotation = createQuaternion(state.rotation);\n\t\tauto velocity = createVector3(state.velocity);\n\t\tauto angular = createVector3(state.angularVelocity);\n\n\t\treturn rlbot::flat::CreateRigidBodyState(*builder, state.frame, &location, &rotation, &velocity, &angular);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::ControllerState> createControllerState(flatbuffers::FlatBufferBuilder* builder, PlayerInput structPlayerInput)\n\t{\n\t\treturn rlbot::flat::CreateControllerState(*builder,\n\t\t\tstructPlayerInput.throttle,\n\t\t\tstructPlayerInput.steer,\n\t\t\tstructPlayerInput.pitch,\n\t\t\tstructPlayerInput.yaw,\n\t\t\tstructPlayerInput.roll,\n\t\t\tstructPlayerInput.jump,\n\t\t\tstructPlayerInput.boost,\n\t\t\tstructPlayerInput.handbrake,\n\t\t\tstructPlayerInput.useItem);\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::PlayerRigidBodyState> createPlayerRigid(flatbuffers::FlatBufferBuilder* builder, PlayerRigidBodyState stateStruct)\n\t{\n\t\tauto state = createRigidBodyState(builder, stateStruct.state);\n\t\tauto input = createControllerState(builder, stateStruct.input);\n\n\t\treturn rlbot::flat::CreatePlayerRigidBodyState(*builder, state, input);\n\n\t}\n\n\tflatbuffers::Offset<rlbot::flat::BallRigidBodyState> createBallRigidBody(flatbuffers::FlatBufferBuilder* builder, BallRigidBodyState structBallState)\n\t{\n\t\treturn rlbot::flat::CreateBallRigidBodyState(*builder, createRigidBodyState(builder, structBallState.state));\n\t}\n\n\tbool FillRigidBody(flatbuffers::FlatBufferBuilder* builder, RigidBodyTick rigidBodyTick)\n\t{\n\t\tstd::vector<flatbuffers::Offset<rlbot::flat::PlayerRigidBodyState>> players;\n\t\tflatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<rlbot::flat::PlayerRigidBodyState>>> playersOffset;\n\n\n\t\tfor (int i = 0; i < rigidBodyTick.numPlayers; i++)\n\t\t{\n\t\t\tplayers.push_back(createPlayerRigid(builder, rigidBodyTick.players[i]));\n\t\t}\n\n\t\tplayersOffset = builder->CreateVector(players);\n\n\t\tflatbuffers::Offset<rlbot::flat::BallRigidBodyState> ballOffset;\n\n\t\tballOffset = createBallRigidBody(builder, rigidBodyTick.ball);\n\n\t\tauto tickOffset = rlbot::flat::CreateRigidBodyTick(*builder, ballOffset, playersOffset);\n\n\t\tbuilder->Finish(tickOffset);\n\n\t\treturn true;\n\t}\n}\n", "meta": {"hexsha": "3bb03048c4b753837464a3c7c22ae37034d1b3f0", "size": 20131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/cpp/RLBotInterface/src/RLBotMessages/MessageTranslation/StructToRlbotFlatbuffer.cpp", "max_stars_repo_name": "dvptl68/RLBot", "max_stars_repo_head_hexsha": "e3cc4d2d7f04ec846b219e274e9633623859179b", "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/RLBotInterface/src/RLBotMessages/MessageTranslation/StructToRlbotFlatbuffer.cpp", "max_issues_repo_name": "dvptl68/RLBot", "max_issues_repo_head_hexsha": "e3cc4d2d7f04ec846b219e274e9633623859179b", "max_issues_repo_licenses": ["MIT"], "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/RLBotInterface/src/RLBotMessages/MessageTranslation/StructToRlbotFlatbuffer.cpp", "max_forks_repo_name": "dvptl68/RLBot", "max_forks_repo_head_hexsha": "e3cc4d2d7f04ec846b219e274e9633623859179b", "max_forks_repo_licenses": ["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.2107208872, "max_line_length": 160, "alphanum_fraction": 0.7852068948, "num_tokens": 5186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.1770500253285444}}
{"text": "/*\n    Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@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#include \"hashstore.hpp\"\n\n#include \"../lib/hashtree.hpp\"\n\n#include <algorithm>\n#include <sstream>\n\n#include <boost/filesystem.hpp>\n#include <boost/smart_ptr/make_shared.hpp>\n#include <netinet/in.h>\n\nusing namespace std;\nusing namespace bithorded::store;\n\nnamespace io = boost::iostreams;\nnamespace fs = boost::filesystem;\n\nbithorded::store::TigerNode::TigerNode(HashStore& metaFile, size_t offset) :\n\tTigerBaseNode(metaFile.read(offset)),\n\t_metaFile(metaFile),\n\t_offset(offset),\n\t_unmodified(*this)\n{\n}\n\nbithorded::store::TigerNode::~TigerNode()\n{\n\tif (_unmodified != *static_cast<TigerBaseNode*>(this)) {\n\t\t_metaFile.write(_offset, *this);\n\t}\n}\n\nHashStore::HashStore( const bithorded::IDataArray::Ptr& storage, uint8_t hashLevelsSkipped )\n\t: _storage(storage), _hashLevelsSkipped(hashLevelsSkipped)\n{\n\tif (_storage->size() == 0) {\n\t\tthrow ios_base::failure(\"Hash storage of size 0 is pointless; \"+storage->describe());\n\t} else if (_storage->size() % sizeof(TigerBaseNode)) {\n\t\tthrow ios_base::failure(\"Hash storage not even multiple of nodes; \"+storage->describe());\n\t}\n}\n\nHashStore::NodePtr HashStore::operator[](const size_t offset)\n{\n\tif (auto node = _nodeMap[offset]) {\n\t\treturn node;\n\t} else {\n\t\tauto res = boost::make_shared<TigerNode>(*this, offset);\n\t\t_nodeMap.set(offset, res);\n\t\treturn res;\n\t}\n}\n\nsize_t HashStore::size() const\n{\n\treturn _storage->size() / sizeof(TigerBaseNode);\n}\n\nTigerBaseNode HashStore::read(size_t offset) const\n{\n\tuint64_t f_offset = offset*sizeof(TigerBaseNode);\n\tTigerBaseNode res;\n\tauto read = _storage->read(f_offset, sizeof(TigerBaseNode), reinterpret_cast<byte*>(&res));\n\tif (read != sizeof(TigerBaseNode)) {\n\t\tostringstream buf;\n\t\tbuf << \"Failed reading node at offset \" << offset;\n\t\tthrow ios_base::failure(buf.str());\n\t}\n\treturn res;\n}\n\nvoid HashStore::write(size_t offset, const TigerBaseNode& node)\n{\n\tuint64_t f_offset = offset*sizeof(TigerBaseNode);\n\tauto written = _storage->write(f_offset, reinterpret_cast<const byte*>(&node), sizeof(TigerBaseNode));\n\tif (written != sizeof(TigerBaseNode)) {\n\t\tostringstream buf;\n\t\tbuf << \"Failed writing node at offset \" << offset;\n\t\tthrow ios_base::failure(buf.str());\n\t}\n}\n\nuint64_t HashStore::atoms_needed_for_content ( uint64_t content_size ) {\n\tauto atomSize = TreeHasher<Node::HashAlgorithm>::ATOMSIZE;\n\treturn (content_size + atomSize - 1) / atomSize;\n}\n\nuint64_t HashStore::leaves_needed_for_atoms ( uint64_t atoms, uint8_t levelsSkipped ) {\n\tauto stored_leaves = atoms >> levelsSkipped;\n\tif ((stored_leaves << levelsSkipped) != atoms) { // Check for overflow\n\t\tstored_leaves += 1;\n\t}\n\treturn stored_leaves;\n}\n\nuint64_t HashStore::leaves_needed_for_content ( uint64_t content_size, uint8_t levelsSkipped ) {\n\treturn leaves_needed_for_atoms(atoms_needed_for_content(content_size), levelsSkipped);\n}\n\nuint64_t HashStore::nodes_needed_for_atoms ( uint64_t atoms, uint8_t levelsSkipped ) {\n\treturn treesize(leaves_needed_for_atoms(atoms, levelsSkipped));\n}\n\nuint64_t HashStore::nodes_needed_for_content ( uint64_t content_size, uint8_t levelsSkipped ) {\n\treturn nodes_needed_for_atoms(atoms_needed_for_content(content_size), levelsSkipped);\n}\n\nuint64_t HashStore::size_needed_for_atoms ( uint64_t atoms, uint8_t levelsSkipped ) {\n\treturn nodes_needed_for_atoms(atoms, levelsSkipped) * sizeof(Node);\n}\n\nuint64_t HashStore::size_needed_for_content ( uint64_t content_size, uint8_t levelsSkipped ) {\n\treturn size_needed_for_atoms(atoms_needed_for_content(content_size), levelsSkipped);\n}\n", "meta": {"hexsha": "58d0de7e93c50abf553b997e37bfc6fd4400d724", "size": 4106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bithorded/store/hashstore.cpp", "max_stars_repo_name": "zidz/bithorde", "max_stars_repo_head_hexsha": "dbaa67eb0ddfa7d28e5325d87428c1b0225d598b", "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": "bithorded/store/hashstore.cpp", "max_issues_repo_name": "zidz/bithorde", "max_issues_repo_head_hexsha": "dbaa67eb0ddfa7d28e5325d87428c1b0225d598b", "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": "bithorded/store/hashstore.cpp", "max_forks_repo_name": "zidz/bithorde", "max_forks_repo_head_hexsha": "dbaa67eb0ddfa7d28e5325d87428c1b0225d598b", "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.3435114504, "max_line_length": 103, "alphanum_fraction": 0.7532878714, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.177046143019406}}
{"text": "/*****************************************************************************************************************\n * ReelRobotix Inc. - Software License Agreement      Copyright (c) 2018\n * \t Authors: Pablo Inigo Blasco, Brett Aldrich\n *\n ******************************************************************************************************************/\n#include <angles/angles.h>\n#include <pluginlib/class_list_macros.h>\n#include <forward_local_planner/forward_local_planner.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <boost/intrusive_ptr.hpp>\n#include <angles/angles.h>\n\n#include <base_local_planner/simple_trajectory_generator.h>\n\n//register this planner as a BaseLocalPlanner plugin\nPLUGINLIB_EXPORT_CLASS(cl_move_base_z::forward_local_planner::ForwardLocalPlanner, nav_core::BaseLocalPlanner)\n\nnamespace cl_move_base_z\n{\nnamespace forward_local_planner\n{\n/**\n******************************************************************************************************************\n* ForwardLocalPlanner()\n******************************************************************************************************************\n*/\nForwardLocalPlanner::ForwardLocalPlanner()\n{\n}\n\n/**\n******************************************************************************************************************\n* ForwardLocalPlanner()\n******************************************************************************************************************\n*/\nForwardLocalPlanner::~ForwardLocalPlanner()\n{\n}\n\nvoid ForwardLocalPlanner::initialize()\n{\n    k_rho_ = 1.0;\n    k_alpha_ = -0.4;\n    k_betta_ = -1.0; // set to zero means that orientation is not important\n    //k_betta_ = 1.0;\n    //betta_offset_=0;\n\n    goalReached_ = false;\n    carrot_distance_ = 0.4;\n\n    ros::NodeHandle private_nh(\"~\");\n\n    currentPoseIndex_ = 0;\n\n    ros::NodeHandle nh(\"~/ForwardLocalPlanner\");\n\n    nh.param(\"k_rho\", k_rho_, k_rho_);\n    nh.param(\"k_alpha\", k_alpha_, k_alpha_);\n    nh.param(\"k_betta\", k_betta_, k_betta_);\n    nh.param(\"carrot_distance\", carrot_distance_, carrot_distance_);\n\n    nh.param(\"yaw_goal_tolerance\", yaw_goal_tolerance_, 0.05);\n    nh.param(\"xy_goal_tolerance\", xy_goal_tolerance_, 0.10);\n    nh.param(\"max_linear_x_speed\", max_linear_x_speed_, 1.0);\n    nh.param(\"max_angular_z_speed\", max_angular_z_speed_, 2.0);\n\n    ROS_INFO(\"[ForwardLocalPlanner] max linear speed: %lf, max angular speed: %lf, k_rho: %lf, carrot_distance: %lf, \", max_linear_x_speed_, max_angular_z_speed_, k_rho_, carrot_distance_);\n    goalMarkerPublisher_ = nh.advertise<visualization_msgs::MarkerArray>(\"goal_marker\", 1);\n\n    waiting_ = false;\n    waitingTimeout_ = ros::Duration(10);\n    ROS_INFO(\"[ForwardLocalPlanner] initialized\");\n}\n\nvoid ForwardLocalPlanner::initialize(std::string name, tf2_ros::Buffer *tf, costmap_2d::Costmap2DROS *costmap_ros)\n{\n    costmapRos_ = costmap_ros;\n    this->initialize();\n}\n\nvoid ForwardLocalPlanner::generateTrajectory(const Eigen::Vector3f &pos, const Eigen::Vector3f &vel, float maxdist, float maxanglediff, float maxtime, float dt, std::vector<Eigen::Vector3f> &outtraj)\n{\n    //simulate the trajectory and check for collisions, updating costs along the way\n    bool end = false;\n    float time = 0;\n    Eigen::Vector3f currentpos = pos;\n    int i = 0;\n    while (!end)\n    {\n        //add the point to the trajectory so we can draw it later if we want\n        //traj.addPoint(pos[0], pos[1], pos[2]);\n\n        // if (continued_acceleration_) {\n        //   //calculate velocities\n        //   loop_vel = computeNewVelocities(sample_target_vel, loop_vel, limits_->getAccLimits(), dt);\n        //   //ROS_WARN_NAMED(\"Generator\", \"Flag: %d, Loop_Vel %f, %f, %f\", continued_acceleration_, loop_vel[0], loop_vel[1], loop_vel[2]);\n        // }\n\n        auto loop_vel = vel;\n        //update the position of the robot using the velocities passed in\n        auto newpos = computeNewPositions(currentpos, loop_vel, dt);\n\n        auto dx = newpos[0] - currentpos[0];\n        auto dy = newpos[1] - currentpos[1];\n        float dist, angledist;\n\n        //ROS_INFO(\"traj point %d\", i);\n        dist = sqrt(dx * dx + dy * dy);\n        if (dist > maxdist)\n        {\n            end = true;\n            //ROS_INFO(\"dist break: %f\", dist);\n        }\n        else\n        {\n            // ouble from, double to\n            angledist = fabs(angles::shortest_angular_distance(currentpos[2], newpos[2]));\n            if (angledist > maxanglediff)\n            {\n                end = true;\n                //ROS_INFO(\"angle dist break: %f\", angledist);\n            }\n            else\n            {\n                outtraj.push_back(newpos);\n\n                time += dt;\n                if (time > maxtime)\n                {\n                    end = true;\n                    //ROS_INFO(\"time break: %f\", time);\n                }\n\n                //ROS_INFO(\"dist: %f, angledist: %f, time: %f\", dist, angledist, time);\n            }\n        }\n\n        currentpos = newpos;\n        i++;\n    } // end for simulation steps\n}\n\nEigen::Vector3f ForwardLocalPlanner::computeNewPositions(const Eigen::Vector3f &pos, const Eigen::Vector3f &vel, double dt)\n{\n    Eigen::Vector3f new_pos = Eigen::Vector3f::Zero();\n    new_pos[0] = pos[0] + (vel[0] * cos(pos[2]) + vel[1] * cos(M_PI_2 + pos[2])) * dt;\n    new_pos[1] = pos[1] + (vel[0] * sin(pos[2]) + vel[1] * sin(M_PI_2 + pos[2])) * dt;\n    new_pos[2] = pos[2] + vel[2] * dt;\n    return new_pos;\n}\n\n/**\n******************************************************************************************************************\n* initialize()\n******************************************************************************************************************\n*/\nvoid ForwardLocalPlanner::initialize(std::string name, tf::TransformListener *tf, costmap_2d::Costmap2DROS *costmap_ros)\n{\n    costmapRos_ = costmap_ros;\n    this->initialize();\n}\n\n/**\n******************************************************************************************************************\n* publishGoalMarker()\n******************************************************************************************************************\n*/\nvoid ForwardLocalPlanner::publishGoalMarker(double x, double y, double phi)\n{\n    visualization_msgs::Marker marker;\n\n    marker.header.frame_id = this->costmapRos_->getGlobalFrameID();\n    marker.header.stamp = ros::Time::now();\n    marker.ns = \"my_namespace2\";\n    marker.id = 0;\n    marker.type = visualization_msgs::Marker::ARROW;\n    marker.action = visualization_msgs::Marker::ADD;\n    marker.pose.orientation.w = 1;\n    \n    marker.scale.x = 0.1;\n    marker.scale.y = 0.3;\n    marker.scale.z = 0.1;\n    marker.color.a = 1.0;\n    marker.color.r = 0;\n    marker.color.g = 0;\n    marker.color.b = 1.0;\n\n    geometry_msgs::Point start, end;\n    start.x = x;\n    start.y = y;\n\n    end.x = x + 0.5 * cos(phi);\n    end.y = y + 0.5 * sin(phi);\n\n    marker.points.push_back(start);\n    marker.points.push_back(end);\n\n    visualization_msgs::MarkerArray ma;\n    ma.markers.push_back(marker);\n\n    this->goalMarkerPublisher_.publish(ma);\n}\n\n// MELODIC\n#if ROS_VERSION_MINIMUM(1, 13, 0)\ntf::Stamped<tf::Pose> optionalRobotPose(costmap_2d::Costmap2DROS *costmapRos)\n{\n    geometry_msgs::PoseStamped paux;\n    costmapRos->getRobotPose(paux);\n    tf::Stamped<tf::Pose> tfpose;\n    tf::poseStampedMsgToTF(paux, tfpose);\n    return tfpose;\n}\n#else\n// INDIGO AND PREVIOUS\ntf::Stamped<tf::Pose> optionalRobotPose(costmap_2d::Costmap2DROS *costmapRos)\n{\n    tf::Stamped<tf::Pose> tfpose;\n    costmapRos->getRobotPose(tfpose);\n    return tfpose;\n}\n#endif\n\nvoid clamp(geometry_msgs::Twist &cmd_vel, double max_linear_x_speed_, double max_angular_z_speed_)\n{\n    if (max_angular_z_speed_ == 0 || max_linear_x_speed_ == 0)\n        return;\n\n    if (cmd_vel.angular.z == 0)\n    {\n        cmd_vel.linear.x = max_linear_x_speed_;\n    }\n    else\n    {\n        double kurvature = cmd_vel.linear.x / cmd_vel.angular.z;\n\n        double linearAuthority = fabs(cmd_vel.linear.x / max_linear_x_speed_);\n        double angularAuthority = fabs(cmd_vel.angular.z / max_angular_z_speed_);\n        if (linearAuthority < angularAuthority)\n        {\n            // lets go to maximum linear speed\n            cmd_vel.linear.x = max_linear_x_speed_;\n            cmd_vel.angular.z = kurvature / max_linear_x_speed_;\n            ROS_WARN_STREAM(\"k=\" << kurvature << \"lets go to maximum linear capacity: \" << cmd_vel);\n        }\n        else\n        {\n            // lets go with maximum angular speed\n            cmd_vel.angular.x = max_angular_z_speed_;\n            cmd_vel.linear.x = kurvature * max_angular_z_speed_;\n            ROS_WARN_STREAM(\"lets go to maximum angular capacity: \" << cmd_vel);\n        }\n    }\n}\n\n/**\n******************************************************************************************************************\n* computeVelocityCommands()\n******************************************************************************************************************\n*/\nbool ForwardLocalPlanner::computeVelocityCommands(geometry_msgs::Twist &cmd_vel)\n{\n    goalReached_ = false;\n    ROS_DEBUG(\"[ForwardLocalPlanner] ----- COMUTE VELOCITY COMMAND LOCAL PLANNER ---\");\n\n    tf::Stamped<tf::Pose> tfpose = optionalRobotPose(costmapRos_);\n\n    geometry_msgs::PoseStamped currentPose;\n    tf::poseStampedTFToMsg(tfpose,currentPose);\n    ROS_DEBUG_STREAM(\"[ForwardLocalPlanner] current robot pose \" << currentPose);\n\n\n    bool ok = false;\n    while (!ok)\n    {\n        // iterate the point from the current position and ahead until reaching a new goal point in the path\n        while (!ok && currentPoseIndex_ < plan_.size())\n        {\n            auto &pose = plan_[currentPoseIndex_];\n            const geometry_msgs::Point &p = pose.pose.position;\n            tf::Quaternion q;\n            tf::quaternionMsgToTF(pose.pose.orientation, q);\n\n            // take error from the current position to the path point\n            double dx = p.x - tfpose.getOrigin().x();\n            double dy = p.y - tfpose.getOrigin().y();\n            double dist = sqrt(dx * dx + dy * dy);\n\n            double pangle = tf::getYaw(q);\n            double angle = tf::getYaw(tfpose.getRotation());\n            double angular_error = angles::shortest_angular_distance(pangle, angle);\n\n            if (dist >= carrot_distance_ || fabs(angular_error) > 0.1)\n            {\n                // the target pose is enough different to be defined as a target\n                ok = true;\n                ROS_DEBUG(\"current index: %d, carrot goal percentaje: %lf, dist: %lf, maxdist: %lf, angle_error: %lf\", currentPoseIndex_, 100.0 * currentPoseIndex_ / plan_.size(), dist, carrot_distance_, angular_error);\n            }\n            else\n            {\n                currentPoseIndex_++;\n            }\n        }\n\n        ROS_DEBUG_STREAM(\"[ForwardLocalPlanner] selected carrot pose index \" << currentPoseIndex_ << \"/\" << plan_.size());\n\n        if (currentPoseIndex_ >= plan_.size())\n        {\n            // even the latest point is quite similar, then take the last since it is the final goal\n            cmd_vel.linear.x = 0;\n            cmd_vel.angular.z = 0;\n            //ROS_INFO(\"End Local planner\");\n            ok = true;\n            currentPoseIndex_ = plan_.size() - 1;\n            //return true;\n        }\n    }\n\n    //ROS_INFO(\"pose control algorithm\");\n\n    const geometry_msgs::PoseStamped &finalgoalpose = plan_.back();\n    const geometry_msgs::PoseStamped &carrot_goalpose = plan_[currentPoseIndex_];\n    const geometry_msgs::Point &goalposition = carrot_goalpose.pose.position;\n\n    tf::Quaternion carrotGoalQ;\n    tf::quaternionMsgToTF(carrot_goalpose.pose.orientation, carrotGoalQ);\n    //ROS_INFO_STREAM(\"Plan goal quaternion at \"<< goalpose.pose.orientation);\n\n    //goal orientation (global frame)\n    double betta = tf::getYaw(carrot_goalpose.pose.orientation) + betta_offset_;\n\n    double dx = goalposition.x - tfpose.getOrigin().x();\n    double dy = goalposition.y - tfpose.getOrigin().y();\n\n    //distance error to the targetpoint\n    double rho_error = sqrt(dx * dx + dy * dy);\n\n    //current angle\n    tf::Quaternion currentOrientation = tfpose.getRotation();\n    double theta = tf::getYaw(currentOrientation);\n    double alpha = atan2(dy, dx);\n    alpha = alpha + alpha_offset_;\n\n    double alpha_error = angles::shortest_angular_distance(alpha, theta);\n    double betta_error = angles::shortest_angular_distance(betta, theta);\n\n    double vetta; // = k_rho_ * rho_error;\n    double gamma; //= k_alpha_ * alpha_error + k_betta_ * betta_error;\n\n    if (rho_error > xy_goal_tolerance_) // reguular control rule, be careful, rho error is with the carrot not with the final goal (this is something to improve like the backwards planner)\n    {\n        vetta = k_rho_ * rho_error;\n        gamma = k_alpha_ * alpha_error;\n    }\n    else if (fabs(betta_error) >= yaw_goal_tolerance_) // pureSpining\n    {\n        vetta = 0;\n        gamma = k_betta_ * betta_error;\n    }\n    else // goal reached\n    {\n        ROS_DEBUG(\"GOAL REACHED\");\n        vetta = 0;\n        gamma = 0;\n        goalReached_ = true;\n    }\n\n    // linear speed clamp\n    if (vetta > max_linear_x_speed_)\n    {\n        vetta = max_linear_x_speed_;\n    }\n    else if (vetta < -max_linear_x_speed_)\n    {\n        vetta = -max_linear_x_speed_;\n    }\n\n    // angular speed clamp\n    if (gamma > max_angular_z_speed_)\n    {\n        gamma = max_angular_z_speed_;\n    }\n    else if (gamma < -max_angular_z_speed_)\n    {\n        gamma = -max_angular_z_speed_;\n    }\n\n    cmd_vel.linear.x = vetta;\n    cmd_vel.angular.z = gamma;\n\n    //clamp(cmd_vel, max_linear_x_speed_, max_angular_z_speed_);\n\n    //ROS_INFO_STREAM(\"Local planner: \"<< cmd_vel);\n\n    publishGoalMarker(goalposition.x, goalposition.y, betta);\n\n    ROS_DEBUG_STREAM(\"Forward local planner,\" << std::endl\n                                              << \" theta: \" << theta << std::endl\n                                              << \" betta: \" << betta << std::endl\n                                              << \" err_x: \" << dx << std::endl\n                                              << \" err_y:\" << dy << std::endl\n                                              << \" rho_error:\" << rho_error << std::endl\n                                              << \" alpha_error:\" << alpha_error << std::endl\n                                              << \" betta_error:\" << betta_error << std::endl\n                                              << \" vetta:\" << vetta << std::endl\n                                              << \" gamma:\" << gamma << std::endl\n                                              << \" xy_goal_tolerance:\" << xy_goal_tolerance_ << std::endl\n                                              << \" yaw_goal_tolerance:\" << yaw_goal_tolerance_ << std::endl);\n\n    //if(cmd_vel.linear.x==0 && cmd_vel.angular.z == 0 )\n    //{\n    //}\n\n    //integrate trajectory and check collision\n\n    tf::Stamped<tf::Pose> global_pose = optionalRobotPose(costmapRos_);\n\n    //->getRobotPose(global_pose);\n\n    auto *costmap2d = costmapRos_->getCostmap();\n    auto yaw = tf::getYaw(global_pose.getRotation());\n\n    auto &pos = global_pose.getOrigin();\n\n    Eigen::Vector3f currentpose(pos.x(), pos.y(), yaw);\n    Eigen::Vector3f currentvel(cmd_vel.linear.x, cmd_vel.linear.y, cmd_vel.angular.z);\n    std::vector<Eigen::Vector3f> trajectory;\n    this->generateTrajectory(currentpose, currentvel, 0.8 /*meters*/, M_PI / 8 /*rads*/, 3.0 /*seconds*/, 0.05 /*seconds*/, trajectory);\n\n    // check plan rejection\n    bool aceptedplan = true;\n\n    unsigned int mx, my;\n\n    int i = 0;\n    // ROS_INFO_STREAM(\"lplanner goal: \" << finalgoalpose.pose.position);\n    for (auto &p : trajectory)\n    {\n        float dx = p[0] - finalgoalpose.pose.position.x;\n        float dy = p[1] - finalgoalpose.pose.position.y;\n\n        float dst = sqrt(dx * dx + dy * dy);\n        if (dst < xy_goal_tolerance_)\n        {\n            //  ROS_INFO(\"trajectory checking skipped, goal reached\");\n            break;\n        }\n\n        costmap2d->worldToMap(p[0], p[1], mx, my);\n        unsigned int cost = costmap2d->getCost(mx, my);\n\n        // ROS_INFO(\"checking cost pt %d [%lf, %lf] cell[%d,%d] = %d\", i, p[0], p[1], mx, my, cost);\n        // ROS_INFO_STREAM(\"cost: \" << cost);\n\n        // static const unsigned char NO_INFORMATION = 255;\n        // static const unsigned char LETHAL_OBSTACLE = 254;\n        // static const unsigned char INSCRIBED_INFLATED_OBSTACLE = 253;\n        // static const unsigned char FREE_SPACE = 0;\n\n        if (costmap2d->getCost(mx, my) >= costmap_2d::INSCRIBED_INFLATED_OBSTACLE)\n        {\n            aceptedplan = false;\n            // ROS_WARN(\"ABORTED LOCAL PLAN BECAUSE OBSTACLE DETEDTED\");\n            break;\n        }\n        i++;\n    }\n\n    if (aceptedplan)\n    {\n        waiting_ = false;\n        return true;\n    }\n    else\n    {\n        // stop and wait\n        cmd_vel.linear.x = 0;\n        cmd_vel.angular.z = 0;\n\n        if (waiting_ == false)\n        {\n            waiting_ = true;\n            waitingStamp_ = ros::Time::now();\n        }\n        else\n        {\n            auto waitingduration = ros::Time::now() - waitingStamp_;\n\n            if (waitingduration > this->waitingTimeout_)\n            {\n                return false;\n            }\n        }\n\n        return true;\n    }\n}\n\n/**\n******************************************************************************************************************\n* isGoalReached()\n******************************************************************************************************************\n*/\nbool ForwardLocalPlanner::isGoalReached()\n{\n    return goalReached_;\n}\n\n/**\n******************************************************************************************************************\n* setPlan()\n******************************************************************************************************************\n*/\nbool ForwardLocalPlanner::setPlan(const std::vector<geometry_msgs::PoseStamped> &plan)\n{\n    plan_ = plan;\n    goalReached_ = false;\n    return true;\n}\n} // namespace forward_local_planner\n} // namespace cl_move_base_z", "meta": {"hexsha": "36a9b34586ddc695afef068ce1f993858c646eda", "size": 18128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "smacc_client_library/move_base_z_client/custom_planners/forward_local_planner/src/forward_local_planner.cpp", "max_stars_repo_name": "tylerjw/SMACC", "max_stars_repo_head_hexsha": "76dceb90411c2e4b13e4ae78c0af67d1acfb3333", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 203.0, "max_stars_repo_stars_event_min_datetime": "2019-04-11T16:42:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T06:02:56.000Z", "max_issues_repo_path": "smacc_client_library/move_base_z_client/custom_planners/forward_local_planner/src/forward_local_planner.cpp", "max_issues_repo_name": "tylerjw/SMACC", "max_issues_repo_head_hexsha": "76dceb90411c2e4b13e4ae78c0af67d1acfb3333", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 50.0, "max_issues_repo_issues_event_min_datetime": "2019-04-18T09:09:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:38:21.000Z", "max_forks_repo_path": "smacc_client_library/move_base_z_client/custom_planners/forward_local_planner/src/forward_local_planner.cpp", "max_forks_repo_name": "tylerjw/SMACC", "max_forks_repo_head_hexsha": "76dceb90411c2e4b13e4ae78c0af67d1acfb3333", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2019-09-10T15:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T09:10:08.000Z", "avg_line_length": 34.7946257198, "max_line_length": 219, "alphanum_fraction": 0.5434686673, "num_tokens": 4203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.17704613958260626}}
{"text": "/******************************************************************************\r\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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#ifndef MODULES_LOCALIZATION_MSF_LOCAL_GNSS_GNSS_UTILITY_HPP_\r\n#define MODULES_LOCALIZATION_MSF_LOCAL_GNSS_GNSS_UTILITY_HPP_\r\n\r\n#include <math.h>\r\n#include <stdarg.h>\r\n#include <Eigen/Eigen>\r\n#include <string>\r\n#include <vector>\r\n#include \"modules/localization/msf/local_gnss/gnss_constants.hpp\"\r\n\r\n#include \"modules/localization/proto/gnss_pnt_result.pb.h\"\r\n#include \"modules/drivers/gnss/proto/gnss_raw_observation.pb.h\"\r\n\r\nnamespace apollo {\r\nnamespace localization {\r\nnamespace local_gnss {\r\n\r\ntypedef apollo::drivers::gnss::GnssType GnssType;\r\ntypedef apollo::drivers::gnss::GnssBandID GnssBandID;\r\ntypedef apollo::drivers::gnss::EpochObservation EpochObservation;\r\ntypedef apollo::drivers::gnss::SatelliteObservation SatelliteObservation;\r\ntypedef apollo::drivers::gnss::BandObservation BandObservation;\r\ntypedef apollo::drivers::gnss::GlonassOrbit GlonassOrbit;\r\ntypedef apollo::drivers::gnss::GnssEphemeris GnssEphemeris;\r\ntypedef apollo::drivers::gnss::KepplerOrbit KepplerOrbit;\r\n\r\nstruct PointThreeDim {\r\n  double x;\r\n  double y;\r\n  double z;\r\n  PointThreeDim() {\r\n    x = 0.0;\r\n    y = 0.0;\r\n    z = 0.0;\r\n  }\r\n\r\n  PointThreeDim(double t_x, double t_y, double t_z) {\r\n    x = t_x;\r\n    y = t_y;\r\n    z = t_z;\r\n  }\r\n\r\n  PointThreeDim& operator=(const PointThreeDim& p2) {\r\n    x = p2.x;\r\n    y = p2.y;\r\n    z = p2.z;\r\n    return *this;\r\n  }\r\n\r\n  PointThreeDim& operator+=(const PointThreeDim& p2) {\r\n    x = x + p2.x;\r\n    y = y + p2.y;\r\n    z = z + p2.z;\r\n    return *this;\r\n  }\r\n\r\n  PointThreeDim operator+(const PointThreeDim& p2) {\r\n    PointThreeDim t;\r\n    t.x = this->x + p2.x;\r\n    t.y = this->y + p2.y;\r\n    t.z = this->z + p2.z;\r\n    return t;\r\n  }\r\n\r\n  PointThreeDim operator-(const PointThreeDim& p2) {\r\n    PointThreeDim t;\r\n    t.x = this->x - p2.x;\r\n    t.y = this->y - p2.y;\r\n    t.z = this->z - p2.z;\r\n    return t;\r\n  }\r\n\r\n  PointThreeDim SquareRoot() {\r\n    PointThreeDim t;\r\n    t.x = sqrt(x);\r\n    t.y = sqrt(y);\r\n    t.z = sqrt(z);\r\n    return t;\r\n  }\r\n\r\n  PointThreeDim operator/(const double scale) {\r\n    PointThreeDim t;\r\n    t.x = x / scale;\r\n    t.y = y / scale;\r\n    t.z = z / scale;\r\n    return t;\r\n  }\r\n\r\n  PointThreeDim operator*(const double scale) {\r\n    PointThreeDim t;\r\n    t.x = x * scale;\r\n    t.y = y * scale;\r\n    t.z = z * scale;\r\n    return t;\r\n  }\r\n\r\n  double Norm3D() { return sqrt(x * x + y * y + z * z); }\r\n\r\n  double GetDistance(const PointThreeDim& dest) {\r\n    double dist = 0.0;\r\n    dist += (x - dest.x) * (x - dest.x);\r\n    dist += (y - dest.y) * (y - dest.y);\r\n    dist += (z - dest.z) * (z - dest.z);\r\n    return sqrt(dist);\r\n  }\r\n};\r\n\r\nstruct SatelliteInfor {\r\n  short sat_prn; // NOLINT\r\n  GnssType sat_sys;\r\n  int index_in_obs;\r\n  double clock_bias;\r\n  double clock_drift;\r\n  PointThreeDim position;\r\n  PointThreeDim velocity;\r\n  PointThreeDim direction;\r\n  double distance;\r\n  double elevation;\r\n  double azimuth;\r\n  bool multi_path;\r\n  // week_num * SECOND_PER_WEEK + week_second_s\r\n  double toe;\r\n  unsigned int gnss_week;\r\n  double time_signal_transmitted;\r\n  double time_travles;\r\n  SatelliteInfor() {\r\n    sat_prn = 0;\r\n    sat_sys = apollo::drivers::gnss::SYS_UNKNOWN;\r\n    index_in_obs = -1;\r\n    clock_bias = 0;\r\n    clock_drift = 0;\r\n    distance = 0;\r\n    elevation = 0;\r\n    azimuth = 0;\r\n    multi_path = false;\r\n    toe = -0.1;\r\n    gnss_week = 0;\r\n    time_signal_transmitted = 0.0;\r\n    time_travles = 0.0;\r\n  }\r\n  bool IsSameSatellite(const SatelliteInfor& other) {\r\n    return (sat_sys == other.sat_sys && sat_prn == other.sat_prn);\r\n  }\r\n  bool operator==(const SatelliteInfor& other) const {\r\n    return (sat_sys == other.sat_sys && sat_prn == other.sat_prn);\r\n  }\r\n  void PrintSat(const bool& b_print = false) {\r\n    if (!b_print) {\r\n      return;\r\n    }\r\n    printf(\"%3d%3d%14.9f%14.3f%14.3f%14.3f%11.3f%11.3f%11.3f\\n\", sat_prn,\r\n          static_cast<int>(sat_sys), clock_bias, position.x, position.y,\r\n          position.z, velocity.x, velocity.y, velocity.z);\r\n  }\r\n};\r\n\r\nstruct ObsKey {\r\n  apollo::drivers::gnss::GnssBandID band_id;\r\n  unsigned int sat_prn;\r\n  ObsKey(const apollo::drivers::gnss::GnssBandID& id, const unsigned int prn) {\r\n    band_id = id;\r\n    sat_prn = prn;\r\n  }\r\n  ObsKey() {\r\n    band_id = apollo::drivers::gnss::GPS_L1;\r\n    sat_prn = 0;\r\n  }\r\n  bool operator<(const ObsKey& key2) const {\r\n    if (band_id < key2.band_id) {\r\n      return true;\r\n    }\r\n    if (band_id == key2.band_id) {\r\n      return sat_prn < key2.sat_prn;\r\n    }\r\n    return false;\r\n  }\r\n  bool operator==(const ObsKey& key2) const {\r\n    return (band_id == key2.band_id) && (sat_prn == key2.sat_prn);\r\n  }\r\n  ObsKey& operator=(const ObsKey& key2) {\r\n    band_id = key2.band_id;\r\n    sat_prn = key2.sat_prn;\r\n    return *this;\r\n  }\r\n};\r\n\r\ntypedef ObsKey AmbKey;\r\n\r\nstruct EphKey {\r\n  GnssType gnss_type;\r\n  unsigned int sat_prn;\r\n  // toe = eph.toe + eph.week_num * sec_per_week\r\n  double eph_toe;\r\n  EphKey(const GnssType type, const unsigned int prn, double toe) {\r\n    gnss_type = type;\r\n    sat_prn = prn;\r\n    eph_toe = toe;\r\n  }\r\n  EphKey(const GnssType type, const unsigned int prn,\r\n         const unsigned int week_num, double toe) {\r\n    gnss_type = type;\r\n    sat_prn = prn;\r\n    eph_toe = toe + week_num * SECOND_PER_WEEK;\r\n  }\r\n  EphKey() {\r\n    gnss_type = apollo::drivers::gnss::SYS_UNKNOWN;\r\n    sat_prn = 0;\r\n    eph_toe = -0.1;\r\n  }\r\n  bool operator<(const EphKey& key2) const {\r\n    if (gnss_type < key2.gnss_type) {\r\n      return true;\r\n    }\r\n    if (gnss_type == key2.gnss_type) {\r\n      if (sat_prn < key2.sat_prn) {\r\n        return true;\r\n      }\r\n      if (sat_prn == key2.sat_prn) {\r\n        return eph_toe < key2.eph_toe;\r\n      }\r\n      return false;\r\n    }\r\n    return false;\r\n  }\r\n  bool operator==(const EphKey& key2) const {\r\n    return (gnss_type == key2.gnss_type) && (sat_prn == key2.sat_prn) &&\r\n           (eph_toe == key2.eph_toe);\r\n  }\r\n  EphKey& operator=(const EphKey& key2) {\r\n    gnss_type = key2.gnss_type;\r\n    sat_prn = key2.sat_prn;\r\n    eph_toe = key2.eph_toe;\r\n    return *this;\r\n  }\r\n};\r\n\r\nnamespace gnss_utility {\r\n\r\ninline int RoundDoubleToInt(double val) { return static_cast<int>(val); }\r\n\r\ninline double sign(const double val) {\r\n  if (val >= 0) {\r\n    return 1.0;\r\n  } else {\r\n    return -1.0;\r\n  }\r\n}\r\n\r\ninline double round(double x) {\r\n  return static_cast<double>(std::floor(x + 0.5));\r\n}\r\n\r\ntemplate <typename T>\r\nint GetIndexInVector(const T& type, const std::vector<T>& group) {\r\n  unsigned int size = group.size();\r\n  for (unsigned int m = 0; m < size; m++) {\r\n    if (type == group[m]) {\r\n      return m;\r\n    }\r\n  }\r\n  return -1;\r\n}\r\n\r\ntemplate <typename T>\r\nint AppendNewToVector(const T& type, const std::vector<T>& group) {\r\n  if (GetIndexInVector<T>(type, group) == -1) {\r\n    group.push_back(type);\r\n    return 0;\r\n  }\r\n  return -1;\r\n}\r\n\r\ninline std::string FormatString(const char* format, ...) {\r\n  const int buf_size = 2048;\r\n  char temp[buf_size] = {'\\0'};\r\n  va_list args;\r\n  va_start(args, format);\r\n  vsprintf(temp, format, args);\r\n  va_end(args);\r\n  return std::string(temp);\r\n}\r\n\r\ninline void PrintPvtResult(const GnssPntResult& rover_pnt, double ratio) {\r\n  std::string part1 = FormatString(\r\n      \"%6d%12.3f%4d%16.3f%16.3f%16.3f%4d%4.1f%6.1f%8.3f%8.3f%8.3f\",\r\n      rover_pnt.gnss_week(), rover_pnt.gnss_second_s(),\r\n      static_cast<int>(rover_pnt.pnt_type()), rover_pnt.pos_x_m(),\r\n      rover_pnt.pos_y_m(), rover_pnt.pos_z_m(), rover_pnt.sovled_sat_num(),\r\n      rover_pnt.pdop(), ratio, rover_pnt.vel_x_m(), rover_pnt.vel_y_m(),\r\n      rover_pnt.vel_z_m());\r\n  std::string part2 =\r\n      FormatString(\"%8.3f%8.3f%8.3f\", rover_pnt.std_pos_x_m(),\r\n                    rover_pnt.std_pos_y_m(), rover_pnt.std_pos_z_m());\r\n  printf(\"%s%s\\n\", part1.c_str(), part2.c_str());\r\n}\r\n\r\ninline void PrintEigenMatrix(const Eigen::MatrixXd& t, const char* t_name,\r\n                               const bool print_long = false) {\r\n  if (t_name == NULL) {\r\n    return;\r\n  }\r\n  printf(\"debug matrix %s row=%d col=%d\\n\", t_name, static_cast<int>(t.rows()),\r\n         static_cast<int>(t.cols()));\r\n  for (unsigned int r = 0; r < t.rows(); ++r) {\r\n    for (unsigned int c = 0; c < t.cols(); ++c) {\r\n      if (print_long) {\r\n        printf(\"%40.20f\", t(r, c));\r\n      } else {\r\n        printf(\"%16.8f\", t(r, c));\r\n      }\r\n    }\r\n    printf(\"\\n\");\r\n  }\r\n}\r\n\r\n// time conversion\r\ninline bool IsLeapYear(const unsigned int year) {\r\n  if (year % 4 != 0) {\r\n    return false;\r\n  }\r\n  if (year % 400 == 0) {\r\n    return true;\r\n  }\r\n  if (year % 100 == 0) {\r\n    return false;\r\n  }\r\n  /*if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {\r\n    return true;\r\n  }*/\r\n  return true;\r\n}\r\n\r\ninline bool CheckDateForGnss(const int& year, const int& month,\r\n                               const int& day) {\r\n  if (year < 1981 || month < 1 || month > 12 || day < 1 || day > 31) {\r\n    return false;\r\n  }\r\n  return true;\r\n}\r\n\r\ninline unsigned int GetDayOfYear(const int& year, const int& month,\r\n                                const int& day) {\r\n  const int dinmth[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\r\n  int dayofy = 0;\r\n  if (!CheckDateForGnss(year, month, day)) {\r\n    return 0;\r\n  }\r\n  if (month == 1) {\r\n    return day;\r\n  }\r\n  dayofy = 0;\r\n  for (int m = 1; m <= (month - 1); ++m) {\r\n    dayofy += dinmth[m];\r\n    if (m == 2 && IsLeapYear(year)) {\r\n      dayofy += 1;\r\n    }\r\n  }\r\n  dayofy += day;\r\n  return dayofy;\r\n}\r\n\r\ninline void GpsTime2DayTime(int weekno, double gpstime, int* year,\r\n                                 int* month, int* day, int* hour, int* minute,\r\n                                 double* second) {\r\n  int dayofweek = RoundDoubleToInt(gpstime / 86400);\r\n  double secofday = gpstime - dayofweek * 86400;\r\n  *hour = RoundDoubleToInt(secofday / 3600);\r\n  double sminute = secofday - *hour * 3600;\r\n  *minute = RoundDoubleToInt(sminute / 60);\r\n  *second = sminute - *minute * 60;\r\n\r\n  int daysum = weekno * 7 + dayofweek;\r\n  // 44244 is gps-time origin corrected julian-day\r\n  double cor_julian_day = 44244 + daysum;\r\n\r\n  double abs_julian_day = 1 + RoundDoubleToInt(cor_julian_day) + 2400000;\r\n  double part_cor_jul = cor_julian_day - RoundDoubleToInt(cor_julian_day);\r\n  int ih = RoundDoubleToInt((abs_julian_day - 1867216.25) / 36524.25);\r\n  double tt2 = abs_julian_day + 1 + ih - RoundDoubleToInt(ih / 4);\r\n  double tt3 = tt2 - 1720995;\r\n  int th1 = RoundDoubleToInt((tt3 - 122.1) / 365.25);\r\n  abs_julian_day = 365.25 * th1 -\r\n                  (365.25 * th1 - RoundDoubleToInt(365.25 * th1));\r\n  int ih2 = RoundDoubleToInt((tt3 - abs_julian_day) / 30.6001);\r\n  *day = RoundDoubleToInt((tt3 - abs_julian_day -\r\n        RoundDoubleToInt(30.6001 * ih2)) + part_cor_jul);\r\n  *month = ih2 - 1;\r\n  if (ih2 > 13) {\r\n    *month = ih2 - 13;\r\n  }\r\n  *year = th1;\r\n  if (*month <= 2) {\r\n    *year = *year + 1;\r\n  }\r\n}\r\n\r\ninline int DayTime2GpsTime(int year, int month, int day, int hour,\r\n                                int minute, double second, double* gpstime) {\r\n  int dayofw = 0;\r\n  int dayofy = 0;\r\n  int weekno = 0;\r\n  *gpstime = -0.1;\r\n  if (!CheckDateForGnss(year, month, day)) {\r\n    return weekno;\r\n  }\r\n  // Convert day, month and year to day of year\r\n  dayofy = GetDayOfYear(year, month, day);\r\n  // Convert day of year and year into week numearth_ber and day of week\r\n  int ttlday = 360;\r\n  for (int yr = 1981; yr <= (year - 1); yr++) {\r\n    ttlday += 365;\r\n    if (IsLeapYear(yr)) {\r\n      ttlday += 1;\r\n    }\r\n  }\r\n  ttlday += dayofy;\r\n  weekno = ttlday / 7;\r\n  dayofw = ttlday - 7 * weekno;\r\n  *gpstime = (hour * 3600 + minute * 60 + second + dayofw * 86400);\r\n  return weekno;\r\n}\r\n\r\n// coordinate conversion\r\ninline void llh2xyz(const double longitude, const double latitude,\r\n                    const double height, double r_xyz[3]) {\r\n  // earth parameters of WGS-84\r\n  double a = 6378137;\r\n  double f = 0.00335281066474;\r\n  double b = a - a * f;\r\n  double easquare = (a + b) * (a - b) / (a * a);\r\n  double n = a / sqrt(1 - easquare * sin(latitude) * sin(latitude));\r\n\r\n  r_xyz[0] = (n + height) * cos(latitude) * cos(longitude);\r\n  r_xyz[1] = (n + height) * cos(latitude) * sin(longitude);\r\n  r_xyz[2] = (n * (1 - easquare) + height) * sin(latitude);\r\n}\r\n\r\ninline void llh2xyz(const double longitude, const double latitude,\r\n                    const double height, PointThreeDim* user) {\r\n  double r_xyz[3] = {0.0};\r\n  llh2xyz(longitude, latitude, height, r_xyz);\r\n  user->x = r_xyz[0];\r\n  user->y = r_xyz[1];\r\n  user->z = r_xyz[2];\r\n}\r\n\r\ninline void xyz2llh(double* rr, double* lat, double* lon, double* rh) {\r\n  // PNT solving done under WGS-84 with listed below\r\n  const double earth_ae = 6378137;\r\n  // const double earth_be = 6356752.3142;\r\n  const double earth_fe = 1.0 / 298.257223563;\r\n  double earth_e2 = 2 * earth_fe - earth_fe * earth_fe;\r\n\r\n  double x = rr[0];\r\n  double y = rr[1];\r\n  double z = rr[2];\r\n\r\n  if (fabs(y) < 1.0E-12) {\r\n    if (x > 0.0) {\r\n      *lon = 0.0;\r\n    } else {\r\n      *lon = PI;\r\n    }\r\n  } else {\r\n    *lon = atan2(y, x);\r\n  }\r\n  double s = sqrt(x * x + y * y) + 1e-10;\r\n  double zs = z / s;\r\n  *rh = sqrt(x * x + y * y + z * z) - earth_ae;\r\n  *lat = atan(zs / (1 - earth_e2 * earth_ae / (earth_ae + *rh + 1e-12)));\r\n\r\n  int cnum = 0;\r\n  int b_true = 1;\r\n  do {\r\n    cnum++;\r\n    double nn1 = 0;\r\n    nn1 = earth_ae / sqrt(1 - earth_e2 * pow(sin(*lat), 2));\r\n    double lat1 = *lat;\r\n    *rh = s / cos(*lat) - nn1;\r\n    *lat = atan(zs / (1 - earth_e2 * nn1 / (nn1 + *rh + 1e-12)));\r\n    if ((fabs(*lat - lat1) < 1e-12) || (cnum > 5)) {\r\n      break;\r\n    }\r\n  } while (b_true);\r\n\r\n  if (fabs(*lon) < 1e-12) {\r\n    *lon = *lon + 2 * PI;\r\n  }\r\n}\r\n\r\ninline void xyz2blh(const PointThreeDim& user, double* lat, double* lon,\r\n                    double* alt) {\r\n  double r[3] = {user.x, user.y, user.z};\r\n  xyz2llh(r, lat, lon, alt);\r\n}\r\n\r\ninline void dxyz2enu(const double dxyz[3], const double lat, const double lon,\r\n                     double denu[3]) {\r\n  denu[0] = -sin(lon) * dxyz[0] + cos(lon) * dxyz[1];\r\n  denu[1] = -sin(lat) * cos(lon) * dxyz[0] - sin(lat) * sin(lon) * dxyz[1] +\r\n            cos(lat) * dxyz[2];\r\n  denu[2] = cos(lat) * cos(lon) * dxyz[0] + cos(lat) * sin(lon) * dxyz[1] +\r\n            sin(lat) * dxyz[2];\r\n  return;\r\n}\r\n\r\ninline void enu2xyz(const double denu[3], const double lat, const double lon,\r\n                    double dxyz[3]) {\r\n  double matrix_r[3][3] = {-sin(lon),\r\n                           cos(lon),\r\n                           0,\r\n                           -sin(lat) * cos(lon),\r\n                           -sin(lat) * sin(lon),\r\n                           cos(lat),\r\n                           cos(lat) * cos(lon),\r\n                           cos(lat) * sin(lon),\r\n                           sin(lat)};\r\n  // xyz = m.transpose() * denu\r\n  for (unsigned int i = 0; i < 3; ++i) {\r\n    dxyz[i] = 0;\r\n    for (unsigned int j = 0; j < 3; ++j) {\r\n      dxyz[i] += matrix_r[j][i] * denu[j];\r\n    }\r\n  }\r\n  return;\r\n}\r\n\r\ninline void enu2xyz(const double denu[3], const double lat, const double lon,\r\n                    PointThreeDim* xyz) {\r\n  double dxyz[3] = {0.0};\r\n  //\r\n  enu2xyz(denu, lat, lon, dxyz);\r\n  xyz->x = dxyz[0];\r\n  xyz->y = dxyz[1];\r\n  xyz->z = dxyz[2];\r\n  return;\r\n}\r\n\r\ninline void dxyz2enu(const PointThreeDim& user, const PointThreeDim& dxyz,\r\n                     PointThreeDim* denu) {\r\n  double dxyz0[3] = {dxyz.x, dxyz.y, dxyz.z};\r\n  double lat = 0;\r\n  double lon = 0;\r\n  double rh = 0;\r\n  xyz2blh(user, &lat, &lon, &rh);\r\n  double denu0[3] = {0.0};\r\n  dxyz2enu(dxyz0, lat, lon, denu0);\r\n  denu->x = denu0[0];\r\n  denu->y = denu0[1];\r\n  denu->z = denu0[2];\r\n}\r\n\r\ninline double GetDistance(const PointThreeDim& src, const PointThreeDim& dest) {\r\n  double dist = 0.0;\r\n  dist += (src.x - dest.x) * (src.x - dest.x);\r\n  dist += (src.y - dest.y) * (src.y - dest.y);\r\n  dist += (src.z - dest.z) * (src.z - dest.z);\r\n  return sqrt(dist);\r\n}\r\n\r\ninline double GetCosineDirection(const PointThreeDim& src,\r\n                               const PointThreeDim& dest,\r\n                               PointThreeDim* cosine) {\r\n  double dist = GetDistance(src, dest);\r\n  cosine->x = (src.x - dest.x) / dist;\r\n  cosine->y = (src.y - dest.y) / dist;\r\n  cosine->z = (src.z - dest.z) / dist;\r\n  return dist;\r\n}\r\n\r\ninline void GetEleAzm(const PointThreeDim& user, const PointThreeDim& sat,\r\n                    double* elv_deg, double* azm_deg) {\r\n  double lat = 0;\r\n  double lon = 0;\r\n  double alt = 0;\r\n\r\n  xyz2blh(user, &lat, &lon, &alt);\r\n  double dx = sat.x - user.x;\r\n  double dy = sat.y - user.y;\r\n  double dz = sat.z - user.z;\r\n\r\n  double xp =\r\n      -sin(lat) * cos(lon) * dx - sin(lat) * sin(lon) * dy + cos(lat) * dz;\r\n  double yp = -sin(lon) * dx + cos(lon) * dy;\r\n  double zp =\r\n      cos(lat) * cos(lon) * dx + cos(lat) * sin(lon) * dy + sin(lat) * dz;\r\n  *elv_deg = atan(zp / sqrt(xp * xp + yp * yp)) / PI * 180;\r\n  if (fabs(yp) < 1.0E-12) {\r\n    if (xp > 0.0) {\r\n      *azm_deg = 0.0;\r\n    } else {\r\n      *azm_deg = PI;\r\n    }\r\n  } else {\r\n    *azm_deg = atan2(yp, xp);\r\n  }\r\n  *azm_deg = *azm_deg / PI * 180;\r\n  return;\r\n}\r\n\r\ninline Eigen::MatrixXd DcmEcef2Navi(const PointThreeDim& pos) {\r\n  // dcm from ecef XYZ to local navigation\r\n  double lat = 0;\r\n  double lon = 0;\r\n  double rh = 0;\r\n  gnss_utility::xyz2blh(pos, &lat, &lon, &rh);\r\n  Eigen::Matrix3d matrix_r;\r\n  matrix_r(0, 0) = -sin(lon);\r\n  matrix_r(0, 1) = cos(lon);\r\n  matrix_r(0, 2) = 0;\r\n  matrix_r(1, 0) = -sin(lat) * cos(lon);\r\n  matrix_r(1, 1) = -sin(lat) * sin(lon);\r\n  matrix_r(1, 2) = cos(lat);\r\n  matrix_r(2, 0) = cos(lat) * cos(lon);\r\n  matrix_r(2, 1) = cos(lat) * sin(lon);\r\n  matrix_r(2, 2) = sin(lat);\r\n  return matrix_r;\r\n}\r\n\r\ninline Eigen::Matrix3d DcmBody2Navi(const double pitch, const double roll,\r\n                               const double yaw) {\r\n  // keep following codes for further non-Eigen environment\r\n  // NOTICE: positive yaw being North by West (= anti-clockwise).\r\n  double matrix_body2navi[3][3] = {0.0};\r\n  matrix_body2navi[0][0] =\r\n      cos(roll) * cos(yaw) - sin(pitch) * sin(yaw) * sin(roll);\r\n  matrix_body2navi[0][1] = -cos(pitch) * sin(yaw);\r\n  matrix_body2navi[0][2] =\r\n      sin(roll) * cos(yaw) + cos(roll) * sin(pitch) * sin(yaw);\r\n  matrix_body2navi[1][0] =\r\n      cos(roll) * sin(yaw) + sin(roll) * sin(pitch) * cos(yaw);\r\n  matrix_body2navi[1][1] = cos(pitch) * cos(yaw);\r\n  matrix_body2navi[1][2] =\r\n      sin(roll) * sin(yaw) - cos(roll) * sin(pitch) * cos(yaw);\r\n  matrix_body2navi[2][0] = -sin(roll) * cos(pitch);\r\n  matrix_body2navi[2][1] = sin(pitch);\r\n  matrix_body2navi[2][2] = cos(roll) * cos(pitch);\r\n\r\n  Eigen::Matrix3d temp;\r\n  for (unsigned int i = 0; i < 3; ++i) {\r\n    for (unsigned int j = 0; j < 3; ++j) {\r\n      temp(i, j) = matrix_body2navi[i][j];\r\n    }\r\n  }\r\n  return temp;\r\n}\r\n\r\ninline Eigen::MatrixXd RoundMatrix(const Eigen::MatrixXd& m1) {\r\n  Eigen::MatrixXd m2 = m1;\r\n  for (unsigned int r = 0; r < m2.rows(); ++r) {\r\n    for (unsigned int c = 0; c < m2.cols(); ++c) {\r\n      m2(r, c) = static_cast<int>(m2(r, c) + 0.5 * sign(m2(r, c)));\r\n    }\r\n  }\r\n  return m2;\r\n}\r\n\r\n}  // namespace gnss_utility\r\n\r\n}  // namespace local_gnss\r\n}  // namespace localization\r\n}  // namespace apollo\r\n\r\n#endif\r\n", "meta": {"hexsha": "440fd36fe2fb6f03c7d116c07fd2cdffccd79d2a", "size": 19928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/localization/msf/local_gnss/gnss_utility.hpp", "max_stars_repo_name": "renlancai/apollo", "max_stars_repo_head_hexsha": "400c00d28526b21b71dfe699dc38ee7fdfb3e9f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-07T02:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-07T02:40:16.000Z", "max_issues_repo_path": "modules/localization/msf/local_gnss/gnss_utility.hpp", "max_issues_repo_name": "renlancai/apollo", "max_issues_repo_head_hexsha": "400c00d28526b21b71dfe699dc38ee7fdfb3e9f8", "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": "modules/localization/msf/local_gnss/gnss_utility.hpp", "max_forks_repo_name": "renlancai/apollo", "max_forks_repo_head_hexsha": "400c00d28526b21b71dfe699dc38ee7fdfb3e9f8", "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.2628487518, "max_line_length": 81, "alphanum_fraction": 0.5685467684, "num_tokens": 6407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17704613614580653}}
{"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_X86_SSE2_SIMD_FUNCTION_SUBS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_SUBS_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd =  boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( subs_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::uint8_<A0>, bs::sse_>\n                          , bs::pack_<bd::uint8_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0\n                                    , const A0 & a1 ) const BOOST_NOEXCEPT\n    {\n      return _mm_subs_epu8(a0, a1);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( subs_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::int8_<A0>, bs::sse_>\n                          , bs::pack_<bd::int8_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0\n                                    , const A0 & a1 ) const BOOST_NOEXCEPT\n    {\n      return _mm_subs_epi8(a0, a1);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( subs_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::uint16_<A0>, bs::sse_>\n                          , bs::pack_<bd::uint16_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0\n                                    , const A0 & a1 ) const BOOST_NOEXCEPT\n    {\n      return _mm_subs_epu16(a0, a1);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( subs_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::int16_<A0>, bs::sse_>\n                          , bs::pack_<bd::int16_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0\n                                    , const A0 & a1 ) const BOOST_NOEXCEPT\n    {\n      return _mm_subs_epi16(a0, a1);\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "4405d65b88a0be15f503ee479fbfc4bbc03909d0", "size": 2523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/x86/sse2/simd/function/subs.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/x86/sse2/simd/function/subs.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/x86/sse2/simd/function/subs.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.7662337662, "max_line_length": 100, "alphanum_fraction": 0.4359889021, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17704613614580653}}
{"text": "#include <stdio.h>\n#include <filesystem>\n\n#include <deal.II/fe/fe_q.h>\n\n#include \"framework/builder/framework_builder.hpp\"\n#include \"framework/framework_parameters.hpp\"\n\n// Instantiated concerete classes\n#include \"calculator/drift_diffusion/drift_diffusion_vector_calculator.hpp\"\n#include \"convergence/parameters/single_parameter_checker.hpp\"\n#include \"convergence/iteration_completion_checker.hpp\"\n#include \"data/cross_sections/material_cross_sections.hpp\"\n#include \"domain/finite_element/finite_element_gaussian.hpp\"\n#include \"domain/domain.hpp\"\n#include \"eigenvalue/k_eigenvalue/calculator_via_fission_source.hpp\"\n#include \"eigenvalue/k_eigenvalue/calculator_via_rayleigh_quotient.hpp\"\n#include \"formulation/scalar/diffusion.hpp\"\n#include \"formulation/scalar/drift_diffusion.hpp\"\n#include \"formulation/angular/self_adjoint_angular_flux.h\"\n#include \"formulation/updater/saaf_updater.h\"\n#include \"formulation/updater/diffusion_updater.hpp\"\n#include \"formulation/updater/drift_diffusion_updater.hpp\"\n#include \"formulation/stamper.hpp\"\n#include \"instrumentation/instrument.h\"\n#include \"instrumentation/basic_instrument.h\"\n#include \"iteration/outer/outer_power_iteration.hpp\"\n#include \"iteration/outer/outer_fixed_source_iteration.hpp\"\n#include \"quadrature/calculators/scalar_moment.h\"\n#include \"quadrature/calculators/angular_flux_integrator.hpp\"\n#include \"quadrature/calculators/spherical_harmonic_zeroth_moment.h\"\n#include \"quadrature/quadrature_set.hpp\"\n#include \"solver/linear/gmres.h\"\n#include \"solver/group/single_group_solver.h\"\n#include \"system/solution/mpi_group_angular_solution.h\"\n#include \"iteration/initializer/initialize_fixed_terms_once.h\"\n#include \"iteration/initializer/initialize_fixed_terms_reset_moments.hpp\"\n#include \"iteration/group/group_source_iteration.hpp\"\n#include \"iteration/subroutine/get_scalar_flux_from_framework.hpp\"\n#include \"system/system_types.h\"\n#include \"system/solution/solution_types.h\"\n#include \"system/system_helper.hpp\"\n\n// Mock objects\n#include \"convergence/tests/convergence_checker_mock.hpp\"\n#include \"convergence/tests/iteration_completion_checker_mock.hpp\"\n#include \"domain/tests/domain_mock.hpp\"\n#include \"domain/finite_element/tests/finite_element_mock.hpp\"\n#include \"eigenvalue/k_eigenvalue/tests/k_eigenvalue_calculator_mock.hpp\"\n#include \"formulation/angular/tests/self_adjoint_angular_flux_mock.h\"\n#include \"formulation/scalar/tests/diffusion_mock.hpp\"\n#include \"formulation/scalar/tests/drift_diffusion_mock.hpp\"\n#include \"formulation/tests/stamper_mock.hpp\"\n#include \"formulation/updater/tests/boundary_conditions_updater_mock.h\"\n#include \"formulation/updater/tests/scattering_source_updater_mock.h\"\n#include \"formulation/updater/tests/fission_source_updater_mock.h\"\n#include \"formulation/updater/tests/fixed_updater_mock.h\"\n#include \"framework/builder/tests/framework_validator_mock.hpp\"\n#include \"framework/tests/framework_mock.hpp\"\n#include \"iteration/group/tests/group_solve_iteration_mock.hpp\"\n#include \"data/material/tests/material_mock.hpp\"\n#include \"problem/tests/parameters_mock.hpp\"\n#include \"formulation/updater/tests/fixed_updater_mock.h\"\n#include \"quadrature/calculators/tests/angular_flux_integrator_mock.hpp\"\n#include \"quadrature/tests/quadrature_set_mock.hpp\"\n#include \"quadrature/calculators/tests/spherical_harmonic_moments_mock.h\"\n#include \"solver/group/tests/single_group_solver_mock.h\"\n#include \"system/solution/tests/mpi_group_angular_solution_mock.h\"\n#include \"system/moments/tests/spherical_harmonic_mock.h\"\n\n#include \"test_helpers/gmock_wrapper.h\"\n#include \"test_helpers/test_helper_functions.h\"\n\nnamespace {\n\nusing namespace bart;\n\nusing ::testing::Return, ::testing::NiceMock, ::testing::DoDefault;\nusing ::testing::WhenDynamicCastTo, ::testing::NotNull;\nusing ::testing::HasSubstr, ::testing::_;\nusing ::testing::ReturnRef, ::testing::A;\n\nusing ::testing::AtLeast;\n\nusing Part = framework::builder::FrameworkPart;\n\ntemplate <typename DimensionWrapper>\nclass FrameworkBuilderIntegrationTest : public ::testing::Test {\n public:\n  static constexpr int dim = DimensionWrapper::value;\n\n  using FrameworkBuilder = framework::builder::FrameworkBuilder<dim>;\n  using ProblemParameters = NiceMock<problem::ParametersMock>;\n  using Material = NiceMock<data::material::MaterialMock>;\n\n  // Mock object types\n  using AngularFluxIntegrator = quadrature::calculators::AngularFluxIntegratorMock;\n  using BoundaryConditionsUpdaterType = formulation::updater::BoundaryConditionsUpdaterMock;\n  using DiffusionFormulationType = formulation::scalar::DiffusionMock<dim>;\n  using DriftDiffusionFormulation = formulation::scalar::DriftDiffusionMock<dim>;\n  using DomainType = domain::DomainMock<dim>;\n  using FiniteElementType = domain::finite_element::FiniteElementMock<dim>;\n  using FissionSourceUpdaterType = formulation::updater::FissionSourceUpdaterMock;\n  using FrameworkMock = framework::FrameworkMock;\n  using GroupSolutionType = system::solution::MPIGroupAngularSolutionMock;\n  using GroupSolveIterationType = iteration::group::GroupSolveIterationMock;\n  using KEffectiveUpdaterType = eigenvalue::k_eigenvalue::K_EigenvalueCalculatorMock;\n  using MomentCalculatorType = quadrature::calculators::SphericalHarmonicMomentsMock;\n  using MomentConvergenceCheckerType = convergence::IterationCompletionCheckerMock<bart::system::moments::MomentVector>;\n  using ParameterConvergenceCheckerType = convergence::IterationCompletionCheckerMock<double>;\n  using QuadratureSetType = quadrature::QuadratureSetMock<dim>;\n  using SAAFFormulationType = formulation::angular::SelfAdjointAngularFluxMock<dim>;\n  using ScatteringSourceUpdaterType = formulation::updater::ScatteringSourceUpdaterMock;\n  using SphericalHarmonicMoments = system::moments::SphericalHarmonicMock;\n  using SingleGroupSolverType = solver::group::SingleGroupSolverMock;\n  using StamperType = formulation::StamperMock<dim>;\n  using Validator = NiceMock<framework::builder::FrameworkValidatorMock>;\n\n  FrameworkBuilderIntegrationTest()\n      : mock_material() {}\n\n  std::unique_ptr<FrameworkBuilder> test_builder_ptr_;\n  ProblemParameters parameters;\n  Material mock_material;\n  system::SystemHelper<dim> system_helper_;\n\n  // Various mock objects to be used\n  std::shared_ptr<AngularFluxIntegrator> angular_flux_integrator_sptr_ { nullptr };\n  std::shared_ptr<BoundaryConditionsUpdaterType> boundary_conditions_updater_sptr_;\n  std::shared_ptr<data::cross_sections::MaterialCrossSections> cross_sections_sptr_;\n  std::unique_ptr<DiffusionFormulationType> diffusion_formulation_uptr_;\n  std::unique_ptr<DriftDiffusionFormulation> drift_diffusion_formulation_uptr_;\n  std::shared_ptr<DomainType> domain_sptr_;\n  std::shared_ptr<FiniteElementType> finite_element_sptr_;\n  std::shared_ptr<FissionSourceUpdaterType> fission_source_updater_sptr_;\n  std::unique_ptr<FrameworkMock> framework_uptr_{ nullptr };\n  std::shared_ptr<GroupSolutionType> group_solution_sptr_;\n  std::unique_ptr<GroupSolveIterationType> group_solve_iteration_uptr_;\n  std::unique_ptr<KEffectiveUpdaterType> k_effective_updater_uptr_;\n  std::unique_ptr<MomentCalculatorType> moment_calculator_uptr_;\n  std::unique_ptr<MomentConvergenceCheckerType> moment_convergence_checker_uptr_;\n  std::unique_ptr<ParameterConvergenceCheckerType> parameter_convergence_checker_uptr_;\n  std::shared_ptr<QuadratureSetType> quadrature_set_sptr_;\n  std::unique_ptr<SAAFFormulationType> saaf_formulation_uptr_;\n  std::shared_ptr<ScatteringSourceUpdaterType> scattering_source_updater_sptr_;\n  std::shared_ptr<SphericalHarmonicMoments> spherical_harmonics_sptr_;\n  std::unique_ptr<SingleGroupSolverType> single_group_solver_uptr_;\n  std::unique_ptr<StamperType> stamper_uptr_;\n\n  Validator* validator_obs_ptr_{ nullptr };\n\n  // Test Parameters\n  const int polynomial_degree = 2;\n  std::vector<double> spatial_max;\n  std::vector<int> n_cells;\n  const int n_energy_groups = 3;\n  const int n_angles = 2;\n  std::array<int, 4> dofs_per_cell_by_dim_{1, 3, 9, 27};\n  std::map<problem::Boundary, bool> reflective_bcs_;\n  static int files_in_working_directory_;\n\n  static void SetUpTestSuite() {\n    for (const auto & entry : std::filesystem::directory_iterator(\".\")) {\n      std::ignore = entry;\n      ++files_in_working_directory_;\n    }\n  }\n  static void TearDownTestSuite() {\n    files_in_working_directory_ = 0;\n  }\n  void SetUp() override;\n  void TearDown() override;\n};\n\ntemplate <typename DimensionWrapper>\nint FrameworkBuilderIntegrationTest<DimensionWrapper>::files_in_working_directory_ = 0;\n\ntemplate <typename DimensionWrapper>\nvoid FrameworkBuilderIntegrationTest<DimensionWrapper>::SetUp() {\n  angular_flux_integrator_sptr_ = std::make_shared<AngularFluxIntegrator>();\n  boundary_conditions_updater_sptr_ = std::make_shared<BoundaryConditionsUpdaterType>();\n  cross_sections_sptr_ = std::make_shared<data::cross_sections::MaterialCrossSections>(mock_material);\n  diffusion_formulation_uptr_ = std::move(std::make_unique<DiffusionFormulationType>());\n  drift_diffusion_formulation_uptr_ = std::move(std::make_unique<DriftDiffusionFormulation>());\n  domain_sptr_ = std::make_shared<DomainType>();\n  finite_element_sptr_ = std::make_shared<FiniteElementType>();\n  fission_source_updater_sptr_ = std::make_shared<FissionSourceUpdaterType>();\n  framework_uptr_ = std::make_unique<FrameworkMock>();\n  group_solution_sptr_ = std::make_shared<GroupSolutionType>();\n  group_solve_iteration_uptr_  = std::move(std::make_unique<GroupSolveIterationType>());\n  k_effective_updater_uptr_ = std::move(std::make_unique<KEffectiveUpdaterType>());\n  moment_calculator_uptr_ = std::move(std::make_unique<MomentCalculatorType>());\n  moment_convergence_checker_uptr_ = std::move(std::make_unique<MomentConvergenceCheckerType>());\n  parameter_convergence_checker_uptr_ = std::move(std::make_unique<ParameterConvergenceCheckerType>());\n  quadrature_set_sptr_ = std::make_shared<QuadratureSetType>();\n  saaf_formulation_uptr_ = std::move(std::make_unique<SAAFFormulationType>());\n  scattering_source_updater_sptr_ = std::make_shared<ScatteringSourceUpdaterType>();\n  spherical_harmonics_sptr_ = std::make_shared<SphericalHarmonicMoments>();\n  stamper_uptr_ = std::move(std::make_unique<StamperType>());\n  single_group_solver_uptr_ = std::move(std::make_unique<SingleGroupSolverType>());\n  auto validator_ptr = std::make_unique<Validator>();\n  validator_obs_ptr_ = validator_ptr.get();\n\n  ON_CALL(*validator_ptr, AddPart(_)).WillByDefault(ReturnRef(*validator_ptr));\n\n  test_builder_ptr_ = std::move(std::make_unique<FrameworkBuilder>(std::move(validator_ptr)));\n\n  for (int i = 0; i < this->dim; ++i) {\n    spatial_max.push_back(10);\n    n_cells.push_back(2);\n  }\n\n  reflective_bcs_ = {\n      {problem::Boundary::kXMin, true},\n      {problem::Boundary::kXMax, true},\n      {problem::Boundary::kYMin, false},\n      {problem::Boundary::kYMax, false},\n      {problem::Boundary::kZMin, false},\n      {problem::Boundary::kZMax, false},\n  };\n\n  ON_CALL(parameters, NEnergyGroups())\n      .WillByDefault(Return(n_energy_groups));\n  ON_CALL(parameters, NCells())\n      .WillByDefault(Return(n_cells));\n  ON_CALL(parameters, SpatialMax())\n      .WillByDefault(Return(spatial_max));\n  ON_CALL(parameters, FEPolynomialDegree())\n      .WillByDefault(Return(polynomial_degree));\n  ON_CALL(parameters, TransportModel())\n      .WillByDefault(Return(problem::EquationType::kDiffusion));\n  ON_CALL(parameters, ReflectiveBoundary())\n      .WillByDefault(Return(reflective_bcs_));\n}\n\ntemplate <typename DimensionWrapper>\nvoid FrameworkBuilderIntegrationTest<DimensionWrapper>::TearDown() {\n  int files_in_working_directory_after{0};\n  for (const auto & entry : std::filesystem::directory_iterator(\".\")) {\n    std::ignore = entry;\n    ++files_in_working_directory_after;\n  }\n  EXPECT_EQ(files_in_working_directory_after,\n            files_in_working_directory_)\n            << \"Test changed number of files in working directory from \"\n            << files_in_working_directory_ << \" to \"\n            << files_in_working_directory_after << std::endl;\n}\n\nTYPED_TEST_CASE(FrameworkBuilderIntegrationTest, bart::testing::AllDimensions);\n\n// =====================================================================================================================\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, Constructor) {\n  ASSERT_NE(this->test_builder_ptr_->validator_ptr(), nullptr);\n}\n\n// =============================================================================\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildAngularFluxIntegratorTest) {\n  constexpr int dim = this->dim;\n  auto angular_flux_integrator_ptr = this->test_builder_ptr_->BuildAngularFluxIntegrator(this->quadrature_set_sptr_);\n\n  using ExpectedType = typename quadrature::calculators::AngularFluxIntegrator<dim>;\n  auto dynamic_ptr = dynamic_cast<ExpectedType*>(angular_flux_integrator_ptr.get());\n  ASSERT_NE(nullptr, dynamic_ptr);\n  EXPECT_EQ(dynamic_ptr->quadrature_set_ptr(), this->quadrature_set_sptr_.get());\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDiffusionFormulationTest) {\n  constexpr int dim = this->dim;\n\n  auto finite_element_ptr =\n      std::make_shared<domain::finite_element::FiniteElementMock<dim>>();\n  auto cross_sections_ptr =\n      std::make_shared<data::cross_sections::MaterialCrossSections>(this->mock_material);\n\n  EXPECT_CALL(*finite_element_ptr, dofs_per_cell());\n  EXPECT_CALL(*finite_element_ptr, n_cell_quad_pts());\n  EXPECT_CALL(*finite_element_ptr, n_face_quad_pts());\n\n  auto diffusion_formulation_ptr = this->test_builder_ptr_->BuildDiffusionFormulation(\n      finite_element_ptr, cross_sections_ptr);\n\n  using ExpectedType = formulation::scalar::Diffusion<dim>;\n  EXPECT_THAT(diffusion_formulation_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDriftDiffusionFormulationTest) {\n  constexpr int dim = this->dim;\n\n  EXPECT_CALL(*this->finite_element_sptr_, dofs_per_cell());\n  EXPECT_CALL(*this->finite_element_sptr_, n_cell_quad_pts());\n  EXPECT_CALL(*this->finite_element_sptr_, n_face_quad_pts());\n\n  auto drift_diffusion_formulation_ptr = this->test_builder_ptr_->BuildDriftDiffusionFormulation(\n      this->angular_flux_integrator_sptr_,\n      this->finite_element_sptr_,\n      this->cross_sections_sptr_);\n\n  using Formulation = formulation::scalar::DriftDiffusion<dim>;\n  using DriftDiffusionCalculator = calculator::drift_diffusion::DriftDiffusionVectorCalculator<dim>;\n\n  auto dynamic_formulation_ptr = dynamic_cast<Formulation*>(drift_diffusion_formulation_ptr.get());\n  ASSERT_NE(dynamic_formulation_ptr, nullptr);\n  EXPECT_EQ(dynamic_formulation_ptr->angular_flux_integrator_ptr(), this->angular_flux_integrator_sptr_.get());\n  EXPECT_THAT(dynamic_formulation_ptr->drift_diffusion_calculator_ptr(),\n              WhenDynamicCastTo<DriftDiffusionCalculator*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDiffusionUpdaterPointers) {\n  constexpr int dim = this->dim;\n  using ExpectedType = formulation::updater::DiffusionUpdater<dim>;\n  std::map<problem::Boundary, bool> reflective_bcs{\n      {problem::Boundary::kXMin, false},\n      {problem::Boundary::kXMax, false},\n      {problem::Boundary::kYMin, false},\n      {problem::Boundary::kYMax, false},\n      {problem::Boundary::kZMin, false},\n      {problem::Boundary::kZMax, false},\n  };\n  auto updater_struct = this->test_builder_ptr_->BuildUpdaterPointers(\n      std::move(this->diffusion_formulation_uptr_),\n      std::move(this->stamper_uptr_),\n      reflective_bcs);\n  EXPECT_THAT(updater_struct.fixed_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.scattering_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.fission_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDriftDiffusionUpdaterPointers) {\n  constexpr int dim = this->dim;\n  using ExpectedType = typename formulation::updater::DriftDiffusionUpdater<dim>;\n  system::solution::EnergyGroupToAngularSolutionPtrMap angular_flux_storage;\n  this->system_helper_.SetUpEnergyGroupToAngularSolutionPtrMap(angular_flux_storage,\n                                                               this->n_energy_groups,\n                                                               this->n_angles);\n\n  auto updater_struct = this->test_builder_ptr_->BuildUpdaterPointers(\n      std::move(this->diffusion_formulation_uptr_),\n      std::move(this->drift_diffusion_formulation_uptr_),\n      std::move(this->stamper_uptr_),\n      this->angular_flux_integrator_sptr_,\n      this->spherical_harmonics_sptr_,\n      angular_flux_storage,\n      this->reflective_bcs_);\n  ASSERT_THAT(updater_struct.fixed_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  ASSERT_THAT(updater_struct.scattering_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  ASSERT_THAT(updater_struct.fission_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  auto dynamic_ptr = dynamic_cast<ExpectedType*>(updater_struct.fixed_updater_ptr.get());\n  ASSERT_NE(dynamic_ptr, nullptr);\n  EXPECT_NE(dynamic_ptr->drift_diffusion_formulation_ptr(), nullptr);\n  EXPECT_NE(dynamic_ptr->formulation_ptr(), nullptr);\n  EXPECT_EQ(dynamic_ptr->integrated_flux_calculator_ptr(), this->angular_flux_integrator_sptr_.get());\n  EXPECT_EQ(dynamic_ptr->high_order_moments(), this->spherical_harmonics_sptr_.get());\n  EXPECT_EQ(angular_flux_storage.size(), dynamic_ptr->angular_flux_storage_map().size());\n  for (auto& [boundary, is_reflective] : this->reflective_bcs_ ) {\n    if (is_reflective) {\n      EXPECT_EQ(dynamic_ptr->reflective_boundaries().count(boundary), 1);\n    }\n  }\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDiffusionUpdaterPointersRefl) {\n  constexpr int dim = this->dim;\n  using ExpectedType = formulation::updater::DiffusionUpdater<dim>;\n\n  auto updater_struct = this->test_builder_ptr_->BuildUpdaterPointers(\n      std::move(this->diffusion_formulation_uptr_),\n      std::move(this->stamper_uptr_),\n      this->reflective_bcs_);\n  ASSERT_THAT(updater_struct.fixed_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.scattering_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.fission_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n\n  auto dynamic_ptr =\n      dynamic_cast<ExpectedType*>(updater_struct.fixed_updater_ptr.get());\n  for (auto& [boundary, is_reflective] : this->reflective_bcs_ ) {\n    if (is_reflective) {\n      EXPECT_EQ(dynamic_ptr->reflective_boundaries().count(boundary), 1);\n    }\n  }\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildSAAFUpdaterPointers) {\n  constexpr int dim = this->dim;\n  using ExpectedType = formulation::updater::SAAFUpdater<dim>;\n  auto updater_struct = this->test_builder_ptr_->BuildUpdaterPointers(\n      std::move(this->saaf_formulation_uptr_),\n      std::move(this->stamper_uptr_),\n      this->quadrature_set_sptr_);\n  EXPECT_THAT(updater_struct.fixed_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.scattering_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.fission_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest,\n    BuildSAAFUpdaterPointersWithReflectiveBCs) {\n  using ExpectedType = formulation::updater::SAAFUpdater<this->dim>;\n  system::solution::EnergyGroupToAngularSolutionPtrMap angular_flux_storage;\n\n  this->system_helper_.SetUpEnergyGroupToAngularSolutionPtrMap(\n      angular_flux_storage, this->n_energy_groups, this->n_angles);\n\n  auto updater_struct = this->test_builder_ptr_->BuildUpdaterPointers(\n      std::move(this->saaf_formulation_uptr_),\n      std::move(this->stamper_uptr_),\n      this->quadrature_set_sptr_,\n      this->reflective_bcs_,\n      angular_flux_storage);\n  EXPECT_THAT(updater_struct.fixed_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.scattering_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.fission_source_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_THAT(updater_struct.boundary_conditions_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDomainParametersTest) {\n  constexpr int dim = this->dim;\n  using Parameters = framework::FrameworkParameters;\n  auto finite_element_ptr = std::make_shared<NiceMock<domain::finite_element::FiniteElementMock<dim>>>();\n\n  auto test_domain_ptr = this->test_builder_ptr_->BuildDomain(Parameters::DomainSize(this->spatial_max),\n                                                              Parameters::NumberOfCells(this->n_cells),\n                                                              finite_element_ptr,\n                                                              \"1 1 2 2\");\n\n  using ExpectedType = domain::Domain<this->dim>;\n\n  ASSERT_THAT(test_domain_ptr.get(), WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDomainNullFiniteElementPtr) {\n  using Parameters = framework::FrameworkParameters;\n  EXPECT_ANY_THROW({\n  auto test_domain_ptr = this->test_builder_ptr_->BuildDomain(Parameters::DomainSize(this->spatial_max),\n                                                              Parameters::NumberOfCells(this->n_cells),\n                                                              nullptr,\n                                                              \"1 1 2 2\");\n                   });\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDomainBadDomainSize) {\n  constexpr int dim = this->dim;\n  using Parameters = framework::FrameworkParameters;\n  auto finite_element_ptr = std::make_shared<NiceMock<domain::finite_element::FiniteElementMock<dim>>>();\n\n  const auto bad_index{ bart::test_helpers::RandomInt(0, this->dim) };\n  auto bad_spatial_max { this->spatial_max };\n  bad_spatial_max.at(bad_index) = 0;\n\n  EXPECT_ANY_THROW({\n    auto test_domain_ptr = this->test_builder_ptr_->BuildDomain(Parameters::DomainSize(bad_spatial_max),\n                                                                Parameters::NumberOfCells(this->n_cells),\n                                                                finite_element_ptr,\n                                                                \"1 1 2 2\");\n                   });\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildDomainBadNCells) {\n  constexpr int dim = this->dim;\n  using Parameters = framework::FrameworkParameters;\n  auto finite_element_ptr = std::make_shared<NiceMock<domain::finite_element::FiniteElementMock<dim>>>();\n\n  const auto bad_index{ bart::test_helpers::RandomInt(0, this->dim) };\n  auto bad_n_cells { this->n_cells };\n  bad_n_cells.at(bad_index) = 0;\n\n  EXPECT_ANY_THROW({\n                     auto test_domain_ptr = this->test_builder_ptr_->BuildDomain(Parameters::DomainSize(this->spatial_max),\n                                                                                 Parameters::NumberOfCells(bad_n_cells),\n                                                                                 finite_element_ptr,\n                                                                                 \"1 1 2 2\");\n                   });\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildGroupSourceIterationTest) {\n  using ExpectedType = iteration::group::GroupSourceIteration<this->dim>;\n  using UpdaterPointersStruct = typename framework::builder::FrameworkBuilder<this->dim>::UpdaterPointers;\n\n  UpdaterPointersStruct updater_ptrs;\n  updater_ptrs.scattering_source_updater_ptr = this->scattering_source_updater_sptr_;\n\n  EXPECT_CALL(*this->validator_obs_ptr_, AddPart(Part::ScatteringSourceUpdate)).WillOnce(DoDefault());\n\n  auto source_iteration_ptr = this->test_builder_ptr_->BuildGroupSolveIteration(\n      std::move(this->single_group_solver_uptr_),\n      std::move(this->moment_convergence_checker_uptr_),\n      std::move(this->moment_calculator_uptr_),\n      this->group_solution_sptr_,\n      updater_ptrs,\n      nullptr);\n  EXPECT_THAT(source_iteration_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildGroupSourceIterationWithBCUpdateTest) {\n  using ExpectedType = iteration::group::GroupSourceIteration<this->dim>;\n  using UpdaterPointersStruct = typename framework::builder::FrameworkBuilder<this->dim>::UpdaterPointers;\n\n  UpdaterPointersStruct updater_ptrs;\n  updater_ptrs.scattering_source_updater_ptr = this->scattering_source_updater_sptr_;\n  updater_ptrs.boundary_conditions_updater_ptr = this->boundary_conditions_updater_sptr_;\n\n  EXPECT_CALL(*this->validator_obs_ptr_, AddPart(Part::ScatteringSourceUpdate)).WillOnce(DoDefault());\n\n  auto source_iteration_ptr = this->test_builder_ptr_->BuildGroupSolveIteration(\n      std::move(this->single_group_solver_uptr_),\n      std::move(this->moment_convergence_checker_uptr_),\n      std::move(this->moment_calculator_uptr_),\n      this->group_solution_sptr_,\n      updater_ptrs,\n      nullptr);\n  EXPECT_THAT(source_iteration_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildGroupSolution) {\n  using ExpectedType = system::solution::MPIGroupAngularSolution;\n  const int n_angles = bart::test_helpers::RandomDouble(1, 10);\n  auto group_solution_ptr = this->test_builder_ptr_->BuildGroupSolution(n_angles);\n\n  ASSERT_THAT(group_solution_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_EQ(n_angles, group_solution_ptr->total_angles());\n}\n\n// BuildFiniteElement should return correct object when given good parameters\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildFiniteElementFrameworkParameters) {\n  constexpr int dim = this->dim;\n  using PolynomialDegree = framework::FrameworkParameters::PolynomialDegree;\n  using ExpectedType = domain::finite_element::FiniteElementGaussian<dim>;\n\n  auto finite_element_ptr = this->test_builder_ptr_->BuildFiniteElement(problem::CellFiniteElementType::kGaussian,\n                                                                        problem::DiscretizationType::kContinuousFEM,\n                                                                        PolynomialDegree(this->polynomial_degree));\n  ASSERT_NE(finite_element_ptr, nullptr);\n  auto gaussian_ptr = dynamic_cast<ExpectedType*>(finite_element_ptr.get());\n  ASSERT_NE(gaussian_ptr, nullptr);\n  EXPECT_EQ(finite_element_ptr->polynomial_degree(), this->polynomial_degree);\n  auto dealii_finite_element_ptr = dynamic_cast<dealii::FE_Q<dim>*>(finite_element_ptr->finite_element());\n  ASSERT_NE(dealii_finite_element_ptr, nullptr);\n}\n\n// BuildFiniteElement should throw if bad parameters are passed\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildFiniteElementFrameworkParametersBadPolynomialDegree) {\n  constexpr int dim = this->dim;\n  using PolynomialDegree = framework::FrameworkParameters::PolynomialDegree;\n  using ExpectedType = domain::finite_element::FiniteElementGaussian<dim>;\n  auto bad_polynomial_degrees = bart::test_helpers::RandomVector(5, -10, -1);\n  bad_polynomial_degrees.push_back(0);\n  for (int bad_polynomial_degree : bad_polynomial_degrees) {\n    EXPECT_ANY_THROW({\n      auto finite_element_ptr = this->test_builder_ptr_->BuildFiniteElement(problem::CellFiniteElementType::kGaussian,\n                                                                            problem::DiscretizationType::kContinuousFEM,\n                                                                            PolynomialDegree(bad_polynomial_degree));\n    });\n  }\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildKeffectiveUpdater) {\n  using ExpectedType = eigenvalue::k_eigenvalue::CalculatorViaFissionSource;\n  EXPECT_CALL(*this->finite_element_sptr_, n_cell_quad_pts())\n      .WillOnce(Return(10));\n  auto k_effective_updater_ptr = this->test_builder_ptr_->BuildKEffectiveUpdater(\n      this->finite_element_sptr_,\n      this->cross_sections_sptr_,\n      this->domain_sptr_);\n  EXPECT_THAT(k_effective_updater_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildKeffectiveUpdaterRayleighQuotient) {\n  using ExpectedType = eigenvalue::k_eigenvalue::CalculatorViaRayleighQuotient;\n\n  auto k_effective_updater_ptr = this->test_builder_ptr_->BuildKEffectiveUpdater();\n  EXPECT_THAT(k_effective_updater_ptr.get(), WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildMomentCalculatorScalar) {\n  using ExpectedType = quadrature::calculators::ScalarMoment;\n\n  auto moment_calculator_ptr = this->test_builder_ptr_->BuildMomentCalculator();\n  ASSERT_THAT(moment_calculator_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildMomentCalculatorScalarQuadSet) {\n  using ExpectedType = quadrature::calculators::ScalarMoment;\n  using Implementation = quadrature::MomentCalculatorImpl;\n  auto moment_calculator_ptr = this->test_builder_ptr_->BuildMomentCalculator(\n      this->quadrature_set_sptr_, Implementation::kScalarMoment);\n  ASSERT_THAT(moment_calculator_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BulidMomentCalculatorAngular) {\n  constexpr int dim = this->dim;\n  using ExpectedType = quadrature::calculators::SphericalHarmonicZerothMoment<dim>;\n\n  auto moment_calculator_ptr = this->test_builder_ptr_->BuildMomentCalculator(\n      this->quadrature_set_sptr_);\n  ASSERT_THAT(moment_calculator_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildPowerIterationTest) {\n  EXPECT_CALL(*this->validator_obs_ptr_, AddPart(Part::FissionSourceUpdate)).WillOnce(DoDefault());\n\n  auto power_iteration_ptr = this->test_builder_ptr_->BuildOuterIteration(\n      std::move(this->group_solve_iteration_uptr_),\n      std::move(this->parameter_convergence_checker_uptr_),\n      std::move(this->k_effective_updater_uptr_),\n      this->fission_source_updater_sptr_,\n      \"test\");\n  using ExpectedType = iteration::outer::OuterPowerIteration;\n  ASSERT_THAT(power_iteration_ptr.get(),\n                  WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_EQ(remove(\"test_iteration_error.csv\"), 0);\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildFixedSourceIterationTest) {\n  auto power_iteration_ptr = this->test_builder_ptr_->BuildOuterIteration(\n      std::move(this->group_solve_iteration_uptr_),\n      std::move(this->parameter_convergence_checker_uptr_), \"\");\n  using ExpectedType = iteration::outer::OuterFixedSourceIteration;\n  ASSERT_THAT(power_iteration_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildQuadratureSetBadOrder) {\n  using Order = framework::FrameworkParameters::AngularQuadratureOrder;\n  auto bad_orders{ test_helpers::RandomVector(5, -10, -1) };\n  bad_orders.push_back(0);\n  for (const auto bad_order : bad_orders) {\n    for (const auto quadrature_type : {problem::AngularQuadType::kLevelSymmetricGaussian,\n                                       problem::AngularQuadType::kGaussLegendre}) {\n      EXPECT_ANY_THROW({\n        auto quadrature_set = this->test_builder_ptr_->BuildQuadratureSet(quadrature_type, Order(bad_order));\n      });\n    }\n  }\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildGaussLegendreQuadratureSetWithParameters) {\n  constexpr int dim = this->dim;\n  const framework::FrameworkParameters::AngularQuadratureOrder order{ 4 };\n  const auto framework_type { problem::AngularQuadType::kGaussLegendre };\n\n  if (dim == 1) {\n    using ExpectedType = quadrature::QuadratureSet<dim>;\n    auto quadrature_set = this->test_builder_ptr_->BuildQuadratureSet(framework_type, order);\n    ASSERT_NE(nullptr, quadrature_set);\n    ASSERT_NE(nullptr, dynamic_cast<ExpectedType*>(quadrature_set.get()));\n    EXPECT_EQ(quadrature_set->size(), 2*order.get());\n  } else {\n    EXPECT_ANY_THROW({\n      auto quadrature_set = this->test_builder_ptr_->BuildQuadratureSet(framework_type, order);\n                     });\n  }\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildLSAngularQuadratureSetWithParameters) {\n  constexpr int dim = this->dim;\n  const framework::FrameworkParameters::AngularQuadratureOrder order{ 4 };\n  const auto framework_type { problem::AngularQuadType::kLevelSymmetricGaussian };\n\n  if (dim == 3) {\n    using ExpectedType = quadrature::QuadratureSet<dim>;\n    auto quadrature_set = this->test_builder_ptr_->BuildQuadratureSet(framework_type, order);\n    ASSERT_NE(nullptr, quadrature_set);\n    ASSERT_NE(nullptr, dynamic_cast<ExpectedType*>(quadrature_set.get()));\n    EXPECT_EQ(quadrature_set->size(), order.get() * (order.get() + 2));\n  } else {\n    EXPECT_ANY_THROW({\n      auto quadrature_set = this->test_builder_ptr_->BuildQuadratureSet(framework_type, order);\n                     });\n  }\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildkNoneTypeQuadratureSetWithParameters) {\n  const framework::FrameworkParameters::AngularQuadratureOrder order{ 4 };\n  const auto framework_type { problem::AngularQuadType::kNone };\n\n  EXPECT_ANY_THROW({\n    auto quadrature_set = this->test_builder_ptr_->BuildQuadratureSet(framework_type, order);\n                   });\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildSingleGroupSolver) {\n  using ExpectedType = solver::group::SingleGroupSolver;\n\n  auto solver_ptr = this->test_builder_ptr_->BuildSingleGroupSolver(100, 1e-12);\n\n  ASSERT_NE(nullptr, solver_ptr);\n\n  auto dynamic_ptr = dynamic_cast<ExpectedType*>(solver_ptr.get());\n  ASSERT_NE(nullptr, dynamic_ptr);\n\n  using ExpectedLinearSolverType = solver::linear::GMRES;\n\n  auto linear_solver_ptr = dynamic_cast<ExpectedLinearSolverType*>(\n      dynamic_ptr->linear_solver_ptr());\n\n  ASSERT_NE(nullptr, linear_solver_ptr);\n  EXPECT_EQ(linear_solver_ptr->convergence_tolerance(), 1e-12);\n  EXPECT_EQ(linear_solver_ptr->max_iterations(), 100);\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildConvergenceChecker) {\n  const double max_delta = 1e-4;\n  const int max_iterations = 100;\n\n  auto convergence_ptr =\n      this->test_builder_ptr_->BuildParameterConvergenceChecker(\n          max_delta,\n          max_iterations);\n\n  using ParameterConvergenceChecker = convergence::IterationCompletionChecker<double>;\n\n\n  ASSERT_NE(convergence_ptr, nullptr);\n  EXPECT_NE(nullptr, dynamic_cast<ParameterConvergenceChecker*>(convergence_ptr.get()));\n  EXPECT_EQ(convergence_ptr->max_iterations(), max_iterations);\n\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildMomentConvergenceChecker) {\n  const double max_delta = 1e-4;\n  const int max_iterations = 73;\n\n  auto convergence_ptr =\n      this->test_builder_ptr_->BuildMomentConvergenceChecker(\n          max_delta,\n          max_iterations);\n\n  using ExpectedType = convergence::IterationCompletionChecker<system::moments::MomentVector>;\n\n  EXPECT_THAT(convergence_ptr.get(), WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_EQ(convergence_ptr->max_iterations(), max_iterations);\n\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildMomentMapConvergenceChecker) {\n  const double max_delta = 1e-4;\n  const int max_iterations = 73;\n\n  auto convergence_ptr = this->test_builder_ptr_->BuildMomentMapConvergenceChecker(max_delta, max_iterations);\n  using ExpectedType = convergence::IterationCompletionChecker<system::moments::MomentsMap>;\n  ASSERT_THAT(convergence_ptr.get(), WhenDynamicCastTo<ExpectedType*>(NotNull()));\n  EXPECT_EQ(convergence_ptr->max_iterations(), max_iterations);\n}\n\n\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildSAAFFormulationTest) {\n  constexpr int dim = this->dim;\n\n  auto finite_element_ptr =\n      std::make_shared<domain::finite_element::FiniteElementMock<dim>>();\n  auto cross_sections_ptr =\n      std::make_shared<data::cross_sections::MaterialCrossSections>(this->mock_material);\n  auto quadrature_set_ptr =\n      std::make_shared<quadrature::QuadratureSetMock<dim>>();\n\n  EXPECT_CALL(*finite_element_ptr, dofs_per_cell());\n  EXPECT_CALL(*finite_element_ptr, n_cell_quad_pts());\n  EXPECT_CALL(*finite_element_ptr, n_face_quad_pts());\n\n  auto saaf_formulation_ptr = this->test_builder_ptr_->BuildSAAFFormulation(\n      finite_element_ptr, cross_sections_ptr, quadrature_set_ptr);\n\n  using ExpectedType = formulation::angular::SelfAdjointAngularFlux<dim>;\n\n  EXPECT_THAT(saaf_formulation_ptr.get(),\n              WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildStamper) {\n  constexpr int dim = this->dim;\n\n  auto domain_ptr = std::make_shared<domain::DomainMock<dim>>();\n\n  using ExpectedType = formulation::Stamper<dim>;\n  auto stamper_ptr = this->test_builder_ptr_->BuildStamper(domain_ptr);\n\n  EXPECT_THAT(stamper_ptr.get(), WhenDynamicCastTo<ExpectedType*>(NotNull()));\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildSubroutine) {\n  using ExpectedType = iteration::subroutine::GetScalarFluxFromFramework;\n  auto subroutine_ptr = this->test_builder_ptr_->BuildSubroutine(\n      std::move(this->framework_uptr_),\n      iteration::subroutine::SubroutineName::kGetScalarFluxFromFramework);\n  auto dynamic_ptr{ dynamic_cast<ExpectedType*>(subroutine_ptr.get()) };\n  ASSERT_NE(dynamic_ptr, nullptr);\n  EXPECT_NE(dynamic_ptr->framework_ptr(), nullptr);\n}\n\nTYPED_TEST(FrameworkBuilderIntegrationTest, BuildSystem) {\n  constexpr int dim = this->dim;\n  using VariableLinearTerms = system::terms::VariableLinearTerms;\n\n  domain::DomainMock<dim> mock_domain;\n  const int total_groups = 2, total_angles = 3;\n  const std::size_t solution_size = 10;\n  const bool is_eigenvalue_problem = true, need_rhs_boundary_condition = false;\n\n  EXPECT_CALL(mock_domain, MakeSystemMatrix())\n      .Times(total_angles * total_groups)\n      .WillRepeatedly(Return(std::make_shared<system::MPISparseMatrix>()));\n  EXPECT_CALL(mock_domain, MakeSystemVector())\n      .Times(3*total_angles * total_groups)\n      .WillRepeatedly(Return(std::make_shared<system::MPIVector>()));\n\n  auto system_ptr = this->test_builder_ptr_->BuildSystem(\n      total_groups, total_angles, mock_domain, solution_size,\n      is_eigenvalue_problem, need_rhs_boundary_condition);\n\n  auto& system = *system_ptr;\n\n  EXPECT_EQ(system.total_groups, total_groups);\n  EXPECT_EQ(system.total_angles, total_angles);\n  EXPECT_EQ(system.k_effective.value(), 1.0);\n  ASSERT_NE(nullptr, system.right_hand_side_ptr_);\n  EXPECT_THAT(system.right_hand_side_ptr_->GetVariableTerms(),\n            ::testing::UnorderedElementsAre(VariableLinearTerms::kFissionSource,\n                                            VariableLinearTerms::kScatteringSource));\n  ASSERT_NE(nullptr, system.left_hand_side_ptr_);\n\n  for (const auto& moments : {system.current_moments.get(),\n                              system.previous_moments.get()}) {\n    ASSERT_NE(nullptr, moments);\n    EXPECT_EQ(moments->total_groups(), total_groups);\n    EXPECT_EQ(moments->max_harmonic_l(), 0);\n    for (const auto& moment : *moments)\n      EXPECT_EQ(moment.second.size(), solution_size);\n  }\n}\n\n/* ===== Non-dimensional tests =================================================\n * These tests instantiate classes and use depdent classes that do not have a\n * dimension template varaible and therefore only need to be run in a single\n * dimension.\n*/\n\n\nclass FrameworkBuilderIntegrationNonDimTest\n : public FrameworkBuilderIntegrationTest<bart::testing::OneD> {};\n\nTEST_F(FrameworkBuilderIntegrationNonDimTest, BuildDefaultInitializer) {\n  using InitializerName = iteration::initializer::InitializerName;\n  auto fixed_updater_ptr = std::make_shared<formulation::updater::FixedUpdaterMock>();\n\n  using ExpectedType = iteration::initializer::InitializeFixedTermsOnce;\n  const int total_groups = bart::test_helpers::RandomDouble(1, 10);\n  const int total_angles = total_groups + 1;\n\n  auto initializer_ptr = this->test_builder_ptr_->BuildInitializer(fixed_updater_ptr,\n                                                                  total_groups,\n                                                                  total_angles);\n  auto dynamic_ptr = dynamic_cast<ExpectedType*>(initializer_ptr.get());\n  ASSERT_NE(initializer_ptr, nullptr);\n  ASSERT_NE(dynamic_ptr, nullptr);\n  EXPECT_EQ(dynamic_ptr->total_angles(), total_angles);\n  EXPECT_EQ(dynamic_ptr->total_groups(), total_groups);\n}\n\nTEST_F(FrameworkBuilderIntegrationNonDimTest, BuildInitializerFixedOnceSpecified) {\n  using InitializerName = iteration::initializer::InitializerName;\n  auto fixed_updater_ptr = std::make_shared<formulation::updater::FixedUpdaterMock>();\n\n  using ExpectedType = iteration::initializer::InitializeFixedTermsOnce;\n  const int total_groups = bart::test_helpers::RandomDouble(1, 10);\n  const int total_angles = total_groups + 1;\n\n  auto initializer_ptr = this->test_builder_ptr_->BuildInitializer(fixed_updater_ptr,\n                                                                   total_groups,\n                                                                   total_angles,\n                                                                   InitializerName::kInitializeFixedTermsOnce);\n  auto dynamic_ptr = dynamic_cast<ExpectedType*>(initializer_ptr.get());\n  ASSERT_NE(initializer_ptr, nullptr);\n  ASSERT_NE(dynamic_ptr, nullptr);\n  EXPECT_EQ(dynamic_ptr->total_angles(), total_angles);\n  EXPECT_EQ(dynamic_ptr->total_groups(), total_groups);\n}\n\nTEST_F(FrameworkBuilderIntegrationNonDimTest, BuildInitializerResetMoments) {\n  using InitializerName = iteration::initializer::InitializerName;\n  auto fixed_updater_ptr = std::make_shared<formulation::updater::FixedUpdaterMock>();\n\n  using ExpectedType = iteration::initializer::InitializeFixedTermsResetMoments;\n  const int total_groups = bart::test_helpers::RandomDouble(1, 10);\n  const int total_angles = total_groups + 1;\n\n  auto initializer_ptr = this->test_builder_ptr_->BuildInitializer(fixed_updater_ptr,\n                                                                   total_groups,\n                                                                   total_angles,\n                                                                   InitializerName::kInitializeFixedTermsAndResetMoments);\n  auto dynamic_ptr = dynamic_cast<ExpectedType*>(initializer_ptr.get());\n  ASSERT_NE(initializer_ptr, nullptr);\n  ASSERT_NE(dynamic_ptr, nullptr);\n  EXPECT_EQ(dynamic_ptr->total_angles(), total_angles);\n  EXPECT_EQ(dynamic_ptr->total_groups(), total_groups);\n}\n\n} // namespace\n", "meta": {"hexsha": "afea7900a46045b6cb89b89fe49cd8193f0b23fb", "size": 42955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/framework/builder/tests/framework_builder_integration_tests.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/framework/builder/tests/framework_builder_integration_tests.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/framework/builder/tests/framework_builder_integration_tests.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 46.4880952381, "max_line_length": 123, "alphanum_fraction": 0.745128623, "num_tokens": 9561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17704613614580653}}
{"text": "/* boost random/detail/generator_bits.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: generator_bits.hpp 72951 2011-07-07 04:57:37Z steven_watanabe $\n *\n */\n\n#ifndef BOOST_RANDOM_DETAIL_GENERATOR_BITS_HPP\n#define BOOST_RANDOM_DETAIL_GENERATOR_BITS_HPP\n\n#include <boost/limits.hpp>\n\nnamespace boost {\nnamespace random {\nnamespace detail {\n\n// This is a temporary measure that retains backwards\n// compatibility.\ntemplate<class URNG>\nstruct generator_bits {\n    static std::size_t value() {\n        return std::numeric_limits<typename URNG::result_type>::digits;\n    }\n};\n\n} // namespace detail\n} // namespace random\n} // namespace boost\n\n#endif // BOOST_RANDOM_DETAIL_GENERATOR_BITS_HPP\n", "meta": {"hexsha": "44b4248b2f3ef8bc3d07d316905a1484314b38ad", "size": 938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nuparu/include/boost/random/detail/generator_bits.hpp", "max_stars_repo_name": "jumokbap/Practice_CentOS", "max_stars_repo_head_hexsha": "df38220f326e24a0df9e16326b7ae4aa67252fe9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 324.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:56:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T04:52:37.000Z", "max_issues_repo_path": "src/third_party/boost/boost/random/detail/generator_bits.hpp", "max_issues_repo_name": "wujf/mongo", "max_issues_repo_head_hexsha": "f2f48b749ded0c5585c798c302f6162f19336670", "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": "src/third_party/boost/boost/random/detail/generator_bits.hpp", "max_forks_repo_name": "wujf/mongo", "max_forks_repo_head_hexsha": "f2f48b749ded0c5585c798c302f6162f19336670", "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": 25.3513513514, "max_line_length": 76, "alphanum_fraction": 0.7547974414, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17704613614580653}}
{"text": "#include <boost/python.hpp>\n#include <boost/numpy.hpp>\n\n#include \"game/rigid_body_motion_estimation.h\"\n\nnamespace bp = boost::python;\nnamespace np = boost::numpy;\n\nBOOST_PYTHON_MODULE(librigid_body_motion_estimation) {\n  np::initialize();\n\n  bp::class_<game::RotorTranslationVectorEstimation>(\"RotorTranslationVectorEstimation\", bp::init<const bp::dict&>())\n      .def(\"run\", &game::RotorTranslationVectorEstimation::Run)\n      .def(\"summary\", &game::RotorTranslationVectorEstimation::Summary);\n\n  bp::class_<game::RotorTranslationVectorBivectorGeneratorEstimation>(\"RotorTranslationVectorBivectorGeneratorEstimation\")\n      .def(\"run\", &game::RotorTranslationVectorBivectorGeneratorEstimation::Run)\n      .def(\"summary\", &game::RotorTranslationVectorBivectorGeneratorEstimation::Summary);\n\n  bp::class_<game::GeneralRotorEstimation>(\"GeneralRotorEstimation\")\n      .def(\"run\", &game::GeneralRotorEstimation::Run)\n      .def(\"summary\", &game::GeneralRotorEstimation::Summary);\n\n}", "meta": {"hexsha": "61403cc96c3429fdca36290e9048548a2b5c7d53", "size": 979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rigid_body_motion_estimation_wrapper.cpp", "max_stars_repo_name": "tingelst/game", "max_stars_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-07-25T08:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T23:05:46.000Z", "max_issues_repo_path": "src/rigid_body_motion_estimation_wrapper.cpp", "max_issues_repo_name": "tingelst/game", "max_issues_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T09:32:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T09:41:47.000Z", "max_forks_repo_path": "src/rigid_body_motion_estimation_wrapper.cpp", "max_forks_repo_name": "tingelst/game", "max_forks_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T04:42:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-12T12:56:45.000Z", "avg_line_length": 40.7916666667, "max_line_length": 122, "alphanum_fraction": 0.7691521961, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17704613614580653}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (c) 2018-2020, The Regents of the University of California\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\n// 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 \"initialPlace.h\"\n#include \"placerBase.h\"\n#include <iostream>\n\n#include <Eigen/IterativeLinearSolvers>\n\n#include \"plot.h\"\n#include \"graphics.h\"\n\n#include \"utility/Logger.h\"\n\nnamespace gpl {\nusing namespace std;\n\nusing Eigen::BiCGSTAB;\nusing Eigen::IdentityPreconditioner;\nusing utl::GPL;\n\ntypedef Eigen::Triplet< float > T;\n\nInitialPlaceVars::InitialPlaceVars() \n{\n  reset();\n}\n\nvoid InitialPlaceVars::reset() {\n  maxIter = 20;\n  minDiffLength = 1500;\n  maxSolverIter = 100;\n  maxFanout = 200;\n  netWeightScale = 800.0;\n  incrementalPlaceMode = false;\n  debug = false;\n}\n\nInitialPlace::InitialPlace()\n: ipVars_(), pb_(nullptr), log_(nullptr) {} \n\nInitialPlace::InitialPlace(InitialPlaceVars ipVars, \n    std::shared_ptr<PlacerBase> pb,\n    utl::Logger* log)\n: ipVars_(ipVars), pb_(pb), log_(log)\n{\n}\n\nInitialPlace::~InitialPlace() {\n  reset();\n}\n\nvoid InitialPlace::reset() {\n  pb_ = nullptr;\n  ipVars_.reset();\n}\n\n#ifdef ENABLE_CIMG_LIB\nstatic PlotEnv pe;\n#endif\n\nvoid InitialPlace::doBicgstabPlace() {\n  float errorX = 0.0f, errorY = 0.0f;\n\n#ifdef ENABLE_CIMG_LIB\n  pe.setPlacerBase(pb_);\n  pe.Init();\n#endif\n\n  std::unique_ptr<Graphics> graphics;\n  if (ipVars_.debug && Graphics::guiActive()) {\n    graphics = make_unique<Graphics>(log_, pb_, this);\n  }\n\n  // normally, initial place will place all cells in the centers.\n  if( !ipVars_.incrementalPlaceMode ) {\n    placeInstsCenter();\n  }\n\n  // set ExtId for idx reference // easy recovery\n  setPlaceInstExtId();\n  for(int i=1; i<=ipVars_.maxIter; i++) {\n    updatePinInfo();\n    createSparseMatrix();\n\n    // BiCGSTAB solver for initial place\n    BiCGSTAB< SMatrix, IdentityPreconditioner > solver;\n    solver.setMaxIterations(ipVars_.maxSolverIter);\n    solver.compute(placeInstForceMatrixX_);\n    instLocVecX_ = solver.solveWithGuess(fixedInstForceVecX_, instLocVecX_);\n    errorX = solver.error();\n\n    solver.compute(placeInstForceMatrixY_);\n    instLocVecY_ = solver.solveWithGuess(fixedInstForceVecY_, instLocVecY_);\n    errorY = solver.error();\n\n    log_->report(\"[InitialPlace]  Iter: {} CG Error: {:0.8f} HPWL: {}\",\n       i, max(errorX, errorY), pb_->hpwl());\n    updateCoordi();\n\n#ifdef ENABLE_CIMG_LIB\n    pe.SaveCellPlotAsJPEG(\n        string(\"InitPlace \") + to_string(i), false,\n        string(\"./plot/cell/ip_\") + to_string(i));\n#endif\n\n    if (graphics) {\n        graphics->cellPlot(true);\n    }\n\n    if( max(errorX, errorY) <= 1e-5 && i >= 5 ) {\n      break;\n    }\n  }\n}\n\n// starting point of initial place is center.\nvoid InitialPlace::placeInstsCenter() {\n  const int centerX = pb_->die().coreCx();\n  const int centerY = pb_->die().coreCy();\n\n  for(auto& inst: pb_->placeInsts()) {\n    inst->setCenterLocation(centerX, centerY);\n  }\n}\n\nvoid InitialPlace::setPlaceInstExtId() {\n  // reset ExtId for all instances\n  for(auto& inst : pb_->insts()) {\n    inst->setExtId(INT_MAX);\n  }\n  // set index only with place-able instances\n  for(auto& inst : pb_->placeInsts()) {\n    inst->setExtId(&inst - &(pb_->placeInsts()[0]));\n  }\n}\n\nvoid InitialPlace::updatePinInfo() {\n  // reset all MinMax attributes\n  for(auto& pin : pb_->pins()) {\n    pin->unsetMinPinX();\n    pin->unsetMinPinY();\n    pin->unsetMaxPinX();\n    pin->unsetMaxPinY();\n  }\n\n  for(auto& net : pb_->nets()) {\n    Pin* pinMinX = nullptr, *pinMinY = nullptr;\n    Pin* pinMaxX = nullptr, *pinMaxY = nullptr;  \n    int lx = INT_MAX, ly = INT_MAX;\n    int ux = INT_MIN, uy = INT_MIN;\n\n    // Mark B2B info on Pin structures\n    for(auto& pin : net->pins()) {\n      if( lx > pin->cx() ) {\n        if( pinMinX ) {\n          pinMinX->unsetMinPinX();\n        }\n        lx = pin->cx();\n        pinMinX = pin; \n        pinMinX->setMinPinX();\n      } \n      \n      if( ux < pin->cx() ) {\n        if( pinMaxX ) {\n          pinMaxX->unsetMaxPinX();\n        }\n        ux = pin->cx();\n        pinMaxX = pin; \n        pinMaxX->setMaxPinX();\n      } \n\n      if( ly > pin->cy() ) {\n        if( pinMinY ) {\n          pinMinY->unsetMinPinY();\n        }\n        ly = pin->cy();\n        pinMinY = pin; \n        pinMinY->setMinPinY();\n      } \n      \n      if( uy < pin->cy() ) {\n        if( pinMaxY ) {\n          pinMaxY->unsetMaxPinY();\n        }\n        uy = pin->cy();\n        pinMaxY = pin; \n        pinMaxY->setMaxPinY();\n      } \n    }\n  } \n}\n\n// solve placeInstForceMatrixX_ * xcg_x_ = xcg_b_ and placeInstForceMatrixY_ * ycg_x_ = ycg_b_ eq.\nvoid InitialPlace::createSparseMatrix() {\n  const int placeCnt = pb_->placeInsts().size();\n  instLocVecX_.resize( placeCnt );\n  fixedInstForceVecX_.resize( placeCnt );\n  instLocVecY_.resize( placeCnt );\n  fixedInstForceVecY_.resize( placeCnt );\n\n  placeInstForceMatrixX_.resize( placeCnt, placeCnt );\n  placeInstForceMatrixY_.resize( placeCnt, placeCnt );\n\n\n  // \n  // listX and listY is a temporary vector that have tuples, (idx1, idx2, val)\n  //\n  // listX finally becomes placeInstForceMatrixX_\n  // listY finally becomes placeInstForceMatrixY_\n  //\n  // The triplet vector is recommended usages \n  // to fill in SparseMatrix from Eigen docs.\n  //\n\n  vector< T > listX, listY;\n  listX.reserve(1000000);\n  listY.reserve(1000000);\n\n  // initialize vector\n  for(auto& inst : pb_->placeInsts()) {\n    int idx = inst->extId(); \n    \n    instLocVecX_(idx) = inst->cx();\n    instLocVecY_(idx) = inst->cy();\n\n    fixedInstForceVecX_(idx) = fixedInstForceVecY_(idx) = 0;\n  }\n\n  // for each net\n  for(auto& net : pb_->nets()) {\n\n    // skip for small nets.\n    if( net->pins().size() <= 1 ) {\n      continue;\n    }\n \n    // escape long time cals on huge fanout.\n    //\n    if( net->pins().size() >= ipVars_.maxFanout) { \n      continue;\n    }\n\n    float netWeight = ipVars_.netWeightScale \n      / (net->pins().size() - 1);\n    //cout << \"net: \" << net.net()->getConstName() << endl;\n\n    // foreach two pins in single nets.\n    auto& pins = net->pins();\n    for(int pinIdx1 = 1; pinIdx1 < pins.size(); ++pinIdx1) {\n      Pin* pin1 = pins[pinIdx1];\n      for(int pinIdx2 = 0; pinIdx2 < pinIdx1; ++pinIdx2) {\n        Pin* pin2 = pins[pinIdx2];\n\n        // no need to fill in when instance is same\n        if( pin1->instance() == pin2->instance() ) {\n          continue;\n        }\n\n        // B2B modeling on min/maxX pins.\n        if( pin1->isMinPinX() || pin1->isMaxPinX() ||\n            pin2->isMinPinX() || pin2->isMaxPinX() ) {\n          int diffX = abs(pin1->cx() - pin2->cx());\n          float weightX = 0;\n          if( diffX > ipVars_.minDiffLength ) {\n            weightX = netWeight / diffX;\n          }\n          else {\n            weightX = netWeight \n              / ipVars_.minDiffLength;\n          }\n          //cout << weightX << endl;\n\n          // both pin cames from instance\n          if( pin1->isPlaceInstConnected() \n              && pin2->isPlaceInstConnected() ) {\n            const int inst1 = pin1->instance()->extId();\n            const int inst2 = pin2->instance()->extId();\n            //cout << \"inst: \" << inst1 << \" \" << inst2 << endl;\n\n            listX.push_back( T(inst1, inst1, weightX) );\n            listX.push_back( T(inst2, inst2, weightX) );\n\n            listX.push_back( T(inst1, inst2, -weightX) );\n            listX.push_back( T(inst2, inst1, -weightX) );\n\n            //cout << pin1->cx() << \" \" \n            //  << pin1->instance()->cx() << endl;\n            fixedInstForceVecX_(inst1) += \n              -weightX * (\n              (pin1->cx() - pin1->instance()->cx()) - \n              (pin2->cx() - pin2->instance()->cx()));\n\n            fixedInstForceVecX_(inst2) +=\n              -weightX * (\n              (pin2->cx() - pin2->instance()->cx()) -\n              (pin1->cx() - pin1->instance()->cx())); \n          }\n          // pin1 from IO port / pin2 from Instance\n          else if( !pin1->isPlaceInstConnected() \n              && pin2->isPlaceInstConnected() ) {\n            const int inst2 = pin2->instance()->extId();\n            //cout << \"inst2: \" << inst2 << endl;\n            listX.push_back( T(inst2, inst2, weightX) );\n            fixedInstForceVecX_(inst2) += weightX * \n              ( pin1->cx() - \n                ( pin2->cx() - pin2->instance()->cx()) );\n          }\n          // pin1 from Instance / pin2 from IO port\n          else if( pin1->isPlaceInstConnected() \n              && !pin2->isPlaceInstConnected() ) {\n            const int inst1 = pin1->instance()->extId();\n            //cout << \"inst1: \" << inst1 << endl;\n            listX.push_back( T(inst1, inst1, weightX) );\n            fixedInstForceVecX_(inst1) += weightX *\n              ( pin2->cx() -\n                ( pin1->cx() - pin1->instance()->cx()) );\n          }\n        }\n        \n        // B2B modeling on min/maxY pins.\n        if( pin1->isMinPinY() || pin1->isMaxPinY() ||\n            pin2->isMinPinY() || pin2->isMaxPinY() ) {\n          \n          int diffY = abs(pin1->cy() - pin2->cy());\n          float weightY = 0;\n          if( diffY > ipVars_.minDiffLength ) {\n            weightY = netWeight / diffY;\n          }\n          else {\n            weightY = netWeight \n              / ipVars_.minDiffLength;\n          }\n\n          // both pin cames from instance\n          if( pin1->isPlaceInstConnected() \n              && pin2->isPlaceInstConnected() ) {\n            const int inst1 = pin1->instance()->extId();\n            const int inst2 = pin2->instance()->extId();\n\n            listY.push_back( T(inst1, inst1, weightY) );\n            listY.push_back( T(inst2, inst2, weightY) );\n\n            listY.push_back( T(inst1, inst2, -weightY) );\n            listY.push_back( T(inst2, inst1, -weightY) );\n\n            fixedInstForceVecY_(inst1) += \n              -weightY * (\n              (pin1->cy() - pin1->instance()->cy()) - \n              (pin2->cy() - pin2->instance()->cy()));\n\n            fixedInstForceVecY_(inst2) +=\n              -weightY * (\n              (pin2->cy() - pin2->instance()->cy()) -\n              (pin1->cy() - pin1->instance()->cy())); \n          }\n          // pin1 from IO port / pin2 from Instance\n          else if( !pin1->isPlaceInstConnected() \n              && pin2->isPlaceInstConnected() ) {\n            const int inst2 = pin2->instance()->extId();\n            listY.push_back( T(inst2, inst2, weightY) );\n            fixedInstForceVecY_(inst2) += weightY * \n              ( pin1->cy() - \n                ( pin2->cy() - pin2->instance()->cy()) );\n          }\n          // pin1 from Instance / pin2 from IO port\n          else if( pin1->isPlaceInstConnected() \n              && !pin2->isPlaceInstConnected() ) {\n            const int inst1 = pin1->instance()->extId();\n            listY.push_back( T(inst1, inst1, weightY) );\n            fixedInstForceVecY_(inst1) += weightY *\n              ( pin2->cy() -\n                ( pin1->cy() - pin1->instance()->cy()) );\n          }\n        }\n      }\n    }\n  } \n\n  placeInstForceMatrixX_.setFromTriplets(listX.begin(), listX.end());\n  placeInstForceMatrixY_.setFromTriplets(listY.begin(), listY.end());\n}\n\nvoid InitialPlace::updateCoordi() {\n  for(auto& inst : pb_->placeInsts()) {\n    int idx = inst->extId();\n    inst->dbSetCenterLocation( instLocVecX_(idx), instLocVecY_(idx) );\n  }\n}\n\n}\n", "meta": {"hexsha": "edb5a97de007bccaeb5dcb82c939866daf2b25b7", "size": 12861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/replace/src/initialPlace.cpp", "max_stars_repo_name": "ibrahimkhairy/OpenROAD", "max_stars_repo_head_hexsha": "399a51332ce32e816b914f38cd38b9d0fe77785f", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-20T04:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T04:25:57.000Z", "max_issues_repo_path": "src/replace/src/initialPlace.cpp", "max_issues_repo_name": "QuantamHD/OpenROAD", "max_issues_repo_head_hexsha": "5a8314e60cfebd07b843e91c41a13b42a22f55e4", "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": "src/replace/src/initialPlace.cpp", "max_forks_repo_name": "QuantamHD/OpenROAD", "max_forks_repo_head_hexsha": "5a8314e60cfebd07b843e91c41a13b42a22f55e4", "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.4763033175, "max_line_length": 98, "alphanum_fraction": 0.5754606951, "num_tokens": 3501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.1769564532715677}}
{"text": "#include \"biggles/observation.hpp\"\n#include \"biggles/detail/random.hpp\"\n#include \"biggles/mh_moves/mh_moves.hpp\"\n#include \"biggles/mh_moves/utility.hpp\"\n#include \"biggles/tracker.hpp\"\n#include \"biggles/simulate.hpp\"\n#include <boost/filesystem.hpp>\n#include <boost/foreach.hpp>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <fstream>\n#include <algorithm>\n#include <string>\n#include \"biggles/tools/sundries.hpp\"\n\n// include this last to stop pre-processor macros breaking things\nextern \"C\" {\n#include <ccan/tap/tap.h>\n}\n\nusing namespace biggles;\n\nclass select_move_from {\n    std::deque<mh_moves::move_type> m_data;\n    int m_size;\npublic:\n    select_move_from &operator<<(const mh_moves::move_type &type) {\n        m_data.push_back(type);\n        m_size = int(m_data.size());\n        return *this;\n    }\n    mh_moves::move_type operator()() const {\n        return m_data[biggles::sampling::uniform_int(0, m_size)];\n    }\n};\n\nmh_moves::move_type simple_metropolis_hastings(partition_ptr_t &partition_ptr, const model::parameters& para,\n        const select_move_from &selector)\n{\n    const capability_recorder_ptr &cap_rec_ptr(partition_ptr->get_capability_recorder());\n    mh_moves::move_type this_move(selector());\n    biggles_move proposal(mh_moves::move_name(this_move));\n    float pdr;\n    partition_ptr_t proposed_sample_ptr;\n    bool success = proposal(partition_ptr, proposed_sample_ptr, pdr);\n    if (not success) {\n        return mh_moves::IDENTITY;\n    }\n\n    float proposed_density = model::log_partition_given_parameters_density(*proposed_sample_ptr, para);\n    float current_density = model::log_partition_given_parameters_density(*partition_ptr, para);\n    float mh_ratio = proposed_density - current_density + pdr;\n    bool accept = logf(sampling::uniform_real()) < mh_ratio;\n    if (accept) {\n        partition_ptr = proposed_sample_ptr;\n        cap_rec_ptr->commit_changes(partition_ptr->tracks());\n    }\n    else {\n        this_move = mh_moves::NONE;\n    }\n    return this_move;\n}\n\nstd::ostream &get_ostream(const std::string &fname, std::ofstream &fout) {\n    if (fname.size() > 0) {\n        fout.open(fname.c_str());\n        if (fout.good()) {\n            return fout;\n        }\n    }\n    return std::cout;\n}\n\n\nvoid log_part_for_para_sampler(partition &partition_ptr, const general_paras &opts) {\n    model::parameters para_sample;\n    std::string fname(boost::filesystem::temp_directory_path().string());\n    std::ofstream fh((fname + \"/cpp_biggles.log_part_for_para.txt\").c_str());\n    for (int i = 0; i < opts.total; ++i) {\n        sample_model_parameters_given_partition(partition_ptr, para_sample);\n        fh\n            << model::log_partition_given_parameters_density(partition_ptr, para_sample)\n            << std::endl\n        ;\n    }\n}\n\nvoid parameter_sampler(partition &partition_ptr, const general_paras &opts) {\n    model::parameters para_sample;\n    std::ofstream fh;\n    std::ostream &out = get_ostream(opts.rgp.output, fh);\n    for (int i = 0; i < opts.total; ++i) {\n        sample_model_parameters_given_partition(partition_ptr, para_sample);\n        out << model::mean_new_tracks_per_frame(para_sample) << \",\"\n            << model::mean_false_observations_per_frame(para_sample) << \",\"\n            << model::generate_observation_probability(para_sample) << \",\"\n            << model::frame_to_frame_survival_probability(para_sample)\n            << std::endl\n        ;\n    }\n}\n\nbool mh_only(partition_ptr_t &partition_ptr, model::parameters& para_sample, const general_paras &opts) {\n    int half_time = opts.total/2;\n    mh_moves::move_type last_move;\n    select_move_from selector;\n    std::map<mh_moves::move_type, size_t> move_hist;\n    std::map<mh_moves::move_type, size_t>::iterator it;\n    selector << mh_moves::BIRTH << mh_moves::DEATH << mh_moves::UPDATE\n        << mh_moves::MERGE << mh_moves::SPLIT << mh_moves::EXTEND << mh_moves::REDUCE;\n    diag(\"parameters: %s\", parameters_to_string(para_sample).c_str());\n\n    for (int i = 0; i < half_time; ++i) {\n        last_move = simple_metropolis_hastings(partition_ptr, para_sample, selector);\n        ++move_hist[last_move];\n    }\n    for (it = move_hist.begin(); it not_eq move_hist.end(); ++it) {\n        diag(\"%8s => %6.2f%%\", mh_moves::move_name(it->first).c_str(), 100.f*(it->second)/half_time);\n    }\n    return true;\n}\n\nbool simple_gibbs(partition_ptr_t partition_ptr, model::parameters& para_sample, const general_paras &opts) {\n    int half_time = opts.total/2;\n    mh_moves::move_type last_move;\n    select_move_from selector;\n    std::map<mh_moves::move_type, size_t> move_hist;\n    std::map<mh_moves::move_type, size_t>::iterator it;\n    //selector << mh_moves::BIRTH << mh_moves::DEATH << mh_moves::UPDATE;\n    selector << mh_moves::BIRTH << mh_moves::DEATH << mh_moves::UPDATE\n        << mh_moves::MERGE << mh_moves::SPLIT << mh_moves::EXTEND << mh_moves::REDUCE;\n    diag(\"parameters: %s\", parameters_to_string(para_sample).c_str());\n    capability_recorder_ptr cap_rec_ptr(new_cap_recorder(*partition_ptr));\n\n    for (int i = 0; i < half_time; ++i) {\n        partition_ptr->set_capability_recorder(cap_rec_ptr);\n        last_move = simple_metropolis_hastings(partition_ptr, para_sample, selector);\n        ++move_hist[last_move];\n        sample_model_parameters_given_partition(*partition_ptr, para_sample);\n\n    }\n    for (it = move_hist.begin(); it not_eq move_hist.end(); ++it) {\n        diag(\"%8s => %6.2f%%\", mh_moves::move_name(it->first).c_str(), 100.f*(it->second)/half_time);\n    }\n    move_hist.clear();\n    bool write_parameters = opts.rgp.output.size() > 0;\n    std::ofstream fh;\n    std::ostream &out = get_ostream(opts.rgp.output, fh);\n    int generic_ctr = 0;\n    for (int i = 0; i < half_time; ++i) {\n        partition_ptr->set_capability_recorder(cap_rec_ptr);\n        last_move = simple_metropolis_hastings(partition_ptr, para_sample, selector);\n        sample_model_parameters_given_partition(*partition_ptr, para_sample);\n        ++move_hist[last_move];\n        if (partition_ptr->tracks().size() == 0)\n            generic_ctr++;\n        if (write_parameters) out << model::mean_new_tracks_per_frame(para_sample) << \",\"\n            << model::mean_false_observations_per_frame(para_sample) << \",\"\n            << model::generate_observation_probability(para_sample) << \",\"\n            << model::frame_to_frame_survival_probability(para_sample)\n            << std::endl\n        ;\n    }\n    for (it = move_hist.begin(); it not_eq move_hist.end(); ++it) {\n        diag(\"%8s => %6.2f%%\", mh_moves::move_name(it->first).c_str(), 100.f*(it->second)/half_time);\n    }\n    diag(\"trivial proportion %6.2f%%\", 100.0f*float(generic_ctr)/float(half_time));\n    return true;\n}\n\nint main(int argc, char** argv)\n{\n    general_paras gen_pars;\n    gen_pars.total = 200000;\n    gen_pars.seed = 0;\n    gen_pars.opts = \"gibbs\";\n    gen_pars.rgp.lambda = 2.5;\n    gen_pars.rgp.p_no = 0.2;\n    gen_pars.rgp.p_yes = 0.2;\n    gen_pars.rgp.p_tr = 0.5;\n    gen_pars.rgp.min_tracks = 1;\n    gen_pars.rgp.max_tracks = 2;\n    if (not parse_args(argc, argv, gen_pars))\n        return exit_status();\n    biggles::detail::seed_prng(gen_pars.seed);\n\n    plan_no_plan();\n\n    model::parameters para_sample;\n    generate_parameters(para_sample);\n    diag(\"paramters: %s\", parameters_to_string(para_sample).c_str());\n    partition_ptr_t partition_ptr(random_debug_partition(gen_pars.rgp));\n    diag(\"opts = %s, total = %d\", gen_pars.opts.c_str(), gen_pars.total);\n    if (gen_pars.opts == \"part\")\n        log_part_for_para_sampler(*partition_ptr, gen_pars);\n    else if (gen_pars.opts == \"part\")\n        parameter_sampler(*partition_ptr, gen_pars);\n    else if (gen_pars.opts == \"gibbs\")\n        simple_gibbs(partition_ptr, para_sample, gen_pars);\n    else if (gen_pars.opts == \"moves\") {\n        model::mean_new_tracks_per_frame(para_sample)           = 0.1f;\n        model::mean_false_observations_per_frame(para_sample)   = 0.25f;\n        model::frame_to_frame_survival_probability(para_sample) = 0.9f;\n        model::generate_observation_probability(para_sample)    = 0.9f;\n        mh_only(partition_ptr, para_sample, gen_pars);\n    }\n    else\n        std::cout << \"--opts is required\"\n            << std::endl\n            << \"Possible values: \\\"para\\\", \\\"part\\\", \\\"gibbs\\\", \\\"moves\\\"\"\n            << std::endl\n            ;\n    ok1(true);\n\n    diag(\"random seed = 0x%x\", gen_pars.seed);\n    return exit_status();\n}\n", "meta": {"hexsha": "ba5fe8248b48872e4543ec29b9090699fa44a17f", "size": 8434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/biggles_observation_rate.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": "test/biggles_observation_rate.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": "test/biggles_observation_rate.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": 38.5114155251, "max_line_length": 109, "alphanum_fraction": 0.6687218402, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17695644628998497}}
{"text": "// DEx & MetaDEx\n\n#include \"base58.h\"\n#include \"rpcserver.h\"\n#include \"init.h\"\n#include \"util.h\"\n#include \"wallet.h\"\n\n#include <stdint.h>\n#include <string.h>\n\n#include <map>\n#include <set>\n\n#include <fstream>\n#include <algorithm>\n\n#include <vector>\n\n#include <utility>\n#include <string>\n\n#include <boost/assign/list_of.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/find.hpp>\n#include <boost/algorithm/string/join.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include \"json/json_spirit_utils.h\"\n#include \"json/json_spirit_value.h\"\n\n#include \"leveldb/db.h\"\n#include \"leveldb/write_batch.h\"\n\n#include <openssl/sha.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing boost::multiprecision::int128_t;\nusing boost::multiprecision::cpp_int;\nusing boost::multiprecision::cpp_dec_float;\nusing boost::multiprecision::cpp_dec_float_100;\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace json_spirit;\nusing namespace leveldb;\n\n#include \"mastercore.h\"\n\nusing namespace mastercore;\n\n#include \"mastercore_convert.h\"\n#include \"mastercore_dex.h\"\n#include \"mastercore_tx.h\"\n\nextern int msc_debug_metadex1, msc_debug_metadex2, msc_debug_metadex3;\n\nmd_PropertiesMap mastercore::metadex;\n\nmd_PricesMap* mastercore::get_Prices(unsigned int prop)\n{\nmd_PropertiesMap::iterator it = metadex.find(prop);\n\n  if (it != metadex.end()) return &(it->second);\n\n  return (md_PricesMap *) NULL;\n}\n\nmd_Set* mastercore::get_Indexes(md_PricesMap *p, XDOUBLE price)\n{\nmd_PricesMap::iterator it = p->find(price);\n\n  if (it != p->end()) return &(it->second);\n\n  return (md_Set *) NULL;\n}\n\nenum MatchReturnType\n{\n  NOTHING             = 0,\n  TRADED              = 1,\n  TRADED_MOREINSELLER,\n  TRADED_MOREINBUYER,\n  ADDED,\n  CANCELLED,\n};\n\nconst string getTradeReturnType(MatchReturnType ret)\n{\n  switch (ret)\n  {\n    case NOTHING: return string(\"NOTHING\");\n    case TRADED: return string(\"TRADED\");\n    case TRADED_MOREINSELLER: return string(\"TRADED_MOREINSELLER\");\n    case TRADED_MOREINBUYER: return string(\"TRADED_MOREINBUYER\");\n    case ADDED: return string(\"ADDED\");\n    case CANCELLED: return string(\"CANCELLED\");\n    default: return string(\"* unknown *\");\n  }\n}\n\nbool operator==(XDOUBLE first, XDOUBLE second)\n{\n  return (first.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed) == second.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed));\n}\n\nbool operator!=(XDOUBLE first, XDOUBLE second)\n{\n  return !(first == second);\n}\n\nbool operator<=(XDOUBLE first, XDOUBLE second)\n{\n  return ((first.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed) < second.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed)) || (first == second));\n}\n\nbool operator>=(XDOUBLE first, XDOUBLE second)\n{\n  return ((first.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed) > second.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed)) || (first == second));\n}\n\nstatic void PriceCheck(const string &label, XDOUBLE left, XDOUBLE right)\n{\nconst bool bOK = (left == right);\n\n  file_log(\"PRICE CHECK %s: buyer = %s , inserted = %s : %s\\n\", label,\n   left.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed),\n   right.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed), bOK ? \"good\":\"PROBLEM!\");\n}\n\n// find the best match on the market\n// NOTE: sometimes I refer to the older order as seller & the newer order as buyer, in this trade\n// INPUT: property, desprop, desprice = of the new order being inserted; the new object being processed\n// RETURN: \nstatic MatchReturnType x_Trade(CMPMetaDEx *newo)\n{\nconst CMPMetaDEx *p_older = NULL;\nmd_PricesMap *prices = NULL;\nconst unsigned int prop = newo->getProperty();\nconst unsigned int desprop = newo->getDesProperty();\nMatchReturnType NewReturn = NOTHING;\nbool bBuyerSatisfied = false;\nconst XDOUBLE buyersprice = newo->effectivePrice();\nconst XDOUBLE desprice = (1/buyersprice); // inverse, to be matched against that of the existing older order\n\n  if (msc_debug_metadex1)\n  {\n    file_log(\"%s(%s: prop=%u, desprop=%u, desprice= %s);newo: %s\\n\",\n     __FUNCTION__, newo->getAddr(), prop, desprop, desprice.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed), newo->ToString());\n  }\n\n  prices = get_Prices(desprop);\n\n  // nothing for the desired property exists in the market, sorry!\n  if (!prices)\n  {\n    file_log(\"%s()=%u:%s NOT FOUND ON THE MARKET\\n\", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn));\n    return NewReturn;\n  }\n\n  // within the desired property map (given one property) iterate over the items looking at prices\n  for (md_PricesMap::iterator my_it = prices->begin(); my_it != prices->end(); ++my_it)\n  { // check all prices\n  XDOUBLE sellers_price = (my_it->first);\n\n    if (msc_debug_metadex2) file_log(\"comparing prices: desprice %s needs to be GREATER THAN OR EQUAL TO %s\\n\",\n     desprice.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed), sellers_price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed));\n\n    // Is the desired price check satisfied? The buyer's inverse price must be larger than that of the seller.\n    if (desprice < sellers_price) continue;\n\n    md_Set *indexes = &(my_it->second);\n\n    // at good (single) price level and property iterate over offers looking at all parameters to find the match\n    md_Set::iterator iitt;\n    for (iitt = indexes->begin(); iitt != indexes->end();)\n    { // specific price, check all properties\n      p_older = &(*iitt);\n\n      if (msc_debug_metadex1) file_log(\"Looking at existing: %s (its prop= %u, its des prop= %u) = %s\\n\",\n       sellers_price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed), p_older->getProperty(), p_older->getDesProperty(), p_older->ToString());\n\n      // is the desired property correct?\n        if (p_older->getDesProperty() != prop)\n        {\n          ++iitt;\n          continue;\n        }\n\n      if (msc_debug_metadex1) file_log(\"MATCH FOUND, Trade: %s = %s\\n\", sellers_price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed), p_older->ToString());\n\n        // All Matched ! Trade now.\n        // p_older is the old order pointer\n        // newo is the new order pointer\n        // the price in the older order is used\n        const int64_t seller_amountForSale = p_older->getAmountForSale();\n        const int64_t seller_amountWanted = p_older->getAmountDesired();\n        const int64_t buyer_amountOffered = newo->getAmountForSale();\n\n        if (msc_debug_metadex1) file_log(\"$$ trading using price: %s; seller: forsale= %ld, wanted= %ld, buyer amount offered= %ld\\n\",\n         sellers_price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed), seller_amountForSale, seller_amountWanted, buyer_amountOffered);\n\n        if (msc_debug_metadex1) file_log(\"$$ old: %s\\n\", p_older->ToString());\n        if (msc_debug_metadex1) file_log(\"$$ new: %s\\n\", newo->ToString());\n\n        int64_t seller_amountGot = seller_amountWanted;\n\n        if (buyer_amountOffered < seller_amountWanted)\n        {\n          seller_amountGot = buyer_amountOffered;\n        }\n\n        const int64_t buyer_amountStillForSale = buyer_amountOffered - seller_amountGot;\n\n///////////////////////////\n        XDOUBLE x_buyer_got = (XDOUBLE) seller_amountGot / sellers_price;\n\n        x_buyer_got += (XDOUBLE) 0.5; // ROUND UP\n\n        std::string str_buyer_got = x_buyer_got.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed);\n        std::string str_buyer_got_int_part = str_buyer_got.substr(0, str_buyer_got.find_first_of(\".\"));\n        const int64_t buyer_amountGot = boost::lexical_cast<int64_t>( str_buyer_got_int_part );\n\n        const int64_t seller_amountLeft = p_older->getAmountForSale() - buyer_amountGot;\n\n        if (msc_debug_metadex1) file_log(\"$$ buyer_got= %ld, seller_got= %ld, seller_left_for_sale= %ld, buyer_still_for_sale= %ld\\n\",\n         buyer_amountGot, seller_amountGot, seller_amountLeft, buyer_amountStillForSale);\n\n        XDOUBLE seller_amount_stilldesired = (XDOUBLE) seller_amountLeft * sellers_price;\n\n        seller_amount_stilldesired += (XDOUBLE) 0.5; // ROUND UP\n\n        std::string str_amount_stilldesired = seller_amount_stilldesired.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed);\n        std::string str_stilldesired_int_part = str_amount_stilldesired.substr(0, str_amount_stilldesired.find_first_of(\".\"));\n\n///////////////////////////\n        CMPMetaDEx seller_replacement = *p_older;\n\n        seller_replacement.setAmountForSale(seller_amountLeft, \"seller_replacement\");\n        seller_replacement.setAmountDesired(boost::lexical_cast<int64_t>( str_stilldesired_int_part ), \"seller_replacement\");\n\n        // transfer the payment property from buyer to seller\n        // TODO: do something when failing here............\n        // FIXME\n        // ...\n        if (update_tally_map(newo->getAddr(), newo->getProperty(), - seller_amountGot, BALANCE))\n        {\n          if (update_tally_map(p_older->getAddr(), p_older->getDesProperty(), seller_amountGot, BALANCE))\n          {\n          }\n        }\n\n        // transfer the market (the one being sold) property from seller to buyer\n        // TODO: do something when failing here............\n        // FIXME\n        // ...\n        if (update_tally_map(p_older->getAddr(), p_older->getProperty(), - buyer_amountGot, METADEX_RESERVE))\n        {\n          update_tally_map(newo->getAddr(), newo->getDesProperty(), buyer_amountGot, BALANCE);\n        }\n\n        NewReturn = TRADED;\n\n        XDOUBLE will_pay = (XDOUBLE) buyer_amountStillForSale * newo->effectivePrice();\n\n        will_pay += (XDOUBLE) 0.5;  // ROUND UP\n\n        std::string str_will_pay = will_pay.str(INTERNAL_PRECISION_LEN, std::ios_base::fixed);\n        std::string str_will_pay_int_part = str_will_pay.substr(0, str_will_pay.find_first_of(\".\"));\n\n        newo->setAmountForSale(buyer_amountStillForSale, \"buyer\");\n        newo->setAmountDesired(boost::lexical_cast<int64_t>( str_will_pay_int_part ), \"buyer\");\n\n        if (0 < buyer_amountStillForSale)\n        {\n          NewReturn = TRADED_MOREINBUYER;\n\n          PriceCheck(getTradeReturnType(NewReturn), buyersprice, newo->effectivePrice());\n        }\n        else\n        {\n          bBuyerSatisfied = true;\n        }\n\n        if (0 < seller_amountLeft)  // done with all loops, update the seller, buyer is fully satisfied\n        {\n          NewReturn = TRADED_MOREINSELLER;\n          bBuyerSatisfied = true;\n\n          PriceCheck(getTradeReturnType(NewReturn), p_older->effectivePrice(), seller_replacement.effectivePrice());\n        }\n\n        if (msc_debug_metadex1) file_log(\"==== TRADED !!! %u=%s\\n\", NewReturn, getTradeReturnType(NewReturn));\n\n        t_tradelistdb->recordTrade(p_older->getHash(), newo->getHash(),\n         p_older->getAddr(), newo->getAddr(), p_older->getDesProperty(), newo->getDesProperty(), seller_amountGot, buyer_amountGot, newo->getBlock());\n\n      if (msc_debug_metadex1) file_log(\"++ erased old: %s\\n\", iitt->ToString());\n      // erase the old seller element\n      indexes->erase(iitt++);\n\n      if (bBuyerSatisfied)\n      {\n        // insert the updated one in place of the old\n        if (0 < seller_replacement.getAmountForSale())\n        {\n          file_log(\"++ inserting seller_replacement: %s\\n\", seller_replacement.ToString());\n          indexes->insert(seller_replacement);\n        }\n        break;\n      }\n    } // specific price, check all properties\n\n    if (bBuyerSatisfied) break;\n  } // check all prices\n  \n  file_log(\"%s()=%u:%s\\n\", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn));\n\n  return NewReturn;\n}\n\nvoid mastercore::MetaDEx_debug_print(bool bShowPriceLevel, bool bDisplay)\n{\n  file_log(\"<<<\\n\");\n  for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it)\n  {\n    unsigned int prop = my_it->first;\n\n    file_log(\" ## property: %u\\n\", prop);\n    md_PricesMap & prices = my_it->second;\n\n    for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it)\n    {\n      XDOUBLE price = (it->first);\n      md_Set & indexes = (it->second);\n\n      if (bShowPriceLevel) file_log(\"  # Price Level: %s\\n\", price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed));\n\n      for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it)\n      {\n      CMPMetaDEx obj = *it;\n\n        if (bDisplay) printf(\"%s= %s\\n\", price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed).c_str() , obj.ToString().c_str());\n        else file_log(\"%s= %s\\n\", price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed) , obj.ToString());\n\n        // extra checks: price or either of the amounts is 0\n//        assert((XDOUBLE)0 != obj.effectivePrice());\n//        assert(obj.getAmountForSale());\n//        assert(obj.getAmountDesired());\n      }\n    }\n  }\n  file_log(\">>>\\n\");\n}\n\nvoid CMPMetaDEx::Set(const string &sa, int b, unsigned int c, uint64_t nValue, unsigned int cd, uint64_t ad, const uint256 &tx, unsigned int i, unsigned char suba)\n{\n  addr = sa;\n  block = b;\n  txid = tx;\n  property = c;\n  amount_forsale = nValue;\n  desired_property = cd;\n  amount_desired = ad;\n  idx = i;\n  subaction = suba;\n}\n\nCMPMetaDEx::CMPMetaDEx(const string &addr, int b, unsigned int c, uint64_t nValue, unsigned int cd, uint64_t ad, const uint256 &tx, unsigned int i, unsigned char suba, uint64_t lfors)\n{\n  still_left_forsale = lfors;\n  Set(addr, b,c,nValue,cd,ad,tx,i,suba);\n}\n\nstd::string CMPMetaDEx::ToString() const\n{\n  return strprintf(\"%s:%34s in %d/%03u, txid: %s , trade #%u %s for #%u %s\",\n   effectivePrice().str(DISPLAY_PRECISION_LEN, std::ios_base::fixed),\n   addr.c_str(), block, idx, txid.ToString().substr(0,10).c_str(),\n   property, FormatMP(property, amount_forsale), desired_property, FormatMP(desired_property, amount_desired));\n}\n\n// check to see if such a sell offer exists\nbool mastercore::DEx_offerExists(const string &seller_addr, unsigned int prop)\n{\n//  if (msc_debug_dex) file_log(\"%s()\\n\", __FUNCTION__);\nconst string combo = STR_SELLOFFER_ADDR_PROP_COMBO(seller_addr);\nOfferMap::iterator my_it = my_offers.find(combo);\n\n  return !(my_it == my_offers.end());\n}\n\n// getOffer may replace DEx_offerExists() in the near future\n// TODO: locks are needed around map's insert & erase\nCMPOffer *mastercore::DEx_getOffer(const string &seller_addr, unsigned int prop)\n{\n  if (msc_debug_dex) file_log(\"%s(%s, %u)\\n\", __FUNCTION__, seller_addr, prop);\nconst string combo = STR_SELLOFFER_ADDR_PROP_COMBO(seller_addr);\nOfferMap::iterator my_it = my_offers.find(combo);\n\n  if (my_it != my_offers.end()) return &(my_it->second);\n\n  return (CMPOffer *) NULL;\n}\n\n// TODO: locks are needed around map's insert & erase\nCMPAccept *mastercore::DEx_getAccept(const string &seller_addr, unsigned int prop, const string &buyer_addr)\n{\n  if (msc_debug_dex) file_log(\"%s(%s, %u, %s)\\n\", __FUNCTION__, seller_addr, prop, buyer_addr);\nconst string combo = STR_ACCEPT_ADDR_PROP_ADDR_COMBO(seller_addr, buyer_addr);\nAcceptMap::iterator my_it = my_accepts.find(combo);\n\n  if (my_it != my_accepts.end()) return &(my_it->second);\n\n  return (CMPAccept *) NULL;\n}\n\n// returns 0 if everything is OK\nint mastercore::DEx_offerCreate(string seller_addr, unsigned int prop, uint64_t nValue, int block, uint64_t amount_des, uint64_t fee, unsigned char btl, const uint256 &txid, uint64_t *nAmended)\n{\nint rc = DEX_ERROR_SELLOFFER;\n\n  // sanity check our params are OK\n  if ((!btl) || (!amount_des)) return (DEX_ERROR_SELLOFFER -101); // time limit or amount desired empty\n\n  if (DEx_getOffer(seller_addr, prop)) return (DEX_ERROR_SELLOFFER -10);  // offer already exists\n\n  const string combo = STR_SELLOFFER_ADDR_PROP_COMBO(seller_addr);\n\n  if (msc_debug_dex)\n   file_log(\"%s(%s|%s), nValue=%lu)\\n\", __FUNCTION__, seller_addr, combo, nValue);\n\n  const uint64_t balanceReallyAvailable = getMPbalance(seller_addr, prop, BALANCE);\n\n  // if offering more than available -- put everything up on sale\n  if (nValue > balanceReallyAvailable)\n  {\n  double BTC;\n\n    // AND we must also re-adjust the BTC desired in this case...\n    BTC = amount_des * balanceReallyAvailable;\n    BTC /= (double)nValue;\n    amount_des = rounduint64(BTC);\n\n    nValue = balanceReallyAvailable;\n\n    if (nAmended) *nAmended = nValue;\n  }\n\n  if (update_tally_map(seller_addr, prop, - nValue, BALANCE)) // subtract from what's available\n  {\n    update_tally_map(seller_addr, prop, nValue, SELLOFFER_RESERVE); // put in reserve\n\n    my_offers.insert(std::make_pair(combo, CMPOffer(block, nValue, prop, amount_des, fee, btl, txid)));\n\n    rc = 0;\n  }\n\n  return rc;\n}\n\n// returns 0 if everything is OK\nint mastercore::DEx_offerDestroy(const string &seller_addr, unsigned int prop)\n{\nconst uint64_t amount = getMPbalance(seller_addr, prop, SELLOFFER_RESERVE);\n\n  if (!DEx_offerExists(seller_addr, prop)) return (DEX_ERROR_SELLOFFER -11); // offer does not exist\n\n  const string combo = STR_SELLOFFER_ADDR_PROP_COMBO(seller_addr);\n\n  OfferMap::iterator my_it;\n\n  my_it = my_offers.find(combo);\n\n  if (amount)\n  {\n    update_tally_map(seller_addr, prop, amount, BALANCE);   // give back to the seller from SellOffer-Reserve\n    update_tally_map(seller_addr, prop, - amount, SELLOFFER_RESERVE);\n  }\n\n  // delete the offer\n  my_offers.erase(my_it);\n\n  if (msc_debug_dex)\n   file_log(\"%s(%s|%s)\\n\", __FUNCTION__, seller_addr, combo);\n\n  return 0;\n}\n\n// returns 0 if everything is OK\nint mastercore::DEx_offerUpdate(const string &seller_addr, unsigned int prop, uint64_t nValue, int block, uint64_t desired, uint64_t fee, unsigned char btl, const uint256 &txid, uint64_t *nAmended)\n{\nint rc = DEX_ERROR_SELLOFFER;\n\n  file_log(\"%s(%s, %d)\\n\", __FUNCTION__, seller_addr, prop);\n\n  if (!DEx_offerExists(seller_addr, prop)) return (DEX_ERROR_SELLOFFER -12); // offer does not exist\n\n  rc = DEx_offerDestroy(seller_addr, prop);\n\n  if (!rc)\n  {\n    rc = DEx_offerCreate(seller_addr, prop, nValue, block, desired, fee, btl, txid, nAmended);\n  }\n\n  return rc;\n}\n\n// returns 0 if everything is OK\nint mastercore::DEx_acceptCreate(const string &buyer, const string &seller, int prop, uint64_t nValue, int block, uint64_t fee_paid, uint64_t *nAmended)\n{\nint rc = DEX_ERROR_ACCEPT - 10;\nOfferMap::iterator my_it;\nconst string selloffer_combo = STR_SELLOFFER_ADDR_PROP_COMBO(seller);\nconst string accept_combo = STR_ACCEPT_ADDR_PROP_ADDR_COMBO(seller, buyer);\nuint64_t nActualAmount = getMPbalance(seller, prop, SELLOFFER_RESERVE);\n\n  my_it = my_offers.find(selloffer_combo);\n\n  if (my_it == my_offers.end()) return DEX_ERROR_ACCEPT -15;\n\n  CMPOffer &offer = my_it->second;\n\n  if (msc_debug_dex) file_log(\"%s(offer: %s)\\n\", __FUNCTION__, offer.getHash().GetHex());\n\n  // here we ensure the correct BTC fee was paid in this acceptance message, per spec\n  if (fee_paid < offer.getMinFee())\n  {\n    file_log(\"ERROR: fee too small -- the ACCEPT is rejected! (%lu is smaller than %lu)\\n\", fee_paid, offer.getMinFee());\n    return DEX_ERROR_ACCEPT -105;\n  }\n\n  file_log(\"%s(%s) OFFER FOUND\\n\", __FUNCTION__, selloffer_combo);\n\n  // the older accept is the valid one: do not accept any new ones!\n  if (DEx_getAccept(seller, prop, buyer))\n  {\n    file_log(\"%s() ERROR: an accept from this same seller for this same offer is already open !!!!!\\n\", __FUNCTION__);\n    return DEX_ERROR_ACCEPT -205;\n  }\n\n  if (nActualAmount > nValue)\n  {\n    nActualAmount = nValue;\n\n    if (nAmended) *nAmended = nActualAmount;\n  }\n\n  // TODO: think if we want to save nValue -- as the amount coming off the wire into the object or not\n  if (update_tally_map(seller, prop, - nActualAmount, SELLOFFER_RESERVE))\n  {\n    if (update_tally_map(seller, prop, nActualAmount, ACCEPT_RESERVE))\n    {\n      // insert into the map !\n      my_accepts.insert(std::make_pair(accept_combo, CMPAccept(nActualAmount, block,\n       offer.getBlockTimeLimit(), offer.getProperty(), offer.getOfferAmountOriginal(), offer.getBTCDesiredOriginal(), offer.getHash() )));\n\n      rc = 0;\n    }\n  }\n\n  return rc;\n}\n\n// this function is called by handler_block() for each Accept that has expired\n// this function is also called when the purchase has been completed (the buyer bought everything he was allocated)\n//\n// returns 0 if everything is OK\nint mastercore::DEx_acceptDestroy(const string &buyer, const string &seller, int prop, bool bForceErase)\n{\nint rc = DEX_ERROR_ACCEPT - 20;\nCMPOffer *p_offer = DEx_getOffer(seller, prop);\nCMPAccept *p_accept = DEx_getAccept(seller, prop, buyer);\nbool bReturnToMoney; // return to BALANCE of the seller, otherwise return to SELLOFFER_RESERVE\nconst string accept_combo = STR_ACCEPT_ADDR_PROP_ADDR_COMBO(seller, buyer);\n\n  if (!p_accept) return rc; // sanity check\n\n  const uint64_t nActualAmount = p_accept->getAcceptAmountRemaining();\n\n  // if the offer is gone ACCEPT_RESERVE should go back to BALANCE\n  if (!p_offer)\n  {\n    bReturnToMoney = true;\n  }\n  else\n  {\n    file_log(\"%s() HASHES: offer=%s, accept=%s\\n\", __FUNCTION__, p_offer->getHash().GetHex(), p_accept->getHash().GetHex());\n\n    // offer exists, determine whether it's the original offer or some random new one\n    if (p_offer->getHash() == p_accept->getHash())\n    {\n      // same offer, return to SELLOFFER_RESERVE\n      bReturnToMoney = false;\n    }\n    else\n    {\n      // old offer is gone !\n      bReturnToMoney = true;\n    }\n  }\n\n  if (bReturnToMoney)\n  {\n    if (update_tally_map(seller, prop, - nActualAmount, ACCEPT_RESERVE))\n    {\n      update_tally_map(seller, prop, nActualAmount, BALANCE);\n      rc = 0;\n    }\n  }\n  else\n  {\n    // return to SELLOFFER_RESERVE\n    if (update_tally_map(seller, prop, - nActualAmount, ACCEPT_RESERVE))\n    {\n      update_tally_map(seller, prop, nActualAmount, SELLOFFER_RESERVE);\n      rc = 0;\n    }\n  }\n\n  // can only erase when is NOT called from an iterator loop\n  if (bForceErase)\n  {\n  const AcceptMap::iterator my_it = my_accepts.find(accept_combo);\n\n    if (my_accepts.end() !=my_it) my_accepts.erase(my_it);\n  }\n\n  return rc;\n}\n\n// incoming BTC payment for the offer\n// TODO: verify proper partial payment handling\nint mastercore::DEx_payment(uint256 txid, unsigned int vout, string seller, string buyer, uint64_t BTC_paid, int blockNow, uint64_t *nAmended)\n{\n//  if (msc_debug_dex) file_log(\"%s()\\n\", __FUNCTION__);\nint rc = DEX_ERROR_PAYMENT;\nCMPAccept *p_accept;\nint prop;\n\nprop = OMNI_PROPERTY_MSC; //test for MSC accept first\np_accept = DEx_getAccept(seller, prop, buyer);\n\n  if (!p_accept) \n  {\n    prop = OMNI_PROPERTY_TMSC; //test for TMSC accept second\n    p_accept = DEx_getAccept(seller, prop, buyer); \n  }\n\n  if (msc_debug_dex) file_log(\"%s(%s, %s)\\n\", __FUNCTION__, seller, buyer);\n\n  if (!p_accept) return (DEX_ERROR_PAYMENT -1);  // there must be an active Accept for this payment\n\n  const double BTC_desired_original = p_accept->getBTCDesiredOriginal();\n  const double offer_amount_original = p_accept->getOfferAmountOriginal();\n\n  if (0==(double)BTC_desired_original) return (DEX_ERROR_PAYMENT -2);  // divide by 0 protection\n\n  double perc_X = (double)BTC_paid/BTC_desired_original;\n  double Purchased = offer_amount_original * perc_X;\n\n  uint64_t units_purchased = rounduint64(Purchased);\n\n  const uint64_t nActualAmount = p_accept->getAcceptAmountRemaining();  // actual amount desired, in the Accept\n\n  if (msc_debug_dex)\n   file_log(\"BTC_desired= %30.20lf , offer_amount=%30.20lf , perc_X= %30.20lf , Purchased= %30.20lf , units_purchased= %lu\\n\",\n   BTC_desired_original, offer_amount_original, perc_X, Purchased, units_purchased);\n\n  // if units_purchased is greater than what's in the Accept, the buyer gets only what's in the Accept\n  if (nActualAmount < units_purchased)\n  {\n    units_purchased = nActualAmount;\n\n    if (nAmended) *nAmended = units_purchased;\n  }\n\n  if (update_tally_map(seller, prop, - units_purchased, ACCEPT_RESERVE))\n  {\n      update_tally_map(buyer, prop, units_purchased, BALANCE);\n      rc = 0;\n      bool bValid = true;\n      p_txlistdb->recordPaymentTX(txid, bValid, blockNow, vout, prop, units_purchased, buyer, seller);\n\n      file_log(\"#######################################################\\n\");\n  }\n\n  // reduce the amount of units still desired by the buyer and if 0 must destroy the Accept\n  if (p_accept->reduceAcceptAmountRemaining_andIsZero(units_purchased))\n  {\n  const uint64_t selloffer_reserve = getMPbalance(seller, prop, SELLOFFER_RESERVE);\n  const uint64_t accept_reserve = getMPbalance(seller, prop, ACCEPT_RESERVE);\n\n    DEx_acceptDestroy(buyer, seller, prop, true);\n\n    // delete the Offer object if there is nothing in its Reserves -- everything got puchased and paid for\n    if ((0 == selloffer_reserve) && (0 == accept_reserve))\n    {\n      DEx_offerDestroy(seller, prop);\n    }\n  }\n\n  return rc;\n}\n\nunsigned int eraseExpiredAccepts(int blockNow)\n{\nunsigned int how_many_erased = 0;\nAcceptMap::iterator my_it = my_accepts.begin();\n\n  while (my_accepts.end() != my_it)\n  {\n    // my_it->first = key\n    // my_it->second = value\n\n    CMPAccept &mpaccept = my_it->second;\n\n    if ((blockNow - mpaccept.block) >= (int) mpaccept.getBlockTimeLimit())\n    {\n      file_log(\"%s() FOUND EXPIRED ACCEPT, erasing: blockNow=%d, offer block=%d, blocktimelimit= %d\\n\",\n       __FUNCTION__, blockNow, mpaccept.block, mpaccept.getBlockTimeLimit());\n\n      // extract the seller, buyer & property from the Key\n      std::vector<std::string> vstr;\n      boost::split(vstr, my_it->first, boost::is_any_of(\"-+\"), token_compress_on);\n      string seller = vstr[0];\n      int property = atoi(vstr[1]);\n      string buyer = vstr[2];\n\n      DEx_acceptDestroy(buyer, seller, property);\n\n      my_accepts.erase(my_it++);\n\n      ++how_many_erased;\n    }\n    else my_it++;\n\n  }\n\n  return how_many_erased;\n}\n\n// pretty much directly linked to the ADD TX21 command off the wire\nint mastercore::MetaDEx_ADD(const string &sender_addr, unsigned int prop, uint64_t amount, int block, unsigned int property_desired, uint64_t amount_desired, const uint256 &txid, unsigned int idx)\n{\nint rc = METADEX_ERROR -1;\n\n  // MetaDEx implementation phase 1 check\n  if ((prop != OMNI_PROPERTY_MSC) && (property_desired != OMNI_PROPERTY_MSC) &&\n   (prop != OMNI_PROPERTY_TMSC) && (property_desired != OMNI_PROPERTY_TMSC))\n  {\n    return METADEX_ERROR -800;\n  }\n\n    // store the data into the temp MetaDEx object here\n    CMPMetaDEx new_mdex(sender_addr, block, prop, amount, property_desired, amount_desired, txid, idx, CMPTransaction::ADD);\n    XDOUBLE neworder_buyersprice = new_mdex.effectivePrice();\n\n    if (msc_debug_metadex1) file_log(\"%s(); buyer obj: %s\\n\", __FUNCTION__, new_mdex.ToString());\n\n    // given the property & the price find the proper place for insertion\n\n    // TODO: reconsider for boost::multiprecision\n    // FIXME\n    if (0 >= neworder_buyersprice)\n    {\n      // do not work with 0 prices\n      return METADEX_ERROR -66;\n    }\n\n    if (msc_debug_metadex3) MetaDEx_debug_print();\n\n    // TRADE, check matches, remainder of the order will be put into the order book\n    x_Trade(&new_mdex);\n\n    if (msc_debug_metadex3) MetaDEx_debug_print();\n\n#if 0\n    // if anything is left in the new order, INSERT\n    if ((0 < new_mdex.getAmountForSale()) && (!disable_Combo))\n    {\n      x_AddOrCancel(&new_mdex); // straight match to ADD\n    }\n#endif\n\n    if (msc_debug_metadex3) MetaDEx_debug_print();\n\n    // plain insert\n    if (0 < new_mdex.getAmountForSale())\n    { // not added nor subtracted, insert as new or post-traded amounts\n    md_PricesMap temp_prices, *p_prices = get_Prices(prop);\n    md_Set temp_indexes, *p_indexes = NULL;\n    std::pair<md_Set::iterator,bool> ret;\n\n      if (p_prices)\n      {\n        p_indexes = get_Indexes(p_prices, neworder_buyersprice);\n      }\n\n      if (!p_indexes) p_indexes = &temp_indexes;\n\n      ret = p_indexes->insert(new_mdex);\n\n      if (false == ret.second)\n      {\n        file_log(\"%s() ERROR: ALREADY EXISTS, line %d, file: %s\\n\", __FUNCTION__, __LINE__, __FILE__);\n      }\n      else\n      {\n        // TODO: think about failure scenarios\n        // FIXME\n        if (update_tally_map(sender_addr, prop, - new_mdex.getAmountForSale(), BALANCE)) // subtract from what's available\n        {\n          // TODO: think about failure scenarios\n          // FIXME\n          update_tally_map(sender_addr, prop, new_mdex.getAmountForSale(), METADEX_RESERVE); // put in reserve\n        }\n\n        // price check\n        PriceCheck(\"Insert\", neworder_buyersprice, new_mdex.effectivePrice());\n\n        if (msc_debug_metadex1) file_log(\"==== INSERTED: %s= %s\\n\", neworder_buyersprice.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed), new_mdex.ToString());\n      }\n\n      if (!p_prices) p_prices = &temp_prices;\n\n      (*p_prices)[neworder_buyersprice] = *p_indexes;\n\n      metadex[prop] = *p_prices;\n    } // Must Insert\n\n  rc = 0;\n\n  if (msc_debug_metadex3) MetaDEx_debug_print();\n\n  return rc;\n}\n\nint mastercore::MetaDEx_CANCEL_AT_PRICE(const uint256 txid, unsigned int block, const string &sender_addr, unsigned int prop, uint64_t amount, unsigned int property_desired, uint64_t amount_desired)\n{\nint rc = METADEX_ERROR -20;\nCMPMetaDEx mdex(sender_addr, 0, prop, amount, property_desired, amount_desired, 0, 0, CMPTransaction::CANCEL_AT_PRICE);\nmd_PricesMap *prices = get_Prices(prop);\nconst CMPMetaDEx *p_mdex = NULL;\n\n  if (msc_debug_metadex1) file_log(\"%s():%s\\n\", __FUNCTION__, mdex.ToString());\n\n  if (msc_debug_metadex2) MetaDEx_debug_print();\n\n  if (!prices)\n  {\n    file_log(\"%s() NOTHING FOUND for %s\\n\", __FUNCTION__, mdex.ToString());\n    return rc -1;\n  }\n\n  // within the desired property map (given one property) iterate over the items\n  for (md_PricesMap::iterator my_it = prices->begin(); my_it != prices->end(); ++my_it)\n  {\n  XDOUBLE sellers_price = (my_it->first);\n\n    if (mdex.effectivePrice() != sellers_price) continue;\n\n    md_Set *indexes = &(my_it->second);\n\n    for (md_Set::iterator iitt = indexes->begin(); iitt != indexes->end();)\n    { // for iitt\n      p_mdex = &(*iitt);\n\n      if (msc_debug_metadex3) file_log(\"%s(): %s\\n\", __FUNCTION__, p_mdex->ToString());\n\n      if ((p_mdex->getDesProperty() != property_desired) || (p_mdex->getAddr() != sender_addr))\n      {\n        ++iitt;\n        continue;\n      }\n\n      rc = 0;\n      file_log(\"%s(): REMOVING %s\\n\", __FUNCTION__, p_mdex->ToString());\n\n      // move from reserve to main\n      update_tally_map(p_mdex->getAddr(), p_mdex->getProperty(), - p_mdex->getAmountForSale(), METADEX_RESERVE);\n      update_tally_map(p_mdex->getAddr(), p_mdex->getProperty(), p_mdex->getAmountForSale(), BALANCE);\n\n      // record the cancellation\n      bool bValid = true;\n      p_txlistdb->recordMetaDExCancelTX(txid, p_mdex->getHash(), bValid, block, p_mdex->getProperty(), p_mdex->getAmountForSale());\n\n      indexes->erase(iitt++);\n    }\n  }\n\n  if (msc_debug_metadex2) MetaDEx_debug_print();\n\n  return rc;\n}\n\nint mastercore::MetaDEx_CANCEL_ALL_FOR_PAIR(const uint256 txid, unsigned int block, const string &sender_addr, unsigned int prop, unsigned int property_desired)\n{\nint rc = METADEX_ERROR -30;\nmd_PricesMap *prices = get_Prices(prop);\nconst CMPMetaDEx *p_mdex = NULL;\n\n  file_log(\"%s(%d,%d)\\n\", __FUNCTION__, prop, property_desired);\n\n  if (msc_debug_metadex3) MetaDEx_debug_print();\n\n  if (!prices)\n  {\n    file_log(\"%s() NOTHING FOUND\\n\", __FUNCTION__);\n    return rc -1;\n  }\n\n  // within the desired property map (given one property) iterate over the items\n  for (md_PricesMap::iterator my_it = prices->begin(); my_it != prices->end(); ++my_it)\n  {\n  md_Set *indexes = &(my_it->second);\n\n    for (md_Set::iterator iitt = indexes->begin(); iitt != indexes->end();)\n    { // for iitt\n      p_mdex = &(*iitt);\n\n      if (msc_debug_metadex3) file_log(\"%s(): %s\\n\", __FUNCTION__, p_mdex->ToString());\n\n      if ((p_mdex->getDesProperty() != property_desired) || (p_mdex->getAddr() != sender_addr))\n      {\n        ++iitt;\n        continue;\n      }\n\n      rc = 0;\n      file_log(\"%s(): REMOVING %s\\n\", __FUNCTION__, p_mdex->ToString());\n\n      // move from reserve to main\n      update_tally_map(p_mdex->getAddr(), p_mdex->getProperty(), - p_mdex->getAmountForSale(), METADEX_RESERVE);\n      update_tally_map(p_mdex->getAddr(), p_mdex->getProperty(), p_mdex->getAmountForSale(), BALANCE);\n\n      // record the cancellation\n      bool bValid = true;\n      p_txlistdb->recordMetaDExCancelTX(txid, p_mdex->getHash(), bValid, block, p_mdex->getProperty(), p_mdex->getAmountForSale());\n\n      indexes->erase(iitt++);\n    }\n  }\n\n  if (msc_debug_metadex3) MetaDEx_debug_print();\n\n  return rc;\n}\n\n// scan the orderbook and remove everything for an address\nint mastercore::MetaDEx_CANCEL_EVERYTHING(const uint256 txid, unsigned int block, const string &sender_addr)\n{\nint rc = METADEX_ERROR -40;\n\n  file_log(\"%s()\\n\", __FUNCTION__);\n\n  if (msc_debug_metadex2) MetaDEx_debug_print();\n\n  file_log(\"<<<<<<\\n\");\n\n  for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it)\n  {\n    unsigned int prop = my_it->first;\n\n    file_log(\" ## property: %u\\n\", prop);\n    md_PricesMap & prices = my_it->second;\n\n    for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it)\n    {\n      XDOUBLE price = (it->first);\n      md_Set & indexes = (it->second);\n\n      file_log(\"  # Price Level: %s\\n\", price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed));\n\n      for (md_Set::iterator it = indexes.begin(); it != indexes.end();)\n      {\n        file_log(\"%s= %s\\n\", price.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed) , it->ToString());\n\n        if ((it->getAddr() != sender_addr))\n        {\n          ++it;\n          continue;\n        }\n\n        rc = 0;\n        file_log(\"%s(): REMOVING %s\\n\", __FUNCTION__, it->ToString());\n\n        // move from reserve to balance\n        update_tally_map(it->getAddr(), it->getProperty(), - it->getAmountForSale(), METADEX_RESERVE);\n        update_tally_map(it->getAddr(), it->getProperty(), it->getAmountForSale(), BALANCE);\n\n        // record the cancellation\n        bool bValid = true;\n        p_txlistdb->recordMetaDExCancelTX(txid, it->getHash(), bValid, block, it->getProperty(), it->getAmountForSale());\n\n        indexes.erase(it++);\n      }\n    }\n  }\n  file_log(\">>>>>>\\n\");\n\n  if (msc_debug_metadex2) MetaDEx_debug_print();\n\n  return rc;\n}\n\nbool MetaDEx_compare::operator()(const CMPMetaDEx &lhs, const CMPMetaDEx &rhs) const\n{\n  if (lhs.getBlock() == rhs.getBlock()) return lhs.getIdx() < rhs.getIdx();\n  else return lhs.getBlock() < rhs.getBlock();\n}\n\nvoid CMPMetaDEx::saveOffer(ofstream &file, SHA256_CTX *shaCtx) const\n{\n    string lineOut = (boost::format(\"%s,%d,%d,%d,%d,%d,%d,%d,%s,%d\")\n      % addr\n      % block\n      % amount_forsale\n      % property\n      % amount_desired\n      % desired_property\n      % (unsigned int) subaction\n      % idx\n      % txid.ToString()\n      % still_left_forsale\n      ).str();\n\n    // add the line to the hash\n    SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length());\n\n    // write the line\n    file << lineOut << endl;\n}\n\n", "meta": {"hexsha": "e711568a51f9328c0c47ec0db1ba2c1a460659e0", "size": 34803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mastercore_dex.cpp", "max_stars_repo_name": "cybershrapnel/mastercore", "max_stars_repo_head_hexsha": "5b7fe81c601fe7ed60a465ff944b2b89083b015a", "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/mastercore_dex.cpp", "max_issues_repo_name": "cybershrapnel/mastercore", "max_issues_repo_head_hexsha": "5b7fe81c601fe7ed60a465ff944b2b89083b015a", "max_issues_repo_licenses": ["MIT"], "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/mastercore_dex.cpp", "max_forks_repo_name": "cybershrapnel/mastercore", "max_forks_repo_head_hexsha": "5b7fe81c601fe7ed60a465ff944b2b89083b015a", "max_forks_repo_licenses": ["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.4644230769, "max_line_length": 198, "alphanum_fraction": 0.684682355, "num_tokens": 9580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1769564412632963}}
{"text": "/*\n * Copyright (c) 2015, Intel Corporation\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\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 Intel Corporation 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 \"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/** \\file\n * \\brief State for corpus generator.\n  */\n\n#include \"config.h\"\n\n#include \"ng_corpus_properties.h\"\n#include \"ue2common.h\"\n\n#include <boost/random/uniform_int_distribution.hpp>\n\n// default constructor\nCorpusProperties::CorpusProperties()\n    : matchness(100), unmatchness(0), randomness(0), prefixRange(0, 0),\n      suffixRange(0, 0), cycleMin(1), cycleMax(1),\n      corpusLimit(DEFAULT_CORPUS_GENERATOR_LIMIT), editDistance(0),\n      alphabetSize(~0) {\n    // empty\n}\n\nbool CorpusProperties::setPercentages(unsigned int match, unsigned int unmatch,\n                                      unsigned int random) {\n    if (match + unmatch + random != 100) {\n        // Do not update probabilities\n        return false;\n    }\n    matchness = match;\n    unmatchness = unmatch;\n    randomness = random;\n    return true;\n}\n\nvoid CorpusProperties::seed(unsigned val) {\n    rngSeed = val;\n    randomGen.seed(val);\n}\n\nunsigned CorpusProperties::getSeed() const {\n    return rngSeed;\n}\n\nunsigned CorpusProperties::rand(unsigned n, unsigned m) {\n    boost::random::uniform_int_distribution<> dist(n, m);\n    return dist(randomGen);\n}\n\n// not const because it stores state for the random number generator\nCorpusProperties::RollResult CorpusProperties::throwDice() {\n    if (matchness == 100) {\n        return ROLLED_MATCH;\n    }\n    if (unmatchness == 100) {\n        return ROLLED_UNMATCH;\n    }\n    if (randomness == 100) {\n        return ROLLED_RANDOM;\n    }\n\n    // This assumes a uniform distribution.  Perhaps factor some 'depth' param\n    // and whether this 'depth' should increase or decrease the likelihood of\n    // unmatch or random rolls.\n    unsigned int outcome = rand(0, 99);\n    if (outcome < matchness) {\n        return ROLLED_MATCH;\n    }\n    if (outcome < matchness + unmatchness) {\n        return ROLLED_UNMATCH;\n    }\n\n    return ROLLED_RANDOM;\n}\n", "meta": {"hexsha": "e784e05827a75059abea40aaf35805a7fbc7a9ad", "size": 3419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/ng_corpus_properties.cpp", "max_stars_repo_name": "Mic92/hyperscan", "max_stars_repo_head_hexsha": "64a995bf445d86b74eb0f375624ffc85682eadfe", "max_stars_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_stars_count": 2868.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T02:25:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:24:16.000Z", "max_issues_repo_path": "util/ng_corpus_properties.cpp", "max_issues_repo_name": "Mic92/hyperscan", "max_issues_repo_head_hexsha": "64a995bf445d86b74eb0f375624ffc85682eadfe", "max_issues_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_issues_count": 270.0, "max_issues_repo_issues_event_min_datetime": "2017-10-30T19:53:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:03:17.000Z", "max_forks_repo_path": "util/ng_corpus_properties.cpp", "max_forks_repo_name": "Mic92/hyperscan", "max_forks_repo_head_hexsha": "64a995bf445d86b74eb0f375624ffc85682eadfe", "max_forks_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_forks_count": 403.0, "max_forks_repo_forks_event_min_datetime": "2017-11-02T01:18:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T08:46:20.000Z", "avg_line_length": 34.19, "max_line_length": 79, "alphanum_fraction": 0.7081017841, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.17695643930840238}}
{"text": "// Copyright 2015-2020 Tier IV, 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#include <quaternion_operation/quaternion_operation.h>\n\n#include <boost/algorithm/clamp.hpp>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <traffic_simulator/behavior/pedestrian/follow_lane_action.hpp>\n#include <vector>\n\nnamespace entity_behavior\n{\nnamespace pedestrian\n{\nFollowLaneAction::FollowLaneAction(const std::string & name, const BT::NodeConfiguration & config)\n: entity_behavior::PedestrianActionNode(name, config)\n{\n}\n\nvoid FollowLaneAction::getBlackBoardValues() { PedestrianActionNode::getBlackBoardValues(); }\n\nBT::NodeStatus FollowLaneAction::tick()\n{\n  getBlackBoardValues();\n  if (request != \"none\" && request != \"follow_lane\") {\n    return BT::NodeStatus::FAILURE;\n  }\n  if (!entity_status.lanelet_pose_valid) {\n    setOutput(\"updated_status\", stopAtEndOfRoad());\n    return BT::NodeStatus::RUNNING;\n  }\n  auto following_lanelets =\n    hdmap_utils->getFollowingLanelets(entity_status.lanelet_pose.lanelet_id);\n  if (!target_speed) {\n    target_speed = hdmap_utils->getSpeedLimit(following_lanelets);\n  }\n  geometry_msgs::msg::Accel accel_new;\n  accel_new = entity_status.action_status.accel;\n\n  double target_accel =\n    (target_speed.get() - entity_status.action_status.twist.linear.x) / step_time;\n  if (entity_status.action_status.twist.linear.x > target_speed.get()) {\n    target_accel = boost::algorithm::clamp(target_accel, -5, 0);\n    /*\u3000target_accel = boost::algorithm::clamp(target_accel,\n      -1*vehicle_param_ptr->performance.max_deceleration, vehicle_param_ptr->performance.max_acceleration);\n      */\n  } else {\n    target_accel = boost::algorithm::clamp(target_accel, 0, 3);\n    /* target_accel = boost::algorithm::clamp(target_accel,\n      -1*vehicle_param_ptr->performance.max_deceleration, vehicle_param_ptr->performance.max_acceleration);*/\n  }\n  accel_new.linear.x = target_accel;\n  geometry_msgs::msg::Twist twist_new;\n  twist_new.linear.x = boost::algorithm::clamp(\n    entity_status.action_status.twist.linear.x + accel_new.linear.x * step_time, 0, 5.0);\n  twist_new.linear.y = 0.0;\n  twist_new.linear.z = 0.0;\n  twist_new.angular.x = 0.0;\n  twist_new.angular.y = 0.0;\n  twist_new.angular.z = 0.0;\n\n  double new_s =\n    entity_status.lanelet_pose.s +\n    (twist_new.linear.x + entity_status.action_status.twist.linear.x) / 2.0 * step_time;\n  geometry_msgs::msg::Vector3 rpy = entity_status.lanelet_pose.rpy;\n\n  openscenario_msgs::msg::EntityStatus entity_status_updated;\n  entity_status_updated.time = current_time + step_time;\n  entity_status_updated.lanelet_pose.lanelet_id = entity_status.lanelet_pose.lanelet_id;\n  entity_status_updated.lanelet_pose.s = new_s;\n  entity_status_updated.lanelet_pose.offset = entity_status.lanelet_pose.offset;\n  entity_status_updated.lanelet_pose.rpy = rpy;\n  entity_status_updated.action_status.twist = twist_new;\n  entity_status_updated.action_status.accel = accel_new;\n  entity_status_updated.pose = hdmap_utils->toMapPose(entity_status.lanelet_pose).pose;\n  setOutput(\"updated_status\", entity_status_updated);\n  return BT::NodeStatus::RUNNING;\n}\n}  // namespace pedestrian\n}  // namespace entity_behavior\n", "meta": {"hexsha": "69bcba0bd239a53e7b9e19fe574fc9b4ac1a7299", "size": 3722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation/traffic_simulator/src/behavior/pedestrian/follow_lane_action.cpp", "max_stars_repo_name": "kmiya/scenario_simulator_v2", "max_stars_repo_head_hexsha": "13635e661cc643c783853d1b4c060d1e3dff3458", "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": "simulation/traffic_simulator/src/behavior/pedestrian/follow_lane_action.cpp", "max_issues_repo_name": "kmiya/scenario_simulator_v2", "max_issues_repo_head_hexsha": "13635e661cc643c783853d1b4c060d1e3dff3458", "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": "simulation/traffic_simulator/src/behavior/pedestrian/follow_lane_action.cpp", "max_forks_repo_name": "kmiya/scenario_simulator_v2", "max_forks_repo_head_hexsha": "13635e661cc643c783853d1b4c060d1e3dff3458", "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.5957446809, "max_line_length": 109, "alphanum_fraction": 0.7619559377, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.17681835178862526}}
{"text": "/* Copyright (c) 2012 Cheese and Bacon Games, LLC */\n/* This file is licensed under the MIT License. */\n/* See the file docs/LICENSE.txt for the full license text. */\n\n#include \"cipher.h\"\n#include \"pixels.h\"\n\n#include <boost/crc.hpp>\n\nusing namespace std;\n\nconst vector<unsigned char> Cipher::characters=Cipher::generate_characters();\n\nvector<unsigned char> Cipher::generate_characters(){\n    vector<unsigned char> temp_characters;\n\n    for(unsigned char i=' ';i<='~';i++){\n        temp_characters.push_back(i);\n    }\n\n    temp_characters.push_back('\\n');\n\n    return temp_characters;\n}\n\nint Cipher::get_max_character_index(){\n    return characters.size()-1;\n}\n\nint Cipher::get_character_index(unsigned char input){\n    for(int i=0;i<characters.size();i++){\n        if(input==characters[i]){\n            return i;\n        }\n    }\n\n    return 0;\n}\n\nunsigned char Cipher::get_character(int input){\n    if(input<0 || input>get_max_character_index()){\n        input=0;\n    }\n\n    return characters[input];\n}\n\nvector<RNG> Cipher::generate_rngs(){\n    vector<RNG> rngs;\n\n    for(size_t i=0;i<seeds.size();i++){\n        rngs.push_back(RNG(seeds[i]));\n    }\n\n    return rngs;\n}\n\nunsigned char Cipher::encipher_character(unsigned char character,vector<RNG>& rngs){\n    int character_index=get_character_index(character);\n\n    for(size_t i=0;i<rngs.size();i++){\n        character_index+=(int)rngs[i].random_range(0,(uint32_t)get_max_character_index());\n\n        while(character_index>get_max_character_index()){\n            character_index-=get_max_character_index()+1;\n        }\n    }\n\n    return get_character(character_index);\n}\n\nunsigned char Cipher::decipher_character(unsigned char character,vector<RNG>& rngs){\n    int character_index=get_character_index(character);\n\n    for(size_t i=rngs.size()-1;;i--){\n        character_index-=(int)rngs[i].random_range(0,(uint32_t)get_max_character_index());\n\n        while(character_index<0){\n            character_index+=get_max_character_index()+1;\n        }\n\n        if(i==0){\n            break;\n        }\n    }\n\n    return get_character(character_index);\n}\n\nvoid Cipher::cipher(string& input,bool enciphering){\n    if(seeds.size()>0){\n        vector<RNG> rngs=generate_rngs();\n\n        for(size_t i=0;i<input.length();i++){\n            if(enciphering){\n                input[i]=encipher_character(input[i],rngs);\n            }\n            else{\n                input[i]=decipher_character(input[i],rngs);\n            }\n        }\n    }\n}\n\nstring Cipher::cipher_copy(string input,bool enciphering){\n    cipher(input,enciphering);\n\n    return input;\n}\n\nvoid Cipher::encipher_pixel(SDL_Surface* surface,int x,int y,vector<RNG>& rngs){\n    Color color=surface_get_pixel(surface,x,y);\n    int red=color.get_red_short();\n    int green=color.get_green_short();\n    int blue=color.get_blue_short();\n    int alpha=color.get_alpha_short();\n\n    for(size_t i=0;i<rngs.size();i++){\n        red+=(int)rngs[i].random_range(0,255);\n        green+=(int)rngs[i].random_range(0,255);\n        blue+=(int)rngs[i].random_range(0,255);\n        alpha+=(int)rngs[i].random_range(0,255);\n\n        while(red>255){\n            red-=256;\n        }\n        while(green>255){\n            green-=256;\n        }\n        while(blue>255){\n            blue-=256;\n        }\n        while(alpha>255){\n            alpha-=256;\n        }\n    }\n\n    color.set_rgb(red,green,blue,alpha);\n\n    surface_put_pixel(surface,x,y,color);\n}\n\nvoid Cipher::decipher_pixel(SDL_Surface* surface,int x,int y,vector<RNG>& rngs){\n    Color color=surface_get_pixel(surface,x,y);\n    int red=color.get_red_short();\n    int green=color.get_green_short();\n    int blue=color.get_blue_short();\n    int alpha=color.get_alpha_short();\n\n    for(size_t i=rngs.size()-1;;i--){\n        red-=(int)rngs[i].random_range(0,255);\n        green-=(int)rngs[i].random_range(0,255);\n        blue-=(int)rngs[i].random_range(0,255);\n        alpha-=(int)rngs[i].random_range(0,255);\n\n        while(red<0){\n            red+=256;\n        }\n        while(green<0){\n            green+=256;\n        }\n        while(blue<0){\n            blue+=256;\n        }\n        while(alpha<0){\n            alpha+=256;\n        }\n\n        if(i==0){\n            break;\n        }\n    }\n\n    color.set_rgb(red,green,blue,alpha);\n\n    surface_put_pixel(surface,x,y,color);\n}\n\nvoid Cipher::cipher(SDL_Surface* input,bool enciphering){\n    if(seeds.size()>0){\n        vector<RNG> rngs=generate_rngs();\n\n        for(int x=0;x<input->w;x++){\n            for(int y=0;y<input->h;y++){\n                if(enciphering){\n                    encipher_pixel(input,x,y,rngs);\n                }\n                else{\n                    decipher_pixel(input,x,y,rngs);\n                }\n            }\n        }\n    }\n}\n\nuint8_t Cipher::encipher_sound_byte(uint8_t sound_byte,vector<RNG>& rngs){\n    int input=sound_byte;\n\n    for(size_t i=0;i<rngs.size();i++){\n        input+=(int)rngs[i].random_range(0,255);\n\n        while(input>255){\n            input-=256;\n        }\n    }\n\n    return (uint8_t)input;\n}\n\nuint8_t Cipher::decipher_sound_byte(uint8_t sound_byte,vector<RNG>& rngs){\n    int input=sound_byte;\n\n    for(size_t i=rngs.size()-1;;i--){\n        input-=(int)rngs[i].random_range(0,255);\n\n        while(input<0){\n            input+=256;\n        }\n\n        if(i==0){\n            break;\n        }\n    }\n\n    return (uint8_t)input;\n}\n\nvoid Cipher::cipher(Mix_Chunk* input,bool enciphering){\n    if(seeds.size()>0){\n        vector<RNG> rngs=generate_rngs();\n\n        for(size_t i=0;i<input->alen;i++){\n            if(enciphering){\n                input->abuf[i]=encipher_sound_byte(input->abuf[i],rngs);\n            }\n            else{\n                input->abuf[i]=decipher_sound_byte(input->abuf[i],rngs);\n            }\n        }\n    }\n}\n\nCipher::Cipher(const vector<string>& seed_strings){\n    set_seeds(seed_strings);\n}\n\nvoid Cipher::set_seeds(const vector<string>& seed_strings){\n    seeds.clear();\n\n    for(size_t i=0;i<seed_strings.size();i++){\n        if(seed_strings[i].length()>0){\n            boost::crc_32_type result;\n            result.process_bytes(seed_strings[i].data(),seed_strings[i].length());\n\n            seeds.push_back((uint32_t)result.checksum());\n        }\n    }\n}\n\nvoid Cipher::encipher(string& input){\n    cipher(input,true);\n}\n\nvoid Cipher::decipher(string& input){\n    cipher(input,false);\n}\n\nstring Cipher::encipher_copy(const string& input){\n    return cipher_copy(input,true);\n}\n\nstring Cipher::decipher_copy(const string& input){\n    return cipher_copy(input,false);\n}\n\nvoid Cipher::encipher(SDL_Surface* input){\n    cipher(input,true);\n}\n\nvoid Cipher::decipher(SDL_Surface* input){\n    cipher(input,false);\n}\n\nvoid Cipher::encipher(Mix_Chunk* input){\n    cipher(input,true);\n}\n\nvoid Cipher::decipher(Mix_Chunk* input){\n    cipher(input,false);\n}\n", "meta": {"hexsha": "b474e1fafc5f0e440582b3aaf95c35e08777ea38", "size": 6809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cipher.cpp", "max_stars_repo_name": "darkoppressor/ainos", "max_stars_repo_head_hexsha": "6fcf863db10242995705f3e1507277ef9260486c", "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": "cipher.cpp", "max_issues_repo_name": "darkoppressor/ainos", "max_issues_repo_head_hexsha": "6fcf863db10242995705f3e1507277ef9260486c", "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": "cipher.cpp", "max_forks_repo_name": "darkoppressor/ainos", "max_forks_repo_head_hexsha": "6fcf863db10242995705f3e1507277ef9260486c", "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": 23.3986254296, "max_line_length": 90, "alphanum_fraction": 0.5946541342, "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.17674036167692506}}
{"text": "#ifndef BackgroundHandler_cc\n#define BackgroundHandler_cc\n\n#include \"MuonAnalysis/MomentumScaleCalibration/interface/BackgroundHandler.h\"\n#include <algorithm>\n#include <TF1.h>\n#include <iostream>\n#include <boost/foreach.hpp>\n\ntypedef reco::Particle::LorentzVector lorentzVector;\n\nBackgroundHandler::BackgroundHandler( const std::vector<int> & identifiers,\n                                      const std::vector<double> & leftWindowBorders,\n                                      const std::vector<double> & rightWindowBorders,\n                                      const double * ResMass,\n                                      const double * massWindowHalfWidth )\n{\n  // : leftWindowFactors_(leftWindowFactors),\n  // rightWindowFactors_(rightWindowFactors)\n\n  // Define the correspondence between regions and halfWidth to use\n  // Defines also the function type to use (but they are checked to be consistent over a region)\n  regToResHW_[0] = 0; // Region 0 use the one from Z\n  regToResHW_[1] = 3; // Region 1 use the one from Upsilon1S\n  regToResHW_[2] = 5; // Region 2 use the one from J/Psi\n\n  // Define the correspondence between resonances and regions\n  resToReg_[0] = 0; // Z\n  resToReg_[1] = 1; // Upsilon3S\n  resToReg_[2] = 1; // Upsilon2S\n  resToReg_[3] = 1; // Upsilon1S\n  resToReg_[4] = 2; // Psi2S\n  resToReg_[5] = 2; // J/Psi\n\n  // Throws cms::Exception(\"Configuration\") in case the parameters are not what is expected\n  consistencyCheck(identifiers, leftWindowBorders, rightWindowBorders);\n\n  // Build the resonance windows\n  for( unsigned int i=0; i<6; ++i ) {\n    double mass = ResMass[i];\n    double lowerLimit = mass - massWindowHalfWidth[i];\n    double upperLimit = mass + massWindowHalfWidth[i];\n    resonanceWindow_.push_back( MassWindow( mass, lowerLimit, upperLimit,\n                                            std::vector<unsigned int>(1,i),\n                                            backgroundFunctionService(identifiers[resToReg_[i]],\n                                                                      lowerLimit,\n                                                                      upperLimit) ) );\n  }\n\n  // Build the background windows\n  // ----------------------------\n  // Compute the mass center of each region\n  double resMassForRegion[3];\n  resMassForRegion[0] = ResMass[0];\n  resMassForRegion[1] = (ResMass[1]+ResMass[2]+ResMass[3])/3;\n  resMassForRegion[2] = (ResMass[4]+ResMass[5])/2;\n\n  // Define which resonance is in which background window\n  std::vector<std::vector<unsigned int> > indexes;\n  indexes.push_back(std::vector<unsigned int>(1,0));\n  indexes.push_back(std::vector<unsigned int>());\n  for( int i=1; i<=3; ++i ) { indexes[1].push_back(i); }\n  indexes.push_back(std::vector<unsigned int>());\n  for( int i=4; i<=5; ++i ) { indexes[2].push_back(i); }\n\n  unsigned int i=0;\n  typedef std::vector<unsigned int> indexVec;\n  BOOST_FOREACH(const indexVec & index, indexes) {\n    //     double lowerLimit = resMassForRegion[i] - massWindowHalfWidth[regToResHW_[i]]*leftWindowFactors[i];\n    //     double upperLimit = resMassForRegion[i] + massWindowHalfWidth[regToResHW_[i]]*rightWindowFactors[i];\n    //     backgroundWindow_.push_back( MassWindow( resMassForRegion[i], lowerLimit, upperLimit, index,\n    //                                              backgroundFunctionService(identifiers[i], lowerLimit, upperLimit ) ) );\n    backgroundWindow_.push_back( MassWindow( resMassForRegion[i], leftWindowBorders[i], rightWindowBorders[i], index,\n                                             backgroundFunctionService(identifiers[i], leftWindowBorders[i], rightWindowBorders[i] ) ) );\n    ++i;\n  }\n  // Initialize the parNums to be used in the shifts of parval\n  initializeParNums();\n}\n\nBackgroundHandler::~BackgroundHandler()\n{\n}\n\nvoid BackgroundHandler::initializeParNums()\n{\n  // Initialize the parNums to be used in the shifts of parval\n  parNumsRegions_[0] = 0;\n  for( unsigned int i=1; i<backgroundWindow_.size() ; ++i ) {\n    parNumsRegions_[i] = parNumsRegions_[i-1] + backgroundWindow_[i-1].backgroundFunction()->parNum();\n  }\n  parNumsResonances_[0] = parNumsRegions_[2]+backgroundWindow_[2].backgroundFunction()->parNum();\n  for( unsigned int i=1; i<resonanceWindow_.size() ; ++i ) {\n    parNumsResonances_[i] = parNumsResonances_[i-1] + resonanceWindow_[i-1].backgroundFunction()->parNum();\n  }\n}\n\nvoid BackgroundHandler::setParameters(double* Start, double* Step, double* Mini, double* Maxi, int* ind, TString* parname, const std::vector<double> & parBgr, const std::vector<int> & parBgrOrder, const int muonType)\n{\n  std::vector<double>::const_iterator parBgrIt = parBgr.begin();\n  std::vector<int>::const_iterator parBgrOrderIt = parBgrOrder.begin();\n  // Set the parameters for the regions only if this is not a rescaling\n  for( int iReg = 0; iReg < 3; ++iReg ) {\n    int shift = parNumsRegions_[iReg];\n    backgroundWindow_[iReg].backgroundFunction()->setParameters( &(Start[shift]), &(Step[shift]), &(Mini[shift]),\n        &(Maxi[shift]), &(ind[shift]), &(parname[shift]),\n        parBgrIt+shift, parBgrOrderIt+shift, muonType );\n  }\n  for( int iRes = 0; iRes < 6; ++iRes ) {\n    // parNumsResonances is already shifted for the regions parameters\n    int shift = parNumsResonances_[iRes];\n    resonanceWindow_[iRes].backgroundFunction()->setParameters( &(Start[shift]), &(Step[shift]), &(Mini[shift]),\n        &(Maxi[shift]), &(ind[shift]), &(parname[shift]),\n        parBgrIt+shift, parBgrOrderIt+shift, muonType );\n  }\n}\n\nbool BackgroundHandler::unlockParameter(const std::vector<int> & resfind, const unsigned int ipar)\n{\n  // parNumsRegions_ are shifted: [1] contains the number of parameters for 0 and so on.\n  if( ipar < unsigned(parNumsRegions_[1]) && resfind[0] > 0 ) {\n    return true;\n  }\n  if( ipar >= unsigned(parNumsRegions_[1]) && ipar < unsigned(parNumsRegions_[2]) && ( resfind[1] > 0 || resfind[2] > 0 || resfind[3] > 0 ) ) {\n    return true;\n  }\n  // The first of parNumsResonances_ has the sum of parNums of the regions.\n  if( ipar >= unsigned(parNumsRegions_[2]) && ipar < unsigned(parNumsResonances_[0]) && ( resfind[4] > 0 || resfind[5] > 0 ) ) {\n    return true;\n  }\n  return false;\n}\n\n// std::pair<double, double> BackgroundHandler::windowFactors( const bool doBackgroundFit, const int ires )\n// {\n//   if( doBackgroundFit ) {\n//     // Fitting the background: use the regions\n//     return std::make_pair(leftWindowFactors_[resToReg_[ires]], rightWindowFactors_[resToReg_[ires]]);\n//   }\n//   else {\n//     // Not fitting the background: use the resonances\n//     return std::make_pair(1.,1.);\n//   }\n// }\n\nstd::pair<double, double> BackgroundHandler::windowBorders( const bool doBackgroundFit, const int ires )\n{\n  if( doBackgroundFit ) {\n    // Fitting the background: use the regions\n    return std::make_pair(backgroundWindow_[resToReg_[ires]].lowerBound(), backgroundWindow_[resToReg_[ires]].upperBound());\n  }\n  else {\n    // Not fitting the background: use the resonances\n    // return std::make_pair(1.,1.);\n    return std::make_pair(resonanceWindow_[ires].lowerBound(), resonanceWindow_[ires].upperBound());\n  }\n}\n\ndouble BackgroundHandler::resMass( const bool doBackgroundFit, const int ires )\n{\n  if( doBackgroundFit ) {\n    // Fitting the background: use the regions\n    return backgroundWindow_[resToReg_[ires]].mass();\n  }\n  else {\n    // Not fitting the background: use the resonances\n    return resonanceWindow_[ires].mass();\n  }\n}\n\nvoid BackgroundHandler::rescale( std::vector<double> & parBgr, const double * ResMass, const double * massWindowHalfWidth,\n                                 const std::vector<std::pair<reco::Particle::LorentzVector,reco::Particle::LorentzVector> > & muonPairs,\n                                 const double & weight )\n{\n  countEventsInAllWindows(muonPairs, weight);\n\n  // Loop on all regions and on all the resonances of each region and compute the background fraction\n  // for each resonance window.\n  unsigned int iRegion = 0;\n  BOOST_FOREACH(MassWindow & backgroundWindow, backgroundWindow_)\n  {\n    // Iterator pointing to the first parameter of this background function in the full set of parameters\n    std::vector<double>::const_iterator parBgrIt = (parBgr.begin()+parNumsRegions_[iRegion]);\n    TF1 * backgroundFunctionForIntegral = backgroundWindow.backgroundFunction()->functionForIntegral(parBgrIt);\n    // WARNING: this expects the background fraction parameter to be parBgr[0] for all the background functions.\n    double kOld = *parBgrIt;\n    double Nbw = backgroundWindow.events();\n    double Ibw = backgroundFunctionForIntegral->Integral(backgroundWindow.lowerBound(),\n                                                         backgroundWindow.upperBound());\n\n    // index is the index of the resonance in the background window\n    BOOST_FOREACH( unsigned int index, *(backgroundWindow.indexes()) )\n    {\n      // First set all parameters of the resonance window background function to those of the corresponding region\n      for( int iPar = 0; iPar < resonanceWindow_[index].backgroundFunction()->parNum(); ++iPar ) {\n        parBgr[parNumsResonances_[index]+iPar] = parBgr[parNumsRegions_[resToReg_[index]]+iPar];\n      }\n      // Estimated fraction of events in the resonance window\n      double Irw = backgroundFunctionForIntegral->Integral(resonanceWindow_[index].lowerBound(),\n                                                           resonanceWindow_[index].upperBound());\n      double Nrw = resonanceWindow_[index].events();\n\n      // Ibw is 1 (to avoid effects from approximation errors we set it to 1 and do not include it in the computation).\n      if( Nrw != 0 ) parBgr[parNumsResonances_[index]] = kOld*Nbw/Nrw*Irw;\n      else parBgr[parNumsResonances_[index]] = 0.;\n\n      // Protect against fluctuations of number of events which could cause the fraction to go above 1.\n      if( parBgr[parNumsResonances_[index]] > 1. ) parBgr[parNumsResonances_[index]] = 1.;\n\n      double kNew = parBgr[parNumsResonances_[index]];\n      std::cout << \"For resonance = \" << index << std::endl;\n      std::cout << \"backgroundWindow.lowerBound = \" << backgroundWindow.lowerBound() << std::endl;\n      std::cout << \"backgroundWindow.upperBound = \" << backgroundWindow.upperBound() << std::endl;\n      std::cout << \"parNumsResonances_[\"<<index<<\"] = \" << parNumsResonances_[index] << std::endl;\n      std::cout << \"Nbw = \" << Nbw << \", Ibw = \" << Ibw << std::endl;\n      std::cout << \"Nrw = \" << Nrw << \", Irw = \" << Irw << std::endl;\n      std::cout << \"k = \" << kOld << \", k' = \" << parBgr[parNumsResonances_[index]] << std::endl;\n      std::cout << \"background fraction in background window = Nbw*k = \" << Nbw*kOld << std::endl;\n      std::cout << \"background fraction in resonance window = Nrw*k' = \" << Nrw*kNew << std::endl;\n    }\n    ++iRegion;\n    delete backgroundFunctionForIntegral;\n  }\n}\n\nstd::pair<double, double> BackgroundHandler::backgroundFunction( const bool doBackgroundFit,\n\t\t\t\t\t\t\t\t const double * parval, const int resTotNum, const int ires,\n\t\t\t\t\t\t\t\t const bool * resConsidered, const double * ResMass, const double ResHalfWidth[],\n\t\t\t\t\t\t\t\t const int MuonType, const double & mass,\n\t\t\t\t\t\t\t\t const double & eta1, const double & eta2 )\n{\n  if( doBackgroundFit ) {\n    // Return the values for the region\n    int iReg = resToReg_[ires];\n    // return std::make_pair( parval[parNumsRegions_[iReg]] * backgroundWindow_[iReg].backgroundFunction()->fracVsEta(&(parval[parNumsRegions_[iReg]]), resEta),\n    return std::make_pair( parval[parNumsRegions_[iReg]] * backgroundWindow_[iReg].backgroundFunction()->fracVsEta(&(parval[parNumsRegions_[iReg]]), eta1, eta2 ),\n    \t\t\t   (*(backgroundWindow_[iReg].backgroundFunction()))( &(parval[parNumsRegions_[iReg]]), mass, eta1, eta2 ) );\n    // return std::make_pair( backgroundWindow_[iReg].backgroundFunction()->fracVsEta(&(parval[parNumsRegions_[iReg]]), eta1, eta2),\n    // \t\t\t   (*(backgroundWindow_[iReg].backgroundFunction()))( &(parval[parNumsRegions_[iReg]]), mass, eta1, eta2 ) );\n  }\n  // Return the values for the resonance\n  // return std::make_pair( parval[parNumsResonances_[ires]] * resonanceWindow_[ires].backgroundFunction()->fracVsEta(&(parval[parNumsResonances_[ires]]), resEta),\n  // \t\t\t (*(resonanceWindow_[ires].backgroundFunction()))( &(parval[parNumsResonances_[ires]]), mass, resEta ) );\n  return std::make_pair( parval[parNumsResonances_[ires]] * resonanceWindow_[ires].backgroundFunction()->fracVsEta(&(parval[parNumsResonances_[ires]]), eta1, eta2),\n\t\t\t (*(resonanceWindow_[ires].backgroundFunction()))( &(parval[parNumsResonances_[ires]]), mass, eta1, eta2 ) );\n}\n\nvoid BackgroundHandler::countEventsInAllWindows(const std::vector<std::pair<reco::Particle::LorentzVector,reco::Particle::LorentzVector> > & muonPairs,\n                                                const double & weight)\n{\n  // First reset all the counters\n  BOOST_FOREACH(MassWindow & resonanceWindow, resonanceWindow_) {\n    resonanceWindow.resetCounter();\n  }\n  // Count events in background windows\n  BOOST_FOREACH(MassWindow & backgroundWindow, backgroundWindow_) {\n    backgroundWindow.resetCounter();\n  }\n\n  // Now count the events in each window\n  std::pair<lorentzVector,lorentzVector> muonPair;\n  BOOST_FOREACH(muonPair, muonPairs) {\n    // Count events in resonance windows\n    BOOST_FOREACH(MassWindow & resonanceWindow, resonanceWindow_) {\n      resonanceWindow.count((muonPair.first + muonPair.second).mass(), weight);\n    }\n    // Count events in background windows\n    BOOST_FOREACH(MassWindow & backgroundWindow, backgroundWindow_) {\n      backgroundWindow.count((muonPair.first + muonPair.second).mass(), weight);\n    }\n  }\n}\n\nvoid BackgroundHandler::consistencyCheck(const std::vector<int> & identifiers,\n                                         const std::vector<double> & leftWindowBorders,\n                                         const std::vector<double> & rightWindowBorders) const noexcept(false)\n{\n  if( leftWindowBorders.size() != rightWindowBorders.size() ) {\n    throw cms::Exception(\"Configuration\") << \"BackgroundHandler::BackgroundHandler: leftWindowBorders.size() = \" << leftWindowBorders.size()\n                                          << \" != rightWindowBorders.size() = \" << rightWindowBorders.size() << std::endl;\n  }\n  if( leftWindowBorders.size() != 3 ) {\n    throw cms::Exception(\"Configuration\") << \"BackgroundHandler::BackgroundHandler: leftWindowBorders.size() = rightWindowBorders.size() = \"\n                                          << leftWindowBorders.size() << \" != 3\" << std::endl;\n  }\n  if( identifiers.size() != 3 ) {\n    throw cms::Exception(\"Configuration\") << \"BackgroundHandler::BackgroundHandler: identifiers must match the number of regions = 3\" << std::endl;\n  }\n}\n\n#endif // BackgroundHandler_cc\n", "meta": {"hexsha": "1341489446276005c7f35ef98e82f6daf9d8de26", "size": 14759, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MuonAnalysis/MomentumScaleCalibration/src/BackgroundHandler.cc", "max_stars_repo_name": "nistefan/cmssw", "max_stars_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "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": "MuonAnalysis/MomentumScaleCalibration/src/BackgroundHandler.cc", "max_issues_repo_name": "nistefan/cmssw", "max_issues_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "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": "MuonAnalysis/MomentumScaleCalibration/src/BackgroundHandler.cc", "max_forks_repo_name": "nistefan/cmssw", "max_forks_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "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": 50.5445205479, "max_line_length": 216, "alphanum_fraction": 0.6642726472, "num_tokens": 3818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1766465712546257}}
{"text": "\ufeff#include \"../include/init.hpp\"\r\n\r\n#include <iostream>\r\n#include <cmath>\r\n#include <opencv2/opencv.hpp>\r\n#include <boost/version.hpp>\r\n#include \"../include/yuriface.hpp\"\r\n#include \"../include/transform.hpp\"\r\n#include \"../include/geometry.hpp\"\r\n#include \"../include/face_part.hpp\"\r\n\r\n\r\nint main(int argc, char **argv) {\r\n\r\n\tstd::cout << \"Start Yuri Face\" << std::endl;\r\n\r\n\tYuriFace *yuriface = LoadYFML(argv[1]);\r\n\tcv::Mat img = yuriface->getImage();\r\n\r\n\tFace *face_obj = NULL;\r\n\tyuriface2face(yuriface, face_obj);\r\n\r\n\r\n\t/*\r\n\tstd::cout << \"dots\" << std::endl;\r\n\t\r\n\tfor (Dot *dot : *yuriface->getObjects()->at(0)->getDotsVector()) {\r\n\t\tstd::cout << dot->getX() << \":\" << dot->getY() << std::endl;\r\n\t\tcv::circle(img, cv::Point(dot->getX(), dot->getY()), 5, cv::Scalar(0, 0, 0), 1, 1);\r\n\t}\r\n\tstd::cout << \"line\" << std::endl;\r\n\tfor (Dot *dot : *yuriface->getObjects()->at(0)->getDotsVector()) {\r\n\t\tstd::cout << dot->getX() << \":\" << dot->getY() << \" \";\r\n\t\tfor (Dot *dot2 : *dot->getConnectedDotsVector()) {\r\n\t\t\tstd::cout << dot2->getX() << \":\" << dot2->getY() << std::endl;\r\n\t\t\tcv::line(img, cv::Point(dot->getX(), dot->getY()), cv::Point(dot2->getX(), dot2->getY()), cv::Scalar(0, 0, 0));\r\n\t\t}\r\n\t}\r\n\tstd::cout << \"name : \" << yuriface->getObjects()->at(0)->getName() << std::endl;\r\n\t\r\n\t*/\r\n\r\n\tcv::Point2f dst_points[4];\r\n\r\n\tcv::Rect rect = BoostBox2CvRect(CreateEnvelope(CreateRing(yuriface->getObjects()->at(0))));\r\n\tcv::Mat result = CutImage(img, rect);\r\n\tresult = RotationTransform(result, 45);\r\n\r\n\tcv::Mat face = YuriInpainting(img, rect);\r\n\r\n\tdst_points[0] = cv::Point2f(0.0f, 0.0f);\r\n\tdst_points[1] = cv::Point2f(result.cols * 0.2, result.rows * 0.8);\r\n\tdst_points[2] = cv::Point2f(result.cols, result.rows);\r\n\tdst_points[3] = cv::Point2f(result.cols * 0.8, result.rows * 0.2);\r\n\r\n\tresult = PerspectiveTransform(result, dst_points, cv::Size(result.cols, result.rows));\r\n\r\n\tresult = RotationTransform(result, -45);\r\n\t\r\n\tint i;\r\n\tresult = SharpenImage(result, &i);\r\n\r\n\tcv::namedWindow(\"Yuri Face\");\r\n\t//result = YuriFacePasteImage(face, result, rect.x * 0.90, rect.y * 0.85).clone();\r\n\tresult = face_obj->getMouth()->OpenMouth(face_obj->getFaceBase(), 6).clone();\r\n\tcv::Mat level3 = face_obj->getMouth()->OpenMouth(face_obj->getFaceBase(), 4).clone();\r\n\t\r\n\twhile (true) {\r\n\t\tShowAndWait(img, \"Yuri Face\", 180);\r\n\t\tShowAndWait(level3, \"Yuri Face\", 180);\r\n\t\tShowAndWait(result, \"Yuri Face\", 180);\r\n\t}\r\n\r\n}\r\n", "meta": {"hexsha": "31a64d4b96d033805ae8d9f16b22249ed9082aa2", "size": 2406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "atsisy/yuri_face_cc", "max_stars_repo_head_hexsha": "bdfd90c2aacec70f2abcfffff472f390c0e9f73f", "max_stars_repo_licenses": ["MIT", "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": "src/main.cpp", "max_issues_repo_name": "atsisy/yuri_face_cc", "max_issues_repo_head_hexsha": "bdfd90c2aacec70f2abcfffff472f390c0e9f73f", "max_issues_repo_licenses": ["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/main.cpp", "max_forks_repo_name": "atsisy/yuri_face_cc", "max_forks_repo_head_hexsha": "bdfd90c2aacec70f2abcfffff472f390c0e9f73f", "max_forks_repo_licenses": ["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": 32.08, "max_line_length": 115, "alphanum_fraction": 0.6134663342, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17664657125462568}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@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_BLOCK_DECRYPT_HPP\n#define CRYPTO3_BLOCK_DECRYPT_HPP\n\n#include <boost/crypto3/detail/type_traits.hpp>\n\n#include <boost/crypto3/block/algorithm/block.hpp>\n\n#include <boost/crypto3/block/cipher_value.hpp>\n#include <boost/crypto3/block/cipher_state.hpp>\n#include <boost/crypto3/block/cipher_key.hpp>\n\n#include <boost/crypto3/block/detail/cipher_modes.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace block {\n            template<typename BlockCipher>\n            using decryption_policy = typename block::modes::isomorphic<BlockCipher, nop_padding>::decryption_policy;\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam InputIterator\n         * @tparam KeyIterator\n         * @tparam OutputIterator\n         *\n         * @param first\n         * @param last\n         * @param key_first\n         * @param key_last\n         * @param out\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename InputIterator, typename KeyInputIterator, typename OutputIterator,\n                 typename = typename std::enable_if<detail::is_iterator<InputIterator>::value>::type>\n        OutputIterator decrypt(InputIterator first, InputIterator last, KeyInputIterator key_first,\n                               KeyInputIterator key_last, OutputIterator out) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n            typedef typename block::accumulator_set<DecryptionMode> CipherAccumulator;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::itr_cipher_impl<StreamDecrypterImpl, OutputIterator> DecrypterImpl;\n\n            return DecrypterImpl(first, last, std::move(out),\n                                 CipherAccumulator(DecryptionMode(\n                                     BlockCipher(block::cipher_key<BlockCipher>(key_first, key_last).key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam InputIterator\n         * @tparam KeySinglePassRange\n         * @tparam OutputIterator\n         *\n         * @param first\n         * @param last\n         * @param key\n         * @param out\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename InputIterator, typename KeySinglePassRange, typename OutputIterator,\n                 typename = typename std::enable_if<detail::is_iterator<InputIterator>::value>::type>\n        OutputIterator decrypt(InputIterator first, InputIterator last, const KeySinglePassRange &key,\n                               OutputIterator out) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n            typedef typename block::accumulator_set<DecryptionMode> CipherAccumulator;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::itr_cipher_impl<StreamDecrypterImpl, OutputIterator> DecrypterImpl;\n\n            return DecrypterImpl(\n                first, last, std::move(out),\n                CipherAccumulator(DecryptionMode(BlockCipher(block::cipher_key<BlockCipher>(key).key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam InputIterator\n         * @tparam OutputIterator\n         *\n         * @param first\n         * @param last\n         * @param key\n         * @param out\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename InputIterator, typename OutputIterator,\n                 typename = typename std::enable_if<detail::is_iterator<InputIterator>::value>::type>\n        OutputIterator decrypt(InputIterator first, InputIterator last, const block::cipher_key<BlockCipher> &key,\n                               OutputIterator out) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n            typedef typename block::accumulator_set<DecryptionMode> CipherAccumulator;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::itr_cipher_impl<StreamDecrypterImpl, OutputIterator> DecrypterImpl;\n\n            return DecrypterImpl(first, last, std::move(out), CipherAccumulator(DecryptionMode(BlockCipher(key.key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam InputIterator\n         * @tparam OutputAccumulator\n         *\n         * @param first\n         * @param last\n         * @param acc\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename InputIterator,\n                 typename OutputAccumulator = typename block::accumulator_set<typename block::modes::isomorphic<\n                     BlockCipher, block::nop_padding>::template bind<block::decryption_policy<BlockCipher>>::type>,\n                 typename = typename std::enable_if<detail::is_iterator<InputIterator>::value>::type>\n        typename std::enable_if<boost::accumulators::detail::is_accumulator_set<OutputAccumulator>::value,\n                                OutputAccumulator>::type &\n            decrypt(InputIterator first, InputIterator last, OutputAccumulator &acc) {\n\n            typedef block::detail::ref_cipher_impl<OutputAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(first, last, std::forward<OutputAccumulator>(acc));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam SinglePassRange\n         * @tparam OutputAccumulator\n         *\n         * @param r\n         * @param acc\n         *\n         * @return\n         */\n\n        template<typename BlockCipher, typename SinglePassRange,\n                 typename OutputAccumulator = typename block::accumulator_set<\n                     typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                         typename block::modes::isomorphic<BlockCipher, block::nop_padding>::decryption_policy>::type>,\n                 typename = typename std::enable_if<detail::is_range<SinglePassRange>::value>::type>\n        typename std::enable_if<boost::accumulators::detail::is_accumulator_set<OutputAccumulator>::value,\n                                OutputAccumulator>::type &\n            decrypt(const SinglePassRange &r, OutputAccumulator &acc) {\n\n            typedef block::detail::ref_cipher_impl<OutputAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(r, acc);\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam InputIterator\n         * @tparam KeyIterator\n         * @tparam CipherAccumulator\n         *\n         * @param first\n         * @param last\n         * @param key_first\n         * @param key_last\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename InputIterator, typename KeyInputIterator,\n                 typename CipherAccumulator = typename block::accumulator_set<typename block::modes::isomorphic<\n                     BlockCipher, block::nop_padding>::template bind<block::decryption_policy<BlockCipher>>::type>,\n                 typename = typename std::enable_if<detail::is_iterator<InputIterator>::value>::type>\n        block::detail::range_cipher_impl<block::detail::value_cipher_impl<CipherAccumulator>>\n            decrypt(InputIterator first, InputIterator last, KeyInputIterator key_first, KeyInputIterator key_last) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(first, last,\n                                 CipherAccumulator(DecryptionMode(\n                                     BlockCipher(block::cipher_key<BlockCipher>(key_first, key_last).key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @tparam BlockCipher\n         * @tparam InputIterator\n         * @tparam KeySinglePassRange\n         * @tparam CipherAccumulator\n         *\n         * @param first\n         * @param last\n         * @param key\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename InputIterator, typename KeySinglePassRange,\n                 typename CipherAccumulator = typename block::accumulator_set<typename block::modes::isomorphic<\n                     BlockCipher, block::nop_padding>::template bind<block::decryption_policy<BlockCipher>>::type>,\n                 typename = typename std::enable_if<detail::is_iterator<InputIterator>::value>::type>\n        block::detail::range_cipher_impl<block::detail::value_cipher_impl<CipherAccumulator>>\n            decrypt(InputIterator first, InputIterator last, const KeySinglePassRange &key) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(\n                first, last, CipherAccumulator(DecryptionMode(BlockCipher(block::cipher_key<BlockCipher>(key).key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam InputIterator\n         * @tparam CipherAccumulator\n         * @param first\n         * @param last\n         * @param key\n         * @return\n         */\n        template<typename BlockCipher, typename InputIterator,\n                 typename CipherAccumulator = typename block::accumulator_set<typename block::modes::isomorphic<\n                     BlockCipher, block::nop_padding>::template bind<block::decryption_policy<BlockCipher>>::type>,\n                 typename = typename std::enable_if<detail::is_iterator<InputIterator>::value>::type>\n        block::detail::range_cipher_impl<block::detail::value_cipher_impl<CipherAccumulator>>\n            decrypt(InputIterator first, InputIterator last, const block::cipher_key<BlockCipher> &key) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(first, last, CipherAccumulator(DecryptionMode(BlockCipher(key.key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam SinglePassRange\n         * @tparam KeyRange\n         * @tparam OutputIterator\n         *\n         * @param rng\n         * @param key\n         * @param out\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename SinglePassRange, typename KeySinglePassRange, typename OutputIterator,\n                 typename = typename std::enable_if<detail::is_range<SinglePassRange>::value>::type>\n        OutputIterator decrypt(const SinglePassRange &rng, const KeySinglePassRange &key, OutputIterator out) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n            typedef typename block::accumulator_set<DecryptionMode> CipherAccumulator;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::itr_cipher_impl<StreamDecrypterImpl, OutputIterator> DecrypterImpl;\n\n            return DecrypterImpl(\n                rng, std::move(out),\n                CipherAccumulator(DecryptionMode(BlockCipher(block::cipher_key<BlockCipher>(key).key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam SinglePassRange\n         * @tparam OutputIterator\n         *\n         * @param rng\n         * @param key\n         * @param out\n         * @return\n         */\n        template<typename BlockCipher, typename SinglePassRange, typename OutputIterator,\n                 typename = typename std::enable_if<detail::is_range<SinglePassRange>::value>::type>\n        OutputIterator decrypt(const SinglePassRange &rng, const block::cipher_key<BlockCipher> &key,\n                               OutputIterator out) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n            typedef typename block::accumulator_set<DecryptionMode> CipherAccumulator;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::itr_cipher_impl<StreamDecrypterImpl, OutputIterator> DecrypterImpl;\n\n            return DecrypterImpl(rng, std::move(out), CipherAccumulator(DecryptionMode(BlockCipher(key.key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @tparam BlockCipher\n         * @tparam SinglePassRange\n         * @tparam KeySinglePassRange\n         * @tparam OutputRange\n         *\n         * @param rng\n         * @param key\n         * @param out\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename SinglePassRange, typename KeySinglePassRange, typename OutputRange,\n                 typename = typename std::enable_if<detail::is_range<SinglePassRange>::value>::type>\n        OutputRange &decrypt(const SinglePassRange &rng, const KeySinglePassRange &key, OutputRange &out) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n            typedef typename block::accumulator_set<DecryptionMode> CipherAccumulator;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(\n                rng, std::move(out),\n                CipherAccumulator(DecryptionMode(BlockCipher(block::cipher_key<BlockCipher>(key).key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam SinglePassRange\n         * @tparam OutputRange\n         * @param rng\n         * @param key\n         * @param out\n         * @return\n         */\n        template<typename BlockCipher, typename SinglePassRange, typename OutputRange,\n                 typename = typename std::enable_if<detail::is_range<SinglePassRange>::value>::type>\n        OutputRange &decrypt(const SinglePassRange &rng, const block::cipher_key<BlockCipher> &key, OutputRange &out) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n            typedef typename block::accumulator_set<DecryptionMode> CipherAccumulator;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(rng, std::move(out), CipherAccumulator(DecryptionMode(BlockCipher(key.key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam SinglePassRange\n         * @tparam KeyRange\n         * @tparam CipherAccumulator\n         *\n         * @param r\n         * @param key\n         *\n         * @return\n         */\n        template<typename BlockCipher, typename SinglePassRange, typename KeySinglePassRange,\n                 typename CipherAccumulator = typename block::accumulator_set<typename block::modes::isomorphic<\n                     BlockCipher, block::nop_padding>::template bind<block::decryption_policy<BlockCipher>>::type>,\n                 typename = typename std::enable_if<detail::is_range<SinglePassRange>::value>::type>\n        block::detail::range_cipher_impl<block::detail::value_cipher_impl<CipherAccumulator>>\n            decrypt(const SinglePassRange &r, const KeySinglePassRange &key) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(\n                r, CipherAccumulator(DecryptionMode(BlockCipher(block::cipher_key<BlockCipher>(key).key))));\n        }\n\n        /*!\n         * @brief\n         *\n         * @ingroup block_algorithms\n         *\n         * @tparam BlockCipher\n         * @tparam SinglePassRange\n         * @tparam CipherAccumulator\n         * @param r\n         * @param key\n         * @return\n         */\n        template<typename BlockCipher, typename SinglePassRange,\n                 typename CipherAccumulator = typename block::accumulator_set<typename block::modes::isomorphic<\n                     BlockCipher, block::nop_padding>::template bind<block::decryption_policy<BlockCipher>>::type>,\n                 typename = typename std::enable_if<detail::is_range<SinglePassRange>::value>::type>\n        block::detail::range_cipher_impl<block::detail::value_cipher_impl<CipherAccumulator>>\n            decrypt(const SinglePassRange &r, const block::cipher_key<BlockCipher> &key) {\n\n            typedef typename block::modes::isomorphic<BlockCipher, block::nop_padding>::template bind<\n                block::decryption_policy<BlockCipher>>::type DecryptionMode;\n\n            typedef block::detail::value_cipher_impl<CipherAccumulator> StreamDecrypterImpl;\n            typedef block::detail::range_cipher_impl<StreamDecrypterImpl> DecrypterImpl;\n\n            return DecrypterImpl(r, CipherAccumulator(DecryptionMode(BlockCipher(key.key))));\n        }\n    }    // namespace crypto3\n}    // namespace boost\n\n#endif    // include guard\n", "meta": {"hexsha": "63e4f11f0a482c10c941380a3f7a8ce3ed591741", "size": 19940, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/block/algorithm/decrypt.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/block/algorithm/decrypt.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/block/algorithm/decrypt.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": 42.8817204301, "max_line_length": 119, "alphanum_fraction": 0.6251755266, "num_tokens": 4096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1766465676791044}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <deque>\n#include <memory>\n#include <utility>\n\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"DataStructures/DataBox/PrefixHelpers.hpp\"\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/DataBox/Tag.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"DataStructures/VariablesTag.hpp\"\n#include \"Domain/LogicalCoordinates.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Evolution/DgSubcell/Actions/TciAndSwitchToDg.hpp\"\n#include \"Evolution/DgSubcell/ActiveGrid.hpp\"\n#include \"Evolution/DgSubcell/Mesh.hpp\"\n#include \"Evolution/DgSubcell/NeighborData.hpp\"\n#include \"Evolution/DgSubcell/Reconstruction.hpp\"\n#include \"Evolution/DgSubcell/SubcellOptions.hpp\"\n#include \"Evolution/DgSubcell/Tags/ActiveGrid.hpp\"\n#include \"Evolution/DgSubcell/Tags/DidRollback.hpp\"\n#include \"Evolution/DgSubcell/Tags/Inactive.hpp\"\n#include \"Evolution/DgSubcell/Tags/Mesh.hpp\"\n#include \"Evolution/DgSubcell/Tags/NeighborData.hpp\"\n#include \"Evolution/DgSubcell/Tags/SubcellOptions.hpp\"\n#include \"Evolution/DgSubcell/Tags/TciGridHistory.hpp\"\n#include \"Framework/ActionTesting.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Parallel/RegisterDerivedClassesWithCharm.hpp\"\n#include \"Time/History.hpp\"\n#include \"Time/Slab.hpp\"\n#include \"Time/Tags.hpp\"\n#include \"Time/Time.hpp\"\n#include \"Time/TimeStepId.hpp\"\n#include \"Time/TimeSteppers/AdamsBashforthN.hpp\"\n#include \"Time/TimeSteppers/RungeKutta3.hpp\"\n#include \"Time/TimeSteppers/TimeStepper.hpp\"\n#include \"Utilities/ErrorHandling/Error.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n#include \"Utilities/TaggedTuple.hpp\"\n\nnamespace {\nstruct Var1 : db::SimpleTag {\n  using type = Scalar<DataVector>;\n};\n\ntemplate <size_t Dim>\nstruct System {\n  static constexpr size_t volume_dim = Dim;\n  using variables_tag = Tags::Variables<tmpl::list<Var1>>;\n};\n\ntemplate <size_t Dim, typename Metavariables>\nstruct component {\n  using metavariables = Metavariables;\n  using chare_type = ActionTesting::MockArrayChare;\n  using array_index = size_t;\n\n  using initial_tags = tmpl::list<\n      ::Tags::TimeStepId, domain::Tags::Mesh<Dim>,\n      evolution::dg::subcell::Tags::Mesh<Dim>,\n      evolution::dg::subcell::Tags::ActiveGrid,\n      evolution::dg::subcell::Tags::DidRollback,\n      evolution::dg::subcell::Tags::NeighborDataForReconstructionAndRdmpTci<\n          Dim>,\n      evolution::dg::subcell::Tags::TciGridHistory,\n      Tags::Variables<tmpl::list<Var1>>,\n      evolution::dg::subcell::Tags::Inactive<Tags::Variables<tmpl::list<Var1>>>,\n      Tags::HistoryEvolvedVariables<Tags::Variables<tmpl::list<Var1>>>,\n      Tags::TimeStepper<TimeStepper>>;\n\n  using phase_dependent_action_list = tmpl::list<Parallel::PhaseActions<\n      typename Metavariables::Phase, Metavariables::Phase::Initialization,\n      tmpl::list<ActionTesting::InitializeDataBox<initial_tags>,\n                 evolution::dg::subcell::Actions::TciAndSwitchToDg<\n                     typename Metavariables::TciOnSubcellGrid>>>>;\n};\n\ntemplate <size_t Dim>\nstruct Metavariables {\n  static constexpr size_t volume_dim = Dim;\n  using component_list = tmpl::list<component<Dim, Metavariables>>;\n  using system = System<Dim>;\n  using analytic_variables_tags = typename system::variables_tag::tags_list;\n  using const_global_cache_tags =\n      tmpl::list<evolution::dg::subcell::Tags::SubcellOptions>;\n  enum class Phase { Initialization, Exit };\n\n  // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\n  static bool rdmp_fails;\n  // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\n  static bool tci_fails;\n  // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\n  static bool tci_invoked;\n\n  struct TciOnSubcellGrid {\n    using return_tags = tmpl::list<>;\n    using argument_tags =\n        tmpl::list<evolution::dg::subcell::Tags::Inactive<\n                       Tags::Variables<tmpl::list<Var1>>>,\n                   Tags::Variables<tmpl::list<Var1>>, domain::Tags::Mesh<Dim>>;\n\n    static bool apply(\n        const Variables<\n            tmpl::list<evolution::dg::subcell::Tags::Inactive<Var1>>>& dg_vars,\n        const Variables<tmpl::list<Var1>>& subcell_vars,\n        const Mesh<Dim>& dg_mesh, const double persson_exponent) noexcept {\n      Variables<tmpl::list<evolution::dg::subcell::Tags::Inactive<Var1>>>\n          reconstructed_dg_vars{dg_vars.number_of_grid_points()};\n      evolution::dg::subcell::fd::reconstruct(\n          make_not_null(&reconstructed_dg_vars), subcell_vars, dg_mesh,\n          evolution::dg::subcell::fd::mesh(dg_mesh).extents());\n      CHECK(reconstructed_dg_vars == dg_vars);\n      CHECK(approx(persson_exponent) == 5.0);  // Should be subcell_opts + 1\n      tci_invoked = true;\n      return tci_fails;\n    }\n  };\n};\n\ntemplate <size_t Dim>\n// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\nbool Metavariables<Dim>::rdmp_fails = false;\ntemplate <size_t Dim>\n// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\nbool Metavariables<Dim>::tci_fails = false;\ntemplate <size_t Dim>\n// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\nbool Metavariables<Dim>::tci_invoked = false;\n\nstd::unique_ptr<TimeStepper> make_time_stepper(\n    const bool multistep_time_stepper) {\n  if (multistep_time_stepper) {\n    return std::make_unique<TimeSteppers::AdamsBashforthN>(2);\n  } else {\n    return std::make_unique<TimeSteppers::RungeKutta3>();\n  }\n}\n\ntemplate <size_t Dim>\nvoid test_impl(const bool multistep_time_stepper, const bool rdmp_fails,\n               const bool tci_fails, const bool always_use_subcell,\n               const bool self_starting, const bool in_substep) {\n  CAPTURE(Dim);\n  CAPTURE(multistep_time_stepper);\n  CAPTURE(rdmp_fails);\n  CAPTURE(tci_fails);\n  CAPTURE(always_use_subcell);\n  CAPTURE(self_starting);\n  CAPTURE(in_substep);\n  if (in_substep and multistep_time_stepper) {\n    ERROR(\"Can't both be taking a substep and using a multistep time stepper\");\n  }\n\n  using metavars = Metavariables<Dim>;\n  metavars::rdmp_fails = rdmp_fails;\n  metavars::tci_fails = tci_fails;\n  metavars::tci_invoked = false;\n\n  using comp = component<Dim, metavars>;\n  using MockRuntimeSystem = ActionTesting::MockRuntimeSystem<metavars>;\n  MockRuntimeSystem runner{{evolution::dg::subcell::SubcellOptions{\n      1.0e-3, 1.0e-4, 2.0e-3, 2.0e-4, 4.0, 4.0, always_use_subcell}}};\n\n  TimeStepId time_step_id{true, self_starting ? -1 : 1,\n                          Time{Slab{1.0, 2.0}, {0, 10}}};\n  if (in_substep) {\n    // We are in the middle of a time step with a substep method, so update\n    // time_step_id to signal it is in a substep.\n    time_step_id = TimeStepId{true, 1, Time{Slab{1.0, 2.0}, {0, 10}}, 1,\n                              Time{Slab{1.0, 2.0}, {1, 10}}};\n  }\n  const Mesh<Dim> dg_mesh{5, Spectral::Basis::Legendre,\n                          Spectral::Quadrature::GaussLobatto};\n  const Mesh<Dim> subcell_mesh = evolution::dg::subcell::fd::mesh(dg_mesh);\n  const evolution::dg::subcell::ActiveGrid active_grid =\n      evolution::dg::subcell::ActiveGrid::Subcell;\n  const std::unique_ptr<TimeStepper> time_stepper =\n      make_time_stepper(multistep_time_stepper);\n\n  FixedHashMap<maximum_number_of_neighbors(Dim) + 1,\n               std::pair<Direction<Dim>, ElementId<Dim>>,\n               evolution::dg::subcell::NeighborData,\n               boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>\n      neighbor_data{};\n  const std::pair self_id{Direction<Dim>::lower_xi(),\n                          ElementId<Dim>::external_boundary_id()};\n  neighbor_data[self_id] = {};\n  // max and min of +-2 at last time level means reconstructed vars will be in\n  // limit\n  neighbor_data[self_id].max_variables_values.push_back(2.0);\n  neighbor_data[self_id].min_variables_values.push_back(-2.0);\n  std::deque<evolution::dg::subcell::ActiveGrid> tci_grid_history{};\n  for (size_t i = 0; i < time_stepper->order(); ++i) {\n    tci_grid_history.push_back(evolution::dg::subcell::ActiveGrid::Dg);\n  }\n\n  using evolved_vars_tags = tmpl::list<Var1>;\n  Variables<evolved_vars_tags> evolved_vars{\n      subcell_mesh.number_of_grid_points()};\n  // Set Var1 to the logical coords, since those are linear\n  get(get<Var1>(evolved_vars)) = get<0>(logical_coordinates(subcell_mesh));\n  if (rdmp_fails) {\n    get(get<Var1>(evolved_vars))[0] = 100.0;\n  }\n  const Variables<tmpl::list<evolution::dg::subcell::Tags::Inactive<Var1>>>\n      inactive_evolved_vars{dg_mesh.number_of_grid_points(), 1.0};\n  TimeSteppers::History<\n      Variables<evolved_vars_tags>,\n      Variables<db::wrap_tags_in<Tags::dt, evolved_vars_tags>>>\n      time_stepper_history{};\n  for (size_t i = 0; i < time_stepper->order(); ++i) {\n    Variables<evolved_vars_tags> vars{subcell_mesh.number_of_grid_points()};\n    get(get<Var1>(vars)) =\n        (i + 2.0) * get<0>(logical_coordinates(subcell_mesh));\n    Variables<db::wrap_tags_in<Tags::dt, evolved_vars_tags>> dt_vars{\n        subcell_mesh.number_of_grid_points()};\n    get(get<Tags::dt<Var1>>(dt_vars)) =\n        (i + 20.0) * get<0>(logical_coordinates(subcell_mesh));\n    time_stepper_history.insert(\n        {true, 1, Time{Slab{1.0, 2.0}, {static_cast<int>(5 - i), 10}}}, vars,\n        dt_vars);\n  }\n\n  ActionTesting::emplace_array_component_and_initialize<comp>(\n      &runner, ActionTesting::NodeId{0}, ActionTesting::LocalCoreId{0}, 0,\n      {time_step_id, dg_mesh, subcell_mesh, active_grid, true, neighbor_data,\n       tci_grid_history, evolved_vars, inactive_evolved_vars,\n       time_stepper_history, make_time_stepper(multistep_time_stepper)});\n\n  // Invoke the TciAndSwitchToDg action on the runner\n  ActionTesting::next_action<comp>(make_not_null(&runner), 0);\n\n  const auto active_grid_from_box =\n      ActionTesting::get_databox_tag<comp,\n                                     evolution::dg::subcell::Tags::ActiveGrid>(\n          runner, 0);\n  const auto& inactive_vars_from_box =\n      ActionTesting::get_databox_tag<comp,\n                                     evolution::dg::subcell::Tags::Inactive<\n                                         Tags::Variables<evolved_vars_tags>>>(\n          runner, 0);\n  const auto& active_vars_from_box =\n      ActionTesting::get_databox_tag<comp, Tags::Variables<evolved_vars_tags>>(\n          runner, 0);\n  const auto& time_stepper_history_from_box =\n      ActionTesting::get_databox_tag<comp, Tags::HistoryEvolvedVariables<>>(\n          runner, 0);\n  const auto& tci_grid_history_from_box = ActionTesting::get_databox_tag<\n      comp, evolution::dg::subcell::Tags::TciGridHistory>(runner, 0);\n  const auto& neighbor_data_from_box = ActionTesting::get_databox_tag<\n      comp, evolution::dg::subcell::Tags::\n                NeighborDataForReconstructionAndRdmpTci<Dim>>(runner, 0);\n\n  // true if the TCI wasn't invoked at all because we are always using subcell,\n  // doing self-start, or took a substep.\n  const bool avoid_tci =\n      always_use_subcell or self_starting or time_step_id.substep() != 0;\n\n  CHECK_FALSE(ActionTesting::get_databox_tag<\n              comp, evolution::dg::subcell::Tags::DidRollback>(runner, 0));\n\n  if (rdmp_fails or avoid_tci) {\n    // If the RDMP decided the cell is troubled, we shouldn't be checking the\n    // user-specified TCI\n    CHECK_FALSE(metavars::tci_invoked);\n  }\n\n  // Check ActiveGrid\n  if (avoid_tci or rdmp_fails or tci_fails) {\n    CHECK(active_grid_from_box == evolution::dg::subcell::ActiveGrid::Subcell);\n\n  } else {\n    CHECK(active_grid_from_box == evolution::dg::subcell::ActiveGrid::Dg);\n  }\n\n  if (avoid_tci) {\n    // Should not have reconstructed DG variables\n    CHECK(inactive_vars_from_box == inactive_evolved_vars);\n  } else {\n    auto reconstructed_dg_vars = inactive_evolved_vars;\n    evolution::dg::subcell::fd::reconstruct(\n        make_not_null(&reconstructed_dg_vars), evolved_vars, dg_mesh,\n        subcell_mesh.extents());\n    if (active_grid_from_box == evolution::dg::subcell::ActiveGrid::Subcell) {\n      CHECK(reconstructed_dg_vars == inactive_vars_from_box);\n    } else {\n      // Do swap because types are different\n      auto reconstructed_active_vars = evolved_vars;\n      swap(reconstructed_dg_vars, reconstructed_active_vars);\n      CHECK(reconstructed_active_vars == active_vars_from_box);\n    }\n  }\n\n  if (active_grid_from_box == evolution::dg::subcell::ActiveGrid::Dg) {\n    for (auto expected_it = time_stepper_history.cbegin(),\n              box_it = time_stepper_history_from_box.cbegin();\n         expected_it != time_stepper_history.end(); ++expected_it, ++box_it) {\n      CHECK(expected_it.time_step_id() == box_it.time_step_id());\n      CHECK(evolution::dg::subcell::fd::reconstruct(\n                expected_it.value(), dg_mesh, subcell_mesh.extents()) ==\n            box_it.value());\n      CHECK(evolution::dg::subcell::fd::reconstruct(\n                expected_it.derivative(), dg_mesh, subcell_mesh.extents()) ==\n            box_it.derivative());\n    }\n    CHECK(neighbor_data_from_box.empty());\n    CHECK(tci_grid_history_from_box.empty());\n  } else {\n    // TCI failed\n    for (auto expected_it = time_stepper_history.cbegin(),\n              box_it = time_stepper_history_from_box.cbegin();\n         expected_it != time_stepper_history.end(); ++expected_it, ++box_it) {\n      CHECK(expected_it.time_step_id() == box_it.time_step_id());\n      CHECK(expected_it.value() == box_it.value());\n      CHECK(expected_it.derivative() == box_it.derivative());\n    }\n    CHECK(neighbor_data_from_box.size() == 1);\n    CHECK(neighbor_data_from_box.count(self_id) == 1);\n    if (avoid_tci) {\n      CHECK(tci_grid_history_from_box.front() ==\n            evolution::dg::subcell::ActiveGrid::Dg);\n    } else if (multistep_time_stepper) {\n      CHECK(tci_grid_history_from_box.front() ==\n            evolution::dg::subcell::ActiveGrid::Subcell);\n    } else {\n      // substep time steppers don't need to keep track of the history right now\n      // because we restrict subcell to DG changes only on step boundaries.\n      CHECK(tci_grid_history_from_box.front() ==\n            evolution::dg::subcell::ActiveGrid::Dg);\n    }\n    if (multistep_time_stepper) {\n      CHECK(tci_grid_history_from_box.size() == time_stepper->order());\n    }\n  }\n}\n\ntemplate <size_t Dim>\nvoid test() {\n  for (const bool use_multistep_time_stepper : {true, false}) {\n    for (const bool rdmp_fails : {true, false}) {\n      for (const bool tci_fails : {false, true}) {\n        for (const bool always_use_subcell : {false, true}) {\n          for (const bool self_starting : {false, true}) {\n            test_impl<Dim>(use_multistep_time_stepper, rdmp_fails, tci_fails,\n                           always_use_subcell, self_starting, false);\n            if (not use_multistep_time_stepper) {\n              test_impl<Dim>(use_multistep_time_stepper, rdmp_fails, tci_fails,\n                             always_use_subcell, self_starting, true);\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nSPECTRE_TEST_CASE(\"Unit.Evolution.Subcell.Actions.TciAndSwitchToDg\",\n                  \"[Evolution][Unit]\") {\n  // 1. check that if we are in self-start nothing happens. This can be done by\n  //    verifying that the Inactive vars are untouched.\n  // 2. check if substep != 0, nothing happens. Check Inactive vars untouched.\n  // 3. Check if always_use_subcells, inactive vars are untouched.\n  // 4. Check if RDMP gets triggered, then tci_mutator is not called, and we\n  //    stay on subcell\n  // 5. Check if RDMP is not triggered, but tci_mutator is, we stay on subcell\n  // 6. check if RDMP & TCI not triggered, switch to DG.\n  Parallel::register_derived_classes_with_charm<TimeStepper>();\n  test<1>();\n  test<2>();\n  test<3>();\n}\n}  // namespace\n", "meta": {"hexsha": "17086467afce2db4c448e87b22970fb2a22b6198", "size": 16082, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Evolution/DgSubcell/Actions/Test_TciAndSwitchToDg.cpp", "max_stars_repo_name": "isha1810/spectre", "max_stars_repo_head_hexsha": "fc22b6cc9c64d7ebc7f6ffef3252056358673558", "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/Unit/Evolution/DgSubcell/Actions/Test_TciAndSwitchToDg.cpp", "max_issues_repo_name": "isha1810/spectre", "max_issues_repo_head_hexsha": "fc22b6cc9c64d7ebc7f6ffef3252056358673558", "max_issues_repo_licenses": ["MIT"], "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/Unit/Evolution/DgSubcell/Actions/Test_TciAndSwitchToDg.cpp", "max_forks_repo_name": "isha1810/spectre", "max_forks_repo_head_hexsha": "fc22b6cc9c64d7ebc7f6ffef3252056358673558", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 80, "alphanum_fraction": 0.6981718692, "num_tokens": 4321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.1766465629474691}}
{"text": "#include <limits>\n#include <string>\n#include <random>\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include <cassert>\n\nusing namespace std;\n\nstring randomString(const size_t size)\n{\n  string        data(size, 0);\n  random_device rd;\n  mt19937_64    prng( rd() );\n  using Byte = string::value_type;\n  std::uniform_int_distribution<Byte> dist( numeric_limits<Byte>::min(), numeric_limits<Byte>::max() );\n  for(auto& byte: data)\n    byte = dist(prng);\n  return data;\n}\n\n\nint main(int argc, const char **argv)\n{\n  if(argc!=2)\n  {\n    cerr<<argv[0]<<\" <size_in_MB>\"<<endl;\n    return 42;\n  }\n\n  constexpr size_t mb   = 1024*1024;\n  constexpr size_t size = 1*mb;\n  const     size_t count=boost::lexical_cast<size_t>(argv[1]);\n\n  const auto data = randomString(size);\n  assert( data.size() == size );\n\n  // output data proper number of times\n  for(size_t i=0; i<count; ++i)\n    cout.write( data.data(), data.size() );\n}\n", "meta": {"hexsha": "177290bd3b525b5a47cd7421dc80df1bfc957aed", "size": 922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rand_junk/repeated_data.cpp", "max_stars_repo_name": "el-bart/mini", "max_stars_repo_head_hexsha": "65877690f453dcae668f8a2f37a61319bb271ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-15T19:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-11T09:14:10.000Z", "max_issues_repo_path": "rand_junk/repeated_data.cpp", "max_issues_repo_name": "el-bart/mini", "max_issues_repo_head_hexsha": "65877690f453dcae668f8a2f37a61319bb271ee3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rand_junk/repeated_data.cpp", "max_forks_repo_name": "el-bart/mini", "max_forks_repo_head_hexsha": "65877690f453dcae668f8a2f37a61319bb271ee3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T12:33:46.000Z", "max_forks_repo_forks_event_max_datetime": "2015-02-05T12:33:46.000Z", "avg_line_length": 21.9523809524, "max_line_length": 103, "alphanum_fraction": 0.6561822126, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.17660771963230626}}
{"text": "#include <boost/predef.h>\n#if BOOST_OS_WINDOWS\n#if EXT_ENABLE_OPENSSL\n\n#include <winsock2.h>\n#include <windows.h>\n#include <wincrypt.h>\n\n// defined in wincrypt, conflicts with openssl\n#undef X509_NAME\n\n#include <fmt/core.h>\n\n#include <ext/wincrypt/utils.hpp>\n#include <ext/wincrypt/openssl.hpp>\n\n#include <openssl/evp.h>\n#include <openssl/x509.h>\n#include <openssl/err.h>\n#include <openssl/engine.h>\n\n#include <ext/codecvt_conv/generic_conv.hpp>\n#include <ext/codecvt_conv/wchar_cvt.hpp>\n\nnamespace ext::wincrypt\n{\n\tusing ext::codecvt_convert::wchar_cvt::to_utf8;\n\tusing ext::codecvt_convert::wchar_cvt::to_wchar;\n\t\n\t\n\tstatic std::string to_string(const ::BIGNUM * num)\n\t{\n\t\tauto * str = ::BN_bn2dec(num);\n\t\tstd::string result = str;\n\t\t::OPENSSL_free(str);\n\t\treturn result;\n\t}\n\n\tstatic std::wstring to_wstring(const ::BIGNUM * num)\n\t{\n\t\tauto * str = ::BN_bn2dec(num);\n\t\tauto result = to_wchar(str);\n\t\t::OPENSSL_free(str);\n\t\treturn result;\n\t}\n\n\tstd::string integer_string(const ::CRYPT_INTEGER_BLOB * num)\n\t{\n\t\t// use openssl to print big integer as decimal.\n\t\t// openssl BIGNUM can be create from binary big-endian octet stream,\n\t\t// but CRYPT_INTEGER_BLOB is little-endian octet stream\n\t\tstd::vector<unsigned char> num_data(num->pbData, num->pbData + num->cbData);\n\t\tstd::reverse(num_data.begin(), num_data.end());\n\n\t\text::openssl::bignum_uptr bn(::BN_bin2bn(num_data.data(), num_data.size(), nullptr));\n\t\tauto result = to_string(bn.get());\n\t\treturn result;\n\t}\n\n\tstd::wstring integer_wstring(const ::CRYPT_INTEGER_BLOB * num)\n\t{\n\t\t// use openssl to print big integer as decimal.\n\t\t// openssl BIGNUM can be create from binary big-endian octet stream,\n\t\t// but CRYPT_INTEGER_BLOB is little-endian octet stream\n\t\tstd::vector<unsigned char> num_data(num->pbData, num->pbData + num->cbData);\n\t\tstd::reverse(num_data.begin(), num_data.end());\n\n\t\text::openssl::bignum_uptr bn(::BN_bin2bn(num_data.data(), num_data.size(), nullptr));\n\t\tauto result = to_wstring(bn.get());\n\t\treturn result;\n\t}\n\t\n\t\n\text::openssl::x509_iptr create_openssl_cert(const ::CERT_CONTEXT * wincert)\n\t{\n\t\tusing namespace ext::openssl;\n\t\tx509_iptr x509_ptr;\n\t\t\n\t\tauto * cert_blob_ptr = reinterpret_cast<const unsigned char *>(wincert->pbCertEncoded);\n\t\tauto * cert = ::d2i_X509(nullptr, &cert_blob_ptr, wincert->cbCertEncoded);\n\t\tif (not cert) throw_last_error(\"ext::wincrypt::create_openssl_cert: d2i_X509 for wincert blob failed\");\n\t\tx509_ptr.reset(cert, ext::noaddref);\n\t\t\n\t\treturn x509_ptr;\n\t}\n\t\n\tcert_iptr create_wincrypt_cert(::X509 * cert)\n\t{\n\t\tauto pem = ext::openssl::write_certificate(cert);\n\t\treturn ext::wincrypt::load_certificate(pem);\n\t}\n\t\n\tstd::vector<unsigned char> create_rsa_public_blob(::RSA * rsa)\n\t{\n\t\tusing ext::openssl::throw_last_error;\n\t\t// RSA public blob:\n\t\t//   PUBLICKEYSTRUC  publickeystruc;\n\t\t//   RSAPUBKEY rsapubkey;\n\t\t//   BYTE modulus[rsapubkey.bitlen/8];\n\t\t// \n\t\tauto * modulus          = ::RSA_get0_n(rsa);\n\t\tauto * public_exponent  = ::RSA_get0_e(rsa);\n\t\t\n\t\tauto rsa_version = ::RSA_get_version(rsa);\n\t\tauto rsa_size    = ::RSA_size(rsa);\n\t\tauto bitlen      = rsa_size * 8;\n\t\t\n\t\tif (rsa_version != RSA_ASN1_VERSION_DEFAULT)\n\t\t\tthrow std::runtime_error(\"ext::wincrypt::create_rsa_public_blob: Only RSA_ASN1_VERSION_DEFAULT supported(regular 2 prime keys, not multiprime)\");\n\t\n\t\tassert(rsa_size % 8 == 0);\n\t\t\n\t\tauto blobsize = sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY)\n\t\t        + bitlen / 8;   // modulus\n\t\t\n\t\tstd::vector<unsigned char> blob_buffer;\n\t\tblob_buffer.resize(blobsize);\n\t\tauto * ptr = blob_buffer.data();\n\t\t\n\t\tauto * blobhdr = reinterpret_cast<::PUBLICKEYSTRUC *>(ptr);\n\t\tauto * rsapub  = reinterpret_cast<::RSAPUBKEY * >(ptr + sizeof(::PUBLICKEYSTRUC));\n\t\t\n\t\tblobhdr->bType = PUBLICKEYBLOB;\n\t\tblobhdr->bVersion = CUR_BLOB_VERSION;\n\t\tblobhdr->reserved = 0;\n\t\tblobhdr->aiKeyAlg = CALG_RSA_KEYX;\n\t\t\n\t\trsapub->magic = 0x32415352; // RSA2 in ASCII\n\t\trsapub->bitlen = bitlen;\n\t\trsapub->pubexp = ::BN_get_word(public_exponent);\n\t\tassert(rsapub->pubexp != -1);\n\t\t\n\t\tauto * modulus_ptr = ptr += sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY);\n\t\t\n\t\tint res;\n\t\tres = ::BN_bn2lebinpad(modulus, modulus_ptr, bitlen / 8);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_rsa_public_blob: ::BN_bn2lebinpad failed for modulus\");\n\t\t\n\t\treturn blob_buffer;\n\t}\n\t\n\tstd::vector<unsigned char> create_rsa_private_blob(::RSA * rsa)\n\t{\n\t\tusing ext::openssl::throw_last_error;\n\t\t// CryptImportKey can import private keys, for RSA/DSA/DH it's expects a blob described in following man pages\n\t\t// \n\t\t// DH/DSS\n\t\t// https://docs.microsoft.com/en-us/windows/win32/seccrypto/dss-version-3-private-key-blobs\n\t\t// https://docs.microsoft.com/en-us/windows/win32/seccrypto/diffie-hellman-version-3-private-key-blobs\n\t\t// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-dhprivkey_ver3\n\t\t// \n\t\t// RSA\n\t\t// https://docs.microsoft.com/en-us/windows/win32/seccrypto/microsoft-cryptographic-service-providers\n\t\t// https://docs.microsoft.com/en-us/windows/win32/seccrypto/base-provider-key-blobs\n\t\t// https://docs.microsoft.com/en-us/windows/win32/seccrypto/enhanced-provider-key-blobs\n\t\t// \n\t\t// RSA private blob:\n\t\t//   PUBLICKEYSTRUC  publickeystruc;\n\t\t//   RSAPUBKEY rsapubkey;\n\t\t//   BYTE modulus          [rsapubkey.bitlen/8];\n\t\t//   BYTE prime1           [rsapubkey.bitlen/16];\n\t\t//   BYTE prime2           [rsapubkey.bitlen/16];\n\t\t//   BYTE exponent1        [rsapubkey.bitlen/16];\n\t\t//   BYTE exponent2        [rsapubkey.bitlen/16];\n\t\t//   BYTE coefficient      [rsapubkey.bitlen/16];\n\t\t//   BYTE privateExponent  [rsapubkey.bitlen/8];\n\t\t\n\t\tauto * modulus          = ::RSA_get0_n(rsa);\n\t\tauto * public_exponent  = ::RSA_get0_e(rsa);\n\t\tauto * private_exponent = ::RSA_get0_d(rsa);\n\t\tauto * prime1           = ::RSA_get0_p(rsa);\n\t\tauto * prime2           = ::RSA_get0_q(rsa);\n\t\tauto * exponent1        = ::RSA_get0_dmp1(rsa);\n\t\tauto * exponent2        = ::RSA_get0_dmq1(rsa);\n\t\tauto * coefficient      = ::RSA_get0_iqmp(rsa);\n\t\t\n\t\tauto rsa_version = ::RSA_get_version(rsa);\n\t\tauto rsa_size    = ::RSA_size(rsa);\n\t\tauto bitlen      = rsa_size * 8;\n\t\t\n\t\tif (rsa_version != RSA_ASN1_VERSION_DEFAULT)\n\t\t\tthrow std::runtime_error(\"ext::wincrypt::create_rsa_private_blob: Only RSA_ASN1_VERSION_DEFAULT supported(regular 2 prime keys, not multiprime)\");\n\t\n\t\tassert(rsa_size % 8 == 0);\n\t\t\n\t\tauto blobsize = sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY)\n\t\t        + bitlen / 8   // modulus\n\t\t        + bitlen / 16  // prime1\n\t\t        + bitlen / 16  // prime2\n\t\t        + bitlen / 16  // exponent1\n\t\t        + bitlen / 16  // exponent2\n\t\t        + bitlen / 16  // coefficient\n\t\t        + bitlen / 8   // privateExponent\n\t\t        ;\n\t\t\n\t\tstd::vector<unsigned char> blob_buffer;\n\t\tblob_buffer.resize(blobsize);\n\t\tauto * ptr = blob_buffer.data();\n\t\t\n\t\tauto * blobhdr = reinterpret_cast<::PUBLICKEYSTRUC *>(ptr);\n\t\tauto * rsapub  = reinterpret_cast<::RSAPUBKEY * >(ptr + sizeof(::PUBLICKEYSTRUC));\n\t\t\n\t\tblobhdr->bType = PRIVATEKEYBLOB;\n\t\tblobhdr->bVersion = CUR_BLOB_VERSION;\n\t\tblobhdr->reserved = 0;\n\t\tblobhdr->aiKeyAlg = CALG_RSA_KEYX;\n\t\t\n\t\trsapub->magic = 0x32415352; // RSA2 in ASCII\n\t\trsapub->bitlen = bitlen;\n\t\trsapub->pubexp = ::BN_get_word(public_exponent);\n\t\tassert(rsapub->pubexp != -1);\n\t\t\n\t\tauto * modulus_ptr          = ptr += sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY);\n\t\tauto * prime1_ptr           = ptr += bitlen / 8;\n\t\tauto * prime2_ptr           = ptr += bitlen / 16;\n\t\tauto * exponent1_ptr        = ptr += bitlen / 16;\n\t\tauto * exponent2_ptr        = ptr += bitlen / 16;\n\t\tauto * coefficient_ptr      = ptr += bitlen / 16;\n\t\tauto * private_exponent_ptr = ptr += bitlen / 16;\n\t\t\n\t\tint res;\n\t\tres = ::BN_bn2lebinpad(modulus,          modulus_ptr,          bitlen / 8);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_rsa_private_blob: ::BN_bn2lebinpad failed for modulus\");\n\t\t\n\t\tres = ::BN_bn2lebinpad(prime1,           prime1_ptr,           bitlen / 16);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_rsa_private_blob: ::BN_bn2lebinpad failed for prime1\");\n\t\t\n\t\tres = ::BN_bn2lebinpad(prime2,           prime2_ptr,           bitlen / 16);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_rsa_private_blob: ::BN_bn2lebinpad failed for prime2\");\n\t\t\n\t\tres = ::BN_bn2lebinpad(exponent1,        exponent1_ptr,        bitlen / 16);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_rsa_private_blob: ::BN_bn2lebinpad failed for exponent1\");\n\t\t\n\t\tres = ::BN_bn2lebinpad(exponent2,        exponent2_ptr,        bitlen / 16);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_rsa_private_blob: ::BN_bn2lebinpad failed for exponent2\");\n\t\t\n\t\tres = ::BN_bn2lebinpad(coefficient,      coefficient_ptr,      bitlen / 16);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_rsa_private_blob: ::BN_bn2lebinpad failed for coefficient\");\n\t\t\n\t\tres = ::BN_bn2lebinpad(private_exponent, private_exponent_ptr, bitlen / 8);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_rsa_private_blob: ::BN_bn2lebinpad failed for private_exponent\");\n\t\t\n\t\t\n\t\treturn blob_buffer;\n\t}\n\n\tstd::vector<unsigned char> create_wincrypt_public_blob(::EVP_PKEY * pkey)\n\t{\n\t\tint type = ::EVP_PKEY_base_id(pkey); // can return EVP_PKEY_RSA/EVP_PKEY_RSA2, EVP_PKEY_DSA1, EVP_PKEY_RSA2, ...\n\t\ttype = ::EVP_PKEY_type(type);        // more like family, EVP_PKEY_RSA2 -> EVP_PKEY_RSA, EVP_PKEY_DSA2 -> EVP_PKEY_DSA, etc\n\t\t\n\t\tif (type != EVP_PKEY_RSA)\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_wincrypt_public_blob: only EVP_PKEY_RSA is supported, was = {}\", type));\n\t\t\n\t\tauto * rsa = ::EVP_PKEY_get0_RSA(pkey);\n\t\treturn create_rsa_public_blob(rsa);\n\t}\n\t\n\tstd::vector<unsigned char> create_wincrypt_private_blob(::EVP_PKEY * pkey)\n\t{\n\t\tint type = ::EVP_PKEY_base_id(pkey); // can return EVP_PKEY_RSA/EVP_PKEY_RSA2, EVP_PKEY_DSA1, EVP_PKEY_RSA2, ...\n\t\ttype = ::EVP_PKEY_type(type);        // more like family, EVP_PKEY_RSA2 -> EVP_PKEY_RSA, EVP_PKEY_DSA2 -> EVP_PKEY_DSA, etc\n\t\t\n\t\tif (type != EVP_PKEY_RSA)\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_wincrypt_private_blob: only EVP_PKEY_RSA is supported, was = {}\", type));\n\t\t\n\t\tauto * rsa = ::EVP_PKEY_get0_RSA(pkey);\n\t\treturn create_rsa_private_blob(rsa);\n\t}\n\t\n\text::openssl::rsa_iptr create_openssl_rsa_publickey(const unsigned char * data, std::size_t datalen)\n\t{\n\t\tif (datalen < sizeof(::PUBLICKEYSTRUC))\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_openssl_rsa_publickey: sizeof blob < PUBLICKEYSTRUC({} < {})\", datalen, sizeof(::PUBLICKEYSTRUC)));\n\n\t\tif (datalen < sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY))\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_openssl_rsa_publickey: sizeof blob < PUBLICKEYSTRUC + RSAPUBKEY({} < {})\", datalen, sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY)));\n\t\t\n\t\tauto * blobhdr = reinterpret_cast<const ::PUBLICKEYSTRUC *>(data);\n\t\tauto * rsapub  = reinterpret_cast<const ::RSAPUBKEY *>(data + sizeof(::PUBLICKEYSTRUC));\n\t\t\n\t\tif(blobhdr->bType != PUBLICKEYBLOB)\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_openssl_rsa_publickey: expected PUBLICKEYBLOB, was = {}\", blobhdr->bType));\n\t\t\n\t\tassert(blobhdr->bVersion == CUR_BLOB_VERSION);\n\t\tassert(blobhdr->aiKeyAlg == CALG_RSA_KEYX);\n\t\t\n\t\tauto bitlen = rsapub->bitlen;\n\t\t\n\t\tauto expected_blobsize = sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY)\n\t\t        + bitlen / 8;  // modulus\n\t\t\n\t\tif (datalen < expected_blobsize)\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_openssl_rsa_publickey: wrong private blob size, was = {}, expected = {}\", datalen, expected_blobsize));\n\t\t\n\t\tauto * ptr = data;\n\t\tauto * modulus_ptr          = ptr += sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY);\n\t\t\n\t\tint res;\n\t\tconst char * errmsg;\n\t\t::BIGNUM * public_exponent, * modulus;\n\t\t::RSA * rsa;\n\t\t\n\t\tpublic_exponent = modulus = nullptr;\n\t\trsa = nullptr;\n\t\t\n\t\tpublic_exponent = ::BN_new();\n\t\tif (not public_exponent) { errmsg = \"ext::wincrypt::create_openssl_rsa_publickey: ::BN_new failed for public_exponent creation\"; goto error; }\n\t\t::BN_set_word(public_exponent, rsapub->pubexp);\n\t\t\n\t\tmodulus = ::BN_lebin2bn(modulus_ptr, bitlen / 8,  nullptr);\n\t\tif (not modulus) { errmsg = \"ext::wincrypt::create_openssl_rsa_publickey: ::BN_lebin2bn failed for modulus creation\"; goto error; }\n\t\t\n\t\trsa = ::RSA_new();\n\t\tif (not rsa) { errmsg = \"ext::wincrypt::create_openssl_rsa_publickey: ::RSA_new failed\"; goto error; }\n\t\t\n\t\tres = ::RSA_set0_key(rsa, modulus, public_exponent, nullptr);\n\t\tmodulus = public_exponent = nullptr;\n\t\tif (not res) { errmsg = \"ext::wincrypt::create_openssl_rsa_publickey: ::RSA_set0_key failed\"; goto error; }\n\t\t\n\t\treturn ext::openssl::rsa_iptr(rsa, ext::noaddref);\n\t\t\n\terror:\n\t\t::RSA_free(rsa);\n\t\t::BN_clear_free(modulus);\n\t\t::BN_clear_free(public_exponent);\n\t\t\n\t\tauto errc = ext::openssl::last_error();\n\t\tthrow std::system_error(errc, errmsg);\n\t}\n\t\n\text::openssl::rsa_iptr create_openssl_rsa_privatekey(const unsigned char * data, std::size_t datalen)\n\t{\n\t\tif (datalen < sizeof(::PUBLICKEYSTRUC))\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_openssl_rsa_privatekey: sizeof blob < PUBLICKEYSTRUC({} < {})\", datalen, sizeof(::PUBLICKEYSTRUC)));\n\n\t\tif (datalen < sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY))\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_openssl_rsa_privatekey: sizeof blob < PUBLICKEYSTRUC + RSAPUBKEY({} < {})\", datalen, sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY)));\n\t\t\n\t\tauto * blobhdr = reinterpret_cast<const ::PUBLICKEYSTRUC *>(data);\n\t\tauto * rsapub  = reinterpret_cast<const ::RSAPUBKEY *>(data + sizeof(::PUBLICKEYSTRUC));\n\t\t\n\t\tif(blobhdr->bType != PRIVATEKEYBLOB)\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_openssl_rsa_privatekey: expected PRIVATEKEYBLOB, was = {}\", blobhdr->bType));\n\t\t\n\t\tassert(blobhdr->bVersion == CUR_BLOB_VERSION);\n\t\tassert(blobhdr->aiKeyAlg == CALG_RSA_KEYX);\n\t\t\n\t\tauto bitlen = rsapub->bitlen;\n\t\t\n\t\tauto expected_blobsize = sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY)\n\t\t        + bitlen / 8   // modulus\n\t\t        + bitlen / 16  // prime1\n\t\t        + bitlen / 16  // prime2\n\t\t        + bitlen / 16  // exponent1\n\t\t        + bitlen / 16  // exponent2\n\t\t        + bitlen / 16  // coefficient\n\t\t        + bitlen / 8   // privateExponent\n\t\t        ;\n\t\t\n\t\tif (datalen < expected_blobsize)\n\t\t\tthrow std::runtime_error(fmt::format(\"ext::wincrypt::create_openssl_rsa_privatekey: wrong private blob size, was = {}, expected = {}\", datalen, expected_blobsize));\n\t\t\n\t\tauto * ptr = data;\n\t\tauto * modulus_ptr          = ptr += sizeof(::PUBLICKEYSTRUC) + sizeof(::RSAPUBKEY);\n\t\tauto * prime1_ptr           = ptr += bitlen / 8;\n\t\tauto * prime2_ptr           = ptr += bitlen / 16;\n\t\tauto * exponent1_ptr        = ptr += bitlen / 16;\n\t\tauto * exponent2_ptr        = ptr += bitlen / 16;\n\t\tauto * coefficient_ptr      = ptr += bitlen / 16;\n\t\tauto * private_exponent_ptr = ptr += bitlen / 16;\n\t\t\n\t\t\n\t\tint res;\n\t\tconst char * errmsg;\n\t\t::BIGNUM * public_exponent, * modulus, * prime1, * prime2, * exponent1, * exponent2, * coefficient, * private_exponent;\n\t\t::RSA * rsa;\n\t\t\n\t\tpublic_exponent = modulus = prime1 = prime2 = exponent1 = exponent2 = coefficient = private_exponent = nullptr;\n\t\trsa = nullptr;\n\t\t\n\t\tpublic_exponent = ::BN_new();\n\t\tif (not public_exponent) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::BN_new failed for public_exponent creation\"; goto error; }\n\t\t::BN_set_word(public_exponent, rsapub->pubexp);\n\t\t\n\t\tmodulus = ::BN_lebin2bn(modulus_ptr, bitlen / 8,  nullptr);\n\t\tif (not modulus) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::BN_lebin2bn failed for modulus creation\"; goto error; }\n\t\t\n\t\tprime1 = ::BN_lebin2bn(prime1_ptr, bitlen / 16, nullptr);\n\t\tif (not prime1) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::BN_lebin2bn failed for prime1 creation\"; goto error; }\n\t\t\n\t\tprime2 = ::BN_lebin2bn(prime2_ptr, bitlen / 16, nullptr);\n\t\tif (not prime2) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::BN_lebin2bn failed for prime2 creation\"; goto error; }\n\t\t\n\t\texponent1 = ::BN_lebin2bn(exponent1_ptr, bitlen / 16, nullptr);\n\t\tif (not exponent1) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::BN_lebin2bn failed for exponent1 creation\"; goto error; }\n\t\t\n\t\texponent2 = ::BN_lebin2bn(exponent2_ptr, bitlen / 16, nullptr);\n\t\tif (not exponent2) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::BN_lebin2bn failed for exponent2 creation\"; goto error; }\n\t\t\n\t\tcoefficient = ::BN_lebin2bn(coefficient_ptr, bitlen / 16, nullptr);\n\t\tif (not coefficient) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::BN_lebin2bn failed for coefficient creation\"; goto error; }\n\t\t\n\t\tprivate_exponent = ::BN_lebin2bn(private_exponent_ptr, bitlen / 8,  nullptr);\n\t\tif (not private_exponent) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::BN_lebin2bn failed for private_exponent creation\"; goto error;  }\n\t\t\n\t\t\n\t\t\n\t\trsa = ::RSA_new();\n\t\tif (not rsa) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::RSA_new failed\"; goto error; }\n\t\t\n\t\tres = ::RSA_set0_key(rsa, modulus, public_exponent, private_exponent);\n\t\tmodulus = public_exponent = private_exponent = nullptr;\n\t\tif (not res) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::RSA_set0_key failed\"; goto error; }\n\t\t\n\t\tres = ::RSA_set0_factors(rsa, prime1, prime2);\n\t\tprime1 = prime2 = nullptr;\n\t\tif (not res) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::RSA_set0_factors failed\"; goto error; }\n\t\t\n\t\tres = ::RSA_set0_crt_params(rsa, exponent1, exponent2, coefficient);\n\t\texponent1 = exponent2 = coefficient = nullptr;\n\t\tif (not res) { errmsg = \"ext::wincrypt::create_openssl_rsa_privatekey: ::RSA_set0_crt_params failed\"; goto error; }\n\t\t\n\t\treturn ext::openssl::rsa_iptr(rsa, ext::noaddref);\n\t\t\n\terror:\n\t\t::RSA_free(rsa);\n\t\t::BN_clear_free(private_exponent);\n\t\t::BN_clear_free(coefficient);\n\t\t::BN_clear_free(exponent2);\n\t\t::BN_clear_free(exponent1);\n\t\t::BN_clear_free(prime2);\n\t\t::BN_clear_free(prime1);\n\t\t::BN_clear_free(modulus);\n\t\t::BN_clear_free(public_exponent);\n\t\t\n\t\tauto errc = ext::openssl::last_error();\n\t\tthrow std::system_error(errc, errmsg);\n\t}\n\t\n\text::openssl::evp_pkey_iptr create_openssl_publickey(::HCRYPTPROV prov, unsigned keyspec)\n\t{\n\t\tauto hkey = get_user_key(prov, keyspec);\n\t\tauto blob = export_public_key(*hkey);\n\t\tauto rsa_uptr = create_openssl_rsa_publickey(blob);\n\t\t\n\t\tauto pkey = ::EVP_PKEY_new();\n\t\tif (not pkey) ext::openssl::throw_last_error(\"ext::wincrypt::create_openssl_publickey: ::EVP_PKEY_new failed\");\n\t\t\n\t\text::openssl::evp_pkey_iptr pkey_iptr(pkey, ext::noaddref);\n\t\tauto res = ::EVP_PKEY_assign_RSA(pkey, rsa_uptr.release());\n\t\tif (not res) ext::openssl::throw_last_error(\"ext::wincrypt::create_openssl_publickey: ::EVP_PKEY_assign_RSA failed\");\n\t\t\n\t\treturn pkey_iptr;\n\t}\n\t\n\text::openssl::evp_pkey_iptr create_openssl_privatekey(::HCRYPTPROV prov, unsigned keyspec)\n\t{\n\t\tauto hkey = get_user_key(prov, keyspec);\n\t\tauto blob = export_private_key(*hkey);\n\t\tauto rsa_uptr = create_openssl_rsa_privatekey(blob);\n\t\t\n\t\tauto pkey = ::EVP_PKEY_new();\n\t\tif (not pkey) ext::openssl::throw_last_error(\"ext::wincrypt::create_openssl_privatekey: ::EVP_PKEY_new failed\");\n\t\t\n\t\text::openssl::evp_pkey_iptr pkey_iptr(pkey, ext::noaddref);\n\t\tauto res = ::EVP_PKEY_assign_RSA(pkey, rsa_uptr.release());\n\t\tif (not res) ext::openssl::throw_last_error(\"ext::wincrypt::create_openssl_privatekey: ::EVP_PKEY_assign_RSA failed\");\n\t\t\n\t\treturn pkey_iptr;\n\t}\n\t\n\tauto create_capi_openssl_privatekey(const ::CERT_CONTEXT * wincert)\n\t\t-> std::tuple<ext::openssl::x509_iptr, ext::openssl::evp_pkey_iptr>\n\t{\n\t\tauto info = ext::wincrypt::get_provider_info(wincert);\n\t\treturn create_capi_openssl_privatekey(wincert, info.get());\n\t}\n\t\n\tauto create_capi_openssl_privatekey(const ::CERT_CONTEXT * wincert, const ::CRYPT_KEY_PROV_INFO * info)\n\t\t-> std::tuple<ext::openssl::x509_iptr, ext::openssl::evp_pkey_iptr>\n\t{\n\t\tusing namespace ext::openssl;\n\t\t\n\t\tx509_iptr x509_ptr;\n\t\tevp_pkey_iptr evp_ptr;\n\t\tint res;\n\t\t\n\t\tauto cont_name = to_utf8(info->pwszContainerName);\n\t\tauto prov_name = to_utf8(info->pwszProvName);\n\t\t\n\t\tauto * cert_blob_ptr = reinterpret_cast<const unsigned char *>(wincert->pbCertEncoded);\n\t\tauto * cert = ::d2i_X509(nullptr, &cert_blob_ptr, wincert->cbCertEncoded);\n\t\tif (not cert) throw_last_error(\"ext::wincrypt::create_capi_openssl_privatekey: d2i_X509 for wincert blob failed\");\n\t\tx509_ptr.reset(cert, ext::noaddref);\n\t\t\n\t\tENGINE * capi = ::ENGINE_by_id(\"capi\");\n\t\tif (not capi) throw_last_error(\"ext::wincrypt::create_capi_openssl_privatekey: ENGINE_by_id(\\\"capi\\\") failed\");\n\t\t\n\t\t// Set key lookup method (1=substring, 2=friendlyname, 3=container name)\n\t\tres = ::ENGINE_ctrl_cmd(capi, \"lookup_method\", 3, nullptr, nullptr, 0);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_capi_openssl_privatekey: ENGINE_ctrl_cmd/lookup_method=3 failed\");\n\t\t// Set CSP name, (default CSP used if not specified)\n\t\tres = ::ENGINE_ctrl_cmd(capi, \"csp_name\", 0, prov_name.data(), nullptr, 0);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_capi_openssl_privatekey: ENGINE_ctrl_cmd/csp_name failed\");\n\t\t// Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE\n\t\tres = ::ENGINE_ctrl_cmd(capi, \"key_type\", info->dwKeySpec, nullptr, nullptr, 0);\n\t\tif (not res) throw_last_error(\"ext::wincrypt::create_capi_openssl_privatekey: ENGINE_ctrl_cmd/key_type failed\");\n\t\t\n\t\t// ENGINE_load_private_key accepts something to lookup key,\n\t\t// how is interpreted depends on lookup_method cmd, and we set it to 3=container name, so pass it\n\t\tauto * evp_pkey = ::ENGINE_load_private_key(capi, cont_name.c_str(),  nullptr, nullptr);\n\t\tif (not evp_pkey) throw_last_error(\"ext::wincrypt::create_capi_openssl_privatekey: ENGINE_load_private_key failed\");\n\t\t\n\t\tevp_ptr.reset(evp_pkey, ext::noaddref);\n\t\t\n\t\treturn std::make_tuple(std::move(x509_ptr), std::move(evp_ptr));\n\t}\n}\n\n#endif // EXT_ENABLE_OPENSSL\n#endif // BOOST_OS_WINDOWS\n", "meta": {"hexsha": "ca35451882d3ff0fce52f5c2c11933f0ab10f748", "size": 21863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openssl.cpp", "max_stars_repo_name": "dmlys/wincrypt-utils", "max_stars_repo_head_hexsha": "c9e7d8fe10b6784636b588c88d91777cbb65637f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-26T13:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T13:28:18.000Z", "max_issues_repo_path": "src/openssl.cpp", "max_issues_repo_name": "dmlys/wincrypt-utils", "max_issues_repo_head_hexsha": "c9e7d8fe10b6784636b588c88d91777cbb65637f", "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/openssl.cpp", "max_forks_repo_name": "dmlys/wincrypt-utils", "max_forks_repo_head_hexsha": "c9e7d8fe10b6784636b588c88d91777cbb65637f", "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.8030592734, "max_line_length": 197, "alphanum_fraction": 0.7004528198, "num_tokens": 6643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.17660771255491237}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"weights.h\"\n#include \"rule_lexer.h\"\n#include \"trule.h\"\n#include \"filelib.h\"\n#include \"tdict.h\"\n#include \"lm/model.hh\"\n#include \"lm/enumerate_vocab.hh\"\n#include \"wordid.h\"\n\nnamespace po = boost::program_options;\nusing namespace std;\n\nvector<lm::WordIndex> word_map;\nlm::ngram::ProbingModel* ngram;\nstruct VMapper : public lm::EnumerateVocab {\n  VMapper(vector<lm::WordIndex>* out) : out_(out), kLM_UNKNOWN_TOKEN(0) { out_->clear(); }\n  void Add(lm::WordIndex index, const StringPiece &str) {\n    const WordID cdec_id = TD::Convert(str.as_string());\n    if (cdec_id >= out_->size())\n      out_->resize(cdec_id + 1, kLM_UNKNOWN_TOKEN);\n    (*out_)[cdec_id] = index;\n  }\n  vector<lm::WordIndex>* out_;\n  const lm::WordIndex kLM_UNKNOWN_TOKEN;\n};\n\nbool InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"source_lm,l\",po::value<string>(),\"Source language LM (KLM)\")\n        (\"collapse_weights,w\",po::value<string>(), \"Collapse weights into a single feature X using the coefficients from this weights file\")\n        (\"clear_features_after_collapse,c\", \"After collapse_weights, clear the features except for X\")\n        (\"add_shape_types,s\", \"Add rule shape types\")\n        (\"extra_lex_feature,x\", \"Experimental nonlinear lexical weighting feature\")\n        (\"replace_files,r\", \"Replace files with transformed variants (requires loading full grammar into memory)\")\n        (\"grammar,g\", po::value<vector<string> >(), \"Input (also output) grammar file(s)\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config\", po::value<string>(), \"Configuration file\")\n        (\"help,h\", \"Print this help message and exit\");\n  po::options_description dconfig_options, dcmdline_options;\n  po::positional_options_description p;\n  p.add(\"grammar\", -1);\n  \n  dconfig_options.add(opts);\n  dcmdline_options.add(opts).add(clo);\n\n  po::store(po::command_line_parser(argc, argv).options(dcmdline_options).positional(p).run(), *conf);\n  if (conf->count(\"config\")) {\n    ifstream config((*conf)[\"config\"].as<string>().c_str());\n    po::store(po::parse_config_file(config, dconfig_options), *conf);\n  }\n  po::notify(*conf);\n\n  if (conf->count(\"help\") || conf->count(\"grammar\")==0) {\n    cerr << \"Usage \" << argv[0] << \" [OPTIONS] file.scfg [file2.scfg...]\\n\";\n    cerr << dcmdline_options << endl;\n    return false;\n  }\n  return true;\n}\n\nlm::WordIndex kSOS;\n\ntemplate <class Model> float Score(const vector<WordID>& str, const Model &model) {\n  typename Model::State state, out;\n  lm::FullScoreReturn ret;\n  float total = 0.0f;\n  state = model.NullContextState();\n\n  for (int i = 0; i < str.size(); ++i) {\n    lm::WordIndex vocab = ((str[i] < word_map.size() && str[i] > 0) ? word_map[str[i]] : 0);\n    if (vocab == kSOS) {\n      state = model.BeginSentenceState();\n    } else {\n      ret = model.FullScore(state, vocab, out);\n      total += ret.prob;\n      state = out;\n    }\n  }\n  return total;\n}\n\nbool extra_feature;\nint kSrcLM;\nvector<double> col_weights;\nbool gather_rules;\nbool clear_features = false;\nvector<TRulePtr> rules;\n\nstatic void RuleHelper(const TRulePtr& new_rule, const unsigned int ctf_level, const TRulePtr& coarse_rule, void* extra) {\n  static const int kSrcLM = FD::Convert(\"SrcLM\");\n  static const int kPC = FD::Convert(\"PC\");\n  static const int kX = FD::Convert(\"X\");\n  static const int kPhraseModel2 = FD::Convert(\"PhraseModel_1\");\n  static const int kNewLex = FD::Convert(\"NewLex\");\n  TRulePtr r; r.reset(new TRule(*new_rule));\n  if (ngram) r->scores_.set_value(kSrcLM, Score(r->f_, *ngram));\n  r->scores_.set_value(kPC, 1.0);\n  if (extra_feature) {\n    float v = r->scores_.value(kPhraseModel2);\n    r->scores_.set_value(kNewLex, v*(v+1));\n  }\n  if (col_weights.size()) {\n    double score = r->scores_.dot(col_weights);\n    if (clear_features) r->scores_.clear();\n    r->scores_.set_value(kX, score);\n  }\n  if (gather_rules) {\n    rules.push_back(r);\n  } else {\n    cout << *r << endl;\n  }\n}\n\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  if (!InitCommandLine(argc, argv, &conf)) return 1;\n  if (conf.count(\"source_lm\")) {\n    lm::ngram::Config kconf;\n    VMapper vm(&word_map);\n    kconf.enumerate_vocab = &vm; \n    ngram = new lm::ngram::ProbingModel(conf[\"source_lm\"].as<string>().c_str(), kconf);\n    kSOS = word_map[TD::Convert(\"<s>\")];\n    cerr << \"Loaded \" << (int)ngram->Order() << \"-gram KenLM (MapSize=\" << word_map.size() << \")\\n\";\n    cerr << \"  <s> = \" << kSOS << endl;\n  } else { ngram = NULL; }\n  extra_feature = conf.count(\"extra_lex_feature\") > 0;\n  if (conf.count(\"collapse_weights\")) {\n    Weights::InitFromFile(conf[\"collapse_weights\"].as<string>(), &col_weights);\n  }\n  clear_features = conf.count(\"clear_features_after_collapse\") > 0;\n  gather_rules = false;\n  bool replace_files = conf.count(\"replace_files\");\n  if (replace_files) gather_rules = true;\n  vector<string> files = conf[\"grammar\"].as<vector<string> >();\n  for (int i=0; i < files.size(); ++i) {\n    cerr << \"Processing \" << files[i] << \" ...\" << endl;\n    if (true) {\n      ReadFile rf(files[i]);\n      rules.clear();\n      RuleLexer::ReadRules(rf.stream(), &RuleHelper, NULL);\n    }\n    if (replace_files) {\n      WriteFile wf(files[i]);\n      for (int i = 0; i < rules.size(); ++i) { (*wf.stream()) << *rules[i] << endl; }\n    }\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "1e5af9a173602d9cd9e78a68f156a4f52b89af81", "size": 5524, "ext": "cc", "lang": "C++", "max_stars_repo_path": "training/augment_grammar.cc", "max_stars_repo_name": "kho/cdec", "max_stars_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 114.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T05:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T03:47:12.000Z", "max_issues_repo_path": "training/augment_grammar.cc", "max_issues_repo_name": "kho/cdec", "max_issues_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T01:00:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-25T06:04:02.000Z", "max_forks_repo_path": "training/augment_grammar.cc", "max_forks_repo_name": "kho/cdec", "max_forks_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T13:48:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-07T09:45:11.000Z", "avg_line_length": 34.7421383648, "max_line_length": 140, "alphanum_fraction": 0.6545981173, "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.17659610441346116}}
{"text": "#include \"zkp.h\"\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <fstream>\n#include <iostream>\n#include <libff/common/profiling.hpp>\n#include <sstream>\n#include <vector>\n\nnamespace\n{\nvoid DisableLibffLog()\n{\n  libff::inhibit_profiling_info = true;\n  libff::inhibit_profiling_counters = true;\n}\n\nstruct imembuf : public std::streambuf\n{\n  imembuf(char const *array, size_t len)\n  {\n    char *p(const_cast<char *>(array));\n    this->setg(p, p, p + len);\n  }\n};\n\nstruct imemstream : virtual imembuf, std::istream\n{\n  imemstream(char *array, size_t len)\n      : imembuf(array, len), std::istream(static_cast<std::streambuf *>(this)) {}\n};\n\nstruct omembuf : public std::streambuf\n{\n  omembuf(char *array, size_t len) { this->setp(array, array + len); }\n};\n\nstruct omemstream : virtual omembuf, std::ostream\n{\n  omemstream(char *array, size_t len)\n      : omembuf(array, len), std::ostream(static_cast<std::streambuf *>(this)) {}\n};\n} // namespace\n\nvoid InitZkp(bool disable_log)\n{\n  libsnark::default_r1cs_gg_ppzksnark_pp::init_public_params();\n  if (disable_log)\n  {\n    DisableLibffLog();\n  }\n}\n\nZkFr ConvertToZkFr(Fr const &mcl_fr)\n{\n  mpz_class m = mcl_fr.getMpz();\n  return ZkFr(libff::bigint<ZkFr::num_limbs>(m.get_mpz_t()));\n}\n\nstd::vector<ZkFr> ConvertToZkFr(std::vector<Fr> const &mcl_frs)\n{\n  std::vector<ZkFr> zk_frs(mcl_frs.size());\n  for (size_t i = 0; i < zk_frs.size(); ++i)\n  {\n    zk_frs[i] = ConvertToZkFr(mcl_frs[i]);\n  }\n  return zk_frs;\n}\n\nstd::vector<ZkFr> ConvertToZkFr(std::vector<uint64_t> const &o)\n{\n  std::vector<ZkFr> zk_frs(o.size());\n  for (size_t i = 0; i < zk_frs.size(); ++i)\n  {\n    zk_frs[i] = ConvertToZkFr(Fr(o[i]));\n  }\n  return zk_frs;\n}\n\nZkPkPtr LoadZkPk(std::string const &file)\n{\n  try\n  {\n    ZkPkPtr ret(new ZkPk());\n    std::ifstream ifs;\n    ifs.open(file, std::ifstream::in | std::ifstream::binary);\n    ifs >> (*ret);\n    return ret;\n  }\n  catch (std::exception &ex)\n  {\n    std::cerr << \"Exception: \" << ex.what() << \"\\n\";\n    return ZkPkPtr();\n  }\n}\n\nZkVkPtr LoadZkVk(std::string const &file)\n{\n  try\n  {\n    ZkVkPtr ret(new ZkVk());\n    std::ifstream ifs;\n    ifs.open(file, std::ifstream::in | std::ifstream::binary);\n    ifs >> (*ret);\n    return ret;\n  }\n  catch (std::exception &ex)\n  {\n    std::cerr << \"Exception: \" << ex.what() << \"\\n\";\n    return ZkVkPtr();\n  }\n}\n\nvoid ZkProofToBin(ZkProof const &proof,\n                  std::array<uint8_t, kZkProofSerializeSize> &bin)\n{\n  omemstream out((char *)bin.data(), bin.size());\n  out << proof;\n}\n\nvoid ZkProofFromBin(ZkProof &proof,\n                    std::array<uint8_t, kZkProofSerializeSize> const &bin)\n{\n  imemstream in((char *)bin.data(), bin.size());\n  in >> proof;\n}", "meta": {"hexsha": "b70901eb5d074e65753711a99c6789b41d2b7357", "size": 2727, "ext": "cc", "lang": "C++", "max_stars_repo_path": "zkPoD-lib/public/zkp.cc", "max_stars_repo_name": "Jackieyewang/Spicy-strips", "max_stars_repo_head_hexsha": "bd9f7800f0bf321d91e5ae00a033756cbdd32818", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T11:37:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T02:46:26.000Z", "max_issues_repo_path": "zkPoD-lib/public/zkp.cc", "max_issues_repo_name": "Jackieyewang/Spicy-strips", "max_issues_repo_head_hexsha": "bd9f7800f0bf321d91e5ae00a033756cbdd32818", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T18:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T02:04:01.000Z", "max_forks_repo_path": "zkPoD-lib/public/zkp.cc", "max_forks_repo_name": "Jackieyewang/Spicy-strips", "max_forks_repo_head_hexsha": "bd9f7800f0bf321d91e5ae00a033756cbdd32818", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-06-28T08:24:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T09:27:45.000Z", "avg_line_length": 21.6428571429, "max_line_length": 81, "alphanum_fraction": 0.6402640264, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17659610096676728}}
{"text": "//\r\n// $Id: greazy.cpp 8583 2015-06-29 16:12:57Z 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 greazy.\r\n//\r\n// The Initial Developer of the Original Code is Mike Kochen.\r\n//\r\n// Copyright 2015 Vanderbilt University\r\n//\r\n// Contributor(s):\r\n//\r\n\r\n#include \"freicore.h\"\r\n#include \"pwiz/data/msdata/MSDataFile.hpp\"\r\n#include \"pwiz/data/vendor_readers/ExtendedReaderList.hpp\"\r\n#include <iostream>\r\n#include <map>\r\n#include <fstream>\r\n#include <string>\r\n#include <sstream>\r\n#include <vector>\r\n#include <cmath>\r\n#include <ctime>\r\n#include <algorithm>\r\n#include <boost/filesystem.hpp>\r\n\r\nusing namespace pwiz::msdata;\r\n\r\n// atomic masses of relevant elements\r\ndouble H = 1.007825;\r\ndouble Li = 7.016005;\r\ndouble C = 12;\r\ndouble N = 14.003074;\r\ndouble O = 15.994915;\r\ndouble Na = 22.989770;\r\ndouble P = 30.973763;\r\ndouble Cl = 34.968853;\r\ndouble K = 38.963708;\r\n\r\n// Holds adduct information\r\nstruct Adduct {\r\n    string name;\r\n    string description;\r\n    string type;\r\n    double mass;\r\n    string polarity;\r\n};\r\n\r\n// Holds head-group information\r\nstruct HeadGroup {\r\n    string name;\r\n    string common;\r\n    string formula;\r\n    double mass;\r\n    double search;\r\n};\r\n\r\n// Holds backbone information\r\nstruct BackBone {\r\n    string name;\r\n    string formula;\r\n    double mass;\r\n    double search;\r\n    int length;\r\n    int ca;\r\n    int hy;\r\n    int ni;\r\n    int ox;\r\n    int ph;\r\n};\r\n\r\n// Holds fragment information\r\nstruct Fragment {\r\n    string fragType;\r\n    string fragDescription;\r\n    double fragmentMass;\r\n};\r\n\r\ntypedef vector<Fragment> Fragments; \r\n\r\n// Holds precursor information\r\nstruct PreCursor {\r\n    string description;\r\n    string adduct;\r\n    double adductMass;\r\n    string adductType;\r\n    string ESI;\r\n    double precursorMass;\r\n    Fragments fragments;\r\n};\r\n\r\ntypedef vector<PreCursor> PreCursors;\r\n\r\n// Holds lipid information\r\nstruct Lipid {\r\n    string name;\r\n    bool decoy;\r\n    double totalMass;\r\n    string lipidFormula;\r\n    string backbone;\r\n    string backboneFormula;\r\n    double backboneMass;\r\n    string headGroup;\r\n    string headGroupFormula;\r\n    double headGroupMass;\r\n    string FA1;\r\n    double FA1Mass;\r\n    double FA1DoubleBonds;\r\n    string SN1bond;\r\n    string FA2;\r\n    double FA2Mass;\r\n    double FA2DoubleBonds;\r\n    string SN2bond;\r\n    string FA3;\r\n    double FA3Mass;\r\n    double FA3DoubleBonds;\r\n    string SN3bond;\r\n    string FA4;\r\n    double FA4Mass;\r\n    double FA4DoubleBonds;\r\n    string SN4bond;\r\n    PreCursors precursors;\r\n};\r\n\r\nstruct SpectraHolder {\r\n    double preMassN;\r\n    double preMassP;\r\n    int spectraIndex;\r\n    double retentionTime;\r\n};\r\n\r\n// variable shorthand\r\ntypedef map<string, double> Map;\r\ntypedef vector<HeadGroup> HeadGroups;\r\ntypedef vector<BackBone> BackBones;\r\n\r\nstruct Match {\r\n    double mz;\r\n    double intensity;\r\n    bool match;\r\n    int peakIndex;\r\n    string fragmentD;\r\n    string fragmentT;\r\n};\r\n\r\nstruct Score {\r\n    int spectrumNumber;\r\n    bool decoy;\r\n    double spectrumPrecursorMass;\r\n    string lipidName;\r\n    string chemFormula;\r\n    double lipidMass;\r\n    string precursorDescription;\r\n    double precursorMass;\r\n    double peakScore;\r\n    double intensityScore;\r\n    double totalScore;\r\n    double retTime;\r\n    string charge;\r\n    string mod;\r\n    vector<Match> match;\r\n    vector<Match> ms2list;\r\n};\r\n\r\nstruct Secondary {\r\n    vector<double> PC;\r\n    vector<double> PE;\r\n    vector<double> PI;\r\n    vector<double> PS;\r\n    vector<double> PG;\r\n    vector<double> PA;\r\n    vector<double> CL;\r\n    vector<double> CL2;\r\n    vector<double> SM;\r\n    vector<double> PIP;\r\n    vector<double> PIP2;\r\n    vector<double> MPC;\r\n    vector<double> MPE;\r\n    vector<double> MPI;\r\n    vector<double> MPS;\r\n    vector<double> MPG;\r\n    vector<double> MPA;\r\n    vector<double> MCL;\r\n    //vector<double> M3CL;\r\n    vector<double> MSM;\r\n    vector<double> MPIP;\r\n    vector<double> PEC;\r\n    vector<double> PIC;\r\n    vector<double> MPEC;\r\n    vector<double> MPIC;\r\n};\r\n\r\n// Parameter map from configuration file\r\nMap processConfig(const string & fname);\r\n\r\n// lipid count \r\nvoid lipidCount(vector<Adduct> adducts, Map & paraMap, const HeadGroups & head, const BackBones & back, const HeadGroups & sphingoHead, const HeadGroups & cardioHead, double* count, int* pre);\r\n\r\n// precursor count\r\nvoid precursorCount(vector<Adduct> adducts, Lipid lipid, Map & paraMap, int* pre);\r\n\r\n// GP list construction \r\nvoid lipidConstructionAndScoring(vector<Adduct> adducts, Map & paraMap, const HeadGroups & head, const BackBones & back, const HeadGroups & sphingoHead, const HeadGroups & cardioHead, vector<SpectraHolder> spectraHolder, const SpectrumListPtr& SL, double* count, int* pre);\r\n\r\n// precursor list construction\r\nvoid precursorListConstruction(vector<Adduct> adducts, Lipid lipid, Map & paraMap, vector<SpectraHolder> spectraHolder, const SpectrumListPtr& SL, int* pre);\r\n\r\n// fragment list construction\r\nvoid fragmentListConstruction(Lipid lipid, Map & paraMap, vector<SpectraHolder> spectraHolder, const SpectrumListPtr& SL);\r\n\r\n// scoring algorithm\r\nvoid scoring(Lipid lipid, Map & paraMap, vector<SpectraHolder> spectraHolder, const SpectrumListPtr& SL);\r\n\r\n// various sorting functions\r\nbool sortByIntensity(const MZIntensityPair &lhs, const MZIntensityPair &rhs) \r\n{\r\n    return lhs.intensity > rhs.intensity;\r\n}\r\nbool sortByMZr(const Match &lhs, const Match &rhs) \r\n{\r\n    return lhs.mz < rhs.mz;\r\n}\r\nbool sortByTotalScore(const Score &lhs, const Score &rhs)\r\n{\r\n    return (lhs.totalScore > rhs.totalScore) || ((lhs.totalScore == rhs.totalScore) && (lhs.intensityScore > rhs.intensityScore));\r\n}\r\nbool sortByName(const Score &lhs, const Score &rhs)\r\n{\r\n    return lhs.lipidName < rhs.lipidName;\r\n}\r\nvector<vector<Score> > spec, spec2;\r\nvector<Secondary> secondary;\r\nvector<vector<double> > firstSecondFull;\r\nint lipCount;\r\nbool sortByHighScore(const vector<Score> &lhs, const vector<Score> &rhs)\r\n{\r\n    return lhs[0].totalScore > rhs[0].totalScore;\r\n}\r\nbool sortBySpecMZ(const SpectraHolder &lhs, const SpectraHolder &rhs) \r\n{\r\n    return lhs.preMassN < rhs.preMassN;\r\n}\r\n\r\n// binary search algorithm\r\nint binarySearch(vector<SpectraHolder> spectraHolder, double mass, int min, int max)\r\n{\r\n    int mid;\r\n    if ((max-min) > 1)\r\n    {\r\n        mid = (max+min)/2;\r\n        if (mass > spectraHolder[mid].preMassN)\r\n        {\r\n            return binarySearch(spectraHolder, mass, mid, max);\r\n        }\r\n        else\r\n        {\r\n            return binarySearch(spectraHolder, mass, min, mid);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        if (mass > max)\r\n        {\r\n            return max;\r\n        }\r\n        else\r\n        {\r\n            return min;\r\n        }\r\n    }\r\n}\r\n\r\n //initialize vectors containing CL combinations\r\n vector<vector<size_t> > CLspecies;\r\n\r\ntypedef vector<Match> match;\r\n// combinatorial function for computing intensity score\r\nvoid combo (int index, double totalMatchedIntensity, double intensity, int matchNum, match & ms2list, int* num)\r\n{     \r\n    if (index + 1 < matchNum)\r\n    {\r\n        for (size_t i=index; i<ms2list.size(); i++)\r\n        {\r\n            combo(i+1, totalMatchedIntensity, intensity + ms2list[i].intensity, matchNum, ms2list, num);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for (size_t i=index; i<ms2list.size(); i++)\r\n        {\r\n            if (intensity + ms2list[i].intensity + 0.000000000001 >= totalMatchedIntensity)\r\n            {\r\n                (*num)++;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n// initialize factorials\r\nvector<double> factorials(10000000);\r\n\r\n /////////// CLEANED TO HERE //////////////////////////////////////////////////////////////////\r\nint main(int argc, const char* argv[])\r\n{\r\n    /*\r\n    time_t now;\r\n    struct tm *current;\r\n    now = time(0);\r\n    current = localtime(&now);\r\n    cout << \"hour:\" << current->tm_hour << \" min:\" << current->tm_min << \" sec:\" << current->tm_sec << endl;\r\n    */\r\n\r\n    if (argc < 2)\r\n    {\r\n        cout << \"Please choose a data set.\" << endl; // give accepted formats\r\n        cout << \"Press ENTER to continue...\";\r\n        cin.get();\r\n        return 1;\r\n    }\r\n\r\n    string help = argv[1];\r\n    if (help == \"-h\" || help == \"-help\")\r\n    {\r\n        cout << \"help me!!!!\" << endl;\r\n        cin.get();\r\n        return 1;\r\n    }\r\n\r\n    if (!bfs::exists(argv[1]))\r\n    {\r\n        cout << \"Please choose a data set.\" << endl; // give accepted formats\r\n        cout << \"Press ENTER to continue...\";\r\n        cin.get();\r\n        return 1;\r\n    }\r\n\r\n    \r\n    cout << \"Greazy: Phospholipid Identification\" << endl << endl;\r\n    Map paraMap = processConfig(\"lipidConfig.txt\");\r\n\r\n    // adduct information\r\n    vector<Adduct> adducts;\r\n    if (paraMap[\"Add.Pro\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"+H\";\r\n        adducts[adducts.size()-1].description = \"protonated\";\r\n        adducts[adducts.size()-1].type = \"nonMetal\";\r\n        adducts[adducts.size()-1].mass = H;\r\n        adducts[adducts.size()-1].polarity = \"positive\";\r\n    }\r\n\r\n    if (paraMap[\"Add.Na\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"+Na\";\r\n        adducts[adducts.size()-1].description = \"Sodium adduct\";\r\n        adducts[adducts.size()-1].type = \"Metal\";\r\n        adducts[adducts.size()-1].mass = Na;\r\n        adducts[adducts.size()-1].polarity = \"positive\";\r\n    }\r\n\r\n    if (paraMap[\"Add.NH4\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"+NH4\";\r\n        adducts[adducts.size()-1].description = \"Ammonium adduct\";\r\n        adducts[adducts.size()-1].type = \"nonMetal\";\r\n        adducts[adducts.size()-1].mass = N + 4*H;\r\n        adducts[adducts.size()-1].polarity = \"positive\";\r\n    }\r\n\r\n    if (paraMap[\"Add.Li\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"+Li\";\r\n        adducts[adducts.size()-1].description = \"Lithium adduct\";\r\n        adducts[adducts.size()-1].type = \"Metal\";\r\n        adducts[adducts.size()-1].mass = Li;\r\n        adducts[adducts.size()-1].polarity = \"positive\";\r\n    }\r\n\r\n    if (paraMap[\"Add.K\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"+K\";\r\n        adducts[adducts.size()-1].description = \"Potassium adduct\";\r\n        adducts[adducts.size()-1].type = \"Metal\";\r\n        adducts[adducts.size()-1].mass = K;\r\n        adducts[adducts.size()-1].polarity = \"positive\";\r\n    }\r\n\r\n    if (paraMap[\"Add.Depro\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"Deprotonated\";\r\n        adducts[adducts.size()-1].description = \"Deprotonated\";\r\n        adducts[adducts.size()-1].type = \"nonMetal\";\r\n        adducts[adducts.size()-1].mass = -H;\r\n        adducts[adducts.size()-1].polarity = \"negative\";\r\n    }\r\n\r\n    if (paraMap[\"Add.Cl\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"Cl\";\r\n        adducts[adducts.size()-1].description = \"Chlorine adduct\";\r\n        adducts[adducts.size()-1].type = \"nonMetal\";\r\n        adducts[adducts.size()-1].mass = Cl;\r\n        adducts[adducts.size()-1].polarity = \"negative\";\r\n    }\r\n\r\n    if (paraMap[\"Add.HCOO\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"Formate\";\r\n        adducts[adducts.size()-1].description = \"Formate adduct\";\r\n        adducts[adducts.size()-1].type = \"nonMetal\";\r\n        adducts[adducts.size()-1].mass = C + H + 2*O;\r\n        adducts[adducts.size()-1].polarity = \"negative\";\r\n    }\r\n\r\n    if (paraMap[\"Add.CH3COO\"] == 1)\r\n    {\r\n        adducts.push_back(Adduct());\r\n        adducts[adducts.size()-1].name = \"Acetate\";\r\n        adducts[adducts.size()-1].description = \"Acetate adduct\";\r\n        adducts[adducts.size()-1].type = \"nonMetal\";\r\n        adducts[adducts.size()-1].mass = 2*C + 2*O + 3*H;\r\n        adducts[adducts.size()-1].polarity = \"negative\";\r\n    }\r\n\r\n    vector<string> modifications;\r\n    if ((paraMap[\"Add.Pro\"] == 1) && (paraMap[\"ESI.pos\"] == 1))\r\n    {\r\n        modifications.push_back(\"+H\");\r\n    }\r\n\r\n    if ((paraMap[\"Add.Na\"] == 1) && (paraMap[\"ESI.pos\"] == 1))\r\n    {\r\n        modifications.push_back(\"+Na\");\r\n    }\r\n\r\n    if ((paraMap[\"CL\"] == 1) && (paraMap[\"Add.Na\"] == 1) && (paraMap[\"ESI.neg\"] == 1))\r\n    {\r\n        modifications.push_back(\"-2H + Na\");\r\n    }\r\n\r\n    if ((paraMap[\"Add.NH4\"] == 1) && (paraMap[\"ESI.pos\"] == 1))\r\n    {\r\n        modifications.push_back(\"+NH4\");\r\n    }\r\n\r\n    if ((paraMap[\"Add.Li\"] == 1) && (paraMap[\"ESI.pos\"] == 1))\r\n    {\r\n        modifications.push_back(\"+Li\");\r\n    }\r\n\r\n    if ((paraMap[\"Add.K\"] == 1) && (paraMap[\"ESI.pos\"] == 1))\r\n    {\r\n        modifications.push_back(\"+K\");\r\n    }\r\n\r\n    if ((paraMap[\"Add.Depro\"] == 1) && (paraMap[\"ESI.neg\"] == 1))\r\n    {\r\n        modifications.push_back(\"-H\");\r\n    }\r\n\r\n    if ((paraMap[\"Add.Cl\"] == 1) && (paraMap[\"ESI.neg\"] == 1))\r\n    {\r\n        modifications.push_back(\"+Cl\");\r\n    }\r\n\r\n    if ((paraMap[\"Add.HCOO\"] == 1) && (paraMap[\"ESI.neg\"] == 1))\r\n    {\r\n        modifications.push_back(\"+HCOO\");\r\n    }\r\n\r\n    if ((paraMap[\"Add.CH3COO\"] == 1) && (paraMap[\"ESI.neg\"] == 1))\r\n    {\r\n        modifications.push_back(\"+CH3COO\");\r\n    }\r\n\r\n    if ((paraMap[\"GP.Cholines\"] == 1) && (paraMap[\"ESI.neg\"] == 1) && (paraMap[\"Add.Cl\"] == 1 || paraMap[\"Add.CH3COO\"] == 1 || paraMap[\"Add.HCOO\"] == 1))\r\n    {\r\n        modifications.push_back(\"-CH3\");\r\n    }\r\n\r\n    if (((paraMap[\"GP\"] == 1) && (paraMap[\"GP.InositolPhosphates\"] == 1) && (paraMap[\"ESI.neg\"] == 1) ) || ((paraMap[\"CL\"] == 1) && (paraMap[\"ESI.neg\"] == 1) && (paraMap[\"CL.double\"] == 1)))\r\n    {\r\n        modifications.push_back(\"-2H\");\r\n    }\r\n\r\n    // backbone information\r\n    int sphingoBack = (paraMap[\"SP.UpperBack\"] - paraMap[\"SP.LowerBack\"] + 1)*(paraMap[\"SP.Sphingosine\"] + paraMap[\"SP.Sphinganine\"] + paraMap[\"SP.Phytosphingosine\"] + paraMap[\"SP.Sphingadienine\"]) + 2;\r\n    BackBones back (sphingoBack);\r\n\r\n    back[0].name = \"Glycerol\";\r\n    back[0].formula = \"C3H5O3\";\r\n    back[0].mass = 3*C + 5*H + 3*O;\r\n\r\n    back[1].name = \"Cardiolipin\";\r\n    back[1].formula = \"C9H17O13P2\";\r\n    back[1].mass = 9*C + 17*H + 13*O + 2*P;\r\n    \r\n    int backIndex = 2;\r\n    for (size_t i=paraMap[\"SP.LowerBack\"]; i<paraMap[\"SP.UpperBack\"]+1; i++)\r\n    {\r\n        if (paraMap[\"SP.Sphingosine\"])\r\n        {\r\n            stringstream name;\r\n            name << \"(C\" << i << \")Sphingosine\";\r\n            back[backIndex].name = name.str();\r\n            back[backIndex].formula = \"Sphingosine\";\r\n            back[backIndex].mass = i*C + (2*i - 1)*H + 2*O + N;\r\n            back[backIndex].ca = i;\r\n            back[backIndex].hy = 2*i - 1;\r\n            back[backIndex].ox = 2;\r\n            back[backIndex].ni = 1;\r\n            back[backIndex].search = paraMap[\"SP.Sphingosine\"];\r\n            back[backIndex].length = i;\r\n            backIndex++;\r\n        }\r\n        \r\n        if (paraMap[\"SP.Sphinganine\"])\r\n        {\r\n            stringstream name;\r\n            name << \"(C\" << i << \")Sphinganine\";\r\n            back[backIndex].name = name.str();\r\n            back[backIndex].formula = \"Sphinganine\";\r\n            back[backIndex].mass = i*C + (2*i + 1)*H + 2*O + N;\r\n            back[backIndex].ca = i;\r\n            back[backIndex].hy = 2*i + 1;\r\n            back[backIndex].ox = 2;\r\n            back[backIndex].ni = 1;\r\n            back[backIndex].search = paraMap[\"SP.Sphinganine\"];\r\n            back[backIndex].length = i;\r\n            backIndex++;\r\n        }\r\n\r\n        if (paraMap[\"SP.Phytosphingosine\"])\r\n        {\r\n            stringstream name;\r\n            name << \"(C\" << i << \")Phytosphingosine\";\r\n            back[backIndex].name = name.str();\r\n            back[backIndex].formula = \"Phytosphingosine\";\r\n            back[backIndex].mass = i*C + (2*i + 1)*H + 3*O + N;\r\n            back[backIndex].ca = i;\r\n            back[backIndex].hy = 2*i + 1;\r\n            back[backIndex].ox = 3;\r\n            back[backIndex].ni = 1;\r\n            back[backIndex].search = paraMap[\"SP.Phytosphingosine\"];\r\n            back[backIndex].length = i;\r\n            backIndex++;\r\n        }\r\n\r\n        if (paraMap[\"SP.Sphingadienine\"])\r\n        {\r\n            stringstream name;\r\n            name << \"(C\" << i << \")Sphingadienine\";\r\n            back[backIndex].name = name.str();\r\n            back[backIndex].formula = \"Sphingadienine\";\r\n            back[backIndex].mass = i*C + (2*i - 3)*H + 2*O + N;\r\n            back[backIndex].ca = i;\r\n            back[backIndex].hy = 2*i - 3;\r\n            back[backIndex].ox = 2;\r\n            back[backIndex].ni = 1;\r\n            back[backIndex].search = paraMap[\"SP.Sphingadienine\"];\r\n            back[backIndex].length = i;\r\n            backIndex++;\r\n        }\r\n    }\r\n     \r\n    // vector of structs holding glycerophospholipid head-group information\r\n    HeadGroups head (9);\r\n\r\n    head[0].name = \"Choline\";\r\n    head[0].common = \"PC\";\r\n    head[0].formula = \"C5H13O3PN\";\r\n    head[0].mass = 5*C + 13*H + 3*O + P + N;\r\n    head[0].search = paraMap[\"GP.Cholines\"];\r\n\r\n    head[1].name = \"Ethanolamine\";\r\n    head[1].common = \"PE\";\r\n    head[1].formula = \"C2H7O3PN\";\r\n    head[1].mass = 2*C + 7*H + 3*O + P + N;\r\n    head[1].search = paraMap[\"GP.Ethanolamines\"];\r\n    \r\n    head[2].name = \"Serine\";\r\n    head[2].common = \"PS\";\r\n    head[2].formula = \"C3H7O5PN\";\r\n    head[2].mass = 3*C + 7*H + 5*O + P + N;\r\n    head[2].search = paraMap[\"GP.Serines\"];\r\n\r\n    head[3].name = \"Glycerol\";\r\n    head[3].common = \"PG\";\r\n    head[3].formula = \"C3H8O5P\";\r\n    head[3].mass = 3*C + 8*H + 5*O + P;\r\n    head[3].search = paraMap[\"GP.Glycerols\"];\r\n\r\n    head[4].name = \"Inositol\";\r\n    head[4].common = \"PI\";\r\n    head[4].formula = \"C6H12O8P\";\r\n    head[4].mass = 6*C + 12*H + 8*O + P;\r\n    head[4].search = paraMap[\"GP.Inositols\"];\r\n\r\n    head[5].name = \"Phosphate\";\r\n    head[5].common = \"PA\";\r\n    head[5].formula = \"H2O3P\";\r\n    head[5].mass = 2*H + 3*O + P;\r\n    head[5].search = paraMap[\"GP.Phosphates\"];\r\n    \r\n    head[6].name = \"PIP\";\r\n    head[6].common = \"PIP\";\r\n    head[6].formula = \"C6H13O11P2\";\r\n    head[6].mass = 6*C + 13*H + 11*O + 2*P;\r\n    head[6].search = paraMap[\"GP.InositolPhosphates\"];\r\n    \r\n    head[7].name = \"PIP2\";\r\n    head[7].common = \"PIP2\";\r\n    head[7].formula = \"C6H14O14P3\";\r\n    head[7].mass = 6*C + 14*H + 14*O + 3*P;\r\n    head[7].search = paraMap[\"GP.InositolPhosphates\"];\r\n    \r\n    head[8].name = \"PIP3\";\r\n    head[8].common = \"PIP3\";\r\n    head[8].formula = \"C6H15O17P4\";\r\n    head[8].mass = 6*C + 15*H + 17*O + 4*P;\r\n    head[8].search = paraMap[\"GP.InositolPhosphates\"];\r\n    \r\n    // vector of structs holding sphingolipid head-group information\r\n    HeadGroups sphingoHead (3);\r\n\r\n    sphingoHead[0].name = \"Choline\";\r\n    sphingoHead[0].common = \"SM\";\r\n    sphingoHead[0].formula = \"C5H13O3PN\";\r\n    sphingoHead[0].mass = 5*C + 13*H + 3*O + P + N;\r\n    sphingoHead[0].search = paraMap[\"SP.Cholines\"];\r\n\r\n    sphingoHead[1].name = \"Ethanolamine\";\r\n    sphingoHead[1].common = \"PE-Cer\";\r\n    sphingoHead[1].formula = \"C2H7O3PN\";\r\n    sphingoHead[1].mass = 2*C + 7*H + 3*O + P + N;\r\n    sphingoHead[1].search = paraMap[\"SP.Ethanolamines\"];\r\n\r\n    sphingoHead[2].name = \"Inositol\";\r\n    sphingoHead[2].common = \"PI-Cer\";\r\n    sphingoHead[2].formula = \"C6H12O8P\";\r\n    sphingoHead[2].mass = 6*C + 12*H + 8*O + P;\r\n    sphingoHead[2].search = paraMap[\"SP.Inositols\"];\r\n\r\n    // vector of structs holding cardiolipin head-group information\r\n    HeadGroups cardioHead (2);\r\n\r\n    cardioHead[0].name = \"None\";\r\n    cardioHead[0].common = \"\";\r\n    cardioHead[0].formula = \"H\";\r\n    cardioHead[0].mass = H;\r\n    cardioHead[0].search = paraMap[\"CL.None\"];\r\n\r\n    /*\r\n    cardioHead[1].name = \"Glucose\";\r\n    cardioHead[1].common = \"Glucosyl\";\r\n    cardioHead[1].formula = \"C6H11O5\";\r\n    cardioHead[1].mass = 6*C + 11*H + 5*O;\r\n    cardioHead[1].search = paraMap[\"CL.Glucosyl\"];\r\n    */\r\n\r\n    // populate vector of log factorials\r\n    factorials[0] = 0;\r\n    for (double i=1; i<10000000; i++)\r\n    {\r\n        factorials[i] = factorials[i-1] + log10(i);\r\n    }\r\n\r\n    /*\r\n    // define fragment tolerances\r\n    double fragTolerance;\r\n    if (paraMap[\"fragTolmz\"] == 1)\r\n    {\r\n        fragTolerance = paraMap[\"mzFragTol\"];\r\n    }\r\n    else if (paraMap[\"fragTolmz\"] == 0)\r\n    {\r\n        fragTolerance = paraMap[\"ppmFragTol\"];\r\n    }\r\n    */\r\n\r\n    // collect spectra information    \r\n    ExtendedReaderList readerList;\r\n    MSDataFile msd(argv[1], &readerList);\r\n    const SpectrumListPtr& SL = msd.run.spectrumListPtr;\r\n    size_t numSpectra = msd.run.spectrumListPtr->size();\r\n    spec.resize(numSpectra);\r\n    secondary.resize(numSpectra);\r\n    firstSecondFull.resize(numSpectra);\r\n    for (size_t i=0; i<firstSecondFull.size(); i++)\r\n    {\r\n        firstSecondFull[i].resize(2, 0);\r\n    }\r\n\r\n\r\n    for (size_t i=0; i<secondary.size(); i++)\r\n    {\r\n        secondary[i].PC.resize(2,0.0);\r\n        secondary[i].PE.resize(2,0.0);\r\n        secondary[i].PI.resize(2,0.0);\r\n        secondary[i].PS.resize(2,0.0);\r\n        secondary[i].PG.resize(2,0.0);\r\n        secondary[i].PA.resize(2,0.0);\r\n        secondary[i].CL.resize(2,0.0);\r\n        secondary[i].CL2.resize(2,0.0);\r\n        secondary[i].SM.resize(2,0.0);\r\n        secondary[i].PIP.resize(2,0.0);\r\n        secondary[i].PIP2.resize(2,0.0);\r\n        secondary[i].MPC.resize(2,0.0);\r\n        secondary[i].MPE.resize(2,0.0);\r\n        secondary[i].MPI.resize(2,0.0);\r\n        secondary[i].MPS.resize(2,0.0);\r\n        secondary[i].MPG.resize(2,0.0);\r\n        secondary[i].MPA.resize(2,0.0);\r\n        secondary[i].MCL.resize(2,0.0);\r\n        //secondary[i].M3CL.resize(2,0.0);\r\n        secondary[i].MSM.resize(2,0.0);\r\n        secondary[i].MPIP.resize(2,0.0);\r\n        secondary[i].PEC.resize(2,0.0);\r\n        secondary[i].PIC.resize(2,0.0);\r\n        secondary[i].MPEC.resize(2,0.0);\r\n        secondary[i].MPIC.resize(2,0.0);\r\n    }\r\n\r\n    vector<SpectraHolder> spectraHolder;\r\n    int spectraIndex = 0;\r\n    double retTime;\r\n    for (size_t i=0; i < numSpectra; ++i)\r\n    {\r\n        SpectrumPtr s = SL->spectrum(i);\r\n        if (s->precursors.empty() == false)\r\n        {    \r\n            retTime = s->scanList.scans[0].cvParam(MS_scan_start_time).valueAs<double>();\r\n            double mass = s->precursors[0].selectedIons[0].cvParam(MS_selected_ion_m_z).valueAs<double>();\r\n            \r\n            double preTol;\r\n            if (paraMap[\"preTolmz\"] == 1)\r\n            {\r\n                preTol = paraMap[\"mzTol\"];\r\n            }\r\n            else if (paraMap[\"preTolmz\"] == 0)\r\n            {\r\n                preTol = paraMap[\"ppmTol\"]*mass/1000000;\r\n            }\r\n            spectraHolder.push_back(SpectraHolder());\r\n            spectraHolder[spectraIndex].retentionTime = retTime;\r\n            spectraHolder[spectraIndex].preMassN = mass - preTol;\r\n            spectraHolder[spectraIndex].preMassP = mass + preTol;\r\n            spectraHolder[spectraIndex].spectraIndex = i;\r\n            spectraIndex++;\r\n\r\n        }\r\n    }\r\n    if (spectraHolder.size() == 0)\r\n    {\r\n        cout << endl << \"NO PRECURSOR DATA\" << endl;\r\n        return 1;\r\n    }\r\n    sort(spectraHolder.begin(), spectraHolder.end(), sortBySpecMZ);\r\n\r\n    // creation of the lipid search space and scoring vector\r\n    double count = 0;\r\n    double* pCount = &count;\r\n    int pre = 0;\r\n    int* pPre = &pre;\r\n    \r\n    lipidCount(adducts, paraMap, head, back, sphingoHead, cardioHead, pCount, pPre);\r\n    \r\n    lipCount = count;\r\n    cout << \"There are \" << lipCount << \" lipids in the search space.\" << endl;\r\n    count = 0;\r\n    lipidConstructionAndScoring(adducts, paraMap, head, back, sphingoHead, cardioHead, spectraHolder, SL, pCount, pPre);\r\n    cout << endl << \"writing results to .lama file and spectral svg's to embedded .html files ... \";\r\n\r\n    // eliminate empty vector entries\r\n    vector<vector<Score> >::iterator it = spec.begin();\r\n    while (it != spec.end())\r\n    {\r\n        if (it->empty())\r\n        {\r\n            it = spec.erase(it);\r\n        }\r\n        else\r\n        {\r\n            ++it;\r\n        }\r\n    }\r\n\r\n    // Score vector sorting\r\n    for (size_t i=0; i<spec.size(); i++)\r\n    {\r\n        sort(spec[i].begin(), spec[i].end(), sortByTotalScore);\r\n    }\r\n    sort(spec.begin(), spec.end(), sortByHighScore);\r\n\r\n    // print list of scores for R and LipidLama and SVG\r\n    string hist = argv[1];\r\n    size_t dot = hist.find_last_of(\".\");\r\n    string dotless = hist.substr(0,dot);\r\n    dotless += \".lama\";\r\n    ofstream hfile(dotless.c_str());\r\n    hfile << argv[1] << endl;\r\n    hfile << setprecision(10);    \r\n    for (size_t i=0; i<spec.size(); i++)\r\n    {\r\n        double scoreTest = spec[i][0].totalScore;\r\n        spec2.push_back(vector<Score>());\r\n        for (size_t j=0; j<spec[i].size(); j++)\r\n        {\r\n            if (spec[i][j].totalScore >= scoreTest)\r\n            {\r\n                spec2[i].push_back(Score());\r\n                spec2[i][j]=spec[i][j];\r\n            }\r\n        }\r\n    }\r\n\r\n    for (size_t i=0; i<spec2.size(); i++)\r\n    {\r\n        sort(spec2[i].begin(), spec2[i].end(), sortByName);\r\n    }\r\n\r\n    for (size_t i=0; i<spec2.size(); i++)\r\n    {\r\n        if (spec2[i][0].totalScore > 0)\r\n        {\r\n            hfile << \"---\" << endl;\r\n            hfile << spec2[i][0].spectrumNumber << endl;\r\n            hfile << spec2[i][0].lipidName << endl;\r\n            hfile << spec2[i][0].chemFormula << endl;\r\n            hfile << spec2[i][0].precursorMass << endl;            \r\n            hfile << spec2[i][0].spectrumPrecursorMass << endl;\r\n            hfile << spec2[i][0].charge << endl;\r\n            hfile << spec2[i][0].retTime << endl;\r\n            hfile << spec2[i][0].mod << endl;\r\n            hfile << spec2[i][0].totalScore << endl;\r\n        }\r\n    }\r\n    hfile << \"SECONDHIGHESTSCORES\" << endl;\r\n\r\n    \r\n    for (size_t i=0; i<secondary.size(); i++)\r\n    {\r\n        if (secondary[i].PC[0] != 0)\r\n        {\r\n            hfile << \"PC \" << secondary[i].PC[0] << \" \" << secondary[i].PC[1] << endl;\r\n        }\r\n        if (secondary[i].MPC[0] != 0)\r\n        {\r\n            hfile << \"MPC \" << secondary[i].MPC[0] << \" \" << secondary[i].MPC[1] << endl;\r\n        }\r\n        if (secondary[i].PE[0] != 0)\r\n        {\r\n            hfile << \"PE \" << secondary[i].PE[0] << \" \" << secondary[i].PE[1] << endl;\r\n        }\r\n        if (secondary[i].MPE[0] != 0)\r\n        {\r\n            hfile << \"MPE \" << secondary[i].MPE[0] << \" \" << secondary[i].MPE[1] << endl;\r\n        }\r\n        if (secondary[i].PI[0] != 0)\r\n        {\r\n            hfile << \"PI \" << secondary[i].PI[0] << \" \" << secondary[i].PI[1] << endl;\r\n        }\r\n        if (secondary[i].MPI[0] != 0)\r\n        {\r\n            hfile << \"MPI \" << secondary[i].MPI[0] << \" \" << secondary[i].MPI[1] << endl;\r\n        }\r\n        if (secondary[i].PG[0] != 0)\r\n        {\r\n            hfile << \"PG \" << secondary[i].PG[0] << \" \" << secondary[i].PG[1] << endl;\r\n        }\r\n        if (secondary[i].MPG[0] != 0)\r\n        {\r\n            hfile << \"MPG \" << secondary[i].MPG[0] << \" \" << secondary[i].MPG[1] << endl;\r\n        }\r\n        if (secondary[i].PS[0] != 0)\r\n        {\r\n            hfile << \"PS \" << secondary[i].PS[0] << \" \" << secondary[i].PS[1] << endl;\r\n        }\r\n        if (secondary[i].MPS[0] != 0)\r\n        {\r\n            hfile << \"MPS \" << secondary[i].MPS[0] << \" \" << secondary[i].MPS[1] << endl;\r\n        }\r\n        if (secondary[i].PA[0] != 0)\r\n        {\r\n            hfile << \"PA \" << secondary[i].PA[0] << \" \" << secondary[i].PA[1] << endl;\r\n        }\r\n        if (secondary[i].MPA[0] != 0)\r\n        {\r\n            hfile << \"MPA \" << secondary[i].MPA[0] << \" \" << secondary[i].MPA[1] << endl;\r\n        }\r\n        if (secondary[i].SM[0] != 0)\r\n        {\r\n            hfile << \"SM \" << secondary[i].SM[0] << \" \" << secondary[i].SM[1] << endl;\r\n        }\r\n        if (secondary[i].MSM[0] != 0)\r\n        {\r\n            hfile << \"MSM \" << secondary[i].MSM[0] << \" \" << secondary[i].MSM[1] << endl;\r\n        }\r\n        if (secondary[i].CL[0] != 0)\r\n        {\r\n            hfile << \"CL \" << secondary[i].CL[0] << \" \" << secondary[i].CL[1] << endl;\r\n        }\r\n        if (secondary[i].MCL[0] != 0)\r\n        {\r\n            hfile << \"MCL \" << secondary[i].MCL[0] << \" \" << secondary[i].MCL[1] << endl;\r\n        }\r\n        if (secondary[i].CL2[0] != 0)\r\n        {\r\n            hfile << \"CL2 \" << secondary[i].CL2[0] << \" \" << secondary[i].CL2[1] << endl;\r\n        }\r\n        if (secondary[i].PIP[0] != 0)\r\n        {\r\n            hfile << \"PIP \" << secondary[i].PIP[0] << \" \" << secondary[i].PIP[1] << endl;\r\n        }\r\n        if (secondary[i].MPIP[0] != 0)\r\n        {\r\n            hfile << \"MPIP \" << secondary[i].MPIP[0] << \" \" << secondary[i].MPIP[1] << endl;\r\n        }\r\n        if (secondary[i].PIP2[0] != 0)\r\n        {\r\n            hfile << \"PIP2 \" << secondary[i].PIP2[0] << \" \" << secondary[i].PIP2[1] << endl;\r\n        }\r\n        if (secondary[i].PEC[0] != 0)\r\n        {\r\n            hfile << \"PEC \" << secondary[i].PEC[0] << \" \" << secondary[i].PEC[1] << endl;\r\n        }\r\n        if (secondary[i].PIC[0] != 0)\r\n        {\r\n            hfile << \"PIC \" << secondary[i].PIC[0] << \" \" << secondary[i].PIC[1] << endl;\r\n        }\r\n        if (secondary[i].MPEC[0] != 0)\r\n        {\r\n            hfile << \"MPEC \" << secondary[i].MPEC[0] << \" \" << secondary[i].MPEC[1] << endl;\r\n        }\r\n        if (secondary[i].MPIC[0] != 0)\r\n        {\r\n            hfile << \"MPIC \" << secondary[i].MPIC[0] << \" \" << secondary[i].MPIC[1] << endl;\r\n        }\r\n    }\r\n    hfile << \"MODIFICATIONS\" << endl;\r\n    for (size_t i=0; i<modifications.size(); i++)\r\n    {\r\n        hfile << modifications[i] << endl;\r\n    }\r\n\r\n    /*\r\n    string dirString = argv[1];\r\n    size_t dirInd = 0;\r\n    for (size_t i=0; i<dirString.length(); i++)\r\n    {\r\n        if (dirString[i] == '\\\\')\r\n        {\r\n            dirInd = i;\r\n        }\r\n    }\r\n    */\r\n\r\n    int i = 0;\r\n    string direct = argv[1];\r\n    while(direct[i] != '.')\r\n    {\r\n        i++;\r\n    }\r\n    direct = direct.substr(0, i);\r\n    boost::filesystem::path dir(direct);\r\n    if (!(boost::filesystem::exists(dir)))\r\n    {\r\n        boost::filesystem::create_directory(dir);\r\n    }\r\n    for (boost::filesystem::directory_iterator end_dir_it, it(dir); it!=end_dir_it; ++it)\r\n    {\r\n        remove_all(it->path());\r\n    }\r\n\r\n    const unsigned WIDTH = 1800;\r\n    const unsigned HEIGHT = 1000;\r\n\r\n    for (size_t i=0; i<spec.size(); i++)\r\n    {\r\n        double tScore = spec[i][0].totalScore;\r\n        //size_t j = 0;\r\n\r\n        for (size_t j=0; j<spec[i].size(); j++)\r\n        {\r\n            if (spec[i][j].totalScore >= tScore)\r\n            {\r\n                double cutoff;\r\n                if (spec[i][j].precursorDescription == \"deprotonatedX2\")\r\n                {\r\n                    cutoff = spec[i][j].precursorMass*2;\r\n                }\r\n                else\r\n                {\r\n                    cutoff = spec[i][j].precursorMass;\r\n                }\r\n\r\n                for (size_t k=0; k<spec[i][j].match.size(); k++)\r\n                {\r\n                    if (spec[i][j].match[k].peakIndex != 99999)\r\n                    {\r\n                        spec[i][j].ms2list[spec[i][j].match[k].peakIndex].match = 1;\r\n                        spec[i][j].ms2list[spec[i][j].match[k].peakIndex].fragmentD = spec[i][j].match[k].fragmentD;\r\n                    }\r\n                }\r\n                double left = spec[i][j].match[0].mz;\r\n                double right = max(spec[i][j].match[spec[i][j].match.size()-1].mz, spec[i][j].precursorMass);\r\n                for (size_t k=0; k<spec[i][j].ms2list.size(); k++)\r\n                {\r\n                \r\n                    if (spec[i][j].ms2list[k].mz < left)\r\n                    {\r\n                        left = spec[i][j].ms2list[k].mz;\r\n                    }\r\n                    if ((spec[i][j].ms2list[k].mz > right) && (spec[i][j].ms2list[k].mz < cutoff+10))\r\n                    {\r\n                        right = spec[i][j].ms2list[k].mz;\r\n                    }\r\n                }\r\n                left = floor(left/100)*100;\r\n                right = ceil(right/100)*100;\r\n                double range = right - left;\r\n                double yHeight = spec[i][j].ms2list[0].intensity;\r\n                yHeight = ceil(yHeight/pow(10, floor(log10(yHeight))))*pow(10, floor(log10(yHeight)));\r\n                stringstream ss;\r\n                ss << direct << \"\\\\\" << spec[i][j].spectrumNumber << \".html\";\r\n                string svgName = ss.str();\r\n            \r\n                ofstream svg(svgName.c_str());\r\n\r\n                svg << \"<!DOCTYPE html>\" << endl << \"<html>\" << endl << \"<body>\" << endl << endl\r\n                    //<< \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"no\\\"?>\" << endl\r\n                    << \"<svg width=\\\"\" << WIDTH << \"\\\" height=\\\"\" << HEIGHT << \"\\\">\" << endl\r\n                    << \"<line x1=\\\"99\\\" y1=\\\"500\\\" x2=\\\"1000\\\" y2=\\\"500\\\" stroke=\\\"black\\\" stroke-width=\\\"2\\\" />\" << endl\r\n                    << \"<line x1=\\\"99\\\" y1=\\\"600\\\" x2=\\\"1000\\\" y2=\\\"600\\\" stroke=\\\"black\\\" stroke-width=\\\"2\\\" />\" << endl\r\n                    << \"<line x1=\\\"100\\\" y1=\\\"500\\\" x2=\\\"100\\\" y2=\\\"50\\\" stroke=\\\"black\\\" stroke-width=\\\"2\\\" />\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-size=\\\"18\\\" transform=\\\"rotate(270 35,300)\\\" x=\\\"35\\\" y=\\\"300\\\" fill=\\\"black\\\">Intensity</text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-size=\\\"18\\\" x=\\\"550\\\" y=\\\"650\\\" fill=\\\"black\\\">m/z</text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-size=\\\"20\\\" font-weight=\\\"bold\\\" x=\\\"1050\\\" y=\\\"50\\\" fill=\\\"black\\\">Lipid: </text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-size=\\\"20\\\" font-weight=\\\"bold\\\" x=\\\"1115\\\" y=\\\"50\\\" fill=\\\"black\\\">\" << spec[i][j].lipidName << \"</text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-size=\\\"20\\\" font-weight=\\\"bold\\\" x=\\\"1050\\\" y=\\\"75\\\" fill=\\\"black\\\">Score: </text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-size=\\\"20\\\" font-weight=\\\"bold\\\" x=\\\"1120\\\" y=\\\"75\\\" fill=\\\"black\\\">\" << spec[i][j].totalScore << \"</text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-weight=\\\"bold\\\" x=\\\"1050\\\" y=\\\"110\\\" fill=\\\"black\\\">Precursor: </text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" x=\\\"1205\\\" y=\\\"110\\\" fill=\\\"black\\\">\" << \"(\" << spec[i][j].precursorDescription << \")\" << \"</text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" x=\\\"1140\\\" y=\\\"110\\\" fill=\\\"darkorange\\\">\" << spec[i][j].precursorMass << \"</text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-weight=\\\"bold\\\" x=\\\"1050\\\" y=\\\"145\\\" fill=\\\"black\\\">m/z</text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-weight=\\\"bold\\\" x=\\\"1150\\\" y=\\\"145\\\" fill=\\\"black\\\">Intensity</text>\" << endl\r\n                    << \"<text font-family=\\\"sans-serif\\\" font-weight=\\\"bold\\\" x=\\\"1250\\\" y=\\\"145\\\" fill=\\\"black\\\">Fragment</text>\" << endl\r\n                    << \"<line x1=\\\"\" << 150 + (spec[i][j].precursorMass-left)*800/range << \"\\\" y1=\\\"600\\\" x2=\\\"\" << 150 + (spec[i][j].precursorMass-left)*800/range << \"\\\" y2=\\\"550\\\" stroke=\\\"darkorange\\\" stroke-width=\\\"1\\\" />\" << endl;\r\n\r\n                for (size_t k=left; k<right+1; k+=100)\r\n                {\r\n\r\n                    svg << \"<line x1=\\\"\" << 150 + (k-left)*800/range << \"\\\" y1=\\\"507\\\" x2=\\\"\" << 150 + (k-left)*800/range << \"\\\" y2=\\\"493\\\" stroke=\\\"black\\\" stroke-width=\\\"1\\\" />\" << endl\r\n                        << \"<line x1=\\\"\" << 150 + (k-left)*800/range << \"\\\" y1=\\\"607\\\" x2=\\\"\" << 150 + (k-left)*800/range << \"\\\" y2=\\\"593\\\" stroke=\\\"black\\\" stroke-width=\\\"1\\\" />\" << endl\r\n                        << \"<text text-anchor=\\\"middle\\\" font-family=\\\"sans-serif\\\" x=\\\"\" << 150 + (k-left)*800/range << \"\\\" y=\\\"623\\\" fill=\\\"black\\\">\" << k << \"</text>\" << endl;\r\n                }\r\n            \r\n                double step = pow(10, floor(log10(yHeight)));\r\n                for (size_t k=step; k<yHeight+1; k+=step)\r\n                {\r\n                    svg << \"<line x1=\\\"\" << 93 << \"\\\" y1=\\\"\" << 500 - k*400/yHeight << \"\\\" x2=\\\"\" << 107 << \"\\\" y2=\\\"\" << 500 - k*400/yHeight << \"\\\" stroke=\\\"black\\\" stroke-width=\\\"1\\\" />\" << endl\r\n                        << \"<text font-family=\\\"sans-serif\\\" x=\\\"60\\\" y=\\\"\" << 506 - k*400/yHeight << \"\\\" fill=\\\"black\\\">\" << k << \"</text>\" << endl;\r\n                }\r\n\r\n                for (size_t k=0; k<spec[i][j].ms2list.size(); k++)\r\n                {\r\n                    if (spec[i][j].ms2list[k].mz < cutoff+10)\r\n                    {\r\n                        string color = \"black\";\r\n                        if (spec[i][j].ms2list[k].match == 1)\r\n                        {\r\n                            color = \"green\";\r\n                        }\r\n                        svg << \"<line x1=\\\"\" << 150 + (spec[i][j].ms2list[k].mz-left)*800/range << \"\\\" y1=\\\"500\\\" x2=\\\"\" << 150 + (spec[i][j].ms2list[k].mz-left)*800/range << \"\\\" y2=\\\"\" \r\n                            << 500 - spec[i][j].ms2list[k].intensity*400/yHeight << \"\\\" stroke=\\\"\" << color << \"\\\" stroke-width=\\\"1\\\" />\" << endl;\r\n                    }\r\n                }\r\n\r\n                for (size_t k=0; k<spec[i][j].match.size(); k++)\r\n                {\r\n                    string color = \"black\";\r\n                    if (spec[i][j].match[k].match == 1)\r\n                    {\r\n                        color = \"green\";\r\n                    }\r\n                    svg << \"<line x1=\\\"\" << 150 + (spec[i][j].match[k].mz-left)*800/range << \"\\\" y1=\\\"600\\\" x2=\\\"\" << 150 + (spec[i][j].match[k].mz-left)*800/range << \"\\\" y2=\\\"\" \r\n                        << 550 << \"\\\" stroke=\\\"\" << color << \"\\\" stroke-width=\\\"1\\\" />\" << endl\r\n                        //<< \"<text font-size=\\\"8\\\" text-anchor=\\\"middle\\\" font-family=\\\"sans-serif\\\" x=\\\"\" << 150 + spec[i][j].match[k].mz*800/range << \"\\\" y=\\\"545\\\" fill=\\\"black\\\">\" << k+1 << \"</text>\" << endl\r\n                        //<< \"<text font-family=\\\"sans-serif\\\" x=\\\"\" << 1050 << \"\\\" y=\\\"\" << 50 + 20*k << \"\\\" fill=\\\"black\\\">\" << k+1 << \". \" << \"</text>\" << endl\r\n                        << \"<text font-family=\\\"sans-serif\\\" x=\\\"\" << 1050 << \"\\\" y=\\\"\" << 165 + 20*k << \"\\\" fill=\\\"\" << color << \"\\\">\" << spec[i][j].match[k].mz << \"</text>\" << endl\r\n                        << \"<text font-family=\\\"sans-serif\\\" x=\\\"\" << 1150 << \"\\\" y=\\\"\" << 165 + 20*k << \"\\\" fill=\\\"\" << color << \"\\\">\" << spec[i][j].match[k].intensity << \"</text>\" << endl\r\n                        << \"<text font-family=\\\"sans-serif\\\" x=\\\"\" << 1250 << \"\\\" y=\\\"\" << 165 + 20*k << \"\\\" fill=\\\"\" << color << \"\\\">\" << spec[i][j].match[k].fragmentD << \"</text>\" << endl;\r\n                }\r\n\r\n                svg    << \"</svg>\" << endl << endl\r\n                    << \"</body>\" << endl << \"</html>\" << endl;\r\n\r\n                svg.close();\r\n            }\r\n        }\r\n    }\r\n    cout << \"done.\" << endl;\r\n\r\n    /*\r\n    now = time(0);\r\n    current = localtime(&now);\r\n    //cout << \"hour:\" << current->tm_hour << \" min:\" << current->tm_min << \" sec:\" << current->tm_sec << endl;\r\n    */\r\n\r\n    return 0;\r\n}\r\n\r\n// Processing of configuration/User input file\r\nMap processConfig(const string & fname)\r\n{\r\n    string str;\r\n    ifstream file(fname.c_str());\r\n    if (!file)\r\n    {\r\n        cout << \"Unable to open file.\";\r\n        getline(cin, str);\r\n        cin.get();\r\n        exit(1);\r\n    }\r\n\r\n    string line, tempLine, pStr;\r\n    Map tempMap;\r\n    while(getline(file, line))\r\n    {\r\n        if (line[line.length()-1] == 'Y')\r\n        {    \r\n            tempLine = line.substr(0, line.length() - 4);\r\n            tempMap[tempLine] = 1;\r\n        }\r\n        if (line[line.length()-1] == 'N')\r\n        {    \r\n            tempLine = line.substr(0, line.length() - 4);\r\n            tempMap[tempLine] = 0;\r\n        }\r\n        if (isdigit(line[line.length()-1]))\r\n        {    \r\n            int i = 0;\r\n            while(line[i] != '=')\r\n            {\r\n                i++;                \r\n            }\r\n            tempLine = line.substr(0, i - 1);\r\n            pStr = line.substr(i + 1, line.length() - 1);\r\n            tempMap[tempLine] = atof(pStr.c_str());\r\n        }\r\n    }\r\n    return tempMap;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n// lipid count\r\nvoid lipidCount(vector<Adduct> adducts, Map & paraMap, const HeadGroups & head, const BackBones & back, const HeadGroups & sphingoHead, const HeadGroups & cardioHead, double* count, int* pre)\r\n{ \r\n    if (paraMap[\"GP\"] == 1)\r\n    {\r\n        for  (int i = 0; i < 9; i++)\r\n        {\r\n            if (head[i].search == 1)\r\n            {\r\n                if (paraMap[\"GP.Lyso2\"] == 1)\r\n                {\r\n                    if (paraMap[\"GP.AcylBond1\"] == 1)\r\n                    {\r\n                        for (double m = paraMap[\"GP.LowerLengthLim1\"]; m <= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                        {\r\n                            for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                            {\r\n                                if ((m < 2) || (n > (m - 1)/2))\r\n                                {\r\n                                    break;\r\n                                }\r\n                                if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                {\r\n                                    break;\r\n                                }\r\n                                \r\n                                (*count)++;\r\n\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    if (paraMap[\"GP.EtherBond1\"] == 1)\r\n                    {\r\n                        for (double m = paraMap[\"GP.LowerLengthLim1\"]; m<= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                        {\r\n                            for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                            {\r\n                                if ((m < 2) || (n > m/2))\r\n                                {\r\n                                    break;\r\n                                }\r\n                                if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                {\r\n                                    break;\r\n                                }\r\n\r\n                                (*count)++;\r\n                                \r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n\r\n                if (paraMap[\"GP.AcylBond2\"] == 1)    // sn-2/acyl\r\n                {\r\n                    for (double j = paraMap[\"GP.LowerLengthLim2\"]; j <= paraMap[\"GP.UpperLengthLim2\"]; j++)\r\n                    {\r\n                        for (double k = paraMap[\"GP.LowerDoubleBondLim2\"]; k <= paraMap[\"GP.UpperDoubleBondLim2\"]; k++)\r\n                        {\r\n                            if ((j < 2) || (k > (j - 1)/2))\r\n                            {\r\n                                break;\r\n                            }\r\n                            if ((paraMap[\"GP.evenOnly\"] == 1) && (int(j) % 2 != 0))\r\n                            {\r\n                                break;\r\n                            }\r\n\r\n                            if (paraMap[\"GP.Lyso1\"] == 1)\r\n                            {\r\n\r\n                                (*count)++;\r\n                                \r\n                            }\r\n\r\n                            if (paraMap[\"GP.AcylBond1\"] == 1)\r\n                            {\r\n                                for (double m = paraMap[\"GP.LowerLengthLim1\"]; m <= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                                {\r\n                                    for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                                    {\r\n\r\n                                        if ((m < 2) || (n > (m - 1)/2))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                \r\n                                        (*count)++;                                    \r\n\r\n\r\n                                    }\r\n                                }\r\n                            }\r\n                            if (paraMap[\"GP.EtherBond1\"] == 1)\r\n                            {\r\n                                for (double m = paraMap[\"GP.LowerLengthLim1\"]; m<= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                                {\r\n                                    for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                                    {\r\n                                        if ((m < 2) || (n > m/2))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                \r\n                                        (*count)++;\r\n                                        \r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                if (paraMap[\"GP.EtherBond2\"] == 1)    // sn-2/ether\r\n                {\r\n                    for (double j = paraMap[\"GP.LowerLengthLim2\"]; j <= paraMap[\"GP.UpperLengthLim2\"]; j++)\r\n                    {\r\n                        for (double k = paraMap[\"GP.LowerDoubleBondLim2\"]; k <= paraMap[\"GP.UpperDoubleBondLim2\"]; k++)\r\n                        {\r\n                            if ((j < 2) || (k > j/2))\r\n                            {\r\n                                break;\r\n                            }\r\n                            if ((paraMap[\"GP.evenOnly\"] == 1) && (int(j) % 2 != 0))\r\n                            {\r\n                                break;\r\n                            }\r\n\r\n\r\n                            if (paraMap[\"GP.Lyso1\"] == 1)\r\n                            {\r\n                                (*count)++;\r\n                                \r\n                            }\r\n\r\n                            if (paraMap[\"GP.AcylBond1\"] == 1)\r\n                            {\r\n                                for (double m = paraMap[\"GP.LowerLengthLim1\"]; m <= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                                {\r\n                                    for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                                    {\r\n                                        if ((m < 2) || (n > (m - 1)/2))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                                                \r\n                                        (*count)++;\r\n                                        \r\n                                    }\r\n                                }\r\n                            }\r\n                            if (paraMap[\"GP.EtherBond1\"] == 1)    // sn-2/ether sn-1/ether\r\n                            {\r\n                                for (double m = paraMap[\"GP.LowerLengthLim1\"]; m<= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                                {\r\n                                    for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                                    {\r\n                                        if ((m < 2) || (n > m/2))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                \r\n                                        (*count)++;\r\n                                        \r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n    \r\n    if (paraMap[\"SP\"] == 1)\r\n    { \r\n        for (size_t i = 2; i < back.size(); i++)\r\n        {\r\n            for (int j = 0; j < 3; j++)\r\n            {\r\n                if (sphingoHead[j].search == 1)\r\n                {\r\n                    for (double m = paraMap[\"SP.LowerLength\"]; m <= paraMap[\"SP.UpperLength\"]; m++)\r\n                    {\r\n                        for (double n = paraMap[\"SP.LowerDoubleBond\"]; n <= paraMap[\"SP.UpperDoubleBond\"]; n++)\r\n                        {\r\n                            if ((m < 2) || (n > (m - 1)/2))\r\n                            {\r\n                                break;\r\n                            }\r\n                            /*if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                            {\r\n                                break;\r\n                            }*/\r\n\r\n                            (*count)++;\r\n                            \r\n                        }\r\n                    }                \r\n                }\r\n            }\r\n        }\r\n    }    \r\n    int cardioCount = 0;\r\n    int twice = 0;\r\n    if (paraMap[\"CL\"] == 1)\r\n    { \r\n        for  (int l = 0; l < 1; l++)\r\n        {\r\n            if (cardioHead[l].search == 1)\r\n            {\r\n                if (paraMap[\"CL.Acyl\"] == 1)\r\n                {\r\n                    size_t L1;\r\n                    if ((paraMap[\"CL.Lyso1\"] == 1) || (paraMap[\"CL.LowerLengthLim1a\"] < 0))\r\n                    {\r\n                        L1 = 0;\r\n                    }\r\n                    else\r\n                    {\r\n                        L1 = paraMap[\"CL.LowerLengthLim1a\"];\r\n                    }\r\n                    for (size_t j = L1; j <= paraMap[\"CL.UpperLengthLim1a\"]; j++)\r\n                    {\r\n                        if ((j != 0) && (j < paraMap[\"CL.LowerLengthLim1a\"]))\r\n                        {\r\n                            continue;\r\n                        }\r\n                        for (size_t k = paraMap[\"CL.LowerDoubleBondLim1a\"]; k <= paraMap[\"CL.UpperDoubleBondLim1a\"]; k++)\r\n                        {\r\n                            if (k > (j - 1)/2)\r\n                            {\r\n                                break;\r\n                            }\r\n                            if ((paraMap[\"CL.evenOnly\"] == 1) && (int(j) % 2 != 0))\r\n                            {\r\n                                break;\r\n                            }\r\n\r\n                            double FA1mass;\r\n\r\n                            if (j == 0)\r\n                            {\r\n                                FA1mass = H;\r\n                            }\r\n\r\n                            else\r\n                            {\r\n                                FA1mass = j*C + (2*(j-1)+1)*H - 2*k*H + O;\r\n                            }\r\n\r\n                            size_t L2;\r\n                            if ((paraMap[\"CL.Lyso2\"] == 1) || (paraMap[\"CL.LowerLengthLim2a\"] < 0))\r\n                            {\r\n                                L2 = 0;\r\n                            }\r\n                            else\r\n                            {\r\n                                L2 = paraMap[\"CL.LowerLengthLim2a\"];\r\n                            }\r\n                            \r\n                            for (size_t m = L2; m <= paraMap[\"CL.UpperLengthLim2a\"]; m++)\r\n                            {\r\n                                \r\n                                if ((m != 0) && (m < paraMap[\"CL.LowerLengthLim2a\"]))\r\n                                {\r\n                                    continue;\r\n                                }\r\n                                for (size_t n = paraMap[\"CL.LowerDoubleBondLim2a\"]; n <= paraMap[\"CL.UpperDoubleBondLim2a\"]; n++)\r\n                                {\r\n                                    if (n > (m - 1)/2)\r\n                                    {\r\n                                        break;\r\n                                    }\r\n                                    if ((paraMap[\"CL.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                    {\r\n                                        break;\r\n                                    }\r\n\r\n                                    double FA2mass;\r\n\r\n                                    if (m == 0)\r\n                                    {\r\n                                        FA2mass = H;\r\n                                    }\r\n\r\n                                    else\r\n                                    {\r\n                                        FA2mass = m*C + (2*(m-1)+1)*H - 2*n*H + O;\r\n                                    }\r\n                                    \r\n                                    size_t L3;\r\n                                    if ((paraMap[\"CL.Lyso3\"] == 1) || (paraMap[\"CL.LowerLengthLim1b\"] < 0))\r\n                                    {\r\n                                        L3 = 0;\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        L3 = paraMap[\"CL.LowerLengthLim1b\"];\r\n                                    }\r\n                                    for (size_t s = L3; s<= paraMap[\"CL.UpperLengthLim1b\"]; s++)\r\n                                    {\r\n                                        if ((s != 0) && (s < paraMap[\"CL.LowerLengthLim1b\"]))\r\n                                        {\r\n                                            continue;\r\n                                        }\r\n                                        for (size_t t = paraMap[\"CL.LowerDoubleBondLim1b\"]; t <= paraMap[\"CL.UpperDoubleBondLim1b\"]; t++)\r\n                                        {\r\n                                            if (t > (s - 1)/2)\r\n                                            {\r\n                                                break;\r\n                                            }\r\n                                            if ((paraMap[\"CL.evenOnly\"] == 1) && (int(s) % 2 != 0))\r\n                                            {\r\n                                                break;\r\n                                            }\r\n                                            double FA3mass;\r\n\r\n                                            if (s == 0)\r\n                                            {\r\n                                                FA3mass = H;\r\n                                            }\r\n\r\n                                            else\r\n                                            {\r\n                                                FA3mass = s*C + (2*(s-1)+1)*H - 2*t*H + O;\r\n                                            }\r\n\r\n                                            size_t L4;\r\n                                            if ((paraMap[\"CL.Lyso4\"] == 1) || (paraMap[\"CL.LowerLengthLim2b\"] < 0))\r\n                                            {\r\n                                                L4 = 0;\r\n                                            }\r\n                                            else\r\n                                            {\r\n                                                L4 = paraMap[\"CL.LowerLengthLim2b\"];\r\n                                            }\r\n                                            for (size_t u = L4; u<= paraMap[\"CL.UpperLengthLim2b\"]; u++)\r\n                                            {\r\n                                            if ((u != 0) && (u < paraMap[\"CL.LowerLengthLim2b\"]))\r\n                                            {\r\n                                                continue;\r\n                                            }\r\n                                                for (size_t v = paraMap[\"CL.LowerDoubleBondLim2b\"]; v <= paraMap[\"CL.UpperDoubleBondLim2b\"]; v++)\r\n                                                {\r\n                                                    if (v > (u - 1)/2)\r\n                                                    {\r\n                                                        break;\r\n                                                    }\r\n                                                    if ((paraMap[\"CL.evenOnly\"] == 1) && (int(u) % 2 != 0))\r\n                                                    {\r\n                                                        break;\r\n                                                    }\r\n\r\n                                                    double FA4mass;\r\n\r\n                                                    if (u == 0)\r\n                                                    {\r\n                                                        FA4mass = H;\r\n                                                    }\r\n\r\n                                                    else\r\n                                                    {\r\n                                                        FA4mass = u*C + (2*(u-1)+1)*H - 2*v*H + O;\r\n                                                    }\r\n\r\n                                                    if (FA1mass != H || FA2mass != H || FA3mass != H || FA4mass != H)\r\n                                                    {\r\n                                                        //(*count)++;\r\n                                                        cardioCount++;\r\n                                                    }\r\n                                                    int symmetric = 0;\r\n                                                    if ((j == s) && (m == u) && (k == t) && (n == v))\r\n                                                    {\r\n                                                        symmetric = 1;\r\n                                                    }\r\n                                                    if (symmetric == 0)\r\n                                                    {\r\n                                                        if ((((j >= paraMap[\"CL.LowerLengthLim1b\"]) && (j <= paraMap[\"CL.UpperLengthLim1b\"]) && (k >= paraMap[\"CL.LowerDoubleBondLim1b\"]) && (k <= paraMap[\"CL.UpperDoubleBondLim1b\"])) || ((j == 0) && (paraMap[\"CL.Lyso3\"] == 1)))\r\n                                                            && (((m >= paraMap[\"CL.LowerLengthLim2b\"]) && (m <= paraMap[\"CL.UpperLengthLim2b\"]) && (n >= paraMap[\"CL.LowerDoubleBondLim2b\"]) && (n <= paraMap[\"CL.UpperDoubleBondLim2b\"])) || ((m == 0) && (paraMap[\"CL.Lyso4\"] == 1)))\r\n                                                            && (((s >= paraMap[\"CL.LowerLengthLim1a\"]) && (s <= paraMap[\"CL.UpperLengthLim1a\"]) && (t >= paraMap[\"CL.LowerDoubleBondLim1a\"]) && (t <= paraMap[\"CL.UpperDoubleBondLim1a\"])) || ((s == 0) && (paraMap[\"CL.Lyso1\"] == 1)))\r\n                                                            && (((u >= paraMap[\"CL.LowerLengthLim2a\"]) && (u <= paraMap[\"CL.UpperLengthLim2a\"]) && (v >= paraMap[\"CL.LowerDoubleBondLim2a\"]) && (v <= paraMap[\"CL.UpperDoubleBondLim2a\"])) || ((u == 0) && (paraMap[\"CL.Lyso2\"] == 1))))\r\n                                                        {\r\n                                                            twice++;\r\n                                                        }\r\n                                                    }\r\n                                                }\r\n                                            }\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }        \r\n    }\r\n    (*count) += (cardioCount - twice/2);\r\n}\r\n\r\n// Generation of lipid search space\r\nvoid lipidConstructionAndScoring(vector<Adduct> adducts, Map & paraMap, const HeadGroups & head, const BackBones & back, const HeadGroups & sphingoHead, const HeadGroups & cardioHead, vector<SpectraHolder> spectraHolder, const SpectrumListPtr& SL, double* count, int* pre)\r\n{ \r\n    if (paraMap[\"GP\"] == 1)\r\n    {\r\n        int ca, ox, hy, ph, ni;\r\n        for  (int i = 0; i < 9; i++)\r\n        {\r\n            ca = 3;\r\n            hy = 5;\r\n            ox = 3;\r\n            ph = 0;\r\n            ni = 0;\r\n\r\n            if (head[i].search == 1)\r\n            {\r\n                if (head[i].name == \"Choline\")\r\n                {\r\n                    ca += 5;\r\n                    hy += 13;\r\n                    ox += 3;\r\n                    ph += 1;\r\n                    ni += 1;\r\n                }\r\n                if (head[i].name == \"Ethanolamine\")\r\n                {\r\n                    ca += 2;\r\n                    hy += 7;\r\n                    ox += 3;\r\n                    ph += 1;\r\n                    ni += 1;\r\n                }\r\n                if (head[i].name == \"Serine\")\r\n                {\r\n                    ca += 3;\r\n                    hy += 7;\r\n                    ox += 5;\r\n                    ph += 1;\r\n                    ni += 1;\r\n                }\r\n                if (head[i].name == \"Glycerol\")\r\n                {\r\n                    ca += 3;\r\n                    hy += 8;\r\n                    ox += 5;\r\n                    ph += 1;\r\n                    ni += 0;\r\n                }\r\n                if (head[i].name == \"Inositol\")\r\n                {\r\n                    ca += 6;\r\n                    hy += 12;\r\n                    ox += 8;\r\n                    ph += 1;\r\n                    ni += 0;\r\n                }\r\n                if (head[i].name == \"Phosphate\")\r\n                {\r\n                    ca += 0;\r\n                    hy += 2;\r\n                    ox += 3;\r\n                    ph += 1;\r\n                    ni += 0;\r\n                }\r\n                if (head[i].name == \"PIP\")\r\n                {\r\n                    ca += 6;\r\n                    hy += 13;\r\n                    ox += 11;\r\n                    ph += 2;\r\n                    ni += 0;\r\n                }\r\n                if (head[i].name == \"PIP2\")\r\n                {\r\n                    ca += 6;\r\n                    hy += 14;\r\n                    ox += 14;\r\n                    ph += 3;\r\n                    ni += 0;\r\n                }\r\n                if (head[i].name == \"PIP3\")\r\n                {\r\n                    ca += 6;\r\n                    hy += 15;\r\n                    ox += 17;\r\n                    ph += 4;\r\n                    ni += 0;\r\n                }\r\n\r\n                if (paraMap[\"GP.Lyso2\"] == 1)    // sn-2/lyso\r\n                {\r\n                    stringstream designation;\r\n                    designation /*<< \"Lyso\"*/ << head[i].common << \"(\";\r\n\r\n                    stringstream FA2formula;\r\n                    double FA2mass;\r\n                    FA2formula << \"H\";\r\n                    int ca1 = ca;\r\n                    int hy1 = hy;\r\n                    int ox1 = ox;\r\n                    hy1 += 1;\r\n                    FA2mass = H;\r\n                    string bond2 = \"lyso\";\r\n\r\n                    if (paraMap[\"GP.AcylBond1\"] == 1)    // sn-2/lyso sn-1/acyl \r\n                    {\r\n                        for (double m = paraMap[\"GP.LowerLengthLim1\"]; m <= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                        {\r\n                            for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                            {\r\n                                if ((m < 2) || (n > (m - 1)/2))\r\n                                {\r\n                                    break;\r\n                                }\r\n                                if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                {\r\n                                    break;\r\n                                }\r\n                                stringstream FA1formula;\r\n                                double FA1mass;\r\n                                FA1formula << \"C\" << m << \"H\" << 2*(m-1)+1-2*n << \"O\";\r\n                                int ca2 = ca1;\r\n                                int hy2 = hy1;\r\n                                int ox2 = ox1;\r\n                                ca2 += m;\r\n                                hy2 += 2*(m-1)+1-2*n;\r\n                                ox2 += 1;\r\n                                FA1mass = m*C + (2*(m-1)+1)*H - 2*n*H + O;\r\n                                string bond1 = \"acyl\";\r\n                                stringstream designationA;\r\n                                designationA << designation.str();\r\n                                designationA << m << \":\" << n << \"/\" << 0 << \":\" << 0 << \")\";\r\n                                \r\n                                stringstream lipidFormula;\r\n                                lipidFormula << \"C\" << ca2 << \"H\" << hy2;\r\n                                if (ni != 0)\r\n                                {\r\n                                    if (ni == 1)\r\n                                    {\r\n                                        lipidFormula << \"N\";\r\n                                    }\r\n                                    if (ni > 1)\r\n                                    {\r\n                                        lipidFormula << \"N\" << ni;\r\n                                    }\r\n                                        \r\n                                }\r\n                                if (ox2 == 1)\r\n                                {\r\n                                    lipidFormula << \"O\";\r\n                                }\r\n                                if (ox2 > 1)\r\n                                {\r\n                                    lipidFormula << \"O\" << ox2;\r\n                                }\r\n                                lipidFormula << \"P\";\r\n\r\n                                Lipid lipid;\r\n\r\n                                lipid.name = designationA.str();\r\n                                lipid.decoy = false;\r\n                                lipid.totalMass = back[0].mass + head[i].mass + FA1mass + FA2mass;\r\n                                lipid.lipidFormula = lipidFormula.str();\r\n                                lipid.backbone = back[0].name;\r\n                                lipid.backboneFormula = back[0].formula;\r\n                                lipid.backboneMass = back[0].mass;\r\n                                lipid.headGroup = head[i].name;\r\n                                lipid.headGroupFormula = head[i].formula;\r\n                                lipid.headGroupMass = head[i].mass;\r\n                                lipid.FA1 = FA1formula.str();\r\n                                lipid.FA1Mass = FA1mass;\r\n                                lipid.FA1DoubleBonds = n;\r\n                                lipid.SN1bond = bond1;\r\n                                lipid.FA2 = FA2formula.str();\r\n                                lipid.FA2Mass = FA2mass;\r\n                                lipid.FA2DoubleBonds = 0;\r\n                                lipid.SN2bond = bond2;\r\n                                (*count)++;\r\n                                if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                {\r\n                                    cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                                }\r\n\r\n                                precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    if (paraMap[\"GP.EtherBond1\"] == 1)    // sn-2/lyso sn-1/ether\r\n                    {\r\n                        for (double m = paraMap[\"GP.LowerLengthLim1\"]; m<= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                        {\r\n                            for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                            {\r\n                                if ((m < 2) || (n > m/2))\r\n                                {\r\n                                    break;\r\n                                }\r\n                                if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                {\r\n                                    break;\r\n                                }\r\n                                stringstream FA1formula;\r\n                                double FA1mass;\r\n                                FA1formula << \"C\" << m << \"H\" << 2*m+1-2*n;\r\n                                int ca2 = ca1;\r\n                                int hy2 = hy1;\r\n                                int ox2 = ox1;\r\n                                ca2 += m;\r\n                                hy2 += 2*m+1-2*n;\r\n                                FA1mass = m*C + (2*m+1)*H - 2*n*H;\r\n                                string bond1 = \"ether\";\r\n                                string bondDes1 = \"O-\";\r\n                                stringstream designationE;\r\n                                designationE << designation.str();\r\n                                designationE << bondDes1 << m << \":\" << n << \"/\" << 0 << \":\" << 0 << \")\";\r\n                                \r\n                                stringstream lipidFormula;\r\n                                lipidFormula << \"C\" << ca2 << \"H\" << hy2;\r\n                                if (ni != 0)\r\n                                {\r\n                                    if (ni == 1)\r\n                                    {\r\n                                        lipidFormula << \"N\";\r\n                                    }\r\n                                    if (ni > 1)\r\n                                    {\r\n                                        lipidFormula << \"N\" << ni;\r\n                                    }\r\n                                        \r\n                                }\r\n                                if (ox2 == 1)\r\n                                {\r\n                                    lipidFormula << \"O\";    \r\n                                }\r\n                                if (ox2 > 1)\r\n                                {\r\n                                    lipidFormula << \"O\" << ox2;    \r\n                                }\r\n                                lipidFormula << \"P\";\r\n\r\n                                Lipid lipid;\r\n\r\n                                lipid.name = designationE.str();\r\n                                lipid.decoy = false;\r\n                                lipid.totalMass = back[0].mass + head[i].mass + FA1mass + FA2mass;\r\n                                lipid.lipidFormula = lipidFormula.str();\r\n                                lipid.backbone = back[0].name;\r\n                                lipid.backboneFormula = back[0].formula;\r\n                                lipid.backboneMass = back[0].mass;\r\n                                lipid.headGroup = head[i].name;\r\n                                lipid.headGroupFormula = head[i].formula;\r\n                                lipid.headGroupMass = head[i].mass;\r\n                                lipid.FA1 = FA1formula.str();\r\n                                lipid.FA1Mass = FA1mass;\r\n                                lipid.FA1DoubleBonds = n;\r\n                                lipid.SN1bond = bond1;\r\n                                lipid.FA2 = FA2formula.str();\r\n                                lipid.FA2Mass = FA2mass;\r\n                                lipid.FA2DoubleBonds = 0;\r\n                                lipid.SN2bond = bond2;\r\n                                (*count)++;\r\n                                if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                {\r\n                                    cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                                }\r\n                                \r\n                                precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n\r\n                if (paraMap[\"GP.AcylBond2\"] == 1)    // sn-2/acyl\r\n                {\r\n                    \r\n                    stringstream designation;\r\n                    designation << head[i].common << \"(\";\r\n\r\n                    for (double j = paraMap[\"GP.LowerLengthLim2\"]; j <= paraMap[\"GP.UpperLengthLim2\"]; j++)\r\n                    {\r\n                        for (double k = paraMap[\"GP.LowerDoubleBondLim2\"]; k <= paraMap[\"GP.UpperDoubleBondLim2\"]; k++)\r\n                        {\r\n                            if ((j < 2) || (k > (j - 1)/2))\r\n                            {\r\n                                break;\r\n                            }\r\n                            if ((paraMap[\"GP.evenOnly\"] == 1) && (int(j) % 2 != 0))\r\n                            {\r\n                                break;\r\n                            }\r\n                            stringstream FA2formula;\r\n                            double FA2mass;\r\n                            FA2formula << \"C\" << j << \"H\" << 2*(j-1)+1-2*k << \"O\";\r\n                            int ca1 = ca;\r\n                            int hy1 = hy;\r\n                            int ox1 = ox;\r\n                            ca1 += j;\r\n                            hy1 += 2*(j-1)+1-2*k;\r\n                            ox1 += 1;\r\n                            FA2mass = j*C + (2*(j-1)+1)*H - 2*k*H + O;\r\n                            string bond2 = \"acyl\";\r\n\r\n                            if (paraMap[\"GP.Lyso1\"] == 1)\r\n                            {\r\n                                stringstream FA1formula;\r\n                                double FA1mass;\r\n                                FA1formula << \"H\";\r\n                                int ca2 = ca1;\r\n                                int hy2 = hy1;\r\n                                int ox2 = ox1;\r\n                                hy2 += 1;\r\n                                FA1mass = H;\r\n                                string bond1 = \"lyso\";\r\n                                stringstream designationA;\r\n                                designationA /*<< \"Lyso\"*/ << designation.str();\r\n                                designationA << 0 << \":\" << 0 << \"/\" << j << \":\" << k << \")\";\r\n                                \r\n                                stringstream lipidFormula;\r\n                                lipidFormula << \"C\" << ca2 << \"H\" << hy2;\r\n                                if (ni != 0)\r\n                                {\r\n                                    if (ni == 1)\r\n                                    {\r\n                                        lipidFormula << \"N\";\r\n                                    }\r\n                                    if (ni > 1)\r\n                                    {\r\n                                        lipidFormula << \"N\" << ni;\r\n                                    }\r\n                                        \r\n                                }\r\n                                if (ox2 == 1)\r\n                                {\r\n                                    lipidFormula << \"O\";    \r\n                                }\r\n                                if (ox2 > 1)\r\n                                {\r\n                                    lipidFormula << \"O\" << ox2;    \r\n                                }\r\n                                lipidFormula << \"P\";\r\n\r\n                                Lipid lipid;\r\n                                \r\n                                lipid.name = designationA.str();\r\n                                lipid.decoy = false;\r\n                                lipid.totalMass = back[0].mass + head[i].mass + FA1mass + FA2mass;\r\n                                lipid.lipidFormula = lipidFormula.str();\r\n                                lipid.backbone = back[0].name;\r\n                                lipid.backboneFormula = back[0].formula;\r\n                                lipid.backboneMass = back[0].mass;\r\n                                lipid.headGroup = head[i].name;\r\n                                lipid.headGroupFormula = head[i].formula;\r\n                                lipid.headGroupMass = head[i].mass;\r\n                                lipid.FA1 = FA1formula.str();\r\n                                lipid.FA1Mass = FA1mass;\r\n                                lipid.FA1DoubleBonds = 0;\r\n                                lipid.SN1bond = bond1;\r\n                                lipid.FA2 = FA2formula.str();\r\n                                lipid.FA2Mass = FA2mass;\r\n                                lipid.FA2DoubleBonds = k;\r\n                                lipid.SN2bond = bond2;\r\n                                (*count)++;\r\n                                if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                {\r\n                                    cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                                }\r\n                                \r\n                                precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                            }\r\n\r\n                            if (paraMap[\"GP.AcylBond1\"] == 1)    // sn-2/acyl sn-1/acyl\r\n                            {\r\n                                for (double m = paraMap[\"GP.LowerLengthLim1\"]; m <= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                                {\r\n                                    for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                                    {\r\n                                        //if (m != j && k != n)\r\n                                        //{\r\n\r\n\r\n\r\n\r\n                                        if ((m < 2) || (n > (m - 1)/2))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        stringstream FA1formula;\r\n                                        double FA1mass;\r\n                                        FA1formula << \"C\" << m << \"H\" << 2*(m-1)+1-2*n << \"O\";\r\n                                        int ca2 = ca1;\r\n                                        int hy2 = hy1;\r\n                                        int ox2 = ox1;\r\n                                        ca2 += m;\r\n                                        hy2 += 2*(m-1)+1-2*n;\r\n                                        ox2 += 1;\r\n                                        FA1mass = m*C + (2*(m-1)+1)*H - 2*n*H + O;\r\n                                        string bond1 = \"acyl\";\r\n                                        stringstream designationA;\r\n                                        designationA << designation.str();\r\n                                        designationA << m << \":\" << n << \"/\" << j << \":\" << k << \")\";\r\n                                \r\n                                        stringstream lipidFormula;\r\n                                        lipidFormula << \"C\" << ca2 << \"H\" << hy2;\r\n                                        if (ni != 0)\r\n                                        {\r\n                                            if (ni == 1)\r\n                                            {\r\n                                                lipidFormula << \"N\";\r\n                                            }\r\n                                            if (ni > 1)\r\n                                            {\r\n                                                lipidFormula << \"N\" << ni;\r\n                                            }\r\n                                        \r\n                                        }\r\n                                        if (ox2 == 1)\r\n                                        {\r\n                                            lipidFormula << \"O\";    \r\n                                        }\r\n                                        if (ox2 > 1)\r\n                                        {\r\n                                            lipidFormula << \"O\" << ox2;    \r\n                                        }\r\n                                        lipidFormula << \"P\";\r\n\r\n                                        Lipid lipid;\r\n                                \r\n                                        lipid.name = designationA.str();\r\n                                        lipid.decoy = false;\r\n                                        lipid.totalMass = back[0].mass + head[i].mass + FA1mass + FA2mass;\r\n                                        lipid.lipidFormula = lipidFormula.str();\r\n                                        lipid.backbone = back[0].name;\r\n                                        lipid.backboneFormula = back[0].formula;\r\n                                        lipid.backboneMass = back[0].mass;\r\n                                        lipid.headGroup = head[i].name;\r\n                                        lipid.headGroupFormula = head[i].formula;\r\n                                        lipid.headGroupMass = head[i].mass;\r\n                                        lipid.FA1 = FA1formula.str();\r\n                                        lipid.FA1Mass = FA1mass;\r\n                                        lipid.FA1DoubleBonds = n;\r\n                                        lipid.SN1bond = bond1;\r\n                                        lipid.FA2 = FA2formula.str();\r\n                                        lipid.FA2Mass = FA2mass;\r\n                                        lipid.FA2DoubleBonds = k;\r\n                                        lipid.SN2bond = bond2;\r\n                                        (*count)++;    \r\n                                        if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                        {\r\n                                            cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                                        }                                \r\n\r\n                                        precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                                    //    }\r\n\r\n\r\n\r\n\r\n\r\n                                    }\r\n                                }\r\n                            }\r\n                            if (paraMap[\"GP.EtherBond1\"] == 1)    // sn-2/acyl sn-1/ether\r\n                            {\r\n                                for (double m = paraMap[\"GP.LowerLengthLim1\"]; m<= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                                {\r\n                                    for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                                    {\r\n                                        if ((m < 2) || (n > m/2))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        stringstream FA1formula;\r\n                                        double FA1mass;\r\n                                        FA1formula << \"C\" << m << \"H\" << 2*m+1-2*n;\r\n                                        int ca2 = ca1;\r\n                                        int hy2 = hy1;\r\n                                        int ox2 = ox1;\r\n                                        ca2 += m;\r\n                                        hy2 += 2*m+1-2*n;\r\n                                        FA1mass = m*C + (2*m+1)*H - 2*n*H;\r\n                                        string bond1 = \"ether\";\r\n                                        string bondDes1 = \"O-\";\r\n                                        stringstream designationE;\r\n                                        designationE << designation.str();\r\n                                        designationE << bondDes1 << m << \":\" << n << \"/\" << j << \":\" << k << \")\";\r\n                                \r\n                                        stringstream lipidFormula;\r\n                                        lipidFormula << \"C\" << ca2 << \"H\" << hy2;\r\n                                        if (ni != 0)\r\n                                        {\r\n                                            if (ni == 1)\r\n                                            {\r\n                                                lipidFormula << \"N\";\r\n                                            }\r\n                                            if (ni > 1)\r\n                                            {\r\n                                                lipidFormula << \"N\" << ni;\r\n                                            }\r\n                                        \r\n                                        }\r\n                                        if (ox2 == 1)\r\n                                        {\r\n                                            lipidFormula << \"O\";    \r\n                                        }\r\n                                        if (ox2 > 1)\r\n                                        {\r\n                                            lipidFormula << \"O\" << ox2;    \r\n                                        }\r\n                                        lipidFormula << \"P\";\r\n\r\n                                        Lipid lipid;\r\n                                \r\n                                        lipid.name = designationE.str();\r\n                                        lipid.decoy = false;\r\n                                        lipid.totalMass = back[0].mass + head[i].mass + FA1mass + FA2mass;\r\n                                        lipid.lipidFormula = lipidFormula.str();\r\n                                        lipid.backbone = back[0].name;\r\n                                        lipid.backboneFormula = back[0].formula;\r\n                                        lipid.backboneMass = back[0].mass;\r\n                                        lipid.headGroup = head[i].name;\r\n                                        lipid.headGroupFormula = head[i].formula;\r\n                                        lipid.headGroupMass = head[i].mass;\r\n                                        lipid.FA1 = FA1formula.str();\r\n                                        lipid.FA1Mass = FA1mass;\r\n                                        lipid.FA1DoubleBonds = n;\r\n                                        lipid.SN1bond = bond1;\r\n                                        lipid.FA2 = FA2formula.str();\r\n                                        lipid.FA2Mass = FA2mass;\r\n                                        lipid.FA2DoubleBonds = k;\r\n                                        lipid.SN2bond = bond2;\r\n                                        (*count)++;\r\n                                        if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                        {\r\n                                            cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                                        }\r\n                                        \r\n                                        precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                if (paraMap[\"GP.EtherBond2\"] == 1)    // sn-2/ether\r\n                {\r\n                    stringstream designation;\r\n                    designation << head[i].common << \"(\";\r\n\r\n                    for (double j = paraMap[\"GP.LowerLengthLim2\"]; j <= paraMap[\"GP.UpperLengthLim2\"]; j++)\r\n                    {\r\n                        for (double k = paraMap[\"GP.LowerDoubleBondLim2\"]; k <= paraMap[\"GP.UpperDoubleBondLim2\"]; k++)\r\n                        {\r\n                            if ((j < 2) || (k > j/2))\r\n                            {\r\n                                break;\r\n                            }\r\n                            if ((paraMap[\"GP.evenOnly\"] == 1) && (int(j) % 2 != 0))\r\n                            {\r\n                                break;\r\n                            }\r\n                            stringstream FA2formula;\r\n                            double FA2mass;\r\n                            FA2formula << \"C\" << j << \"H\" << 2*j+1-2*k;\r\n                            int ca1 = ca;\r\n                            int hy1 = hy;\r\n                            int ox1 = ox;\r\n                            ca1 += j;\r\n                            hy1 += 2*j+1-2*k;\r\n                            FA2mass = j*C + (2*j+1)*H - 2*k*H;\r\n                            string bond2 = \"ether\";\r\n\r\n                            if (paraMap[\"GP.Lyso1\"] == 1)\r\n                            {\r\n                                stringstream FA1formula;\r\n                                double FA1mass;\r\n                                FA1formula << \"H\";\r\n                                int ca2 = ca1;\r\n                                int hy2 = hy1;\r\n                                int ox2 = ox1;\r\n                                hy2 += 1;\r\n                                FA1mass = H;\r\n                                string bond1 = \"lyso\";\r\n                                stringstream designationA;\r\n                                designationA /*<< \"Lyso\"*/ << designation.str();\r\n                                designationA << 0 << \":\" << 0 << \"/\" << \"O-\" << j << \":\" << k << \")\";\r\n                                \r\n                                stringstream lipidFormula;\r\n                                lipidFormula << \"C\" << ca2 << \"H\" << hy2;\r\n                                if (ni != 0)\r\n                                {\r\n                                    if (ni == 1)\r\n                                    {\r\n                                        lipidFormula << \"N\";\r\n                                    }\r\n                                    if (ni > 1)\r\n                                    {\r\n                                        lipidFormula << \"N\" << ni;\r\n                                    }\r\n                                        \r\n                                }\r\n                                if (ox2 == 1)\r\n                                {\r\n                                    lipidFormula << \"O\";    \r\n                                }\r\n                                if (ox2 > 1)\r\n                                {\r\n                                    lipidFormula << \"O\" << ox2;    \r\n                                }\r\n                                lipidFormula << \"P\";\r\n\r\n                                Lipid lipid;\r\n                                                                \r\n                                lipid.name = designationA.str();\r\n                                lipid.decoy = false;\r\n                                lipid.totalMass = back[0].mass + head[i].mass + FA1mass + FA2mass;\r\n                                lipid.lipidFormula = lipidFormula.str();\r\n                                lipid.backbone = back[0].name;\r\n                                lipid.backboneFormula = back[0].formula;\r\n                                lipid.backboneMass = back[0].mass;\r\n                                lipid.headGroup = head[i].name;\r\n                                lipid.headGroupFormula = head[i].formula;\r\n                                lipid.headGroupMass = head[i].mass;\r\n                                lipid.FA1 = FA1formula.str();\r\n                                lipid.FA1Mass = FA1mass;\r\n                                lipid.FA1DoubleBonds = 0;\r\n                                lipid.SN1bond = bond1;\r\n                                lipid.FA2 = FA2formula.str();\r\n                                lipid.FA2Mass = FA2mass;\r\n                                lipid.FA2DoubleBonds = k;\r\n                                lipid.SN2bond = bond2;\r\n                                (*count)++;\r\n                                if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                {\r\n                                    cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"% done\";\r\n                                }\r\n                                \r\n                                precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                            }\r\n\r\n                            if (paraMap[\"GP.AcylBond1\"] == 1)    // sn-2/ether sn-1/acyl\r\n                            {\r\n                                for (double m = paraMap[\"GP.LowerLengthLim1\"]; m <= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                                {\r\n                                    for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                                    {\r\n                                        if ((m < 2) || (n > (m - 1)/2))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        stringstream FA1formula;\r\n                                        double FA1mass;\r\n                                        FA1formula << \"C\" << m << \"H\" << 2*(m-1)+1-2*n << \"O\";\r\n                                        int ca2 = ca1;\r\n                                        int hy2 = hy1;\r\n                                        int ox2 = ox1;\r\n                                        ca2 += m;\r\n                                        hy2 += 2*(m-1)+1-2*n;\r\n                                        ox2 += 1;\r\n                                        FA1mass = m*C + (2*(m-1)+1)*H - 2*n*H + O;\r\n                                        string bond1 = \"acyl\";\r\n                                        stringstream designationA;\r\n                                        designationA << designation.str();\r\n                                        designationA << m << \":\" << n << \"/\" << \"O-\" << j << \":\" << k << \")\";\r\n                                \r\n                                        stringstream lipidFormula;\r\n                                        lipidFormula << \"C\" << ca2 << \"H\" << hy2;\r\n                                        if (ni != 0)\r\n                                        {\r\n                                            if (ni == 1)\r\n                                            {\r\n                                                lipidFormula << \"N\";\r\n                                            }\r\n                                            if (ni > 1)\r\n                                            {\r\n                                                lipidFormula << \"N\" << ni;\r\n                                            }\r\n                                        \r\n                                        }\r\n                                        if (ox2 == 1)\r\n                                        {\r\n                                            lipidFormula << \"O\";    \r\n                                        }\r\n                                        if (ox2 > 1)\r\n                                        {\r\n                                            lipidFormula << \"O\" << ox2;    \r\n                                        }\r\n                                        lipidFormula << \"P\";\r\n\r\n                                        Lipid lipid;\r\n                                                                \r\n                                        lipid.name = designationA.str();\r\n                                        lipid.decoy = false;\r\n                                        lipid.totalMass = back[0].mass + head[i].mass + FA1mass + FA2mass;\r\n                                        lipid.lipidFormula = lipidFormula.str();\r\n                                        lipid.backbone = back[0].name;\r\n                                        lipid.backboneFormula = back[0].formula;\r\n                                        lipid.backboneMass = back[0].mass;\r\n                                        lipid.headGroup = head[i].name;\r\n                                        lipid.headGroupFormula = head[i].formula;\r\n                                        lipid.headGroupMass = head[i].mass;\r\n                                        lipid.FA1 = FA1formula.str();\r\n                                        lipid.FA1Mass = FA1mass;\r\n                                        lipid.FA1DoubleBonds = n;\r\n                                        lipid.SN1bond = bond1;\r\n                                        lipid.FA2 = FA2formula.str();\r\n                                        lipid.FA2Mass = FA2mass;\r\n                                        lipid.FA2DoubleBonds = k;\r\n                                        lipid.SN2bond = bond2;\r\n                                        (*count)++;\r\n                                        if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                        {\r\n                                            cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                                        }\r\n                                        \r\n                                        precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                                    }\r\n                                }\r\n                            }\r\n                            if (paraMap[\"GP.EtherBond1\"] == 1)    // sn-2/ether sn-1/ether\r\n                            {\r\n                                for (double m = paraMap[\"GP.LowerLengthLim1\"]; m<= paraMap[\"GP.UpperLengthLim1\"]; m++)\r\n                                {\r\n                                    for (double n = paraMap[\"GP.LowerDoubleBondLim1\"]; n <= paraMap[\"GP.UpperDoubleBondLim1\"]; n++)\r\n                                    {\r\n                                        if ((m < 2) || (n > m/2))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                        {\r\n                                            break;\r\n                                        }\r\n                                        stringstream FA1formula;\r\n                                        double FA1mass;\r\n                                        FA1formula << \"C\" << m << \"H\" << 2*m+1-2*n;\r\n                                        int ca2 = ca1;\r\n                                        int hy2 = hy1;\r\n                                        int ox2 = ox1;\r\n                                        ca2 += m;\r\n                                        hy2 += 2*m+1-2*n;\r\n                                        FA1mass = m*C + (2*m+1)*H - 2*n*H;\r\n                                        string bond1 = \"ether\";\r\n                                        string bondDes1 = \"O-\";\r\n                                        stringstream designationE;\r\n                                        designationE << designation.str();\r\n                                        designationE << bondDes1 << m << \":\" << n << \"/\" << \"O-\" << j << \":\" << k << \")\";\r\n                                \r\n                                        stringstream lipidFormula;\r\n                                        lipidFormula << \"C\" << ca2 << \"H\" << hy2;\r\n                                        if (ni != 0)\r\n                                        {\r\n                                            if (ni == 1)\r\n                                            {\r\n                                                lipidFormula << \"N\";\r\n                                            }\r\n                                            if (ni > 1)\r\n                                            {\r\n                                                lipidFormula << \"N\" << ni;\r\n                                            }\r\n                                        \r\n                                        }\r\n                                        if (ox2 == 1)\r\n                                        {\r\n                                            lipidFormula << \"O\";    \r\n                                        }\r\n                                        if (ox2 > 1)\r\n                                        {\r\n                                            lipidFormula << \"O\" << ox2;    \r\n                                        }\r\n                                        lipidFormula << \"P\";\r\n\r\n                                        Lipid lipid;\r\n                                \r\n                                        lipid.name = designationE.str();\r\n                                        lipid.decoy = false;\r\n                                        lipid.totalMass = back[0].mass + head[i].mass + FA1mass + FA2mass;\r\n                                        lipid.lipidFormula = lipidFormula.str();\r\n                                        lipid.backbone = back[0].name;\r\n                                        lipid.backboneFormula = back[0].formula;\r\n                                        lipid.backboneMass = back[0].mass;\r\n                                        lipid.headGroup = head[i].name;\r\n                                        lipid.headGroupFormula = head[i].formula;\r\n                                        lipid.headGroupMass = head[i].mass;\r\n                                        lipid.FA1 = FA1formula.str();\r\n                                        lipid.FA1Mass = FA1mass;\r\n                                        lipid.FA1DoubleBonds = n;\r\n                                        lipid.SN1bond = bond1;\r\n                                        lipid.FA2 = FA2formula.str();\r\n                                        lipid.FA2Mass = FA2mass;\r\n                                        lipid.FA2DoubleBonds = k;\r\n                                        lipid.SN2bond = bond2;\r\n                                        (*count)++;\r\n                                        if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                        {\r\n                                            cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                                        }\r\n                                        \r\n                                        precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n    \r\n    if (paraMap[\"SP\"] == 1)\r\n    { \r\n        int ca, hy, ni, ox, ph;\r\n        for (size_t i = 2; i < back.size(); i++)\r\n        {\r\n            ca = back[i].ca;\r\n            hy = back[i].hy;\r\n            ni = back[i].ni;\r\n            ox = back[i].ox;\r\n            ph = 0;\r\n            for (int j = 0; j < 3; j++)\r\n            {\r\n                if (sphingoHead[j].search == 1)\r\n                {\r\n\r\n                    if (sphingoHead[j].name == \"Choline\")\r\n                    {\r\n                        ca += 5;\r\n                        hy += 13;\r\n                        ox += 3;\r\n                        ph += 1;\r\n                        ni += 1;\r\n                    }\r\n                    if (sphingoHead[j].name == \"Ethanolamine\")\r\n                    {\r\n                        ca += 2;\r\n                        hy += 7;\r\n                        ox += 3;\r\n                        ph += 1;\r\n                        ni += 1;\r\n                    }\r\n                    if (sphingoHead[j].name == \"Inositol\")\r\n                    {\r\n                        ca += 6;\r\n                        hy += 12;\r\n                        ox += 8;\r\n                        ph += 1;\r\n                        ni += 0;\r\n                    }\r\n\r\n                    stringstream designation;\r\n                    //designation << sphingoHead[j].common << \"(d\" << back[i].length << \":\";\r\n\r\n                    if (back[i].formula == \"Sphingosine\")\r\n                    {\r\n                        designation << sphingoHead[j].common << \"(d\" << back[i].length << \":\" << \"1/\";\r\n                    }\r\n                    if (back[i].formula == \"Sphinganine\")\r\n                    {\r\n                        designation << sphingoHead[j].common << \"(d\" << back[i].length << \":\" << \"0/\";\r\n                    }\r\n                    if (back[i].formula == \"Phytosphingosine\")\r\n                    {\r\n                        designation << sphingoHead[j].common << \"(t\" << back[i].length << \":\" << \"0/\";\r\n                    }\r\n                    if (back[i].formula == \"Sphingadienine\")\r\n                    {\r\n                        designation << sphingoHead[j].common << \"(d\" << back[i].length << \":\" << \"2/\";\r\n                    }\r\n\r\n                    for (double m = paraMap[\"SP.LowerLength\"]; m <= paraMap[\"SP.UpperLength\"]; m++)\r\n                    {\r\n                        for (double n = paraMap[\"SP.LowerDoubleBond\"]; n <= paraMap[\"SP.UpperDoubleBond\"]; n++)\r\n                        {\r\n                            stringstream FAdesig;\r\n\r\n                            int ca1 = ca;\r\n                            int hy1 = hy;\r\n                            int ox1 = ox;\r\n\r\n                            FAdesig << designation.str() << m << \":\" << n << \")\";\r\n                            if ((m < 2) || (n > (m - 1)/2))\r\n                            {\r\n                                break;\r\n                            }\r\n                            /*if ((paraMap[\"GP.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                            {\r\n                                break;\r\n                            }*/\r\n                            stringstream FAformula;\r\n                            double FAmass;\r\n                            if (m == 0)\r\n                            {\r\n                                FAformula << \"H\";\r\n                                FAmass = H;\r\n                                hy1 += 1;\r\n\r\n                            }\r\n                            else if (m == 1)\r\n                            {\r\n                                FAformula << \"C\" << \"O\" << \"H\";\r\n                                FAmass = C + H + O;\r\n                                ca1 += 1;\r\n                                hy1 += 1;\r\n                                ox1 += 1;\r\n                            }\r\n                            else\r\n                            {\r\n                                FAformula << \"C\" << m << \"H\" << 2*(m-1)+1-2*n << \"O\";\r\n                                FAmass = m*C + (2*(m-1)+1)*H - 2*n*H + O;\r\n                                ca1 += m;\r\n                                hy1 += 2*(m-1)+1-2*n;\r\n                                ox1 += 1;\r\n                            }\r\n\r\n                            stringstream lipidFormula;\r\n                            lipidFormula << \"C\" << ca1 << \"H\" << hy1;\r\n                            if (ni != 0)\r\n                            {\r\n                                if (ni == 1)\r\n                                {\r\n                                    lipidFormula << \"N\";\r\n                                }\r\n                                if (ni > 1)\r\n                                {\r\n                                    lipidFormula << \"N\" << ni;\r\n                                }\r\n                                        \r\n                            }\r\n                            if (ox1 == 1)\r\n                            {\r\n                                lipidFormula << \"O\";    \r\n                            }\r\n                            if (ox1 > 1)\r\n                            {\r\n                                lipidFormula << \"O\" << ox1;    \r\n                            }\r\n                            lipidFormula << \"P\";\r\n\r\n                            Lipid lipid;\r\n                                \r\n                            lipid.name = FAdesig.str();\r\n                            lipid.decoy = false;\r\n                            lipid.totalMass = back[i].mass + sphingoHead[j].mass + FAmass;\r\n                            lipid.lipidFormula = lipidFormula.str();\r\n                            lipid.backbone = back[i].name;\r\n                            lipid.backboneFormula = back[i].formula;\r\n                            lipid.backboneMass = back[i].mass;\r\n                            lipid.headGroup = sphingoHead[j].name;\r\n                            lipid.headGroupFormula = sphingoHead[j].formula;\r\n                            lipid.headGroupMass = sphingoHead[j].mass;\r\n                            lipid.FA1 = FAformula.str();\r\n                            lipid.FA1Mass = FAmass;\r\n                            lipid.FA1DoubleBonds = n;\r\n                            lipid.FA2 = \"-\";\r\n                            lipid.FA2Mass = 0;\r\n                            lipid.FA2DoubleBonds = 0;\r\n                            lipid.FA3 = \"-\";\r\n                            lipid.FA3Mass = 0;\r\n                            lipid.FA3DoubleBonds = 0;\r\n                            lipid.FA4 = \"-\";\r\n                            lipid.FA4Mass = 0;\r\n                            lipid.FA4DoubleBonds = 0;\r\n                            (*count)++;\r\n                            if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                            {\r\n                                cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                            }\r\n                            \r\n                            precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                        }\r\n                    }                \r\n                }\r\n            }\r\n        }\r\n    }    \r\n    \r\n    if (paraMap[\"CL\"] == 1)\r\n    { \r\n        int ca, hy, ox; //ph;\r\n        for  (int l = 0; l < 1; l++)\r\n        {\r\n            if (cardioHead[l].search == 1)\r\n            {\r\n                ca = 9;\r\n                hy = 18;\r\n                ox = 13;\r\n                //ph = 2;\r\n\r\n                if (paraMap[\"CL.Acyl\"] == 1)\r\n                {\r\n                    size_t L1;\r\n                    if ((paraMap[\"CL.Lyso1\"] == 1) || (paraMap[\"CL.LowerLengthLim1a\"] < 0))\r\n                    {\r\n                        L1 = 0;\r\n                    }\r\n                    else\r\n                    {\r\n                        L1 = paraMap[\"CL.LowerLengthLim1a\"];\r\n                    }\r\n                    for (size_t j = L1; j <= paraMap[\"CL.UpperLengthLim1a\"]; j++)\r\n                    {\r\n                        if ((j != 0) && (j < paraMap[\"CL.LowerLengthLim1a\"]))\r\n                        {\r\n                            continue;\r\n                        }\r\n                        for (size_t k = paraMap[\"CL.LowerDoubleBondLim1a\"]; k <= paraMap[\"CL.UpperDoubleBondLim1a\"]; k++)\r\n                        {\r\n                            if (k > (j - 1)/2)\r\n                            {\r\n                                break;\r\n                            }\r\n                            if ((paraMap[\"CL.evenOnly\"] == 1) && (int(j) % 2 != 0))\r\n                            {\r\n                                break;\r\n                            }\r\n                            stringstream FA1formula;\r\n                            double FA1mass;\r\n                            string bond1 = \"acyl\";\r\n                            int ca1 = ca;\r\n                            int hy1 = hy;\r\n                            int ox1 = ox;\r\n                            if (j == 0)\r\n                            {\r\n                                FA1formula << \"H\";\r\n                                FA1mass = H;\r\n                                hy1 += 1;\r\n                            }\r\n                            //else if (j == 1)\r\n                            //{\r\n                                //FA1formula << \"C\" << \"O\" << \"H\";\r\n                                //FA1mass = C + H + O;\r\n                            //}\r\n                            else\r\n                            {\r\n                                FA1formula << \"C\" << j << \"H\" << 2*(j-1)+1-2*k << \"O\";\r\n                                FA1mass = j*C + (2*(j-1)+1)*H - 2*k*H + O;\r\n                                ca1 += j;\r\n                                hy1 += 2*(j-1)+1-2*k;\r\n                                ox1 += 1;\r\n\r\n                            }\r\n\r\n                            size_t L2;\r\n                            if ((paraMap[\"CL.Lyso2\"] == 1) || (paraMap[\"CL.LowerLengthLim2a\"] < 0))\r\n                            {\r\n                                L2 = 0;\r\n                            }\r\n                            else\r\n                            {\r\n                                L2 = paraMap[\"CL.LowerLengthLim2a\"];\r\n                            }\r\n                            \r\n                            for (size_t m = L2; m <= paraMap[\"CL.UpperLengthLim2a\"]; m++)\r\n                            {\r\n                                \r\n                                if ((m != 0) && (m < paraMap[\"CL.LowerLengthLim2a\"]))\r\n                                {\r\n                                    continue;\r\n                                }\r\n                                for (size_t n = paraMap[\"CL.LowerDoubleBondLim2a\"]; n <= paraMap[\"CL.UpperDoubleBondLim2a\"]; n++)\r\n                                {\r\n                                    if (n > (m - 1)/2)\r\n                                    {\r\n                                        break;\r\n                                    }\r\n                                    if ((paraMap[\"CL.evenOnly\"] == 1) && (int(m) % 2 != 0))\r\n                                    {\r\n                                        break;\r\n                                    }\r\n                                    stringstream FA2formula;\r\n                                    double FA2mass;\r\n                                    string bond2 = \"acyl\";\r\n                                    int ca2 = ca1;\r\n                                    int hy2 = hy1;\r\n                                    int ox2 = ox1;\r\n                                    if (m == 0)\r\n                                    {\r\n                                        FA2formula << \"H\";\r\n                                        FA2mass = H;\r\n                                        hy2 += 1;\r\n                                    }\r\n                                    //else if (m == 1)\r\n                                    //{\r\n                                        //FA2formula << \"C\" << \"O\" << \"H\";\r\n                                        //FA2mass = C + H + O;\r\n                                    //}\r\n                                    else\r\n                                    {\r\n                                        FA2formula << \"C\" << m << \"H\" << 2*(m-1)+1-2*n << \"O\";\r\n                                        FA2mass = m*C + (2*(m-1)+1)*H - 2*n*H + O;\r\n                                        ca2 += m;\r\n                                        hy2 += 2*(m-1)+1-2*n;\r\n                                        ox2 += 1;\r\n                                    }\r\n                                    \r\n                                    size_t L3;\r\n                                    if ((paraMap[\"CL.Lyso3\"] == 1) || (paraMap[\"CL.LowerLengthLim1b\"] < 0))\r\n                                    {\r\n                                        L3 = 0;\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        L3 = paraMap[\"CL.LowerLengthLim1b\"];\r\n                                    }\r\n                                    for (size_t s = L3; s<= paraMap[\"CL.UpperLengthLim1b\"]; s++)\r\n                                    {\r\n                                        if ((s != 0) && (s < paraMap[\"CL.LowerLengthLim1b\"]))\r\n                                        {\r\n                                            continue;\r\n                                        }\r\n                                        for (size_t t = paraMap[\"CL.LowerDoubleBondLim1b\"]; t <= paraMap[\"CL.UpperDoubleBondLim1b\"]; t++)\r\n                                        {\r\n                                            if (t > (s - 1)/2)\r\n                                            {\r\n                                                break;\r\n                                            }\r\n                                            if ((paraMap[\"CL.evenOnly\"] == 1) && (int(s) % 2 != 0))\r\n                                            {\r\n                                                break;\r\n                                            }\r\n                                            stringstream FA3formula;\r\n                                            double FA3mass;\r\n                                            string bond3 = \"acyl\";\r\n                                            int ca3 = ca2;\r\n                                            int hy3 = hy2;\r\n                                            int ox3 = ox2;\r\n                                            if (s == 0)\r\n                                            {\r\n                                                FA3formula << \"H\";\r\n                                                FA3mass = H;\r\n                                                hy3 += 1;\r\n                                            }\r\n                                            //else if (s == 1)\r\n                                            //{\r\n                                                //FA3formula << \"C\" << \"O\" << \"H\";\r\n                                                //FA3mass = C + H + O;\r\n                                            //}\r\n                                            else\r\n                                            {\r\n                                                FA3formula << \"C\" << s << \"H\" << 2*(s-1)+1-2*t << \"O\";\r\n                                                FA3mass = s*C + (2*(s-1)+1)*H - 2*t*H + O;\r\n                                                ca3 += s;\r\n                                                hy3 += 2*(s-1)+1-2*t;\r\n                                                ox3 += 1;\r\n                                            }\r\n\r\n                                            size_t L4;\r\n                                            if ((paraMap[\"CL.Lyso4\"] == 1) || (paraMap[\"CL.LowerLengthLim2b\"] < 0))\r\n                                            {\r\n                                                L4 = 0;\r\n                                            }\r\n                                            else\r\n                                            {\r\n                                                L4 = paraMap[\"CL.LowerLengthLim2b\"];\r\n                                            }\r\n                                            for (size_t u = L4; u<= paraMap[\"CL.UpperLengthLim2b\"]; u++)\r\n                                            {\r\n                                            if ((u != 0) && (u < paraMap[\"CL.LowerLengthLim2b\"]))\r\n                                            {\r\n                                                continue;\r\n                                            }\r\n                                                for (size_t v = paraMap[\"CL.LowerDoubleBondLim2b\"]; v <= paraMap[\"CL.UpperDoubleBondLim2b\"]; v++)\r\n                                                {\r\n                                                    if (v > (u - 1)/2)\r\n                                                    {\r\n                                                        break;\r\n                                                    }\r\n                                                    if ((paraMap[\"CL.evenOnly\"] == 1) && (int(u) % 2 != 0))\r\n                                                    {\r\n                                                        break;\r\n                                                    }\r\n                                                    stringstream FA4formula;\r\n                                                    double FA4mass;\r\n                                                    string bond4 = \"acyl\";\r\n                                                    int ca4 = ca3;\r\n                                                    int hy4 = hy3;\r\n                                                    int ox4 = ox3;\r\n                                                    if (u == 0)\r\n                                                    {\r\n                                                        FA4formula << \"H\";\r\n                                                        FA4mass = H;\r\n                                                        hy4 += 1;\r\n                                                    }\r\n                                                    //else if (u == 1)\r\n                                                    //{\r\n                                                        //FA4formula << \"C\" << \"O\" << \"H\";\r\n                                                        //FA4mass = C + H + O;\r\n                                                    //}\r\n                                                    else\r\n                                                    {\r\n                                                        FA4formula << \"C\" << u << \"H\" << 2*(u-1)+1-2*v << \"O\";\r\n                                                        FA4mass = u*C + (2*(u-1)+1)*H - 2*v*H + O;\r\n                                                        ca4 += u;\r\n                                                        hy4 += 2*(u-1)+1-2*v;\r\n                                                        ox4 += 1;\r\n                                                    }\r\n\r\n                                                    stringstream designation;\r\n                                                    designation << \"CL\" << \"(\" << j << \":\" << k << \"/\" << m << \":\" << n << \"/\" << s << \":\" << t << \"/\" << u << \":\" << v << \")\";\r\n\r\n                                                    if (FA1mass != H || FA2mass != H || FA3mass != H || FA4mass != H)\r\n                                                    {\r\n                                                        bool useLipid = true;\r\n                                                        \r\n                                                        vector<size_t> clvR(8);\r\n                                                        clvR[0] = s;\r\n                                                        clvR[1] = t;\r\n                                                        clvR[2] = u;\r\n                                                        clvR[3] = v;\r\n                                                        clvR[4] = j;\r\n                                                        clvR[5] = k;\r\n                                                        clvR[6] = m;\r\n                                                        clvR[7] = n;\r\n\r\n                                                        size_t CLsize = CLspecies.size();\r\n                                                        for (size_t c = 0; c<CLsize; c++)\r\n                                                        {\r\n                                                            if (CLspecies[c] == clvR)\r\n                                                            {\r\n                                                                useLipid = false;\r\n                                                                break;\r\n                                                            }\r\n                                                        }                                                        \r\n                                                                                                        \r\n                                                        if (useLipid == true)\r\n                                                        {\r\n                                                            vector<size_t> clv(8);\r\n                                                            clv[0] = j;\r\n                                                            clv[1] = k;\r\n                                                            clv[2] = m;\r\n                                                            clv[3] = n;\r\n                                                            clv[4] = s;\r\n                                                            clv[5] = t;\r\n                                                            clv[6] = u;\r\n                                                            clv[7] = v;\r\n                                                            CLspecies.push_back(clv);\r\n\r\n                                                            stringstream lipidFormula;\r\n                                                            lipidFormula << \"C\" << ca4 << \"H\" << hy4;\r\n\r\n                                                            if (ox4 == 1)\r\n                                                            {\r\n                                                                lipidFormula << \"O\";    \r\n                                                            }\r\n                                                            if (ox4 > 1)\r\n                                                            {\r\n                                                                lipidFormula << \"O\" << ox4;    \r\n                                                            }\r\n                                                            lipidFormula << \"P\" << 2;\r\n\r\n                                                            Lipid lipid;\r\n                                \r\n                                                            lipid.name = designation.str();\r\n                                                            lipid.decoy = false;\r\n                                                            lipid.totalMass = back[1].mass + cardioHead[l].mass + FA1mass + FA2mass + FA3mass + FA4mass;\r\n                                                            lipid.lipidFormula = lipidFormula.str();\r\n                                                            lipid.backbone = back[1].name;\r\n                                                            lipid.backboneFormula = back[1].formula;\r\n                                                            lipid.backboneMass = back[1].mass;\r\n                                                            lipid.headGroup = cardioHead[l].name;\r\n                                                            lipid.headGroupFormula = cardioHead[l].formula;\r\n                                                            lipid.headGroupMass = cardioHead[l].mass;\r\n                                                            lipid.FA1 = FA1formula.str();\r\n                                                            lipid.FA1Mass = FA1mass;\r\n                                                            lipid.FA1DoubleBonds = k;\r\n                                                            lipid.SN1bond = bond1;\r\n                                                            lipid.FA2 = FA2formula.str();\r\n                                                            lipid.FA2Mass = FA2mass;\r\n                                                            lipid.FA2DoubleBonds = n;\r\n                                                            lipid.SN2bond = bond2;\r\n                                                            lipid.FA3 = FA3formula.str();\r\n                                                            lipid.FA3Mass = FA3mass;\r\n                                                            lipid.FA3DoubleBonds = t;\r\n                                                            lipid.SN3bond = bond3;\r\n                                                            lipid.FA4 = FA4formula.str();\r\n                                                            lipid.FA4Mass = FA4mass;\r\n                                                            lipid.FA4DoubleBonds = v;\r\n                                                            lipid.SN4bond = bond4;\r\n                                                            (*count)++;\r\n                                                            if (round(100.0*(*count)/lipCount) > round(100.0*((*count)-1)/lipCount))\r\n                                                            {\r\n                                                                cout << string(70, '\\b') << \"Comparing experimental and theoretical spectra. Progress...... \" << round(100.0*(*count)/lipCount) << \"%\";\r\n                                                            }\r\n                                                        \r\n                                                            precursorListConstruction(adducts, lipid, paraMap, spectraHolder, SL, pre);\r\n                                                        }\r\n                                                    }\r\n                                                }\r\n                                            }\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n// precursor list construction\r\nvoid precursorListConstruction(vector<Adduct> adducts, Lipid lipid, Map & paraMap, vector<SpectraHolder> spectraHolder, const SpectrumListPtr& SL, int* pre)\r\n{\r\n    int index = 0; \r\n    string backsub = lipid.backbone.substr(5, 6);\r\n    if (lipid.backbone == \"Glycerol\" || backsub == \"Sphing\" || backsub == \"Phytos\")\r\n    {\r\n        for (size_t i=0; i<adducts.size(); i++)\r\n        {\r\n            if ((paraMap[\"ESI.pos\"] == 1) && (adducts[i].polarity == \"positive\"))\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = adducts[i].description;\r\n                lipid.precursors[index].adduct = adducts[i].name;\r\n                lipid.precursors[index].adductMass = adducts[i].mass;\r\n                lipid.precursors[index].adductType = adducts[i].type;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + adducts[i].mass;\r\n                index++;\r\n                //(*pre)++; \r\n            }\r\n        }\r\n        /*\r\n        if (paraMap[\"ESI.pos\"] == 1) //positive mode\r\n        {\r\n            if (paraMap[\"Add.Pro\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"protonated\";\r\n                lipid.precursors[index].adduct = \"None\";\r\n                lipid.precursors[index].adductMass = 0;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + H;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (paraMap[\"Add.Na\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"Sodium adduct\";\r\n                lipid.precursors[index].adduct = \"Na\";\r\n                lipid.precursors[index].adductMass = Na;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + Na;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (paraMap[\"Add.NH4\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"Ammonium adduct\";\r\n                lipid.precursors[index].adduct = \"NH4\";\r\n                lipid.precursors[index].adductMass = N + 4*H;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + N + 4*H;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (paraMap[\"Add.Li\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"Lithium adduct\";\r\n                lipid.precursors[index].adduct = \"Li\";\r\n                lipid.precursors[index].adductMass = Li;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + Li;\r\n                index++;\r\n                //(*pre)++;\r\n                \r\n            }\r\n\r\n            if (paraMap[\"Add.K\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"Potassium adduct\";\r\n                lipid.precursors[index].adduct = \"K\";\r\n                lipid.precursors[index].adductMass = K;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + K;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n        }\r\n        */\r\n        if (paraMap[\"ESI.neg\"] == 1) //negative mode\r\n        {\r\n            \r\n            if (paraMap[\"Add.Depro\"] == 1 && lipid.headGroup != \"Choline\")\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"deprotonated\";\r\n                lipid.precursors[index].adduct = \"-H\";\r\n                lipid.precursors[index].adductMass = 0;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - H;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n            \r\n            if (paraMap[\"Add.Depro\"] == 1 && lipid.headGroup == \"PIP\")\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"deprotonatedX2\";\r\n                lipid.precursors[index].adduct = \"-2H\";\r\n                lipid.precursors[index].adductMass = 0;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = (lipid.totalMass - 2*H)/2;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n            \r\n            if (paraMap[\"Add.Depro\"] == 1 && lipid.headGroup == \"PIP2\")\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"deprotonatedX2\";\r\n                lipid.precursors[index].adduct = \"-2H\";\r\n                lipid.precursors[index].adductMass = 0;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = (lipid.totalMass - 2*H)/2;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n            /*\r\n            if (paraMap[\"Add.Depro\"] == 1 && lipid.headGroup == \"PIP3\")\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"deprotonatedX2\";\r\n                lipid.precursors[index].adduct = \"-2H\";\r\n                lipid.precursors[index].adductMass = 0;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = (lipid.totalMass - 2*H)/2;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n            */\r\n            if (paraMap[\"Add.Cl\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"Cl adduct\";\r\n                lipid.precursors[index].adduct = \"+Cl\";\r\n                lipid.precursors[index].adductMass = Cl;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + Cl;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (paraMap[\"Add.HCOO\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"formate adduct\";\r\n                lipid.precursors[index].adduct = \"+HCO2\";\r\n                lipid.precursors[index].adductMass = C + H + 2*O;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + C + H + 2*O;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (paraMap[\"Add.CH3COO\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"acetate adduct\";\r\n                lipid.precursors[index].adduct = \"+CH3CO2\";\r\n                lipid.precursors[index].adductMass = 2*C + 3*H + 2*O;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + 2*C + 3*H + 2*O;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (lipid.headGroup == \"Choline\" && (paraMap[\"Add.Cl\"] == 1 || paraMap[\"Add.CH3COO\"] == 1 || paraMap[\"Add.HCOO\"] == 1))\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"loss of adduct and methyl group\";\r\n                lipid.precursors[index].adduct = \"-CH3\";\r\n                lipid.precursors[index].adductMass = 0;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - C - 3*H;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n            /*\r\n            if (lipid.headGroup == \"Glycerol\")\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"deprotonated; loss of H2O\";\r\n                lipid.precursors[index].adduct = \"none\";\r\n                lipid.precursors[index].adductMass = 0;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - 3*H - O;\r\n                index++;\r\n                //(*pre)++;\r\n            }*/\r\n        }\r\n    }\r\n    \r\n    if (lipid.backbone == \"Cardiolipin\")\r\n    {\r\n        if (paraMap[\"ESI.pos\"] == 1) //positive mode\r\n        {\r\n            if (paraMap[\"Add.Pro\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"protonated\";\r\n                lipid.precursors[index].adduct = \"+H\";\r\n                lipid.precursors[index].adductMass = H;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + H;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (paraMap[\"Add.Na\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"+ Na\";\r\n                lipid.precursors[index].adduct = \"+Na\";\r\n                lipid.precursors[index].adductMass = Na;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + Na;\r\n                index++;\r\n                //(*pre)++;\r\n\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"- H + 2Na\";\r\n                lipid.precursors[index].adduct = \"+2Na-H\";\r\n                lipid.precursors[index].adductMass = Na;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + 2*Na - H;\r\n                index++;\r\n                //(*pre)++;\r\n\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"- 2H + 3Na\";\r\n                lipid.precursors[index].adduct = \"-2H + 3Na\";\r\n                lipid.precursors[index].adductMass = Na;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + 3*Na - 2*H;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (paraMap[\"Add.K\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"+ K\";\r\n                lipid.precursors[index].adduct = \"+K\";\r\n                lipid.precursors[index].adductMass = K;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + K;\r\n                index++;\r\n                //(*pre)++;\r\n\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"- H + 2K\";\r\n                lipid.precursors[index].adduct = \"+2K-H\";\r\n                lipid.precursors[index].adductMass = K;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + 2*K - H;\r\n                index++;\r\n                //(*pre)++;\r\n\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"- 2H + 3K\";\r\n                lipid.precursors[index].adduct = \"-2H + 3K\";\r\n                lipid.precursors[index].adductMass = K;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + 3*K - 2*H;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n\r\n            if (paraMap[\"Add.Li\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"+ Li\";\r\n                lipid.precursors[index].adduct = \"+Li\";\r\n                lipid.precursors[index].adductMass = Li;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + Li;\r\n                index++;\r\n                //(*pre)++;\r\n\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"- H + 2Li\";\r\n                lipid.precursors[index].adduct = \"+2Li-H\";\r\n                lipid.precursors[index].adductMass = Li;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + 2*Li - H;\r\n                index++;\r\n                //(*pre)++;\r\n\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"- 2H + 3Li\";\r\n                lipid.precursors[index].adduct = \"-2H + 3Li\";\r\n                lipid.precursors[index].adductMass = Li;\r\n                lipid.precursors[index].ESI = \"pos\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass + 3*Li - 2*H;\r\n                index++;\r\n                //(*pre)++;\r\n            }\r\n        }\r\n\r\n        if (paraMap[\"ESI.neg\"] == 1) //negative mode\r\n        {\r\n            if (paraMap[\"Add.Depro\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"deprotonated\";\r\n                lipid.precursors[index].adduct = \"-H\";\r\n                lipid.precursors[index].adductMass = 0;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - H;\r\n                index++;\r\n                (*pre)++;\r\n\r\n                if (paraMap[\"CL.double\"] == 1)\r\n                {\r\n                    lipid.precursors.push_back(PreCursor());\r\n                    lipid.precursors[index].description = \"deprotonatedX2\";\r\n                    lipid.precursors[index].adduct = \"-2H\";\r\n                    lipid.precursors[index].adductMass = 0;\r\n                    lipid.precursors[index].ESI = \"neg\";\r\n                    lipid.precursors[index].precursorMass = (lipid.totalMass - 2*H)/2;\r\n                    index++;                \r\n                    (*pre)++;\r\n                }\r\n            }\r\n            \r\n            if (paraMap[\"Add.Na\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"-2H + Na\";\r\n                lipid.precursors[index].adduct = \"-2H + Na\";\r\n                lipid.precursors[index].adductMass = Na;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - 2*H + Na;\r\n                index++;\r\n                (*pre)++;\r\n\r\n                /*\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"-3H + 2Na\";\r\n                lipid.precursors[index].adduct = \"2Na\";\r\n                lipid.precursors[index].adductMass = 2*Na;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - 3*H + 2*Na;\r\n                index++;\r\n                (*pre)++;\r\n                */\r\n            } \r\n\r\n            if (paraMap[\"Add.K\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"-2H + K\";\r\n                lipid.precursors[index].adduct = \"-2H + K\";\r\n                lipid.precursors[index].adductMass = K;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - 2*H + K;\r\n                index++;\r\n                (*pre)++;\r\n\r\n                /*\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"-3H + 2K\";\r\n                lipid.precursors[index].adduct = \"2K\";\r\n                lipid.precursors[index].adductMass = 2*K;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - 3*H + 2*K;\r\n                index++;\r\n                (*pre)++;\r\n                */\r\n            } \r\n\r\n            if (paraMap[\"Add.Li\"] == 1)\r\n            {\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"-2H + Li\";\r\n                lipid.precursors[index].adduct = \"-2H + Li\";\r\n                lipid.precursors[index].adductMass = Li;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - 2*H + Li;\r\n                index++;\r\n                (*pre)++;\r\n\r\n                /*\r\n                lipid.precursors.push_back(PreCursor());\r\n                lipid.precursors[index].description = \"-3H + 2Li\";\r\n                lipid.precursors[index].adduct = \"2Li\";\r\n                lipid.precursors[index].adductMass = 2*Li;\r\n                lipid.precursors[index].ESI = \"neg\";\r\n                lipid.precursors[index].precursorMass = lipid.totalMass - 3*H + 2*Li;\r\n                index++;\r\n                (*pre)++;\r\n                */\r\n            } \r\n        }\r\n    }\r\n\r\n    fragmentListConstruction(lipid, paraMap, spectraHolder, SL);\r\n}\r\n\r\n// fragment list construction\r\nvoid fragmentListConstruction(Lipid lipid, Map & paraMap, vector<SpectraHolder> spectraHolder, const SpectrumListPtr& SL)\r\n{\r\n    for (size_t j=0; j<lipid.precursors.size(); j++)\r\n    {\r\n        int index = 0;\r\n        if (lipid.backbone == \"Glycerol\")\r\n        {\r\n            if (lipid.precursors[j].ESI == \"pos\")\r\n            {\r\n                if (lipid.precursors[j].adductType == \"nonMetal\")\r\n                {\r\n                    if (lipid.headGroup == \"Choline\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"choline\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = N + 5*C + 12*H;\r\n                        index++;\r\n        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphocholine head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 5*C + N + 15*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }\r\n                    }\r\n                    if (lipid.headGroup == \"Ethanolamine\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 2*C + N + 9*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Serine\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoserine head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 6*O + P + 3*C + N + 9*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Glycerol\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoglycerol head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 6*O + P + 3*C + 9*H;\r\n                        index++;\r\n                        */\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Inositol\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 9*O + P + 6*C + 13*H;\r\n                        index++;\r\n                        */\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n\r\n                    if (lipid.headGroup == \"Phosphate\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphate head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 3*H;\r\n                        index++;\r\n                        */\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"PIP\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 9*O + P + 6*C + 13*H;\r\n                        index++;\r\n                        */\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }                        \r\n                    }\r\n\r\n                    if (lipid.headGroup == \"PIP2\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 9*O + P + 6*C + 13*H;\r\n                        index++;\r\n                        */\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }                            \r\n                    }\r\n\r\n                    if (lipid.headGroup == \"PIP3\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 9*O + P + 6*C + 13*H;\r\n                        index++;\r\n                        */\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                            index++;\r\n                        }                            \r\n                    }\r\n                }\r\n\r\n                if (lipid.precursors[j].adductType == \"Metal\")\r\n                {\r\n                    if (lipid.headGroup != \"Choline\")\r\n                    {\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoric acid & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 3*H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"glycerophosphoric acid & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 5*O + P + 7*H + 3*C + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        */\r\n                    }\r\n\r\n                    if (lipid.SN1bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                        index++;\r\n                        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                        index++;\r\n                        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.SN2bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                        index++;\r\n                        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                        index++;\r\n                        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                        index++;\r\n                    }    \r\n\r\n                    if (lipid.headGroup == \"Choline\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"choline\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = N + 5*C + 12*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"PO4C2H5 & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 2*C + 5*H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n                        */\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphocholine & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphocholine & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass -H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of choline\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                        index++;\r\n                        */\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid; loss of adduct\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H - lipid.precursors[j].adductMass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of choline; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of choline & adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H - lipid.precursors[j].adductMass + H;\r\n                            index++;\r\n                            /*\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of choline; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                            */\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            /*\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of choline; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of choline; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n                            */\r\n                            //if (lipid.FA2DoubleBonds > 2)\r\n                            //{\r\n                                lipid.precursors[j].fragments.push_back(Fragment());\r\n                                lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                                lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine & adduct; loss of FA2 as ketene\";\r\n                                lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                                index++;\r\n                            //}\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid; loss of adduct\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H - lipid.precursors[j].adductMass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphocholine; loss of FA2 as carboxylic acid (additional double bond)\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.FA2Mass - O;\r\n                            index++;\r\n                            \r\n                        }    \r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Ethanolamine\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine and adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine and adduct; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass + H;\r\n                            index++;\r\n                            \r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine and adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n                            \r\n                            //if (lipid.FA2DoubleBonds > 2)\r\n                            //{\r\n                                lipid.precursors[j].fragments.push_back(Fragment());\r\n                                lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                                lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine and adduct; loss of FA2 as ketene\";\r\n                                lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                                index++;\r\n                            //}\r\n                        }    \r\n                    }\r\n                    \r\n                    if (lipid.headGroup == \"Serine\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoric acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - P - 4*O - 3*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoserine & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoserine & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass -H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        */\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of serine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine and adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n                            \r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine and adduct; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                            \r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass + H;\r\n                            index++;\r\n                            \r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine and adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n                            \r\n                            //if (lipid.FA2DoubleBonds > 2)\r\n                            //{\r\n                                lipid.precursors[j].fragments.push_back(Fragment());\r\n                                lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                                lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoserine and adduct; loss of FA2 as ketene\";\r\n                                lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                                index++;\r\n                            //}\r\n                        }    \r\n                    }\r\n                    \r\n                    if (lipid.headGroup == \"Glycerol\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoglycerol & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoglycerol & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass -H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        */\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol and adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n                            \r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol and adduct; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                            \r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass + H;\r\n                            index++;\r\n                            \r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol and adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n                            \r\n                            //if (lipid.FA2DoubleBonds > 2)\r\n                            //{\r\n                                lipid.precursors[j].fragments.push_back(Fragment());\r\n                                lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                                lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoglycerol and adduct; loss of FA2 as ketene\";\r\n                                lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                                index++;\r\n                            //}\r\n                        }    \r\n                    }\r\n                    \r\n                    if (lipid.headGroup == \"Inositol\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass -H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        */\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol and adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol and adduct; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol and adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol and adduct; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                            index++;\r\n                        }    \r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Phosphate\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphate & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphate & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass -H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        */\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate and adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate and adduct; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate and adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphate and adduct; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                            index++;\r\n                        }    \r\n                    }\r\n\r\n\r\n\r\n\r\n                    if (lipid.headGroup == \"PIP\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol phosphate & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol phosphate & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass -H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        */\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol phosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol phosphate; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol phosphate; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate and adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate and adduct; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol phosphate; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol phosphate; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate and adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol phosphate and adduct; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                            index++;\r\n                        }    \r\n                    }\r\n\r\n\r\n\r\n\r\n\r\n                    if (lipid.headGroup == \"PIP2\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol bisphosphate & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol bisphosphate & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass -H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        */\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol bisphosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol bisphosphate; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol bisphosphate; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate and adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate and adduct; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol bisphosphate; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol bisphosphate; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate and adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol bisphosphate and adduct; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                            index++;\r\n                        }    \r\n                    }\r\n\r\n\r\n\r\n                    if (lipid.headGroup == \"PIP3\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate; loss of adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol trisphosphate & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol trisphosphate & adduct - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass -H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                        */\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol trisphosphate\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol trisphosphate; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol trisphosphate; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA1Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate and adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA1Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate and adduct; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA1Mass;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol trisphosphate; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol trisphosphate; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H - lipid.FA2Mass + H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate and adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass - O - H - lipid.FA2Mass;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoinositol trisphosphate and adduct; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.precursors[j].adductMass + H - lipid.FA2Mass;\r\n                            index++;\r\n                        }    \r\n                    }\r\n                }\r\n\r\n                /*\r\n                lipid.precursors[j].fragments.push_back(Fragment());\r\n                lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                lipid.precursors[j].fragments[index].fragDescription = \"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ\";\r\n                lipid.precursors[j].fragments[index].fragmentMass = 999.999;\r\n                index++;\r\n\r\n                lipid.precursors[j].fragments.push_back(Fragment());\r\n                lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group\";\r\n                lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                index++;\r\n\r\n                if (lipid.SN1bond == \"acyl\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of FA1 as ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + 2*O + 3*C + 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"R1CO\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.SN2bond == \"acyl\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of FA2 as ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + 2*O + 3*C + 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"R2CO\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.headGroup == \"Choline\") \r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"choline\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = N + 5*C + 12*H;\r\n                    index++;\r\n        \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphocholine head-group\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 5*C + N + 15*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H;\r\n                    index++;\r\n                    \r\n                    if (lipid.precursors[j].description == \"Lithium adduct\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of Li adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - Li;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of Li adduct; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - Li - lipid.FA1Mass - O - H;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of Li adduct; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - Li - lipid.FA2Mass - O - H;\r\n                            index++;\r\n                        }\r\n                    }\r\n                    \r\n                }\r\n\r\n                if (lipid.headGroup == \"Ethanolamine\") \r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine head-group\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 2*C + N + 9*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head group; addition of water\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H;\r\n                    index++;\r\n\r\n                    if (lipid.SN1bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine; loss of FA1 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H\r\n                                                                                        - lipid.FA1Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine; loss of FA1 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H\r\n                                                                                        - lipid.FA1Mass + H;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.SN2bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine; loss of FA2 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H\r\n                                                                                        - lipid.FA2Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine; loss of FA2 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H\r\n                                                                                        - lipid.FA2Mass + H;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.precursors[j].description == \"Lithium adduct\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of lithiated head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - Li;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"lithiated phosphoethanolamine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O + H + Li;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"lithiated phosphoric acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 3*H + Li;\r\n                        index++;\r\n                    }\r\n                }\r\n\r\n                if (lipid.headGroup == \"Serine\") \r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoserine head-group\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O + 2*H;\r\n                    index++;\r\n                    \r\n                    if (lipid.precursors[j].description == \"Lithium adduct\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of lithiated head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - Li;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of serine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - N - 5*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA1 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - N - 5*H - lipid.FA1Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA2 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - N - 5*H - lipid.FA2Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoric acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - P - 3*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"lithiated phosphoserine head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O + H + Li;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"lithiated phosphoric acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 3*H + Li;\r\n                        index++;\r\n                    }\r\n                }\r\n\r\n                if (lipid.headGroup == \"Glycerol\") \r\n                {                    \r\n                    if (lipid.precursors[j].description == \"Lithium adduct\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of lithiated head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - Li;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - 6*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA1 as a carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - 6*H - lipid.FA1Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA2 as a carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - 6*H - lipid.FA2Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"lithiated phosphoglycerol head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O + H + Li;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"lithiated phosphoric acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 3*H + Li;\r\n                        index++;\r\n                    }\r\n                }\r\n\r\n                if (lipid.headGroup == \"Phosphate\") \r\n                {                    \r\n                    if (lipid.precursors[j].description == \"Lithium adduct\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of lithiated head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - Li;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"lithiated phosphoric acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 3*H + Li;\r\n                        index++;\r\n                    }\r\n                }\r\n                */\r\n            }\r\n\r\n            if (lipid.precursors[j].ESI == \"neg\")\r\n            {\r\n                if ((lipid.headGroup == \"PIP\") && (lipid.precursors[j].description == \"deprotonated\"))\r\n                {\r\n                    if ((lipid.SN1bond != \"lyso\") && (lipid.SN2bond != \"lyso\"))\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"G3P-H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 3*C + 6*H + 5*O + P;\r\n                        index++;\r\n                    }\r\n\r\n\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol phosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + P + 3*O + 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H2PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*H + 4*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = P + 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"HO6P2\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 6*O + H + 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H3O7P2\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 7*O + 3*H + 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HPO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*O - H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 6*O - 12*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - O - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - O - 4*H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol - 3*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 7*H - P - 5*O;\r\n                    index++;\r\n\r\n                    if (lipid.SN1bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid; loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - O - 2*H - lipid.FA1Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA1 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4; loss of FA1 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P - lipid.FA1Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4; loss of FA1 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P - lipid.FA1Mass + H;\r\n                        index++;\r\n                        */\r\n                    }\r\n\r\n                    if (lipid.SN2bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid; loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - O - 2*H - lipid.FA2Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA2 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                        index++;\r\n                        /*\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4; loss of FA2 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P - lipid.FA2Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4; loss of FA2 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P - lipid.FA2Mass + H;\r\n                        index++;\r\n                        */\r\n                    }\r\n                }\r\n\r\n                if (lipid.headGroup == \"PIP\" && lipid.precursors[j].description == \"deprotonatedX2\")\r\n                {\r\n                    if ((lipid.SN1bond != \"lyso\") && (lipid.SN2bond != \"lyso\"))\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"G3P-H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 3*C + 6*H + 5*O + P;\r\n                        index++;\r\n                    }\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H2PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*H + 4*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = P + 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 1*H - P - 2*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 3*H - P - 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 5*H - P - 4*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - 3*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 7*H - P - 5*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - P - 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"bisphosphate (2-)\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = (lipid.headGroupMass + O)/2;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"bisphosphate - H2O (2-)\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = (lipid.headGroupMass - 2*H)/2;\r\n                    index++;\r\n\r\n\r\n\r\n                    if (lipid.SN1bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA1 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - lipid.FA1Mass - O;\r\n                        index++;\r\n\r\n                        //lipid.precursors[j].fragments.push_back(Fragment());\r\n                        //lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        //lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                        //lipid.precursors[j].fragments[index].fragmentMass = (2*(lipid.precursors[j].precursorMass) - lipid.FA1Mass + H)/2;\r\n                        //index++;\r\n\r\n                    }\r\n\r\n                    if (lipid.SN2bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA2 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - lipid.FA2Mass - O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = (2*(lipid.precursors[j].precursorMass) - lipid.FA2Mass + H)/2;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene and PO3\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 2*((2*(lipid.precursors[j].precursorMass) - lipid.FA2Mass + H)/2) - P - 3*O;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.SN1bond == \"acyl\" && lipid.SN2bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene and FA1 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 2*((2*(lipid.precursors[j].precursorMass) - lipid.FA2Mass + H)/2) - lipid.FA1Mass - O;\r\n                        index++;\r\n                    }\r\n\r\n                }\r\n\r\n                if ((lipid.headGroup == \"PIP2\") && (lipid.precursors[j].description == \"deprotonated\"))\r\n                {\r\n                    if ((lipid.SN1bond != \"lyso\") && (lipid.SN2bond != \"lyso\"))\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"G3P-H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 3*C + 6*H + 5*O + P;\r\n                        index++;\r\n                    }\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H2PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*H + 4*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = P + 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"HO6P2\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 6*O + H + 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H3O7P2\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 7*O + 3*H + 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HPO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*O - H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HPO3 & inositol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 10*H - 9*O - 3*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of 2*HPO3 & inositol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 10*H - 12*O - 4*H - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HPO3 & inositol; addition of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 10*H - 8*O - H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4 & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 5*O - 5*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - P - 2*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - O - 4*H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol trisphosphate + H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + 2*(H + O);\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol trisphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol trisphosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol trisphosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 4*H - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H - P - 3*O - H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - O - 4*H - P - 3*O - H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - 3*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 8*O - 8*H - 2*P;\r\n                    index++;\r\n\r\n                    if (lipid.SN1bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid; loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - O - 2*H - lipid.FA1Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4 & FA1 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P - lipid.FA1Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA1 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + O;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.SN2bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid; loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - O - 2*H - lipid.FA2Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4 & FA2 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P - lipid.FA2Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA2 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + O;\r\n                        index++;\r\n                    }\r\n                }\r\n\r\n                if ((lipid.headGroup == \"PIP2\") && (lipid.precursors[j].description == \"deprotonatedX2\"))\r\n                {\r\n                    if ((lipid.SN1bond != \"lyso\") && (lipid.SN2bond != \"lyso\"))\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"G3P-H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 3*C + 6*H + 5*O + P;\r\n                        index++;\r\n                    }\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H2PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*H + 4*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = P + 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"HO6P2\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 6*O + H + 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 3*H - P - 3*O - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 5*H - P - 4*O - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 3*H - P - 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 5*H - P - 4*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - P - 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of PO3; loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - P - 3*O - 2*H - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HO6P2\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - 2*P - 6*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HO6P2; loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - 2*P - 6*O - 3*H - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of PO3 & inositol; addition of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - 6*C - 10*H - 8*O - P;\r\n                    index++;\r\n\r\n\r\n\r\n                    if (lipid.SN1bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA1 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - lipid.FA1Mass - O;\r\n                        index++;\r\n\r\n                        //lipid.precursors[j].fragments.push_back(Fragment());\r\n                        //lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        //lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                        //lipid.precursors[j].fragments[index].fragmentMass = (2*(lipid.precursors[j].precursorMass) - lipid.FA1Mass + H)/2;\r\n                        //index++;\r\n\r\n                    }\r\n\r\n                    if (lipid.SN2bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA2 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - lipid.FA2Mass - O;\r\n                        index++;\r\n                    }\r\n                }\r\n\r\n\r\n\r\n\r\n\r\n\r\n                if (lipid.headGroup == \"PIP3\")\r\n                {\r\n                    if ((lipid.SN1bond != \"lyso\") && (lipid.SN2bond != \"lyso\"))\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"G3P-H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 3*C + 6*H + 5*O + P;\r\n                        index++;\r\n                    }\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H2PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*H + 4*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = P + 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"HO6P2\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 6*O + H + 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H3O7P2\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 7*O + 3*H + 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HPO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*O - H - P;\r\n                    index++;\r\n                    /*\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HPO3 & inositol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 10*H - 9*O - 3*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of HPO3 & inositol; addition of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 10*H - 8*O - H - P;\r\n                    index++;\r\n                    */\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of 2*H3PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 2*(4*O + 3*H + P);\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4 & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 5*O - 5*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*(P + 3*O + H) + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*(P + 3*O + H) - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol bisphosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*(P + 3*O + H) - 4*H - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol trisphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - P - 2*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol trisphosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol trisphosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - O - 4*H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol tetraphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol tetraphosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol tetraphosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 4*H - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H - P - 3*O - H - P - 3*O - H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - O - 4*H - P - 3*O - H - P - 3*O - H - P - 3*O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"inositol phosphate - 3*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 8*O - 8*H - 2*P - P - 3*O - H;\r\n                    index++;\r\n\r\n                    if (lipid.SN1bond == \"acyl\")\r\n                    {\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4 & FA1 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P - lipid.FA1Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA1 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + O;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.SN2bond == \"acyl\")\r\n                    {\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H3PO4 & FA2 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*O - 3*H - P - lipid.FA2Mass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA2 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + O;\r\n                        index++;\r\n                    }\r\n                }\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n                if (lipid.headGroup != \"PIP\" && lipid.headGroup != \"PIP2\" &&  lipid.headGroup != \"PIP3\")\r\n                {\r\n                    if ((lipid.SN1bond != \"lyso\") && (lipid.SN2bond != \"lyso\"))\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"G3P-H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 3*C + 6*H + 5*O + P;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"G3P\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 3*C + 8*H + 6*O + P;\r\n                        index++;\r\n                    }\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H2PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*H + 4*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = P + 3*O;\r\n                    index++;\r\n            \r\n                    if (lipid.SN1bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA1 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.SN2bond == \"acyl\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"FA2 carboxylate anion\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                        index++;\r\n                    }\r\n\r\n                    if ((lipid.headGroup == \"Choline\") && (lipid.precursors[j].adduct != \"-CH3\"))\r\n                    {    \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"demethylation\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass\r\n                                                                                    - lipid.precursors[j].adductMass - C - 3*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass \r\n                                                                                    - lipid.precursors[j].adductMass - 3*C - 10*H - N;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass\r\n                                                                                    - lipid.precursors[j].adductMass - 5*C - 12*H - N;\r\n                        index++;\r\n        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"BH\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"GPC-CH3-H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 7*C + 15*H + 5*O + P + N;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"PC-CH3\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*C + 11*H + 4*O + P + N;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"demethylation; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - C - 3*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - 3*C - 10*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - 5*C - 12*H - N;\r\n                            index++;                    \r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"demethylation; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - C - 3*H;\r\n                            index++;\r\n                \r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - 3*C - 10*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - 5*C - 12*H - N;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"demethylation; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - C - 3*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - 3*C - 10*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - 5*C - 12*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"demethylation; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - C - 3*H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - 3*C - 10*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - 5*C - 12*H - N;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if ((lipid.headGroup == \"Choline\") && (lipid.precursors[j].adduct == \"-CH3\"))\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass \r\n                                                                                    - lipid.precursors[j].adductMass - 2*C - 7*H - N;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass\r\n                                                                                    - lipid.precursors[j].adductMass - 4*C - 9*H - N;\r\n                        index++;\r\n        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"BH\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"GPC-CH3-H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 7*C + 15*H + 5*O + P + N;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"PC-CH3\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*C + 11*H + 4*O + P + N;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - 2*C - 7*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - 4*C - 9*H - N;\r\n                            index++;\r\n                \r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - 2*C - 7*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - 4*C - 9*H - N;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - 2*C - 7*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H\r\n                                                                                        - lipid.precursors[j].adductMass - 4*C - 9*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - 2*C - 7*H - N;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H\r\n                                                                                        - lipid.precursors[j].adductMass - 4*C - 9*H - N;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Ethanolamine\") \r\n                    {        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of ethanolamine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of ethanolamine; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of ethanolamine; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H - lipid.FA1Mass + H;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of ethanolamine; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of ethanolamine; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H - lipid.FA2Mass + H;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Serine\") \r\n                    {        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of serine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 2*O - N - 3*C - 5*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"serine head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 2*O - N - 3*C - 5*H \r\n                                                                                        - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 2*O - N - 3*C - 5*H \r\n                                                                                        - lipid.FA1Mass + H;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 2*O - N - 3*C - 5*H \r\n                                                                                        - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of serine; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 2*O - N - 3*C - 5*H \r\n                                                                                        - lipid.FA2Mass + H;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Inositol\") \r\n                    {            \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"glycerophosphoinositol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + lipid.backboneMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"glycerophosphoinositol - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + lipid.backboneMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"glycerophosphoinositol - 2*H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + lipid.backboneMass - 2*O - 3*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"glycerophosphoinositol - 3*H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + lipid.backboneMass - 3*O - 5*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol - 2*H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - O - 4*H;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H - lipid.FA1Mass + H;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H - lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H - lipid.FA2Mass + H;\r\n                            index++;\r\n                        }\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Glycerol\") \r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - 6*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"glycerophosphoglycerol\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + lipid.backboneMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"glycerophosphoglycerol - H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + lipid.backboneMass - H - O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"glycerophosphoglycerol - 2*H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + lipid.backboneMass -3*H - 2*O;\r\n                        index++;\r\n\r\n                        if (lipid.SN1bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA1 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - 6*H - lipid.FA1Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF1\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA1 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - 6*H- lipid.FA1Mass + H;\r\n                            index++;\r\n                        }\r\n\r\n                        if (lipid.SN2bond == \"acyl\")\r\n                        {\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA2 as carboxylic acid\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - 6*H- lipid.FA2Mass - O - H;\r\n                            index++;\r\n\r\n                            lipid.precursors[j].fragments.push_back(Fragment());\r\n                            lipid.precursors[j].fragments[index].fragType = \"HF2\";\r\n                            lipid.precursors[j].fragments[index].fragDescription = \"loss of glycerol; loss of FA2 as ketene\";\r\n                            lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 3*C - 2*O - 6*H- lipid.FA2Mass + H;\r\n                            index++;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        \r\n        string backsub = lipid.backbone.substr(5, 6);\r\n        if (backsub == \"Sphing\" || backsub == \"Phytos\")\r\n        {\r\n            if (lipid.precursors[j].ESI == \"pos\")\r\n            {\r\n                if (lipid.precursors[j].adductType == \"nonMetal\")\r\n                {\r\n                    if (lipid.headGroup == \"Choline\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"HF\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of fatty acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*H - 2*O - lipid.FA1Mass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"HF\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of fatty acid; addition of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.FA1Mass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NC2H3\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*C + 3*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 3*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphocholine head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 5*C + N + 15*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"choline\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = N + 5*C + 12*H;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Ethanolamine\")\r\n                    {\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; loss of fatty acid\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*H - 2*O - lipid.FA1Mass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; loss of fatty acid; addition of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.FA1Mass;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NC2H3\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*C + 3*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 3*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 2*C + N + 9*H;\r\n                        index++;\r\n                        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; addition of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Inositol\")\r\n                    {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; addition of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of fatty acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*H - 2*O - lipid.FA1Mass;\r\n                    index++;\r\n                    /*\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of fatty acid; addition of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.FA1Mass;\r\n                    index++;\r\n                    */\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NC2H3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*C + 3*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 3*H;\r\n                    index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 2*H - O;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of 2*H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 4*H - 2*O;\r\n                        index++;\r\n\r\n                        //lipid.precursors[j].fragments.push_back(Fragment());\r\n                        //lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        //lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol & adduct\";\r\n                        //lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        //index++;\r\n                    }\r\n                }\r\n\r\n                if (lipid.precursors[j].adductType == \"Metal\")\r\n                {\r\n                    if (lipid.headGroup == \"Choline\")\r\n                    {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group & adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group, loss of H2O; loss of adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*O - 3*H - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of CH2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O - C;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of adduct; loss of fatty acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*H - 2*O - lipid.FA1Mass - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of fatty acid; addition of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NC2H3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*C + 3*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 3*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3 + adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*H + lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphocholine head-group\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 5*C + N + 15*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of NC3H9\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 3*C - 9*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"choline\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = N + 5*C + 12*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"PO4C2H5 & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = P + 4*O + 2*C + 5*H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                    }\r\n\r\n                    if (lipid.headGroup == \"Ethanolamine\")\r\n                    {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group & adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group, loss of H2O; loss of adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*O - 3*H - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of CH2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O - C;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of adduct; loss of fatty acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*H - 2*O - lipid.FA1Mass - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of fatty acid; addition of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NC2H3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*C + 3*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 3*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3 + adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*H + lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = 4*O + P + 2*C + N + 9*H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of phosphoethanolamine; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of aziridine\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H;\r\n                        index++;\r\n                    }\r\n                    \r\n                    if (lipid.headGroup == \"Inositol\")\r\n                    {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol; loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H - 2*H - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group & adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - H - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group, loss of H2O; loss of adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*O - 3*H - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n                    /*\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O;\r\n                    index++;\r\n                    */\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of CH2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 3*H - 2*O - C;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of adduct; loss of fatty acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - 2*H - 2*O - lipid.FA1Mass - lipid.precursors[j].adductMass + H;\r\n                    index++;\r\n                    /*\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; loss of fatty acid; addition of H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass - O - lipid.FA1Mass;\r\n                    index++;\r\n                    */\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NC2H3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*C + 3*H;\r\n                    index++;\r\n                    /*\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NC2H3; loss of water\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*C + 3*H - 2*H - O;\r\n                    index++;\r\n                    */\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 3*H;\r\n                    index++;\r\n                    /*\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FH\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"fatty acid + NH3 + adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + N + 2*H + lipid.precursors[j].adductMass;\r\n                    index++;\r\n                    */    \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 2*H - O;\r\n                        index++;\r\n                        \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"loss of head-group; addition of water\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.headGroupMass + H;\r\n                        index++;\r\n\r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol & adduct\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + H + O + lipid.precursors[j].adductMass;\r\n                        index++;\r\n    \r\n                        lipid.precursors[j].fragments.push_back(Fragment());\r\n                        lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                        lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol & adduct; loss of H2O\";\r\n                        lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - H + lipid.precursors[j].adductMass;\r\n                        index++;\r\n                    }\r\n                    \r\n                }\r\n            }\r\n\r\n            if (lipid.precursors[j].ESI == \"neg\")\r\n            {\r\n                if ((lipid.headGroup == \"Choline\") && (lipid.precursors[j].adduct != \"-CH3\"))\r\n                {    \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of methyl group and adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass\r\n                                                                                - lipid.precursors[j].adductMass - C - 3*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N and adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass \r\n                                                                                - lipid.precursors[j].adductMass - 3*C - 10*H - N;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N and adduct\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass\r\n                                                                                - lipid.precursors[j].adductMass - 5*C - 12*H - N;\r\n                    index++;\r\n                }\r\n\r\n                if ((lipid.headGroup == \"Choline\") && (lipid.precursors[j].adduct == \"-CH3\"))\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of C3H10N\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass \r\n                                                                                - lipid.precursors[j].adductMass - 2*C - 7*H - N;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of C5H12N\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass\r\n                                                                                - lipid.precursors[j].adductMass - 4*C - 9*H - N;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.headGroup == \"Ethanolamine\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of ethanolamine\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - N - 2*C - 5*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoethanolamine - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.headGroup == \"Inositol\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of inositol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - 6*C - 5*O - 10*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol - H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"H\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"phosphoinositol - 2*H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.headGroupMass - O - 4*H;\r\n                    index++;\r\n                }\r\n            }\r\n        }\r\n\r\n        if (lipid.backbone == \"Cardiolipin\")\r\n        {\r\n            if (lipid.precursors[j].ESI == \"pos\")\r\n            {\r\n                if (lipid.precursors[j].description == \"protonated\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 11*O - 6*C - 14*H - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3, glycerol, & glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 12*O - 6*C - 15*H - 2*P - lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 11*O - 6*C - 14*H - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1, glycerol, & glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 12*O - 6*C - 15*H - 2*P - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.precursors[j].description == \"+ Na\")\r\n                {\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & sodium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 11*O - 6*C - 13*H - Na - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3, glycerol, & sodium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 12*O - 6*C - 14*H - Na - 2*P - lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & sodium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 11*O - 6*C - 13*H - Na - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1, glycerol, & sodium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 12*O - 6*C - 14*H - Na - 2*P - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                    index++;\r\n\r\n                }\r\n            \r\n                if (lipid.precursors[j].description == \"- H + 2Na\")\r\n                {\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & di-sodium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 11*O - 6*C - 12*H - 2*Na - 2*P;\r\n                    index++;                \r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3, glycerol, & di-sodium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 12*O - 6*C - 13*H - 2*Na - 2*P - lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & di-sodium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 11*O - 6*C - 12*H - 2*Na - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1, glycerol, & di-sodium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 12*O - 6*C - 13*H - 2*Na - 2*P - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.precursors[j].description == \"- 2H + 3Na\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & sodiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 6*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & sodiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 6*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & phosphoglycerolphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & phosphoglycerolphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 & FA3 as carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA3Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 & FA2 as carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 & FA4 as carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA3Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA1Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA3Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA1Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, and FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA4Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, and FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA2Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA4Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA2Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, sodiated glycerophosphatidic acid, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 3*C - 7*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, sodiated glycerophosphatidic acid, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 3*C - 7*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n                } \r\n\r\n                if (lipid.precursors[j].description == \"+ K\")\r\n                {\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & potassium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 11*O - 6*C - 13*H - K - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3, glycerol, & potassium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 12*O - 6*C - 14*H - K - 2*P - lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & potassium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 11*O - 6*C - 13*H - K - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1, glycerol, & potassium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 12*O - 6*C - 14*H - K - 2*P - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                    index++;\r\n                }\r\n            \r\n                if (lipid.precursors[j].description == \"- H + 2K\")\r\n                {\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & di-potassium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 11*O - 6*C - 12*H - 2*K - 2*P;\r\n                    index++;                \r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3, glycerol, & di-potassium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 12*O - 6*C - 13*H - 2*K - 2*P - lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & di-potassium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 11*O - 6*C - 12*H - 2*K - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1, glycerol, & di-potassium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 12*O - 6*C - 13*H - 2*K - 2*P - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.precursors[j].description == \"- 2H + 3K\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & potassiated glycerphosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 6*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & potassiated glycerphosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 6*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & phosphoglycerolphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & phosphoglycerolphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 & FA3 as a carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA3Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 & FA2 as a carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 & FA4 as a carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA3Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA1Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA3Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA1Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA4Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA2Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol and FA4 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA4Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, and FA2 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA2Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, potassiated glycerophosphatidic acid, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 3*C - 7*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, potassiated glycerophosphatidic acid, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 3*C - 7*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n                } \r\n\r\n                if (lipid.precursors[j].description == \"+ Li\")\r\n                {\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol & lithium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 11*O - 6*C - 13*H - Li - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3, glycerol & lithium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 12*O - 6*C - 14*H - Li - 2*P - lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol & lithium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 11*O - 6*C - 13*H - Li - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1, glycerol & lithium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 12*O - 6*C - 14*H - Li - 2*P - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                    index++;\r\n                }\r\n            \r\n                if (lipid.precursors[j].description == \"- H + 2Li\")\r\n                {\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 3*C - 4*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol & di-lithium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 11*O - 6*C - 12*H - 2*Li - 2*P;\r\n                    index++;                \r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3, glycerol & di-lithium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 12*O - 6*C - 13*H - 2*Li - 2*P - lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol & di-lithium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 11*O - 6*C - 12*H - 2*Li - 2*P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1, glycerol & di-lithium glycerol-1,3-diphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 12*O - 6*C - 13*H - 2*Li - 2*P - lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 cation\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.precursors[j].description == \"- 2H + 3Li\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & lithiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 6*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & lithiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 6*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, & phosphoglycerolphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, & phosphoglycerolphosphate\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 & FA3 as a carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA3Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 & FA2 as a carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 & FA4 as a carboxylic acids\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 2*O - 2*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA3Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA1Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA3Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA1Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA4Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA2Mass - 4*O - 3*C - 7*H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, and FA4 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - lipid.FA4Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, and FA2 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - lipid.FA2Mass - 4*O - 3*C - 6*H - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, lithiated glycerophosphatidic acid, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 3*C - 7*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"N\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, lithiated glycerophosphatidic acid, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 3*C - 7*H - P - lipid.precursors[j].adductMass;\r\n                    index++;\r\n                }\r\n            }\r\n\r\n            if (lipid.precursors[j].ESI == \"neg\")\r\n            {\r\n                if (lipid.precursors[j].description == \"deprotonated\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"G3P-H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 3*C + 6*H + 5*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"G3P\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 3*C + 8*H + 6*O + P;\r\n                    index++;\r\n            \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H2PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*H + 4*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = P + 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 carboxylate anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 carboxylate anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 carboxylate anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 carboxylate anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1 as carboxylic acid & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H\r\n                                                                                - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA2 as carboxylic acid & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H\r\n                                                                                - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1 as ketene & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H\r\n                                                                                - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA2 as ketene & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H\r\n                                                                                - lipid.FA2Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & phosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1 as carboxylic acid & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA2 as carboxylic acid & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1 as ketene & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA2 as ketene & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA2Mass + H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, phosphoglycerol & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, phosphoglycerol & FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, phosphoglycerol & FA1 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, phosphoglycerol & FA2 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA2Mass + H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3 as carboxylic acid & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H\r\n                                                                                - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA4 as carboxylic acid & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H\r\n                                                                                - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3 as ketene & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H\r\n                                                                                - lipid.FA3Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA4 as ketene & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H\r\n                                                                                - lipid.FA4Mass + H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & phosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3 as carboxylic acid & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA4 as carboxylic acid & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3 as ketene & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA3Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA4 as ketene & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA4Mass + H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, phosphoglycerol & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, phosphoglycerol & FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, phosphoglycerol & FA3 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA3Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, phosphoglycerol & FA4 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA4Mass + H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n                }\r\n            \r\n                if (lipid.precursors[j].description == \"deprotonatedX2\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"G3P-H2O\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 3*C + 6*H + 5*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"G3P\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 3*C + 8*H + 6*O + P;\r\n                    index++;\r\n            \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"H2PO4\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*H + 4*O + P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"B\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"PO3\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = P + 3*O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA1 carboxylate anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA1Mass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 carboxylic anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - lipid.FA1Mass - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA2 carboxylate anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA2Mass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 carboxylic anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - lipid.FA2Mass - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = (2*(lipid.precursors[j].precursorMass) - lipid.FA2Mass + H)/2;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA3 carboxylate anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA3Mass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 carboxylic anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - lipid.FA3Mass - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"FA4 carboxylate anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.FA4Mass + O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 carboxylic anion\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) - lipid.FA4Mass - O;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = (2*(lipid.precursors[j].precursorMass) - lipid.FA4Mass + H)/2;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & phosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, phosphoglycerol & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, phosphoglycerol & FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, phosphoglycerol & FA3 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA3Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, phosphoglycerol & FA4 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA4Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3 as carboxylic acid & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA4 as carboxylic acid & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA3 as ketene & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA3Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, FA4 as ketene & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA4Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & phosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, phosphoglycerol & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, phosphoglycerol & FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, phosphoglycerol & FA1 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, phosphoglycerol & FA2 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 7*H - P\r\n                                                                                - lipid.FA2Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1 as carboxylic acid & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA2 as carboxylic acid & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA1 as ketene & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, FA2 as ketene & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = 2*(lipid.precursors[j].precursorMass) + H - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA2Mass + H;\r\n                    index++;\r\n                }\r\n            \r\n                if (lipid.precursors[j].description == \"-2H + Na\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - Na;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - Na;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - Na;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - Na;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA1Mass - Na;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA2Mass - Na;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA1Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA2Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA1Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA2Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerophosphoglycerol & FA1 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA1Mass - Na;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerophosphoglycerol & FA2 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA2Mass - Na;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA3Mass - Na;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA4Mass - Na;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA3Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA4Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA3Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerophosphoglycerol & FA3 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA3Mass - Na;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerophosphoglycerol & FA4 as a sodium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA4Mass - Na;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & sodiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 6*H - P - Na;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & sodiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 6*H - P - Na;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.precursors[j].description == \"-2H + K\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - K;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - K;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - K;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - K;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA1Mass - K;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA2Mass - K;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA1Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA2Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA1Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA2Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerophosphoglycerol & FA1 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA1Mass - K;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerophosphoglycerol & FA2 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA2Mass - K;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA3Mass - K;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA4Mass - K;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA3Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA4Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA3Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerophosphoglycerol & FA3 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA3Mass - K;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerophosphoglycerol & FA4 as a potassium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA4Mass - K;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & sodiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 6*H - P - K;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & sodiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 6*H - P - K;\r\n                    index++;\r\n                }\r\n\r\n                if (lipid.precursors[j].description == \"-2H + Li\")\r\n                {\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F2\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA2 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA2Mass - O - Li;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F4\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA4 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA4Mass - O - Li;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass + H;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F1\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - O - Li;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"F3\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - O - Li;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA1Mass - Li;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA2Mass - Li;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA1Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA2Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA1 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA1Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerol, & FA2 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA2Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerophosphoglycerol & FA1 as a lithiated salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA1Mass - Li;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4, glycerophosphoglycerol & FA2 as a lithiated salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA2Mass - Li;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 6*H;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA3Mass - Li;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 6*H\r\n                                                                                - lipid.FA4Mass - Li;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA3Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a carboxylic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 4*O - 3*C - 7*H\r\n                                                                                - lipid.FA4Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA3 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA3Mass;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerol, & FA4 as a ketene\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 3*O - 3*C - 5*H\r\n                                                                                - lipid.FA4Mass;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & glycerophosphoglycerol\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 7*O - 6*C - 11*H - P;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerophosphoglycerol & FA3 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA3Mass - Li;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2, glycerophosphoglycerol & FA4 as a lithium salt\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 8*O - 6*C - 11*H - P\r\n                                                                                - lipid.FA4Mass - Li;\r\n                    index++;\r\n                \r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA1, FA2 & lithiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA1Mass - lipid.FA2Mass - 6*O - 3*C - 6*H - P - Li;\r\n                    index++;\r\n\r\n                    lipid.precursors[j].fragments.push_back(Fragment());\r\n                    lipid.precursors[j].fragments[index].fragType = \"FA\";\r\n                    lipid.precursors[j].fragments[index].fragDescription = \"loss of FA3, FA4 & lithiated glycerophosphatidic acid\";\r\n                    lipid.precursors[j].fragments[index].fragmentMass = lipid.precursors[j].precursorMass - lipid.FA3Mass - lipid.FA4Mass - 6*O - 3*C - 6*H - P - Li;\r\n                    index++;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    \r\n    Lipid decoy;\r\n    decoy = lipid;\r\n    decoy.decoy = true;\r\n    decoy.name = lipid.name + \"D\";\r\n    for (size_t i=0; i<decoy.precursors.size(); i++)\r\n    {\r\n        vector<double> masses(decoy.precursors[i].fragments.size());\r\n        for (size_t j=0; j<decoy.precursors[i].fragments.size(); j++)\r\n        {\r\n            masses[j] = decoy.precursors[i].fragments[j].fragmentMass;\r\n        }\r\n        sort(masses.begin(), masses.end());\r\n        for (size_t j=0; j<masses.size(); j++)\r\n        {\r\n            double fragmass = masses[j];\r\n            masses[j] = 0 - (fragmass - decoy.precursors[i].precursorMass) + 100;\r\n        }\r\n        for (size_t j=0; j<decoy.precursors[i].fragments.size(); j++)\r\n        {\r\n            decoy.precursors[i].fragments[j].fragmentMass = masses[j];\r\n        }\r\n    }    \r\n    scoring(lipid, paraMap, spectraHolder, SL);\r\n    \r\n}\r\n\r\n// scoring algorithm\r\nvoid scoring(Lipid lipid, Map & paraMap, vector<SpectraHolder> spectraHolder, const SpectrumListPtr& SL)\r\n{    \r\n    size_t peaks = paraMap[\"PeakNumber\"];\r\n    for (size_t i=0; i<lipid.precursors.size(); i++)\r\n    {\r\n        double test = lipid.precursors[i].precursorMass;\r\n        int searchIndex=0;\r\n        bool searchThis = false;\r\n        for (size_t ii=0; ii<spectraHolder.size(); ii++)\r\n        {\r\n            if ((test >= spectraHolder[ii].preMassN) && (test <= spectraHolder[ii].preMassP))\r\n            {\r\n                searchThis = true;\r\n                searchIndex = ii;\r\n            }\r\n        }\r\n        if (searchThis == false)\r\n        {\r\n            continue;\r\n        }\r\n        int n = searchIndex;\r\n\r\n        while ((test < spectraHolder[n].preMassP) && (test > spectraHolder[n].preMassN) && (n >= 0))\r\n        {\r\n            // get fragment data\r\n            SpectrumPtr s = SL->spectrum(spectraHolder[n].spectraIndex);\r\n            double lowLim, uppLim;\r\n            if (s->scanList.scans[0].scanWindows.empty() == true)\r\n            {\r\n                lowLim = s->cvParam(MS_lowest_observed_m_z).valueAs<double>();\r\n                uppLim = s->cvParam(MS_highest_observed_m_z).valueAs<double>();\r\n            }\r\n            if (s->scanList.scans[0].scanWindows.empty() == false)\r\n            {\r\n                lowLim = s->scanList.scans[0].scanWindows[0].cvParam(MS_scan_window_lower_limit).valueAs<double>();\r\n                uppLim = s->scanList.scans[0].scanWindows[0].cvParam(MS_scan_window_upper_limit).valueAs<double>();\r\n            }\r\n\r\n            double mass = s->precursors[0].selectedIons[0].cvParam(MS_selected_ion_m_z).valueAs<double>();\r\n            const bool getBinaryData = true;\r\n            SpectrumPtr spectrum = SL->spectrum(spectraHolder[n].spectraIndex, getBinaryData);\r\n            vector<MZIntensityPair> pairs;\r\n            spectrum->getMZIntensityPairs(pairs);\r\n            \r\n            // Delete any peaks witin tolerance of the precursor mass\r\n            for (vector<MZIntensityPair>::iterator it = pairs.begin(), end = pairs.end(); it!=end; ++it)\r\n            {\r\n                if ((it->mz > spectraHolder[n].preMassN) && (it->mz < spectraHolder[n].preMassP))\r\n                {\r\n                    pairs.erase (it);\r\n                    --it;\r\n                    pairs.push_back(MZIntensityPair());\r\n                }\r\n            }\r\n            \r\n            int mzNum = 0;\r\n            for (vector<MZIntensityPair>::iterator it = pairs.begin(), end = pairs.end(); it!=end; ++it)\r\n            {\r\n                if (it->mz != 0)\r\n                {\r\n                    mzNum++;\r\n                }\r\n            }\r\n            pairs.resize(mzNum);\r\n            \r\n\r\n            // Sort list by intensity and resize to the number of allowed peaks\r\n            sort(pairs.begin(), pairs.end(), sortByIntensity);\r\n            if (peaks < pairs.size())\r\n            {\r\n                pairs.resize(peaks);\r\n            }\r\n\r\n            // Normalize intensities\r\n            double sum = 0;\r\n            for (vector<MZIntensityPair>::const_iterator it = pairs.begin(), end = pairs.end(); it!=end; ++it)\r\n            {\r\n                sum = sum + it->intensity;\r\n            }\r\n            double factor = 1000/sum;\r\n            for (vector<MZIntensityPair>::iterator it = pairs.begin(), end = pairs.end(); it!=end; ++it)\r\n            {\r\n                double intense = (it->intensity)*factor;\r\n                it->intensity = intense;\r\n            }\r\n\r\n            // Creation of vector containing full list of m/z:intensity pairs \r\n            vector<Match> ms2list(pairs.size());\r\n            int ms2index = 0;\r\n            for (vector<MZIntensityPair>::const_iterator it = pairs.begin(), end = pairs.end(); it!=end; ++it)\r\n            {\r\n                ms2list[ms2index].mz = it->mz;\r\n                ms2list[ms2index].intensity = it->intensity;\r\n                ms2index++;\r\n            }\r\n\r\n            // Creation of vector containing full list of matched peaks\r\n            int matchSize = 0;\r\n            for (size_t m=0; m < lipid.precursors[i].fragments.size(); m++)\r\n            {\r\n                lipid.precursors[i].fragments[m].fragmentMass = floor(lipid.precursors[i].fragments[m].fragmentMass*1000000 + 0.5)/1000000;\r\n            }\r\n            for (size_t m=0; m < lipid.precursors[i].fragments.size(); m++)\r\n            {\r\n                if ((lipid.precursors[i].fragments[m].fragmentMass >= lowLim) && (lipid.precursors[i].fragments[m].fragmentMass <= uppLim))\r\n                {\r\n                    matchSize++;\r\n                }\r\n            }\r\n            vector<Match> match(matchSize);\r\n            int matvecIndex = 0;\r\n            if (paraMap[\"fragTolmz\"] == 1)\r\n            {\r\n                for (size_t m=0; m < lipid.precursors[i].fragments.size(); m++)\r\n                {\r\n                    if ((lipid.precursors[i].fragments[m].fragmentMass >= lowLim) && (lipid.precursors[i].fragments[m].fragmentMass <= uppLim))\r\n                    {\r\n                        match[matvecIndex].mz = lipid.precursors[i].fragments[m].fragmentMass;\r\n                        match[matvecIndex].intensity = 0;\r\n                        match[matvecIndex].match = false;\r\n                        match[matvecIndex].peakIndex = 99999;\r\n                        match[matvecIndex].fragmentD = lipid.precursors[i].fragments[m].fragDescription;\r\n                        match[matvecIndex].fragmentT = lipid.precursors[i].fragments[m].fragType;\r\n                        double variance = paraMap[\"mzFragTol\"];\r\n                                    \r\n                        for (vector<MZIntensityPair>::const_iterator it = pairs.begin(), end = pairs.end(); it!=end; ++it)\r\n                        {\r\n                            if ((abs(lipid.precursors[i].fragments[m].fragmentMass - it->mz) < variance))\r\n                            {\r\n                                int isit = 0;\r\n                                for (size_t nn=0; nn < lipid.precursors[i].fragments.size(); nn++)\r\n                                {                                        \r\n                                    if ((nn!=m) && (abs(lipid.precursors[i].fragments[nn].fragmentMass - it->mz) < abs(lipid.precursors[i].fragments[m].fragmentMass - it->mz)) \r\n                                        && (lipid.precursors[i].fragments[m].fragmentMass >= lowLim) && (lipid.precursors[i].fragments[m].fragmentMass <= uppLim))\r\n                                    {\r\n                                        isit = 1;\r\n                                    }\r\n                                }\r\n                                if (isit == 0)\r\n                                {\r\n                                    match[matvecIndex].match = true;\r\n                                    match[matvecIndex].intensity = it->intensity;\r\n                                    match[matvecIndex].peakIndex = it - pairs.begin();\r\n                                    variance = abs(lipid.precursors[i].fragments[m].fragmentMass - it->mz);\r\n                                }\r\n                            }\r\n                        }\r\n                        matvecIndex++;\r\n                    }\r\n                }\r\n            }\r\n            if (paraMap[\"fragTolmz\"] == 0)\r\n            { \r\n                for (size_t m=0; m < lipid.precursors[i].fragments.size(); m++)\r\n                {\r\n                    if ((lipid.precursors[i].fragments[m].fragmentMass >= lowLim) && (lipid.precursors[i].fragments[m].fragmentMass <= uppLim))\r\n                    {\r\n                        match[matvecIndex].mz = lipid.precursors[i].fragments[m].fragmentMass;\r\n                        match[matvecIndex].intensity = 0;\r\n                        match[matvecIndex].match = false;\r\n                        match[matvecIndex].peakIndex = 99999;\r\n                        match[matvecIndex].fragmentD = lipid.precursors[i].fragments[m].fragDescription;\r\n                        match[matvecIndex].fragmentT = lipid.precursors[i].fragments[m].fragType;\r\n                        double variance = 1000;\r\n                        for (vector<MZIntensityPair>::const_iterator it = pairs.begin(), end = pairs.end(); it!=end; ++it)\r\n                        {\r\n                            double fragTol = paraMap[\"ppmFragTol\"]*(it->mz)/1000000;\r\n                            if ((abs(lipid.precursors[i].fragments[m].fragmentMass - it->mz) < fragTol) \r\n                                && (abs(lipid.precursors[i].fragments[m].fragmentMass - it->mz) < variance))\r\n                            {\r\n                                int isit = 0;\r\n                                for (size_t nn=0; nn < lipid.precursors[i].fragments.size(); nn++)\r\n                                {\r\n                                    if ((nn!=m) && (abs(lipid.precursors[i].fragments[nn].fragmentMass - it->mz) < abs(lipid.precursors[i].fragments[m].fragmentMass - it->mz))\r\n                                        && (lipid.precursors[i].fragments[m].fragmentMass >= lowLim) && (lipid.precursors[i].fragments[m].fragmentMass <= uppLim))\r\n                                    {\r\n                                        isit = 1;\r\n                                    }\r\n                                }\r\n                                if (isit == 0)\r\n                                {\r\n                                    match[matvecIndex].match = true;\r\n                                    match[matvecIndex].intensity = it->intensity;\r\n                                    match[matvecIndex].peakIndex = it - pairs.begin();\r\n                                    variance = abs(lipid.precursors[i].fragments[m].fragmentMass - it->mz);\r\n                                }\r\n                            }\r\n                        }\r\n                        matvecIndex++;\r\n                    }\r\n                }\r\n            }    \r\n\r\n            // This code eliminates entries for lipids with identical FA chains.\r\n            vector<double> tempMZ(match.size());\r\n            size_t tempIndex = 0;\r\n            for (vector<Match>::const_iterator it = match.begin(), end = match.end(); it!=end; ++it)\r\n            {\r\n                tempMZ[tempIndex] = it->mz;\r\n                tempIndex++;\r\n            }\r\n            for (size_t m=0; m<tempMZ.size(); m++)\r\n            {\r\n                int indexA = 0;\r\n                for (vector<Match>::iterator it = match.begin(), end = match.end(); it!=end; ++it)\r\n                {\r\n\r\n                    if ((it->mz == tempMZ[m]) && (indexA != 0))\r\n                    {\r\n                        match.erase (it);\r\n                        --it;\r\n                        match.push_back(Match());\r\n                        match.back().mz = 0;\r\n                    }\r\n                    if ((it->mz == tempMZ[m]) && (indexA == 0))\r\n                    {\r\n                        indexA++;\r\n                    }\r\n                }\r\n            }\r\n            int indexB = 0;\r\n            for (vector<Match>::const_iterator it = match.begin(), end = match.end(); it!=end; ++it)\r\n            {\r\n                            \r\n                if (it->mz != 0)\r\n                {\r\n                    indexB++;\r\n                }\r\n            }\r\n            match.resize(indexB);\r\n\r\n            // calculates the number of matched peaks and \"continues\" if zero\r\n            int x = 0;\r\n            for (size_t m=0; m<match.size(); m++)\r\n            {\r\n                if (match[m].match)\r\n                {\r\n                    x++;\r\n                }                            \r\n            }\r\n            if (x == 0)\r\n            {\r\n                n--;\r\n                continue;\r\n            }    \r\n            \r\n            // set number of bins, filled bins, matching peaks, and support for the HGM method\r\n            double N;\r\n            if (paraMap[\"fragTolmz\"] == 1)\r\n            {\r\n                N = round((uppLim - lowLim)/paraMap[\"mzFragTol\"]);\r\n            }\r\n            else if (paraMap[\"fragTolmz\"] == 0)\r\n            {\r\n                N = round((uppLim - lowLim)/(paraMap[\"ppmFragTol\"]*((lowLim + uppLim)/2)/1000000));\r\n            }\r\n            int K = ms2list.size();\r\n            int M = match.size();\r\n\r\n            // calculate peakScore\r\n            double c = factorials[N] - factorials[K] - factorials[N - K];\r\n            double peakScore = 0;\r\n            int Q = min(M, K);\r\n            \r\n            if (x != 0)\r\n            {\r\n                for (int m=x; m<Q+1; m++)\r\n                {\r\n                    double a = factorials[M] - factorials[m] - factorials[M - m];\r\n                    double b = factorials[N - M] - factorials[(N - M) - (K - m)] - factorials[K - m];\r\n                    peakScore = peakScore + pow(10, a + b - c);\r\n                        \r\n                }\r\n            }\r\n            else\r\n            {\r\n                peakScore = 1;\r\n            }\r\n            \r\n            // calculate intensityScore\r\n            double intensitySum = 0;\r\n            for (size_t m=0; m<match.size(); m++)\r\n            {\r\n                intensitySum = intensitySum + match[m].intensity;\r\n            }\r\n                \r\n            double iScore2;\r\n            int numerator = 0;\r\n            int* pNum = &numerator;\r\n\r\n\r\n            if (x > 0)\r\n            {\r\n                combo(0, intensitySum, 0, x, ms2list, pNum);\r\n                double num = numerator;\r\n                double den =  factorials[K] - factorials[x] - factorials[K - x];\r\n                iScore2 = (log10(num) - den);\r\n            }\r\n            else\r\n            {\r\n                iScore2 = 0;\r\n            }\r\n\r\n            // calculate chi-squared value\r\n            long double totalScore;\r\n            if ((peakScore == 1) && (iScore2 == 0))\r\n            {\r\n                totalScore = 0;\r\n            }\r\n            else\r\n            {\r\n                if (paraMap[\"intensityScore\"] == 1)\r\n                {\r\n                    totalScore = -2*(log(peakScore) + log(pow(10,iScore2)));\r\n                }\r\n                if (paraMap[\"intensityScore\"] == 0)\r\n                {\r\n                    totalScore = -2*log(peakScore);\r\n                }\r\n            }\r\n\r\n            sort(match.begin(), match.end(), sortByMZr);\r\n\r\n            spec[spectraHolder[n].spectraIndex].push_back(Score());\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].totalScore = totalScore;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].intensityScore = iScore2;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].peakScore = peakScore;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].spectrumNumber = spectraHolder[n].spectraIndex;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].spectrumPrecursorMass = mass;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].lipidName = lipid.name;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].lipidMass = lipid.totalMass;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].chemFormula = lipid.lipidFormula;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].precursorDescription = lipid.precursors[i].description;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].precursorMass = lipid.precursors[i].precursorMass;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].match = match;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].ms2list = ms2list;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].retTime = spectraHolder[n].retentionTime;\r\n            spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].mod = lipid.precursors[i].adduct;\r\n\r\n            if (lipid.precursors[i].ESI == \"pos\")\r\n            {\r\n                spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].charge = \"+1\";\r\n            }\r\n            if ((lipid.precursors[i].ESI == \"neg\") && (lipid.precursors[i].description != \"deprotonatedX2\"))\r\n            {\r\n                spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].charge = \"-1\";\r\n            }\r\n            if ((lipid.precursors[i].ESI == \"neg\") && (lipid.precursors[i].description == \"deprotonatedX2\"))\r\n            {\r\n                spec[spectraHolder[n].spectraIndex][spec[spectraHolder[n].spectraIndex].size()-1].charge = \"-2\";\r\n            }\r\n\r\n            sort(spec[spectraHolder[n].spectraIndex].begin(), spec[spectraHolder[n].spectraIndex].end(), sortByName);\r\n            sort(spec[spectraHolder[n].spectraIndex].begin(), spec[spectraHolder[n].spectraIndex].end(), sortByTotalScore);\r\n\r\n            int pc = 0;\r\n            int pe = 0;\r\n            int pi = 0;\r\n            int pg = 0;\r\n            int ps = 0;\r\n            int pa = 0;\r\n            int sm = 0;\r\n            int pip = 0;\r\n            int pip2 = 0;\r\n            int cl = 0;\r\n            int cl2 = 0;\r\n            int mpc = 0;\r\n            int mpe = 0;\r\n            int mpi = 0;\r\n            int mpg = 0;\r\n            int mps = 0;\r\n            int mpa = 0;\r\n            int msm = 0;\r\n            //int m3cl = 0;\r\n            int mcl = 0;\r\n            int mpip = 0;\r\n            int pec = 0;\r\n            int pic = 0;\r\n            int mpec = 0;\r\n            int mpic = 0;\r\n\r\n            vector<Score> specTemp;\r\n            for (size_t m=0; m<spec[spectraHolder[n].spectraIndex].size(); m++)\r\n            {\r\n                if (lipid.precursors[i].ESI == \"pos\")\r\n                {\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PC\" && pc == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pc = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PC\" && mpc == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mpc = 1;\r\n                    }\r\n\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PE(\" && pe == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pe = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PE(\" && mpe == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mpe = 1;\r\n                    }\r\n\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PI(\" && pi == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pi = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PI(\" && mpi == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mpi = 1;\r\n                    }\r\n\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PG\" && pg == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pg = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PG\" && mpg == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mpg = 1;\r\n                    }\r\n\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PS\" && ps == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        ps = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PS\" && mps == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mps = 1;\r\n                    }\r\n\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PA\" && pa == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pa = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PA\" && mpa == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mpa = 1;\r\n                    }\r\n\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"SM\" && sm == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        sm = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"SM\" && msm == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        msm = 1;\r\n                    }                \r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 6) == \"PE-Cer\" && pec == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pec = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 6) == \"PE-Cer\" && mpec == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mpec = 1;\r\n                    }\r\n\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 6) == \"PI-Cer\" && pic == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pic = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 6) == \"PI-Cer\" && mpic == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mpic = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PIP\" && pip == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"+H\" || spec[spectraHolder[n].spectraIndex][m].mod == \"+NH4\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pip = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PIP\" && mpip == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"+H\" && spec[spectraHolder[n].spectraIndex][m].mod != \"+NH4\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mpip = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"CL\" && cl == 0 && spec[spectraHolder[n].spectraIndex][m].mod != \"-2H + 3Na\" && spec[spectraHolder[n].spectraIndex][m].mod != \"-2H + 3Li\" && spec[spectraHolder[n].spectraIndex][m].mod != \"-2H + 3K\")\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        cl = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"CL\" && mcl == 0 && (spec[spectraHolder[n].spectraIndex][m].mod == \"-2H + 3Na\" || spec[spectraHolder[n].spectraIndex][m].mod == \"-2H + 3Li\" || spec[spectraHolder[n].spectraIndex][m].mod == \"-2H + 3K\"))\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mcl = 1;\r\n                    }\r\n                }\r\n\r\n                if (lipid.precursors[i].ESI == \"neg\")\r\n                {\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PC\" && pc == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pc = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PE(\" && pe == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pe = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PI(\" && pi == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pi = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PG\" && pg == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pg = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PS\" && ps == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        ps = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"PA\" && pa == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pa = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"SM\" && sm == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        sm = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 6) == \"PE-Cer\" && sm == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pec = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 6) == \"PI-Cer\" && sm == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pic = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"CL\" && spec[spectraHolder[n].spectraIndex][m].mod == \"-H\" && cl == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        cl = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"CL\" && (spec[spectraHolder[n].spectraIndex][m].mod == \"-2H + Na\" || spec[spectraHolder[n].spectraIndex][m].mod == \"-2H + K\" || spec[spectraHolder[n].spectraIndex][m].mod == \"-2H + Li\" ) && mcl == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        mcl = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 2) == \"CL\" && spec[spectraHolder[n].spectraIndex][m].mod == \"-2H\" && cl2 == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        cl2 = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PIP\" && spec[spectraHolder[n].spectraIndex][m].mod != \"-2H\" && pip == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pip = 1;\r\n                    }\r\n                    if (spec[spectraHolder[n].spectraIndex][m].lipidName.substr(0, 3) == \"PIP\" && spec[spectraHolder[n].spectraIndex][m].mod == \"-2H\" && pip2 == 0)\r\n                    {\r\n                        specTemp.push_back(spec[spectraHolder[n].spectraIndex][m]);\r\n                        pip2 = 1;\r\n                    }\r\n                }\r\n            }\r\n            spec[spectraHolder[n].spectraIndex] = specTemp;\r\n\r\n            if (totalScore > firstSecondFull[spectraHolder[n].spectraIndex][0])\r\n            {\r\n                firstSecondFull[spectraHolder[n].spectraIndex][1] = firstSecondFull[spectraHolder[n].spectraIndex][0];\r\n                firstSecondFull[spectraHolder[n].spectraIndex][0] = totalScore;\r\n            }\r\n            if (totalScore < firstSecondFull[spectraHolder[n].spectraIndex][0] && totalScore > firstSecondFull[spectraHolder[n].spectraIndex][1])\r\n            {\r\n                firstSecondFull[spectraHolder[n].spectraIndex][1] = totalScore;\r\n            }\r\n\r\n            if (lipid.precursors[i].ESI == \"pos\")\r\n            {\r\n                if (lipid.name.substr(0, 2) == \"PC\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PC[1] = secondary[spectraHolder[n].spectraIndex].PC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PC[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"PC\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPC[1] = secondary[spectraHolder[n].spectraIndex].MPC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPC[1] = totalScore;\r\n                    }\r\n                }\r\n\r\n                if (lipid.name.substr(0, 3) == \"PE(\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PE[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PE[1] = secondary[spectraHolder[n].spectraIndex].PE[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PE[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PE[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PE[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PE[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 3) == \"PE(\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPE[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPE[1] = secondary[spectraHolder[n].spectraIndex].MPE[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPE[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPE[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPE[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPE[1] = totalScore;\r\n                    }\r\n                }\r\n\r\n                if (lipid.name.substr(0, 3) == \"PI(\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PI[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PI[1] = secondary[spectraHolder[n].spectraIndex].PI[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PI[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PI[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PI[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PI[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 3) == \"PI(\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPI[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPI[1] = secondary[spectraHolder[n].spectraIndex].MPI[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPI[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPI[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPI[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPI[1] = totalScore;\r\n                    }\r\n                }\r\n\r\n                if (lipid.name.substr(0, 2) == \"PG\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PG[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PG[1] = secondary[spectraHolder[n].spectraIndex].PG[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PG[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PG[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PG[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PG[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"PG\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPG[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPG[1] = secondary[spectraHolder[n].spectraIndex].MPG[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPG[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPG[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPG[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPG[1] = totalScore;\r\n                    }\r\n                }\r\n\r\n                if (lipid.name.substr(0, 2) == \"PS\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PS[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PS[1] = secondary[spectraHolder[n].spectraIndex].PS[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PS[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PS[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PS[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PS[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"PS\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPS[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPS[1] = secondary[spectraHolder[n].spectraIndex].MPS[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPS[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPS[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPS[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPS[1] = totalScore;\r\n                    }\r\n                }\r\n\r\n                if (lipid.name.substr(0, 2) == \"PA\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PA[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PA[1] = secondary[spectraHolder[n].spectraIndex].PA[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PA[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PA[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PA[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PA[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"PA\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPA[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPA[1] = secondary[spectraHolder[n].spectraIndex].MPA[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPA[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPA[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPA[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPA[1] = totalScore;\r\n                    }\r\n                }\r\n\r\n                if (lipid.name.substr(0, 2) == \"CL\" && lipid.precursors[i].adduct != \"-2H + 3Na\" && lipid.precursors[i].adduct != \"-2H + 3Li\" && lipid.precursors[i].adduct != \"-2H + 3K\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].CL[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].CL[1] = secondary[spectraHolder[n].spectraIndex].CL[0];\r\n                        secondary[spectraHolder[n].spectraIndex].CL[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].CL[0] && totalScore > secondary[spectraHolder[n].spectraIndex].CL[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].CL[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"CL\" && (lipid.precursors[i].adduct == \"-2H + 3Na\" || lipid.precursors[i].adduct == \"-2H + 3Li\" || lipid.precursors[i].adduct == \"-2H + 3K\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MCL[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MCL[1] = secondary[spectraHolder[n].spectraIndex].MCL[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MCL[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MCL[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MCL[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MCL[1] = totalScore;\r\n                    }\r\n                }\r\n\r\n                if (lipid.name.substr(0, 2) == \"SM\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].SM[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].SM[1] = secondary[spectraHolder[n].spectraIndex].SM[0];\r\n                        secondary[spectraHolder[n].spectraIndex].SM[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].SM[0] && totalScore > secondary[spectraHolder[n].spectraIndex].SM[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].SM[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"SM\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MSM[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MSM[1] = secondary[spectraHolder[n].spectraIndex].MSM[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MSM[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MSM[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MSM[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MSM[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 6) == \"PE-Cer\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PEC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PEC[1] = secondary[spectraHolder[n].spectraIndex].PEC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PEC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PEC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PEC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PEC[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 6) == \"PE-Cer\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPEC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPEC[1] = secondary[spectraHolder[n].spectraIndex].MPEC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPEC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPEC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPEC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPEC[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 6) == \"PI-Cer\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PIC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIC[1] = secondary[spectraHolder[n].spectraIndex].PIC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PIC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PIC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PIC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIC[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 6) == \"PI-Cer\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPIC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPIC[1] = secondary[spectraHolder[n].spectraIndex].MPIC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPIC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPIC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPIC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPIC[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 3) == \"PIP\" && (lipid.precursors[i].adduct == \"+H\" || lipid.precursors[i].adduct == \"+NH4\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PIP[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIP[1] = secondary[spectraHolder[n].spectraIndex].PIP[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PIP[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PIP[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PIP[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIP[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 3) == \"PIP\" && lipid.precursors[i].adduct != \"+H\" && lipid.precursors[i].adduct != \"+NH4\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MPIP[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPIP[1] = secondary[spectraHolder[n].spectraIndex].MPIP[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MPIP[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MPIP[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MPIP[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MPIP[1] = totalScore;\r\n                    }\r\n                }\r\n            }\r\n            if (lipid.precursors[i].ESI == \"neg\")\r\n            {\r\n                if (lipid.name.substr(0, 2) == \"PC\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PC[1] = secondary[spectraHolder[n].spectraIndex].PC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PC[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 3) == \"PE(\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PE[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PE[1] = secondary[spectraHolder[n].spectraIndex].PE[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PE[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PE[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PE[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PE[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 3) == \"PI(\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PI[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PI[1] = secondary[spectraHolder[n].spectraIndex].PI[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PI[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PI[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PI[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PI[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"PG\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PG[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PG[1] = secondary[spectraHolder[n].spectraIndex].PG[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PG[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PG[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PG[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PG[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"PS\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PS[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PS[1] = secondary[spectraHolder[n].spectraIndex].PS[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PS[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PS[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PS[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PS[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"PA\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PA[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PA[1] = secondary[spectraHolder[n].spectraIndex].PA[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PA[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PA[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PA[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PA[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"CL\" && lipid.precursors[i].adduct == \"-H\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].CL[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].CL[1] = secondary[spectraHolder[n].spectraIndex].CL[0];\r\n                        secondary[spectraHolder[n].spectraIndex].CL[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].CL[0] && totalScore > secondary[spectraHolder[n].spectraIndex].CL[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].CL[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"CL\" && (lipid.precursors[i].adduct == \"-2H + Na\" || lipid.precursors[i].adduct == \"-2H + K\" ||lipid.precursors[i].adduct == \"-2H + Li\"))\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].MCL[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MCL[1] = secondary[spectraHolder[n].spectraIndex].MCL[0];\r\n                        secondary[spectraHolder[n].spectraIndex].MCL[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].MCL[0] && totalScore > secondary[spectraHolder[n].spectraIndex].MCL[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].MCL[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"CL\" && lipid.precursors[i].adduct == \"-2H\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].CL2[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].CL2[1] = secondary[spectraHolder[n].spectraIndex].CL2[0];\r\n                        secondary[spectraHolder[n].spectraIndex].CL2[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].CL2[0] && totalScore > secondary[spectraHolder[n].spectraIndex].CL2[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].CL2[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 2) == \"SM\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].SM[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].SM[1] = secondary[spectraHolder[n].spectraIndex].SM[0];\r\n                        secondary[spectraHolder[n].spectraIndex].SM[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].SM[0] && totalScore > secondary[spectraHolder[n].spectraIndex].SM[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].SM[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 6) == \"PE-Cer\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PEC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PEC[1] = secondary[spectraHolder[n].spectraIndex].PEC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PEC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PEC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PEC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PEC[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 6) == \"PI-Cer\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PIC[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIC[1] = secondary[spectraHolder[n].spectraIndex].PIC[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PIC[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PIC[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PIC[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIC[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 3) == \"PIP\" && lipid.precursors[i].adduct != \"-2H\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PIP[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIP[1] = secondary[spectraHolder[n].spectraIndex].PIP[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PIP[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PIP[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PIP[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIP[1] = totalScore;\r\n                    }\r\n                }\r\n                if (lipid.name.substr(0, 3) == \"PIP\" && lipid.precursors[i].adduct == \"-2H\")\r\n                {\r\n                    if (totalScore > secondary[spectraHolder[n].spectraIndex].PIP2[0])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIP2[1] = secondary[spectraHolder[n].spectraIndex].PIP2[0];\r\n                        secondary[spectraHolder[n].spectraIndex].PIP2[0] = totalScore;\r\n                    }\r\n                    if (totalScore < secondary[spectraHolder[n].spectraIndex].PIP2[0] && totalScore > secondary[spectraHolder[n].spectraIndex].PIP2[1])\r\n                    {\r\n                        secondary[spectraHolder[n].spectraIndex].PIP2[1] = totalScore;\r\n                    }\r\n                }\r\n            }\r\n            n--;\r\n        }\r\n    }\r\n}", "meta": {"hexsha": "11a140c130188248bf9017cde17fcae7c2511987", "size": 638553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz_tools/Bumbershoot/greazy/greazy.cpp", "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/greazy/greazy.cpp", "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/greazy/greazy.cpp", "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": 61.7496373658, "max_line_length": 291, "alphanum_fraction": 0.4716397856, "num_tokens": 140119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1765960975200735}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <scitbx/lbfgsb.h>\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\nnamespace scitbx { namespace lbfgsb { namespace {\n\n  template <typename FloatType>\n  struct minimizer_wrappers\n  {\n    typedef minimizer<FloatType> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"minimizer\", no_init)\n        .def(init<int const&,\n                  int const&,\n                  af::shared<FloatType>,\n                  af::shared<FloatType>,\n                  af::shared<int>,\n                  bool,\n                  FloatType const&,\n                  FloatType const&,\n                  int const&>())\n        .def(\"process\", &w_t::process, (\n          arg(\"x\"),\n          arg(\"f\"),\n          arg(\"g\"),\n          arg(\"use_fortran_library\")=false))\n        .def(\"requests_f_and_g\", &w_t::requests_f_and_g)\n        .def(\"requests_stp_init\", &w_t::requests_stp_init)\n        .def(\"is_terminated\", &w_t::is_terminated)\n        .def(\"task\", &w_t::task)\n        .def(\"f_list\", &w_t::f_list)\n        .def(\"f\", &w_t::f)\n        .def(\"request_restart\", &w_t::request_restart)\n        .def(\"request_stop\", &w_t::request_stop)\n        .def(\"request_stop_with_restore\", &w_t::request_stop_with_restore)\n        .def(\"n\", &w_t::n)\n        .def(\"m\", &w_t::m)\n        .def(\"l\", &w_t::l)\n        .def(\"u\", &w_t::u)\n        .def(\"nbd\", &w_t::nbd)\n        .def(\"enable_stp_init\", &w_t::enable_stp_init)\n        .def(\"factr\", &w_t::factr)\n        .def(\"pgtol\", &w_t::pgtol)\n        .def(\"iprint\", &w_t::iprint)\n        .def(  \"initial_x_replaced_by_projection\",\n          &w_t::initial_x_replaced_by_projection)\n        .def(\"is_constrained\", &w_t::is_constrained)\n        .def(\"is_fully_constrained\", &w_t::is_fully_constrained)\n        .def(\"n_iteration\", &w_t::n_iteration)\n        .def(\"n_fg_evaluations_total\", &w_t::n_fg_evaluations_total)\n        .def(\"n_fg_evaluations_iter\", &w_t::n_fg_evaluations_iter)\n        .def(  \"n_intervals_explored_cauchy_search_total\",\n          &w_t::n_intervals_explored_cauchy_search_total)\n        .def(  \"n_intervals_explored_cauchy_search_iter\",\n          &w_t::n_intervals_explored_cauchy_search_iter)\n        .def(  \"n_skipped_bfgs_updates_total\",\n          &w_t::n_skipped_bfgs_updates_total)\n        .def(\"n_bfgs_updates_total\", &w_t::n_bfgs_updates_total)\n        .def(  \"subspace_argmin_is_within_box\",\n          &w_t::subspace_argmin_is_within_box)\n        .def(\"n_free_variables\", &w_t::n_free_variables)\n        .def(\"n_active_constraints\", &w_t::n_active_constraints)\n        .def(  \"n_variables_leaving_active_set\",\n          &w_t::n_variables_leaving_active_set)\n        .def(  \"n_variables_entering_active_set\",\n          &w_t::n_variables_entering_active_set)\n        .def(\"theta_bfgs_matrix_current\", &w_t::theta_bfgs_matrix_current)\n        .def(\"f_previous_iteration\", &w_t::f_previous_iteration)\n        .def(\"floating_point_epsilon\", &w_t::floating_point_epsilon)\n        .def(  \"factr_times_floating_point_epsilon\",\n          &w_t::factr_times_floating_point_epsilon)\n        .def(  \"two_norm_line_search_direction_vector\",\n          &w_t::two_norm_line_search_direction_vector)\n        .def(  \"two_norm_line_search_direction_vector_sq\",\n          &w_t::two_norm_line_search_direction_vector_sq)\n        .def(  \"accumulated_time_cauchy_search\",\n          &w_t::accumulated_time_cauchy_search)\n        .def(  \"accumulated_time_subspace_minimization\",\n          &w_t::accumulated_time_subspace_minimization)\n        .def(  \"accumulated_time_line_search\",\n          &w_t::accumulated_time_line_search)\n        .def(  \"slope_line_search_function_current\",\n          &w_t::slope_line_search_function_current)\n        .def(  \"slope_line_search_function_start\",\n          &w_t::slope_line_search_function_start)\n        .def(  \"maximum_relative_step_length\",\n          &w_t::maximum_relative_step_length)\n        .def(  \"relative_step_length_line_search\",\n          &w_t::relative_step_length_line_search)\n        .def(  \"set_relative_step_length_line_search\",\n          &w_t::set_relative_step_length_line_search, (\n            arg(\"value\")))\n        .def(  \"infinity_norm_projected_gradient\",\n          &w_t::infinity_norm_projected_gradient)\n        .def(  \"current_search_direction\",\n          &w_t::current_search_direction)\n      ;\n    }\n  };\n\n  void init_module()\n  {\n    using namespace boost::python;\n\n    minimizer_wrappers<double>::wrap();\n  }\n\n}}} // namespace scitbx::lbfgs::<anonymous>\n\nBOOST_PYTHON_MODULE(scitbx_lbfgsb_ext)\n{\n  scitbx::lbfgsb::init_module();\n}\n", "meta": {"hexsha": "4c6a2a0c308ec2f227d00b520b42dc8ddb7f4f44", "size": 4667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/lbfgsb/boost_python/lbfgsb_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": "scitbx/lbfgsb/boost_python/lbfgsb_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": "scitbx/lbfgsb/boost_python/lbfgsb_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": 38.5702479339, "max_line_length": 74, "alphanum_fraction": 0.6370259267, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17659609752007346}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2022 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2022 Ilias Khairullin <ilias@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#define BOOST_ENABLE_ASSERT_HANDLER\n#include <boost/assert.hpp>\n\n#include <iostream>\n#include <filesystem>\n#include <fstream>\n#include <string>\n#include <functional>\n#include <time.h>\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#include <nil/crypto3/zk/components/voting/encrypted_input_voting.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#include <nil/crypto3/algebra/pairing/bls12.hpp>\n#include <nil/crypto3/algebra/pairing/mnt4.hpp>\n#include <nil/crypto3/algebra/pairing/mnt6.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n#include <nil/crypto3/zk/components/blueprint_variable.hpp>\n#include <nil/crypto3/zk/components/disjunction.hpp>\n\n#include <nil/crypto3/zk/snark/systems/ppzksnark/r1cs_gg_ppzksnark.hpp>\n\n#include <nil/crypto3/zk/algorithms/generate.hpp>\n#include <nil/crypto3/zk/algorithms/verify.hpp>\n#include <nil/crypto3/zk/algorithms/prove.hpp>\n\n#include <nil/marshalling/status_type.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/primary_input.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/proof.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/verification_key.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/proving_key.hpp>\n#include <nil/crypto3/marshalling/pubkey/types/elgamal_verifiable.hpp>\n\n#include <nil/crypto3/pubkey/algorithm/generate_keypair.hpp>\n#include <nil/crypto3/pubkey/algorithm/encrypt.hpp>\n#include <nil/crypto3/pubkey/algorithm/decrypt.hpp>\n#include <nil/crypto3/pubkey/algorithm/verify_encryption.hpp>\n#include <nil/crypto3/pubkey/algorithm/verify_decryption.hpp>\n#include <nil/crypto3/pubkey/algorithm/rerandomize.hpp>\n#include <nil/crypto3/pubkey/elgamal_verifiable.hpp>\n#include <nil/crypto3/pubkey/modes/verifiable_encryption.hpp>\n\n#include <nil/crypto3/random/algebraic_random_device.hpp>\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::algebra;\nusing namespace nil::crypto3::pubkey;\nusing namespace nil::crypto3::marshalling;\nusing namespace nil::crypto3::zk;\n\nnamespace boost {\n    void assertion_failed(char const *expr, char const *function, char const *file, long line) {\n        std::cerr << \"Error: in file \" << file << \": in function \" << function << \": on line \" << line << std::endl;\n        std::exit(1);\n    }\n    void assertion_failed_msg(char const *expr, char const *msg, char const *function, char const *file, long line) {\n        std::cerr << \"Error: in file \" << file << \": in function \" << function << \": on line \" << line << std::endl\n                  << std::endl;\n        std::cerr << \"Error message:\" << std::endl << msg << std::endl;\n        std::exit(1);\n    }\n}    // namespace boost\n\ntemplate<typename TIter>\nvoid print_byteblob(std::ostream &os, TIter iter_begin, TIter iter_end) {\n    os << std::hex;\n    for (TIter it = iter_begin; it != iter_end; it++) {\n        os << std::setfill('0') << std::setw(2) << std::right << int(*it);\n    }\n    os << std::dec << std::endl;\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp<FieldParams> &e,\n                         bool endline = true) {\n    os << e.data;\n    if (endline) {\n        os << std::endl;\n    }\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp2<FieldParams> &e,\n                         bool endline = true) {\n    os << e.data[0].data << \", \" << e.data[1].data;\n    if (endline) {\n        os << std::endl;\n    }\n}\n\ntemplate<typename CurveParams, typename Form, typename Coordinates>\ntypename std::enable_if<std::is_same<Coordinates, curves::coordinates::affine>::value>::type\n    print_curve_point(std::ostream &os, const curves::detail::curve_element<CurveParams, Form, Coordinates> &p) {\n    os << \"( X: [\";\n    print_field_element(os, p.X, false);\n    os << \"], Y: [\";\n    print_field_element(os, p.Y, false);\n    os << \"] )\" << std::endl;\n}\n\ntemplate<typename CurveParams, typename Form, typename Coordinates>\ntypename std::enable_if<std::is_same<Coordinates, curves::coordinates::projective>::value ||\n                        std::is_same<Coordinates, curves::coordinates::jacobian_with_a4_0>::value ||\n                        std::is_same<Coordinates, curves::coordinates::inverted>::value>::type\n    print_curve_point(std::ostream &os, const curves::detail::curve_element<CurveParams, Form, Coordinates> &p) {\n    os << \"( X: [\";\n    print_field_element(os, p.X, false);\n    os << \"], Y: [\";\n    print_field_element(os, p.Y, false);\n    os << \"], Z:[\";\n    print_field_element(os, p.Z, false);\n    os << \"] )\" << std::endl;\n}\n\nstruct encrypted_input_policy {\n    using pairing_curve_type = curves::bls12_381;\n    using curve_type = curves::jubjub;\n    using base_points_generator_hash_type = hashes::sha2<256>;\n    using hash_params = hashes::find_group_hash_default_params;\n    using hash_component = components::pedersen<curve_type, base_points_generator_hash_type, hash_params>;\n    using hash_type = typename hash_component::hash_type;\n    using merkle_hash_component = hash_component;\n    using merkle_hash_type = typename merkle_hash_component::hash_type;\n    using field_type = typename hash_component::field_type;\n    static constexpr std::size_t arity = 2;\n    using voting_component =\n        components::encrypted_input_voting<arity, hash_component, merkle_hash_component, field_type>;\n    using merkle_proof_component = typename voting_component::merkle_proof_component;\n    using encryption_scheme_type = elgamal_verifiable<pairing_curve_type>;\n    using proof_system = typename encryption_scheme_type::proof_system_type;\n    static constexpr std::size_t msg_size = 25;\n    static constexpr std::size_t secret_key_bits = hash_type::digest_bits;\n    static constexpr std::size_t public_key_bits = secret_key_bits;\n};\n\nstruct marshaling_policy {\n    using scalar_field_value_type =\n        typename encrypted_input_policy::encryption_scheme_type::curve_type::scalar_field_type::value_type;\n    using proof_type = typename encrypted_input_policy::proof_system::proof_type;\n    using verification_key_type = typename encrypted_input_policy::proof_system::verification_key_type;\n    using proving_key_type = typename encrypted_input_policy::proof_system::proving_key_type;\n    using primary_input_type = typename encrypted_input_policy::proof_system::primary_input_type;\n    using elgamal_public_key_type = typename encrypted_input_policy::encryption_scheme_type::public_key_type;\n    using elgamal_private_key_type = typename encrypted_input_policy::encryption_scheme_type::private_key_type;\n    using elgamal_verification_key_type =\n        typename encrypted_input_policy::encryption_scheme_type::verification_key_type;\n\n    using endianness = nil::marshalling::option::big_endian;\n    using r1cs_proof_marshaling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_proof<nil::marshalling::field_type<endianness>, proof_type>;\n    using r1cs_verification_key_marshaling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_extended_verification_key<\n            nil::marshalling::field_type<endianness>, verification_key_type>;\n    using r1cs_proving_key_marshalling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_proving_key<nil::marshalling::field_type<endianness>,\n                                                                        proving_key_type>;\n    using public_key_marshaling_type =\n        nil::crypto3::marshalling::types::elgamal_verifiable_public_key<nil::marshalling::field_type<endianness>,\n                                                                        elgamal_public_key_type>;\n    using secret_key_marshaling_type =\n        nil::crypto3::marshalling::types::elgamal_verifiable_private_key<nil::marshalling::field_type<endianness>,\n                                                                         elgamal_private_key_type>;\n    using verification_key_marshaling_type =\n        nil::crypto3::marshalling::types::elgamal_verifiable_verification_key<nil::marshalling::field_type<endianness>,\n                                                                              elgamal_verification_key_type>;\n    using ct_marshaling_type = nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_encrypted_primary_input<\n        nil::marshalling::field_type<endianness>,\n        encrypted_input_policy::encryption_scheme_type::cipher_type::first_type>;\n    using pinput_marshaling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_primary_input<nil::marshalling::field_type<endianness>,\n                                                                          primary_input_type>;\n\n    template<typename MarshalingType, typename InputObj, typename F>\n    static std::vector<std::uint8_t> serialize_obj(const InputObj &in_obj, const std::function<F> &f) {\n        MarshalingType filled_val = f(in_obj);\n        std::vector<std::uint8_t> blob(filled_val.length());\n        auto it = std::begin(blob);\n        nil::marshalling::status_type status = filled_val.write(it, blob.size());\n        return blob;\n    }\n\n    template<typename Path, typename Blob>\n    static void write_obj(const Path &path, std::initializer_list<Blob> blobs) {\n        if (std::filesystem::exists(path)) {\n            std::cout << \"File \" << path << \" exists and won't be overwritten.\" << std::endl;\n            return;\n        }\n        std::ofstream out(path, std::ios_base::binary);\n        for (const auto &blob : blobs) {\n            for (const auto b : blob) {\n                out << b;\n            }\n        }\n        out.close();\n    }\n\n    template<typename MarshalingType, typename ReturnType, typename InputBlob, typename F>\n    static ReturnType deserialize_obj(const InputBlob &blob, const std::function<F> &f) {\n        MarshalingType marshaling_obj;\n        auto it = std::cbegin(blob);\n        nil::marshalling::status_type status = marshaling_obj.read(it, blob.size());\n        return f(marshaling_obj);\n    }\n\n    template<typename Path>\n    static std::vector<std::uint8_t> read_obj(const Path &path) {\n        BOOST_ASSERT_MSG(\n            std::filesystem::exists(path),\n            (std::string(\"File \") + path + std::string(\" doesn't exist, make sure you created it!\")).c_str());\n        std::ifstream in(path, std::ios_base::binary);\n        std::stringstream buffer;\n        buffer << in.rdbuf();\n        auto blob_str = buffer.str();\n        return {std::cbegin(blob_str), std::cend(blob_str)};\n    }\n\n    static void write_initial_phase_voter_data(const std::vector<scalar_field_value_type> &voter_pubkey,\n                                               const std::vector<scalar_field_value_type> &voter_skey, std::size_t i,\n                                               const std::string &voter_pk_out, const std::string &voter_sk_out) {\n        auto pubkey_blob = serialize_obj<pinput_marshaling_type>(\n            voter_pubkey,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (!voter_pk_out.empty()) {\n            auto filename = voter_pk_out + std::to_string(i) + \".bin\";\n            write_obj(std::filesystem::path(filename), {pubkey_blob});\n        }\n\n        auto sk_blob = serialize_obj<pinput_marshaling_type>(\n            voter_skey,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (!voter_sk_out.empty()) {\n            auto filename = voter_sk_out + std::to_string(i) + \".bin\";\n            write_obj(std::filesystem::path(filename), {sk_blob});\n        }\n    }\n\n    static void serialize_initial_phase_voter_data(const std::vector<scalar_field_value_type> &voter_pubkey,\n                                                   const std::vector<scalar_field_value_type> &voter_skey,\n                                                   std::vector<std::uint8_t> &voter_pk_out,\n                                                   std::vector<std::uint8_t> &voter_sk_out) {\n        voter_pk_out = serialize_obj<pinput_marshaling_type>(\n            voter_pubkey,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        voter_sk_out = serialize_obj<pinput_marshaling_type>(\n            voter_skey,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n    }\n\n    static void write_initial_phase_admin_data(\n        const proving_key_type &pk_crs, const verification_key_type &vk_crs, const elgamal_public_key_type &pk_eid,\n        const elgamal_private_key_type &sk_eid, const elgamal_verification_key_type &vk_eid,\n        const primary_input_type &eid, const primary_input_type &rt, const std::string &r1cs_proving_key_out,\n        const std::string &r1cs_verification_key_out, const std::string &public_key_output,\n        const std::string &secret_key_output, const std::string &verification_key_output, const std::string &eid_output,\n        const std::string &rt_output) {\n        auto pk_crs_blob = serialize_obj<r1cs_proving_key_marshalling_type>(\n            pk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_proving_key<proving_key_type, endianness>));\n        if (!r1cs_proving_key_out.empty()) {\n            auto filename = r1cs_proving_key_out + \".bin\";\n            write_obj(std::filesystem::path(filename), {pk_crs_blob});\n        }\n\n        auto vk_crs_blob = serialize_obj<r1cs_verification_key_marshaling_type>(\n            vk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_verification_key<verification_key_type,\n                                                                                          endianness>));\n        if (!r1cs_verification_key_out.empty()) {\n            auto filename = r1cs_verification_key_out + \".bin\";\n            write_obj(std::filesystem::path(filename), {vk_crs_blob});\n        }\n\n        auto pk_eid_blob = serialize_obj<public_key_marshaling_type>(\n            pk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_public_key<elgamal_public_key_type, endianness>));\n        if (!public_key_output.empty()) {\n            auto filename = public_key_output + \".bin\";\n            write_obj(std::filesystem::path(filename), {pk_eid_blob});\n        }\n\n        auto sk_eid_blob = serialize_obj<secret_key_marshaling_type>(\n            sk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_private_key<elgamal_private_key_type, endianness>));\n        if (!secret_key_output.empty()) {\n            auto filename = secret_key_output + \".bin\";\n            write_obj(std::filesystem::path(filename), {sk_eid_blob});\n        }\n\n        auto vk_eid_blob = serialize_obj<verification_key_marshaling_type>(\n            vk_eid,\n            std::function(\n                nil::crypto3::marshalling::types::fill_verification_key<elgamal_verification_key_type, endianness>));\n        if (!verification_key_output.empty()) {\n            auto filename = verification_key_output + \".bin\";\n            write_obj(std::filesystem::path(filename), {vk_eid_blob});\n        }\n\n        auto eid_blob = serialize_obj<pinput_marshaling_type>(\n            eid,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (!eid_output.empty()) {\n            auto filename = eid_output + \".bin\";\n            write_obj(std::filesystem::path(filename), {eid_blob});\n        }\n\n        auto rt_blob = serialize_obj<pinput_marshaling_type>(\n            rt,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (!rt_output.empty()) {\n            auto filename = rt_output + \".bin\";\n            write_obj(std::filesystem::path(filename), {rt_blob});\n        }\n    }\n\n    static void serialize_initial_phase_admin_data(\n        const proving_key_type &pk_crs, const verification_key_type &vk_crs, const elgamal_public_key_type &pk_eid,\n        const elgamal_private_key_type &sk_eid, const elgamal_verification_key_type &vk_eid,\n        const primary_input_type &eid, const primary_input_type &rt, std::vector<std::uint8_t> &r1cs_proving_key_out,\n        std::vector<std::uint8_t> &r1cs_verification_key_out, std::vector<std::uint8_t> &public_key_output,\n        std::vector<std::uint8_t> &secret_key_output, std::vector<std::uint8_t> &verification_key_output,\n        std::vector<std::uint8_t> &eid_output, std::vector<std::uint8_t> &rt_output) {\n        r1cs_proving_key_out = serialize_obj<r1cs_proving_key_marshalling_type>(\n            pk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_proving_key<proving_key_type, endianness>));\n\n        r1cs_verification_key_out = serialize_obj<r1cs_verification_key_marshaling_type>(\n            vk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_verification_key<verification_key_type,\n                                                                                          endianness>));\n\n        public_key_output = serialize_obj<public_key_marshaling_type>(\n            pk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_public_key<elgamal_public_key_type, endianness>));\n\n        secret_key_output = serialize_obj<secret_key_marshaling_type>(\n            sk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_private_key<elgamal_private_key_type, endianness>));\n\n        verification_key_output = serialize_obj<verification_key_marshaling_type>(\n            vk_eid,\n            std::function(\n                nil::crypto3::marshalling::types::fill_verification_key<elgamal_verification_key_type, endianness>));\n\n        eid_output = serialize_obj<pinput_marshaling_type>(\n            eid,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        rt_output = serialize_obj<pinput_marshaling_type>(\n            rt,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n    }\n\n    static void write_data(std::size_t proof_idx, const boost::program_options::variables_map &vm,\n                           const verification_key_type &vk_crs, const elgamal_public_key_type &pk_eid,\n                           const proof_type &proof, const primary_input_type &pinput,\n                           const encrypted_input_policy::encryption_scheme_type::cipher_type::first_type &ct,\n                           const primary_input_type &eid, const primary_input_type &sn, const primary_input_type &rt) {\n        auto proof_blob = serialize_obj<r1cs_proof_marshaling_type>(\n            proof,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_proof<proof_type, endianness>));\n        if (vm.count(\"r1cs-proof-output\")) {\n            auto filename = vm[\"r1cs-proof-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {proof_blob});\n        }\n\n        auto pinput_blob = serialize_obj<pinput_marshaling_type>(\n            pinput,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (vm.count(\"r1cs-primary-input-output\")) {\n            auto filename = vm[\"r1cs-primary-input-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {pinput_blob});\n        }\n\n        auto ct_blob = serialize_obj<ct_marshaling_type>(\n            ct,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_encrypted_primary_input<\n                          encrypted_input_policy::encryption_scheme_type::cipher_type::first_type, endianness>));\n        if (vm.count(\"cipher-text-output\")) {\n            auto filename = vm[\"cipher-text-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {ct_blob});\n        }\n\n        auto eid_blob = serialize_obj<pinput_marshaling_type>(\n            eid,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        auto sn_blob = serialize_obj<pinput_marshaling_type>(\n            sn,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (vm.count(\"sn-output\")) {\n            auto filename = vm[\"sn-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {sn_blob});\n        }\n\n        auto rt_blob = serialize_obj<pinput_marshaling_type>(\n            rt,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        auto vk_crs_blob = serialize_obj<r1cs_verification_key_marshaling_type>(\n            vk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_verification_key<verification_key_type,\n                                                                                          endianness>));\n        auto pk_eid_blob = serialize_obj<public_key_marshaling_type>(\n            pk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_public_key<elgamal_public_key_type, endianness>));\n        if (vm.count(\"r1cs-verifier-input-output\")) {\n            auto filename = vm[\"r1cs-verifier-input-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            auto filename1 = vm[\"r1cs-verifier-input-output\"].as<std::string>() + std::string(\"_chunked\") +\n                             std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {proof_blob, vk_crs_blob, pk_eid_blob, ct_blob, pinput_blob});\n            write_obj(std::filesystem::path(filename1),\n                      {proof_blob, vk_crs_blob, pk_eid_blob, ct_blob, eid_blob, sn_blob, rt_blob});\n        }\n    }\n\n    static void serialize_data(std::size_t proof_idx, const verification_key_type &vk_crs,\n                               const elgamal_public_key_type &pk_eid, const proof_type &proof,\n                               const primary_input_type &pinput,\n                               const encrypted_input_policy::encryption_scheme_type::cipher_type::first_type &ct,\n                               const primary_input_type &eid, const primary_input_type &sn,\n                               const primary_input_type &rt, std::vector<std::uint8_t> &proof_blob,\n                               std::vector<std::uint8_t> &pinput_blob, std::vector<std::uint8_t> &ct_blob,\n                               std::vector<std::uint8_t> &eid_blob, std::vector<std::uint8_t> &sn_blob,\n                               std::vector<std::uint8_t> &rt_blob, std::vector<std::uint8_t> &vk_crs_blob,\n                               std::vector<std::uint8_t> &pk_eid_blob) {\n        proof_blob = serialize_obj<r1cs_proof_marshaling_type>(\n            proof,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_proof<proof_type, endianness>));\n\n        pinput_blob = serialize_obj<pinput_marshaling_type>(\n            pinput,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        ct_blob = serialize_obj<ct_marshaling_type>(\n            ct,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_encrypted_primary_input<\n                          encrypted_input_policy::encryption_scheme_type::cipher_type::first_type, endianness>));\n\n        eid_blob = serialize_obj<pinput_marshaling_type>(\n            eid,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        sn_blob = serialize_obj<pinput_marshaling_type>(\n            sn,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        rt_blob = serialize_obj<pinput_marshaling_type>(\n            rt,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        vk_crs_blob = serialize_obj<r1cs_verification_key_marshaling_type>(\n            vk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_verification_key<verification_key_type,\n                                                                                          endianness>));\n        pk_eid_blob = serialize_obj<public_key_marshaling_type>(\n            pk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_public_key<elgamal_public_key_type, endianness>));\n    }\n\n    static void\n        write_tally_phase_data(const boost::program_options::variables_map &vm,\n                               const typename encrypted_input_policy::encryption_scheme_type::decipher_type &dec) {\n        nil::marshalling::status_type status;\n        std::vector<std::uint8_t> dec_proof_blob = nil::marshalling::pack<endianness>(dec.second, status);\n        if (vm.count(\"decryption-proof-output\")) {\n            auto filename = vm[\"decryption-proof-output\"].as<std::string>() + \".bin\";\n            write_obj(filename, {\n                                    dec_proof_blob,\n                                });\n        }\n\n        auto voting_res_blob = serialize_obj<pinput_marshaling_type>(\n            dec.first,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<\n                          std::vector<scalar_field_value_type>, endianness>));\n        if (vm.count(\"voting-result-output\")) {\n            auto filename = vm[\"voting-result-output\"].as<std::string>() + \".bin\";\n            write_obj(filename, {\n                                    voting_res_blob,\n                                });\n        }\n    }\n\n    static void\n        serialize_tally_phase_data(const typename encrypted_input_policy::encryption_scheme_type::decipher_type &dec,\n                                   std::vector<std::uint8_t> &dec_proof_blob,\n                                   std::vector<std::uint8_t> &voting_res_blob) {\n        nil::marshalling::status_type status;\n        dec_proof_blob = static_cast<std::vector<std::uint8_t>>(nil::marshalling::pack<endianness>(dec.second, status));\n\n        voting_res_blob = serialize_obj<pinput_marshaling_type>(\n            dec.first,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<\n                          std::vector<scalar_field_value_type>, endianness>));\n    }\n\n    static std::vector<scalar_field_value_type> read_scalar_vector(const std::string &file_prefix) {\n        auto filename = file_prefix + \".bin\";\n        return deserialize_scalar_vector(read_obj(filename));\n    }\n\n    static std::vector<scalar_field_value_type> deserialize_scalar_vector(const std::vector<std::uint8_t> &blob) {\n        return deserialize_obj<pinput_marshaling_type, std::vector<scalar_field_value_type>>(\n            blob,\n            std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_primary_input<\n                          std::vector<scalar_field_value_type>, endianness>));\n    }\n\n    static std::vector<bool> read_bool_vector(const std::string &file_prefix) {\n        auto filename = file_prefix + \".bin\";\n        return deserialize_bool_vector(read_obj(filename));\n    }\n\n    static std::vector<bool> deserialize_bool_vector(const std::vector<std::uint8_t> &blob) {\n        std::vector<bool> result;\n        for (const auto &i : deserialize_scalar_vector(blob)) {\n            result.emplace_back(i.data);\n        }\n        return result;\n    }\n\n    static std::vector<std::uint8_t> serialize_255_bit_array(const std::array<bool, 255> &bit_array_255) {\n        std::array<bool, 256> bit_array_256;\n        std::copy_n(bit_array_255.begin(), 255, bit_array_256.begin());\n        std::array<std::uint8_t, 32> octet_array;\n        nil::crypto3::detail::pack<stream_endian::big_octet_big_bit, stream_endian::big_octet_big_bit, 1, 8>(\n            bit_array_256.begin(), bit_array_256.end(), octet_array.begin());\n        return std::vector<std::uint8_t>(octet_array.begin(), octet_array.end());\n    }\n\n    static std::array<bool, 255> deserialize_255_bit_array(const std::vector<std::uint8_t> &blob) {\n        std::array<std::uint8_t, 32> octet_array;\n        std::copy_n(blob.begin(), 32, octet_array.begin());\n        std::array<bool, 256> bit_array_256;\n        nil::crypto3::detail::pack<stream_endian::big_octet_big_bit, stream_endian::big_octet_big_bit, 8, 1>(\n            octet_array.begin(), octet_array.end(), bit_array_256.begin());\n        std::array<bool, 255> bit_array_255;\n        std::copy_n(bit_array_256.begin(), 255, bit_array_255.begin());\n        return bit_array_255;\n    }\n\n    static std::vector<std::vector<bool>> read_voters_public_keys(std::size_t tree_depth,\n                                                                  const std::string &voter_public_key_output) {\n        std::size_t participants_number = 1 << tree_depth;\n        std::vector<std::vector<bool>> result;\n\n        for (auto i = 0; i < participants_number; i++) {\n            if (!voter_public_key_output.empty()) {\n                result.emplace_back(read_bool_vector(voter_public_key_output + std::to_string(i)));\n            }\n        }\n        return result;\n    }\n\n    static std::vector<std::vector<bool>>\n        deserialize_voters_public_keys(std::size_t tree_depth, const std::vector<std::vector<std::uint8_t>> &blobs) {\n        std::size_t participants_number = 1 << tree_depth;\n        BOOST_ASSERT(blobs.size() <= participants_number);\n        std::vector<std::vector<bool>> result;\n\n        for (auto i = 0; i < blobs.size(); i++) {\n            result.emplace_back(deserialize_bool_vector(blobs[i]));\n        }\n\n        for (auto i = blobs.size(); i < participants_number; i++) {\n            result.emplace_back(\n                std::vector<bool>(encrypted_input_policy::hash_type::digest_bits, 0)\n            );\n        }\n\n        return result;\n    }\n\n    static elgamal_public_key_type read_pk_eid(const boost::program_options::variables_map &vm) {\n        auto pk_eid_blob = read_obj(vm[\"public-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<public_key_marshaling_type, elgamal_public_key_type>(\n            pk_eid_blob,\n            std::function(nil::crypto3::marshalling::types::make_public_key<elgamal_public_key_type, endianness>));\n    }\n\n    static elgamal_public_key_type deserialize_pk_eid(const std::vector<std::uint8_t> &pk_eid_blob) {\n        return deserialize_obj<public_key_marshaling_type, elgamal_public_key_type>(\n            pk_eid_blob,\n            std::function(nil::crypto3::marshalling::types::make_public_key<elgamal_public_key_type, endianness>));\n    }\n\n    static elgamal_verification_key_type read_vk_eid(const boost::program_options::variables_map &vm) {\n        auto vk_eid_blob = read_obj(vm[\"verification-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<verification_key_marshaling_type, elgamal_verification_key_type>(\n            vk_eid_blob,\n            std::function(\n                nil::crypto3::marshalling::types::make_verification_key<elgamal_verification_key_type, endianness>));\n    }\n\n    static elgamal_verification_key_type deserialize_vk_eid(const std::vector<std::uint8_t> &vk_eid_blob) {\n        return deserialize_obj<verification_key_marshaling_type, elgamal_verification_key_type>(\n            vk_eid_blob,\n            std::function(\n                nil::crypto3::marshalling::types::make_verification_key<elgamal_verification_key_type, endianness>));\n    }\n\n    static elgamal_private_key_type read_sk_eid(const boost::program_options::variables_map &vm) {\n        auto sk_eid_blob = read_obj(vm[\"secret-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<secret_key_marshaling_type, elgamal_private_key_type>(\n            sk_eid_blob,\n            std::function(nil::crypto3::marshalling::types::make_private_key<elgamal_private_key_type, endianness>));\n    }\n\n    static elgamal_private_key_type deserialize_sk_eid(const std::vector<std::uint8_t> &sk_eid_blob) {\n        return deserialize_obj<secret_key_marshaling_type, elgamal_private_key_type>(\n            sk_eid_blob,\n            std::function(nil::crypto3::marshalling::types::make_private_key<elgamal_private_key_type, endianness>));\n    }\n\n    static verification_key_type read_vk_crs(const boost::program_options::variables_map &vm) {\n        auto vk_crs_blob = read_obj(vm[\"r1cs-verification-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<r1cs_verification_key_marshaling_type, verification_key_type>(\n            vk_crs_blob, std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_verification_key<\n                                       verification_key_type, endianness>));\n    }\n\n    static verification_key_type deserialize_vk_crs(const std::vector<std::uint8_t> &vk_crs_blob) {\n        return deserialize_obj<r1cs_verification_key_marshaling_type, verification_key_type>(\n            vk_crs_blob, std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_verification_key<\n                                       verification_key_type, endianness>));\n    }\n\n    static proving_key_type read_pk_crs(const boost::program_options::variables_map &vm) {\n        auto pk_crs_blob = read_obj(vm[\"r1cs-proving-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<r1cs_proving_key_marshalling_type, proving_key_type>(\n            pk_crs_blob,\n            std::function(\n                nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_proving_key<proving_key_type, endianness>));\n    }\n\n    static proving_key_type deserialize_pk_crs(const std::vector<std::uint8_t> &pk_crs_blob) {\n        return deserialize_obj<r1cs_proving_key_marshalling_type, proving_key_type>(\n            pk_crs_blob,\n            std::function(\n                nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_proving_key<proving_key_type, endianness>));\n    }\n\n    static proof_type read_proof(const boost::program_options::variables_map &vm, std::size_t proof_idx) {\n        auto proof_blob = read_obj(vm[\"r1cs-proof-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\");\n        return deserialize_obj<r1cs_proof_marshaling_type, proof_type>(\n            proof_blob,\n            std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_proof<proof_type, endianness>));\n    }\n\n    static typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type\n        read_ct(const boost::program_options::variables_map &vm, std::size_t proof_idx) {\n        return deserialize_obj<ct_marshaling_type,\n                               typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type>(\n            read_obj(vm[\"cipher-text-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\"),\n            std::function(\n                nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_encrypted_primary_input<\n                    typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type, endianness>));\n    }\n\n    static typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type\n        deserialize_ct(const std::vector<std::uint8_t> &blob) {\n        return deserialize_obj<ct_marshaling_type,\n                               typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type>(\n            blob,\n            std::function(\n                nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_encrypted_primary_input<\n                    typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type, endianness>));\n    }\n\n    static typename encrypted_input_policy::encryption_scheme_type::decipher_type::second_type\n        read_decryption_proof(const boost::program_options::variables_map &vm) {\n        auto dec_proof_blob = read_obj(vm[\"decryption-proof-output\"].as<std::string>() + \".bin\");\n        nil::marshalling::status_type status;\n        return static_cast<typename encrypted_input_policy::encryption_scheme_type::decipher_type::second_type>(\n            nil::marshalling::pack<endianness>(dec_proof_blob, status));\n    }\n\n    static typename encrypted_input_policy::encryption_scheme_type::decipher_type::second_type\n        deserialize_decryption_proof(const std::vector<std::uint8_t> &dec_proof_blob) {\n        nil::marshalling::status_type status;\n        return static_cast<typename encrypted_input_policy::encryption_scheme_type::decipher_type::second_type>(\n            nil::marshalling::pack<endianness>(dec_proof_blob, status));\n    }\n};\n\nbool did_srand = false;\n\nvoid srand_once() {\n    if(!did_srand) {\n        did_srand = true;\n        std::srand(std::time(0));\n    }\n}\n\ntemplate<typename ValueType, std::size_t N>\ntypename std::enable_if<std::is_unsigned<ValueType>::value, std::vector<std::array<ValueType, N>>>::type\n    generate_random_data(std::size_t leaf_number) {\n    std::vector<std::array<ValueType, N>> v;\n    srand_once();\n    for (std::size_t i = 0; i < leaf_number; ++i) {\n        std::array<ValueType, N> leaf {};\n        std::generate(std::begin(leaf), std::end(leaf),\n                      [&]() { return std::rand() % (std::numeric_limits<ValueType>::max() + 1); });\n        v.emplace_back(leaf);\n    }\n    return v;\n}\n\nvoid process_encrypted_input_mode(const boost::program_options::variables_map &vm) {\n    using scalar_field_value_type = typename encrypted_input_policy::pairing_curve_type::scalar_field_type::value_type;\n\n    BOOST_ASSERT_MSG(vm.count(\"tree-depth\"), \"Tree depth is not specified!\");\n    std::size_t tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n\n    std::size_t participants_number = 1 << tree_depth;\n    std::cout << \"There will be \" << participants_number << \" participants in voting.\" << std::endl;\n\n    std::cout << \"Generation of voters key pairs...\" << std::endl;\n    auto secret_keys = generate_random_data<bool, encrypted_input_policy::secret_key_bits>(participants_number);\n    std::vector<std::array<bool, encrypted_input_policy::public_key_bits>> public_keys;\n    std::vector<std::vector<scalar_field_value_type>> public_keys_field;\n    std::vector<std::vector<scalar_field_value_type>> secret_keys_field;\n    auto j = 0;\n    for (const auto &sk : secret_keys) {\n        std::array<bool, encrypted_input_policy::hash_type::digest_bits> pk {};\n        hash<encrypted_input_policy::merkle_hash_type>(sk, std::begin(pk));\n        public_keys.emplace_back(pk);\n        std::vector<scalar_field_value_type> pk_field;\n        std::vector<scalar_field_value_type> sk_field;\n        std::cout << \"Public key of the Voter \" << j << \": \";\n        for (auto c : pk) {\n            std::cout << int(c);\n            pk_field.emplace_back(int(c));\n        }\n        sk_field.reserve(sk.size());\n        for (auto c : sk) {\n            sk_field.emplace_back(int(c));\n        }\n        std::cout << std::endl;\n        public_keys_field.push_back(pk_field);\n        secret_keys_field.push_back(sk_field);\n        marshaling_policy::write_initial_phase_voter_data(\n            public_keys_field.back(), secret_keys_field.back(), j,\n            vm.count(\"voter-public-key-output\") ? vm[\"voter-public-key-output\"].as<std::string>() : \"\",\n            vm.count(\"voter-secret-key-output\") ? vm[\"voter-secret-key-output\"].as<std::string>() : \"\");\n        ++j;\n    }\n    std::cout << \"Voters key pairs generated.\" << std::endl;\n\n    std::cout << \"Merkle tree generation upon participants public keys started...\" << std::endl;\n    containers::merkle_tree<encrypted_input_policy::merkle_hash_type, encrypted_input_policy::arity> tree(\n        std::cbegin(public_keys), std::cend(public_keys));\n    std::vector<scalar_field_value_type> rt_field;\n    for (auto i : tree.root()) {\n        rt_field.emplace_back(int(i));\n    }\n\n    auto public_keys_read = marshaling_policy::read_voters_public_keys(\n        vm[\"tree-depth\"].as<std::size_t>(),\n        vm.count(\"voter-public-key-output\") ? vm[\"voter-public-key-output\"].as<std::string>() : \"\");\n    containers::merkle_tree<encrypted_input_policy::merkle_hash_type, encrypted_input_policy::arity>\n        tree_built_from_read(std::cbegin(public_keys_read), std::cend(public_keys_read));\n    std::vector<scalar_field_value_type> rt_field_from_read;\n    for (auto i : tree_built_from_read.root()) {\n        rt_field_from_read.emplace_back(int(i));\n    }\n    BOOST_ASSERT(rt_field == rt_field_from_read);\n    std::cout << \"Merkle tree generation finished.\" << std::endl;\n\n    BOOST_ASSERT_MSG(vm.count(\"eid-bits\"), \"Eid length is not specified!\");\n    const std::size_t eid_size = vm[\"eid-bits\"].as<std::size_t>();\n    std::vector<bool> eid(eid_size);\n    std::vector<scalar_field_value_type> eid_field;\n    std::generate(eid.begin(), eid.end(), [&]() { return std::rand() % 2; });\n    std::cout << \"Voting session (eid) is: \";\n    for (auto i : eid) {\n        std::cout << int(i);\n        eid_field.emplace_back(int(i));\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Voting system administrator generates R1CS...\" << std::endl;\n    components::blueprint<encrypted_input_policy::field_type> bp;\n    components::block_variable<encrypted_input_policy::field_type> m_block(bp, encrypted_input_policy::msg_size);\n    components::block_variable<encrypted_input_policy::field_type> eid_block(bp, eid.size());\n    components::digest_variable<encrypted_input_policy::field_type> sn_digest(\n        bp, encrypted_input_policy::hash_component::digest_bits);\n    components::digest_variable<encrypted_input_policy::field_type> root_digest(\n        bp, encrypted_input_policy::merkle_hash_component::digest_bits);\n    components::blueprint_variable_vector<encrypted_input_policy::field_type> address_bits_va;\n    address_bits_va.allocate(bp, tree_depth);\n    encrypted_input_policy::merkle_proof_component path_var(bp, tree_depth);\n    components::block_variable<encrypted_input_policy::field_type> sk_block(bp,\n                                                                            encrypted_input_policy::secret_key_bits);\n    encrypted_input_policy::voting_component vote_var(\n        bp, m_block, eid_block, sn_digest, root_digest, address_bits_va, path_var, sk_block,\n        components::blueprint_variable<encrypted_input_policy::field_type>(0));\n    path_var.generate_r1cs_constraints();\n    vote_var.generate_r1cs_constraints();\n    std::cout << \"R1CS generation finished.\" << std::endl;\n    std::cout << \"Constraints number in the generated R1CS: \" << bp.num_constraints() << std::endl;\n    bp.set_input_sizes(vote_var.get_input_size());\n\n    std::cout << \"Administrator generates CRS...\" << std::endl;\n    typename encrypted_input_policy::proof_system::keypair_type gg_keypair =\n        nil::crypto3::zk::generate<encrypted_input_policy::proof_system>(bp.get_constraint_system());\n    std::cout << \"CRS generation finished.\" << std::endl;\n\n    std::cout << \"Administrator generates private, public and verification keys for El-Gamal verifiable encryption \"\n                 \"scheme...\"\n              << std::endl;\n    random::algebraic_random_device<typename encrypted_input_policy::pairing_curve_type::scalar_field_type> d;\n    std::vector<scalar_field_value_type> rnd;\n    for (std::size_t i = 0; i < encrypted_input_policy::msg_size * 3 + 2; ++i) {\n        rnd.emplace_back(d());\n    }\n    typename encrypted_input_policy::encryption_scheme_type::keypair_type keypair =\n        generate_keypair<encrypted_input_policy::encryption_scheme_type,\n                         modes::verifiable_encryption<encrypted_input_policy::encryption_scheme_type>>(\n            rnd, {gg_keypair, encrypted_input_policy::msg_size});\n    std::cout << \"Private, public and verification keys for El-Gamal verifiable encryption scheme generated.\"\n              << std::endl\n              << std::endl;\n    std::cout << \"====================================================================\" << std::endl << std::endl;\n\n    std::cout << \"Administrator initial phase marshalling started...\" << std::endl;\n    marshaling_policy::write_initial_phase_admin_data(\n        gg_keypair.first, gg_keypair.second, std::get<0>(keypair), std::get<1>(keypair), std::get<2>(keypair),\n        eid_field, rt_field, vm.count(\"r1cs-proving-key-output\") ? vm[\"r1cs-proving-key-output\"].as<std::string>() : \"\",\n        vm.count(\"r1cs-verification-key-output\") ? vm[\"r1cs-verification-key-output\"].as<std::string>() : \"\",\n        vm.count(\"public-key-output\") ? vm[\"public-key-output\"].as<std::string>() : \"\",\n        vm.count(\"secret-key-output\") ? vm[\"secret-key-output\"].as<std::string>() : \"\",\n        vm.count(\"verification-key-output\") ? vm[\"verification-key-output\"].as<std::string>() : \"\",\n        vm.count(\"eid-output\") ? vm[\"eid-output\"].as<std::string>() : \"\",\n        vm.count(\"rt-output\") ? vm[\"-output\"].as<std::string>() : \"\");\n    std::cout << \"Marshalling finished.\" << std::endl;\n\n    std::vector<typename encrypted_input_policy::encryption_scheme_type::cipher_type> ct_n;\n\n    for (std::size_t i = 0; i < participants_number; ++i) {\n\n        std::size_t proof_idx = i;\n        std::cout << \"Voter with index \" << proof_idx << \" generates its merkle copath...\" << std::endl;\n        containers::merkle_proof<encrypted_input_policy::merkle_hash_type, encrypted_input_policy::arity> path(\n            tree, proof_idx);\n        auto tree_pk_leaf = tree[proof_idx];\n        std::cout << \"Copath generated.\" << std::endl;\n\n        std::vector<bool> m(encrypted_input_policy::msg_size, false);\n        m[std::rand() % m.size()] = true;\n        std::cout << \"Voter \" << proof_idx << \" is willing to vote with the following ballot: { \";\n        for (auto m_i : m) {\n            std::cout << int(m_i);\n        }\n        std::cout << \" }\" << std::endl;\n        std::vector<scalar_field_value_type> m_field;\n        m_field.reserve(m.size());\n        for (const auto m_i : m) {\n            m_field.emplace_back(std::size_t(m_i));\n        }\n\n        std::vector<bool> eid_sk;\n        std::copy(std::cbegin(eid), std::cend(eid), std::back_inserter(eid_sk));\n        std::copy(std::cbegin(secret_keys[proof_idx]), std::cend(secret_keys[proof_idx]), std::back_inserter(eid_sk));\n        std::vector<bool> sn = hash<encrypted_input_policy::hash_type>(eid_sk);\n        std::cout << \"Sender has following serial number (sn) in current session: \";\n        for (auto i : sn) {\n            std::cout << int(i);\n        }\n        std::cout << std::endl;\n\n        // BOOST_ASSERT(!bp.is_satisfied());\n        path_var.generate_r1cs_witness(path, true);\n        BOOST_ASSERT(!bp.is_satisfied());\n        address_bits_va.fill_with_bits_of_ulong(bp, path_var.address);\n        BOOST_ASSERT(!bp.is_satisfied());\n        BOOST_ASSERT(address_bits_va.get_field_element_from_bits(bp) == path_var.address);\n        m_block.generate_r1cs_witness(m);\n        BOOST_ASSERT(!bp.is_satisfied());\n        eid_block.generate_r1cs_witness(eid);\n        BOOST_ASSERT(!bp.is_satisfied());\n        sk_block.generate_r1cs_witness(secret_keys[proof_idx]);\n        BOOST_ASSERT(!bp.is_satisfied());\n        vote_var.generate_r1cs_witness(tree.root(), sn);\n        BOOST_ASSERT(bp.is_satisfied());\n\n        std::cout << \"Voter \" << proof_idx << \" generates its vote consisting of proof and cipher text...\" << std::endl;\n        typename encrypted_input_policy::encryption_scheme_type::cipher_type cipher_text =\n            encrypt<encrypted_input_policy::encryption_scheme_type,\n                    modes::verifiable_encryption<encrypted_input_policy::encryption_scheme_type>>(\n                m_field, {d(), std::get<0>(keypair), gg_keypair, bp.primary_input(), bp.auxiliary_input()});\n        ct_n.push_back(cipher_text);\n        std::cout << \"Vote generated.\" << std::endl;\n\n        std::cout << \"Rerandomization of the cipher text and proof started...\" << std::endl;\n        std::vector<scalar_field_value_type> rnd_rerandomization;\n        for (std::size_t i = 0; i < 3; ++i) {\n            rnd_rerandomization.emplace_back(d());\n        }\n        typename encrypted_input_policy::encryption_scheme_type::cipher_type rerand_cipher_text =\n            rerandomize<encrypted_input_policy::encryption_scheme_type>(\n                rnd_rerandomization, cipher_text.first, {std::get<0>(keypair), gg_keypair, cipher_text.second});\n        std::cout << \"Rerandomization finished.\" << std::endl;\n\n        std::cout << \"Voter \" << proof_idx << \" marshalling started...\" << std::endl;\n        std::size_t eid_offset = m.size();\n        std::size_t sn_offset = eid_offset + eid.size();\n        std::size_t rt_offset = sn_offset + sn.size();\n        std::size_t rt_offset_end = rt_offset + tree.root().size();\n        typename encrypted_input_policy::proof_system::primary_input_type pinput = bp.primary_input();\n        BOOST_ASSERT(std::cbegin(pinput) + rt_offset_end == std::cend(pinput));\n        BOOST_ASSERT((eid_field == typename encrypted_input_policy::proof_system::primary_input_type {\n                                       std::cbegin(pinput) + eid_offset, std::cbegin(pinput) + sn_offset}));\n        BOOST_ASSERT((rt_field == typename encrypted_input_policy::proof_system::primary_input_type {\n                                      std::cbegin(pinput) + rt_offset, std::cbegin(pinput) + rt_offset_end}));\n        marshaling_policy::write_data(proof_idx, vm, gg_keypair.second, std::get<0>(keypair), rerand_cipher_text.second,\n                                      typename encrypted_input_policy::proof_system::primary_input_type {\n                                          std::cbegin(pinput) + eid_offset, std::cend(pinput)},\n                                      rerand_cipher_text.first,\n                                      typename encrypted_input_policy::proof_system::primary_input_type {\n                                          std::cbegin(pinput) + eid_offset, std::cbegin(pinput) + sn_offset},\n                                      typename encrypted_input_policy::proof_system::primary_input_type {\n                                          std::cbegin(pinput) + sn_offset, std::cbegin(pinput) + rt_offset},\n                                      typename encrypted_input_policy::proof_system::primary_input_type {\n                                          std::cbegin(pinput) + rt_offset, std::cbegin(pinput) + rt_offset_end});\n        std::cout << \"Marshalling finished.\" << std::endl;\n\n        std::cout << \"Sender verifies rerandomized encrypted ballot and proof...\" << std::endl;\n        bool enc_verification_ans = verify_encryption<encrypted_input_policy::encryption_scheme_type>(\n            rerand_cipher_text.first,\n            {std::get<0>(keypair), gg_keypair.second, rerand_cipher_text.second,\n             typename encrypted_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + m.size(),\n                                                                                std::cend(pinput)}});\n        BOOST_ASSERT(enc_verification_ans);\n        std::cout << \"Encryption verification of rerandomazed cipher text and proof finished.\" << std::endl;\n\n        std::cout << \"Administrator decrypts ballot from rerandomized cipher text and generates decryption proof...\"\n                  << std::endl;\n        typename encrypted_input_policy::encryption_scheme_type::decipher_type decipher_rerand_text =\n            decrypt<encrypted_input_policy::encryption_scheme_type,\n                    modes::verifiable_encryption<encrypted_input_policy::encryption_scheme_type>>(\n                rerand_cipher_text.first, {std::get<1>(keypair), std::get<2>(keypair), gg_keypair});\n        BOOST_ASSERT(decipher_rerand_text.first.size() == m_field.size());\n        for (std::size_t i = 0; i < m_field.size(); ++i) {\n            BOOST_ASSERT(decipher_rerand_text.first[i] == m_field[i]);\n        }\n        std::cout << \"Decryption finished, decryption proof generated.\" << std::endl;\n\n        std::cout << \"Any voter could verify decryption using decryption proof...\" << std::endl;\n        bool dec_verification_ans = verify_decryption<encrypted_input_policy::encryption_scheme_type>(\n            rerand_cipher_text.first, decipher_rerand_text.first,\n            {std::get<2>(keypair), gg_keypair, decipher_rerand_text.second});\n        BOOST_ASSERT(dec_verification_ans);\n        std::cout << \"Decryption verification finished.\" << std::endl << std::endl;\n        std::cout << \"====================================================================\" << std::endl << std::endl;\n    }\n\n    std::cout << \"Tally results phase started.\" << std::endl;\n    std::cout << \"Administrator counts final results...\" << std::endl;\n    auto ct_it = std::cbegin(ct_n);\n    auto ct_ = ct_it->first;\n    ct_it++;\n    while (ct_it != std::cend(ct_n)) {\n        for (std::size_t i = 0; i < std::size(ct_); ++i) {\n            ct_[i] = ct_[i] + ct_it->first[i];\n        }\n        ct_it++;\n    }\n    std::cout << \"Final results are ready.\" << std::endl;\n\n    std::cout << \"Deciphered results of voting:\" << std::endl;\n    typename encrypted_input_policy::encryption_scheme_type::decipher_type decipher_rerand_sum_text =\n        decrypt<encrypted_input_policy::encryption_scheme_type,\n                modes::verifiable_encryption<encrypted_input_policy::encryption_scheme_type>>(\n            ct_, {std::get<1>(keypair), std::get<2>(keypair), gg_keypair});\n    BOOST_ASSERT(decipher_rerand_sum_text.first.size() == encrypted_input_policy::msg_size);\n    for (std::size_t i = 0; i < encrypted_input_policy::msg_size; ++i) {\n        std::cout << decipher_rerand_sum_text.first[i].data << \", \";\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Tally phase marshalling started...\" << std::endl;\n    marshaling_policy::write_tally_phase_data(vm, decipher_rerand_sum_text);\n    std::cout << \"Marshalling finished.\" << std::endl;\n\n    std::cout << \"Verification of the deciphered tally result...\" << std::endl;\n    bool dec_verification_ans = verify_decryption<encrypted_input_policy::encryption_scheme_type>(\n        ct_, decipher_rerand_sum_text.first, {std::get<2>(keypair), gg_keypair, decipher_rerand_sum_text.second});\n    BOOST_ASSERT(dec_verification_ans);\n    std::cout << \"Verification of the deciphered tally result succeeded.\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_init_voter_phase(std::size_t voter_idx, std::vector<std::uint8_t> &voter_pk_out,\n                                                   std::vector<std::uint8_t> &voter_sk_out) {\n    using scalar_field_value_type = typename encrypted_input_policy::pairing_curve_type::scalar_field_type::value_type;\n\n    std::size_t proof_idx = voter_idx;\n    std::cout << \"Voter \" << proof_idx << \" generates its public and secret keys...\" << std::endl << std::endl;\n    auto secret_keys = generate_random_data<bool, encrypted_input_policy::secret_key_bits>(1);\n    std::vector<std::array<bool, encrypted_input_policy::public_key_bits>> public_keys;\n    std::array<bool, encrypted_input_policy::hash_type::digest_bits> pk {};\n    hash<encrypted_input_policy::merkle_hash_type>(secret_keys[0], std::begin(pk));\n    public_keys.emplace_back(pk);\n    std::vector<scalar_field_value_type> pk_field;\n    std::vector<scalar_field_value_type> sk_field;\n    std::cout << \"Public key of the Voter \" << proof_idx << \": \";\n    for (auto c : pk) {\n        std::cout << int(c);\n        pk_field.emplace_back(int(c));\n    }\n    for (auto c : secret_keys[0]) {\n        sk_field.emplace_back(int(c));\n    }\n    std::cout << std::endl;\n    std::cout << \"Participants key pairs generated.\" << std::endl;\n\n    std::cout << \"Voter \" << proof_idx << \" keypair marshalling started...\" << std::endl;\n    marshaling_policy::serialize_initial_phase_voter_data(pk_field, sk_field, voter_pk_out, voter_sk_out);\n    std::cout << \"Marshalling finished.\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_init_admin_phase(\n    std::size_t tree_depth, std::size_t eid_bits, const std::vector<std::vector<bool>> &public_keys,\n    std::vector<std::uint8_t> &r1cs_proving_key_out, std::vector<std::uint8_t> &r1cs_verification_key_out,\n    std::vector<std::uint8_t> &public_key_output, std::vector<std::uint8_t> &secret_key_output,\n    std::vector<std::uint8_t> &verification_key_output, std::vector<std::uint8_t> &eid_output,\n    std::vector<std::uint8_t> &rt_output) {\n    using scalar_field_value_type = typename encrypted_input_policy::pairing_curve_type::scalar_field_type::value_type;\n\n    std::cout << \"Administrator pre-initializes voting session...\" << std::endl << std::endl;\n\n    std::cout << \"Merkle tree generation upon participants public keys started...\" << std::endl;\n    containers::merkle_tree<encrypted_input_policy::merkle_hash_type, encrypted_input_policy::arity> tree(\n        std::cbegin(public_keys), std::cend(public_keys));\n    std::vector<scalar_field_value_type> rt_field;\n    for (auto i : tree.root()) {\n        rt_field.emplace_back(int(i));\n    }\n    std::cout << \"Merkle tree generation finished.\" << std::endl;\n\n    std::vector<bool> eid(eid_bits);\n    std::vector<scalar_field_value_type> eid_field;\n    srand_once();\n    std::generate(eid.begin(), eid.end(), [&]() { return std::rand() % 2; });\n    std::cout << \"Voting session (eid) is: \";\n    for (auto i : eid) {\n        std::cout << int(i);\n        eid_field.emplace_back(int(i));\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Voting system administrator generates R1CS...\" << std::endl;\n    components::blueprint<encrypted_input_policy::field_type> bp;\n    components::block_variable<encrypted_input_policy::field_type> m_block(bp, encrypted_input_policy::msg_size);\n    components::block_variable<encrypted_input_policy::field_type> eid_block(bp, eid.size());\n    components::digest_variable<encrypted_input_policy::field_type> sn_digest(\n        bp, encrypted_input_policy::hash_component::digest_bits);\n    components::digest_variable<encrypted_input_policy::field_type> root_digest(\n        bp, encrypted_input_policy::merkle_hash_component::digest_bits);\n    components::blueprint_variable_vector<encrypted_input_policy::field_type> address_bits_va;\n    address_bits_va.allocate(bp, tree_depth);\n    encrypted_input_policy::merkle_proof_component path_var(bp, tree_depth);\n    components::block_variable<encrypted_input_policy::field_type> sk_block(bp,\n                                                                            encrypted_input_policy::secret_key_bits);\n    encrypted_input_policy::voting_component vote_var(\n        bp, m_block, eid_block, sn_digest, root_digest, address_bits_va, path_var, sk_block,\n        components::blueprint_variable<encrypted_input_policy::field_type>(0));\n    path_var.generate_r1cs_constraints();\n    vote_var.generate_r1cs_constraints();\n    std::cout << \"R1CS generation finished.\" << std::endl;\n    std::cout << \"Constraints number in the generated R1CS: \" << bp.num_constraints() << std::endl;\n    bp.set_input_sizes(vote_var.get_input_size());\n\n    std::cout << \"Administrator generates CRS...\" << std::endl;\n    typename encrypted_input_policy::proof_system::keypair_type gg_keypair =\n        nil::crypto3::zk::generate<encrypted_input_policy::proof_system>(bp.get_constraint_system());\n    std::cout << \"CRS generation finished.\" << std::endl;\n\n    std::cout << \"Administrator generates private, public and verification keys for El-Gamal verifiable encryption \"\n                 \"scheme...\"\n              << std::endl;\n    random::algebraic_random_device<typename encrypted_input_policy::pairing_curve_type::scalar_field_type> d;\n    std::vector<scalar_field_value_type> rnd;\n    for (std::size_t i = 0; i < encrypted_input_policy::msg_size * 3 + 2; ++i) {\n        rnd.emplace_back(d());\n    }\n    typename encrypted_input_policy::encryption_scheme_type::keypair_type keypair =\n        generate_keypair<encrypted_input_policy::encryption_scheme_type,\n                         modes::verifiable_encryption<encrypted_input_policy::encryption_scheme_type>>(\n            rnd, {gg_keypair, encrypted_input_policy::msg_size});\n    std::cout << \"Private, public and verification keys for El-Gamal verifiable encryption scheme generated.\"\n              << std::endl\n              << std::endl;\n    std::cout << \"====================================================================\" << std::endl << std::endl;\n\n    std::cout << \"Administrator initial phase marshalling started...\" << std::endl;\n    marshaling_policy::serialize_initial_phase_admin_data(\n        gg_keypair.first, gg_keypair.second, std::get<0>(keypair), std::get<1>(keypair), std::get<2>(keypair),\n        eid_field, rt_field, r1cs_proving_key_out, r1cs_verification_key_out, public_key_output, secret_key_output,\n        verification_key_output, eid_output, rt_output);\n    std::cout << \"Marshalling finished.\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_vote_phase(\n    std::size_t tree_depth, std::size_t voter_idx, std::size_t vote, const std::vector<std::vector<bool>> &public_keys,\n    const std::vector<typename marshaling_policy::scalar_field_value_type> &admin_rt_field,\n    const std::vector<bool> &eid, const std::vector<bool> &sk,\n    const typename marshaling_policy::elgamal_public_key_type &pk_eid,\n    const typename encrypted_input_policy::proof_system::keypair_type &gg_keypair,\n    std::vector<std::uint8_t> &proof_blob, std::vector<std::uint8_t> &pinput_blob, std::vector<std::uint8_t> &ct_blob,\n    std::vector<std::uint8_t> &eid_blob, std::vector<std::uint8_t> &sn_blob, std::vector<std::uint8_t> &rt_blob,\n    std::vector<std::uint8_t> &vk_crs_blob, std::vector<std::uint8_t> &pk_eid_blob) {\n    using scalar_field_value_type = typename encrypted_input_policy::pairing_curve_type::scalar_field_type::value_type;\n\n    std::size_t participants_number = 1 << tree_depth;\n\n    std::size_t proof_idx = voter_idx;\n    BOOST_ASSERT_MSG(participants_number > proof_idx, \"Voter index should be lass than number of participants!\");\n\n    std::cout << \"Voter \" << proof_idx << \" generate encrypted ballot\" << std::endl << std::endl;\n\n    std::cout << \"Voter with index \" << proof_idx << \" generates its merkle copath...\" << std::endl;\n    containers::merkle_tree<encrypted_input_policy::merkle_hash_type, encrypted_input_policy::arity> tree(\n        std::cbegin(public_keys), std::cend(public_keys));\n    std::vector<scalar_field_value_type> rt_field;\n    for (int i : tree.root()) {\n        rt_field.emplace_back(i);\n    }\n    BOOST_ASSERT(rt_field == admin_rt_field);\n    containers::merkle_proof<encrypted_input_policy::merkle_hash_type, encrypted_input_policy::arity> path(tree,\n                                                                                                           proof_idx);\n    std::cout << \"Copath generated.\" << std::endl;\n    auto tree_pk_leaf = tree[proof_idx];\n\n    std::vector<bool> m(encrypted_input_policy::msg_size, false);\n    m[vote] = true;\n    std::cout << \"Voter \" << proof_idx << \" is willing to vote with the following ballot: { \";\n    for (auto m_i : m) {\n        std::cout << int(m_i);\n    }\n    std::cout << \" }\" << std::endl;\n    std::vector<typename encrypted_input_policy::pairing_curve_type::scalar_field_type::value_type> m_field;\n    m_field.reserve(m.size());\n    for (const auto m_i : m) {\n        m_field.emplace_back(std::size_t(m_i));\n    }\n\n    std::vector<bool> eid_sk;\n    std::copy(std::cbegin(eid), std::cend(eid), std::back_inserter(eid_sk));\n    std::copy(std::cbegin(sk), std::cend(sk), std::back_inserter(eid_sk));\n    std::vector<bool> sn = hash<encrypted_input_policy::hash_type>(eid_sk);\n    std::cout << \"Sender has following serial number (sn) in current session: \";\n    for (auto i : sn) {\n        std::cout << int(i);\n    }\n    std::cout << std::endl;\n\n    components::blueprint<encrypted_input_policy::field_type> bp;\n    components::block_variable<encrypted_input_policy::field_type> m_block(bp, encrypted_input_policy::msg_size);\n    components::block_variable<encrypted_input_policy::field_type> eid_block(bp, eid.size());\n    components::digest_variable<encrypted_input_policy::field_type> sn_digest(\n        bp, encrypted_input_policy::hash_component::digest_bits);\n    components::digest_variable<encrypted_input_policy::field_type> root_digest(\n        bp, encrypted_input_policy::merkle_hash_component::digest_bits);\n    components::blueprint_variable_vector<encrypted_input_policy::field_type> address_bits_va;\n    address_bits_va.allocate(bp, tree_depth);\n    encrypted_input_policy::merkle_proof_component path_var(bp, tree_depth);\n    components::block_variable<encrypted_input_policy::field_type> sk_block(bp,\n                                                                            encrypted_input_policy::secret_key_bits);\n    encrypted_input_policy::voting_component vote_var(\n        bp, m_block, eid_block, sn_digest, root_digest, address_bits_va, path_var, sk_block,\n        components::blueprint_variable<encrypted_input_policy::field_type>(0));\n    path_var.generate_r1cs_constraints();\n    vote_var.generate_r1cs_constraints();\n    std::cout << \"R1CS generation finished.\" << std::endl;\n    std::cout << \"Constraints number in the generated R1CS: \" << bp.num_constraints() << std::endl;\n    bp.set_input_sizes(vote_var.get_input_size());\n\n    // BOOST_ASSERT(!bp.is_satisfied());\n    path_var.generate_r1cs_witness(path, true);\n    BOOST_ASSERT(!bp.is_satisfied());\n    address_bits_va.fill_with_bits_of_ulong(bp, path_var.address);\n    BOOST_ASSERT(!bp.is_satisfied());\n    BOOST_ASSERT(address_bits_va.get_field_element_from_bits(bp) == path_var.address);\n    m_block.generate_r1cs_witness(m);\n    BOOST_ASSERT(!bp.is_satisfied());\n    eid_block.generate_r1cs_witness(eid);\n    BOOST_ASSERT(!bp.is_satisfied());\n    sk_block.generate_r1cs_witness(sk);\n    BOOST_ASSERT(!bp.is_satisfied());\n    vote_var.generate_r1cs_witness(tree.root(), sn);\n    BOOST_ASSERT(bp.is_satisfied());\n\n    std::cout << \"Voter \" << proof_idx << \" generates its vote consisting of proof and cipher text...\" << std::endl;\n    random::algebraic_random_device<typename encrypted_input_policy::pairing_curve_type::scalar_field_type> d;\n    typename encrypted_input_policy::encryption_scheme_type::cipher_type cipher_text =\n        encrypt<encrypted_input_policy::encryption_scheme_type,\n                modes::verifiable_encryption<encrypted_input_policy::encryption_scheme_type>>(\n            m_field, {d(), pk_eid, gg_keypair, bp.primary_input(), bp.auxiliary_input()});\n    std::cout << \"Vote generated.\" << std::endl;\n\n    std::cout << \"Rerandomization of the cipher text and proof started...\" << std::endl;\n    std::vector<typename encrypted_input_policy::pairing_curve_type::scalar_field_type::value_type> rnd_rerandomization;\n    for (std::size_t i = 0; i < 3; ++i) {\n        rnd_rerandomization.emplace_back(d());\n    }\n    typename encrypted_input_policy::encryption_scheme_type::cipher_type rerand_cipher_text =\n        rerandomize<encrypted_input_policy::encryption_scheme_type>(rnd_rerandomization, cipher_text.first,\n                                                                    {pk_eid, gg_keypair, cipher_text.second});\n    std::cout << \"Rerandomization finished.\" << std::endl;\n\n    std::cout << \"Voter \" << proof_idx << \" marshalling started...\" << std::endl;\n    std::size_t eid_offset = m.size();\n    std::size_t sn_offset = eid_offset + eid.size();\n    std::size_t rt_offset = sn_offset + sn.size();\n    std::size_t rt_offset_end = rt_offset + tree.root().size();\n    typename encrypted_input_policy::proof_system::primary_input_type pinput = bp.primary_input();\n    marshaling_policy::serialize_data(\n        proof_idx, gg_keypair.second, pk_eid, rerand_cipher_text.second,\n        typename encrypted_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + eid_offset,\n                                                                           std::cend(pinput)},\n        rerand_cipher_text.first,\n        typename encrypted_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + eid_offset,\n                                                                           std::cbegin(pinput) + sn_offset},\n        typename encrypted_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + sn_offset,\n                                                                           std::cbegin(pinput) + rt_offset},\n        typename encrypted_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + rt_offset,\n                                                                           std::cbegin(pinput) + rt_offset_end},\n        proof_blob, pinput_blob, ct_blob, eid_blob, sn_blob, rt_blob, vk_crs_blob, pk_eid_blob);\n    std::cout << \"Marshalling finished.\" << std::endl;\n\n    std::cout << \"Sender verifies rerandomized encrypted ballot and proof...\" << std::endl;\n    bool enc_verification_ans = verify_encryption<encrypted_input_policy::encryption_scheme_type>(\n        rerand_cipher_text.first,\n        {pk_eid, gg_keypair.second, rerand_cipher_text.second,\n         typename encrypted_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + m.size(),\n                                                                            std::cend(pinput)}});\n    BOOST_ASSERT(enc_verification_ans);\n    std::cout << \"Encryption verification of rerandomazed cipher text and proof finished.\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_tally_admin_phase(\n    std::size_t tree_depth,\n    const std::vector<typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type> &cts,\n    const typename marshaling_policy::elgamal_private_key_type &sk_eid,\n    const typename marshaling_policy::elgamal_verification_key_type &vk_eid,\n    const typename encrypted_input_policy::proof_system::keypair_type &gg_keypair,\n    std::vector<std::uint8_t> &dec_proof_blob,\n    std::vector<std::uint8_t> &voting_res_blob) {\n    std::cout << \"Administrator processes tally phase - aggregates encrypted ballots, decrypts aggregated ballot, \"\n                 \"generate decryption proof...\"\n              << std::endl\n              << std::endl;\n\n    auto ct_agg = cts[0];\n    std::cout << \"Administrator counts final results...\" << std::endl;\n    for (auto proof_idx = 1; proof_idx < cts.size(); proof_idx++) {\n        auto ct_i = cts[proof_idx];\n        BOOST_ASSERT_MSG(std::size(ct_agg) == std::size(ct_i), \"Wrong size of the ct!\");\n        for (std::size_t i = 0; i < std::size(ct_i); ++i) {\n            ct_agg[i] = ct_agg[i] + ct_i[i];\n        }\n    }\n    std::cout << \"Final results are ready.\" << std::endl;\n\n    std::cout << \"Final results decryption...\" << std::endl;\n    typename encrypted_input_policy::encryption_scheme_type::decipher_type decipher_rerand_sum_text =\n        decrypt<encrypted_input_policy::encryption_scheme_type,\n                modes::verifiable_encryption<encrypted_input_policy::encryption_scheme_type>>(\n            ct_agg, {sk_eid, vk_eid, gg_keypair});\n    std::cout << \"Decryption finished.\" << std::endl;\n    BOOST_ASSERT_MSG(decipher_rerand_sum_text.first.size() == encrypted_input_policy::msg_size,\n                     \"Deciphered lens not equal\");\n\n    std::cout << \"Deciphered results of voting:\" << std::endl;\n    for (std::size_t i = 0; i < encrypted_input_policy::msg_size; ++i) {\n        std::cout << decipher_rerand_sum_text.first[i].data << \", \";\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Tally phase marshalling started...\" << std::endl;\n    marshaling_policy::serialize_tally_phase_data(decipher_rerand_sum_text, dec_proof_blob, voting_res_blob);\n    std::cout << \"Marshalling finished.\" << std::endl;\n}\n\nbool process_encrypted_input_mode_tally_voter_phase(\n    std::size_t tree_depth,\n    const std::vector<typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type> &cts,\n    const typename marshaling_policy::elgamal_verification_key_type &vk_eid,\n    const typename encrypted_input_policy::proof_system::keypair_type &gg_keypair,\n    const std::vector<typename marshaling_policy::scalar_field_value_type> &voting_result,\n    const typename encrypted_input_policy::encryption_scheme_type::decipher_type::second_type &dec_proof) {\n    std::cout << \"Voter processes tally phase - aggregates encrypted ballots, verifies voting result using decryption \"\n                 \"proof...\"\n              << std::endl\n              << std::endl;\n\n    std::size_t participants_number = 1 << tree_depth;\n\n    auto ct_agg = cts[0];\n    for (auto proof_idx = 1; proof_idx < cts.size(); proof_idx++) {\n        auto ct_i = cts[proof_idx];\n        BOOST_ASSERT_MSG(std::size(ct_agg) == std::size(ct_i), \"Wrong size of the ct!\");\n        for (std::size_t i = 0; i < std::size(ct_i); ++i) {\n            ct_agg[i] = ct_agg[i] + ct_i[i];\n        }\n    }\n\n    std::cout << \"Verification of the deciphered tally result.\" << std::endl;\n    bool dec_verification_ans = verify_decryption<encrypted_input_policy::encryption_scheme_type>(\n        ct_agg, voting_result, {vk_eid, gg_keypair, dec_proof});\n    BOOST_ASSERT_MSG(dec_verification_ans, \"Decryption proof verification failed.\");\n    std::cout << \"Decryption proof verification succeeded.\" << std::endl;\n    std::cout << \"Results of voting:\" << std::endl;\n    for (std::size_t i = 0; i < encrypted_input_policy::msg_size; ++i) {\n        std::cout << voting_result[i].data << \", \";\n    }\n    std::cout << std::endl;\n\n    return dec_verification_ans;\n}\n\ntemplate<typename T>\nstruct buffer {\n    std::size_t size;\n    T *ptr;\n};\n\nbuffer<char> blob_to_buffer(const std::vector<std::uint8_t> &blob) {\n    buffer<char> buff;\n    buff.size = blob.size();\n    buff.ptr = new char[buff.size];\n    std::copy(blob.begin(), blob.end(), buff.ptr);\n    return buff;\n}\n\nstd::vector<std::uint8_t> buffer_to_blob(const buffer<char> *const buff) {\n    std::vector<std::uint8_t> res(buff->ptr, buff->ptr + buff->size);\n    return res;\n}\n\nstd::vector<std::vector<std::uint8_t>> super_buffer_to_blobs(const buffer<buffer<char> *const> *const super_buff) {\n    std::vector<std::vector<std::uint8_t>> res;\n    res.reserve(super_buff->size);\n\n    for (std::size_t i = 0; i < super_buff->size; ++i) {\n        res.push_back(buffer_to_blob(super_buff->ptr[i]));\n    }\n\n    return res;\n}\n\nextern \"C\" {\nvoid generate_voter_keypair(buffer<char> *const voter_pk_out, buffer<char> *const voter_sk_out) {\n    std::vector<std::uint8_t> voter_pk_blob;\n    std::vector<std::uint8_t> voter_sk_blob;\n\n    // voter index only matters for prints\n    process_encrypted_input_mode_init_voter_phase(0, voter_pk_blob, voter_sk_blob);\n\n    *voter_pk_out = blob_to_buffer(voter_pk_blob);\n    *voter_sk_out = blob_to_buffer(voter_sk_blob);\n}\n\nvoid init_election(std::size_t tree_depth, std::size_t eid_bits,\n                   const buffer<buffer<char> *const> *const public_keys_super_buffer,\n                   buffer<char> *const r1cs_proving_key_out, buffer<char> *const r1cs_verification_key_out,\n                   buffer<char> *const public_key_out, buffer<char> *const secret_key_out,\n                   buffer<char> *const verification_key_out, buffer<char> *const eid_out, buffer<char> *const rt_out) {\n    std::vector<std::uint8_t> r1cs_proving_key_blob;\n    std::vector<std::uint8_t> r1cs_verification_key_blob;\n    std::vector<std::uint8_t> public_key_blob;\n    std::vector<std::uint8_t> secret_key_blob;\n    std::vector<std::uint8_t> verification_key_blob;\n    std::vector<std::uint8_t> eid_blob;\n    std::vector<std::uint8_t> rt_blob;\n\n    auto blobs = super_buffer_to_blobs(public_keys_super_buffer);\n    std::cout << \"Finished conversion from buffer to blobs of public keys\" << std::endl;\n\n    auto public_keys = marshaling_policy::deserialize_voters_public_keys(tree_depth, blobs);\n\n    std::cout << \"Finished deserialization of public keys\" << std::endl;\n\n    process_encrypted_input_mode_init_admin_phase(tree_depth, eid_bits, public_keys, r1cs_proving_key_blob,\n                                                  r1cs_verification_key_blob, public_key_blob, secret_key_blob,\n                                                  verification_key_blob, eid_blob, rt_blob);\n\n    *r1cs_proving_key_out = blob_to_buffer(r1cs_proving_key_blob);\n    *r1cs_verification_key_out = blob_to_buffer(r1cs_verification_key_blob);\n    *public_key_out = blob_to_buffer(public_key_blob);\n    *secret_key_out = blob_to_buffer(secret_key_blob);\n    *verification_key_out = blob_to_buffer(verification_key_blob);\n    *eid_out = blob_to_buffer(eid_blob);\n    *rt_out = blob_to_buffer(rt_blob);\n}\n\nvoid generate_vote(std::size_t tree_depth, std::size_t voter_idx, std::size_t vote,\n                   const buffer<buffer<char> *const> *const public_keys_super_buffer,\n                   const buffer<char> *const rt_buffer, const buffer<char> *const eid_buffer,\n                   const buffer<char> *const sk_buffer, const buffer<char> *const pk_eid_buffer,\n                   const buffer<char> *const r1cs_proving_key_buffer,\n                   const buffer<char> *const r1cs_verification_key_buffer, buffer<char> *const proof_buffer_out,\n                   buffer<char> *const pinput_buffer_out, buffer<char> *const ct_buffer_out,\n                   buffer<char> *const sn_buffer_out) {\n\n    std::vector<std::uint8_t> proof_blob_out;\n    std::vector<std::uint8_t> pinput_blob_out;\n    std::vector<std::uint8_t> ct_blob_out;\n    std::vector<std::uint8_t> eid_blob_out;\n    std::vector<std::uint8_t> sn_blob_out;\n    std::vector<std::uint8_t> rt_blob_out;\n    std::vector<std::uint8_t> vk_crs_blob_out;\n    std::vector<std::uint8_t> pk_eid_blob_out;\n\n    auto blobs = super_buffer_to_blobs(public_keys_super_buffer);\n    std::cout << \"Finished conversion from buffer to blobs of public keys\" << std::endl;\n\n    auto public_keys = marshaling_policy::deserialize_voters_public_keys(tree_depth, blobs);\n    std::cout << \"Finished deserialization of public keys\" << std::endl;\n\n    auto rt_blob = buffer_to_blob(rt_buffer);\n    auto eid_blob = buffer_to_blob(eid_buffer);\n    auto sk_blob = buffer_to_blob(sk_buffer);\n    auto pk_eid_blob = buffer_to_blob(pk_eid_buffer);\n    auto proving_key_blob = buffer_to_blob(r1cs_proving_key_buffer);\n    auto verification_key_blob = buffer_to_blob(r1cs_verification_key_buffer);\n\n    std::cout << \"Finished conversion of rt,eid,sk,pk_eid,proving_key,verification_key from buffer to blob\"\n              << std::endl;\n\n    auto rt = marshaling_policy::deserialize_scalar_vector(rt_blob);\n    auto eid = marshaling_policy::deserialize_bool_vector(eid_blob);\n    auto sk = marshaling_policy::deserialize_bool_vector(sk_blob);\n    auto pk_eid = marshaling_policy::deserialize_pk_eid(pk_eid_blob);\n\n    typename encrypted_input_policy::proof_system::keypair_type gg_keypair = {\n        marshaling_policy::deserialize_pk_crs(proving_key_blob),\n        marshaling_policy::deserialize_vk_crs(verification_key_blob)};\n\n    std::cout << \"Finished deserialization of rt,eid,sk,pk_eid,proving_key,verification_key\" << std::endl;\n\n    process_encrypted_input_mode_vote_phase(tree_depth, voter_idx, vote, public_keys, rt, eid, sk, pk_eid, gg_keypair,\n                                            proof_blob_out, pinput_blob_out, ct_blob_out, eid_blob_out, sn_blob_out,\n                                            rt_blob_out, vk_crs_blob_out, pk_eid_blob_out);\n\n    *proof_buffer_out = blob_to_buffer(proof_blob_out);\n    *pinput_buffer_out = blob_to_buffer(pinput_blob_out);\n    *ct_buffer_out = blob_to_buffer(ct_blob_out);\n    *sn_buffer_out = blob_to_buffer(sn_blob_out);\n}\n\nvoid tally_votes(std::size_t tree_depth,\n                 const buffer<char> *const sk_eid_buffer,\n                 const buffer<char> *const vk_eid_buffer,\n                 const buffer<char> *const pk_crs_buffer,\n                 const buffer<char> *const vk_crs_buffer,\n                 const buffer<buffer<char> *const> *const cts_super_buffer,\n                 buffer<char> *const dec_proof_buffer_out,\n                 buffer<char> *const voting_res_buffer_out) {\n\n    std::cout << \"tally votes begin deserialization\" <<std::endl;\n\n    std::vector<std::uint8_t> sk_eid_blob = buffer_to_blob(sk_eid_buffer);\n    std::vector<std::uint8_t> vk_eid_blob = buffer_to_blob(vk_eid_buffer);\n    std::vector<std::uint8_t> pk_crs_blob = buffer_to_blob(pk_crs_buffer);\n    std::vector<std::uint8_t> vk_crs_blob = buffer_to_blob(vk_crs_buffer);\n    std::vector<std::vector<std::uint8_t>> cts_blobs = super_buffer_to_blobs(cts_super_buffer);\n\n    std::cout << \"tally votes finished converting from buffers to blobs\" <<std::endl;\n\n\n    auto sk_eid = marshaling_policy::deserialize_sk_eid(sk_eid_blob);\n    auto vk_eid = marshaling_policy::deserialize_vk_eid(vk_eid_blob);\n    typename encrypted_input_policy::proof_system::keypair_type gg_keypair = {\n        marshaling_policy::deserialize_pk_crs(pk_crs_blob), marshaling_policy::deserialize_vk_crs(vk_crs_blob)};\n    std::cout << \"tally votes begin cts deserialization\" <<std::endl;\n    std::size_t participants_number = 1 << tree_depth;\n    BOOST_ASSERT(cts_blobs.size() <= participants_number);\n    std::vector<typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type> cts;\n    cts.reserve(cts_blobs.size());\n    for (auto proof_idx = 0; proof_idx < cts_blobs.size(); proof_idx++) {\n        cts.push_back(marshaling_policy::deserialize_ct(cts_blobs[proof_idx]));\n    }\n\n    std::cout << \"tally votes finished deserialization\" <<std::endl;\n\n    std::vector<std::uint8_t> dec_proof_blob;\n    std::vector<std::uint8_t> voting_res_blob;\n\n    process_encrypted_input_mode_tally_admin_phase(tree_depth, cts, sk_eid, vk_eid, gg_keypair, dec_proof_blob,\n                                                   voting_res_blob);\n     std::cout << \"tally votes begin blobs to buffers conversion\" <<std::endl;\n\n    *dec_proof_buffer_out = blob_to_buffer(dec_proof_blob);\n    *voting_res_buffer_out = blob_to_buffer(voting_res_blob);\n     std::cout << \"tally votes finished blobs to buffers conversion\" <<std::endl;\n\n}\n\nbool verify_tally(std::size_t tree_depth,\n                  const buffer<buffer<char> *const> *const cts_super_buffer,\n                  const buffer<char> *const vk_eid_buffer,\n                  const buffer<char> *const pk_crs_buffer,\n                  const buffer<char> *const vk_crs_buffer,\n                  buffer<char> *const dec_proof_buffer,\n                  buffer<char> *const voting_res_buffer\n) {\n    std::cout << \"verify tally begin deserialization\" <<std::endl;\n\n    std::vector<std::uint8_t> vk_eid_blob = buffer_to_blob(vk_eid_buffer);\n    std::vector<std::uint8_t> pk_crs_blob = buffer_to_blob(pk_crs_buffer);\n    std::vector<std::uint8_t> vk_crs_blob = buffer_to_blob(vk_crs_buffer);\n    std::vector<std::uint8_t> dec_proof_blob = buffer_to_blob(dec_proof_buffer);\n    std::vector<std::uint8_t> voting_res_blob = buffer_to_blob(voting_res_buffer);\n    std::vector<std::vector<std::uint8_t>> cts_blobs = super_buffer_to_blobs(cts_super_buffer);\n\n    std::cout << \"verify tally finished converting from buffers to blobs\" <<std::endl;\n\n    auto vk_eid = marshaling_policy::deserialize_vk_eid(vk_eid_blob);\n    typename encrypted_input_policy::proof_system::keypair_type gg_keypair = {\n        marshaling_policy::deserialize_pk_crs(pk_crs_blob), marshaling_policy::deserialize_vk_crs(vk_crs_blob)};\n    \n    auto voting_result = marshaling_policy::deserialize_scalar_vector(voting_res_blob);\n    auto dec_proof = marshaling_policy::deserialize_decryption_proof(dec_proof_blob);\n\n    std::cout << \"verify tally begin cts deserialization\" <<std::endl;\n    std::size_t participants_number = 1 << tree_depth;\n    BOOST_ASSERT(cts_blobs.size() <= participants_number);\n    std::vector<typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type> cts;\n    cts.reserve(cts_blobs.size());\n    for (auto proof_idx = 0; proof_idx < cts_blobs.size(); proof_idx++) {\n        cts.push_back(marshaling_policy::deserialize_ct(cts_blobs[proof_idx]));\n    }\n\n    std::cout << \"verify tally finished deserialization\" <<std::endl;\n\n    bool is_tally_valid = process_encrypted_input_mode_tally_voter_phase(tree_depth, cts, vk_eid, gg_keypair, voting_result,\n                                                           dec_proof);\n\n    std::cout<<(is_tally_valid ? \"tally is valid\": \"tally is invalid\")<<std::endl;\n\n    return is_tally_valid;\n}\n\n}\n\nint main(int argc, char *argv[]) {\n#if __EMSCRIPTEN__\n\n#else\n    srand_once();\n    boost::program_options::options_description desc(\n        \"R1CS Generic Group PreProcessing Zero-Knowledge Succinct Non-interactive ARgument of Knowledge \"\n        \"(https://eprint.iacr.org/2016/260.pdf) CLI Proof Generator.\");\n    // clang-format off\n    desc.add_options()\n    (\"help,h\", \"Display help message.\")\n    (\"version,v\", \"Display version.\")\n    (\"phase,p\", boost::program_options::value<std::string>(),\"Execute protocol phase, allowed values:\\n\\t - init_voter (generate and write voters public and secret keys),\\n\\t - init_admin (generate and write CRS and ElGamal keys),\\n\\t - vote (read CRS and ElGamal keys, encrypt ballot and generate proof, then write them),\\n\\t - vote_verify (read voters' proofs and encrypted ballots and verify them),\\n\\t - tally_admin (read voters' encrypted ballots, aggregate encrypted ballots, decrypt aggregated ballot and generate decryption proof and write them),\\n\\t - tally_voter (read ElGamal verification and public keys, encrypted ballots, decrypted aggregated ballot, decryption proof and verify them).\")\n    (\"voter-idx,vidx\", boost::program_options::value<std::size_t>()->default_value(0),\"Voter index\")\n    (\"vote\", boost::program_options::value<std::size_t>()->default_value(0),\"Vote\")\n    (\"voter-public-key-output,vpko\", boost::program_options::value<std::string>()->default_value(\"voter_public_key\"),\"Voter public key\")\n    (\"voter-secret-key-output,vsko\", boost::program_options::value<std::string>()->default_value(\"voter_secret_key\"),\"Voter secret key\")\n    (\"r1cs-proof-output,rpo\", boost::program_options::value<std::string>()->default_value(\"r1cs_proof\"), \"Proof output path.\")\n    (\"r1cs-primary-input-output,rpio\", boost::program_options::value<std::string>()->default_value(\"r1cs_primary_input\"), \"Primary input output path.\")\n    (\"r1cs-proving-key-output,rpko\", boost::program_options::value<std::string>()->default_value(\"r1cs_proving_key\"), \"Proving key output path.\")\n    (\"r1cs-verification-key-output,rvko\", boost::program_options::value<std::string>()->default_value(\"r1cs_verification_key\"), \"Verification output path.\")\n    (\"r1cs-verifier-input-output,rvio\", boost::program_options::value<std::string>()->default_value(\"r1cs_verification_input\"), \"Verification input output path.\")\n    (\"public-key-output,pko\", boost::program_options::value<std::string>()->default_value(\"pk_eid\"), \"Public key output path.\")\n    (\"verification-key-output,vko\", boost::program_options::value<std::string>()->default_value(\"vk_eid\"), \"Verification key output path.\")\n    (\"secret-key-output,sko\", boost::program_options::value<std::string>()->default_value(\"sk_eid\"), \"Secret key output path.\")\n    (\"cipher-text-output,cto\", boost::program_options::value<std::string>()->default_value(\"cipher_text\"), \"Cipher text output path.\")\n    (\"decryption-proof-output,dpo\", boost::program_options::value<std::string>()->default_value(\"decryption_proof\"), \"Decryption proof output path.\")\n    (\"voting-result-output,vro\", boost::program_options::value<std::string>()->default_value(\"voting_result\"), \"Voting result output path.\")\n    (\"eid-output,eido\", boost::program_options::value<std::string>()->default_value(\"eid\"), \"Session id output path.\")\n    (\"sn-output,sno\", boost::program_options::value<std::string>()->default_value(\"sn\"), \"Serial number output path.\")\n    (\"rt-output,rto\", boost::program_options::value<std::string>()->default_value(\"rt\"), \"Session id output path.\")\n    (\"tree-depth,td\", boost::program_options::value<std::size_t>()->default_value(2), \"Depth of Merkle tree built upon participants' public keys.\")\n    (\"eid-bits,eb\", boost::program_options::value<std::size_t>()->default_value(64), \"EID length in bits.\");\n    // clang-format on\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).run(), vm);\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    if (!vm.count(\"phase\")) {\n        process_encrypted_input_mode(vm);\n    } else {\n        if (vm[\"phase\"].as<std::string>() == \"init_voter\") {\n            std::vector<std::uint8_t> voter_public_key_bb;\n            std::vector<std::uint8_t> voter_secret_key_bb;\n            std::string voter_pk_out =\n                vm.count(\"voter-public-key-output\") ? vm[\"voter-public-key-output\"].as<std::string>() : \"\";\n            std::string voter_sk_out =\n                vm.count(\"voter-secret-key-output\") ? vm[\"voter-secret-key-output\"].as<std::string>() : \"\";\n\n            process_encrypted_input_mode_init_voter_phase(vm[\"voter-idx\"].as<std::size_t>(), voter_public_key_bb,\n                                                          voter_secret_key_bb);\n\n            if (!voter_pk_out.empty()) {\n                auto filename = voter_pk_out + std::to_string(vm[\"voter-idx\"].as<std::size_t>()) + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {voter_public_key_bb});\n            }\n\n            if (!voter_sk_out.empty()) {\n                auto filename = voter_sk_out + std::to_string(vm[\"voter-idx\"].as<std::size_t>()) + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {voter_secret_key_bb});\n            }\n\n        } else if (vm[\"phase\"].as<std::string>() == \"init_admin\") {\n            BOOST_ASSERT_MSG(vm.count(\"tree-depth\"), \"Tree depth is not specified!\");\n            auto tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n            std::vector<std::uint8_t> r1cs_proving_key_out;\n            std::vector<std::uint8_t> r1cs_verification_key_out;\n            std::vector<std::uint8_t> public_key_output;\n            std::vector<std::uint8_t> secret_key_output;\n            std::vector<std::uint8_t> verification_key_output;\n            std::vector<std::uint8_t> eid_output;\n            std::vector<std::uint8_t> rt_output;\n\n            auto public_keys = marshaling_policy::read_voters_public_keys(\n                tree_depth, vm.count(\"voter-public-key-output\") ? vm[\"voter-public-key-output\"].as<std::string>() : \"\");\n\n            process_encrypted_input_mode_init_admin_phase(tree_depth, vm[\"eid-bits\"].as<std::size_t>(), public_keys,\n                                                          r1cs_proving_key_out, r1cs_verification_key_out,\n                                                          public_key_output, secret_key_output, verification_key_output,\n                                                          eid_output, rt_output);\n            if (vm.count(\"r1cs-proving-key-output\")) {\n                auto filename = vm[\"r1cs-proving-key-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {r1cs_proving_key_out});\n            }\n            if (vm.count(\"r1cs-verification-key-output\")) {\n                auto filename = vm[\"r1cs-verification-key-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {r1cs_verification_key_out});\n            }\n            if (vm.count(\"public-key-output\")) {\n                auto filename = vm[\"public-key-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {public_key_output});\n            }\n            if (vm.count(\"secret-key-output\")) {\n                auto filename = vm[\"secret-key-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {secret_key_output});\n            }\n            if (vm.count(\"verification-key-output\")) {\n                auto filename = vm[\"verification-key-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {verification_key_output});\n            }\n            if (vm.count(\"eid-output\")) {\n                auto filename = vm[\"eid-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {eid_output});\n            }\n            if (vm.count(\"rt-output\")) {\n                auto filename = vm[\"rt-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {rt_output});\n            }\n\n        } else if (vm[\"phase\"].as<std::string>() == \"vote\") {\n            std::vector<std::uint8_t> proof_blob;\n            std::vector<std::uint8_t> pinput_blob;\n            std::vector<std::uint8_t> ct_blob;\n            std::vector<std::uint8_t> eid_blob;\n            std::vector<std::uint8_t> sn_blob;\n            std::vector<std::uint8_t> rt_blob;\n            std::vector<std::uint8_t> vk_crs_blob;\n            std::vector<std::uint8_t> pk_eid_blob;\n\n            auto tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n            auto vote = vm[\"vote\"].as<std::size_t>();\n            auto proof_idx = vm[\"voter-idx\"].as<std::size_t>();\n            auto public_keys = marshaling_policy::read_voters_public_keys(\n                tree_depth, vm.count(\"voter-public-key-output\") ? vm[\"voter-public-key-output\"].as<std::string>() : \"\");\n            std::vector<typename marshaling_policy::scalar_field_value_type> admin_rt_field =\n                marshaling_policy::read_scalar_vector(vm[\"rt-output\"].as<std::string>());\n\n            auto eid = marshaling_policy::read_bool_vector(vm[\"eid-output\"].as<std::string>());\n            auto sk = marshaling_policy::read_bool_vector(vm[\"voter-secret-key-output\"].as<std::string>() +\n                                                          std::to_string(proof_idx));\n            auto pk_eid = marshaling_policy::read_pk_eid(vm);\n\n            typename encrypted_input_policy::proof_system::keypair_type gg_keypair = {\n                marshaling_policy::read_pk_crs(vm), marshaling_policy::read_vk_crs(vm)};\n\n            process_encrypted_input_mode_vote_phase(tree_depth, proof_idx, vote, public_keys, admin_rt_field, eid, sk,\n                                                    pk_eid, gg_keypair, proof_blob, pinput_blob, ct_blob, eid_blob,\n                                                    sn_blob, rt_blob, vk_crs_blob, pk_eid_blob);\n            if (vm.count(\"r1cs-proof-output\")) {\n                auto filename = vm[\"r1cs-proof-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {proof_blob});\n            }\n            if (vm.count(\"r1cs-primary-input-output\")) {\n                auto filename = vm[\"r1cs-primary-input-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {pinput_blob});\n            }\n            if (vm.count(\"cipher-text-output\")) {\n                auto filename = vm[\"cipher-text-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {ct_blob});\n            }\n            if (vm.count(\"sn-output\")) {\n                auto filename = vm[\"sn-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename), {sn_blob});\n            }\n            if (vm.count(\"r1cs-verifier-input-output\")) {\n                auto filename = vm[\"r1cs-verifier-input-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n                auto filename1 = vm[\"r1cs-verifier-input-output\"].as<std::string>() + std::string(\"_chunked\") +\n                                 std::to_string(proof_idx) + \".bin\";\n                marshaling_policy::write_obj(std::filesystem::path(filename),\n                                             {proof_blob, vk_crs_blob, pk_eid_blob, ct_blob, pinput_blob});\n                marshaling_policy::write_obj(\n                    std::filesystem::path(filename1),\n                    {proof_blob, vk_crs_blob, pk_eid_blob, ct_blob, eid_blob, sn_blob, rt_blob});\n            }\n\n        } else if (vm[\"phase\"].as<std::string>() == \"tally_admin\") {\n            auto tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n            auto sk_eid = marshaling_policy::read_sk_eid(vm);\n            auto vk_eid = marshaling_policy::read_vk_eid(vm);\n            typename encrypted_input_policy::proof_system::keypair_type gg_keypair = {\n                marshaling_policy::read_pk_crs(vm), marshaling_policy::read_vk_crs(vm)};\n            std::size_t participants_number = 1 << tree_depth;\n            std::vector<typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type> cts;\n            cts.reserve(participants_number);\n            for (auto proof_idx = 0; proof_idx < participants_number; proof_idx++) {\n                cts[proof_idx] = marshaling_policy::read_ct(vm, proof_idx);\n            }\n\n            std::vector<std::uint8_t> dec_proof_blob;\n            std::vector<std::uint8_t> voting_res_blob;\n\n            process_encrypted_input_mode_tally_admin_phase(tree_depth, cts, sk_eid, vk_eid, gg_keypair, dec_proof_blob,\n                                                           voting_res_blob);\n\n            if (vm.count(\"decryption-proof-output\")) {\n                auto filename = vm[\"decryption-proof-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(filename, {\n                                                           dec_proof_blob,\n                                                       });\n            }\n\n            if (vm.count(\"voting-result-output\")) {\n                auto filename = vm[\"voting-result-output\"].as<std::string>() + \".bin\";\n                marshaling_policy::write_obj(filename, {\n                                                           voting_res_blob,\n                                                       });\n            }\n        } else if (vm[\"phase\"].as<std::string>() == \"tally_voter\") {\n            BOOST_ASSERT_MSG(vm.count(\"tree-depth\"), \"Tree depth is not specified!\");\n            auto tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n            auto vk_eid = marshaling_policy::read_vk_eid(vm);\n            typename encrypted_input_policy::proof_system::keypair_type gg_keypair = {\n                marshaling_policy::read_pk_crs(vm), marshaling_policy::read_vk_crs(vm)};\n            std::size_t participants_number = 1 << tree_depth;\n            std::vector<typename encrypted_input_policy::encryption_scheme_type::cipher_type::first_type> cts;\n            cts.reserve(participants_number);\n            for (auto proof_idx = 0; proof_idx < participants_number; proof_idx++) {\n                cts[proof_idx] = marshaling_policy::read_ct(vm, proof_idx);\n            }\n\n            auto voting_result = marshaling_policy::read_scalar_vector(vm[\"voting-result-output\"].as<std::string>());\n            auto dec_proof = marshaling_policy::read_decryption_proof(vm);\n\n            process_encrypted_input_mode_tally_voter_phase(tree_depth, cts, vk_eid, gg_keypair, voting_result,\n                                                           dec_proof);\n        } else {\n            std::cout << desc << std::endl;\n            return 0;\n        }\n    }\n#endif\n\n    return 0;\n}", "meta": {"hexsha": "d11c6c7f4a3eec44238f506466f9d543a1ff322f", "size": 103149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bin/cli/src/main.cpp", "max_stars_repo_name": "NilFoundation/saver-voting-protocol", "max_stars_repo_head_hexsha": "b0d709b43c6afaf27236677d87d3cfb9e5794e8f", "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": "bin/cli/src/main.cpp", "max_issues_repo_name": "NilFoundation/saver-voting-protocol", "max_issues_repo_head_hexsha": "b0d709b43c6afaf27236677d87d3cfb9e5794e8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/cli/src/main.cpp", "max_forks_repo_name": "NilFoundation/saver-voting-protocol", "max_forks_repo_head_hexsha": "b0d709b43c6afaf27236677d87d3cfb9e5794e8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-03T19:51:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T19:51:56.000Z", "avg_line_length": 56.4581280788, "max_line_length": 701, "alphanum_fraction": 0.6494779397, "num_tokens": 23836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.1765844019061266}}
{"text": "#ifndef STAN_MATH_TORSTEN_EVENT_SOLVER_HPP\n#define STAN_MATH_TORSTEN_EVENT_SOLVER_HPP\n\n#include <stan/math/prim/fun/multiply.hpp>\n#include <stan/math/rev/fun/multiply.hpp>\n#include <stan/math/torsten/dsolve/pk_vars.hpp>\n#include <stan/math/torsten/dsolve/pmx_ode_integrator.hpp>\n#include <stan/math/torsten/ev_manager.hpp>\n#include <stan/math/torsten/model_factory.hpp>\n#include <stan/math/torsten/event.hpp>\n#include <stan/math/torsten/mpi/session.hpp>\n#include <stan/math/torsten/mpi/my_worker.hpp>\n#include <stan/math/torsten/mpi/precomputed_gradients.hpp>\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace torsten{\n\n  template<typename T_model, typename T_em>\n  struct EventSolver;\n\n  /*\n   * the solver wrapper is aware of @c T_model so it build model\n   * accordingly.\n   */\n  template<typename T_model, typename T_event_record,\n           typename T0, typename T4, template<typename...> class theta_container,\n           typename... event_ctrl_type,\n           typename... ode_data_type>\n  struct EventSolver<T_model,\n                     EventsManager<T_event_record, NonEventParameters<T0, T4, theta_container,\n                                                                      std::tuple<event_ctrl_type...>,\n                                                                      ode_data_type...>> > {\n    using EM = EventsManager<T_event_record, NonEventParameters<T0, T4, theta_container,\n                                                                std::tuple<event_ctrl_type...>,\n                                                                ode_data_type...>>;\n    using T_param = NonEventParameters<T0, T4, theta_container,\n                                       std::tuple<event_ctrl_type...>,\n                                       ode_data_type...>;\n    /*\n     * Data used to fill the results when computation throws exception.\n     */\n    static constexpr double invalid_res_d = std::numeric_limits<double>::quiet_NaN();\n\n    /*\n     * calculate the number of parameters according to the\n     * model type.\n     *\n     * @tparam T_er type of events record\n     * @param id subject id among a population\n     * @param rec events record for the population\n     */\n    static int system_size(int id, const T_event_record& rec,\n                           const std::vector<theta_container<T4>>& theta) {\n      const int ncmt = rec.ncmt;\n      const int npar = theta[0].size();\n      const int nvar = pmx_model_nvars<T_model,\n                                       typename EM::T_time,\n                                       typename EM::T_scalar,\n                                       typename EM::T_rate>::nvars(ncmt, npar);\n      const int nvar_ss = pmx_model_nvars_ss<T_model,\n                                             typename EM::T_amt,\n                                             typename EM::T_par_rate,\n                                             typename EM::T_par_ii>::nvars(npar);\n      return rec.has_ss_dosing(id) ? pk_nsys(ncmt, nvar, nvar_ss) : pk_nsys(ncmt, nvar);\n    }\n\n    /**\n     * Every Torsten function calls Pred.\n     *\n     * Predicts the amount in each compartment for each event,\n     * given the event schedule and the parameters of the model.\n     *\n     * Proceeds in two steps. First, computes all the events that\n     * are not included in the original data set but during which\n     * amounts in the system get updated. Secondly, predicts\n     * the amounts in each compartment sequentially by going\n     * through the augmented schedule of events. The returned pred\n     * Matrix only contains the amounts in the event originally\n     * specified by the users.\n     *\n     * This function is valid for all models. What changes from one\n     * model to the other are the Pred1 and PredSS functions, which\n     * calculate the amount at an individual event.\n     *\n     * @tparam T_em type the @c EventsManager\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 (starts at 1)\n     * @param[in] addl additional dosing at each event\n     * @param[in] ss steady state approximation at each event\n     * (0: no, 1: yes)\n     * @param[in] pMatrix parameters at each event\n     * @param[in] addParm additional parameters at each event\n     * @parem[in] model basic info for ODE model and evolution operators\n     * @param[in] SystemODE matrix describing linear ODE system that\n     * defines compartment model. Used for matrix exponential solutions.\n     * Included because it may get updated in modelParameters.\n     * @return a matrix with predicted amount in each compartment\n     * at each event.\n     */\n    template<typename integrator_type, typename... scalar_pars_type>\n    void pred(int id,\n              const T_event_record& events_rec,\n              Eigen::Matrix<typename EM::T_scalar, -1, -1>& res,\n              const integrator_type& integrator,\n              const std::vector<theta_container<T4>>& theta,\n              const std::vector<std::vector<event_ctrl_type>>&... event_ctrl,\n              const std::vector<std::vector<ode_data_type>>&... ode_data,\n              const scalar_pars_type... scalar_pars) {\n      using Eigen::Matrix;\n      using Eigen::Dynamic;\n      using std::vector;\n      using torsten::PKRec;\n\n      int nCmt = EM::nCmt(events_rec);\n\n      res.resize(nCmt, events_rec.num_event_times(id));\n      PKRec<typename EM::T_scalar> init(nCmt);\n      init.setZero();\n\n      try {\n        EM em(id, events_rec, theta, event_ctrl..., ode_data...);\n        int ikeep = 0, iev = 0;\n\n        while(ikeep < em.nKeep) {\n          stepper(iev, init, em, integrator, scalar_pars...);\n          if(em.events().keep(iev)) {\n            res.col(ikeep) = init;\n            ikeep++;\n          }\n          iev++;\n        }\n      } catch (const std::exception& e) {\n        throw;\n      }\n    }\n\n    /*\n     * Step through a range of events.\n     */\n    template<typename integrator_type, typename... scalar_pars_type>\n    void stepper(int i, PKRec<typename EM::T_scalar>& init, const EM& em,\n                 const integrator_type& integrator,\n                 const scalar_pars_type... scalar_pars) {\n      auto& events = em.events();\n      using scalar = typename EM::T_scalar;\n      typename EM::T_time tprev = i == 0 ? events.time(0) : events.time(i-1);\n\n      T_model pkmodel {model_factory<T_model, EM, scalar_pars_type...>::model(em, i,\n                                                                              par_index_seq<ode_data_type...>{},\n                                                                              scalar_pars...)};\n      auto ev = em.event(i);\n      ev(init, pkmodel, integrator);\n    }\n\n    /**\n     * Solve an event from event manager and store the result in both\n     * data format(solution & gradient) and <code>var</code> format.\n     *\n     * @param i id of the event to be solved\n     * @param init <code>var</code> solution\n     * @param sol_d data solution\n     * @param em event manager\n     * @param integrator numerical integrator for ODE\n     * @param scalar_pars params needed to construst the PMX model,\n     *        such as functor & dimension of ODE system\n     */\n    template<typename integrator_type, typename... scalar_pars_type>\n    void stepper_solve(int i, torsten::PKRec<typename EM::T_scalar>& init,\n                       torsten::PKRec<double>& sol_d,\n                       const EM& em,\n                       const integrator_type& integrator,\n                       const scalar_pars_type... scalar_pars) {\n      using std::vector;\n      using stan::math::var;\n\n      auto& events = em.events();\n\n      typename EM::T_time tprev = i == 0 ? events.time(0) : events.time(i-1);\n\n      T_model pkmodel {model_factory<T_model, EM, scalar_pars_type...>::model(em, i,\n                                                                              par_index_seq<ode_data_type...>{},\n                                                                              scalar_pars...)};\n      auto ev = em.event(i);\n      ev(sol_d, init, pkmodel, integrator, scalar_pars...);\n    }\n\n    template<typename integrator_type, typename... scalar_pars_type>\n    /**\n     * For MPI solutions, after each rank solves its corresponding\n     * subjects, all ranks sync their results among each other.\n     *\n     * @param i id of the event to be synced\n     * @param init <code>var</code> solution\n     * @param sol_d data solution\n     * @param em event manager\n     * @param integrator numerical integrator for ODE\n     * @param scalar_pars params needed to construst the PMX model,\n     *        such as functor & dimension of ODE system\n     */\n    void stepper_sync(int i, torsten::PKRec<typename EM::T_scalar>& init,\n                      torsten::PKRec<double>& sol_d,\n                      const EM& em,\n                      const integrator_type& integrator,\n                      const scalar_pars_type... scalar_pars) {\n      using std::vector;\n      using stan::math::var;\n\n      auto& events = em.events();\n\n      typename EM::T_time tprev = i == 0 ? events.time(0) : events.time(i-1);\n\n      if (events.is_reset(i)) {\n        init.setZero();\n      } else if (events.is_ss_dosing(i)) {  // steady state event\n        T_model pkmodel {model_factory<T_model, EM, scalar_pars_type...>::model(em, i,\n                                                                                par_index_seq<ode_data_type...>{},\n                                                                                scalar_pars...)};\n        auto curr_amt = em.fractioned_amt(i);\n        vector<var> v_i(dsolve::pk_vars(curr_amt, events.rate(i), events.ii(i), pkmodel.par()));\n        int nsys = torsten::pk_nsys(em.ncmt, v_i.size());\n        if (events.ss(i) == 2)\n          init += torsten::mpi::precomputed_gradients(sol_d.segment(0, nsys), v_i);  // steady state without reset\n        else\n          init = torsten::mpi::precomputed_gradients(sol_d.segment(0, nsys), v_i);  // steady state with reset (ss = 1)\n      } else if (events.time(i) > tprev) {\n        // auto curr_rates = stan::math::value_of(em.fractioned_rates(i));\n        auto curr_rates = em.fractioned_rates(i);\n          T_model pkmodel {model_factory<T_model, EM, scalar_pars_type...>::model(em, i,\n                                                                                  par_index_seq<ode_data_type...>{},\n                                                                                  scalar_pars...)};\n          vector<var> v_i =\n            pmx_model_vars<T_model>::vars(events.time(i), init, curr_rates, pkmodel.par());\n          int nsys = torsten::pk_nsys(em.ncmt, v_i.size());\n          init = torsten::mpi::precomputed_gradients(sol_d.segment(0, nsys), v_i);\n      }\n\n      if (events.is_bolus_dosing(i)) {\n        init(events.cmt(i) - 1) += em.fractioned_amt(i);\n      }\n    }\n\n#ifdef TORSTEN_MPI\n\n    /*\n     * MPI solution when the population\n     * information passed in as ragged arrays. The overloading occurs\n     * on <code>res</code> arg for results. Here the result is <code>var</code>.\n     *\n     * @param events_rec event record\n     * @param res solution \n     * @param integrator ODE integrator\n     * @param theta PMX parameters passed into ODE function\n     * @param event_ctrl optional PMX parameters: bioavailability & tlag\n     * @param ode_data optional ODE parameters: real & integer data\n     * @param scalar_pars params needed to construst the PMX model,\n     *        such as functor & dimension of ODE system\n     */\n    template<typename integrator_type, typename... scalar_pars_type>\n    void pred(const T_event_record& events_rec,\n              Eigen::Matrix<stan::math::var, -1, -1>& res,\n              const integrator_type& integrator,\n              const std::vector<theta_container<T4>>& theta,\n              const std::vector<std::vector<event_ctrl_type>>&... event_ctrl,\n              const std::vector<std::vector<ode_data_type>>&... ode_data,\n              const scalar_pars_type... scalar_pars) {\n      using Eigen::Matrix;\n      using Eigen::MatrixXd;\n      using Eigen::VectorXd;\n      using Eigen::Dynamic;\n      using std::vector;\n      using::stan::math::var;\n      using torsten::PKRec;\n\n      using scalar = typename EM::T_scalar;\n\n      const int nCmt = EM::nCmt(events_rec);\n      const int np = events_rec.num_subjects();\n      bool is_invalid = false;\n      std::ostringstream rank_fail_msg;\n\n      const MPI_Comm& comm = torsten::mpi::Session::pmx_parm_comm().comm();\n      int rank = torsten::mpi::Session::pmx_parm_comm().rank();\n      int size = torsten::mpi::Session::pmx_parm_comm().size();\n\n      std::vector<MPI_Request> req(np);\n      vector<MatrixXd> res_d(np);\n      \n      res.resize(nCmt, events_rec.total_num_event_times);\n\n      PKRec<scalar> init(nCmt);\n      PKRec<double> pred1;\n      for (int id = 0; id < np; ++id) {\n\n        /* For every rank */\n\n        const int nKeep = events_rec.num_event_times(id);\n\n        int nev = EM::num_events(id, events_rec, theta, event_ctrl..., ode_data...);\n        res_d[id].resize(system_size(id, events_rec, theta), nev);\n        res_d[id].setConstant(0.0);\n\n        int my_worker_id = torsten::mpi::my_worker(id, np, size);\n\n        /* only solver rank */\n\n        if (rank == my_worker_id) {\n          if (is_invalid) {\n            res_d[id].setConstant(invalid_res_d);\n          } else {\n            try {\n              EM em(id, events_rec, theta, event_ctrl..., ode_data...);\n              auto& events = em.events();\n              assert(nev == events.size());\n              assert(nKeep == em.nKeep);\n              init.setZero();\n\n              int ikeep = 0, iev = 0;\n              while(ikeep < em.nKeep) {\n                stepper_solve(iev, init, pred1, em, integrator, scalar_pars...);\n                res_d[id].col(iev).segment(0, pred1.size()) = pred1;\n                if(events.keep(iev)) {\n                  res.col(EM::begin(id, events_rec) + ikeep) = init;\n                  ikeep++;\n                }\n                iev++;\n              }\n            } catch (const std::exception& e) {\n              is_invalid = true;\n              res_d[id].setConstant(invalid_res_d);\n              rank_fail_msg << \"Rank \" << rank << \" failed to solve id \" << id << \": \" << e.what();\n            }\n          }\n        }\n        MPI_Ibcast(res_d[id].data(), res_d[id].size(), MPI_DOUBLE, my_worker_id, comm, &req[id]);\n      }\n\n      // int finished = 0;\n      // int index;\n      // int flag = 0;\n      // for(int id = 0; id < np; ++id) {\n      //   MPI_Wait(&req[id], MPI_STATUS_IGNORE);\n\n      //   if (is_invalid) continue;\n      //   if (std::isnan(res_d[id](0))) {\n      //     assert(rank != torsten::mpi::my_worker(id, np, size));\n      //     is_invalid = true;\n      //     rank_fail_msg << \"Rank \" << rank << \" received invalid data for id \" << id;\n      //   } else {\n      //     EM em(id, events_rec);\n      //     auto& events = em.events();\n      //     PKRec<scalar> init(nCmt); init.setZero();\n      //     PKRec<double> pred1 = VectorXd::Zero(res_d[id].rows());\n\n      //     int ikeep = 0, iev = 0;\n      //     while(ikeep < em.nKeep) {\n      //       pred1 = res_d[id].col(iev);\n      //       stepper_sync(iev, init, pred1, em, integrator, scalar_pars...);\n      //       if(events.keep(iev)) {\n      //         res.col(EM::begin(id, events_rec) + ikeep) = init;\n      //         ikeep++;\n      //       }\n      //       iev++;\n      //     }\n      //   }\n      // }\n\n      int finished = 0;\n      int index = 0;\n      int flag = 0;\n      while (finished < np) {\n        MPI_Test(&req[index], &flag, MPI_STATUS_IGNORE);\n        if (flag) {\n          int id = index;\n          index++;\n          finished++;\n          if (is_invalid) continue;\n          if (std::isnan(res_d[id](0))) {\n            // assert(rank != torsten::mpi::my_worker(id, np, size));\n            is_invalid = true;\n            rank_fail_msg << \"Rank \" << rank << \" received invalid data for id \" << id;\n          } else {\n            EM em(id, events_rec, theta, event_ctrl..., ode_data...);\n            auto& events = em.events();\n            PKRec<scalar> init(nCmt); init.setZero();\n            PKRec<double> pred1 = VectorXd::Zero(res_d[id].rows());\n\n            int ikeep = 0, iev = 0;\n            while(ikeep < em.nKeep) {\n              pred1 = res_d[id].col(iev);\n              stepper_sync(iev, init, pred1, em, integrator, scalar_pars...);\n              if(events.keep(iev)) {\n                res.col(EM::begin(id, events_rec) + ikeep) = init;\n                ikeep++;\n              }\n              iev++;\n            }\n          }\n        } \n      }\n\n      MPI_Barrier(comm);\n\n      if(is_invalid) {\n        throw std::runtime_error(rank_fail_msg.str());\n      }\n    }\n\n    /*\n     * Data-only MPI solver that takes ragged arrays as input.\n     */\n    template<typename integrator_type, typename... scalar_pars_type>\n    void pred(const T_event_record& events_rec, Eigen::MatrixXd& res,\n              const integrator_type& integrator,\n              const std::vector<theta_container<T4>>& theta,\n              const std::vector<std::vector<event_ctrl_type>>&... event_ctrl,\n              const std::vector<std::vector<ode_data_type>>&... ode_data,\n              const scalar_pars_type... scalar_pars) {\n      using Eigen::Matrix;\n      using Eigen::MatrixXd;\n      using Eigen::VectorXd;\n      using Eigen::Dynamic;\n      using std::vector;\n      using::stan::math::var;\n      using torsten::PKRec;\n\n      using ER = NONMENEventsRecord<double, double, double, double>;\n      using EM_d = EventsManager<ER, NonEventParameters<T0, T4, theta_container, std::tuple<event_ctrl_type...>, ode_data_type...>>;\n\n      const int nCmt = EM_d::nCmt(events_rec);\n      const int np = events_rec.num_subjects();\n      bool is_invalid = false;\n      std::ostringstream rank_fail_msg;\n\n      const MPI_Comm& comm = torsten::mpi::Session::pmx_data_comm().comm();\n      int rank = torsten::mpi::Session::pmx_data_comm().rank();\n      int size = torsten::mpi::Session::pmx_data_comm().size();\n\n      std::vector<MPI_Request> req(np);\n\n      res.resize(nCmt, events_rec.total_num_event_times);\n\n      PKRec<double> init(nCmt);\n      for (int id = 0; id < np; ++id) {\n\n        /* For every rank */\n        int nKeep = events_rec.num_event_times(id);\n        int my_worker_id = torsten::mpi::my_worker(id, np, size);\n        int begin_id = EM_d::begin(id, events_rec) * nCmt;\n        int size_id = nKeep * nCmt;\n\n        /* only solver rank */\n        if (rank == my_worker_id) {\n          try {\n            EM em(id, events_rec, theta, event_ctrl..., ode_data...);\n            auto& events = em.events();\n            init.setZero();\n            int ikeep = 0, iev = 0;\n            while(ikeep < em.nKeep) {\n              stepper(iev, init, em, integrator, scalar_pars...);\n              if(events.keep(iev)) {\n                res.col(EM_d::begin(id, events_rec) + ikeep) = init;\n                ikeep++;\n              }\n              iev++;\n            }\n          } catch (const std::exception& e) {\n            is_invalid = true;\n            res(begin_id) = invalid_res_d;\n            rank_fail_msg << \"Rank \" << rank << \" failed to solve id \" << id << \": \" << e.what();\n          }\n        }\n\n        MPI_Ibcast(res.data() + begin_id, size_id, MPI_DOUBLE, my_worker_id, comm, &req[id]);\n      }\n\n      // make sure every rank throws in case any rank fails\n      int finished = 0;\n      int index = 0;\n      int flag = 0;\n      while (finished < np && size > 1) {\n        MPI_Testany(np, req.data(), &index, &flag, MPI_STATUS_IGNORE);\n        if (flag) {\n          finished++;\n          if(is_invalid) continue;\n          int id = index;\n          int begin_id = EM_d::begin(id, events_rec) * nCmt;\n          if (std::isnan(res(begin_id))) {\n            is_invalid = true;\n            rank_fail_msg << \"Rank \" << rank << \" received invalid data for id \" << id;\n          }\n        }\n      }\n\n      MPI_Barrier(comm);\n\n      if(is_invalid) {\n        MPI_Barrier(comm);\n        throw std::runtime_error(rank_fail_msg.str());\n      }\n    }\n#else\n\n    /*\n     * For population input in the form of ragged arrays,\n     * addional information of the size of each individual\n     * is required to locate the data in a single array for population.\n     */\n    template<typename integrator_type, typename... scalar_pars_type> //NOLINT\n    void pred(const T_event_record& events_rec,\n              Eigen::Matrix<typename EM::T_scalar, -1, -1>& res,\n              const integrator_type& integrator,\n              const std::vector<theta_container<T4>>& theta,\n              const std::vector<std::vector<event_ctrl_type>>&... event_ctrl,\n              const std::vector<std::vector<ode_data_type>>&... ode_data,\n              const scalar_pars_type... scalar_pars) {\n      using ER = T_event_record;\n\n      const int nCmt = EM::nCmt(events_rec);\n      const int np = events_rec.num_subjects();\n      \n      res.resize(nCmt, events_rec.total_num_event_times);\n\n      static bool has_warning = false;\n      if (!has_warning) {\n        std::cout << \"Torsten Population PK solver \" << \"running sequentially\" << \"\\n\";\n        has_warning = true;\n      }\n\n      for (int id = 0; id < np; ++id) {\n        const int nKeep = events_rec.num_event_times(id);\n        Eigen::Matrix<typename EM::T_scalar, -1, -1> res_id(nCmt, nKeep);\n        pred(id, events_rec, res_id, integrator, theta,\n             event_ctrl..., ode_data..., scalar_pars...);\n        for (int j = 0; j < nKeep; ++j) {\n          res.col(EM::begin(id, events_rec) + j) = res_id.col(j);\n        }\n      }\n    }\n#endif\n  };\n\n  template<typename T_model, typename T_event_record,\n           typename T0, typename T4, template<typename...> class theta_container,\n           typename... event_ctrl_type,\n           typename... ode_data_type>\n  constexpr double EventSolver<T_model,\n                               EventsManager<T_event_record, NonEventParameters<T0, T4, theta_container,\n                                                                                std::tuple<event_ctrl_type...>,\n                                                                                ode_data_type...>> >::invalid_res_d;\n}\n#endif\n", "meta": {"hexsha": "83c46101692e385225d66c1674f9cc76af1e229f", "size": 22594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ev_solver.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": "ev_solver.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": "ev_solver.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": 40.2028469751, "max_line_length": 132, "alphanum_fraction": 0.5531557051, "num_tokens": 5311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.17655183748289513}}
{"text": "#pragma once\n\n#define BOOST_PARAMETER_MAX_ARITY 17\n// Following defines move parts of SVG++ code to svgpp_parser_impl.cpp file\n// reducing compiler memory requirements\n#define SVGPP_USE_EXTERNAL_PATH_DATA_PARSER\n#define SVGPP_USE_EXTERNAL_TRANSFORM_PARSER\n#define SVGPP_USE_EXTERNAL_PRESERVE_ASPECT_RATIO_PARSER\n#define SVGPP_USE_EXTERNAL_PAINT_PARSER\n#define SVGPP_USE_EXTERNAL_MISC_PARSER\n#define SVGPP_USE_EXTERNAL_COLOR_PARSER\n#define SVGPP_USE_EXTERNAL_LENGTH_PARSER\n\n#if defined(RENDERER_AGG)\n#include <agg_color_rgba.h>\n#include <agg_trans_affine.h>\n#elif defined(RENDERER_GDIPLUS)\n#include <windows.h>\n#include <gdiplus.h>\n#undef min\n#undef max\n#undef small\n#include <vector>\n#elif defined(RENDERER_SKIA)\n#include <SkPaint.h>\n#endif\n\n#include <svgpp/factory/integer_color.hpp>\n#include <svgpp/factory/unitless_length.hpp>\n#if defined(SVG_PARSER_MSXML)\n# include \"parser_msxml.hpp\"\n#elif defined(SVG_PARSER_RAPIDXML_NS)\n# include \"parser_rapidxml_ns.hpp\"\n#elif defined(SVG_PARSER_LIBXML)\n# include \"parser_libxml.hpp\"\n#elif defined(SVG_PARSER_XERCES)\n# include \"parser_xerces.hpp\"\n#else\n#error One of XML parsers must be set with SVG_PARSER_xxxx macro\n#endif\n#include <boost/function.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <map>\n\n#if defined(RENDERER_AGG)\ntypedef double number_t;\ntypedef agg::trans_affine transform_t;\ntypedef agg::rgba8 color_t;\n\ninline color_t BlackColor() { return color_t(0, 0, 0); }\ninline color_t TransparentBlackColor() { return color_t(0, 0, 0, 0); }\ninline color_t TransparentWhiteColor() { return color_t(255, 255, 255, 0); }\n\nstruct color_factory_base_t\n{\n  typedef agg::rgba8 color_type;\n\n  static color_type create(unsigned char r, unsigned char g, unsigned char b)\n  {\n    return color_type(r, g, b);\n  }\n};\ntypedef svgpp::factory::color::percentage_adapter<color_factory_base_t> color_factory_t;\n#elif defined(RENDERER_GDIPLUS)\ntypedef Gdiplus::REAL number_t;\ntypedef Gdiplus::Matrix transform_t;\ntypedef Gdiplus::Color color_t;\n\ninline color_t BlackColor() { return color_t(0, 0, 0); }\ninline color_t TransparentBlackColor() { return color_t(0, 0, 0, 0); }\ninline color_t TransparentWhiteColor() { return color_t(0, 255, 255, 255); }\n\nstruct color_factory_base_t\n{\n  typedef Gdiplus::Color color_type;\n\n  static color_type create(unsigned char r, unsigned char g, unsigned char b)\n  {\n    return color_type(r, g, b);\n  }\n};\ntypedef svgpp::factory::color::percentage_adapter<color_factory_base_t> color_factory_t;\n#elif defined(RENDERER_SKIA)\ntypedef SkScalar number_t;\ntypedef SkMatrix transform_t;\ntypedef SkColor color_t;\n\ninline color_t BlackColor() { return SK_ColorBLACK; }\ninline color_t TransparentBlackColor() { return SK_ColorTRANSPARENT; }\ninline color_t TransparentWhiteColor() { return 0x00FFFFFF; }\n\nstruct color_policy\n{\n  static const SkColor preset_bits = 0xFF000000;\n  static const SkColor r_offset = 16;\n  static const SkColor g_offset = 8;\n  static const SkColor b_offset = 0;\n};\n\ntypedef svgpp::factory::color::integer<SkColor, color_policy> color_factory_t;\n#else\n#error One of renderers must be set with RENDERER_xxxx macro\n#endif\n\ntypedef svgpp::factory::length::unitless<number_t, number_t> length_factory_t;\ntypedef boost::tuple<double, double, double, double> bounding_box_t;\ntypedef boost::function<bounding_box_t()> get_bounding_box_func_t;\n\n#if defined(RENDERER_GDIPLUS)\ninline void AssignMatrix(Gdiplus::Matrix & dest, Gdiplus::Matrix const & src)\n{\n  Gdiplus::REAL m[6];\n  src.GetElements(m);\n  dest.SetElements(m[0], m[1], m[2], m[3], m[4], m[5]);\n}\n\nclass PathStorage\n{\npublic:\n  void path_move_to(number_t x, number_t y, svgpp::tag::coordinate::absolute const &)\n  { \n    path_points_.push_back(Gdiplus::PointF(x, y));\n    path_types_.push_back(Gdiplus::PathPointTypeStart);\n  }\n\n  void path_line_to(number_t x, number_t y, svgpp::tag::coordinate::absolute const &)\n  { \n    path_points_.push_back(Gdiplus::PointF(x, y));\n    path_types_.push_back(Gdiplus::PathPointTypeLine);\n  }\n\n  void path_cubic_bezier_to(\n    number_t x1, number_t y1,\n    number_t x2, number_t y2,\n    number_t x, number_t y,\n    svgpp::tag::coordinate::absolute const &)\n  { \n    // TODO:\n    path_points_.push_back(Gdiplus::PointF(x1, y1));\n    path_types_.push_back(Gdiplus::PathPointTypeBezier);\n    path_points_.push_back(Gdiplus::PointF(x2, y2));\n    path_types_.push_back(Gdiplus::PathPointTypeBezier);\n    path_points_.push_back(Gdiplus::PointF(x, y));\n    path_types_.push_back(Gdiplus::PathPointTypeBezier);\n  }\n\n  void path_close_subpath()\n  {\n    if (!path_types_.empty())\n      path_types_.back() |= Gdiplus::PathPointTypeCloseSubpath;\n  }\n\n  void path_exit()\n  {}\n\n  std::vector<Gdiplus::PointF> path_points_;\n  std::vector<BYTE> path_types_;\n};\n#endif", "meta": {"hexsha": "a75980487501adbe8495e03a25c2805188e019d1", "size": 4722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "P0267_RefImpl/Samples/svg/external/svgpp/src/demo/render/common.hpp", "max_stars_repo_name": "zmm-Embedded/io2d", "max_stars_repo_head_hexsha": "2e53612d60692d70700b4f7d0f9e4e34dbe11388", "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": "P0267_RefImpl/Samples/svg/external/svgpp/src/demo/render/common.hpp", "max_issues_repo_name": "zmm-Embedded/io2d", "max_issues_repo_head_hexsha": "2e53612d60692d70700b4f7d0f9e4e34dbe11388", "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": "P0267_RefImpl/Samples/svg/external/svgpp/src/demo/render/common.hpp", "max_forks_repo_name": "zmm-Embedded/io2d", "max_forks_repo_head_hexsha": "2e53612d60692d70700b4f7d0f9e4e34dbe11388", "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.6981132075, "max_line_length": 88, "alphanum_fraction": 0.7662007624, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17643454092114197}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: David Wojnar $\n// $Authors: David Wojnar $\n// --------------------------------------------------------------------------\n#include <OpenMS/ANALYSIS/ID/AScore.h>\n#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>\n#include <OpenMS/KERNEL/MSSpectrum.h>\n#include <OpenMS/KERNEL/RangeUtils.h>\n#include <OpenMS/METADATA/PeptideHit.h>\n#include <OpenMS/DATASTRUCTURES/String.h>\n\n#include <map>\n#include <cmath>\n#include <algorithm> //find\n#include <boost/math/special_functions/binomial.hpp>\n\n#include <iostream>\n\nusing namespace std;\n\nnamespace OpenMS\n{\n\n  AScore::AScore()\n  {\n  }\n\n  AScore::~AScore()\n  {\n  }\n\n  PeptideHit AScore::compute(PeptideHit & hit, RichPeakSpectrum & real_spectrum, double fmt, Int number_of_phospho_sites)\n  {\n    String without_phospho_str(hit.getSequence().toString());\n    size_t found = without_phospho_str.find(\"(Phospho)\");\n    while (found != string::npos)\n    {\n      without_phospho_str.erase(found, String(\"(Phospho)\").size());\n      found = without_phospho_str.find(\"(Phospho)\");\n    }\n    AASequence without_phospho = AASequence::fromString(without_phospho_str);\n    String umps = without_phospho.toUnmodifiedString(); // unmodified phosphostring\n    Int number_of_STY = Int(std::count(umps.begin(), umps.end(), 'S') + std::count(umps.begin(), umps.end(), 'T') + std::count(umps.begin(), umps.end(), 'Y'));\n    if (real_spectrum.empty() || number_of_phospho_sites < 1 || number_of_STY == 0)\n    {\n      return PeptideHit(-1, 0, hit.getCharge(), without_phospho);\n    }\n    TheoreticalSpectrumGenerator spectrum_generator;\n    vector<RichPeakSpectrum> th_spectra;     //typedef MSSpectrum<RichPeak1D> RichPeakSpectrum;\n    ///produce theoretical spectra\n    if (number_of_STY < number_of_phospho_sites)\n    {\n      number_of_phospho_sites = number_of_STY;\n    }\n    //Int number_of_permutations = (Int)boost::math::binomial_coefficient<double>((double)number_of_STY, number_of_phospho_sites);\n    vector<Size> tupel(computeTupel_(without_phospho));\n    vector<vector<Size> > permutations(computePermutations_(tupel, number_of_phospho_sites));\n    //cout<<\"number of permutations \"<<permutations.size();//<< \" - \" << number_of_permutations;\n    th_spectra.resize(permutations.size());\n    for (Size i = 0; i < permutations.size(); ++i)\n    {\n      AASequence temp(without_phospho);\n      Size permu = 0;\n      for (Size as = 0; as < temp.size(); ++as)\n      {\n        if (as == permutations[i][permu])\n        {\n          temp.setModification(as, \"Phospho\");\n          ++permu;\n        }\n        if (permu == permutations[i].size())\n          break;\n      }\n      spectrum_generator.addPeaks(th_spectra[i], temp, Residue::BIon, hit.getCharge());\n      spectrum_generator.addPeaks(th_spectra[i], temp, Residue::YIon, hit.getCharge());\n      th_spectra[i].setName(temp.toString());\n    }\n    ///produce theoretical spectra - END\n\n    if (!real_spectrum.isSorted())\n    {\n      real_spectrum.sortByPosition();\n    }\n    vector<vector<double> > peptide_site_scores(th_spectra.size());\n    vector<RichPeakSpectrum> windows_with_all_peak_depths;\n    ///prepare peak depth for all windows in the actual spectrum\n    {\n      double biggest_window = real_spectrum[real_spectrum.size() - 1].getMZ();\n      Size number_of_windows = 1;\n      if (biggest_window > 100)\n        number_of_windows = ceil(biggest_window / 100);\n      windows_with_all_peak_depths.resize(number_of_windows);\n      RichPeakSpectrum::Iterator begin_window = real_spectrum.MZBegin(0);\n      RichPeakSpectrum::Iterator end_window = real_spectrum.MZBegin(100);\n      for (Size current_window = 0; current_window < number_of_windows; ++current_window)\n      {\n        RichPeakSpectrum real_window;\n        RichPeakSpectrum::Iterator runner = begin_window;\n        while (runner <= end_window)\n        {\n          real_window.push_back(*runner);\n          ++runner;\n        }\n\n        real_window.sortByIntensity(true);\n        for (Size i = 0; i < 10; ++i)\n        {\n          if (i < real_window.size())\n            windows_with_all_peak_depths[current_window].push_back(real_window[i]);\n        }\n        begin_window = end_window + 1;\n        end_window = real_spectrum.MZBegin((current_window + 1) * 100);\n      }\n    }\n    ///prepare peak depth for all windows in the actual spectrum - END\n    UInt N;\n    vector<vector<double> >::iterator side_scores = peptide_site_scores.begin();\n    for (vector<RichPeakSpectrum>::iterator it = th_spectra.begin(); it < th_spectra.end(); ++it, ++side_scores)    //each theoretical spectrum\n    {\n      N = UInt(it->size());       //real or theo!!\n      UInt i = 1;\n      side_scores->resize(10);\n      while (i <= 10)\n      {\n        //Auslagern\n        UInt n = 0;\n        for (Size depth = 0; depth <  windows_with_all_peak_depths.size(); ++depth)         //each 100 m/z window\n        {\n          n += numberOfMatchedIons_(*it, windows_with_all_peak_depths[depth], i, fmt);\n        }\n        //auslagern_end\n        double p = (double)i / 100;\n        double cum_socre = computeCumulativeScore(N, n, p);\n        (*side_scores)[i - 1] = (-10 * log10(cum_socre));    //computeCumulativeScore(N,n,p);\n        ++i;\n      }\n    }\n    vector<ProbablePhosphoSites> highest_peptides;\n    PeptideHit phospho;\n    if (permutations[0].size() < permutations.size())\n    {\n      computeHighestPeptides(peptide_site_scores, highest_peptides, permutations);\n      phospho.setScore(peptideScore_(peptide_site_scores[highest_peptides[0].seq_1]));\n      //phospho.setSequence(AASequence(th_spectra[highest_peptides[0].seq_1].getName()));\n    }\n    {\n      multimap<double, Size> ranking;\n      for (Size it = 0; it < peptide_site_scores.size(); ++it)\n      {\n        double current_score = peptideScore_(peptide_site_scores[it]);\n        ranking.insert(pair<double, Size>(current_score, it));\n      }\n      phospho.setScore(ranking.rbegin()->first);\n      phospho.setSequence(AASequence::fromString(th_spectra[ranking.rbegin()->second].getName()));\n    }\n    phospho.setCharge(hit.getCharge());\n    phospho.setMetaValue(\"Search_engine_sequence\", hit.getSequence().toString());\n    ///Calculate AScore\n    //Int add_ascores = (Int)highest_peptides.size()/permutations[0].size();\n    //Int count_ascores = 0;\n    //vector<ProbablePhosphoSites>::iterator winner = highest_peptides.begin();\n    //vector<ProbablePhosphoSites>::iterator actual = winner;\n    //double ascore_addition = 0.0;\n    //double highest_addition = 0.0;\n    Int rank = 1;\n    for (vector<ProbablePhosphoSites>::iterator hp = highest_peptides.begin(); hp < highest_peptides.end(); ++hp)\n    {\n      vector<RichPeakSpectrum> site_determining_ions;\n      compute_site_determining_ions(th_spectra, *hp, hit.getCharge(), site_determining_ions);\n      N = UInt(site_determining_ions[0].size());       // all possiblities have the same number\n      double p = (double)hp->peak_depth / 100;\n      Int n = 0;\n      //Auslagern\n      for (Size depth = 0; depth <  windows_with_all_peak_depths.size(); ++depth)       //each 100 m/z window\n      {\n        n += numberOfMatchedIons_(site_determining_ions[0], windows_with_all_peak_depths[depth], (Size)p, fmt);\n      }\n      //auslagern_end\n      double P_first = computeCumulativeScore(N, n, p);\n      Int n2 = 0;\n      //Auslagern\n      for (Size depth = 0; depth <  windows_with_all_peak_depths.size(); ++depth)       //each 100 m/z window\n      {\n        n2 += numberOfMatchedIons_(site_determining_ions[1], windows_with_all_peak_depths[depth], (Size)p, fmt);\n      }\n      //auslagern_end\n      double P_second = computeCumulativeScore(N, n2, p);\n      double score_first = -10 * log10(P_first);\n      double score_second = -10 * log10(P_second);\n      double AScore_first = score_first - score_second;\n      phospho.setMetaValue(\"AScore_\" + String(rank), AScore_first);\n      ++rank;\n      /*    hp->AScore = AScore_first;\n          ++count_ascores;\n          ascore_addition += AScore_first;\n          if(count_ascores == add_ascores)\n          {\n\n              count_ascores = 0;\n              if(ascore_addition > highest_addition)\n              {\n                  highest_addition = ascore_addition;\n                  winner = actual;\n              }\n              actual = hp;\n              ascore_addition = 0;\n          }*/\n    }\n    return phospho;\n  }\n\n  double AScore::computeCumulativeScore(UInt N, UInt n, double p)\n  {\n    if (n > N)\n    {\n      return -1.0;\n    }\n    double score = 0.0;\n    for (UInt k = n; k <= N; ++k)\n    {\n      double coeff = boost::math::binomial_coefficient<double>((double)N, k);\n      double pow1 = pow((double)p, (int)k);\n      double pow2 = pow(double(1 - p), double(N - k));\n      score += coeff * pow1 * pow2;\n    }\n    if (score == 0.0)\n    {\n      return 1.0;\n    }\n    return score;\n  }\n\n  void AScore::computeHighestPeptides(std::vector<std::vector<double> > & peptide_site_scores, std::vector<ProbablePhosphoSites> & sites, vector<vector<Size> > & permutations)\n  {\n    sites.clear();\n    sites.resize(permutations[0].size());\n    multimap<double, Size> ranking;\n    for (Size it = 0; it < peptide_site_scores.size(); ++it)\n    {\n      double current_score = peptideScore_(peptide_site_scores[it]);\n      ranking.insert(pair<double, Size>(current_score, it));\n    }\n    vector<Size> & hps = permutations[ranking.rbegin()->second /*it->second*/];       //highest peptide score\n    for (Size i = 0; i < hps.size(); ++i)\n    {\n      multimap<double, Size>::reverse_iterator rev = ranking.rbegin();\n      sites[i].first = hps[i];\n      sites[i].seq_1 = rev->second;          //it->second;\n      bool peptide_not_found = true;\n      do\n      {\n        ++rev;\n        for (Size j = 0; j < hps.size(); ++j)\n        {\n          if (j == i)\n          {\n            if (find(permutations[rev->second].begin(), permutations[rev->second].end(), hps[j]) != permutations[rev->second].end())\n            {\n              peptide_not_found = true;\n              break;\n            }\n            else\n            {\n              peptide_not_found = false;\n            }\n          }\n          else if (find(permutations[rev->second].begin(), permutations[rev->second].end(), hps[j]) == permutations[rev->second].end())\n          {\n            peptide_not_found = true;\n            break;\n          }\n          else\n          {\n            peptide_not_found = false;\n          }\n        }\n      }\n      while (peptide_not_found);\n      sites[i].seq_2 = rev->second;\n      for (Size j = 0; j < permutations[sites[i].seq_2].size(); ++j)\n      {\n        if (find(permutations[sites[i].seq_1].begin(), permutations[sites[i].seq_1].end(), permutations[sites[i].seq_2][j]) == permutations[sites[i].seq_1].end())\n        {\n          sites[i].second = permutations[sites[i].seq_2][j];\n          break;\n        }\n      }\n    }\n    for (Size i = 0; i < sites.size(); ++i)\n    {\n      double current_peak_depth = 0.0;\n      sites[i].peak_depth = 1;\n      vector<double>::iterator first_it = peptide_site_scores[sites[i].seq_1].begin();\n      Size depth = 1;\n      for (vector<double>::iterator second_it = peptide_site_scores[sites[i].seq_2].begin(); second_it < peptide_site_scores[sites[i].seq_2].end(); ++second_it, ++first_it)\n      {\n        if ((*first_it - *second_it) > current_peak_depth)\n        {\n          current_peak_depth = *first_it - *second_it;\n          sites[i].peak_depth = depth;\n        }\n        ++depth;\n      }\n    }\n  }\n\n  void AScore::compute_site_determining_ions(vector<RichPeakSpectrum> & th_spectra, ProbablePhosphoSites & candidates, Int charge, vector<RichPeakSpectrum> & site_determining_ions)\n  {\n    site_determining_ions.clear();\n    site_determining_ions.resize(2);\n    TheoreticalSpectrumGenerator spectrum_generator;\n    AASequence pref, suf, pref_with_phospho_first, pref_with_phospho_second, suf_with_phospho_first, suf_with_phospho_second;\n    RichPeakSpectrum prefix, suffix, prefix_with_phospho_first, prefix_with_phospho_second, suffix_with_phospho_second, suffix_with_phospho_first;\n    AASequence first(AASequence::fromString(th_spectra[candidates.seq_1].getName()));\n    AASequence second(AASequence::fromString(th_spectra[candidates.seq_2].getName()));\n    if (candidates.first < candidates.second)\n    {\n      pref = AASequence::fromString(first.getPrefix(candidates.first + 1).toString());\n      suf = AASequence::fromString(second.getSuffix(second.size() - candidates.second - 1).toString());\n      pref_with_phospho_first = AASequence::fromString(first.getPrefix(candidates.second + 1).toString());\n      pref_with_phospho_second = AASequence::fromString(second.getPrefix(candidates.second + 1).toString());\n      suf_with_phospho_first = AASequence::fromString(first.getSuffix(first.size() - candidates.first).toString());\n      suf_with_phospho_second = AASequence::fromString(second.getSuffix(second.size() - candidates.first).toString());\n    }\n    else\n    {\n      pref = AASequence::fromString(second.getPrefix(candidates.second + 1).toString());\n      suf = AASequence::fromString(first.getSuffix(first.size() - candidates.first - 1).toString());\n      pref_with_phospho_first = AASequence::fromString(first.getPrefix(candidates.first + 1).toString());\n      pref_with_phospho_second = AASequence::fromString(second.getPrefix(candidates.first + 1).toString());\n      suf_with_phospho_first = AASequence::fromString(first.getSuffix(first.size() - candidates.second).toString());\n      suf_with_phospho_second = AASequence::fromString(second.getSuffix(first.size() - candidates.second).toString());\n    }\n    spectrum_generator.addPeaks(prefix, pref, Residue::BIon, charge);\n    spectrum_generator.addPeaks(suffix, suf, Residue::YIon, charge);\n    spectrum_generator.addPeaks(prefix_with_phospho_first, pref_with_phospho_first, Residue::BIon, charge);\n    spectrum_generator.addPeaks(prefix_with_phospho_second, pref_with_phospho_second, Residue::BIon, charge);\n    spectrum_generator.addPeaks(suffix_with_phospho_first, suf_with_phospho_first, Residue::YIon, charge);\n    spectrum_generator.addPeaks(suffix_with_phospho_second, suf_with_phospho_second, Residue::YIon, charge);\n    if (!prefix.empty())\n    {\n      for (RichPeakSpectrum::iterator it = prefix_with_phospho_first.begin(); it < prefix_with_phospho_first.end(); ++it)\n      {\n        if (it->getMZ() > prefix[prefix.size() - 1].getMZ())\n          site_determining_ions[0].push_back(*it);\n      }\n      for (RichPeakSpectrum::iterator it = prefix_with_phospho_second.begin(); it < prefix_with_phospho_second.end(); ++it)\n      {\n        if (it->getMZ() > prefix[prefix.size() - 1].getMZ())\n          site_determining_ions[1].push_back(*it);\n      }\n    }\n    else\n    {\n      for (RichPeakSpectrum::iterator it = prefix_with_phospho_first.begin(); it < prefix_with_phospho_first.end(); ++it)\n      {\n        site_determining_ions[0].push_back(*it);\n      }\n      for (RichPeakSpectrum::iterator it = prefix_with_phospho_second.begin(); it < prefix_with_phospho_second.end(); ++it)\n      {\n        site_determining_ions[1].push_back(*it);\n      }\n    }\n    if (!suffix.empty())\n    {\n      for (RichPeakSpectrum::iterator it = suffix_with_phospho_first.begin(); it < suffix_with_phospho_first.end(); ++it)\n      {\n        if (it->getMZ() > suffix[suffix.size() - 1].getMZ())\n          site_determining_ions[0].push_back(*it);\n      }\n      for (RichPeakSpectrum::iterator it = suffix_with_phospho_second.begin(); it < suffix_with_phospho_second.end(); ++it)\n      {\n        if (it->getMZ() > suffix[suffix.size() - 1].getMZ())\n          site_determining_ions[1].push_back(*it);\n      }\n    }\n    else\n    {\n      RichPeakSpectrum::iterator it1 = suffix_with_phospho_first.begin();\n      RichPeakSpectrum::iterator it2 = suffix_with_phospho_second.begin();\n      if (!suf.empty())\n      {\n        ++it1;\n        ++it2;\n      }\n      for (; it1 < suffix_with_phospho_first.end(); ++it1)\n      {\n        site_determining_ions[0].push_back(*it1);\n      }\n      for (; it2 < suffix_with_phospho_second.end(); ++it2)\n      {\n        site_determining_ions[1].push_back(*it2);\n      }\n    }\n    site_determining_ions[0].sortByPosition();\n    site_determining_ions[1].sortByPosition();\n  }\n\n  Int AScore::numberOfMatchedIons_(const RichPeakSpectrum & th, const RichPeakSpectrum & windows, Size depth, double fmt)\n  {\n    Int n = 0;\n    for (Size i = 0; i < windows.size() && i <= depth; ++i)\n    {\n      Size nearest_peak = th.findNearest(windows[i].getMZ());\n      if (nearest_peak < th.size() && fabs(th[nearest_peak].getMZ() - windows[i].getMZ()) < fmt)\n        ++n;\n    }\n    return n;\n  }\n\n  double AScore::peptideScore_(std::vector<double> & scores)\n  {\n    return (scores[0] * 0.5\n            + scores[1] * 0.75\n            + scores[2]           //*1\n            + scores[3]           //*1\n            + scores[4]           //*1\n            + scores[5]           //*1\n            + scores[6] * 0.75\n            + scores[7] * 0.5\n            + scores[8] * 0.25\n            + scores[9] * 0.25)\n           / 10;\n  }\n\n  vector<Size> AScore::computeTupel_(AASequence & without_phospho)\n  {\n    vector<Size> tupel;\n    String unmodified = without_phospho.toUnmodifiedString();\n    for (Size i = 0; i < unmodified.size(); ++i)\n    {\n      if (unmodified[i] == 'Y' || unmodified[i] == 'T' || unmodified[i] == 'S')\n      {\n        tupel.push_back(i);\n      }\n    }\n    return tupel;\n  }\n\n  vector<vector<Size> > AScore::computePermutations_(vector<Size> tupel, Int number_of_phospho_sites)\n  {\n    if (number_of_phospho_sites == 1)\n    {\n      vector<vector<Size>  > permutations;\n      for (Size i = 0; i < tupel.size(); ++i)\n      {\n        vector<Size> temp;\n        temp.push_back(tupel[i]);\n        permutations.push_back(temp);\n      }\n      return permutations;\n    }\n    else if (tupel.size() == (Size)number_of_phospho_sites)\n    {\n      vector<vector<Size> > permutations;\n      permutations.push_back(tupel);\n      return permutations;\n    }\n    else\n    {\n      vector<vector<Size> > permutations;\n      vector<Size> head;\n      vector<vector<Size> > tail;\n      head.push_back(tupel[0]);\n      vector<Size> tupel_left(++tupel.begin(), tupel.end());\n      Int tail_phospho_sites = number_of_phospho_sites - 1;\n      tail = computePermutations_(tupel_left, tail_phospho_sites);\n      for (vector<vector<Size> >::iterator it = tail.begin(); it < tail.end(); ++it)\n      {\n        vector<Size> temp(head);\n        temp.insert(temp.end(), it->begin(), it->end());\n        permutations.push_back(temp);\n      }\n      vector<vector<Size> > other_possibilities(computePermutations_(tupel_left, number_of_phospho_sites));\n      permutations.insert(permutations.end(), other_possibilities.begin(), other_possibilities.end());\n      return permutations;\n    }\n  }\n\n} // namespace OpenMS\n", "meta": {"hexsha": "1bff9b37154f13d24683d1aebcdf4f4a05ba7ec5", "size": 20753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/ANALYSIS/ID/AScore.cpp", "max_stars_repo_name": "liangoaix/OpenMS", "max_stars_repo_head_hexsha": "cccbc5d872320f197091596db275f35b4d0458cd", "max_stars_repo_licenses": ["Zlib", "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/openms/source/ANALYSIS/ID/AScore.cpp", "max_issues_repo_name": "liangoaix/OpenMS", "max_issues_repo_head_hexsha": "cccbc5d872320f197091596db275f35b4d0458cd", "max_issues_repo_licenses": ["Zlib", "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/openms/source/ANALYSIS/ID/AScore.cpp", "max_forks_repo_name": "liangoaix/OpenMS", "max_forks_repo_head_hexsha": "cccbc5d872320f197091596db275f35b4d0458cd", "max_forks_repo_licenses": ["Zlib", "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.6921568627, "max_line_length": 180, "alphanum_fraction": 0.6320531971, "num_tokens": 5338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.1764345339234729}}
{"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_PACK_NUMERIC_HPP\n#define CRYPTO3_PACK_NUMERIC_HPP\n\n#include <boost/assert.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace detail {\n            using namespace boost::multiprecision;\n\n            template<typename Endianness, int InValueBits, int OutValueBits, typename InputIterator, typename Backend,\n                     expression_template_option ExpressionTemplates>\n            inline void pack(InputIterator first, InputIterator last, number<Backend, ExpressionTemplates> &out) {\n                import_bits(out, first, last);\n                BOOST_ASSERT(msb(out) == OutValueBits);\n            }\n\n            template<typename Endianness, int OutValueBits, typename InputType, typename Backend,\n                     expression_template_option ExpressionTemplates>\n            inline void pack(const InputType &in, number<Backend, ExpressionTemplates> &out) {\n                import_bits(out, in.begin(), in.end());\n                BOOST_ASSERT(msb(out) == OutValueBits);\n            }\n\n            template<typename Endianness, int OutValueBits, typename OutputType, typename Backend,\n                     expression_template_option ExpressionTemplates>\n            inline void pack(const number<Backend, ExpressionTemplates> &in, OutputType &out) {\n                export_bits(in, out);\n                BOOST_ASSERT(msb(out) == OutValueBits);\n            }\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_BLOCK_PACK_HPP\n", "meta": {"hexsha": "25dcb7dc6132b70ac531ef0f8654b01296d09456", "size": 1989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/detail/pack_numeric.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/pack_numeric.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/pack_numeric.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": 42.3191489362, "max_line_length": 118, "alphanum_fraction": 0.6058320764, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.1764345339234729}}
{"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\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: OptimizeLinkage_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        (\"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\n// Sum the values appearing on periodically-identified vertices.\n// First sum onto the reduced DoFs, then redistribute.\ntemplate<class Sim, class VField>\nVField sumIdentifiedValues(const Sim &sim, VField v) {\n    const auto &mesh = sim.mesh();\n    if (v.domainSize() != mesh.numNodes())\n        throw std::runtime_error(\"Expected per-node vector field\");\n\n    VField dofField(sim.numDoFs());\n    dofField.clear();\n    for (size_t i = 0; i < mesh.numNodes(); ++i)\n        dofField(sim.DoF(i)) +=  v(i);\n    for (size_t i = 0; i < mesh.numNodes(); ++i)\n        v(i) = dofField(sim.DoF(i));\n\n    return v;\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    ETensor Eh;\n    for (size_t it = 0; it < 20; ++it) {\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            cout << systems.size() << endl;\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        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        // Make all eigenstrains positive\n        if (eigs.strains(0, 0) < 0) eigs.strains.col(0) *= -1;\n        if (eigs.strains(0, 1) < 0) eigs.strains.col(1) *= -1;\n        if (eigs.strains(0, 2) < 0) eigs.strains.col(2) *= -1;\n\n        cout << \"Minimum Eh eigenvalue \" << eigs.lambdas[0] << \" for eigenstrain: \"\n             << eigs.strains.col(0).transpose() << endl;\n\n        SymmetricMatrixValue<Real, _N> minEigenstrain(eigs.strains.col(0));\n        SymmetricMatrixValue<Real, _N> midEigenstrain(eigs.strains.col(1));\n        SymmetricMatrixValue<Real, _N> maxEigenstrain(eigs.strains.col(2));\n\n        ETensor Eh_pinv = Eh.pseudoinverse();\n        // cout << \"Eh : Eh_pinv: \" << endl << Eh.doubleContract(Eh_pinv) << endl << endl;\n        // cout << \"Eh : Eh_pinv : Eh \" << endl << Eh.doubleContract(Eh_pinv).doubleContract(Eh) << endl << endl;\n\n        // Compute discrete shape derivative of minimum eigenvalue and\n        // one of the eigenstrain components\n        // (to steer away from the uniform expansion mode).\n        auto dEh = homogenizedElasticityTensorDiscreteDifferential(w_ij, sim);\n        // Work with vector fields instead of OneForms; we probably can't compute a\n        // proper Riesz representative on non-manifold meshes anyway, so don't\n        // worry about distinction between one-forms and vector fields.\n        VField dMinEigenvalue = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return minEigenstrain.doubleContract(E.doubleContract(minEigenstrain)); }, dEh).asVectorField());\n        VField dMidEigenvalue = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return midEigenstrain.doubleContract(E.doubleContract(midEigenstrain)); }, dEh).asVectorField());\n        VField dMaxEigenvalue = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return maxEigenstrain.doubleContract(E.doubleContract(maxEigenstrain)); }, dEh).asVectorField());\n\n        VField dMinEigenstrainC0 = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return -Eh_pinv.doubleContract(E.doubleContract(minEigenstrain))(0, 0); }, dEh).asVectorField());\n        VField dMinEigenstrainC1 = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return -Eh_pinv.doubleContract(E.doubleContract(minEigenstrain))(1, 1); }, dEh).asVectorField());\n        VField dMinEigenstrainC2 = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return -Eh_pinv.doubleContract(E.doubleContract(minEigenstrain))(0, 1); }, dEh).asVectorField());\n\n        bool linearSubsampleFields = args.count(\"fullDegreeFieldOutput\") == 0;\n        MSHFieldWriter writer(\"vertical_linkage_it\" + std::to_string(it) + \".msh\", sim.mesh(), linearSubsampleFields);\n        writer.addField(\"dE00\", sumIdentifiedValues(sim, compose([&](const ETensor &E) { return E.D(0,0); }, dEh).asVectorField()), DomainType::PER_NODE);\n        writer.addField(\"dE01\", sumIdentifiedValues(sim, compose([&](const ETensor &E) { return E.D(0,1); }, dEh).asVectorField()), DomainType::PER_NODE);\n        writer.addField(\"dE11\", sumIdentifiedValues(sim, compose([&](const ETensor &E) { return E.D(1,1); }, dEh).asVectorField()), DomainType::PER_NODE);\n        writer.addField(\"dE22\", sumIdentifiedValues(sim, compose([&](const ETensor &E) { return E.D(2,2); }, dEh).asVectorField()), DomainType::PER_NODE);\n\n        writer.addField(\"dMinEigenvalue\", dMinEigenvalue, DomainType::PER_NODE);\n        writer.addField(\"dMidEigenvalue\", dMidEigenvalue, DomainType::PER_NODE);\n        writer.addField(\"dMaxEigenvalue\", dMaxEigenvalue, DomainType::PER_NODE);\n\n        writer.addField(\"dMinEigenstrainC0\", dMinEigenstrainC0, DomainType::PER_NODE);\n        writer.addField(\"dMinEigenstrainC1\", dMinEigenstrainC1, DomainType::PER_NODE);\n        writer.addField(\"dMinEigenstrainC2\", dMinEigenstrainC2, DomainType::PER_NODE);\n\n        VField descentStep = dMinEigenstrainC1;\n        descentStep.maxColumnNormalize();\n        descentStep *= 0.01;\n        std::vector<MeshIO::IOVertex> pts(sim.mesh().numVertices());\n        for (auto v : sim.mesh().vertices()) {\n            pts[v.index()] = v.node()->p;\n            pts[v.index()].point += padTo3D(PointND<_N>(descentStep(v.index())));\n        }\n        sim.updateMeshNodePositions(pts);\n    }\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(\"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": "a921b749f3764b26f0f2574f7374116b5e9a717e", "size": 15753, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bin/mechanisms/OptimizeLinkage.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/mechanisms/OptimizeLinkage.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/mechanisms/OptimizeLinkage.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": 48.0274390244, "max_line_length": 189, "alphanum_fraction": 0.6025518949, "num_tokens": 4190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.1763246503535193}}
{"text": "#pragma once\n\n#include <memory>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#define _USE_MATH_DEFINES\n#include <cmath>\n\n#include \"math/IWorldAdapter.hpp\"\n#include \"math/IMatrixFactory.hpp\"\n#include \"math/IVectorFactory.hpp\"\n\nnamespace northstar {\n    namespace math {\n        class CWorldAdapter : public IWorldAdapter {\n        public:\n            CWorldAdapter(\n                std::shared_ptr<IMatrixFactory> pMatrixFactory,\n                std::shared_ptr<IVectorFactory> pVectorFactory);\n\n            virtual types::SPose FromStructureSensorPoseToOpenVRSpace(const ST::XRPose& Pose) override final;\n            virtual types::Vector3d FromStructureSensorLinearVectorArrayToOpenVRSpace(const std::array<double, 3>& Vector) override final;\n            virtual types::Vector3d FromStructureSensorAngularVectorArrayToOpenVRSpace(const std::array<double, 3>& Vector) override final;\n            virtual types::AffineMatrix4d ConversionMatrixFromLeapMotionTrackingSpaceToHMDRelativeSpace(const types::Vector3d& v3dHeadRelativeLeapPosition, const types::Quaterniond& qdHeadRelativeLeapOrientation) override final;\n            virtual types::AffineMatrix4d ConversionMatrixFromHMDSpaceToOpenVRWorldSpace(const vr::DriverPose_t& sOVRPose) override final;\n            virtual types::Vector3d FromLeapMotionVelocityToOpenVRVelocity(const types::AffineMatrix4d& m4dConversionMatrix, const types::Vector3d& v3dLeapVelocity) override final;\n            virtual types::Quaterniond FromUnityQuaternionToOpenVRQuaternion(const types::Quaterniond& qdUnityRotation) override final;\n            virtual types::Vector3d FromUnityPositionToOpenVRPosition(const types::Vector3d& v3dUnityPosition) override final;\n            virtual types::Vector4d FromUnityProjectionExtentsLRTBToOpenVRProjectionExtentsLRTB(const types::Vector4d& v4dUnityProjectionExtentsLRTB) override final;\n            virtual types::AffineMatrix4d FromUnityMatrix4dToOpenVRMatrix4d(const types::AffineMatrix4d& v4dUnityPose) override final;\n            virtual types::Vector2d FromOpenGLUVToUnityUV(const types::Vector2d& v2dOpenGLUV) override final;\n            virtual types::Vector2d FromUnityUVToOpenGLUV(const types::Vector2d& v2dUnityUV) override final;\n\n        private:\n            static constexpr double x_dMillimetersToMeters = 0.001;\n            std::shared_ptr<IMatrixFactory> m_pMatrixFactory;\n            std::shared_ptr<IVectorFactory> m_pVectorFactory;\n        };\n    }\n}", "meta": {"hexsha": "9b08b98cef8bb8c8b4ded456797694038cab1bc4", "size": 2449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "northstar/include/math/WorldAdapter.hpp", "max_stars_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_stars_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "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": "northstar/include/math/WorldAdapter.hpp", "max_issues_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_issues_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "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": "northstar/include/math/WorldAdapter.hpp", "max_forks_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_forks_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "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": 59.7317073171, "max_line_length": 228, "alphanum_fraction": 0.7603103307, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.17625796578106162}}
{"text": "#include \"decoder.h\"\n#include <fstream>\n#include <iostream>\n#include <boost/timer/timer.hpp>\n\n// Mainly for profiling purposes\n\nint main(int argc, char** argv)\n{\n    int N = 32;\n    int T = 648;\n    double data[N*T];\n\n    std::ifstream is(\"probs.dat\", std::ios::binary);\n    is.read(reinterpret_cast<char*>(data), is.tellg());\n    is.close();\n\n    // TODO FIXME PARAM Import\n    std::string CHARMAP_PATH = \"/scail/group/deeplearning/speech/zxie/kaldi-stanford/kaldi-trunk/egs/wsj/s6/ctc-utils\";\n    PrefixTree ptree(CHARMAP_PATH + \"/chars.txt\",\n                     CHARMAP_PATH + \"/wordlist\",\n                     CHARMAP_PATH + \"/lm_bg.arpa\");\n\n    // Decode!\n    PrefixKey best_prefix;\n    int beam = 40;\n    double alpha = 1.0;\n    double beta = 0.0;\n    boost::timer::cpu_timer timer;\n    double best_score = decode_bg_lm(data, N, T, ptree, beam, alpha, beta, best_prefix);\n    boost::timer::cpu_times elapsed = timer.elapsed();\n    std::cout << \"decoding time (wall): \" << elapsed.wall / 1e9 << std::endl;\n\n    for (int k = 0; k < best_prefix.size(); k++)\n    {\n        std::cout << best_prefix[k] << \" \";\n    }\n    std::cout << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "eb1f9793da23f23b248ed57f739d2a21db1ed9ec", "size": 1163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ctc_fast/decoder/fastdecode/test_decode.cpp", "max_stars_repo_name": "SrikarSiddarth/stanford-ctc", "max_stars_repo_head_hexsha": "c8f8257227ec218c4794a96a089ef0a093dcbdfd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 268.0, "max_stars_repo_stars_event_min_datetime": "2015-06-15T20:59:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T15:05:50.000Z", "max_issues_repo_path": "ctc_fast/decoder/fastdecode/test_decode.cpp", "max_issues_repo_name": "guker/stanford-ctc", "max_issues_repo_head_hexsha": "3d3bd9ce92cfdc0173b1bd2096ecea8634d6b62f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T03:22:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-11T15:58:57.000Z", "max_forks_repo_path": "ctc_fast/decoder/fastdecode/test_decode.cpp", "max_forks_repo_name": "guker/stanford-ctc", "max_forks_repo_head_hexsha": "3d3bd9ce92cfdc0173b1bd2096ecea8634d6b62f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 109.0, "max_forks_repo_forks_event_min_datetime": "2015-07-07T15:36:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T03:48:15.000Z", "avg_line_length": 27.6904761905, "max_line_length": 119, "alphanum_fraction": 0.6027515047, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.17612674302886622}}
{"text": "/*********************************************************************\n *\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2015, Daichi Yoshikawa\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 Daichi Yoshikawa 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 * Author: Daichi Yoshikawa\n *\n *********************************************************************/\n\n#ifndef __AHL_ROBOT_CONTROLLER_PARAM_HPP\n#define __AHL_ROBOT_CONTROLLER_PARAM_HPP\n\n#include <memory>\n#include <mutex>\n#include <Eigen/Dense>\n#include <dynamic_reconfigure/server.h>\n#include <ahl_robot/robot/robot.hpp>\n#include <ahl_utils/scoped_lock.hpp>\n#include \"ahl_robot_controller/param_base.hpp\"\n#include \"ahl_robot_controller/ParamConfig.h\"\n\nnamespace ahl_ctrl\n{\n\n  class Param : public ParamBase\n  {\n  public:\n    explicit Param(const ahl_robot::RobotPtr& robot);\n\n    virtual const Eigen::MatrixXd& getKpJoint() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return Kp_joint_;\n    }\n\n    virtual const Eigen::MatrixXd& getKvJoint() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return Kv_joint_;\n    }\n\n    virtual const Eigen::MatrixXd& getKpTask() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return Kp_task_;\n    }\n\n    virtual const Eigen::MatrixXd& getKiTask() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return Ki_task_;\n    }\n\n    virtual const Eigen::MatrixXd& getKvTask() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return Kv_task_;\n    }\n\n    virtual const Eigen::Vector3d& getIClippingTaskPos() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return i_clipping_task_pos_;\n    }\n\n    virtual const Eigen::Vector3d& getIClippingTaskOri() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return i_clipping_task_ori_;\n    }\n\n    virtual const Eigen::MatrixXd& getKvDamp() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return Kv_damp_;\n    }\n\n    virtual const Eigen::MatrixXd& getKpLimit() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return Kp_limit_;\n    }\n\n    virtual const Eigen::MatrixXd& getKvLimit() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return Kv_limit_;\n    }\n\n    virtual double getJointErrorMax() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return joint_error_max_;\n    }\n\n    virtual double getPosErrorMax() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return pos_error_max_;\n    }\n\n    virtual double getOriErrorMax() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return ori_error_max_;\n    }\n\n    virtual double getDqMax() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return dq_max_;\n    }\n\n    virtual double getVxMax() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return vx_max_;\n    }\n\n    virtual const Eigen::Vector3d& getG() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return g_;\n    }\n\n    virtual const Eigen::MatrixXd& getB() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return b_;\n    }\n\n    virtual double getKpWheel() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return kp_wheel_;\n    }\n\n    virtual double getKvWheel() override\n    {\n      ahl_utils::ScopedLock lock(mutex_);\n      return kv_wheel_;\n    }\n\n  private:\n    void update(ahl_robot_controller::ParamConfig& config, uint32_t level);\n    using ParamConfigServer = dynamic_reconfigure::Server<ahl_robot_controller::ParamConfig>;\n    using ParamConfigServerPtr = std::shared_ptr<ParamConfigServer>;\n\n    std::mutex mutex_;\n\n    ParamConfigServerPtr server_;\n    dynamic_reconfigure::Server<ahl_robot_controller::ParamConfig>::CallbackType f_;\n\n    uint32_t dof_;\n    uint32_t macro_dof_;\n\n    Eigen::MatrixXd Kp_joint_;\n    Eigen::MatrixXd Kv_joint_;\n    Eigen::MatrixXd Kp_task_;\n    Eigen::MatrixXd Ki_task_;\n    Eigen::MatrixXd Kv_task_;\n    Eigen::Vector3d i_clipping_task_pos_;\n    Eigen::Vector3d i_clipping_task_ori_;\n    Eigen::MatrixXd Kv_damp_;\n    Eigen::MatrixXd Kp_limit_;\n    Eigen::MatrixXd Kv_limit_;\n    double joint_error_max_;\n    double pos_error_max_;\n    double ori_error_max_;\n    double dq_max_;\n    double vx_max_;\n    double kp_wheel_;\n    double kv_wheel_;\n    Eigen::Vector3d g_;\n    Eigen::MatrixXd b_;\n  };\n\n  using ParamPtr = std::shared_ptr<Param>;\n\n} // namespace ahl_ctrl\n\n#endif // __AHL_ROBOT_CONTROLLER_PARAM_HPP\n", "meta": {"hexsha": "4eb79a02f2bd979b87986b5d9ee0f119d3fd94c1", "size": 5915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wbc/ahl_robot_controller/include/ahl_robot_controller/param.hpp", "max_stars_repo_name": "daichi-yoshikawa/ahl_wbc", "max_stars_repo_head_hexsha": "ea241562e521c7509d3b0405393996998f7cdc6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-12-16T15:32:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T05:09:40.000Z", "max_issues_repo_path": "wbc/ahl_robot_controller/include/ahl_robot_controller/param.hpp", "max_issues_repo_name": "daichi-yoshikawa/ahl_wbc", "max_issues_repo_head_hexsha": "ea241562e521c7509d3b0405393996998f7cdc6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-06-08T09:53:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T11:27:23.000Z", "max_forks_repo_path": "wbc/ahl_robot_controller/include/ahl_robot_controller/param.hpp", "max_forks_repo_name": "daichi-yoshikawa/ahl_wbc", "max_forks_repo_head_hexsha": "ea241562e521c7509d3b0405393996998f7cdc6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T10:30:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T05:08:27.000Z", "avg_line_length": 27.9009433962, "max_line_length": 93, "alphanum_fraction": 0.6853761623, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.17601549675638542}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2009-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NGT platform is licensed under the Apache License, Version 2.0 (the\n//  \"License\"); you may not use this file except in compliance with the\n//  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/// \\file StereoSessionIsis.cc\n///\n\n// Vision Workbench\n#include <vw/Core/Settings.h>\n#include <vw/Core/Log.h>\n#include <vw/Math/Functors.h>\n#include <vw/Image/Algorithms.h>\n#include <vw/Image/EdgeExtension.h>\n#include <vw/Image/ImageViewRef.h>\n#include <vw/Image/Manipulation.h>\n#include <vw/Image/ImageMath.h>\n#include <vw/Image/MaskViews.h>\n#include <vw/Image/Statistics.h>\n#include <vw/Image/Transform.h>\n#include <vw/FileIO/DiskImageView.h>\n#include <vw/FileIO/DiskImageResourceGDAL.h>\n#include <vw/FileIO/DiskImageResourceOpenEXR.h>\n#include <vw/Camera/CameraModel.h>\n#include <vw/Stereo/DisparityMap.h>\n#include <vw/InterestPoint/Descriptor.h>\n#include <vw/InterestPoint/Detector.h>\n#include <vw/InterestPoint/Matcher.h>\n#include <vw/InterestPoint/MatrixIO.h>\n#include <vw/Cartography/Datum.h>\n\n// Stereo Pipeline\n#include <asp/Core/InterestPointMatching.h>\n#include <asp/Core/AffineEpipolar.h>\n#include <asp/Core/PhotometricOutlier.h>\n#include <asp/Sessions/StereoSessionIsis.h>\n#include <asp/IsisIO/IsisCameraModel.h>\n#include <asp/IsisIO/DiskImageResourceIsis.h>\n#include <asp/IsisIO/Equation.h>\n\n// Boost\n#include <boost/filesystem/operations.hpp>\n#include <boost/math/special_functions/next.hpp> // boost::float_next\n#include <boost/shared_ptr.hpp>\nnamespace fs = boost::filesystem;\n\n#include <algorithm>\n\nusing namespace vw;\nusing namespace vw::camera;\nusing namespace asp;\n\n#if defined(ASP_HAVE_PKG_ISISIO) && ASP_HAVE_PKG_ISISIO == 1\n\n// Allows FileIO to correctly read/write these pixel types\nnamespace vw {\n  template<> struct PixelFormatID<Vector3>   { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };\n}\n\n#endif  // ASP_HAVE_PKG_ISISIO\n*/\n", "meta": {"hexsha": "2a86f94dd7596262500aa620f1624c621ca90b25", "size": 2473, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/Sessions/StereoSessionIsis.cc", "max_stars_repo_name": "AndrewAnnex/StereoPipeline", "max_stars_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 323.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T12:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:52:22.000Z", "max_issues_repo_path": "src/asp/Sessions/StereoSessionIsis.cc", "max_issues_repo_name": "AndrewAnnex/StereoPipeline", "max_issues_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 252.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T16:36:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:34:28.000Z", "max_forks_repo_path": "src/asp/Sessions/StereoSessionIsis.cc", "max_forks_repo_name": "AndrewAnnex/StereoPipeline", "max_forks_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 105.0, "max_forks_repo_forks_event_min_datetime": "2015-02-28T02:37:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T09:17:30.000Z", "avg_line_length": 32.9733333333, "max_line_length": 114, "alphanum_fraction": 0.7658714112, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17601549321154702}}
{"text": "/***************************************************************************\n *   Copyright (C) Preparatory Commission for the Comprehensive            *\n *   Nuclear-Test-Ban Treaty Organization (CTBTO).                         *\n *                                                                         *\n *   You can redistribute and/or modify this program under the             *\n *   terms of the SeisComP Public License.                                 *\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 *   SeisComP Public License for more details.                             *\n ***************************************************************************/\n\n\n#define SEISCOMP_COMPONENT Magnitudes/ML_idc\n\n#include \"ML_idc_private.h\"\n\n#include <seiscomp3/logging/log.h>\n#include <seiscomp3/system/environment.h>\n\n#include <boost/thread/mutex.hpp>\n\n#include <cmath> // log10\n#include <vector> // log10\n#include <cfloat>\n#include <fstream>\n\n\n#define AMP_TYPE \"SBSNR\"\n#define MAG_TYPE \"ML(IDC)\"\n\n#define MINIMUM_DISTANCE 0.0   // in degrees\n#define MAXIMUM_DISTANCE 20.0  // in degrees\n\n#define MAXIMUM_DEPTH    40.0  // in km\n\n\nusing namespace std;\n\n\nnamespace {\n\n\nstd::string ExpectedAmplitudeUnit = \"nm\";\n\nUtil::TabValues tableA;\nbool validTableA = false;\nbool readTableA = false;\nboost::mutex mutexTableA;\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nMagnitude_ML_idc::Magnitude_ML_idc()\n: MagnitudeProcessor(MAG_TYPE) {}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nstd::string Magnitude_ML_idc::amplitudeType() const {\n\treturn AMP_TYPE;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nbool Magnitude_ML_idc::setup(const Settings &settings) {\n\t_attenuation.reset();\n\n\tif ( !MagnitudeProcessor::setup(settings) )\n\t\treturn false;\n\n\ttry {\n\t\tstring tablePath = Environment::Instance()->absolutePath(settings.getString(\"magnitudes.ML(IDC).A\"));\n\t\tsize_t p;\n\n\t\tp = tablePath.find(\"{net}\");\n\t\tif ( p != string::npos ) {\n\t\t\ttablePath.replace(p, 5, settings.networkCode);\n\t\t}\n\n\t\tp = tablePath.find(\"{sta}\");\n\t\tif ( p != string::npos ) {\n\t\t\ttablePath.replace(p, 5, settings.stationCode);\n\t\t}\n\n\t\tp = tablePath.find(\"{loc}\");\n\t\tif ( p != string::npos ) {\n\t\t\ttablePath.replace(p, 5, settings.locationCode);\n\t\t}\n\n\t\tSEISCOMP_DEBUG(\"Read station specific ML(IDC) attentuation table at %s\",\n\t\t               tablePath.c_str());\n\n\t\t_attenuation = new Util::TabValues;\n\t\tbool validLocalTable = _attenuation->read(tablePath);\n\t\tif ( !validLocalTable ) {\n\t\t\t_attenuation.reset();\n\t\t\tSEISCOMP_ERROR(\"Failed to read A values from: %s\", tablePath.c_str());\n\t\t\treturn false;\n\t\t}\n\t}\n\tcatch ( ... ) {}\n\n\tif ( !_attenuation ) {\n\t\tmutexTableA.lock();\n\n\t\tif ( !readTableA ) {\n\t\t\tstring tablePath = Environment::Instance()->absolutePath(\"@DATADIR@/magnitudes/IDC/global.ml\");\n\t\t\tSEISCOMP_DEBUG(\"Read global ML(IDC) attentuation table at %s\",\n\t\t\t               tablePath.c_str());\n\n\t\t\tvalidTableA = tableA.read(tablePath);\n\t\t\tif ( !validTableA ) {\n\t\t\t\tSEISCOMP_ERROR(\"Failed to read A values from: %s\", tablePath.c_str());\n\t\t\t}\n\n\t\t\treadTableA = true;\n\t\t}\n\t\telse if ( !validTableA ) {\n\t\t\tSEISCOMP_ERROR(\"Invalid A value table\");\n\t\t}\n\n\t\tmutexTableA.unlock();\n\t\treturn validTableA;\n\t}\n\n\treturn true;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nMagnitudeProcessor::Status\nMagnitude_ML_idc::computeMagnitude(double amplitude,\n                                   const std::string &unit,\n                                   double period, double,\n                                   double delta, double depth,\n                                   const DataModel::Origin *,\n                                   const DataModel::SensorLocation *,\n                                   const DataModel::Amplitude *,\n                                   double &value) {\n\tif ( !_attenuation && !validTableA )\n\t\treturn IncompleteConfiguration;\n\n\tif ( (delta < MINIMUM_DISTANCE) || (delta > MAXIMUM_DISTANCE) )\n\t\treturn DistanceOutOfRange;\n\n\tif ( depth > MAXIMUM_DEPTH )\n\t\treturn DepthOutOfRange;\n\n\tif ( !convertAmplitude(amplitude, unit, ExpectedAmplitudeUnit) )\n\t\treturn InvalidAmplitudeUnit;\n\n\tdouble x_1st_deriv, z_1st_deriv, x_2nd_deriv, z_2nd_deriv;\n\tdouble interpolated_value;\n\tint interp_err;\n\tbool ok;\n\n\tif ( _attenuation ) {\n\t\tok = _attenuation->interpolate(interpolated_value, false, true,\n\t\t                               delta, 0, &x_1st_deriv, &z_1st_deriv,\n\t\t                               &x_2nd_deriv, &z_2nd_deriv, &interp_err);\n\t}\n\telse {\n\t\tmutexTableA.lock();\n\t\tok = tableA.interpolate(interpolated_value, false, true,\n\t\t                        delta, 0, &x_1st_deriv, &z_1st_deriv,\n\t\t                        &x_2nd_deriv, &z_2nd_deriv, &interp_err);\n\t\tmutexTableA.unlock();\n\t}\n\n\tif ( !ok ) {\n\t\tSEISCOMP_ERROR(\"Failed to interpolate attentuation value\");\n\t\treturn Error;\n\t}\n\n\tif ( interp_err ) {\n\t\tSEISCOMP_ERROR(\"Error on attentuation interpolation: %d\", interp_err);\n\t\treturn Error;\n\t}\n\n\tvalue = correctMagnitude(log10(amplitude) + double(interpolated_value));\n\n\treturn OK;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nREGISTER_MAGNITUDEPROCESSOR(Magnitude_ML_idc, MAG_TYPE);\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>}\n}\n", "meta": {"hexsha": "7924d8d21fda0ca20dc618de48212db6e5ce9adf", "size": 6055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trunk/libs/seiscomp3/processing/magnitudes/ML_idc.cpp", "max_stars_repo_name": "kbouk/seiscomp3", "max_stars_repo_head_hexsha": "2385e4197274135c70aaef93a0b7df65ed8fa6a6", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T13:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T15:10:06.000Z", "max_issues_repo_path": "src/trunk/libs/seiscomp3/processing/magnitudes/ML_idc.cpp", "max_issues_repo_name": "kbouk/seiscomp3", "max_issues_repo_head_hexsha": "2385e4197274135c70aaef93a0b7df65ed8fa6a6", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": 233.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T15:16:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T11:31:37.000Z", "max_forks_repo_path": "src/trunk/libs/seiscomp3/processing/magnitudes/ML_idc.cpp", "max_forks_repo_name": "kbouk/seiscomp3", "max_forks_repo_head_hexsha": "2385e4197274135c70aaef93a0b7df65ed8fa6a6", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": 95.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T15:53:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T14:54:54.000Z", "avg_line_length": 28.8333333333, "max_line_length": 103, "alphanum_fraction": 0.5035507845, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.17596657802596138}}
{"text": "//-*- mode: c++; indent-tabs-mode: nil; tab-width: 2 -*-\n\n#include \"ug_bitext.h\"\n#include <algorithm>\n#include <boost/math/distributions/binomial.hpp>\n\nnamespace sapt\n{\n\n  float\n  lbop(size_t const tries, size_t const succ, float const confidence)\n  {\n    return (confidence == 0\n            ? float(succ)/tries\n            : (boost::math::binomial_distribution<>::\n               find_lower_bound_on_p(tries, succ, confidence)));\n  }\n\n  void\n  snt_adder<L2R_Token<SimpleWordId> >::\n  operator()()\n  {\n    typedef L2R_Token<SimpleWordId> tkn;\n    std::vector<id_type> sids; sids.reserve(snt.size());\n    BOOST_FOREACH(std::string const& foo, snt)\n      {\n        sids.push_back(track ? track->size() : 0);\n        std::istringstream buf(foo);\n        std::string w;\n        std::vector<tkn> s; s.reserve(100);\n        while (buf >> w) s.push_back(tkn(V[w]));\n        track = append(track,s);\n      }\n    if (index)\n      index.reset(new imTSA<tkn>(*index,track,sids,V.tsize()));\n    else\n      index.reset(new imTSA<tkn>(track,NULL,NULL));\n  }\n  \n  snt_adder<L2R_Token<SimpleWordId> >::\n  snt_adder(std::vector<std::string> const& s, TokenIndex& v,\n            SPTR<imTtrack<L2R_Token<SimpleWordId> > >& t,\n            SPTR<imTSA<L2R_Token<SimpleWordId> > >& i)\n    : snt(s), V(v), track(t), index(i)\n  { }\n  \n  bool\n  expand_phrase_pair\n  (std::vector<std::vector<ushort> >& a1,\n   std::vector<std::vector<ushort> >& a2,\n   ushort const s2, // next word on in target side\n   ushort const L1, ushort const R1, // limits of previous phrase\n   ushort & s1, ushort & e1, ushort& e2) // start/end src; end trg\n  {\n    if (a2[s2].size() == 0)\n      {\n        std::cout << __FILE__ << \":\" << __LINE__ << std::endl;\n        return false;\n      }\n    bitvector done1(a1.size());\n    bitvector done2(a2.size());\n    std::vector<std::pair<ushort,ushort> > agenda;\n    // x.first:  side (1 or 2)\n    // x.second: word position\n    agenda.reserve(a1.size() + a2.size());\n    agenda.push_back(std::pair<ushort,ushort>(2,s2));\n    e2 = s2;\n    s1 = e1 = a2[s2].front();\n    if (s1 >= L1 && s1 < R1)\n      {\n        std::cout << __FILE__ << \":\" << __LINE__ << std::endl;\n        return false;\n      }\n    agenda.push_back(std::pair<ushort,ushort>(2,s2));\n    while (agenda.size())\n      {\n        ushort side = agenda.back().first;\n        ushort p    = agenda.back().second;\n        agenda.pop_back();\n        if (side == 1)\n          {\n            done1.set(p);\n            BOOST_FOREACH(ushort i, a1[p])\n              {\n                if (i < s2)\n                  {\n                    // cout << __FILE__ << \":\" << __LINE__ << endl;\n                    return false;\n                  }\n                if (done2[i]) continue;\n                for (;e2 <= i;++e2)\n                  if (!done2[e2])\n                    agenda.push_back(std::pair<ushort,ushort>(2,e2));\n              }\n          }\n        else\n          {\n            done2.set(p);\n            BOOST_FOREACH(ushort i, a2[p])\n              {\n                if ((e1 < L1 && i >= L1) ||\n                    (s1 >= R1 && i < R1) ||\n                    (i >= L1 && i < R1))\n                  {\n                    // cout << __FILE__ << \":\" << __LINE__ << \" \"\n                    // << L1 << \"-\" << R1 << \" \" << i << \" \"\n                    // << s1 << \"-\" << e1<< endl;\n                    return false;\n                  }\n          \n                if (e1 < i)\n                  {\n                    for (; e1 <= i; ++e1)\n                      if (!done1[e1])\n                        agenda.push_back(std::pair<ushort,ushort>(1,e1));\n                  }\n                else if (s1 > i)\n                  {\n                    for (; i <= s1; ++i)\n                      if (!done1[i])\n                        agenda.push_back(std::pair<ushort,ushort>(1,i));\n                  }\n              }\n          }\n      }\n    ++e1;\n    ++e2;\n    return true;\n  }\n  \n  void\n  print_amatrix(std::vector<std::vector<ushort> > a1, uint32_t len2,\n                ushort b1, ushort e1, ushort b2, ushort e2)\n  {\n    using namespace std;\n    std::vector<bitvector> M(a1.size(),bitvector(len2));\n    for (ushort j = 0; j < a1.size(); ++j)\n      {\n        BOOST_FOREACH(ushort k, a1[j])\n          M[j].set(k);\n      }\n    cout << b1 << \"-\" << e1 << \" \" << b2 << \"-\" << e2 << endl;\n    cout << \"   \";\n    for (size_t c = 0; c < len2;++c)\n      cout << c%10;\n    cout << endl;\n    for (size_t r = 0; r < M.size(); ++r)\n      {\n        cout << setw(3) << r << \" \";\n        for (size_t c = 0; c < M[r].size(); ++c)\n          {\n            if ((b1 <= r) && (r < e1) && b2 <= c && c < e2)\n              cout << (M[r][c] ? 'x' : '-');\n            else cout << (M[r][c] ? 'o' : '.');\n          }\n        cout << endl;\n      }\n    cout  << std::string(90,'-') << endl;\n  }\n  \n  void\n  write_bitvector(bitvector const& v, std::ostream& out)\n  {\n    for (size_t i = v.find_first(); i < v.size();)\n      {\n        out << i;\n        if ((i = v.find_next(i)) < v.size()) out << \",\";\n      }\n  }\n  \n}\n", "meta": {"hexsha": "0857cc21f49918d6e2ff0ac7a192f22bdabb03a7", "size": 5024, "ext": "cc", "lang": "C++", "max_stars_repo_path": "model/mosesdecoder/moses/TranslationModel/UG/mm/ug_bitext.cc", "max_stars_repo_name": "saeedesm/UNMT_AH", "max_stars_repo_head_hexsha": "cc171bf66933b5c0ad8a0ab87e57f7364312a7df", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-28T21:42:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T13:56:16.000Z", "max_issues_repo_path": "tools/mosesdecoder-master/moses/TranslationModel/UG/mm/ug_bitext.cc", "max_issues_repo_name": "Pangeamt/nectm", "max_issues_repo_head_hexsha": "6b84f048698f2530b9fdbb30695f2e2217c3fbfe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-06T14:40:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T19:03:11.000Z", "max_forks_repo_path": "tools/mosesdecoder-master/moses/TranslationModel/UG/mm/ug_bitext.cc", "max_forks_repo_name": "Pangeamt/nectm", "max_forks_repo_head_hexsha": "6b84f048698f2530b9fdbb30695f2e2217c3fbfe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-26T05:27:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-17T01:53:43.000Z", "avg_line_length": 29.2093023256, "max_line_length": 73, "alphanum_fraction": 0.4428742038, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17589390939999788}}
{"text": "#include \"CommonTools/Utils/interface/DynArray.h\"\n#include \"DataFormats/ParticleFlowReco/interface/PFRecHit.h\"\n#include \"DataFormats/ParticleFlowReco/interface/PFRecHitFwd.h\"\n#include \"FWCore/Framework/interface/ConsumesCollector.h\"\n#include \"FWCore/MessageLogger/interface/MessageLogger.h\"\n#include \"FWCore/Utilities/interface/isFinite.h\"\n#include \"RecoParticleFlow/PFClusterProducer/interface/CaloRecHitResolutionProvider.h\"\n#include \"RecoParticleFlow/PFClusterProducer/interface/PFCPositionCalculatorBase.h\"\n\n#include \"vdt/vdtMath.h\"\n\n#include <boost/iterator/function_output_iterator.hpp>\n\n#include <cmath>\n#include <iterator>\n#include <memory>\n#include <tuple>\n\nclass Basic2DGenericPFlowPositionCalc : public PFCPositionCalculatorBase {\npublic:\n  Basic2DGenericPFlowPositionCalc(const edm::ParameterSet& conf, edm::ConsumesCollector& cc)\n      : PFCPositionCalculatorBase(conf, cc),\n        _posCalcNCrystals(conf.getParameter<int>(\"posCalcNCrystals\")),\n        _minAllowedNorm(conf.getParameter<double>(\"minAllowedNormalization\")) {\n    std::vector<int> detectorEnum;\n    std::vector<int> depths;\n    std::vector<double> logWeightDenom;\n    std::vector<float> logWeightDenomInv;\n\n    if (conf.exists(\"logWeightDenominatorByDetector\")) {\n      const std::vector<edm::ParameterSet>& logWeightDenominatorByDetectorPSet =\n          conf.getParameterSetVector(\"logWeightDenominatorByDetector\");\n\n      for (const auto& pset : logWeightDenominatorByDetectorPSet) {\n        if (!pset.exists(\"detector\")) {\n          throw cms::Exception(\"logWeightDenominatorByDetectorPSet\") << \"logWeightDenominator : detector not specified\";\n        }\n\n        const std::string& det = pset.getParameter<std::string>(\"detector\");\n\n        if (det == std::string(\"HCAL_BARREL1\") || det == std::string(\"HCAL_ENDCAP\")) {\n          std::vector<int> depthsT = pset.getParameter<std::vector<int> >(\"depths\");\n          std::vector<double> logWeightDenomT = pset.getParameter<std::vector<double> >(\"logWeightDenominator\");\n          if (logWeightDenomT.size() != depthsT.size()) {\n            throw cms::Exception(\"logWeightDenominator\") << \"logWeightDenominator mismatch with the numbers of depths\";\n          }\n          for (unsigned int i = 0; i < depthsT.size(); ++i) {\n            if (det == std::string(\"HCAL_BARREL1\"))\n              detectorEnum.push_back(1);\n            if (det == std::string(\"HCAL_ENDCAP\"))\n              detectorEnum.push_back(2);\n            depths.push_back(depthsT[i]);\n            logWeightDenom.push_back(logWeightDenomT[i]);\n          }\n        }\n      }\n    } else {\n      detectorEnum.push_back(0);\n      depths.push_back(0);\n      logWeightDenom.push_back(conf.getParameter<double>(\"logWeightDenominator\"));\n    }\n\n    for (unsigned int i = 0; i < depths.size(); ++i) {\n      logWeightDenomInv.push_back(1. / logWeightDenom[i]);\n    }\n\n    //    _logWeightDenom = std::make_pair(depths,logWeightDenomInv);\n    _logWeightDenom = std::make_tuple(detectorEnum, depths, logWeightDenomInv);\n\n    _timeResolutionCalcBarrel.reset(nullptr);\n    if (conf.exists(\"timeResolutionCalcBarrel\")) {\n      const edm::ParameterSet& timeResConf = conf.getParameterSet(\"timeResolutionCalcBarrel\");\n      _timeResolutionCalcBarrel = std::make_unique<CaloRecHitResolutionProvider>(timeResConf);\n    }\n    _timeResolutionCalcEndcap.reset(nullptr);\n    if (conf.exists(\"timeResolutionCalcEndcap\")) {\n      const edm::ParameterSet& timeResConf = conf.getParameterSet(\"timeResolutionCalcEndcap\");\n      _timeResolutionCalcEndcap = std::make_unique<CaloRecHitResolutionProvider>(timeResConf);\n    }\n\n    switch (_posCalcNCrystals) {\n      case 5:\n      case 9:\n      case -1:\n        break;\n      default:\n        edm::LogError(\"Basic2DGenericPFlowPositionCalc\") << \"posCalcNCrystals not valid\";\n        assert(0);  // bug\n    }\n  }\n\n  Basic2DGenericPFlowPositionCalc(const Basic2DGenericPFlowPositionCalc&) = delete;\n  Basic2DGenericPFlowPositionCalc& operator=(const Basic2DGenericPFlowPositionCalc&) = delete;\n\n  void calculateAndSetPosition(reco::PFCluster&) override;\n  void calculateAndSetPositions(reco::PFClusterCollection&) override;\n\nprivate:\n  const int _posCalcNCrystals;\n  std::tuple<std::vector<int>, std::vector<int>, std::vector<float> > _logWeightDenom;\n  const float _minAllowedNorm;\n\n  std::unique_ptr<CaloRecHitResolutionProvider> _timeResolutionCalcBarrel;\n  std::unique_ptr<CaloRecHitResolutionProvider> _timeResolutionCalcEndcap;\n\n  void calculateAndSetPositionActual(reco::PFCluster&) const;\n};\n\nDEFINE_EDM_PLUGIN(PFCPositionCalculatorFactory, Basic2DGenericPFlowPositionCalc, \"Basic2DGenericPFlowPositionCalc\");\n\nnamespace {\n  inline bool isBarrel(int cell_layer) {\n    return (cell_layer == PFLayer::HCAL_BARREL1 || cell_layer == PFLayer::HCAL_BARREL2 ||\n            cell_layer == PFLayer::ECAL_BARREL);\n  }\n}  // namespace\n\nvoid Basic2DGenericPFlowPositionCalc::calculateAndSetPosition(reco::PFCluster& cluster) {\n  calculateAndSetPositionActual(cluster);\n}\n\nvoid Basic2DGenericPFlowPositionCalc::calculateAndSetPositions(reco::PFClusterCollection& clusters) {\n  for (reco::PFCluster& cluster : clusters) {\n    calculateAndSetPositionActual(cluster);\n  }\n}\n\nvoid Basic2DGenericPFlowPositionCalc::calculateAndSetPositionActual(reco::PFCluster& cluster) const {\n  if (!cluster.seed()) {\n    throw cms::Exception(\"ClusterWithNoSeed\") << \" Found a cluster with no seed: \" << cluster;\n  }\n  double cl_energy = 0;\n  double cl_time = 0;\n  double cl_timeweight = 0.0;\n  double max_e = 0.0;\n  PFLayer::Layer max_e_layer = PFLayer::NONE;\n  // find the seed and max layer and also calculate time\n  //Michalis : Even if we dont use timing in clustering here we should fill\n  //the time information for the cluster. This should use the timing resolution(1/E)\n  //so the weight should be fraction*E^2\n  //calculate a simplistic depth now. The log weighted will be done\n  //in different stage\n\n  auto const recHitCollection =\n      &(*cluster.recHitFractions()[0].recHitRef()) - cluster.recHitFractions()[0].recHitRef().key();\n  auto nhits = cluster.recHitFractions().size();\n  struct LHit {\n    reco::PFRecHit const* hit;\n    float energy;\n    float fraction;\n  };\n  declareDynArray(LHit, nhits, hits);\n  for (auto i = 0U; i < nhits; ++i) {\n    auto const& hf = cluster.recHitFractions()[i];\n    auto k = hf.recHitRef().key();\n    auto p = recHitCollection + k;\n    hits[i] = {p, (*p).energy(), float(hf.fraction())};\n  }\n\n  bool resGiven = bool(_timeResolutionCalcBarrel) & bool(_timeResolutionCalcEndcap);\n  LHit mySeed = {};\n  for (auto const& rhf : hits) {\n    const reco::PFRecHit& refhit = *rhf.hit;\n    if (refhit.detId() == cluster.seed())\n      mySeed = rhf;\n    const auto rh_fraction = rhf.fraction;\n    const auto rh_rawenergy = rhf.energy;\n    const auto rh_energy = rh_rawenergy * rh_fraction;\n#ifdef PF_DEBUG\n    if UNLIKELY (edm::isNotFinite(rh_energy)) {\n      throw cms::Exception(\"PFClusterAlgo\") << \"rechit \" << refhit.detId() << \" has a NaN energy... \"\n                                            << \"The input of the particle flow clustering seems to be corrupted.\";\n    }\n#endif\n    cl_energy += rh_energy;\n    // If time resolution is given, calculated weighted average\n    if (resGiven) {\n      double res2 = 1.e-4;\n      int cell_layer = (int)refhit.layer();\n      res2 = isBarrel(cell_layer) ? 1. / _timeResolutionCalcBarrel->timeResolution2(rh_rawenergy)\n                                  : 1. / _timeResolutionCalcEndcap->timeResolution2(rh_rawenergy);\n      cl_time += rh_fraction * refhit.time() * res2;\n      cl_timeweight += rh_fraction * res2;\n    } else {  // assume resolution = 1/E**2\n      const double rh_rawenergy2 = rh_rawenergy * rh_rawenergy;\n      cl_timeweight += rh_rawenergy2 * rh_fraction;\n      cl_time += rh_rawenergy2 * rh_fraction * refhit.time();\n    }\n\n    if (rh_energy > max_e) {\n      max_e = rh_energy;\n      max_e_layer = refhit.layer();\n    }\n  }\n\n  cluster.setEnergy(cl_energy);\n  cluster.setTime(cl_time / cl_timeweight);\n  if (resGiven) {\n    cluster.setTimeError(std::sqrt(1.0f / float(cl_timeweight)));\n  }\n  cluster.setLayer(max_e_layer);\n\n  // calculate the position\n  double depth = 0.0;\n  double position_norm = 0.0;\n  double x(0.0), y(0.0), z(0.0);\n  if (nullptr != mySeed.hit) {\n    auto seedNeighbours = mySeed.hit->neighbours();\n    switch (_posCalcNCrystals) {\n      case 5:\n        seedNeighbours = mySeed.hit->neighbours4();\n        break;\n      case 9:\n        seedNeighbours = mySeed.hit->neighbours8();\n        break;\n      default:\n        break;\n    }\n\n    auto compute = [&](LHit const& rhf) {\n      const reco::PFRecHit& refhit = *rhf.hit;\n\n      int cell_layer = (int)refhit.layer();\n      float threshold = 0;\n\n      for (unsigned int j = 0; j < (std::get<2>(_logWeightDenom)).size(); ++j) {\n        // barrel is detecor type1\n        int detectorEnum = std::get<0>(_logWeightDenom)[j];\n        int depth = std::get<1>(_logWeightDenom)[j];\n\n        if ((cell_layer == PFLayer::HCAL_BARREL1 && detectorEnum == 1 && refhit.depth() == depth) ||\n            (cell_layer == PFLayer::HCAL_ENDCAP && detectorEnum == 2 && refhit.depth() == depth) || detectorEnum == 0)\n          threshold = std::get<2>(_logWeightDenom)[j];\n      }\n\n      const auto rh_energy = rhf.energy * rhf.fraction;\n      const auto norm =\n          (rhf.fraction < _minFractionInCalc ? 0.0f : std::max(0.0f, vdt::fast_logf(rh_energy * threshold)));\n      const auto rhpos_xyz = refhit.position() * norm;\n      x += rhpos_xyz.x();\n      y += rhpos_xyz.y();\n      z += rhpos_xyz.z();\n      depth += refhit.depth() * norm;\n      position_norm += norm;\n    };\n\n    if (_posCalcNCrystals != -1)  // sorted to make neighbour search faster (maybe)\n      std::sort(hits.begin(), hits.end(), [](LHit const& a, LHit const& b) { return a.hit < b.hit; });\n\n    if (_posCalcNCrystals == -1)\n      for (auto const& rhf : hits)\n        compute(rhf);\n    else {  // only seed and its neighbours\n      compute(mySeed);\n      // search seedNeighbours to find energy fraction in cluster (sic)\n      unInitDynArray(reco::PFRecHit const*, seedNeighbours.size(), nei);\n      for (auto k : seedNeighbours) {\n        nei.push_back(recHitCollection + k);\n      }\n      std::sort(nei.begin(), nei.end());\n      struct LHitLess {\n        auto operator()(LHit const& a, reco::PFRecHit const* b) const { return a.hit < b; }\n        auto operator()(reco::PFRecHit const* b, LHit const& a) const { return b < a.hit; }\n      };\n      std::set_intersection(\n          hits.begin(), hits.end(), nei.begin(), nei.end(), boost::make_function_output_iterator(compute), LHitLess());\n    }\n  } else {\n    throw cms::Exception(\"Basic2DGenerticPFlowPositionCalc\")\n        << \"Cluster seed hit is null, something is wrong with PFlow RecHit!\";\n  }\n\n  if (position_norm < _minAllowedNorm) {\n    edm::LogError(\"WeirdClusterNormalization\") << \"PFCluster too far from seeding cell: set position to (0,0,0).\";\n    cluster.setPosition(math::XYZPoint(0, 0, 0));\n    cluster.calculatePositionREP();\n  } else {\n    const double norm_inverse = 1.0 / position_norm;\n    x *= norm_inverse;\n    y *= norm_inverse;\n    z *= norm_inverse;\n    depth *= norm_inverse;\n    cluster.setPosition(math::XYZPoint(x, y, z));\n    cluster.setDepth(depth);\n    cluster.calculatePositionREP();\n  }\n}\n", "meta": {"hexsha": "fd7576ff940da697eb15d759c10264e97c612c34", "size": 11282, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RecoParticleFlow/PFClusterProducer/plugins/Basic2DGenericPFlowPositionCalc.cc", "max_stars_repo_name": "Purva-Chaudhari/cmssw", "max_stars_repo_head_hexsha": "32e5cbfe54c4d809d60022586cf200b7c3020bcf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 852.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T21:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T21:14:00.000Z", "max_issues_repo_path": "RecoParticleFlow/PFClusterProducer/plugins/Basic2DGenericPFlowPositionCalc.cc", "max_issues_repo_name": "Purva-Chaudhari/cmssw", "max_issues_repo_head_hexsha": "32e5cbfe54c4d809d60022586cf200b7c3020bcf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30371.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T00:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:26:05.000Z", "max_forks_repo_path": "RecoParticleFlow/PFClusterProducer/plugins/Basic2DGenericPFlowPositionCalc.cc", "max_forks_repo_name": "Purva-Chaudhari/cmssw", "max_forks_repo_head_hexsha": "32e5cbfe54c4d809d60022586cf200b7c3020bcf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3240.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T05:53:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:24:21.000Z", "avg_line_length": 39.1736111111, "max_line_length": 120, "alphanum_fraction": 0.6743485198, "num_tokens": 3002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.17568444184045476}}
{"text": "\ufeff/* ============================================================================================== *\n *                                                                                                *\n *                                     Galaxia Blockchain                                         *\n *                                                                                                *\n * ---------------------------------------------------------------------------------------------- *\n * This file is part of the Xi framework.                                                         *\n * ---------------------------------------------------------------------------------------------- *\n *                                                                                                *\n * Copyright 2018-2019 Xi Project Developers <support.xiproject.io>                               *\n *                                                                                                *\n * This program is free software: you can redistribute it and/or modify it under the terms of the *\n * GNU General Public License as published by the Free Software Foundation, either version 3 of   *\n * the License, or (at your option) any later version.                                            *\n *                                                                                                *\n * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;      *\n * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.      *\n * See the GNU General Public License for more details.                                           *\n *                                                                                                *\n * You should have received a copy of the GNU General Public License along with this program.     *\n * If not, see <https://www.gnu.org/licenses/>.                                                   *\n *                                                                                                *\n * ============================================================================================== */\n\n#include \"Xi/Crypto/Hash/Crc.hpp\"\n\n#if defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable : 4701)\n#endif\n\n#include <boost/crc.hpp>\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\n#include <boost/endian/conversion.hpp>\n\n#include <Xi/Exceptions.hpp>\n\nXI_CRYPTO_HASH_DECLARE_HASH_IMPLEMENTATION(Xi::Crypto::Hash::Crc::Hash16, 16)\nXI_CRYPTO_HASH_DECLARE_HASH_IMPLEMENTATION(Xi::Crypto::Hash::Crc::Hash32, 32)\n\nvoid Xi::Crypto::Hash::Crc::compute(Xi::ConstByteSpan data, Hash16 &out) {\n  static_assert(sizeof(boost::crc_16_type::value_type) == Hash16::bytes(), \"invalid hash size for boost crc\");\n  boost::crc_16_type result{};\n  result.process_bytes(data.data(), data.size());\n  *reinterpret_cast<boost::crc_16_type::value_type *>(out.data()) = boost::endian::native_to_big(result.checksum());\n}\n\nvoid Xi::Crypto::Hash::Crc::compute(Xi::ConstByteSpan data, Hash32 &out) {\n  static_assert(sizeof(boost::crc_32_type::value_type) == Hash32::bytes(), \"invalid hash size for boost crc\");\n  boost::crc_32_type result{};\n  result.process_bytes(data.data(), data.size());\n  *reinterpret_cast<boost::crc_32_type::value_type *>(out.data()) = boost::endian::native_to_big(result.checksum());\n}\n\nXi::Crypto::Hash::Crc::Hash16 Xi::Crypto::Hash::crc16(Xi::ConstByteSpan data) {\n  Crc::Hash16 reval;\n  compute(data, reval);\n  return reval;\n}\n\nXi::Crypto::Hash::Crc::Hash32 Xi::Crypto::Hash::crc32(Xi::ConstByteSpan data) {\n  Crc::Hash32 reval;\n  compute(data, reval);\n  return reval;\n}\n", "meta": {"hexsha": "5c6a3ad66e9279eb67dfe26b2733a856de6a02a7", "size": 3687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Xi-Crypto/source/hash/Crc.cpp", "max_stars_repo_name": "ElSamaritan/blockchain-OLD", "max_stars_repo_head_hexsha": "ca3422c8873613226db99b7e6735c5ea1fac9f1a", "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/Xi-Crypto/source/hash/Crc.cpp", "max_issues_repo_name": "ElSamaritan/blockchain-OLD", "max_issues_repo_head_hexsha": "ca3422c8873613226db99b7e6735c5ea1fac9f1a", "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/Xi-Crypto/source/hash/Crc.cpp", "max_forks_repo_name": "ElSamaritan/blockchain-OLD", "max_forks_repo_head_hexsha": "ca3422c8873613226db99b7e6735c5ea1fac9f1a", "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": 53.4347826087, "max_line_length": 116, "alphanum_fraction": 0.4532139951, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1756844350197216}}
{"text": "#include \"../agg.hpp\"\n#include <boost/accumulators/statistics/sum.hpp>\n\nARRAY_AGGREGATE_FNC(asum, tag::sum);\nSQL_AGGREGATE_FNC(v_sum, tag::sum);\n", "meta": {"hexsha": "594214ff0b968f1262b42604efd0b4d1f1cf0e36", "size": 145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/aggregate/sum.cpp", "max_stars_repo_name": "tarkmeper/numpgsql", "max_stars_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T15:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-07T16:31:55.000Z", "max_issues_repo_path": "src/math/aggregate/sum.cpp", "max_issues_repo_name": "tarkmeper/numpgsql", "max_issues_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_issues_repo_licenses": ["MIT"], "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/aggregate/sum.cpp", "max_forks_repo_name": "tarkmeper/numpgsql", "max_forks_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_forks_repo_licenses": ["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.1666666667, "max_line_length": 48, "alphanum_fraction": 0.7586206897, "num_tokens": 45, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061556288288, "lm_q2_score": 0.34864512856608554, "lm_q1q2_score": 0.17568442641445492}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>\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#include <main.h>\n#include <iostream>\n#include <GL/glew.h>\n#include <Eigen/OpenGLSupport>\n#include <GL/glut.h>\nusing namespace Eigen;\n\n\n\n\n#define VERIFY_MATRIX(CODE,REF) { \\\n    glLoadIdentity(); \\\n    CODE; \\\n    Matrix<float,4,4,ColMajor> m; m.setZero(); \\\n    glGet(GL_MODELVIEW_MATRIX, m); \\\n    if(!(REF).cast<float>().isApprox(m)) { \\\n      std::cerr << \"Expected:\\n\" << ((REF).cast<float>()) << \"\\n\" << \"got\\n\" << m << \"\\n\\n\"; \\\n    } \\\n    VERIFY_IS_APPROX((REF).cast<float>(), m); \\\n  }\n\n#define VERIFY_UNIFORM(SUFFIX,NAME,TYPE) { \\\n    TYPE value; value.setRandom(); \\\n    TYPE data; \\\n    int loc = glGetUniformLocation(prg_id, #NAME); \\\n    VERIFY((loc!=-1) && \"uniform not found\"); \\\n    glUniform(loc,value); \\\n    EIGEN_CAT(glGetUniform,SUFFIX)(prg_id,loc,data.data()); \\\n    if(!value.isApprox(data)) { \\\n      std::cerr << \"Expected:\\n\" << value << \"\\n\" << \"got\\n\" << data << \"\\n\\n\"; \\\n    } \\\n    VERIFY_IS_APPROX(value, data); \\\n  }\n  \n#define VERIFY_UNIFORMi(NAME,TYPE) { \\\n    TYPE value = TYPE::Random().eval().cast<float>().cast<TYPE::Scalar>(); \\\n    TYPE data; \\\n    int loc = glGetUniformLocation(prg_id, #NAME); \\\n    VERIFY((loc!=-1) && \"uniform not found\"); \\\n    glUniform(loc,value); \\\n    glGetUniformiv(prg_id,loc,(GLint*)data.data()); \\\n    if(!value.isApprox(data)) { \\\n      std::cerr << \"Expected:\\n\" << value << \"\\n\" << \"got\\n\" << data << \"\\n\\n\"; \\\n    } \\\n    VERIFY_IS_APPROX(value, data); \\\n  }\n  \nvoid printInfoLog(GLuint objectID)\n{\n    int infologLength, charsWritten;\n    GLchar *infoLog;\n    glGetProgramiv(objectID,GL_INFO_LOG_LENGTH, &infologLength);\n    if(infologLength > 0)\n    {\n        infoLog = new GLchar[infologLength];\n        glGetProgramInfoLog(objectID, infologLength, &charsWritten, infoLog);\n        if (charsWritten>0)\n          std::cerr << \"Shader info : \\n\" << infoLog << std::endl;\n        delete[] infoLog;\n    }\n}\n\nGLint createShader(const char* vtx, const char* frg)\n{\n  GLint prg_id = glCreateProgram();\n  GLint vtx_id = glCreateShader(GL_VERTEX_SHADER);\n  GLint frg_id = glCreateShader(GL_FRAGMENT_SHADER);\n  GLint ok;\n  \n  glShaderSource(vtx_id, 1, &vtx, 0);\n  glCompileShader(vtx_id);\n  glGetShaderiv(vtx_id,GL_COMPILE_STATUS,&ok);\n  if(!ok)\n  {\n    std::cerr << \"vtx compilation failed\\n\";\n  }\n  \n  glShaderSource(frg_id, 1, &frg, 0);\n  glCompileShader(frg_id);\n  glGetShaderiv(frg_id,GL_COMPILE_STATUS,&ok);\n  if(!ok)\n  {\n    std::cerr << \"frg compilation failed\\n\";\n  }\n  \n  glAttachShader(prg_id, vtx_id);\n  glAttachShader(prg_id, frg_id);\n  glLinkProgram(prg_id);\n  glGetProgramiv(prg_id,GL_LINK_STATUS,&ok);\n  if(!ok)\n  {\n    std::cerr << \"linking failed\\n\";\n  }\n  printInfoLog(prg_id);\n  \n  glUseProgram(prg_id);\n  return prg_id;\n}\n\nvoid test_openglsupport()\n{\n  int argc = 0;\n  glutInit(&argc, 0);\n  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);\n  glutInitWindowPosition (0,0);\n  glutInitWindowSize(10, 10);\n\n  if(glutCreateWindow(\"Eigen\") <= 0)\n  {\n    std::cerr << \"Error: Unable to create GLUT Window.\\n\";\n    exit(1);\n  }\n  \n  glewExperimental = GL_TRUE;\n  if(glewInit() != GLEW_OK)\n  {\n    std::cerr << \"Warning: Failed to initialize GLEW\\n\";\n  }\n\n  Vector3f v3f;\n  Matrix3f rot;\n  glBegin(GL_POINTS);\n  \n  glVertex(v3f);\n  glVertex(2*v3f+v3f);\n  glVertex(rot*v3f);\n  \n  glEnd();\n  \n  // 4x4 matrices\n  Matrix4f mf44; mf44.setRandom();\n  VERIFY_MATRIX(glLoadMatrix(mf44), mf44);\n  VERIFY_MATRIX(glMultMatrix(mf44), mf44);\n  Matrix4d md44; md44.setRandom();\n  VERIFY_MATRIX(glLoadMatrix(md44), md44);\n  VERIFY_MATRIX(glMultMatrix(md44), md44);\n  \n  // Quaternion\n  Quaterniond qd(AngleAxisd(internal::random<double>(), Vector3d::Random()));\n  VERIFY_MATRIX(glRotate(qd), Projective3d(qd).matrix());\n  \n  Quaternionf qf(AngleAxisf(internal::random<double>(), Vector3f::Random()));\n  VERIFY_MATRIX(glRotate(qf), Projective3f(qf).matrix());\n  \n  // 3D Transform\n  Transform<float,3,AffineCompact> acf3; acf3.matrix().setRandom();\n  VERIFY_MATRIX(glLoadMatrix(acf3), Projective3f(acf3).matrix());\n  VERIFY_MATRIX(glMultMatrix(acf3), Projective3f(acf3).matrix());\n  \n  Transform<float,3,Affine> af3(acf3);\n  VERIFY_MATRIX(glLoadMatrix(af3), Projective3f(af3).matrix());\n  VERIFY_MATRIX(glMultMatrix(af3), Projective3f(af3).matrix());\n  \n  Transform<float,3,Projective> pf3; pf3.matrix().setRandom();\n  VERIFY_MATRIX(glLoadMatrix(pf3), Projective3f(pf3).matrix());\n  VERIFY_MATRIX(glMultMatrix(pf3), Projective3f(pf3).matrix());\n  \n  Transform<double,3,AffineCompact> acd3; acd3.matrix().setRandom();\n  VERIFY_MATRIX(glLoadMatrix(acd3), Projective3d(acd3).matrix());\n  VERIFY_MATRIX(glMultMatrix(acd3), Projective3d(acd3).matrix());\n  \n  Transform<double,3,Affine> ad3(acd3);\n  VERIFY_MATRIX(glLoadMatrix(ad3), Projective3d(ad3).matrix());\n  VERIFY_MATRIX(glMultMatrix(ad3), Projective3d(ad3).matrix());\n  \n  Transform<double,3,Projective> pd3; pd3.matrix().setRandom();\n  VERIFY_MATRIX(glLoadMatrix(pd3), Projective3d(pd3).matrix());\n  VERIFY_MATRIX(glMultMatrix(pd3), Projective3d(pd3).matrix());\n  \n  // translations (2D and 3D)\n  {\n    Vector2f vf2; vf2.setRandom(); Vector3f vf23; vf23 << vf2, 0;\n    VERIFY_MATRIX(glTranslate(vf2), Projective3f(Translation3f(vf23)).matrix());\n    Vector2d vd2; vd2.setRandom(); Vector3d vd23; vd23 << vd2, 0;\n    VERIFY_MATRIX(glTranslate(vd2), Projective3d(Translation3d(vd23)).matrix());\n    \n    Vector3f vf3; vf3.setRandom();\n    VERIFY_MATRIX(glTranslate(vf3), Projective3f(Translation3f(vf3)).matrix());\n    Vector3d vd3; vd3.setRandom();\n    VERIFY_MATRIX(glTranslate(vd3), Projective3d(Translation3d(vd3)).matrix());\n    \n    Translation<float,3> tf3; tf3.vector().setRandom();\n    VERIFY_MATRIX(glTranslate(tf3), Projective3f(tf3).matrix());\n    \n    Translation<double,3> td3;  td3.vector().setRandom();\n    VERIFY_MATRIX(glTranslate(td3), Projective3d(td3).matrix());\n  }\n  \n  // scaling (2D and 3D)\n  {\n    Vector2f vf2; vf2.setRandom(); Vector3f vf23; vf23 << vf2, 1;\n    VERIFY_MATRIX(glScale(vf2), Projective3f(Scaling(vf23)).matrix());\n    Vector2d vd2; vd2.setRandom(); Vector3d vd23; vd23 << vd2, 1;\n    VERIFY_MATRIX(glScale(vd2), Projective3d(Scaling(vd23)).matrix());\n    \n    Vector3f vf3; vf3.setRandom();\n    VERIFY_MATRIX(glScale(vf3), Projective3f(Scaling(vf3)).matrix());\n    Vector3d vd3; vd3.setRandom();\n    VERIFY_MATRIX(glScale(vd3), Projective3d(Scaling(vd3)).matrix());\n    \n    UniformScaling<float> usf(internal::random<float>());\n    VERIFY_MATRIX(glScale(usf), Projective3f(usf).matrix());\n    \n    UniformScaling<double> usd(internal::random<double>());\n    VERIFY_MATRIX(glScale(usd), Projective3d(usd).matrix());\n  }\n  \n  // uniform\n  {\n    const char* vtx = \"void main(void) { gl_Position = gl_Vertex; }\\n\";\n    \n    if(GLEW_VERSION_2_0)\n    {\n      #ifdef GL_VERSION_2_0\n      const char* frg = \"\"\n        \"uniform vec2 v2f;\\n\"\n        \"uniform vec3 v3f;\\n\"\n        \"uniform vec4 v4f;\\n\"\n        \"uniform ivec2 v2i;\\n\"\n        \"uniform ivec3 v3i;\\n\"\n        \"uniform ivec4 v4i;\\n\"\n        \"uniform mat2 m2f;\\n\"\n        \"uniform mat3 m3f;\\n\"\n        \"uniform mat4 m4f;\\n\"\n        \"void main(void) { gl_FragColor = vec4(v2f[0]+v3f[0]+v4f[0])+vec4(v2i[0]+v3i[0]+v4i[0])+vec4(m2f[0][0]+m3f[0][0]+m4f[0][0]); }\\n\";\n        \n      GLint prg_id = createShader(vtx,frg);\n      \n      VERIFY_UNIFORM(fv,v2f, Vector2f);\n      VERIFY_UNIFORM(fv,v3f, Vector3f);\n      VERIFY_UNIFORM(fv,v4f, Vector4f);\n      VERIFY_UNIFORMi(v2i, Vector2i);\n      VERIFY_UNIFORMi(v3i, Vector3i);\n      VERIFY_UNIFORMi(v4i, Vector4i);\n      VERIFY_UNIFORM(fv,m2f, Matrix2f);\n      VERIFY_UNIFORM(fv,m3f, Matrix3f);\n      VERIFY_UNIFORM(fv,m4f, Matrix4f);\n      #endif\n    }\n    else\n      std::cerr << \"Warning: opengl 2.0 was not tested\\n\";\n    \n    if(GLEW_VERSION_2_1)\n    {\n      #ifdef GL_VERSION_2_1\n      const char* frg = \"#version 120\\n\"\n        \"uniform mat2x3 m23f;\\n\"\n        \"uniform mat3x2 m32f;\\n\"\n        \"uniform mat2x4 m24f;\\n\"\n        \"uniform mat4x2 m42f;\\n\"\n        \"uniform mat3x4 m34f;\\n\"\n        \"uniform mat4x3 m43f;\\n\"\n        \"void main(void) { gl_FragColor = vec4(m23f[0][0]+m32f[0][0]+m24f[0][0]+m42f[0][0]+m34f[0][0]+m43f[0][0]); }\\n\";\n        \n      GLint prg_id = createShader(vtx,frg);\n      \n      typedef Matrix<float,2,3> Matrix23f;\n      typedef Matrix<float,3,2> Matrix32f;\n      typedef Matrix<float,2,4> Matrix24f;\n      typedef Matrix<float,4,2> Matrix42f;\n      typedef Matrix<float,3,4> Matrix34f;\n      typedef Matrix<float,4,3> Matrix43f;\n      \n      VERIFY_UNIFORM(fv,m23f, Matrix23f);\n      VERIFY_UNIFORM(fv,m32f, Matrix32f);\n      VERIFY_UNIFORM(fv,m24f, Matrix24f);\n      VERIFY_UNIFORM(fv,m42f, Matrix42f);\n      VERIFY_UNIFORM(fv,m34f, Matrix34f);\n      VERIFY_UNIFORM(fv,m43f, Matrix43f);\n      #endif\n    }\n    else\n      std::cerr << \"Warning: opengl 2.1 was not tested\\n\";\n    \n    if(GLEW_VERSION_3_0)\n    {\n      #ifdef GL_VERSION_3_0\n      const char* frg = \"#version 150\\n\"\n        \"uniform uvec2 v2ui;\\n\"\n        \"uniform uvec3 v3ui;\\n\"\n        \"uniform uvec4 v4ui;\\n\"\n        \"out vec4 data;\\n\"\n        \"void main(void) { data = vec4(v2ui[0]+v3ui[0]+v4ui[0]); }\\n\";\n        \n      GLint prg_id = createShader(vtx,frg);\n      \n      typedef Matrix<unsigned int,2,1> Vector2ui;\n      typedef Matrix<unsigned int,3,1> Vector3ui;\n      typedef Matrix<unsigned int,4,1> Vector4ui;\n      \n      VERIFY_UNIFORMi(v2ui, Vector2ui);\n      VERIFY_UNIFORMi(v3ui, Vector3ui);\n      VERIFY_UNIFORMi(v4ui, Vector4ui);\n      #endif\n    }\n    else\n      std::cerr << \"Warning: opengl 3.0 was not tested\\n\";\n    \n    #ifdef GLEW_ARB_gpu_shader_fp64\n    if(GLEW_ARB_gpu_shader_fp64)\n    {\n      #ifdef GL_ARB_gpu_shader_fp64\n      const char* frg = \"#version 150\\n\"\n        \"uniform dvec2 v2d;\\n\"\n        \"uniform dvec3 v3d;\\n\"\n        \"uniform dvec4 v4d;\\n\"\n        \"out vec4 data;\\n\"\n        \"void main(void) { data = vec4(v2d[0]+v3d[0]+v4d[0]); }\\n\";\n        \n      GLint prg_id = createShader(vtx,frg);\n      \n      typedef Vector2d Vector2d;\n      typedef Vector3d Vector3d;\n      typedef Vector4d Vector4d;\n      \n      VERIFY_UNIFORM(dv,v2d, Vector2d);\n      VERIFY_UNIFORM(dv,v3d, Vector3d);\n      VERIFY_UNIFORM(dv,v4d, Vector4d);\n      #endif\n    }\n    else\n      std::cerr << \"Warning: GLEW_ARB_gpu_shader_fp64 was not tested\\n\";\n    #else\n      std::cerr << \"Warning: GLEW_ARB_gpu_shader_fp64 was not tested\\n\";\n    #endif\n  }\n  \n}\n", "meta": {"hexsha": "706a816f7297ac1c7dc23d645faf8f6ac0367a21", "size": 10694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/unsupported/test/openglsupport.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "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": "src/Eigen-3.3/unsupported/test/openglsupport.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 224.0, "max_issues_repo_issues_event_min_datetime": "2018-02-26T00:41:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:38:16.000Z", "max_forks_repo_path": "src/Eigen-3.3/unsupported/test/openglsupport.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 31.6390532544, "max_line_length": 138, "alphanum_fraction": 0.641387694, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17563827792496084}}
{"text": "#include \"packet_protocol.h\"\n#include <boost/crc.hpp> // for boost::crc_basic, boost::crc_optimal\n\nstatic uint32_t crc32(const void *data, size_t size) {\n    boost::crc_32_type crc32_obj;\n    crc32_obj.process_bytes(data, size);\n    return crc32_obj();\n}\n\nint serialize_packet(OutputStream &out, FIELD *fields, int len) {\n    char *body_base = 0;\n    int n = 0;\n\n    for (FIELD *p = fields; p->type >= 0; ++p, ++n) {\n        /*Caculate CRC for header crc field*/\n        if (n == FIELD_HCRC) {\n            unsigned int length = out.write_ptr() - out.base_ptr();\n            if (length > 0) {\n                p->ivalue = crc32(out.base_ptr(), length);\n            }\n        }\n            /*Caculate CRC for body crc field*/\n        else if (len - 1 == n) {\n            if (0 != body_base) {\n                int length = out.write_ptr() - body_base;\n                if (length > 0)\n                    p->ivalue = crc32(body_base, length);\n            }\n        }\n\n        /**************caculate binary stream************************/\n        if (0 == p->data) {\n            bool ret = false;\n            switch (p->type) {\n                case TYPE_CHAR:\n                case TYPE_BYTE:\n                    ret = out.write_char((Char) p->ivalue);\n                    break;\n                case TYPE_SHORT:\n                    ret = out.write_short((Short) p->ivalue);\n                    break;\n                case TYPE_LONG:\n                    ret = out.write_long((Long) p->ivalue);\n                    break;\n                case TYPE_LONGLONG:\n                    ret = out.write_llong((LongLong) p->ivalue);\n                    break;\n                case TYPE_FLOAT:\n                    ret = out.write_float((Float) p->fvalue);\n                    break;\n                case TYPE_DOUBLE:\n                    ret = out.write_double((Double) p->fvalue);\n                    break;\n                default:\n                    break;\n            }\n        } else /*p->data !=0*/\n        {\n            if (p->count > 0)/*p->data !=0 && p->count >0*/\n            {\n                int count = p->count * fields[FIELD_COUNT].ivalue;\n                switch (p->type) {\n                    case TYPE_CHAR:\n                    case TYPE_BYTE:\n                        out.write_char_array((Char *) p->data, count);\n                        break;\n                    case TYPE_SHORT:\n                        out.write_short_array((Short *) p->data, count);\n                        break;\n                    case TYPE_LONG:\n                        out.write_long_array((Long *) p->data, count);\n                        break;\n                    case TYPE_LONGLONG:\n                        out.write_llong_array((LongLong *) p->data, count);\n                        break;\n                    case TYPE_FLOAT:\n                        out.write_float_array((Float *) p->data, count);\n                        break;\n                    case TYPE_DOUBLE:\n                        out.write_double_array((Double *) p->data, count);\n                        break;\n                    default:\n                        break;\n                }\n            } else /*p->data !=0 && p->count==0*/\n            {\n                FIELD *prev = p - 1;\n                if (prev->type != TYPE_SHORT && prev->type != TYPE_LONG)\n                    return ERR_ENCODE_ERROE;\n\n                int count = 0;\n                switch (p->count) {\n                    case -1: {\n                        count = prev->ivalue;\n                        switch (p->type) {\n                            case TYPE_CHAR:\n                            case TYPE_BYTE:\n                                out.write_char_array((Char *) p->data, count);\n                                break;\n                            case TYPE_SHORT:\n                                out.write_short_array((Short *) p->data, count);\n                                break;\n                            case TYPE_LONG:\n                                out.write_long_array((Long *) p->data, count);\n                                break;\n                            case TYPE_LONGLONG:\n                                out.write_llong_array((LongLong *) p->data, count);\n                                break;\n                            case TYPE_FLOAT:\n                                out.write_float_array((Float *) p->data, count);\n                                break;\n                            case TYPE_DOUBLE:\n                                out.write_double_array((Double *) p->data, count);\n                                break;\n                            default:\n                                break;\n                        }\n                        break;\n                    }\n                    case -2://reserved!\n                        break;\n                    case -3://reserved!\n                        break;\n                    case -4://reserved!\n                        break;\n                    default:\n                        break;\n                }\n            }\n        }\n\n        if (n == FIELD_BMARK - 1)\n            body_base = out.write_ptr();\n\n        if (!out.good())\n            return ERR_ENCODE_ERROE;\n    }\n\n    return ERR_OK;\n}\n\n\nint unserialize_header_packet(InputStream &in, FIELD *fields, bool compare_crc) {\n    Char c_val = 0;\n    Short s_val = 0;\n    Long l_val = 0;\n    LongLong ll_val = 0;\n    Float f_val = 0.;\n    Double d_val = 0;\n    int n = 0;\n    unsigned int crc = 0;\n    char *base = in.base_ptr();\n\n    for (FIELD *p = fields; p->type >= 0; ++p, ++n) {\n        if (n == FIELD_HCRC) {\n            int length = in.read_ptr() - base;\n            if (length > 0 && compare_crc)\n                crc = crc32(base, length);\n        }\n\n        if (p->data == 0) {\n            switch (p->type) {\n                case TYPE_CHAR:\n                case TYPE_BYTE:\n                    in.read_char(c_val);\n                    p->ivalue = c_val;\n                    break;\n                case TYPE_SHORT:\n                    in.read_short(s_val);\n                    p->ivalue = s_val;\n                    break;\n                case TYPE_LONG:\n                    in.read_long(l_val);\n                    p->ivalue = l_val;\n                    break;\n                case TYPE_LONGLONG:\n                    in.read_llong(ll_val);\n                    p->ivalue = ll_val;\n                    break;\n                case TYPE_FLOAT:\n                    in.read_float(f_val);\n                    p->fvalue = f_val;\n                    break;\n                case TYPE_DOUBLE:\n                    in.read_double(d_val);\n                    p->fvalue = d_val;\n                    break;\n                default:\n                    break;\n            }\n        }\n\n        if (n == FIELD_HMARK) {\n            if ((unsigned int) p->ivalue != HEAD_MARK)\n                return ERR_DECODE_ERROE;\n        } else if (n == FIELD_HCRC) {\n            if (compare_crc && crc != (unsigned int) p->ivalue)\n                return ERR_CHECK_CRC_ERROR;\n\n            break;\n        }\n\n        if (!in.good())\n            return ERR_DECODE_ERROE;\n    }\n\n    return ERR_OK;\n}\n\nint unserialize_body_packet(InputStream &in, FIELD *fields, int len, bool compare_crc) {\n    Char c_val = 0;\n    Short s_val = 0;\n    Long l_val = 0;\n    LongLong ll_val = 0;\n    Float f_val = 0.;\n    Double d_val = 0;\n\n    int n = FIELD_BMARK;\n    unsigned int crc = 0;\n    int cnt = fields[FIELD_COUNT].ivalue;\n    char *base = in.read_ptr();\n\n    for (FIELD *p = &fields[n]; p->type >= 0; ++p, ++n) {\n        if (len - 1 == n && compare_crc) {\n            int length = in.read_ptr() - base;\n            if (length > 0)\n                crc = crc32(base, length);\n        }\n\n        if (p->data == 0) {\n            bool ret = false;\n            switch (p->type) {\n                case TYPE_CHAR:\n                case TYPE_BYTE:\n                    ret = in.read_char(c_val);\n                    p->ivalue = c_val;\n                    break;\n                case TYPE_SHORT:\n                    ret = in.read_short(s_val);\n                    p->ivalue = s_val;\n                    break;\n                case TYPE_LONG:\n                    ret = in.read_long(l_val);\n                    p->ivalue = l_val;\n                    break;\n                case TYPE_LONGLONG:\n                    ret = in.read_llong(ll_val);\n                    p->ivalue = ll_val;\n                    break;\n                case TYPE_FLOAT:\n                    ret = in.read_float(f_val);\n                    p->fvalue = f_val;\n                    break;\n                case TYPE_DOUBLE:\n                    ret = in.read_double(d_val);\n                    p->fvalue = d_val;\n                    break;\n                default:\n                    break;\n            }\n\n        } else // p->data != 0\n        {\n            int count = 0;\n            if (p->count >= 0) // p->data != 0  && p->count >= 0\n            {\n                count = cnt * p->count;\n                switch (p->type) {\n                    case TYPE_CHAR:\n                    case TYPE_BYTE:\n                        in.read_char_array((Char *) p->data, count);\n                        break;\n                    case TYPE_SHORT:\n                        in.read_short_array((Short *) p->data, count);\n                        break;\n                    case TYPE_LONG:\n                        in.read_long_array((Long *) p->data, count);\n                        break;\n                    case TYPE_LONGLONG:\n                        in.read_llong_array((LongLong *) p->data, count);\n                        break;\n                    case TYPE_FLOAT:\n                        in.read_float_array((Float *) p->data, count);\n                        break;\n                    case TYPE_DOUBLE:\n                        in.read_double_array((Double *) p->data, count);\n                        break;\n                    default:\n                        break;\n                }\n            } else// p->data != 0  && p->count < 0\n            {\n                FIELD *prev = p - 1;\n                if (prev->type != TYPE_SHORT && prev->type != TYPE_LONG)\n                    return ERR_DECODE_ERROE;\n\n                switch (p->count) {\n                    case -1: {\n                        if (prev->data != 0)\n                            return ERR_DECODE_ERROE;\n\n                        count = prev->ivalue;\n                        if (count > 0) {\n                            switch (p->type) {\n                                case TYPE_CHAR:\n                                case TYPE_BYTE:\n                                    in.read_char_array((Char *) p->data, count);\n                                    break;\n                                case TYPE_SHORT:\n                                    in.read_short_array((Short *) p->data, count);\n                                    break;\n                                case TYPE_LONG:\n                                    in.read_long_array((Long *) p->data, count);\n                                    break;\n                                case TYPE_LONGLONG:\n                                    in.read_llong_array((LongLong *) p->data, count);\n                                    break;\n                                case TYPE_FLOAT:\n                                    in.read_float_array((Float *) p->data, count);\n                                    break;\n                                case TYPE_DOUBLE:\n                                    in.read_double_array((Double *) p->data, count);\n                                    break;\n                                default:\n                                    break;\n                            }\n                        }\n                    }\n                    case -2://reserved!\n                        break;\n                    case -3://reserved!\n                        break;\n                    case -4://reserved!\n                        break;\n                    default:\n                        break;\n                }\n            }\n        }\n\n        if (n == len - 1) {\n            if (compare_crc && (unsigned int) p->ivalue != crc)\n                return ERR_CHECK_CRC_ERROR;\n        }\n    }\n\n    return ERR_OK;\n\n}\n\nint copy_fields(FIELD *dest, FIELD *src, bool only_header/*=false*/) {\n    int n = 0;\n    for (FIELD *p = src; p->type > 0; ++p, ++n) {\n        dest[n] = *p;\n        if (only_header && n == FIELD_BMARK - 1)\n            break;\n    }\n\n    if (!only_header)\n        dest[n].type = -1;\n\n    return n;\n}\n\n\nvoid fields_size(FIELD *fields, int *total, int *header, int *body, int *body_count) {\n    if (total) *total = 0;\n    if (header) *header = 0;\n    if (body) *body = 0;\n\n    int n = 0;\n    int cnt = fields[FIELD_COUNT].ivalue;\n\n    for (FIELD *p = fields; p->type >= 0; ++p, ++n) {\n        int size = 0;\n        switch (p->type) {\n            case TYPE_CHAR:\n            case TYPE_BYTE:\n                size = 1;\n                break;\n            case TYPE_SHORT:\n                size = 2;\n                break;\n            case TYPE_LONG:\n                size = 4;\n                break;\n            case TYPE_LONGLONG:\n                size = 8;\n                break;\n            case TYPE_FLOAT:\n                size = 4;\n                break;\n            case TYPE_DOUBLE:\n                size = 8;\n                break;\n            default:\n                break;\n        }\n\n        if (p->data != 0) {\n            if (p->count >= 0) {\n                size *= p->count * cnt;\n            } else {\n                //reserved!\n                switch (p->count) {\n                    case -1: {\n                        FIELD *prev = p - 1;\n                        if (prev->data == 0)\n                            size *= prev->ivalue;\n                        break;\n                    }\n                    case -2:\n                        break;\n                    case -3:\n                        break;\n                    case -4:\n                        break;\n                    default:\n                        break;\n                }\n            }\n        }\n\n        if (n == FIELD_NEXT) {\n            if (body_count)\n                *body_count = n;\n        }\n\n        if (total) {\n            *total += size;\n        }\n\n        if (n <= FIELD_HCRC) {\n            if (header)\n                *header += size;\n        } else {\n            if (body)\n                *body += size;\n        }\n    }\n\n    if (body_count)\n        *body_count = n - *body_count + 1;\n}\n", "meta": {"hexsha": "40a97e0d9ace97a1c38a98a58dad40a551d5aad1", "size": 14524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "protocol/packet_protocol.cpp", "max_stars_repo_name": "yorkart/asio_network", "max_stars_repo_head_hexsha": "dd5da8c4a339d76208872cc87af84e58cd3f5d42", "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": "protocol/packet_protocol.cpp", "max_issues_repo_name": "yorkart/asio_network", "max_issues_repo_head_hexsha": "dd5da8c4a339d76208872cc87af84e58cd3f5d42", "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": "protocol/packet_protocol.cpp", "max_forks_repo_name": "yorkart/asio_network", "max_forks_repo_head_hexsha": "dd5da8c4a339d76208872cc87af84e58cd3f5d42", "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.6382022472, "max_line_length": 88, "alphanum_fraction": 0.3615395208, "num_tokens": 2878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33807713081919877, "lm_q1q2_score": 0.1756382779249608}}
{"text": "//   Copyright 2015 Patrick Putnam\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 OFFSPRING_GENERATOR_HPP_\n#define OFFSPRING_GENERATOR_HPP_\n\n#include <boost/property_tree/ptree.hpp>\n\n#include \"clotho/cuda/curand_state_pool.hpp\"\n\n#include \"clotho/cuda/crossover/select_and_crossover_unordered_impl.hpp\"\n\n#include \"clotho/cuda/distributions/poisson_distribution.hpp\"\n#include \"clotho/recombination/recombination_rate_parameter.hpp\"\n\ntemplate < class PopulationType >\nclass OffspringGenerator {\npublic:\n\n    typedef PopulationType                                  population_type;\n    typedef typename population_type::real_type             real_type;\n    typedef typename population_type::int_type              int_type;\n    typedef typename population_type::order_tag_type        order_tag_type;\n\n    typedef typename population_type::allele_space_type::device_space_type     allele_space_type;\n\n    typedef basic_data_space< int_type >                    selection_type;\n\n    typedef clotho::cuda::curand_state_pool                 state_pool_type;\n\n    typedef recombination_rate_parameter< real_type > recombination_rate_type;\n    typedef poisson_cdf< real_type, 32 >                    poisson_type;\n\n    OffspringGenerator( boost::property_tree::ptree & config ) :\n        m_recomb_rate( config )\n    {\n        parse_configuration( config );\n        initialize();\n    }\n\n    void operator()( population_type * parent, selection_type * sel, population_type * offspring ) {\n\n        unsigned int bcount = state_pool_type::getInstance()->get_max_blocks();\n        unsigned int tcount = state_pool_type::getInstance()->get_max_threads();\n\n        select_and_crossover_kernel<<< bcount, tcount >>>( state_pool_type::getInstance()->get_device_states()\n                                                           , parent->sequences.get_device_space()\n                                                           , sel\n                                                           , parent->alleles.get_device_space()\n                                                           , offspring->free_space\n                                                           , dPoisCDF\n                                                           , offspring->sequences.get_device_space());\n    }\n\n    virtual ~OffspringGenerator() {\n        cudaFree( dPoisCDF );\n    }\n\nprotected:\n\n    void parse_configuration( boost::property_tree::ptree & config ) {\n        state_pool_type::getInstance()->initialize( config );\n    }\n\n    void initialize() {\n        assert( cudaMalloc( (void **) &dPoisCDF, sizeof( poisson_type) ) == cudaSuccess );\n\n        initialize_poisson( m_recomb_rate.m_rho, (order_tag_type *) NULL );\n    }\n\n    void initialize_poisson( real_type mean, unordered_tag * p ) {\n        real_type lambda = (mean / (real_type) allele_space_type::ALIGNMENT_SIZE);\n\n        make_poisson_cdf_maxk32<<< 1, 32 >>>( dPoisCDF, lambda );\n    }\n\n    void initialize_poisson( real_type mean, unit_ordered_tag< int_type > * p ) {\n        real_type lambda = (mean / 32.0);\n\n        make_poisson_cdf_maxk32<<< 1, 32 >>>( dPoisCDF, lambda );\n    }\n\n    poisson_type            * dPoisCDF;\n    recombination_rate_type m_recomb_rate;\n};\n\n#endif  // OFFSPRING_GENERATOR_HPP_\n", "meta": {"hexsha": "5fe471e5e07bd28a331dca9f55a74912e3908958", "size": 3778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clotho/cuda/crossover/offspring_generator.hpp", "max_stars_repo_name": "putnampp/clotho", "max_stars_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T21:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:26:54.000Z", "max_issues_repo_path": "include/clotho/cuda/crossover/offspring_generator.hpp", "max_issues_repo_name": "putnampp/clotho", "max_issues_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T21:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-23T12:41:00.000Z", "max_forks_repo_path": "include/clotho/cuda/crossover/offspring_generator.hpp", "max_forks_repo_name": "putnampp/clotho", "max_forks_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "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": 38.5510204082, "max_line_length": 110, "alphanum_fraction": 0.6334039174, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17563827446017283}}
{"text": "//! \u30d9\u30af\u30c8\u30eb\u30af\u30e9\u30b9\u57fa\u5e95\u30d8\u30c3\u30c0\n/*! 2-4\u6b21\u5143\u306e\u30d9\u30af\u30c8\u30eb\u3092\u30a2\u30e9\u30a4\u30f3\u30e1\u30f3\u30c8\u6709\u308a\u3068\u7121\u3057\u3067\u305d\u308c\u305e\u308c\u5b9a\u7fa9\n\t\u521d\u671f\u5316\u3084\u8981\u7d20\u6bce\u306e\u30a2\u30af\u30bb\u30b9\u306a\u3069\u57fa\u672c\u7684\u306a\u30e1\u30bd\u30c3\u30c9 */\n#if !BOOST_PP_IS_ITERATING\n\t#if !defined(VECTOR_H_) || INCLUDE_VECTOR_LEVEL >= 1\n\t\t#define VECTOR_H_\n\t\t#include <boost/preprocessor.hpp>\n\t\t#include <boost/operators.hpp>\n\t\t#include <boost/serialization/access.hpp>\n\t\t#include <boost/serialization/level.hpp>\n\t\t#include <boost/serialization/nvp.hpp>\n\t\t#include <cmath>\n\t\t#include \"spn_math.hpp\"\n\t\t#include \"tostring.hpp\"\n\t\t#include \"random/vector.hpp\"\n\n\t\t#define DEF_ARGPAIR(index,data,elem)\t(float BOOST_PP_CAT(f, elem))\n\t\t#define ENUM_ARGPAIR(subseq) BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_FOR_EACH(DEF_ARGPAIR, NOTHING, subseq))\n\t\t#define DEF_ARGSET(index,data,elem)\t\telem = BOOST_PP_CAT(f, elem);\n\t\t#define SEQ_VECELEM (x)(y)(z)(w)\n\n\t\t// \u8981\u6c42\u3055\u308c\u305f\u5b9a\u7fa9\u30ec\u30d9\u30eb\u3092\u5b9f\u4f53\u5316\n\t\t#ifndef INCLUDE_VECTOR_LEVEL\n\t\t\t#define INCLUDE_VECTOR_LEVEL 0\n\t\t#endif\n\t\t#define BOOST_PP_ITERATION_PARAMS_1 (4, (2,4, \"vector.hpp\", INCLUDE_VECTOR_LEVEL))\n\t\t#include BOOST_PP_ITERATE()\n\t\t#undef INCLUDE_VECTOR_LEVEL\n\t#endif\n#elif BOOST_PP_ITERATION_DEPTH() == 1\n\t// \u30a2\u30e9\u30a4\u30f3\u30e1\u30f3\u30c8\u30a4\u30c6\u30ec\u30fc\u30b7\u30e7\u30f3\n\t#define DIM\t\tBOOST_PP_FRAME_ITERATION(1)\n\t#define BOOST_PP_ITERATION_PARAMS_2 (4, (0,1, \"vector.hpp\", BOOST_PP_FRAME_FLAGS(1)))\n\t#include BOOST_PP_ITERATE()\n\t#undef DIM\n#else\n\t#define ALIGN\tBOOST_PP_ITERATION()\n\t#define ALIGNB\tBOOLNIZE(ALIGN)\n\t#define Vec\t\tBOOST_PP_IF(ALIGN, alignas(16), NOTHING) VecT<DIM, ALIGNB>\n\t#define VT\t\tVecT<DIM, ALIGNB>\n\t#include \"local_macro.hpp\"\n\t#if BOOST_PP_ITERATION_FLAGS() == 0\n\t\t// \u30af\u30e9\u30b9\u306e\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u3068\u30e1\u30bd\u30c3\u30c9\u306e\u30d7\u30ed\u30c8\u30bf\u30a4\u30d7\u3060\u3051\u5b9a\u7fa9\n\t\tnamespace spn {\n\t\t\tclass MTRandom;\n\t\t\ttemplate <>\n\t\t\tstruct Vec {\n\t\t\t\tconstexpr static int width = DIM;\n\t\t\t\tconstexpr static bool align = ALIGNB;\n\t\t\t\tusing AVec = VecT<DIM,true>;\n\t\t\t\tusing UVec = VecT<DIM,false>;\n\t\t\t\tunion {\n\t\t\t\t\tstruct {\n\t\t\t\t\t\tfloat BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_SUBSEQ(SEQ_VECELEM, 0, DIM));\n\t\t\t\t\t};\n\t\t\t\t\tfloat m[DIM];\n\t\t\t\t};\n\n\t\t\t\tfriend class boost::serialization::access;\n\t\t\t\ttemplate <class Archive>\n\t\t\t\tvoid serialize(Archive& ar, const unsigned int /*ver*/) {\n\t\t\t\t\tar & BOOST_SERIALIZATION_NVP(m);\n\t\t\t\t}\n\n\t\t\t\t// -------------------- ctor --------------------\n\t\t\t\tVecT() = default;\n\t\t\t\texplicit VecT(reg128 r);\n\t\t\t\texplicit VecT(float a);\n\t\t\t\texplicit VecT(ENUM_ARGPAIR(BOOST_PP_SEQ_SUBSEQ(SEQ_VECELEM, 0, DIM)));\n\t\t\t\ttemplate <class V, class=std::enable_if_t<std::is_floating_point<V>::value>>\n\t\t\t\texplicit VecT(const V* src);\n\t\t\t\tVecT(std::initializer_list<float> il);\n\t\t\t\treg128 loadPS() const;\n\t\t\t\treg128 loadPSZ() const;\n\n\t\t\t\t//! \u30a2\u30e9\u30a4\u30f3\u30e1\u30f3\u30c8\u6e08\u30d9\u30af\u30c8\u30eb\u3067\u521d\u671f\u5316\n\t\t\t\tVecT(const AVec& v);\n\t\t\t\t//! \u30a2\u30e9\u30a4\u30f3\u30e1\u30f3\u30c8\u7121\u3057\u30d9\u30af\u30c8\u30eb\u3067\u521d\u671f\u5316\n\t\t\t\tVecT(const UVec& v);\n\t\t\t\tVecT& operator = (const AVec& v);\n\t\t\t\tVecT& operator = (const UVec& v);\n\t\t\t\tVecT& operator = (reg128 r);\n\t\t\t\tVecT& operator = (std::initializer_list<float> il);\n\t\t\t\t// -------------------- operators --------------------\n\t\t\t\t// \u30d9\u30af\u30c8\u30eb\u3068\u306e\u7a4d\u7b97\u3084\u9664\u7b97\u306f\u540c\u3058\u8981\u7d20\u540c\u58eb\u306e\u6f14\u7b97\u3068\u3059\u308b\n\t\t\t\t#define DEF_PRE(op, func)\tVecT& operator BOOST_PP_CAT(op,=) (float s); \\\n\t\t\t\t\tVecT operator op (float s) const; \\\n\t\t\t\t\tVecT& operator BOOST_PP_CAT(op,=) (const AVec& v); \\\n\t\t\t\t\tVecT& operator BOOST_PP_CAT(op,=) (const UVec& v); \\\n\t\t\t\t\tAVec operator op (const AVec& v) const; \\\n\t\t\t\t\tUVec operator op (const UVec& v) const; \\\n\t\t\t\t\tAVec&& operator op (AVec&& v) const; \\\n\t\t\t\t\tUVec&& operator op (UVec&& v) const; \\\n\t\t\t\t\tfriend VecT operator op (float fv, const VecT& v);\n\t\t\t\tDEF_PRE(+, reg_add_ps)\n\t\t\t\tDEF_PRE(-, reg_sub_ps)\n\t\t\t\tDEF_PRE(*, reg_mul_ps)\n\t\t\t\tDEF_PRE(/, _mmDivPs)\n\n\t\t\t\t// -------- Lua\u3078\u306e\u30a8\u30af\u30b9\u30dd\u30fc\u30c8\u7528 --------\n\t\t\t\tVecT addV(const UVec& v) const;\n\t\t\t\tVecT subV(const UVec& v) const;\n\t\t\t\tVecT mulF(float s) const;\n\t\t\t\tVecT mulM(const MatT<DIM,DIM,align>& m) const;\n\t\t\t\tVecT divF(float s) const;\n\t\t\t\tVecT invert() const;\n\t\t\t\tbool equal(const UVec& v) const;\n\t\t\t\tstd::string toString() const;\n\n\t\t\t\tfriend std::ostream& operator << (std::ostream& os, const VT& v);\n\t\t\t\t// -------------------- others --------------------\n\t\t\t\tstatic float _sumup(reg128 xm);\n\t\t\t\t// \u30ed\u30fc\u30c9\u95a2\u6570\u547c\u3073\u51fa\u3057\u306e\u30b3\u30b9\u30c8\u304c\u8a31\u5bb9\u51fa\u6765\u308b\u30b1\u30fc\u30b9\u3067\u306floadPS()\u3092\u547c\u3073\u3001\u305d\u3046\u3067\u306a\u3044\u30b1\u30fc\u30b9\u306f\u30aa\u30fc\u30d0\u30fc\u30ed\u30fc\u30c9\u3067\u5bfe\u51e6\n\t\t\t\ttemplate <bool A>\n\t\t\t\tfloat dot(const VecT<DIM,A>& v) const;\n\t\t\t\t//! \u5404\u8981\u7d20\u3092\u8db3\u3057\u3042\u308f\u305b\u305f\u5408\u8a08\n\t\t\t\tfloat sum() const;\n\t\t\t\t//! \u5404\u8981\u7d20\u306e\u7b97\u8853\u5e73\u5747\n\t\t\t\tfloat average() const;\n\t\t\t\ttemplate <bool A>\n\t\t\t\tfloat distance(const VecT<DIM,A>& v) const;\n\t\t\t\ttemplate <bool A>\n\t\t\t\tfloat dist_sq(const VecT<DIM,A>& v) const;\n\n\t\t\t\t//! \u8981\u7d20\u3054\u3068\u306b\u6700\u5c0f\u5024\u9078\u629e\n\t\t\t\ttemplate <bool A>\n\t\t\t\tVecT getMin(const VecT<DIM,A>& v) const;\n\t\t\t\ttemplate <bool A>\n\t\t\t\tvoid selectMin(const VecT<DIM,A>& v);\n\n\t\t\t\t//! \u8981\u7d20\u3054\u3068\u306b\u6700\u5927\u5024\u9078\u629e\n\t\t\t\ttemplate <bool A>\n\t\t\t\tVecT getMax(const VecT<DIM,A>& v) const;\n\t\t\t\ttemplate <bool A>\n\t\t\t\tvoid selectMax(const VecT<DIM,A>& v);\n\n\t\t\t\tVecT operator - () const;\n\n\t\t\t\t/*! \\return \u8981\u7d20\u304c\u5168\u3066\u7b49\u3057\u3044\u6642\u306btrue, \u305d\u308c\u4ee5\u5916\u306ffalse */\n\t\t\t\ttemplate <bool A>\n\t\t\t\tbool operator == (const VecT<DIM,A>& v) const;\n\t\t\t\ttemplate <bool A>\n\t\t\t\tbool operator != (const VecT<DIM,A>& v) const;\n\n\t\t\t\tfloat normalize();\n\t\t\t\tVecT normalization() const;\n\t\t\t\t/*! \\return \u30d9\u30af\u30c8\u30eb\u306e\u9577\u3055 */\n\t\t\t\tfloat length() const;\n\t\t\t\t/*! \\return \u30d9\u30af\u30c8\u30eb\u9577\u306e2\u4e57 */\n\t\t\t\tfloat len_sq() const;\n\t\t\t\t//! \u8981\u7d20\u306e\u4f55\u308c\u304b\u304cNaN\u306b\u306a\u3063\u3066\u3044\u308b\u304b\n\t\t\t\tbool isNaN() const;\n\t\t\t\t//! \u8981\u7d20\u306e\u4f55\u308c\u304b\u304cNaN\u53c8\u306finf\u306b\u306a\u3063\u3066\u3044\u308b\u304b\n\t\t\t\tbool isOutstanding() const;\n\n\t\t\t\tvoid saturate(float fMin, float fMax);\n\t\t\t\tVecT saturation(float fMin, float fMax) const;\n\t\t\t\tvoid lerp(const UVec& v, float r);\n\t\t\t\ttemplate <bool A>\n\t\t\t\tVecT l_intp(const VecT<DIM,A>& v, float r) const;\n\n\t\t\t\t//! \u8981\u7d20\u306e\u5024\u304c\u30e9\u30f3\u30c0\u30e0\u306a\u30d9\u30af\u30c8\u30eb\n\t\t\t\ttemplate <class RDF>\n\t\t\t\tstatic VecT Random(const RDF& rdf, const RangeF& r=random::DefaultRVecRange) {\n\t\t\t\t\treturn random::GenRVec<VecT>(rdf, r);\n\t\t\t\t}\n\t\t\t\ttemplate <class RDF>\n\t\t\t\tstatic VecT RandomF(const RDF& rdf) {\n\t\t\t\t\treturn random::GenRVecF<VecT>(rdf);\n\t\t\t\t}\n\t\t\t\t//! \u30e9\u30f3\u30c0\u30e0\u306a\u30d9\u30af\u30c8\u30eb\uff08\u4f46\u3057\u9577\u3055\u304c\u6307\u5b9a\u5024\u3088\u308a\u5927\u304d\u3044\uff09\n\t\t\t\ttemplate <class RDF>\n\t\t\t\tstatic VecT RandomWithLength(const RDF& rdf, float th, const RangeF& r=random::DefaultRVecRange) {\n\t\t\t\t\treturn random::GenRVecLen<VecT>(rdf, th, r);\n\t\t\t\t}\n\t\t\t\t//! \u30e9\u30f3\u30c0\u30e0\u306a\u30d9\u30af\u30c8\u30eb (\u4f46\u3057\u5168\u3066\u306e\u6210\u5206\u306e\u7d76\u5bfe\u5024\u304c\u305d\u308c\u305e\u308c\u57fa\u6e96\u7bc4\u56f2\u5185)\n\t\t\t\ttemplate <class RDF>\n\t\t\t\tstatic VecT RandomWithAbs(const RDF& rdf, const RangeF& rTh, const RangeF& r=random::DefaultRVecRange) {\n\t\t\t\t\treturn random::GenRVecAbs<VecT>(rdf, rTh, r);\n\t\t\t\t}\n\t\t\t\t//! \u30e9\u30f3\u30c0\u30e0\u306a\u65b9\u5411\u30d9\u30af\u30c8\u30eb\n\t\t\t\ttemplate <class RDF>\n\t\t\t\tstatic VecT RandomDir(const RDF& rdf) {\n\t\t\t\t\treturn random::GenRDir<VecT>(rdf);\n\t\t\t\t}\n\t\t\t\t// -------- Lua\u3078\u306e\u30a8\u30af\u30b9\u30dd\u30fc\u30c8\u7528 --------\n\t\t\t\tstatic VecT luaRandom(MTRandom& mt, const RangeF& r);\n\t\t\t\tstatic VecT luaRandomWithLength(MTRandom& mt, float th, const RangeF& r);\n\t\t\t\tstatic VecT luaRandomWithAbs(MTRandom& mt, const RangeF& rTh, const RangeF& r);\n\t\t\t\t#if ALIGN==1\n\t\t\t\t\t//! AVec -> Vec \u3078\u6697\u9ed9\u5909\u63db\n\t\t\t\t\toperator VecT<DIM,false>& ();\n\t\t\t\t\toperator const VecT<DIM,false>& () const;\n\t\t\t\t#endif\n\t\t\t\t#if DIM==4\n\t\t\t\t\tusing Vec3 = VecT<3,ALIGNB>;\n\t\t\t\t\t/*! \\return x,y,z\u6210\u5206 */\n\t\t\t\t\tconst Vec3& asVec3() const;\n\t\t\t\t\t/*! \\return x,y,z\u305d\u308c\u305e\u308c\u3092w\u3067\u5272\u3063\u305f\u5024 */\n\t\t\t\t\tVec3 asVec3Coord() const;\n\t\t\t\t#elif DIM==3\n\t\t\t\t\t//! \u30d9\u30af\u30c8\u30eb\u306b\u5782\u76f4\u306a\u30d9\u30af\u30c8\u30eb\u3092\u9069\u5f53\u306b\u5b9a\u3081\u308b\n\t\t\t\t\tVecT verticalVector() const;\n\t\t\t\t\t/*! \\return this X v \u306e\u5916\u7a4d\u30d9\u30af\u30c8\u30eb */\n\t\t\t\t\ttemplate <bool A>\n\t\t\t\t\tVecT cross(const VecT<DIM,A>& v) const;\n\t\t\t\t\t//! \u5916\u7a4d\u8a08\u7b97cross()\u3068\u540c\u7fa9\n\t\t\t\t\ttemplate <bool A>\n\t\t\t\t\tvoid operator %= (const VecT<DIM,A>& v);\n\t\t\t\t\t//! \u5916\u7a4d\u8a08\u7b97cross()\u3068\u540c\u7fa9\n\t\t\t\t\ttemplate <bool A>\n\t\t\t\t\tVecT operator % (const VecT<DIM,A>& v) const;\n\t\t\t\t\tusing Vec4 = VecT<4,ALIGNB>;\n\t\t\t\t\tVec4 asVec4(float w) const;\n\t\t\t\t\t//! \u5e73\u9762\u3068\u306e\u4ea4\u5dee\u70b9\u3092\u7b97\u51fa\n\t\t\t\t\ttemplate <bool A>\n\t\t\t\t\tstd::tuple<VecT,bool> planeDivide(const VecT<DIM,A>& v, const PlaneT<false>& p) const;\n\t\t\t\t\t//! \u5e73\u9762\u306b\u3066\u30d9\u30af\u30c8\u30eb\u3092\u53cd\u8ee2\n\t\t\t\t\tvoid flip(const PlaneT<false>& plane);\n\t\t\t\t\tVecT& operator *= (const QuatT<ALIGNB>& q);\n\t\t\t\t\tVecT operator * (const QuatT<ALIGNB>& q) const;\n\t\t\t\t\tVecT&& operator * (QuatT<ALIGNB>&& q) const;\n\t\t\t\t\t/*! \\return x,y \u6210\u5206 */\n\t\t\t\t\tconst VecT<2,ALIGNB>& asVec2() const;\n\t\t\t\t\t// -------- Lua\u3078\u306e\u30a8\u30af\u30b9\u30dd\u30fc\u30c8\u7528 --------\n\t\t\t\t\tVecT modV(const UVec& v) const;\n\t\t\t\t\tVecT mulQ(const QuatT<ALIGNB>& q) const;\n\t\t\t\t\tstd::tuple<VecT,bool> luaPlaneDivide(const VecT<DIM,false>& v, const PlaneT<false>& p) const;\n\t\t\t\t#elif DIM==2\n\t\t\t\t\tfloat ccw(const VecT<DIM,false>& v) const;\n\t\t\t\t\tfloat cw(const VecT<DIM,false>& v) const;\n\t\t\t\t\t#if ALIGN==0\n\t\t\t\t\t\tstatic float Ccw(const UVec& v0, const UVec& v1, const UVec& v2);\n\t\t\t\t\t\tstatic float Cw(const UVec& v0, const UVec& v1, const UVec& v2);\n\t\t\t\t\t#endif\n\t\t\t\t\tusing Vec3 = VecT<3,ALIGNB>;\n\t\t\t\t\tVec3 asVec3(float z) const;\n\t\t\t\t#endif\n\t\t\t\t//! \u884c\u5217\u3068\u306e\u7a4d\u7b97 (\u5de6\u304b\u3089\u639b\u3051\u308b)\n\t\t\t\t/*! \u884c\u30d9\u30af\u30c8\u30eb\u3068\u3057\u3066\u6271\u3046 */\n\t\t\t\ttemplate <int N, bool A>\n\t\t\t\tVecT<N,ALIGNB> operator * (const MatT<DIM,N,A>& m) const;\n\t\t\t\ttemplate <int N, bool A>\n\t\t\t\tVecT& operator *= (const MatT<DIM,N,A>& m);\n\n\t\t\t\t#if DIM>=3\n\t\t\t\t\t//! \u30d1\u30c3\u30af\u3055\u308c\u305f32bit\u6570\u5024\u304b\u3089\u8272\u3092\u53d6\u308a\u51fa\u3059\n\t\t\t\t\tstatic VecT FromPacked(uint32_t val);\n\t\t\t\t\t//! 32bit\u6570\u5024\u306b\u5024\u3092\u30d1\u30c3\u30af (1.0\u304c255)\n\t\t\t\t\tuint32_t toPacked() const;\n\t\t\t\t#endif\n\t\t\t};\n\t\t\t#undef Vec\n\t\t\t// \u4f7f\u3044\u3084\u3059\u3044\u3088\u3046\u306b\u30af\u30e9\u30b9\u306e\u5225\u540d\u3092\u5b9a\u7fa9\n\t\t\tusing BOOST_PP_CAT(BOOST_PP_IF(ALIGN,A,NOTHING), BOOST_PP_CAT(Vec,DIM)) = VT;\n\t\t}\n\t\tBOOST_CLASS_IMPLEMENTATION(spn::VT, object_serializable)\n\t\t#elif BOOST_PP_ITERATION_FLAGS() == 1\n\t\t// \u540c\u6b21\u5143\u30d9\u30af\u30c8\u30eb\u3068\u306e\u6f14\u7b97\u3092\u5b9a\u7fa9\n\t\tnamespace spn {\n\t\t\tVT::VecT(reg128 r){\n\t\t\t\tSTORETHIS(r);\n\t\t\t}\n\t\t\tVT::VecT(float a) {\n\t\t\t\tSTORETHIS(reg_load1_ps(&a));\n\t\t\t}\n\t\t\tVT::VecT(ENUM_ARGPAIR(BOOST_PP_SEQ_SUBSEQ(SEQ_VECELEM, 0, DIM))) {\n\t\t\t\tBOOST_PP_SEQ_FOR_EACH(\n\t\t\t\t\tDEF_ARGSET,\n\t\t\t\t\tNOTHING,\n\t\t\t\t\tBOOST_PP_SEQ_SUBSEQ(SEQ_VECELEM, 0, DIM)\n\t\t\t\t)\n\t\t\t}\n\t\t\ttemplate <class V, class>\n\t\t\tVT::VecT(const V* src) {\n\t\t\t\tfor(int i=0 ; i<DIM ; i++)\n\t\t\t\t\tm[i] = src[i];\n\t\t\t}\n\t\t\ttemplate VT::VecT(const float*);\n\t\t\ttemplate VT::VecT(const double*);\n\t\t\tVT::VecT(std::initializer_list<float> il) {\n\t\t\t\t// \u8981\u7d20\u6570\u304c\u6e80\u305f\u306a\u304b\u3063\u305f\u3089\u6b8b\u308a\u306f0\u306b\u3059\u308b\n\t\t\t\talignas(16) float tmp[4] = {};\n\t\t\t\tauto* pTmp = tmp;\n\t\t\t\tfor(auto itr=il.begin() ; itr!=il.end() ; ++itr)\n\t\t\t\t\t*pTmp++ = *itr;\n\t\t\t\tSTORETHIS(reg_load_ps(tmp));\n\t\t\t}\n\t\t\treg128 VT::loadPS() const {\n\t\t\t\treturn LOADTHIS();\n\t\t\t}\n\t\t\treg128 VT::loadPSZ() const {\n\t\t\t\treturn LOADTHISZ();\n\t\t\t}\n\t\t\tVT& VT::operator = (reg128 r) {\n\t\t\t\tSTORETHIS(r);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tVT& VT::operator = (std::initializer_list<float> il) {\n\t\t\t\treturn *this = VecT(il);\n\t\t\t}\n\t\t\tfloat VT::_sumup(reg128 xm) {\n\t\t\t\tSUMVEC(xm)\n\t\t\t\tfloat ret;\n\t\t\t\treg_store_ss(&ret, xm);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tVT::VecT(const AVec& v) {\n\t\t\t\tSTORETHIS(LOADPS(v.m)); }\n\t\t\tVT::VecT(const UVec& v) {\n\t\t\t\tSTORETHIS(LOADPSU(v.m)); }\n\t\t\tbool VT::isNaN() const {\n\t\t\t\treg128 r0 = LOADTHISZ(),\n\t\t\t\t\tr_zero = reg_setzero_ps();\n\t\t\t\treg128 res = reg_or_ps(reg_cmple_ps(r0, r_zero),\n\t\t\t\t\t\t\t\t\t\treg_cmpgt_ps(r0, r_zero));\n\t\t\t\tres = reg_andnot_ps(res, xmm_const::fullbit());\n\t\t\t\tSUMVEC(res)\n\t\t\t\tfloat f;\n\t\t\t\treg_store_ss(&f, res);\n\t\t\t\treturn f != 0;\n\t\t\t}\n\t\t\tbool VT::isOutstanding() const {\n\t\t\t\tconst float f = std::numeric_limits<float>::infinity();\n\t\t\t\treg128 r_inf = reg_load1_ps(&f),\n\t\t\t\t\t\tr_zero = reg_setzero_ps(),\n\t\t\t\t\t\tr0 = reg_and_ps(LOADTHIS(), xmm_const::absmask());\n\t\t\t\treg128 r1 = reg_or_ps(reg_cmple_ps(r0, r_zero),\n\t\t\t\t\t\t\t\t\treg_cmpgt_ps(r0, r_zero));\n\t\t\t\tr0 = reg_cmpeq_ps(r0, r_inf);\n\n\t\t\t\tr1 = reg_andnot_ps(r1, xmm_const::fullbit());\n\t\t\t\tr0 = reg_or_ps(r0, r1);\n\t\t\t\tSUMVEC(r0)\n\n\t\t\t\tfloat fv;\n\t\t\t\treg_store_ss(&fv, r0);\n\t\t\t\treturn fv != 0;\n\t\t\t}\n\n\t\t\tVT& VT::operator = (const AVec& v) {\n\t\t\t\tSTORETHIS(LOADPS(v.m));\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tVT& VT::operator = (const UVec& v) {\n\t\t\t\tSTORETHIS(LOADPSU(v.m));\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\t#define DEF_OP(op, func) \\\n\t\t\t\t\tVT& VT::operator BOOST_PP_CAT(op,=) (float s) { \\\n\t\t\t\t\t\tSTORETHIS(func(LOADTHIS(), reg_load_ps1(&s))); \\\n\t\t\t\t\t\treturn *this; } \\\n\t\t\t\t\tVT VT::operator op (float s) const { \\\n\t\t\t\t\t\treturn VecT(func(LOADTHIS(), reg_load1_ps(&s))); } \\\n\t\t\t\t\tVT& VT::operator BOOST_PP_CAT(op,=) (const AVec& v) { \\\n\t\t\t\t\t\tSTORETHIS(func(LOADTHIS(), LOADPS(v.m))); \\\n\t\t\t\t\t\treturn *this; } \\\n\t\t\t\t\tVT& VT::operator BOOST_PP_CAT(op,=) (const UVec& v) { \\\n\t\t\t\t\t\tSTORETHIS(func(LOADTHIS(), LOADPSU(v.m))); \\\n\t\t\t\t\t\treturn *this; } \\\n\t\t\t\t\tVT::AVec VT::operator op (const AVec& v) const { \\\n\t\t\t\t\t\treturn AVec(func(LOADTHIS(), LOADPS(v.m))); } \\\n\t\t\t\t\tVT::UVec VT::operator op (const UVec& v) const { \\\n\t\t\t\t\t\treturn UVec(func(LOADTHIS(), LOADPSU(v.m))); } \\\n\t\t\t\t\tVT::AVec&& VT::operator op (AVec&& v) const { \\\n\t\t\t\t\t\tSTOREPS(v.m, func(LOADTHIS(), LOADPS(v.m))); \\\n\t\t\t\t\t\treturn std::forward<AVec>(v); } \\\n\t\t\t\t\tVT::UVec&& VT::operator op (UVec&& v) const { \\\n\t\t\t\t\t\tSTOREPSU(v.m, func(LOADTHIS(), LOADPSU(v.m))); \\\n\t\t\t\t\t\treturn std::forward<UVec>(v); } \\\n\t\t\t\t\tVT operator op (float fv, const VT& v) { \\\n\t\t\t\t\t\treturn VT(func(LOADTHISPS(v.m), reg_load1_ps(&fv))); }\n\t\t\tDEF_OP(+, reg_add_ps)\n\t\t\tDEF_OP(-, reg_sub_ps)\n\t\t\tDEF_OP(*, reg_mul_ps)\n\t\t\tDEF_OP(/, _mmDivPs)\n\t\t\t#undef DEF_OP\n\t\t\tVT VT::addV(const UVec& v) const {\n\t\t\t\treturn *this + v; }\n\t\t\tVT VT::subV(const UVec& v) const {\n\t\t\t\treturn *this - v; }\n\t\t\tVT VT::mulF(float s) const {\n\t\t\t\treturn *this * s; }\n\t\t\tVT VT::mulM(const MatT<DIM,DIM,align>& m) const {\n\t\t\t\treturn *this * m; }\n\t\t\tVT VT::divF(float s) const {\n\t\t\t\treturn *this / s; }\n\t\t\tVT VT::invert() const {\n\t\t\t\treturn -(*this); }\n\t\t\tbool VT::equal(const UVec& v) const {\n\t\t\t\treturn *this == v; }\n\t\t\tstd::string VT::toString() const {\n\t\t\t\treturn ToString(*this);\n\t\t\t}\n\n\t\t\tstd::ostream& operator << (std::ostream& os, const VT& v) {\n\t\t\t\tos << BOOST_PP_IF(ALIGN, 'A', ' ') << \"Vec\" << DIM << '[';\n\t\t\t\tfor(int i=0 ; i<DIM-1 ; i++)\n\t\t\t\t\tos << v.m[i] << ',';\n\t\t\t\treturn os << v.m[DIM-1] << ']';\n\t\t\t}\n\n\t\t\ttemplate <bool A>\n\t\t\tfloat VT::dot(const VecT<DIM,A>& v) const {\n\t\t\t\treturn _sumup(reg_mul_ps(LOADTHISZ(), v.loadPSZ()));\n\t\t\t}\n\t\t\ttemplate float VT::dot(const VecT<DIM,false>& v) const;\n\t\t\ttemplate float VT::dot(const VecT<DIM,true>& v) const;\n\n\t\t\tfloat VT::sum() const {\n\t\t\t\treturn _sumup(LOADTHISZ());\n\t\t\t}\n\t\t\tfloat VT::average() const {\n\t\t\t\treturn sum() * spn::Rcp22Bit(DIM);\n\t\t\t}\n\t\t\ttemplate <bool A>\n\t\t\tfloat VT::distance(const VecT<DIM,A>& v) const {\n\t\t\t\treturn std::sqrt(dist_sq(v));\n\t\t\t}\n\t\t\ttemplate float VT::distance(const VecT<DIM,false>&) const;\n\t\t\ttemplate float VT::distance(const VecT<DIM,true>&) const;\n\n\t\t\ttemplate <bool A>\n\t\t\tfloat VT::dist_sq(const VecT<DIM,A>& v) const {\n\t\t\t\tauto tv = v - *this;\n\t\t\t\treturn tv.len_sq();\n\t\t\t}\n\t\t\ttemplate float VT::dist_sq(const VecT<DIM,false>&) const;\n\t\t\ttemplate float VT::dist_sq(const VecT<DIM,true>&) const;\n\n\t\t\ttemplate <bool A>\n\t\t\tVT VT::getMin(const VecT<DIM,A>& v) const {\n\t\t\t\treturn VT(reg_min_ps(LOADTHIS(), v.loadPS())); }\n\t\t\ttemplate VT VT::getMin(const VecT<DIM,false>&) const;\n\t\t\ttemplate VT VT::getMin(const VecT<DIM,true>&) const;\n\n\t\t\ttemplate <bool A>\n\t\t\tvoid VT::selectMin(const VecT<DIM,A>& v) {\n\t\t\t\tSTORETHIS(reg_min_ps(LOADTHIS(), v.loadPS())); }\n\t\t\ttemplate void VT::selectMin(const VecT<DIM,false>&);\n\t\t\ttemplate void VT::selectMin(const VecT<DIM,true>&);\n\n\t\t\ttemplate <bool A>\n\t\t\tVT VT::getMax(const VecT<DIM,A>& v) const {\n\t\t\t\treturn VT(reg_max_ps(LOADTHIS(), v.loadPS())); }\n\t\t\ttemplate VT VT::getMax(const VecT<DIM,false>&) const;\n\t\t\ttemplate VT VT::getMax(const VecT<DIM,true>&) const;\n\n\t\t\ttemplate <bool A>\n\t\t\tvoid VT::selectMax(const VecT<DIM,A>& v) {\n\t\t\t\tSTORETHIS(reg_max_ps(LOADTHIS(), v.loadPS())); }\n\t\t\ttemplate void VT::selectMax(const VecT<DIM,false>&);\n\t\t\ttemplate void VT::selectMax(const VecT<DIM,true>&);\n\n\t\t\tVT VT::operator - () const {\n\t\t\t\treturn *this * -1.0f;\n\t\t\t}\n\n\t\t\ttemplate <bool A>\n\t\t\tbool VT::operator == (const VecT<DIM,A>& v) const {\n\t\t\t\treg128 r0 = reg_cmpeq_ps(LOADTHISZ(), v.loadPSZ());\n\t\t\t\tr0 = reg_and_ps(r0, reg_shuffle_ps(r0, r0, _REG_SHUFFLE(1,0,3,2)));\n\t\t\t\tr0 = reg_and_ps(r0, reg_shuffle_ps(r0, r0, _REG_SHUFFLE(0,1,2,3)));\n\t\t\t\treturn reg_cvttss_si32(r0) != 0;\n\t\t\t}\n\t\t\ttemplate <bool A>\n\t\t\tbool VT::operator != (const VecT<DIM,A>& v) const {\n\t\t\t\treturn !(this->operator == (v));\n\t\t\t}\n\t\t\ttemplate bool VT::operator == (const VecT<DIM,false>&) const;\n\t\t\ttemplate bool VT::operator == (const VecT<DIM,true>&) const;\n\t\t\ttemplate bool VT::operator != (const VecT<DIM,false>&) const;\n\t\t\ttemplate bool VT::operator != (const VecT<DIM,true>&) const;\n\n\t\t\tfloat VT::normalize() {\n\t\t\t\tfloat len = length();\n\t\t\t\t*this *= spn::Rcp22Bit(len);\n\t\t\t\treturn len;\n\t\t\t}\n\t\t\tVT VT::normalization() const {\n\t\t\t\tfloat tmp = length();\n\t\t\t\treg128 r0 = reg_load_ps1(&tmp);\n\t\t\t\tr0 = reg_div_ps(LOADTHIS(), r0);\n\t\t\t\treturn VT(r0);\n\t\t\t}\n\t\t\t/*! \\return \u30d9\u30af\u30c8\u30eb\u306e\u9577\u3055 */\n\t\t\tfloat VT::length() const {\n\t\t\t\treturn std::sqrt(len_sq());\n\t\t\t}\n\t\t\t/*! \\return \u30d9\u30af\u30c8\u30eb\u9577\u306e2\u4e57 */\n\t\t\tfloat VT::len_sq() const {\n\t\t\t\treg128 r0 = LOADTHISZ();\n\t\t\t\tr0 = reg_mul_ps(r0, r0);\n\t\t\t\tSUMVEC(r0)\n\n\t\t\t\tfloat ret;\n\t\t\t\treg_store_ss(&ret, r0);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tvoid VT::saturate(float fMin, float fMax) {\n\t\t\t\t*this = saturation(fMin, fMax);\n\t\t\t}\n\t\t\tVT VT::saturation(float fMin, float fMax) const {\n\t\t\t\treg128 xm = reg_max_ps(LOADTHIS(), reg_load1_ps(&fMin));\n\t\t\t\treturn VT(reg_min_ps(xm, reg_load1_ps(&fMax)));\n\t\t\t}\n\t\t\tvoid VT::lerp(const UVec& v, float r) {\n\t\t\t\t*this = l_intp(v,r);\n\t\t\t}\n\t\t\ttemplate <bool A>\n\t\t\tVT VT::l_intp(const VecT<DIM,A>& v, float r) const {\n\t\t\t\treg128 ths = LOADTHIS();\n\t\t\t\tths = reg_add_ps(ths, reg_mul_ps(reg_sub_ps(v.loadPS(), ths), reg_load1_ps(&r)));\n\t\t\t\treturn VT(ths);\n\t\t\t}\n\t\t\ttemplate VT VT::l_intp(const VecT<DIM,false>&, float) const;\n\t\t\ttemplate VT VT::l_intp(const VecT<DIM,true>&, float) const;\n\n\t\t\t#if DIM>=3\n\t\t\t\tVT VT::FromPacked(uint32_t val) {\n\t\t\t\t\talignas(16) const uint32_t tmp[4] = {val, val>>8, val>>16, val>>24};\n\t\t\t\t\talignas(16) const uint32_t mask[4] = {0xff,0xff,0xff,0xff};\n\n\t\t\t\t\treg128 x = reg_and_ps(reg_load_ps((const float*)mask), reg_load_ps((const float*)tmp));\n\t\t\t\t\tx = reg_cvtepi32_ps((reg128i)x);\n\n\t\t\t\t\tconst float f255 = 1.f/255;\n\t\t\t\t\tx = reg_mul_ps(x, reg_load1_ps(&f255));\n\t\t\t\t\treturn VecT(x);\n\t\t\t\t}\n\t\t\t\tuint32_t VT::toPacked() const {\n\t\t\t\t\treg128 x = reg_mul_ps(reg_set_ps(255,255,255,255), LOADTHISZ());\n\t\t\t\t\treg128i x2 = reg_cvtps_epi32(x);\n\t\t\t\t\tx2 = reg_packs_epi32(x2,x2);\n\t\t\t\t\tx2 = reg_packus_epi16(x2,x2);\n\t\t\t\t\tfloat ret;\n\t\t\t\t\treg_store_ss(&ret, (reg128)x2);\n\t\t\t\t\treturn *reinterpret_cast<uint32_t*>(&ret);\n\t\t\t\t}\n\t\t\t#endif\n\t\t}\n\t#elif BOOST_PP_ITERATION_FLAGS() == 2\n\t\t// \u4ed6\u6b21\u5143\u30d9\u30af\u30c8\u30eb\u3068\u306e\u6f14\u7b97\u3092\u5b9a\u7fa9\n\t\tnamespace spn {\n\t\t\t#if ALIGN==1\n\t\t\t\t//! AVec -> Vec \u3078\u6697\u9ed9\u5909\u63db\n\t\t\t\tVT::operator VecT<DIM,false>& () { return *reinterpret_cast<VecT<DIM,false>*>(this); }\n\t\t\t\tVT::operator const VecT<DIM,false>& () const { return *reinterpret_cast<const VecT<DIM,false>*>(this); }\n\t\t\t#endif\n\t\t\t#if DIM==4\n\t\t\t\t#define _Vec3 VecT<3,ALIGNB>\n\t\t\t\t/*! \\return x,y,z\u6210\u5206 */\n\t\t\t\tconst _Vec3& VT::asVec3() const {\n\t\t\t\t\treturn reinterpret_cast<const _Vec3&>(*this);\n\t\t\t\t}\n\t\t\t\t/*! \\return x,y,z\u305d\u308c\u305e\u308c\u3092w\u3067\u5272\u3063\u305f\u5024 */\n\t\t\t\t_Vec3 VT::asVec3Coord() const {\n\t\t\t\t\treg128 r0 = reg_rcp_ps(reg_load_ps1(&w));\n\t\t\t\t\treturn _Vec3(reg_mul_ps(LOADTHIS(), r0));\n\t\t\t\t}\n\t\t\t#elif DIM==3\n\t\t\t\tconst VecT<2,ALIGNB>& VT::asVec2() const {\n\t\t\t\t\treturn reinterpret_cast<const VecT<2,ALIGNB>&>(*this);\n\t\t\t\t}\n\t\t\t\t//! \u30d9\u30af\u30c8\u30eb\u306b\u5782\u76f4\u306a\u30d9\u30af\u30c8\u30eb\u3092\u9069\u5f53\u306b\u5b9a\u3081\u308b\n\t\t\t\tVT VT::verticalVector() const {\n\t\t\t\t\tVT ret = VT(1,0,0) % *this;\n\t\t\t\t\tfloat len_s = ret.len_sq();\n\t\t\t\t\tif(len_s < 1e-6f) {\n\t\t\t\t\t\tret = VT(0,0,1) % *this;\n\t\t\t\t\t\treturn ret.normalization();\n\t\t\t\t\t}\n\t\t\t\t\treturn ret * RSqrt(len_s);\n\t\t\t\t}\n\t\t\t\t/*! \\return this X v \u306e\u5916\u7a4d\u30d9\u30af\u30c8\u30eb */\n\t\t\t\ttemplate <bool A>\n\t\t\t\tVT VT::cross(const VecT<DIM,A>& v) const {\n\t\t\t\t\treg128 r0 = LOADTHIS(),\n\t\t\t\t\t\t\tr1 = v.loadPS();\n\t\t\t\t\t// r0[y,z,x]\n\t\t\t\t\treg128 m0 = reg_shuffle_ps(r0, r0, _REG_SHUFFLE(0,0,2,1)),\n\t\t\t\t\t// r0[z,x,y]\n\t\t\t\t\t\t\tm1 = reg_shuffle_ps(r0, r0, _REG_SHUFFLE(0,1,0,2)),\n\t\t\t\t\t// r1[z,x,y]\n\t\t\t\t\t\t\tm2 = reg_shuffle_ps(r1, r1, _REG_SHUFFLE(0,1,0,2)),\n\t\t\t\t\t// r1[y,z,x]\n\t\t\t\t\t\t\tm3 = reg_shuffle_ps(r1, r1, _REG_SHUFFLE(0,0,2,1));\n\t\t\t\t\tr0 = reg_mul_ps(m0,m2);\n\t\t\t\t\tr1 = reg_mul_ps(m1,m3);\n\t\t\t\t\tr0 = reg_sub_ps(r0, r1);\n\t\t\t\t\treturn VT(r0);\n\t\t\t\t}\n\t\t\t\ttemplate VT VT::cross(const VecT<DIM,false>&) const;\n\t\t\t\ttemplate VT VT::cross(const VecT<DIM,true>&) const;\n\n\t\t\t\t//! \u5916\u7a4d\u8a08\u7b97cross()\u3068\u540c\u7fa9\n\t\t\t\ttemplate <bool A>\n\t\t\t\tvoid VT::operator %= (const VecT<DIM,A>& v) {\n\t\t\t\t\t*this = cross(v);\n\t\t\t\t}\n\t\t\t\ttemplate void VT::operator %= (const VecT<DIM,false>&);\n\t\t\t\ttemplate void VT::operator %= (const VecT<DIM,true>&);\n\n\t\t\t\t//! \u5916\u7a4d\u8a08\u7b97cross()\u3068\u540c\u7fa9\n\t\t\t\ttemplate <bool A>\n\t\t\t\tVT VT::operator % (const VecT<DIM,A>& v) const {\n\t\t\t\t\treturn cross(v);\n\t\t\t\t}\n\t\t\t\ttemplate VT VT::operator % (const VecT<DIM,false>&) const;\n\t\t\t\ttemplate VT VT::operator % (const VecT<DIM,true>&) const;\n\n\t\t\t\tVT VT::modV(const UVec& v) const {\n\t\t\t\t\treturn *this % v; }\n\t\t\t\tVT VT::mulQ(const QuatT<ALIGNB>& q) const {\n\t\t\t\t\treturn *this * q; }\n\t\t\t\tstd::tuple<VT,bool> VT::luaPlaneDivide(const VecT<DIM,false>& v, const PlaneT<false>& p) const {\n\t\t\t\t\treturn planeDivide(v, p);\n\t\t\t\t}\n\t\t\t\t#define _Vec4 VecT<4,ALIGNB>\n\t\t\t\t_Vec4 VT::asVec4(float w) const {\n\t\t\t\t\treturn _Vec4(x,y,z,w);\n\t\t\t\t}\n\t\t\t#elif DIM==2\n\t\t\t\t//! counter clockwise\n\t\t\t\t/*! \u534a\u6642\u8a08\u56de\u308a\u304c\u6b63\u6570\u3092\u8fd4\u3059 */\n\t\t\t\tfloat VT::ccw(const UVec& v) const {\n\t\t\t\t\treturn x*v.y - y*v.x;\n\t\t\t\t}\n\t\t\t\t//! clockwise\n\t\t\t\t/*! \u6642\u8a08\u56de\u308a\u304c\u6b63\u6570\u3092\u8fd4\u3059 */\n\t\t\t\tfloat VT::cw(const UVec& v) const {\n\t\t\t\t\treturn -x*v.y + y*v.x;\n\t\t\t\t}\n\t\t\t\t#define _Vec3 VecT<3,ALIGNB>\n\t\t\t\t_Vec3 VT::asVec3(float z) const {\n\t\t\t\t\treturn _Vec3(x,y,z);\n\t\t\t\t}\n\t\t\t\t#if ALIGN==0\n\t\t\t\t\tfloat VT::Ccw(const UVec& v0, const UVec& v1, const UVec& v2) {\n\t\t\t\t\t\treturn (v0-v1).ccw(v2-v1);\n\t\t\t\t\t}\n\t\t\t\t\tfloat VT::Cw(const UVec& v0, const UVec& v1, const UVec& v2) {\n\t\t\t\t\t\treturn (v0-v1).cw(v2-v1);\n\t\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t#endif\n\t\t}\n\t#else\n\t\t#include \"random.hpp\"\n\t\tnamespace spn {\n\t\t\t/*\tPseudo-code:\n\t\t\t\ttemplate <int N, bool A>\n\t\t\t\tVecT<N,ALIGNB> VT::operator * (const MatT<DIM,N,A>& m) const {\n\t\t\t\t\treg128 ths = LOADTHIS(),\n\t\t\t\t\t\t\taccum = reg_setzero_ps();\n\t\t\t\t\tfor(int i=0 ; i<DIM ; i++) {\n\t\t\t\t\t\treg128 tmp = reg_shuffle_ps(ths, ths, _REG_SHUFFLE(i,i,i,i));\n\t\t\t\t\t\taccum = reg_add_ps(accum, reg_mul_ps(tmp, LOADPS_(N)(m.ma[i])));\n\t\t\t\t\t}\n\t\t\t\t\treturn VecT<N,ALIGNB>(accum);\n\t\t\t\t}\n\t\t\t*/\n\t\t\t#define LOOP_MULOP(z,n,loadf)\t\t{reg128 tmp=reg_shuffle_ps(ths,ths, _REG_SHUFFLE(n,n,n,n)); \\\n\t\t\t\t\t\taccum = reg_add_ps(accum, reg_mul_ps(tmp, loadf(mat.ma[n])));}\n\t\t\t#define DEF_MULOPA(z,n,align)\ttemplate <> VecT<n,ALIGNB> VT::operator * (const MatT<DIM,n,BOOLNIZE(align)>& mat) const { \\\n\t\t\t\t\t\treg128 ths = LOADTHIS(), \\\n\t\t\t\t\t\taccum = reg_setzero_ps(); \\\n\t\t\t\t\t\tBOOST_PP_REPEAT_##z(DIM, LOOP_MULOP, BOOST_PP_CAT(LOADPS_, BOOST_PP_CAT(AFLAG(align),n))) \\\n\t\t\t\t\t\treturn VecT<n,ALIGNB>(accum); }\n\t\t\t#define DEF_MULOPA_2(z,n,align)\ttemplate <> VT& VT::operator *= (const MatT<DIM,DIM,BOOLNIZE(align)>& mat) { \\\n\t\t\t\t\treturn *this = *this * mat; }\n\n\t\t\t#define DEF_MULOP(z,align,dummy)\tBOOST_PP_REPEAT_FROM_TO_##z(2,5, DEF_MULOPA, align) DEF_MULOPA_2(dummy,dummy,align)\n\t\t\tBOOST_PP_REPEAT(2, DEF_MULOP, NOTHING)\n\t\t\t#undef DEF_MULOP\n\n\t\t\t#if DIM==3\n\t\t\t\tVT& VT::operator *= (const QuatT<ALIGNB>& q) {\n\t\t\t\t\t*this = (*this * q);\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\tVT VT::operator * (const QuatT<ALIGNB>& q) const {\n\t\t\t\t\tauto tq = q * QuatT<ALIGNB>(*this,0) * q.conjugation();\n\t\t\t\t\treturn tq.getVector();\n\t\t\t\t}\n\t\t\t\tVT&& VT::operator * (QuatT<ALIGNB>&& q) const {\n\t\t\t\t\tVT& rVT = *reinterpret_cast<VT*>(&q);\n\t\t\t\t\trVT = *this * q;\n\t\t\t\t\treturn std::move(rVT);\n\t\t\t\t}\n\t\t\t\tvoid VT::flip(const Plane& plane) {\n\t\t\t\t\tconst auto& nml = plane.getNormal();\n\t\t\t\t\tfloat d = plane.dot(*this);\n\t\t\t\t\t*this += nml*-d*2;\n\t\t\t\t}\n\t\t\t\ttemplate <bool A>\n\t\t\t\tstd::tuple<VT,bool> VT::planeDivide(const VecT<DIM,A>& v, const PlaneT<false>& p) const {\n\t\t\t\t\t// \u7dda\u5206\u304c\u5e73\u9762\u3092\u307e\u305f\u3050\u304b\n\t\t\t\t\tfloat distf = p.dot(*this);\n\t\t\t\t\tfloat distb = p.dot(v);\n\t\t\t\t\tif(distf * distb >= 0.0f)\n\t\t\t\t\t\treturn std::make_tuple(VecT(),false);\n\n\t\t\t\t\tfloat ratio = fabs(distf) / (fabs(distf) + fabs(distb));\n\t\t\t\t\t// \u5e73\u9762\u3068\u7dda\u5206\u306e\u4ea4\u70b9 -> tv\n\t\t\t\t\tVec3 tv = v - (*this);\n\t\t\t\t\ttv *= ratio;\n\t\t\t\t\tVecT cp = tv + (*this);\n\t\t\t\t\treturn std::make_tuple(cp,true);\n\t\t\t\t}\n\t\t\t\ttemplate std::tuple<VT,bool> VT::planeDivide(const VecT<DIM,true>&,const PlaneT<false>&) const;\n\t\t\t\ttemplate std::tuple<VT,bool> VT::planeDivide(const VecT<DIM,false>&,const PlaneT<false>&) const;\n\t\t\t#endif\n\n\t\t\tVT VT::luaRandom(MTRandom& mt, const RangeF& r) {\n\t\t\t\treturn Random(mt.getUniformF<float>(), r);\n\t\t\t}\n\t\t\tVT VT::luaRandomWithLength(MTRandom& mt, float th, const RangeF& r) {\n\t\t\t\treturn RandomWithLength(mt.getUniformF<float>(), th, r);\n\t\t\t}\n\t\t\tVT VT::luaRandomWithAbs(MTRandom& mt, const RangeF& rTh, const RangeF& r) {\n\t\t\t\treturn RandomWithAbs(mt.getUniformF<float>(), rTh, r);\n\t\t\t}\n\t\t}\n\t#endif\n\t#include \"local_unmacro.hpp\"\n\t#undef ALIGN\n\t#undef ALIGNB\n\t#undef Vec\n\t#undef VT\n#endif\n", "meta": {"hexsha": "3ec03172a3bb61777b2d5429e5153257a089ab16", "size": 23864, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vector.hpp", "max_stars_repo_name": "degarashi/spinner", "max_stars_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "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": "vector.hpp", "max_issues_repo_name": "degarashi/spinner", "max_issues_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vector.hpp", "max_forks_repo_name": "degarashi/spinner", "max_forks_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_forks_repo_licenses": ["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.6010928962, "max_line_length": 125, "alphanum_fraction": 0.6120097218, "num_tokens": 8481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17563827446017283}}
{"text": "/// @file\n/// @copyright The code is licensed under the BSD License\n///            <http://opensource.org/licenses/BSD-2-Clause>,\n///            Copyright (c) 2012-2015 Alexandre Hamez.\n/// @author Alexandre Hamez\n\n#pragma once\n\n#include <algorithm>  // all_of, copy\n#include <deque>\n#include <initializer_list>\n#include <iosfwd>\n#include <stdexcept>  //invalid_argument\n#include <unordered_map>\n\n#include <boost/container/flat_set.hpp>\n\n#include \"sdd/dd/definition.hh\"\n#include \"sdd/hom/context_fwd.hh\"\n#include \"sdd/hom/definition_fwd.hh\"\n#include \"sdd/hom/identity.hh\"\n#include \"sdd/hom/local.hh\"\n#include \"sdd/order/order.hh\"\n#include \"sdd/util/packed.hh\"\n\nnamespace sdd { namespace hom {\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief intersection homomorphism.\ntemplate <typename C>\nstruct _intersection\n{\n  /// @brief The type of the homomorphism operands' set.\n  using operands_type = boost::container::flat_set<homomorphism<C>>;\n\n  /// @brief The type of a const iterator on this intersection's operands.\n  using const_iterator = typename operands_type::const_iterator;\n\n  /// @brief The homomorphism operands' set.\n  const operands_type operands;\n\n  /// @brief Evaluation.\n  SDD<C>\n  operator()(context<C>& cxt, const order<C>& o, const SDD<C>& x)\n  const\n  {\n    dd::intersection_builder<C, SDD<C>> intersection_operands(cxt.sdd_context());\n    intersection_operands.reserve(operands.size());\n    for (const auto& op : operands)\n    {\n      auto res = op(cxt, o, x);\n      if (res.empty())\n      {\n        return zero<C>();\n      }\n      intersection_operands.add(std::move(res));\n    }\n    return dd::intersection(cxt.sdd_context(), std::move(intersection_operands));\n  }\n\n  /// @brief Skip variable predicate.\n  bool\n  skip(const order<C>& o)\n  const noexcept\n  {\n    return std::all_of( operands.begin(), operands.end()\n                      , [&o](const homomorphism<C>& h){return h.skip(o);});\n  }\n\n  /// @brief Selector predicate\n  bool\n  selector()\n  const noexcept\n  {\n    return std::all_of( operands.begin(), operands.end()\n                      , [](const homomorphism<C>& h){return h.selector();});\n  }\n\n  /// @brief Get an iterator to the first operand.\n  ///\n  /// O(1).\n  const_iterator\n  begin()\n  const noexcept\n  {\n    return operands.begin();\n  }\n\n  /// @brief Get an iterator to the end of operands.\n  ///\n  /// O(1).\n  const_iterator\n  end()\n  const noexcept\n  {\n    return operands.end();\n  }\n\n  friend\n  bool\n  operator==(const _intersection& lhs, const _intersection& rhs)\n  noexcept\n  {\n    return lhs.operands == rhs.operands;\n  }\n\n  friend\n  std::ostream&\n  operator<<(std::ostream& os, const _intersection& s)\n  {\n    os << \"(\";\n    std::copy( s.operands.begin(), std::prev(s.operands.end())\n              , std::ostream_iterator<homomorphism<C>>(os, \" & \"));\n    return os << *std::prev(s.operands.end()) << \")\";\n  }\n\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief Help optimize an intersection's operands.\ntemplate <typename C>\nstruct intersection_builder\n{\n  using operands_type = typename _intersection<C>::operands_type;\n  using hom_list_type = std::deque<homomorphism<C>> ;\n  using locals_type = std::unordered_map< typename C::variable_type, hom_list_type>;\n\n  operands_type& operands_;\n  locals_type& locals_;\n\n  /// @brief Flatten nested intersections.\n  void\n  operator()(const _intersection<C>& s, const homomorphism<C>&)\n  const\n  {\n    for (const auto& op : s.operands)\n    {\n      visit(*this, op, op);\n    }\n  }\n\n  /// @brief Regroup locals.\n  void\n  operator()(const _local<C>& l, const homomorphism<C>&)\n  const\n  {\n    auto insertion = locals_.emplace(l.target, hom_list_type{});\n    insertion.first->second.emplace_back(l.h);\n  }\n\n  /// @brief Insert normally all other operands.\n  template <typename T>\n  void\n  operator()(const T&, const homomorphism<C>& h)\n  const\n  {\n    operands_.insert(h);\n  }\n};\n\n} // namespace hom\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @brief Create the intersection homomorphism.\n/// @related homomorphism\ntemplate <typename C, typename InputIterator>\nhomomorphism<C>\nintersection(const order<C>& o, InputIterator begin, InputIterator end)\n{\n  const auto size = std::distance(begin, end);\n\n  if (size == 0)\n  {\n    throw std::invalid_argument(\"Empty operands at intersection construction.\");\n  }\n\n  typename hom::_intersection<C>::operands_type operands;\n  operands.reserve(size);\n\n  typename hom::intersection_builder<C>::locals_type locals;\n  hom::intersection_builder<C> ib {operands, locals};\n  for (; begin != end; ++begin)\n  {\n    visit(ib, *begin, *begin);\n  }\n\n  // insert remaining locals\n  for (const auto& l : locals)\n  {\n    operands.insert(local<C>(l.first, intersection(o, l.second.begin(), l.second.end())));\n  }\n\n  if (operands.size() == 1)\n  {\n    return *operands.begin();\n  }\n  else\n  {\n    operands.shrink_to_fit();\n    return hom::make<C, hom::_intersection<C>>(std::move(operands));\n  }\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @brief Create the intersection homomorphism.\n/// @related homomorphism\ntemplate <typename C>\nhomomorphism<C>\nintersection(const order<C>& o, std::initializer_list<homomorphism<C>> operands)\n{\n  return intersection(o, operands.begin(), operands.end());\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\n} // namespace sdd\n\nnamespace std {\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief Hash specialization for sdd::hom::_intersection.\ntemplate <typename C>\nstruct hash<sdd::hom::_intersection<C>>\n{\n  std::size_t\n  operator()(const sdd::hom::_intersection<C>& s)\n  const\n  {\n    using namespace sdd::hash;\n    return seed() (range(s.operands));\n  }\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n} // namespace std\n", "meta": {"hexsha": "0948ffdd0401fa0b6ef9ef57a5a9675437aab29d", "size": 6146, "ext": "hh", "lang": "C++", "max_stars_repo_path": "sdd/hom/intersection.hh", "max_stars_repo_name": "tic-toc/libsdd", "max_stars_repo_head_hexsha": "5c3deb43523d062929f169c3d7a301240f0fb811", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T01:20:28.000Z", "max_issues_repo_path": "sdd/hom/intersection.hh", "max_issues_repo_name": "tic-toc/libsdd", "max_issues_repo_head_hexsha": "5c3deb43523d062929f169c3d7a301240f0fb811", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-05T23:39:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-05T23:40:04.000Z", "max_forks_repo_path": "libsdd/sdd/hom/intersection.hh", "max_forks_repo_name": "kyouko-taiga/SwiftSDD", "max_forks_repo_head_hexsha": "9312160e0fac5fef6e605c9e74c543ded9708e54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-05-13T14:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T20:13:39.000Z", "avg_line_length": 25.0857142857, "max_line_length": 100, "alphanum_fraction": 0.5836316303, "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17563827099538495}}
{"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//#define BOOST_TEST_DYN_LINK\n//#define BOOST_TEST_MAIN\n\n#include <limits>\n#include <string>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"tudat/simulation/estimation.h\"\n\n//namespace tudat\n//{\n//namespace unit_tests\n//{\n\nusing namespace tudat;\nusing namespace tudat::observation_models;\nusing namespace tudat::orbit_determination;\nusing namespace tudat::estimatable_parameters;\nusing namespace tudat::interpolators;\nusing namespace tudat::numerical_integrators;\nusing namespace tudat::spice_interface;\nusing namespace tudat::simulation_setup;\nusing namespace tudat::orbital_element_conversions;\nusing namespace tudat::ephemerides;\nusing namespace tudat::propagators;\nusing namespace tudat::basic_astrodynamics;\nusing namespace tudat::coordinate_conversions;\nusing namespace tudat::statistics;\n\n//BOOST_AUTO_TEST_SUITE( test_observation_noise_models )\n\n//// Function to conver\n//double ignoreInputeVariable( std::function< double( ) > inputFreeFunction, const double dummyInput )\n//{\n//    return inputFreeFunction( );\n//}\n\n//! Test whether observation noise is correctly added when simulating noisy observations\nint main( )\n{\n    //Load spice kernels.\n    spice_interface::loadStandardSpiceKernels( );\n\n    // Define bodies in simulation\n    std::vector< std::string > bodyNames;\n    bodyNames.push_back( \"Earth\" );\n    bodyNames.push_back( \"Moon\" );\n\n    // Specify initial time\n    double initialEphemerisTime = double( 1.0E7 );\n    double finalEphemerisTime = double( 1.0E7 + 3.0 * physical_constants::JULIAN_DAY );\n\n    // Create bodies needed in simulation\n    BodyListSettings bodySettings =\n            getDefaultBodySettings( bodyNames, initialEphemerisTime - 3600.0, finalEphemerisTime + 3600.0 );\n    bodySettings.at( \"Earth\" )->rotationModelSettings = std::make_shared< SimpleRotationModelSettings >(\n                \"ECLIPJ2000\", \"IAU_Earth\",\n                spice_interface::computeRotationQuaternionBetweenFrames(\n                    \"ECLIPJ2000\", \"IAU_Earth\", initialEphemerisTime ),\n                initialEphemerisTime, 2.0 * mathematical_constants::PI /\n                ( physical_constants::JULIAN_DAY ) );\n\n    SystemOfBodies bodies = createSystemOfBodies( bodySettings );\n    \n\n    // Creatre ground stations\n    std::vector< std::string > groundStationNames;\n    groundStationNames.push_back( \"Station1\" );\n    groundStationNames.push_back( \"Station2\" );\n    groundStationNames.push_back( \"Station3\" );\n\n    createGroundStation( bodies.at( \"Earth\" ), \"Station1\", ( Eigen::Vector3d( ) << 0.0, 0.35, 0.0 ).finished( ), geodetic_position );\n    createGroundStation( bodies.at( \"Earth\" ), \"Station2\", ( Eigen::Vector3d( ) << 0.0, -0.55, 2.0 ).finished( ), geodetic_position );\n    createGroundStation( bodies.at( \"Earth\" ), \"Station3\", ( Eigen::Vector3d( ) << 0.0, 0.05, 4.0 ).finished( ), geodetic_position );\n\n    // Define parameters.\n    std::vector< LinkEnds > stationReceiverLinkEnds;\n    std::vector< LinkEnds > stationTransmitterLinkEnds;\n    std::vector< LinkEnds > twoWayLinkEnds;\n\n    // Define link ends to/from ground stations to Moon\n    for( unsigned int i = 0; i < groundStationNames.size( ); i++ )\n    {\n        LinkEnds linkEnds;\n        linkEnds[ transmitter ] = std::make_pair( \"Earth\", groundStationNames.at( i ) );\n        linkEnds[ receiver ] = std::make_pair( \"Moon\", \"\" );\n        stationTransmitterLinkEnds.push_back( linkEnds );\n\n        linkEnds.clear( );\n        linkEnds[ receiver ] = std::make_pair( \"Earth\", groundStationNames.at( i ) );\n        linkEnds[ transmitter ] = std::make_pair( \"Moon\", \"\" );\n        stationReceiverLinkEnds.push_back( linkEnds );\n\n        twoWayLinkEnds.clear( );\n        linkEnds[ receiver ] = std::make_pair( \"Earth\", groundStationNames.at( i ) );\n        linkEnds[ retransmitter ] = std::make_pair( \"Moon\", \"\" );\n        linkEnds[ transmitter ] = std::make_pair( \"Earth\", groundStationNames.at( i ) );\n        twoWayLinkEnds.push_back( linkEnds );\n    }\n\n    // Define (arbitrary) link ends for each observable\n    std::map< ObservableType, std::vector< LinkEnds > > linkEndsPerObservable;\n    linkEndsPerObservable[ one_way_range ].push_back( stationReceiverLinkEnds[ 0 ] );\n    linkEndsPerObservable[ one_way_range ].push_back( stationReceiverLinkEnds[ 1 ] );\n\n    linkEndsPerObservable[ one_way_doppler ].push_back( stationReceiverLinkEnds[ 0 ] );\n    linkEndsPerObservable[ one_way_doppler ].push_back( stationReceiverLinkEnds[ 1 ] );\n\n    // Define observation settings for each observable/link ends combination\n    std::vector< std::shared_ptr< ObservationModelSettings > > observationSettingsList;\n    for( std::map< ObservableType, std::vector< LinkEnds > >::iterator linkEndIterator = linkEndsPerObservable.begin( );\n         linkEndIterator != linkEndsPerObservable.end( ); linkEndIterator++ )\n    {\n        ObservableType currentObservable = linkEndIterator->first;\n        std::vector< LinkEnds > currentLinkEndsList = linkEndIterator->second;\n\n        for( unsigned int i = 0; i < currentLinkEndsList.size( ); i++ )\n        {\n            // Create observation settings\n            observationSettingsList.push_back( std::make_shared< ObservationModelSettings >(\n                                                   currentObservable, currentLinkEndsList.at( i ) ) );\n        }\n    }\n\n    // Create observation simulators\n    std::vector< std::shared_ptr< ObservationSimulatorBase< double, double > > >  observationSimulators =\n            createObservationSimulators( observationSettingsList, bodies );\n\n    // Define osbervation times.\n    std::vector< double > baseTimeList;\n    double observationTimeStart = initialEphemerisTime + 1000.0;\n    double observationInterval = 10.0;\n    for( unsigned int i = 0; i < 14; i++ )\n    {\n        for( unsigned int j = 0; j < 4320; j++ )\n        {\n            baseTimeList.push_back( observationTimeStart + static_cast< double >( i ) * 86400.0 +\n                                    static_cast< double >( j ) * observationInterval );\n        }\n    }\n\n    // Define observation simulation settings (observation type, link end, times and reference link end)\n    std::vector< std::shared_ptr< ObservationSimulationSettings< double > > > measurementSimulationInput;\n    for( std::map< ObservableType, std::vector< LinkEnds > >::iterator linkEndIterator = linkEndsPerObservable.begin( );\n         linkEndIterator != linkEndsPerObservable.end( ); linkEndIterator++ )\n    {\n        ObservableType currentObservable = linkEndIterator->first;\n        std::vector< LinkEnds > currentLinkEndsList = linkEndIterator->second;\n        for( unsigned int i = 0; i < currentLinkEndsList.size( ); i++ )\n        {\n            measurementSimulationInput.push_back(\n                        std::make_shared< TabulatedObservationSimulationSettings< > >(\n                            currentObservable, currentLinkEndsList.at( i ), baseTimeList, receiver ) );\n        }\n    }\n\n    std::vector< std::shared_ptr< observation_models::ObservationViabilitySettings > > viabilitySettingsList;\n    viabilitySettingsList.push_back( elevationAngleViabilitySettings(\n                                         std::make_pair( \"Earth\", \"Station1\" ), 25.0 * mathematical_constants::PI / 180.0 ) );\n    viabilitySettingsList.push_back( elevationAngleViabilitySettings(\n                                         std::make_pair( \"Earth\", \"Station2\" ), 25.0 * mathematical_constants::PI / 180.0 ) );\n\n    addViabilityToObservationSimulationSettings(\n            measurementSimulationInput, viabilitySettingsList );\n\n    // Define settings for dependent variables\n    std::vector< std::shared_ptr< ObservationDependentVariableSettings > > dependentVariableList;\n\n    std::shared_ptr< ObservationDependentVariableSettings > elevationAngleSettings1 =\n            std::make_shared< StationAngleObservationDependentVariableSettings >(\n                station_elevation_angle, std::make_pair( \"Earth\", \"Station1\" ) );\n    std::shared_ptr< ObservationDependentVariableSettings > azimuthAngleSettings1 =\n            std::make_shared< StationAngleObservationDependentVariableSettings >(\n                station_azimuth_angle, std::make_pair( \"Earth\", \"Station1\" ) );\n\n//    std::shared_ptr< ObservationDependentVariableSettings > elevationAngleSettings2 =\n//            std::make_shared< StationAngleObservationDependentVariableSettings >(\n//                station_elevation_angle, std::make_pair( \"Earth\", \"Station2\" ) );\n\n    dependentVariableList.push_back( elevationAngleSettings1 );\n    dependentVariableList.push_back( azimuthAngleSettings1 );\n\n    addDependentVariablesToObservationSimulationSettings(\n                measurementSimulationInput, dependentVariableList, bodies );\n\n\n\n    // Simulate noise-free observations\n    std::shared_ptr< ObservationCollection< > > idealObservationsAndTimes = simulateObservations< double, double >(\n                measurementSimulationInput, observationSimulators, bodies );\n\n    std::cout<<\"Simulated observations \"<<std::endl;\n    std::map< double, Eigen::VectorXd > elevationAngles;\n    std::map< double, Eigen::VectorXd > azimuthAngles;\n\n    std::cout<<\"Getting elevation angle\"<<std::endl;\n    elevationAngles = getDependentVariableResultList(\n                idealObservationsAndTimes, elevationAngleSettings1,\n                one_way_range );\n    input_output::writeDataMapToTextFile( elevationAngles,\n                                          \"elevationAngles1_range.dat\",\n                                          \"/home/dominic/Software/Tudat30Bundle/test-output/\" );\n\n    std::cout<<\"Getting azimuth angle\"<<std::endl;\n    azimuthAngles = getDependentVariableResultList(\n                idealObservationsAndTimes, azimuthAngleSettings1,\n                one_way_range );\n    input_output::writeDataMapToTextFile( azimuthAngles,\n                                          \"azimuthAngles1_range.dat\",\n                                          \"/home/dominic/Software/Tudat30Bundle/test-output/\" );\n\n//    elevationAngles = getDependentVariableResultList(\n//                idealObservationsAndTimes, elevationAngleSettings1,\n//                one_way_range, stationReceiverLinkEnds[ 0 ] );\n//    input_output::writeDataMapToTextFile( elevationAngles,\n//                                          \"elevationAngles2_range.dat\",\n//                                          \"/home/dominic/Software/Tudat30Bundle/test-output/\" );\n\n//    elevationAngles = getDependentVariableResultList(\n//                idealObservationsAndTimes, elevationAngleSettings2,\n//                one_way_doppler );\n//    input_output::writeDataMapToTextFile( elevationAngles,\n//                                          \"elevationAngles1_doppler.dat\",\n//                                          \"/home/dominic/Software/Tudat30Bundle/test-output/\" );\n\n//    elevationAngles = getDependentVariableResultList(\n//                idealObservationsAndTimes, elevationAngleSettings2,\n//                one_way_doppler, stationReceiverLinkEnds[ 1 ] );\n//    input_output::writeDataMapToTextFile( elevationAngles,\n//                                          \"elevationAngles2_doppler.dat\",\n//                                          \"/home/dominic/Software/Tudat30Bundle/test-output/\" );\n\n\n}\n\n//class ObservationDependentVariableWrapper\n//{\n//  ObservableType observableType_;\n\n//  LinkEnds linkEnds;\n\n//  std::map< double, Eigen::VectorXd > dependentVariables_;\n\n//  std::vector< std::shared_ptr< ObservationDependentVariableSettings > > dependentVariableList;\n\n//  std::vector< int > sizeIndices_;\n\n//  std::map< double, Eigen::VectorXd > getSingleDependentVariables( std::shared_ptr< ObservationDependentVariableSettings > );\n\n\n\n//};\n\n//BOOST_AUTO_TEST_SUITE_END( )\n\n//}\n\n//}\n\n", "meta": {"hexsha": "37ae962f349059f25a0ca2f3f56ff3208b323c80", "size": 12147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/observation_models/unitTestObservationDependentVariables.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": "tests/src/astro/observation_models/unitTestObservationDependentVariables.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": "tests/src/astro/observation_models/unitTestObservationDependentVariables.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": 44.6580882353, "max_line_length": 134, "alphanum_fraction": 0.6739935787, "num_tokens": 2824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17540524513014552}}
{"text": "\n/* scene.hpp - path rendering scene graph. */\n\n// Copyright (c) NVIDIA Corporation. All rights reserved.\n\n#ifndef __scene_hpp__\n#define __scene_hpp__\n\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n# pragma once\n#endif\n\n#include <vector>\n#include <stack>\n#include <string>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/weak_ptr.hpp>\n#include <boost/enable_shared_from_this.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <stdio.h>    /* for printf and NULL */\n#include <stdlib.h>   /* for exit */\n#include <math.h>     /* for sin and cos */\n#include <GL/glew.h>\n#if __APPLE__\n#include <OpenGL/glext.h>\n#endif\n\n#include <Cg/vector/xyzw.hpp>\n#include <Cg/vector/rgba.hpp>\n#include <Cg/double.hpp>\n#include <Cg/vector.hpp>\n#include <Cg/matrix.hpp>\n#include <Cg/dot.hpp>\n#include <Cg/any.hpp>\n#include <Cg/all.hpp>\n#include <Cg/mul.hpp>\n#include <Cg/round.hpp>\n#include <Cg/cross.hpp>\n#include <Cg/min.hpp>\n#include <Cg/max.hpp>\n#include <Cg/distance.hpp>\n#include <Cg/saturate.hpp>\n#include <Cg/inverse.hpp>\n#include <Cg/iostream.hpp>\n\n#include \"renderer.hpp\"\n\n#include \"ActiveControlPoint.hpp\"\n#include \"path.hpp\"\n#include \"path_process.hpp\"\n#include \"glmatrix.hpp\"\n\n// Grumble, Microsoft (and probably others) define these as macros\n#undef min\n#undef max\n\nusing namespace boost;\nusing std::string;\nusing std::vector;\nusing std::stack;\nusing namespace Cg;\n\n\nclass Traversal;\ntypedef shared_ptr<class Visitor> VisitorPtr;\n\nclass RectBounds : public float4\n{\npublic:\n    RectBounds();\n    RectBounds(const float4 &bounds);\n    RectBounds(const RectBounds &bounds);\n    RectBounds(float2 top_left, float2 bottom_right);\n    RectBounds(float left, float top, float right, float bottom);\n\n    inline float width() { return z-x; }\n    inline float height() { return w-y; }\n    inline bool isValid() { return valid; }\n    inline void invalidate() { valid = false; }\n    inline RectBounds dilate(float amount) { return dilate(amount, amount); }\n\n    RectBounds& operator =(const float4 &bounds);\n    RectBounds& operator =(const RectBounds &bounds);\n    RectBounds operator |(const float4 &bounds);\n    RectBounds operator |(const RectBounds &bounds);\n    RectBounds& operator |=(const float4 &bounds);\n    RectBounds& operator |=(const RectBounds &bounds);\n    RectBounds operator & (const float4 &bounds);\n    RectBounds operator & (const RectBounds &bounds);\n    RectBounds& operator &=(const float4 &bounds);\n    RectBounds& operator &=(const RectBounds &bounds);\n    RectBounds include(float2 point);\n    RectBounds transform(const float4x4 &matrix);\n    RectBounds transform(const float3x3 &matrix);\n    RectBounds dilate(float x_, float y_);\n\nprotected:\n    bool valid;\n};\n\nstruct Node {\n    virtual ~Node() {};\n\n    virtual void dumpSVGHelper(FILE *file, const float4x4 &transform) { };\n    void dumpSVG(FILE *file, const float4x4 &transform);\n\n    virtual float4 getBounds() { return float4(0,0,-1,-1); } // bogus bounds (x>z and y>w);\n\n    // Force every subclass to implement a traverse() method\n    virtual void traverse(VisitorPtr visitor, Traversal &traversal) = 0;\n    \n    // Make it easier to traverse by automatically using a generic traversal\n    void traverse(VisitorPtr visitor);\n};\n\nstruct Shape;\ntypedef shared_ptr<struct RendererState<Shape> > ShapeRendererStatePtr;\n\ntypedef shared_ptr<struct Text> TextPtr;\nstruct Text : Node, HasRendererState<Text>, enable_shared_from_this<Text> {\nprotected:\npublic:\n\tstd::string font_family;\n\tstd::string text;\n\tdouble font_size;\n\tdouble3x3 transform;\n\n    Text(const char* font_, const char* text_, double font_size_,\n\t\tdouble3x3 matrix_)\n        : HasRendererState<Text>(this),\n\t\tfont_family(font_),\n\t\ttext(text_),\n\t\tfont_size(font_size_),\n\t\ttransform(matrix_)\n    {}\n    virtual ~Text() {}\n\n    void invalidate() {\n        invalidateRenderStates();\n    }\n\n\tvoid traverse(VisitorPtr visitor, Traversal &traversal);\n};\n\nenum OpacityTreatment {\n    FULLY_OPAQUE,\n    VARIABLE_PREMULTIPLIED_ALPHA,\n    VARIABLE_INDEPENDENT_ALPHA,\n};\n\n// Gradient-related enumerations\nenum SpreadMethod {\n    PAD,      // clamp to edge\n    REFLECT,  // mirror\n    REPEAT,   // repeat\n    NONE      // clamp to border with (0,0,0,0) border\n};\nenum GradientUnits {\n    USER_SPACE_ON_USE,\n    OBJECT_BOUNDING_BOX\n};\n// http://www.w3.org/TR/SVG/painting.html#ColorInterpolationProperty\nenum ColorSpace {\n    CORRECTED_SRGB,     // Indicates that sRGB color values should be converted into linearized RGB color space \n    UNCORRECTED         // Indicates that color interpolation should be uncorrected\n};\n\nstruct Paint : HasRendererState<Paint> {\n    virtual bool isNonOpaque() = 0;\n    virtual bool isOpaque() = 0;\n    virtual bool isTransparent() = 0;\n    virtual string toSVG(string fillOrStroke) = 0;\n    virtual ~Paint() {}\n\n    Paint()\n        : HasRendererState<Paint>(this)\n    { }\n};\ntypedef shared_ptr<Paint> PaintPtr;\ntypedef shared_ptr<RendererState<Paint> > PaintRendererStatePtr;\n\nstring glColorToSVGColor(const string fillOrStroke, const float4 &color);\n\nstruct SolidColorPaint : Paint {\nprotected:\n    float4 color;\n\npublic:\n    SolidColorPaint(float4 c) \n        : color(c)\n    {}\n\n    bool isNonOpaque() {\n        return color.a != 1;\n    }\n    bool isOpaque() {\\\n        return color.a == 1;\n    }\n    bool isTransparent() {\n        return color.a != 1;\n    }\n    string toSVG(string fillOrStroke) {\n        return glColorToSVGColor(fillOrStroke, color);\n    }\n\n    inline float4 getColor() const { return color; }\n};\ntypedef shared_ptr<SolidColorPaint> SolidColorPaintPtr;\n\nstruct GradientStop {\n    float offset;\n    float4 color;  // RGB is color, alpha is opacity\n\n    GradientStop()\n        : color(0,0,0,1)\n    { }  // opaque black is default\n\n    GradientStop operator = (const GradientStop &src) {\n        if (&src != this) {\n            offset = src.offset;\n            color = src.color;\n        }\n        return *this;\n    }\n};\n\nstruct GradientStops {\n    vector<GradientStop> stop_array;\n};\ntypedef shared_ptr<GradientStops> GradientStopsPtr;\n\nstruct GradientPaint : Paint {\nprotected:\n    // Generic gradient attributes\n    GradientUnits gradient_units;\n    float3x3 gradient_transform,\n             inverse_gradient_transform;  // could be float4x4\n    SpreadMethod spread_method;\n    GradientStopsPtr gradient_stops;\n\npublic:\n    GradientPaint()\n        : gradient_units(OBJECT_BOUNDING_BOX)\n        , gradient_transform(1,0,0, 0,1,0, 0,0,1)  // 3x3 identity\n        , inverse_gradient_transform(1,0,0, 0,1,0, 0,0,1)  // 3x3 identity\n        , spread_method(PAD)\n    {}\n\n    inline const vector<GradientStop> &getStopArray() const { return gradient_stops->stop_array; }\n    inline SpreadMethod getSpreadMethod() const { return spread_method; }\n    inline const float3x3 &getGradientTransform() const { return gradient_transform; }\n    inline const float3x3 &getInverseGradientTransform() const { return inverse_gradient_transform; }\n    inline GradientUnits getGradientUnits() const { return gradient_units; }\n\n    inline void setGradientStops(GradientStopsPtr stops) {\n        gradient_stops = stops;\n    }\n    inline void setGradientTransform(const float3x3 &matrix) {\n        gradient_transform = matrix;\n        // OpenGL wants to map path-space positions to texture\n        // coordinates so needs the reverse transform so take the inverse.\n        inverse_gradient_transform = inverse(matrix);\n    }\n    inline void setSpreadMethod(SpreadMethod v) {\n        spread_method = v;\n    }\n    inline void setGradientUnits(GradientUnits v) {\n      gradient_units = v;\n    }\n};\ntypedef shared_ptr<GradientPaint> GradientPaintPtr;\n\nstruct LinearGradientPaint : GradientPaint {\nprotected:\n    float2 v1, v2;\n\npublic:\n    LinearGradientPaint(float2 v1_, float2 v2_) \n        : v1(v1_)\n        , v2(v2_)\n    {}\n\n    OpacityTreatment startShading();\n    void stopShading();\n    bool isNonOpaque() {\n        return false;\n    }\n    bool isOpaque() {\n        return false;\n    }\n    bool isTransparent() {\n        return false;\n    }\n    string toSVG(string fillOrStroke) {\n        printf(\"LinearGradientPaint lacks proper toSVG, outputting red\\n\");\n        return glColorToSVGColor(fillOrStroke, float4(1,0,0,1));\n    }\n\n    inline float2 getV1() const { return v1; }\n    inline float2 getV2() const { return v2; }\n};\ntypedef shared_ptr<LinearGradientPaint> LinearGradientPaintPtr;\n\nstruct RadialGradientPaint : GradientPaint {\nprotected:\n    float2 center, focal_point;\n    float radius;\n\npublic:\n    RadialGradientPaint(float2 c, float2 f, float r) \n        : center(c)\n        , focal_point(f)\n        , radius(r)\n    {}\n\n    OpacityTreatment startShading();\n    void stopShading();\n    bool isNonOpaque() {\n        return false;\n    }\n    bool isOpaque() {\n        return false;\n    }\n    bool isTransparent() {\n        return false;\n    }\n    string toSVG(string fillOrStroke) {\n        printf(\"RadialGradientPaint lacks proper toSVG, outputting cyan\\n\");\n        return glColorToSVGColor(fillOrStroke, float4(0,1,1,1));\n    }\n\n    inline float2 getCenter() const { return center; }\n    inline float2 getFocalPoint() const { return focal_point; }\n    inline float getRadius() const { return radius; }\n};\ntypedef shared_ptr<RadialGradientPaint> RadialGradientPaintPtr;\n\nstruct RasterImage {\n#pragma pack(1)\n    struct Pixel { \n        GLubyte r, g, b, a; \n    };\n#pragma pack()\n\n    RasterImage(Pixel *pixels_, int width_, int height_) \n        : pixels(pixels_), width(width_), height(height_) { }\n    RasterImage()\n        : pixels(NULL)\n        , width(0)\n        , height(0)\n    { }\n    ~RasterImage() { if (pixels) free(pixels); }\n\n    Pixel *pixels;\n    int width, height;\n};\ntypedef shared_ptr<RasterImage> RasterImagePtr;\n\nstruct ImagePaint : Paint {\n    RasterImagePtr image;\n    bool opaque;\n\n    ImagePaint(RasterImagePtr image_);\n\n    bool isNonOpaque() {\n        return !opaque;\n    }\n    bool isOpaque() {\n        return opaque;\n    }\n    bool isTransparent() {\n        return !opaque;\n    }\n    string toSVG(string fillOrStroke) {\n        printf(\"LinearGradientPaint lacks proper toSVG, outputting green\\n\");\n        return glColorToSVGColor(fillOrStroke, float4(0,1,0,1));\n    }\n};\ntypedef shared_ptr<ImagePaint> ImagePaintPtr;\n\ntypedef shared_ptr<struct Shape> ShapePtr;\nstruct Shape : Node, HasRendererState<Shape>, enable_shared_from_this<Shape> {\nprotected:\n    PathPtr path;\n    PaintPtr fill_paint, stroke_paint;\npublic:\n\tLdpPolyGroupPtr ldpPoly;\npublic:\n    float net_fill_opacity, net_stroke_opacity;\n\n    Shape()\n        : HasRendererState<Shape>(this)\n    {}\n    Shape(PathPtr p)\n        : HasRendererState<Shape>(this)\n        , path(p)\n        , net_fill_opacity(1)\n        , net_stroke_opacity(1)\n    { }\n    Shape(PathPtr p, PaintPtr f, PaintPtr s)\n        : HasRendererState<Shape>(this)\n        , path(p)\n        , fill_paint(f)\n        , stroke_paint(s)\n        , net_fill_opacity(1)\n        , net_stroke_opacity(1)\n    { }\n\n    virtual ~Shape() {}\n\n    int countSegments();\n\n    inline PathPtr getPath() const { return path; }\n    inline PaintPtr getFillPaint() const { return fill_paint; }\n    inline PaintPtr getStrokePaint() const { return stroke_paint; }\n\n    void dumpSVGHelper(FILE *file, const float4x4 &transform);\n\n    void drawControlPoints();\n    void drawReferencePoints();\n\n    float4 getBounds() {\n        return path ? path->getBounds() : Node::getBounds();\n    }\n\n    using Node::traverse; // Lame ... Node::traverse(VisitorPtr visitor) gets \"shadowed\"\n    void traverse(VisitorPtr visitor, Traversal &traversal);\n\n    bool isEmpty() { \n        return path->isEmpty();\n    }\n    bool isFillable() { \n        return path->isFillable();\n    }\n    bool isStrokable() { \n        return path->isStrokable();\n    }\n    void invalidate() {\n        invalidateRenderStates();\n        path->invalidate();\n    }\n\n    bool isOpaqueFill() {\n        if (fill_paint) {\n            return fill_paint->isOpaque();\n        } else {\n            return true;\n        }\n    }\n    bool isOpaqueStroke() {\n        if (stroke_paint) {\n            return stroke_paint->isOpaque();\n        } else {\n            return true;\n        }\n    }\n    bool isOpaque() {\n        return isOpaqueFill() && isOpaqueStroke();\n    }\n    bool isNonOpaque() {\n        return !isOpaque();\n    }\n\n    void processSegments(PathSegmentProcessor &processor);\n};\n\nstruct Transform : Node, enable_shared_from_this<Transform> {\npublic:\n    NodePtr node;\nprotected:\n    float4x4 matrix;\n    float4x4 inverse_matrix;\n\npublic:\n    // Identity transform\n    Transform(NodePtr node_);\n\n    // Projective 3D transform (4x4 matrix)\n    Transform(NodePtr node_, const float4x4 &matrix_);\n\n    // Projective 2D transform (3x3 matrix)\n    Transform(NodePtr node_, const double3x3 &matrix_);\n\n    void dumpSVGHelper(FILE *file, const float4x4 &transform);\n    void setMatrix(const float4x4 &transform);\n    inline float4x4 getMatrix() const { return matrix; }\n    inline float4x4 getInverseMatrix() const { return inverse_matrix; }\n\n    float4 getBounds();\n\n    using Node::traverse; // Lame ... Node::traverse(VisitorPtr visitor) gets \"shadowed\"\n    void traverse(VisitorPtr visitor, Traversal &traversal);\n};\ntypedef shared_ptr<Transform> TransformPtr;\n\nstruct WarpTransform : Transform {\nprotected:\n    float2 to[4];\n    float2 from[4];  // Points for a quadrilateral that should map to a [-1..+1,-1..+1] square.\n    float2 scale;    // Extra scaling term (typically 90%).\n\n    void updateMatrix();\n\npublic:\n    // Identity transform\n    WarpTransform(NodePtr node_, const float2 to_[4], const float2 from_[4], const float2 &scale);\n\n    void drawWarpPoints();\n\n    void setWarpPoint(int ndx, const float2 &xy);\n\n    void findNearerControlPoint(ActiveWarpPoint &hit);\n\n    inline float4x4 scaledTransform(const float4x4 &m) const {\n        return mul(m, scale4x4(scale));\n    }\n};\ntypedef shared_ptr<WarpTransform> WarpTransformPtr;\n\nenum ClipMerge {\n    SUM_WINDING_NUMBERS,\n    SUM_WINDING_NUMBERS_MOD_2,\n    CLIP_COVERAGE_UNION\n};\nenum ClipRule {\n    NON_ZERO,\n    EVEN_ODD\n};\n\ntypedef shared_ptr<struct Clip> ClipPtr;\nstruct Clip : Node, enable_shared_from_this<Clip> {\n    NodePtr path;\n    NodePtr node;\n    ClipMerge clip_merge;\n\n    Clip(NodePtr path_, NodePtr node_, ClipMerge clip_merge_)\n        : path(path_)\n        , node(node_)\n        , clip_merge(clip_merge_) {\n    }\n\n    float4 getBounds() { return node->getBounds(); }\n    RectBounds getClipBounds();\n    using Node::traverse; // Lame ... Node::traverse(VisitorPtr visitor) gets \"shadowed\"\n    void traverse(VisitorPtr visitor, Traversal &traversal);\n};\n\nstruct ViewBox : Clip {\n    ViewBox(NodePtr node_, RectBounds &viewbox);\n};\ntypedef shared_ptr<ViewBox> ViewBoxPtr;\n\nstruct Group : public Node, enable_shared_from_this<Group> {\n    vector<NodePtr> list;\n\n    void push_back(NodePtr node) { list.push_back(node); }\n\n    void dumpSVGHelper(FILE *file, const float4x4 &transform);\n\n    float4 getBounds();\n\n    using Node::traverse; // Lame ... Node::traverse(VisitorPtr visitor) gets \"shadowed\"\n    void traverse(VisitorPtr visitor, Traversal &traversal);\n\n\tstd::string ldp_layer_name;\n};\ntypedef shared_ptr<Group> GroupPtr;\n\nstruct SvgScene : public Group {\n    int width, height;\n    RectBounds view_box;\n    string preserve_aspect_ratio;\n\tdouble ldp_pixel2meter;\n};\ntypedef shared_ptr<SvgScene> SvgScenePtr;\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Visitor/Traversal Interfaces\n\n// This class lets us \n//   1. Customize how the different types of nodes are treated during traversal\n//   2. Confidently maintain state throughout the process\nclass Visitor \n{\npublic:\n    virtual ~Visitor() { } // Make the destructor virtual\n\n    virtual void visit(ShapePtr shape) = 0;\n\n\tvirtual void visit(TextPtr text) {}\n\n    virtual void apply(TransformPtr transform) { }\n    virtual void unapply(TransformPtr transform) { }\n\n    virtual void apply(ClipPtr clip) { }\n    virtual void unapply(ClipPtr clip) { }\n\n    virtual void apply(GroupPtr group) { }\n    virtual void unapply(GroupPtr group) { }\n};\n\n// This class lets us customize\n//   1. The order a node gets traversed in\n//   2. What nodes get traversed\nclass Traversal \n{\npublic:\n    virtual ~Traversal() { } // Make the destructor virtual\n\n    virtual void traverse(ShapePtr shape, VisitorPtr visitor) = 0;\n    virtual void traverse(TransformPtr transform, VisitorPtr visitor) = 0;\n    virtual void traverse(ClipPtr clip, VisitorPtr visitor) = 0;\n\tvirtual void traverse(GroupPtr group, VisitorPtr visitor) = 0;\n\tvirtual void traverse(TextPtr group, VisitorPtr visitor) = 0;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Traversal implementations\nclass GenericTraversal : public Traversal\n{\npublic:\n    virtual void traverse(ShapePtr shape, VisitorPtr visitor);\n    virtual void traverse(TransformPtr transform, VisitorPtr visitor);\n    virtual void traverse(ClipPtr clip, VisitorPtr visitor);\n\tvirtual void traverse(GroupPtr group, VisitorPtr visitor);\n\tvirtual void traverse(TextPtr group, VisitorPtr visitor);\n};\n\nclass ReverseTraversal : public GenericTraversal \n{\npublic:\n    void traverse(GroupPtr group, VisitorPtr visitor);\n};\n\nclass ForEachShapeTraversal : public GenericTraversal\n{\npublic:\n    void traverse(ClipPtr clip, VisitorPtr visitor);\n};\n\nclass ForEachTransformTraversal : public GenericTraversal\n{\npublic:\n    void traverse(ShapePtr shape, VisitorPtr visitor) { }  // ignore shapes\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Visitor implementations\nclass MatrixSaveVisitor : public Visitor \n{\nprotected:\n    stack<float4x4> matrix_stack;\n\npublic:\n    MatrixSaveVisitor();\n    virtual ~MatrixSaveVisitor();\n    void apply(TransformPtr transform);\n    void unapply(TransformPtr transform);\n};\n\n// OK to just inherit from MatrixSaveVisitor because the ClipPathSaveVisitor\n// requires a matrix anyway\nclass ClipSaveVisitor : public MatrixSaveVisitor \n{\nprotected:\n    struct ClipAndMatrix {\n        ClipAndMatrix(ClipPtr c, float4x4 m)\n            : clip(c)\n            , matrix(m) { }\n        ClipPtr clip;\n        float4x4 matrix;\n    };\n    vector<ClipAndMatrix> clip_stack;\n    \t\npublic:\n    virtual ~ClipSaveVisitor();\n    void apply(ClipPtr clip);\n    void unapply(ClipPtr clip);\n};\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Other visitors \nclass Invalidate : public Visitor \n{\npublic:\n    void visit(ShapePtr shape);\n};\n\nclass FlushRendererStates : public Visitor \n{\npublic:\n    void visit(ShapePtr shape);\n};\n\nclass FlushRendererState : public Visitor\n{\npublic:\n    FlushRendererState(RendererPtr renderer_) : renderer(renderer_) { }\n    void visit(ShapePtr shape);\n\nprotected:\n    RendererPtr renderer;\n};\n\nclass InvalidateRendererStates : public Visitor \n{\npublic:\n    void visit(ShapePtr shape);\n};\n\nclass InvalidateRendererState : public Visitor \n{\npublic:\n    InvalidateRendererState(RendererPtr renderer_) : renderer(renderer_) { }\nvoid visit(ShapePtr shape);\n\nprotected:\n    RendererPtr renderer;\n};\n\nclass CountVisitor : public Visitor {\npublic:\n    CountVisitor()\n        : count(0)\n    { }\n    inline int getCount() { return count; }\n\nprotected:\n    int count;\n};\n\nclass CountSegments : public CountVisitor  {\npublic:\n    void visit(ShapePtr shape);\n};\ntypedef shared_ptr<CountSegments> CountSegmentsPtr;\n\nclass CountNonOpaqueObjects : public CountVisitor  {\npublic:\n    void visit(ShapePtr shape);\n};\ntypedef shared_ptr<CountNonOpaqueObjects> CountNonOpaqueObjectsPtr;\n\nextern float2 clipToSurfaceScales(float w, float h, float scene_ratio);\nextern float4x4 surfaceToClip(float w, float h, float scene_ratio);\n\n#endif // __scene_hpp__\n", "meta": {"hexsha": "efb63a4a071d30e30de1ac1a6fad2051e7a12fa6", "size": 19713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Algorithm/svgpp/nvprsvg/scene.hpp", "max_stars_repo_name": "dolphin-li/ClothDesigner", "max_stars_repo_head_hexsha": "82b186d6db320b645ac67a4d32d7746cc9bdd391", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2016-12-13T05:49:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T06:15:47.000Z", "max_issues_repo_path": "Algorithm/svgpp/nvprsvg/scene.hpp", "max_issues_repo_name": "dolphin-li/ClothDesigner", "max_issues_repo_head_hexsha": "82b186d6db320b645ac67a4d32d7746cc9bdd391", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T02:01:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-12T15:06:51.000Z", "max_forks_repo_path": "Algorithm/svgpp/nvprsvg/scene.hpp", "max_forks_repo_name": "dolphin-li/ClothDesigner", "max_forks_repo_head_hexsha": "82b186d6db320b645ac67a4d32d7746cc9bdd391", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2017-11-16T13:37:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T08:13:46.000Z", "avg_line_length": 26.2140957447, "max_line_length": 112, "alphanum_fraction": 0.6755947852, "num_tokens": 4736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17534290043917714}}
{"text": "#include \"WLSEventAction.hh\"\n\n#include \"G4Event.hh\"\n#include \"G4EventManager.hh\"\n#include \"G4CerenkovNew.hh\"\n#include \"WLSSteppingAction.hh\"\n#include \"WLSStackingAction.hh\"\n#include \"WLSDetectorConstruction.hh\"\n\n#include \"Randomize.hh\"\n#include <TMath.h>\n#include <TFitResult.h>\n#include <TFitResultPtr.h>\n#include <TF1.h>\n#include <TH1D.h>\n#include <TH2D.h>\n#include <TH3D.h>\n#include <TNtuple.h>\n#include <TFile.h>\n\n#include <TStyle.h>\n#include <TText.h>\n#include <TGraph.h>\n#include <TMarker.h>\n#include <TGaxis.h>\n#include <TCanvas.h>\n#include <TPaveStats.h>\n\n#include \"MakeCrvPhotons.hh\"\n#include \"MakeCrvSiPMCharges.hh\"\n#include \"MakeCrvWaveforms.hh\"\n#include \"MakeCrvDigis.hh\"\n#include \"MakeCrvRecoPulses.hh\"\n\n#include <stdexcept>\n#include <boost/shared_ptr.hpp>\n\n#include \"CLHEP/Random/Randomize.h\"\n\nWLSEventAction* WLSEventAction::_fgInstance = NULL;\n\nWLSEventAction::WLSEventAction(WLSSteppingAction::simulationMode mode, const std::string &singlePEWaveformFilename, const std::string &photonMapFilename,  \n                               int numberOfPhotons, int simType, unsigned int minBin, bool verbose) : \n                                                                                         _mode(mode), \n                                                                                         _numberOfPhotons(numberOfPhotons), \n                                                                                         _simType(simType), \n                                                                                         _minBin(minBin), \n                                                                                         _currentBin(minBin), \n                                                                                         _singlePEWaveformFilename(singlePEWaveformFilename), \n                                                                                         _photonMapFilename(photonMapFilename), \n                                                                                         _verbose(verbose)\n                               //numberOfPhotons, simType, minBin, currentBin, verbose is only needed for simulationMode::CreateLookupTables\n{\n  _fgInstance = this;\n\n  if(_mode==WLSSteppingAction::UseGeantOnly || _mode==WLSSteppingAction::UseGeantAndLookupTables)\n  {\n    for(int SiPM=0; SiPM<4; SiPM++)\n    {\n      std::stringstream s0, s1, title;\n      s0<<\"Photons_Geant_SiPM_\"<<SiPM;\n      s1<<\"Photons_LookupTable_SiPM_\"<<SiPM;\n      title<<\"Fiber: \"<<SiPM/2<<\",  Side: \"<<SiPM%2;\n      _histP[0][SiPM] = new TH1D(s0.str().c_str(),title.str().c_str(),1000,0,1000);\n      _histP[1][SiPM] = new TH1D(s1.str().c_str(),title.str().c_str(),1000,0,1000);\n      _histP[0][SiPM]->GetXaxis()->SetTitle(\"Photons\");\n      _histP[0][SiPM]->SetLineColor(1);\n      _histP[1][SiPM]->GetXaxis()->SetTitle(\"Photons\");\n      _histP[1][SiPM]->SetLineColor(2);\n    }\n\n    for(int SiPM=0; SiPM<4; SiPM++)\n    {\n      std::stringstream s0, s1, title;\n      s0<<\"ArrivalTimes_Geant_SiPM_\"<<SiPM;\n      s1<<\"ArrivalTimes_LookupTable_SiPM_\"<<SiPM;\n      title<<\"Fiber: \"<<SiPM/2<<\",  Side: \"<<SiPM%2;\n      _histT[0][SiPM] = new TH1D(s0.str().c_str(),title.str().c_str(),250,0,250);\n      _histT[1][SiPM] = new TH1D(s1.str().c_str(),title.str().c_str(),250,0,250);\n      _histT[0][SiPM]->GetXaxis()->SetTitle(\"t [ns]\");\n      _histT[0][SiPM]->SetLineColor(1);\n      _histT[1][SiPM]->GetXaxis()->SetTitle(\"t [ns]\");\n      _histT[1][SiPM]->SetLineColor(2);\n    }\n\n    for(int SiPM=0; SiPM<4; SiPM++)\n    {\n      std::stringstream s0, title;\n      s0<<\"PEs_SiPM_\"<<SiPM;\n      title<<\"Fiber: \"<<SiPM/2<<\",  Side: \"<<SiPM%2;\n      _histPE[SiPM] = new TH1D(s0.str().c_str(),title.str().c_str(),500,0,500);\n      _histPE[SiPM]->GetXaxis()->SetTitle(\"PEs\");\n      _histPE[SiPM]->SetLineColor(1);\n    }\n\n    _ntuple = new TNtuple(\"CRVNtuple\",\"CRVNtuple\",\"SiPM:photons:PEs:pulseHeight:pulseBeta:recoPEs:pulseTime:LEtime:chi2\");\n  }\n}\n\nWLSEventAction::~WLSEventAction()\n{\n  if(_mode==WLSSteppingAction::UseGeantOnly || _mode==WLSSteppingAction::UseGeantAndLookupTables)\n  {\n    for(int SiPM=0; SiPM<4; SiPM++)\n    {\n      delete _histP[0][SiPM];\n      delete _histP[1][SiPM];\n      delete _histT[0][SiPM];\n      delete _histT[1][SiPM];\n      delete _histPE[SiPM];\n    }\n  \n    _ntuple->SaveAs(\"CRVNtuple.root\");\n    delete _ntuple;\n  }\n\n}\n\nvoid WLSEventAction::BeginOfEventAction(const G4Event* evt)\n{\n  std::cout<<\"Event # \"<<evt->GetEventID()<<std::endl;\n\n  WLSSteppingAction::Instance()->Reset();\n}\n\nvoid WLSEventAction::EndOfEventAction(const G4Event* evt)\n{\n  //create entry in lookup tables\n  if(_mode==WLSSteppingAction::CreateLookupTables)\n  {\n    WLSDetectorConstruction *detector = WLSDetectorConstruction::Instance();\n\n    mu2eCrv::LookupBin bin;\n\n    bin.binNumber = _currentBin;  //gets set by WLSPrimaryGenerator\n\n    bin.arrivalProbability=0;\n    bin.timeDelays.clear();\n    bin.fiberEmissions.clear();\n\n    //prepare histograms\n    int histTimeDifference[mu2eCrv::LookupBin::maxTimeDelays]={0}; //in ns\n    int histEmissions[mu2eCrv::LookupBin::maxFiberEmissions]={0};\n    int maxTimeDifference=0;\n    int maxEmissions=0;\n    int arrivingPhotons=0;\n\n    //Lookup tables are created only for SiPM# 0 due to symmetry reasons\n    const std::vector<WLSSteppingAction::PhotonInfo> &photonInfo = WLSSteppingAction::Instance()->GetPhotonInfo(0);\n    for(size_t i=0; i<photonInfo.size(); i++)\n    {\n      //extract travel times\n      int timeDifference=static_cast<int>(photonInfo[i]._arrivalTime+0.5); //rounded to full ns  \n                                                                  //the WLS decay time has been set to 0 for mode=CreateLookupTables\n                                                                  //so that the true travel time can be determined\n                                                                  //(in WLSPrimaryGeneratorAction)\n      if(timeDifference<0) timeDifference=0;\n      if(timeDifference>=mu2eCrv::LookupBin::maxTimeDelays) continue;\n\n      //extract number of fiber emissions\n      int nEmissions=photonInfo[i]._fiberEmissions;\n      if(nEmissions<0) nEmissions=0;\n      if(nEmissions>=mu2eCrv::LookupBin::maxFiberEmissions) continue;\n\n      //fill histogram bins\n      histTimeDifference[timeDifference]++;   //fill this histogram bin\n      histEmissions[nEmissions]++;\n\n      if(timeDifference>maxTimeDifference) maxTimeDifference=timeDifference;\n      if(nEmissions>maxEmissions) maxEmissions=nEmissions;\n\n      arrivingPhotons++; //only count photons for which the arrival time and number of fiber emissions \n                         //can be stored in the histograms\n    }\n\n    if(arrivingPhotons>0)\n    {\n      bin.arrivalProbability=static_cast<float>(arrivingPhotons)/static_cast<float>(_generatedPhotons);\n                                                              //_generatedPhotons gets set by WLSPrimaryGeneratorAction\n                                                              //after sending out all photons\n\n      //store time time delay histogram in bin\n      bin.timeDelays.reserve(maxTimeDifference+1);\n      for(int i=0; i<=maxTimeDifference; i++)\n      {\n        float p=static_cast<float>(histTimeDifference[i])/static_cast<float>(arrivingPhotons);\n        //multiplying the probability with the probability scale makes it possible to store it as an unsigned char\n        unsigned char pChar = static_cast<unsigned char>(mu2eCrv::LookupBin::probabilityScale*p+0.5);\n        bin.timeDelays.push_back(pChar);\n      }\n\n      //store fiber emission histogram in bin\n      bin.fiberEmissions.reserve(maxEmissions+1);\n      for(int i=0; i<=maxEmissions; i++)\n      {\n        float p=static_cast<float>(histEmissions[i])/static_cast<float>(arrivingPhotons);\n        //multiplying the probability with the probability scale makes it possible to store it as an unsigned char\n        unsigned char pChar = static_cast<unsigned char>(mu2eCrv::LookupBin::probabilityScale*p+0.5);\n        bin.fiberEmissions.push_back(pChar);\n      }\n    }\n\n    if(_verbose)\n    {\n      std::streamsize origPrecision = std::cout.precision();\n      std::cout.precision(10);\n      float p=bin.arrivalProbability;\n      std::cout<<\"Probability: \"<<p<<std::endl;\n      std::cout.precision(origPrecision);\n      std::cout<<\"Time Difference Probabilities: \";\n      for(size_t i=0; i<bin.timeDelays.size(); i++) std::cout<<i<<\"/\"<<(int)bin.timeDelays[i]<<\" \";\n      std::cout<<std::endl;\n      std::cout<<\"Fiber Emissions Probabilities: \";\n      for(size_t i=0; i<bin.fiberEmissions.size(); i++) std::cout<<i<<\"/\"<<(int)bin.fiberEmissions[i]<<\" \";\n      std::cout<<std::endl<<std::endl;\n    }\n\n    std::stringstream filename;\n    filename<<\"LookupTable_\"<<_simType<<\"_\";\n    filename.fill('0');\n    filename.width(6);\n    filename<<_minBin;\n    if(evt->GetEventID()==0) std::remove(filename.str().c_str());  //remove existing file\n\n//write some constants to the file before the first bin\n    if(_simType==0 && _currentBin==0)\n    {\n      G4Material *scintillator = G4Material::GetMaterial(\"PolystyreneScint\",true); //scintillator\n      G4MaterialPropertiesTable *scintillatorPropertiesTable = scintillator->GetMaterialPropertiesTable();\n      G4MaterialPropertyVector *rindexScintillator = scintillatorPropertiesTable->GetProperty(\"RINDEX\");\n  \n      G4Material *fiber = G4Material::GetMaterial(\"PolystyreneFiber\",true); //fiber\n      G4MaterialPropertiesTable* fiberPropertiesTable = fiber->GetMaterialPropertiesTable();\n      G4MaterialPropertyVector *rindexFiber = fiberPropertiesTable->GetProperty(\"RINDEX\");\n\n      mu2eCrv::LookupConstants LC;\n      LC.version1           = 6;\n      LC.version2           = 0;\n      LC.reflector          = detector->GetReflectorOption();\n      LC.halfThickness      = detector->GetScintillatorHalfThickness(),\n      LC.halfWidth          = detector->GetScintillatorHalfWidth(), \n      LC.halfLength         = detector->GetScintillatorHalfLength(),\n      LC.fiberSeparation    = detector->GetFiberSeparation(),\n      LC.holeRadiusX        = detector->GetHoleRadiusX(),\n      LC.holeRadiusY        = detector->GetHoleRadiusY(),\n      LC.fiberRadius        = detector->GetClad2Radius();\n      LC.scintillatorCornerRadius  = detector->GetScintillatorCornerRadius();\n      LC.scintillatorBirksConstant = scintillator->GetIonisation()->GetBirksConstant();\n      LC.WLSfiberDecayTime         = fiberPropertiesTable->GetConstProperty(\"WLSTIMECONSTANT\");\n      LC.Write(filename.str());\n\n      mu2eCrv::LookupCerenkov LCerenkov;\n      G4CerenkovNew *cerenkov = G4CerenkovNew::Instance();\n      for(double beta=1.0; ; beta/=1.01)\n      {\n        double photonsScintillator=cerenkov->GetAverageNumberOfPhotons(CLHEP::eplus, beta, scintillator, rindexScintillator);\n        double photonsFiber=cerenkov->GetAverageNumberOfPhotons(CLHEP::eplus, beta, fiber, rindexFiber);\n        LCerenkov.photonsScintillator[beta]=photonsScintillator;\n        LCerenkov.photonsFiber[beta]=photonsFiber;\n        if(photonsScintillator==0 && photonsFiber==0) break;\n      }\n      LCerenkov.Write(filename.str());\n\n      mu2eCrv::LookupBinDefinitions LBD;\n      LBD.xBins     = WLSDetectorConstruction::Instance()->GetXBins();\n      LBD.yBins     = WLSDetectorConstruction::Instance()->GetYBins();\n      LBD.zBins     = WLSDetectorConstruction::Instance()->GetZBins();\n      LBD.betaBins  = WLSDetectorConstruction::Instance()->GetBetaBins();\n      LBD.thetaBins = WLSDetectorConstruction::Instance()->GetThetaBins();\n      LBD.phiBins   = WLSDetectorConstruction::Instance()->GetPhiBins();\n      LBD.rBins     = WLSDetectorConstruction::Instance()->GetRBins();\n      LBD.Write(filename.str());\n    }\n\n//write the data to file\n    bin.Write(filename.str());\n  }\n\n  //fill histograms if a simulation is run\n  if(_mode==WLSSteppingAction::UseGeantOnly || _mode==WLSSteppingAction::UseGeantAndLookupTables)\n  {\n    for(int SiPM=0; SiPM<4; SiPM++)\n    {\n      _histP[0][SiPM]->Fill(WLSSteppingAction::Instance()->GetPhotonInfo(SiPM).size());\n      _histP[1][SiPM]->Fill(WLSSteppingAction::Instance()->GetArrivalTimesFromLookupTables(SiPM).size());\n      const std::vector<WLSSteppingAction::PhotonInfo> &photonInfo = WLSSteppingAction::Instance()->GetPhotonInfo(SiPM);\n      const std::vector<double> &arrivalTimesFromLookupTables = WLSSteppingAction::Instance()->GetArrivalTimesFromLookupTables(SiPM);\n      for(size_t i=0; i<photonInfo.size(); i++) _histT[0][SiPM]->Fill(photonInfo[i]._arrivalTime);\n      for(size_t i=0; i<arrivalTimesFromLookupTables.size(); i++) _histT[1][SiPM]->Fill(arrivalTimesFromLookupTables[i]);\n    }\n\n    Draw(evt);\n\n    std::cout<<\"Photons: \";\n    for(int SiPM=0; SiPM<4; SiPM++) std::cout<<_histP[0][SiPM]->GetMean()<<\"/\"<<_histP[1][SiPM]->GetMean()<<\"  \";\n    std::cout<<std::endl;\n    std::cout<<\"PEs: \";\n    for(int SiPM=0; SiPM<4; SiPM++) std::cout<<_histPE[SiPM]->GetMean()<<\"       \";\n    std::cout<<std::endl;\n    std::cout<<\"Times: \";\n    for(int SiPM=0; SiPM<4; SiPM++) std::cout<<_histT[0][SiPM]->GetMean()<<\"/\"<<_histT[1][SiPM]->GetMean()<<\"  \";\n    std::cout<<std::endl;\n  }\n\n  WLSStackingAction::Instance()->PrintStatus();\n  WLSSteppingAction::Instance()->PrintFiberStats();\n}\n\nvoid WLSEventAction::Draw(const G4Event* evt) \n{\n  double maxTime=200.0;\n\n  mu2eCrv::MakeCrvSiPMCharges::ProbabilitiesStruct probabilities;\n  probabilities._avalancheProbParam1 = 0.607;\n  probabilities._avalancheProbParam2 = 2.7;\n  probabilities._trapType0Prob = 0.0;\n  probabilities._trapType1Prob = 0.0;\n  probabilities._trapType0Lifetime = 5;\n  probabilities._trapType1Lifetime = 50;\n  probabilities._thermalRate = 3.0e-4;   \n  probabilities._crossTalkProb = 0.09;  //at 2017 test beam\n\n  int nPixelsX=40;\n  int nPixelsY=40;\n  double overvoltage=3.0;  //at 2017 test beam\n  double timeConstant=13.3;\n  double capacitance=8.84e-14;\n  std::vector<std::pair<int,int> > inactivePixels = { {18,18}, {18,19}, {18,20}, {18,21},\n                                                      {19,18}, {19,19}, {19,20}, {19,21},\n                                                      {20,18}, {20,19}, {20,20}, {20,21},\n                                                      {21,18}, {21,19}, {21,20}, {21,21} };\n\n  static CLHEP::HepJamesRandom engine(1);\n  static CLHEP::RandFlat randFlat(engine);\n  static CLHEP::RandGaussQ randGaussQ(engine);\n  static CLHEP::RandPoissonQ randPoissonQ(engine);\n  mu2eCrv::MakeCrvSiPMCharges sim(randFlat,randPoissonQ,_photonMapFilename.c_str());\n  sim.SetSiPMConstants(nPixelsX, nPixelsY, overvoltage, timeConstant, capacitance, probabilities, inactivePixels);\n\n  mu2eCrv::MakeCrvWaveforms makeCrvWaveform;\n  double singlePEWaveformPrecision=0.5;\n  double singlePEWaveformStretchFactor=1.047;\n  double singlePEWaveformMaxTime=100.0;\n  double singlePEReferenceCharge=2.652e-13;\n  double digitizationInterval = 12.55; //ns\n  double digitizationInterval2 = 1.0; //ns\n  double noise = 4.0e-4;\n  double pedestal = 100; //ADC\n  double ADCconversionFactor = 2300; //ADC/V\n  double calibrationFactor = 391.2; //ADC*ns/PE\n  double calibrationFactorPulseHeight = 11.4; //ADC/PE\n  makeCrvWaveform.LoadSinglePEWaveform(_singlePEWaveformFilename.c_str(),\n                                       singlePEWaveformPrecision, singlePEWaveformStretchFactor,\n                                       singlePEWaveformMaxTime, singlePEReferenceCharge);\n\n  mu2eCrv::MakeCrvDigis makeCrvDigis;\n\n  boost::shared_ptr<mu2eCrv::MakeCrvRecoPulses> makeRecoPulses[4];\n\n  double startTimeGlobal=G4UniformRand()*digitizationInterval;  //cannot be negative\n  std::vector<double> siPMtimes[4], siPMcharges[4], siPMchargesInPEs[4];\n  std::vector<double> waveform[4], waveform2[4];\n  std::vector<unsigned int> ADCs[4], ADCs2[4];\n  unsigned int TDC, TDC2;\n  for(int SiPM=0; SiPM<4; SiPM++)\n  {\n    std::vector<std::pair<double, size_t> > photonTimes;\n    if(_mode==WLSSteppingAction::UseGeantAndLookupTables)\n    {\n      const std::vector<double> &photonTimesTmp = WLSSteppingAction::Instance()->GetArrivalTimesFromLookupTables(SiPM);\n      for(size_t i=0; i<photonTimesTmp.size(); i++) photonTimes.emplace_back(std::pair<double,size_t>(photonTimesTmp[i],0));\n    }\n    else\n    {\n      const std::vector<WLSSteppingAction::PhotonInfo> &photonInfo = WLSSteppingAction::Instance()->GetPhotonInfo(SiPM);\n      for(size_t i=0; i<photonInfo.size(); i++) photonTimes.emplace_back(std::pair<double,size_t>(photonInfo[i]._arrivalTime,0));\n    }\n    int photons = photonTimes.size();\n\n    std::vector<mu2eCrv::SiPMresponse> SiPMresponseVector;\n    sim.Simulate(photonTimes, SiPMresponseVector, 0.0, maxTime);\n    double PEs=0;\n    double firstTime=NAN;\n    for(size_t i=0; i<SiPMresponseVector.size(); i++)\n    {\n      siPMtimes[SiPM].push_back(SiPMresponseVector[i]._time);\n      siPMcharges[SiPM].push_back(SiPMresponseVector[i]._charge);\n      siPMchargesInPEs[SiPM].push_back(SiPMresponseVector[i]._chargeInPEs);\n      PEs+=SiPMresponseVector[i]._chargeInPEs;\n      if(isnan(firstTime) || firstTime>SiPMresponseVector[i]._time) firstTime=SiPMresponseVector[i]._time;\n    }\n    _histPE[SiPM]->Fill(PEs);\n\n    double startTime=startTimeGlobal;\n    if(firstTime<startTime) startTime=firstTime*G4UniformRand();  //earliest charge cannot be before start time\n\n    makeCrvWaveform.MakeWaveform(siPMtimes[SiPM], siPMcharges[SiPM], waveform[SiPM], startTime, digitizationInterval);\n    makeCrvWaveform.MakeWaveform(siPMtimes[SiPM], siPMcharges[SiPM], waveform2[SiPM], startTime, digitizationInterval2);\n\n    makeCrvWaveform.AddElectronicNoise(waveform[SiPM], noise, randGaussQ);\n    makeCrvWaveform.AddElectronicNoise(waveform2[SiPM], noise, randGaussQ);\n\n    makeCrvDigis.SetWaveform(waveform[SiPM], ADCconversionFactor, pedestal, startTime, digitizationInterval);\n    ADCs[SiPM] = makeCrvDigis.GetADCs();\n    TDC = makeCrvDigis.GetTDC();\n    makeCrvDigis.SetWaveform(waveform2[SiPM], ADCconversionFactor, pedestal, startTime, digitizationInterval2);\n    ADCs2[SiPM] = makeCrvDigis.GetADCs();\n    TDC2 = makeCrvDigis.GetTDC();\n\n    float minADCdifference=5;\n    float defaultBeta=19.0;\n    float minBeta=5.0;\n    float maxBeta=40.0;\n    float maxTimeDifference=15.0;\n    float minPulseHeightRatio=0.7;\n    float maxPulseHeightRatio=1.5;\n    float LEtimeFactor=0.985;\n    bool  allowDoubleGumbel=false;\n    float doubleGumbelThreshold=2.0;\n    makeRecoPulses[SiPM]=boost::shared_ptr<mu2eCrv::MakeCrvRecoPulses>(new mu2eCrv::MakeCrvRecoPulses(minADCdifference, defaultBeta, minBeta, maxBeta,\n                                                                                                      maxTimeDifference, minPulseHeightRatio, \n                                                                                                      maxPulseHeightRatio, LEtimeFactor,\n                                                                                                      allowDoubleGumbel, doubleGumbelThreshold));\n    makeRecoPulses[SiPM]->SetWaveform(ADCs[SiPM], TDC, digitizationInterval, pedestal, calibrationFactor, calibrationFactorPulseHeight);\n    if(makeRecoPulses[SiPM]->GetPEs().size()>0) \n    {\n      double pulseHeight=0;\n      double recoPEs= 0;\n      double pulseBeta=0;\n      double pulseTime=0;\n      double LEtime=0;\n      double pulseChi2=0;\n      for(size_t j=0; j<makeRecoPulses[SiPM]->GetPEs().size(); j++)\n      {\n         double recoPEsTmp = makeRecoPulses[SiPM]->GetPEs().at(j);\n         if(recoPEsTmp>recoPEs)\n         {\n           recoPEs=recoPEsTmp;\n           pulseHeight = makeRecoPulses[SiPM]->GetPulseHeights().at(j);\n           pulseBeta = makeRecoPulses[SiPM]->GetPulseBetas().at(j);\n           pulseTime = makeRecoPulses[SiPM]->GetPulseTimes().at(j);\n           LEtime = makeRecoPulses[SiPM]->GetLEtimes().at(j);\n           pulseChi2 = makeRecoPulses[SiPM]->GetPulseFitChi2s().at(j);\n         }\n      }\n      _ntuple->Fill(SiPM,photons,PEs,pulseHeight,pulseBeta,recoPEs,pulseTime,LEtime,pulseChi2);\n      _PEs[SiPM].push_back(PEs);\n      _recoPEs[SiPM].push_back(recoPEs);\n      _pulseTimes[SiPM].push_back(pulseTime);\n      _LETimes[SiPM].push_back(LEtime);\n      _pulseBetas[SiPM].push_back(pulseBeta);\n      double avgPEs=0;\n      double avgrecoPEs=0;\n      double avgPulseTime=0;\n      double avgLETime=0;\n      double avgPulseBeta=0;\n      for(size_t j=0; j<_PEs[SiPM].size(); j++) {avgPEs+=_PEs[SiPM][j];}\n      for(size_t j=0; j<_recoPEs[SiPM].size(); j++) {avgrecoPEs+=_recoPEs[SiPM][j];}\n      for(size_t j=0; j<_pulseTimes[SiPM].size(); j++) {avgPulseTime+=_pulseTimes[SiPM][j];}\n      for(size_t j=0; j<_LETimes[SiPM].size(); j++) {avgLETime+=_LETimes[SiPM][j];}\n      for(size_t j=0; j<_pulseBetas[SiPM].size(); j++) {avgPulseBeta+=_pulseBetas[SiPM][j];}\n      avgPEs/=_PEs[SiPM].size();\n      avgrecoPEs/=_recoPEs[SiPM].size();\n      avgPulseTime/=_pulseTimes[SiPM].size();\n      avgLETime/=_LETimes[SiPM].size();\n      avgPulseBeta/=_pulseBetas[SiPM].size();\n      std::cout<<\"SiPM: \"<<SiPM<<\" PEs: \"<<PEs<<\"  avg: \"<<avgPEs<<\"     recoPEs: \"<<recoPEs<<\"(\"<<recoPEs/PEs<<\") avg: \"<<avgrecoPEs<<\"(\"<<avgrecoPEs/avgPEs<<\")   \";\n      std::cout<<\"avgtime:\"<<avgPulseTime<<\"/\"<<avgLETime<<\"       width:\"<<pulseBeta<<\"  avg:\"<<avgPulseBeta<<\"   height:\"<<pulseHeight<<\"  \";\n      std::cout<<\"nPulses:\"<<makeRecoPulses[SiPM]->GetPEs().size()<<std::endl;\n    }\n  }\n\n//Plotting things\n  std::ostringstream s1;\n  s1<<\"waveform_\"<<evt->GetEventID();\n\n  gStyle->SetOptStat(0);\n  TCanvas c(s1.str().c_str(),s1.str().c_str(),1000,1000);\n  c.Divide(2,2);\n  TGraph *graph[4]={NULL};\n  TGraph *graph2[4]={NULL};\n  TH1D *hist[4], *histSiPMResponse[4];\n\n  if(evt->GetEventID()<20)\n  {\n  std::vector<TGraph*> graphVector;\n  std::vector<TMarker*> markerVector;\n  std::vector<TGaxis*> axisVector;\n\n  for(int SiPM=0; SiPM<4; SiPM++)\n  {\n    c.cd(SiPM+1);\n\n//Photon Arrival Times\n    std::ostringstream s2, s3;\n    s2<<\"Photons_\"<<evt->GetEventID()<<\"__\"<<SiPM;\n    s3<<\"Fiber: \"<<SiPM/2<<\",  Side: \"<<SiPM%2;\n    hist[SiPM]=new TH1D(s2.str().c_str(),s3.str().c_str(),100,0,maxTime);\n    if(_mode==WLSSteppingAction::UseGeantAndLookupTables)\n    {\n      const std::vector<double> &photonTimesTmp = WLSSteppingAction::Instance()->GetArrivalTimesFromLookupTables(SiPM);\n      for(size_t i=0; i<photonTimesTmp.size(); i++) hist[SiPM]->Fill(photonTimesTmp[i]);\n    }\n    else\n    {\n      const std::vector<WLSSteppingAction::PhotonInfo> &photonInfo = WLSSteppingAction::Instance()->GetPhotonInfo(SiPM);\n      for(size_t i=0; i<photonInfo.size(); i++) hist[SiPM]->Fill(photonInfo[i]._arrivalTime);\n    }\n\n    hist[SiPM]->SetLineColor(kBlue);\n    hist[SiPM]->GetXaxis()->SetTitle(\"t [ns]\");\n    hist[SiPM]->GetXaxis()->SetTitleOffset(0.8);\n    hist[SiPM]->GetXaxis()->SetTitleSize(0.05);\n    hist[SiPM]->GetYaxis()->SetTitle(\"Photons\");\n    hist[SiPM]->GetYaxis()->SetTitleOffset(0.8);\n    hist[SiPM]->GetYaxis()->SetTitleSize(0.05);\n    hist[SiPM]->GetYaxis()->SetAxisColor(kBlue);\n    hist[SiPM]->GetYaxis()->SetTitleColor(kBlue);\n    hist[SiPM]->GetYaxis()->SetLabelColor(kBlue);\n    hist[SiPM]->Draw();\n\n//SiPM response\n    double scaleSiPMResponse = 1.0;\n    double totalPEs=0;\n    histSiPMResponse[SiPM]=new TH1D((s2.str()+\"SiPMResponse\").c_str(),\"\",100,0,maxTime);\n    for(unsigned int j=0; j<siPMtimes[SiPM].size(); j++)\n    {\n      histSiPMResponse[SiPM]->Fill(siPMtimes[SiPM][j], siPMchargesInPEs[SiPM][j]*scaleSiPMResponse);\n      totalPEs+=siPMchargesInPEs[SiPM][j];\n    }\n    histSiPMResponse[SiPM]->SetLineColor(kOrange-6);\n    histSiPMResponse[SiPM]->Draw(\"histsame\");\n\n//waveforms with 1 ns bin width\n    unsigned int n2 = ADCs2[SiPM].size();\n    if(n2==0) continue;\n    double *t2 = new double[n2];\n    double *v2 = new double[n2];\n    double histMax = hist[SiPM]->GetMaximum();\n    double waveformMax = *std::max_element(ADCs2[SiPM].begin(),ADCs2[SiPM].end());\n    double scale = histMax/waveformMax;\n    for(unsigned int j=0; j<n2; j++)\n    {\n      t2[j]=(TDC2+j)*digitizationInterval2;\n      v2[j]=ADCs2[SiPM][j];\n      v2[j]*=scale;\n    }\n    graph2[SiPM]=new TGraph();\n    graph2[SiPM]->SetTitle(\"\");\n    graph2[SiPM]->SetLineWidth(1);\n    graph2[SiPM]->SetLineColor(kRed);\n    graph2[SiPM]->DrawGraph(n2,t2,v2,\"same\");\n\n    delete[] t2;\n    delete[] v2;\n\n//waveforms with 12.55 ns bin width\n    unsigned int n = ADCs[SiPM].size();\n    if(n==0) continue;\n    double *t = new double[n];\n    double *v = new double[n];\n    for(unsigned int j=0; j<n; j++)\n    {\n      t[j]=(TDC+j)*digitizationInterval;\n      v[j]=ADCs[SiPM][j];\n      v[j]*=scale;\n    }\n    graph[SiPM]=new TGraph(n,t,v);\n    graph[SiPM]->SetTitle(\"\");\n    graph[SiPM]->SetMarkerStyle(20);\n    graph[SiPM]->SetMarkerSize(1.5);\n    graph[SiPM]->SetMarkerColor(kRed);\n    graph[SiPM]->Draw(\"sameP\");\n\n    delete[] t;\n    delete[] v;\n\n//fit\n    unsigned int nPulse = makeRecoPulses[SiPM]->GetPEs().size();\n    for(unsigned int pulse=0; pulse<nPulse; pulse++)\n    {\n      if(isnan(makeRecoPulses[SiPM]->GetPulseBetas().at(pulse))) continue;\n      double tF1=makeRecoPulses[SiPM]->GetPulseStarts().at(pulse);\n      double tF2=makeRecoPulses[SiPM]->GetPulseEnds().at(pulse);\n      int nF=(tF2-tF1)/1.0 + 1;\n      double *tF = new double[nF];\n      double *vF = new double[nF];\n      for(int iF=0; iF<nF; iF++)\n      {\n        double p0 = makeRecoPulses[SiPM]->GetPulseHeights().at(pulse)*TMath::E();\n        double p1 = makeRecoPulses[SiPM]->GetPulseTimes().at(pulse);\n        double p2 = makeRecoPulses[SiPM]->GetPulseBetas().at(pulse);\n        tF[iF] = tF1 + iF*1.0;\n        vF[iF] = p0*TMath::Exp(-(tF[iF]-p1)/p2-TMath::Exp(-(tF[iF]-p1)/p2));\n        vF[iF]+=pedestal;\n        vF[iF]*=scale;\n        if(isnan(vF[iF])) nF=0;\n      }\n      if(nF>0)\n      {\n        TGraph *graphF=new TGraph();\n        graphVector.push_back(graphF);\n        graphF->SetTitle(\"\");\n        graphF->SetLineWidth(2);\n        graphF->SetLineColor(kGreen);\n        graphF->DrawGraph(nF,tF,vF,\"same\");\n      }\n\n      delete[] tF;\n      delete[] vF;\n    }\n\n    TGaxis *axis = new TGaxis(maxTime*0.9,0,maxTime*0.9,histMax,0,histMax/scale,10,\"+L\");\n    axisVector.push_back(axis);\n    axis->SetTitle(\"ADC\");\n    axis->SetTitleOffset(-0.5);\n    axis->SetTitleSize(0.05);\n    axis->SetTitleColor(kRed);\n    axis->SetLineColor(kRed);\n    axis->SetLabelColor(kRed);\n    axis->Draw(\"same\");\n\n    TGaxis *axisSiPMResponse = new TGaxis(maxTime,0,maxTime,histMax,0,histMax/scaleSiPMResponse,10,\"+L\");\n    axisVector.push_back(axisSiPMResponse);\n    axisSiPMResponse->SetTitle(\"SiPM charges [PE]\");\n    axisSiPMResponse->SetTitleOffset(0.85);\n    axisSiPMResponse->SetTitleSize(0.05);\n    axisSiPMResponse->SetTitleColor(kOrange-6);\n    axisSiPMResponse->SetLineColor(kOrange-6);\n    axisSiPMResponse->SetLabelColor(kOrange-6);\n    axisSiPMResponse->Draw(\"same\");\n  }\n\n  c.SaveAs((s1.str()+\".C\").c_str());\n\n  for(int SiPM=0; SiPM<4; SiPM++)\n  {\n    delete hist[SiPM];\n    delete histSiPMResponse[SiPM];\n    if(graph[SiPM]) delete graph[SiPM];\n    if(graph2[SiPM]) delete graph2[SiPM];\n  }\n  for(size_t i=0; i<graphVector.size(); i++) delete graphVector[i];\n  for(size_t i=0; i<markerVector.size(); i++) delete markerVector[i];\n  for(size_t i=0; i<axisVector.size(); i++) delete axisVector[i];\n  }\n\n  gStyle->SetOptStat(1111);\n  TCanvas c1(\"Photons\",\"Photons\",1000,1000);\n  c1.Divide(2,2);\n  for(int SiPM=0; SiPM<4; SiPM++)\n  {\n    c1.cd(SiPM+1);\n    gPad->SetLogy();\n    _histP[0][SiPM]->Draw();\n    gPad->Update();\n    TPaveStats *stats0 = (TPaveStats*)_histP[0][SiPM]->FindObject(\"stats\");\n    stats0->SetTextColor(1);\n    stats0->SetLineColor(1);\n    double X1 = stats0->GetX1NDC();\n    double Y1 = stats0->GetY1NDC();\n    double X2 = stats0->GetX2NDC();\n    double Y2 = stats0->GetY2NDC();\n    _histP[1][SiPM]->Draw();\n    gPad->Update();\n    TPaveStats *stats1 = (TPaveStats*)_histP[1][SiPM]->FindObject(\"stats\");\n    stats1->SetTextColor(2);\n    stats1->SetLineColor(2);\n    stats1->SetX1NDC(X1);\n    stats1->SetY1NDC(Y1-(Y2-Y1));\n    stats1->SetX2NDC(X2);\n    stats1->SetY2NDC(Y1);\n    _histP[0][SiPM]->Draw();\n    _histP[1][SiPM]->Draw(\"same\");\n  }      \n  c1.SaveAs(\"Photons.C\");\n\n  TCanvas c2(\"ArrivalTimes\",\"ArrivalTimes\",1000,1000);\n  c2.Divide(2,2);\n  for(int SiPM=0; SiPM<4; SiPM++)\n  {\n    c2.cd(SiPM+1);\n    gPad->SetLogy();\n    _histT[0][SiPM]->Draw();\n    gPad->Update();\n    TPaveStats *stats0 = (TPaveStats*)_histT[0][SiPM]->FindObject(\"stats\");\n    stats0->SetTextColor(1);\n    stats0->SetLineColor(1);\n    double X1 = stats0->GetX1NDC();\n    double Y1 = stats0->GetY1NDC();\n    double X2 = stats0->GetX2NDC();\n    double Y2 = stats0->GetY2NDC();\n    _histT[1][SiPM]->Draw();\n    gPad->Update();\n    TPaveStats *stats1 = (TPaveStats*)_histT[1][SiPM]->FindObject(\"stats\");\n    stats1->SetTextColor(2);\n    stats1->SetLineColor(2);\n    stats1->SetX1NDC(X1);\n    stats1->SetY1NDC(Y1-(Y2-Y1));\n    stats1->SetX2NDC(X2);\n    stats1->SetY2NDC(Y1);\n    _histT[0][SiPM]->Draw();\n    _histT[1][SiPM]->Draw(\"same\");\n  }      \n  c2.SaveAs(\"ArrivalTimes.C\");\n\n  TCanvas c3(\"PEs\",\"PEs\",1000,1000);\n  c3.Divide(2,2);\n  for(int SiPM=0; SiPM<4; SiPM++)\n  {\n    c3.cd(SiPM+1);\n    gPad->SetLogy();\n    _histPE[SiPM]->Draw();\n  }      \n  c3.SaveAs(\"PEs.C\");\n}\n\n", "meta": {"hexsha": "a81a11dfeeda49b8ba1124f5457b2a57e48eb00a", "size": 29105, "ext": "cc", "lang": "C++", "max_stars_repo_path": "wls/src/WLSEventAction.cc", "max_stars_repo_name": "ehrlich-uva/CRVStandalone", "max_stars_repo_head_hexsha": "5fb97ee82a36b553190b81ada59d2acfeac18d70", "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": "wls/src/WLSEventAction.cc", "max_issues_repo_name": "ehrlich-uva/CRVStandalone", "max_issues_repo_head_hexsha": "5fb97ee82a36b553190b81ada59d2acfeac18d70", "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": "wls/src/WLSEventAction.cc", "max_forks_repo_name": "ehrlich-uva/CRVStandalone", "max_forks_repo_head_hexsha": "5fb97ee82a36b553190b81ada59d2acfeac18d70", "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.5362116992, "max_line_length": 166, "alphanum_fraction": 0.6344614327, "num_tokens": 8837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.17534289327014718}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Ion Gaztanaga 2005-2008. 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// See http://www.boost.org/libs/interprocess for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef BOOST_INTERPROCESS_DETAIL_NODE_POOL_HPP\n#define BOOST_INTERPROCESS_DETAIL_NODE_POOL_HPP\n\n#if (defined _MSC_VER) && (_MSC_VER >= 1200)\n#  pragma once\n#endif\n\n#include <boost/interprocess/detail/config_begin.hpp>\n#include <boost/interprocess/detail/workaround.hpp>\n\n#include <boost/intrusive/slist.hpp>\n#include <boost/math/common_factor_ct.hpp>\n#include <boost/pointer_to_other.hpp>\n\n#include <boost/interprocess/sync/interprocess_mutex.hpp>\n#include <boost/interprocess/detail/utilities.hpp>\n#include <boost/interprocess/exceptions.hpp>\n#include <boost/interprocess/detail/math_functions.hpp>\n#include <boost/interprocess/detail/type_traits.hpp>\n#include <boost/interprocess/allocators/detail/node_tools.hpp>\n#include <boost/interprocess/mem_algo/detail/mem_algo_common.hpp>\n#include <boost/interprocess/allocators/detail/allocator_common.hpp>\n#include <cstddef>\n#include <functional>\n#include <algorithm>\n#include <cassert>\n\n//!\\file\n//!Describes the real adaptive pool shared by many Interprocess adaptive pool allocators\n\nnamespace boost {\nnamespace interprocess {\nnamespace detail {\n\ntemplate<class SegmentManagerBase>\nclass private_node_pool_impl\n{\n   //Non-copyable\n   private_node_pool_impl();\n   private_node_pool_impl(const private_node_pool_impl &);\n   private_node_pool_impl &operator=(const private_node_pool_impl &);\n\n   //A node object will hold node_t when it's not allocated\n   public:\n   typedef typename SegmentManagerBase::void_pointer              void_pointer;\n   typedef typename node_slist<void_pointer>::slist_hook_t        slist_hook_t;\n   typedef typename node_slist<void_pointer>::node_t              node_t;\n   typedef typename node_slist<void_pointer>::node_slist_t        free_nodes_t;\n   typedef typename SegmentManagerBase::multiallocation_chain     multiallocation_chain;\n\n   private:\n   typedef typename bi::make_slist\n      < node_t, bi::base_hook<slist_hook_t>\n      , bi::linear<true>\n      , bi::constant_time_size<false> >::type      blockslist_t;\n   public:\n\n   //!Segment manager typedef\n   typedef SegmentManagerBase segment_manager_base_type;\n\n   //!Constructor from a segment manager. Never throws\n   private_node_pool_impl(segment_manager_base_type *segment_mngr_base, std::size_t node_size, std::size_t nodes_per_block)\n   :  m_nodes_per_block(nodes_per_block)\n   ,  m_real_node_size(detail::lcm(node_size, std::size_t(alignment_of<node_t>::value)))\n      //General purpose allocator\n   ,  mp_segment_mngr_base(segment_mngr_base)\n   ,  m_blocklist()\n   ,  m_freelist()\n      //Debug node count\n   ,  m_allocated(0)\n   {}\n\n   //!Destructor. Deallocates all allocated blocks. Never throws\n   ~private_node_pool_impl()\n   {  this->purge_blocks();  }\n\n   std::size_t get_real_num_node() const\n   {  return m_nodes_per_block; }\n\n   //!Returns the segment manager. Never throws\n   segment_manager_base_type* get_segment_manager_base()const\n   {  return detail::get_pointer(mp_segment_mngr_base);  }\n\n   //!Allocates array of count elements. Can throw boost::interprocess::bad_alloc\n   void *allocate_node()\n   {\n      //If there are no free nodes we allocate a new block\n      if (m_freelist.empty())\n         priv_alloc_block();\n      //We take the first free node\n      node_t *n = &m_freelist.front();\n      m_freelist.pop_front();\n      ++m_allocated;\n      return n;\n   }\n   \n   //!Deallocates an array pointed by ptr. Never throws\n   void deallocate_node(void *ptr)\n   {\n      //We put the node at the beginning of the free node list\n      node_t * to_deallocate = static_cast<node_t*>(ptr);\n      m_freelist.push_front(*to_deallocate);\n      assert(m_allocated>0);\n      --m_allocated;\n   }\n\n   //!Allocates a singly linked list of n nodes ending in null pointer \n   //!can throw boost::interprocess::bad_alloc\n   multiallocation_chain allocate_nodes(const std::size_t n)\n   {\n      multiallocation_chain nodes;\n      std::size_t i = 0;\n      try{\n         for(; i < n; ++i){\n            nodes.push_front(this->allocate_node());\n         }\n      }\n      catch(...){\n         this->deallocate_nodes(nodes, i);\n         throw;\n      }\n      return boost::interprocess::move(nodes);\n   }\n\n   //!Deallocates the first n nodes of a linked list of nodes. Never throws\n   void deallocate_nodes(multiallocation_chain &nodes, std::size_t n)\n   {\n      for(std::size_t i = 0; i < n; ++i){\n         void *p = detail::get_pointer(nodes.front());\n         assert(p);\n         nodes.pop_front();\n         this->deallocate_node(p);\n      }\n   }\n\n   //!Deallocates the nodes pointed by the multiallocation iterator. Never throws\n   void deallocate_nodes(multiallocation_chain chain)\n   {\n      while(!chain.empty()){\n         void *addr = detail::get_pointer(chain.front());\n         chain.pop_front();\n         deallocate_node(addr);\n      }\n   }\n\n   //!Deallocates all the free blocks of memory. Never throws\n   void deallocate_free_blocks()\n   {\n      typedef typename free_nodes_t::iterator nodelist_iterator;\n      typename blockslist_t::iterator bit(m_blocklist.before_begin()),\n                                      it(m_blocklist.begin()),\n                                      itend(m_blocklist.end());\n      free_nodes_t backup_list;\n      nodelist_iterator backup_list_last = backup_list.before_begin();\n\n      //Execute the algorithm and get an iterator to the last value\n      std::size_t blocksize = detail::get_rounded_size\n         (m_real_node_size*m_nodes_per_block, alignment_of<node_t>::value);\n\n      while(it != itend){\n         //Collect all the nodes from the block pointed by it\n         //and push them in the list\n         free_nodes_t free_nodes;\n         nodelist_iterator last_it = free_nodes.before_begin();\n         const void *addr = get_block_from_hook(&*it, blocksize);\n\n         m_freelist.remove_and_dispose_if\n            (is_between(addr, blocksize), push_in_list(free_nodes, last_it));\n\n         //If the number of nodes is equal to m_nodes_per_block\n         //this means that the block can be deallocated\n         if(free_nodes.size() == m_nodes_per_block){\n            //Unlink the nodes\n            free_nodes.clear();\n            it = m_blocklist.erase_after(bit);\n            mp_segment_mngr_base->deallocate((void*)addr);\n         }\n         //Otherwise, insert them in the backup list, since the\n         //next \"remove_if\" does not need to check them again.\n         else{\n            //Assign the iterator to the last value if necessary\n            if(backup_list.empty() && !m_freelist.empty()){\n               backup_list_last = last_it;\n            }\n            //Transfer nodes. This is constant time.\n            backup_list.splice_after\n               ( backup_list.before_begin()\n               , free_nodes\n               , free_nodes.before_begin()\n               , last_it\n               , free_nodes.size());\n            bit = it;\n            ++it;\n         }\n      }\n      //We should have removed all the nodes from the free list\n      assert(m_freelist.empty());\n\n      //Now pass all the node to the free list again\n      m_freelist.splice_after\n         ( m_freelist.before_begin()\n         , backup_list\n         , backup_list.before_begin()\n         , backup_list_last\n         , backup_list.size());\n   }\n\n   std::size_t num_free_nodes()\n   {  return m_freelist.size();  }\n\n   //!Deallocates all used memory. Precondition: all nodes allocated from this pool should\n   //!already be deallocated. Otherwise, undefined behaviour. Never throws\n   void purge_blocks()\n   {\n      //check for memory leaks\n      assert(m_allocated==0);\n      std::size_t blocksize = detail::get_rounded_size\n         (m_real_node_size*m_nodes_per_block, alignment_of<node_t>::value);\n      typename blockslist_t::iterator\n         it(m_blocklist.begin()), itend(m_blocklist.end()), aux;\n\n      //We iterate though the NodeBlock list to free the memory\n      while(!m_blocklist.empty()){\n         void *addr = get_block_from_hook(&m_blocklist.front(), blocksize);\n         m_blocklist.pop_front();\n         mp_segment_mngr_base->deallocate((void*)addr);\n      }\n      //Just clear free node list\n      m_freelist.clear();\n   }\n\n   void swap(private_node_pool_impl &other)\n   {\n      std::swap(mp_segment_mngr_base, other.mp_segment_mngr_base);\n      m_blocklist.swap(other.m_blocklist);\n      m_freelist.swap(other.m_freelist);\n      std::swap(m_allocated, other.m_allocated);\n   }\n\n   private:\n\n   struct push_in_list\n   {\n      push_in_list(free_nodes_t &l, typename free_nodes_t::iterator &it)\n         :  slist_(l), last_it_(it)\n      {}\n      \n      void operator()(typename free_nodes_t::pointer p) const\n      {\n         slist_.push_front(*p);\n         if(slist_.size() == 1){ //Cache last element\n            ++last_it_ = slist_.begin();\n         }\n      }\n\n      private:\n      free_nodes_t &slist_;\n      typename free_nodes_t::iterator &last_it_;\n   };\n\n   struct is_between\n      :  std::unary_function<typename free_nodes_t::value_type, bool>\n   {\n      is_between(const void *addr, std::size_t size)\n         :  beg_(static_cast<const char *>(addr)), end_(beg_+size)\n      {}\n      \n      bool operator()(typename free_nodes_t::const_reference v) const\n      {\n         return (beg_ <= reinterpret_cast<const char *>(&v) && \n                 end_ >  reinterpret_cast<const char *>(&v));\n      }\n      private:\n      const char *      beg_;\n      const char *      end_;\n   };\n\n   //!Allocates a block of nodes. Can throw boost::interprocess::bad_alloc\n   void priv_alloc_block()\n   {\n      //We allocate a new NodeBlock and put it as first\n      //element in the free Node list\n      std::size_t blocksize = \n         detail::get_rounded_size(m_real_node_size*m_nodes_per_block, alignment_of<node_t>::value);\n      char *pNode = reinterpret_cast<char*>\n         (mp_segment_mngr_base->allocate(blocksize + sizeof(node_t)));\n      if(!pNode)  throw bad_alloc();\n      char *pBlock = pNode;\n      m_blocklist.push_front(get_block_hook(pBlock, blocksize));\n\n      //We initialize all Nodes in Node Block to insert \n      //them in the free Node list\n      for(std::size_t i = 0; i < m_nodes_per_block; ++i, pNode += m_real_node_size){\n         m_freelist.push_front(*new (pNode) node_t);\n      }\n   }\n\n   //!Deprecated, use deallocate_free_blocks\n   void deallocate_free_chunks()\n   {  this->deallocate_free_blocks(); }\n\n   //!Deprecated, use purge_blocks\n   void purge_chunks()\n   {  this->purge_blocks(); }\n\n   private:\n   //!Returns a reference to the block hook placed in the end of the block\n   static node_t & get_block_hook (void *block, std::size_t blocksize)\n   {  \n      return *reinterpret_cast<node_t*>(reinterpret_cast<char*>(block) + blocksize);  \n   }\n\n   //!Returns the starting address of the block reference to the block hook placed in the end of the block\n   void *get_block_from_hook (node_t *hook, std::size_t blocksize)\n   {  \n      return (reinterpret_cast<char*>(hook) - blocksize);\n   }\n\n   private:\n   typedef typename boost::pointer_to_other\n      <void_pointer, segment_manager_base_type>::type   segment_mngr_base_ptr_t;\n\n   const std::size_t m_nodes_per_block;\n   const std::size_t m_real_node_size;\n   segment_mngr_base_ptr_t mp_segment_mngr_base;   //Segment manager\n   blockslist_t      m_blocklist;      //Intrusive container of blocks\n   free_nodes_t      m_freelist;       //Intrusive container of free nods\n   std::size_t       m_allocated;      //Used nodes for debugging\n};\n\n\n//!Pooled shared memory allocator using single segregated storage. Includes\n//!a reference count but the class does not delete itself, this is  \n//!responsibility of user classes. Node size (NodeSize) and the number of\n//!nodes allocated per block (NodesPerBlock) are known at compile time\ntemplate< class SegmentManager, std::size_t NodeSize, std::size_t NodesPerBlock >\nclass private_node_pool\n   //Inherit from the implementation to avoid template bloat\n   :  public private_node_pool_impl<typename SegmentManager::segment_manager_base_type>\n{\n   typedef private_node_pool_impl<typename SegmentManager::segment_manager_base_type> base_t;\n   //Non-copyable\n   private_node_pool();\n   private_node_pool(const private_node_pool &);\n   private_node_pool &operator=(const private_node_pool &);\n\n   public:\n   typedef SegmentManager segment_manager;\n\n   static const std::size_t nodes_per_block = NodesPerBlock;\n   //Deprecated, use nodes_per_block\n   static const std::size_t nodes_per_chunk = NodesPerBlock;\n\n   //!Constructor from a segment manager. Never throws\n   private_node_pool(segment_manager *segment_mngr)\n      :  base_t(segment_mngr, NodeSize, NodesPerBlock)\n   {}\n\n   //!Returns the segment manager. Never throws\n   segment_manager* get_segment_manager() const\n   {  return static_cast<segment_manager*>(base_t::get_segment_manager_base()); }\n};\n\n\n//!Pooled shared memory allocator using single segregated storage. Includes\n//!a reference count but the class does not delete itself, this is  \n//!responsibility of user classes. Node size (NodeSize) and the number of\n//!nodes allocated per block (NodesPerBlock) are known at compile time\n//!Pooled shared memory allocator using adaptive pool. Includes\n//!a reference count but the class does not delete itself, this is  \n//!responsibility of user classes. Node size (NodeSize) and the number of\n//!nodes allocated per block (NodesPerBlock) are known at compile time\ntemplate< class SegmentManager\n        , std::size_t NodeSize\n        , std::size_t NodesPerBlock\n        >\nclass shared_node_pool \n   :  public detail::shared_pool_impl\n      < private_node_pool\n         <SegmentManager, NodeSize, NodesPerBlock>\n      >\n{\n   typedef detail::shared_pool_impl\n      < private_node_pool\n         <SegmentManager, NodeSize, NodesPerBlock>\n      > base_t;\n   public:\n   shared_node_pool(SegmentManager *segment_mgnr)\n      : base_t(segment_mgnr)\n   {}\n};\n\n}  //namespace detail {\n}  //namespace interprocess {\n}  //namespace boost {\n\n#include <boost/interprocess/detail/config_end.hpp>\n\n#endif   //#ifndef BOOST_INTERPROCESS_DETAIL_NODE_POOL_HPP\n", "meta": {"hexsha": "1dd923c9b89bc3f7bbbf32fefb198d948ad5c4c1", "size": 14442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/interprocess/allocators/detail/node_pool.hpp", "max_stars_repo_name": "TE-tatuonagamatu/boost", "max_stars_repo_head_hexsha": "ac861f8c0f33538060790a8e50701464ca9982d3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T00:14:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T00:59:22.000Z", "max_issues_repo_path": "boost/interprocess/allocators/detail/node_pool.hpp", "max_issues_repo_name": "xin3liang/platform_external_boost", "max_issues_repo_head_hexsha": "ac861f8c0f33538060790a8e50701464ca9982d3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-11-22T13:14:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T00:56:51.000Z", "max_forks_repo_path": "boost/interprocess/allocators/detail/node_pool.hpp", "max_forks_repo_name": "xin3liang/platform_external_boost", "max_forks_repo_head_hexsha": "ac861f8c0f33538060790a8e50701464ca9982d3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-11-07T13:38:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T12:13:31.000Z", "avg_line_length": 35.2243902439, "max_line_length": 123, "alphanum_fraction": 0.6747680377, "num_tokens": 3347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.31405053215160805, "lm_q1q2_score": 0.17534288968563222}}
{"text": "#include \"generate_data/full_scene/generate_data.h\"\n#include \"generate_data/baryocentric_to_ray.h\"\n#include \"generate_data/full_scene/amend_config.h\"\n#include \"generate_data/full_scene/constants.h\"\n#include \"generate_data/full_scene/intersect_for_baryocentric_coords.h\"\n#include \"generate_data/full_scene/scene_generator.h\"\n#include \"generate_data/possibly_shadowed.h\"\n#include \"generate_data/shadowed.h\"\n#include \"generate_data/sort_triangle_points.h\"\n#include \"generate_data/subset_to_multi.h\"\n#include \"generate_data/to_tensor.h\"\n#include \"generate_data/triangle.h\"\n#include \"generate_data/triangle_subset_intersection.h\"\n#include \"generate_data/triangle_subset_union.h\"\n#include \"generate_data/value_adder.h\"\n#include \"integrate/dir_sampler/uniform_direction_sample.h\"\n#include \"lib/vector_type.h\"\n#include \"meta/array_cat.h\"\n#include \"render/renderer.h\"\n#include \"rng/uniform/uniform.h\"\n\n#include <boost/multi_array.hpp>\n\n#include \"dbg.h\"\n\nnamespace generate_data {\nnamespace full_scene {\nstatic VectorT<render::Renderer> renderers;\n\ntemplate <bool is_image>\nusing Out = std::conditional_t<is_image, ImageData<NetworkInputs>,\n                               StandardData<NetworkInputs>>;\n\ntemplate <bool is_image>\nOut<is_image> generate_data_impl(int max_tris,\n                                 std::optional<int> forced_n_scenes,\n                                 int n_samples_per_tri_or_dim, int n_samples,\n                                 int n_steps, unsigned seed) {\n  VectorT<IntersectedBaryocentricCoords> intersected_coords;\n  unsigned max_n_samples_per_scene = 0;\n  VectorT<scene::Scene> scenes;\n  VectorT<unsigned> mesh_threshs; // not used ATM\n  SceneGenerator generator;\n  int tri_count = 0;\n  unsigned max_tri_count = 0;\n  rng::uniform::Uniform<ExecutionModel::CPU>::Ref::State rng_state(seed);\n  std::vector<unsigned> n_total_samples_per;\n  while (forced_n_scenes.has_value()\n             ? scenes.size() < unsigned(*forced_n_scenes)\n             : tri_count < max_tris) {\n    auto vals = generator.generate(rng_state.state());\n    auto scene = std::get<0>(vals);\n    unsigned n_tris = scene.triangles().size();\n    int new_tri_count = tri_count + n_tris;\n\n    // TODO: restrict tris somehow?\n\n    tri_count = new_tri_count;\n    max_tri_count = std::max(max_tri_count, n_tris);\n\n    unsigned n_total_samples;\n    if constexpr (is_image) {\n      unsigned dim = n_samples_per_tri_or_dim;\n      auto values = intersect_for_baryocentric_coords(scene, dim);\n      n_total_samples = unsigned(values.image_indexes.size());\n      intersected_coords.push_back(values);\n    } else {\n      unsigned n_samples_per_tri = n_samples_per_tri_or_dim;\n      n_total_samples = n_samples_per_tri * n_tris;\n    }\n    max_n_samples_per_scene =\n        std::max(max_n_samples_per_scene, n_total_samples);\n    n_total_samples_per.push_back(n_total_samples);\n\n    scenes.push_back(scene);\n    mesh_threshs.push_back(std::get<1>(vals));\n  }\n\n  render::Settings settings;\n  amend_config(settings);\n\n  std::array<unsigned, 2> base_dims{unsigned(scenes.size()), max_tri_count};\n\n  boost::multi_array<float, 3> triangle_features{\n      array_append(base_dims, unsigned(constants.n_tri_values))};\n  boost::multi_array<float, 3> bsdf_features{\n      array_append(base_dims, unsigned(constants.n_bsdf_values))};\n  boost::multi_array<float, 3> emissive_values{\n      array_append(base_dims, unsigned(constants.n_rgb_dims))};\n  boost::multi_array<bool, 2> mask{base_dims};\n\n  std::array<unsigned, 2> base_sample_dims{unsigned(scenes.size()),\n                                           max_n_samples_per_scene};\n\n  boost::multi_array<float, 3> baryocentric_coords{array_append(\n      base_sample_dims, unsigned(constants.n_coords_feature_values))};\n  boost::multi_array<TorchIdxT, 2> triangle_idxs_for_coords{base_sample_dims};\n  boost::multi_array<TorchIdxT, 3> image_indexes;\n  if constexpr (is_image) {\n    image_indexes.resize(array_append(base_sample_dims, 2u));\n  }\n  boost::multi_array<float, 4> values{\n      std::array{unsigned(scenes.size()), unsigned(n_steps),\n                 max_n_samples_per_scene, unsigned(constants.n_rgb_dims)}};\n  for (unsigned scene_idx = 0; scene_idx < scenes.size(); ++scene_idx) {\n    const auto &scene = scenes[scene_idx];\n    VectorT<Triangle> tris(scene.triangles().size());\n\n    Eigen::Vector3d avg = Eigen::Vector3d::Zero();\n    Eigen::Vector3d min_pos = max_eigen_vec<double>();\n    Eigen::Vector3d max_pos = min_eigen_vec<double>();\n\n    for (unsigned i = 0; i < tris.size(); ++i) {\n      tris[i] = scene.triangles()[i].template cast<double>();\n      for (const auto &vert : tris[i].vertices) {\n        avg += vert;\n        min_pos = min_pos.cwiseMin(vert);\n        max_pos = max_pos.cwiseMax(vert);\n      }\n    }\n\n    avg /= tris.size() * 3;\n\n    double scale =\n        1. / std::max((avg - min_pos).maxCoeff(), (max_pos - avg).maxCoeff());\n    auto scaling = Eigen::Scaling(scale);\n    auto translate = Eigen::Translation3d(-avg);\n    const Eigen::Affine3d transform = scaling * translate;\n\n    for (unsigned i = 0; i < tris.size(); ++i) {\n      auto &tri = tris[i];\n      for (auto &vert : tri.vertices) {\n        vert = transform * vert;\n      }\n\n      sort_triangle_points(tri);\n\n      if (tri.normal_raw().z() < 0.f) {\n        std::swap(tri.vertices[1], tri.vertices[2]);\n      }\n\n      auto tri_adder = make_value_adder([&](float v, int value_idx) {\n        triangle_features[scene_idx][i][value_idx] = v;\n      });\n\n      for (const auto &point : tri.vertices) {\n        tri_adder.add_remap_all_values(point);\n      }\n      const auto normal_scaled = tri.normal_scaled_by_area();\n      tri_adder.add_remap_all_values(normal_scaled);\n      const auto normal = normal_scaled.normalized().eval();\n      tri_adder.add_values(normal);\n      tri_adder.add_remap_all_value(tri.area());\n\n      debug_assert(tri_adder.idx == constants.n_tri_values);\n\n      const auto &material =\n          scene.materials()[scene.triangle_data()[i].material_idx()];\n\n      make_value_adder([&](float v, int value_idx) {\n        emissive_values[scene_idx][i][value_idx] = v;\n      }).add_values(material.emission);\n\n      FloatRGB diffuse_value = FloatRGB::Zero();\n      FloatRGB glossy_value = FloatRGB::Zero();\n      FloatRGB mirror_value = FloatRGB::Zero();\n      FloatRGB dielectric_value = FloatRGB::Zero();\n      float shininess = 40.;\n      float ior = 1.6;\n\n      material.bsdf.bsdf.visit_tagged([&](auto tag, const auto &value) {\n        if constexpr (tag == bsdf::BSDFType::Diffuse) {\n          diffuse_value = value.diffuse;\n        } else if constexpr (tag == bsdf::BSDFType::Glossy) {\n          glossy_value = value.specular();\n          shininess = value.shininess();\n        } else if constexpr (tag == bsdf::BSDFType::DiffuseGlossy) {\n          float diffuse_weight = value.weight_continuous_inclusive()[0];\n          float glossy_weight = 1 - diffuse_weight;\n          diffuse_value =\n              diffuse_weight * value.items()[boost::hana::int_c<0>].diffuse;\n          glossy_value =\n              glossy_weight * value.items()[boost::hana::int_c<1>].specular();\n          shininess = value.items()[boost::hana::int_c<1>].shininess();\n        } else if constexpr (tag == bsdf::BSDFType::DiffuseMirror) {\n          unreachable_unchecked();\n        } else if constexpr (tag == bsdf::BSDFType::Mirror) {\n          mirror_value = value.specular;\n        } else {\n          static_assert(tag == bsdf::BSDFType::DielectricRefractive);\n          dielectric_value = value.specular();\n          ior = value.ior();\n        }\n      });\n\n      auto bsdf_adder = make_value_adder([&](float v, int value_idx) {\n        bsdf_features[scene_idx][i][value_idx] = v;\n      });\n\n      bsdf_adder.add_values(diffuse_value);\n      bsdf_adder.add_values(glossy_value);\n      bsdf_adder.add_values(mirror_value);\n      bsdf_adder.add_values(dielectric_value);\n      bsdf_adder.add_value(shininess);\n      bsdf_adder.add_value(ior);\n\n      debug_assert(bsdf_adder.idx == constants.n_bsdf_values);\n    }\n\n    for (unsigned i = 0; i < max_tri_count; ++i) {\n      mask[scene_idx][i] = i >= tris.size();\n    }\n\n    unsigned n_samples_this_scene = [&] {\n      if constexpr (is_image) {\n        return intersected_coords[scene_idx].coords.size();\n      } else {\n        unsigned n_samples_per_tri = n_samples_per_tri_or_dim;\n        return tris.size() * n_samples_per_tri;\n      }\n    }();\n\n    VectorT<render::InitialIdxAndDirSpec> idxs_and_dirs(n_samples_this_scene);\n\n    auto add_value = [&](unsigned i, float s, float t, unsigned tri_idx,\n                         const UnitVector &dir) {\n      const auto &tri = tris[tri_idx];\n      idxs_and_dirs[i] = {\n          .idx = tri_idx,\n          .ray = baryocentric_to_ray(s, t, tri.template cast<float>(), dir),\n      };\n      triangle_idxs_for_coords[scene_idx][i] = tri_idx;\n\n      auto baryo_addr = make_value_adder([&](float v, int value_idx) {\n        baryocentric_coords[scene_idx][i][value_idx] = v;\n      });\n\n      baryo_addr.add_value(s);\n      baryo_addr.add_value(t);\n      const Eigen::Vector3d vec0 = tri.vertices[1] - tri.vertices[0];\n      const Eigen::Vector3d vec1 = tri.vertices[2] - tri.vertices[0];\n\n      const Eigen::Vector3d double_dir = dir->template cast<double>();\n      Eigen::Vector3d dir_tri_space{tri.normal()->dot(double_dir),\n                                    vec0.dot(double_dir) / vec0.norm(),\n                                    vec1.dot(double_dir) / vec1.norm()};\n      dir_tri_space.normalize();\n      baryo_addr.add_values(dir_tri_space);\n    };\n    if constexpr (is_image) {\n      const auto &item = intersected_coords[scene_idx];\n      for (unsigned i = 0; i < item.coords.size(); ++i) {\n        auto [s, t] = item.coords[i];\n        add_value(i, s, t, item.tri_idxs[i], item.directions[i]);\n      }\n      for (unsigned i = 0; i < item.image_indexes.size(); ++i) {\n        auto [x, y] = item.image_indexes[i];\n        image_indexes[scene_idx][i][0] = TorchIdxT(x);\n        image_indexes[scene_idx][i][1] = TorchIdxT(y);\n      }\n    } else {\n      unsigned n_samples_per_tri = n_samples_per_tri_or_dim;\n      unsigned i = 0;\n      for (unsigned tri_idx = 0; tri_idx < tris.size(); ++tri_idx) {\n        for (unsigned sample_idx = 0; sample_idx < n_samples_per_tri;\n             ++sample_idx, ++i) {\n          auto [s, t] = integrate::uniform_baryocentric(rng_state);\n          auto direction = integrate::dir_sampler::uniform_direction_sample(\n              rng_state, UnitVector::new_unchecked(Eigen::Vector3f::UnitX()),\n              true);\n          add_value(i, s, t, tri_idx, direction);\n        }\n      }\n    }\n\n    VectorT<VectorT<FloatRGB>> step_outputs(\n        n_steps, VectorT<FloatRGB>{n_samples_this_scene});\n    VectorT<Span<FloatRGB>> outputs(step_outputs.begin(), step_outputs.end());\n\n    if (n_samples_this_scene > 0) {\n      renderers.resize(1);\n      renderers[0].render(\n          ExecutionModel::GPU,\n          {tag_v<render::SampleSpecType::InitialIdxAndDir>, idxs_and_dirs},\n          {tag_v<render::OutputType::OutputPerStep>, outputs}, scene, n_samples,\n          settings, false);\n      for (unsigned j = 0; j < unsigned(n_steps); ++j) {\n        for (unsigned k = 0; k < n_samples_this_scene; ++k) {\n          for (unsigned l = 0; l < 3; ++l) {\n            values[scene_idx][j][k][l] = outputs[j][k][l];\n          }\n        }\n      }\n    }\n  }\n\n  StandardData<NetworkInputs> out{\n      .inputs =\n          {\n              .triangle_features = to_tensor(triangle_features),\n              .mask = to_tensor(mask),\n              .bsdf_features = to_tensor(bsdf_features),\n              .emissive_values = to_tensor(emissive_values),\n              .baryocentric_coords = to_tensor(baryocentric_coords),\n              .triangle_idxs_for_coords = to_tensor(triangle_idxs_for_coords),\n              .total_tri_count = unsigned(tri_count),\n              .n_samples_per = n_total_samples_per,\n          },\n\n      .values = to_tensor(values),\n  };\n\n  if constexpr (is_image) {\n    return {.standard = out, .image_indexes = to_tensor(image_indexes)};\n  } else {\n    return out;\n  }\n}\n\nStandardData<NetworkInputs> generate_data(int max_tris,\n                                          std::optional<int> forced_n_scenes,\n                                          int n_samples_per_scene,\n                                          int n_samples, int n_steps,\n                                          unsigned base_seed) {\n  return generate_data_impl<false>(max_tris, forced_n_scenes,\n                                   n_samples_per_scene, n_samples, n_steps,\n                                   base_seed);\n}\n\nImageData<NetworkInputs>\ngenerate_data_for_image(int max_tris, std::optional<int> forced_n_scenes,\n                        int dim, int n_samples, int n_steps,\n                        unsigned base_seed) {\n  return generate_data_impl<true>(max_tris, forced_n_scenes, dim, n_samples,\n                                  n_steps, base_seed);\n}\n\nvoid deinit_renderers() { renderers.clear(); }\n} // namespace full_scene\n} // namespace generate_data\n", "meta": {"hexsha": "749a1c54267dfa32034cca14f9449ae2cdceec75", "size": 13060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/generate_data/full_scene/generate_data.cpp", "max_stars_repo_name": "rgreenblatt/path", "max_stars_repo_head_hexsha": "2057618ee3a6067c230c1c1c40856d2c9f5006b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-15T19:26:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T19:26:37.000Z", "max_issues_repo_path": "src/generate_data/full_scene/generate_data.cpp", "max_issues_repo_name": "rgreenblatt/path", "max_issues_repo_head_hexsha": "2057618ee3a6067c230c1c1c40856d2c9f5006b0", "max_issues_repo_licenses": ["MIT"], "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_data/full_scene/generate_data.cpp", "max_forks_repo_name": "rgreenblatt/path", "max_forks_repo_head_hexsha": "2057618ee3a6067c230c1c1c40856d2c9f5006b0", "max_forks_repo_licenses": ["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.2991202346, "max_line_length": 80, "alphanum_fraction": 0.6387442573, "num_tokens": 3200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17533479287991585}}
{"text": "/*\nCopyright (c) 2019 Naomasa Matsubayashi (aka. Fadis)\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 <array>\n#include <vector>\n#include <utility>\n#include <boost/math/common_factor_rt.hpp>\n#include <glm/vec4.hpp>\n#include <liblnn/layer_def.h>\n#include <liblnn/descriptor_set.h>\n#include <liblnn/pipeline_layout.h>\n#include <liblnn/exceptions.h>\n#include <liblnn/pipeline.h>\nnamespace liblnn {\n  layer create_init_pipeline(\n    const std::shared_ptr< vk::Device > &device,\n    const modules &mods,\n    const std::shared_ptr< vk::DescriptorPool > &descriptor_pool,\n    const std::shared_ptr< vk::PipelineCache > &pipeline_cache,\n    const device_props &props,\n    const buffer_view< glm::vec4 > &weight,\n    uint32_t input_size\n  ) {\n    const std::vector< vk::DescriptorSetLayoutBinding > descriptor_set_layout_bindings{\n      vk::DescriptorSetLayoutBinding()\n        .setDescriptorType( vk::DescriptorType::eStorageBuffer )\n        .setDescriptorCount( 1 )\n        .setBinding( 2 )\n        .setStageFlags( vk::ShaderStageFlagBits::eCompute )\n        .setPImmutableSamplers( nullptr )\n    };\n    const uint32_t size = weight.size();\n    uint32_t width = ( size > props.props.limits.maxComputeWorkGroupCount[ 0 ] ) ? boost::math::gcd( size, props.props.limits.maxComputeWorkGroupCount[ 0 ] ) : size;\n    uint32_t local_group_size = boost::math::gcd( width, props.subgroup_props.subgroupSize );\n    uint32_t height = size / width;\n    if( height > props.props.limits.maxComputeWorkGroupCount[ 1 ] ) throw too_large_data();\n    auto [descriptor_set,descriptor_set_layout] = get_descriptor_set( device, descriptor_pool, descriptor_set_layout_bindings );\n    std::vector< vk::PushConstantRange > push_constant_range{\n      vk::PushConstantRange()\n       .setStageFlags( vk::ShaderStageFlagBits::eCompute )\n       .setOffset( 0 )\n       .setSize( 8 )\n    };\n    auto pipeline_layout = get_pipeline_layout( device, descriptor_set_layout, push_constant_range );\n    std::array< uint32_t, 3 > spec_data{ local_group_size, 1, input_size };\n    std::array< vk::SpecializationMapEntry, 3 > spec_ent {\n      vk::SpecializationMapEntry()\n        .setConstantID( 1 )\n        .setOffset( 0 )\n        .setSize( 4 ),\n      vk::SpecializationMapEntry()\n        .setConstantID( 2 )\n        .setOffset( 4 )\n        .setSize( 4 ),\n      vk::SpecializationMapEntry()\n        .setConstantID( 3 )\n        .setOffset( 8 )\n        .setSize( 4 )\n    };\n    auto spec = vk::SpecializationInfo()\n      .setMapEntryCount( spec_ent.size() )\n      .setPMapEntries( spec_ent.data() )\n      .setDataSize( spec_data.size() )\n      .setPData( spec_data.data() );\n    auto pipelines = device->createComputePipelines(\n      *pipeline_cache,\n      std::vector< vk::ComputePipelineCreateInfo >{\n        vk::ComputePipelineCreateInfo()\n    .setStage(\n      vk::PipelineShaderStageCreateInfo()\n        .setStage( vk::ShaderStageFlagBits::eCompute )\n        .setModule( *mods.init )\n        .setPName( \"main\" )\n    .setPSpecializationInfo( &spec )\n    )\n    .setLayout( *pipeline_layout )\n      }\n    );\n    std::shared_ptr< vk::Pipeline > pipeline(\n      new vk::Pipeline( std::move( pipelines[ 0 ] ) ),\n      [device,pipeline_cache,module=mods.init,pipeline_layout]( vk::Pipeline *p ) {\n        if( p ) device->destroyPipeline( *p );\n        delete p;\n      }\n    );\n\n    auto weight_dbi = vk::DescriptorBufferInfo()\n      .setBuffer( weight.get() )\n      .setOffset( weight.offset() * sizeof( glm::vec4 ) )\n      .setRange( weight.size() * sizeof( glm::vec4 ) );\n    device->updateDescriptorSets(\n      std::vector< vk::WriteDescriptorSet >{\n         vk::WriteDescriptorSet()\n           .setDstSet( *descriptor_set )\n           .setDstBinding( 2 )\n           .setDescriptorType( vk::DescriptorType::eStorageBuffer )\n           .setDescriptorCount( 1 )\n           .setPBufferInfo( &weight_dbi )\n      },\n      nullptr\n    );\n    return layer( layer_def()\n      .set_weight( weight )\n      .set_descriptor_set( descriptor_set )\n      .set_pipeline( pipeline )\n      .set_descriptor_set_layout( descriptor_set_layout )\n      .set_pipeline_layout( pipeline_layout )\n      .set_dispatch_size( width / local_group_size, height, 1 ) );\n  }\n}\n\n", "meta": {"hexsha": "8342c8ddee96c9af8b9f67e9375d5cae4ecca3a6", "size": 5186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/create_init_pipeline.cpp", "max_stars_repo_name": "Fadis/kernelvm_20190720_samples", "max_stars_repo_head_hexsha": "8f51e7e24313122d25edf51aa4acc3f0581e3238", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-07-20T06:37:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T18:40:31.000Z", "max_issues_repo_path": "src/create_init_pipeline.cpp", "max_issues_repo_name": "Fadis/kernelvm_20190720_samples", "max_issues_repo_head_hexsha": "8f51e7e24313122d25edf51aa4acc3f0581e3238", "max_issues_repo_licenses": ["MIT"], "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_init_pipeline.cpp", "max_forks_repo_name": "Fadis/kernelvm_20190720_samples", "max_forks_repo_head_hexsha": "8f51e7e24313122d25edf51aa4acc3f0581e3238", "max_forks_repo_licenses": ["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.5877862595, "max_line_length": 165, "alphanum_fraction": 0.6878133436, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.17533478936672453}}
{"text": "/*\n * Copyright (c) 2020, Robobrain.\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/* Author: Konstantinos Konstantinidis */\n\n#pragma once\n\n#include \"kalman-cpp/kalman.hpp\"\n#include <Eigen/Dense>\n#include <ros/console.h>\n\nusing namespace Eigen;\n\ntypedef std::pair<double, double> Point;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\nconst double pi = 3.141592653589793238463; \n\nclass LshapeTracker {\npublic:\n\n  LshapeTracker(const double& x_corner, const double& y_corner, const double& L1, const double& L2, const double& theta, const double& dt);\n  LshapeTracker();\n  void update(const double& thetaL1, const double& x_corner, const double& y_corner, const double& L1, const double& L2, const double& dt, const int cluster_size);\n  void BoxModel(double& x, double& y,double& vx, double& vy,double& theta, double& psi, double& omega, double& L1, double& L2, double& length, double& width);\n\nprivate:\n  int current_size;\n  double test1, test2, test3;\n  double x_old, y_old, L1_old, L2_old, old_thetaL1;\n\n  KalmanFilter shape_kf;\n  KalmanFilter dynamic_kf;\n\n  void ClockwisePointSwitch();\n  void CounterClockwisePointSwitch();\n  double findTurn(const double& new_angle, const double& old_angle);\n  void detectCornerPointSwitch(const double& from, const double& to, const double dt);\n  void detectCornerPointSwitchMahalanobis(const double& from, const double& to, const double dt);\n  void detectCornerPointSwitchMahalanobis(const double& from, const double& to, const double L1, const double L2, const double x_corner, const double y_corner);\n  /*! \\brief Finds orientations of tracked object\n   *\n   * Given the orientation of L1 the other three angles of the rectangle are calculated.\n   * Then they are compared with the speed of the object, to estimate it's direction.\n   *\n   * \\angle angle of one edge of the box\n   * \\vx velocity in the x axis\n   * \\vy velocity in the y axis\n   * \\orientation orientation of tracked object, based on it's speed\n   */\n  void findOrientation(double& psi, double& length, double& width);\n};\n", "meta": {"hexsha": "465c466e0b89b17592772443ac6976d546ecfd22", "size": 3548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/l_shape_tracker.hpp", "max_stars_repo_name": "kostaskonkk/datmo", "max_stars_repo_head_hexsha": "a8b614751c41f94ed677e7f42faca6400fbf272e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2019-10-22T03:15:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:42:51.000Z", "max_issues_repo_path": "src/l_shape_tracker.hpp", "max_issues_repo_name": "NamDinhRobotics/datmo", "max_issues_repo_head_hexsha": "a8b614751c41f94ed677e7f42faca6400fbf272e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-21T11:45:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T17:44:54.000Z", "max_forks_repo_path": "src/l_shape_tracker.hpp", "max_forks_repo_name": "NamDinhRobotics/datmo", "max_forks_repo_head_hexsha": "a8b614751c41f94ed677e7f42faca6400fbf272e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-05-17T09:48:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T05:00:30.000Z", "avg_line_length": 44.9113924051, "max_line_length": 163, "alphanum_fraction": 0.7488726043, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.17524855785848373}}
{"text": "#include <fc/crypto/openssl.hpp>\n\n#include <fc/filesystem.hpp>\n\n#include <boost/filesystem/path.hpp>\n\n#include <cstdlib>\n#include <string>\n#include <stdlib.h>\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\nvoid ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps) {\n   if (pr != NULL)\n      *pr = sig->r;\n   if (ps != NULL)\n      *ps = sig->s;\n }\n\n int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s) {\n   if (r == NULL || s == NULL)\n      return 0;\n   BN_clear_free(sig->r);\n   BN_clear_free(sig->s);\n   sig->r = r;\n   sig->s = s;\n   return 1;\n}\n#endif\n\nnamespace  fc \n{\n    struct openssl_scope\n    {\n       static path& config_path() {\n          static path cfg;\n          return cfg;\n       }\n       openssl_scope()\n       {\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n          ERR_load_crypto_strings(); \n          OpenSSL_add_all_algorithms();\n#endif\n          const boost::filesystem::path& boostPath = config_path();\n          if(boostPath.empty() == false)\n          {\n            std::string varSetting(\"OPENSSL_CONF=\");\n            varSetting += config_path().to_native_ansi_path();\n#if defined(WIN32)\n            _putenv((char*)varSetting.c_str());\n#else\n            putenv((char*)varSetting.c_str());\n#endif\n          }\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n \t       OPENSSL_config(nullptr);\n#else\n\t       OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);\n#endif\n       }\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n       ~openssl_scope()\n       {\n          EVP_cleanup();\n          ERR_free_strings();\n       }\n#endif           \n    };\n\n\n    void store_configuration_path(const path& filePath)\n    {\n      openssl_scope::config_path() = filePath;\n    }\n   \n    int init_openssl()\n    {\n      static openssl_scope ossl;\n      return 0;\n    }\n}\n", "meta": {"hexsha": "40d624671710c2e22dd2bb8d2a7d1cfaa803857b", "size": 1782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crypto/openssl.cpp", "max_stars_repo_name": "noir-protocol/fc", "max_stars_repo_head_hexsha": "ef8d71bfe84b57491ed12046dcbe1369807bf1d0", "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/crypto/openssl.cpp", "max_issues_repo_name": "noir-protocol/fc", "max_issues_repo_head_hexsha": "ef8d71bfe84b57491ed12046dcbe1369807bf1d0", "max_issues_repo_licenses": ["MIT"], "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/crypto/openssl.cpp", "max_forks_repo_name": "noir-protocol/fc", "max_forks_repo_head_hexsha": "ef8d71bfe84b57491ed12046dcbe1369807bf1d0", "max_forks_repo_licenses": ["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.4698795181, "max_line_length": 81, "alphanum_fraction": 0.593714927, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17524855443809045}}
{"text": "//\n// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)\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// Official repository: https://github.com/boostorg/beast\n//\n\n#ifndef BOOST_BEAST_TEST_FUZZ_HPP\n#define BOOST_BEAST_TEST_FUZZ_HPP\n\n#include <boost/beast/core/static_string.hpp>\n#include <boost/beast/core/string.hpp>\n#include <random>\n\nnamespace boost {\nnamespace beast {\nnamespace test {\n\nclass fuzz_rand\n{\n    std::mt19937 rng_;\n\npublic:\n    std::mt19937&\n    rng()\n    {\n        return rng_;\n    }\n\n    template<class Unsigned>\n    Unsigned\n    operator()(Unsigned n)\n    {\n        return static_cast<Unsigned>(\n            std::uniform_int_distribution<\n                Unsigned>{0, n-1}(rng_));\n    }\n};\n\ntemplate<std::size_t N, class Rand, class F>\nstatic\nvoid\nfuzz(\n    static_string<N> const& input,\n    std::size_t repeat,\n    std::size_t depth,\n    Rand& r,\n    F const& f)\n{\n    static_string<N> mod{input};\n    for(auto i = repeat; i; --i)\n    {\n        switch(r(4))\n        {\n        case 0: // insert\n            if(mod.size() >= mod.max_size())\n                continue;\n            mod.insert(r(mod.size() + 1), 1,\n                static_cast<char>(r(256)));\n            break;\n\n        case 1: // erase\n            if(mod.size() == 0)\n                continue;\n            mod.erase(r(mod.size()), 1);\n            break;\n\n        case 2: // swap\n        {\n            if(mod.size() <= 1)\n                continue;\n            auto off = r(mod.size() - 1);\n            auto const temp = mod[off];\n            mod[off] = mod[off + 1];\n            mod[off + 1] = temp;\n            break;\n        }\n        case 3: // repeat\n        {\n            if(mod.empty())\n                continue;\n            auto n = (std::min)(\n                std::geometric_distribution<\n                    std::size_t>{}(r.rng()),\n                mod.max_size() - mod.size());\n            if(n == 0)\n                continue;\n            auto off = r(mod.size());\n            mod.insert(off, n, mod[off + 1]);\n            break;\n        }\n        }\n        f(string_view{mod.data(), mod.size()});\n        if(depth > 0)\n            fuzz(mod, repeat, depth - 1, r, f);\n    }\n}\n\n} // test\n} // beast\n} // boost\n\n#endif\n", "meta": {"hexsha": "6b8e929f1678b4758adbd8a3b17b3ae567548991", "size": 2347, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/beast/test/extras/include/boost/beast/test/fuzz.hpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "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/boost/libs/beast/test/extras/include/boost/beast/test/fuzz.hpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "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/boost/libs/beast/test/extras/include/boost/beast/test/fuzz.hpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "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": 22.141509434, "max_line_length": 79, "alphanum_fraction": 0.5006391138, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17524855101769718}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, 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_STRATEGIES_AZIMUTH_SPHERICAL_HPP\n#define BOOST_GEOMETRY_STRATEGIES_AZIMUTH_SPHERICAL_HPP\n\n\n// TODO: move this file to boost/geometry/strategy\n#include <boost/geometry/strategies/spherical/azimuth.hpp>\n\n#include <boost/geometry/strategies/azimuth/services.hpp>\n#include <boost/geometry/strategies/detail.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace azimuth\n{\n\ntemplate <typename CalculationType = void>\nclass spherical : strategies::detail::spherical_base<void>\n{\n    using base_t = strategies::detail::spherical_base<void>;\n\npublic:\n    \n    static auto azimuth()\n    {\n        return strategy::azimuth::spherical<CalculationType>();\n    }\n};\n\n\nnamespace services\n{\n\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<Point1, Point2, spherical_equatorial_tag, spherical_equatorial_tag>\n{\n    using type = strategies::azimuth::spherical<>;\n};\n\ntemplate <typename CT>\nstruct strategy_converter<strategy::azimuth::spherical<CT> >\n{\n    static auto get(strategy::azimuth::spherical<CT> const&)\n    {\n        return strategies::azimuth::spherical<CT>();\n    }\n};\n\n\n} // namespace services\n\n}} // namespace strategies::azimuth\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_AZIMUTH_SPHERICAL_HPP\n", "meta": {"hexsha": "a87cf927b93c139fba027c27654167463903418f", "size": 1536, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/spherical.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/spherical.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/spherical.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": 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": 22.5882352941, "max_line_length": 91, "alphanum_fraction": 0.7545572917, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17524855101769715}}
{"text": "// Copyright \u00a9 2017-2019 Trust Wallet.\n//\n// This file is part of Trust. The full Trust copyright notice, including\n// terms governing use, modification, and redistribution, is contained in the\n// file LICENSE at the root of the source code distribution tree.\n\n#include \"Signer.h\"\n#include \"Serialization.h\"\n\n#include \"../Hash.h\"\n#include \"../HexCoding.h\"\n#include \"../PrivateKey.h\"\n#include \"../Data.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl_lite.h>\n#include <string>\n\nusing namespace TW;\nusing namespace TW::Seele;\n\nusing json = nlohmann::json;\nusing uint128_t = boost::multiprecision::uint128_t;\n\nSigner::Signer(Proto::SigningInput&& input) {\n    this->input = input;\n}\n\nstd::vector<uint8_t> Signer::sign() const {\n    auto key = PrivateKey(input.private_key());\n    auto hash = this->hash(input.sign_transaction());\n    auto signature = key.sign(hash, TWCurveSECP256k1);\n\n    return std::vector<uint8_t>(signature.begin(), signature.end());\n}\n\nstd::string Signer::signaturePreimage() const {\n    return signaturePreimageJSON(input).dump();\n}\n\njson Signer::buildTransactionJSON(const Data& signature) const {\n    auto sig = Seele::Proto::Signature();\n    sig.set_sig(signature.data(), signature.size());\n    auto privateKey = PrivateKey(input.private_key());\n\n    auto transaction = Seele::Proto::Transaction();\n    auto hash = this->hash(input.sign_transaction());\n\n\n    *transaction.mutable_data() = input.sign_transaction();\n    *transaction.mutable_signature() = sig;\n    transaction.set_hash(\"0x\"+hex(hash));\n\n    return transactionJSON(transaction);\n}\n\nstd::string Signer::buildTransaction() const {\n    auto signature = sign();\n    return buildTransactionJSON(signature).dump();\n}\n\nProto::SigningOutput Signer::build() const {\n    auto output = Proto::SigningOutput();\n\n    auto signature = sign();\n    auto txJson = buildTransactionJSON(signature);\n\n    output.set_json(txJson.dump());\n    output.set_signature(signature.data(), signature.size());\n\n    return output;\n}\n\nData Signer::hash(const Proto::SignTransaction& transaction) const noexcept {\n    auto encoded = Data();\n\n    append(encoded, RLP::encodeLong(transaction.type()));\n    append(encoded, RLP::encode(parse_hex(transaction.from())));\n    append(encoded, RLP::encode(parse_hex(transaction.to())));\n    append(encoded, RLP::encode(transaction.amount()));\n    append(encoded, RLP::encode(transaction.account_nonce()));\n    append(encoded, RLP::encodeLong(transaction.gas_price()));\n    append(encoded, RLP::encodeLong(transaction.gas_limit()));\n    append(encoded, RLP::encodeLong(transaction.timestamp()));\n    append(encoded, RLP::encode(transaction.payload()));\n\n    return Hash::keccak256(RLP::encodeList(encoded));\n}\n", "meta": {"hexsha": "0b500d88e85eb9f24c90b0216fa184ad698367da", "size": 2798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Seele/Signer.cpp", "max_stars_repo_name": "IFWallet/wallet-core", "max_stars_repo_head_hexsha": "4ab8d2fac26530ffde6dbd56a5b4f1e96c111191", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T02:56:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T16:58:29.000Z", "max_issues_repo_path": "src/Seele/Signer.cpp", "max_issues_repo_name": "moneto-dev/wallet-core", "max_issues_repo_head_hexsha": "0bfd312f868f02fe51cd2672e2397fd98d707db7", "max_issues_repo_licenses": ["MIT"], "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/Seele/Signer.cpp", "max_forks_repo_name": "moneto-dev/wallet-core", "max_forks_repo_head_hexsha": "0bfd312f868f02fe51cd2672e2397fd98d707db7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-03-07T14:54:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T03:27:31.000Z", "avg_line_length": 31.0888888889, "max_line_length": 77, "alphanum_fraction": 0.7155110793, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.17524854759730396}}
{"text": "\n#ifndef BOOST_MPL_NEGATE_HPP_INCLUDED\n#define BOOST_MPL_NEGATE_HPP_INCLUDED\n\n// Copyright Aleksey Gurtovoy 2000-2004\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// See http://www.boost.org/libs/mpl for documentation.\n\n// $Id: negate.hpp 49267 2008-10-11 06:19:02Z agurtovoy $\n// $Date: 2008-10-11 08:19:02 +0200 (sam., 11 oct. 2008) $\n// $Revision: 49267 $\n\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/aux_/msvc_eti_base.hpp>\n#include <boost/mpl/aux_/na_spec.hpp>\n#include <boost/mpl/aux_/lambda_support.hpp>\n#include <boost/mpl/aux_/config/eti.hpp>\n#include <boost/mpl/aux_/config/integral.hpp>\n#include <boost/mpl/aux_/config/static_constant.hpp>\n\nnamespace boost { namespace mpl {\n\ntemplate< typename Tag > struct negate_impl;\n\ntemplate< typename T > struct negate_tag\n{\n    typedef typename T::tag type;\n};\n\ntemplate<\n      typename BOOST_MPL_AUX_NA_PARAM(N)\n    >\nstruct negate\n#if !defined(BOOST_MPL_CFG_MSVC_ETI_BUG)\n    : negate_impl<\n          typename negate_tag<N>::type\n        >::template apply<N>::type\n#else\n    : aux::msvc_eti_base< typename apply_wrap1<\n          negate_impl< typename negate_tag<N>::type >\n        , N\n        >::type >::type\n#endif\n{\n    BOOST_MPL_AUX_LAMBDA_SUPPORT(1, negate, (N))\n};\n\nBOOST_MPL_AUX_NA_SPEC(1, negate)\n\n\n#if defined(BOOST_MPL_CFG_NO_NESTED_VALUE_ARITHMETIC)\nnamespace aux {\ntemplate< typename T, T n > struct negate_wknd\n{\n    BOOST_STATIC_CONSTANT(T, value = -n);\n    typedef integral_c<T,value> type;\n};\n}\n#endif\n\ntemplate<>\nstruct negate_impl<integral_c_tag>\n{\n#if defined(BOOST_MPL_CFG_NO_NESTED_VALUE_ARITHMETIC)\n    template< typename N > struct apply\n        : aux::negate_wknd< typename N::value_type, N::value >\n#else\n    template< typename N > struct apply\n        : integral_c< typename N::value_type, (-N::value) >\n#endif    \n    {\n    };\n};\n\n}}\n\n#endif // BOOST_MPL_NEGATE_HPP_INCLUDED\n", "meta": {"hexsha": "7df8c11938a0c811e97080a824edc9f0c4903b9d", "size": 1986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_45/boost/mpl/negate.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "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": "vegastrike/boost/1_45/boost/mpl/negate.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_45/boost/mpl/negate.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["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.2195121951, "max_line_length": 62, "alphanum_fraction": 0.7104733132, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.17524854759730396}}
{"text": "\n\n#include <NTL/GF2E.h>\n\n\nNTL_START_IMPL\n\nNTL_TLS_GLOBAL_DECL(SmartPtr<GF2EInfoT>, GF2EInfo_stg)\n\nNTL_CHEAP_THREAD_LOCAL\nGF2EInfoT *GF2EInfo = 0; \n\n\nGF2EInfoT::GF2EInfoT(const GF2X& NewP)\n{\n   build(p, NewP);\n   _card_exp = p.n;\n\n   long sz = p.size;\n\n// The following crossovers were set using the programs\n// GF2EXKarCross.cpp, GF2EXModCross.cpp, GF2EXModCross.cpp,\n// and GF2EXGCDCross.cpp.\n// To use these programs, one has to remove the #if 0 guards\n// in GF2EX.cpp on mul_disable_plain, BuildPlain, and DivRemPlain.\n\n// There are three different configurations that are treated separately:\n//   * with gf2x lib and with pclmul instruction available\n//   * without gf2x lib but with pclmul\n//   * without gf2X lib and without pclmul\n// It is possible that one could be using gf2x lib on a platform without\n// pclmul, in which case the crossovers used here are not optimal.  It is also\n// possible that one could be using gf2x lib with pclmul, but compile NTL with\n// NATIVE=off, so that NTL assumes there is no pclmul.  Again, this will lead\n// to crossovers that are not optimal.\n\n// The crossovers were calculated based on a Skylake Xeon processor:\n// Intel(R) Xeon(R) Gold 6132 CPU @ 2.60GHz.\n\n\n#if (defined(NTL_GF2X_LIB) && defined(NTL_HAVE_PCLMUL))\n\n   //========== KarCross ==========\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         KarCross = 3;\n      else\n         KarCross = 4;\n   }\n   else if (sz <= 6) KarCross = 8;\n   else if (sz <= 9) KarCross = 4;\n   else              KarCross = 2;\n\n\n\n   //========== ModCross ==========\n\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         ModCross = 15;\n      else\n         ModCross = 20;\n   }\n   else if (sz <=  9) ModCross =  60;\n   else if (sz <= 18) ModCross =  25;\n   else               ModCross =  15;\n\n\n   //========== DivCross ==========\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         DivCross =  50;\n      else\n         DivCross =  75;\n   }\n   else if (sz <=  2) DivCross = 100;\n   else if (sz <=  3) DivCross = 150;\n   else if (sz <=  4) DivCross = 200;\n   else if (sz <=  6) DivCross = 250;\n   else if (sz <=  9) DivCross = 225;\n   else if (sz <= 15) DivCross = 125;\n   else if (sz < 125) DivCross = 100;\n   else               DivCross =  75;\n\n   //========== GCDCross ==========\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         GCDCross = 225;\n      else\n         GCDCross = 225;\n   }\n   else if (sz <=  2) GCDCross =  450;\n   else if (sz <=  4) GCDCross =  600;\n   else if (sz <  12) GCDCross = 1150;\n   else               GCDCross =  600;\n\n\n#elif (defined(NTL_HAVE_PCLMUL))\n\n   //========== KarCross ==========\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         KarCross = 5;\n      else\n         KarCross = 8;\n   }\n   else if (sz <= 5) KarCross = 8;\n   else if (sz <= 9) KarCross = 4;\n   else              KarCross = 2;\n\n\n\n   //========== ModCross ==========\n\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         ModCross = 30;\n      else\n         ModCross = 45;\n   }\n   else if (sz <=  2) ModCross = 110;\n   else if (sz <=  3) ModCross = 105;\n   else if (sz <=  4) ModCross =  65;\n   else if (sz <=  5) ModCross =  60;\n   else if (sz <=  6) ModCross =  55;\n   else if (sz <=  8) ModCross =  50;\n   else if (sz <= 12) ModCross =  30;\n   else if (sz <= 18) ModCross =  25;\n   else               ModCross =  15;\n\n\n\n   //========== DivCross ==========\n\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         DivCross =  75;\n      else\n         DivCross = 125;\n   }\n   else if (sz <=  2) DivCross = 450;\n   else if (sz <=  3) DivCross = 425;\n   else if (sz <=  4) DivCross = 375;\n   else if (sz <=  6) DivCross = 250;\n   else if (sz <=  8) DivCross = 225;\n   else if (sz <= 16) DivCross = 125;\n   else if (sz <= 45) DivCross = 100;\n   else               DivCross =  75;\n\n\n   //========== GCDCross ==========\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         GCDCross = 225;\n      else\n         GCDCross = 225;\n   }\n   else if (sz < 12) GCDCross = 1150;\n   else              GCDCross =  850;\n\n#else\n\n   //========== KarCross ==========\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         KarCross = 4;\n      else\n         KarCross = 12;\n   }\n   else if (sz <= 3) KarCross = 4;\n   else              KarCross = 2;\n\n\n\n   //========== ModCross ==========\n\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         ModCross = 45;\n      else\n         ModCross = 65;\n   }\n   else if (sz <=  2) ModCross =  25;\n   else               ModCross =  15;\n\n\n   //========== DivCross ==========\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         DivCross = 175;\n      else\n         DivCross = 250;\n   }\n   else if (sz <=  4) DivCross = 100;\n   else               DivCross =  75;\n\n   //========== GCDCross ==========\n\n   if (sz <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         GCDCross = 225;\n      else\n         GCDCross = 850;\n   }\n   else if (sz <  8) GCDCross =  850;\n   else if (sz < 12) GCDCross =  600;\n   else              GCDCross =  450;\n\n\n#endif\n\n}\n\n\nconst ZZ& GF2E::cardinality()\n{\n   if (!GF2EInfo) LogicError(\"GF2E::cardinality: undefined modulus\");\n\n   do { // NOTE: thread safe lazy init\n      Lazy<ZZ>::Builder builder(GF2EInfo->_card);\n      if (!builder()) break;\n      UniquePtr<ZZ> p;\n      p.make();\n      power(*p, 2, GF2EInfo->_card_exp);\n      builder.move(p);\n   } while (0);\n\n   return *GF2EInfo->_card;\n}\n\n\n\n\n\n\n\nvoid GF2E::init(const GF2X& p)\n{\n   GF2EContext c(p);\n   c.restore();\n}\n\n\nvoid GF2EContext::save()\n{\n   NTL_TLS_GLOBAL_ACCESS(GF2EInfo_stg);\n   ptr = GF2EInfo_stg;\n}\n\nvoid GF2EContext::restore() const\n{\n   NTL_TLS_GLOBAL_ACCESS(GF2EInfo_stg);\n   GF2EInfo_stg = ptr;\n   GF2EInfo = GF2EInfo_stg.get();\n}\n\n\n\nGF2EBak::~GF2EBak()\n{\n   if (MustRestore) c.restore();\n}\n\nvoid GF2EBak::save()\n{\n   c.save();\n   MustRestore = true;\n}\n\n\nvoid GF2EBak::restore()\n{\n   c.restore();\n   MustRestore = false;\n}\n\n\n\nconst GF2E& GF2E::zero()\n{\n   static const GF2E z(INIT_NO_ALLOC); // GLOBAL (assumes C++11 thread-safe init)\n   return z;\n}\n\n\n\nistream& operator>>(istream& s, GF2E& x)\n{\n   GF2X y;\n\n   NTL_INPUT_CHECK_RET(s, s >> y);\n   conv(x, y);\n\n   return s;\n}\n\nvoid div(GF2E& x, const GF2E& a, const GF2E& b)\n{\n   GF2E t;\n\n   inv(t, b);\n   mul(x, a, t);\n}\n\nvoid div(GF2E& x, GF2 a, const GF2E& b)\n{\n   inv(x, b);\n   mul(x, x, a);\n}\n\nvoid div(GF2E& x, long a, const GF2E& b)\n{\n   inv(x, b);\n   mul(x, x, a);\n}\n\n\nvoid inv(GF2E& x, const GF2E& a)\n{\n   InvMod(x._GF2E__rep, a._GF2E__rep, GF2E::modulus());\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "a95d015e75df9c339e9a62968c47c1a7dc5d5fe2", "size": 6593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2E.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": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T06:14:16.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2E.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T22:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T10:03:13.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/GF2E.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T07:59:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T10:27:23.000Z", "avg_line_length": 19.6220238095, "max_line_length": 81, "alphanum_fraction": 0.5308660701, "num_tokens": 2274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.17517681226241266}}
{"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_SDK_SIMD_EXTENSIONS_X86_FMA4_HPP_INCLUDED\n#define BOOST_SIMD_SDK_SIMD_EXTENSIONS_X86_FMA4_HPP_INCLUDED\n\n#if defined(__FMA4__)\n#  ifndef BOOST_SIMD_HAS_FMA4_SUPPORT\n#    define BOOST_SIMD_HAS_FMA4_SUPPORT\n#  endif\n#elif defined(BOOST_SIMD_HAS_FMA4_SUPPORT) && !defined(_MSC_VER)\n#  undef BOOST_SIMD_HAS_FMA4_SUPPORT\n#endif\n\n#ifdef BOOST_SIMD_HAS_FMA4_SUPPORT\n#  ifndef BOOST_SIMD_HAS_AVX_SUPPORT\n#    define BOOST_SIMD_HAS_AVX_SUPPORT\n#  endif\n#  ifndef BOOST_SIMD_HAS_SSE4A_SUPPORT\n#    define BOOST_SIMD_HAS_SSE4A_SUPPORT\n#  endif\n#endif\n\n#if !defined(BOOST_SIMD_DETECTED) && defined(BOOST_SIMD_HAS_FMA4_SUPPORT)\n\n////////////////////////////////////////////////////////////////////////////////\n// FMA4 extensions flags\n////////////////////////////////////////////////////////////////////////////////\n#define BOOST_SIMD_DETECTED\n#define BOOST_SIMD_FMA4\n#define BOOST_SIMD_SSE_FAMILY\n#define BOOST_SIMD_STRING             \"FMA4\"\n#define BOOST_SIMD_STRING_LIST        \"SSE2 SSE3 SSE4A SSSE3 SSE4_1 SSE4_2 AVX FMA4\"\n#define BOOST_SIMD_BYTES              32\n#define BOOST_SIMD_BITS               256\n#define BOOST_SIMD_CARDINALS          (2)(4)(8)(16)(32)\n#define BOOST_SIMD_TAG_SEQ            (::boost::simd::tag::avx_)(::boost::simd::tag::sse_)\n\n#ifndef BOOST_SIMD_DEFAULT_EXTENSION\n#define BOOST_SIMD_DEFAULT_EXTENSION  ::boost::simd::tag::avx_\n#endif\n\n#define BOOST_SIMD_DEFAULT_SITE       ::boost::simd::tag::fma4_\n#define BOOST_SIMD_SIMD_HAS_ALL_TYPES\n\n// FMA4 header not standardized\n#ifdef _MSC_VER\n#include <intrin.h>\n#else\n#include <x86intrin.h>\n#include <fma4intrin.h>\n#endif\n\n#include <boost/simd/sdk/simd/extensions/meta/sse.hpp>\n#include <boost/simd/sdk/simd/extensions/meta/avx.hpp>\n\n#endif\n#endif\n", "meta": {"hexsha": "3e83908d6197a42ebb7e6271a52deb7a95fda992", "size": 2237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/sdk/simd/extensions/x86/fma4.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/sdk/include/boost/simd/sdk/simd/extensions/x86/fma4.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/sdk/include/boost/simd/sdk/simd/extensions/x86/fma4.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.953125, "max_line_length": 90, "alphanum_fraction": 0.6370138578, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.17513093053896736}}
{"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_SIMD_FUNCTION_COMPARE_GREATER_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_COMPARE_GREATER_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/function/compare_less.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( compare_greater_\n                          , (typename X, typename A0)\n                          , bd::cpu_\n                          , bs::pack_<bd::fundamental_<A0>, X>\n                          , bs::pack_<bd::fundamental_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE bool operator()( const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      return compare_less(a1, a0);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "12fc8bf53c9f8180f2c1d7d82fe93a7fb331e597", "size": 1187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/compare_greater.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/compare_greater.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/compare_greater.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.9142857143, "max_line_length": 100, "alphanum_fraction": 0.5358045493, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.1751309255641351}}
{"text": "/*\n * Copyright 2013-2014, Unbounded Robotics 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 Unbounded Robotics, 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// Author: Michael Ferguson\n\n#include <math.h>\n#include <Eigen/Eigen>\n#include <pcl/filters/project_inliers.h>\n#include <pcl/surface/convex_hull.h>\n#include <simple_grasping/shape_extraction.h>\n\nnamespace simple_grasping\n{\n\nbool extractShape(const pcl::PointCloud<pcl::PointXYZRGB>& input,\n                  const pcl::ModelCoefficients::Ptr model,\n                  pcl::PointCloud<pcl::PointXYZRGB>& output,\n                  shape_msgs::SolidPrimitive& shape,\n                  geometry_msgs::Pose& pose)\n{\n  // Used to decide between various shapes\n  double min_volume = 1000.0;  // the minimum volume shape found thus far.\n  Eigen::Matrix3f transformation;  // the transformation for the best-fit shape\n\n  // Compute z height as maximum distance from planes\n  double height = 0.0;\n  for (size_t i = 0; i < input.size(); ++i)\n  {\n    Eigen::Vector4f pp(input[i].x, input[i].y, input[i].z, 1);\n    Eigen::Vector4f m(model->values[0], model->values[1], model->values[2], model->values[3]);\n    double distance_to_plane = fabs(pp.dot(m));\n    if (distance_to_plane > height)\n      height = distance_to_plane;\n  }\n\n  // Project object into 2d, using plane model coefficients\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr flat(new pcl::PointCloud<pcl::PointXYZRGB>);\n  pcl::ProjectInliers<pcl::PointXYZRGB> projection;\n  projection.setModelType(pcl::SACMODEL_PLANE);\n  projection.setInputCloud(input.makeShared());  // stupid API\n  projection.setModelCoefficients(model);\n  projection.filter(*flat);\n\n  // Rotate plane so that Z=0\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr flat_projected(new pcl::PointCloud<pcl::PointXYZRGB>);\n  Eigen::Vector3f normal(model->values[0], model->values[1], model->values[2]);\n  Eigen::Quaternionf qz; qz.setFromTwoVectors(normal, Eigen::Vector3f::UnitZ());\n  Eigen::Matrix3f plane_rotation = qz.toRotationMatrix();\n  Eigen::Matrix3f inv_plane_rotation = plane_rotation.inverse();\n\n  for (size_t i = 0; i < flat->size(); ++i)\n  {\n    pcl::PointXYZRGB p;\n    p.getVector3fMap() = plane_rotation * (*flat)[i].getVector3fMap();\n    flat_projected->push_back(p);\n  }\n\n  // Find the convex hull\n  pcl::PointCloud<pcl::PointXYZRGB> hull;\n  pcl::ConvexHull<pcl::PointXYZRGB> convex_hull;\n  convex_hull.setInputCloud(flat_projected);\n  convex_hull.setDimension(2);\n  convex_hull.reconstruct(hull);\n\n  // Try fitting a rectangle\n  shape_msgs::SolidPrimitive rect;  // the best-fit rectangle\n  rect.type = rect.BOX;\n  rect.dimensions.resize(3);\n  for (size_t i = 0; i < hull.size() - 1; ++i)\n  {\n    // For each pair of hull points, determine the angle\n    double rise = hull[i+1].y - hull[i].y;\n    double run = hull[i+1].x - hull[i].x;\n    // and normalize..\n    {\n      double l = sqrt((rise * rise) + (run * run));\n      rise = rise/l;\n      run = run/l;\n    }\n\n    // Build rotation matrix from change of basis\n    Eigen::Matrix3f rotation;\n    rotation(0, 0) = run;\n    rotation(0, 1) = rise;\n    rotation(0, 2) = 0.0;\n    rotation(1, 0) = -rise;\n    rotation(1, 1) = run;\n    rotation(1, 2) = 0.0;\n    rotation(2, 0) = 0.0;\n    rotation(2, 1) = 0.0;\n    rotation(2, 2) = 1.0;\n    Eigen::Matrix3f inv_rotation = rotation.inverse();\n\n    // Project hull to new coordinate system\n    pcl::PointCloud<pcl::PointXYZRGB> projected_cloud;\n    for (size_t j = 0; j < hull.size(); ++j)\n    {\n      pcl::PointXYZRGB p;\n      p.getVector3fMap() = rotation * hull[j].getVector3fMap();\n      projected_cloud.push_back(p);\n    }\n\n    // Compute min/max\n    double x_min = 1000.0;\n    double x_max = -1000.0;\n    double y_min = 1000.0;\n    double y_max = -1000.0;\n    for (size_t j = 0; j < projected_cloud.size(); ++j)\n    {\n      if (projected_cloud[j].x < x_min)\n        x_min = projected_cloud[j].x;\n      if (projected_cloud[j].x > x_max)\n        x_max = projected_cloud[j].x;\n\n      if (projected_cloud[j].y < y_min)\n        y_min = projected_cloud[j].y;\n      if (projected_cloud[j].y > y_max)\n        y_max = projected_cloud[j].y;\n    }\n\n    // Is this the best estimate?\n    double area = (x_max - x_min) * (y_max - y_min);\n    if (area*height < min_volume)\n    {\n      transformation = inv_plane_rotation * inv_rotation;\n\n      rect.dimensions[0] = (x_max - x_min);\n      rect.dimensions[1] = (y_max - y_min);\n      rect.dimensions[2] = height;\n\n      Eigen::Vector3f pose3f((x_max + x_min)/2.0, (y_max + y_min)/2.0,\n                             projected_cloud[0].z + height/2.0);\n      pose3f = transformation * pose3f;\n      pose.position.x = pose3f(0);\n      pose.position.y = pose3f(1);\n      pose.position.z = pose3f(2);\n\n      Eigen::Quaternionf q(transformation);\n      pose.orientation.x = q.x();\n      pose.orientation.y = q.y();\n      pose.orientation.z = q.z();\n      pose.orientation.w = q.w();\n\n      min_volume = area * height;\n      shape = rect;\n    }\n  }\n\n  // Try fitting a cylinder\n  shape_msgs::SolidPrimitive cylinder;  // the best-fit cylinder\n  cylinder.type = cylinder.CYLINDER;\n  cylinder.dimensions.resize(2);\n  for (size_t i = 0; i < hull.size(); ++i)\n  {\n    for (size_t j = i + 1; j < hull.size(); ++j)\n    {\n      // For each pair of hull points determine the center point\n      //  between them as a possible cylinder\n      pcl::PointXYZRGB p;\n      p.x = (hull[i].x + hull[j].x) / 2.0;\n      p.y = (hull[i].y + hull[j].y) / 2.0;\n      double radius = 0.0;\n      // Find radius from this point\n      for (size_t k = 0; k < hull.size(); ++k)\n      {\n        double dx = hull[k].x - p.x;\n        double dy = hull[k].y - p.y;\n        double r = sqrt((dx * dx) + (dy * dy));\n        if (r > radius)\n          radius = r;\n      }\n      // Is this cylinder the best match?\n      double volume = M_PI * radius * radius * height;\n      if (volume < min_volume)\n      {\n        transformation = inv_plane_rotation;\n\n        cylinder.dimensions[0] = height;\n        cylinder.dimensions[1] = radius;\n\n        Eigen::Vector3f pose3f(p.x, p.y, hull[0].z + height/2.0);\n        pose3f = transformation * pose3f;\n        pose.position.x = pose3f(0);\n        pose.position.y = pose3f(1);\n        pose.position.z = pose3f(2);\n\n        min_volume = volume;\n        shape = cylinder;\n      }\n    }\n  }\n\n  // TODO: Try fitting a sphere?\n\n  // Project input to new frame\n  Eigen::Vector3f origin(pose.position.x, pose.position.y, pose.position.z);\n  for (size_t j = 0; j < input.size(); ++j)\n  {\n    pcl::PointXYZRGB p;\n    p.getVector3fMap() = transformation * (input[j].getVector3fMap() - origin);\n    output.push_back(p);\n  }\n  return true;\n}\n\nbool extractShape(const pcl::PointCloud<pcl::PointXYZRGB>& input,\n                  pcl::PointCloud<pcl::PointXYZRGB>& output,\n                  shape_msgs::SolidPrimitive& shape,\n                  geometry_msgs::Pose& pose)\n{\n  // Find lowest point, use as z height\n  pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);\n  coefficients->values.resize(4);\n  coefficients->values[0] = 0.0;\n  coefficients->values[1] = 0.0;\n  coefficients->values[2] = 1.0;\n  coefficients->values[3] = 1000.0;  // z-height\n  for (size_t i = 0; i < input.size(); ++i)\n  {\n    if (input[i].z < coefficients->values[3])\n      coefficients->values[3] = input[i].z;\n  }\n  coefficients->values[3] = -coefficients->values[3];\n  return extractShape(input, coefficients, output, shape, pose);\n}\n\nbool extractUnorientedBoundingBox(const pcl::PointCloud<pcl::PointXYZRGB>& input,\n                                  shape_msgs::SolidPrimitive& shape,\n                                  geometry_msgs::Pose& pose)\n{\n  double x_min = 1000.0;\n  double x_max = -1000.0;\n  double y_min = 1000.0;\n  double y_max = -1000.0;\n  double z_min = 1000.0;\n  double z_max = -1000.0;\n\n  for (size_t i = 0; i < input.size(); ++i)\n  {\n    if (input[i].x < x_min)\n      x_min = input[i].x;\n    if (input[i].x > x_max)\n      x_max = input[i].x;\n\n    if (input[i].y < y_min)\n      y_min = input[i].y;\n    if (input[i].y > y_max)\n      y_max = input[i].y;\n\n    if (input[i].z < z_min)\n      z_min = input[i].z;\n    if (input[i].z > z_max)\n      z_max = input[i].z;\n  }\n\n  pose.position.x = (x_min + x_max)/2.0;\n  pose.position.y = (y_min + y_max)/2.0;\n  pose.position.z = (z_min + z_max)/2.0;\n\n  shape.type = shape.BOX;\n  shape.dimensions.push_back(x_max-x_min);\n  shape.dimensions.push_back(y_max-y_min);\n  shape.dimensions.push_back(z_max-z_min);\n\n  return true;\n}\n\n}  // namespace simple_grasping\n", "meta": {"hexsha": "1c89210c6ff32152d630ec15d9d89d1ef4c89a9b", "size": 9958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "movo_common/movo_third_party/simple_grasping/src/shape_extraction.cpp", "max_stars_repo_name": "aaronsnoswell/kinova-movo", "max_stars_repo_head_hexsha": "380c7827a9cec12cc0f4f0cc19ce0b88775c6c51", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2017-12-13T16:14:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T03:12:52.000Z", "max_issues_repo_path": "movo_common/movo_third_party/simple_grasping/src/shape_extraction.cpp", "max_issues_repo_name": "aaronsnoswell/kinova-movo", "max_issues_repo_head_hexsha": "380c7827a9cec12cc0f4f0cc19ce0b88775c6c51", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 71.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T20:17:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:48:45.000Z", "max_forks_repo_path": "movo_common/movo_third_party/simple_grasping/src/shape_extraction.cpp", "max_forks_repo_name": "aaronsnoswell/kinova-movo", "max_forks_repo_head_hexsha": "380c7827a9cec12cc0f4f0cc19ce0b88775c6c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T03:21:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T03:12:47.000Z", "avg_line_length": 33.7559322034, "max_line_length": 95, "alphanum_fraction": 0.6367744527, "num_tokens": 2740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.17513092556413506}}
{"text": "#ifndef __wrapper_MSSMNoFV_onshell_soft_parameters_decl_gm2calc_1_3_0_hpp__\n#define __wrapper_MSSMNoFV_onshell_soft_parameters_decl_gm2calc_1_3_0_hpp__\n\n#include <cstddef>\n#include <Eigen/Core>\n#include <ostream>\n#include \"forward_decls_wrapper_classes.hpp\"\n#include \"gambit/Backends/wrapperbase.hpp\"\n#include \"abstract_MSSMNoFV_onshell_soft_parameters.hpp\"\n#include \"wrapper_MSSMNoFV_onshell_susy_parameters_decl.hpp\"\n\n#include \"identification.hpp\"\n\nnamespace CAT_3(BACKENDNAME,_,SAFE_VERSION)\n{\n   \n   namespace gm2calc\n   {\n      \n      class MSSMNoFV_onshell_soft_parameters : public MSSMNoFV_onshell_susy_parameters\n      {\n            // Member variables: \n         public:\n            // -- Static factory pointers: \n            static Abstract_MSSMNoFV_onshell_soft_parameters* (*__factory0)();\n            static Abstract_MSSMNoFV_onshell_soft_parameters* (*__factory1)(const gm2calc::MSSMNoFV_onshell_susy_parameters&, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&, double, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&, double, double, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>&, double, double, double);\n      \n            // -- Other member variables: \n      \n            // Member functions: \n         public:\n            void print(::std::basic_ostream<char, std::char_traits<char> >& arg_1) const;\n      \n            void clear();\n      \n            void set_TYd(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& TYd_);\n      \n            void set_TYd(int i, int k, double value);\n      \n            void set_TYe(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& TYe_);\n      \n            void set_TYe(int i, int k, double value);\n      \n            void set_TYu(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& TYu_);\n      \n            void set_TYu(int i, int k, double value);\n      \n            void set_BMu(double BMu_);\n      \n            void set_mq2(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& mq2_);\n      \n            void set_mq2(int i, int k, double value);\n      \n            void set_ml2(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& ml2_);\n      \n            void set_ml2(int i, int k, double value);\n      \n            void set_mHd2(double mHd2_);\n      \n            void set_mHu2(double mHu2_);\n      \n            void set_md2(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& md2_);\n      \n            void set_md2(int i, int k, double value);\n      \n            void set_mu2(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& mu2_);\n      \n            void set_mu2(int i, int k, double value);\n      \n            void set_me2(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& me2_);\n      \n            void set_me2(int i, int k, double value);\n      \n            void set_MassB(double MassB_);\n      \n            void set_MassWB(double MassWB_);\n      \n            void set_MassG(double MassG_);\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_TYd() const;\n      \n            double get_TYd(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_TYe() const;\n      \n            double get_TYe(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_TYu() const;\n      \n            double get_TYu(int i, int k) const;\n      \n            double get_BMu() const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_mq2() const;\n      \n            double get_mq2(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_ml2() const;\n      \n            double get_ml2(int i, int k) const;\n      \n            double get_mHd2() const;\n      \n            double get_mHu2() const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_md2() const;\n      \n            double get_md2(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_mu2() const;\n      \n            double get_mu2(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_me2() const;\n      \n            double get_me2(int i, int k) const;\n      \n            double get_MassB() const;\n      \n            double get_MassWB() const;\n      \n            double get_MassG() const;\n      \n      \n            // Wrappers for original constructors: \n         public:\n            MSSMNoFV_onshell_soft_parameters();\n            MSSMNoFV_onshell_soft_parameters(const gm2calc::MSSMNoFV_onshell_susy_parameters& arg_1, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& TYd_, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& TYe_, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& TYu_, double BMu_, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& mq2_, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& ml2_, double mHd2_, double mHu2_, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& md2_, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& mu2_, const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& me2_, double MassB_, double MassWB_, double MassG_);\n      \n            // Special pointer-based constructor: \n            MSSMNoFV_onshell_soft_parameters(Abstract_MSSMNoFV_onshell_soft_parameters* in);\n      \n            // Copy constructor: \n            MSSMNoFV_onshell_soft_parameters(const MSSMNoFV_onshell_soft_parameters& in);\n      \n            // Assignment operator: \n            MSSMNoFV_onshell_soft_parameters& operator=(const MSSMNoFV_onshell_soft_parameters& in);\n      \n            // Destructor: \n            ~MSSMNoFV_onshell_soft_parameters();\n      \n            // Returns correctly casted pointer to Abstract class: \n            Abstract_MSSMNoFV_onshell_soft_parameters* get_BEptr() const;\n      \n      };\n   }\n   \n}\n\n\n#include \"gambit/Backends/backend_undefs.hpp\"\n\n#endif /* __wrapper_MSSMNoFV_onshell_soft_parameters_decl_gm2calc_1_3_0_hpp__ */\n", "meta": {"hexsha": "707f8735b84aa982a517377adfba65c5127398ea", "size": 5963, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/wrapper_MSSMNoFV_onshell_soft_parameters_decl.hpp", "max_stars_repo_name": "GambitBSM/gambit_2.0", "max_stars_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T22:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T22:53:26.000Z", "max_issues_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/wrapper_MSSMNoFV_onshell_soft_parameters_decl.hpp", "max_issues_repo_name": "GambitBSM/gambit_2.0", "max_issues_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T11:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T17:24:41.000Z", "max_forks_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/wrapper_MSSMNoFV_onshell_soft_parameters_decl.hpp", "max_forks_repo_name": "GambitBSM/gambit_2.0", "max_forks_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:31:41.000Z", "avg_line_length": 38.7207792208, "max_line_length": 604, "alphanum_fraction": 0.5777293309, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.17513091861816954}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2019 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@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_MAC_HMAC_HPP\n#define CRYPTO3_MAC_HMAC_HPP\n\n#include <nil/crypto3/detail/pack.hpp>\n\n#include <nil/crypto3/mac/detail/hmac/accumulator.hpp>\n#include <nil/crypto3/mac/detail/hmac/hmac_policy.hpp>\n\n#include <nil/crypto3/hash/hash_state.hpp>\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace mac {\n            /*!\n             * @brief\n             * @tparam Hash\n             * @ingroup mac\n             */\n            template<typename Hash>\n            class hmac {\n                typedef detail::hmac_policy<Hash> policy_type;\n\n                typedef typename policy_type::byte_type byte_type;\n                typedef typename policy_type::word_type word_type;\n\n                typedef typename policy_type::construction_type construction_type;\n                typedef typename construction_type::endian_type endian_type;\n\n                constexpr static const std::size_t block_bytes = policy_type::block_bits / CHAR_BIT;\n\n            public:\n                typedef Hash hash_type;\n\n                constexpr static const std::size_t block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                constexpr static const std::size_t key_bits = policy_type::key_bits;\n                constexpr static const std::size_t key_words = policy_type::key_words;\n                typedef typename policy_type::key_type key_type;\n\n                constexpr static const std::size_t digest_bits = policy_type::digest_bits;\n                typedef typename policy_type::digest_type digest_type;\n\n                hmac(const key_type &key) {\n                    schedule_key(key);\n                }\n\n            protected:\n                void schedule_key(const key_type &key) {\n                    m_hash->clear();\n\n                    const uint8_t ipad = 0x36;\n                    const uint8_t opad = 0x5C;\n\n                    std::fill(ikey.begin(), ikey.end(), ipad);\n                    std::fill(okey.begin(), okey.end(), opad);\n\n                    if (length > m_hash->hash_block_size()) {\n                        secure_vector<uint8_t> hmac_key = m_hash->process(key, length);\n                        xor_buf(ikey, hmac_key, hmac_key.size());\n                        xor_buf(okey, hmac_key, hmac_key.size());\n                    } else {\n                        xor_buf(ikey, key, length);\n                        xor_buf(okey, key, length);\n                    }\n\n                    m_hash->update(m_ikey);\n                }\n\n            private:\n                std::array<byte_type, block_bytes> ikey, okey;\n            };\n        }    // namespace mac\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif", "meta": {"hexsha": "d2dd6ab257f98a2ee8f6487bf56238d9ef899b97", "size": 4285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/mac/include/nil/crypto3/mac/hmac.hpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "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/mac/include/nil/crypto3/mac/hmac.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-10T11:06:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T08:52:49.000Z", "max_forks_repo_path": "libs/mac/include/nil/crypto3/mac/hmac.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": 40.046728972, "max_line_length": 100, "alphanum_fraction": 0.5955659277, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.17513091861816954}}
{"text": "#define BOOST_TEST_MODULE pichi method test\n\n#include <boost/test/unit_test.hpp>\n#include <pichi/crypto/method.hpp>\n\nusing namespace pichi::crypto;\n\nBOOST_AUTO_TEST_SUITE(METHOD)\n\nBOOST_AUTO_TEST_CASE(KEY_SIZE_Test)\n{\n  BOOST_CHECK_EQUAL(16, KEY_SIZE<CryptoMethod::RC4_MD5>);\n  BOOST_CHECK_EQUAL(16, KEY_SIZE<CryptoMethod::BF_CFB>);\n  BOOST_CHECK_EQUAL(16, KEY_SIZE<CryptoMethod::AES_128_CTR>);\n  BOOST_CHECK_EQUAL(24, KEY_SIZE<CryptoMethod::AES_192_CTR>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::AES_256_CTR>);\n  BOOST_CHECK_EQUAL(16, KEY_SIZE<CryptoMethod::AES_128_CFB>);\n  BOOST_CHECK_EQUAL(24, KEY_SIZE<CryptoMethod::AES_192_CFB>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::AES_256_CFB>);\n  BOOST_CHECK_EQUAL(16, KEY_SIZE<CryptoMethod::CAMELLIA_128_CFB>);\n  BOOST_CHECK_EQUAL(24, KEY_SIZE<CryptoMethod::CAMELLIA_192_CFB>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::CAMELLIA_256_CFB>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::CHACHA20>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::SALSA20>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::CHACHA20_IETF>);\n  BOOST_CHECK_EQUAL(16, KEY_SIZE<CryptoMethod::AES_128_GCM>);\n  BOOST_CHECK_EQUAL(24, KEY_SIZE<CryptoMethod::AES_192_GCM>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::AES_256_GCM>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::CHACHA20_IETF_POLY1305>);\n  BOOST_CHECK_EQUAL(32, KEY_SIZE<CryptoMethod::XCHACHA20_IETF_POLY1305>);\n}\n\nBOOST_AUTO_TEST_CASE(IV_SIZE_Test)\n{\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::RC4_MD5>);\n  BOOST_CHECK_EQUAL(8, IV_SIZE<CryptoMethod::BF_CFB>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::AES_128_CTR>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::AES_192_CTR>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::AES_256_CTR>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::AES_128_CFB>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::AES_192_CFB>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::AES_256_CFB>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::CAMELLIA_128_CFB>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::CAMELLIA_192_CFB>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::CAMELLIA_256_CFB>);\n  BOOST_CHECK_EQUAL(8, IV_SIZE<CryptoMethod::CHACHA20>);\n  BOOST_CHECK_EQUAL(8, IV_SIZE<CryptoMethod::SALSA20>);\n  BOOST_CHECK_EQUAL(12, IV_SIZE<CryptoMethod::CHACHA20_IETF>);\n  BOOST_CHECK_EQUAL(16, IV_SIZE<CryptoMethod::AES_128_GCM>);\n  BOOST_CHECK_EQUAL(24, IV_SIZE<CryptoMethod::AES_192_GCM>);\n  BOOST_CHECK_EQUAL(32, IV_SIZE<CryptoMethod::AES_256_GCM>);\n  BOOST_CHECK_EQUAL(32, IV_SIZE<CryptoMethod::CHACHA20_IETF_POLY1305>);\n  BOOST_CHECK_EQUAL(32, IV_SIZE<CryptoMethod::XCHACHA20_IETF_POLY1305>);\n}\n\nBOOST_AUTO_TEST_CASE(NONCE_SIZE_Test)\n{\n  BOOST_CHECK_EQUAL(12, NONCE_SIZE<CryptoMethod::AES_128_GCM>);\n  BOOST_CHECK_EQUAL(12, NONCE_SIZE<CryptoMethod::AES_192_GCM>);\n  BOOST_CHECK_EQUAL(12, NONCE_SIZE<CryptoMethod::AES_256_GCM>);\n  BOOST_CHECK_EQUAL(12, NONCE_SIZE<CryptoMethod::CHACHA20_IETF_POLY1305>);\n  BOOST_CHECK_EQUAL(24, NONCE_SIZE<CryptoMethod::XCHACHA20_IETF_POLY1305>);\n}\n\nBOOST_AUTO_TEST_CASE(TAG_SIZE_Test)\n{\n  BOOST_CHECK_EQUAL(16, TAG_SIZE<CryptoMethod::AES_128_GCM>);\n  BOOST_CHECK_EQUAL(16, TAG_SIZE<CryptoMethod::AES_192_GCM>);\n  BOOST_CHECK_EQUAL(16, TAG_SIZE<CryptoMethod::AES_256_GCM>);\n  BOOST_CHECK_EQUAL(16, TAG_SIZE<CryptoMethod::CHACHA20_IETF_POLY1305>);\n  BOOST_CHECK_EQUAL(16, TAG_SIZE<CryptoMethod::XCHACHA20_IETF_POLY1305>);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "de653917415a27b542e2323a541973123ad84f82", "size": 3430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/method.cpp", "max_stars_repo_name": "0xflotus/pichi", "max_stars_repo_head_hexsha": "5463f4a0e170452aa305fd8a3de3118d6674db46", "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": "test/method.cpp", "max_issues_repo_name": "0xflotus/pichi", "max_issues_repo_head_hexsha": "5463f4a0e170452aa305fd8a3de3118d6674db46", "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/method.cpp", "max_forks_repo_name": "0xflotus/pichi", "max_forks_repo_head_hexsha": "5463f4a0e170452aa305fd8a3de3118d6674db46", "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": 46.3513513514, "max_line_length": 75, "alphanum_fraction": 0.8119533528, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17513091514518675}}
{"text": "/*\n * vector_filterMain.c\n *\n *  Created on: Nov 12, 2013\n *      Author: hxin\n */\n\n//#ifndef BOOST_PP_IS_ITERATING\n//#include \"print.h\"\n#include <stdint.h>\n#include \"vector_filter.h\"\n#include <stdio.h>\n#include <string.h>\n#include <nmmintrin.h>\n#include <emmintrin.h>\n\n#include \"mask.h\"\n/*\n #include <boost/preprocessor/repetition.hpp>\n #include <boost/preprocessor/iteration.hpp>\n #include <boost/preprocessor/arithmetic.hpp>\n #include <boost/preprocessor/punctuation/comma_if.hpp>\n\n #define SSE_BIT_LENGTH\t\t128\n #define BASE_SIZE\t\t\t2\n #define SSE_BASE_NUM\t\tBOOST_PP_DIV(SSE_BIT_LENGTH, BASE_SIZE)\n #define BYTE_BASE_NUM\t\tBOOST_PP_DIV(8, BASE_SIZE)\n #define SSE_BYTE_NUM\t\tBOOST_PP_DIV(SSE_BIT_LENGTH, 8)\n\n uint8_t MASK_SSE_END[SSE_BIT_LENGTH * SSE_BYTE_NUM / BASE_SIZE] = {\n\n #define BOOST_PP_ITERATION_LIMITS\t(0, SSE_BIT_LENGTH / 2  - 1)\n #define BOOST_PP_FILENAME_1\t\t\t\"vector_filterMain.c\" // this file\n #include BOOST_PP_ITERATE()\n\n #else // BOOST_PP_IS_ITERATING\n\n #define I\t\tBOOST_PP_ITERATION()\n #define PRINT_DATA(z, n, data) data\n\n #define FF_NUM\tBOOST_PP_DIV(I, BYTE_BASE_NUM)\n BOOST_PP_ENUM(FF_NUM, PRINT_DATA, 0xff)\n\n #if\t\tFF_NUM != 0\n BOOST_PP_COMMA()\n #endif\t//FF_NUM != 0\n\n #if\t\tBOOST_PP_MOD(I, BYTE_BASE_NUM) == 1\n 0x03\n #elif\tBOOST_PP_MOD(I, BYTE_BASE_NUM) == 2\n 0x0f\n #elif\tBOOST_PP_MOD(I, BYTE_BASE_NUM) == 3\n 0x3f\n #else\n 0x00\n #endif\t//End of switch\n\n #define ZZ_NUM\tBOOST_PP_SUB( BOOST_PP_SUB(SSE_BYTE_NUM, 1), FF_NUM)\n\n #if\t\tZZ_NUM != 0\n BOOST_PP_COMMA()\n #endif\t//ZZ_NUM != 0\n\n BOOST_PP_ENUM(ZZ_NUM, PRINT_DATA, 0x00)\n\n #if I != BOOST_PP_ITERATION_FINISH()\n BOOST_PP_COMMA()\n #endif // I != BOOST_PP_ITERATION_FINISH()\n\n #undef\tFF_NUM\n #undef\tZZ_NUM\n #undef\tI\n #undef\tPRINT_DATA\n\n #endif // BOOST_PP_IS_ITERATING\n #ifndef BOOST_PP_IS_ITERATING\n };\n\n */\n\n#define _MAX_LENGTH_ 320\n\nchar read_t[_MAX_LENGTH_] __aligned__;\nchar ref_t[_MAX_LENGTH_] __aligned__;\n\n//uint8_t read_bit_t[_MAX_LENGTH_ / 4] __aligned__;\n//uint8_t ref_bit_t[_MAX_LENGTH_ / 4] __aligned__;\n\nint main(int argc, char* argv[]) {\n\n\tint length = 128;\n\tint error = 0;\n\tint repeat_count = 10000;\n\tint average_loc = 10;\n\n\tstrcpy(read_t,\n\t\t\t\"AAAAAAAAAAAAAGACTAACCACCTTGTCCTGTTGTCTGTCTGGTCAGCCAATCATTGGGACCACACACCCCAGCATCGTGGACTGCGTGCTGAAGGTGC\");\n//\t\t\t\"TCGCTAGTAGCCGGAACTAACAGGTAGGCCTACATCAGCTATACGGCATCGGCAACCTTGAGGGGCCGCGCCCCGTTACACTTTATACGTTTCCCTTGCAAGCCTTCGTGTCGGAGCATATGTATATG\");\n//\t\t\t\"TCGCTAGTAGCCGGAACTAACAGGTAGGCCTCATCAGCTATACGGCTTCGGCAACCTTGAGGGGCCGCGCCCCGTTACCCTTTATACGTTTCCCGGGCAAGCCTTCGTGTGGGAGCATATGTATATGG\");\n//\t\t\t\"TCGCTAGTAGCCGGAACTAACAGGTAGGCCTACATCAGCTATACGGCATCGGCAACCTTGAGTGGCCGCGGCCCGTTACACTTTATACGTTATCCCTTGCAAGCCTTCGTGTCGGAGCATATGTATATG\");\n\tstrcpy(ref_t,\n\t\t\t\"AAAAAAAAAAAAAGACTAACCACCTTGTCCTGTTGTCTGTCTGGTCAGCCAATCATTGGGACCACACACCCCAGCATGGTGGACTGCGTGCTGAAGGGGC\");\n//\t\t\t\"TCGCTAGTAGCCGGAACTAACAGGTAGGCCTACATCAGCTATACGGCCGTCGGCAACCTTGAGGGGTCGCGCCCCGTTACACTTTATACGTTTACCATTGCAAGCCTTCGTGTCGGAGCATATGTATA\");\n//\t\t\t\"TCGCTAGTAGCCGGAACTAACAGGTAGGCCT ACATCAGCTATACGGCATCGGCAACCTTGAGGGGCCGCGCCCCGTTACACTTTATACGTTTCCCTTGCAAGCCTTCGTGTCGGAGCATATGTATATG\");\n//\t\t\t\"TCGCTAGTTAGCCGGACCTAAAGGTAGGCCTACATCAGCTATACGGCATCGGCAACCTTGAGGGGCCGCGCCCCGTTACACTTTATACGTCTCCCTTGCAAGCCTTCGTGTCGGAGCATATGTATATGG\");\n\n\tif (argc >= 2)\n\t\tlength = atoi(argv[1]);\n\tif (argc >= 3)\n\t\terror = atoi(argv[2]);\n\tif (argc >= 4)\n\t\trepeat_count = atoi(argv[3]);\n\tif (argc >= 5)\n\t\taverage_loc = atoi(argv[4]);\n\n//\tfor (int i = 0; i < SSE_BIT_LENGTH * SSE_BYTE_NUM / BASE_SIZE1; i++) {\n//\t\tif (i % SSE_BYTE_NUM == 0)\n//\t\t\tprintf(\"\\n\");\n//\t\tprintf(\"%x \", MASK_SSE_END1[i]);\n//\t}\n\n//\tif (read_t[repeat_count] = 'A')\n//\t\tread_t[repeat_count] = 'C';\n//\telse\n//\t\tread_t[repeat_count] = 'A';\n\n//\t\tprintf(\"\\n\");\n\n//\twhile (repeat_count--)\n//\t\tbit_vec_filter_sse_simulate11(read_t, ref_t, length, error, average_loc);\n//\twhile (repeat_count--)\n//\t\tbit_vec_filter_sse_simulate1(read_t, ref_t, length, error, average_loc);\n//\tif (bit_vec_filter_sse11(read_t, ref_t, length, error))\n//\t\tprintf(\"Pass Filter\\n\");\n//\telse\n//\t\tprintf(\"Fail Filter\\n\");\n//\n\t\n\tif (bit_vec_filter_sse1(read_t, ref_t, length, error))\n\t\tprintf(\"Pass Filter\\n\");\n\telse\n\t\tprintf(\"Fail Filter\\n\");\n\t\n//\tstrcpy(read_t,\n//\t\t\t\"TCGCTAGTAGCCGGAACTAACAGGTAGGCCTACATCAGCTATACGGCATCGGCAACCTTGAGGGGCCGCGCCCCGTTACACTTTATACGTTTCCCTTGCAAGCCTTCGTGTCGGAGCATATGTATATG\");\n////\t\t\t\"TCGCTAGTAGCCGGAACTAACAGGTAGGCCTACATCAGCTATACGGCATCGGCAACCTTGAGGGGCCGCGCCCCGTTACACTTTATACGTTTCCCTTGCAAGCCTTCGTGTCGGAGCATATGTATATGG\");\n//\tstrcpy(ref_t,\n//\t\t\t\"TCGCTAGTAGCCGGAACTAACAGGTAGGCCTACATCAGCTATACGGCCGTCGGCAACCTTGAGGGGTCGCGCCCCGTTACACTTTATACGTTTACCATTGCAAGCCTTCGTGTCGGAGCATATGTATA\");\n////\t\t\t\"TCGCTAGTTAGCCGGACCTAAAGGTAGGCCTACATCAGCTATACGGCATCGGCAACCTTGAGGGGCCGCGCCCCGTTACACTTTATACGTTTCCCTTGCAAGCCTTCGTGTCGGAGCATATGTATATGG\");\n//\t\n//\tif (bit_vec_filter_no_flipping_sse1(read_t, ref_t, length, error))\n//\t\tprintf(\"Pass Filter\\n\");\n//\telse\n//\t\tprintf(\"Fail Filter\\n\");\n\n\treturn 0;\n\n}\n\n//#endif\n", "meta": {"hexsha": "e0260617a246c519ef1dd88e533b2d088a28d06c", "size": 4874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vector_filterMain.cpp", "max_stars_repo_name": "nahmedraja/gase-gasal2", "max_stars_repo_head_hexsha": "0fda5cc307dee6a0da87fdcb7d9300ca54be72e6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-02-27T09:53:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-13T06:49:04.000Z", "max_issues_repo_path": "src/vector_filterMain.cpp", "max_issues_repo_name": "nahmedraja/GASE", "max_issues_repo_head_hexsha": "7c3f66a29bfc178daf54e0afd131252d61e3f008", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T20:11:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T20:11:13.000Z", "max_forks_repo_path": "src/vector_filterMain.cpp", "max_forks_repo_name": "nahmedraja/GASE", "max_forks_repo_head_hexsha": "7c3f66a29bfc178daf54e0afd131252d61e3f008", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-20T09:39:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-20T09:39:23.000Z", "avg_line_length": 30.2732919255, "max_line_length": 140, "alphanum_fraction": 0.7722609766, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1751309136433375}}
{"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#ifndef FILECOIN_STORAGE_PROOFS_POREP_STACKED_VANILLA_PARAMS_HPP\n#define FILECOIN_STORAGE_PROOFS_POREP_STACKED_VANILLA_PARAMS_HPP\n\n#include <array>\n#include <string>\n\n#include <boost/filesystem/path.hpp>\n#include <boost/log/trivial.hpp>\n\n#include <nil/crypto3/hash/sha2.hpp>\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/challenges.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/column_proof.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/labelling_proof.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/encoding_proof.hpp>\n\n#include <nil/filecoin/storage/proofs/core/merkle/proof.hpp>\n#include <nil/filecoin/storage/proofs/core/merkle/builders.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        namespace stacked {\n            namespace vanilla {\n\n                /*************************  Pre-defined values  ***********************************/\n\n                constexpr static const std::size_t BINARY_ARITY = 2;\n                constexpr static const std::size_t QUAD_ARITY = 4;\n                constexpr static const std::size_t OCT_ARITY = 8;\n\n                /*************************  SetupParams  ***********************************/\n\n                struct SetupParams {\n                    // Number of nodes\n                    std::size_t nodes;\n\n                    // Base degree of DRG\n                    std::size_t degree;\n\n                    std::size_t expansion_degree;\n\n                    std::array<std::uint8_t, 32> porep_id;\n                    LayerChallenges layer_challenges;\n                };\n\n                /*************************  PublicParams  ***********************************/\n\n                template<typename MerkleTreeType>\n                struct PublicParams {\n                    typedef MerkleTreeType tree_type;\n                    typedef typename tree_type::hash_type hash_type;\n\n                    std::string identifier() {\n                        return std::string(\"layered_drgporep::PublicParams{{ graph:\") +\n                               std::to_string(graph.identifier()) +\n                               \", challenges: \" + std::to_string(layer_challenges) +\n                               \", tree: \" + std::to_string(MerkleTreeType::display()) + \"}}\";\n                    }\n\n                    StackedBucketGraph<hash_type> graph;\n                    LayerChallenges layer_challenges;\n                };\n\n                /*************************  Tau  ***********************************/\n\n                /// Tau for a single parition.\n                template<typename DDomain, typename EDomain>\n                struct Tau {\n                    EDomain comm_d;\n                    DDomain comm_r;\n                };\n\n                /*************************  PersistentAux  ***********************************/\n\n                /// Stored along side the sector on disk.\n                template<typename D>\n                struct PersistentAux {\n                    D comm_c;\n                    D comm_r_last;\n                };\n\n                /*************************  ???  ***********************************/\n\n                typedef std::function<void(const StoreConfig &, std::size_t, std::size_t)> VerifyCallback;\n\n                /*************************  Labels  ***********************************/\n\n                template<typename MerkleTreeType>\n                struct Labels {\n                    Labels(const std::vector<StoreConfig> &labels) : labels(labels) {\n                    }\n\n                    void verify_stores(VerifyCallback callback, const boost::filesystem::path &cache_dir) {\n                        std::vector<StoreConfig> updated_path_labels = labels;\n                        std::size_t required_configs = get_base_tree_count<MerkleTreeType>();\n                        for (const auto &label : updated_path_labels) {\n                            label.path = cache_dir;\n                            callback(label, BINARY_ARITY, required_configs);\n                        }\n                    }\n\n                    DiskStore<typename MerkleTreeType::hash_type::digest_type> labels_for_layer(std::size_t layer) {\n                        BOOST_ASSERT_MSG(layer != 0, \"Layer cannot be 0\");\n                        BOOST_ASSERT_MSG(\n                            layer <= layers(),\n                            std::format(\"Layer {%d} is not available (only {%d} layers available)\", layer, layers()));\n\n                        std::size_t row_index = layer - 1;\n                        StoreConfig config = labels[row_index];\n                        assert(config.size.is_some());\n\n                        DiskStore::new_from_disk(config.size, MerkleTreeType::base_arity, config);\n                    }\n\n                    /// Returns label for the last layer.\n                    DiskStore<typename MerkleTreeType::hash_type::digest_type> labels_for_last_layer() {\n                        return labels_for_layer(labels.size() - 1);\n                    }\n\n                    /// How many layers are available.\n                    std::size_t layers() const {\n                        return labels.size();\n                    }\n\n                    /// Build the column for the given node.\n                    Column<typename MerkleTreeType::hash_type> column(std::uint32_t node) {\n                        std::vector<typename MerkleTreeType::hash_type::digest_type> rows;\n\n                        for (const auto &label : labels) {\n                            assert(label.size());\n                            DiskStore store = DiskStore::new_from_disk(label.size, MerkleTreeType::base_arity, label);\n                            rows.push_back(store.read_at(node));\n                        }\n\n                        return Column<typename MerkleTreeType::hash_type>(node, rows);\n                    }\n\n                    /// Update all configs to the new passed in root cache path.\n                    void update_root(const boost::filesystem::path &root) {\n                        for (const auto &config : labels) {\n                            config.path = root;\n                        }\n                    }\n\n                    std::vector<StoreConfig> labels;\n                };\n\n                /*************************  TemporaryAux  ***********************************/\n\n                template<typename MerkleTreeType, typename Hash>\n                struct TemporaryAux {\n                    void set_cache_path(const boost::filesystem::path &cache_path) {\n                        for (labels::iterator label = labels.begin(); label != labels.end(); ++label) {\n                            (*label).path = cache_path;\n                        }\n                        tree_d_config.path = cache_path;\n                        tree_r_last_config.path = cache_path;\n                        tree_c_config.path = cache_path;\n                    }\n\n                    DiskStore<typename MerkleTreeType::hash_type::digest_type> labels_for_layer(std::size_t layer) {\n                        return labels.labels_for_layer(layer);\n                    }\n\n                    typename MerkleTreeType::hash_type::digest_type domain_node_at_layer(std::size_t layer,\n                                                                                         std::uint32_t node_index) {\n                        return labels_for_layer(layer).read_at(node_index);\n                    }\n\n                    Column<typename MerkleTreeType::hash_type> column(std::uint32_t column_index) {\n                        return labels.column(column_index);\n                    }\n\n                    // 'clear_temp' will discard all persisted merkle and layer data\n                    // that is no longer required.\n                    void clear_temp(TemporaryAux<MerkleTreeType, Hash> t_aux) {\n\n                        const auto delete_tree_c_store = [&](const StoreConfig &config, std::size_t tree_c_size) {\n                            DiskStore<typename MerkleTreeType::hash_type::digest_type> tree_c_store =\n                                DiskStore<typename MerkleTreeType::hash_type::digest_type>::new_from_disk(\n                                    tree_c_size, MerkleTreeType::base_arity, config);\n                            // Note: from_data_store requires the base tree leaf count\n                            DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                     MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>\n                                tree_c = DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                                  MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>::\n                                    from_data_store(tree_c_store,\n                                                    get_merkle_tree_leafs(tree_c_size, MerkleTreeType::base_arity));\n                            tree_c.erase(config.clone());\n                        };\n\n                        if (is_cached(&t_aux.tree_d_config)) {\n                            std::size_t tree_d_size = t_aux.tree_d_config.size.context(\"tree_d config has no size\");\n                            DiskStore<typename Hash::digest_type> tree_d_store =\n                                DiskStore::new_from_disk(tree_d_size, BINARY_ARITY, &t_aux.tree_d_config)\n                                    .context(\"tree_d\");\n                            // Note: from_data_store requires the base tree leaf count\n                            BinaryMerkleTree<Hash> tree_d = BinaryMerkleTree<Hash>::from_data_store(\n                                tree_d_store, get_merkle_tree_leafs(tree_d_size, BINARY_ARITY));\n\n                            tree_d.erase(t_aux.tree_d_config);\n                            BOOST_LOG_TRIVIAL(trace) << \"tree d deleted\";\n                        }\n\n                        std::size_t tree_count = get_base_tree_count<MerkleTreeType>();\n                        std::size_t tree_c_size = t_aux.tree_c_config.size;\n                        const auto configs = split_config(t_aux.tree_c_config.clone(), tree_count);\n\n                        if (is_cached(&t_aux.tree_c_config)) {\n                            delete_tree_c_store(&t_aux.tree_c_config, tree_c_size);\n                        } else if (is_cached(configs[0])) {\n                            for (configs::const_iterator config = configs.begin(); config != configs.end(); ++config) {\n                                // Trees with sub-trees cannot be instantiated and deleted via the existing tree\n                                // interface since knowledge of how the base trees are split exists outside of merkle\n                                // light.  For now, we manually remove each on disk tree file since we know where they\n                                // are here.\n                                boost::filesystem::path tree_c_path = StoreConfig::data_path(config->path, config->id);\n                                boost::filesystem::remove(tree_c_path);\n                            }\n                        }\n                        BOOST_LOG_TRIVIAL(trace) << \"tree c deleted\";\n\n                        for (int i = 0; i < t_aux.labels.labels.size(); i++) {\n                            StoreConfig cur_config = t_aux.labels.labels[i].clone();\n                            if (is_cached(cur_config)) {\n                                DiskStore<typename MerkleTreeType::hash_type::digest_type>::delete (cur_config)\n                                    .with_context(|| std::format(\"labels %d\", i));\n                                BOOST_LOG_TRIVIAL(trace) << std::format(\"layer %d deleted\", i);\n                            }\n                        }\n                    }\n\n                    Labels<MerkleTreeType> labels;\n                    StoreConfig tree_d_config;\n                    StoreConfig tree_r_last_config;\n                    StoreConfig tree_c_config;\n\n                private:\n                    bool is_cached(const StoreConfig &config) {\n                        return boost::filesystem::exists(\n                            boost::filesystem::path(StoreConfig::data_path(config.path, config.id)));\n                    };\n                };\n\n                /*************************  PublicInputs  ***********************************/\n\n                template<typename T, typename S>\n                struct PublicInputs {\n                    typedef Tau<T, S> tau_type;\n                    typedef std::size_t challenge_type;\n\n                    std::vector<std::size_t> challenges(const LayerChallenges &layer_challenges, std::size_t leaves,\n                                                        std::size_t partition_k = 0) {\n                        k = partition_k;\n                        return layer_challenges.derive<T>(leaves, replica_id, seed, k);\n                    }\n\n                    T replica_id;\n\n                    std::array<std::uint8_t, 32> seed;\n\n                    Tau<T, S> tau;\n\n                    /// Partition index\n                    std::size_t k;\n                };\n\n                /*************************  LabelsCache  ***********************************/\n\n                template<typename MerkleTreeType>\n                struct LabelsCache {\n                    typedef MerkleTreeType tree_type;\n                    typedef typename tree_type::hash_type tree_hash_type;\n\n                    LabelsCache(const Labels<MerkleTreeType> &labels) {\n                        std::vector<DiskStore<typename tree_hash_type::digest_type>> disk_store_labels(labels.size());\n                        for (int i = 0; i < labels.size(); i++) {\n                            disk_store_labels.emplace_back(labels.labels_for_layer(i + 1));\n                        }\n\n                        return {disk_store_labels};\n                    }\n\n                    std::size_t size() {\n                        return labels.size();\n                    }\n\n                    bool empty() {\n                        return labels.empty();\n                    }\n\n                    const DiskStore<typename tree_hash_type::digest_type> &labels_for_layer(std::size_t layer) {\n                        BOOST_ASSERT_MSG(layer != 0, \"Layer cannot be 0\");\n                        assert(layer <= layers());\n\n                        std::size_t row_index = layer - 1;\n                        return labels[row_index];\n                    }\n\n                    /// Returns the labels on the last layer.\n                    const DiskStore<typename tree_hash_type::digest_type> &labels_for_last_layer() {\n                        return labels[labels.size() - 1];\n                    }\n\n                    /// How many layers are available.\n                    std::size_t layers() {\n                        return labels.size();\n                    }\n\n                    /// Build the column for the given node.\n                    Column<typename MerkleTreeType::hash_type> column(std::uint32_t node) {\n                        std::vector<typename MerkleTreeType::hash_type::digest_type> rows;\n\n                        for (const DiskStore<typename MerkleTreeType::hash_type::digest_type> &l : labels) {\n                            rows.push_back(l.read_at(node));\n                        }\n\n                        return {node, rows};\n                    }\n\n                    std::vector<DiskStore<typename MerkleTreeType::hash_type::digest_type>> labels;\n                };\n\n                /*************************  TemporaryAuxCache  ***********************************/\n\n                template<typename MerkleTreeType, typename Hash>\n                struct TemporaryAuxCache {\n                    typedef MerkleTreeType tree_type;\n                    typedef Hash hash_type;\n\n                    typedef typename tree_type::hash_type tree_hash_type;\n\n                    /// The encoded nodes for 1..layers.\n                    LabelsCache<tree_type> labels;\n                    BinaryMerkleTree<hash_type> tree_d;\n\n                    // Notably this is a LevelCacheTree instead of a full merkle.\n                    LCTree<typename tree_type::hash_type, typename tree_type::Arity, typename tree_type::SubTreeArity,\n                           typename tree_type::TopTreeArity>\n                        tree_r_last;\n\n                    // Store the 'rows_to_discard' value from the tree_r_last\n                    // StoreConfig for later use (i.e. proof generation).\n                    std::size_t tree_r_last_config_rows_to_discard;\n\n                    DiskTree<tree_hash_type, typename tree_type::Arity, typename tree_type::SubTreeArity,\n                             typename tree_type::TopTreeArity>\n                        tree_c;\n                    TemporaryAux<tree_type, hash_type> t_aux;\n                    boost::filesystem::path replica_path;\n\n                    TemporaryAuxCache(const TemporaryAux<tree_type, hash_type> &t_aux,\n                                      const boost::filesystem::path &replica_path) {\n                        // tree_d_size stored in the config is the base tree size\n                        std::size_t tree_d_size = t_aux.tree_d_config.size();\n                        std::size_t tree_d_leafs = get_merkle_tree_leafs(tree_d_size, BINARY_ARITY);\n                        BOOST_LOG_TRIVIAL(trace)\n                            << std::format(\"Instantiating tree d with size {} and leafs {}\", tree_d_size, tree_d_leafs);\n                        DiskStore<typename Hash::digest_type> tree_d_store =\n                            DiskStore::new_from_disk(tree_d_size, BINARY_ARITY, &t_aux.tree_d_config)\n                                .context(\"tree_d_store\");\n                        BinaryMerkleTree<hash_type> tree_d =\n                            BinaryMerkleTree<Hash>::from_data_store(tree_d_store, tree_d_leafs).context(\"tree_d\");\n\n                        std::size_t tree_count = get_base_tree_count<MerkleTreeType>();\n                        std::vector<StoreConfig> configs = split_config(t_aux.tree_c_config.clone(), tree_count);\n\n                        // tree_c_size stored in the config is the base tree size\n                        std::size_t tree_c_size = t_aux.tree_c_config.size;\n                        BOOST_LOG_TRIVIAL(trace)\n                            << std::format(\"Instantiating tree c [count {}] with size {} and arity {}\", tree_count,\n                                           tree_c_size, MerkleTreeType::base_arity);\n                        DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                 MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>\n                            tree_c = create_disk_tree<\n                                DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                         MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>>(tree_c_size,\n                                                                                                          configs);\n\n                        // tree_r_last_size stored in the config is the base tree size\n                        std::size_t tree_r_last_size = t_aux.tree_r_last_config.size;\n                        std::size_t tree_r_last_config_rows_to_discard = t_aux.tree_r_last_config.rows_to_discard;\n                        const auto(configs, replica_config) = split_config_and_replica(\n                            t_aux.tree_r_last_config,\n                            replica_path,\n                            get_merkle_tree_leafs(tree_r_last_size, MerkleTreeType::base_arity),\n                            tree_count);\n\n                        BOOST_LOG_TRIVIAL(trace)\n                            << std::format(\"Instantiating tree r last [count {}] with size {} and arity {}, {}, {}\",\n                                           tree_count, tree_r_last_size, MerkleTreeType::base_arity,\n                                           MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity);\n                        LCTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                               MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>\n                            tree_r_last =\n                                create_lc_tree<LCTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                                      MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>>(\n                                    tree_r_last_size, configs, replica_config);\n\n                        return {{t_aux.labels.context(\"labels_cache\")},\n                                tree_d,\n                                tree_r_last,\n                                tree_r_last_config_rows_to_discard,\n                                tree_c,\n                                replica_path,\n                                t_aux};\n                    }\n\n                    DiskStore<typename MerkleTreeType::hash_type::digest_type> &labels_for_layer(std::size_t layer) {\n                        return labels.labels_for_layer(layer);\n                    }\n\n                    typename MerkleTreeType::hash_type::digest_type domain_node_at_layer(std::size_t layer,\n                                                                                         std::uint32_t node_index) {\n                        return labels_for_layer(layer).read_at(node_index);\n                    }\n\n                    Column<typename MerkleTreeType::hash_type> column(std::uint32_t column_index) {\n                        return labels.column(column_index);\n                    }\n                };\n\n                /*************************  PrivateInputs  ***********************************/\n\n                template<typename MerkleTreeType, typename Hash>\n                struct PrivateInputs {\n                    PersistentAux<typename MerkleTreeType::hash_type::digest_type> p_aux;\n                    TemporaryAuxCache<MerkleTreeType, Hash> t_aux;\n                };\n\n                /*************************  Proof  ***********************************/\n\n                template<typename MerkleTreeType, typename Hash>\n                struct Proof {\n                    typedef Hash hash_type;\n                    typedef MerkleTreeType tree_type;\n                    typedef typename tree_type::hash_type tree_hash_type;\n\n                    MerkleProof<hash_type, MerkleTreeType::base_arity, MerkleTreeType::sub_tree_arity,\n                                MerkleTreeType::top_tree_arity>\n                        comm_d_proofs;\n                    MerkleProof<tree_hash_type, MerkleTreeType::base_arity, MerkleTreeType::sub_tree_arity,\n                                MerkleTreeType::top_tree_arity>\n                        comm_r_last_proof;\n                    ReplicaColumnProof<MerkleProof<tree_hash_type, MerkleTreeType::base_arity,\n                                                   MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>>\n                        replica_column_proofs;\n\n                    /// Indexed by layer in 1..layers.\n                    std::vector<LabelingProof<typename MerkleTreeType::hash_type>> labeling_proofs;\n                    EncodingProof<typename MerkleTreeType::hash_type> encoding_proof;\n                };\n\n                /*************************  ReplicaColumnProof  ***********************************/\n\n                template<typename MerkleProofType>\n                struct ReplicaColumnProof {\n                    typedef MerkleProofType proof_type;\n\n                    ColumnProof<proof_type> c_x;\n                    std::vector<ColumnProof<proof_type>> drg_parents;\n                    std::vector<ColumnProof<proof_type>> exp_parents;\n                };\n\n                /*************************  TransformedLayers  ***********************************/\n\n                template<typename MerkleTreeType, typename Hash>\n                using TransformedLayers =\n                    std::tuple<Tau<typename MerkleTreeType::hash_type::digest_type, typename Hash::digest_type>,\n                               PersistentAux<typename MerkleTreeType::hash_type::digest_type>,\n                               TemporaryAux<MerkleTreeType, Hash>>;\n\n                /*************************  ???  ***********************************/\n\n                template<typename Hash, typename InputDataRange>\n                typename Hash::digest_type get_node(const InputDataRange &data, std::size_t index) {\n                    return Hash::digest_type::try_from_bytes(data_at_node(data, index));\n                }\n\n                /// Generate the replica id as expected for Stacked DRG.\n                template<typename InputDataRange, typename Hash = crypto3::hashes::sha2<256>>\n                typename Hash::digest_type\n                    generate_replica_id(const std::array<std::uint8_t, 32> &prover_id, std::uint64_t sector_id,\n                                        const std::array<std::uint8_t, 32> &ticket, const InputDataRange &comm_d,\n                                        const std::array<std::uint8_t, 32> &porep_seed) {\n                    using namespace nil::crypto3;\n\n                    accumulator_set<Hash> acc;\n\n                    hash<Hash>(prover_id, acc);\n                    hash<Hash>(sector_id, acc);\n                    hash<Hash>(ticket, acc);\n                    hash<Hash>(comm_d, acc);\n                    hash<Hash>(porep_seed, acc);\n\n                    return accumulators::extract::hash<Hash>(acc);\n                }\n            }    // namespace vanilla\n        }        // namespace stacked\n    }            // namespace filecoin\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "4c4f2225fbbeca96d708b70d0892bc61bb0daff1", "size": 27362, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/porep/stacked/vanilla/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/porep/stacked/vanilla/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/porep/stacked/vanilla/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": 51.5291902072, "max_line_length": 120, "alphanum_fraction": 0.4936408157, "num_tokens": 4875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.2845759981489974, "lm_q1q2_score": 0.1750392444486577}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include\"Eigen/Dense\"\n#include <vector>\n#include <iostream>\n#include <QString>\n#include <QList>\n#include \"Robot.h\"\n//#include\"TaskSpace.h\"\n#include\"taskspaceofflineRamp.h\"\n#include <qmath.h>\n#include <cstring>\n#include<qdebug.h>\n#include <Eigen/Geometry>\n#include <cstdlib>\n//#include <link.h>\n#include \"Eigen/eiquadprog.h\"\n#include \"Eigen/Core\"\n#include \"Eigen/Cholesky\"\n#include \"Eigen/LU\"\n#include<std_msgs/Int32MultiArray.h>\n#include<std_msgs/Float32MultiArray.h>\n#include<math.h>\n#include<sensor_msgs/Imu.h>\n#include<std_msgs/Float64.h>\n#include \"qcgenerator.h\"\n\n\n\nusing namespace  std;\nusing namespace  Eigen;\n\n\nros::Publisher pub1  ;\nros::Publisher pub2  ;\nros::Publisher pub3  ;\nros::Publisher pub4  ;\nros::Publisher pub5  ;\nros::Publisher pub6  ;\nros::Publisher pub7  ;\nros::Publisher pub8  ;\nros::Publisher pub9  ;\nros::Publisher pub10 ;\nros::Publisher pub11 ;\nros::Publisher pub12 ;\nros::Publisher pub13 ;\nros::Publisher pub14 ;\nros::Publisher pub15 ;\nros::Publisher pub16 ;\nros::Publisher pub17 ;\nros::Publisher pub18 ;\nros::Publisher pub19 ;\nros::Publisher pub20 ;\nros::Publisher pub21 ;\nros::Publisher pub22 ;\nros::Publisher pub23 ;\nros::Publisher pub24 ;\nros::Publisher pub25 ;\nros::Publisher pub26 ;\nros::Publisher pub27 ;\nros::Publisher pub28 ;\n\n//ros::Publisher pid1 ;\n\n\n\n\n\nvoid  SendGazebo(QList<LinkM> links){\n    if(links.count()<28){qDebug()<<\"index err\";return;}\n    std_msgs::Float64 data;\n    data.data=links[1].JointAngle;\n    pub1.publish(data);\n    data.data=links[2].JointAngle;\n    pub2.publish(data);\n    data.data=links[3].JointAngle;\n    pub3.publish(data);\n    data.data=links[4].JointAngle;\n    pub4.publish(data);\n    data.data=links[5].JointAngle;\n    pub5.publish(data);\n    data.data=links[6].JointAngle;\n    pub6.publish(data);\n    data.data=links[7].JointAngle;\n    pub7.publish(data);\n    data.data=links[8].JointAngle;\n    pub8.publish(data);\n    data.data=links[9].JointAngle;\n    pub9.publish(data);\n    data.data=links[10].JointAngle;\n    pub10.publish(data);\n    data.data=links[11].JointAngle;\n    pub11.publish(data);\n    data.data=links[12].JointAngle;\n    pub12.publish(data);\n    data.data=links[13].JointAngle;\n    pub13.publish(data);\n    data.data=links[14].JointAngle;\n    pub14.publish(data);\n    data.data=links[15].JointAngle;\n    pub15.publish(data);\n    data.data=links[16].JointAngle;\n    pub16.publish(data);\n    data.data=links[17].JointAngle;\n    pub17.publish(data);\n    data.data=links[18].JointAngle;\n    pub18.publish(data);\n    data.data=links[19].JointAngle;\n    pub19.publish(data);\n    data.data=links[20].JointAngle;\n    pub20.publish(data);\n    data.data=links[21].JointAngle;\n    pub21.publish(data);\n    data.data=links[22].JointAngle;\n    pub22.publish(data);\n    data.data=links[23].JointAngle;\n    pub23.publish(data);\n    data.data=links[24].JointAngle;\n    pub24.publish(data);\n    data.data=links[25].JointAngle;\n    pub25.publish(data);\n    data.data=links[26].JointAngle;\n    pub26.publish(data);\n    data.data=links[27].JointAngle;\n    pub27.publish(data);\n    data.data=links[28].JointAngle;\n    pub28.publish(data);\n\n\n\n}\n\n\n\n\n\n\nint main(int argc, char **argv)\n{\n    vector<double> cntrl(13);\n    QCgenerator QC;\n    //check _timesteps\n    QElapsedTimer timer;\n    Robot SURENA;\n    TaskSpaceOfflineRamp SURENAOffilneTaskSpaceRamp;\n    QList<LinkM> links;\n    MatrixXd PoseRoot;\n    MatrixXd PoseRFoot;\n    MatrixXd PoseLFoot;\n    double dt;\n\n    double k1;\n    double k2;\n    double k3;\n    double k4;\n\n    bool aState=false;\n    bool bState=false;\n    bool cState=false;\n    bool dState=false;\n    bool LeftFootLanded=false;\n\n    double teta_motor_L=0;\n    double teta_motor_R=0;\n    double phi_motor_L=0;\n    double phi_motor_R=0;\n\n    int numberOfLeftFootSensorData=0;\n    double footSensorSaturation=90;//if all sensors data are bigger than this amount, this means the foot is landed on the ground\n    double footSensorthreshold=4;\n    double hipRoll=0;\n    double StartTime=0;\n    double WalkTime=0;\n    double RollTime=0;\n    double  DurationOfStartPhase=6;\n    double  DurationOfendPhase=6;\n    //SURENAOffilneTaskSpaceRamp.GetAccVelPos();\n    bool startPhase=true;\n    bool endPhase=true;\n    bool walk=true;\n    PoseRoot.resize(6,1);\n    PoseRFoot.resize(6,1);\n    PoseLFoot.resize(6,1);\n\n    //*******************This part of code is for initialization of joints of the robot for walking**********************************\n    int count = 0;\n\n    ros::init(argc, argv, \"myNode\");\n\n    ros::NodeHandle nh;\n    ros::Publisher  chatter_pub  = nh.advertise<std_msgs::Int32MultiArray>(\"jointdata/qc\",1000);\n\n    //ros::Subscriber sub = nh.subscribe(\"/foot\", 1000, receiveFootSensor);\n\n    pub1  = nh.advertise<std_msgs::Float64>(\"rrbot/joint1_position_controller/command\",1000);\n    pub2  = nh.advertise<std_msgs::Float64>(\"rrbot/joint2_position_controller/command\",1000);\n    pub3  = nh.advertise<std_msgs::Float64>(\"rrbot/joint3_position_controller/command\",1000);\n    pub4  = nh.advertise<std_msgs::Float64>(\"rrbot/joint4_position_controller/command\",1000);\n    pub5  = nh.advertise<std_msgs::Float64>(\"rrbot/joint5_position_controller/command\",1000);\n    pub6  = nh.advertise<std_msgs::Float64>(\"rrbot/joint6_position_controller/command\",1000);\n    pub7  = nh.advertise<std_msgs::Float64>(\"rrbot/joint7_position_controller/command\",1000);\n    pub8  = nh.advertise<std_msgs::Float64>(\"rrbot/joint8_position_controller/command\",1000);\n    pub9  = nh.advertise<std_msgs::Float64>(\"rrbot/joint9_position_controller/command\",1000);\n    pub10 = nh.advertise<std_msgs::Float64>(\"rrbot/joint10_position_controller/command\",1000);\n    pub11 = nh.advertise<std_msgs::Float64>(\"rrbot/joint11_position_controller/command\",1000);\n    pub12 = nh.advertise<std_msgs::Float64>(\"rrbot/joint12_position_controller/command\",1000);\n    pub13 = nh.advertise<std_msgs::Float64>(\"rrbot/joint13_position_controller/command\",1000);\n    pub14 = nh.advertise<std_msgs::Float64>(\"rrbot/joint14_position_controller/command\",1000);\n    pub15 = nh.advertise<std_msgs::Float64>(\"rrbot/joint15_position_controller/command\",1000);\n    pub16 = nh.advertise<std_msgs::Float64>(\"rrbot/joint16_position_controller/command\",1000);\n    pub17 = nh.advertise<std_msgs::Float64>(\"rrbot/joint17_position_controller/command\",1000);\n    pub18 = nh.advertise<std_msgs::Float64>(\"rrbot/joint18_position_controller/command\",1000);\n    pub19 = nh.advertise<std_msgs::Float64>(\"rrbot/joint19_position_controller/command\",1000);\n    pub20 = nh.advertise<std_msgs::Float64>(\"rrbot/joint20_position_controller/command\",1000);\n    pub21 = nh.advertise<std_msgs::Float64>(\"rrbot/joint21_position_controller/command\",1000);\n    pub22 = nh.advertise<std_msgs::Float64>(\"rrbot/joint22_position_controller/command\",1000);\n    pub23 = nh.advertise<std_msgs::Float64>(\"rrbot/joint23_position_controller/command\",1000);\n    pub24 = nh.advertise<std_msgs::Float64>(\"rrbot/joint24_position_controller/command\",1000);\n    pub25 = nh.advertise<std_msgs::Float64>(\"rrbot/joint25_position_controller/command\",1000);\n    pub26 = nh.advertise<std_msgs::Float64>(\"rrbot/joint26_position_controller/command\",1000);\n    pub27 = nh.advertise<std_msgs::Float64>(\"rrbot/joint27_position_controller/command\",1000);\n    pub28 = nh.advertise<std_msgs::Float64>(\"rrbot/joint28_position_controller/command\",1000);\n\n    //pid1= nh.advertise<std_msgs::Float64>(\"rrbot/joint28_position_controller/pid/parameter_updates\",1000);\n\n\n\n\n\n    ros::Rate loop_rate(100);\n    std_msgs::Int32MultiArray msg;\n    std_msgs::MultiArrayDimension msg_dim;\n\n    msg_dim.label = \"joint_position\";\n    msg_dim.size = 1;\n    msg.layout.dim.clear();\n    msg.layout.dim.push_back(msg_dim);\n    k1=0.00009;\n    k2=0.00009;\n    k3=0.00001;\n    k4=0.00001;\n\n\n\n    while (ros::ok())\n    {\n        // qDebug()<<StartTime;\n\n\n\n\n\n\n\n\n\n        if (startPhase==true && StartTime<=DurationOfStartPhase) {\n            MinimumJerkInterpolation Coef;\n            MatrixXd ZPosition(1,2);\n            ZPosition<<0.95100,0.8300;\n            MatrixXd ZVelocity(1,2);\n            ZVelocity<<0.000,0.000;\n            MatrixXd ZAcceleration(1,2);\n            ZAcceleration<<0.000,0.000;\n\n\n            MatrixXd Time(1,2);\n            Time<<0,DurationOfStartPhase;\n            MatrixXd CoefZStart =Coef.Coefficient(Time,ZPosition,ZVelocity,ZAcceleration);\n\n\n            double zStart=0;\n            double yStart=0;\n            double xStart=0;\n            StartTime=StartTime+SURENAOffilneTaskSpaceRamp._timeStep;\n\n            MatrixXd outputZStart= SURENAOffilneTaskSpaceRamp.GetAccVelPos(CoefZStart,StartTime,0,5);\n            zStart=outputZStart(0,0);\n\n            PoseRoot<<xStart,yStart,zStart,0,0,0;\n\n            PoseRFoot<<0,\n                    -0.11500,\n                    0.112000,\n                    0,\n                    0,\n                    0;\n\n            PoseLFoot<<0,\n                    0.11500,\n                    0.11200,\n                    0,\n                    0,\n                    0;\n\n            SURENA.doIK(\"LLeg_AnkleR_J6\",PoseLFoot,\"Body\", PoseRoot);\n            SURENA.doIK(\"RLeg_AnkleR_J6\",PoseRFoot,\"Body\", PoseRoot);\n        }\n\n\n\n        if (StartTime>DurationOfStartPhase && StartTime<(DurationOfStartPhase+SURENAOffilneTaskSpaceRamp.MotionTime)){\n\n            bool walk=true;\n            double m1;\n            double m2;\n            double m3;\n            double m4;\n            double m5;\n            double m6;\n            double m7;\n            double m8;\n            StartTime=StartTime+SURENAOffilneTaskSpaceRamp._timeStep;\n            //qDebug()<<StartTime;\n            MatrixXd P;\n            if(walk==true){\n                MatrixXd m=SURENAOffilneTaskSpaceRamp.AnkleTrajectory(SURENAOffilneTaskSpaceRamp.globalTime);\n                m1=m(0,0);\n                m2=m(1,0);\n                m3=m(2,0);\n                m4=m(3,0);\n                m5=m(4,0);\n                m6=m(5,0);\n                m7=m(6,0);\n                m8=m(7,0);\n\n                P=SURENAOffilneTaskSpaceRamp.PelvisTrajectory (SURENAOffilneTaskSpaceRamp.globalTime);\n\n                // just some samples for plotting!!!\n                //                SURENAOffilneTaskSpaceRamp.CoMXVector.append(P(0,0));\n                //                SURENAOffilneTaskSpaceRamp.timeVector.append(SURENAOffilneTaskSpaceRamp.globalTime);\n                //                SURENAOffilneTaskSpaceRamp.LeftFootXTrajectory.append(m1);\n\n\n\n                SURENAOffilneTaskSpaceRamp.globalTime=SURENAOffilneTaskSpaceRamp.globalTime+SURENAOffilneTaskSpaceRamp._timeStep;\n\n                if (round(SURENAOffilneTaskSpaceRamp.globalTime)<=round(SURENAOffilneTaskSpaceRamp.MotionTime)){\n\n\n\n                    //cout<<SURENAOffilneTaskSpaceRamp.TSS<<endl;\n                    //cout<<RollTime<<endl;\n\n                    PoseRoot<<P(0,0),\n                            P(1,0),\n                            P(2,0),\n                            0,\n                            0,\n                            0;\n\n                    PoseRFoot<<m5,\n                            m6,\n                            m7,\n                            0,\n                            1*m8,\n                            0;\n\n                    PoseLFoot<<m1,\n                            m2,\n                            m3,\n                            0,\n                            1*m4,\n                            0;\n\n\n\n\n\n                    SURENA.doIK(\"LLeg_AnkleR_J6\",PoseLFoot,\"Body\", PoseRoot);\n                    SURENA.doIK(\"RLeg_AnkleR_J6\",PoseRFoot,\"Body\", PoseRoot);\n\n                }\n\n            }\n        }\n\n        if (endPhase==true &&  StartTime>=(DurationOfStartPhase+SURENAOffilneTaskSpaceRamp.MotionTime) && StartTime<=DurationOfendPhase+DurationOfStartPhase+SURENAOffilneTaskSpaceRamp.MotionTime) {\n            MinimumJerkInterpolation Coef;\n            MatrixXd ZPosition(1,2);\n            ZPosition<<0.830,0.95100;\n            MatrixXd ZVelocity(1,2);\n            ZVelocity<<0.000,0.000;\n            MatrixXd ZAcceleration(1,2);\n            ZAcceleration<<0.000,0.000;\n\n\n            MatrixXd Time(1,2);\n            Time<<DurationOfStartPhase+SURENAOffilneTaskSpaceRamp.MotionTime,DurationOfStartPhase+SURENAOffilneTaskSpaceRamp.MotionTime+DurationOfendPhase;\n            MatrixXd CoefZStart =Coef.Coefficient(Time,ZPosition,ZVelocity,ZAcceleration);\n\n            double zStart=0;\n            double yStart=0;\n            double xStart=0;\n            StartTime=StartTime+SURENAOffilneTaskSpaceRamp._timeStep;\n\n            MatrixXd outputZStart= SURENAOffilneTaskSpaceRamp.GetAccVelPos(CoefZStart,StartTime,DurationOfStartPhase+SURENAOffilneTaskSpaceRamp.MotionTime,5);\n            zStart=outputZStart(0,0);\n\n            PoseRoot<<xStart,yStart,zStart,0,0,0;\n\n            PoseRFoot<<0,\n                    -0.11500,\n                    0.112000,\n                    0,\n                    0,\n                    0;\n\n            PoseLFoot<<0,\n                    0.11500,\n                    0.11200,\n                    0,\n                    0,\n                    0;\n\n            SURENA.doIK(\"LLeg_AnkleR_J6\",PoseLFoot,\"Body\", PoseRoot);\n            SURENA.doIK(\"RLeg_AnkleR_J6\",PoseRFoot,\"Body\", PoseRoot);\n        }\n        links = SURENA.GetLinks();\n        msg.data.clear();\n\n        //        ROS_INFO(\"I heard motor pitch: [%f]\",teta_motor_L);\n        //        ROS_INFO(\"I heard motor roll: [%f]\",phi_motor_L);\n        msg.data.clear();\n\n\n\n\n                cntrl[0]=0.0;\n                cntrl[1]=links[1].JointAngle;\n                cntrl[2]=links[2].JointAngle;\n                cntrl[3]=links[3].JointAngle;\n                cntrl[4]=links[4].JointAngle;\n                cntrl[5]=links[5].JointAngle;//+teta_motor_R;//pitch\n                cntrl[6]=links[6].JointAngle;//roll\n                cntrl[7]=links[7].JointAngle;\n                cntrl[8]=links[8].JointAngle;\n                cntrl[9]=links[9].JointAngle;\n                cntrl[10]=links[10].JointAngle;\n\n                cntrl[11]=links[11].JointAngle;\n                cntrl[12]=links[12].JointAngle;\n\n\n\n\n\n\n        vector<int> qref(12);\n        qref=QC.ctrldata2qc(cntrl);\n\n\n        for(int  i = 0;i < 12;i++)\n        {\n            msg.data.push_back(qref[i]);\n\n        }\n        // std::string varAsString = std::to_string(qref[i-1]);\n        // msg.data =varAsString;\n        SendGazebo(links);\n        // SendGazeboPID();\n        chatter_pub.publish(msg);\n        //  ROS_INFO(\"t={%d} c={%d}\",timer.elapsed(),count);\n\n        ros::spinOnce();\n        loop_rate.sleep();\n        ++count;\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "f2805fa0d68e6860cbf86f82632142320e40ea4b", "size": 14601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "surena4/src/trajectory_generation/src/trajectory_generation_ramp.cpp", "max_stars_repo_name": "amin-amani/humanoid", "max_stars_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T08:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T08:51:26.000Z", "max_issues_repo_path": "surena4/src/trajectory_generation/src/trajectory_generation_ramp.cpp", "max_issues_repo_name": "amin-amani/humanoid", "max_issues_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-27T13:34:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-27T13:34:18.000Z", "max_forks_repo_path": "surena4/src/trajectory_generation/src/trajectory_generation_ramp.cpp", "max_forks_repo_name": "amin-amani/humanoid", "max_forks_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_forks_repo_licenses": ["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.8689217759, "max_line_length": 197, "alphanum_fraction": 0.6102321759, "num_tokens": 3895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.17486590310124905}}
{"text": "#include \"../src/ForceFields/GayBerneFF.h\"\n#include \"../src/ForceFields/ForceFieldManager.h\"\n#include \"../src/Simulation/StandardSimulation.h\"\n#include \"../src/Moves/MoveManager.h\"\n#include \"../src/Moves/TranslateMove.h\"\n#include \"../src/Particles/Particle.h\"\n\n#include \"../src/Worlds/World.h\"\n#include \"../src/Worlds/WorldManager.h\"\n#include \"../src/Constraints/Constraint.h\"\n#include \"TestAccumulator.h\"\n#include \"json/json.h\"\n#include \"gtest/gtest.h\"\n#include <fstream>\n\n#ifdef MULTI_WALKER\n#include <boost/mpi.hpp>\nusing namespace boost;\n#endif\n\nusing namespace SAPHRON;\n\n// Verified against OpenMD 2.4.\nTEST(GayBerneFF, DefaultBehavior)\n{\n\tdouble rcut = 55.0;\n\tGayBerneFF ff(16.27, 16.27, 3.254, 3.254, 418.0, 10.0, 1.0, 0.20, {rcut}, 1.0, 2.0);\n\n\tParticle s1({0.0, 0.0, 0.0}, {0.0, 0.0, 1.0}, \"L1\");\n\tParticle s2({0.0, 0.0, 0.0}, {0.0, 0.0, 1.0}, \"L1\");\n\ts1.AddNeighbor(&s2);\n\ts2.AddNeighbor(&s1);\n\n\ts2.SetPosition({16.6855, 0, 0});\n\tauto NB = ff.Evaluate(s1, s2, s1.GetPosition() - s2.GetPosition(), 0);\n\tASSERT_NEAR(NB.energy, -2823.5, 1e-1);\n\t\n\ts2.SetPosition({0, 0, 32.5468});\n\tNB = ff.Evaluate(s1, s2, s1.GetPosition() - s2.GetPosition(), 0);\n\tASSERT_NEAR(NB.energy, -0.1129, 1e-4);\n}\n\n// Tests conservation of energy in a system with GB \n// particles and no skin thickness. (rcut = nlist).\nTEST(GayBerneFF, NoSkinConservation)\n{\n\t#ifdef MULTI_WALKER\n\tmpi::environment env;\n\tmpi::communicator comm;\n\t#endif\n\t\n\t// Load file (assumes we are in build folder).\n\tstd::ifstream t(\"../test/gb_no_skin.json\");\n\tstd::stringstream buffer;\n\tbuffer << t.rdbuf();\n\n\t// Read JSON.\n\tJson::Reader reader;\n\tJson::Value root;\n\tASSERT_TRUE(reader.parse(buffer, root));\n\n\t// Build world.\n\tWorldManager wm;\n\tWorld* w;\n\tASSERT_NO_THROW(w = World::Build(root[\"worlds\"][0], root[\"blueprints\"]));\n\tASSERT_NE(nullptr, w);\n\twm.AddWorld(w);\n\n\tASSERT_EQ(338, w->GetParticleCount());\n\tASSERT_EQ(5.0, w->GetNeighborRadius());\n\tASSERT_EQ(0.0, w->GetSkinThickness());\n\n\t// Gay Berne interaction.\n\tForceFieldManager ffm;\n\tGayBerneFF ff(1.0, 1.0, 3.0, 3.0, 1.0, 1.0, 5.0, 1.0, {5.0}, 2.0, 1.0);\n\tffm.AddNonBondedForceField(\"GB\", \"GB\", ff);\n\n\t// Get constraints.\n\tstd::vector<Constraint*> constraints;\n\tASSERT_NO_THROW(Constraint::BuildConstraints(root[\"forcefields\"][\"constraints\"], &ffm, &wm, constraints));\n\n\t// Get moves.\n\tMoveManager mm;\n\tMoveList moves;\n\tASSERT_NO_THROW(Move::BuildMoves(root[\"moves\"], &mm, &wm, moves));\n\n\t// Initialize simulation. \n\tStandardSimulation sim(&wm, &ffm, &mm);\n\n\tsim.Run(100);\n\n\t// Conservation of energy and pressure.\n\tauto H = ffm.EvaluateEnergy(*w);\n\tASSERT_NEAR(H.energy.total(), w->GetEnergy().total(), 1e-10);\n\n\tdelete w;\n\tfor(auto& m : mm)\n\t\tdelete m;\n\n\tfor(auto& c : constraints)\n\t\tdelete c;\n}", "meta": {"hexsha": "9d1639a5dc8fe8fc357e430fee7bdda75addf641", "size": 2713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/GayBerneFFTests.cpp", "max_stars_repo_name": "hsidky/LNTMC", "max_stars_repo_head_hexsha": "6f1cc81476718ef19f85fd596d0815a194705a50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-08-16T23:32:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T09:39:58.000Z", "max_issues_repo_path": "test/GayBerneFFTests.cpp", "max_issues_repo_name": "hsidky/LNT-MC", "max_issues_repo_head_hexsha": "6f1cc81476718ef19f85fd596d0815a194705a50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2015-04-09T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-06T04:34:01.000Z", "max_forks_repo_path": "test/GayBerneFFTests.cpp", "max_forks_repo_name": "hsidky/LNT-MC", "max_forks_repo_head_hexsha": "6f1cc81476718ef19f85fd596d0815a194705a50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-02-16T18:34:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T19:37:14.000Z", "avg_line_length": 26.5980392157, "max_line_length": 107, "alphanum_fraction": 0.680427571, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.30074559147596, "lm_q1q2_score": 0.17482434618559287}}
{"text": "/*\n * spot_prediction_ext.cc\n *\n *  Copyright (C) 2013 Diamond Light Source\n *\n *  Author: James Parkhurst\n *\n *  This code is distributed under the BSD license, a copy of which is\n *  included in the root directory of this package.\n */\n#include <boost/python.hpp>\n#include <boost/python/def.hpp>\n#include <scitbx/array_family/small.h>\n#include <scitbx/boost_python/container_conversions.h>\n\nnamespace dials { namespace algorithms { namespace boost_python {\n\n  using namespace boost::python;\n  using namespace scitbx::boost_python::container_conversions;\n\n  void export_index_generator();\n  void export_reeke_index_generator();\n  void export_solve_quad();\n  void export_rotation_angles();\n  void export_ray_predictor();\n  void export_scan_varying_ray_predictor();\n  void export_stills_ray_predictor();\n  void export_ray_intersection();\n  void export_reflection_predictor();\n  void export_pixel_labeller();\n  void export_pixel_to_miller_index();\n\n  BOOST_PYTHON_MODULE(dials_algorithms_spot_prediction_ext) {\n    tuple_mapping_fixed_capacity<scitbx::af::small<double, 2> >();\n\n    export_index_generator();\n    export_reeke_index_generator();\n    export_solve_quad();\n    export_rotation_angles();\n    export_ray_predictor();\n    export_scan_varying_ray_predictor();\n    export_stills_ray_predictor();\n    export_ray_intersection();\n    export_reflection_predictor();\n    export_pixel_labeller();\n    export_pixel_to_miller_index();\n  }\n\n}}}  // namespace dials::algorithms::boost_python\n", "meta": {"hexsha": "b398ccb885e2079c143abf892fd9c269b69fc386", "size": 1487, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/spot_prediction/boost_python/spot_prediction_ext.cc", "max_stars_repo_name": "TiankunZhou/dials", "max_stars_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2015-10-15T09:28:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T20:09:38.000Z", "max_issues_repo_path": "algorithms/spot_prediction/boost_python/spot_prediction_ext.cc", "max_issues_repo_name": "TiankunZhou/dials", "max_issues_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1741.0, "max_issues_repo_issues_event_min_datetime": "2015-11-24T08:17:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:46:42.000Z", "max_forks_repo_path": "algorithms/spot_prediction/boost_python/spot_prediction_ext.cc", "max_forks_repo_name": "TiankunZhou/dials", "max_forks_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2015-10-14T13:44:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T14:45:56.000Z", "avg_line_length": 29.74, "max_line_length": 70, "alphanum_fraction": 0.7659717552, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.17479344369866132}}
{"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_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_DIGITS_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_DIGITS_HPP_INCLUDED\n\n#include <boost/simd/toolbox/constant/include/constants/mone.hpp>\n#include <boost/simd/toolbox/constant/include/constants/mtwo.hpp>\n#include <boost/simd/toolbox/constant/include/constants/mthree.hpp>\n#include <boost/simd/toolbox/constant/include/constants/mfour.hpp>\n#include <boost/simd/toolbox/constant/include/constants/mfive.hpp>\n#include <boost/simd/toolbox/constant/include/constants/msix.hpp>\n#include <boost/simd/toolbox/constant/include/constants/mseven.hpp>\n#include <boost/simd/toolbox/constant/include/constants/meight.hpp>\n#include <boost/simd/toolbox/constant/include/constants/mnine.hpp>\n#include <boost/simd/toolbox/constant/include/constants/mten.hpp>\n\n#include <boost/simd/toolbox/constant/include/constants/zero.hpp>\n\n#include <boost/simd/toolbox/constant/include/constants/one.hpp>\n#include <boost/simd/toolbox/constant/include/constants/two.hpp>\n#include <boost/simd/toolbox/constant/include/constants/three.hpp>\n#include <boost/simd/toolbox/constant/include/constants/four.hpp>\n#include <boost/simd/toolbox/constant/include/constants/five.hpp>\n#include <boost/simd/toolbox/constant/include/constants/six.hpp>\n#include <boost/simd/toolbox/constant/include/constants/seven.hpp>\n#include <boost/simd/toolbox/constant/include/constants/eight.hpp>\n#include <boost/simd/toolbox/constant/include/constants/nine.hpp>\n#include <boost/simd/toolbox/constant/include/constants/ten.hpp>\n#include <boost/simd/toolbox/constant/include/constants/eleven.hpp>\n#include <boost/simd/toolbox/constant/include/constants/twelve.hpp>\n#include <boost/simd/toolbox/constant/include/constants/twenty.hpp>\n\n#include <boost/simd/toolbox/constant/include/constants/fact_4.hpp>\n#include <boost/simd/toolbox/constant/include/constants/fact_5.hpp>\n#include <boost/simd/toolbox/constant/include/constants/fact_6.hpp>\n#include <boost/simd/toolbox/constant/include/constants/fact_7.hpp>\n#include <boost/simd/toolbox/constant/include/constants/fact_8.hpp>\n#include <boost/simd/toolbox/constant/include/constants/fact_9.hpp>\n#include <boost/simd/toolbox/constant/include/constants/fact_10.hpp>\n#include <boost/simd/toolbox/constant/include/constants/fact_11.hpp>\n#include <boost/simd/toolbox/constant/include/constants/fact_12.hpp>\n\n\n#include <boost/simd/toolbox/constant/include/constants/int_splat.hpp>\n\n#endif\n", "meta": {"hexsha": "c1db1875b8452eb3c992411adbd507337b34cc93", "size": 2954, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/constant/include/boost/simd/toolbox/constant/include/constants/digits.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/constant/include/boost/simd/toolbox/constant/include/constants/digits.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/constant/include/boost/simd/toolbox/constant/include/constants/digits.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": 55.7358490566, "max_line_length": 80, "alphanum_fraction": 0.7549085985, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3415824994383169, "lm_q1q2_score": 0.174793436838938}}
{"text": "/**************************************************************************\n * Copyright (c) 2017-2019 by the mfmg authors                            *\n * All rights reserved.                                                   *\n *                                                                        *\n * This file is part of the mfmg library. mfmg is distributed under a BSD *\n * 3-clause license. For the licensing terms see the LICENSE file in the  *\n * top-level directory                                                    *\n *                                                                        *\n * SPDX-License-Identifier: BSD-3-Clause                                  *\n *************************************************************************/\n\n#ifndef MFMG_HIERARCHY_HPP\n#define MFMG_HIERARCHY_HPP\n\n#include <mfmg/common/exceptions.hpp>\n#include <mfmg/common/level.hpp>\n#include <mfmg/common/mesh_evaluator.hpp>\n#include <mfmg/common/utils.hpp>\n#include <mfmg/dealii/dealii_hierarchy_helpers.hpp>\n#include <mfmg/dealii/dealii_matrix_free_hierarchy_helpers.hpp>\n#ifdef MFMG_WITH_CUDA\n#include <mfmg/cuda/cuda_hierarchy_helpers.cuh>\n#include <mfmg/cuda/cuda_matrix_operator.cuh>\n#include <mfmg/cuda/cuda_mesh_evaluator.cuh>\n#endif\n\n#include <deal.II/base/timer.h>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <memory>\n#include <vector>\n\nnamespace mfmg\n{\nvoid timer_enter_subsection(std::shared_ptr<dealii::TimerOutput> const &timer,\n                            std::string const &section)\n{\n  if (timer)\n    timer->enter_subsection(section);\n}\n\nvoid timer_leave_subsection(std::shared_ptr<dealii::TimerOutput> const &timer)\n{\n  if (timer)\n    timer->leave_subsection();\n}\n\ntemplate <typename VectorType>\nstd::unique_ptr<HierarchyHelpers<VectorType>>\ncreate_hierarchy_helpers(std::shared_ptr<MeshEvaluator const> evaluator)\n{\n  std::unique_ptr<HierarchyHelpers<VectorType>> hierarchy_helpers;\n  std::string evaluator_type = evaluator->get_mesh_evaluator_type();\n  if (evaluator_type == \"DealIIMeshEvaluator\")\n  {\n    int const dim = evaluator->get_dim();\n    if (dim == 2)\n      hierarchy_helpers.reset(new DealIIHierarchyHelpers<2, VectorType>());\n    else if (dim == 3)\n      hierarchy_helpers.reset(new DealIIHierarchyHelpers<3, VectorType>());\n    else\n      ASSERT_THROW_NOT_IMPLEMENTED();\n  }\n  else if (evaluator_type == \"DealIIMatrixFreeMeshEvaluator\")\n  {\n    int const dim = evaluator->get_dim();\n    if (dim == 2)\n      hierarchy_helpers.reset(\n          new DealIIMatrixFreeHierarchyHelpers<2, VectorType>());\n    else if (dim == 3)\n      hierarchy_helpers.reset(\n          new DealIIMatrixFreeHierarchyHelpers<3, VectorType>());\n    else\n      ASSERT_THROW_NOT_IMPLEMENTED();\n  }\n#ifdef MFMG_WITH_CUDA\n  else if (evaluator_type == \"CudaMeshEvaluator\")\n  {\n    int const dim = evaluator->get_dim();\n\n    if (dim == 2)\n    {\n      // Downcast evaluator\n      auto const cuda_evaluator =\n          std::dynamic_pointer_cast<CudaMeshEvaluator<2> const>(evaluator);\n      hierarchy_helpers.reset(new CudaHierarchyHelpers<2, VectorType>(\n          cuda_evaluator->get_cuda_handle()));\n    }\n    else if (dim == 3)\n    {\n      // Downcast evaluator\n      auto const cuda_evaluator =\n          std::dynamic_pointer_cast<CudaMeshEvaluator<3> const>(evaluator);\n      hierarchy_helpers.reset(new CudaHierarchyHelpers<3, VectorType>(\n          cuda_evaluator->get_cuda_handle()));\n    }\n    else\n      ASSERT_THROW_NOT_IMPLEMENTED();\n  }\n#endif\n  else\n  {\n    ASSERT_THROW_NOT_IMPLEMENTED();\n  }\n  return hierarchy_helpers;\n}\n\n#ifdef MFMG_WITH_CUDA\ntemplate <>\nstd::unique_ptr<HierarchyHelpers<dealii::LinearAlgebra::distributed::Vector<\n    double, dealii::MemorySpace::CUDA>>>\ncreate_hierarchy_helpers(std::shared_ptr<MeshEvaluator const> evaluator)\n{\n  std::unique_ptr<HierarchyHelpers<dealii::LinearAlgebra::distributed::Vector<\n      double, dealii::MemorySpace::CUDA>>>\n      hierarchy_helpers;\n  std::string evaluator_type = evaluator->get_mesh_evaluator_type();\n  if (evaluator_type == \"CudaMeshEvaluator\")\n  {\n    int const dim = evaluator->get_dim();\n\n    if (dim == 2)\n    {\n      // Downcast evaluator\n      auto const cuda_evaluator =\n          std::dynamic_pointer_cast<CudaMeshEvaluator<2> const>(evaluator);\n      hierarchy_helpers.reset(\n          new CudaHierarchyHelpers<2,\n                                   dealii::LinearAlgebra::distributed::Vector<\n                                       double, dealii::MemorySpace::CUDA>>(\n              cuda_evaluator->get_cuda_handle()));\n    }\n    else if (dim == 3)\n    {\n      // Downcast evaluator\n      auto const cuda_evaluator =\n          std::dynamic_pointer_cast<CudaMeshEvaluator<3> const>(evaluator);\n      hierarchy_helpers.reset(\n          new CudaHierarchyHelpers<3,\n                                   dealii::LinearAlgebra::distributed::Vector<\n                                       double, dealii::MemorySpace::CUDA>>(\n              cuda_evaluator->get_cuda_handle()));\n    }\n    else\n      ASSERT_THROW_NOT_IMPLEMENTED();\n  }\n  else\n    ASSERT_THROW_NOT_IMPLEMENTED();\n\n  return hierarchy_helpers;\n}\n#endif\n\ntemplate <typename VectorType>\nclass Hierarchy\n{\npublic:\n  Hierarchy(MPI_Comm comm, std::shared_ptr<MeshEvaluator> evaluator,\n            std::shared_ptr<boost::property_tree::ptree> params = nullptr,\n            std::shared_ptr<dealii::TimerOutput> timer = nullptr)\n      : _timer(timer)\n  {\n    timer_enter_subsection(_timer, \"Setup\");\n    // Replace by a factory\n    auto hierarchy_helpers = create_hierarchy_helpers<VectorType>(evaluator);\n\n    _is_preconditioner = params->get(\"is preconditioner\", true);\n    _n_smoothing_steps = params->get(\"smoother.n_smoothing_steps\", 1);\n\n    // TODO: add stopping criteria for levels (number of levels / coarse size)\n    int const num_levels = params->get(\"max levels\", 2);\n    ASSERT(num_levels > 0, \"number of levels specified by \\\"max levels\\\" \"\n                           \"parameter must be positive\");\n    _levels.resize(num_levels);\n\n    _levels[0].set_operator(hierarchy_helpers->get_global_operator(evaluator));\n    for (int level_index = 0; level_index < num_levels; level_index++)\n    {\n      auto &level_fine = _levels[level_index];\n\n      auto a = level_fine.get_operator();\n\n      if (level_index == num_levels - 1)\n      {\n        if (level_index == 0)\n        {\n          // When using ML for the full hierarchy, do not zero out initial guess\n          params->put(\"coarse.params.zero starting solution\",\n                      _is_preconditioner);\n        }\n\n        timer_enter_subsection(_timer, \"Setup: build coarse solver\");\n        auto coarse_solver = hierarchy_helpers->build_coarse_solver(a, params);\n        level_fine.set_solver(coarse_solver);\n        timer_leave_subsection(_timer);\n\n        break;\n      }\n\n      auto &level_coarse = _levels[level_index + 1];\n\n      timer_enter_subsection(_timer, \"Setup: build smoother\");\n      auto smoother = hierarchy_helpers->build_smoother(a, params);\n      level_fine.set_smoother(smoother);\n      timer_leave_subsection(_timer);\n\n      timer_enter_subsection(_timer, \"Setup: build restrictor\");\n      auto restrictor =\n          hierarchy_helpers->build_restrictor(comm, evaluator, params);\n      level_coarse.set_restrictor(restrictor);\n      timer_leave_subsection(_timer);\n\n      std::shared_ptr<Operator<VectorType>> ap;\n      bool fast_ap = params->get(\"fast_ap\", false);\n      if (fast_ap)\n      {\n        timer_enter_subsection(_timer, \"Setup: fast_ap\");\n        ap = hierarchy_helpers->fast_multiply_transpose();\n        timer_leave_subsection(_timer);\n      }\n      else\n      {\n        timer_enter_subsection(_timer, \"Setup: ap\");\n        ap = a->multiply_transpose(restrictor);\n        timer_leave_subsection(_timer);\n      }\n\n      timer_enter_subsection(_timer, \"Setup: build coarse matrix\");\n      auto a_coarse = restrictor->multiply(ap);\n      timer_leave_subsection(_timer);\n\n      level_coarse.set_operator(a_coarse);\n    }\n    timer_leave_subsection(_timer);\n  }\n\n  void vmult(VectorType &x, VectorType const &b) const\n  {\n    // Apply calls itself recursively which trips the timer so put it here\n    timer_enter_subsection(_timer, \"Apply\");\n    apply(b, x, 0);\n    timer_leave_subsection(_timer);\n  }\n\n  void apply(VectorType const &b, VectorType &x, int level_index = 0) const\n  {\n    auto const num_levels = _levels.size();\n\n    auto &level_fine = _levels[level_index];\n    auto a = level_fine.get_operator();\n\n    if (level_index > 0 || _is_preconditioner)\n    {\n      // Zero out any garbage in x.\n      // The only exception is when it's the finest level in a standalone\n      // mode.\n      x = 0.;\n    }\n\n    if (level_index == num_levels - 1)\n    {\n      timer_enter_subsection(_timer, \"Apply: coarsest level\");\n      // Coarsest level\n      auto coarse_solver = level_fine.get_solver();\n      coarse_solver->apply(b, x);\n      timer_leave_subsection(_timer);\n    }\n    else\n    {\n      timer_enter_subsection(_timer, \"Apply: fine levels\");\n      auto &level_coarse = _levels[level_index + 1];\n\n      auto restrictor = level_coarse.get_restrictor();\n\n      // apply pre-smoother\n      auto smoother = level_fine.get_smoother();\n      for (unsigned int i = 0; i < _n_smoothing_steps; ++i)\n        smoother->apply(b, x);\n\n      // compute residual\n      // NOTE: we compute negative residual -r = Ax-b, so that we can avoid\n      // using sadd and can just use add\n      auto res = level_fine.build_vector();\n      a->apply(x, *res);\n      res->add(-1., b);\n\n      // restrict residual\n      auto b_coarse = level_coarse.build_vector();\n      restrictor->apply(*res, *b_coarse);\n\n      // compute coarse grid correction\n      auto x_coarse = level_coarse.build_vector();\n      apply(*b_coarse, *x_coarse, level_index + 1);\n\n      // update solution\n      auto x_correction = level_fine.build_vector();\n      restrictor->apply(*x_coarse, *x_correction, OperatorMode::TRANS);\n\n      // NOTE: as we used negative residual, we subtract instead of adding\n      // here\n      x.add(-1., *x_correction);\n\n      // apply post-smoother\n      for (unsigned int i = 0; i < _n_smoothing_steps; ++i)\n        smoother->apply(b, x);\n      timer_leave_subsection(_timer);\n    }\n  }\n\n  double grid_complexity() const\n  {\n    // auto const num_levels = _levels.size();\n\n    // if (num_levels == 0)\n    //   return -1.0;\n\n    // auto level0_m = _levels[0].get_operator()->grid_complexity();\n    // ASSERT(level0_m, \"The size of the finest level operator is 0.\");\n\n    // double complexity = level0_m;\n\n    // for (int i = 1; i < num_levels; i++)\n    // {\n    //   if (i < num_levels - 1)\n    //     complexity += _levels[i].get_operator()->grid_complexity();\n    //   else\n    //   {\n    //     // Hierarchy may be continued using a different multigrid\n    //     // For direct solvers, this would be equivalent to using\n    //     //   _levels[i].get_operator()->grid_complexity()\n    //     complexity += _levels[i].get_smoother()->grid_complexity();\n    //   }\n    // }\n\n    // return complexity / level0_m;\n\n    return 0;\n  }\n\n  double operator_complexity() const\n  {\n    // auto const num_levels = _levels.size();\n\n    // if (num_levels == 0)\n    //   return -1.0;\n\n    // auto level0_nnz = _levels[0].get_operator()->operator_complexity();\n    // ASSERT(level0_nnz, \"The nnz of the finest level operator is 0.\");\n\n    // double complexity = level0_nnz;\n    // for (int i = 1; i < num_levels; i++)\n    // {\n    //   if (i < num_levels - 1)\n    //     complexity += _levels[i].get_operator()->operator_complexity();\n    //   else\n    //   {\n    //     // Hierarchy may be continued using a different multigrid\n    //     // For direct solvers, this would be equivalent to using\n    //     //   _levels[i].get_operator()->operator_complexity()\n    //     complexity += _levels[i].get_smoother()->operator_complexity();\n    //   }\n    // }\n    // return complexity / level0_nnz;\n    return 0;\n  }\n\nprivate:\n  std::shared_ptr<dealii::TimerOutput> _timer;\n  std::vector<Level<VectorType>> _levels;\n  bool _is_preconditioner = true;\n  unsigned int _n_smoothing_steps;\n};\n} // namespace mfmg\n\n#endif // ifdef MFMG_HIERARCHY_HPP\n", "meta": {"hexsha": "24811acb551f21cb5edf8d4649096f2c167cac31", "size": 12157, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mfmg/common/hierarchy.hpp", "max_stars_repo_name": "Rombur/mfmg", "max_stars_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-03T15:13:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:33:10.000Z", "max_issues_repo_path": "include/mfmg/common/hierarchy.hpp", "max_issues_repo_name": "Rombur/mfmg", "max_issues_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 199.0, "max_issues_repo_issues_event_min_datetime": "2017-11-03T13:33:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-07T22:46:18.000Z", "max_forks_repo_path": "include/mfmg/common/hierarchy.hpp", "max_forks_repo_name": "Rombur/mfmg", "max_forks_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-03T12:44:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T05:51:23.000Z", "avg_line_length": 32.2466843501, "max_line_length": 80, "alphanum_fraction": 0.6304186888, "num_tokens": 2907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.17479342997921493}}
{"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#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <vw/Math/Matrix.h>\n#include <vw/Cartography/GeoReference.h>\n#include <vw/Image/ImageView.h>\n#include <vw/Image/MaskViews.h>\n#include <vw/Image/Statistics.h>\n#include <vw/InterestPoint.h>\n#include <vw/FileIO/DiskImageResource.h>\n#include <vw/FileIO/DiskImageView.h>\n\n// Not sure which of these we need but we get run-time errors otherwise...\n#include <vw/InterestPoint.h>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <vw/Stereo/PreFilter.h>\n#include <vw/Stereo/CorrelationView.h>\n#include <vw/Stereo/CostFunctions.h>\n#include <vw/Stereo/DisparityMap.h>\n#include <asp/Core/DemDisparity.h>\n#include <asp/Core/LocalHomography.h>\n\n//#include <asp/Tools/stereo.h>\n#include <stereo.h> // Using local copy\n\n/// \\file pixelPairsFromStereo.cc Generates a list of pixel point pairs from the output of the stereo tool\n\n\nint main( int argc, char *argv[] ) {\n\n\n  std::string inputImagePath, outputPath=\"\";\n  int pointSpacing=0;\n  std::vector<float> leftAffineVals, rightAffineVals;\n\n  // Affine transforms are identity matrix by default\n  vw::Matrix<double> leftAffine, rightAffine;\n  leftAffine  = vw::math::identity_matrix<3>();\n  rightAffine = vw::math::identity_matrix<3>();\n  // Note that the user inputs the matrices that were used in stereo,\n  //  we need to compute the inverse of those matrices.\n\n  po::options_description general_options(\"Options\");\n  general_options.add_options()\n    (\"help\",        \"Display this help message\")\n    (\"pointSpacing\", po::value<int        >(&pointSpacing)->default_value(100), \"Selected pixels are this far apart\")\n    (\"leftAffine\",    po::value<std::vector<float> >(&leftAffineVals)->multitoken(),\n                           \"Affine transform which was applied to the left image pixels)\")\n    (\"rightAffine\",   po::value<std::vector<float> >(&rightAffineVals)->multitoken(),\n                           \"Affine transform which was applied to the right image pixels)\");\n\n  po::options_description positional(\"\");\n  positional.add_options()\n    (\"input-file\",   po::value(&inputImagePath), \"The input stereo file (xxx-D.tif)\")\n    (\"output-file\",  po::value(&outputPath),     \"Specify an output text file to store the program output\");\n\n  po::positional_options_description positional_desc;\n  positional_desc.add(\"input-file\",  1);\n  positional_desc.add(\"output-file\", 1);\n\n  std::string usage(\"[options] <input path> <output path>\\n\");\n  po::variables_map vm;\n  try {\n    po::options_description all_options;\n    all_options.add(general_options).add(positional);\n\n    po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).style( po::command_line_style::unix_style ^ po::command_line_style::allow_short ).run(), vm );\n\n    po::notify( vm );\n  } catch (po::error const& e) {\n    vw::vw_throw( vw::ArgumentErr() << \"Error parsing input:\\n\"\n                  << e.what() << \"\\n\" << usage << general_options );\n  }\n\n  if ( !vm.count(\"input-file\") || !vm.count(\"output-file\") )\n    vw_throw( vw::ArgumentErr() << \"Requires <input path> and <output path> input in order to proceed.\\n\\n\"\n              << usage << general_options );\n\n  const size_t NUM_AFFINE_ELEMENTS = 6; // The last three elements are 0 0 1\n  if (vm.count(\"leftAffine\"))\n  {\n    // Check input size\n    if (leftAffineVals.size() != NUM_AFFINE_ELEMENTS)\n      vw::vw_throw( vw::ArgumentErr() << \"Incorrect number of left affine arguments passed in!\\n\"\n                                      << usage << general_options );\n    // Store affine values in a temp matrix object which is then inverted\n    vw::Matrix<double> affineTemp = vw::math::identity_matrix<3>();\n    for (int i=0; i<NUM_AFFINE_ELEMENTS; ++i)\n      affineTemp.data()[i] = leftAffineVals[i];\n    vw::vw_out() << \"Read in left affine matrix:\\n\" << affineTemp << \"\\n\";\n    leftAffine = inverse(affineTemp);\n  }\n  if (vm.count(\"rightAffine\"))\n  {\n    // Check input size\n    if (rightAffineVals.size() != NUM_AFFINE_ELEMENTS)\n      vw::vw_throw( vw::ArgumentErr() << \"Incorrect number of right affine arguments passed in!\\n\"\n                                      << usage << general_options );\n    // Store affine values in a temp matrix object which is then inverted\n    vw::Matrix<double> affineTemp = vw::math::identity_matrix<3>();\n    for (int i=0; i<NUM_AFFINE_ELEMENTS; ++i)\n      affineTemp.data()[i] = rightAffineVals[i];\n    vw::vw_out() << \"Read in right affine matrix:\\n\" << affineTemp << \"\\n\";\n    rightAffine = inverse(affineTemp);\n  }\n\n  try {\n  \n    std::ofstream outputFile(outputPath.c_str());\n    if (outputFile.fail())\n    {\n      printf(\"Failed to open output file for writing\\n\");\n      return 0;\n    }\n    \n    printf(\"Loading image\\n\");\n\n    vw::ImageViewRef<vw::PixelMask<vw::Vector2i> > inputImage = vw::DiskImageView<vw::PixelMask<vw::Vector2i> >(inputImagePath);\n\n    printf(\"Done loading image\\n\");\n    \n    //if (!inputImage.is_valid_image())\n    //{\n    //  printf(\"Failed to load image!\\n\");\n    //  return 0;\n    //}\n    printf(\"Image size: %d x %d\\n\", inputImage.rows(), inputImage.cols());\n\n    vw::ImageViewRef<vw::PixelMask<vw::Vector2i> >::iterator iter = inputImage.begin();\n    \n    // First pass computes min, max, mean, and std_dev\n    int count = 0;\n    for (int row=0; row<inputImage.rows(); row+=1)\n    {\n    \n      for (int col=0; col<inputImage.cols(); col+=1)\n      {\n        if ((row % pointSpacing == 0) && (col % pointSpacing == 0))\n        {\n          //printf(\"%d, %d\\n\", row, col);\n          if (vw::is_valid(*iter)) // Skip invalid pixels\n          {\n            //printf(\"%d, %d\\n\", row, col);\n            //std::cout << (*iter)[0] << std::endl;\n\n            // Pixel in other image = original pixel location + stored offset\n            int rightCol = floor(0.5 + col + (*iter)[0]);\n            int rightRow = floor(0.5 + row + (*iter)[1]);\n\n            // Apply the affine transforms to the left and right pixels\n            vw::Vector3 leftCoord (col,      row, 1);\n            vw::Vector3 rightCoord(rightCol, rightRow, 1);\n            vw::Vector3 leftTransformed  = leftAffine * leftCoord;\n            vw::Vector3 rightTransformed = rightAffine * rightCoord;\n\n            // Write to file and record total\n            outputFile << leftTransformed [0] <<\",\"<< leftTransformed [1] <<\",\"\n                       << rightTransformed[0] <<\",\"<< rightTransformed[1] << std::endl;\n            ++count;\n          } // End valid check\n        } // End spacing check\n        ++iter;\n      } // End loop through cols\n\n    } // End loop through rows\n\n    // Done writing the output file\n    outputFile.close();\n\n    printf(\"Wrote %d pixel pairs\\n\", count);\n    \n  }\n  catch (const vw::Exception& e) {\n    std::cerr << \"Error: \" << e.what() << std::endl;\n  }\n\n  return 0;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e59d1517bf00c24d8e4ce5bcb2a603282a93dfc4", "size": 7846, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pixelPairsFromStereo.cc", "max_stars_repo_name": "NeoGeographyToolkit/Tools", "max_stars_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-05-13T22:49:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-08T19:57:11.000Z", "max_issues_repo_path": "pixelPairsFromStereo.cc", "max_issues_repo_name": "NeoGeographyToolkit/Tools", "max_issues_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "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": "pixelPairsFromStereo.cc", "max_forks_repo_name": "NeoGeographyToolkit/Tools", "max_forks_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-12-17T22:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T18:57:32.000Z", "avg_line_length": 35.9908256881, "max_line_length": 196, "alphanum_fraction": 0.645679327, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.17477724340228776}}
{"text": "#include <ignition/math/Pose3.hh>\n#include \"gazebo/physics/physics.hh\"\n#include \"gazebo/common/common.hh\"\n#include \"gazebo/gazebo.hh\"\n#include <boost/bind.hpp>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <mutex>\n#include <map>\n#include <vector>\n#include <set>\n\n#include <sstream>\n#include <iomanip>\n#include <ctime>\n\nusing namespace std;\nnamespace gazebo\n{\n\tclass WP_Swarm1 : public WorldPlugin\n\t{\n\t\t//Pointer to the update event connection\n\t\tprivate:\n\t\t\tevent::ConnectionPtr updateConnection;\n\t\t\tphysics::WorldPtr world;\n\t\t\tstd::mutex mutex;\n\t\t\ttransport::NodePtr node;\n\t\t\ttransport::PublisherPtr pub_litter_pose;\n\t\t\tstd::string world_info_string;//should state when simulation starts and ends per world\n\t\t\tbool world_info_bool;//used to indicate the world is loaded and ready to go\n\t\t\ttransport::PublisherPtr pub_world_loaded;\n\t\t\t\n\t\t\tbool world_gov_experiment_control;// used by world governor to control start of simulation runs\n\t\t\ttransport::SubscriberPtr sub_world_gov_experiment_control;\n\n\t\t\tdouble nei_sensing;\n\t\t\tbool param_set;\n\t\t\tgazebo::transport::SubscriberPtr sub_params;\n\t\t\t//This section of parameters are used to handle communication between robots\n\t\t\tstd::map<std::string,transport::PublisherPtr> pub_commSignal;\n\t\t\t//std::map<std::string,transport::PublisherPtr> pub_attraction;\n\t\t\t\n\t\t\tstd::map<std::string,int> seen_litter_map;\n\t\t\tgazebo::transport::SubscriberPtr sub_seen_litter;//Models publish seen litter to this topic\n\t\t\t\n\t\t\tstd::map<std::string,std::string> robot_status_map;\n\t\t\tgazebo::transport::SubscriberPtr sub_robot_status;//Models publish their status to this sub\n\t\t\t\n\t\t\tgazebo::transport::PublisherPtr pub_repel_signal;\n\t\t\tgazebo::transport::PublisherPtr pub_attract_signal;\n\t\t\tgazebo::physics::Model_V robot_ptr;//consider changing it to set\n\t\t\tgazebo::physics::Model_V litter_ptr;\n\t\t\tdouble lit_threshold;\n\t\t\t\n\t\t\t\n\t\t\t//*********************START: TO HANDLE PARAMTER UPDATING AND SIMULATION RESETS\n\t\t\tbool start_sim;\n\t\t\tbool start_sim2;\n\t\t\tbool no_litter;\n\t\t\tgazebo::transport::PublisherPtr pub_start_sim;\n\t\t\tgazebo::transport::PublisherPtr pub_my_Init;\n\t\t\tgazebo::transport::PublisherPtr pub_model_log_control;\n\t\t\ttransport::PublisherPtr physicsPub;\n\t\t\tbool set_max_step_size;\n\t\t\tdouble exp_dur; //maximum duration of experiment before activating  homing behaviour\n\t\t\tstd::string params_str;\n\n\t\t\t\n\t\t\t//*******nest model pointer *********//\n\t\t\tgazebo::physics::ModelPtr m_nest;\n\n\t\t\tint litter_tot;//total litter in world\n\t\t\tint litter_in_nest;//total litter deposited at the nest\n\t\t\tgazebo::transport::SubscriberPtr sub_litter_in_nest;//subscriber to litter in nest topic\n\t\t\tdouble nest_distance_travelled;\n\t\t\tdouble max_nest_travel;\n\t\t\t//---------------end nest model pointer--------//\n\t\t\t\n\t\t\t//All params to be simulated are stored in a vector\n\t\t\tvector<string> my_params;\n\t\t\tstd::vector<string>::iterator param_it;\n\t\t\t\n\t\t\t\n\t\t\tdouble world_size;\n\t\t\t//double world_sizeY;\n\t\t\t//double psec;\n\t\t\t//*********************END: TO HANDLE PARAMTER UPDATING AND SIMULATION RESETS\n\t\t\t\n\t\t\t//START: EXPERIMENT START STOP CONTROL\n\t\t\tgazebo::transport::PublisherPtr pub_experiment_control;\n\t\t\tbool end_experiment;\n\t\t\t//END: EXPERMEINT START STOP CONTROL\n\t\t\t\n\t\t\tdouble log_timer;\n\t\t\tdouble max_step_size;\n\t\t\tdouble log_rate;\n\t\t\t\n\t\t\tstd::string com_model;\n\t\t\tint cap_com;\n\t\t\t// Sound source modelling parameters\n\t\t\tmath::Vector3 signal_source_pos;\n\t\t\tdouble A0; //intensity from source\n\t\t\tdouble alpha; //attenuation factor\n\t\t\tdouble Ae; //ambient noise scale\n\t\t\tdouble noise_mean;//mean of the noise\n\t\t\tdouble noise_std;//standard deviation of the noise\n\t\t\tstd::normal_distribution<double> noise_distro;//distribution for making sound noisy\n\t\t\tstd::default_random_engine generator;\n\t\tpublic:\n\t\t\tvoid Load(physics::WorldPtr _parent, sdf::ElementPtr /*_sdf*/)\n\t\t\t{\n\t\t\t\t// std::cout<<\"world loading\"<<std::endl;\n\t\t\t\tthis->node = transport::NodePtr(new transport::Node());\n\t\t\t\tthis->node->Init();\n\t\t\t\tthis->world = _parent;\n\t\t\t\tthis->world_info_bool = true;//default value is true when world is loaded\n\t\t\t\tthis->pub_world_loaded = this->node->Advertise<msgs::Any>(\"/world_loaded\");\n\t\t\t\t\n\n\t\t\t\tthis->world_gov_experiment_control = false;//default value is false. Set to true from subscribed topic\n\t\t\t\tthis->sub_world_gov_experiment_control = this->node->Subscribe(\"/world_gov_experiment_control\",&WP_Swarm1::world_gov_experiment_control_cb,this);\n\n\t\t\t\tthis->physicsPub = node->Advertise<msgs::Physics>(\"~/physics\");\n\t\t\t\tmsgs::Physics physicsMsg;\n\t\t\t\tphysicsMsg.set_type(msgs::Physics::ODE);\n\t\t\t\tphysicsMsg.set_max_step_size(0.025);//manually increase the step size\n\t\t\t\tthis->physicsPub->Publish(physicsMsg);\n\n\t\t\t\tthis->set_max_step_size = true;\n\t\t\t\t//this->psec = 0;\n\t\t\t\t//exit(5);\n\t\t\t\t//load simulation paramters\n\t\t\t\t// ifstream myfile;\n\t\t\t\t// string line, header;\n\t\t\t\t// myfile.open(\"params/params.csv\");\n\t\t\t\t// if(myfile.is_open())\n\t\t\t\t// {\n\t\t\t\t// \tgetline(myfile,header);\n\t\t\t\t// \twhile(getline(myfile,line))\n\t\t\t\t// \t{\n\t\t\t\t// \t\tsize_t hsep1=0,hsep2=0,psep1=0,psep2=0;\n\t\t\t\t// \t\tstring hparam,param_value;\n\t\t\t\t// \t\tstring param_line = \"\";\n\t\t\t\t// \t\twhile(header.find(\",\",hsep1) != string::npos and\n\t\t\t\t// \t\t\t\tline.find(\",\",psep1) != string::npos)\n\t\t\t\t// \t\t{\n\t\t\t\t// \t\t\thsep2 = header.find(\",\",hsep1);\n\t\t\t\t// \t\t\thparam = header.substr(hsep1,hsep2-hsep1);\n\t\t\t\t// \t\t\tpsep2 = line.find(\",\",psep1);\n\t\t\t\t// \t\t\tparam_value = line.substr(psep1,psep2-psep1);\n\t\t\t\t\t\t\t\n\t\t\t\t// \t\t\tparam_line = param_line + hparam + \":\" + param_value + \",\";\n\t\t\t\t// \t\t\thsep1 = hsep2 + 1;\n\t\t\t\t// \t\t\tpsep1 = psep2 + 1;\n\t\t\t\t// \t\t\tif(hparam.compare(\"max_step_size\") == 0)\n\t\t\t\t// \t\t\t{\n\t\t\t\t// \t\t\t\ttransport::PublisherPtr physicsPub = \n\t\t\t\t// \t\t\t\tnode->Advertise<msgs::Physics>(\"~/physics\");\n\t\t\t\t// \t\t\t\tmsgs::Physics physicsMsg;\n\t\t\t\t// \t\t\t\tphysicsMsg.set_type(msgs::Physics::ODE);\n\t\t\t\t\t\t\t\t\n\t\t\t\t// \t\t\t\tdouble value = std::stod(param_value);\n\t\t\t\t// \t\t\t\t//this->max_step_size = value;\n\t\t\t\t// \t\t\t\t//value = 1.0/value;\n\t\t\t\t// \t\t\t\tphysicsMsg.set_max_step_size(value);\n\t\t\t\t// \t\t\t\tphysicsPub->Publish(physicsMsg);\n\t\t\t\t// \t\t\t}\n\t\t\t\t// \t\t}\n\t\t\t\t// \t\tthis->my_params.push_back(param_line);\n\t\t\t\t// \t}\n\t\t\t\t// \t//iterator set to first parameter list\n\t\t\t\t// \tthis->param_it = this->my_params.begin();\n\t\t\t\t// \tmyfile.close();\n\t\t\t\t// }\n\t\t\t\t// else\n\t\t\t\t// {\n\t\t\t\t// \t//cout<<\"unable to load file\"<<endl;\n\t\t\t\t// \t//exit(5);\n\t\t\t\t// }\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(this->world->GetModel(\"boundary1\"))\n\t\t\t\t{\n\t\t\t\t\tmath::Box boundary = this->world->GetModel(\"boundary1\")->GetBoundingBox();\n\t\t\t\t\tthis->world_size = boundary.GetXLength();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthis->world_size = 9999999;\n\t\t\t\t}\n\t\t\t\t//std::cout<<boundary.GetXLength()<<\":\"<<boundary.GetYLength()<<\":\"<<boundary.GetZLength()<<std::endl;\n\t\t\t\t\n\t\t\t\tthis->sub_params = this->node->Subscribe(\"/params_topic\",&WP_Swarm1::Params_cb,this);\n\t\t\t\tthis->sub_seen_litter = this->node->Subscribe(\"/topic_seen_litter\",&WP_Swarm1::seen_litter_cb,this);\n\t\t\t\tthis->sub_robot_status = this->node->Subscribe(\"/topic_robot_status\",&WP_Swarm1::robot_status_cb,this);\n\t\t\t\tthis->pub_litter_pose = this->node->Advertise<msgs::Any>(\"/topic_litter_pose\");\n\t\t\t\tstd::string all_litter_pos = \"\";\n\t\t\t\t//////////////////////////////////////////////////////////////\n\t\t\t\tthis->m_nest = this->world->GetModel(\"m_nest\");\n\t\t\t\t\n\t\t\t\tgazebo::physics::Model_V all_models = this->world->GetModels();\n\t\t\t\tthis->sub_litter_in_nest = this->node->Subscribe(\"/litter_in_nest\",&WP_Swarm1::litter_in_nest_cb,this);\n\t\t\t\tthis->litter_in_nest = 0;\n\t\t\t\t\n\t\t\t\tthis->litter_tot = 0;\n\t\t\t\tfor(auto m : all_models)\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tstd::string model_name = m->GetName();\n\t\t\t\t\tif(model_name.find(\"m_4wrobot\") != std::string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->robot_ptr.push_back(m);\n\t\t\t\t\t\tthis->pub_commSignal[model_name] = this->node->Advertise<msgs::Any>(\"/\"+model_name+\"/comm_signal\");\n\t\t\t\t\t\t//this->pub_attraction[model_name] = this->node->Advertise<msgs::Any>(\"/\"+model_name+\"/attract_signal\");\n\t\t\t\t\t\tthis->seen_litter_map[model_name] = 0;\n\t\t\t\t\t\tthis->robot_status_map[model_name] = \"searching\";\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(model_name.find(\"litter\") != std::string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->litter_tot += 1;\n\t\t\t\t\t\tgazebo::math::Vector3 lit_loc = m->GetWorldPose().pos;\n\t\t\t\t\t\tthis->litter_ptr.push_back(m);\n\t\t\t\t\t\tall_litter_pos = all_litter_pos + to_string(lit_loc.x) + \",\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ to_string(lit_loc.y) + \":\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmsgs::Any all_litter_pos_msg;\n\t\t\t\tall_litter_pos_msg.set_type(msgs::Any::STRING);\n\t\t\t\tall_litter_pos_msg.set_string_value(all_litter_pos);\n\t\t\t\tthis->pub_litter_pose->Publish(all_litter_pos_msg);//publish initial pos of all litter\n\t\t\t\t\n\t\t\t\tthis->pub_repel_signal = this->node->Advertise<msgs::Any>(\"/repulsion_signal\");\n\t\t\t\tthis->pub_attract_signal = this->node->Advertise<msgs::Any>(\"/attraction_signal\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tthis->pub_start_sim = this->node->Advertise<msgs::Any>(\"/start_sim\");//control start and stop for simulations\n\t\t\t\tthis->pub_my_Init = this->node->Advertise<msgs::Any>(\"/my_Init\");//publish simulation parameters\n\t\t\t\tthis->start_sim = false;\n\t\t\t\tthis->start_sim2 = false;\n\t\t\t\tthis->pub_model_log_control = this->node->Advertise<msgs::Any>(\"/topic_model_log\");\n\t\t\t\t\n\t\t\t\tthis->pub_experiment_control = this->node->Advertise<msgs::Any>(\"/experiment_control\");\n\t\t\t\tthis->end_experiment = false;\n\t\t\t\t//my_Init();\n\t\t\t\tthis->param_set = false;//Initially params_str is null. so we know it has not been set.\n\n\t\t\t\t//set to invalid value to prevent premature end to simulation\n\t\t\t\tthis->nest_distance_travelled = -900;\n\t\t\t\tthis->exp_dur = 1800; //default experimemnt duration is 1800 except changed from params file\n\t\t\t\t//Handling communication among robots section\n\t\t\t\t/*for (int i = 1; i <= 10;i++)\n\t\t\t\t{\n\t\t\t\t\tstd::string name = \"m_4wrobot\" + to_string(i);\n\t\t\t\t\tthis->pub_repulsion[name] = this->node->Advertise<msgs::Any>(\"/\"+name+\"/comm_signal\");\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t*/\n\t\t\t\t//////////////////////////////////////////////////////////\n\t\t\t\tthis->updateConnection = event::Events::ConnectWorldUpdateBegin(\n\t\t\t\t\t\t\tboost::bind(&WP_Swarm1::OnUpdate,this,_1));\n\t\t\t\t// std::cout<<\"world loaded\"<<std::endl;\n\t\t\t}\n\t\t\tvoid litter_in_nest_cb(ConstAnyPtr &any)\n\t\t\t{\n\t\t\t\tstd::lock_guard<std::mutex> lock(this->mutex);\n\t\t\t\tstd::string nest_msg_str = any->string_value();\n\t\t\t\tif(nest_msg_str.find(\"t,\") == std::string::npos){\n\t\t\t\t\tstd::istringstream stream(nest_msg_str);\n\t\t\t\t\t\n\t\t\t\t\tstd::string t;\n\t\t\t\t\tstd::getline(stream,t,',');\n\t\t\t\t\t\n\t\t\t\t\tstd::string litter_in_nest_str;\n\t\t\t\t\tstd::getline(stream,litter_in_nest_str,',');\n\n\t\t\t\t\tstd::string x,y,theta,nest_dst_travelled;\n\t\t\t\t\tstd::getline(stream,x,',');\n\t\t\t\t\tstd::getline(stream,y,',');\n\t\t\t\t\tstd::getline(stream,theta,',');\n\t\t\t\t\tstd::getline(stream,nest_dst_travelled,',');\n\n\t\t\t\t\t//distance travelled by nest\n\t\t\t\t\tthis->nest_distance_travelled = std::stod(nest_dst_travelled);\n\n\t\t\t\t\tint l = std::stoi(litter_in_nest_str);\n\t\t\t\t\tthis->litter_in_nest = l;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid seen_litter_cb(ConstAnyPtr &any)\n\t\t\t{\n\t\t\t\tstd::lock_guard<std::mutex> lock(this->mutex);\n\t\t\t\tstd::string seen_litter_msg = any->string_value();\n\t\t\t\tsize_t n_loc = seen_litter_msg.find(\":\");\n\t\t\t\tstd::string model_name = seen_litter_msg.substr(0,n_loc);\n\t\t\t\tint seen_litter_num = std::stoi(seen_litter_msg.substr(n_loc+1));\n\t\t\t\t//update appropriate model with it's seen litter\n\t\t\t\tthis->seen_litter_map[model_name] = seen_litter_num;\n\t\t\t}\n\t\t\t\n\t\t\tvoid robot_status_cb(ConstAnyPtr &any)\n\t\t\t{\n\t\t\t\tstd::lock_guard<std::mutex> lock(this->mutex);\n\t\t\t\t\n\t\t\t\tstd::string robot_status_msg = any->string_value();\n\t\t\t\tsize_t n_loc = robot_status_msg.find(\":\");\n\t\t\t\tstd::string model_name = robot_status_msg.substr(0,n_loc);\n\t\t\t\tstd::string robot_status = robot_status_msg.substr(n_loc+1);\n\t\t\t\t\n\t\t\t\tthis->robot_status_map[model_name] = robot_status;\n\t\t\t\t\n\t\t\t\t//std::cout<<model_name<<\" \"<<robot_status<<std::endl;\n\t\t\t}\n\t\t\t\n\t\t\tvoid my_Init()\n\t\t\t{\n\t\t\t\t// std::cout<<\"Init called\"<<std::endl;\n\t\t\t\tmsgs::Any exp_control;\n\t\t\t\texp_control.set_type(msgs::Any::STRING);\n\t\t\t\tstd::string sim_params = \"param:value pairs\";\n\t\t\t\t\n\t\t\t\tif(this->params_str.compare(\"end_simulation\") != 0)\n\t\t\t\t{\n\t\t\t\t\t// sim_params = *(this->param_it);\n\t\t\t\t\tsim_params = this->params_str;\n\n\t\t\t\t\tint area = (int)(this->world_size)*(this->world_size);\n\t\t\t\t\tstd::string x = sim_params;\n\t\t\t\t\tx = x + \n\t\t\t\t\t\t\"no_of_litter:\" + to_string(this->litter_ptr.size())\n\t\t\t\t\t\t+ \",no_of_robots:\" + to_string(this->robot_ptr.size())\n\t\t\t\t\t\t+ \",world_size:\" +\n\t\t\t\t\t\t to_string(area) + \"sqm\";\n\t\t\t\t\texp_control.set_string_value(x);\n\t\t\t\t\tthis->pub_experiment_control->Publish(exp_control);\n\t\t\t\t}\n\t\t\t\tif(this->params_str.compare(\"end_simulation\") == 0)\n\t\t\t\t{\n\t\t\t\t\t// exp_control.set_string_value(\"end\");\n\t\t\t\t\t// this->pub_experiment_control->Publish(exp_control);\n\t\t\t\t\tthis->end_experiment = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t//cout<<\"called\"<<endl;\n\t\t\t\t\n\t\t\t\t//stop all models by sending start_sim = false\n\t\t\t\tmsgs::Any s_sim;\n\t\t\t\ts_sim.set_type(msgs::Any::BOOLEAN);\n\t\t\t\tthis->start_sim = false;//to be double sure that simulation does not start\n\t\t\t\ts_sim.set_bool_value(this->start_sim);\n\t\t\t\tthis->pub_start_sim->Publish(s_sim);\n\t\t\t\t\n\t\t\t\t//reset world\n\t\t\t\tthis->world->Reset();\n\t\t\t\t\n\t\t\t\t//Extract all parameters for this simulation\n\t\t\t\t/*if(this->param_it == this->my_params.end())\n\t\t\t\t{\n\t\t\t\t\tstd::cout<<\"Simulations Ended\"<<endl;\n\t\t\t\t\texit(0);\n\t\t\t\t}*/\n\t\t\t\t\n\t\t\t\t//insert seed for each robot type.\n\t\t\t\tsrand(std::time(nullptr));\n\t\t\t\tfor (auto m:this->robot_ptr)\n\t\t\t\t{\n\t\t\t\t\tstd::string robot_name = m->GetName();\n\t\t\t\t\tsim_params = sim_params + robot_name + \":\" + to_string(rand()) + \",\";\n\t\t\t\t}\n\t\t\t\tstd::string sim_params_mine = sim_params;\n\t\t\t\t\n\t\t\t\t//set parameters of world plugin++++\n\t\t\t\twhile(sim_params_mine.find(\",\") != std::string::npos)\n\t\t\t\t{//loop through all parameters and assign to appropriate variable in plugin\n\t\t\t\t\tsize_t ploc = sim_params_mine.find(\",\");\n\t\t\t\t\tstd::string temp = sim_params_mine.substr(0,ploc);\n\t\t\t\t\t\n\t\t\t\t\tsize_t aloc = temp.find(\":\");\n\t\t\t\t\tstd::string param_name = temp.substr(0,aloc);\n\t\t\t\t\tstd::string param_value_str = temp.substr(aloc+1);\n\t\t\t\t\t// double value  = std::stod(param_value_str);//double value of parameter\n\t\t\t\t\t\n\t\t\t\t\tif(param_name.compare(\"nei_sensing\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->nei_sensing = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t\t//std::cout<<\"nei_sensing = \"<<this->nei_sensing<<endl;\n\t\t\t\t\t\t//break;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"log_rate\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->log_rate = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"max_step_size\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->max_step_size = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"lit_threshold\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->lit_threshold = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\n\t\t\t\t\telse if(param_name.compare(\"A0\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->A0 = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\t\t\t\t\telse if (param_name.compare(\"Ae\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->Ae = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"alpha\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->alpha = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"noise_mean\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->noise_mean = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"noise_std\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->noise_std = std::stod(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"com_model\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->com_model = param_value_str;//communication model is a string\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"cap_com\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->cap_com = std::stoi(param_value_str);//double value of parameter;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"max_step_size\") == 0 and this->set_max_step_size)\n\t\t\t\t\t{\n\t\t\t\t\t\tmsgs::Physics physicsMsg;\n\t\t\t\t\t\tphysicsMsg.set_type(msgs::Physics::ODE);\n\t\t\t\t\t\t\n\t\t\t\t\t\tdouble value = std::stod(param_value_str);\n\t\t\t\t\t\t//this->max_step_size = value;\n\t\t\t\t\t\t//value = 1.0/value;\n\t\t\t\t\t\tphysicsMsg.set_max_step_size(value);\n\t\t\t\t\t\tthis->physicsPub->Publish(physicsMsg);\n\t\t\t\t\t\tthis->set_max_step_size = false;\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"exp_dur\") == 0)\n\t\t\t\t\t{//initialize foraging length\n\t\t\t\t\t\tthis->exp_dur = std::stod(param_value_str);\n\t\t\t\t\t}\n\t\t\t\t\telse if(param_name.compare(\"max_nest_travel\") == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->max_nest_travel = std::stod(param_value_str);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t//cout<<temp<<endl;\n\t\t\t\t\t}\n\t\t\t\t\t//cout<<temp<<endl;\n\t\t\t\t\tsim_params_mine = sim_params_mine.substr(ploc+1);\n\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t//cout<<\"params set\"<<endl;\n\t\t\t\t//this->nei_sensing = 5.0;\n\t\t\t\t\n\t\t\t\t//publish simulation parameters for this set of simulation.\n\t\t\t\tmsgs::Any sim_params_msg;\n\t\t\t\tsim_params_msg.set_type(msgs::Any::STRING);\n\t\t\t\tsim_params_msg.set_string_value(sim_params);\n\t\t\t\tthis->pub_my_Init->Publish(sim_params_msg);\n\t\t\t\t\n\t\t\t\t//noisy data based on normal distro\n\t\t\t\tthis->generator = std::default_random_engine(rand());\n\t\t\t\tthis->noise_distro = std::normal_distribution<double>(this->noise_mean,this->noise_std);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t// (this->param_it)++;//increment iterator to next parameter set;\n\t\t\t\t\n\t\t\t\t//this->param_set = false;\n\t\t\t\tthis->world_info_string = \"\";\n\t\t\t\t\n\t\t\t\tthis->start_sim2 = true;\n\t\t\t\tthis->no_litter = false;//assume there is litter;\n\t\t\t\t\n\t\t\t\tthis->log_timer = 0;//reset log timer.\n\t\t\t\t// std::cout<<\"Init exited\"<<std::endl;\n\t\t\t\tthis->nest_distance_travelled = 0;\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tvoid Params_cb(ConstAnyPtr &a)\n\t\t\t{//set all parameters and set param_set = true when done.\n\t\t\t\tstd::lock_guard<std::mutex> lock(this->mutex);\n\t\t\t\tthis->params_str = a->string_value();\n\t\t\t\t// std::cout<<this->params_str<<std::endl;\n\t\t\t\tthis->param_set = true;\n\t\t\t}\n\t\t\t\n\t\t\tvoid world_gov_experiment_control_cb(ConstAnyPtr &a){\n\t\t\t\t//controls when to start a simulation.\n\t\t\t\tstd::lock_guard<std::mutex> lock(this->mutex);\n\n\t\t\t\tthis->world_gov_experiment_control = a->bool_value();\n\n\t\t\t\t//world governor has been informed that the world is ready to go. Set the world_info_bool to false;\n\t\t\t\tthis->world_info_bool = false;\n\t\t\t}\n\t\t\tvoid OnUpdate(const common::UpdateInfo &_info)\n\t\t\t{\n\t\t\t\tstd::lock_guard<std::mutex> lock(this->mutex);\n\t\t\t\t// std::cout<<_info.simTime<<std::endl;\n\t\t\t\tif(this->param_set)\n\t\t\t\t{//check if parameters have been initialized.\n\t\t\t\t\t\n\t\t\t\t\tthis->my_Init();\n\t\t\t\t\tthis->param_set = false;\n\t\t\t\t}\n\t\t\t\tif(this->end_experiment)\n\t\t\t\t{//Publish this->begin_experiment\n\t\t\t\t\t//std::cout<<\"Simulations Ended\"<<endl;\n\t\t\t\t\texit(0); \n\t\t\t\t}\n\t\t\t\t// if(_info.simTime.sec >= this->exp_dur)\n\t\t\t\t// { //set number of litter to picked litter, so that robots will activate homing state\n\t\t\t\t// \tthis->no_litter = true;\n\t\t\t\t// \tthis->litter_tot = this->litter_in_nest;\n\t\t\t\t// }\n\t\t\t\tif(this->world_info_bool){\n\t\t\t\t\t//At start of simulation, this informs the world governor that the world has been loaded and ready to go\n\t\t\t\t\tmsgs::Any any;\n\t\t\t\t\t//any.set_type(msgs::Any::STRING);\n\t\t\t\t\t//any.set_string_value(\"end\");\n\t\t\t\t\tany.set_type(msgs::Any::BOOLEAN);\n\t\t\t\t\tany.set_bool_value(this->world_info_bool);\n\t\t\t\t\tthis->pub_world_loaded->Publish(any);\n\t\t\t\t\t// this->world_info_bool = false;//to be set to false from world_gov_experiment_control subscriber\n\t\t\t\t}\n\t\t\t\tif(!this->world_gov_experiment_control){\n\t\t\t\t\t//needed to prevent simulation from counting while world-gov-control is set to false\n\t\t\t\t\tthis->world->Reset();\n\t\t\t\t\t// this->end_experiment = this->world_gov_experiment_control;\n\t\t\t\t}\n\t\t\t\tif(/*this->litter_in_nest >= this->litter_tot  */\n\t\t\t\t\tthis->nest_distance_travelled >= this->max_nest_travel\n\t\t\t\t\tor _info.simTime.sec >= this->exp_dur)// or st.sec >= 30)//(true and this->no_litter) or  false and (st.sec >= 300 and st.nsec==0))\n\t\t\t\t{\n\t\t\t\t\t// this->litter_in_nest = 0;\n\t\t\t\t\t// // this->param_set =  true;\n\t\t\t\t\t// msgs::Any s_sim;\n\t\t\t\t\t// s_sim.set_type(msgs::Any::BOOLEAN);\n\t\t\t\t\t// this->start_sim = false;//to be double sure that simulation does not start\n\t\t\t\t\t// s_sim.set_bool_value(this->start_sim);\n\t\t\t\t\t// this->pub_start_sim->Publish(s_sim);\n\t\t\t\t\t// this->world_gov_experiment_control = false;//set to false since a simulation iteration is ended\n\t\t\t\t\t\n\t\t\t\t\t//All litter collected. Alert Governor that you have ended current simulation\n\t\t\t\t\tmsgs::Any exp_control;\n\t\t\t\t\texp_control.set_type(msgs::Any::STRING);\n\t\t\t\t\tstd::string end_sim_str = \"end\"/* + to_string(this->nest_distance_travelled) +\n\t\t\t\t\t\t\t\t\t\t\t\t\",\" + to_string(this->max_nest_travel)*/;\n\t\t\t\t\texp_control.set_string_value(end_sim_str);\n\t\t\t\t\tthis->pub_experiment_control->Publish(exp_control);\n\t\t\t\t\t// std::cout<<\"End Published\"<<std::endl;\n\t\t\t\t\t// return;\n\t\t\t\t\t// this->world->Reset();\n\t\t\t\t\t// exit(0); \n\t\t\t\t}\n\n\t\t\t\tif(this->world_gov_experiment_control and !(this->param_set)) {\n\t\t\t\t\t\t//world governor controls when simulation starts by setting the value of world_gov_experiment_control to true\n\t\t\t\t\t\t//Also, if simulation parameters have been set\n\t\t\t\t\t//std::cout<<_info.simTime.Double()<<std::endl;\n\t\t\t\t\tif(this->start_sim2)\n\t\t\t\t\t{\n\t\t\t\t\t\tmsgs::Any s_sim;\n\t\t\t\t\t\ts_sim.set_type(msgs::Any::BOOLEAN);\n\t\t\t\t\t\tthis->start_sim = true;\n\t\t\t\t\t\ts_sim.set_bool_value(this->start_sim);\n\t\t\t\t\t\tthis->pub_start_sim->Publish(s_sim);\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis->start_sim2 = false;\n\t\t\t\t\t\tthis->log_timer = 0;\n\t\t\t\t\t\t// msgs::Any set_prefix;\n\t\t\t\t\t\t// set_prefix.set_type(msgs::Any::STRING);\n\t\t\t\t\t\t// set_prefix.set_string_value(\"new_file\");\n\t\t\t\t\t\t// this->pub_model_log_control->Publish(set_prefix);\n\t\t\t\t\t}\n\t\t\t\t\tthis->log_timer += this->max_step_size;\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t// if(this->param_set)\n\t\t\t\t\t// {\n\t\t\t\t\t\t\n\t\t\t\t\t// \tthis->my_Init();\n\t\t\t\t\t// \tthis->param_set = false;\n\t\t\t\t\t// }\n\t\t\t\t\t//std::cout<<this->world->GetModelCount()<<endl;\n\t\t\t\t\tgazebo::common::Time st = _info.simTime;\n\t\t\t\t/*\n\t\t\t\t\tif(st.nsec==0)\n\t\t\t\t\t{\n\t\t\t\t\t\tofstream myfile(\"robot_name.txt\",std::ios::app|std::ios::ate);\n\t\t\t\t\t\tmyfile << st.nsec<<std::endl;\n\t\t\t\t\t\tmyfile.close();\n\t\t\t\t\t}*/\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t/*/Start::Testing Seen litter messages\n\t\t\t\t\tstd::string s=\"\";\n\t\t\t\t\tfor(auto it = this->seen_litter_map.begin(); it != this->seen_litter_map.end();it++)\n\t\t\t\t\t{\n\t\t\t\t\t\ts = s + it->first + \":\" + to_string(it->second) + \",\";\n\t\t\t\t\t}\n\t\t\t\t\tstd::cout<<s<<std::endl;\n\t\t\t\t\t/End :: Test seen litter messages*/\n\t\t\t\t\tif(/*this->litter_in_nest >= this->litter_tot or */\n\t\t\t\t\t\tthis->nest_distance_travelled >= this->max_nest_travel\n\t\t\t\t\t\tor st.sec >= this->exp_dur)//(true and this->no_litter) or  false and (st.sec >= 300 and st.nsec==0))\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->litter_in_nest = 0;\n\t\t\t\t\t\t// this->param_set = true;\n\t\t\t\t\t\tmsgs::Any s_sim;\n\t\t\t\t\t\ts_sim.set_type(msgs::Any::BOOLEAN);\n\t\t\t\t\t\tthis->start_sim = false;//to be double sure that simulation does not start\n\t\t\t\t\t\ts_sim.set_bool_value(this->start_sim);\n\t\t\t\t\t\tthis->pub_start_sim->Publish(s_sim);\n\t\t\t\t\t\tthis->world_gov_experiment_control = false;//set to false since a simulation iteration is ended\n\t\t\t\t\t\t\n\t\t\t\t\t\t//All litter collected. Alert Governor that you have ended current simulation\n\t\t\t\t\t\t// msgs::Any exp_control;\n\t\t\t\t\t\t// exp_control.set_string_value(\"end\");\n\t\t\t\t\t\t// this->pub_experiment_control->Publish(exp_control);\n\t\t\t\t\t\t// this->world->Reset();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// for(auto m : this->robot_ptr)\n\t\t\t\t\t\t// {//Get current robot.\n\t\t\t\t\t\t\t// std::string r_name = m->GetName();\n\t\t\t\t\t\t\tmath::Vector3 nest_pos = this->m_nest->GetWorldPose().pos;\n\t\t\t\t\t\t\t// int rep_neighbours = 0;\n\t\t\t\t\t\t\t// std::string rep_data = \"\";\n\t\t\t\t\t\t\tstd::string att_data = \"\";\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdouble rslt_x=0.0,rslt_y=0.0;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor(auto n : this->robot_ptr)\n\t\t\t\t\t\t\t{//Loop through neighbours\n\t\t\t\t\t\t\t\tstd::string n_name = n->GetName();\n\t\t\t\t\t\t\t\tmath::Vector3 n_pos = n->GetWorldPose().pos;\n\t\t\t\t\t\t\t\tint att_neighbours = 0;//initialize attraction neighbours to 0\n\t\t\t\t\t\t\t\t// double rep_signal = 0;\n\t\t\t\t\t\t\t\tdouble att_signal = 0; //initialize attraction signal to 0\n\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\t// std::string n_status = this->robot_status_map[n_name];\n\t\t\t\t\t\t\t\t// int n_seen_litter = this->seen_litter_map[n_name];\n\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\t//std::cout<<n_name<<\" \"<<n_status<<std::endl;\n\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\t// if(n_name.compare(r_name) !=0)\n\t\t\t\t\t\t\t\t// {//If not the current robot do this section\n\t\t\t\t\t\t\t\t\tnest_pos.z = 0;\n\t\t\t\t\t\t\t\t\tn_pos.z = 0;\n\t\t\t\t\t\t\t\t\t// if(abs(r_pos.x - n_pos.x) < this->nei_sensing and\n\t\t\t\t\t\t\t\t\t// \t\tabs(r_pos.y - n_pos.y) < this->nei_sensing)\n\t\t\t\t\t\t\t\t\t// {\n\t\t\t\t\t\t\t\t\t\tdouble dist = nest_pos.Distance(n_pos);\n\t\t\t\t\t\t\t\t\t\t// if(dist <= this->nei_sensing)//neighbour sensing distance... Consider setting parameter at startup\n\t\t\t\t\t\t\t\t\t\t// {\n\t\t\t\t\t\t\t\t\t\t\t// if(n_status.compare(\"searching\")==0 || false)\n\t\t\t\t\t\t\t\t\t\t\t// {\n\t\t\t\t\t\t\t\t\t\t\t// \trep_neighbours += 1;\n\t\t\t\t\t\t\t\t\t\t\t// \tdouble repulsion_intensity = 0;\n\t\t\t\t\t\t\t\t\t\t\t// \tif(this->com_model.compare(\"linear\") == 0){\n\t\t\t\t\t\t\t\t\t\t\t// \t\trepulsion_intensity = (this->nei_sensing - dist)/(this->nei_sensing);\n\t\t\t\t\t\t\t\t\t\t\t// \t}\n\t\t\t\t\t\t\t\t\t\t\t// \telse if(this->com_model.compare(\"sound\") == 0) {\n\t\t\t\t\t\t\t\t\t\t\t// \t\trepulsion_intensity = this->A0 * exp(-dist*(this->alpha)) + this->Ae;\n\t\t\t\t\t\t\t\t\t\t\t// \t\t//add noise\n\t\t\t\t\t\t\t\t\t\t\t// \t\trepulsion_intensity += this->noise_distro(this->generator);\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t// \t}\n\t\t\t\t\t\t\t\t\t\t\t// \telse if(this->com_model.compare(\"soundv2\") == 0){\n\t\t\t\t\t\t\t\t\t\t\t// \t\t//noise_mean is average of fitError/signalStrength and noise_std is the deviation across experiments\n\t\t\t\t\t\t\t\t\t\t\t// \t\tstd::normal_distribution<double> noise_distro_std(this->noise_mean,this->noise_std);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t// \t\t//intensity of pure signal\n\t\t\t\t\t\t\t\t\t\t\t// \t\trepulsion_intensity = this->A0 * exp(-dist*(this->alpha)) + this->Ae;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t// \t\t//noise is proportional to intensity\n\t\t\t\t\t\t\t\t\t\t\t// \t\tdouble signal_std = repulsion_intensity * noise_distro_std(this->generator);\n\n\t\t\t\t\t\t\t\t\t\t\t// \t\t//use proportional value computed as standard deviation\n\t\t\t\t\t\t\t\t\t\t\t// \t\tstd::normal_distribution<double> noise_distro_signal(repulsion_intensity,signal_std);\n\n\t\t\t\t\t\t\t\t\t\t\t// \t\t//noisy repulsion intenisity of communicated signal\n\t\t\t\t\t\t\t\t\t\t\t// \t\trepulsion_intensity = noise_distro_signal(this->generator);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t// \t}\n\t\t\t\t\t\t\t\t\t\t\t// \telse if(this->com_model.compare(\"vector\") == 0) {\n\t\t\t\t\t\t\t\t\t\t\t// \t\t//TO DO\n\t\t\t\t\t\t\t\t\t\t\t// \t}\n\t\t\t\t\t\t\t\t\t\t\t// \t//double repulsion_intensity = (this->nei_sensing - dist)/(this->nei_sensing);\n\t\t\t\t\t\t\t\t\t\t\t// \t/*******************************************************/\n\t\t\t\t\t\t\t\t\t\t\t// \t// double repulsion_intensity = this->A0 * exp(-dist*(this->alpha)) + this->Ae;\n\t\t\t\t\t\t\t\t\t\t\t// \tif(dist > this->nei_sensing and this->cap_com == 1)\n\t\t\t\t\t\t\t\t\t\t\t// \t{//If outside comm range and cap_com is set\n\t\t\t\t\t\t\t\t\t\t\t// \t\trepulsion_intensity = 0;\n\t\t\t\t\t\t\t\t\t\t\t// \t}\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t// \tif(repulsion_intensity < 0)\n\t\t\t\t\t\t\t\t\t\t\t// \t\trepulsion_intensity = 0;\n\t\t\t\t\t\t\t\t\t\t\t// \t/*******************************************************/\n\n\t\t\t\t\t\t\t\t\t\t\t// \trep_signal += repulsion_intensity;\n\t\t\t\t\t\t\t\t\t\t\t// \trep_data = rep_data + \",\" + to_string(dist);\n\t\t\t\t\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t// if(n_seen_litter >= this->lit_threshold)//If seen litter is greater than 5, send an attraction signal\n\t\t\t\t\t\t\t\t\t\t\t// {\n\t\t\t\t\t\t\t\t\t\t\t\t//cout<<\"n_seen_litter:\"<<n_seen_litter<<\" this->lit_threshold:\"<<this->lit_threshold<<endl;\n\t\t\t\t\t\t\t\t\t\t\t\tatt_neighbours += 1;\n\t\t\t\t\t\t\t\t\t\t\t\tdouble attraction_intensity = 0;\n\t\t\t\t\t\t\t\t\t\t\t\tif(this->com_model.compare(\"linear\") == 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\tattraction_intensity = (this->nei_sensing - dist)/(this->nei_sensing);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\telse if(this->com_model.compare(\"sound\") == 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tattraction_intensity = this->A0 * exp(-dist*(this->alpha)) + this->Ae;\n\t\t\t\t\t\t\t\t\t\t\t\t\t//add noise\n\t\t\t\t\t\t\t\t\t\t\t\t\tattraction_intensity += this->noise_distro(this->generator);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\telse if(this->com_model.compare(\"soundv2\") == 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t//noise_mean is average of fitError/signalStrength and noise_std is the deviation across experiments\n\t\t\t\t\t\t\t\t\t\t\t\t\tstd::normal_distribution<double> noise_distro_std1(this->noise_mean,this->noise_std);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t//intensity of pure signal\n\t\t\t\t\t\t\t\t\t\t\t\t\tattraction_intensity = this->A0 * exp(-dist*(this->alpha)) + this->Ae;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t//noise is proportional to intensity\n\t\t\t\t\t\t\t\t\t\t\t\t\tdouble signal_std1 = attraction_intensity * noise_distro_std1(this->generator);\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t//use proportional value computed as standard deviation\n\t\t\t\t\t\t\t\t\t\t\t\t\tstd::normal_distribution<double> noise_distro_signal1(attraction_intensity,signal_std1);\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t//noisy repulsion intenisity of communicated signal\n\t\t\t\t\t\t\t\t\t\t\t\t\tattraction_intensity = noise_distro_signal1(this->generator);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\telse if(this->com_model.compare(\"vector\") == 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t//TO DO\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t// double attraction_intensity = (this->nei_sensing - dist)/(this->nei_sensing);\n\t\t\t\t\t\t\t\t\t\t\t\t/*******************************************************/\n\t\t\t\t\t\t\t\t\t\t\t\t// double attraction_intensity = this->A0 * exp(-dist*(this->alpha)) + this->Ae;\n\n\t\t\t\t\t\t\t\t\t\t\t\tif(dist > this->nei_sensing and this->cap_com == 1)\n\t\t\t\t\t\t\t\t\t\t\t\t{//If outside comm range and cap_com is set\n\t\t\t\t\t\t\t\t\t\t\t\t\tattraction_intensity = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\tif(attraction_intensity < 0)\n\t\t\t\t\t\t\t\t\t\t\t\t\tattraction_intensity = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t/*******************************************************/\n\t\t\t\t\t\t\t\t\t\t\t\tatt_signal += attraction_intensity;\n\t\t\t\t\t\t\t\t\t\t\t\tatt_data = att_data + \",\" + to_string(dist);\n\t\t\t\t\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\t\t\t\t\t//Computing Resultant Vector\n\t\t\t\t\t\t\t\t\t\t\tdouble vec_x,vec_y;\n\t\t\t\t\t\t\t\t\t\t\tvec_x = (nest_pos.x - n_pos.x)/dist;\n\t\t\t\t\t\t\t\t\t\t\tvec_y = (nest_pos.y - n_pos.y)/dist;\n\t\t\t\t\t\t\t\t\t\t\trslt_x += vec_x;\n\t\t\t\t\t\t\t\t\t\t\trslt_y += vec_y;\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\t\t\t\tdouble rslt_theta = atan2(rslt_y,rslt_x);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tmsgs::Any any;\n\t\t\t\t\t\t\t\t\t\t\tany.set_type(msgs::Any::STRING);\n\t\t\t\t\t\t\t\t\t\t\tany.set_string_value(to_string(0) + \":\" + to_string(0)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ \":\" + to_string(rslt_theta) + \":\" + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_string(att_neighbours) + \":\" + to_string(att_signal));\n\t\t\t\t\t\t\t\t\t\t\tthis->pub_commSignal[n_name]->Publish(any);//publish attraction info to the specific robot\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t// \t//any.set_string_value(to_string(att_neighbours) + \":\" + to_string(att_signal));\n\t\t\t\t\t\t// \t//this->pub_attraction[r_name]->Publish(any);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t// \tif(st.nsec==0){//record repulsion once per second.\t\n\t\t\t\t\t\t// \t\trep_data = r_name + \",\" + to_string(rep_signal) + \",\" + to_string(rep_neighbours) + rep_data;\n\t\t\t\t\t\t// \t\tmsgs::Any any2;\n\t\t\t\t\t\t// \t\tany2.set_type(msgs::Any::STRING);\n\t\t\t\t\t\t// \t\tany2.set_string_value(rep_data);\n\t\t\t\t\t\t// \t\tthis->pub_repel_signal->Publish(any2);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t// \t\tatt_data = r_name + \",\" + to_string(att_signal) + \",\" + to_string(att_neighbours) + att_data;\n\t\t\t\t\t\t// \t\tany2.set_string_value(att_data);\n\t\t\t\t\t\t// \t\tthis->pub_attract_signal->Publish(any2);\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\t//std::cout <<this->log_timer << this->log_rate << this->start_sim <<std::endl;\n\t\t\t\t\t\tif( (st.nsec==0 or (this->log_timer >= this->log_rate and this->start_sim)))//rate of 100Hz\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthis->log_timer = 0;\n\t\t\t\t\t\t\tthis->no_litter = true;//Assume there is no litter within world\n\t\t\t\t\t\t\t//std::cout<<this->psec<<endl;\n\t\t\t\t\t\t\tstd::string all_litter_pos = \"\";\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdouble picked_litter = 0;\n\n\t\t\t\t\t\t\tfor(auto m: this->litter_ptr)\n\t\t\t\t\t\t\t{//Get current pose of all litter in world\n\t\t\t\t\t\t\t\tgazebo::math::Vector3 lit_loc = m->GetWorldPose().pos;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(abs(lit_loc.x) < 500 && abs(lit_loc.y) < 500)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tthis->no_litter = false;\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\tpicked_litter += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tall_litter_pos = all_litter_pos + to_string(lit_loc.x) + \",\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ to_string(lit_loc.y) + \":\";\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmsgs::Any all_litter_pos_msg;\n\t\t\t\t\t\t\tall_litter_pos_msg.set_type(msgs::Any::STRING);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tall_litter_pos = to_string(_info.simTime.Double())\n\t\t\t\t\t\t\t\t\t\t\t+ \":\" + all_litter_pos;\n\t\t\t\t\t\t\tall_litter_pos_msg.set_string_value(all_litter_pos);\n\t\t\t\t\t\t\tthis->pub_litter_pose->Publish(all_litter_pos_msg);//publish current pos of all litter\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//this->psec = st.nsec;\n\t\t\t\t\t}\n\t\t\t\t\tif(this->log_timer > this->log_rate)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->log_timer = 0;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t/*if(this->param_set)\n\t\t\t\t\t{\t\t\n\t\t\t\t\t\t//msgs::Any any;\n\t\t\t\t\t\t//any.set_type(msgs::Any::INT32);\n\t\t\t\t\t\t//any.set_int_value(this->robot_ptr.size());\n\t\t\t\t\t\t//any.set_type(msgs::Any::BOOLEAN);\n\t\t\t\t\t\t//any.set_bool_value(true);\n\t\t\t\t\t\tif(st.sec >= 30)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmsgs::Any any;\n\t\t\t\t\t\t\t//any.set_type(msgs::Any::STRING);\n\t\t\t\t\t\t\t//any.set_string_value(\"end\");\n\t\t\t\t\t\t\tany.set_type(msgs::Any::BOOLEAN);\n\t\t\t\t\t\t\tany.set_bool_value(this->world_info_bool);\n\t\t\t\t\t\t\tthis->pub_world_loaded->Publish(any);\n\t\t\t\t\t\t\tthis->world->Reset();\n\t\t\t\t\t\t\tthis->world->Stop();//or this->world->Stop()(or Fini();\n\t\t\t\t\t\t\t//this->Load(this->world,sdf::ElementPtr sdf);\n\t\t\t\t\t\t\t//this->world_info_bool = true;\n\t\t\t\t\t\t\t//this->world->Load\n\t\t\t\t\t\t\t//this->world->Init();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(this->world_info_bool){\n\t\t\t\t\t\tmsgs::Any any;\n\t\t\t\t\t\t//any.set_type(msgs::Any::STRING);\n\t\t\t\t\t\t//any.set_string_value(\"start\");\n\t\t\t\t\t\tany.set_type(msgs::Any::BOOLEAN);\n\t\t\t\t\t\tany.set_bool_value(this->world_info_bool);\n\t\t\t\t\t\tthis->pub_world_loaded->Publish(any);\n\t\t\t\t\t\tthis->world_info_bool = false;\n\t\t\t\t\t}\n\t\t\t\t\t//this->pub_world_loaded->Publish(any);*/\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t};\n\t\n\t//Register this plugin with the simulator\n\tGZ_REGISTER_WORLD_PLUGIN(WP_Swarm1)\n}\n", "meta": {"hexsha": "9fba29c0e43f70e8b3a31227f90067e859ce43c9", "size": 33297, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sources/w_swarm1/wp_swarm1.cc", "max_stars_repo_name": "elcymon/cpfa", "max_stars_repo_head_hexsha": "e5f1c0dfdace9913aee5ef5c6642bc60efef22f2", "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": "sources/w_swarm1/wp_swarm1.cc", "max_issues_repo_name": "elcymon/cpfa", "max_issues_repo_head_hexsha": "e5f1c0dfdace9913aee5ef5c6642bc60efef22f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/w_swarm1/wp_swarm1.cc", "max_forks_repo_name": "elcymon/cpfa", "max_forks_repo_head_hexsha": "e5f1c0dfdace9913aee5ef5c6642bc60efef22f2", "max_forks_repo_licenses": ["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.2033519553, "max_line_length": 149, "alphanum_fraction": 0.6112562693, "num_tokens": 8943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.17477723629155179}}
{"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/lambda/lambda.hpp>\n\n#include \"tudat/simulation/environment_setup/createAerodynamicCoefficientInterface.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\n//! Function to create aerodynamic coefficient settings from coefficients stored in data files\nstd::shared_ptr< AerodynamicCoefficientSettings > readTabulatedAerodynamicCoefficientsFromFiles(\n        const std::map< int, std::string > forceCoefficientFiles,\n        const std::map< int, std::string > momentCoefficientFiles,\n        const double referenceLength,\n        const double referenceArea,\n        const double lateralReferenceLength,\n        const Eigen::Vector3d& momentReferencePoint,\n        const std::vector< aerodynamics::AerodynamicCoefficientsIndependentVariables > independentVariableNames,\n        const bool areCoefficientsInAerodynamicFrame,\n        const bool areCoefficientsInNegativeAxisDirection,\n        const std::shared_ptr< interpolators::InterpolatorSettings > interpolatorSettings )\n{\n    // Retrieve number of independent variables from file.\n    int numberOfIndependentVariables =\n            input_output::getNumberOfIndependentVariablesInCoefficientFile( forceCoefficientFiles.begin( )->second );\n\n    // Call approriate file reading function for N independent variables\n    std::shared_ptr< AerodynamicCoefficientSettings > coefficientSettings;\n    if( numberOfIndependentVariables == 1 )\n    {\n        coefficientSettings = readGivenSizeTabulatedAerodynamicCoefficientsFromFiles< 1 >(\n                    forceCoefficientFiles, momentCoefficientFiles, referenceLength, referenceArea, lateralReferenceLength,\n                    momentReferencePoint, independentVariableNames, areCoefficientsInAerodynamicFrame,\n                    areCoefficientsInNegativeAxisDirection, interpolatorSettings );\n    }\n    else if( numberOfIndependentVariables == 2 )\n    {\n        coefficientSettings = readGivenSizeTabulatedAerodynamicCoefficientsFromFiles< 2 >(\n                    forceCoefficientFiles, momentCoefficientFiles, referenceLength, referenceArea, lateralReferenceLength,\n                    momentReferencePoint, independentVariableNames, areCoefficientsInAerodynamicFrame,\n                    areCoefficientsInNegativeAxisDirection, interpolatorSettings );\n    }\n    else if( numberOfIndependentVariables == 3 )\n    {\n        coefficientSettings = readGivenSizeTabulatedAerodynamicCoefficientsFromFiles< 3 >(\n                    forceCoefficientFiles, momentCoefficientFiles, referenceLength, referenceArea, lateralReferenceLength,\n                    momentReferencePoint, independentVariableNames, areCoefficientsInAerodynamicFrame,\n                    areCoefficientsInNegativeAxisDirection, interpolatorSettings );\n    }\n    else\n    {\n        throw std::runtime_error( \"Error when reading aerodynamic coefficient settings from file, found \" +\n                                  std::to_string( numberOfIndependentVariables ) +\n                                  \" independent variables, up to 3 currently supported\" );\n    }\n    return coefficientSettings;\n}\n\n//! Function to create aerodynamic coefficient settings from coefficients stored in data files\nstd::shared_ptr< AerodynamicCoefficientSettings >\nreadTabulatedAerodynamicCoefficientsFromFiles(\n        const std::map< int, std::string > forceCoefficientFiles,\n        const double referenceArea,\n        const std::vector< aerodynamics::AerodynamicCoefficientsIndependentVariables > independentVariableNames,\n        const bool areCoefficientsInAerodynamicFrame,\n        const bool areCoefficientsInNegativeAxisDirection,\n        const std::shared_ptr< interpolators::InterpolatorSettings > interpolatorSettings )\n{\n    // Retrieve number of independent variables from file.\n    int numberOfIndependentVariables =\n            input_output::getNumberOfIndependentVariablesInCoefficientFile( forceCoefficientFiles.begin( )->second );\n\n    // Call approriate file reading function for N independent variables\n    std::shared_ptr< AerodynamicCoefficientSettings > coefficientSettings;\n    if( numberOfIndependentVariables == 1 )\n    {\n        coefficientSettings = readGivenSizeTabulatedAerodynamicCoefficientsFromFiles< 1 >(\n                    forceCoefficientFiles, referenceArea, independentVariableNames,\n                    areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection, interpolatorSettings );\n    }\n    else if( numberOfIndependentVariables == 2 )\n    {\n        coefficientSettings = readGivenSizeTabulatedAerodynamicCoefficientsFromFiles< 2 >(\n                    forceCoefficientFiles, referenceArea, independentVariableNames,\n                    areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection, interpolatorSettings );\n    }\n    else if( numberOfIndependentVariables == 3 )\n    {\n        coefficientSettings = readGivenSizeTabulatedAerodynamicCoefficientsFromFiles< 3 >(\n                    forceCoefficientFiles, referenceArea, independentVariableNames,\n                    areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection, interpolatorSettings );\n    }\n    else\n    {\n        throw std::runtime_error( \"Error when reading aerodynamic coefficient settings from file, found \" +\n                                  std::to_string( numberOfIndependentVariables ) +\n                                  \" independent variables, up to 3 currently supported\" );\n    }\n    return coefficientSettings;\n}\n\n//! Function to create an aerodynamic coefficient interface containing constant coefficients.\nstd::shared_ptr< aerodynamics::AerodynamicCoefficientInterface >\ncreateConstantCoefficientAerodynamicCoefficientInterface(\n        const Eigen::Vector3d constantForceCoefficient,\n        const Eigen::Vector3d constantMomentCoefficient,\n        const double referenceLength,\n        const double referenceArea,\n        const double lateralReferenceLength,\n        const Eigen::Vector3d& momentReferencePoint,\n        const bool areCoefficientsInAerodynamicFrame,\n        const bool areCoefficientsInNegativeAxisDirection )\n{\n    // Create coefficient interface\n    std::shared_ptr< aerodynamics::AerodynamicCoefficientInterface > coefficientInterface =\n            std::make_shared< aerodynamics::CustomAerodynamicCoefficientInterface >(\n                [ = ]( const std::vector< double >& ){ return constantForceCoefficient; },\n                [ = ]( const std::vector< double >& ){ return constantMomentCoefficient; },\n                referenceLength, referenceArea, lateralReferenceLength, momentReferencePoint,\n                std::vector< aerodynamics::AerodynamicCoefficientsIndependentVariables >( ),\n                areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection );\n    coefficientInterface->updateFullCurrentCoefficients( std::vector< double >( ) );\n    return coefficientInterface;\n}\n\n//! Function to create an aerodynamic coefficient interface containing constant coefficients.\nstd::shared_ptr< aerodynamics::AerodynamicCoefficientInterface >\ncreateZeroParameterAerodynamicCoefficientInterface(\n        const std::function< Eigen::Vector3d( ) > constantForceCoefficientFunction,\n        const std::function< Eigen::Vector3d( ) > constantMomentCoefficientFunction,\n        const double referenceLength,\n        const double referenceArea,\n        const double lateralReferenceLength,\n        const Eigen::Vector3d& momentReferencePoint,\n        const bool areCoefficientsInAerodynamicFrame,\n        const bool areCoefficientsInNegativeAxisDirection )\n{\n    // Create coefficient interface\n    std::shared_ptr< aerodynamics::AerodynamicCoefficientInterface > coefficientInterface =\n            std::make_shared< aerodynamics::CustomAerodynamicCoefficientInterface >(\n                [ = ]( const std::vector< double >& ){ return constantForceCoefficientFunction( ); },\n                [ = ]( const std::vector< double >& ){ return constantMomentCoefficientFunction( ); },\n                referenceLength, referenceArea, lateralReferenceLength, momentReferencePoint,\n                std::vector< aerodynamics::AerodynamicCoefficientsIndependentVariables >( ),\n                areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection );\n    coefficientInterface->updateFullCurrentCoefficients( std::vector< double >( ) );\n    return coefficientInterface;\n}\n\n//! Factory function for tabulated (1-D independent variables) aerodynamic coefficient interface from coefficient settings.\nstd::shared_ptr< aerodynamics::AerodynamicCoefficientInterface >\ncreateUnivariateTabulatedCoefficientAerodynamicCoefficientInterface(\n        const std::shared_ptr< AerodynamicCoefficientSettings > coefficientSettings,\n        const std::string& body )\n{\n    using namespace tudat::interpolators;\n\n    // Check consistency of type.\n    std::shared_ptr< TabulatedAerodynamicCoefficientSettings< 1 > > tabulatedCoefficientSettings =\n            std::dynamic_pointer_cast< TabulatedAerodynamicCoefficientSettings< 1 > >( coefficientSettings );\n    if( tabulatedCoefficientSettings == nullptr )\n    {\n        throw std::runtime_error(\n                    \"Error, expected tabulated aerodynamic coefficients of size \" +\n                    std::to_string( 1 ) + \"for body \" + body );\n    }\n    else\n    {\n\n        // Retrieve or generate interpolation settings\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector3d > > forceInterpolator;\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector3d > > momentInterpolator;\n        if ( tabulatedCoefficientSettings->getInterpolatorSettings( ) == nullptr )\n        {\n            forceInterpolator = createOneDimensionalInterpolator( tabulatedCoefficientSettings->getForceCoefficients( ),\n                                                                  std::make_shared< InterpolatorSettings >( linear_interpolator ) );\n            momentInterpolator = createOneDimensionalInterpolator( tabulatedCoefficientSettings->getForceCoefficients( ),\n                                                                   std::make_shared< InterpolatorSettings >( linear_interpolator ) );\n        }\n        else\n        {\n            forceInterpolator = createOneDimensionalInterpolator( tabulatedCoefficientSettings->getForceCoefficients( ),\n                                                                  std::dynamic_pointer_cast< InterpolatorSettings >(\n                                                                      tabulatedCoefficientSettings->getInterpolatorSettings( ) ) );\n            momentInterpolator = createOneDimensionalInterpolator( tabulatedCoefficientSettings->getForceCoefficients( ),\n                                                                   std::dynamic_pointer_cast< InterpolatorSettings >(\n                                                                       tabulatedCoefficientSettings->getInterpolatorSettings( ) ) );\n        }\n\n        // Create aerodynamic coefficient interface.\n        return  std::make_shared< aerodynamics::CustomAerodynamicCoefficientInterface >(\n                    std::bind( &Interpolator< double, Eigen::Vector3d >::interpolate, forceInterpolator, std::placeholders::_1 ),\n                    std::bind( &Interpolator< double, Eigen::Vector3d >::interpolate, momentInterpolator, std::placeholders::_1 ),\n                    tabulatedCoefficientSettings->getReferenceLength( ),\n                    tabulatedCoefficientSettings->getReferenceArea( ),\n                    tabulatedCoefficientSettings->getReferenceLength( ),\n                    tabulatedCoefficientSettings->getMomentReferencePoint( ),\n                    tabulatedCoefficientSettings->getIndependentVariableNames( ),\n                    tabulatedCoefficientSettings->getAreCoefficientsInAerodynamicFrame( ),\n                    tabulatedCoefficientSettings->getAreCoefficientsInNegativeAxisDirection( ) );\n    }\n}\n\n//! Function to create and aerodynamic coefficient interface.\nstd::shared_ptr< aerodynamics::AerodynamicCoefficientInterface >\ncreateAerodynamicCoefficientInterface(\n        const std::shared_ptr< AerodynamicCoefficientSettings > coefficientSettings,\n        const std::string& body )\n{\n    using namespace tudat::aerodynamics;\n\n    std::shared_ptr< AerodynamicCoefficientInterface > coefficientInterface;\n\n    // Check type of interface that is to be created.\n    switch( coefficientSettings->getAerodynamicCoefficientType( ) )\n    {\n    case constant_aerodynamic_coefficients:\n    {\n        // Check consistency of type.\n        std::shared_ptr< ConstantAerodynamicCoefficientSettings > constantCoefficientSettings =\n                std::dynamic_pointer_cast< ConstantAerodynamicCoefficientSettings >(\n                    coefficientSettings );\n        if( constantCoefficientSettings == nullptr )\n        {\n            throw std::runtime_error(\n                        \"Error, expected constant aerodynamic coefficients for body \" + body );\n        }\n        else\n        {\n            // create constant interface.\n            coefficientInterface = createConstantCoefficientAerodynamicCoefficientInterface(\n                        constantCoefficientSettings->getConstantForceCoefficient( ),\n                        constantCoefficientSettings->getConstantMomentCoefficient( ),\n                        constantCoefficientSettings->getReferenceLength( ),\n                        constantCoefficientSettings->getReferenceArea( ),\n                        constantCoefficientSettings->getReferenceLength( ),\n                        constantCoefficientSettings->getMomentReferencePoint( ),\n                        constantCoefficientSettings->getAreCoefficientsInAerodynamicFrame( ),\n                        constantCoefficientSettings->getAreCoefficientsInNegativeAxisDirection( ) );\n        }\n        break;\n    }\n    case custom_aerodynamic_coefficients:\n    {\n        // Check consistency of type.\n        std::shared_ptr< CustomAerodynamicCoefficientSettings > customCoefficientSettings =\n                std::dynamic_pointer_cast< CustomAerodynamicCoefficientSettings >(\n                    coefficientSettings );\n        if( customCoefficientSettings == nullptr )\n        {\n            throw std::runtime_error(\n                        \"Error, expected custom aerodynamic coefficients for body \" + body );\n        }\n        else\n        {\n            // create constant interface.\n            coefficientInterface = std::make_shared< CustomAerodynamicCoefficientInterface >(\n                        customCoefficientSettings->getForceCoefficientFunction( ),\n                        customCoefficientSettings->getMomentCoefficientFunction( ),\n                        customCoefficientSettings->getReferenceLength( ),\n                        customCoefficientSettings->getReferenceArea( ),\n                        customCoefficientSettings->getReferenceLength( ),\n                        customCoefficientSettings->getMomentReferencePoint( ),\n                        customCoefficientSettings->getIndependentVariableNames( ),\n                        customCoefficientSettings->getAreCoefficientsInAerodynamicFrame( ),\n                        customCoefficientSettings->getAreCoefficientsInNegativeAxisDirection( ) );\n        }\n        break;\n    }\n    case tabulated_coefficients:\n    {\n        // Check number of dimensions of tabulated coefficients.\n        int numberOfDimensions = coefficientSettings->getIndependentVariableNames( ).size( );\n        switch( numberOfDimensions )\n        {\n        case 1:\n        {\n            coefficientInterface = createUnivariateTabulatedCoefficientAerodynamicCoefficientInterface(\n                        coefficientSettings, body );\n            break;\n        }\n        case 2:\n        {\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 2 >(\n                        coefficientSettings, body );\n            break;\n        }\n        case 3:\n        {\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 3 >(\n                        coefficientSettings, body );\n            break;\n        }\n        case 4:\n        {\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 4 >(\n                        coefficientSettings, body );\n            break;\n        }\n        case 5:\n        {\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 5 >(\n                        coefficientSettings, body );\n            break;\n        }\n        case 6:\n        {\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 6 >(\n                        coefficientSettings, body );\n            break;\n        }\n        default:\n            throw std::runtime_error( \"Error when making tabulated aerodynamic coefficient interface, \" +\n                                      std::to_string( numberOfDimensions ) + \" dimensions not yet implemented\" );\n        }\n        break;\n    }\n    case scaled_coefficients:\n    {\n        // Check consistency of type and class.\n        std::shared_ptr< ScaledAerodynamicCoefficientInterfaceSettings > scaledCoefficientSettings =\n                std::dynamic_pointer_cast< ScaledAerodynamicCoefficientInterfaceSettings >(\n                    coefficientSettings );\n        if( scaledCoefficientSettings == nullptr )\n        {\n            throw std::runtime_error(\n                        \"Error, expected scaled aerodynamic coefficient settings for body \" + body );\n        }\n        else\n        {\n            std::shared_ptr< AerodynamicCoefficientInterface > baseInterface = createAerodynamicCoefficientInterface(\n                        scaledCoefficientSettings->getBaseSettings( ), body );\n            coefficientInterface = std::make_shared< ScaledAerodynamicCoefficientInterface >(\n                        baseInterface, scaledCoefficientSettings->getForceScaling( ),\n                        scaledCoefficientSettings->getMomentScaling( ), scaledCoefficientSettings->getIsScalingAbsolute( ) );\n        }\n        break;\n    }\n    default:\n        throw std::runtime_error( \"Error, do not recognize aerodynamic coefficient settings for \" + body );\n    }\n\n    // Create and set control surfaces\n    if( coefficientSettings->getControlSurfaceSettings( ).size( ) != 0 )\n    {\n        std::map< std::string, std::shared_ptr< ControlSurfaceIncrementAerodynamicInterface > >\n                controlSurfaceIncrementInterfaces;\n        std::map< std::string, std::shared_ptr< ControlSurfaceIncrementAerodynamicCoefficientSettings > >\n                controlSurfaceSettings = coefficientSettings->getControlSurfaceSettings( );\n        for( std::map< std::string, std::shared_ptr< ControlSurfaceIncrementAerodynamicCoefficientSettings > >::iterator\n             settingIterator = controlSurfaceSettings.begin( ); settingIterator != controlSurfaceSettings.end( );\n             settingIterator++ )\n        {\n            controlSurfaceIncrementInterfaces[ settingIterator->first ] =\n                    createControlSurfaceIncrementAerodynamicCoefficientInterface(\n                        settingIterator->second, body );\n        }\n        coefficientInterface->setControlSurfaceIncrements( controlSurfaceIncrementInterfaces );\n\n    }\n\n    return coefficientInterface;\n}\n\n} // simulation_setup\n\n} // tudat\n", "meta": {"hexsha": "2eaafe94ef94e434557d287d6474f9219fcc1760", "size": 19799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/environment_setup/createAerodynamicCoefficientInterface.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/simulation/environment_setup/createAerodynamicCoefficientInterface.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/simulation/environment_setup/createAerodynamicCoefficientInterface.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": 52.2401055409, "max_line_length": 133, "alphanum_fraction": 0.6764988131, "num_tokens": 3582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.17475744312321204}}
{"text": "#ifndef VISCOELASTICTRANSFORMER_HPP\n#define VISCOELASTICTRANSFORMER_HPP\n\n#include <Eigen/Dense>\n#include \"NeighbourFinder.hpp\"\n#include <iostream>\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>\n#include \"helper_functions.hpp\"\n\ntypedef Eigen::Vector3f Vec3Float;\ntypedef Eigen::VectorXf VecDynFloat;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, 3> Vec3Mat; //matrix Mx3 of type float\ntypedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic> MatDynFloat;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat; //matrix Mx6 of type float\ntypedef Eigen::Matrix< int, Eigen::Dynamic, 3> FacesMat;\ntypedef OpenMesh::DefaultTraits MyTraits;\ntypedef OpenMesh::TriMesh_ArrayKernelT<MyTraits>  TriMesh;\n\nnamespace registration{\n\nclass ViscoElasticTransformer\n{\n    public:\n\n        void set_input(const FeatureMat * const inCorrespondingFeatures,\n                       const VecDynFloat * const inWeights,\n                       const VecDynFloat * const inFlags,\n                       const FacesMat * const inFloatingFaces);\n        void set_output(FeatureMat * const ioFloatingFeatures);\n        void set_parameters(size_t numNeighbours = 10, float sigma = 3.0,\n                            size_t viscousIterations = 10, size_t elasticIterations = 10);\n        Vec3Mat get_transformation() const {return _displacementField;}\n        void update();\n\n    protected:\n\n    private:\n        //# Inputs\n        //##_ioFeatures is used as both an input (to compute the transformation) and output\n        const FeatureMat * _inCorrespondingFeatures = NULL;\n        const VecDynFloat * _inWeights = NULL;\n        const VecDynFloat * _inFlags = NULL;\n        const FacesMat * _inFloatingFaces = NULL;\n\n        //# Outputs\n        FeatureMat * _ioFloatingFeatures = NULL;\n\n\n        //# User Parameters\n        size_t _numNeighbours = 10;\n        float _sigma = 3.0;\n        size_t _viscousIterations = 0;\n        size_t _elasticIterations = 0;\n        size_t _outlierDiffusionIterations = 15;\n\n        //# Internal Data structures\n        Vec3Mat _displacementField;\n        Vec3Mat _oldDisplacementField;\n        NeighbourFinder<Vec3Mat> _neighbourFinder;\n        MatDynFloat _smoothingWeights;\n        TriMesh _floatingMesh;\n\n        //# Internal Parameters\n        size_t _numElements = 0;\n        bool _neighboursOutdated = true;\n        bool _flagsOutdated = true;\n        const float _minWeight = 0.00001f;\n\n        //# Internal functions\n        //## Update the neighbour finder\n        void _update_neighbours();\n        //## Update the weights used for smoothing\n        void _update_smoothing_weights();\n        //## Update the displacement field in a viscous manner\n        void _update_viscously();\n        //## Update the displacement field in an elastic manner\n        void _update_elastically();\n        //## Update the transformation for any outliers (via a diffusion process)\n        void _update_outlier_transformation();\n        //## Function to update the transformation\n        void _update_transformation();\n        //## Function to apply the transformation\n        void _apply_transformation();\n};\n\n}//namespace registration\n\n#endif // VISCOELASTICTRANSFORMER_HPP\n", "meta": {"hexsha": "61ae4d6a961029085b5a7c11041e2afe5d8ff31a", "size": 3253, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ViscoElasticTransformer.hpp", "max_stars_repo_name": "alorcas/meshmonk", "max_stars_repo_head_hexsha": "8090d4e137222e7a65d4868b5a639eb61daba917", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T14:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T05:40:58.000Z", "max_issues_repo_path": "src/ViscoElasticTransformer.hpp", "max_issues_repo_name": "alorcas/meshmonk", "max_issues_repo_head_hexsha": "8090d4e137222e7a65d4868b5a639eb61daba917", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T10:34:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T04:37:12.000Z", "max_forks_repo_path": "src/ViscoElasticTransformer.hpp", "max_forks_repo_name": "alorcas/meshmonk", "max_forks_repo_head_hexsha": "8090d4e137222e7a65d4868b5a639eb61daba917", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-07-05T14:59:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T07:01:47.000Z", "avg_line_length": 36.1444444444, "max_line_length": 112, "alphanum_fraction": 0.6815247464, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.1746049134041139}}
{"text": "#include <iostream>\n#include <vector>\n#include <set>\n#include <tuple>\n#include <Eigen/Dense>\n#include <math.h>\n#include <cosan/io/utils.h>\nint main(int argc, char *argv[]){\n    CosanMatrix X;\n    std::string SummaryMessageX;\n    std::vector<std::vector<uint>> IdxpinfX,IdxminfX,IdxmissingX;\n    std::set<uint> colCatX;\n    uint rowsX = 0,colsX = 0;\n    std::vector<std::string> svaluesX;\n//    std::cout<<isinf(stod(std::string(\"inf\")))<<std::endl;\n//    std::tie(rowsX,colsX,SummaryMessageX) = _load_csv<Eigen::MatrixXd>(argv[1],X,IdxpinfX,IdxminfX,IdxmissingX,svaluesX,colCatX);\n    std::cout<<rowsX<<\" \"<<colsX<<\" \"<<std::endl;\n    for (auto each : IdxpinfX) {std::cout<<each[0]<<\" \"<<each[1]<<std::endl;}\n    for (auto each : IdxminfX) {std::cout<<each[0]<<\" \"<<each[1]<<std::endl;}\n    for (auto each : IdxmissingX) {std::cout<<each[0]<<\" \"<<each[1]<<std::endl;}\n    for (auto each : colCatX) {std::cout<<each<<std::endl;}\n    for (auto each : svaluesX) {std::cout<<each<<std::endl;}\n    std::cout<<X<<std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "f3c3d0dc1928a9c4855b96ad41e6df3345b8698c", "size": 1034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/io/test2.cpp", "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "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/io/test2.cpp", "max_issues_repo_name": "zhxinyu/cosan", "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_issues_repo_licenses": ["MIT"], "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/io/test2.cpp", "max_forks_repo_name": "zhxinyu/cosan", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "avg_line_length": 39.7692307692, "max_line_length": 131, "alphanum_fraction": 0.6305609284, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17460491340411385}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  Defines the abstraction for SIMD registers\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_DETAIL_PACK_OPERATORS_HPP_INCLUDED\n#define BOOST_SIMD_DETAIL_PACK_OPERATORS_HPP_INCLUDED\n\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/modulo.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/is_less_equal.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/is_greater_equal.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/bitwise_or.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/complement.hpp>\n#include <boost/simd/function/logical_not.hpp>\n#include <boost/simd/function/shift_left.hpp>\n#include <boost/simd/function/shift_right.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/logical_or.hpp>\n#include <boost/simd/function/logical_not.hpp>\n#include <boost/simd/function/unary_plus.hpp>\n#include <boost/simd/function/unary_minus.hpp>\n#include <boost/simd/detail/brigand.hpp>\n\n#include <boost/simd/meta/is_pack.hpp>\n\nnamespace boost { namespace simd\n{\n\n#define BOOST_SIMD_PACK_DEFINE_OP(type_, op, f)                                                    \\\n  template <typename T, std::size_t N, typename U> BOOST_FORCEINLINE                               \\\n  typename std::enable_if<is_not_pack_t<U>::value, pack<type_, N>>::type                           \\\n  op(pack<T, N> const& p0, U const& s1) BOOST_NOEXCEPT { return f(p0, s1); }                       \\\n                                                                                                   \\\n  template <typename T, std::size_t N, typename U> BOOST_FORCEINLINE                               \\\n  typename std::enable_if<is_not_pack_t<U>::value, pack<type_, N>>::type                           \\\n  op(U const& s0, pack<T, N> const& p1) BOOST_NOEXCEPT { return f(s0, p1); }                       \\\n                                                                                                   \\\n  template <typename T, std::size_t N> BOOST_FORCEINLINE                                           \\\n  auto op(pack<T, N> const& p0, pack<T, N> const& p1) BOOST_NOEXCEPT                               \\\n  -> decltype(f(p0, p1)) { return f(p0, p1); }                                                     \\\n/**/\n\nBOOST_SIMD_PACK_DEFINE_OP(T, operator+, plus)\nBOOST_SIMD_PACK_DEFINE_OP(T, operator-, minus)\nBOOST_SIMD_PACK_DEFINE_OP(T, operator%, modulo)\nBOOST_SIMD_PACK_DEFINE_OP(T, operator/, divides)\nBOOST_SIMD_PACK_DEFINE_OP(T, operator*, multiplies)\n\nBOOST_SIMD_PACK_DEFINE_OP(T, operator&, bitwise_and)\nBOOST_SIMD_PACK_DEFINE_OP(T, operator|, bitwise_or)\nBOOST_SIMD_PACK_DEFINE_OP(T, operator^, bitwise_xor)\nBOOST_SIMD_PACK_DEFINE_OP(logical<T>, operator&&, logical_and)\nBOOST_SIMD_PACK_DEFINE_OP(logical<T>, operator||, logical_or)\n\nBOOST_SIMD_PACK_DEFINE_OP(T, operator << , shift_left)\nBOOST_SIMD_PACK_DEFINE_OP(T, operator >> , shift_right)\n\nBOOST_SIMD_PACK_DEFINE_OP(logical<T>, operator<,  is_less)\nBOOST_SIMD_PACK_DEFINE_OP(logical<T>, operator>,  is_greater)\nBOOST_SIMD_PACK_DEFINE_OP(logical<T>, operator==, is_equal)\nBOOST_SIMD_PACK_DEFINE_OP(logical<T>, operator<=, is_less_equal)\nBOOST_SIMD_PACK_DEFINE_OP(logical<T>, operator>=, is_greater_equal)\nBOOST_SIMD_PACK_DEFINE_OP(logical<T>, operator!=, is_not_equal)\n\n#undef BOOST_SIMD_PACK_DEFINE_OP\n\n  template <typename T, std::size_t N>\n  BOOST_FORCEINLINE pack<as_logical_t<T>,N> operator!(pack<T,N> const& a) BOOST_NOEXCEPT\n  {\n    return logical_not(a);\n  }\n\n} }\n\n#endif\n", "meta": {"hexsha": "428474ba06f42d5bd75b63a1d1322213ad9b6cc3", "size": 4074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/detail/pack_operators.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/detail/pack_operators.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/detail/pack_operators.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": 44.2826086957, "max_line_length": 100, "alphanum_fraction": 0.6352479136, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.17460490644290066}}
{"text": "// Copyright 2020 The Defold Foundation\n// Licensed under the Defold License version 1.0 (the \"License\"); you may not use\n// this file except in compliance with the License.\n//\n// You may obtain a copy of the License, together with FAQs at\n// https://www.defold.com/license\n//\n// Unless required by applicable law or agreed to in writing, software distributed\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n// specific language governing permissions and limitations under the License.\n\n#include \"res_convex_shape.h\"\n\n#include <dlib/log.h>\n\n#include \"gamesys.h\"\n#include <gamesys/physics_ddf.h>\n\n/*\n * NOTE: Convex-shape is obsolete and the code below is not currently in use\n * We currently embed external convex shape resources into the collisionshape at compile-time\n */\n\nnamespace dmGameSystem\n{\n    bool AcquireResources(dmResource::HFactory factory,\n                           PhysicsContext* context,\n                           const void* buffer, uint32_t buffer_size,\n                           ConvexShapeResource* resource,\n                           const char* filename)\n    {\n        dmPhysicsDDF::ConvexShape* convex_shape;\n        dmDDF::Result e = dmDDF::LoadMessage<dmPhysicsDDF::ConvexShape>(buffer, buffer_size, &convex_shape);\n        if ( e != dmDDF::RESULT_OK )\n        {\n            return false;\n        }\n\n        bool result = true;\n        switch (convex_shape->m_ShapeType)\n        {\n        case dmPhysicsDDF::ConvexShape::TYPE_SPHERE:\n            if (convex_shape->m_Data.m_Count != 1)\n            {\n                dmLogError(\"Invalid sphere shape\");\n                result = false;\n            }\n            else\n            {\n                if (context->m_3D)\n                    resource->m_Shape3D = dmPhysics::NewSphereShape3D(context->m_Context3D, convex_shape->m_Data[0]);\n                else\n                    resource->m_Shape2D = dmPhysics::NewCircleShape2D(context->m_Context2D, convex_shape->m_Data[0]);\n            }\n            break;\n        case dmPhysicsDDF::ConvexShape::TYPE_BOX:\n            if (convex_shape->m_Data.m_Count != 3)\n            {\n                dmLogError(\"Invalid box shape\");\n                result = false;\n            }\n            else\n            {\n                if (context->m_3D)\n                    resource->m_Shape3D = dmPhysics::NewBoxShape3D(context->m_Context3D, dmVMath::Vector3(convex_shape->m_Data[0], convex_shape->m_Data[1], convex_shape->m_Data[2]));\n                else\n                    resource->m_Shape2D = dmPhysics::NewBoxShape2D(context->m_Context2D, dmVMath::Vector3(convex_shape->m_Data[0], convex_shape->m_Data[1], convex_shape->m_Data[2]));\n            }\n            break;\n        case dmPhysicsDDF::ConvexShape::TYPE_CAPSULE:\n            if (convex_shape->m_Data.m_Count != 2)\n            {\n                dmLogError(\"Invalid capsule shape\");\n                result = false;\n            }\n            else\n            {\n                if (context->m_3D)\n                    resource->m_Shape3D = dmPhysics::NewCapsuleShape3D(context->m_Context3D, convex_shape->m_Data[0], convex_shape->m_Data[1]);\n                else\n                    // TODO: Add support\n                    dmLogError(\"%s\", \"Capsules are not supported in 2D.\");\n            }\n            break;\n        case dmPhysicsDDF::ConvexShape::TYPE_HULL:\n            if (convex_shape->m_Data.m_Count < 9)\n            {\n                dmLogError(\"Invalid hull shape\");\n                result = false;\n            }\n            else\n            {\n                if (context->m_3D)\n                    resource->m_Shape3D = dmPhysics::NewConvexHullShape3D(context->m_Context3D, &convex_shape->m_Data[0], convex_shape->m_Data.m_Count / 3);\n                else\n                {\n                    const uint32_t data_size = 2 * convex_shape->m_Data.m_Count / 3;\n                    float* data_2d = new float[2 * convex_shape->m_Data.m_Count / 3];\n                    for (uint32_t i = 0; i < data_size; ++i)\n                    {\n                        data_2d[i] = convex_shape->m_Data[i/2*3 + i%2];\n                    }\n                    resource->m_Shape2D = dmPhysics::NewPolygonShape2D(context->m_Context2D, data_2d, data_size/2);\n                    delete [] data_2d;\n                }\n            }\n            break;\n        }\n\n        dmDDF::FreeMessage(convex_shape);\n        return result;\n    }\n\n    dmResource::Result ResConvexShapeCreate(const dmResource::ResourceCreateParams& params)\n    {\n        ConvexShapeResource* convex_shape = new ConvexShapeResource();\n        convex_shape->m_3D = ((PhysicsContext*) params.m_Context)->m_3D;\n        if (AcquireResources(params.m_Factory, (PhysicsContext*) params.m_Context, params.m_Buffer, params.m_BufferSize, convex_shape, params.m_Filename))\n        {\n            params.m_Resource->m_Resource = convex_shape;\n            return dmResource::RESULT_OK;\n        }\n        else\n        {\n            delete convex_shape;\n            return dmResource::RESULT_FORMAT_ERROR;\n        }\n    }\n\n    void ReleaseResources(ConvexShapeResource* resource)\n    {\n        if (resource->m_Shape3D)\n        {\n            if (resource->m_3D)\n                dmPhysics::DeleteCollisionShape3D(resource->m_Shape3D);\n            else\n                dmPhysics::DeleteCollisionShape2D(resource->m_Shape2D);\n        }\n    }\n\n    dmResource::Result ResConvexShapeDestroy(const dmResource::ResourceDestroyParams& params)\n    {\n        ConvexShapeResource* convex_shape = (ConvexShapeResource*)params.m_Resource->m_Resource;\n        ReleaseResources(convex_shape);\n        delete convex_shape;\n        return dmResource::RESULT_OK;\n    }\n\n    dmResource::Result ResConvexShapeRecreate(const dmResource::ResourceRecreateParams& params)\n    {\n        ConvexShapeResource* cs_resource = (ConvexShapeResource*)params.m_Resource->m_Resource;\n        ConvexShapeResource tmp_convex_shape;\n        PhysicsContext* physics_context = (PhysicsContext*) params.m_Context;\n        tmp_convex_shape.m_3D = physics_context->m_3D;\n        if (AcquireResources(params.m_Factory, (PhysicsContext*) params.m_Context, params.m_Buffer, params.m_BufferSize, &tmp_convex_shape, params.m_Filename))\n        {\n            if (physics_context->m_3D)\n                dmPhysics::ReplaceShape3D(physics_context->m_Context3D, cs_resource->m_Shape3D, tmp_convex_shape.m_Shape3D);\n            else\n                dmPhysics::ReplaceShape2D(physics_context->m_Context2D, cs_resource->m_Shape2D, tmp_convex_shape.m_Shape2D);\n            ReleaseResources(cs_resource);\n            cs_resource->m_Shape3D = tmp_convex_shape.m_Shape3D;\n            return dmResource::RESULT_OK;\n        }\n        else\n        {\n            return dmResource::RESULT_FORMAT_ERROR;\n        }\n    }\n}\n", "meta": {"hexsha": "41ac13bcbd85247207a271f87bcf966d419206d7", "size": 6873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "engine/gamesys/src/gamesys/resources/res_convex_shape.cpp", "max_stars_repo_name": "dapetcu21/defold", "max_stars_repo_head_hexsha": "2a1faa9ed227eb3dfda0cbba8e4ea4ef1bcdb962", "max_stars_repo_licenses": ["ECL-2.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": "engine/gamesys/src/gamesys/resources/res_convex_shape.cpp", "max_issues_repo_name": "dapetcu21/defold", "max_issues_repo_head_hexsha": "2a1faa9ed227eb3dfda0cbba8e4ea4ef1bcdb962", "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": "engine/gamesys/src/gamesys/resources/res_convex_shape.cpp", "max_forks_repo_name": "dapetcu21/defold", "max_forks_repo_head_hexsha": "2a1faa9ed227eb3dfda0cbba8e4ea4ef1bcdb962", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-29T04:14:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T04:14:35.000Z", "avg_line_length": 39.9593023256, "max_line_length": 182, "alphanum_fraction": 0.5943547214, "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.17442215112944282}}
{"text": "// Copyright 2021 Josh Pieper, jjp@pobox.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#include \"fw/stm32_i2c_timing.h\"\n\n#include <boost/test/auto_unit_test.hpp>\n\nusing namespace moteus;\n\nnamespace tt = boost::test_tools;\n\n// Just some basic sanity checks\n\nBOOST_AUTO_TEST_CASE(TimingTest1) {\n  TimingInput input;\n  input.peripheral_hz = 64000000;\n  input.i2c_hz = 100000;\n  input.i2c_mode = I2cMode::kStandard;\n  input.analog_filter = AnalogFilter::kOff;\n\n  const auto result = CalculateI2cTiming(input);\n  BOOST_TEST(result.error == 0);\n  BOOST_TEST(result.prescaler == 1);\n  BOOST_TEST(result.scldel == 8);\n  BOOST_TEST(result.sclh == 147);\n  BOOST_TEST(result.scll == 172);\n  BOOST_TEST(result.timingr == 0x108993ac);\n}\n\nBOOST_AUTO_TEST_CASE(TimingTest2) {\n  TimingInput input;\n  input.peripheral_hz = 64000000;\n  input.i2c_hz = 400000;\n  input.i2c_mode = I2cMode::kFast;\n  input.analog_filter = AnalogFilter::kOff;\n\n  const auto result = CalculateI2cTiming(input);\n  BOOST_TEST(result.error == 0);\n  BOOST_TEST(result.prescaler == 0);\n  BOOST_TEST(result.scldel == 6);\n  BOOST_TEST(result.sclh == 51);\n  BOOST_TEST(result.scll == 108);\n  BOOST_TEST(result.timingr == 0x0060336c);\n}\n\nBOOST_AUTO_TEST_CASE(TimingTest3) {\n  TimingInput input;\n  input.peripheral_hz = 64000000;\n  input.i2c_hz = 1000000;\n  input.i2c_mode = I2cMode::kFastPlus;\n  input.analog_filter = AnalogFilter::kOff;\n\n  const auto result = CalculateI2cTiming(input);\n  BOOST_TEST(result.error == 0);\n  BOOST_TEST(result.prescaler == 0);\n  BOOST_TEST(result.scldel == 3);\n  BOOST_TEST(result.sclh == 21);\n  BOOST_TEST(result.scll == 42);\n  BOOST_TEST(result.timingr == 0x0030152a);\n}\n\nBOOST_AUTO_TEST_CASE(TimingTest4) {\n  TimingInput input;\n  input.peripheral_hz = 128000000;\n  input.i2c_hz = 1000000;\n  input.i2c_mode = I2cMode::kFastPlus;\n  input.analog_filter = AnalogFilter::kOff;\n\n  const auto result = CalculateI2cTiming(input);\n  BOOST_TEST(result.error == 0);\n  BOOST_TEST(result.prescaler == 0);\n  BOOST_TEST(result.scldel == 6);\n  BOOST_TEST(result.sclh == 42);\n  BOOST_TEST(result.scll == 85);\n  BOOST_TEST(result.timingr == 0x00602a55);\n}\n", "meta": {"hexsha": "edee19d07bc82a4c122fcc2acec2eab910814443", "size": 2640, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fw/test/stm32_i2c_timing_test.cc", "max_stars_repo_name": "fxd0h/moteus", "max_stars_repo_head_hexsha": "e66ba9fb54ad0482a0bdf9a32420f5bf18677216", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 347.0, "max_stars_repo_stars_event_min_datetime": "2019-03-16T12:00:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:19:42.000Z", "max_issues_repo_path": "fw/test/stm32_i2c_timing_test.cc", "max_issues_repo_name": "fxd0h/moteus", "max_issues_repo_head_hexsha": "e66ba9fb54ad0482a0bdf9a32420f5bf18677216", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2020-04-20T20:37:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T18:13:59.000Z", "max_forks_repo_path": "fw/test/stm32_i2c_timing_test.cc", "max_forks_repo_name": "fxd0h/moteus", "max_forks_repo_head_hexsha": "e66ba9fb54ad0482a0bdf9a32420f5bf18677216", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 127.0, "max_forks_repo_forks_event_min_datetime": "2019-03-23T16:06:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:33:27.000Z", "avg_line_length": 30.0, "max_line_length": 75, "alphanum_fraction": 0.7340909091, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.17437138664159688}}
{"text": "#include <boost/python.hpp>\n\n#include <scitbx/cubicle_neighbors.hpp>\n\nnamespace scitbx { namespace cubicle_neighbors_ext {\n\n  struct cubicle_neighbors_wrappers\n  {\n    typedef cubicle_neighbors<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"cubicle_neighbors\", no_init)\n        .def(init<\n          af::const_ref<vec3<double> > const&,\n          double const&,\n          double const&>((\n            arg(\"main_sites_cart\"),\n            arg(\"cubicle_edge\"),\n            arg(\"epsilon\")=1.e-6)))\n        .def(\"neighbors_of\", &w_t::neighbors_of, (\n          arg(\"other_sites_cart\"),\n          arg(\"distance_cutoff_sq\")))\n      ;\n    }\n  };\n\n  void\n  init_module()\n  {\n    using namespace boost::python;\n    cubicle_neighbors_wrappers::wrap();\n    def(\"cubicles_max_memory_allocation_set\",\n      cubicles_max_memory_allocation_set, (arg(\"number_of_bytes\")));\n    def(\"cubicles_max_memory_allocation_get\",\n      cubicles_max_memory_allocation_get);\n  }\n\n}} // namespace scitbx::cubicle_neighbors_ext\n\nBOOST_PYTHON_MODULE(scitbx_cubicle_neighbors_ext)\n{\n  scitbx::cubicle_neighbors_ext::init_module();\n}\n", "meta": {"hexsha": "543e998f20d615ed563e1e02893c90ab530b4f67", "size": 1147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/cubicle_neighbors_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": "scitbx/cubicle_neighbors_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": "scitbx/cubicle_neighbors_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": 24.4042553191, "max_line_length": 68, "alphanum_fraction": 0.6556233653, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.174319305139643}}
{"text": "#include \"Geometry/GEMGeometryBuilder/src/ME0GeometryBuilderFromDDD10EtaPart.h\"\n#include \"Geometry/GEMGeometry/interface/ME0Geometry.h\"\n#include \"Geometry/GEMGeometry/interface/ME0EtaPartitionSpecs.h\"\n\n#include <DetectorDescription/Core/interface/DDFilter.h>\n#include <DetectorDescription/Core/interface/DDFilteredView.h>\n#include <DetectorDescription/Core/interface/DDSolid.h>\n\n#include \"Geometry/MuonNumbering/interface/MuonDDDNumbering.h\"\n#include \"Geometry/MuonNumbering/interface/MuonBaseNumber.h\"\n#include \"Geometry/MuonNumbering/interface/ME0NumberingScheme.h\"\n\n#include \"DataFormats/GeometrySurface/interface/TrapezoidalPlaneBounds.h\"\n\n#include \"DataFormats/GeometryVector/interface/Basic3DVector.h\"\n\n#include \"CLHEP/Units/GlobalSystemOfUnits.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n\nME0GeometryBuilderFromDDD10EtaPart::ME0GeometryBuilderFromDDD10EtaPart()\n{ }\n\nME0GeometryBuilderFromDDD10EtaPart::~ME0GeometryBuilderFromDDD10EtaPart() \n{ }\n\n\nME0Geometry* ME0GeometryBuilderFromDDD10EtaPart::build(const DDCompactView* cview, const MuonDDDConstants& muonConstants)\n{\n\n  std::string attribute = \"MuStructure\";\n  std::string value     = \"MuonEndCapME0\";\n\n  // Asking only for the MuonME0's\n  DDSpecificsMatchesValueFilter filter{DDValue(attribute, value, 0.0)};\n  DDFilteredView fview(*cview,filter);\n\n  return this->buildGeometry(fview, muonConstants);\n}\n\n\nME0Geometry* ME0GeometryBuilderFromDDD10EtaPart::buildGeometry(DDFilteredView& fv, const MuonDDDConstants& muonConstants)\n{\n\n  ME0Geometry* geometry = new ME0Geometry();\n\n  LogTrace(\"ME0GeometryBuilderFromDDD\") <<\"Building the geometry service\";\n  LogTrace(\"ME0GeometryBuilderFromDDD\") <<\"About to run through the ME0 structure\\n\" \n\t\t\t\t\t<<\"Top level logical part: \"\n\t\t\t\t\t<<fv.logicalPart().name().name();\n\n  // ==========================================\n  // ===  Test to understand the structure  ===\n  // ========================================== \n  #ifdef EDM_ML_DEBUG\n  bool testChambers = fv.firstChild();\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \"doChamber = fv.firstChild() = \" << testChambers;\n  // ----------------------------------------------------------------------------------------------------------------------------------------------\n  while (testChambers) {\n    // to etapartitions\n    LogTrace(\"ME0GeometryBuilderFromDDD\")<<\"to layer \"<<fv.firstChild(); // commented out in case only looping over sensitive volumes\n    LogTrace(\"ME0GeometryBuilderFromDDD\")<<\"to etapt \"<<fv.firstChild(); // commented out in case only looping over sensitive volumes\n    MuonDDDNumbering mdddnum(muonConstants);\n    ME0NumberingScheme me0Num(muonConstants);\n    int rawId = me0Num.baseNumberToUnitNumber(mdddnum.geoHistoryToBaseNumber(fv.geoHistory()));\n    ME0DetId detId = ME0DetId(rawId);\n    ME0DetId detIdCh = detId.chamberId();\n    // back to chambers\n    LogTrace(\"ME0GeometryBuilderFromDDD\")<<\"back to layer \"<<fv.parent(); // commented out in case only looping over sensitive volumes\n    LogTrace(\"ME0GeometryBuilderFromDDD\")<<\"back to chamb \"<<fv.parent(); // commented out in case only looping over sensitive volumes\n    // ok lets get started ...                             \n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \"In DoChambers Loop :: ME0DetId \"<<detId<<\" = \"<<detId.rawId()<<\" (which belongs to ME0Chamber \"<<detIdCh<<\" = \"<<detIdCh.rawId()<<\")\";\n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \"Second level logical part: \" << fv.logicalPart().name().name();\n    DDBooleanSolid solid2 = (DDBooleanSolid)(fv.logicalPart().solid());\n    std::vector<double> dpar2  = solid2.parameters();\n    std::stringstream parameters2;\n    for(unsigned int i=0; i<dpar2.size(); ++i) {\n      parameters2 << \" dpar[\"<<i<<\"]=\"<< dpar2[i]/10 << \"cm \";\n    }\n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \"Second level parameters: vector with size = \"<<dpar2.size()<<\" and elements \"<<parameters2.str();\n    // from GEM\n    // DDBooleanSolid solid = (DDBooleanSolid)(fv.logicalPart().solid());\n    // std::vector<double> dpar = solid.solidA().parameters();\n    /*\n    if(solid2.solidA()) {\n      std::vector<double> dpar2a = solid2.solidA().parameters();\n      std::stringstream parameters2a;\n      for(unsigned int i=0; i<dpar2a.size(); ++i) {\n\tparameters2a << \" dpara[\"<<i<<\"]=\"<< dpar2a[i]/10 << \"cm \";\n      }\n      LogTrace(\"ME0GeometryBuilderFromDDD\") << \"Second level parameters: vector with size = \"<<dpar2a.size()<<\" and elements \"<<parameters2.str();\n    }\n    if(solid2.solidB()) {\n      std::vector<double> dpar2b = solid2.solidB().parameters();\n      std::stringstream parameters2b;\n      for(unsigned int i=0; i<dpar2b.size(); ++i) {\n\tparameters2b << \" dparb[\"<<i<<\"]=\"<< dpar2b[i]/10 << \"cm \";\n      }\n      LogTrace(\"ME0GeometryBuilderFromDDD\") << \"Second level parameters: vector with size = \"<<dpar2b.size()<<\" and elements \"<<parameters2.str();\n    }\n    */\n    bool doLayers = fv.firstChild();\n    // --------------------------------------------------------------------------------------------------------------------------------------------\n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \"doLayer = fv.firstChild() = \" << doLayers;\n    while (doLayers) {\n      // to etapartitions\n      LogTrace(\"ME0GeometryBuilderFromDDD\")<<\"to etapt \"<<fv.firstChild(); // commented out in case only looping over sensitive volumes\n      MuonDDDNumbering mdddnum(muonConstants);\n      ME0NumberingScheme me0Num(muonConstants);\n      int rawId = me0Num.baseNumberToUnitNumber(mdddnum.geoHistoryToBaseNumber(fv.geoHistory()));\n      ME0DetId detId = ME0DetId(rawId);\n      ME0DetId detIdLa = detId.layerId();\n      // back to layers\n      LogTrace(\"ME0GeometryBuilderFromDDD\")<<\"back to layer \"<<fv.parent(); // commented out in case only looping over sensitive volumes\n      LogTrace(\"ME0GeometryBuilderFromDDD\") << \"In DoLayers Loop :: ME0DetId \"<<detId<<\" = \"<<detId.rawId()<<\" (which belongs to ME0Layer \"<<detIdLa<<\" = \"<<detIdLa.rawId()<<\")\";\n      LogTrace(\"ME0GeometryBuilderFromDDD\") << \"Third level logical part: \" << fv.logicalPart().name().name();\n      DDBooleanSolid solid3 = (DDBooleanSolid)(fv.logicalPart().solid());\n      std::vector<double> dpar3 = solid3.parameters();\n      std::stringstream parameters3;\n      for(unsigned int i=0; i<dpar3.size(); ++i) {\n\tparameters3 << \" dpar[\"<<i<<\"]=\"<< dpar3[i]/10 << \"cm \";\n      }\n      LogTrace(\"ME0GeometryBuilderFromDDD\") << \"Third level parameters: vector with size = \"<<dpar3.size()<<\" and elements \"<<parameters3.str();\n      bool doEtaParts = fv.firstChild(); \n      // --------------------------------------------------------------------------------------------------------------------------------------------\n      LogTrace(\"ME0GeometryBuilderFromDDD\") << \"doEtaPart = fv.firstChild() = \" << doEtaParts;\n      while (doEtaParts) {\n\tLogTrace(\"ME0GeometryBuilderFromDDD\") << \"In DoEtaParts Loop :: ME0DetId \"<<detId<<\" = \"<<detId.rawId();\n\tLogTrace(\"ME0GeometryBuilderFromDDD\") << \"Fourth level logical part: \" << fv.logicalPart().name().name();\n\tDDBooleanSolid solid4 = (DDBooleanSolid)(fv.logicalPart().solid());\n\tstd::vector<double> dpar4 = solid4.parameters();\n\tstd::stringstream parameters4;\n\tfor(unsigned int i=0; i<dpar4.size(); ++i) {\n\t  parameters4 << \" dpar[\"<<i<<\"]=\"<< dpar4[i]/10 << \"cm \";\n\t}\n\tLogTrace(\"ME0GeometryBuilderFromDDD\") << \"Fourth level parameters: vector with size = \"<<dpar4.size()<<\" and elements \"<<parameters4.str();\n\t// --------------------------------------------------------------------------------------------------------------------------------------------\n\tdoEtaParts = fv.nextSibling();\n\tLogTrace(\"ME0GeometryBuilderFromDDD\") << \"doEtaPart = fv.nextSibling() = \" << doEtaParts;\n      }\n      fv.parent(); // commented out in case only looping over sensitive volumes\n      LogTrace(\"ME0GeometryBuilderFromDDD\") << \"went back to parent :: name = \"<<fv.logicalPart().name().name()<<\" will now ask for nextSibling\";\n      doLayers = fv.nextSibling();\n      LogTrace(\"ME0GeometryBuilderFromDDD\") << \"doLayer = fv.nextSibling() = \" << doLayers;\n    }\n    fv.parent(); // commented out in case only looping over sensitive volumes\n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \"went back to parent :: name = \"<<fv.logicalPart().name().name()<<\" will now ask for nextSibling\";\n    testChambers = fv.nextSibling();\n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \"doChamber = fv.nextSibling() = \" << testChambers;\n  }\n  fv.parent();\n  #endif\n\n \n  // ==========================================\n  // === Here the Real ME0 Geometry Builder ===\n  // ==========================================\n  bool doChambers = fv.firstChild();\n  while (doChambers) {\n    // to etapartitions and back again to pick up DetId\n    fv.firstChild();\n    fv.firstChild();\n    MuonDDDNumbering mdddnum(muonConstants);\n    ME0NumberingScheme me0Num(muonConstants);\n    int rawId = me0Num.baseNumberToUnitNumber(mdddnum.geoHistoryToBaseNumber(fv.geoHistory()));\n    ME0DetId detId = ME0DetId(rawId);\n    ME0DetId detIdCh = detId.chamberId();\n    fv.parent();\n    fv.parent();\n\n    // build chamber \n    ME0Chamber *me0Chamber = buildChamber(fv, detIdCh);\n    geometry->add(me0Chamber);\n\n    // loop over layers of the chamber\n    bool doLayers = fv.firstChild();\n    while (doLayers) {\n      // to etapartitions and back again to pick up DetId\n      fv.firstChild();\n      MuonDDDNumbering mdddnum(muonConstants);\n      ME0NumberingScheme me0Num(muonConstants);\n      int rawId = me0Num.baseNumberToUnitNumber(mdddnum.geoHistoryToBaseNumber(fv.geoHistory()));\n      ME0DetId detId = ME0DetId(rawId);\n      ME0DetId detIdLa = detId.layerId();\n      fv.parent();\n\n      // build layer\n      ME0Layer *me0Layer = buildLayer(fv, detIdLa);\n      me0Chamber->add(me0Layer);\n      geometry->add(me0Layer);\n\n\n      // loop over etapartitions of the layer\n      bool doEtaParts = fv.firstChild(); \n      while (doEtaParts) {\n\t// pick up DetId\n\tMuonDDDNumbering mdddnum(muonConstants);\n\tME0NumberingScheme me0Num(muonConstants);\n\tint rawId = me0Num.baseNumberToUnitNumber(mdddnum.geoHistoryToBaseNumber(fv.geoHistory()));\n\tME0DetId detId = ME0DetId(rawId);\n\n\t// build etapartition\n\tME0EtaPartition *etaPart = buildEtaPartition(fv, detId);\n\tme0Layer->add(etaPart);\n\tgeometry->add(etaPart);\n\n\tdoEtaParts = fv.nextSibling();\n      }\n      fv.parent();\n      doLayers = fv.nextSibling();\n    }\n    fv.parent();\n    doChambers = fv.nextSibling();\n  }\n\n  return geometry;\n}\n\nME0Chamber* ME0GeometryBuilderFromDDD10EtaPart::buildChamber(DDFilteredView& fv, ME0DetId detId) const {\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \"buildChamber \"<<fv.logicalPart().name().name() <<\" \"<< detId <<std::endl;\n  \n  DDBooleanSolid solid = (DDBooleanSolid)(fv.logicalPart().solid());\n  // std::vector<double> dpar = solid.solidA().parameters();\n  std::vector<double> dpar = solid.parameters(); \n  double L  = dpar[0]/cm;// length is along local Y\n  double T  = dpar[3]/cm;// thickness is long local Z\n  double b  = dpar[4]/cm;// bottom width is along local X\n  double B  = dpar[8]/cm;// top width is along local X\n  // hardcoded :: double b = 21.9859, B = 52.7261, L = 87.1678, T = 12.9;\n\n  #ifdef EDM_ML_DEBUG  \n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \" name of logical part = \"<<fv.logicalPart().name().name()<<std::endl;\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \" dpar is vector with size = \"<<dpar.size()<<std::endl;\n  for(unsigned int i=0; i<dpar.size(); ++i) {\n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \" dpar [\"<<i<<\"] = \"<< dpar[i]/10 << \" cm \"<<std::endl;\n  }\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \"size  b: \"<< b << \"cm, B: \" << B << \"cm,  L: \" << L << \"cm, T: \" << T <<\"cm \"<<std::endl;\n  #endif\n\n  bool isOdd = false; // detId.chamber()%2;\n  ME0BoundPlane surf(boundPlane(fv, new TrapezoidalPlaneBounds(b,B,L,T), isOdd ));\n  ME0Chamber* chamber = new ME0Chamber(detId.chamberId(), surf);\n  return chamber;\n}\n\nME0Layer* ME0GeometryBuilderFromDDD10EtaPart::buildLayer(DDFilteredView& fv, ME0DetId detId) const {\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \"buildLayer \"<<fv.logicalPart().name().name() <<\" \"<< detId <<std::endl;\n  \n  DDBooleanSolid solid = (DDBooleanSolid)(fv.logicalPart().solid());\n  // std::vector<double> dpar = solid.solidA().parameters();\n  std::vector<double> dpar = solid.parameters();\n  double L = dpar[0]/cm;// length is along local Y\n  double t = dpar[3]/cm;// thickness is long local Z\n  double b = dpar[4]/cm;// bottom width is along local X\n  double B = dpar[8]/cm;// top width is along local X\n  // dpar = solid.solidB().parameters();\n  // dz += dpar[3]/cm;     // layer thickness --- to be checked !!! layer thickness should be same as eta part thickness\n  // hardcoded :: double b = 21.9859, B = 52.7261, L = 87.1678, t = 0.4;\n\n  #ifdef EDM_ML_DEBUG\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \" name of logical part = \"<<fv.logicalPart().name().name()<<std::endl;\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \" dpar is vector with size = \"<<dpar.size()<<std::endl;\n  for(unsigned int i=0; i<dpar.size(); ++i) {\n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \" dpar [\"<<i<<\"] = \"<< dpar[i]/10 << \" cm \"<<std::endl;\n  }\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \"size  b: \"<< b << \"cm, B: \" << B << \"cm,  L: \" << L << \"cm, t: \" << t <<\"cm \"<<std::endl;\n  #endif\n\n  bool isOdd = false; // detId.chamber()%2;\n  ME0BoundPlane surf(boundPlane(fv, new TrapezoidalPlaneBounds(b,B,L,t), isOdd ));\n  ME0Layer* layer = new ME0Layer(detId.layerId(), surf);\n  return layer;\n}\n\nME0EtaPartition* ME0GeometryBuilderFromDDD10EtaPart::buildEtaPartition(DDFilteredView& fv, ME0DetId detId) const {\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \"buildEtaPartition \"<<fv.logicalPart().name().name() <<\" \"<< detId <<std::endl;\n  \n  // EtaPartition specific parameter (nstrips and npads) \n  DDValue numbOfStrips(\"nStrips\");\n  DDValue numbOfPads(\"nPads\");\n  std::vector<const DDsvalues_type* > specs(fv.specifics());\n  std::vector<const DDsvalues_type* >::iterator is = specs.begin();\n  double nStrips = 0., nPads = 0.;\n  for (;is != specs.end(); is++){\n    if (DDfetch( *is, numbOfStrips)) nStrips = numbOfStrips.doubles()[0];\n    if (DDfetch( *is, numbOfPads))   nPads = numbOfPads.doubles()[0];\n  }\n  LogTrace(\"ME0GeometryBuilderFromDDD\") \n    << ((nStrips == 0. ) ? (\"No nStrips found!!\") : (\"Number of strips: \" + boost::lexical_cast<std::string>(nStrips))); \n  LogTrace(\"ME0GeometryBuilderFromDDD\") \n    << ((nPads == 0. ) ? (\"No nPads found!!\") : (\"Number of pads: \" + boost::lexical_cast<std::string>(nPads)));\n  \n  // EtaPartition specific parameter (size) \n  std::vector<double> dpar = fv.logicalPart().solid().parameters();\n  double b = dpar[4]/cm; // half bottom edge\n  double B = dpar[8]/cm; // half top edge\n  double L = dpar[0]/cm; // half apothem\n  double t = dpar[3]/cm; // half thickness\n  \n  #ifdef EDM_ML_DEBUG\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \" name of logical part = \"<<fv.logicalPart().name().name()<<std::endl;\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \" dpar is vector with size = \"<<dpar.size()<<std::endl;\n  for(unsigned int i=0; i<dpar.size(); ++i) {\n    LogTrace(\"ME0GeometryBuilderFromDDD\") << \" dpar [\"<<i<<\"] = \"<< dpar[i]/10 << \" cm \"<<std::endl;\n  }\n  LogTrace(\"ME0GeometryBuilderFromDDD\") << \"size  b: \"<< b << \"cm, B: \" << B << \"cm,  L: \" << L << \"cm, t: \" << t <<\"cm \"<<std::endl;\n  #endif\n\n  std::vector<float> pars;\n  pars.emplace_back(b); \n  pars.emplace_back(B); \n  pars.emplace_back(L); \n  pars.emplace_back(nStrips);\n  pars.emplace_back(nPads);\n  \n  bool isOdd = false; // detId.chamber()%2; // this gives the opportunity (in future) to change the face of the chamber (electronics facing IP or electronics away from IP)\n  ME0BoundPlane surf(boundPlane(fv, new TrapezoidalPlaneBounds(b, B, L, t), isOdd ));\n  std::string name = fv.logicalPart().name().name();\n  ME0EtaPartitionSpecs* e_p_specs = new ME0EtaPartitionSpecs(GeomDetEnumerators::ME0, name, pars);\n  \n  ME0EtaPartition* etaPartition = new ME0EtaPartition(detId, surf, e_p_specs);\n  return etaPartition;\n}\n\nME0GeometryBuilderFromDDD10EtaPart::ME0BoundPlane\nME0GeometryBuilderFromDDD10EtaPart::boundPlane(const DDFilteredView& fv,\n                                      Bounds* bounds, bool isOddChamber) const {\n  // extract the position\n  const DDTranslation & trans(fv.translation());\n  const Surface::PositionType posResult(float(trans.x()/cm),\n                                        float(trans.y()/cm),\n                                        float(trans.z()/cm));\n\n  // now the rotation\n  //  DDRotationMatrix tmp = fv.rotation(); \n  // === DDD uses 'active' rotations - see CLHEP user guide === \n  //     ORCA uses 'passive' rotation.                          \n  //     'active' and 'passive' rotations are inverse to each other\n  //  DDRotationMatrix tmp = fv.rotation();                        \n  DDRotationMatrix rotation = fv.rotation();//REMOVED .Inverse();  \n  DD3Vector x, y, z;\n  rotation.GetComponents(x,y,z);\n  // LogTrace(\"GEMGeometryBuilderFromDDD\") << \"translation: \"<< fv.translation() << std::endl;\n  // LogTrace(\"GEMGeometryBuilderFromDDD\") << \"rotation   : \"<< fv.rotation() << std::endl;   \n  // LogTrace(\"GEMGeometryBuilderFromDDD\") << \"INVERSE rotation manually: \\n\"                 \n  //        << x.X() << \", \" << x.Y() << \", \" << x.Z() << std::endl                           \n  //        << y.X() << \", \" << y.Y() << \", \" << y.Z() << std::endl                          \n  //        << z.X() << \", \" << z.Y() << \", \" << z.Z() << std::endl;                         \n\n  Surface::RotationType rotResult(float(x.X()),float(x.Y()),float(x.Z()),\n                                  float(y.X()),float(y.Y()),float(y.Z()),\n                                  float(z.X()),float(z.Y()),float(z.Z()));\n\n  //Change of axes for the forward\n  Basic3DVector<float> newX(1.,0.,0.);\n  Basic3DVector<float> newY(0.,0.,1.);\n  Basic3DVector<float> newZ(0.,1.,0.);\n  newY *= -1;\n\n  rotResult.rotateAxes(newX, newY, newZ);\n\n  return ME0BoundPlane( new BoundPlane( posResult, rotResult, bounds));\n}\n\n", "meta": {"hexsha": "b9ebc8089b2527927b39d8e83382df43264343bf", "size": 17983, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Geometry/GEMGeometryBuilder/src/ME0GeometryBuilderFromDDD10EtaPart.cc", "max_stars_repo_name": "pasmuss/cmssw", "max_stars_repo_head_hexsha": "566f40c323beef46134485a45ea53349f59ae534", "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/GEMGeometryBuilder/src/ME0GeometryBuilderFromDDD10EtaPart.cc", "max_issues_repo_name": "pasmuss/cmssw", "max_issues_repo_head_hexsha": "566f40c323beef46134485a45ea53349f59ae534", "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/GEMGeometryBuilder/src/ME0GeometryBuilderFromDDD10EtaPart.cc", "max_forks_repo_name": "pasmuss/cmssw", "max_forks_repo_head_hexsha": "566f40c323beef46134485a45ea53349f59ae534", "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.0, "max_line_length": 180, "alphanum_fraction": 0.6323194128, "num_tokens": 4914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17431929482333677}}
{"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   *      130219    D. Dirkx            File created.\n   *      130227    R.C.A. Boon         Removed using directives (using namespace), added necessary\n   *                                    using declarations (using ...::member), removed obsolete\n   *                                    include statements\n   *      130302    D. Dirkx            Updated file by putting tests in local scope;\n   *                                    expanded tests.\n   *\n   *    References\n   *\n   *    Notes\n   *      The unit tests use rotation matrices generated by spice, the code for the spice interface\n   *      used to generate these testing values are included in this file, but commented.\n   */\n\n#define BOOST_TEST_MAIN\n\n#include <limits>\n#include <iostream>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/simpleRotationalEphemeris.h\"\n//#include \"Tudat/External/SpiceInterface/spiceInterface.h\"\n//#include \"Tudat/InputOutput/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace ephemerides;\n\nBOOST_AUTO_TEST_SUITE( test_rotational_ephemeris )\n\n// Test functions to calculate rotation matrix derivative from angular velocity vector and vice\n// versa.\nBOOST_AUTO_TEST_CASE( testRotationalEphemeris )\n{\n    // Define names of frames.\n    const std::string baseFrame = \"J2000\";\n    const std::string targetFrame = \"IAU_VENUS\";\n\n    // Set time at which rotational ephemeris it to be called for subsequent tests.\n\n    // Test rotation to target frame at specified time.\n    {\n\n        // The following code block can be used to retrieve the benchmark data from Spice.\n        //        spice_interface::loadSpiceKernelInTudat( input_output::getSpiceKernelPath( ) +\n        // \"pck00010.tpc\" );\n        //        const double secondsSinceJ2000 = 1.0E6;\n        //        Eigen::Quaterniond spiceRotationMatrix =\n        //                spice_interface::computeRotationQuaternionBetweenFrames(\n        // baseFrame, targetFrame, secondsSinceJ2000 );\n        //        Eigen::Matrix3d spiceRotationMatrixDerivative =\n        //                spice_interface::computeRotationMatrixDerivativeBetweenFrames(\n        // baseFrame, targetFrame, secondsSinceJ2000 );\n        //        Eigen::Vector3d spiceRotationalVelocityVector =\n        //                spice_interface::getAngularVelocityVectorOfFrameInOriginalFrame(\n        // baseFrame, targetFrame, secondsSinceJ2000 );\n\n        // Set rotational characteristics at given time, as calculated with Spice\n        // (see above commented lines).\n        Eigen::Matrix3d spiceRotationMatrixDerivative;\n        spiceRotationMatrixDerivative <<\n                1.690407961416589e-07, 2.288121921543265e-07, 9.283170431475241e-08,\n                -2.468632444964533e-07, 1.540516111965609e-07, 6.981529179974795e-08,\n                0.0,           0.0,          0.0;\n\n        Eigen::Matrix3d spiceRotationMatrix;\n        spiceRotationMatrix << -0.8249537745726603, 0.5148010526833556, 0.2333048348715243,\n                -0.5648910720519699, -0.7646317780963481, -0.3102197940834743,\n                0.01869081416890206, -0.3877088083617987, 0.9215923900425707;\n\n        Eigen::Vector3d spiceRotationalVelocityVector;\n        spiceRotationalVelocityVector << -5.593131603532092e-09,\n                1.160198999048488e-07,\n                -2.75781861386115e-07;\n\n        // Calculate rotational velocity from SPICE rotation matrix derivative.\n        Eigen::Vector3d rotationalVelocityVector =\n                getRotationalVelocityVectorInBaseFrameFromMatrices(\n                    spiceRotationMatrix, spiceRotationMatrixDerivative.transpose( ) );\n\n        // Calculate rotation matrix derivative from SPICE rotational velocity vector.\n        Eigen::Matrix3d rotationMatrixDerivative = getDerivativeOfRotationMatrixToFrame(\n                    spiceRotationMatrix, spiceRotationalVelocityVector );\n\n        // Calculate rotational velocity from previously calculated rotation matrix derivative.\n        Eigen::Matrix3d backCalculatedRotationMatrixDerivative =\n                getDerivativeOfRotationMatrixToFrame(\n                    spiceRotationMatrix, rotationalVelocityVector );\n\n        // Calculate rotation matrix derivative from previously calculated rotational velocity\n        // vector.\n        Eigen::Vector3d backCalculatedRotationalVelocityVector =\n                getRotationalVelocityVectorInBaseFrameFromMatrices(\n                    spiceRotationMatrix, rotationMatrixDerivative.transpose( ) );\n\n        // Check equivalence of results.\n        for( int i = 0; i < 3; i++ )\n        {\n            BOOST_CHECK_SMALL( rotationalVelocityVector( i ) -\n                               backCalculatedRotationalVelocityVector( i ), 2.0E-22 );\n            BOOST_CHECK_SMALL( rotationalVelocityVector( i ) -\n                               spiceRotationalVelocityVector( i ), 2.0E-22 );\n\n            for( int j = 0; j < 3; j++ )\n            {\n                BOOST_CHECK_SMALL( rotationMatrixDerivative( i, j ) -\n                                   backCalculatedRotationMatrixDerivative( i, j ), 2.0E-22 );\n                BOOST_CHECK_SMALL( rotationMatrixDerivative( i, j ) -\n                                   spiceRotationMatrixDerivative( i, j ), 2.0E-22 );\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "68aefae7eb1657a1dab8190f683f77bd922a1808", "size": 7403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Ephemerides/UnitTests/unitTestRotationalEphemeris.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/Ephemerides/UnitTests/unitTestRotationalEphemeris.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/Ephemerides/UnitTests/unitTestRotationalEphemeris.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": 47.7612903226, "max_line_length": 101, "alphanum_fraction": 0.6651357558, "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.1743192913845681}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"PhotonSystematic/DataStore.h\"\n#include \"PlotFunctions/RobustMinimize.h\"\n\n#include \"TH1D.h\"\n#include \"RooRealVar.h\"\n#include \"RooDataHist.h\"\n#include \"RooArgSet.h\"\n#include \"RooGaussian.h\"\n\n// The name of the suite must be a different name to your class\nBOOST_AUTO_TEST_SUITE( DataStoreSuite )\n\nBOOST_AUTO_TEST_CASE( FitTest ) {\n  // TH1D hist(\"hist\", \"hist\", 100,-5, 5 );\n  // hist.FillRandom( \"gaus\", 1e6 );\n\n  // RooRealVar mass( \"mass\", \"mass\", 0, -5, 5 );\n  // RooRealVar mean( \"mean\", \"mean\", 0, -5, 5 );\n  // RooRealVar sigma( \"sigma\", \"sigma\", 1, 0, 3 );\n\n  // RooDataHist dataHist( \"datahist\", \"datahist\", RooArgSet(mass), &hist );\n  // RooGaussian pdf( \"gaus\", \"gaus\", mass, mean, sigma );\n\n  // FitData( &dataHist, &pdf, -1 );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3c837584dc941f7b086d2e6f126656c858622f57", "size": 816, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Root/TestDataStore.cxx", "max_stars_repo_name": "cgoudet/PhotonSystematic", "max_stars_repo_head_hexsha": "60181e4292df6b42b2c3a5cd7336a8a9eca724f8", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Root/TestDataStore.cxx", "max_issues_repo_name": "cgoudet/PhotonSystematic", "max_issues_repo_head_hexsha": "60181e4292df6b42b2c3a5cd7336a8a9eca724f8", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Root/TestDataStore.cxx", "max_forks_repo_name": "cgoudet/PhotonSystematic", "max_forks_repo_head_hexsha": "60181e4292df6b42b2c3a5cd7336a8a9eca724f8", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3225806452, "max_line_length": 76, "alphanum_fraction": 0.6642156863, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.17426868456035405}}
{"text": "#include \"mainwindow1.h\"\n#include <QApplication>\n#include \"Eigen/Dense\"\n//#include \"robot.h\"\n#include <Eigen/Geometry>\n#include <iostream>\n#include <cstdlib>\n#include <qdebug.h>\n#include <qmath.h>\n#include <QMainWindow>\n    #include <QLabel>\n#include <QLineEdit>\n#include <QHBoxLayout>\n//#include <taskspace.h>\n//#include<taskspaceoffline.h>\nusing namespace Eigen;\nusing namespace std;\nint main(int argc, char *argv[])\n{\n    //QApplication a(argc, argv);\n\n// MainWindow w;\n\n\n\n\n    // SQDTaskSpace Forwardwalking();\n    //    MatrixXd PelvisTrajectory;\n    // PelvisTrajectory.setLinSpaced(81,0,0.4);\n    // MatrixXd AnkleTrajectory;\n    //AnkleTrajectory.setLinSpaced(81,0,0.4);\n    //Robot Milad;\n//TaskSpaceOffline offline;\n//   TaskSpace Pelvis;\n//    QApplication a(argc, argv);\n//    MainWindow w;\n     //QList<Link> temp = Surena4.GetLinks();\n    //w.show();\n    //MatrixXd temp(2,3);\n    //temp<< 1,2,3,4,5,6;\n    //return a.exec();\n//uncomment below\n   // w.show();\n    //w.Plot(Pelvis);\n   // return a.exec();\n\n\n\n\n\n\n    QApplication app(argc, argv);\n    QWidget window;\n    QLabel *label = new QLabel(QApplication::translate(\"windowlayout\", \"Name:\"));\n    QLineEdit *lineEdit = new QLineEdit();\n\n    QHBoxLayout *layout = new QHBoxLayout();\n    layout->addWidget(label);\n    layout->addWidget(lineEdit);\n    window.setLayout(layout);\n    window.setWindowTitle(\n        QApplication::translate(\"windowlayout\", \"Window layout\"));\n    window.show();\n    return app.exec();\n\n\n\n\n\n}\n", "meta": {"hexsha": "7a3035776349018d5c00630957ff976956e12405", "size": 1486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sample/HelloWorldPlugin/main.cpp", "max_stars_repo_name": "MiladShafiee/Surena4HumanoidSimulation-Choreonoid", "max_stars_repo_head_hexsha": "a3d8af2a6ae2e7720bab4a329809507632173177", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:57:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T21:42:22.000Z", "max_issues_repo_path": "sample/HelloWorldPlugin/main.cpp", "max_issues_repo_name": "MiladShafiee/Surena4HumanoidSimulation-Choreonoid", "max_issues_repo_head_hexsha": "a3d8af2a6ae2e7720bab4a329809507632173177", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample/HelloWorldPlugin/main.cpp", "max_forks_repo_name": "MiladShafiee/Surena4HumanoidSimulation-Choreonoid", "max_forks_repo_head_hexsha": "a3d8af2a6ae2e7720bab4a329809507632173177", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T06:42:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T06:42:16.000Z", "avg_line_length": 20.9295774648, "max_line_length": 81, "alphanum_fraction": 0.6541049798, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.17426868082755864}}
{"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// File generated at Thu 10 May 2018 14:41:56\n\n#ifndef MSSMEFTHiggs_PHYSICAL_H\n#define MSSMEFTHiggs_PHYSICAL_H\n\n#include <Eigen/Core>\n\n#include <iosfwd>\n\nnamespace flexiblesusy {\n\nstruct MSSMEFTHiggs_physical {\n   void clear();\n   void convert_to_hk();   ///< converts pole masses to HK convention\n   void convert_to_slha(); ///< converts pole masses to SLHA convention\n   Eigen::ArrayXd get() const; ///< returns array with all masses and mixings\n   void set(const Eigen::ArrayXd&); ///< set all masses and mixings\n   Eigen::ArrayXd get_masses() const; ///< returns array with all masses\n   void set_masses(const Eigen::ArrayXd&); ///< set all masses\n   void print(std::ostream&) const;\n\n   double MVG{};\n   double MGlu{};\n   Eigen::Array<double,3,1> MFv{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,6,1> MSd{Eigen::Array<double,6,1>::Zero()};\n   Eigen::Array<double,3,1> MSv{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,6,1> MSu{Eigen::Array<double,6,1>::Zero()};\n   Eigen::Array<double,6,1> MSe{Eigen::Array<double,6,1>::Zero()};\n   Eigen::Array<double,2,1> Mhh{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MAh{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MHpm{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,4,1> MChi{Eigen::Array<double,4,1>::Zero()};\n   Eigen::Array<double,2,1> MCha{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,3,1> MFe{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,3,1> MFd{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,3,1> MFu{Eigen::Array<double,3,1>::Zero()};\n   double MVWm{};\n   double MVP{};\n   double MVZ{};\n\n   Eigen::Matrix<double,6,6> ZD{Eigen::Matrix<double,6,6>::Zero()};\n   Eigen::Matrix<double,3,3> ZV{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,6,6> ZU{Eigen::Matrix<double,6,6>::Zero()};\n   Eigen::Matrix<double,6,6> ZE{Eigen::Matrix<double,6,6>::Zero()};\n   Eigen::Matrix<double,2,2> ZH{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZA{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZP{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,4,4> ZN{Eigen::Matrix<std::complex<double>,4,4>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UM{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UP{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZEL{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZER{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZDL{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZDR{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZUL{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> ZUR{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<double,2,2> ZZ{Eigen::Matrix<double,2,2>::Zero()};\n\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMEFTHiggs_physical&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "288a5ea24c356612141f32d9380929c335295311", "size": 4013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs/MSSMEFTHiggs_physical.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs/MSSMEFTHiggs_physical.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs/MSSMEFTHiggs_physical.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 47.7738095238, "max_line_length": 96, "alphanum_fraction": 0.6576127585, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.17422329838510425}}
{"text": "#include \"storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h\"\n\n#include <boost/container/flat_map.hpp>\n\n#include \"storm/modelchecker/results/ExplicitQuantitativeCheckResult.h\"\n#include \"storm/modelchecker/hints/ExplicitModelCheckerHint.h\"\n#include \"storm/modelchecker/prctl/helper/DsMpiUpperRewardBoundsComputer.h\"\n#include \"storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.h\"\n#include \"storm/modelchecker/prctl/helper/SparseMdpEndComponentInformation.h\"\n\n#include \"storm/models/sparse/StandardRewardModel.h\"\n\n#include \"storm/storage/MaximalEndComponentDecomposition.h\"\n\n#include \"storm/utility/macros.h\"\n#include \"storm/utility/vector.h\"\n#include \"storm/utility/graph.h\"\n\n#include \"storm/storage/expressions/Variable.h\"\n#include \"storm/storage/expressions/Expression.h\"\n#include \"storm/storage/Scheduler.h\"\n\n#include \"storm/solver/MinMaxLinearEquationSolver.h\"\n#include \"storm/solver/Multiplier.h\"\n#include \"storm/solver/LpSolver.h\"\n\n#include \"storm/settings/SettingsManager.h\"\n#include \"storm/settings/modules/ModelCheckerSettings.h\"\n#include \"storm/settings/modules/GeneralSettings.h\"\n#include \"storm/settings/modules/CoreSettings.h\"\n#include \"storm/settings/modules/IOSettings.h\"\n\n#include \"storm/utility/Stopwatch.h\"\n#include \"storm/utility/ProgressMeasurement.h\"\n#include \"storm/utility/SignalHandler.h\"\n#include \"storm/io/export.h\"\n#include \"storm/utility/NumberTraits.h\"\n\n#include \"storm/transformer/EndComponentEliminator.h\"\n\n#include \"storm/environment/solver/MinMaxSolverEnvironment.h\"\n\n#include \"storm/exceptions/InvalidStateException.h\"\n#include \"storm/exceptions/InvalidPropertyException.h\"\n#include \"storm/exceptions/InvalidSettingsException.h\"\n#include \"storm/exceptions/IllegalFunctionCallException.h\"\n#include \"storm/exceptions/IllegalArgumentException.h\"\n#include \"storm/exceptions/UncheckedRequirementException.h\"\n#include \"storm/exceptions/NotSupportedException.h\"\n\nnamespace storm {\n    namespace modelchecker {\n        namespace helper {\n\n            \n            template<typename ValueType>\n            std::map<storm::storage::sparse::state_type, ValueType> SparseMdpPrctlHelper<ValueType>::computeRewardBoundedValues(Environment const& env, OptimizationDirection dir, rewardbounded::MultiDimensionalRewardUnfolding<ValueType, true>& rewardUnfolding, storm::storage::BitVector const& initialStates) {\n                storm::utility::Stopwatch swAll(true), swBuild, swCheck;\n                \n                // Get lower and upper bounds for the solution.\n                auto lowerBound = rewardUnfolding.getLowerObjectiveBound();\n                auto upperBound = rewardUnfolding.getUpperObjectiveBound();\n                \n                // Initialize epoch models\n                auto initEpoch = rewardUnfolding.getStartEpoch();\n                auto epochOrder = rewardUnfolding.getEpochComputationOrder(initEpoch);\n                \n                // initialize data that will be needed for each epoch\n                std::vector<ValueType> x, b;\n                std::unique_ptr<storm::solver::MinMaxLinearEquationSolver<ValueType>> minMaxSolver;\n\n                ValueType precision = rewardUnfolding.getRequiredEpochModelPrecision(initEpoch, storm::utility::convertNumber<ValueType>(storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()));\n                Environment preciseEnv = env;\n                preciseEnv.solver().minMax().setPrecision(storm::utility::convertNumber<storm::RationalNumber>(precision));\n                \n                // In case of cdf export we store the necessary data.\n                std::vector<std::vector<ValueType>> cdfData;\n\n                storm::utility::ProgressMeasurement progress(\"epochs\");\n                progress.setMaxCount(epochOrder.size());\n                progress.startNewMeasurement(0);\n                uint64_t numCheckedEpochs = 0;\n                for (auto const& epoch : epochOrder) {\n                    swBuild.start();\n                    auto& epochModel = rewardUnfolding.setCurrentEpoch(epoch);\n                    swBuild.stop(); swCheck.start();\n                    rewardUnfolding.setSolutionForCurrentEpoch(epochModel.analyzeSingleObjective(preciseEnv, dir, x, b, minMaxSolver, lowerBound, upperBound));\n                    swCheck.stop();\n                    if (storm::settings::getModule<storm::settings::modules::IOSettings>().isExportCdfSet() && !rewardUnfolding.getEpochManager().hasBottomDimension(epoch)) {\n                        std::vector<ValueType> cdfEntry;\n                        for (uint64_t i = 0; i < rewardUnfolding.getEpochManager().getDimensionCount(); ++i) {\n                            uint64_t offset = rewardUnfolding.getDimension(i).boundType == helper::rewardbounded::DimensionBoundType::LowerBound ? 1 : 0;\n                            cdfEntry.push_back(storm::utility::convertNumber<ValueType>(rewardUnfolding.getEpochManager().getDimensionOfEpoch(epoch, i) + offset) * rewardUnfolding.getDimension(i).scalingFactor);\n                        }\n                        cdfEntry.push_back(rewardUnfolding.getInitialStateResult(epoch));\n                        cdfData.push_back(std::move(cdfEntry));\n                    }\n                    ++numCheckedEpochs;\n                    progress.updateProgress(numCheckedEpochs);\n                    if (storm::utility::resources::isTerminate()) {\n                        break;\n                    }\n                }\n                \n                std::map<storm::storage::sparse::state_type, ValueType> result;\n                for (auto const& initState : initialStates) {\n                    result[initState] = rewardUnfolding.getInitialStateResult(initEpoch, initState);\n                }\n                \n                swAll.stop();\n                \n                if (storm::settings::getModule<storm::settings::modules::IOSettings>().isExportCdfSet()) {\n                    std::vector<std::string> headers;\n                    for (uint64_t i = 0; i < rewardUnfolding.getEpochManager().getDimensionCount(); ++i) {\n                        headers.push_back(rewardUnfolding.getDimension(i).formula->toString());\n                    }\n                    headers.push_back(\"Result\");\n                    storm::utility::exportDataToCSVFile<ValueType, std::string, std::string>(storm::settings::getModule<storm::settings::modules::IOSettings>().getExportCdfDirectory() + \"cdf.csv\", cdfData, headers);\n                }\n\n                \n                if (storm::settings::getModule<storm::settings::modules::CoreSettings>().isShowStatisticsSet()) {\n                    STORM_PRINT_AND_LOG(\"---------------------------------\" << std::endl);\n                    STORM_PRINT_AND_LOG(\"Statistics:\" << std::endl);\n                    STORM_PRINT_AND_LOG(\"---------------------------------\" << std::endl);\n                    STORM_PRINT_AND_LOG(\"          #checked epochs: \" << epochOrder.size() << \".\" << std::endl);\n                    STORM_PRINT_AND_LOG(\"             overall Time: \" << swAll << \".\" << std::endl);\n                    STORM_PRINT_AND_LOG(\"Epoch Model building Time: \" << swBuild << \".\" << std::endl);\n                    STORM_PRINT_AND_LOG(\"Epoch Model checking Time: \" << swCheck << \".\" << std::endl);\n                    STORM_PRINT_AND_LOG(\"---------------------------------\" << std::endl);\n                }\n                \n                return  result;\n            }\n\n            template<typename ValueType>\n            std::vector<ValueType> SparseMdpPrctlHelper<ValueType>::computeNextProbabilities(Environment const& env, OptimizationDirection dir, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::BitVector const& nextStates) {\n\n                // Create the vector with which to multiply and initialize it correctly.\n                std::vector<ValueType> result(transitionMatrix.getRowGroupCount());\n                storm::utility::vector::setVectorValues(result, nextStates, storm::utility::one<ValueType>());\n                \n                auto multiplier = storm::solver::MultiplierFactory<ValueType>().create(env, transitionMatrix);\n                multiplier->multiplyAndReduce(env, dir, result, nullptr, result);\n                \n                return result;\n            }\n            \n            template<typename ValueType>\n            std::vector<uint_fast64_t> computeValidSchedulerHint(Environment const& env, SolutionType const& type, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& maybeStates, storm::storage::BitVector const& filterStates, storm::storage::BitVector const& targetStates) {\n                storm::storage::Scheduler<ValueType> validScheduler(maybeStates.size());\n\n                if (type == SolutionType::UntilProbabilities) {\n                    storm::utility::graph::computeSchedulerProbGreater0E(transitionMatrix, backwardTransitions, filterStates, targetStates, validScheduler, boost::none);\n                } else if (type == SolutionType::ExpectedRewards) {\n                    storm::utility::graph::computeSchedulerProb1E(maybeStates | targetStates, transitionMatrix, backwardTransitions, filterStates, targetStates, validScheduler);\n                } else {\n                    STORM_LOG_ASSERT(false, \"Unexpected equation system type.\");\n                }\n                \n                // Extract the relevant parts of the scheduler for the solver.\n                std::vector<uint_fast64_t> schedulerHint(maybeStates.getNumberOfSetBits());\n                auto maybeIt = maybeStates.begin();\n                for (auto& choice : schedulerHint) {\n                    choice = validScheduler.getChoice(*maybeIt).getDeterministicChoice();\n                    ++maybeIt;\n                }\n                return schedulerHint;\n            }\n            \n            template<typename ValueType>\n            struct SparseMdpHintType {\n                SparseMdpHintType() : eliminateEndComponents(false), computeUpperBounds(false), uniqueSolution(false), noEndComponents(false) {\n                    // Intentionally left empty.\n                }\n                \n                bool hasSchedulerHint() const {\n                    return static_cast<bool>(schedulerHint);\n                }\n\n                bool hasValueHint() const {\n                    return static_cast<bool>(valueHint);\n                }\n\n                bool hasLowerResultBound() const {\n                    return static_cast<bool>(lowerResultBound);\n                }\n\n                ValueType const& getLowerResultBound() const {\n                    return lowerResultBound.get();\n                }\n                \n                bool hasUpperResultBound() const {\n                    return static_cast<bool>(upperResultBound);\n                }\n                \n                bool hasUpperResultBounds() const {\n                    return static_cast<bool>(upperResultBounds);\n                }\n\n                ValueType const& getUpperResultBound() const {\n                    return upperResultBound.get();\n                }\n\n                std::vector<ValueType>& getUpperResultBounds() {\n                    return upperResultBounds.get();\n                }\n                \n                std::vector<ValueType> const& getUpperResultBounds() const {\n                    return upperResultBounds.get();\n                }\n                \n                std::vector<uint64_t>& getSchedulerHint() {\n                    return schedulerHint.get();\n                }\n                \n                std::vector<ValueType>& getValueHint() {\n                    return valueHint.get();\n                }\n                \n                bool getEliminateEndComponents() const {\n                    return eliminateEndComponents;\n                }\n\n                bool getComputeUpperBounds() {\n                    return computeUpperBounds;\n                }\n\n                bool hasUniqueSolution() const {\n                    return uniqueSolution;\n                }\n                \n                bool hasNoEndComponents() const {\n                    return noEndComponents;\n                }\n                \n                boost::optional<std::vector<uint64_t>> schedulerHint;\n                boost::optional<std::vector<ValueType>> valueHint;\n                boost::optional<ValueType> lowerResultBound;\n                boost::optional<ValueType> upperResultBound;\n                boost::optional<std::vector<ValueType>> upperResultBounds;\n                bool eliminateEndComponents;\n                bool computeUpperBounds;\n                bool uniqueSolution;\n                bool noEndComponents;\n            };\n            \n            template<typename ValueType>\n            void extractValueAndSchedulerHint(SparseMdpHintType<ValueType>& hintStorage, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& maybeStates, boost::optional<storm::storage::BitVector> const& selectedChoices, ModelCheckerHint const& hint, bool skipECWithinMaybeStatesCheck) {\n                \n                // Deal with scheduler hint.\n                if (hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().hasSchedulerHint()) {\n                    if (hintStorage.hasSchedulerHint()) {\n                        STORM_LOG_WARN(\"A scheduler hint was provided, but the solver requires a specific one. The provided scheduler hint will be ignored.\");\n                    } else {\n                        auto const& schedulerHint = hint.template asExplicitModelCheckerHint<ValueType>().getSchedulerHint();\n                        std::vector<uint64_t> hintChoices;\n\n                        // The scheduler hint is only applicable if it induces no BSCC consisting of maybe states.\n                        bool hintApplicable;\n                        if (!skipECWithinMaybeStatesCheck) {\n                            hintChoices.reserve(maybeStates.size());\n                            for (uint_fast64_t state = 0; state < maybeStates.size(); ++state) {\n                                hintChoices.push_back(schedulerHint.getChoice(state).getDeterministicChoice());\n                            }\n                            hintApplicable = storm::utility::graph::performProb1(transitionMatrix.transposeSelectedRowsFromRowGroups(hintChoices), maybeStates, ~maybeStates).full();\n                        } else {\n                            hintApplicable = true;\n                        }\n    \n                        if (hintApplicable) {\n                            // Compute the hint w.r.t. the given subsystem.\n                            hintChoices.clear();\n                            hintChoices.reserve(maybeStates.getNumberOfSetBits());\n                            for (auto const& state : maybeStates) {\n                                uint_fast64_t hintChoice = schedulerHint.getChoice(state).getDeterministicChoice();\n                                if (selectedChoices) {\n                                    uint_fast64_t firstChoice = transitionMatrix.getRowGroupIndices()[state];\n                                    uint_fast64_t lastChoice = firstChoice + hintChoice;\n                                    hintChoice = 0;\n                                    for (uint_fast64_t choice = selectedChoices->getNextSetIndex(firstChoice); choice < lastChoice; choice = selectedChoices->getNextSetIndex(choice + 1)) {\n                                        ++hintChoice;\n                                    }\n                                }\n                                hintChoices.push_back(hintChoice);\n                            }\n                            hintStorage.schedulerHint = std::move(hintChoices);\n                        }\n                    }\n                }\n                \n                // Deal with solution value hint. Only applicable if there are no End Components consisting of maybe states.\n                if (hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().hasResultHint() && (skipECWithinMaybeStatesCheck || hintStorage.hasSchedulerHint() || storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, maybeStates, ~maybeStates).full())) {\n                    hintStorage.valueHint = storm::utility::vector::filterVector(hint.template asExplicitModelCheckerHint<ValueType>().getResultHint(), maybeStates);\n                }\n            }\n            \n            template<typename ValueType>\n            SparseMdpHintType<ValueType> computeHints(Environment const& env, SolutionType const& type, ModelCheckerHint const& hint, storm::OptimizationDirection const& dir, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& maybeStates, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& targetStates, bool produceScheduler, boost::optional<storm::storage::BitVector> const& selectedChoices = boost::none) {\n                SparseMdpHintType<ValueType> result;\n\n                // There are no end components if we minimize until probabilities or\n                // maximize reachability rewards or if the hint tells us so.\n                result.noEndComponents = (dir == storm::solver::OptimizationDirection::Minimize && type == SolutionType::UntilProbabilities)\n                                      || (dir == storm::solver::OptimizationDirection::Maximize && type == SolutionType::ExpectedRewards)\n                                      || (hint.isExplicitModelCheckerHint() && hint.asExplicitModelCheckerHint<ValueType>().getNoEndComponentsInMaybeStates());\n                \n                // If there are no end components, the solution is unique. (Note that the other direction does not hold,\n                // e.g., end components in which infinite reward is collected.\n                result.uniqueSolution = result.hasNoEndComponents();\n                \n                // Check for requirements of the solver.\n                bool hasSchedulerHint = hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().hasSchedulerHint();\n                storm::solver::GeneralMinMaxLinearEquationSolverFactory<ValueType> minMaxLinearEquationSolverFactory;\n                storm::solver::MinMaxLinearEquationSolverRequirements requirements = minMaxLinearEquationSolverFactory.getRequirements(env, result.uniqueSolution, result.noEndComponents, dir, hasSchedulerHint, produceScheduler);\n                if (requirements.hasEnabledRequirement()) {\n                    // If the solver still requires no end-components, we have to eliminate them later.\n                    if (requirements.uniqueSolution()) {\n                        STORM_LOG_ASSERT(!result.hasUniqueSolution(), \"The solver requires to eliminate the end components although the solution is already assumed to be unique.\");\n                        STORM_LOG_DEBUG(\"Scheduling EC elimination, because the solver requires a unique solution.\");\n                        result.eliminateEndComponents = true;\n                        // If end components have been eliminated we can assume a unique solution.\n                        result.uniqueSolution = true;\n                        requirements.clearUniqueSolution();\n                        // If we compute until probabilities, we can even assume the absence of end components.\n                        // Note that in the case of minimizing expected rewards there might still be end components in which reward is collected.\n                        result.noEndComponents = (type == SolutionType::UntilProbabilities);\n                    }\n                    \n                    // If the solver requires an initial scheduler, compute one now. Note that any scheduler is valid if there are no end components.\n                    if (requirements.validInitialScheduler() && !result.noEndComponents) {\n                        STORM_LOG_DEBUG(\"Computing valid scheduler, because the solver requires it.\");\n                        result.schedulerHint = computeValidSchedulerHint(env, type, transitionMatrix, backwardTransitions, maybeStates, phiStates, targetStates);\n                        requirements.clearValidInitialScheduler();\n                    }\n                    \n                    // Finally, we have information on the bounds depending on the problem type.\n                    if (type == SolutionType::UntilProbabilities) {\n                        requirements.clearBounds();\n                    } else if (type == SolutionType::ExpectedRewards) {\n                        requirements.clearLowerBounds();\n                    }\n                    if (requirements.upperBounds()) {\n                        result.computeUpperBounds = true;\n                        requirements.clearUpperBounds();\n                    }\n                    STORM_LOG_THROW(!requirements.hasEnabledCriticalRequirement(), storm::exceptions::UncheckedRequirementException, \"Solver requirements \" + requirements.getEnabledRequirementsAsString() + \" not checked.\");\n                } else {\n                    STORM_LOG_DEBUG(\"Solver has no requirements.\");\n                }\n\n                // Only if there is no end component decomposition that we will need to do later, we use value and scheduler\n                // hints from the provided hint.\n                if (!result.eliminateEndComponents) {\n                    extractValueAndSchedulerHint(result, transitionMatrix, backwardTransitions, maybeStates, selectedChoices, hint, result.uniqueSolution);\n                } else {\n                    STORM_LOG_WARN_COND(hint.isEmpty(), \"A non-empty hint was provided, but its information will be disregarded.\");\n                }\n\n                // Only set bounds if we did not obtain them from the hint.\n                if (!result.hasLowerResultBound()) {\n                    result.lowerResultBound = storm::utility::zero<ValueType>();\n                }\n                if (!result.hasUpperResultBound() && type == SolutionType::UntilProbabilities) {\n                    result.upperResultBound = storm::utility::one<ValueType>();\n                }\n                \n                // If we received an upper bound, we can drop the requirement to compute one.\n                if (result.hasUpperResultBound()) {\n                    result.computeUpperBounds = false;\n                }\n\n                return result;\n            }\n            \n            template<typename ValueType>\n            struct MaybeStateResult {\n                MaybeStateResult(std::vector<ValueType>&& values) : values(std::move(values)) {\n                    // Intentionally left empty.\n                }\n                \n                bool hasScheduler() const {\n                    return static_cast<bool>(scheduler);\n                }\n                \n                std::vector<uint64_t> const& getScheduler() const {\n                    return scheduler.get();\n                }\n                \n                std::vector<ValueType> const& getValues() const {\n                    return values;\n                }\n                \n                std::vector<ValueType> values;\n                boost::optional<std::vector<uint64_t>> scheduler;\n            };\n            \n            template<typename ValueType>\n            MaybeStateResult<ValueType> computeValuesForMaybeStates(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType>&& submatrix, std::vector<ValueType> const& b, bool produceScheduler, SparseMdpHintType<ValueType>& hint) {\n                \n                // Initialize the solution vector.\n                std::vector<ValueType> x = hint.hasValueHint() ? std::move(hint.getValueHint()) : std::vector<ValueType>(submatrix.getRowGroupCount(), hint.hasLowerResultBound() ? hint.getLowerResultBound() : storm::utility::zero<ValueType>());\n                \n                // Set up the solver.\n                storm::solver::GeneralMinMaxLinearEquationSolverFactory<ValueType> minMaxLinearEquationSolverFactory;\n                std::unique_ptr<storm::solver::MinMaxLinearEquationSolver<ValueType>> solver = storm::solver::configureMinMaxLinearEquationSolver(env, std::move(goal), minMaxLinearEquationSolverFactory, std::move(submatrix));\n                solver->setRequirementsChecked();\n                solver->setHasUniqueSolution(hint.hasUniqueSolution());\n                solver->setHasNoEndComponents(hint.hasNoEndComponents());\n                if (hint.hasLowerResultBound()) {\n                    solver->setLowerBound(hint.getLowerResultBound());\n                }\n                if (hint.hasUpperResultBound()) {\n                    solver->setUpperBound(hint.getUpperResultBound());\n                }\n                if (hint.hasUpperResultBounds()) {\n                    solver->setUpperBounds(std::move(hint.getUpperResultBounds()));\n                }\n                if (hint.hasSchedulerHint()) {\n                    solver->setInitialScheduler(std::move(hint.getSchedulerHint()));\n                }\n                solver->setTrackScheduler(produceScheduler);\n                \n                // Solve the corresponding system of equations.\n                solver->solveEquations(env, x, b);\n                \n#ifndef NDEBUG\n                // As a sanity check, make sure our local upper bounds were in fact correct.\n                if (solver->hasUpperBound(storm::solver::AbstractEquationSolver<ValueType>::BoundType::Local)) {\n                    auto resultIt = x.begin();\n                    for (auto const& entry : solver->getUpperBounds()) {\n                        STORM_LOG_ASSERT(*resultIt <= entry + env.solver().minMax().getPrecision(), \"Expecting result value for state \" << std::distance(x.begin(), resultIt) << \" to be <= \" << entry << \", but got \" << *resultIt << \".\");\n                        ++resultIt;\n                    }\n                }\n#endif\n                \n                // Create result.\n                MaybeStateResult<ValueType> result(std::move(x));\n\n                // If requested, return the requested scheduler.\n                if (produceScheduler) {\n                    result.scheduler = std::move(solver->getSchedulerChoices());\n                }\n                return result;\n            }\n            \n            struct QualitativeStateSetsUntilProbabilities {\n                storm::storage::BitVector maybeStates;\n                storm::storage::BitVector statesWithProbability0;\n                storm::storage::BitVector statesWithProbability1;\n            };\n            \n            template<typename ValueType>\n            QualitativeStateSetsUntilProbabilities getQualitativeStateSetsUntilProbabilitiesFromHint(ModelCheckerHint const& hint) {\n                QualitativeStateSetsUntilProbabilities result;\n                result.maybeStates = hint.template asExplicitModelCheckerHint<ValueType>().getMaybeStates();\n                \n                // Treat the states with probability zero/one.\n                std::vector<ValueType> const& resultsForNonMaybeStates = hint.template asExplicitModelCheckerHint<ValueType>().getResultHint();\n                result.statesWithProbability1 = storm::storage::BitVector(result.maybeStates.size());\n                result.statesWithProbability0 = storm::storage::BitVector(result.maybeStates.size());\n                storm::storage::BitVector nonMaybeStates = ~result.maybeStates;\n                for (auto const& state : nonMaybeStates) {\n                    if (storm::utility::isOne(resultsForNonMaybeStates[state])) {\n                        result.statesWithProbability1.set(state, true);\n                    } else {\n                        STORM_LOG_THROW(storm::utility::isZero(resultsForNonMaybeStates[state]), storm::exceptions::IllegalArgumentException, \"Expected that the result hint specifies probabilities in {0,1} for non-maybe states\");\n                        result.statesWithProbability0.set(state, true);\n                    }\n                }\n                \n                return result;\n            }\n            \n            template<typename ValueType>\n            QualitativeStateSetsUntilProbabilities computeQualitativeStateSetsUntilProbabilities(storm::solver::SolveGoal<ValueType> const& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates) {\n                QualitativeStateSetsUntilProbabilities result;\n\n                // Get all states that have probability 0 and 1 of satisfying the until-formula.\n                std::pair<storm::storage::BitVector, storm::storage::BitVector> statesWithProbability01;\n                if (goal.minimize()) {\n                    statesWithProbability01 = storm::utility::graph::performProb01Min(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, phiStates, psiStates);\n                } else {\n                    statesWithProbability01 = storm::utility::graph::performProb01Max(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, phiStates, psiStates);\n                }\n                result.statesWithProbability0 = std::move(statesWithProbability01.first);\n                result.statesWithProbability1 = std::move(statesWithProbability01.second);\n                result.maybeStates = ~(result.statesWithProbability0 | result.statesWithProbability1);\n                \n                return result;\n            }\n            \n            template<typename ValueType>\n            QualitativeStateSetsUntilProbabilities getQualitativeStateSetsUntilProbabilities(storm::solver::SolveGoal<ValueType> const& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, ModelCheckerHint const& hint) {\n                if (hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().getComputeOnlyMaybeStates()) {\n                    return getQualitativeStateSetsUntilProbabilitiesFromHint<ValueType>(hint);\n                } else {\n                    return computeQualitativeStateSetsUntilProbabilities(goal, transitionMatrix, backwardTransitions, phiStates, psiStates);\n                }\n            }\n            \n            template<typename ValueType>\n            void extractSchedulerChoices(storm::storage::Scheduler<ValueType>& scheduler, std::vector<uint_fast64_t> const& subChoices, storm::storage::BitVector const& maybeStates) {\n                auto subChoiceIt = subChoices.begin();\n                for (auto maybeState : maybeStates) {\n                    scheduler.setChoice(*subChoiceIt, maybeState);\n                    ++subChoiceIt;\n                }\n                assert(subChoiceIt == subChoices.end());\n            }\n            \n            template<typename ValueType>\n            void extendScheduler(storm::storage::Scheduler<ValueType>& scheduler, storm::solver::SolveGoal<ValueType> const& goal, QualitativeStateSetsUntilProbabilities const& qualitativeStateSets, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates) {\n                \n                // Finally, if we need to produce a scheduler, we also need to figure out the parts of the scheduler for\n                // the states with probability 1 or 0 (depending on whether we maximize or minimize).\n                // We also need to define some arbitrary choice for the remaining states to obtain a fully defined scheduler.\n                if (goal.minimize()) {\n                    storm::utility::graph::computeSchedulerProb0E(qualitativeStateSets.statesWithProbability0, transitionMatrix, scheduler);\n                    for (auto const& prob1State : qualitativeStateSets.statesWithProbability1) {\n                        scheduler.setChoice(0, prob1State);\n                    }\n                } else {\n                    storm::utility::graph::computeSchedulerProb1E(qualitativeStateSets.statesWithProbability1, transitionMatrix, backwardTransitions, phiStates, psiStates, scheduler);\n                    for (auto const& prob0State : qualitativeStateSets.statesWithProbability0) {\n                        scheduler.setChoice(0, prob0State);\n                    }\n                }\n            }\n            \n            template<typename ValueType>\n            void computeFixedPointSystemUntilProbabilities(storm::solver::SolveGoal<ValueType>& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, QualitativeStateSetsUntilProbabilities const& qualitativeStateSets, storm::storage::SparseMatrix<ValueType>& submatrix, std::vector<ValueType>& b) {\n                // First, we can eliminate the rows and columns from the original transition probability matrix for states\n                // whose probabilities are already known.\n                submatrix = transitionMatrix.getSubmatrix(true, qualitativeStateSets.maybeStates, qualitativeStateSets.maybeStates, false);\n                \n                // Prepare the right-hand side of the equation system. For entry i this corresponds to\n                // the accumulated probability of going from state i to some state that has probability 1.\n                b = transitionMatrix.getConstrainedRowGroupSumVector(qualitativeStateSets.maybeStates, qualitativeStateSets.statesWithProbability1);\n                \n                // If the solve goal has relevant values, we need to adjust them.\n                goal.restrictRelevantValues(qualitativeStateSets.maybeStates);\n            }\n            \n            template<typename ValueType>\n            boost::optional<SparseMdpEndComponentInformation<ValueType>> computeFixedPointSystemUntilProbabilitiesEliminateEndComponents(storm::solver::SolveGoal<ValueType>& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, QualitativeStateSetsUntilProbabilities const& qualitativeStateSets, storm::storage::SparseMatrix<ValueType>& submatrix, std::vector<ValueType>& b, bool produceScheduler) {\n                \n                // Get the set of states that (under some scheduler) can stay in the set of maybestates forever\n                storm::storage::BitVector candidateStates = storm::utility::graph::performProb0E(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, qualitativeStateSets.maybeStates, ~qualitativeStateSets.maybeStates);\n                \n                bool doDecomposition = !candidateStates.empty();\n                \n                storm::storage::MaximalEndComponentDecomposition<ValueType> endComponentDecomposition;\n                if (doDecomposition) {\n                    // Compute the states that are in MECs.\n                    endComponentDecomposition = storm::storage::MaximalEndComponentDecomposition<ValueType>(transitionMatrix, backwardTransitions, candidateStates);\n                }\n                \n                // Only do more work if there are actually end-components.\n                if (doDecomposition && !endComponentDecomposition.empty()) {\n                    STORM_LOG_DEBUG(\"Eliminating \" << endComponentDecomposition.size() << \" EC(s).\");\n                    SparseMdpEndComponentInformation<ValueType> result = SparseMdpEndComponentInformation<ValueType>::eliminateEndComponents(endComponentDecomposition, transitionMatrix, qualitativeStateSets.maybeStates, &qualitativeStateSets.statesWithProbability1, nullptr, nullptr, submatrix, &b, nullptr, produceScheduler);\n                    \n                    // If the solve goal has relevant values, we need to adjust them.\n                    if (goal.hasRelevantValues()) {\n                        storm::storage::BitVector newRelevantValues(submatrix.getRowGroupCount());\n                        for (auto state : goal.relevantValues()) {\n                            if (qualitativeStateSets.maybeStates.get(state)) {\n                                newRelevantValues.set(result.getRowGroupAfterElimination(state));\n                            }\n                        }\n                        if (!newRelevantValues.empty()) {\n                            goal.setRelevantValues(std::move(newRelevantValues));\n                        }\n                    }\n                    \n                    return result;\n                } else {\n                    STORM_LOG_DEBUG(\"Not eliminating ECs as there are none.\");\n                    computeFixedPointSystemUntilProbabilities(goal, transitionMatrix, qualitativeStateSets, submatrix, b);\n                    \n                    return boost::none;\n                }\n            }\n            \n            template<typename ValueType>\n            MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint) {\n                STORM_LOG_THROW(!qualitative || !produceScheduler, storm::exceptions::InvalidSettingsException, \"Cannot produce scheduler when performing qualitative model checking only.\");\n                \n                // Prepare resulting vector.\n                std::vector<ValueType> result(transitionMatrix.getRowGroupCount(), storm::utility::zero<ValueType>());\n                \n                // We need to identify the maybe states (states which have a probability for satisfying the until formula\n                // that is strictly between 0 and 1) and the states that satisfy the formula with probablity 1 and 0, respectively.\n                QualitativeStateSetsUntilProbabilities qualitativeStateSets = getQualitativeStateSetsUntilProbabilities(goal, transitionMatrix, backwardTransitions, phiStates, psiStates, hint);\n                \n                STORM_LOG_INFO(\"Preprocessing: \" << qualitativeStateSets.statesWithProbability1.getNumberOfSetBits() << \" states with probability 1, \" << qualitativeStateSets.statesWithProbability0.getNumberOfSetBits() << \" with probability 0 (\" << qualitativeStateSets.maybeStates.getNumberOfSetBits() << \" states remaining).\");\n                \n                // Set values of resulting vector that are known exactly.\n                storm::utility::vector::setVectorValues<ValueType>(result, qualitativeStateSets.statesWithProbability1, storm::utility::one<ValueType>());\n                \n                // If requested, we will produce a scheduler.\n                std::unique_ptr<storm::storage::Scheduler<ValueType>> scheduler;\n                if (produceScheduler) {\n                    scheduler = std::make_unique<storm::storage::Scheduler<ValueType>>(transitionMatrix.getRowGroupCount());\n                }\n                \n                // Check whether we need to compute exact probabilities for some states.\n                if (qualitative) {\n                    // Set the values for all maybe-states to 0.5 to indicate that their probability values are neither 0 nor 1.\n                    storm::utility::vector::setVectorValues<ValueType>(result, qualitativeStateSets.maybeStates, storm::utility::convertNumber<ValueType>(0.5));\n                } else {\n                    if (!qualitativeStateSets.maybeStates.empty()) {\n                        // In this case we have have to compute the remaining probabilities.\n                        \n                        // Obtain proper hint information either from the provided hint or from requirements of the solver.\n                        SparseMdpHintType<ValueType> hintInformation = computeHints(env, SolutionType::UntilProbabilities, hint, goal.direction(), transitionMatrix, backwardTransitions, qualitativeStateSets.maybeStates, phiStates, qualitativeStateSets.statesWithProbability1, produceScheduler);\n                        \n                        // Declare the components of the equation system we will solve.\n                        storm::storage::SparseMatrix<ValueType> submatrix;\n                        std::vector<ValueType> b;\n                        \n                        // If the hint information tells us that we have to eliminate MECs, we do so now.\n                        boost::optional<SparseMdpEndComponentInformation<ValueType>> ecInformation;\n                        if (hintInformation.getEliminateEndComponents()) {\n                            ecInformation = computeFixedPointSystemUntilProbabilitiesEliminateEndComponents(goal, transitionMatrix, backwardTransitions, qualitativeStateSets, submatrix, b, produceScheduler);\n                        } else {\n                            // Otherwise, we compute the standard equations.\n                            computeFixedPointSystemUntilProbabilities(goal, transitionMatrix, qualitativeStateSets, submatrix, b);\n                        }\n                        \n                        // Now compute the results for the maybe states.\n                        MaybeStateResult<ValueType> resultForMaybeStates = computeValuesForMaybeStates(env, std::move(goal), std::move(submatrix), b, produceScheduler, hintInformation);\n                        \n                        // If we eliminated end components, we need to extract the result differently.\n                        if (ecInformation && ecInformation.get().getEliminatedEndComponents()) {\n                            ecInformation.get().setValues(result, qualitativeStateSets.maybeStates, resultForMaybeStates.getValues());\n                            if (produceScheduler) {\n                                ecInformation.get().setScheduler(*scheduler, qualitativeStateSets.maybeStates, transitionMatrix, backwardTransitions, resultForMaybeStates.getScheduler());\n                            }\n                        } else {\n                            // Set values of resulting vector according to result.\n                            storm::utility::vector::setVectorValues<ValueType>(result, qualitativeStateSets.maybeStates, resultForMaybeStates.getValues());\n                            if (produceScheduler) {\n                                extractSchedulerChoices(*scheduler, resultForMaybeStates.getScheduler(), qualitativeStateSets.maybeStates);\n                            }\n                        }\n                    }\n                }\n\n                // Extend scheduler with choices for the states in the qualitative state sets.\n                if (produceScheduler) {\n                    extendScheduler(*scheduler, goal, qualitativeStateSets, transitionMatrix, backwardTransitions, phiStates, psiStates);\n                }\n                \n                // Sanity check for created scheduler.\n                STORM_LOG_ASSERT(!produceScheduler || scheduler, \"Expected that a scheduler was obtained.\");\n                STORM_LOG_ASSERT((!produceScheduler && !scheduler) || !scheduler->isPartialScheduler(), \"Expected a fully defined scheduler\");\n                STORM_LOG_ASSERT((!produceScheduler && !scheduler) || scheduler->isDeterministicScheduler(), \"Expected a deterministic scheduler\");\n                STORM_LOG_ASSERT((!produceScheduler && !scheduler) || scheduler->isMemorylessScheduler(), \"Expected a memoryless scheduler\");\n\n                // Return result.\n                return MDPSparseModelCheckingHelperReturnType<ValueType>(std::move(result), std::move(scheduler));\n            }\n\n            template<typename ValueType>\n            std::vector<ValueType> SparseMdpPrctlHelper<ValueType>::computeGloballyProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& psiStates, bool qualitative, bool useMecBasedTechnique) {\n                if (useMecBasedTechnique) {\n                    storm::storage::MaximalEndComponentDecomposition<ValueType> mecDecomposition(transitionMatrix, backwardTransitions, psiStates);\n                    storm::storage::BitVector statesInPsiMecs(transitionMatrix.getRowGroupCount());\n                    for (auto const& mec : mecDecomposition) {\n                        for (auto const& stateActionsPair : mec) {\n                            statesInPsiMecs.set(stateActionsPair.first, true);\n                        }\n                    }\n                    \n                    return std::move(computeUntilProbabilities(env, std::move(goal), transitionMatrix, backwardTransitions, psiStates, statesInPsiMecs, qualitative, false).values);\n                } else {\n                    goal.oneMinus();\n                    std::vector<ValueType> result = computeUntilProbabilities(env, std::move(goal), transitionMatrix, backwardTransitions, storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true), ~psiStates, qualitative, false).values;\n                    for (auto& element : result) {\n                        element = storm::utility::one<ValueType>() - element;\n                    }\n                    return std::move(result); // move() required by, e.g., clang 3.8\n                }\n            }\n            \n            template<typename ValueType>\n            template<typename RewardModelType>\n            std::vector<ValueType> SparseMdpPrctlHelper<ValueType>::computeInstantaneousRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, RewardModelType const& rewardModel, uint_fast64_t stepCount) {\n\n                // Only compute the result if the model has a state-based reward this->getModel().\n                STORM_LOG_THROW(rewardModel.hasStateRewards(), storm::exceptions::InvalidPropertyException, \"Missing reward model for formula. Skipping formula.\");\n                \n                // Initialize result to state rewards of the this->getModel().\n                std::vector<ValueType> result(rewardModel.getStateRewardVector());\n                \n                auto multiplier = storm::solver::MultiplierFactory<ValueType>().create(env, transitionMatrix);\n                multiplier->repeatedMultiplyAndReduce(env, goal.direction(), result, nullptr, stepCount);\n\n                return result;\n            }\n            \n            template<typename ValueType>\n            template<typename RewardModelType>\n            std::vector<ValueType> SparseMdpPrctlHelper<ValueType>::computeCumulativeRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, RewardModelType const& rewardModel, uint_fast64_t stepBound) {\n\n                // Only compute the result if the model has at least one reward this->getModel().\n                STORM_LOG_THROW(!rewardModel.empty(), storm::exceptions::InvalidPropertyException, \"Missing reward model for formula. Skipping formula.\");\n                \n                // Compute the reward vector to add in each step based on the available reward models.\n                std::vector<ValueType> totalRewardVector = rewardModel.getTotalRewardVector(transitionMatrix);\n                \n                // Initialize result to the zero vector.\n                std::vector<ValueType> result(transitionMatrix.getRowGroupCount(), storm::utility::zero<ValueType>());\n                \n                auto multiplier = storm::solver::MultiplierFactory<ValueType>().create(env, transitionMatrix);\n                multiplier->repeatedMultiplyAndReduce(env, goal.direction(), result, &totalRewardVector, stepBound);\n                \n                return result;\n            }\n            \n            template<typename ValueType>\n            template<typename RewardModelType>\n            MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeTotalRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, RewardModelType const& rewardModel, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint) {\n\n                // Reduce to reachability rewards\n                if (goal.minimize()) {\n                    STORM_LOG_ERROR_COND(!produceScheduler, \"Can not produce scheduler for this property (functionality not implemented\");\n                    // Identify the states from which no reward can be collected under some scheduler\n                    storm::storage::BitVector choicesWithoutReward = rewardModel.getChoicesWithZeroReward(transitionMatrix);\n                    storm::storage::BitVector statesWithZeroRewardChoice(transitionMatrix.getRowGroupCount(), false);\n                    for (uint64_t state = 0; state < transitionMatrix.getRowGroupCount(); ++state) {\n                        if (choicesWithoutReward.getNextSetIndex(transitionMatrix.getRowGroupIndices()[state])< transitionMatrix.getRowGroupIndices()[state + 1]) {\n                            statesWithZeroRewardChoice.set(state);\n                        }\n                    }\n                    storm::storage::BitVector rew0EStates = storm::utility::graph::performProbGreater0A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, statesWithZeroRewardChoice, ~statesWithZeroRewardChoice, false, 0, choicesWithoutReward);\n                    rew0EStates.complement();\n                    return computeReachabilityRewards(env, std::move(goal), transitionMatrix, backwardTransitions, rewardModel, rew0EStates, qualitative, false, hint);\n                } else {\n                    // Identify the states from which only states with zero reward are reachable.\n                    storm::storage::BitVector statesWithoutReward = rewardModel.getStatesWithZeroReward(transitionMatrix);\n                    storm::storage::BitVector rew0AStates = storm::utility::graph::performProbGreater0E(backwardTransitions, statesWithoutReward, ~statesWithoutReward);\n                    rew0AStates.complement();\n                    \n                    // There might be end components that consists only of states/choices with zero rewards. The reachability reward semantics would assign such\n                    // end components reward infinity. To avoid this, we potentially need to eliminate such end components\n                    storm::storage::BitVector trueStates(transitionMatrix.getRowGroupCount(), true);\n                    if (storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, trueStates, rew0AStates).full()) {\n                        return computeReachabilityRewards(env, std::move(goal), transitionMatrix, backwardTransitions, rewardModel, rew0AStates, qualitative, produceScheduler, hint);\n                    } else {\n                        // The transformation of schedulers for the ec-eliminated system back to the original one is not implemented.\n                        STORM_LOG_ERROR_COND(!produceScheduler, \"Can not produce scheduler for this property (functionality not implemented\");\n                        storm::storage::BitVector choicesWithoutReward = rewardModel.getChoicesWithZeroReward(transitionMatrix);\n                        auto ecElimResult = storm::transformer::EndComponentEliminator<ValueType>::transform(transitionMatrix, storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true), choicesWithoutReward, rew0AStates, true);\n                        storm::storage::BitVector newRew0AStates(ecElimResult.matrix.getRowGroupCount(), false);\n                        for (auto const& oldRew0AState : rew0AStates) {\n                            newRew0AStates.set(ecElimResult.oldToNewStateMapping[oldRew0AState]);\n                        }\n                        \n                        MDPSparseModelCheckingHelperReturnType<ValueType> result = computeReachabilityRewardsHelper(env, std::move(goal), ecElimResult.matrix, ecElimResult.matrix.transpose(true),\n                                                                [&] (uint_fast64_t rowCount, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::BitVector const& maybeStates) {\n                                                                    std::vector<ValueType> result;\n                                                                    std::vector<ValueType> oldChoiceRewards = rewardModel.getTotalRewardVector(transitionMatrix);\n                                                                    result.reserve(rowCount);\n                                                                    for (uint64_t newState : maybeStates) {\n                                                                        for (uint64_t newChoice = transitionMatrix.getRowGroupIndices()[newState]; newChoice < transitionMatrix.getRowGroupIndices()[newState + 1]; ++newChoice) {\n                                                                            uint64_t oldChoice = ecElimResult.newToOldRowMapping[newChoice];\n                                                                            result.push_back(oldChoiceRewards[oldChoice]);\n                                                                        }\n                                                                    }\n                                                                    STORM_LOG_ASSERT(result.size() == rowCount, \"Unexpected size of reward vector.\");\n                                                                    return result;\n                                                                }, newRew0AStates, qualitative, false,\n                                                                [&] () {\n                                                                    storm::storage::BitVector newStatesWithoutReward(ecElimResult.matrix.getRowGroupCount(), false);\n                                                                    for (auto const& oldStateWithoutRew : statesWithoutReward) {\n                                                                        newStatesWithoutReward.set(ecElimResult.oldToNewStateMapping[oldStateWithoutRew]);\n                                                                    }\n                                                                    return newStatesWithoutReward;\n                                                                },\n                                                                [&] () {\n                                                                    storm::storage::BitVector newChoicesWithoutReward(ecElimResult.matrix.getRowGroupCount(), false);\n                                                                    for (uint64_t newChoice = 0; newChoice < ecElimResult.matrix.getRowCount(); ++newChoice) {\n                                                                            if (choicesWithoutReward.get(ecElimResult.newToOldRowMapping[newChoice])) {\n                                                                                newChoicesWithoutReward.set(newChoice);\n                                                                            }\n                                                                    }\n                                                                    return newChoicesWithoutReward;\n                                                                });\n                        \n                        std::vector<ValueType> resultInEcQuotient = std::move(result.values);\n                        result.values.resize(ecElimResult.oldToNewStateMapping.size());\n                        storm::utility::vector::selectVectorValues(result.values, ecElimResult.oldToNewStateMapping, resultInEcQuotient);\n                        return result;\n                    }\n                }\n            }\n            \n            template<typename ValueType>\n            template<typename RewardModelType>\n            MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeReachabilityRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, RewardModelType const& rewardModel, storm::storage::BitVector const& targetStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint) {\n                // Only compute the result if the model has at least one reward this->getModel().\n                STORM_LOG_THROW(!rewardModel.empty(), storm::exceptions::InvalidPropertyException, \"Reward model for formula is empty. Skipping formula.\");\n                return computeReachabilityRewardsHelper(env, std::move(goal), transitionMatrix, backwardTransitions,\n                                                        [&rewardModel] (uint_fast64_t rowCount, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::BitVector const& maybeStates) {\n                                                            return rewardModel.getTotalRewardVector(rowCount, transitionMatrix, maybeStates);\n                                                        },\n                                                        targetStates, qualitative, produceScheduler,\n                                                        [&] () {\n                                                            return rewardModel.getStatesWithZeroReward(transitionMatrix);\n                                                        },\n                                                        [&] () {\n                                                            return rewardModel.getChoicesWithZeroReward(transitionMatrix);\n                                                        },\n                                                        hint);\n            }\n            \n            template<typename ValueType>\n            MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeReachabilityTimes(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint) {\n                return computeReachabilityRewardsHelper(env, std::move(goal), transitionMatrix, backwardTransitions,\n                                                        [] (uint_fast64_t rowCount, storm::storage::SparseMatrix<ValueType> const&, storm::storage::BitVector const&) {\n                                                            return std::vector<ValueType>(rowCount, storm::utility::one<ValueType>());\n                                                        },\n                                                        targetStates, qualitative, produceScheduler,\n                                                        [&] () {\n                                                            return storm::storage::BitVector(transitionMatrix.getRowGroupCount(), false);\n                                                        },\n                                                        [&] () {\n                                                            return storm::storage::BitVector(transitionMatrix.getRowCount(), false);\n                                                        },\n                                                        hint);\n            }\n            \n#ifdef STORM_HAVE_CARL\n            template<typename ValueType>\n            std::vector<ValueType> SparseMdpPrctlHelper<ValueType>::computeReachabilityRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::models::sparse::StandardRewardModel<storm::Interval> const& intervalRewardModel, bool lowerBoundOfIntervals, storm::storage::BitVector const& targetStates, bool qualitative) {\n                // Only compute the result if the reward model is not empty.\n                STORM_LOG_THROW(!intervalRewardModel.empty(), storm::exceptions::InvalidPropertyException, \"Missing reward model for formula. Skipping formula.\");\n                return computeReachabilityRewardsHelper(env, std::move(goal), transitionMatrix, backwardTransitions, \\\n                                                        [&] (uint_fast64_t rowCount, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::BitVector const& maybeStates) {\n                                                            std::vector<ValueType> result;\n                                                            result.reserve(rowCount);\n                                                            std::vector<storm::Interval> subIntervalVector = intervalRewardModel.getTotalRewardVector(rowCount, transitionMatrix, maybeStates);\n                                                            for (auto const& interval : subIntervalVector) {\n                                                                result.push_back(lowerBoundOfIntervals ? interval.lower() : interval.upper());\n                                                            }\n                                                            return result;\n                                                        },\n                                                        targetStates, qualitative, false,\n                                                        [&] () {\n                                                            return intervalRewardModel.getStatesWithFilter(transitionMatrix, [&](storm::Interval const& i) {return storm::utility::isZero(lowerBoundOfIntervals ? i.lower() : i.upper());});\n                                                        },\n                                                        [&] () {\n                                                            return intervalRewardModel.getChoicesWithFilter(transitionMatrix, [&](storm::Interval const& i) {return storm::utility::isZero(lowerBoundOfIntervals ? i.lower() : i.upper());});\n                                                        }).values;\n            }\n            \n            template<>\n            std::vector<storm::RationalNumber> SparseMdpPrctlHelper<storm::RationalNumber>::computeReachabilityRewards(Environment const& env, storm::solver::SolveGoal<storm::RationalNumber>&&, storm::storage::SparseMatrix<storm::RationalNumber> const&, storm::storage::SparseMatrix<storm::RationalNumber> const&, storm::models::sparse::StandardRewardModel<storm::Interval> const&, bool, storm::storage::BitVector const&, bool) {\n                STORM_LOG_THROW(false, storm::exceptions::IllegalFunctionCallException, \"Computing reachability rewards is unsupported for this data type.\");\n            }\n#endif\n            \n            struct QualitativeStateSetsReachabilityRewards {\n                storm::storage::BitVector maybeStates;\n                storm::storage::BitVector infinityStates;\n                storm::storage::BitVector rewardZeroStates;\n            };\n\n            template<typename ValueType>\n            QualitativeStateSetsReachabilityRewards getQualitativeStateSetsReachabilityRewardsFromHint(ModelCheckerHint const& hint, storm::storage::BitVector const& targetStates) {\n                QualitativeStateSetsReachabilityRewards result;\n                result.maybeStates = hint.template asExplicitModelCheckerHint<ValueType>().getMaybeStates();\n                \n                // Treat the states with reward zero/infinity.\n                std::vector<ValueType> const& resultsForNonMaybeStates = hint.template asExplicitModelCheckerHint<ValueType>().getResultHint();\n                result.infinityStates = storm::storage::BitVector(result.maybeStates.size());\n                result.rewardZeroStates = storm::storage::BitVector(result.maybeStates.size());\n                storm::storage::BitVector nonMaybeStates = ~result.maybeStates;\n                for (auto const& state : nonMaybeStates) {\n                    if (storm::utility::isZero(resultsForNonMaybeStates[state])) {\n                        result.rewardZeroStates.set(state, true);\n                    } else {\n                        STORM_LOG_THROW(storm::utility::isInfinity(resultsForNonMaybeStates[state]), storm::exceptions::IllegalArgumentException, \"Expected that the result hint specifies probabilities in {0,infinity} for non-maybe states\");\n                        result.infinityStates.set(state, true);\n                    }\n                }\n                return result;\n            }\n            \n            template<typename ValueType>\n            QualitativeStateSetsReachabilityRewards computeQualitativeStateSetsReachabilityRewards(storm::solver::SolveGoal<ValueType> const& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, std::function<storm::storage::BitVector()> const& zeroRewardStatesGetter, std::function<storm::storage::BitVector()> const& zeroRewardChoicesGetter) {\n                QualitativeStateSetsReachabilityRewards result;\n                storm::storage::BitVector trueStates(transitionMatrix.getRowGroupCount(), true);\n                if (goal.minimize()) {\n                    result.infinityStates = storm::utility::graph::performProb1E(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, trueStates, targetStates);\n                } else {\n                    result.infinityStates = storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, trueStates, targetStates);\n                }\n                result.infinityStates.complement();\n                \n                if (storm::settings::getModule<storm::settings::modules::ModelCheckerSettings>().isFilterRewZeroSet()) {\n                    if (goal.minimize()) {\n                        result.rewardZeroStates = storm::utility::graph::performProb1E(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, trueStates, targetStates, zeroRewardChoicesGetter());\n                    } else {\n                        result.rewardZeroStates = storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, zeroRewardStatesGetter(), targetStates);\n                    }\n                } else {\n                    result.rewardZeroStates = targetStates;\n                }\n                result.maybeStates = ~(result.rewardZeroStates | result.infinityStates);\n                return result;\n            }\n            \n            template<typename ValueType>\n            QualitativeStateSetsReachabilityRewards getQualitativeStateSetsReachabilityRewards(storm::solver::SolveGoal<ValueType> const& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, ModelCheckerHint const& hint, std::function<storm::storage::BitVector()> const& zeroRewardStatesGetter, std::function<storm::storage::BitVector()> const& zeroRewardChoicesGetter) {\n                if (hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().getComputeOnlyMaybeStates()) {\n                    return getQualitativeStateSetsReachabilityRewardsFromHint<ValueType>(hint, targetStates);\n                } else {\n                    return computeQualitativeStateSetsReachabilityRewards(goal, transitionMatrix, backwardTransitions, targetStates, zeroRewardStatesGetter, zeroRewardChoicesGetter);\n                }\n            }\n            \n            template<typename ValueType>\n            void extendScheduler(storm::storage::Scheduler<ValueType>& scheduler, storm::solver::SolveGoal<ValueType> const& goal, QualitativeStateSetsReachabilityRewards const& qualitativeStateSets, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, std::function<storm::storage::BitVector()> const& zeroRewardChoicesGetter) {\n                // Finally, if we need to produce a scheduler, we also need to figure out the parts of the scheduler for\n                // the states with reward zero/infinity.\n                if (goal.minimize()) {\n                    storm::utility::graph::computeSchedulerProb1E(qualitativeStateSets.rewardZeroStates, transitionMatrix, backwardTransitions, qualitativeStateSets.rewardZeroStates, targetStates, scheduler, zeroRewardChoicesGetter());\n                    for (auto const& state : qualitativeStateSets.infinityStates) {\n                        scheduler.setChoice(0, state);\n                    }\n                } else {\n                    storm::utility::graph::computeSchedulerRewInf(qualitativeStateSets.infinityStates, transitionMatrix, scheduler);\n                    for (auto const& state : qualitativeStateSets.rewardZeroStates) {\n                        scheduler.setChoice(0, state);\n                    }\n                }\n            }\n            \n            template<typename ValueType>\n            void extractSchedulerChoices(storm::storage::Scheduler<ValueType>& scheduler, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<uint_fast64_t> const& subChoices, storm::storage::BitVector const& maybeStates, boost::optional<storm::storage::BitVector> const& selectedChoices) {\n                auto subChoiceIt = subChoices.begin();\n                if (selectedChoices) {\n                    for (auto maybeState : maybeStates) {\n                        // find the rowindex that corresponds to the selected row of the submodel\n                        uint_fast64_t firstRowIndex = transitionMatrix.getRowGroupIndices()[maybeState];\n                        uint_fast64_t selectedRowIndex = selectedChoices->getNextSetIndex(firstRowIndex);\n                        for (uint_fast64_t choice = 0; choice < *subChoiceIt; ++choice) {\n                            selectedRowIndex = selectedChoices->getNextSetIndex(selectedRowIndex + 1);\n                        }\n                        scheduler.setChoice(selectedRowIndex - firstRowIndex, maybeState);\n                        ++subChoiceIt;\n                    }\n                } else {\n                    for (auto maybeState : maybeStates) {\n                        scheduler.setChoice(*subChoiceIt, maybeState);\n                        ++subChoiceIt;\n                    }\n                }\n                assert(subChoiceIt == subChoices.end());\n            }\n            \n            template<typename ValueType>\n            void computeFixedPointSystemReachabilityRewards(storm::solver::SolveGoal<ValueType>& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, QualitativeStateSetsReachabilityRewards const& qualitativeStateSets, boost::optional<storm::storage::BitVector> const& selectedChoices, std::function<std::vector<ValueType>(uint_fast64_t, storm::storage::SparseMatrix<ValueType> const&, storm::storage::BitVector const&)> const& totalStateRewardVectorGetter, storm::storage::SparseMatrix<ValueType>& submatrix, std::vector<ValueType>& b, std::vector<ValueType>* oneStepTargetProbabilities = nullptr) {\n                // Remove rows and columns from the original transition probability matrix for states whose reward values are already known.\n                // If there are infinity states, we additionally have to remove choices of maybeState that lead to infinity.\n                if (qualitativeStateSets.infinityStates.empty()) {\n                    submatrix = transitionMatrix.getSubmatrix(true, qualitativeStateSets.maybeStates, qualitativeStateSets.maybeStates, false);\n                    b = totalStateRewardVectorGetter(submatrix.getRowCount(), transitionMatrix, qualitativeStateSets.maybeStates);\n                    if (oneStepTargetProbabilities) {\n                        (*oneStepTargetProbabilities) = transitionMatrix.getConstrainedRowGroupSumVector(qualitativeStateSets.maybeStates, qualitativeStateSets.rewardZeroStates);\n                    }\n                } else {\n                    submatrix = transitionMatrix.getSubmatrix(false, *selectedChoices, qualitativeStateSets.maybeStates, false);\n                    b = totalStateRewardVectorGetter(transitionMatrix.getRowCount(), transitionMatrix, storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true));\n                    storm::utility::vector::filterVectorInPlace(b, *selectedChoices);\n                    if (oneStepTargetProbabilities) {\n                        (*oneStepTargetProbabilities) = transitionMatrix.getConstrainedRowSumVector(*selectedChoices, qualitativeStateSets.rewardZeroStates);\n                    }\n                }\n                \n                // If the solve goal has relevant values, we need to adjust them.\n                goal.restrictRelevantValues(qualitativeStateSets.maybeStates);\n            }\n            \n            template<typename ValueType>\n            boost::optional<SparseMdpEndComponentInformation<ValueType>> computeFixedPointSystemReachabilityRewardsEliminateEndComponents(storm::solver::SolveGoal<ValueType>& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, QualitativeStateSetsReachabilityRewards const& qualitativeStateSets, boost::optional<storm::storage::BitVector> const& selectedChoices, std::function<std::vector<ValueType>(uint_fast64_t, storm::storage::SparseMatrix<ValueType> const&, storm::storage::BitVector const&)> const& totalStateRewardVectorGetter, storm::storage::SparseMatrix<ValueType>& submatrix, std::vector<ValueType>& b, boost::optional<std::vector<ValueType>>& oneStepTargetProbabilities, bool produceScheduler) {\n                \n                // Start by computing the choices with reward 0, as we only want ECs within this fragment.\n                storm::storage::BitVector zeroRewardChoices(transitionMatrix.getRowCount());\n\n                // Get the rewards of all choices.\n                std::vector<ValueType> rewardVector = totalStateRewardVectorGetter(transitionMatrix.getRowCount(), transitionMatrix, storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true));\n                \n                uint64_t index = 0;\n                for (auto const& e : rewardVector) {\n                    if (storm::utility::isZero(e)) {\n                        zeroRewardChoices.set(index);\n                    }\n                    ++index;\n                }\n                \n                // Compute the states that have some zero reward choice.\n                storm::storage::BitVector candidateStates(qualitativeStateSets.maybeStates);\n                for (auto state : qualitativeStateSets.maybeStates) {\n                    bool keepState = false;\n                    \n                    for (auto row = transitionMatrix.getRowGroupIndices()[state], rowEnd = transitionMatrix.getRowGroupIndices()[state + 1]; row < rowEnd; ++row) {\n                        if (zeroRewardChoices.get(row)) {\n                            keepState = true;\n                            break;\n                        }\n                    }\n                    \n                    if (!keepState) {\n                        candidateStates.set(state, false);\n                    }\n                }\n                \n                // Only keep the candidate states that (under some scheduler) can stay in the set of candidates forever\n                candidateStates = storm::utility::graph::performProb0E(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, candidateStates, ~candidateStates);\n                \n                bool doDecomposition = !candidateStates.empty();\n                \n                storm::storage::MaximalEndComponentDecomposition<ValueType> endComponentDecomposition;\n                if (doDecomposition) {\n                    // Then compute the states that are in MECs with zero reward.\n                    endComponentDecomposition = storm::storage::MaximalEndComponentDecomposition<ValueType>(transitionMatrix, backwardTransitions, candidateStates, zeroRewardChoices);\n                }\n                \n                // Only do more work if there are actually end-components.\n                if (doDecomposition && !endComponentDecomposition.empty()) {\n                    STORM_LOG_DEBUG(\"Eliminating \" << endComponentDecomposition.size() << \" ECs.\");\n                    SparseMdpEndComponentInformation<ValueType> result = SparseMdpEndComponentInformation<ValueType>::eliminateEndComponents(endComponentDecomposition, transitionMatrix, qualitativeStateSets.maybeStates, oneStepTargetProbabilities ? &qualitativeStateSets.rewardZeroStates : nullptr, selectedChoices ? &selectedChoices.get() : nullptr, &rewardVector, submatrix, oneStepTargetProbabilities ? &oneStepTargetProbabilities.get() : nullptr, &b, produceScheduler);\n                    \n                    // If the solve goal has relevant values, we need to adjust them.\n                    if (goal.hasRelevantValues()) {\n                        storm::storage::BitVector newRelevantValues(submatrix.getRowGroupCount());\n                        for (auto state : goal.relevantValues()) {\n                            if (qualitativeStateSets.maybeStates.get(state)) {\n                                newRelevantValues.set(result.getRowGroupAfterElimination(state));\n                            }\n                        }\n                        if (!newRelevantValues.empty()) {\n                            goal.setRelevantValues(std::move(newRelevantValues));\n                        }\n                    }\n                    \n                    return result;\n                } else {\n                    STORM_LOG_DEBUG(\"Not eliminating ECs as there are none.\");\n                    computeFixedPointSystemReachabilityRewards(goal, transitionMatrix, qualitativeStateSets, selectedChoices, totalStateRewardVectorGetter, submatrix, b, oneStepTargetProbabilities ? &oneStepTargetProbabilities.get() : nullptr);\n                    return boost::none;\n                }\n            }\n            \n            template<typename ValueType>\n            void computeUpperRewardBounds(SparseMdpHintType<ValueType>& hintInformation, storm::OptimizationDirection const& direction, storm::storage::SparseMatrix<ValueType> const& submatrix, std::vector<ValueType> const& choiceRewards, std::vector<ValueType> const& oneStepTargetProbabilities) {\n                \n                // For the min-case, we use DS-MPI, for the max-case variant 2 of the Baier et al. paper (CAV'17).\n                if (direction == storm::OptimizationDirection::Minimize) {\n                    DsMpiMdpUpperRewardBoundsComputer<ValueType> dsmpi(submatrix, choiceRewards, oneStepTargetProbabilities);\n                    hintInformation.upperResultBounds = dsmpi.computeUpperBounds();\n                } else {\n                    BaierUpperRewardBoundsComputer<ValueType> baier(submatrix, choiceRewards, oneStepTargetProbabilities);\n                    hintInformation.upperResultBound = baier.computeUpperBound();\n                }\n            }\n            \n            template<typename ValueType>\n            MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeReachabilityRewardsHelper(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, std::function<std::vector<ValueType>(uint_fast64_t, storm::storage::SparseMatrix<ValueType> const&, storm::storage::BitVector const&)> const& totalStateRewardVectorGetter, storm::storage::BitVector const& targetStates, bool qualitative, bool produceScheduler, std::function<storm::storage::BitVector()> const& zeroRewardStatesGetter, std::function<storm::storage::BitVector()> const& zeroRewardChoicesGetter, ModelCheckerHint const& hint) {\n                \n                // Prepare resulting vector.\n                std::vector<ValueType> result(transitionMatrix.getRowGroupCount(), storm::utility::zero<ValueType>());\n                \n                // Determine which states have a reward that is infinity or less than infinity.\n                QualitativeStateSetsReachabilityRewards qualitativeStateSets = getQualitativeStateSetsReachabilityRewards(goal, transitionMatrix, backwardTransitions, targetStates, hint, zeroRewardStatesGetter, zeroRewardChoicesGetter);\n                \n                STORM_LOG_INFO(\"Preprocessing: \" << qualitativeStateSets.infinityStates.getNumberOfSetBits() << \" states with reward infinity, \" << qualitativeStateSets.rewardZeroStates.getNumberOfSetBits() << \" states with reward zero (\" << qualitativeStateSets.maybeStates.getNumberOfSetBits() << \" states remaining).\");\n\n                storm::utility::vector::setVectorValues(result, qualitativeStateSets.infinityStates, storm::utility::infinity<ValueType>());\n                \n                // If requested, we will produce a scheduler.\n                std::unique_ptr<storm::storage::Scheduler<ValueType>> scheduler;\n                if (produceScheduler) {\n                    scheduler = std::make_unique<storm::storage::Scheduler<ValueType>>(transitionMatrix.getRowGroupCount());\n                }\n                \n                // Check whether we need to compute exact rewards for some states.\n                if (qualitative) {\n                    STORM_LOG_INFO(\"The rewards for the initial states were determined in a preprocessing step. No exact rewards were computed.\");\n                    // Set the values for all maybe-states to 1 to indicate that their reward values\n                    // are neither 0 nor infinity.\n                    storm::utility::vector::setVectorValues<ValueType>(result, qualitativeStateSets.maybeStates, storm::utility::one<ValueType>());\n                } else {\n                    if (!qualitativeStateSets.maybeStates.empty()) {\n                        // In this case we have to compute the reward values for the remaining states.\n\n                        // Store the choices that lead to non-infinity values. If none, all choices im maybe states can be selected.\n                        boost::optional<storm::storage::BitVector> selectedChoices;\n                        if (!qualitativeStateSets.infinityStates.empty()) {\n                            selectedChoices = transitionMatrix.getRowFilter(qualitativeStateSets.maybeStates, ~qualitativeStateSets.infinityStates);\n                        }\n                        \n                        // Obtain proper hint information either from the provided hint or from requirements of the solver.\n                        SparseMdpHintType<ValueType> hintInformation = computeHints(env, SolutionType::ExpectedRewards, hint, goal.direction(), transitionMatrix, backwardTransitions, qualitativeStateSets.maybeStates, ~qualitativeStateSets.rewardZeroStates, qualitativeStateSets.rewardZeroStates, produceScheduler, selectedChoices);\n                        \n                        // Declare the components of the equation system we will solve.\n                        storm::storage::SparseMatrix<ValueType> submatrix;\n                        std::vector<ValueType> b;\n\n                        // If we need to compute upper bounds on the reward values, we need the one step probabilities\n                        // to a target state.\n                        boost::optional<std::vector<ValueType>> oneStepTargetProbabilities;\n                        if (hintInformation.getComputeUpperBounds()) {\n                            oneStepTargetProbabilities = std::vector<ValueType>();\n                        }\n                        \n                        // If the hint information tells us that we have to eliminate MECs, we do so now.\n                        boost::optional<SparseMdpEndComponentInformation<ValueType>> ecInformation;\n                        if (hintInformation.getEliminateEndComponents()) {\n                            ecInformation = computeFixedPointSystemReachabilityRewardsEliminateEndComponents(goal, transitionMatrix, backwardTransitions, qualitativeStateSets, selectedChoices, totalStateRewardVectorGetter, submatrix, b, oneStepTargetProbabilities, produceScheduler);\n                        } else {\n                            // Otherwise, we compute the standard equations.\n                            computeFixedPointSystemReachabilityRewards(goal, transitionMatrix, qualitativeStateSets, selectedChoices, totalStateRewardVectorGetter, submatrix, b, oneStepTargetProbabilities ? &oneStepTargetProbabilities.get() : nullptr);\n                        }\n                        \n                        // If we need to compute upper bounds, do so now.\n                        if (hintInformation.getComputeUpperBounds()) {\n                            STORM_LOG_ASSERT(oneStepTargetProbabilities, \"Expecting one step target probability vector to be available.\");\n                            computeUpperRewardBounds(hintInformation, goal.direction(), submatrix, b, oneStepTargetProbabilities.get());\n                        }\n                        \n                        // Now compute the results for the maybe states.\n                        MaybeStateResult<ValueType> resultForMaybeStates = computeValuesForMaybeStates(env, std::move(goal), std::move(submatrix), b, produceScheduler, hintInformation);\n\n                        // If we eliminated end components, we need to extract the result differently.\n                        if (ecInformation && ecInformation.get().getEliminatedEndComponents()) {\n                            ecInformation.get().setValues(result, qualitativeStateSets.maybeStates, resultForMaybeStates.getValues());\n                            if (produceScheduler) {\n                                ecInformation.get().setScheduler(*scheduler, qualitativeStateSets.maybeStates, transitionMatrix, backwardTransitions, resultForMaybeStates.getScheduler());\n                            }\n                        } else {\n                            // Set values of resulting vector according to result.\n                            storm::utility::vector::setVectorValues<ValueType>(result, qualitativeStateSets.maybeStates, resultForMaybeStates.getValues());\n                            if (produceScheduler) {\n                                extractSchedulerChoices(*scheduler, transitionMatrix, resultForMaybeStates.getScheduler(), qualitativeStateSets.maybeStates, selectedChoices);\n                            }\n                        }\n                    }\n                }\n                \n                // Extend scheduler with choices for the states in the qualitative state sets.\n                if (produceScheduler) {\n                    extendScheduler(*scheduler, goal, qualitativeStateSets, transitionMatrix, backwardTransitions, targetStates, zeroRewardChoicesGetter);\n                }\n                \n                // Sanity check for created scheduler.\n                STORM_LOG_ASSERT(!produceScheduler || scheduler, \"Expected that a scheduler was obtained.\");\n                STORM_LOG_ASSERT((!produceScheduler && !scheduler) || !scheduler->isPartialScheduler(), \"Expected a fully defined scheduler\");\n                STORM_LOG_ASSERT((!produceScheduler && !scheduler) || scheduler->isDeterministicScheduler(), \"Expected a deterministic scheduler\");\n                STORM_LOG_ASSERT((!produceScheduler && !scheduler) || scheduler->isMemorylessScheduler(), \"Expected a memoryless scheduler\");\n\n\n                return MDPSparseModelCheckingHelperReturnType<ValueType>(std::move(result), std::move(scheduler));\n            }\n            \n            template<typename ValueType>\n            std::unique_ptr<CheckResult> SparseMdpPrctlHelper<ValueType>::computeConditionalProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, storm::storage::BitVector const& conditionStates) {\n                \n                std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();\n                \n                // For the max-case, we can simply take the given target states. For the min-case, however, we need to\n                // find the MECs of non-target states and make them the new target states.\n                storm::storage::BitVector fixedTargetStates;\n                if (!goal.minimize()) {\n                    fixedTargetStates = targetStates;\n                } else {\n                    fixedTargetStates = storm::storage::BitVector(targetStates.size());\n                    storm::storage::MaximalEndComponentDecomposition<ValueType> mecDecomposition(transitionMatrix, backwardTransitions, ~targetStates);\n                    for (auto const& mec : mecDecomposition) {\n                        for (auto const& stateActionsPair : mec) {\n                            fixedTargetStates.set(stateActionsPair.first);\n                        }\n                    }\n                }\n                \n                storm::storage::BitVector allStates(fixedTargetStates.size(), true);\n                \n                // Extend the target states by computing all states that have probability 1 to go to a target state\n                // under *all* schedulers.\n                fixedTargetStates = storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, allStates, fixedTargetStates);\n                \n                // We solve the max-case and later adjust the result if the optimization direction was to minimize.\n                storm::storage::BitVector initialStatesBitVector = goal.relevantValues();\n                STORM_LOG_THROW(initialStatesBitVector.getNumberOfSetBits() == 1, storm::exceptions::NotSupportedException, \"Computing conditional probabilities in MDPs is only supported for models with exactly one initial state.\");\n                storm::storage::sparse::state_type initialState = *initialStatesBitVector.begin();\n                \n                // Extend the condition states by computing all states that have probability 1 to go to a condition state\n                // under *all* schedulers.\n                storm::storage::BitVector extendedConditionStates = storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, allStates, conditionStates);\n\n                STORM_LOG_DEBUG(\"Computing probabilities to satisfy condition.\");\n                std::chrono::high_resolution_clock::time_point conditionStart = std::chrono::high_resolution_clock::now();\n                std::vector<ValueType> conditionProbabilities = std::move(computeUntilProbabilities(env, OptimizationDirection::Maximize, transitionMatrix, backwardTransitions, allStates, extendedConditionStates, false, false).values);\n                std::chrono::high_resolution_clock::time_point conditionEnd = std::chrono::high_resolution_clock::now();\n                STORM_LOG_DEBUG(\"Computed probabilities to satisfy for condition in \" << std::chrono::duration_cast<std::chrono::milliseconds>(conditionEnd - conditionStart).count() << \"ms.\");\n                \n                // If the conditional probability is undefined for the initial state, we return directly.\n                if (storm::utility::isZero(conditionProbabilities[initialState])) {\n                    return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(initialState, storm::utility::infinity<ValueType>()));\n                }\n                \n                STORM_LOG_DEBUG(\"Computing probabilities to reach target.\");\n                std::chrono::high_resolution_clock::time_point targetStart = std::chrono::high_resolution_clock::now();\n                std::vector<ValueType> targetProbabilities = std::move(computeUntilProbabilities(env, OptimizationDirection::Maximize, transitionMatrix, backwardTransitions, allStates, fixedTargetStates, false, false).values);\n                std::chrono::high_resolution_clock::time_point targetEnd = std::chrono::high_resolution_clock::now();\n                STORM_LOG_DEBUG(\"Computed probabilities to reach target in \" << std::chrono::duration_cast<std::chrono::milliseconds>(targetEnd - targetStart).count() << \"ms.\");\n\n                storm::storage::BitVector statesWithProbabilityGreater0E(transitionMatrix.getRowGroupCount(), true);\n                storm::storage::sparse::state_type state = 0;\n                for (auto const& element : conditionProbabilities) {\n                    if (storm::utility::isZero(element)) {\n                        statesWithProbabilityGreater0E.set(state, false);\n                    }\n                    ++state;\n                }\n\n                // Determine those states that need to be equipped with a restart mechanism.\n                STORM_LOG_DEBUG(\"Computing problematic states.\");\n                storm::storage::BitVector pureResetStates = storm::utility::graph::performProb0A(backwardTransitions, allStates, extendedConditionStates);\n                storm::storage::BitVector problematicStates = storm::utility::graph::performProb0E(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, allStates, extendedConditionStates | fixedTargetStates);\n\n                // Otherwise, we build the transformed MDP.\n                storm::storage::BitVector relevantStates = storm::utility::graph::getReachableStates(transitionMatrix, initialStatesBitVector, allStates, extendedConditionStates | fixedTargetStates | pureResetStates);\n                STORM_LOG_TRACE(\"Found \" << relevantStates.getNumberOfSetBits() << \" relevant states for conditional probability computation.\");\n                std::vector<uint_fast64_t> numberOfStatesBeforeRelevantStates = relevantStates.getNumberOfSetBitsBeforeIndices();\n                storm::storage::sparse::state_type newGoalState = relevantStates.getNumberOfSetBits();\n                storm::storage::sparse::state_type newStopState = newGoalState + 1;\n                storm::storage::sparse::state_type newFailState = newStopState + 1;\n                \n                // Build the transitions of the (relevant) states of the original model.\n                storm::storage::SparseMatrixBuilder<ValueType> builder(0, newFailState + 1, 0, true, true);\n                uint_fast64_t currentRow = 0;\n                for (auto state : relevantStates) {\n                    builder.newRowGroup(currentRow);\n                    if (fixedTargetStates.get(state)) {\n                        if (!storm::utility::isZero(conditionProbabilities[state])) {\n                            builder.addNextValue(currentRow, newGoalState, conditionProbabilities[state]);\n                        }\n                        if (!storm::utility::isOne(conditionProbabilities[state])) {\n                            builder.addNextValue(currentRow, newFailState, storm::utility::one<ValueType>() - conditionProbabilities[state]);\n                        }\n                        ++currentRow;\n                    } else if (extendedConditionStates.get(state)) {\n                        if (!storm::utility::isZero(targetProbabilities[state])) {\n                            builder.addNextValue(currentRow, newGoalState, targetProbabilities[state]);\n                        }\n                        if (!storm::utility::isOne(targetProbabilities[state])) {\n                            builder.addNextValue(currentRow, newStopState, storm::utility::one<ValueType>() - targetProbabilities[state]);\n                        }\n                        ++currentRow;\n                    } else if (pureResetStates.get(state)) {\n                        builder.addNextValue(currentRow, numberOfStatesBeforeRelevantStates[initialState], storm::utility::one<ValueType>());\n                        ++currentRow;\n                    } else {\n                        for (uint_fast64_t row = transitionMatrix.getRowGroupIndices()[state]; row < transitionMatrix.getRowGroupIndices()[state + 1]; ++row) {\n                            for (auto const& successorEntry : transitionMatrix.getRow(row)) {\n                                builder.addNextValue(currentRow, numberOfStatesBeforeRelevantStates[successorEntry.getColumn()], successorEntry.getValue());\n                            }\n                            ++currentRow;\n                        }\n                        if (problematicStates.get(state)) {\n                            builder.addNextValue(currentRow, numberOfStatesBeforeRelevantStates[initialState], storm::utility::one<ValueType>());\n                            ++currentRow;\n                        }\n                    }\n                }\n                \n                // Now build the transitions of the newly introduced states.\n                builder.newRowGroup(currentRow);\n                builder.addNextValue(currentRow, newGoalState, storm::utility::one<ValueType>());\n                ++currentRow;\n                builder.newRowGroup(currentRow);\n                builder.addNextValue(currentRow, newStopState, storm::utility::one<ValueType>());\n                ++currentRow;\n                builder.newRowGroup(currentRow);\n                builder.addNextValue(currentRow, numberOfStatesBeforeRelevantStates[initialState], storm::utility::one<ValueType>());\n                ++currentRow;\n                \n                std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();\n                STORM_LOG_DEBUG(\"Computed transformed model in \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << \"ms.\");\n                \n                // Finally, build the matrix and dispatch the query as a reachability query.\n                STORM_LOG_DEBUG(\"Computing conditional probabilties.\");\n                storm::storage::BitVector newGoalStates(newFailState + 1);\n                newGoalStates.set(newGoalState);\n                storm::storage::SparseMatrix<ValueType> newTransitionMatrix = builder.build();\n                STORM_LOG_DEBUG(\"Transformed model has \" << newTransitionMatrix.getRowGroupCount() << \" states and \" << newTransitionMatrix.getNonzeroEntryCount() << \" transitions.\");\n                storm::storage::SparseMatrix<ValueType> newBackwardTransitions = newTransitionMatrix.transpose(true);\n                \n                storm::solver::OptimizationDirection dir = goal.direction();\n                if (goal.minimize()) {\n                    goal.oneMinus();\n                }\n                \n                std::chrono::high_resolution_clock::time_point conditionalStart = std::chrono::high_resolution_clock::now();\n                std::vector<ValueType> goalProbabilities = std::move(computeUntilProbabilities(env, std::move(goal), newTransitionMatrix, newBackwardTransitions, storm::storage::BitVector(newFailState + 1, true), newGoalStates, false, false).values);\n                std::chrono::high_resolution_clock::time_point conditionalEnd = std::chrono::high_resolution_clock::now();\n                STORM_LOG_DEBUG(\"Computed conditional probabilities in transformed model in \" << std::chrono::duration_cast<std::chrono::milliseconds>(conditionalEnd - conditionalStart).count() << \"ms.\");\n                \n                return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(initialState, dir == OptimizationDirection::Maximize ? goalProbabilities[numberOfStatesBeforeRelevantStates[initialState]] : storm::utility::one<ValueType>() - goalProbabilities[numberOfStatesBeforeRelevantStates[initialState]]));\n            }\n            \n            template class SparseMdpPrctlHelper<double>;\n            template std::vector<double> SparseMdpPrctlHelper<double>::computeInstantaneousRewards(Environment const& env, storm::solver::SolveGoal<double>&& goal, storm::storage::SparseMatrix<double> const& transitionMatrix, storm::models::sparse::StandardRewardModel<double> const& rewardModel, uint_fast64_t stepCount);\n            template std::vector<double> SparseMdpPrctlHelper<double>::computeCumulativeRewards(Environment const& env, storm::solver::SolveGoal<double>&& goal, storm::storage::SparseMatrix<double> const& transitionMatrix, storm::models::sparse::StandardRewardModel<double> const& rewardModel, uint_fast64_t stepBound);\n            template MDPSparseModelCheckingHelperReturnType<double> SparseMdpPrctlHelper<double>::computeReachabilityRewards(Environment const& env, storm::solver::SolveGoal<double>&& goal, storm::storage::SparseMatrix<double> const& transitionMatrix, storm::storage::SparseMatrix<double> const& backwardTransitions, storm::models::sparse::StandardRewardModel<double> const& rewardModel, storm::storage::BitVector const& targetStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint);\n            template MDPSparseModelCheckingHelperReturnType<double> SparseMdpPrctlHelper<double>::computeTotalRewards(Environment const& env, storm::solver::SolveGoal<double>&& goal, storm::storage::SparseMatrix<double> const& transitionMatrix, storm::storage::SparseMatrix<double> const& backwardTransitions, storm::models::sparse::StandardRewardModel<double> const& rewardModel, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint);\n\n#ifdef STORM_HAVE_CARL\n            template class SparseMdpPrctlHelper<storm::RationalNumber>;\n            template std::vector<storm::RationalNumber> SparseMdpPrctlHelper<storm::RationalNumber>::computeInstantaneousRewards(Environment const& env, storm::solver::SolveGoal<storm::RationalNumber>&& goal, storm::storage::SparseMatrix<storm::RationalNumber> const& transitionMatrix, storm::models::sparse::StandardRewardModel<storm::RationalNumber> const& rewardModel, uint_fast64_t stepCount);\n            template std::vector<storm::RationalNumber> SparseMdpPrctlHelper<storm::RationalNumber>::computeCumulativeRewards(Environment const& env, storm::solver::SolveGoal<storm::RationalNumber>&& goal, storm::storage::SparseMatrix<storm::RationalNumber> const& transitionMatrix, storm::models::sparse::StandardRewardModel<storm::RationalNumber> const& rewardModel, uint_fast64_t stepBound);\n            template MDPSparseModelCheckingHelperReturnType<storm::RationalNumber> SparseMdpPrctlHelper<storm::RationalNumber>::computeReachabilityRewards(Environment const& env, storm::solver::SolveGoal<storm::RationalNumber>&& goal, storm::storage::SparseMatrix<storm::RationalNumber> const& transitionMatrix, storm::storage::SparseMatrix<storm::RationalNumber> const& backwardTransitions, storm::models::sparse::StandardRewardModel<storm::RationalNumber> const& rewardModel, storm::storage::BitVector const& targetStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint);\n            template MDPSparseModelCheckingHelperReturnType<storm::RationalNumber> SparseMdpPrctlHelper<storm::RationalNumber>::computeTotalRewards(Environment const& env, storm::solver::SolveGoal<storm::RationalNumber>&& goal, storm::storage::SparseMatrix<storm::RationalNumber> const& transitionMatrix, storm::storage::SparseMatrix<storm::RationalNumber> const& backwardTransitions, storm::models::sparse::StandardRewardModel<storm::RationalNumber> const& rewardModel, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint);\n#endif\n        }\n    }\n}\n", "meta": {"hexsha": "2e31f108cac9fbab66c88049fea2d33ed4cebeb3", "size": 104880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "artifact/storm/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp", "max_stars_repo_name": "glatteis/tacas21-artifact", "max_stars_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "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": "artifact/storm/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp", "max_issues_repo_name": "glatteis/tacas21-artifact", "max_issues_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "artifact/storm/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp", "max_forks_repo_name": "glatteis/tacas21-artifact", "max_forks_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-05T12:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T12:39:53.000Z", "avg_line_length": 78.5617977528, "max_line_length": 794, "alphanum_fraction": 0.6112223494, "num_tokens": 18895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.24798742624020279, "lm_q1q2_score": 0.1742186177008199}}
{"text": "//\r\n// Copyright 2019 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\r\n//\r\n// Use, modification and distribution are 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_GIL_IMAGE_PROCESSING_SCALING_HPP\r\n#define BOOST_GIL_IMAGE_PROCESSING_SCALING_HPP\r\n\r\n#include <boost/gil/image_view.hpp>\r\n#include <boost/gil/rgb.hpp>\r\n#include <boost/gil/pixel.hpp>\r\n#include <boost/gil/image_processing/numeric.hpp>\r\n\r\nnamespace boost { namespace gil {\r\n\r\n/// \\defgroup ScalingAlgorithms\r\n/// \\brief Algorthims suitable for rescaling\r\n///\r\n/// These algorithms are used to improve image quality after image resizing is made.\r\n///\r\n/// \\defgroup DownScalingAlgorithms\r\n/// \\ingroup ScalingAlgorithms\r\n/// \\brief Algorthims suitable for downscaling\r\n///\r\n/// These algorithms provide best results when used for downscaling. Using for upscaling will\r\n/// probably provide less than good results.\r\n///\r\n/// \\brief a single step of lanczos downscaling\r\n/// \\ingroup DownScalingAlgorithms\r\n///\r\n/// Use this algorithm to scale down source image into a smaller image with reasonable quality.\r\n/// Do note that having a look at the output once is a good idea, since it might have ringing\r\n/// artifacts.\r\ntemplate <typename ImageView>\r\nvoid lanczos_at(\r\n    ImageView input_view,\r\n    ImageView output_view,\r\n    typename ImageView::x_coord_t source_x,\r\n    typename ImageView::y_coord_t source_y,\r\n    typename ImageView::x_coord_t target_x,\r\n    typename ImageView::y_coord_t target_y,\r\n    std::ptrdiff_t a)\r\n{\r\n    using x_coord_t = typename ImageView::x_coord_t;\r\n    using y_coord_t = typename ImageView::y_coord_t;\r\n    using pixel_t = typename std::remove_reference<decltype(std::declval<ImageView>()(0, 0))>::type;\r\n\r\n    // C++11 doesn't allow auto in lambdas\r\n    using channel_t = typename std::remove_reference\r\n        <\r\n            decltype(std::declval<pixel_t>().at(std::integral_constant<int, 0>{}))\r\n        >::type;\r\n\r\n    pixel_t result_pixel;\r\n    static_transform(result_pixel, result_pixel, [](channel_t) {\r\n        return static_cast<channel_t>(0);\r\n    });\r\n    auto x_zero = static_cast<x_coord_t>(0);\r\n    auto x_one = static_cast<x_coord_t>(1);\r\n    auto y_zero = static_cast<y_coord_t>(0);\r\n    auto y_one = static_cast<y_coord_t>(1);\r\n\r\n    for (y_coord_t y_i = (std::max)(source_y - static_cast<y_coord_t>(a) + y_one, y_zero);\r\n         y_i <= (std::min)(source_y + static_cast<y_coord_t>(a), input_view.height() - y_one);\r\n         ++y_i)\r\n    {\r\n        for (x_coord_t x_i = (std::max)(source_x - static_cast<x_coord_t>(a) + x_one, x_zero);\r\n             x_i <= (std::min)(source_x + static_cast<x_coord_t>(a), input_view.width() - x_one);\r\n             ++x_i)\r\n        {\r\n            double lanczos_response = lanczos(source_x - x_i, a) * lanczos(source_y - y_i, a);\r\n            auto op = [lanczos_response](channel_t prev, channel_t next)\r\n            {\r\n                return static_cast<channel_t>(prev + next * lanczos_response);\r\n            };\r\n            static_transform(result_pixel, input_view(source_x, source_y), result_pixel, op);\r\n        }\r\n    }\r\n\r\n    output_view(target_x, target_y) = result_pixel;\r\n}\r\n\r\n/// \\brief Complete Lanczos algorithm\r\n/// \\ingroup DownScalingAlgorithms\r\n///\r\n/// This algorithm does full pass over resulting image and convolves pixels from\r\n/// original image. Do note that it might be a good idea to have a look at test\r\n/// output as there might be ringing artifacts.\r\n/// Based on wikipedia article:\r\n/// https://en.wikipedia.org/wiki/Lanczos_resampling\r\n/// with standardinzed cardinal sin (sinc)\r\ntemplate <typename ImageView>\r\nvoid scale_lanczos(ImageView input_view, ImageView output_view, std::ptrdiff_t a)\r\n{\r\n    double scale_x = (static_cast<double>(output_view.width()))\r\n                     / static_cast<double>(input_view.width());\r\n    double scale_y = (static_cast<double>(output_view.height()))\r\n                     / static_cast<double>(input_view.height());\r\n\r\n    using x_coord_t = typename ImageView::x_coord_t;\r\n    using y_coord_t = typename ImageView::y_coord_t;\r\n    for (y_coord_t y = 0; y < output_view.height(); ++y)\r\n    {\r\n        for (x_coord_t x = 0; x < output_view.width(); ++x)\r\n        {\r\n            lanczos_at(input_view, output_view, x / scale_x, y / scale_y, x, y, a);\r\n        }\r\n    }\r\n}\r\n\r\n}} // namespace boost::gil\r\n\r\n#endif\r\n", "meta": {"hexsha": "6f0c7845d4a5736314062b0df8bc26dde8e298c3", "size": 4455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/gil/image_processing/scaling.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/gil/image_processing/scaling.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/gil/image_processing/scaling.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": 38.4051724138, "max_line_length": 101, "alphanum_fraction": 0.6698092031, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.17416210820255315}}
{"text": "/*\n* Copyright (C) 2017 Incognito (Edited by ProMetheus)\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 <streamer/config.hpp>\n#include \"../natives.h\"\n\n#include \"../core.h\"\n#include \"../utility.h\"\n\n#include <streamer/extended.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/intrusive_ptr.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/unordered_set.hpp>\n#include <boost/variant.hpp>\n\n#include <Eigen/Core>\n\nSTREAMER_BEGIN_NS\n\nint CreateDynamicObjectEx(\n\tint modelid,\n\tfloat x,\n\tfloat y,\n\tfloat z,\n\tfloat rx,\n\tfloat ry,\n\tfloat rz,\n\tfloat streamDistance,\n\tfloat drawDistance,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tboost::unordered_set<int> &areas,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_OBJECT) == core->getData()->objects.size()) {\n\t\treturn 0;\n\t}\n\n\tint objectId = Item::Object::identifier.get();\n\tItem::SharedObject object(new Item::Object);\n\t//object->amx = amx;\n\tobject->objectId = objectId;\n\tobject->inverseAreaChecking = false;\n\tobject->noCameraCollision = false;\n\tobject->originalComparableStreamDistance = -1.0f;\n\tobject->positionOffset = Eigen::Vector3f::Zero();\n\tobject->streamCallbacks = false;\n\tobject->modelId = modelid;\n\tobject->position = Eigen::Vector3f(x, y, z);\n\tobject->rotation = Eigen::Vector3f(rx, ry, rz);\n\tobject->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;\n\tobject->streamDistance = streamDistance;\n\tobject->drawDistance = drawDistance;\n\n\tworlds = object->worlds;\n\tinteriors = object->interiors;\n\tplayers = object->players;\n\tareas = object->areas;\n\n\tobject->priority = priority;\n\tcore->getGrid()->addObject(object);\n\tcore->getData()->objects.insert(std::make_pair(objectId, object));\n\treturn objectId;\n}\n\nint CreateDynamicPickupEx(\n\tint modelid,\n\tint type,\n\tfloat x,\n\tfloat y,\n\tfloat z,\n\tfloat streamDistance,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tboost::unordered_set<int> &areas,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_PICKUP) == core->getData()->pickups.size()) {\n\t\treturn 0;\n\t}\n\tint pickupId = Item::Pickup::identifier.get();\n\tItem::SharedPickup pickup(new Item::Pickup);\n\t//pickup->amx = amx;\n\tpickup->pickupId = pickupId;\n\tpickup->inverseAreaChecking = false;\n\tpickup->originalComparableStreamDistance = -1.0f;\n\tpickup->modelId = modelid;\n\tpickup->positionOffset = Eigen::Vector3f::Zero();\n\tpickup->streamCallbacks = false;\n\tpickup->type = type;\n\tpickup->position = Eigen::Vector3f(x, y, z);\n\tpickup->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;\n\tpickup->streamDistance = streamDistance;\n\n\tworlds = pickup->worlds;\n\tinteriors = pickup->interiors;\n\tplayers = pickup->players;\n\tareas = pickup->areas;\n\n\tpickup->priority = priority;\n\tcore->getGrid()->addPickup(pickup);\n\tcore->getData()->pickups.insert(std::make_pair(pickupId, pickup));\n\treturn pickupId;\n}\n\nint CreateDynamicCPEx(\n\tfloat x,\n\tfloat y,\n\tfloat z,\n\tfloat size,\n\tfloat streamDistance,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tboost::unordered_set<int> &areas,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_CP) == core->getData()->checkpoints.size()) {\n\t\treturn 0;\n\t}\n\tint checkpointId = Item::Checkpoint::identifier.get();\n\tItem::SharedCheckpoint checkpoint(new Item::Checkpoint);\n\t//checkpoint->amx = amx;\n\tcheckpoint->checkpointId = checkpointId;\n\tcheckpoint->inverseAreaChecking = false;\n\tcheckpoint->originalComparableStreamDistance = -1.0f;\n\tcheckpoint->positionOffset = Eigen::Vector3f::Zero();\n\tcheckpoint->position = Eigen::Vector3f(x, y, z);\n\tcheckpoint->size = size;\n\tcheckpoint->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;\n\tcheckpoint->streamDistance = streamDistance;\n\n\tworlds = checkpoint->worlds;\n\tinteriors = checkpoint->interiors;\n\tplayers = checkpoint->players;\n\tareas = checkpoint->areas;\n\n\tcheckpoint->priority = priority;\n\tcore->getGrid()->addCheckpoint(checkpoint);\n\tcore->getData()->checkpoints.insert(std::make_pair(checkpointId, checkpoint));\n\treturn checkpointId;\n}\n\nint CreateDynamicRaceCPEx(\n\tint type,\n\tfloat x,\n\tfloat y,\n\tfloat z,\n\tfloat nx,\n\tfloat ny,\n\tfloat nz,\n\tfloat size,\n\tfloat streamDistance,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tboost::unordered_set<int> &areas,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_RACE_CP) == core->getData()->raceCheckpoints.size()) {\n\t\treturn 0;\n\t}\n\tint raceCheckpointId = Item::RaceCheckpoint::identifier.get();\n\tItem::SharedRaceCheckpoint raceCheckpoint(new Item::RaceCheckpoint);\n\t//raceCheckpoint->amx = amx;\n\traceCheckpoint->raceCheckpointId = raceCheckpointId;\n\traceCheckpoint->inverseAreaChecking = false;\n\traceCheckpoint->originalComparableStreamDistance = -1.0f;\n\traceCheckpoint->positionOffset = Eigen::Vector3f::Zero();\n\traceCheckpoint->type = type;\n\traceCheckpoint->position = Eigen::Vector3f(x, y, z);\n\traceCheckpoint->next = Eigen::Vector3f(nx, ny, nz);\n\traceCheckpoint->size = size;\n\traceCheckpoint->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;\n\traceCheckpoint->streamDistance = streamDistance;\n\n\tworlds = raceCheckpoint->worlds;\n\tinteriors = raceCheckpoint->interiors;\n\tplayers = raceCheckpoint->players;\n\tareas = raceCheckpoint->areas;\n\n\traceCheckpoint->priority = priority;\n\tcore->getGrid()->addRaceCheckpoint(raceCheckpoint);\n\tcore->getData()->raceCheckpoints.insert(std::make_pair(raceCheckpointId, raceCheckpoint));\n\treturn raceCheckpointId;\n}\n\nint CreateDynamicMapIconEx(\n\tfloat x,\n\tfloat y,\n\tfloat z,\n\tint type,\n\tint color,\n\tint style,\n\tfloat streamDistance,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tboost::unordered_set<int> &areas,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_MAP_ICON) == core->getData()->mapIcons.size()) {\n\t\treturn 0;\n\t}\n\tint mapIconId = Item::MapIcon::identifier.get();\n\tItem::SharedMapIcon mapIcon(new Item::MapIcon);\n\t//mapIcon->amx = amx;\n\tmapIcon->mapIconId = mapIconId;\n\tmapIcon->inverseAreaChecking = false;\n\tmapIcon->originalComparableStreamDistance = -1.0f;\n\tmapIcon->positionOffset = Eigen::Vector3f::Zero();\n\tmapIcon->position = Eigen::Vector3f(x, y, z);\n\tmapIcon->type = type;\n\tmapIcon->color = color;\n\tmapIcon->style = style;\n\tmapIcon->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;\n\tmapIcon->streamDistance = streamDistance;\n\n\tworlds = mapIcon->worlds;\n\tinteriors = mapIcon->interiors;\n\tplayers = mapIcon->players;\n\tareas = mapIcon->areas;\n\n\tmapIcon->priority = priority;\n\tcore->getGrid()->addMapIcon(mapIcon);\n\tcore->getData()->mapIcons.insert(std::make_pair(mapIconId, mapIcon));\n\treturn mapIconId;\n}\n\nint CreateDynamic3DTextLabelEx(\n\tstd::string text,\n\tint color,\n\tfloat x,\n\tfloat y,\n\tfloat z,\n\tfloat drawDistance,\n\tint attachedPlayer,\n\tint attachedVehicle,\n\tbool testlos,\n\tfloat streamDistance,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tboost::unordered_set<int> &areas,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_3D_TEXT_LABEL) == core->getData()->textLabels.size()) {\n\t\treturn 0;\n\t}\n\tint textLabelId = Item::TextLabel::identifier.get();\n\tItem::SharedTextLabel textLabel(new Item::TextLabel);\n\t//textLabel->amx = amx;\n\ttextLabel->textLabelId = textLabelId;\n\ttextLabel->inverseAreaChecking = false;\n\ttextLabel->originalComparableStreamDistance = -1.0f;\n\ttextLabel->positionOffset = Eigen::Vector3f::Zero();\n\ttextLabel->text = text;\n\ttextLabel->color = color;\n\ttextLabel->position = Eigen::Vector3f(x, y, z);\n\ttextLabel->drawDistance = drawDistance;\n\tif (attachedPlayer != INVALID_OBJECT_ID || attachedVehicle != INVALID_OBJECT_ID)\n\t{\n\t\ttextLabel->attach = boost::intrusive_ptr<Item::TextLabel::Attach>(new Item::TextLabel::Attach);\n\t\ttextLabel->attach->player = attachedPlayer;\n\t\ttextLabel->attach->vehicle = attachedVehicle;\n\t\tif (textLabel->position.cwiseAbs().maxCoeff() > 50.0f)\n\t\t{\n\t\t\ttextLabel->position.setZero();\n\t\t}\n\t\tcore->getStreamer()->attachedTextLabels.insert(textLabel);\n\t}\n\ttextLabel->testLOS = testlos;\n\ttextLabel->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;\n\ttextLabel->streamDistance = streamDistance;\n\n\tworlds = textLabel->worlds;\n\tinteriors = textLabel->interiors;\n\tplayers = textLabel->players;\n\tareas = textLabel->areas;\n\n\ttextLabel->priority = priority;\n\tcore->getGrid()->addTextLabel(textLabel);\n\tcore->getData()->textLabels.insert(std::make_pair(textLabelId, textLabel));\n\treturn textLabelId;\n}\n\nint CreateDynamicCircleEx(\n\tfloat x,\n\tfloat y,\n\tfloat size,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_AREA) == core->getData()->areas.size()) {\n\t\treturn 0;\n\t}\n\tint areaId = Item::Area::identifier.get();\n\tItem::SharedArea area(new Item::Area);\n\t//area->amx = amx;\n\tarea->areaId = areaId;\n\tarea->type = STREAMER_AREA_TYPE_CIRCLE;\n\tarea->position = Eigen::Vector2f(x, y);\n\tarea->comparableSize = size * size;\n\tarea->size = size;\n\n\tworlds = area->worlds;\n\tinteriors = area->interiors;\n\tplayers = area->players;\n\n\tarea->priority = priority;\n\tcore->getGrid()->addArea(area);\n\tcore->getData()->areas.insert(std::make_pair(areaId, area));\n\treturn areaId;\n}\n\nint CreateDynamicCylinderEx(\n\tfloat x,\n\tfloat y,\n\tfloat minz,\n\tfloat maxz,\n\tfloat size,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_AREA) == core->getData()->areas.size()) {\n\t\treturn 0;\n\t}\n\tint areaId = Item::Area::identifier.get();\n\tItem::SharedArea area(new Item::Area);\n\t//area->amx = amx;\n\tarea->areaId = areaId;\n\tarea->type = STREAMER_AREA_TYPE_CYLINDER;\n\tarea->position = Eigen::Vector2f(x, y);\n\tarea->height = Eigen::Vector2f(minz, maxz);\n\tarea->comparableSize = size * size;\n\tarea->size = size;\n\n\tworlds = area->worlds;\n\tinteriors = area->interiors;\n\tplayers = area->players;\n\n\tarea->priority = priority;\n\tcore->getGrid()->addArea(area);\n\tcore->getData()->areas.insert(std::make_pair(areaId, area));\n\treturn areaId;\n}\n\nint CreateDynamicSphereEx(\n\tfloat x,\n\tfloat y,\n\tfloat z,\n\tfloat size,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_AREA) == core->getData()->areas.size()) {\n\t\treturn 0;\n\t}\n\tint areaId = Item::Area::identifier.get();\n\tItem::SharedArea area(new Item::Area);\n\t//area->amx = amx;\n\tarea->areaId = areaId;\n\tarea->type = STREAMER_AREA_TYPE_SPHERE;\n\tarea->position = Eigen::Vector3f(x, y, z);\n\tarea->comparableSize = size * size;\n\tarea->size = size;\n\n\tworlds = area->worlds;\n\tinteriors = area->interiors;\n\tplayers = area->players;\n\n\tarea->priority = priority;\n\tcore->getGrid()->addArea(area);\n\tcore->getData()->areas.insert(std::make_pair(areaId, area));\n\treturn areaId;\n}\n\nint CreateDynamicRectangleEx(\n\tfloat minx,\n\tfloat miny,\n\tfloat maxx,\n\tfloat maxy,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_AREA) == core->getData()->areas.size()) {\n\t\treturn 0;\n\t}\n\tint areaId = Item::Area::identifier.get();\n\tItem::SharedArea area(new Item::Area);\n\t//area->amx = amx;\n\tarea->areaId = areaId;\n\tarea->type = STREAMER_AREA_TYPE_RECTANGLE;\n\tarea->position = Box2d(Eigen::Vector2f(minx, miny), Eigen::Vector2f(maxx, maxy));\n\tboost::geometry::correct(boost::get<Box2d>(area->position));\n\tarea->comparableSize = static_cast<float>(boost::geometry::comparable_distance(boost::get<Box2d>(area->position).min_corner(), boost::get<Box2d>(area->position).max_corner()));\n\tarea->size = static_cast<float>(boost::geometry::distance(boost::get<Box2d>(area->position).min_corner(), boost::get<Box2d>(area->position).max_corner()));\n\n\tworlds = area->worlds;\n\tinteriors = area->interiors;\n\tplayers = area->players;\n\n\tarea->priority = priority;\n\tcore->getGrid()->addArea(area);\n\tcore->getData()->areas.insert(std::make_pair(areaId, area));\n\treturn areaId;\n}\n\nint CreateDynamicCuboidEx(\n\tfloat minx,\n\tfloat miny,\n\tfloat minz,\n\tfloat maxx,\n\tfloat maxy,\n\tfloat maxz,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_AREA) == core->getData()->areas.size()) {\n\t\treturn 0;\n\t}\n\tint areaId = Item::Area::identifier.get();\n\tItem::SharedArea area(new Item::Area);\n\t//area->amx = amx;\n\tarea->areaId = areaId;\n\tarea->type = STREAMER_AREA_TYPE_CUBOID;\n\tarea->position = Box3d(Eigen::Vector3f(minx, miny, minz), Eigen::Vector3f(maxx, maxy, maxz));\n\tboost::geometry::correct(boost::get<Box3d>(area->position));\n\tarea->comparableSize = static_cast<float>(boost::geometry::comparable_distance(Eigen::Vector2f(boost::get<Box3d>(area->position).min_corner()[0], boost::get<Box3d>(area->position).min_corner()[1]), Eigen::Vector2f(boost::get<Box3d>(area->position).max_corner()[0], boost::get<Box3d>(area->position).max_corner()[1])));\n\tarea->size = static_cast<float>(boost::geometry::distance(Eigen::Vector2f(boost::get<Box3d>(area->position).min_corner()[0], boost::get<Box3d>(area->position).min_corner()[1]), Eigen::Vector2f(boost::get<Box3d>(area->position).max_corner()[0], boost::get<Box3d>(area->position).max_corner()[1])));\n\tworlds = area->worlds;\n\tinteriors = area->interiors;\n\tplayers = area->players;\n\tarea->priority = priority;\n\tcore->getGrid()->addArea(area);\n\tcore->getData()->areas.insert(std::make_pair(areaId, area));\n\treturn areaId;\n}\n\nint CreateDynamicPolygonEx(\n\tstd::vector<Eigen::Vector2f> points,\n\tfloat minz,\n\tfloat maxz,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_AREA) == core->getData()->areas.size()) {\n\t\treturn 0;\n\t}\n\n\tint areaId = Item::Area::identifier.get();\n\tItem::SharedArea area(new Item::Area);\n\t//area->amx = amx;\n\tarea->areaId = areaId;\n\tarea->type = STREAMER_AREA_TYPE_POLYGON;\n\n\tPolygon2d polygon = boost::get<Polygon2d>(area->position);\n\tboost::geometry::assign_points(polygon, points);\n\tboost::geometry::correct(polygon);\n\n\tarea->height = Eigen::Vector2f(minz, maxz);\n\tBox2d box = boost::geometry::return_envelope<Box2d>(boost::get<Polygon2d>(area->position));\n\tarea->comparableSize = static_cast<float>(boost::geometry::comparable_distance(box.min_corner(), box.max_corner()));\n\tarea->size = static_cast<float>(boost::geometry::distance(box.min_corner(), box.max_corner()));\n\n\tworlds = area->worlds;\n\tinteriors = area->interiors;\n\tplayers = area->players;\n\n\tarea->priority = priority;\n\tcore->getGrid()->addArea(area);\n\tcore->getData()->areas.insert(std::make_pair(areaId, area));\n\treturn areaId;\n}\n\nint CreateDynamicActorEx(\n\tint modelid,\n\tfloat x,\n\tfloat y,\n\tfloat z,\n\tfloat r,\n\tbool invulnerable,\n\tfloat health,\n\tfloat streamDistance,\n\tboost::unordered_set<int> &worlds,\n\tboost::unordered_set<int> &interiors,\n\tstd::bitset<MAX_PLAYERS> &players,\n\tboost::unordered_set<int> &areas,\n\tint priority\n) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_ACTOR) == core->getData()->actors.size()) {\n\t\treturn 0;\n\t}\n\tint actorId = Item::Actor::identifier.get();\n\tItem::SharedActor actor(new Item::Actor);\n\t//actor->amx = amx;\n\tactor->actorId = actorId;\n\tactor->inverseAreaChecking = false;\n\tactor->originalComparableStreamDistance = -1.0f;\n\tactor->modelId = modelid;\n\tactor->position = Eigen::Vector3f(x, y, z);\n\tactor->rotation = r;\n\tactor->invulnerable = invulnerable;\n\tactor->health = health;\n\tactor->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;\n\tactor->streamDistance = streamDistance;\n\n\tworlds = actor->worlds;\n\tinteriors = actor->interiors;\n\tplayers = actor->players;\n\tareas = actor->areas;\n\n\tactor->priority = priority;\n\tcore->getGrid()->addActor(actor);\n\tcore->getData()->actors.insert(std::make_pair(actorId, actor));\n\treturn actorId;\n}\n\nSTREAMER_END_NS\n", "meta": {"hexsha": "d93e894deaf99efea5c47b67240147e60910b00e", "size": 17332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/implements/extended_impl.cpp", "max_stars_repo_name": "philip1337/samp-plugin-streamer", "max_stars_repo_head_hexsha": "54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T23:27:03.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-24T06:18:13.000Z", "max_issues_repo_path": "src/implements/extended_impl.cpp", "max_issues_repo_name": "Sphinxila/samp-plugin-streamer", "max_issues_repo_head_hexsha": "54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a", "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/implements/extended_impl.cpp", "max_forks_repo_name": "Sphinxila/samp-plugin-streamer", "max_forks_repo_head_hexsha": "54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a", "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.4555353902, "max_line_length": 319, "alphanum_fraction": 0.7353450265, "num_tokens": 4551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.17416210467732016}}
{"text": "// #include <core/scoring/motif/motif_hash_stuff.hh>\n// #include <core/import_pose/import_pose.hh>\n#include <basic/options/option_macros.hh>\n\n// #include <core/chemical/ChemicalManager.hh>\n// #include <core/pose/PDBInfo.hh>\n\n// #include <core/scoring/ScoreFunctionFactory.hh>\n// #include <core/pose/Pose.hh>\n// #include <core/io/pdb/pose_io.hh>\n// #include <core/import_pose/import_pose.hh>\n// #include <core/id/AtomID.hh>\n#include <devel/init.hh>\n\n#include <utility/io/izstream.hh>\n#include <utility/io/ozstream.hh>\n#include <utility/file/file_sys_util.hh>\n#include <ObjexxFCL/format.hh>\n\n\n#include <boost/lexical_cast.hpp>\n#include <boost/foreach.hpp>\n#include <map>\n\n#include <riflib/RifFactory.hh>\n\n#include <riflib/util.hh>\n\n\n\nusing std::cout;\nusing std::endl;\nusing devel::scheme::KMGT;\n\n\n\t\t// Float lever_radius,\n\t\t// Float lever_dis,\n\t\t// XformHashNeighbors<Hasher> & nbcache\n\nOPT_1GRP_KEY( StringVector, scheme, base_xmap_files             )\n\tOPT_1GRP_KEY( Real              , scheme, base_xmap_cart_resl )\n\tOPT_1GRP_KEY( Real              , scheme, base_xmap_ang_resl )\n\tOPT_1GRP_KEY( RealVector        , scheme, hash_cart_resls        )\n\tOPT_1GRP_KEY( RealVector        , scheme, hash_cart_bounds       )\n\tOPT_1GRP_KEY( RealVector        , scheme, hash_ang_resls         )\n\tOPT_1GRP_KEY( RealVector        , scheme, lever_radii      )\n\tOPT_1GRP_KEY( RealVector        , scheme, lever_bounds     )\n\tOPT_1GRP_KEY( String            , scheme, nbcache_path )\n\tOPT_1GRP_KEY( Boolean           , scheme, verbose          )\n\tOPT_1GRP_KEY( Integer           , scheme, nbcache_rotation_sample_factor          )\n\tOPT_1GRP_KEY( Boolean           , scheme, make_hacky_grids )\n\n\tvoid REGISTER_OPTIONS() {\n\t\tusing namespace basic::options;\n\t\tusing namespace basic::options::OptionKeys;\n\t\tNEW_OPT( scheme::base_xmap_files, \"xmap files to make 'coarse' grids for\"     , utility::vector1<std::string>() );\n\t\tNEW_OPT( scheme::base_xmap_cart_resl, \"cart resl for input xmap\", 0 );\n\t\tNEW_OPT( scheme::base_xmap_ang_resl, \"ang resl for input xmap\", 0 );\n\t\tNEW_OPT( scheme::hash_cart_resls, \"cartesian resolution(s) of hash table(s)\"      , utility::vector1<double>() );\n\t\tNEW_OPT( scheme::hash_cart_bounds, \"bound on cartesian coordinates\"               , utility::vector1<double>() );\n\t\tNEW_OPT( scheme::hash_ang_resls,  \"ang reslolution(s) of hash table(s) in degrees\", utility::vector1<double>() );\n\t\tNEW_OPT( scheme::lever_radii      , \"\"                                      , utility::vector1<double>() );\n\t\tNEW_OPT( scheme::lever_bounds     , \"\"                                      , utility::vector1<double>() );\n\t\tNEW_OPT( scheme::nbcache_path , \"\"                                      , \".\");\n\t\tNEW_OPT( scheme::verbose, \"\", false );\n\t\tNEW_OPT( scheme::nbcache_rotation_sample_factor, \"\", 1000 );\n\t\tNEW_OPT( scheme::make_hacky_grids, \"\", true );\n\t}\n\n\nvoid\nmake_bounding_grids(){\n\n\tusing namespace basic::options;\n\tusing ObjexxFCL::format::F;\n\tnamespace sopt = basic::options::OptionKeys::scheme;\n\tusing namespace devel::scheme;\n\n\n\truntime_assert( option[sopt::lever_radii     ]().size() == option[sopt::lever_bounds     ]().size() );\n\truntime_assert( option[sopt::lever_radii     ]().size() == option[sopt::hash_ang_resls   ]().size() );\n\truntime_assert( option[sopt::lever_radii     ]().size() == option[sopt::hash_cart_resls  ]().size() );\n\truntime_assert( option[sopt::lever_radii     ]().size() == option[sopt::hash_cart_bounds ]().size() );\n\n\truntime_assert( option[sopt::base_xmap_files]().size() == 1 );\n\n\tstd::string base_xmap_file = option[sopt::base_xmap_files]().front();\n\truntime_assert( utility::file::file_exists( base_xmap_file ) );\n\truntime_assert( base_xmap_file.substr(base_xmap_file.size()-8) == \".xmap.gz\" ||\n\t                base_xmap_file.substr(base_xmap_file.size()-7) == \".rif.gz\"  ||\n\t                base_xmap_file.substr(base_xmap_file.size()-5) == \".xmap\"  ||\n\t                base_xmap_file.substr(base_xmap_file.size()-4) == \".rif\"\n\t                );\n\tcout << \"reading \" << base_xmap_file << endl;\n\n\tstd::string rif_type = get_rif_type_from_file( base_xmap_file );\n\tstd::cout << \"======================================================================\" << std::endl;\n\tstd::cout << \"read RIF type: \" << rif_type << std::endl;\n\tstd::cout << \"======================================================================\" << std::endl;\n\tdevel::scheme::RifFactoryConfig rif_factory_config;\n\trif_factory_config.rif_type = rif_type;\n\tshared_ptr<RifFactory> rif_factory = ::devel::scheme::create_rif_factory( rif_factory_config );\n\n\tstd::string ref_description;\n\tRifConstPtr ref_rif = rif_factory->create_rif_from_file( base_xmap_file, ref_description );\n\tstd::cout << \"read description: \" << std::endl << ref_description << std::endl;\n\tstd::cout << \"======================================================================\" << std::endl;\n\n\tstd::cout << \"RIF size: \" << KMGT( ref_rif->mem_use() ) << \" load: \" << ref_rif->load_factor() << std::endl;\n\n\tint nbase = ref_rif->size();\n\tstd::cout <<\"read full xmap, size: \" << KMGT(nbase) << std::endl;\n\n\n\tfor( int ibound = 1; ibound <= option[sopt::lever_bounds]().size(); ++ibound ){\n\n\t\tdouble const lever_radius      = option[sopt::lever_radii      ]().at( ibound );\n\t\tdouble const lever_bound       = option[sopt::lever_bounds     ]().at( ibound );\n\t\tdouble const hash_ang_resl     = option[sopt::hash_ang_resls   ]().at( ibound );\n\t\tdouble const hash_cart_resl    = option[sopt::hash_cart_resls  ]().at( ibound );\n\t\tdouble const hash_cart_bound   = option[sopt::hash_cart_bounds ]().at( ibound );\n\n\t\tdouble const cart_bound = lever_bound;\n\t\tdouble const  ang_bound_rad = lever_bound / lever_radius;\n\t\tdouble const  ang_bound = ang_bound_rad * 180.0 / M_PI;\n\t\tcout << \"========================================= make bounding grids for resl. \" << lever_bound << \" ==============================================\" << endl;\n\t\tcout << \"cart_bound: \" << cart_bound << \", ang_bound: \" << ang_bound << endl;\n\t\tcout << \"cart_hash_resl: \" << hash_cart_resl << \", hash_ang_resl: \" << hash_ang_resl << std::endl;\n\n\t\tRifPtr new_rif = rif_factory->create_rif_from_rif( ref_rif, hash_cart_resl, hash_ang_resl, hash_cart_bound );\n\t\tstd::cout << \"new map size \" << KMGT(new_rif->size()) << \" ratio: \" <<  (float)new_rif->size() / (float)ref_rif->size() << std::endl;\n\n\t\t{\n\t\t\tcout << \"before resize, bounding grid size: \" << KMGT( new_rif->mem_use() )\n\t\t\t     << \" load: \" << new_rif->load_factor()\n\t\t\t\t << \", sizeof(value_type) \" << new_rif->sizeof_value_type() << endl;\n\t\t\t cout << \"NOT RESIZING bounding grid\" << endl;\n\t\t\t// bounding_xmapfull.map_.max_load_factor(0.8);\n\t\t\t// bounding_xmapfull.map_.min_load_factor(0.4);\n\t\t\t// bounding_xmapfull.map_.resize(0);\n\t\t\t// cout << \"after  resize, bounding grid size: \" << KMGT( bounding_xmapfull.mem_use() )\n\t\t\t     // << \" load: \" << bounding_xmapfull.map_.size()*1.f/bounding_xmapfull.map_.bucket_count() << endl;\n\t\t\tstd::string digits = boost::lexical_cast<std::string>(lever_bound);\n\t\t\tif( digits.size() == 1 ) digits = \"0\" + digits;\n\t\t\tstd::string tag = \"_BOUNDING_\";\n\t\t\tif( option[sopt::make_hacky_grids]() ) tag += \"HACK_\";\n\t\t\telse                                   tag += \"RANDHACK_\";\n\t\t\tstd::ostringstream oss_description;\n\t\t\toss_description << \"==== bounding xmap ====\" << endl;\n\t\t\tif( option[sopt::make_hacky_grids]() ){\n\t\t\t\toss_description << \"!!!!!!!!!!!!!!!!!!!!!!!!!!!! USING_HACKY_GRIDS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n\t\t\t}\n\t\t\toss_description << \"hash_cart_bound: \" << hash_cart_bound << endl;\n\t\t\toss_description << \"lever_radius:  \" << lever_radius << endl;\n\t\t\toss_description << \"lever_bound:   \" << lever_bound << endl;\n\t\t\toss_description << \"==== source oss_description ====\\n\" << ref_description;\n\t\t\tstd::string description = oss_description.str();\n\n\t\t\tutility::io::ozstream out( base_xmap_file+tag+\"RIF_\"+digits + \".xmap.gz\" );\n\t\t\tnew_rif->save( out, description );\n\t\t\tout.close();\n\t\t}\n\n\n\n\t}\n\n}\n\n\nint main(int argc, char *argv[])\n{\n\n\tusing namespace ::devel::scheme;\n\n\tREGISTER_OPTIONS();\n\tdevel::init(argc,argv);\n\n\tmake_bounding_grids();\n\n\treturn 0;\n}\n\n\n\n\n\n\n/*\n\ntemplate<class T>\nfloat fullval_to_numeric( T const & t ){\n\treturn t;\n}\n\ntemplate< int N >\nfloat fullval_to_numeric( ::scheme::objective::storage::RotamerScores<N> const & rs ){\n\treturn rs.score(0);\n}\n\n////////////// depricated... left for possible future reference\ntemplate<\n\tclass EigenXform,\n\tclass XMapValFull,\n\ttemplate<class Xform> class HasherFull ,\n\ttemplate<class Xform> class HasherBounding\n>\nvoid\nmake_bounding_grids_failed(){\n\n\tint const ArrayBits1 = 0;\n\tint const ArrayBits2 = 0;\n\ttypedef float XMapValBounding;\n\n\ttypedef ::scheme::objective::hash::XformMap< EigenXform, XMapValFull, HasherFull > XMapFull;\n\n\tusing namespace basic::options;\n\tusing namespace core::scoring::motif;\n\tnamespace sopt = basic::options::OptionKeys::scheme;\n\tusing ObjexxFCL::format::F;\n\tusing devel::scheme::omp_max_threads;\n\tusing devel::scheme::omp_thread_num;\n\n\tboost::random::mt19937 rng((unsigned int)time(0) + 736495684);\n\tint const num_threads = omp_max_threads();\n\n\ttypedef scheme::objective::hash::XformMap< EigenXform, XMapValBounding, HasherBounding > XMapBounding;\n\ttypedef scheme::objective::hash::XformHashNeighbors<typename XMapBounding::Hasher> XHNB;\n\n\truntime_assert( option[sopt::lever_radii     ]().size() == option[sopt::lever_bounds     ]().size() );\n\truntime_assert( option[sopt::lever_radii     ]().size() == option[sopt::hash_ang_resls   ]().size() );\n\truntime_assert( option[sopt::lever_radii     ]().size() == option[sopt::hash_cart_resls  ]().size() );\n\truntime_assert( option[sopt::lever_radii     ]().size() == option[sopt::hash_cart_bounds ]().size() );\n\n\tXMapFull full_xmap; // read resls from file unless artificial\n\tstd::string full_xmap_description;\n\tstd::string base_xmap_file = \"artificial_test\";\n\tif( option[sopt::base_xmap_files]().size() > 0 ){\n\t\tbase_xmap_file = option[sopt::base_xmap_files]().front();\n\t\tcout << \"reading \" << base_xmap_file << endl;\n\t\truntime_assert( option[sopt::base_xmap_files]().size() == 1 );\n\t\truntime_assert( utility::file::file_exists( base_xmap_file ) )\n\t\truntime_assert( base_xmap_file.substr(base_xmap_file.size()-8) == \".xmap.gz\" ||\n\t\t                base_xmap_file.substr(base_xmap_file.size()-7) == \".rif.gz\"  ||\n\t\t                base_xmap_file.substr(base_xmap_file.size()-5) == \".xmap\"  ||\n\t\t                base_xmap_file.substr(base_xmap_file.size()-4) == \".rif\"\n\t\t                );\n\t\tutility::io::izstream in( base_xmap_file );\n\t\truntime_assert( full_xmap.load( in, full_xmap_description ) );\n\t\tin.close();\n\t\tstd::cout << \"RIF size: \" << KMGT( full_xmap.mem_use() ) << \" load: \" << full_xmap.map_.size()*1.f/full_xmap.map_.bucket_count() << std::endl;\n\t} else if( option[sopt::test_structure].user() ) {\n\t\tcout << \"make artificial test RIF from: \" << option[sopt::test_structure]() << endl;\n\t\tfull_xmap.init( option[sopt::base_xmap_cart_resl](), option[sopt::base_xmap_ang_resl]() );\n\t\tcore::pose::Pose pose;\n\t\tcore::import_pose::pose_from_pdb( pose, option[sopt::test_structure]() );\n\t\tfor( int itest = 0; itest < option[sopt::num_test_points](); ++itest ){\n\t\t\t{\n\t\t\t\tnumeric::xyzVector<double> cen   = protocols::sic_dock::center_of_geom( pose );\n\t\t\t\tnumeric::xyzVector<double> trans = numeric::random::random_vector_unit_cube() * 20.0 - 10.0;\n\t\t\t\tnumeric::xyzMatrix<double> rot   = numeric::random::random_rotation();\n\t\t\t\tprotocols::sic_dock::trans_pose( pose, -cen );\n\t\t\t\tprotocols::sic_dock::rot_pose( pose, rot );\n\t\t\t\tprotocols::sic_dock::trans_pose( pose, trans );\n\t\t\t}\n\t\t\tstd::vector<int> picked_res;\n\t\t\tfor( int ir = 1; ir <= pose.size(); ++ir ) picked_res.push_back(ir);\n\t\t\tnumeric::random::random_permutation( picked_res, numeric::random::rg() );\n\t\t\tstd::vector<EigenXform> target_frames;\n\t\t\tfloat score = 2.0 - (double)itest / ((double)option[sopt::num_test_points]()-1);\n\t\t\tstd::cout << itest << \" \" << score << std::endl;\n\t\t\tfor( int i = 0; i < option[sopt::num_target_frames](); ++i ){\n\t\t\t\tint ir = picked_res[i];\n\t\t\t\tscheme::actor::BackboneActor<EigenXform> bbactor( pose.residue(ir).xyz(\"N\"), pose.residue(ir).xyz(\"CA\"), pose.residue(ir).xyz(\"C\") );\n\t\t\t\t::scheme::objective::storage::RotamerScores< 12 > rs;\n\t\t\t\trs.add_rotamer( 1, score );\n\t\t\t\tfull_xmap.insert( bbactor.position(), rs );\n\t\t\t}\n\t\t\tpose.dump_pdb( \"test\"+ObjexxFCL::format::I(4,itest+1)+\".pdb\" );\n\t\t}\n\t} else {\n\t\tutility_exit_with_message( \"must specify base_xmap_files OR test_structure\" );\n\t}\n\t// int nbase = full_xmap.count_not( 0.0 );\n\t// int nbase = full_xmap.count_not( XMapValFull() );\n\tint nbase = full_xmap.size();\n\tstd::cout <<\"read full xmap, size: \" << KMGT(nbase) << std::endl;\n\n\n\tfor( int ibound = 1; ibound <= option[sopt::lever_bounds]().size(); ++ibound ){\n\n\t\tdouble const lever_radius      = option[sopt::lever_radii      ]().at( ibound );\n\t\tdouble const lever_bound       = option[sopt::lever_bounds     ]().at( ibound );\n\t\tdouble const hash_ang_resl     = option[sopt::hash_ang_resls   ]().at( ibound );\n\t\tdouble const hash_cart_resl    = option[sopt::hash_cart_resls  ]().at( ibound );\n\t\tdouble const hash_cart_bound   = option[sopt::hash_cart_bounds ]().at( ibound );\n\t\tstd::string nbcache_file = option[sopt::nbcache_path]() + \"/__scheme_make_bounding_grids_\"\n\t\t\t+\"cr\"+F(5,2,hash_cart_resl)+\"_\"\n\t\t\t+\"ar\"+F(5,2,hash_ang_resl)+\"_\"\n\t\t\t+\"lr\"+F(5,2,lever_radius)+\"_\"\n\t\t\t+\"lb\"+F(5,2,lever_bound)+\".nbcache.gz\";\n\n\n\t\tdouble const cart_bound = lever_bound;\n\t\tdouble const  ang_bound_rad = lever_bound / lever_radius;\n\t\tdouble const  ang_bound = ang_bound_rad * 180.0 / M_PI;\n\t\tcout << \"========================================= make bounding grids for resl. \" << lever_bound << \" ==============================================\" << endl;\n\t\tcout << \"cart_bound: \" << cart_bound << \", ang_bound: \" << ang_bound << endl;\n\t\tcout << \"cart_hash_resl: \" << hash_cart_resl << \", hash_ang_resl: \" << hash_ang_resl << std::endl;\n\n\t\tstd::cout << \"insert all values into coarse_xmap \"; std::cout.flush();\n\t\t// XMapBounding coarse_xmap( hash_cart_resl, hash_ang_resl, hash_cart_bound );\n\n\t\tXMapFull * coarse_xmapfull_p;\n\n\t\tif( option[sopt::make_hacky_grids]() || lever_bound > 3.0 ){\n\n\t\t\tcoarse_xmapfull_p = new XMapFull( hash_cart_resl, hash_ang_resl, hash_cart_bound );\n\t\t\tint progress0 = 0;\n\t\t\tBOOST_FOREACH( typename XMapFull::Map::value_type const & v, full_xmap.map_ ){\n\t\t\t\tif( ++progress0 % std::max((size_t)1,(full_xmap.size()/100)) == 0 ){\n\t\t\t\t\tstd::cout << '*'; std::cout.flush();\n\t\t\t\t}\n\t\t\t\tEigenXform x = full_xmap.hasher_.get_center( v.first );\n\t\t\t\tXMapValBounding val = fullval_to_numeric( v.second );\n\t\t\t\tif( val != 0.0 ){\n\t\t\t\t\t// coarse_xmap.insert( x, val );\n\t\t\t\t\tuint64_t k = coarse_xmapfull_p->hasher_.get_key(x);\n\t\t\t\t\ttypename XMapFull::Map::iterator iter = coarse_xmapfull_p->map_.find(k);\n\t\t\t\t\tif( iter == coarse_xmapfull_p->map_.end() ){\n\t\t\t\t\t\tcoarse_xmapfull_p->map_.insert( std::make_pair(k,v.second) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\titer->second.merge( v.second );\n\t\t\t\t\t}\n\t\t\t\t\t// bounding_xmap.insert_sphere( x, lever_radius, lever_bound, val, nbcache );\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << endl;\n\t\t\tstd::cout << \"coarse_map size \" << KMGT(coarse_xmapfull_p->size()) << \" ratio: \" <<  (float)coarse_xmapfull_p->size() / (float)full_xmap.size() << std::endl;\n\n\t\t} else {\n\t\t\tcoarse_xmapfull_p = & full_xmap;\n\t\t}\n\n\t\t// XMapBounding bounding_xmap( hash_cart_resl, hash_ang_resl, hash_cart_bound );\n\t\tXMapFull bounding_xmapfull( hash_cart_resl, hash_ang_resl, hash_cart_bound );\n\n\t\tif( option[sopt::make_hacky_grids]() ){\n\n\t\t\t// bounding_xmap = coarse_xmap;\n\t\t\tbounding_xmapfull = *coarse_xmapfull_p;\n\t\t\tstd::cout << \"make_hacky_grids, using coarse_xmap as bounding map\" << std::endl;\n\n\t\t} else if( true ) {\n\t\t\tstd::cout << \"using better hack to make bounding grids\" << std::endl;\n\n\n\t\t\tfloat cart_rand_spread = cart_bound - hash_cart_resl / 2.0; // no justification for this...\n\t\t\tfloat ang_rand_spread  =  ang_bound -  hash_ang_resl / 2.0;\n\t\t\tstd::cout << \"cart_rand_spread: \" << cart_rand_spread << \", \" << \"ang_rand_spread: \" << ang_rand_spread << endl;\n\n\t\t\tfloat cratio = cart_bound / hash_cart_resl;\n\t\t\tfloat aratio = ang_bound / hash_ang_resl;\n\n\t\t\tint Nrandxform = 100.0  *  cratio*cratio*cratio  *  aratio*aratio*aratio;\n\t\t\tstd::cout << \"N insertion samples: \" << KMGT(Nrandxform) << std::endl;\n\t\t\tif( lever_radius < 3.0 ) Nrandxform /= 3.0;\n\n\t\t\tstd::vector<EigenXform> rand_xforms(Nrandxform);\n\t\t\trand_xforms[0] = EigenXform::Identity();\n\t\t\tfor( int i = 1; i < Nrandxform; ++i ){\n\t\t\t\t::scheme::numeric::rand_xform_sphere( rng, rand_xforms[i], cart_rand_spread, float(ang_rand_spread * M_PI/180.0) );\n\t\t\t}\n\n\t\t\tstd::vector<XMapFull> bounding_xmaps( omp_max_threads(), XMapFull( hash_cart_resl, hash_ang_resl, hash_cart_bound ) );\n\n\t\t\tstd::vector< std::pair< typename XMapFull::Map::key_type, typename XMapFull::Map::data_type > > coarse_xmap_values;\n\t\t\t// std::vector< typename XMapFull::Map::value_type > coarse_xmap_values;\n\t\t\tcoarse_xmap_values.reserve(coarse_xmapfull_p->size());\n\t\t\tBOOST_FOREACH( typename XMapFull::Map::value_type const & v, coarse_xmapfull_p->map_ ){\n\t\t\t\tcoarse_xmap_values.push_back( v );\n\t\t\t}\n\n\t\t\tstd::cout << \"make grid with \" << KMGT(Nrandxform) << \" rand nbr samp. \";\n\t\t\tfloat avg_nbcount = 0;\n\t\t\t#ifdef USE_OPENMP\n\t\t\t#pragma omp parallel for schedule(dynamic,1)\n\t\t\t#endif\n\t\t\tfor( int i = 0; i < coarse_xmap_values.size(); ++i ){\n\t\t\t\tint ithread = omp_thread_num();\n\t\t\t\tXMapFull & bounding_xmap( bounding_xmaps[ithread] );\n\t\t\t\ttypename XMapFull::Map::data_type const val = coarse_xmap_values[i].second;\n\t\t\t\tEigenXform x0 = coarse_xmapfull_p->hasher_.get_center( coarse_xmap_values[i].first );\n\t\t\t\t// std::set<uint64_t> seenit;\n\t\t\t\tgoogle::dense_hash_set<uint64_t> seenit;\n\t\t\t\tseenit.set_empty_key(0);\n\t\t\t\tfor( int irand = 0; irand < Nrandxform; ++irand ){\n\t\t\t\t\tEigenXform const x = rand_xforms[irand] * x0;\n\t\t\t\t\tuint64_t const k = bounding_xmap.hasher_.get_key(x);\n\t\t\t\t\tif( seenit.find(k) == seenit.end() ){\n\t\t\t\t\t\tseenit.insert(k);\n\t\t\t\t\t\ttypename XMapFull::Map::iterator iter = bounding_xmap.map_.find(k);\n\t\t\t\t\t\tif( iter == bounding_xmap.map_.end() ){\n\t\t\t\t\t\t\tbounding_xmap.map_.insert( std::make_pair( k, val ) );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\titer->second.merge( val );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#pragma omp critical\n\t\t\t\tavg_nbcount += seenit.size();\n\n\t\t\t\tif( i % std::max((size_t)1,(coarse_xmapfull_p->size()/100)) == 0 ){\n\t\t\t\t\tstd::cout << \"*\"; std::cout.flush();\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t\tavg_nbcount /= coarse_xmap_values.size();\n\t\t\tstd::cout << \"avg_nbcount \" << avg_nbcount << \", nsamp / nbinfound = \" << Nrandxform / avg_nbcount << std::endl;\n\n\t\t\tif( lever_radius > 3.0 ) delete coarse_xmapfull_p;\n\n// utility_exit_with_message(\"testing rand neighbor gen\");\n\n\t\t\tint n = 1; while( n < bounding_xmaps.size() ) n *= 2;\n\t\t\twhile( n > 1 ){\n\t\t\t\tstd::cout << \"condense per-thread maps, to merge: \" << n << std::endl;\n\t\t\t\t#ifdef USE_OPENMP\n\t\t\t\t#pragma omp parallel for schedule(dynamic,1)\n\t\t\t\t#endif\n\t\t\t\tfor( int i = 0; i < n; ++i ){\n\t\t\t\t\tif( i < n/2 && i + n/2 < bounding_xmaps.size() ){\n\t\t\t\t\t\tXMapFull       & merge_to   = bounding_xmaps[i];\n\t\t\t\t\t\tXMapFull const & merge_from = bounding_xmaps[n/2+i];\n\t\t\t\t\t\tBOOST_FOREACH( typename XMapFull::Map::value_type const & v, merge_from.map_ ){\n\t\t\t\t\t\t\ttypename XMapFull::Map::iterator iter = merge_to.map_.find( v.first );\n\t\t\t\t\t\t\tif( iter == merge_to.map_.end() ){\n\t\t\t\t\t\t\t\tmerge_to.map_.insert( v );\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\titer->second.merge( v.second );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// std::cout << \"merged \" << i+n/2 << \" into \" << i << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tn /= 2;\n\t\t\t}\n\t\t\tbounding_xmapfull = bounding_xmaps[0];\n\n\t\t} else { // the way that doesn't work yet, using nb cells from library funcs\n\n\t// \t\tstd::cout << \"now do insert_sphere for all \" << KMGT( coarse_xmap.size() ) << \" values in coarse xmap with \" << num_threads << \" threads\" << std::endl;\n\n\t// \t\tstd::vector<XMapBounding> bounding_xmaps( omp_max_threads(), XMapBounding( hash_cart_resl, hash_ang_resl, hash_cart_bound ) );\n\t// \t\tXHNB nbcache_tmp( cart_bound, ang_bound, bounding_xmaps.front().hasher_, option[sopt::nbcache_rotation_sample_factor]() );\n\t// \t\tif( utility::file::file_exists( nbcache_file ) ){\n\t// \t\t\tcout << \"reading nbcache file: \" << nbcache_file << endl;\n\t// \t\t\tutility::io::izstream in( nbcache_file );\n\t// \t\t\tnbcache_tmp.load(in);\n\t// \t\t\tin.close();\n\t// \t\t}\n\t// \t\tstd::vector<XHNB> nbcaches( num_threads, nbcache_tmp );\n\n\t// \t\tstd::vector< std::pair< typename XMapBounding::Map::key_type, typename XMapBounding::Map::data_type > > coarse_xmap_values;\n\t// \t\tcoarse_xmap_values.reserve(coarse_xmap.size());\n\t// \t\tBOOST_FOREACH( typename XMapBounding::Map::value_type const & v, coarse_xmap.map_ ){\n\t// \t\t\tcoarse_xmap_values.push_back(v);\n\t// \t\t}\n\t// \t\tstd::vector<double> avg_nbcounts(omp_max_threads(),0.0);\n\n\t// \t\t#ifdef USE_OPENMP\n\t// \t\t#pragma omp parallel for schedule(dynamic,1)\n\t// \t\t#endif\n\t// \t\tfor( int i = 0; i < coarse_xmap_values.size(); ++i ){\n\t// \t\t\tint ithread = omp_thread_num();\n\t// \t\t\tXMapBounding & bounding_xmap( bounding_xmaps[ithread] );\n\t// \t\t\tXHNB & nbcache( nbcaches[ithread] );\n\t// \t\t\tdouble avg_nbcount = 0;\n\t// \t\t\tXMapValBounding val = coarse_xmap_values[i].second;\n\t// \t\t\tEigenXform x = coarse_xmap.hasher_.get_center( coarse_xmap_values[i].first );\n\t// \t\t\tavg_nbcounts[ithread] += bounding_xmap.insert_sphere( x, lever_radius, lever_bound, val, nbcache );\n\t// \t\t\tif( i % std::max((size_t)1,(coarse_xmap.size()/100)) == 0 ){\n\t// \t\t\t\tstd::cout << \"progress \" << (float)i / (float)coarse_xmap_values.size() *100.0 << \"% \" << std::endl;\n\t// \t\t\t}\n\t// \t\t}\n\t// \t\tdouble avg_nbcount = 0;\n\t// \t\tBOOST_FOREACH( double d, avg_nbcounts ) avg_nbcount += d;\n\t// \t\tavg_nbcount /= double( coarse_xmap_values.size() );\n\n\n\t// // test = [(str(i)+\" \") for i in range(12)]\n\t// // print\n\t// // n = 1\n\t// // while n < len(test): n *= 2\n\t// // while True:\n\t// // \tprint \"=======\",n,\"=======\"\n\t// // \tfor i in range(n):\n\t// // \t\tif i < n/2 and i+n/2 < len(test):\n\t// // \t\t\tprint i,n/2+i\n\t// // \t\t\ttest[i] += test[n/2+i]\n\t// // \tn /= 2\n\n\t// // \tif n == 1: break\n\n\t// // #for i in test: print i\n\t// \t\t// hacky parallel merge\n\t// \t\tint n = 1; while( n < bounding_xmaps.size() ) n *= 2;\n\t// \t\twhile( n > 1 ){\n\t// \t\t\tstd::cout << \"condense per-thread maps, to merge: \" << n << std::endl;\n\t// \t\t\t#ifdef USE_OPENMP\n\t// \t\t\t#pragma omp parallel for schedule(dynamic,1)\n\t// \t\t\t#endif\n\t// \t\t\tfor( int i = 0; i < n; ++i ){\n\t// \t\t\t\tif( i < n/2 && i + n/2 < bounding_xmaps.size() ){\n\t// \t\t\t\t\tXMapBounding       & merge_to   = bounding_xmaps[i];\n\t// \t\t\t\t\tXMapBounding const & merge_from = bounding_xmaps[n/2+i];\n\t// \t\t\t\t\tBOOST_FOREACH( typename XMapBounding::Map::value_type const & v, merge_from.map_ ){\n\t// \t\t\t\t\t\ttypename XMapBounding::Map::iterator iter = merge_to.map_.find( v.first );\n\t// \t\t\t\t\t\tif( iter == merge_to.map_.end() ){\n\t// \t\t\t\t\t\t\tmerge_to.map_.insert( v );\n\t// \t\t\t\t\t\t} else {\n\t// \t\t\t\t\t\t\titer->second = std::min( v.second, iter->second );\n\t// \t\t\t\t\t\t}\n\t// \t\t\t\t\t}\n\t// \t\t\t\t\tstd::cout << \"merged \" << i+n/2 << \" into \" << i << std::endl;\n\t// \t\t\t\t}\n\t// \t\t\t}\n\t// \t\t\tn /= 2;\n\t// \t\t}\n\t// \t\tbounding_xmap = bounding_xmaps[0];\n\n\t// \t\t// std::cout << \"condense per-thread maps\" << std::endl;\n\t// \t\t// XMapBounding bounding_xmap( hash_cart_resl, hash_ang_resl, hash_cart_bound );\n\t// \t\t// BOOST_FOREACH( XMapBounding const & xm, bounding_xmaps ){\n\t// \t\t// \tBOOST_FOREACH( typename XMapBounding::Map::value_type const & v, xm.map_ ){\n\t// \t\t// \t\ttypename XMapBounding::Map::iterator iter = bounding_xmap.map_.find( v.first );\n\t// \t\t// \t\tif( iter == bounding_xmap.map_.end() ){\n\t// \t\t// \t\t\tbounding_xmap.map_.insert( v );\n\t// \t\t// \t\t} else {\n\t// \t\t// \t\t\titer->second = std::min( v.second, iter->second );\n\t// \t\t// \t\t}\n\t// \t\t// \t}\n\t// \t\t// }\n\n\t// \t\tstd::cout << endl << \"average nbcount: \" << avg_nbcount << \" hash mem use: \" << KMGT(bounding_xmap.mem_use()) << std::endl;\n\n\t// \t\tstd::cout << \"save nbcache_file \" << nbcache_file << std::endl;\n\t// \t\t{\n\t// \t\t\tBOOST_FOREACH( XHNB const & nbcache, nbcaches ){\n\t// \t\t\t\tnbcache_tmp.merge( nbcache );\n\t// \t\t\t}\n\t// \t\t\tutility::io::ozstream out( nbcache_file );\n\t// \t\t\tnbcache_tmp.save( out );\n\t// \t\t\tout.close();\n\t// \t\t}\n\n\t\t} // end if hacky\n\n\n\t\t{\n\t\t\tcout << \"before resize, bounding grid size: \" << KMGT( bounding_xmapfull.mem_use() )\n\t\t\t     << \" load: \" << bounding_xmapfull.map_.size()*1.f/bounding_xmapfull.map_.bucket_count()\n\t\t\t\t << \", sizeof(value_type) \" << sizeof(typename XMapFull::Map::value_type) << endl;\n\t\t\t cout << \"NOT RESIZING bounding grid\" << endl;\n\t\t\t// bounding_xmapfull.map_.max_load_factor(0.8);\n\t\t\t// bounding_xmapfull.map_.min_load_factor(0.4);\n\t\t\t// bounding_xmapfull.map_.resize(0);\n\t\t\t// cout << \"after  resize, bounding grid size: \" << KMGT( bounding_xmapfull.mem_use() )\n\t\t\t     // << \" load: \" << bounding_xmapfull.map_.size()*1.f/bounding_xmapfull.map_.bucket_count() << endl;\n\t\t\tstd::string digits = boost::lexical_cast<std::string>(lever_bound);\n\t\t\tif( digits.size() == 1 ) digits = \"0\" + digits;\n\t\t\tstd::string tag = \"_BOUNDING_\";\n\t\t\tif( option[sopt::make_hacky_grids]() ) tag += \"HACK_\";\n\t\t\telse                                   tag += \"RANDHACK_\";\n\t\t\tstd::ostringstream description;\n\t\t\tdescription << \"==== bounding xmap ====\" << endl;\n\t\t\tif( option[sopt::make_hacky_grids]() ){\n\t\t\t\tdescription << \"!!!!!!!!!!!!!!!!!!!!!!!!!!!! USING_HACKY_GRIDS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n\t\t\t}\n\t\t\tdescription << \"hash_cart_bound: \" << hash_cart_bound << endl;\n\t\t\tdescription << \"lever_radius:  \" << lever_radius << endl;\n\t\t\tdescription << \"lever_bound:   \" << lever_bound << endl;\n\t\t\tdescription << \"==== source description ====\\n\" << full_xmap_description;\n\n\t\t\t// utility::io::ozstream out( utility::file_basename(base_xmap_file)+tag+digits + \".xmap.gz\" );\n\t\t\t// bounding_xmapfull.save( out, description.str() );\n\t\t\t// out.close();\n\n\t\t\tutility::io::ozstream out2( base_xmap_file+tag+\"RIF_\"+digits + \".xmap.gz\" );\n\t\t\tbounding_xmapfull.save( out2, description.str() );\n\t\t\tout2.close();\n\t\t}\n\n\n\t\t// int nbounding = bounding_xmapfull.count_not(0.0);\n\t\t// cout << \"Bounding size cost \" << (float)nbounding/nbase << endl;\n\t\t// float fracfill = (float)nbounding/bounding_xmapfull.map_.size() / (float)(1<<ArrayBits2);\n\t\t// float memper = (float)((1<<ArrayBits2)+8.0) / (1<<ArrayBits2);\n\n\t\t// cout << \"array fill frac \" << fracfill << \" zorder array[\" << (1<<ArrayBits2) << \"] mem_saving = \" << 9.0 / memper * fracfill << \"-fold \" << endl;\n\t\t// some very quick test data:\n\t\t//            1   2    4    8   16   32   64   128  256  512  1024\n\t\t// R2.0/1.0: 1.0 1.53 2.05 2.54 2.79 2.34 1.97 1.53 1.17 0.90 0.66\n\t\t// R3.0/1.0:               2.23 2.39 1.99      1.28           0.52\n\t\t// R1.0/0.5                3.20 3.60 3.05\n\t\t// R1.5/0.5                3.40 4.00 3.45\n\t\t// R2.5/0.5                3.11 3.68\n\n\n\t}\n\n}\n\n\n*/\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ecb2d04e9d9c4bb73936088744257f6f0d6e1b63", "size": 26711, "ext": "cc", "lang": "C++", "max_stars_repo_path": "apps/rosetta/scheme_make_bounding_grids.cc", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "apps/rosetta/scheme_make_bounding_grids.cc", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "apps/rosetta/scheme_make_bounding_grids.cc", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 42.7376, "max_line_length": 161, "alphanum_fraction": 0.6263337202, "num_tokens": 8095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.17413174458317177}}
{"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_SIMD_FUNCTION_REC_RAW_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REC_RAW_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/detail/traits.hpp>\n#include <boost/simd/function/raw.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  ///////////////////////////////////////////////////////////////////////////////////////////////////\n  /// raw_(rec) for floating types: 'take all' version when no speedier exists\n  /// on some architectures an intrinsic is called providing few bits and/or not getting correct\n  /// results for zeros denormals  and infinities (sse1, sse2, avx, vmx)\n  /// These version are used as bases for improvement using Newton Raphson and correcting limits\n  ///////////////////////////////////////////////////////////////////////////////////////////////////\n  BOOST_DISPATCH_OVERLOAD_IF( rec_\n                            , (typename T, typename X)\n                            , (detail::is_native<X>)\n                            , bd::cpu_\n                            , bs::raw_tag\n                            , bs::pack_<bd::unspecified_<T>, X>\n                            )\n  {\n    BOOST_FORCEINLINE T operator()(const raw_tag &, T const& a) const BOOST_NOEXCEPT\n    {\n      return rec(a);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "12dd8387c75d9cac748986fd257afd6a653ee2fa", "size": 1763, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/rec_raw.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/rec_raw.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/rec_raw.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": 41.0, "max_line_length": 101, "alphanum_fraction": 0.4985819626, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1740604727534149}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/Core>\n\n#ifndef NO_AUTODIFF\n#include <cmath>\n#ifdef USE_STAN_MATH\n#include <vector>\n#include <stan/math.hpp>\n#else\n#include <cfloat>\n#include <unsupported/Eigen/AutoDiff>\n#endif\n#endif\n\n#include \"celerite/celerite.h\"\n#include \"celerite/carma.h\"\n\n\nnamespace py = pybind11;\n\n//\n// By sub-classing CholeskySolver here, we can make it picklable but not make\n// C++11 a requirement for the C++ library.\n//\n// The pybind11 pickle docs are here:\n// http://pybind11.readthedocs.io/en/master/advanced/classes.html#pickling-support\n// but the gist is that class just needs to expose __getstate__ and __setstate__.\n// These will just directly call serialize and deserialize below.\n//\nclass PicklableCholeskySolver : public celerite::solver::CholeskySolver<double> {\npublic:\n  PicklableCholeskySolver () : celerite::solver::CholeskySolver<double>() {};\n\n  auto serialize () const {\n    return std::make_tuple(\n      this->computed_, this->N_, this->J_, this->log_det_,\n      this->phi_, this->u_, this->W_, this->D_\n    );\n  };\n\n  void deserialize (\n      bool computed, int n, int J, double log_det,\n      Eigen::MatrixXd phi,\n      Eigen::MatrixXd u,\n      Eigen::MatrixXd W,\n      Eigen::VectorXd D) {\n    this->computed_ = computed;\n    this->N_        = n;\n    this->J_        = J;\n    this->log_det_  = log_det;\n    this->phi_      = phi;\n    this->u_        = u;\n    this->W_        = W;\n    this->D_        = D;\n  };\n};\n\n//\n// Below is the boilerplate code for the pybind11 extension module.\n//\nPYBIND11_PLUGIN(solver) {\n  typedef Eigen::MatrixXd matrix_t;\n  typedef Eigen::VectorXd vector_t;\n\n  py::module m(\"solver\", R\"delim(\nThis is the low-level interface to the C++ implementation of the celerite\nalgorithm. These methods do most of the heavy lifting but most users shouldn't\nneed to call these directly. This interface was built using `pybind11\n<http://pybind11.readthedocs.io/>`_.\n\n)delim\");\n\n  m.def(\"get_library_version\", []() { return CELERITE_VERSION_STRING; },\n        \"The version of the linked C++ library\");\n\n  m.def(\"has_autodiff\", []() {\n#ifdef NO_AUTODIFF\n    return false;\n#else\n    return true;\n#endif\n  }, \"Returns True if celerite was compiled with autodiff support\");\n\n  py::register_exception<celerite::linalg_exception>(m, \"LinAlgError\");\n\n  m.def(\"get_kernel_value\",\n    [](\n      const vector_t& a_real,\n      const vector_t& c_real,\n      const vector_t& a_comp,\n      const vector_t& b_comp,\n      const vector_t& c_comp,\n      const vector_t& d_comp,\n      py::array_t<double> tau\n    ) {\n      auto get_kernel_value_closure = [a_real, c_real, a_comp, b_comp, c_comp, d_comp] (double t) {\n        return celerite::get_kernel_value(\n          a_real, c_real, a_comp, b_comp, c_comp, d_comp, t\n        );\n      };\n      return py::vectorize(get_kernel_value_closure)(tau);\n    },\n    R\"delim(\nGet the value of the kernel for given parameters and lags\n\nArgs:\n    a_real (array[j_real]): The coefficients of the real terms.\n    c_real (array[j_real]): The exponents of the real terms.\n    a_comp (array[j_complex]): The real part of the coefficients of the\n        complex terms.\n    b_comp (array[j_complex]): The imaginary part of the coefficients of\n        the complex terms.\n    c_comp (array[j_complex]): The real part of the exponents of the\n        complex terms.\n    d_comp (array[j_complex]): The imaginary part of the exponents of the\n        complex terms.\n    tau (array[n]): The time lags where the kernel should be evaluated.\n\nReturns:\n    array[n]: The kernel evaluated at ``tau``.\n\n)delim\");\n\n  m.def(\"get_psd_value\",\n    [](\n      const vector_t& a_real,\n      const vector_t& c_real,\n      const vector_t& a_comp,\n      const vector_t& b_comp,\n      const vector_t& c_comp,\n      const vector_t& d_comp,\n      py::array_t<double> omega\n    ) {\n      auto get_psd_value_closure = [a_real, c_real, a_comp, b_comp, c_comp, d_comp] (double t) {\n        return celerite::get_psd_value(\n          a_real, c_real, a_comp, b_comp, c_comp, d_comp, t\n        );\n      };\n      return py::vectorize(get_psd_value_closure)(omega);\n    },\n    R\"delim(\nGet the PSD of the kernel for given parameters and angular frequencies\n\nArgs:\n    a_real (array[j_real]): The coefficients of the real terms.\n    c_real (array[j_real]): The exponents of the real terms.\n    a_comp (array[j_complex]): The real part of the coefficients of the\n        complex terms.\n    b_comp (array[j_complex]): The imaginary part of the coefficients of\n        the complex terms.\n    c_comp (array[j_complex]): The real part of the exponents of the\n        complex terms.\n    d_comp (array[j_complex]): The imaginary part of the exponents of the\n        complex terms.\n    omega (array[n]): The frequencies where the PSD should be evaluated.\n\nReturns:\n    array[n]: The PSD evaluated at ``omega``.\n\n)delim\");\n\n  m.def(\"check_coefficients\",\n    [](\n      const vector_t& a_real,\n      const vector_t& c_real,\n      const vector_t& a_comp,\n      const vector_t& b_comp,\n      const vector_t& c_comp,\n      const vector_t& d_comp\n    ) {\n      return celerite::check_coefficients(a_real, c_real, a_comp, b_comp, c_comp, d_comp);\n    },\n    R\"delim(\nApply Sturm's theorem to check if parameters yield a positive PSD\n\nArgs:\n    a_real (array[j_real]): The coefficients of the real terms.\n    c_real (array[j_real]): The exponents of the real terms.\n    a_comp (array[j_complex]): The real part of the coefficients of the\n        complex terms.\n    b_comp (array[j_complex]): The imaginary part of the coefficients of\n        the complex terms.\n    c_comp (array[j_complex]): The real part of the exponents of the\n        complex terms.\n    d_comp (array[j_complex]): The imaginary part of the exponents of the\n        complex terms.\n\nReturns:\n    bool: ``True`` if the PSD is everywhere positive.\n\n)delim\");\n\n\n  //\n  // ------ CARMA ------\n  //\n  py::class_<celerite::carma::CARMASolver> carma_solver(m, \"CARMASolver\", R\"delim(\nA thin wrapper around the C++ CARMASolver class\n\nThis solver is parameterized following carma_pack:\nhttps://github.com/brandonckelly/carma_pack\n\nArgs:\n    log_sigma (float): The log of the variance of the process.\n    arparams (array[p]): The parameters of the autoregressive component.\n    maparams (array[q]): The parameters of the moving average component.\n\n)delim\");\n  carma_solver.def(py::init<double, vector_t, vector_t>());\n\n  carma_solver.def(\"log_likelihood\",\n    [](celerite::carma::CARMASolver& solver, const vector_t& t, const vector_t& y, const vector_t& yerr) {\n      return solver.log_likelihood(t, y, yerr);\n    }, R\"delim(\nCompute the log likelihood using a Kalman filter\n\nArgs:\n    t (array[n]): The input coordinates of the observations.\n    y (array[n]): The observations.\n    yerr (array[n]): The measurement uncertainties of the observations.\n\n)delim\");\n\n  carma_solver.def(\"get_celerite_coeffs\",\n    [](celerite::carma::CARMASolver& solver) {\n      vector_t a_real, c_real, a_comp, b_comp, c_comp, d_comp;\n      solver.get_celerite_coeffs(a_real, c_real, a_comp, b_comp, c_comp, d_comp);\n      return std::make_tuple(a_real, c_real, a_comp, b_comp, c_comp, d_comp);\n    }, R\"delim(\nCompute the coefficients of the celerite model for the given CARMA model\n\n)delim\");\n\n\n  //\n  // ------ CHOLESKY ------\n  //\n  py::class_<PicklableCholeskySolver> cholesky_solver(m, \"CholeskySolver\", R\"delim(\nA thin wrapper around the C++ CholeskySolver class\n)delim\");\n  cholesky_solver.def(py::init<>());\n\n#ifdef USE_STAN_MATH\n  cholesky_solver.def(\"grad_log_likelihood\",\n    [](\n        PicklableCholeskySolver& nothing,\n        double jitter,\n        const vector_t& a_real,\n        const vector_t& c_real,\n        const vector_t& a_comp,\n        const vector_t& b_comp,\n        const vector_t& c_comp,\n        const vector_t& d_comp,\n        const vector_t& A,\n        const matrix_t& U,\n        const matrix_t& V,\n        const vector_t& x,\n        const vector_t& y,\n        const vector_t& diag\n    ) {\n\n#ifndef NO_AUTODIFF\n      typedef stan::math::var g_t;\n      typedef Eigen::Matrix<g_t, Eigen::Dynamic, 1> v_t;\n\n      int J_real = a_real.rows();\n      int J_comp = a_comp.rows();\n\n      // Set up the solver to track the gradients\n      celerite::solver::CholeskySolver<g_t> solver;\n      g_t jitter_ = g_t(jitter);\n      v_t a_real_(J_real), c_real_(J_real),\n          a_comp_(J_comp), b_comp_(J_comp), c_comp_(J_comp), d_comp_(J_comp);\n      a_real_ << a_real;\n      c_real_ << c_real;\n      a_comp_ << a_comp;\n      b_comp_ << b_comp;\n      c_comp_ << c_comp;\n      d_comp_ << d_comp;\n\n      // Factorize the matrix while propagating the gradients\n      solver.compute(\n        jitter_, a_real_, c_real_, a_comp_, b_comp_, c_comp_, d_comp_,\n        A, U, V, x, diag\n      );\n\n      // Compute the likelihood\n      g_t ll = -0.5 * (solver.dot_solve(y) + solver.log_determinant() + M_PI * log(x.rows()));\n      double ll_val = ll.val();\n\n      // Evaluate the backpropagated gradients\n      std::vector<g_t> params;\n      params.push_back(jitter_);\n      for (int i = 0; i < J_real; ++i) params.push_back(a_real_(i));\n      for (int i = 0; i < J_real; ++i) params.push_back(c_real_(i));\n      for (int i = 0; i < J_comp; ++i) params.push_back(a_comp_(i));\n      for (int i = 0; i < J_comp; ++i) params.push_back(b_comp_(i));\n      for (int i = 0; i < J_comp; ++i) params.push_back(c_comp_(i));\n      for (int i = 0; i < J_comp; ++i) params.push_back(d_comp_(i));\n      std::vector<double> g;\n      ll.grad(params, g);\n\n      // Copy the results to a numpy array\n      auto result = py::array_t<double>(g.size());\n      auto buf = result.request();\n      double* ptr = (double *) buf.ptr;\n      for (size_t i = 0; i < g.size(); ++i) ptr[i] = g[i];\n\n      // Tell stan that we don't need these gradients anymore\n      stan::math::recover_memory();\n\n      return std::make_tuple(ll_val, result);\n#else\n      throw std::exception();\n#endif\n    }, R\"delim(\nCompute the gradient of the log likelihood of the model using autodiff\n\nThe returned gradient is with respect to the jitter and the coefficients.\n\nArgs:\n    jitter (float): The jitter of the kernel.\n    a_real (array[j_real]): The coefficients of the real terms.\n    c_real (array[j_real]): The exponents of the real terms.\n    a_comp (array[j_complex]): The real part of the coefficients of the\n        complex terms.\n    b_comp (array[j_complex]): The imaginary part of the coefficients of\n        the complex terms.\n    c_comp (array[j_complex]): The real part of the exponents of the\n        complex terms.\n    d_comp (array[j_complex]): The imaginary part of the exponents of the\n        complex terms.\n    x (array[n]): The _sorted_ array of input coordinates.\n    y (array[n]): The observations at ``x``.\n    diag (array[n]): An array that should be added to the diagonal of the\n        matrix. This often corresponds to measurement uncertainties and in\n        that case, ``diag`` should be the measurement _variance_\n        (i.e. sigma^2).\n\n)delim\");\n\n#else\n\n  cholesky_solver.def(\"grad_log_likelihood\",\n    [](\n      PicklableCholeskySolver& nothing,\n      double jitter,\n      const vector_t& a_real,\n      const vector_t& c_real,\n      const vector_t& a_comp,\n      const vector_t& b_comp,\n      const vector_t& c_comp,\n      const vector_t& d_comp,\n      const vector_t& A,\n      const matrix_t& U,\n      const matrix_t& V,\n      const vector_t& x,\n      const vector_t& y,\n      const vector_t& diag\n    ) {\n\n#ifndef NO_AUTODIFF\n      typedef Eigen::AutoDiffScalar<Eigen::VectorXd> g_t;\n      typedef Eigen::Matrix<g_t, Eigen::Dynamic, 1> v_t;\n\n      int J_real = a_real.rows();\n      int J_comp = a_comp.rows();\n      int g_tot = 2 * J_real + 4 * J_comp;\n\n      celerite::solver::CholeskySolver<g_t> solver;\n      v_t a_real_(J_real), c_real_(J_real),\n          a_comp_(J_comp), b_comp_(J_comp), c_comp_(J_comp), d_comp_(J_comp);\n\n      // This hack is needed because, if jitter is zero, we end up with\n      // numerically unstable gradients in all dimensions.\n      bool compute_jitter = false;\n      int i0 = 0, i = 0;\n      g_t jitter_ = g_t(jitter);\n      if (jitter > DBL_EPSILON) {\n        compute_jitter = true;\n        i0 = 1;\n        g_tot ++;\n        jitter_ = g_t(jitter, g_tot, 0);\n      } else {\n        jitter_ = g_t(jitter);\n      }\n\n      // Keep track of the coordinates of each gradient\n      if (J_real) {\n        for (i = 0; i < J_real; ++i) a_real_(i) = g_t(a_real(i), g_tot, i0+i);\n        i0 += i;\n        for (i = 0; i < J_real; ++i) c_real_(i) = g_t(c_real(i), g_tot, i0+i);\n        i0 += i;\n      }\n      if (J_comp) {\n        for (i = 0; i < J_comp; ++i) a_comp_(i) = g_t(a_comp(i), g_tot, i0+i);\n        i0 += i;\n        for (i = 0; i < J_comp; ++i) b_comp_(i) = g_t(b_comp(i), g_tot, i0+i);\n        i0 += i;\n        for (i = 0; i < J_comp; ++i) c_comp_(i) = g_t(c_comp(i), g_tot, i0+i);\n        i0 += i;\n        for (i = 0; i < J_comp; ++i) d_comp_(i) = g_t(d_comp(i), g_tot, i0+i);\n      }\n\n      // Factorize and track the gradients\n      solver.compute(\n        jitter_, a_real_, c_real_, a_comp_, b_comp_, c_comp_, d_comp_,\n        A, U, V, x, diag\n      );\n\n      // Compute the likelihood and the gradients\n      g_t ll = -0.5 * (solver.dot_solve(y) + solver.log_determinant() + M_PI * log(x.rows()));\n      double ll_val = ll.value();\n\n      // Deal with our zero jitter hack\n      Eigen::VectorXd g;\n      if (compute_jitter) {\n        g = ll.derivatives();\n      } else {\n        g.resize(g_tot + 1);\n        g(0) = 0.0;\n        g.tail(g_tot) = ll.derivatives();\n      }\n\n      // Copy the result to a numpy array\n      auto result = py::array_t<double>(g.size());\n      auto buf = result.request();\n      double* ptr = (double *) buf.ptr;\n      for (int i = 0; i < g.rows(); ++i) ptr[i] = g(i);\n\n      return std::make_tuple(ll_val, result);\n#else\n      throw std::exception();\n#endif\n\n    }, R\"delim(\nCompute the gradient of the log likelihood of the model using autodiff\n\nThe returned gradient is with respect to the jitter and the coefficients.\n\nArgs:\n    jitter (float): The jitter of the kernel.\n    a_real (array[j_real]): The coefficients of the real terms.\n    c_real (array[j_real]): The exponents of the real terms.\n    a_comp (array[j_complex]): The real part of the coefficients of the\n        complex terms.\n    b_comp (array[j_complex]): The imaginary part of the coefficients of\n        the complex terms.\n    c_comp (array[j_complex]): The real part of the exponents of the\n        complex terms.\n    d_comp (array[j_complex]): The imaginary part of the exponents of the\n        complex terms.\n    x (array[n]): The _sorted_ array of input coordinates.\n    y (array[n]): The observations at ``x``.\n    diag (array[n]): An array that should be added to the diagonal of the\n        matrix. This often corresponds to measurement uncertainties and in\n        that case, ``diag`` should be the measurement _variance_\n        (i.e. sigma^2).\n\n)delim\");\n\n#endif\n\n  cholesky_solver.def(\"compute\", [](PicklableCholeskySolver& solver,\n      double jitter,\n      const vector_t& a_real,\n      const vector_t& c_real,\n      const vector_t& a_comp,\n      const vector_t& b_comp,\n      const vector_t& c_comp,\n      const vector_t& d_comp,\n      const vector_t& A,\n      const matrix_t& U,\n      const matrix_t& V,\n      const vector_t& x,\n      const vector_t& diag) {\n    return solver.compute(\n      jitter, a_real, c_real, a_comp, b_comp, c_comp, d_comp, A, U, V, x, diag\n    );\n  },\n  R\"delim(\nCompute the Cholesky factorization of the matrix\n\nArgs:\n    jitter (float): The jitter of the kernel.\n    a_real (array[j_real]): The coefficients of the real terms.\n    c_real (array[j_real]): The exponents of the real terms.\n    a_comp (array[j_complex]): The real part of the coefficients of the\n        complex terms.\n    b_comp (array[j_complex]): The imaginary part of the coefficients of\n        the complex terms.\n    c_comp (array[j_complex]): The real part of the exponents of the\n        complex terms.\n    d_comp (array[j_complex]): The imaginary part of the exponents of the\n        complex terms.\n    x (array[n]): The _sorted_ array of input coordinates.\n    diag (array[n]): An array that should be added to the diagonal of the\n        matrix. This often corresponds to measurement uncertainties and in\n        that case, ``diag`` should be the measurement _variance_\n        (i.e. sigma^2).\n\n)delim\");\n\n  cholesky_solver.def(\"solve\", [](PicklableCholeskySolver& solver, const matrix_t& b) {\n    return solver.solve(b);\n  },\n  R\"delim(\nSolve a linear system for the matrix defined in ``compute``\n\nA previous call to :func:`solver.CholeskySolver.compute` defines a matrix\n``A`` and this method solves for ``x`` in the matrix equation ``A.x = b``.\n\nArgs:\n    b (array[n] or array[n, nrhs]): The right hand side of the linear system.\n\nReturns:\n    array[n] or array[n, nrhs]: The solution of the linear system.\n\nRaises:\n    ValueError: For mismatched dimensions.\n\n)delim\");\n\n  cholesky_solver.def(\"dot_solve\", [](PicklableCholeskySolver& solver, const matrix_t& b) {\n    return solver.dot_solve(b);\n  },\n  R\"delim(\nSolve the system ``b^T . A^-1 . b``\n\nA previous call to :func:`solver.Solver.compute` defines a matrix ``A``\nand this method solves ``b^T . A^-1 . b`` for a vector ``b``.\n\nArgs:\n    b (array[n]): The right hand side of the linear system.\n\nReturns:\n    float: The solution of ``b^T . A^-1 . b``.\n\nRaises:\n    ValueError: For mismatched dimensions.\n\n)delim\");\n\n  cholesky_solver.def(\"dot_L\", [](PicklableCholeskySolver& solver, const matrix_t& z) {\n    return solver.dot_L(z);\n  },\n  R\"delim(\nCompute the dot product of the square root of a ``celerite`` matrix\n\nThis method computes ``L.z`` where ``A = L.L^T`` is the matrix defined in\n``compute``.\n\nArgs:\n    z (array[n] or array[n, neq]): The matrix ``z`` described above.\n\nReturns:\n    array[n] or array[n, neq]: The dot product ``L.b`` as described above.\n\nRaises:\n    ValueError: For mismatched dimensions.\n\n)delim\");\n\n  cholesky_solver.def(\"dot\", [](PicklableCholeskySolver& solver,\n      double jitter,\n      const vector_t& a_real,\n      const vector_t& c_real,\n      const vector_t& a_comp,\n      const vector_t& b_comp,\n      const vector_t& c_comp,\n      const vector_t& d_comp,\n      const vector_t& A,\n      const matrix_t& U,\n      const matrix_t& V,\n      const vector_t& x,\n      const matrix_t& b) {\n    return solver.dot(jitter, a_real, c_real, a_comp, b_comp, c_comp, d_comp, A, U, V, x, b);\n  },\n  R\"delim(\nCompute the dot product of a ``celerite`` matrix and another arbitrary matrix\n\nThis method computes ``A.b`` where ``A`` is defined by the parameters and\n``b`` is an arbitrary matrix of the correct shape.\n\nArgs:\n    jitter (float): The jitter of the kernel.\n    a_real (array[j_real]): The coefficients of the real terms.\n    c_real (array[j_real]): The exponents of the real terms.\n    a_comp (array[j_complex]): The real part of the coefficients of the\n        complex terms.\n    b_comp (array[j_complex]): The imaginary part of the coefficients of\n        the complex terms.\n    c_comp (array[j_complex]): The real part of the exponents of the\n        complex terms.\n    d_comp (array[j_complex]): The imaginary part of the exponents of the\n        complex terms.\n    x (array[n]): The _sorted_ array of input coordinates.\n    b (array[n] or array[n, neq]): The matrix ``b`` described above.\n\nReturns:\n    array[n] or array[n, neq]: The dot product ``A.b`` as described above.\n\nRaises:\n    ValueError: For mismatched dimensions.\n\n)delim\");\n\n  cholesky_solver.def(\"predict\", [](PicklableCholeskySolver& solver,\n      const vector_t& y,\n      const vector_t& x) {\n    return solver.predict(y, x);\n  },\n  R\"delim(\n\n)delim\");\n\n  cholesky_solver.def(\"log_determinant\", [](PicklableCholeskySolver& solver) {\n    return solver.log_determinant();\n  },\n  R\"delim(\nGet the log-determinant of the matrix defined by ``compute``\n\nReturns:\n    float: The log-determinant of the matrix defined by\n    :func:`solver.CholeskySolver.compute`.\n\n)delim\");\n\n  cholesky_solver.def(\"computed\", [](PicklableCholeskySolver& solver) {\n      return solver.computed();\n  },\n  R\"delim(\nA flag that indicates if ``compute`` has been executed\n\nReturns:\n    bool: ``True`` if :func:`solver.CholeskySolver.compute` was previously\n    executed successfully.\n\n)delim\");\n\n  cholesky_solver.def(\"__getstate__\", [](const PicklableCholeskySolver& solver) {\n    return solver.serialize();\n  });\n\n  cholesky_solver.def(\"__setstate__\", [](PicklableCholeskySolver& solver, py::tuple t) {\n    if (t.size() != 8) throw std::runtime_error(\"Invalid state!\");\n    new (&solver) PicklableCholeskySolver();\n    solver.deserialize(\n      t[0].cast<bool>(),\n      t[1].cast<int>(),\n      t[2].cast<int>(),\n      t[3].cast<double>(),\n\n      t[4].cast<matrix_t>(),\n      t[5].cast<matrix_t>(),\n      t[6].cast<matrix_t>(),\n\n      t[7].cast<vector_t>()\n    );\n  });\n\n  return m.ptr();\n}\n", "meta": {"hexsha": "b8e7e2689ba54b7d005c8d20897e790f7456e614", "size": 20960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "celerite/solver.cpp", "max_stars_repo_name": "sczesla/celerite", "max_stars_repo_head_hexsha": "ec6c5e39267c07df4aacd3ced70d3af24634e08c", "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": "celerite/solver.cpp", "max_issues_repo_name": "sczesla/celerite", "max_issues_repo_head_hexsha": "ec6c5e39267c07df4aacd3ced70d3af24634e08c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "celerite/solver.cpp", "max_forks_repo_name": "sczesla/celerite", "max_forks_repo_head_hexsha": "ec6c5e39267c07df4aacd3ced70d3af24634e08c", "max_forks_repo_licenses": ["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.4714714715, "max_line_length": 106, "alphanum_fraction": 0.6480438931, "num_tokens": 5709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1740604727534149}}
{"text": "// Copyright (c) 2009-2010 Satoshi Nakamoto\n// Copyright (c) 2009-2013 The Bitcoin developers\n// Copyright (c) 2014 The Mini-Blockchain Project\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 \"script.h\"\n\n#include \"bignum.h\"\n#include \"core.h\"\n#include \"hash.h\"\n#include \"key.h\"\n#include \"keystore.h\"\n#include \"sync.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n\n#include <boost/foreach.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef vector<unsigned char> valtype;\n\nconst char* GetTxnOutputType(txnouttype t)\n{\n    switch (t)\n    {\n    case TX_NONSTANDARD: return \"nonstandard\";\n    case TX_PUBKEY: return \"pubkey\";\n    case TX_PUBKEYHASH: return \"pubkeyhash\";\n    case TX_SCRIPTHASH: return \"scripthash\";\n    case TX_MULTISIG: return \"multisig\";\n    case TX_NULL_DATA: return \"nulldata\";\n    }\n    return NULL;\n}\n\nnamespace {\n/** Wrapper that serializes like CTransaction, but with the modifications\n *  required for the signature hash done in-place\n */\nclass CTransactionSignatureSerializer {\nprivate:\n    const CTransaction &txTo;  // reference to the spending transaction (the one being serialized)\n\npublic:\n    CTransactionSignatureSerializer(const CTransaction &txToIn) :\n        txTo(txToIn) {}\n\n    /** Serialize an input of txTo */\n    template<typename S>\n    void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {\n        // Serialize the prevout\n        ::Serialize(s, txTo.vin[nInput].pubKey, nType, nVersion);\n\t::Serialize(s, txTo.vin[nInput].nValue, nType, nVersion);\n    }\n\n    /** Serialize an output of txTo */\n    template<typename S>\n    void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {\n        ::Serialize(s, txTo.vout[nOutput], nType, nVersion);\n    }\n\n    /** Serialize txTo */\n    template<typename S>\n    void Serialize(S &s, int nType, int nVersion) const {\n        // Serialize nVersion\n        ::Serialize(s, txTo.nVersion, nType, nVersion);\n        // Serialize vin\n        unsigned int nInputs = txTo.vin.size();\n        ::WriteCompactSize(s, nInputs);\n        for (unsigned int nInput = 0; nInput < nInputs; nInput++)\n             SerializeInput(s, nInput, nType, nVersion);\n        // Serialize vout\n        unsigned int nOutputs = txTo.vout.size();\n        ::WriteCompactSize(s, nOutputs);\n        for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)\n             SerializeOutput(s, nOutput, nType, nVersion);\n\t// Serialize msg\n\t::WriteCompactSize(s, txTo.msg.size());\n\t::Serialize(s, txTo.msg, nType, nVersion);\n        // Serialie nLockTime\n        ::Serialize(s, txTo.nLockHeight, nType, nVersion);\n    }\n};\n}\n\nuint256 SignatureHash(const CTransaction& txTo)\n{\n    // Wrapper to serialize only the necessary parts of the transaction being signed\n    CTransactionSignatureSerializer txTmp(txTo);\n\n    // Serialize and hash\n    CHashWriter ss(SER_GETHASH, 0);\n    ss << txTmp;\n    return ss.GetHash();\n}\n\n\n// Valid signature cache, to avoid doing expensive ECDSA signature checking\n// twice for every transaction (once when accepted into memory pool, and\n// again when accepted into the block chain)\n\nclass CSignatureCache\n{\nprivate:\n     // sigdata_type is (signature hash, signature, public key):\n    typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;\n    std::set< sigdata_type> setValid;\n    boost::shared_mutex cs_sigcache;\n\npublic:\n    bool\n    Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)\n    {\n        boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);\n\n        sigdata_type k(hash, vchSig, pubKey);\n        std::set<sigdata_type>::iterator mi = setValid.find(k);\n        if (mi != setValid.end())\n            return true;\n        return false;\n    }\n\n    void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)\n    {\n        // DoS prevention: limit cache size to less than 10MB\n        // (~200 bytes per cache entry times 50,000 entries)\n        // Since there are a maximum of 20,000 signature operations per block\n        // 50,000 is a reasonable default.\n        int64_t nMaxCacheSize = GetArg(\"-maxsigcachesize\", 50000);\n        if (nMaxCacheSize <= 0) return;\n\n        boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);\n\n        while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)\n        {\n            // Evict a random entry. Random because that helps\n            // foil would-be DoS attackers who might try to pre-generate\n            // and re-use a set of valid signatures just-slightly-greater\n            // than our cache size.\n            uint256 randomHash = GetRandHash();\n            std::vector<unsigned char> unused;\n            std::set<sigdata_type>::iterator it =\n                setValid.lower_bound(sigdata_type(randomHash, unused, unused));\n            if (it == setValid.end())\n                it = setValid.begin();\n            setValid.erase(*it);\n        }\n\n        sigdata_type k(hash, vchSig, pubKey);\n        setValid.insert(k);\n    }\n};\n\nbool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, CScript& scriptSigRet)\n{\n    CKey key;\n    if (!keystore.GetKey(address, key))\n        return false;\n\n    vector<unsigned char> vchSig;\n    if (!key.SignCompact(hash, vchSig))\n        return false;\n    scriptSigRet << vchSig;\n\n    //printf(\"Size: %ld %ld\\n\", scriptSigRet.size(), vchSig.size());\n\n    return true;\n}\n\nbool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, CScript& scriptSigRet)\n{\n    int nSigned = 0;\n    int nRequired = multisigdata.front()[0];\n    for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)\n    {\n        const valtype& pubkey = multisigdata[i];\n        CKeyID keyID = CPubKey(pubkey).GetID();\n        if (Sign1(keyID, keystore, hash, scriptSigRet))\n            ++nSigned;\n    }\n    return nSigned==nRequired;\n}\n\nunsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)\n{\n    unsigned int nResult = 0;\n    BOOST_FOREACH(const valtype& pubkey, pubkeys)\n    {\n        CKeyID keyID = CPubKey(pubkey).GetID();\n        if (keystore.HaveKey(keyID))\n            ++nResult;\n    }\n    return nResult;\n}\n\nbool VerifyScript(const CScript& scriptSig, const uint160& pubKey, const CTransaction& txTo, unsigned int nIn)\n{\n    assert(nIn < txTo.vin.size());\n    // Leave out the signature from the hash, since a signature can't sign itself.\n    // The checksig op will also drop the signatures from its hash.\n    uint256 hash = SignatureHash(txTo);\n    //cout << \"Tx Hash: \" << hash.GetHex() << endl;\n    //cout << \"Key: \" << pubKey.GetHex() << endl;\n    bool found=false;\n    BOOST_FOREACH(const CTxIn &txin, txTo.vin){\n\tif(txin.pubKey!=pubKey)\n\t    continue;\n#if 0\n\tprintf(\"Size: %ld\\n\", txin.scriptSig.size());\n\tfor(int i=0; i < txin.scriptSig.size(); i++){\n\t\tprintf(\"%2.2X\", txin.scriptSig[i]);\n\t}\n\tprintf(\"\\n\");\n#endif\n\tif(!txin.scriptSig.size())\n\t    return false;\n\n\t//Signature format is 1 byte for number of signatures.\n\t//Signatures are 65 bytes each\n\t//Public hashs of (m-n) of m are 20 bytes\n\tuint32_t nSigs = txin.scriptSig[0];\n\tif(!nSigs)\n\t    return false;\n\n\tuint32_t nHashStart = nSigs*65 + 1;\n\n\tif(txin.scriptSig.size() < nHashStart)\n\t    return false;\n\n\tuint32_t nHashArea = txin.scriptSig.size() - nHashStart;\n\tif(nHashArea%20)\n\t    return false;\n\n\tuint32_t nHashSigs = nHashArea/20;\n\n\tCPubKey key;\n    \tvector<uint160> recoveredKeys;\n\tfor(uint32_t i=0; i < nSigs; i++){\n\t    if(!key.RecoverCompact(hash,&txin.scriptSig[1+i*65])){\n\t\tprintf(\"Could not recover key\\n\");\n\t\treturn false;\n\t    }\n\t    recoveredKeys.push_back(key.GetID());\n\t}\n\n\tvector<uint160> explicitKeys;\n\tfor(uint32_t i=0; i < nHashSigs; i++){\n\t    uint160 temp;\n\t    memcpy(&temp, &txin.scriptSig[nHashStart + i * 20], 20);\n\t    explicitKeys.push_back(temp);\n\t}\n        \n\t//printf(\"Recovered: %s for %s\\n\", recoveredKeys[0].GetHex().c_str(), pubKey.GetHex().c_str());\n\n\t//We must enforce that the keys are sorted in order to remove malleability\n\tif(!is_sorted(recoveredKeys.begin(),recoveredKeys.end()))\n\t    return false;\n\n\tif(!is_sorted(explicitKeys.begin(),explicitKeys.end()))\n\t    return false;\n\n\t//combine the vectors\n\tvector<uint160> allKeys;\n\tallKeys.insert(allKeys.end(), recoveredKeys.begin(), recoveredKeys.end());\n\tallKeys.insert(allKeys.end(), explicitKeys.begin(), explicitKeys.end());\n\n\t//Special case for single sigs\n\tif(nSigs==1 && nHashSigs==0){\n\t    //printf(\"RecoveredKeys:s %lu\\n\", recoveredKeys.size());\n\t    if(recoveredKeys[0] != pubKey){\n\t\tprintf(\"Fail!!!!\\n\");\n\t\treturn false;\n\t    }\n\t    found=true;\n\t    continue;\n\t}\n\n\t//Sort the complete key collection\n\tsort(allKeys.begin(),allKeys.end());\n\tchar data[allKeys.size()*20 + 1];\n\tfor(uint32_t i=0; i < allKeys.size(); i++){\n\t    memcpy(&data[i*20],&allKeys[i],20);\n\t}\n\tdata[sizeof(data)-1] = nSigs;\n\n\tuint160 hash = Hash160(data,data+sizeof(data));\t\n\tif(hash!=pubKey){\n\t    printf(\"Multisig fail\\n\");\n\t    return false;\n\t}\n\tfound=true;\n    }\n    return found;\n}\n\nbool SignSignature(const CKeyStore &keystore, uint160 pubKey, CTransaction& txTo, uint32_t nIn)\n{\n    assert(nIn < txTo.vin.size());\n    // Leave out the signature from the hash, since a signature can't sign itself.\n    // The checksig op will also drop the signatures from its hash.\n    uint256 hash = SignatureHash(txTo);\n    //cout << \"Tx Hash: \" << hash.GetHex() << endl;\n    //cout << \"Key: \" << pubKey.GetHex() << endl;\n    BOOST_FOREACH(CTxIn &txin, txTo.vin){\n\tif(txin.pubKey!=pubKey)\n\t    continue;\n\ttxin.scriptSig.push_back(1);\n\treturn Sign1(CKeyID(pubKey),keystore,hash,txin.scriptSig);\n    }\n    return false;\n}\nvoid CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)\n{\n#if 0\n    this->clear();\n\n    *this << EncodeOP_N(nRequired);\n    BOOST_FOREACH(const CPubKey& key, keys)\n        *this << key;\n    *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;\n#else\n   assert(0);\n#endif\n}\n\n\n", "meta": {"hexsha": "4855dff71ca75b33a18c34a3fbb393a8eb947eb1", "size": 10128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/script.cpp", "max_stars_repo_name": "Takicegek/ocore", "max_stars_repo_head_hexsha": "9ac53cae30e065b235f16d4df35728e798552d54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-04-01T12:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:41:17.000Z", "max_issues_repo_path": "src/script.cpp", "max_issues_repo_name": "Takicegek/ocore", "max_issues_repo_head_hexsha": "9ac53cae30e065b235f16d4df35728e798552d54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-17T00:45:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-10T05:04:28.000Z", "max_forks_repo_path": "src/script.cpp", "max_forks_repo_name": "Takicegek/ocore", "max_forks_repo_head_hexsha": "9ac53cae30e065b235f16d4df35728e798552d54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T10:08:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T06:55:07.000Z", "avg_line_length": 30.5060240964, "max_line_length": 111, "alphanum_fraction": 0.6583728278, "num_tokens": 2723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.17390068230595473}}
{"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     hypothesis.cpp\n * \\author   Collin Johnson\n *\n * Implementation of AreaHypothesis.\n */\n\n#include \"hssh/local_topological/area_detection/labeling/hypothesis.h\"\n#include \"hssh/local_topological/area_detection/labeling/area_graph.h\"\n#include \"hssh/local_topological/area_detection/labeling/area_proposal.h\"\n#include \"hssh/local_topological/area_detection/labeling/boundary.h\"\n#include \"hssh/local_topological/area_detection/labeling/debug.h\"\n#include \"hssh/local_topological/area_detection/labeling/hypothesis_features.h\"\n#include \"hssh/local_topological/area_detection/labeling/loops_and_trees.h\"\n#include \"hssh/local_topological/area_detection/labeling/path_endpoints.h\"\n#include \"hssh/local_topological/area_detection/labeling/small_scale_star_builder.h\"\n#include \"hssh/local_topological/area_detection/local_topo_isovist_field.h\"\n#include \"hssh/local_topological/area_extent.h\"\n#include \"hssh/local_topological/voronoi_skeleton_grid.h\"\n#include \"math/covariance.h\"\n#include \"math/geometry/convex_hull.h\"\n#include \"math/geometry/shape_fitting.h\"\n#include \"utils/algorithm_ext.h\"\n#include \"utils/func_ptr.h\"\n#include <algorithm>\n#include <array>\n#include <boost/core/null_deleter.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/range/algorithm_ext.hpp>\n#include <boost/range/as_array.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <queue>\n\n// #define DEBUG_EIG_STATS\n// #define DEBUG_CONTAINMENT\n// #define DEBUG_ENDPOINTS\n\nnamespace vulcan\n{\nnamespace hssh\n{\n\nstd::vector<AreaHypothesis*> extract_hypotheses(const std::vector<const AreaHypothesisBoundary*>& boundaries);\n\n\nAreaHypothesis::AreaHypothesis(int id,\n                               AreaGraph* graph,\n                               const std::set<AreaNode*>& nodes,\n                               const std::set<AreaEdge*>& edges,\n                               const VoronoiSkeletonGrid* grid,\n                               const VoronoiIsovistField* isovistField,\n                               const utils::VisibilityGraph* visGraph,\n                               const utils::VisibilityGraph* skeletonGraph,\n                               const SmallScaleStarBuilder* starBuilder)\n: areaGraph_(graph)\n, nodes_(nodes.begin(), nodes.end())\n, edges_(edges.begin(), edges.end())\n, grid_(grid)\n, isovistField_(isovistField)\n, visGraph_(visGraph)\n, skelGraph_(skeletonGraph)\n, starBuilder_(starBuilder)\n, boundariesDirty_(true)\n, type_(HypothesisType::kArea)\n, frontier_(false)\n, boundary_(false)\n, id_(id)\n, length_(0.0)\n, width_(0.0)\n{\n    assert(!nodes_.empty());\n    assert(!edges_.empty());\n    assert(std::find(nodes_.begin(), nodes_.end(), nullptr) == nodes_.end());\n    //     assert(std::find(edges_.begin(), edges_.end(), nullptr) == edges_.end());\n\n    assert(edges_.find(nullptr) == edges_.end());\n\n    initialize();\n\n    // Must find path endpoints after initialize is called because that is where the axis direction is established.\n    findPathEndpoints();\n\n    for (auto cell : cells_) {\n        if (visGraph->isVertex(cell)) {\n            visibilityVertices_.push_back(cell);\n        }\n    }\n\n    for (auto node : nodes_) {\n        graphVertices_.push_back(node->getCell());\n    }\n\n    // Sanity check the nodes for the hypothesis and their loop conditions. If no boundaries are on a loop, but\n    // there's a loop node, then turn it to a non-loop because it is local to the hypothesis, which means that it\n    // comes from a small loop in the skeleton, not a larger loop through the map\n    bool haveBoundaryLoop = false;\n    for (auto node : nodes) {\n        if ((node->getType() & AreaNode::kGateway) && node->isLoop()) {\n            haveBoundaryLoop = true;\n            break;\n        }\n    }\n\n    // Go through all the nodes and turn off any loops if no boundaries are loops\n    if (!haveBoundaryLoop) {\n        for (auto node : nodes) {\n            if ((~node->getType() & AreaNode::kGateway) && node->isLoop() && !haveBoundaryLoop) {\n                node->setLoop(false);\n            }\n        }\n    }\n}\n\n\nAreaHypothesis::AreaHypothesis(const std::vector<const AreaHypothesisBoundary*>& boundaries,\n                               HypothesisType classification,\n                               bool needExtent)\n: AreaHypothesis(extract_hypotheses(boundaries), needExtent)\n{\n    assert(!boundaries.empty());\n    type_ = classification;\n}\n\n\nAreaHypothesis::AreaHypothesis(const std::vector<AreaHypothesis*>& areas, bool needExtent)\n: endNodes_{{nullptr, nullptr}}\n, boundariesDirty_(true)\n, frontier_(false)\n, boundary_(false)\n, length_(0.0f)\n{\n    assert(!areas.empty());\n\n    id_ = areas.front()->getId();\n    areaGraph_ = areas.front()->areaGraph_;\n\n    std::set<AreaNode*> mergedNodes;\n    //     std::set<AreaEdge*>       mergedEdges;\n    std::set<const AreaHypothesisBoundary*> mergedBoundaries;\n\n    std::size_t numSkeletonCells = 0;\n\n    for (auto area : areas) {\n        grid_ = area->grid_;\n        isovistField_ = area->isovistField_;\n        visGraph_ = area->visGraph_;\n        skelGraph_ = area->skelGraph_;\n        starBuilder_ = area->starBuilder_;\n\n        mergedNodes.insert(area->nodes_.begin(), area->nodes_.end());\n        edges_.insert(area->edges_.begin(), area->edges_.end());\n        numSkeletonCells += area->cells_.size();\n        mergedBoundaries.insert(area->boundaries_.begin(), area->boundaries_.end());\n\n        boost::push_back(visibilityVertices_, boost::as_array(area->visibilityVertices_));\n        boost::push_back(graphVertices_, boost::as_array(area->graphVertices_));\n\n        boundary_ |= area->boundary_;\n    }\n\n    std::sort(visibilityVertices_.begin(), visibilityVertices_.end());\n    utils::erase_unique(visibilityVertices_);\n\n    std::sort(graphVertices_.begin(), graphVertices_.end());\n    utils::erase_unique(graphVertices_);\n\n    // One type of invalid area will have a boundary appear multiple times because the gateways doesn't actually enclose\n    // the space, and thus a single hypothesis contains the edges on both sides of the boundary. This boundary will be\n    // removed, but this case needs to be handled properly.\n    auto unequalBoundaryCondition = [&areas](const AreaHypothesisBoundary* toCopy) -> bool {\n        std::array<bool, 2> similar = {{false, false}};\n        for (auto a : areas) {\n            if (!similar[0] && toCopy->getHypotheses()[0]->isSimilar(*a)) {\n                similar[0] = true;\n            } else if (!similar[1] && toCopy->getHypotheses()[1]->isSimilar(*a)) {\n                similar[1] = true;\n            }\n        }\n        return !similar[0] || !similar[1];\n    };\n\n    boundaries_.reserve(mergedBoundaries.size());\n    std::copy_if(mergedBoundaries.begin(),\n                 mergedBoundaries.end(),\n                 back_inserter(boundaries_),\n                 unequalBoundaryCondition);\n\n    nodes_.reserve(mergedNodes.size());\n    nodes_.insert(nodes_.end(), mergedNodes.begin(), mergedNodes.end());\n\n    if (boundaries_.empty()) {\n        // If there are no boundaries, then there must be at least two termination points for the area\n        assert(getPoints(AreaNode::kDeadEnd | AreaNode::kFrontier | AreaNode::kJunction).size() >= 2);\n    }\n\n    // For every boundary, copy over its max path dist -- yes this might run through the area, but it should be a\n    // close enough approximation. The path most likely won't since that path would have to be internal to get\n    // through the merged area though\n    for (auto& area : areas) {\n        for (auto& node : area->maxPathDist_) {\n            bool isBoundary = utils::contains_if(boundaries_, [node](const auto& bnd) {\n                return bnd->getNode() == node.first;\n            });\n\n            if (isBoundary) {\n                maxPathDist_[node.first] = node.second;\n            }\n        }\n    }\n\n    assert(std::find(nodes_.begin(), nodes_.end(), nullptr) == nodes_.end());\n\n    for (auto& e : edges_) {\n        length_ += e->getLength();\n        width_ += e->getAverageWidth() * e->getLength();\n    }\n\n    if (length_ > 0.0) {\n        width_ /= length_;\n    }\n\n    // Copy over all skeleton cells and merge the extents into one\n\n    if (needExtent) {\n        bool haveExtents = true;\n\n        std::vector<const AreaExtent*> extents;\n        extents.reserve(areas.size());\n        cells_.reserve(numSkeletonCells);\n        for (auto& hyp : areas) {\n            cells_.insert(cells_.end(), hyp->cells_.begin(), hyp->cells_.end());\n            extents.push_back(hyp->extent_.get());\n            haveExtents &= hyp->extent_ != nullptr;\n        }\n\n        if (haveExtents) {\n            extent_.reset(new AreaExtent(extents));\n            calculateAxis();\n            polygonBoundary_ = extent_->polygonBoundary(math::ReferenceFrame::GLOBAL);\n            rectangleBoundary_ = extent_->rectangleBoundary(math::ReferenceFrame::GLOBAL);\n            center_ = extent_->center().toPoint();\n        } else {\n            initialize();\n        }\n    } else {\n        // Create the polygon boundary via convex hull of the individual boundaries\n        std::vector<Point<double>> hullPoints;\n        for (auto& hyp : areas) {\n            hullPoints.insert(hullPoints.end(), hyp->polygonBoundary_.begin(), hyp->polygonBoundary_.end());\n        }\n        polygonBoundary_ = math::convex_hull<double>(hullPoints.begin(), hullPoints.end());\n        rectangleBoundary_ =\n          math::axis_aligned_bounding_rectangle<double>(polygonBoundary_.begin(), polygonBoundary_.end());\n\n        // Compute weighted mean of center\n        center_ = Point<double>(0, 0);\n        double totalArea = 0.0;\n        for (auto& hyp : areas) {\n            center_.x += hyp->center().x * hyp->extent_->area();\n            center_.y += hyp->center().y * hyp->extent_->area();\n            totalArea += hyp->extent_->area();\n        }\n        center_.x /= totalArea;\n        center_.y /= totalArea;\n\n        double sumCos = 0.0;\n        double sumSin = 0.0;\n        double sumEcc = 0.0;\n\n        for (auto& hyp : areas) {\n            sumCos += std::cos(hyp->axisDirection_) * hyp->cells_.size();\n            sumSin += std::sin(hyp->axisDirection_) * hyp->cells_.size();\n            sumEcc += hyp->axisRatio_ * hyp->cells_.size();\n        }\n\n        axisDirection_ = std::atan2(sumSin, sumCos);\n        axisRatio_ = sumEcc / numSkeletonCells;\n    }\n\n    mergeEndpoints(areas);\n}\n\n\nAreaHypothesis::~AreaHypothesis(void)\n{\n    // For unique_ptr\n}\n\n\nPoint<float> AreaHypothesis::center(void) const\n{\n    return center_;\n}\n\n\nmath::Rectangle<float> AreaHypothesis::rectangleBoundary(void) const\n{\n    //     assert(extent_);\n    //     return extent_->rectangleBoundary(math::ReferenceFrame::GLOBAL);\n    return rectangleBoundary_;\n}\n\n\nEndpoints AreaHypothesis::endpoints(void) const\n{\n    return std::make_pair(endNodes_[0]->getPosition(), endNodes_[1]->getPosition());\n}\n\n\nbool AreaHypothesis::isSimilar(const AreaHypothesis& rhs) const\n{\n    // Always similar to self\n    if (&rhs == this) {\n        return true;\n    }\n\n    for (auto& edge : edges_) {\n        if (rhs.edges_.find(edge) != rhs.edges_.end()) {\n            return true;\n        }\n    }\n\n    return false;\n}\n\n\nHypothesisContainment AreaHypothesis::amountContained(const AreaHypothesis& rhs) const\n{\n    //  amountContained determines how much this hypothesis contains the input hypothesis. The containment is determined\n    //  by comparing the boundaries of rhs with gateway nodes in this hypothesis. If rhs.boundaries is a subset of the\n    //  gateway nodes in this hypothesis, the containment is complete. If only some of rhs.boundaries are gateway nodes,\n    //  the containment is partial. If none of rhs.boundaries are gateway nodes, there is no containment.\n\n    std::size_t numContained = 0;\n\n    // Keep the most recent match around for disambiguating the one-boundary match areas\n    const AreaNode* lhsMatch = nullptr;\n    const AreaNode* rhsMatch = nullptr;\n\n    // Search through the boundaries in rhs\n    for (auto& b : rhs.boundaries_) {\n        auto boundaryGateway = b->getGateway();\n\n        // See if any of the internal or boundary gateway nodes are similar to the boundary's gateway\n        for (auto& n : nodes_) {\n            if ((n->getType() & AreaNode::kGateway) && boundaryGateway.isSimilarTo(n->getGateway())) {\n                lhsMatch = n;\n                rhsMatch = b->getNode();\n                ++numContained;\n                break;\n            }\n        }\n    }\n\n#ifdef DEBUG_CONTAINMENT\n    std::cout << \"DEBUG:AreaHypothesis:Contained:\" << numContained << \" Total:\" << rhs.numBoundaries() << '\\n';\n#endif\n\n    if (numContained == 0) {\n        return HypothesisContainment::none;\n    } else if (numContained > 1) {\n        if (numContained < rhs.numBoundaries()) {\n            return HypothesisContainment::partial;\n        } else   // numContained == rhs.numBoundaries()\n        {\n            return HypothesisContainment::complete;\n        }\n    } else   // numContained == 1\n    {\n        assert(lhsMatch);\n        assert(rhsMatch);\n        return singleBoundaryContainment(lhsMatch, rhs, rhsMatch);\n    }\n}\n\n\nbool AreaHypothesis::addBoundary(const AreaHypothesisBoundary* boundary)\n{\n    if (std::find(nodes_.begin(), nodes_.end(), boundary->getNode()) == nodes_.end()) {\n        std::cerr << \"WARNING:AreaHypothesis::addBoundary: Attempted to add invalid boundary.\\n\";\n        return false;\n    }\n\n    // Trying to add a duplicate boundary means the graph is being constructed incorrectly and should fail\n    assert(std::find(boundaries_.begin(), boundaries_.end(), boundary) == boundaries_.end());\n    boundaries_.push_back(boundary);\n    boundariesDirty_ = true;\n\n    return true;\n}\n\n\nbool AreaHypothesis::isValid(void) const\n{\n    // Need at least two cells to calculate valid isovist statistics\n    if (cells_.size() < 5) {\n        if (extent_) {\n            std::cout << \"Invalid area. \" << rectangleBoundary() << \" Not enough cells: \" << cells_.size() << '\\n';\n        }\n        return false;\n    }\n\n    if (edges_.size() > 1) {\n        return true;\n    }\n\n    // The type of an edge is the OR of the endpoint types. If both endpoints are gateways, then the edge type will\n    // be exactly GATEWAY_NODE, and thus the edge is valid.\n    AreaEdge* edge = *edges_.begin();\n    if ((edge->getEndpoint(0)->getType() & AreaNode::kGateway)\n        && (edge->getEndpoint(1)->getType() & AreaNode::kGateway)) {\n        return true;\n    }\n\n    assert(extent_);\n    if (extent_->area() <= 0.5) {\n        std::cout << \"Invalid area. \" << rectangleBoundary() << \" Not big enough: \" << extent_->area() << '\\n';\n    }\n    return (extent_->area() > 0.5);\n\n    // The estimated length is the measured length + the distance from the end of the edge to the wall\n    // which is just half the width because the width comes from the voronoi skeleton\n    //     return (nodes_.size() > 1) && (length_ > 1.0);\n}\n\n\nSmallScaleStar AreaHypothesis::calculateStar(HypothesisType typeMask) const\n{\n    return calculateStar(typeMask, &AreaHypothesis::getGatewaysFullType);\n}\n\n\nstd::vector<std::pair<const Gateway*, const Gateway*>> AreaHypothesis::pairwiseUnalignedGateways(void) const\n{\n    std::vector<std::pair<const Gateway*, const Gateway*>> unaligned;\n\n    for (auto bIt = beginBoundary(); bIt < endBoundary(); ++bIt) {\n        const Gateway& firstGateway = (*bIt)->getGateway();\n\n        for (auto nextIt = bIt + 1; nextIt < endBoundary(); ++nextIt) {\n            const Gateway& secondGateway = (*nextIt)->getGateway();\n\n            if (!starBuilder_->areGatewaysAligned(firstGateway, secondGateway, center())) {\n                unaligned.push_back(std::make_pair(&firstGateway, &secondGateway));\n            }\n        }\n    }\n\n    return unaligned;\n}\n\n\nstd::vector<std::pair<const Gateway*, const Gateway*>> AreaHypothesis::pairwiseAlignedGateways(void) const\n{\n    std::vector<std::pair<const Gateway*, const Gateway*>> aligned;\n\n    for (auto bIt = beginBoundary(); bIt < endBoundary(); ++bIt) {\n        const Gateway& firstGateway = (*bIt)->getGateway();\n\n        for (auto nextIt = bIt + 1; nextIt < endBoundary(); ++nextIt) {\n            const Gateway& secondGateway = (*nextIt)->getGateway();\n\n            if (starBuilder_->areGatewaysAligned(firstGateway, secondGateway, center())) {\n                aligned.push_back(std::make_pair(&firstGateway, &secondGateway));\n            }\n        }\n    }\n\n    return aligned;\n}\n\n\nint AreaHypothesis::numGatewaysAlignedToAxis(HypothesisType typeMask) const\n{\n    auto gateways = getGatewaysFullType(typeMask);\n    return starBuilder_->numGatewaysAlignedToAxis(gateways, axisDirection_);\n}\n\n\nint AreaHypothesis::numNonGatewayEnds(void) const\n{\n    const auto kEndType = AreaNode::kFrontier | AreaNode::kDeadEnd;\n\n    int numNonGateway = 0;\n\n    for (auto& node : endNodes_) {\n        if (node && (node->getType() & kEndType)) {\n            ++numNonGateway;\n        }\n    }\n\n    return numNonGateway;\n}\n\n\nbool AreaHypothesis::isEndGateway(int32_t gatewayId) const\n{\n    for (auto& node : endNodes_) {\n        if (node && (node->getType() & AreaNode::kGateway) && (node->getGateway().id() == gatewayId)) {\n            return true;\n        }\n    }\n\n    return false;\n}\n\n\nint AreaHypothesis::numEndpointsWithType(HypothesisType type) const\n{\n    int count = 0;\n\n    for (auto& node : endNodes_) {\n        for (auto& boundary : boundaries_) {\n            if (boundary->getNode() == node) {\n                auto otherGraph = boundary->getOtherHypothesis(*this);\n                assert(otherGraph);\n                if (is_hypothesis_type(otherGraph->getGatewayType(*(boundary->getNode())), type)) {\n                    ++count;\n                }\n                break;\n            }\n        }\n    }\n\n    return count;\n}\n\n\nstd::size_t AreaHypothesis::countGatewaysWithMask(HypothesisType typeMask) const\n{\n    std::size_t count = 0;\n\n    for (auto& boundary : boundaries_) {\n        auto otherGraph = boundary->getOtherHypothesis(*this);\n        assert(otherGraph);\n        if (is_hypothesis_type(otherGraph->getGatewayType(*(boundary->getNode())), typeMask)) {\n            ++count;\n        }\n    }\n\n    return count;\n}\n\n\nstd::vector<AreaHypothesis*> AreaHypothesis::findAdjacentHypotheses(void) const\n{\n    std::vector<AreaHypothesis*> adjacent;\n\n    for (auto& boundary : boundaries_) {\n        auto otherGraph = boundary->getOtherHypothesis(*this);\n        if (otherGraph) {\n            adjacent.push_back(otherGraph);\n        }\n    }\n\n    return adjacent;\n}\n\n\nAreaHypothesis* AreaHypothesis::adjacentArea(const Gateway& gateway)\n{\n    for (auto& boundary : boundaries_) {\n        if (boundary->getGateway() == gateway) {\n            return boundary->getOtherHypothesis(*this);\n        }\n    }\n\n    return nullptr;\n}\n\n\nbool AreaHypothesis::hasMergeableBoundary(void) const\n{\n    for (auto boundary : boundaries_) {\n        if (boundary->shouldMerge(BoundaryMergeCondition::kSameType)) {\n            return true;\n        }\n    }\n\n    return false;\n}\n\n\nbool AreaHypothesis::isFrontier(void) const\n{\n    return extent_->frontierRatio() > 0.5;\n}\n\n\nbool AreaHypothesis::isBoundary(void) const\n{\n    return boundary_;\n}\n\n\nconst HypothesisFeatures& AreaHypothesis::features(void) const\n{\n    calculateFeaturesIfNeeded();\n    return *features_;\n}\n\n\nHypothesisType AreaHypothesis::getType(void) const\n{\n    return type_;\n}\n\n\nHypothesisType AreaHypothesis::getGatewayType(const AreaNode& gateway) const\n{\n    auto currentType = getType();\n\n    if (currentType != HypothesisType::kPath) {\n        return currentType;\n    }\n\n    return isEndpoint(gateway) ? HypothesisType::kPathEndpoint : HypothesisType::kPathDest;\n}\n\n\nAreaProposal AreaHypothesis::toAreaProposal(void) const\n{\n    AreaType proposalClassification;\n\n    HypothesisType proposalType = getType();\n\n    if (proposalType == HypothesisType::kArea) {\n        proposalClassification = AreaType::area;\n        std::cerr << \"WARNING::AreaSegmenter: Invalid final classification of hypothesis. Creating a generic area.\\n\";\n    } else if (is_hypothesis_type(proposalType, HypothesisType::kPath)) {\n        proposalClassification = AreaType::path_segment;\n    } else if (is_hypothesis_type(proposalType, HypothesisType::kDecision)) {\n        proposalClassification = AreaType::decision_point;\n    } else if (is_hypothesis_type(proposalType, HypothesisType::kDest)) {\n        proposalClassification = AreaType::destination;\n    } else {\n        assert(is_hypothesis_type(proposalType, HypothesisType::kArea) && \"Hypothesis type didn't match area!\");\n        proposalClassification = AreaType::area;\n    }\n\n    // A path is created with different data than a place\n    if (proposalClassification == AreaType::path_segment) {\n        AreaProposal::path_endpoint_t endpoints[2];\n        for (int n = 0; n < 2; ++n) {\n            assert(endNodes_[n]);\n\n            // A gateway node will be on the boundary, see if this node is a boundary node or not\n            auto bIt = std::find_if(boundaries_.begin(), boundaries_.end(), [n, this](const AreaHypothesisBoundary* b) {\n                return b->getNode() == endNodes_[n];\n            });\n\n            endpoints[n].point = endNodes_[n]->getPosition();\n\n            if (bIt != boundaries_.end()) {\n                endpoints[n].type = AreaType::area;\n                endpoints[n].isGatewayEndpoint = true;\n                endpoints[n].gateway = (*bIt)->getGateway();\n            } else {\n                endpoints[n].isGatewayEndpoint = false;\n                if (endNodes_[n]->getType() & AreaNode::kFrontier) {\n                    endpoints[n].type = AreaType::frontier;\n                } else if (endNodes_[n]->getType() & AreaNode::kDeadEnd) {\n                    endpoints[n].type = AreaType::dead_end;\n                } else   // don't know what type it is!\n                {\n                    std::cerr << \"WARNING: AreaHypothesis: Unknown endpoint node type: \" << endNodes_[n]->getType()\n                              << \". Assigning as a dead end to be safe.\\n\";\n                    endpoints[n].type = AreaType::dead_end;\n                }\n            }\n        }\n\n        return AreaProposal(id_,\n                            endpoints[0],\n                            endpoints[1],\n                            frontier_,\n                            boundary_,\n                            *extent_,\n                            getGatewaysBasicType(HypothesisType::kPath),\n                            getGatewaysBasicType(HypothesisType::kDest),\n                            getGatewaysBasicType(HypothesisType::kDecision),\n                            getPoints(AreaNode::kFrontier),\n                            getPoints(AreaNode::kDeadEnd | AreaNode::kJunction));\n    } else {\n        return AreaProposal(id_,\n                            proposalClassification,\n                            frontier_,\n                            boundary_,\n                            *extent_,\n                            getGatewaysBasicType(HypothesisType::kPath),\n                            getGatewaysBasicType(HypothesisType::kDest),\n                            getGatewaysBasicType(HypothesisType::kDecision),\n                            getPoints(AreaNode::kFrontier),\n                            getPoints(AreaNode::kDeadEnd | AreaNode::kJunction));\n    }\n}\n\n\nDebugHypothesis AreaHypothesis::toDebug(const HypothesisTypeDistribution& distribution) const\n{\n    HypothesisType current = getType();\n\n    calculateFeaturesIfNeeded();\n    assert(extent_);\n    assert(features_);\n\n    if (current == HypothesisType::kPath) {\n        assert(endNodes_[0] && endNodes_[1]);\n        DebugHypothesis::Endpoints debugEndpoints = {{endNodes_[0]->getPosition(), endNodes_[1]->getPosition()}};\n        return DebugHypothesis(debugEndpoints,\n                               *extent_,\n                               distribution,\n                               axisRatio_,\n                               axisDirection_,\n                               extent_->frontierRatio(),\n                               std::vector<double>(features_->begin(), features_->end()));\n    } else {\n        return DebugHypothesis(current,\n                               *extent_,\n                               distribution,\n                               axisRatio_,\n                               axisDirection_,\n                               extent_->frontierRatio(),\n                               std::vector<double>(features_->begin(), features_->end()));\n    }\n}\n\n\nvoid AreaHypothesis::initialize(void)\n{\n    extractSkeletonCells();\n    calculateAxis();\n\n    std::vector<Gateway> gateways;\n\n    for (auto& n : nodes_) {\n        if (boundaries_.empty() && (n->getType() & AreaNode::kGateway)) {\n            gateways.push_back(n->getGateway());\n        }\n    }\n\n    for (auto& b : boundaries_) {\n        gateways.push_back(b->getGateway());\n    }\n\n    extent_.reset(new AreaExtent(gateways, cells_, *grid_));\n    polygonBoundary_ = extent_->polygonBoundary(math::ReferenceFrame::GLOBAL);\n    rectangleBoundary_ = extent_->rectangleBoundary(math::ReferenceFrame::GLOBAL);\n    center_ = extent_->center().toPoint();\n\n    // Normalize the initial type distribution\n    distribution_.normalize();\n\n    // Setup the distances for paths leaving through each of the gateway nodes\n    LoopGraph loopGraph;\n    construct_loop_graph(*areaGraph_, loopGraph);\n    NotExcludedEdge<LoopGraph> edgeFilter(&nodes_, &loopGraph);\n    auto filtered = boost::make_filtered_graph(loopGraph, edgeFilter);\n\n    std::vector<int> components(areaGraph_->sizeNodes(), -1);\n    boost::connected_components(filtered, &components[0]);\n\n    // Find the vertex index for the boundary so the correct component can be found\n    for (auto node : nodes_) {\n        if (node->getType() & AreaNode::kGateway) {\n            int vertex = 0;\n            for (std::size_t n = 0; n < areaGraph_->sizeNodes(); ++n) {\n                if (loopGraph[n].node == node) {\n                    vertex = n;\n                    break;\n                }\n            }\n\n            double maxDist = 0.0;\n            for (std::size_t n = 0; n < areaGraph_->sizeNodes(); ++n) {\n                if (components[n] == components[vertex]) {\n                    maxDist = std::max(areaGraph_->distanceBetweenNodes(node, loopGraph[n].node), maxDist);\n                }\n            }\n\n            maxPathDist_[node] = maxDist;\n        }\n    }\n}\n\n\nSmallScaleStar AreaHypothesis::calculateStar(HypothesisType mask, GatewayFunc func) const\n{\n    auto gateways = CALL_MEMBER_FN(*this, func)(mask);\n    return starBuilder_->buildStar(gateways, center(), rectangleBoundary());\n}\n\n\nstd::vector<Gateway> AreaHypothesis::getGatewaysBasicType(HypothesisType type) const\n{\n    std::vector<Gateway> gateways;\n\n    for (auto& boundary : boundaries_) {\n        auto otherGraph = boundary->getOtherHypothesis(*this);\n        if (otherGraph && (otherGraph->getType() == type)) {\n            gateways.push_back(boundary->getGateway());\n        }\n        assert(otherGraph);\n    }\n\n    return gateways;\n}\n\n\nstd::vector<Gateway> AreaHypothesis::getGatewaysFullType(HypothesisType mask) const\n{\n    std::vector<Gateway> gateways;\n\n    for (auto& boundary : boundaries_) {\n        auto otherGraph = boundary->getOtherHypothesis(*this);\n        if (otherGraph && (is_hypothesis_type(otherGraph->getGatewayType(*(boundary->getNode())), mask))) {\n            gateways.push_back(boundary->getGateway());\n        }\n        assert(otherGraph);\n    }\n\n    return gateways;\n}\n\n\nstd::vector<Point<double>> AreaHypothesis::getPoints(char mask) const\n{\n    std::vector<Point<double>> points;\n\n    for (auto& node : nodes_) {\n        if (node->getType() & mask) {\n            points.push_back(node->getPosition());\n        }\n    }\n\n    return points;\n}\n\n\nstd::vector<const AreaNode*> AreaHypothesis::getNodes(char mask) const\n{\n    std::vector<const AreaNode*> nodes;\n\n    for (auto& node : nodes_) {\n        if (node->getType() & mask) {\n            nodes.push_back(node);\n        }\n    }\n\n    return nodes;\n}\n\n\nvoid AreaHypothesis::extractSkeletonCells(void)\n{\n    length_ = 0.0;\n\n    for (auto& edge : edges_) {\n        assert(edge);\n\n        for (auto cellIt = edge->beginCell(), cellEnd = edge->endCell(); cellIt != cellEnd; ++cellIt) {\n            cells_.push_back(cellIt->cell);\n        }\n\n        boundary_ |= edge->isBorderEdge();\n        length_ += edge->getLength();\n        width_ += edge->getAverageWidth() * edge->getLength();\n    }\n\n    if (length_ > 0.0) {\n        width_ /= length_;\n    }\n}\n\n\nvoid AreaHypothesis::calculateAxis(void)\n{\n    assert(!cells_.empty());\n\n    double sumCos = 0.0;\n    double sumSin = 0.0;\n    double sumCosPlusPi = 0.0;\n    double sumSinPlusPi = 0.0;\n    double sumEccentricity = 0.0;\n\n    for (auto& c : cells_) {\n        // Try range [-pi/2,pi/2] and [0,pi] to see which gives a better average\n        // Ignore any cells that haven't ended up in the isovist field\n        if (isovistField_->contains(c)) {\n            double orientation = wrap_to_pi_2(isovistField_->at(c).scalar(utils::Isovist::kMaxThroughDistOrientation));\n            double flippedOrientation = (orientation < 0) ? orientation + M_PI : orientation;\n\n            sumCos += std::cos(orientation);\n            sumSin += std::sin(orientation);\n            sumCosPlusPi += std::cos(flippedOrientation);\n            sumSinPlusPi += std::sin(flippedOrientation);\n            sumEccentricity += isovistField_->at(c).scalar(utils::Isovist::kShapeEccentricity);\n        }\n    }\n\n    double dir = wrap_to_pi_2(std::atan2(sumSin, sumCos));\n    double plusPiDir = wrap_to_pi_2(std::atan2(sumSinPlusPi, sumCosPlusPi));\n\n    double totalDiffDir = 0.0;\n    double totalDiffPlusPi = 0.0;\n\n    for (auto& c : cells_) {\n        if (isovistField_->contains(c)) {\n            double orientation = wrap_to_pi_2(isovistField_->at(c).scalar(utils::Isovist::kMaxThroughDistOrientation));\n            totalDiffDir += angle_diff_abs_pi_2(orientation, dir);\n            totalDiffPlusPi += angle_diff_abs_pi_2(orientation, plusPiDir);\n        }\n    }\n\n    axisDirection_ = (totalDiffDir < totalDiffPlusPi) ? dir : plusPiDir;\n    axisRatio_ = sumEccentricity / cells_.size();\n}\n\n\nvoid AreaHypothesis::calculateFeaturesIfNeeded(void) const\n{\n    if (!features_) {\n        //         auto subgraph = visGraph_->createSubgraph(beginVisVertices(), endVisVertices());\n        features_.reset(new HypothesisFeatures(*this, *extent_, *grid_, *isovistField_, *visGraph_, *skelGraph_));\n    }\n}\n\n\nvoid AreaHypothesis::findPathEndpoints(void)\n{\n    std::vector<const AreaNode*> validBoundaryNodes;\n    std::vector<DirectedPoint> possibleEndpoints;\n\n    for (auto bnd : boundaryNodes()) {\n        // If there isn't space for the robot to fit on the other side, then skip this boundary\n        if (maxPathDist_.empty() || (maxPathDist_[bnd] > 3.0)) {\n            validBoundaryNodes.push_back(bnd);\n        }\n    }\n\n    // Use all nodes if there aren't enough valid boundaries found\n    if (validBoundaryNodes.size() < 2) {\n        validBoundaryNodes = boundaryNodes();\n    }\n\n    std::size_t numLoopNodes = 0;\n\n    for (auto& bnd : validBoundaryNodes) {\n        if (bnd->getType() & AreaNode::kGateway) {\n            const auto& gwy = bnd->getGateway();\n\n            DirectedPoint endpoint;\n            endpoint.point = gwy.center();\n            endpoint.node = bnd;\n            endpoint.weight =\n              gwy.probability();   // 1.0 - other->getTypeDistribution().typeAppropriateness(HypothesisType::kDest);\n            endpoint.width = gwy.length();\n            endpoint.isGateway = true;\n\n            double leftDiff = angle_diff_abs_pi_2(gwy.leftDirection(), axisDirection_);\n            double rightDiff = angle_diff_abs_pi_2(gwy.rightDirection(), axisDirection_);\n            endpoint.direction = leftDiff < rightDiff ? gwy.leftDirection() : gwy.rightDirection();\n\n            if (bnd->isLoop()) {\n                ++numLoopNodes;\n            }\n\n            possibleEndpoints.push_back(endpoint);\n        }\n    }\n\n    // Find the axis line for the path as the line intersecting the convex hull originating at the center of the\n    // area and extending along the axis direction\n    // The intersect is between line segment, so make the segment larger than any possible map to ensure an intersection\n    // with the boundary occurs.\n    Line<double> centerLine(\n      Point<double>(center().x + 10000.0 * std::cos(axisDirection_), center().y + 10000.0 * std::sin(axisDirection_)),\n      Point<double>(center().x - 10000.0 * std::cos(axisDirection_), center().y - 10000.0 * std::sin(axisDirection_)));\n    //\n    //     // If the center line intersects a gateway, then its an endpoint. If it intersects more than two gateways,\n    //     consider\n    //     // the weird polygon approach.\n    //     for(auto& node : gatewayNodes)\n    //     {\n    //         if(node->isLoop() || line_segments_intersect(node->getGateway().boundary(), centerLine))\n    //         {\n    //             const auto& gwy = node->getGateway();\n    //\n    //             if((angle_diff_abs_pi_2(gwy.leftDirection(), axisDirection_) < M_PI / 3.0)\n    //                 || (angle_diff_abs_pi_2(gwy.rightDirection(), axisDirection_) < M_PI / 3.0))\n    //             {\n    //                 filteredGateways.push_back(node);\n    //             }\n    //         }\n    //     }\n    //\n    //     // obvious ends occur if at least two gateways are aligned to the axis of the area from the start\n    //     bool hasObviousEndGateways = filteredGateways.size() > 1;\n    //\n    //     // If there aren't end viable candidates based on loops, then consider the amount of graph that\n    //     // exists on the other side of a gateway\n    //     if(!hasObviousEndGateways && !maxPathDist_.empty())\n    //     {\n    //         filteredGateways.clear();\n    //         for(auto& bnd : maxPathDist_)\n    //         {\n    //             // Can the wheelchair fit back there?\n    //             if(bnd.second > 3.0)\n    //             {\n    //                 filteredGateways.push_back(bnd.first);\n    //             }\n    //         }\n    //\n    //         hasObviousEndGateways = filteredGateways.size() > 1;\n    //     }\n    //\n    //     if(!hasObviousEndGateways)\n    //     {\n    //         filteredGateways = gatewayNodes;\n    //         hasObviousEndGateways = filteredGateways.size() > 1;\n    //     }\n    //\n    //     for(auto& bnd : filteredGateways)\n    //     {\n    //         // For each gateway, select the direction that is most well-aligned with the axis of the area to get the\n    //         best\n    //         // possible alignment for the endpoints\n    //         const auto& gwy = bnd->getGateway();\n    //         double leftDiff = angle_diff_abs_pi_2(gwy.leftDirection(), axisDirection_);\n    //         double rightDiff = angle_diff_abs_pi_2(gwy.rightDirection(), axisDirection_);\n    //         double direction =  leftDiff < rightDiff ? gwy.leftDirection() : gwy.rightDirection();\n    //\n    //         possibleEndpoints.push_back({gwy.center(), bnd, direction, true});\n    //     }\n\n    if ((possibleEndpoints.size() < 2) || (numLoopNodes < 2)) {\n        auto frontiers = getNodes(AreaNode::kDeadEnd);\n\n        // If there aren't enough possible endpoints, then consider the junctions as well. By default they shouldn't be\n        // included because they usually align very well with the axis and result in the path being too short.\n        if (frontiers.size() + possibleEndpoints.size() < 2) {\n            boost::push_back(frontiers, boost::as_array(getNodes(AreaNode::kJunction)));\n        }\n\n        // For each frontier point, need to find the direction. Use the orientation of the isovist at the cell.\n        for (auto node : frontiers) {\n            cell_t cell = utils::global_point_to_grid_cell_round(node->getPosition(), *grid_);\n            if (isovistField_->contains(cell)) {\n                double direction = isovistField_->at(cell).scalar(utils::Isovist::kWeightedOrientation);\n                possibleEndpoints.push_back(\n                  {node->getPosition(), node, direction, 0.1, grid_->getMetricDistance(cell.x, cell.y), false});\n            } else {\n                std::cerr << \"ERROR: No isovist found for skeleton cell at \" << cell << '\\n';\n            }\n        }\n\n        // If there aren't enough points for two endpoints, then this area can't have them\n        if (possibleEndpoints.size() < 2) {\n            std::cerr\n              << \"ERROR: AreaHypothesis: Created area without enough endpoints. Must be at least two gateways + \"\n              << \"frontiers/dead ends for a valid area.\"\n              << \" Areas:\" << possibleEndpoints.size() << \" Frontiers:\" << frontiers.size()\n              << \" Nodes:\" << nodes_.size() << '\\n';\n            for (auto n : nodes_) {\n                std::cout << \"Node:\" << n->getPosition() << ':' << static_cast<int>(n->getType()) << '\\n';\n            }\n\n            assert(possibleEndpoints.size() >= 2);\n        }\n    }\n\n    PointPair endpoints;\n\n    if (possibleEndpoints.size() != 2) {\n        // NOTE: To ensure the correct inter-node, a new AreaGraph containing only the nodes in this area\n        // would need to be computed. It's REALLY slow, so approximate with the original AreaGraph. In most cases,\n        // these graphs will give the same inter-node distances, so the approximation is find for the 40% speedup.\n        std::vector<Point<double>> boundaryIntersections;\n        polygonBoundary_.intersections(centerLine, boundaryIntersections);\n        if (boundaryIntersections.size() != 2) {\n            if (boundaryIntersections.size() < 2) {\n                std::cerr\n                  << \"ERROR: AreaHypothesis: Axis line starting from center doesn't intersect the convex hull! Axis:\"\n                  << centerLine << \" Boundary:\" << polygonBoundary_ << '\\n';\n            }\n\n            boundaryIntersections.resize(2);\n            boundaryIntersections[0] = centerLine.a;\n            boundaryIntersections[1] = centerLine.b;\n        }\n\n        endpoints = find_path_endpoints(possibleEndpoints,\n                                        Line<double>(boundaryIntersections[0], boundaryIntersections[1]),\n                                        axisDirection_,\n                                        *areaGraph_);\n    } else {\n        endpoints.first = possibleEndpoints[0];\n        endpoints.second = possibleEndpoints[1];\n    }\n\n    assignEndNodes(std::make_pair(endpoints.first.point, endpoints.second.point));\n\n#ifdef DEBUG_ENDPOINTS\n    std::cout << \"DEBUG: AreaHypothesis: Selecting endpoint amongst gateways: \";\n    for (auto& g : gateways) {\n        std::cout << g.id() << ' ';\n    }\n    std::cout << '\\n';\n\n    std::cout << \"DEBUG: AreaHypothesis: Endpoints: \";\n    for (auto& node : endNodes_) {\n        if (node->getType() & AreaNode::kGateway) {\n            std::cout << \"G:\" << node->getGateway().id() << ':' << node->getGateway().boundary() << ' ';\n        } else {\n            std::cout << \"F:\" << node->getPosition() << ' ';\n        }\n    }\n    std::cout << '\\n';\n#endif\n}\n\n\nvoid AreaHypothesis::mergeEndpoints(const std::vector<AreaHypothesis*>& areas)\n{\n    // Collect all the endpoints.\n    std::vector<Point<double>> endpoints;\n    std::vector<int8_t> hasMatch;\n    std::vector<int> ids;\n    for (auto& area : areas) {\n        hasMatch.resize(area->endNodes_.size());\n        std::fill(hasMatch.begin(), hasMatch.end(), 0);\n        ids.clear();\n\n        for (auto& node : area->endNodes_) {\n            ids.push_back((node->getType() & AreaNode::kGateway) ? node->getGateway().id() : -1);\n        }\n\n        // We care about any endpoint that doesn't match another endpoint in one of the merged areas. Any matching\n        // end gateways should be the merge point for the boundary.\n        for (auto& other : areas) {\n            if (other != area) {\n                for (std::size_t n = 0; n < ids.size(); ++n) {\n                    hasMatch[n] |= other->isEndGateway(ids[n]);\n                }\n            }\n        }\n\n        // There there weren't matches, then this endpoint is a new possible endpoint for the merged area, as it\n        // won't be internal to the area like any matched gateway, which are now internal to the merged area\n        for (std::size_t n = 0; n < ids.size(); ++n) {\n            if (!hasMatch[n]) {\n                endpoints.push_back(area->endNodes_[n]->getPosition());\n            }\n        }\n    }\n\n    // Remove any endpoints where the count is more than one, as they are now internal to the area\n    // Can't use erase_unique because unique still leaves one of the original values. Need to remove them all.\n    auto pEnd = endpoints.end();\n    for (auto pIt = endpoints.begin(); pIt < pEnd; ++pIt) {\n        if (std::count(pIt, pEnd, *pIt) > 1) {\n            pEnd = std::remove(pIt, pEnd, *pIt);\n            pIt = endpoints.begin();\n        }\n    }\n    endpoints.erase(pEnd, endpoints.end());\n\n    // If only two endpoints remain, then a merge can be performed\n    if (endpoints.size() == 2) {\n        assignEndNodes(Endpoints(endpoints[0], endpoints[1]));\n    }\n    // Otherwise, need to do a full search for new endpoints\n    else {\n        findPathEndpoints();\n    }\n}\n\n\nvoid AreaHypothesis::assignEndNodes(Endpoints endpoints)\n{\n    endNodes_.clear();\n\n    // Once the actual position of the endpoints have been found, go through the nodes in the hypothesis\n    // to determine which endpoint they correspond to\n    for (auto& node : nodes_) {\n        if (node->getPosition() == endpoints.first) {\n            addEndNode(node);\n        }\n\n        if (node->getPosition() == endpoints.second) {\n            addEndNode(node);\n        }\n    }\n\n    if (endNodes_.size() < 2) {\n        std::cerr << \"ERROR: AreaHypothesis: Have a null end node. Endpoints:\" << endpoints.first << \"->\"\n                  << endpoints.second << \" Nodes:\\n\";\n        for (auto& node : nodes_) {\n            std::cerr << node->getPosition() << \" Type:\" << static_cast<int>(node->getType()) << '\\n';\n\n            if (node->getType() & AreaNode::kGateway) {\n                std::cerr << \"Gateway:\" << node->getGateway().center() << '\\n';\n            }\n        }\n        assert(endNodes_.size() >= 2);\n    }\n\n    // Now check if either of the assigned end nodes leads to the same area as the established end node\n    // If this node is associated with a boundary, then see if any other boundaries lead to the same area.\n    // If so, those gateways are also end nodes, as the endpoint condition is area-based not gateway-based.\n    for (int n = 0; n < 2; ++n) {\n        const AreaNode* node = endNodes_[n];\n        auto bndIt = std::find_if(boundaries_.begin(), boundaries_.end(), [node](auto& bnd) {\n            return bnd->getNode() == node;\n        });\n\n        if (bndIt != boundaries_.end()) {\n            auto otherHyp = (*bndIt)->getOtherHypothesis(*this);\n\n            for (auto& boundary : boundaries_) {\n                if ((boundary != *bndIt) && (boundary->getOtherHypothesis(*this) == otherHyp)) {\n                    endNodes_.push_back(boundary->getNode());\n                }\n            }\n        }\n    }\n}\n\n\nvoid AreaHypothesis::addEndNode(AreaNode* node)\n{\n    // This node will definitely be an end node\n    endNodes_.push_back(node);\n}\n\n\nbool AreaHypothesis::isNonEndpointGateway(const AreaNode* node) const\n{\n    // If the node isn't on the boundary, then obviously, it isn't a gateway\n    // NOTE: Can't just check if it is a gateway node because gateway nodes won't be on the boundary of merged areas!\n    //       They'll be marked gateway because they are associated with a potential gateway, but only the boundaries of\n    //       an area represent the final gateways\n    auto boundaryNodeComp = [node](const AreaHypothesisBoundary* boundary) {\n        return boundary->getNode() == node;\n    };\n\n    if (std::find_if(boundaries_.begin(), boundaries_.end(), boundaryNodeComp) == boundaries_.end()) {\n        return false;\n    }\n\n    return !utils::contains(endNodes_, node);\n}\n\n\nbool AreaHypothesis::isEndpoint(const AreaNode& node) const\n{\n    return utils::contains_if(endNodes_, [&node](auto& endNode) {\n        return node.getPosition() == endNode->getPosition();\n    });\n}\n\n\nstd::vector<const AreaNode*> AreaHypothesis::boundaryNodes(void) const\n{\n    std::vector<const AreaNode*> bndNodes;\n\n    // If boundaries exist, just use those nodes\n    if (!boundaries_.empty()) {\n        for (auto& bnd : boundaries_) {\n            bndNodes.push_back(bnd->getNode());\n        }\n    }\n    // Otherwise internal gateway nodes must be valid.\n    else {\n        for (auto& node : nodes_) {\n            if (node->getType() & AreaNode::kGateway) {\n                bndNodes.push_back(node);\n            }\n        }\n    }\n\n    return bndNodes;\n}\n\n\nHypothesisContainment AreaHypothesis::singleBoundaryContainment(const AreaNode* lhsNode,\n                                                                const AreaHypothesis& rhs,\n                                                                const AreaNode* rhsNode) const\n{\n    auto otherLhsNode = findConnectedNode(lhsNode);\n    auto otherRhsNode = rhs.findConnectedNode(rhsNode);\n\n    auto lhsGateway = lhsNode->getGateway();\n\n    if (lhsGateway.isPointToLeft(otherLhsNode->getPosition())\n        == lhsGateway.isPointToLeft(otherRhsNode->getPosition())) {\n        return HypothesisContainment::complete;\n    } else {\n        return HypothesisContainment::none;\n    }\n}\n\n\nconst AreaNode* AreaHypothesis::findConnectedNode(const AreaNode* node) const\n{\n    auto edgeIt = std::find_if(edges_.begin(), edges_.end(), [node](const AreaEdge* e) {\n        return e->nodeIndex(node) >= 0;\n    });\n    assert(edgeIt != edges_.end());\n    int otherIndex = ((*edgeIt)->nodeIndex(node) + 1) % 2;\n    return (*edgeIt)->getEndpoint(otherIndex).get();\n}\n\n\nstd::vector<AreaHypothesis*> extract_hypotheses(const std::vector<const AreaHypothesisBoundary*>& boundaries)\n{\n    std::set<AreaHypothesis*> areasToMerge;\n\n    for (auto boundary : boundaries) {\n        areasToMerge.insert(boundary->beginHypotheses(), boundary->endHypotheses());\n    }\n\n    return std::vector<AreaHypothesis*>(areasToMerge.begin(), areasToMerge.end());\n}\n\n}   // namespace hssh\n}   // namespace vulcan\n", "meta": {"hexsha": "08008ff8c4560d45f2584c5f45a837bebc8f1e34", "size": 46625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hssh/local_topological/area_detection/labeling/hypothesis.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/hssh/local_topological/area_detection/labeling/hypothesis.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/hssh/local_topological/area_detection/labeling/hypothesis.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": 34.7688292319, "max_line_length": 120, "alphanum_fraction": 0.6086005362, "num_tokens": 11080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1739006755177822}}
{"text": "#ifndef MPLLIBS_METAPARSE_V1_IMPL_ITERATE_IMPL_UNCHECKED_HPP\n#define MPLLIBS_METAPARSE_V1_IMPL_ITERATE_IMPL_UNCHECKED_HPP\n\n// Copyright Abel Sinkovics (abel@sinkovics.hu)  2013.\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 <mpllibs/metaparse/v1/impl/fwd/iterate_impl.hpp>\n#include <mpllibs/metaparse/v1/get_result.hpp>\n#include <mpllibs/metaparse/v1/get_remaining.hpp>\n#include <mpllibs/metaparse/v1/get_position.hpp>\n\n#include <boost/mpl/apply.hpp>\n#include <boost/mpl/apply_wrap.hpp>\n#include <boost/mpl/push_back.hpp>\n\nnamespace mpllibs\n{\n  namespace metaparse\n  {\n    namespace v1\n    {\n      namespace impl\n      {\n        template <int N, class P, class Accum, class S, class Pos>\n        struct iterate_impl_unchecked :\n          boost::mpl::apply_wrap2<\n            iterate_impl<\n              N - 1,\n              P,\n              typename boost::mpl::push_back<\n                Accum,\n                typename get_result<boost::mpl::apply<P, S, Pos> >::type\n              >::type\n            >,\n            typename get_remaining<boost::mpl::apply<P, S, Pos> >::type,\n            typename get_position<boost::mpl::apply<P, S, Pos> >::type\n          >\n        {};\n      }\n    }\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "17f1252b17baf0a2c6b7be31d95036a292f5dc0b", "size": 1335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lab/mpllibs/metaparse/v1/impl/iterate_impl_unchecked.hpp", "max_stars_repo_name": "sabel83/metaparse_tutorial", "max_stars_repo_head_hexsha": "819fddf6bf06736861adbeabeb30967f56b7e8d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-07-14T01:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:48:46.000Z", "max_issues_repo_path": "lab/mpllibs/metaparse/v1/impl/iterate_impl_unchecked.hpp", "max_issues_repo_name": "sabel83/metaparse_tutorial", "max_issues_repo_head_hexsha": "819fddf6bf06736861adbeabeb30967f56b7e8d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-01T12:31:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-04T12:16:47.000Z", "max_forks_repo_path": "lab/mpllibs/metaparse/v1/impl/iterate_impl_unchecked.hpp", "max_forks_repo_name": "sabel83/metaparse_tutorial", "max_forks_repo_head_hexsha": "819fddf6bf06736861adbeabeb30967f56b7e8d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-22T20:31:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-23T07:32:29.000Z", "avg_line_length": 27.8125, "max_line_length": 72, "alphanum_fraction": 0.6329588015, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17382634193684324}}
{"text": "/*\ninteraction.cpp\n\nCopyright (c) 2014, 2015, 2016 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 <iomanip>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <boost/lexical_cast.hpp>\n#include \"interaction.h\"\n#include \"memory.h\"\n#include \"system.h\"\n#include \"error.h\"\n#include \"symmetry.h\"\n#include \"combination.h\"\n#include \"constants.h\"\n#include \"listcomparison.h\"\n#include \"files.h\"\n#include \"timer.h\"\n#include \"fcs.h\"\n#include <cmath>\n\nusing namespace ALM_NS;\n\nInteraction::Interaction(ALM *alm) : Pointers(alm) {\n    nsize[0] = nsize[1] = nsize[2] = 1;\n}\n\nInteraction::~Interaction() \n{\n    memory->deallocate(x_image);\n    memory->deallocate(exist_image);\n    memory->deallocate(str_order);\n    memory->deallocate(nbody_include);\n    memory->deallocate(pairs);\n    memory->deallocate(mindist_pairs);\n    memory->deallocate(interaction_pair);\n    memory->deallocate(mindist_cluster);\n    memory->deallocate(distall);\n}\n\nvoid Interaction::init()\n{\n    int i, j, k;\n    int nat = system->nat;\n    int nkd = system->nkd;\n\n    std::cout << \" INTERACTION\" << std::endl;\n    std::cout << \" ===========\" << std::endl << std::endl;\n\n    memory->allocate(str_order, maxorder);\n    set_ordername();\n\n    std::cout << \"  +++ Cutoff Radii Matrix in Bohr Unit (NKD x NKD matrix) +++\" << std::endl;\n\n    for (i = 0; i < maxorder; ++i) {\n        std::cout << \"  \" <<  std::setw(9) << str_order[i] << std::endl; \n        for (j = 0; j < nkd; ++j) {\n            for (k = 0; k < nkd; ++k) {\n                if (rcs[i][j][k] < 0.0) {\n                    std::cout << std::setw(9) << \"None\";\n                } else {\n                    std::cout << std::setw(9) << rcs[i][j][k];\n                }\n            }\n            std::cout << std::endl;\n        }\n        std::cout << std::endl;\n    }\n\n    nneib = (2 * nsize[0] + 1) * (2 * nsize[1] + 1) * (2 * nsize[2] + 1);\n    memory->allocate(x_image, nneib, nat, 3);\n    memory->allocate(exist_image, nneib);\n    memory->allocate(distall, nat, nat);\n    memory->allocate(mindist_pairs, nat, nat);\n    memory->allocate(interaction_pair, maxorder, symmetry->natmin);\n    memory->allocate(mindist_cluster, maxorder, symmetry->natmin);\n    memory->allocate(pairs, maxorder);\n\n    generate_coordinate_of_periodic_images(nat, system->xcoord, is_periodic, x_image, exist_image);\n    get_pairs_of_minimum_distance(nat, x_image, exist_image, distall, mindist_pairs);\n    print_neighborlist(mindist_pairs);\n    search_interactions(interaction_pair, pairs);\n    //    calc_mindist_clusters2(interaction_pair, mindist_pairs, distall, exist_image, mindist_cluster);\n    calc_mindist_clusters(interaction_pair, mindist_pairs, distall, exist_image, mindist_cluster);\n    generate_pairs(pairs, mindist_cluster);\n\n    /*\n    for (int order = 0; order < maxorder; ++order) {\n    for (i = 0; i < symmetry->natmin; ++i) {\n    for (std::set<MinimumDistanceCluster>::const_iterator it = mindist_cluster[order][i].begin();\n    it != mindist_cluster[order][i].end(); ++it) {\n    std::cout << \" order = \" << std::setw(5) << order;\n    std::cout << \" iat = \" << std::setw(5) << i << \" : \";\n    for (j = 0; j < (*it).atom.size(); ++j) {\n    std::cout << std::setw(5) << (*it).atom[j];\n    }\n    std::cout << std::endl;\n    for (j = 0; j < (*it).cell.size(); ++j) {\n    for (k = 0; k < (*it).cell[j].size(); ++k) {\n    std::cout << std::setw(5) << (*it).cell[j][k];\n    }\n    std::cout << std::endl;\n    }\n    std::cout << std::endl;\n    }\n    }\n    }\n\n\n    for (int order = 0; order < maxorder; ++order) {\n    std::cout << \"order = \" << order << \" pairs_size = \" << pairs[order].size() << std::endl;\n    for (std::set<IntList>::const_iterator it = pairs[order].begin(); it != pairs[order].end(); ++it) {\n    for (i = 0; i < (*it).iarray.size(); ++i) {\n    std::cout << std::setw(5) << (*it).iarray[i];\n    }\n    std::cout << std::endl;\n    }\n    }\n    */\n\n\n    timer->print_elapsed();\n    std::cout << \" --------------------------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n}\n\nvoid Interaction::generate_pairs(std::set<IntList> *pair_out, std::set<MinimumDistanceCluster> **mindist_cluster)\n{\n    int i, j;\n    int iat;\n    int order;\n    int natmin = symmetry->natmin;\n    int nat = system->nat;\n\n    int *pair_tmp;\n\n    for (order = 0; order < maxorder; ++order) {\n\n        pair_out[order].clear();\n\n        if (order + 2 > nbody_include[order]) {\n            std::cout << \"  For \" << std::setw(8) << interaction->str_order[order] << \", \";\n            std::cout << \"interactions related to more than\" << std::setw(2) << nbody_include[order];\n            std::cout << \" atoms will be neglected.\" << std::endl;\n        }\n\n        memory->allocate(pair_tmp, order + 2);\n\n        for (i = 0; i < natmin; ++i) {\n\n            iat = symmetry->map_p2s[i][0];\n\n            for (std::set<MinimumDistanceCluster>::const_iterator it = mindist_cluster[order][i].begin();\n                it != mindist_cluster[order][i].end(); ++it) {\n\n                    pair_tmp[0] = iat;\n                    for (j = 0; j < order + 1; ++j) {\n                        pair_tmp[j+1] = (*it).atom[j];\n                    }\n\n                    insort(order+2, pair_tmp);\n\n                    // Ignore many-body case \n                    if (nbody(order + 2, pair_tmp) > nbody_include[order]) continue;\n                    pair_out[order].insert(IntList(order + 2, pair_tmp));\n            }\n        }\n        memory->deallocate(pair_tmp);\n    }\n}\n\nvoid Interaction::generate_coordinate_of_periodic_images(const unsigned int nat, double **xf_in, \n                                                         const int periodic_flag[3], double ***xc_out, \n                                                         int *is_allowed)\n{\n    //\n    // Generate Cartesian coordinates of atoms in the neighboring 27 supercells\n    // \n\n    unsigned int i, j;\n    int ia, ja, ka;\n    int icell;\n\n    icell = 0;\n    for (i = 0; i < nat; ++i) {\n        for (j = 0; j < 3; ++j) {\n            xc_out[0][i][j] = xf_in[i][j];\n        }\n    }\n    // Convert to Cartesian coordinate\n    system->frac2cart(xc_out[0]);\n\n    for (ia = -1; ia <= 1; ++ia) {\n        for (ja = -1; ja <= 1; ++ja) {\n            for (ka = -1; ka <= 1; ++ka) {\n\n                if (ia == 0 && ja == 0 && ka == 0) continue;\n\n                ++icell;\n                for (i = 0; i < nat; ++i) {\n                    xc_out[icell][i][0] = xf_in[i][0] + static_cast<double>(ia);\n                    xc_out[icell][i][1] = xf_in[i][1] + static_cast<double>(ja);\n                    xc_out[icell][i][2] = xf_in[i][2] + static_cast<double>(ka);\n                }\n                // Convert to Cartesian coordinate\n                system->frac2cart(xc_out[icell]);\n            }\n        }\n    }\n\n    icell = 0;\n    is_allowed[0] = 1;\n\n    for (ia = -1; ia <= 1; ++ia) {\n        for (ja = -1; ja <= 1; ++ja) {\n            for (ka = -1; ka <= 1; ++ka) {\n\n                ++icell;\n\n                // When periodic flag is zero along an axis, \n                // periodic images along that axis cannot be considered.\n                if (((std::abs(ia) == 1) && (periodic_flag[0] == 0)) || \n                    ((std::abs(ja) == 1) && (periodic_flag[1] == 0)) || \n                    ((std::abs(ka) == 1) && (periodic_flag[2] == 0)) ) {\n\n                        is_allowed[icell] = 0;\n\n                } else {\n\n                    is_allowed[icell] = 1;\n                }\n            }\n        }\n    }\n\n}\n\ndouble Interaction::distance(double *x1, double *x2)\n{\n    double dist;    \n    dist = std::pow(x1[0] - x2[0], 2) + std::pow(x1[1] - x2[1], 2) + std::pow(x1[2] - x2[2], 2);\n    dist = std::sqrt(dist);\n\n    return dist;\n}\n\nvoid Interaction::get_pairs_of_minimum_distance(int nat, double ***xc_in, int *exist, std::vector<DistInfo> **distall,\n                                                std::vector<DistInfo> **mindist_pairs)\n{\n    int icell = 0;\n    int i, j, k;\n    double dist_tmp;\n    double vec[3];\n\n\n    for (i = 0; i < nat; ++i) {\n        for (j = 0; j < nat; ++j) {\n\n            distall[i][j].clear();\n\n            for (icell = 0; icell < nneib; ++icell) {\n\n                if (exist[icell]) {\n\n                    dist_tmp = distance(xc_in[0][i], xc_in[icell][j]);\n\n                    for (k = 0; k < 3; ++k) vec[k] = xc_in[icell][j][k] - xc_in[0][i][k];\n\n                    distall[i][j].push_back(DistInfo(icell, dist_tmp, vec));\n                }\n            }\n            std::sort(distall[i][j].begin(), distall[i][j].end());\n        }\n    }\n\n    // Construct pairs of minimum distance.\n\n    double dist_min;\n    for (i = 0; i < nat; ++i) {\n        for (j = 0; j < nat; ++j) {\n            mindist_pairs[i][j].clear();\n\n            dist_min = distall[i][j][0].dist;\n            for (std::vector<DistInfo>::const_iterator it = distall[i][j].begin(); it != distall[i][j].end(); ++it) {\n                if (std::abs((*it).dist - dist_min) < eps8) {\n                    mindist_pairs[i][j].push_back(DistInfo(*it));\n                }\n            }\n        }\n\n        /*\n        for (j = 0; j < nat; ++j) {\n        std::cout << \"Mindist : \" << std::setw(5) << i + 1 << \" <--> \" << std::setw(5) << j + 1 << std::endl;\n        for (k = 0; k < mindist_pairs[i][j].size(); ++k) {\n        std::cout << \" cell_j = \" << std::setw(5) << mindist_pairs[i][j][k].cell;\n        std::cout << \" dist = \" << std::setw(5) << mindist_pairs[i][j][k].dist;\n        std::cout << std::endl;\n        }\n        std::cout << std::endl;\n        }\n        */\n    }\n}\n\nvoid Interaction::print_neighborlist(std::vector<DistInfo> **mindist)\n{\n    int i, j, k;\n    int iat;\n    int nat = system->nat;\n    int icount;\n\n    double dist_tmp;\n    std::vector<DistList> *neighborlist;\n\n    memory->allocate(neighborlist, symmetry->natmin);\n\n    for (i = 0; i < symmetry->natmin; ++i) {\n        neighborlist[i].clear();\n\n        iat = symmetry->map_p2s[i][0];\n\n        for (j = 0; j < nat; ++j) {\n            neighborlist[i].push_back(DistList(j, mindist[iat][j][0].dist));\n        }\n        std::sort(neighborlist[i].begin(), neighborlist[i].end());\n    }\n\n    std::cout << std::endl;\n    std::cout << \"  List of neighboring atoms below.\" << std::endl;\n    std::cout << \"  Format [N th-nearest shell, distance in Bohr (Number of atoms on the shell)]\" << std::endl << std::endl;\n\n    int nthnearest;\n    std::vector<int> atomlist;\n\n    for (i = 0; i < symmetry->natmin; ++i) {\n\n        nthnearest = 0;\n        atomlist.clear();\n\n        iat = symmetry->map_p2s[i][0];\n        std::cout << std::setw(5) << iat + 1 << \" (\" << std::setw(3) << system->kdname[system->kd[iat] - 1] << \"): \";\n\n        dist_tmp = 0.0;\n\n        for (j = 0; j < nat; ++j) {\n\n            if (neighborlist[i][j].dist < eps8) continue; // distance is zero\n\n            if (std::abs(neighborlist[i][j].dist - dist_tmp) > eps6) {\n\n                if (atomlist.size() > 0) {\n                    nthnearest += 1;\n\n                    if (nthnearest > 1) std::cout << std::setw(13) << \" \";\n\n                    std::cout << std::setw(3) << nthnearest << std::setw(10) << dist_tmp \n                        << \" (\" << std::setw(3) << atomlist.size() << \") -\";\n\n                    icount = 0;\n                    for (k = 0; k < atomlist.size(); ++k) {\n\n                        if (icount % 4 == 0 && icount > 0) {\n                            std::cout << std::endl;\n                            std::cout << std::setw(34) << \" \";\n                        }\n                        ++icount;\n\n                        std::cout << std::setw(4) << atomlist[k] + 1; \n                        std::cout <<  \"(\" << std::setw(3) << system->kdname[system->kd[atomlist[k]] - 1] << \")\";\n\n                    }\n                    std::cout << std::endl;\n                }\n\n\n                dist_tmp = neighborlist[i][j].dist;\n                atomlist.clear();\n                atomlist.push_back(neighborlist[i][j].atom);\n            } else {\n                atomlist.push_back(neighborlist[i][j].atom);\n            }\n        }\n        if (atomlist.size() > 0) {\n            nthnearest += 1;\n\n            if (nthnearest > 1) std::cout << std::setw(13) << \" \";\n\n            std::cout << std::setw(3) << nthnearest << std::setw(10) << dist_tmp \n                << \" (\" << std::setw(3) << atomlist.size() << \") -\";\n\n            icount = 0;\n            for (k = 0; k < atomlist.size(); ++k) {\n\n                if (icount % 4 == 0 && icount > 0) {\n                    std::cout << std::endl;\n                    std::cout << std::setw(34) << \" \";\n                }\n                ++icount;\n\n                std::cout << std::setw(4) << atomlist[k] + 1; \n                std::cout <<  \"(\" << std::setw(3) << system->kdname[system->kd[atomlist[k]] - 1] << \")\";\n\n            }\n            std::cout << std::endl;\n        }\n        std::cout << std::endl;\n    }\n    atomlist.clear();\n    memory->deallocate(neighborlist);\n}\n\nvoid Interaction::search_interactions(std::vector<int> **interaction_list_out, std::set<IntList> *pair_out)\n{\n    int i;\n    int order;\n    int natmin = symmetry->natmin;\n    int iat, jat;\n    int nat = system->nat;\n    int ikd, jkd;\n\n    double cutoff_tmp;\n    std::set<IntList> *interacting_atom_pairs;\n    std::vector<int> intlist;\n\n    memory->allocate(interacting_atom_pairs, maxorder);\n\n    for (order = 0; order < maxorder; ++order) {\n        for (i = 0; i < natmin; ++i) {\n            interaction_list_out[order][i].clear();\n\n            iat = symmetry->map_p2s[i][0];\n            ikd = system->kd[iat] - 1;\n\n            for (jat = 0; jat < nat; ++jat) {\n\n                jkd = system->kd[jat] - 1;\n\n                cutoff_tmp = rcs[order][ikd][jkd];\n\n                if (cutoff_tmp < 0.0) {\n\n                    interaction_list_out[order][i].push_back(jat);\n\n                } else {\n\n                    if (mindist_pairs[iat][jat][0].dist <= cutoff_tmp) {\n                        interaction_list_out[order][i].push_back(jat);\n                    }\n                }\n            }            \n        }\n    }\n\n    intlist.clear();\n    std::cout << std::endl;\n    std::cout << \"  List of interacting atom pairs considered for each order:\" << std::endl;\n\n    for (order = 0; order < maxorder; ++order) {\n\n        interacting_atom_pairs[order].clear();\n\n        std::cout << std::endl << \"   ***\" << str_order[order] << \"***\" << std::endl;\n\n        for (i = 0; i < natmin; ++i) {\n\n            if (interaction_list_out[order][i].size() == 0) {\n                std::cout << \"   No interacting atoms! Skipped.\" << std::endl;\n                continue; // no interaction\n            }\n\n            iat = symmetry->map_p2s[i][0];\n\n            intlist.clear();\n            for (std::vector<int>::const_iterator it = interaction_list_out[order][i].begin(); \n                it != interaction_list_out[order][i].end(); ++it) {\n                    intlist.push_back((*it));\n            }\n            std::sort(intlist.begin(), intlist.end()); // Necessarily to sort here\n\n            // write atoms inside the cutoff radius\n            int id = 0;\n            std::cout << \"    Atom \" << std::setw(5) << iat + 1\n                << \"(\" << std::setw(3) << system->kdname[system->kd[iat]-1] << \")\" << \" interacts with atoms ... \" << std::endl;\n\n            for (int id = 0; id < intlist.size(); ++id) {\n                if (id%6 == 0) {\n                    if (id == 0) {\n                        std::cout << \"   \";\n                    } else {\n                        std::cout << std::endl;\n                        std::cout << \"   \";\n                    }\n                }\n                std::cout << std::setw(5) << intlist[id] + 1 << \"(\" \n                    << std::setw(3) << system->kdname[system->kd[intlist[id]]-1] << \")\";\n            }\n\n            std::cout << std::endl << std::endl;\n            std::cout << \"    Number of total interaction pairs = \" \n                << interaction_list_out[order][i].size() << std::endl << std::endl;\n\n            int *intarr;        \n            memory->allocate(intarr, order + 2);\n\n            if (intlist.size() > 0) {\n                if (order == 0) {\n                    for (unsigned int ielem = 0; ielem < intlist.size(); ++ielem) {\n                        intarr[0] = iat;\n                        intarr[1] = intlist[ielem];\n                        insort(2, intarr);\n\n                        interacting_atom_pairs[0].insert(IntList(2, intarr));\n                    }\n                } else if (order > 0) {\n                    CombinationWithRepetition<int> g(intlist.begin(), intlist.end(), order + 1);\n                    do {\n                        std::vector<int> data = g.now();\n                        intarr[0] = iat;\n                        intarr[1] = data[0];\n                        for (unsigned int isize = 1; isize < data.size() ; ++isize) {\n                            intarr[isize + 1] = data[isize];\n                        }\n                        if (!is_incutoff(order+2, intarr, order)) continue;\n\n                        insort(order+2, intarr);\n                        interacting_atom_pairs[order].insert(IntList(order + 2, intarr));\n\n                    } while(g.next());\n                }\n            }\n            intlist.clear();\n            memory->deallocate(intarr);\n        }\n    }\n\n    std::cout << std::endl;\n\n    /*\n    int *pair_tmp;\n\n    for (order = 0; order < maxorder; ++order) {\n\n    pair_out[order].clear();\n\n    if (order + 2 > nbody_include[order]) {\n    std::cout << \"  For \" << std::setw(8) << interaction->str_order[order] << \", \";\n    std::cout << \"interactions related to more than\" << std::setw(2) << nbody_include[order];\n    std::cout << \" atoms will be neglected.\" << std::endl;\n    }\n\n    memory->allocate(pair_tmp, order + 2);\n\n    for (std::set<IntList>::const_iterator it = interacting_atom_pairs[order].begin(); \n    it != interacting_atom_pairs[order].end(); ++it) {\n    for (j = 0; j < order + 2; ++j) {\n    pair_tmp[j] = (*it).iarray[j];\n    }\n\n    // Ignore many-body case \n    if (nbody(order + 2, pair_tmp) > nbody_include[order]) continue;\n\n    pair_out[order].insert(IntList(order + 2, pair_tmp));\n    }\n    memory->deallocate(pair_tmp);\n    }\n    */\n\n    memory->deallocate(interacting_atom_pairs);\n}\n\nbool Interaction::is_incutoff(const int n, int *atomnumlist, const int order) \n{\n    int i, j;\n    int iat, jat;\n    int ikd, jkd;\n    int ncheck = n - 1;\n    double cutoff_tmp;\n    std::vector<DistInfo>::const_iterator it, it2;\n\n    iat = atomnumlist[0];\n    ikd = system->kd[iat] - 1;\n\n    for (i = 0; i < n; ++i) {\n        iat = atomnumlist[i];\n        ikd = system->kd[iat] - 1;\n\n        for (j = i + 1; j < n; ++j) {\n            jat = atomnumlist[j];\n            jkd = system->kd[jat] - 1;\n\n            cutoff_tmp = rcs[order][ikd][jkd];\n\n            if (cutoff_tmp >= 0.0 &&\n                (mindist_pairs[iat][jat][0].dist > cutoff_tmp)) return false;\n\n        }\n    }\n    return true;\n\n    /*\n    for (i = 0; i < ncheck; ++i) {\n\n    jat = atomnumlist[i + 1];\n    jkd = system->kd[jat] - 1;\n\n    if (rcs[order][ikd][jkd] >= 0.0 && \n    (mindist_pairs[iat][jat][0].dist > rcs[order][ikd][jkd])) return false;\n\n    for (j = i + 1; j < ncheck; ++j) {\n\n    kat = atomnumlist[j + 1];\n    kkd = system->kd[kat] - 1;\n\n    if (rcs[order][ikd][kkd] >= 0.0 && \n    (mindist_pairs[iat][kat][0].dist > rcs[order][ikd][kkd])) return false;\n\n    cutoff_tmp = rcs[order][jkd][kkd];\n\n    if (cutoff_tmp >= 0.0) {\n\n    in_cutoff_tmp = false;\n\n    for (it = mindist_pairs[iat][jat].begin(); it != mindist_pairs[iat][jat].end(); ++it) {\n    for (it2 = mindist_pairs[iat][kat].begin(); it2 != mindist_pairs[iat][kat].end(); ++it2) {\n    dist_tmp = distance(x_image[(*it).cell][jat], x_image[(*it2).cell][kat]);\n\n    if (n == 4) {\n    if (iat == 0 && jat == 4 && kat == 20) {\n    std::cout << \"DEBUG :\" << std::setw(5) << (*it).cell;\n    std::cout << std::setw(5) << (*it2).cell << std::setw(15) << dist_tmp << std::endl;\n    }\n    }\n\n    if (dist_tmp <= cutoff_tmp) {\n    in_cutoff_tmp = true;\n    }\n    }\n    }\n    if (!in_cutoff_tmp) return false;\n    }\n    }\n    }\n    return true;\n    */\n\n\n}\n\nbool Interaction::is_incutoff2(const int n, int *atomnumlist, const int order) \n{\n    int i, j;\n    int iat, jat, kat;\n    int ikd, jkd, kkd;\n    int ncheck = n - 1;\n    //    int order = n - 2;   \n    bool in_cutoff_tmp;\n    double cutoff_tmp;\n    double dist_tmp;\n    std::vector<DistInfo>::const_iterator it, it2;\n\n    iat = atomnumlist[0];\n    ikd = system->kd[iat] - 1;\n\n    for (i = 0; i < ncheck; ++i) {\n\n        jat = atomnumlist[i + 1];\n        jkd = system->kd[jat] - 1;\n\n        if (rcs[order][ikd][jkd] >= 0.0 && \n            (mindist_pairs[iat][jat][0].dist > rcs[order][ikd][jkd])) return false;\n\n        for (j = i + 1; j < ncheck; ++j) {\n\n            kat = atomnumlist[j + 1];\n            kkd = system->kd[kat] - 1;\n\n            if (rcs[order][ikd][kkd] >= 0.0 && \n                (mindist_pairs[iat][kat][0].dist > rcs[order][ikd][kkd])) return false;\n\n            cutoff_tmp = rcs[order][jkd][kkd];\n\n            if (cutoff_tmp >= 0.0) {\n\n                in_cutoff_tmp = false;\n\n                for (it = mindist_pairs[iat][jat].begin(); it != mindist_pairs[iat][jat].end(); ++it) {\n                    for (it2 = mindist_pairs[iat][kat].begin(); it2 != mindist_pairs[iat][kat].end(); ++it2) {\n                        dist_tmp = distance(x_image[(*it).cell][jat], x_image[(*it2).cell][kat]);\n\n                        if (dist_tmp <= cutoff_tmp) {\n                            in_cutoff_tmp = true;\n                        }\n                    }\n                }\n                if (!in_cutoff_tmp) return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid Interaction::set_ordername()\n{\n    std::string strnum;\n\n    str_order[0] = \"HARMONIC\";\n\n    for (int i = 1;  i < maxorder; ++i) {\n        strnum = boost::lexical_cast<std::string>(i+2);\n        str_order[i] = \"ANHARM\" + strnum;\n    }\n}\n\nint Interaction::nbody(const int n, const int *arr)\n{\n    std::vector<int> v;\n    v.clear();\n    int ret;\n\n    for (unsigned int i = 0; i < n; ++i) {\n        v.push_back(arr[i]);\n    }\n    std::sort(v.begin(), v.end());\n    v.erase(std::unique(v.begin(), v.end()), v.end());\n\n    ret = v.size();\n    v.clear();\n\n    return ret;\n}\n\n\nvoid Interaction::calc_mindist_clusters(std::vector<int> **interaction_pair_in, std::vector<DistInfo> **mindist_pair_in, \n                                        std::vector<DistInfo> **distance_image, int *exist, \n                                        std::set<MinimumDistanceCluster> **mindist_cluster_out)\n{\n    std::vector<MinDistList> distance_list;\n\n    int natmin = symmetry->natmin;\n    int i, j, k;\n    int iat, jat;\n    int order;\n    int ii;\n    int ikd, jkd;\n    //    int *intpair_tmp;\n    std::vector<int> intlist;\n\n    double dist_tmp, rc_tmp;\n    double distmax;\n\n    bool isok;\n\n    std::vector<int> cell_vector;\n    std::vector<double> dist_vector;\n    std::vector<std::vector<int> > pairs_icell, comb_cell, comb_cell_min;\n    std::vector<std::vector<int> > comb_cell_atom_center;\n    std::vector<int> accum_tmp;\n    std::vector<int> atom_tmp, cell_tmp;\n    std::vector<int> intpair_uniq, cellpair;\n    std::vector<int> group_atom;\n\n    int icount;\n\n    //    memory->allocate(intpair_tmp, maxorder + 2);\n\n    for (order = 0; order < maxorder; ++order) {\n        for (i = 0; i < symmetry->natmin; ++i) {\n\n            mindist_cluster_out[order][i].clear();\n\n            iat = symmetry->map_p2s[i][0];\n            ikd = system->kd[iat] - 1;\n\n            // List of 2-body interaction pairs\n            intlist.clear();\n            for (std::vector<int>::const_iterator it  = interaction_pair_in[order][i].begin(); \n                it != interaction_pair_in[order][i].end(); ++it) {\n                    intlist.push_back((*it));\n            }\n            std::sort(intlist.begin(), intlist.end()); // Need to sort here\n\n            if (intlist.size() > 0) {\n                if (order == 0){\n                    for (unsigned int ielem = 0; ielem < intlist.size(); ++ielem) {\n\n                        comb_cell_min.clear();\n                        atom_tmp.clear();\n\n                        jat = intlist[ielem];\n                        atom_tmp.push_back(jat);\n\n                        for (j = 0; j < mindist_pair_in[iat][jat].size(); ++j) {\n                            cell_tmp.clear();\n                            cell_tmp.push_back(mindist_pair_in[iat][jat][j].cell);\n                            comb_cell_min.push_back(cell_tmp);\n                        }\n                        distmax = mindist_pair_in[iat][jat][0].dist;\n                        mindist_cluster_out[order][i].insert(MinimumDistanceCluster(atom_tmp, comb_cell_min, distmax));\n                    }\n                } else if (order > 0) {\n                    CombinationWithRepetition<int> g(intlist.begin(), intlist.end(), order + 1);\n                    do {\n                        std::vector<int> data = g.now();\n\n                        // Uniq the list of atoms in data like as follows:\n                        // cubic   term : (i, i) --> (i) x 2\n                        // quartic term : (i, i, j) --> (i, j) x (2, 1)\n                        intpair_uniq.clear();\n                        group_atom.clear();\n                        icount = 1;\n\n                        for (j = 0; j < order; ++j) {\n                            if (data[j] == data[j+1]) {\n                                ++icount;\n                            } else {\n                                group_atom.push_back(icount);\n                                intpair_uniq.push_back(data[j]);\n                                icount = 1;\n                            }\n                        }\n                        group_atom.push_back(icount);\n                        intpair_uniq.push_back(data[order]);\n\n                        pairs_icell.clear();\n                        for (j = 0; j < intpair_uniq.size(); ++j) {\n                            jat = intpair_uniq[j];\n                            jkd = system->kd[jat] - 1;\n\n                            rc_tmp = rcs[order][ikd][jkd];\n                            cell_vector.clear();\n\n                            // Loop over the cell images of atom 'jat' and add to the list \n                            // as a candidate for the minimum distance cluster\n                            for (std::vector<DistInfo>::const_iterator it = distance_image[iat][jat].begin();\n                                it != distance_image[iat][jat].end(); ++it) {\n                                    if (exist[(*it).cell]) {\n                                        if (rc_tmp < 0.0 || (*it).dist <= rc_tmp) {\n                                            cell_vector.push_back((*it).cell);\n                                        }\n                                    }\n                            }\n                            pairs_icell.push_back(cell_vector);\n                        }\n\n                        accum_tmp.clear();\n                        comb_cell.clear();\n                        cell_combination(pairs_icell, 0, accum_tmp, comb_cell);\n\n                        distance_list.clear();\n                        for (j = 0; j < comb_cell.size(); ++j) {\n\n                            cellpair.clear();\n\n                            for (k = 0; k < group_atom.size(); ++k) {\n                                for (ii = 0; ii < group_atom[k]; ++ii) {\n                                    cellpair.push_back(comb_cell[j][k]);\n                                }\n                            }\n\n                            dist_vector.clear();\n\n                            for (k = 0; k < cellpair.size(); ++k) {\n                                dist_tmp = distance(x_image[cellpair[k]][data[k]], x_image[0][iat]);\n                                //   if (dist_tmp > eps15) dist_vector.push_back(dist_tmp);\n                                dist_vector.push_back(dist_tmp);\n                            }\n\n                            // Flag to check if the distance is smaller than the cutoff radius\n                            isok = true;\n\n                            for (k = 0; k < cellpair.size(); ++k) {\n                                for (ii = k + 1; ii < cellpair.size(); ++ii) {\n                                    dist_tmp = distance(x_image[cellpair[k]][data[k]], x_image[cellpair[ii]][data[ii]]);\n                                    rc_tmp = rcs[order][system->kd[data[k]]-1][system->kd[data[ii]]-1];\n                                    if (rc_tmp >= 0.0 && dist_tmp > rc_tmp) {\n                                        isok = false;\n                                    }\n                                    //                                    if (dist_tmp > eps15) dist_vector.push_back(dist_tmp);\n                                    dist_vector.push_back(dist_tmp);\n                                }\n                            }\n                            if (isok) {\n                                // This combination is a candidate of the minimum distance cluster\n                                distance_list.push_back(MinDistList(cellpair, dist_vector));\n                            }\n                        } // close loop over the mirror image combination\n\n                        if (distance_list.size() > 0) {\n                            // If the distance_list is not empty, there is a set of mirror images\n                            // that satisfies the condition of the interaction.\n\n                            pairs_icell.clear();\n                            for (j = 0; j < intpair_uniq.size(); ++j) {\n                                jat = intpair_uniq[j];\n                                cell_vector.clear();\n\n                                for (ii = 0; ii < mindist_pair_in[iat][jat].size(); ++ii) {\n                                    cell_vector.push_back(mindist_pair_in[iat][jat][ii].cell);\n                                }\n                                pairs_icell.push_back(cell_vector);\n                            }\n\n                            accum_tmp.clear();\n                            comb_cell.clear();\n                            comb_cell_atom_center.clear();\n                            cell_combination(pairs_icell, 0, accum_tmp, comb_cell);\n\n                            for (j = 0; j < comb_cell.size(); ++j) {\n                                cellpair.clear();\n                                for (k = 0; k < group_atom.size(); ++k) {\n                                    for (ii = 0; ii < group_atom[k]; ++ii) {\n                                        cellpair.push_back(comb_cell[j][k]);\n                                    }\n                                }\n                                comb_cell_atom_center.push_back(cellpair);\n                            }\n\n                            std::sort(distance_list.begin(), distance_list.end(), MinDistList::compare_max_distance);\n                            distmax = *std::max_element(distance_list[0].dist.begin(), distance_list[0].dist.end());\n                            mindist_cluster_out[order][i].insert(MinimumDistanceCluster(data, comb_cell_atom_center,distmax));\n                            /*\n                            std::sort(distance_list.begin(), distance_list.end(), MinDistList::compare_sum_distance);\n                            comb_cell_min.clear();\n\n                            sum_dist_min = 0.0;\n                            for (j = 0; j < distance_list[0].dist.size(); ++j) {\n                            sum_dist_min += distance_list[0].dist[j];\n                            }\n\n                            for (j = 0; j < distance_list.size(); ++j) {\n                            sum_dist = 0.0;\n\n                            for (k = 0; k < distance_list[j].dist.size(); ++k) {\n                            sum_dist += distance_list[j].dist[k];\n                            }\n\n                            // In the following, only pairs having minimum sum of distances\n                            // are stored. However, we found that this treatment didn't\n                            // return a reliable value of phonon linewidth.\n                            if (std::abs(sum_dist - sum_dist_min) < eps6) {\n                            comb_cell_min.push_back(distance_list[j].cell);\n                            } else {\n                            break;\n                            }\n                            // Therefore, we consider all duplicate pairs\n                            //comb_cell_min.push_back(distance_list[j].cell);\n                            }\n                            //                            mindist_cluster_out[order][i].insert(MinimumDistanceCluster(data, comb_cell_min));\n                            */\n\n                        }\n\n                    } while(g.next());\n                }\n            }\n            intlist.clear();\n        }\n    }\n\n    //    memory->deallocate(intpair_tmp);\n}\n\nvoid Interaction::calc_mindist_clusters2(std::vector<int> **interaction_pair_in, std::vector<DistInfo> **mindist_pair_in,\n                                         std::vector<DistInfo> **distance_image, int *exist, \n                                         std::set<MinimumDistanceCluster> **mindist_cluster_out)\n{\n    std::vector<MinDistList> distance_list;\n\n    int natmin = symmetry->natmin;\n    int i, j, k;\n    int iat, jat;\n    int ikd, jkd;\n    int order;\n    int ii;\n    std::vector<int> intlist;\n\n    double rc_tmp;\n    double dist_tmp;\n    double sum_dist_min, sum_dist;\n    double dist_max;\n\n    std::vector<int> cell_vector;\n    std::vector<double> dist_vector;\n    std::vector<std::vector<int> > pairs_icell, comb_cell, comb_cell_min;\n    std::vector<int> accum_tmp;\n    std::vector<int> atom_tmp, cell_tmp;\n    std::vector<int> intpair_uniq, cellpair;\n    std::vector<int> group_atom;\n\n    int icount;\n    bool isok;\n\n    for (order = 0; order < maxorder; ++order) {\n        for (i = 0; i < symmetry->natmin; ++i) {\n\n            mindist_cluster_out[order][i].clear();\n            iat = symmetry->map_p2s[i][0];\n            ikd = system->kd[iat] - 1;\n\n            intlist.clear();\n            for (std::vector<int>::const_iterator it  = interaction_pair_in[order][i].begin(); \n                it != interaction_pair_in[order][i].end(); ++it) {\n                    intlist.push_back((*it));\n            }\n            std::sort(intlist.begin(), intlist.end()); // Need to sort here\n\n            if (intlist.size() > 0) {\n\n                if (order == 0){\n                    // For harmonic case, the minimum distance cluster is equivalen to the \n                    // minimum distance pairs.\n                    for (unsigned int ielem = 0; ielem < intlist.size(); ++ielem) {\n\n                        comb_cell_min.clear();\n                        atom_tmp.clear();\n\n                        jat = intlist[ielem];\n                        atom_tmp.push_back(jat);\n\n                        for (j = 0; j < mindist_pair_in[iat][jat].size(); ++j) {\n                            cell_tmp.clear();\n                            cell_tmp.push_back(mindist_pair_in[iat][jat][j].cell);\n                            comb_cell_min.push_back(cell_tmp);\n                        }\n                        dist_max = mindist_pair_in[iat][jat][0].dist;\n                        mindist_cluster_out[order][i].insert(MinimumDistanceCluster(atom_tmp, comb_cell_min));\n                    }\n\n                } else if (order > 0) {\n\n                    // For anharmonic cases, the minimum distance cluster is the set of\n                    // cell images having the smallest value for the sum of distance.\n\n                    // Generate all possible combination of atoms from intlist\n                    CombinationWithRepetition<int> g(intlist.begin(), intlist.end(), order + 1);\n                    do {\n                        std::vector<int> data = g.now();\n\n                        // Uniq the list of atoms in data like as follows:\n                        // cubic   term : (i, i) --> (i) x 2\n                        // quartic term : (i, i, j) --> (i, j) x (2, 1)\n                        intpair_uniq.clear();\n                        group_atom.clear();\n                        icount = 1;\n\n                        for (j = 0; j < order; ++j) {\n                            if (data[j] == data[j+1]) {\n                                ++icount;\n                            } else {\n                                group_atom.push_back(icount);\n                                intpair_uniq.push_back(data[j]);\n                                icount = 1;\n                            }\n                        }\n                        group_atom.push_back(icount);\n                        intpair_uniq.push_back(data[order]);\n\n                        pairs_icell.clear();\n                        for (j = 0; j < intpair_uniq.size(); ++j) {\n                            jat = intpair_uniq[j];\n                            jkd = system->kd[jat] - 1;\n\n                            rc_tmp = rcs[order][ikd][jkd];\n                            cell_vector.clear();\n\n                            // Loop over the cell images of atom 'jat' and add to the list \n                            // as a candidate for the minimum distance cluster\n                            for (std::vector<DistInfo>::const_iterator it = distance_image[iat][jat].begin();\n                                it != distance_image[iat][jat].end(); ++it) {\n                                    if (exist[(*it).cell]) {\n                                        if (rc_tmp < 0.0 || (*it).dist <= rc_tmp) {\n                                            cell_vector.push_back((*it).cell);\n                                            // std::cout << \" iat = \" << std::setw(5) << iat;\n                                            // std::cout << \" jat = \" << std::setw(5) << jat;\n                                            // std::cout << \" cell = \" << (*it).cell;\n                                            // std::cout << \" dist = \" << (*it).dist;\n                                            // std::cout << \" rc = \" << rc_tmp << std::endl;\n                                        }\n                                    }\n                            }\n                            pairs_icell.push_back(cell_vector);\n                        }\n\n                        // Generate all possible combinations of mirror images\n                        accum_tmp.clear();\n                        comb_cell.clear();\n                        cell_combination(pairs_icell, 0, accum_tmp, comb_cell);\n\n                        distance_list.clear();\n\n                        // Loop over the combination of the mirror images and \n                        // generate the list of atomic distances of all pairs for each combination.\n                        // Add to list only if the distance is smaller than the cutoff radius.\n\n                        for (j = 0; j < comb_cell.size(); ++j) {\n\n                            cellpair.clear();\n\n                            for (k = 0; k < group_atom.size(); ++k) {\n                                for (ii = 0; ii < group_atom[k]; ++ii) {\n                                    cellpair.push_back(comb_cell[j][k]);\n                                }\n                            }\n\n                            dist_vector.clear();\n\n                            for (k = 0; k < cellpair.size(); ++k) {\n                                dist_tmp = distance(x_image[cellpair[k]][data[k]], x_image[0][iat]);\n                                if (dist_tmp > eps15) dist_vector.push_back(dist_tmp);\n                            }\n\n                            // Flag to check if the distance is smaller than the cutoff radius\n                            isok = true;\n\n                            for (k = 0; k < cellpair.size(); ++k) {\n                                for (ii = k + 1; ii < cellpair.size(); ++ii) {\n                                    dist_tmp = distance(x_image[cellpair[k]][data[k]], x_image[cellpair[ii]][data[ii]]);\n                                    rc_tmp = rcs[order][system->kd[data[k]]-1][system->kd[data[ii]]-1];\n                                    if (rc_tmp >= 0.0 && dist_tmp > rc_tmp) {\n                                        isok = false;\n                                        //                                            break;\n                                    }\n                                    if (dist_tmp > eps15) dist_vector.push_back(dist_tmp);\n                                }\n                            }\n                            if (isok) {\n                                // This combination a candidate for the minimum distance cluster\n                                distance_list.push_back(MinDistList(cellpair, dist_vector));\n                            }\n                        }\n\n                        std::sort(distance_list.begin(), distance_list.end(), MinDistList::compare_sum_distance);\n\n                        comb_cell_min.clear();\n\n                        sum_dist_min = 0.0;\n                        dist_max = 0.0;\n                        for (j = 0; j < distance_list[0].dist.size(); ++j) {\n                            sum_dist_min += distance_list[0].dist[j];\n                            dist_max = std::max<double>(dist_max, distance_list[0].dist[j]);\n                        }\n\n                        for (j = 0; j < distance_list.size(); ++j) {\n                            sum_dist = 0.0;\n\n                            for (k = 0; k < distance_list[j].dist.size(); ++k) {\n                                sum_dist += distance_list[j].dist[k];\n                            }\n\n                            // In the following, only pairs having minimum sum of distances\n                            // are stored. \n                            if (std::abs(sum_dist - sum_dist_min) < eps6) {\n                                comb_cell_min.push_back(distance_list[j].cell);\n                            } else {\n                                break;\n                            }\n                        }\n\n                        if (comb_cell_min.size() > 0) {\n                            mindist_cluster_out[order][i].insert(MinimumDistanceCluster(data, comb_cell_min));\n                        }\n\n                    } while(g.next());\n                }\n            }\n            intlist.clear();\n        }\n    }\n}\n\n\nvoid Interaction::cell_combination(std::vector<std::vector<int> > array, int i, \n                                   std::vector<int> accum, std::vector<std::vector<int> > &comb)\n{\n    if (i == array.size())  {\n        comb.push_back(accum); \n    } else  {\n        std::vector<int> row = array[i];\n        for (int j = 0; j < row.size(); ++j) {\n            std::vector<int> tmp(accum);\n            tmp.push_back(row[j]);\n            cell_combination(array,i+1,tmp, comb);\n        }\n    }\n}\n", "meta": {"hexsha": "1d4e9ef323ea813e27a029e4ce646b4c8eb754be", "size": 43084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "alm/interaction.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/interaction.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/interaction.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": 36.0535564854, "max_line_length": 140, "alphanum_fraction": 0.4415328196, "num_tokens": 10533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.1734978559939649}}
{"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_BITWISE_FUNCTIONS_SIMD_SSE_SSE2_SHLI_HPP_INCLUDED\n#define BOOST_SIMD_BITWISE_FUNCTIONS_SIMD_SSE_SSE2_SHLI_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n#include <boost/simd/bitwise/functions/shli.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/include/functions/simd/bitwise_or.hpp>\n#include <boost/simd/include/constants/int_splat.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/sdk/meta/make_dependent.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::shli_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<type8_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    typedef typename meta::make_dependent<int64_t,A0>::type int_t;\n\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef simd::native<int_t,boost::simd::tag::sse_> gen_type;\n      result_type const\n      Mask1 = bitwise_cast<result_type>( boost::simd::integral_constant< gen_type\n                                                      , 0x00ff00ff00ff00ffll\n                                                      >()\n                                    );\n      result_type const\n      Mask2 = bitwise_cast<result_type>( boost::simd::integral_constant < gen_type\n                                                        , 0xff00ff00ff00ff00ll\n                                                        >()\n                                    );\n      result_type tmp  = b_and(a0, Mask1);\n      result_type tmp1 = _mm_slli_epi16(tmp, int(a1));\n      tmp1 = b_and(tmp1, Mask1);\n      tmp = b_and(a0, Mask2);\n      result_type tmp3 = _mm_slli_epi16(tmp, int(a1));\n      return tmp1 | b_and(tmp3, Mask2);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::shli_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<type32_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef typename dispatch::meta::as_integer<A0,signed>::type sint;\n      sint const that = _mm_slli_epi32(bitwise_cast<sint>(a0), int(a1));\n      return bitwise_cast<A0>(that);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::shli_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<type64_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef typename dispatch::meta::as_integer<A0,signed>::type sint;\n      sint const that = _mm_slli_epi64(bitwise_cast<sint>(a0), int(a1));\n      return bitwise_cast<A0>(that);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::shli_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)(A1)\n                                    , ((simd_<type16_<A0>,boost::simd::tag::sse_>))\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      return _mm_slli_epi16(a0, int(a1));\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "98babc4d201b2082b1c4607bffb80cd0dc6f745b", "size": 4246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/sse/sse2/shli.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/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/sse/sse2/shli.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/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/sse/sse2/shli.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": 41.2233009709, "max_line_length": 83, "alphanum_fraction": 0.4964672633, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17349785249983007}}
{"text": "#if !defined(ARCADIA_BUILD)\n#    include <Common/config.h>\n#endif\n#include <Common/Exception.h>\n#include <base/types.h>\n#include <IO/VarInt.h>\n#include <Compression/CompressionFactory.h>\n#include <Compression/CompressionCodecEncrypted.h>\n#include <Poco/Logger.h>\n#include <base/logger_useful.h>\n#include <Common/ErrorCodes.h>\n\n// This depends on BoringSSL-specific API, notably <openssl/aead.h>.\n#if USE_SSL && USE_INTERNAL_SSL_LIBRARY\n#include <Parsers/ASTLiteral.h>\n#include <openssl/digest.h> // Y_IGNORE\n#include <openssl/err.h>\n#include <boost/algorithm/hex.hpp>\n#include <openssl/aead.h> // Y_IGNORE\n#endif\n\n// Common part for both parts (with SSL and without)\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int OPENSSL_ERROR;\n}\n\nnamespace\n{\n\n/// Get string name for method. Return empty string for undefined Method\nString getMethodName(EncryptionMethod Method)\n{\n    if (Method == AES_128_GCM_SIV)\n    {\n        return \"AES_128_GCM_SIV\";\n    }\n    else if (Method == AES_256_GCM_SIV)\n    {\n        return \"AES_256_GCM_SIV\";\n    }\n    else\n    {\n        return \"\";\n    }\n}\n\n/// Get method code (used for codec, to understand which one we are using)\nuint8_t getMethodCode(EncryptionMethod Method)\n{\n    if (Method == AES_128_GCM_SIV)\n    {\n        return uint8_t(CompressionMethodByte::AES_128_GCM_SIV);\n    }\n    else if (Method == AES_256_GCM_SIV)\n    {\n        return uint8_t(CompressionMethodByte::AES_256_GCM_SIV);\n    }\n    else\n    {\n        throw Exception(\"Wrong encryption Method. Got \" + getMethodName(Method), ErrorCodes::BAD_ARGUMENTS);\n    }\n}\n\n} // end of namespace\n\n} // end of namespace DB\n\n#if USE_SSL && USE_INTERNAL_SSL_LIBRARY\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int ILLEGAL_SYNTAX_FOR_CODEC_TYPE;\n    extern const int LOGICAL_ERROR;\n    extern const int BAD_ARGUMENTS;\n    extern const int INCORRECT_DATA;\n}\n\nnamespace\n{\nconstexpr size_t tag_size        = 16;   /// AES-GCM-SIV always uses a tag of 16 bytes length\nconstexpr size_t key_id_max_size = 8;    /// Max size of varint.\nconstexpr size_t nonce_max_size  = 13;   /// Nonce size and one byte to show if nonce in in text\n\n/// Get encryption/decryption algorithms.\nauto getMethod(EncryptionMethod Method)\n{\n    if (Method == AES_128_GCM_SIV)\n    {\n        return EVP_aead_aes_128_gcm_siv;\n    }\n    else if (Method == AES_256_GCM_SIV)\n    {\n        return EVP_aead_aes_256_gcm_siv;\n    }\n    else\n    {\n        throw Exception(\"Wrong encryption Method. Got \" + getMethodName(Method), ErrorCodes::BAD_ARGUMENTS);\n    }\n}\n\n/// Find out key size for each algorithm\nUInt64 methodKeySize(EncryptionMethod Method)\n{\n    if (Method == AES_128_GCM_SIV)\n    {\n        return 16;\n    }\n    else if (Method == AES_256_GCM_SIV)\n    {\n        return 32;\n    }\n    else\n    {\n        throw Exception(\"Wrong encryption Method. Got \" + getMethodName(Method), ErrorCodes::BAD_ARGUMENTS);\n    }\n}\n\nstd::string lastErrorString()\n{\n    std::array<char, 1024> buffer = {};\n    ERR_error_string_n(ERR_get_error(), buffer.data(), buffer.size());\n    return std::string(buffer.data());\n}\n\n/// Encrypt plaintext with particular algorithm and put result into ciphertext_and_tag.\n/// This function get key and nonce and encrypt text with their help.\n/// If something went wrong (can't init context or can't encrypt data) it throws exception.\n/// It returns length of encrypted text.\nsize_t encrypt(const std::string_view & plaintext, char * ciphertext_and_tag, EncryptionMethod method, const String & key, const String & nonce)\n{\n    /// Init context for encryption, using key.\n    EVP_AEAD_CTX encrypt_ctx;\n    EVP_AEAD_CTX_zero(&encrypt_ctx);\n    const int ok_init = EVP_AEAD_CTX_init(&encrypt_ctx, getMethod(method)(),\n                                            reinterpret_cast<const uint8_t*>(key.data()), key.size(),\n                                            16 /* tag size */, nullptr);\n    if (!ok_init)\n        throw Exception(lastErrorString(), ErrorCodes::OPENSSL_ERROR);\n\n    /// encrypt data using context and given nonce.\n    size_t out_len;\n    const int ok_open = EVP_AEAD_CTX_seal(&encrypt_ctx,\n                                            reinterpret_cast<uint8_t *>(ciphertext_and_tag),\n                                            &out_len, plaintext.size() + 16,\n                                            reinterpret_cast<const uint8_t *>(nonce.data()), nonce.size(),\n                                            reinterpret_cast<const uint8_t *>(plaintext.data()), plaintext.size(),\n                                            nullptr, 0);\n    if (!ok_open)\n        throw Exception(lastErrorString(), ErrorCodes::OPENSSL_ERROR);\n\n    return out_len;\n}\n\n/// Encrypt plaintext with particular algorithm and put result into ciphertext_and_tag.\n/// This function get key and nonce and encrypt text with their help.\n/// If something went wrong (can't init context or can't encrypt data) it throws exception.\n/// It returns length of encrypted text.\nsize_t decrypt(const std::string_view & ciphertext, char * plaintext, EncryptionMethod method, const String & key, const String & nonce)\n{\n    /// Init context for decryption with given key.\n    EVP_AEAD_CTX decrypt_ctx;\n    EVP_AEAD_CTX_zero(&decrypt_ctx);\n\n    const int ok_init = EVP_AEAD_CTX_init(&decrypt_ctx, getMethod(method)(),\n                                          reinterpret_cast<const uint8_t*>(key.data()), key.size(),\n                                          16 /* tag size */, nullptr);\n    if (!ok_init)\n        throw Exception(lastErrorString(), ErrorCodes::OPENSSL_ERROR);\n\n    /// decrypt data using given nonce\n    size_t out_len;\n    const int ok_open = EVP_AEAD_CTX_open(&decrypt_ctx,\n                                          reinterpret_cast<uint8_t *>(plaintext),\n                                          &out_len, ciphertext.size(),\n                                          reinterpret_cast<const uint8_t *>(nonce.data()), nonce.size(),\n                                          reinterpret_cast<const uint8_t *>(ciphertext.data()), ciphertext.size(),\n                                          nullptr, 0);\n    if (!ok_open)\n        throw Exception(lastErrorString(), ErrorCodes::OPENSSL_ERROR);\n\n    return out_len;\n}\n\n/// Register codec in factory\nvoid registerEncryptionCodec(CompressionCodecFactory & factory, EncryptionMethod Method)\n{\n    const auto method_code = getMethodCode(Method); /// Codec need to know its code\n    factory.registerCompressionCodec(getMethodName(Method), method_code, [&, Method](const ASTPtr & arguments) -> CompressionCodecPtr\n    {\n        if (arguments)\n        {\n            if (!arguments->children.empty())\n                throw Exception(\"Codec \" + getMethodName(Method) + \" must not have parameters, given \" +\n                                std::to_string(arguments->children.size()),\n                                ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE);\n        }\n        return std::make_shared<CompressionCodecEncrypted>(Method);\n    });\n}\n\nString unhexKey(const String & hex)\n{\n    try\n    {\n        return boost::algorithm::unhex(hex);\n    }\n    catch (const std::exception &)\n    {\n        throw Exception(ErrorCodes::BAD_ARGUMENTS, \"Cannot read key_hex, check for valid characters [0-9a-fA-F] and length\");\n    }\n}\n\n/// Firstly, write a byte, which shows if the nonce will be put in text (if it was defined in config)\n/// Secondly, write nonce in text (this step depends from first step)\n/// return new position to write\ninline char* writeNonce(const String& nonce, char* dest)\n{\n    /// If nonce consists of nul bytes, it shouldn't be in dest. Zero byte is the only byte that should be written.\n    /// Otherwise, 1 is written and data from nonce is copied\n    if (nonce != String(\"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\", 12))\n    {\n        *dest = 1;\n        ++dest;\n        size_t copied_symbols = nonce.copy(dest, nonce.size());\n        if (copied_symbols != nonce.size())\n            throw Exception(ErrorCodes::INCORRECT_DATA, \"Can't copy nonce into destination. Count of copied symbols {}, need to copy {}\", copied_symbols, nonce.size());\n        dest += copied_symbols;\n        return dest;\n    }\n    else\n    {\n        *dest = 0;\n        return ++dest;\n    }\n}\n\n/// Firstly, read a byte, which shows if the nonce will be put in text (if it was defined in config)\n/// Secondly, read nonce in text (this step depends from first step)\n/// return new position to read\ninline const char* readNonce(String& nonce, const char* source)\n{\n    /// If first is zero byte: move source and set zero-bytes nonce\n    if (!*source)\n    {\n        nonce = {\"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\", 12};\n        return ++source;\n    }\n    /// Move to next byte. Nonce will begin from there\n    ++source;\n\n    /// Otherwise, use data from source in nonce\n    nonce = {source, 12};\n    source += 12;\n    return source;\n}\n\n}\n\nCompressionCodecEncrypted::Configuration & CompressionCodecEncrypted::Configuration::instance()\n{\n    static CompressionCodecEncrypted::Configuration ret;\n    return ret;\n}\n\nvoid CompressionCodecEncrypted::Configuration::loadImpl(\n    const Poco::Util::AbstractConfiguration & config, const String & config_prefix, EncryptionMethod method, std::unique_ptr<Params> & new_params)\n{\n    // if method is not smaller than MAX_ENCRYPTION_METHOD it is incorrect\n    if (method >= MAX_ENCRYPTION_METHOD)\n        throw Exception(\"Wrong argument for loading configurations.\", ErrorCodes::BAD_ARGUMENTS);\n\n    /// Scan all keys in config and add them into storage. If key is in hex, transform it.\n    /// Remember key ID for each key, because it will be used in encryption/decryption\n    Strings config_keys;\n    config.keys(config_prefix, config_keys);\n    for (const std::string & config_key : config_keys)\n    {\n        String key;\n        UInt64 key_id;\n\n        if ((config_key == \"key\") || config_key.starts_with(\"key[\"))\n        {\n            key = config.getString(config_prefix + \".\" + config_key, \"\");\n            key_id = config.getUInt64(config_prefix + \".\" + config_key + \"[@id]\", 0);\n        }\n        else if ((config_key == \"key_hex\") || config_key.starts_with(\"key_hex[\"))\n        {\n            key = unhexKey(config.getString(config_prefix + \".\" + config_key, \"\"));\n            key_id = config.getUInt64(config_prefix + \".\" + config_key + \"[@id]\", 0);\n        }\n        else\n            continue;\n\n        /// For each key its id should be unique.\n        if (new_params->keys_storage[method].contains(key_id))\n            throw Exception(ErrorCodes::BAD_ARGUMENTS, \"Multiple keys have the same ID {}\", key_id);\n\n        /// Check size of key. Its length depends on encryption algorithm.\n        if (key.size() != methodKeySize(method))\n            throw Exception(\n                ErrorCodes::BAD_ARGUMENTS,\n                \"Got an encryption key with unexpected size {}, the size should be {}\",\n                key.size(), methodKeySize(method));\n\n        new_params->keys_storage[method][key_id] = key;\n    }\n\n    /// Check that we have at least one key for this method (otherwise it is incorrect to use it).\n    if (new_params->keys_storage[method].empty())\n        throw Exception(ErrorCodes::BAD_ARGUMENTS, \"No keys, an encryption needs keys to work\");\n\n    /// Try to find which key will be used for encryption. If there is no current_key,\n    /// first key will be used for encryption (its index equals to zero).\n    new_params->current_key_id[method] = config.getUInt64(config_prefix + \".current_key_id\", 0);\n\n    /// Check that we have current key. Otherwise config is incorrect.\n    if (!new_params->keys_storage[method].contains(new_params->current_key_id[method]))\n        throw Exception(ErrorCodes::BAD_ARGUMENTS, \"Not found a key with the current ID {}\", new_params->current_key_id[method]);\n\n    /// Read nonce (in hex or in string). Its length should be 12 bytes.\n    if (config.has(config_prefix + \".nonce_hex\"))\n        new_params->nonce[method] = unhexKey(config.getString(config_prefix + \".nonce_hex\"));\n    else\n        new_params->nonce[method] = config.getString(config_prefix + \".nonce\", \"\");\n\n    if (new_params->nonce[method].size() != 12 && !new_params->nonce[method].empty())\n        throw Exception(ErrorCodes::BAD_ARGUMENTS, \"Got nonce with unexpected size {}, the size should be 12\", new_params->nonce[method].size());\n}\n\nbool CompressionCodecEncrypted::Configuration::tryLoad(const Poco::Util::AbstractConfiguration & config, const String & config_prefix)\n{\n    /// Try to create new parameters and fill them from config.\n    /// If there will be some errors, print their message to notify user that\n    /// something went wrong and new parameters are not available\n    try\n    {\n        load(config, config_prefix);\n    }\n    catch (...)\n    {\n        tryLogCurrentException(__PRETTY_FUNCTION__);\n        return false;\n    }\n    return true;\n}\n\nvoid CompressionCodecEncrypted::Configuration::load(const Poco::Util::AbstractConfiguration & config, const String & config_prefix)\n{\n    /// Try to create new parameters and fill them from config.\n    /// If there will be some errors, throw error\n    std::unique_ptr<Params> new_params(new Params);\n    if (config.has(config_prefix + \".aes_128_gcm_siv\"))\n    {\n        loadImpl(config, config_prefix + \".aes_128_gcm_siv\", AES_128_GCM_SIV, new_params);\n    }\n    if (config.has(config_prefix + \".aes_256_gcm_siv\"))\n    {\n        loadImpl(config, config_prefix + \".aes_256_gcm_siv\", AES_256_GCM_SIV, new_params);\n    }\n\n    params.set(std::move(new_params));\n}\n\nvoid CompressionCodecEncrypted::Configuration::getCurrentKeyAndNonce(EncryptionMethod method, UInt64 & current_key_id, String &current_key, String & nonce) const\n{\n    /// It parameters were not set, throw exception\n    if (!params.get())\n        throw Exception(\"Empty params in CompressionCodecEncrypted configuration\", ErrorCodes::BAD_ARGUMENTS);\n\n    /// Save parameters in variable, because they can always change.\n    /// As this function not atomic, we should be certain that we get information from one particular version for correct work.\n    const auto current_params = params.get();\n    current_key_id = current_params->current_key_id[method];\n\n    /// As parameters can be created empty, we need to check that this key is available.\n    if (current_params->keys_storage[method].contains(current_key_id))\n        current_key = current_params->keys_storage[method].at(current_key_id);\n    else\n        throw Exception(ErrorCodes::BAD_ARGUMENTS, \"There is no current_key {} in config. Please, put it in config and reload.\", current_key_id);\n\n    /// If there is no nonce in config, we need to generate particular one,\n    /// because all encryptions should have nonce and random nonce generation will lead to cases\n    /// when nonce after config reload (nonce is not defined in config) will differ from previously generated one.\n    /// This will lead to data loss.\n    nonce = current_params->nonce[method];\n    if (nonce.empty())\n        nonce = {\"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\", 12};\n}\n\nString CompressionCodecEncrypted::Configuration::getKey(EncryptionMethod method, const UInt64 & key_id) const\n{\n    String key;\n    /// See description of previous finction, logic is the same.\n    if (!params.get())\n        throw Exception(\"Empty params in CompressionCodecEncrypted configuration\", ErrorCodes::BAD_ARGUMENTS);\n\n    const auto current_params = params.get();\n\n    /// check if there is current key in storage\n    if (current_params->keys_storage[method].contains(key_id))\n        key = current_params->keys_storage[method].at(key_id);\n    else\n        throw Exception(ErrorCodes::BAD_ARGUMENTS, \"There is no key {} in config\", key_id);\n\n    return key;\n}\n\n\nCompressionCodecEncrypted::CompressionCodecEncrypted(EncryptionMethod Method): encryption_method(Method)\n{\n    setCodecDescription(getMethodName(encryption_method));\n}\n\nuint8_t CompressionCodecEncrypted::getMethodByte() const\n{\n    return getMethodCode(encryption_method);\n}\n\nvoid CompressionCodecEncrypted::updateHash(SipHash & hash) const\n{\n    getCodecDesc()->updateTreeHash(hash);\n}\n\nUInt32 CompressionCodecEncrypted::getMaxCompressedDataSize(UInt32 uncompressed_size) const\n{\n    // The GCM mode is a stream cipher. No paddings are\n    // involved. There will be a tag at the end of ciphertext (16\n    // octets). Also it has not more than 8 bytes for key_id in the beginning\n    // KeyID is followed by byte, that shows if nonce was set in config (and also will be put into data)\n    // and 12 bytes nonce or this byte will be equal to zero and no nonce will follow it.\n    return uncompressed_size + tag_size + key_id_max_size + nonce_max_size;\n}\n\nUInt32 CompressionCodecEncrypted::doCompressData(const char * source, UInt32 source_size, char * dest) const\n{\n    // Generate an IV out of the data block and the key-generation\n    // key. It is completely deterministic, but does not leak any\n    // information about the data block except for equivalence of\n    // identical blocks (under the same key).\n\n    const std::string_view plaintext = std::string_view(source, source_size);\n\n    /// Get key and nonce for encryption\n    UInt64 current_key_id;\n    String current_key, nonce;\n    Configuration::instance().getCurrentKeyAndNonce(encryption_method, current_key_id, current_key, nonce);\n\n    /// Write current key id to support multiple keys.\n    /// (key id in the beginning will help to decrypt data after changing current key)\n    char* ciphertext_with_nonce = writeVarUInt(current_key_id, dest);\n    size_t keyid_size = ciphertext_with_nonce - dest;\n\n    /// write nonce in data. This will help to read data even after changing nonce in config\n    /// If there were no nonce in data, one zero byte will be written\n    char* ciphertext = writeNonce(nonce, ciphertext_with_nonce);\n    UInt64 nonce_size = ciphertext - ciphertext_with_nonce;\n\n    // The IV will be used as an authentication tag. The ciphertext and the\n    // tag will be written directly in the dest buffer.\n    size_t out_len = encrypt(plaintext, ciphertext, encryption_method, current_key, nonce);\n\n    /// Length of encrypted text should be equal to text length plus tag_size (which was added by algorithm).\n    if (out_len != source_size + tag_size)\n        throw Exception(ErrorCodes::LOGICAL_ERROR, \"Can't encrypt data, length after encryption {} is wrong, expected {}\", out_len, source_size + tag_size);\n\n    return out_len + keyid_size + nonce_size;\n}\n\nvoid CompressionCodecEncrypted::doDecompressData(const char * source, UInt32 source_size, char * dest, UInt32 uncompressed_size) const\n{\n    /// The key is needed for decrypting. That's why it is read at the beginning of process.\n    UInt64 key_id;\n    const char * ciphertext_with_nonce = readVarUInt(key_id, source, source_size);\n\n    /// Size of text should be decreased by key_size, because key_size bytes were not participating in encryption process.\n    size_t keyid_size = ciphertext_with_nonce - source;\n    String nonce;\n    String key = Configuration::instance().getKey(encryption_method, key_id);\n\n    /// try to read nonce from file (if it was set while encrypting)\n    const char * ciphertext = readNonce(nonce, ciphertext_with_nonce);\n\n    /// Size of text should be decreased by nonce_size, because nonce_size bytes were not participating in encryption process.\n    UInt64 nonce_size = ciphertext - ciphertext_with_nonce;\n\n    /// Count text size (nonce and key_id was read from source)\n    size_t ciphertext_size = source_size - keyid_size - nonce_size;\n    if (ciphertext_size != uncompressed_size + tag_size)\n        throw Exception(ErrorCodes::LOGICAL_ERROR, \"Can't decrypt data, uncompressed_size {} is wrong, expected {}\", uncompressed_size, ciphertext_size - tag_size);\n\n\n    size_t out_len = decrypt({ciphertext, ciphertext_size}, dest, encryption_method, key, nonce);\n    if (out_len != ciphertext_size - tag_size)\n        throw Exception(ErrorCodes::LOGICAL_ERROR, \"Can't decrypt data, out length after decryption {} is wrong, expected {}\", out_len, ciphertext_size - tag_size);\n}\n\n}\n\n#else /* USE_SSL && USE_INTERNAL_SSL_LIBRARY */\n\nnamespace DB\n{\n\nnamespace\n{\n\n/// Register codec in factory\nvoid registerEncryptionCodec(CompressionCodecFactory & factory, EncryptionMethod Method)\n{\n    auto throw_no_ssl = [](const ASTPtr &) -> CompressionCodecPtr { throw Exception(ErrorCodes::OPENSSL_ERROR, \"Server was built without SSL support. Encryption is disabled.\"); };\n    const auto method_code = getMethodCode(Method); /// Codec need to know its code\n    factory.registerCompressionCodec(getMethodName(Method), method_code, throw_no_ssl);\n}\n\n}\n\nCompressionCodecEncrypted::Configuration & CompressionCodecEncrypted::Configuration::instance()\n{\n    static CompressionCodecEncrypted::Configuration ret;\n    return ret;\n}\n\n/// if encryption is disabled.\nbool CompressionCodecEncrypted::Configuration::tryLoad(const Poco::Util::AbstractConfiguration & config [[maybe_unused]], const String & config_prefix [[maybe_unused]])\n{\n    return false;\n}\n\n/// if encryption is disabled, print warning about this.\nvoid CompressionCodecEncrypted::Configuration::load(const Poco::Util::AbstractConfiguration & config [[maybe_unused]], const String & config_prefix [[maybe_unused]])\n{\n    LOG_WARNING(&Poco::Logger::get(\"CompressionCodecEncrypted\"), \"Server was built without SSL support. Encryption is disabled.\");\n}\n\n}\n\n#endif /* USE_SSL && USE_INTERNAL_SSL_LIBRARY */\n\nnamespace DB\n{\n/// Register codecs for all algorithms\nvoid registerCodecEncrypted(CompressionCodecFactory & factory)\n{\n    registerEncryptionCodec(factory, AES_128_GCM_SIV);\n    registerEncryptionCodec(factory, AES_256_GCM_SIV);\n}\n}\n", "meta": {"hexsha": "a7da4fd5ade97dfd2fddd16f90528022054375f8", "size": 21589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Compression/CompressionCodecEncrypted.cpp", "max_stars_repo_name": "ne1r0n/ClickHouse", "max_stars_repo_head_hexsha": "17fe76709f9a605c1a8bd9e877a73f068082489d", "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/Compression/CompressionCodecEncrypted.cpp", "max_issues_repo_name": "ne1r0n/ClickHouse", "max_issues_repo_head_hexsha": "17fe76709f9a605c1a8bd9e877a73f068082489d", "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/Compression/CompressionCodecEncrypted.cpp", "max_forks_repo_name": "ne1r0n/ClickHouse", "max_forks_repo_head_hexsha": "17fe76709f9a605c1a8bd9e877a73f068082489d", "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.9693140794, "max_line_length": 179, "alphanum_fraction": 0.6847931817, "num_tokens": 4853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17349785249983007}}
{"text": "// Copyright (c) 2015-2019 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <chain.h>\n#include <chainparams.h>\n#include <pow.h>\n#include <test/util/setup_common.h>\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)\n\n/* Test calculation of next difficulty target with no constraints applying */\nBOOST_AUTO_TEST_CASE(get_next_work)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    int64_t nLastRetargetTime = 1261130161; // Block #30240\n    CBlockIndex pindexLast;\n    pindexLast.nHeight = 32255;\n    pindexLast.nTime = 1262152739;  // Block #32255\n    pindexLast.nBits = 0x1d00ffff;\n    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00d86aU);\n}\n\n/* Test the constraint on the upper bound for next work */\nBOOST_AUTO_TEST_CASE(get_next_work_pow_limit)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    int64_t nLastRetargetTime = 1231006505; // Block #0\n    CBlockIndex pindexLast;\n    pindexLast.nHeight = 2015;\n    pindexLast.nTime = 1233061996;  // Block #2015\n    pindexLast.nBits = 0x1d00ffff;\n    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00ffffU);\n}\n\n/* Test the constraint on the lower bound for actual time taken */\nBOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    int64_t nLastRetargetTime = 1279008237; // Block #66528\n    CBlockIndex pindexLast;\n    pindexLast.nHeight = 68543;\n    pindexLast.nTime = 1279297671;  // Block #68543\n    pindexLast.nBits = 0x1c05a3f4;\n    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1c0168fdU);\n}\n\n/* Test the constraint on the upper bound for actual time taken */\nBOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time\n    CBlockIndex pindexLast;\n    pindexLast.nHeight = 46367;\n    pindexLast.nTime = 1269211443;  // Block #46367\n    pindexLast.nBits = 0x1c387f6f;\n    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00e1fdU);\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_negative_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits;\n    nBits = UintToArith256(consensus.powLimit).GetCompact(true);\n    hash.SetHex(\"0x1\");\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_overflow_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits = ~0x00800000;\n    hash.SetHex(\"0x1\");\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_too_easy_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits;\n    arith_uint256 nBits_arith = UintToArith256(consensus.powLimit);\n    nBits_arith *= 2;\n    nBits = nBits_arith.GetCompact();\n    hash.SetHex(\"0x1\");\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_biger_hash_than_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits;\n    arith_uint256 hash_arith = UintToArith256(consensus.powLimit);\n    nBits = hash_arith.GetCompact();\n    hash_arith *= 2; // hash > nBits\n    hash = ArithToUint256(hash_arith);\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_zero_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits;\n    arith_uint256 hash_arith{0};\n    nBits = hash_arith.GetCompact();\n    hash = ArithToUint256(hash_arith);\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    std::vector<CBlockIndex> blocks(10000);\n    for (int i = 0; i < 10000; i++) {\n        blocks[i].pprev = i ? &blocks[i - 1] : nullptr;\n        blocks[i].nHeight = i;\n        blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing;\n        blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */\n        blocks[i].nChainTrust = i ? blocks[i - 1].nChainTrust + GetBlockProof(blocks[i - 1]) : arith_uint256(0);\n    }\n\n    for (int j = 0; j < 1000; j++) {\n        CBlockIndex *p1 = &blocks[InsecureRandRange(10000)];\n        CBlockIndex *p2 = &blocks[InsecureRandRange(10000)];\n        CBlockIndex *p3 = &blocks[InsecureRandRange(10000)];\n\n        int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus());\n        BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4fa22619171f09fff7e85d9e0ceeca95c232a7b0", "size": 5333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/pow_tests.cpp", "max_stars_repo_name": "mderasse/vericonomy", "max_stars_repo_head_hexsha": "fcc74c006121ce55badc2feec349fdfc76d678d2", "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/test/pow_tests.cpp", "max_issues_repo_name": "mderasse/vericonomy", "max_issues_repo_head_hexsha": "fcc74c006121ce55badc2feec349fdfc76d678d2", "max_issues_repo_licenses": ["MIT"], "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/pow_tests.cpp", "max_forks_repo_name": "mderasse/vericonomy", "max_forks_repo_head_hexsha": "fcc74c006121ce55badc2feec349fdfc76d678d2", "max_forks_repo_licenses": ["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.3669064748, "max_line_length": 123, "alphanum_fraction": 0.7412338271, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.17349785031923678}}
{"text": "// Copyright (c) 2015-2019 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <chain.h>\n#include <chainparams.h>\n#include <pow.h>\n#include <test/util/setup_common.h>\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)\n\n/* Test calculation of next difficulty target with no constraints applying */\nBOOST_AUTO_TEST_CASE(get_next_work)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    int64_t nLastRetargetTime = 1261130161; // Block #30240\n    CBlockIndex pindexLast;\n    pindexLast.nHeight = 32255;\n    pindexLast.nTime = 1262152739;  // Block #32255\n    pindexLast.nBits = 0x1d00ffff;\n    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00d86aU);\n}\n\n/* Test the constraint on the upper bound for next work */\nBOOST_AUTO_TEST_CASE(get_next_work_pow_limit)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    int64_t nLastRetargetTime = 1231006505; // Block #0\n    CBlockIndex pindexLast;\n    pindexLast.nHeight = 2015;\n    pindexLast.nTime = 1233061996;  // Block #2015\n    pindexLast.nBits = 0x1d00ffff;\n    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00ffffU);\n}\n\n/* Test the constraint on the lower bound for actual time taken */\nBOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    int64_t nLastRetargetTime = 1279008237; // Block #66528\n    CBlockIndex pindexLast;\n    pindexLast.nHeight = 68543;\n    pindexLast.nTime = 1279297671;  // Block #68543\n    pindexLast.nBits = 0x1c05a3f4;\n    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1c0168fdU);\n}\n\n/* Test the constraint on the upper bound for actual time taken */\nBOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time\n    CBlockIndex pindexLast;\n    pindexLast.nHeight = 46367;\n    pindexLast.nTime = 1269211443;  // Block #46367\n    pindexLast.nBits = 0x1c387f6f;\n    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00e1fdU);\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_negative_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits;\n    nBits = UintToArith256(consensus.powLimit).GetCompact(true);\n    hash.SetHex(\"0x1\");\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_overflow_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits = ~0x00800000;\n    hash.SetHex(\"0x1\");\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_too_easy_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits;\n    arith_uint256 nBits_arith = UintToArith256(consensus.powLimit);\n    nBits_arith *= 2;\n    nBits = nBits_arith.GetCompact();\n    hash.SetHex(\"0x1\");\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_biger_hash_than_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits;\n    arith_uint256 hash_arith = UintToArith256(consensus.powLimit);\n    nBits = hash_arith.GetCompact();\n    hash_arith *= 2; // hash > nBits\n    hash = ArithToUint256(hash_arith);\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(CheckProofOfWork_test_zero_target)\n{\n    const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n    uint256 hash;\n    unsigned int nBits;\n    arith_uint256 hash_arith{0};\n    nBits = hash_arith.GetCompact();\n    hash = ArithToUint256(hash_arith);\n    BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus));\n}\n\nBOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)\n{\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    std::vector<CBlockIndex> blocks(10000);\n    for (int i = 0; i < 10000; i++) {\n        blocks[i].pprev = i ? &blocks[i - 1] : nullptr;\n        blocks[i].nHeight = i;\n        blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing;\n        blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */\n        blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);\n    }\n\n    for (int j = 0; j < 1000; j++) {\n        CBlockIndex *p1 = &blocks[InsecureRandRange(10000)];\n        CBlockIndex *p2 = &blocks[InsecureRandRange(10000)];\n        CBlockIndex *p3 = &blocks[InsecureRandRange(10000)];\n\n        int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus());\n        BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());\n    }\n}\n\n// ASERT DAA related tests\n// Tests of the CalculateASERT function.\n\nstd::string StrPrintCalcArgs(const arith_uint256 refTarget,\n                             const int64_t targetSpacing,\n                             const int64_t timeDiff,\n                             const int64_t heightDiff,\n                             const arith_uint256 expectedTarget,\n                             const uint32_t expectednBits) {\n    return strprintf(\"\\n\"\n                     \"ref=         %s\\n\"\n                     \"spacing=     %d\\n\"\n                     \"timeDiff=    %d\\n\"\n                     \"heightDiff=  %d\\n\"\n                     \"expTarget=   %s\\n\"\n                     \"exp nBits=   0x%08x\\n\",\n                     refTarget.ToString(),\n                     targetSpacing,\n                     timeDiff,\n                     heightDiff,\n                     expectedTarget.ToString(),\n                     expectednBits);\n}\n\nBOOST_AUTO_TEST_CASE(calculate_asert_test) {\n  const Consensus::Params params = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus();\n  const int64_t nHalfLife = params.nASERTHalfLife;\n\n  const arith_uint256 powLimit = UintToArith256(params.powLimit);\n  arith_uint256 initialTarget = powLimit >> 4; // anchor block target\n  int64_t height = 0; // height will always be preincrementing\n\n  // The CalculateASERT function uses the absolute ASERT formulation\n  // and adds +1 to the height difference that it receives.\n  // The time difference passed to it must factor in the difference\n  // to the *parent* of the reference block.\n  // We assume the parent is ideally spaced in time before the reference block.\n  static const int64_t parent_time_diff = params.nPowTargetSpacing; // diff of nTime of anchor and parent of anchor\n\n  // Steady\n  arith_uint256 nextTarget = CalculateASERT(initialTarget, params.nPowTargetSpacing, parent_time_diff + 600 /* nTimeDiff - diff between current tip and anchor's parent */, ++height, powLimit, nHalfLife);\n  BOOST_CHECK(nextTarget == initialTarget);\n\n  // A block that arrives in half the expected time\n  nextTarget = CalculateASERT(initialTarget, params.nPowTargetSpacing, parent_time_diff + 600 + 300, ++height, powLimit, nHalfLife);\n  BOOST_CHECK(nextTarget < initialTarget); // aka higher difficulty\n\n  // A block that makes up for the shortfall of the previous one, restores the target to initial\n  arith_uint256 prevTarget = nextTarget;\n  nextTarget = CalculateASERT(initialTarget, params.nPowTargetSpacing, parent_time_diff + 600 + 300 + 900, ++height, powLimit, nHalfLife);\n  BOOST_CHECK(nextTarget > prevTarget);\n  BOOST_CHECK(nextTarget == initialTarget);\n\n  // Two days ahead of schedule should double the target (halve the difficulty) (for 288s block the ideal would be 288*600)\n  prevTarget = nextTarget;\n  nextTarget = CalculateASERT(prevTarget, params.nPowTargetSpacing, parent_time_diff + 288*1200, 288, powLimit, nHalfLife);\n  BOOST_CHECK(nextTarget == prevTarget * 2);\n\n  // Two days behind of schedule should halve the target (double the difficulty) (for 288s block the ideal would be 288*600)\n  prevTarget = nextTarget;\n  nextTarget = CalculateASERT(prevTarget, params.nPowTargetSpacing, parent_time_diff + 288*0, 288, powLimit, nHalfLife);\n  BOOST_CHECK(nextTarget == prevTarget / 2);\n  BOOST_CHECK(nextTarget == initialTarget);\n\n  // Ramp up from initialTarget to PowLimit - should only take 4 doublings...\n  uint32_t powLimit_nBits = powLimit.GetCompact();\n  uint32_t next_nBits;\n  for (size_t k = 0; k < 3; k++) {\n      prevTarget = nextTarget;\n      nextTarget = CalculateASERT(prevTarget, params.nPowTargetSpacing, parent_time_diff + 288*1200, 288, powLimit, nHalfLife);\n      BOOST_CHECK(nextTarget == prevTarget * 2);\n      BOOST_CHECK(nextTarget < powLimit);\n      next_nBits = nextTarget.GetCompact();\n      BOOST_CHECK(next_nBits != powLimit_nBits);\n  }\n\n  prevTarget = nextTarget;\n  nextTarget = CalculateASERT(prevTarget, params.nPowTargetSpacing, parent_time_diff + 288*1200, 288, powLimit, nHalfLife);\n  next_nBits = nextTarget.GetCompact();\n  BOOST_CHECK(nextTarget == prevTarget * 2);\n  BOOST_CHECK(next_nBits == powLimit_nBits);\n\n  // Fast periods now cannot increase target beyond POW limit, even if we try to overflow nextTarget.\n  // prevTarget is a uint256, so 256*2 = 512 days would overflow nextTarget unless CalculateASERT\n  // correctly detects this error\n  nextTarget = CalculateASERT(prevTarget, params.nPowTargetSpacing, parent_time_diff + 512*144*600, 0, powLimit, nHalfLife);\n  next_nBits = nextTarget.GetCompact();\n  BOOST_CHECK(next_nBits == powLimit_nBits);\n\n  // We also need to watch for underflows on nextTarget. We need to withstand an extra ~446 days worth of blocks.\n  // This should bring down a powLimit target to the a minimum target of 1.\n  nextTarget = CalculateASERT(powLimit, params.nPowTargetSpacing, 0, 2*(256-33)*144, powLimit, nHalfLife);\n  next_nBits = nextTarget.GetCompact();\n  BOOST_CHECK_EQUAL(next_nBits, arith_uint256(1).GetCompact());\n\n  // Define a structure holding parameters to pass to CalculateASERT.\n  // We are going to check some expected results  against a vector of\n  // possible arguments.\n  struct calc_params {\n      arith_uint256 refTarget;\n      int64_t targetSpacing;\n      int64_t timeDiff;\n      int64_t heightDiff;\n      arith_uint256 expectedTarget;\n      uint32_t expectednBits;\n  };\n\n  // Define some named input argument values\n  const arith_uint256 SINGLE_300_TARGET { \"0000000000ffb1004e0000000000000000000000000000000000000000000000\" };\n  const arith_uint256 FUNNY_REF_TARGET { \"000000000080000000000000000fffffffffffffffffffffffffffffffffffff\" };\n\n  // Define our expected input and output values.\n  // The timeDiff entries exclude the `parent_time_diff` - this is\n  // added in the call to CalculateASERT in the test loop.\n  const std::vector<calc_params> calculate_args = {\n\n      /* refTarget, targetSpacing, timeDiff, heightDiff, expectedTarget, expectednBits */\n\n      { powLimit, 600, 0, 2*144, powLimit >> 1, 0x1b7fff80 }, // block comes too early (exactly nHalfLife) the target should be dropped twice\n      { powLimit, 600, 0, 4*144, powLimit >> 2, 0x1b3fffc0 },\n      { powLimit >> 1, 600, 0, 2*144, powLimit >> 2, 0x1b3fffc0 },\n      { powLimit >> 2, 600, 0, 2*144, powLimit >> 3, 0x1b1fffe0 },\n      { powLimit >> 3, 600, 0, 2*144, powLimit >> 4, 0x1b0ffff0 },\n      { powLimit, 600, 0, 2*(256-42)*144, 3, 0x01030000 },\n      { powLimit, 600, 0, 2*(256-32)*144 + 119, 1, 0x01010000 },\n      { powLimit, 600, 0, 2*(256-40)*144 + 120, 1, 0x01010000 },\n      { powLimit, 600, 0, 2*(256-39)*144-1, 1, 0x01010000 },\n      { powLimit, 600, 0, 2*(256-33)*144, 1, 0x01010000 },  // 1 bit less since we do not need to shift to 0\n      { powLimit, 600, 0, 2*(256-32)*144, 1, 0x01010000 },  // more will not decrease below 1\n      { 1, 600, 0, 2*(256-32)*144, 1, 0x01010000 },\n      { powLimit, 600, 2*(512-32)*144, 0, powLimit, powLimit_nBits },\n      { 1, 600, (512-64)*144*600, 0, powLimit, powLimit_nBits },\n      { powLimit, 600, 300, 1, SINGLE_300_TARGET, 0x1c00ffb1 },  // clamps to powLimit\n      { FUNNY_REF_TARGET, 600, 600*2*33*144, 0, powLimit, powLimit_nBits }, // confuses any attempt to detect overflow by inspecting result\n      { 1, 600, 600*2*256*144, 0, powLimit, powLimit_nBits }, // overflow to exactly 2^256\n      { 1, 600, 600*2*224*144 - 1, 0, arith_uint256(0xffff) << 200, powLimit_nBits }, // just under powlimit (not clamped) yet over powlimit_nbits\n  };\n\n  for (auto& v : calculate_args) {\n      nextTarget = CalculateASERT(v.refTarget, v.targetSpacing, parent_time_diff + v.timeDiff, v.heightDiff, powLimit, nHalfLife);\n      next_nBits = nextTarget.GetCompact();\n      const auto failMsg =\n          StrPrintCalcArgs(v.refTarget, v.targetSpacing, parent_time_diff + v.timeDiff, v.heightDiff, v.expectedTarget, v.expectednBits)\n          + strprintf(\"nextTarget=  %s\\nnext nBits=  0x%08x\\n\", nextTarget.ToString(), next_nBits);\n      BOOST_CHECK_MESSAGE(nextTarget == v.expectedTarget && next_nBits == v.expectednBits, failMsg);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f8bf2131f7f69e185f0ca1e78a1da33056de2c91", "size": 13373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/pow_tests.cpp", "max_stars_repo_name": "JohnEndor/obtc", "max_stars_repo_head_hexsha": "d05871873c28a12be3310e8cb3beee3b277fc0bc", "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/test/pow_tests.cpp", "max_issues_repo_name": "JohnEndor/obtc", "max_issues_repo_head_hexsha": "d05871873c28a12be3310e8cb3beee3b277fc0bc", "max_issues_repo_licenses": ["MIT"], "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/pow_tests.cpp", "max_forks_repo_name": "JohnEndor/obtc", "max_forks_repo_head_hexsha": "d05871873c28a12be3310e8cb3beee3b277fc0bc", "max_forks_repo_licenses": ["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.4340277778, "max_line_length": 203, "alphanum_fraction": 0.7099379346, "num_tokens": 3775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.17349784551156064}}
{"text": "#ifndef PYTHONIC_INCLUDE_SCIPY_SPECIAL_GAMMA_HPP\n#define PYTHONIC_INCLUDE_SCIPY_SPECIAL_GAMMA_HPP\n\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n#include <boost/simd/function/gamma.hpp>\n\nPYTHONIC_NS_BEGIN\n\nnamespace scipy\n{\n  namespace special\n  {\n\n#define NUMPY_NARY_FUNC_NAME gamma\n#define NUMPY_NARY_FUNC_SYM boost::simd::gamma\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n  }\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "825eb1bed445f81e3c56c6549272a2c1a5fc3452", "size": 512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/scipy/special/gamma.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T00:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-24T00:33:03.000Z", "max_issues_repo_path": "pythran/pythonic/include/scipy/special/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": "pythran/pythonic/include/scipy/special/gamma.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "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": 21.3333333333, "max_line_length": 53, "alphanum_fraction": 0.82421875, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.173469068264183}}
{"text": "//\n// Created by tao on 19-3-25.\n//\n\n#include \"AES_func_adaptor.h\"\n#include \"log_init.h\"\n\n#include <cstring>\n#include <string>\n#include \"adaptor_base.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <openssl/rsa.h>       /* SSLeay stuff */\n#include <openssl/crypto.h>\n#include <openssl/x509.h>\n#include <openssl/pem.h>\n#include <openssl/ssl.h>\n#include <openssl/err.h>\n#include <openssl/bio.h>\n#include <openssl/evp.h>\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <sstream>\n#include <iosfwd>\n#define BUFF_SIZE_4K 4096\n\nstd::string printBinToStr(const unsigned char *uc_pMd, int len) {\n    std::stringbuf resBuff;\n    char tmp[5];\n    int i = 0;\n    for (i = 0; i < len; i++) {\n        snprintf(tmp, sizeof(tmp), \"%02x\", uc_pMd[i]);\n        resBuff.sputn(tmp, strlen(tmp));\n    }\n    return resBuff.str();\n}\n\nstd::string printBinToStr(const char *uc_pMd, int len) {\n    std::stringbuf resBuff;\n    char tmp[5];\n    int i = 0;\n    for (i = 0; i < len; i++) {\n        snprintf(tmp, sizeof(tmp), \"%02x\", uc_pMd[i]);\n        resBuff.sputn(tmp, strlen(tmp));\n    }\n    return resBuff.str();\n}\n\n\nint checkFile(std::string fileStr) {\n    namespace bf=boost::filesystem;\n    bf::path file(fileStr);\n    if ((!bf::exists(file)) || (!bf::is_regular(file))) {\n        ERROR_LOG(\"file not exists :\" << fileStr)\n        return -1;\n    }\n    return 0;\n}\n\nint trunkFile(std::string fileStr) {\n    namespace bf=boost::filesystem;\n    bf::path file(fileStr);\n    if ((!bf::exists(file)) || (!bf::is_regular(file))) {\n        return 0;\n    }\n    bf::remove(file);\n    return 0;\n}\n\nint aesDataToData(std::string keyStr, const char *inData, size_t inLen, char *outData, size_t &outlen, int type) {\n    const unsigned char *key = (unsigned char *) keyStr.c_str();\n    BIO *enc = nullptr, *out = nullptr;\n    unsigned char iv[16] = {0};\n    const unsigned char *inStr = (const unsigned char *) inData;\n\n    EVP_CIPHER_CTX *ctx = nullptr;\n    BUF_MEM *bptr = nullptr;\n\n    OpenSSL_add_all_algorithms();\n    out = BIO_new(BIO_s_mem());\n    if (out == NULL) {\n        ERROR_LOG(\"out null\\n\");\n        return -1;\n    }\n    if ((enc = BIO_new(BIO_f_cipher())) == nullptr) {\n        ERROR_LOG(\"Cipher New BIO Error\\n\");\n        return -1;\n    }\n    BIO_get_cipher_ctx(enc, &ctx);\n    if (ctx == nullptr) {\n        ERROR_LOG(\"ctx null\\n\");\n        return -1;\n    }\n\n    if (!EVP_CipherInit_ex(ctx, EVP_des_cbc(), NULL, key, iv, type)) {\n        ERROR_LOG(\"EVP_CipherInit_ex Error\\n\");\n        return -1;\n    }\n\n    enc = BIO_push(enc, out);\n    BIO_write(enc, inStr, inLen);\n    BIO_flush(enc);\n    BIO_flush(out);\n    BIO_get_mem_ptr(out, &bptr);\n    if (bptr->length > outlen) {\n        ERROR_LOG(\"out put mem is too small\")\n        return -1;\n    }\n    memcpy(outData, bptr->data, bptr->length);\n    outlen = bptr->length;\n    BIO_free_all(out);\n    return 0;\n}\n\nint aesFileToFile(std::string keyStr, std::string inFile, std::string outFile, int type, size_t &curr_size) {\n    const unsigned char *key = (unsigned char *) keyStr.c_str();\n    BIO *enc = nullptr, *out_bio_file = nullptr;\n    unsigned char iv[16] = {0};\n    curr_size = 0;\n    namespace bf=boost::filesystem;\n\n    char buff[BUFF_SIZE_4K];\n    EVP_CIPHER_CTX *ctx = nullptr;\n\n    OpenSSL_add_all_algorithms();\n\n    out_bio_file = BIO_new(BIO_s_file());\n    if (checkFile(inFile)) {\n        ERROR_LOG(\"in file not exists\\n\");\n        return -1;\n    }\n    trunkFile(outFile);\n\n    BIO_write_filename(out_bio_file, (void *) outFile.c_str());\n\n    if (out_bio_file == NULL) {\n        ERROR_LOG(\"out_bio_file null\\n\");\n        return -1;\n    }\n    if ((enc = BIO_new(BIO_f_cipher())) == nullptr) {\n        ERROR_LOG(\"Cipher New BIO Error\\n\");\n        return -1;\n    }\n    BIO_get_cipher_ctx(enc, &ctx);\n    if (ctx == nullptr) {\n        ERROR_LOG(\"ctx null\\n\");\n        return -1;\n    }\n\n    if (!EVP_CipherInit_ex(ctx, EVP_des_cbc(), NULL, key, iv, type)) {\n        ERROR_LOG(\"EVP_CipherInit_ex Error\\n\");\n        return -1;\n    }\n\n    enc = BIO_push(enc, out_bio_file);\n    bf::ifstream file(inFile);\n\n    while (!file.eof()) {\n        file.read(buff, sizeof(buff));\n        BIO_write(enc, buff, file.gcount());\n        curr_size += file.gcount();\n    }\n\n    BIO_flush(enc);\n    BIO_flush(out_bio_file);\n    BIO_free_all(out_bio_file);\n    return 0;\n}\n\nint aesFdToFd(std::string keyStr, int inFd, int outFd, int type, size_t &curr_size) {\n    const unsigned char *key = (unsigned char *) keyStr.c_str();\n    BIO *enc = nullptr, *out_bio_file = nullptr;\n    unsigned char iv[16] = {0};\n    curr_size = 0;\n    namespace bf=boost::filesystem;\n\n    char buff[BUFF_SIZE_4K];\n    EVP_CIPHER_CTX *ctx = nullptr;\n\n    OpenSSL_add_all_algorithms();\n\n    out_bio_file = BIO_new(BIO_s_fd());\n\n    out_bio_file = BIO_new_fd(outFd, BIO_NOCLOSE);\n\n    if (out_bio_file == NULL) {\n        ERROR_LOG(\"out_bio_file null\\n\");\n        return -1;\n    }\n    if ((enc = BIO_new(BIO_f_cipher())) == nullptr) {\n        ERROR_LOG(\"Cipher New BIO Error\\n\");\n        return -1;\n    }\n    BIO_get_cipher_ctx(enc, &ctx);\n    if (ctx == nullptr) {\n        ERROR_LOG(\"ctx null\\n\");\n        return -1;\n    }\n\n    if (!EVP_CipherInit_ex(ctx, EVP_des_cbc(), NULL, key, iv, type)) {\n        ERROR_LOG(\"EVP_CipherInit_ex Error\\n\");\n        return -1;\n    }\n\n    enc = BIO_push(enc, out_bio_file);\n    int readLen = 0;\n    while ((readLen = read(inFd, buff, sizeof(buff))) > 0) {\n        BIO_write(enc, buff, readLen);\n        curr_size += readLen;\n    }\n\n    BIO_flush(enc);\n    BIO_flush(out_bio_file);\n    BIO_free_all(out_bio_file);\n    return 0;\n}\n", "meta": {"hexsha": "95d3773fe102dae953f550bd2035d026cebdcb04", "size": 5628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crypto_adaptor/AES_func_adaptor.cpp", "max_stars_repo_name": "puzzzzzzle/-personal_file_protector", "max_stars_repo_head_hexsha": "d38eb7e8ea3c957a0bc09c51e3431e1aa453d039", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "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/crypto_adaptor/AES_func_adaptor.cpp", "max_issues_repo_name": "puzzzzzzle/-personal_file_protector", "max_issues_repo_head_hexsha": "d38eb7e8ea3c957a0bc09c51e3431e1aa453d039", "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": "src/crypto_adaptor/AES_func_adaptor.cpp", "max_forks_repo_name": "puzzzzzzle/-personal_file_protector", "max_forks_repo_head_hexsha": "d38eb7e8ea3c957a0bc09c51e3431e1aa453d039", "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": 25.698630137, "max_line_length": 114, "alphanum_fraction": 0.6044776119, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.17346906826418299}}
{"text": "//\n// Created by yale on 7/26/18.\n//\n\n#ifndef POW_ETHASH_H\n#define POW_ETHASH_H\n\n#include <cstdint>\n#include <vector>\n#include <string>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace celesos {\n    namespace ethash {\n        static const uint32_t FNV_PRIME = 0x01000193;\n        static const uint32_t WORD_BYTES = 4;\n        static const uint32_t NODE_BYTES = 64;\n        static const uint32_t NODE_WORDS = NODE_BYTES / WORD_BYTES;\n        static const uint32_t MIX_BYTES = NODE_BYTES * 2;\n        static const uint32_t MIX_WORDS = MIX_BYTES / WORD_BYTES;\n        static const uint32_t MIX_NODES = MIX_WORDS / NODE_WORDS;\n        static const uint32_t DATASET_PARENTS = 256;\n        static const uint32_t CACHE_ROUNDS = 3;\n        static const uint32_t ACCESSES = 3;\n\n        union node {\n            uint8_t bytes[NODE_BYTES];\n            uint32_t words[NODE_WORDS];\n        };\n\n        bool calc_cache(std::vector<node> &cache, uint32_t cache_count, const std::string &seed);\n\n        node calc_dataset_item(const std::vector<node> &cache, uint32_t item_idx);\n\n        bool\n        calc_dataset(std::vector<node> &dataset, uint32_t dataset_count, const std::vector<node> &cache);\n\n        boost::multiprecision::uint256_t\n        hash_light(const std::string &forest,\n                   const boost::multiprecision::uint256_t &wood,\n                   uint32_t dataset_count,\n                   const std::vector<node> &cache);\n\n        boost::multiprecision::uint256_t\n        hash_full(const std::string &forest,\n                  const boost::multiprecision::uint256_t &wood,\n                  uint32_t dataset_count,\n                  const std::vector<node> &dataset);\n\n        bool uint256_to_hex(std::string &dst, const boost::multiprecision::uint256_t &src);\n\n        bool hex_to_uint256(boost::multiprecision::uint256_t &dst, const std::string &src);\n\n        boost::multiprecision::uint256_t\n        hash_light_hex(const std::string &forest,\n                       const std::string &wood_hex,\n                       uint32_t dataset_count,\n                       const std::vector<node> &cache);\n\n        boost::multiprecision::uint256_t\n        hash_full_hex(const std::string &forest,\n                      const std::string &wood_hex,\n                      uint32_t dataset_count,\n                      const std::vector<node> &dataset);\n    }\n}\n\n#endif //POW_ETHASH_H\n", "meta": {"hexsha": "3d828f95ac1eacf3a84d46e11dd8574be72ede5f", "size": 2392, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/pow/include/celesos/pow/ethash.hpp", "max_stars_repo_name": "celes-dev/celesos", "max_stars_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "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": "libraries/pow/include/celesos/pow/ethash.hpp", "max_issues_repo_name": "celes-dev/celesos", "max_issues_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/pow/include/celesos/pow/ethash.hpp", "max_forks_repo_name": "celes-dev/celesos", "max_forks_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 105, "alphanum_fraction": 0.6224916388, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.17346906470062395}}
{"text": "/**\n ** Isaac Genome Alignment Software\n ** Copyright (c) 2010-2017 Illumina, Inc.\n ** All rights reserved.\n **\n ** This software is provided under the terms and conditions of the\n ** GNU GENERAL PUBLIC LICENSE Version 3\n **\n ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3\n ** along with this program. If not, see\n ** <https://github.com/illumina/licenses/>.\n **\n ** \\file ReferenceKmer.hh\n **\n ** Representation of a k-mer at a given position in a reference genome.\n **\n ** \\author Come Raczy\n **/\n\n#ifndef iSAAC_REFERENCE_REFERENCE_KMER_HH\n#define iSAAC_REFERENCE_REFERENCE_KMER_HH\n\n#include <utility>\n\n#include <boost/mpl/back.hpp>\n#include <boost/mpl/begin_end.hpp>\n#include <boost/mpl/copy_if.hpp>\n#include <boost/mpl/deref.hpp>\n#include <boost/mpl/front.hpp>\n#include <boost/mpl/modulus.hpp>\n\n#include \"oligo/Kmer.hh\"\n#include \"oligo/Permutate.hh\"\n#include \"reference/ReferencePosition.hh\"\n\nnamespace isaac\n{\nnamespace reference\n{\n\ntypedef boost::mpl::copy_if<\n    oligo::SUPPORTED_KMERS\n    , boost::mpl::equal_to<boost::mpl::modulus<boost::mpl::_1, boost::mpl::int_<4> >, boost::mpl::int_<0> >\n    , boost::mpl::back_inserter< boost::mpl::vector<> >\n    >::type SUPPORTED_KMERS;\n\nstatic const unsigned FIRST_SUPPORTED_KMER = boost::mpl::front<SUPPORTED_KMERS>::type::value;\nstatic const unsigned LAST_SUPPORTED_KMER = boost::mpl::back<SUPPORTED_KMERS>::type::value;\n\n} // namespace reference\n} // namespace isaac\n\n#endif // #ifndef iSAAC_REFERENCE_REFERENCE_KMER_HH\n", "meta": {"hexsha": "0e94fa286c52dc7a7d487e9cd29ad828f51424a8", "size": 1506, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/c++/include/reference/ReferenceKmer.hh", "max_stars_repo_name": "Illumina/Isaac4", "max_stars_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T22:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:33:22.000Z", "max_issues_repo_path": "src/c++/include/reference/ReferenceKmer.hh", "max_issues_repo_name": "Illumina/Isaac4", "max_issues_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-26T11:36:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T18:48:43.000Z", "max_forks_repo_path": "src/c++/include/reference/ReferenceKmer.hh", "max_forks_repo_name": "Illumina/Isaac4", "max_forks_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T20:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T14:44:06.000Z", "avg_line_length": 27.8888888889, "max_line_length": 107, "alphanum_fraction": 0.7310756972, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.17346905757350595}}
{"text": "#include <vector>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n\nnamespace qi = boost::spirit::qi;\nnamespace phx = boost::phoenix;\n\ntemplate <typename Container, typename Iter>\nstruct srec_parser: qi::grammar<Iter, Container()> {\n\tsrec_parser(): srec_parser::base_type(start) {\n\t\tstart = qi::no_skip[lines];\n\t\t// _a: address length of this line\n\t\t// _b: data length of this line\n\t\t// _c: start address of this line\n\t\t// _d: data of this line\n\t\t// _e: line doesn't contain data\n\t\tlines = *('S'\n\t\t\t> qi::digit[\n\t\t\t\tphx::switch_(qi::_1) [\n\t\t\t\t\tphx::case_<'3'>(qi::_a = 4),\n\t\t\t\t\tphx::case_<'7'>(qi::_a = 4),\n\t\t\t\t\tphx::case_<'2'>(qi::_a = 3),\n\t\t\t\t\tphx::case_<'8'>(qi::_a = 3),\n\t\t\t\t\tphx::default_(qi::_a = 2)\n\t\t\t\t],\n\t\t\t\tphx::switch_(qi::_1) [\n\t\t\t\t\tphx::case_<'1'>(qi::_e = false),\n\t\t\t\t\tphx::case_<'2'>(qi::_e = false),\n\t\t\t\t\tphx::case_<'3'>(qi::_e = false),\n\t\t\t\t\tphx::default_(qi::_e = true)\n\t\t\t\t]\n\t\t\t  ]\n\t\t\t> hex_byte[qi::_b = qi::_1 - qi::_a - 1]\n\t\t\t> qi::eps[qi::_c = 0] > qi::repeat(qi::_a)[hex_byte[qi::_c = (qi::_c << 8) | qi::_1]]\n\t\t\t> qi::eps[phx::clear(qi::_d)] > qi::repeat(qi::_b)[hex_byte[phx::push_back(qi::_d, qi::_1)]]\n\t\t\t> hex_byte[\n\t\t\t\tqi::_pass = qi::_1 == (0xFF & ~phx::accumulate(qi::_d, (qi::_c>>24) + (qi::_c>>16) + (qi::_c>>8) + qi::_c + qi::_b + qi::_a + 1)),\n\t\t\t\tif_(!qi::_e) [\n\t\t\t\t\tphx::resize(qi::_val, qi::_b+qi::_c),\n\t\t\t\t\tphx::for_(qi::_b = 0, qi::_b < phx::size(qi::_d), ++qi::_b) [\n\t\t\t\t\t\tqi::_val[qi::_b+qi::_c] = qi::_d[qi::_b]\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t  ]\n\t\t\t> +qi::eol);\n\t\thex_byte = qi::uint_parser<unsigned, 16, 2, 2>();\n\t\tqi::on_error<qi::fail>\n\t\t(\n            lines\n          , std::cout\n\t\t\t<< phx::val(\"Error! Expecting \")\n\t\t\t<< qi::_4                               // what failed?\n\t\t\t<< phx::val(\" here: \\\"\")\n\t\t\t<< phx::construct<std::string>(qi::_3, qi::_2)   // iterators to error-pos, end\n\t\t\t<< phx::val(\"\\\"\")\n                << std::endl\n        );\t}\n\tqi::rule<Iter, Container()> start;\n\tqi::rule<Iter, Container(), qi::locals<unsigned, unsigned, std::size_t, std::vector<unsigned char>, bool> > lines;\n\tqi::rule<Iter, unsigned char()> hex_byte;\n};\n\ntemplate <typename Container, typename Iter>\nContainer parse_srec(Iter &first, Iter last) {\n\tContainer c;\n\tqi::parse(first, last, srec_parser<Container, Iter>(), c);\n\treturn c;\n}\n\ntemplate <typename Container, typename Input>\nContainer parse_srec(const Input &in) {\n\ttypename Input::const_iterator ite = in.begin();\n\ttypename Input::const_iterator end = in.end();\n\treturn parse_srec<Container>(ite, end);\n}\n\n#include <boost/asio.hpp>\n\nnamespace asio = boost::asio;\n\n\n#include <string>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <deque>\n#include <boost/exception/all.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n\nusing namespace std;\nusing boost::system::error_code;\nusing boost::format;\n\ninline string get_option_arg(int &argc, char **&argv) {\n\tif (strlen(*argv)==2) {\n\t\tif (--argc) return string(*++argv);\n\t\t++argv;\n\t\treturn string();\n\t}\n\treturn string((*argv)+2);\n}\n\ninline void require(unsigned char val, unsigned char ex) {\n\tif (val == ex) return;\n\tcerr << (format(\"invalid response '0x%02X'(should be 0x%02X\\n\") % (unsigned)val % (unsigned)ex);\n\tthrow runtime_error(\"unexpected respoonse\");\n}\n\nvoid help() {\n\tcerr << \"usage: yaki-h8 [opts...] {file}\\n\";\n\tcerr << \"\\n\";\n\tcerr << \"  file:        S-record file to transfer\\n\";\n\tcerr << \" options:\\n\";\n\tcerr << \"  -p PORT      specify serial port\\n\";\n\tcerr << \"  -s BAUDRATE  specify initial hand-shake speed\\n\";\n\tcerr << \"  -c CLOCK     specify target system clock freq\\n\";\n\tcerr << \"  -t BAUDRATE  specify data transfer speed\\n\";\n\tcerr << \"  -h           print this message\\n\";\n}\n\n#include \"stub-h8tiny.h\"\n\ninline std::vector<unsigned char> read_file(const string &file) {\n\tstd::ifstream f(file);\n\tf.seekg(0, std::ios_base::end);\n\tstd::vector<unsigned char> r(f.tellg());\n\tf.seekg(0, std::ios_base::beg);\n\tf.read((char *)&r[0], r.size());\n\treturn r;\n}\n\nint main(int argc, char **argv) {\n\tstring mot_name;\n\tstring port_name(\"COM1\");\n\tint init_speed = 9600;\n\tint alt_speed = 0;\n\tdouble target_clock = 20.0;\n\n\twhile (--argc) {\n\t\tstring arg(*++argv);\n\t\tif (arg.empty()) continue;\n\t\tif (arg[0]=='-') {\n\t\t\tif (arg.length()==1) {\n\t\t\t\tif (--argc) mot_name = *++argv;\n\t\t\t\telse ++argc;\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tswitch (arg[1]) {\n\t\t\t\tcase 'h': help(); continue;\n\t\t\t\tcase 'p': port_name = get_option_arg(argc, argv); continue;\n\t\t\t\tcase 's': init_speed = boost::lexical_cast<int>(get_option_arg(argc, argv)); continue;\n\t\t\t\tcase 'c': target_clock = boost::lexical_cast<double>(get_option_arg(argc, argv)); continue;\n\t\t\t\tcase 't': alt_speed = boost::lexical_cast<int>(get_option_arg(argc, argv)); continue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcerr << \"unknown option: '\" << arg << \"'\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (mot_name.empty()) mot_name = std::move(arg);\n\t\telse cerr << \"multiple target files. ignored.\\n\";\n\t}\n\tif (mot_name.empty()) {\n\t\tcerr << \"target file must be set\\n\";\n\t\treturn 1;\n\t}\n\n\tasio::io_service serv;\n\tasio::serial_port ser(serv, port_name);\n\tser.set_option(asio::serial_port::baud_rate(init_speed));\n\tser.set_option(asio::serial_port::flow_control());\n\tser.set_option(asio::serial_port::parity());\n\tser.set_option(asio::serial_port::stop_bits());\n\tser.set_option(asio::serial_port::character_size());\n\n\tconst auto sendb = [&ser](unsigned char b) {\n\t\tasio::write(ser, asio::buffer(&b, 1));\n\t};\n\tconst auto sendw = [&ser](uint16_t w) {\n\t\tconst unsigned char a[] = { (unsigned char)(w>>8), (unsigned char)w };\n\t\tasio::write(ser, asio::buffer(a));\n\t};\n\tconst auto sendl = [&ser](uint32_t l) {\n\t\tconst unsigned char a[] = { (unsigned char)(l>>24), (unsigned char)(l>>16), (unsigned char)(l>>8), (unsigned char)(l) };\n\t\tasio::write(ser, asio::buffer(a));\n\t};\n\tconst auto recvb = [&ser]() -> unsigned char {\n\t\tunsigned char c;\n\t\tasio::read(ser, asio::buffer(&c, 1));\n\t\treturn c;\n\t};\n\n\tauto romdata(parse_srec<deque<unsigned char>>(read_file(mot_name)));\n\tromdata.resize(((romdata.size()-1)|0x000000FF)+1, 0xFF);\n\n\t{\n\t\tcout << \"synchronizing\" << flush;\n\t\tunsigned char c;\n\t\tconst array<unsigned char, 256> zeroes = {{}};\n\t\tbool synced = false;\n\t\tasio::async_read(ser, asio::buffer(&c, 1), [&synced](error_code ec, size_t) { synced = true; });\n\t\tfor (unsigned n = 0; n < static_cast<unsigned>(-1) && !synced; ++n) {\n\t\t\tcout << '.' << flush;\n\t\t\tasio::async_write(ser, asio::buffer(zeroes), [](error_code ec, size_t) { });\n\t\t\tserv.run_one();\n\t\t}\n\t\tser.cancel();\n\t\tif (!synced) {\n\t\t\tcerr << \"no responce from target.\\n\";\n\t\t\treturn 2;\n\t\t}\n\t\trequire(c, 0x00);\n\t\tcout << \" done.\" << endl;\n\t} {\n\t\tcout << \"erasing...\" << flush;\n\t\tsendb(0x55);\n\t\tunsigned char c;\n\t\twhile ((c=recvb()) == 0x00);\n\t\trequire(c, 0xAA);\n\t\tcout << \" done.\" << endl;\n\t} {\n\t\tconst vector<unsigned char> stub(stub_h8tiny, stub_h8tiny+sizeof(stub_h8tiny));\n\t\tcout << \"sending stub (\" << stub.size() << \"B) \" << flush;\n\t\tsendw(stub.size()&0xFFFF);\n\t\tcout << '.' << flush;\n\t\trecvb(); recvb();\n\t\tfor (unsigned n=0; n<stub.size(); ++n) {\n\t\t\tif (n%16==0) cout << '.' << flush;\n\t\t\tsendb(stub[n]);\n\t\t\trecvb();\n\t\t}\n\t\trequire(recvb(), 0xAA);\n\t\tcout << \"done.\" << endl;\n\t} {\n\t\tcout << \"writing \" << mot_name << \" (\" << (romdata.size()/1024) << \"KiB) \"<< flush;\n\t\trequire(recvb(), 'B');\n\t\tcout << '.' << flush;\n\t\tconst int baud = alt_speed ? alt_speed : init_speed;\n\t\tconst unsigned char spdchr = static_cast<unsigned char>(round(target_clock / 32 / baud * 1000000 - 1));\n\t\tsendb(spdchr);\n\t\trequire(recvb(), spdchr);\n\t\tser.set_option(asio::serial_port::baud_rate(baud));\n\t\twhile (recvb() != 'S');\n\t\tdo {\n\t\t\tsendb('s');\n\t\t} while (recvb() != 'T') ;\n\t\tsendb('t');\n\t\tcout << '.' << flush;\n\t\tconst uint16_t m = static_cast<uint16_t>(romdata.size()>>8);\n\t\tsendw(m);\n\t\tfor (uint32_t n = 0; n < m; ++n) {\n\t\t\trequire(recvb(), 'A');\n\t\t\tcout << '.' << flush;\n\t\t\tasio::write(ser, asio::buffer(&romdata[n*256], 128));\n\t\t\trequire(recvb(), 'A');\n\t\t\tasio::write(ser, asio::buffer(&romdata[n*256+128], 128));\n\t\t}\n\t\trequire(recvb(), 'F');\n\t\tcout << \"done.\" << endl;\n\t}\n\tcout << \"finish.\" << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "35dee3df75d4e598c5b2a067af629de031326fae", "size": 8033, "ext": "cc", "lang": "C++", "max_stars_repo_path": "yaki-h8tiny.cc", "max_stars_repo_name": "kikairoya/yaki-h8", "max_stars_repo_head_hexsha": "5b697faa28bde2b3211bc8920feeec2f2163fb2f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-29T12:40:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-29T12:40:36.000Z", "max_issues_repo_path": "yaki-h8tiny.cc", "max_issues_repo_name": "kikairoya/yaki-h8", "max_issues_repo_head_hexsha": "5b697faa28bde2b3211bc8920feeec2f2163fb2f", "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": "yaki-h8tiny.cc", "max_forks_repo_name": "kikairoya/yaki-h8", "max_forks_repo_head_hexsha": "5b697faa28bde2b3211bc8920feeec2f2163fb2f", "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.428030303, "max_line_length": 134, "alphanum_fraction": 0.6000248973, "num_tokens": 2616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.17346905757350595}}
{"text": "#pragma once\n#include <fc/static_variant.hpp>\n#include <scorum/protocol/betting/wincase.hpp>\n#include <scorum/protocol/betting/market_kind.hpp>\n#include <scorum/protocol/config.hpp>\n\n#include <boost/range/algorithm/transform.hpp>\n\nnamespace scorum {\nnamespace protocol {\n\ntemplate <market_kind kind, typename tag = void> struct over_under_market\n{\n    int16_t threshold;\n\n    template <bool site> using wincase = over_under_wincase<site, kind, tag>;\n    using over = wincase<true>;\n    using under = wincase<false>;\n    static constexpr market_kind kind_v = kind;\n\n    bool has_trd_state() const\n    {\n        return threshold % SCORUM_BETTING_THRESHOLD_FACTOR == 0;\n    }\n};\n\ntemplate <market_kind kind, typename tag = void> struct score_yes_no_market\n{\n    uint16_t home;\n    uint16_t away;\n\n    template <bool site> using wincase = score_yes_no_wincase<site, kind, tag>;\n    using yes = wincase<true>;\n    using no = wincase<false>;\n    static constexpr market_kind kind_v = kind;\n\n    bool has_trd_state() const\n    {\n        return false;\n    }\n};\n\ntemplate <market_kind kind, typename tag = void> struct yes_no_market\n{\n    template <bool site> using wincase = yes_no_wincase<site, kind, tag>;\n    using yes = wincase<true>;\n    using no = wincase<false>;\n    static constexpr market_kind kind_v = kind;\n\n    bool has_trd_state() const\n    {\n        return false;\n    }\n};\n\nstruct home_tag;\nstruct away_tag;\nstruct draw_tag;\nstruct both_tag;\n\nusing result_home = yes_no_market<market_kind::result, home_tag>;\nusing result_draw = yes_no_market<market_kind::result, draw_tag>;\nusing result_away = yes_no_market<market_kind::result, away_tag>;\n\nusing round_home = yes_no_market<market_kind::round>;\n\nusing handicap = over_under_market<market_kind::handicap>;\n\nusing correct_score_home = yes_no_market<market_kind::correct_score, home_tag>;\nusing correct_score_draw = yes_no_market<market_kind::correct_score, draw_tag>;\nusing correct_score_away = yes_no_market<market_kind::correct_score, away_tag>;\nusing correct_score = score_yes_no_market<market_kind::correct_score>;\n\nusing goal_home = yes_no_market<market_kind::goal, home_tag>;\nusing goal_both = yes_no_market<market_kind::goal, both_tag>;\nusing goal_away = yes_no_market<market_kind::goal, away_tag>;\n\nusing total = over_under_market<market_kind::total>;\n\nusing total_goals_home = over_under_market<market_kind::total_goals, home_tag>;\nusing total_goals_away = over_under_market<market_kind::total_goals, away_tag>;\n\nusing market_type = fc::static_variant<result_home,\n                                       result_draw,\n                                       result_away,\n                                       round_home,\n                                       handicap,\n                                       correct_score_home,\n                                       correct_score_draw,\n                                       correct_score_away,\n                                       correct_score,\n                                       goal_home,\n                                       goal_both,\n                                       goal_away,\n                                       total,\n                                       total_goals_home,\n                                       total_goals_away>;\n\nusing wincase_type = fc::static_variant<result_home::yes,\n                                        result_home::no,\n                                        result_draw::yes,\n                                        result_draw::no,\n                                        result_away::yes,\n                                        result_away::no,\n                                        round_home::yes,\n                                        round_home::no,\n                                        handicap::over,\n                                        handicap::under,\n                                        correct_score_home::yes,\n                                        correct_score_home::no,\n                                        correct_score_draw::yes,\n                                        correct_score_draw::no,\n                                        correct_score_away::yes,\n                                        correct_score_away::no,\n                                        correct_score::yes,\n                                        correct_score::no,\n                                        goal_home::yes,\n                                        goal_home::no,\n                                        goal_both::yes,\n                                        goal_both::no,\n                                        goal_away::yes,\n                                        goal_away::no,\n                                        total::over,\n                                        total::under,\n                                        total_goals_home::over,\n                                        total_goals_home::under,\n                                        total_goals_away::over,\n                                        total_goals_away::under>;\n\nstd::pair<wincase_type, wincase_type> create_wincases(const market_type& market);\nwincase_type create_opposite(const wincase_type& wincase);\nmarket_type create_market(const wincase_type& wincase);\nbool has_trd_state(const market_type& market);\nbool match_wincases(const wincase_type& lhs, const wincase_type& rhs);\n\nmarket_kind get_market_kind(const wincase_type& wincase);\n\ntemplate <typename T> std::set<market_kind> get_markets_kind(const T& markets)\n{\n    std::set<market_kind> actual_markets;\n    boost::transform(markets, std::inserter(actual_markets, actual_markets.begin()), [](const market_type& m) {\n        return m.visit([&](const auto& market_impl) { return market_impl.kind_v; });\n    });\n\n    return actual_markets;\n}\n\ntemplate <typename T> bool is_belong_markets(const wincase_type& wincase, const T& markets)\n{\n    const auto wincase_market = create_market(wincase);\n\n    for (const auto& market : markets)\n    {\n        if (wincase_market == market)\n            return true;\n    }\n\n    return false;\n}\n\n} // namespace protocol\n} // namespace scorum\n\n#include <scorum/protocol/betting/wincase_comparison.hpp>\n#include <scorum/protocol/betting/market_comparison.hpp>\n\nnamespace fc {\nusing scorum::protocol::market_type;\nusing scorum::protocol::wincase_type;\n\ntemplate <> void to_variant(const wincase_type& wincase, fc::variant& variant);\ntemplate <> void from_variant(const fc::variant& variant, wincase_type& wincase);\n\ntemplate <> void to_variant(const market_type& market, fc::variant& var);\ntemplate <> void from_variant(const fc::variant& var, market_type& market);\n}\n\nFC_REFLECT_EMPTY(scorum::protocol::result_home)\nFC_REFLECT_EMPTY(scorum::protocol::result_draw)\nFC_REFLECT_EMPTY(scorum::protocol::result_away)\nFC_REFLECT_EMPTY(scorum::protocol::round_home)\nFC_REFLECT(scorum::protocol::handicap, (threshold))\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_home)\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_draw)\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_away)\nFC_REFLECT(scorum::protocol::correct_score, (home)(away))\nFC_REFLECT_EMPTY(scorum::protocol::goal_home)\nFC_REFLECT_EMPTY(scorum::protocol::goal_both)\nFC_REFLECT_EMPTY(scorum::protocol::goal_away)\nFC_REFLECT(scorum::protocol::total, (threshold))\nFC_REFLECT(scorum::protocol::total_goals_home, (threshold))\nFC_REFLECT(scorum::protocol::total_goals_away, (threshold))\n\nFC_REFLECT_EMPTY(scorum::protocol::result_home::yes)\nFC_REFLECT_EMPTY(scorum::protocol::result_home::no)\nFC_REFLECT_EMPTY(scorum::protocol::result_draw::yes)\nFC_REFLECT_EMPTY(scorum::protocol::result_draw::no)\nFC_REFLECT_EMPTY(scorum::protocol::result_away::yes)\nFC_REFLECT_EMPTY(scorum::protocol::result_away::no)\nFC_REFLECT_EMPTY(scorum::protocol::round_home::yes)\nFC_REFLECT_EMPTY(scorum::protocol::round_home::no)\nFC_REFLECT(scorum::protocol::handicap::over, (threshold))\nFC_REFLECT(scorum::protocol::handicap::under, (threshold))\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_home::yes)\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_home::no)\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_draw::yes)\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_draw::no)\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_away::yes)\nFC_REFLECT_EMPTY(scorum::protocol::correct_score_away::no)\nFC_REFLECT(scorum::protocol::correct_score::yes, (home)(away))\nFC_REFLECT(scorum::protocol::correct_score::no, (home)(away))\nFC_REFLECT_EMPTY(scorum::protocol::goal_home::yes)\nFC_REFLECT_EMPTY(scorum::protocol::goal_home::no)\nFC_REFLECT_EMPTY(scorum::protocol::goal_both::yes)\nFC_REFLECT_EMPTY(scorum::protocol::goal_both::no)\nFC_REFLECT_EMPTY(scorum::protocol::goal_away::yes)\nFC_REFLECT_EMPTY(scorum::protocol::goal_away::no)\nFC_REFLECT(scorum::protocol::total::over, (threshold))\nFC_REFLECT(scorum::protocol::total::under, (threshold))\nFC_REFLECT(scorum::protocol::total_goals_home::over, (threshold))\nFC_REFLECT(scorum::protocol::total_goals_home::under, (threshold))\nFC_REFLECT(scorum::protocol::total_goals_away::over, (threshold))\nFC_REFLECT(scorum::protocol::total_goals_away::under, (threshold))\n", "meta": {"hexsha": "9b52892eac05dc229e55bcbb9214c1db73817838", "size": 9115, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/protocol/include/scorum/protocol/betting/market.hpp", "max_stars_repo_name": "scorum/scorum", "max_stars_repo_head_hexsha": "1da00651f2fa14bcf8292da34e1cbee06250ae78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:20:48.000Z", "max_issues_repo_path": "libraries/protocol/include/scorum/protocol/betting/market.hpp", "max_issues_repo_name": "Scorum/Scorum", "max_issues_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2017-11-25T09:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T09:17:22.000Z", "max_forks_repo_path": "libraries/protocol/include/scorum/protocol/betting/market.hpp", "max_forks_repo_name": "Scorum/Scorum", "max_forks_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T19:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:50:42.000Z", "avg_line_length": 40.6919642857, "max_line_length": 111, "alphanum_fraction": 0.6357652222, "num_tokens": 2006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1734596526523011}}
{"text": "// Copyright 2019 Intel Corporation.\n\n#include \"tile/lang/ast/gradient.h\"\n\n#include <map>\n#include <memory>\n#include <stack>\n#include <unordered_set>\n\n#include <boost/format.hpp>\n\n#include \"tile/lang/ast/traversal.h\"\n\nnamespace vertexai {\nnamespace tile {\nnamespace lang {\nnamespace ast {\n\nnamespace {\n\nstruct UseInfo {\n  ExprPtr expr;\n  size_t idx;\n};\n\nclass ComputeUses : public AstVisitor<void> {\n public:\n  explicit ComputeUses(const ExprPtr& src) {\n    stack_.push(src);\n    while (stack_.size()) {\n      auto expr = stack_.top();\n      stack_.pop();\n      if (!seen_.count(expr.get())) {\n        seen_.insert(expr.get());\n        expr->Accept(this);\n      }\n    }\n  }\n\n  const std::vector<UseInfo>& uses(const Expr* expr) const { return uses_.at(expr); }\n\n private:\n  void Visit(const CallExpr& expr) final {\n    for (size_t i = 0; i < expr.args.size(); i++) {\n      Push(expr, expr.args[i], i);\n    }\n  }\n\n  void Visit(const ContractionExpr& expr) final {\n    for (size_t i = 0; i < expr.srcs.size(); i++) {\n      Push(expr, expr.srcs[i]->ref, i);\n    }\n    if (expr.use_default) {\n      Push(expr, expr.use_default, expr.srcs.size());\n    }\n  }\n\n  void Visit(const DimExprExpr& expr) final {}\n  void Visit(const FloatConst& expr) final {}\n  void Visit(const IntConst& expr) final {}\n  void Visit(const ParamExpr& expr) final {}\n\n private:\n  void Push(const Expr& user, const ExprPtr& used, size_t idx) {\n    IVLOG(4, \"ComputeUses::Push> user: \" << &user << \", used: \" << used << \", idx: \" << idx);\n    auto ptr = std::const_pointer_cast<Expr>(user.as_ptr());\n    uses_[used.get()].emplace_back(UseInfo{ptr, idx});\n    stack_.push(used);\n  }\n\n private:\n  std::stack<ExprPtr> stack_;\n  std::unordered_set<const Expr*> seen_;\n  std::unordered_map<const Expr*, std::vector<UseInfo>> uses_;\n};\n\nclass Gradient {\n public:\n  explicit Gradient(const ExprPtr& err) : uses_(err) {\n    IVLOG(4, \"Gradient::Gradient> err: \" << err);\n    seen_[err.get()] = std::make_shared<FloatConst>(1.0);\n  }\n\n  ExprPtr GetDerivative(const ExprPtr& expr) {\n    IVLOG(4, \"Gradient::GetDerivative> \" << expr);\n    auto it = seen_.find(expr.get());\n    if (it != seen_.end()) {\n      IVLOG(5, \"  returning: \" << it->second);\n      return it->second;\n    }\n    ExprPtr total;\n    for (const auto& use : uses_.uses(expr.get())) {\n      ExprPtr dop;\n      auto dout = GetDerivative(use.expr);\n      if (auto call_expr = std::dynamic_pointer_cast<CallExpr>(use.expr)) {\n        dop = DeriveCall(dout, call_expr, use.idx);\n      } else if (auto cion_expr = std::dynamic_pointer_cast<ContractionExpr>(use.expr)) {\n        dop = DeriveContraction(dout, cion_expr, use.idx);\n      } else {\n        throw std::runtime_error(\"Invalid operation type in Gradient::GetDerivative\");\n      }\n      if (!total) {\n        total = dop;\n      } else {\n        total = MakeCall(\"add\", {total, dop});\n      }\n    }\n    if (!total) {\n      total = std::make_shared<FloatConst>(0.0);\n    } else if (total->shape.dims.size()) {\n      total = MakeCall(\"simple_reduce\", {total, expr});\n    }\n    IVLOG(4, \"  Gradient::GetDerivative, final result -> \" << total);\n    seen_.emplace(expr.get(), total);\n    return total;\n  }\n\n private:\n  ExprPtr DeriveContraction(const ExprPtr& dout, const std::shared_ptr<ContractionExpr>& expr, size_t idx) {\n    if (expr->use_default && idx == expr->srcs.size()) {\n      return dout;\n    }\n    if (expr->combo_op == CombinationOp::EQ) {\n      return std::make_shared<IntConst>(0);\n    }\n    if (expr->agg_op == AggregationOp::SUM || expr->agg_op == AggregationOp::ASSIGN) {\n      return DeriveSum(dout, expr, idx);\n    }\n    if (expr->agg_op == AggregationOp::MIN || expr->agg_op == AggregationOp::MAX) {\n      return DeriveExtreme(dout, expr, idx);\n    }\n    if (expr->agg_op == AggregationOp::PROD) {\n      throw std::runtime_error(\"PROD AggregationOp does not support differentiation\");\n    }\n    throw std::runtime_error(\"Invalid ContractionExpr in DeriveContraction\");\n  }\n\n  ExprPtr DeriveCall(const ExprPtr& dout, const std::shared_ptr<CallExpr>& op, size_t idx) {\n    IVLOG(4, \"Gradient::DeriveCall> dout=\" << dout << \", op=\" << op << \", fn=\" << op->fn << \", idx=\" << idx);\n    if (op->fn == \"reshape\") {\n      std::vector<ExprPtr> args = {dout};\n      auto in = op->args[0];\n      auto dim_exprs = in->shape.dims_as_exprs();\n      for (size_t i = 0; i < in->shape.dims.size(); ++i) {\n        args.push_back(std::make_shared<DimExprExpr>(dim_exprs[i]));\n      }\n      return MakeCall(\"reshape\", args);\n    }\n    auto deriv = DerivRegistry::Instance()->Resolve(op->fn);\n    return deriv.fn(op, dout, op->args, deriv.user_fn, deriv.user_ctx)[idx];\n  }\n\n  ExprPtr DeriveSum(const ExprPtr& dout, const std::shared_ptr<ContractionExpr>& op, size_t idx) {\n    IVLOG(4, \"Gradient::DeriveSum> dout=\" << dout << \", op=\" << op << \", idx=\" << idx);\n    auto dop = std::make_shared<ContractionExpr>();\n    dop->agg_op = AggregationOp::SUM;\n    dop->combo_op = CombinationOp::NONE;  // May be overridden below based on op->combo_op\n    dop->constraints = op->constraints;\n    // Anywhere the forward pass hits the default, the derivative w.r.t. any other tensor is 0;\n    // thus, for the corresponding gradient, the default is everywhere zero i.e. the standard unspecified default\n    if (idx == op->srcs.size()) {\n      throw std::logic_error(\"A default tensor fell through to the DeriveSum case during Gradient\");\n    }\n    for (size_t i = 0; i < op->srcs.size(); ++i) {\n      if (idx == i) {\n        dop->srcs.push_back(std::make_shared<IndexMapExpr>(dout, op->sink_idxs->idxs));\n      } else {\n        switch (op->combo_op) {\n          case CombinationOp::MULTIPLY:\n            // For *, we multiply by the other (non-differentiated) input\n            dop->srcs.push_back(op->srcs[i]);\n            dop->combo_op = CombinationOp::MULTIPLY;\n            break;\n          case CombinationOp::PLUS:\n            // For +, we ignore the other (non-differentiated) input\n            dop->combo_op = CombinationOp::NONE;\n            break;\n          case CombinationOp::COND:\n            throw std::runtime_error(\"Gradient of sum of conditionals not supported\");\n          case CombinationOp::NONE:\n            throw std::runtime_error(\n                \"Unexpected multiple inputs found when differentiating contraction with NONE combination op\");\n          case CombinationOp::EQ:\n            throw std::runtime_error(\"Gradient of sum of equalities not supported\");\n          default:\n            throw std::runtime_error(\"Failed to recognize combination op during differentiation\");\n        }\n      }\n    }\n    auto input = op->srcs[idx];\n    dop->sink_idxs = std::make_shared<IndexMapExpr>(nullptr, input->idxs);\n    dop->sink_dims = std::make_shared<SizeMapExpr>(input->ref->shape.dims_as_exprs());\n    dop->ComputeShape(input->ref->shape.layout);\n    return dop;\n  }\n\n  ExprPtr DeriveExtreme(const ExprPtr& dout, const std::shared_ptr<ContractionExpr>& op, size_t idx) {\n    // Given `O(oidxs) >= I(iidxs);` (or a MIN aggregation too), produce the derivative\n    //  ```dI(iidxs) += (I(iidxs) == O(oidxs)) ? dO(oidxs);```\n    // where the above notation is meant to represent a COND combination op\n    IVLOG(4, \"Gradient::DeriveExtreme> dout=\" << dout << \", op=\" << op << \", idx=\" << idx);\n    auto input = op->srcs[0];\n    auto dop = std::make_shared<ContractionExpr>();\n    dop->agg_op = AggregationOp::SUM;\n    dop->combo_op = CombinationOp::COND;\n    dop->constraints = op->constraints;\n    // Anywhere the forward pass hits the default, the derivative w.r.t. any other tensor is 0;\n    // thus, for the corresponding gradient, the default is everywhere zero i.e. the standard unspecified default\n    dop->srcs.push_back(input);\n    dop->srcs.push_back(std::make_shared<IndexMapExpr>(op, op->sink_idxs->idxs));\n    dop->srcs.push_back(std::make_shared<IndexMapExpr>(dout, op->sink_idxs->idxs));\n    dop->sink_idxs = std::make_shared<IndexMapExpr>(nullptr, input->idxs);\n    dop->sink_dims = std::make_shared<SizeMapExpr>(input->ref->shape.dims_as_exprs());\n    dop->ComputeShape(input->ref->shape.layout);\n    return dop;\n  }\n\n private:\n  ComputeUses uses_;\n  std::map<const Expr*, ExprPtr> seen_;\n};\n\n}  // namespace\n\nstd::vector<ExprPtr> ComputeGradients(const std::vector<ExprPtr>& wrts, const ExprPtr& loss) {\n  ExprPtr value = loss;\n  auto ndims = loss->shape.dims.size();\n  if (ndims) {\n    auto cion = std::make_shared<ContractionExpr>();\n    cion->agg_op = AggregationOp::SUM;\n    cion->combo_op = CombinationOp::NONE;\n    std::vector<PolyExprPtr> idxs;\n    for (size_t i = 0; i < ndims; i++) {\n      idxs.push_back(std::make_shared<PolyIndex>(i));\n    }\n    cion->srcs = {std::make_shared<IndexMapExpr>(loss, idxs)};\n    cion->sink_idxs = std::make_shared<IndexMapExpr>(nullptr, std::vector<PolyExprPtr>{});\n    cion->sink_dims = std::make_shared<SizeMapExpr>(std::vector<DimExprPtr>{});\n    cion->ComputeShape(\"\");\n    value = cion;\n  }\n  Gradient grad(value);\n  std::vector<ExprPtr> ret(wrts.size());\n  for (size_t i = 0; i < wrts.size(); i++) {\n    ret[i] = grad.GetDerivative(wrts[i]);\n  }\n  return ret;\n}\n\n}  // namespace ast\n}  // namespace lang\n}  // namespace tile\n}  // namespace vertexai\n", "meta": {"hexsha": "0f9a84954c22ff8798d38cd2708582e9d9e49558", "size": 9194, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tile/lang/ast/gradient.cc", "max_stars_repo_name": "TolyaTalamanov/plaidml", "max_stars_repo_head_hexsha": "275a79cd640def34c1b7bc7053397f5989ef55c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T11:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-11T11:18:50.000Z", "max_issues_repo_path": "tile/lang/ast/gradient.cc", "max_issues_repo_name": "HubBucket-Team/plaidml", "max_issues_repo_head_hexsha": "762d5fff6467b43a15623f927502892ce8df91a4", "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": "tile/lang/ast/gradient.cc", "max_forks_repo_name": "HubBucket-Team/plaidml", "max_forks_repo_head_hexsha": "762d5fff6467b43a15623f927502892ce8df91a4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T11:18:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T11:18:52.000Z", "avg_line_length": 36.1968503937, "max_line_length": 113, "alphanum_fraction": 0.6319338699, "num_tokens": 2526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.173459652652301}}
{"text": "#include \"utils.h\"\n#include \"GL/glwrapper.h\"\n#include \"ImGuizmo/ImGuizmo.h\"\n\n#include <Eigen/Dense>\n#include <boost/program_options.hpp>\n#include <thread>\n\nglm::vec2 clicked_point;\nfloat rot_x =0.0f;\nfloat rot_y =0.0f;\nbool drawing_buffer_dirty = true;\nglm::vec3 view_translation{ 0,0,-30 };\n\nvoid cursor_calback(GLFWwindow* window, double xpos, double ypos)\n{\n    ImGuiIO& io = ImGui::GetIO();\n    if(!io.WantCaptureMouse) {\n        const glm::vec2 p{-xpos, ypos};\n        const auto d = clicked_point - p;\n        if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1) == GLFW_PRESS) {\n            rot_x += 0.01 * d[1];\n            rot_y += 0.01 * d[0];\n        }\n        if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_2) == GLFW_PRESS) {\n            view_translation[2] += 0.02 * d[1];\n        }\n        if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_3) == GLFW_PRESS) {\n            view_translation[1] += 0.01 * d[1];\n            view_translation[0] -= 0.01 * d[0];\n        }\n        clicked_point = p;\n    }\n}\nvoid framebuffer_size_callback(GLFWwindow* window, int width, int height)\n{\n    glViewport(0, 0, width, height);\n}\n\n\nint main(int argc, char **argv) {\n\n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"mirror_config\", po::value<std::string>()->required(), \"path to mirror mesh PLY.\");\n\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    {\n        std::cout << desc << \"\\n\";\n        return false;\n    }\n\n\n    bool gl_dirty = false;\n\n    // Loading mirrrors initial params\n    std::vector<catoptric_livox::Mirror> mirrors = catoptric_livox::loadMirrorFromPLY(vm[\"mirror_config\"].as<std::string>());\n\n    std::vector<std::pair<double,double>> angle_mask;\n\n    GLFWwindow *window;\n    const char *glsl_version = \"#version 130\";\n    if (!glfwInit())\n        return -1;\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n    window = glfwCreateWindow(960, 540, \"Simulation\", NULL, NULL);\n    if (!window) {\n        glfwTerminate();\n        return -1;\n    }\n    glfwMakeContextCurrent(window);\n    glfwSetCursorPosCallback(window, cursor_calback);\n    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);\n\n    glfwSwapInterval(1);\n    if (glewInit() != GLEW_OK) { return -1; }\n\n    GLCall(glClearColor(1.0, 1.0, 1.0, 1));\n\n    Renderer renderer;\n\n    Shader shader(shader_simple_v, shader_simple_f);\n\n    VertexBufferLayout layout;\n    layout.Push<float>(3);\n    layout.Push<float>(3);\n\n    VertexArray va_co;\n    VertexBuffer vb_co(gl_primitives::coordinate_system_vertex.data(),\n                       gl_primitives::coordinate_system_vertex.size() * sizeof(float));\n    va_co.AddBuffer(vb_co, layout);\n    IndexBuffer ib_co(gl_primitives::coordinate_system_indices.data(), gl_primitives::coordinate_system_indices.size());\n\n    std::vector<float> mirrors_vertices;\n    std::vector<unsigned int> mirrors_indices;\n    catoptric_livox::updateDrawingBuffer(mirrors, mirrors_vertices, mirrors_indices);\n    VertexArray va_mirror;\n    VertexBuffer vb_mirror(mirrors_vertices.data(),\n                           mirrors_vertices.size() * sizeof(float));\n    va_mirror.AddBuffer(vb_mirror, layout);\n    IndexBuffer ib_mirror(mirrors_indices.data(), mirrors_indices.size());\n\n    std::vector<float> ray_vertices;\n    std::vector<unsigned int> ray_indicies;\n    float all_points = 0;\n    float classified = 0;\n\n    for (float i = -38.4/2; i <0; i+=1)\n    {\n        for (float j = 0;j < 360; j+=0.25) {\n            Eigen::Vector3f  color{0,0,0};\n            Eigen::Affine3d mat1(Eigen::Matrix4d::Identity());\n            Eigen::Affine3d mat2(Eigen::Matrix4d::Identity());\n\n            mat1.rotate(Eigen::AngleAxisd(M_PI * i / 180.0, Eigen::Vector3d::UnitZ()));\n            mat2.rotate(Eigen::AngleAxisd(M_PI * j / 180.0, Eigen::Vector3d::UnitX()));\n\n            Eigen::Affine3d mat3 = mat1 * mat2;\n\n\n            Eigen::Vector3d p_local{10*mat3(0, 0), 10*mat3(0, 1), 10*mat3(0, 2)};\n            double p_local_l = p_local.norm();\n            Eigen::Vector3d p_local_norm = p_local / p_local_l;\n\n            int mirror_id = -1;\n            for (int m = 0; m < mirrors.size();m++)\n            {\n                if (mirrors[m].checkIfRayIntersectMirror(Eigen::Vector3d::Zero(),p_local)) {\n                    mirror_id = m;\n                }\n            }\n            all_points++;\n            if (mirror_id==-1) {continue;}\n\n            classified++;\n            color = catoptric_livox::mirror_colors[mirror_id];\n            color = color *0.5;\n            ray_vertices.push_back(0);\n            ray_vertices.push_back(0);\n            ray_vertices.push_back(0);\n            ray_vertices.push_back(color.x());\n            ray_vertices.push_back(color.y());\n            ray_vertices.push_back(color.z());\n\n            const Eigen::Vector4d plane = mirrors[mirror_id].getABCDofPlane();\n\n            Eigen::Vector3d p_glob = catoptric_livox::getMirroredRayIntersection(p_local_norm, p_local_l,plane);\n\n            ray_vertices.push_back(p_glob.x());\n            ray_vertices.push_back(p_glob.y());\n            ray_vertices.push_back(p_glob.z());\n            ray_vertices.push_back(color.x());\n            ray_vertices.push_back(color.y());\n            ray_vertices.push_back(color.z());\n\n            ray_indicies.push_back(ray_indicies.size());\n            ray_indicies.push_back(ray_indicies.size());\n\n            ray_vertices.push_back(p_glob.x());\n            ray_vertices.push_back(p_glob.y());\n            ray_vertices.push_back(p_glob.z());\n            ray_vertices.push_back(color.x());\n            ray_vertices.push_back(color.y());\n            ray_vertices.push_back(color.z());\n\n            Eigen::Vector3d p_glob2 = catoptric_livox::getMirroredRay(p_local_norm, p_local_l,plane);\n\n            ray_vertices.push_back(p_glob2.x());\n            ray_vertices.push_back(p_glob2.y());\n            ray_vertices.push_back(p_glob2.z());\n            ray_vertices.push_back(color.x());\n            ray_vertices.push_back(color.y());\n            ray_vertices.push_back(color.z());\n\n\n            ray_indicies.push_back(ray_indicies.size());\n            ray_indicies.push_back(ray_indicies.size());\n        }\n    }\n    std::cout << \" classified to all points \"  << classified/all_points <<std::endl;\n\n    VertexArray va_ray;\n    VertexBuffer vb_ray(ray_vertices.data(),\n                               ray_vertices.size() * sizeof(float));\n    va_ray.AddBuffer(vb_ray, layout);\n    IndexBuffer ib_ray(ray_indicies.data(), ray_indicies.size());\n\n    auto mat = Eigen::Affine3d::Identity();\n    mat.rotate(Eigen::AngleAxisd(-M_PI/2, Eigen::Vector3d::UnitX()));\n\n    std::vector<float> nns_vertices;\n    std::vector<unsigned int> nns_indices;\n    VertexArray va_nns;\n    VertexBuffer vb_nns(nns_vertices.data(),\n                        nns_vertices.size() * sizeof(float));\n    va_nns.AddBuffer(vb_nns, layout);\n    IndexBuffer ib_nns(nns_indices.data(), nns_indices.size());\n\n    ImGui::CreateContext();\n    ImGui::StyleColorsDark();\n    ImGui_ImplGlfw_InitForOpenGL(window, false);\n    ImGui_ImplOpenGL3_Init(glsl_version);\n    glm::mat4 glm_test {glm::mat4(1.0f)};\n\n    while (!glfwWindowShouldClose(window)) {\n\n        GLCall(glEnable(GL_DEPTH_TEST));\n        GLCall(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n        ImGui_ImplOpenGL3_NewFrame();\n        ImGui_ImplGlfw_NewFrame();\n        ImGui::NewFrame();\n\n        ImGuizmo::BeginFrame();\n        ImGuizmo::Enable(true);\n        ImGuiIO &io = ImGui::GetIO();\n        ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);\n\n        ImGuizmo::Enable(true);\n        int width, height;\n        glfwGetWindowSize(window, &width, &height);\n        glm::mat4 proj = glm::perspective(30.f, 1.0f * width / height, 0.05f, 100.0f);\n        glm::mat4 model_translate = glm::translate(glm::mat4(1.0f), view_translation);\n        glm::mat4 model_rotation_0 = glm::rotate(model_translate, float(-0.5 * M_PI), glm::vec3(0.0f, 0.0f, 1.0f));\n\n        glm::mat4 model_rotation_1 = glm::rotate(model_rotation_0, rot_x, glm::vec3(0.0f, 1.0f, 0.0f));\n        glm::mat4 model_rotation_2 = glm::rotate(model_rotation_1, rot_y, glm::vec3(1.0f, 0.0f, 0.0f));\n\n        shader.Bind(); // bind shader to apply uniform\n        // draw reference frame\n        GLCall(glPointSize(1));\n        GLCall(glLineWidth(1));\n\n        shader.setUniformMat4f(\"u_MVP\", proj * model_rotation_2);\n        renderer.Draw(va_ray, ib_ray, shader, GL_LINES);\n        renderer.Draw(va_co, ib_co, shader, GL_LINES);\n        GLCall(glLineWidth(3));\n        renderer.Draw(va_mirror, ib_mirror, shader, GL_LINES);\n        GLCall(glLineWidth(1));\n        renderer.Draw(va_nns, ib_nns, shader, GL_LINES);\n\n        for (int i = 0; i < mirrors.size(); i++) {\n            glm::mat4 tr = glm::mat4(1.0f);\n            glm::mat4 sc = glm::scale(glm::mat4(1.0f), glm::vec3(0.01f));\n            Eigen::Map<Eigen::Matrix4f> tr_e(&tr[0][0]);\n            tr_e = mirrors[i].getTransformation().matrix().cast<float>();\n            shader.setUniformMat4f(\"u_MVP\", proj * model_rotation_2 * tr * sc);\n            renderer.Draw(va_co, ib_co, shader, GL_LINES);\n        }\n\n        ImGui::Begin(\"Calibration Demo\");\n        ImGui::End();\n        ImGui::Render();\n\n        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());\n        glfwSwapBuffers(window);\n        glfwPollEvents();\n    }\n    ImGui_ImplOpenGL3_Shutdown();\n    ImGui_ImplGlfw_Shutdown();\n    ImGui::DestroyContext();\n    glfwTerminate();\n    return 0;\n}", "meta": {"hexsha": "56c256648d8ff470e15127a731a707c7428f6a47", "size": 9755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calibration_tool/simulation_gui.cpp", "max_stars_repo_name": "michalpelka/catoptric_livox", "max_stars_repo_head_hexsha": "fde4db428840509b6102ac0d2aacee6d4d973ca8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-08-18T02:42:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T12:02:22.000Z", "max_issues_repo_path": "calibration_tool/simulation_gui.cpp", "max_issues_repo_name": "michalpelka/catoptric_livox", "max_issues_repo_head_hexsha": "fde4db428840509b6102ac0d2aacee6d4d973ca8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calibration_tool/simulation_gui.cpp", "max_forks_repo_name": "michalpelka/catoptric_livox", "max_forks_repo_head_hexsha": "fde4db428840509b6102ac0d2aacee6d4d973ca8", "max_forks_repo_licenses": ["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.1296296296, "max_line_length": 125, "alphanum_fraction": 0.621937468, "num_tokens": 2519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17345964584492204}}
{"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_GENERIC_FUNCTION_GENMASK_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_GENMASK_HPP_INCLUDED\n\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/meta/as_arithmetic.hpp>\n#include <boost/simd/constant/allbits.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/detail/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\n  // -----------------------------------------------------------------------------------------------\n  // re-targeted genmask for other types\n  BOOST_DISPATCH_OVERLOAD ( genmask_\n                          , (typename A0, typename Target)\n                          , bd::cpu_\n                          , bd::scalar_< bd::unspecified_<A0> >\n                          , bd::target_< bd::generic_<bd::unspecified_<Target> > >\n                          )\n  {\n    using result_t = typename Target::type;\n    BOOST_FORCEINLINE result_t operator()( A0 const& a0, Target const& ) const BOOST_NOEXCEPT\n    {\n      return (a0!=0) ? Allbits<result_t>() : Zero<result_t>();\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "c8a7b8d8387e470634834f5a8a8b65415c370361", "size": 1598, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/boost/simd/arch/common/generic/function/genmask.hpp", "max_stars_repo_name": "chronos38/low_latency_demo", "max_stars_repo_head_hexsha": "de0d0d3dcebff23ba77c06c6c368b9d1c3d2c648", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-11-18T18:23:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-15T12:41:24.000Z", "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/genmask.hpp", "max_issues_repo_name": "dendisuhubdy/boost.simd", "max_issues_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "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/genmask.hpp", "max_forks_repo_name": "dendisuhubdy/boost.simd", "max_forks_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T20:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-11T20:18:39.000Z", "avg_line_length": 36.3181818182, "max_line_length": 100, "alphanum_fraction": 0.5394242804, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.1734596390375432}}
{"text": "#include <vector>\n#include <map>\n#include <string>\n//#include <boost/python.hpp>\n\n#include \"SSDR.h\"\n\n#define DLLEXPORT extern \"C\" __declspec(dllexport)\n\nSSDR::Output ssdrOutput;\n\nDLLEXPORT double build(int numMinBones, int numMaxInfluences, int numMaxIterations, float *bindVertices, float *animVertices, int numVertices, int numFrames)\n{\n    SSDR::Parameter ssdrParam;\n    ssdrParam.numMaxInfluences = numMaxInfluences;\n    ssdrParam.numMaxIterations = numMaxIterations;\n    ssdrParam.numMinBones = numMinBones;\n\n    SSDR::Input ssdrInput;\n    ssdrInput.numVertices = numVertices;\n    ssdrInput.numExamples = numFrames;\n    ssdrInput.bindModel.resize(ssdrInput.numVertices);\n    ssdrInput.sample.resize(ssdrInput.numVertices * numFrames);\n    for (int vid = 0; vid < ssdrInput.numVertices; ++vid)\n    {\n        ssdrInput.bindModel[vid].x = bindVertices[vid * 3 + 0];\n        ssdrInput.bindModel[vid].y = bindVertices[vid * 3 + 1];\n        ssdrInput.bindModel[vid].z = bindVertices[vid * 3 + 2];\n    }\n    for (int f = 0; f < numFrames; ++f)\n    {\n        for (int vid = 0; vid < ssdrInput.numVertices; ++vid)\n        {\n            ssdrInput.sample[f * numVertices + vid].x = animVertices[(f * numVertices + vid) * 3 + 0];\n            ssdrInput.sample[f * numVertices + vid].y = animVertices[(f * numVertices + vid) * 3 + 1];\n            ssdrInput.sample[f * numVertices + vid].z = animVertices[(f * numVertices + vid) * 3 + 2];\n        }\n    }\n\n    double sqe = SSDR::Decompose(ssdrOutput, ssdrInput, ssdrParam);\n    return std::sqrt(sqe / ssdrInput.numVertices);\n}\n\nDLLEXPORT double* getSkinningWeight()\n{\n    size_t num = ssdrOutput.weight.size();\n    double *skinningWeight = (double *)malloc(sizeof(double) * num);\n    if(skinningWeight==NULL)return NULL;\n    \n    size_t i=0;\n    for (auto it = ssdrOutput.weight.begin(); it != ssdrOutput.weight.end(); ++it,i++)\n    {\n        skinningWeight[i]=*it;\n    }\n    return skinningWeight;\n}\n\nDLLEXPORT int* getSkinningIndex()\n{\n    size_t num = ssdrOutput.index.size();\n    int *skinningIndex = (int *)malloc(sizeof(int) * num);\n    if(skinningIndex==NULL)return NULL;\n    \n    size_t i=0;\n    for (auto it = ssdrOutput.index.begin(); it != ssdrOutput.index.end(); ++it,i++)\n    {\n        skinningIndex[i]=*it;\n    }\n    return skinningIndex;\n}\n\nDLLEXPORT int getNumBones()\n{\n    return ssdrOutput.numBones;\n}\n\nDLLEXPORT float* getBoneTranslation(int boneIdx, int frame)\n{\n    float *retval = (float *)malloc(sizeof(float) * 3);\n    if(retval==NULL)return NULL;\n    \n    retval[0]=ssdrOutput.boneTrans[frame * ssdrOutput.numBones + boneIdx].Translation().x;\n    retval[1]=ssdrOutput.boneTrans[frame * ssdrOutput.numBones + boneIdx].Translation().y;\n    retval[2]=ssdrOutput.boneTrans[frame * ssdrOutput.numBones + boneIdx].Translation().z;\n    return retval;\n}\n\nDLLEXPORT float* getBoneRotation(int boneIdx, int frame)\n{\n    float *retval = (float *)malloc(sizeof(float) * 4);\n    if(retval==NULL)return NULL;\n    \n    retval[0]=ssdrOutput.boneTrans[frame * ssdrOutput.numBones + boneIdx].Rotation().x;\n    retval[1]=ssdrOutput.boneTrans[frame * ssdrOutput.numBones + boneIdx].Rotation().y;\n    retval[2]=ssdrOutput.boneTrans[frame * ssdrOutput.numBones + boneIdx].Rotation().z;\n    retval[3]=ssdrOutput.boneTrans[frame * ssdrOutput.numBones + boneIdx].Rotation().w;\n    return retval;\n}\n\nDLLEXPORT void freeRetArr(void *p)\n{\n  free(p);\n}\n", "meta": {"hexsha": "cc33a8201fe1f051453ad712a619c5368408881e", "size": 3389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/main.cpp", "max_stars_repo_name": "devil-tamachan/ssdr4maya", "max_stars_repo_head_hexsha": "910a595b5bdfe5a2327dd697f5d61b4f129ac538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-02-13T07:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T06:03:12.000Z", "max_issues_repo_path": "src/cpp/main.cpp", "max_issues_repo_name": "devil-tamachan/ssdr4blender", "max_issues_repo_head_hexsha": "910a595b5bdfe5a2327dd697f5d61b4f129ac538", "max_issues_repo_licenses": ["MIT"], "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": "devil-tamachan/ssdr4blender", "max_forks_repo_head_hexsha": "910a595b5bdfe5a2327dd697f5d61b4f129ac538", "max_forks_repo_licenses": ["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.5865384615, "max_line_length": 157, "alphanum_fraction": 0.6709943936, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.173314806201422}}
{"text": "// Copyright (c) 2015-2018 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 \"str_period.hpp\"\n\n#include <iterator>\n#include <algorithm>\n\n#include <boost/variant.hpp>\n#include <boost/optional.hpp>\n\n#include \"basics/tandem_repeat.hpp\"\n#include \"io/variant/vcf_record.hpp\"\n#include \"utils/repeat_finder.hpp\"\n#include \"../facets/reference_context.hpp\"\n\nnamespace octopus { namespace csr {\n\nconst std::string STRPeriod::name_ = \"STR_PERIOD\";\n\nstd::unique_ptr<Measure> STRPeriod::do_clone() const\n{\n    return std::make_unique<STRPeriod>(*this);\n}\n\nnamespace {\n\nstruct RepeatContextLess\n{\n    bool operator()(const TandemRepeat& lhs, const TandemRepeat& rhs) const noexcept\n    {\n        // Expand to discount possible reference pad\n        const auto expanded_lhs_region = expand_lhs(mapped_region(lhs), 1);\n        const auto expanded_rhs_region = expand_lhs(mapped_region(rhs), 1);\n        if (overlap_size(expanded_lhs_region, call_) != overlap_size(expanded_rhs_region, call_)) {\n            return overlap_size(expanded_lhs_region, call_) < overlap_size(expanded_rhs_region, call_);\n        }\n        return ends_before(lhs, rhs);\n    }\n    RepeatContextLess(const VcfRecord& call) : call_ {call} {};\nprivate:\n    const VcfRecord& call_;\n};\n\nbool could_contain(const TandemRepeat& repeat, const VcfRecord& call)\n{\n    return contains(expand(mapped_region(repeat), 1), call);\n}\n\nboost::optional<TandemRepeat> find_repeat_context(const VcfRecord& call, const Haplotype& reference)\n{\n    const auto repeats = find_exact_tandem_repeats(reference.sequence(), reference.mapped_region(), 1, 20);\n    const auto overlapping_repeats = overlap_range(repeats, expand(mapped_region(call), 1));\n    boost::optional<TandemRepeat> result {};\n    if (!empty(overlapping_repeats)) {\n        for (const auto& repeat : repeats) {\n            if (could_contain(repeat, call)) {\n                if (result) {\n                    result = std::max(repeat, *result, RepeatContextLess {call});\n                } else {\n                    result = repeat;\n                }\n            }\n        }\n        if (!result) {\n            result = *max_overlapped(repeats, call);\n        }\n    }\n    return result;\n}\n\n} // namespace\n\nMeasure::ResultType STRPeriod::do_evaluate(const VcfRecord& call, const FacetMap& facets) const\n{\n    int result {0};\n    const auto& reference = get_value<ReferenceContext>(facets.at(\"ReferenceContext\"));\n    const auto repeat_context = find_repeat_context(call, reference);\n    if (repeat_context) result = repeat_context->period();\n    return result;\n}\n\nMeasure::ResultCardinality STRPeriod::do_cardinality() const noexcept\n{\n    return ResultCardinality::one;\n}\n\nconst std::string& STRPeriod::do_name() const\n{\n    return name_;\n}\n\nstd::string STRPeriod::do_describe() const\n{\n    return \"Length of overlapping STR\";\n}\n\nstd::vector<std::string> STRPeriod::do_requirements() const\n{\n    return {\"ReferenceContext\"};\n}\n\n} // namespace csr\n} // namespace octopus\n", "meta": {"hexsha": "1891fd2aaaa7d9d75df37d02002e604ee2967d3b", "size": 3038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/csr/measures/str_period.cpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "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/csr/measures/str_period.cpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/csr/measures/str_period.cpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.9333333333, "max_line_length": 107, "alphanum_fraction": 0.6849901251, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.17331480620142198}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\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\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// Definitions corresponding to vc.hpp.\n\n#include <Eigen/Dense>\n#include <exceptions.hpp>\n#include <periodic_table.hpp>\n#include <vc.hpp>\n\nnamespace alma {\nstd::unique_ptr<Crystal_structure> vc_mix_structures(\n    const std::vector<Crystal_structure>& components,\n    const std::vector<double>& ratios) {\n    auto ncomponents = components.size();\n\n    // Perform some sanity checks. Note that even passing all of\n    // those does not guarantee that the resulting virtual crystal\n    // will make sense.\n    if (ratios.size() != ncomponents)\n        throw value_error(\"different numbers of components and ratios\");\n\n    if (ncomponents == 0)\n        throw value_error(\"no components in the virtual crystal\");\n\n    for (auto r : ratios)\n        if (r <= 0)\n            throw value_error(\"all atomic ratios must be positive\");\n    auto natoms = components[0].get_natoms();\n\n    for (decltype(ncomponents) i = 1; i < ncomponents; ++i) {\n        if (components[i].get_natoms() != natoms)\n            throw value_error(\"all components must have the same\"\n                              \" number of atoms\");\n    }\n    // Build the weighted lattice vectors.\n    double total{ratios[0]};\n    Eigen::Matrix3d lattvec(ratios[0] * components[0].lattvec);\n\n    for (decltype(ncomponents) i = 1; i < ncomponents; ++i) {\n        total += ratios[i];\n        lattvec += ratios[i] * components[i].lattvec;\n    }\n    lattvec /= total;\n    // Build the weighted atomic positions.\n    Eigen::Matrix<double, 3, Eigen::Dynamic> positions(ratios[0] *\n                                                       components[0].positions);\n\n    for (decltype(ncomponents) i = 1; i < ncomponents; ++i)\n        positions += ratios[i] * components[i].positions;\n    positions /= total;\n    // And the set of virtual elements.\n    std::vector<std::string> vnames;\n    std::vector<int> numbers;\n\n    for (decltype(natoms) ia = 0; ia < natoms; ++ia) {\n        std::vector<std::string> symbols;\n\n        for (auto& c : components)\n            symbols.emplace_back(c.get_element(ia));\n        // Adjacent atoms belonging to the same element are grouped\n        // together.\n        auto name = Virtual_element(symbols, ratios).get_name();\n\n        if ((vnames.size() == 0) || (vnames.back() != name)) {\n            vnames.emplace_back(name);\n            numbers.emplace_back(1);\n        }\n        else\n            ++numbers.back();\n    }\n    return std::make_unique<Crystal_structure>(\n        lattvec, positions, vnames, numbers);\n}\n\n\nstd::unique_ptr<Dielectric_parameters> vc_mix_dielectric_parameters(\n    const std::vector<Dielectric_parameters>& components,\n    const std::vector<double>& ratios) {\n    auto ncomponents = components.size();\n\n    // Basic sanity checks.\n    if (ratios.size() != ncomponents)\n        throw value_error(\"different numbers of components and ratios\");\n\n    if (ncomponents == 0)\n        throw value_error(\"no components in the virtual crystal\");\n\n    for (auto r : ratios)\n        if (r <= 0)\n            throw value_error(\"all atomic ratios must be positive\");\n    auto nborn = components[0].born.size();\n    double total{ratios[0]};\n    Eigen::Matrix3d epsilon{ratios[0] * components[0].epsilon};\n    std::vector<Eigen::MatrixXd> born;\n\n    for (decltype(nborn) ib = 0; ib < nborn; ++ib)\n        born.emplace_back(Eigen::MatrixXd{ratios[0] * components[0].born[ib]});\n\n    for (decltype(ncomponents) i = 1; i < ncomponents; ++i) {\n        if (components[i].born.size() != nborn)\n            throw value_error(\"all components must contain the same\"\n                              \" number of Born charge tensors\");\n        total += ratios[i];\n        epsilon += ratios[i] * components[i].epsilon;\n\n        for (decltype(nborn) ib = 0; ib < nborn; ++ib)\n            born[ib] += ratios[i] * components[i].born[ib];\n    }\n    epsilon /= total;\n\n    for (auto& b : born)\n        b /= total;\n    return std::make_unique<Dielectric_parameters>(born, epsilon);\n}\n\n\nstd::unique_ptr<Harmonic_ifcs> vc_mix_harmonic_ifcs(\n    const std::vector<Harmonic_ifcs>& components,\n    const std::vector<double>& ratios) {\n    auto ncomponents = components.size();\n\n    // Basic sanity checks.\n    if (ratios.size() != ncomponents)\n        throw value_error(\"different numbers of components and ratios\");\n\n    if (ncomponents == 0)\n        throw value_error(\"no components in the virtual crystal\");\n\n    for (auto r : ratios)\n        if (r <= 0)\n            throw value_error(\"all atomic ratios must be positive\");\n    // Only the ifcs themselves are averaged. The remainin\n    // attributes must be common to all objects.\n    double total{ratios[0]};\n    auto na = components[0].na;\n    auto nb = components[0].nb;\n    auto nc = components[0].nc;\n    auto nblocks = components[0].ifcs.size();\n    std::vector<Triple_int> pos{components[0].pos};\n    std::vector<Eigen::MatrixXd> blocks;\n\n    for (decltype(nblocks) ib = 0; ib < nblocks; ++ib)\n        blocks.emplace_back(\n            Eigen::MatrixXd{ratios[0] * components[0].ifcs[ib]});\n\n    for (decltype(ncomponents) i = 1; i < ncomponents; ++i) {\n        if (components[i].ifcs.size() != nblocks)\n            throw value_error(\"all components must contain the same\"\n                              \" number of IFC matrices\");\n        total += ratios[i];\n\n        for (decltype(nblocks) ib = 0; ib < nblocks; ++ib) {\n            if (components[i].pos[ib] != pos[ib])\n                throw value_error(\"all components must contain IFC matrices\"\n                                  \" for the same cell pairs\");\n            blocks[ib] += ratios[i] * components[i].ifcs[ib];\n        }\n    }\n\n    for (auto& b : blocks)\n        b /= total;\n    return std::make_unique<Harmonic_ifcs>(pos, blocks, na, nb, nc);\n}\n\n\nstd::unique_ptr<std::vector<Thirdorder_ifcs>> vc_mix_thirdorder_ifcs(\n    const std::vector<std::vector<Thirdorder_ifcs>>& components,\n    const std::vector<double>& ratios) {\n    auto ncomponents = components.size();\n\n    // Basic sanity checks.\n    if (ratios.size() != ncomponents)\n        throw value_error(\"different numbers of components and ratios\");\n\n    if (ncomponents == 0)\n        throw value_error(\"no components in the virtual crystal\");\n\n    for (auto r : ratios)\n        if (r <= 0)\n            throw value_error(\"all atomic ratios must be positive\");\n    auto nifcs = components[0].size();\n\n    for (decltype(ncomponents) i = 1; i < ncomponents; ++i)\n        if (components[i].size() != nifcs)\n            throw value_error(\"all components must contain the same number\"\n                              \" of IFC blocks\");\n    // Create the final object.\n    auto nruter = std::make_unique<std::vector<Thirdorder_ifcs>>();\n    // We average the Cartesian coordinates of the unit cells and\n    // the IFCs. We require the atom indices to be common to all\n    // inputs.\n    double total = std::accumulate(ratios.begin(), ratios.end(), 0.);\n\n    for (decltype(nifcs) ic = 0; ic < nifcs; ++ic) {\n        auto i = components[0][ic].i;\n        auto j = components[0][ic].j;\n        auto k = components[0][ic].k;\n        Eigen::VectorXd rj{ratios[0] * components[0][ic].rj};\n        Eigen::VectorXd rk{ratios[0] * components[0][ic].rk};\n\n        for (decltype(ncomponents) ir = 1; ir < ncomponents; ++ir) {\n            if ((components[ir][ic].i != i) || (components[ir][ic].j != j) ||\n                (components[ir][ic].k != k))\n                throw value_error(\"all components must contain IFC blocks\"\n                                  \" for the same atom triplets\");\n            rj += ratios[ir] * components[ir][ic].rj;\n            rk += ratios[ir] * components[ir][ic].rk;\n        }\n        rj /= total;\n        rk /= total;\n        Thirdorder_ifcs block{rj, rk, i, j, k};\n\n        for (std::size_t alpha = 0; alpha < 3; ++alpha)\n            for (std::size_t beta = 0; beta < 3; ++beta)\n                for (std::size_t gamma = 0; gamma < 3; ++gamma) {\n                    block.ifc(alpha, beta, gamma) =\n                        ratios[0] * components[0][ic].ifc(alpha, beta, gamma);\n\n                    for (decltype(ncomponents) ir = 1; ir < ncomponents; ++ir)\n                        block.ifc(alpha, beta, gamma) +=\n                            ratios[ir] *\n                            components[ir][ic].ifc(alpha, beta, gamma);\n                    block.ifc(alpha, beta, gamma) /= total;\n                }\n        nruter->emplace_back(block);\n    }\n    return nruter;\n}\n} // namespace alma\n", "meta": {"hexsha": "dcbff9084bc47823721160b1359f0a03e2da9a91", "size": 9058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vc.cpp", "max_stars_repo_name": "sousaw/BTE-Barna", "max_stars_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T03:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:11:20.000Z", "max_issues_repo_path": "src/vc.cpp", "max_issues_repo_name": "sousaw/BTE-Barna", "max_issues_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_issues_repo_licenses": ["MIT", "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/vc.cpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "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": 37.2757201646, "max_line_length": 80, "alphanum_fraction": 0.5965996909, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.17326000225907393}}
{"text": "#include \"darknet.h\"\n#include \"yolo.h\"\n\n#include <dlib/data_io.h>\n#include <iostream>\n\n#undef VISUAL\n\n#include <dlib/gui_widgets.h>\n\nstruct training_sample\n{\n    dlib::matrix<dlib::rgb_pixel> image;\n    std::vector<dlib::mmod_rect> boxes;\n    dlib::yolo_options::map_type yolo_map;\n};\n\nauto main(const int argc, const char** argv) -> int\ntry\n{\n    if (argc > 1)\n    {\n        dlib::image_window win;\n        darknet::detector19_infer net;\n        {\n            darknet::detector19_infer temp;\n            auto trainer = dlib::dnn_trainer(temp);\n            trainer.set_synchronization_file(\"yolo_darknet19_sync\");\n            net = trainer.get_net(dlib::force_flush_to_disk::no);\n        }\n\n        std::cout << net << '\\n';\n        dlib::matrix<dlib::rgb_pixel> image, input_image;\n        for (int i = 1; i < argc; ++i)\n        {\n            dlib::load_image(image, argv[i]);\n            dlib::letter_box(\n                image,\n                net.loss_details().get_options().get_input_size(),\n                input_image);\n            win.set_image(input_image);\n            const auto detections = net.process(input_image, -1);\n            std::cout << \"found \" << detections.size() << \" detections\\n\";\n            for (const auto& det : detections)\n            {\n                std::cout << det.label << \", \" << det.detection_confidence << \", \" << det.rect\n                          << '\\n';\n                win.add_overlay(\n                    det.rect,\n                    dlib::rgb_pixel(255, 0, 0),\n                    det.label + \": \" + std::to_string(det.detection_confidence));\n            }\n            std::cin.get();\n            win.clear_overlay();\n        }\n    }\n    else\n    {\n        std::vector<dlib::matrix<dlib::rgb_pixel>> images;\n        std::vector<std::vector<dlib::mmod_rect>> bboxes;\n        dlib::load_image_dataset(images, bboxes, \"./pascal.xml\");\n        std::cout << \"image dataset loaded: \" << images.size() << \" images\\n\";\n\n        const long input_size = 448;\n        dlib::yolo_options options(input_size, 32, bboxes);\n        darknet::detector19_train net(options);\n        dlib::set_all_bn_inputs_no_bias(net);\n        dlib::visit_computational_layers(net, [](dlib::leaky_relu_& l) {\n            l = dlib::leaky_relu_(0.2);\n        });\n\n        net.subnet().layer_details().set_num_filters(options.get_labels().size() + 5);\n        {\n            dlib::matrix<dlib::rgb_pixel> dummy(input_size, input_size);\n            net(dummy);\n        }\n        std::cout << net << '\\n';\n        std::cout << \"num parameters: \" << dlib::count_parameters(net) << '\\n';\n        std::cout << \"num convolutions: \" << count_convolutions(net) << '\\n';\n        dlib::pipe<training_sample> training_data(1000);\n\n#ifdef VISUAL\n        dlib::image_window win;\n        auto data_loader = [&win, &training_data, &images, &bboxes, &options](time_t seed)\n#else\n        auto data_loader = [&training_data, &images, &bboxes, &options](time_t seed)\n#endif\n        {\n            dlib::rand rnd(time(nullptr) + seed);\n\n            // const long min_size = options.get_downsampling_factor() * 1.5;\n            // const long chip_dim = options.get_input_size();\n            // dlib::random_cropper cropper;\n            // cropper.set_seed(time(nullptr) + seed);\n            // cropper.set_chip_dims(chip_dim, chip_dim);\n            // cropper.set_translate_amount(0.1);\n            // cropper.set_background_crops_fraction(0);\n            // cropper.set_randomly_flip(true);\n            // cropper.set_max_rotation_degrees(0);\n            // cropper.set_min_object_size(min_size, min_size);\n            // cropper.set_max_object_size(0.9);\n\n            training_sample sample;\n            while (training_data.is_enabled())\n            {\n                const auto idx = rnd.get_random_32bit_number() % images.size();\n                // const auto& image = images[idx];\n                // const auto& boxes = bboxes[idx];\n                // cropper(image, boxes, sample.image, sample.boxes);\n\n                const auto temp = options.generate_map(images[idx], bboxes[idx]);\n                sample.image = std::move(temp.first);\n                sample.yolo_map = std::move(temp.second);\n                dlib::disturb_colors(sample.image, rnd);\n\n#ifdef VISUAL\n                dlib::matrix<dlib::rgb_pixel> square_image;\n                const auto [scale, offset] =\n                    dlib::letter_box(images[idx], options.get_input_size(), square_image);\n                win.set_image(sample.image);\n                for (const auto& box : bboxes[idx])\n                {\n                    sample.boxes.push_back(\n                        dlib::translate_rect(dlib::scale_rect(box.rect, scale), offset));\n                    win.add_overlay(sample.boxes.back(), dlib::rgb_pixel(0, 255, 0), box.label);\n                }\n                std::cin.get();\n                win.clear_overlay();\n                win.set_image(options.overlay_map(images[idx], bboxes[idx]));\n                std::cin.get();\n#endif\n\n                training_data.enqueue(sample);\n            }\n        };\n\n        std::vector<std::thread> data_loaders;\n        for (int i = 0; i < 1; ++i)\n        {\n            data_loaders.emplace_back([&data_loader, i]() { data_loader(i + 1); });\n        }\n\n        auto trainer = dlib::dnn_trainer(net);\n        trainer.be_verbose();\n        trainer.set_learning_rate(0.1);\n        trainer.set_iterations_without_progress_threshold(3000);\n        trainer.set_mini_batch_size(32);\n        trainer.set_synchronization_file(\"yolo_darknet19_sync\", std::chrono::minutes(10));\n        std::cout << trainer << '\\n';\n        std::vector<dlib::matrix<dlib::rgb_pixel>> minibatch_images;\n        std::vector<dlib::yolo_options::map_type> minibatch_labels;\n        while (trainer.get_learning_rate() > 1e-5)\n        {\n            minibatch_images.clear();\n            minibatch_labels.clear();\n            training_sample sample;\n            while (minibatch_images.size() < trainer.get_mini_batch_size())\n            {\n                training_data.dequeue(sample);\n                minibatch_images.push_back(sample.image);\n                minibatch_labels.push_back(sample.yolo_map);\n            }\n            trainer.train_one_step(minibatch_images, minibatch_labels);\n        }\n\n        training_data.disable();\n        for (auto& dl : data_loaders)\n        {\n            dl.join();\n        }\n        trainer.get_net();\n        net.clean();\n        dlib::serialize(\"yolo-darknet19.dnn\") << net;\n    }\n}\ncatch (const std::exception& e)\n{\n    std::cout << e.what() << '\\n';\n}\n", "meta": {"hexsha": "23da62561ddea025a89fd1f631d9fe3abd948d4b", "size": 6585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "dlibml/yolo-dlib", "max_stars_repo_head_hexsha": "e44e9442cc1ed3a82e796032ec6f204fac90bd02", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-12T02:12:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T13:04:26.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "dlib-users/yolo-dlib", "max_issues_repo_head_hexsha": "e44e9442cc1ed3a82e796032ec6f204fac90bd02", "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/main.cpp", "max_forks_repo_name": "dlib-users/yolo-dlib", "max_forks_repo_head_hexsha": "e44e9442cc1ed3a82e796032ec6f204fac90bd02", "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.5833333333, "max_line_length": 96, "alphanum_fraction": 0.5523158694, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.1732599961728145}}
{"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#include \"dart/constraint/PgsBoxedLcpSolver.hpp\"\n\n#include <cmath>\n#include <cstring>\n#include <Eigen/Dense>\n#include \"dart/external/odelcpsolver/matrix.h\"\n#include \"dart/external/odelcpsolver/misc.h\"\n#include \"dart/math/Constants.hpp\"\n\n#define PGS_EPSILON 10e-9\n\nnamespace dart {\nnamespace constraint {\n\n//==============================================================================\nPgsBoxedLcpSolver::Option::Option(\n    int maxIteration,\n    double deltaXTolerance,\n    double relativeDeltaXTolerance,\n    double epsilonForDivision,\n    bool randomizeConstraintOrder)\n  : mMaxIteration(maxIteration),\n    mDeltaXThreshold(deltaXTolerance),\n    mRelativeDeltaXTolerance(relativeDeltaXTolerance),\n    mEpsilonForDivision(epsilonForDivision),\n    mRandomizeConstraintOrder(randomizeConstraintOrder)\n{\n  // Do nothing\n}\n\n//==============================================================================\nconst std::string& PgsBoxedLcpSolver::getType() const\n{\n  return getStaticType();\n}\n\n//==============================================================================\nconst std::string& PgsBoxedLcpSolver::getStaticType()\n{\n  static const std::string type = \"PgsBoxedLcpSolver\";\n  return type;\n}\n\n//==============================================================================\nbool PgsBoxedLcpSolver::solve(\n    int n,\n    double* A,\n    double* x,\n    double* b,\n    int nub,\n    double* lo,\n    double* hi,\n    int* findex,\n    bool /*earlyTermination*/)\n{\n  const int nskip = dPAD(n);\n\n  // If all the variables are unbounded then we can just factor, solve, and\n  // return.R\n  if (nub >= n)\n  {\n    mCacheD.resize(n);\n    std::fill(mCacheD.begin(), mCacheD.end(), 0);\n\n    dFactorLDLT(A, mCacheD.data(), n, nskip);\n    dSolveLDLT(A, mCacheD.data(), b, n, nskip);\n    std::memcpy(x, b, n * sizeof(double));\n\n    return true;\n  }\n\n  mCacheOrder.clear();\n  mCacheOrder.reserve(n);\n\n  bool possibleToTerminate = true;\n  for (int i = 0; i < n; ++i)\n  {\n    // mOrderCacheing\n    if (A[nskip * i + i] < mOption.mEpsilonForDivision)\n    {\n      x[i] = 0.0;\n      continue;\n    }\n\n    mCacheOrder.push_back(i);\n\n    // Initial loop\n    const double* A_ptr = A + nskip * i;\n    const double old_x = x[i];\n\n    double new_x = b[i];\n\n    for (int j = 0; j < i; ++j)\n      new_x -= A_ptr[j] * x[j];\n\n    for (int j = i + 1; j < n; ++j)\n      new_x -= A_ptr[j] * x[j];\n\n    new_x /= A[nskip * i + i];\n\n    if (findex[i] >= 0)\n    {\n      const double hi_tmp = hi[i] * x[findex[i]];\n      const double lo_tmp = -hi_tmp;\n\n      if (new_x > hi_tmp)\n        x[i] = hi_tmp;\n      else if (new_x < lo_tmp)\n        x[i] = lo_tmp;\n      else\n        x[i] = new_x;\n    }\n    else\n    {\n      if (new_x > hi[i])\n        x[i] = hi[i];\n      else if (new_x < lo[i])\n        x[i] = lo[i];\n      else\n        x[i] = new_x;\n    }\n\n    // Test\n    if (possibleToTerminate)\n    {\n      const double deltaX = std::abs(x[i] - old_x);\n      if (deltaX > mOption.mDeltaXThreshold)\n        possibleToTerminate = false;\n    }\n  }\n\n  if (possibleToTerminate)\n  {\n    return true;\n  }\n\n  // Normalizing\n  for (const auto& index : mCacheOrder)\n  {\n    const double dummy = 1.0 / A[nskip * index + index];\n    b[index] *= dummy;\n    for (int j = 0; j < n; ++j)\n      A[nskip * index + j] *= dummy;\n  }\n\n  for (int iter = 1; iter < mOption.mMaxIteration; ++iter)\n  {\n    if (mOption.mRandomizeConstraintOrder)\n    {\n      if ((iter & 7) == 0)\n      {\n        for (std::size_t i = 1; i < mCacheOrder.size(); ++i)\n        {\n          const int tmp = mCacheOrder[i];\n          const int swapi = dRandInt(i + 1);\n          mCacheOrder[i] = mCacheOrder[swapi];\n          mCacheOrder[swapi] = tmp;\n        }\n      }\n    }\n\n    possibleToTerminate = true;\n\n    // Single loop\n    for (const auto& index : mCacheOrder)\n    {\n      const double* A_ptr = A + nskip * index;\n      double new_x = b[index];\n      const double old_x = x[index];\n\n      for (int j = 0; j < index; j++)\n        new_x -= A_ptr[j] * x[j];\n\n      for (int j = index + 1; j < n; j++)\n        new_x -= A_ptr[j] * x[j];\n\n      if (findex[index] >= 0)\n      {\n        const double hi_tmp = hi[index] * x[findex[index]];\n        const double lo_tmp = -hi_tmp;\n\n        if (new_x > hi_tmp)\n          x[index] = hi_tmp;\n        else if (new_x < lo_tmp)\n          x[index] = lo_tmp;\n        else\n          x[index] = new_x;\n      }\n      else\n      {\n        if (new_x > hi[index])\n          x[index] = hi[index];\n        else if (new_x < lo[index])\n          x[index] = lo[index];\n        else\n          x[index] = new_x;\n      }\n\n      if (possibleToTerminate\n          && std::abs(x[index]) > mOption.mEpsilonForDivision)\n      {\n        const double relativeDeltaX = std::abs((x[index] - old_x) / x[index]);\n        if (relativeDeltaX > mOption.mRelativeDeltaXTolerance)\n          possibleToTerminate = false;\n      }\n    }\n\n    if (possibleToTerminate)\n      break;\n  }\n\n  return possibleToTerminate;\n}\n\n#ifndef NDEBUG\n//==============================================================================\nbool PgsBoxedLcpSolver::canSolve(int n, const double* A)\n{\n  const int nskip = dPAD(n);\n\n  // Return false if A has zero-diagonal or A is nonsymmetric matrix\n  for (auto i = 0; i < n; ++i)\n  {\n    if (A[nskip * i + i] < PGS_EPSILON)\n      return false;\n\n    for (auto j = 0; j < n; ++j)\n    {\n      if (std::abs(A[nskip * i + j] - A[nskip * j + i]) > PGS_EPSILON)\n        return false;\n    }\n  }\n\n  return true;\n}\n#endif\n\n//==============================================================================\nvoid PgsBoxedLcpSolver::setOption(const PgsBoxedLcpSolver::Option& option)\n{\n  mOption = option;\n}\n\n//==============================================================================\nconst PgsBoxedLcpSolver::Option& PgsBoxedLcpSolver::getOption() const\n{\n  return mOption;\n}\n\n} // namespace constraint\n} // namespace dart\n", "meta": {"hexsha": "dc26e658ad5eab9f51c43b7387bc2c8ca9e9c296", "size": 7467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dart/constraint/PgsBoxedLcpSolver.cpp", "max_stars_repo_name": "JShep1/dart", "max_stars_repo_head_hexsha": "0ed33f028386bf5f2cdfe52858a6042ae8b45c38", "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": "dart/constraint/PgsBoxedLcpSolver.cpp", "max_issues_repo_name": "JShep1/dart", "max_issues_repo_head_hexsha": "0ed33f028386bf5f2cdfe52858a6042ae8b45c38", "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/constraint/PgsBoxedLcpSolver.cpp", "max_forks_repo_name": "JShep1/dart", "max_forks_repo_head_hexsha": "0ed33f028386bf5f2cdfe52858a6042ae8b45c38", "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": 26.2922535211, "max_line_length": 80, "alphanum_fraction": 0.5663586447, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.17325895017794019}}
{"text": "#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\n#include \"debug.h\"\n#include \"types.h\"\n#include \"imgproc.h\"\n#include \"photobundle.h\"\n#include \"sample_eigen.h\"\n#include \"utils.h\"\n\n#if defined(WITH_CEREAL)\n#include \"ceres_cereal.h\"\n#include \"eigen_cereal.h\"\n#include <fstream>\n#include <cereal/archives/binary.hpp>\n#include <cereal/types/memory.hpp>\n#endif\n\n#include <cassert>\n#include <cmath>\n#include <type_traits>\n#include <iterator>\n#include <algorithm>\n#include <map>\n\n// this is just for YCM to stop highlighting openmp as error (there is no openmp\n// in clang3.5)\n#define HAS_OPENMP __GNUC__ >= 4 && __clang__ == 0\n\n#if HAS_OPENMP\n#include <omp.h>\n#endif\n\n#include <Eigen/Geometry>\n\nstatic PhotometricBundleAdjustment::Options::DescriptorType\nDescriptorTypeFromString(std::string s)\n{\n  if(utils::icompare(\"Intensity\", s))\n    return PhotometricBundleAdjustment::Options::DescriptorType::Intensity;\n  else if(utils::icompare(\"IntensityAndGradient\", s))\n    return PhotometricBundleAdjustment::Options::DescriptorType::IntensityAndGradient;\n  else if(utils::icompare(\"BitPlanes\", s))\n    return PhotometricBundleAdjustment::Options::DescriptorType::BitPlanes;\n  else {\n    Warn(\"Unknown descriptorType '%s'\\n\", s.c_str());\n    return PhotometricBundleAdjustment::Options::DescriptorType::Intensity;\n  }\n}\n\nPhotometricBundleAdjustment::Result\nPhotometricBundleAdjustment::Result::FromFile(std::string filename)\n{\n#if defined(WITH_CEREAL)\n  std::ifstream ifs(filename);\n  if(ifs.is_open()) {\n    cereal::BinaryInputArchive ar(ifs);\n    Result ret;\n    ar(ret);\n    return ret;\n  } else {\n    Fatal(\"Failed to open %s\\n\", filename.c_str());\n  }\n#else\n  UNUSED(filename);\n  Fatal(\"compile WITH_CEREAL\\n\");\n#endif\n}\n\nbool PhotometricBundleAdjustment::Result::Writer::add(const Result& result)\n{\n  bool ret = false;\n\n#if defined(WITH_CEREAL)\n  std::ofstream ofs(utils::Format(\"%s/%05d.out\", _prefix.c_str(), _counter++));\n  if(ofs.is_open()) {\n    cereal::BinaryOutputArchive ar(ofs);\n    ar(result);\n    ret = true;\n  }\n#else\n  utils::UNUSED(result);\n#endif\n\n  return ret;\n}\n\nPhotometricBundleAdjustment::Options::Options(const utils::ConfigFile& cf)\n  : maxNumPoints(cf.get<int>(\"maxNumPoints\", 4096)),\n    slidingWindowSize(cf.get<int>(\"slidingWindowSize\", 5)),\n    patchRadius(cf.get<int>(\"patchRadius\", 2)),\n    maskBlockRadius(cf.get<int>(\"maskBlockRadius\", 1)),\n    maxFrameDistance(cf.get<int>(\"maxFrameDistance\", 1)),\n    numThreads(cf.get<int>(\"numThreads\", -1)),\n    doGaussianWeighting((bool) cf.get<int>(\"doGaussianWeighting\", 0)),\n    verbose((bool) cf.get<int>(\"verbose\", 1)),\n    minScore(cf.get<double>(\"minScore\", 0.75)),\n    robustThreshold(cf.get<double>(\"robustThreshold\", 0.05)),\n    minValidDepth(cf.get<double>(\"minValidDepth\", 0.01)),\n    maxValidDepth(cf.get<double>(\"maxValidDepth\", 1000.0)),\n    nonMaxSuppRadius(cf.get<int>(\"nonMaxSuppRadius\", 1)),\n    descriptorType(DescriptorTypeFromString(cf.get<std::string>(\"descriptorType\", \"Intensity\")))\n{}\n\n/**\n * simple class to store the image gradient\n */\nclass ImageGradient\n{\n public:\n  typedef Image_<float> ImageT;\n\n public:\n  ImageGradient() = default;\n  ImageGradient(const ImageT& Ix, const ImageT& Iy)\n      : _Ix(Ix), _Iy(Iy) {}\n\n  inline const ImageT& Ix() const { return _Ix; }\n  inline const ImageT& Iy() const { return _Iy; }\n\n  inline ImageT absGradientMag() const\n  {\n    return _Ix.array().abs() + _Iy.array().abs();\n  }\n\n  template <class InputImage>\n  inline void compute(const InputImage& I)\n  {\n    static_assert(std::is_same<typename InputImage::Scalar, uint8_t>::value ||\n                  std::is_same<typename InputImage::Scalar, float>::value,\n                  \"type mismatch, input image must be uint8_t or float\");\n\n    optResize(I.rows(), I.cols());\n    imgradient(I.data(), ImageSize(I.rows(), I.cols()), _Ix.data(), _Iy.data());\n  }\n\n private:\n  ImageT _Ix;\n  ImageT _Iy;\n\n  void optResize(int rows, int cols)\n  {\n    if(_Ix.rows() != rows || _Ix.cols() != cols) {\n      _Ix.resize(rows, cols);\n      _Iy.resize(rows, cols);\n    }\n  }\n}; // ImageGradient\n\n\nclass PhotometricBundleAdjustment::DescriptorFrame\n{\n public:\n  typedef EigenAlignedContainer_<Image_<float>> Channels;\n  typedef EigenAlignedContainer_<ImageGradient> ImageGradientList;\n\n public:\n  /**\n   * \\param frame_id the frame number (unique per image)\n   * \\param I        grayscale input image\n   * \\param gx       list of x-gradients per channel\n   * \\param gy       list of y-gradients per channel\n   */\n  inline DescriptorFrame(uint32_t frame_id, const Channels& channels)\n      : _frame_id(frame_id), _channels(channels)\n  {\n    assert( !_channels.empty() );\n\n    _max_rows = _channels[0].rows() - 1;\n    _max_cols = _channels[0].cols() - 1;\n\n    _gradients.resize( _channels.size() );\n    for(size_t i = 0; i < _channels.size(); ++i) {\n      _gradients[i].compute(_channels[i]);\n    }\n  }\n\n\n  DescriptorFrame(const DescriptorFrame&) = delete;\n  DescriptorFrame& operator=(const DescriptorFrame&) = delete;\n\n  inline uint32_t id() const { return _frame_id; }\n\n  inline bool operator<(const DescriptorFrame& other) const\n  {\n    return _frame_id < other._frame_id;\n  }\n\n  inline size_t numChannels() const { return _channels.size(); }\n\n  inline const Image_<float>& getChannel(size_t i) const\n  {\n    assert(i < _channels.size());\n    return _channels[i];\n  }\n\n  inline const ImageGradient& getChannelGradient(size_t i) const\n  {\n    assert(i < _gradients.size());\n    return _gradients[i];\n  }\n\n  /**\n   * \\return true of point projects to the image\n   */\n  template <class ProjType> inline\n  bool isProjectionValid(const ProjType& x) const\n  {\n    return x[0] >= 0.0 && x[0] < _max_cols &&\n           x[1] >= 0.0 && x[1] < _max_rows;\n  }\n\n  void computeSaliencyMap(Image_<float>& smap) const\n  {\n    assert( !_gradients.empty() );\n\n    smap.array() = _gradients[0].absGradientMag();\n    for(size_t i = 1; i < _gradients.size(); ++i) {\n      smap.array() += _gradients[i].absGradientMag().array();\n    }\n  }\n\n\n public:\n  static inline DescriptorFrame* Create(uint32_t id, const Image_<uint8_t>& image,\n                                        PhotometricBundleAdjustment::Options::DescriptorType type)\n  {\n    Channels channels;\n    switch(type) {\n      case PhotometricBundleAdjustment::Options::DescriptorType::Intensity:\n        channels.push_back( image.cast<Channels::value_type::Scalar>() );\n        break;\n      case PhotometricBundleAdjustment::Options::DescriptorType::IntensityAndGradient: {\n        channels.push_back( image.cast<Channels::value_type::Scalar>() );\n        channels.push_back( Image_<float>(image.rows(), image.cols()) );\n        channels.push_back( Image_<float>(image.rows(), image.cols()) );\n\n        imgradient(image.data(), ImageSize(image.rows(), image.cols()),\n                   channels[1].data(), channels[2].data());\n\n      } break;\n      case PhotometricBundleAdjustment::Options::DescriptorType::BitPlanes: {\n        computeBitPlanes(image.data(), ImageSize(image.rows(), image.cols()), channels);\n      } break;\n    }\n\n    return new DescriptorFrame(id, channels);\n  }\n\n private:\n  uint32_t _frame_id;\n  uint32_t _max_rows;\n  uint32_t _max_cols;\n\n  Channels _channels;\n  ImageGradientList _gradients;\n}; // DescriptorFrame\n\n/**\n * \\return bilinearly interpolated pixel value at subpixel location (xf,yf)\n */\ntemplate <class Image, class T> inline\nT interp2(const Image& I, T xf, T yf, T fillval = 0.0, T offset = 0.0)\n{\n  const int max_cols = I.cols() - 1;\n  const int max_rows = I.rows() - 1;\n\n  xf += offset;\n  yf += offset;\n\n  int xi = (int) std::floor(xf);\n  int yi = (int) std::floor(yf);\n\n  xf -= xi;\n  yf -= yi;\n\n  if( xi >= 0 && xi < max_cols && yi >= 0 && yi < max_rows )\n  {\n    const T wx = 1.0 - xf;\n    return (1.0 - yf) * ( I(yi,   xi)*wx + I(yi,   xi+1)*xf )\n               +  yf  * ( I(yi+1, xi)*wx + I(yi+1, xi+1)*xf );\n  } else\n  {\n    if( xi == max_cols && yi < max_rows )\n      return ( xf > 0 ) ? fillval : (1.0-yf)*I(yi,xi) + yf*I(yi+1, xi);\n    else if( yi == max_rows && xi < max_cols )\n      return ( yf > 0 ) ? fillval : (1.0-xf)*I(yi,xi) + xf*I(yi, xi+1);\n    else if( xi == max_cols && yi == max_rows )\n      return ( xf > 0 || yf > 0 ) ? fillval : I(yi, xi);\n    else\n      return fillval;\n  }\n\n}\n\ntemplate <int N> constexpr int square() { return N*N; }\n\ntemplate <int R, class ImageType, class ProjType, typename T = double>\nvoid interpolateFixedPatch(Vec_<T, square<2*R+1>()>& dst,\n                           const ImageType& I, const ProjType& p,\n                           const T& fillval = T(0), const T& offset = T(0))\n{\n  const T x = static_cast<T>( p[0] + offset );\n  const T y = static_cast<T>( p[1] + offset );\n\n  auto d_ptr = dst.data();\n  for(int r = -R; r <= R; ++r) {\n    for(int c = -R; c <= R; ++c) {\n      *d_ptr++ = interp2(I, c + x, r + y, fillval);\n    }\n  }\n}\n\n\ntemplate <int R, typename T = float>\nclass ZnccPatch_\n{\n  static_assert(std::is_floating_point<T>::value, \"T must be floating point\");\n\n public:\n  static constexpr int Radius    = R;\n  static constexpr int Dimension = (2*R+1) * (2*R+1);\n\n public:\n  inline ZnccPatch_() {}\n\n  template <class ImageType, class ProjType> inline\n  ZnccPatch_(const ImageType& image, const ProjType& uv) { set(image, uv); }\n\n  template <class ImageType, class ProjType> inline\n  const ZnccPatch_& set(const ImageType& I, const ProjType& uv)\n  {\n    interpolateFixedPatch<R>(_data, I, uv, T(0.0), T(0.0));\n    T mean = _data.array().sum() / (T) _data.size();\n    _data.array() -= mean;\n    _norm = _data.norm();\n\n    return *this;\n  }\n\n  template <class ImageType, class ProjType>\n  inline static ZnccPatch_ FromImage(const ImageType& I, const ProjType& p)\n  {\n    ZnccPatch_ ret;\n    ret.set(I, p);\n    return ret;\n  }\n\n  inline T score(const ZnccPatch_& other) const\n  {\n    T d = _norm * other._norm;\n    return d > 1e-6 ? _data.dot(other._data) / d : -1.0;\n  }\n\n private:\n  Vec_<T, Dimension> _data;\n  T _norm;\n\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n}; // ZnccPatch\n\n\n/**\n */\nstruct PhotometricBundleAdjustment::ScenePoint\n{\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  typedef std::vector<uint32_t>        VisibilityList;\n  typedef EigenAlignedContainer_<Vec2> ProjectionList;\n  typedef ZnccPatch_<2, float>         ZnccPatchType;\n\n  /**\n   * Create a scene point with position 'X' and reference frame number 'f_id'\n   *\n   * We also store the original point for later comparision\n   */\n  inline ScenePoint(const Vec3& X, uint32_t f_id)\n      : _X(X), _X_original(X)\n  {\n    _f.reserve(8);\n    _f.push_back(f_id);\n  }\n\n  /**\n   * \\return true if the scene point has 'f_id' it is visibility list\n   */\n  inline bool hasFrame(uint32_t f_id) const {\n    return std::find(_f.begin(), _f.end(), f_id) != _f.end();\n  }\n\n  /**\n   * \\return the visibility list\n   */\n  inline const VisibilityList& visibilityList() const { return _f; }\n\n  /** \\return the reference frame number (also the first in the list) */\n  inline const uint32_t& refFrameId() const { return _f.front(); }\n\n  /** \\return the last frame number, most recent observation */\n  inline const uint32_t& lastFrameId() const { return _f.back(); }\n\n  /** \\return the 3D point associated with the ScenePoint */\n  inline const Vec3& X() const { return _X; }\n  inline       Vec3& X()       { return _X; }\n\n  /** \\return the original 3D point */\n  inline const Vec3& getOriginalPoint() const { return _X_original; }\n\n  /** \\return the associated patch */\n  inline const ZnccPatchType& patch() const { return _patch; }\n\n  inline void addFrame(uint32_t f) { _f.push_back(f); }\n\n  template <class ImageType, class ProjType> inline\n  void setZnccPach(const ImageType& I, const ProjType& x)\n  {\n    _patch.set(I, x);\n  }\n\n  inline const std::vector<double>& descriptor() const { return _descriptor; }\n  inline       std::vector<double>& descriptor()       { return _descriptor; }\n\n  inline void setSaliency(double v) { _saliency = v; }\n  inline const double& getSaliency() const { return _saliency; }\n\n  inline void setRefined(bool v) { _was_refined = v; }\n  inline const bool& wasRefined() const { return _was_refined; }\n\n  inline size_t numFrames() const { return _f.size(); }\n\n  inline void setFirstProjection(const Vec_<int,2>& x) { _x = x; }\n  inline const Vec_<int,2>& getFirstProjection() const { return _x; }\n\n  Vec3 _X;\n  Vec3 _X_original;\n  VisibilityList _f;\n  ZnccPatchType _patch;\n  std::vector<double> _descriptor;\n\n  double _saliency  = 0.0;\n  bool _was_refined = false;\n\n  Vec_<int,2> _x;\n}; // ScenePoint\n\n\nPhotometricBundleAdjustment::PhotometricBundleAdjustment(\n    const Calibration& calib, const ImageSize& image_size, const Options& options)\n  : _calib(calib), _image_size(image_size), _options(options),\n    _frame_buffer(options.slidingWindowSize)\n{\n  _mask.resize(_image_size.rows, _image_size.cols);\n  _saliency_map.resize(_image_size.rows, _image_size.cols);\n\n  _K_inv = calib.K().inverse();\n}\n\nPhotometricBundleAdjustment::~PhotometricBundleAdjustment() {}\n\nstatic inline int PatchSizeFromRadius(int r) { return (2*r+1) * (2*r+1);  }\n\nstatic inline int PatchRadiusFromLength(int l) { return std::sqrt(l)/2; }\n\ntemplate <typename T, class Image> static inline\nvoid ExtractPatch(T* dst, const Image& I, const Vec_<int,2>& uv, int radius)\n{\n  int max_cols = I.cols() - radius - 1,\n      max_rows = I.rows() - radius - 1;\n\n  for(int r = -radius, i=0; r <= radius; ++r) {\n    int r_i = std::max(radius, std::min(uv[1] + r, max_rows));\n    for(int c = -radius; c <= radius; ++c, ++i) {\n      int c_i = std::max(radius, std::min(uv[0] + c, max_cols));\n      dst[i] = static_cast<T>( I(r_i, c_i) );\n    }\n  }\n}\n\n\nvoid PhotometricBundleAdjustment::\naddFrame(const uint8_t* I_ptr, const float* Z_ptr, const Mat44& T, Result* result)\n{\n  _trajectory.push_back(T, _frame_id);\n  const Eigen::Isometry3d T_w(_trajectory.back());\n  const Eigen::Isometry3d T_c(T_w.inverse());\n\n  typedef Eigen::Map<const Image_<uint8_t>, Eigen::Aligned> SrcMap;\n  auto I = SrcMap(I_ptr, _image_size.rows, _image_size.cols);\n\n  typedef Eigen::Map<const Image_<float>, Eigen::Aligned> SrcDepthMap;\n  auto Z = SrcDepthMap(Z_ptr, _image_size.rows, _image_size.cols);\n\n  auto frame = DescriptorFrame::Create(_frame_id, I, _options.descriptorType);\n\n  auto B = std::max(_options.maskBlockRadius, std::max(2, _options.patchRadius));\n  auto max_rows = (int) I.rows() - B - 1,\n       max_cols = (int) I.cols() - B - 1,\n       radius = _options.patchRadius,\n       patch_length = PatchSizeFromRadius(radius),\n       descriptor_dim = (int) frame->numChannels() * patch_length,\n       mask_radius = _options.maskBlockRadius;\n\n  //\n  // Establish \"correspondences\" with the old data. This is the visibility list\n  // computation\n  //\n  _mask.setOnes();\n\n  int num_updated = 0, max_num_to_update = 0;\n  for(size_t i = 0; i < _scene_points.size(); ++i) {\n    const auto& pt = _scene_points[i];\n    int f_dist = _frame_id - pt->lastFrameId();\n    if(f_dist <= _options.maxFrameDistance) { // do not go too far back\n      //\n      // If the point projects to the current frame and it zncc score is\n      // sufficiently highly, we'll add the current image to its visibility list\n      Vec2 uv = _calib.project(T_c * pt->X());\n      ++max_num_to_update;\n\n      int r = std::round(uv[1]), c = std::round(uv[0]);\n      if(r >= B && r < max_rows && c >= B && c <= max_cols) {\n        typename ScenePoint::ZnccPatchType other_patch(I, uv);\n        auto score = pt->patch().score( other_patch );\n        if(score > _options.minScore) {\n          num_updated++;\n\n          // TODO update the patch for the new frame data\n          pt->addFrame(_frame_id);\n\n          //\n          // block an area in the mask to prevent initializing redandant new\n          // scene points\n          //\n          for(int r_i = -mask_radius; r_i <= mask_radius; ++r_i)\n            for(int c_i = -mask_radius; c_i <= mask_radius; ++c_i)\n              _mask(r+r_i, c+c_i) = 0;\n        }\n      }\n    }\n  }\n\n\n  //\n  // Add new scene points\n  //\n  decltype(_scene_points) new_scene_points;\n  new_scene_points.reserve( max_rows * max_cols * 0.5 );\n  frame->computeSaliencyMap(_saliency_map);\n\n  typedef IsLocalMax_<decltype(_saliency_map), decltype(_mask)> IsLocalMax;\n  const IsLocalMax is_local_max(_saliency_map, _mask, _options.nonMaxSuppRadius);\n\n  for(int y = B; y < max_rows; ++y) {\n    for(int x = B; x < max_cols; ++x) {\n      auto z = Z(y,x);\n      if(z >= _options.minValidDepth && z <= _options.maxValidDepth) {\n        if(is_local_max(y, x)) {\n          Vec3 X = T_w * (z * _K_inv * Vec3(x, y, 1.0));\n\n          auto p = make_unique<ScenePoint>(X, _frame_id);\n          Vec_<int,2> xy(x, y);\n          p->setZnccPach( I, xy );\n          p->descriptor().resize(descriptor_dim);\n          p->setSaliency( _saliency_map(y,x) );\n          p->setFirstProjection(xy);\n\n          new_scene_points.push_back(std::move(p));\n        }\n      }\n    }\n  }\n\n  //\n  // keep the best N points\n  //\n  if(new_scene_points.size() > (size_t) _options.maxNumPoints) {\n    auto nth = new_scene_points.begin() + _options.maxNumPoints;\n    std::nth_element(new_scene_points.begin(), nth, new_scene_points.end(),\n                     [&](const ScenePointPointer& a, const ScenePointPointer& b) {\n                      return a->getSaliency() > b->getSaliency();\n                     });\n    new_scene_points.erase(nth, new_scene_points.end());\n  }\n\n  //\n  // extract the descriptors\n  //\n  const int num_channels = frame->numChannels(),\n        num_new_points = (int) new_scene_points.size();\n\n  Info(\"updated %d [%0.2f%%] max %d new %d\\n\",\n       num_updated, 100.0 * num_updated / _scene_points.size(),\n       max_num_to_update, num_new_points);\n\n  for(int k = 0; k < num_channels; ++k) {\n    const auto& channel = frame->getChannel(k);\n    for(int i = 0; i < num_new_points; ++i) {\n      auto ptr = new_scene_points[i]->descriptor().data() + k*patch_length;\n      ExtractPatch(ptr, channel, new_scene_points[i]->getFirstProjection(), radius);\n    }\n  }\n\n  _scene_points.reserve(_scene_points.size() + new_scene_points.size());\n  std::move(new_scene_points.begin(), new_scene_points.end(), std::back_inserter(_scene_points));\n\n  _frame_buffer.push_back(DescriptorFramePointer(frame));\n\n  if(_frame_buffer.full()) {\n    optimize(result);\n  }\n\n  ++_frame_id;\n}\n\nstatic inline std::vector<double>\nMakePatchWeights(int radius, bool do_gaussian, double s_x = 1.0,\n                 double s_y = 1.0, double a = 1.0)\n{\n  int n = (2*radius + 1) * (2*radius + 1);\n\n  if(do_gaussian) {\n    std::vector<double> ret(n);\n    double sum = 0.0;\n    for(int r = -radius, i = 0; r <= radius; ++r) {\n      const double d_r = (r*r) / s_x;\n      for(int c = -radius; c <= radius; ++c, ++i) {\n        const double d_c = (c*c) / s_y;\n        const double w = a * std::exp( -0.5 * (d_r + d_c) );\n        ret[i] = w;\n        sum += w;\n      }\n    }\n\n    for(int i = 0; i < n; ++i) {\n      ret[i] /= sum;\n    }\n\n    return ret;\n  } else {\n    return std::vector<double>(n, 1.0);\n  }\n}\n\nstatic Vec_<double,6> PoseToParams(const Mat44& T)\n{\n  Vec_<double,6> ret;\n  const Mat_<double,3,3> R = T.block<3,3>(0,0);\n  ceres::RotationMatrixToAngleAxis(ceres::ColumnMajorAdapter3x3(R.data()), ret.data());\n\n  ret[3] = T(0,3);\n  ret[4] = T(1,3);\n  ret[5] = T(2,3);\n  return ret;\n}\n\nstatic Mat_<double,4,4> ParamsToPose(const double* p)\n{\n  Mat_<double,3,3> R;\n  ceres::AngleAxisToRotationMatrix(p, ceres::ColumnMajorAdapter3x3(R.data()));\n\n  Mat_<double,4,4> ret(Mat_<double,4,4>::Identity());\n  ret.block<3,3>(0,0) = R;\n  ret.block<3,1>(0,3) = Vec_<double,3>(p[3], p[4], p[5]);\n  return ret;\n}\n\nclass PhotometricBundleAdjustment::DescriptorError\n{\n public:\n  /**\n   * \\param radius  the patch radius\n   * \\param calib   the camera calibration\n   * \\param p0      the reference frame descriptor must have size (2*radius+1)^2\n   * \\param frame   descriptor data of the image we are matching against\n   */\n  DescriptorError(const Calibration& calib, const std::vector<double>& p0,\n                  const DescriptorFrame* frame, const std::vector<double>& w)\n      : _radius(PatchRadiusFromLength(p0.size() / frame->numChannels())),\n      _calib(calib), _p0(p0.data()), _frame(frame), _patch_weights(w.data())\n  {\n    // TODO should just pass the config to get the radius value\n    assert( p0.size() == w.size() );\n  }\n\n  static ceres::CostFunction* Create(const Calibration& calib,\n                                     const std::vector<double>& p0,\n                                     const DescriptorFrame* f,\n                                     const std::vector<double>& w)\n  {\n    return new ceres::AutoDiffCostFunction<DescriptorError, ceres::DYNAMIC, 6, 3>(\n        new DescriptorError(calib, p0, f, w), p0.size());\n  }\n\n  template <class T> inline\n  bool operator()(const T* const camera, const T* const point, T* residuals) const\n  {\n    T xw[3];\n    ceres::AngleAxisRotatePoint(camera, point, xw);\n    xw[0] += camera[3];\n    xw[1] += camera[4];\n    xw[2] += camera[5];\n\n    T u_w, v_w;\n    _calib.project(xw, u_w, v_w);\n\n    for(size_t k = 0, i=0; k < _frame->numChannels(); ++k) {\n      const auto& I = _frame->getChannel(k);\n      const auto& G = _frame->getChannelGradient(k);\n      const auto& Gx = G.Ix();\n      const auto& Gy = G.Iy();\n\n      for(int y = -_radius, j = 0; y <= _radius; ++y) {\n        const T v = v_w + T(y);\n        for(int x = -_radius; x <= _radius; ++x, ++i, ++j) {\n          const T u = u_w + T(x);\n          const T i0 = T(_p0[i]);\n          const T i1 = SampleWithDerivative(I, Gx, Gy, u, v);\n          residuals[i] = _patch_weights[j] * (i0 - i1);\n        }\n      }\n    }\n\n    // maybe we should return false if the point goes out of the image!\n    return true;\n  }\n\n\n private:\n  const int _radius;\n  const Calibration& _calib;\n  const double* const _p0;\n  const DescriptorFrame* _frame;\n  const double* const _patch_weights;\n}; // DescriptorError\n\nstatic inline ceres::Solver::Options\nGetSolverOptions(int num_threads, bool verbose = false, double tol = 1e-6)\n{\n  ceres::Solver::Options options;\n\n  options.linear_solver_type            = ceres::SPARSE_SCHUR;\n\n  options.minimizer_type                = ceres::TRUST_REGION;\n  options.trust_region_strategy_type    = ceres::LEVENBERG_MARQUARDT;\n\n  options.preconditioner_type           = ceres::CLUSTER_JACOBI;\n  options.visibility_clustering_type    = ceres::SINGLE_LINKAGE;\n  options.minimizer_progress_to_stdout  = verbose;\n  options.max_num_iterations            = 500;\n\n  options.num_threads = num_threads;\n  options.num_linear_solver_threads = options.num_threads;\n\n  options.function_tolerance  = tol;\n  options.gradient_tolerance  = tol;\n  options.parameter_tolerance = tol;\n\n  return options;\n}\n\n\nvoid PhotometricBundleAdjustment::optimize(Result* result)\n{\n  auto frame_id_start = _frame_buffer.front()->id(),\n       frame_id_end   = _frame_buffer.back()->id();\n\n  auto patch_weights = MakePatchWeights(_options.patchRadius, _options.doGaussianWeighting);\n\n  //\n  // collect the camera poses in a single map for easy access\n  //\n  std::map<uint32_t, Vec_<double,6>> camera_params;\n  for(auto id = frame_id_start; id <= frame_id_end; ++id) {\n    // NOTE camera parameters are inverted\n    camera_params[id] = PoseToParams(Eigen::Isometry3d(_trajectory.atId(id)).inverse().matrix());\n  }\n\n  //\n  // get the points that we *should* optimize. They must have a large enough\n  // visibility list\n  //\n  ceres::Problem problem;\n  int num_selected_points = 0;\n  for(auto& pt : _scene_points) {\n    // it is enough to check the visibility list length, because we will remove\n    // points as soon as they leave the optimization window\n    if(pt->numFrames() >= 3 && pt->refFrameId() >= frame_id_start) {\n      num_selected_points++;\n      for(auto id : pt->visibilityList()) {\n        if(id >= frame_id_start && id <= frame_id_end) {\n          pt->setRefined(true);\n          auto* camera_ptr = camera_params[id].data();\n          auto* xyz = pt->X().data();\n\n          const auto huber_t = _options.robustThreshold;\n          auto* loss = huber_t > 0.0 ? new ceres::HuberLoss(huber_t) : nullptr;\n\n          ceres::CostFunction* cost = nullptr;\n          cost = DescriptorError::Create(_calib, pt->descriptor(), getFrameAtId(id), patch_weights);\n          problem.AddResidualBlock(cost, loss, camera_ptr, xyz);\n        }\n      }\n    }\n  }\n\n  // set the first camera cosntant\n  {\n    auto p = camera_params[frame_id_start].data();\n    if(problem.HasParameterBlock(p)) {\n      problem.SetParameterBlockConstant(p);\n    } else {\n      Warn(\"first camera is not in bundle\\n\");\n    }\n  }\n\n  Info(\"Using %d points (%d residual blocks) [id start %d]\\n\",\n       num_selected_points, problem.NumResidualBlocks(), frame_id_start);\n\n  ceres::Solver::Summary summary;\n\n#if HAS_OPENMP\n  int num_threads = _options.numThreads > 0 ? _options.numThreads : std::min(omp_get_max_threads(), 4);\n#else\n  int num_threads = 4;\n#endif\n\n  ceres::Solve(GetSolverOptions(num_threads, _options.verbose), &problem, &summary);\n  if(_options.verbose)\n    std::cout << summary.FullReport() << std::endl;\n\n  //\n  // TODO: run another optimization pass over residuals with small error\n  // (eliminate the outliers)\n  //\n\n  //\n  // put back the refined camera poses\n  //\n  for(auto& it : camera_params) {\n    _trajectory.atId(it.first) = Eigen::Isometry3d(\n        ParamsToPose(it.second.data())).inverse().matrix();\n  }\n\n\n  //\n  // set a side the old points. Since we are doing a sliding window, all points\n  // at frame_id_start should go out\n  //\n  auto points_to_remove = removePointsAtFrame(frame_id_start);\n  printf(\"removing %zu old points\\n\", points_to_remove.size());\n\n  //\n  // check if we should return a result to the user\n  //\n  if(result) {\n    result->poses = _trajectory.poses();\n    const auto npts = points_to_remove.size();\n    result->refinedPoints.resize(npts);\n    result->originalPoints.resize(npts);\n    for(size_t i = 0; i < npts; ++i) {\n      result->refinedPoints[i] = points_to_remove[i]->X();\n      result->originalPoints[i] = points_to_remove[i]->getOriginalPoint();\n    }\n\n    result->initialCost = summary.initial_cost;\n    result->finalCost   = summary.final_cost;\n    result->fixedCost   = summary.fixed_cost;\n    result->numSuccessfulStep = summary.num_successful_steps;\n    result->totalTime = summary.total_time_in_seconds;\n    result->numResiduals = summary.num_residuals;\n    result->message = std::string(summary.message);\n    result->iterationSummary = summary.iterations;\n  }\n}\n\nauto PhotometricBundleAdjustment::getFrameAtId(uint32_t id) const -> const DescriptorFrame*\n{\n  for(const auto& f : _frame_buffer)\n    if(f->id() == id) {\n      return f.get();\n    }\n\n  throw std::runtime_error(\"could not find frame id!\");\n}\n\nauto PhotometricBundleAdjustment::removePointsAtFrame(uint32_t id) -> ScenePointPointerList\n{\n  using namespace std;\n\n  decltype(_scene_points) points_to_keep, points_to_remove;\n\n  points_to_keep.reserve(_scene_points.size());\n  points_to_remove.reserve( 0.5 * _scene_points.size() );\n\n  partition_copy(make_move_iterator(begin(_scene_points)),\n                 make_move_iterator(end(_scene_points)),\n                 back_inserter(points_to_remove),\n                 back_inserter(points_to_keep),\n                 [&](const ScenePointPointer& p) { return p->refFrameId() <= id; });\n\n  _scene_points.swap(points_to_keep);\n  return points_to_remove;\n}\n\n", "meta": {"hexsha": "da761b4745c14c98d81b6d65e1d3f0c6f5631f77", "size": 27338, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/photobundle.cc", "max_stars_repo_name": "halismai/photobundle", "max_stars_repo_head_hexsha": "8b5466fa8ead930625771c4d72232ff4b8da6833", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2016-12-01T05:16:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T14:10:07.000Z", "max_issues_repo_path": "src/photobundle.cc", "max_issues_repo_name": "halismai/photobundle", "max_issues_repo_head_hexsha": "8b5466fa8ead930625771c4d72232ff4b8da6833", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-07-31T07:25:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-31T07:25:05.000Z", "max_forks_repo_path": "src/photobundle.cc", "max_forks_repo_name": "halismai/photobundle", "max_forks_repo_head_hexsha": "8b5466fa8ead930625771c4d72232ff4b8da6833", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2017-01-02T12:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-16T05:58:56.000Z", "avg_line_length": 30.1411245865, "max_line_length": 103, "alphanum_fraction": 0.6463164826, "num_tokens": 7648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.1729996849236632}}
{"text": "/* Copyright Institute of Sound and Vibration Research - All rights reserved */\n\n#include <librcl/listener_compensation.hpp>\n#include <libpanning/LoudspeakerArray.h>\n\n#include <iostream>\n#include <cstdio>\n#include <stdlib.h>\n\n#include <libvisr/signal_flow_context.hpp>\n#include <libobjectmodel/object_vector.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/filesystem/path.hpp>\n\n\n#include <stdexcept>\n#include <string>\n\nnamespace visr\n{\nnamespace rcl\n{\nnamespace test\n{\n\nBOOST_AUTO_TEST_CASE( testListenerCompensation )\n{\n#if 0\n  // TODO: Implement met\n  LoudspeakerArray array;\n  ListenerCompensation listcomp;\n  FILE* file; //why as a pointer?\n  Afloat(*compGains)[MAX_NUM_SPEAKERS];\n  Afloat(*compDelays)[MAX_NUM_SPEAKERS];\n  int j; //number of loudspeakers for printing out the gains and distances\n\t\n  // 5.1 test, 2D Compensation\n\n  boost::filesystem::path const basePath(CMAKE_SOURCE_DIR);\n  boost::filesystem::path const arrayPath = basePath / boost::filesystem::path(\"config/isvr/stereo_audiolab.txt\");\n  BOOST_CHECK_MESSAGE( exists(arrayPath), \"The loudspeaker array file does not exist.\");\n\n  file = fopen( arrayPath.string().c_str(), \"r\");\n  BOOST_CHECK( array.load(file) != -1);\n  if (file != 0)\n  {\n    fclose(file);\n  }\n  file = 0;\n\n  listcomp.setLoudspeakerArray(&array);\n  listcomp.setListenerPosition(1.0, 0.0, 0.0);\n\n\t\n  listcomp.calcGainComp();// calculating delay and gain, this in the future will be combined in same function?\n  listcomp.calcDelayComp();\n\n  compGains = listcomp.getGains(); //getting the gains for the compensation\n  compDelays = listcomp.getDelays(); //getting the gains for the compensation\n\n\n  for (j = 0; j < listcomp.getNumSpeakers(); j++) {\n\n    std::cout << \"Source \" << j <<\"Gain=\" << (*compGains)[j]<<\"\\n\";\n    std::cout << \"Source \" << j << \"Delay=\" <<(*compDelays)[j] << \"\\n\";\n\n  }\n#endif\n}\n\n} // namespace test\n} // namespace rcl\n} // namespce visr\n", "meta": {"hexsha": "105eab76dbeccabd26251cce712e241ca9e4a334", "size": 1908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/librcl/test/test_listener_compensation.cpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/librcl/test/test_listener_compensation.cpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_issues_repo_licenses": ["ISC"], "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/librcl/test/test_listener_compensation.cpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 25.44, "max_line_length": 114, "alphanum_fraction": 0.7070230608, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.1729996849236632}}
{"text": "#pragma warning( disable: 4996 )\r\n#include \"Generic/common/leak_detection.h\"\r\n#include \"Generic/common/SessionLogger.h\"\r\n#include <vector>\r\n#include <string>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <wchar.h>\r\n\r\n#include <boost/foreach.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/thread/thread.hpp>\r\n\r\n#include \"Generic/common/ParamReader.h\"\r\n#include \"Generic/common/StringTransliterator.h\"\r\n#include \"Generic/common/UnexpectedInputException.h\"\r\n#include \"Generic/common/foreach_pair.hpp\"\r\n#include \"ActiveLearning/AnnotatedInstanceRecord.h\"\r\n#include \"ActiveLearning/AnnotatedFeatureRecord.h\"\r\n#include \"ActiveLearning/ActiveLearningData.h\"\r\n#include \"ActiveLearning/DataView.h\"\r\n#include \"ActiveLearning/StringStore.h\"\r\n#include \"ActiveLearning/strategies/ActiveLearningStrategy.h\"\r\n#include \"ActiveLearning/strategies/RandomStrategy.h\"\r\n#include \"ActiveLearning/strategies/CoverageStrategy.h\"\r\n#include \"ActiveLearning/ui/ClientInstance.h\"\r\n#include \"ActiveLearning/ui/JSONUtils.h\"\r\n#include \"ActiveLearning/ui/MongooseUtils.h\"\r\n#include \"ActiveLearning/alphabet/FeatureAlphabet.h\"\r\n#include \"LearnIt/lbfgs/lbfgs.h\"\r\n#include \"LearnIt/Eigen/Core\"\r\n#include \"LearnIt/Eigen/Sparse\"\r\n#include \"LearnIt/db/LearnIt2DB.h\"\r\n#include \"OptimizationView.h\"\r\n#include \"trainer.h\"\r\n#include \"ProbChart.h\"\n\r\nusing namespace Eigen;\r\nusing boost::make_shared;\r\nusing std::wstring; using std::string;\r\n\r\nLearnIt2Trainer::LearnIt2Trainer(LearnIt2DB_ptr db, FeatureAlphabet_ptr alphabet,\r\n\tOptimizationView_ptr slotView, OptimizationView_ptr sentenceView, \r\n\tunsigned int n_instances, bool active_learning) :\r\n\t\t_db(db), _nParams(slotView->nParams()),\r\n\t\t_alphabet(alphabet), _sentenceView(sentenceView), _slotView(slotView),\r\n\t\t_canFinish(!active_learning),\r\n\t\t_iteration(0), _prob_chart(_slotView->data(), _sentenceView->data())\r\n{\r\n\tif (db->readOnly()) {\r\n\t\tthrow UnexpectedInputException(\"LearnIt2Trainer::LearnIt2Trainer\",\r\n\t\t\t\"Cannot construct LearnIt2Trainer from a read-only LearnIt DB\");\r\n\t}\r\n};\r\n\r\n\r\n\r\nvoid LearnIt2Trainer::registerPostIterationHook(PostIterationCallback_ptr cb) {\r\n\t_postIterationHooks.push_back(cb);\r\n}\r\n\r\nvoid LearnIt2Trainer::syncToDB() {\r\n\tVectorXd tmpParams(_nParams);\r\n\r\n\tfor (unsigned int i=0; i<_nParams; ++i) {\r\n\t\tif (_sentenceView->ownsFeature(i)) {\r\n\t\t\ttmpParams(i) = _sentenceView->parameters()(i);\r\n\t\t} else {\r\n\t\t\ttmpParams(i) = _slotView->parameters()(i);\r\n\t\t}\r\n\t}\r\n\r\n\t_alphabet->setFeatureWeights(tmpParams);\r\n}\r\n\r\nvoid LearnIt2Trainer::optimize() {\r\n\toptimize(ParamReader::getRequiredIntParam(\"max_trainer_iterations\"));\r\n}\r\n\r\nvoid LearnIt2Trainer::optimize(int max_iterations) {\r\n\tint max_view_iterations = ParamReader::getOptionalIntParamWithDefaultValue(\n\t\t\t\"max_view_iterations\", 1000);\n\tdouble global_objective_change_threshold = ParamReader::getOptionalFloatParamWithDefaultValue(\n\t\t\t\"global_objective_change_threshold\", 0.01);\n\tdouble lbfgs_gradient_tolerance = ParamReader::getOptionalFloatParamWithDefaultValue(\n\t\t\t\"lbfgs_gradient_tolerance\", 1e-3);\n\tdouble lbfgs_objective_tolerance = ParamReader::getOptionalFloatParamWithDefaultValue(\n\t\t\t\"lbfgs_objective_tolerance\", 0.0);\n\tint outer_iterations_after_can_finish = ParamReader::getOptionalIntParamWithDefaultValue(\n\t\t\t\"iterations_after_annotation\", 25);\n\n\r\n\tSessionLogger::info(\"remember_to_cite\") << L\"Remember to cite \" \r\n\t\t<< L\"Massih-Reza Amini & Cyril Goutte. \\\"A co-classification \"\r\n\t\t<< L\"approach to learning from multilingual corpora.\\\". Machine Learning\"\r\n\t\t<< L\" (2010) 79:105-121\";\r\n\r\n\tint iterations_after_annotation = 0;\n\twhile (!_canFinish) {\r\n\t\tdouble old_global_objective = -std::numeric_limits<double>::max();\r\n\t\t\r\n\t\t_sentenceView->inference();\r\n\t\t_slotView->inference();\r\n\t\t_sentenceView->optimize(max_view_iterations, lbfgs_gradient_tolerance,\n\t\t\t\tlbfgs_objective_tolerance);\r\n\t\t_slotView->optimize(max_view_iterations, lbfgs_gradient_tolerance,\n\t\t\t\tlbfgs_objective_tolerance);\r\n\t\t_global_objective = _sentenceView->value() + _slotView->value();\r\n\r\n\t\tSessionLogger::info(\"global_progress\") << \r\n\t\t\t_iteration << L\": g: \" << _global_objective << L\"; sent: \" <<\r\n\t\t\t_sentenceView->value() << \"; slot: \" << _slotView->value();\r\n\r\n\t\twhile (fabs(_global_objective - old_global_objective) > global_objective_change_threshold) {\r\n\t\t\tif (iterations_after_annotation > outer_iterations_after_can_finish) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++_iteration;\r\n\t\t\tif (_canFinish) {\n\t\t\t\t++iterations_after_annotation;\n\t\t\t}\n\t\t\tpostIterationHook();\r\n\t\t\t_sentenceView->optimize(max_view_iterations, lbfgs_gradient_tolerance,\n\t\t\t\t\tlbfgs_objective_tolerance);\r\n\t\t\t_sentenceView->inference();\r\n\t\t\t_slotView->optimize(max_view_iterations, lbfgs_gradient_tolerance,\n\t\t\t\t\tlbfgs_objective_tolerance);\r\n\t\t\t_slotView->inference();\r\n\t\t\told_global_objective = _global_objective;\r\n\t\t\t_global_objective = _sentenceView->value() + _slotView->value();\r\n\t\t\tSessionLogger::info(\"global_progress\") << \r\n\t\t\t_iteration << L\"(\" << iterations_after_annotation << L\"): g: \" << _global_objective << L\"; sent: \" <<\r\n\t\t\t_sentenceView->value() << \"; slot: \" << _slotView->value();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool LearnIt2Trainer::postIterationHook() {\r\n\tbool ret = false;\r\n\t\r\n\tBOOST_FOREACH(PostIterationCallback_ptr callback, _postIterationHooks) {\r\n\t\tif ((*callback)()) {\r\n\t\t\tsetDirty();\r\n\t\t\tret = true;\r\n\t\t}\r\n\t}\r\n\r\n\t_sentenceView->betweenIterations();\r\n\t_slotView->betweenIterations();\r\n\r\n\t_prob_chart.observe();\r\n\r\n\t++_iteration;\r\n\treturn ret;\r\n}\r\n\r\nvoid LearnIt2Trainer::setDirty() {\r\n\t_sentenceView->setDirty();\r\n\t_slotView->setDirty();\r\n}\r\n\r\nint LearnIt2Trainer::nFeatures() const {\r\n\treturn _nParams;\r\n}\r\n\nLearnIt2DB& LearnIt2Trainer::database() const {\r\n\treturn *_db;\r\n}\r\n\r\nwstring LearnIt2Trainer::UIDiagnosticString() const {\r\n\twstringstream str;\r\n\tstr << L\"Sent View: \" << _sentenceView->UIDiagnosticString() << L\"<br/>\";\r\n\tstr << L\"Slot View: \" << _slotView->UIDiagnosticString() << L\"<br/>\";\r\n\tstr << L\"Global: \" << _global_objective;\r\n\r\n\treturn str.str();\r\n}\r\n\r\nconst ProbChart& LearnIt2Trainer::probChart() const {\r\n\treturn _prob_chart;\r\n}\r\n\r\nboost::mutex& LearnIt2Trainer::updateMutex() {\r\n\treturn _active_learning_update_mutex;\r\n}\r\n\r\nvoid LearnIt2Trainer::stop() {\r\n\t_canFinish = true;\r\n}\r\n\r\ndouble LearnIt2Trainer::featureWeight(int feat) const {\r\n\tif (_sentenceView->ownsFeature(feat)) {\r\n\t\treturn _sentenceView->parameters()(feat);\r\n\t} else {\r\n\t\treturn _slotView->parameters()(feat);\r\n\t}\r\n}\r\n\r\nstd::wstring LearnIt2Trainer::featureName(int feat) const {\r\n\treturn _alphabet->getFeatureName(feat);\r\n}\r\n\r\nvoid LearnIt2Trainer::_test_clear_objective_components() {\r\n\t_sentenceView->_test_clear_objective_components();\r\n\t_slotView->_test_clear_objective_components();\r\n}\n", "meta": {"hexsha": "b7f93de925266dba8af9eb5f971441c897f11a6d", "size": 6681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LearnIt2Trainer/trainer.cpp", "max_stars_repo_name": "BBN-E/serif", "max_stars_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T19:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:57:00.000Z", "max_issues_repo_path": "src/LearnIt2Trainer/trainer.cpp", "max_issues_repo_name": "BBN-E/serif", "max_issues_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "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/LearnIt2Trainer/trainer.cpp", "max_forks_repo_name": "BBN-E/serif", "max_forks_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "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.1201923077, "max_line_length": 105, "alphanum_fraction": 0.7395599461, "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.1729996849236632}}
{"text": "// -*- C++ -*-\n//\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n//\n//                                   Jiao Lin\n//                      California Institute of Technology\n//                         (C) 2007 All Rights Reserved\n//\n// {LicenseText}\n//\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n//\n\n\n#include <sstream>\n#include <boost/python.hpp>\n#include \"mccomponents/kernels/sample/phonon/IncoherentElastic.h\"\n#include \"mccomponents/boostpython_binding/wrap_kernel.h\"\n\n\nnamespace wrap_mccomponents {\n\n  void wrap_Phonon_IncoherentElastic_kernel()\n  {\n    using namespace boost::python;\n    using namespace mccomponents::boostpython_binding;\n\n    typedef mccomponents::kernels::phonon::IncoherentElastic w_t;\n\n    kernel_wrapper<w_t>::wrap\n      ( \"Phonon_IncoherentElastic_kernel\",\n\tinit<\n\tconst w_t::atoms_t &, // atoms\n\tw_t::float_t, // unitcell_vol. AA**3\n\tw_t::float_t, // dw_core. AA**2\n\tw_t::float_t, // scattering_xs. barn\n\tw_t::float_t  // absorption_xs. barn\n\t> ()\n\t[with_custodian_and_ward<1,2> () ]\n\t)\n      ;\n    \n  }\n\n}\n\n\n// version\n// $Id: wrap_Phonon_IncoherentElastic_kernel.cc 603 2010-10-04 15:58:16Z linjiao $\n\n// End of file \n", "meta": {"hexsha": "41c1ff9fc1b019868046682ee6680c71444c31f7", "size": 1223, "ext": "cc", "lang": "C++", "max_stars_repo_path": "packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_IncoherentElastic_kernel.cc", "max_stars_repo_name": "mcvine/mcvine", "max_stars_repo_head_hexsha": "42232534b0c6af729628009bed165cd7d833789d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T03:59:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-23T02:54:19.000Z", "max_issues_repo_path": "packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_IncoherentElastic_kernel.cc", "max_issues_repo_name": "mcvine/mcvine", "max_issues_repo_head_hexsha": "42232534b0c6af729628009bed165cd7d833789d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 293.0, "max_issues_repo_issues_event_min_datetime": "2015-10-29T17:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T16:31:09.000Z", "max_forks_repo_path": "packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_IncoherentElastic_kernel.cc", "max_forks_repo_name": "mcvine/mcvine", "max_forks_repo_head_hexsha": "42232534b0c6af729628009bed165cd7d833789d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-25T00:53:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-25T00:53:31.000Z", "avg_line_length": 23.5192307692, "max_line_length": 82, "alphanum_fraction": 0.5576451349, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.17299968492366313}}
{"text": "#include \"Generator.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nnamespace tbu=toolbox::util;\n\nstruct some_resource {\n    int x;\n    explicit some_resource(int x) : x(x) {\n        std::printf(\"some_resource(%i)\\n\", x);\n    }\n    ~some_resource() {\n        std::printf(\"~some_resource(%i)\\n\", x);\n    }\n};\n\nstatic tbu::generator<const uint64_t> fib(int max) {\n    some_resource r{2};\n    auto a = 0, b = 1 ;\n    for(auto n = 0; n <  max; n ++)  {\n        co_yield b;\n        const auto next = a + b;\n        a = b, b = next;\n    }\n}\n\n\nstatic tbu::generator<const uint64_t> test(int max) {\n    auto g = fib(max);\n    some_resource r{1};\n    co_yield std::move(g);    \n}\n\n\nBOOST_AUTO_TEST_SUITE(GeneratorSuite)\n\nBOOST_AUTO_TEST_CASE(GeneratorIterate)\n{\n    //setbuf(stdout, NULL);\n\n#if __has_include(<ranges>)\n    auto v = test(10) | std::views::drop(9);\n    return *std::ranges::begin(v);\n#else\n    uint64_t  i = 0;\n    for(auto a : test(10)) {\n        i = a;\n    }\n    return i;\n#endif\n}\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "f04abe9cca1cbbe13a7aa6c1c062cdc504cb5802", "size": 1015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox/util/Generator.ut.cpp", "max_stars_repo_name": "mmitkevich/toolbox-cpp", "max_stars_repo_head_hexsha": "59e26154acbd990de9658bf229ebdbf7f89fc0c8", "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": "toolbox/util/Generator.ut.cpp", "max_issues_repo_name": "mmitkevich/toolbox-cpp", "max_issues_repo_head_hexsha": "59e26154acbd990de9658bf229ebdbf7f89fc0c8", "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": "toolbox/util/Generator.ut.cpp", "max_forks_repo_name": "mmitkevich/toolbox-cpp", "max_forks_repo_head_hexsha": "59e26154acbd990de9658bf229ebdbf7f89fc0c8", "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": 18.4545454545, "max_line_length": 53, "alphanum_fraction": 0.5852216749, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17299968151092637}}
{"text": "#include <string>\n#include <set>\n#include <regex>\n#include <iostream>\n#include <algorithm>\n#include <boost/program_options.hpp>\n#include \"JavaRandom.hpp\"\n#include \"minecrack-48bit.hpp\"\n\nusing namespace std;\n\n/*\n * Get exceptions instead of asserts from boost.\n */\nnamespace boost {\nvoid assertion_failed(const char* expr, const char* function, const char* file, long line) {\n\tthrow logic_error(\"Boost assert failed: \"s + expr + \", at \" + file + \":\" + to_string(line) + \" in \" + function);\n}\n\nvoid assertion_failed_msg(const char* expr, const char* msg, const char* function, const char* file, long line) {\n\tthrow logic_error(\n\t\t\t\"Boost assert failed (\"s + msg + \"): \" + \"\" + expr + \", at \" + file + \":\" + to_string(line) + \" in \" +\n\t\t\tfunction);\n}\n}\n\nnamespace cmdline {\n\nbool verbose;\nstd::vector<int64_t> chunk_seed_offset;\n\n}\n\nint main(int argc, char** argv) try {\n\t{\n\t\tusing namespace boost::program_options;\n\t\toptions_description options;\n\t\toptions.add_options()\n\t\t\t\t(\"verbose,v\", \"print extra informations\")\n\t\t\t\t(\"force,f\", \"do not bail out if too few chunks are provided\");\n\t\tif (argc == 1) {\n\t\t\tcerr << \"Usage: \" << argv[0] << \" [options] chunk1X:chunk1Z chunk2X:chunk2Z ...\" << endl << \"Options:\"\n\t\t\t     << endl << options;\n\t\t\treturn 0;\n\t\t}\n\t\toptions_description options_with_chunks;\n\t\toptions_with_chunks.add(options).add_options()(\"slime-chunk\", value<vector<string>>());\n\t\tpositional_options_description positional;\n\t\tpositional.add(\"slime-chunk\", -1);\n\t\tvariables_map vm;\n\t\ttry {\n\t\t\tstore(command_line_parser(argc, argv).options(options_with_chunks).positional(positional).run(),\n\t\t\t\t\tvm);\n\t\t\tnotify(vm);\n\t\t} catch (const boost::program_options::error& e) { throw invalid_argument(e.what()); }\n\t\tcmdline::verbose = vm.count(\"verbose\");\n\t\tif (!vm.count(\"slime-chunk\"))\n\t\t\tthrow invalid_argument(\"You must specify some slime chunks\");\n\t\tauto slimechunks_vector = vm[\"slime-chunk\"].as<vector<string>>();\n\t\tset<string> slimechunks(slimechunks_vector.begin(), slimechunks_vector.end());\n\t\tregex slimechunk_regex(\"([\\\\-\\\\+]?\\\\d+)\\\\:([\\\\-\\\\+]?\\\\d+)\", regex::ECMAScript | regex::optimize);\n\t\tsmatch result;\n\t\tfor (auto& chunkspec: slimechunks) {\n\t\t\tif (!regex_match(chunkspec, result, slimechunk_regex))\n\t\t\t\tthrow invalid_argument(\"slime chunk coordinate \" + chunkspec + \" cannot be parsed\");\n\t\t\ttry {\n\t\t\t\tint chunkX = stoi(result[1]), chunkZ = stoi(result[2]);\n\t\t\t\tcmdline::chunk_seed_offset.push_back(slime_seed_offset(chunkX, chunkZ));\n\t\t\t} catch (const out_of_range& o) {\n\t\t\t\tthrow invalid_argument(\"slime chunk coordinate \" + chunkspec + \" cannot is out of int range\");\n\t\t\t}\n\t\t}\n\t\t/*\n\t\t * each slime chunk gives log2(10) bits of information on the 48bit seed of the world. At least 15 slime\n\t\t * chunks must be found to have one or just few 48bit candidates.\n\t\t */\n\t\tif (cmdline::chunk_seed_offset.size() < 13 && !vm.count(\"force\"))\n\t\t\tthrow invalid_argument(\"Too few slime chunks provided, at least 13 are needed (or use the -f option)\");\n\t\tif (cmdline::chunk_seed_offset.size() < 15)\n\t\t\tcerr << \"Warning: 15 or more slime chunks should be provided\" << endl;\n\t}\n\n\t//calculate lower 18bits candidates\n\tvector<uint32_t> lowbits_candidates = ::lowbits_candidates();\n\tif (lowbits_candidates.empty())\n\t\tthrow invalid_argument(\"The provided slime chunks are wrong or they are generated by a modded Minecraft version\");\n\tif (cmdline::verbose) {\n\t\tcerr << \"Found \" << lowbits_candidates.size() << \" lowbits candidates:\";\n\t\tfor (auto c: lowbits_candidates) cerr << ' ' << c;\n\t\tcerr << endl;\n\t}\n\n\tauto seeds = test_seeds(lowbits_candidates);\n\tsort(seeds.begin(), seeds.end());\n\tfor (auto s: seeds) cout << s << endl;\n\n} catch (const invalid_argument& e) {\n\tcerr << \"Invalid argument: \" << e.what() << endl;\n\treturn 1;\n} catch (const exception& e) {\n\tcerr << e.what() << endl;\n\treturn 2;\n}\n", "meta": {"hexsha": "4ca5ed0e201a2a3db163917f9e099885b1ff1efa", "size": 3791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slime/main.cpp", "max_stars_repo_name": "pisto/minecrack", "max_stars_repo_head_hexsha": "d024cd306f80d35238109063be2787a766169a0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T13:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:40:32.000Z", "max_issues_repo_path": "slime/main.cpp", "max_issues_repo_name": "pisto/minecrack", "max_issues_repo_head_hexsha": "d024cd306f80d35238109063be2787a766169a0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-04-02T13:04:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-18T23:02:23.000Z", "max_forks_repo_path": "slime/main.cpp", "max_forks_repo_name": "pisto/minecrack", "max_forks_repo_head_hexsha": "d024cd306f80d35238109063be2787a766169a0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-11T19:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T12:55:23.000Z", "avg_line_length": 36.4519230769, "max_line_length": 116, "alphanum_fraction": 0.6826694803, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.1729996746854528}}
{"text": "/**\n * @file numpdesetup_test.cc\n * @brief NPDE homework NumPDESetup code\n * @author Ralf Hiptmair, Oliver Rietmann, Erick Schulz\n * @date 17.02.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../numpdesetup.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <iostream>\n\nnamespace NumPDESetup::test {\n\n/* SAM_LISTING_BEGIN_3 */\nTEST(NumPDESetup, dummyFunction) {\n  double x = 1.0;\n  int n = 2;\n  // Invoke the function to be tested\n  Eigen::Vector2d v = NumPDESetup::dummyFunction(x, n);\n  // The expected solution\n  Eigen::Vector2d v_ref = {1.0, 1.0};\n  // Check whether function call produces correct result using the Google test\n  // framework\n  double tol = 1.0e-8;\n  ASSERT_NEAR(0.0, (v - v_ref).lpNorm<Eigen::Infinity>(), tol);\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace NumPDESetup::test\n", "meta": {"hexsha": "c4497b756be72009dcfeb7779564f230d3c3d344", "size": 815, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NumPDESetup/templates/test/numpdesetup_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/NumPDESetup/templates/test/numpdesetup_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/NumPDESetup/templates/test/numpdesetup_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 23.9705882353, "max_line_length": 78, "alphanum_fraction": 0.6944785276, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.1729837438815902}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, 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_STRATEGIES_IS_CONVEX_SPHERICAL_HPP\n#define BOOST_GEOMETRY_STRATEGIES_IS_CONVEX_SPHERICAL_HPP\n\n\n#include <boost/geometry/strategies/convex_hull/spherical.hpp>\n#include <boost/geometry/strategies/detail.hpp>\n#include <boost/geometry/strategies/is_convex/services.hpp>\n#include <boost/geometry/strategies/spherical/point_in_point.hpp>\n#include <boost/geometry/util/type_traits.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace is_convex\n{\n\ntemplate <typename CalculationType = void>\nclass spherical : public strategies::convex_hull::spherical<CalculationType>\n{\npublic:\n    template <typename Geometry1, typename Geometry2>\n    static auto relate(Geometry1 const&, Geometry2 const&,\n                       std::enable_if_t\n                            <\n                                util::is_pointlike<Geometry1>::value\n                             && util::is_pointlike<Geometry2>::value\n                            > * = nullptr)\n    {\n        return strategy::within::spherical_point_point();\n    }\n};\n\nnamespace services\n{\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, spherical_equatorial_tag>\n{\n    using type = strategies::is_convex::spherical<>;\n};\n\ntemplate <typename CT>\nstruct strategy_converter<strategy::side::spherical_side_formula<CT>>\n{\n    static auto get(strategy::side::spherical_side_formula<CT> const& )\n    {\n        return strategies::is_convex::spherical<CT>();\n    }\n};\n\n} // namespace services\n\n}} // namespace strategies::is_convex\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_IS_CONVEX_SPHERICAL_HPP\n", "meta": {"hexsha": "06ff3fae8c3a817cbdf7786eebcef0378239ad72", "size": 1870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/strategies/is_convex/spherical.hpp", "max_stars_repo_name": "angryDuck2/PopcornTorrent", "max_stars_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "max_stars_repo_licenses": ["MIT"], "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": "include/boost/geometry/strategies/is_convex/spherical.hpp", "max_issues_repo_name": "angryDuck2/PopcornTorrent", "max_issues_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "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": "include/boost/geometry/strategies/is_convex/spherical.hpp", "max_forks_repo_name": "angryDuck2/PopcornTorrent", "max_forks_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "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": 27.5, "max_line_length": 76, "alphanum_fraction": 0.7122994652, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.17291855029275408}}
{"text": "//\n//  replicates.cpp\n//  cufflinks\n//\n//  Created by Cole Trapnell on 3/11/11.\n//  Copyright 2011 Cole Trapnell. All rights reserved.\n//\n\n#include <boost/thread.hpp>\n\nextern \"C\" {\n#include \"locfit/local.h\"\n}\n\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/poisson_distribution.hpp>\n\n#include \"replicates.h\"\n//#include \"rounding.h\"\n\n#if ENABLE_THREADS\t\nboost::mutex _locfit_lock;\n#endif\n\nMassDispersionModel::MassDispersionModel(const std::string& name,\n                                         const std::vector<double>& scaled_compatible_mass_means, \n                                         const std::vector<double>& scaled_compatible_variances,\n                                         const std::vector<double>& scaled_mass_variances) \n{\n    _name = name;\n    \n    if (scaled_compatible_mass_means.size() != scaled_mass_variances.size())\n    {\n        fprintf (stderr, \"Error: dispersion model table is malformed\\n\");\n    }\n    \n    double last_val = 0;\n    for (size_t i = 0; i < scaled_compatible_mass_means.size(); i++)\n    {\n        \n        if (last_val > scaled_compatible_mass_means[i])\n        {\n            fprintf (stderr, \"Error: DispersionModel input is malformed\\n\");\n        }\n        \n        if ( i == 0 || last_val < scaled_compatible_mass_means[i])\n        {\n            _scaled_compatible_mass_means.push_back(scaled_compatible_mass_means[i]);\n            _scaled_compatible_variances.push_back(scaled_compatible_variances[i]);\n            _scaled_mass_variances.push_back(scaled_mass_variances[i]);\n        }\n        else\n        {\n            // skip this element if it's equal to what we've already seen\n        }\n        \n        last_val = scaled_compatible_mass_means[i];\n    }\n}\n\ndouble MassDispersionModel::scale_mass_variance(double scaled_mass) const \n{\n    if (scaled_mass <= 0)\n        return 0.0;\n    \n    if (_scaled_compatible_mass_means.size() < 2 || _scaled_mass_variances.size() < 2)\n    {\n        return scaled_mass; // revert to poisson.\n    }\n    if (scaled_mass > _scaled_compatible_mass_means.back())\n    {\n        // extrapolate to the right\n        // off the right end\n        double x1_mean = _scaled_compatible_mass_means[_scaled_compatible_mass_means.size()-2];\n        double x2_mean = _scaled_compatible_mass_means[_scaled_compatible_mass_means.size()-1];\n        \n        double y1_var = _scaled_mass_variances[_scaled_compatible_mass_means.size()-2];\n        double y2_var = _scaled_mass_variances[_scaled_compatible_mass_means.size()-1];\n        double slope = 0.0;                \n        if (x2_mean != x1_mean)\n        {\n            slope = (y2_var - y1_var) / (x2_mean-x1_mean);\n        }\n        else if (y1_var == y2_var)\n        {\n            assert (false); // should have a unique'd table\n        }\n        double mean_interp = _scaled_mass_variances[_scaled_compatible_mass_means.size()-1] -\n        slope*(scaled_mass - _scaled_compatible_mass_means.size()-1);\n        if (mean_interp < scaled_mass)\n            mean_interp = scaled_mass;\n        assert (!isnan(mean_interp) && !isinf(mean_interp));\n        return mean_interp;\n    }\n    else if (scaled_mass < _scaled_compatible_mass_means.front())\n    {\n        // extrapolate to the left\n        // off the left end?\n        double x1_mean = _scaled_compatible_mass_means[0];\n        double x2_mean = _scaled_compatible_mass_means[1];\n        \n        double y1_var = _scaled_mass_variances[0];\n        double y2_var = _scaled_mass_variances[1];\n        double slope = 0.0;                \n        if (x2_mean != x1_mean)\n        {\n            slope = (y2_var - y1_var) / (x2_mean-x1_mean);\n        }\n        else if (y1_var == y2_var)\n        {\n            assert (false); // should have a unique'd table\n        }\n        double mean_interp = _scaled_mass_variances[0] - slope*(_scaled_compatible_mass_means[0] - scaled_mass);\n        if (mean_interp < scaled_mass)\n            mean_interp = scaled_mass;\n\n        assert (!isnan(mean_interp) && !isinf(mean_interp));\n        return mean_interp;\n    }\n    \n    vector<double>::const_iterator lb;\n    lb = lower_bound(_scaled_compatible_mass_means.begin(), \n                     _scaled_compatible_mass_means.end(), \n                     scaled_mass);\n    if (lb < _scaled_compatible_mass_means.end())\n    {\n        int d = lb - _scaled_compatible_mass_means.begin();\n        if (*lb == scaled_mass || lb == _scaled_compatible_mass_means.begin())\n        {\n            double var = _scaled_mass_variances[d];\n            if (var < scaled_mass) // revert to poisson if underdispersed\n                var = scaled_mass;\n            assert (!isnan(var) && !isinf(var));\n            return var;\n        }\n        \n        \n        //in between two points on the scale.\n        d--;\n        \n        if (d < 0)\n        {\n            fprintf(stderr, \"ARG d < 0, d = %d \\n\", d);\n        }\n        \n        if (d >= _scaled_compatible_mass_means.size())\n        {\n            fprintf(stderr, \"ARG d >= _scaled_compatible_mass_means.size(), d = %d\\n\", d);\n        }\n        if (d >= _scaled_mass_variances.size())\n        {\n            fprintf(stderr, \"ARG d >= _scaled_mass_variances.size(), d = %d\\n\", d);\n        }\n        \n        double x1_mean = _scaled_compatible_mass_means[d];\n        double x2_mean = _scaled_compatible_mass_means[d + 1];\n        \n        double y1_var = _scaled_mass_variances[d];\n        double y2_var = _scaled_mass_variances[d + 1];\n        double slope = 0.0;                \n        if (x2_mean != x1_mean)\n        {\n            slope = (y2_var - y1_var) / (x2_mean-x1_mean);\n        }\n        else if (y1_var == y2_var)\n        {\n            assert (false); // should have a unique'd table\n        }\n        double mean_interp = _scaled_mass_variances[d] + slope*(scaled_mass - _scaled_compatible_mass_means[d]);\n        if (mean_interp < scaled_mass) // revert to poisson if underdispersed\n            mean_interp = scaled_mass;\n \n        assert (!isnan(mean_interp) && !isinf(mean_interp));\n        return mean_interp;\n    }\n    else\n    {\n        assert (!isnan(scaled_mass) && !isinf(scaled_mass));\n        return scaled_mass; // revert to poisson assumption\n    }\n}\n\n\nMleErrorModel::MleErrorModel(const std::string& name,\n                             const std::vector<double>& scaled_compatible_mass_means,\n                             const std::vector<double>& scaled_mle_variances)\n{\n    _name = name;\n    \n    if (scaled_compatible_mass_means.size() != scaled_mle_variances.size())\n    {\n        fprintf (stderr, \"Error: dispersion model table is malformed\\n\");\n    }\n    \n    double last_val = 0;\n    for (size_t i = 0; i < scaled_compatible_mass_means.size(); i++)\n    {\n        \n        if (last_val > scaled_compatible_mass_means[i])\n        {\n            fprintf (stderr, \"Error: MLEError input is malformed\\n\");\n        }\n        \n        if ( i == 0 || last_val < scaled_compatible_mass_means[i])\n        {\n            _scaled_compatible_mass_means.push_back(scaled_compatible_mass_means[i]);\n            _scaled_mle_variances.push_back(scaled_mle_variances[i]);\n        }\n        else\n        {\n            // skip this element if it's equal to what we've already seen\n        }\n        \n        last_val = scaled_compatible_mass_means[i];\n    }\n}\n\ndouble MleErrorModel::scale_mle_variance(double scaled_mass) const\n{\n    if (scaled_mass <= 0)\n        return 0.0;\n    \n    if (_scaled_compatible_mass_means.size() < 2 || _scaled_mle_variances.size() < 2)\n    {\n        return 0; // revert to poisson.\n    }\n    if (scaled_mass > _scaled_compatible_mass_means.back())\n    {\n        return 0;\n    }\n    else if (scaled_mass < _scaled_compatible_mass_means.front())\n    {\n        return 0; // we won't add anything if we're out of the range of the table\n    }\n    \n    vector<double>::const_iterator lb;\n    lb = lower_bound(_scaled_compatible_mass_means.begin(),\n                     _scaled_compatible_mass_means.end(),\n                     scaled_mass);\n    if (lb < _scaled_compatible_mass_means.end())\n    {\n        int d = lb - _scaled_compatible_mass_means.begin();\n        if (*lb == scaled_mass || lb == _scaled_compatible_mass_means.begin())\n        {\n            double var = _scaled_mle_variances[d];\n            assert (!isnan(var) && !isinf(var));\n            if (var < 0)\n                var = 0;\n            return var;\n        }\n        \n        //in between two points on the scale.\n        d--;\n        \n        if (d < 0)\n        {\n            fprintf(stderr, \"ARG d < 0, d = %d \\n\", d);\n        }\n        \n        if (d >= _scaled_compatible_mass_means.size())\n        {\n            fprintf(stderr, \"ARG d >= _scaled_compatible_mass_means.size(), d = %d\\n\", d);\n        }\n        if (d >= _scaled_mle_variances.size())\n        {\n            fprintf(stderr, \"ARG d >= _scaled_mass_variances.size(), d = %d\\n\", d);\n        }\n        \n        double x1_mean = _scaled_compatible_mass_means[d];\n        double x2_mean = _scaled_compatible_mass_means[d + 1];\n        \n        double y1_var = _scaled_mle_variances[d];\n        double y2_var = _scaled_mle_variances[d + 1];\n        double slope = 0.0;\n        if (x2_mean != x1_mean)\n        {\n            slope = (y2_var - y1_var) / (x2_mean-x1_mean);\n        }\n        else if (y1_var == y2_var)\n        {\n            assert (false); // should have a unique'd table\n        }\n        double mean_interp = _scaled_mle_variances[d] + slope*(scaled_mass - _scaled_compatible_mass_means[d]);\n        if (mean_interp < 0)\n            mean_interp = 0;\n        \n        assert (!isnan(mean_interp) && !isinf(mean_interp));\n        return mean_interp;\n    }\n    else\n    {\n        assert (!isnan(scaled_mass) && !isinf(scaled_mass));\n        return 0; // revert to poisson assumption\n    }\n}\n\nvoid transform_counts_to_common_scale(const vector<double>& scale_factors,\n                                      vector<LocusCountList>& sample_compatible_count_table)\n{\n    // Transform raw counts to the common scale\n    for (size_t i = 0; i < sample_compatible_count_table.size(); ++i)\n    {\n        LocusCountList& p = sample_compatible_count_table[i];\n        for (size_t j = 0; j < p.counts.size(); ++j)\n        {\n            assert (scale_factors.size() > j);\n            p.counts[j] *= (1.0 / scale_factors[j]);\n        }\n    }\n}\n\nvoid calc_geometric_scaling_factors(const vector<LocusCountList>& sample_compatible_count_table,\n                                    vector<double>& scale_factors)\n{\n    \n    vector<double> log_geom_means(sample_compatible_count_table.size(), 0.0);\n    \n    for (size_t i = 0; i < sample_compatible_count_table.size(); ++i)\n    {\n        const LocusCountList& p = sample_compatible_count_table[i];\n        \n        for (size_t j = 0; j < p.counts.size(); ++j)\n        {\n            //assert (log_geom_means.size() > j);\n            //if (floor(p.counts[j]) > 0)\n            //{\n                log_geom_means[i] += (1.0/p.counts.size()) * log(floor(p.counts[j]));\n            //}\n            \n        }\n        //log_geom_means[i] = pow(log_geom_means[i], 1.0/(double)p.counts.size());\n    }\n    \n    for (size_t j = 0; j < scale_factors.size(); ++j)\n    {\n        vector<double> tmp_counts;\n        for (size_t i = 0; i < sample_compatible_count_table.size(); ++i)\n        {\n            if (log_geom_means[i] && !isinf(log_geom_means[i]) && !isnan(log_geom_means[i]) && floor(sample_compatible_count_table[i].counts[j]))\n            {\n                double gm = (double)log(floor(sample_compatible_count_table[i].counts[j])) - log_geom_means[i];\n                assert (!isinf(gm));\n                tmp_counts.push_back(gm);\n            }\n        }\n        sort(tmp_counts.begin(), tmp_counts.end());\n        if (!tmp_counts.empty())\n            scale_factors[j] = exp(tmp_counts[tmp_counts.size()/2]);\n        else\n            scale_factors[j] = 1.0;\n    }\n}\n\nvoid calc_classic_fpkm_scaling_factors(const vector<LocusCountList>& sample_compatible_count_table,\n                                       vector<double>& scale_factors)\n{\n    vector<double> total_counts(sample_compatible_count_table.size(), 0.0);\n    \n    for (size_t i = 0; i < sample_compatible_count_table.size(); ++i)\n    {\n        const LocusCountList& p = sample_compatible_count_table[i];\n        \n        for (size_t j = 0; j < p.counts.size(); ++j)\n        {\n            total_counts[j] += floor(p.counts[j]);\n        }\n    }\n    \n    double all_library_counts = accumulate(total_counts.begin(), total_counts.end(), 0.0);\n    if (all_library_counts == 0.0)\n    {\n        for (size_t i = 0; i < scale_factors.size(); ++i)\n        {\n            scale_factors[i] = 1.0;\n        }\n        return;\n    }\n    for (size_t i = 0; i < scale_factors.size(); ++i)\n    {\n        scale_factors[i] = total_counts[i] / all_library_counts;\n    }\n    \n    double avg_scaling_factor = accumulate(scale_factors.begin(), scale_factors.end(), 0.0);\n    avg_scaling_factor /= scale_factors.size();\n    \n    for (size_t i = 0; i < scale_factors.size(); ++i)\n    {\n        scale_factors[i] = scale_factors[i] / avg_scaling_factor;\n    }\n}\n\nvoid calc_estimated_absolute_scaling_factors(vector<boost::shared_ptr<ReadGroupProperties> > & all_read_groups,\n                                             vector<double>& scale_factors)\n{\n    assert (scale_factors.size() == all_read_groups.size());\n    for (size_t i = 0; i < scale_factors.size(); ++i)\n    {\n        double med_cov = all_read_groups[i]->mode_transcript_coverage();\n        if (med_cov == 0)\n        {\n            scale_factors[i] = 0.0;\n        }\n        else if (med_cov == -1)\n        {\n            fprintf(stderr, \"Error: estimated-absolute requires pre-calculated CXB files\\n\");\n            exit(1);\n        }\n        \n        scale_factors[i] =  med_cov * 1000000000 / (all_read_groups[i]->normalized_map_mass()) ;\n    }\n    \n//\n//    void adjust_fpkms_by_median_coverage(const vector<vector<double > >& median_coverage,\n//                                         FPKMTrackingTable& tracking)\n//    {\n//        for (FPKMTrackingTable::iterator itr = tracking.begin(); itr != tracking.end(); ++itr)\n//        {\n//            if (itr != tracking.end())\n//            {\n//                FPKMTracking& track = itr->second;\n//                vector<FPKMContext>& fpkms = track.fpkm_series;\n//                \n//                for (size_t i = 0; i < fpkms.size(); ++i)\n//                {\n//                    for (size_t j = 0; j != fpkms[i].tracking_info_per_rep.size();\n//                         ++j)\n//                    {\n//                        double& FPKM = fpkms[i].tracking_info_per_rep[j].fpkm;\n//                        FPKM /= median_coverage[i][j];\n//                        FPKM *= fpkms[i].tracking_info_per_rep[j].rg_props->normalized_map_mass();\n//                        FPKM /= 1000000000;\n//                    }\n//                }\n//            }\n//        }\n//    }\n//\n//    \n}\n\n\n\nvoid calc_quartile_scaling_factors(const vector<LocusCountList>& sample_compatible_count_table,\n                                   vector<double>& scale_factors)\n{\n    \n    if (sample_compatible_count_table.empty())\n        return;\n    \n    vector<double> upper_quartiles(sample_compatible_count_table.front().counts.size(), 0.0);\n    vector<double> total_common_masses(sample_compatible_count_table.front().counts.size(), 0.0);\n    \n    for (size_t i = 0; i < sample_compatible_count_table.front().counts.size(); ++i)\n    {\n        vector<double> common_scaled_counts;\n        double total_common = 0.0;\n\n        for (size_t j = 0; j < sample_compatible_count_table.size(); ++j)\n        {\n        \n            //boost::shared_ptr<ReadGroupProperties> rg = bundle_factories[fac_idx];\n            //double scaled_mass = scale_factors[fac_idx] * rg->total_map_mass();\n            \n            total_common += sample_compatible_count_table[j].counts[i];\n            common_scaled_counts.push_back(sample_compatible_count_table[j].counts[i]);\n        }\n    \n        sort(common_scaled_counts.begin(), common_scaled_counts.end());\n        if (common_scaled_counts.empty())\n            continue;\n        \n        int upper_quart_index = common_scaled_counts.size() * 0.75;\n        double upper_quart_count = common_scaled_counts[upper_quart_index];\n        upper_quartiles[i] = upper_quart_count;\n        total_common_masses[i] = total_common;\n    }\n    \n    long double total_mass = accumulate(total_common_masses.begin(), total_common_masses.end(), 0.0);\n    long double total_norm_mass = accumulate(upper_quartiles.begin(), upper_quartiles.end(), 0.0);\n    \n    for (size_t i = 0; i < sample_compatible_count_table.front().counts.size(); ++i)\n    {\n        if (total_mass > 0)\n        {\n            double scaling_factor = upper_quartiles[i];\n            scaling_factor /= (total_norm_mass / upper_quartiles.size());\n            scale_factors[i] = scaling_factor;\n        }\n        else\n        {\n            scale_factors[i] = 1.0;\n        }\n    }\n}\n\nvoid calc_tmm_scaling_factors(const vector<LocusCountList>& sample_compatible_count_table,\n                              vector<double>& scale_factors)\n{\n    scale_factors = vector<double>(sample_compatible_count_table.size(), 1.0);\n}\n\nstatic const int min_loci_for_fitting = 30;\n\nstruct SCVInterpolator\n{\n    void add_scv_pair(double est_scv, double true_scv)\n    {\n        true_scvs.push_back(true_scv);\n        est_scvs.push_back(est_scv);\n    }\n    \n    void finalize() \n    {\n        vector<pair<double, double> > pv;\n        for (size_t i =0; i < true_scvs.size(); ++i)\n        {\n            pv.push_back(make_pair(est_scvs[i], true_scvs[i]));\n        }\n        sort(pv.begin(), pv.end());\n    }\n    \n    // This was built from the dispersion model interpolator - we should refactor these \n    // into a single routine.\n    double interpolate_scv(double est_scv)\n    {\n//        if (est_scv <= 0)\n//            return 0.0;\n        \n        if (est_scvs.size() < 2 || true_scvs.size() < 2)\n        {\n            return est_scv; // revert to poisson.\n        }\n        if (est_scv > est_scvs.back())\n        {\n            //fprintf(stderr, \"Warning: extrapolating to the right\\n\");\n            // extrapolate to the right\n            // off the right end\n            double x1_mean = est_scvs[est_scvs.size()-2];\n            double x2_mean = est_scvs[est_scvs.size()-1];\n            \n            double y1_var = true_scvs[est_scvs.size()-2];\n            double y2_var = true_scvs[est_scvs.size()-1];\n            double slope = 0.0;                \n            if (x2_mean != x1_mean)\n            {\n                slope = (y2_var - y1_var) / (x2_mean-x1_mean);\n            }\n            else if (y1_var == y2_var)\n            {\n                assert (false); // should have a unique'd table\n            }\n            double mean_interp = true_scvs[est_scvs.size()-1] -\n                slope*(est_scv - est_scvs.size()-1);\n//            if (mean_interp < est_scv)\n//                mean_interp = est_scv;\n            assert (!isnan(mean_interp) && !isinf(mean_interp));\n            return mean_interp;\n        }\n        else if (est_scv < est_scvs.front())\n        {\n            //fprintf(stderr, \"Warning: extrapolating to the left\\n\");\n            \n            // If we're extrapolating to the left, our fit is too coarse, but\n            // that probably means we don't need SCV bias correction at all.\n            return est_scv;\n        }\n        \n        vector<double>::const_iterator lb;\n        lb = lower_bound(est_scvs.begin(), \n                         est_scvs.end(), \n                         est_scv);\n        if (lb < est_scvs.end())\n        {\n            int d = lb - est_scvs.begin();\n            if (*lb == est_scv || lb == est_scvs.begin())\n            {\n                double var = true_scvs[d];\n//                if (var < est_scv) // revert to poisson if underdispersed\n//                    var = est_scv;\n                assert (!isnan(var) && !isinf(var));\n                return var;\n            }\n            \n            \n            //in between two points on the scale.\n            d--;\n            \n            if (d < 0)\n            {\n                fprintf(stderr, \"ARG d < 0, d = %d \\n\", d);\n            }\n            \n            if (d >= est_scvs.size())\n            {\n                fprintf(stderr, \"ARG d >= est_scvs.size(), d = %d\\n\", d);\n            }\n            if (d >= true_scvs.size())\n            {\n                fprintf(stderr, \"ARG d >= true_scvs.size(), d = %d\\n\", d);\n            }\n            \n            double x1_mean = est_scvs[d];\n            double x2_mean = est_scvs[d + 1];\n            \n            double y1_var = true_scvs[d];\n            double y2_var = true_scvs[d + 1];\n            double slope = 0.0;                \n            if (x2_mean != x1_mean)\n            {\n                slope = (y2_var - y1_var) / (x2_mean-x1_mean);\n            }\n            else if (y1_var == y2_var)\n            {\n                fprintf(stderr, \"Warning: SCV table does not have unique keys\\n!\");\n                assert (false); // should have a unique'd table\n            }\n            double mean_interp = true_scvs[d] + slope*(est_scv - est_scvs[d]);\n//            if (mean_interp < est_scv) // revert to poisson if underdispersed\n//                mean_interp = est_scv;\n            \n            assert (!isnan(mean_interp) && !isinf(mean_interp));\n            return mean_interp;\n        }\n        else\n        {\n            assert (!isnan(est_scv) && !isinf(est_scv));\n            return est_scv; // revert to poisson assumption\n        }\n        \n        return est_scv;\n    }\n    \nprivate:\n    vector<double> true_scvs;\n    vector<double> est_scvs;\n};\n\nvoid build_scv_correction_fit(int nreps, int ngenes, int mean_count, SCVInterpolator& true_to_est_scv_table)\n{    \n    setuplf();  \n    \n    vector<pair<double, double> > alpha_vs_scv;\n   \n    boost::mt19937 rng;\n    vector<boost::random::negative_binomial_distribution<int, double> > nb_gens;\n    \n    vector<double> alpha_range;\n    for(double a = 0.0002; a < 2.0; a += 0.0002)\n    {\n        alpha_range.push_back(a);\n    }\n    \n    for (double a = 2; a < 100.0; a += 1)\n    {\n        alpha_range.push_back(a);\n    }\n    \n    BOOST_FOREACH (double alpha, alpha_range)\n    {\n        double k = 1.0/alpha;\n        double p = k / (k + mean_count);\n        double r = (mean_count * p) / (1-p);\n\n        //boost::random::negative_binomial_distribution<int, double> nb(r, p);\n        \n        boost::random::gamma_distribution<double> gamma(r, (1-p)/p);\n        \n        \n        vector<double> scvs_for_alpha;\n        vector<double> draws;\n        for (size_t i = 0; i < ngenes; ++i)\n        {\n            LocusCountList locus_count(\"\", nreps, 1, vector<string>(), vector<string>());\n            for (size_t rep_idx = 0; rep_idx < nreps; ++rep_idx)\n            {\n                double gamma_draw = gamma(rng);\n                if (gamma_draw == 0)\n                {\n                    locus_count.counts[rep_idx] = 0;\n                    draws.push_back(0);\n                }\n                else\n                {\n                    boost::random::poisson_distribution<long, double> poisson(gamma_draw);\n                    locus_count.counts[rep_idx] = poisson(rng);\n                    draws.push_back(locus_count.counts[rep_idx]);\n                    //fprintf(stderr, \"%lg\\t\", locus_count.counts[rep_idx]);\n                }\n            }\n            \n            double mean = accumulate(locus_count.counts.begin(), locus_count.counts.end(), 0.0);\n            if (mean == 0)\n                continue;\n            mean /= locus_count.counts.size();\n            double var = 0.0;\n            BOOST_FOREACH(double c,  locus_count.counts)\n            {\n                var += (c-mean)*(c-mean);\n            }\n            var /= locus_count.counts.size();\n            var *= locus_count.counts.size() / (locus_count.counts.size() - 1);\n            \n            double scv = var / (mean*mean);\n            scvs_for_alpha.push_back(scv);\n            //fprintf(stderr, \" : mean = %lg, var = %lg, scv = %lg\\n\", mean, var, scv);\n            \n            //fprintf(stderr, \"\\n\");\n        }\n        \n        double mean = accumulate(draws.begin(), draws.end(), 0.0);\n        mean /= draws.size();\n        double var = 0.0;\n        BOOST_FOREACH(int c,  draws)\n        {\n            var += (c - mean)*(c-mean);\n        }\n        var /= draws.size();\n        var *= draws.size() / (draws.size() - 1);\n        \n       \n        \n        //fprintf(stderr, \"##########\\n\");\n        //fprintf(stderr, \"mean = %lf, var = %lg\\n\", mean, var);\n        if (scvs_for_alpha.size() > 0)\n        {\n            double mean_scv = accumulate(scvs_for_alpha.begin(),scvs_for_alpha.end(), 0.0);\n            mean_scv /= scvs_for_alpha.size();\n            //fprintf(stderr, \"alpha = %lg scv = %lg\\n\", alpha, mean_scv);\n            alpha_vs_scv.push_back(make_pair(alpha, mean_scv));\n        }\n    }\n    \n    //fprintf(stderr, \"$$$$$$$$$\\n\");\n    \n    //sort (alpha_range.begin(), alpha_range.end());\n    \n    char namebuf[256];\n    sprintf(namebuf, \"trueSCV\");\n    vari* cm = createvar(namebuf,STREGULAR,alpha_vs_scv.size(),VDOUBLE);\n    for (size_t i = 0; i < alpha_vs_scv.size(); ++i)\n    {\n        cm->dpr[i] = alpha_vs_scv[i].first;\n    }\n    \n    sprintf(namebuf, \"estSCV\");\n    vari* cv = createvar(namebuf,STREGULAR,alpha_vs_scv.size(),VDOUBLE);\n    for (size_t i = 0; i < alpha_vs_scv.size(); ++i)\n    {\n        cv->dpr[i] = alpha_vs_scv[i].second;\n    }\n    \n    char locfit_cmd[2048];\n    sprintf(locfit_cmd, \"locfit trueSCV~estSCV\");\n    \n    locfit_dispatch(locfit_cmd);\n    \n    sprintf(namebuf, \"domainSCV\");\n    vari* cd = createvar(namebuf,STREGULAR,alpha_vs_scv.size(),VDOUBLE);\n    for (size_t i = 0; i < alpha_vs_scv.size(); ++i)\n    {\n        cd->dpr[i] = alpha_vs_scv[i].second;\n    }\n    \n    sprintf(locfit_cmd, \"fittedSCV=predict domainSCV\");\n    locfit_dispatch(locfit_cmd);\n    \n    int n = 0;\n    sprintf(namebuf, \"fittedSCV\");\n    vari* cp = findvar(namebuf, 1, &n);\n    assert(cp != NULL);\n    \n    for (size_t i = 0; i < cp->n; ++i)\n    {\n        //fprintf(stderr, \"%lg\\t%lg\\n\",alpha_range[i], cp->dpr[i]);\n        true_to_est_scv_table.add_scv_pair(alpha_range[i], cp->dpr[i]);\n    }\n    true_to_est_scv_table.finalize();\n}\n\nvoid calculate_count_means_and_vars(const vector<LocusCountList>& sample_compatible_count_table,\n                                    vector<pair<double, double> >& means_and_vars)\n{\n    \n    for (size_t i = 0; i < sample_compatible_count_table.size(); ++i)\n    {\n        const LocusCountList& p = sample_compatible_count_table[i];\n        double mean = accumulate(p.counts.begin(), p.counts.end(), 0.0);\n        if (mean > 0.0 && p.counts.size() > 0)\n            mean /= p.counts.size();\n        \n        double var = 0.0;\n        double num_non_zero = 0;\n        BOOST_FOREACH (double d, p.counts)\n        {\n            if (d > 0)\n                num_non_zero++;\n            var += (d - mean) * (d - mean);\n        }\n        if (var > 0.0 && p.counts.size())\n        {\n            var /= p.counts.size();\n            var *= p.counts.size() / (p.counts.size() - 1);\n        }\n        means_and_vars.push_back(make_pair(mean, var));\n    }\n}\n                              \nboost::shared_ptr<MassDispersionModel>\nfit_dispersion_model_helper(const string& condition_name,\n                            const vector<double>& scale_factors,\n                            const vector<LocusCountList>& sample_compatible_count_table)\n{\n    vector<pair<double, double> > compatible_means_and_vars;\n    \n    SCVInterpolator true_to_est_scv_table;\n    \n    int num_samples = sample_compatible_count_table.front().counts.size();\n    if (no_scv_correction == false)\n    {\n        build_scv_correction_fit(num_samples, 10000, 100000, true_to_est_scv_table);\n    }\n    \n    setuplf();  \n    \n    calculate_count_means_and_vars(sample_compatible_count_table, compatible_means_and_vars);\n\n    sort(compatible_means_and_vars.begin(), compatible_means_and_vars.end());\n    \n    vector<double> compatible_count_means;\n    vector<double> raw_variances;\n    \n    for(size_t i = 0; i < compatible_means_and_vars.size(); ++i)\n    {\n        if (compatible_means_and_vars[i].first > 0 && compatible_means_and_vars[i].second > 0.0)\n        {\n            compatible_count_means.push_back(compatible_means_and_vars[i].first);\n            raw_variances.push_back(compatible_means_and_vars[i].second);\n        }\n    }\n    \n    if (compatible_count_means.size() < min_loci_for_fitting)\n    {\n        boost::shared_ptr<MassDispersionModel> disperser;\n        disperser = boost::shared_ptr<MassDispersionModel>(new PoissonDispersionModel(condition_name));\n        \n        return disperser;\n    }\n    \n    \n    vector<double> fitted_values;\n    \n    // WARNING: locfit doesn't like undescores - need camel case for \n    // variable names\n    \n    char namebuf[256];\n    sprintf(namebuf, \"countMeans\");\n    vari* cm = createvar(namebuf,STREGULAR,compatible_count_means.size(),VDOUBLE);\n    for (size_t i = 0; i < compatible_count_means.size(); ++i)\n    {\n        cm->dpr[i] = log(compatible_count_means[i]);\n    }\n    \n    //sprintf(namebuf, \"countSCV\");\n    sprintf(namebuf, \"countVariances\");\n    vari* cv = createvar(namebuf,STREGULAR,raw_variances.size(),VDOUBLE);\n    for (size_t i = 0; i < raw_variances.size(); ++i)\n    {\n        cv->dpr[i] = raw_variances[i]; \n        //cv->dpr[i] = raw_scvs[i];\n    }\n    \n    char locfit_cmd[2048];\n    //sprintf(locfit_cmd, \"locfit countVariances~countMeans family=gamma\");\n    sprintf(locfit_cmd, \"locfit countVariances~countMeans family=gamma\");\n    \n    locfit_dispatch(locfit_cmd);\n    \n    sprintf(locfit_cmd, \"fittedVars=predict countMeans\");\n    locfit_dispatch(locfit_cmd);\n    \n    //sprintf(locfit_cmd, \"prfit x fhat h nlx\");\n    //locfit_dispatch(locfit_cmd);\n    \n    double xim = 0;\n    BOOST_FOREACH(double s, scale_factors)\n    {\n        if (s)\n            xim += 1.0 / s;\n    }\n    xim /= scale_factors.size();\n    \n    int n = 0;\n    sprintf(namebuf, \"fittedVars\");\n    vari* cp = findvar(namebuf, 1, &n);\n    assert(cp != NULL);\n    for (size_t i = 0; i < cp->n; ++i)\n    {\n//        if (cp->dpr[i] >= 0)\n//        {\n            double mean = exp(cm->dpr[i]);\n            double fitted_scv = (cp->dpr[i] - mean) / (mean * mean);\n            double corrected_scv = true_to_est_scv_table.interpolate_scv(fitted_scv);\n            double corrected_variance = mean + (corrected_scv * (mean * mean));\n            double uncorrected_variance = mean + (fitted_scv * (mean * mean));\n            //fitted_values.push_back(mean + (cp->dpr[i] - xim * mean));\n            if (no_scv_correction == false && corrected_variance > uncorrected_variance)\n                fitted_values.push_back(corrected_variance);\n            else if (uncorrected_variance > 0)\n                fitted_values.push_back(uncorrected_variance);\n            else\n                fitted_values.push_back(compatible_count_means[i]);\n        \n            \n//        }\n//        else\n//        {\n//            fitted_values.push_back(compatible_count_means[i]);\n//        }\n    }\n    \n    boost::shared_ptr<MassDispersionModel> disperser;\n    disperser = boost::shared_ptr<MassDispersionModel>(new MassDispersionModel(condition_name, compatible_count_means, raw_variances, fitted_values));\n    if (dispersion_method == POISSON)\n        disperser = boost::shared_ptr<MassDispersionModel>(new PoissonDispersionModel(condition_name));\n    \n//    for (map<string, pair<double, double> >::iterator itr = labeled_mv_table.begin();\n//         itr != labeled_mv_table.end();\n//         ++itr)\n//    {\n//        string label = itr->first;\n//        disperser->set_compatible_mean_and_var(itr->first, itr->second);\n//    }\n    \n    return disperser;\n}\n\nboost::shared_ptr<MassDispersionModel>\nfit_dispersion_model(const string& condition_name,\n                     const vector<double>& scale_factors,\n                     const vector<LocusCountList>& sample_compatible_count_table)\n{\n//    \n//#if ENABLE_THREADS\n//\tboost::mutex::scoped_lock lock(_locfit_lock);\n//#endif\n    for (size_t i = 0; i < sample_compatible_count_table.size(); ++i)\n    {\n        if (sample_compatible_count_table[i].counts.size() <= 1)\n        {\n            // only one replicate - no point in fitting variance\n            return boost::shared_ptr<MassDispersionModel>(new PoissonDispersionModel(condition_name));\n        }\n    }\n#if ENABLE_THREADS\n    _locfit_lock.lock();\n#endif\n    \n    ProgressBar p_bar(\"Modeling fragment count overdispersion.\",0);\n    \n    int max_transcripts = 0;\n    BOOST_FOREACH(const LocusCountList& L, sample_compatible_count_table)\n    {\n        if (L.num_transcripts > max_transcripts)\n        {\n            max_transcripts = L.num_transcripts;\n        }\n    }\n    \n    boost::shared_ptr<MassDispersionModel>  model = fit_dispersion_model_helper(condition_name, scale_factors, sample_compatible_count_table);\n\n#if ENABLE_THREADS\n    _locfit_lock.unlock();\n#endif\n    return model;\n}\n\nvoid build_norm_table(const vector<LocusCountList>& full_count_table,\n                      boost::shared_ptr<const map<string, LibNormStandards> > normalizing_standards,\n                      vector<LocusCountList>& norm_table)\n{\n    // If we're using housekeeping genes or spike-in controls, select the rows we'll be using from the full count table.\n    if (normalizing_standards)\n    {\n        for (size_t i = 0; i < full_count_table.size(); ++i)\n        {\n            const vector<string>& gene_ids = full_count_table[i].gene_ids;\n            const vector<string>& gene_short_names = full_count_table[i].gene_short_names;\n            \n            // If the row has an ID that's in the table, take it.\n            map<string, LibNormStandards>::const_iterator g_id_itr = normalizing_standards->end();\n            map<string, LibNormStandards>::const_iterator g_name_itr = normalizing_standards->end();\n            \n            for (size_t j = 0; j < gene_ids.size(); ++j)\n            {\n                g_id_itr = normalizing_standards->find(gene_ids[j]);\n                if (g_id_itr != normalizing_standards->end())\n                {\n                    break;\n                }\n            }\n            \n            if (g_id_itr != normalizing_standards->end())\n            {\n                norm_table.push_back(full_count_table[i]);\n                continue;\n            }\n\n            for (size_t j = 0; j < gene_short_names.size(); ++j)\n            {\n                g_name_itr = normalizing_standards->find(gene_short_names[j]);\n                if (g_name_itr != normalizing_standards->end())\n                {\n                    break;\n                }\n            }\n            \n            if (g_name_itr != normalizing_standards->end())\n            {\n                norm_table.push_back(full_count_table[i]);\n                continue;\n            }\n\n        }\n    }\n    else // otherwise, just take all rows.\n    {\n        norm_table = full_count_table;\n    }\n}\n\nvoid normalize_counts(vector<boost::shared_ptr<ReadGroupProperties> > & all_read_groups)\n{\n    vector<LocusCountList> sample_compatible_count_table;\n    vector<LocusCountList> sample_total_count_table;\n    \n    for (size_t i = 0; i < all_read_groups.size(); ++i)\n    {\n        boost::shared_ptr<ReadGroupProperties> rg_props = all_read_groups[i];\n        const vector<LocusCount>& raw_compatible_counts = rg_props->raw_compatible_counts();\n        const vector<LocusCount>& raw_total_counts = rg_props->raw_total_counts();\n        \n        for (size_t j = 0; j < raw_compatible_counts.size(); ++j)\n        {\n            if (sample_compatible_count_table.size() == j)\n            {\n                const string& locus_id = raw_compatible_counts[j].locus_desc;\n                int num_transcripts = raw_compatible_counts[j].num_transcripts;\n                \n                const vector<string>& gene_ids = raw_compatible_counts[j].gene_ids;\n                const vector<string>& gene_short_names = raw_compatible_counts[j].gene_short_names;\n                \n                sample_compatible_count_table.push_back(LocusCountList(locus_id,all_read_groups.size(), num_transcripts, gene_ids, gene_short_names));\n                sample_total_count_table.push_back(LocusCountList(locus_id,all_read_groups.size(), num_transcripts, gene_ids, gene_short_names));\n            }\n            double scaled = raw_compatible_counts[j].count;\n            //sample_compatible_count_table[j].counts[i] = scaled * unscaling_factor;\n            sample_compatible_count_table[j].counts[i] = floor(scaled);\n            sample_total_count_table[j].counts[i] = floor(raw_total_counts[j].count);\n            \n            assert(sample_compatible_count_table[j].counts[i] >= 0 && !isinf(sample_compatible_count_table[j].counts[i]));\n        }\n    }\n    \n    vector<double> scale_factors(all_read_groups.size(), 0.0);\n    \n    vector<LocusCountList> norm_table;\n    \n    if (use_compat_mass)\n    {\n        build_norm_table(sample_compatible_count_table, lib_norm_standards, norm_table);\n    }\n    else // use_total_mass\n    {\n        assert(use_total_mass);\n        build_norm_table(sample_total_count_table, lib_norm_standards, norm_table);\n    }\n    \n    if (lib_norm_method == GEOMETRIC)\n    {\n        calc_geometric_scaling_factors(norm_table, scale_factors);\n    }\n    else if (lib_norm_method == CLASSIC_FPKM)\n    {\n        calc_classic_fpkm_scaling_factors(norm_table, scale_factors);\n    }\n    else if (lib_norm_method == QUARTILE)\n    {\n        calc_quartile_scaling_factors(norm_table, scale_factors);\n    }\n    else if (lib_norm_method == TMM)\n    {\n        calc_tmm_scaling_factors(norm_table, scale_factors);\n    }\n    else if (lib_norm_method == ESTIMATED_ABSOLUTE)\n    {\n        calc_estimated_absolute_scaling_factors(all_read_groups, scale_factors);\n    }\n    else\n    {\n        assert (false);\n    }\n    \n    \n    \n    for (size_t i = 0; i < all_read_groups.size(); ++i)\n    {\n        boost::shared_ptr<ReadGroupProperties> rg_props = all_read_groups[i];\n        rg_props->internal_scale_factor(scale_factors[i]);\n    }\n    \n    assert(sample_compatible_count_table.size() == sample_total_count_table.size());\n    \n    // Transform raw counts to the common scale\n    for (size_t i = 0; i < sample_compatible_count_table.size(); ++i)\n    {\n        LocusCountList& p = sample_compatible_count_table[i];\n        for (size_t j = 0; j < p.counts.size(); ++j)\n        {\n            assert (scale_factors.size() > j);\n            p.counts[j] *= (1.0 / scale_factors[j]);\n        }\n        \n        LocusCountList& t = sample_total_count_table[i];\n        for (size_t j = 0; j < t.counts.size(); ++j)\n        {\n            assert (scale_factors.size() > j);\n            t.counts[j] *= (1.0 / scale_factors[j]);\n        }\n    }\n    \n    for (size_t i = 0; i < all_read_groups.size(); ++i)\n    {\n        boost::shared_ptr<ReadGroupProperties> rg_props = all_read_groups[i];\n        vector<LocusCount> scaled_compatible_counts;\n        for (size_t j = 0; j < sample_compatible_count_table.size(); ++j)\n        {\n            string& locus_id = sample_compatible_count_table[j].locus_desc;\n            double count = sample_compatible_count_table[j].counts[i];\n            int num_transcripts = sample_compatible_count_table[j].num_transcripts;\n            \n            const vector<string>& gids = sample_compatible_count_table[j].gene_ids;\n            const vector<string>& gnms = sample_compatible_count_table[j].gene_short_names;\n            \n            LocusCount locus_count(locus_id, count, num_transcripts, gids, gnms);\n            scaled_compatible_counts.push_back(locus_count);\n        }\n        rg_props->common_scale_compatible_counts(scaled_compatible_counts);\n    }\n    \n    for (size_t i = 0; i < all_read_groups.size(); ++i)\n    {\n        boost::shared_ptr<ReadGroupProperties> rg_props = all_read_groups[i];\n        vector<LocusCount> scaled_total_counts;\n        for (size_t j = 0; j < sample_total_count_table.size(); ++j)\n        {\n            string& locus_id = sample_total_count_table[j].locus_desc;\n            double count = sample_total_count_table[j].counts[i];\n            int num_transcripts = sample_total_count_table[j].num_transcripts;\n            \n            const vector<string>& gids = sample_total_count_table[j].gene_ids;\n            const vector<string>& gnms = sample_total_count_table[j].gene_short_names;\n            \n            LocusCount locus_count(locus_id, count, num_transcripts, gids, gnms);\n            scaled_total_counts.push_back(locus_count);\n        }\n        rg_props->common_scale_total_counts(scaled_total_counts);\n    }\n    \n    double avg_total_common_scaled_count = 0.0;\n    \n    for (size_t fac_idx = 0; fac_idx < all_read_groups.size(); ++fac_idx)\n    {\n        double total_common = 0.0;\n        if (use_compat_mass)\n        {\n            for (size_t j = 0; j < sample_compatible_count_table.size(); ++j)\n            {\n                total_common += sample_compatible_count_table[j].counts[fac_idx];\n            }\n        }\n        else\n        {\n            for (size_t j = 0; j < sample_compatible_count_table.size(); ++j)\n            {\n                total_common += sample_total_count_table[j].counts[fac_idx];\n            }\n\n        }\n        \n        avg_total_common_scaled_count += (1.0/all_read_groups.size()) * total_common;\n    }\n    \n    BOOST_FOREACH(boost::shared_ptr<ReadGroupProperties> rg, all_read_groups)\n    {\n        rg->normalized_map_mass(avg_total_common_scaled_count);\n    }\n}\n\n", "meta": {"hexsha": "a370a8019956e1ad8664101c3a2d5d8184c49138", "size": 41633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/replicates.cpp", "max_stars_repo_name": "idiv-biodiversity/cufflinks", "max_stars_repo_head_hexsha": "e17bfcb3190b12ade76a5e326234dc490444bf42", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-09-08T04:23:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-12T15:00:33.000Z", "max_issues_repo_path": "src/replicates.cpp", "max_issues_repo_name": "idiv-biodiversity/cufflinks", "max_issues_repo_head_hexsha": "e17bfcb3190b12ade76a5e326234dc490444bf42", "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/replicates.cpp", "max_forks_repo_name": "idiv-biodiversity/cufflinks", "max_forks_repo_head_hexsha": "e17bfcb3190b12ade76a5e326234dc490444bf42", "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.7231025855, "max_line_length": 150, "alphanum_fraction": 0.5705089712, "num_tokens": 10032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.17291730498373267}}
{"text": "#ifndef __abstract_MSSMNoFV_onshell_physical_gm2calc_1_3_0_hpp__\n#define __abstract_MSSMNoFV_onshell_physical_gm2calc_1_3_0_hpp__\n\n#include <cstddef>\n#include <iostream>\n#include <ostream>\n#include <Eigen/Core>\n#include \"gambit/Backends/abstractbase.hpp\"\n#include \"forward_decls_abstract_classes.hpp\"\n#include \"forward_decls_wrapper_classes.hpp\"\n\n#include \"identification.hpp\"\n\nnamespace CAT_3(BACKENDNAME,_,SAFE_VERSION)\n{\n   \n   \n   namespace gm2calc\n   {\n      class Abstract_MSSMNoFV_onshell_physical : public virtual AbstractBase\n      {\n         public:\n   \n            virtual void clear() =0;\n   \n            virtual void convert_to_hk() =0;\n   \n            virtual void convert_to_slha() =0;\n   \n            virtual void print(::std::basic_ostream<char, std::char_traits<char> >&) const =0;\n   \n            virtual double& MVG_ref__BOSS() =0;\n   \n            virtual double& MGlu_ref__BOSS() =0;\n   \n            virtual double& MVP_ref__BOSS() =0;\n   \n            virtual double& MVZ_ref__BOSS() =0;\n   \n            virtual double& MFd_ref__BOSS() =0;\n   \n            virtual double& MFs_ref__BOSS() =0;\n   \n            virtual double& MFb_ref__BOSS() =0;\n   \n            virtual double& MFu_ref__BOSS() =0;\n   \n            virtual double& MFc_ref__BOSS() =0;\n   \n            virtual double& MFt_ref__BOSS() =0;\n   \n            virtual double& MFve_ref__BOSS() =0;\n   \n            virtual double& MFvm_ref__BOSS() =0;\n   \n            virtual double& MFvt_ref__BOSS() =0;\n   \n            virtual double& MFe_ref__BOSS() =0;\n   \n            virtual double& MFm_ref__BOSS() =0;\n   \n            virtual double& MFtau_ref__BOSS() =0;\n   \n            virtual double& MSveL_ref__BOSS() =0;\n   \n            virtual double& MSvmL_ref__BOSS() =0;\n   \n            virtual double& MSvtL_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSd_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSu_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSe_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSm_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MStau_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSs_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSc_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSb_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSt_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& Mhh_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MAh_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MHpm_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 4, 1, 0, 4, 1>& MChi_ref__BOSS() =0;\n   \n            virtual ::Eigen::Array<double, 2, 1, 0, 2, 1>& MCha_ref__BOSS() =0;\n   \n            virtual double& MVWm_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZD_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZU_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZE_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZM_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZTau_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZS_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZC_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZB_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZT_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZH_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZA_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZP_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<std::complex<double>, 4, 4, 0, 4, 4>& ZN_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<std::complex<double>, 2, 2, 0, 2, 2>& UM_ref__BOSS() =0;\n   \n            virtual ::Eigen::Matrix<std::complex<double>, 2, 2, 0, 2, 2>& UP_ref__BOSS() =0;\n   \n         public:\n            virtual void pointer_assign__BOSS(Abstract_MSSMNoFV_onshell_physical*) =0;\n            virtual Abstract_MSSMNoFV_onshell_physical* pointer_copy__BOSS() =0;\n   \n         private:\n            MSSMNoFV_onshell_physical* wptr;\n            bool delete_wrapper;\n         public:\n            MSSMNoFV_onshell_physical* get_wptr() { return wptr; }\n            void set_wptr(MSSMNoFV_onshell_physical* wptr_in) { wptr = wptr_in; }\n            bool get_delete_wrapper() { return delete_wrapper; }\n            void set_delete_wrapper(bool del_wrp_in) { delete_wrapper = del_wrp_in; }\n   \n         public:\n            Abstract_MSSMNoFV_onshell_physical()\n            {\n               wptr = 0;\n               delete_wrapper = false;\n            }\n   \n            Abstract_MSSMNoFV_onshell_physical(const Abstract_MSSMNoFV_onshell_physical&)\n            {\n               wptr = 0;\n               delete_wrapper = false;\n            }\n   \n            Abstract_MSSMNoFV_onshell_physical& operator=(const Abstract_MSSMNoFV_onshell_physical&) { return *this; }\n   \n            virtual void init_wrapper() =0;\n   \n            MSSMNoFV_onshell_physical* get_init_wptr()\n            {\n               init_wrapper();\n               return wptr;\n            }\n   \n            MSSMNoFV_onshell_physical& get_init_wref()\n            {\n               init_wrapper();\n               return *wptr;\n            }\n   \n            virtual ~Abstract_MSSMNoFV_onshell_physical() =0;\n      };\n   }\n   \n}\n\n\n#include \"gambit/Backends/backend_undefs.hpp\"\n\n\n#endif /* __abstract_MSSMNoFV_onshell_physical_gm2calc_1_3_0_hpp__ */\n", "meta": {"hexsha": "610c0a10fa3e1c9b30396aba1509ebf4f749c84d", "size": 5933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/abstract_MSSMNoFV_onshell_physical.hpp", "max_stars_repo_name": "GambitBSM/gambit_2.0", "max_stars_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T22:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T22:53:26.000Z", "max_issues_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/abstract_MSSMNoFV_onshell_physical.hpp", "max_issues_repo_name": "GambitBSM/gambit_2.0", "max_issues_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T11:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T17:24:41.000Z", "max_forks_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/abstract_MSSMNoFV_onshell_physical.hpp", "max_forks_repo_name": "GambitBSM/gambit_2.0", "max_forks_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:31:41.000Z", "avg_line_length": 32.4207650273, "max_line_length": 118, "alphanum_fraction": 0.5582336086, "num_tokens": 1898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.17278946251645871}}
{"text": "#include <numeric>\n#include <boost/algorithm/string.hpp>\n#include <regex>\n\n#include \"PositionStringParser.hpp\"\n#include \"Board.hpp\"\n\nBoard PositionStringParser::ParsePositionString(const std::string& positionString)\n{\n\tSetPosition(positionString);\n\n\treturn Board(\n\t\ttoMove,\n\t\tcastlingRights,\n\t\tremainingPlayers,\n\t\thalfMoveClock,\n\t\tfullMoveNumber,\n\t\trPawns,\n\t\trKnights,\n\t\trBishops,\n\t\trRooks,\n\t\trQueens,\n\t\trKing,\n\t\tbPawns,\n\t\tbKnights,\n\t\tbBishops,\n\t\tbRooks,\n\t\tbQueens,\n\t\tbKing,\n\t\tyPawns,\n\t\tyKnights,\n\t\tyBishops,\n\t\tyRooks,\n\t\tyQueens,\n\t\tyKing,\n\t\tgPawns,\n\t\tgKnights,\n\t\tgBishops,\n\t\tgRooks,\n\t\tgQueens,\n\t\tgKing);\n}\n\nstd::string PositionStringParser::GetPositionString(const Board& board) const\n{\n\treturn std::string();\n}\n\nvoid PositionStringParser::SetPosition(const std::string& positionString)\n{\n\tif (positionString.empty())\n\t{\n\t\tthrow;\n\t}\n\n\tstd::vector<std::string> slashTokens;\n\n\tboost::split(slashTokens, positionString, [](char c) {return c == '/'; });\n\n\tif (slashTokens.size() != SLASH_DELIMITED_TOKENS)\n\t{\n\t\tthrow;\n\t}\n\n\tstd::vector<std::string> emptySpaceTokens;\n\n\tboost::split(emptySpaceTokens, slashTokens.back(), [](char c) {return c == ' '; });\n\n\tif (emptySpaceTokens.size() != LAST_TOKEN_TOKENS)\n\t{\n\t\tthrow;\n\t}\n\n\tslashTokens.pop_back();\n\n\tstd::vector<std::string> positionTokens(slashTokens);\n\n\tpositionTokens.push_back(emptySpaceTokens.front());\n\n\tstd::regex regex(\"(\\\\d+)|(rP)|(rN)|(rB)|(rR)|(rQ)|(rq)|(rK)|(bP)|(bN)|(bB)|(bR)|(bQ)|(bq)|(bK)|(yP)|(yN)|(yB)|(yR)|(yQ)|(yq)|(yK)|(gP)|(gN)|(gB)|(gR)|(gQ)|(gq)|(gK)\");\n\n\tint position = Board::TOTAL_SQUARES;\n\n\tfor (auto& token : positionTokens)\n\t{\n\t\tstd::vector<int> squares;\n\t\tstd::vector<std::string> pieces;\n\t\tstd::smatch match;\n\t\tstd::string matchable(token);\n\n\t\twhile (std::regex_search(matchable, match, regex))\n\t\t{\n\t\t\tstd::string matchString = match[0].str();\n\t\t\tbool isNumber =\n\t\t\t\t!matchString.empty() &&\n\t\t\t\tstd::find_if(\n\t\t\t\t\tmatchString.cbegin(),\n\t\t\t\t\tmatchString.cend(),\n\t\t\t\t\t[](char c) { return !std::isdigit(c); }) == matchString.cend();\n\n\t\t\tif (isNumber)\n\t\t\t{\n\t\t\t\tint number = std::stoi(match[0]);\n\t\t\t\tposition -= number;\n\n\t\t\t\tif (number <= 0 || number > Board::TOTAL_SQUARES)\n\t\t\t\t{\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\n\t\t\t\tsquares.push_back(number);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tposition--;\n\n\t\t\t\tSetSquare(matchString, position);\n\n\t\t\t\tpieces.push_back(matchString);\n\t\t\t}\n\n\t\t\tmatchable = match.suffix();\n\t\t}\n\n\t\tint totalOccupancy = std::accumulate(squares.cbegin(), squares.cend(), 0) + pieces.size();\n\n\t\tif (totalOccupancy != Board::SQUARES_PER_SIDE)\n\t\t{\n\t\t\tthrow;\n\t\t}\n\t}\n\n\temptySpaceTokens.erase(emptySpaceTokens.begin());\n\n\tSetToMove(emptySpaceTokens.at(0));\n\n\tSetCastlingRights(emptySpaceTokens.at(1));\n\n\tSetRemainingPlayers(emptySpaceTokens.at(2));\n\n\tSetHalfMoveClock(emptySpaceTokens.at(3));\n\n\tSetFullMoveNumber(emptySpaceTokens.at(4));\n}\n\nvoid PositionStringParser::SetSquare(const std::string& matchString, int position)\n{\n\tauto mask = (I256{ 1 } << position);\n\n\tif (matchString == RED_PAWN)\n\t{\n\t\trPawns |= mask;\n\t}\n\telse if (matchString == RED_KNIGHT)\n\t{\n\t\trKnights |= mask;\n\t}\n\telse if (matchString == RED_BISHOP)\n\t{\n\t\trBishops |= mask;\n\t}\n\telse if (matchString == RED_ROOK)\n\t{\n\t\trRooks |= mask;\n\t}\n\telse if (matchString == RED_QUEEN || matchString == RED_NEW_QUEEN)\n\t{\n\t\trQueens |= mask;\n\t}\n\telse if (matchString == RED_KING)\n\t{\n\t\trKing |= mask;\n\t}\n\telse if (matchString == BLUE_PAWN)\n\t{\n\t\tbPawns |= mask;\n\t}\n\telse if (matchString == BLUE_KNIGHT)\n\t{\n\t\tbKnights |= mask;\n\t}\n\telse if (matchString == BLUE_BISHOP)\n\t{\n\t\tbBishops |= mask;\n\t}\n\telse if (matchString == BLUE_ROOK)\n\t{\n\t\tbRooks |= mask;\n\t}\n\telse if (matchString == BLUE_QUEEN || matchString == BLUE_NEW_QUEEN)\n\t{\n\t\tbQueens |= mask;\n\t}\n\telse if (matchString == BLUE_KING)\n\t{\n\t\tbKing |= mask;\n\t}\n\telse if (matchString == YELLOW_PAWN)\n\t{\n\t\tyPawns |= mask;\n\t}\n\telse if (matchString == YELLOW_KNIGHT)\n\t{\n\t\tyKnights |= mask;\n\t}\n\telse if (matchString == YELLOW_BISHOP)\n\t{\n\t\tyBishops |= mask;\n\t}\n\telse if (matchString == YELLOW_ROOK)\n\t{\n\t\tyRooks |= mask;\n\t}\n\telse if (matchString == YELLOW_QUEEN || matchString == YELLOW_NEW_QUEEN)\n\t{\n\t\tyQueens |= mask;\n\t}\n\telse if (matchString == YELLOW_KING)\n\t{\n\t\tyKing |= mask;\n\t}\n\telse if (matchString == GREEN_PAWN)\n\t{\n\t\tgPawns |= mask;\n\t}\n\telse if (matchString == GREEN_KNIGHT)\n\t{\n\t\tgKnights |= mask;\n\t}\n\telse if (matchString == GREEN_BISHOP)\n\t{\n\t\tgBishops |= mask;\n\t}\n\telse if (matchString == GREEN_ROOK)\n\t{\n\t\tgRooks |= mask;\n\t}\n\telse if (matchString == GREEN_QUEEN || matchString == GREEN_NEW_QUEEN)\n\t{\n\t\tgQueens |= mask;\n\t}\n\telse if (matchString == GREEN_KING)\n\t{\n\t\tgKing |= mask;\n\t}\n}\n\nvoid PositionStringParser::SetToMove(const std::string& toMoveString)\n{\n\tif (toMoveString == RED)\n\t{\n\t\ttoMove = PlayerColor::Red;\n\t}\n\telse if (toMoveString == BLUE)\n\t{\n\t\ttoMove = PlayerColor::Blue;\n\t}\n\telse if (toMoveString == YELLOW)\n\t{\n\t\ttoMove = PlayerColor::Yellow;\n\t}\n\telse if (toMoveString == GREEN)\n\t{\n\t\ttoMove = PlayerColor::Green;\n\t}\n\telse\n\t{\n\t\tthrow;\n\t}\n}\n\nvoid PositionStringParser::SetCastlingRights(const std::string& castleString)\n{\n\tif (castleString.find(RED_KING_CASTLE) != std::string::npos)\n\t{\n\t\tcastlingRights |= CastlingRight::RedKingSide;\n\t}\n\n\tif (castleString.find(RED_QUEEN_CASTLE) != std::string::npos)\n\t{\n\t\tcastlingRights |= CastlingRight::RedQueenSide;\n\t}\n\n\tif (castleString.find(BLUE_KING_CASTLE) != std::string::npos)\n\t{\n\t\tcastlingRights |= CastlingRight::BlueKingSide;\n\t}\n\n\tif (castleString.find(BLUE_QUEEN_CASTLE) != std::string::npos)\n\t{\n\t\tcastlingRights |= CastlingRight::BlueQueenSide;\n\t}\n\n\tif (castleString.find(YELLOW_KING_CASTLE) != std::string::npos)\n\t{\n\t\tcastlingRights |= CastlingRight::YellowKingSide;\n\t}\n\n\tif (castleString.find(YELLOW_QUEEN_CASTLE) != std::string::npos)\n\t{\n\t\tcastlingRights |= CastlingRight::YellowQueenSide;\n\t}\n\n\tif (castleString.find(GREEN_KING_CASTLE) != std::string::npos)\n\t{\n\t\tcastlingRights |= CastlingRight::GreenKingSide;\n\t}\n\n\tif (castleString.find(GREEN_QUEEN_CASTLE) != std::string::npos)\n\t{\n\t\tcastlingRights |= CastlingRight::GreenQueenSide;\n\t}\n}\n\nvoid PositionStringParser::SetRemainingPlayers(const std::string& remainingPlayersString)\n{\n\tsize_t maximumPlayers = 4;\n\n\tif (remainingPlayersString.size() > maximumPlayers)\n\t{\n\t\tthrow;\n\t}\n\n\tif (remainingPlayersString.find(RED) != std::string::npos) \n\t{\n\t\tremainingPlayers |= PlayerColor::Red;\n\t}\n\n\tif (remainingPlayersString.find(BLUE) != std::string::npos) \n\t{\n\t\tremainingPlayers |= PlayerColor::Blue;\n\t}\n\n\tif (remainingPlayersString.find(YELLOW) != std::string::npos) \n\t{\n\t\tremainingPlayers |= PlayerColor::Yellow;\n\t}\n\n\tif (remainingPlayersString.find(GREEN) != std::string::npos) \n\t{\n\t\tremainingPlayers |= PlayerColor::Green;\n\t}\n}\n\nvoid PositionStringParser::SetHalfMoveClock(const std::string& halfMoveClockString)\n{\n\thalfMoveClock = std::stoi(halfMoveClockString);\n}\n\nvoid PositionStringParser::SetFullMoveNumber(const std::string& fullMoveNumberString)\n{\n\tfullMoveNumber = std::stoi(fullMoveNumberString);\n}\n", "meta": {"hexsha": "6bfa0af8b0cf30705f337146ce2046269cd75c0d", "size": 6865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gti/PositionStringParser.cpp", "max_stars_repo_name": "YouJinTou/gti", "max_stars_repo_head_hexsha": "25d8d6f15ba7c12b32cff4a4a502340c31cdcd1d", "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": "gti/PositionStringParser.cpp", "max_issues_repo_name": "YouJinTou/gti", "max_issues_repo_head_hexsha": "25d8d6f15ba7c12b32cff4a4a502340c31cdcd1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gti/PositionStringParser.cpp", "max_forks_repo_name": "YouJinTou/gti", "max_forks_repo_head_hexsha": "25d8d6f15ba7c12b32cff4a4a502340c31cdcd1d", "max_forks_repo_licenses": ["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.3926553672, "max_line_length": 168, "alphanum_fraction": 0.6769118718, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3073580168652638, "lm_q1q2_score": 0.17278945444051216}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/list.hpp>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/math/mean_and_variance.h>\n#include <xfel/mono_simulation/parameters.h>\n#include <xfel/mono_simulation/bandpass_gaussian.h>\n#include <xfel/mono_simulation/vector_collection.h>\n\n\n#include <vector>\n#include <map>\n\nusing namespace boost::python;\nnamespace xfel{\nnamespace boost_python { namespace {\n\n  void\n  xfel_mono_sim_init_module() {\n    using namespace boost::python;\n\n    typedef return_value_policy<return_by_value> rbv;\n    typedef default_call_policies dcp;\n    class_<xfel::parameter::parameter_array>(\n      \"parameter_array\",no_init)\n      .add_property(\"x\",\n       make_getter(&xfel::parameter::parameter_array::parameters, rbv()))\n      .add_property(\"gradients\",\n       make_getter(&xfel::parameter::parameter_array::gradients,rbv()))\n      .add_property(\"curvatures\",\n       make_getter(&xfel::parameter::parameter_array::curvatures,rbv()))\n    ;\n    class_<xfel::parameter::organizer_base>(\n      \"organizer_base\",init<>())\n      .def(\"register\",&xfel::parameter::organizer_base::register_array,\n        (arg(\"tag\"),arg(\"ndata\"),arg(\"kdim\")=1,arg(\"data\")))\n      .def(\"register_local\",&xfel::parameter::organizer_base::register_local_array,\n        (arg(\"tag\"),arg(\"ndata\"),arg(\"kdim\")=1,arg(\"data\")))\n      .def(\"as_x_array\",&xfel::parameter::organizer_base::as_x_array)\n      .def(\"get_gradient_array\",\n           (xfel::farray(xfel::parameter::organizer_base::*)()const)\n           &xfel::parameter::organizer_base::get_gradient_array)\n      .def(\"set_gradient_array\",&xfel::parameter::organizer_base::set_gradient_array)\n      .def(\"get_curvature_array\",&xfel::parameter::organizer_base::get_curvature_array)\n      .def(\"from_x_array\",&xfel::parameter::organizer_base::from_x_array)\n      .def(\"initialize_gradients_curvatures\",\n         &xfel::parameter::organizer_base::initialize_gradients_curvatures)\n      .def(\"rezero_gradients_curvatures\",\n         &xfel::parameter::organizer_base::rezero_gradients_curvatures)\n    ;\n\n    class_<xfel::parameter::vector_array >(\n      \"vector_array\",init<>())\n      .add_property(\"gradients\",\n       make_getter(&xfel::parameter::vector_array::gradients,rbv()))\n    ;\n\n    class_<xfel::parameter::vector_collection >(\n      \"vector_collection\",init<>())\n      .def(init<xfel::iarray,xfel::marray>())\n      .def(\"collect_vector_information\",\n        &xfel::parameter::vector_collection::collect_vector_information)\n      .def(\"register\",\n        &xfel::parameter::vector_collection::register_tag,(arg_(\"tag\")))\n    ;\n\n    class_<xfel::parameter::streak_parameters >(\n      \"streak_parameters\",no_init)\n      .add_property(\"rotax\",make_getter(\n         &xfel::parameter::streak_parameters::rotax, rbv()))\n      .add_property(\"position\",make_getter(\n         &xfel::parameter::streak_parameters::position, rbv()))\n      .add_property(\"position_to_fictitious\",make_getter(\n         &xfel::parameter::streak_parameters::position_to_fictitious, rbv()))\n      .add_property(\"rotax_excursion_rad\",make_getter(\n         &xfel::parameter::streak_parameters::rotax_excursion_rad, rbv()))\n      .add_property(\"rotax_excursion_rad_pvr\",make_getter(\n         &xfel::parameter::streak_parameters::rotax_excursion_rad_pvr, rbv()))\n     ;\n\n    class_<xfel::parameter::bandpass_gaussian>(\"bandpass_gaussian\",\n      init<rstbx::bandpass::parameters_bp3 const&>(arg(\"parameters\")))\n      .def(\"set_active_areas\", &xfel::parameter::bandpass_gaussian::set_active_areas)\n      .def(\"set_sensor_model\", &xfel::parameter::bandpass_gaussian::set_sensor_model,(\n         arg(\"thickness_mm\"), arg(\"mu_rho\"), arg(\"signal_penetration\")))\n      .def(\"gaussian_fast_slow\",\n         &xfel::parameter::bandpass_gaussian::gaussian_fast_slow)\n      .add_property(\"hi_E_limit\",make_getter(\n         &xfel::parameter::bandpass_gaussian::hi_E_limit, rbv()))\n      .add_property(\"lo_E_limit\",make_getter(\n         &xfel::parameter::bandpass_gaussian::lo_E_limit, rbv()))\n      .add_property(\"mean_position\",make_getter(\n         &xfel::parameter::bandpass_gaussian::mean_position, rbv()))\n      .add_property(\"calc_radial_length\",make_getter(\n         &xfel::parameter::bandpass_gaussian::calc_radial_length, rbv()))\n      .add_property(\"part_distance\",make_getter(\n         &xfel::parameter::bandpass_gaussian::part_distance, rbv()))\n      .add_property(\"observed_flag\",make_getter(\n         &xfel::parameter::bandpass_gaussian::observed_flag, rbv()))\n      .def(\"set_subpixel\", &xfel::parameter::bandpass_gaussian::set_subpixel,(\n           arg(\"translations\"), arg(\"rotations_deg\")))\n      .def(\"set_mosaicity\", &xfel::parameter::bandpass_gaussian::set_mosaicity)\n      .def(\"set_domain_size\", &xfel::parameter::bandpass_gaussian::set_domain_size)\n      .def(\"set_bandpass\", &xfel::parameter::bandpass_gaussian::set_bandpass)\n      .def(\"set_orientation\", &xfel::parameter::bandpass_gaussian::set_orientation)\n      .def(\"set_detector_origin\",\n         &xfel::parameter::bandpass_gaussian::set_detector_origin)\n      .def(\"set_distance\", &xfel::parameter::bandpass_gaussian::set_distance)\n      .def(\"set_vector_output_pointers\",\n         &xfel::parameter::bandpass_gaussian::set_vector_output_pointers,\n         (arg_(\"vector_collection\"),arg_(\"frame_id\")))\n      .def(\"measure_bandpass_and_mosaic_parameters\", &\n      xfel::parameter::bandpass_gaussian::measure_bandpass_and_mosaic_parameters\n         ,(arg(\"radial\"), arg(\"azimut\"), arg(\"domain_sz_inv_ang\"),\n           arg(\"lab_frame_obs\")\n          ))\n      .add_property(\"wavelength_fit_ang\",make_getter(\n         &xfel::parameter::bandpass_gaussian::wavelength_fit_ang, rbv()))\n      .add_property(\"mosaicity_fit_rad\",make_getter(\n         &xfel::parameter::bandpass_gaussian::mosaicity_fit_rad, rbv()))\n      .add_property(\"wavelength_fit_ang_sigma\",make_getter(\n         &xfel::parameter::bandpass_gaussian::wavelength_fit_ang_sigma, rbv()))\n      .add_property(\"mosaicity_fit_rad_sigma\",make_getter(\n         &xfel::parameter::bandpass_gaussian::mosaicity_fit_rad_sigma, rbv()))\n      .def(\"simple_forward_calculation_spot_position\",\n           &xfel::parameter::bandpass_gaussian::simple_forward_calculation_spot_position,\n           (arg_(\"wavelength\"), arg_(\"observation_no\")))\n      .def(\"simple_part_excursion_part_rotxy\",\n           &xfel::parameter::bandpass_gaussian::simple_part_excursion_part_rotxy,\n           (arg_(\"wavelength\"), arg_(\"observation_no\"),\n            arg_(\"dA_drotxy\")))\n    ;\n\n    def(\"best_fit_limit\",xfel::parameter::best_fit_limit);\n  }\n\n}\n}} // namespace xfel::boost_python::<anonymous>\n\nBOOST_PYTHON_MODULE(xfel_mono_sim_ext)\n{\n  xfel::boost_python::xfel_mono_sim_init_module();\n\n}\n", "meta": {"hexsha": "141efc0094041ae79ab40c3c47fbf671adbbd823", "size": 6907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xfel/mono_simulation/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": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "xfel/mono_simulation/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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xfel/mono_simulation/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": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T12:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T12:52:30.000Z", "avg_line_length": 46.0466666667, "max_line_length": 89, "alphanum_fraction": 0.7045026784, "num_tokens": 1787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.17278945087373354}}
{"text": "/*\n * @Description: lidar localization frontend, interface\n * @Author: Ren Qian\n * @Date: 2020-02-04 18:52:45\n */\n#ifndef LIDAR_LOCALIZATION_MATCHING_FRONT_END_MATCHING_HPP_\n#define LIDAR_LOCALIZATION_MATCHING_FRONT_END_MATCHING_HPP_\n\n#include <deque>\n#include <Eigen/Dense>\n#include <yaml-cpp/yaml.h>\n\n#include \"lidar_localization/sensor_data/cloud_data.hpp\"\n#include \"lidar_localization/sensor_data/pose_data.hpp\"\n\n#include \"lidar_localization/models/scan_context_manager/scan_context_manager.hpp\"\n#include \"lidar_localization/models/registration/registration_interface.hpp\"\n#include \"lidar_localization/models/cloud_filter/cloud_filter_interface.hpp\"\n#include \"lidar_localization/models/cloud_filter/box_filter.hpp\"\n\nnamespace lidar_localization {\n\nclass Matching {\npublic:\n    Matching();\n\n    bool HasInited(void);\n    bool HasNewGlobalMap(void);\n    bool HasNewLocalMap(void);\n\n    Eigen::Matrix4f GetInitPose(void);\n    CloudData::CLOUD_PTR& GetGlobalMap(void);\n    CloudData::CLOUD_PTR& GetLocalMap(void);\n    CloudData::CLOUD_PTR& GetCurrentScan(void);\n\n    bool Update(\n      const CloudData& cloud_data, \n      Eigen::Matrix4f& laser_pose, Eigen::Matrix4f &map_matching_pose\n    );\n\n    bool SetGNSSPose(const Eigen::Matrix4f& init_pose);\n    bool SetScanContextPose(const CloudData& init_scan);\n\nprivate:\n    bool InitWithConfig();\n    // \n    // point cloud map & measurement processors:\n    // \n    bool InitFilter(\n      const YAML::Node &config_node, std::string filter_user, \n      std::shared_ptr<CloudFilterInterface>& filter_ptr\n    );\n    bool InitLocalMapSegmenter(const YAML::Node& config_node);\n    bool InitPointCloudProcessors(const YAML::Node& config_node);\n    //\n    // global map:\n    //\n    bool InitGlobalMap(const YAML::Node& config_node);\n    //\n    // lidar frontend for relative pose estimation:\n    //\n    bool InitRegistration(const YAML::Node& config_node, std::shared_ptr<RegistrationInterface>& registration_ptr);\n    //\n    // map matcher:\n    //\n    bool InitScanContextManager(const YAML::Node& config_node);\n\n    bool SetInitPose(const Eigen::Matrix4f& init_pose);\n    bool ResetLocalMap(float x, float y, float z);\n\nprivate:\n    std::shared_ptr<CloudFilterInterface> global_map_filter_ptr_;\n\n    std::shared_ptr<BoxFilter> local_map_segmenter_ptr_;\n    std::shared_ptr<CloudFilterInterface> local_map_filter_ptr_;\n\n    std::shared_ptr<CloudFilterInterface> frame_filter_ptr_;\n\n    CloudData::CLOUD_PTR global_map_ptr_;\n    CloudData::CLOUD_PTR local_map_ptr_;\n    CloudData::CLOUD_PTR current_scan_ptr_;\n\n    std::shared_ptr<RegistrationInterface> registration_ptr_;\n\n    std::shared_ptr<ScanContextManager> scan_context_manager_ptr_;\n\n    Eigen::Matrix4f current_pose_ = Eigen::Matrix4f::Identity();\n\n    Eigen::Matrix4f init_pose_ = Eigen::Matrix4f::Identity();\n    Eigen::Matrix4f current_gnss_pose_ = Eigen::Matrix4f::Identity();\n\n    bool has_inited_ = false;\n    bool has_new_global_map_ = false;\n    bool has_new_local_map_ = false;\n};\n\n} // namespace lidar_localization\n\n#endif // LIDAR_LOCALIZATION_MATCHING_FRONTEND_MATCHING_HPP_", "meta": {"hexsha": "c6f81b0adf337d0e14710e6758a77bb51d70411a", "size": 3085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/matching/front_end/matching.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "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": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/matching/front_end/matching.hpp", "max_issues_repo_name": "lanqing30/SensorFusionCourse", "max_issues_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "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": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/matching/front_end/matching.hpp", "max_forks_repo_name": "lanqing30/SensorFusionCourse", "max_forks_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:05:31.000Z", "avg_line_length": 31.1616161616, "max_line_length": 115, "alphanum_fraction": 0.752350081, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.17278490921046905}}
{"text": "#include <boost/function.hpp>\n\nnamespace learning\n{\n\n    boost::function<float (int x) f;\n\n    boost::function grad(boost::function f)\n    {\n        // right now this would contain a simple grad program\t\n        return 0;\n    }\n\n}\n", "meta": {"hexsha": "ea7b03cc30a840f3213e7c17f77e3ff4cdedb16b", "size": 231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/learning.hpp", "max_stars_repo_name": "suhubdy/Boost.learning", "max_stars_repo_head_hexsha": "66eac93ca806fde3282191827f84a5a07c78259d", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-02T21:17:06.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-02T21:17:06.000Z", "max_issues_repo_path": "include/boost/learning.hpp", "max_issues_repo_name": "dendisuhubdy/Boost.learning", "max_issues_repo_head_hexsha": "66eac93ca806fde3282191827f84a5a07c78259d", "max_issues_repo_licenses": ["WTFPL"], "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/learning.hpp", "max_forks_repo_name": "dendisuhubdy/Boost.learning", "max_forks_repo_head_hexsha": "66eac93ca806fde3282191827f84a5a07c78259d", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4, "max_line_length": 62, "alphanum_fraction": 0.619047619, "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17278490921046902}}
{"text": "/**\n * @file beam_pattern_multi.cc\n */\n\n#include <usml/sensors/beam_pattern_multi.h>\n#include <boost/foreach.hpp>\n\nusing namespace usml::sensors ;\nusing namespace boost ;\n\n/**\n * Constructor\n */\nbeam_pattern_multi::beam_pattern_multi(\n    std::list<beam_pattern_model*> beam_list )\n    : _beam_list(beam_list)\n{\n\n}\n\n/**\n * Destructor\n */\nbeam_pattern_multi::~beam_pattern_multi()\n{\n    BOOST_FOREACH( beam_pattern_model* b, _beam_list )\n        delete b ;\n}\n\n/**\n * Multiplies all beam levels from each beam pattern\n */\nvoid beam_pattern_multi::beam_level(\n    double de, double az,\n    orientation& orient,\n    const vector<double>& frequencies,\n    vector<double>* level )\n{\n    write_lock_guard(_mutex) ;\n    vector<double> tmp( frequencies.size(), 1.0 ) ;\n    noalias(*level) = vector<double>( frequencies.size(), 1.0 ) ;\n    BOOST_FOREACH( beam_pattern_model* b, _beam_list )\n    {\n        b->beam_level( de, az, orient, frequencies, &tmp ) ;\n        *level = element_prod( *level, tmp ) ;\n    }\n}\n\n/**\n * Multiplies the directivity indices from each beam pattern\n */\nvoid beam_pattern_multi::directivity_index(\n    const vector<double>& frequencies,\n    vector<double>* level )\n{\n    write_lock_guard(_mutex) ;\n    vector<double> tmp( frequencies.size(), 1.0 ) ;\n    noalias(*level) = vector<double>( frequencies.size(), 0.0 ) ;\n    BOOST_FOREACH( beam_pattern_model* b, _beam_list )\n    {\n        b->directivity_index( frequencies, &tmp ) ;\n        *level += tmp ;\n    }\n}\n", "meta": {"hexsha": "6caee6c119e99946298277e8ce4aca6434062d2c", "size": 1480, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sensors/beam_pattern_multi.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "sensors/beam_pattern_multi.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "sensors/beam_pattern_multi.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": 22.7692307692, "max_line_length": 65, "alphanum_fraction": 0.6635135135, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17278490921046902}}
{"text": "// Copyright 2014 Jonathan Graehl - http://graehl.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#ifndef GRAEHL__SHARED__HASH_CACHE_HPP\n#define GRAEHL__SHARED__HASH_CACHE_HPP\n\n#include <boost/functional/hash.hpp>\n//#include <graehl/shared/hashtable_fwd.hpp>\n#include <vector>\n#include <cassert>\n\n#include <graehl/shared/doubling_primes.hpp>\n\nnamespace graehl {\n\n/* *Hash is a stateless functor:\n   size_t Hash::operator()(const Key &key) const\n\n   *Backing class is stored by value, and must provide:\n   void Backing::get(const Key &key,Val *val)\n\n   *Key must provide equality,assignment\n   */\ntemplate <class Key, class Val, class Backing, class Hash = boost::hash<Key>, size_t default_cache_size = 7919 >\nstruct hash_cache\n{\n  Backing backing_store;\n  static Hash stateless_hasher;\n  unsigned cachesize;\n  typedef hash_cache<Key, Val, Backing> Self;\n  static unsigned hash(const Key &key)\n  {\n    return stateless_hasher(key);\n  }\n  hash_cache(const Key &null_value = Key(), std::size_t cache_size = 10000) { init(null_value); }\n  hash_cache(const Key &null_value = Key(), const Backing &back, std::size_t cache_size = 10000) : backing_store(back) { init(null_value); }\n  typedef std::pair<Key, Val> entry;\n  typedef std::vector<entry> cache;\n  void init(const Key &null_value = Key(), std::size_t cache_size = 10000)\n  {\n    cachesize = prime_upper_bound(cache_size);\n    cache.clear();\n    cache.resize(cachesize, entry(null_value, Val()));\n    assert(cache.size()==cachesize);\n    n_miss = n_hit = 0;\n  }\n  std::size_t n_miss, n_hit;\n  // returns [0...1] portion of hits\n  double hit_rate()\n  {\n    return n_hit / ((double)n_miss+n_hit);\n  }\n  Val &operator[](const Key &key)\n  {\n    unsigned i = hash(key) % cachesize;\n    Key &cached_key = cache[i].first;\n    Val &cached_val = cache[i].second;\n    if (cached_key != key) {\n      cached_key = key;\n      ++n_miss;\n      backing_store.get(key, &cached_val);\n    } else {\n      ++n_hit;\n    }\n    return cached_val;\n  }\n};\n\n\n}\n\n#endif\n", "meta": {"hexsha": "ca1ada77137c80655f951fae033038e9df10313b", "size": 2507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "graehl/shared/hash_cache.hpp", "max_stars_repo_name": "graehl/carmel", "max_stars_repo_head_hexsha": "4a5d0990a17d0d853621348272b2f05a0dab3450", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T16:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T07:36:10.000Z", "max_issues_repo_path": "graehl/shared/hash_cache.hpp", "max_issues_repo_name": "graehl/carmel", "max_issues_repo_head_hexsha": "4a5d0990a17d0d853621348272b2f05a0dab3450", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-18T17:20:37.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-23T07:36:38.000Z", "max_forks_repo_path": "graehl/shared/hash_cache.hpp", "max_forks_repo_name": "graehl/carmel", "max_forks_repo_head_hexsha": "4a5d0990a17d0d853621348272b2f05a0dab3450", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-06-11T14:48:13.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-12T16:06:19.000Z", "avg_line_length": 30.2048192771, "max_line_length": 140, "alphanum_fraction": 0.6988432389, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.17278490574836988}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SIMD_TANPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIMD_TANPI_HPP_INCLUDED\n\n#include <boost/simd/function/scalar/tanpi.hpp>\n#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>\n#include <boost/simd/arch/common/simd/function/tanpi.hpp>\n\n#endif\n", "meta": {"hexsha": "e1aa8d495f39cdfa2cf3da6f8ec5ab07e1f91f6d", "size": 673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/simd/tanpi.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/simd/tanpi.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/simd/tanpi.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": 37.3888888889, "max_line_length": 100, "alphanum_fraction": 0.5631500743, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.1725312491595423}}
{"text": "#pragma once\n#include <CreateCoin/protocol/types_fwd.hpp>\n#include <CreateCoin/protocol/config.hpp>\n\n#include <CreateCoin/protocol/asset_symbol.hpp>\n#include <CreateCoin/protocol/fixed_string.hpp>\n\n#include <fc/container/flat_fwd.hpp>\n#include <fc/io/varint.hpp>\n#include <fc/io/enum_type.hpp>\n#include <fc/crypto/sha224.hpp>\n#include <fc/crypto/ripemd160.hpp>\n#include <fc/crypto/elliptic.hpp>\n#include <fc/reflect/reflect.hpp>\n#include <fc/reflect/variant.hpp>\n#include <fc/safe.hpp>\n#include <fc/optional.hpp>\n#include <fc/container/flat.hpp>\n#include <fc/string.hpp>\n#include <fc/io/raw.hpp>\n#include <fc/uint128.hpp>\n#include <fc/static_variant.hpp>\n#include <fc/smart_ref_fwd.hpp>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <memory>\n#include <vector>\n#include <deque>\n#include <cstdint>\n\nnamespace CreateCoin {\n\n   using                                    fc::uint128_t;\n   typedef boost::multiprecision::uint256_t u256;\n   typedef boost::multiprecision::uint512_t u512;\n\n   using                               std::map;\n   using                               std::vector;\n   using                               std::unordered_map;\n   using                               std::string;\n   using                               std::deque;\n   using                               std::shared_ptr;\n   using                               std::weak_ptr;\n   using                               std::unique_ptr;\n   using                               std::set;\n   using                               std::pair;\n   using                               std::enable_shared_from_this;\n   using                               std::tie;\n   using                               std::make_pair;\n\n   using                               fc::smart_ref;\n   using                               fc::variant_object;\n   using                               fc::variant;\n   using                               fc::enum_type;\n   using                               fc::optional;\n   using                               fc::unsigned_int;\n   using                               fc::signed_int;\n   using                               fc::time_point_sec;\n   using                               fc::time_point;\n   using                               fc::safe;\n   using                               fc::flat_map;\n   using                               fc::flat_set;\n   using                               fc::static_variant;\n   using                               fc::ecc::range_proof_type;\n   using                               fc::ecc::range_proof_info;\n   using                               fc::ecc::commitment_type;\n   struct void_t{};\n\n   namespace protocol {\n\n      typedef fc::ecc::private_key        private_key_type;\n      typedef fc::sha256                  chain_id_type;\n      typedef fixed_string<16>            account_name_type;\n      typedef fc::ripemd160               block_id_type;\n      typedef fc::ripemd160               checksum_type;\n      typedef fc::ripemd160               transaction_id_type;\n      typedef fc::sha256                  digest_type;\n      typedef fc::ecc::compact_signature  signature_type;\n      typedef safe<int64_t>               share_type;\n      typedef uint16_t                    weight_type;\n      typedef uint32_t                    contribution_id_type;\n      typedef fixed_string<32>            custom_id_type;\n\n\n      struct public_key_type\n      {\n            struct binary_key\n            {\n               binary_key() {}\n               uint32_t                 check = 0;\n               fc::ecc::public_key_data data;\n            };\n            fc::ecc::public_key_data key_data;\n            public_key_type();\n            public_key_type( const fc::ecc::public_key_data& data );\n            public_key_type( const fc::ecc::public_key& pubkey );\n            explicit public_key_type( const std::string& base58str );\n            operator fc::ecc::public_key_data() const;\n            operator fc::ecc::public_key() const;\n            explicit operator std::string() const;\n            friend bool operator == ( const public_key_type& p1, const fc::ecc::public_key& p2);\n            friend bool operator == ( const public_key_type& p1, const public_key_type& p2);\n            friend bool operator < ( const public_key_type& p1, const public_key_type& p2) { return p1.key_data < p2.key_data; }\n            friend bool operator != ( const public_key_type& p1, const public_key_type& p2);\n      };\n\n      #define CreateCoin_INIT_PUBLIC_KEY (CreateCoin::protocol::public_key_type(CreateCoin_INIT_PUBLIC_KEY_STR))\n\n      struct extended_public_key_type\n      {\n         struct binary_key\n         {\n            binary_key() {}\n            uint32_t                   check = 0;\n            fc::ecc::extended_key_data data;\n         };\n\n         fc::ecc::extended_key_data key_data;\n\n         extended_public_key_type();\n         extended_public_key_type( const fc::ecc::extended_key_data& data );\n         extended_public_key_type( const fc::ecc::extended_public_key& extpubkey );\n         explicit extended_public_key_type( const std::string& base58str );\n         operator fc::ecc::extended_public_key() const;\n         explicit operator std::string() const;\n         friend bool operator == ( const extended_public_key_type& p1, const fc::ecc::extended_public_key& p2);\n         friend bool operator == ( const extended_public_key_type& p1, const extended_public_key_type& p2);\n         friend bool operator != ( const extended_public_key_type& p1, const extended_public_key_type& p2);\n      };\n\n      struct extended_private_key_type\n      {\n         struct binary_key\n         {\n            binary_key() {}\n            uint32_t                   check = 0;\n            fc::ecc::extended_key_data data;\n         };\n\n         fc::ecc::extended_key_data key_data;\n\n         extended_private_key_type();\n         extended_private_key_type( const fc::ecc::extended_key_data& data );\n         extended_private_key_type( const fc::ecc::extended_private_key& extprivkey );\n         explicit extended_private_key_type( const std::string& base58str );\n         operator fc::ecc::extended_private_key() const;\n         explicit operator std::string() const;\n         friend bool operator == ( const extended_private_key_type& p1, const fc::ecc::extended_private_key& p2);\n         friend bool operator == ( const extended_private_key_type& p1, const extended_private_key_type& p2);\n         friend bool operator != ( const extended_private_key_type& p1, const extended_private_key_type& p2);\n      };\n\n      chain_id_type generate_chain_id( const std::string& chain_id_name );\n\n} }  // CreateCoin::protocol\n\nnamespace fc\n{\n    void to_variant( const CreateCoin::protocol::public_key_type& var,  fc::variant& vo );\n    void from_variant( const fc::variant& var,  CreateCoin::protocol::public_key_type& vo );\n    void to_variant( const CreateCoin::protocol::extended_public_key_type& var, fc::variant& vo );\n    void from_variant( const fc::variant& var, CreateCoin::protocol::extended_public_key_type& vo );\n    void to_variant( const CreateCoin::protocol::extended_private_key_type& var, fc::variant& vo );\n    void from_variant( const fc::variant& var, CreateCoin::protocol::extended_private_key_type& vo );\n}\n\nFC_REFLECT( CreateCoin::protocol::public_key_type, (key_data) )\nFC_REFLECT( CreateCoin::protocol::public_key_type::binary_key, (data)(check) )\nFC_REFLECT( CreateCoin::protocol::extended_public_key_type, (key_data) )\nFC_REFLECT( CreateCoin::protocol::extended_public_key_type::binary_key, (check)(data) )\nFC_REFLECT( CreateCoin::protocol::extended_private_key_type, (key_data) )\nFC_REFLECT( CreateCoin::protocol::extended_private_key_type::binary_key, (check)(data) )\n\nFC_REFLECT_TYPENAME( CreateCoin::protocol::share_type )\n\nFC_REFLECT( CreateCoin::void_t, )\n", "meta": {"hexsha": "8844b961272a61e706cd163c95d6b1e4c69a47d8", "size": 7796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/protocol/include/steem/protocol/types.hpp", "max_stars_repo_name": "DunnCreativeSS/ccd", "max_stars_repo_head_hexsha": "83531f2c902a7e8bea351c86c4ca0e4b03820d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T16:09:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T16:09:26.000Z", "max_issues_repo_path": "libraries/protocol/include/steem/protocol/types.hpp", "max_issues_repo_name": "DunnCreativeSS/ccd", "max_issues_repo_head_hexsha": "83531f2c902a7e8bea351c86c4ca0e4b03820d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/protocol/include/steem/protocol/types.hpp", "max_forks_repo_name": "DunnCreativeSS/ccd", "max_forks_repo_head_hexsha": "83531f2c902a7e8bea351c86c4ca0e4b03820d5b", "max_forks_repo_licenses": ["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.797752809, "max_line_length": 128, "alphanum_fraction": 0.5931246793, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.1725209829220043}}
{"text": "/*! *****************************************************************************\n *   \\file libSampler.cpp\n *   \\author moennen\n *   \\brief\n *   \\date 2018-04-06\n *   *****************************************************************************/\n\n#include \"sampleBuffDataset/libBuffDatasetSampler.h\"\n\n#include \"utils/cv_utils.h\"\n#include \"utils/imgFileLst.h\"\n#include \"utils/Hop.h\"\n\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include <glm/glm.hpp>\n\n#include <future>\n\n#include <random>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <array>\n\n#include <ctime>\n#include <iostream>\n#include <map>\n\nusing namespace std;\nusing namespace cv;\nusing namespace glm;\n\n#define TRACE cout << __PRETTY_FUNCTION__ << \"@\" << __LINE__ << endl;\n\nnamespace\n{\n// copy the input mask to the output and set null the averaged mask values\nvoid correctMask( const Mat& imask, Mat& omask )\n{\n#pragma omp parallel for\n   for ( unsigned y = 0; y < omask.rows; y++ )\n   {\n      const float* imaskPtr = imask.ptr<float>( y );\n      float* omaskPtr = omask.ptr<float>( y );\n      for ( unsigned x = 0; x < omask.cols; x++ )\n      {\n         omaskPtr[x] = ( imaskPtr[x] < 0.999 ? 0.0 : 1.0 );\n      }\n   }\n}\n\n// set to null masked depth entries\nvoid maskDepth( const Mat& matMask, Mat& matDepth )\n{\n#pragma omp parallel for\n   for ( unsigned y = 0; y < matDepth.rows; y++ )\n   {\n      const float* fPtrMask = matMask.ptr<float>( y );\n      float* fPtrDepth = matDepth.ptr<float>( y );\n      for ( unsigned x = 0; x < matDepth.cols; x++ )\n      {\n         if (fPtrMask[x] < 0.999) fPtrDepth[x] = 0.0;\n      }\n   }\n}\n\nstruct Sampler final\n{\n   mt19937 _rng;\n   uniform_int_distribution<> _dataGen;\n   uniform_real_distribution<> _tsGen;\n   normal_distribution<> _rnGen;\n\n   const ivec3 _sampleSz;\n   const bool _toLinear;\n   const bool _doRescale;\n\n   const unsigned _depthBuffSz;\n   const unsigned _maskBuffSz;\n   const unsigned _imgBuffSz;\n\n   const unsigned _fullBuffSz;\n   future<bool> _asyncSample;\n   vector<float> _asyncBuff;\n\n   enum\n   {\n      nInBuffers = 3,\n      nOutBuffers = 3,\n      nOutPlanes = 5  // RGB : 3 / Depth : 1 / Mask : 1\n   };\n   ImgNFileLst _data;\n\n   inline static unsigned getBufferDepth( const unsigned buffId ) { return buffId == 0 ? 3 : 1; }\n\n   Sampler(\n       const char* dataSetPath,\n       const char* dataPath,\n       const ivec3 sampleSz,\n       const bool toLinear,\n       const bool doRescale,\n       const bool doAsync,\n       const int seed )\n       : _rng( seed ),\n         _tsGen( 0.0, 1.0 ),\n         _sampleSz( sampleSz ),\n         _toLinear( toLinear ),\n         _doRescale( doRescale ),\n         _depthBuffSz( _sampleSz.y * _sampleSz.z ),\n         _maskBuffSz( _depthBuffSz ),\n         _imgBuffSz( _depthBuffSz * 3 ),\n         _fullBuffSz( _sampleSz.y * _sampleSz.z * nOutPlanes ),\n         _data( nInBuffers )\n   {\n      HOP_PROF_FUNC();\n\n      _data.open( dataSetPath, dataPath );\n\n      if ( _data.size() )\n      {\n         std::cout << \"Read dataset \" << dataSetPath << \" (\" << _data.size() << \") \" << std::endl;\n      }\n      _dataGen = uniform_int_distribution<>( 0, _data.size() - 1 );\n\n      cout << endl << \"WARNING ! SAMPLER : NO ERODED MASK PRODUCED !!!!!!! \" << endl << endl;\n\n      if ( _data.size() && doAsync )\n      {\n         _asyncBuff.resize( sampleSz.x * _fullBuffSz );\n         _asyncSample = async( launch::async, [&]() { return sample_internal( &_asyncBuff[0] ); } );\n      }\n   }\n\n   bool sample( float* buff )\n   {\n      if ( _asyncBuff.empty() )\n         return sample_internal( buff );\n      else\n      {\n         bool success = _asyncSample.get();\n         if ( success )\n         {\n#pragma omp parallel for\n            for ( int b = 0; b < _sampleSz.x; ++b )\n            {\n               const size_t off = b * _fullBuffSz;\n               memcpy( buff + off, &_asyncBuff[off], sizeof( float ) * _fullBuffSz );\n            }\n         }\n         _asyncSample = async( launch::async, [&]() { return sample_internal( &_asyncBuff[0] ); } );\n         return success;\n      }\n   }\n\n   size_t nSamples() const { return _data.size(); }\n   ivec3 sampleSizes() const { return _sampleSz; }\n\n  private:\n   bool sample_internal( float* buff )\n   {\n      HOP_PROF_FUNC();\n\n      float* currBuffImg = buff;\n      float* currBuffDepth = buff + _imgBuffSz * _sampleSz.x;\n      float* currBuffMask = buff + ( _imgBuffSz + _depthBuffSz ) * _sampleSz.x;\n      // float* currBuffErodedMask = buff + ( _imgBuffSz + _depthBuffSz + _maskBuffSz ) *\n      // _sampleSz.x;\n\n      std::vector<char> sampled( _sampleSz.x, 0 );\n      std::vector<size_t> v_si( _sampleSz.x );\n      do\n      {\n         for ( auto& si : v_si ) si = _dataGen( _rng );\n\n#pragma omp parallel for\n         for ( size_t s = 0; s < _sampleSz.x; ++s )\n         {\n            if ( sampled[s] ) continue;\n\n            const size_t si = v_si[s];\n\n            Mat currImg =\n                cv_utils::imread32FC3( _data.filePath( si, 0 ), _toLinear, true /*toRGB*/ );\n            Mat currDepth = cv_utils::imread32FC1( _data.filePath( si, 1 ) );\n            Mat currMask = cv_utils::imread32FC1( _data.filePath( si, 2 ) );\n\n            ivec2 imgSz( currImg.cols, currImg.rows );\n\n            // ignore failed samples\n            if ( currImg.empty() || currDepth.empty() || currMask.empty() ) continue;\n\n            // padd too small samples\n            if ( ( imgSz.x < _sampleSz.y ) || ( imgSz.y < _sampleSz.z ) )\n            {\n               const ivec2 topright(\n                   max( ivec2( _sampleSz.y - imgSz.x, _sampleSz.z - imgSz.y ), ivec2( 0 ) ) );\n               copyMakeBorder( currImg, currImg, topright.y, 0, 0, topright.x, BORDER_CONSTANT );\n               copyMakeBorder(\n                   currDepth, currDepth, topright.y, 0, 0, topright.x, BORDER_CONSTANT );\n               copyMakeBorder( currMask, currMask, topright.y, 0, 0, topright.x, BORDER_CONSTANT );\n               imgSz = ivec2( currImg.cols, currImg.rows );\n            }\n\n            // random rescale\n            bool rescaled = false;\n            if ( _doRescale )\n            {\n               const float minDs =\n                   std::max( (float)_sampleSz.z / imgSz.y, (float)_sampleSz.y / imgSz.x );\n               const float ds = minDs; //mix( 1.0f, minDs, _tsGen( _rng ) );\n               if ( ds < 1.0 )\n               {\n                  rescaled = true;\n                  resize( currImg, currImg, Size(), ds, ds, INTER_AREA );\n                  resize( currDepth, currDepth, Size(), ds, ds, INTER_AREA );\n                  resize( currMask, currMask, Size(), ds, ds, INTER_AREA );\n                  imgSz = ivec2( currImg.cols, currImg.rows );\n               }\n            }\n\n            // random translate\n            const ivec2 trans(\n                std::floor( _tsGen( _rng ) * ( imgSz.x - _sampleSz.y ) ),\n                std::floor( _tsGen( _rng ) * ( imgSz.y - _sampleSz.z ) ) );\n\n            // crop\n            currImg = currImg( Rect( trans.x, trans.y, _sampleSz.y, _sampleSz.z ) );\n            currDepth = currDepth( Rect( trans.x, trans.y, _sampleSz.y, _sampleSz.z ) );\n            currMask = currMask( Rect( trans.x, trans.y, _sampleSz.y, _sampleSz.z ) );\n\n            // copy and correct mask\n            Mat maskSple( _sampleSz.z, _sampleSz.y, CV_32FC1, currBuffMask + s * _maskBuffSz );\n            if ( rescaled )\n               correctMask( currMask, maskSple );\n            else\n               currMask.copyTo( maskSple );\n            if ( sum( maskSple )[0] < 20 ) continue;\n\n            // random small blur to remove artifacts + copy to destination\n            Mat imgSple( _sampleSz.z, _sampleSz.y, CV_32FC3, currBuffImg + s * _imgBuffSz );\n            currImg.copyTo(imgSple);\n            /*cv_utils::adjustContrastBrightness<vec3>(\n                currImg, ( 1.0f + 0.11f * _rnGen( _rng ) ), 0.11f * _rnGen( _rng ) );\n            GaussianBlur( currImg, imgSple, Size( 3, 3 ), 0.31 * abs( _rnGen( _rng ) ) );*/\n\n            // copy and process depth\n            Mat depthSple( _sampleSz.z, _sampleSz.y, CV_32FC1, currBuffDepth + s * _depthBuffSz );\n            maskSple.convertTo( currMask, CV_8UC1, 255.0, 0.0 );\n            currDepth.copyTo(depthSple);\n            /*cv::Mat mean, std;\n            cv::meanStdDev( currDepth, mean, std, currMask );\n            depthSple = ( ( currDepth - mean ) / std );\n            // normalize( currDepth, depthSple, 0.0, 1.0, NORM_MINMAX, -1, currMask );\n            // this is for debugging !!!\n            depthSple = depthSple.mul( maskSple );*/\n            // apply log \n            cv::log(currDepth, depthSple);\n            maskDepth(maskSple,depthSple);\n            \n            \n            //transpose(imgSple,imgSple);\n            //transpose(depthSple,depthSple);\n            //transpose(maskSple,maskSple);\n            \n            // copy and process eroded mask\n            // Mat erodedMaskSple( _sampleSz.z, _sampleSz.y, CV_32FC1, currBuffErodedMask );\n            // erode(maskSple, erodedMaskSple, Mat());\n\n            sampled[s] = 1;\n         }\n      } while ( accumulate( sampled.begin(), sampled.end(), 0 ) != _sampleSz.x );\n\n      return true;\n   }\n};\n\narray<unique_ptr<Sampler>, 33> g_samplers;\n};\n\nextern \"C\" int getNbBuffers( const int /*sidx*/ ) { return Sampler::nOutBuffers; }\n\nextern \"C\" int getBuffersDim( const int sidx, float* dims )\n{\n   HOP_PROF_FUNC();\n\n   if ( !g_samplers[sidx].get() ) return ERROR_UNINIT;\n\n   const ivec3 sz = g_samplers[sidx]->sampleSizes();\n   float* d = dims;\n   for ( size_t i = 0; i < Sampler::nOutBuffers; ++i )\n   {\n      d[0] = sz.z;\n      d[1] = sz.y;\n      d[2] = Sampler::getBufferDepth( i );\n      d += 3;\n   }\n\n   return SUCCESS;\n}\n\nextern \"C\" int initBuffersDataSampler(\n    const int sidx,\n    const char* datasetPath,\n    const char* dataPath,\n    const int nParams,\n    const float* params,\n    const int seed )\n{\n   HOP_PROF_FUNC();\n\n   // check input\n   if ( ( nParams < 3 ) || ( sidx > g_samplers.size() ) ) return ERROR_BAD_ARGS;\n\n   // parse params\n   const ivec3 sz( params[0], params[2], params[1] );\n   const bool toLinear( nParams > 3 ? params[3] > 0.0 : false );\n   const bool doRescale( nParams > 4 ? params[4] > 0.0 : false );\n   const bool doAsync( nParams > 5 ? params[5] > 0.0 : true );\n   g_samplers[sidx].reset(\n       new Sampler( datasetPath, dataPath, sz, toLinear, doRescale, doAsync, seed ) );\n\n   return g_samplers[sidx]->nSamples() ? SUCCESS : ERROR_BAD_DB;\n}\n\nextern \"C\" int getBuffersDataSample( const int sidx, float* buff )\n{\n   HOP_PROF_FUNC();\n\n   if ( !g_samplers[sidx].get() ) return ERROR_UNINIT;\n\n   // sample\n   if ( !g_samplers[sidx]->sample( buff ) ) return ERROR_GENERIC;\n\n   return SUCCESS;\n}\n", "meta": {"hexsha": "b51a7885af6c92648cae19c58a1ad92b6b749500", "size": 10696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sampleBuffDataset/libSparseDepthImgSampler/libSampler.cpp", "max_stars_repo_name": "moennen/sceneIllEst", "max_stars_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-04T09:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-17T07:02:49.000Z", "max_issues_repo_path": "sampleBuffDataset/libSparseDepthImgSampler/libSampler.cpp", "max_issues_repo_name": "moennen/sceneIllEst", "max_issues_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "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": "sampleBuffDataset/libSparseDepthImgSampler/libSampler.cpp", "max_forks_repo_name": "moennen/sceneIllEst", "max_forks_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "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.6449704142, "max_line_length": 100, "alphanum_fraction": 0.5559087509, "num_tokens": 3027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.17252098292200427}}
{"text": "#include \"manycal/FiducialArrayCalibrator.h\"\n#include \"argus_utils/utils/ParamUtils.h\"\n\n#include <boost/foreach.hpp>\n\nnamespace argus\n{\n\t\nFiducialArrayCalibrator::FiducialArrayCalibrator( ros::NodeHandle& nh,\n                                                  ros::NodeHandle& ph )\n: _fiducialManager( _lookupInterface ),\n  _extrinsicsManager( nh, ph ), \n  _detCounter( 0 )\n{\n\tGetParamRequired( ph, \"reference_frame\", _referenceFrame );\n\tGetParam( ph, \"batch_period\", _batchPeriod, (unsigned int) 10 );\n\tGetParam( ph, \"min_detections_per_image\", _minDetectionsPerImage, (unsigned int) 2 );\n\tGetParam( ph, \"prior_covariance\", _priorCovariance, PoseSE3::CovarianceMatrix::Identity() );\n\t\n\tstd::string lookupNamespace;\n\tGetParam<std::string>( ph, \"lookup_namespace\", lookupNamespace, \"/lookup\" );\n\t_lookupInterface.SetLookupNamespace( lookupNamespace );\n\n\t// Create optimizer object\n\tros::NodeHandle oh( ph.resolveName( \"optimizer\" ) );\n\t_optimizer = GraphOptimizer( oh );\n\t\n\t// Create camera intrinsics node\n\t_cameraIntrinsics = std::make_shared <isam::MonocularIntrinsics_Node>();\n\t_cameraIntrinsics->init( isam::MonocularIntrinsics( 1.0, 1.0, Eigen::Vector2d( 0, 0 ) ) );\n\n\t// Create fiducial reference pose node\n\t_fiducialReference = std::make_shared<isam::PoseSE3_Node>();\n\t_fiducialReference->init( isam::PoseSE3() );\n\t\n\tunsigned int buffSize;\n\tGetParam( ph, \"buffer_size\", buffSize, (unsigned int) 10 );\n\t_detSub = nh.subscribe( \"detections\", \n\t                        buffSize, \n\t                        &FiducialArrayCalibrator::DetectionCallback,\n\t                        this );\n}\n\nvoid FiducialArrayCalibrator::WriteResults() \n{\n\tBOOST_FOREACH( const FiducialRegistry::value_type& item, _fiducialRegistry )\n\t{\n\t\tconst std::string& name = item.first;\n\t\tconst FiducialRegistration& registration = item.second;\n\t\tPoseSE3 extrinsics = registration.extrinsics->value().pose;\n\t\tROS_INFO_STREAM( \"Fiducial \" << name << \" pose \" << extrinsics );\n\t\t\n\t\t// TODO Write to a YAML file\n\t\t// ExtrinsicsInfo info;\n\t\t// info.referenceFrame = _referenceFrame;\n\t\t// info.extrinsics = extrinsics;\n\t\t// _extrinsicsManager.WriteMemberInfo( name, info, true );\n\t}\n}\n\nisam::PoseSE3_Node::Ptr\nFiducialArrayCalibrator::InitializeCameraPose( const std::vector<FiducialDetection>& detections )\n{\n\tisam::PoseSE3_Node::Ptr cameraNode;\n\tBOOST_FOREACH( const FiducialDetection& det, detections )\n\t{\n\t\t// Attempt to initialize unregistered fiducials from prior info\n\t\t// If we can't, continue to the next detection\n\t\tif( _fiducialRegistry.count( det.name ) == 0 &&\n\t\t    !InitializeFiducialFromPrior( det.name ) ) { continue; }\n\n\t\t// If we have a registered fiducial, use it to initialize\n\t\tif( _fiducialRegistry.count( det.name ) > 0 )\n\t\t{\n\t\t\tPoseSE3 relPose = EstimateArrayPose( det,\n\t\t\t                                     _fiducialManager.GetInfo( det.name ) );\n\t\t\tPoseSE3 fiducialPose = _fiducialRegistry[ det.name ].extrinsics->value().pose;\n\t\t\tPoseSE3 cameraPose = fiducialPose * relPose.Inverse();\n\t\t\t\n\t\t\tcameraNode = std::make_shared <isam::PoseSE3_Node>();\n\t\t\tcameraNode->init( isam::PoseSE3( cameraPose ) );\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn cameraNode;\n}\n\nvoid FiducialArrayCalibrator::ProcessDetections( const FiducialDetections& detections )\n{\n\tif( detections.size() < _minDetectionsPerImage )\n\t{\n\t\tROS_WARN_STREAM( \"Only \" << detections.size() << \" detections, less than \" <<\n\t\t                 _minDetectionsPerImage << \" minimum. Skipping...\" );\n\t\treturn;\n\t}\n\t_detectionsBuffer.PushBack( detections );\n}\n\nvoid FiducialArrayCalibrator::Spin()\n{\n\tisam::PoseSE3_Node::Ptr cameraNode = InitializeCameraPose( detections );\n\tif( !cameraNode )\n\t{\n\t\tROS_WARN_STREAM( \"Could not initialize camera pose.\" );\n\t\treturn;\n\t}\n\t_cameraPoses.push_back( cameraNode );\n\t_optimizer.GetOptimizer().add_node( cameraNode.get() );\n\t\n\t// Create observation factors for each fiducial detection\n\tBOOST_FOREACH( const FiducialDetection& det, detections )\n\t{\n\t\t// if the fiducial is not registered and we can't get intrinsics, skip it\n\t\tif( _fiducialRegistry.count( det.name ) == 0 \n\t\t    && !_fiducialManager.CheckMemberInfo( det.name ) ) { continue; }\n\t\t\n\t\tconst Fiducial& intrinsics = _fiducialManager.GetInfo( det.name );\n\t\tPoseSE3 relPose = EstimateArrayPose( det, intrinsics );\n\t\tPoseSE3 cameraPose = cameraNode->value().pose;\n\t\tPoseSE3 fiducialPose = cameraPose * relPose;\n\t\tRegisterFiducial( det.name, fiducialPose, false );\n\t\t\n\t\tconst FiducialRegistration& reg = _fiducialRegistry[ det.name ];\n\t\t\n\t\t// TODO Formalize this error model?\n\t\tdouble imageCoordinateErr = std::pow( 0.03, 2 );\n\t\tisam::Noise cov = isam::Covariance( imageCoordinateErr * isam::eye( 2*det.points.size() ) );\n\t\t\n\t\tisam::FiducialFactor::Properties props;\n\t\tprops.optCamReference = true;\n\t\tprops.optCamIntrinsics = false;\n\t\tprops.optCamExtrinsics = false;\n\t\tprops.optFidReference = false;\n\t\tprops.optFidIntrinsics = false;\n\t\tprops.optFidExtrinsics = true;\n\t\t\n\t\tisam::FiducialFactor::Ptr factor = std::make_shared<isam::FiducialFactor>\n\t\t    ( cameraNode.get(), \n\t\t      _cameraIntrinsics.get(), \n\t\t      nullptr,\n\t\t      _fiducialReference.get(), \n\t\t      reg.intrinsics.get(), \n\t\t      reg.extrinsics.get(),\n\t\t      DetectionToIsam( det ), \n\t\t      cov, \n\t\t      props );\n\t\t_optimizer.GetOptimizer().add_factor( factor.get() );\n\t\t_observations.push_back( factor );\n\t}\n\n\tif( _detCounter % _batchPeriod == 0 )\n\t{\n\t\t_optimizer.GetOptimizer().batch_optimization();\n\t\t_optimizer.GetOptimizer().print_graph();\n\t}\n\telse\n\t{\n\t\t_optimizer.GetOptimizer().update();\n\t}\n\t_detCounter++;\n}\n\nbool FiducialArrayCalibrator::InitializeFiducialFromPrior( const std::string& name )\n{\n\tif( _fiducialRegistry.count( name ) > 0 ) { return true; }\n\n\t// If not registered, attempt initialization\n\t// First check intrinsics\n\tif( !_fiducialManager.CheckMemberInfo( name ) ) { return false; }\n\t// Then check extrinsics\n\ttry\n\t{\n\t\tPoseSE3 ext = _extrinsicsManager.GetExtrinsics( name,\n\t\t                                                _referenceFrame );\n\t\tRegisterFiducial( name, ext, true );\n\t\treturn true;\n\t}\n\tcatch( ExtrinsicsException& e ) { return false; }\n}\n\nvoid FiducialArrayCalibrator::RegisterFiducial( const std::string& name,\n                                                const PoseSE3& pose,\n                                                bool addPrior )\n{\n\tif( _fiducialRegistry.count( name ) > 0 ) { return; }\n\t\n\tROS_INFO_STREAM( \"Registering fiducial \" << name << \" with pose \" << pose );\n\t\n\tFiducialRegistration registration;\n\tisam::FiducialIntrinsics intrinsics = FiducialToIsam( _fiducialManager.GetInfo( name ) );\n\tregistration.intrinsics = \n\t    std::make_shared<isam::FiducialIntrinsics_Node>( intrinsics.name(), intrinsics.dim() );\n\tregistration.intrinsics->init( intrinsics );\n\t// NOTE Not optimizing intrinsics, so we don't have to add it to the SLAM object\n\t\n\tregistration.extrinsics = std::make_shared<isam::PoseSE3_Node>();\n\tregistration.extrinsics->init( isam::PoseSE3( pose ) );\n\t_optimizer.GetOptimizer().add_node( registration.extrinsics.get() );\n\t\n\tif( addPrior )\n\t{\n\t\tisam::Noise priorCov = isam::Covariance( _priorCovariance );\n\t\tregistration.extrinsicsPrior = \n\t\t\tstd::make_shared<isam::PoseSE3_Prior>( registration.extrinsics.get(),\n\t\t\t                                       isam::PoseSE3( pose ),\n\t\t\t                                       priorCov );\n\t\t_optimizer.GetOptimizer().add_factor( registration.extrinsicsPrior.get() );\n\t}\n\n\t_fiducialRegistry[ name ] = registration;\n}\n\n}\n", "meta": {"hexsha": "b6e1b4ea0030d0889177d868193432649c17eeca", "size": 7425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "manycal/src/FiducialArrayCalibrator.cpp", "max_stars_repo_name": "Humhu/argus", "max_stars_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-08-02T20:32:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T09:33:33.000Z", "max_issues_repo_path": "manycal/src/FiducialArrayCalibrator.cpp", "max_issues_repo_name": "Humhu/argus", "max_issues_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-12T22:57:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-13T02:52:36.000Z", "max_forks_repo_path": "manycal/src/FiducialArrayCalibrator.cpp", "max_forks_repo_name": "Humhu/argus", "max_forks_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-03-25T08:36:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-23T00:28:16.000Z", "avg_line_length": 34.6962616822, "max_line_length": 97, "alphanum_fraction": 0.6856565657, "num_tokens": 2032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.17252098136232422}}
{"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 MAPGENERATOR_H\n#define MAPGENERATOR_H\n\n#include \"config.hpp\"\n\n#include \"animation.hpp\"\n\n#include <vector>\n#include <string>\n#include <map>\n#include <cmath>\n#include <unordered_map>\n#include <memory>\n#include <random>\n#include <utility>\n\n#include <boost/polygon/polygon.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/polygon/gtl.hpp>\n\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n#include <boost/atomic.hpp>\n#include <boost/thread/shared_mutex.hpp>\n\n#include <boost/logic/tribool.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 <json/value.h>\n#include <FreeImagePlus.h>\n\nnamespace ADWIF\n{\n  class Engine;\n  class Game;\n  class GenerateTerrainTask;\n\n  typedef boost::polygon::polygon_with_holes_data<double> Polygon;\n  typedef boost::polygon::polygon_traits<Polygon>::point_type Point2D;\n\n  typedef boost::geometry::model::point<int, 3, boost::geometry::cs::cartesian> Point3D;\n  typedef boost::geometry::model::box<Point3D> Box3D;\n  typedef std::pair<Box3D, std::shared_ptr<GenerateTerrainTask>> SIVal;\n  typedef boost::geometry::index::rtree<SIVal, boost::geometry::index::quadratic<16> > SpatialIndex;\n\n  struct BiomeCell\n  {\n    std::string name;\n    int x, y;\n    double height;\n    bool aquatic;\n\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version)\n    {\n      ar & name;\n      ar & x;\n      ar & y;\n      ar & height;\n      ar & aquatic;\n    }\n\n    bool operator== (const BiomeCell & other) const\n    {\n      return x == other.x && y == other.y && height == other.height && name == other.name && aquatic == other.aquatic;\n    }\n  };\n\n  struct Region\n  {\n    std::string biome;\n    std::string name;\n    std::string desc;\n    Point2D centroid;\n    Polygon poly;\n    double area;\n    bool infinite;\n\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version)\n    {\n      ar & biome;\n      ar & name;\n      ar & desc;\n      ar & centroid;\n      ar & poly;\n      ar & area;\n      ar & infinite;\n    }\n  };\n\n  class MapGenerator: public std::enable_shared_from_this<MapGenerator>\n  {\n  public:\n    MapGenerator(const std::shared_ptr<class Game> & game);\n    ~MapGenerator();\n\n    std::shared_ptr<class Game> game() { return myGame.lock(); }\n    void game(std::shared_ptr<class Game> & game) { myGame = game; }\n\n    const fipImage & heightmap() const { return myHeightMap; }\n    void heightmapImage(const fipImage & image) { myHeightMap = image; myHeightMap.convertTo32Bits(); }\n\n    const fipImage & mapImage() const { return myMapImg; }\n    void mapImage(const fipImage & image) { myMapImg = image; myMapImg.convertTo32Bits(); }\n\n    int chunkSizeX() const { return myChunkSizeX; }\n    void chunkSizeX( int size) { myChunkSizeX = size; }\n\n    int chunkSizeY() const { return myChunkSizeY; }\n    void chunkSizeY( int size) { myChunkSizeY = size; }\n\n    int chunkSizeZ() const { return myChunkSizeZ; }\n    void chunkSizeZ( int size) { myChunkSizeZ = size; }\n\n    std::mt19937 & random() { return myRandomEngine; }\n\n    int height() const { return myHeight; }\n    int width() const { return myWidth; }\n    int depth() const { return myDepth; }\n    void depth( int depth) { myDepth = depth; }\n\n    const boost::multi_array<BiomeCell, 2> & biomeMap() const { return myBiomeMap; }\n    boost::multi_array<BiomeCell, 2> & biomeMap() { return myBiomeMap; }\n\n    const std::vector<Region> & regions() const { return myRegions; }\n    std::vector<Region> & regions() { return myRegions; }\n\n    int preprocessingProgress() const { return myMapPreprocessingProgress.load(); }\n\n    void init();\n    void generateAround( int x,  int y, int z = 0,  int radius = 1,  int radiusZ = 1);\n\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version)\n    {\n      ar & mySeed;\n      ar & myChunkSizeX;\n      ar & myChunkSizeY;\n      ar & myChunkSizeZ;\n      ar & myColourIndex;\n      ar & myRandomEngine;\n      ar & myGenerationMap;\n      ar & myBiomeMap;\n      ar & myHeights;\n      ar & myInitialisedFlag;\n      ar & myRegions;\n      ar & myHeight;\n      ar & myWidth;\n      ar & myDepth;\n    }\n\n    void notifyLoad();\n    void notifySave();\n\n    void abort();\n\n    inline int getHeight(double x, double y, double z = 0)\n    {\n      return ceil(getHeightReal(x, y, z));\n    }\n\n    inline double getHeightReal(double x, double y, double z = 0)\n    {\n      return myHeightSource->GetValue(x, y, z) * (double)myChunkSizeZ * ((double)myDepth / 2.0);\n    }\n\n  private:\n    bool generateBiomeMap();\n\n  public:\n    boost::logic::tribool isGenerated(int x, int y, int z)\n    {\n      boost::upgrade_lock<boost::shared_mutex> guard(myGenerationLock);\n      return myGenerationMap[x][y][z+myDepth/2];\n    }\n\n    void setGenerated(int x, int y, int z, const boost::logic::tribool & g)\n    {\n      boost::upgrade_lock<boost::shared_mutex> guard(myGenerationLock);\n      boost::upgrade_to_unique_lock<boost::shared_mutex> lock(guard);\n      myGenerationMap[x][y][z+myDepth/2] = g;\n    }\n\n    void notifyComplete(const std::shared_ptr<GenerateTerrainTask> & task);\n\n  private:\n\n    inline static uint32_t getPixelColour (int x, int y, const fipImage & img)\n    {\n      RGBQUAD pptc;\n      img.getPixelColor(x,y,&pptc);\n      return pptc.rgbBlue | pptc.rgbGreen << 8 | pptc.rgbRed << 16;\n    }\n\n  private:\n    std::weak_ptr<class Game> myGame;\n    fipImage myMapImg;\n    fipImage myHeightMap;\n    int myChunkSizeX, myChunkSizeY, myChunkSizeZ;\n    std::unordered_map<uint32_t, std::string> myColourIndex;\n    std::mt19937 myRandomEngine;\n    boost::multi_array<boost::tribool, 3> myGenerationMap;\n    boost::shared_mutex myGenerationLock;\n    boost::multi_array<BiomeCell, 2> myBiomeMap;\n    boost::multi_array<double, 2> myHeights;\n    std::vector<Region> myRegions;\n    int myHeight, myWidth, myDepth;\n    unsigned int mySeed;\n    std::vector<std::shared_ptr<noise::module::Module>> myNoiseModules;\n    std::map<std::string, std::shared_ptr<noise::module::Module>> myNoiseModuleDefs;\n    std::shared_ptr<noise::module::Module> myHeightSource;\n    SpatialIndex myIndex;\n    boost::atomic_int myMapPreprocessingProgress;\n    bool myInitialisedFlag;\n  };\n}\n\nnamespace std\n{\n  template <> struct hash<ADWIF::BiomeCell>\n  {\n    size_t operator()(const ADWIF::BiomeCell & bc) const\n    {\n      size_t h = 0;\n      boost::hash_combine(h, bc.name);\n      boost::hash_combine(h, bc.x);\n      boost::hash_combine(h, bc.y);\n      boost::hash_combine(h, bc.height);\n      return h;\n    }\n  };\n}\n\n#endif // MAPGENERATOR_H\n", "meta": {"hexsha": "14294b9910f68b40a2c437c07b339f9ce8f74b58", "size": 8029, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mapgenerator.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": "mapgenerator.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": "mapgenerator.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": 30.6450381679, "max_line_length": 146, "alphanum_fraction": 0.6826503923, "num_tokens": 2097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17252097265832755}}
{"text": "// ======================================================================\n/*!\n * \\file shape2ps.cpp\n * \\brief A program to render shapefiles into PostScript\n */\n// ======================================================================\n/*!\n * \\page shape2ps shape2ps\n *\n * shape2ps takes as input a single filename containing rendering\n * directives. All rendering directive lines are by default considered\n * to be plain PostScript, and are output as is. A few special tokens\n * will read and output shapefile data, set projections and so on.\n * Note that the special tokens must be the first ones on the line,\n * otherwise they won't be recognized.\n *\n * A very simple example file would be\n *\n * \\code\n * projection stereographic,20,90,60:6,51.3,49,70.2:400,400\n * body\n * 3 setlinewidth\n * 1 1 0 setrgbcolor\n * shape moveto lineto closepath suomi stroke\n * subshape moveto lineto closepath field=value suomi stroke\n * gshhs moveto lineto closepath gshhs_f.c stroke\n * \\endcode\n *\n * Atleast one of coordinate ranges given in the projection is expected to\n * differ from 0-1. If only one differs, the other is calculated to be 0-X,\n * where X is calculated so that aspect ratio is preserved in the set\n * projection.\n *\n * To render querydata contours one can use code like\n * \\code\n * area 10 NFmiLatLonArea ...\n * body\n * querydata /data/pal/querydata/pal/skandinavia/pinta\n * parameter Temperature\n * level 750\n * timemode utc\n * time +1 12\n * newpath\n * bezier approximate 10\n * contourcommands moveto lineto curveto closepath\n * labelcommand show\n * contourline 10 stroke\n * contourline 15 stroke\n * contourline 20 stroke\n * contourline 25 stroke\n * contourline 30 stroke\n * contourfill -10 10 fill\n * contourlabels 10 30 5\n * \\endcode\n *\n * The list of special commands is\n * - projection ... to set the projection\n * - area ... to set the projection as an object\n * - projectioncenter <lon> <lat> <scale>\n * - boundingbox to generate the path for the bounding box\n * - body to indicate the start of the PostScript body\n * - shape <moveto> <lineto> <closepath> <shapefile> to render a shapefile\n * - gshhs <moveto> <lineto> <closepath> <gshhsfile> to render a shoreline\n * - graticule <moveto> <lineto> <lon1> <lon2> <dx> <lat1> <lat2> <dy> to render\n * a graticule\n * - {moveto} {lineto} exec <shapefile> to execute given commands for vertices\n * - {} qdexec <querydata> to execute given commands for grid points\n * - project <x> <y> to output projected x and y\n * - location <place> to output projected x and y\n * - system .... to execute the remaining line in the shell\n * - querydata <name> Set the active querydata\n * - parameter <name> Set the active querydata parameter\n * - level <levelvalue> Set the active querydata level\n * - timemode <local|utc>\n * - time <days> <hour>\n * - smoother <name> <factor> <radius>\n * - contourcommands <moveto> <lineto> <curveto> <closepath>\n * - contourline <value>\n * - contourfill <lolimit> <hilimit>\n * - bezier none\n * - bezier cardinal <0-1>\n * - bezier approximate <maxerror>\n * - bezier tight <maxerror>\n */\n// ======================================================================\n\n#include \"Polyline.h\"\n#include <gis/CoordinateMatrix.h>\n#include <imagine/NFmiApproximateBezierFit.h>\n#include <imagine/NFmiCardinalBezierFit.h>\n#include <imagine/NFmiContourTree.h>\n#include <imagine/NFmiGeoShape.h>\n#include <imagine/NFmiGshhsTools.h>\n#include <imagine/NFmiPath.h>\n#include <imagine/NFmiTightBezierFit.h>\n#include <newbase/NFmiArea.h>\n#include <newbase/NFmiAreaFactory.h>\n#include <newbase/NFmiAreaTools.h>\n#include <newbase/NFmiCmdLine.h>\n#include <newbase/NFmiEnumConverter.h>\n#include <newbase/NFmiFileSystem.h>\n#include <newbase/NFmiLocationFinder.h>\n#include <newbase/NFmiParameterName.h>\n#include <newbase/NFmiPreProcessor.h>\n#include <newbase/NFmiSaveBaseFactory.h>\n#include <newbase/NFmiSettings.h>\n#include <newbase/NFmiSmoother.h>\n#include <newbase/NFmiStreamQueryData.h>\n#include <newbase/NFmiValueString.h>\n#include <cstdlib>\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <string>\n\n#include <boost/lexical_cast.hpp>\n\nusing namespace boost;\nusing namespace std;\n\n// Clamp PostScript path elements to within this range\nconst double clamp_limit = 10000;\n\nstruct BezierSettings\n{\n  BezierSettings(const string &theName,\n                 const string theMode,\n                 double theSmoothness,\n                 double theMaxError)\n      : name(theName), mode(theMode), smoothness(theSmoothness), maxerror(theMaxError)\n  {\n  }\n\n  bool operator==(const BezierSettings &theOther) const\n  {\n    return (mode == theOther.mode && smoothness == theOther.smoothness &&\n            maxerror == theOther.maxerror);\n  }\n\n  bool operator<(const BezierSettings &theOther) const\n  {\n    if (mode != theOther.mode)\n      return (mode < theOther.mode);\n    if (smoothness != theOther.smoothness)\n      return (smoothness < theOther.smoothness);\n    return (maxerror < theOther.maxerror);\n  }\n\n  string name;\n  string mode;\n  double smoothness;\n  double maxerror;\n};\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Global replace within a string\n *\n * \\param theString The string in which to replace\n * \\param theMatch The original string\n * \\param theReplacement The replacement string\n */\n// ----------------------------------------------------------------------\n\nvoid replace(string &theString, const string &theMatch, const string &theReplacement)\n{\n  string::size_type pos;\n\n  while ((pos = theString.find(theMatch)) != string::npos)\n  {\n    theString.replace(pos, theMatch.size(), theReplacement);\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Create unique name for a contour\n *\n * \\param theIndex The unique ordinal of the contour\n * \\return The unique name\n */\n// ----------------------------------------------------------------------\n\nstring ContourName(unsigned long theIndex)\n{\n  return (\"% shape2ps: path \" + lexical_cast<string>(theIndex) + \" place holder\");\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Convert local time to UTC time using current TZ\n *\n * \\param theLocalTime The local time\n * \\return The UTC time\n *\n * \\note This was stolen from textgen library TimeTools namespace\n */\n// ----------------------------------------------------------------------\n\nNFmiTime toutctime(const NFmiTime &theLocalTime)\n{\n  ::tm tlocal;\n  tlocal.tm_sec = theLocalTime.GetSec();\n  tlocal.tm_min = theLocalTime.GetMin();\n  tlocal.tm_hour = theLocalTime.GetHour();\n  tlocal.tm_mday = theLocalTime.GetDay();\n  tlocal.tm_mon = theLocalTime.GetMonth() - 1;\n  tlocal.tm_year = theLocalTime.GetYear() - 1900;\n  tlocal.tm_wday = -1;\n  tlocal.tm_yday = -1;\n  tlocal.tm_isdst = -1;\n\n  ::time_t tsec = mktime(&tlocal);\n\n  ::tm *tutc = ::gmtime(&tsec);\n\n  NFmiTime out(tutc->tm_year + 1900,\n               tutc->tm_mon + 1,\n               tutc->tm_mday,\n               tutc->tm_hour,\n               tutc->tm_min,\n               tutc->tm_sec);\n\n  return out;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Convert path to PostScript path\n */\n// ----------------------------------------------------------------------\n\nstring pathtostring(const Imagine::NFmiPath &thePath,\n                    const NFmiArea &theArea,\n                    double theClipMargin,\n                    const string &theMoveto,\n                    const string &theLineto,\n                    const string &theClosepath = \"\")\n{\n  const Imagine::NFmiPathData::const_iterator begin = thePath.Elements().begin();\n  const Imagine::NFmiPathData::const_iterator end = thePath.Elements().end();\n\n  string out;\n\n  Polyline polyline;\n  for (Imagine::NFmiPathData::const_iterator iter = begin; iter != end;)\n  {\n    double X = (*iter).X();\n    double Y = theArea.Bottom() - ((*iter).Y() - theArea.Top());\n\n    X = std::min(X, clamp_limit);\n    Y = std::min(Y, clamp_limit);\n    X = std::max(X, -clamp_limit);\n    Y = std::max(Y, -clamp_limit);\n\n    if ((*iter).Oper() == Imagine::kFmiMoveTo || (*iter).Oper() == Imagine::kFmiLineTo ||\n        (*iter).Oper() == Imagine::kFmiGhostLineTo)\n      polyline.add(X, Y);\n    else\n      throw runtime_error(\"Only moveto and lineto commands are supported in paths\");\n\n    // Advance to next point. If end or moveto, flush previous polyline out\n    ++iter;\n    if (!polyline.empty() && (iter == end || (*iter).Oper() == Imagine::kFmiMoveTo))\n    {\n      polyline.clip(\n          theArea.Left(), theArea.Top(), theArea.Right(), theArea.Bottom(), theClipMargin);\n      if (!polyline.empty())\n        out += polyline.path(theMoveto, theLineto, theClosepath);\n      polyline.clear();\n    }\n  }\n\n  return out;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Convert path to PostScript path\n */\n// ----------------------------------------------------------------------\n\nstring pathtostring(const Imagine::NFmiPath &thePath,\n                    const NFmiArea &theArea,\n                    double theClipMargin,\n                    const string &theMoveto,\n                    const string &theLineto,\n                    const string &theCurveto,\n                    const string &theClosepath)\n{\n  Imagine::NFmiPath path =\n      thePath.Clip(theArea.Left(), theArea.Top(), theArea.Right(), theArea.Bottom(), theClipMargin);\n\n  const Imagine::NFmiPathData::const_iterator begin = path.Elements().begin();\n  const Imagine::NFmiPathData::const_iterator end = path.Elements().end();\n\n  ostringstream out;\n\n  unsigned int cubic_count = 0;\n\n  for (Imagine::NFmiPathData::const_iterator iter = begin; iter != end; ++iter)\n  {\n    double X = iter->X();\n    double Y = theArea.Bottom() - (iter->Y() - theArea.Top());\n\n    X = std::min(X, clamp_limit);\n    Y = std::min(Y, clamp_limit);\n    X = std::max(X, -clamp_limit);\n    Y = std::max(Y, -clamp_limit);\n\n    out << X << ' ' << Y << ' ';\n\n    switch (iter->Oper())\n    {\n      case Imagine::kFmiMoveTo:\n        out << theMoveto << endl;\n        cubic_count = 0;\n        break;\n      case Imagine::kFmiLineTo:\n      case Imagine::kFmiGhostLineTo:\n        out << theLineto << endl;\n        cubic_count = 0;\n        break;\n      case Imagine::kFmiCubicTo:\n        ++cubic_count;\n        if (cubic_count % 3 == 0)\n          out << theCurveto << endl;\n        break;\n      case Imagine::kFmiConicTo:\n        throw runtime_error(\"Conic segments not supported\");\n    }\n  }\n\n  return out.str();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set queryinfo level\n *\n * A negative level value implies the first level in the data\n *\n * \\param theInfo The queryinfo\n * \\param theLevel The level value\n */\n// ----------------------------------------------------------------------\n\nvoid set_level(NFmiFastQueryInfo &theInfo, int theLevel)\n{\n  if (theLevel < 0)\n    theInfo.FirstLevel();\n  else\n  {\n    for (theInfo.ResetLevel(); theInfo.NextLevel();)\n      if (theInfo.Level()->LevelValue() == static_cast<unsigned int>(theLevel))\n        return;\n    throw runtime_error(\"Level value \" + NFmiStringTools::Convert(theLevel) + \" is not available\");\n  }\n}\n\n// ----------------------------------------------------------------------\n// The main driver\n// ----------------------------------------------------------------------\n\nint domain(int argc, const char *argv[])\n{\n  bool verbose = false;\n\n  NFmiCmdLine cmdline(argc, argv, \"v\");\n\n  if (cmdline.NumberofParameters() != 1)\n    throw runtime_error(\"Usage: shape2ps [options] <filename>\");\n\n  if (cmdline.Status().IsError())\n    throw runtime_error(cmdline.Status().ErrorLog().CharPtr());\n\n  if (cmdline.isOption('v'))\n    verbose = true;\n\n  string scriptfile = cmdline.Parameter(1);\n\n  // Open the script file\n\n  const bool strip_pound = false;\n  NFmiPreProcessor processor(strip_pound);\n  processor.SetIncluding(\"include\", \"\", \"\");\n  processor.SetDefine(\"#define\");\n  if (!processor.ReadAndStripFile(scriptfile))\n    throw runtime_error(\"Error: \" + processor.GetMessage());\n\n  string text = processor.GetString();\n  istringstream script(text);\n\n  // The area specification is not given yet\n  boost::shared_ptr<NFmiArea> theArea;\n\n  // The querydata is not given yet\n  string theQueryDataName;\n  NFmiStreamQueryData theQueryData;\n\n  // The querydata parameter is not given yet\n  string theParameterName;\n  FmiParameterName theParameter = kFmiBadParameter;\n\n  // The level is not given yet - use first level\n  int theLevel = -1;\n\n  // The time mode is by default local time\n  bool theLocalTimeMode = true;\n\n  // The time offset has not been given yet\n  string theTimeOrigin = \"now\";\n  int theDay = -1;\n  int theHour = -1;\n\n  // Contouring movement command names\n\n  string theMovetoCommand = \"moveto\";\n  string theLinetoCommand = \"lineto\";\n  string theCurvetoCommand = \"curveto\";\n  string theClosepathCommand = \"closepath\";\n\n  // Bezier smoothing\n  string theBezierMode = \"none\";\n  double theBezierSmoothness = 0.5;\n  double theBezierMaxError = 1.0;\n\n  // Smoothing\n\n  string theSmoother = \"None\";\n  double theSmootherRadius = 10;\n  int theSmootherFactor = 5;\n\n  // The calculated contours before Bezier fitting, and set of all\n  // different combinatins of Bezier parameters used in the script\n\n  typedef list<pair<BezierSettings, Imagine::NFmiPath>> Contours;\n  Contours theContours;\n  set<BezierSettings> theContourSettings;\n\n  // No clipping margin given yet\n  double theClipMargin = 0.0;\n\n  // Not in the body yet\n  bool body = false;\n\n  // Prepare the location finder for \"location\" token\n\n  string coordfile = NFmiSettings::Optional<string>(\"qdpoint::coordinates_file\", \"default.txt\");\n  string coordpath = NFmiSettings::Optional<string>(\"qdpoint::coordinates_path\", \".\");\n\n  NFmiLocationFinder locfinder;\n  locfinder.AddFile(NFmiFileSystem::FileComplete(coordfile, coordpath), false);\n\n  // We try to cache the matrices for best speed.\n  // Some tokens will invalidate the matrices\n\n  unique_ptr<NFmiDataMatrix<float>> values;\n  unique_ptr<Fmi::CoordinateMatrix> coords;\n\n  // Do the deed\n  string token;\n  ostringstream buffer;\n\n  while (script >> token)\n  {\n    // ------------------------------------------------------------\n    // Handle script comments\n    // ------------------------------------------------------------\n    if (token == \"#\")\n      script.ignore(1000000, '\\n');\n\n    // ------------------------------------------------------------\n    // Handle PostScript comments\n    // ------------------------------------------------------------\n    else if (token == \"%\")\n    {\n      getline(script, token);\n      buffer << '%' << token << endl;\n    }\n\n    // ------------------------------------------------------------\n    // Handle the clipmargin command\n    // ------------------------------------------------------------\n    else if (token == \"clipmargin\")\n      script >> theClipMargin;\n\n    // ------------------------------------------------------------\n    // Handle the area command\n    // ------------------------------------------------------------\n    else if (token == \"area\")\n    {\n      cerr << \"Warning: The area command is deprecated, use projection command \"\n              \"instead\"\n           << endl;\n\n      // Invalidate coordinate matrix\n      coords.reset(0);\n\n      if (theArea.get())\n        throw runtime_error(\"Area given twice\");\n\n      unsigned long classID;\n      string className;\n      script >> classID >> className;\n      theArea.reset(static_cast<NFmiArea *>(CreateSaveBase(classID)));\n      if (!theArea.get())\n        throw runtime_error(\"Unrecognized area in the script\");\n\n      script >> *theArea;\n\n      // Now handle XY limits\n\n      double x1 = theArea->Left();\n      double x2 = theArea->Right();\n      double y1 = theArea->Top();\n      double y2 = theArea->Bottom();\n\n      if (x2 - x1 == 1 && y2 - y1 == 1)\n        throw runtime_error(\"Error: No decent XY-area given in projection\");\n      // Recalculate x-range from y-range if necessary\n      if (x2 - x1 == 1)\n      {\n        x1 = 0;\n        x2 = (y2 - y1) * theArea->WorldXYAspectRatio();\n        theArea->SetXYArea(NFmiRect(x1, y2, x2, y1));\n      }\n      // Recalculate y-range from x-range if necessary\n      if (y2 - y1 == 1)\n      {\n        y1 = 0;\n        y2 = (x2 - x1) / theArea->WorldXYAspectRatio();\n        theArea->SetXYArea(NFmiRect(x1, y2, x2, y1));\n      }\n    }\n\n    // ------------------------------------------------------------\n    // Handle the projectioncenter command\n    // ------------------------------------------------------------\n\n    else if (token == \"projectioncenter\")\n    {\n      cerr << \"Warning: The projectioncenter command is deprecated, use \"\n              \"projection command instead\"\n           << endl;\n\n      coords.reset(0);\n\n      if (!theArea.get())\n        throw runtime_error(\n            \"projectioncenter must be used after a projection \"\n            \"has been specified\");\n\n      float lon, lat, scale;\n      script >> lon >> lat >> scale;\n\n      NFmiPoint center(lon, lat);\n      double x1 = theArea->Left();\n      double x2 = theArea->Right();\n      double y1 = theArea->Top();\n      double y2 = theArea->Bottom();\n\n      // Projektiolaskuja varten\n      theArea.reset(theArea->NewArea(center, center));\n\n      NFmiPoint c = theArea->LatLonToWorldXY(center);\n\n      NFmiPoint bl(c.X() - scale * 1000 * (x2 - x1), c.Y() - scale * 1000 * (y2 - y1));\n      NFmiPoint tr(c.X() + scale * 1000 * (x2 - x1), c.Y() + scale * 1000 * (y2 - y1));\n      NFmiPoint bottomleft = theArea->WorldXYToLatLon(bl);\n      NFmiPoint topright = theArea->WorldXYToLatLon(tr);\n      theArea.reset(theArea->NewArea(bottomleft, topright));\n\n      if (verbose)\n      {\n        cerr << \"Calculated new area to be\" << endl << *theArea << endl;\n      }\n    }\n\n    // ------------------------------------------------------------\n    // Handle the projection command\n    // ------------------------------------------------------------\n\n    else if (token == \"projection\")\n    {\n      // Invalidate coordinate matrix\n      coords.reset(0);\n\n      if (theArea.get())\n        throw runtime_error(\"Projection given twice\");\n\n      string specs;\n      script >> specs;\n      theArea = NFmiAreaFactory::Create(specs);\n\n      // Now handle XY limits\n\n      double x1 = theArea->Left();\n      double x2 = theArea->Right();\n      double y1 = theArea->Top();\n      double y2 = theArea->Bottom();\n\n      if (x2 - x1 == 1 && y2 - y1 == 1)\n        throw runtime_error(\"Error: No decent XY-area given in projection\");\n      // Recalculate x-range from y-range if necessary\n      if (x2 - x1 == 1)\n      {\n        x1 = 0;\n        x2 = (y2 - y1) * theArea->WorldXYAspectRatio();\n        theArea->SetXYArea(NFmiRect(x1, y2, x2, y1));\n      }\n      // Recalculate y-range from x-range if necessary\n      if (y2 - y1 == 1)\n      {\n        y1 = 0;\n        y2 = (x2 - x1) / theArea->WorldXYAspectRatio();\n        theArea->SetXYArea(NFmiRect(x1, y2, x2, y1));\n      }\n\n      if (verbose)\n      {\n        cerr << \"The new projection is\" << endl << *theArea << endl;\n      }\n    }\n\n    // ------------------------------------------------------------\n    // Handle the body command\n    // ------------------------------------------------------------\n    else if (token == \"body\")\n    {\n      if (body)\n        throw runtime_error(\"body command given twice in script\");\n\n      if (!theArea.get())\n        throw runtime_error(\"No area specified before body\");\n\n      body = true;\n\n      // Output the header, then the buffer, then the beginning of body\n\n      string tmp = buffer.str();\n      buffer.str(\"\");\n\n      buffer << \"%!PS-Adobe-3.0 EPSF-3.0\" << endl\n             << \"%%Creator: shape2ps\" << endl\n             << \"%%Pages: 1\" << endl\n             << \"%%BoundingBox: \" << static_cast<int>(theArea->Left()) << \" \"\n             << static_cast<int>(theArea->Top()) << \" \" << static_cast<int>(theArea->Right()) << \" \"\n             << static_cast<int>(theArea->Bottom()) << endl\n             << \"%%EndComments\" << endl\n             << \"%%BeginProcSet: shape2ps\" << endl\n             << \"save /mysave exch def\" << endl\n             << \"/mydict 1000 dict def\" << endl\n             << \"mydict begin\" << endl\n             << \"/e2{2 index exec}def\" << endl\n             << \"/e3{3 index exec}def\" << endl\n             << tmp << endl\n             << \"end\" << endl\n             << \"%%EndProcSet\" << endl\n             << \"%%EndProlog\" << endl\n             << \"%%Page: 1 1\" << endl\n             << \"%%BeginPageSetup\" << endl\n             << \"mydict begin\" << endl\n             << \"%%EndPageSetup\" << endl\n             << \"gsave \" << static_cast<int>(theArea->Left()) << \" \"\n             << static_cast<int>(theArea->Top()) << \" \" << static_cast<int>(theArea->Right()) << \" \"\n             << static_cast<int>(theArea->Bottom()) << \" rectclip newpath\" << endl;\n    }\n\n    // ----------------------------------------------------------------------\n    // Handle a boundingbox command\n    // ----------------------------------------------------------------------\n\n    else if (token == \"boundingbox\")\n    {\n      if (!theArea.get())\n        throw runtime_error(\"Using boundingbox before area\");\n\n      buffer << static_cast<int>(theArea->Left()) << \" \" << static_cast<int>(theArea->Bottom())\n             << \" moveto \" << static_cast<int>(theArea->Left()) << \" \"\n             << static_cast<int>(theArea->Top()) << \" lineto \" << static_cast<int>(theArea->Right())\n             << \" \" << static_cast<int>(theArea->Top()) << \" lineto \"\n             << static_cast<int>(theArea->Right()) << \" \" << static_cast<int>(theArea->Bottom())\n             << \" lineto closepath\" << endl;\n    }\n\n    // ------------------------------------------------------------\n    // Handle a project command\n    // ------------------------------------------------------------\n\n    else if (token == \"project\")\n    {\n      if (!theArea.get())\n        throw runtime_error(\"Using project before area\");\n\n      double x, y;\n      script >> x >> y;\n      NFmiPoint pt = theArea->ToXY(NFmiPoint(x, y));\n      buffer << static_cast<char *>(NFmiValueString(pt.X())) << ' '\n             << static_cast<char *>(NFmiValueString(theArea->Bottom() - (pt.Y() - theArea->Top())))\n             << ' ';\n    }\n\n    // ------------------------------------------------------------\n    // Handle a location command\n    // ------------------------------------------------------------\n\n    else if (token == \"location\")\n    {\n      if (!theArea.get())\n        throw runtime_error(\"Using location before area\");\n\n      string placename;\n      script >> placename;\n\n      NFmiPoint lonlat = locfinder.Find(placename);\n      if (locfinder.LastSearchFailed())\n        throw runtime_error(\"Location \" + placename + \" is not in the database\");\n\n      NFmiPoint pt = theArea->ToXY(lonlat);\n      buffer << static_cast<char *>(NFmiValueString(pt.X())) << ' '\n             << static_cast<char *>(NFmiValueString(theArea->Bottom() - (pt.Y() - theArea->Top())))\n             << ' ';\n    }\n\n    // ------------------------------------------------------------\n    // Handle a system command\n    // ------------------------------------------------------------\n\n    else if (token == \"system\")\n    {\n      if (!body)\n        throw runtime_error(\"system command does not work in the header\");\n\n      getline(script, token);\n      buffer << \"% \" << token << endl;\n      ::system(token.c_str());\n    }\n\n    // ------------------------------------------------------------\n    // Handle the shape and exec commands\n    // ------------------------------------------------------------\n    else if (token == \"shape\" || token == \"subshape\" || token == \"exec\")\n    {\n      if (!body)\n        throw runtime_error(\"Cannot have \" + token + \" command in header\");\n\n      string moveto, lineto, closepath;\n      if (token == \"shape\" || token == \"subshape\")\n        script >> moveto >> lineto >> closepath;\n\n      string shapefile, condition;\n\n      if (token == \"subshape\")\n        script >> condition;\n\n      script >> shapefile;\n\n      buffer << \"% \";\n      buffer << token;\n      buffer << ' ';\n      buffer << shapefile;\n      buffer << endl;\n\n      // Read the shape, project and get as path\n      try\n      {\n        Imagine::NFmiGeoShape geo(shapefile, Imagine::kFmiGeoShapeEsri, condition);\n        // geo.ProjectXY(*theArea);\n\n#ifdef WGS84\n        Imagine::NFmiPath path = geo.Path();\n#else\n        Imagine::NFmiPath path = geo.Path().PacificView(theArea->PacificView());\n#endif\n\n        path.Project(theArea.get());\n\n        if (token == \"shape\" || token == \"subshape\")\n          buffer << pathtostring(path, *theArea, theClipMargin, moveto, lineto, closepath);\n        else\n          buffer << pathtostring(path, *theArea, theClipMargin, \"e3\", \"e2\");\n        if (token == \"exec\")\n          buffer << \"pop pop\" << endl;\n      }\n      catch (std::exception &e)\n      {\n        if (token != \"shape\")\n          throw e;\n        string msg = \"Failed at command shape \";\n        msg += moveto + ' ';\n        msg += lineto + ' ';\n        msg += closepath + ' ';\n        msg += shapefile;\n        msg += \" : \";\n        msg += e.what();\n        throw runtime_error(msg);\n      }\n    }\n\n    // ------------------------------------------------------------\n    // Handle the qdexec command\n    // ------------------------------------------------------------\n\n    else if (token == \"qdexec\")\n    {\n      if (!body)\n        throw runtime_error(\"Cannot have \" + token + \" command in header\");\n\n      if (!theArea.get())\n        throw runtime_error(\"Using qdexec before projection specified\");\n\n      string queryfile;\n      script >> queryfile;\n      buffer << \"% \" << token << ' ' << queryfile << endl;\n\n      NFmiStreamQueryData qd;\n      qd.SafeReadLatestData(queryfile);\n      NFmiFastQueryInfo *qi = qd.QueryInfoIter();\n      qi->First();\n\n      for (qi->ResetLocation(); qi->NextLocation();)\n      {\n        const NFmiPoint lonlat = qi->LatLon();\n        const NFmiPoint pt = theArea->ToXY(lonlat);\n        buffer << static_cast<char *>(NFmiValueString(pt.X())) << ' '\n               << static_cast<char *>(\n                      NFmiValueString(theArea->Bottom() - (pt.Y() - theArea->Top())))\n               << \" e2\" << endl;\n      }\n      buffer << \"pop\" << endl;\n    }\n\n    // ------------------------------------------------------------\n    // Handle the gshhs command\n    // ------------------------------------------------------------\n\n    else if (token == \"gshhs\")\n    {\n      if (!body)\n        throw runtime_error(\"Cannot have \" + token + \" command in header\");\n\n      string moveto, lineto, closepath;\n      script >> moveto >> lineto >> closepath;\n\n      string gshhsfile;\n      script >> gshhsfile;\n\n      buffer << \"% \" << token << ' ' << gshhsfile << endl;\n\n      // Read the gshhs, project and get as path\n      try\n      {\n        double minlon, minlat, maxlon, maxlat;\n        NFmiAreaTools::LatLonBoundingBox(*theArea, minlon, minlat, maxlon, maxlat);\n\n        Imagine::NFmiPath path =\n            Imagine::NFmiGshhsTools::ReadPath(gshhsfile, minlon, minlat, maxlon, maxlat);\n\n        path.Project(theArea.get());\n\n        buffer << pathtostring(path, *theArea, theClipMargin, moveto, lineto, closepath);\n      }\n      catch (std::exception &e)\n      {\n        string msg = \"Failed at command gshhs \";\n        msg += moveto + ' ';\n        msg += lineto + ' ';\n        msg += closepath + ' ';\n        msg += gshhsfile;\n        msg += \" due to \";\n        msg += e.what();\n        throw runtime_error(e.what());\n      }\n    }\n\n    // ------------------------------------------------------------\n    // Handle the graticule <moveto> <lineto> <lon1> <lon2> <dx> <lat1> <lat2>\n    // <dy> command\n    // ------------------------------------------------------------\n\n    else if (token == \"graticule\")\n    {\n      if (!body)\n        throw runtime_error(\"Cannot have \" + token + \" command in header\");\n\n      string moveto, lineto;\n      script >> moveto >> lineto;\n\n      double lon1, lon2, dx, lat1, lat2, dy;\n      script >> lon1 >> lon2 >> dx >> lat1 >> lat2 >> dy;\n\n      if (lon1 > lon2)\n        throw runtime_error(\"Graticule lon1>lon2\");\n      if (lat1 > lat2)\n        throw runtime_error(\"Graticule lat1>lat2\");\n      if (dx <= 0)\n        throw runtime_error(\"Graticule dx<=0\");\n      if (dy <= 0)\n        throw runtime_error(\"Graticule dy<=0\");\n\n      buffer << \"% graticule \" << lon1 << ' ' << lon2 << ' ' << dx << ' ' << lat1 << ' ' << lat2\n             << ' ' << dy << endl;\n\n      Imagine::NFmiPath path;\n\n      for (double x = lon1; x <= lon2; x += dx)\n        for (double y = lat1; y <= lat2; y += dy)\n        {\n          if (y == lat1)\n            path.MoveTo(x, y);\n          else\n            path.LineTo(x, y);\n        }\n\n      for (double y = lat1; y <= lat2; y += dy)\n        for (double x = lon1; x <= lon2; x += dx)\n        {\n          if (x == lon1)\n            path.MoveTo(x, y);\n          else\n            path.LineTo(x, y);\n        }\n\n      path.Project(theArea.get());\n\n      buffer << pathtostring(path, *theArea, theClipMargin, moveto, lineto, \"closepath\");\n    }\n\n    // ------------------------------------------------------------\n    // Handle the querydata <filename> command\n    // ------------------------------------------------------------\n\n    else if (token == \"querydata\")\n    {\n      coords.reset(0);\n      values.reset(0);\n      script >> theQueryDataName;\n      if (!theQueryData.SafeReadLatestData(theQueryDataName))\n        throw runtime_error(\"Failed to read querydata from \" + theQueryDataName);\n    }\n\n    // ------------------------------------------------------------\n    // Handle the parameter <name> command\n    // ----------------------------------------------------------------------\n\n    else if (token == \"parameter\")\n    {\n      values.reset(0);\n      script >> theParameterName;\n      NFmiEnumConverter converter;\n      theParameter = FmiParameterName(converter.ToEnum(theParameterName));\n      if (theParameter == kFmiBadParameter)\n        throw runtime_error(\"Parameter name \" + theParameterName + \" is not recognized by newbase\");\n    }\n\n    // ------------------------------------------------------------\n    // Handle the level <levelvalue> command\n    // ----------------------------------------------------------------------\n\n    else if (token == \"level\")\n    {\n      values.reset(0);\n      script >> theLevel;\n    }\n\n    // ------------------------------------------------------------\n    // Handle the timemode <local|utc> command\n    // ------------------------------------------------------------\n\n    else if (token == \"timemode\")\n    {\n      values.reset(0);\n      string name;\n      script >> name;\n      if (name == \"local\")\n        theLocalTimeMode = true;\n      else if (name == \"utc\")\n        theLocalTimeMode = false;\n      else\n        throw runtime_error(\"Unrecognized time mode \" + name +\n                            \", the name must be 'local' or 'utc'\");\n    }\n\n    // ------------------------------------------------------------\n    // Handle the time <day> <hour> command\n    // ------------------------------------------------------------\n\n    else if (token == \"time\")\n    {\n      values.reset(0);\n      script >> theTimeOrigin >> theDay >> theHour;\n      if (theTimeOrigin != \"now\" && theTimeOrigin != \"origintime\" && theTimeOrigin != \"firsttime\")\n        throw runtime_error(\"Time mode \" + theTimeOrigin + \" is not recognized\");\n      if (theDay < 0)\n        throw runtime_error(\"First argument of time-command must be nonnegative\");\n      if (theHour < 0 || theHour > 24)\n        throw runtime_error(\"Second argument of time-command must be in range 0-23\");\n    }\n\n    // ------------------------------------------------------------\n    // Handle the bezier command\n    // ------------------------------------------------------------\n\n    else if (token == \"bezier\")\n    {\n      script >> theBezierMode;\n      if (theBezierMode == \"none\")\n        ;\n      else if (theBezierMode == \"cardinal\")\n        script >> theBezierSmoothness;\n      else if (theBezierMode == \"approximate\")\n        script >> theBezierMaxError;\n      else if (theBezierMode == \"tight\")\n        script >> theBezierMaxError;\n      else\n        throw runtime_error(\"Bezier mode \" + theBezierMode + \" is not recognized\");\n    }\n\n    // ------------------------------------------------------------\n    // Handle the smoother command\n    // ------------------------------------------------------------\n\n    else if (token == \"smoother\")\n    {\n      values.reset(0);\n      script >> theSmoother;\n      if (theSmoother != \"None\")\n        script >> theSmootherFactor >> theSmootherRadius;\n      if (NFmiSmoother::SmootherValue(theSmoother) == NFmiSmoother::kFmiSmootherMissing)\n        throw runtime_error(\"Smoother mode \" + theSmoother + \" is not recognized\");\n    }\n\n    // ------------------------------------------------------------\n    // Handle the contourcommands <moveto> <lineto>  <curveto> <closepath>\n    // command\n    // ------------------------------------------------------------\n\n    else if (token == \"contourcommands\")\n    {\n      script >> theMovetoCommand >> theLinetoCommand >> theCurvetoCommand >> theClosepathCommand;\n    }\n\n    // ----------------------------------------------------------------------\n    // Handle the windarrows <dx> <dy> command\n    // ----------------------------------------------------------------------\n\n    else if (token == \"windarrows\")\n    {\n      if (!body)\n        throw runtime_error(token + \" command is not allowed in the header\");\n\n      int dx, dy;\n      script >> dx >> dy;\n\n      NFmiFastQueryInfo *q = theQueryData.QueryInfoIter();\n      if (q == 0)\n        throw runtime_error(\"querydata must be specified before using any windarrows commands\");\n      if (!q->Param(kFmiWindDirection))\n        throw runtime_error(\"parameter WindDirection is not available in \" + theQueryDataName);\n\n      if (theDay < 0 || theHour < 0)\n        throw runtime_error(\"time must be specified before using any contouring commands\");\n\n      // Try to set the proper level on\n      set_level(*q, theLevel);\n\n      // Try to set the proper time on\n\n      NFmiTime t;\n      t.SetMin(0);\n      t.SetSec(0);\n      if (theTimeOrigin == \"now\")\n      {\n        t.ChangeByDays(theDay);\n        t.SetHour(theHour);\n      }\n      if (theTimeOrigin == \"origintime\")\n      {\n        t = q->OriginTime();\n        t.ChangeByDays(theDay);\n        t.ChangeByHours(theHour);\n      }\n      else if (theTimeOrigin == \"firsttime\")\n      {\n        q->FirstTime();\n        t = q->ValidTime();\n        t.ChangeByDays(theDay);\n        t.ChangeByHours(theHour);\n      }\n\n      // Get the data to be contoured\n\n      if (coords.get() == 0)\n        coords.reset(new Fmi::CoordinateMatrix(q->LocationsXY(*theArea)));\n\n      values.reset(new NFmiDataMatrix<float>(q->Values(t)));\n\n      // Loop through the data and render arrows\n\n      for (unsigned int j = 0; j < values->NY(); j += dy)\n        for (unsigned int i = 0; i < values->NX(); i += dx)\n        {\n          float wdir = (*values)[i][j];\n          NFmiPoint xy = (*coords)(i, j);\n\n          double x = xy.X();\n          double y = theArea->Bottom() - (xy.Y() - theArea->Top());\n\n          if ((x > theArea->Left() && x < theArea->Right()) ||\n              (y > theArea->Top() && y < theArea->Bottom()))\n          {\n            buffer << wdir << ' ' << x << ' ' << y << ' ' << \" windarrow\" << endl;\n          }\n        }\n    }\n\n    // ------------------------------------------------------------\n    // Handle the contourline <value> command\n    // Handle the contourfill <lolimit> <hilimit> command\n    // ------------------------------------------------------------\n\n    else if (token == \"contourline\" || token == \"contourfill\")\n    {\n      if (!body)\n        throw runtime_error(token + \" command is not allowed in the header\");\n\n      NFmiFastQueryInfo *q = theQueryData.QueryInfoIter();\n      if (q == 0)\n        throw runtime_error(\"querydata must be specified before using any contouring commands\");\n\n      if (theParameter == kFmiBadParameter)\n        throw runtime_error(\"parameter must be specified before using any contouring commands\");\n\n      if (!q->Param(theParameter))\n        throw runtime_error(\"parameter \" + theParameterName + \" is not available in \" +\n                            theQueryDataName);\n\n      // Try to set the proper level on\n      set_level(*q, theLevel);\n\n      if (theDay < 0 || theHour < 0)\n        throw runtime_error(\"time must be specified before using any contouring commands\");\n\n      // Try to set the proper time on\n\n      NFmiTime t;\n      t.SetMin(0);\n      t.SetSec(0);\n      if (theTimeOrigin == \"now\")\n      {\n        t.ChangeByDays(theDay);\n        t.SetHour(theHour);\n      }\n      if (theTimeOrigin == \"origintime\")\n      {\n        t = q->OriginTime();\n        t.ChangeByDays(theDay);\n        t.ChangeByHours(theHour);\n      }\n      else if (theTimeOrigin == \"firsttime\")\n      {\n        q->FirstTime();\n        t = q->ValidTime();\n        t.ChangeByDays(theDay);\n        t.ChangeByHours(theHour);\n      }\n\n      if (theLocalTimeMode)\n        t = toutctime(t);\n\n      cerr << \"Time = \" << t << endl;\n\n      float lolimit, hilimit;\n      if (token == \"contourline\")\n      {\n        script >> lolimit;\n        hilimit = kFloatMissing;\n      }\n      else\n      {\n        script >> lolimit >> hilimit;\n        if (lolimit != kFloatMissing && hilimit != kFloatMissing && lolimit >= hilimit)\n          throw runtime_error(\n              \"contourfill first argument must be smaller than \"\n              \"second argument\");\n      }\n\n      // Get the data to be contoured\n\n      if (coords.get() == 0)\n      {\n        coords.reset(new Fmi::CoordinateMatrix(q->LocationsXY(*theArea)));\n      }\n\n      if (values.get() == 0)\n      {\n        values.reset(new NFmiDataMatrix<float>(q->Values(t)));\n\n        if (theSmoother != \"None\")\n        {\n          NFmiSmoother smoother(theSmoother, theSmootherFactor, theSmootherRadius);\n          *values = smoother.Smoothen(*coords, *values);\n        }\n      }\n\n      Imagine::NFmiContourTree tree(lolimit, hilimit);\n      if (token == \"contourline\")\n        tree.LinesOnly(true);\n\n      tree.Contour(*coords, *values, Imagine::NFmiContourTree::kFmiContourLinear);\n\n      Imagine::NFmiPath path = tree.Path();\n\n      // We don't bother to store non-smoothed contours at all\n      if (theBezierMode == \"none\")\n      {\n        buffer << pathtostring(path,\n                               *theArea,\n                               theClipMargin,\n                               theMovetoCommand,\n                               theLinetoCommand,\n                               theCurvetoCommand,\n                               theClosepathCommand);\n      }\n      else\n      {\n        const string name = ContourName(theContours.size() + 1);\n        BezierSettings bset(name, theBezierMode, theBezierSmoothness, theBezierMaxError);\n        theContourSettings.insert(bset);\n        theContours.push_back(make_pair(bset, path));\n        buffer << name << endl;\n      }\n    }\n\n    // ------------------------------------------------------------\n    // Handle a regular PostScript token line\n    // ------------------------------------------------------------\n\n    else\n    {\n      buffer << token;\n      getline(script, token);\n      buffer << token << endl;\n    }\n  }\n\n  // The script finished\n\n  if (!body)\n  {\n    cerr << \"Error: There was no body in the script\" << endl;\n    return 1;\n  }\n\n  // End the clipping\n\n  buffer << \"grestore\" << endl;\n\n  // Fill in the contours\n\n  string output = buffer.str();\n\n  if (!theContours.empty())\n  {\n    for (set<BezierSettings>::const_iterator sit = theContourSettings.begin();\n         sit != theContourSettings.end();\n         ++sit)\n    {\n      list<string> names;\n      Imagine::NFmiBezierTools::NFmiPaths paths;\n      for (Contours::const_iterator it = theContours.begin(); it != theContours.end(); ++it)\n      {\n        if (*sit == it->first)\n        {\n          paths.push_back(it->second);\n          names.push_back(it->first.name);\n        }\n      }\n\n      Imagine::NFmiBezierTools::NFmiPaths outpaths;\n      if (sit->mode == \"cardinal\")\n        outpaths = Imagine::NFmiCardinalBezierFit::Fit(paths, sit->smoothness);\n      else if (sit->mode == \"approximate\")\n        outpaths = Imagine::NFmiApproximateBezierFit::Fit(paths, sit->maxerror);\n      else if (sit->mode == \"tight\")\n        outpaths = Imagine::NFmiTightBezierFit::Fit(paths, sit->maxerror);\n      else\n        throw runtime_error(\"Unknown Bezier mode \" + sit->mode + \" while fitting contours\");\n\n      list<string>::const_iterator nit = names.begin();\n      Imagine::NFmiBezierTools::NFmiPaths::const_iterator it = outpaths.begin();\n      for (; nit != names.end() && it != outpaths.end(); ++nit, ++it)\n      {\n        const string name = *nit;\n        const string path = pathtostring(*it,\n                                         *theArea,\n                                         theClipMargin,\n                                         theMovetoCommand,\n                                         theLinetoCommand,\n                                         theCurvetoCommand,\n                                         theClosepathCommand);\n        replace(output, name, path);\n      }\n    }\n  }\n\n  cout << output << \"end\" << endl\n       << \"%%Trailer\" << endl\n       << \"mysave restore\" << endl\n       << \"%%EOF\" << endl;\n\n  return 0;\n}\n\n// ----------------------------------------------------------------------\n// Main program.\n// ----------------------------------------------------------------------\n\nint main(int argc, const char *argv[])\n{\n  try\n  {\n    return domain(argc, argv);\n  }\n  catch (runtime_error &e)\n  {\n    cerr << \"Error: shape2ps failed due to\" << endl << \"--> \" << e.what() << endl;\n    return 1;\n  }\n  catch (...)\n  {\n    cerr << \"Error: shape2ps failed due to an unknown exception\" << endl;\n    return 1;\n  }\n}\n\n// ======================================================================\n", "meta": {"hexsha": "91b95435e263acac346fd8e95fc4831dec7b39ec", "size": 42097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main/shape2ps.cpp", "max_stars_repo_name": "fmidev/smartmet-shapetools", "max_stars_repo_head_hexsha": "8ca25d3a007af8582c2553c9f608ec18482ea0d4", "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/shape2ps.cpp", "max_issues_repo_name": "fmidev/smartmet-shapetools", "max_issues_repo_head_hexsha": "8ca25d3a007af8582c2553c9f608ec18482ea0d4", "max_issues_repo_licenses": ["MIT"], "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/shape2ps.cpp", "max_forks_repo_name": "fmidev/smartmet-shapetools", "max_forks_repo_head_hexsha": "8ca25d3a007af8582c2553c9f608ec18482ea0d4", "max_forks_repo_licenses": ["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.3922445936, "max_line_length": 100, "alphanum_fraction": 0.5182079483, "num_tokens": 9960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.17245463644425907}}
{"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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <limits>\n#include <string>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"tudat/basics/testMacros.h\"\n\n#include \"tudat/astro/ground_stations/pointingAnglesCalculator.h\"\n#include \"tudat/simulation/estimation.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace tudat::observation_models;\nusing namespace tudat::spice_interface;\nusing namespace tudat::ephemerides;\nusing namespace tudat::simulation_setup;\nusing namespace tudat::ground_stations;\nusing namespace tudat::unit_conversions;\n\nBOOST_AUTO_TEST_SUITE( test_observation_viability_calculators )\n\nBOOST_AUTO_TEST_CASE( testSeparateObservationViabilityCalculators )\n{\n\n    //Load spice kernels.\n    spice_interface::loadStandardSpiceKernels( );\n\n    // Create default Earth\n    std::vector< std::string > bodyNames = { \"Earth\" };\n    BodyListSettings bodySettings = getDefaultBodySettings(\n                bodyNames, \"Earth\", \"J2000\" );\n    SystemOfBodies bodies = createSystemOfBodies( bodySettings );\n\n    // Define ground station\n    double stationRadius = spice_interface::getAverageRadius( \"Earth\" );\n    double stationLatitude = convertDegreesToRadians( 20.0 );\n    double stationLongitude = convertDegreesToRadians( 50.0 );\n    createGroundStation( bodies.at( \"Earth\" ), \"Station\",\n                         ( Eigen::Vector3d( ) << stationRadius, stationLatitude, stationLongitude ).finished( ),\n                         coordinate_conversions::spherical_position );\n\n    // Get inertial ground station state function\n    std::function< Eigen::Vector6d( const double ) > groundStationStateFunction =\n            getLinkEndCompleteEphemerisFunction( std::make_pair( \"Earth\", \"Station\" ), bodies );\n\n    // Get Earth-fixed ground station position\n    Eigen::Vector3d earthFixedGroundStationState =\n            bodies.at( \"Earth\" )->getGroundStation( \"Station\" )->getNominalStationState( )->getCartesianStateInTime( 0.0 ).segment( 0, 3 );\n\n    // Define limiting elevation angle for test\n    double testAngle = 20.0 * mathematical_constants::PI / 180.0;\n\n    // Retrieve pointing angle calculator\n    std::shared_ptr< PointingAnglesCalculator > pointingAngleCalculator =\n            bodies.at( \"Earth\" )->getGroundStation( \"Station\" )->getPointingAnglesCalculator( );\n\n    // Define test body for occultation/avoidance tests\n    Eigen::Vector6d testBodyState = Eigen::Vector6d::Zero( );\n    testBodyState( 0 ) = 8000.0E3;\n    double testBodyRadius = 1000.0E3;\n\n    // Declare test variables\n    Eigen::Vector3d manualGroundStationInertialPosition;\n    Eigen::Vector3d vectorToTarget;\n    Eigen::Vector3d vectorToTestBody;\n    Eigen::Vector6d targetState = Eigen::Vector6d::Zero( );\n    Eigen::Vector6d groundStationState = Eigen::Vector6d::Zero( );\n    Eigen::Vector3d localVerticalVector = Eigen::Vector3d::UnitZ( );\n\n    // Run different test cases:\n    // 0: one-way uplink\n    // 1: one-way downlink\n    for( unsigned int i = 0; i < 2; i++ )\n    {\n        int targetIndex = -1;\n        int groundStationIndex = -1;\n        std::vector< std::pair< int, int > > linkEndIndices;\n        if( i == 0 )\n        {\n            targetIndex = 1;\n            groundStationIndex = 0;\n            linkEndIndices = { { 0, 1 } };\n        }\n        else if( i == 1 )\n        {\n            targetIndex = 0;\n            groundStationIndex = 1;\n            linkEndIndices = { { 1, 0 } };\n        }\n        std::shared_ptr< ObservationViabilityCalculator > minimumElevationCalculator =\n                std::make_shared< MinimumElevationAngleCalculator >(\n                    linkEndIndices, testAngle, pointingAngleCalculator );\n        std::shared_ptr< ObservationViabilityCalculator > bodyAvoidanceCalculator =\n                std::make_shared< BodyAvoidanceAngleCalculator >(\n                    linkEndIndices, testAngle, [=](const double){return testBodyState;}, \"TestBody\" );\n        std::shared_ptr< ObservationViabilityCalculator > bodyOccultationCalculator =\n                std::make_shared< OccultationCalculator >(\n                    linkEndIndices, [=](const double){return testBodyState;}, testBodyRadius );\n\n\n        std::vector< double > linkEndTimes;\n        linkEndTimes.resize( 2 );\n\n        std::vector< Eigen::Vector6d > linkEndStates;\n        linkEndStates.resize( 2 );\n\n        // Test viability settings for ~100 orbits\n        for( int j = 0; j < 20000; j++ )\n        {\n            // Set spacraft state in circular orbit (velocity not set)\n            targetState( 0 ) = std::sin( ( static_cast< double >( j ) / 200.0 ) * 2.0 * mathematical_constants::PI ) * 10000.0E3;\n            targetState( 2 ) = std::cos( ( static_cast< double >( j ) / 200.0 ) * 2.0 * mathematical_constants::PI ) * 10000.0E3;\n            // Set link end times (exagerated light time for testing purposes)\n            linkEndTimes[ 0 ] = 2.0 * 3600.0 * ( static_cast< double >( j ) / 200.0 );\n            linkEndTimes[ 1 ] = 2.0 * 3600.0 * ( static_cast< double >( j ) / 200.0 ) + 100.0;\n\n            linkEndStates[ groundStationIndex ] = groundStationStateFunction( linkEndTimes[ groundStationIndex ] );\n            linkEndStates[ targetIndex ] = targetState;\n\n            // Manually calculate elevation angle\n            manualGroundStationInertialPosition = spice_interface::computeRotationMatrixBetweenFrames(\n                        \"IAU_Earth\", \"J2000\", linkEndTimes[ groundStationIndex ] ) * earthFixedGroundStationState;\n            vectorToTarget = ( targetState.segment( 0, 3 ) - manualGroundStationInertialPosition );\n            vectorToTestBody = ( testBodyState.segment( 0, 3 ) - manualGroundStationInertialPosition );\n\n            // Test elevation angle\n            {\n                double manualElevationAngle = mathematical_constants::PI / 2.0 -\n                        std::acos( manualGroundStationInertialPosition.normalized( ).dot( vectorToTarget.normalized( ) ) );\n\n                // Compute viability and check against manual calculation\n                bool isObservationViable = minimumElevationCalculator->isObservationViable(\n                            linkEndStates, linkEndTimes );\n                if( manualElevationAngle > testAngle )\n                {\n                    BOOST_CHECK_EQUAL( isObservationViable, 1 );\n                }\n                else\n                {\n                    BOOST_CHECK_EQUAL( isObservationViable, 0 );\n                }\n            }\n\n            // Test avoidance angle\n            {\n                double manualAvoidanceAngle =\n                        std::acos( ( vectorToTestBody.normalized( ) ).dot( vectorToTarget.normalized( ) ) );\n\n                // Compute viability and check against manual calculation\n                bool isObservationViable = bodyAvoidanceCalculator->isObservationViable(\n                            linkEndStates, linkEndTimes );\n                if( manualAvoidanceAngle > testAngle )\n                {\n                    BOOST_CHECK_EQUAL( isObservationViable, 1 );\n                }\n                else\n                {\n                    BOOST_CHECK_EQUAL( isObservationViable, 0 );\n                }\n            }\n\n            // Test occultation\n            {\n\n                bool manualIsObservationViable = true;\n                if( mission_geometry::computeShadowFunction(\n                            manualGroundStationInertialPosition, 0.0,\n                            testBodyState.segment( 0, 3 ),\n                            testBodyRadius,\n                            targetState.segment( 0, 3 ) ) < 1.0E-10 )\n                {\n                    manualIsObservationViable = false;\n                }\n\n                // Compute viability and check against manual calculation\n                bool isObservationViable = bodyOccultationCalculator->isObservationViable(\n                            linkEndStates, linkEndTimes );\n                BOOST_CHECK_EQUAL( isObservationViable, manualIsObservationViable );\n            }\n        }\n    }\n}\n\n\n////! Test function to manually compute elevation angle(s) of observation link at given body\n//std::vector< double > getBodyLinkElevationAngles(\n//        const LinkEnds linkEnds,\n//        const ObservableType observableType,\n//        const std::string referenceBody,\n//        const std::vector< Eigen::Vector6d > linkEndStates,\n//        const std::vector< double > linkEndTimes,\n//        const SystemOfBodies& bodies )\n//{\n//    std::shared_ptr< ground_stations::PointingAnglesCalculator > currentPointingAnglesCalculator;\n//    std::vector< double > elevationAngles;\n//    switch( observableType )\n//    {\n//    case one_way_range:\n//    {\n//        if( linkEnds.at( transmitter ).first == referenceBody )\n//        {\n//            currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                        linkEnds.at( transmitter ).second )->getPointingAnglesCalculator( );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 1 ) - linkEndStates.at( 0 ) ).segment( 0, 3 ), linkEndTimes.at( 0 ) ) );\n\n//        }\n//        else if( linkEnds.at( receiver ).first == referenceBody )\n//        {\n//            currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                        linkEnds.at( receiver ).second )->getPointingAnglesCalculator( );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 0 ) - linkEndStates.at( 1 ) ).segment( 0, 3 ), linkEndTimes.at( 1 ) ) );\n//        }\n//        break;\n//    }\n//    case one_way_doppler:\n//    {\n//        if( linkEnds.at( transmitter ).first == referenceBody )\n//        {\n//            currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                        linkEnds.at( transmitter ).second )->getPointingAnglesCalculator( );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 1 ) - linkEndStates.at( 0 ) ).segment( 0, 3 ), linkEndTimes.at( 0 ) ) );\n\n//        }\n//        else if( linkEnds.at( receiver ).first == referenceBody )\n//        {\n//            currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                        linkEnds.at( receiver ).second )->getPointingAnglesCalculator( );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 0 ) - linkEndStates.at( 1 ) ).segment( 0, 3 ), linkEndTimes.at( 1 ) ) );\n//        }\n//        break;\n//    }\n//    case angular_position:\n//    {\n//        if( linkEnds.at( transmitter ).first == referenceBody )\n//        {\n//            currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                        linkEnds.at( transmitter ).second )->getPointingAnglesCalculator( );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 1 ) - linkEndStates.at( 0 ) ).segment( 0, 3 ), linkEndTimes.at( 0 ) ) );\n\n//        }\n//        else if( linkEnds.at( receiver ).first == referenceBody )\n//        {\n//            currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                        linkEnds.at( receiver ).second )->getPointingAnglesCalculator( );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 0 ) - linkEndStates.at( 1 ) ).segment( 0, 3 ), linkEndTimes.at( 1 ) ) );\n//        }\n//        break;\n//    }\n//    case one_way_differenced_range:\n//    {\n//        if( linkEnds.at( transmitter ).first == referenceBody )\n//        {\n//            currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                        linkEnds.at( transmitter ).second )->getPointingAnglesCalculator( );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 1 ) - linkEndStates.at( 0 ) ).segment( 0, 3 ), linkEndTimes.at( 0 ) ) );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 3 ) - linkEndStates.at( 2 ) ).segment( 0, 3 ), linkEndTimes.at( 2 ) ) );\n\n//        }\n//        else if( linkEnds.at( receiver ).first == referenceBody )\n//        {\n//            currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                        linkEnds.at( receiver ).second )->getPointingAnglesCalculator( );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 0 ) - linkEndStates.at( 1 ) ).segment( 0, 3 ), linkEndTimes.at( 1 ) ) );\n//            elevationAngles.push_back( currentPointingAnglesCalculator->calculateElevationAngle(\n//                                           ( linkEndStates.at( 2 ) - linkEndStates.at( 3 ) ).segment( 0, 3 ), linkEndTimes.at( 3 ) ) );\n//        }\n//        break;\n//    }\n//    case n_way_range:\n//    {\n//        int linkEndIndex = 0;\n//        for( LinkEnds::const_iterator linkEndIterator = linkEnds.begin( ); linkEndIterator != linkEnds.end( );\n//             linkEndIterator++ )\n//        {\n//            if( linkEndIterator->second.first == referenceBody )\n//            {\n//                currentPointingAnglesCalculator = bodies.at( referenceBody )->getGroundStation(\n//                            linkEndIterator->second.second )->getPointingAnglesCalculator( );\n//                if( linkEndIndex != 0 )\n//                {\n//                    elevationAngles.push_back(\n//                                currentPointingAnglesCalculator->calculateElevationAngle(\n//                                    ( linkEndStates.at( 2 * ( linkEndIndex - 1 ) ) -\n//                                      linkEndStates.at( 2 * ( linkEndIndex - 1 ) + 1 ) ).segment( 0, 3 ),\n//                                    linkEndTimes.at( 2 * ( linkEndIndex - 1 ) + 1 ) ) );\n//                }\n\n//                if( linkEndIndex != static_cast< int >( linkEnds.size( ) ) - 1 )\n//                {\n//                    elevationAngles.push_back(\n//                                currentPointingAnglesCalculator->calculateElevationAngle(\n//                                    ( linkEndStates.at( 2 * linkEndIndex + 1) -\n//                                      linkEndStates.at( 2 * linkEndIndex ) ).segment( 0, 3 ),\n//                                    linkEndTimes.at( 2 * linkEndIndex ) ) );\n//                }\n\n//            }\n//            linkEndIndex++;\n//        }\n//        break;\n//    }\n//    default:\n//        throw std::runtime_error( \"Error when testing elevation angle viability, observable not recognized\" );\n\n//    }\n\n//    return elevationAngles;\n//}\n\n////! Test function to manually compute body avoidance angle(s) of observation link at given body\n//std::vector< double > getBodyCosineAvoidanceAngles(\n//        const LinkEnds linkEnds,\n//        const ObservableType observableType,\n//        const std::string referenceBody,\n//        const std::string bodyToAvoid,\n//        const std::vector< Eigen::Vector6d > linkEndStates,\n//        const std::vector< double > linkEndTimes,\n//        const SystemOfBodies& bodies )\n//{\n//    std::vector< double > cosineAvoidanceAngles;\n//    switch( observableType )\n//    {\n//    case one_way_range:\n//    {\n//        if( linkEnds.at( transmitter ).first == referenceBody )\n//        {\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 1 ) - linkEndStates.at( 0 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 1 ) + linkEndTimes.at( 0 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 0 ).segment( 0, 3 ) ) ) );\n//        }\n//        else if( linkEnds.at( receiver ).first == referenceBody )\n//        {\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 0 ) - linkEndStates.at( 1 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 1 ) + linkEndTimes.at( 0 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 1 ).segment( 0, 3 ) ) ) );\n//        }\n//        break;\n//    }\n//    case one_way_doppler:\n//    {\n//        if( linkEnds.at( transmitter ).first == referenceBody )\n//        {\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 1 ) - linkEndStates.at( 0 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 1 ) + linkEndTimes.at( 0 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 0 ).segment( 0, 3 ) ) ) );\n//        }\n//        else if( linkEnds.at( receiver ).first == referenceBody )\n//        {\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 0 ) - linkEndStates.at( 1 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 1 ) + linkEndTimes.at( 0 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 1 ).segment( 0, 3 ) ) ) );\n//        }\n//        break;\n//    }\n//    case angular_position:\n//    {\n//        if( linkEnds.at( transmitter ).first == referenceBody )\n//        {\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 1 ) - linkEndStates.at( 0 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 1 ) + linkEndTimes.at( 0 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 0 ).segment( 0, 3 ) ) ) );\n//        }\n//        else if( linkEnds.at( receiver ).first == referenceBody )\n//        {\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 0 ) - linkEndStates.at( 1 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 1 ) + linkEndTimes.at( 0 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 1 ).segment( 0, 3 ) ) ) );\n//        }\n//        break;\n//    }\n//    case one_way_differenced_range:\n//    {\n//        if( linkEnds.at( transmitter ).first == referenceBody )\n//        {\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 1 ) - linkEndStates.at( 0 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 1 ) + linkEndTimes.at( 0 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 0 ).segment( 0, 3 ) ) ) );\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 3 ) - linkEndStates.at( 2 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 3 ) + linkEndTimes.at( 2 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 2 ).segment( 0, 3 ) ) ) );\n//        }\n//        else if( linkEnds.at( receiver ).first == referenceBody )\n//        {\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 0 ) - linkEndStates.at( 1 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 1 ) + linkEndTimes.at( 0 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 1 ).segment( 0, 3 ) ) ) );\n//            cosineAvoidanceAngles.push_back(\n//                        linear_algebra::computeCosineOfmanualElevationAngle(\n//                            ( ( linkEndStates.at( 2 ) - linkEndStates.at( 3 ) ).segment( 0, 3 ) ), (\n//                                bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                    ( linkEndTimes.at( 3 ) + linkEndTimes.at( 2 ) ) / 2.0 ).segment( 0, 3 ) -\n//                                linkEndStates.at( 3 ).segment( 0, 3 ) ) ) );\n//        }\n//        break;\n//    }\n//    case n_way_range:\n//    {\n//        int linkEndIndex = 0;\n//        for( LinkEnds::const_iterator linkEndIterator = linkEnds.begin( ); linkEndIterator != linkEnds.end( );\n//             linkEndIterator++ )\n//        {\n//            if( linkEndIterator->second.first == referenceBody )\n//            {\n//                if( linkEndIndex != 0 )\n//                {\n//                    cosineAvoidanceAngles.push_back(\n//                                linear_algebra::computeCosineOfmanualElevationAngle(\n//                                    ( ( linkEndStates.at( 2 * ( linkEndIndex - 1 ) ) -\n//                                        linkEndStates.at( 2 * ( linkEndIndex - 1 ) + 1 ) ).segment( 0, 3 ) ), (\n//                                        bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                            ( linkEndTimes.at( 2 * ( linkEndIndex - 1 ) + 1  ) +\n//                                              linkEndTimes.at( 2 * ( linkEndIndex - 1 ) ) ) / 2.0 ).segment( 0, 3 ) -\n//                                        linkEndStates.at( 2 * ( linkEndIndex - 1 ) + 1 ).segment( 0, 3 ) ) ) );\n//                }\n\n//                if( linkEndIndex != static_cast< int >( linkEnds.size( ) ) - 1 )\n//                {\n//                    cosineAvoidanceAngles.push_back(\n//                                linear_algebra::computeCosineOfmanualElevationAngle(\n//                                    ( linkEndStates.at( 2 * linkEndIndex + 1 ) -\n//                                      linkEndStates.at( 2 * linkEndIndex ) ).segment( 0, 3 ), (\n//                                        bodies.at( bodyToAvoid )->getStateInBaseFrameFromEphemeris< double, double >(\n//                                            ( linkEndTimes.at( 2 * linkEndIndex + 1  ) +\n//                                              linkEndTimes.at( 2 * linkEndIndex  ) ) / 2.0 ).segment( 0, 3 ) -\n//                                        linkEndStates.at( 2 * linkEndIndex ).segment( 0, 3 ) ) ) );\n//                }\n\n//            }\n//            linkEndIndex++;\n//        }\n//        break;\n//    }\n//    default:\n//        throw std::runtime_error( \"Error when testing avoidance angle viability, observable not recognized\" );\n\n//    }\n\n//    return cosineAvoidanceAngles;\n//}\n\n////! Test function to manually compute body distance between body center of mass and observation link vector\n//std::vector< double > getDistanceBetweenLineOfSightVectorAndPoint(\n//        const std::string bodyToAnalyze,\n//        const std::vector< Eigen::Vector6d > linkEndStates,\n//        const std::vector< double > linkEndTimes,\n//        const SystemOfBodies& bodies )\n//{\n//    std::vector< double > pointDistances;\n//    for( unsigned int i = 0; i < linkEndStates.size( ); i += 2 )\n//    {\n//        Eigen::Vector3d linkEnd1Position = linkEndStates.at( i ).segment( 0, 3 );\n//        Eigen::Vector3d linkEnd2Position = linkEndStates.at( i + 1 ).segment( 0, 3 );\n\n//        Eigen::Vector3d pointPosition = bodies.at( bodyToAnalyze )->getStateInBaseFrameFromEphemeris< double, double >(\n//                    ( linkEndTimes.at( i ) + linkEndTimes.at( i ) ) / 2.0 ).segment( 0, 3 );\n\n//        pointDistances.push_back( ( ( linkEnd2Position - pointPosition ).cross( linkEnd1Position - pointPosition ) ).norm( ) /\n//                                  ( linkEnd2Position - linkEnd1Position ).norm( ) );\n\n//    }\n//    return pointDistances;\n//}\n\n////! Test if observation viability calculators correctly constrain observations\n///*!\n// *  Test if observation viability calculators correctly constrain observations. Test is performed for a list of observables,\n// *  and a list of link ends per observable. The elevation angle, occultation and avoidance angle conditions are all checked.\n// */\n//BOOST_AUTO_TEST_CASE( testObservationViabilityCalculators )\n//{\n//    //Load spice kernels.\n//    spice_interface::loadStandardSpiceKernels( );\n\n//    // Define environment settings\n//    std::vector< std::string > bodyNames;\n//    bodyNames.push_back( \"Earth\" );\n//    bodyNames.push_back( \"Mars\" );\n//    bodyNames.push_back( \"Sun\" );\n//    bodyNames.push_back( \"Moon\" );\n\n//    BodyListSettings bodySettings =\n//            getDefaultBodySettings( bodyNames );\n\n//    // Set simplified rotation models for Earth/Mars (spice rotation retrieval is slow)\n//    bodySettings.at( \"Earth\" )->rotationModelSettings = std::make_shared< SimpleRotationModelSettings >(\n//                \"ECLIPJ2000\", \"IAU_Earth\",\n//                spice_interface::computeRotationQuaternionBetweenFrames(\n//                    \"ECLIPJ2000\", \"IAU_Earth\", 0.0 ),\n//                0.0, 2.0 * mathematical_constants::PI /\n//                ( physical_constants::JULIAN_DAY ) );\n//    bodySettings.at( \"Mars\" )->rotationModelSettings = std::make_shared< SimpleRotationModelSettings >(\n//                \"ECLIPJ2000\", \"IAU_Mars\",\n//                spice_interface::computeRotationQuaternionBetweenFrames(\n//                    \"ECLIPJ2000\", \"IAU_Mars\", 0.0 ),\n//                0.0, 2.0 * mathematical_constants::PI /\n//                ( physical_constants::JULIAN_DAY + 40.0 * 60.0 ) );\n\n//    // Set unrealistically large radius of Moon to make iss occultation mode significant\n//    double moonRadius = 1.0E6;\n//    bodySettings.at( \"Moon\" )->shapeModelSettings = std::make_shared< SphericalBodyShapeSettings >( moonRadius );\n\n//    // Create list of body objects\n//    SystemOfBodies bodies = createSystemOfBodies( bodySettings );\n\n\n//    // Create ground stations\n//    std::pair< std::string, std::string > earthStation1 = std::pair< std::string, std::string >( \"Earth\", \"EarthStation1\" );\n//    std::pair< std::string, std::string > earthStation2 = std::pair< std::string, std::string >( \"Earth\", \"EarthStation2\" );\n//    std::pair< std::string, std::string > mslStation1 = std::pair< std::string, std::string >( \"Mars\", \"MarsStation1\" );\n//    std::pair< std::string, std::string > mslStation2 = std::pair< std::string, std::string >( \"Mars\", \"MarsStation2\" );\n//    createGroundStation( bodies.at( \"Mars\" ), \"MarsStation1\", ( Eigen::Vector3d( ) << 100.0, 0.2, 2.1 ).finished( ),\n//                         coordinate_conversions::geodetic_position );\n//    createGroundStation( bodies.at( \"Mars\" ), \"MarsStation2\", ( Eigen::Vector3d( ) << -2000.0, -0.4, 0.1 ).finished( ),\n//                         coordinate_conversions::geodetic_position );\n//    createGroundStation( bodies.at( \"Earth\" ), \"EarthStation1\", ( Eigen::Vector3d( ) << 800.0, 0.12, 5.3 ).finished( ),\n//                         coordinate_conversions::geodetic_position );\n//    createGroundStation( bodies.at( \"Earth\" ), \"EarthStation2\", ( Eigen::Vector3d( ) << 100.0, 0.15, 0.0 ).finished( ),\n//                         coordinate_conversions::geodetic_position );\n\n//    // Define one-way range/one-way Doppler/angular position/one-way differenced range link ends\n//    LinkEnds oneWayLinkEnds1;\n//    oneWayLinkEnds1[ transmitter ] = std::make_pair( \"Mars\", \"MarsStation1\" );\n//    oneWayLinkEnds1[ receiver ] = std::make_pair( \"Earth\", \"EarthStation1\" );\n\n//    LinkEnds oneWayLinkEnds2;\n//    oneWayLinkEnds2[ transmitter ] = std::make_pair( \"Earth\", \"EarthStation2\" );\n//    oneWayLinkEnds2[ receiver ] = std::make_pair( \"Mars\", \"MarsStation2\" );\n\n//    LinkEnds oneWayLinkEnds3;\n//    oneWayLinkEnds3[ transmitter ] = std::make_pair( \"Mars\", \"MarsStation1\" );\n//    oneWayLinkEnds3[ receiver ] = std::make_pair( \"Earth\", \"EarthStation2\" );\n\n//    std::vector< LinkEnds > oneWayRangeLinkEnds;\n//    oneWayRangeLinkEnds.push_back( oneWayLinkEnds1 );\n//    oneWayRangeLinkEnds.push_back( oneWayLinkEnds2 );\n//    oneWayRangeLinkEnds.push_back( oneWayLinkEnds3 );\n\n//    // Define two-way range link ends\n//    LinkEnds twoWayLinkEnds1;\n//    twoWayLinkEnds1[ transmitter ] = std::make_pair( \"Mars\", \"MarsStation1\" );\n//    twoWayLinkEnds1[ reflector1 ] = std::make_pair( \"Earth\", \"EarthStation1\" );\n//    twoWayLinkEnds1[ receiver ] = std::make_pair( \"Mars\", \"MarsStation1\" );\n\n//    LinkEnds twoWayLinkEnds2;\n//    twoWayLinkEnds2[ transmitter ] = std::make_pair( \"Earth\", \"EarthStation2\" );\n//    twoWayLinkEnds2[ reflector1 ] = std::make_pair( \"Mars\", \"MarsStation2\" );\n//    twoWayLinkEnds2[ receiver ] = std::make_pair( \"Earth\", \"EarthStation1\" );\n\n//    LinkEnds twoWayLinkEnds3;\n//    twoWayLinkEnds3[ transmitter ] = std::make_pair( \"Mars\", \"MarsStation2\" );\n//    twoWayLinkEnds3[ reflector1 ] = std::make_pair( \"Earth\", \"EarthStation2\" );\n//    twoWayLinkEnds3[ receiver ] = std::make_pair( \"Mars\", \"MarsStation1\" );\n//    std::vector< LinkEnds > twoWayRangeLinkEnds;\n//    twoWayRangeLinkEnds.push_back( twoWayLinkEnds1 );\n//    twoWayRangeLinkEnds.push_back( twoWayLinkEnds2 );\n//    twoWayRangeLinkEnds.push_back( twoWayLinkEnds3 );\n\n//    // Create list of link ends per obsevables\n//    std::map< ObservableType, std::vector< LinkEnds > > testLinkEndsList;\n//    testLinkEndsList[ one_way_range ] = oneWayRangeLinkEnds;\n//    testLinkEndsList[ one_way_differenced_range ] = oneWayRangeLinkEnds;\n////    testLinkEndsList[ angular_position ] = oneWayRangeLinkEnds;\n//    testLinkEndsList[ n_way_range ] = twoWayRangeLinkEnds;\n\n//    // Define list of observation times that are to be checked: one observation every 2.5 days, over a period of 10 years.\n//    std::vector< double > unconstrainedObservationTimes;\n//    LinkEndType referenceLinkEnd = transmitter;\n//    double initialTime = 0.0, finalTime = 10.0 * physical_constants::JULIAN_YEAR, timeStep = physical_constants::JULIAN_DAY * 2.5;\n//    double currentTime = initialTime;\n//    while( currentTime <= finalTime )\n//    {\n//        unconstrainedObservationTimes.push_back( currentTime );\n//        currentTime += timeStep;\n//    }\n//    int unconstrainedNumberOfObservations = unconstrainedObservationTimes.size( );\n\n\n//    // Define minimum elevation angles for Earth/Mars stations\n//    double earthtestAngle = 4.0 * mathematical_constants::PI / 180.0;\n//    double marstestAngle = 10.0 * mathematical_constants::PI / 180.0;\n\n//    // Define minimum Sun avoidance angles for Earth/Mars stations\n//    double earthSunAvoidanceAngle = 30.0 * mathematical_constants::PI / 180.0;\n//    double marsSunAvoidanceAngle = 21.0 * mathematical_constants::PI / 180.0;\n\n\n//    // Create observation viability settings\n//    std::vector< std::shared_ptr< ObservationViabilitySettings > > observationViabilitySettings;\n//    observationViabilitySettings.push_back( std::make_shared< ObservationViabilitySettings >(\n//                                                minimum_elevation_angle, std::make_pair( \"Earth\", \"\" ), \"\",\n//                                                earthtestAngle ) );\n//    observationViabilitySettings.push_back( std::make_shared< ObservationViabilitySettings >(\n//                                                minimum_elevation_angle, std::make_pair( \"Mars\", \"\" ), \"\",\n//                                                marstestAngle ) );\n//    observationViabilitySettings.push_back( std::make_shared< ObservationViabilitySettings >(\n//                                                body_avoidance_angle, std::make_pair( \"Earth\", \"\" ), \"Sun\",\n//                                                earthSunAvoidanceAngle ) );\n//    observationViabilitySettings.push_back( std::make_shared< ObservationViabilitySettings >(\n//                                                body_avoidance_angle, std::make_pair( \"Mars\", \"\" ), \"Sun\",\n//                                                marsSunAvoidanceAngle ) );\n//    observationViabilitySettings.push_back( std::make_shared< ObservationViabilitySettings >(\n//                                                body_occultation, std::make_pair( \"Earth\", \"\" ), \"Moon\" ) );\n\n//    // Create observation model and observation time settings for all observables\n//    std::vector< std::shared_ptr< ObservationSimulationSettings< double > > > observationTimeSettings;\n//    std::vector< std::shared_ptr< ObservationSimulationSettings< double > > > observationTimeSettingsConstrained;\n\n//    std::vector< std::shared_ptr< ObservationModelSettings > >  observationSettingsList;\n//    for( std::map< ObservableType, std::vector< LinkEnds > >::const_iterator observableIterator = testLinkEndsList.begin( );\n//         observableIterator != testLinkEndsList.end( ); observableIterator++ )\n//    {\n//        for( unsigned int i = 0; i < observableIterator->second.size( ); i++ )\n//        {\n//            LinkEnds linkEnds = observableIterator->second.at( i );\n//            if( observableIterator->first == one_way_differenced_range )\n//            {\n//                observationSettingsList.push_back(\n//                            std::make_shared< OneWayDifferencedRangeRateObservationSettings >( linkEnds,\n//                                                                                               [ ]( const double ){ return 60.0; }, std::shared_ptr< LightTimeCorrectionSettings > ( ) ) );\n//            }\n//            else if( observableIterator->first == n_way_range )\n//            {\n//                observationSettingsList.push_back(\n//                            std::make_shared< NWayRangeObservationSettings >( linkEnds,\n//                                                                              std::shared_ptr< LightTimeCorrectionSettings >( ), observableIterator->second.at( i ).size( ) ) );\n//            }\n//            else\n//            {\n//                observationSettingsList.push_back(\n//                            std::make_shared< ObservationModelSettings >(\n//                                observableIterator->first, linkEnds, std::shared_ptr< LightTimeCorrectionSettings >( ) ) );\n\n//            }\n//            observationTimeSettings.push_back(\n//                        std::make_shared< TabulatedObservationSimulationSettings< double > >(\n//                            observableIterator->first, observableIterator->second.at( i ), unconstrainedObservationTimes,\n//                            referenceLinkEnd ) );\n//            observationTimeSettingsConstrained.push_back(\n//                        std::make_shared< TabulatedObservationSimulationSettings< double > >(\n//                            observableIterator->first, observableIterator->second.at( i ), unconstrainedObservationTimes,\n//                            referenceLinkEnd, observationViabilitySettings ) );\n//        }\n//    }\n\n//    // Create osbervation simulatos\n//    std::vector< std::shared_ptr< ObservationSimulatorBase< double, double > > > observationSimulators =\n//            createObservationSimulators( observationSettingsList, bodies );\n//    std::map< ObservableType, std::shared_ptr< ObservationSimulatorBase< double, double > > > observationSimulatorsMap;\n//    for( unsigned int i = 0; i < observationSimulators.size( ); i++ )\n//    {\n//        observationSimulatorsMap[ observationSimulators.at( i )->getObservableType( ) ] = observationSimulators.at( i );\n//    }\n\n//    // Simulate observations without constraints directly from simulateObservations function\n//    std::shared_ptr< observation_models::ObservationCollection< > > unconstrainedSimulatedObservables =\n//            simulateObservations( observationTimeSettings, observationSimulators, bodies );\n\n\n//    // Simulate observations with viability constraints directly from simulateObservations function\n//    std::shared_ptr< observation_models::ObservationCollection< > > constrainedSimulatedObservables =\n//            simulateObservations( observationTimeSettingsConstrained, observationSimulators, bodies );\n\n\n//    int numberOfObservables = testLinkEndsList.size( );\n\n//    // Check consistency of simulated observations from ObservationSimulator objects/simulateObservations function\n//    BOOST_CHECK_EQUAL( numberOfObservables, unconstrainedSimulatedObservables->getObservationTypeStartAndSize( ).size( ) );\n//    BOOST_CHECK_EQUAL( numberOfObservables, constrainedSimulatedObservables->getObservationTypeStartAndSize( ).size( ) );\n\n//    // Create iterators over all simulated observations\n//    auto unconstrainedSortedObservations = unconstrainedSimulatedObservables->getObservationSetStartAndSize( );\n//    auto constrainedSortedObservations = constrainedSimulatedObservables->getObservationSetStartAndSize( );\n\n//    std::map< ObservableType, std::map< LinkEnds, std::vector< std::pair< int, int > > > >::iterator unconstrainedIterator =\n//            unconstrainedSortedObservations.begin( );\n//    std::map< ObservableType, std::map< LinkEnds, std::vector< std::pair< int, int > > > >::iterator constrainedIterator =\n//            constrainedSortedObservations.begin( );\n\n//    std::vector< double > linkEndTimes;\n//    std::vector< Eigen::Vector6d > linkEndStates;\n\n//    std::vector< double > unconstrainedConcatenatedTimes = unconstrainedSimulatedObservables->getConcatenatedTimeVector( );\n//    std::vector< double > constrainedConcatenatedTimes = constrainedSimulatedObservables->getConcatenatedTimeVector( );\n\n//    // Iterate over all observations and check viability constraints\n//    for( int i = 0; i < numberOfObservables; i++ )\n//    {\n//        int numberOfLinkEnds = testLinkEndsList.at( unconstrainedIterator->first ).size( );\n//        int currentObservableSize = getObservableSize( unconstrainedIterator->first );\n\n//        // Check consistency of simulated observations from ObservationSimulator objects/simulateObservations function\n//        BOOST_CHECK_EQUAL( numberOfLinkEnds, unconstrainedIterator->second.size( ) );\n//        BOOST_CHECK_EQUAL( numberOfLinkEnds, constrainedIterator->second.size( ) );\n\n//        // Create iterators over all simulated observations of current observable\n//        auto unconstrainedLinkIterator = unconstrainedIterator->second.begin( );\n//        auto constrainedLinkIterator = constrainedIterator->second.begin( );\n\n//        ObservableType currentObservable = unconstrainedIterator->first;\n\n//        std::shared_ptr< ObservationSimulatorBase< double, double > > currentObservationSimulator =\n//                observationSimulatorsMap.at( currentObservable );\n\n//        // Iterate over all link ends of current observables.\n//        for( int j = 0; j < numberOfLinkEnds; j++ )\n//        {\n//            LinkEnds currentLinkEnds = unconstrainedLinkIterator->first;\n\n//            std::vector< std::shared_ptr< ObservationViabilityCalculator > > currentViabilityCalculators =\n//                    tudat::observation_models::createObservationViabilityCalculators(\n//                        bodies, currentLinkEnds, currentObservable, observationViabilitySettings );\n\n//            int unconstrainedIndex = 0;\n//            int constrainedIndex = 0;\n\n//            bool currentObservationWasViable = 0;\n//            bool currentObservationIsViable = 0;\n//            bool isSingleViabilityConditionMet = 0;\n//            Eigen::VectorXd currentObservation;\n\n//            // Retrieve observations for current link ends/observable type\n//            std::vector< std::pair< int, int > > constrainedIndices = constrainedLinkIterator->second;\n//            std::vector< std::pair< int, int > > unconstrainedIndices = unconstrainedLinkIterator->second;\n\n//            BOOST_CHECK_EQUAL( constrainedIndices.size( ), unconstrainedIndices.size( ) );\n\n\n//            for( unsigned int k = 0; k < constrainedIndices.size( ); k++ )\n//            {\n\n//                int currentUnconstrainedStartIndex = unconstrainedIndices.at( k ).first;\n//                int currentUnconstrainedBlockSize = unconstrainedIndices.at( k ).second;\n\n//                int currentConstrainedStartIndex = constrainedIndices.at( k ).first;\n//                int currentConstrainedBlockSize = constrainedIndices.at( k ).second;\n//                std::cout<<currentObservable<<\" \"<<j<<std::endl;\n\n//                std::cout<<currentUnconstrainedStartIndex<<\" \"<<currentUnconstrainedBlockSize<<\" \"<<unconstrainedConcatenatedTimes.size( )<<std::endl;\n////                Eigen::VectorXd unconstrainedObservationSegment =\n////                        unconstrainedSimulatedObservables->getObservationVector( ).segment(\n////                            currentUnconstrainedStartIndex, currentUnconstrainedBlockSize );\n////                Eigen::VectorXd constrainedObservationSegment =\n////                        constrainedSimulatedObservables->currentConstrainedBlockSize( ).segment(\n////                            currentConstrainedStartIndex, currentBlockSize );\n\n//                std::vector< double > unconstrainedTimesSegment(\n//                            unconstrainedConcatenatedTimes.begin( ) + currentUnconstrainedStartIndex,\n//                            unconstrainedConcatenatedTimes.begin( ) + currentUnconstrainedStartIndex + currentUnconstrainedBlockSize );\n//                std::cout<<currentConstrainedStartIndex<<\" \"<<currentConstrainedBlockSize<<\" \"<<constrainedConcatenatedTimes.size( )<<std::endl;\n\n//                std::vector< double > constrainedTimesSegment(\n//                            constrainedConcatenatedTimes.begin( ) + currentConstrainedStartIndex,\n//                            constrainedConcatenatedTimes.begin( ) + currentConstrainedStartIndex + currentConstrainedBlockSize );\n\n\n////                std::pair< Eigen::VectorXd, std::vector< double > > unconstrainedSingleLinkObservations;\n////                    unconstrainedSimulatedObservables->\n////                std::pair< Eigen::VectorXd, std::vector< double > > constrainedSingleLinkObservations;\n\n//                // Iterate over all unconstrained observations for current observable/link ends\n//                while( unconstrainedIndex < unconstrainedNumberOfObservations )\n//                {\n//                    // Check if current observation was rejected by viability calculators\n//                    if( constrainedIndex >= static_cast< int >( constrainedTimesSegment.size( ) ) )\n//                    {\n//                        currentObservationWasViable = false;\n//                    }\n//                    else if( unconstrainedTimesSegment.at( unconstrainedIndex ) ==\n//                             constrainedTimesSegment.at( constrainedIndex ) )\n//                    {\n//                        currentObservationWasViable = true;\n//                    }\n//                    else\n//                    {\n//                        currentObservationWasViable = false;\n//                    }\n\n//                    // Re-simulate current observation\n//                    if( currentObservable == angular_position )\n//                    {\n//                        currentObservation = std::dynamic_pointer_cast< ObservationSimulator< 2 > >(\n//                                    currentObservationSimulator )->getObservationModel( currentLinkEnds )->\n//                                computeObservationsWithLinkEndData(\n//                                    unconstrainedObservationTimes.at( unconstrainedIndex ), referenceLinkEnd,\n//                                    linkEndTimes, linkEndStates );\n//                    }\n//                    else\n//                    {\n//                        currentObservation = std::dynamic_pointer_cast< ObservationSimulator< 1 > >(\n//                                    currentObservationSimulator )->getObservationModel( currentLinkEnds )->\n//                                computeObservationsWithLinkEndData(\n//                                    unconstrainedObservationTimes.at( unconstrainedIndex ), referenceLinkEnd,\n//                                    linkEndTimes, linkEndStates );\n//                    }\n\n//                    // Re-compute viability according to viability calculator objects.\n//                    currentObservationIsViable = true;\n//                    for( unsigned int k = 0; k < currentViabilityCalculators.size( ); k++ )\n//                    {\n//                        isSingleViabilityConditionMet = currentViabilityCalculators.at( k )->isObservationViable(\n//                                    linkEndStates, linkEndTimes );\n//                        if( !isSingleViabilityConditionMet )\n//                        {\n//                            currentObservationIsViable = false;\n//                        }\n//                    }\n\n//                    // Manually recompute mars elevation angle condition\n//                    std::vector< double > marsElevationAngles = getBodyLinkElevationAngles(\n//                                currentLinkEnds, currentObservable, \"Mars\", linkEndStates, linkEndTimes, bodies );\n//                    bool computedViability = true;\n//                    for( unsigned int l = 0; l < marsElevationAngles.size( ); l++ )\n//                    {\n//                        if( marsElevationAngles.at( l ) < marstestAngle )\n//                        {\n//                            computedViability =  false;\n//                        }\n//                    }\n\n////                    std::cout<<computedViability<<\" \";\n//                    // Manually recompute earth elevation angle condition\n//                    std::vector< double > earthElevationAngles = getBodyLinkElevationAngles(\n//                                currentLinkEnds, currentObservable, \"Earth\", linkEndStates, linkEndTimes, bodies );\n//                    for( unsigned int l = 0; l < earthElevationAngles.size( ); l++ )\n//                    {\n//                        if( earthElevationAngles.at( l ) < earthtestAngle )\n//                        {\n//                            computedViability =  false;\n//                        }\n//                    }\n////                    std::cout<<computedViability<<\" \";\n\n//                    // Manually recompute earth-Sun avoidance angle condition\n//                    std::vector< double > earthSunCosineAvoidanceAngles = getBodyCosineAvoidanceAngles(\n//                                currentLinkEnds, currentObservable, \"Earth\", \"Sun\", linkEndStates, linkEndTimes, bodies );\n//                    for( unsigned int l = 0; l < earthSunCosineAvoidanceAngles.size( ); l++ )\n//                    {\n//                        if( earthSunCosineAvoidanceAngles.at( l ) > std::cos( earthSunAvoidanceAngle ) )\n//                        {\n//                            computedViability =  false;\n//                        }\n//                    }\n////                    std::cout<<computedViability<<\" \";\n\n//                    // Manually recompute mars-Sun avoidance angle condition\n//                    std::vector< double > marsSunCosineAvoidanceAngles = getBodyCosineAvoidanceAngles(\n//                                currentLinkEnds, currentObservable, \"Mars\", \"Sun\", linkEndStates, linkEndTimes, bodies );\n//                    for( unsigned int l = 0; l < marsSunCosineAvoidanceAngles.size( ); l++ )\n//                    {\n//                        if( marsSunCosineAvoidanceAngles.at( l ) > std::cos( marsSunAvoidanceAngle ) )\n//                        {\n//                            computedViability =  false;\n//                        }\n//                    }\n////                    std::cout<<computedViability<<\" \";\n\n//                    // Manually recompute occultataion consition\n//                    std::vector< double > moonLineOfSightDistances = getDistanceBetweenLineOfSightVectorAndPoint(\n//                                \"Moon\", linkEndStates, linkEndTimes, bodies );\n//                    for( unsigned int l = 0; l < moonLineOfSightDistances.size( ); l++ )\n//                    {\n////                        std::cout<<moonLineOfSightDistances.at( l )<<\" \"<<moonRadius<<std::endl;\n//                        if( moonLineOfSightDistances.at( l ) < moonRadius )\n//                        {\n//                            computedViability =  false;\n//                        }\n//                    }\n\n////                    std::cout<<currentObservationIsViable<<std::endl<<std::endl;\n\n//                    // Check manual/automatic viability check\n//                    BOOST_CHECK_EQUAL( currentObservationIsViable, currentObservationWasViable );\n//                    BOOST_CHECK_EQUAL( computedViability, currentObservationWasViable );\n\n\n//                    if( currentObservationWasViable )\n//                    {\n//                        constrainedIndex++;\n//                    }\n//                    unconstrainedIndex++;\n//                }\n////                BOOST_CHECK_EQUAL( constrainedIndex, constrainedLinkIterator->second.second.size( ) );\n\n//            }\n//            unconstrainedLinkIterator++;\n//            constrainedLinkIterator++;\n//        }\n\n//        unconstrainedIterator++;\n//        constrainedIterator++;\n//    }\n//}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n}\n\n}\n\n", "meta": {"hexsha": "9e82f039901a38e437bf80009c59456b17466989", "size": 51317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/observation_models/unitTestObservationViabilityCalculators.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": "tests/src/astro/observation_models/unitTestObservationViabilityCalculators.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": "tests/src/astro/observation_models/unitTestObservationViabilityCalculators.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.7914046122, "max_line_length": 189, "alphanum_fraction": 0.5720716332, "num_tokens": 11747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.17231906820747642}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_TMERC_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_TMERC_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// This file was modified by Oracle on 2017.\n// Modifications copyright (c) 2017, 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// 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// 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/geometry/util/math.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/function_overloads.hpp>\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct tmerc {};\n    struct utm {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace tmerc\n    {\n\n            static const double EPS10 = 1.e-10;\n            //static const double FC1 = 1.;\n            //static const double FC2 = .5;\n            //static const double FC3 = .16666666666666666666;\n            //static const double FC4 = .08333333333333333333;\n            //static const double FC5 = .05;\n            //static const double FC6 = .03333333333333333333;\n            //static const double FC7 = .02380952380952380952;\n            //static const double FC8 = .01785714285714285714;\n\n            template <typename T>\n            inline T FC1() { return 1.; }\n            template <typename T>\n            inline T FC2() { return .5; }\n            template <typename T>\n            inline T FC3() { return .16666666666666666666666666666666666666; }\n            template <typename T>\n            inline T FC4() { return .08333333333333333333333333333333333333; }\n            template <typename T>\n            inline T FC5() { return .05; }\n            template <typename T>\n            inline T FC6() { return .03333333333333333333333333333333333333; }\n            template <typename T>\n            inline T FC7() { return .02380952380952380952380952380952380952; }\n            template <typename T>\n            inline T FC8() { return .01785714285714285714285714285714285714; }\n\n            template <typename T>\n            struct par_tmerc\n            {\n                T    esp;\n                T    ml0;\n                T    en[EN_SIZE];\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_tmerc_ellipsoid : public base_t_fi<base_tmerc_ellipsoid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_tmerc<CalculationType> m_proj_parm;\n\n                inline base_tmerc_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_tmerc_ellipsoid<CalculationType, Parameters>,\n                     CalculationType, Parameters>(*this, par) {}\n\n                // FORWARD(e_forward)  ellipse\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                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n                    static const CalculationType FC1 = tmerc::FC1<CalculationType>();\n                    static const CalculationType FC2 = tmerc::FC2<CalculationType>();\n                    static const CalculationType FC3 = tmerc::FC3<CalculationType>();\n                    static const CalculationType FC4 = tmerc::FC4<CalculationType>();\n                    static const CalculationType FC5 = tmerc::FC5<CalculationType>();\n                    static const CalculationType FC6 = tmerc::FC6<CalculationType>();\n                    static const CalculationType FC7 = tmerc::FC7<CalculationType>();\n                    static const CalculationType FC8 = tmerc::FC8<CalculationType>();\n\n                    CalculationType al, als, n, cosphi, sinphi, t;\n\n                    /*\n                     * Fail if our longitude is more than 90 degrees from the\n                     * central meridian since the results are essentially garbage.\n                     * Is error -20 really an appropriate return value?\n                     *\n                     *  http://trac.osgeo.org/proj/ticket/5\n                     */\n                    if( lp_lon < -HALFPI || lp_lon > HALFPI )\n                    {\n                        xy_x = HUGE_VAL;\n                        xy_y = HUGE_VAL;\n                        BOOST_THROW_EXCEPTION( projection_exception(-14) );\n                        return;\n                    }\n\n                    sinphi = sin(lp_lat);\n                    cosphi = cos(lp_lat);\n                    t = fabs(cosphi) > 1e-10 ? sinphi/cosphi : 0.;\n                    t *= t;\n                    al = cosphi * lp_lon;\n                    als = al * al;\n                    al /= sqrt(1. - this->m_par.es * sinphi * sinphi);\n                    n = this->m_proj_parm.esp * cosphi * cosphi;\n                    xy_x = this->m_par.k0 * al * (FC1 +\n                        FC3 * als * (1. - t + n +\n                        FC5 * als * (5. + t * (t - 18.) + n * (14. - 58. * t)\n                        + FC7 * als * (61. + t * ( t * (179. - t) - 479. ) )\n                        )));\n                    xy_y = this->m_par.k0 * (pj_mlfn(lp_lat, sinphi, cosphi, this->m_proj_parm.en) - this->m_proj_parm.ml0 +\n                        sinphi * al * lp_lon * FC2 * ( 1. +\n                        FC4 * als * (5. - t + n * (9. + 4. * n) +\n                        FC6 * als * (61. + t * (t - 58.) + n * (270. - 330 * t)\n                        + FC8 * als * (1385. + t * ( t * (543. - t) - 3111.) )\n                        ))));\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\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                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n                    static const CalculationType FC1 = tmerc::FC1<CalculationType>();\n                    static const CalculationType FC2 = tmerc::FC2<CalculationType>();\n                    static const CalculationType FC3 = tmerc::FC3<CalculationType>();\n                    static const CalculationType FC4 = tmerc::FC4<CalculationType>();\n                    static const CalculationType FC5 = tmerc::FC5<CalculationType>();\n                    static const CalculationType FC6 = tmerc::FC6<CalculationType>();\n                    static const CalculationType FC7 = tmerc::FC7<CalculationType>();\n                    static const CalculationType FC8 = tmerc::FC8<CalculationType>();\n\n                    CalculationType n, con, cosphi, d, ds, sinphi, t;\n\n                    lp_lat = pj_inv_mlfn(this->m_proj_parm.ml0 + xy_y / this->m_par.k0, this->m_par.es, this->m_proj_parm.en);\n                    if (fabs(lp_lat) >= HALFPI) {\n                        lp_lat = xy_y < 0. ? -HALFPI : HALFPI;\n                        lp_lon = 0.;\n                    } else {\n                        sinphi = sin(lp_lat);\n                        cosphi = cos(lp_lat);\n                        t = fabs(cosphi) > 1e-10 ? sinphi/cosphi : 0.;\n                        n = this->m_proj_parm.esp * cosphi * cosphi;\n                        d = xy_x * sqrt(con = 1. - this->m_par.es * sinphi * sinphi) / this->m_par.k0;\n                        con *= t;\n                        t *= t;\n                        ds = d * d;\n                        lp_lat -= (con * ds / (1.-this->m_par.es)) * FC2 * (1. -\n                            ds * FC4 * (5. + t * (3. - 9. *  n) + n * (1. - 4 * n) -\n                            ds * FC6 * (61. + t * (90. - 252. * n +\n                                45. * t) + 46. * n\n                           - ds * FC8 * (1385. + t * (3633. + t * (4095. + 1574. * t)) )\n                            )));\n                        lp_lon = d*(FC1 -\n                            ds*FC3*( 1. + 2.*t + n -\n                            ds*FC5*(5. + t*(28. + 24.*t + 8.*n) + 6.*n\n                           - ds * FC7 * (61. + t * (662. + t * (1320. + 720. * t)) )\n                        ))) / cosphi;\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"tmerc_ellipsoid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_tmerc_spheroid : public base_t_fi<base_tmerc_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_tmerc<CalculationType> m_proj_parm;\n\n                inline base_tmerc_spheroid(const Parameters& par)\n                    : base_t_fi<base_tmerc_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  sphere\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                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n\n                    CalculationType b, cosphi;\n\n                    /*\n                     * Fail if our longitude is more than 90 degrees from the\n                     * central meridian since the results are essentially garbage.\n                     * Is error -20 really an appropriate return value?\n                     *\n                     *  http://trac.osgeo.org/proj/ticket/5\n                     */\n                    if( lp_lon < -HALFPI || lp_lon > HALFPI )\n                    {\n                        xy_x = HUGE_VAL;\n                        xy_y = HUGE_VAL;\n                        BOOST_THROW_EXCEPTION( projection_exception(-14) );\n                        return;\n                    }\n\n                    cosphi = cos(lp_lat);\n                    b = cosphi * sin(lp_lon);\n                    if (fabs(fabs(b) - 1.) <= EPS10)\n                        BOOST_THROW_EXCEPTION( projection_exception(-20) );\n\n                    xy_x = this->m_proj_parm.ml0 * log((1. + b) / (1. - b));\n                    xy_y = cosphi * cos(lp_lon) / sqrt(1. - b * b);\n\n                    b = fabs( xy_y );\n                    if (b >= 1.) {\n                        if ((b - 1.) > EPS10)\n                            BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                        else xy_y = 0.;\n                    } else\n                        xy_y = acos(xy_y);\n\n                    if (lp_lat < 0.)\n                        xy_y = -xy_y;\n                    xy_y = this->m_proj_parm.esp * (xy_y - this->m_par.phi0);\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                    CalculationType h, g;\n\n                    h = exp(xy_x / this->m_proj_parm.esp);\n                    g = .5 * (h - 1. / h);\n                    h = cos(this->m_par.phi0 + xy_y / this->m_proj_parm.esp);\n                    lp_lat = asin(sqrt((1. - h * h) / (1. + g * g)));\n                    if (xy_y < 0.) lp_lat = -lp_lat;\n                    lp_lon = (g || h) ? atan2(g, h) : 0.;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"tmerc_spheroid\";\n                }\n\n            };\n\n            template <typename Parameters, typename T>\n            inline void setup(Parameters& par, par_tmerc<T>& proj_parm)  /* general initialization */\n            {\n                if (par.es) {\n                    if (!pj_enfn(par.es, proj_parm.en))\n                        BOOST_THROW_EXCEPTION( projection_exception(0) );\n                    proj_parm.ml0 = pj_mlfn(par.phi0, sin(par.phi0), cos(par.phi0), proj_parm.en);\n                    proj_parm.esp = par.es / (1. - par.es);\n                } else {\n                    proj_parm.esp = par.k0;\n                    proj_parm.ml0 = .5 * proj_parm.esp;\n                }\n            }\n\n\n            // Transverse Mercator\n            template <typename Parameters, typename T>\n            inline void setup_tmerc(Parameters& par, par_tmerc<T>& proj_parm)\n            {\n                setup(par, proj_parm);\n            }\n\n            // Universal Transverse Mercator (UTM)\n            template <typename Parameters, typename T>\n            inline void setup_utm(Parameters& par, par_tmerc<T>& proj_parm)\n            {\n                static const T ONEPI = detail::ONEPI<T>();\n\n                int zone;\n\n                par.y0 = pj_param(par.params, \"bsouth\").i ? 10000000. : 0.;\n                par.x0 = 500000.;\n                if (pj_param(par.params, \"tzone\").i) /* zone input ? */\n                    if ((zone = pj_param(par.params, \"izone\").i) > 0 && zone <= 60)\n                        --zone;\n                    else\n                        BOOST_THROW_EXCEPTION( projection_exception(-35) );\n                else /* nearest central meridian input */\n                    if ((zone = int_floor((adjlon(par.lam0) + ONEPI) * 30. / ONEPI)) < 0)\n                        zone = 0;\n                    else if (zone >= 60)\n                        zone = 59;\n                par.lam0 = (zone + .5) * ONEPI / 30. - ONEPI;\n                par.k0 = 0.9996;\n                par.phi0 = 0.;\n                setup(par, proj_parm);\n            }\n\n    }} // namespace detail::tmerc\n    #endif // doxygen\n\n    /*!\n        \\brief Transverse Mercator 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         - Cylindrical\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_tmerc.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct tmerc_ellipsoid : public detail::tmerc::base_tmerc_ellipsoid<CalculationType, Parameters>\n    {\n        inline tmerc_ellipsoid(const Parameters& par) : detail::tmerc::base_tmerc_ellipsoid<CalculationType, Parameters>(par)\n        {\n            detail::tmerc::setup_tmerc(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Transverse Mercator 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         - Cylindrical\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_tmerc.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct tmerc_spheroid : public detail::tmerc::base_tmerc_spheroid<CalculationType, Parameters>\n    {\n        inline tmerc_spheroid(const Parameters& par) : detail::tmerc::base_tmerc_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::tmerc::setup_tmerc(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Universal Transverse Mercator (UTM) 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         - Cylindrical\n         - Spheroid\n        \\par Projection parameters\n         - zone: UTM Zone (integer)\n         - south: Denotes southern hemisphere UTM zone (boolean)\n        \\par Example\n        \\image html ex_utm.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct utm_ellipsoid : public detail::tmerc::base_tmerc_ellipsoid<CalculationType, Parameters>\n    {\n        inline utm_ellipsoid(const Parameters& par) : detail::tmerc::base_tmerc_ellipsoid<CalculationType, Parameters>(par)\n        {\n            detail::tmerc::setup_utm(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Universal Transverse Mercator (UTM) 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         - Cylindrical\n         - Spheroid\n        \\par Projection parameters\n         - zone: UTM Zone (integer)\n         - south: Denotes southern hemisphere UTM zone (boolean)\n        \\par Example\n        \\image html ex_utm.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct utm_spheroid : public detail::tmerc::base_tmerc_spheroid<CalculationType, Parameters>\n    {\n        inline utm_spheroid(const Parameters& par) : detail::tmerc::base_tmerc_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::tmerc::setup_utm(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::tmerc, tmerc_spheroid, tmerc_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::utm, utm_spheroid, utm_ellipsoid)\n        \n        // Factory entry(s) - dynamic projection\n        template <typename CalculationType, typename Parameters>\n        class tmerc_entry : public detail::factory_entry<CalculationType, Parameters>\n        {\n            public :\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\n                {\n                    if (par.es)\n                        return new base_v_fi<tmerc_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                    else\n                        return new base_v_fi<tmerc_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        class utm_entry : public detail::factory_entry<CalculationType, Parameters>\n        {\n            public :\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\n                {\n                    if (par.es)\n                        return new base_v_fi<utm_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                    else\n                        return new base_v_fi<utm_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void tmerc_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"tmerc\", new tmerc_entry<CalculationType, Parameters>);\n            factory.add_to_factory(\"utm\", new utm_entry<CalculationType, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_TMERC_HPP\n\n", "meta": {"hexsha": "6ed2902142c441dbaf8633b172370fcc9bf76ae1", "size": 21580, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/tmerc.hpp", "max_stars_repo_name": "ramcn/gemmx", "max_stars_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2018-08-13T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:37:20.000Z", "max_issues_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/tmerc.hpp", "max_issues_repo_name": "ramcn/gemmx", "max_issues_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/tmerc.hpp", "max_forks_repo_name": "ramcn/gemmx", "max_forks_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T12:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:39.000Z", "avg_line_length": 43.5080645161, "max_line_length": 131, "alphanum_fraction": 0.547265987, "num_tokens": 4896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.17231906119675028}}
{"text": "\n#include <boost/program_options.hpp>\n\n#include <bts/blockchain/address.hpp>\n#include <bts/blockchain/pts_address.hpp>\n#include <bts/blockchain/types.hpp>\n#include <bts/utilities/deterministic_openssl_rand.hpp>\n#include <bts/utilities/key_conversion.hpp>\n\n#include <fc/crypto/elliptic.hpp>\n#include <fc/io/json.hpp>\n#include <fc/reflect/variant.hpp>\n#include <fc/filesystem.hpp>\n#include <fc/variant_object.hpp>\n\n#include <iostream>\n\nusing namespace bts::blockchain;\n\nboost::program_options::variables_map parse_option_variables(int argc, char** argv)\n{\n    boost::program_options::positional_options_description p_option_config;\n    p_option_config.add(\"json-outfile\", 1);\n\n    boost::program_options::options_description option_config(\"Usage\");\n    option_config.add_options()\n        (\"help\", \"Display this help message and exit\")\n\n        (\"json-outfile\", boost::program_options::value<string>()->default_value(\"\"), \"Output file for private key data\")\n\n        (\"seed\", boost::program_options::value<string>(), \"Set seed for deterministic key generation\")\n        (\"count\", boost::program_options::value<int64_t>()->default_value(-1), \"Set number of keys to generate\")\n        ;\n\n    boost::program_options::variables_map option_variables;\n    try\n    {\n        boost::program_options::store(\n                                      boost::program_options::command_line_parser(argc, argv)\n                                     .options(option_config)\n                                     .positional(p_option_config)\n                                     .run(),\n                                     option_variables\n                                     );\n        boost::program_options::notify(option_variables);\n    }\n    catch (boost::program_options::error& cmdline_error)\n    {\n        std::cerr << \"Error: \" << cmdline_error.what() << \"\\n\";\n        std::cerr << option_config << \"\\n\";\n        exit(1);\n    }\n\n    if (option_variables.count(\"help\"))\n    {\n        std::cout << option_config << \"\\n\";\n        exit(0);\n    }\n\n    return option_variables;\n}\n\nint run( int64_t index, fc::optional<string> seed, fc::optional<fc::path> json_outfile )\n{\n     fc::ecc::private_key key;\n    \n     if( seed.valid() )\n     {\n         string effective_seed;\n         if( index >= 0 )\n             effective_seed = (*seed)+std::to_string(index);\n         else\n             effective_seed = (*seed);\n         fc::sha256 hash_effective_seed = fc::sha256::hash(\n             effective_seed.c_str(),\n             effective_seed.length() );\n         key = fc::ecc::private_key::regenerate( hash_effective_seed );\n    }\n    else\n        key = fc::ecc::private_key::generate();\n    \n    \n    if( !json_outfile.valid() )\n    {\n        auto obj = fc::mutable_variant_object();\n\n        obj[\"public_key\"] = public_key_type(key.get_public_key());\n        obj[\"private_key\"] = key.get_secret();\n        obj[\"wif_private_key\"] = bts::utilities::key_to_wif(key);\n        obj[\"native_address\"] = bts::blockchain::address(key.get_public_key());\n        obj[\"pts_address\"] = bts::blockchain::pts_address(key.get_public_key());\n\n        std::cout << fc::json::to_pretty_string(obj) << '\\n';\n        return 0;\n    }\n    else\n    {\n        std::cout << \"writing new private key to JSON file \" << (*json_outfile).string() << \"\\n\";\n        fc::json::save_to_file(key, (*json_outfile));\n\n        std::cout << \"bts address: \"\n        << std::string(bts::blockchain::address(key.get_public_key())) << \"\\n\";\n\n        return 0;\n    }\n}\n\nint main( int argc, char** argv )\n{\n    boost::program_options::variables_map option_variables =\n        parse_option_variables(argc, argv);\n\n    fc::optional<string> seed;\n    fc::optional<fc::path> json_outfile;\n    \n    if( option_variables.count(\"seed\") )\n        seed = option_variables[\"seed\"].as<string>();\n    if( option_variables.count(\"json-outfile\") )\n    {\n        string s_json_outfile = option_variables[\"json-outfile\"].as<string>();\n        if( s_json_outfile != \"\" )\n            json_outfile = fc::path(s_json_outfile);\n    }\n    \n    if( ! option_variables.count(\"count\") )\n    {\n        std::cerr << \"count undefined, should never happen!\\n\";\n        return 1;\n    }\n    \n    int n = option_variables[\"count\"].as<int64_t>();\n    if( n != -1 )\n    {\n        if( json_outfile.valid() )\n        {\n            std::cerr << \"Combining --count and --json-outfile is currently unsupported\\n\";\n            return 1;\n        }\n        std::cout << \"[\\n\";\n        for( int64_t i=0; i<n; i++ )\n        {\n            if (i != 0)\n                std::cout << \",\\n\";\n            int result = run(i, seed, json_outfile);\n            if( result != 0 )\n                return result;\n        }\n        std::cout << \"]\\n\";\n    }\n    else\n        return run(-1, seed, json_outfile);\n    \n    return 0;\n}\n", "meta": {"hexsha": "64ec10a735464c8a75ee0b7f2c34bcc894118b81", "size": 4806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/utils/bts_create_key.cpp", "max_stars_repo_name": "emfrias/bitshares", "max_stars_repo_head_hexsha": "8af3c28c2a7225857b2b37f7821332279b4fd66e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T21:11:35.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-08T17:53:49.000Z", "max_issues_repo_path": "programs/utils/bts_create_key.cpp", "max_issues_repo_name": "emfrias/bitshares", "max_issues_repo_head_hexsha": "8af3c28c2a7225857b2b37f7821332279b4fd66e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 428.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T18:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-08T16:08:08.000Z", "max_forks_repo_path": "programs/utils/bts_create_key.cpp", "max_forks_repo_name": "emfrias/bitshares", "max_forks_repo_head_hexsha": "8af3c28c2a7225857b2b37f7821332279b4fd66e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T02:31:30.000Z", "max_forks_repo_forks_event_max_datetime": "2015-06-05T18:50:57.000Z", "avg_line_length": 31.0064516129, "max_line_length": 120, "alphanum_fraction": 0.5753225135, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.17227085912156687}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <math.h> \n#include <vector>\n#include <ctime>\n#include <cstdlib>\n#include <unistd.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cstddef> \n#include <nlopt.hpp>\n#include <pangolin/pangolin.h>\n#include \"opencv2/opencv.hpp\"\n\n#include <Eigen/Core>\n\n#include <df/camera/camera.h>\n#include <df/camera/linear.h>\n#include <df/camera/poly3.h>\n#include <df/camera/rig.h>\n#include <df/image/backprojection.h>\n#include <df/prediction/glRender.h>\n#include <df/prediction/glRenderTypes.h>\n#include <df/util/args.h>\n#include <df/util/glHelpers.h>\n#include <df/util/pangolinHelpers.h>\n#include <df/util/tensor.h>\n\n#include <assimp/cimport.h>\n#include <assimp/scene.h>\n\ntemplate <typename Derived>\ninline void operator >>(std::istream & stream, Eigen::MatrixBase<Derived> & M)\n{\n\n    for (int r = 0; r < M.rows(); ++r) {\n        for (int c = 0; c < M.cols(); ++c) {\n            stream >> M(r,c);\n        }\n    }\n\n}\n\nstruct ForegroundRenderType {\n    static std::string vertShaderName() {\n        static const char name[] = \"foreground.vert\";\n        return std::string(name);\n    }\n    static std::string fragShaderName() {\n        static const char name[] = \"foreground.frag\";\n        return std::string(name);\n    }\n    static constexpr int numTextures = 1;\n    static const GLenum * textureFormats() {\n        static const GLenum formats[numTextures] = { GL_RGBA32F};\n        return formats;\n    }\n    static constexpr int numVertexAttributes = 1;\n    static const int * vertexAttributeSizes() {\n        static const int sizes[numVertexAttributes] = { 3 };\n        return sizes;\n    }\n    static const GLenum * vertexAttributeTypes() {\n        static const GLenum types[numVertexAttributes] = { GL_FLOAT };\n        return types;\n    }\n};\n\nunsigned char class_colors[22][3] = {{255, 255, 255}, {255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {255, 255, 0}, {255, 0, 255}, {0, 255, 255},\n                              {128, 0, 0}, {0, 128, 0}, {0, 0, 128}, {128, 128, 0}, {128, 0, 128}, {0, 128, 128},\n                              {64, 0, 0}, {0, 64, 0}, {0, 0, 64}, {64, 64, 0}, {64, 0, 64}, {0, 64, 64}, \n                              {192, 0, 0}, {0, 192, 0}, {0, 0, 192}};\n\nstruct DataForOpt\n{\n  int width, height;\n  cv::Rect bb2D;\n  std::vector<cv::Point3f> bb3D;\n  cv::Mat_<float> camMat;\n  pangolin::OpenGlMatrixSpec projectionMatrix;\n  pangolin::GlBuffer* texturedVertices;\n  pangolin::GlBuffer* texturedIndices;\n  cv::Mat* gt_mask;\n  pangolin::View* view;\n  df::GLRenderer<ForegroundRenderType>* renderer;\n};\n\nstatic double optEnergy(const std::vector<double> &pose, std::vector<double> &grad, void *data);\ndouble poseWithOpt(std::vector<double> & vec, DataForOpt data, int iterations);\ninline float getIoU(const cv::Rect& bb1, const cv::Rect bb2);\nint clamp(int val, int min_val, int max_val);\ninline cv::Rect getBB2D(int imageWidth, int imageHeight, const std::vector<cv::Point3f>& bb3D, const cv::Mat& camMat, const cv::Mat& RT);\n\nclass Refiner\n{\n public:\n\n  Refiner() {};\n  Refiner(std::string model_file);\n  ~Refiner();\n\n  void setup(std::string model_file);\n  void create_window(int width, int height);\n  void destroy_window();\n  void render(unsigned char* data, unsigned char* labels, float* rois, int num_rois, int num_gt, int width, int height, int num_classes,\n                    float* poses_gt, float* poses_pred, float fx, float fy, float px, float py, float* extents, float* poses_new, int is_save);\n  void loadModels(std::string filename);\n  aiMesh* loadTexturedMesh(const std::string filename, std::string & texture_name);\n  void initializeBuffers(aiMesh* assimpMesh, std::string textureName, \n    pangolin::GlBuffer & vertices, pangolin::GlBuffer & indices, pangolin::GlBuffer & texCoords, pangolin::GlTexture & texture, bool is_textured);\n  void feed_data(int width, int height, unsigned char* data, unsigned char* labels, pangolin::GlTexture & colorTex, pangolin::GlTexture & labelTex);\n\n  void refine(unsigned char* labels, float* rois, int num_rois, int width, int height, int num_classes,\n                    float* poses_pred, float fx, float fy, float px, float py, float* extents, float* poses_new);\n\n  void getBb3Ds(float* extents, std::vector<std::vector<cv::Point3f>>& bb3Ds, int num_classes);\n  inline std::vector<cv::Point3f> getBB3D(const cv::Vec<float, 3>& extent);\n\n private:\n  int counter_;\n\n  // 3D models\n  std::vector<aiMesh*> assimpMeshes_;\n  std::vector<std::string> texture_names_;\n\n  // pangoline views\n  pangolin::View* gtView_;\n  pangolin::View* poseView_;\n  pangolin::View* colorView_;\n  pangolin::View* labelView_;\n  pangolin::View* maskView_;\n  pangolin::View* multiView_;\n\n  // buffers\n  std::vector<pangolin::GlBuffer> texturedVertices_;\n  std::vector<pangolin::GlBuffer> texturedIndices_;\n  std::vector<pangolin::GlBuffer> texturedCoords_;\n  std::vector<pangolin::GlTexture> texturedTextures_;\n\n  df::GLRenderer<ForegroundRenderType>* renderer_;\n};\n", "meta": {"hexsha": "83c539a123668afaa0d837c6686232e2a0f9d5ab", "size": 4952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/pose_refinement/refinement.hpp", "max_stars_repo_name": "aditya2592/PoseCNN", "max_stars_repo_head_hexsha": "a763120ce0ceb55cf3432980287ef463728f8052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 655.0, "max_stars_repo_stars_event_min_datetime": "2018-03-21T19:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:41:21.000Z", "max_issues_repo_path": "lib/pose_refinement/refinement.hpp", "max_issues_repo_name": "SergioRAgostinho/PoseCNN", "max_issues_repo_head_hexsha": "da9eaae850eed7521a2a48a4d27474d655caab42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122.0, "max_issues_repo_issues_event_min_datetime": "2018-04-04T13:57:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T09:28:44.000Z", "max_forks_repo_path": "lib/pose_refinement/refinement.hpp", "max_forks_repo_name": "SergioRAgostinho/PoseCNN", "max_forks_repo_head_hexsha": "da9eaae850eed7521a2a48a4d27474d655caab42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 226.0, "max_forks_repo_forks_event_min_datetime": "2018-03-22T01:40:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T11:56:14.000Z", "avg_line_length": 34.6293706294, "max_line_length": 148, "alphanum_fraction": 0.6688206785, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.17227085558262248}}
{"text": "#include \"main.hpp\"\n#include <Eigen/Core>\n#include <chrono>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include <vector>\n#include \"HardwareIO/Joint/LinearAxis/LinearAxis.hpp\"\n#include \"HardwareIO/Joint/OneAxis/OneAxis.hpp\"\n#include \"HardwareIO/Joint/TwoAxis/TwoAxis.hpp\"\n#include \"HardwareIO/Muscle/Muscle.hpp\"\n#include \"HardwareIO/Valve/Valve.hpp\"\n#include \"Input/Controller/Controller.hpp\"\n#include \"MPC/AdaptiveMPC/AdaptiveMPC.hpp\"\n#include \"MPC/AdaptiveMPC/Optimizer.hpp\"\n#include \"PID/PID.hpp\"\n#include \"SMC/SMC.hpp\"\n#include \"Sensors/LinearPotentiometer/LinearPotentiometer.hpp\"\n#include \"Sensors/PressureSensor/PressureSensor.hpp\"\n#include \"adc.h\"\n#include \"dma.h\"\n#include \"gpio.h\"\n#include \"main.h\"\n#include \"nuclear/src/clock.hpp\"\n#include \"stm32f7xx_hal_conf.h\"\n#include \"stm32f7xx_it.h\"\n#include \"tim.h\"\n#include \"usart.h\"\n#include \"utility/io/adc.hpp\"\n#include \"utility/io/gpio.hpp\"\n#include \"utility/io/uart.hpp\"\n\nextern \"C\" {\nvoid SystemClock_Config(void) {\n    RCC_OscInitTypeDef RCC_OscInitStruct;\n    RCC_ClkInitTypeDef RCC_ClkInitStruct;\n    RCC_PeriphCLKInitTypeDef PeriphClkInitStruct;\n\n    // Configure LSE Drive Capability\n    HAL_PWR_EnableBkUpAccess();\n\n    // Configure the main internal regulator output voltage\n    __HAL_RCC_PWR_CLK_ENABLE();\n    __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);\n\n    // Initializes the CPU, AHB and APB busses clocks\n    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;\n    RCC_OscInitStruct.HSEState       = RCC_HSE_ON;\n    RCC_OscInitStruct.PLL.PLLState   = RCC_PLL_ON;\n    RCC_OscInitStruct.PLL.PLLSource  = RCC_PLLSOURCE_HSE;\n    RCC_OscInitStruct.PLL.PLLM       = 8;\n    RCC_OscInitStruct.PLL.PLLN       = 432;\n    RCC_OscInitStruct.PLL.PLLP       = RCC_PLLP_DIV2;\n    RCC_OscInitStruct.PLL.PLLQ       = 9;\n    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {\n        Error_Handler();\n    }\n\n    // Activate the Over-Drive mode\n    if (HAL_PWREx_EnableOverDrive() != HAL_OK) {\n        Error_Handler();\n    }\n\n    // Initializes the CPU, AHB and APB busses clocks\n    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;\n    RCC_ClkInitStruct.SYSCLKSource   = RCC_SYSCLKSOURCE_PLLCLK;\n    RCC_ClkInitStruct.AHBCLKDivider  = RCC_SYSCLK_DIV1;\n    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;\n    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;\n\n    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {\n        Error_Handler();\n    }\n    PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USART6;\n    PeriphClkInitStruct.Usart6ClockSelection = RCC_USART6CLKSOURCE_PCLK2;\n    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) {\n        Error_Handler();\n    }\n}\n\nvoid Error_Handler(void) {\n    utility::io::debug.error(\"\\n\");\n    utility::io::gpio::led3 = true;\n    while (1) {\n    }\n}\n}\n\nint main() {\n    /*******************************************************************************************************************\n    ********************************************** System Initialisation ***********************************************\n    *******************************************************************************************************************/\n    // Initialise the HAL driver\n    HAL_Init();\n\n    // Configure the system clock\n    SystemClock_Config();\n    MX_GPIO_Init();\n    MX_DMA_Init();\n    MX_USART6_UART_Init();\n    utility::clock::initialise();\n    utility::io::adc_io.initialise();\n\n    /*******************************************************************************************************************\n    ************************************************* Muscles & Joints *************************************************\n    *******************************************************************************************************************/\n    auto time_start = NUClear::clock::now();\n\n    utility::io::debug.out(\"\\033[3J\");\n    utility::io::debug.out(\"\\014\");\n    utility::io::debug.out(\"\\033[3J\");\n    utility::io::debug.out(\"\\014\");\n    utility::io::debug.out(\"\\e[0m\");\n\n    utility::io::debug.out(\"Welcome to PNEUbot\\n\");\n\n    // We need our setpoint potentiometer\n    // auto Setpoint = module::Input::controller.GetPosition();\n\n\n    // Declare our muscle parameters and populate a vector of muscles\n    // float nom_length;\n    // float contraction_percent;\n    // float critical_ratio;\n    // float sonic_conductance;\n    // float T_0;\n    // float T_1;\n    // float damping_coefficient;\n    // float muscle_coefficients[4];\n    // float F_ce[6][6];\n\n    constexpr float p00 = (76.27) * 10e-35;       // (76.25, 76.29)\n    constexpr float p10 = (1.515e+12) * 10e-35;   // (-1.512e+13, 1.815e+13)\n    constexpr float p01 = (-1.515e+12) * 10e-35;  // (-1.815e+13, 1.512e+13)\n    constexpr float p20 = (7.645e+12) * 10e-35;   // (-3.98e+12, 1.927e+13)\n    constexpr float p11 = (-1.984e+13) * 10e-35;  // (-3.816e+13, -1.518e+12)\n    constexpr float p02 = (1.219e+13) * 10e-35;   // (-2.637e+12, 2.702e+13)\n    constexpr float p30 = (-1.535e+13) * 10e-35;  // (-3.118e+13, 4.877e+11)\n    constexpr float p21 = (3.063e+13) * 10e-35;   // (9.519e+12, 5.174e+13)\n    constexpr float p12 = (-1.087e+13) * 10e-35;  // (-3.451e+13, 1.277e+13)\n    constexpr float p03 = (-4.412e+12) * 10e-35;  // (-2.166e+13, 1.284e+13)\n    constexpr float p40 = (2.531e+13) * 10e-35;   // (1.529e+13, 3.532e+13)\n    constexpr float p31 = (-2.712e+13) * 10e-35;  // (-3.913e+13, -1.511e+13)\n    constexpr float p22 = (-1.771e+13) * 10e-35;  // (-2.676e+13, -8.651e+12)\n    constexpr float p13 = (1.455e+13) * 10e-35;   // (9.587e+11, 2.814e+13)\n    constexpr float p04 = (4.974e+12) * 10e-35;   // (-5.777e+12, 1.572e+13)\n    constexpr float p50 = (-1.836e+12) * 10e-35;  // (-4.701e+12, 1.03e+12)\n    constexpr float p41 = (3.682e+12) * 10e-35;   // (1.3e+12, 6.063e+12)\n    constexpr float p32 = (2.06e+12) * 10e-35;    // (-9.788e+11, 5.098e+12)\n    constexpr float p23 = (-6.712e+12) * 10e-35;  // (-9.919e+12, -3.506e+12)\n    constexpr float p14 = (1.642e+12) * 10e-35;   // (-9.098e+11, 4.195e+12)\n    constexpr float p05 = (1.164e+12) * 10e-35;   // (-1.678e+12, 4.006e+12)\n\n    // clang-format off\n\n    Eigen::Matrix<float, 6, 6> F_ce;\n    F_ce <<  p00, p01, p02, p03, p04, p05,\n             p10, p11, p12, p13, p14, 0,\n             p20, p21, p22, p23, 0,   0,\n             p30, p31, p32, 0,   0,   0,\n             p40, p41, 0,   0,   0,   0,\n             p50, 0,   0,   0,   0,   0;   \n    const module::HardwareIO::muscle_properties_t pm_280 = {0.25, 0.108, 0.433, 2.6167e-9, 298.15, 298.15, 0.0007, {1.6e-4, -6.4e-4, 5.5e-4, 0.8e-4}, F_ce};\n    // clang-format on\n\n    std::vector<module::HardwareIO::muscle_t> muscles;\n\n    module::HardwareIO::muscle_t muscle1 = {\n        module::HardwareIO::valve1, module::Sensors::pressuresensor1, module::Sensors::linearpot1, pm_280};\n\n    module::HardwareIO::muscle_t muscle2 = {\n        module::HardwareIO::valve2, module::Sensors::pressuresensor2, module::Sensors::linearpot2, pm_280};\n\n    muscles.push_back(muscle1);\n    muscles.push_back(muscle2);\n\n    // Make our joints with the previously declared muscles\n    // MPC Controller\n    module::HardwareIO::joint::OneAxis<module::MPC::AdaptiveMPC::AdaptiveMPC> one_axis_joint(\n        muscles, 1, 0.47, module::MPC::AdaptiveMPC::mpc, module::MPC::AdaptiveMPC::optimizer1);\n    // SMC Controller\n    // module::HardwareIO::joint::OneAxis<module::SMC::SMC> one_axis_joint(muscles, 1, 0.47, module::SMC::smc);\n\n    // Start our ADC DMA\n    utility::io::adc_io.Start();\n    utility::io::debug.out(\"Initialisation Finished\\n\");\n\n    /*******************************************************************************************************************\n    **************************************************** Controller ****************************************************\n    *******************************************************************************************************************/\n    // This is where our 'controller' starts\n    float Sampling_time = 50;  // 0.01 T_s\n    int i               = 0;\n    time_start          = NUClear::clock::now();  // TODO Remove\n    auto prev_now       = NUClear::clock::now();\n\n    while (1) {\n\n        // auto now   = NUClear::clock::now();\n        float time = std::chrono::duration_cast<std::chrono::milliseconds>(NUClear::clock::now() - prev_now).count();\n\n        // utility::io::debug.out(\"PNEUBot is running %lf\\n\", time / 1000);\n\n        one_axis_joint.UpdateVelocity();\n\n        // Sampling time controller to handle the periodicity of the code\n        if (time >= Sampling_time) {  // && time < Sampling_time * 2) {\n            utility::io::gpio::led2 = !utility::io::gpio::led2;\n            prev_now                = NUClear::clock::now();\n            // Time to run our controller again\n            // utility::io::debug.out(\"SP %.2f | \", module::Input::controller.GetPosition());\n\n            one_axis_joint.Compute(module::Input::controller.GetPosition());\n\n            utility::io::adc_io.Start();\n            Error_Handler();\n\n            // utility::io::debug.out(\"%lf ->\\t\", time);\n\n            // utility::io::adc_io.PrintSensors();\n            i++;\n        }\n        // else if (time >= Sampling_time) {\n        //     utility::io::debug.out(\"Too slow %lf\\n\", time);\n        //     Error_Handler();\n        // }\n        if (i >= 500) {\n            time = std::chrono::duration_cast<std::chrono::milliseconds>(NUClear::clock::now() - time_start).count();\n            utility::io::debug.out(\"TIME %lf, Avg %lf\\n\", time, time / 500.0);\n            Error_Handler();\n        }\n    }\n}\n\n// TODO I think this is how the system needs to work\n// Joints know about the muscles, a joint contains all of the muscles it needs to perform. Each muscle has knowledge of\n// its respective sensors, pressure, position. A muscle is responsible for reading it's sensors. The joint compute\n// function then calls the appropriate MPC function and arranges the inputs how the MPC expects. Something like this", "meta": {"hexsha": "82de1eeb728c26fadd5bb3fe8bcdae6ae756b727", "size": 10084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "tayloryoung6396/FYP", "max_stars_repo_head_hexsha": "3ad6589fa67f89d5522510aeea7cfa433530d398", "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": "tayloryoung6396/FYP", "max_issues_repo_head_hexsha": "3ad6589fa67f89d5522510aeea7cfa433530d398", "max_issues_repo_licenses": ["MIT"], "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": "tayloryoung6396/FYP", "max_forks_repo_head_hexsha": "3ad6589fa67f89d5522510aeea7cfa433530d398", "max_forks_repo_licenses": ["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.3697478992, "max_line_length": 156, "alphanum_fraction": 0.5741769139, "num_tokens": 2938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.17223688658700123}}
{"text": "//          Copyright Rein Halbersma 2010-2020.\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 <core/board/sequence.hpp>              // nano, micro, checkers, Roman, spantsiretti, international, frisian, ktar<10, 11>,\n                                                // ktar<10, 12>, Compact_10_12, Compact_12_10, basic_board<12, 10>, canadian, srilankan, dumm\n#include <core/board/transform.hpp>             // is_involution, is_idempotent\n#include <dctl/core/board/basic_board.hpp>      // board\n#include <dctl/core/board/mask.hpp>             // basic_mask\n#include <dctl/core/rules/type_traits.hpp>      // is_empty, is_pushable, is_jumpable, invert\n#include <dctl/core/state/color.hpp>\n#include <boost/range/irange.hpp>               // irange\n#include <boost/test/unit_test.hpp>             // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_SUITE_END, BOOST_AUTO_TEST_CASE, BOOST_AUTO_TEST_CASE_TEMPLATE\n#include <algorithm>                            // all_of\n#include <numeric>                              // accumulate\n#include <type_traits>                          // is_same\n\nBOOST_AUTO_TEST_SUITE(BoardTraits)\n\nusing namespace dctl::core;\n\nBOOST_AUTO_TEST_CASE(IsEmpty)\n{\n        static_assert( is_placeable_v<basic_board<rectangular<1, 1>>>);\n        static_assert( is_placeable_v<basic_board<rectangular<2, 1, 0>>>);\n        static_assert( is_placeable_v<basic_board<rectangular<1, 2, 0>>>);\n}\n\nBOOST_AUTO_TEST_CASE(IsPushable)\n{\n        static_assert(!is_pushable_v<basic_board<rectangular<1, 1>>>);\n        static_assert(!is_pushable_v<basic_board<rectangular<2, 1>>>);\n        static_assert(!is_pushable_v<basic_board<rectangular<1, 2>>>);\n        static_assert(    is_pushable_v<basic_board<rectangular<2, 2>>>);\n}\n\nBOOST_AUTO_TEST_CASE(IsJumpable)\n{\n        static_assert(!is_jumpable_v<basic_board<rectangular<2, 2>>>);\n        static_assert(!is_jumpable_v<basic_board<rectangular<3, 2>>>);\n        static_assert(!is_jumpable_v<basic_board<rectangular<2, 3>>>);\n        static_assert(!is_jumpable_v<basic_board<rectangular<3, 3, 0>>>);\n        static_assert(    is_jumpable_v<basic_board<rectangular<3, 3>>>);\n        static_assert(    is_jumpable_v<basic_board<rectangular<4, 3, 0>>>);\n        static_assert(    is_jumpable_v<basic_board<rectangular<3, 4, 0>>>);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(IsRegular, T, BoardSequence)\n{\n        static_assert(is_placeable_v<T>);\n        static_assert(is_pushable_v<T>);\n        static_assert(is_jumpable_v<T>);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(SquaresCountEqualsBoardSize, T, BoardSequence)\n{\n        using mask_type = basic_mask<T>;\n        BOOST_CHECK_EQUAL(mask_type::squares.ssize(), T::size());\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(ColumnsEquivalencePartitionSquares, T, BoardSequence)\n{\n        auto const files = boost::irange(0, T::width);\n        using mask_type = basic_mask<T>;\n\n        BOOST_CHECK(\n                std::all_of(files.begin(), files.end(), [=](auto i) {\n                        return mask_type::file(black_c, i) == mask_type::file(white_c, T::width - 1 - i);\n                })\n        );\n\n        BOOST_CHECK(\n                std::all_of(files.begin(), files.end(), [=](auto i) {\n                        return std::all_of(files.begin(), files.end(), [=](auto j) {\n                                return i == j ? true : is_disjoint(mask_type::file(white_c, i), mask_type::file(white_c, j));\n                        });\n                })\n        );\n\n        BOOST_CHECK(\n                std::accumulate(files.begin(), files.end(), set_t<mask_type>{}, [](auto result, auto i) {\n                        return result ^ mask_type::file(white_c, i);\n                }) == mask_type::squares\n        );\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(RowsEquivalencePartitionSquares, T, BoardSequence)\n{\n        auto const rows = boost::irange(0, T::height);\n        using mask_type = basic_mask<T>;\n\n        BOOST_CHECK(\n                std::all_of(rows.begin(), rows.end(), [=](auto i) {\n                        return mask_type::rank(black_c, i) == mask_type::rank(white_c, T::height - 1 - i);\n                })\n        );\n\n        BOOST_CHECK(\n                std::all_of(rows.begin(), rows.end(), [=](auto i) {\n                        return std::all_of(rows.begin(), rows.end(), [=](auto j) {\n                                return i == j ? true : is_disjoint(mask_type::rank(white_c, i), mask_type::rank(white_c, j));\n                        });\n                })\n        );\n\n        BOOST_CHECK(\n                std::accumulate(rows.begin(), rows.end(), set_t<mask_type>{}, [](auto result, auto i) {\n                        return result ^ mask_type::rank(white_c, i);\n                }) == mask_type::squares\n        );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c2554923b1ae7f027c39245c41855b1eb83551ce", "size": 4854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/core/board/board_traits.cpp", "max_stars_repo_name": "sagarpant1/dctl", "max_stars_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "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/src/core/board/board_traits.cpp", "max_issues_repo_name": "sagarpant1/dctl", "max_issues_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "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/src/core/board/board_traits.cpp", "max_forks_repo_name": "sagarpant1/dctl", "max_forks_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-27T14:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T14:19:28.000Z", "avg_line_length": 42.2086956522, "max_line_length": 152, "alphanum_fraction": 0.5960032963, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1722368831182616}}
{"text": "//initialization related to ros \n#include \"ros/ros.h\"\n#include \"std_msgs/Byte.h\"\n//#include \"std_msgs/String.h\"\n//#include \"dynamixel_workbench_msgs/DynamixelCommand.h\"\n#include <darknet_ros_msgs/BoundingBoxes.h> \n#include <gb_visual_detection_3d_msgs/BoundingBoxes3d.h>\n#include <python2.7/Python.h>   \n//#include <thread>\n#include <boost/thread/thread.hpp>  //use thread in ros\n\n#define pi 3.141592653589\n\nint pole_tag=0;  \nint pole_tag_flag=1;\nint motor_velocity=-200;\ndouble diameter_wheel= 0.0326;    //m  @\ndouble to_rad_coef=pi/2048;\nbool is_car=false;\nbool is_plastic_person=false;\nbool is_pix_in_tor=false;\nint path_vec_update_flag=0;\nint pole_rel=0;\n\nstd::vector<gb_visual_detection_3d_msgs::BoundingBox3d> detected_bboxes_; //vector\ub85c \ubcc0\ud658 \nstd::vector<std::string> detected_bboxes_class_;\n\ngb_visual_detection_3d_msgs::BoundingBox3d car_box;\ngb_visual_detection_3d_msgs::BoundingBox3d plastic_man_box;\ndouble pix_x,pix_y,pix_z; \nint state_store_flag=1;\nint stay_for_store_flag=0;\nstd::vector<double> pix_car_position(3,0);\nstd::vector<double> toler_pix_car_position(3,0.5); //\uc218\uc815\uac00\ub2a5@\nstd::vector<double> prev_pix_car_position(3,0);\nstd::vector<double> tor_plus_vector(3,0);\nstd::vector<double> tor_minus_vector(3,0);\nstd::vector<int> path_vec;\nstd::array<int,2> pole_num_arr;\nstd::array<int,2> pole_angle_arr;\n\n\ndouble pos,prev_pos,prev_pos_rad,pos_rad,distance,prev_distance;\ndouble toler_distance=0.1;\n\nstd_msgs::Byte savetag;\nstd_msgs::Byte direction_roi;\nstd_msgs::Byte pole_angle;\n\nvoid pole1_callback(const std_msgs::Byte::ConstPtr& msg)\n{\n    if (msg->data==1){pole_tag=1;}\n    else{pole_tag=0;}\n}\nvoid pole2_callback(const std_msgs::Byte::ConstPtr& msg)\n{\n    if (msg->data==1){pole_tag=2;}\n    else{pole_tag=0;}\n}\nvoid pole3_callback(const std_msgs::Byte::ConstPtr& msg)\n{\n    if (msg->data==1){pole_tag=3;}\n    else{pole_tag=0;}\n}\nvoid pole4_callback(const std_msgs::Byte::ConstPtr& msg)\n{\n    if (msg->data==1){pole_tag=4;}\n    else{pole_tag=0;}\n}\n/*\ntemplate<typename T>\nstd::string getType(T) {\n    std::string type = \"unknown\";\n    if (std::is_same<T, int>::value) type = \"int\";\n    if (std::is_same<T, double>::value) type = \"double\";\n    if (std::is_same<T, float>::value) type = \"float\";\n    if (std::is_same<T, bool>::value) type = \"bool\";\n    if (std::is_same<T, std::string>::value) type = \"string\";\n\n    return type;\n}\n\nstd::cout<<getType(detected_bboxes_[i].Class)<<std::endl;\n*/\nvoid detect_box(const gb_visual_detection_3d_msgs::BoundingBoxes3d::ConstPtr& msg)\n{\n    detected_bboxes_ = msg->bounding_boxes;  //BoundingBox3d[]. \uc989, array\ud615\ud0dc\uc774\ub2e4.\n    int size =detected_bboxes_.size();\n    std::string element_to_check_car=\"car\";\n    std::string element_to_check_plastic_man=\"plastic_man\";\n    \n    for(int i=0;i<size;i++)\n    {\n        detected_bboxes_class_.insert(detected_bboxes_class_.begin() + i, detected_bboxes_[i].Class);\n        if(detected_bboxes_[i].Class==\"car\")  \n        {\n            car_box= detected_bboxes_[i];\n        }\n        if(detected_bboxes_[i].Class==\"plastic_man\")  \n        {\n            plastic_man_box= detected_bboxes_[i];\n        }\n    }\n  \n    if (any_of(detected_bboxes_class_.begin(), detected_bboxes_class_.end(), [&](const std::string& elem) { return elem == element_to_check_car; })) \n    {\n        //printf(\"%s is present in the vector\\n\", element_to_check_car.c_str());\n        is_car=true;\n    }\n    else\n    {\n        //printf(\"%s isn't present in the vector\\n\", element_to_check_car.c_str());\n        is_car=false;\n//        car_box.xmax=0; car_box.xmin=0;\n//        car_box.ymax=0; car_box.ymin=0;  \n//        car_box.zmax=0; car_box.zmin=0; \n    }\n\n    if (any_of(detected_bboxes_class_.begin(), detected_bboxes_class_.end(), [&](const std::string& elem) { return elem == element_to_check_plastic_man; })) \n    {\n        //printf(\"%s is present in the vector\\n\", element_to_check_plastic_man.c_str());\n        is_plastic_person=true;\n    }\n    else\n    {\n        //printf(\"%s isn't present in the vector\\n\", element_to_check_plastic_man.c_str());\n        is_plastic_person=false;\n    }\n\n    for(int i=0;i<size;i++)\n    {\n        detected_bboxes_class_.erase(detected_bboxes_class_.begin() + i);\n    }\n}\nbool pix_in_tor(std::vector<double> pix, std::vector<double> prev, std::vector<double> tor)\n{\n    std::vector<double> tor_plus(3,0);\n    std::vector<double> tor_minus(3,0);\n    \n    for(const auto i:prev)\n    {\n        tor_plus[i]=prev[i]+tor[i];\n        tor_minus[i]=prev[i]-tor[i];\n\n        if(tor_minus[i]<pix[i] && pix[i]<tor_plus[i])\n        {\n            is_pix_in_tor=true;\n        }\n    }\n    return is_pix_in_tor;\n}\nvoid thread_save_mode()  \n{\n    ros::NodeHandlePtr n = boost::make_shared<ros::NodeHandle>();\n    ros::Publisher save_pub = n->advertise<std_msgs::Byte>(\"/image_save_tag\", 1000);\n    ros::Rate loop_rate(30);\n    while(ros::ok())\n    {   \n        save_pub.publish(savetag);\n        loop_rate.sleep();\n    }\n}\n\nvoid thread_pole_angle()\n{\n    ros::NodeHandlePtr n = boost::make_shared<ros::NodeHandle>();\n    ros::Publisher pole1_angle_pub = n->advertise<std_msgs::Byte>(\"pole1/pole_angle\", 1000);\n    ros::Publisher pole2_angle_pub = n->advertise<std_msgs::Byte>(\"pole2/pole_angle\", 1000);\n    ros::Publisher pole3_angle_pub = n->advertise<std_msgs::Byte>(\"pole3/pole_angle\", 1000);\n    ros::Publisher pole4_angle_pub = n->advertise<std_msgs::Byte>(\"pole4/pole_angle\", 1000);\n    ros::Publisher direction_roi_pub = n->advertise<std_msgs::Byte>(\"/direction_roi\", 1000);\n    \n    ros::Rate loop_rate(30);\n    while(ros::ok())\n    {   \n        for(int i=0; i<2; i++)\n        {\n            pole_angle.data=pole_angle_arr[i];\n\n            switch(pole_num_arr[i])  \n            {\n                case 2:   \n                    pole1_angle_pub.publish(pole_angle);\n                    break;\n                case 5:\n                    pole2_angle_pub.publish(pole_angle);\n                    break;\n                case 4: \n                    pole3_angle_pub.publish(pole_angle);\n                    break;\n                case 6:\n                    pole4_angle_pub.publish(pole_angle);\n                    break;   \n            }        \n        }\n        direction_roi_pub.publish(direction_roi);\n        loop_rate.sleep();\n    } \n}\nvoid thread_pole_num()  //path_vec\uc758 2\uc694\uc18c\uc529 \uac80\uc0ac.\n{   \n    ros::NodeHandlePtr n = boost::make_shared<ros::NodeHandle>();\n\n    int path_index=0;\n\n    ros::Rate loop_rate(30);\n    while(ros::ok())\n    {\n        if(path_vec_update_flag==1)\n        {\n            if(path_index==path_vec.size()-1)\n            {\n                path_index=0;\n            }\n            pole_num_arr[0]=path_vec[path_index];\n            pole_num_arr[1]=path_vec[path_index+1];\n\n            pole_rel=pole_num_arr[1]-pole_num_arr[0];\n            switch(pole_rel)\n            {\n                case -1:    //left\n                    pole_angle_arr[0]=3;\n                    pole_angle_arr[1]=3;\n                    direction_roi.data=1;\n                    break;\n                case +1:    //right\n                    pole_angle_arr[0]=1;\n                    pole_angle_arr[1]=1;\n                    direction_roi.data=2;\n                    break;\n                case +3:    //up\n                    pole_angle_arr[0]=0;\n                    pole_angle_arr[1]=0;\n                    direction_roi.data=0;\n                    break;\n                case -3:    //down\n                    pole_angle_arr[0]=2;\n                    pole_angle_arr[1]=2;\n                    direction_roi.data=0;\n                    break;\n            }\n            path_index++;\n            path_vec_update_flag=0;\n        }\n        loop_rate.sleep();\n    }\n}\nint main(int argc, char **argv)\n{\n    if(argc>2)\n    {\n        for(int i=1; i<argc; i++)\n        {\n            path_vec.push_back(atoi(argv[i]));\n            //std::cout << path_vec[i-1] << std::endl;\n        }\n    }\n    else\n    {\n        ROS_ERROR(\"Enter a number of points 2 or more. \\n\\n\");\n    }\n    ros::init(argc, argv, \"mobile\");\n    //ros::NodeHandle n; \n    ros::NodeHandlePtr n = boost::make_shared<ros::NodeHandle>();\n\n    ros::Subscriber sub1 = n->subscribe(\"pole1_sensor\", 1000, pole1_callback);\n    ros::Subscriber sub2 = n->subscribe(\"pole2_sensor\", 1000, pole2_callback);\n    ros::Subscriber sub3 = n->subscribe(\"pole3_sensor\", 1000, pole3_callback);\n    ros::Subscriber sub4 = n->subscribe(\"pole4_sensor\", 1000, pole4_callback);\n    ros::Subscriber car_box_sub = n->subscribe(\"/darknet_ros_3d/bounding_boxes\", 1000, detect_box);     \n\n    ros::Rate rate(30);\n    \n    ros::Duration turn_time= ros::Duration(10); //@\n    ros::Duration slow_time= ros::Duration(7);\n    ros::Duration capture_time= ros::Duration(2);\n\n    ros::Time temp_time=ros::Time::now();\n    ros::Time is_car_time=ros::Time::now();\n    ros::Time isnot_car_time=ros::Time::now();\n    ros::Time stored_time=ros::Time::now();\n    ros::Time under_sensor_time=ros::Time::now();\n\n    PyObject *pName,*pValue,*pModule,*SET_VEL, *GET_STATUS, *CLEAR;\n    PyObject *pArgs;\n\n    Py_Initialize();\n    PyRun_SimpleString(\"import sys\");\n    PyRun_SimpleString(\"sys.path.append(\\\"/home/jelly/catkin_ws/src/rosi_controller/script\\\")\");\n    pArgs = PyTuple_New(2);\n\n    pName = PyUnicode_FromString(\"velocity_mode_read_status\");  //PyObject \uc0dd\uc131.\n    pModule = PyImport_Import(pName); //\uc0dd\uc131\ud55c PyObject pName\uc744 import\ud55c\ub2e4.\n\n    SET_VEL = PyObject_GetAttrString(pModule, \"set_vel\"); //\uc2e4\ud589\ud560 \ud568\uc218\ub97c PyObject\uc5d0 \uc804\ub2ec.\n    GET_STATUS = PyObject_GetAttrString(pModule, \"get_status\");\n    CLEAR = PyObject_GetAttrString(pModule, \"clear\");\n    //pValue = PyObject_CallObject(pFunc, NULL); //\ub9e4\uac1c\ubcc0\uc218(pArgs)\ub97c \uc804\ub2ec\ud558\uba70 pFunc\ub97c \ud638\ucd9c\ud55c\ub2e4. \ud604\uc7ac \ub9e4\uac1c\ubcc0\uc218\uac00 NULL\uc778 \uacbd\uc6b0\uc774\ub2e4. return\uac12\uc744 \ubc1b\uc73c\ub824\uba74 PyLong_AsLong\uc744 \uc368\uc57c\ud55c\ub2e4.\n\n    //std::thread t1(thread_save_mode);\n    boost::thread t1(thread_save_mode);\n    boost::thread t2(thread_pole_angle);\n    boost::thread t3(thread_pole_num);\n    \n    \n    /*\n    pValue = PyObject_CallObject(GET_STATUS, NULL);\n    pos = PyLong_AsLong(pValue);    //rad\uc544\ub2c8\ub2e4. 4byte row data(-2,147,483,648 to 2,147,483,647)\uc774\ub2e4.\n    prev_pos_rad = pos*to_rad_coef; \n    double prev_degree=prev_pos_rad*(180/pi);\n    */ \n    while(ros::ok())\n    {\n        /*\n        pValue = PyObject_CallObject(GET_STATUS, NULL);\n        pos = PyLong_AsLong(pValue);    //rad\uc544\ub2c8\ub2e4. 4byte row data(-2,147,483,648 to 2,147,483,647)\uc774\ub2e4.\n        pos_rad = pos*to_rad_coef; \n        int degree=pos_rad*(180/pi);\n        degree=degree-prev_degree;\n\n        printf(\"%d \\n\", degree);\n        if(0<=degree%360&&degree%360<=5)\n        {\n            PyTuple_SetItem(pArgs, 0, PyLong_FromLong(0)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(0));\n            PyObject_CallObject(SET_VEL, pArgs);\n            ros::Duration(3).sleep();\n        }\n        */\n        if(pole_tag==1 && pole_tag_flag==1)\n        {\n\t        ROS_INFO(\"pole1_taged! \\n\");\n            under_sensor_time=ros::Time::now();\n            path_vec_update_flag=1;\n\n            PyTuple_SetItem(pArgs, 0, PyLong_FromLong(0)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(0));\n            PyObject_CallObject(SET_VEL, pArgs); \n            turn_time.sleep();  //10\ucd08 \ub300\uae30\n            pValue = PyObject_CallObject(GET_STATUS, NULL);\n            prev_pos = PyLong_AsLong(pValue);\n            prev_pos_rad = prev_pos*to_rad_coef;\n\n            pole_tag_flag=0;\n        }\n        else if(pole_tag==2 && pole_tag_flag==1)  //\ub3c4\ucc29\uc2dc \uc815\uc9c0.\n        {\n\t        ROS_INFO(\"pole2_taged! \\n\");\n            under_sensor_time=ros::Time::now();\n            path_vec_update_flag=1;\n\n            PyTuple_SetItem(pArgs, 0, PyLong_FromLong(0)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(0));\n            PyObject_CallObject(SET_VEL, pArgs); \n            turn_time.sleep();  //10\ucd08 \ub300\uae30\n            pValue = PyObject_CallObject(GET_STATUS, NULL);\n            prev_pos = PyLong_AsLong(pValue);\n            prev_pos_rad = prev_pos*to_rad_coef;\n\n            pole_tag_flag=0;\n        }\n        else if(pole_tag==3 && pole_tag_flag==1)  //\ub3c4\ucc29\uc2dc \uc815\uc9c0.\n        {\n\t        ROS_INFO(\"pole3_taged! \\n\");\n            under_sensor_time=ros::Time::now();\n            path_vec_update_flag=1;\n\n            PyTuple_SetItem(pArgs, 0, PyLong_FromLong(0)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(0));\n            PyObject_CallObject(SET_VEL, pArgs); \n            turn_time.sleep();  //10\ucd08 \ub300\uae30\n            pValue = PyObject_CallObject(GET_STATUS, NULL);\n            prev_pos = PyLong_AsLong(pValue);\n            prev_pos_rad = prev_pos*to_rad_coef;\n\n            pole_tag_flag=0;\n        }\n        else if(pole_tag==4 && pole_tag_flag==1)  //\ub3c4\ucc29\uc2dc \uc815\uc9c0.\n        {\n\t        ROS_INFO(\"pole4_taged! \\n\");\n            under_sensor_time=ros::Time::now();\n            path_vec_update_flag=1;\n\n            PyTuple_SetItem(pArgs, 0, PyLong_FromLong(0)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(0));\n            PyObject_CallObject(SET_VEL, pArgs); \n            turn_time.sleep();  //10\ucd08 \ub300\uae30\n            pValue = PyObject_CallObject(GET_STATUS, NULL);\n            prev_pos = PyLong_AsLong(pValue);\n            prev_pos_rad = prev_pos*to_rad_coef;\n\n            pole_tag_flag=0;\n        }\n        else\n        {\n            //default \n            PyTuple_SetItem(pArgs, 0, PyLong_FromLong(motor_velocity)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(-motor_velocity));\n            PyObject_CallObject(SET_VEL, pArgs);\n\n            if(ros::Time::now()-under_sensor_time>ros::Duration(18))\n            {\n                pole_tag_flag=1;  //sensor\ub97c \ubc97\uc5b4\ub09c\uc9c0 3\ucd08\uac00 \uc9c0\ub0ac\uc744 \ub54c \ucf20\ub2e4. \ub108\ubb34 \uc9e7\uc73c\uba74 \ubcc0\uacbd\ud574\uc57c \ud568.@\n            }\n\n            if(is_car==true && (pole_rel==1 || pole_rel==-1))\n            {\n                is_car_time=ros::Time::now(); //current_time -> is_car_time\uc73c\ub85c \ubc14\uafc8. @\n\n                while(is_car_time-isnot_car_time<ros::Duration(9))\n                {\n                    PyTuple_SetItem(pArgs, 0, PyLong_FromLong(motor_velocity/2)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(-motor_velocity/2));\n                    PyObject_CallObject(SET_VEL, pArgs);\n                    slow_time.sleep();      //7\ucd08 \ub300\uae30 \n                    PyTuple_SetItem(pArgs, 0, PyLong_FromLong(0)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(0));\n                    PyObject_CallObject(SET_VEL, pArgs);\n                    capture_time.sleep();   //2\ucd08 \ub300\uae30 \n                    \n                    //store previous pixel coordinate\n                    pix_car_position[0]=(car_box.xmax+car_box.xmin)/2.0;   \n                    pix_car_position[1]=(car_box.ymax+car_box.ymin)/2.0;\n                    pix_car_position[2]=(car_box.zmax+car_box.zmin)/2.0;\n                \n                    is_car_time=ros::Time::now();\n                    rate.sleep();\n                    ros::spinOnce();\n                }\n\n                if(state_store_flag==1)  //store state.\n                {\n                    stored_time=ros::Time::now();\n                \n                    prev_pix_car_position=pix_car_position;\n                    //printf(\"x: %f y: %f z: %f \\n\",pix_car_position[0], pix_car_position[1] ,pix_car_position[2]);    \n\n                    //store previous distance\n                    pValue = PyObject_CallObject(GET_STATUS, NULL);\n                    pos = PyLong_AsLong(pValue);   \n\n                    pos_rad = pos*to_rad_coef;      \n                    distance=(pos_rad-prev_pos_rad)*diameter_wheel*pi;    //m\n                    printf(\"distance %f \\n\",distance);\n\n                    prev_distance=distance;\n\n                    savetag.data=1;\n                    state_store_flag=0;\n                }\n                else   //\ube44\uad50\n                {\n                    //store present position\n                    pValue = PyObject_CallObject(GET_STATUS, NULL);\n                    pos = PyLong_AsLong(pValue);\n                    pos_rad = pos*to_rad_coef;\n                    distance=(pos_rad-prev_pos_rad)*diameter_wheel*pi;    //m\n                    \n                    is_pix_in_tor=pix_in_tor(pix_car_position,prev_pix_car_position,toler_pix_car_position);\n                    \n                    if(prev_distance-toler_distance<distance<prev_distance+toler_distance && \\\n                    is_pix_in_tor && (ros::Time::now()-stored_time)>ros::Duration(5))\n                    {\n                        stored_time=ros::Time::now();\n                        prev_pix_car_position=pix_car_position;\n                        prev_distance=distance;\n\n                        savetag.data=2;  \n                        stay_for_store_flag=1; \n                        is_pix_in_tor=false; \n                    }\n                }  \n            }\n            else\n            {   \n                temp_time=ros::Time::now();\n\n                if(temp_time-is_car_time>ros::Duration(1))\n                {\n                    isnot_car_time=ros::Time::now();\n                    savetag.data=0;\n                    if(stay_for_store_flag==1)\n                    {\n                        state_store_flag=1;\n                        stay_for_store_flag=0;\n                    }\n                }\n            }\n        }\n\n        rate.sleep();\n        ros::spinOnce();\n    }\n    \n    PyObject_CallObject(CLEAR, NULL);\n    Py_Finalize();\n\n    t1.join();\n    t2.join();\n    t3.join();\n    return 0;\n}\n", "meta": {"hexsha": "33af2bc16b4882fdb78c551b323761e094e62c87", "size": 17098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "final/rosi_controller/src/mobile_tolerance.cpp", "max_stars_repo_name": "songdaegeun/school-zone-enforcement-system", "max_stars_repo_head_hexsha": "b5680909fd5a348575563534428d2117f8dc2e3f", "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": "final/rosi_controller/src/mobile_tolerance.cpp", "max_issues_repo_name": "songdaegeun/school-zone-enforcement-system", "max_issues_repo_head_hexsha": "b5680909fd5a348575563534428d2117f8dc2e3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "final/rosi_controller/src/mobile_tolerance.cpp", "max_forks_repo_name": "songdaegeun/school-zone-enforcement-system", "max_forks_repo_head_hexsha": "b5680909fd5a348575563534428d2117f8dc2e3f", "max_forks_repo_licenses": ["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.5414141414, "max_line_length": 157, "alphanum_fraction": 0.5731079658, "num_tokens": 4504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.17223687964952197}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <string>\n#include <boost/program_options.hpp>\n\n#include \"msa.hpp\"\n#include \"model.hpp\"\n#include \"MCseq.hpp\"\n#include \"OptParam.hpp\"\nusing namespace std;\n\nnamespace po = boost::program_options;\n\nint main(int argc, char *argv[])\n{\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\",\"produce help message\")\n    (\"dos\", po::value<string>(), \"WL DOS file\")\n    (\"param,p\", po::value<string>(), \"LGM parameter file\")\n    (\"logbase,l\", po::value<string>(), \"basename for log files\")\n    (\"nsweep\", po::value<int>(), \"number of sweeps\")\n    (\"nloop\", po::value<int>(), \"number of loops\")\n    (\"mu_len\", po::value<double>(), \"Mu_len\")\n    (\"mu_I\", po::value<double>(), \"Mu_I\")\n    (\"traj,t\", po::value<bool>(), \"save trajectory in 'LOGBASE.traj' or not\")\n    (\"seed\", po::value<int>(), \"random seed\")\n    (\"ntraj\", po::value<int>(), \"interval for saving trajectory\")\n    (\"temp_max\", po::value<double>(), \"highest temperature\")\n    (\"min_cnt\", po::value<int>(), \"minimum count for each bin\")\n    ;\n\n  po::positional_options_description p;\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc,argv).\n\t    options(desc).positional(p).run(), vm);\n  po::notify(vm);\n\n  if(vm.count(\"help\")) {\n    cout << desc << endl;\n    return 1;\n  }\n\n  string logbase = \"wldos\";\n  if(vm.count(\"logbase\")) {\n    logbase = vm[\"logbase\"].as<string>();\n  }\n  cerr << \"# LOGBASE= \" << logbase << endl;\n\n  Model model;\n  if(vm.count(\"param\")) {\n    model.read_parameters(vm[\"param\"].as<string>());\n  } else {\n    cerr << \"Specify the parameter file!\" << endl;\n    exit(1);\n  }\n  if(vm.count(\"mu_len\")) {\n    const double mu_len  = vm[\"mu_len\"].as<double>();\n    cerr << \"Mu_len = \" << mu_len << endl;\n    model.set_mu_len(mu_len);\n  }\n  if(vm.count(\"mu_I\")) {\n    const double mu_I  = vm[\"mu_I\"].as<double>();\n    cerr << \"Mu_I = \" << mu_I << endl;\n    model.set_mu_lenI(mu_I);\n  }\n\n  double tmax=1.2;\n  if(vm.count(\"temp_max\")) {\n    tmax = (vm[\"temp_max\"].as<double>());\n  }\n\n  int min_cnt = 1000;\n  if(vm.count(\"min_cnt\")) {\n    min_cnt = (vm[\"min_cnt\"].as<int>());\n  }\n  cerr << \"Minimum count for convergence: \" << min_cnt << endl;\n  \n  MCseq mcs(model);\n  if(vm.count(\"seed\")) {\n    mcs.set_seed(vm[\"seed\"].as<int>());\n    cerr << \"random seed= \" << (vm[\"seed\"].as<int>()) << endl;;\n  }\n    \n  int nsweeps = 100000;\n  if(vm.count(\"nsweep\")) {\n    nsweeps = vm[\"nsweep\"].as<int>();\n  }\n  int nloops = 100;\n  if(vm.count(\"nloop\")) {\n    nloops = vm[\"nloop\"].as<int>();\n  }\n\n  mcs.NTRAJ = 1;\n  if(vm.count(\"ntraj\")) {\n    mcs.NTRAJ = vm[\"ntraj\"].as<int>();\n  }\n  cerr << \"Saving trajectory for every \" << mcs.NTRAJ\n       << \" sweeps\" << endl;\n\n  mcs.NMONITOR = 10000; //nsweeps / 10 ;\n  mcs.setup_WL(0,0,0.1);\n  if(vm.count(\"dos\")) {\n    mcs.read_DOS(vm[\"dos\"].as<string>(), true);\n    cerr << \"Reading DOS file: \" << vm[\"dos\"].as<string>() << endl;;\n  } else {\n    cerr << \"Specify the DOS file with the '--dos' option!!\" << endl;\n    exit(1);\n  }\n\n  if(vm.count(\"traj\")) {\n    const string ftraj = logbase + \".traj\";\n    cerr << \"# Trajectory saved to \" <<  ftraj << endl;\n    mcs.set_trajectory_file(ftraj);\n  }\n  const clock_t begin_time = clock();\n  cerr << \"# WL sampling run for \"\n       << nsweeps << \" sweeps.\" << endl;\n\n  int iloop,isweeps;\n  mcs.gibbs_sampler_p = false;\n\n  mcs.init_stats(model);\n  mcs.stats_full_nonbonded = false;\n  for(int iloop = 0; iloop != nloops; ++iloop) {\n    cerr << \"#Loop: \" << iloop << endl;\n    mcs.trajectory_p = false;\n    mcs.select_type = CANONICAL;\n    mcs.set_random_sequence(model);\n    mcs.set_temperature(tmax);\n    mcs.run(model, 1000, false);\n    mcs.set_temperature(1.0);\n    while(1) {\n      mcs.run(model, 10, false);\n      if(mcs.Energy > mcs.MIN_ENERGY && mcs.Energy < mcs.MAX_ENERGY) break;\n    }\n    mcs.select_type = MULTI_CANONICAL;\n    isweeps = mcs.run(model, 1000, false);\n    mcs.trajectory_p = true;\n    isweeps = mcs.run(model, nsweeps, true);\n    const int traj_min_cnt = mcs.traj_min_count();\n    if(traj_min_cnt > min_cnt) {\n      cerr << \"Multicanonical sampling converged in loop: \" << iloop << endl;\n      break;\n    }\n  }\n  mcs.finish_stats(model);\n  const clock_t end_time = clock();\n  cerr << \"Time \" << float(end_time - begin_time)/CLOCKS_PER_SEC << endl;\n\n  if(vm.count(\"traj\")) {\n    mcs.unset_trajectory_file();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "bf6a92610233e628d4ed001b960e77f0ffd52602", "size": 4397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lgm_wlsamp.cpp", "max_stars_repo_name": "arkinjo/lgm_mc", "max_stars_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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": "src/lgm_wlsamp.cpp", "max_issues_repo_name": "arkinjo/lgm_mc", "max_issues_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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": "src/lgm_wlsamp.cpp", "max_forks_repo_name": "arkinjo/lgm_mc", "max_forks_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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": 27.8291139241, "max_line_length": 77, "alphanum_fraction": 0.5940413919, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.17212553596673608}}
{"text": "#define BOOST_PYTHON_STATIC_LIB\n#include <boost/python/list.hpp>\n#include <boost/python/extract.hpp>\n#include <boost/python/object_attributes.hpp>\n#include \"DFSPolicy.h\"\n#include \"FileTools.h\"\n\nusing namespace BOSS;\nnamespace python = boost::python;\n\nDFSPolicy::DFSPolicy(const CombatSearchParameters p,\n    const std::string & dir, const std::string & prefix, const std::string & name)\n    : CombatSearch_Integral(p, dir, prefix, name)\n{\n\n}\n\nvoid DFSPolicy::recurse(const GameState & state, int depth)\n{\n    m_highestValueFound = recurseReturnValue(state, depth);\n    m_results.buildOrder = m_integral.getBestBuildOrder();\n}\n\nFracType DFSPolicy::recurseReturnValue(const GameState & state, int depth)\n{\n    if (timeLimitReached())\n    {\n        throw BOSS_COMBATSEARCH_TIMEOUT;\n    }\n\n    updateResults(state);\n\n    FracType nodeIntegralToThisPoint = m_integral.getCurrentStackValue();\n    FracType nodeIntegralValue = nodeIntegralToThisPoint;\n    bool ffCalculated = false;\n    bool isLeafNode = true;\n\n    ActionSetAbilities legalActions;\n    generateLegalActions(state, legalActions, m_params);\n    if (legalActions.size() > 0)\n    {\n        std::cout << \"at depth: \" << depth << std::endl;\n        auto actionProbabilities = evaluateState(state, legalActions);\n        std::sort(actionProbabilities.begin(), actionProbabilities.end(),\n            [](const ActionValue & lhs, const ActionValue & rhs) { return lhs.evaluation > rhs.evaluation; });\n\n        for (int index = 0; index < actionProbabilities.size(); ++index)\n        {\n            GameState child(state);\n\n            auto action = actionProbabilities[index].action;\n\n            if (action.first.isAbility())\n            {\n                child.doAbility(action.first, action.second);\n                m_buildOrder.add(action.first, child.getLastAbility());\n            }\n            else\n            {\n                child.doAction(action.first);\n                m_buildOrder.add(action.first);\n            }\n\n            //std::cout << \"action added: \" << action.getName() << std::endl;\n            //std::cout << \"target of action added: \" << actionTarget << std::endl;\n            //std::cout << \"frame of action added: \" << child.getCurrentFrame() << std::endl;\n\n            m_integral.update(child, m_buildOrder, m_params, m_searchTimer, true);\n            isLeafNode = false;\n\n            nodeIntegralValue = std::max(nodeIntegralValue, recurseReturnValue(child, depth + 1));\n\n            m_buildOrder.pop_back();\n            m_integral.popFinishedLastOrder(state, child);\n        }\n\n        if (m_params.getSaveStates())\n        {\n            state.writeToSS(m_ssStates, m_params);\n            m_ssStates << \",\" << nodeIntegralValue - nodeIntegralToThisPoint << \"\\n\";\n            //json stateValuePair;\n            //stateValuePair[\"State\"] = state.writeToJson(m_params);\n            //stateValuePair[\"Value\"] = nodeIntegralValue - nodeIntegralToThisPoint;\n            //std::vector<std::uint8_t> v_msgpack = json::to_msgpack(stateValuePair);\n            //m_jStates.insert(m_jStates.end(), v_msgpack.begin(), v_msgpack.end());\n            m_statesWritten++;\n\n            if (m_statesWritten % 1000000 == 0)\n            {\n                FileTools::MakeDirectory(CONSTANTS::ExecutablePath + \"/SavedStates\");\n                //std::ofstream fileStates(CONSTANTS::ExecutablePath + \"/SavedStates/\" + m_name + \"_\" + std::to_string(m_filesWritten) + \".csv\", std::ofstream::out | std::ofstream::app | std::ofstream::binary);\n                std::ofstream fileStates(CONSTANTS::ExecutablePath + \"/SavedStates/\" + m_name + \".csv\", std::ofstream::out | std::ofstream::app | std::ofstream::binary);\n                fileStates << m_ssStates.rdbuf();\n                m_ssStates.str(std::string());\n                m_ssStates.clear();\n                //fileStates.write(reinterpret_cast<const char*>(m_jStates.data()), m_jStates.size());\n                //m_jStates.clear();\n                m_filesWritten++;\n            }\n        }\n    }\n\n\n    if (nodeIntegralValue > highestValueThusFar)\n    {\n        highestValueThusFar = nodeIntegralValue;\n        m_ssHighestValue << m_results.nodesExpanded << \",\" << highestValueThusFar << \"\\n\";\n    }\n\n    if (isLeafNode)\n    {\n        m_results.leafNodesExpanded++;\n    }\n\n    //std::cout << \"Value to this point: \" << nodeIntegralToThisPoint << \". Total value: \" << nodeIntegralValue << std::endl;\n    //std::cout << nodeIntegralValue << std::endl;\n\n    return nodeIntegralValue;\n}\n\nstd::vector<ActionValue> DFSPolicy::evaluateState(const GameState & state, ActionSetAbilities & legalActions)\n{\n\n    std::stringstream ss;\n    state.writeToSS(ss, m_params);\n\n    std::vector<ActionValue> actionValues;\n\n    // evaluate the states. the results will be returned as a list of FracTypes\n    python::object values = CONSTANTS::Predictor.attr(\"predict\")(ss.str().c_str());\n\n    BOSS_ASSERT(len(values) == 69, \"size of values %i does not match the size of Protoss actions 69\", len(values));\n\n    std::cout << std::endl;\n    std::cout << \"current frame: \" << state.getCurrentFrame() << std::endl;\n    for (int i = 0; i < len(values); ++i)\n    {\n        for (auto & action : legalActions)\n        {\n            if (action.first.getID() == i)\n            {\n                ActionValue av;\n                av.evaluation = python::extract<FracType>(values[i]);\n                av.action = action;\n                actionValues.push_back(av);\n\n                std::cout << action.first.getName() << \": network: \" << av.evaluation << std::endl;\n                break;\n            }\n        }\n    }\n    std::cout << std::endl;\n\n    BOSS_ASSERT(actionValues.size() == legalActions.size(), \"Size of actionValues %i does not match the size of legalActions %i\", actionValues.size(), legalActions.size());\n\n    return actionValues;\n}\n", "meta": {"hexsha": "1c93acd6ddf6c3d83b574316206a20da4ff15370", "size": 5817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/old/DFSPolicy.cpp", "max_stars_repo_name": "ArtaSeify/BOSS-SC2", "max_stars_repo_head_hexsha": "a86db4bcb1cd0a9cfd71c4583ccb9bd87c0cb415", "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/DFSPolicy.cpp", "max_issues_repo_name": "ArtaSeify/BOSS-SC2", "max_issues_repo_head_hexsha": "a86db4bcb1cd0a9cfd71c4583ccb9bd87c0cb415", "max_issues_repo_licenses": ["MIT"], "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/DFSPolicy.cpp", "max_forks_repo_name": "ArtaSeify/BOSS-SC2", "max_forks_repo_head_hexsha": "a86db4bcb1cd0a9cfd71c4583ccb9bd87c0cb415", "max_forks_repo_licenses": ["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.8164556962, "max_line_length": 210, "alphanum_fraction": 0.6138903215, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.17212553596673602}}
{"text": "#pragma once\n\n#include \"../frontend/QF_BV.hpp\"\n#include <boost/proto/transform.hpp>\n#include \"rewrite.hpp\"\n\n\nnamespace metaSMT {\n  namespace transform {\n    namespace proto = boost::proto;\n\n    struct fmiToQF_BV;\n\n    struct fmiToQF_BV_c\n    {\n      // The primary template matches nothing:\n      template<typename Tag>\n        struct case_\n        : proto::nary_expr<proto::_, proto::vararg<fmiToQF_BV> >\n        {};\n    };\n\n    template<>\n    struct fmiToQF_BV_c::case_<proto::tag::terminal>\n      : proto::_ \n    {};\n\n    struct make_bvand: proto::callable\n    {\n        template<typename Sig>\n        struct result;\n    \n        template<typename This, typename Left, typename Right>\n        struct result<This(Left, Right)>\n        // this class provides ::type\n        : boost::proto::result_of::make_expr< \n              logic::QF_BV::tag::bvand_tag\n            , logic::QF_BV::QF_BV_Domain\n            , Left\n            , Right\n          >\n        {};\n    \n        template<typename Left, typename Right>\n        typename make_bvand::result<make_bvand(Left,Right)>::type \n        operator()(Left const & left, Right const & right) const\n        {\n            return boost::proto::make_expr<logic::QF_BV::tag::bvand_tag, logic::QF_BV::QF_BV_Domain>( left, right);\n        }\n    };\n\n   \n#define TRANSLATE_FMI_QF_BV( tag1, tag2) \\\n    template<>\\\n    struct fmiToQF_BV_c::case_<tag1>\\\n      : proto::call< \\\n          proto::functional::make_expr<tag2>( \\\n                fmiToQF_BV(proto::_left)\\\n              , fmiToQF_BV(proto::_right)\\\n            )>\\\n    {};\n\n    TRANSLATE_FMI_QF_BV( proto::tag::bitwise_and,    logic::QF_BV::tag::bvand_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::bitwise_or,     logic::QF_BV::tag::bvor_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::bitwise_xor,    logic::QF_BV::tag::bvxor_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::equal_to,       logic::tag::equal_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::not_equal_to,   logic::tag::nequal_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::modulus_assign, logic::tag::equal_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::shift_left,     logic::QF_BV::tag::bvshl_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::shift_right,    logic::QF_BV::tag::bvshr_tag)\n\n    TRANSLATE_FMI_QF_BV( proto::tag::plus,           logic::QF_BV::tag::bvadd_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::multiplies,     logic::QF_BV::tag::bvmul_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::minus,          logic::QF_BV::tag::bvsub_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::divides,        logic::QF_BV::tag::bvudiv_tag)\n    TRANSLATE_FMI_QF_BV( proto::tag::modulus,        logic::QF_BV::tag::bvurem_tag)\n\n#undef TRANSLATE_FMI_QF_BV\n\n    template<>\n    struct fmiToQF_BV_c::case_<proto::tag::complement>\n      : proto::call<\n          proto::functional::make_expr<logic::QF_BV::tag::bvnot_tag>(\n                fmiToQF_BV(proto::_left)\n            )>\n    {};\n\n    template<>\n    struct fmiToQF_BV_c::case_<proto::tag::negate>\n      : proto::call<\n          proto::functional::make_expr<logic::QF_BV::tag::bvneg_tag>(\n                fmiToQF_BV(proto::_left)\n            )>\n    {};\n\n    struct fmiToQF_BV : proto::switch_< fmiToQF_BV_c > {};\n  \n  } /* transform */\n} /* metaSMT */\n\n\n// vim: tabstop=2 shiftwidth=2 expandtab\n", "meta": {"hexsha": "7be75aa2165c391f338efcaadf8cbf1433868a5d", "size": 3251, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/metaSMT/transform/fmiToQF_BV.hpp", "max_stars_repo_name": "finnhaedicke/metaSMT", "max_stars_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-09T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:55:58.000Z", "max_issues_repo_path": "src/metaSMT/transform/fmiToQF_BV.hpp", "max_issues_repo_name": "finnhaedicke/metaSMT", "max_issues_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-03-13T14:21:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T07:59:34.000Z", "max_forks_repo_path": "src/metaSMT/transform/fmiToQF_BV.hpp", "max_forks_repo_name": "finnhaedicke/metaSMT", "max_forks_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-04-22T18:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T12:44:12.000Z", "avg_line_length": 31.5631067961, "max_line_length": 115, "alphanum_fraction": 0.6161181175, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.17212553258922508}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <range/v3/all.hpp>\n\n#include <sqlite3.h>\n\n#include \"graphviz_interface.hpp\"\n\n#include \"DiGraph.hpp\"\n#include \"Tran_Mat_Cell.hpp\"\n#include <fmt/format.h>\n#include <nlohmann/json.hpp>\n\n#ifdef TIME\n  #include \"CSVWriter.hpp\"\n#endif\n\nconst double tuning_param = 1.0;\n\nenum InitialBeta { ZERO, ONE, HALF, MEAN, MEDIAN, PRIOR, RANDOM };\n//enum class InitialBeta : char { ZERO, ONE, HALF, MEAN, MEDIAN, PRIOR, RANDOM };\nenum InitialDerivative { DERI_ZERO, DERI_PRIOR };\n\ntypedef std::unordered_map<std::string, std::vector<double>>\n    AdjectiveResponseMap;\n\n// This is a multimap to keep provision to have multiple observations per\n// time point per indicator.\n// Access (concept is a vertex in the CAG)\n// [ concept ][ indicator ][ epoch --\u2192 observation ]\ntypedef std::vector<std::vector<std::multimap<long, double>>>\n    ConceptIndicatorData;\n\n// Keeps the sequence of dates for which data points are available\n// Data points are sorted according to dates\n// Access:\n// [ concept ][ indicator ][epoch]\ntypedef std::vector<std::vector<long>> ConceptIndicatorEpochs;\n\n// Access\n// [ timestep ][ concept ][ indicator ][ observation ]\ntypedef std::vector<std::vector<std::vector<std::vector<double>>>>\n    ObservedStateSequence;\n\ntypedef std::vector<std::vector<std::vector<double>>>\n    PredictedObservedStateSequence;\n\ntypedef std::pair<std::tuple<std::string, int, std::string>,\n                  std::tuple<std::string, int, std::string>>\n    CausalFragment;\n\n// { concept_name --> (ind_name, [obs_0, obs_1, ... ])}\ntypedef std::unordered_map<std::string,\n                           std::pair<std::string, std::vector<double>>>\n    ConceptIndicatorAlignedData;\n\ntypedef std::tuple<std::vector<std::string>, std::vector<int>, std::string>\n    EventCollection;\n\ntypedef std::pair<EventCollection, EventCollection>\n    CausalFragmentCollection;\n\n// Access\n// [ sample ][ time_step ]{ vertex_name --> { indicator_name --> pred}}\n// [ sample ][ time_step ][ vertex_name ][ indicator_name ]\ntypedef std::vector<std::vector<\n    std::unordered_map<std::string, std::unordered_map<std::string, double>>>>\n    FormattedPredictionResult;\n\n// Access\n// [ vertex_name ][ timestep ][ sample ]\ntypedef std::unordered_map<std::string, std::vector<std::vector<double>>>\n    FormattedProjectionResult;\n\n// Access\n// get<0>:\n//      Training range\n//      <<start_year, start_month>, <end_year, end_month>>\n// get<1>:\n//      Sequence of prediction time steps\n//      [yyyy-mm\u2080, yyyy-mm\u2081, yyyy-mm\u2082, yyyy-mm\u2083, .....]\n// get<2>:\n//      Prediction results\n//      [ sample ][ time_step ]{ vertex_name --> { indicator_name --> pred}}\n//      [ sample ][ time_step ][ vertex_name ][ indicator_name ]\ntypedef std::tuple<std::pair<std::pair<int, int>, std::pair<int, int>>,\n                   std::vector<std::string>,\n                   FormattedPredictionResult>\n    Prediction;\n\n// Format AnalysisGraph state to output\n// [ concept name ] --> [ ind1, ind2, ... ]\ntypedef std::unordered_map<std::string, std::vector<std::string>> ConceptIndicators;\n\n// List of edges [(source, target), ...]\ntypedef std::vector<std::pair<std::string, std::string>> Edges;\n\n// List of adjectives [(source, target), ...]\ntypedef std::vector<std::pair<std::string, std::string>> Adjectives;\n\n// List of polarities [(source, target), ...]\ntypedef std::vector<std::pair<int, int>> Polarities;\n\n// Vector of theta priors and samples pairs for each edge\n// Ordering is according to order of edges in Edges data vector\n// For each edge, there is a tuple of vectors\n// first element of the tuple is a vector of theta priors KDEs\n// second element of the tuple is a vector of sampled thetas\n// [([p1, p1, ...], [s1, s2, ...]), ... ]\n// Each tuple: <dataset, sampled thertas, log prior histogram>\n// TODO: remove dataset and convert this to a pair\n//typedef std::vector<std::pair<std::vector<double>, std::vector<double>>> Thetas;\ntypedef std::vector<std::tuple<std::vector<double>, std::vector<double>, std::vector<double>>> Thetas;\n\n// Sampled Derivatives for each concept\n// Access\n// [ concept name ] --> [s_1, s_2, ..., s_res ]\ntypedef std::unordered_map<std::string, std::vector<double>> Derivatives;\n\n// Data\n// Access\n// [ indicator name ] --> {\n//                           [ \"Time Step\" ] --> [ts1, ts2, ...]\n//                           [ \"Data\" ]      --> [ d1,  d2, ...]\n//                        }\ntypedef std::unordered_map<std::string, std::unordered_map<std::string, std::vector<double>>> Data;\n\n// Predictions\n// Access\n// [ indicator name ] --> {\n//                           [ ts ] --> [p_1, p_2, p_3, ..., p_res]\n//                        }\ntypedef std::unordered_map<std::string, std::unordered_map<int, std::vector<double>>> Predictions;\n\ntypedef std::unordered_map<std::string, std::unordered_map<std::string, std::vector<double>>>\n    CredibleIntervals;\n\ntypedef std::tuple<\n    ConceptIndicators,\n    Edges, // List of edges [(source, target), ...]\n    Adjectives,\n    Polarities,\n    // Theta priors and samples for each edge\n    // [(priors, samples), ... ]\n    Thetas,\n    Derivatives,\n    // Data year month range\n    //std::vector<std::string>,\n    std::vector<long>,\n    // Data\n    Data,\n    // Prediction year month range\n    //std::vector<std::string>,\n    std::vector<double>,\n    Predictions,\n    CredibleIntervals,\n    // Log likelihoods\n    std::vector<double>,\n    int // Number of bins in theta prior distributions\n            > CompleteState;\n\n// Access\n// [prediction time step] -->\n//      get<0>:\n//          concept name\n//      get<1>\n//          indicator name\n//      get<2>\n//          value\ntypedef std::unordered_map<int, std::vector<std::tuple<std::string,\n        std::string, double>>> ConstraintSchedule;\n\ntypedef boost::graph_traits<DiGraph>::edge_descriptor EdgeDescriptor;\ntypedef boost::graph_traits<DiGraph>::edge_iterator EdgeIterator;\n\ntypedef std::multimap<std::pair<int, int>, std::pair<int, int>>::iterator\n    MMapIterator;\n\nAdjectiveResponseMap construct_adjective_response_map(size_t n_kernels);\n\n/**\n * The AnalysisGraph class is the main model/interface for Delphi.\n */\nclass AnalysisGraph {\n\n  private:\n  #ifdef TIME\n    std::pair<std::vector<std::string>, std::vector<long>> durations;\n    std::pair<std::vector<std::string>, std::vector<long>> mcmc_part_duration;\n    CSVWriter writer;\n    std::string timing_file_prefix = \"\";\n    int timing_run_number = 0;\n  #endif\n\n  // True only when Delphi is run through the CauseMos HMI.\n  bool causemos_call = false;\n\n  DiGraph graph;\n\n\n  // Handle to the random number generator singleton object\n  RNG* rng_instance = nullptr;\n\n  std::mt19937 rand_num_generator;\n\n\n  // Uniform distribution used by the MCMC sampler\n  std::uniform_real_distribution<double> uni_dist;\n\n  // Normal distribution used to perturb \u03b2\n  std::normal_distribution<double> norm_dist;\n\n  // Uniform discrete distributions used by the MCMC sampler\n  // to perturb the initial latent state\n  std::uniform_int_distribution<int> uni_disc_dist;\n  // to sample an edge\n  std::uniform_int_distribution<int> uni_disc_dist_edge;\n\n  // Sampling resolution\n  size_t res;\n\n  // Number of KDE kernels\n  size_t n_kde_kernels = 1000;\n\n  /*\n   ============================================================================\n   Meta Data Structures\n   ============================================================================\n  */\n\n  // Maps each concept name to the vertex id of the\n  // vertex that concept is represented in the CAG\n  // concept name --> CAG vertex id\n  std::unordered_map<std::string, int> name_to_vertex = {};\n\n  // Keeps track of indicators in CAG to ensure there are no duplicates.\n  std::unordered_set<std::string> indicators_in_CAG;\n\n  // A_beta_factors is a 2D array (std::vector of std::vectors) that keeps track\n  // of the \u03b2 factors involved with each cell of the transition matrix A.\n  //\n  // According to our current model, which uses variables and their partial\n  // derivatives with respect to each other ( x --> y, \u03b2xy = \u2202y/\u2202x ),\n  // at most half of the transition matrix cells can be affected by \u03b2s.\n  // According to the way we organize the transition matrix, the cells\n  // A[row][col] where row is an even index and col is an odd index\n  // are such cells.\n  //\n  // Each cell of matrix A_beta_factors represent all the directed paths\n  // starting at the vertex equal to the column index of the matrix and\n  // ending at the vertex equal to the row index of the matrix.\n  //\n  // Each cell of matrix A_beta_factors is an object of Tran_Mat_Cell class.\n  std::vector<std::vector<std::shared_ptr<Tran_Mat_Cell>>> A_beta_factors;\n\n  // A set of (row, column) numbers of the 2D matrix A_beta_factors\n  // where the cell (row, column) depends on \u03b2 factors.\n  std::set<std::pair<int, int>> beta_dependent_cells;\n\n  // Maps each \u03b2 to all the transition matrix cells that are dependent on it.\n  std::multimap<std::pair<int, int>, std::pair<int, int>> beta2cell;\n\n  std::unordered_set<int> body_nodes = {};\n  std::unordered_set<int> head_nodes = {};\n  std::vector<double> generated_latent_sequence;\n  int generated_concept;\n\n  /*\n   ============================================================================\n   Sampler Related Variables\n   ============================================================================\n  */\n\n  // keep track of training progress\n  float training_progress = 0.0;  // Range is [0.0, 1.0]\n\n  // Used to check whether there is a trained model before calling\n  // generate_prediction()\n  bool trained = false;\n\n  // training was stopped by user input\n  bool stopped = false;\n\n  int n_timesteps = 0;\n  int pred_timesteps = 0;\n  std::pair<std::pair<int, int>, std::pair<int, int>> training_range;\n  std::vector<std::string> pred_range;\n  long train_start_epoch = -1;\n  long train_end_epoch = -1;\n  double pred_start_timestep = -1;\n  std::vector<double> observation_timestep_gaps;\n  std::unordered_map<double, Eigen::MatrixXd> e_A_ts;\n  long modeling_period = 1; // Number of epochs per one modeling timestep\n\n  std::unordered_map<int, std::function<double(unsigned int, double)>> external_concepts;\n  std::vector<unsigned int> concept_sample_pool;\n  std::vector<EdgeDescriptor> edge_sample_pool;\n\n  double t = 0.0;\n  double delta_t = 1.0;\n\n  double log_likelihood = 0.0;\n  double previous_log_likelihood = 0.0;\n  double log_likelihood_MAP = 0.0;\n  int MAP_sample_number = -1;\n  std::vector<double> log_likelihoods;\n\n  // To decide whether to perturb a \u03b8 or a derivative\n  // If coin_flip < coin_flip_thresh perturb \u03b8 else perturb derivative\n  double coin_flip = 0;\n  double coin_flip_thresh = 0.5;\n\n  // Remember the old \u03b8, logpdf(\u03b8) and the edge where we perturbed the \u03b8.\n  // We need this to revert the system to the previous state if the proposal\n  // gets rejected.\n  // Access:\n  //        edge, \u03b8, logpdf(\u03b8)\n  std::tuple<EdgeDescriptor, double, double> previous_theta;\n\n  // Remember the old derivative and the concept we perturbed the derivative\n  int changed_derivative = 0;\n  double previous_derivative = 0;\n\n  // Latent state that is evolved by sampling.\n  Eigen::VectorXd s0;\n  Eigen::VectorXd s0_prev;\n  double derivative_prior_variance = 0.1;\n\n  // Transition matrix that is evolved by sampling.\n  // Since variable A has been already used locally in other methods,\n  // I chose to name this A_original. After refactoring the code, we could\n  // rename this to A.\n  Eigen::MatrixXd A_original;\n\n  // Determines whether to use the continuous version or the discretized\n  // version of the solution for the system of differential equations.\n  //\n  // continuous = true:\n  //    Continuous version of the solution. We use the continuous form of the\n  //    transition matrix and matrix exponential.\n  //\n  // continuous = false:\n  //    Discretized version of the solution. We use the discretized version of\n  //    the transition matrix and repeated matrix multiplication.\n  //\n  // A_discretized = I + A_continuous * \u0394t\n  bool continuous = true;\n\n  // Access this as\n  // current_latent_state\n  Eigen::VectorXd current_latent_state;\n\n  // Access this as\n  // observed_state_sequence[ time step ][ vertex ][ indicator ]\n  ObservedStateSequence observed_state_sequence;\n\n  // Access this as\n  // prediction_latent_state_sequences[ sample ][ time step ]\n  std::vector<std::vector<Eigen::VectorXd>> predicted_latent_state_sequences;\n\n  // Access this as\n  // predicted_observed_state_sequences\n  //                            [ sample ][ time step ][ vertex ][ indicator ]\n  std::vector<PredictedObservedStateSequence>\n      predicted_observed_state_sequences;\n\n  PredictedObservedStateSequence test_observed_state_sequence;\n\n  // Implementing constraints or interventions.\n  // -------------------------------------------------------------------------\n  // We are implementing two ways to constrain the model.\n  //    1. One-off constraints.\n  //        A latent state is clamped to a constrained value just for the\n  //        specified time step and released to evolve from the subsequent time\n  //        step onward until the next constrained time step and so on.\n  //        E.g. Getting a one time grant.\n  //    2. Perpetual constraints\n  //        Once a latent state gets clamped at a value at a particular time\n  //        step, it stays clamped at that value in subsequent time steps until\n  //        another constrain overwrites the current constrain or the end of\n  //        the prediction time is reached.\n  //        NOTE: Currently we do not have a way to have a semi-perpetual\n  //        constraint: A constraint is applied perpetually for some number of\n  //        continuous time steps and then switched off. With a little bit of\n  //        work we can implement this. We just need a special constraint value\n  //        to signal end of a constraint. One suggestion is to use NaN.\n  //        E.g. Maintaining a water level of a reservoir at a certain amount.\n  //\n  // NOTE: WE either apply One-off or Perpetual constraints to all the\n  //       concepts. The current design does not permit applying mixed\n  //       constraints such that some concepts are constrained one-off while\n  //       some others are constrained perpetual. With a little bit more work,\n  //       we could also achieve this. Moving the constraint type into the\n  //       constraint information data structure would work for keeping track\n  //       of mixed constraint types:\n  //        std::unordered_map<int, std::vector<std::tuple<int, double, bool>>>\n  //       Then we would have to update the constraint processing logic\n  //       accordingly.\n  // -------------------------------------------------------------------------\n  //\n  // NOTE: This implementation of the constraints does not work at all with\n  // multiple indicators being attached to a single concept. Constraining the\n  // concept effects all the indicators and we cannot constrain targeted for a\n  // particular indicator. In the current model we might achieve this by\n  // constraining the scaling factor (which we incorrectly call as the\n  // indicator mean).\n  // Currently we are doing:\n  //    constrained latent state = constrained indicator value / scaling factor\n  // The constraining that might work with multiple indicators per concept:\n  //    constrained scaling factor = constrained indicator value / latent state\n  // -------------------------------------------------------------------------\n  //\n  // Implementing the One-off constraints:\n  // -------------------------------------------------------------------------\n  // To store constraints (or interventions)\n  // For some times steps of the prediction range, latent state values could be\n  // constrained to a value external from what the LDS predicts that value\n  // should be. When prediction happens, if constrains are present at a time\n  // step for some concepts, the predicted latent state values for those\n  // concepts are overwritten by the constraints supplied in this data\n  // structure.\n  // Access\n  // [ time step ] --> [(concept id, constrained value), ... ]\n  // latent_state_constraints.at(time step)\n  std::unordered_map<int, std::vector<std::pair<int, double>>>\n      one_off_constraints;\n  std::unordered_map<int, std::vector<std::pair<int, double>>>\n      head_node_one_off_constraints;\n  //\n  // Implementing Perpetual constraints:\n  // -------------------------------------------------------------------------\n  // Access\n  // [ concept id ] --> constrained value\n  // perpetual_constraints.at(concept id)\n  std::unordered_map<int, double> perpetual_constraints;\n  //\n  // Deciding which type of constraints to enforce\n  // one_off_constraints is empty => unconstrained prediction\n  // is_one_off_constraints = true => One-off constraints\n  // is_one_off_constraints = false => Perpetual constraints\n  bool is_one_off_constraints = true;\n  //\n  // Deciding whether to clamp the latent variable or the derivative\n  // true  => clamp at derivative\n  // false => clamp at latent variable\n  bool clamp_at_derivative = true;\n  //\n  // When we are clamping derivatives the clamp sticks since derivatives never\n  // chance in our current model. So for one-off clamping, we have to reset the\n  // derivative back to original after the clamping step. This variable\n  // remembers the time step to reset the clamped derivatives.\n  int rest_derivative_clamp_ts = -1;\n\n  std::vector<Eigen::MatrixXd> transition_matrix_collection;\n  std::vector<Eigen::VectorXd> initial_latent_state_collection;\n  //std::vector<std::vector<double>> latent_mean_collection;\n  //std::vector<std::vector<double>> latent_std_collection;\n  // Access:\n  // [sample][node id]{partition --> (mean, std)}\n  //std::vector<std::vector<std::unordered_map<int, std::pair<double, double>>>> latent_mean_std_collection;\n\n  std::vector<Eigen::VectorXd> synthetic_latent_state_sequence;\n  bool synthetic_data_experiment = false;\n\n  /*\n   ============================================================================\n   Private: Integration with Uncharted's CauseMos interface\n                                                  (in causemos_integration.cpp)\n   ============================================================================\n  */\n\n            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                            training-progress\n            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                            create-model\n            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n  /** Extracts concept to indicator mapping and the indicator observation\n   * sequences from the create model JSON input received from the CauseMose\n   * HMI. The JSON input specifies time as POSIX time stamps in milliseconds.\n   * Also the JSON input does not mention anything about the observation\n   * frequency, missing data points, or whether observation sequences for\n   * multiple indicators are time aligned (e.g. Whether they have the same\n   * starting and ending time, whether data points for a single indicator are\n   * ordered in chronologically increasing order).\n   *\n   * This method does not assume any of these unspoken qualities. This method\n   * reads in the observations from JSON and populate an internal intermediate\n   * and temporary data structure time aligning observations.\n   *\n   * All the parameters except the first are used to return the results back to\n   * the caller. The caller should declare these variables and pass them here so\n   * that after the execution of this method, the caller can access the results.\n   *\n   * @param json_indicators         : conceptIndicators portion of the JSON\n   *                                  input received from the HMI.\n   * @param concept_indicator_data  : This data structure gets filled with\n   *                                  chronologically ordered observation\n   *                                  sequences for all the indicators,\n   *                                  segmented according to the concepts they\n   *                                  attach to. This is a temporary\n   *                                  intermediate data structure used to time\n   *                                  align observation and accumulate multiple\n   *                                  observations for an indicator at a time\n   *                                  point. Observed state sequence is filled\n   *                                  using data in this data structure.\n   * @param concept_indicator_epochs : This data structure gets filled with\n   *                                  epochs where observations\n   *                                  are available for each indicator. Each\n   *                                  indicator gets a separate sequence of\n   *                                  chronologically ordered epochs.\n   *                                  These are used to asses the best\n   *                                  frequency to align observations across\n   *                                  all the indicators.\n   * @returns void\n   *\n   */\n  void extract_concept_indicator_mapping_and_observations_from_json(\n                        const nlohmann::json &json_indicators,\n                        ConceptIndicatorData &concept_indicator_data,\n                        ConceptIndicatorEpochs &concept_indicator_epochs);\n\n\n  static double epoch_to_timestep(long epoch, long train_start_epoch, long modeling_frequency);\n\n  /** Infer the best sampling period to align observations to be used as the\n   * modeling frequency from all the observation sequences.\n   *\n   * We consider the sequence of epochs where observations are available and\n   * then the gaps in epochs between adjacent observations. We take the most\n   * frequent gap as the modeling frequency. When more than one gap is most\n   * frequent, we take the smallest such gap.\n   *\n   * NOTE: Some thought about how to use this information:\n   * shortest_gap = longest_gap  \u21d2 no missing data\n   * shortest_gap < longest_gap \u21d2 missing data\n   * 1 < shortest_gap < longest_gap\n   *    Best frequency to model at is the greatest common divisor of all\n   *    gaps. For example if we see gaps 4, 6, 10 then gcd(4, 6, 10) = 2\n   *    and modeling at a frequency of 2 months starting from the start\n   *    date would allow us to capture all the observation sequences while\n   *    aligning them with each other.\n   *\n   * All the parameters except the first are used to return the results back to\n   * the caller. The caller should declare these variables and pass them here so\n   * that after the execution of this method, the caller can access the results.\n   *\n   * @param concept_indicator_epochs : Chronologically ordered observation epoch\n   *                                  sequences for each indicator extracted\n   *                                  from the JSON data in the create model\n   *                                  request. This data structure is populated\n   *                                  by AnalysisGraph::\n   *                                  extract_concept_indicator_mapping_and_observations_from_json().\n   * @param shortest_gap            : Least number of epochs between any two\n   *                                  consecutive observations.\n   * @param longest_gap             : Most number of epochs between any two\n   *                                  consecutive observations.\n   * @param frequent_gap            : Most frequent number of epochs between\n   *                                  two consecutive observations.\n   * @param highest_frequency       : Number of time the frequent_gap is seen\n   *                                  in all the observation sequences.\n   * @returns epochs_sorted         : A sorted list of epochs where observations\n   *                                  are present for at least one indicator\n   */\n  std::vector<long>\n  infer_modeling_period(\n                        const ConceptIndicatorEpochs &concept_indicator_epochs,\n                        long &shortest_gap,\n                        long &longest_gap,\n                        long &frequent_gap,\n                        int &highest_frequency);\n\n  void infer_concept_period(const ConceptIndicatorEpochs &concept_indicator_epochs);\n\n  /**\n   * Set the observed state sequence from the create model JSON input received\n   * from the HMI.\n   * The training_start_epoch and training_end_epochs are extracted from the\n   * observation sequences for indicators provided in the JSON input.\n   * The sequence includes both ends of the range.\n   *\n   * NOTE: When Delphi is run locally, the observed state sequence is set in a\n   *       separate method:\n   *       AnalysisGraph::set_observed_state_sequence_from_data(), which the\n   *       code could be found in train_model.cpp.\n   *       It would be better if we could combine these two methods into one.\n   *\n   * @param json_indicators : JSON concept-indicator mapping and observations\n   * @returns void\n   *\n   */\n  void\n  set_observed_state_sequence_from_json_dict(const nlohmann::json &json_indicators);\n\n            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                          create-experiment\n            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n  // Epoch --> (year, month, date)\n  std::tuple<int, int, int> timestamp_to_year_month_date(long timestamp);\n\n  void extract_projection_constraints(\n                                const nlohmann::json &projection_constraints, long skip_steps);\n\n  FormattedProjectionResult run_causemos_projection_experiment_from_json_dict(\n                                               const nlohmann::json &json_data);\n\n  FormattedProjectionResult format_projection_result();\n\n  void sample_transition_matrix_collection_from_prior();\n\n\n  /*\n   ============================================================================\n   Private: Model serialization (in serialize.cpp)\n   ============================================================================\n  */\n\n  void from_delphi_json_dict(const nlohmann::json &json_data, bool verbose);\n\n  /*\n   ============================================================================\n   Private: Utilities (in graph_utils.cpp)\n   ============================================================================\n  */\n\n  void clear_state();\n\n  void initialize_random_number_generator();\n\n  void remove_node(int node_id);\n\n  // Allocate a num_verts x num_verts 2D array (std::vector of std::vectors)\n  void allocate_A_beta_factors();\n\n  /**\n   * Finds all the simple paths starting at the start vertex and\n   * ending at the end vertex.\n   * Uses find_all_paths_between_util() as a helper to recursively find the\n   * paths\n   */\n  void find_all_paths_between(int start, int end, int cutoff);\n\n  /**\n   * Recursively finds all the simple paths starting at the start vertex and\n   * ending at the end vertex. Used by find_all_paths_between()\n   * Paths found are added to the Tran_Mat_Cell object that is tracking the\n   * transition matrix cell (2*end, 2*start)\n   *\n   * @param start: Start vertex of the path\n   * @param end  : End vertex of the path\n   * @param path : A path starting at vettex start that is being explored\n   *\n   * @return void\n   */\n  void find_all_paths_between_util(int start,\n                                   int end,\n                                   std::vector<int>& path,\n                                   int cutoff);\n\n  /**\n   * Utility function that converts a time range given a start date and end date\n   * into an integer value.\n   * At the moment returns the number of months withing the time range.\n   * This should be the number of training data time points we have\n   *\n   * @param start_year  : Start year of the training data sequence\n   * @param start_month : Start month of the training data sequence\n   * @param end_year    : End year of the training data sequence\n   * @param end_month   : End month of the training data sequence\n   *\n   * @return            : Number of months in the training data sequence\n   *                      Including both start and end months\n   */\n  int calculate_num_timesteps(int start_year,\n                              int start_month,\n                              int end_year,\n                              int end_month);\n\n  /*\n   ============================================================================\n   Private: Subgraphs (in subgraphs.cpp)\n   ============================================================================\n  */\n\n  void get_subgraph(int vert,\n                    std::unordered_set<int>& vertices_to_keep,\n                    int cutoff,\n                    bool inward);\n\n  void get_subgraph_between(int start,\n                            int end,\n                            std::vector<int>& path,\n                            std::unordered_set<int>& vertices_to_keep,\n                            int cutoff);\n\n  /*\n   ============================================================================\n   Private: Accessors\n   ============================================================================\n  */\n\n  int num_nodes() { return boost::num_vertices(graph); }\n\n  int get_vertex_id(std::string concept) {\n    using namespace fmt::literals;\n    try {\n      return this->name_to_vertex.at(concept);\n    }\n    catch (const std::out_of_range& oor) {\n      throw std::out_of_range(\"Concept \\\"{}\\\" not in CAG!\"_format(concept));\n    }\n  }\n\n  auto node_indices() const {\n    return boost::make_iterator_range(boost::vertices(this->graph));\n  };\n\n  auto nodes() {\n    using boost::adaptors::transformed;\n    return this->node_indices() |\n           transformed([&](int v) -> Node& { return (*this)[v]; });\n  };\n\n  auto node_names() {\n    using boost::adaptors::transformed;\n    return this->nodes() |\n           transformed([&](auto node) -> std::string { return node.name; });\n  };\n\n  int get_degree(int vertex_id) {\n    return boost::in_degree(vertex_id, this->graph) +\n           boost::out_degree(vertex_id, this->graph);\n  };\n\n  auto out_edges(int i) {\n    return boost::make_iterator_range(boost::out_edges(i, graph));\n  }\n\n  Node& source(EdgeDescriptor e) {\n    return (*this)[boost::source(e, this->graph)];\n  };\n\n  Node& target(EdgeDescriptor e) {\n    return (*this)[boost::target(e, this->graph)];\n  };\n\n  auto successors(int i) {\n    return boost::make_iterator_range(boost::adjacent_vertices(i, this->graph));\n  }\n\n  auto successors(std::string node_name) {\n    return this->successors(this->name_to_vertex.at(node_name));\n  }\n\n  std::vector<Node> get_successor_list(std::string node) {\n    std::vector<Node> successors = {};\n    for (int successor : this->successors(node)) {\n      successors.push_back((*this)[successor]);\n    }\n    return successors;\n  }\n\n  auto predecessors(int i) {\n    return boost::make_iterator_range(\n        boost::inv_adjacent_vertices(i, this->graph));\n  }\n\n  auto predecessors(std::string node_name) {\n    return this->predecessors(this->name_to_vertex.at(node_name));\n  }\n\n  std::vector<Node> get_predecessor_list(std::string node) {\n    std::vector<Node> predecessors = {};\n    for (int predecessor : this->predecessors(node)) {\n      predecessors.push_back((*this)[predecessor]);\n    }\n    return predecessors;\n  }\n\n  double get_beta(std::string source_vertex_name,\n                  std::string target_vertex_name) {\n\n    // This is \u2202target / \u2202source\n    return this->A_original(2 * get_vertex_id(target_vertex_name),\n                            2 * get_vertex_id(source_vertex_name) + 1);\n  }\n\n  /*\n   ============================================================================\n   Private: Get Training Data Sequence (in train_model.cpp)\n   ============================================================================\n  */\n\n\n  /**\n   * Set the observed state sequence for a given time range from data.\n   * The sequence includes both ends of the range.\n   * See data.hpp::get_observations_for() for missing data rules.\n   * Note: units are automatically set according\n   * to the parameterization of the given CAG.\n   *\n   * @param start_year  : Start year of the sequence of data\n   * @param start_month : Start month of the sequence of data\n   * @param end_year    : End year of the sequence of data\n   * @param end_month   : End month of the sequence of data\n   * @param country     : Country where the data is about\n   * @param state       : State where the data is about\n   * @param county      : County where the data is about\n   *\n   */\n  void\n  set_observed_state_sequence_from_data(std::string country = \"South Sudan\",\n                                        std::string state = \"\",\n                                        std::string county = \"\");\n\n  /**\n   * Get the observed state (values for all the indicators)\n   * for a given time point from data.\n   * See data.hpp::get_observations_for() for missing data rules.\n   * Note: units are automatically set according\n   * to the parameterization of the given CAG.\n   *\n   * @param year    : Year of the time point data is extracted\n   * @param month   : Month of the time point data is extracted\n   * @param country : Country where the data is about\n   * @param state   : State where the data is about\n   * @param county  : County where the data is about\n   *\n   * @return        : Observed state std::vector for the specified location\n   *                  on the specified time point.\n   *                  Access it as: [ vertex id ][ indicator id ]\n   */\n  std::vector<std::vector<std::vector<double>>>\n  get_observed_state_from_data(int year,\n                               int month,\n                               std::string country,\n                               std::string state = \"\",\n                               std::string county = \"\");\n\n  /*\n   ============================================================================\n   Private: Initializing model parameters (in parameter_initialization.cpp)\n   ============================================================================\n  */\n\n  /**\n   * Initialize all the parameters and hyper-parameters of the Delphi model.\n   *\n   * @param start_year  : Start year of the sequence of data\n   * @param start_month : Start month of the sequence of data\n   * @param end_year    : End year of the sequence of data\n   * @param end_month   : End month of the sequence of data\n   * @param res         : Sampling resolution. The number of samples to retain.\n   * @param initial_beta: Criteria to initialize \u03b2\n   * @param use_heuristic : Informs how to handle missing observations.\n   *                        false => let them be missing.\n   *                        true => fill them. See\n   *                        data.hpp::get_observations_for() for missing data\n   *                        rules.\n   * @param use_continuous: Choose between continuous vs discretized versions\n   *                        of the differential equation solution.\n   *                        Default is to use the continuous version with\n   *                        matrix exponential.\n   */\n  void initialize_parameters(int res = 200,\n                             InitialBeta initial_beta = InitialBeta::ZERO,\n                             InitialDerivative initial_derivative = InitialDerivative::DERI_ZERO,\n                             bool use_heuristic = false,\n                             bool use_continuous = true);\n\n  void set_indicator_means_and_standard_deviations();\n\n  /**\n   * To help experiment with initializing \u03b2s to different values\n   *\n   * @param ib: Criteria to initialize \u03b2\n   */\n  void init_betas_to(InitialBeta ib = InitialBeta::MEAN);\n\n  void construct_theta_pdfs();\n\n  /*\n   ============================================================================\n   Private: Training by MCMC Sampling (in sampling.cpp)\n   ============================================================================\n  */\n\n  void set_base_transition_matrix();\n\n  // Sample elements of the stochastic transition matrix from the\n  // prior distribution, based on gradable adjectives.\n  void set_transition_matrix_from_betas();\n\n  void set_log_likelihood_helper(int ts);\n\n  void set_log_likelihood();\n\n  /**\n   * Run Bayesian inference - sample from the posterior distribution.\n   */\n  void sample_from_posterior();\n\n  /**\n   * Sample a new transition matrix from the proposal distribution,\n   * given a current candidate transition matrix.\n   * In practice, this amounts to:\n   *    Selecting a random \u03b2.\n   *    Perturbing it a bit.\n   *    Updating all the transition matrix cells that are dependent on it.\n   */\n  // TODO: Need testng\n  // TODO: Before calling sample_from_proposal() we must call\n  // AnalysisGraph::find_all_paths()\n  // TODO: Before calling sample_from_proposal(), we mush assign initial \u03b2s and\n  // run Tran_Mat_Cell::compute_cell() to initialize the first transistion\n  // matrix.\n  // TODO: Update Tran_Mat_Cell::compute_cell() to calculate the proper value.\n  // At the moment it just computes sum of length of all the paths realted to\n  // this cell\n  void sample_from_proposal();\n\n  /**\n   * Find all the transition matrix (A) cells that are dependent on the \u03b2\n   * attached to the provided edge and update them.\n   * Acts upon this->A_original\n   *\n   * @param e: The directed edge \u2261 \u03b2 that has been perturbed\n   */\n  void update_transition_matrix_cells(EdgeDescriptor e);\n\n  double calculate_delta_log_prior();\n\n  void revert_back_to_previous_state();\n\n\n  /*\n   ============================================================================\n   Private: Modeling head nodes (in head_nodes.cpp)\n   ============================================================================\n  */\n\n  void partition_data_and_calculate_mean_std_for_each_partition(\n      Node& n, std::vector<double>& latent_sequence);\n\n  void apply_constraint_at(int ts, int node_id);\n\n  void generate_head_node_latent_sequence(int node_id,\n                                          int num_timesteps,\n                                          bool sample,\n                                          int seq_no = 0);\n\n  void generate_head_node_latent_sequence_from_changes(Node &n,\n                                                       int num_timesteps,\n                                                       bool sample);\n\n  void generate_head_node_latent_sequences(int samp, int num_timesteps);\n\n  void update_head_node_latent_state_with_generated_derivatives(\n      int ts_current,\n      int ts_next,\n      int concept_id,\n      std::vector<double>& latent_sequence);\n\n  void update_latent_state_with_generated_derivatives(int ts_current,\n                                                      int ts_next);\n\n  /*\n   ============================================================================\n   Private: Prediction (in prediction.cpp)\n   ============================================================================\n  */\n\n  /**\n   * Generate a collection of latent state sequences from the likelihood\n   * model given a collection of sampled\n   * (initial latent state,  transition matrix) pairs.\n   *\n   * @param prediction_timesteps   : The number of timesteps for the prediction\n   *                                 sequences.\n   * @param initial_prediction_step: The initial prediction timestep relative\n   *                                 to training timesteps.\n   * @param total_timesteps        : Total number of timesteps from the initial\n   *                                 training date to the end prediction date.\n   * @param project                : Default false. If true, generate a single\n   *                                 latent state sequence based on the\n   *                                 perturbed initial latent state s0.\n   */\n  void generate_latent_state_sequences(double initial_prediction_step);\n\n  void perturb_predicted_latent_state_at(int timestep, int sample_number);\n\n  /** Generate observed state sequences given predicted latent state\n   * sequences using the emission model\n   */\n  void generate_observed_state_sequences();\n\n  std::vector<std::vector<double>>\n  generate_observed_state(Eigen::VectorXd latent_state);\n\n  /**\n   * Format the prediction result into a format Python callers favor.\n   *\n   * @param pred_timestes: Number of timesteps in the predicted sequence.\n   *\n   * @return Re-formatted prediction result.\n   *         Access it as:\n   *         [ sample number ][ time point ][ vertex name ][ indicator name ]\n   */\n  FormattedPredictionResult format_prediction_result();\n\n  void run_model(int start_year,\n                 int start_month,\n                 int end_year,\n                 int end_month);\n\n  void add_constraint(int step, std::string concept_name, std::string indicator_name,\n                                                double indicator_clamp_value);\n\n  /*\n   ============================================================================\n   Private: Synthetic Data Experiment (in synthetic_data.cpp)\n   ============================================================================\n  */\n\n  /*\n   ============================================================================\n   Private: Graph Visualization (in graphviz.cpp)\n   ============================================================================\n  */\n\n  std::pair<Agraph_t*, GVC_t*> to_agraph(\n      bool simplified_labels =\n          false, /** Whether to create simplified labels or not. */\n      int label_depth =\n          1, /** Depth in the ontology to which simplified labels extend */\n      std::string node_to_highlight = \"\",\n      std::string rankdir = \"TB\");\n\n  public:\n  AnalysisGraph() {\n     one_off_constraints.clear();\n     perpetual_constraints.clear();\n  }\n\n  ~AnalysisGraph() {}\n\n  std::string id;\n  std::string to_json_string(int indent = 0);\n  bool data_heuristic = false;\n\n  // Set the sampling resolution.\n  void set_res(size_t res);\n\n  // Set the number of KDE kernels.\n  void set_n_kde_kernels(size_t kde_kernels)\n      {this->n_kde_kernels = kde_kernels;};\n\n  // Get the sampling resolution.\n  size_t get_res();\n\n\n  // there may be a better place in this file for this prototype\n  /** Construct an AnalysisGraph object from JSON exported by CauseMos. */\n  void from_causemos_json_dict(const nlohmann::json &json_data,\n                               double belief_score_cutoff,\n                               double grounding_score_cutoff);\n\n  /*\n   ============================================================================\n   Constructors from INDRA-exported JSON (in constructors.cpp)\n   ============================================================================\n  */\n\n  /**\n   * A method to construct an AnalysisGraph object given a JSON-serialized list\n   * of INDRA statements.\n   *\n   * @param filename: The path to the file containing the JSON-serialized INDRA\n   * statements.\n   */\n  static AnalysisGraph\n  from_indra_statements_json_dict(nlohmann::json json_data,\n                                  double belief_score_cutoff = 0.9,\n                                  double grounding_score_cutoff = 0.0,\n                                  std::string ontology = \"WM\");\n\n  static AnalysisGraph\n  from_indra_statements_json_string(std::string json_string,\n                                    double belief_score_cutoff = 0.9,\n                                    double grounding_score_cutoff = 0.0,\n                                    std::string ontology = \"WM\");\n\n  static AnalysisGraph\n  from_indra_statements_json_file(std::string filename,\n                                  double belief_score_cutoff = 0.9,\n                                  double grounding_score_cutoff = 0.0,\n                                  std::string ontology = \"WM\");\n\n  /**\n   * A method to construct an AnalysisGraph object given from a std::vector of\n   * ( subject, object ) pairs (Statements)\n   *\n   * @param statements: A std::vector of CausalFragment objects\n   */\n  static AnalysisGraph\n  from_causal_fragments(std::vector<CausalFragment> causal_fragments);\n\n  static AnalysisGraph\n  from_causal_fragments_with_data(std::pair<std::vector<CausalFragment>,\n                                  ConceptIndicatorAlignedData> cag_ind_data,\n                                  int kde_kernels = 5);\n\n  /** From internal string representation output by to_json_string */\n  static AnalysisGraph from_json_string(std::string);\n\n  /** Copy constructor */\n  AnalysisGraph(const AnalysisGraph& rhs);\n\n  /*\n   ============================================================================\n   Public: Integration with Uncharted's CauseMos interface\n                                                  (in causemos_integration.cpp)\n   ============================================================================\n  */\n\n            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                            training-progress\n            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n  float get_training_progress();\n  bool get_trained();\n  bool get_stopped();\n  double get_log_likelihood();\n  double get_previous_log_likelihood();\n  double get_log_likelihood_MAP();\n\n            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                            create-model\n            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n  /** Construct an AnalysisGraph object from a JSON string exported by CauseMos.\n   */\n  static AnalysisGraph from_causemos_json_string(std::string json_string,\n                                                 double belief_score_cutoff = 0,\n                                                 double grounding_score_cutoff = 0,\n                                                 int kde_kernels = 4);\n\n  /** Construct an AnalysisGraph object from a file containing JSON data from\n   * CauseMos. */\n  static AnalysisGraph from_causemos_json_file(std::string filename,\n                                               double belief_score_cutoff = 0,\n                                               double grounding_score_cutoff = 0,\n                                               int kde_kernels = 4);\n\n  /**\n   * Generate the response for the create model request from the HMI.\n   * Calculate and return a JSON string with edge weight information for\n   * visualizing AnalysisGraph models in CauseMos.\n   * For now we always return success. We need to update this by conveying\n   * errors into this response.\n   */\n  std::string generate_create_model_response();\n\n\n            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                          create-experiment\n            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n  FormattedProjectionResult\n  run_causemos_projection_experiment_from_json_string(std::string json_string);\n\n  FormattedProjectionResult\n  run_causemos_projection_experiment_from_json_file(std::string filename);\n\n  /*\n   ============================================================================\n   Public: Model serialization (in serialize.cpp)\n   ============================================================================\n  */\n\n  std::string serialize_to_json_string(bool verbose = true);\n\n  void export_create_model_json_string();\n\n  static AnalysisGraph deserialize_from_json_string(std::string json_string, bool verbose = true);\n\n  static AnalysisGraph deserialize_from_json_file(std::string filename, bool verbose = true);\n\n  /*\n   ============================================================================\n   Public: Accessors\n   ============================================================================\n  */\n\n  /** Number of nodes in the graph */\n  size_t num_vertices() { return boost::num_vertices(this->graph); }\n\n  Node& operator[](std::string node_name) {\n    return (*this)[this->get_vertex_id(node_name)];\n  }\n\n  Node& operator[](int v) { return this->graph[v]; }\n\n  size_t num_edges() { return boost::num_edges(this->graph); }\n\n  auto edges() const { return boost::make_iterator_range(boost::edges(graph)); }\n\n  Edge& edge(EdgeDescriptor e) { return this->graph[e]; }\n\n  Edge& edge(int source, int target) {\n    return this->graph[boost::edge(source, target, this->graph).first];\n  }\n\n  Edge& edge(int source, std::string target) {\n    return this->graph\n        [boost::edge(source, this->get_vertex_id(target), this->graph).first];\n  }\n\n  Edge& edge(std::string source, int target) {\n    return this->graph\n        [boost::edge(this->get_vertex_id(source), target, this->graph).first];\n  }\n\n  Edge& edge(std::string source, std::string target) {\n    return this->graph[boost::edge(this->get_vertex_id(source),\n                                   this->get_vertex_id(target),\n                                   this->graph)\n                           .first];\n  }\n\n  boost::range_detail::integer_iterator<unsigned long> begin() {\n    return boost::vertices(this->graph).first;\n  };\n\n  boost::range_detail::integer_iterator<unsigned long> end() {\n    return boost::vertices(this->graph).second;\n  };\n\n  Eigen::VectorXd& get_initial_latent_state() { return this->s0; };\n\n  double get_MAP_log_likelihood() { return this->log_likelihood_MAP; };\n\n  /*\n   ============================================================================\n   Public: Graph Building (in graph_building.cpp)\n   ============================================================================\n  */\n\n  int add_node(std::string concept);\n\n  bool add_edge(CausalFragment causal_fragment);\n  void add_edge(CausalFragmentCollection causal_fragments);\n  std::pair<EdgeDescriptor, bool> add_edge(int, int);\n  std::pair<EdgeDescriptor, bool> add_edge(int, std::string);\n  std::pair<EdgeDescriptor, bool> add_edge(std::string, int);\n  std::pair<EdgeDescriptor, bool> add_edge(std::string, std::string);\n\n  void remove_node(std::string concept);\n\n  // Note:\n  //      Although just calling this->remove_node(concept) within the loop\n  //          for( std::string concept : concept_s )\n  //      is sufficient to implement this method, it is not very efficient.\n  //      It re-calculates directed simple paths for each vertex removed\n  //\n  //      Therefore, the code in this->remove_node() has been duplicated with\n  //      slightly different flow to achive a more efficient execution.\n  void remove_nodes(std::unordered_set<std::string> concepts);\n\n  void remove_edge(std::string src, std::string tgt);\n\n  void remove_edges(std::vector<std::pair<std::string, std::string>> edges);\n\n  /*\n   ============================================================================\n   Public: Subgraphs (in subgraphs.cpp)\n   ============================================================================\n  */\n\n  // TODO Change the name of this function to something better, like\n  // restrict_to_subgraph_for_concept, update docstring\n\n  /**\n   * Returns the subgraph of the AnalysisGraph around a concept.\n   *\n   * @param concept: The concept to center the subgraph about.\n   * @param depth  : The maximum number of hops from the concept provided\n   *                 to be included in the subgraph.\n   * #param inward : Sets the direction of the causal influence flow to\n   *                 examine.\n   *                 False - (default) A subgraph rooted at the concept\n   * provided.\n   *                 True  - A subgraph with all the paths ending at the concept\n   * provided.\n   */\n  AnalysisGraph get_subgraph_for_concept(std::string concept,\n                                         bool inward = false,\n                                         int depth = -1);\n\n  /**\n   * Returns a new AnaysisGraph related to the source concept and the target\n   * concetp provided, which is a subgraph of this graph.\n   * This subgraph contains all the simple directed paths of length less than\n   * or equal to the provided cutoff.\n   *\n   * @param source_concept: The concept where the influence starts.\n   * @param target_concept: The concept where the influence ends.\n   * @param cutoff        : Maximum length of a directed simple path from\n   *                        the source to target to be included in the\n   *                        subgraph.\n   */\n  AnalysisGraph get_subgraph_for_concept_pair(std::string source_concept,\n                                              std::string target_concept,\n                                              int cutoff = -1);\n\n  /*\n   ============================================================================\n   Public: Graph Modification (in graph_modification.cpp)\n   ============================================================================\n  */\n\n  void prune(int cutoff = 2);\n\n  // Merge node n1 into node n2, with the option to specify relative polarity.\n  // void\n  // merge_nodes_old(std::string n1, std::string n2, bool same_polarity = true);\n\n  /**\n   * Merges the CAG nodes for the two concepts concept_1 and concept_2\n   * with the option to specify relative polarity.\n   */\n  void merge_nodes(std::string concept_1,\n                   std::string concept_2,\n                   bool same_polarity = true);\n\n  void change_polarity_of_edge(std::string source_concept,\n                               int source_polarity,\n                               std::string target_concept,\n                               int target_polarity);\n\n  /*\n   ============================================================================\n   Public: Indicator Manipulation (in indicator_manipulation.cpp)\n   ============================================================================\n  */\n\n  int\n  set_indicator(std::string concept, std::string indicator, std::string source);\n\n  void delete_indicator(std::string concept, std::string indicator);\n\n  void delete_all_indicators(std::string concept);\n\n  /**\n   * Map each concept node in the AnalysisGraph instance to one or more\n   * tangible quantities, known as 'indicators'.\n   *\n   * @param n: Int representing number of indicators to attach per node.\n   * Default is 1 since our model so far is configured for only 1 indicator per\n   * node.\n   */\n  void map_concepts_to_indicators(int n = 1, std::string country = \"\");\n\n  /*\n   ============================================================================\n   Public: Utilities (in graph_utils.cpp)\n   ============================================================================\n  */\n\n  /*\n   * Find all the simple paths between all the paris of nodes of the graph\n   */\n  void find_all_paths();\n\n  void set_random_seed(int seed);\n\n  void set_derivative(std::string, double);\n\n  /*\n   ============================================================================\n   Public: Training the Model (in train_model.cpp)\n   ============================================================================\n  */\n\n  /**\n   * Train a prediction model given a CAG with indicators\n   *\n   * @param start_year  : Start year of the sequence of data\n   * @param start_month : Start month of the sequence of data\n   * @param end_year    : End year of the sequence of data\n   * @param end_month   : End month of the sequence of data\n   * @param res         : Sampling resolution. The number of samples to retain.\n   * @param burn        : Number of samples to throw away. Start retaining\n   *                      samples after throwing away this many samples.\n   * @param country     : Country where the data is about\n   * @param state       : State where the data is about\n   * @param county      : county where the data is about\n   * @param units       : Units for each indicator. Maps\n   *                      indicator name --> unit\n   * @param initial_beta: Criteria to initialize \u03b2\n   * @param use_heuristic : Informs how to handle missing observations.\n   *                        false => let them be missing.\n   *                        true => fill them. See\n   *                        data.hpp::get_observations_for() for missing data\n   *                        rules.\n   * @param use_continuous: Choose between continuous vs discretized versions\n   *                        of the differential equation solution.\n   *                        Default is to use the continuous version with\n   *                        matrix exponential.\n   */\n  void train_model(int start_year = 2012,\n                   int start_month = 1,\n                   int end_year = 2017,\n                   int end_month = 12,\n                   int res = 200,\n                   int burn = 10000,\n                   std::string country = \"South Sudan\",\n                   std::string state = \"\",\n                   std::string county = \"\",\n                   std::map<std::string, std::string> units = {},\n                   InitialBeta initial_beta = InitialBeta::ZERO,\n                   InitialDerivative initial_derivative = InitialDerivative::DERI_ZERO,\n                   bool use_heuristic = false,\n                   bool use_continuous = true);\n\n  void run_train_model(int res = 200,\n                   int burn = 10000,\n                   InitialBeta initial_beta = InitialBeta::ZERO,\n                   InitialDerivative initial_derivative = InitialDerivative::DERI_ZERO,\n                   bool use_heuristic = false,\n                   bool use_continuous = true,\n                   int train_start_timestep = 0,\n                   int train_timesteps = -1,\n                   std::unordered_map<std::string, int> concept_periods = {},\n                   std::unordered_map<std::string, std::string> concept_center_measures = {},\n                   std::unordered_map<std::string, std::string> concept_models = {},\n                   std::unordered_map<std::string, double> concept_min_vals = {},\n                   std::unordered_map<std::string, double> concept_max_vals = {},\n                   std::unordered_map\n                       <std::string, std::function<double(unsigned int, double)>>\n                   ext_concepts = {});\n\n  void run_train_model_2(int res = 200,\n                       int burn = 10000,\n                       InitialBeta initial_beta = InitialBeta::ZERO,\n                       InitialDerivative initial_derivative = InitialDerivative::DERI_ZERO,\n                       bool use_heuristic = false,\n                       bool use_continuous = true);\n\n  /*\n   ============================================================================\n   Public: Training by MCMC Sampling (in sampling.cpp)\n   ============================================================================\n  */\n\n  void set_initial_latent_state(Eigen::VectorXd vec) { this->s0 = vec; };\n\n  void set_default_initial_state(InitialDerivative id = InitialDerivative::DERI_ZERO);\n\n  /*\n   ============================================================================\n   Public: Prediction (in prediction.cpp)\n   ============================================================================\n  */\n\n  /**\n   * Given a trained model, generate this->res number of\n   * predicted observed state sequences.\n   *\n   * @param start_year  : Start year of the prediction\n   *                      Should be >= the start year of training\n   * @param start_month : Start month of the prediction\n   *                      If training and prediction start years are equal\n   *                      should be >= the start month of training\n   * @param end_year    : End year of the prediction\n   * @param end_month   : End month of the prediction\n   *\n   * @return Predicted observed state (indicator value) sequence for the\n   *         prediction period including start and end time points.\n   *         This is a tuple.\n   *         The first element is a std::vector of std::strings with labels for\n   * each time point predicted (year-month). The second element contains\n   * predicted values. Access it as: [ sample number ][ time point ][ vertex\n   * name ][ indicator name ]\n   */\n  Prediction generate_prediction(int start_year,\n                                 int start_month,\n                                 int end_year,\n                                 int end_month,\n                                 ConstraintSchedule constraints =\n                                 ConstraintSchedule(),\n                                 bool one_off = true,\n                                 bool clamp_deri = true);\n\n  void generate_prediction(int pred_start_timestep,\n                           int pred_timesteps,\n                           ConstraintSchedule constraints =\n                           ConstraintSchedule(),\n                           bool one_off = true,\n                           bool clamp_deri = true);\n\n  /**\n   * this->generate_prediction() must be called before calling this method.\n   * Outputs raw predictions for a given indicator that were generated by\n   * generate_prediction(). Each column is a time step and the rows are the\n   * samples for that time step.\n   *\n   * @param indicator: A std::string representing the indicator variable for\n   * which we want predictions.\n   * @return A (this->res, x this->pred_timesteps) dimension 2D array\n   *         (std::vector of std::vectors)\n   *\n   */\n  std::vector<std::vector<double>> prediction_to_array(std::string indicator);\n\n  /*\n   ============================================================================\n   Public: Synthetic data experiment (in synthetic_data.cpp)\n   ============================================================================\n  */\n\n  static AnalysisGraph generate_random_CAG(unsigned int num_nodes,\n                                           unsigned int num_extra_edges = 0);\n\n  void generate_synthetic_data(unsigned int num_obs = 48,\n                               double noise_variance = 0.1,\n                               unsigned int kde_kernels = 1000,\n                               InitialBeta initial_beta = InitialBeta::PRIOR,\n                               InitialDerivative initial_derivative = InitialDerivative::DERI_PRIOR,\n                               bool use_continuous = false);\n\n  void initialize_random_CAG(unsigned int num_obs,\n                             unsigned int kde_kernels,\n                             InitialBeta initial_beta,\n                             InitialDerivative initial_derivative,\n                             bool use_continuous);\n\n  void interpolate_missing_months(std::vector<int> &filled_months, Node &n);\n\n  /*\n   ============================================================================\n   Public: Graph Visualization (in graphviz.cpp)\n   ============================================================================\n  */\n\n  std::string to_dot();\n\n  void\n  to_png(std::string filename = \"CAG.png\",\n         bool simplified_labels =\n             false, /** Whether to create simplified labels or not. */\n         int label_depth =\n             1, /** Depth in the ontology to which simplified labels extend */\n         std::string node_to_highlight = \"\",\n         std::string rankdir = \"TB\");\n\n  /*\n   ============================================================================\n   Public: Printing (in printing.cpp)\n   ============================================================================\n  */\n\n  void print_nodes();\n  void print_edges();\n  void print_name_to_vertex();\n  void print_indicators();\n  void print_A_beta_factors();\n  void print_latent_state(const Eigen::VectorXd&);\n\n  /*\n   * Prints the simple paths found between all pairs of nodes of the graph\n   * Groupd according to the starting and ending vertex.\n   * find_all_paths() should be called before this to populate the paths\n   */\n  void print_all_paths();\n\n  // Given an edge (source, target vertex ids - i.e. a \u03b2 \u2261 \u2202target/\u2202source),\n  // print all the transition matrix cells that are dependent on it.\n  void print_cells_affected_by_beta(int source, int target);\n\n  void print_training_range();\n\n  /*\n   ============================================================================\n   Public: Formatting output (in format_output.cpp)\n   ============================================================================\n  */\n\n  CredibleIntervals get_credible_interval(Predictions preds);\n\n  CompleteState get_complete_state();\n\n  /*\n   ============================================================================\n   Public: Database interactions (in database.cpp)\n   ============================================================================\n  */\n\n  sqlite3* open_delphi_db(int mode = SQLITE_OPEN_READONLY);\n\n  void write_model_to_db(std::string model_id);\n\n  AdjectiveResponseMap construct_adjective_response_map(\n      std::mt19937 gen,\n      std::uniform_real_distribution<double>& uni_dist,\n      std::normal_distribution<double>& norm_dist,\n      size_t n_kernels\n  );\n\n  /*\n   ============================================================================\n   Public: Profiling Delphi (in profiler.cpp)\n   ============================================================================\n  */\n\n  void initialize_profiler(int res = 100,\n                           int kde_kernels = 1000,\n                           InitialBeta initial_beta = InitialBeta::ZERO,\n                           InitialDerivative initial_derivative = InitialDerivative::DERI_ZERO,\n                           bool use_continuous = true);\n\n  void profile_mcmc(int run = 1, std::string file_name_prefix = \"mcmc_timing\");\n\n  void profile_kde(int run = 1, std::string file_name_prefix = \"kde_timing\");\n\n  void profile_prediction(int run = 1, int pred_timesteps = 24, std::string file_name_prefix = \"prediction_timing\");\n\n#ifdef TIME\n  void set_timing_file_prefix(std::string tfp) {this->timing_file_prefix = tfp;}\n  void create_mcmc_part_timing_file()\n  {\n      std::string filename = this->timing_file_prefix + \"embeded_\" +\n                              std::to_string(this->num_nodes()) + \"-\" +\n                              std::to_string(this->num_nodes()) + \"_\" +\n                              std::to_string(this->timing_run_number) + \"_\" +\n                              delphi::utils::get_timestamp() + \".csv\";\n      this->writer = CSVWriter(filename);\n      std::vector<std::string> headings = {\"Run\", \"Nodes\", \"Edges\", \"Wall Clock Time (ns)\", \"CPU Time (ns)\", \"Sample Type\"};\n      writer.write_row(headings.begin(), headings.end());\n//      cout << filename << endl;\n  }\n  void set_timing_run_number(int run) {this->timing_run_number = run;}\n#endif\n};\n", "meta": {"hexsha": "cb32afe6ff830c1c6322bdf39c3964020a7037ff", "size": 66261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/AnalysisGraph.hpp", "max_stars_repo_name": "ml4ai/delphi", "max_stars_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T11:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T21:19:54.000Z", "max_issues_repo_path": "lib/AnalysisGraph.hpp", "max_issues_repo_name": "ml4ai/delphi", "max_issues_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 385.0, "max_issues_repo_issues_event_min_datetime": "2018-02-21T16:52:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T07:44:56.000Z", "max_forks_repo_path": "lib/AnalysisGraph.hpp", "max_forks_repo_name": "ml4ai/delphi", "max_forks_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-03-20T01:08:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T01:04:49.000Z", "avg_line_length": 40.0610640871, "max_line_length": 124, "alphanum_fraction": 0.5802659181, "num_tokens": 13248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.17212553258922506}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2014, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, 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_ALGORITHMS_DETAIL_DISTANCE_RANGE_TO_GEOMETRY_RTREE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_RANGE_TO_GEOMETRY_RTREE_HPP\n\n#include <iterator>\n#include <utility>\n\n#include <boost/assert.hpp>\n\n#include <boost/geometry/core/point_type.hpp>\n\n#include <boost/geometry/iterators/has_one_element.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n\n#include <boost/geometry/algorithms/dispatch/distance.hpp>\n\n#include <boost/geometry/algorithms/detail/closest_feature/range_to_range.hpp>\n#include <boost/geometry/algorithms/detail/distance/is_comparable.hpp>\n#include <boost/geometry/algorithms/detail/distance/iterator_selector.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace distance\n{\n\n\ntemplate\n<\n    typename PointOrSegmentIterator,\n    typename Geometry,\n    typename Strategy\n>\nclass point_or_segment_range_to_geometry_rtree\n{\nprivate:\n    typedef typename std::iterator_traits\n        <\n            PointOrSegmentIterator\n        >::value_type point_or_segment_type;\n\n    typedef iterator_selector<Geometry const> selector_type;\n\n    typedef detail::closest_feature::range_to_range_rtree range_to_range;\n\npublic:\n    typedef typename strategy::distance::services::return_type\n        <\n            Strategy,\n            typename point_type<point_or_segment_type>::type,\n            typename point_type<Geometry>::type\n        >::type return_type;\n\n    static inline return_type apply(PointOrSegmentIterator first,\n                                    PointOrSegmentIterator last,\n                                    Geometry const& geometry,\n                                    Strategy const& strategy)\n    {\n        namespace sds = strategy::distance::services;\n\n        BOOST_ASSERT( first != last );\n\n        if ( geometry::has_one_element(first, last) )\n        {\n            return dispatch::distance\n                <\n                    point_or_segment_type, Geometry, Strategy\n                >::apply(*first, geometry, strategy);\n        }\n\n        typename sds::return_type\n            <\n                typename sds::comparable_type<Strategy>::type,\n                typename point_type<point_or_segment_type>::type,\n                typename point_type<Geometry>::type\n            >::type cd_min;\n\n        std::pair\n            <\n                point_or_segment_type,\n                typename selector_type::iterator_type\n            > closest_features\n            = range_to_range::apply(first,\n                                    last,\n                                    selector_type::begin(geometry),\n                                    selector_type::end(geometry),\n                                    sds::get_comparable\n                                        <\n                                            Strategy\n                                        >::apply(strategy),\n                                    cd_min);\n\n        return\n            is_comparable<Strategy>::value\n            ?\n            cd_min\n            :\n            dispatch::distance\n                <\n                    point_or_segment_type,                    \n                    typename std::iterator_traits\n                        <\n                            typename selector_type::iterator_type\n                        >::value_type,\n                    Strategy\n                >::apply(closest_features.first,\n                         *closest_features.second,\n                         strategy);\n    }\n};\n\n\n}} // namespace detail::distance\n#endif // DOXYGEN_NO_DETAIL\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_RANGE_TO_GEOMETRY_RTREE_HPP\n", "meta": {"hexsha": "78189794a1b3da80639bd69d9f44b98a882ab270", "size": 3972, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/algorithms/detail/distance/range_to_geometry_rtree.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": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-01-26T15:50:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T08:27:00.000Z", "max_issues_repo_path": "deps/cinder/include/boost/geometry/algorithms/detail/distance/range_to_geometry_rtree.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": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-07-18T21:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-17T02:54:52.000Z", "max_forks_repo_path": "deps/cinder/include/boost/geometry/algorithms/detail/distance/range_to_geometry_rtree.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": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-01-27T22:36:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T12:00:36.000Z", "avg_line_length": 30.0909090909, "max_line_length": 79, "alphanum_fraction": 0.5866062437, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17212552921171415}}
{"text": "// Copyright 2020 Speech Technology Center www.speechpro.com\n//\n// Licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0\n//\n// This code is provided *as is* basis, without warranties or conditions of any kind.\n////////////////////////////////////////////////////////////////////////////////////////////\n// If you find this code useful for your research or production, please cite our paper:\n//\n// @inproceedings{Medennikov_mixup2018,\n//   author={Ivan Medennikov and Yuri Khokhlov and Aleksei Romanenko and Dmitry Popov and Natalia Tomashenko and Ivan Sorokin and Alexander Zatvornitskiy},\n//   title={An Investigation of Mixup Training Strategies for Acoustic Models in ASR},\n//   year=2018,\n//   booktitle={Proc. Interspeech 2018},\n//   pages={2903--2907},\n//   doi={10.21437/Interspeech.2018-2191},\n//   url={http://dx.doi.org/10.21437/Interspeech.2018-2191}\n// }\n//\n// (corresponding author: medennikov@speechpro.com)\n////////////////////////////////////////////////////////////////////////////////////////////\n\n\n#include <limits>\n#include <algorithm>\n#include <boost/shared_ptr.hpp>\n#include <boost/format.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/beta_distribution.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <utility>\n#include \"base/kaldi-common.h\"\n#include \"util/common-utils.h\"\n#include \"nnet3/nnet-example.h\"\n\nnamespace kaldi { namespace nnet3 {\n\ntypedef Matrix<BaseFloat> KaldiMatrix;\ntypedef Vector<BaseFloat> KaldiVector;\ntypedef SparseMatrix<BaseFloat> KaldiSparMatrix;\ntypedef SparseVector<BaseFloat> KaldiSparVector;\ntypedef SubMatrix<BaseFloat> KaldiSubMatrix;\ntypedef SubVector<BaseFloat> KaldiSubVector;\ntypedef boost::shared_ptr<NnetExample> ExamplePtr;\ntypedef std::pair<std::string, ExamplePtr> ExamplePair;\n\nclass LabelsMap {\nprotected:\n    std::map<int32_t, int32_t> lmap;\n\npublic:\n    explicit LabelsMap(const std::string& _labels_map) : lmap() {\n        if (!_labels_map.empty()) {\n            std::vector<std::string> parts;\n            boost::split(parts, _labels_map, boost::is_any_of(\" \\t,;|/\"), boost::token_compress_on);\n            for (const auto &part : parts) {\n                std::vector<std::string> pair;\n                boost::split(pair, part, boost::is_any_of(\":\"), boost::token_compress_on);\n                if (pair.size() != 2) {\n                    KALDI_ERR << \"Wrong labels map format: \\\"\" << _labels_map << \"\\\"\";\n                }\n                lmap.insert(std::make_pair(boost::lexical_cast<int32_t>(pair[0]), boost::lexical_cast<int32_t>(pair[1])));\n            }\n        }\n    }\n    bool empty() const { return lmap.empty(); }\n    int32_t operator()(int32_t _label) const {\n        auto iter = lmap.find(_label);\n        return (iter == lmap.end()) ? _label : iter->second;\n    }\n    std::string to_string() const {\n        std::stringstream strstrm;\n        for (auto& pair : lmap) {\n            if (strstrm.tellp() > 0) {\n                strstrm << \",\";\n            }\n            strstrm << pair.first << \":\" << pair.second;\n        }\n        return strstrm.str();\n    }\n};\n\nclass IRandomScale {\npublic:\n    virtual float Value() = 0;\n};\n\nclass RandomScaleUniform: public IRandomScale {\nprotected:\n    typedef boost::random::uniform_real_distribution<float> real_distrib_t;\n    typedef boost::shared_ptr<real_distrib_t> distrib_ptr_t;\n\nprotected:\n    boost::random::mt19937& rand_gen;\n    distrib_ptr_t distrib;\n\npublic:\n    RandomScaleUniform(boost::random::mt19937& _rand_gen, const std::string& _params);\n    float Value() override;\n};\n\nRandomScaleUniform::RandomScaleUniform(boost::random::mt19937& _rand_gen, const std::string& _params): rand_gen(_rand_gen), distrib() {\n    std::vector<std::string> parts;\n    boost::split(parts, _params, boost::is_any_of(\":\"));\n    if (parts.size() != 2) {\n        KALDI_ERR << \"Wrong uniform distribution parameters string: \\\"\" << _params << \"\\\".\";\n    }\n    if (parts.front() != \"uniform\") {\n        KALDI_ERR << \"Wrong uniform distribution parameters string: \\\"\" << _params << \"\\\".\";\n    }\n    std::vector<std::string> min_max;\n    boost::split(min_max, parts.back(), boost::is_any_of(\",\"));\n    if (parts.size() != 2) {\n        KALDI_ERR << \"Wrong uniform distribution parameters string: \\\"\" << _params << \"\\\".\";\n    }\n    const auto min_value = boost::lexical_cast<float>(min_max.front());\n    const auto max_value = boost::lexical_cast<float>(min_max.back());\n    if (min_value > max_value) {\n        KALDI_ERR << \"min_value must be less or equal max_value (\" << _params << \")\";\n    }\n    if ((min_value < 0.0f) || (min_value > 1.0f)) {\n        KALDI_ERR << \"min_value must be in the range [0, 1] (\" << _params << \")\";\n    }\n    if ((max_value < 0.0f) || (max_value > 1.0f)) {\n        KALDI_ERR << \"max_value must be in the range [0, 1] (\" << _params << \")\";\n    }\n    distrib.reset(new real_distrib_t(min_value, max_value));\n}\n\nfloat RandomScaleUniform::Value() {\n    return (*distrib)(rand_gen);\n}\n\nclass RandomScaleBeta: public IRandomScale {\nprotected:\n    typedef boost::random::beta_distribution<double> real_distrib_t;\n    typedef boost::shared_ptr<real_distrib_t> distrib_ptr_t;\n\nprotected:\n    boost::random::mt19937& rand_gen;\n    distrib_ptr_t distrib;\n\npublic:\n    RandomScaleBeta(boost::random::mt19937& _rand_gen, const std::string& _params);\n    float Value() override;\n};\n\nRandomScaleBeta::RandomScaleBeta(boost::random::mt19937& _rand_gen, const std::string& _params): rand_gen(_rand_gen), distrib() {\n    std::vector<std::string> parts;\n    boost::split(parts, _params, boost::is_any_of(\":\"));\n    if (parts.size() != 2) {\n        KALDI_ERR << \"Wrong beta distribution parameters string: \\\"\" << _params << \"\\\".\";\n    }\n    if ((parts.front() != \"beta\") && (parts.front() != \"beta2\")) {\n        KALDI_ERR << \"Wrong beta distribution parameters string: \\\"\" << _params << \"\\\".\";\n    }\n    const auto alpha = boost::lexical_cast<float>(parts.back());\n    if (alpha <= 0.0f) {\n        KALDI_ERR << \"alpha must be a positive value (\" << _params << \")\";\n    }\n    distrib.reset(new real_distrib_t(alpha, alpha));\n}\n\nfloat RandomScaleBeta::Value() {\n    return (float)(*distrib)(rand_gen);\n}\n\nclass RandomScaleBeta2: public RandomScaleBeta {\npublic:\n    RandomScaleBeta2(boost::random::mt19937& _rand_gen, const std::string& _params);\n    float Value() override;\n};\n\nRandomScaleBeta2::RandomScaleBeta2(boost::random::mt19937& _rand_gen, const std::string& _params):\n        RandomScaleBeta(_rand_gen, _params)\n{}\n\nfloat RandomScaleBeta2::Value() {\n    const double value = (*distrib)(rand_gen);\n    if (value <= 0.5) {\n        return (float) value;\n    } else {\n        return (float)(1.0 - value);\n    }\n}\n\nclass RandomScale {\nprotected:\n    typedef boost::shared_ptr<IRandomScale> rand_scale_t;\n\nprotected:\n    rand_scale_t rand_scale;\n\npublic:\n    RandomScale(boost::random::mt19937& _rand_gen, const std::string& _params);\n    float operator()();\n};\n\nRandomScale::RandomScale(boost::random::mt19937& _rand_gen, const std::string& _params): rand_scale() {\n    if (_params.find(\"uniform\") == 0) {\n        rand_scale.reset(new RandomScaleUniform(_rand_gen, _params));\n    } else if (_params.find(\"beta2\") == 0) {\n        rand_scale.reset(new RandomScaleBeta2(_rand_gen, _params));\n    } else if (_params.find(\"beta\") == 0) {\n        rand_scale.reset(new RandomScaleBeta(_rand_gen, _params));\n    } else {\n        KALDI_ERR << \"Unknown random scale generator ID: \\\"\" << _params << \"\\\".\";\n    }\n}\n\nfloat RandomScale::operator()() {\n    return rand_scale->Value();\n}\n\nclass IScaleTransform {\npublic:\n    virtual float operator()(float _scale) const = 0;\n};\n\nclass SigmoidTransform : public IScaleTransform {\nprotected:\n    double k;\n    double denom;\n\npublic:\n    explicit SigmoidTransform(double _k): IScaleTransform(), k(_k), denom(2.0 * std::tanh(_k)) {}\n    float operator()(float _scale) const override;\n};\n\nfloat SigmoidTransform::operator()(float _scale) const {\n    return (float)(0.5 + std::tanh(k * (2.0 * _scale - 1)) / denom);\n}\n\nclass ScaleTransform : public IScaleTransform {\nprotected:\n    typedef boost::shared_ptr<IScaleTransform> transform_t;\n\nprotected:\n    transform_t transform;\n\npublic:\n    explicit ScaleTransform(const std::string& _transform);\n    float operator()(float _scale) const override;\n};\n\nScaleTransform::ScaleTransform(const std::string& _transform): IScaleTransform(), transform() {\n    if (!_transform.empty()) {\n        std::string trans_name;\n        float value1 = 0.0f;\n        const size_t indx = _transform.find(':');\n        if (indx != std::string::npos) {\n            std::string value = _transform.substr(indx + 1);\n            if (value.empty()) {\n                KALDI_ERR << \"Invalid transform functions parameners string format: \\\"\" << _transform << \"\\\".\";\n            }\n            std::vector<std::string> parts;\n            boost::split(parts, value, boost::is_any_of(\",\"), boost::token_compress_on);\n            value1 = boost::lexical_cast<float>(parts.at(0));\n            trans_name = _transform.substr(0, indx);\n        }\n        if (trans_name == \"sigmoid\") {\n            transform.reset(new SigmoidTransform(value1));\n        } else {\n            KALDI_ERR << \"Unknown type of transform \\\"\" << _transform << \"\\\".\";\n        }\n    }\n}\n\nfloat ScaleTransform::operator()(float _scale) const {\n    if (transform == nullptr) {\n        return _scale;\n    } else {\n        return (*transform)(_scale);\n    }\n}\n\ntemplate<class Type>\nclass TCounter {\nprotected:\n    Type minimum;\n    Type maximum;\n    double summa;\n    size_t count;\n\npublic:\n    TCounter():\n        minimum(std::numeric_limits<Type>::max()),\n        maximum(std::numeric_limits<Type>::min()),\n        summa(0.0), count(0)\n    {}\n    Type Minimum() const {return minimum;}\n    Type Maximum() const {return maximum;}\n    double Average() const {return summa / count;}\n    size_t Count() const {return count;}\n    bool Valid() const {return (count > 0);}\n    void operator+=(Type _value) {\n        minimum = std::min(_value, minimum);\n        maximum = std::max(_value, maximum);\n        summa += _value;\n        ++count;\n    }\n};\n\ntypedef TCounter<int> IntCounter;\ntypedef TCounter<float> FloatCounter;\n\nclass ExampleMixer {\nprotected:\n    typedef boost::random::mt19937 rand_gen_t;\n    typedef boost::random::uniform_int_distribution<int32_t> int_distrib_t;\n    typedef boost::random::uniform_int_distribution<size_t> uint_distrib_t;\n    typedef boost::random::uniform_real_distribution<float> real_distrib_t;\n    typedef std::vector<ExamplePair> egs_buffer_t;\n    typedef unordered_map<NnetExample*, egs_buffer_t, NnetExampleStructureHasher, NnetExampleStructureCompare> eg_to_egs_t;\n\nprotected:\n    struct MixupData {\n        int32_t row_main;\n        int32_t row_admx;\n        int32_t label_main;\n        int32_t label_admx;\n        float scale;\n        MixupData(): row_main(0), row_admx(0), label_main(-1), label_admx(-1), scale(0.0f) {}\n        MixupData(int32_t _row_main, int32_t _row_admx, int32_t _label_main, int32_t _label_admx, float _scale):\n            row_main(_row_main), row_admx(_row_admx), label_main(_label_main), label_admx(_label_admx), scale(_scale)\n        {}\n    };\n\nprotected:\n    const std::string mix_mode;\n    NnetExampleWriter& example_writer;\n    size_t min_num;\n    size_t max_num;\n    int32_t min_shift;\n    int32_t max_shift;\n    float fixed_egs;\n    float fixed_frames;\n    size_t left_range;\n    size_t right_range;\n    size_t buff_size;\n    bool mix_ivect;\n    bool mix_feats;\n    bool mix_labels;\n    const LabelsMap& labels_map;\n    bool compress;\n    bool test_mode;\n    rand_gen_t rand_gen;\n    uint_distrib_t int_distrib;\n    uint_distrib_t num_distrib;\n    int_distrib_t shift_distrib;\n    real_distrib_t float_distrib;\n    RandomScale scale_distrib;\n    ScaleTransform transform;\n    eg_to_egs_t eg_to_egs;\n    egs_buffer_t egs_buffer;\n    FloatCounter scale_count;\n    IntCounter shift_count;\n    IntCounter adnum_count;\n    IntCounter left_count;\n    IntCounter right_count;\n    size_t num_mixed;\n    size_t num_untouched;\n    size_t num_accepted;\n    size_t num_wrote;\n\npublic:\n    ExampleMixer(\n        std::string _mix_mode, const std::string& _distrib, const std::string& _transform,\n        NnetExampleWriter& _example_writer, size_t _min_num, size_t _max_num,\n        int32_t _min_shift, int32_t _max_shift, float _fixed_egs, float _fixed_frames,\n        size_t _left_range, size_t _right_range, size_t _buff_size,\n        bool _mix_ivect, bool _mix_feats, bool _mix_labels, const LabelsMap& _labels_map,\n        bool _compress, bool _test_mode\n    );\n\nprotected:\n    const std::vector<Index>& FindIndexes(const std::string& _name, const std::vector<NnetIo>& _nnet_io) const;\n    GeneralMatrix& FindFeatures(const std::string& _name, std::vector<NnetIo>& _nnet_io) const;\n    GeneralMatrix* FindIVector(std::vector<NnetIo>& _nnet_io) const;\n    void MixupLocal(ExamplePair& _example);\n    void AdmixGlobal(const std::vector<float>& _adm_scales, const std::vector<ExamplePtr>& _admixtures, float _exam_scale, ExamplePair& _example);\n    void FlushGlobal(egs_buffer_t& _buffer);\n    void FlushClass(egs_buffer_t& _buffer);\n    void ShiftAndMixup(ExamplePair& _example);\n\npublic:\n    void AcceptExample(ExamplePair& _example);\n    void Finish();\n    const FloatCounter& ScaleCount() const {return scale_count;}\n    const IntCounter& ShiftCount() const {return shift_count;}\n    const IntCounter& AdmixNumCount() const {return adnum_count;}\n    const IntCounter& LeftCount() const {return left_count;}\n    const IntCounter& RightCount() const {return right_count;}\n    size_t NumMixed() const {return num_mixed;}\n    size_t NumUntouched() const {return num_untouched;}\n    size_t NumAccepted() const {return num_accepted;}\n    size_t NumWrote() const {return num_wrote;}\n};\n\nExampleMixer::ExampleMixer(\n    std::string _mix_mode, const std::string& _distrib, const std::string& _transform,\n    NnetExampleWriter& _example_writer, size_t _min_num, size_t _max_num,\n    int32_t _min_shift, int32_t _max_shift, float _fixed_egs, float _fixed_frames,\n    size_t _left_range, size_t _right_range, size_t _buff_size,\n    bool _mix_ivect, bool _mix_feats, bool _mix_labels, const LabelsMap& _labels_map,\n    bool _compress, bool _test_mode\n):\n    mix_mode(std::move(_mix_mode)), transform(_transform),\n    example_writer(_example_writer), min_num(_min_num), max_num(_max_num),\n    min_shift(_min_shift), max_shift(_max_shift),\n    fixed_egs(_fixed_egs), fixed_frames(_fixed_frames),\n    left_range(_left_range), right_range(_right_range), buff_size(_buff_size),\n    mix_ivect(_mix_ivect), mix_feats(_mix_feats), mix_labels(_mix_labels),\n    labels_map(_labels_map), compress(_compress && !_test_mode), test_mode(_test_mode),\n    rand_gen(), int_distrib(0, 100000), num_distrib(min_num, max_num),\n    shift_distrib(_min_shift, _max_shift), float_distrib(0.0f, 1.0f),\n    scale_distrib(rand_gen, _distrib), eg_to_egs(), egs_buffer(),\n    scale_count(), shift_count(), adnum_count(), left_count(), right_count(),\n    num_mixed(0), num_untouched(0), num_accepted(0), num_wrote(0)\n{\n    rand_gen.seed(static_cast<unsigned int>(std::time(0)));\n    KALDI_LOG << \"mix_mode: \" << mix_mode;\n    KALDI_LOG << \"distrib: \" << _distrib;\n    KALDI_LOG << \"transform: \" << _transform;\n    if (mix_mode == \"global\") {\n        KALDI_LOG << \"min_num: \" << min_num;\n        KALDI_LOG << \"max_num: \" << max_num;\n    }\n    if (mix_mode == \"shift\") {\n        KALDI_LOG << \"min_shift: \" << min_shift;\n        KALDI_LOG << \"max_shift: \" << max_shift;\n    }\n    KALDI_LOG << \"fixed_egs: \" << fixed_egs;\n    KALDI_LOG << \"fixed_frames: \" << fixed_frames;\n    if (mix_mode == \"local\") {\n        KALDI_LOG << \"left_range: \" << left_range;\n        KALDI_LOG << \"right_range: \" << right_range;\n    }\n    KALDI_LOG << \"buff_size: \" << buff_size;\n    KALDI_LOG << \"mix_ivect: \" << (mix_ivect? \"yes\": \"no\");\n    KALDI_LOG << \"mix_feats: \" << (mix_feats? \"yes\": \"no\");\n    KALDI_LOG << \"mix_labels: \" << (mix_labels? \"yes\": \"no\");\n    KALDI_LOG << \"labels_map: \" << labels_map.to_string();\n    KALDI_LOG << \"compress: \" << (compress? \"yes\": \"no\");\n    KALDI_LOG << \"test_mode: \" << (test_mode? \"yes\": \"no\");\n}\n\nconst std::vector<Index>& ExampleMixer::FindIndexes(const std::string& _name, const std::vector<NnetIo>& _nnet_io) const {\n    for (size_t i = 0; i < _nnet_io.size(); ++i) {\n        const NnetIo& nnet_io = _nnet_io[i];\n        if (nnet_io.name == _name) {\n            if ((nnet_io.indexes.size() != nnet_io.features.NumRows())) {\n                KALDI_ERR << \"Data indexes have wrong dimension \" << nnet_io.indexes.size() << \" (must be \" << nnet_io.features.NumRows() << \").\";\n            }\n            return nnet_io.indexes;\n        }\n    }\n    KALDI_ERR << \"Failed to find example indexes with name \\\"\" << _name << \"\\\".\";\n}\n\nGeneralMatrix& ExampleMixer::FindFeatures(const std::string& _name, std::vector<NnetIo>& _nnet_io) const {\n    for (size_t i = 0; i < _nnet_io.size(); ++i) {\n        NnetIo& nnet_io = _nnet_io[i];\n        if (nnet_io.name == _name) {\n            if ((nnet_io.indexes.size() != nnet_io.features.NumRows())) {\n                KALDI_ERR << \"Data indexes have wrong dimension \" << nnet_io.indexes.size() << \" (must be \" << nnet_io.features.NumRows() << \").\";\n            }\n            return nnet_io.features;\n        }\n    }\n    KALDI_ERR << \"Failed to find example features with name \\\"\" << _name << \"\\\".\";\n}\n\nGeneralMatrix* ExampleMixer::FindIVector(std::vector<NnetIo>& _nnet_io) const {\n    for (size_t i = 0; i < _nnet_io.size(); ++i) {\n        NnetIo& nnet_io = _nnet_io[i];\n        if (nnet_io.name == \"ivector\") {\n            if ((nnet_io.indexes.size() != nnet_io.features.NumRows())) {\n                KALDI_ERR << \"I-vector indexes have wrong dimension \" << nnet_io.indexes.size() << \" (must be \" << nnet_io.features.NumRows() << \").\";\n            }\n            return &nnet_io.features;\n        }\n    }\n    return nullptr;\n}\n\nvoid ExampleMixer::MixupLocal(ExamplePair& _example) {\n    KaldiMatrix test_feats_org;\n    KaldiMatrix test_labels_org;\n    if (test_mode) {\n        FindFeatures(\"input\", _example.second->io).GetMatrix(&test_feats_org);\n        FindFeatures(\"output\", _example.second->io).GetMatrix(&test_labels_org);\n    }\n    std::vector<NnetIo>& in_out = _example.second->io;\n    const std::vector<Index>& in_indx = FindIndexes(\"input\", in_out);\n    GeneralMatrix& features_g = FindFeatures(\"input\", in_out);\n    const std::vector<Index>& out_indx = FindIndexes(\"output\", in_out);;\n    GeneralMatrix& labels_g = FindFeatures(\"output\", in_out);\n    KaldiMatrix features_org;\n    features_g.GetMatrix(&features_org);\n    const KaldiSparMatrix& labels_org = labels_g.GetSparseMatrix();\n    KaldiMatrix features_mix(features_org.NumRows(), features_org.NumCols(), kSetZero);\n    KaldiSparMatrix labels_mix(labels_org.NumRows(), labels_org.NumCols());\n    std::vector<MixupData> mixup_data((size_t) features_org.NumRows());\n    for (size_t row_main = 0; row_main < mixup_data.size(); ++row_main) {\n        int32_t shift = 0;\n        if (float_distrib(rand_gen) > 0.5f) {\n            shift = -(int)(int_distrib(rand_gen) % left_range + 1);\n            left_count += shift;\n        } else {\n            shift = (int)(int_distrib(rand_gen) % right_range + 1);\n            right_count += shift;\n        }\n        shift_count += shift;\n        int32_t row_admx = int32_t(row_main) + shift;\n        row_admx = std::max(0, row_admx);\n        row_admx = std::min(features_org.NumRows() - 1, row_admx);\n        const int32_t time = in_indx.at(row_main).t;\n        int32_t label_main = -1;\n        int32_t label_admx = -1;\n        if ((time >= 0) && (time < labels_org.NumRows())) {\n            label_main = time;\n            label_admx = time + shift;\n            label_admx = std::max(0, label_admx);\n            label_admx = std::min(labels_org.NumRows() - 1, label_admx);\n            shift = label_admx - label_main;\n            row_admx = int32_t(row_main) + shift;\n        }\n        const float scale = scale_distrib();\n        mixup_data.at(row_main) = MixupData((int32_t) row_main, row_admx, label_main, label_admx, scale);\n        scale_count += scale;\n    }\n    for (const auto & data : mixup_data) {\n        const KaldiSubVector frame_main(features_org, data.row_main);\n        const KaldiSubVector frame_admx(features_org, data.row_admx);\n        KaldiSubVector frame_dest(features_mix, data.row_main);\n        frame_dest.AddVec((1.0f - data.scale), frame_main);\n        frame_dest.AddVec(data.scale, frame_admx);\n        if (data.label_main >= 0) {\n            typedef std::pair<int32_t, float> label_t;\n            typedef std::map<int32_t, float> labels_t;\n            labels_t labels;\n            const KaldiSparVector& labls_main = labels_org.Row(data.label_main);\n            for (int32_t j = 0; j < labls_main.NumElements(); ++j) {\n                const label_t& label = labls_main.GetElement(j);\n                labels.insert(std::make_pair(label.first, (1.0f - data.scale) * label.second));\n            }\n            const KaldiSparVector& labls_admx = labels_org.Row(data.label_admx);\n            for (int32_t j = 0; j < labls_admx.NumElements(); ++j) {\n                const label_t& label = labls_admx.GetElement(j);\n                auto iter = labels.find(label.first);\n                if (iter == labels.end()) {\n                    labels.insert(std::make_pair(label.first, data.scale * label.second));\n                } else {\n                    iter->second += data.scale * label.second;\n                }\n            }\n            KaldiSparVector labls_dest(labels_org.NumCols(), std::vector<label_t>(labels.begin(), labels.end()));\n            labels_mix.SetRow(data.label_main, labls_dest);\n        }\n    }\n    features_g = features_mix;\n    if (compress) {\n        features_g.Compress();\n    }\n    labels_g = labels_mix;\n    if (test_mode) {\n        {\n            KaldiMatrix feats_mix;\n            FindFeatures(\"input\", _example.second->io).GetMatrix(&feats_mix);\n            for (const auto & data : mixup_data) {\n                KaldiVector row_main(test_feats_org.Row(data.row_main));\n                KaldiVector row_admx(test_feats_org.Row(data.row_admx));\n                row_main.Scale(1.0f - data.scale);\n                row_main.AddVec(data.scale, row_admx);\n                KaldiSubVector mixed(feats_mix.Row(data.row_main));\n                row_main.AddVec(-1.0f, mixed);\n                row_main.ApplyAbs();\n                const float value = row_main.Max();\n                KALDI_ASSERT(value < 1e-9);\n            }\n        }\n        {\n            KaldiMatrix labels_mix;\n            FindFeatures(\"output\", _example.second->io).GetMatrix(&labels_mix);\n            for (const auto & data : mixup_data) {\n                if (data.label_main < 0) {\n                    continue;\n                }\n                KaldiVector row_main(test_labels_org.Row(data.label_main));\n                KaldiVector row_admx(test_labels_org.Row(data.label_admx));\n                row_main.Scale(1.0f - data.scale);\n                row_main.AddVec(data.scale, row_admx);\n                KaldiSubVector mixed(labels_mix.Row(data.label_main));\n                row_main.AddVec(-1.0f, mixed);\n                row_main.ApplyAbs();\n                const float value = row_main.Max();\n                KALDI_ASSERT(value < 1e-9);\n            }\n        }\n    }\n}\n\nvoid ExampleMixer::AdmixGlobal(const std::vector<float>& _adm_scales, const std::vector<ExamplePtr>& _admixtures, float _exam_scale, ExamplePair& _example) {\n    if (test_mode) {\n        const float diff = std::fabs(1.0f - std::accumulate(_adm_scales.begin(), _adm_scales.end(), _exam_scale));\n        KALDI_ASSERT(diff < 1e-6);\n    }\n    if (_admixtures.size() != _adm_scales.size()) {\n        KALDI_ERR << \"Wrong admixtures vector size \" << _admixtures.size() << \" (must be \" << _adm_scales.size() << \").\";\n    }\n    KaldiMatrix test_feats_org;\n    KaldiMatrix test_ivect_org;\n    KaldiMatrix test_labels_org;\n    if (test_mode) {\n        FindFeatures(\"input\", _example.second->io).GetMatrix(&test_feats_org);\n        if (FindIVector(_example.second->io) != nullptr) {\n            FindIVector(_example.second->io)->GetMatrix(&test_ivect_org);\n        }\n        FindFeatures(\"output\", _example.second->io).GetMatrix(&test_labels_org);\n    }\n    GeneralMatrix* ivector = FindIVector(_example.second->io);\n    if (mix_ivect && (ivector != nullptr)) {\n        KaldiMatrix ivec_main;\n        ivector->GetMatrix(&ivec_main);\n        ivec_main.Scale(_exam_scale);\n        for (size_t i = 0; i < _adm_scales.size(); ++i) {\n            KaldiMatrix ivec_admx;\n            FindIVector(_admixtures[i]->io)->GetMatrix(&ivec_admx);\n            ivec_main.AddMat(_adm_scales[i], ivec_admx);\n        }\n        *ivector = ivec_main;\n        if (compress) {\n            ivector->Compress();\n        }\n    }\n    if (mix_feats) {\n        GeneralMatrix &features = FindFeatures(\"input\", _example.second->io);\n        KaldiMatrix feat_main;\n        features.GetMatrix(&feat_main);\n        feat_main.Scale(_exam_scale);\n        for (size_t i = 0; i < _adm_scales.size(); ++i) {\n            KaldiMatrix feat_admx;\n            FindFeatures(\"input\", _admixtures[i]->io).GetMatrix(&feat_admx);\n            feat_main.AddMat(_adm_scales[i], feat_admx);\n        }\n        features = feat_main;\n        if (compress) {\n            features.Compress();\n        }\n    }\n    float exam_scale = transform(_exam_scale);\n    std::vector<float> adm_scales(_adm_scales);\n    for (float & adm_scale : adm_scales) {\n        adm_scale = transform(adm_scale);\n    }\n    const float scale_norm = std::accumulate(adm_scales.begin(), adm_scales.end(), exam_scale);\n    exam_scale /= scale_norm;\n    std::transform(adm_scales.begin(), adm_scales.end(), adm_scales.begin(), [scale_norm](float _value) -> float { return _value / scale_norm; });\n    if (mix_labels) {\n        GeneralMatrix &labels = FindFeatures(\"output\", _example.second->io);\n        if (labels.Type() == kaldi::kSparseMatrix) {\n            KaldiSparMatrix labels_main(labels.GetSparseMatrix());\n            std::vector<float> row_wght((size_t) labels_main.NumRows(), 0.0f);\n            for (int32_t j = 0; j < labels_main.NumRows(); ++j) {\n                auto &wght = row_wght[j];\n                const KaldiSparVector &lab_main = labels_main.Row(j);\n                for (int32_t k = 0; k < lab_main.NumElements(); ++k) {\n                    wght += lab_main.GetElement(k).second;\n                }\n            }\n            labels_main.Scale(exam_scale);\n            typedef std::pair<int32_t, float> label_t;\n            typedef std::map<int32_t, float> labels_t;\n            for (size_t i = 0; i < adm_scales.size(); ++i) {\n                KaldiSparMatrix labels_admx(FindFeatures(\"output\", _admixtures[i]->io).GetSparseMatrix());\n                labels_admx.Scale(adm_scales[i]);\n                for (int32_t j = 0; j < labels_main.NumRows(); ++j) {\n                    labels_t lab_set;\n                    const KaldiSparVector &lab_main = labels_main.Row(j);\n                    for (int32_t k = 0; k < lab_main.NumElements(); ++k) {\n                        lab_set.insert(lab_main.GetElement(k));\n                    }\n                    const KaldiSparVector &lab_admx = labels_admx.Row(j);\n                    for (int32_t k = 0; k < lab_admx.NumElements(); ++k) {\n                        label_t label = lab_admx.GetElement(k);\n                        if (!labels_map.empty()) {\n                            label.first = labels_map(label.first);\n                        }\n                        label.second *= row_wght.at((size_t) j);\n                        auto iter = lab_set.find(label.first);\n                        if (iter == lab_set.end()) {\n                            lab_set.insert(label);\n                        } else {\n                            iter->second += label.second;\n                        }\n                    }\n                    KaldiSparVector labls_dest(labels_main.NumCols(), std::vector<label_t>(lab_set.begin(), lab_set.end()));\n                    labels_main.SetRow(j, labls_dest);\n                }\n            }\n            for (int32_t j = 0; j < labels_main.NumRows(); ++j) {\n                labels_t lab_set;\n                float scale = 0.0f;\n                const KaldiSparVector &lab_main = labels_main.Row(j);\n                for (int32_t k = 0; k < lab_main.NumElements(); ++k) {\n                    auto &label = lab_main.GetElement(k);\n                    scale += label.second;\n                    lab_set.insert(label);\n                }\n                scale = row_wght[j] / scale;\n                for (auto &label : lab_set) {\n                    label.second *= scale;\n                }\n                KaldiSparVector labls_dest(labels_main.NumCols(), std::vector<label_t>(lab_set.begin(), lab_set.end()));\n                labels_main.SetRow(j, labls_dest);\n            }\n            labels = labels_main;\n        } else {\n            KaldiMatrix labels_main;\n            labels.GetMatrix(&labels_main);\n            labels_main.Scale(exam_scale);\n            for (size_t i = 0; i < adm_scales.size(); ++i) {\n                KaldiMatrix labels_admx;\n                FindFeatures(\"output\", _admixtures[i]->io).GetMatrix(&labels_admx);\n                labels_main.AddMat(adm_scales[i], labels_admx);\n            }\n            labels = labels_main;\n        }\n    }\n    scale_count += 1.0 - _exam_scale;\n    adnum_count += _adm_scales.size();\n    if (test_mode) {\n        {\n            KaldiMatrix feats_res;\n            FindFeatures(\"input\", _example.second->io).GetMatrix(&feats_res);\n            feats_res.AddMat(-_exam_scale, test_feats_org);\n            for (size_t i = 0; i < _adm_scales.size(); ++i) {\n                KaldiMatrix feats_tmp;\n                FindFeatures(\"input\", _admixtures[i]->io).GetMatrix(&feats_tmp);\n                feats_res.AddMat(-_adm_scales[i], feats_tmp);\n            }\n            const float value = std::max(std::fabs(feats_res.Max()), std::fabs(feats_res.Min())) / _adm_scales.size();\n            KALDI_ASSERT(value < 1e-5);\n        }\n        if (ivector != nullptr) {\n            KaldiMatrix ivect_res;\n            FindIVector(_example.second->io)->GetMatrix(&ivect_res);\n            ivect_res.AddMat(-_exam_scale, test_ivect_org);\n            for (size_t i = 0; i < _adm_scales.size(); ++i) {\n                KaldiMatrix ivect_tmp;\n                FindIVector(_admixtures[i]->io)->GetMatrix(&ivect_tmp);\n                ivect_res.AddMat(-_adm_scales[i], ivect_tmp);\n            }\n            const float value = std::max(std::fabs(ivect_res.Max()), std::fabs(ivect_res.Min())) / _adm_scales.size();\n            KALDI_ASSERT(value < 1e-6);\n        }\n        {\n            KaldiMatrix labels_res;\n            FindFeatures(\"output\", _example.second->io).GetMatrix(&labels_res);\n            labels_res.AddMat(-exam_scale, test_labels_org);\n            for (size_t i = 0; i < adm_scales.size(); ++i) {\n                KaldiMatrix labels_tmp;\n                FindFeatures(\"output\", _admixtures[i]->io).GetMatrix(&labels_tmp);\n                labels_res.AddMat(-adm_scales[i], labels_tmp);\n            }\n            const float value = std::max(std::fabs(labels_res.Max()), std::fabs(labels_res.Min())) / adm_scales.size();\n            KALDI_ASSERT(value < 1e-7);\n        }\n    }\n}\n\nvoid ExampleMixer::FlushGlobal(egs_buffer_t& _buffer) {\n    egs_buffer_t buffer(_buffer.size());\n    for (size_t i = 0; i < _buffer.size(); ++i) {\n        const ExamplePair& pair = _buffer[i];\n        buffer[i] = std::make_pair(pair.first, ExamplePtr(new NnetExample(*pair.second)));\n    }\n    for (size_t i = 0; i < _buffer.size(); ++i) {\n        ExamplePair& example = _buffer.at(i);\n        const bool mixup = ((float_distrib(rand_gen) > fixed_egs) && (_buffer.size() > 1));\n        if (mixup) {\n            const size_t admix_num = (min_num == max_num)? min_num: num_distrib(rand_gen);\n            std::vector<float> scales;\n            scales.reserve(admix_num);\n            float summ = 0.0f;\n            for (size_t j = 0; j < admix_num; ++j) {\n                const float scale = float_distrib(rand_gen);\n                scales.push_back(scale);\n                summ += scale;\n            }\n            const float scale = scale_distrib();\n            for (size_t j = 0; j < scales.size(); ++j) {\n                scales[j] *= scale / summ;\n            }\n            if (test_mode) {\n                summ = 0.0f;\n                for (size_t j = 0; j < scales.size(); ++j) {\n                    summ += scales[j];\n                }\n                const float diff = std::fabs(summ - scale);\n                KALDI_ASSERT(diff < 1e-6);\n            }\n            std::vector<ExamplePtr> admixts;\n            admixts.reserve(scales.size());\n            for (size_t j = 0; j < scales.size(); ++j) {\n                size_t indx = int_distrib(rand_gen) % buffer.size();\n                if (indx == i) {\n                    indx = (indx == (buffer.size() - 1)) ? indx - 1 : indx + 1;\n                }\n                admixts.push_back(buffer.at(indx).second);\n            }\n            AdmixGlobal(scales, admixts, 1.0f - scale, example);\n            ++num_mixed;\n        } else {\n            ++num_untouched;\n        }\n        example_writer.Write(example.first, *example.second);\n        ++num_wrote;\n    }\n}\n\nvoid ExampleMixer::FlushClass(egs_buffer_t& _buffer) {\n    typedef std::pair<const KaldiSubVector, const KaldiSparVector*> frame_pair_t;\n    typedef std::vector<frame_pair_t> frame_arr_t;\n    typedef unordered_map<int32_t, frame_arr_t> frame_map_t;\n    frame_map_t frame_map;\n    egs_buffer_t buffer(_buffer.size());\n    for (size_t i = 0; i < _buffer.size(); ++i) {\n        const ExamplePair& pair = _buffer[i];\n        buffer[i] = std::make_pair(pair.first, ExamplePtr(new NnetExample(*pair.second)));\n        NnetExample& example = *buffer[i].second;\n        const std::vector<Index>& in_indx = FindIndexes(\"input\", example.io);\n        const std::vector<Index>& out_indx = FindIndexes(\"output\", example.io);\n        if (out_indx.front().t != 0) {\n            KALDI_ERR << \"Unexpected time stamp of first label \" << out_indx.front().t << \" (zero expected).\";\n        }\n        if (out_indx.back().t != (out_indx.size() - 1)) {\n            KALDI_ERR << \"Unexpected time stamp of last label \" << out_indx.back().t << \" (must be \" << (out_indx.size() - 1) << \").\";\n        }\n        GeneralMatrix& gen_matrix = FindFeatures(\"input\", example.io);\n        {\n            KaldiMatrix matrix;\n            gen_matrix.GetMatrix(&matrix);\n            gen_matrix = matrix;\n        }\n        const KaldiMatrix& matrix = gen_matrix.GetFullMatrix();\n        if (matrix.NumRows() != in_indx.size()) {\n            KALDI_ERR << \"Wrong number of rows in input features matrix \" << matrix.NumRows() << \" (must be \" << in_indx.size() << \").\";\n        }\n        const KaldiSparMatrix& labels = FindFeatures(\"output\", example.io).GetSparseMatrix();\n        if (labels.NumRows() != out_indx.size()) {\n            KALDI_ERR << \"Wrong number of rows in output labels matrix \" << labels.NumRows() << \" (must be \" << out_indx.size() << \").\";\n        }\n        int32_t last_label = -1;\n        auto class_iter = frame_map.end();\n        for (size_t j = 0; j < in_indx.size(); ++j) {\n            const Index& indx = in_indx[j];\n            if ((indx.t < 0) || (indx.t >= labels.NumRows())) {\n                continue;\n            }\n            const KaldiSparVector& spvect = labels.Row(indx.t);\n            int32_t label = spvect.GetElement(0).first;\n            if (spvect.NumElements() > 1) {\n                float max_value = spvect.GetElement(0).second;\n                for (int32_t k = 1; k < spvect.NumElements(); ++k) {\n                    const std::pair<MatrixIndexT, BaseFloat>& item = spvect.GetElement(k);\n                    if (max_value < item.second) {\n                        label = item.first;\n                        max_value = item.second;\n                    }\n                }\n            }\n            if (last_label != label) {\n                class_iter = frame_map.find(label);\n                if (class_iter == frame_map.end()) {\n                    class_iter = frame_map.insert(std::make_pair(label, frame_arr_t())).first;\n                }\n                last_label = label;\n            }\n            class_iter->second.emplace_back(std::make_pair(matrix.Row((MatrixIndexT) j), &spvect));\n        }\n    }\n    for (auto & pair : _buffer) {\n        if (float_distrib(rand_gen) > fixed_egs) {\n            NnetExample& example = *pair.second;\n            const std::vector<Index>& in_indx = FindIndexes(\"input\", example.io);\n            GeneralMatrix& gen_matrix = FindFeatures(\"input\", example.io);\n            KaldiMatrix matrix;\n            gen_matrix.GetMatrix(&matrix);\n            const std::vector<Index>& out_indx = FindIndexes(\"output\", example.io);\n            GeneralMatrix& gen_labels = FindFeatures(\"output\", example.io);\n            KaldiSparMatrix labels = gen_labels.GetSparseMatrix();\n            int32_t last_label = -1;\n            auto class_iter = frame_map.end();\n            for (auto indx : in_indx) {\n                if ((indx.t < 0) || (indx.t >= labels.NumRows())) {\n                    continue;\n                }\n                if (float_distrib(rand_gen) < fixed_frames) {\n                    continue;\n                }\n                KaldiSubVector frame_row1 = matrix.Row(indx.t);\n                const KaldiSparVector& labels_row1 = labels.Row(indx.t);\n                int32_t label = labels_row1.GetElement(0).first;\n                if (labels_row1.NumElements() > 1) {\n                    float max_value = labels_row1.GetElement(0).second;\n                    for (int32_t k = 1; k < labels_row1.NumElements(); ++k) {\n                        const std::pair<MatrixIndexT, BaseFloat>& item = labels_row1.GetElement(k);\n                        if (max_value < item.second) {\n                            label = item.first;\n                            max_value = item.second;\n                        }\n                    }\n                }\n                if (last_label != label) {\n                    class_iter = frame_map.find(label);\n                    if (class_iter == frame_map.end()) {\n                        class_iter = frame_map.insert(std::make_pair(label, frame_arr_t())).first;\n                    }\n                    last_label = label;\n                }\n                const frame_arr_t& frame_arr = class_iter->second;\n                const auto frame_indx = (size_t)(int_distrib(rand_gen) % frame_arr.size());\n                const frame_pair_t& frame_pair = frame_arr.at(frame_indx);\n                const KaldiSubVector& frame_row2 = frame_pair.first;\n                const KaldiSparVector& labels_row2 = *frame_pair.second;\n                const float scale2 = scale_distrib();\n                const float scale1 = 1.0f - scale2;\n                frame_row1.Scale(scale1);\n                frame_row1.AddVec(scale2, frame_row2);\n                typedef std::pair<int32_t, float> element_t;\n                typedef std::map<int32_t, float> elements_t;\n                elements_t elements;\n                for (int32_t k = 0; k < labels_row1.NumElements(); ++k) {\n                    const element_t& label = labels_row1.GetElement(k);\n                    elements.insert(std::make_pair(label.first, scale1 * label.second));\n                }\n                for (int32_t k = 0; k < labels_row2.NumElements(); ++k) {\n                    const element_t& label = labels_row2.GetElement(k);\n                    auto iter = elements.find(label.first);\n                    if (iter == elements.end()) {\n                        elements.insert(std::make_pair(label.first, scale2 * label.second));\n                    } else {\n                        iter->second += scale2 * label.second;\n                    }\n                }\n                KaldiSparVector labls_mixt(labels.NumCols(), std::vector<element_t>(elements.begin(), elements.end()));\n                labels.SetRow(indx.t, labls_mixt);\n                scale_count += scale2;\n                adnum_count += 1;\n            }\n            gen_matrix = matrix;\n            if (compress) {\n                gen_matrix.Compress();\n            }\n            gen_labels = labels;\n            ++num_mixed;\n        } else {\n            ++num_untouched;\n        }\n        const ExamplePair& example = pair;\n        example_writer.Write(example.first, *example.second);\n        ++num_wrote;\n    }\n}\n\nvoid ExampleMixer::ShiftAndMixup(ExamplePair& _example) {\n    GeneralMatrix& features = FindFeatures(\"input\", _example.second->io);\n    KaldiMatrix feat_main;\n    features.GetMatrix(&feat_main);\n    KaldiMatrix feat_admx(feat_main.NumRows(), feat_main.NumCols());\n    const int32_t shift = ((float_distrib(rand_gen) > 0.5)? 1: -1) * shift_distrib(rand_gen);\n    for (int32_t i = 0; i < feat_main.NumRows(); ++i) {\n        int32_t admx_indx = i + shift;\n        if (admx_indx < 0) {\n            admx_indx = 0;\n        } else if (admx_indx >= feat_main.NumRows()) {\n            admx_indx = feat_main.NumRows() - 1;\n        }\n        feat_admx.Row(i).CopyRowFromMat(feat_main, admx_indx);\n    }\n    const float admx_scale = scale_distrib();\n    const float exam_scale = 1.0f - admx_scale;\n    feat_main.Scale(exam_scale);\n    feat_main.AddMat(admx_scale, feat_admx);\n    features = feat_main;\n    if (compress) {\n        features.Compress();\n    }\n    GeneralMatrix& labels = FindFeatures(\"output\", _example.second->io);\n    KaldiSparMatrix labels_main(labels.GetSparseMatrix());\n    labels_main.Scale(exam_scale);\n    KaldiSparMatrix labels_admx(labels.GetSparseMatrix());\n    labels_admx.Scale(admx_scale);\n    for (int32_t i = 0; i < labels_main.NumRows(); ++i) {\n        int32_t admx_indx = i + shift;\n        if (admx_indx < 0) {\n            admx_indx = 0;\n        } else if (admx_indx >= labels_main.NumRows()) {\n            admx_indx = labels_main.NumRows() - 1;\n        }\n        typedef std::pair<int32_t, float> label_t;\n        typedef std::map<int32_t, float> labels_t;\n        labels_t lab_set;\n        const KaldiSparVector& row_main = labels_main.Row(i);\n        for (int32_t j = 0; j < row_main.NumElements(); ++j) {\n            lab_set.insert(row_main.GetElement(j));\n        }\n        const KaldiSparVector& row_admx = labels_admx.Row(admx_indx);\n        for (int32_t j = 0; j < row_admx.NumElements(); ++j) {\n            const label_t& label = row_admx.GetElement(j);\n            auto iter = lab_set.find(label.first);\n            if (iter == lab_set.end()) {\n                lab_set.insert(label);\n            } else {\n                iter->second += label.second;\n            }\n        }\n        KaldiSparVector labls_dest(labels_main.NumCols(), std::vector<label_t>(lab_set.begin(), lab_set.end()));\n        labels_main.SetRow(i, labls_dest);\n    }\n    labels = labels_main;\n    scale_count += admx_scale;\n    adnum_count += 1;\n    shift_count += shift;\n}\n\nvoid ExampleMixer::AcceptExample(ExamplePair& _example) {\n    if (mix_mode == \"local\") {\n        const bool mixup = (float_distrib(rand_gen) > fixed_egs);\n        if (mixup) {\n            MixupLocal(_example);\n            ++num_mixed;\n        } else {\n            ++num_untouched;\n        }\n        example_writer.Write(_example.first, *_example.second);\n        ++num_wrote;\n    } else if (mix_mode == \"global\") {\n        egs_buffer_t &buffer = eg_to_egs[_example.second.get()];\n        if (buffer.empty()) {\n            buffer.reserve(buff_size);\n        }\n        buffer.push_back(_example);\n        if (buffer.size() == buff_size) {\n            egs_buffer_t buff_copy = buffer;\n            eg_to_egs.erase(_example.second.get());\n            FlushGlobal(buff_copy);\n        }\n    } else if (mix_mode == \"class\") {\n        if (egs_buffer.empty()) {\n            egs_buffer.reserve(buff_size);\n        }\n        egs_buffer.push_back(_example);\n        if (egs_buffer.size() == buff_size) {\n            FlushClass(egs_buffer);\n            egs_buffer.clear();\n        }\n    } else if (mix_mode == \"shift\") {\n        const bool mixup = (float_distrib(rand_gen) > fixed_egs);\n        if (mixup) {\n            ShiftAndMixup(_example);\n            ++num_mixed;\n        } else {\n            ++num_untouched;\n        }\n        example_writer.Write(_example.first, *_example.second);\n        ++num_wrote;\n    } else {\n        KALDI_ERR << \"Unknown mixup mode: \\\"\" << mix_mode << \"\\\"\";\n    }\n    ++num_accepted;\n}\n\nvoid ExampleMixer::Finish() {\n    if (mix_mode == \"global\") {\n        while (!eg_to_egs.empty()) {\n            egs_buffer_t buffer = eg_to_egs.begin()->second;\n            eg_to_egs.erase(eg_to_egs.begin());\n            if (!buffer.empty()) {\n                FlushGlobal(buffer);\n            }\n        }\n    } else if (mix_mode == \"class\") {\n        FlushClass(egs_buffer);\n    }\n}\n\n} }\n\nbool AsBool(const char* _value) {\n    if (_value == nullptr) {\n        KALDI_ERR << \"Pointer to bool string is nullptr.\";\n    }\n    std::string value(_value);\n    boost::to_lower(value);\n    return (value == \"true\") || (value == \"yes\") || (value == \"on\") || (value == \"1\");\n}\n\n// --mix_mode=local ark:/media/work/coding/data/mgb3/train_data/egs.479.ark ark:/dev/null\n// --mix_mode=global ark:/media/work/coding/data/mgb3/train_data/egs.479.ark ark:/dev/null\n// --test_mode=1 --mix_mode=global ark:/media/work/coding/data/mgb3/train_data/cegs.10.ark ark:/dev/null\n// --test_mode=1 --mix_mode=global --distrib=beta2:1.0 ark:/media/work/coding/data/mgb3/train_data/egs.479.ark ark:/dev/null\n\n// --test_mode=1 --mix_mode=local --left_range=3 --right_range=3 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.mix.ark\n// --test_mode=1 --mix_mode=local --left_range=3 --right_range=3 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.mix.ark\n\n// --test_mode=1 --mix_mode=global ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.mix.ark\n// --test_mode=1 --mix_mode=global ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.mix.ark\n\n// --test_mode=1 --mix_mode=global --max_num=1 --distrib=uniform:0.1,0.7 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.mix.ark\n// --test_mode=1 --mix_mode=global --max_num=1 --distrib=uniform:0.1,0.7 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.mix.ark\n// --test_mode=1 --mix_mode=global --max_num=1 --distrib=beta:0.5        ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.mix.ark\n// --test_mode=1 --mix_mode=global --transform=sigmoid:10 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.mix.ark\n\n// --test_mode=1 --mix_mode=local --max_num=1 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.mix.ark\n// --test_mode=1 --mix_mode=local --max_num=1 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.mix.ark\n\n// --test_mode=1 --mix_mode=class --max_num=1 --distrib=uniform:0.1,0.7 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.mix.ark\n// --test_mode=1 --mix_mode=class --max_num=1 --distrib=uniform:0.1,0.7 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.101.mix.ark\n\n// --test_mode=1 --mix_mode=shift --min-shift=2 --max-shift=5 --distrib=uniform:0.1,0.7 ark:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.ark ark,t:/mnt/TOSHIBA/khokhlov/coding/temp/i-vect/temp/mixup/egs.100.mix.ark\n\n/*\n\nwork dir: /mnt/diskD/khokhlov/temp/mixup\n\nark:egs.112.ark ark:/dev/null\n--mix-ivect=false ark:egs.112.ark ark:/dev/null\n--mix-feats=false ark:egs.112.ark ark:/dev/null\n--mix-labels=true ark:egs.112.ark ark:/dev/null\n--mix-labels=false ark:egs.112.ark ark:/dev/null\n--labels-map=1:2 ark:egs.112.ark ark:/dev/null\n--labels-map=1:2 ark:valid.ark ark,t:valid.txt\n\nark:egs.333.ark ark:/dev/null\n\n\n*/\n\nint main(int argc, char *argv[]) {\n    try {\n        using namespace kaldi;\n        using namespace kaldi::nnet3;\n\n        const char *usage =\n            \"Usage:  nnet3-mixup-egs [options] <egs-rspecifier> <egs-wspecifier>\\n\"\n            \"\\n\"\n            \"e.g.\\n\"\n            \"nnet3-mixup-egs ark:train.egs ark:mixup.egs\\n\";\n        ParseOptions po(usage);\n\n        std::string mix_mode(\"global\");\n        const char* env_var = getenv(\"MIXUP_MIX_MODE\");\n        if (env_var != nullptr) {\n            mix_mode = env_var;\n        }\n        po.Register(\"mix-mode\", &mix_mode, R\"(Mixup mode (\"local\", \"global\", \"class\", \"shift\") MIXUP_MIX_MODE)\");\n\n        std::string distrib(\"uniform:0.0,0.5\");\n        env_var = getenv(\"MIXUP_DISTRIB\");\n        if (env_var != nullptr) {\n            distrib = env_var;\n        }\n        po.Register(\"distrib\", &distrib, R\"(Mixup scaling factors distribution (\"uniform:min,max\", \"beta:alpha\", \"beta2:alpha\") MIXUP_DISTRIB)\");\n\n        std::string transform;\n        env_var = getenv(\"MIXUP_TRANSFORM\");\n        if (env_var != nullptr) {\n            transform = env_var;\n        }\n        po.Register(\"transform\", &transform, \"Mixup scaling factor transform function for labels (\\\"sigmoid:k\\\") MIXUP_TRANSFORM\");\n\n        int32_t min_num = 1;\n        env_var = getenv(\"MIXUP_MIN_NUM\");\n        if (env_var != nullptr) {\n            min_num = boost::lexical_cast<int32_t>(env_var);\n        }\n        po.Register(\"min-num\", &min_num, \"Minimum number of admixtures MIXUP_MIN_NUM\");\n\n        int32_t max_num = 1;\n        env_var = getenv(\"MIXUP_MAX_NUM\");\n        if (env_var != nullptr) {\n            max_num = boost::lexical_cast<int32_t>(env_var);\n        }\n        po.Register(\"max-num\", &max_num, \"Maximum number of admixtures MIXUP_MAX_NUM\");\n\n        int32_t min_shift = 1;\n        env_var = getenv(\"MIXUP_MIN_SHIFT\");\n        if (env_var != nullptr) {\n            min_shift = boost::lexical_cast<int32_t>(env_var);\n        }\n        po.Register(\"min-shift\", &min_shift, \"Minimum sequence shift size (shift mode) MIXUP_MIN_SHIFT\");\n\n        int32_t max_shift = 3;\n        env_var = getenv(\"MIXUP_MAX_SHIFT\");\n        if (env_var != nullptr) {\n            max_shift = boost::lexical_cast<int32_t>(env_var);\n        }\n        po.Register(\"max-shift\", &max_shift, \"Maximum sequence shift size (shift mode) MIXUP_MAX_SHIFT\");\n\n        float fixed_egs = 0.10;\n        env_var = getenv(\"MIXUP_FIXED_EGS\");\n        if (env_var != nullptr) {\n            fixed_egs = boost::lexical_cast<float>(env_var);\n        }\n        po.Register(\"fixed-egs\", &fixed_egs, \"Portion of examples to leave untouched MIXUP_FIXED_EGS\");\n\n        float fixed_frames = 0.10;\n        env_var = getenv(\"MIXUP_FIXED_FRAMES\");\n        if (env_var != nullptr) {\n            fixed_frames = boost::lexical_cast<float>(env_var);\n        }\n        po.Register(\"fixed-frames\", &fixed_frames, \"Portion of frames to leave untouched MIXUP_FIXED_FRAMES\");\n\n        int32_t left_range = 3;\n        env_var = getenv(\"MIXUP_LEFT_RANGE\");\n        if (env_var != nullptr) {\n            left_range = boost::lexical_cast<int32_t>(env_var);\n        }\n        po.Register(\"left-range\", &left_range, \"Left range to pick an admixture frame (local mode) MIXUP_LEFT_RANGE\");\n\n        int32_t right_range = 3;\n        env_var = getenv(\"MIXUP_RIGHT_RANGE\");\n        if (env_var != nullptr) {\n            right_range = boost::lexical_cast<int32_t>(env_var);\n        }\n        po.Register(\"right-range\", &right_range, \"Right range to pick an admixture frame (local mode) MIXUP_RIGHT_RANGE\");\n\n        int32_t buff_size = 500;\n        env_var = getenv(\"MIXUP_BUFF_SIZE\");\n        if (env_var != nullptr) {\n            buff_size = boost::lexical_cast<int32_t>(env_var);\n        }\n        po.Register(\"buff-size\", &buff_size, \"Buffer size for data shuffling (global mode) MIXUP_BUFF_SIZE\");\n\n        bool mix_ivect = true;\n        env_var = getenv(\"MIXUP_MIX_IVECT\");\n        if (env_var != nullptr) {\n            mix_ivect = AsBool(env_var);\n        }\n        po.Register(\"mix-ivect\", &mix_ivect, \"Make i-vectors mixtures (MIXUP_MIX_IVECT)\");\n\n        bool mix_feats = true;\n        env_var = getenv(\"MIXUP_MIX_FEATS\");\n        if (env_var != nullptr) {\n            mix_feats = AsBool(env_var);\n        }\n        po.Register(\"mix-feats\", &mix_feats, \"Make features mixtures (MIXUP_MIX_FEATS)\");\n\n        bool mix_labels = true;\n        env_var = getenv(\"MIXUP_MIX_LABELS\");\n        if (env_var != nullptr) {\n            mix_labels = AsBool(env_var);\n        }\n        po.Register(\"mix-labels\", &mix_labels, \"Make labels mixtures (MIXUP_MIX_LABELS)\");\n\n        std::string labels_map_str;\n        env_var = getenv(\"MIXUP_LABELS_MAP\");\n        if (env_var != nullptr) {\n            labels_map_str = env_var;\n        }\n        po.Register(\"labels-map\", &labels_map_str, \"Map to transform labels in admixtures examples (MIXUP_LABELS_MAP)\");\n\n        bool compress = false;\n        env_var = getenv(\"MIXUP_COMPRESS\");\n        if (env_var != nullptr) {\n            compress = AsBool(env_var);\n        }\n        po.Register(\"compress\", &compress, \"Compress features and i-vectors MIXUP_COMPRESS\");\n\n        bool test_mode = false;\n        po.Register(\"test-mode\", &test_mode, \"Self testing mode\");\n\n        po.Read(argc, argv);\n        if (po.NumArgs() < 2) {\n            po.PrintUsage();\n            exit(1);\n        }\n        if (min_num < 1) {\n            KALDI_ERR << \"min_num must be greater or equal 1\";\n        }\n        if (min_num > max_num) {\n            KALDI_ERR << \"min_num must be less or equal max_num\";\n        }\n        if (mix_mode == \"shift\") {\n            if (min_shift < 1) {\n                KALDI_ERR << \"min_shift must be greater or equal 1\";\n            }\n            if (min_shift > max_shift) {\n                KALDI_ERR << \"min_shift must be less or equal max_shift\";\n            }\n        }\n        LabelsMap labels_map(labels_map_str);\n\n        std::string examples_rspecifier = po.GetArg(1);\n        std::string examples_wspecifier = po.GetArg(2);\n\n        SequentialNnetExampleReader example_reader(examples_rspecifier);\n        NnetExampleWriter example_writer(examples_wspecifier);\n\n        ExampleMixer mixer(\n            mix_mode, distrib, transform, example_writer, (size_t) min_num, (size_t) max_num,\n            min_shift, max_shift, fixed_egs, fixed_frames, (size_t) left_range, (size_t) right_range,\n            (size_t) buff_size, mix_ivect, mix_feats, mix_labels, labels_map, compress, test_mode\n        );\n        size_t num_read = 0;\n        for (; !example_reader.Done(); example_reader.Next(), num_read++) {\n            const NnetExample& example = example_reader.Value();\n            ExamplePair ex_pair(example_reader.Key(), ExamplePtr(new NnetExample(example)));\n            mixer.AcceptExample(ex_pair);\n        }\n        mixer.Finish();\n\n        const FloatCounter& scale_count = mixer.ScaleCount();\n        const IntCounter& shift_count = mixer.ShiftCount();\n        const IntCounter& adnum_count = mixer.AdmixNumCount();\n        const IntCounter& left_count = mixer.LeftCount();\n        const IntCounter& right_count = mixer.RightCount();\n        const size_t num_mixed = mixer.NumMixed();\n        const size_t num_untouched = mixer.NumUntouched();\n        const size_t num_accepted = mixer.NumAccepted();\n        const size_t num_wrote = mixer.NumWrote();\n\n        KALDI_LOG << \"Num read: \" << num_read << \" examples\";\n        KALDI_LOG << \"Num accepted: \" << num_accepted << \" examples ( \" << (100.0 * num_accepted / num_read) << \" % of read )\";\n        KALDI_LOG << \"Num wrote: \" << num_wrote << \" examples ( \" << (100.0 * num_wrote / num_read) << \" % of read )\";\n        KALDI_LOG << \"Num mixed: \" << num_mixed << \" examples ( \" << (100.0 * num_mixed / num_accepted) << \" % of accepted )\";\n        KALDI_LOG << \"Num untouched: \" << num_untouched << \" examples ( \" << (100.0 * num_untouched / num_accepted) << \" % of accepted )\";\n        KALDI_LOG << \"Average scale: \" << (boost::format(\"%.4f ( min: %.4f, max: %.4f )\") % scale_count.Average() % scale_count.Minimum() % scale_count.Maximum()).str();\n        if (mix_mode == \"global\") {\n            KALDI_LOG << \"Average num: \" << (boost::format(\"%.4f ( min: %d, max: %d )\") % adnum_count.Average() % adnum_count.Minimum() % adnum_count.Maximum()).str();\n        }\n        if (mix_mode == \"shift\") {\n            KALDI_LOG << \"Average shift: \" << (boost::format(\"%.4f ( min: %.4f, max: %.4f )\") % shift_count.Average() % shift_count.Minimum() % shift_count.Maximum()).str();\n        }\n        if (mix_mode == \"local\") {\n            KALDI_LOG << \"Average total shift: \" << (boost::format(\"%.4f ( min: %d, max: %d, num: %d )\") % shift_count.Average() % shift_count.Minimum() % shift_count.Maximum() % shift_count.Count()).str();\n            KALDI_LOG << \"Average left shift: \" << (boost::format(\"%.4f ( min: %d, max: %d, num: %d )\") % left_count.Average() % left_count.Minimum() % left_count.Maximum() % left_count.Count()).str();\n            KALDI_LOG << \"Average right shift: \" << (boost::format(\"%.4f ( min: %d, max: %d, num: %d )\") % right_count.Average() % right_count.Minimum() % right_count.Maximum() % right_count.Count()).str();\n        }\n\n        return (num_wrote == 0 ? 1 : 0);\n    } catch(const std::exception &e) {\n        std::cerr << e.what() << '\\n';\n        return -1;\n    }\n}\n", "meta": {"hexsha": "9bfa5902ca3d787b9399535f5e566c1ea376b790", "size": 58391, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/nnet3bin/nnet3-mixup-egs.cc", "max_stars_repo_name": "entn-at/mixup", "max_stars_repo_head_hexsha": "8b0cd83f8399dac4ee00b1850b09cc3078fd99c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T22:46:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T21:29:52.000Z", "max_issues_repo_path": "src/nnet3bin/nnet3-mixup-egs.cc", "max_issues_repo_name": "entn-at/mixup", "max_issues_repo_head_hexsha": "8b0cd83f8399dac4ee00b1850b09cc3078fd99c5", "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/nnet3bin/nnet3-mixup-egs.cc", "max_forks_repo_name": "entn-at/mixup", "max_forks_repo_head_hexsha": "8b0cd83f8399dac4ee00b1850b09cc3078fd99c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-09-07T07:10:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T07:24:28.000Z", "avg_line_length": 43.1248153619, "max_line_length": 229, "alphanum_fraction": 0.5990135466, "num_tokens": 15275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1721255292117141}}
{"text": "#pragma once\n\n#include <doctest/doctest.h>\n#include <doctest/trompeloeil.hpp>\n#include <ST/XRTypes.h>\n#include <Eigen/Dense>\n\n#include \"mock/MockIMatrixFactory.hpp\"\n#include \"mock/MockIVectorFactory.hpp\"\n\n#include \"math/WorldAdapter.hpp\"\n#include \"math/IMatrixFactory.hpp\"\n#include \"math/IVectorFactory.hpp\"\n#include \"math/Types.hpp\"\n\n#include \"utility/Test.hpp\"\n#include <array>\n\nusing trompeloeil::_;\nusing northstar::math::MockIMatrixFactory;\nusing northstar::math::IMatrixFactory;\nusing northstar::math::MockIVectorFactory;\nusing northstar::math::IVectorFactory;\nusing northstar::math::types::AffineMatrix4d;\nusing northstar::math::types::Vector3d;\n\nusing namespace northstar::test::utils;\n\nTEST_SUITE(\"WorldAdapter\") {\n    SCENARIO(\"When converting to OpenVR from a StrucureSensor Pose\") {\n        auto pMockMatrixFactory = std::make_shared<MockIMatrixFactory>();\n        auto pMockVectorFactory = std::make_shared<MockIVectorFactory>();\n        auto Subject = northstar::math::CWorldAdapter(\n            pMockMatrixFactory,\n            pMockVectorFactory);\n\n        ALLOW_CALL(*pMockMatrixFactory, FromRowMajorArray(_))\n            .RETURN(CreateMatrixFromArray(_1));\n\n        ALLOW_CALL(*pMockVectorFactory, V3DFromArray(_))\n            .RETURN(Vector3d(_1[0], _1[1], _1[2]));\n\n        // TODO: test\n        WHEN(\"Given a pose\") {\n            THEN(\"it returns the appropriate open vr space matrix\") {}\n        }\n    }\n\n    SCENARIO(\"World adapter should convert vectors from structure sensor space to OPenVR Space\") {\n        auto pMockMatrixFactory = std::make_shared<MockIMatrixFactory>();\n        auto pMockVectorFactory = std::make_shared<MockIVectorFactory>();\n        auto Subject = northstar::math::CWorldAdapter(\n            pMockMatrixFactory,\n            pMockVectorFactory);\n\n        ALLOW_CALL(*pMockVectorFactory, V3DFromArray(_))\n            .RETURN(Vector3d(_1[0], _1[1], _1[2]));\n\n        // TODO: test\n        WHEN(\"Given a linear vector in structure sensor space\") {\n            std::array<double, 3> adStructureVector{ 1, 2, 3 };\n            std::array<double, 3> adExpected{ -1, -2, -3 };\n            THEN(\"It returns the apropriate open vr space vector\") {\n                auto Result = Subject.FromStructureSensorLinearVectorArrayToOpenVRSpace(adStructureVector);\n                CompareIndexed(Result, adExpected, 0, 2);\n            }\n        }\n\n        // TODO: test\n        WHEN(\"Given an angular vector in structure sensor space\") {\n            std::array<double, 3> adStructureVector{ 1, 2, 3 };\n            std::array<double, 3> adExpected{ -1, -2, -3 };\n            THEN(\"It returns the apropriate open vr space vector\") {\n                auto Result = Subject.FromStructureSensorAngularVectorArrayToOpenVRSpace(adStructureVector);\n                CompareIndexed(Result, adExpected, 0, 2);\n            }\n        }\n    }\n\n    SCENARIO(\"World adapter should support converting from LeapMotion space to OVR space\") {\n        auto pMockMatrixFactory = std::make_shared<MockIMatrixFactory>();\n        auto pMockVectorFactory = std::make_shared<MockIVectorFactory>();\n        auto Subject = northstar::math::CWorldAdapter(\n            pMockMatrixFactory,\n            pMockVectorFactory);\n\n        ALLOW_CALL(*pMockVectorFactory, V3DFromArray(_))\n            .RETURN(Vector3d(_1[0], _1[1], _1[2]));\n\n        // TODO: Test\n        WHEN(\"asked to generate a conversion matrix given a config\") {\n            THEN(\"the conversion matrix is as expected\") {\n\n            }\n        }\n\n        // TODO: Test\n        WHEN(\"Asked to use a conversion matrix to convert velocity in leap space to hmp space\") {\n            THEN(\"the conversion is as expected\") {\n\n            }\n        }\n\n        // TODO: Test\n        WHEN(\"Asked to use a conversion matrix to convert drive pose to hmd space\") {\n            THEN(\"the conversion matrix is as expected\") {\n\n            }\n        }\n    }\n\n    // TOOD: Test\n    SCENARIO(\"World adapter should support converting from UnitySpace (used for configuration) to OpenVR space\") {\n        auto pMockMatrixFactory = std::make_shared<MockIMatrixFactory>();\n        auto pMockVectorFactory = std::make_shared<MockIVectorFactory>();\n        auto Subject = northstar::math::CWorldAdapter(\n            pMockMatrixFactory,\n            pMockVectorFactory);\n\n        ALLOW_CALL(*pMockVectorFactory, V3DFromArray(_))\n            .RETURN(Vector3d(_1[0], _1[1], _1[2]));\n\n        WHEN(\"Converting a Unity Pose to an OpenVR Pose\") {\n            THEN(\"THe conversion is as expected\") {}\n        }\n\n        WHEN(\"Converting a Unity Quaternion to HMD Quaternion\") {\n            THEN(\"The conversion quatertion is as expected\") {}\n        }\n\n        WHEN(\"Converting a Unity Position to HMD Position\") {\n            THEN(\"The conversion position is as expected\") {}\n        }\n\n        WHEN(\"Converting a Unity LRTB Projection Extent\") {\n            THEN(\"The conversion extents are as expected\") {}\n        }\n    }\n\n    // TOOD: Test\n    SCENARIO(\"World adapter should support converting between Unity space UV and OpenVR space UV\") {\n        auto pMockMatrixFactory = std::make_shared<MockIMatrixFactory>();\n        auto pMockVectorFactory = std::make_shared<MockIVectorFactory>();\n        auto Subject = northstar::math::CWorldAdapter(\n            pMockMatrixFactory,\n            pMockVectorFactory);\n\n        ALLOW_CALL(*pMockVectorFactory, V3DFromArray(_))\n            .RETURN(Vector3d(_1[0], _1[1], _1[2]));\n\n        WHEN(\"Converting a Unity UV to an OpenVR UV\") {\n            THEN(\"THe conversion is as expected\") {}\n        }\n\n        WHEN(\"Converting an OpenVR UV to a Unity UV\") {\n            THEN(\"THe conversion is as expected\") {}\n        }\n    }\n}\n", "meta": {"hexsha": "e6383d0061dd25c332fb24826ab04088a9c19028", "size": 5700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "northstar/src/spec/WorldAdapterSpec.cpp", "max_stars_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_stars_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "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": "northstar/src/spec/WorldAdapterSpec.cpp", "max_issues_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_issues_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "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": "northstar/src/spec/WorldAdapterSpec.cpp", "max_forks_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_forks_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "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": 35.625, "max_line_length": 114, "alphanum_fraction": 0.6314035088, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.1721255258342032}}
{"text": "#include <string>\n#include <iostream>\n#include <fstream>\n\n#include \"read.h\"\n\n#include <boost/algorithm/string.hpp>\n\nvoid split_line(System *sys, std::vector<std::string> linevect, int num);\nvoid number_of_filaments(System *sys);    \n\nvoid number_of_filaments(System *sys) \n{\n    std::string fil_file = sys->m_files[\"dir\"] + sys->m_files[\".fil\"];\n    std::ifstream myfile(fil_file);\n    std::string line;\n\n    int line_num = 0;\n    \n    if (myfile.is_open()) {\n        while (getline(myfile, line)) {\n            std::stringstream ss(line);\n            std::string word;\n            std::string linestr(line);\n                        \n            if (line_num == 3)\n                sys->fil_len = atoi(linestr.c_str());\n\n            line_num++;\n        }\n        \n        myfile.close();\n    } else\n        throw std::invalid_argument(\"Unable to open filament file.\");\n}\n\nvoid create_fil_corners(System *sys) \n{\n    std::cout << \"** Creating filament corners\" << std::endl;\n    \n    // For now we assume the filaments are lying in one plane.\n    // i.o.w. we have to implement algorithms for filaments \n    // that are lying at an angle.\n    for (auto fil : sys->filVect) {\n        double lx = fil->length*fil->L.x;\n        double ly = fil->length*fil->L.y;        \n\n        double wx = fil->width*fil->W.x;\n        double wy = fil->width*fil->W.y;\n\n        double h = fil->height*fil->H.z;\n        \n        if (fil->L.x == 1.0) {\n            // Bot-Left\n            fil->corners[0].x = fil->S.x;\n            fil->corners[0].y = fil->S.y - wy;\n            fil->corners[0].z = fil->S.z + h;\n            // Bot-Right\n            fil->corners[1].x = fil->S.x;\n            fil->corners[1].y = fil->S.y - wy;\n            fil->corners[1].z = fil->S.z - h;\n            // Top-Right\n            fil->corners[2].x = fil->S.x;\n            fil->corners[2].y = fil->S.y + wy;\n            fil->corners[2].z = fil->S.z - h;\n            // Top-Left\n            fil->corners[3].x = fil->S.x;\n            fil->corners[3].y = fil->S.y + wy;\n            fil->corners[3].z = fil->S.z + h;\n\n            // Bot-Left\n            fil->corners[4].x = fil->S.x - lx;\n            fil->corners[4].y = fil->S.y - wy;\n            fil->corners[4].z = fil->S.z + h;\n            // Bot-Right\n            fil->corners[5].x = fil->S.x - lx;\n            fil->corners[5].y = fil->S.y - wy;\n            fil->corners[5].z = fil->S.z - h;\n            // Top-Right\n            fil->corners[6].x = fil->S.x - lx;\n            fil->corners[6].y = fil->S.y + wy;\n            fil->corners[6].z = fil->S.z - h;\n            // Top-Left\n            fil->corners[7].x = fil->S.x - lx;\n            fil->corners[7].y = fil->S.y + wy;\n            fil->corners[7].z = fil->S.z + h;\n        }\n\n        if (fil->L.y == 1.0) {\n            // Bot-Left\n            fil->corners[0].x = fil->S.x - wx;\n            fil->corners[0].y = fil->S.y;\n            fil->corners[0].z = fil->S.z + h;\n            // Bot-Right\n            fil->corners[1].x = fil->S.x - wx;\n            fil->corners[1].y = fil->S.y;\n            fil->corners[1].z = fil->S.z - h;\n            // Top-Right\n            fil->corners[2].x = fil->S.x + wx;\n            fil->corners[2].y = fil->S.y;\n            fil->corners[2].z = fil->S.z - h;\n            // Top-Left\n            fil->corners[3].x = fil->S.x + wx;\n            fil->corners[3].y = fil->S.y;\n            fil->corners[3].z = fil->S.z + h;\n\n            // Bot-Left\n            fil->corners[4].x = fil->S.x - wx;\n            fil->corners[4].y = fil->S.y - ly;\n            fil->corners[4].z = fil->S.z + h;\n            // Bot-Right\n            fil->corners[5].x = fil->S.x - wx;\n            fil->corners[5].y = fil->S.y - ly;\n            fil->corners[5].z = fil->S.z - h;\n            // Top-Right\n            fil->corners[6].x = fil->S.x - wx;\n            fil->corners[6].y = fil->S.y + ly;\n            fil->corners[6].z = fil->S.z - h;\n            // Top-Left\n            fil->corners[7].x = fil->S.x - wx;\n            fil->corners[7].y = fil->S.y + ly;\n            fil->corners[7].z = fil->S.z + h;\n        }\n    }\n\n    std::cout << \"-- \" << \"\\033[1;32m\" << \"success\" << \"\\033[0m\" << std::endl;\n}\n\nvoid read_filaments(System *sys) \n{\n    std::string fil_file = sys->m_files[\"dir\"] + sys->m_files[\".fil\"];\n    std::cout << \"\\n* Reading filament file: \" << fil_file << std::endl;\n    std::ifstream myfile(fil_file);\n    std::string line;\n\n    number_of_filaments(sys);\n\n    int line_num = 0;\n    \n    if (myfile.is_open()) {\n        while (getline(myfile, line)) {\n            std::stringstream ss(line);\n            std::string word;\n            std::string linestr(line);\n\n            if (line_num > 3) {\n                std::vector<std::string> linevect;\n                boost::split(linevect, linestr, boost::is_any_of(\" \"));\n                split_line(sys, linevect, line_num);\n            }\n\n            line_num++;\n        }\n        \n        myfile.close();\n    } else\n        throw std::invalid_argument(\"Unable to open filament file.\");\n\n    create_fil_corners(sys);\n\n    // Initialize all filament currents to zero.\n    for (auto fil : sys->filVect) {\n        fil->stroom.x = 0.0;\n        fil->stroom.y = 0.0;\n        fil->stroom.z = 0.0;        \n    }    \n    \n    std::cout << \"- \" << \"\\033[1;32m\" << \"success\" << \"\\033[0m\" << std::endl;\n}\n\n// id layer Sx Sy Sz Lx Ly Lz Wx Wy Wz Hx Hy Hz length width height area\n// 0  1     2  3  4  5  6  7  8  9  10 11 12 13 14     15    16     17\nvoid split_line(System *sys, std::vector<std::string> linevect, int num) {\n    double um = 10e12;\n\n    Filament *fil = new Filament;\n\n    fil->id = std::stod(linevect[0]);\n    fil->layer = linevect[1];\n    \n    fil->S.x = std::stod(linevect[2]) * um;\n    fil->S.y = std::stod(linevect[3]) * um;\n    fil->S.z = std::stod(linevect[4]) * um;\n\n    fil->L.x = std::stod(linevect[5]);\n    fil->L.y = std::stod(linevect[6]);\n    fil->L.z = std::stod(linevect[7]);\n\n    fil->W.x = std::stod(linevect[8]);\n    fil->W.y = std::stod(linevect[9]);\n    fil->W.z = std::stod(linevect[10]);\n\n    fil->H.x = std::stod(linevect[11]);\n    fil->H.y = std::stod(linevect[12]);\n    fil->H.z = std::stod(linevect[13]);\n    \n    fil->length = std::stod(linevect[14]) * um;\n    fil->width = std::stod(linevect[15]) * um;\n    fil->height = std::stod(linevect[16]) * um;\n    fil->area = std::stod(linevect[17]) * um;\n\n    sys->filVect.push_back(fil);\n}\n\nvoid read_mat(System *sys, std::string mat_name) {\n    mat_name = mat_name + \".mat\";\n    std::string mat_file = sys->m_files[\"dir\"] + mat_name;\n    std::ifstream myfile(mat_file);\n    std::string line;\n    \n    std::cout << \"Reading port: \" << \"\\033[1;35m\" + mat_name + \"\\033[0m\" << std::endl;\n\n    int num = 0;\n    \n    if (myfile.is_open()) {\n        while (getline(myfile, line)) {\n            std::stringstream ss(line);\n            std::string word;\n            std::string linestr(line);\n\n            std::vector<std::string> linevect;\n            boost::trim_if(linestr, boost::is_any_of(\"\\t \"));\n            boost::split(linevect, linestr, boost::is_any_of(\"\\t \"), boost::token_compress_on);\n\n            double x = std::stod(linevect[3]);\n\n            sys->filVect[num]->stroom.x += x;\n            sys->filVect[num]->stroom.y += std::stod(linevect[4]);\n            sys->filVect[num]->stroom.z += std::stod(linevect[5]);\n    \n            num++;\n        }\n\n        myfile.close();\n    } else\n        throw std::invalid_argument(\"Unable to open port file.\");\n}\n\nstd::map <std::string, Node *> filament_point_currents(System *sys)\n{\n    std::map <std::string, Node *> filpoints;\n\n    int count = 0;\n    \n    for (auto fil : sys->filVect) {\n        Node *p = new Node;\n        Node *c = new Node;\n\n        p->x = fil->S.x;\n        p->y = fil->S.y;\n        p->z = fil->S.z;\n        \n        c->x = fil->stroom.x;\n        c->y = fil->stroom.y;\n        c->z = fil->stroom.z;\n\n        std::string nodekey = std::to_string(p->x) + \" \" + std::to_string(p->y) + \" \" + std::to_string(p->z);\n\n        if (filpoints[nodekey] == 0) {\n            filpoints[nodekey] = c;\n        }\n        else {\n            Node *c_prev = filpoints[nodekey];\n            c->x += c_prev->x;\n            c->y += c_prev->y;\n            c->z += c_prev->z;\n            filpoints[nodekey] = c;\n        }\n    }\n\n    return filpoints;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "a2e764e65b52f3933e8685de7c8c72cd7f73c7fc", "size": 8305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/read.cpp", "max_stars_repo_name": "rubenvanstaden/Magix", "max_stars_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "max_stars_repo_licenses": ["CECILL-B"], "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/read.cpp", "max_issues_repo_name": "rubenvanstaden/Magix", "max_issues_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "max_issues_repo_licenses": ["CECILL-B"], "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/read.cpp", "max_forks_repo_name": "rubenvanstaden/Magix", "max_forks_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3462897527, "max_line_length": 109, "alphanum_fraction": 0.4805538832, "num_tokens": 2564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.1720237717147937}}
{"text": "/*\n *\n * BigInt\n * ledger-core\n *\n * Created by Pierre Pollastri on 15/09/2016.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Ledger\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 \"BigInt.h\"\n#include <cstdlib>\n#include <iostream>\n#include <algorithm>\n#include \"../collections/collections.hpp\"\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <cstdlib>\n#include <utils/endian.h>\n\nnamespace ledger {\n    namespace core {\n\n        const BigInt BigInt::ZERO = BigInt(0);\n        const BigInt BigInt::ONE = BigInt(1);\n        const BigInt BigInt::TEN = BigInt(10);\n        const std::string BigInt::DIGITS = std::string(\"0123456789abcdefghijklmnopqrstuvwxyz\");\n        const int BigInt::MIN_RADIX = 2;\n        const int BigInt::MAX_RADIX = 36;\n\n        BigInt::BigInt() {\n            _bigd = bdNew();\n            _negative = false;\n        }\n\n        BigInt::BigInt(const BigInt& cpy) {\n            _bigd = bdNew();\n            _negative = cpy._negative;\n            bdSetEqual(_bigd, cpy._bigd);\n        }\n\n        BigInt::BigInt(const void *data, size_t length, bool negative) : BigInt() {\n            bdConvFromOctets(_bigd, reinterpret_cast<const unsigned char *>(data), length);\n            _negative = negative;\n        }\n\n        BigInt::BigInt(const std::vector<uint8_t> &data, bool negative)\n        : BigInt(data.data(), data.size(), negative){\n\n        }\n\n        BigInt::BigInt(int value)\n                : BigInt() {\n            bdSetShort(_bigd, (bdigit_t)std::abs(value));\n            if (value < 0) {\n                _negative = true;\n            }\n        }\n\n        BigInt::BigInt(unsigned int value) : BigInt() {\n            bdSetShort(_bigd, (bdigit_t)value);\n            _negative = false;\n        }\n\n        BigInt::BigInt(unsigned long long value) : BigInt() {\n            auto bytes = endianness::scalar_type_to_array<unsigned long long>(value, endianness::Endianness::BIG);\n            bdConvFromOctets(_bigd, reinterpret_cast<const unsigned char *>(bytes), sizeof(unsigned long long));\n            std::free(bytes);\n            _negative = false;\n        }\n\n        BigInt::BigInt(int64_t value) : BigInt() {\n            auto bytes = endianness::scalar_type_to_array<int64_t >(std::abs(value), endianness::Endianness::BIG);\n            bdConvFromOctets(_bigd, reinterpret_cast<const unsigned char *>(bytes), sizeof(int64_t));\n            std::free(bytes);\n            _negative = value < 0LL;\n        }\n\n        BigInt::BigInt(const std::string& str) : BigInt(str, 10)\n        {};\n\n        BigInt& BigInt::assignI64(int64_t value) {\n            auto bytes = endianness::scalar_type_to_array<int64_t >(std::abs(value), endianness::Endianness::BIG);\n            bdConvFromOctets(_bigd, reinterpret_cast<const unsigned char *>(bytes), sizeof(int64_t));\n            std::free(bytes);\n            _negative = value < 0LL;\n            return *this;\n        }\n\n        BigInt::BigInt(const std::string &str, int radix) : BigInt() {\n            if (radix == 10) {\n                // handle digit representation\n                if (!all_digits(str)) {\n                    throw std::invalid_argument(\"Non-numeric base 10 big int\");\n                }\n\n                _negative = str[0] == '-';\n                bdConvFromDecimal(_bigd, str.c_str());\n            } else if (radix == 16) {\n                bdConvFromHex(_bigd, str.c_str());\n            } else {\n                throw std::invalid_argument(\"Cannot handle radix\");\n            }\n        }\n\n        BigInt::~BigInt() {\n            if (_bigd != nullptr) {\n                bdFree(&_bigd);\n            }\n        }\n\n        int BigInt::toInt() const {\n            return bdToShort(_bigd) * (_negative ? -1 : 1);\n        }\n\n        unsigned int BigInt::toUnsignedInt() const {\n            return bdToShort(_bigd);\n        }\n\n        std::string BigInt::toString() const {\n            size_t nchars = bdConvToDecimal(_bigd, NULL, 0);\n            auto s = std::shared_ptr<char>(new char[nchars + 1]);\n            bdConvToDecimal(_bigd, s.get(), nchars + 1);\n            auto out = std::string(s.get());\n            if (this->isNegative()) {\n                out = \"-\" + out;\n            }\n            return out;\n        }\n\n        std::string BigInt::toHexString() const {\n            size_t nchars = bdConvToHex(_bigd, NULL, 0);\n            auto s = std::shared_ptr<char>(new char[nchars + 1]);\n            bdConvToHex(_bigd, s.get(), nchars + 1);\n            auto out = std::string(s.get());\n            if (out.length() % 2 != 0) {\n                out = \"0\" + out;\n            }\n            return out;\n        }\n\n        unsigned long BigInt::getBitSize() const {\n            return bdSizeof(_bigd) * sizeof(SimpleInt) * 8;\n        }\n\n        BigInt *BigInt::from_hex(const std::string &str) {\n            return new BigInt(str, 16);\n        }\n\n        BigInt *BigInt::from_dec(const std::string &str) {\n            return new BigInt(str, 10);\n        }\n\n        BigInt BigInt::operator+(const BigInt &rhs) const {\n            if (rhs.isNegative() && !this->isNegative()) {\n                return *this - rhs.positive();\n            } else if (this->isNegative() && !rhs.isNegative()) {\n                return rhs - this->positive();\n            }\n            BigInt result;\n            bdAdd(result._bigd, this->_bigd, rhs._bigd);\n            result._negative = rhs.isNegative() && this->isNegative();\n            return result;\n        }\n\n        BigInt BigInt::operator-(const BigInt &rhs) const {\n            if (this->isPositive() && rhs.isNegative()) {\n                return *this + rhs.positive();\n            } else if (this->isNegative() && rhs.isPositive()) {\n                return *this + rhs.negative();\n            } else if (rhs > *this) {\n                return (rhs - *this).negative();\n            }\n            BigInt result;\n            bdSubtract(result._bigd, this->_bigd, rhs._bigd);\n            return result;\n        }\n\n        BigInt BigInt::operator*(const BigInt &rhs) const {\n            BigInt result;\n            bdMultiply(result._bigd, this->_bigd, rhs._bigd);\n            result._negative = this->isNegative() != rhs.isNegative();\n            return result;\n        }\n\n        BigInt BigInt::operator/(const BigInt &rhs) const {\n            BigInt result;\n            BigInt remainder;\n            bdDivide(result._bigd, remainder._bigd, this->_bigd, rhs._bigd);\n            result._negative = this->isNegative() != rhs.isNegative();\n            return result;\n        }\n\n        BigInt BigInt::operator%(const BigInt &rhs) const {\n            BigInt result;\n            BigInt remainder;\n            bdDivide(result._bigd, remainder._bigd, this->_bigd, rhs._bigd);\n            remainder._negative = this->isNegative();\n            return remainder;\n        }\n\n        BigInt &BigInt::operator++() {\n            if (this->isNegative()) {\n                bdDecrement(_bigd);\n            } else {\n                bdIncrement(_bigd);\n            }\n            return *this;\n        }\n\n        BigInt BigInt::operator++(int) {\n            BigInt temp = *this;\n            ++*this;\n            return temp;\n        }\n\n        BigInt &BigInt::operator--() {\n            if (this->isPositive()) {\n                bdDecrement(_bigd);\n            } else {\n                bdIncrement(_bigd);\n            }\n            return *this;\n        }\n\n        BigInt BigInt::operator--(int) {\n            BigInt temp = *this;\n            ++*this;\n            return temp;\n        }\n\n        BigInt& BigInt::operator=(const BigInt &a) {\n            if (this != &a) {\n                bdSetEqual(_bigd, a._bigd);\n                _negative = a._negative;\n            }\n\n            return *this;\n        }\n\n        BigInt& BigInt::operator=(BigInt&& a) {\n            if (this == &a) {\n                return *this;\n            }\n\n            if (_bigd != nullptr) {\n                bdFree(&_bigd);\n            }\n\n            _bigd = a._bigd;\n            _negative = a._negative;\n            a._bigd = nullptr;\n\n            return *this;\n        }\n\n        bool BigInt::isNegative() const {\n            return _negative && !this->isZero();\n        }\n\n        bool BigInt::isPositive() const {\n            return !_negative || this->isZero();\n        }\n\n        bool BigInt::isZero() const {\n            return bdIsZero(_bigd) != 0;\n        }\n\n        BigInt BigInt::negative() const {\n            BigInt result = *this;\n            result._negative = true;\n            return result;\n        }\n\n        BigInt BigInt::positive() const {\n            BigInt result = *this;\n            result._negative = false;\n            return result;\n        }\n\n        bool BigInt::operator<(const BigInt &rhs) const {\n            if (this->isNegative() && rhs.isPositive()) {\n                return true;\n            } else if (this->isPositive() && rhs.isNegative()) {\n                return false;\n            } else if (this->isNegative() && rhs.isNegative()) {\n                return bdCompare(this->_bigd, rhs._bigd) == 1;\n            }\n            return bdCompare(this->_bigd, rhs._bigd) == -1;\n        }\n\n        bool BigInt::operator<=(const BigInt &rhs) const {\n            if (this->isNegative() && rhs.isPositive()) {\n                return true;\n            } else if (this->isPositive() && rhs.isNegative()) {\n                return false;\n            } else if (this->isNegative() && rhs.isNegative()) {\n                return bdCompare(this->_bigd, rhs._bigd) >= 0;\n            }\n            return bdCompare(this->_bigd, rhs._bigd) <= 0;\n        }\n\n        bool BigInt::operator==(const BigInt &rhs) const {\n            return this->_negative == rhs._negative && bdCompare(this->_bigd, rhs._bigd) == 0;\n        }\n\n        bool BigInt::operator!=(const BigInt &rhs) const {\n            return !(*this == rhs);\n        }\n\n        bool BigInt::operator>(const BigInt &rhs) const {\n            return rhs < *this;\n        }\n\n        bool BigInt::operator>=(const BigInt &rhs) const {\n            return rhs == *this || rhs < *this;\n        }\n\n        BigInt BigInt::pow(unsigned short p) const {\n            BigInt result;\n            bdPower(result._bigd, _bigd, p);\n            result._negative = isNegative() && (p % 2 != 0 || p == 0);\n            return result;\n        }\n\n        std::vector<uint8_t> BigInt::toByteArray() const {\n            size_t nchars = bdConvToOctets(_bigd, NULL, 0);\n            std::vector<uint8_t> out = std::vector<uint8_t >(nchars);\n            bdConvToOctets(_bigd, reinterpret_cast<unsigned char *>(out.data()), nchars);\n            return out;\n        }\n\n        uint64_t BigInt::toUint64() const {\n            std::vector<uint8_t> result(sizeof(uint64_t));\n            bdConvToOctets(_bigd, result.data(), sizeof(uint64_t));\n            if (ledger::core::endianness::isSystemLittleEndian()) {\n                std::reverse(result.begin(), result.end());\n            }\n            return reinterpret_cast<uint64_t *>(result.data())[0];\n        }\n\n        int64_t BigInt::toInt64() const {\n            std::vector<uint8_t> result(sizeof(uint64_t));\n            bdConvToOctets(_bigd, result.data(), sizeof(uint64_t));\n            if (ledger::core::endianness::isSystemLittleEndian()) {\n                std::reverse(result.begin(), result.end());\n            }\n            return reinterpret_cast<int64_t *>(result.data())[0] * (_negative ? -1 : 1);\n        }\n\n        int BigInt::compare(const BigInt &rhs) const {\n            if (this->isNegative() && rhs.isPositive()) {\n                return -1;\n            } else if (this->isPositive() && rhs.isNegative()) {\n                return 1;\n            } else if (this->isNegative() && rhs.isNegative()) {\n                return -bdCompare(this->_bigd, rhs._bigd);\n            }\n            return bdCompare(this->_bigd, rhs._bigd);\n        }\n\n        BigInt BigInt::fromHex(const std::string &str) {\n            return BigInt(str, 16);\n        }\n\n        BigInt BigInt::fromDecimal(const std::string &str) {\n            return BigInt(str, 10);\n        }\n\n        BigInt BigInt::fromString(const std::string &str) {\n            if (strings::startsWith(str, \"0x\")) {\n                return BigInt::fromHex(str.substr(2, str.length()));\n            } else {\n                return BigInt::fromDecimal(str);\n            }\n        }\n\n        BigInt::BigInt(BigInt &&mov) {\n            _bigd = mov._bigd;\n            _negative = mov._negative;\n            mov._bigd = nullptr;\n        }\n\n        bool BigInt::all_digits(std::string const& s) {\n            auto it = s.cbegin();\n            auto end = s.cend();\n\n            if (it != end && (*it == '-' || *it == '+')) {\n                it++; // move past the first character\n            }\n\n            return std::all_of(it, end, [](char c) { return isdigit(c); });\n        }\n\n        BigInt BigInt::fromFloatString(const std::string &str, int scaleFactor) {\n            namespace mp = boost::multiprecision;\n\n            mp::cpp_dec_float_50 f(str);\n            mp::cpp_dec_float_50 scale = mp::pow(mp::cpp_dec_float_50(10), (float) scaleFactor);\n            f = f * scale;\n\n            bool isNegative = f < 0;\n\n            if (isNegative)\n                f = f * -1;\n\n            mp::uint256_t i;\n            i.assign(f);\n\n            auto size = i.backend().size();\n            auto *limbs = i.backend().limbs();\n\n            // Here is the weird part. Boost is dividing the number into \"limbs\", the limbs size may differ depending on the\n            // platform but there are always ordered like little endian (the least significant limb is always first).\n            // We can't forget that limb endianness depends on the architecture. To avoid having to perform multiple\n            // swaps for every architecture we forces the whole limb \"byte array\" to be ordered like a bit uint256 in little endian\n            // number and then swap all of it in big endian.\n            if (endianness::getSystemEndianness() == endianness::Endianness::BIG) {\n                for (auto offset = 0; offset < size; offset++) {\n                    endianness::swapToEndianness(limbs + offset, sizeof(mp::limb_type),\n                                                 endianness::getSystemEndianness(), endianness::Endianness::LITTLE);\n                }\n            }\n            endianness::swapToEndianness(limbs, size * sizeof(mp::limb_type), endianness::Endianness::LITTLE, endianness::Endianness::BIG);\n            return BigInt(limbs, size * sizeof(mp::limb_type), isNegative);\n        }\n\n    }\n}\n", "meta": {"hexsha": "a7f741ef386cb74ffa3af9a09d0f49a65b6a36a9", "size": 15610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/math/BigInt.cpp", "max_stars_repo_name": "RomanWlm/lib-ledger-core", "max_stars_repo_head_hexsha": "8c068fccb074c516096abb818a4e20786e02318b", "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": "core/src/math/BigInt.cpp", "max_issues_repo_name": "RomanWlm/lib-ledger-core", "max_issues_repo_head_hexsha": "8c068fccb074c516096abb818a4e20786e02318b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-05T11:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T11:33:07.000Z", "max_forks_repo_path": "core/src/math/BigInt.cpp", "max_forks_repo_name": "RomanWlm/lib-ledger-core", "max_forks_repo_head_hexsha": "8c068fccb074c516096abb818a4e20786e02318b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-16T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-16T13:08:45.000Z", "avg_line_length": 34.6119733925, "max_line_length": 139, "alphanum_fraction": 0.53119795, "num_tokens": 3584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17202376828564006}}
{"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_IEEE_FUNCTIONS_SIMD_COMMON_SIGNNZ_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_SIMD_COMMON_SIGNNZ_HPP_INCLUDED\n\n#include <boost/simd/ieee/functions/signnz.hpp>\n#include <boost/simd/include/functions/simd/bitwise_or.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/include/functions/simd/shift_right.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/signmask.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/dispatch/attributes.hpp>\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <boost/simd/include/functions/simd/if_allbits_else.hpp>\n#include <boost/simd/include/functions/simd/is_nan.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( signnz_, tag::cpu_\n                                    , (A0)(X)\n                                    , ((simd_<integer_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      typedef typename meta::scalar_of<A0>::type sA0;\n      return b_or(shrai(a0, (sizeof(sA0)*8-2)), One<A0>());\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( signnz_, tag::cpu_\n                                    , (A0)(X)\n                                    , ((simd_<unsigned_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE result_type operator()(const A0&) const\n    {\n      return One<A0>();\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( signnz_, tag::cpu_\n                                    , (A0)(X)\n                                    , ((simd_<floating_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      #ifndef BOOST_SIMD_NO_NANS\n      return if_nan_else(is_nan(a0), b_or(One<A0>(), b_and(Signmask<A0>(), a0)));\n      #else\n      return b_or(One<A0>(), b_and(Signmask<A0>(), a0));\n      #endif\n      ;\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "bce8eacbb6ea68f912a11deb2d2254b8e0feca4c", "size": 2599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/ieee/functions/simd/common/signnz.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/ieee/functions/simd/common/signnz.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/ieee/functions/simd/common/signnz.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.1216216216, "max_line_length": 81, "alphanum_fraction": 0.5529049634, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17202376485648646}}
{"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/GeometryOptimization/NtOptimizer.h\"\n#include \"Utils/CalculatorBasics/CalculationRoutines.h\"\n#include \"Utils/Geometry/AtomCollection.h\"\n#include \"Utils/Geometry/ElementInfo.h\"\n#include \"Utils/GeometryOptimization/NtOptimizerSettings.h\"\n#include \"Utils/Optimizer/GradientBased/Bfgs.h\"\n#include <array>\n#include <boost/exception/diagnostic_information.hpp>\n#include <cmath>\n#include <valarray>\n\nnamespace Scine {\nnamespace Utils {\n\nint NtOptimizer::optimize(AtomCollection& atoms, Core::Log& log) {\n  this->sanityCheck(atoms);\n  // Configure Calculator\n  _calculator.setStructure(atoms);\n  _calculator.setRequiredProperties(Utils::Property::Energy | Utils::Property::Gradients);\n  Utils::PositionCollection coordinates = atoms.getPositions();\n  const unsigned int nAtoms = atoms.size();\n  int cycle = 0;\n  _values.clear();\n  for (unsigned int loop = 0; loop < this->check.maxIter; loop++) {\n    cycle++;\n    // Micro cycles performed in true Cartesians due to constraints\n    if (cycle > 1 && useMicroCycles && nAtoms > 2) {\n      // Define micro iteration optimizer\n      Bfgs bfgs;\n      bfgs.projection = nullptr;\n      bfgs.trustRadius = 0.2;\n      bfgs.useTrustRadius = true;\n      // Define micro iteration convergence\n      GradientBasedCheck microIterCheck;\n      microIterCheck.maxIter = (fixedNumberOfMicroCycles ? numberOfMicroCycles : std::min(cycle, numberOfMicroCycles));\n      // Define micro iteration update\n      auto const microIterUpdate = [&](const Eigen::VectorXd& parameters, double& value, Eigen::VectorXd& gradients) {\n        coordinates = Eigen::Map<const Utils::PositionCollection>(parameters.data(), nAtoms, 3);\n        _calculator.modifyPositions(coordinates);\n        _calculator.setRequiredProperties(Utils::Property::Energy | Utils::Property::Gradients);\n        atoms.setPositions(coordinates);\n        Results results = CalculationRoutines::calculateWithCatch(_calculator, log, \"Calculation in NT optimization failed.\");\n        value = results.get<Property::Energy>();\n        // Apply Cartesian constraints\n        auto gradientMatrix = results.get<Property::Gradients>();\n        this->updateGradients(atoms, value, gradientMatrix);\n        gradients = Eigen::Map<const Eigen::VectorXd>(gradientMatrix.data(), nAtoms * 3);\n      };\n      // Run micro iterations\n      Eigen::VectorXd positions = Eigen::Map<const Eigen::VectorXd>(atoms.getPositions().data(), atoms.size() * 3);\n      try {\n        bfgs.optimize(positions, microIterUpdate, microIterCheck);\n      }\n      catch (...) {\n        if (cycle > 5) {\n          coordinates = this->extractTsGuess();\n          atoms.setPositions(coordinates);\n          _calculator.modifyPositions(coordinates);\n          return cycle;\n        }\n        throw std::runtime_error(\"NT micro iterations failed.\");\n      }\n      coordinates = Eigen::Map<const Utils::PositionCollection>(positions.data(), nAtoms, 3);\n      atoms.setPositions(coordinates);\n    }\n\n    _calculator.modifyPositions(coordinates);\n\n    // Calculate data\n    Utils::Results results;\n    try {\n      results = _calculator.calculate(\"NT Macro Cycle\"); // might throw exception\n      if (!results.get<Property::SuccessfulCalculation>()) {\n        throw std::runtime_error(\"Calculator signalled unsuccessful calculation.\");\n      }\n    }\n    catch (...) {\n      // try extraction if we already walked a bit, calculation failure might occur because atoms are already quite close\n      if (cycle > 5) {\n        coordinates = this->extractTsGuess();\n        atoms.setPositions(coordinates);\n        _calculator.modifyPositions(coordinates);\n        return cycle;\n      }\n      throw Core::UnsuccessfulCalculationException(\"Calculation in NT optimization failed: \" +\n                                                   boost::current_exception_diagnostic_information());\n    }\n    double value = results.get<Property::Energy>();\n    auto gradients = results.get<Property::Gradients>();\n    this->triggerObservers(cycle, value, Eigen::Map<const Eigen::VectorXd>(coordinates.data(), nAtoms * 3));\n    // Evaluate additional force\n    this->updateGradients(atoms, value, gradients, true);\n    _values.push_back(value);\n    _trajectory.push_back(coordinates);\n    // Check convergence\n    if (this->convergedOptimization(atoms)) {\n      coordinates = this->extractTsGuess();\n      atoms.setPositions(coordinates);\n      _calculator.modifyPositions(coordinates);\n      return cycle;\n    }\n    // Update positions (SD)\n    this->updateCoordinates(coordinates, atoms, gradients);\n    atoms.setPositions(coordinates);\n    _calculator.modifyPositions(coordinates);\n  }\n  return cycle;\n}\n\nvoid NtOptimizer::sanityCheck(const AtomCollection& atoms) const {\n  if (lhsList.empty() || rhsList.empty()) {\n    throw std::logic_error(\"Called NT optimization without atoms to apply a force to.\");\n  }\n  // check for negative indices\n  if (std::any_of(lhsList.begin(), lhsList.end(), [&](int i) { return i < 0; })) {\n    throw std::logic_error(\n        \"At least one of the given indices in the 'nt_lhs_list' is negative, which is not possible.\");\n  }\n  if (std::any_of(rhsList.begin(), rhsList.end(), [&](int i) { return i < 0; })) {\n    throw std::logic_error(\n        \"At least one of the given indices in the 'nt_rhs_list' is negative, which is not possible.\");\n  }\n  // check for too large indices\n  const int nAtoms = atoms.size();\n  for (const auto i : lhsList) {\n    if (i >= nAtoms) {\n      throw std::logic_error(\"Index '\" + std::to_string(i) + \"' in 'nt_lhs_list' too large for \" +\n                             std::to_string(nAtoms) + \" atoms.\");\n    }\n  }\n  for (const auto i : rhsList) {\n    if (i >= nAtoms) {\n      throw std::logic_error(\"Index '\" + std::to_string(i) + \"' in 'nt_rhs_list' too large for \" +\n                             std::to_string(nAtoms) + \" atoms.\");\n    }\n  }\n  // check if there is an identical index on both sides\n  for (const auto lhs : lhsList) {\n    if (std::find(rhsList.begin(), rhsList.end(), lhs) != rhsList.end()) {\n      throw std::logic_error(\"The index \" + std::to_string(lhs) + \" is present in lhs and rhs, which is not valid.\");\n    }\n  }\n  // check if there is an overlap of reaction indices and constrained atoms and too large indices of restrained atoms\n  if (!this->fixedAtoms.empty()) {\n    for (const auto& a : fixedAtoms) {\n      if (a >= nAtoms) {\n        throw std::logic_error(\"Constrained atom index \" + std::to_string(a) + \" is too large for \" +\n                               std::to_string(nAtoms) + \" atoms.\");\n      }\n      std::vector<int> movableReactionIndicesList;\n      if (this->movableSide == \"both\") {\n        movableReactionIndicesList = lhsList;\n        movableReactionIndicesList.insert(movableReactionIndicesList.end(), rhsList.begin(), rhsList.end());\n      }\n      else if (this->movableSide == \"lhs\") {\n        movableReactionIndicesList = lhsList;\n      }\n      else if (this->movableSide == \"rhs\") {\n        movableReactionIndicesList = rhsList;\n      }\n      else {\n        // should be handled by settings\n        throw std::logic_error(\"Unknown input \" + movableSide + \" for \" + NtOptimizer::ntMovableSide);\n      }\n      if (std::find(movableReactionIndicesList.begin(), movableReactionIndicesList.end(), a) !=\n          movableReactionIndicesList.end()) {\n        throw std::logic_error(\"The atom index \" + std::to_string(a) +\n                               \" was specified to be constrained although \"\n                               \"it is within a movable reaction side. You can change '\" +\n                               NtOptimizer::ntMovableSide + \"' if you want to constrain atoms.\");\n      }\n    }\n  }\n}\n\nvoid NtOptimizer::updateGradients(const AtomCollection& atoms, const double& /* energy */,\n                                  GradientCollection& gradients, bool addForce) const {\n  // define reaction coordinate based on LHS and RHS list\n  GradientCollection reactionCoordinate(gradients);\n  reactionCoordinate.setZero();\n  Displacement c2c = this->centerToCenterVector(atoms.getPositions());\n  c2c /= c2c.norm();\n  for (const auto l : lhsList) {\n    reactionCoordinate.row(l) = -c2c;\n  }\n  for (const auto r : rhsList) {\n    reactionCoordinate.row(r) = c2c;\n  }\n  /* Update gradients */\n  // remove gradient along reaction coordinate\n  for (const auto l : lhsList) {\n    if (lhsList.size() > 1) {\n      gradients.row(l) -= (gradients.row(l).cwiseProduct(reactionCoordinate.row(l)).sum()) * reactionCoordinate.row(l);\n    }\n    else {\n      gradients.row(l).setZero();\n    }\n    // replace gradient along reaction coordinate with fixed force only for lhs\n    if (addForce && this->movableSide == \"lhs\") {\n      double factor = (attractive) ? 1.0 : -1.0;\n      gradients.row(l) += factor * totalForceNorm * reactionCoordinate.row(l);\n    }\n  }\n  for (const auto r : rhsList) {\n    if (rhsList.size() > 1) {\n      gradients.row(r) -= (gradients.row(r).cwiseProduct(reactionCoordinate.row(r)).sum()) * reactionCoordinate.row(r);\n    }\n    else {\n      gradients.row(r).setZero();\n    }\n    // replace gradient along reaction coordinate with fixed force only for rhs\n    if (addForce && this->movableSide == \"rhs\") {\n      double factor = (attractive) ? 1.0 : -1.0;\n      gradients.row(r) += factor * totalForceNorm * reactionCoordinate.row(r);\n    }\n  }\n  // replace gradient along reaction coordinate with fixed force for both sides\n  if (addForce && this->movableSide == \"both\") {\n    double factor = (attractive) ? 0.5 : -0.5;\n    gradients += factor * totalForceNorm * reactionCoordinate;\n  }\n  // Apply Cartesian constraints\n  if (!this->fixedAtoms.empty()) {\n    for (const auto& a : fixedAtoms) {\n      gradients.row(a).setZero();\n    }\n  }\n}\n\nDisplacement NtOptimizer::centerToCenterVector(const PositionCollection& positions) const {\n  Position lhsCenter = Position::Zero();\n  Position rhsCenter = Position::Zero();\n  for (const auto l : lhsList) {\n    lhsCenter += positions.row(l);\n  }\n  lhsCenter.array() /= static_cast<double>(lhsList.size());\n  for (const auto r : rhsList) {\n    rhsCenter += positions.row(r);\n  }\n  rhsCenter.array() /= static_cast<double>(rhsList.size());\n  Displacement c2c = rhsCenter - lhsCenter;\n  return c2c;\n}\n\nbool NtOptimizer::convergedOptimization(const AtomCollection& atoms) const {\n  const auto& positions = atoms.getPositions();\n  double c2cNorm = this->centerToCenterVector(positions).norm();\n  if (this->attractive) {\n    if (c2cNorm < this->check.attractiveStop) {\n      return true;\n    }\n    for (const auto& l : this->lhsList) {\n      for (const auto& r : this->rhsList) {\n        Eigen::Vector3d dir = positions.row(l) - positions.row(r);\n        const double dist = dir.norm();\n        const double r12cov =\n            ElementInfo::covalentRadius(atoms.getElement(l)) + ElementInfo::covalentRadius(atoms.getElement(r));\n        if (dist < this->check.attractiveStop * r12cov) {\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n  bool done = true;\n  for (const auto& l : this->lhsList) {\n    for (const auto& r : this->rhsList) {\n      Eigen::Vector3d dir = positions.row(l) - positions.row(r);\n      const double dist = dir.norm();\n      const double r12cov =\n          ElementInfo::covalentRadius(atoms.getElement(l)) + ElementInfo::covalentRadius(atoms.getElement(r));\n      if (dist < this->check.repulsiveStop * r12cov) {\n        done = false;\n        break;\n      }\n    }\n  }\n  if (c2cNorm <= this->check.repulsiveStop) {\n    done = false;\n  }\n  return done;\n}\n\nPositionCollection NtOptimizer::extractTsGuess() const {\n  // Apply a Savitzky-Golay filter (width 5) and take the 1st derivative\n  std::vector<double> filteredValues(_values);\n  std::vector<double> filteredGradients(_values.size());\n  for (int i = 0; i < this->filterPasses; i++) {\n    // prepend and post pend data\n    std::vector<double> tmp;\n    tmp.reserve(filteredValues.size() + 4);\n    tmp.push_back(filteredValues[0]);\n    tmp.push_back(filteredValues[0]);\n    tmp.insert(tmp.begin() + 2, filteredValues.begin(), filteredValues.end());\n    tmp.push_back(filteredValues[filteredValues.size() - 1]);\n    tmp.push_back(filteredValues[filteredValues.size() - 1]);\n    for (unsigned int j = 2; j < filteredValues.size() + 2; j++) {\n      const double a0 = (-3.0 * tmp[j - 2] + 12.0 * tmp[j - 1] + 17.0 * tmp[j] + 12.0 * tmp[j + 1] - 3.0 * tmp[j + 2]) / 35.0;\n      const double a1 = (tmp[j - 2] - 8.0 * tmp[j - 1] + 8.0 * tmp[j + 1] - 1.0 * tmp[j + 2]) / 12.0;\n      filteredValues[j - 2] = a0;\n      filteredGradients[j - 2] = a1;\n    }\n  }\n\n  // Find all maxima of energy curve as indicated by a plus to minus zero pass (read from the left)\n  // Search from the back if the force is attractive\n  std::vector<int> maximaList;\n  if (this->attractive) {\n    for (int i = static_cast<int>(filteredGradients.size()) - 2; i > 0; i--) {\n      if (filteredGradients[i] >= 0.0 && filteredGradients[i + 1] < 0.0) {\n        maximaList.push_back((fabs(filteredGradients[i]) < fabs(filteredGradients[i + 1])) ? i : i + 1);\n      }\n    }\n  }\n  else {\n    const int N = static_cast<int>(_values.size()) - 1;\n    for (int i = 0; i < N; i++) {\n      if (filteredGradients[i + 1] <= 0.0 && filteredGradients[i] > 0.0) {\n        maximaList.push_back((fabs(filteredGradients[i]) < fabs(filteredGradients[i + 1])) ? i : i + 1);\n      }\n    }\n  }\n\n  if (maximaList.empty()) {\n    throw std::runtime_error(\"No transition state guess was found in Newton Trajectory scan.\");\n  }\n  // Extract TS guess from point with highest energy\n  double maxValue = -std::numeric_limits<double>::max();\n  int maxIndex = -1;\n  for (auto& i : maximaList) {\n    if (_values[i] > maxValue) {\n      maxIndex = i;\n      maxValue = _values[i];\n    }\n  }\n\n  return _trajectory[maxIndex];\n}\n\nvoid NtOptimizer::updateCoordinates(PositionCollection& coordinates, const AtomCollection& atoms,\n                                    const GradientCollection& gradients) const {\n  // transform coordinates and gradients if transformation was specified\n  if (this->coordinateSystem == CoordinateSystem::Internal) {\n    try {\n      auto transformation = std::make_shared<InternalCoordinates>(atoms);\n      auto internalCoordinates = transformation->coordinatesToInternal(coordinates);\n      auto internalGradients = transformation->gradientsToInternal(gradients);\n      internalCoordinates -= optimizer.factor * internalGradients;\n      coordinates = transformation->coordinatesToCartesian(internalCoordinates);\n    }\n    catch (const InternalCoordinatesException& e) {\n      // if true internals fail, fall back to Cartesians without rotation and translation\n      auto transformation = std::make_shared<InternalCoordinates>(atoms, true);\n      auto internalCoordinates = transformation->coordinatesToInternal(coordinates);\n      auto internalGradients = transformation->gradientsToInternal(gradients);\n      internalCoordinates -= optimizer.factor * internalGradients;\n      coordinates = transformation->coordinatesToCartesian(internalCoordinates);\n    }\n  }\n  else if (this->coordinateSystem == CoordinateSystem::CartesianWithoutRotTrans) {\n    auto transformation = std::make_shared<InternalCoordinates>(atoms, true);\n    auto internalCoordinates = transformation->coordinatesToInternal(coordinates);\n    auto internalGradients = transformation->gradientsToInternal(gradients);\n    internalCoordinates -= optimizer.factor * internalGradients;\n    coordinates = transformation->coordinatesToCartesian(internalCoordinates);\n  }\n  else if (this->coordinateSystem == CoordinateSystem::Cartesian) {\n    coordinates -= optimizer.factor * gradients;\n  }\n  else {\n    throw std::runtime_error(\"Unknown coordinate system, please check your '\" + std::string(ntCoordinateSystemKey) + \"' input.\");\n  }\n}\n\nvoid NtOptimizer::addSettingsDescriptors(UniversalSettings::DescriptorCollection& /* collection */) const {\n  // Not implemented yet\n  throw std::runtime_error(\"You reached a function in the NTOptimizer that should not be called.\");\n}\n\nvoid NtOptimizer::setSettings(const Settings& settings) {\n  // optimizer.applySettings(settings);\n  if (!settings.valid()) {\n    settings.throwIncorrectSettings();\n  }\n  this->optimizer.factor = settings.getDouble(NtOptimizer::ntSdFactorKey);\n  this->check.maxIter = settings.getInt(NtOptimizer::ntMaxIterKey);\n  this->check.repulsiveStop = settings.getDouble(NtOptimizer::ntRepulsiveStopKey);\n  this->check.attractiveStop = settings.getDouble(NtOptimizer::ntAttractiveStopKey);\n  this->rhsList = settings.getIntList(NtOptimizer::ntRHSListKey);\n  this->lhsList = settings.getIntList(NtOptimizer::ntLHSListKey);\n  this->attractive = settings.getBool(NtOptimizer::ntAttractiveKey);\n  this->totalForceNorm = settings.getDouble(NtOptimizer::ntTotalForceNormKey);\n  this->coordinateSystem =\n      CoordinateSystemInterpreter::getCoordinateSystemFromString(settings.getString(NtOptimizer::ntCoordinateSystemKey));\n  this->useMicroCycles = settings.getBool(NtOptimizer::ntUseMicroCycles);\n  this->fixedNumberOfMicroCycles = settings.getBool(NtOptimizer::ntFixedNumberOfMicroCycles);\n  this->numberOfMicroCycles = settings.getInt(NtOptimizer::ntNumberOfMicroCycles);\n  this->filterPasses = settings.getInt(NtOptimizer::ntFilterPasses);\n  this->fixedAtoms = settings.getIntList(NtOptimizer::ntFixedAtomsKey);\n  this->movableSide = settings.getString(NtOptimizer::ntMovableSide);\n\n  // Check whether constraints and coordinate transformations are both switched on:\n  if (!this->fixedAtoms.empty() && this->coordinateSystem != CoordinateSystem::Cartesian) {\n    throw std::logic_error(\"Cartesian constraints cannot be set when using coordinate transformations! Set \"\n                           \"'nt_coordinate_system' to 'cartesian'.\");\n  }\n}\n\nvoid NtOptimizer::applySettings(const Settings& settings) {\n  this->setSettings(settings);\n}\n\nSettings NtOptimizer::getSettings() const {\n  return NtOptimizerSettings(*this);\n}\n\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "89d5b28303745bf83d434dad764d1afacf6bf082", "size": 18132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/GeometryOptimization/NtOptimizer.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/GeometryOptimization/NtOptimizer.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/GeometryOptimization/NtOptimizer.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": 42.5633802817, "max_line_length": 129, "alphanum_fraction": 0.6712442091, "num_tokens": 4359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.17202376142733292}}
{"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 scenario/scenariosimmarket.cpp\n    \\brief A Market class that can be updated by Scenarios\n    \\ingroup\n*/\n\n#include <orea/engine/observationmode.hpp>\n#include <orea/scenario/scenariosimmarket.hpp>\n#include <orea/scenario/simplescenario.hpp>\n#include <ql/experimental/credit/basecorrelationstructure.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n#include <ql/termstructures/credit/interpolatedsurvivalprobabilitycurve.hpp>\n#include <ql/termstructures/defaulttermstructure.hpp>\n#include <ql/termstructures/volatility/capfloor/capfloortermvolatilitystructure.hpp>\n#include <ql/termstructures/volatility/capfloor/capfloortermvolsurface.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvariancecurve.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp>\n#include <ql/termstructures/volatility/optionlet/strippedoptionlet.hpp>\n#include <ql/termstructures/volatility/optionlet/strippedoptionletadapter.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionconstantvol.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionvolcube.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionvolmatrix.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionvolstructure.hpp>\n#include <ql/termstructures/yield/discountcurve.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <qle/indexes/inflationindexobserver.hpp>\n#include <qle/indexes/inflationindexwrapper.hpp>\n#include <qle/termstructures/dynamicblackvoltermstructure.hpp>\n#include <qle/termstructures/dynamicswaptionvolmatrix.hpp>\n#include <qle/termstructures/flatcorrelation.hpp>\n#include <qle/termstructures/interpolatedcorrelationcurve.hpp>\n#include <qle/termstructures/pricecurve.hpp>\n#include <qle/termstructures/strippedoptionletadapter2.hpp>\n#include <qle/termstructures/survivalprobabilitycurve.hpp>\n#include <qle/termstructures/swaptionvolatilityconverter.hpp>\n#include <qle/termstructures/swaptionvolconstantspread.hpp>\n#include <qle/termstructures/swaptionvolcube2.hpp>\n#include <qle/termstructures/swaptionvolcubewithatm.hpp>\n#include <qle/termstructures/yoyinflationcurveobservermoving.hpp>\n#include <qle/termstructures/zeroinflationcurveobservermoving.hpp>\n\n#include <boost/timer.hpp>\n\n#include <ored/utilities/indexparser.hpp>\n#include <ored/utilities/log.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace ore::data;\nusing namespace std;\n\ntypedef QuantLib::BaseCorrelationTermStructure<QuantLib::BilinearInterpolation> BilinearBaseCorrelationTermStructure;\n\nnamespace ore {\nnamespace analytics {\n\nRiskFactorKey::KeyType yieldCurveRiskFactor(const ore::data::YieldCurveType y) {\n\n    if (y == ore::data::YieldCurveType::Discount) {\n        return RiskFactorKey::KeyType::DiscountCurve;\n    } else if (y == ore::data::YieldCurveType::Yield) {\n        return RiskFactorKey::KeyType::YieldCurve;\n    } else if (y == ore::data::YieldCurveType::EquityDividend) {\n        return RiskFactorKey::KeyType::DividendYield;\n    } else if (y == ore::data::YieldCurveType::EquityForecast) {\n        return RiskFactorKey::KeyType::EquityForecastCurve;\n    } else {\n        QL_FAIL(\"yieldCurveType not supported\");\n    }\n}\n\nnamespace {\nReactionToTimeDecay parseDecayMode(const string& s) {\n    static map<string, ReactionToTimeDecay> m = {{\"ForwardVariance\", ForwardForwardVariance},\n                                                 {\"ConstantVariance\", ConstantVariance}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Decay mode \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\n} // namespace\n\nvoid ScenarioSimMarket::addYieldCurve(const boost::shared_ptr<Market>& initMarket, const std::string& configuration,\n                                      const ore::data::YieldCurveType y, const string& key,\n                                      const vector<Period>& tenors, const string& dayCounter) {\n    Handle<YieldTermStructure> wrapper = initMarket->yieldCurve(y, key, configuration);\n    QL_REQUIRE(!wrapper.empty(), \"yield curve not provided for \" << key);\n    QL_REQUIRE(tenors.front() > 0 * Days, \"yield curve tenors must not include t=0\");\n    // include today\n\n    // constructing yield curves\n    DayCounter dc = ore::data::parseDayCounter(dayCounter); // used to convert YieldCurve Periods to Times\n    vector<Time> yieldCurveTimes(1, 0.0);                   // include today\n    vector<Date> yieldCurveDates(1, asof_);\n    for (auto& tenor : tenors) {\n        yieldCurveTimes.push_back(dc.yearFraction(asof_, asof_ + tenor));\n        yieldCurveDates.push_back(asof_ + tenor);\n    }\n\n    vector<Handle<Quote>> quotes;\n    boost::shared_ptr<SimpleQuote> q(new SimpleQuote(1.0));\n    quotes.push_back(Handle<Quote>(q));\n    vector<Real> discounts(yieldCurveTimes.size());\n    RiskFactorKey::KeyType rf = yieldCurveRiskFactor(y);\n    std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n    for (Size i = 0; i < yieldCurveTimes.size() - 1; i++) {\n        boost::shared_ptr<SimpleQuote> q(new SimpleQuote(wrapper->discount(yieldCurveDates[i + 1])));\n        Handle<Quote> qh(q);\n        quotes.push_back(qh);\n\n        // Check if the risk factor is simulated before adding it\n        if (nonSimulatedFactors_.find(rf) == nonSimulatedFactors_.end()) {\n            simDataTmp.emplace(std::piecewise_construct, std::forward_as_tuple(rf, key, i), std::forward_as_tuple(q));\n            DLOG(\"ScenarioSimMarket yield curve \" << key << \" discount[\" << i << \"]=\" << q->value());\n        }\n    }\n\n    boost::shared_ptr<YieldTermStructure> yieldCurve;\n\n    if (ObservationMode::instance().mode() == ObservationMode::Mode::Unregister) {\n        yieldCurve = boost::shared_ptr<YieldTermStructure>(\n            new QuantExt::InterpolatedDiscountCurve(yieldCurveTimes, quotes, 0, TARGET(), dc));\n    } else {\n        yieldCurve = boost::shared_ptr<YieldTermStructure>(\n            new QuantExt::InterpolatedDiscountCurve2(yieldCurveTimes, quotes, dc));\n    }\n\n    Handle<YieldTermStructure> ych(yieldCurve);\n    if (wrapper->allowsExtrapolation())\n        ych->enableExtrapolation();\n    yieldCurves_.insert(pair<tuple<string, ore::data::YieldCurveType, string>, Handle<YieldTermStructure>>(\n        make_tuple(Market::defaultConfiguration, y, key), ych));\n    simData_.insert(simDataTmp.begin(), simDataTmp.end());\n}\n\nScenarioSimMarket::ScenarioSimMarket(const boost::shared_ptr<Market>& initMarket,\n                                     const boost::shared_ptr<ScenarioSimMarketParameters>& parameters,\n                                     const Conventions& conventions, const std::string& configuration,\n                                     const bool continueOnError)\n    : SimMarket(conventions), parameters_(parameters), filter_(boost::make_shared<ScenarioFilter>()) {\n\n    LOG(\"building ScenarioSimMarket...\");\n    asof_ = initMarket->asofDate();\n    LOG(\"AsOf \" << QuantLib::io::iso_date(asof_));\n\n    // Set non simulated risk factor key types\n    if (!parameters->simulateSwapVols())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::SwaptionVolatility);\n    if (!parameters->simulateCapFloorVols())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::OptionletVolatility);\n    if (!parameters->simulateSurvivalProbabilities())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::SurvivalProbability);\n    if (!parameters->simulateCdsVols())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::CDSVolatility);\n    if (!parameters->simulateFXVols())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::FXVolatility);\n    if (!parameters->simulateEquityVols())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::EquityVolatility);\n    if (!parameters->simulateBaseCorrelations())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::BaseCorrelation);\n    if (!parameters->simulateEquityForecastCurve())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::EquityForecastCurve);\n    if (!parameters->simulateDividendYield())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::DividendYield);\n    if (!parameters->commodityCurveSimulate())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::CommodityCurve);\n    if (!parameters->commodityVolSimulate())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::CommodityVolatility);\n    if (!parameters->securitySpreadsSimulate())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::SecuritySpread);\n    if (!parameters->simulateFxSpots())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::FXSpot);\n    if (!parameters->simulateCorrelations())\n        nonSimulatedFactors_.insert(RiskFactorKey::KeyType::Correlation);\n\n    // Build fixing manager\n    fixingManager_ = boost::make_shared<FixingManager>(asof_);\n\n    // constructing fxSpots_\n    LOG(\"building FX triangulation..\");\n    for (const auto& ccyPair : parameters->fxCcyPairs()) {\n        try {\n            LOG(\"adding \" << ccyPair << \" FX rates\");\n            boost::shared_ptr<SimpleQuote> q(new SimpleQuote(initMarket->fxSpot(ccyPair, configuration)->value()));\n            Handle<Quote> qh(q);\n            fxSpots_[Market::defaultConfiguration].addQuote(ccyPair, qh);\n            // Check if the risk factor is simulated before adding it\n            RiskFactorKey::KeyType rf = RiskFactorKey::KeyType::FXSpot;\n            if (nonSimulatedFactors_.find(rf) == nonSimulatedFactors_.end()) {\n                simData_.emplace(std::piecewise_construct, std::forward_as_tuple(rf, ccyPair),\n                                 std::forward_as_tuple(q));\n            }\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n\n    LOG(\"FX triangulation done\");\n\n    // constructing discount yield curves\n    LOG(\"building discount yield curves...\");\n    for (const auto& ccy : parameters->ccys()) {\n        try {\n            LOG(\"building \" << ccy << \" discount yield curve..\");\n            vector<Period> tenors = parameters->yieldCurveTenors(ccy);\n            addYieldCurve(initMarket, configuration, ore::data::YieldCurveType::Discount, ccy, tenors,\n                          parameters->yieldCurveDayCounter(ccy));\n            LOG(\"building \" << ccy << \" discount yield curve done\");\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"discount yield curves done\");\n\n    LOG(\"building benchmark yield curves...\");\n    for (const auto& name : parameters->yieldCurveNames()) {\n        try {\n            LOG(\"building benchmark yield curve name \" << name);\n            vector<Period> tenors = parameters->yieldCurveTenors(name);\n            addYieldCurve(initMarket, configuration, ore::data::YieldCurveType::Yield, name, tenors,\n                          parameters->yieldCurveDayCounter(name));\n            LOG(\"building benchmark yield curve \" << name << \" done\");\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"benchmark yield curves done\");\n\n    // building equity yield curves\n    LOG(\"building equity curves...\");\n    for (const auto& eqName : parameters->equityNames()) {\n        try {\n            // building equity spots\n            LOG(\"adding \" << eqName << \" equity spot...\");\n            Real spotVal = initMarket->equitySpot(eqName, configuration)->value();\n            boost::shared_ptr<SimpleQuote> q(new SimpleQuote(spotVal));\n            Handle<Quote> qh(q);\n            equitySpots_.insert(\n                pair<pair<string, string>, Handle<Quote>>(make_pair(Market::defaultConfiguration, eqName), qh));\n            simData_.emplace(std::piecewise_construct,\n                             std::forward_as_tuple(RiskFactorKey::KeyType::EquitySpot, eqName),\n                             std::forward_as_tuple(q));\n            LOG(\"adding \" << eqName << \" equity spot done\");\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n        try {\n            LOG(\"building \" << eqName << \" equity dividend yield curve..\");\n            vector<Period> divTenors = parameters->equityDividendTenors(eqName);\n            addYieldCurve(initMarket, configuration, ore::data::YieldCurveType::EquityDividend, eqName, divTenors,\n                          parameters->yieldCurveDayCounter(eqName));\n            LOG(\"building \" << eqName << \" equity dividend yield curve done\");\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n        try {\n            LOG(\"building \" << eqName << \" equity forecast curve..\");\n            vector<Period> foreTenors = parameters->equityForecastTenors(eqName);\n            addYieldCurve(initMarket, configuration, ore::data::YieldCurveType::EquityForecast, eqName, foreTenors,\n                          parameters->yieldCurveDayCounter(eqName));\n            LOG(\"building \" << eqName << \" forecast curve done\");\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n        try {\n            LOG(\"building \" << eqName << \" equity index curve..\");\n            Handle<EquityIndex> curve = initMarket->equityCurve(eqName, configuration);\n            boost::shared_ptr<EquityIndex> ei(curve->clone(\n                equitySpot(eqName, configuration), yieldCurve(YieldCurveType::EquityForecast, eqName, configuration),\n                yieldCurve(YieldCurveType::EquityDividend, eqName, configuration)));\n            Handle<EquityIndex> eh(ei);\n            equityCurves_.insert(\n                pair<pair<string, string>, Handle<EquityIndex>>(make_pair(Market::defaultConfiguration, eqName), eh));\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"equity yield curves done\");\n\n    // building security spreads\n    LOG(\"building security spreads...\");\n    for (const auto& name : parameters->securities()) {\n        DLOG(\"Adding security spread \" << name << \" from configuration \" << configuration);\n        try {\n            boost::shared_ptr<SimpleQuote> spreadQuote(\n                new SimpleQuote(initMarket->securitySpread(name, configuration)->value()));\n            if (parameters->securitySpreadsSimulate()) {\n                simData_.emplace(std::piecewise_construct,\n                                 std::forward_as_tuple(RiskFactorKey::KeyType::SecuritySpread, name),\n                                 std::forward_as_tuple(spreadQuote));\n            }\n            securitySpreads_.insert(pair<pair<string, string>, Handle<Quote>>(\n                make_pair(Market::defaultConfiguration, name), Handle<Quote>(spreadQuote)));\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"security spreads done...\");\n\n    // building security recovery rates\n    LOG(\"building security recovery rates...\");\n    for (const auto& name : parameters->securities()) {\n        DLOG(\"Adding security recovery rate \" << name << \" from configuration \" << configuration);\n        try {\n            boost::shared_ptr<SimpleQuote> recoveryQuote(\n                new SimpleQuote(initMarket->recoveryRate(name, configuration)->value()));\n            // TODO this comes from the default curves section in the parameters,\n            // do we want to specify the simulation of security recovery rates separately?\n            if (parameters->simulateRecoveryRates()) {\n                simData_.emplace(std::piecewise_construct,\n                                 std::forward_as_tuple(RiskFactorKey::KeyType::RecoveryRate, name),\n                                 std::forward_as_tuple(recoveryQuote));\n            }\n            recoveryRates_.insert(pair<pair<string, string>, Handle<Quote>>(\n                make_pair(Market::defaultConfiguration, name), Handle<Quote>(recoveryQuote)));\n        } catch (const std::exception& e) {\n            // security recovery rates are optional, therefore we never throw\n            ALOG(\"skipping this object: \" << e.what());\n        }\n    }\n    LOG(\"security recovery rates done...\");\n\n    // building security cpr\n    LOG(\"building security cpr...\");\n    for (const auto& name : parameters->securities()) {\n        DLOG(\"Adding security cpr \" << name << \" from configuration \" << configuration);\n        // security cpr are optional, so we need a try-catch block\n        try {\n            boost::shared_ptr<SimpleQuote> cprQuote(new SimpleQuote(initMarket->cpr(name, configuration)->value()));\n            if (parameters->cprSimulate()) {\n                simData_.emplace(std::piecewise_construct, std::forward_as_tuple(RiskFactorKey::KeyType::CPR, name),\n                                 std::forward_as_tuple(cprQuote));\n            }\n            cprs_.insert(pair<pair<string, string>, Handle<Quote>>(make_pair(Market::defaultConfiguration, name),\n                                                                   Handle<Quote>(cprQuote)));\n        } catch (...) {\n        }\n    }\n    LOG(\"security cprs done...\");\n\n    // constructing index curves\n    LOG(\"building index curves...\");\n    for (const auto& ind : parameters->indices()) {\n        try {\n            LOG(\"building \" << ind << \" index curve\");\n            std::vector<string> indexTokens;\n            split(indexTokens, ind, boost::is_any_of(\"-\"));\n            Handle<IborIndex> index;\n            if (indexTokens[1] == \"GENERIC\") {\n                // If we have a generic curve build the index using the index currency's discount curve\n                index =\n                    Handle<IborIndex>(parseIborIndex(ind, initMarket->discountCurve(indexTokens[0], configuration)));\n            } else {\n                index = initMarket->iborIndex(ind, configuration);\n            }\n            QL_REQUIRE(!index.empty(), \"index object for \" << ind << \" not provided\");\n            Handle<YieldTermStructure> wrapperIndex = index->forwardingTermStructure();\n            QL_REQUIRE(!wrapperIndex.empty(), \"no termstructure for index \" << ind);\n            vector<string> keys(parameters->yieldCurveTenors(ind).size());\n\n            DayCounter dc = ore::data::parseDayCounter(\n                parameters->yieldCurveDayCounter(ind)); // used to convert YieldCurve Periods to Times\n            vector<Time> yieldCurveTimes(1, 0.0);       // include today\n            vector<Date> yieldCurveDates(1, asof_);\n            QL_REQUIRE(parameters->yieldCurveTenors(ind).front() > 0 * Days, \"yield curve tenors must not include t=0\");\n            for (auto& tenor : parameters->yieldCurveTenors(ind)) {\n                yieldCurveTimes.push_back(dc.yearFraction(asof_, asof_ + tenor));\n                yieldCurveDates.push_back(asof_ + tenor);\n            }\n\n            // include today\n            vector<Handle<Quote>> quotes;\n            boost::shared_ptr<SimpleQuote> q(new SimpleQuote(1.0));\n            quotes.push_back(Handle<Quote>(q));\n\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            for (Size i = 0; i < yieldCurveTimes.size() - 1; i++) {\n                boost::shared_ptr<SimpleQuote> q(new SimpleQuote(wrapperIndex->discount(yieldCurveDates[i + 1])));\n                Handle<Quote> qh(q);\n                quotes.push_back(qh);\n                simDataTmp.emplace(std::piecewise_construct,\n                                   std::forward_as_tuple(RiskFactorKey::KeyType::IndexCurve, ind, i),\n                                   std::forward_as_tuple(q));\n\n                DLOG(\"ScenarioSimMarket index curve \" << ind << \" discount[\" << i << \"]=\" << q->value());\n            }\n            // FIXME interpolation fixed to linear, added to xml??\n            boost::shared_ptr<YieldTermStructure> indexCurve;\n            if (ObservationMode::instance().mode() == ObservationMode::Mode::Unregister) {\n                indexCurve = boost::shared_ptr<YieldTermStructure>(\n                    new QuantExt::InterpolatedDiscountCurve(yieldCurveTimes, quotes, 0, index->fixingCalendar(), dc));\n            } else {\n                indexCurve = boost::shared_ptr<YieldTermStructure>(\n                    new QuantExt::InterpolatedDiscountCurve2(yieldCurveTimes, quotes, dc));\n            }\n\n            // wrapped curve, is slower than a native curve\n            // boost::shared_ptr<YieldTermStructure> correctedIndexCurve(\n            //     new StaticallyCorrectedYieldTermStructure(\n            //         discountCurves_[ccy], initMarket->discountCurve(ccy, configuration),\n            //         wrapperIndex));\n\n            Handle<YieldTermStructure> ich(indexCurve);\n            // Handle<YieldTermStructure> ich(correctedIndexCurve);\n            if (wrapperIndex->allowsExtrapolation())\n                ich->enableExtrapolation();\n\n            boost::shared_ptr<IborIndex> i(index->clone(ich));\n            Handle<IborIndex> ih(i);\n            iborIndices_.insert(\n                pair<pair<string, string>, Handle<IborIndex>>(make_pair(Market::defaultConfiguration, ind), ih));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n            LOG(\"building \" << ind << \" index curve done\");\n        } catch (const std::exception& e) {\n            ALOG(\"skipping this object: \" << e.what());\n        }\n    }\n    LOG(\"index curves done\");\n\n    // swap indices\n    LOG(\"building swap indices...\");\n    for (const auto& it : parameters->swapIndices()) {\n        try {\n            const string& indexName = it.first;\n            const string& discounting = it.second;\n            LOG(\"Adding swap index \" << indexName << \" with discounting index \" << discounting);\n\n            addSwapIndex(indexName, discounting, Market::defaultConfiguration);\n            LOG(\"Adding swap index \" << indexName << \" done.\");\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n\n    // constructing swaption volatility curves\n    LOG(\"building swaption volatility curves...\");\n    for (const auto& ccy : parameters->swapVolCcys()) {\n        try {\n            LOG(\"building \" << ccy << \" swaption volatility curve...\");\n            RelinkableHandle<SwaptionVolatilityStructure> wrapper(*initMarket->swaptionVol(ccy, configuration));\n\n            LOG(\"Initial market \" << ccy << \" swaption volatility type = \" << wrapper->volatilityType());\n\n            string shortSwapIndexBase = initMarket->shortSwapIndexBase(ccy, configuration);\n            string swapIndexBase = initMarket->swapIndexBase(ccy, configuration);\n\n            bool isCube = parameters->swapVolIsCube();\n\n            // If swaption volatility type is not Normal, convert to Normal for the simulation\n            if (wrapper->volatilityType() != Normal) {\n                // FIXME we can not convert constant swaption vol structures yet\n                if (boost::dynamic_pointer_cast<ConstantSwaptionVolatility>(*wrapper) != nullptr) {\n                    ALOG(\"Constant swaption volatility found in configuration \"\n                         << configuration << \" for currency \" << ccy << \" will not be converted to normal\");\n                } else {\n                    // Get swap index associated with this volatility structure\n                    string swapIndexName = initMarket->swapIndexBase(ccy, configuration);\n                    string shortSwapIndexName = initMarket->shortSwapIndexBase(ccy, configuration);\n                    Handle<SwapIndex> swapIndex = initMarket->swapIndex(swapIndexName, configuration);\n                    Handle<SwapIndex> shortSwapIndex = initMarket->swapIndex(shortSwapIndexName, configuration);\n\n                    // Set up swaption volatility converter\n                    SwaptionVolatilityConverter converter(asof_, *wrapper, *swapIndex, *shortSwapIndex, Normal);\n                    wrapper.linkTo(converter.convert());\n\n                    LOG(\"Converting swaption volatilities in configuration \"\n                        << configuration << \" with currency \" << ccy << \" to normal swaption volatilities\");\n                }\n            }\n\n            Handle<SwaptionVolatilityStructure> svp;\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            if (parameters->simulateSwapVols()) {\n                LOG(\"Simulating (\" << wrapper->volatilityType() << \") Swaption vols for ccy \" << ccy);\n                vector<Period> optionTenors = parameters->swapVolExpiries();\n                vector<Period> swapTenors = parameters->swapVolTerms();\n                vector<Real> strikeSpreads = parameters->swapVolStrikeSpreads();\n                bool atmOnly = parameters->simulateSwapVolATMOnly();\n                DLOG(\"Swaption atmOnly : \" << (atmOnly ? \"True\" : \"False\"));\n                DLOG(\"Swaption isCube : \" << (isCube ? \"True\" : \"False\"));\n                if (atmOnly) {\n                    QL_REQUIRE(strikeSpreads.size() == 1 && close_enough(strikeSpreads[0], 0),\n                               \"for atmOnly strikeSpreads must be {0.0}\");\n                } else {\n                    QL_REQUIRE(isCube, \"Only atmOnly simulation supported for swaption vol surfaces\");\n                }\n                boost::shared_ptr<QuantLib::SwaptionVolatilityCube> cube;\n                if (isCube) {\n                    boost::shared_ptr<SwaptionVolCubeWithATM> tmp =\n                        boost::dynamic_pointer_cast<SwaptionVolCubeWithATM>(*wrapper);\n                    QL_REQUIRE(tmp, \"swaption cube missing\")\n                    cube = tmp->cube();\n                }\n                vector<vector<Handle<Quote>>> quotes, atmQuotes;\n                quotes.resize(optionTenors.size() * swapTenors.size(),\n                              vector<Handle<Quote>>(strikeSpreads.size(), Handle<Quote>()));\n                atmQuotes.resize(optionTenors.size(), std::vector<Handle<Quote>>(swapTenors.size(), Handle<Quote>()));\n                vector<vector<Real>> shift(optionTenors.size(), vector<Real>(swapTenors.size(), 0.0));\n                Size atmSlice = std::find_if(strikeSpreads.begin(), strikeSpreads.end(),\n                                             [](const Real s) { return close_enough(s, 0.0); }) -\n                                strikeSpreads.begin();\n                QL_REQUIRE(atmSlice < strikeSpreads.size(),\n                           \"could not find atm slice (strikeSpreads do not contain 0.0)\");\n                for (Size k = 0; k < strikeSpreads.size(); ++k) {\n                    for (Size i = 0; i < optionTenors.size(); ++i) {\n                        for (Size j = 0; j < swapTenors.size(); ++j) {\n                            Real strike = Null<Real>();\n                            if (!atmOnly && cube)\n                                strike = cube->atmStrike(optionTenors[i], swapTenors[j]) + strikeSpreads[k];\n                            Real vol = wrapper->volatility(optionTenors[i], swapTenors[j], strike, true);\n                            boost::shared_ptr<SimpleQuote> q(new SimpleQuote(vol));\n\n                            Size index = i * swapTenors.size() * strikeSpreads.size() + j * strikeSpreads.size() + k;\n\n                            simDataTmp.emplace(\n                                std::piecewise_construct,\n                                std::forward_as_tuple(RiskFactorKey::KeyType::SwaptionVolatility, ccy, index),\n                                std::forward_as_tuple(q));\n                            auto tmp = Handle<Quote>(q);\n                            quotes[i * swapTenors.size() + j][k] = tmp;\n                            if (k == atmSlice) {\n                                atmQuotes[i][j] = tmp;\n                                shift[i][j] = wrapper->volatilityType() == ShiftedLognormal\n                                                  ? wrapper->shift(optionTenors[i], swapTenors[j])\n                                                  : 0.0;\n                            }\n                        }\n                    }\n                }\n                bool flatExtrapolation = true; // FIXME: get this from curve configuration\n                VolatilityType volType = wrapper->volatilityType();\n                DayCounter dc = ore::data::parseDayCounter(parameters->swapVolDayCounter(ccy));\n                Handle<SwaptionVolatilityStructure> atm(boost::make_shared<SwaptionVolatilityMatrix>(\n                    wrapper->calendar(), wrapper->businessDayConvention(), optionTenors, swapTenors, atmQuotes, dc,\n                    flatExtrapolation, volType, shift));\n                if (atmOnly) {\n                    // floating reference date matrix in sim market\n                    // if we have a cube, we keep the vol spreads constant under scenarios\n                    // notice that cube is from todaysmarket, so it has a fixed reference date, which means that\n                    // we keep the smiles constant in terms of vol spreads when moving forward in time;\n                    // notice also that the volatility will be \"sticky strike\", i.e. it will not react to\n                    // changes in the ATM level\n                    if (isCube) {\n                        svp = Handle<SwaptionVolatilityStructure>(\n                            boost::make_shared<SwaptionVolatilityConstantSpread>(atm, wrapper));\n                    } else {\n                        svp = atm;\n                    }\n                } else {\n                    QL_REQUIRE(isCube, \"Only atmOnly simulation supported for swaption vol surfaces\");\n                    boost::shared_ptr<SwaptionVolatilityCube> tmp(new QuantExt::SwaptionVolCube2(\n                        atm, optionTenors, swapTenors, strikeSpreads, quotes,\n                        *initMarket->swapIndex(swapIndexBase, configuration),\n                        *initMarket->swapIndex(shortSwapIndexBase, configuration), false, flatExtrapolation, false));\n                    svp = Handle<SwaptionVolatilityStructure>(boost::make_shared<SwaptionVolCubeWithATM>(tmp));\n                }\n            } else {\n                string decayModeString = parameters->swapVolDecayMode();\n                ReactionToTimeDecay decayMode = parseDecayMode(decayModeString);\n                LOG(\"Dynamic (\" << wrapper->volatilityType() << \") Swaption vols (\" << decayModeString << \") for ccy \"\n                                << ccy);\n                if (isCube)\n                    WLOG(\"Only ATM slice is considered from init market's cube\");\n                boost::shared_ptr<QuantLib::SwaptionVolatilityStructure> svolp =\n                    boost::make_shared<QuantExt::DynamicSwaptionVolatilityMatrix>(*wrapper, 0, NullCalendar(),\n                                                                                  decayMode);\n                svp = Handle<SwaptionVolatilityStructure>(svolp);\n            }\n\n            svp->enableExtrapolation(); // FIXME\n            swaptionCurves_.insert(pair<pair<string, string>, Handle<SwaptionVolatilityStructure>>(\n                make_pair(Market::defaultConfiguration, ccy), svp));\n\n            LOG(\"Simulaton market \" << ccy << \" swaption volatility type = \" << svp->volatilityType());\n\n            swaptionIndexBases_.insert(pair<pair<string, string>, pair<string, string>>(\n                make_pair(Market::defaultConfiguration, ccy), make_pair(shortSwapIndexBase, swapIndexBase)));\n            swaptionIndexBases_.insert(pair<pair<string, string>, pair<string, string>>(\n                make_pair(Market::defaultConfiguration, ccy), make_pair(swapIndexBase, swapIndexBase)));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n\n    LOG(\"swaption volatility curves done\");\n\n    // Constructing caplet/floorlet volatility surfaces\n    LOG(\"building cap/floor volatility curves...\");\n    for (const auto& ccy : parameters->capFloorVolCcys()) {\n        try {\n            LOG(\"building \" << ccy << \" cap/floor volatility curve...\");\n            Handle<OptionletVolatilityStructure> wrapper = initMarket->capFloorVol(ccy, configuration);\n\n            LOG(\"Initial market cap/floor volatility type = \" << wrapper->volatilityType());\n\n            Handle<OptionletVolatilityStructure> hCapletVol;\n\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            if (parameters->simulateCapFloorVols()) {\n                LOG(\"Simulating Cap/Floor Optionlet vols for ccy \" << ccy);\n                vector<Period> optionTenors = parameters->capFloorVolExpiries(ccy);\n                vector<Date> optionDates(optionTenors.size());\n                vector<Real> strikes = parameters->capFloorVolStrikes();\n                vector<vector<Handle<Quote>>> quotes(optionTenors.size(),\n                                                     vector<Handle<Quote>>(strikes.size(), Handle<Quote>()));\n                for (Size i = 0; i < optionTenors.size(); ++i) {\n                    optionDates[i] = wrapper->optionDateFromTenor(optionTenors[i]);\n                    for (Size j = 0; j < strikes.size(); ++j) {\n                        Real vol = wrapper->volatility(optionTenors[i], strikes[j], wrapper->allowsExtrapolation());\n                        boost::shared_ptr<SimpleQuote> q(new SimpleQuote(vol));\n                        Size index = i * strikes.size() + j;\n                        simDataTmp.emplace(\n                            std::piecewise_construct,\n                            std::forward_as_tuple(RiskFactorKey::KeyType::OptionletVolatility, ccy, index),\n                            std::forward_as_tuple(q));\n                        quotes[i][j] = Handle<Quote>(q);\n                    }\n                }\n                DayCounter dc = ore::data::parseDayCounter(parameters->capFloorVolDayCounter(ccy));\n                // FIXME: Works as of today only, i.e. for sensitivity/scenario analysis.\n                // TODO: Build floating reference date StrippedOptionlet class for MC path generators\n                boost::shared_ptr<StrippedOptionlet> optionlet = boost::make_shared<StrippedOptionlet>(\n                    0, // FIXME: settlement days\n                    wrapper->calendar(), wrapper->businessDayConvention(),\n                    boost::shared_ptr<IborIndex>(), // FIXME: required for ATM vol calculation\n                    optionDates, strikes, quotes, dc, wrapper->volatilityType(), wrapper->displacement());\n                boost::shared_ptr<StrippedOptionletAdapter2> adapter =\n                    boost::make_shared<StrippedOptionletAdapter2>(optionlet, true); // FIXME always flat extrapolation\n                hCapletVol = Handle<OptionletVolatilityStructure>(adapter);\n            } else {\n                string decayModeString = parameters->capFloorVolDecayMode();\n                ReactionToTimeDecay decayMode = parseDecayMode(decayModeString);\n                boost::shared_ptr<OptionletVolatilityStructure> capletVol =\n                    boost::make_shared<DynamicOptionletVolatilityStructure>(*wrapper, 0, NullCalendar(), decayMode);\n                hCapletVol = Handle<OptionletVolatilityStructure>(capletVol);\n            }\n\n            hCapletVol->enableExtrapolation(); // FIXME\n            capFloorCurves_.emplace(std::piecewise_construct, std::forward_as_tuple(Market::defaultConfiguration, ccy),\n                                    std::forward_as_tuple(hCapletVol));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n\n            LOG(\"Simulaton market cap/floor volatility type = \" << hCapletVol->volatilityType());\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n\n    LOG(\"cap/floor volatility curves done\");\n\n    // building default curves\n    LOG(\"building default curves...\");\n    for (const auto& name : parameters->defaultNames()) {\n        try {\n            LOG(\"building \" << name << \" default curve..\");\n            Handle<DefaultProbabilityTermStructure> wrapper = initMarket->defaultCurve(name, configuration);\n            vector<Handle<Quote>> quotes;\n\n            QL_REQUIRE(parameters->defaultTenors(name).front() > 0 * Days, \"default curve tenors must not include t=0\");\n\n            vector<Date> dates(1, asof_);\n\n            for (Size i = 0; i < parameters->defaultTenors(name).size(); i++) {\n                dates.push_back(asof_ + parameters->defaultTenors(name)[i]);\n            }\n\n            boost::shared_ptr<SimpleQuote> q(new SimpleQuote(1.0));\n            quotes.push_back(Handle<Quote>(q));\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            for (Size i = 0; i < dates.size() - 1; i++) {\n                Probability prob = wrapper->survivalProbability(dates[i + 1], true);\n                boost::shared_ptr<SimpleQuote> q(new SimpleQuote(prob));\n                if (parameters->simulateSurvivalProbabilities()) {\n                    simDataTmp.emplace(std::piecewise_construct,\n                                       std::forward_as_tuple(RiskFactorKey::KeyType::SurvivalProbability, name, i),\n                                       std::forward_as_tuple(q));\n                    DLOG(\"ScenarioSimMarket default curve \" << name << \" survival[\" << i << \"]=\" << prob);\n                }\n                Handle<Quote> qh(q);\n                quotes.push_back(qh);\n            }\n            DayCounter dc = ore::data::parseDayCounter(parameters->defaultCurveDayCounter(name));\n            Calendar cal = ore::data::parseCalendar(parameters->defaultCurveCalendar(name));\n            // FIXME riskmarket uses SurvivalProbabilityCurve but this isn't added to ore\n            boost::shared_ptr<DefaultProbabilityTermStructure> defaultCurve(\n                new QuantExt::SurvivalProbabilityCurve<Linear>(dates, quotes, dc, cal));\n            Handle<DefaultProbabilityTermStructure> dch(defaultCurve);\n\n            dch->enableExtrapolation();\n\n            // add recovery rate\n            boost::shared_ptr<SimpleQuote> rrQuote(\n                new SimpleQuote(initMarket->recoveryRate(name, configuration)->value()));\n            if (parameters->simulateRecoveryRates()) {\n                simDataTmp.emplace(std::piecewise_construct,\n                                   std::forward_as_tuple(RiskFactorKey::KeyType::RecoveryRate, name),\n                                   std::forward_as_tuple(rrQuote));\n            }\n            defaultCurves_.insert(pair<pair<string, string>, Handle<DefaultProbabilityTermStructure>>(\n                make_pair(Market::defaultConfiguration, name), dch));\n            recoveryRates_.insert(pair<pair<string, string>, Handle<Quote>>(\n                make_pair(Market::defaultConfiguration, name), Handle<Quote>(rrQuote)));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"default curves done\");\n\n    // building cds volatilities\n    LOG(\"building cds volatilities...\");\n    for (const auto& name : parameters->cdsVolNames()) {\n        try {\n            LOG(\"building \" << name << \"  cds vols..\");\n            Handle<BlackVolTermStructure> wrapper = initMarket->cdsVol(name, configuration);\n            Handle<BlackVolTermStructure> cvh;\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            if (parameters->simulateCdsVols()) {\n                LOG(\"Simulating CDS Vols for \" << name);\n                vector<Handle<Quote>> quotes;\n                vector<Time> times;\n                for (Size i = 0; i < parameters->cdsVolExpiries().size(); i++) {\n                    Date date = asof_ + parameters->cdsVolExpiries()[i];\n                    Volatility vol = wrapper->blackVol(date, Null<Real>(), true);\n                    times.push_back(wrapper->timeFromReference(date));\n                    boost::shared_ptr<SimpleQuote> q(new SimpleQuote(vol));\n                    if (parameters->simulateCdsVols()) {\n                        simDataTmp.emplace(std::piecewise_construct,\n                                           std::forward_as_tuple(RiskFactorKey::KeyType::CDSVolatility, name, i),\n                                           std::forward_as_tuple(q));\n                    }\n                    quotes.emplace_back(q);\n                }\n\n                DayCounter dc = ore::data::parseDayCounter(parameters->cdsVolDayCounter(name));\n                boost::shared_ptr<BlackVolTermStructure> cdsVolCurve(\n                    new BlackVarianceCurve3(0, NullCalendar(), wrapper->businessDayConvention(), dc, times, quotes));\n\n                cvh = Handle<BlackVolTermStructure>(cdsVolCurve);\n            } else {\n                string decayModeString = parameters->cdsVolDecayMode();\n                LOG(\"Deterministic CDS Vols with decay mode \" << decayModeString << \" for \" << name);\n                ReactionToTimeDecay decayMode = parseDecayMode(decayModeString);\n\n                // currently only curves (i.e. strike indepdendent) CDS volatility structures are\n                // supported, so we use a) the more efficient curve tag and b) a hard coded sticky\n                // strike stickyness, since then no yield term structures and no fx spot are required\n                // that define the ATM level\n                cvh = Handle<BlackVolTermStructure>(\n                    boost::make_shared<QuantExt::DynamicBlackVolTermStructure<tag::curve>>(wrapper, 0, NullCalendar(),\n                                                                                           decayMode, StickyStrike));\n            }\n\n            if (wrapper->allowsExtrapolation())\n                cvh->enableExtrapolation();\n            cdsVols_.insert(pair<pair<string, string>, Handle<BlackVolTermStructure>>(\n                make_pair(Market::defaultConfiguration, name), cvh));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"cds volatilities done\");\n\n    // building fx volatilities\n    LOG(\"building fx volatilities...\");\n    for (const auto& ccyPair : parameters->fxVolCcyPairs()) {\n        try {\n            Handle<BlackVolTermStructure> wrapper = initMarket->fxVol(ccyPair, configuration);\n            Handle<Quote> spot = fxSpot(ccyPair);\n            QL_REQUIRE(ccyPair.length() == 6, \"invalid ccy pair length\");\n            string forCcy = ccyPair.substr(0, 3);\n            string domCcy = ccyPair.substr(3, 3);\n            Handle<YieldTermStructure> forTS = discountCurve(forCcy);\n            Handle<YieldTermStructure> domTS = discountCurve(domCcy);\n            Handle<BlackVolTermStructure> fvh;\n\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            if (parameters->simulateFXVols()) {\n                LOG(\"Simulating FX Vols (BlackVarianceCurve3) for \" << ccyPair);\n                Size n = parameters->fxVolExpiries().size();\n                Size m = parameters->fxVolMoneyness().size();\n                vector<vector<Handle<Quote>>> quotes(m, vector<Handle<Quote>>(n, Handle<Quote>()));\n                Calendar cal = wrapper->calendar();\n                // FIXME hardcoded in todaysmarket\n                DayCounter dc = ore::data::parseDayCounter(parameters->fxVolDayCounter(ccyPair));\n                vector<Time> times;\n\n                for (Size i = 0; i < n; i++) {\n                    Date date = asof_ + parameters->fxVolExpiries()[i];\n\n                    times.push_back(wrapper->timeFromReference(date));\n\n                    for (Size j = 0; j < m; j++) {\n                        Size idx = j * n + i;\n                        Real mon = parameters->fxVolMoneyness()[j]; // 0 if ATM\n\n                        // strike (assuming forward prices)\n                        Real k = spot->value() * mon * forTS->discount(date) / domTS->discount(date);\n                        Volatility vol = wrapper->blackVol(date, k, true);\n                        boost::shared_ptr<SimpleQuote> q(new SimpleQuote(vol));\n                        simDataTmp.emplace(std::piecewise_construct,\n                                           std::forward_as_tuple(RiskFactorKey::KeyType::FXVolatility, ccyPair, idx),\n                                           std::forward_as_tuple(q));\n                        quotes[j][i] = Handle<Quote>(q);\n                    }\n                }\n\n                boost::shared_ptr<BlackVolTermStructure> fxVolCurve;\n                if (parameters->fxVolIsSurface()) {\n                    bool stickyStrike = true;\n                    fxVolCurve = boost::shared_ptr<BlackVolTermStructure>(new BlackVarianceSurfaceMoneynessForward(\n                        cal, spot, times, parameters->fxVolMoneyness(), quotes, dc, forTS, domTS, stickyStrike));\n                } else {\n                    fxVolCurve = boost::shared_ptr<BlackVolTermStructure>(new BlackVarianceCurve3(\n                        0, NullCalendar(), wrapper->businessDayConvention(), dc, times, quotes[0]));\n                }\n                fvh = Handle<BlackVolTermStructure>(fxVolCurve);\n\n            } else {\n                string decayModeString = parameters->fxVolDecayMode();\n                LOG(\"Deterministic FX Vols with decay mode \" << decayModeString << \" for \" << ccyPair);\n                ReactionToTimeDecay decayMode = parseDecayMode(decayModeString);\n\n                // currently only curves (i.e. strike indepdendent) FX volatility structures are\n                // supported, so we use a) the more efficient curve tag and b) a hard coded sticky\n                // strike stickyness, since then no yield term structures and no fx spot are required\n                // that define the ATM level - to be revisited when FX surfaces are supported\n                fvh = Handle<BlackVolTermStructure>(\n                    boost::make_shared<QuantExt::DynamicBlackVolTermStructure<tag::curve>>(wrapper, 0, NullCalendar(),\n                                                                                           decayMode, StickyStrike));\n            }\n\n            fvh->enableExtrapolation();\n            fxVols_.insert(pair<pair<string, string>, Handle<BlackVolTermStructure>>(\n                make_pair(Market::defaultConfiguration, ccyPair), fvh));\n\n            // build inverted surface\n            QL_REQUIRE(ccyPair.size() == 6, \"Invalid Ccy pair \" << ccyPair);\n            string reverse = ccyPair.substr(3) + ccyPair.substr(0, 3);\n            Handle<QuantLib::BlackVolTermStructure> ifvh(boost::make_shared<BlackInvertedVolTermStructure>(fvh));\n            ifvh->enableExtrapolation();\n            fxVols_.insert(pair<pair<string, string>, Handle<BlackVolTermStructure>>(\n                make_pair(Market::defaultConfiguration, reverse), ifvh));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"fx volatilities done\");\n\n    // building eq volatilities\n    LOG(\"building eq volatilities...\");\n    for (const auto& equityName : parameters->equityVolNames()) {\n        try {\n            Handle<BlackVolTermStructure> wrapper = initMarket->equityVol(equityName, configuration);\n\n            Handle<BlackVolTermStructure> evh;\n\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            if (parameters->simulateEquityVols()) {\n                Handle<Quote> spot = equitySpots_[make_pair(Market::defaultConfiguration, equityName)];\n                Size n = parameters->equityVolMoneyness().size();\n                Size m = parameters->equityVolExpiries().size();\n                vector<vector<Handle<Quote>>> quotes(n, vector<Handle<Quote>>(m, Handle<Quote>()));\n                vector<Time> times(m);\n                Calendar cal = wrapper->calendar();\n                DayCounter dc = ore::data::parseDayCounter(parameters->equityVolDayCounter(equityName));\n                bool atmOnly = parameters->simulateEquityVolATMOnly();\n\n                for (Size i = 0; i < n; i++) {\n                    Real mon = parameters->equityVolMoneyness()[i];\n                    // strike\n                    Real k = atmOnly ? Null<Real>() : spot->value() * mon;\n\n                    for (Size j = 0; j < m; j++) {\n                        // Index is expires then moneyness. TODO: is this the best?\n                        Size idx = i * m + j;\n                        times[j] = dc.yearFraction(asof_, asof_ + parameters->equityVolExpiries()[j]);\n                        Volatility vol = wrapper->blackVol(asof_ + parameters->equityVolExpiries()[j], k);\n                        boost::shared_ptr<SimpleQuote> q(new SimpleQuote(vol));\n                        simDataTmp.emplace(\n                            std::piecewise_construct,\n                            std::forward_as_tuple(RiskFactorKey::KeyType::EquityVolatility, equityName, idx),\n                            std::forward_as_tuple(q));\n                        quotes[i][j] = Handle<Quote>(q);\n                    }\n                }\n                boost::shared_ptr<BlackVolTermStructure> eqVolCurve;\n                if (!parameters->simulateEquityVolATMOnly()) {\n                    LOG(\"Simulating EQ Vols (BlackVarianceSurfaceMoneyness) for \" << equityName);\n                    // If true, the strikes are fixed, if false they move with the spot handle\n                    // Should probably be false, but some people like true for sensi runs.\n                    bool stickyStrike = true;\n\n                    eqVolCurve = boost::shared_ptr<BlackVolTermStructure>(new BlackVarianceSurfaceMoneynessSpot(\n                        cal, spot, times, parameters->equityVolMoneyness(), quotes, dc, stickyStrike));\n                    eqVolCurve->enableExtrapolation();\n                } else {\n                    LOG(\"Simulating EQ Vols (BlackVarianceCurve3) for \" << equityName);\n                    eqVolCurve = boost::shared_ptr<BlackVolTermStructure>(new BlackVarianceCurve3(\n                        0, NullCalendar(), wrapper->businessDayConvention(), dc, times, quotes[0]));\n                }\n\n                // if we have a surface but are only simulating atm vols we wrap the atm curve and the full t0 surface\n                if (parameters->equityVolIsSurface() && parameters->simulateEquityVolATMOnly()) {\n                    LOG(\"Simulating EQ Vols (EquityVolatilityConstantSpread) for \" << equityName);\n                    evh = Handle<BlackVolTermStructure>(boost::make_shared<EquityVolatilityConstantSpread>(\n                        Handle<BlackVolTermStructure>(eqVolCurve), wrapper));\n                } else {\n                    evh = Handle<BlackVolTermStructure>(eqVolCurve);\n                }\n            } else {\n                string decayModeString = parameters->equityVolDecayMode();\n                DLOG(\"Deterministic EQ Vols with decay mode \" << decayModeString << \" for \" << equityName);\n                ReactionToTimeDecay decayMode = parseDecayMode(decayModeString);\n\n                // currently only curves (i.e. strike indepdendent) EQ volatility structures are\n                // supported, so we use a) the more efficient curve tag and b) a hard coded sticky\n                // strike stickyness, since then no yield term structures and no EQ spot are required\n                // that define the ATM level - to be revisited when EQ surfaces are supported\n                evh = Handle<BlackVolTermStructure>(\n                    boost::make_shared<QuantExt::DynamicBlackVolTermStructure<tag::curve>>(wrapper, 0, NullCalendar(),\n                                                                                           decayMode, StickyStrike));\n            }\n            if (wrapper->allowsExtrapolation())\n                evh->enableExtrapolation();\n            equityVols_.insert(pair<pair<string, string>, Handle<BlackVolTermStructure>>(\n                make_pair(Market::defaultConfiguration, equityName), evh));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n            DLOG(\"EQ volatility curve built for \" << equityName);\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"equity volatilities done\");\n\n    // building base correlation structures\n    LOG(\"building base correlations...\");\n    for (const auto& bcName : parameters->baseCorrelationNames()) {\n        try {\n            Handle<BaseCorrelationTermStructure<BilinearInterpolation>> wrapper =\n                initMarket->baseCorrelation(bcName, configuration);\n            if (!parameters->simulateBaseCorrelations())\n                baseCorrelations_.insert(\n                    pair<pair<string, string>, Handle<BaseCorrelationTermStructure<BilinearInterpolation>>>(\n                        make_pair(Market::defaultConfiguration, bcName), wrapper));\n            else {\n                Size nd = parameters->baseCorrelationDetachmentPoints().size();\n                Size nt = parameters->baseCorrelationTerms().size();\n                vector<vector<Handle<Quote>>> quotes(nd, vector<Handle<Quote>>(nt));\n                vector<Period> terms(nt);\n                std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n                for (Size i = 0; i < nd; ++i) {\n                    Real lossLevel = parameters->baseCorrelationDetachmentPoints()[i];\n                    for (Size j = 0; j < nt; ++j) {\n                        Period term = parameters->baseCorrelationTerms()[j];\n                        if (i == 0)\n                            terms[j] = term;\n                        Real bc = wrapper->correlation(asof_ + term, lossLevel, true); // extrapolate\n                        boost::shared_ptr<SimpleQuote> q(new SimpleQuote(bc));\n                        simDataTmp.emplace(\n                            std::piecewise_construct,\n                            std::forward_as_tuple(RiskFactorKey::KeyType::BaseCorrelation, bcName, i * nt + j),\n                            std::forward_as_tuple(q));\n                        quotes[i][j] = Handle<Quote>(q);\n                    }\n                }\n\n                // FIXME: Same change as in ored/market/basecorrelationcurve.cpp\n                if (nt == 1) {\n                    terms.push_back(terms[0] + 1 * Days); // arbitrary, but larger than the first term\n                    for (Size i = 0; i < nd; ++i)\n                        quotes[i].push_back(quotes[i][0]);\n                }\n                DayCounter dc = ore::data::parseDayCounter(parameters->baseCorrelationDayCounter(bcName));\n                boost::shared_ptr<BilinearBaseCorrelationTermStructure> bcp =\n                    boost::make_shared<BilinearBaseCorrelationTermStructure>(\n                        wrapper->settlementDays(), wrapper->calendar(), wrapper->businessDayConvention(), terms,\n                        parameters->baseCorrelationDetachmentPoints(), quotes, dc);\n\n                bcp->enableExtrapolation(wrapper->allowsExtrapolation());\n                Handle<BilinearBaseCorrelationTermStructure> bch(bcp);\n                baseCorrelations_.insert(\n                    pair<pair<string, string>, Handle<BaseCorrelationTermStructure<BilinearInterpolation>>>(\n                        make_pair(Market::defaultConfiguration, bcName), bch));\n                simData_.insert(simDataTmp.begin(), simDataTmp.end());\n            }\n            DLOG(\"Base correlations built for \" << bcName);\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"base correlations done\");\n\n    LOG(\"building CPI Indices...\");\n    for (const auto& ci : parameters->cpiIndices()) {\n        try {\n\n            DLOG(\"adding \" << ci << \" base CPI price\");\n            Handle<ZeroInflationIndex> zeroInflationIndex = initMarket->zeroInflationIndex(ci, configuration);\n            Period obsLag = zeroInflationIndex->zeroInflationTermStructure()->observationLag();\n            Date fixingDate = zeroInflationIndex->zeroInflationTermStructure()->baseDate();\n            Real baseCPI = zeroInflationIndex->fixing(fixingDate);\n\n            boost::shared_ptr<SimpleQuote> q(new SimpleQuote(baseCPI));\n            Handle<Quote> qh(q);\n\n            boost::shared_ptr<InflationIndex> inflationIndex =\n                boost::dynamic_pointer_cast<InflationIndex>(*zeroInflationIndex);\n            Handle<InflationIndexObserver> inflObserver(\n                boost::make_shared<InflationIndexObserver>(inflationIndex, qh, obsLag));\n\n            baseCpis_.insert(pair<pair<string, string>, Handle<InflationIndexObserver>>(\n                make_pair(Market::defaultConfiguration, ci), inflObserver));\n            simData_.emplace(std::piecewise_construct, std::forward_as_tuple(RiskFactorKey::KeyType::CPIIndex, ci),\n                             std::forward_as_tuple(q));\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"CPI Indices done\");\n\n    LOG(\"building zero inflation curves...\");\n    for (const auto& zic : parameters->zeroInflationIndices()) {\n        try {\n            LOG(\"building \" << zic << \" zero inflation curve\");\n\n            Handle<ZeroInflationIndex> inflationIndex = initMarket->zeroInflationIndex(zic, configuration);\n            Handle<ZeroInflationTermStructure> inflationTs = inflationIndex->zeroInflationTermStructure();\n            vector<string> keys(parameters->zeroInflationTenors(zic).size());\n\n            string ccy = inflationIndex->currency().code();\n            Handle<YieldTermStructure> yts = discountCurve(ccy, configuration);\n\n            Date date0 = asof_ - inflationTs->observationLag();\n            DayCounter dc = ore::data::parseDayCounter(parameters->zeroInflationDayCounter(zic));\n            vector<Date> quoteDates;\n            vector<Time> zeroCurveTimes(\n                1, -dc.yearFraction(inflationPeriod(date0, inflationTs->frequency()).first, asof_));\n            vector<Handle<Quote>> quotes;\n            QL_REQUIRE(parameters->zeroInflationTenors(zic).front() > 0 * Days,\n                       \"zero inflation tenors must not include t=0\");\n\n            for (auto& tenor : parameters->zeroInflationTenors(zic)) {\n                Date inflDate = inflationPeriod(date0 + tenor, inflationTs->frequency()).first;\n                zeroCurveTimes.push_back(dc.yearFraction(asof_, inflDate));\n                quoteDates.push_back(asof_ + tenor);\n            }\n\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            for (Size i = 1; i < zeroCurveTimes.size(); i++) {\n                boost::shared_ptr<SimpleQuote> q(new SimpleQuote(inflationTs->zeroRate(quoteDates[i - 1])));\n                Handle<Quote> qh(q);\n                if (i == 1) {\n                    // add the zero rate at first tenor to the T0 time, to ensure flat interpolation of T1 rate\n                    // for time t T0 < t < T1\n                    quotes.push_back(qh);\n                }\n                quotes.push_back(qh);\n                simDataTmp.emplace(std::piecewise_construct,\n                                   std::forward_as_tuple(RiskFactorKey::KeyType::ZeroInflationCurve, zic, i - 1),\n                                   std::forward_as_tuple(q));\n                DLOG(\"ScenarioSimMarket index curve \" << zic << \" zeroRate[\" << i << \"]=\" << q->value());\n            }\n\n            // FIXME: Settlement days set to zero - needed for floating term structure implementation\n            boost::shared_ptr<ZeroInflationTermStructure> zeroCurve;\n            dc = ore::data::parseDayCounter(parameters->zeroInflationDayCounter(zic));\n            zeroCurve = boost::shared_ptr<ZeroInflationCurveObserverMoving<Linear>>(\n                new ZeroInflationCurveObserverMoving<Linear>(\n                    0, inflationIndex->fixingCalendar(), dc, inflationTs->observationLag(), inflationTs->frequency(),\n                    inflationTs->indexIsInterpolated(), yts, zeroCurveTimes, quotes, inflationTs->seasonality()));\n\n            Handle<ZeroInflationTermStructure> its(zeroCurve);\n            its->enableExtrapolation();\n            boost::shared_ptr<ZeroInflationIndex> i =\n                ore::data::parseZeroInflationIndex(zic, false, Handle<ZeroInflationTermStructure>(its));\n            Handle<ZeroInflationIndex> zh(i);\n            zeroInflationIndices_.insert(pair<pair<string, string>, Handle<ZeroInflationIndex>>(\n                make_pair(Market::defaultConfiguration, zic), zh));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n\n            LOG(\"building \" << zic << \" zero inflation curve done\");\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"zero inflation curves done\");\n\n    LOG(\"building yoy inflation curves...\");\n    for (const auto& yic : parameters->yoyInflationIndices()) {\n        try {\n\n            Handle<YoYInflationIndex> yoyInflationIndex = initMarket->yoyInflationIndex(yic, configuration);\n            Handle<YoYInflationTermStructure> yoyInflationTs = yoyInflationIndex->yoyInflationTermStructure();\n            vector<string> keys(parameters->yoyInflationTenors(yic).size());\n\n            string ccy = yoyInflationIndex->currency().code();\n            Handle<YieldTermStructure> yts = initMarket->discountCurve(ccy, configuration);\n\n            Date date0 = asof_ - yoyInflationTs->observationLag();\n            DayCounter dc = ore::data::parseDayCounter(parameters->yoyInflationDayCounter(yic));\n            vector<Date> quoteDates;\n            vector<Time> yoyCurveTimes(\n                1, -dc.yearFraction(inflationPeriod(date0, yoyInflationTs->frequency()).first, asof_));\n            vector<Handle<Quote>> quotes;\n            QL_REQUIRE(parameters->yoyInflationTenors(yic).front() > 0 * Days,\n                       \"zero inflation tenors must not include t=0\");\n\n            for (auto& tenor : parameters->yoyInflationTenors(yic)) {\n                Date inflDate = inflationPeriod(date0 + tenor, yoyInflationTs->frequency()).first;\n                yoyCurveTimes.push_back(dc.yearFraction(asof_, inflDate));\n                quoteDates.push_back(asof_ + tenor);\n            }\n\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            for (Size i = 1; i < yoyCurveTimes.size(); i++) {\n                boost::shared_ptr<SimpleQuote> q(new SimpleQuote(yoyInflationTs->yoyRate(quoteDates[i - 1])));\n                Handle<Quote> qh(q);\n                if (i == 1) {\n                    // add the zero rate at first tenor to the T0 time, to ensure flat interpolation of T1 rate\n                    // for time t T0 < t < T1\n                    quotes.push_back(qh);\n                }\n                quotes.push_back(qh);\n                simDataTmp.emplace(std::piecewise_construct,\n                                   std::forward_as_tuple(RiskFactorKey::KeyType::YoYInflationCurve, yic, i - 1),\n                                   std::forward_as_tuple(q));\n                DLOG(\"ScenarioSimMarket index curve \" << yic << \" zeroRate[\" << i << \"]=\" << q->value());\n            }\n\n            boost::shared_ptr<YoYInflationTermStructure> yoyCurve;\n            // Note this is *not* a floating term structure, it is only suitable for sensi runs\n            // TODO: floating\n            yoyCurve =\n                boost::shared_ptr<YoYInflationCurveObserverMoving<Linear>>(new YoYInflationCurveObserverMoving<Linear>(\n                    0, yoyInflationIndex->fixingCalendar(), dc, yoyInflationTs->observationLag(),\n                    yoyInflationTs->frequency(), yoyInflationTs->indexIsInterpolated(), yts, yoyCurveTimes, quotes,\n                    yoyInflationTs->seasonality()));\n\n            Handle<YoYInflationTermStructure> its(yoyCurve);\n            its->enableExtrapolation();\n            boost::shared_ptr<YoYInflationIndex> i(yoyInflationIndex->clone(its));\n            Handle<YoYInflationIndex> zh(i);\n            yoyInflationIndices_.insert(pair<pair<string, string>, Handle<YoYInflationIndex>>(\n                make_pair(Market::defaultConfiguration, yic), zh));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"yoy inflation curves done\");\n\n    LOG(\"building commodity spots\");\n    for (const auto& name : parameters->commodityNames()) {\n        try {\n            Real spot = initMarket->commoditySpot(name, configuration)->value();\n            DLOG(\"adding \" << name << \" commodity spot price\");\n            boost::shared_ptr<SimpleQuote> q = boost::make_shared<SimpleQuote>(spot);\n            commoditySpots_.emplace(piecewise_construct, forward_as_tuple(Market::defaultConfiguration, name),\n                                    forward_as_tuple(q));\n            simData_.emplace(piecewise_construct, forward_as_tuple(RiskFactorKey::KeyType::CommoditySpot, name),\n                             forward_as_tuple(q));\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"commodity spots done\");\n\n    LOG(\"building commodity curves\");\n    for (const string& name : parameters->commodityNames()) {\n        try {\n\n            LOG(\"building commodity curve for \" << name);\n\n            // Time zero initial market commodity curve\n            Handle<PriceTermStructure> initialCommodityCurve = initMarket->commodityPriceCurve(name, configuration);\n            bool allowsExtrapolation = initialCommodityCurve->allowsExtrapolation();\n\n            // Get prices at specified simulation tenors from time 0 market curve and place in quotes\n            vector<Period> simulationTenors = parameters->commodityCurveTenors(name);\n            DayCounter commodityCurveDayCounter = parseDayCounter(parameters->commodityCurveDayCounter(name));\n            vector<Time> times(simulationTenors.size());\n            vector<Handle<Quote>> quotes(simulationTenors.size());\n\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            for (Size i = 0; i < simulationTenors.size(); i++) {\n                times[i] = commodityCurveDayCounter.yearFraction(asof_, asof_ + simulationTenors[i]);\n                Real price = initialCommodityCurve->price(times[i], allowsExtrapolation);\n                boost::shared_ptr<SimpleQuote> quote = boost::make_shared<SimpleQuote>(price);\n                quotes[i] = Handle<Quote>(quote);\n\n                // If we are simulating commodities, add the quote to simData_\n                if (parameters->commodityCurveSimulate()) {\n                    simDataTmp.emplace(piecewise_construct,\n                                       forward_as_tuple(RiskFactorKey::KeyType::CommodityCurve, name, i),\n                                       forward_as_tuple(quote));\n                }\n            }\n\n            // Create a commodity price curve with simulation tenors as pillars and store\n            // Hard-coded linear interpolation here - may need to make this more dynamic\n            Handle<PriceTermStructure> simCommodityCurve(\n                boost::make_shared<InterpolatedPriceCurve<Linear>>(times, quotes, commodityCurveDayCounter));\n            simCommodityCurve->enableExtrapolation(allowsExtrapolation);\n\n            commodityCurves_.emplace(piecewise_construct, forward_as_tuple(Market::defaultConfiguration, name),\n                                     forward_as_tuple(simCommodityCurve));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"commodity curves done\");\n\n    LOG(\"building commodity volatilities\");\n    for (const auto& name : parameters->commodityVolNames()) {\n        try {\n            // Get initial base volatility structure\n            Handle<BlackVolTermStructure> baseVol = initMarket->commodityVolatility(name, configuration);\n\n            Handle<BlackVolTermStructure> newVol;\n            std::map<RiskFactorKey, boost::shared_ptr<SimpleQuote>> simDataTmp;\n            if (parameters->commodityVolSimulate()) {\n                Handle<Quote> spot = commoditySpot(name, configuration);\n                const vector<Real>& moneyness = parameters->commodityVolMoneyness(name);\n                QL_REQUIRE(!moneyness.empty(),\n                           \"Commodity volatility moneyness for \" << name << \" should have at least one element\");\n                const vector<Period>& expiries = parameters->commodityVolExpiries(name);\n                QL_REQUIRE(!expiries.empty(),\n                           \"Commodity volatility expiries for \" << name << \" should have at least one element\");\n\n                // Create surface of quotes\n                vector<vector<Handle<Quote>>> quotes(moneyness.size(), vector<Handle<Quote>>(expiries.size()));\n                vector<Time> expiryTimes(expiries.size());\n                Size index = 0;\n                DayCounter dayCounter = baseVol->dayCounter();\n\n                for (Size i = 0; i < quotes.size(); i++) {\n                    Real strike = moneyness[i] * spot->value();\n                    for (Size j = 0; j < quotes[0].size(); j++) {\n                        if (i == 0)\n                            expiryTimes[j] = dayCounter.yearFraction(asof_, asof_ + expiries[j]);\n                        boost::shared_ptr<SimpleQuote> quote =\n                            boost::make_shared<SimpleQuote>(baseVol->blackVol(asof_ + expiries[j], strike));\n                        simDataTmp.emplace(piecewise_construct,\n                                           forward_as_tuple(RiskFactorKey::KeyType::CommodityVolatility, name, index++),\n                                           forward_as_tuple(quote));\n                        quotes[i][j] = Handle<Quote>(quote);\n                    }\n                }\n\n                // Create volatility structure\n                if (moneyness.size() == 1) {\n                    // We have a term structure of volatilities with no strike dependence\n                    LOG(\"Simulating commodity volatilites for \" << name << \" using BlackVarianceCurve3.\");\n                    newVol = Handle<BlackVolTermStructure>(boost::make_shared<BlackVarianceCurve3>(\n                        0, NullCalendar(), baseVol->businessDayConvention(), dayCounter, expiryTimes, quotes[0]));\n                } else {\n                    // We have a volatility surface\n                    LOG(\"Simulating commodity volatilites for \" << name << \" using BlackVarianceSurfaceMoneynessSpot.\");\n                    bool stickyStrike = true;\n                    newVol = Handle<BlackVolTermStructure>(boost::make_shared<BlackVarianceSurfaceMoneynessSpot>(\n                        baseVol->calendar(), spot, expiryTimes, moneyness, quotes, dayCounter, stickyStrike));\n                }\n\n            } else {\n                string decayModeString = parameters->equityVolDecayMode();\n                DLOG(\"Deterministic commodity volatilities with decay mode \" << decayModeString << \" for \" << name);\n                ReactionToTimeDecay decayMode = parseDecayMode(decayModeString);\n                // Copy what was done for equity here\n                // May need to revisit when looking at commodity RFE\n                newVol = Handle<BlackVolTermStructure>(\n                    boost::make_shared<QuantExt::DynamicBlackVolTermStructure<tag::curve>>(baseVol, 0, NullCalendar(),\n                                                                                           decayMode, StickyStrike));\n            }\n\n            newVol->enableExtrapolation(baseVol->allowsExtrapolation());\n\n            commodityVols_.emplace(piecewise_construct, forward_as_tuple(Market::defaultConfiguration, name),\n                                   forward_as_tuple(newVol));\n            simData_.insert(simDataTmp.begin(), simDataTmp.end());\n\n            DLOG(\"Commodity volatility curve built for \" << name);\n        } catch (const std::exception& e) {\n            if (continueOnError) {\n                ALOG(\"skipping this object: \" << e.what());\n            } else {\n                QL_FAIL(e.what());\n            }\n        }\n    }\n    LOG(\"commodity volatilities done\");\n\n    // building correlations\n    LOG(\"building correlations... \" << parameters->correlationPairs().size());\n    for (const auto& pair : parameters->correlationPairs()) {\n        LOG(\"Adding correlations for \" << pair.first << \":\" << pair.second << \" from configuration \" << configuration);\n        boost::shared_ptr<QuantExt::CorrelationTermStructure> corr;\n        Handle<QuantExt::CorrelationTermStructure> baseCorr =\n            initMarket->correlationCurve(pair.first, pair.second, configuration);\n\n        Handle<QuantExt::CorrelationTermStructure> ch;\n        if (parameters->simulateCorrelations()) {\n\n            string label = pair.first + \":\" + pair.second;\n\n            Size n = parameters->correlationStrikes().size();\n            Size m = parameters->correlationExpiries().size();\n            vector<vector<Handle<Quote>>> quotes(n, vector<Handle<Quote>>(m, Handle<Quote>()));\n            vector<Time> times(m);\n            Calendar cal = baseCorr->calendar();\n            DayCounter dc = ore::data::parseDayCounter(parameters->correlationDayCounter(pair.first, pair.second));\n\n            for (Size i = 0; i < n; i++) {\n                Real strike = parameters->correlationStrikes()[i];\n\n                for (Size j = 0; j < m; j++) {\n                    // Index is expiries then strike TODO: is this the best?\n                    Size idx = i * m + j;\n                    times[j] = dc.yearFraction(asof_, asof_ + parameters->correlationExpiries()[j]);\n                    Real correlation = baseCorr->correlation(asof_ + parameters->correlationExpiries()[j], strike);\n                    boost::shared_ptr<SimpleQuote> q(new SimpleQuote(correlation));\n                    simData_.emplace(std::piecewise_construct,\n                                     std::forward_as_tuple(RiskFactorKey::KeyType::Correlation, label, idx),\n                                     std::forward_as_tuple(q));\n                    quotes[i][j] = Handle<Quote>(q);\n                }\n            }\n\n            if (n == 1 && m == 1) {\n                ch = Handle<QuantExt::CorrelationTermStructure>(\n                    boost::make_shared<FlatCorrelation>(baseCorr->settlementDays(), cal, quotes[0][0], dc));\n            } else if (n == 1) {\n                ch = Handle<QuantExt::CorrelationTermStructure>(\n                    boost::make_shared<InterpolatedCorrelationCurve<Linear>>(times, quotes[0], dc, cal));\n            } else {\n                QL_FAIL(\"only atm or flat correlation termstructures currently supported\");\n            }\n\n            ch->enableExtrapolation(baseCorr->allowsExtrapolation());\n        } else {\n            ch = Handle<QuantExt::CorrelationTermStructure>(*baseCorr);\n        }\n\n        correlationCurves_[make_tuple(Market::defaultConfiguration, pair.first, pair.second)] = ch;\n    }\n    LOG(\"security recovery rates done...\");\n\n    LOG(\"building base scenario\");\n    baseScenario_ = boost::make_shared<SimpleScenario>(initMarket->asofDate(), \"BASE\", 1.0);\n    for (auto const& data : simData_) {\n        baseScenario_->add(data.first, data.second->value());\n    }\n    LOG(\"building base scenario done\");\n}\n\nvoid ScenarioSimMarket::applyScenario(const boost::shared_ptr<Scenario>& scenario) {\n    const vector<RiskFactorKey>& keys = scenario->keys();\n\n    Size count = 0;\n    for (const auto& key : keys) {\n        // Loop through the scenario keys and check which keys are present in simData_,\n        // adding to the count when a match is identified\n        // Then check that the count=simData_.size - this ensures that simData_ is a valid\n        // subset of the scenario - fails is a member of simData is not present in the\n        // scenario\n        auto it = simData_.find(key);\n        if (it == simData_.end()) {\n            ALOG(\"simulation data point missing for key \" << key);\n        } else {\n            if (filter_->allow(key))\n                it->second->setValue(scenario->get(key));\n            count++;\n        }\n    }\n\n    if (count != simData_.size()) {\n        ALOG(\"mismatch between scenario and sim data size, \" << count << \" vs \" << simData_.size());\n        for (auto it : simData_) {\n            if (!scenario->has(it.first))\n                ALOG(\"Key \" << it.first << \" missing in scenario\");\n        }\n        QL_FAIL(\"mismatch between scenario and sim data size, exit.\");\n    }\n\n    // update market asof date\n    asof_ = scenario->asof();\n}\n\nvoid ScenarioSimMarket::reset() {\n    auto filterBackup = filter_;\n    // no filter\n    filter_ = boost::make_shared<ScenarioFilter>();\n    // reset eval date\n    Settings::instance().evaluationDate() = baseScenario_->asof();\n    // reset numeraire\n    numeraire_ = baseScenario_->getNumeraire();\n    // reset term structures\n    applyScenario(baseScenario_);\n    // see the comment in update() for why this is necessary...\n    if (ObservationMode::instance().mode() == ObservationMode::Mode::Unregister) {\n        boost::shared_ptr<QuantLib::Observable> obs = QuantLib::Settings::instance().evaluationDate();\n        obs->notifyObservers();\n    }\n    // reset fixing manager\n    fixingManager_->reset();\n    // restore the filter\n    filter_ = filterBackup;\n}\n\nvoid ScenarioSimMarket::update(const Date& d) {\n    // DLOG(\"ScenarioSimMarket::update called with Date \" << QuantLib::io::iso_date(d));\n    QL_REQUIRE(scenarioGenerator_ != nullptr, \"ScenarioSimMarket::update: no scenario generator set\");\n\n    ObservationMode::Mode om = ObservationMode::instance().mode();\n    if (om == ObservationMode::Mode::Disable)\n        ObservableSettings::instance().disableUpdates(false);\n    else if (om == ObservationMode::Mode::Defer)\n        ObservableSettings::instance().disableUpdates(true);\n\n    boost::shared_ptr<Scenario> scenario = scenarioGenerator_->next(d);\n    QL_REQUIRE(scenario->asof() == d, \"Invalid Scenario date \" << scenario->asof() << \", expected \" << d);\n\n    numeraire_ = scenario->getNumeraire();\n\n    if (d != Settings::instance().evaluationDate())\n        Settings::instance().evaluationDate() = d;\n    else if (om == ObservationMode::Mode::Unregister) {\n        // Due to some of the notification chains having been unregistered,\n        // it is possible that some lazy objects might be missed in the case\n        // that the evaluation date has not been updated. Therefore, we\n        // manually kick off an observer notification from this level.\n        // We have unit regression tests in OREAnalyticsTestSuite to ensure\n        // the various ObservationMode settings return the anticipated results.\n        boost::shared_ptr<QuantLib::Observable> obs = QuantLib::Settings::instance().evaluationDate();\n        obs->notifyObservers();\n    }\n\n    applyScenario(scenario);\n\n    // Observation Mode - key to update these before fixings are set\n    if (om == ObservationMode::Mode::Disable) {\n        refresh();\n        ObservableSettings::instance().enableUpdates();\n    } else if (om == ObservationMode::Mode::Defer) {\n        ObservableSettings::instance().enableUpdates();\n    }\n\n    // Apply fixings as historical fixings. Must do this before we populate ASD\n    fixingManager_->update(d);\n\n    if (asd_) {\n        // add additional scenario data to the given container, if required\n        for (auto i : parameters_->additionalScenarioDataIndices()) {\n            boost::shared_ptr<QuantLib::Index> index;\n            try {\n                index = *iborIndex(i);\n            } catch (...) {\n            }\n            try {\n                index = *swapIndex(i);\n            } catch (...) {\n            }\n            QL_REQUIRE(index != nullptr, \"ScenarioSimMarket::update() index \" << i << \" not found in sim market\");\n            asd_->set(index->fixing(d), AggregationScenarioDataType::IndexFixing, i);\n        }\n\n        for (auto c : parameters_->additionalScenarioDataCcys()) {\n            if (c != parameters_->baseCcy())\n                asd_->set(fxSpot(c + parameters_->baseCcy())->value(), AggregationScenarioDataType::FXSpot, c);\n        }\n\n        asd_->set(numeraire_, AggregationScenarioDataType::Numeraire);\n\n        asd_->next();\n    }\n\n    // DLOG(\"ScenarioSimMarket::update done\");\n}\n\nbool ScenarioSimMarket::isSimulated(const RiskFactorKey::KeyType& factor) const {\n    return std::find(nonSimulatedFactors_.begin(), nonSimulatedFactors_.end(), factor) == nonSimulatedFactors_.end();\n}\n\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "d974af8148cfc99260c0ec43206218336a07c947", "size": 84001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/scenario/scenariosimmarket.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": "OREAnalytics/orea/scenario/scenariosimmarket.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": "OREAnalytics/orea/scenario/scenariosimmarket.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": 52.5663329161, "max_line_length": 120, "alphanum_fraction": 0.5876953846, "num_tokens": 18149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.17178752032979813}}
{"text": "// Copyright (c) 2020 The UNIGRID organization\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 <boost/filesystem.hpp>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <fstream>\n#include <generatecert.h>\n#include <iostream>\n#include <random>\n#include <regex>\n#include <util.h>\n\n#include <openssl/pem.h>\n#include <openssl/x509.h>\n\n/* Generates a 2048-bit RSA key. */\nEVP_PKEY* GenerateCert::generate_key()\n{\n    LogPrintf(\"Attempting to allocate memory for the EVP_PKEY structure. \\n\");\n    /* Allocate memory for the EVP_PKEY structure. */\n    EVP_PKEY* pkey = EVP_PKEY_new();\n\n    /* Generate a RSA key and assign it to pkey. */\n    BIGNUM* bne = BN_new();\n    BN_set_word(bne, RSA_F4);\n    RSA* rsa = RSA_new();\n    RSA_generate_key_ex(rsa, 2048, bne, nullptr);\n\n    EVP_PKEY_assign_RSA(pkey, rsa);\n    LogPrintf(\"Returning new key. \\n\");\n    return pkey;\n}\n\n/* Generates a self-signed x509 certificate. */\nX509* GenerateCert::generate_x509(EVP_PKEY* pkey)\n{\n    /* Allocate memory for the X509 structure. */\n    X509* x509 = X509_new();\n    if (!x509) {\n        LogPrintf(\"Unable to create X509 structure. \\n\");\n        return NULL;\n    }\n\n    /* Set the serial number. */\n    ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);\n\n    /* This certificate is valid from now until exactly 10 years from now. */\n    X509_gmtime_adj(X509_get_notBefore(x509), 0);\n    X509_gmtime_adj(X509_get_notAfter(x509), 315360000L);\n\n    /* Set the public key for our certificate. */\n    X509_set_pubkey(x509, pkey);\n\n    /* We want to copy the subject name to the issuer name. */\n    X509_NAME* name = X509_get_subject_name(x509);\n\n    /* Set the country code and common name. */\n    X509_NAME_add_entry_by_txt(name, \"C\", MBSTRING_ASC, (unsigned char*)\"SE\", -1, -1, 0);\n    X509_NAME_add_entry_by_txt(name, \"O\", MBSTRING_ASC, (unsigned char*)\"UNIGRID\", -1, -1, 0);\n    X509_NAME_add_entry_by_txt(name, \"CN\", MBSTRING_ASC, (unsigned char*)GenerateCert::gen_random(15), -1, -1, 0);\n    LogPrintf(\"random string: %s \\n\", GenerateCert::gen_random(15));\n    /* Now set the issuer name. */\n    X509_set_issuer_name(x509, name);\n\n    /* Actually sign the certificate with our key. */\n    if (!X509_sign(x509, pkey, EVP_sha1())) {\n        LogPrintf(\"Error signing certificate. \\n\");\n        X509_free(x509);\n        return NULL;\n    }\n\n    return x509;\n}\n\nbool GenerateCert::write_to_disk(EVP_PKEY* pkey, X509* x509)\n{\n    /* Open the PEM file for writing the key to disk. */\n    boost::filesystem::path pathKey = GetSslKey();\n    boost::filesystem::ifstream keyStreamConfig(pathKey);\n    if (!keyStreamConfig.good()) {\n        FILE* pkey_file = fopen(pathKey.string().c_str(), \"wb\");\n\n        if (!pkey_file) {\n            LogPrintf(\"Unable to open %s for writing. \\n\", pathKey);\n            return false;\n        }\n\n        /* Write the key to disk. */\n        bool ret = PEM_write_PrivateKey(pkey_file, pkey, NULL, NULL, 0, NULL, NULL);\n        fclose(pkey_file);\n\n        if (!ret) {\n            LogPrintf(\"Unable to write private key to disk. \\n\");\n            return false;\n        }\n    }\n    /* Open the PEM file for writing the certificate to disk. */\n    boost::filesystem::path pathSslCert = GetSslCert();\n    boost::filesystem::ifstream streamConfig(pathSslCert);\n    if (!streamConfig.good()) {\n        FILE* x509_file = fopen(pathSslCert.string().c_str(), \"wb\");\n        LogPrintf(\"Attempting to save cert to disk. \\n\");\n        if (!x509_file) {\n            LogPrintf(\"Unable to open %s for writing. \\n\", pathSslCert);\n            return false;\n        }\n\n        /* Write the certificate to disk. */\n        bool ret = PEM_write_X509(x509_file, x509);\n        fclose(x509_file);\n        if (!ret) {\n            LogPrintf(\"Unable to write certificate to disk. \\n\");\n            return false;\n        }\n        return true; // Nothing to read, so just return\n    } else {\n        LogPrintf(\"Error opening certificate. \\n\");\n    }\n\n    return true;\n}\n\nvoid GenerateCert::setup()\n{\n    boost::filesystem::path certDir = GetDataDir() / \"certificates\";\n    if (!boost::filesystem::exists(certDir)) {\n        LogPrintf(\"Certificates folder does not exist %u \\n\", boost::filesystem::exists(certDir));\n        boost::filesystem::create_directories(certDir);\n        CreateCertFile();\n    } else {\n        // Check cert files are valid\n        LogPrintf(\"Certificates folder exists %u \\n\", boost::filesystem::exists(certDir));\n        GenerateCert::ValidateCertFiles();\n    }\n}\n\nvoid GenerateCert::CreateCertFile()\n{\n    /* Call generate and save to disk */\n    /* Generate the key. */\n    LogPrintf(\"Generating RSA key... \\n\");\n\n    EVP_PKEY* pkey = GenerateCert::generate_key();\n    LogPrintf(\"After generate_key().. \\n\");\n    if (!pkey)\n        LogPrintf(\"Error generating key... \\n\");\n\n    /* Generate the certificate. */\n    LogPrintf(\"Generating x509 certificate... \\n\");\n\n    X509* x509 = GenerateCert::generate_x509(pkey);\n    if (!x509) {\n        EVP_PKEY_free(pkey);\n        LogPrintf(\"Error generating x509 certificate... \\n\");\n    }\n\n    /* Write the private key and certificate out to disk. */\n    LogPrintf(\"Writing key and certificate to disk... \\n\");\n\n    bool ret = GenerateCert::write_to_disk(pkey, x509);\n    EVP_PKEY_free(pkey);\n    X509_free(x509);\n\n    if (ret) {\n        LogPrintf(\"Success writing key and certificate to disk... \\n\");\n        /* validate the key and cert */\n        GenerateCert::ValidateCertFiles();\n    }\n}\n\n\nvoid GenerateCert::ValidateCertFiles()\n{\n    // Check if files exist\n    boost::filesystem::path pathSslCert = GetSslCert();\n    boost::filesystem::path pathKey = GetSslKey();\n\n    LogPrintf(\"Attempting to validate SSL certificates. \\n\");\n\n    std::string output;\n    std::fstream certFile;\n    std::fstream keyFile;\n    char* cert_pem = new char[3000];\n    char* key_pem = new char[3000];\n    std::smatch match;\n    std::regex rgx_pk(\"-----BEGIN PRIVATE KEY-----\\n([A-Za-z0-9\\\\/\\\\+\\n]+)\");\n    std::regex rgx_pbk(\"-----BEGIN CERTIFICATE-----\\n([A-Za-z0-9\\\\/\\\\+\\n]+)\");\n    certFile.open(pathSslCert.string().c_str(), std::ios::in);\n    if (!certFile.is_open()) {\n        LogPrintf(\"no certFile %\\n\");\n    } else {\n        std::string certFileContent((std::istreambuf_iterator<char>(certFile)),\n            std::istreambuf_iterator<char>());\n        //cert_pem = certFileContent.c_str();\n        std::strncpy(cert_pem, certFileContent.c_str(), certFileContent.size());\n        // cert_pem[certFileContent.size() + 1];\n        LogPrintf(\"certFileContent.size()... %s \\n\", certFileContent.size());\n        LogPrintf(\"cert_pem size... %s \\n\", strlen(cert_pem));\n\n\n        if (std::regex_search(certFileContent, match, rgx_pbk)) {\n            //std::strncpy(cert_pem, match.str(0).c_str(), match.str(0).size());\n            LogPrintf(\"certFile: %s \\n\", certFileContent);\n        } else {\n            LogPrintf(\"no match certFile... %s \\n\", certFileContent);\n        }\n    }\n    keyFile.open(pathKey.string().c_str(), std::ios::in);\n    if (!keyFile.is_open()) {\n        LogPrintf(\"no keyFile %\\n\");\n    } else {\n        std::string keyFileContent((std::istreambuf_iterator<char>(keyFile)),\n            std::istreambuf_iterator<char>());\n        //key_pem = keyFileContent.c_str();\n        std::strncpy(key_pem, keyFileContent.c_str(), keyFileContent.size());\n        LogPrintf(\"certFileContent.size()... %s \\n\", keyFileContent.size());\n        LogPrintf(\"cert_pem size... %s \\n\", strlen(key_pem));\n\n        if (std::regex_search(keyFileContent, match, rgx_pk)) {\n            LogPrintf(\"keyFile: %s \\n\", match.str());\n        } else {\n            LogPrintf(\"no match keyFile... %s \\n\", keyFileContent);\n        }\n    }\n\n    //const char* cert_pem = certFileContent.c_str();\n    //const char* key_pem = keyFileContent.c_str();\n\n    //LogPrintf(\"is test cert valid? %s \\n\", GenerateCert::sig_verify(cert, intermediate));\n    LogPrintf(\"is cert valid? %s \\n\", GenerateCert::sig_verify(cert_pem, key_pem));\n\n    keyFile.close();\n    certFile.close();\n\n\n    /*} else {\n        LogPrintf(\"pbkey is not valid and needs to be generated again. \\n\");\n    }*/\n\n    // Validate the files\n    LogPrintf(\"Validating cert files \\n\");\n}\n\nint GenerateCert::sig_verify(const char* cert_pem, const char* key_pem)\n{\n    LogPrintf(\"attempting to validate keys  \\n\");\n    BIO* b = BIO_new(BIO_s_mem());\n    BIO_puts(b, key_pem);\n    X509* issuer = PEM_read_bio_X509(b, NULL, NULL, NULL);\n    EVP_PKEY* signing_key = X509_get_pubkey(issuer);\n    LogPrintf(\"after EVP_PKEY \\n\");\n    BIO* c = BIO_new(BIO_s_mem());\n    BIO_puts(c, cert_pem);\n    X509* x509 = PEM_read_bio_X509(c, NULL, NULL, NULL);\n\n    int result = X509_verify(x509, signing_key);\n\n    EVP_PKEY_free(signing_key);\n    BIO_free(b);\n    BIO_free(c);\n    X509_free(x509);\n    X509_free(issuer);\n\n    return result;\n}\n\nchar* GenerateCert::gen_random(const int len)\n{\n    std::string tmp_s;\n    static const char alphanum[] =\n        \"0123456789\"\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n        \"abcdefghijklmnopqrstuvwxyz\";\n\n    srand((unsigned)time(NULL) * getpid());\n\n    tmp_s.reserve(len);\n\n    for (int i = 0; i < len; ++i)\n        tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];\n        char* rnd_char = new char[15];\n    std::strncpy(rnd_char, tmp_s.c_str(), tmp_s.size());\n    return rnd_char;\n}\n", "meta": {"hexsha": "7b4a62b19e9f3a56e5b444e29f9f62f4f599d928", "size": 9391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "daemon/generatecert.cpp", "max_stars_repo_name": "unigrid-project/daemon", "max_stars_repo_head_hexsha": "d07b21ff454b57ba5b286c0c52dde12743ac8e9e", "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": "daemon/generatecert.cpp", "max_issues_repo_name": "unigrid-project/daemon", "max_issues_repo_head_hexsha": "d07b21ff454b57ba5b286c0c52dde12743ac8e9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "daemon/generatecert.cpp", "max_forks_repo_name": "unigrid-project/daemon", "max_forks_repo_head_hexsha": "d07b21ff454b57ba5b286c0c52dde12743ac8e9e", "max_forks_repo_licenses": ["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.6076388889, "max_line_length": 114, "alphanum_fraction": 0.6277286764, "num_tokens": 2504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.17178751386580438}}
{"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 <boost/bind.hpp>\n#include <Eigen/Core>\n#include \"genfile/VariantEntry.hpp\"\n#include \"genfile/vcf/get_set_eigen.hpp\"\n#include \"genfile/CohortIndividualSource.hpp\"\n#include \"genfile/SNPDataSource.hpp\"\n#include \"components/SNPSummaryComponent/SNPSummaryComputation.hpp\"\n#include \"components/SNPSummaryComponent/CrossDataSetHaplotypeComparisonComputation.hpp\"\n\nnamespace snp_stats {\n\tCrossDataSetHaplotypeComparisonComputation::CrossDataSetHaplotypeComparisonComputation(\n\t\tgenfile::CohortIndividualSource const& samples,\n\t\tstd::string const& main_dataset_sample_id_column\n\t):\n\t\tm_sample_mapper( samples, main_dataset_sample_id_column ),\n\t\tm_call_threshhold( 0.9 )\n\t{}\n\n\tvoid CrossDataSetHaplotypeComparisonComputation::set_comparer( genfile::VariantIdentifyingData::CompareFields const& comparer ) {\n\t\tm_comparer = comparer ;\n\t}\n\n\tvoid CrossDataSetHaplotypeComparisonComputation::set_match_alleles() {\n\t\tm_match_alleles = true ;\n\t}\n\n\tvoid CrossDataSetHaplotypeComparisonComputation::set_alternate_dataset(\n\t\tgenfile::CohortIndividualSource::UniquePtr samples,\n\t\tstd::string const& comparison_dataset_sample_id_column,\n\t\tgenfile::SNPDataSource::UniquePtr snps\n\t) {\n\t\tm_sample_mapper.set_alternate_dataset( samples, comparison_dataset_sample_id_column ) ;\n\t\tm_alt_dataset_snps = snps ;\n\t\tm_relative_phase.setZero( m_sample_mapper.sample_mapping().size() ) ;\n\t}\n\n\tvoid CrossDataSetHaplotypeComparisonComputation::operator()(\n\t\tVariantIdentifyingData const& snp,\n\t\tGenotypes const&,\n\t\tPloidy const&,\n\t\tgenfile::VariantDataReader& data_reader,\n\t\tResultCallback callback\n\t) {\n\t\tusing genfile::string_utils::to_string ;\n\t\tVariantIdentifyingData alt_snp ;\n\t\tgenfile::MissingValue const NA ;\n\t\tif( m_alt_dataset_snps->get_next_snp_matching( &alt_snp, snp, m_comparer )) {\n\t\t\t{\n\t\t\t\tgenfile::vcf::PhasedGenotypeSetter< Eigen::MatrixXd > setter( m_haplotypes1, m_nonmissingness1 ) ;\n\t\t\t\tdata_reader.get( \":genotypes:\", setter ) ;\n\t\t\t}\n\t\t\t{\n\t\t\t\tdouble A_coding = 0 ;\n\t\t\t\tdouble B_coding = 1 ;\n\t\t\t\tbool matching_alleles = true ;\n\t\t\t\tif( m_match_alleles ) {\n\t\t\t\t\tif( alt_snp.get_allele(0) == snp.get_allele(0) && alt_snp.get_allele(1) == snp.get_allele(1) ) {\n\t\t\t\t\t\tA_coding = 0 ;\n\t\t\t\t\t\tB_coding = 1 ;\n\t\t\t\t\t}\n\t\t\t\t\telse if( alt_snp.get_allele(0) == snp.get_allele(1) && alt_snp.get_allele(1) == snp.get_allele(0) ) {\n\t\t\t\t\t\tA_coding = 1 ;\n\t\t\t\t\t\tB_coding = 0 ;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatching_alleles = false ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgenfile::vcf::PhasedGenotypeSetter< Eigen::MatrixXd > setter( m_haplotypes2, m_nonmissingness2, 0, A_coding, B_coding ) ;\n\t\t\t\tm_alt_dataset_snps->read_variant_data()->get( \":genotypes:\", setter ) ;\n\n\t\t\t\tif( !matching_alleles ) {\n\t\t\t\t\tcallback( \"comment\", \"Alleles in main and comparison datasets do not match.\" ) ;\n\t\t\t\t\t// alleles don't match, don't  bother doing any computation.\n\t\t\t\t\treturn ;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcallback( \"compared_variant_rsid\", alt_snp.get_primary_id() ) ;\n\t\t\tcallback( \"compared_variant_alleleA\", alt_snp.get_allele(0) ) ;\n\t\t\tcallback( \"compared_variant_alleleB\", alt_snp.get_allele(1) ) ;\n\n\t\t\tcallback( \"pairwise_non-missing_haplotypes\", NA ) ;\n\t\t\tcallback( \"pairwise_concordant_haplotypes\", NA ) ;\n\t\t\tcallback( \"concordant_heterozygous_haplotypes\", NA ) ;\n\t\t\tcallback( \"concordant_heterozygous_haplotypes_with_switch_error\", NA ) ;\n\t\t\t// Threshhold the calls and set to missing any rows not meeting the\n\t\t\t// threshhold.\n\t\t\tm_haplotypes1.array() *= ( m_haplotypes1.array() >= m_call_threshhold ).cast< double >() ; \n\t\t\tm_haplotypes2.array() *= ( m_haplotypes2.array() >= m_call_threshhold ).cast< double >() ; \n\n\t\t\t// FIX MISSINGNESS HERE\n\n\t\t\tCrossDataSetSampleMapper::SampleMapping::const_iterator i = m_sample_mapper.sample_mapping().begin() ;\n\t\t\tCrossDataSetSampleMapper::SampleMapping::const_iterator const end_i = m_sample_mapper.sample_mapping().end() ;\n\t\t\tint call_count = 0 ;\n\t\t\tint concordant_call_count = 0 ;\n\t\t\tint het_call_count = 0 ;\n\t\t\tint switch_error_count = 0 ;\n\t\t\tfor( std::size_t count = 0; i != end_i; ++i, ++count ) {\n\t\t\t\tstd::string const stub = (\n\t\t\t\t\tm_sample_mapper.dataset1_sample_ids()[ i->first ].as< std::string >()\n\t\t\t\t\t+ \"(\"\n\t\t\t\t\t+ to_string( i->first + 1 )\n\t\t\t\t\t+ \"~\"\n\t\t\t\t\t+ to_string( i->second + 1 )\n\t\t\t\t\t+ \")\"\n\t\t\t\t) ;\n\n\t\t\t\tif( m_nonmissingness1.row( i->first ).sum() == 2 && m_nonmissingness2.row( i->second ).sum() == 2 ) {\n\t\t\t\t\t++call_count ;\n\n\t\t\t\t\tEigen::MatrixXd::RowXpr const& h1 = m_haplotypes1.row( i->first ) ;\n\t\t\t\t\tEigen::MatrixXd::RowXpr const& h2 = m_haplotypes2.row( i->second ) ;\n\t\t\t\t\tint const concordant = ( h1.sum() == h2.sum() ) ;\n\t\t\t\t\tcallback( stub + \":concordance\", concordant ) ;\n\t\t\t\t\tconcordant_call_count += concordant ;\n\t\t\t\t\t\n\t\t\t\t\tint const heterozygote = ( h1.sum() == 1 ) ;\n\t\t\t\t\thet_call_count += heterozygote ;\n\t\t\t\t\tif( concordant && heterozygote ) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tint const relative_phase = ( h1 == h2 ) ? 1 : -1 ;\n\t\t\t\t\t\tint const switch_error = ( m_relative_phase( count ) != 0 ) && ( m_relative_phase( count ) != relative_phase ) ;\n\t\t\t\t\t\tcallback( stub + \":switch_error\", switch_error ) ;\n\t\t\t\t\t\t// take account of the switch for the next SNP.\n\t\t\t\t\t\tm_relative_phase( count ) = relative_phase ;\n\t\t\t\t\t\tswitch_error_count += switch_error ;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcallback( stub + \":switch_error\", genfile::MissingValue() ) ;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcallback( stub + \":concordance\", genfile::MissingValue() ) ;\n\t\t\t\t\tcallback( stub + \":switch_error\", genfile::MissingValue() ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcallback( \"pairwise_non-missing_haplotypes\", call_count ) ;\n\t\t\tcallback( \"pairwise_concordant_haplotypes\", concordant_call_count ) ;\n\t\t\tcallback( \"concordant_heterozygous_haplotypes\", het_call_count ) ;\n\t\t\tcallback( \"concordant_heterozygous_haplotypes_with_switch_error\", switch_error_count ) ;\n\t\t}\n\t}\n\n\tstd::string CrossDataSetHaplotypeComparisonComputation::get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\treturn prefix + \"CrossDataSetHaplotypeComparisonComputation\" ;\n\t}\n}\n\n", "meta": {"hexsha": "435b786b566015411c4c2cca37ee5d60c3f4c798", "size": 6126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/src/CrossDataSetHaplotypeComparisonComputation.cpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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": "components/SNPSummaryComponent/src/CrossDataSetHaplotypeComparisonComputation.cpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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": "components/SNPSummaryComponent/src/CrossDataSetHaplotypeComparisonComputation.cpp", "max_forks_repo_name": "CreRecombinase/qctool", "max_forks_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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.5225806452, "max_line_length": 131, "alphanum_fraction": 0.7022526934, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17170341810869513}}
{"text": "#include <avalon/physics/utils.h>\n\n#include <boost/any.hpp>\n#include <avalon/physics/Box2dContainer.h>\n\nnamespace {\n\nstd::shared_ptr<b2PolygonShape> initRectangleShape(float width, float height, float pixelsInMeter)\n{\n    auto shape = std::make_shared<b2PolygonShape>();\n    shape->SetAsBox((width / pixelsInMeter) * 0.5f, (height / pixelsInMeter) * 0.5f);\n    return shape;\n}\n\nstd::shared_ptr<b2ChainShape> initChainShape(const cocos2d::ValueVector& points, float pixelsInMeter, bool loop = false)\n{\n    auto convert = [&pixelsInMeter](const cocos2d::Value& value) -> b2Vec2 {\n        return {value.asValueMap().at(\"x\").asFloat() / pixelsInMeter, (value.asValueMap().at(\"y\").asFloat() / pixelsInMeter) * -1};\n    };\n\n    std::vector<b2Vec2> vecs;\n    vecs.reserve(points.size());\n    std::transform(points.begin(), points.end(), vecs.begin(), convert);\n\n    auto shape = std::make_shared<b2ChainShape>();\n    if (loop) {\n        shape->CreateLoop(&vecs[0], points.size());\n    } else {\n        shape->CreateChain(&vecs[0], points.size());\n    }\n\n    return shape;\n}\n\nstd::shared_ptr<b2EdgeShape> initEdgeShape(cocos2d::Point p1, cocos2d::Point p2, float pixelsInMeter)\n{\n    p1 = p1 / pixelsInMeter;\n    p2 = p2 / pixelsInMeter;\n    auto shape = std::make_shared<b2EdgeShape>();\n    shape->Set({p1.x, p1.y}, {p2.x, p2.y});\n    return shape;\n}\n\nstd::shared_ptr<b2Shape> initShapeFromPoints(const cocos2d::ValueVector& points, float pixelsInMeter, bool loop = false)\n{\n    if (points.size() == 2) {\n        cocos2d::Point p1 {points.front().asValueMap().at(\"x\").asFloat(), points.front().asValueMap().at(\"y\").asFloat()};\n        cocos2d::Point p2 {points.back().asValueMap().at(\"x\").asFloat(), points.back().asValueMap().at(\"y\").asFloat()};\n        return initEdgeShape(p1, p2, pixelsInMeter);\n    } else {\n        return initChainShape(points, pixelsInMeter, loop);\n    }\n}\n\n} // namespace\n\nnamespace avalon {\nnamespace physics {\nnamespace utils {\n\nb2BodyType getBodyTypeFromString(const std::string& type)\n{\n    if      (type == \"static\")    return b2_staticBody;\n    else if (type == \"dynamic\")   return b2_dynamicBody;\n    else if (type == \"kinematic\") return b2_kinematicBody;\n    else                          throw new std::invalid_argument(\"Unknown box2d type\");\n}\n\navalon::io::TiledMapLoader::Callback rectLoader(b2Filter filter, bool isSensor, float rectWidth, float rectHeight)\n{\n    return [filter, isSensor, rectWidth, rectHeight](const avalon::io::TiledMapLoader::Configuration& config)\n    {\n        auto rWidth = rectWidth;\n        auto rHeight = rectHeight;\n\n        if (rWidth == 0) rWidth = config.map.getTileSize().width;\n\n        if (rHeight == 0) rHeight = config.map.getTileSize().height;\n\n        auto fixtureDef = config.box2dContainer->defaultFixtureDef;\n\n        fixtureDef.isSensor = isSensor;\n        fixtureDef.filter = filter;\n\n        float x = config.settings.at(\"x\").asFloat();\n        float y = config.settings.at(\"y\").asFloat();\n        const float width = rWidth / config.box2dContainer->pixelsInMeter;\n        const float height = rHeight / config.box2dContainer->pixelsInMeter;\n\n        y = (config.map.getMapSize().height - (y));\n\n        x = (x + 0.5) * config.map.getTileSize().width;\n        y = y * config.map.getTileSize().height - config.map.getTileSize().height / 2.f;\n\n        const auto pos = config.box2dContainer->convertToBox2d({static_cast<float>(x), static_cast<float>(y)});\n\n        std::shared_ptr<b2PolygonShape> polygonShape = std::make_shared<b2PolygonShape>();\n        polygonShape->SetAsBox(width / 2.f, height / 2.f);\n\n        b2BodyDef bodyDef;\n        bodyDef.type = b2_staticBody;\n        bodyDef.position.Set(pos.x, pos.y);\n\n        fixtureDef.shape = polygonShape.get();\n\n        auto body = config.box2dContainer->getWorld().CreateBody(&bodyDef);\n        body->CreateFixture(&fixtureDef);\n    };\n}\n\navalon::io::TiledMapLoader::Callback shapeLoader(int filterCategory, bool isSensor)\n{\n    return [filterCategory, isSensor](const avalon::io::TiledMapLoader::Configuration& config)\n    {\n        const float x = config.settings.at(\"x\").asFloat();\n        const float y = config.settings.at(\"y\").asFloat();\n        const float width = config.settings.at(\"width\").asFloat();\n        const float height = config.settings.at(\"height\").asFloat();\n        const float pixelsInMeter = config.box2dContainer->pixelsInMeter;\n        const auto pos = config.box2dContainer->convertToBox2d({static_cast<float>(x + width * 0.5), static_cast<float>(y + height * 0.5)});\n\n        auto fixtureDef = config.box2dContainer->defaultFixtureDef;\n        fixtureDef.isSensor = isSensor;\n        fixtureDef.filter.categoryBits = filterCategory;\n\n        std::string bodytype = \"static\";\n        if (config.settings.count(\"friction\"))          fixtureDef.friction = config.settings.at(\"friction\").asFloat();\n        if (config.settings.count(\"density\"))           fixtureDef.density = config.settings.at(\"density\").asFloat();\n        if (config.settings.count(\"restitution\"))       fixtureDef.restitution = config.settings.at(\"restitution\").asFloat();\n        if (config.settings.count(\"bodytype\"))          bodytype = config.settings.at(\"bodytype\").asString();\n        if (config.settings.count(\"filterCategory\"))    fixtureDef.filter.categoryBits = config.settings.at(\"filterCategory\").asInt();\n\n        std::shared_ptr<b2Shape> shape;\n        if (config.settings.count(\"polylinePoints\")) {\n            auto points = config.settings.at(\"polylinePoints\").asValueVector();\n            shape = initShapeFromPoints(points, pixelsInMeter);\n        } else if (config.settings.count(\"points\") > 0) {\n            auto points = config.settings.at(\"points\").asValueVector();\n            shape = initShapeFromPoints(points, pixelsInMeter, true);\n        } else {\n            cocos2d::log(\"%f,%f,%f,%f\",x,y,width,height);\n            shape = initRectangleShape(width, height, pixelsInMeter);\n        }\n        fixtureDef.shape = shape.get();\n\n        b2BodyDef bodyDef;\n        bodyDef.type = getBodyTypeFromString(bodytype);\n        bodyDef.position.Set(pos.x, pos.y);\n\n        auto body = config.box2dContainer->getWorld().CreateBody(&bodyDef);\n        body->CreateFixture(&fixtureDef);\n    };\n}\n\n} // namespace utils\n} // namespace physics\n} // namespace avalon\n", "meta": {"hexsha": "74a49bec74a68397805b910e9d38a3f863887757", "size": 6297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avalon/physics/utils.cpp", "max_stars_repo_name": "michaelcontento/avalon", "max_stars_repo_head_hexsha": "9207fbe2b3be61050794eca123303f56a08930db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2015-02-20T07:20:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T02:57:47.000Z", "max_issues_repo_path": "avalon/physics/utils.cpp", "max_issues_repo_name": "michaelcontento/avalon", "max_issues_repo_head_hexsha": "9207fbe2b3be61050794eca123303f56a08930db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-09-20T09:07:29.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-22T13:52:56.000Z", "max_forks_repo_path": "avalon/physics/utils.cpp", "max_forks_repo_name": "michaelcontento/avalon", "max_forks_repo_head_hexsha": "9207fbe2b3be61050794eca123303f56a08930db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T12:30:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T18:46:45.000Z", "avg_line_length": 39.8544303797, "max_line_length": 140, "alphanum_fraction": 0.6563442909, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.1717034075783548}}
{"text": "#include \"FWCore/ServiceRegistry/interface/Service.h\"\n#include \"CondCore/DBOutputService/interface/PoolDBOutputService.h\"\n#include \"CondFormats/Calibration/interface/mySiStripNoises.h\"\n\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include \"writeBlob.h\"\n\ntypedef boost::minstd_rand base_generator_type;\nwriteBlob::writeBlob(const edm::ParameterSet& iConfig):\n  m_StripRecordName(\"mySiStripNoisesRcd\")\n{\n}\n\nwriteBlob::~writeBlob()\n{\n  std::cout<<\"writeBlob::writeBlob\"<<std::endl;\n}\n\nvoid\nwriteBlob::analyze( const edm::Event& evt, const edm::EventSetup& evtSetup)\n{\n  std::cout<<\"writeBlob::analyze \"<<std::endl;\n  base_generator_type rng(42u);\n  boost::uniform_real<> uni_dist(0,1);\n  boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(rng, uni_dist);\n  edm::Service<cond::service::PoolDBOutputService> mydbservice;\n  if( !mydbservice.isAvailable() ){\n    std::cout<<\"db service unavailable\"<<std::endl;\n    return;\n  }\n  try{\n    mySiStripNoises* me = new mySiStripNoises;\n    unsigned int detidseed=1234;\n    unsigned int bsize=100;\n    unsigned int nAPV=2;\n    for (uint32_t detid=detidseed;detid<(detidseed+bsize);detid++){\n      //Generate Noise for det detid\n      std::vector<short> theSiStripVector;\n      for(unsigned int strip=0; strip<128*nAPV; ++strip){\n\tfloat noise = uni();;      \n\tme->setData(noise,theSiStripVector);\n      }\n      me->put(detid,theSiStripVector);\n    }\n\n    mydbservice->writeOne(me,mydbservice->currentTime(),m_StripRecordName);\n  }catch(const cond::Exception& er){\n    throw cms::Exception(\"DBOutputServiceUnitTestFailure\",\"failed writeBlob\",er);\n    //std::cout<<er.what()<<std::endl;\n  }catch(const cms::Exception& er){\n    throw cms::Exception(\"DBOutputServiceUnitTestFailure\",\"failed writeBlob\",er);\n  }/*catch(const std::exception& er){\n    std::cout<<\"caught std::exception \"<<er.what()<<std::endl;\n  }catch(...){\n    std::cout<<\"Funny error\"<<std::endl;\n    }*/\n}\n#include \"FWCore/Framework/interface/MakerMacros.h\"\nDEFINE_FWK_MODULE(writeBlob);\n", "meta": {"hexsha": "8164b18fa129a7113292443dd28f77226f1f0253", "size": 2104, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CondCore/DBOutputService/test/stubs/writeBlob.cc", "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": "CondCore/DBOutputService/test/stubs/writeBlob.cc", "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": "CondCore/DBOutputService/test/stubs/writeBlob.cc", "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": 33.3968253968, "max_line_length": 92, "alphanum_fraction": 0.7186311787, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.1716795814581572}}
{"text": "/*\n   Copyright 2016 Mitchell Young\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#pragma once\n\n#include <memory>\n\n#include <Eigen/Sparse>\n\n#include \"util/global_config.hpp\"\n#include \"util/timers.hpp\"\n#include \"coarse_data.hpp\"\n#include \"eigen_interface.hpp\"\n#include \"mesh.hpp\"\n#include \"source_isotropic.hpp\"\n#include \"xs_mesh_homogenized.hpp\"\n\nnamespace mocc {\nclass CMFD : public HasOutput {\npublic:\n    CMFD(const pugi::xml_node &input, const CoreMesh *mesh,\n         SP_XSMeshHomogenized_t xsmesh);\n\n    /**\n     * \\brief Solve the CMFD system\n     *\n     * \\param [in,out] k the initial guess to use for the system eigenvalue.\n     * Updated byt the solve.\n     */\n    void solve(real_t &k);\n\n    /**\n     * \\brief Return a pointer to the coarse data.\n     *\n     * This is used to couple sweepers and other objects that need access to\n     * the coarse data to the CMFD solver.\n     */\n    CoarseData *get_data()\n    {\n        return &coarse_data_;\n    }\n\n    /**\n     * \\brief Return a reference to the \\ref CoarseData object.\n     */\n    CoarseData &coarse_data()\n    {\n        return coarse_data_;\n    }\n\n    /**\n     * \\brief Return a reference to the MG flux.\n     */\n    const ArrayB2 &flux() const\n    {\n        return coarse_data_.flux;\n    }\n\n    /**\n     * \\brief Return whether the CMFD object is meant to actually do a\n     * solve.\n     *\n     * It is possible to need a CMFD object to be constructed to use its\n     * \\ref CoarseData and other functionality, but not want to perform\n     * actual CMFD solves.\n     */\n    bool is_enabled() const\n    {\n        return is_enabled_;\n    }\n\n    /**\n     * \\brief Set the eigenvalue convergence tolerance\n     */\n    void set_k_tolerance(real_t tol)\n    {\n        assert(tol > REAL_FUZZ);\n\n        k_tol_ = tol;\n        return;\n    }\n\n    /**\n     * \\brief Set the fission source convergence tolerance\n     */\n    void set_psi_tolerance(real_t tol)\n    {\n        assert(tol > REAL_FUZZ);\n\n        psi_tol_ = tol;\n        return;\n    }\n\n    void output(H5Node &node) const;\n\nprivate:\n    // Private methods\n    /**\n     * \\brief Compute and return the L-2 norm of the residual of the CMFD\n     * system, scaled by the size of the system.\n     *\n     * This calculates the residual of the CMFD system, considering all groups.\n     * Since this implementation of the method must calculate the source for all\n     * groups and needs to do repeated copies of the flux, it is somewhat more\n     * expensive than the single-group implementation, which assumes that the\n     * source is already calculated. As a result this is useful for calculating\n     * the initial residual at the beginning of the CMFD solve, while the other\n     * is more ideal for calculating the residual for each iteration.\n     *\n     * \\pre The group-independent fission source has been calculated and stored\n     * in \\c fs_.\n     *\n     * \\sa CMFD::residual(int)\n     */\n    real_t residual();\n\n    /**\n     * \\brief Compute and return the squared L-2 norm of the residual for a\n     * single group of the CMFD system\n     *\n     * \\param group the group for which to calculate residual\n     *\n     * This is similar to the all-group method, but it only computes the\n     * contribution to the residual for the requested group. It assumes that the\n     * source (right-hand side) has already been computed and is therefore\n     * cheaper to use for assessing convergence.\n     *\n     * Unlike \\ref CMFD::residual(), this returns an un-scaled, squared L-2\n     * norm. This should lead to the following code producing the same result as\n     * the group-independent \\ref CMFD::residual() method:\n     * \\code\nnorm = 0.0;\nfor(int ig=0; ig<n_group_; ig++) {\n    // Satisfy preconditions\n    norm += this->residual(group);\n}\nnorm = std::sqrt(norm)/(n_cell_*n_group_);\n     * \\endcode\n     *\n     * \\pre The group-independent fission source has been calculated and stored\n     * in \\c fs_.\n     *\n     * \\pre The source (fission and inscattering) must be calculated for the\n     * current group.\n     *\n     * \\pre The current-group flux is already stored in the \\c x_ vector\n     *\n     * \\sa CMFD::residual()\n     */\n    real_t residual(int group) const;\n    real_t solve_1g(int group);\n    void fission_source(real_t k);\n    void print(int iter, real_t k, real_t k_err, real_t psi_err,\n               real_t resid_ratio);\n\n    /**\n     * \\brief Calculate CMFD-derived currents after a CMFD solve and store\n     * on the \\ref CoarseData.\n     *\n     * After performing a CMFD solve, it is useful to have access to the\n     * state of the current, as predicted by the CMFD system given the\n     * current state of the D-hats. This allows us to calculate, for\n     * instance, transverse leakage for an MoC sweeper, which otherwise\n     * wouldn't know what the current looks like in the axial dimension.\n     */\n    void store_currents();\n\n    /**\n     * Set up the linear systems for each group. This doesnt need to be done\n     * for each iteration, nor in the case of non-zero currents/d-hat terms\n     * can it, since the flux is allowed to change, which in turn will\n     * affect the new D-hats. While this conusmes more memory to store the\n     * systems for each group, it should be faster.\n     */\n    void setup_solve();\n    real_t total_fission();\n\n    // Private data\n    Timer &timer_;\n    Timer &timer_init_;\n    Timer &timer_setup_;\n    Timer &timer_solve_;\n\n    Mesh mesh_;\n    const Mesh *fine_mesh_;\n    XSMeshHomogenized xsmesh_;\n    int n_cell_;\n    int n_surf_;\n    int n_group_;\n    CoarseData coarse_data_;\n    // Scratch space for manipulating currents on the CMFD mesh\n    ArrayB1 current_1g_;\n    bool is_enabled_;\n\n    // Single-group fission source\n    ArrayB1 fs_;\n    ArrayB1 fs_old_;\n\n    // Single-group flux result from LS solve, also used for initial guess\n    VectorX x_;\n\n    SourceIsotropic source_;\n\n    // Vector of one-group sparse matrix\n    std::vector<Eigen::SparseMatrix<real_t>> m_;\n\n    // Vector of BiCGSTAB objects.\n    std::vector<Eigen::BiCGSTAB<Eigen::SparseMatrix<real_t>>> solvers_;\n\n    // Surface quantities. We need to keep these around to do the current\n    // update without having to recalculate. Based on profiling, might be\n    // nice to still get these on the fly to save on memory, but this is\n    // fine for now.\n    ArrayB2 d_hat_;\n    ArrayB2 d_tilde_;\n    ArrayB2 s_hat_;\n    ArrayB2 s_tilde_;\n\n    // Number of times solve() has been called\n    int n_solve_;\n\n    // Convergence options\n    real_t k_tol_;\n    real_t psi_tol_;\n    real_t resid_reduction_;\n    int max_iter_;\n\n    // Other options\n    bool zero_fixup_;\n    bool dump_current_;\n};\ntypedef std::unique_ptr<CMFD> UP_CMFD_t;\n}\n", "meta": {"hexsha": "939a4594c8b5ae39cd9d1546f8aa03cd25fa243e", "size": 7204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/cmfd.hpp", "max_stars_repo_name": "tp-ntouran/mocc", "max_stars_repo_head_hexsha": "77d386cdf341b1a860599ff7c6e4017d46e0b102", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T17:46:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T01:07:56.000Z", "max_issues_repo_path": "src/core/cmfd.hpp", "max_issues_repo_name": "tp-ntouran/mocc", "max_issues_repo_head_hexsha": "77d386cdf341b1a860599ff7c6e4017d46e0b102", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-04T16:40:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-16T22:22:54.000Z", "max_forks_repo_path": "src/core/cmfd.hpp", "max_forks_repo_name": "tp-ntouran/mocc", "max_forks_repo_head_hexsha": "77d386cdf341b1a860599ff7c6e4017d46e0b102", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-16T22:20:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T11:59:03.000Z", "avg_line_length": 29.1659919028, "max_line_length": 80, "alphanum_fraction": 0.6599111605, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17167957807146184}}
{"text": "#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <string>\n#include <pcl/io/boost.h>\n#include <pcl/io/pcd_io.h>\n#include <Eigen/Dense>\n#include <pcl/registration/icp.h>\n#include <pcl/registration/ndt.h>\n#include <pcl/filters/approximate_voxel_grid.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/registration/icp_nl.h>\n#include <pcl/search/organized.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/features/normal_3d_omp.h>\n#include <pcl/filters/conditional_removal.h>\n#include <pcl/features/fpfh.h>\n#include \"DoNFilter.hpp\"\n#include \"CubeAligner.hpp\"\n#include \"mapgmuutils.hpp\"\n\n#ifndef TRANSFORMER_H\n#define TRANSFORMER_H\n\nusing namespace pcl;\nusing namespace std;\n\ntypedef pcl::PointXYZI PointType;\ntypedef PointCloud<pcl::PointXYZI> Cloud;\ntypedef PointCloud<pcl::PointXYZI>::Ptr CloudPtr;\ntypedef pcl::PointNormal PointNormalT;\ntypedef pcl::PointCloud<PointNormalT> PointCloudWithNormals;\ntypedef pcl::PointCloud<PointNormalT>::Ptr PointCloudWithNormalsPtr;\ntypedef pcl::KdTreeFLANN<PointType> TreeType;\ntypedef TreeType::Ptr TreePtr;\n\nclass MyPointRepresentation : public pcl::PointRepresentation <PointNormalT>\n{\n  using pcl::PointRepresentation<PointNormalT>::nr_dimensions_;\n\npublic:\n\n  MyPointRepresentation ()\n  {\n    // Define the number of dimensions\n    nr_dimensions_ = 4;\n  }\n\n  // Override the copyToFloatArray method to define our feature vector\n  virtual inline void copyToFloatArray (const PointNormalT &p, float * out) const\n  {\n    // < x, y, z, curvature >\n    out[0] = p.x;\n    out[1] = p.y;\n    out[2] = p.z;\n    out[3] = p.curvature;\n  }\n};\n\nclass Transformer\n{\npublic:\n\n  inline double getFitness(CloudPtr base, CloudPtr toAlign, Eigen::Matrix4f mat)\n  {\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n\n    icp.setMaxCorrespondenceDistance (0.5);\n    icp.setMaximumIterations (0);\n\n    icp.setInputSource(toAlign);\n    icp.setInputTarget(base);\n    icp.align(Final);\n    return icp.getFitnessScore();\n  }\n\n  inline Eigen::Matrix4f getCubeTransform(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t  double cSize, double *eVal)\n  {\n    Eigen::Matrix4f baseTrans = Eigen::Matrix4f::Identity();\n    CloudPtr copyCloud(new Cloud);\n    CubeAligner cb(base,cSize);\n    *copyCloud += *toAlign;\n    cb.filterCloudCubic(copyCloud);\n\n    return cb.alignToMatrix(baseTrans,copyCloud,eVal);\n  }\n\n  inline Eigen::Matrix4f getCubeICPTransform(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t     double cSize, double *eVal)\n  {\n    Eigen::Matrix4f tmpTrans;\n    Eigen::Matrix4f baseTrans = Eigen::Matrix4f::Identity();\n\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    CloudPtr copyCloud(new Cloud);\n    int maxIter = 100;\n    double eps = 1e-8;\n\n    CubeAligner cb(base,cSize);\n\n    *copyCloud += *toAlign;\n    cb.filterCloudCubic(copyCloud);\n\n    //binary cube alignment using cubic filtered toAlign\n    tmpTrans =  cb.alignToMatrix(baseTrans,copyCloud,eVal);\n\n    //scale added for tuning, not necessary\n    icp.setMaxCorrespondenceDistance (cSize*2.0);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n\n    //icp using the filtered copyCloud\n    icp.setInputSource(copyCloud);\n    icp.setInputTarget(base);\n    icp.align(Final,tmpTrans);\n\n    return icp.getFinalTransformation();\n  }\n\n  //assumes gpsGuess already identity, sets the translation values\n  inline void calcGpsGuess(Eigen::Matrix4f& lastTrans,mapgmu::PathFinder *pf,\n\t\t\t   double currTime, double dt, Eigen::Matrix4f& gpsGuess)\n  {\n    Vector3f rotOffset;\n    //create gps estimate, store in 4x4 matrix\n    rotOffset =  lastTrans.block(0,0,3,3).transpose()*pf->getDeltaForTime(currTime,dt);\n    gpsGuess(0,3)=rotOffset(0);\n    gpsGuess(1,3)=rotOffset(1);\n    gpsGuess(2,3)=rotOffset(2);\n  }\n\n  inline Eigen::Matrix4f getGpsIcpNoCubeTransform(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t  Eigen::Matrix4f trans,\n\t\t\t\t\t  mapgmu::PathFinder *pf, double *cSize,\n\t\t\t\t\t  double currTime, double dt)\n  {\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp2;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    int maxIter = 50;\n    double eps = 1e-8;\n    double eVal = *cSize*2.0;\n\n    Matrix4f gpsGuess = Matrix4f::Identity();\n    Matrix4f transMat;\n\n    calcGpsGuess(trans,pf,currTime,dt,gpsGuess);\n\n    //icp pass 1\n    icp.setMaxCorrespondenceDistance (eVal);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(toAlign);\n    icp.setInputTarget(base);\n    icp.align(Final,gpsGuess);\n\n    transMat =  icp.getFinalTransformation();\n\n    Final.clear();\n\n    //icp pass 2, smaller corr, higher euclid fitness\n    icp2.setMaxCorrespondenceDistance (*cSize/15.0);\n    icp2.setMaximumIterations (maxIter);\n    icp2.setEuclideanFitnessEpsilon (eps*10);\n    icp2.setInputSource(toAlign);\n    icp2.setInputTarget(base);\n    icp2.align(Final,transMat);\n\n    transMat = icp2.getFinalTransformation();\n\n    return transMat;\n  }\n\n  inline Eigen::Matrix4f getGpsIcpTransform(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t  Eigen::Matrix4f trans,\n\t\t\t\t\t  mapgmu::PathFinder *pf, double *cSize,\n\t\t\t\t\t  double currTime, double dt)\n  {\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp2;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    CloudPtr copyCloud(new Cloud);\n    int maxIter = 50;\n    double eps = 1e-8;\n    double eVal = *cSize*2.0;\n\n    Vector3f rotOffset;\n    Matrix4f gpsGuess = Matrix4f::Identity();\n    Matrix4f transMat;\n    CubeAligner cb(base,*cSize);\n\n    *copyCloud += *toAlign;\n    cb.filterCloudCubic(copyCloud);\n\n    calcGpsGuess(trans,pf,currTime,dt,gpsGuess);\n\n    CVertex c1(gpsGuess);\n\n    //first pass icp, filtered copyCloud used\n    icp.setMaxCorrespondenceDistance (eVal);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(copyCloud);\n    icp.setInputTarget(base);\n    icp.align(Final,gpsGuess);\n\n    transMat =  icp.getFinalTransformation();\n\n    Final.clear();\n\n    //second pass icp, full toAlign cloud used, smalled corr, higher euc\n    icp2.setMaxCorrespondenceDistance (*cSize/15.0);\n    icp2.setMaximumIterations (maxIter);\n    icp2.setEuclideanFitnessEpsilon (eps*10);\n    icp2.setInputSource(toAlign);\n    icp2.setInputTarget(base);\n    icp2.align(Final,transMat);\n\n    transMat = icp2.getFinalTransformation();\n\n    //uncomment for distance/metric calculations\n    /*CVertex c2(transMat);\n    CVertex c3 = c2-c1;\n\n    std::cout << \"Cube: \" << *cSize << std::endl\n\t\t<< \"Conv: \" << eVal << std::endl\n\t\t<< \"Converged: \" << icp2.hasConverged () << std::endl\n\t\t<< \"Fitness: \" << icp2.getFitnessScore () << std::endl\n\t\t<< \"Vexp: \" << c1.getDist() << std::endl\n\t\t<< \"Vfit: \" << c2.getDist() << std::endl\n\t\t<< \"PathDist: \" << c3.getDist()  << std::endl;*/\n\n    return transMat;\n  }\n\n  inline Eigen::Matrix4f getGpsIcpCubeTransform(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t  Eigen::Matrix4f trans,\n\t\t\t\t\t  mapgmu::PathFinder *pf, double *cSize,\n\t\t\t\t\t  double *eVal, double currTime, double dt)\n  {\n    Eigen::Matrix4f tmpTrans;\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    CloudPtr copyCloud(new Cloud);\n    int maxIter = 50;\n    double eps = 1e-6;\n\n    Vector3f rotOffset;\n    Matrix4f gpsGuess = Matrix4f::Identity();\n    CubeAligner cb(base,*cSize);\n\n    *copyCloud += *toAlign;\n    cb.filterCloudCubic(copyCloud);\n\n    calcGpsGuess(trans,pf,currTime,dt,gpsGuess);\n\n    //icp pass\n    icp.setMaxCorrespondenceDistance (*cSize);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(copyCloud);\n    icp.setInputTarget(base);\n    icp.align(Final,gpsGuess);\n\n    std::cout << \"Converged: \" << icp.hasConverged () << std::endl\n\t\t<< \"Fitness: \" << icp.getFitnessScore () << std::endl;\n\n    tmpTrans = icp.getFinalTransformation();\n\n    //cubic alignment\n    return cb.alignToMatrix(tmpTrans,toAlign,eVal);\n  }\n\n  inline Eigen::Matrix4f getCubeGpsIcpTransform(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t  Eigen::Matrix4f trans,\n\t\t\t\t\t  mapgmu::PathFinder *pf, double *cSize,\n\t\t\t\t\t  double *eVal, double currTime, double dt)\n  {\n    Eigen::Matrix4f tmpTrans;\n\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp2;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    CloudPtr copyCloud(new Cloud);\n    int maxIter = 100;\n    double eps = 1e-8;\n\n    Vector3f rotOffset;\n    Matrix4f gpsGuess = Matrix4f::Identity();\n    Matrix4f transMat;\n    CubeAligner cb(base,*cSize);\n\n    *copyCloud += *toAlign;\n    cb.filterCloudCubic(copyCloud);\n\n    calcGpsGuess(trans,pf,currTime,dt,gpsGuess);\n\n    tmpTrans =  cb.alignToMatrix(gpsGuess,copyCloud,eVal);\n\n    //icp pass one, filtered copyCloud\n    icp.setMaxCorrespondenceDistance (*cSize*2.0);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(copyCloud);\n    icp.setInputTarget(base);\n    icp.align(Final,tmpTrans);\n\n    transMat = icp.getFinalTransformation();\n\n    Final.clear();\n\n    //icp pass two full toAlign cloud\n    icp2.setMaxCorrespondenceDistance (*cSize/15.0);\n    icp2.setMaximumIterations (maxIter);\n    icp2.setEuclideanFitnessEpsilon (eps*100);\n    icp2.setInputSource(toAlign);\n    icp2.setInputTarget(base);\n    icp2.align(Final,transMat);\n\n    transMat = icp2.getFinalTransformation();\n\n    //attempts at dynamically updating eVal\n    /* *eVal = (*eVal + cb.getNextEval(&gpsGuess,&tmpTrans))/2.0;\n    if (*eVal < 0.05) *eVal = 0.05;\n\n    std::cout << \"New EVAL \" << *eVal << std::endl;\n\n    std::cout << \"Converged: \" << icp.hasConverged () << std::endl\n\t\t<< \"Fitness: \" << icp.getFitnessScore () << std::endl;*/\n\n    return transMat;\n  }\n\n  inline Eigen::Matrix4f getCubeGpsIcpTransformAdapt(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t  Eigen::Matrix4f trans,\n\t\t\t\t\t  mapgmu::PathFinder *pf, CVertex lastVel,\n\t\t\t\t\t  double currTime, double dt)\n  {\n    Eigen::Matrix4f cubeTrans;\n    Eigen::Vector3f vel = pf->getDeltaForTime(currTime,dt);\n\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp2;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    CloudPtr copyCloud(new Cloud);\n    int maxIter = 100;\n    double eps = 1e-8;\n\n    Vector3f rotOffset;\n\n    Matrix4f transMat;\n    double cSize;\n    double eVal;\n\n    Matrix4f gpsGuess = Matrix4f::Identity();\n    calcGpsGuess(trans,pf,currTime,dt,gpsGuess);\n\n    cSize = vel.norm();\n    if (lastVel.getDist()>0)\n    {\n      cSize += lastVel.getDist();\n      cSize /= 2.0;\n    }\n\n    if (cSize > 0.45)cSize = 0.45;\n    if (cSize < 0.05)cSize = 0.05;\n\n    eVal = cSize / 2.0;\n\n    CubeAligner cb(base,cSize);\n\n    *copyCloud += *toAlign;\n    cb.filterCloudCubic(copyCloud);\n\n    //cube alignment with gps guess seed\n    cubeTrans =  cb.alignToMatrix(gpsGuess,copyCloud,&eVal);\n\n    //icp pass one with cube alignment seed, filtered copyCloud\n    icp.setMaxCorrespondenceDistance (cSize*1.33);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(copyCloud);\n    icp.setInputTarget(base);\n    icp.align(Final,cubeTrans);\n\n    transMat = icp.getFinalTransformation();\n\n    Final.clear();\n\n    //icp pass two full toAlign cloud\n    icp2.setMaxCorrespondenceDistance (cSize/10.0);\n    icp2.setMaximumIterations (maxIter/5.0);\n    icp2.setEuclideanFitnessEpsilon (eps*100);\n    icp2.setInputSource(toAlign);\n    icp2.setInputTarget(base);\n    icp2.align(Final,transMat);\n\n    transMat = icp2.getFinalTransformation();\n\n    return transMat;\n  }\n\n  inline Eigen::Matrix4f getCubeGpsTransform(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t  Eigen::Matrix4f trans,\n\t\t\t\t\t  mapgmu::PathFinder *pf, double *cSize,\n\t\t\t\t\t  double *eVal, double currTime, double dt)\n  {\n    CubeAligner cb(base,*cSize);\n\n    Matrix4f gpsGuess = Matrix4f::Identity();\n    calcGpsGuess(trans,pf,currTime,dt,gpsGuess);\n\n    CVertex rv(gpsGuess);\n    *eVal = rv.getDist();\n\n    return cb.alignToMatrix(gpsGuess,toAlign,eVal);\n  }\n\n  //Tranlation only GPS velocity vector transforms\n  inline Eigen::Matrix4f getGpsTransform(Eigen::Matrix4f trans,\n\t\t\t\t\t  mapgmu::PathFinder *pf,\n\t\t\t\t\t  double currTime, double dt)\n  {\n    Matrix4f gpsGuess = Matrix4f::Identity();\n    calcGpsGuess(trans,pf,currTime,dt,gpsGuess);\n\n    return gpsGuess;\n  }\n\n  //simple ICP method\n  inline Eigen::Matrix4f getICPTransform(CloudPtr base, CloudPtr toAlign)\n  {\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    int maxIter = 50;\n    double eps = 1e-6;\n    double eVal = 1.0;\n\n    icp.setMaxCorrespondenceDistance (eVal);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(toAlign);\n    icp.setInputTarget(base);\n    icp.align(Final);\n\n    return icp.getFinalTransformation();\n  }\n\n  //Intensity filtered two pass ICP trans\n  inline Eigen::Matrix4f getICPVoxTransform(CloudPtr base, CloudPtr toAlign)\n  {\n    pcl::IterativeClosestPoint<PointType, PointType> icp;\n    pcl::VoxelGrid<PointType> voxGrid;\n    CloudPtr voxBase (new Cloud);\n    CloudPtr voxAlign (new Cloud);\n    Cloud Final;\n    double maxCorrDist = 0.2;\n    int maxIter = 50;\n    double eps = 1e-8;\n    double leafSize = 0.1;\n\n    char *corr,*epsC, *leafStr;\n\n    corr = getenv(\"CORR_DIST\");\n    epsC = getenv(\"CONV_EPS\");\n    leafStr = getenv(\"LEAF_SIZE\");\n    if (corr)\n    {\n      maxCorrDist = atof(corr);\n    }\n    if (epsC)\n    {\n      eps = atof(epsC);\n    }\n    if (leafStr)\n    {\n      leafSize = atof(leafStr);\n    }\n\n    voxGrid.setLeafSize(leafSize,leafSize,leafSize);\n    voxGrid.setInputCloud(base);\n    voxGrid.filter(*voxBase);\n    voxGrid.setInputCloud(toAlign);\n    voxGrid.filter(*voxAlign);\n\n    //icp pass, both source and dest voxel filtered\n    icp.setMaxCorrespondenceDistance (maxCorrDist);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(voxAlign);\n    icp.setInputTarget(voxBase);\n    icp.align(Final);\n\n    std::cout << maxCorrDist << \",\" << eps << \",\" << icp.getFitnessScore () << \",\" << icp.hasConverged () << \",\";\n\n    return icp.getFinalTransformation();\n  }\n\n  // used to determine next single step ICP where [last] is the last alignment\n  inline Eigen::Matrix4f getNextICPStep(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\tEigen::Matrix4f last)\n  {\n    pcl::IterativeClosestPoint<PointType, PointType> icp;\n    pcl::VoxelGrid<PointType> voxGrid;\n    Cloud Final;\n    double maxCorrDist = 0.3;\n    double eps = 1e-8;\n\n    char *corr,*epsC;\n\n    corr = getenv(\"CORR_DIST\");\n    epsC = getenv(\"CONV_EPS\");\n    if (corr)\n    {\n      maxCorrDist = atof(corr);\n    }\n    if (epsC)\n    {\n      eps = atof(epsC);\n    }\n\n    icp.setMaxCorrespondenceDistance (maxCorrDist);\n    icp.setMaximumIterations (1);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(toAlign);\n    icp.setInputTarget(base);\n    icp.align(Final,last);\n\n    std::cout << \"ICP Converged:\" << icp.hasConverged () << std::endl\n\t<< \"Fitness: \" << icp.getFitnessScore () << std::endl\n\t<< \"EucFit Eps: \" << icp.getEuclideanFitnessEpsilon () << std::endl;\n\n    return icp.getFinalTransformation();\n  }\n\n\n  //regular icp transform using \"guess\" to seed the transform\n  inline Eigen::Matrix4f getICPTransformGuess(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t      Eigen::Matrix4f guess,\n\t\t\t\t\t      double maxCorrDist)\n  {\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    int maxIter = 50;\n    double eps = 1e-6;\n\n    icp.setMaxCorrespondenceDistance (maxCorrDist);\n    icp.setMaximumIterations (maxIter);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(toAlign);\n    icp.setInputTarget(base);\n    icp.align(Final, guess);\n\n    std::cout << \"Converged: \" << icp.hasConverged () << std::endl\n\t\t<< \"Fitness: \" << icp.getFitnessScore () << std::endl;\n\n    return icp.getFinalTransformation();\n  }\n\n  inline Eigen::Matrix4f getICPIntTransform(CloudPtr base, CloudPtr toAlign)\n  {\n    pcl::IterativeClosestPoint<PointType, PointType> icp;\n    CloudPtr filter_base(new Cloud);\n    CloudPtr filter_toAlign(new Cloud);\n    Cloud Final;\n    Eigen::Matrix4f intensityMat = Eigen::Matrix4f::Identity();\n    double maxCorrDist = 2.0;\n    double eps = 1e-8;\n    DoNFilter<PointType> donFilter;\n\n    char *corr,*epsC;\n\n    corr = getenv(\"CORR_DIST\");\n    epsC = getenv(\"CONV_EPS\");\n    if (corr)\n    {\n      maxCorrDist = atof(corr);\n    }\n    if (epsC)\n    {\n      eps = atof(epsC);\n    }\n\n    //filter by intensity, see DoNFilter.hpp\n    donFilter.intensityFilter(1.2,base,filter_base);\n    donFilter.intensityFilter(1.2,toAlign,filter_toAlign);\n\n    //icp pass 1, use filtered clouds\n    icp.setMaxCorrespondenceDistance (maxCorrDist);\n    icp.setMaximumIterations (50);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(filter_toAlign);\n    icp.setInputTarget(filter_base);\n    icp.align(Final);\n\n    intensityMat = icp.getFinalTransformation();\n\n    //icp pass 2, use full clouds\n    icp.setMaxCorrespondenceDistance (0.1);\n    icp.setInputSource(toAlign);\n    icp.setInputTarget(base);\n    icp.align(Final,intensityMat);\n\n    std::cout << maxCorrDist << \",\" << eps << \",\" << icp.getFitnessScore () << \",\" << icp.hasConverged () << \",\";\n\n    return icp.getFinalTransformation();\n  }\n\n  //this was from the PCL site, may work if tweaked, never bother to fix it\n  /*inline Eigen::Matrix4f getICPFPFHTransform(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\t\t      Eigen::Matrix4f guess)\n  {\n    pcl::IterativeClosestPoint<PointNormalT, PointNormalT> icp;\n    PointCloudWithNormalsPtr filter_base(new PointCloudWithNormals);\n    PointCloudWithNormalsPtr filter_toAlign(new PointCloudWithNormals);\n    pcl::PointCloud<PointNormalT> Final;\n\n    pcl::NormalEstimation<PointType, PointNormalT> norm_est;\n    pcl::search::KdTree<PointType>::Ptr tree (new pcl::search::KdTree<PointType> ());\n    norm_est.setSearchMethod (tree);\n    norm_est.setRadiusSearch (0.1);\n\n    norm_est.setInputCloud (base);\n    norm_est.compute (*filter_base);\n    pcl::copyPointCloud (*base, *filter_base);\n\n    norm_est.setInputCloud (toAlign);\n    norm_est.compute (*filter_toAlign);\n    pcl::copyPointCloud (*toAlign, *filter_toAlign);\n\n    pcl::FPFHEstimation<PointType, pcl::Normal, pcl::FPFHSignature33> fpfh;\n    // alternatively, if cloud is of tpe PointNormal, do fpfh.setInputNormals (cloud);\n\n    fpfh.setSearchMethod (tree);\n\n    // Output datasets\n    pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs_base (new pcl::PointCloud<pcl::FPFHSignature33> ());\n    pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs_toAlign (new pcl::PointCloud<pcl::FPFHSignature33> ());\n\n    // Use all neighbors in a sphere of radius 5cm\n    // IMPORTANT: the radius used here has to be larger than the radius used to estimate the surface normals!!!\n    fpfh.setRadiusSearch (0.2);\n\n    // Compute the features\n    //fpfh.setInputCloud (base);\n    fpfh.setInputNormals (filter_base);\n    fpfh.compute (*fpfhs_base);\n    //fpfh.setInputCloud (toAlign);\n    fpfh.setInputNormals (filter_toAlign);\n    fpfh.compute (*fpfhs_toAlign);\n\n    icp.setMaxCorrespondenceDistance (maxCorrDist);\n    // Set the maximum number of iterations (criterion 1)\n    icp.setMaximumIterations (maxIter);\n    // Set the transformation epsilon (criterion 2)\n    icp.setEuclideanFitnessEpsilon (eps);\n\n    icp.setInputSource(filter_toAlign);\n    icp.setInputTarget(filter_base);\n    icp.align(Final,guess);\n\n    std::cout << \"Converged: \" << icp.hasConverged () << std::endl\n\t\t<< \"Fitness: \" << icp.getFitnessScore () << std::endl;\n\n    return icp.getFinalTransformation();\n    return Eigen::Matrix4f::Identity();\n  }*/\n\n  inline Eigen::Matrix4f getICPDoNTransform(CloudPtr base, CloudPtr toAlign)\n  {\n    pcl::IterativeClosestPoint<PointNormalT, PointNormalT> icp;\n    PointCloudWithNormalsPtr filter_base(new PointCloudWithNormals);\n    PointCloudWithNormalsPtr filter_toAlign(new PointCloudWithNormals);\n    pcl::PointCloud<PointNormalT> Final;\n    double maxCorrDist = 2.0;\n    double eps = 1e-8;\n    DoNFilter<PointType> donFilter;\n\n    char *corr,*epsC;\n\n    corr = getenv(\"CORR_DIST\");\n    epsC = getenv(\"CONV_EPS\");\n    if (corr)\n    {\n      maxCorrDist = atof(corr);\n    }\n    if (epsC)\n    {\n      eps = atof(epsC);\n    }\n\n    donFilter.filter(base,filter_base);\n    donFilter.filter(toAlign,filter_toAlign);\n\n    //icp with both source and dest don filtered\n    icp.setMaxCorrespondenceDistance (maxCorrDist);\n    icp.setMaximumIterations (150);\n    icp.setEuclideanFitnessEpsilon (eps);\n    icp.setInputSource(filter_toAlign);\n    icp.setInputTarget(filter_base);\n    icp.align(Final);\n\n    std::cout << maxCorrDist << \",\" << eps << \",\" << icp.getFitnessScore () << \",\" << icp.hasConverged () << \",\";\n\n    return icp.getFinalTransformation();\n  }\n\n  //one step DoN, not efficient since DoN filtering is done on each step\n  inline Eigen::Matrix4f getNextDoNStep(CloudPtr base, CloudPtr toAlign,\n\t\t\t\t\tEigen::Matrix4f last)\n  {\n    pcl::IterativeClosestPoint<PointNormalT, PointNormalT> icp;\n    PointCloudWithNormalsPtr filter_base(new PointCloudWithNormals);\n    PointCloudWithNormalsPtr filter_toAlign(new PointCloudWithNormals);\n    pcl::PointCloud<PointNormalT> Final;\n    double maxCorrDist = 0.3;\n    int maxIter = 1;\n    double eps = 1e-8;\n    DoNFilter<PointType> donFilter;\n\n    char *corr,*epsC;\n\n    corr = getenv(\"CORR_DIST\");\n    epsC = getenv(\"CONV_EPS\");\n    if (corr)\n    {\n      maxCorrDist = atof(corr);\n    }\n    if (epsC)\n    {\n      eps = atof(epsC);\n    }\n\n    donFilter.filter(base,filter_base);\n    donFilter.filter(toAlign,filter_toAlign);\n\n    icp.setMaxCorrespondenceDistance (maxCorrDist);\n    icp.setMaximumIterations (maxIter);\n    icp.setTransformationEpsilon (eps);\n    icp.setInputSource(filter_toAlign);\n    icp.setInputTarget(filter_base);\n    icp.align(Final,last);\n\n    std::cout << \"ICP DoN Converged:\" << icp.hasConverged () << std::endl\n\t<< \"Fitness: \" << icp.getFitnessScore () << std::endl\n\t<< \"EucFit Eps: \" << icp.getEuclideanFitnessEpsilon () << std::endl;\n\n    return icp.getFinalTransformation();\n  }\n\n  inline Eigen::Matrix4f getNDTDoNTransform(CloudPtr base, CloudPtr toAlign)\n  {\n    PointCloudWithNormalsPtr filter_base(new PointCloudWithNormals);\n    PointCloudWithNormalsPtr filter_toAlign(new PointCloudWithNormals);\n    pcl::PointCloud<PointNormalT> Final;\n\n    DoNFilter<PointType> donFilter;\n\n    char *stepSzC,*iter,*epsC,*resC;\n    double stepSize = 0.1;\n    int maxIter = 35;\n    double eps = 0.01;\n    double resolution = 1.0;\n\n    stepSzC = getenv(\"STEP_SIZE\");\n    iter = getenv(\"MAX_ITER\");\n    epsC = getenv(\"CONV_EPS\");\n    resC = getenv(\"NDT_RES\");\n    if (resC)\n    {\n      resolution = atof(resC);\n    }\n    if (stepSzC)\n    {\n      stepSize = atof(stepSzC);\n    }\n    if (iter)\n    {\n      maxIter =atoi(iter);\n    }\n    if (epsC)\n    {\n      eps = atof(epsC);\n    }\n\n    donFilter.filter(base,filter_base);\n    donFilter.filter(toAlign,filter_toAlign);\n\n     // Initializing Normal Distributions Transform (NDT).\n    pcl::NormalDistributionsTransform<PointNormalT, PointNormalT> ndt;\n\n    // Setting scale dependent NDT parameters\n    // Setting minimum transformation difference for termination condition.\n    ndt.setEuclideanFitnessEpsilon (eps);\n    // Setting maximum step size for More-Thuente line search.\n    ndt.setStepSize (stepSize);\n    //Setting Resolution of NDT grid structure (VoxelGridCovariance).\n    ndt.setResolution (resolution);\n\n    // Setting max number of registration iterations.\n    ndt.setMaximumIterations (maxIter);\n\n    // Setting point cloud to be aligned.\n    ndt.setInputSource (filter_toAlign);\n    // Setting point cloud to be aligned to.\n    ndt.setInputTarget (filter_base);\n\n    ndt.align (Final);\n\n    std::cout << \"0\" << \",\" << eps << \",\" << ndt.getFitnessScore () << \",\" << ndt.hasConverged () << \",\";\n\n    return ndt.getFinalTransformation();\n  }\n\n  //adaptive correlation distances, not fully implemented to match:\n  //Registration of point clouds using sample-sphere and adaptive distance restriction\n  //DOI\t 10.1007/s00371-011-0580-0\n  inline Eigen::Matrix4f getICPAdaptTransform(CloudPtr base, CloudPtr toAlign)\n  {\n    pcl::IterativeClosestPoint<pcl::PointXYZI, pcl::PointXYZI> icp;\n    pcl::PointCloud<pcl::PointXYZI> Final;\n    Eigen::Matrix4f trans = Eigen::Matrix4f::Identity();\n    double r_start = 1.0;\n    double r_stop = 0.1;\n    double r_scale = 0.75;\n    double r;\n\n    cout << \"Warning ADAPT method not fully implemented\\n\";\n\n    r = r_start;\n    while (r > r_stop)\n    {\n      icp.setMaxCorrespondenceDistance (r);\n      icp.setMaximumIterations (2);\n      icp.setTransformationEpsilon (1e-10);\n      icp.setInputSource(toAlign);\n      icp.setInputTarget(base);\n      icp.align(Final,trans);\n\n      trans = icp.getFinalTransformation()*trans;\n      r = r*r_scale;\n      cout << \"Step @ r=\" << r <<\"\\n\";\n    }\n\n    std::cout << \"Converged: \" << icp.hasConverged () << std::endl\n\t\t<< \"Fitness: \" << icp.getFitnessScore () << std::endl;\n\n    return trans;\n  }\n\n  inline Eigen::Matrix4f getNDTTransform(CloudPtr base, CloudPtr toAlign)\n  {\n    // Filtering input scan to roughly 10% of original size to increase speed of registration.\n    pcl::PointCloud<pcl::PointXYZI>::Ptr filtered_cloud (new pcl::PointCloud<pcl::PointXYZI>);\n\n    char *stepSzC,*iter,*epsC,*resC;\n    double stepSize = 0.1;\n    int maxIter = 35;\n    double eps = 0.01;\n    double resolution = 1.0;\n\n    stepSzC = getenv(\"STEP_SIZE\");\n    iter = getenv(\"MAX_ITER\");\n    epsC = getenv(\"CONV_EPS\");\n    resC = getenv(\"NDT_RES\");\n    if (resC)\n    {\n      resolution = atof(resC);\n    }\n    if (stepSzC)\n    {\n      stepSize = atof(stepSzC);\n    }\n    if (iter)\n    {\n      maxIter =atoi(iter);\n    }\n    if (epsC)\n    {\n      eps = atof(epsC);\n    }\n\n    // Initializing Normal Distributions Transform (NDT).\n    pcl::NormalDistributionsTransform<pcl::PointXYZI, pcl::PointXYZI> ndt;\n\n    // Setting scale dependent NDT parameters\n    // Setting minimum transformation difference for termination condition.\n    ndt.setEuclideanFitnessEpsilon (eps);\n    // Setting maximum step size for More-Thuente line search.\n    ndt.setStepSize (stepSize);\n    //Setting Resolution of NDT grid structure (VoxelGridCovariance).\n    ndt.setResolution (resolution);\n\n    // Setting max number of registration iterations.\n    ndt.setMaximumIterations (maxIter);\n\n    // Setting point cloud to be aligned.\n    ndt.setInputSource (toAlign);\n    // Setting point cloud to be aligned to.\n    ndt.setInputTarget (base);\n\n    // Calculating required rigid transform to align the input cloud to the target cloud.\n    pcl::PointCloud<pcl::PointXYZI>::Ptr output_cloud (new pcl::PointCloud<pcl::PointXYZI>);\n    ndt.align (*output_cloud);\n\n    std::cout << \"0\" << \",\" << eps << \",\" << ndt.getFitnessScore () << \",\" << ndt.hasConverged () << \",\";\n\n    return ndt.getFinalTransformation();\n  }\n\n  //this is ICP_NL_NORM??\n  inline Eigen::Matrix4f getPairTransform(CloudPtr base, CloudPtr toAlign)\n  {\n    CloudPtr src (new Cloud);\n    CloudPtr tgt (new Cloud);\n    pcl::ApproximateVoxelGrid<PointType> grid;\n\n    double leafSize = 0.05;\n    int kNorms = 10;\n    char *leafStr,*kNStr,*corr,*iter,*epsC;\n    double maxCorrDist = 0.5;\n    int maxIter = 40;\n    double eps = 1e-8;\n\n    corr = getenv(\"CORR_DIST\");\n    iter = getenv(\"MAX_ITER\");\n    epsC = getenv(\"CONV_EPS\");\n    leafStr = getenv(\"LEAF_SIZE\");\n    kNStr = getenv(\"K_NORMS\");\n    if (corr)\n    {\n      maxCorrDist = atof(corr);\n    }\n    if (iter)\n    {\n      maxIter =atoi(iter);\n    }\n    if (epsC)\n    {\n      eps = atof(epsC);\n    }\n    if (leafStr)\n    {\n      leafSize = atof(leafStr);\n    }\n    if (kNStr)\n    {\n      kNorms = atoi(kNStr);\n    }\n\n    grid.setLeafSize (leafSize,leafSize,leafSize);\n    grid.setInputCloud (base);\n    grid.filter (*src);\n\n    grid.setInputCloud (toAlign);\n    grid.filter (*tgt);\n\n    // Compute surface normals and curvature\n    PointCloudWithNormals::Ptr points_with_normals_src (new PointCloudWithNormals);\n    PointCloudWithNormals::Ptr points_with_normals_tgt (new PointCloudWithNormals);\n    PointCloudWithNormals::Ptr reg_result (new PointCloudWithNormals);\n\n    pcl::NormalEstimation<PointType, PointNormalT> norm_est;\n    pcl::search::KdTree<PointType>::Ptr tree (new pcl::search::KdTree<PointType> ());\n    norm_est.setSearchMethod (tree);\n    norm_est.setKSearch (kNorms);\n\n    norm_est.setInputCloud (src);\n    norm_est.compute (*points_with_normals_src);\n    pcl::copyPointCloud (*src, *points_with_normals_src);\n\n    norm_est.setInputCloud (tgt);\n    norm_est.compute (*points_with_normals_tgt);\n    pcl::copyPointCloud (*tgt, *points_with_normals_tgt);\n\n    //\n    // Instantiate our custom point representation (defined above) ...\n    MyPointRepresentation point_representation;\n    // ... and weight the 'curvature' dimension so that it is balanced against x, y, and z\n    float alpha[4] = {1.0, 1.0, 1.0, 1.0};\n    point_representation.setRescaleValues (alpha);\n\n    //\n    // Align\n    pcl::IterativeClosestPointNonLinear<PointNormalT, PointNormalT> reg;\n    reg.setEuclideanFitnessEpsilon (eps);\n    // Set the maximum distance between two correspondences (src<->tgt) to 10cm\n    // Note: adjust this based on the size of your datasets\n    reg.setMaxCorrespondenceDistance (maxCorrDist);\n    // Set the point representation\n    reg.setPointRepresentation (boost::make_shared<const MyPointRepresentation> (point_representation));\n\n    reg.setInputSource (points_with_normals_src);\n    reg.setInputTarget (points_with_normals_tgt);\n\n    // Run the same optimization in a loop and visualize the results\n    reg.setMaximumIterations (maxIter);\n\n    // Estimate\n    reg.align (*reg_result);\n\n    std::cout << maxCorrDist << \",\" << eps << \",\" << reg.getFitnessScore () << \",\" << reg.hasConverged () << \",\";\n\n    // Get the transformation from target to source\n    return reg.getFinalTransformation();\n  }\n\n};\n\n#endif\n", "meta": {"hexsha": "41fe43ed5e77ca74e7026b1f375da065b12694bc", "size": 30257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Transformer.hpp", "max_stars_repo_name": "jmlien/mapgmu", "max_stars_repo_head_hexsha": "b4b5eb42e876530e52217191d7980720302522d0", "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": "Transformer.hpp", "max_issues_repo_name": "jmlien/mapgmu", "max_issues_repo_head_hexsha": "b4b5eb42e876530e52217191d7980720302522d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Transformer.hpp", "max_forks_repo_name": "jmlien/mapgmu", "max_forks_repo_head_hexsha": "b4b5eb42e876530e52217191d7980720302522d0", "max_forks_repo_licenses": ["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.8687068115, "max_line_length": 113, "alphanum_fraction": 0.6822222957, "num_tokens": 8488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17167957633458308}}
{"text": "#include \"cliquesolver/algorithms/algorithms.hpp\"\n\n#include <boost/program_options.hpp>\n\nusing namespace cliquesolver;\nnamespace po = boost::program_options;\n\nOutput cliquesolver::run(\n        std::string algorithm,\n        const Instance& instance,\n        std::mt19937_64& generator,\n        optimizationtools::Info info)\n{\n    (void)generator;\n\n    std::vector<std::string> algorithm_args = po::split_unix(algorithm);\n    std::vector<char*> algorithm_argv;\n    for (Counter i = 0; i < (Counter)algorithm_args.size(); ++i)\n        algorithm_argv.push_back(const_cast<char*>(algorithm_args[i].c_str()));\n\n    if (algorithm.empty() || algorithm_args[0].empty()) {\n        std::cerr << \"\\033[32m\" << \"ERROR, missing algorithm.\" << \"\\033[0m\" << std::endl;\n        return Output(instance, info);\n\n    } else if (algorithm_args[0] == \"greedy_gwmin\") {\n        return greedy_gwmin(instance, info);\n    } else if (algorithm_args[0] == \"greedy_strong\") {\n        return greedy_strong(instance, info);\n\n#if CPLEX_FOUND\n    } else if (algorithm_args[0] == \"milp_cplex\") {\n        MilpCplexOptionalParameters parameters;\n        parameters.info = info;\n        return milp_cplex(instance, parameters);\n#endif\n\n    } else {\n        std::cerr << \"\\033[31m\" << \"ERROR, unknown algorithm: \" << algorithm_argv[0] << \"\\033[0m\" << std::endl;\n        assert(false);\n        return Output(instance, info);\n    }\n}\n\n", "meta": {"hexsha": "aadd6fbfd4fda73f3b53ff8ae7547807a9006068", "size": 1396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cliquesolver/algorithms/algorithms.cpp", "max_stars_repo_name": "fontanf/stablesolver", "max_stars_repo_head_hexsha": "9d957f2ec6a2e5008cec305b53478afe30c141c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-10T01:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T12:11:52.000Z", "max_issues_repo_path": "cliquesolver/algorithms/algorithms.cpp", "max_issues_repo_name": "fontanf/stablesolver", "max_issues_repo_head_hexsha": "9d957f2ec6a2e5008cec305b53478afe30c141c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cliquesolver/algorithms/algorithms.cpp", "max_forks_repo_name": "fontanf/stablesolver", "max_forks_repo_head_hexsha": "9d957f2ec6a2e5008cec305b53478afe30c141c1", "max_forks_repo_licenses": ["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.7272727273, "max_line_length": 111, "alphanum_fraction": 0.6425501433, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.17167097741600243}}
{"text": "\ufeff#include <stdio.h>\n\n#include <iostream>\n#include <string>\n\n#define  BOOST_VARIANT_USE_RELAXED_GET_BY_DEFAULT\n\n#include <boost/variant/recursive_variant.hpp>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/get.hpp>\n\n#include <QString>\n#include <QVariant>\n#include <QMessageBox>\n#include <QDebug>\n\nconst int cmd_invalid     = 0;\nconst int cmd_assign      = 1;  // var = 12\nconst int cmd_assign_plus = 2;  // var = 12 + 44\nconst int cmd_assign_new  = 3;  // var = new ...\n\nenum SymbolType_ {\n    NoError,\n    Undefined,\n    NumberError,\n    EndOfText\n};\nSymbolType_ SymbolType;\n\n// ------------------------------------------------------\n// namespace to avoid conflicts with other frameworks ...\n// ------------------------------------------------------\nnamespace kallup\n{\n    int line_no  = 1;\n    int file_eof = 0;\n    int last_op  = 0;\n\n    QString number, ident;\n\n    int    m_pos = 0; // buffer position\n    char * m_TextBuffer;    // the source code buffer\n    double value = 0.00;    // math\n\n    struct add_ { };\n    struct sub_ { };\n    struct mul_ { };\n    struct div_ { };\n\n    struct expr   { };\n    struct sconst { };\n    struct mconst { };\n\n    template <typename OpTag1> struct binary_op;\n\n    class expression_wrapper { public:\n          expression_wrapper() { }\n\n        typedef boost::variant<\n          double\n        , std::string\n\n        , boost::recursive_wrapper< binary_op<add_> >\n        , boost::recursive_wrapper< binary_op<sub_> >\n        , boost::recursive_wrapper< binary_op<mul_> >\n        , boost::recursive_wrapper< binary_op<div_> >\n\n        > expression;\n\n\n        expression_wrapper::expression operator = (TypeDouble<int> const &val) {\n            std::cout << \"assiggnn\" << std::endl;\n        }\n    };\n\n    template <typename OpTag1>\n    struct binary_op\n    {\n        expression_wrapper::expression * left ;\n        expression_wrapper::expression * right;\n\n        binary_op() { }\n        binary_op(double val1, double val2) {\n            double res = val1 * val2;\n            value = res;\n        }\n\n        binary_op(expression_wrapper::expression &exp, double val) {\n            auto *left  = new expression_wrapper::expression;\n            auto *right = new expression_wrapper::expression;\n\n            left  = value;\n            right = val;\n\n            std::cout << \"L:   \" << left  << std::endl;\n            std::cout << \"R:   \" << right << std::endl;\n            std::cout << \"val: \" << val << std::endl;\n            exp = val;\n        }\n        binary_op(double val, expression_wrapper::expression &exp) {\n            auto *left  = new expression_wrapper::expression;\n            auto *right = new expression_wrapper::expression;\n\n            //left  = val;\n            //right = value;\n\n            std::cout << \"L2:   \" << left  << std::endl;\n            std::cout << \"R2:   \" << right << std::endl;\n            std::cout << \"val2: \" << val << std::endl;\n            //value = boost::get<double>(left);\n            exp   = value;\n        }\n\n        void get(binary_op<mul_> &obj) {\n            auto *left  = new expression_wrapper::expression;\n            auto *right = new expression_wrapper::expression;\n\n            std::cout << \"pp: \" << std::endl;\n            left  = obj.left;\n            right = obj.right;\n        }\n\n        binary_op(expression_wrapper::expression &lhs) {\n            auto *left  = new expression_wrapper::expression;\n            auto *right = new expression_wrapper::expression;\n\n            left = lhs;\n            std::cout << \"popser: \" << /*boost::get<double>(left) <<*/ std::endl;\n        }\n\n        binary_op(expression_wrapper::expression *&obj) {\n\n        }\n\n        binary_op(\n              expression_wrapper::expression & lhs,\n              expression_wrapper::expression & rhs)\n            : left(lhs), right(rhs)\n        {\n        }\n\n        binary_op(binary_op<mul_> *mul, double val)\n        {\n            auto *left  = new expression_wrapper::expression;\n            auto *right = new expression_wrapper::expression;\n\n            std::cout << \"mexter\" << std::endl;\n            left  = mul;\n            right = val;\n        }\n\n        binary_op(const binary_op<sub_> &bo)   {\n            std::cout << \"subser: \" << bo.left ->type().name() << std::endl;\n            std::cout << \"subser: \" << bo.right->type().name() << std::endl;\n\n            double res2 = 1.2; //boost::get<double>(bo.right);\n            {\n                //auto *left  = new expression_wrapper::expression;\n                //auto *right = new expression_wrapper::expression;\n\n                value = value - res2;\n                //left  = value ;\n                std::cout << \"ein lefter: \" << value << std::endl;\n            }\n        }\n        binary_op(const binary_op<add_> &bo)   {\n\n        }\n        binary_op(const binary_op<mul_> &bo)   {\n            std::cout << \"mopser\" << std::endl;\n            //auto *left  = new expression_wrapper::expression;\n            //auto *right = new expression_wrapper::expression;\n\n            double l = 1; //boost::get<double>(bo.left );\n            double r = 2; //boost::get<double>(bo.right);\n            double s = r * l;\n\n            //left = value = s;\n\n            std::cout <<  \"multerL \" << l << std::endl;\n            std::cout <<  \"multerR \" << r << std::endl;\n            std::cout <<  \"multerS \" << s << std::endl;\n        }\n        binary_op(const binary_op<div_> &bo)   {\n        }\n    };\n\n    expression_wrapper::expression operator + (\n        expression_wrapper::expression &exp1,\n        expression_wrapper::expression &exp2)\n    {\n        std::cout << \"plus\" << std::endl;\n\n        return exp1;\n    }\n    expression_wrapper::expression& operator += (expression_wrapper::expression &exp, double val) {\n        expression_wrapper::expression tmp = val;\n        exp = exp + tmp;\n        return exp;\n    }\n\n    expression_wrapper::expression& operator - (expression_wrapper::expression& exp,\n                            const binary_op<sub_> &v) {\n        std::cout << \"minus\" << std::endl;\n        exp = boost::get<boost::recursive_wrapper<double>>(v.left)\n            - boost::get<boost::recursive_wrapper<double>>(v.right);\n        return exp;\n    }\n    expression_wrapper::expression& operator +=\n       (expression_wrapper::expression &exp1,\n        expression_wrapper::expression &exp2) {\n        exp1 = exp2;\n        return exp1;\n    }\n    expression_wrapper::expression& operator += (\n        expression_wrapper::expression &exp,\n        cmd_varset<TypeDouble<int> > &v) {\n        std::cout << \"molobster1\" << std::endl;\n        cmd_varset<TypeDouble<int> > tdp = v;\n        TypeDouble<int> td = tdp.value; //.value.value = v.value.value;\n        td.value = tdp.value.value;\n        double r = td.value;\n        std::cout << \"molobster2\" << std::endl;\n        std::cout << r  << std::endl;\n        value = r;\n        exp  += r;\n        return  exp;\n    }\n\n    expression_wrapper::expression& operator += (\n    expression_wrapper::expression& exp, const cmd_print<TypeDoublePrint<int> > &v) {\n        exp += v.getVal().value;\n        return exp;\n    }\n\n\n    class ast_struct: public boost::static_visitor<double> {\n    public:\n        double operator()(std::string txt) const {\n            std::cout << txt << std::endl;\n            return 123.42;\n        }\n        double operator()(const binary_op<add_> &obj) {\n\n        }\n        double operator()(double val) const {\n            std::cout << \"getter value01: \" << val << std::endl;\n            value = val;\n            //return boost::apply_visitor( ast_struct(), tdp.expr );\n            return  value;\n        }\n\n        double operator()(binary_op<add_> & binary) {\n            //return boost::apply_visitor( ast_struct(), binary.left )\n            //     + boost::apply_visitor( ast_struct(), binary.right);\n        }\n        double operator()(const binary_op<sub_> & binary) const     {\n            std::cout << \"double subserle\" << std::endl;\n            std::cout << boost::get<boost::recursive_wrapper<double>>(binary.left)  << std::endl;\n            std::cout << boost::get<boost::recursive_wrapper<double>>(binary.right) << std::endl;\n\n            return 2.2; //boost::apply_visitor( ast_struct(), binary.left );\n               //- boost::apply_visitor( ast_struct(), binary.right );\n        }\n        /*\n        double operator()(binary_op<mul_> &d0) {\n            std::cout << \"double:\" << std::endl;\n\n            expression_wrapper::expression d1; d1 = binary_op<mul_>(d0.left );\n            expression_wrapper::expression d2; d2 = binary_op<mul_>(d0.right);\n\n            expression_wrapper::expression d4; d4 = d1;\n\n            return boost::apply_visitor( ast_struct(), d1)\n                 * boost::apply_visitor( ast_struct(), d2);\n        }*/\n        /*\n        double operator()(binary_op<div_> & binary) {\n            //boost::recursive_wrapper<binary_op<div_>> tmp1; tmp1 = binary;\n            //auto d2 = binary_op<div_>(tmp1);\n\n            expression_wrapper::expression d1; d1 = binary_op<div_>(binary.left);\n            expression_wrapper::expression d2; d2 = binary_op<div_>(binary.right);\n\n            return boost::apply_visitor( ast_struct(), d1)\n                 / boost::apply_visitor( ast_struct(), d2);\n        }*/\n    };\n\n\n    std::ostream& operator << (std::ostream& os, const binary_op<add_> &val) {\n        os << \"adder\" << std::endl;\n        return os;\n    }\n    std::ostream& operator<< (std::ostream& os, const binary_op<sub_> &val) {\n        std::cout << \"subser\" << std::endl;\n        return os;\n    }\n    std::ostream& operator<< (std::ostream& os, binary_op<mul_> val_) {\n        os << \"muller\" << std::endl;\n        return os;\n    }\n    std::ostream& operator<< (std::ostream& os, const binary_op<div_> &val) {\n        os << \"diver\" << std::endl;\n        return os;\n    }\n\n    // ----------------------------------\n    // inline's, to reduce code size, and\n    // make code better in reading ...\n    // ----------------------------------\n    inline int get_ch() {\n        return m_TextBuffer[m_pos++];\n    }\n    inline void get_endl() {\n        int c;\n        while (1) {\n            c = get_ch();\n            if (c == '\\n') {\n                line_no++;\n                break;\n            }\n        }\n    }\n\n    bool TokenSkipper = false;  // ws each token?\n    // ------------------------------------\n    // cut spaces, and return next char ...\n    // ------------------------------------\n    void SkipWhiteSpaces()\n    {\n        int c = 0;\n        while (1) {\n            c = get_ch();\n            if (c == '&') {\n                c = get_ch();\n                if (c == '&') {\n                    get_endl();\n                    continue;\n                }   else break;\n            }\n            else if (c == '*') {\n                c = get_ch();\n                if (c == '*') {\n                    get_endl();\n                    continue;\n                }   else break;\n            }\n            else if (c == '/') {\n                c = get_ch();\n                if (c == '/') {\n                    get_endl();\n                    continue;\n                }\n                else if (c == '*') {\n                    while (1) {\n                        c = get_ch();\n                        if (c == '\\n')\n                        line_no++;\n                        else if (c == '*') {\n                            c = get_ch();\n                            if (c == '/')\n                            break;\n                        }\n                    }\n                    continue;\n                }\n                else {\n                    --m_pos;\n                    break;\n                }\n            }\n            else if (isspace(c)) {\n                if (c == '\\n')\n                line_no++;\n                continue;\n            }\n            break;\n        }\n        --m_pos;\n        return;\n    }\n\n    QString GetIdent()\n    {\n        SkipWhiteSpaces();\n        ident.clear();\n\n        int c = 0;\n        while (1) {\n            c = get_ch();\n            if (isalnum(c)) {\n                ident += c;\n            }\n            else if (c == '/') {\n                c = get_ch();\n                if (c == '/') {\n                    get_endl();\n                    continue;\n                }\n                else if (c == '*') {\n                    while (1) {\n                        c = get_ch();\n                        if (c == '\\n')\n                        line_no++;\n                        else if (c == '*') {\n                            c = get_ch();\n                            if (c == '/')\n                            break;\n                        }\n                    }\n                }\n                break;\n            }   else {\n                --m_pos;\n                break;\n            }\n        }\n\n        if (ident.length() < 1)\n        throw QString(\"Syntax Error - No data?\");\n\n        SkipWhiteSpaces();\n        return ident;\n    }\n\n    bool Match(char expected)\n    {\n        SkipWhiteSpaces();\n        if (m_TextBuffer[m_pos++] == expected) {\n            qDebug() << expected;\n            return true;\n        }\n        throw QString(\"Expected token '%1' at position: %2\")\n            .arg(expected)\n            .arg(m_pos);\n        return false;\n    }\n\n    QString GetNumber(void)\n    {\n        SkipWhiteSpaces();\n        number.clear();\n\n        while (1) {\n            int c = get_ch();\n            if (isdigit(c)) {\n                number += c;\n                continue;\n            }\n            else if (c == '.') {\n                number += '.';\n                continue;\n            }\n            else if (c == '/') {\n                c = get_ch();\n                if (c == '/') {\n                    get_endl();\n                    continue;\n                }\n                else if (c == '*') {\n                    while (1) {\n                        c = get_ch();\n                        if (c == '\\n')\n                        line_no++;\n                        else if (c == '*') {\n                            c = get_ch();\n                            if (c == '/')\n                            break;\n                        }\n                    }\n                }\n            }\n            else if (c == EOF || c == 0) {\n                if (number.size() > 0)\n                break ; else\n                throw QString(\"wrong token as excpected.\");\n            }\n            else if (isspace(c)) {\n                if (number.size() > 0)\n                break;\n                continue;\n            }\n            else {\n                throw QString(\"number expected, wrong type: >>%1<<\").arg(c);\n                break;\n            }\n        }\n        SkipWhiteSpaces();\n        return number;\n    }\n\n    template <typename T>\n    struct Token {\n        Token() {\n            qDebug() << \"new token\";\n        }\n    };\n\n    template < typename T >\n    struct Token<T*> {\n        Token(){ std::cout << \"A< T* >\" << std::endl; }\n    };\n\n    struct TokenTypeAssign { };\n    struct TokenTypeSpace  { };\n\n    struct bool_   { };\n    struct int_    { };\n    struct char_   { };\n    struct space_  { };\n    struct assign_ { };\n\n    template <> struct Token<TokenTypeAssign> {\n    public:\n        Token() {\n            name = QString(\"TokenTypeAssign\");\n            value = 0;\n        }\n        bool parse() {\n            if (!Match('='))\n            throw QString(\"ASSIGN SIGN '=' expected.\");\n            return true;\n        }\n        QVariant value;\n        QString  name;\n    };\n    template <> struct Token<TokenTypeSpace> {\n    public:\n        Token() {\n            name  = QString(\"TokenSpace\");\n            value = 0;\n        }\n        bool parse() {\n            qDebug() << \"parse space\";\n            SkipWhiteSpaces();\n            return true;\n        }\n        QVariant value;\n        QString  name;\n    };\n\n    template <> struct Token<bool> {\n    public:\n        Token() {\n            name  = QString(\"bool\");\n            value = static_cast<bool>(false);\n        }\n        QVariant value;\n        QString  name;\n    };\n\n    template <> struct Token<int> {\n    public:\n        Token() {\n            name  = QString(\"int\");\n            value = static_cast<int>(0);\n        }\n        bool parse() {\n            qDebug() << \"parse int\";\n            qDebug() << GetNumber();\n            return true;\n        }\n\n        QVariant value;\n        QString  name;\n    };\n\n    template <> struct Token<char> {\n    public:\n        Token() {\n            name  = QString(\"char\");\n            value = QString(\"\");\n        }\n        bool parse() {\n            qDebug() << \"parse char\";\n            qDebug() << GetIdent();\n            return true;\n        }\n\n        QVariant value;\n        QString  name;\n    };\n\n    Token<bool> bool_;\n    Token<int>  int_;\n    Token<char> char_;\n\n    Token<TokenTypeSpace> space_;\n    Token<TokenTypeAssign> assign_;\n\n    class ParserCommon {\n    public:\n        ParserCommon(QString src) {\n            m_TextBuffer = new char[src.size()+1];\n            strcpy(m_TextBuffer,src.toLatin1().data());\n        }\n        ~ParserCommon() {\n            delete m_TextBuffer;\n        }\n    };\n\n    // ------------------------------------\n    // wrapper class for token scanning ...\n    // ------------------------------------\n    class grammar {\n    public:\n        grammar() { }\n        template <typename T> grammar & operator << (T &t) { t.parse();return *this; }\n        template <typename T> grammar & operator +  (T &t) { t.parse();return *this; }\n    };\n\n    // -----------------------------------\n    // parser oode for an dBase parser ...\n    // -----------------------------------\n    class dBase {\n    public:\n        dBase() {\n            qDebug() << \"handle dbase grammar...\";\n        }\n        void start(QString src)  {\n            ParserCommon pc(src);\n            grammar go;\n\n            // grammar:\n            go +char_ << assign_ << int_;\n\n            // ---------------------------------\n            // sanity check, if all token read ?\n            // ---------------------------------\n            if (m_pos < strlen(m_TextBuffer))\n            throw QString(\"not all input are proceed.\");\n        }\n    };\n\n    template   <typename T>\n    class Parser: public T {\n    public:\n        Parser() {\n            qDebug() << \"parser init.\";\n            line_no = 1;\n            m_pos   = 0;\n\n            ident .clear();\n            number.clear();\n        }\n    };\n\n    void test()\n    {\n        expression_wrapper::expression res1 = binary_op<mul_>(2.0 ,5.0);\n        //expression_wrapper::expression res2 = binary_op<sub_>(3.0,res1);\n        expression_wrapper::expression result = ( res1 );\n\n        expression_wrapper::expression res3 = binary_op<add_>(21.13,0.00);\n\n        std::cout << std::endl\n                  << \"start visitor...\"\n                  << std::endl;\n        std::cout << boost::apply_visitor(ast_struct(),res3  ) << std::endl; std::cout << \"next...\\n\";\n        std::cout << boost::apply_visitor(ast_struct(),result) << std::endl;\n\n    }\n}\n\n// int main() {\nbool parseText(QString src)\n{\n    using namespace kallup;\n    kallup::test();\n    return true;\n    try {\n        Parser<dBase> p;\n        p.start(src);\n\n        QMessageBox::information(0,\"Info\",\"SUCCESS\");\n        return true;\n    }\n    catch (QString &e) {\n        QMessageBox::critical(0,\"Error\",\n        QString(\"Error in line: %1\\n%2\")\n        .arg(line_no)\n        .arg(e));\n    }\n    return false;\n}\n", "meta": {"hexsha": "b01e28aecd8728cc97c3a610de3a3b1117ac8307", "size": 19426, "ext": "cc", "lang": "C++", "max_stars_repo_path": "2.cc", "max_stars_repo_name": "paule32/keyBase", "max_stars_repo_head_hexsha": "34ac6700ea10872df74d8848412dfb5f134eb319", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-20T00:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T00:09:19.000Z", "max_issues_repo_path": "2.cc", "max_issues_repo_name": "paule32/keyBase", "max_issues_repo_head_hexsha": "34ac6700ea10872df74d8848412dfb5f134eb319", "max_issues_repo_licenses": ["MIT"], "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.cc", "max_forks_repo_name": "paule32/keyBase", "max_forks_repo_head_hexsha": "34ac6700ea10872df74d8848412dfb5f134eb319", "max_forks_repo_licenses": ["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.2765647744, "max_line_length": 102, "alphanum_fraction": 0.4453309997, "num_tokens": 4314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17167097394119268}}
{"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_ALGORITHMS_UNION_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_UNION_HPP\n\n\n#include <boost/mpl/if.hpp>\n\n#include <boost/range/metafunctions.hpp>\n\n#include <boost/geometry/core/is_areal.hpp>\n#include <boost/geometry/core/point_order.hpp>\n#include <boost/geometry/core/reverse_dispatch.hpp>\n#include <boost/geometry/geometries/concepts/check.hpp>\n#include <boost/geometry/algorithms/detail/overlay/overlay.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate\n<\n    // tag dispatching:\n    typename TagIn1, typename TagIn2, typename TagOut,\n    // metafunction finetuning helpers:\n    bool Areal1, bool Areal2, bool ArealOut,\n    // real types\n    typename Geometry1, typename Geometry2,\n    bool Reverse1, bool Reverse2, bool ReverseOut,\n    typename OutputIterator,\n    typename GeometryOut,\n    typename Strategy\n>\nstruct union_insert\n{\n    BOOST_MPL_ASSERT_MSG\n        (\n            false, NOT_OR_NOT_YET_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPES\n            , (types<Geometry1, Geometry2, GeometryOut>)\n        );\n};\n\n\ntemplate\n<\n    typename TagIn1, typename TagIn2, typename TagOut,\n    typename Geometry1, typename Geometry2,\n    bool Reverse1, bool Reverse2, bool ReverseOut,\n    typename OutputIterator,\n    typename GeometryOut,\n    typename Strategy\n>\nstruct union_insert\n    <\n        TagIn1, TagIn2, TagOut,\n        true, true, true,\n        Geometry1, Geometry2,\n        Reverse1, Reverse2, ReverseOut,\n        OutputIterator, GeometryOut,\n        Strategy\n    > : detail::overlay::overlay\n        <Geometry1, Geometry2, Reverse1, Reverse2, ReverseOut, OutputIterator, GeometryOut, overlay_union, Strategy>\n{};\n\n\n\ntemplate\n<\n    typename GeometryTag1, typename GeometryTag2, typename GeometryTag3,\n    bool Areal1, bool Areal2, bool ArealOut,\n    typename Geometry1, typename Geometry2,\n    bool Reverse1, bool Reverse2, bool ReverseOut,\n    typename OutputIterator, typename GeometryOut,\n    typename Strategy\n>\nstruct union_insert_reversed\n{\n    static inline OutputIterator apply(Geometry1 const& g1,\n            Geometry2 const& g2, OutputIterator out,\n            Strategy const& strategy)\n    {\n        return union_insert\n            <\n                GeometryTag2, GeometryTag1, GeometryTag3,\n                Areal2, Areal1, ArealOut,\n                Geometry2, Geometry1,\n                Reverse2, Reverse1, ReverseOut,\n                OutputIterator, GeometryOut,\n                Strategy\n            >::apply(g2, g1, out, strategy);\n    }\n};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace union_\n{\n\ntemplate\n<\n    typename GeometryOut,\n    typename Geometry1, typename Geometry2,\n    typename OutputIterator,\n    typename Strategy\n>\ninline OutputIterator insert(Geometry1 const& geometry1,\n            Geometry2 const& geometry2,\n            OutputIterator out,\n            Strategy const& strategy)\n{\n    return boost::mpl::if_c\n        <\n            geometry::reverse_dispatch<Geometry1, Geometry2>::type::value,\n            dispatch::union_insert_reversed\n            <\n                typename tag<Geometry1>::type,\n                typename tag<Geometry2>::type,\n                typename tag<GeometryOut>::type,\n                geometry::is_areal<Geometry1>::value,\n                geometry::is_areal<Geometry2>::value,\n                geometry::is_areal<GeometryOut>::value,\n                Geometry1, Geometry2,\n                overlay::do_reverse<geometry::point_order<Geometry1>::value>::value,\n                overlay::do_reverse<geometry::point_order<Geometry2>::value>::value,\n                overlay::do_reverse<geometry::point_order<GeometryOut>::value>::value,\n                OutputIterator, GeometryOut,\n                Strategy\n            >,\n            dispatch::union_insert\n            <\n                typename tag<Geometry1>::type,\n                typename tag<Geometry2>::type,\n                typename tag<GeometryOut>::type,\n                geometry::is_areal<Geometry1>::value,\n                geometry::is_areal<Geometry2>::value,\n                geometry::is_areal<GeometryOut>::value,\n                Geometry1, Geometry2,\n                overlay::do_reverse<geometry::point_order<Geometry1>::value>::value,\n                overlay::do_reverse<geometry::point_order<Geometry2>::value>::value,\n                overlay::do_reverse<geometry::point_order<GeometryOut>::value>::value,\n                OutputIterator, GeometryOut,\n                Strategy\n            >\n        >::type::apply(geometry1, geometry2, out, strategy);\n}\n\n/*!\n\\brief_calc2{union} \\brief_strategy\n\\ingroup union\n\\details \\details_calc2{union_insert, spatial set theoretic union}\n    \\brief_strategy. details_insert{union}\n\\tparam GeometryOut output geometry type, must be specified\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\tparam OutputIterator output iterator\n\\tparam Strategy \\tparam_strategy_overlay\n\\param geometry1 \\param_geometry\n\\param geometry2 \\param_geometry\n\\param out \\param_out{union}\n\\param strategy \\param_strategy{union}\n\\return \\return_out\n\n\\qbk{distinguish,with strategy}\n*/\ntemplate\n<\n    typename GeometryOut,\n    typename Geometry1,\n    typename Geometry2,\n    typename OutputIterator,\n    typename Strategy\n>\ninline OutputIterator union_insert(Geometry1 const& geometry1,\n            Geometry2 const& geometry2,\n            OutputIterator out,\n            Strategy const& strategy)\n{\n    concept::check<Geometry1 const>();\n    concept::check<Geometry2 const>();\n    concept::check<GeometryOut>();\n\n    return detail::union_::insert<GeometryOut>(geometry1, geometry2, out, strategy);\n}\n\n/*!\n\\brief_calc2{union}\n\\ingroup union\n\\details \\details_calc2{union_insert, spatial set theoretic union}.\n    \\details_insert{union}\n\\tparam GeometryOut output geometry type, must be specified\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\tparam OutputIterator output iterator\n\\param geometry1 \\param_geometry\n\\param geometry2 \\param_geometry\n\\param out \\param_out{union}\n\\return \\return_out\n*/\ntemplate\n<\n    typename GeometryOut,\n    typename Geometry1,\n    typename Geometry2,\n    typename OutputIterator\n>\ninline OutputIterator union_insert(Geometry1 const& geometry1,\n            Geometry2 const& geometry2,\n            OutputIterator out)\n{\n    concept::check<Geometry1 const>();\n    concept::check<Geometry2 const>();\n    concept::check<GeometryOut>();\n\n    typedef strategy_intersection\n        <\n            typename cs_tag<GeometryOut>::type,\n            Geometry1,\n            Geometry2,\n            typename geometry::point_type<GeometryOut>::type\n        > strategy;\n\n    return union_insert<GeometryOut>(geometry1, geometry2, out, strategy());\n}\n\n\n}} // namespace detail::union_\n#endif // DOXYGEN_NO_DETAIL\n\n\n\n\n/*!\n\\brief Combines two geometries which each other\n\\ingroup union\n\\details \\details_calc2{union, spatial set theoretic union}.\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\tparam Collection output collection, either a multi-geometry,\n    or a std::vector<Geometry> / std::deque<Geometry> etc\n\\param geometry1 \\param_geometry\n\\param geometry2 \\param_geometry\n\\param output_collection the output collection\n\\note Called union_ because union is a reserved word.\n\n\\qbk{[include reference/algorithms/union.qbk]}\n*/\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    typename Collection\n>\ninline void union_(Geometry1 const& geometry1,\n            Geometry2 const& geometry2,\n            Collection& output_collection)\n{\n    concept::check<Geometry1 const>();\n    concept::check<Geometry2 const>();\n\n    typedef typename boost::range_value<Collection>::type geometry_out;\n    concept::check<geometry_out>();\n\n    detail::union_::union_insert<geometry_out>(geometry1, geometry2,\n                std::back_inserter(output_collection));\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_UNION_HPP\n", "meta": {"hexsha": "28d8e5dc0b4dfc37c6e0708df81b56babab75474", "size": 8307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/geometry/algorithms/union.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2015-07-18T08:40:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T13:10:02.000Z", "max_issues_repo_path": "boost/boost/geometry/algorithms/union.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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/boost/geometry/algorithms/union.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-01-05T06:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T18:36:40.000Z", "avg_line_length": 29.1473684211, "max_line_length": 116, "alphanum_fraction": 0.6882147586, "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17167097394119268}}
{"text": "/**************************************************************\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 *************************************************************/\n\n\n\n#ifndef OOX_DRAWINGML_TYPES_HXX\n#define OOX_DRAWINGML_TYPES_HXX\n\n#include <boost/shared_ptr.hpp>\n#include <com/sun/star/style/TabAlign.hpp>\n#include <com/sun/star/drawing/TextVerticalAdjust.hpp>\n#include <com/sun/star/geometry/IntegerRectangle2D.hpp>\n#include <com/sun/star/awt/Point.hpp>\n#include <com/sun/star/awt/Size.hpp>\n#include <com/sun/star/xml/sax/XFastAttributeList.hpp>\n#include \"oox/helper/helper.hxx\"\n\nnamespace oox {\nnamespace drawingml {\n\n// ============================================================================\n\nconst sal_Int32 PER_PERCENT     = 1000;\nconst sal_Int32 MAX_PERCENT     = 100 * PER_PERCENT;\n\nconst sal_Int32 PER_DEGREE      = 60000;\nconst sal_Int32 MAX_DEGREE      = 360 * PER_DEGREE;\n\n// ============================================================================\n\nstruct LineProperties;\ntypedef ::boost::shared_ptr< LineProperties > LinePropertiesPtr;\n\nstruct FillProperties;\ntypedef ::boost::shared_ptr< FillProperties > FillPropertiesPtr;\n\nstruct GraphicProperties;\ntypedef ::boost::shared_ptr< GraphicProperties > GraphicPropertiesPtr;\n\nstruct TextCharacterProperties;\ntypedef ::boost::shared_ptr< TextCharacterProperties > TextCharacterPropertiesPtr;\n\nstruct TextBodyProperties;\ntypedef ::boost::shared_ptr< TextBodyProperties > TextBodyPropertiesPtr;\n\nclass TextBody;\ntypedef ::boost::shared_ptr< TextBody > TextBodyPtr;\n\nclass Shape;\ntypedef ::boost::shared_ptr< Shape > ShapePtr;\n\nclass Theme;\ntypedef ::boost::shared_ptr< Theme > ThemePtr;\n\n// ---------------------------------------------------------------------------\n\nnamespace table {\n\nclass TableProperties;\ntypedef ::boost::shared_ptr< TableProperties > TablePropertiesPtr;\n\n} // namespace table\n\n// ============================================================================\n\n/** converts the attributes from an CT_Point2D into an awt Point with 1/100th mm */\ncom::sun::star::awt::Point GetPoint2D( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes );\n\n/** converts the attributes from an CT_TLPoint into an awt Point with 1/1000% */\ncom::sun::star::awt::Point GetPointPercent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttribs );\n\n\n/** converts the attributes from an CT_Size2D into an awt Size with 1/100th mm */\ncom::sun::star::awt::Size GetSize2D( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes );\n\n/** converts the attributes from a CT_RelativeRect to an IntegerRectangle2D */\ncom::sun::star::geometry::IntegerRectangle2D GetRelativeRect( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes );\n\n/** converts an emu string into 1/100th mmm but constrain as per ST_TextMargin\n * see 5.1.12.73\n */\nsal_Int32 GetTextMargin( const ::rtl::OUString& sValue );\n\n/** converts EMUs into 1/100th mmm */\nsal_Int32 GetCoordinate( sal_Int32 nValue );\n\n/** converts an emu string into 1/100th mmm */\nsal_Int32 GetCoordinate( const ::rtl::OUString& sValue );\n\n/** converts a ST_Percentage % string into 1/1000th of % */\nsal_Int32 GetPercent( const ::rtl::OUString& sValue );\n\n/** Converts a ST_PositiveFixedPercentage to a float. 1.0 == 100% */\ndouble GetPositiveFixedPercentage( const ::rtl::OUString& sValue );\n\n/** converts the ST_TextFontSize to point */\nfloat GetTextSize( const ::rtl::OUString& rValue );\n\n/** converts the ST_TextSpacingPoint to 1/100mm */\nsal_Int32 GetTextSpacingPoint(  const ::rtl::OUString& sValue );\nsal_Int32 GetTextSpacingPoint(  const sal_Int32 nValue );\n\n::com::sun::star::drawing::TextVerticalAdjust GetTextVerticalAdjust( sal_Int32 nToken );\n\n/** */\n::com::sun::star::style::TabAlign GetTabAlign( ::sal_Int32 aToken );\n\nfloat GetFontHeight( sal_Int32 nHeight );\n\nsal_Int16 GetFontUnderline( sal_Int32 nToken );\n\nsal_Int16 GetFontStrikeout( sal_Int32 nToken );\n\nsal_Int16 GetCaseMap( sal_Int32 nToken );\n\n/** converts a paragraph align to a ParaAdjust */\nsal_Int16 GetParaAdjust( sal_Int32 nAlign );\n\n// ============================================================================\n\n// CT_IndexRange\nstruct IndexRange {\n\tsal_Int32 start;\n\tsal_Int32 end;\n};\n\n/** retrieve the content of CT_IndexRange */\nIndexRange GetIndexRange( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes );\n\n// ============================================================================\n\nconst sal_Int32 EMU_PER_HMM = 360;      /// 360 EMUs per 1/100 mm.\n\n/** Converts the passed 32-bit integer value from 1/100 mm to EMUs. */\ninline sal_Int64 convertHmmToEmu( sal_Int32 nValue )\n{\n    return static_cast< sal_Int64 >( nValue ) * EMU_PER_HMM;\n}\n\n/** Converts the passed 64-bit integer value from EMUs to 1/100 mm. */\ninline sal_Int32 convertEmuToHmm( sal_Int64 nValue )\n{\n    return getLimitedValue< sal_Int32, sal_Int64 >( (nValue + EMU_PER_HMM / 2) / EMU_PER_HMM, 0, SAL_MAX_INT32 );\n}\n\n// ============================================================================\n\n/** A structure for a point with 64-bit integer components. */\nstruct EmuPoint\n{\n    sal_Int64           X;\n    sal_Int64           Y;\n\n    inline explicit     EmuPoint() : X( 0 ), Y( 0 ) {}\n    inline explicit     EmuPoint( sal_Int64 nX, sal_Int64 nY ) : X( nX ), Y( nY ) {}\n};\n\n// ============================================================================\n\n/** A structure for a size with 64-bit integer components. */\nstruct EmuSize\n{\n    sal_Int64           Width;\n    sal_Int64           Height;\n\n    inline explicit     EmuSize() : Width( 0 ), Height( 0 ) {}\n    inline explicit     EmuSize( sal_Int64 nWidth, sal_Int64 nHeight ) : Width( nWidth ), Height( nHeight ) {}\n};\n\n// ============================================================================\n\n/** A structure for a rectangle with 64-bit integer components. */\nstruct EmuRectangle : public EmuPoint, public EmuSize\n{\n    inline explicit     EmuRectangle() {}\n    inline explicit     EmuRectangle( const EmuPoint& rPos, const EmuSize& rSize ) : EmuPoint( rPos ), EmuSize( rSize ) {}\n    inline explicit     EmuRectangle( sal_Int64 nX, sal_Int64 nY, sal_Int64 nWidth, sal_Int64 nHeight ) : EmuPoint( nX, nY ), EmuSize( nWidth, nHeight ) {}\n\n    inline void         setPos( const EmuPoint& rPos ) { static_cast< EmuPoint& >( *this ) = rPos; }\n    inline void         setSize( const EmuSize& rSize ) { static_cast< EmuSize& >( *this ) = rSize; }\n};\n\n// ============================================================================\n\n} // namespace drawingml\n} // namespace oox\n\n#endif\n\n", "meta": {"hexsha": "390cf8f960dc46fd69726410095809c4f8439f55", "size": 7522, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "main/oox/inc/oox/drawingml/drawingmltypes.hxx", "max_stars_repo_name": "Grosskopf/openoffice", "max_stars_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 679.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T06:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:06:03.000Z", "max_issues_repo_path": "main/oox/inc/oox/drawingml/drawingmltypes.hxx", "max_issues_repo_name": "Grosskopf/openoffice", "max_issues_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 102.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T08:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T12:13:49.000Z", "max_forks_repo_path": "main/oox/inc/oox/drawingml/drawingmltypes.hxx", "max_forks_repo_name": "Grosskopf/openoffice", "max_forks_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 331.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T11:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T04:07:51.000Z", "avg_line_length": 36.1634615385, "max_line_length": 166, "alphanum_fraction": 0.6356022334, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.1715082597874693}}
{"text": "\n#ifndef BOOST_MPL_AUX_SINGLE_ELEMENT_ITER_HPP_INCLUDED\n#define BOOST_MPL_AUX_SINGLE_ELEMENT_ITER_HPP_INCLUDED\n\n// Copyright Aleksey Gurtovoy 2000-2004\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// See http://www.boost.org/libs/mpl for documentation.\n\n// $Id$\n// $Date$\n// $Revision$\n\n#include <boost/mpl/iterator_tags.hpp>\n#include <boost/mpl/advance_fwd.hpp>\n#include <boost/mpl/distance_fwd.hpp>\n#include <boost/mpl/next_prior.hpp>\n#include <boost/mpl/deref.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/aux_/value_wknd.hpp>\n#include <boost/mpl/aux_/config/ctps.hpp>\n\nnamespace boost { namespace mpl { \n\n\nnamespace aux {\n\ntemplate< typename T, int is_last_ >\nstruct sel_iter;\n\ntemplate< typename T >\nstruct sel_iter<T,0>\n{\n    typedef random_access_iterator_tag category;\n    typedef sel_iter<T,1> next;\n    typedef T type;\n};\n\ntemplate< typename T >\nstruct sel_iter<T,1>\n{\n    typedef random_access_iterator_tag category;\n    typedef sel_iter<T,0> prior;\n};\n\n} // namespace aux\n\ntemplate< typename T, int is_last_, typename Distance >\nstruct advance< aux::sel_iter<T,is_last_>,Distance>\n{\n    typedef aux::sel_iter<\n          T\n        , ( is_last_ + BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Distance) )\n        > type;\n};\n\ntemplate< \n      typename T\n    , int l1\n    , int l2 \n    >\nstruct distance< aux::sel_iter<T,l1>, aux::sel_iter<T,l2> >\n    : int_<( l2 - l1 )>\n{\n};\n\n\n}}\n\n#endif // BOOST_MPL_AUX_SINGLE_ELEMENT_ITER_HPP_INCLUDED\n", "meta": {"hexsha": "e10270dbb60d04c4e595df7df7252c4bc1d0ff3d", "size": 1566, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/mpl/aux_/single_element_iter.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/mpl/aux_/single_element_iter.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/mpl/aux_/single_element_iter.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": 21.1621621622, "max_line_length": 71, "alphanum_fraction": 0.7126436782, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.17150825978746928}}
{"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_BITWISE_FUNCTIONS_SIMD_SSE_SSE2_SHRAI_HPP_INCLUDED\n#define BOOST_SIMD_BITWISE_FUNCTIONS_SIMD_SSE_SSE2_SHRAI_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n#include <boost/simd/bitwise/functions/shrai.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/include/functions/simd/is_gtz.hpp>\n#include <boost/simd/include/functions/simd/if_else.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/make.hpp>\n#include <boost/simd/bitwise/functions/simd/common/shrai.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::shrai_, boost::simd::tag::sse2_\n                            , (A0)(A1)\n                            , ((simd_<int32_<A0>,boost::simd::tag::sse_>))\n                              (scalar_< integer_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef typename dispatch::meta::as_integer<A0,signed>::type sint;\n      sint const that = _mm_srai_epi32(bitwise_cast<sint>(a0), a1);\n      return bitwise_cast<A0>(that);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::shrai_, boost::simd::tag::sse2_\n                            , (A0)(A1)\n                            , ((simd_<int16_<A0>,boost::simd::tag::sse_>))\n                              (scalar_< integer_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef typename dispatch::meta::as_integer<A0,signed>::type sint;\n      sint const that = _mm_srai_epi16(bitwise_cast<sint>(a0), a1);\n      return bitwise_cast<A0>(that);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::shrai_, boost::simd::tag::sse2_\n                            , (A0)(A1)\n                            , ((simd_<int8_<A0>,boost::simd::tag::sse_>))\n                              (scalar_< integer_<A1> >)\n                            )\n  {\n    typedef A0                                              result_type;\n    typedef typename meta::make_dependent<int16_t,A0>::type sub_t;\n    typedef native<sub_t, boost::simd::tag::sse_>           gen_t;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      gen_t a0h, a0l;\n      boost::fusion::tie(a0l, a0h) = split(a0);\n      return bitwise_cast<A0>(group(shrai(a0l, a1),shrai(a0h, a1)));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::shrai_, boost::simd::tag::sse2_\n                            , (A0)(A1)\n                            , ((simd_<int64_<A0>,boost::simd::tag::sse_>))\n                              (scalar_< integer_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      return make<A0>(shrai(a0[0], a1), shrai(a0[1], a1));\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "ba423308c7911ecfeb90c2e8e96982f81741fb8e", "size": 3390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/sse/sse2/shrai.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/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/sse/sse2/shrai.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/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/sse/sse2/shrai.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": 39.4186046512, "max_line_length": 86, "alphanum_fraction": 0.5519174041, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17150825635095046}}
{"text": "#include <ros/ros.h>\n#include <cstdio>\n#include <Eigen/Eigen>\n#include \"stdio.h\"\n#include \"iostream\"\n#include \"message_filters/subscriber.h\"\n#include \"visualization_msgs/MarkerArray.h\"\n#include \"std_srvs/Empty.h\"\n#include \"semanticscreator.h\"\n\n#define PALLET_THETA 0.01564559473350094\n/*   \nBIG Pick items\n      <x>-4.252623558044434</x>\n      <y>0.051172733306884766</y>\n      <theta>-0.005226923516850496</theta>*/\n#define P1 -3.45,-0.75,0\n#define P2 -4.95,-0.75,0\n#define P3 -4.95, 0.75,0\n#define P4 -3.45, 0.75,0\n\n\n\n/*small item picking site 2\n    <Pose name=\"toPose\">\n      <x>-21.755008697509766</x>\n      <y>2.7174549102783203</y>\n      <theta>-1.5736400093450944</theta>*/\n#define P11 -22.5,2.0  ,0\n#define P12 -21  ,2.0  ,0\n#define P13 -21  ,3.5  ,0\n#define P14 -22.5,3.5  ,0\n\n/*      <x>-22.966995239257812</x>\n      <y>-5.024758815765381</y>\n      <theta>0.01564559473350094</theta>*/\nusing namespace std;\n\nusing namespace Eigen;\nclass semantic_map_publisher {\n\npublic:\n  // Constructor\n  semantic_map_publisher(ros::NodeHandle param_nh)\n  {\n\n    param_nh.param<std::string>(\"topic_prefix\",topic_prefix_,\"\");\n\n    marker_publisher_=nh_.advertise<visualization_msgs::MarkerArray>(topic_prefix_+\"semantics_output\",100);\n    // marker_publisher_text_=nh_.advertise<visualization_msgs::MarkerArray>(topic_prefix_+\"semantics_output_text\",100);\n    publish_service_ = param_nh.advertiseService(\"publish_semantics\", &semantic_map_publisher::PublishSemantics, this);\n    semantics_creator_=new  semantics::SemanticsCreator();\n\n  }\n  bool PublishSemantics(std_srvs::Empty::Request  &req,\n                        std_srvs::Empty::Response &res ) {\n    unsigned id=0;\n    cout<<\"Plotting semantics \"<<endl;\n    Eigen::Affine3d pose_pallet=Eigen::Affine3d::Identity();\n    pose_pallet.translation()<<-22.966995239257812,-5.024758815765381,0.075;\n\n    Eigen::AngleAxisd rollAngle(0, Eigen::Vector3d::UnitZ());\n    Eigen::AngleAxisd yawAngle(PALLET_THETA, Eigen::Vector3d::UnitY());  \n    Eigen::AngleAxisd pitchAngle(0, Eigen::Vector3d::UnitX());\n    Eigen::Quaternion<double> q = rollAngle * yawAngle * pitchAngle;\n       pose_pallet.linear()=q.matrix();\n visualization_msgs::MarkerArray pallet_marker;\n    semantics_creator_->GetEuroPallet(pose_pallet,pallet_marker,1,\"pallet1\");\n    publishSemanticsWithText(pallet_marker);\n    {\n      visualization_msgs::MarkerArray arr_picking_site1;\n      std_vector3d points;\n      Eigen::Vector3d point1(P1);\n      points.push_back(point1);\n      Eigen::Vector3d point2(P2);\n      points.push_back(point2);\n      Eigen::Vector3d point3(P3);\n      points.push_back(point3);\n      Eigen::Vector3d point4(P4);\n      points.push_back(point4);\n      points.push_back(point1);\n      semantics_creator_->GetPickingArea(arr_picking_site1,points,2,\"Picking site: small items\");\n      publishSemanticAreaWithText(arr_picking_site1);\n    }\n    {\n      visualization_msgs::MarkerArray arr_picking_site2;\n      std_vector3d points;\n      Eigen::Vector3d point1(P11);\n      points.push_back(point1);\n      Eigen::Vector3d point2(P12);\n      points.push_back(point2);\n      Eigen::Vector3d point3(P13);\n      points.push_back(point3);\n      Eigen::Vector3d point4(P14);\n      points.push_back(point4);\n      points.push_back(point1);\n      semantics_creator_->GetPickingArea(arr_picking_site2,points,3,\"Picking site: large items\");\n      publishSemanticAreaWithText(arr_picking_site2);\n    }\n    return true;\n\n  }\n\n  void publishSemanticAreaWithText( visualization_msgs::MarkerArray &arr){\n    visualization_msgs::MarkerArray markers=arr;\n    marker_publisher_.publish(markers);\n\n    Eigen::Vector3d sum(0,0,0);\n    for(int i=0;i<markers.markers[0].points.size();i++){\n      sum(0)=sum(0)+markers.markers[0].points[i].x;\n      sum(1)=sum(1)+markers.markers[0].points[i].y;\n      sum(2)=sum(2)+markers.markers[0].points[i].z;\n    }\n    sum/=markers.markers[0].points.size();\n\n    markers.markers[0].type=visualization_msgs::Marker::TEXT_VIEW_FACING;\n    markers.markers[0].ns=markers.markers[0].ns+\"_text\";\n    markers.markers[0].pose.position.x=sum(0);\n    markers.markers[0].pose.position.y=sum(1);\n    markers.markers[0].pose.position.z=sum(2)+markers.markers[0].scale.z/2.0+0.5;\n    markers.markers[0].scale.z=0.4;\n    std::cout<<\"ns=\"<<markers.markers[0].ns<<\", text=\"<<markers.markers[0].text<<endl;\n    marker_publisher_.publish(markers);\n  }\n\n  void publishSemanticsWithText( visualization_msgs::MarkerArray &arr){\n    visualization_msgs::MarkerArray markers=arr;\n    marker_publisher_.publish(markers);\n    markers.markers[0].type=visualization_msgs::Marker::TEXT_VIEW_FACING;\n    markers.markers[0].ns=markers.markers[0].ns+\"_text\";\n    markers.markers[0].pose.position.z=markers.markers[0].pose.position.z+markers.markers[0].scale.z/2.0+0.5;\n    markers.markers[0].scale.z=0.4;\n    marker_publisher_.publish(markers);\n  }\n\nprivate:\n  ros::NodeHandle nh_;\n  ros::Publisher marker_publisher_,marker_publisher_text_;\n  std::string topic_prefix_;\n  semantics::SemanticsCreator *semantics_creator_;\n  ros::ServiceServer publish_service_;\n\n\n};\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"ndt_fuser_node\");\n\n  ros::NodeHandle param(\"~\");\n  semantic_map_publisher t(param);\n  ros::spin();\n\n  return 0;\n}\n\n", "meta": {"hexsha": "bfe603790ade9d35949df7a990e02a4a406a3194", "size": 5248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/semantic_map_fake_publisher.cpp", "max_stars_repo_name": "dan11003/semantic_mapping", "max_stars_repo_head_hexsha": "0a4258a0029d6b42501faa5f7905b2a602f5e3a0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-17T03:09:06.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-17T03:09:06.000Z", "max_issues_repo_path": "src/semantic_map_fake_publisher.cpp", "max_issues_repo_name": "dan11003/semantic_mapping", "max_issues_repo_head_hexsha": "0a4258a0029d6b42501faa5f7905b2a602f5e3a0", "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/semantic_map_fake_publisher.cpp", "max_forks_repo_name": "dan11003/semantic_mapping", "max_forks_repo_head_hexsha": "0a4258a0029d6b42501faa5f7905b2a602f5e3a0", "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.4267515924, "max_line_length": 120, "alphanum_fraction": 0.7038871951, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.17150825291443164}}
{"text": "/* By downloading, copying, installing or using the software you agree to this license.\n *\n *                           License Agreement\n *                      For heuristic_search library\n *\n * Copyright (c) 2016,\n * Maciej Przybylski <maciej.przybylski@mchtr.pw.edu.pl>,\n * Warsaw University of Technology.\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 copyright holders 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 HOLDERS 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#include <cstdlib>\n#include <iostream>\n\n#include <boost/program_options.hpp>\n\n#include <heuristic_search/AStar.h>\n#include <heuristic_search/IncrementalSearch.h>\n#include <heuristic_search/DStarExtraLite.h>\n#include <heuristic_search/DStarMain.h>\n#include <heuristic_search/loggers/DStarLogger.h>\n\n#include <search_domains/movingai_benchmark/Domain.h>\n#include <search_domains/movingai_benchmark/loader/MapLoader.h>\n#include \"search_domains/movingai_benchmark/loader/ScenarioLoader.h\"\n#include \"search_domains/movingai_benchmark/benchmark/DynamicExperiment.h\"\n#include \"search_domains/movingai_benchmark/ProgramOptions.h\"\n#include \"search_domains/movingai_benchmark/debug_cv/DStarMain.h\"\n#include <search_domains/movingai_benchmark/debug_cv/debug_cv.h>\n#include <search_domains/movingai_benchmark/debug_cv/Search.h>\n#include <search_domains/movingai_benchmark/debug_cv/DynamicAlgorithms.h>\n\n\ntypedef heuristic_search::SearchAlgorithmBegin<\n            heuristic_search::loggers::DStarLogger<\n            heuristic_search::DStarMain<\n            heuristic_search::SearchLoop<\n            heuristic_search::DStarExtraLite<\n            heuristic_search::IncrementalSearch_SearchStep<\n            heuristic_search::AStar<\n            heuristic_search::IncrementalSearch_Initialize<\n            heuristic_search::HeuristicSearch<\n            heuristic_search::StdOpenList<\n            heuristic_search::StdSearchSpace<\n        heuristic_search::SearchAlgorithmEnd<movingai_benchmark::Domain> > > > > > > > > > > >::Algorithm_t Algorithm_t;\n\ntypedef heuristic_search::SearchAlgorithmBegin<\n            heuristic_search::loggers::DStarLogger<\n            movingai_benchmark::debug_cv::DStarMain<\n            heuristic_search::DStarMain<\n            movingai_benchmark::debug_cv::Search<\n            heuristic_search::SearchLoop<\n            heuristic_search::DStarExtraLite<\n            heuristic_search::IncrementalSearch_SearchStep<\n            heuristic_search::AStar<\n            heuristic_search::IncrementalSearch_Initialize<\n            heuristic_search::HeuristicSearch<\n            heuristic_search::StdOpenList<\n            heuristic_search::StdSearchSpace<\n        heuristic_search::SearchAlgorithmEnd<movingai_benchmark::Domain> > > > > > > > > > > > > >::Algorithm_t Algorithm_CV_t;\n\nint main(int argc, char** argv)\n{\n    typedef movingai_benchmark::Domain::State State_t;\n\n    namespace po = boost::program_options;\n\n    po::options_description visible_ops;\n    visible_ops.add(movingai_benchmark::generalOptions())\n               .add(movingai_benchmark::singleProblemOptions())\n               .add(movingai_benchmark::dynamicExperimentOptions())\n               .add(movingai_benchmark::visualizationOptions())\n               .add(movingai_benchmark::configOptions());\n\n    po::options_description basic_ops;\n    basic_ops.add(movingai_benchmark::generalOptions())\n                .add(movingai_benchmark::configOptions());\n\n    try\n    {\n        po::variables_map basic_vm;\n        po::store(\n            po::basic_command_line_parser<char>(argc,argv).options(basic_ops).allow_unregistered().run(),\n            basic_vm);\n        po::notify(basic_vm);\n\n        if(basic_vm.count(\"help\"))\n        {\n            std::cout << visible_ops << \"\\n\";\n            return 1;\n        }\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, visible_ops), vm);\n\n        if(basic_vm.count(\"config-file\"))\n        {\n            std::string config_filename = basic_vm[\"config-file\"].as<std::string>();\n            std::cout << \"Loading params from file: \" << config_filename << \"\\n\";\n            po::store(po::parse_config_file<char>(config_filename.c_str(), visible_ops), vm);\n        }\n\n        po::notify(vm);\n\n        movingai_benchmark::loader::Experiment problem;\n        problem.SetMap(vm[\"map-file\"].as<std::string>());\n        problem.SetStartX(vm[\"start.x\"].as<int>());\n        problem.SetStartY(vm[\"start.y\"].as<int>());\n        problem.SetGoalX(vm[\"goal.x\"].as<int>());\n        problem.SetGoalY(vm[\"goal.y\"].as<int>());\n\n        movingai_benchmark::benchmark::DynamicExperimentParams dynamic_experiment_params;\n        dynamic_experiment_params.observation_range = vm[\"observation-range\"].as<int>();\n        dynamic_experiment_params.preinitialized = vm[\"preinitialized\"].as<bool>();\n        dynamic_experiment_params.undirected = vm[\"undirected\"].as<bool>();\n\n        bool visualization = vm[\"visualization\"].as<bool>();\n        movingai_benchmark::debug_cv::VisualizationConfig vis_config;\n        vis_config.scale = vm[\"vis-scale\"].as<double>();\n        vis_config.delay = vm[\"vis-delay\"].as<int>();\n        vis_config.hide_text = vm[\"vis-hide-text\"].as<bool>();\n\n        int W;\n        int H;\n        unsigned char *known_map;\n        unsigned char *unknown_map;\n\n        if(!movingai_benchmark::loader::loadMap(problem.GetMapName(),W,H,unknown_map))\n        {\n            std::cerr << \"Couldn't open file \" << problem.GetMapName() << std::endl;\n            return -1;\n        }\n\n        State_t start_state(problem.GetStartX(),problem.GetStartY());\n        State_t goal_state(problem.GetGoalX(),problem.GetGoalY());\n\n        known_map = new unsigned char[W*H];\n        std::memset(known_map, movingai_benchmark::UNKNOWN_TERRAIN, W*H);\n\n        movingai_benchmark::Domain domain(known_map, unknown_map, W, H, dynamic_experiment_params.observation_range);\n\n        if(visualization)\n        {\n            Algorithm_CV_t dstar_extra_lite(domain, heuristic_search::SearchingDirection::Backward,\n                dynamic_experiment_params.preinitialized, dynamic_experiment_params.undirected);\n\n            dstar_extra_lite.cv_window_name = \"D* Extra Lite - demo\";\n            dstar_extra_lite.cv_scale = vis_config.scale;\n            dstar_extra_lite.cv_window_delay = vis_config.delay;\n            dstar_extra_lite.cv_hide_text = vis_config.hide_text;\n\n            dstar_extra_lite.main(start_state, goal_state);\n\n            heuristic_search::loggers::Log::writeHeader(std::cout);\n            std::cout << std::endl;\n            std::cout << dstar_extra_lite.log << std::endl;\n\n            cv::waitKey(0);\n            cv::destroyAllWindows();\n        }\n        else\n        {\n            Algorithm_t dstar_extra_lite(domain, heuristic_search::SearchingDirection::Backward,\n                dynamic_experiment_params.preinitialized, dynamic_experiment_params.undirected);\n\n            dstar_extra_lite.main(start_state, goal_state);\n\n            heuristic_search::loggers::Log::writeHeader(std::cout);\n            std::cout << std::endl;\n            std::cout << dstar_extra_lite.log << std::endl;\n        }\n\n\n        delete [] known_map;\n        delete [] unknown_map;\n\n    }\n    catch(boost::program_options::error const&e)\n    {\n        std::cout << e.what() << \"\\nCheck --help\\n\";\n        return 1;\n    }\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "3f79227c2e86d1e8a940dfbe78f4b365bee4d73b", "size": 8719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/search_domains/movingai_benchmark/movingai_dstar_extra_lite_demo.cpp", "max_stars_repo_name": "Forrest-Z/heuristic_search", "max_stars_repo_head_hexsha": "8a1d2035483e7167baf362dc3de52320845f1109", "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/search_domains/movingai_benchmark/movingai_dstar_extra_lite_demo.cpp", "max_issues_repo_name": "Forrest-Z/heuristic_search", "max_issues_repo_head_hexsha": "8a1d2035483e7167baf362dc3de52320845f1109", "max_issues_repo_licenses": ["MIT"], "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/search_domains/movingai_benchmark/movingai_dstar_extra_lite_demo.cpp", "max_forks_repo_name": "Forrest-Z/heuristic_search", "max_forks_repo_head_hexsha": "8a1d2035483e7167baf362dc3de52320845f1109", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-18T09:58:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-18T09:58:49.000Z", "avg_line_length": 41.1273584906, "max_line_length": 127, "alphanum_fraction": 0.6776006423, "num_tokens": 1853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.17138066913222338}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2018.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Timo Sachsenberg $\n// $Authors: Stephan Aiche, Chris Bielow $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/ANALYSIS/QUANTITATION/IsobaricIsotopeCorrector.h>\n#include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h>\n#include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantifierStatistics.h>\n\n#include <OpenMS/DATASTRUCTURES/Utils/MatrixUtils.h>\n#include <OpenMS/KERNEL/ConsensusMap.h>\n\n// NNLS isotope correction\n#include <OpenMS/MATH/MISC/NonNegativeLeastSquaresSolver.h>\n\n#include <Eigen/LU>\n\n// #define ISOBARIC_QUANT_DEBUG\n\nnamespace OpenMS\n{\n\n  IsobaricQuantifierStatistics\n  IsobaricIsotopeCorrector::correctIsotopicImpurities(\n    const ConsensusMap& consensus_map_in, ConsensusMap& consensus_map_out,\n    const IsobaricQuantitationMethod* quant_method)\n  {\n    OPENMS_PRECONDITION(consensus_map_in.size() == consensus_map_out.size(),\n                        \"The in- and output map need to have the same size.\")\n\n    // the stats object to fill while correcting\n    IsobaricQuantifierStatistics stats;\n    stats.number_ms2_total = consensus_map_out.size();\n    stats.channel_count = quant_method->getNumberOfChannels();\n\n    Matrix<double> correction_matrix = quant_method->getIsotopeCorrectionMatrix();\n\n    if (matrixIsIdentityMatrix(correction_matrix))\n    {\n      throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,\n                                        \"IsobaricIsotopeCorrector: The given isotope correction matrix is an identity matrix leading to no correction. \"\n                                        \"Please provide a valid isotope_correction matrix as it was provided with the sample kit!\");\n    }\n\n    // convert to Eigen matrix\n    EigenMatrixXdPtr m(convertOpenMSMatrix2EigenMatrixXd(correction_matrix));\n    Eigen::FullPivLU<Eigen::MatrixXd> ludecomp(*m);\n    Eigen::VectorXd b;\n    b.resize(quant_method->getNumberOfChannels());\n    b.setZero();\n    std::vector<double> x(quant_method->getNumberOfChannels(), 0);\n\n    if (!ludecomp.isInvertible())\n    {\n      // clean up before we leave\n      throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"IsobaricIsotopeCorrector: The given isotope correction matrix is not invertible!\");\n    }\n\n    // data structures for NNLS\n    Matrix<double> m_b(quant_method->getNumberOfChannels(), 1);\n    Matrix<double> m_x(quant_method->getNumberOfChannels(), 1);\n\n    // correct all consensus elements\n    for (ConsensusMap::size_type i = 0; i < consensus_map_out.size(); ++i)\n    {\n#ifdef ISOBARIC_QUANT_DEBUG\n      std::cout << \"\\nMAP element  #### \" << i << \" #### \\n\" << std::endl;\n#endif\n      // delete only the consensus handles from the output map\n      consensus_map_out[i].clear();\n\n      // fill b vector\n      fillInputVector_(b, m_b, consensus_map_in[i], consensus_map_in);\n\n      //solve\n      Eigen::MatrixXd e_mx = ludecomp.solve(b);\n      if (!((*m) * e_mx).isApprox(b))\n      {\n        throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"IsobaricIsotopeCorrector: Cannot multiply!\");\n      }\n      solveNNLS_(correction_matrix, m_b, m_x);\n\n      // update the output consensus map with the corrected intensities\n      float cf_intensity = updateOutpuMap_(consensus_map_in, consensus_map_out, i, m_x);\n\n      // check consistency\n      computeStats_(m_x, e_mx, cf_intensity, quant_method, stats);    \n    }\n\n    return stats;\n  }\n\n  void\n  IsobaricIsotopeCorrector::fillInputVector_(Eigen::VectorXd& b,\n                                             Matrix<double>& m_b, const ConsensusFeature& cf, const ConsensusMap& cm)\n  {\n    for (ConsensusFeature::HandleSetType::const_iterator it_elements = cf.getFeatures().begin();\n         it_elements != cf.getFeatures().end();\n         ++it_elements)\n    {\n      //find channel_id of current element\n      Int index = Int(cm.getColumnHeaders().find(it_elements->getMapIndex())->second.getMetaValue(\"channel_id\"));\n#ifdef ISOBARIC_QUANT_DEBUG\n      std::cout << \"  map_index \" << it_elements->getMapIndex() << \"-> id \" << index << \" with intensity \" << it_elements->getIntensity() << \"\\n\" << std::endl;\n#endif\n      // this is deprecated, but serves as quality measurement\n      b(index) = it_elements->getIntensity();\n      m_b(index, 0) = it_elements->getIntensity();\n    }\n  }\n\n  void\n  IsobaricIsotopeCorrector::solveNNLS_(const Matrix<double>& correction_matrix,\n                                       const Matrix<double>& m_b, Matrix<double>& m_x)\n  {\n    Int status = NonNegativeLeastSquaresSolver::solve(correction_matrix, m_b, m_x);\n    if (status != NonNegativeLeastSquaresSolver::SOLVED)\n    {\n      throw Exception::FailedAPICall(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"IsobaricIsotopeCorrector: Failed to find least-squares fit!\");\n    }\n  }\n\n  void\n  IsobaricIsotopeCorrector::computeStats_(const Matrix<double>& m_x,\n                                          const Eigen::MatrixXd& x, const float cf_intensity,\n                                          const IsobaricQuantitationMethod* quant_method, IsobaricQuantifierStatistics& stats)\n  {\n    Size s_negative(0);\n    Size s_different_count(0); // happens when naive solution is negative in other channels\n    double s_different_intensity(0);\n\n    // ISOTOPE CORRECTION: compare solutions of Matrix inversion vs. NNLS\n    for (Size index = 0; index < quant_method->getNumberOfChannels(); ++index)\n    {\n      if (x(index) < 0.0)\n      {\n        ++s_negative;\n      }\n      else if ((((std::fabs(m_x(index, 0) - x(index)))/m_x(index, 0))*100) > 1)\n      {\n        ++s_different_count;\n        s_different_intensity += std::fabs(m_x(index, 0) - x(index));\n      }\n    }\n\n    if (s_negative == 0 && s_different_count > 0) //some solutions are inconsistent, despite being positive\n    {\n      OPENMS_LOG_WARN << \"IsobaricIsotopeCorrector: Isotope correction values of alternative method differ!\" << std::endl;\n    }\n\n    // update global stats\n    stats.iso_number_reporter_negative += s_negative;\n    stats.iso_number_reporter_different += s_different_count;\n    stats.iso_solution_different_intensity += s_different_intensity;\n\n    if (s_negative > 0)\n    {\n      ++stats.iso_number_ms2_negative;\n      stats.iso_total_intensity_negative += cf_intensity;\n    }\n  }\n\n  float\n  IsobaricIsotopeCorrector::updateOutpuMap_(\n    const ConsensusMap& consensus_map_in, ConsensusMap& consensus_map_out,\n    ConsensusMap::size_type current_cf, const Matrix<double>& m_x)\n  {\n    float cf_intensity(0);\n    for (ConsensusFeature::HandleSetType::const_iterator it_elements = consensus_map_in[current_cf].begin();\n         it_elements != consensus_map_in[current_cf].end();\n         ++it_elements)\n    {\n      FeatureHandle handle = *it_elements;\n      //find channel_id of current element\n      Int index = Int(consensus_map_out.getColumnHeaders()[it_elements->getMapIndex()].getMetaValue(\"channel_id\"));\n      handle.setIntensity(float(m_x(index, 0)));\n\n      consensus_map_out[current_cf].insert(handle);\n      cf_intensity += handle.getIntensity(); // sum up all channels for CF\n\n#ifdef ISOBARIC_QUANT_DEBUG\n      std::cout <<  it_elements->getIntensity() << \" -> \" << handle.getIntensity() << std::endl;\n#endif\n    }\n    consensus_map_out[current_cf].setIntensity(cf_intensity); // set overall intensity of CF (sum of all channels)\n\n    return cf_intensity;\n  }\n\n} // namespace\n", "meta": {"hexsha": "73185156767a8832c975384bb2b67875c8afa427", "size": 9396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/ANALYSIS/QUANTITATION/IsobaricIsotopeCorrector.cpp", "max_stars_repo_name": "avasq011/FinalProject_OpenMS_76ers", "max_stars_repo_head_hexsha": "6c9e2c295df6ec0eb296a3badfcdff245a869d59", "max_stars_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-15T20:50:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T20:50:22.000Z", "max_issues_repo_path": "src/openms/source/ANALYSIS/QUANTITATION/IsobaricIsotopeCorrector.cpp", "max_issues_repo_name": "avasq011/FinalProject_OpenMS_76ers", "max_issues_repo_head_hexsha": "6c9e2c295df6ec0eb296a3badfcdff245a869d59", "max_issues_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_issues_count": 150.0, "max_issues_repo_issues_event_min_datetime": "2017-09-05T09:43:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-03T10:07:36.000Z", "max_forks_repo_path": "src/openms/source/ANALYSIS/QUANTITATION/IsobaricIsotopeCorrector.cpp", "max_forks_repo_name": "avasq011/FinalProject_OpenMS_76ers", "max_forks_repo_head_hexsha": "6c9e2c295df6ec0eb296a3badfcdff245a869d59", "max_forks_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-02T18:41:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-11T21:39:24.000Z", "avg_line_length": 42.7090909091, "max_line_length": 168, "alphanum_fraction": 0.6714559387, "num_tokens": 2140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.1713806575952899}}
{"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#ifndef METRO_LIKELIHOOD_INDEPENDENTOBSERVATION_LOGLIKELIHOOD_HPP\n#define METRO_LIKELIHOOD_INDEPENDENTOBSERVATION_LOGLIKELIHOOD_HPP\n\n#include <memory>\n#include <boost/noncopyable.hpp>\n#include <Eigen/Core>\n#include \"metro/LogLikelihood.hpp\"\n\nnamespace metro {\n\ttemplate< typename Scalar, typename Vector, typename Matrix >\n\tstruct IndependentObservationLogLikelihood: public LogLikelihood< Scalar, Vector, Matrix > {\n\t\ttypedef std::auto_ptr< IndependentObservationLogLikelihood > UniquePtr ;\n\t\ttypedef typename Eigen::Ref< Matrix > MatrixRef ;\n\n\t\t// A function which returns the underlying terms of the log-likelihood.\n\t\tvirtual void get_terms_of_function( MatrixRef result ) const = 0 ;\n\t\t\n\t\tvirtual void set_data( Matrix const& ) = 0 ;\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "ce551a5cca296321a515a26fc0770c6430b529bb", "size": 969, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/IndependentObservationLogLikelihood.hpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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/include/metro/IndependentObservationLogLikelihood.hpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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/include/metro/IndependentObservationLogLikelihood.hpp", "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": 33.4137931034, "max_line_length": 93, "alphanum_fraction": 0.7647058824, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.27512971193602087, "lm_q1q2_score": 0.17125705648545445}}
{"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_X86_XOP_SIMD_FUNCTION_IS_LESS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_XOP_SIMD_FUNCTION_IS_LESS_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n\n#if !defined(_MM_PCOMCTRL_LT)\n#define _MM_PCOMCTRL_LT 0\n#define BOOST_SIMD_MISSING_MM_PCOMCTRL_LT\n#endif\n\n#if BOOST_HW_SIMD_X86_AMD_XOP\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( is_less_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::int8_<A0>, bs::sse_>\n                          , bs::pack_<bd::int8_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE\n    bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      #if defined(__clang__)\n      return _mm_com_epi8(a0,a1,_MM_PCOMCTRL_LT);\n      #else\n      return _mm_comlt_epi8(a0,a1);\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( is_less_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::int16_<A0>, bs::sse_>\n                          , bs::pack_<bd::int16_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE\n    bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      #if defined(__clang__)\n      return _mm_com_epi16(a0,a1,_MM_PCOMCTRL_LT);\n      #else\n      return _mm_comlt_epi16(a0,a1);\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( is_less_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::int32_<A0>, bs::sse_>\n                          , bs::pack_<bd::int32_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE\n    bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      #if defined(__clang__)\n      return _mm_com_epi32(a0,a1,_MM_PCOMCTRL_LT);\n      #else\n      return _mm_comlt_epi32(a0,a1);\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( is_less_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::int64_<A0>, bs::sse_>\n                          , bs::pack_<bd::int64_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE\n    bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      #if defined(__clang__)\n      return _mm_com_epi64(a0,a1,_MM_PCOMCTRL_LT);\n      #else\n      return _mm_comlt_epi64(a0,a1);\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( is_less_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::uint8_<A0>, bs::sse_>\n                          , bs::pack_<bd::uint8_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE\n    bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      #if defined(__clang__)\n      return _mm_com_epu8(a0,a1,_MM_PCOMCTRL_LT);\n      #else\n      return _mm_comlt_epu8(a0,a1);\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( is_less_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::uint16_<A0>, bs::sse_>\n                          , bs::pack_<bd::uint16_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE\n    bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      #if defined(__clang__)\n      return _mm_com_epu16(a0,a1,_MM_PCOMCTRL_LT);\n      #else\n      return _mm_comlt_epu16(a0,a1);\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( is_less_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::uint32_<A0>, bs::sse_>\n                          , bs::pack_<bd::uint32_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE\n    bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      #if defined(__clang__)\n      return _mm_com_epu32(a0,a1,_MM_PCOMCTRL_LT);\n      #else\n      return _mm_comlt_epu32(a0,a1);\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( is_less_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::uint64_<A0>, bs::sse_>\n                          , bs::pack_<bd::uint64_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE\n    bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n    {\n      #if defined(__clang__)\n      return _mm_com_epu64(a0,a1,_MM_PCOMCTRL_LT);\n      #else\n      return _mm_comlt_epu64(a0,a1);\n      #endif\n    }\n  };\n} } }\n#endif\n\n#if defined(BOOST_SIMD_MISSING_MM_PCOMCTRL_LT)\n#undef _MM_PCOMCTRL_LT\n#undef BOOST_SIMD_MISSING_MM_PCOMCTRL_LT\n#endif\n\n#endif\n", "meta": {"hexsha": "60f34750dbb0549e2ceba67ad70928d138be751a", "size": 5338, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/xop/simd/function/is_less.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/x86/xop/simd/function/is_less.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/x86/xop/simd/function/is_less.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.9887640449, "max_line_length": 100, "alphanum_fraction": 0.511614837, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.17121497624327062}}
{"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_SIMD_SIGN_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIMD_SIGN_INCLUDED\n\n#include <boost/simd/function/scalar/sign.hpp>\n#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>\n#include <boost/simd/arch/common/simd/function/sign.hpp>\n\n#if defined(BOOST_HW_SIMD_X86)\n\n#  if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_SSSE3_VERSION\n#    include <boost/simd/arch/x86/ssse3/simd/function/sign.hpp>\n#  endif\n\n#endif\n\n#endif\n", "meta": {"hexsha": "c65daf0d55a9efec95b361ce3711ab3de0cc073e", "size": 874, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/simd/sign.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/simd/sign.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/simd/sign.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.2142857143, "max_line_length": 100, "alphanum_fraction": 0.6029748284, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1712149728479441}}
{"text": "// Copyright (c) 2016 Graphcore Ltd. All rights reserved.\n#include \"poputil/exceptions.hpp\"\n#include <algorithm>\n#include <boost/multi_array.hpp>\n#include <boost/optional.hpp>\n#include <boost/optional/optional_io.hpp>\n#include <boost/program_options.hpp>\n#include <boost/random.hpp>\n#include <chrono>\n#include <exception>\n#include <fstream>\n#include <istream>\n#include <ostream>\n#include <poplar/CycleCount.hpp>\n#include <poplar/Engine.hpp>\n#include <poplar/Graph.hpp>\n#include <poplar/IPUModel.hpp>\n#include <poplibs_support/Algorithm.hpp>\n#include <poplibs_support/TestDevice.hpp>\n#include <poplibs_test/GeneralMatrixMultiply.hpp>\n#include <poplibs_test/Pass.hpp>\n#include <poplibs_test/SparseMatrix.hpp>\n#include <poplibs_test/Util.hpp>\n#include <poplin/codelets.hpp>\n#include <popops/codelets.hpp>\n#include <popsparse/SparsePartitioner.hpp>\n#include <popsparse/codelets.hpp>\n#include <queue>\n#include <random>\n#include <ratio>\n\n#include \"../lib/popsparse/FullyConnectedOnTile.hpp\"\n#include \"../lib/popsparse/FullyConnectedOptions.hpp\"\n#include \"../lib/popsparse/FullyConnectedPlan.hpp\"\n#include \"../lib/popsparse/SparsePartitionerImpl.hpp\"\n#include \"../lib/popsparse/SparseStorageInternal.hpp\"\n#include \"poplibs_support/VectorUtils.hpp\"\n#include \"poplibs_support/logging.hpp\"\n#include \"popsparse/FullyConnected.hpp\"\n#include \"popsparse/FullyConnectedParams.hpp\"\n\nusing namespace poplar;\nusing namespace poplar::program;\nusing namespace poplibs_test::util;\nusing namespace poputil;\nusing poplibs_test::Pass;\nusing namespace poplibs_support;\n\nusing namespace popsparse;\nusing namespace popsparse::dynamic;\n\n// Tolerances used when data is not ignored\n#define FLOAT_REL_TOL 0.01\n#define HALF_REL_TOL 0.1\n\n// TODO: This could be a program option if at all needed\nusing EType = float;\n\ntemplate <typename T>\nstatic void logBucketStatistics(std::vector<PNBucket> &buckets,\n                                const CSRMatrix<T> &csrMatrix) {\n  if (buckets.empty()) {\n    std::cerr << \"   - No buckets found\"\n              << \"\\n\";\n    return;\n  }\n\n  std::size_t pnUsed = buckets.size();\n\n  std::size_t maxNzElements = 0, maxMetaInfo = 0;\n  std::size_t totalNzElements = 0, totalMetaInfo = 0;\n  std::for_each(buckets.begin(), buckets.end(), [&](const PNBucket &b) {\n    maxNzElements = std::max(maxNzElements, b.numNzElements);\n    maxMetaInfo = std::max(maxMetaInfo, b.metaInfoElements);\n    totalNzElements += b.numNzElements;\n    totalMetaInfo += b.metaInfoElements;\n  });\n\n  std::cerr << \"   - NZ entries \" << csrMatrix.nzValues.size() << \"\\n\";\n  std::cerr << \"   - NZ elements/PN max : \" << maxNzElements;\n  std::cerr << \" avg : \" << static_cast<double>(totalNzElements) / pnUsed;\n  std::cerr << \"\\n\";\n  std::cerr << \"   - Meta info elements/PN max : \" << maxMetaInfo;\n  std::cerr << \" avg : \" << static_cast<double>(totalMetaInfo) / pnUsed;\n  std::cerr << \"\\n\";\n}\n\nint main(int argc, char **argv) try {\n  namespace po = boost::program_options;\n\n  DeviceType deviceType = DeviceType::IpuModel2;\n  unsigned numGroups = 1;\n  unsigned inputSize;\n  unsigned outputSize;\n  unsigned batchSize;\n  bool reportPlan;\n  boost::optional<std::string> profileDir;\n  Type dataType;\n  Type partialsType;\n  unsigned numIPUs = 1;\n  boost::optional<unsigned> tilesPerIPU;\n  Pass pass = Pass::ALL;\n  std::string matmulOptionsString;\n  std::string planConstraintsString;\n  double sparsityFactor;\n  ShapeOption<std::size_t> weightedAreaBegin;\n  ShapeOption<std::size_t> weightedAreaEnd;\n  ShapeOption<std::size_t> blockSize;\n  weightedAreaBegin.val = weightedAreaEnd.val = {0, 0};\n  double weightedAreaWeighting = 1.0;\n  bool denseGradWSerialSplits = false;\n\n  po::options_description desc(\"Options\");\n  // clang-format off\n  desc.add_options()\n    (\"help\", \"Produce help message\")\n    (\"compile-only\", \"Stop after compilation; don't run the program\")\n    (\"device-type\",\n     po::value<DeviceType>(&deviceType)->default_value(deviceType),\n     deviceTypeHelp)\n    (\"input-size\", po::value<unsigned>(&inputSize)->required(),\n     \"Number of inputs\")\n    (\"output-size\", po::value<unsigned>(&outputSize)->required(),\n     \"Number of output channels\")\n    (\"sparsity-factor\", po::value<double>(&sparsityFactor)->required(),\n     \"Sparsity factor (ratio of number of non-zero values to total weight \"\n     \"values\")\n    (\"data-type\",\n     po::value<Type>(&dataType)->default_value(HALF),\n     \"Type of the input and output data\")\n    (\"partials-type\",\n     po::value<Type>(&partialsType)->default_value(FLOAT),\n     \"Type of partials used during the operation\")\n    (\"tiles-per-ipu\",\n     po::value(&tilesPerIPU),\n     \"Number of tiles per IPU\")\n    (\"batch-size\",\n     po::value<unsigned>(&batchSize)->default_value(1),\n     \"Batch size\")\n    (\"block-size\",\n     po::value<ShapeOption<std::size_t>>(&blockSize)->default_value(1),\n     \"Block size as rows and columns (only square blocks are supported)\")\n    (\"single-phase\",\n     po::value<Pass>(&pass)->default_value(pass),\n     \"Run phase all | fwd | bwd | wu\")\n    (\"ignore-data\", \"When set, no upload/download or verification of \"\n     \"results is performed\")\n    (\"plan-only\", \"Whether to perform planning only and skip creation \"\n     \"and running of the program\")\n    (\"profile\", \"Enable profiling and print profiling report\")\n    (\"profile-dir\",\n     po::value<decltype(profileDir)>(&profileDir)\n      ->default_value(boost::none),\n     \"Write profile files to the specified directory.\")\n    (\"report-plan\", po::value<bool>(&reportPlan)->default_value(false),\n     \"Display plan\")\n    (\"report-total-cycle-counts\", \"Report total cycle count ignoring upload/download for \"\n     \"each pass. Note not compatible with 'profile' option\")\n    (\"variable-seed\", \"Use a variable seed based on clock, rather than a \"\n     \"single fixed seed that does not change between runs of this tool\")\n    (\"weighted-area-begin\",\n     po::value<ShapeOption<std::size_t>>(&weightedAreaBegin)->default_value(weightedAreaBegin),\n     \"Starting indices of an area of the sparse operand with a different \"\n     \"level of sparsity to the rest\")\n    (\"weighted-area-end\",\n     po::value<ShapeOption<std::size_t>>(&weightedAreaEnd)->default_value(weightedAreaEnd),\n     \"Ending indices of an area of the sparse operand with a different \"\n     \"level of sparsity to the rest\")\n    (\"weighted-area-weighting\",\n     po::value<double>(&weightedAreaWeighting)->default_value(weightedAreaWeighting),\n     \"Weighting for probability that a sparse element resides within the \"\n     \"specified area\")\n    (\"matmul-options\", po::value<std::string>(&matmulOptionsString),\n     \"Options to use for the matrix multiplication, specified as a JSON \"\n     \"string, e.g. {\\\"key\\\":\\\"value\\\"}\")\n    (\"plan-constraints\", po::value<std::string>(&planConstraintsString),\n     \"Plan constraints to use for the matrix multiplication, specified as \"\n     \"a JSON string\")\n    (\"report-dense-gradw-serial-splits\",\n      po::value<bool>(&denseGradWSerialSplits)->\n        default_value(denseGradWSerialSplits),\n     \"Report dense GradW splits when GradW pass is enabled\")\n  ;\n  // clang-format on\n  po::variables_map vm;\n  try {\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 1;\n    }\n    po::notify(vm);\n  } catch (std::exception &e) {\n    std::cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  bool profile = vm.count(\"profile\");\n  bool profilingEnabled = profile || profileDir;\n  bool reportTotalCycleCounts =\n      vm.count(\"report-total-cycle-counts\") && deviceType == DeviceType::Hw;\n  bool ignoreData = vm.count(\"ignore-data\");\n  bool planOnly = vm.count(\"plan-only\");\n  bool variableSeed = vm.count(\"variable-seed\");\n\n  if (reportTotalCycleCounts && profilingEnabled) {\n    throw poputil::poplibs_error(\n        \"--report-total-cycle-counts and --profile or --profile-dr specified \"\n        \"at the same time. This is not allowed as one affects the other\");\n  }\n\n  if (blockSize.val.size() > 2) {\n    throw poputil::poplibs_error(\"Block size must be of dimension 2\");\n  }\n\n  const std::size_t blockRows = blockSize[0];\n  const std::size_t blockCols =\n      blockSize.val.size() == 1 ? blockRows : blockSize[1];\n  const auto blockArea = blockRows * blockCols;\n\n  if (inputSize % blockRows) {\n    throw poputil::poplibs_error(\"Input size must be an integer multiple of \"\n                                 \"rows in a block\");\n  }\n\n  if (outputSize % blockCols) {\n    throw poputil::poplibs_error(\"output size must be an integer multiple of \"\n                                 \"columns in a block\");\n  }\n\n  if (weightedAreaBegin[0] > weightedAreaEnd[0] ||\n      weightedAreaBegin[1] > weightedAreaEnd[1]) {\n    std::stringstream ss;\n    ss << \"Invalid weighted area specified: \" << weightedAreaBegin.val << \",\"\n       << weightedAreaEnd.val;\n    throw poputil::poplibs_error(ss.str());\n  }\n\n  if (weightedAreaEnd[0] > outputSize || weightedAreaEnd[1] > inputSize) {\n    std::stringstream ss;\n    ss << \"Specified weighted area is out of bounds: Weighted area=\"\n       << weightedAreaBegin.val << \",\" << weightedAreaEnd.val\n       << \" out of bounds {\" << outputSize << \",\" << inputSize << \"}\";\n    throw poputil::poplibs_error(ss.str());\n  }\n\n  // align weighted area to a block size grid\n  weightedAreaBegin.val[0] = roundDown(weightedAreaBegin.val[0], blockRows);\n  weightedAreaBegin.val[1] = roundDown(weightedAreaBegin.val[1], blockCols);\n  weightedAreaEnd.val[0] = roundDown(weightedAreaEnd.val[0], blockRows);\n  weightedAreaEnd.val[1] = roundDown(weightedAreaEnd.val[1], blockCols);\n\n  PlanningCache cache;\n\n  poplar::OptionFlags options;\n  bool doBwdPass = pass == Pass::BWD || pass == Pass::ALL;\n  bool doWuPass = pass == Pass::WU || pass == Pass::ALL;\n  options.set(\"availableMemoryProportion\", \"1.0\");\n  options.set(\"doGradAPass\", doBwdPass ? \"true\" : \"false\");\n  options.set(\"doGradWPass\", doWuPass ? \"true\" : \"false\");\n  options.set(\"partialsType\", partialsType.toString());\n\n  // User options specified via --matmul-options override defaults\n  if (!matmulOptionsString.empty()) {\n    poplar::readJSON(matmulOptionsString, options);\n  }\n  if (!planConstraintsString.empty()) {\n    options.set(\"planConstraints\", planConstraintsString);\n  }\n\n  auto device = tilesPerIPU\n                    ? createTestDevice(deviceType, numIPUs, *tilesPerIPU, true)\n                    : createTestDeviceFullSize(deviceType, numIPUs, true);\n  const auto &target = device.getTarget();\n\n  const auto sparsityType =\n      blockArea == 1 ? SparsityType::Element : SparsityType::Block;\n\n  SparsityParams sparsityParams(sparsityType, SparsityStructure::Unstructured,\n                                {blockRows, blockCols});\n\n  const auto params = FullyConnectedParams::createWithNzRatio(\n      std::move(sparsityParams), sparsityFactor, batchSize, numGroups,\n      inputSize, outputSize);\n\n  popsparse::fullyconnected::Plan plan;\n  popsparse::fullyconnected::Cost planCost;\n\n  // Always do forward\n  std::tie(plan, planCost) = popsparse::fullyconnected::getPlan(\n      target, dataType, params, options, &cache);\n\n  if (reportPlan) {\n    std::string str;\n    if (doBwdPass || doWuPass) {\n      str += \"Joint : \";\n      if (doBwdPass) {\n        str += \" GradA + \";\n      }\n      if (doWuPass) {\n        str += \" GradW + \";\n      }\n    }\n    str += \"Fwd Plan \\n\";\n    std::cerr << str << plan << \"\\n\" << planCost << \"\\n\";\n  }\n\n  std::size_t fwdMetaInfoBucketSize = plan.fwdMetaInfoElemsPerBucket;\n  std::size_t gradAMetaInfoBucketSize = plan.gradAMetaInfoElemsPerBucket;\n  std::size_t nzElementBucketSize = plan.nzElemsPerBucket;\n\n  std::cerr << \"Using bucket sizes:\"\n            << \"\\n  meta info (forward): \" << fwdMetaInfoBucketSize\n            << \"\\n  meta info (grad-a): \" << gradAMetaInfoBucketSize\n            << \"\\n  nz element : \" << nzElementBucketSize << \"\\n\";\n\n  Partitioner<EType> partitioner(params, dataType, target, options, &cache);\n  std::mt19937 randomEngine;\n  if (variableSeed) {\n    using namespace std::chrono;\n    using SeedDurationType = duration<std::mt19937::result_type, std::nano>;\n    const auto now = high_resolution_clock::now();\n    const auto seed =\n        duration_cast<SeedDurationType>(now.time_since_epoch()).count();\n    randomEngine.seed(seed);\n  }\n\n  const bool floatingPointCouldRepresentMaxAccum = [&] {\n    const auto maxVal = maxContiguousInteger(dataType);\n\n    double weightedThreshold, remainingThreshold;\n    std::tie(weightedThreshold, remainingThreshold) =\n        poplibs_test::sparse::calculateWeightedVsRemainingSparsityFactor(\n            {outputSize / blockRows, inputSize / blockCols}, sparsityFactor,\n            {weightedAreaBegin[0] / blockRows,\n             weightedAreaBegin[1] / blockCols},\n            {weightedAreaEnd[0] / blockRows, weightedAreaEnd[1] / blockCols},\n            weightedAreaWeighting);\n    const auto numWeightedInputChannels =\n        (weightedAreaEnd[1] - weightedAreaBegin[1]);\n    const auto numWeightedOutputChannels =\n        (weightedAreaEnd[0] - weightedAreaBegin[0]);\n    std::size_t maxInputChannels =\n        numWeightedInputChannels * weightedThreshold +\n        (params.getInputChannelsPerGroup() - numWeightedInputChannels) *\n            remainingThreshold;\n    std::size_t maxOutputChannels =\n        numWeightedOutputChannels * weightedThreshold +\n        (params.getOutputChannelsPerGroup() - numWeightedOutputChannels) *\n            remainingThreshold;\n    maxInputChannels = roundDown(maxInputChannels, blockCols);\n    maxOutputChannels = roundDown(maxOutputChannels, blockRows);\n    const auto getOpsPerOutputElementEstimate = [&](const Pass &pass) -> int {\n      const auto numAccumulations = pass == Pass::FWD   ? maxInputChannels\n                                    : pass == Pass::BWD ? maxOutputChannels\n                                                        : params.getBatchSize();\n      return numAccumulations;\n    };\n    // We use a modifier to account for the unlikeliness of picking all positive\n    // or negative 1s which would actually get us to the max precisely\n    // represented integer.\n    constexpr int modifier = 10;\n    // We use another modifier to account for the chance that sparsity is not\n    // perfectly evenly spread in this instant.\n    constexpr double wiggleRoom = 1.3;\n    if (wiggleRoom * getOpsPerOutputElementEstimate(Pass::FWD) >\n        maxVal * modifier) {\n      return false;\n    }\n    if (doBwdPass && wiggleRoom * getOpsPerOutputElementEstimate(Pass::BWD) >\n                         maxVal * modifier) {\n      return false;\n    }\n    if (doWuPass && wiggleRoom * getOpsPerOutputElementEstimate(Pass::WU) >\n                        maxVal * modifier) {\n      return false;\n    }\n    return true;\n  }();\n\n  // create CSR matrix for the given sparsity factor\n  const bool useBipolarDistribution = floatingPointCouldRepresentMaxAccum;\n  std::array<std::size_t, 2> blockDims = {blockRows, blockCols};\n  CSRMatrix<EType> csrMatrix(blockDims);\n  std::tie(csrMatrix.nzValues, csrMatrix.columnIndices, csrMatrix.rowIndices) =\n      poplibs_test::sparse::buildCSRMatrix<EType, std::size_t>(\n          randomEngine, {outputSize, inputSize}, {blockRows, blockCols},\n          sparsityFactor, weightedAreaBegin, weightedAreaEnd,\n          weightedAreaWeighting, useBipolarDistribution);\n\n  // Forward\n  boost::multi_array<double, 2> hostInput(boost::extents[batchSize][inputSize]);\n  if (useBipolarDistribution) {\n    writeRandomBinaryValues(target, dataType, hostInput, -1.0, 1.0,\n                            randomEngine);\n  } else {\n    writeRandomValues(target, dataType, hostInput, -3.0, 3.0, randomEngine);\n  }\n  boost::multi_array<double, 2> hostOutputActs(\n      boost::extents[batchSize][outputSize]);\n\n  // GradA\n  boost::multi_array<double, 2> hostOutputGrad(\n      boost::extents[batchSize][outputSize]);\n  if (useBipolarDistribution) {\n    writeRandomBinaryValues(target, dataType, hostOutputGrad, -1.0, 1.0,\n                            randomEngine);\n  } else {\n    writeRandomValues(target, dataType, hostOutputGrad, -3.0, 3.0,\n                      randomEngine);\n  }\n  boost::multi_array<double, 2> hostInputGrad(\n      boost::extents[batchSize][inputSize]);\n\n  if (!plan.useDense) {\n    std::cerr << \"Logging Forward pass bucket statistics: \";\n    auto pnBucketsImpl = partitioner.getImpl().createBuckets(csrMatrix);\n\n    logBucketStatistics(pnBucketsImpl.pnBuckets, csrMatrix);\n  }\n\n  if (planOnly) {\n    return 0;\n  }\n\n  Graph graph(target);\n  popops::addCodelets(graph);\n  poplin::addCodelets(graph);\n  popsparse::addCodelets(graph);\n  Sequence fwdProg, bwdProg, wuProg, uploadProg, downloadProg;\n\n  // Build the graph\n  std::cerr << \"Constructing graph...\\n\";\n  const SparseTensor weights = createFullyConnectedWeights(\n      graph, dataType, params, \"weights\", options, &cache);\n  const Tensor input = createFullyConnectedInput(graph, dataType, params,\n                                                 \"input\", options, &cache);\n  const Tensor outputActs = fullyConnectedFwd(graph, weights, input, params,\n                                              fwdProg, \"fwd\", options, &cache);\n\n  // GradW\n  boost::multi_array<double, 1> hostWeightGrad(\n      boost::extents[weights.getNzValuesTensor().numElements()]);\n\n  Tensor outputGrad;\n  if (doBwdPass || doWuPass) {\n    outputGrad = graph.clone(outputActs, \"outputGrad\");\n  }\n  Tensor inputGrad;\n  if (doBwdPass) {\n    inputGrad = fullyConnectedGradA(graph, weights, outputGrad, params, bwdProg,\n                                    \"grada\", options, &cache);\n  }\n\n  Tensor weightGrad;\n  if (doWuPass) {\n    weightGrad = fullyConnectedSparseGradW(graph, weights.getMetaInfoTensor(),\n                                           outputGrad, input, params, wuProg,\n                                           \"wu\", options, &cache);\n  }\n  std::cerr << \"Done\\n\";\n\n  std::vector<std::pair<std::string, char *>> tmap;\n  auto rawMetaInfo =\n      allocateHostMemoryForTensor(weights.getMetaInfoTensor(), \"weights.meta\",\n                                  graph, uploadProg, downloadProg, tmap);\n\n  auto rawNzInfo =\n      allocateHostMemoryForTensor(weights.getNzValuesTensor(), \"weights.nz\",\n                                  graph, uploadProg, downloadProg, tmap);\n  auto rawInput = allocateHostMemoryForTensor(input, \"input\", graph, uploadProg,\n                                              downloadProg, tmap);\n  auto rawOutputActs = allocateHostMemoryForTensor(\n      outputActs, \"outputActs\", graph, uploadProg, downloadProg, tmap);\n\n  std::unique_ptr<char[]> rawOutputGrad;\n  if (doBwdPass || doWuPass) {\n    rawOutputGrad = allocateHostMemoryForTensor(outputGrad, \"outputGrad\", graph,\n                                                uploadProg, downloadProg, tmap);\n  }\n\n  std::unique_ptr<char[]> rawInputGrad;\n  if (!ignoreData && doBwdPass) {\n    rawInputGrad = allocateHostMemoryForTensor(inputGrad, \"inputGrad\", graph,\n                                               uploadProg, downloadProg, tmap);\n  }\n\n  std::unique_ptr<char[]> rawWeightGrad;\n  if (!ignoreData && doWuPass) {\n    rawWeightGrad = allocateHostMemoryForTensor(weightGrad, \"weightGrad\", graph,\n                                                uploadProg, downloadProg, tmap);\n  }\n\n  Tensor fwdCycles, bwdCycles, wuCycles;\n  if (reportTotalCycleCounts) {\n    fwdCycles = cycleCount(graph, fwdProg, 0, SyncType::INTERNAL, \"fwdCycles\");\n    graph.createHostRead(\"fwdCycles\", fwdCycles);\n    if (doBwdPass) {\n      bwdCycles =\n          cycleCount(graph, bwdProg, 0, SyncType::INTERNAL, \"bwdCycles\");\n      graph.createHostRead(\"bwdCycles\", bwdCycles);\n    }\n    if (doWuPass) {\n      wuCycles = cycleCount(graph, wuProg, 0, SyncType::INTERNAL, \"wuCycles\");\n      graph.createHostRead(\"wuCycles\", wuCycles);\n    }\n  }\n  Sequence controlProg({std::move(uploadProg), std::move(fwdProg),\n                        std::move(bwdProg), std::move(wuProg)});\n  if (!ignoreData) {\n    controlProg.add(std::move(downloadProg));\n  }\n\n  std::cerr << \"Creating engine...\\n\";\n  OptionFlags engineOptions;\n  if (profilingEnabled) {\n    engineOptions.set(\"debug.instrument\", \"true\");\n    if (profileDir) {\n      engineOptions.set(\"autoReport.all\", \"true\");\n      engineOptions.set(\"autoReport.directory\", *profileDir);\n    }\n  }\n  Engine engine(graph, std::move(controlProg), engineOptions);\n\n  if (vm.count(\"compile-only\"))\n    return 0;\n\n  attachStreams(engine, tmap);\n\n  std::cerr << \"Done\\n\";\n\n  std::cerr << \"Running...\\n\";\n\n  // Actual bucket info use by device graph\n  auto buckets = partitioner.createSparsityDataImpl(csrMatrix);\n\n  const auto &metaInfoFlat = buckets.metaInfo;\n  const auto &nzValuesFlat = buckets.nzValues;\n  // Overflow info is the same for all passes at time of writing.\n  if (!plan.useDense) {\n    std::cerr << \"overflowInfo = {\" << metaInfoFlat.at(0) << \",\"\n              << metaInfoFlat.at(1) << \",\" << metaInfoFlat.at(2) << \"}\\n\";\n  }\n\n  copy(target, hostInput, dataType, rawInput.get());\n  if (rawMetaInfo) {\n    copy(target, metaInfoFlat, UNSIGNED_SHORT, rawMetaInfo.get());\n  }\n  copy(target, nzValuesFlat, dataType, rawNzInfo.get());\n\n  if (!ignoreData && (doBwdPass || doWuPass)) {\n    copy(target, hostOutputGrad, outputGrad.elementType(), rawOutputGrad.get());\n  }\n\n  device.bind([&](const Device &d) {\n    engine.loadAndRun(d);\n    if (reportTotalCycleCounts) {\n      std::uint64_t cyclesBuffer;\n      engine.readTensor(\"fwdCycles\", &cyclesBuffer, &cyclesBuffer + 1);\n      std::cerr << \"  Forward pass cycles: \" << cyclesBuffer << \"\\n\";\n      if (doBwdPass) {\n        engine.readTensor(\"bwdCycles\", &cyclesBuffer, &cyclesBuffer + 1);\n        std::cerr << \"  GradA pass cycles: \" << cyclesBuffer << \"\\n\";\n      }\n      if (doWuPass) {\n        engine.readTensor(\"wuCycles\", &cyclesBuffer, &cyclesBuffer + 1);\n        std::cerr << \"  GradW pass cycles: \" << cyclesBuffer << \"\\n\";\n      }\n    }\n  });\n\n  bool matchesModel = true;\n  if (!ignoreData) {\n    const double relTolerance = dataType == HALF ? HALF_REL_TOL : FLOAT_REL_TOL;\n    copy(target, outputActs.elementType(), rawOutputActs.get(), hostOutputActs);\n    boost::multi_array<double, 2> hostDenseWeights(\n        boost::extents[outputSize][inputSize]);\n    boost::multi_array<double, 2> modelOutputActs(\n        boost::extents[batchSize][outputSize]);\n    hostDenseWeights = poplibs_test::sparse::csrToDenseMatrix(\n        csrMatrix.nzValues.data(), csrMatrix.columnIndices.data(),\n        csrMatrix.rowIndices.data(), csrMatrix.nzValues.size(), outputSize,\n        inputSize, blockRows, blockCols);\n\n    poplibs_test::gemm::generalMatrixMultiply(hostInput, hostDenseWeights,\n                                              modelOutputActs, false, true);\n    matchesModel &= checkIsClose(\"outputActs\", hostOutputActs, modelOutputActs,\n                                 relTolerance);\n    if (doBwdPass) {\n      copy(target, inputGrad.elementType(), rawInputGrad.get(), hostInputGrad);\n      boost::multi_array<double, 2> modelInputGrad(\n          boost::extents[batchSize][inputSize]);\n      poplibs_test::gemm::generalMatrixMultiply(\n          hostOutputGrad, hostDenseWeights, modelInputGrad, false, false);\n      matchesModel &= checkIsClose(\"inputGrad\", hostInputGrad, modelInputGrad,\n                                   relTolerance);\n    }\n    if (doWuPass) {\n      copy(target, weightGrad.elementType(), rawWeightGrad.get(),\n           hostWeightGrad);\n      boost::multi_array<double, 2> modelWeightGrad(\n          boost::extents[outputSize][inputSize]);\n      poplibs_test::gemm::generalMatrixMultiply(hostOutputGrad, hostInput,\n                                                modelWeightGrad, true, false);\n\n      std::vector<EType> modelNzValuesCSR;\n      auto columnIdxIt = csrMatrix.columnIndices.begin();\n      for (auto rowIt = std::next(csrMatrix.rowIndices.begin());\n           rowIt != csrMatrix.rowIndices.end(); ++rowIt) {\n        const auto nnzThisRow = *rowIt - *std::prev(rowIt);\n        const auto rowIdx =\n            (std::distance(csrMatrix.rowIndices.begin(), rowIt) - 1) *\n            blockRows;\n        for (std::size_t i = 0; i < nnzThisRow / blockArea; ++i) {\n          const auto columnIdx = *columnIdxIt++;\n          for (std::size_t r = 0; r != blockRows; ++r) {\n            for (std::size_t c = 0; c != blockCols; ++c) {\n              // row major order within a block\n              modelNzValuesCSR.emplace_back(\n                  modelWeightGrad[rowIdx + r][columnIdx + c]);\n            }\n          }\n        }\n      }\n\n      assert(modelNzValuesCSR.size() ==\n             csrMatrix.columnIndices.size() * blockArea);\n\n      SparsityDataImpl<EType> actualBuckets;\n      std::vector<EType> actualWeightGrads;\n      actualWeightGrads.reserve(hostWeightGrad.size());\n      std::copy(hostWeightGrad.begin(), hostWeightGrad.end(),\n                std::back_inserter(actualWeightGrads));\n\n      actualBuckets.nzValues = std::move(actualWeightGrads);\n      actualBuckets.metaInfo = std::move(buckets.metaInfo);\n      auto actualCSR = partitioner.sparsityDataImplToCSRMatrix(actualBuckets);\n\n      auto ait = actualCSR.nzValues.begin();\n      auto mit = modelNzValuesCSR.begin();\n      for (; ait != actualCSR.nzValues.end(); ++ait, ++mit) {\n        bool elemMatch = checkIsClose(*mit, *ait, relTolerance);\n        if (!elemMatch) {\n          std::cerr << \"mismatch at  WeightsGrad.nz[\";\n          std::cerr << std::distance(actualCSR.nzValues.begin(), ait);\n          std::cerr << \"]:\" << *mit << \"!=\" << *ait << \"\\n\";\n        }\n        matchesModel &= elemMatch;\n      }\n      auto columnsMatch = std::equal(\n          actualCSR.columnIndices.begin(), actualCSR.columnIndices.end(),\n          csrMatrix.columnIndices.begin(), csrMatrix.columnIndices.end());\n      if (!columnsMatch) {\n        std::cerr << \"CSR columns indices do not match\\n\";\n      }\n      matchesModel &= columnsMatch;\n    }\n  }\n\n  if (denseGradWSerialSplits && doWuPass) {\n    auto serialSplits =\n        fullyConnectedDenseGradWSerialSplits(graph, dataType, params, options);\n    std::cerr << \"Dense GradW serial splits : \"\n              << \"   groups \" << std::get<0>(serialSplits)\n              << \"   input channel \" << std::get<1>(serialSplits)\n              << \"   output channel \" << std::get<2>(serialSplits) << \"\\n\";\n  }\n\n  std::cerr << \"Done\\n\";\n\n  if (profile) {\n    engine.printProfileSummary(std::cout, {{\"showExecutionSteps\", \"true\"}});\n  }\n\n  if (!matchesModel) {\n    std::cerr << \"Validation failed\\n\";\n    return 1;\n  }\n\n  return 0;\n} catch (const poplar::graph_memory_allocation_error &e) {\n  if (!e.profilePath.empty()) {\n    poplar::printGraphSummary(std::cerr, e.profilePath,\n                              {{\"showVarStorage\", \"true\"}});\n  }\n  throw;\n}\n", "meta": {"hexsha": "d4e12323b4f04b60f50079e9137b8bf540cc65ba", "size": 26680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/sparse_fc_layer.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": "tools/sparse_fc_layer.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": "tools/sparse_fc_layer.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": 38.7790697674, "max_line_length": 95, "alphanum_fraction": 0.6525112444, "num_tokens": 6738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17121496605729128}}
{"text": "// Copyright (c) 2015-2018 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 \"cancer_caller.hpp\"\n\n#include <typeinfo>\n#include <string>\n#include <utility>\n#include <algorithm>\n#include <numeric>\n#include <deque>\n#include <unordered_set>\n#include <stdexcept>\n#include <iostream>\n\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include \"basics/genomic_region.hpp\"\n#include \"containers/probability_matrix.hpp\"\n#include \"readpipe/read_pipe.hpp\"\n#include \"core/types/allele.hpp\"\n#include \"core/types/variant.hpp\"\n#include \"core/types/genotype.hpp\"\n#include \"core/models/genotype/uniform_genotype_prior_model.hpp\"\n#include \"core/models/genotype/coalescent_genotype_prior_model.hpp\"\n#include \"core/models/genotype/constant_mixture_genotype_likelihood_model.hpp\"\n#include \"utils/read_stats.hpp\"\n#include \"utils/sequence_utils.hpp\"\n#include \"utils/merge_transform.hpp\"\n#include \"utils/mappable_algorithms.hpp\"\n#include \"utils/maths.hpp\"\n#include \"logging/logging.hpp\"\n#include \"core/types/calls/germline_variant_call.hpp\"\n#include \"core/types/calls/reference_call.hpp\"\n#include \"core/types/calls/somatic_call.hpp\"\n\nnamespace octopus {\n\n// public methods\n\nCancerCaller::CancerCaller(Caller::Components&& components,\n                           Caller::Parameters general_parameters,\n                           Parameters specific_parameters)\n: Caller {std::move(components), std::move(general_parameters)}\n, parameters_ {std::move(specific_parameters)}\n{\n    if (parameters_.ploidy == 0) {\n        throw std::logic_error {\"CancerCaller: ploidy must be > 0\"};\n    }\n    if (parameters_.max_genotypes == 0) {\n        throw std::logic_error {\"CancerCaller: max genotypes must be > 0\"};\n    }\n    if (has_normal_sample()) {\n        if (std::find(std::cbegin(samples_), std::cend(samples_), normal_sample()) == std::cend(samples_)) {\n            throw std::invalid_argument {\"CancerCaller: normal sample is not a valid sample\"};\n        }\n    }\n    if (parameters_.concentrations.cnv.normal <= 0.0\n        || parameters_.concentrations.cnv.tumour <= 0.0\n        || parameters_.concentrations.somatic.normal_germline <= 0.0\n        || parameters_.concentrations.somatic.normal_somatic <= 0.0\n        || parameters_.concentrations.somatic.tumour_germline <= 0.0\n        || parameters_.concentrations.somatic.tumour_somatic <= 0.0) {\n        throw std::invalid_argument {\"CancerCaller: concentration parameters must be positive\"};\n    }\n    if (parameters_.min_variant_posterior == Phred<double> {0}) {\n        logging::WarningLogger wlog {};\n        wlog << \"Having no germline variant posterior threshold means no somatic variants will be called\";\n    }\n    if (debug_log_) {\n        if (has_normal_sample()) {\n            stream(*debug_log_) << \"Normal sample is \" << *parameters_.normal_sample;\n        } else {\n            *debug_log_ << \"There is no normal sample\";\n        }\n    }\n    if (!has_normal_sample()) {\n        parameters_.concentrations.cnv.tumour = parameters_.concentrations.somatic.tumour_germline;\n    }\n}\n\n// private methods\n\nstd::string CancerCaller::do_name() const\n{\n    return \"cancer\";\n}\n\nCancerCaller::CallTypeSet CancerCaller::do_call_types() const\n{\n    return {\n        std::type_index(typeid(GermlineVariantCall)),\n        std::type_index(typeid(SomaticCall))\n    };\n}\n\nunsigned CancerCaller::do_min_callable_ploidy() const\n{\n    return parameters_.ploidy;\n}\n\nunsigned CancerCaller::do_max_callable_ploidy() const\n{\n    return parameters_.ploidy + parameters_.max_somatic_haplotypes;\n}\n\nbool CancerCaller::has_normal_sample() const noexcept\n{\n    return static_cast<bool>(parameters_.normal_sample);\n}\n\nconst SampleName& CancerCaller::normal_sample() const\n{\n    return *parameters_.normal_sample;\n}\n\nstd::size_t CancerCaller::do_remove_duplicates(std::vector<Haplotype>& haplotypes) const\n{\n    if (parameters_.deduplicate_haplotypes_with_germline_model) {\n        if (haplotypes.size() < 2) return 0;\n        CoalescentModel::Parameters model_params {};\n        if (parameters_.germline_prior_model_params) model_params = *parameters_.germline_prior_model_params;\n        Haplotype reference {mapped_region(haplotypes.front()), reference_.get()};\n        CoalescentModel model {std::move(reference), model_params, haplotypes.size(), CoalescentModel::CachingStrategy::none};\n        const CoalescentProbabilityGreater cmp {std::move(model)};\n        return octopus::remove_duplicates(haplotypes, cmp);\n    } else {\n        return Caller::do_remove_duplicates(haplotypes);\n    }\n}\n\nstd::unique_ptr<CancerCaller::Caller::Latents>\nCancerCaller::infer_latents(const std::vector<Haplotype>& haplotypes,\n                            const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    // Store any intermediate results in Latents for reuse, so the order of model evaluation matters!\n    auto result = std::make_unique<Latents>(haplotypes, samples_, parameters_);\n    set_model_priors(*result);\n    generate_germline_genotypes(*result, haplotypes);\n    if (debug_log_) stream(*debug_log_) << \"There are \" << result->germline_genotypes_.size() << \" candidate germline genotypes\";\n    evaluate_germline_model(*result, haplotype_likelihoods);\n    evaluate_cnv_model(*result, haplotype_likelihoods);\n    fit_somatic_model(*result, haplotype_likelihoods);\n    evaluate_noise_model(*result, haplotype_likelihoods);\n    set_model_posteriors(*result);\n    return result;\n}\n\nboost::optional<double>\nCancerCaller::calculate_model_posterior(const std::vector<Haplotype>& haplotypes,\n                                        const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                                        const Caller::Latents& latents) const\n{\n    return calculate_model_posterior(haplotypes, haplotype_likelihoods,\n                                     dynamic_cast<const Latents&>(latents));\n}\n\nvoid CancerCaller::set_cancer_genotype_prior_model(Latents& latents) const\n{\n    SomaticMutationModel mutation_model {parameters_.somatic_mutation_model_params};\n    latents.cancer_genotype_prior_model_ = CancerGenotypePriorModel {*latents.germline_prior_model_, std::move(mutation_model)};\n}\n\nvoid CancerCaller::fit_somatic_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    set_cancer_genotype_prior_model(latents);\n    SomaticModel::InferredLatents prev_latents;\n    std::vector<CancerGenotype<Haplotype>> prev_cancer_genotypes;\n    boost::optional<std::vector<CancerGenotypeIndex>> prev_cancer_genotype_indices;\n    for (unsigned somatic_ploidy {1}; somatic_ploidy <= parameters_.max_somatic_haplotypes; ++somatic_ploidy) {\n        if (debug_log_) stream(*debug_log_) << \"Fitting somatic model with somatic ploidy \" << somatic_ploidy;\n        latents.somatic_ploidy_ = somatic_ploidy;\n        generate_cancer_genotypes(latents, haplotype_likelihoods);\n        if (debug_log_) stream(*debug_log_) << \"There are \" << latents.cancer_genotypes_.size() << \" candidate cancer genotypes\";\n        evaluate_somatic_model(latents, haplotype_likelihoods);\n        if (somatic_ploidy > 1) {\n            if (latents.somatic_model_inferences_.approx_log_evidence <= prev_latents.approx_log_evidence) {\n                break;\n            }\n        } else {\n            set_model_posteriors(latents);\n            if (latents.model_posteriors_.somatic < std::max(latents.model_posteriors_.germline, latents.model_posteriors_.cnv)) {\n                break;\n            }\n        }\n        if (latents.haplotypes_.get().size() <= somatic_ploidy + 1) break;\n        if (somatic_ploidy < parameters_.max_somatic_haplotypes) {\n            // save previous state, but don't move as next cancer genotype generation may use this information\n            prev_latents = latents.somatic_model_inferences_;\n            prev_cancer_genotypes = latents.cancer_genotypes_;\n            prev_cancer_genotype_indices = latents.cancer_genotype_indices_;\n        }\n    }\n    if (latents.somatic_ploidy_ > 1) {\n        if (latents.cancer_genotypes_.empty()\n            || latents.somatic_model_inferences_.approx_log_evidence <= prev_latents.approx_log_evidence) {\n            // load previous state\n            --latents.somatic_ploidy_;\n            latents.somatic_model_inferences_ = std::move(prev_latents);\n            latents.cancer_genotypes_ = std::move(prev_cancer_genotypes);\n            latents.cancer_genotype_indices_ = std::move(prev_cancer_genotype_indices);\n        }\n    }\n    if (debug_log_) stream(*debug_log_) << \"Using somatic model with somatic ploidy \" << latents.somatic_ploidy_;\n}\n\nstatic double calculate_model_posterior(const double normal_germline_model_log_evidence,\n                                        const double normal_dummy_model_log_evidence)\n{\n    constexpr double normalModelPrior {0.99};\n    constexpr double dummyModelPrior {1.0 - normalModelPrior};\n    const auto normal_model_ljp = std::log(normalModelPrior) + normal_germline_model_log_evidence;\n    const auto dummy_model_ljp  = std::log(dummyModelPrior) + normal_dummy_model_log_evidence;\n    const auto norm = maths::log_sum_exp(normal_model_ljp, dummy_model_ljp);\n    return std::exp(normal_model_ljp - norm);\n}\n\nstatic double calculate_model_posterior(const double germline_model_log_evidence,\n                                        const double dummy_model_log_evidence,\n                                        const double noise_model_log_evidence)\n{\n    constexpr double normalModelPrior {0.99};\n    constexpr double dummyModelPrior {1.0 - normalModelPrior};\n    const auto normal_model_ljp = std::log(normalModelPrior) + germline_model_log_evidence;\n    const auto dummy_model_ljp  = std::log(dummyModelPrior) + dummy_model_log_evidence;\n    const auto noise_model_ljp  = std::log(dummyModelPrior) + noise_model_log_evidence;\n    const auto norm = maths::log_sum_exp(normal_model_ljp, std::max(dummy_model_ljp, noise_model_ljp));\n    return std::exp(normal_model_ljp - norm);\n}\n\nnamespace {\n\nauto demote_each(const std::vector<CancerGenotype<Haplotype>>& genotypes)\n{\n    std::vector<Genotype<Haplotype>> result {};\n    result.reserve(genotypes.size());\n    std::transform(std::cbegin(genotypes), std::cend(genotypes), std::back_inserter(result),\n                   [] (const auto& genotype) { return demote(genotype); });\n    return result;\n}\n\n} // namespace\n\nboost::optional<double>\nCancerCaller::calculate_model_posterior(const std::vector<Haplotype>& haplotypes,\n                                        const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                                        const Latents& latents) const\n{\n    if (has_normal_sample()) {\n        assert(latents.germline_model_);\n        const auto& germline_model = *latents.germline_model_;\n        haplotype_likelihoods.prime(normal_sample());\n        GermlineModel::InferredLatents normal_inferences;\n        if (latents.normal_germline_inferences_) {\n            normal_inferences = *latents.normal_germline_inferences_;\n        } else {\n            normal_inferences = germline_model.evaluate(latents.germline_genotypes_, haplotype_likelihoods);\n        }\n        const auto dummy_genotypes = demote_each(latents.cancer_genotypes_);\n        const auto dummy_inferences = germline_model.evaluate(dummy_genotypes, haplotype_likelihoods);\n        if (latents.noise_model_inferences_) {\n            return octopus::calculate_model_posterior(normal_inferences.log_evidence,\n                                                      dummy_inferences.log_evidence,\n                                                      latents.noise_model_inferences_->approx_log_evidence);\n        } else {\n            return octopus::calculate_model_posterior(normal_inferences.log_evidence,\n                                                      dummy_inferences.log_evidence);\n        }\n    } else {\n        // TODO\n        return boost::none;\n    }\n}\n\nauto pool_likelihood(const std::vector<SampleName>& samples,\n                     const std::vector<Haplotype>& haplotypes,\n                     const HaplotypeLikelihoodArray& haplotype_likelihoods)\n{\n    static const SampleName pooled_sample {\"pool\"};\n    auto result = merge_samples(samples, pooled_sample, haplotypes, haplotype_likelihoods);\n    result.prime(pooled_sample);\n    return result;\n}\n\nvoid CancerCaller::generate_germline_genotypes(Latents& latents, const std::vector<Haplotype>& haplotypes) const\n{\n    if (haplotypes.size() < 4) {\n        latents.germline_genotypes_ = generate_all_genotypes(haplotypes, parameters_.ploidy);\n    } else {\n        std::vector<GenotypeIndex> germline_genotype_indices {};\n        latents.germline_genotypes_ = generate_all_genotypes(haplotypes, parameters_.ploidy, germline_genotype_indices);\n        latents.germline_genotype_indices_ = std::move(germline_genotype_indices);\n    }\n}\n\nnamespace {\n\ntemplate <typename... T>\nauto zip(const T&... containers) -> boost::iterator_range<boost::zip_iterator<decltype(boost::make_tuple(std::begin(containers)...))>>\n{\n    auto zip_begin = boost::make_zip_iterator(boost::make_tuple(std::begin(containers)...));\n    auto zip_end   = boost::make_zip_iterator(boost::make_tuple(std::end(containers)...));\n    return boost::make_iterator_range(zip_begin, zip_end);\n}\n\ntemplate <typename Genotype_>\nauto zip_cref(const std::vector<Genotype_>& genotypes, const std::vector<double>& probabilities)\n{\n    using GenotypeReference = std::reference_wrapper<const Genotype_>;\n    std::vector<std::pair<GenotypeReference, double>> result {};\n    result.reserve(genotypes.size());\n    std::transform(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities), std::back_inserter(result),\n                   [] (const auto& g, const auto& p) noexcept { return std::make_pair(std::cref(g), p); });\n    return result;\n}\n\ntemplate <typename T>\nauto copy_greatest_probability_values(const std::vector<T>& values,\n                                      const std::vector<double>& probabilities,\n                                      const std::size_t n,\n                                      const boost::optional<double> min_include_probability = boost::none,\n                                      const boost::optional<double> max_exclude_probability = boost::none)\n{\n    assert(values.size() == probabilities.size());\n    if (values.size() <= n) return values;\n    auto value_probabilities = zip_cref(values, probabilities);\n    auto last_include_itr = std::next(std::begin(value_probabilities), n);\n    const auto probability_greater = [] (const auto& lhs, const auto& rhs) noexcept { return lhs.second > rhs.second; };\n    std::partial_sort(std::begin(value_probabilities), last_include_itr, std::end(value_probabilities), probability_greater);\n    if (min_include_probability) {\n        last_include_itr = std::upper_bound(std::begin(value_probabilities), last_include_itr, *min_include_probability,\n                                            [] (auto lhs, const auto& rhs) noexcept { return lhs > rhs.second; });\n        if (last_include_itr == std::begin(value_probabilities)) ++last_include_itr;\n    }\n    if (max_exclude_probability) {\n        last_include_itr = std::partition(last_include_itr, std::end(value_probabilities),\n                                          [&] (const auto& p) noexcept { return p.second > *max_exclude_probability; });\n    }\n    std::vector<T> result {};\n    result.reserve(std::distance(std::begin(value_probabilities), last_include_itr));\n    std::transform(std::begin(value_probabilities), last_include_itr, std::back_inserter(result),\n                   [] (const auto& p) { return p.first.get(); });\n    return result;\n}\n\ntemplate <typename G, typename I>\nauto copy_greatest_probability_genotypes(const std::vector<G>& genotypes,\n                                         const std::vector<I>& genotype_indices,\n                                         const std::vector<double>& probabilities,\n                                         const std::size_t n,\n                                         const boost::optional<double> min_include_probability = boost::none,\n                                         const boost::optional<double> max_exclude_probability = boost::none)\n{\n    assert(genotypes.size() == genotype_indices.size());\n    using GenotypeReference = std::reference_wrapper<const G>;\n    using GenotypeIndexReference = std::reference_wrapper<const I>;\n    std::vector<std::pair<GenotypeReference, GenotypeIndexReference>> zipped {};\n    zipped.reserve(genotypes.size());\n    std::transform(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(genotype_indices), std::back_inserter(zipped),\n                   [] (const auto& g, const auto& g_idx) { return std::make_pair(std::cref(g), std::cref(g_idx)); });\n    auto tmp = copy_greatest_probability_values(zipped, probabilities, n, min_include_probability, max_exclude_probability);\n    std::vector<G> result_genotypes {};\n    result_genotypes.reserve(tmp.size());\n    std::vector<I> result_indices {};\n    result_indices.reserve(tmp.size());\n    for (const auto& p : tmp) {\n        result_genotypes.push_back(p.first.get());\n        result_indices.push_back(p.second.get());\n    }\n    return std::make_pair(std::move(result_genotypes), std::move(result_indices));\n}\n\nauto calculate_posteriors_with_germline_likelihood_model(const std::vector<CancerGenotype<Haplotype>>& genotypes,\n                                                         const std::vector<CancerGenotypeIndex>& indices,\n                                                         const CancerGenotypePriorModel& prior_model,\n                                                         const model::ConstantMixtureGenotypeLikelihoodModel likelihood_model,\n                                                         const std::vector<SampleName>& samples)\n{\n    auto result = evaluate(indices, prior_model);\n    GenotypeIndex flattened_index(genotypes.front().ploidy());\n    for (const auto& sample : samples) {\n        likelihood_model.cache().prime(sample);\n        std::transform(std::cbegin(indices), std::cend(indices), std::cbegin(result), std::begin(result),\n                       [&] (const auto& genotype, auto curr) {\n                           auto itr = std::copy(std::cbegin(genotype.germline), std::cbegin(genotype.germline), std::begin(flattened_index));\n                           std::copy(std::cbegin(genotype.somatic), std::cbegin(genotype.somatic), itr);\n                           return curr + likelihood_model.evaluate(flattened_index);\n                       });\n    }\n    maths::normalise_exp(result);\n    return result;\n}\n\nvoid filter_with_germline_model(std::vector<CancerGenotype<Haplotype>>& genotypes,\n                                std::vector<CancerGenotypeIndex>& indices,\n                                const CancerGenotypePriorModel& prior_model,\n                                const model::ConstantMixtureGenotypeLikelihoodModel likelihood_model,\n                                const std::vector<SampleName>& samples,\n                                const std::size_t n)\n{\n    const auto germline_model_posteriors = calculate_posteriors_with_germline_likelihood_model(genotypes, indices, prior_model, likelihood_model, samples);\n    auto result = copy_greatest_probability_genotypes(genotypes, indices, germline_model_posteriors, n);\n    genotypes = std::move(result.first);\n    indices = std::move(result.second);\n}\n\n} // namespace\n\nvoid CancerCaller::generate_cancer_genotypes(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    const auto& germline_genotypes = latents.germline_genotypes_;\n    const auto num_haplotypes = latents.haplotypes_.get().size();\n    const auto num_germline_genotypes = germline_genotypes.size();\n    const auto max_possible_cancer_genotypes = num_haplotypes * num_germline_genotypes;\n    const auto max_allowed_cancer_genotypes = std::max(parameters_.max_genotypes, num_germline_genotypes);\n    if (max_possible_cancer_genotypes <= max_allowed_cancer_genotypes) {\n        generate_cancer_genotypes(latents, latents.germline_genotypes_);\n    } else if (has_normal_sample()) {\n        if (has_high_normal_contamination_risk(latents)) {\n            generate_cancer_genotypes_with_contaminated_normal(latents, haplotype_likelihoods);\n        } else {\n            generate_cancer_genotypes_with_clean_normal(latents, haplotype_likelihoods);\n        }\n    } else {\n        generate_cancer_genotypes_with_no_normal(latents, haplotype_likelihoods);\n    }\n}\n\nauto calculate_max_germline_genotype_bases(const unsigned max_genotypes, const unsigned num_haplotypes,\n                                           const unsigned somatic_ploidy)\n{\n    const auto num_somatic_genotypes = num_genotypes(num_haplotypes, somatic_ploidy);\n    return std::max(max_genotypes / num_somatic_genotypes, decltype(num_somatic_genotypes) {1});\n}\n\nvoid CancerCaller::generate_cancer_genotypes_with_clean_normal(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    const auto& haplotypes = latents.haplotypes_.get();\n    const auto& germline_genotypes = latents.germline_genotypes_;\n    const auto max_allowed_cancer_genotypes = std::max(parameters_.max_genotypes, germline_genotypes.size());\n    if (!latents.cancer_genotypes_.empty()) {\n        const auto max_old_cancer_genotype_bases = std::max(max_allowed_cancer_genotypes / haplotypes.size(), std::size_t {1});\n        const auto& cancer_genotype_posteriors = latents.somatic_model_inferences_.posteriors.genotype_probabilities;\n        if (latents.cancer_genotype_indices_) {\n            std::vector<CancerGenotype<Haplotype>> old_cancer_genotype_bases {};\n            std::vector<CancerGenotypeIndex> old_cancer_genotype_index_bases {};\n            std::tie(old_cancer_genotype_bases, old_cancer_genotype_index_bases)\n            = copy_greatest_probability_genotypes(latents.cancer_genotypes_, *latents.cancer_genotype_indices_,\n                                                  cancer_genotype_posteriors, max_old_cancer_genotype_bases);\n            latents.cancer_genotypes_ = extend_somatic_genotypes(old_cancer_genotype_bases, old_cancer_genotype_index_bases,\n                                                                 haplotypes, *latents.cancer_genotype_indices_);\n        } else {\n            const auto old_cancer_genotype_bases = copy_greatest_probability_values(latents.cancer_genotypes_, cancer_genotype_posteriors, max_old_cancer_genotype_bases);\n            latents.cancer_genotypes_ = extend_somatic_genotypes(old_cancer_genotype_bases, haplotypes);\n        }\n    } else {\n        assert(latents.germline_model_);\n        haplotype_likelihoods.prime(normal_sample());\n        if (latents.germline_genotype_indices_) {\n            latents.normal_germline_inferences_ = latents.germline_model_->evaluate(germline_genotypes,\n                                                                                    *latents.germline_genotype_indices_,\n                                                                                    haplotype_likelihoods);\n        } else {\n            latents.normal_germline_inferences_ = latents.germline_model_->evaluate(germline_genotypes, haplotype_likelihoods);\n        }\n        const auto& germline_normal_posteriors = latents.normal_germline_inferences_->posteriors.genotype_probabilities;\n        const auto max_germline_genotype_bases = calculate_max_germline_genotype_bases(max_allowed_cancer_genotypes, haplotypes.size(), latents.somatic_ploidy_);\n        if (latents.germline_genotype_indices_) {\n            std::vector<Genotype<Haplotype>> germline_bases;\n            std::vector<GenotypeIndex> germline_bases_indices;\n            std::tie(germline_bases, germline_bases_indices) = copy_greatest_probability_genotypes(germline_genotypes,\n                                                                                                   *latents.germline_genotype_indices_,\n                                                                                                   germline_normal_posteriors,\n                                                                                                   max_germline_genotype_bases,\n                                                                                                   1e-100, 1e-2);\n            std::vector<CancerGenotypeIndex> cancer_genotype_indices {};\n            latents.cancer_genotypes_ = generate_all_cancer_genotypes(germline_bases, germline_bases_indices,\n                                                                      haplotypes, cancer_genotype_indices,\n                                                                      latents.somatic_ploidy_);\n            if (latents.cancer_genotypes_.size() > 2 * max_allowed_cancer_genotypes) {\n                if (!latents.cancer_genotype_prior_model_->mutation_model().is_primed()) {\n                    latents.cancer_genotype_prior_model_->mutation_model().prime(haplotypes);\n                }\n                const model::ConstantMixtureGenotypeLikelihoodModel likelihood_model {haplotype_likelihoods, haplotypes};\n                filter_with_germline_model(latents.cancer_genotypes_, cancer_genotype_indices, *latents.cancer_genotype_prior_model_,\n                                           likelihood_model, samples_, max_allowed_cancer_genotypes);\n            }\n            latents.cancer_genotype_indices_ = std::move(cancer_genotype_indices);\n        } else {\n            auto germline_bases = copy_greatest_probability_values(germline_genotypes, germline_normal_posteriors,\n                                                                   max_germline_genotype_bases, 1e-100, 1e-2);\n            latents.cancer_genotypes_ = generate_all_cancer_genotypes(germline_bases, haplotypes, latents.somatic_ploidy_);\n        }\n    }\n}\n\nvoid CancerCaller::generate_cancer_genotypes_with_contaminated_normal(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    // TODO\n    generate_cancer_genotypes_with_clean_normal(latents, haplotype_likelihoods);\n}\n\nnamespace {\n\nstruct GenotypeReferenceEqual\n{\n    using GenotypeReference = std::reference_wrapper<const Genotype<Haplotype>>;\n    std::size_t operator()(const GenotypeReference& lhs, const GenotypeReference& rhs) const\n    {\n        return lhs.get() == rhs.get();\n    }\n};\n\ntemplate <typename BidirIt, typename T, typename Compare>\nBidirIt binary_find(BidirIt first, BidirIt last, const T& value, Compare cmp)\n{\n    const auto itr = std::lower_bound(first, last, value, std::move(cmp));\n    return (itr != last && *itr == value) ? itr : last;\n}\n\n} // namespace\n\nvoid CancerCaller::generate_cancer_genotypes_with_no_normal(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    const auto& haplotypes = latents.haplotypes_.get();\n    const auto& germline_genotypes = latents.germline_genotypes_;\n    const auto max_allowed_cancer_genotypes = std::max(parameters_.max_genotypes, germline_genotypes.size());\n    \n    if (!latents.cancer_genotypes_.empty()) {\n        const auto max_old_cancer_genotype_bases = std::max(max_allowed_cancer_genotypes / haplotypes.size(), std::size_t {1});\n        const auto& cancer_genotype_posteriors = latents.somatic_model_inferences_.posteriors.genotype_probabilities;\n        if (latents.cancer_genotype_indices_) {\n            std::vector<CancerGenotype<Haplotype>> old_cancer_genotype_bases {};\n            std::vector<CancerGenotypeIndex> old_cancer_genotype_index_bases {};\n            std::tie(old_cancer_genotype_bases, old_cancer_genotype_index_bases)\n                = copy_greatest_probability_genotypes(latents.cancer_genotypes_, *latents.cancer_genotype_indices_,\n                                                      cancer_genotype_posteriors, max_old_cancer_genotype_bases);\n            latents.cancer_genotypes_ = extend_somatic_genotypes(old_cancer_genotype_bases, old_cancer_genotype_index_bases,\n                                                                haplotypes, *latents.cancer_genotype_indices_);\n        } else {\n            const auto old_cancer_genotype_bases = copy_greatest_probability_values(latents.cancer_genotypes_, cancer_genotype_posteriors, max_old_cancer_genotype_bases);\n            latents.cancer_genotypes_ = extend_somatic_genotypes(old_cancer_genotype_bases, haplotypes);\n        }\n    } else {\n        const auto max_germline_genotype_bases = calculate_max_germline_genotype_bases(max_allowed_cancer_genotypes, haplotypes.size(), latents.somatic_ploidy_);\n        const auto& germline_genotype_posteriors = latents.germline_model_inferences_.posteriors.genotype_probabilities;\n        std::vector<double> germline_model_haplotype_posteriors(haplotypes.size());\n        if (latents.germline_genotype_indices_) {\n            GenotypeIndex buffer {};\n            for (std::size_t g {0}; g < germline_genotypes.size(); ++g) {\n                const auto& g_indices = (*latents.germline_genotype_indices_)[g];\n                for (auto idx : g_indices) {\n                    if (std::find(std::cbegin(buffer), std::cend(buffer), idx) == std::cend(buffer)) {\n                        germline_model_haplotype_posteriors[idx] += germline_genotype_posteriors[g];\n                    }\n                }\n                buffer.clear();\n            }\n        } else {\n            std::unordered_map<HaplotypeReference, double> tmp {};\n            tmp.reserve(haplotypes.size());\n            for (std::size_t g {0}; g < germline_genotypes.size(); ++g) {\n                for (const auto& haplotype : germline_genotypes[g].copy_unique_ref()) {\n                    tmp[haplotype] += germline_genotype_posteriors[g];\n                }\n                std::transform(std::cbegin(haplotypes), std::cend(haplotypes), std::begin(germline_model_haplotype_posteriors),\n                               [&tmp] (const auto& haplotype) { return tmp.at(haplotype); });\n            }\n        }\n        const auto max_germline_haplotype_bases = max_num_elements(max_germline_genotype_bases, parameters_.ploidy);\n        const auto top_haplotypes = copy_greatest_probability_values(haplotypes, germline_model_haplotype_posteriors,\n                                                                     max_germline_haplotype_bases);\n        auto germline_bases = generate_all_genotypes(top_haplotypes, parameters_.ploidy);\n        if (latents.germline_genotype_indices_) {\n            std::vector<GenotypeIndex> germline_bases_indices;\n            germline_bases_indices.reserve(germline_bases.size());\n            if (std::is_sorted(std::cbegin(germline_genotypes), std::cend(germline_genotypes), GenotypeLess {})) {\n                std::sort(std::begin(germline_bases), std::end(germline_bases), GenotypeLess {});\n                auto genotype_itr = std::cbegin(germline_genotypes);\n                for (const auto& genotype : germline_bases) {\n                    const auto match_itr = binary_find(genotype_itr, std::cend(germline_genotypes), genotype, GenotypeLess {});\n                    assert(match_itr != std::cend(germline_genotypes));\n                    const auto idx = std::distance(std::cbegin(germline_genotypes), match_itr);\n                    germline_bases_indices.push_back((*latents.germline_genotype_indices_)[idx]);\n                    genotype_itr = std::next(match_itr);\n                }\n            } else {\n                using GenotypeReference = std::reference_wrapper<const Genotype<Haplotype>>;\n                using GenotypeReferenceIndexMap = std::unordered_map<GenotypeReference, std::size_t,\n                                                                     std::hash<GenotypeReference>, GenotypeReferenceEqual>;\n                GenotypeReferenceIndexMap genotype_indices {};\n                genotype_indices.reserve(germline_genotypes.size());\n                for (std::size_t i {0}; i < germline_genotypes.size(); ++i) {\n                    genotype_indices.emplace(std::cref(germline_genotypes[i]), i);\n                }\n                for (const auto& genotype : germline_bases) {\n                    germline_bases_indices.push_back((*latents.germline_genotype_indices_)[genotype_indices.at(genotype)]);\n                }\n            }\n            std::vector<CancerGenotypeIndex> cancer_genotype_indices {};\n            latents.cancer_genotypes_ = generate_all_cancer_genotypes(germline_bases, germline_bases_indices,\n                                                                      latents.haplotypes_, cancer_genotype_indices,\n                                                                      latents.somatic_ploidy_);\n            if (latents.cancer_genotypes_.size() > 2 * max_allowed_cancer_genotypes) {\n                if (!latents.cancer_genotype_prior_model_->mutation_model().is_primed()) {\n                    latents.cancer_genotype_prior_model_->mutation_model().prime(latents.haplotypes_);\n                }\n                const model::ConstantMixtureGenotypeLikelihoodModel likelihood_model {haplotype_likelihoods, latents.haplotypes_};\n                filter_with_germline_model(latents.cancer_genotypes_, cancer_genotype_indices, *latents.cancer_genotype_prior_model_,\n                                           likelihood_model, samples_, max_allowed_cancer_genotypes);\n            }\n            latents.cancer_genotype_indices_ = std::move(cancer_genotype_indices);\n        } else {\n            latents.cancer_genotypes_ = generate_all_cancer_genotypes(germline_bases, haplotypes, latents.somatic_ploidy_);\n        }\n    }\n}\n\nvoid CancerCaller::generate_cancer_genotypes(Latents& latents, const std::vector<Genotype<Haplotype>>& germline_genotypes) const\n{\n    if (latents.germline_genotype_indices_) {\n        std::vector<CancerGenotypeIndex> cancer_genotype_indices {};\n        latents.cancer_genotypes_ = generate_all_cancer_genotypes(germline_genotypes, *latents.germline_genotype_indices_,\n                                                                  latents.haplotypes_, cancer_genotype_indices,\n                                                                  latents.somatic_ploidy_);\n        latents.cancer_genotype_indices_ = std::move(cancer_genotype_indices);\n    } else {\n        latents.cancer_genotypes_ = generate_all_cancer_genotypes(germline_genotypes, latents.haplotypes_, latents.somatic_ploidy_);\n    }\n}\n\nbool CancerCaller::has_high_normal_contamination_risk(const Latents& latents) const\n{\n    return parameters_.normal_contamination_risk == Parameters::NormalContaminationRisk::high;\n}\n\nvoid CancerCaller::evaluate_germline_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(!(latents.haplotypes_.get().empty() || latents.germline_genotypes_.empty()));\n    latents.germline_prior_model_ = make_germline_prior_model(latents.haplotypes_);\n    latents.germline_model_ = std::make_unique<GermlineModel>(*latents.germline_prior_model_);\n    const auto pooled_likelihoods = pool_likelihood(samples_,  latents.haplotypes_, haplotype_likelihoods);\n    if (latents.germline_genotype_indices_) {\n        latents.germline_prior_model_->prime(latents.haplotypes_);\n        latents.germline_model_->prime(latents.haplotypes_);\n        latents.germline_model_inferences_ = latents.germline_model_->evaluate(latents.germline_genotypes_,\n                                                                               *latents.germline_genotype_indices_,\n                                                                               pooled_likelihoods);\n    } else {\n        latents.germline_model_inferences_ = latents.germline_model_->evaluate(latents.germline_genotypes_, pooled_likelihoods);\n    }\n}\n\nvoid CancerCaller::evaluate_cnv_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(!latents.germline_genotypes_.empty() && latents.germline_prior_model_);\n    auto cnv_model_priors = get_cnv_model_priors(*latents.germline_prior_model_);\n    CNVModel::AlgorithmParameters params {};\n    if (parameters_.max_vb_seeds) params.max_seeds = *parameters_.max_vb_seeds;\n    params.target_max_memory = this->target_max_memory();\n    CNVModel cnv_model {samples_, cnv_model_priors};\n    if (latents.germline_genotype_indices_) {\n        cnv_model.prime(latents.haplotypes_);\n        latents.cnv_model_inferences_ = cnv_model.evaluate(latents.germline_genotypes_, *latents.germline_genotype_indices_,\n                                                           haplotype_likelihoods);\n    } else {\n        latents.cnv_model_inferences_ = cnv_model.evaluate(latents.germline_genotypes_, haplotype_likelihoods);\n    }\n}\n\nvoid CancerCaller::evaluate_somatic_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(latents.germline_prior_model_ && !latents.cancer_genotypes_.empty());\n    assert(latents.cancer_genotype_prior_model_);\n    auto somatic_model_priors = get_somatic_model_priors(*latents.cancer_genotype_prior_model_, latents.somatic_ploidy_);\n    SomaticModel::AlgorithmParameters params {};\n    if (parameters_.max_vb_seeds) params.max_seeds = *parameters_.max_vb_seeds;\n    params.target_max_memory = this->target_max_memory();\n    SomaticModel model {samples_, somatic_model_priors, params};\n    if (latents.cancer_genotype_indices_) {\n        assert(latents.cancer_genotype_prior_model_->germline_model().is_primed());\n        if (!latents.cancer_genotype_prior_model_->mutation_model().is_primed()) {\n            latents.cancer_genotype_prior_model_->mutation_model().prime(latents.haplotypes_);\n        }\n        model.prime(latents.haplotypes_);\n        latents.somatic_model_inferences_ = model.evaluate(latents.cancer_genotypes_, *latents.cancer_genotype_indices_, haplotype_likelihoods);\n    } else {\n        latents.somatic_model_inferences_ = model.evaluate(latents.cancer_genotypes_, haplotype_likelihoods);\n    }\n}\n\nauto get_high_posterior_genotypes(const std::vector<CancerGenotype<Haplotype>>& genotypes,\n                                  const model::SomaticSubcloneModel::InferredLatents& latents)\n{\n    return copy_greatest_probability_values(genotypes, latents.posteriors.genotype_probabilities, 10, 1e-3);\n}\n\nvoid CancerCaller::evaluate_noise_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    if (has_normal_sample() && !has_high_normal_contamination_risk(latents)) {\n        if (!latents.normal_germline_inferences_) {\n            assert(latents.germline_model_);\n            haplotype_likelihoods.prime(normal_sample());\n            if (latents.germline_genotype_indices_) {\n                latents.normal_germline_inferences_ = latents.germline_model_->evaluate(latents.germline_genotypes_,\n                                                                                        *latents.germline_genotype_indices_,\n                                                                                        haplotype_likelihoods);\n            } else {\n                latents.normal_germline_inferences_ = latents.germline_model_->evaluate(latents.germline_genotypes_,\n                                                                                        haplotype_likelihoods);\n            }\n        }\n        assert(latents.cancer_genotype_prior_model_);\n        auto noise_model_priors = get_noise_model_priors(*latents.cancer_genotype_prior_model_, latents.somatic_ploidy_);\n        const SomaticModel noise_model {{*parameters_.normal_sample}, noise_model_priors};\n        auto noise_genotypes = get_high_posterior_genotypes(latents.cancer_genotypes_, latents.somatic_model_inferences_);\n        latents.noise_model_inferences_ = noise_model.evaluate(noise_genotypes, haplotype_likelihoods);\n    }\n}\n\nvoid CancerCaller::set_model_priors(Latents& latents) const\n{\n    if (has_normal_sample()) {\n        latents.model_priors_ = {.09, 0.01, 0.9};\n    } else {\n        latents.model_priors_ = {.09, 0.001, 0.909};\n    }\n}\n\nvoid CancerCaller::set_model_posteriors(Latents& latents) const\n{\n    const auto& germline_inferences = latents.germline_model_inferences_;\n    const auto& cnv_inferences      = latents.cnv_model_inferences_;\n    const auto& somatic_inferences  = latents.somatic_model_inferences_;\n    const auto& model_priors        = latents.model_priors_;\n    if (debug_log_) {\n        stream(*debug_log_) << \"Germline model evidence: \" << germline_inferences.log_evidence;\n        stream(*debug_log_) << \"CNV model evidence:      \" << cnv_inferences.approx_log_evidence;\n        stream(*debug_log_) << \"Somatic model evidence:  \" << somatic_inferences.approx_log_evidence;\n    }\n    const auto germline_model_jlp = std::log(model_priors.germline) + germline_inferences.log_evidence;\n    const auto cnv_model_jlp      = std::log(model_priors.cnv) + cnv_inferences.approx_log_evidence;\n    const auto somatic_model_jlp  = std::log(model_priors.somatic) + somatic_inferences.approx_log_evidence;\n    const auto norm = maths::log_sum_exp(germline_model_jlp, cnv_model_jlp, somatic_model_jlp);\n    latents.model_posteriors_.germline = std::exp(germline_model_jlp - norm);\n    latents.model_posteriors_.cnv      = std::exp(cnv_model_jlp - norm);\n    latents.model_posteriors_.somatic  = std::exp(somatic_model_jlp - norm);\n    const auto check_sum = latents.model_posteriors_.germline + latents.model_posteriors_.cnv + latents.model_posteriors_.somatic;\n    if (check_sum > 1.0) {\n        latents.model_posteriors_.germline /= check_sum;\n        latents.model_posteriors_.cnv /= check_sum;\n        latents.model_posteriors_.somatic /= check_sum;\n    }\n}\n\nCancerCaller::CNVModel::Priors\nCancerCaller::get_cnv_model_priors(const GenotypePriorModel& prior_model) const\n{\n    using Priors = CNVModel::Priors;\n    Priors::GenotypeMixturesDirichletAlphaMap cnv_alphas {};\n    cnv_alphas.reserve(samples_.size());\n    for (const auto& sample : samples_) {\n        if (has_normal_sample() && sample == normal_sample()) {\n            Priors::GenotypeMixturesDirichletAlphas sample_alphas(parameters_.ploidy, parameters_.concentrations.cnv.normal);\n            cnv_alphas.emplace(sample, std::move(sample_alphas));\n        } else {\n            Priors::GenotypeMixturesDirichletAlphas sample_alphas(parameters_.ploidy, parameters_.concentrations.cnv.tumour);\n            cnv_alphas.emplace(sample, std::move(sample_alphas));\n        }\n    }\n    return Priors {prior_model, std::move(cnv_alphas)};\n}\n\nauto make_dirichlet_alphas(unsigned n_germline, double germline, unsigned n_somatic, double somatic)\n{\n    model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas result(n_germline + n_somatic);\n    std::fill_n(std::begin(result), n_germline, germline);\n    std::fill_n(std::rbegin(result), n_somatic, somatic);\n    return result;\n}\n\nCancerCaller::SomaticModel::Priors\nCancerCaller::get_somatic_model_priors(const CancerGenotypePriorModel& prior_model, const unsigned somatic_ploidy) const\n{\n    using Priors = SomaticModel::Priors;\n    Priors::GenotypeMixturesDirichletAlphaMap alphas {};\n    alphas.reserve(samples_.size());\n    for (const auto& sample : samples_) {\n        if (has_normal_sample() && sample == normal_sample()) {\n            alphas.emplace(sample, make_dirichlet_alphas(parameters_.ploidy, parameters_.concentrations.somatic.normal_germline,\n                                                         somatic_ploidy, parameters_.concentrations.somatic.normal_somatic));\n        } else {\n            alphas.emplace(sample, make_dirichlet_alphas(parameters_.ploidy, parameters_.concentrations.somatic.tumour_germline,\n                                                         somatic_ploidy, parameters_.concentrations.somatic.tumour_somatic));\n        }\n    }\n    return Priors {prior_model, std::move(alphas)};\n}\n\nCancerCaller::SomaticModel::Priors\nCancerCaller::get_noise_model_priors(const CancerGenotypePriorModel& prior_model, const unsigned somatic_ploidy) const\n{\n    // The noise model is intended to capture noise that may also be present in the normal sample,\n    // hence all samples have the same prior alphas.\n    using Priors = SomaticModel::Priors;\n    auto noise_alphas = make_dirichlet_alphas(parameters_.ploidy, parameters_.concentrations.somatic.normal_germline,\n                                              somatic_ploidy, parameters_.concentrations.somatic.tumour_somatic);\n    Priors::GenotypeMixturesDirichletAlphaMap alphas {};\n    alphas.reserve(samples_.size());\n    for (const auto& sample : samples_) {\n        alphas.emplace(sample, noise_alphas);\n    }\n    return Priors {prior_model, std::move(alphas)};\n}\n\nCancerCaller::CNVModel::Priors\nCancerCaller::get_normal_noise_model_priors(const GenotypePriorModel& prior_model) const\n{\n    using Priors = CNVModel::Priors;\n    Priors::GenotypeMixturesDirichletAlphaMap cnv_alphas {};\n    if (has_normal_sample()) {\n        Priors::GenotypeMixturesDirichletAlphas sample_alphas(parameters_.ploidy, 0.5);\n        cnv_alphas.emplace(normal_sample(), std::move(sample_alphas));\n    }\n    return Priors {prior_model, std::move(cnv_alphas)};\n}\n\nstd::vector<std::unique_ptr<VariantCall>>\nCancerCaller::call_variants(const std::vector<Variant>& candidates,\n                                   const Caller::Latents& latents) const\n{\n    return call_variants(candidates, dynamic_cast<const Latents&>(latents));\n}\n\nnamespace {\n\nusing VariantReference  = std::reference_wrapper<const Variant>;\nusing VariantPosteriorVector = std::vector<std::pair<VariantReference, Phred<double>>>;\n\nauto compute_marginal_credible_interval(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas& alphas,\n                                        const std::size_t k, const double mass)\n{\n    const auto a0 = std::accumulate(std::cbegin(alphas), std::cend(alphas), 0.0);\n    return maths::beta_hdi(alphas[k], a0 - alphas[k], mass);\n}\n\nauto compute_marginal_credible_intervals(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas& alphas,\n                                         const double mass)\n{\n    const auto a0 = std::accumulate(std::cbegin(alphas), std::cend(alphas), 0.0);\n    std::vector<std::pair<double, double>> result {};\n    result.reserve(alphas.size());\n    for (const auto& alpha : alphas) {\n        result.push_back(maths::beta_hdi(alpha, a0 - alpha, mass));\n    }\n    return result;\n}\n\nusing CredibleRegionMap = std::unordered_map<SampleName, std::vector<std::pair<double, double>>>;\n\nauto compute_marginal_credible_intervals(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphaMap& alphas,\n                                         const double mass)\n{\n    CredibleRegionMap result {};\n    result.reserve(alphas.size());\n    for (const auto& p : alphas) {\n        result.emplace(p.first, compute_marginal_credible_intervals(p.second, mass));\n    }\n    return result;\n}\n\nauto compute_credible_somatic_mass(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas& alphas,\n                                   const unsigned somatic_ploidy, const double min_credible_somatic_frequency)\n{\n    if (somatic_ploidy == 1) {\n        return maths::dirichlet_marginal_sf(alphas, alphas.size() - 1, min_credible_somatic_frequency);\n    } else {\n        double inv_result {1.0};\n        for (unsigned i {1}; i <= somatic_ploidy; ++i) {\n            inv_result *= maths::dirichlet_marginal_cdf(alphas, alphas.size() - i, min_credible_somatic_frequency);\n        }\n        return 1.0 - inv_result;\n    }\n}\n\nauto compute_credible_somatic_mass(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphaMap& alphas,\n                                   const unsigned somatic_ploidy, const double min_credible_somatic_frequency)\n{\n    double inv_result {1.0};\n    for (const auto& p : alphas) {\n        if (somatic_ploidy == 1) {\n            inv_result *= maths::dirichlet_marginal_cdf(p.second, p.second.size() - 1, min_credible_somatic_frequency);\n        } else {\n            inv_result *= 1.0 - compute_credible_somatic_mass(p.second, somatic_ploidy, min_credible_somatic_frequency);\n        }\n    }\n    return 1.0 - inv_result;\n}\n\nauto compute_map_somatic_vaf(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas& alphas,\n                             const unsigned somatic_ploidy)\n{\n    double result {0.0};\n    for (unsigned i {1}; i <= somatic_ploidy; ++i) {\n        result = std::max(maths::dirichlet_expectation(alphas.size() - i, alphas), result);\n    }\n    return result;\n}\n\nusing SomaticVAFMap = std::unordered_map<SampleName, double>;\n\nauto compute_map_somatic_vafs(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphaMap& alphas,\n                              const unsigned somatic_ploidy)\n{\n    SomaticVAFMap result {};\n    result.reserve(alphas.size());\n    for (const auto& p : alphas) {\n        result.emplace(p.first, compute_map_somatic_vaf(p.second, somatic_ploidy));\n    }\n    return result;\n}\n\nstruct GermlineVariantCall : Mappable<GermlineVariantCall>\n{\n    GermlineVariantCall() = delete;\n    GermlineVariantCall(const std::pair<VariantReference, Phred<double>>& p)\n    : variant {p.first}\n    , posterior {p.second}\n    {}\n    GermlineVariantCall(const Variant& variant, Phred<double> posterior)\n    : variant {variant}\n    , posterior {posterior}\n    {}\n    \n    const GenomicRegion& mapped_region() const noexcept { return octopus::mapped_region(variant.get()); }\n    \n    VariantReference variant;\n    Phred<double> posterior, segregation_quality;\n};\n\nusing GermlineVariantCalls = std::vector<GermlineVariantCall>;\n\nstruct SomaticVariantCall : Mappable<SomaticVariantCall>\n{\n    SomaticVariantCall() = delete;\n    SomaticVariantCall(const std::pair<VariantReference, Phred<double>>& p)\n    : variant {p.first}, posterior {p.second} {}\n    SomaticVariantCall(const Variant& variant, Phred<double> posterior)\n    : variant {variant}, posterior {posterior} {}\n    \n    const GenomicRegion& mapped_region() const noexcept { return octopus::mapped_region(variant.get()); }\n    \n    VariantReference variant;\n    Phred<double> posterior, segregation_quality;\n};\n\nusing SomaticVariantCalls = std::vector<SomaticVariantCall>;\n\nstruct GermlineGenotypeCall\n{\n    template <typename T>\n    GermlineGenotypeCall(T&& genotype, Phred<double> posterior)\n    : genotype {std::forward<T>(genotype)}\n    , somatic {}\n    , posterior {posterior}\n    {}\n    template <typename T, typename A>\n    GermlineGenotypeCall(T&& genotype, A&& somatic, Phred<double> posterior)\n    : genotype {std::forward<T>(genotype)}\n    , somatic {std::forward<A>(somatic)}\n    , posterior {posterior}\n    {}\n    \n    Genotype<Allele> genotype, somatic;\n    Phred<double> posterior;\n};\n\nusing GermlineGenotypeCalls = std::vector<GermlineGenotypeCall>;\n\nstruct CancerGenotypeCall\n{\n    template <typename T>\n    CancerGenotypeCall(T&& genotype, Phred<double> posterior)\n    : genotype {std::forward<T>(genotype)}, posterior {posterior} {}\n    \n    CancerGenotype<Allele> genotype;\n    Phred<double> posterior;\n    CredibleRegionMap credible_regions;\n    SomaticVAFMap somatic_map_vafs;\n};\n\nusing CancerGenotypeCalls = std::vector<CancerGenotypeCall>;\n\ntemplate <typename L>\nauto find_map_genotype(const L& posteriors)\n{\n    return std::max_element(std::cbegin(posteriors), std::cend(posteriors),\n                            [] (const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; });\n}\n\n// germline variant posterior calculations\n\ntemplate <typename M>\nPhred<double> marginalise(const Allele& allele, const M& genotype_posteriors)\n{\n    auto p = std::accumulate(std::cbegin(genotype_posteriors), std::cend(genotype_posteriors),\n                             0.0, [&allele] (const auto curr, const auto& p) {\n                                 return curr + (contains(p.first, allele) ? 0.0 : p.second);\n                             });\n    return probability_to_phred(p);\n}\n\ntemplate <typename M>\nVariantPosteriorVector compute_candidate_posteriors(const std::vector<Variant>& candidates, const M& genotype_posteriors)\n{\n    VariantPosteriorVector result {};\n    result.reserve(candidates.size());\n    for (const auto& candidate : candidates) {\n        result.emplace_back(candidate, marginalise(candidate.alt_allele(), genotype_posteriors));\n    }\n    return result;\n}\n\n// segregation probability\n\nusing BigFloat = boost::multiprecision::number<boost::multiprecision::cpp_dec_float<1000>>;\n\nBigFloat marginalise(const Allele& allele, const std::vector<Genotype<Haplotype>>& genotypes, const std::vector<double>& probabilities)\n{\n    assert(genotypes.size() == probabilities.size());\n    auto inv_result = std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities),\n                                         0.0, std::plus<> {}, [&allele] (const auto& genotype, const auto probability) {\n        return contains(genotype, allele) ? 0.0 : probability; });\n    return BigFloat {1.0} - BigFloat {inv_result};\n}\n\nbool is_somatic(const Allele& allele, const CancerGenotype<Haplotype>& genotype)\n{\n    return contains(genotype.somatic(), allele) && !contains(genotype.germline(), allele);\n}\n\nBigFloat marginalise(const Allele& allele, const std::vector<CancerGenotype<Haplotype>>& genotypes, const std::vector<double>& probabilities,\n                     const BigFloat somatic_mass_complement)\n{\n    assert(genotypes.size() == probabilities.size());\n    const BigFloat contained_complement {std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities),\n                                                  0.0, std::plus<> {}, [&] (const auto& genotype, const auto probability) {\n        return contains(genotype, allele) ? 0.0 : probability; })};\n    BigFloat somatic_complement {std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities),\n                                                 0.0, std::plus<> {}, [&] (const auto& genotype, const auto probability) {\n        return is_somatic(allele, genotype) ? probability : 0.0; })};\n    somatic_complement *= somatic_mass_complement;\n    const BigFloat result_complement {contained_complement + somatic_complement};\n    assert(result_complement >= 0.0 && result_complement <= 1.0);\n    return BigFloat {1.0} - result_complement;\n}\n\nPhred<double> probability_true_to_phred(BigFloat probability_true)\n{\n    using boost::multiprecision::nextafter;\n    if (probability_true <= 0.0) probability_true = nextafter(BigFloat {0.0}, BigFloat {1.0});\n    if (probability_true >= 1.0) probability_true = nextafter(BigFloat {1.0}, BigFloat {0.0});\n    const BigFloat probability_false {BigFloat {1.0} - probability_true};\n    const BigFloat ln_probability_false {boost::multiprecision::log(probability_false)};\n    const BigFloat phred_probability_false {ln_probability_false / -maths::constants::ln10Div10<>};\n    assert(phred_probability_false >= 0.0);\n    return Phred<double> {phred_probability_false.convert_to<double>()};\n}\n\nPhred<double>\ncalculate_segregation_probability(const Allele& allele,\n                                  const std::vector<Genotype<Haplotype>>& germline_genotypes,\n                                  const std::vector<CancerGenotype<Haplotype>>& cancer_genotypes,\n                                  const std::vector<double>& germline_genotype_probabilities,\n                                  const std::vector<double>& cnv_genotype_probabilities,\n                                  const std::vector<double>& cancer_genotype_probabilities,\n                                  const BigFloat germline_probability,\n                                  const BigFloat cnv_probability,\n                                  const BigFloat somatic_probability,\n                                  const BigFloat somatic_mass)\n{\n    auto prob_germline_segregates = marginalise(allele, germline_genotypes, germline_genotype_probabilities);\n    prob_germline_segregates *= germline_probability;\n    auto prob_cnv_segregates = marginalise(allele, germline_genotypes, cnv_genotype_probabilities);\n    prob_cnv_segregates *= cnv_probability;\n    auto prob_somatic_segregates = marginalise(allele, cancer_genotypes, cancer_genotype_probabilities, BigFloat {1.0} - somatic_mass);\n    prob_somatic_segregates *= somatic_probability;\n    const BigFloat prob_segregates {prob_germline_segregates + prob_cnv_segregates + prob_somatic_segregates};\n    return probability_true_to_phred(prob_segregates);\n}\n\nPhred<double>\ncalculate_segregation_probability(const Allele& allele,\n                                  const std::vector<Genotype<Haplotype>>& germline_genotypes,\n                                  const std::vector<CancerGenotype<Haplotype>>& cancer_genotypes,\n                                  const std::vector<double>& germline_genotype_probabilities,\n                                  const std::vector<double>& cnv_genotype_probabilities,\n                                  const std::vector<double>& cancer_genotype_probabilities,\n                                  const double germline_probability,\n                                  const double cnv_probability,\n                                  const double somatic_probability,\n                                  const double somatic_mass)\n{\n    BigFloat germline_bf {germline_probability}, cnv_bf {cnv_probability}, somatic_bf {somatic_probability};\n    const BigFloat norm {germline_bf + cnv_bf + somatic_bf};\n    germline_bf /= norm; cnv_bf /= norm; somatic_bf /= norm;\n    return calculate_segregation_probability(allele, germline_genotypes, cancer_genotypes,\n                                             germline_genotype_probabilities, cnv_genotype_probabilities, cancer_genotype_probabilities,\n                                             germline_bf, cnv_bf, somatic_bf, BigFloat {somatic_mass});\n}\n\nPhred<double> calculate_somatic_posterior(const double somatic_model_posterior, const double somatic_mass)\n{\n    BigFloat somatic_posterior {somatic_model_posterior};\n    somatic_posterior *= somatic_mass;\n    return probability_true_to_phred(somatic_posterior);\n}\n\n// germline variant calling\n\nbool contains_alt(const Genotype<Haplotype>& genotype_call, const VariantReference& candidate)\n{\n    return includes(genotype_call, candidate.get().alt_allele());\n}\n\nauto call_candidates(const VariantPosteriorVector& candidate_posteriors,\n                     const Genotype<Haplotype>& genotype_call,\n                     const Phred<double> min_posterior)\n{\n    GermlineVariantCalls calls {};\n    calls.reserve(candidate_posteriors.size());\n    std::vector<VariantReference> uncalled {};\n    for (const auto& p : candidate_posteriors) {\n        if (p.second >= min_posterior && contains_alt(genotype_call, p.first)) {\n            calls.emplace_back(p.first, p.second);\n        } else {\n            uncalled.emplace_back(p.first);\n        }\n    }\n    return std::make_pair(std::move(calls), std::move(uncalled));\n}\n\n// somatic variant posterior\n\nBigFloat marginalise_somatic(const Allele& allele, const std::vector<CancerGenotype<Haplotype>>& genotypes,\n                             const std::vector<double>& probabilities)\n{\n    BigFloat result_complement {std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities),\n                                                   0.0, std::plus<> {}, [&allele] (const auto& genotype, auto probability) {\n        return is_somatic(allele, genotype) ? 0.0 : probability; })};\n    return BigFloat {1.0} - result_complement;\n}\n\nauto compute_somatic_variant_posteriors(const std::vector<VariantReference>& candidates,\n                                        const std::vector<CancerGenotype<Haplotype>>& cancer_genotypes,\n                                        const std::vector<double>& cancer_genotype_posteriors,\n                                        const BigFloat somatic_posterior)\n{\n    VariantPosteriorVector result {};\n    result.reserve(candidates.size());\n    for (const auto& candidate : candidates) {\n        auto p = marginalise_somatic(candidate.get().alt_allele(), cancer_genotypes, cancer_genotype_posteriors);\n        p *= somatic_posterior;\n        result.emplace_back(candidate, probability_true_to_phred(p));\n    }\n    return result;\n}\n\nauto compute_somatic_variant_posteriors(const std::vector<VariantReference>& candidates,\n                                        const std::vector<CancerGenotype<Haplotype>>& cancer_genotypes,\n                                        const std::vector<double>& cancer_genotype_posteriors,\n                                        const Phred<double> somatic_posterior)\n{\n    return compute_somatic_variant_posteriors(candidates, cancer_genotypes, cancer_genotype_posteriors,\n                                              BigFloat {somatic_posterior.probability_true().value});\n}\n\nauto call_somatic_variants(const VariantPosteriorVector& somatic_variant_posteriors,\n                           const CancerGenotype<Haplotype>& called_genotype,\n                           const Phred<double> min_posterior)\n{\n    SomaticVariantCalls result {};\n    result.reserve(somatic_variant_posteriors.size());\n    std::copy_if(std::begin(somatic_variant_posteriors), std::end(somatic_variant_posteriors), std::back_inserter(result),\n                 [min_posterior, &called_genotype] (const auto& p) {\n                     return p.second >= min_posterior && includes(called_genotype, p.first.get().alt_allele());\n                 });\n    return result;\n}\n\nPhred<double>\nmarginalise(const CancerGenotype<Allele>& genotype, const std::vector<CancerGenotype<Haplotype>>& genotypes,\n            const std::vector<double>& genotype_posteriors)\n{\n    auto p = std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(genotype_posteriors),\n                                0.0, std::plus<> {},  [&genotype] (const auto& g, auto probability) {\n                                    return contains(g, genotype) ? 0.0 : probability; });\n    return probability_to_phred(p);\n}\n\nauto call_somatic_genotypes(const CancerGenotype<Haplotype>& called_genotype,\n                            const std::vector<GenomicRegion>& called_somatic_regions,\n                            const std::vector<CancerGenotype<Haplotype>>& genotypes,\n                            const std::vector<double>& genotype_posteriors,\n                            const CredibleRegionMap& credible_regions,\n                            const SomaticVAFMap& somatic_vafs)\n{\n    CancerGenotypeCalls result {};\n    result.reserve(called_somatic_regions.size());\n    for (const auto& region : called_somatic_regions) {\n        auto genotype_chunk = copy<Allele>(called_genotype, region);\n        auto posterior = marginalise(genotype_chunk, genotypes, genotype_posteriors);\n        result.emplace_back(std::move(genotype_chunk), posterior);\n        result.back().credible_regions = credible_regions;\n        result.back().somatic_map_vafs = somatic_vafs;\n    }\n    return result;\n}\n\n// output\n\noctopus::VariantCall::GenotypeCall demote(GermlineGenotypeCall call)\n{\n    return octopus::VariantCall::GenotypeCall {std::move(call.genotype), call.posterior};\n}\n\nstd::unique_ptr<octopus::VariantCall>\ntransform_germline_call(GermlineVariantCall&& variant_call, GermlineGenotypeCall&& genotype_call,\n                        const std::vector<SampleName>& samples, const std::vector<SampleName>& somatic_samples)\n{\n    std::vector<std::pair<SampleName, Call::GenotypeCall>> genotypes {};\n    for (const auto& sample : samples) {\n        if (std::find(std::cbegin(somatic_samples), std::cend(somatic_samples), sample) == std::cend(somatic_samples)) {\n            genotypes.emplace_back(sample, demote(genotype_call));\n        } else {\n            auto copy = genotype_call;\n            for (auto allele : genotype_call.somatic) copy.genotype.emplace(allele);\n            genotypes.emplace_back(sample, demote(std::move(copy)));\n        }\n    }\n    return std::make_unique<octopus::GermlineVariantCall>(variant_call.variant.get(), std::move(genotypes),\n                                                          variant_call.segregation_quality, variant_call.posterior);\n}\n\ntemplate <typename Container, typename T>\nauto find_index(const Container& values, const T& value)\n{\n    const auto itr = std::find(std::cbegin(values), std::cend(values), value);\n    return itr != std::cend(values) ? std::distance(std::cbegin(values), itr) : -1;\n}\n\nauto transform_somatic_calls(SomaticVariantCalls&& somatic_calls, CancerGenotypeCalls&& genotype_calls,\n                             const std::vector<SampleName>& somatic_samples)\n{\n    std::vector<std::unique_ptr<octopus::VariantCall>> result {};\n    result.reserve(somatic_calls.size());\n    std::transform(std::make_move_iterator(std::begin(somatic_calls)), std::make_move_iterator(std::end(somatic_calls)),\n                   std::make_move_iterator(std::begin(genotype_calls)), std::back_inserter(result),\n                   [&somatic_samples] (auto&& variant_call, auto&& genotype_call) -> std::unique_ptr<octopus::VariantCall> {\n                       std::unordered_map<SampleName, SomaticCall::GenotypeCredibleRegions> credible_regions {};\n                       const auto germline_ploidy = genotype_call.genotype.germline_ploidy();\n                       for (const auto& p : genotype_call.credible_regions) {\n                           SomaticCall::GenotypeCredibleRegions sample_credible_regions {};\n                           sample_credible_regions.germline.reserve(germline_ploidy);\n                           std::copy(std::cbegin(p.second), std::prev(std::cend(p.second)),\n                                     std::back_inserter(sample_credible_regions.germline));\n                           if (std::find(std::cbegin(somatic_samples), std::cend(somatic_samples), p.first) != std::cend(somatic_samples)) {\n                               auto somatic_idx = find_index(genotype_call.genotype.somatic(), variant_call.variant.get().alt_allele());\n                               sample_credible_regions.somatic = p.second[germline_ploidy + somatic_idx];\n                           }\n                           credible_regions.emplace(p.first, std::move(sample_credible_regions));\n                       }\n                       return std::make_unique<SomaticCall>(variant_call.variant.get(), std::move(genotype_call.genotype),\n                                                            genotype_call.posterior, std::move(credible_regions),\n                                                            genotype_call.somatic_map_vafs,\n                                                            variant_call.segregation_quality, variant_call.posterior);\n                   });\n    return result;\n}\n\n} // namespace\n\nPhred<double>\nCancerCaller::calculate_segregation_probability(const Variant& variant, const Latents& latents, double somatic_mass) const\n{\n    return octopus::calculate_segregation_probability(variant.alt_allele(), latents.germline_genotypes_, latents.cancer_genotypes_,\n                                                      latents.germline_model_inferences_.posteriors.genotype_probabilities,\n                                                      latents.cnv_model_inferences_.posteriors.genotype_probabilities,\n                                                      latents.somatic_model_inferences_.posteriors.genotype_probabilities,\n                                                      latents.model_posteriors_.germline, latents.model_posteriors_.cnv,\n                                                      latents.model_posteriors_.somatic, somatic_mass);\n}\n\nnamespace debug {\n\ntemplate <typename S, typename T>\nvoid print_variants(S&& stream, const std::vector<T>& variants)\n{\n    for (const auto& v : variants) stream << v.variant << \" \" << v.posterior << '\\n';\n}\n\n} // namespace debug\n\nstd::vector<std::unique_ptr<VariantCall>>\nCancerCaller::call_variants(const std::vector<Variant>& candidates, const Latents& latents) const\n{\n    // TODO: refactor this into smaller methods!\n    const auto conditional_somatic_mass = calculate_somatic_mass(latents);\n    const auto& model_posteriors = latents.model_posteriors_;\n    log(model_posteriors);\n    const auto somatic_posterior = calculate_somatic_posterior(latents.model_posteriors_.somatic, conditional_somatic_mass);\n    const auto germline_genotype_posteriors = calculate_germline_genotype_posteriors(latents);\n    const auto& cancer_genotype_posteriors = latents.somatic_model_inferences_.posteriors.genotype_probabilities;\n    log(latents.germline_genotypes_, germline_genotype_posteriors, latents.germline_model_inferences_, latents.cnv_model_inferences_,\n        latents.cancer_genotypes_, latents.somatic_model_inferences_);\n    const auto germline_candidate_posteriors = compute_candidate_posteriors(candidates, germline_genotype_posteriors);\n    boost::optional<Genotype<Haplotype>> called_germline_genotype {};\n    boost::optional<CancerGenotype<Haplotype>> called_cancer_genotype {};\n    if (model_posteriors.somatic > model_posteriors.germline && somatic_posterior >= parameters_.min_somatic_posterior) {\n        if (debug_log_) *debug_log_ << \"Using cancer genotype for germline genotype call\";\n        if (!called_cancer_genotype) {\n            auto cancer_posteriors = zip_cref(latents.cancer_genotypes_, cancer_genotype_posteriors);\n            called_cancer_genotype = find_map_genotype(cancer_posteriors)->first;\n        }\n        called_germline_genotype = called_cancer_genotype->germline();\n    } else {\n        called_germline_genotype = find_map_genotype(germline_genotype_posteriors)->first;\n    }\n    GermlineVariantCalls germline_variant_calls;\n    std::vector<VariantReference> uncalled_germline_candidates;\n    std::tie(germline_variant_calls, uncalled_germline_candidates) = call_candidates(germline_candidate_posteriors,\n                                                                                     *called_germline_genotype,\n                                                                                     parameters_.min_variant_posterior);\n    \n    for (auto& v : germline_variant_calls) {\n        v.segregation_quality = calculate_segregation_probability(v.variant, latents, conditional_somatic_mass);\n        if (v.posterior > v.segregation_quality) v.posterior = v.segregation_quality;\n    }\n    \n    std::vector<std::unique_ptr<octopus::VariantCall>> result {};\n    Genotype<Haplotype> called_somatic_genotype {};\n    std::vector<SampleName> somatic_samples {};\n    if (somatic_posterior >= parameters_.min_somatic_posterior) {\n        auto somatic_allele_posteriors = compute_somatic_variant_posteriors(uncalled_germline_candidates, latents.cancer_genotypes_,\n                                                                            cancer_genotype_posteriors, somatic_posterior);\n        if (!called_cancer_genotype) {\n            auto cancer_posteriors = zip_cref(latents.cancer_genotypes_, cancer_genotype_posteriors);\n            called_cancer_genotype = find_map_genotype(cancer_posteriors)->first.get();\n        }\n        if (called_cancer_genotype->germline() == called_germline_genotype) {\n            auto somatic_variant_calls = call_somatic_variants(somatic_allele_posteriors, *called_cancer_genotype,\n                                                               parameters_.min_somatic_posterior);\n            const auto& somatic_alphas = latents.somatic_model_inferences_.posteriors.alphas;\n            const auto credible_regions = compute_marginal_credible_intervals(somatic_alphas, parameters_.credible_mass);\n            if (!somatic_variant_calls.empty()) {\n                for (const auto& p : credible_regions) {\n                    if (debug_log_) {\n                        auto ss = stream(*debug_log_);\n                        ss << p.first << \" somatic credible regions: \";\n                        for (auto cr : p.second) ss << '(' << cr.first << ' ' << cr.second << \") \";\n                    }\n                    if (std::any_of(std::next(std::cbegin(p.second), parameters_.ploidy), std::cend(p.second),\n                        [this] (const auto& credible_region) { return credible_region.first >= parameters_.min_credible_somatic_frequency; })) {\n                        if (has_normal_sample() && p.first == normal_sample()) {\n                            somatic_samples.clear();\n                            break;\n                        }\n                        somatic_samples.push_back(p.first);\n                    }\n                }\n                if (latents.noise_model_inferences_ && latents.normal_germline_inferences_) {\n                    const auto noise_model_evidence = latents.noise_model_inferences_->approx_log_evidence;\n                    const auto germline_model_evidence = latents.normal_germline_inferences_->log_evidence;\n                    if (noise_model_evidence > germline_model_evidence) {\n                        // Does the normal sample contain the called somatic variant?\n                        const auto& noisy_alphas = latents.noise_model_inferences_->posteriors.alphas.at(normal_sample());\n                        const auto noise_mass = compute_credible_somatic_mass(noisy_alphas, latents.somatic_ploidy_, parameters_.min_expected_somatic_frequency);\n                        if (noise_mass > 2 * parameters_.min_credible_somatic_frequency) {\n                            somatic_samples.clear();\n                        }\n                    }\n                }\n                if (somatic_samples.empty()) {\n                    somatic_variant_calls.clear();\n                    somatic_variant_calls.shrink_to_fit();\n                } else {\n                    called_somatic_genotype = called_cancer_genotype->somatic();\n                }\n                for (auto& v : somatic_variant_calls) {\n                    v.segregation_quality = calculate_segregation_probability(v.variant, latents, conditional_somatic_mass);\n                    if (v.posterior > v.segregation_quality) v.posterior = v.segregation_quality;\n                }\n            }\n            if (debug_log_) {\n                *debug_log_ << \"Called somatic variants:\";\n                debug::print_variants(stream(*debug_log_), somatic_variant_calls);\n            }\n            const auto somatic_vafs = compute_map_somatic_vafs(somatic_alphas, latents.somatic_ploidy_);\n            const auto called_somatic_regions = extract_regions(somatic_variant_calls);\n            auto cancer_genotype_calls = call_somatic_genotypes(*called_cancer_genotype, called_somatic_regions,\n                                                                latents.cancer_genotypes_, cancer_genotype_posteriors,\n                                                                credible_regions, somatic_vafs);\n            result = transform_somatic_calls(std::move(somatic_variant_calls), std::move(cancer_genotype_calls), somatic_samples);\n        } else if (debug_log_) {\n            stream(*debug_log_) << \"Conflict between called germline genotype and called cancer genotype. Not calling somatics\";\n        }\n    }\n    const auto called_germline_regions = extract_regions(germline_variant_calls);\n    GermlineGenotypeCalls germline_genotype_calls {};\n    germline_genotype_calls.reserve(called_germline_regions.size());\n    for (const auto& region : called_germline_regions) {\n        auto genotype_chunk = copy<Allele>(*called_germline_genotype, region);\n        const auto inv_posterior = std::accumulate(std::cbegin(germline_genotype_posteriors),\n                                                   std::cend(germline_genotype_posteriors), 0.0,\n                                                   [&called_germline_genotype] (const double curr, const auto& p) {\n                                                       return curr + (contains(p.first, *called_germline_genotype) ? 0.0 : p.second);\n                                                   });\n        if (called_somatic_genotype.ploidy() > 0) {\n            germline_genotype_calls.emplace_back(std::move(genotype_chunk),\n                                                 copy<Allele>(called_somatic_genotype, region),\n                                                 probability_to_phred(inv_posterior));\n        } else {\n            germline_genotype_calls.emplace_back(std::move(genotype_chunk), probability_to_phred(inv_posterior));\n        }\n    }\n    if (debug_log_) {\n        *debug_log_ << \"Called germline variants:\";\n        debug::print_variants(stream(*debug_log_), germline_variant_calls);\n    }\n    result.reserve(result.size() + germline_variant_calls.size());\n    const auto itr = std::end(result);\n    std::transform(std::make_move_iterator(std::begin(germline_variant_calls)),\n                   std::make_move_iterator(std::end(germline_variant_calls)),\n                   std::make_move_iterator(std::begin(germline_genotype_calls)),\n                   std::back_inserter(result),\n                   [this, &somatic_samples] (auto&& variant_call, auto&& genotype_call) {\n                       return transform_germline_call(std::move(variant_call), std::move(genotype_call),\n                                                      samples_, somatic_samples);\n                   });\n    std::inplace_merge(std::begin(result), itr, std::end(result),\n                       [] (const auto& lhs, const auto& rhs) { return *lhs < *rhs; });\n    return result;\n}\n\nCancerCaller::GermlineGenotypeProbabilityMap\nCancerCaller::calculate_germline_genotype_posteriors(const Latents& latents) const\n{\n    const auto& model_posteriors = latents.model_posteriors_;\n    const auto& germline_genotypes = latents.germline_genotypes_;\n    GermlineGenotypeProbabilityMap result {germline_genotypes.size()};\n    std::transform(std::cbegin(germline_genotypes), std::cend(germline_genotypes),\n                   std::cbegin(latents.germline_model_inferences_.posteriors.genotype_probabilities),\n                   std::inserter(result, std::begin(result)),\n                   [&model_posteriors] (const auto& genotype, const auto& posterior) {\n                       return std::make_pair(genotype, model_posteriors.germline * posterior);\n                   });\n    const auto& cnv_posteriors = latents.cnv_model_inferences_.posteriors.genotype_probabilities;\n    for (std::size_t i {0}; i < latents.germline_genotypes_.size(); ++i) {\n        result[germline_genotypes[i]] += model_posteriors.cnv * cnv_posteriors[i];\n    }\n    const auto& cancer_genotypes = latents.cancer_genotypes_;\n    const auto& somatic_posteriors = latents.somatic_model_inferences_.posteriors.genotype_probabilities;\n    for (std::size_t i {0}; i < cancer_genotypes.size(); ++i) {\n        result[cancer_genotypes[i].germline()] += model_posteriors.somatic * somatic_posteriors[i];\n    }\n    return result;\n}\n\ndouble CancerCaller::calculate_somatic_mass(const CancerCaller::Latents& latents) const\n{\n    return compute_credible_somatic_mass(latents.somatic_model_inferences_.posteriors.alphas, latents.somatic_ploidy_,\n                                         parameters_.min_expected_somatic_frequency);\n}\n\nstd::vector<std::unique_ptr<ReferenceCall>>\nCancerCaller::call_reference(const std::vector<Allele>& alleles, const Caller::Latents& latents, const ReadPileupMap& pileups) const\n{\n    return {};\n}\n\nstd::unique_ptr<GenotypePriorModel> CancerCaller::make_germline_prior_model(const std::vector<Haplotype>& haplotypes) const\n{\n    if (parameters_.germline_prior_model_params) {\n        return std::make_unique<CoalescentGenotypePriorModel>(CoalescentModel {\n        Haplotype {octopus::mapped_region(haplotypes.front()), reference_},\n        *parameters_.germline_prior_model_params\n        });\n    } else {\n        return std::make_unique<UniformGenotypePriorModel>();\n    }\n}\n\n// CancerCaller::Latents\n\nCancerCaller::Latents::Latents(const std::vector<Haplotype>& haplotypes, const std::vector<SampleName>& samples,\n                               const CancerCaller::Parameters& parameters)\n: haplotypes_ {haplotypes}\n, samples_ {samples}\n, parameters_ {parameters}\n{}\n\nstd::shared_ptr<CancerCaller::Latents::HaplotypeProbabilityMap>\nCancerCaller::Latents::haplotype_posteriors() const\n{\n    if (haplotype_posteriors_ == nullptr) {\n        compute_haplotype_posteriors();\n    }\n    return haplotype_posteriors_;\n}\n\nstd::shared_ptr<CancerCaller::Latents::GenotypeProbabilityMap>\nCancerCaller::Latents::genotype_posteriors() const\n{\n    if (genotype_posteriors_ == nullptr) {\n        compute_genotype_posteriors();\n    }\n    return genotype_posteriors_;\n}\n\nvoid CancerCaller::Latents::compute_genotype_posteriors() const\n{\n    // TODO: properly\n    GenotypeProbabilityMap genotype_posteriors {std::begin(germline_genotypes_), std::end(germline_genotypes_)};\n    for (const auto& sample : samples_.get()) {\n        insert_sample(sample, germline_model_inferences_.posteriors.genotype_probabilities, genotype_posteriors);\n    }\n    genotype_posteriors_ = std::make_shared<Latents::GenotypeProbabilityMap>(std::move(genotype_posteriors));\n}\n\nvoid CancerCaller::Latents::compute_haplotype_posteriors() const\n{\n    Latents::HaplotypeProbabilityMap result {haplotypes_.get().size()};\n    for (const auto& haplotype : haplotypes_.get()) {\n        result.emplace(haplotype, 0.0);\n    }\n    // Contribution from germline model\n    for (const auto& p : zip(germline_genotypes_, germline_model_inferences_.posteriors.genotype_probabilities)) {\n        for (const auto& haplotype : p.get<0>().copy_unique_ref()) {\n            result.at(haplotype) += model_posteriors_.germline * p.get<1>();\n        }\n    }\n    // Contribution from CNV model\n    for (const auto& p : zip(germline_genotypes_, cnv_model_inferences_.posteriors.genotype_probabilities)) {\n        for (const auto& haplotype : p.get<0>().copy_unique_ref()) {\n            result.at(haplotype) += model_posteriors_.cnv * p.get<1>();\n        }\n    }\n    const auto credible_frequency = parameters_.get().min_expected_somatic_frequency;\n    const auto conditional_somatic_prob = compute_credible_somatic_mass(somatic_model_inferences_.posteriors.alphas, somatic_ploidy_, credible_frequency);\n    // Contribution from somatic model\n    for (const auto& p : zip(cancer_genotypes_, somatic_model_inferences_.posteriors.genotype_probabilities)) {\n        for (const auto& haplotype : p.get<0>().germline().copy_unique_ref()) {\n            result.at(haplotype) += model_posteriors_.somatic * p.get<1>();\n        }\n        for (const auto& haplotype : p.get<0>().somatic().copy_unique_ref()) {\n            result.at(haplotype) += model_posteriors_.somatic * conditional_somatic_prob * p.get<1>();\n        }\n    }\n    haplotype_posteriors_ = std::make_shared<Latents::HaplotypeProbabilityMap>(std::move(result));\n}\n\n// logging\n\nvoid CancerCaller::log(const ModelPosteriors& model_posteriors) const\n{\n    if (debug_log_) {\n        stream(*debug_log_) << \"Germline model posterior: \" << model_posteriors.germline;\n        stream(*debug_log_) << \"CNV model posterior:      \" << model_posteriors.cnv;\n        stream(*debug_log_) << \"Somatic model posterior:  \" << model_posteriors.somatic;\n    }\n}\n\nvoid CancerCaller::log(const GenotypeVector& germline_genotypes,\n                       const GermlineGenotypeProbabilityMap& germline_genotype_posteriors,\n                       const GermlineModel::InferredLatents& germline_inferences,\n                       const CNVModel::InferredLatents& cnv_inferences,\n                       const CancerGenotypeVector& cancer_genotypes,\n                       const SomaticModel::InferredLatents& somatic_inferences) const\n{\n    if (debug_log_) {\n        auto germline_posteriors = zip_cref(germline_genotypes, germline_inferences.posteriors.genotype_probabilities);\n        auto map_germline = find_map_genotype(germline_posteriors);\n        auto germline_log = stream(*debug_log_);\n        germline_log << \"MAP germline genotype: \";\n        debug::print_variant_alleles(germline_log, map_germline->first);\n        germline_log << ' ' << map_germline->second;\n        auto cnv_posteriors = zip_cref(germline_genotypes, cnv_inferences.posteriors.genotype_probabilities);\n        auto map_cnv = find_map_genotype(cnv_posteriors);\n        auto cnv_log = stream(*debug_log_);\n        cnv_log << \"MAP CNV genotype: \";\n        debug::print_variant_alleles(cnv_log, map_cnv->first);\n        cnv_log << ' ' << map_cnv->second;\n        auto somatic_log = stream(*debug_log_);\n        auto cancer_posteriors = zip_cref(cancer_genotypes, somatic_inferences.posteriors.genotype_probabilities);\n        auto map_somatic = find_map_genotype(cancer_posteriors);\n        auto map_cancer_genotype = map_somatic->first.get();\n        somatic_log << \"MAP cancer genotype: \";\n        debug::print_variant_alleles(somatic_log, map_cancer_genotype);\n        somatic_log << ' ' << map_somatic->second;\n        auto map_marginal_germline = find_map_genotype(germline_genotype_posteriors);\n        auto marginal_germline_log = stream(*debug_log_);\n        marginal_germline_log << \"MAP marginal germline genotype: \";\n        debug::print_variant_alleles(marginal_germline_log, map_marginal_germline->first);\n        marginal_germline_log << ' ' << map_marginal_germline->second;\n    }\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "ef300124065743e1b5b9f296d2351f8ae0dfe78f", "size": 85431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/callers/cancer_caller.cpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "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/callers/cancer_caller.cpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/callers/cancer_caller.cpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.0297951583, "max_line_length": 170, "alphanum_fraction": 0.6689726212, "num_tokens": 19490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.17108743791792752}}
{"text": "#include \"extractor/guidance/intersection.hpp\"\n#include \"extractor/guidance/toolkit.hpp\"\n\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/find_if.hpp>\n\n#include <boost/assert.hpp>\n\n#include <algorithm>\n#include <functional>\n#include <limits>\n\nnamespace osrm\n{\nnamespace extractor\n{\nnamespace guidance\n{\n\nConnectedRoad::ConnectedRoad(const TurnOperation turn, const bool entry_allowed)\n    : TurnOperation(turn), entry_allowed(entry_allowed)\n{\n}\n\nbool ConnectedRoad::compareByAngle(const ConnectedRoad &other) const { return angle < other.angle; }\n\nvoid ConnectedRoad::mirror()\n{\n    const constexpr DirectionModifier::Enum mirrored_modifiers[] = {DirectionModifier::UTurn,\n                                                                    DirectionModifier::SharpLeft,\n                                                                    DirectionModifier::Left,\n                                                                    DirectionModifier::SlightLeft,\n                                                                    DirectionModifier::Straight,\n                                                                    DirectionModifier::SlightRight,\n                                                                    DirectionModifier::Right,\n                                                                    DirectionModifier::SharpRight};\n\n    static_assert(sizeof(mirrored_modifiers) / sizeof(DirectionModifier::Enum) ==\n                      DirectionModifier::MaxDirectionModifier,\n                  \"The list of mirrored modifiers needs to match the available modifiers in size.\");\n\n    if (angularDeviation(angle, 0) > std::numeric_limits<double>::epsilon())\n    {\n        angle = 360 - angle;\n        instruction.direction_modifier = mirrored_modifiers[instruction.direction_modifier];\n    }\n}\n\nConnectedRoad ConnectedRoad::getMirroredCopy() const\n{\n    ConnectedRoad copy(*this);\n    copy.mirror();\n    return copy;\n}\n\nstd::string toString(const ConnectedRoad &road)\n{\n    std::string result = \"[connection] \";\n    result += std::to_string(road.eid);\n    result += \" allows entry: \";\n    result += std::to_string(road.entry_allowed);\n    result += \" angle: \";\n    result += std::to_string(road.angle);\n    result += \" bearing: \";\n    result += std::to_string(road.bearing);\n    result += \" instruction: \";\n    result += std::to_string(static_cast<std::int32_t>(road.instruction.type)) + \" \" +\n              std::to_string(static_cast<std::int32_t>(road.instruction.direction_modifier)) + \" \" +\n              std::to_string(static_cast<std::int32_t>(road.lane_data_id));\n    return result;\n}\n\nIntersection::Base::iterator Intersection::findClosestTurn(double angle)\n{\n    // use the const operator to avoid code duplication\n    return begin() +\n           std::distance(cbegin(), static_cast<const Intersection *>(this)->findClosestTurn(angle));\n}\n\nIntersection::Base::const_iterator Intersection::findClosestTurn(double angle) const\n{\n    return std::min_element(\n        begin(), end(), [angle](const ConnectedRoad &lhs, const ConnectedRoad &rhs) {\n            return util::guidance::angularDeviation(lhs.angle, angle) <\n                   util::guidance::angularDeviation(rhs.angle, angle);\n        });\n}\n\nbool Intersection::valid() const\n{\n    return !empty() &&\n           std::is_sorted(begin(), end(), std::mem_fn(&ConnectedRoad::compareByAngle)) &&\n           operator[](0).angle < std::numeric_limits<double>::epsilon();\n}\n\nstd::uint8_t\nIntersection::getHighestConnectedLaneCount(const util::NodeBasedDynamicGraph &graph) const\n{\n    BOOST_ASSERT(valid()); // non empty()\n\n    const std::function<std::uint8_t(const ConnectedRoad &)> to_lane_count =\n        [&](const ConnectedRoad &road) {\n            return graph.GetEdgeData(road.eid).road_classification.GetNumberOfLanes();\n        };\n\n    std::uint8_t max_lanes = 0;\n    const auto extract_maximal_value = [&max_lanes](std::uint8_t value) {\n        max_lanes = std::max(max_lanes, value);\n        return false;\n    };\n\n    const auto view = *this | boost::adaptors::transformed(to_lane_count);\n    boost::range::find_if(view, extract_maximal_value);\n    return max_lanes;\n}\n\n} // namespace guidance\n} // namespace extractor\n} // namespace osrm\n", "meta": {"hexsha": "53a6a618d7c135bb47dad7061217ed22b8405152", "size": 4260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extractor/guidance/intersection.cpp", "max_stars_repo_name": "edudude/osrm-backend", "max_stars_repo_head_hexsha": "8bb183bc8cb2b69cdf861745580951ae3385e068", "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/extractor/guidance/intersection.cpp", "max_issues_repo_name": "edudude/osrm-backend", "max_issues_repo_head_hexsha": "8bb183bc8cb2b69cdf861745580951ae3385e068", "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/extractor/guidance/intersection.cpp", "max_forks_repo_name": "edudude/osrm-backend", "max_forks_repo_head_hexsha": "8bb183bc8cb2b69cdf861745580951ae3385e068", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-19T08:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T08:51:11.000Z", "avg_line_length": 35.5, "max_line_length": 100, "alphanum_fraction": 0.6185446009, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17108743565857698}}
{"text": "#include <STKLib/common.h>\n#include <STKLib/stkstream.h>\n#include <STKLib/MlfStream.h>\n#include <STKLib/Models.h>\n#include <STKLib/Tokenizer.h>\n#include \"STKLib/Features.h\"\n\n\n#include <algorithm>\n#include <cctype>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <list>\n\n#if !defined HAVE_BOOST\n#warning \"Won't run---Requires BOOST\"\nint main(int argc, char* argv[]) {\n  return 1;\n}\n#else\n\n#include <boost/program_options.hpp>\n\n// ............................................................................\n// shorten namespace to program options\nnamespace po = boost::program_options;\n\nusing namespace STK;\nusing namespace std;\n\n\n// typedefs ...................................................................\n\n\n// prototypes .................................................................\nvoid\nTransformMatrix(const Matrix<FLOAT>& rSrc, Matrix<FLOAT>& rDest, \n    ModelSet& rModels, XformInstance* pXform, size_t outSize);\n\n// A helper function to simplify the main part.\ntemplate<class T>\nstd::ostream& operator <<(std::ostream& os, const std::vector<T>& v)\n{\n  std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, \" \")); \n    return os;\n}\n\n\n\n/******************************************************************************/\n/******************************************************************************/\nint main(int argc, char* argv[])\n{\n  try \n  {\n    // general-purpose variables\n  //  bool                    swap_features;\n  //  int                     start_frm_ext;\n  //  int                     end_frm_ext;\n    string                  target_kind;\n\n    FeatureRepository       feature_repo;\n    string                  out_stat_file;\n    string                  script_file;\n    string                  script_file_filter;\n    Matrix<FLOAT>          feature_matrix;\n\n    // Model set, in case we need to use xform .................................\n    ModelSet                hset;\n    std::string             source_mmf;\n    std::string             input_xform_name;\n    XformInstance*          p_input_xform = NULL;\n\n    // Statistics ..............................................................\n    FLOAT                  zero_stats(0.0);\n    BasicVector<FLOAT>     first_stats;\n    Matrix<FLOAT>          second_stats;\n\n    string                  config_file;\n    vector< string >        positional_parameters;\n\n    InitLogMath();\n    hset.Init();\n\n    //srandom((unsigned int)time(NULL));\n    srand((unsigned)time(0));\n\n\n    // command line options only\n    po::options_description generic_options(\"Command line options\");\n    generic_options.add_options()\n      (\"cfgfile,C\",     po::value<string>(&config_file),                      \"Configuration file\")\n      (\"help\",                                                                \"Print more detailed help\") \n\n      (\"outstatfile\",   po::value<string>(),                                  \"Output the stats here\")\n      (\"script,S\",      po::value<string>(),                                  \"Source data script\")\n      (\"scriptfilter\",  po::value<string>()->default_value(\"\"),               \"Script file filter\")\n      (\"sourcemmf,H\",   po::value<string>(&source_mmf),                       \"Source input Xform mmf\")\n      (\"sourceinput\",   po::value<string>(&input_xform_name),                 \"Source input Xform name\")\n      (\"targetkind\",    po::value<string>(&target_kind)->default_value(\"\"),   \"Target kind code\");\n\n\n    // config file options only\n    po::options_description config_options(\"Configuration\");\n\n    // hidden options only\n    po::options_description hidden_options(\"Hidden\");\n\n    // command line options will be combination of generic options, config \n    // file options and hidden options\n    po::options_description cmdline_options;\n    cmdline_options.add(generic_options).add(config_options).add(hidden_options);\n\n    // config file options will be combination of config options and hidden \n    // options\n    po::options_description config_file_options;\n    config_file_options.add(config_options);\n\n    // visible options\n    po::options_description visible_options;\n    visible_options.add(generic_options).add(config_options);\n\n    po::variables_map var_map;\n    po::store(po::command_line_parser(argc, argv)\n        .options(cmdline_options).run(), var_map);\n    po::notify(var_map);\n\n    \n    // if no parameters given, dump the generic options description\n    if (0 == var_map.size()) {\n      std::cout << generic_options << std::endl;\n      return 0;\n    }\n    // if help specified, dump all parameters\n    else if (var_map.count(\"help\")) {\n      std::cout << visible_options << std::endl;\n      return 0;\n    }\n                 \n    // parse the config file\n    if (!config_file.empty()) {\n      IStkStream ifs(config_file.c_str());\n      if (!ifs.good()) {\n        // TODO: Error message\n      }\n\n      po::store(parse_config_file(ifs, config_file_options), var_map);\n      ifs.close();\n    }\n\n    // SOME CHECKING ...........................................................\n    if (!var_map.count(\"script\")) {\n      throw runtime_error(\"Script file not specified\");\n    }\n\n    if (!var_map.count(\"outstatfile\")) {\n      throw runtime_error(\"Output file not specified\");\n    }\n\n    out_stat_file = var_map[\"outstatfile\"].as<string>();\n    script_file   = var_map[\"script\"].as<string>();\n\n\n    // END OF COMMAND LINE PARAMETER PARSING ...................................\n\n\n    // parse MMFs if any given .................................................\n    if (\"\" != source_mmf) {\n      Tokenizer             file_list(source_mmf.c_str(), \",\");\n      Tokenizer::iterator   p_file_name;\n\n      for (p_file_name = file_list.begin(); p_file_name != file_list.end(); \n          ++p_file_name) {\n        // parse the MMF\n        hset.ParseMmf(p_file_name->c_str(), NULL);\n      }\n\n      if (input_xform_name != \"\") \n      {\n        Macro* p_macro = FindMacro(&hset.mXformInstanceHash, \n            input_xform_name.c_str());\n\n        if (p_macro == NULL) { \n          throw runtime_error(std::string(\"Undefined source input \") + \n              input_xform_name);\n        }\n        p_input_xform = static_cast<XformInstance*>(p_macro->mpData);\n      } \n      else if (hset.mpInputXform) \n      {\n        p_input_xform = hset.mpInputXform;\n      }\n    }\n\n\n    int target_kind_code = ReadParmKind(target_kind.c_str(), false);\n\n    // swap_features, start_frm_ext, end_frm_ext, targetKind, deriv_order, \n    // deriv_win_lengths, cmn_path, cmn_mask, cvn_path, cvn_mask, cvg_file\n    feature_repo.Init(!isBigEndian(), 0, 0, target_kind_code,\n        0, NULL, NULL, NULL, NULL, NULL, NULL);\n\n    // retreive the script file name\n    script_file = var_map[\"script\"].as<string >();\n\n    feature_repo.AddFileList(script_file.c_str(), script_file_filter == \"\" ?\n        NULL : script_file_filter.c_str());\n\n    BasicVector<FLOAT> aux_vec;\n\n    for (feature_repo.Rewind(); !feature_repo.EndOfList(); \n        feature_repo.MoveNext()) \n    {\n      size_t out_size;\n\n      std::cout << feature_repo.Current().Logical() << \" = \" <<\n        feature_repo.Current().Physical() << std::endl;\n      \n      if (NULL != p_input_xform) {\n        Matrix<FLOAT> raw_feature_matrix;\n\n        // now reest features are read .........................................\n        feature_repo.ReadFullMatrix(raw_feature_matrix);\n        out_size = p_input_xform->OutSize();\n        \n        // pass the matrix through all filters\n        TransformMatrix(raw_feature_matrix, feature_matrix, hset, p_input_xform,\n            out_size);\n      }\n      else {\n        // now reest features are read ...........................................\n        feature_repo.ReadFullMatrix(feature_matrix);\n        out_size  = feature_matrix.Cols();\n      }\n\n      if (0 == first_stats.Length()) {\n        first_stats.Init(out_size);\n        first_stats.Clear();\n        second_stats.Init(out_size, out_size);\n        second_stats.Clear();\n      }\n      // check the dimensionality of the current feature file\n      else if (first_stats.Length() != out_size) {\n        throw runtime_error(std::string(\"Dimensionality of the feature file \")\n            + feature_repo.Current().Physical() + \" differs from the previous\");\n      }\n\n      // adding a size_t\n      zero_stats += feature_matrix.Rows();\n      first_stats.AddColSum(feature_matrix);\n      second_stats.AddCMtMMul(1.0, feature_matrix, feature_matrix);\n\n      OStkStream tmp_stream(\"hnup\");\n      tmp_stream << feature_matrix;\n      feature_matrix.Destroy();\n    }\n\n    OStkStream out_stream(out_stat_file.c_str());\n    if (!out_stream.good()) {\n      throw runtime_error(string(\"Error opening output file \") + \n          out_stat_file);\n    }\n\n    out_stream << 3 << \" \";\n    out_stream << 1 << \" \";\n    out_stream << first_stats.Length() << \" \" ;\n    out_stream << second_stats.Rows() << \" \" ;\n    out_stream << 0 << std::endl; // write extra zero\n\n    out_stream << std::scientific;\n    out_stream << zero_stats << std::endl << first_stats << std::endl << second_stats;\n\n    out_stream.close();\n  }\n  catch (std::exception& rExc) {\n    std::cerr << \"Exception thrown\" << std::endl;\n    std::cerr << rExc.what() << std::endl;\n    return 1;\n  }\n\n  return 0;\n}\n\n\n//******************************************************************************\n//******************************************************************************\nvoid\nTransformMatrix(const Matrix<FLOAT>& rSrc, Matrix<FLOAT>& rDest, \n    ModelSet& rModels, XformInstance* pXform, size_t outSize)\n{\n  size_t time;\n  FLOAT* out_vector;\n\n  time = -rModels.mTotalDelay;\n  rModels.ResetXformInstances();\n\n  rDest.Destroy();\n  rDest.Init(rSrc.Rows() + time, outSize);\n\n  // we go through each feature vector and xform it\n  for (size_t i = 0 ; i<rSrc.Rows(); i++) {\n    rModels.UpdateStacks(rSrc[i], ++time, FORWARD);\n\n    if (time <= 0) {\n      continue;\n    }\n\n    out_vector = XformPass(pXform, rSrc[i], time, FORWARD);\n    memcpy(rDest[time - 1], out_vector, sizeof(FLOAT) * outSize);\n  }\n}\n\n\n#endif //boost \n\n", "meta": {"hexsha": "25c907d15ebb4a0322d7eec0abf9edd1bbd0b75d", "size": 10040, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/STKLib/trunk/src/SFeaStat.cc", "max_stars_repo_name": "troylee/nnet-asr", "max_stars_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "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/STKLib/trunk/src/SFeaStat.cc", "max_issues_repo_name": "troylee/nnet-asr", "max_issues_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "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/STKLib/trunk/src/SFeaStat.cc", "max_forks_repo_name": "troylee/nnet-asr", "max_forks_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "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.572327044, "max_line_length": 106, "alphanum_fraction": 0.5578685259, "num_tokens": 2210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.17108743565857698}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2007-2008 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_UNIT_SYSTEMS_METRIC_NAUTICAL_MILE_HPP_INCLUDED\n#define BOOST_UNIT_SYSTEMS_METRIC_NAUTICAL_MILE_HPP_INCLUDED\n\n#include <boost/units/scaled_base_unit.hpp>\n#include <boost/units/static_rational.hpp>\n#include <boost/units/scale.hpp>\n#include <boost/units/base_units/si/meter.hpp>\n\nnamespace boost {\nnamespace units {\nnamespace metric {\n\ntypedef scaled_base_unit<boost::units::si::meter_base_unit, scale<1852, static_rational<1> > > nautical_mile_base_unit;\n\n}\n\ntemplate<>\nstruct base_unit_info<metric::nautical_mile_base_unit> {\n    static BOOST_CONSTEXPR const char* name()   { return(\"nautical mile\"); }\n    static BOOST_CONSTEXPR const char* symbol() { return(\"nmi\"); }\n};\n\n}\n}\n\n#endif // BOOST_UNIT_SYSTEMS_METRIC_NAUTICAL_MILE_HPP_INCLUDED\n", "meta": {"hexsha": "4f20951af87ce10cd17ea9af34c8dd5794c94cd0", "size": 1135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/units/base_units/metric/nautical_mile.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/units/base_units/metric/nautical_mile.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/units/base_units/metric/nautical_mile.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": 30.6756756757, "max_line_length": 119, "alphanum_fraction": 0.7806167401, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1710874344376186}}
{"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_X86_SSE2_SIMD_FUNCTION_SLIDE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_SLIDE_HPP_INCLUDED\n\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/detail/overload.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( slide_\n                          , (typename T, typename Offset)\n                          , bs::sse2_\n                          , bs::pack_< bd::fundamental_<T>, bs::sse_ >\n                          , bd::constant_<bd::integer_<Offset>>\n                          )\n  {\n    using bits_t  = typename T::template rebind<std::uint8_t>::template resize<16>;\n    using bcnt    = std::integral_constant<std::size_t,16u/T::static_size>;\n\n    // slide with positive offset\n    static BOOST_FORCEINLINE T side(T const& a0, std::true_type const&) BOOST_NOEXCEPT\n    {\n      using imm = std::integral_constant<std::size_t,Offset::value*bcnt::value>;\n      return bitwise_cast<T>(_mm_srli_si128(bitwise_cast<bits_t>(a0),imm::value));\n    }\n\n    // slide with negative offset\n    static BOOST_FORCEINLINE T side( T const& a0, std::false_type const& ) BOOST_NOEXCEPT\n    {\n      using imm = std::integral_constant<std::size_t,(-Offset::value)*bcnt::value>;\n      return bitwise_cast<T>(_mm_slli_si128(bitwise_cast<bits_t>(a0),imm::value));\n    }\n\n    BOOST_FORCEINLINE T operator()(T const& a0, Offset const&) const BOOST_NOEXCEPT\n    {\n      return side(a0, brigand::bool_<(Offset::value >= 0)>{});\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( slide_\n                          , (typename T, typename Offset)\n                          , bs::sse2_\n                          , bs::pack_< bd::fundamental_<T>, bs::sse_ >\n                          , bs::pack_< bd::fundamental_<T>, bs::sse_ >\n                          , bd::constant_<bd::integer_<Offset>>\n                          )\n  {\n    using bits_t  = typename T::template rebind<std::uint8_t>::template resize<16>;\n\n    BOOST_FORCEINLINE T operator()(T const& a0, T const& a1, Offset const&) const BOOST_NOEXCEPT\n    {\n      // Compute relative offsets for shifted loads pair\n      using bcnt  = std::integral_constant<std::size_t,(16u/T::static_size)>;\n      using ls    = std::integral_constant<std::size_t,bcnt::value*Offset::value>;\n      using rs    = std::integral_constant<std::size_t,bcnt::value*(T::static_size-Offset::value)>;\n\n      // Shift everything in place\n      return bitwise_cast<T>( _mm_or_si128( _mm_srli_si128(bitwise_cast<bits_t>(a0),ls::value)\n                                          , _mm_slli_si128(bitwise_cast<bits_t>(a1),rs::value)\n                                          )\n                            );\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "81e92291bc21711435186b0c8e229cd6b7713f74", "size": 3150, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/sse2/simd/function/slide.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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": "third_party/boost/simd/arch/x86/sse2/simd/function/slide.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/x86/sse2/simd/function/slide.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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.9090909091, "max_line_length": 100, "alphanum_fraction": 0.5685714286, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17108743095730972}}
{"text": "#include <signal.h>\n#include <stdio.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/tcp.h>\n#include <netinet/in.h>\n#include <netdb.h> \n#include <sys/time.h>\n#include <iostream>\n#include <future>\n#include <string>\n#include <array>\n#include <vector>\n#include <stdexcept>\n#include <random>\n#include <chrono>\n#include <thread>\n#include <limits>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <parallel/algorithm>\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\nusing std::array;\nusing std::vector;\nusing std::future;\nusing std::async;\nusing std::launch;\nusing std::runtime_error;\nusing std::numeric_limits;\nusing std::default_random_engine;\nusing boost::timer::auto_cpu_timer;\n\ntypedef boost::numeric::ublas::matrix<int> Matrix;\ntypedef boost::numeric::ublas::zero_matrix<int> ZeroMatrix;\n\nnamespace ba = boost::accumulators;\ntypedef ba::accumulator_set<double, ba::stats<ba::tag::mean, ba::tag::min, ba::tag::max, ba::tag::count, ba::tag::variance, ba::tag::moment<2>>> Acc;\n\nstruct __attribute__ ((__packed__))  NetReq {\n    int64_t        reqID;\n    int32_t        train;        // [0, 5000)\n    int16_t        start;        // [0, 10)\n    int16_t        stop;\n};\n\nstruct __attribute__ ((__packed__))  NetResp {\n    int64_t        reqID;\n    int32_t        respID;\n    int32_t        seat;\n};\n\n// return resp_ts - req_ts in seconds\ndouble time_diff (struct timeval const &resp_ts, struct timeval const &req_ts) {\n    double ss = resp_ts.tv_sec - req_ts.tv_sec;\n    ss += (resp_ts.tv_usec - req_ts.tv_usec) / 1000000.0;\n    return ss;\n}\n\nstruct NetStat {\n    struct timeval req_ts;\n    struct timeval resp_ts;\n    NetReq const *req;\n    NetResp const *resp;\n    int sid;    // global seat id, == (train * tspace.seats + resp.seat) * segments + segment\n\n    NetStat (): req(nullptr), resp(nullptr), sid(-1) {\n    }\n\n    // in seconds\n    double latency () const {\n        return time_diff(resp_ts, req_ts);\n    }\n};\n\nstruct TicketSpace {\n    int trains;\n    int segments;\n    int seats;\n    int max_length;\n\n    void check_size () {\n        int64_t v = 1;\n        v *= trains;\n        v *= segments;\n        v *= max_length;\n        BOOST_VERIFY(v <= numeric_limits<int>::max());\n    }\n\n    // generate one random request\n    template <typename RANDOM_ENGINE>\n    void sample (RANDOM_ENGINE &e, NetReq *req) const {\n        req->train = e() % trains;\n        req->start = e() % segments;\n        int ml = segments - req->start;\n        // extreme case, last segment:  req->start = segments - 1\n        // ml = 1\n        if (ml > max_length) {\n            ml = max_length;\n        }\n        int length = (e() % ml) + 1;\n        req->stop = req->start + length;\n    }\n\n    // SID uniquely identify (train, seat, segment) triplet\n    int make_sid (int train, int seat, int segment) const {\n        return (train * seats + seat) * segments + segment;\n    }\n\n    int total_sids () const {\n        return trains * seats * segments;\n    }\n};\n\nenum {  // performance counters\n    CNT_SEND = 0,\n    CNT_RECV,\n    CNT_SUCC,\n    CNT_SEND_BYTE,\n    CNT_RECV_BYTE,\n    CNT_NUM\n};\n\ntypedef array<size_t, CNT_NUM> Counters;\n\nvoid send_all (int sockfd, void const *buf, size_t len) { \n    while (len > 0) {\n        ssize_t r = send(sockfd, buf, len, 0);\n        if (r < 0 || r > len) throw runtime_error(\"send error\");\n        buf += r;\n        len -= r;\n    }\n}\n\nvoid recv_all (int sockfd, void *buf, size_t len) { \n    while (len > 0) {\n        ssize_t r = recv(sockfd, buf, len, 0);\n        if (r < 0 || r > len) throw runtime_error(\"recv error\");\n        buf += r;\n        len -= r;\n    }\n}\n\nclass Client: public vector<NetStat> {\n\n    TicketSpace ts;\n    int sockfd;\n    bool volatile done;  // stop flag, reader/writer will\n                // stop when done becomes true\n    size_t batch;\n    size_t queue;\n    size_t sleep;\n    Counters counters;\n    size_t volatile *pcounters;\n\n    future<void> rfuture;\n    future<void> wfuture;\n\n    vector<NetReq> reqs;\n    vector<NetResp> resps;\n\n    void reader () {\n        for (auto &resp: resps) {\n            if (done) break;\n            struct timeval tv;\n            recv_all(sockfd, reinterpret_cast<char *>(&resp), sizeof(resp));\n            pcounters[CNT_RECV_BYTE] += sizeof(resp);\n            gettimeofday(&tv, NULL);\n            if (resp.reqID < 0 || resp.reqID >= size()) {\n                throw runtime_error(\"bad server response\");\n            }\n            auto &st = at(resp.reqID);\n            st.resp = &resp;\n            st.resp_ts = tv;\n            ++pcounters[CNT_RECV];\n            if (resp.seat >= 0) {\n                ++pcounters[CNT_SUCC];\n                st.sid = ts.make_sid(st.req->train, resp.seat, st.req->start);\n            }\n        }\n    }\n\n    void writer () {\n        for (unsigned i = 0; i < reqs.size(); i += batch) {\n            while ((pcounters[CNT_SEND] + batch - pcounters[CNT_RECV] >= queue) && (!done)) {\n                usleep(sleep);\n            }\n            // i is batch start\n            if (done) break;\n            struct timeval ts;\n            gettimeofday(&ts, NULL);\n            unsigned n = reqs.size() - i;\n            if (n > batch) n = batch;\n            for (unsigned j = i; j < i + n; ++j) {\n                auto const &req = reqs[j];\n                auto &st = at(j);\n                st.req_ts = ts;\n                st.req = &req;\n            }\n            send_all(sockfd, reinterpret_cast<char const *>(&reqs[i]), sizeof(NetReq) * n);\n            pcounters[CNT_SEND] += batch;\n            pcounters[CNT_SEND_BYTE] += sizeof(NetReq) * n;\n        }\n        done = true;\n    }\n\n\npublic:\n    Client ()\n        : sockfd(-1), done(false), batch(1), queue(100), sleep(100), pcounters(&counters[0])\n    {\n        counters.fill(0);\n    }\n\n    ~Client () {\n        BOOST_VERIFY(sockfd < 0);\n    }\n\n    void setBatch (size_t b) {\n        batch = b;\n    }\n\n    void setQueue (size_t q) {\n        queue = q;\n    }\n\n    void setSleep (size_t s) {\n        sleep = s;\n    }\n\n    // pre-generate random queries\n    template <typename RANDOM_ENGINE>\n    void generate (TicketSpace ts, size_t n, RANDOM_ENGINE &e) {\n        reqs.resize(n);\n        resps.resize(n);\n        resize(n, NetStat());\n        for (unsigned i = 0; i < reqs.size(); ++i) {\n            auto &req = reqs[i];\n            req.reqID = i;\n            ts.sample(e, &req);\n        }\n    }\n\n    void start (string const &server, unsigned short port) {\n        struct sockaddr_in serv_addr;\n        struct hostent *ent;\n\n        BOOST_VERIFY(batch < queue);\n\n        bzero((char *) &serv_addr, sizeof(serv_addr));\n\n        ent = gethostbyname(server.c_str());\n        if (ent == NULL) {\n            throw runtime_error(\"ERROR, no such host\");\n        }\n        serv_addr.sin_family = AF_INET;\n        bcopy((char *)ent->h_addr, \n             (char *)&serv_addr.sin_addr.s_addr,\n             ent->h_length);\n        serv_addr.sin_port = htons(port);\n\n        sockfd = socket(AF_INET, SOCK_STREAM, 0);\n        if (sockfd < 0) \n            throw runtime_error(\"ERROR opening socket\");\n        {\n            int flags = 1;\n            int r = setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&flags), sizeof(flags));\n            if (r != 0) throw runtime_error(\"ERROR setsockopt\");\n        }\n        if (::connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) \n            throw runtime_error(\"ERROR connecting\");\n        rfuture = async(launch::async, &Client::reader, this);\n        wfuture = async(launch::async, &Client::writer, this);\n    }\n\n    void stop () { done = true;\n    }\n\n    void join () {\n        rfuture.get();\n        wfuture.get();\n        close(sockfd);\n        sockfd = -1;\n    }\n\n    void getCounters (Counters *c) const {\n        std::copy(pcounters, pcounters + CNT_NUM, &(*c)[0]);\n    }\n};\n\nvoid count_all (vector<Client> const &clients, Counters *p) {\n    Counters total;\n    total.fill(0);\n    for (auto const &c: clients) {\n        Counters cnts;\n        c.getCounters(&cnts);\n        for (unsigned i = 0; i < total.size(); ++i) {\n            total[i] += cnts[i];\n        }\n    }\n    *p = total;\n}\n\n// print performance counters every cycle seconds\n// stop when *stop becomes true\nvoid monitor_throughput (vector<Client> const *clients, float cycle, bool *stop) {\n    Counters old;\n    count_all(*clients, &old);\n    std::chrono::milliseconds delta(int(cycle * 1000));\n    auto next = std::chrono::system_clock::now() + delta;\n    cout << \"Reporting throughput every \" << cycle << \" seconds...\" << endl;\n    cout << \"Mt/s ==  million transactions per second\" << endl;\n    cout << \"MB/s ==  1024x1024 bytes per second\" << endl;\n    cout.setf(std::ios::fixed);\n    cout.precision(5);\n    double MB = 1024*1024;\n    while (!*stop) {\n        std::this_thread::sleep_until(next);\n        next += delta;\n        Counters cnts;\n        count_all(*clients, &cnts);\n        cout << \"Mt/s \"\n             << \"send: \" << (cnts[CNT_SEND] - old[CNT_SEND]) / cycle / 1000000.0\n             << \" receive: \" << (cnts[CNT_RECV] - old[CNT_RECV]) / cycle / 1000000.0\n             << \" succeed: \" << (cnts[CNT_SUCC] - old[CNT_SUCC]) / cycle / 1000000.0;\n        cout << \"    MB/s \"\n             << \"send: \" << (cnts[CNT_SEND_BYTE] - old[CNT_SEND_BYTE]) / MB\n             << \" receive: \" << (cnts[CNT_RECV_BYTE] - old[CNT_RECV_BYTE]) / MB\n             << endl;\n        old = cnts;\n    }\n}\n\n// MUST BE SINGLETON\n// handle signals during the life cycle of this object\n// when signal received, stop clients\nclass Signal {  \n    static vector<Client> *clients;\n    static void stop_all (int) {\n        if (clients) {\n            for (auto &client: *clients) {\n                client.stop();\n            }\n        }\n    }\npublic:\n    Signal (vector<Client> *clients_) {\n        BOOST_VERIFY(clients == nullptr);\n        clients = clients_;\n        signal(SIGTERM, &Signal::stop_all);\n        signal(SIGINT, &Signal::stop_all);\n    }\n\n    ~Signal () {\n        clients = nullptr;\n        signal(SIGTERM, SIG_DFL);\n        signal(SIGINT, SIG_DFL);\n    }\n};\n\nvector<Client> *Signal::clients = nullptr;\n\nint main (int argc, char *argv[]) {\n\n    namespace po = boost::program_options; \n    TicketSpace tspace;\n    string server;\n    unsigned short port;\n    size_t N, C, B, Q, S;\n    float cycle;\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n    (\"help,h\", \"produce help message.\")\n    (\"server,s\", po::value(&server)->default_value(\"localhost\"), \"\")\n    (\"port,p\", po::value(&port)->default_value(12306), \"\")\n    (\"trains\", po::value(&tspace.trains)->default_value(5000), \"\")\n    (\"segments\", po::value(&tspace.segments)->default_value(10), \"\")\n    (\"seats\", po::value(&tspace.seats)->default_value(3000), \"\")\n    (\"max-length\", po::value(&tspace.max_length)->default_value(5), \"\")\n    (\",N\", po::value(&N)->default_value(10000000), \"queries per client\")\n    (\",C\", po::value(&C)->default_value(4), \"number parallel clients\")\n    (\",B\", po::value(&B)->default_value(20), \"request batch size\")\n    (\",Q\", po::value(&Q)->default_value(1000), \"maximal outstanding request per client\")\n    (\",S\", po::value(&S)->default_value(100), \"if queue is fall, sleep this # us\")\n    (\"cycle\", po::value(&cycle)->default_value(1), \"print counters every cycle seconds\")\n    ;\n\n    po::positional_options_description p;\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).\n                     options(desc).positional(p).run(), vm);\n    po::notify(vm); \n\n    if (vm.count(\"help\")) {\n        cout << desc;\n        return 0;\n    }\n\n    tspace.check_size();\n    \n    vector<Client> clients(C);\n    {\n        auto_cpu_timer timer(cout);\n        cout << \"Generating queries...\" << endl;\n        // this is not efficient when # clients < # available OMP threads\n#pragma omp parallel\n        {\n            int seed = 0;\n#ifdef _OPENMP\n            seed = omp_get_thread_num();\n#endif\n            default_random_engine engine(seed);\n#pragma omp for\n            for (unsigned i = 0; i < clients.size(); ++i) {\n                clients[i].generate(tspace, N, engine);\n            }\n        }\n    }\n\n    {\n        cout << \"Starting clients, interrupt with Ctrl+C...\" << endl;\n        Signal signal(&clients);\n        auto_cpu_timer timer(cout);\n        for (auto &client: clients) {\n            client.setBatch(B);\n            client.setQueue(Q);\n            client.start(server, port);\n        }\n        bool stop_monitor = false;\n        future<void> ft = async(launch::async, monitor_throughput, &clients, cycle, &stop_monitor);\n        // wait for clients\n        for (auto &client: clients) {\n            client.join();\n        }\n        if (clients.empty()) {\n            cout << \"No clients running, sleep 10s for testing...\" << endl;\n            sleep(10); // if no clients, sleep 00s for testing.\n        }\n        stop_monitor = true;\n        asm volatile(\"\": : :\"memory\");\n        // wait for throughput monitor\n        ft.get();\n    }\n\n    // do statistics\n    Counters cnts;\n    count_all(clients, &cnts);\n    cout << \"send: \" << cnts[CNT_SEND] << endl;\n    cout << \"receive: \" << cnts[CNT_RECV] << endl;\n    cout << \"succeed: \" << cnts[CNT_SUCC] << endl;\n    // the array of tickets assigned to each seat\n    vector<NetStat const *> v;\n    size_t asked = 0;\n    size_t succ = 0;\n    size_t sold = 0;\n    Acc acc;\n    for (auto const &client: clients) {\n        for (NetStat const &st: client) {\n            if (!st.req) continue;\n            if (!st.resp) continue;\n            if (st.resp->respID < 0) {\n                cerr << \"respID overflow.\" << endl;\n            }\n            acc(st.latency()); // in seconds\n            ++asked;\n            if (st.sid >= 0) {\n                ++succ;\n                sold += st.req->stop - st.req->start;\n            }\n            v.push_back(&st);\n        }\n    }\n    cout << \"latency.mean: \" << ba::mean(acc) * 1000 << \" ms\" << endl;\n    cout << \"latency.std: \" << sqrt(ba::variance(acc)) * 1000 << \" ms\" << endl;\n    cout << \"latency.min: \" << ba::min(acc) * 1000  << \" ms\" << endl;\n    cout << \"latency.max: \" << ba::max(acc) * 1000 << \" ms\" << endl;\n    cout << \"latency.count: \" << ba::count(acc) << endl;\n    cout << \"fill.rate: \" <<  1.0 * sold / tspace.total_sids() << \"    (rate of inventory sold)\" << endl;\n    cout << \"fulfill.rate: \" <<  1.0 * succ / asked << \"     (rate of reqs satisfied)\" << endl;\n    __gnu_parallel::sort(v.begin(), v.end(),\n                [](NetStat const *p1, NetStat const *p2) {\n                    return p1->resp->respID < p2->resp->respID;\n                });\n    {\n        double max_ood = 0;\n        for (unsigned i = 1; i < v.size(); ++i) {\n            auto prev = v[i-1]->resp->respID;\n            auto cur = v[i]->resp->respID;\n            if (prev >= cur) {\n                cerr << \"respID: \" << prev << \", \" << cur << endl;\n            }\n            double ood = time_diff(v[i-1]->resp_ts, v[i]->resp_ts);\n            if (ood > max_ood) {\n                max_ood = ood;\n            }\n        }\n        cerr << \"ooo.time.max: \" << max_ood * 1000 << \" ms    (big respIDs arrive before small ones)\" << endl;\n    }\n    // detect conflicts 1\n    size_t conflict1 = 0;\n    // conflict1: later successful request containing earlier failed request\n    {\n        vector<Matrix> failed(tspace.trains, ZeroMatrix(tspace.segments, tspace.segments));\n        // failure matrix\n        // elemnet (a, b) = number of times a request [a, b] as failed.\n        for (NetStat const *p: v) {\n            // this test is train specific\n            BOOST_VERIFY(p->req->train < tspace.trains);\n            auto &matrix = failed[p->req->train];\n            int a = p->req->start;\n            int b = p->req->stop-1; // the stop segment is not included as part of the request\n                                    // it is always true that stop >= start + 1\n                                    // so it's always that b >= a\n            BOOST_VERIFY(a >= 0 && a < tspace.segments);\n            BOOST_VERIFY(b >= a && b < tspace.segments);\n            // the segment matrix is a upper-right triangle matrix\n            if (p->sid < 0) {\n                matrix(a, b) += 1;\n            }\n            else {\n                // request for [a, b] succeeded,\n                // ( it's always true that b >= a )\n                // all previous request [A, B] contained in [a, b] must not fail. \n                // equivalently, all matrix entries (A, B) with a <= A <= B <= b must not fail\n                for (int A = a; A <= b; ++A) {\n                    for (int B = A; B <= b; ++B) {\n                        conflict1 += matrix(A, B);\n                    }\n                }\n            }\n        }\n    }\n    cout << \"conflict1: \" << conflict1 << \"    (successful reservation containing failed requests)\" << endl;\n\n    // remove all failed transactions\n    {\n        unsigned i = 0;\n        unsigned sz = v.size();\n        while (i < sz) {\n            if (v[i]->sid < 0) {\n                v[i] = v[sz-1]; // replace v[i] with last element\n                --sz;\n            }\n            else {\n                ++i;\n            }\n        }\n        v.resize(sz);\n    }\n    \n    // detect conflicts 2\n    __gnu_parallel::sort(v.begin(), v.end(),\n                [](NetStat const *p1, NetStat const *p2) {\n                    return p1->sid < p2->sid;\n                });\n    // verify no overlap\n    size_t conflict2 = 0;\n    for (unsigned i = 1; i < v.size(); ++i) {\n        if (v[i-1]->req->train != v[i]->req->train) continue;\n        if (v[i-1]->resp->seat != v[i]->resp->seat) continue;\n        // same seat on same train, detect conflict\n        if (v[i-1]->req->stop >= v[i]->req->start) {\n            /*\n            cout << \"conflict: \"\n                << v[i-1]->resp->reqID << '.'\n                << v[i-1]->resp->respID\n                << \" and \"\n                << v[i]->resp->reqID << '.'\n                << v[i]->resp->respID\n                << endl;\n            */\n            ++conflict2;\n        }\n    }\n    cout << \"conflict2: \" << conflict2 << \"    (seats are sold twice)\" << endl;\n    return 0;\n}\n\n", "meta": {"hexsha": "c95d4d2a19f1116d60cdb4673579e01dfc4c65e0", "size": 18647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pc12306c.cpp", "max_stars_repo_name": "leovegan/12306", "max_stars_repo_head_hexsha": "d9fc9738a6df64f5ca414a18a85a35be3889d4df", "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": "pc12306c.cpp", "max_issues_repo_name": "leovegan/12306", "max_issues_repo_head_hexsha": "d9fc9738a6df64f5ca414a18a85a35be3889d4df", "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": "pc12306c.cpp", "max_forks_repo_name": "leovegan/12306", "max_forks_repo_head_hexsha": "d9fc9738a6df64f5ca414a18a85a35be3889d4df", "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.2869127517, "max_line_length": 149, "alphanum_fraction": 0.5331152464, "num_tokens": 4903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.17108742747700087}}
{"text": "/********************************************************\n  Stanford Driving Software\n  Copyright (c) 2011 Stanford University\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with \n  or without modification, are permitted provided that the \n  following conditions are met:\n\n* Redistributions of source code must retain the above \n  copyright notice, this list of conditions and the \n  following disclaimer.\n* Redistributions in binary form must reproduce the above\n  copyright notice, this list of conditions and the \n  following disclaimer in the documentation and/or other\n  materials provided with the distribution.\n* The names of the contributors may not be used to endorse\n  or promote products derived from this software\n  without specific prior written permission.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n  CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \n  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \n  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n  DAMAGE.\n ********************************************************/\n\n\n#include <boost/format.hpp>\n\n#include <aw_CGAL.h>\n#include <vlrException.h>\n#include <perception/PerceptionObstacles.h>\n//#include <clothoid.h>\n//#include <bezCtxPS.h>\n\n#include <aw_ChsmPlanner.hpp>\n#include <aw_StPause.hpp>\n#include <aw_StActive.hpp>\n#include <aw_LaneChangeManager.hpp>\n#include <obstaclePrediction.h>\n//#include <aw_SituationInterpretation.hpp>\n\nnamespace drc = driving_common;\n\nnamespace vlr {\n\n#undef TRACE\n#define TRACE(str) std::cout << \"[ChsmPlanner] \"<< str << std::endl\n\ntemplate<class T, void*(T::*mem_fn)(void*)>\nvoid* threadCBWrapper(void* ptr) {\n  return (static_cast<T*>(ptr)->*mem_fn)(NULL);\n  }\n\nusing namespace std;\nusing namespace CGAL_Geometry;\nusing namespace driving_common;\n\n#define EPS 0.01\n\n/*---------------------------------------------------------------------------\n * ChsmPlanner::Parameters\n *---------------------------------------------------------------------------*/\nChsmPlanner::Parameters::Parameters() {\n\n  center_line_back_sample_length = -15;      // in what distance are curvepoints sampled behind the car\n  center_line_sample_dist  = 7;    // distance between (re)sampled waypoints\n  center_line_post_smoothing_sample_dist = 1;      // distance between sampled point after clothoid fitting\n  center_line_min_lookahead_dist = 20; // we look at least 20m ahead, regardless of speed\n  smoothing_range = 8;                // smooth over 8 points\n  // kturn params\n  kturn_delta = 4.7;                  // kturn distance offset\n  kturn_radius = 6.0;                 // kturn radius\n  kturn_switch_speed = 0.1;           // switches to next phase if speed below this threshold\n  kturn_switch_distance = 0.5;        // switches to next phase if position difference below this threshold\n\n  // message buffer\n  message_buffer_size = 15;           // size of the internal message buffer\n\n  safety_stop_infront_vehicle_distance = 1.5*SAFETY_DISTANCE; // 1.5 = compensate for measurement failures\n\n  enable_recovery = false;\n  enable_blockade_detection = false;\n\n  // speed related params\n  max_speed_global                      = dgc::dgc_mph2ms(25.0); // maximal velocity used by the planner in m/s\n  curvature_slowdown_factor             = 1.5;              // slowdown factor for curvatures in tentacle mode\n  surface_quality_slowdown_factor       = .5;               // slowdown factor for rough surface areas\n  max_speed_drive                       = dgc::dgc_mph2ms(65);\n  max_speed_kturn                       = dgc::dgc_mph2ms(6);\n  max_speed_intersection                = dgc::dgc_mph2ms(35);\n  max_speed_merge_intersection          = dgc::dgc_mph2ms(35);\n  max_speed_intersection_approach       = dgc::dgc_mph2ms(55);\n  max_speed_traffic_light_approach      = dgc::dgc_mph2ms(45);\n  max_speed_crosswalk_approach_empty    = dgc::dgc_mph2ms(25);\n  max_speed_crosswalk_approach_occupied = dgc::dgc_mph2ms(15);\n  max_speed_goal                        = dgc::dgc_mph2ms(5);\n  max_speed_pass_obstacle               = dgc::dgc_mph2ms(25);\n  max_speed_pass_switch_lane            = dgc::dgc_mph2ms(5); // ?!?\n  max_speed_enter_zone                  = dgc::dgc_mph2ms(5);\n  max_speed_lane_merge_false            = dgc::dgc_mph2ms(5); // ?!?\n}\n\nChsmPlanner::Parameters::~Parameters() {\n\n}\n\n/*---------------------------------------------------------------------------\n * ChsmPlanner\n *---------------------------------------------------------------------------*/\nChsmPlanner::ChsmPlanner(std::string rndf_filename, std::string mdf_filename,\n                        double static_obstacle_map_width, double static_obstacle_map_height,\n                        double static_obstacle_map_resolution)\n                        : pose_queue_(pose_queue_size_), robot_yaw_rate_(0),\n                          vehicle_manager(NULL), topology_(NULL), route_sampler(NULL),\n                          publish_traffic_lights_(false),\n                          current_index_on_mission_(0),\n                          transitionCounter(0),\n                          inPause(true),\n                          traj_eval_(NULL),\n                          last_start_idx_(0),\n                          min_lookahead_s_(0),\n                          lane_change_data(NULL),\n                          stop_before_replanning(true),\n                          forced_start_edge(NULL),\n                          has_pause_lanechange(false),\n                          road_boundaries_enabled( false ),\n                          replan_reason( ChsmPlanner::UNKNOWN ),\n                          static_obstacle_map_raw_(NULL),\n                          static_obstacle_map_tmp_(NULL),\n                          static_obstacle_map_(NULL),\n                          emergency_map_clear_(false),\n                          emergency_stop_initiated_(false),\n                          quit_chsm_planner_(false),\n                          new_static_obstacle_map_ready_(false) {\n\n  pthread_attr_init(&def_thread_attr_);\n\n  pthread_mutex_init(&pose_mutex_, NULL);\n  pthread_mutex_init(&trajectory_mutex_, NULL);\n  pthread_mutex_init(&dyn_obstacles_mutex_, NULL);\n  pthread_mutex_init(&static_obstacle_map_mutex_, NULL);\n  pthread_mutex_init(&static_obstacle_points_mutex_, NULL);\n  pthread_mutex_init(&mission_mutex_, NULL);\n  pthread_mutex_init(&topology_mutex_, NULL);\n  pthread_mutex_init(&center_line_mutex_, NULL);\n  pthread_mutex_init(&intersection_predictor_mutex_, NULL);\n  pthread_mutex_init(&traffic_light_states_mutex_, NULL);\n  pthread_mutex_init(&traffic_light_poses_mutex_, NULL);\n  pthread_mutex_init(&pedestrian_prediction_mutex_, NULL);\n\n  pthread_mutex_init(&static_obstacle_map_cycle_mutex_, NULL);\n  pthread_cond_init(&static_obstacle_map_cycle_cv_, NULL);\n\n  // create helper\n  topology_ = new Topology(rndf_filename.c_str(), mdf_filename.c_str(), \"Topo\");\n  vehicle_manager = new VehicleManager(*topology_);\n  topology_->vehicle_manager = vehicle_manager;\n  route_sampler = new RouteSampler(topology_);\n  blockade_manager = new BlockadeManager(topology_);\n  topology_->blockade_manager = blockade_manager;\n  traj_eval_ = new TrajectoryEvaluator(static_obstacle_map_mutex_, dyn_obstacles_mutex_);\n\n  velocity_desired_ = 0;\n  velocity_following_ = 0;\n  follow_distance_ = 0;\n  stop_distance_ = 0;\n\n  turn_signal_.signal = driving_common::TurnSignal::NONE;\n\n  updateStaticObstacleMapSize(static_obstacle_map_width, static_obstacle_map_height, static_obstacle_map_resolution);\n\n  pthread_create(&obstacle_map_update_thread_id_, &def_thread_attr_,\n      threadCBWrapper<ChsmPlanner, &ChsmPlanner::updateStaticObstacleMapThread>, this);\n\n  bIntersection = false;\n  bOffroad = false;\n\n    // TODO: remove...\n  replan_distance_map_.insert(make_pair(0, 2));\n  replan_distance_map_.insert(make_pair(.5, 2.5));\n  replan_distance_map_.insert(make_pair(6, 3));\n  replan_distance_map_.insert(make_pair(8, 4));\n  replan_distance_map_.insert(make_pair(15, 5));\n  replan_distance_map_.insert(make_pair(20, 6));\n}\n\nChsmPlanner::~ChsmPlanner()\n{\n  delete topology_;\n  delete vehicle_manager;\n  delete route_sampler;\n  delete blockade_manager;\n  quit_chsm_planner_ = true;\n\n  pthread_mutex_lock(&static_obstacle_map_cycle_mutex_);\n  pthread_cond_signal(&static_obstacle_map_cycle_cv_);\n  pthread_mutex_unlock(&static_obstacle_map_cycle_mutex_);\n\n  pthread_join(obstacle_map_update_thread_id_, NULL);\n  if(static_obstacle_map_raw_) {delete[] static_obstacle_map_raw_;}\n  if(static_obstacle_map_tmp_) {delete[] static_obstacle_map_tmp_;}\n  if(static_obstacle_map_) {delete[] static_obstacle_map_;}\n\n  pthread_attr_destroy(&def_thread_attr_);\n\n  pthread_mutex_destroy(&pose_mutex_);\n  pthread_mutex_destroy(&trajectory_mutex_);\n  pthread_mutex_destroy(&dyn_obstacles_mutex_);\n  pthread_mutex_destroy(&static_obstacle_map_mutex_);\n  pthread_mutex_destroy(&static_obstacle_points_mutex_);\n  pthread_mutex_destroy(&mission_mutex_);\n  pthread_mutex_destroy(&topology_mutex_);\n  pthread_mutex_destroy(&center_line_mutex_);\n  pthread_mutex_destroy(&traffic_light_states_mutex_);\n  pthread_mutex_destroy(&traffic_light_poses_mutex_);\n  pthread_mutex_destroy(&pedestrian_prediction_mutex_);\n\n  pthread_mutex_destroy(&static_obstacle_map_cycle_mutex_);\n  pthread_cond_destroy(&static_obstacle_map_cycle_cv_);\n\n}\n\nvoid ChsmPlanner::activate() {\n  process_event(EvActivate());\n}\n\nvoid ChsmPlanner::pause() {\n  process_event(EvPause());\n}\n\nvoid ChsmPlanner::start() {\n\n  if(pose_queue_.empty()) {\n    throw VLRException(\"Could not start chsm planner since current position is unknown (pose queue is empty).\");\n  }\n\n  drc::GlobalPose pose = pose_queue_.pose(drc::Time::current());\n  cout << \"[CHSM] plan the mission\" << endl;\n  addMessage(\"plan the mission\");\n  pthread_mutex_lock(&mission_mutex_);\n  topology_->planMission(pose.utmX(), pose.utmY(), pose.yaw());\n\n  createSmoothedMissionLine();\n\n  last_start_idx_ = 0;\n\n  static bool dump_mission_lines = true;\n\n  if(dump_mission_lines) {\n    std::string ml_name = \"mission_line.txt\";\n    std::string ml_raw_name = \"mission_line_raw.txt\";\n    std::string ml_rndf_name = \"mission_line_rndf.txt\";\n    try {\n      dumpMissionLines(ml_name, ml_raw_name, ml_rndf_name);\n    }\n    catch(vlr::Ex<>& e) {\n      std::cout << \"Could not write center line data for current mission: \" << e.what() << std::endl;\n    }\n  }\n\n  pthread_mutex_unlock(&mission_mutex_);\n\n  pthread_mutex_lock(&topology_mutex_);\n  LaneChangeManager::annotateLaneChanges(topology_);\n  pthread_mutex_unlock(&topology_mutex_);\n\n  // initiate state machine\n  cout << \"[CHSM] initiate state machine\" << endl;\n  addMessage(\"initiate state machine\");\n  initiate();\n}\n\nvoid ChsmPlanner::process()\n{\n  transitionCounter = 0;\n  process_event(EvProcess());\n  process_event(EvAfterProcess());\n}\n\nvoid ChsmPlanner::stop() {\n  //  process_event(EvStop());\n}\n\nuint32_t ChsmPlanner::extendAtMissionStart(std::vector<CurvePoint>& mission) {\n  CurvePoint cp;\n  double extended_length = - 2 * params().center_line_back_sample_length;\n  std::vector<CurvePoint> pre_mission_points;\n  while(extended_length > 0) {\n    extended_length -= params().center_line_post_smoothing_sample_dist;\n    cp.s = mission[0].s - extended_length; // negative s since it's before mission\n    cp.kappa = 0;// smoothed_mission_points_[0].kappa;\n    cp.theta = mission[0].theta;\n    cp.kappa_prime = 0;\n    cp.x = mission[0].x - extended_length*cos(cp.theta);\n    cp.y = mission[0].y - extended_length*sin(cp.theta);\n    pre_mission_points.push_back(cp);\n  }\n  mission.insert(mission.begin(), pre_mission_points.begin(), pre_mission_points.end());\n\nreturn pre_mission_points.size();\n}\n\nuint32_t ChsmPlanner::extendAtMissionEnd(std::vector<CurvePoint>& mission, double front_sample_dist) {\n  CurvePoint cp;\n  CurvePoint& cp_last = mission[mission.size()-1];\n  double extended_length=0;\n  uint32_t num_post_sample_points=0;\n  while(extended_length < front_sample_dist) {\n    extended_length += params().center_line_post_smoothing_sample_dist;\n    cp.s = cp_last.s + extended_length; // negative s since it's before mission\n    cp.kappa = 0;// cp_last.kappa;\n    cp.theta = cp_last.theta;\n    cp.kappa_prime = 0;\n    cp.x = cp_last.x + extended_length*cos(cp.theta);\n    cp.y = cp_last.y + extended_length*sin(cp.theta);\n    mission.push_back(cp);\n    num_post_sample_points++;\n  }\n\n  return num_post_sample_points;\n}\n\nvoid ChsmPlanner::createSmoothedMissionLine() {\n  std::vector<bool> mission_points_to_ignore;\n  route_sampler->sampleMission(mission_points_, mission_points_to_ignore);\n\n  smoother.sampleLinearEquidist(mission_points_, mission_points_to_ignore, params().center_line_sample_dist, sampled_mission_points_);\n\n  if(sampled_mission_points_.size() < 2) {\n    throw VLRException(\"Mission must contain at least 2 waypoints; resampling failed.\");\n  }\n\n    // replacement for clothoid due to licence issues :-(\n  mission_bezier_points_.clear();\n  for(int32_t i=0; i<(int32_t)sampled_mission_points_.size()-1; i++) {\n    CurvePoint& p0 = sampled_mission_points_[i];\n    CurvePoint& p1 = sampled_mission_points_[i+1];\n    CurvePoint tp1, tp2;\n    if(i==0) {\n      CurvePoint& p2 = sampled_mission_points_[i+2];\n      double len0 = hypot(p1.x-p0.x, p1.y-p0.y);\n      double len1 = hypot(p2.x-p1.x, p2.y-p1.y);\n      double scale1 = len0/len1;\n      tp2.x = p1.x - 1./3. * (p2.x-p1.x)*scale1;\n      tp2.y = p1.y - 1./3. * (p2.y-p1.y)*scale1;\n      double lenm1 = hypot(tp2.x-p0.x, tp2.y-p0.y);\n      double scale0 = len0/lenm1;\n      tp1.x = p0.x + 1./3. * (tp2.x-p0.x)*scale0;\n      tp1.y = p0.y + 1./3. * (tp2.y-p0.y)*scale0;\n    }\n    else if((size_t)i==sampled_mission_points_.size()-2) {\n      CurvePoint& pm1 = sampled_mission_points_[i-1];\n      double lenm1 = hypot(p0.x-pm1.x, p0.y-pm1.y);\n      double len0 = hypot(p1.x-p0.x, p1.y-p0.y);\n      double scale0 = len0/lenm1;\n      tp1.x = p0.x + 1./3. * (p0.x-pm1.x)*scale0;\n      tp1.y = p0.y + 1./3. * (p0.y-pm1.y)*scale0;\n      double len1 = hypot(p1.x-tp1.x, p1.y-tp1.y);\n      double scale1 = len0/len1;\n      tp2.x = p1.x - 1./3. * (p1.x-tp1.x)*scale1;\n      tp2.y = p1.y - 1./3. * (p1.y-tp1.y)*scale1;\n    }\n    else {\n      CurvePoint& pm1 = sampled_mission_points_[i-1];\n      CurvePoint& p2 = sampled_mission_points_[i+2];\n      double lenm1 = hypot(p0.x-pm1.x, p0.y-pm1.y);\n      double len0 = hypot(p1.x-p0.x, p1.y-p0.y);\n      double len1 = hypot(p2.x-p1.x, p2.y-p1.y);\n      double scale0 = len0/lenm1;\n      double scale1 = len0/len1;\n      tp1.x = p0.x + 1./3. * (p0.x-pm1.x)*scale0;\n      tp1.y = p0.y + 1./3. * (p0.y-pm1.y)*scale0;\n      tp2.x = p1.x - 1./3. * (p2.x-p1.x)*scale1;\n      tp2.y = p1.y - 1./3. * (p2.y-p1.y)*scale1;\n    }\n    mission_bezier_points_.push_back(p0);\n    mission_bezier_points_.push_back(tp1);\n    mission_bezier_points_.push_back(tp2);\n  }\n\n//  smoother.cubicBezierFromClothoid(sampled_mission_points_, mission_bezier_points_);\n\n  mission_bezier_points_.push_back(sampled_mission_points_[sampled_mission_points_.size()-1]);\n  std::vector<CurvePoint> temp_smoothed_mission_points;\n  std::vector<CurvePoint> temp_smoothed_mission_points2;\n  smoother.sampleCubicBezierEquidist(mission_bezier_points_, 1, temp_smoothed_mission_points);\n\n  extendAtMissionStart(temp_smoothed_mission_points);\n  double post_sample_dist = dgc::dgc_mph2ms(75)*traj_eval_->params().checked_horizon;  // assumed worst case\n  extendAtMissionEnd(temp_smoothed_mission_points, post_sample_dist);\n\n  smoother.clothoideSpline(temp_smoothed_mission_points, temp_smoothed_mission_points[0].theta, temp_smoothed_mission_points[0].kappa, temp_smoothed_mission_points[0].s, params().smoothing_range, smoothed_mission_points_);\n\n  mission_points_set_.clear();\n  std::vector<CurvePoint>::const_iterator cit = temp_smoothed_mission_points.begin();\n  double x0=mission_points_[0].x;\n  double y0=mission_points_[0].y;\n  uint32_t mp_idx=0;\n  for(uint32_t i=0; i<temp_smoothed_mission_points.size(); i++) {\n     if(temp_smoothed_mission_points[i].x == x0 && temp_smoothed_mission_points[i].y == y0) {\n       mission_points_[mp_idx].s=(double)i;   // TODO: index is stored as s, find different structure to store mission data..\n       mission_points_set_.insert(&mission_points_[mp_idx]);\n       mp_idx++;\n       x0=mission_points_[mp_idx].x;\n       y0=mission_points_[mp_idx].y;\n     }\n   }\n\ncreateVelocityProfile();\n}\n\nvoid ChsmPlanner::createVelocityProfile() {\n  // step 1: annotate each points with its maximum velocity\n  Route::RouteEdgeList::const_iterator it = topology_->route.route.begin(), it_end = topology_->route.route.end();\n  Route::RouteEdgeList::const_iterator it_last = --topology_->route.route.end();\n  uint32_t last_idx=0;\n  for(; it != it_end; it++ ) {\n//    const RoutePlanner::AnnotatedRouteEdge::AnnotationList& annotation_list = (*it)->annotations();\n\n    if(it != it_last) {\n      Route::RouteEdgeList::const_iterator it2=it;\n      it2++;\n\n      uint32_t idx = 0, idx2 = 0;\n      try {\n        idx = missionIndex((*it)->edge()->fromVertex()->x(), (*it)->edge()->fromVertex()->y(), last_idx);\n      }\n      catch(vlr::Ex<>& e) {\n        std::cout << e.what() << std::endl;\n      }\n      try {\n        idx2 = missionIndex((*it2)->edge()->fromVertex()->x(), (*it2)->edge()->fromVertex()->y(), idx);\n      }\n      catch(vlr::Ex<>& e) {\n        std::cout << e.what() << std::endl;\n      }\n      last_idx=idx;\n\n        // TODO: Do proper preflight/run to determine state (machine) velocities\n      double max_state_speed = params().max_speed_global;\n//      if(annotation_list.empty()) {continue;}\n//      RoutePlanner::AnnotatedRouteEdge::AnnotationList::const_iterator ait = annotation_list.begin(), ait_end = annotation_list.end();\n//      std::stringstream s;\n//      for(;ait != ait_end; ait++) {\n//        if((*ait)->maneuver() == UC_MANEUVER_TRAVEL) {continue;}\n//      }\n\n      double min_edge_speed=(*it)->edge()->minSpeed();\n      double max_edge_speed=(*it)->edge()->maxSpeed();\n      double max_speed = std::max(min_edge_speed, std::min(max_state_speed, std::min(params().max_speed_global, max_edge_speed)));\n      if(smoothed_mission_points_[idx].kappa >=EPS) {\n        max_speed = std::min(max_speed, sqrt(params().curvature_slowdown_factor/smoothed_mission_points_[idx].kappa));\n      }\n//      if((*it)->edge()->fromVertex()->isStopVertex()) {max_speed=1;}\n      while(idx<idx2) {\n        smoothed_mission_points_[idx++].v=max_speed;\n      }\n    }\n    else {\n      uint32_t idx = 0;\n      try {\n        idx = missionIndex((*it)->edge()->fromVertex()->x(), (*it)->edge()->fromVertex()->y(), last_idx);\n      }\n      catch(vlr::Ex<>& e) {\n        std::cout << e.what() << std::endl;\n      }\n      while(idx<smoothed_mission_points_.size()) {\n        smoothed_mission_points_[idx++].v = 0;\n      }\n    }\n  }\n  double max_accel = 3;\n  double max_decel = -2;\n\n  // 2. Step forward through the mission and make velocities achievable with given accel\n  std::vector<CurvePoint>::iterator mit = smoothed_mission_points_.begin(), mit_end = smoothed_mission_points_.end();\n  for(; mit != mit_end; mit++ ) {\n    std::vector<CurvePoint>::iterator mit2 = mit;\n    mit2++;\n    while(mit2 != mit_end) {\n      if(checkAndReplaceVelocityForward(*mit, *mit2, max_accel)) {break;}\n      mit2++;\n    }\n  }\n\n\n  // 3. Step backwards through the mission and make velocities achievable with given decel\n  std::vector<CurvePoint>::reverse_iterator rit = smoothed_mission_points_.rbegin(), rit_end = smoothed_mission_points_.rend();\n  for(; rit != rit_end; rit++ ) {\n    std::vector<CurvePoint>::reverse_iterator rit2 = rit;\n    rit2++;\n    while(rit2 != rit_end) {\n      if(checkAndReplaceVelocityBackward(*rit, *rit2, max_decel)) {break;}\n      rit2++;\n    }\n  }\n\n    // 4. add time indices\n  mission_time_map_.clear();\n  mit = smoothed_mission_points_.begin(), mit_end = smoothed_mission_points_.end();\n  double last_s, last_v, last_t;\n  if(mit != mit_end) {\n    CurvePoint& cp = *mit;\n    cp.t = 0;\n    last_s=cp.s;\n    last_v=cp.v;\n    last_t=cp.t;\n    mit++;\n  }\n  for(uint32_t i=0; mit != mit_end; mit++, i++) {\n    CurvePoint& cp = *mit;\n    double ds=cp.s-last_s;\n    if(ds==0) {\n      cp.t=last_t;\n      continue;\n    }\n\n    double dv=cp.v-last_v;\n    double a=(cp.v*cp.v-last_v*last_v)/(2*ds);\n    double dt;\n    if (a != 0) {\n      if (dv >= 0) {\n        dt = -last_v / a + sqrt((last_v / a) * (last_v / a) + 2 * ds / a);\n      }\n      else {\n         dt = -last_v / a - sqrt((last_v / a) * (last_v / a) + 2 * ds / a);\n      }\n    }\n    else {\n      if(last_v !=0) {\n        dt = ds/last_v;\n      } else {\n      dt=std::numeric_limits<double>::infinity();\n      }\n    }\n    cp.t = last_t + dt;\n    last_t = cp.t;\n    last_v = cp.v;\n    last_s = cp.s;\n    mission_time_map_.insert(std::make_pair(cp.t, &cp));\n  }\n\n//  {\n//  printf(\"with t:\\n\");\n//  std::vector<CurvePoint>::iterator tmit = smoothed_mission_points_.begin(), tmit_end = smoothed_mission_points_.end();\n//  FILE* f = fopen(\"vt.txt\", \"w\");\n//  for(uint32_t i=0; tmit != tmit_end; tmit++, i++ ) {\n//    fprintf(f, \"%u. %f %f %f\\n\", i, tmit->s, dgc::dgc_ms2mph(tmit->v), tmit->t);\n//  }\n//  fclose(f);\n//  }\n}\n\nbool ChsmPlanner::checkAndReplaceVelocityBackward(CurvePoint& p_ref, CurvePoint& p, double max_decel) {\n\n  if (p.v > p_ref.v) {\n    double t = -p_ref.v/max_decel-sqrt((p_ref.v/max_decel)*(p_ref.v/max_decel)+2*(p.s-p_ref.s)/max_decel);\n    double v_feasible = p_ref.v + max_decel * t;\n    if (p.v > v_feasible) {\n      p.v = v_feasible;\n      return false;\n    }\n  }\n  return true;\n}\n\nbool ChsmPlanner::checkAndReplaceVelocityForward(CurvePoint& p_ref, CurvePoint& p, double max_accel) {\n  if (p.v > p_ref.v) {\n    double t = -p_ref.v/max_accel+sqrt((p_ref.v/max_accel)*(p_ref.v/max_accel)+2*(p.s-p_ref.s)/max_accel);\n    double v_feasible = p_ref.v + max_accel * t;\n    if (v_feasible < p.v) {\n      p.v = v_feasible;\n      return false;\n    }\n  }\n  return true;\n}\n\nvoid ChsmPlanner::updateRobot(double timestamp, double smooth_x, double smooth_y, double offset_x, double offset_y, double yaw, double speed, double ax, double ay, double az, double yaw_rate)\n{\n  pthread_mutex_lock(&pose_mutex_);\n  robot_yaw_rate_ = yaw_rate;\n  double a = ax * cos(-yaw) - ay*sin(-yaw); // TODO: check this...+-theta?!?\n  double a_lat = ax * sin(-yaw) + ay*cos(-yaw);// TODO: check this...+-theta?!?\n\n  pose_queue_.push(GlobalPose(smooth_x, smooth_y, offset_x, offset_y, yaw, 0, 0, speed, 0, 0, a, a_lat, az), timestamp);\n\n  pthread_mutex_unlock(&pose_mutex_);\n\n  if(!topology_->isMissionPlanned()) {return;}\n\n  // update ego vehicle\n  pthread_mutex_lock(&topology_mutex_);\n  topology_->updateEgoVehicle(smooth_x+offset_x, smooth_y+offset_y, yaw, speed);\n  pthread_mutex_unlock(&topology_mutex_);\n\n  // set offroad flag\n  bOffroad = (*topology_->current_edge_it_on_complete_mission_graph)->edge()->isOffroadEdge();\n}\n\nvoid ChsmPlanner::updateTrafficLightStates(const driving_common::TrafficLightStates& tf_states) {\n  pthread_mutex_lock(&traffic_light_states_mutex_);\n  std::vector<driving_common::TrafficLightState>::const_iterator tlsit=tf_states.light_state.begin(), tlsit_end = tf_states.light_state.end();\n\n  for (;tlsit != tlsit_end; tlsit++) {\n\n    // TODO: remove old traffic lights...\n//    printf(\"Got traffic light update for tl id %s (state: %c)\\n\", (*tlsit).name.c_str(), (*tlsit).state);\n    std::map<std::string, driving_common::TrafficLightState>::iterator exists_tlsit = traffic_light_states_.find((*tlsit).name);\n    if (exists_tlsit != traffic_light_states_.end()) {\n      (*exists_tlsit).second = *tlsit;\n    }\n    else {\n      traffic_light_states_.insert(std::make_pair((*tlsit).name, (*tlsit)));\n    }\n  }\n  pthread_mutex_unlock(&traffic_light_states_mutex_);\n}\n\n   // find minimum lane width along center line piece used\n   // for trajectory planning in the next time step\ndouble ChsmPlanner::minLookaheadLaneWidth(Route::RouteEdgeList::iterator edge_it, double front_sample_dist) {\n  double d = 0, lane_width = std::numeric_limits<double>::infinity();\n  while(edge_it != topology_->route.route.end() && d < front_sample_dist) {\n    lane_width = std::min(lane_width, (*edge_it)->edge()->width());\n    d += (*edge_it)->edge()->length();\n    edge_it++;\n  }\n\n  if(lane_width == std::numeric_limits<double>::infinity()) {\n    lane_width = rndf::Lane::default_width;  // TODO: make independent of rndf lib...\n  }\n\n  return lane_width;\n}\n\nuint32_t ChsmPlanner::missionIndex(double x, double y, uint32_t last_idx) {\n  CurvePoint cp;\n  cp.x=x; cp.y=y;\n  return missionIndex(cp, last_idx);\n}\n\nuint32_t ChsmPlanner::missionIndex(CurvePoint& cp, uint32_t last_idx) {\n  std::pair<std::multiset<CurvePoint*, CurvePointComp>::const_iterator,\n            std::multiset<CurvePoint*, CurvePointComp>::const_iterator> range = mission_points_set_.equal_range(&cp);\n\n  if(range.first == range.second) {\n    std::stringstream s;\n    s << \"Mission invalid: requested point (\" << cp.x << \", \" << cp.y << \") is not contained in mission.\";\n    throw VLRException(s.str());\n  }\n\n  std::multiset<CurvePoint*, CurvePointComp>::const_iterator cpit=range.first;\n  for(; cpit != range.second; cpit++) {\n    uint32_t idx = uint32_t((*cpit)->s); // TODO: find a proper way to handle index\n    if(idx>=last_idx) {return idx;}\n  }\n\n  std::stringstream s;\n  s << \"Mission invalid: requested point (\" << cp.x << \", \" << cp.y << \") is not contained in mission before last index (\" << last_idx << \")\";\n  throw VLRException(s.str());\n}\n\nvoid ChsmPlanner::generateCurvePoints(double front_sample_dist, double maxSpeed) {\n\n //printf(\"stop distance: %f\\n\", curvepoints.stop_distance);\n //double dt = Time::current();\n Route::RouteEdgeList::iterator edge_it = topology_->current_edge_it;\n double dist_from_start = topology_->ego_vehicle.distFromStart();\n\n\n   // find current position in smoothed mission data set\n CurvePoint ocp;\n ocp.x = (*edge_it)->edge()->fromVertex()->x();\n ocp.y = (*edge_it)->edge()->fromVertex()->y();\n\n uint32_t min_idx=0;\n try {\n   min_idx = missionIndex(ocp, last_start_idx_);\n }\n catch(vlr::Ex<>& e) {\n   std::cout << \"Error: requesting point on edge \" << (*edge_it)->edge()->name() << \": \" << e.what() << std::endl;\n   throw e;\n }\n\n double s0 = smoothed_mission_points_[min_idx].s + dist_from_start;\n\n    // Hysteresis for lookahead range to avoid velocity oscillations\n  if(min_lookahead_s_ - s0 > front_sample_dist) {\n    front_sample_dist = min_lookahead_s_ - s0;\n  }\n  else {\n    min_lookahead_s_ = s0 + front_sample_dist;\n  }\n\n    // used later on for velocity calculation, this is discretized in original wp steps!\n  current_index_on_mission_ = min_idx;\n\n    // find closest (regarding to s) smoothly sampled index\n  while(smoothed_mission_points_[current_index_on_mission_].s < s0 && current_index_on_mission_<smoothed_mission_points_.size()) {\n      current_index_on_mission_++;\n  }\n      // find index for first back-sampled point\n  while(s0-smoothed_mission_points_[min_idx].s < -params().center_line_back_sample_length) {\n    if(min_idx==0) {break;}\n    min_idx--;\n  }\n\n  last_start_idx_ = min_idx;\n\n  pthread_mutex_lock(&center_line_mutex_);\n  center_line_.clear();\n\n//    // dependent on angle between car and centerline at mission start,\n//    // it's not always possible to project current position onto centerline => extend backwards\n//  if(min_idx == 0 && s0-smoothed_mission_points_[0].s < -params().center_line_back_sample_length) {\n//    extendCenterLineAtMissionStart(s0);\n//   }\n\n  uint32_t idx = min_idx;\n  while(idx<smoothed_mission_points_.size() && smoothed_mission_points_[idx].s-s0 < front_sample_dist) {\n    center_line_.push_back(smoothed_mission_points_[idx]);\n    idx++;\n  }\n\n//  if(idx == smoothed_mission_points_.size()) {\n//    extendCenterLineAtMissionEnd(s0, front_sample_dist);\n//  }\n\n    // for the trajectory generation we need a lookahead range taking the max speed into account, for everything\n    // else, the lookahead range is based on the last desired velocity (replace with last actual?!?)\n  double current_front_sample_dist = std::max(params().center_line_min_lookahead_dist, traj_eval_->params().checked_horizon * velocity_desired_);\n  // calculate desired velocity based on speed limits and curvature\n  velocity_desired_ = calculateVelocity(maxSpeed, current_front_sample_dist);\n  double accel_desired = 0;\n/*  if (current_index_on_mission_ < smoothed_mission_points_.size() - 1) {\n    double mission_t_current = smoothed_mission_points_[current_index_on_mission_].t;\n    uint32_t lookahead_index_ = current_index_on_mission_ + 1;\n    while (lookahead_index_ < smoothed_mission_points_.size()\n            && smoothed_mission_points_[lookahead_index_].t - mission_t_current  < traj_eval_->params().checked_horizon) {\n//      printf(\"mission_t_current: %f, lookahead t: smoothed_mission_points_[current_index_on_mission_].t: %f, dt: %f\\n\",\n//          mission_t_current, smoothed_mission_points_[current_index_on_mission_].t, smoothed_mission_points_[current_index_on_mission_].t- mission_t_current);\n      lookahead_index_++;\n    }\n    if (lookahead_index_ == smoothed_mission_points_.size()) {\n      lookahead_index_--;\n    }\n    velocity_desired_ = std::min(maxSpeed, smoothed_mission_points_[lookahead_index_].v);\n  }\n  else {\n    velocity_desired_ = 0;\n  }\n*/\n  // -------\n  double stop_s;\n  if (stop_distance_ == std::numeric_limits<double>::infinity()) {\n    stop_s = std::numeric_limits<double>::infinity();\n  }\n  else {\n    uint32_t stop_idx = missionIndex(stop_point_, last_start_idx_);\n    stop_s = smoothed_mission_points_[stop_idx].s - FRONT_BUMPER_DELTA;\n  }\n\n  drc::GlobalPose pose = pose_queue_.pose(drc::Time::current());\n\n  double lane_width = minLookaheadLaneWidth(edge_it, current_front_sample_dist)-2.0; // since we want to stay inside lane\n//  lane_width*=3.5; //for circledemo\n\n  double follow_s = s0 + follow_distance_ - 5.0;  // TODO: for at 1m safety distance\n  double accel_following = 0;\n  double current_s = smoothed_mission_points_[current_index_on_mission_].s;\n  //  printf(\"init time: %f\\n\", drc::Time::current() - dt);\n//  printf(\"velocity_desired: %f\\n\", velocity_desired_);\n\n  try {\n    pthread_mutex_lock(&trajectory_mutex_);\n    TrajectoryEvaluator::parameters te_params = traj_eval_->params();\n    te_params.lane_keeping.d_offset_min = -0.5*lane_width;\n    te_params.lane_keeping.d_offset_max =  0.5*lane_width;\n    if(pose.v() < 10) { // TODO: make velocity dependent..more than this parking lot hack...\n      te_params.velocity_keeping.v_offset_max     = 1.0;\n      te_params.velocity_keeping.v_offset_min     = -4.0;\n      te_params.velocity_keeping.v_res            = .5;\n    }\n    else {\n      te_params.velocity_keeping.v_offset_max     = 3.0;\n      te_params.velocity_keeping.v_offset_min     = -8.0;\n      te_params.velocity_keeping.v_res            = 1;\n    }\n    te_params.reinit_dist_thresh = replanDistance(velocity_desired_);\n    traj_eval_->setParams(te_params);\n\n    traj_eval_->makeTrajectory(center_line_, vehicle_manager->vehicle_map, velocity_desired_,\n                               accel_desired, current_s, stop_s, follow_s, velocity_following_, accel_following, pose,\n                               robot_yaw_rate_, trajectory_points_);\n  }\n  catch(vlr::Ex<>& e) {\n    printf(\"Error in trajectory generation: %s\\n\", e.what().c_str());\n    pthread_mutex_unlock(&trajectory_mutex_);\n    pthread_mutex_unlock(&center_line_mutex_);\n\n   // TODO: integrate vehicle interface\n//    vehiclecmd.beeper_on = 1;\n//   vehiclecmd.hazard_lights_on = 1;\n\n//    vehicle_manager->vehicle_map.clear(); // TODO: this will invalidate edge iterators :-(\n    emergency_map_clear_ = true;\n    pthread_mutex_lock(&static_obstacle_map_mutex_);\n    memset(static_obstacle_map_raw_, 0, static_obstacle_map_width_*static_obstacle_map_height_*sizeof(uint8_t));\n    memset(static_obstacle_map_, 0, static_obstacle_map_width_*static_obstacle_map_height_*sizeof(uint8_t));\n    pthread_mutex_unlock(&static_obstacle_map_mutex_);\n\n    generateStopTrajectory();\n    emergency_stop_initiated_=true;\n  }\n  catch(...) {\n    printf(\"Error in trajectory generation.\\n\");\n  }\n\n  pthread_mutex_unlock(&trajectory_mutex_);\n  pthread_mutex_unlock(&center_line_mutex_);\n//  printf(\"generation time: %f\\n\", drc::Time::current() - dt);\n}\n\nvoid ChsmPlanner::generateCurvePoints(double stop_distance, double follow_distance, double maxSpeed) {\n  double front_sample_length = std::max(params().center_line_min_lookahead_dist, traj_eval_->params().checked_horizon * maxSpeed);\n//  double front_sample_length = std::max(params.center_line_min_lookahead_dist, traj_eval_->params().checked_horizon * velocity_desired_);\n\n  if (follow_distance < stop_distance && follow_distance < TRIGGER_DIST_FOLLOWING) { // following mode\n\n    follow_distance_ = follow_distance;\n    stop_distance_ = std::numeric_limits<double>::infinity();\n\n    Vehicle* veh = topology_->get_next_vehicle();\n    if (veh) {\n        // TODO: matched/matched_from incosistent but pose is not used right now...\n      dgc::dgc_pose_t pose;\n      pose.x = veh->xMatched();\n      pose.y = veh->yMatched();\n      pose.z = 0.0;\n      pose.yaw = veh->yawMatchedFrom();\n      pose.pitch = 0.0;\n      pose.roll = 0.0;\n      velocity_following_ = calculateFollowingSpeed(veh->speed(), pose, veh->angleToMatchedEdge());\n    }\n    else {\n      velocity_following_ = 0;\n    }\n    generateCurvePoints(front_sample_length, maxSpeed);\n  }\n  else if (stop_distance < TRIGGER_DIST_STOPLINE) { // stop mode\n   follow_distance_  = std::numeric_limits<double>::infinity();\n    stop_distance_ = stop_distance;\n    generateCurvePoints(front_sample_length, maxSpeed);\n  }\n  else { // drive mode\n    follow_distance_  = std::numeric_limits<double>::infinity();\n    stop_distance_ = std::numeric_limits<double>::infinity();\n    generateCurvePoints(front_sample_length, maxSpeed);\n  }\n}\n\nvoid ChsmPlanner::generateCurvePoints(double maxSpeed) {\n  double stop_distance,follow_distance;\n  double goal_dist = topology_->distToMissionEnd();\n  double kturn_dist = topology_->distToNextKTurn();\n\n\n  if(goal_dist < kturn_dist) {\n    stop_distance = goal_dist;\n    stop_point_.x = mission_points_[mission_points_.size()-1].x;\n    stop_point_.y = mission_points_[mission_points_.size()-1].y;\n    if(stop_distance < 0) {maxSpeed = 0;} // TODO: Otherwise car might start again :-(\n  }\n  else {\n    stop_distance = kturn_dist;\n//    printf(\"TODO: set k turn start point.\\n\");\n//    stop_point_.x = mission_points_[mission_points_.size()-1].x;\n//    stop_point_.y = mission_points_[mission_points_.size()-1].y;\n  }\n\n  double mv_veh_dist, st_veh_dist;\n  getVehicleDistances(st_veh_dist, mv_veh_dist);\n  follow_distance = min(mv_veh_dist, st_veh_dist);\n\n  generateCurvePoints(stop_distance, follow_distance, maxSpeed);\n}\n\nvoid ChsmPlanner::generateStopTrajectory() {\n  velocity_desired_= 0;\n  velocity_following_ = 0;\n  follow_distance_ = std::numeric_limits<double>::infinity();\n  stop_distance_ = std::numeric_limits<double>::infinity();\n  generateCurvePoints(params().center_line_min_lookahead_dist, 0.0);\n}\n\nvoid ChsmPlanner::getVehicleDistances(double& standing, double& moving) {\n  standing = topology_->distToNextStandingVehicle() - params().safety_stop_infront_vehicle_distance;\n  moving = topology_->distToNextMovingVehicle();\n}\n\ndouble ChsmPlanner::calculateCurvatureVelocity(double max_speed, double curvature_slowdown_factor, double sample_length_front) {\n\n  if(current_index_on_mission_>=smoothed_mission_points_.size()) {\n    std::cout << \"Error: position index not in mission.\\n\";\n    return 0.0;\n  }\n\n  double maxAbsCurvature=0;//, meanAbsCurvature=0;\n  double s0 = smoothed_mission_points_[current_index_on_mission_].s;\n\n   // early acceleration: ignore curvature right in front of car\n  s0 += max_speed * 0.5;\n  uint32_t num_points=0, idx=current_index_on_mission_;\n  while(smoothed_mission_points_[idx].s-s0 < sample_length_front) {\n    idx++; num_points++;\n    if(idx==smoothed_mission_points_.size()) {break;}\n\n    maxAbsCurvature = std::max(maxAbsCurvature, std::abs(smoothed_mission_points_[idx].kappa));\n//    meanAbsCurvature += std::abs(smoothed_mission_points_[idx].kappa);\n  }\n\n//  if(num_points>0) {\n//    meanAbsCurvature/=((double)num_points);\n//  }\n\n  //  return max_speed/(1.0+curvature_slowdown_factor*sqrt(maxAbsCurvature));\n//  printf(\"s: %f - macu: %f -> max vel: %f, or: %f or %f or %f\\n\", s0, maxAbsCurvature,\n//      dgc::dgc_ms2mph(std::min(max_speed, sqrt(curvature_slowdown_factor/maxAbsCurvature))),\n//      dgc::dgc_ms2mph(max_speed/(1.0+curvature_slowdown_factor*sqrt(maxAbsCurvature))),\n//      dgc::dgc_ms2mph(max_speed/(1.0+curvature_slowdown_factor*maxAbsCurvature*maxAbsCurvature)),\n//      dgc::dgc_ms2mph(std::min(max_speed, curvature_slowdown_factor/pow(maxAbsCurvature,1.5))));\n\n  if(maxAbsCurvature < EPS) {\n    return max_speed;\n  }\n  else {\n//      return std::min(max_speed, curvature_slowdown_factor/pow(maxAbsCurvature,1.5));\n//    return max_speed/(1.0+curvature_slowdown_factor*maxAbsCurvature*maxAbsCurvature);\n//    return max_speed/(1.0+curvature_slowdown_factor*sqrt(maxAbsCurvature));\n      return std::min(max_speed, sqrt(curvature_slowdown_factor/maxAbsCurvature));\n  }\n}\n\ndouble ChsmPlanner::calculateRoughSurfaceVelocity(double max_speed) {\n//  int i;\n//  double mean=0, var=0;\n//\n//  for(i=0; i<ACCEL_HISTORY_SIZE; i++) {mean+=robot_az[i];}\n//  mean/=((double)ACCEL_HISTORY_SIZE);\n//\n//  for(i=0; i<ACCEL_HISTORY_SIZE; i++) {var+=(robot_az[i]-mean)*(robot_az[i]-mean);}\n//  var/=((double)ACCEL_HISTORY_SIZE); // no bias and simpler :-)\n\n  double var = 0;\n  //cout << \" var \" << var << endl;\n\n  return max_speed/(1.0+params().surface_quality_slowdown_factor*var);\n}\n\ndouble ChsmPlanner::calculateVelocity(double max_state_speed, double sample_length_front) {\n  double min_edge_speed=(*topology_->current_edge_it)->edge()->minSpeed();\n  double max_edge_speed=(*topology_->current_edge_it)->edge()->maxSpeed();\n\n  double max_speed = std::max(min_edge_speed, std::min(max_state_speed, std::min(params().max_speed_global, max_edge_speed)));\n\n  double max_curvature_speed = calculateCurvatureVelocity(max_speed, params().curvature_slowdown_factor, sample_length_front);\n  double max_roughness_speed = calculateRoughSurfaceVelocity(max_curvature_speed);\n\n  double speed = max_roughness_speed; // std::max(min_edge_speed, std::min(max_state_speed, std::min(max_edge_speed, std::min(max_speed, std::min(max_roughness_speed, max_curvature_speed)))));\n//  std::cout << \"max speed:\\nstate: \" << dgc::dgc_ms2mph(max_state_speed) << \" edge: \" << dgc::dgc_ms2mph(max_edge_speed) << \" global: \" << dgc::dgc_ms2mph(max_speed) << \" curvature: \" << dgc::dgc_ms2mph(max_curvature_speed) << \" roughness: \" << dgc::dgc_ms2mph(max_roughness_speed) << \" -> \" << dgc::dgc_ms2mph(speed) << endl;\n  return speed;\n}\n\nint ChsmPlanner::addMessage(const string& message) {\n  last_message_timestamp_ = drc::Time::current();\n  message_buffer_.push_back(message);\n  while(message_buffer_.size()>params().message_buffer_size)\n  message_buffer_.pop_front();\n  return message_buffer_.size();\n}\n\ndouble ChsmPlanner::distance(const GlobalPose& pose) {\n  GlobalPose current_pose = currentPose();\n  return hypot(current_pose.utmX() - pose.utmX(), current_pose.utmY() - pose.utmY());\n}\n\nconst std::string& ChsmPlanner::name() const\n{\n  return name_;\n}\n\nGlobalPose ChsmPlanner::pose(double timestamp) {\n  pthread_mutex_lock(&pose_mutex_);\n  try {\n    GlobalPose pose = pose_queue_.pose(timestamp);\n    pthread_mutex_unlock(&pose_mutex_);\n    return pose;\n  }\n  catch(vlr::Ex<>& e) {\n    pthread_mutex_unlock(&pose_mutex_);\n    throw e;\n  }\n}\n\nvoid ChsmPlanner::latestPose(GlobalPose& latest_pose, double& latest_timestamp) {\n  pthread_mutex_lock(&pose_mutex_);\n  try {\n    pose_queue_.latestPose(latest_pose, latest_timestamp);\n    pthread_mutex_unlock(&pose_mutex_);\n  }\n  catch(vlr::Ex<>& e) {\n    pthread_mutex_unlock(&pose_mutex_);\n    throw e;\n  }\n}\n\nvoid ChsmPlanner::currentLocalizeOffsets(double& offset_x, double& offset_y) {\n  pthread_mutex_lock(&pose_mutex_);\n  pose_queue_.offsets(drc::Time::current(), offset_x, offset_y);\n  pthread_mutex_unlock(&pose_mutex_);\n}\n\n// if the car we want to follow comes towards us the speed will be set to zero\ndouble ChsmPlanner::calculateFollowingSpeed(const double nextVehicleSpeed, const dgc::dgc_pose_t& /*nextVehiclePose*/, const double angleToEdge)\n{\n\n  //double angle_diff = deltaAngle(nextVehiclePose.yaw, robot_pose.yaw);\n  bool is_opposite_angle = angleToEdge > M_PI_2/*  && distance(nextVehiclePose) < 30*/;\n  return is_opposite_angle?-nextVehicleSpeed:nextVehicleSpeed;\n}\n\nvoid perpBisector(double x1, double y1, double x2, double y2, double& AM, double& BM, double& CM) {\n  double A = y2-y1;\n  double B = x1-x2;\n\n  double xm1 = 0.5*(x1+x2);\n  double ym1 = 0.5*(y1+y2);\n\n  double D = -B*xm1 + A*ym1;\n\n  AM = -B;\n  BM = A;\n  CM = D;\n}\n\nvoid ChsmPlanner::estimateKappa(CurvePoint& p1, CurvePoint& p2, CurvePoint& p3, double& kappa) {\n\n    // Ax+By=C\n  double A1, B1, C1, A2, B2, C2;\n  perpBisector(p1.x, p1.y, p2.x, p2.y, A1, B1, C1);\n  perpBisector(p2.x, p2.y, p3.x, p3.y, A2, B2, C2);\n\n  double det = A1*B2 - A2*B1;\n  if(det == 0) {\n     kappa=0;\n     return;\n  }\n\n  double cx = (B2 * C1 - B1 * C2) / det;\n  double cy = (A1 * C2 - A2 * C1) / det;\n\n  kappa = 1.0/hypot(p1.x-cx, p1.y-cy);\n}\n\nvoid ChsmPlanner::dumpMissionLines(std::string& ml_name, std::string& ml_raw_name, std::string& ml_rndf_name) {\n\n  FILE* dbgf = NULL;\n  char buf[1000];\n\n  static const std::string err_str_open = \"Cannot open file \";\n  static const std::string err_str_write = \"Cannot write to file \";\n\n  if(!(dbgf = fopen(ml_name.c_str(), \"w\"))) {\n    throw VLRException(err_str_open + ml_name);\n  }\n\n  for (std::vector<CurvePoint>::const_iterator it = smoothed_mission_points_.begin(); it\n      != smoothed_mission_points_.end(); it++) {\n    sprintf(buf, \"%lf %lf %lf %lf %lf %lf\\n\", (*it).s, (*it).x, (*it).y, (*it).theta, (*it).kappa, (*it).kappa_prime);\n    size_t len = fwrite(buf, 1, strlen(buf), dbgf);\n    if(len != strlen(buf)) {\n      throw VLRException(err_str_write + ml_name);\n    }\n  }\n  fclose(dbgf);\n  dbgf=NULL;\n\n  if(!(dbgf = fopen(ml_rndf_name.c_str(), \"w\"))) {\n    throw VLRException(err_str_open + ml_rndf_name);\n  }\n\n  for (std::vector<CurvePoint>::const_iterator it = mission_points_.begin(); it != mission_points_.end(); it++) {\n    sprintf(buf, \"%lf %lf %lf %lf %lf %lf\\n\", (*it).s, (*it).x, (*it).y, (*it).theta, (*it).kappa, (*it).kappa_prime);\n    size_t len = fwrite(buf, 1, strlen(buf), dbgf);\n    if(len != strlen(buf)) {\n      throw VLRException(err_str_write + ml_rndf_name);\n    }\n  }\n  fclose(dbgf);\n  dbgf=NULL;\n\n  if(!(dbgf = fopen(ml_raw_name.c_str(), \"w\"))) {\n    throw VLRException(err_str_open + ml_raw_name);\n  }\n\n  for (std::vector<CurvePoint>::const_iterator it = sampled_mission_points_.begin(); it\n      != sampled_mission_points_.end(); it++) {\n    sprintf(buf, \"%lf %lf %lf %lf %lf %lf\\n\", (*it).s, (*it).x, (*it).y, (*it).theta, (*it).kappa, (*it).kappa_prime);\n    size_t len = fwrite(buf, 1, strlen(buf), dbgf);\n    if(len != strlen(buf)) {\n      throw VLRException(err_str_write + ml_raw_name);\n    }\n  }\n  fclose(dbgf);\n}\n\ndouble ChsmPlanner::replanDistance(double velocity) {\nstd::map<double, double>::const_iterator rpit = replan_distance_map_.lower_bound(velocity);\nif(rpit != replan_distance_map_.end()) {\n  return rpit->second;\n}\n\nreturn (*(--replan_distance_map_.end())).second;\n}\n\nconst uint32_t ChsmPlanner::pose_queue_size_ = 2000; // buffer 10s @ current applanix rate (or equivalent of localizer rate)\n\n} // namespace vlr\n", "meta": {"hexsha": "4d6c1097808018f4897280456be5978b51538374", "size": 44088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_chsm_planning/src/aw_ChsmPlanner.cpp", "max_stars_repo_name": "EatAllBugs/autonomous_learning", "max_stars_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T08:49:57.000Z", "max_issues_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_chsm_planning/src/aw_ChsmPlanner.cpp", "max_issues_repo_name": "yinflight/autonomous_learning", "max_issues_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_chsm_planning/src/aw_ChsmPlanner.cpp", "max_forks_repo_name": "yinflight/autonomous_learning", "max_forks_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T00:58:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T13:16:09.000Z", "avg_line_length": 38.6059544658, "max_line_length": 328, "alphanum_fraction": 0.6880557068, "num_tokens": 11939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.31069437044942166, "lm_q1q2_score": 0.17107060421750786}}
{"text": "#include <ndt_calibration/ndt_calib.h>\n#include <ndt_calibration/ndt_calib_rviz.h>\n\n#include <ndt_map/ndt_map.h>\n#include <ndt_map/ndt_cell.h>\n#include <ndt_map/pointcloud_utils.h>\n\n#include <tf_conversions/tf_eigen.h>\n#include <eigen_conversions/eigen_msg.h>\n#include <cstdio>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <fstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <dirent.h>\n#include <algorithm>\n\n#include <ros/ros.h>\n\n#include <sensor_msgs/PointCloud2.h>\n\n#include <boost/program_options.hpp>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl_ros/point_cloud.h>\n\nnamespace po = boost::program_options;\nusing namespace std;\n\n\n\n\nint main(int argc, char **argv){\n    std::string gt_file;\n    std::string est_sensorpose_file;\n    std::string base_name_pcd;\n    std::string bag_file;\n    std::string pose_frame;\n    std::string world_frame;\n    Eigen::Vector3d transl;\n    Eigen::Vector3d euler;\n    int score_type, objective_type;\n    double max_translation;\n    double min_rotation;\n    double sensor_time_offset;\n    double resolution;\n    int index_offset;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n\t(\"help\", \"produce help message\")\n\t(\"visualize\", \"visualize the output\")\n\t(\"gt_file\", po::value<std::string>(&gt_file), \"vehicle pose files in world frame\")\n\t(\"est_sensorpose_file\", po::value<std::string>(&est_sensorpose_file)->default_value(std::string(\"\")), \"estimated sensor poses in world frame\")\n\t(\"bag_file\", po::value<std::string>(&bag_file), \"bag file containing the poses to use for performing sensor time offset calibration\")\n\t(\"base_name_pcd\", po::value<string>(&base_name_pcd)->default_value(std::string(\"\")), \"prefix for the .pcd files\")\n      (\"pose_frame\", po::value<string>(&pose_frame)->default_value(\"/state_base_link\"), \"frame containing the vehicle pose\") // EKF\n        (\"world_frame\", po::value<string>(&world_frame)->default_value(\"/world\"), \"default world frame used\")  // World\n\t(\"x\", po::value<double>(&transl[0])->default_value(0.), \"translation vector x\")\n\t(\"y\", po::value<double>(&transl[1])->default_value(0.), \"translation vector y\")\n\t(\"z\", po::value<double>(&transl[2])->default_value(0.), \"translation vector z\")\n\t(\"ex\", po::value<double>(&euler[0])->default_value(0.), \"euler angle vector x\")\n\t(\"ey\", po::value<double>(&euler[1])->default_value(0.), \"euler angle vector y\")\n\t(\"ez\", po::value<double>(&euler[2])->default_value(0.), \"euler angle vector z\")\n\t(\"no_calib\", \"no calibration is performed\")\n\t(\"score_type\", po::value<int>(&score_type)->default_value(3), \"score type used in the optimization, 0 - ICP, 1 - sensorpose difference, 2 - relative sensorpose difference, 3 - NDT\")\n\t(\"objective_type\", po::value<int>(&objective_type)->default_value(0), \"objective type used in the optimization, 0 - full 6D, 1 - only time offset\")\n\n\t(\"max_translation\", po::value<double>(&max_translation)->default_value(3.), \"max allowed translation between two scan pair\")\n\t(\"min_rotation\", po::value<double>(&min_rotation)->default_value(0.2), \"min required rotation between two scan pair\")\n\t(\"sensor_time_offset\", po::value<double>(&sensor_time_offset)->default_value(0.), \"initial time offset for the sensor\")\n        (\"cx\", \"calibrate x axis\")\n        (\"cy\", \"calibrate y axis\")\n        (\"cz\", \"calibrate z axis\")\n        (\"cex\", \"calibrate roll\")\n        (\"cey\", \"calibrate pitch\")\n        (\"cez\", \"calibrate yaw\")\n        (\"ct\", \"calibrate time offset\")\n\t(\"resolution\", po::value<double>(&resolution)->default_value(2.), \"NDT map resolution\")\n      (\"index_offset\", po::value<int>(&index_offset)->default_value(0), \"if there is an index offset bettwen the cloudXXX.pcd and the rows in the pose files\")\n    (\"no_visualize\", \"if the output should not be visualized (visualization markers to RViz)\")\n        ;\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(\"gt_file\"))\n    {\n\tcout << \"Missing gt_file.\\n\";\n\tcout << desc << \"\\n\";\n\treturn 1;\n    }\n    if (vm.count(\"help\"))\n    {\n\tcout << desc << \"\\n\";\n\treturn 1;\n    }\n    bool visualize = !vm.count(\"no_visualize\");\n    bool calib = !vm.count(\"no_calib\");\n    bool cx = vm.count(\"cx\");\n    bool cy = vm.count(\"cy\");\n    bool cz = vm.count(\"cz\");\n    bool cex = vm.count(\"cex\");\n    bool cey = vm.count(\"cey\");\n    bool cez = vm.count(\"cez\");\n    bool ct = vm.count(\"ct\");\n    Eigen::Affine3d Ts;\n    //Ts.setIdentity();\n    Ts = getAsAffine3d(transl, euler);\n    \n    \n    NDTCalibScanPairs pairs;\n    loadNDTCalibScanPairs(gt_file, est_sensorpose_file, base_name_pcd, pairs, max_translation, min_rotation, index_offset);\n    cout << \"Ts : \" << affine3dToString(Ts) << std::endl;\n\n    if (pairs.empty()) {\n      std::cout << \"failed in  loading / no scan pairs detected...\" << std::endl;\n    }\n    std::cout << \"got : \" << pairs.size() << \" scan pairs\" << std::endl;\n\n    std::cout << \"Computing NDTMap... \" << std::endl;\n    pairs.computeNDTMap(resolution);\n    std::cout << \"done.\" << std::endl;\n\n    std::cout << \"Setting up pose interpolation\" << std::endl;\n    PoseInterpolationNavMsgsOdo pose_interp(bag_file, std::string(\"/tf\"), world_frame, ros::Duration(3600));\n    pose_interp.readBagFile();\n    std::cout << \"done.\" << std::endl;\n\n\n    NDTCalibOptimize::ObjectiveType objective(cx, cy, cz, cex, cey, cez, ct);\n\n    NDTCalibOptimize opt(pairs, score_type, objective, pose_interp, pose_frame);\n    std::cout << \"Optimize time : \" << objective.optimizeTime() << std::endl;\n    \n    opt.interpPairPoses(sensor_time_offset);\n\n    std::cout << \" initial sensor pose est : \" << affine3dToString(Ts) << \" dt : \" << sensor_time_offset << \" error : \" << opt.getScore6d(Ts) << std::endl;\n    if (calib) {\n      std::cout << \"starting calibration, using score type : \" << score_type << std::endl;\n      opt.calibrate(Ts, sensor_time_offset);\n      opt.interpPairPoses(sensor_time_offset);\n      std::cout << \"done. \" << std::endl;\n      std::cout << \" new sensor pose est : \" << affine3dToString(Ts) << \" dt : \" << sensor_time_offset << \" error : \" << opt.getScore6d(Ts) << std::endl;\n    }\n\n\n    // ROS based visualization below...\n    if (!visualize) {\n      exit(0);\n    }\n\n    std::cout << \"Starting visualization...\" << std::endl;\n\n    ros::init(argc, argv, \"ndt_calib\");\n    srand(time(NULL));\n\n    ros::NodeHandle nh;\n  \n    visualization_msgs::MarkerArray m_array = ndt_visualisation::getMarkerArrayFromNDTCalibScanPairs(pairs);\n    visualization_msgs::MarkerArray m_array2 = ndt_visualisation::getMarkerArrayRelFromNDTCalibScanPair(pairs[0], Ts);\n\n    ros::Publisher marker_array_pub = nh.advertise<visualization_msgs::MarkerArray>(\"visualization_marker_array\", 10);\n    \n    // Get a global point cloud for all poses with calibration and data in sensor coords.\n    pcl::PointCloud<pcl::PointXYZ> global_cloud;\n    pairs.getGlobalPointCloud(Ts, global_cloud);\n    global_cloud.header.frame_id = \"/world\";\n\n    ros::Publisher pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ> > (\"global_points\", 1);\n    ros::Rate r(1);\n\n    int i = 0;\n    while (ros::ok()) {\n\n      pointcloud_pub.publish(global_cloud);\n\n      // Publish the marker...\n      marker_array_pub.publish(m_array);\n      marker_array_pub.publish(m_array2);\n\n      ros::spinOnce();\n      r.sleep();\n      m_array2 = ndt_visualisation::getMarkerArrayRelFromNDTCalibScanPair(pairs[i++], Ts);\n      i = i % pairs.size();\n    }\n    \n    \n    \n}\n", "meta": {"hexsha": "4e635d18fa754c05648cff11b2474f4cc87a9bf3", "size": 7447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_calibration/src/ndt_calib_main.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_calibration/src/ndt_calib_main.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_calibration/src/ndt_calib_main.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": 38.7864583333, "max_line_length": 182, "alphanum_fraction": 0.6657714516, "num_tokens": 1996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.17097467990390297}}
{"text": "//\n//  electron_optimisation.cpp\n//  indigo-bondorder\n//\n//  Created by Welsh, Ivan on 12/09/17.\n//  Copyright \u00a9 2017 Allison Group. All rights reserved.\n//\n\n#include <algorithm>\n#include <climits>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <boost/algorithm/string.hpp>\n\n#include \"algorithm/electron_optimisation.hpp\"\n#include \"classes/atom.hpp\"\n#include \"classes/electron_graph.hpp\"\n#include \"classes/molecular_graph.hpp\"\n#include \"algorithm/formalbonds/astar.hpp\"\n#include \"algorithm/formalbonds/fpt.hpp\"\n#include \"algorithm/formalbonds/local_optimisation.hpp\"\n#include \"classes/periodictable.hpp\"\n#include \"utils/filereader.hpp\"\n#include \"utils/options.hpp\"\n\nnamespace indigo_bondorder {\n  enum class SortOrder {\n    F_ONE,\n    CL_ONE,\n    BR_ONE,\n    O_ONE,\n    S_ONE,\n    O_TWO,\n    S_TWO,\n    C_TWO_N_ONE,\n    C_TWO_C_TWO,\n    C_THREE_C_THREE,\n    N_ONE,\n    P_ONE,\n    N_TWO,\n    P_TWO,\n    N_THREE,\n    P_THREE,\n    C_THREE_O_ONE,\n    O_ONE_S_FOUR,\n    C_THREE_S_ONE,\n    O_ONE_P_FOUR,\n    C_THREE_N_TWO,\n    N_TWO_N_TWO,\n    N_THREE_O_ONE,\n    UNDEFINED\n  };\n}\n\nusing namespace indigo_bondorder;\ntypedef Options::AssignElectrons opt_;\n\n\n\nElectronOpt::ElectronOpt()\n: electronsToAdd_(0), molGraph_(std::make_shared<MolecularGraph>()),\nelnGraph_(std::make_shared<ElectronGraph>()) { }\n\nElectronOpt::ElectronOpt(std::shared_ptr<MolecularGraph> G)\n: electronsToAdd_(0), molGraph_(G),\nelnGraph_(std::make_shared<ElectronGraph>()) { }\n\nvoid ElectronOpt::SetMolecularGraph(std::shared_ptr<MolecularGraph> G) {\n  molGraph_ = G;\n  elnGraph_.reset(new ElectronGraph(*G));\n}\n\nsize_t ElectronOpt::Run() {\n  possibleLocations_.clear();\n  if (scores_.empty()) LoadScores();\n  \n  switch (opt_::ALGORITHM) {\n    case opt_::Algorithm::LOCAL_OPTIMISATION:\n      algo_.reset(new algorithm::LocalOptimisation(this));\n      break;\n    case opt_::Algorithm::ASTAR:\n      algo_.reset(new algorithm::AStarOptimisation(this));\n      break;\n    case opt_::Algorithm::FPT:\n      algo_.reset(new algorithm::FPTOptimisation(this));\n      break;\n      \n    default:\n      throw std::runtime_error(\"Unsupported optimisation algorithm\");\n      break;\n  }\n  SetMolecularGraph(molGraph_);\n  DetermineElectronsToAdd();\n  DeterminePotentialElectronLocations();\n  if (opt_::ALGORITHM == opt_::Algorithm::ASTAR) SortPotentialLocations();\n  algo_->PopulateMVP2EV();\n  algo_->Run();\n  size_t res = algo_->GetResultCount();\n  finalScore_ = algo_->GetResultEnergy();\n  return res;\n}\n\nbool ElectronOpt::ApplyElectronAssigment(Uint i) {\n  return algo_->ApplyElectronAssignment(i);\n}\n\nvoid ElectronOpt::DetermineElectronsToAdd() {\n  electronsToAdd_ = -molGraph_->GetTotalCharge();\n  MolVertIterPair vs = molGraph_->GetVertices();\n  for (MolVertexIter v = vs.first; v != vs.second; ++v)\n    electronsToAdd_ += molGraph_->GetProperties(*v)->atom->GetElement()->GetValenceElectronCount();\n  // All bonds should have order of at least 1\n  // Preplace code\n  ElnVertIterPair elnvs = elnGraph_->GetVertices();\n  for (; elnvs.first != elnvs.second; ++elnvs.first)\n    electronsToAdd_ -= elnGraph_->GetProperties(*elnvs.first)->pre_placed;\n  //electronsToAdd_ -= 2 * molGraph_->NumEdges();\n  // End Preplace code\n  \n  if (opt_::AUTO_USE_ELECTRON_PAIRS && electronsToAdd_ % 2)\n    opt_::USE_ELECTRON_PAIRS = false;\n  else if (opt_::AUTO_USE_ELECTRON_PAIRS)\n    opt_::USE_ELECTRON_PAIRS = true;\n  \n  if (opt_::USE_ELECTRON_PAIRS && electronsToAdd_ % 2)\n    throw std::runtime_error(\"Unable to handle odd number of electrons when using electron pairs.\");\n  else if (opt_::USE_ELECTRON_PAIRS)\n    electronsToAdd_ /= 2;\n}\n\nvoid ElectronOpt::DeterminePotentialElectronLocations() {\n  MolVertIterPair vs = molGraph_->GetVertices();\n  for (MolVertexIter v = vs.first; v != vs.second; ++v) {\n    int8_t octet;\n    if (molGraph_->Degree(*v) > 2)\n      octet = molGraph_->GetProperties(*v)->atom->GetElement()->GetHypervalentOctet();\n    else\n      octet = molGraph_->GetProperties(*v)->atom->GetElement()->GetOctet();\n    \n    int8_t bondedElectrons = 2 * molGraph_->Degree(*v);\n    int8_t missingElectrons = octet - bondedElectrons;\n    \n    MolVertPair id = std::make_pair(*v, *v);\n    // Preplace code\n    ElnVertex ev = elnGraph_->GetVertex(id);\n    missingElectrons -= elnGraph_->GetProperties(ev)->pre_placed;\n    // End Preplace code\n    \n    while (missingElectrons > 0) {\n      possibleLocations_.push_back(id);\n      if (opt_::USE_ELECTRON_PAIRS)\n        missingElectrons -= 2;\n      else\n        missingElectrons -= 1;\n    }\n  }\n  \n  MolEdgeIterPair es = molGraph_->GetEdges();\n  for (MolEdgeIter e = es.first; e != es.second; ++e) {\n    MolVertex u = molGraph_->GetSource(*e);\n    MolVertex v = molGraph_->GetTarget(*e);\n    if (u > v) {\n      MolVertex tmp = u;\n      u = v;\n      v = tmp;\n    }\n    int8_t u_oct, v_oct, u_bond, v_bond, u_miss, v_miss;\n    if (molGraph_->Degree(u) > 2)\n      u_oct = molGraph_->GetProperties(u)->atom->GetElement()->GetHypervalentOctet();\n    else\n      u_oct = molGraph_->GetProperties(u)->atom->GetElement()->GetOctet();\n    if (molGraph_->Degree(v) > 2)\n      v_oct = molGraph_->GetProperties(v)->atom->GetElement()->GetHypervalentOctet();\n    else\n      v_oct = molGraph_->GetProperties(v)->atom->GetElement()->GetOctet();\n    u_bond = 2 * molGraph_->Degree(u);\n    v_bond = 2 * molGraph_->Degree(v);\n    u_miss = u_oct - u_bond;\n    v_miss = v_oct - v_bond;\n    uint8_t order = 1;\n    MolVertPair id = std::make_pair(u, v);\n    // TODO: Check energy tables for available bond orders\n    while (u_miss > 0 && v_miss > 0 && order <= opt_::MAXIMUM_BOND_ORDER) {\n      possibleLocations_.push_back(id);\n      if (!opt_::USE_ELECTRON_PAIRS)\n        possibleLocations_.push_back(id);\n      u_miss -= 2;\n      v_miss -= 2;\n      order++;\n    }\n  }\n}\n\nvoid ElectronOpt::LoadScores() {\n  PeriodicTable_p pt = PeriodicTable::GetInstance();\n  if (Options::DATA_DIRECTORY.back() != '/') {\n    Options::DATA_DIRECTORY.append(\"/\");\n  }\n  String atmFile = Options::DATA_DIRECTORY + opt_::ATOM_ENERGY_FILE;\n  utils::FileReader at(atmFile);\n  String bndFile = Options::DATA_DIRECTORY + opt_::BOND_ENERGY_FILE;\n  utils::FileReader bn(bndFile);\n  std::vector<std::string> at_items, bn_items;\n  at.GetAllItems(at_items);\n  bn.GetAllItems(bn_items);\n  \n  int64_t global_min = LLONG_MAX;\n  std::map<String, int64_t> la_mins;\n  std::map<std::pair<String, String>, int64_t> lb_mins;\n  \n  // Convert atom energies to ints\n#define NUM_DECIMAL_PLACE 5\n  for (size_t i = 2; i < at_items.size(); i += 3) {\n    std::string lead, tail;\n    size_t sep_pos = at_items[i].find_first_of('.');\n    if (sep_pos == std::string::npos)\n      throw std::invalid_argument(at_items[i] + std::string(\" is not a decimal value.\"));\n    lead = at_items[i].substr(0, sep_pos);\n    tail = at_items[i].substr(sep_pos + 1, NUM_DECIMAL_PLACE);\n    while (tail.size() < NUM_DECIMAL_PLACE) tail.append(\"0\");\n    int64_t score;\n    try {\n      score = std::stoll(lead + tail);\n    } catch (const std::invalid_argument& e) {\n      throw std::invalid_argument(at_items[i] + std::string(\" is not a decimal value.\"));\n    }\n    if (la_mins.find(at_items[i-2]) == la_mins.end()) {\n      la_mins.emplace(at_items[i-2], score);\n    } else if (la_mins.at(at_items[i-2]) > score) {\n      la_mins.at(at_items[i-2]) = score;\n    }\n    if (score < global_min) global_min = score;\n    at_items[i] = lead + tail;\n  }\n  \n  // Convert bond energies to ints\n  for (size_t i = 3; i < bn_items.size(); i += 4) {\n    std::string lead, tail;\n    size_t sep_pos = bn_items[i].find_first_of('.');\n    if (sep_pos == std::string::npos)\n      throw std::invalid_argument(bn_items[i] + std::string(\" is not a decimal value.\"));\n    lead = bn_items[i].substr(0, sep_pos);\n    tail = bn_items[i].substr(sep_pos + 1, NUM_DECIMAL_PLACE);\n    while (tail.size() < NUM_DECIMAL_PLACE) tail.append(\"0\");\n    int64_t score;\n    try {\n      score = std::stoll(lead + tail);\n    } catch (const std::invalid_argument& e) {\n      throw std::invalid_argument(bn_items[i] + std::string(\" is not a decimal value.\"));\n    }\n    if (score < global_min) global_min = score;\n    \n    String atomA = bn_items[i-3];\n    String atomB = bn_items[i-2];\n    size_t pos_sign_a, pos_sign_b;\n    pos_sign_a = atomA.find_first_of('+');\n    pos_sign_b = atomB.find_first_of('+');\n    \n    if (pos_sign_a != std::string::npos) {\n      atomA = atomA.substr(0, pos_sign_a);\n    } else {\n      pos_sign_a = atomA.find_first_of('-');\n      if (pos_sign_a != std::string::npos) atomA = atomA.substr(0, pos_sign_a);\n    }\n    \n    if (pos_sign_b != std::string::npos) {\n      atomB = atomB.substr(0, pos_sign_b);\n    } else {\n      pos_sign_b = atomB.find_first_of('-');\n      if (pos_sign_b != std::string::npos) atomB = atomB.substr(0, pos_sign_b);\n    }\n    \n    std::pair<String, String> b1 = std::make_pair(atomA, atomB);\n    std::pair<String, String> b2 = std::make_pair(atomB, atomA);\n    if (lb_mins.find(b1) == lb_mins.end()) {\n      lb_mins.emplace(b1, score);\n    } else if (lb_mins.at(b1) > score) {\n      lb_mins.at(b1) = score;\n    }\n    if (lb_mins.find(b2) == lb_mins.end()) {\n      lb_mins.emplace(b2, score);\n    } else if (lb_mins.at(b2) > score) {\n      lb_mins.at(b2) = score;\n    }\n    bn_items[i] = lead + tail;\n  }\n  \n  // Load atom energies\n  for (size_t i = 0; i < at_items.size(); i += 3) {\n    uint8_t Z = pt->GetElement(at_items[i])->GetAtomicNumber();\n    if (Z == 0) throw std::invalid_argument(at_items[i] + std::string(\" is not a valid atomic symbol.\"));\n    int fc;\n    try {\n      fc = std::stoi(at_items[i + 1]);\n    } catch (const std::invalid_argument& e) {\n      throw std::invalid_argument(at_items[i+1] + std::string(\" is not an integer value.\"));\n    }\n    uint32_t k = Z + (std::abs(fc) << 8);\n    if (fc < 0) k += (1 << 15);\n    Score val = (Score)(std::stoll(at_items[i + 2]) - la_mins.at(at_items[i]));\n    scores_.emplace(k, val);\n  }\n  \n  // Load bond energies\n  for (size_t i = 0; i < bn_items.size(); i += 4) {\n    char a_sign, b_sign;\n    size_t pos_sign_a, pos_sign_b;\n    pos_sign_a = bn_items[i].find_first_of('+');\n    pos_sign_b = bn_items[i + 1].find_first_of('+');\n    \n    if (pos_sign_a != std::string::npos) {\n      a_sign = '+';\n      bn_items[i] = bn_items[i].substr(0, pos_sign_a);\n    } else {\n      pos_sign_a = bn_items[i].find_first_of('-');\n      if (pos_sign_a != std::string::npos) {\n        a_sign = '-';\n        bn_items[i] = bn_items[i].substr(0, pos_sign_a);\n      } else a_sign = '0';\n    }\n    \n    if (pos_sign_b != std::string::npos) {\n      b_sign = '+';\n      bn_items[i+1] = bn_items[i+1].substr(0, pos_sign_b);\n    } else {\n      pos_sign_b = bn_items[i+1].find_first_of('-');\n      if (pos_sign_b != std::string::npos) {\n        b_sign = '-';\n        bn_items[i+1] = bn_items[i+1].substr(0, pos_sign_b);\n      } else b_sign = '0';\n    }\n    \n    uint8_t Za = pt->GetElement(bn_items[i])->GetAtomicNumber();\n    uint8_t Zb = pt->GetElement(bn_items[i+1])->GetAtomicNumber();\n    if (Za == 0) throw std::invalid_argument(at_items[i] + std::string(\" is not a valid atomic symbol.\"));\n    if (Zb == 0) throw std::invalid_argument(at_items[i+1] + std::string(\" is not a valid atomic symbol.\"));\n    \n    int order;\n    try {\n      order = std::stoi(bn_items[i + 2]);\n    } catch (const std::invalid_argument& e) {\n      throw std::invalid_argument(bn_items[i+2] + std::string(\" is not an integer value.\"));\n    }\n    if (order < 1) throw std::invalid_argument(bn_items[i+2] + std::string(\" is an invalid bond order.\"));\n    \n    uint32_t k1 = Za + (Zb << 8) + ((order * 2) << 20);\n    uint32_t k2 = Zb + (Za << 8) + ((order * 2) << 20);\n    \n    if (a_sign == '+') {\n      k1 += (1 << 16);\n      k2 += (1 << 18);\n    } else if (a_sign == '-') {\n      k1 += (2 << 16);\n      k2 += (2 << 18);\n    }\n    \n    if (b_sign == '+') {\n      k2 += (1 << 16);\n      k1 += (1 << 18);\n    } else if (b_sign == '-') {\n      k2 += (2 << 16);\n      k1 += (2 << 18);\n    }\n    std::pair<String, String> bondType = std::make_pair(bn_items[i], bn_items[i+1]);\n    Score val = (Score)(std::stoll(bn_items[i + 3]) - lb_mins.at(bondType));\n//    Score val = (Score)(std::stoll(bn_items[i + 3]) - global_min);\n    scores_.emplace(k1, val);\n    if (k1 != k2) scores_.emplace(k2, val);\n  }\n}\n\nvoid ElectronOpt::SortPotentialLocations() {\n  std::vector<ElnVertProp*> sortedUniques;\n  sortedUniques.reserve(possibleLocations_.size());\n  for (MolVertPair& vp : possibleLocations_) {\n    ElnVertProp* p = elnGraph_->GetProperties(elnGraph_->GetVertex(vp));\n    if (vp.first == vp.second) {\n      MolVertProp* prop = molGraph_->GetProperties(vp.first);\n      switch (prop->atom->GetElement()->GetAtomicNumber()) {\n        case 7:  // Nitrogen\n          switch (molGraph_->Degree(vp.first)) {\n            case 1: p->sort_score = SortOrder::N_ONE; break;\n            case 2: p->sort_score = SortOrder::N_TWO; break;\n            case 3: p->sort_score = SortOrder::N_THREE; break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 8:  // Oxygen\n          switch (molGraph_->Degree(vp.first)) {\n            case 1: p->sort_score = SortOrder::O_ONE; break;\n            case 2: p->sort_score = SortOrder::O_TWO; break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 9:  // Fluorine\n          switch (molGraph_->Degree(vp.first)) {\n            case 1: p->sort_score = SortOrder::F_ONE; break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 15:  // Phosphorus\n          switch (molGraph_->Degree(vp.first)) {\n            case 1: p->sort_score = SortOrder::P_ONE; break;\n            case 2: p->sort_score = SortOrder::P_TWO; break;\n            case 3: p->sort_score = SortOrder::P_THREE; break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 16:  // Sulfur\n          switch (molGraph_->Degree(vp.first)) {\n            case 1: p->sort_score = SortOrder::S_ONE; break;\n            case 2: p->sort_score = SortOrder::S_ONE; break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 17:  // Chlorine\n          switch (molGraph_->Degree(vp.first)) {\n            case 1: p->sort_score = SortOrder::CL_ONE; break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 35:\n          switch (molGraph_->Degree(vp.first)) {\n            case 1: p->sort_score = SortOrder::BR_ONE; break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        default: p->sort_score = SortOrder::UNDEFINED; break;\n      }\n    } else {\n      MolVertProp* propa = molGraph_->GetProperties(vp.first);\n      MolVertProp* propb = molGraph_->GetProperties(vp.second);\n      switch (propa->atom->GetElement()->GetAtomicNumber()) {\n        case 6:\n          switch (propb->atom->GetElement()->GetAtomicNumber()) {\n            case 6:\n              if (molGraph_->Degree(vp.first) == 2\n                  && molGraph_->Degree(vp.second) == 2)\n                p->sort_score = SortOrder::C_TWO_C_TWO;\n              else if (molGraph_->Degree(vp.first) == 3\n                    && molGraph_->Degree(vp.second) == 3)\n                  p->sort_score = SortOrder::C_THREE_C_THREE;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 7:\n              if (molGraph_->Degree(vp.first) == 2\n                  && molGraph_->Degree(vp.second) == 1)\n                p->sort_score = SortOrder::C_TWO_N_ONE;\n              else if (molGraph_->Degree(vp.first) == 3\n                       && molGraph_->Degree(vp.second) == 2)\n                p->sort_score = SortOrder::C_THREE_N_TWO;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 8:\n              if (molGraph_->Degree(vp.first) == 3\n                  && molGraph_->Degree(vp.second) == 1)\n                p->sort_score = SortOrder::C_THREE_O_ONE;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 16:\n              if (molGraph_->Degree(vp.first) == 3\n                  && molGraph_->Degree(vp.second) == 1)\n                p->sort_score = SortOrder::C_THREE_S_ONE;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 7:\n          switch (propb->atom->GetElement()->GetAtomicNumber()) {\n            case 6:\n              if (molGraph_->Degree(vp.first) == 1\n                  && molGraph_->Degree(vp.second) == 2)\n                p->sort_score = SortOrder::C_TWO_N_ONE;\n              else if (molGraph_->Degree(vp.first) == 2\n                       && molGraph_->Degree(vp.second) == 3)\n                p->sort_score = SortOrder::C_THREE_N_TWO;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 7:\n              if (molGraph_->Degree(vp.first) == 2\n                  && molGraph_->Degree(vp.second) == 2)\n                p->sort_score = SortOrder::N_TWO_N_TWO;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 8:\n              if (molGraph_->Degree(vp.first) == 3\n                  && molGraph_->Degree(vp.second) == 1)\n                p->sort_score = SortOrder::N_THREE_O_ONE;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 8:\n          switch (propb->atom->GetElement()->GetAtomicNumber()) {\n            case 6:\n              if (molGraph_->Degree(vp.first) == 1\n                  && molGraph_->Degree(vp.second) == 3)\n                p->sort_score = SortOrder::C_THREE_O_ONE;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 7:\n              if (molGraph_->Degree(vp.first) == 1\n                  && molGraph_->Degree(vp.second) == 3)\n                p->sort_score = SortOrder::N_THREE_O_ONE;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 15:\n              if (molGraph_->Degree(vp.first) == 1\n                  && molGraph_->Degree(vp.second) == 4)\n                p->sort_score = SortOrder::O_ONE_P_FOUR;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 16:\n              if (molGraph_->Degree(vp.first) == 1\n                  && molGraph_->Degree(vp.second) == 4)\n                p->sort_score = SortOrder::O_ONE_S_FOUR;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 15:\n          switch (propb->atom->GetElement()->GetAtomicNumber()) {\n            case 8:\n              if (molGraph_->Degree(vp.first) == 4\n                  && molGraph_->Degree(vp.second) == 1)\n                p->sort_score = SortOrder::O_ONE_P_FOUR;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        case 16:\n          switch (propb->atom->GetElement()->GetAtomicNumber()) {\n            case 6:\n              if (molGraph_->Degree(vp.first) == 1\n                  && molGraph_->Degree(vp.second) == 3)\n                p->sort_score = SortOrder::C_THREE_S_ONE;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            case 8:\n              if (molGraph_->Degree(vp.first) == 4\n                  && molGraph_->Degree(vp.second) == 1)\n                p->sort_score = SortOrder::O_ONE_S_FOUR;\n              else p->sort_score = SortOrder::UNDEFINED;\n              break;\n            default: p->sort_score = SortOrder::UNDEFINED; break;\n          }\n          break;\n        default: p->sort_score = SortOrder::UNDEFINED; break;\n      }\n    }\n    \n    sortedUniques.push_back(p);\n  }\n  std::stable_sort(sortedUniques.begin(), sortedUniques.end(),\n                   [](const ElnVertProp* lhs, const ElnVertProp* rhs) {\n                     if (opt_::ALGORITHM == opt_::Algorithm::ASTAR)\n                       return lhs->sort_score < rhs->sort_score;\n                     else return lhs->sort_score > rhs->sort_score;\n                   });\n  \n  for (unsigned int i = 0; i < sortedUniques.size(); ++i)\n    possibleLocations_[i] = sortedUniques[i]->id;\n}\n", "meta": {"hexsha": "8c0b4110821735c0f3ddde699ee0f9f325d035a1", "size": 20632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithm/electron_optimisation.cpp", "max_stars_repo_name": "Cuboxylate/indigo-bondorder", "max_stars_repo_head_hexsha": "a7d4543b4245c5b987c45c1440cc5764f862fce5", "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/algorithm/electron_optimisation.cpp", "max_issues_repo_name": "Cuboxylate/indigo-bondorder", "max_issues_repo_head_hexsha": "a7d4543b4245c5b987c45c1440cc5764f862fce5", "max_issues_repo_licenses": ["MIT"], "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/algorithm/electron_optimisation.cpp", "max_forks_repo_name": "Cuboxylate/indigo-bondorder", "max_forks_repo_head_hexsha": "a7d4543b4245c5b987c45c1440cc5764f862fce5", "max_forks_repo_licenses": ["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.1330998249, "max_line_length": 108, "alphanum_fraction": 0.5852074447, "num_tokens": 5772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.17092509650703971}}
{"text": "\n//------------------------------------------------------------------\n//  **MEDYAN** - Simulation Package for the Mechanochemical\n//               Dynamics of Active Networks, v4.0\n//\n//  Copyright (2015-2018)  Papoian Lab, University of Maryland\n//\n//                 ALL RIGHTS RESERVED\n//\n//  See the MEDYAN web page for more information:\n//  http://www.medyan.org\n//------------------------------------------------------------------\n#if defined(HYBRID_NLSTENCILLIST) || defined(SIMDBINDINGSEARCH)\n#include \"Compartment.h\"\n#include \"Filament.h\"\n#include \"Cylinder.h\"\n#include \"Bead.h\"\n#include \"HybridBindingSearchManager.h\"\n#include \"HybridNeighborListImpl.h\"\n#include \"MotorGhost.h\"\n#include \"MathFunctions.h\"\n#include \"GController.h\"\n#include \"SysParams.h\"\n#include \"CUDAcommon.h\"\n#include \"Rand.h\"\n/*#include <boost/range/counting_range.hpp>\n#include <thrust/execution_policy.h>\n#include <thrust/system/omp/execution_policy.h>\n#include <thrust/sort.h>\n#include <thrust/iterator/iterator_traits.h>\n#include <thrust/binary_search.h>\n#include <cstdlib>\n#include <thrust/scan.h>*/\n\n#include \"CController.h\"\n\n\n\nvector<short> HybridBindingSearchManager::HNLIDvec;\nusing namespace mathfunc;\n\nvoid HybridBindingSearchManager::setbindingsearchparameter(\n\tFilamentBindingManager* fmanager,\n\tshort bstatepos, short ftype1, short ftype2, float rMax, float rMin) {\n\n    unordered_map<uint32_t, vector<uint32_t>> tempuint;\n    unordered_map<uint32_t, vector<uint32_t>> rtempuint;\n    int tempNbind;\n\n    bool isfound = false;\n    vector<short> ftypepairs;\n    if(ftype1 < ftype2)\n        ftypepairs = {ftype1,ftype2};\n    else\n        ftypepairs = {ftype2, ftype1};\n    for(short idx = 0; idx < totaluniquefIDpairs; idx++){\n        vector<short> fIDpair = _filamentIDvec[idx];\n        if(fIDpair[0] != ftypepairs[0] || fIDpair[1] != ftypepairs[1]) continue;\n        else {\n            isfound = true;\n            _rMaxsqvec[idx].push_back(rMax *rMax);\n            _rMinsqvec[idx].push_back(rMin *rMin);\n            fManagervec[idx].push_back(fmanager);\n\n            _possibleBindingsstencilvecuint[idx].push_back(tempuint);\n            _reversepossibleBindingsstencilvecuint[idx].push_back(rtempuint);\n            bstateposvec[idx].push_back(bstatepos);\n            Nbindingpairs[idx].push_back(tempNbind);\n            break;\n        }\n    }\n    if(isfound == false){\n        vector<unordered_map<uint32_t, vector<uint32_t>>> temp2uint;\n        vector<unordered_map<uint32_t, vector<uint32_t>>> rtemp2uint;\n\n        vector<int> tempNbind2={0};\n        temp2uint.push_back(tempuint);\n        rtemp2uint.push_back(rtempuint);\n\n        Nbindingpairs.push_back(tempNbind2);\n        vector<float> localrmaxsq ={rMax * rMax};\n        vector<float> localrminsq = {rMin * rMin};\n        vector<FilamentBindingManager*> localfmanager;\n        vector<short> localbstateposvec = {bstatepos};\n        _rMaxsqvec.push_back(localrmaxsq);\n        _rMinsqvec.push_back(localrminsq);\n        localfmanager.push_back(fmanager);\n        fManagervec.push_back(localfmanager);\n        _filamentIDvec.push_back(ftypepairs);\n        _possibleBindingsstencilvecuint.push_back(temp2uint);\n        _reversepossibleBindingsstencilvecuint.push_back(rtemp2uint);\n        bstateposvec.push_back(localbstateposvec);\n        vector<floatingpoint> bs1, bs2;\n        vector<float> minvec = {(float)*(SysParams::Chemistry().bindingSites[ftypepairs[0]]\n                .begin())/ SysParams::Geometry().cylinderNumMon[ftypepairs[0]],\n                                (float)*(SysParams::Chemistry().bindingSites[ftypepairs[1]]\n                                        .begin())/ SysParams::Geometry().cylinderNumMon[ftypepairs[1]]};\n        vector<float> maxvec = {(float)*(SysParams::Chemistry().bindingSites[ftypepairs[0]]\n                                                    .end() -1)/ SysParams::Geometry().cylinderNumMon[ftypepairs[0]],\n                                (float)*(SysParams::Chemistry().bindingSites[ftypepairs[1]]\n                                                    .end() -1)/ SysParams::Geometry().cylinderNumMon[ftypepairs[1]]};\n        for(auto it1 = SysParams::Chemistry().bindingSites[ftypepairs[0]].begin();\n            it1 != SysParams::Chemistry().bindingSites[ftypepairs[0]].end(); it1++) {\n            bs1.push_back((float)*it1 / SysParams::Geometry().cylinderNumMon[ftypepairs[0]]);\n        }\n        for(auto it1 = SysParams::Chemistry().bindingSites[ftypepairs[1]].begin();\n            it1 != SysParams::Chemistry().bindingSites[ftypepairs[1]].end(); it1++) {\n            bs2.push_back((float)*it1 / SysParams::Geometry().cylinderNumMon[ftypepairs[1]]);\n        }\n        minparamcyl2.push_back(minvec);\n        maxparamcyl2.push_back(maxvec);\n        bindingsites1.push_back(bs1);\n        bindingsites2.push_back(bs1);\n        totaluniquefIDpairs++;\n    }\n}\n\nHybridBindingSearchManager::HybridBindingSearchManager(Compartment* compartment){\n\tmask = (1 << SysParams::Chemistry().shiftbybits) - 1;\n\n    _compartment = compartment;\n    totaluniquefIDpairs = 0;\n}\n\n#ifdef SIMDBINDINGSEARCH\nvoid HybridBindingSearchManager::initializeSIMDvars(){\n\tshort count = 0;\n\tfor (short idx = 0; idx < totaluniquefIDpairs; idx++) {\n\t\tint countbounds = _rMaxsqvec[idx].size();\n\t\tfor (short idx2 = 0; idx2 < countbounds; idx2++) {\n\t\t\tif(bstateposvec[idx][idx2] == 1) //Linker\n\t\t\t\tlargestlinkerdistance = max<floatingpoint>(largestlinkerdistance,\n\t\t\t\t\t\tsqrt(_rMaxsqvec[idx][idx2]));\n\t\t\telse//Motor\n\t\t\t\tlargestmotordistance = max<floatingpoint>(largestmotordistance,\n\t\t\t\t                                           sqrt(_rMaxsqvec[idx][idx2]));\n\n\t\t\tauto coord = _compartment->coordinates();\n\n\t\t\tgetdOut<1U, true>(count).init_dout(10000, {_rMinsqvec[idx][idx2],\n\t\t\t\t\t\t\t\t\t _rMaxsqvec[idx][idx2]});\n\t\t\tgetdOut<1U, false>(count).init_dout(10000, {_rMinsqvec[idx][idx2],\n\t\t\t                                           _rMaxsqvec[idx][idx2]});\n\t\t\tcount++;\n\t\t}\n\t}\n}\n\ntemplate<>\ndist::dOut<1,true>& HybridBindingSearchManager::getdOut(short dOutID){\n\tif(dOutID < 8)\n\t\treturn bspairsself[NPROCS - 1][dOutID];\n\telse{\n\t\tcout<<\"Illegal ID is requested from getdOut function. Code accomodates \"\n\t\t\t\t  \"upto 6 (linker + motor types) Exiting.\"<<endl;\n\t\t\t\t\texit(EXIT_FAILURE);\n\t}\n}\n\ntemplate<>\ndist::dOut<1,false>& HybridBindingSearchManager::getdOut(short dOutID){\n\tif(dOutID < 8)\n\t\treturn bspairs[NPROCS - 1][dOutID];\n\telse{\n\t\tcout<<\"Illegal ID is requested from getdOut function. Code accomodates \"\n\t\t      \"upto 6 (linker + motor types) Exiting.\"<<endl;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\ntemplate <uint D, bool SELF, bool LinkerorMotor>\nvoid HybridBindingSearchManager::calculatebspairsLMselfV3(dist::dOut<D, SELF>&\nbspairsoutSself, short idvec[2]) {\n\n\tauto filTypepairs =_filamentIDvec[idvec[0]];\n\tauto boundstate = SysParams::Mechanics().speciesboundvec;\n\n\tminsfind = chrono::high_resolution_clock::now();\n\tint C1size = _compartment->getSIMDcoordsV3<LinkerorMotor>(0, filTypepairs[0]).size();\n\n\tif (C1size > 0) {\n\t\tbspairsoutSself.reset_counters();\n\t\tif(CROSSCHECK_BS_SWITCH){\n            if (C1size >= switchfactor * dist::get_simd_size(t_avx))\n                HybridNeighborList::_crosscheckdumpFileNL << \"SELF t_avx\" << endl;\n            else\n                HybridNeighborList::_crosscheckdumpFileNL << \"SELF t_serial\" << endl;\n        }\n\n\t\tif(filTypepairs[0] == filTypepairs[1]) {\n\t\t\tif (C1size >= switchfactor * dist::get_simd_size(t_avx))\n\t\t\t\tdist::find_distances(bspairsoutSself,\n\t\t\t\t                     _compartment->getSIMDcoordsV3<LinkerorMotor>(0, filTypepairs[0]),\n\t\t\t\t                     t_avx);\n\t\t\telse\n\t\t\t\tdist::find_distances(bspairsoutSself,\n\t\t\t\t                     _compartment->getSIMDcoordsV3<LinkerorMotor>(0, filTypepairs[0]), t_serial);\n\t\t}\n\t\telse{\n\t\t\tint C2size = _compartment->getSIMDcoordsV3<LinkerorMotor>(0, filTypepairs[1]).size();\n\t\t\tif (C1size >= switchfactor * dist::get_simd_size(t_avx) &&\n\t\t\t    C2size >= switchfactor * dist::get_simd_size(t_avx)) {\n\n\t\t\t\tdist::find_distances(bspairsoutSself,\n\t\t\t\t                     _compartment->getSIMDcoordsV3<LinkerorMotor>(0, filTypepairs[0]),\n\t\t\t\t                     _compartment->getSIMDcoordsV3<LinkerorMotor>(0, filTypepairs[1]),\n\t\t\t\t                     t_avx);\n\n\t\t\t} else {\n\n\t\t\t\tdist::find_distances(bspairsoutSself,\n\t\t\t\t                     _compartment->getSIMDcoordsV3<LinkerorMotor>(0, filTypepairs[0]),\n\t\t\t\t                     _compartment->getSIMDcoordsV3<LinkerorMotor>(0, filTypepairs[1]), t_serial);\n\n\t\t\t}\n\n\t\t}\n\n\t\tminefind = chrono::high_resolution_clock::now();\n\t\tchrono::duration<floatingpoint> elapsed_runfind(minefind - minsfind);\n\t\tfindtimeV3 += elapsed_runfind.count();\n\n\n\t\t//MERGE INTO single vector\n\t\t//@{\n\t\tif(CROSSCHECK_BS_SWITCH)\n\t\t    HybridNeighborList::_crosscheckdumpFileNL << \"SELF gather\" << endl;\n\t\tif (true) {\n\t\t\tuint N = bspairsoutSself.counter[D - 1];\n//\t\tcout<<\" Contacts found by SIMD Self \"<<N<<endl;\n\t\t\tminsfind = chrono::high_resolution_clock::now();\n\t\t\tif (nthreads == 1)\n\t\t\t\tgatherCylindercIndexV3<D, SELF, LinkerorMotor>\n\t\t\t\t\t\t(bspairsoutSself, 0, N, idvec, _compartment);\n\n\t\t\tminefind = chrono::high_resolution_clock::now();\n\t\t\tchrono::duration<floatingpoint> elapsed_append(minefind - minsfind);\n\t\t\tSIMDV3appendtime += elapsed_append.count();\n\t\t}\n\t}\n\t//@}\n}\n\ntemplate<uint D, bool SELF, bool LinkerorMotor>\nvoid HybridBindingSearchManager::calculatebspairsLMenclosedV3(dist::dOut<D,SELF>&\nbspairsoutS, dist::dOut<D,SELF>& bspairsoutS2, short idvec[2]){\n\n\n\tauto filTypepairs =_filamentIDvec[idvec[0]];\n\tauto boundstate = SysParams::Mechanics().speciesboundvec;\n\tauto upnstencilvec = _compartment->getuniquepermuteneighborsstencil();\n\tshort i =0;\n\n\tfor(auto ncmp: _compartment->getuniquepermuteNeighbours()) {\n\n\t\tshort pos = upnstencilvec[i];\n\t\t/*Note. There is hard coded  referencing of complimentary sub volumes. For example,\n\t\t * the top plane of a compartment has paritioned_volume_ID 1 and the bottom plane\n\t\t * (complimentary) is 2. So, if permuting through C1 and C2, and if C2 is on top of C1,\n\t\t * C2's stencil ID in C1 is 14 (Hard Coded in GController.cpp). C1 will compare\n\t\t * paritioned_volume_ID 1 with C2's paritioned_volume_ID 2*/\n\t\tint C1size = _compartment->getSIMDcoordsV3<LinkerorMotor>\n\t\t\t\t(partitioned_volume_ID[pos], filTypepairs[0]).size();\n\t\tint C2size = ncmp->getSIMDcoordsV3<LinkerorMotor>\n\t\t\t\t(partitioned_volume_ID[pos] + 1, filTypepairs[1]).size();\n\n\t\tif (CROSSCHECK_BS_SWITCH && C1size > 0 && C2size > 0) {\n\t\t\tif (C1size >= switchfactor * dist::get_simd_size(t_avx) &&\n\t\t\t    C2size >= switchfactor * dist::get_simd_size(t_avx))\n\t\t\t\tHybridNeighborList::_crosscheckdumpFileNL << \"ENCLOSED t_avx\" << endl;\n\t\t\telse\n\t\t\t\tHybridNeighborList::_crosscheckdumpFileNL << \"ENCLOSED t_serial\" << endl;\n\t\t}\n\n\t\tif (C1size > 0 && C2size > 0) {\n\n\t\t\tminsfind = chrono::high_resolution_clock::now();\n\n\t\t\tbspairsoutS.reset_counters();\n\t\t\tif (C1size >= switchfactor * dist::get_simd_size(t_avx) &&\n\t\t\t    C2size >= switchfactor * dist::get_simd_size(t_avx)) {\n\n\t\t\t\tdist::find_distances(bspairsoutS,\n\t\t\t\t                     _compartment->getSIMDcoordsV3<LinkerorMotor>\n\t\t\t\t\t\t                     (partitioned_volume_ID[pos], filTypepairs[0]),\n\t\t\t\t                     ncmp->getSIMDcoordsV3<LinkerorMotor>\n\t\t\t\t\t\t                     (partitioned_volume_ID[pos] + 1, filTypepairs[1]), t_avx);\n\n\t\t\t} else {\n\n\t\t\t\tdist::find_distances(bspairsoutS,\n\t\t\t\t                     _compartment->getSIMDcoordsV3<LinkerorMotor>\n\t\t\t\t\t\t                     (partitioned_volume_ID[pos], filTypepairs[0]),\n\t\t\t\t                     ncmp->getSIMDcoordsV3<LinkerorMotor>\n\t\t\t\t\t\t                     (partitioned_volume_ID[pos] + 1, filTypepairs[1]),\n\t\t\t\t                     t_serial);\n\n\t\t\t}\n\n\t\t\tminefind = chrono::high_resolution_clock::now();\n\t\t\tchrono::duration<floatingpoint> elapsed_runfind(minefind - minsfind);\n\t\t\tfindtimeV3 += elapsed_runfind.count();\n\n\t\t\ti++;\n\n\t\t\t//MERGE INTO single vector\n\t\t\t//@{\n            if(CROSSCHECK_BS_SWITCH)\n                HybridNeighborList::_crosscheckdumpFileNL << \"ENCLOSED gather\" << endl;\n\t\t\tif (true) {\n\t\t\t\tminsfind = chrono::high_resolution_clock::now();\n\t\t\t\tuint N = bspairsoutS.counter[D-1];\n\t\t\t\tif (nthreads == 1)\n\t\t\t\t\tgatherCylindercIndexV3<D, SELF, LinkerorMotor>\n\t\t\t\t\t\t\t(bspairsoutS, 0, N, idvec, ncmp);\n\t\t\t\telse {\n\t\t\t\t\tLOG(ERROR)<<\"Multiple thread support not available in MEDYAN. Exiting\"\n\t\t\t\t \".\"<<endl;\n\n\t\t\t\t\tstd::vector<std::thread> threads_avx;\n\t\t\t\t\tuint nt = nthreads;\n\t\t\t\t\tthreads_avx.reserve(nt);\n\t\t\t\t\tuint prev = 0;\n\t\t\t\t\tuint frac = N / nt;\n\t\t\t\t\tuint next = frac + N % nt;\n\t\t\t\t\tfor (uint i = 0; i < nt; ++i) {\n\t\t\t\t\t\tthreads_avx.push_back(std::thread\n\t\t\t\t\t\t\t\t                      (&HybridBindingSearchManager::gatherCylindercIndexV3<D, SELF, LinkerorMotor>,\n\t\t\t\t\t\t\t\t                       this, std::ref(bspairsoutS), prev, next, idvec, ncmp));\n\t\t\t\t\t\tprev = next;\n\t\t\t\t\t\tnext = min(N, prev + frac);\n\t\t\t\t\t}\n\n\t\t\t\t\t//Join\n\t\t\t\t\tfor (auto &t : threads_avx)\n\t\t\t\t\t\tt.join();\n\t\t\t\t\tthreads_avx.clear();\n\t\t\t\t}//else\n\t\t\t\tminefind = chrono::high_resolution_clock::now();\n\t\t\t\tchrono::duration<floatingpoint> elapsed_append(minefind - minsfind);\n\t\t\t\tSIMDV3appendtime += elapsed_append.count();\n\t\t\t}\n\n\t\t}\n\t\t//@}\n\t}\n}\n\ntemplate <uint D, bool SELF, bool LinkerorMotor>\nvoid HybridBindingSearchManager::gatherCylindercIndexV3(dist::dOut<D,SELF>&\nbspairsoutS, int first, int last, short idvec[2], Compartment* nCmp){\n\n\tconst auto& cylinderInfoData = Cylinder::getDbData().value;\n\tunsigned int count64 = 0;//counter to bits in random integer\n\tbitset<64> randInt = 0;\n\tshort idx = idvec[0];\n\tshort idx2 = idvec[1];\n\tauto &nCmppbs = nCmp->getHybridBindingSearchManager()\n\t\t\t->_possibleBindingsstencilvecuint;\n\tauto &nCmprpbs = nCmp->getHybridBindingSearchManager()\n\t\t\t->_reversepossibleBindingsstencilvecuint;\n\n\tfor(uint pid = first; pid < last; pid++) {\n\t\tuint32_t t1 = bspairsoutS.dout[2 * (D - 1)][pid];\n\t\tuint32_t t2 = bspairsoutS.dout[2 * (D - 1) + 1][pid];\n\n\t\tif(SELF == true){\n\t\t\t_possibleBindingsstencilvecuint[idx][idx2][t1].push_back(t2);\n\n\t\t\t_reversepossibleBindingsstencilvecuint[idx][idx2][t2].push_back(t1);\n\t\t}\n\t\telse {\n\t\t\t//Generate random number of 64 bits\n\t\t\tif(count64 == 0) {\n\t\t\t\trandInt = bitset<64>(Rand::randUInt64bit());\n//\t\t\t\tcout<<randInt<<endl;\n\t\t\t}\n\t\t\tif(randInt[count64]){\n\t\t\t\t_possibleBindingsstencilvecuint[idx][idx2][t1].push_back(t2);\n\n\t\t\t\t_reversepossibleBindingsstencilvecuint[idx][idx2][t2].push_back(t1);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tnCmppbs[idx][idx2][t2].push_back(t1);\n\t\t\t\tnCmprpbs[idx][idx2][t1].push_back(t2);\n\t\t\t}\n\t\t\t//Keep count\n\t\t\tcount64++;\n//\t\t\tcout<<count64<<\" \"<<first<<\" \"<<last<<endl;\n\t\t\t//reset if you reach 64 bits\n\t\t\tif(count64>63)\n\t\t\t\tcount64=0;\n\n\t\t\t/*if(t1>t2) {\n\t\t\t\t_possibleBindingsstencilvecuint[idvec[0]][idvec[1]][t1].push_back(t2);\n\n\t\t\t\t_reversepossibleBindingsstencilvecuint[idvec[0]][idvec[1]][t2].push_back(t1);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tnCmp->getHybridBindingSearchManager()\n\t\t\t\t->_possibleBindingsstencilvecuint[idvec[0]][idvec[1]][t2].push_back(t1);\n\t\t\t\tnCmp->getHybridBindingSearchManager()\n\t\t\t\t->_reversepossibleBindingsstencilvecuint[idvec[0]][idvec[1]][t1].push_back(t2);\n\t\t\t}*/\n\t\t}\n\t}\n}\n#endif\n\nvoid HybridBindingSearchManager::addPossibleBindingsstencil(short idvec[2],\n                                 CCylinder* cc, short bindingSite) {\n\tif (SysParams::INITIALIZEDSTATUS ) {\n\t\tshort idx = idvec[0];\n\t\tshort idx2 = idvec[1];\n\n\t\tauto fIDpair = _filamentIDvec[idx].data();\n\t\tshort bstatepos = bstateposvec[idx][idx2];\n//\t\tcout<<\"bstatepos \"<<bstatepos<<endl;\n\t\tshort _filamentType = cc->getType();\n\t\tshort HNLID = HNLIDvec[idx];\n\t\tshort complimentaryfID;\n\n\t\tif (_filamentType != fIDpair[0] && _filamentType != fIDpair[1]) return;\n\t\telse if (_filamentType == fIDpair[0]) complimentaryfID = fIDpair[1];\n\t\telse complimentaryfID = fIDpair[0];\n\n\t\tbool bstatecheck = false;\n\t\tfloat _rMaxsq = _rMaxsqvec[idx][idx2];\n\t\tfloat _rMinsq = _rMinsqvec[idx][idx2];\n\n\t\tint bindingsitestep = 1;\n\n\t\tif (bstatepos == 1) {\n\t\t\tbindingsitestep = SysParams::Chemistry().linkerbindingskip-1;\n\t\t\tbstatecheck = areEqual(cc->getCMonomer(bindingSite)->speciesBound(\n\t\t\t\t\tSysParams::Chemistry().linkerBoundIndex[_filamentType])->getN(), 1.0);\n\t\t}\n\n\t\tif (bstatepos == 2) {\n\t\t\tbstatecheck = areEqual(cc->getCMonomer(bindingSite)->speciesBound(\n\t\t\t\t\tSysParams::Chemistry().motorBoundIndex[_filamentType])->getN(), 1.0);\n\t\t}\n\n\t\t/*if Minus End, check if binding site exists*/\n\t\tauto cylinder = cc->getCylinder();\n\t\tif(cylinder->isMinusEnd()){\n\t\t\tauto sf = cc->getCMonomer(bindingSite)->activeSpeciesFilament();\n\t\t\tif(sf == -1)\n\t\t\t\treturn;\n\t\t}\n\n\t\t//add valid binding sites\n\t\tif (bstatecheck) {\n\n\t\t\tuint32_t shiftedIndex1 = cc->getCylinder()->getStableIndex();\n\t\t\tshiftedIndex1 = shiftedIndex1 << SysParams::Chemistry().shiftbybits;\n\n\t\t\tuint32_t pos = find(SysParams::Chemistry().bindingSites[_filamentType].begin(),\n\t\t\t                    SysParams::Chemistry().bindingSites[_filamentType].end(),\n\t\t\t                    bindingSite)\n\t\t\t               - SysParams::Chemistry().bindingSites[_filamentType].begin();\n\n\t\t\t// Do not add if the linker to be added does not satisfy this condition.\n\t\t\tif(pos % bindingsitestep != 0) return;\n\n\t\t\tuint32_t t1 = shiftedIndex1|pos;\n\t\t\t//loop through neighbors\n\t\t\t//now re add valid based on CCNL\n\t\t\tvector<Cylinder *> Neighbors;\n\n\t\t\tNeighbors = _HneighborList->getNeighborsstencil(HNLID, cc->getCylinder());\n\n\t\t\tfor (auto cn : Neighbors) {\n\t\t\t\tCylinder *c = cc->getCylinder();\n\t\t\t\tshort _nfilamentType = cn->getType();\n\n\t\t\t\tif (_nfilamentType != complimentaryfID) return;\n\t\t\t\tif (cn->getParent() == c->getParent()) continue;\n\n\t\t\t\tauto ccn = cn->getCCylinder();\n\t\t\t\tint k = 0;\n\n\t\t\t\tfor (int itI = 0; itI < SysParams::Chemistry().bindingSites[_nfilamentType].size(); itI += bindingsitestep) {\n\n\t\t\t\t\tauto it = SysParams::Chemistry().bindingSites[_nfilamentType].begin() + itI;\n\n\t\t\t\t\tbool filstatecheckn = true;\n\t\t\t\t\tif(cn->isMinusEnd()) {\n\t\t\t\t\t\tauto sfn = ccn->getCMonomer(*it)->activeSpeciesFilament();\n\t\t\t\t\t\tif (sfn == -1)\n\t\t\t\t\t\t\tfilstatecheckn = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tbool bstatecheckn = false;\n\n\t\t\t\t\tif (bstatepos == 1)\n\t\t\t\t\t\tbstatecheckn = areEqual(ccn->getCMonomer(*it)->speciesBound(\n\t\t\t\t\t\t\t\tSysParams::Chemistry().linkerBoundIndex[_nfilamentType])->getN(),\n\t\t\t\t\t\t                        1.0);\n\t\t\t\t\tif (bstatepos == 2)\n\t\t\t\t\t\tbstatecheckn = areEqual(ccn->getCMonomer(*it)->speciesBound(\n\t\t\t\t\t\t\t\tSysParams::Chemistry().motorBoundIndex[_nfilamentType])->getN(),\n\t\t\t\t\t\t                        1.0);\n\n\t\t\t\t\tif (bstatecheckn && filstatecheckn) {\n//\t\t\t\t\t\tcout<<\"Adding neighbor \"<<cn->getID()<<\" \"<<*it<<\" \"<<k<<endl;\n\t\t\t\t\t\t//check distances..\n\t\t\t\t\t\tauto mp1 = (float) bindingSite /\n\t\t\t\t\t\t           SysParams::Geometry().cylinderNumMon[_filamentType];\n\t\t\t\t\t\tauto mp2 = (float) *it /\n\t\t\t\t\t\t           SysParams::Geometry().cylinderNumMon[_nfilamentType];\n\n\t\t\t\t\t\tauto x1 = c->getFirstBead()->vcoordinate();\n\t\t\t\t\t\tauto x2 = c->getSecondBead()->vcoordinate();\n\t\t\t\t\t\tauto x3 = cn->getFirstBead()->vcoordinate();\n\t\t\t\t\t\tauto x4 = cn->getSecondBead()->vcoordinate();\n\n\t\t\t\t\t\tauto m1 = midPointCoordinate(x1, x2, mp1);\n\t\t\t\t\t\tauto m2 = midPointCoordinate(x3, x4, mp2);\n\n\t\t\t\t\t\tfloatingpoint distsq = twoPointDistancesquared(m1, m2);\n\n\t\t\t\t\t\tif (distsq > _rMaxsq || distsq < _rMinsq) {k = k + bindingsitestep;continue;}\n\n\t\t\t\t\t\tuint32_t shiftedIndex2 = cn->getStableIndex() << SysParams::Chemistry().shiftbybits;\n\n\t\t\t\t\t\tuint32_t t2 = shiftedIndex2|k;\n\n\t\t\t\t\t\t//add in correct order\n//\t\t\t\t\t\t_mpossibleBindingsstencilvecuint[idx][idx2].emplace(t1,t2);\n\t\t\t\t\t\t_possibleBindingsstencilvecuint[idx][idx2][t1].push_back(t2);\n\t\t\t\t\t\t_reversepossibleBindingsstencilvecuint[idx][idx2][t2].push_back(t1);\n\t\t\t\t\t}\n\t\t\t\t\tk = k + bindingsitestep;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//Calculate N\n\t\t\tcountNpairsfound(idvec);\n\t\t\tfManagervec[idx][idx2]->updateBindingReaction(Nbindingpairs[idx][idx2]);\n\n\t\t\tminefind = chrono::high_resolution_clock::now();\n\t\t\tchrono::duration<floatingpoint> elapsed_countsites(minefind - minsfind);\n\t\t\tSIMDcountbs += elapsed_countsites.count();\n\t\t}\n//\t\tcheckoccupancySIMD(idvec);\n\t}\n}\n\nvoid HybridBindingSearchManager::removePossibleBindingsstencil(short idvec[2], CCylinder*\n                                    cc, short bindingSite) {\n    if(CROSSCHECK_BS_SWITCH) {\n        CController::_crosscheckdumpFilechem << \"Removing site \" << cc->getCylinder()->getId()\n                                             << \" \" << cc->getCylinder()->getStableIndex() << \" \" << bindingSite\n                                             << \" with idvec \" << idvec[0] << \" \" << idvec[1] << endl;\n    }\n\n    short idx = idvec[0];\n    short idx2 = idvec[1];\n    auto fIDpair = _filamentIDvec[idx].data();\n    short _filamentType = cc->getType();\n\n    if(_filamentType != fIDpair[0] && _filamentType != fIDpair[1] ) return;\n\n    //remove all tuples which have this ccylinder as key\n    uint32_t t = cc->getCylinder()->getStableIndex()<<SysParams::Chemistry().shiftbybits;\n\n    uint32_t pos = find (SysParams::Chemistry().bindingSites[_filamentType].begin(),\n                      SysParams::Chemistry().bindingSites[_filamentType].end(),\n                      bindingSite) -\n                      SysParams::Chemistry().bindingSites[_filamentType].begin();\n    //Key\n    t = t|pos;\n\n    if(CROSSCHECK_BS_SWITCH)\n        CController::_crosscheckdumpFilechem <<\"Removing by key\"<<endl;\n\n\t_possibleBindingsstencilvecuint[idx][idx2].erase(t);\n\n    if(CROSSCHECK_BS_SWITCH)\n        CController::_crosscheckdumpFilechem <<\"Removing by value\"<<endl;\n\n    //remove all tuples which have this as value\n    //Iterate through the reverse map\n    auto keys = _reversepossibleBindingsstencilvecuint[idx][idx2][t];//keys that contain\n    // t as value in possiblebindings\n\n    for(auto k:keys){\n        //get the iterator range that corresponds to this key.\n        auto range = _possibleBindingsstencilvecuint[idx][idx2].equal_range(k);\n//\t    auto range = _mpossibleBindingsstencilvecuint[idx][idx2].equal_range(k);\n        //iterate through the range\n        for(auto it = range.first; it != range.second;){\n            //Go through the value vector and delete entries that match\n            it->second.erase(remove(it->second.begin(), it->second.end(), t), it->second.end());\n            it++;\n        }\n    }\n    //remove from the reverse map.\n\t_reversepossibleBindingsstencilvecuint[idx][idx2][t].clear();\n\n    if(CROSSCHECK_BS_SWITCH)\n        CController::_crosscheckdumpFilechem <<\"Update rxn\"<<endl;\n\n    countNpairsfound(idvec);\n    fManagervec[idx][idx2]->updateBindingReaction(Nbindingpairs[idx][idx2]);\n\n    //remove all neighbors which have this binding site pair\n    //Go through enclosing compartments to remove all entries with the current cylinder\n    // and binding site as values.\n    auto nencl = _compartment->getenclosingNeighbours().size();\n    for(auto nc: _compartment->getenclosingNeighbours()){\n        if(nc != _compartment) {\n            auto m = nc->getHybridBindingSearchManager();\n\t        if(CROSSCHECK_BS_SWITCH)\n\t            CController::_crosscheckdumpFilechem <<\"Remove by value from neighbor \"\n\t\t\t\t\t\t\t\t\t\t\t\t\"\"<<nc->getId()<<\" total \"<<nencl<<endl;\n\n            //Iterate through the reverse map\n            auto keys = m->_reversepossibleBindingsstencilvecuint[idx][idx2][t];//keys that\n            // contain t as value in possiblebindings\n\n            for(auto k:keys){\n                //get the iterator range that corresponds to this key.\n                auto range = m->_possibleBindingsstencilvecuint[idx][idx2].equal_range(k);\n//\t            auto range = m->_mpossibleBindingsstencilvecuint[idx][idx2].equal_range(k);\n                //iterate through the range\n                for(auto it = range.first; it != range.second;){\n                    //Go through the value vector and delete entries that match\n                    it->second.erase(remove(it->second.begin(), it->second.end(), t),\n                            it->second.end());\n\t                it++;\n                }\n            }\n            //remove from the reverse map.\n            m->_reversepossibleBindingsstencilvecuint[idx][idx2][t].clear();\n\t        if(CROSSCHECK_BS_SWITCH)\n\t            CController::_crosscheckdumpFilechem <<\"Update rxn\"<<endl;\n\n            m->countNpairsfound(idvec);\n            m->fManagervec[idx][idx2]->updateBindingReaction(m->Nbindingpairs[idx][idx2]);\n\n        }\n    }\n//\tcheckoccupancySIMD(idvec);\n}\n\nvoid HybridBindingSearchManager::appendPossibleBindingsstencil(short idvec[2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCCylinder* ccyl1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCCylinder* ccyl2,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tshort site1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tshort site2){\n    short idx = idvec[0];\n    short idx2 = idvec[1];\n    short _filamentType = ccyl1->getType();\n    short _nfilamentType = ccyl2->getType();\n    uint32_t shiftedIndex1 = ccyl1->getCylinder()->getStableIndex();\n    shiftedIndex1 = shiftedIndex1 << SysParams::Chemistry().shiftbybits;\n    uint32_t pos1 = find(SysParams::Chemistry().bindingSites[_filamentType].begin(),\n                            SysParams::Chemistry().bindingSites[_filamentType].end(), site1)\n                    - SysParams::Chemistry().bindingSites[_filamentType].begin();\n    uint32_t t1 = shiftedIndex1|pos1;\n\n    uint32_t shiftedIndex2 = ccyl2->getCylinder()->getStableIndex();\n    shiftedIndex2 = shiftedIndex2 << SysParams::Chemistry().shiftbybits;\n    uint32_t pos2 = find(SysParams::Chemistry().bindingSites[_nfilamentType].begin(),\n                            SysParams::Chemistry().bindingSites[_nfilamentType].end(), site2)\n                    - SysParams::Chemistry().bindingSites[_nfilamentType].begin();\n    uint32_t t2 = shiftedIndex2|pos2;\n\n    _possibleBindingsstencilvecuint[idx][idx2][t1].push_back(t2);\n    _reversepossibleBindingsstencilvecuint[idx][idx2][t2].push_back(t1);\n\n    countNpairsfound(idvec);\n    fManagervec[idx][idx2]->updateBindingReaction(Nbindingpairs[idx][idx2]);\n\n}\n\nvoid HybridBindingSearchManager::checkoccupancySIMD(short idvec[2]){\n\n    short idx = idvec[0];\n    short idx2 = idvec[1];\n    short _filamentType = 0;\n    short _complimentaryfilamentType = 0;\n    auto speciesboundvec = SysParams::Mechanics().speciesboundvec;\n\n    vector<int> CIDvec(Cylinder::rawNumStableElements());\n    const auto& cylinderInfoData = Cylinder::getDbData().value;\n    short bstatepos = bstateposvec[idx][idx2];\n\n    for(auto cyl: Cylinder::getCylinders())\n        CIDvec[cyl->getStableIndex()] = cyl->getId();\n\n    auto pbs = _possibleBindingsstencilvecuint[idx][idx2];\n\n    for(auto pair = pbs.begin(); pair != pbs.end(); pair++){\n\n        //Key\n        uint32_t leg1 = pair->first;\n        vector<uint32_t> leg2 = pair->second;\n\n        uint32_t cIndex1 = leg1 >> SysParams::Chemistry().shiftbybits;\n        uint32_t bsite1 = mask & leg1;\n\n        CCylinder* ccyl1 = cylinderInfoData[cIndex1].chemCylinder;\n\n        short it1 = SysParams::Chemistry().bindingSites[_filamentType][bsite1];\n\n        bool boundstate1 = false;\n\n        if(bstatepos == 1) {\n            boundstate1 = areEqual(ccyl1->getCMonomer(it1)->speciesBound(\n                    SysParams::Chemistry().linkerBoundIndex[_filamentType])->getN(), 1.0);\n\n        }\n        if(bstatepos == 2) {\n            boundstate1 = areEqual(ccyl1->getCMonomer(it1)->speciesBound(\n                    SysParams::Chemistry().motorBoundIndex[_filamentType])->getN(), 1.0);\n        }\n\n\n        //Values\n        for(auto V:leg2){\n            uint32_t cIndex2 = V >> SysParams::Chemistry().shiftbybits;\n            uint32_t bsite2 = mask & V;\n            CCylinder* ccyl2 = cylinderInfoData[cIndex2].chemCylinder;\n\n            short it2 = SysParams::Chemistry().bindingSites[_complimentaryfilamentType][bsite2];\n\n            bool boundstate2 = false;\n//            bool vecboundstate2 = speciesboundvec[bstatepos][maxnbs * cIndex2 + bsite2];\n            if(bstatepos == 1) {\n                boundstate2 = areEqual(ccyl2->getCMonomer(it2)->speciesBound(\n                        SysParams::Chemistry().linkerBoundIndex[_complimentaryfilamentType])->getN(),\n                                       1.0);\n            }\n            if(bstatepos == 2) {\n                boundstate2 = areEqual(ccyl2->getCMonomer(it2)->speciesBound(\n                        SysParams::Chemistry().motorBoundIndex[_complimentaryfilamentType])->getN(),\n                                       1.0);\n            }\n\t\t\tauto ncmpcoord = ccyl2->getCompartment()->coordinates();\n            if(boundstate1 == false || boundstate2 == false) {\n\n                std::cout << \"OOPS occupied species exist \" << boundstate1 << \" \"\n                          << boundstate2 << endl;\n                cout<<\"bstate pos (1-Linker, 2-Motor)= \"<<bstatepos<<endl;\n\n                std::cout<<\"Cmp \"<<_compartment->coordinates()[0]<<\" \"<<\n                                   _compartment->coordinates()[1]<<\" \"<<\n                                   _compartment->coordinates()[2]<<\n                        \" nCmp \"<<ncmpcoord[0]<<\" \"<< ncmpcoord[1]<<\" \"<< ncmpcoord[2]<<\n                        \" L/M Cylindex bs \"<< cIndex1<<\" \"<<it1<<\" \"<<\n                                  cIndex2<<\" \"<<it2<<\" cIDs \"\n                                  <<ccyl1->getCylinder()->getId()<<\" \"\n                                  <<ccyl2->getCylinder()->getId()<<\" \"<<endl;\n\n                cout<<\"uint32_t \"<<leg1<<\" \"<<V<<endl;\n                exit(EXIT_FAILURE);\n\n            }\n\n        }\n    }\n}\n\nvoid HybridBindingSearchManager::updateAllPossibleBindingsstencilHYBD() {\n\n\t//Delete all entries in the binding pair maps\n    for (int idx = 0; idx < totaluniquefIDpairs; idx++){\n        int countbounds = _rMaxsqvec[idx].size();\n        for (int idx2 = 0; idx2 < countbounds; idx2++) {\n            _possibleBindingsstencilvecuint[idx][idx2].clear();\n            _reversepossibleBindingsstencilvecuint[idx][idx2].clear();\n        }\n    }\n\n    floatingpoint min1,min2,max1,max2;\n    bool status1 = true;\n    bool status2 = true;\n    floatingpoint minveca[2];\n    floatingpoint maxveca[2];\n    //vector of squared cylinder length\n    floatingpoint* cylsqmagnitudevector = SysParams::Mechanics().cylsqmagnitudevector;\n    int Ncylincmp = _compartment->getCylinders().size();\n    int* cindexvec = new int[Ncylincmp]; //stores cindex of cylinders in this compartment\n    vector<vector<int>> ncindices; //cindices of cylinders in neighbor list.\n    vector<int> ncindex; //helper vector\n\t//vector storing information on state (bound/free) of each binding site\n    auto boundstate = SysParams::Mechanics().speciesboundvec;\n    int maxnbs = SysParams::Chemistry().maxbindingsitespercylinder;\n\n    const auto& cylinderInfoData = Cylinder::getDbData().value;\n\n    int idx; int idx2;\n\t//Go through all filament types in our simulation\n    for(idx = 0; idx<totaluniquefIDpairs;idx++) {\n\n        long id = 0;\n        ncindices.clear();\n        auto fpairs = _filamentIDvec[idx].data();\n\n        int nbs1 = SysParams::Chemistry().bindingSites[fpairs[0]].size();\n        int nbs2 = SysParams::Chemistry().bindingSites[fpairs[1]].size();\n        int Nbounds = _rMaxsqvec[idx].size();\n\n        //Go through cylinders in the compartment, get the half of neighbors.\n        for (auto c : _compartment->getCylinders()) {\n            cindexvec[id] = c->getStableIndex();\n            id++;\n            //Get neighors corresponding to the cylinder.\n            auto Neighbors = _HneighborList->getNeighborsstencil(HNLIDvec[idx], c);\n            ncindex.reserve(Neighbors.size());\n            for (auto cn : Neighbors) {\n                if (c->getId() > cn->getId())\n                    ncindex.push_back(cn->getStableIndex());\n            }\n            ncindices.push_back(ncindex);\n            ncindex.clear();\n        }\n\n        //Go through cylinder\n        for (int i = 0; i < Ncylincmp; i++) {\n\n            int cindex = cindexvec[i];\n            short complimentaryfID;\n            const auto& c = cylinderInfoData[cindex];\n            const auto& x1 = Bead::getStableElement(c.beadIndices[0])->coord;\n            const auto& x2 = Bead::getStableElement(c.beadIndices[1])->coord;\n            floatingpoint X1X2[3] = {x2[0] - x1[0], x2[1] - x1[1], x2[2] - x1[2]};\n            int *cnindices = ncindices[i].data();\n\n            if (c.type != fpairs[0] && c.type != fpairs[1]) continue;\n            else if(c.type == fpairs[0]) complimentaryfID = fpairs[1];\n            else complimentaryfID = fpairs[0];\n\n            //Go through the neighbors of the cylinder\n            for (int arraycount = 0; arraycount < ncindices[i].size(); arraycount++) {\n\n                int cnindex = cnindices[arraycount];\n                const auto& cn = cylinderInfoData[cnindex];\n\n//            if(c.ID < cn.ID) {counter++; continue;} commented as the above vector does\n//              not contain ncs that will fail this cndn.\n                if (c.filamentId == cn.filamentId) continue;\n                if(c.type != complimentaryfID) continue;\n\n                const auto& x3 = Bead::getStableElement(cn.beadIndices[0])->coord;\n                const auto& x4 = Bead::getStableElement(cn.beadIndices[1])->coord;\n                floatingpoint X1X3[3] = {x3[0] - x1[0], x3[1] - x1[1], x3[2] - x1[2]};\n                floatingpoint X3X4[3] = {x4[0] - x3[0], x4[1] - x3[1], x4[2] - x3[2]};\n                floatingpoint X1X3squared = sqmagnitude(X1X3);\n                floatingpoint X1X2squared = cylsqmagnitudevector[cindex];\n                floatingpoint X1X3dotX1X2 = scalarprojection(X1X3, X1X2);\n                floatingpoint X3X4squared = cylsqmagnitudevector[cnindex];\n                floatingpoint X1X3dotX3X4 = scalarprojection(X1X3, X3X4);\n                floatingpoint X3X4dotX1X2 = scalarprojection(X3X4, X1X2);\n\n                //Number of binding sites on the cylinder/filament of Type A.\n                for (int pos1 = 0; pos1 < nbs1; pos1++) {\n\n                    //Number of binding distance pairs we are looking at\n                    for (idx2 = 0; idx2 < Nbounds; idx2++) {\n\n                        short bstatepos = bstateposvec[idx][idx2];\n\t\t\t\t\t\t// Check for linkers if the binding site is acceptable.\n\t                    if (bstatepos == 1) {\n\t\t                    int bindingsitestep = SysParams::Chemistry().linkerbindingskip - 1;\n\t\t                    if(pos1 % bindingsitestep != 0) continue;\n\t                    }\n\n                        //now re add valid binding sites\n                        if (areEqual(boundstate[bstatepos][maxnbs * cindex + pos1], 1.0)) {\n\n                            auto mp1 = bindingsites1[idx][pos1];\n                            floatingpoint A = X3X4squared;\n                            floatingpoint B = 2.0 * X1X3dotX3X4 - 2.0 * mp1 * X3X4dotX1X2;\n                            floatingpoint C = X1X3squared + mp1 * mp1 * X1X2squared -\n                                       2.0 * mp1 * X1X3dotX1X2;\n                            floatingpoint Bsq = B*B;\n                            floatingpoint C1 = C - _rMinsqvec[idx][idx2];\n                            floatingpoint C2 = C - _rMaxsqvec[idx][idx2];\n                            floatingpoint b2m4ac1 = Bsq - 4 * A * C1;\n                            floatingpoint b2m4ac2 = Bsq - 4 * A * C2;\n\n\n                            status1 = b2m4ac1 < 0;\n                            status2 = b2m4ac2 < 0;\n\n                            if (status1 && status2) continue;\n\n                            if (!status1) {\n                                min1 = (-B + sqrt(b2m4ac1)) / (2 * A);\n                                min2 = (-B - sqrt(b2m4ac1)) / (2 * A);\n                                if (min1 < min2) {\n                                    minveca[0] = (min1);\n                                    minveca[1] = (min2);\n                                } else {\n                                    minveca[0] = (min2);\n                                    minveca[1] = (min1);\n                                }\n                                //Compare the MIN solutions are within the first and last\n                                // binding sites in filament/cylinder of type B.\n                                if (minveca[0] < minparamcyl2[idx][1] &&\n                                    minveca[1] > maxparamcyl2[idx][1]) continue;\n                            }\n\n                            if (!status2) {\n                                max1 = (-B + sqrt(b2m4ac2)) / (2 * A);\n                                max2 = (-B - sqrt(b2m4ac2)) / (2 * A);\n                                if (max1 < max2) {\n                                    maxveca[0] = (max1);\n                                    maxveca[1] = (max2);\n                                } else {\n                                    maxveca[0] = (max2);\n                                    maxveca[1] = (max1);\n                                }\n                                //Compare the mAX solutions are within the first and last\n                                // binding sites in filament/cylinder of type B.\n                                if (maxveca[0] > maxparamcyl2[idx][1] ||\n                                    maxveca[1] < minparamcyl2[idx][1]) continue;\n                            }\n\n                            for (int pos2 = 0; pos2 < nbs2; pos2++) {\n\n\t                            // Check for linkers if the binding site is acceptable.\n\t                            if (bstatepos == 1) {\n\t\t                            int bindingsitestep = SysParams::Chemistry().linkerbindingskip - 1;\n\t\t                            if(pos2 % bindingsitestep != 0) continue;\n\t                            }\n\n                                if (areEqual(boundstate[bstatepos][maxnbs * cnindex + pos2], 1.0)) {\n\n                                    //check distances..\n                                    auto mp2 = bindingsites2[idx][pos2];\n                                    if (!status2)\n                                        if (mp2 < maxveca[0] || mp2 > maxveca[1]) continue;\n                                    if (!status1)\n                                        if (mp2 > minveca[0] && mp2 < minveca[1]) continue;\n\n\n                                    auto it1 = SysParams::Chemistry().bindingSites[fpairs[0]][pos1];\n                                    auto it2 = SysParams::Chemistry().bindingSites[fpairs[1]][pos2];\n\n\t                                uint32_t shiftedIndex1 = cindex;\n\t                                shiftedIndex1 = shiftedIndex1 << SysParams::Chemistry().shiftbybits;\n\t                                uint32_t t1 = shiftedIndex1|pos1;\n\n\t                                uint32_t shiftedIndex2 = cnindex << SysParams::Chemistry().shiftbybits;\n\t                                uint32_t t2 = shiftedIndex2|pos2;\n\n\t                                //add in correct order\n\t                                _possibleBindingsstencilvecuint[idx][idx2][t1].push_back(t2);\n\t                                _reversepossibleBindingsstencilvecuint[idx][idx2][t2].push_back(t1);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    //Place in the appropriate BindingManager\n    /*for(short idx = 0; idx<totaluniquefIDpairs; idx++){\n        int countbounds = _rMaxsqvec[idx].size();\n        for (short idx2 = 0; idx2 < countbounds; idx2++) {\n        \tshort idvec[2];\n        \tidvec = {idx, idx2};\n\t        countNpairsfound(idvec);\n\t        fManagervec[idx][idx2]->updateBindingReaction(Nbindingpairs[idx][idx2]);\n        }\n    }*/\n    delete[] cindexvec;\n}\n\nvoid HybridBindingSearchManager::countNpairsfound(short idvec[2]){\n    short idx = idvec[0];\n    short idx2 = idvec[1];\n    int N = 0;\n    Nbindingpairs[idx][idx2] = 0;\n\n    for (auto iter = _possibleBindingsstencilvecuint[idx][idx2].begin(); iter !=\n\t\t    _possibleBindingsstencilvecuint[idx][idx2].end(); iter++) {\n        N += iter->second.size();\n    }\n//    cout<<Nbindingpairs[idx][idx2]<<\" \"<<N<<endl;\n    Nbindingpairs[idx][idx2] = N;\n}\n\nvoid HybridBindingSearchManager::updateAllPossibleBindingsstencilSIMDV3() {\n\n#ifdef SIMDBINDINGSEARCH\n    short count = 0;\n\tfor (short idx = 0; idx < totaluniquefIDpairs; idx++) {\n\t\tint countbounds = _rMaxsqvec[idx].size();\n\t\tfor (short idx2 = 0; idx2 < countbounds; idx2++) {\n\t\t\tshort idvec[2] = {idx, idx2};\n\t\t\tbool LinkerorMotor = false; //Motor\n\t\t\tif (bstateposvec[idx][idx2] == 1)\n\t\t\t\tLinkerorMotor = true;//Linker\n\t\t\tif(LinkerorMotor) {\n\t\t\t\t//Linker\n\t\t\t\tcalculatebspairsLMselfV3<1,true, true>(getdOut<1U, true>(count), idvec);\n\t\t\t\tcalculatebspairsLMenclosedV3<1,false, true>(getdOut<1U, false>(count),\n\t\t\t\t        bspairslinker2, idvec);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//Motor\n\t\t\t\tcalculatebspairsLMselfV3<1,true, false>(getdOut<1U, true>(count), idvec);\n\t\t\t\tcalculatebspairsLMenclosedV3<1,false, false>(getdOut<1U, false>(count),\n\t\t\t\t        bspairsmotor2, idvec);\n\t\t\t}\n\t\t\tcount++;\n//\t\t\tcheckoccupancySIMD(idvec);\n\t\t}\n\t}\n\n#endif\n}\n\nvoid HybridBindingSearchManager::updateAllBindingReactions() {\n\tfor (short idx = 0; idx < totaluniquefIDpairs; idx++) {\n\t\tint countbounds = _rMaxsqvec[idx].size();\n\t\tfor (short idx2 = 0; idx2 < countbounds; idx2++) {\n\t\t\tshort idvec[2] = {idx, idx2};\n\t\t\tcountNpairsfound(idvec);\n\t\t\tfManagervec[idx][idx2]->updateBindingReaction(Nbindingpairs[idx][idx2]);\n\t\t}\n\t}\n}\n\nvoid HybridBindingSearchManager::addtoHNeighborList(){\n    HNLIDvec.resize(totaluniquefIDpairs);\n    for(short idx = 0; idx < totaluniquefIDpairs; idx++) {\n        vector<float> temprMaxsq = _rMaxsqvec[idx];\n        vector<float> temprMinsq = _rMinsqvec[idx];\n        vector<short> ftypepair = _filamentIDvec[idx];\n        float localmaxcylsize = max(SysParams::Geometry().cylinderSize[ftypepair[0]],\n                                    SysParams::Geometry().cylinderSize[ftypepair[1]]);\n        float maxrMaxsq = *max_element(temprMaxsq.begin(), temprMaxsq.end());\n        float minrMinsq = *min_element(temprMinsq.begin(), temprMinsq.end());\n\t    HNLIDvec[idx] = _HneighborList->setneighborsearchparameters(ftypepair[0], ftypepair[1],\n\t                                                       false, true, localmaxcylsize + sqrt(maxrMaxsq),\n\t                                                       max( sqrt(minrMinsq) - localmaxcylsize,float(0.0)));\n\n        for(short idx2 = 0; idx2<temprMaxsq.size();idx2++) {\n            short idvec[2] = {idx, idx2};\n            fManagervec[idx][idx2]->setHNLID(HNLIDvec[idx], idvec);\n        }\n    }\n}\n\nvector<tuple<CCylinder*, short>>\nHybridBindingSearchManager::chooseBindingSitesstencil(short idvec[2]){\n\n\tif(CROSSCHECK_BS_SWITCH)\n\t    CController::_crosscheckdumpFilechem <<\"Choosing site\"<<endl;\n\n    short idx = idvec[0];\n    short idx2 = idvec[1];\n    auto fpairs = _filamentIDvec[idx].data();\n    int pbsSize = Nbindingpairs[idx][idx2];\n\n    const auto& cylinderInfoData = Cylinder::getDbData().value;\n\n    assert((pbsSize!= 0)\n           && \"Major bug: Linker/Motor binding manager should not have zero binding \\\n                   sites when called to choose a binding site.\");\n    if(true) {\n\t    uint randomIndex = Rand::randInteger(1, pbsSize);\n\n\t    auto it = _possibleBindingsstencilvecuint[idx][idx2].begin();\n\t    uint cumulativesum = 0;\n\t    uint prevstepsum = 0;\n\n\t    while (it != _possibleBindingsstencilvecuint[idx][idx2].end() &&\n\t           cumulativesum < randomIndex) {\n\t\t    prevstepsum = cumulativesum;\n\t\t    cumulativesum += it->second.size();\n\t\t    if (cumulativesum < randomIndex)\n\t\t\t    it++;\n\t    }\n\t    Nbindingpairs[idx][idx2]--;\n\n\t    uint position = randomIndex - prevstepsum - 1;\n\n\t    uint32_t site1 = it->first;\n\t    uint32_t site2 = it->second[position];\n\n\t    uint32_t cIndex1 = site1 >> SysParams::Chemistry().shiftbybits;\n\t    uint32_t cIndex2 = site2 >> SysParams::Chemistry().shiftbybits;\n\n\t    short bsitepos1 = mask & site1;\n\t    short bsitepos2 = mask & site2;\n\n\t    if(CROSSCHECK_BS_SWITCH)\n\t        CController::_crosscheckdumpFilechem <<\"Chosen cindices, pos \"<<cIndex1<<\" \"\n\t                <<cIndex2<<\" \"<<bsitepos1<<\" \"<<bsitepos2<<endl;\n\n\t    CCylinder *ccyl1;\n\t    CCylinder *ccyl2;\n\n\t    ccyl1 = cylinderInfoData[cIndex1].chemCylinder;\n\t    ccyl2 = cylinderInfoData[cIndex2].chemCylinder;\n\n\t    short bindingSite1 = SysParams::Chemistry().bindingSites[ccyl1->getType\n\t\t\t    ()][bsitepos1];\n\t    short bindingSite2 = SysParams::Chemistry().bindingSites[ccyl2->getType\n\t\t\t    ()][bsitepos2];\n\n\t    tuple<CCylinder *, short> t1 = make_tuple(ccyl1, bindingSite1);\n\t    tuple<CCylinder *, short> t2 = make_tuple(ccyl2, bindingSite2);\n\n\t    if(CROSSCHECK_BS_SWITCH)\n\t        CController::_crosscheckdumpFilechem <<\"Chosen!\"<<endl;\n\t    return vector<tuple<CCylinder *, short>>{t1, t2};\n    }\n}\n\nvoid HybridBindingSearchManager::clearPossibleBindingsstencil(short idvec[2]){\n\tshort idx = idvec[0];\n\tshort idx2 = idvec[1];\n\t_possibleBindingsstencilvecuint[idx][idx2].clear();\n\t_reversepossibleBindingsstencilvecuint[idx][idx2].clear();\n\tcountNpairsfound(idvec);\n\tfManagervec[idx][idx2]->updateBindingReaction(Nbindingpairs[idx][idx2]);\n}\n\nvoid HybridBindingSearchManager::printbindingsitesstencil(short idvec[2]) {\n    cout<<\"BINDINGSITES: CYL1(SIDX) CYL2(SIDX) SITE1 SITE2\"<<endl;\n    short idx = idvec[0];\n    short idx2 = idvec[1];\n\n    auto pbs = _possibleBindingsstencilvecuint[idx][idx2];\n\n    for (auto pair = pbs.begin(); pair != pbs.end(); pair++) {\n\n        //Key\n        uint32_t leg1 = pair->first;\n        vector<uint32_t> leg2 = pair->second;\n\n        uint32_t cIndex1 = leg1 >> SysParams::Chemistry().shiftbybits;\n        uint32_t bsite1 = mask & leg1;\n        //Values\n        for (auto V:leg2) {\n            uint32_t cIndex2 = V >> SysParams::Chemistry().shiftbybits;\n            uint32_t bsite2 = mask & V;\n            cout<<cIndex1<<\" \"<<cIndex2<<\" \"<<bsite1<<\" \"<<bsite2<<endl;\n        }\n    }\n}\n\nHybridCylinderCylinderNL* HybridBindingSearchManager::_HneighborList;\nbool initialized = false;\n#ifdef SIMDBINDINGSEARCH\n//D = 1\n//dist::dOut<1U,false> HybridBindingSearchManager::bspairslinker;\ndist::dOut<1U,true> HybridBindingSearchManager::bspairslinkerself;\n//dist::dOut<1U,false> HybridBindingSearchManager::bspairsmotor;\ndist::dOut<1U,true> HybridBindingSearchManager::bspairsmotorself;\ndist::dOut<1U,false> HybridBindingSearchManager::bspairsmotor2;\ndist::dOut<1U,false> HybridBindingSearchManager::bspairslinker2;\n\ndist::dOut<1U,true> HybridBindingSearchManager::bspairsself[NPROCS][8];\ndist::dOut<1U,false> HybridBindingSearchManager::bspairs[NPROCS][8];\nfloatingpoint HybridBindingSearchManager::largestlinkerdistance = 0.0;\nfloatingpoint HybridBindingSearchManager::largestmotordistance = 0.0;\n//D = 2\n/*dist::dOut<2U,true> HybridBindingSearchManager::bspairs2self;\ndist::dOut<2U,false> HybridBindingSearchManager::bspairs2;\ndist::dOut<1U,false> HybridBindingSearchManager::bspairs2_D1;\ndist::dOut<1U,false> HybridBindingSearchManager::bspairs2_D2;*/\n\n\nshort HybridBindingSearchManager::Totallinkermotor = 0;\n#endif\nfloatingpoint HybridBindingSearchManager::SIMDtime = 0.0;\nfloatingpoint HybridBindingSearchManager::HYBDtime = 0.0;\nfloatingpoint HybridBindingSearchManager::findtime = 0.0;\nfloatingpoint HybridBindingSearchManager::appendtime = 0.0;\nfloatingpoint HybridBindingSearchManager::findtimeV2 = 0.0;\nfloatingpoint HybridBindingSearchManager::SIMDparse1 = 0.0;\nfloatingpoint HybridBindingSearchManager::SIMDparse2 = 0.0;\nfloatingpoint HybridBindingSearchManager::SIMDparse3 = 0.0;\nfloatingpoint HybridBindingSearchManager::SIMDcountbs = 0.0;\nfloatingpoint HybridBindingSearchManager::HYBDappendtime = 0.0;\nfloatingpoint HybridBindingSearchManager::SIMDV3appendtime = 0.0;\nfloatingpoint HybridBindingSearchManager::findtimeV3 = 0.0;\n#endif\n", "meta": {"hexsha": "7ef783a3ff209a3f3cd5513fe847df40ce3e6b2a", "size": 47425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Chemistry/HybridBindingSearchManager.cpp", "max_stars_repo_name": "allen-cell-animated/medyan", "max_stars_repo_head_hexsha": "0b5ef64fb338c3961673361e5632980617937ee6", "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/Chemistry/HybridBindingSearchManager.cpp", "max_issues_repo_name": "allen-cell-animated/medyan", "max_issues_repo_head_hexsha": "0b5ef64fb338c3961673361e5632980617937ee6", "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/Chemistry/HybridBindingSearchManager.cpp", "max_forks_repo_name": "allen-cell-animated/medyan", "max_forks_repo_head_hexsha": "0b5ef64fb338c3961673361e5632980617937ee6", "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": 39.8529411765, "max_line_length": 117, "alphanum_fraction": 0.609847127, "num_tokens": 12851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17073193564512942}}
{"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_OPERATOR_FUNCTIONS_SIMD_SSE_AVX_IF_ELSE_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_OPERATOR_FUNCTIONS_SIMD_SSE_AVX_IF_ELSE_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_AVX_SUPPORT\n#include <boost/simd/toolbox/operator/functions/if_else.hpp>\n#include <boost/simd/include/functions/simd/genmask.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::if_else_, boost::simd::tag::avx_\n                            , (A0)(A1)\n                            , ((simd_<logical_<A0>, boost::simd::tag::avx_>))\n                              ((simd_<single_<A1>, boost::simd::tag::avx_>))\n                              ((simd_<single_<A1>, boost::simd::tag::avx_>))\n                            )\n  {\n    typedef A1 result_type;\n    inline result_type operator()(A0 const& a0,A1 const& a1,A1 const& a2) const\n    {\n      return bitwise_cast<result_type>(_mm256_blendv_ps(a2, a1, bitwise_cast<A1>(genmask(a0))));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::if_else_, boost::simd::tag::avx_\n                            , (A0)(A1)\n                            , ((simd_<logical_<A0>, boost::simd::tag::avx_>))\n                              ((simd_<double_<A1>, boost::simd::tag::avx_>))\n                              ((simd_<double_<A1>, boost::simd::tag::avx_>))\n                            )\n  {\n    typedef A1 result_type;\n    inline result_type operator()(A0 const& a0,A1 const& a1,A1 const& a2) const\n    {\n      return bitwise_cast<result_type>(_mm256_blendv_pd(a2, a1,  bitwise_cast<A1>(genmask(a0))));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::if_else_, boost::simd::tag::avx_\n                            , (A0)(A1)\n                            , ((simd_<logical_<A0>, boost::simd::tag::avx_>))\n                              ((simd_<floating_sized_<A1>, boost::simd::tag::avx_>))\n                              ((simd_<floating_sized_<A1>, boost::simd::tag::avx_>))\n                            )\n  {\n    typedef A1 result_type;\n    inline result_type operator()(A0 const& a0,A1 const& a1,A1 const& a2) const\n    {\n      typedef typename dispatch::meta::as_floating<A1>::type ctype;\n      typedef typename meta::as_logical<ctype>::type ltype;\n      return bitwise_cast<result_type>(if_else(bitwise_cast<ltype>(a0), bitwise_cast<ctype>(a1), bitwise_cast<ctype>(a2)));\n    }\n  };\n} } }\n\n#endif\n#endif\n\n", "meta": {"hexsha": "22e1be1452449799b3f79109a419ec6720e18ffa", "size": 3064, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/operator/include/boost/simd/toolbox/operator/functions/simd/sse/avx/if_else.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/operator/include/boost/simd/toolbox/operator/functions/simd/sse/avx/if_else.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/operator/include/boost/simd/toolbox/operator/functions/simd/sse/avx/if_else.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": 45.0588235294, "max_line_length": 123, "alphanum_fraction": 0.5646214099, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.1707319356451294}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2007-2008 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_UNITS_ANGLE_GRADIAN_BASE_UNIT_HPP\n#define BOOST_UNITS_ANGLE_GRADIAN_BASE_UNIT_HPP\n\n#include <boost/units/conversion.hpp>\n#include <boost/units/base_units/angle/radian.hpp>\n\nBOOST_UNITS_DEFINE_BASE_UNIT_WITH_CONVERSIONS(angle,gradian,\"gradian\",\"grad\",6.28318530718/400.,boost::units::angle::radian_base_unit,-102);\n\n#if BOOST_UNITS_HAS_BOOST_TYPEOF\n\n#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()\n\nBOOST_TYPEOF_REGISTER_TYPE(boost::units::angle::gradian_base_unit)\n\n#endif\n\n#endif // BOOST_UNITS_ANGLE_GRADIAN_BASE_UNIT_HPP\n", "meta": {"hexsha": "7b291b4697831dd567b15f3775984dfb2c460a2e", "size": 923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/units/base_units/angle/gradian.hpp", "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/boost/units/base_units/angle/gradian.hpp", "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/boost/units/base_units/angle/gradian.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 32.9642857143, "max_line_length": 140, "alphanum_fraction": 0.8104008667, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.17073193224172745}}
{"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// File generated at Thu 10 May 2018 14:52:05\n\n#ifndef MSSMNoFVatMGUT_EFFECTIVE_COUPLINGS_H\n#define MSSMNoFVatMGUT_EFFECTIVE_COUPLINGS_H\n\n#include \"MSSMNoFVatMGUT_mass_eigenstates.hpp\"\n#include \"lowe.h\"\n#include \"physical_input.hpp\"\n#include \"standard_model.hpp\"\n\n#include <complex>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nnamespace standard_model {\nclass Standard_model;\n}\n\nclass MSSMNoFVatMGUT_effective_couplings {\npublic:\n   MSSMNoFVatMGUT_effective_couplings(const MSSMNoFVatMGUT_mass_eigenstates&,\n                                   const softsusy::QedQcd&,\n                                   const Physical_input&);\n\n   void do_run_couplings(bool flag) { rg_improve = flag; }\n   bool do_run_couplings() const { return rg_improve; }\n   void do_include_qcd_corrections(bool flag) { include_qcd_corrections = flag; }\n   bool do_include_qcd_corrections() const { return include_qcd_corrections; }\n   void set_physical_inputs(const Physical_input& inputs_) { physical_input = inputs_; }\n   void set_low_energy_data(const softsusy::QedQcd& qedqcd_) { qedqcd = qedqcd_; }\n   void set_model(const MSSMNoFVatMGUT_mass_eigenstates& model_);\n\n   double get_hhVPVP_partial_width(int gO1) const;\n   double get_hhVGVG_partial_width(int gO1) const;\n   double get_AhVPVP_partial_width(int gO1) const;\n   double get_AhVGVG_partial_width(int gO1) const;\n   std::complex<double> get_eff_CphhVPVP(int gO1) const { return eff_CphhVPVP(gO1); }\n   std::complex<double> get_eff_CphhVGVG(int gO1) const { return eff_CphhVGVG(gO1); }\n   std::complex<double> get_eff_CpAhVPVP(int gO1) const { return eff_CpAhVPVP(gO1); }\n   std::complex<double> get_eff_CpAhVGVG(int gO1) const { return eff_CpAhVGVG(gO1); }\n\n   void calculate_effective_couplings();\n\n   std::complex<double> CphhconjVWmVWm(int gI2) const;\n   std::complex<double> CpbarFdFdhhPL(int gI1) const;\n   std::complex<double> CpbarFdFdAhPL(int gI2) const;\n   std::complex<double> CpbarFsFshhPL(int gI1) const;\n   std::complex<double> CpbarFsFsAhPL(int gI2) const;\n   std::complex<double> CpbarFbFbhhPL(int gI1) const;\n   std::complex<double> CpbarFbFbAhPL(int gI2) const;\n   std::complex<double> CpbarFuFuhhPL(int gI1) const;\n   std::complex<double> CpbarFuFuAhPL(int gI2) const;\n   std::complex<double> CpbarFcFchhPL(int gI1) const;\n   std::complex<double> CpbarFcFcAhPL(int gI2) const;\n   std::complex<double> CpbarFtFthhPL(int gI1) const;\n   std::complex<double> CpbarFtFtAhPL(int gI2) const;\n   std::complex<double> CpbarFeFehhPL(int gI1) const;\n   std::complex<double> CpbarFeFeAhPL(int gI2) const;\n   std::complex<double> CpbarFmFmhhPL(int gI1) const;\n   std::complex<double> CpbarFmFmAhPL(int gI2) const;\n   std::complex<double> CpbarFtauFtauhhPL(int gI1) const;\n   std::complex<double> CpbarFtauFtauAhPL(int gI2) const;\n   std::complex<double> CphhSdconjSd(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhSuconjSu(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhSeconjSe(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhSmconjSm(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhStauconjStau(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhSsconjSs(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhScconjSc(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhSbconjSb(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhStconjSt(int gt1, int gt2, int gt3) const;\n   std::complex<double> CphhHpmconjHpm(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpbarChaChahhPL(int gt3, int gt1, int gt2) const;\n   std::complex<double> CpAhSdconjSd(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhSuconjSu(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhSeconjSe(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhSmconjSm(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhStauconjStau(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhSsconjSs(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhScconjSc(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhSbconjSb(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhStconjSt(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpAhHpmconjHpm(int gt1, int gt2, int gt3) const;\n   std::complex<double> CpbarChaChaAhPL(int gt3, int gt2, int gt1) const;\n   void calculate_eff_CphhVPVP(int gO1);\n   void calculate_eff_CphhVGVG(int gO1);\n   void calculate_eff_CpAhVPVP(int gO1);\n   void calculate_eff_CpAhVGVG(int gO1);\n\nprivate:\n   MSSMNoFVatMGUT_mass_eigenstates model;\n   softsusy::QedQcd qedqcd;\n   Physical_input physical_input;\n   bool rg_improve;\n   bool include_qcd_corrections;\n\n   void copy_mixing_matrices_from_model();\n\n   standard_model::Standard_model initialise_SM() const;\n   void run_SM_strong_coupling_to(standard_model::Standard_model, double m);\n\n   // higher order corrections to the amplitudes for\n   // effective coupling to photons\n   std::complex<double> scalar_scalar_qcd_factor(double, double) const;\n   std::complex<double> scalar_fermion_qcd_factor(double, double) const;\n   std::complex<double> pseudoscalar_fermion_qcd_factor(double, double) const;\n\n   // higher order corrections to the leading order\n   // effective couplings to gluons\n   double number_of_active_flavours(double) const;\n   double scalar_scaling_factor(double) const;\n   double pseudoscalar_scaling_factor(double) const;\n\n   Eigen::Matrix<double,2,2> ZD{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZU{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZE{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZM{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZTau{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZS{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZC{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZB{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZT{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZH{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZA{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZP{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,4,4> ZN{Eigen::Matrix<std::complex<double>,4,4>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UM{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UP{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZZ{Eigen::Matrix<double,2,2>::Zero()};\n\n   Eigen::Array<std::complex<double>,2,1> eff_CphhVPVP;\n   Eigen::Array<std::complex<double>,2,1> eff_CphhVGVG;\n   Eigen::Array<std::complex<double>,2,1> eff_CpAhVPVP;\n   Eigen::Array<std::complex<double>,2,1> eff_CpAhVGVG;\n\n};\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "8b11285cf5d5889b134bfc6293a2dd8176b1e6ff", "size": 7694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_effective_couplings.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_effective_couplings.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_effective_couplings.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 48.0875, "max_line_length": 95, "alphanum_fraction": 0.719131791, "num_tokens": 2417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.17055037294331252}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <vector>\n#include <map>\n#include <string>\n#include <iostream>\n#include <random>\n#include <Eigen/Geometry>\n#include <arc_utilities/arc_helpers.hpp>\n\n#ifndef IIWA_ROBOT_CONFIG_HPP\n#define IIWA_ROBOT_CONFIG_HPP\n\nnamespace iiwa_robot_controllers\n{\n    class PIDParams\n    {\n    protected:\n\n        double kp_;\n        double ki_;\n        double kd_;\n        double i_clamp_;\n\n    public:\n\n        PIDParams(const double kp, const double ki, const double kd, const double i_clamp) : kp_(kp), ki_(ki), kd_(kd), i_clamp_(i_clamp) {}\n\n        PIDParams() : kp_(0.0), ki_(0.0), kd_(0.0), i_clamp_(0.0) {}\n\n        inline double Kp() const\n        {\n            return kp_;\n        }\n\n        inline double Ki() const\n        {\n            return ki_;\n        }\n\n        inline double Kd() const\n        {\n            return kd_;\n        }\n\n        inline double Iclamp() const\n        {\n            return i_clamp_;\n        }\n    };\n\n    class JointLimits\n    {\n    protected:\n\n        double min_position_;\n        double max_position_;\n        double max_velocity_;\n        double max_effort_;\n\n    public:\n\n        JointLimits(const double min_position, const double max_position, const double max_velocity, const double max_effort)\n        {\n            assert(min_position <= max_position);\n            min_position_ = min_position;\n            max_position_ = max_position;\n            max_velocity_ = std::abs(max_velocity);\n            max_effort_ = std::abs(max_effort);\n        }\n\n        JointLimits() : min_position_(0.0), max_position_(0.0), max_velocity_(0.0), max_effort_(0.0) {}\n\n        inline double MinPosition() const\n        {\n            return min_position_;\n        }\n\n        inline double MaxPosition() const\n        {\n            return max_position_;\n        }\n\n        inline std::pair<double, double> PositionLimits() const\n        {\n            return std::make_pair(min_position_, max_position_);\n        }\n\n        inline double MaxVelocity() const\n        {\n            return max_velocity_;\n        }\n\n        inline double MaxEffort() const\n        {\n            return max_effort_;\n        }\n    };\n\n    inline std::vector<std::string> GetJointNames(const std::string& joint_name_prefix)\n    {\n        std::vector<std::string> joint_names(7);\n        joint_names[0] = joint_name_prefix + \"_joint_1\";\n        joint_names[1] = joint_name_prefix + \"_joint_2\";\n        joint_names[2] = joint_name_prefix + \"_joint_3\";\n        joint_names[3] = joint_name_prefix + \"_joint_4\";\n        joint_names[4] = joint_name_prefix + \"_joint_5\";\n        joint_names[5] = joint_name_prefix + \"_joint_6\";\n        joint_names[6] = joint_name_prefix + \"_joint_7\";\n        return joint_names;\n    }\n\n    inline std::map<std::string, JointLimits> GetArmDefaultLimits(const std::string& joint_name_prefix)\n    {\n        const std::vector<std::string> joint_names = GetJointNames(joint_name_prefix);\n        std::map<std::string, JointLimits> joint_limits;\n        joint_limits[joint_names[0]] = JointLimits(-2.96705972839, 2.96705972839, 10.0, 300.0);\n        joint_limits[joint_names[1]] = JointLimits(-2.09439510239, 2.09439510239, 10.0, 300.0);\n        joint_limits[joint_names[2]] = JointLimits(-2.96705972839, 2.96705972839, 10.0, 300.0);\n        joint_limits[joint_names[3]] = JointLimits(-2.09439510239, 2.09439510239, 10.0, 300.0);\n        joint_limits[joint_names[4]] = JointLimits(-2.96705972839, 2.96705972839, 10.0, 300.0);\n        joint_limits[joint_names[5]] = JointLimits(-2.09439510239, 2.09439510239, 10.0, 300.0);\n        joint_limits[joint_names[6]] = JointLimits(-3.05432619099, 3.05432619099, 10.0, 300.0);\n        return joint_limits;\n    }\n\n    inline std::map<std::string, JointLimits> GetArmLimits(const std::string& joint_name_prefix, const double position_scaling=1.0, const double velocity_scaling=1.0, const double effort_scaling=1.0)\n    {\n        assert(position_scaling >= 0.0);\n        assert(position_scaling <= 1.0);\n        assert(velocity_scaling >= 0.0);\n        assert(velocity_scaling <= 1.0);\n        assert(effort_scaling >= 0.0);\n        assert(effort_scaling <= 1.0);\n        const std::map<std::string, JointLimits> default_joint_limits = GetArmDefaultLimits(joint_name_prefix);\n        std::map<std::string, JointLimits> joint_limits;\n        const auto default_limit_pairs = arc_helpers::GetKeysAndValues(default_joint_limits);\n        for (size_t idx = 0; idx < default_limit_pairs.size(); idx++)\n        {\n            const std::string& joint_name = default_limit_pairs[idx].first;\n            const JointLimits& default_joint_limit = default_limit_pairs[idx].second;\n            const JointLimits scaled_joint_limit((default_joint_limit.MinPosition() * position_scaling),\n                                                 (default_joint_limit.MaxPosition() * position_scaling),\n                                                 (default_joint_limit.MaxVelocity() * velocity_scaling),\n                                                 (default_joint_limit.MaxEffort() * effort_scaling));\n            joint_limits[joint_name] = scaled_joint_limit;\n        }\n        return joint_limits;\n    }\n\n    inline std::map<std::string, PIDParams> GetArmDefaultPositionControllerParams(const std::string& joint_name_prefix)\n    {\n        const std::vector<std::string> joint_names = GetJointNames(joint_name_prefix);\n        std::map<std::string, iiwa_robot_controllers::PIDParams> joint_controller_params;\n        joint_controller_params[joint_names[0]] = iiwa_robot_controllers::PIDParams(1.0, 0.0, 0.1, 1.0);\n        joint_controller_params[joint_names[1]] = iiwa_robot_controllers::PIDParams(1.0, 0.0, 0.1, 1.0);\n        joint_controller_params[joint_names[2]] = iiwa_robot_controllers::PIDParams(1.0, 0.0, 0.1, 1.0);\n        joint_controller_params[joint_names[3]] = iiwa_robot_controllers::PIDParams(1.0, 0.0, 0.1, 1.0);\n        joint_controller_params[joint_names[4]] = iiwa_robot_controllers::PIDParams(1.0, 0.0, 0.1, 1.0);\n        joint_controller_params[joint_names[5]] = iiwa_robot_controllers::PIDParams(1.0, 0.0, 0.1, 1.0);\n        joint_controller_params[joint_names[6]] = iiwa_robot_controllers::PIDParams(1.0, 0.0, 0.1, 1.0);\n        return joint_controller_params;\n    }\n\n    inline std::map<std::string, PIDParams> GetArmDefaultVelocityControllerParams(const std::string& joint_name_prefix)\n    {\n        const std::vector<std::string> joint_names = GetJointNames(joint_name_prefix);\n        std::map<std::string, iiwa_robot_controllers::PIDParams> joint_controller_params;\n        joint_controller_params[joint_names[0]] = iiwa_robot_controllers::PIDParams(10.0, 0.0, 1.0, 0.0);\n        joint_controller_params[joint_names[1]] = iiwa_robot_controllers::PIDParams(10.0, 0.0, 1.0, 0.0);\n        joint_controller_params[joint_names[2]] = iiwa_robot_controllers::PIDParams(10.0, 0.0, 1.0, 0.0);\n        joint_controller_params[joint_names[3]] = iiwa_robot_controllers::PIDParams(10.0, 0.0, 1.0, 0.0);\n        joint_controller_params[joint_names[4]] = iiwa_robot_controllers::PIDParams(10.0, 0.0, 1.0, 0.0);\n        joint_controller_params[joint_names[5]] = iiwa_robot_controllers::PIDParams(10.0, 0.0, 1.0, 0.0);\n        joint_controller_params[joint_names[6]] = iiwa_robot_controllers::PIDParams(10.0, 0.0, 1.0, 0.0);\n        return joint_controller_params;\n    }\n\n}\n#endif // IIWA_ROBOT_CONFIG_HPP\n", "meta": {"hexsha": "6555d6d62c8e5765823e24b08503af0db56f8b4b", "size": 7419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "iiwa_robot_controllers/include/iiwa_robot_controllers/iiwa_robot_config.hpp", "max_stars_repo_name": "MMintLab/kuka_iiwa_interface", "max_stars_repo_head_hexsha": "0dd258641377263e7275bc63f37cf32eb12f3e56", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-11T09:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:59:01.000Z", "max_issues_repo_path": "iiwa_robot_controllers/include/iiwa_robot_controllers/iiwa_robot_config.hpp", "max_issues_repo_name": "MMintLab/kuka_iiwa_interface", "max_issues_repo_head_hexsha": "0dd258641377263e7275bc63f37cf32eb12f3e56", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2020-07-01T14:48:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-13T18:38:53.000Z", "max_forks_repo_path": "iiwa_robot_controllers/include/iiwa_robot_controllers/iiwa_robot_config.hpp", "max_forks_repo_name": "MMintLab/kuka_iiwa_interface", "max_forks_repo_head_hexsha": "0dd258641377263e7275bc63f37cf32eb12f3e56", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T23:39:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T23:39:17.000Z", "avg_line_length": 40.7637362637, "max_line_length": 199, "alphanum_fraction": 0.6473918318, "num_tokens": 2000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.17048650993636716}}
{"text": "#include <tinyxml.h>\n#include <Eigen/Core>\n#include <map>\n#include <vector>\n#include <fstream>\n#define LARGE_VALUE 1E6\n#define REVOLUTE_JOINT_LIMIT 0.05\n#define PROXIMAR_JOINT_LIMIT 1.0\nnamespace Eigen\n{\n\ttypedef Matrix<double,1,1> Vector1d;\n};\nstruct UserConstant\n{\n\tUserConstant(double _f0,double _lm,double _lt,double angle,double lmax)\n\t\t:f0(_f0),lm(_lm),lt(_lt),pen_angle(angle),l_max(lmax)\n\t{}\n\tdouble f0;\n\tdouble lm;\n\tdouble lt;\n\tdouble pen_angle;\n\tdouble l_max;\t\n};\nstruct MayaConstant\n{\n\tMayaConstant(std::string name)\n\t\t:mName(name)\n\t{}\n\tvoid AddAnchor(std::string body,Eigen::Vector3d glob_pos)\n\t{\n\t\tmAnchors.push_back(std::make_pair(body,glob_pos));\n\t}\n\tstd::string mName;\n\tstd::vector<std::pair<std::string,Eigen::Vector3d>> mAnchors;\n};\nstd::string toString(const Eigen::Vector3d& v)\n{\n\tstd::string ret =\"\";\n\tfor(int i=0;i<v.rows();i++){\n\t\tret += std::to_string(v[i]);\n\t\tret += \" \";\n\t}\n\treturn ret;\n\n}\nstd::string toString(const Eigen::VectorXd& v)\n{\n\tstd::string ret =\"\";\n\tfor(int i=0;i<v.rows();i++){\n\t\tret += std::to_string(v[i]);\n\t\tret += \" \";\n\t}\n\treturn ret;\t\n}\nvoid ReadMayaConstant(std::vector<MayaConstant>& mc,std::string path)\n{\n\tstd::ifstream ifs(path);\n\tif(!(ifs.is_open()))\n\t{\n\t\tstd::cout<<\"Can't read file \"<<path<<std::endl;\n\t\treturn;\n\t}\n\tstd::string str;\n\tstd::string index;\n\tstd::stringstream ss;\n\n\tstd::string name;\n\tdouble x,y,z;\n\twhile(!ifs.eof())\n\t{\n\t\tstr.clear();\n\t\tindex.clear();\n\t\tss.clear();\n\n\t\tstd::getline(ifs,str);\n\t\tss.str(str);\n\t\tss>>index;\n\t\tif(index==\"unit\")\n\t\t{\n\t\t\tss>>name;\n\t\t\t// std::cout<<\"unit \"<<name<<std::endl;\n\t\t\tstd::cout<<name<<std::endl;\n\t\t\tmc.push_back(MayaConstant(name));\n\t\t}\n\t\telse if(index==\"attach\")\n\t\t{\n\t\t\tss>>name;\n\n\t\t\tss>>x>>y>>z;\n\t\t\t// std::cout<<\"attach \"<<name<<\" \"<<-x<<\" \"<<y<<\" \"<<z<<std::endl;\n\t\t\tmc.back().AddAnchor(name,Eigen::Vector3d(x,y,z));\n\t\t}\n\t}\n\n\tifs.close();\n}\nint main(int argc,char** argv)\n{\n\tstd::map<std::string,UserConstant> ucs;\n\tstd::vector<MayaConstant> mcs;\n\tReadMayaConstant(mcs,argv[1]);\n\t// exit(0);\n\tstd::vector<std::string> knee_flexor;\n\tknee_flexor.push_back(\"L_Bicep_Femoris_Short\");\n\tknee_flexor.push_back(\"L_Gastrocnemius_Lateral_Head\");\n\tknee_flexor.push_back(\"L_Gastrocnemius_Medial_Head\");\n\tknee_flexor.push_back(\"L_Gracilis\");\n\tknee_flexor.push_back(\"L_Popliteus\");\n\tknee_flexor.push_back(\"L_Sartorius\");\n\tstd::vector<std::string> knee_extensor;\n\tknee_extensor.push_back(\"L_Bicep_Femoris_Longus\");\n\tknee_extensor.push_back(\"L_Rectus_Femoris\");\n\tknee_extensor.push_back(\"L_Semimembranosus1\");\n\tknee_extensor.push_back(\"L_Semitendinosus\");\n\tknee_extensor.push_back(\"L_Tensor_Fascia_Lata2\");\n\tknee_extensor.push_back(\"L_Vastus_Intermedius1\");\n\tknee_extensor.push_back(\"L_Vastus_Lateralis1\");\n\tknee_extensor.push_back(\"L_Vastus_Medialis2\");\n\tfor(int i =0;i<mcs.size();i++){\n\t\tucs.insert(std::make_pair(mcs[i].mName,UserConstant(2000.0,1.0,0.2,0.0,-0.1)));\n\t}\n\t// ucs.at(\"L_Soleus1\").l_max = 1.5;\n\t// ucs.at(\"L_Extensor_Digitorum_Longus2\").l_max =0.975;\n\t// ucs.at(\"L_Extensor_Hallucis_Longus\").l_max =0.975;\n\n\t// ucs.at(\"R_Soleus1\").l_max = 0.95;\n\t// ucs.at(\"R_Extensor_Digitorum_Longus2\").l_max =0.975;\n\t// ucs.at(\"R_Extensor_Hallucis_Longus\").l_max =0.975;\n\n\t// // For tibia\n\t// ucs.at(\"L_Semitendinosus\").l_max = 1.02;\n\t// ucs.at(\"L_Vastus_Intermedius1\").l_max = 1.06;\n\t// // ucs.at(\"L_Adductor_Magnus2\").l_max = 1.2;\n\n\t// ucs.at(\"R_Semitendinosus\").l_max = 1.02;\n\t// ucs.at(\"R_Vastus_Intermedius1\").l_max = 1.06;\n\t// // ucs.at(\"R_Adductor_Magnus2\").l_max = 1.2;\n\t// ucs.at(\"L_Psoas_Major1\").l_max = 0.96;\n\t// ucs.at(\"L_Sartorius\").l_max = 0.9;\n\t// ucs.at(\"L_Tensor_Fascia_Lata2\").l_max = 0.98;\n\n\t// ucs.at(\"R_Psoas_Major1\").l_max = 0.96;\n\t// ucs.at(\"L_iliacus1\").l_max = 0.98;\n\t// ucs.at(\"R_iliacus1\").l_max = 0.98;\n\t// ucs.at(\"R_Sartorius\").l_max = 0.9;\n\t// ucs.at(\"R_Tensor_Fascia_Lata2\").l_max = 0.98;\nucs.at(\"L_Bicep_Femoris_Longus\").l_max = 1.0;\nucs.at(\"R_Bicep_Femoris_Longus\").l_max = 1.0;\n// ucs.at(\"L_Gastrocnemius_Lateral_Head\").l_max = 0.95;\nucs.at(\"L_Semimembranosus1\").l_max = 0.95;\nucs.at(\"R_Semimembranosus1\").l_max = 0.95;\n// ucs.at(\"L_Semitendinosus\").l_max = 1.2;\n\t// for(int i=0;i<knee_flexor.size();i++)\n\t// {\n\t// \tucs.at(knee_flexor[i]).lm = 0.4;\n\t// \tucs.at(knee_flexor[i]).lt = 0.4;\n\t// }\n\t// for(int i=0;i<knee_extensor.size();i++)\n\t// {\n\t// \tucs.at(knee_extensor[i]).lm = 0.7;\n\t// \tucs.at(knee_extensor[i]).lt = 0.2;\n\t// }\n\n\t// ucs.insert(std::make_pair(\"L_Adductor_Longus1\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Bicep_Femoris_Longus\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Bicep_Femoris_Short\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Extensor_Digitorum_Longus1\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Extensor_Hallucis_Longus\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Flexor_Digitorum_Longus2\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Flexor_Hallucis\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Gastrocnemius_Lateral_Head\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Gluteus_Maximus\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Gluteus_Maximus2\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Gluteus_Maximus4\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Gluteus_Medius1\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Gracilis\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Obturator_Externus\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Obturator_Internus\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Peroneus_Longus\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Plantaris\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Psoas_Major2\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Rectus_Femoris\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Sartorius\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Semimembranosus\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Semitendinosus\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Soleus1\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Tensor_Fascia_Lata2\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Tibialis_Anterior\",UserConstant(300.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Vastus_Intermedius1\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Vastus_Lateralis\",UserConstant(500.0,1.0,0.2,0.0)));\n\t// ucs.insert(std::make_pair(\"L_Vastus_Medialis1\",UserConstant(500.0,1.0,0.2,0.0)));\n\tstd::vector<std::string> upper_body;\n\t// upper_body.push_back(\"Pevlis\");\n\tupper_body.push_back(\"Spine\");\n\tupper_body.push_back(\"Torso\");\n\tupper_body.push_back(\"Neck\");\n\tupper_body.push_back(\"Head\");\n\tupper_body.push_back(\"ShoulderL\");\n\tupper_body.push_back(\"ArmL\");\n\tupper_body.push_back(\"ForeArmL\");\n\tupper_body.push_back(\"HandL\");\n\tupper_body.push_back(\"ShoulderR\");\n\tupper_body.push_back(\"ArmR\");\n\tupper_body.push_back(\"ForeArmR\");\n\tupper_body.push_back(\"HandR\");\n\tupper_body.push_back(\"FemurR\");\n\tupper_body.push_back(\"TibiaR\");\n\tupper_body.push_back(\"TalusR\");\n\n\n\t// upper_body.push_back(\"FemurL\");\n\t// upper_body.push_back(\"TibiaL\");\n\t// upper_body.push_back(\"TalusL\");\n\t\n\tTiXmlDocument doc;\n\tTiXmlElement* muscle_elem = new TiXmlElement(\"Muscle\");\n\tdoc.LinkEndChild(muscle_elem);\n\n\tfor(int i =0;i<mcs.size();i++)\n\t{\n\t\tTiXmlElement* unit_elem = new TiXmlElement(\"Unit\");\n\t\tstd::cout<<mcs[i].mName<<std::endl;\n\t\tauto& uc = ucs.at(mcs[i].mName);\n\n\t\tunit_elem->SetAttribute(\"name\",mcs[i].mName);\n\t\tunit_elem->SetAttribute(\"f0\",std::to_string(uc.f0));\n\t\tunit_elem->SetAttribute(\"lm\",std::to_string(uc.lm));\n\t\tunit_elem->SetAttribute(\"lt\",std::to_string(uc.lt));\n\t\tunit_elem->SetAttribute(\"pen_angle\",std::to_string(uc.pen_angle));\n\t\tunit_elem->SetAttribute(\"lmax\",std::to_string(uc.l_max));\n\t\tbool is_lower_body = true;\n\t\tfor(int j =0;j<mcs[i].mAnchors.size();j++)\n\t\t{\n\t\t\tTiXmlElement* waypoint_elem = new TiXmlElement(\"Waypoint\");\n\n\t\t\t// for(int k =0;k<upper_body.size();k++)\n\t\t\t// \tif(mcs[i].mAnchors[j].first == upper_body[k])\n\t\t\t// \t\tis_lower_body = false;\n\t\t\t// if(mcs[i].mAnchors[j].first == \"Pelvis\")\n\t\t\t// \tis_lower_body = true;\n\t\t\t// else\n\t\t\t// \tis_lower_body = false;\n\t\t\t\t\n\t\t\tif(uc.l_max<0.0)\n\t\t\t\tis_lower_body = false;\n\t\t\twaypoint_elem->SetAttribute(\"body\",mcs[i].mAnchors[j].first);\n\t\t\twaypoint_elem->SetAttribute(\"p\",toString(mcs[i].mAnchors[j].second));\n\t\t\tunit_elem->LinkEndChild(waypoint_elem);\t\n\t\t}\n\t\tif(is_lower_body)\n\t\t\tmuscle_elem->LinkEndChild(unit_elem);\n\t}\n\tTiXmlPrinter printer;\n\tprinter.SetIndent( \"\\n\" );\n\n\tdoc.Accept( &printer );\n\tdoc.SaveFile(argv[2]);\n\t\n\treturn 0;\n}", "meta": {"hexsha": "444f95ef4b7bd86f1542ca18f2eae5366ed76f7e", "size": 8871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xmlparser/muscle_main.cpp", "max_stars_repo_name": "snumrl/MSS", "max_stars_repo_head_hexsha": "29433598a9a026a18cbc6c5a9742dee7490ab9c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-01-22T11:10:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T09:26:14.000Z", "max_issues_repo_path": "xmlparser/muscle_main.cpp", "max_issues_repo_name": "snumrl/MSS", "max_issues_repo_head_hexsha": "29433598a9a026a18cbc6c5a9742dee7490ab9c7", "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": "xmlparser/muscle_main.cpp", "max_forks_repo_name": "snumrl/MSS", "max_forks_repo_head_hexsha": "29433598a9a026a18cbc6c5a9742dee7490ab9c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-26T12:29:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T15:13:39.000Z", "avg_line_length": 34.1192307692, "max_line_length": 95, "alphanum_fraction": 0.6866193214, "num_tokens": 3340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.17048650993636716}}
{"text": "#pragma once\n\n#include <memory>\n#include <utility>\n\n#include <boost/operators.hpp>\n\n#include <elle/serialization.hh>\n\n#include <elle/cryptography/fwd.hh>\n#include <elle/cryptography/types.hh>\n#include <elle/cryptography/Oneway.hh>\n#include <elle/cryptography/Cipher.hh>\n#if defined(ELLE_CRYPTOGRAPHY_ROTATION)\n# include <elle/cryptography/rsa/Seed.hh>\n#endif\n#include <elle/cryptography/rsa/Padding.hh>\n#include <elle/cryptography/rsa/defaults.hh>\n\n//\n// ---------- Class -----------------------------------------------------------\n//\n\nnamespace elle\n{\n  namespace cryptography\n  {\n    namespace rsa\n    {\n      /// Represent a private key in the RSA asymmetric cryptosystem.\n      class PrivateKey\n        : public elle::Printable\n        , public std::enable_shared_from_this<PrivateKey>\n        , private boost::totally_ordered<PrivateKey>\n      {\n        /*-------------.\n        | Construction |\n        `-------------*/\n      public:\n        /// Construct a private key based on the given EVP_PKEY key whose\n        /// ownership is transferred.\n        explicit\n        PrivateKey(::EVP_PKEY* key);\n        /// Construct a private key based on the given RSA key whose\n        /// ownership is transferred to the private key.\n        explicit\n        PrivateKey(::RSA* rsa);\n        PrivateKey(PrivateKey const& other);\n        PrivateKey(PrivateKey&& other);\n        virtual\n        ~PrivateKey() = default;\n\n        /*--------.\n        | Methods |\n        `--------*/\n      private:\n        /// Construct the object based on the given RSA structure whose\n        /// ownership is transferred to the callee.\n        void\n        _construct(::RSA* rsa);\n        /// Check that the key is valid.\n        void\n        _check() const;\n      public:\n        /// Open the envelope and return the original plain text.\n        elle::Buffer\n        open(elle::ConstWeakBuffer const& code,\n             Cipher const cipher = defaults::envelope_cipher,\n             Mode const mode = defaults::envelope_mode) const;\n        /// Open the envelope, decrypt its stream-based content and return the\n        /// original plan text in the output stream.\n        void\n        open(std::istream& code,\n             std::ostream& plain,\n             Cipher const cipher = defaults::envelope_cipher,\n             Mode const mode = defaults::envelope_mode) const;\n        /// Decrypt a code with the raw public key.\n        ///\n        /// WARNING: This method cannot be used to decrypt large amount of\n        ///          data as constrained by the key's modulus. Please refer\n        ///          to the seal()/open() methods.\n        elle::Buffer\n        decrypt(elle::ConstWeakBuffer const& code,\n                Padding const padding = defaults::encryption_padding) const;\n        /// Sign the given plain text and return the signature.\n        virtual\n        elle::Buffer\n        sign(elle::ConstWeakBuffer const& plain,\n             Padding const padding = defaults::signature_padding,\n             Oneway const oneway = defaults::oneway) const;\n        /// Sign the given plain text and return the signature.\n        template <typename T>\n        elle::Buffer\n        sign(T const& o) const;\n        /// Sign the given plain text and return the signature.\n        template <typename T>\n        elle::Buffer\n        sign(T const& o, elle::Version const& version) const;\n        /// Sign the given plain text and return the signature.\n        template <typename T>\n        std::function <elle::Buffer ()>\n        sign_async(T const& o, elle::Version const& version) const;\n      private:\n        template <typename T>\n        std::function<elle::Buffer (PrivateKey const* self)>\n        _sign_async(T const& o, elle::Version const& version) const;\n      public:\n        /// Write the signature in the output stream given the stream-based\n        /// plain text.\n        elle::Buffer\n        sign(std::istream& plain,\n             Padding const padding = defaults::signature_padding,\n             Oneway const oneway = defaults::oneway) const;\n        /// Return the private key's size in bytes.\n        uint32_t\n        size() const;\n        /// Return the private key's length in bits.\n        uint32_t\n        length() const;\n\n# if defined(ELLE_CRYPTOGRAPHY_ROTATION)\n        /*---------.\n        | Rotation |\n        `---------*/\n      public:\n        /// Construct a private key based on a given seed i.e in a deterministic\n        /// way.\n        explicit\n        PrivateKey(Seed const& seed);\n        /// Return the seed once rotated by the private key.\n        Seed\n        rotate(Seed const& seed) const;\n# endif\n\n        /*----------.\n        | Operators |\n        `----------*/\n      public:\n        bool\n        operator ==(PrivateKey const& other) const;\n        PrivateKey&\n        operator =(PrivateKey& other) = delete;\n        PrivateKey&\n        operator =(PrivateKey&& other);\n\n        /*----------.\n        | Printable |\n        `----------*/\n      public:\n        void\n        print(std::ostream& stream) const override;\n\n        /*-------------.\n        | Serializable |\n        `-------------*/\n      public:\n        PrivateKey(elle::serialization::SerializerIn& serializer);\n        void\n        serialize(elle::serialization::Serializer& serializer);\n        using serialization_tag = elle::serialization_tag;\n\n        /*-----------.\n        | Attributes |\n        `-----------*/\n      private:\n        ELLE_ATTRIBUTE_R(types::EVP_PKEY, key);\n      };\n    }\n  }\n}\n\n//\n// ---------- DER -------------------------------------------------------------\n//\n\nnamespace elle\n{\n  namespace cryptography\n  {\n    namespace rsa\n    {\n      namespace privatekey\n      {\n        namespace der\n        {\n          /*----------.\n          | Functions |\n          `----------*/\n\n          /// Encode the private key in DER.\n          elle::Buffer\n          encode(PrivateKey const& K);\n          /// Decode the private key from a DER representation.\n          PrivateKey\n          decode(elle::ConstWeakBuffer const& buffer);\n        }\n      }\n    }\n  }\n}\n\nnamespace std\n{\n  template <>\n  struct hash<elle::cryptography::rsa::PrivateKey>\n  {\n    size_t\n    operator ()(elle::cryptography::rsa::PrivateKey const& value) const;\n  };\n}\n\n#include <elle/cryptography/rsa/PrivateKey.hxx>\n", "meta": {"hexsha": "e99e1125787a0da143a62cc7561eceb9dbad2f8d", "size": 6283, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/elle/cryptography/rsa/PrivateKey.hh", "max_stars_repo_name": "infinitio/elle", "max_stars_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 521.0, "max_stars_repo_stars_event_min_datetime": "2016-02-14T00:39:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T22:39:25.000Z", "max_issues_repo_path": "src/elle/cryptography/rsa/PrivateKey.hh", "max_issues_repo_name": "infinitio/elle", "max_issues_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-02-21T11:47:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-01T09:37:14.000Z", "max_forks_repo_path": "src/elle/cryptography/rsa/PrivateKey.hh", "max_forks_repo_name": "infinitio/elle", "max_forks_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2017-02-21T10:18:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:35:20.000Z", "avg_line_length": 29.4976525822, "max_line_length": 80, "alphanum_fraction": 0.5570587299, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3140505514119072, "lm_q1q2_score": 0.17048650877627713}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2014 - 2022 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/////////////////////////////// INCLUDES /////////////////////////////////////\n\n#include \"ibamr/ConstraintIBKinematics.h\"\n#include \"ibamr/ConstraintIBMethod.h\"\n#include \"ibamr/IBHierarchyIntegrator.h\"\n#include \"ibamr/IBStrategy.h\"\n#include \"ibamr/INSHierarchyIntegrator.h\"\n#include \"ibamr/INSVCStaggeredHierarchyIntegrator.h\"\n#include \"ibamr/StokesSpecifications.h\"\n\n#include \"ibtk/CCLaplaceOperator.h\"\n#include \"ibtk/CCPoissonPointRelaxationFACOperator.h\"\n#include \"ibtk/FACPreconditioner.h\"\n#include \"ibtk/FACPreconditionerStrategy.h\"\n#include \"ibtk/HierarchyMathOps.h\"\n#include \"ibtk/IBTK_CHKERRQ.h\"\n#include \"ibtk/IBTK_MPI.h\"\n#include \"ibtk/IndexUtilities.h\"\n#include \"ibtk/LData.h\"\n#include \"ibtk/LDataManager.h\"\n#include \"ibtk/LIndexSetData.h\"\n#include \"ibtk/LMesh.h\"\n#include \"ibtk/LNode.h\"\n#include \"ibtk/LNodeSetData.h\"\n#include \"ibtk/LSet.h\"\n#include \"ibtk/LSetData.h\"\n#include \"ibtk/LSetDataIterator.h\"\n#include \"ibtk/LinearOperator.h\"\n#include \"ibtk/LinearSolver.h\"\n#include \"ibtk/SideDataSynchronization.h\"\n#include \"ibtk/ibtk_utilities.h\"\n\n#include \"ArrayData.h\"\n#include \"CartesianGridGeometry.h\"\n#include \"CartesianPatchGeometry.h\"\n#include \"CellData.h\"\n#include \"CellIndex.h\"\n#include \"CellIterator.h\"\n#include \"ComponentSelector.h\"\n#include \"HierarchyDataOpsManager.h\"\n#include \"HierarchyDataOpsReal.h\"\n#include \"Patch.h\"\n#include \"PatchHierarchy.h\"\n#include \"PatchLevel.h\"\n#include \"PoissonSpecifications.h\"\n#include \"SAMRAIVectorReal.h\"\n#include \"SideData.h\"\n#include \"VariableDatabase.h\"\n#include \"VariableFillPattern.h\"\n#include \"tbox/Array.h\"\n#include \"tbox/MathUtilities.h\"\n#include \"tbox/PIO.h\"\n#include \"tbox/RestartManager.h\"\n#include \"tbox/Timer.h\"\n#include \"tbox/TimerManager.h\"\n#include \"tbox/Utilities.h\"\n\n#include \"petscvec.h\"\n\n#include \"ibamr/app_namespaces.h\" // IWYU pragma: keep\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <boost/multi_array.hpp>\nIBTK_ENABLE_EXTRA_WARNINGS\n\n#include <algorithm>\n#include <limits>\n#include <utility>\n\nnamespace SAMRAI\n{\nnamespace hier\n{\ntemplate <int DIM>\nclass Box;\n} // namespace hier\nnamespace solv\n{\ntemplate <int DIM>\nclass RobinBcCoefStrategy;\n} // namespace solv\n} // namespace SAMRAI\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\nnamespace IBAMR\n{\n/////////////////////////////// STATIC ///////////////////////////////////////\n\nnamespace\n{\n// Timers.\nstatic Pointer<Timer> t_postprocessSolveFluidEquation;\nstatic Pointer<Timer> t_calculateCOMandMOIOfStructures;\nstatic Pointer<Timer> t_interpolateFluidSolveVelocity;\nstatic Pointer<Timer> t_calculateKinematicsVelocity;\nstatic Pointer<Timer> t_calculateRigidMomentum;\nstatic Pointer<Timer> t_correctVelocityOnLagrangianMesh;\nstatic Pointer<Timer> t_spreadCorrectedLagrangianVelocity;\nstatic Pointer<Timer> t_applyProjection;\nstatic Pointer<Timer> t_eulerStep;\nstatic Pointer<Timer> t_midpointStep;\n\n// Number of ghost cells used for each variable quantity.\nstatic const int CELLG = 1;\n\n// Type of coarsening to perform prior to setting coarse-fine boundary and\n// physical boundary ghost cell values.\nstatic const std::string DATA_REFINE_TYPE = \"NONE\";\nstatic const bool USE_CF_INTERPOLATION = true;\nstatic const std::string CELL_DATA_COARSEN_TYPE = \"CUBIC_COARSEN\";\nstatic const std::string SIDE_DATA_COARSEN_TYPE = \"CUBIC_COARSEN\";\n\n// Type of extrapolation to use at physical boundaries.\nstatic const std::string BDRY_EXTRAP_TYPE = \"LINEAR\";\n\n// Whether to enforce consistent interpolated values at Type 2 coarse-fine\n// interface ghost cells.\nstatic const bool CONSISTENT_TYPE_2_BDRY = false;\n\nclass find_struct_handle\n{\nprivate:\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    std::pair<int, int> struct_to_find_range;\n\npublic:\n    find_struct_handle(std::pair<int, int> struct_range) : struct_to_find_range(std::move(struct_range))\n    {\n    }\n\n    inline bool operator()(Pointer<ConstraintIBKinematics> ib_kinematics_ptr)\n    {\n        const StructureParameters& struct_param = ib_kinematics_ptr->getStructureParameters();\n        const std::vector<std::pair<int, int> >& range = struct_param.getLagIdxRange();\n\n        bool is_in_range = false;\n        for (const auto& idx : range)\n        {\n            if (struct_to_find_range.first == idx.first && struct_to_find_range.second == idx.second)\n            {\n                is_in_range = true;\n                break;\n            }\n        }\n\n        return is_in_range;\n    }\n};\n\ntemplate <typename itr, typename T>\ninline int\nfind_struct_handle_position(itr begin, itr end, const T& value)\n{\n    int position = 0;\n    while (begin != end)\n    {\n        if (*begin++ == value)\n            return position;\n        else\n            ++position;\n    }\n\n    TBOX_ASSERT(false);\n    return -1;\n}\n\n#if (NDIM == 3)\n// Routine to solve 3X3 equation to get rigid body rotational velocity.\ninline void\nsolveSystemOfEqns(std::vector<double>& ang_mom, const Eigen::Matrix3d& inertiaTensor)\n{\n    const double a1 = inertiaTensor(0, 0), a2 = inertiaTensor(0, 1), a3 = inertiaTensor(0, 2), b1 = inertiaTensor(1, 0),\n                 b2 = inertiaTensor(1, 1), b3 = inertiaTensor(1, 2), c1 = inertiaTensor(2, 0), c2 = inertiaTensor(2, 1),\n                 c3 = inertiaTensor(2, 2), d1 = ang_mom[0], d2 = ang_mom[1], d3 = ang_mom[2];\n    const double Dnr = (a3 * b2 * c1 - a2 * b3 * c1 - a3 * b1 * c2 + a1 * b3 * c2 + a2 * b1 * c3 - a1 * b2 * c3);\n    ang_mom[0] = (b3 * c2 * d1 - b2 * c3 * d1 - a3 * c2 * d2 + a2 * c3 * d2 + a3 * b2 * d3 - a2 * b3 * d3) / Dnr;\n    ang_mom[1] = -(b3 * c1 * d1 - b1 * c3 * d1 - a3 * c1 * d2 + a1 * c3 * d2 + a3 * b1 * d3 - a1 * b3 * d3) / Dnr;\n    ang_mom[2] = (b2 * c1 * d1 - b1 * c2 * d1 - a2 * c1 * d2 + a1 * c2 * d2 + a2 * b1 * d3 - a1 * b2 * d3) / Dnr;\n    return;\n}\n#endif\n} // namespace\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\n\nConstraintIBMethod::ConstraintIBMethod(std::string object_name,\n                                       Pointer<Database> input_db,\n                                       const int no_structures,\n                                       bool register_for_restart)\n    : IBMethod(std::move(object_name), input_db, register_for_restart),\n      d_no_structures(no_structures),\n      d_ib_kinematics(d_no_structures, Pointer<ConstraintIBKinematics>(nullptr)),\n      d_vol_element(d_no_structures, 0.0),\n      d_vol_element_is_set(d_no_structures, false),\n      d_structure_vol(d_no_structures, 0.0),\n      d_structure_mom(d_no_structures, std::vector<double>(3, 0.0)),\n      d_structure_rotational_mom(d_no_structures, std::vector<double>(3, 0.0)),\n      d_rigid_trans_vel_current(d_no_structures, std::vector<double>(3, 0.0)),\n      d_rigid_trans_vel_new(d_no_structures, std::vector<double>(3, 0.0)),\n      d_rigid_rot_vel_current(d_no_structures, std::vector<double>(3, 0.0)),\n      d_rigid_rot_vel_new(d_no_structures, std::vector<double>(3, 0.0)),\n      d_incremented_angle_from_reference_axis(d_no_structures, std::vector<double>(3, 0.0)),\n      d_vel_com_def_current(d_no_structures, std::vector<double>(3, 0.0)),\n      d_vel_com_def_new(d_no_structures, std::vector<double>(3, 0.0)),\n      d_omega_com_def_current(d_no_structures, std::vector<double>(3, 0.0)),\n      d_omega_com_def_new(d_no_structures, std::vector<double>(3, 0.0)),\n      d_center_of_mass_current(d_no_structures, std::vector<double>(3, 0.0)),\n      d_center_of_mass_new(d_no_structures, std::vector<double>(3, 0.0)),\n      d_center_of_mass_unshifted_current(d_no_structures, std::vector<double>(3, 0.0)),\n      d_center_of_mass_unshifted_new(d_no_structures, std::vector<double>(3, 0.0)),\n      d_moment_of_inertia_current(d_no_structures, Eigen::Matrix3d::Zero()),\n      d_moment_of_inertia_new(d_no_structures, Eigen::Matrix3d::Zero()),\n      d_tagged_pt_lag_idx(d_no_structures, 0),\n      d_tagged_pt_position(d_no_structures, std::vector<double>(3, 0.0)),\n      d_rho_solid(d_no_structures, std::numeric_limits<double>::quiet_NaN())\n{\n    // NOTE: Parent class constructor registers class with the restart manager,\n    // sets object name.\n\n    // Initialize object with data read from the input and restart databases.\n    bool from_restart = RestartManager::getManager()->isFromRestart();\n    if (from_restart) getFromRestart();\n    if (!input_db.isNull()) getFromInput(input_db, from_restart);\n\n    // Setup the cell centered Poisson Solver needed for projection.\n    if (d_needs_div_free_projection)\n    {\n        const std::string velcorrection_projection_prefix = \"cIB_\";\n        // Setup the various solver components.\n        for (int d = 0; d < NDIM; ++d)\n        {\n            d_velcorrection_projection_bc_coef.setBoundarySlope(2 * d, 0.0);\n            d_velcorrection_projection_bc_coef.setBoundarySlope(2 * d + 1, 0.0);\n        }\n\n        d_velcorrection_projection_spec.reset(\n            new PoissonSpecifications(d_object_name + \"::ConstraintIBMethodProjection::Spec\"));\n        d_velcorrection_projection_op =\n            new CCLaplaceOperator(d_object_name + \"ConstraintIBMethodProjection::PoissonOperator\", true);\n        d_velcorrection_projection_op->setPoissonSpecifications(*d_velcorrection_projection_spec);\n        d_velcorrection_projection_op->setPhysicalBcCoef(&d_velcorrection_projection_bc_coef);\n\n        d_velcorrection_projection_solver =\n            new PETScKrylovPoissonSolver(d_object_name + \"ConstraintIBMethodProjection::PoissonKrylovSolver\",\n                                         Pointer<Database>(nullptr),\n                                         velcorrection_projection_prefix);\n        d_velcorrection_projection_solver->setInitialGuessNonzero(false);\n        d_velcorrection_projection_solver->setOperator(d_velcorrection_projection_op);\n\n        if (d_velcorrection_projection_fac_pc_db.isNull())\n        {\n            TBOX_WARNING(d_object_name << \"::ConstraintIBMethod():\\n\"\n                                       << \" ConstraintIBMethodProjection:: Poisson \"\n                                          \"FAC PC solver database is null.\"\n                                       << std::endl);\n        }\n\n        d_velcorrection_projection_fac_op = new CCPoissonPointRelaxationFACOperator(\n            d_object_name + \":: ConstraintIBMethodProjection::PoissonFACOperator\",\n            d_velcorrection_projection_fac_pc_db,\n            \"\");\n        d_velcorrection_projection_fac_op->setPoissonSpecifications(*d_velcorrection_projection_spec);\n        d_velcorrection_projection_fac_pc =\n            new IBTK::FACPreconditioner(d_object_name + \"::ConstraintIBMethodProjection::PoissonPreconditioner\",\n                                        d_velcorrection_projection_fac_op,\n                                        d_velcorrection_projection_fac_pc_db,\n                                        \"\");\n        d_velcorrection_projection_solver->setPreconditioner(d_velcorrection_projection_fac_pc);\n\n        // Set some default options.\n        d_velcorrection_projection_solver->setKSPType(\"gmres\");\n        d_velcorrection_projection_solver->setAbsoluteTolerance(1.0e-12);\n        d_velcorrection_projection_solver->setRelativeTolerance(1.0e-08);\n        d_velcorrection_projection_solver->setMaxIterations(25);\n\n        // NOTE: We always use homogeneous Neumann boundary conditions for the\n        // velocity correction projection Poisson solver.\n        d_velcorrection_projection_solver->setNullspace(true);\n    }\n    else\n    {\n        d_velcorrection_projection_spec = nullptr;\n        d_velcorrection_projection_op = nullptr;\n        d_velcorrection_projection_fac_op = nullptr;\n        d_velcorrection_projection_fac_pc = nullptr;\n        d_velcorrection_projection_solver = nullptr;\n    }\n\n    // Do printing operation for processor 0 only.\n    if (!IBTK_MPI::getRank() && d_print_output)\n    {\n        d_trans_vel_stream.resize(d_no_structures);\n        d_rot_vel_stream.resize(d_no_structures);\n        d_drag_force_stream.resize(d_no_structures);\n        d_moment_of_inertia_stream.resize(d_no_structures);\n        d_torque_stream.resize(d_no_structures);\n        d_position_COM_stream.resize(d_no_structures);\n        d_power_spent_stream.resize(d_no_structures);\n\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            const std::string struct_no_str = std::to_string(struct_no);\n\n            if (from_restart)\n                d_trans_vel_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Trans_vel_struct_no_\" + struct_no_str, std::fstream::app));\n            else\n                d_trans_vel_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Trans_vel_struct_no_\" + struct_no_str, std::fstream::out));\n\n            if (from_restart)\n                d_rot_vel_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Rot_vel_struct_no_\" + struct_no_str, std::fstream::app));\n            else\n                d_rot_vel_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Rot_vel_struct_no_\" + struct_no_str, std::fstream::out));\n\n            if (from_restart)\n                d_drag_force_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Drag_force_struct_no_\" + struct_no_str, std::fstream::app));\n            else\n                d_drag_force_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Drag_force_struct_no_\" + struct_no_str, std::fstream::out));\n\n            if (from_restart)\n                d_moment_of_inertia_stream[struct_no].reset(\n                    new std::ofstream(d_base_output_filename + \"_MOI_struct_no_\" + struct_no_str, std::fstream::app));\n            else\n                d_moment_of_inertia_stream[struct_no].reset(\n                    new std::ofstream(d_base_output_filename + \"_MOI_struct_no_\" + struct_no_str, std::fstream::out));\n\n            if (from_restart)\n                d_torque_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Torque_struct_no_\" + struct_no_str, std::fstream::app));\n            else\n                d_torque_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Torque_struct_no_\" + struct_no_str, std::fstream::out));\n\n            if (from_restart)\n                d_position_COM_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_COM_coordinates_struct_no_\" + struct_no_str, std::fstream::app));\n            else\n                d_position_COM_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_COM_coordinates_struct_no_\" + struct_no_str, std::fstream::out));\n\n            if (from_restart)\n                d_power_spent_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Power_spent_struct_no_\" + struct_no_str, std::fstream::app));\n            else\n                d_power_spent_stream[struct_no].reset(new std::ofstream(\n                    d_base_output_filename + \"_Power_spent_struct_no_\" + struct_no_str, std::fstream::out));\n        }\n\n        // Output Eulerian momentum.\n        std::string eul_mom_str = d_base_output_filename + \"_EULERIAN_MOMENTUM.TXT\";\n        if (from_restart)\n            d_eulerian_mom_stream.open(eul_mom_str.c_str(), std::fstream::app | std::fstream::out);\n        else\n            d_eulerian_mom_stream.open(eul_mom_str.c_str(), std::fstream::out);\n    }\n\n    // Setup the Timers.\n    IBTK_DO_ONCE(\n        t_postprocessSolveFluidEquation =\n            TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::postprocessSolveFluidEquation()\", true);\n        t_calculateCOMandMOIOfStructures =\n            TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::calculateCOMandMOIOfStructures()\", true);\n        t_interpolateFluidSolveVelocity =\n            TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::interpolateFluidSolveVelocity()\", true);\n        t_calculateKinematicsVelocity =\n            TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::calculateKinematicsVelocity()\", true);\n        t_calculateRigidMomentum =\n            TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::calculateRigidMomentum()\", true);\n        t_correctVelocityOnLagrangianMesh =\n            TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::correctVelocityOnLagrangianMesh()\", true);\n        t_spreadCorrectedLagrangianVelocity = TimerManager::getManager()->getTimer(\n            \"IBAMR::ConstraintIBMethod::spreadCorrectedLagrangianVelocity()\", true);\n        t_applyProjection = TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::applyProjection()\", true);\n        t_eulerStep = TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::eulerStep()\", true);\n        t_midpointStep = TimerManager::getManager()->getTimer(\"IBAMR::ConstraintIBMethod::midpointStep()\", true););\n\n    return;\n} // ConstraintIBMethod\n\nConstraintIBMethod::~ConstraintIBMethod()\n{\n    // Deallocate the scratch fluid solve variable.\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n        if (level->checkAllocated(d_u_fluidSolve_cib_idx)) level->deallocatePatchData(d_u_fluidSolve_cib_idx);\n        if (!d_rho_is_const && level->checkAllocated(d_rho_scratch_idx)) level->deallocatePatchData(d_rho_scratch_idx);\n    }\n\n    return;\n} //~ConstraintIBMethod\n\nvoid\nConstraintIBMethod::preprocessSolveFluidEquations(double current_time, double new_time, int cycle_num)\n{\n    IBMethod::preprocessSolveFluidEquations(current_time, new_time, cycle_num);\n\n    // Call any registered pre fluid solve callback functions.\n    for (unsigned i = 0; i < d_prefluidsolve_callback_fns.size(); ++i)\n        d_prefluidsolve_callback_fns[i](current_time, new_time, cycle_num, d_prefluidsolve_callback_fns_ctx[i]);\n    return;\n}\n\nvoid\nConstraintIBMethod::postprocessSolveFluidEquations(double current_time, double new_time, int cycle_num)\n{\n    IBMethod::postprocessSolveFluidEquations(current_time, new_time, cycle_num);\n\n    IBTK_TIMER_START(t_postprocessSolveFluidEquation);\n\n    setCounter();\n\n    IBTK_TIMER_START(t_calculateCOMandMOIOfStructures);\n    calculateCOMandMOIOfStructures();\n    IBTK_TIMER_STOP(t_calculateCOMandMOIOfStructures);\n\n    IBTK_TIMER_START(t_interpolateFluidSolveVelocity);\n    copyFluidVariable(d_u_fluidSolve_idx, d_u_fluidSolve_cib_idx);\n    interpolateFluidSolveVelocity();\n    IBTK_TIMER_STOP(t_interpolateFluidSolveVelocity);\n\n    IBTK_TIMER_START(t_calculateKinematicsVelocity);\n    calculateKinematicsVelocity();\n    IBTK_TIMER_STOP(t_calculateKinematicsVelocity);\n\n    IBTK_TIMER_START(t_calculateRigidMomentum);\n    calculateRigidTranslationalMomentum();\n    calculateRigidRotationalMomentum();\n    IBTK_TIMER_STOP(t_calculateRigidMomentum);\n\n    IBTK_TIMER_START(t_correctVelocityOnLagrangianMesh);\n    correctVelocityOnLagrangianMesh();\n    IBTK_TIMER_STOP(t_correctVelocityOnLagrangianMesh);\n\n    IBTK_TIMER_START(t_spreadCorrectedLagrangianVelocity);\n    spreadCorrectedLagrangianVelocity();\n    IBTK_TIMER_STOP(t_spreadCorrectedLagrangianVelocity);\n\n    if (d_needs_div_free_projection)\n    {\n        IBTK_TIMER_START(t_applyProjection);\n        applyProjection();\n        IBTK_TIMER_STOP(t_applyProjection);\n    }\n\n    if (d_output_drag) calculateDrag();\n    if (d_output_torque) calculateTorque();\n    if (d_output_eul_mom) calculateEulerianMomentum();\n    if (d_output_power) calculatePower();\n    if (d_calculate_structure_linear_mom) calculateStructureMomentum();\n    if (d_calculate_structure_rotational_mom) calculateStructureRotationalMomentum();\n\n    IBTK_TIMER_STOP(t_postprocessSolveFluidEquation);\n\n    // call any other registered post fluid solve callback functions.\n    for (unsigned i = 0; i < d_postfluidsolve_callback_fns.size(); ++i)\n        d_postfluidsolve_callback_fns[i](current_time, new_time, cycle_num, d_postfluidsolve_callback_fns_ctx[i]);\n\n    return;\n}\n\nvoid\nConstraintIBMethod::calculateEulerianMomentum()\n{\n    // Compute Eulerian momentum.\n    std::vector<double> momentum(3, 0.0);\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    SAMRAIVectorReal<NDIM, double> wgt_sc(\"sc_wgt_original\", d_hierarchy, coarsest_ln, finest_ln);\n    wgt_sc.addComponent(getHierarchyMathOps()->getSideWeightVariable(),\n                        getHierarchyMathOps()->getSideWeightPatchDescriptorIndex());\n\n    for (int active = 0; active < NDIM; ++active)\n    {\n        Pointer<SAMRAIVectorReal<NDIM, double> > wgt_sc_active = wgt_sc.cloneVector(\"\");\n        wgt_sc_active->allocateVectorData();\n        wgt_sc_active->copyVector(Pointer<SAMRAIVectorReal<NDIM, double> >(&wgt_sc, false));\n\n        // Zero out components other than active dimension.\n        const int wgt_sc_active_idx = wgt_sc_active->getComponentDescriptorIndex(0);\n        for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n        {\n            Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n            for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n            {\n                Pointer<Patch<NDIM> > patch = level->getPatch(p());\n                Pointer<SideData<NDIM, double> > wgt_sc_active_data = patch->getPatchData(wgt_sc_active_idx);\n                for (int d = 0; d < NDIM; ++d)\n                {\n                    if (d != active)\n                    {\n                        ArrayData<NDIM, double>& arraydata = wgt_sc_active_data->getArrayData(d);\n                        arraydata.fill(0.0);\n                    }\n                }\n            }\n        }\n        if (d_rho_is_const)\n        {\n#if !defined(NDEBUG)\n            TBOX_ASSERT(d_rho_fluid >= 0.0);\n#endif\n            d_hier_sc_data_ops->scale(wgt_sc_active_idx, d_rho_fluid, wgt_sc_active_idx);\n        }\n        else\n        {\n#if !defined(NDEBUG)\n            TBOX_ASSERT(d_rho_ins_idx > 0);\n#endif\n            d_hier_sc_data_ops->multiply(wgt_sc_active_idx, d_rho_ins_idx, wgt_sc_active_idx);\n        }\n\n        momentum[active] = d_hier_sc_data_ops->dot(d_u_fluidSolve_idx, wgt_sc_active_idx);\n\n        wgt_sc_active->freeVectorComponents();\n    }\n\n    if (!IBTK_MPI::getRank() && d_print_output && d_output_eul_mom && (d_timestep_counter % d_output_interval) == 0)\n    {\n        d_eulerian_mom_stream << d_FuRMoRP_new_time << '\\t' << momentum[0] << '\\t' << momentum[1] << '\\t' << momentum[2]\n                              << '\\t' << std::endl;\n    }\n\n    return;\n} // calculateEulerianMomentum\n\nvoid\nConstraintIBMethod::registerEulerianVariables()\n{\n    IBMethod::registerEulerianVariables();\n\n    // Register a scratch fluid velocity variable with appropriate IB-width.\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    d_u_fluidSolve_var = d_ib_solver->getVelocityVariable();\n    Pointer<VariableContext> u_new_ctx = d_ib_solver->getNewContext();\n    d_scratch_context = var_db->getContext(d_object_name + \"::SCRATCH\");\n    d_u_fluidSolve_idx = var_db->mapVariableAndContextToIndex(d_u_fluidSolve_var, u_new_ctx);\n    d_u_fluidSolve_cib_idx =\n        var_db->registerVariableAndContext(d_u_fluidSolve_var, d_scratch_context, getMinimumGhostCellWidth());\n\n    // Initialize  variables & variable contexts associated with projection step.\n    if (d_needs_div_free_projection)\n    {\n        d_u_var = new SideVariable<NDIM, double>(d_object_name + \"::u\");\n        d_Div_u_var = new CellVariable<NDIM, double>(d_object_name + \"::Div_u\");\n        d_phi_var = new CellVariable<NDIM, double>(d_object_name + \"::phi\");\n        const IntVector<NDIM> cell_ghosts = CELLG;\n        d_phi_idx = var_db->registerVariableAndContext(d_phi_var, d_scratch_context, cell_ghosts);\n        d_Div_u_scratch_idx = var_db->registerVariableAndContext(d_Div_u_var, d_scratch_context, cell_ghosts);\n    }\n\n    auto p_vc_ins_hier_integrator =\n        dynamic_cast<INSVCStaggeredHierarchyIntegrator*>(IBStrategy::getINSHierarchyIntegrator());\n    // If using constant rho INS solver,\n    // then assert rho_fluid == rho_solid\n    if (!p_vc_ins_hier_integrator)\n    {\n        d_rho_is_const = true;\n        INSHierarchyIntegrator* p_ins_hier_integrator = IBStrategy::getINSHierarchyIntegrator();\n        d_rho_fluid = p_ins_hier_integrator->getStokesSpecifications()->getRho();\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            if (d_rho_solid[struct_no] != d_rho_fluid)\n            {\n                TBOX_ERROR(d_object_name << \"::registerEulerianVariables():\\n\"\n                                         << \"  for constant density cases, rho_solid[struct_no]\\n\"\n                                         << \"  must equal rho_fluid\");\n            }\n        }\n    }\n    else\n    {\n        d_rho_is_const = p_vc_ins_hier_integrator->rhoIsConstant();\n        if (d_rho_is_const)\n        {\n            d_rho_fluid = p_vc_ins_hier_integrator->getStokesSpecifications()->getRho();\n            for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n            {\n                if (d_rho_solid[struct_no] != d_rho_fluid)\n                {\n                    TBOX_ERROR(d_object_name << \"::registerEulerianVariables():\\n\"\n                                             << \"  for constant density cases, rho_solid[struct_no]\\n\"\n                                             << \"  must equal rho_fluid\");\n                }\n            }\n        }\n        else\n        {\n            // Get the density maintained by the integrator\n            d_rho_ins_idx = p_vc_ins_hier_integrator->getLinearOperatorRhoPatchDataIndex();\n#if !defined(NDEBUG)\n            TBOX_ASSERT(d_rho_ins_idx >= 0);\n#endif\n            d_rho_var = new SideVariable<NDIM, double>(d_object_name + \"::rho\");\n            d_rho_scratch_idx =\n                var_db->registerVariableAndContext(d_rho_var, d_scratch_context, getMinimumGhostCellWidth());\n        }\n    }\n\n    return;\n} // registerEulerianVariables\n\nvoid\nConstraintIBMethod::initializeHierarchyOperatorsandData()\n{\n    // Obtain the Hierarchy data operations objects\n    HierarchyDataOpsManager<NDIM>* hier_ops_manager = HierarchyDataOpsManager<NDIM>::getManager();\n    Pointer<CellVariable<NDIM, double> > cc_var = new CellVariable<NDIM, double>(\"cc_var\");\n    d_hier_cc_data_ops = hier_ops_manager->getOperationsDouble(cc_var, d_hierarchy, true);\n    Pointer<SideVariable<NDIM, double> > sc_var = new SideVariable<NDIM, double>(\"sc_var\");\n    d_hier_sc_data_ops = hier_ops_manager->getOperationsDouble(sc_var, d_hierarchy, true);\n    d_wgt_cc_idx = getHierarchyMathOps()->getCellWeightPatchDescriptorIndex();\n    d_wgt_sc_idx = getHierarchyMathOps()->getSideWeightPatchDescriptorIndex();\n    d_volume = getHierarchyMathOps()->getVolumeOfPhysicalDomain();\n\n    const bool from_restart = RestartManager::getManager()->isFromRestart();\n    if (!from_restart) calculateVolumeElement();\n    setInitialLagrangianVelocity();\n\n    return;\n} // initializeHierarchyOperatorsandData\n\nvoid\nConstraintIBMethod::registerConstraintIBKinematics(const std::vector<Pointer<ConstraintIBKinematics> >& ib_kinematics)\n{\n    if (ib_kinematics.size() != static_cast<unsigned int>(d_no_structures))\n    {\n        TBOX_ERROR(\n            \"ConstraintIBMethod::registerConstraintIBKinematics(). No of \"\n            \"structures \"\n            << ib_kinematics.size() << \" in vector passed to this method is not equal to no. of structures \"\n            << d_no_structures << \" registered with this class\" << std::endl);\n    }\n    else\n    {\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            if (ib_kinematics[struct_no].isNull())\n                TBOX_ERROR(\"NULL ConstraintIBKinematics encountered in vector at \" << struct_no << std::endl);\n            else\n                d_ib_kinematics[struct_no] = ib_kinematics[struct_no];\n        }\n    }\n\n    // Get tagged point index info from objects.\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        const StructureParameters& struct_param = d_ib_kinematics[struct_no]->getStructureParameters();\n        d_tagged_pt_lag_idx[struct_no] = struct_param.getTaggedPtIdx();\n    }\n    return;\n\n} // registerConstraintIBKinematics\n\nvoid\nConstraintIBMethod::putToDatabase(Pointer<Database> db)\n{\n    IBMethod::putToDatabase(db);\n\n    // Put the following quantities to restart database.\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        const std::string struct_no_str = std::to_string(struct_no);\n\n        db->putDoubleArray(\"POSN_COM_STRUCT_\" + struct_no_str, &d_center_of_mass_current[struct_no][0], 3);\n\n        db->putDoubleArray(\"VEL_COM_DEF_STRUCT_\" + struct_no_str, &d_vel_com_def_current[struct_no][0], 3);\n        db->putDoubleArray(\"OMEGA_COM_DEF_STRUCT_\" + struct_no_str, &d_omega_com_def_current[struct_no][0], 3);\n\n        db->putDoubleArray(\"VOL_ELEMENT_STRUCT_\" + struct_no_str, &d_vol_element[0], d_no_structures);\n\n        db->putDoubleArray(\"VOL_STRUCT_\" + struct_no_str, &d_structure_vol[0], d_no_structures);\n\n        db->putDoubleArray(\"VEL_COM_RIG_STRUCT_\" + struct_no_str, &d_rigid_trans_vel_current[struct_no][0], 3);\n        db->putDoubleArray(\"OMEGA_COM_RIG_STRUCT_\" + struct_no_str, &d_rigid_rot_vel_current[struct_no][0], 3);\n\n        db->putDoubleArray(\n            \"DELTA_THETA_STRUCT_\" + struct_no_str, &d_incremented_angle_from_reference_axis[struct_no][0], 3);\n    }\n    db->putDouble(\"TIMESTEP_COUNTER\", d_timestep_counter);\n    db->putDouble(\"FuRMoRP_CURRENT_TIME\", d_FuRMoRP_new_time);\n\n    return;\n\n} // putToDatabase\n\nvoid\nConstraintIBMethod::preprocessIntegrateData(double current_time, double new_time, int num_cycles)\n{\n    IBMethod::preprocessIntegrateData(current_time, new_time, num_cycles);\n\n    // Allocate memory for Lagrangian data.\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    d_l_data_U_interp.resize(finest_ln + 1);\n    d_l_data_U_correction.resize(finest_ln + 1);\n    d_l_data_U_new.resize(finest_ln + 1);\n    d_l_data_U_half.resize(finest_ln + 1);\n    d_l_data_X_half_Euler.resize(finest_ln + 1);\n    d_l_data_X_new_MidPoint.resize(finest_ln + 1);\n    d_l_data_U_current.resize(finest_ln + 1);\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        d_l_data_U_interp[ln] = d_l_data_manager->createLData(d_object_name + \"interp_lag_vel\", ln, NDIM, false);\n        d_l_data_U_correction[ln] = d_l_data_manager->createLData(d_object_name + \"correct_lag_vel\", ln, NDIM, false);\n        d_l_data_U_new[ln] = d_l_data_manager->createLData(d_object_name + \"new_lag_vel\", ln, NDIM, false);\n        d_l_data_U_half[ln] = d_l_data_manager->createLData(d_object_name + \"half_lag_vel\", ln, NDIM, false);\n        d_l_data_X_half_Euler[ln] = d_l_data_manager->createLData(d_object_name + \"X_Euler\", ln, NDIM, false);\n        d_l_data_X_new_MidPoint[ln] = d_l_data_manager->createLData(d_object_name + \"X_MidPoint\", ln, NDIM, false);\n        d_l_data_U_current[ln] = d_l_data_manager->createLData(d_object_name + \"current_lag_vel\", ln, NDIM, false);\n    }\n\n    // Compue the current Lagrangian velocity according to constraint for the\n    // predictor Euler step.\n    calculateCurrentLagrangianVelocity();\n    return;\n\n} // preprocessIntegrateData\n\nvoid\nConstraintIBMethod::postprocessIntegrateData(double current_time, double new_time, int num_cycles)\n{\n    IBMethod::postprocessIntegrateData(current_time, new_time, num_cycles);\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        d_vel_com_def_current[struct_no] = d_vel_com_def_new[struct_no];\n        d_omega_com_def_current[struct_no] = d_omega_com_def_new[struct_no];\n        d_rigid_trans_vel_current[struct_no] = d_rigid_trans_vel_new[struct_no];\n        d_rigid_rot_vel_current[struct_no] = d_rigid_rot_vel_new[struct_no];\n    }\n\n    // Deallocate memory for Lagrangian data.\n    d_l_data_U_interp.clear();\n    d_l_data_U_correction.clear();\n    d_l_data_U_new.clear();\n    d_l_data_U_half.clear();\n    d_l_data_X_half_Euler.clear();\n    d_l_data_X_new_MidPoint.clear();\n    d_l_data_U_current.clear();\n\n    return;\n} // postprocessIntegrateData\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\nConstraintIBMethod::getFromInput(Pointer<Database> input_db, const bool from_restart)\n{\n    // Read in control parameters from input database.\n    d_needs_div_free_projection = input_db->getBoolWithDefault(\"needs_divfree_projection\", d_needs_div_free_projection);\n    input_db->getDoubleArray(\"rho_solid\", &d_rho_solid[0], d_no_structures);\n    d_rho_fluid = input_db->getDoubleWithDefault(\"rho_fluid\", d_rho_fluid);\n    d_calculate_structure_linear_mom =\n        input_db->getBoolWithDefault(\"calculate_structure_linear_mom\", d_calculate_structure_linear_mom);\n    d_calculate_structure_rotational_mom =\n        input_db->getBoolWithDefault(\"calculate_structure_rotational_mom\", d_calculate_structure_rotational_mom);\n\n    // Printing stuff to files.\n    Pointer<Database> output_db = input_db->getDatabase(\"PrintOutput\");\n    d_print_output = output_db->getBoolWithDefault(\"print_output\", d_print_output);\n    d_output_interval = output_db->getIntegerWithDefault(\"output_interval\", d_output_interval);\n    d_output_drag = output_db->getBoolWithDefault(\"output_drag\", d_output_drag);\n    d_output_torque = output_db->getBoolWithDefault(\"output_torque\", d_output_torque);\n    d_output_power = output_db->getBoolWithDefault(\"output_power\", d_output_power);\n    d_output_trans_vel = output_db->getBoolWithDefault(\"output_rig_transvel\", d_output_trans_vel);\n    d_output_rot_vel = output_db->getBoolWithDefault(\"output_rig_rotvel\", d_output_rot_vel);\n    d_output_COM_coordinates = output_db->getBoolWithDefault(\"output_com_coords\", d_output_COM_coordinates);\n    d_output_MOI = output_db->getBoolWithDefault(\"output_moment_inertia\", d_output_MOI);\n    d_output_eul_mom = output_db->getBoolWithDefault(\"output_eulerian_mom\", d_output_eul_mom);\n    d_dir_name = output_db->getStringWithDefault(\"output_dirname\", d_dir_name) + \"/\";\n    d_base_output_filename = d_dir_name + output_db->getStringWithDefault(\"base_filename\", d_base_output_filename);\n\n    // Sanity check.\n    if (d_output_eul_mom && !d_needs_div_free_projection)\n        TBOX_WARNING(\n            \"WARNING ConstraintIBMethod::getFromInput() Eulerian momentum \"\n            \"is calculated but divergence free projection \"\n            \"is not active\"\n            << std::endl);\n\n    if (!from_restart)\n        tbox::Utilities::recursiveMkdir(d_dir_name);\n    else\n    {\n        const bool restart_output_dump_dir_exists = output_db->keyExists(\"restart_output_dump_dir\");\n        if (restart_output_dump_dir_exists)\n        {\n            std::string restart_output_dump_dir = output_db->getString(\"restart_output_dump_dir\");\n            tbox::Utilities::recursiveMkdir(restart_output_dump_dir);\n            d_base_output_filename = restart_output_dump_dir + \"/\" +\n                                     output_db->getStringWithDefault(\"base_filename\", d_base_output_filename);\n        }\n    }\n\n    return;\n} // getFromInput\n\nvoid\nConstraintIBMethod::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(d_object_name << \":  Restart database corresponding to \" << d_object_name\n                                 << \" not found in restart file.\" << std::endl);\n    }\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        const std::string struct_no_str = std::to_string(struct_no);\n\n        db->getDoubleArray(\"POSN_COM_STRUCT_\" + struct_no_str, &d_center_of_mass_current[struct_no][0], 3);\n\n        db->getDoubleArray(\"VEL_COM_DEF_STRUCT_\" + struct_no_str, &d_vel_com_def_current[struct_no][0], 3);\n        db->getDoubleArray(\"OMEGA_COM_DEF_STRUCT_\" + struct_no_str, &d_omega_com_def_current[struct_no][0], 3);\n\n        db->getDoubleArray(\"VOL_ELEMENT_STRUCT_\" + struct_no_str, &d_vol_element[0], d_no_structures);\n\n        db->getDoubleArray(\"VOL_STRUCT_\" + struct_no_str, &d_structure_vol[0], d_no_structures);\n\n        db->getDoubleArray(\"VEL_COM_RIG_STRUCT_\" + struct_no_str, &d_rigid_trans_vel_current[struct_no][0], 3);\n        db->getDoubleArray(\"OMEGA_COM_RIG_STRUCT_\" + struct_no_str, &d_rigid_rot_vel_current[struct_no][0], 3);\n\n        db->getDoubleArray(\n            \"DELTA_THETA_STRUCT_\" + struct_no_str, &d_incremented_angle_from_reference_axis[struct_no][0], 3);\n    }\n    d_timestep_counter = db->getDouble(\"TIMESTEP_COUNTER\");\n    d_FuRMoRP_current_time = db->getDouble(\"FuRMoRP_CURRENT_TIME\");\n\n    return;\n} // getFromRestart\n\nvoid\nConstraintIBMethod::setInitialLagrangianVelocity()\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n\n    const bool from_restart = RestartManager::getManager()->isFromRestart();\n    if (!from_restart) calculateCOMandMOIOfStructures();\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        d_ib_kinematics[struct_no]->setKinematicsVelocity(d_FuRMoRP_current_time,\n                                                          d_incremented_angle_from_reference_axis[struct_no],\n                                                          d_center_of_mass_current[struct_no],\n                                                          d_tagged_pt_position[struct_no]);\n        d_ib_kinematics[struct_no]->setShape(d_FuRMoRP_current_time,\n                                             d_incremented_angle_from_reference_axis[struct_no]);\n\n        if (!from_restart)\n        {\n            const StructureParameters& struct_param = d_ib_kinematics[struct_no]->getStructureParameters();\n            if (struct_param.getStructureIsSelfTranslating()) calculateMomentumOfKinematicsVelocity(struct_no);\n\n            d_vel_com_def_current[struct_no] = d_vel_com_def_new[struct_no];\n            d_omega_com_def_current[struct_no] = d_omega_com_def_new[struct_no];\n        }\n    }\n    return;\n} // setInitialLagrangianVelocity\n\nvoid\nConstraintIBMethod::calculateCOMandMOIOfStructures()\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    Pointer<CartesianGridGeometry<NDIM> > grid_geom = d_hierarchy->getGridGeometry();\n    const double* const domain_x_lower = grid_geom->getXLower();\n    const double* const domain_x_upper = grid_geom->getXUpper();\n    double domain_length[NDIM];\n    for (int d = 0; d < NDIM; ++d)\n    {\n        domain_length[d] = domain_x_upper[d] - domain_x_lower[d];\n    }\n    const IntVector<NDIM>& periodic_shift = grid_geom->getPeriodicShift();\n\n    // Zero out the COM vector.\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        for (int d = 0; d < 3; ++d)\n        {\n            d_center_of_mass_unshifted_current[struct_no][d] = 0.0;\n            d_center_of_mass_unshifted_new[struct_no][d] = 0.0;\n            d_center_of_mass_current[struct_no][d] = 0.0;\n            d_center_of_mass_new[struct_no][d] = 0.0;\n        }\n    }\n    std::vector<std::vector<double> > tagged_position(d_no_structures, std::vector<double>(3, 0.0));\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        // Get LData corresponding to the present and new position of the\n        // structures.\n        Pointer<LData> ptr_x_lag_data_current(nullptr), ptr_x_lag_data_new(nullptr);\n        ptr_x_lag_data_current = d_l_data_manager->getLData(\"X\", ln);\n        if (IBTK::abs_equal_eps(d_FuRMoRP_current_time, 0.0))\n        {\n            ptr_x_lag_data_new = d_l_data_manager->getLData(\"X\", ln);\n        }\n        else\n        {\n            ptr_x_lag_data_new = d_l_data_X_half_Euler[ln];\n        }\n\n        const boost::multi_array_ref<double, 2>& X_data_current = *ptr_x_lag_data_current->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_data_new = *ptr_x_lag_data_new->getLocalFormVecArray();\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            double X_com_current[NDIM] = { 0.0 }, X_com_new[NDIM] = { 0.0 };\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const IBTK::Vector& displacement = node_idx->getPeriodicDisplacement();\n                    const double* const X_current = &X_data_current[local_idx][0];\n                    const double* const X_new = &X_data_new[local_idx][0];\n                    for (unsigned int d = 0; d < NDIM; ++d)\n                    {\n                        X_com_current[d] += X_current[d] + displacement[d];\n                        X_com_new[d] += X_new[d] + displacement[d];\n                    }\n                    if (lag_idx == d_tagged_pt_lag_idx[location_struct_handle])\n                    {\n                        for (unsigned int d = 0; d < NDIM; ++d) tagged_position[location_struct_handle][d] = X_new[d];\n                    }\n                }\n            }\n            for (int d = 0; d < NDIM; ++d)\n            {\n                d_center_of_mass_unshifted_current[location_struct_handle][d] += X_com_current[d];\n                d_center_of_mass_unshifted_new[location_struct_handle][d] += X_com_new[d];\n            }\n        }\n        ptr_x_lag_data_current->restoreArrays();\n        ptr_x_lag_data_new->restoreArrays();\n    }\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        const StructureParameters& struct_param = d_ib_kinematics[struct_no]->getStructureParameters();\n        const int total_nodes = struct_param.getTotalNodes();\n\n        IBTK_MPI::sumReduction(d_center_of_mass_unshifted_current[struct_no].data(),\n                               d_center_of_mass_unshifted_current[struct_no].size());\n        IBTK_MPI::sumReduction(d_center_of_mass_unshifted_new[struct_no].data(),\n                               d_center_of_mass_unshifted_new[struct_no].size());\n\n        for (int i = 0; i < 3; ++i)\n        {\n            d_center_of_mass_unshifted_current[struct_no][i] /= total_nodes;\n            d_center_of_mass_unshifted_new[struct_no][i] /= total_nodes;\n\n            d_center_of_mass_current[struct_no][i] = d_center_of_mass_unshifted_current[struct_no][i];\n            d_center_of_mass_new[struct_no][i] = d_center_of_mass_unshifted_new[struct_no][i];\n        }\n    }\n\n    // now apply displacement\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        for (unsigned int i = 0; i < NDIM; ++i)\n        {\n            if (periodic_shift[i])\n            {\n                while (d_center_of_mass_current[struct_no][i] < domain_x_lower[i])\n                {\n                    d_center_of_mass_current[struct_no][i] += domain_length[i];\n                }\n                while (d_center_of_mass_current[struct_no][i] >= domain_x_upper[i])\n                {\n                    d_center_of_mass_current[struct_no][i] -= domain_length[i];\n                }\n\n                while (d_center_of_mass_new[struct_no][i] < domain_x_lower[i])\n                {\n                    d_center_of_mass_new[struct_no][i] += domain_length[i];\n                }\n                while (d_center_of_mass_new[struct_no][i] >= domain_x_upper[i])\n                {\n                    d_center_of_mass_new[struct_no][i] -= domain_length[i];\n                }\n            }\n        }\n    }\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        IBTK_MPI::sumReduction(&tagged_position[struct_no][0], 3);\n        d_tagged_pt_position[struct_no] = tagged_position[struct_no];\n    }\n\n    // Zero out the moment of inertia tensor.\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        d_moment_of_inertia_current[struct_no].setZero();\n        d_moment_of_inertia_new[struct_no].setZero();\n    }\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        // Get LData corresponding to the present position of the structures.\n        Pointer<LData> ptr_x_lag_data_current, ptr_x_lag_data_new;\n        ptr_x_lag_data_current = d_l_data_manager->getLData(\"X\", ln);\n        if (IBTK::abs_equal_eps(d_FuRMoRP_current_time, 0.0))\n        {\n            ptr_x_lag_data_new = d_l_data_manager->getLData(\"X\", ln);\n        }\n        else\n        {\n            ptr_x_lag_data_new = d_l_data_X_half_Euler[ln];\n        }\n\n        const boost::multi_array_ref<double, 2>& X_data_current = *ptr_x_lag_data_current->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_data_new = *ptr_x_lag_data_new->getLocalFormVecArray();\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n            if (!struct_param.getStructureIsSelfRotating()) continue;\n\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n            const std::vector<double>& X_com_current = d_center_of_mass_unshifted_current[location_struct_handle];\n            const std::vector<double>& X_com_new = d_center_of_mass_unshifted_new[location_struct_handle];\n\n            Eigen::Matrix3d Inertia_current(3, 3), Inertia_new(3, 3);\n            Inertia_current.setZero();\n            Inertia_new.setZero();\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const IBTK::Vector& displacement = node_idx->getPeriodicDisplacement();\n                    const double* const X_current = &X_data_current[local_idx][0];\n                    const double* const X_new = &X_data_new[local_idx][0];\n#if (NDIM == 2)\n                    Inertia_current(0, 0) += std::pow(displacement[1] + X_current[1] - X_com_current[1], 2);\n                    Inertia_current(0, 1) += -(displacement[0] + X_current[0] - X_com_current[0]) *\n                                             (displacement[1] + X_current[1] - X_com_current[1]);\n                    Inertia_current(1, 1) += std::pow(displacement[0] + X_current[0] - X_com_current[0], 2);\n                    Inertia_current(2, 2) += std::pow(displacement[0] + X_current[0] - X_com_current[0], 2) +\n                                             std::pow(displacement[1] + X_current[1] - X_com_current[1], 2);\n\n                    Inertia_new(0, 0) += std::pow(displacement[1] + X_new[1] - X_com_new[1], 2);\n                    Inertia_new(0, 1) +=\n                        -(displacement[0] + X_new[0] - X_com_new[0]) * (displacement[1] + X_new[1] - X_com_new[1]);\n                    Inertia_new(1, 1) += std::pow(displacement[0] + X_new[0] - X_com_new[0], 2);\n                    Inertia_new(2, 2) += std::pow(displacement[0] + X_new[0] - X_com_new[0], 2) +\n                                         std::pow(displacement[1] + X_new[1] - X_com_new[1], 2);\n#endif\n\n#if (NDIM == 3)\n                    Inertia_current(0, 0) += std::pow(displacement[1] + X_current[1] - X_com_current[1], 2) +\n                                             std::pow(displacement[2] + X_current[2] - X_com_current[2], 2);\n                    Inertia_current(0, 1) += -(displacement[0] + X_current[0] - X_com_current[0]) *\n                                             (displacement[1] + X_current[1] - X_com_current[1]);\n                    Inertia_current(0, 2) += -(displacement[0] + X_current[0] - X_com_current[0]) *\n                                             (displacement[2] + X_current[2] - X_com_current[2]);\n                    Inertia_current(1, 1) += std::pow(displacement[0] + X_current[0] - X_com_current[0], 2) +\n                                             std::pow(displacement[2] + X_current[2] - X_com_current[2], 2);\n                    Inertia_current(1, 2) += -(displacement[1] + X_current[1] - X_com_current[1]) *\n                                             (displacement[2] + X_current[2] - X_com_current[2]);\n                    Inertia_current(2, 2) += std::pow(displacement[0] + X_current[0] - X_com_current[0], 2) +\n                                             std::pow(displacement[1] + X_current[1] - X_com_current[1], 2);\n\n                    Inertia_new(0, 0) += std::pow(displacement[1] + X_new[1] - X_com_new[1], 2) +\n                                         std::pow(displacement[2] + X_new[2] - X_com_new[2], 2);\n                    Inertia_new(0, 1) +=\n                        -(displacement[0] + X_new[0] - X_com_new[0]) * (displacement[1] + X_new[1] - X_com_new[1]);\n                    Inertia_new(0, 2) +=\n                        -(displacement[0] + X_new[0] - X_com_new[0]) * (displacement[2] + X_new[2] - X_com_new[2]);\n                    Inertia_new(1, 1) += std::pow(displacement[0] + X_new[0] - X_com_new[0], 2) +\n                                         std::pow(displacement[2] + X_new[2] - X_com_new[2], 2);\n                    Inertia_new(1, 2) +=\n                        -(displacement[1] + X_new[1] - X_com_new[1]) * (displacement[2] + X_new[2] - X_com_new[2]);\n                    Inertia_new(2, 2) += std::pow(displacement[0] + X_new[0] - X_com_new[0], 2) +\n                                         std::pow(displacement[1] + X_new[1] - X_com_new[1], 2);\n#endif\n                }\n            }\n            d_moment_of_inertia_current[location_struct_handle] += Inertia_current;\n            d_moment_of_inertia_new[location_struct_handle] += Inertia_new;\n        } // all structs\n        ptr_x_lag_data_current->restoreArrays();\n        ptr_x_lag_data_new->restoreArrays();\n    } // all levels\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        const StructureParameters& struct_param = d_ib_kinematics[struct_no]->getStructureParameters();\n        if (struct_param.getStructureIsSelfRotating())\n        {\n            IBTK_MPI::sumReduction(&d_moment_of_inertia_current[struct_no](0, 0), 9);\n            IBTK_MPI::sumReduction(&d_moment_of_inertia_new[struct_no](0, 0), 9);\n        }\n    }\n\n    // Fill-in symmetric part of inertia tensor.\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        d_moment_of_inertia_current[struct_no](1, 0) = d_moment_of_inertia_current[struct_no](0, 1);\n        d_moment_of_inertia_current[struct_no](2, 0) = d_moment_of_inertia_current[struct_no](0, 2);\n        d_moment_of_inertia_current[struct_no](2, 1) = d_moment_of_inertia_current[struct_no](1, 2);\n\n        d_moment_of_inertia_new[struct_no](1, 0) = d_moment_of_inertia_new[struct_no](0, 1);\n        d_moment_of_inertia_new[struct_no](2, 0) = d_moment_of_inertia_new[struct_no](0, 2);\n        d_moment_of_inertia_new[struct_no](2, 1) = d_moment_of_inertia_new[struct_no](1, 2);\n    }\n\n    // write the COM and MOI to the output file\n    if (!IBTK_MPI::getRank() && d_print_output && d_output_COM_coordinates &&\n        (d_timestep_counter % d_output_interval) == 0 && !IBTK::abs_equal_eps(d_FuRMoRP_current_time, 0.0))\n    {\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            *d_position_COM_stream[struct_no]\n                << d_FuRMoRP_current_time << '\\t' << d_center_of_mass_current[struct_no][0] << '\\t'\n                << d_center_of_mass_current[struct_no][1] << '\\t' << d_center_of_mass_current[struct_no][2]\n                << std::endl;\n        }\n    }\n\n    if (!IBTK_MPI::getRank() && d_print_output && d_output_MOI && (d_timestep_counter % d_output_interval) == 0 &&\n        !IBTK::abs_equal_eps(d_FuRMoRP_current_time, 0.0))\n    {\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            *d_moment_of_inertia_stream[struct_no]\n                << d_FuRMoRP_current_time << '\\t' << d_moment_of_inertia_current[struct_no](0, 0) << '\\t'\n                << d_moment_of_inertia_current[struct_no](0, 1) << '\\t' << d_moment_of_inertia_current[struct_no](0, 2)\n                << '\\t' << d_moment_of_inertia_current[struct_no](1, 0) << '\\t'\n                << d_moment_of_inertia_current[struct_no](1, 1) << '\\t' << d_moment_of_inertia_current[struct_no](1, 2)\n                << '\\t' << d_moment_of_inertia_current[struct_no](2, 0) << '\\t'\n                << d_moment_of_inertia_current[struct_no](2, 1) << '\\t' << d_moment_of_inertia_current[struct_no](2, 2)\n                << std::endl;\n        }\n    }\n\n    return;\n} // calculateCOMandMOIOfStructures\n\nvoid\nConstraintIBMethod::calculateKinematicsVelocity()\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    const double dt = d_FuRMoRP_new_time - d_FuRMoRP_current_time;\n    // Theta_new = Theta_old + Omega_old*dt\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        const StructureParameters& struct_param = d_ib_kinematics[struct_no]->getStructureParameters();\n\n        for (int d = 0; d < 3; ++d)\n            d_incremented_angle_from_reference_axis[struct_no][d] +=\n                (d_rigid_rot_vel_current[struct_no][d] - d_omega_com_def_current[struct_no][d]) * dt;\n\n        d_ib_kinematics[struct_no]->setKinematicsVelocity(d_FuRMoRP_new_time,\n                                                          d_incremented_angle_from_reference_axis[struct_no],\n                                                          d_center_of_mass_new[struct_no],\n                                                          d_tagged_pt_position[struct_no]);\n\n        d_ib_kinematics[struct_no]->setShape(d_FuRMoRP_new_time, d_incremented_angle_from_reference_axis[struct_no]);\n\n        if (struct_param.getStructureIsSelfTranslating()) calculateMomentumOfKinematicsVelocity(struct_no);\n    }\n\n    return;\n} // calculateKinematicsVelocity\n\nvoid\nConstraintIBMethod::calculateMomentumOfKinematicsVelocity(const int position_handle)\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    Pointer<ConstraintIBKinematics> ptr_ib_kinematics = d_ib_kinematics[position_handle];\n    const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n    tbox::Array<int> calculate_trans_mom = struct_param.getCalculateTranslationalMomentum();\n    tbox::Array<int> calculate_rot_mom = struct_param.getCalculateRotationalMomentum();\n    const int coarsest_ln = struct_param.getCoarsestLevelNumber();\n    const int finest_ln = struct_param.getFinestLevelNumber();\n    const std::vector<std::pair<int, int> >& range = struct_param.getLagIdxRange();\n    const int total_nodes = struct_param.getTotalNodes();\n\n    // Zero out linear momentum of kinematics velocity of the structure.\n    for (int d = 0; d < 3; ++d) d_vel_com_def_new[position_handle][d] = 0.0;\n\n    // Calculate linear momentum\n    for (int ln = coarsest_ln, itr = 0; ln <= finest_ln && static_cast<unsigned int>(itr) < range.size(); ++ln, ++itr)\n    {\n#if !defined(NDEBUG)\n        TBOX_ASSERT(d_l_data_manager->levelContainsLagrangianData(ln));\n#endif\n\n        std::pair<int, int> lag_idx_range = range[itr];\n        const int offset = lag_idx_range.first;\n        double U_com_def[NDIM] = { 0.0 };\n\n        // Get LMesh corresponding to the present position of the structures\n        // on this level.\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n        const std::vector<std::vector<double> >& def_vel = ptr_ib_kinematics->getKinematicsVelocity(ln);\n\n        for (const auto& node_idx : local_nodes)\n        {\n            const int lag_idx = node_idx->getLagrangianIndex();\n            if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n            {\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    U_com_def[d] += def_vel[d][lag_idx - offset];\n                }\n            }\n        }\n        for (int d = 0; d < NDIM; ++d)\n        {\n            d_vel_com_def_new[position_handle][d] += U_com_def[d];\n        }\n    }\n    IBTK_MPI::sumReduction(d_vel_com_def_new[position_handle].data(), d_vel_com_def_new[position_handle].size());\n\n    for (int d = 0; d < 3; ++d)\n    {\n        if (calculate_trans_mom[d])\n            d_vel_com_def_new[position_handle][d] /= total_nodes;\n        else\n            d_vel_com_def_new[position_handle][d] = 0.0;\n    }\n\n    // Calculate angular momentum.\n    if (struct_param.getStructureIsSelfRotating())\n    {\n        // Zero out angular momentum of kinematics velocity of the structure.\n        for (int d = 0; d < 3; ++d) d_omega_com_def_new[position_handle][d] = 0.0;\n\n        for (int ln = coarsest_ln, itr = 0; ln <= finest_ln && static_cast<unsigned int>(itr) < range.size();\n             ++ln, ++itr)\n        {\n#if !defined(NDEBUG)\n            TBOX_ASSERT(d_l_data_manager->levelContainsLagrangianData(ln));\n#endif\n\n            std::pair<int, int> lag_idx_range = range[itr];\n            const int offset = lag_idx_range.first;\n            double R_cross_U_def[3] = { 0.0 };\n\n            // Get LData corresponding to the present position of the structures.\n            Pointer<LData> ptr_x_lag_data;\n            if (IBTK::abs_equal_eps(d_FuRMoRP_current_time, 0.0))\n            {\n                ptr_x_lag_data = d_l_data_manager->getLData(\"X\", ln);\n            }\n            else\n            {\n                ptr_x_lag_data = d_l_data_X_half_Euler[ln];\n            }\n\n            const boost::multi_array_ref<double, 2>& X_data = *ptr_x_lag_data->getLocalFormVecArray();\n            const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n            const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n            const std::vector<std::vector<double> >& def_vel = ptr_ib_kinematics->getKinematicsVelocity(ln);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const double* const X = &X_data[local_idx][0];\n                    const IBTK::Vector& displacement = node_idx->getPeriodicDisplacement();\n#if (NDIM == 2)\n                    double x = displacement[0] + X[0] - d_center_of_mass_unshifted_new[position_handle][0];\n                    double y = displacement[1] + X[1] - d_center_of_mass_unshifted_new[position_handle][1];\n                    R_cross_U_def[2] += (x * (def_vel[1][lag_idx - offset]) - y * (def_vel[0][lag_idx - offset]));\n\n#endif\n\n#if (NDIM == 3)\n                    double x = displacement[0] + X[0] - d_center_of_mass_unshifted_new[position_handle][0];\n                    double y = displacement[1] + X[1] - d_center_of_mass_unshifted_new[position_handle][1];\n                    double z = displacement[2] + X[2] - d_center_of_mass_unshifted_new[position_handle][2];\n\n                    R_cross_U_def[0] += (y * (def_vel[2][lag_idx - offset]) - z * (def_vel[1][lag_idx - offset]));\n\n                    R_cross_U_def[1] += (-x * (def_vel[2][lag_idx - offset]) + z * (def_vel[0][lag_idx - offset]));\n\n                    R_cross_U_def[2] += (x * (def_vel[1][lag_idx - offset]) - y * (def_vel[0][lag_idx - offset]));\n#endif\n                }\n            }\n            for (int d = 0; d < 3; ++d)\n            {\n                d_omega_com_def_new[position_handle][d] += R_cross_U_def[d];\n            }\n            ptr_x_lag_data->restoreArrays();\n        } // all levels\n        IBTK_MPI::sumReduction(&d_omega_com_def_new[position_handle][0], 3);\n\n// Find angular velocity of deformational velocity.\n#if (NDIM == 2)\n        d_omega_com_def_new[position_handle][2] /= d_moment_of_inertia_new[position_handle](2, 2);\n#endif\n\n#if (NDIM == 3)\n        solveSystemOfEqns(d_omega_com_def_new[position_handle], d_moment_of_inertia_new[position_handle]);\n        for (int d = 0; d < 3; ++d)\n            if (!calculate_rot_mom[d]) d_omega_com_def_new[position_handle][d] = 0.0;\n#endif\n    } // if struct is rotating\n\n    return;\n} // calculateMomentumOfKinematicsVelocity\n\nvoid\nConstraintIBMethod::calculateVolumeElement()\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n\n    // Initialize variables and variable contexts associated with Eulerian\n    // tracking of the Lagrangian points.\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    const IntVector<NDIM> cell_ghosts = 0;\n    Pointer<CellVariable<NDIM, int> > vol_cc_var = new CellVariable<NDIM, int>(d_object_name + \"::vol_cc_var\");\n    const int vol_cc_scratch_idx = var_db->registerVariableAndContext(vol_cc_var, d_scratch_context, cell_ghosts);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n        level->allocatePatchData(vol_cc_scratch_idx, 0.0);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            Pointer<CellData<NDIM, int> > vol_cc_scratch_idx_data = patch->getPatchData(vol_cc_scratch_idx);\n            vol_cc_scratch_idx_data->fill(0, 0);\n        }\n    }\n\n    const int lag_node_index_idx = d_l_data_manager->getLNodePatchDescriptorIndex();\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        // Get LData corresponding to the present position of the structures.\n        const boost::multi_array_ref<double, 2>& X_data = *d_l_data_manager->getLData(\"X\", ln)->getLocalFormVecArray();\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            // If the volume element has already been set, then skip the volume\n            // computation\n            if (d_vol_element_is_set[struct_no])\n            {\n                tbox::plog << \"Skipping volume element computation for structure no. \" << struct_no << std::endl;\n                tbox::pout << \"Skipping volume element computation for structure no. \" << struct_no << std::endl;\n                continue;\n            }\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n            {\n                Pointer<Patch<NDIM> > patch = level->getPatch(p());\n                Pointer<CellData<NDIM, int> > vol_cc_scratch_idx_data = patch->getPatchData(vol_cc_scratch_idx);\n                Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n                Pointer<CartesianGridGeometry<NDIM> > ggeom = level->getGridGeometry();\n                const IntVector<NDIM>& ratio = level->getRatio();\n                const double* const dx = pgeom->getDx();\n                const Box<NDIM>& patch_box = patch->getBox();\n#if (NDIM == 2)\n                const double patch_cell_vol = dx[0] * dx[1];\n#endif\n\n#if (NDIM == 3)\n                const double patch_cell_vol = dx[0] * dx[1] * dx[2];\n#endif\n                const Pointer<LNodeSetData> lag_node_index_data = patch->getPatchData(lag_node_index_idx);\n                for (LNodeSetData::DataIterator it = lag_node_index_data->data_begin(patch_box);\n                     it != lag_node_index_data->data_end();\n                     ++it)\n                {\n                    LNode* const node_idx = *it;\n                    const int lag_idx = node_idx->getLagrangianIndex();\n                    if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                    {\n                        const int local_idx = node_idx->getLocalPETScIndex();\n                        const double* const X = &X_data[local_idx][0];\n                        const CellIndex<NDIM> Lag2Eul_cellindex = IndexUtilities::getCellIndex(X, ggeom, ratio);\n\n                        (*vol_cc_scratch_idx_data)(Lag2Eul_cellindex)++;\n                    }\n                } // on a patch\n\n                for (CellData<NDIM, int>::Iterator it(patch_box); it; it++)\n                {\n                    if ((*vol_cc_scratch_idx_data)(*it)) d_structure_vol[location_struct_handle] += patch_cell_vol;\n\n                } // on the same patch\n                vol_cc_scratch_idx_data->fill(0, patch_box, 0);\n\n            } // all patches\n        }     // all structs\n        d_l_data_manager->getLData(\"X\", ln)->restoreArrays();\n    } // all levels\n    IBTK_MPI::sumReduction(&d_structure_vol[0], d_no_structures);\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        Pointer<ConstraintIBKinematics> ptr_ib_kinematics = d_ib_kinematics[struct_no];\n        const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n\n        // If the volume element has already been set, then no need to compute it\n        if (d_vol_element_is_set[struct_no])\n        {\n            d_structure_vol[struct_no] = struct_param.getTotalNodes() * d_vol_element[struct_no];\n        }\n        else\n        {\n            d_vol_element[struct_no] = d_structure_vol[struct_no] / struct_param.getTotalNodes();\n            d_vol_element_is_set[struct_no] = true;\n        }\n\n        tbox::plog << \" ++++++++++++++++ \"\n                   << \" STRUCTURE NO. \" << struct_no << \"  ++++++++++++++++++++++++++ \\n\\n\\n\"\n                   << \" VOLUME OF THE MATERIAL ELEMENT           = \" << d_vol_element[struct_no] << \"\\n\"\n                   << \" VOLUME OF THE STRUCTURE                  = \" << d_structure_vol[struct_no] << \"\\n\"\n                   << \" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"\n                      \"+++++++\\n\"\n                   << std::endl;\n\n        tbox::pout << \" ++++++++++++++++ \"\n                   << \" STRUCTURE NO. \" << struct_no << \"  ++++++++++++++++++++++++++ \\n\\n\\n\"\n                   << \" VOLUME OF THE MATERIAL ELEMENT           = \" << d_vol_element[struct_no] << \"\\n\"\n                   << \" VOLUME OF THE STRUCTURE                  = \" << d_structure_vol[struct_no] << \"\\n\"\n                   << \" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"\n                      \"+++++++\\n\"\n                   << std::endl;\n    }\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n        if (level->checkAllocated(vol_cc_scratch_idx)) level->deallocatePatchData(vol_cc_scratch_idx);\n    }\n    var_db->removePatchDataIndex(vol_cc_scratch_idx);\n\n    return;\n\n} // calculateVolumeElement\n\nvoid\nConstraintIBMethod::calculateRigidTranslationalMomentum()\n{\n    // Zero out new rigid momentum.\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        for (int d = 0; d < 3; ++d) d_rigid_trans_vel_new[struct_no][d] = 0.0;\n    }\n\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Calculate rigid translational velocity.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        // Get LData corresponding to the present position of the structures.\n        const boost::multi_array_ref<double, 2>& U_interp_data = *d_l_data_U_interp[ln]->getLocalFormVecArray();\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n            if (!struct_param.getStructureIsSelfTranslating()) continue;\n\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            double U_rigid[NDIM] = { 0.0 };\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const double* const U = &U_interp_data[local_idx][0];\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        U_rigid[d] += U[d];\n                    }\n                }\n            }\n            for (int d = 0; d < NDIM; ++d) d_rigid_trans_vel_new[location_struct_handle][d] += U_rigid[d];\n        } // all structs\n        d_l_data_U_interp[ln]->restoreArrays();\n    } // all levels\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        const StructureParameters& struct_param = d_ib_kinematics[struct_no]->getStructureParameters();\n        if (struct_param.getStructureIsSelfTranslating())\n        {\n            IBTK_MPI::sumReduction(d_rigid_trans_vel_new[struct_no].data(), d_rigid_trans_vel_new[struct_no].size());\n            tbox::Array<int> calculate_trans_mom = struct_param.getCalculateTranslationalMomentum();\n            for (int d = 0; d < NDIM; ++d)\n            {\n                if (calculate_trans_mom[d])\n                    d_rigid_trans_vel_new[struct_no][d] /= struct_param.getTotalNodes();\n                else\n                    d_rigid_trans_vel_new[struct_no][d] = 0.0;\n            }\n        }\n    }\n\n    if (!IBTK_MPI::getRank() && d_print_output && d_output_trans_vel && (d_timestep_counter % d_output_interval) == 0)\n    {\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            *d_trans_vel_stream[struct_no]\n                << d_FuRMoRP_new_time << '\\t' << d_rigid_trans_vel_new[struct_no][0] << '\\t'\n                << d_rigid_trans_vel_new[struct_no][1] << '\\t' << d_rigid_trans_vel_new[struct_no][2] << '\\t'\n                << d_vel_com_def_new[struct_no][0] << '\\t' << d_vel_com_def_new[struct_no][1] << '\\t'\n                << d_vel_com_def_new[struct_no][2] << std::endl;\n        }\n    }\n\n    return;\n\n} // calculateRigidTranslationalMomentum\n\nvoid\nConstraintIBMethod::calculateRigidRotationalMomentum()\n{\n    // Zero out new rigid momentum.\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        for (int d = 0; d < 3; ++d) d_rigid_rot_vel_new[struct_no][d] = 0.0;\n    }\n\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Calculate rigid rotational velocity.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        // Get ponter to LData.\n        const boost::multi_array_ref<double, 2>& U_interp_data = *d_l_data_U_interp[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_data = *d_l_data_X_half_Euler[ln]->getLocalFormVecArray();\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n            if (!struct_param.getStructureIsSelfRotating()) continue;\n\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            double Omega_rigid[3] = { 0.0 };\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const IBTK::Vector& displacement = node_idx->getPeriodicDisplacement();\n                    const double* const U = &U_interp_data[local_idx][0];\n                    const double* const X = &X_data[local_idx][0];\n#if (NDIM == 2)\n                    const double x = displacement[0] + X[0] - d_center_of_mass_unshifted_new[location_struct_handle][0];\n                    const double y = displacement[1] + X[1] - d_center_of_mass_unshifted_new[location_struct_handle][1];\n                    Omega_rigid[2] += x * U[1] - y * U[0];\n#endif\n\n#if (NDIM == 3)\n                    const double x = displacement[0] + X[0] - d_center_of_mass_unshifted_new[location_struct_handle][0];\n                    const double y = displacement[1] + X[1] - d_center_of_mass_unshifted_new[location_struct_handle][1];\n                    const double z = displacement[2] + X[2] - d_center_of_mass_unshifted_new[location_struct_handle][2];\n                    Omega_rigid[0] += y * U[2] - z * U[1];\n                    Omega_rigid[1] += -x * U[2] + z * U[0];\n                    Omega_rigid[2] += x * U[1] - y * U[0];\n#endif\n                }\n            }\n            for (int d = 0; d < 3; ++d) d_rigid_rot_vel_new[location_struct_handle][d] += Omega_rigid[d];\n        } // all structs\n        d_l_data_U_interp[ln]->restoreArrays();\n        d_l_data_X_half_Euler[ln]->restoreArrays();\n    } // all levels\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        const StructureParameters& struct_param = d_ib_kinematics[struct_no]->getStructureParameters();\n        if (struct_param.getStructureIsSelfRotating())\n        {\n            IBTK_MPI::sumReduction(&d_rigid_rot_vel_new[struct_no][0], 3);\n#if (NDIM == 2)\n            d_rigid_rot_vel_new[struct_no][2] /= d_moment_of_inertia_new[struct_no](2, 2);\n#endif\n\n#if (NDIM == 3)\n            solveSystemOfEqns(d_rigid_rot_vel_new[struct_no], d_moment_of_inertia_new[struct_no]);\n            tbox::Array<int> calculate_rot_mom = struct_param.getCalculateRotationalMomentum();\n            for (int d = 0; d < NDIM; ++d)\n            {\n                if (!calculate_rot_mom[d]) d_rigid_rot_vel_new[struct_no][d] = 0.0;\n            }\n#endif\n        }\n    }\n\n    if (!IBTK_MPI::getRank() && d_print_output && d_output_rot_vel && (d_timestep_counter % d_output_interval) == 0)\n    {\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            *d_rot_vel_stream[struct_no] << d_FuRMoRP_new_time << '\\t' << d_rigid_rot_vel_new[struct_no][0] << '\\t'\n                                         << d_rigid_rot_vel_new[struct_no][1] << '\\t'\n                                         << d_rigid_rot_vel_new[struct_no][2] << '\\t'\n                                         << d_omega_com_def_new[struct_no][0] << '\\t'\n                                         << d_omega_com_def_new[struct_no][1] << '\\t'\n                                         << d_omega_com_def_new[struct_no][2] << std::endl;\n        }\n    }\n\n    return;\n\n} // calculateRigidRotationalMomentum\n\nvoid\nConstraintIBMethod::calculateCurrentLagrangianVelocity()\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    std::vector<double> WxR(3, 0.0), R(3, 0.0);\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        // Get pointer to LData.\n        boost::multi_array_ref<double, 2>& U_current_data = *d_l_data_U_current[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_data = *d_l_data_manager->getLData(\"X\", ln)->getLocalFormVecArray();\n\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            const int offset = lag_idx_range.first;\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n            const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n            const std::vector<std::vector<double> >& current_vel = ptr_ib_kinematics->getKinematicsVelocity(ln);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    double* const U_current = &U_current_data[local_idx][0];\n                    const double* const X = &X_data[local_idx][0];\n\n                    // Imposed velocity\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        U_current[d] = current_vel[d][lag_idx - offset];\n                    }\n\n                    // Translational velocity\n                    if (struct_param.getStructureIsSelfTranslating())\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            U_current[d] += d_rigid_trans_vel_current[location_struct_handle][d] -\n                                            d_vel_com_def_current[location_struct_handle][d];\n                        }\n                    }\n\n                    // Rotational velocity\n                    const IBTK::Vector& displacement = node_idx->getPeriodicDisplacement();\n                    if (struct_param.getStructureIsSelfRotating())\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            R[d] =\n                                displacement[d] + X[d] - d_center_of_mass_unshifted_current[location_struct_handle][d];\n                        }\n\n                        WxR[0] = R[2] * (d_rigid_rot_vel_current[location_struct_handle][1] -\n                                         d_omega_com_def_current[location_struct_handle][1]) -\n                                 R[1] * (d_rigid_rot_vel_current[location_struct_handle][2] -\n                                         d_omega_com_def_current[location_struct_handle][2]);\n\n                        WxR[1] = -R[2] * (d_rigid_rot_vel_current[location_struct_handle][0] -\n                                          d_omega_com_def_current[location_struct_handle][0]) +\n                                 R[0] * (d_rigid_rot_vel_current[location_struct_handle][2] -\n                                         d_omega_com_def_current[location_struct_handle][2]);\n\n                        WxR[2] = R[1] * (d_rigid_rot_vel_current[location_struct_handle][0] -\n                                         d_omega_com_def_current[location_struct_handle][0]) -\n                                 R[0] * (d_rigid_rot_vel_current[location_struct_handle][1] -\n                                         d_omega_com_def_current[location_struct_handle][1]);\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            U_current[d] += WxR[d];\n                        }\n                    }\n\n                } // choose a struct\n            }     // all nodes on a level\n        }         // all structs\n        d_l_data_U_current[ln]->restoreArrays();\n        d_l_data_manager->getLData(\"X\", ln)->restoreArrays();\n    } // all levels\n\n    return;\n\n} // calculateCurrentLagrangianVelocity\n\nvoid\nConstraintIBMethod::correctVelocityOnLagrangianMesh()\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    std::vector<double> WxR(3, 0.0), R(3, 0.0);\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        // Get pointer to LData.\n        const boost::multi_array_ref<double, 2>& U_interp_data = *d_l_data_U_interp[ln]->getLocalFormVecArray();\n        boost::multi_array_ref<double, 2>& U_corr_data = *d_l_data_U_correction[ln]->getLocalFormVecArray();\n        boost::multi_array_ref<double, 2>& U_new_data = *d_l_data_U_new[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_data = *d_l_data_X_half_Euler[ln]->getLocalFormVecArray();\n\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            const int offset = lag_idx_range.first;\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n            const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n            const std::vector<std::vector<double> >& new_vel = ptr_ib_kinematics->getKinematicsVelocity(ln);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const double* const U = &U_interp_data[local_idx][0];\n                    double* const U_corr = &U_corr_data[local_idx][0];\n                    double* const U_new = &U_new_data[local_idx][0];\n                    const double* const X = &X_data[local_idx][0];\n\n                    // Imposed velocity\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        U_new[d] = new_vel[d][lag_idx - offset];\n                    }\n\n                    // Translational velocity\n                    if (struct_param.getStructureIsSelfTranslating())\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            U_new[d] += d_rigid_trans_vel_new[location_struct_handle][d] -\n                                        d_vel_com_def_new[location_struct_handle][d];\n                        }\n                    }\n\n                    // Rotational velocity\n                    const IBTK::Vector& displacement = node_idx->getPeriodicDisplacement();\n                    if (struct_param.getStructureIsSelfRotating())\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            R[d] = displacement[d] + X[d] - d_center_of_mass_unshifted_new[location_struct_handle][d];\n                        }\n                        WxR[0] = R[2] * (d_rigid_rot_vel_new[location_struct_handle][1] -\n                                         d_omega_com_def_new[location_struct_handle][1]) -\n                                 R[1] * (d_rigid_rot_vel_new[location_struct_handle][2] -\n                                         d_omega_com_def_new[location_struct_handle][2]);\n\n                        WxR[1] = -R[2] * (d_rigid_rot_vel_new[location_struct_handle][0] -\n                                          d_omega_com_def_new[location_struct_handle][0]) +\n                                 R[0] * (d_rigid_rot_vel_new[location_struct_handle][2] -\n                                         d_omega_com_def_new[location_struct_handle][2]);\n\n                        WxR[2] = R[1] * (d_rigid_rot_vel_new[location_struct_handle][0] -\n                                         d_omega_com_def_new[location_struct_handle][0]) -\n                                 R[0] * (d_rigid_rot_vel_new[location_struct_handle][1] -\n                                         d_omega_com_def_new[location_struct_handle][1]);\n\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            U_new[d] += WxR[d];\n                        }\n                    }\n\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        U_corr[d] = (U_new[d] - U[d]) * d_vol_element[location_struct_handle];\n                    }\n\n                } // choose a struct\n            }     // all nodes on a level\n        }         // all structs\n        d_l_data_U_interp[ln]->restoreArrays();\n        d_l_data_U_correction[ln]->restoreArrays();\n        d_l_data_U_new[ln]->restoreArrays();\n        d_l_data_X_half_Euler[ln]->restoreArrays();\n    } // all levels\n\n    return;\n\n} // correctVelocityOnLagrangianMesh\n\nvoid\nConstraintIBMethod::applyProjection()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Allocate temporary data.\n    ComponentSelector scratch_idxs;\n    scratch_idxs.setFlag(d_phi_idx);\n    scratch_idxs.setFlag(d_Div_u_scratch_idx);\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n        level->allocatePatchData(scratch_idxs, d_FuRMoRP_new_time);\n    }\n\n    // Compute div U before applying the projection operator.\n    const bool U_current_cf_bdry_synch = true;\n    getHierarchyMathOps()->div(d_Div_u_scratch_idx,\n                               d_Div_u_var, // dst\n                               +1.0,        // alpha\n                               d_u_fluidSolve_idx,\n                               Pointer<SideVariable<NDIM, double> >(d_u_fluidSolve_var), // src\n                               d_no_fill_op,                                             // src_bdry_fill\n                               d_FuRMoRP_new_time,                                       // src_bdry_fill_time\n                               U_current_cf_bdry_synch);                                 // src_cf_bdry_synch\n\n    if (d_do_log)\n    {\n        const double Div_u_norm_1 = d_hier_cc_data_ops->L1Norm(d_Div_u_scratch_idx, d_wgt_cc_idx);\n        const double Div_u_norm_2 = d_hier_cc_data_ops->L2Norm(d_Div_u_scratch_idx, d_wgt_cc_idx);\n        const double Div_u_norm_oo = d_hier_cc_data_ops->maxNorm(d_Div_u_scratch_idx, d_wgt_cc_idx);\n        tbox::plog << d_object_name << \"::applyProjection():\\n\"\n                   << \"  performing velocity correction projection\\n\"\n                   << \"  before projection:\\n\"\n                   << \"    ||Div U||_1  = \" << Div_u_norm_1 << \"\\n\"\n                   << \"    ||Div U||_2  = \" << Div_u_norm_2 << \"\\n\"\n                   << \"    ||Div U||_oo = \" << Div_u_norm_oo << \"\\n\";\n    }\n\n    // Setup the solver vectors.\n    d_hier_cc_data_ops->setToScalar(d_phi_idx, 0.0, false);\n    d_hier_cc_data_ops->scale(d_Div_u_scratch_idx, -1.0, d_Div_u_scratch_idx);\n    const double Div_u_mean = (1.0 / d_volume) * d_hier_cc_data_ops->integral(d_Div_u_scratch_idx, d_wgt_cc_idx);\n    d_hier_cc_data_ops->addScalar(d_Div_u_scratch_idx, d_Div_u_scratch_idx, -Div_u_mean);\n\n    SAMRAIVectorReal<NDIM, double> sol_vec(d_object_name + \"::sol_vec\", d_hierarchy, coarsest_ln, finest_ln);\n    sol_vec.addComponent(d_phi_var, d_phi_idx, d_wgt_cc_idx, d_hier_cc_data_ops);\n\n    SAMRAIVectorReal<NDIM, double> rhs_vec(d_object_name + \"::rhs_vec\", d_hierarchy, coarsest_ln, finest_ln);\n    rhs_vec.addComponent(d_Div_u_var, d_Div_u_scratch_idx, d_wgt_cc_idx, d_hier_cc_data_ops);\n\n    // Setup the Poisson solver.\n    // Note that here, the delta t is absorbed in the phi term\n    d_velcorrection_projection_spec->setCZero();\n    if (!d_rho_is_const)\n    {\n        // Copy rho from INS integrator and take reciprocal and scale\n        copyDensityVariable(d_rho_ins_idx, d_rho_scratch_idx);\n        d_hier_sc_data_ops->reciprocal(d_rho_scratch_idx, d_rho_scratch_idx);\n        d_hier_sc_data_ops->scale(d_rho_scratch_idx, -1.0, d_rho_scratch_idx);\n\n        // Synchronize the coefficient patch data\n        using SynchronizationTransactionComponent = SideDataSynchronization::SynchronizationTransactionComponent;\n        SynchronizationTransactionComponent coef_synch_transaction =\n            SynchronizationTransactionComponent(d_rho_scratch_idx, \"CONSERVATIVE_COARSEN\");\n        Pointer<SideDataSynchronization> side_synch_op = new SideDataSynchronization();\n        side_synch_op->initializeOperatorState(coef_synch_transaction, d_hierarchy);\n        side_synch_op->synchronizeData(d_FuRMoRP_new_time);\n        d_velcorrection_projection_spec->setDPatchDataId(d_rho_scratch_idx);\n    }\n    else\n    {\n        d_velcorrection_projection_spec->setDConstant(-1.0 / d_rho_fluid);\n    }\n\n    d_velcorrection_projection_op->setPoissonSpecifications(*d_velcorrection_projection_spec);\n    d_velcorrection_projection_op->setPhysicalBcCoef(&d_velcorrection_projection_bc_coef);\n    d_velcorrection_projection_op->setHomogeneousBc(true);\n    d_velcorrection_projection_op->setHierarchyMathOps(getHierarchyMathOps());\n\n    d_velcorrection_projection_fac_op->setPoissonSpecifications(*d_velcorrection_projection_spec);\n    d_velcorrection_projection_fac_op->setPhysicalBcCoef(&d_velcorrection_projection_bc_coef);\n\n    d_velcorrection_projection_solver->setInitialGuessNonzero(false);\n    d_velcorrection_projection_solver->setOperator(d_velcorrection_projection_op);\n\n    // NOTE: We always use homogeneous Neumann boundary conditions for the\n    // velocity correction projection Poisson solver.\n    d_velcorrection_projection_solver->setNullspace(true);\n\n    // Solve the projection Poisson problem.\n    d_velcorrection_projection_solver->initializeSolverState(sol_vec, rhs_vec);\n    d_velcorrection_projection_solver->solveSystem(sol_vec, rhs_vec);\n    d_velcorrection_projection_solver->deallocateSolverState();\n\n    // Setup the interpolation transaction information.\n    using InterpolationTransactionComponent = HierarchyGhostCellInterpolation::InterpolationTransactionComponent;\n    InterpolationTransactionComponent Phi_bc_component(\n        d_phi_idx, \"LINEAR_REFINE\", true, \"CUBIC_COARSEN\", \"LINEAR\", false, &d_velcorrection_projection_bc_coef);\n    Pointer<HierarchyGhostCellInterpolation> Phi_bdry_bc_fill_op = new HierarchyGhostCellInterpolation();\n    Phi_bdry_bc_fill_op->initializeOperatorState(Phi_bc_component, d_hierarchy);\n\n    // Fill the physical boundary conditions for Phi.\n    Phi_bdry_bc_fill_op->setHomogeneousBc(true);\n    Phi_bdry_bc_fill_op->fillData(d_FuRMoRP_new_time);\n\n    // Set U := U - 1/rho * grad Phi.\n    const bool U_scratch_cf_bdry_synch = true;\n    if (!d_rho_is_const)\n    {\n        getHierarchyMathOps()->grad(d_u_fluidSolve_idx,\n                                    Pointer<SideVariable<NDIM, double> >(d_u_var),\n                                    U_scratch_cf_bdry_synch,\n                                    d_rho_scratch_idx,\n                                    Pointer<SideVariable<NDIM, double> >(d_rho_var),\n                                    d_phi_idx,\n                                    d_phi_var,\n                                    d_no_fill_op,\n                                    d_FuRMoRP_new_time,\n                                    1.0,\n                                    d_u_fluidSolve_idx,\n                                    Pointer<SideVariable<NDIM, double> >(d_u_var));\n    }\n    else\n    {\n        getHierarchyMathOps()->grad(d_u_fluidSolve_idx,\n                                    Pointer<SideVariable<NDIM, double> >(d_u_var),\n                                    U_scratch_cf_bdry_synch,\n                                    -1.0 / d_rho_fluid,\n                                    d_phi_idx,\n                                    d_phi_var,\n                                    d_no_fill_op,\n                                    d_FuRMoRP_new_time,\n                                    1.0,\n                                    d_u_fluidSolve_idx,\n                                    Pointer<SideVariable<NDIM, double> >(d_u_var));\n    }\n\n    // Update pressure p = p + phi/dt\n    const Pointer<Variable<NDIM> > p_var = d_ib_solver->getPressureVariable();\n    const Pointer<VariableContext> p_ctx = d_ib_solver->getNewContext();\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    const int p_idx = var_db->mapVariableAndContextToIndex(p_var, p_ctx);\n    const double dt = d_FuRMoRP_new_time - d_FuRMoRP_current_time;\n    d_hier_cc_data_ops->axpy(p_idx, 1.0 / dt, d_phi_idx, p_idx);\n\n    // Compute div U after applying the projection operator\n    if (d_do_log)\n    {\n        // Compute div U before applying the projection operator.\n        const bool U_current_cf_bdry_synch = true;\n        getHierarchyMathOps()->div(d_Div_u_scratch_idx,\n                                   d_Div_u_var, // dst\n                                   +1.0,        // alpha\n                                   d_u_fluidSolve_idx,\n                                   Pointer<SideVariable<NDIM, double> >(d_u_fluidSolve_var), // src\n                                   d_no_fill_op,                                             // src_bdry_fill\n                                   d_FuRMoRP_new_time,                                       // src_bdry_fill_time\n                                   U_current_cf_bdry_synch);                                 // src_cf_bdry_synch\n\n        const double Div_u_norm_1 = d_hier_cc_data_ops->L1Norm(d_Div_u_scratch_idx, d_wgt_cc_idx);\n        const double Div_u_norm_2 = d_hier_cc_data_ops->L2Norm(d_Div_u_scratch_idx, d_wgt_cc_idx);\n        const double Div_u_norm_oo = d_hier_cc_data_ops->maxNorm(d_Div_u_scratch_idx, d_wgt_cc_idx);\n        tbox::plog << \"  after projection:\\n\"\n                   << \"    ||Div U||_1  = \" << Div_u_norm_1 << \"\\n\"\n                   << \"    ||Div U||_2  = \" << Div_u_norm_2 << \"\\n\"\n                   << \"    ||Div U||_oo = \" << Div_u_norm_oo << \"\\n\";\n    }\n\n    // Deallocate scratch data.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n        level->deallocatePatchData(scratch_idxs);\n    }\n\n    return;\n\n} // applyProjection\n\nvoid\nConstraintIBMethod::updateStructurePositionEulerStep()\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = d_FuRMoRP_new_time - d_FuRMoRP_current_time;\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        boost::multi_array_ref<double, 2>& X_half_Euler_data = *d_l_data_X_half_Euler[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_current_data =\n            *d_l_data_manager->getLData(\"X\", ln)->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& U_current_data = *d_l_data_U_current[ln]->getLocalFormVecArray();\n\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            const int offset = lag_idx_range.first;\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n            const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n            const std::string position_update_method = struct_param.getPositionUpdateMethod();\n            const std::vector<std::vector<double> >& current_shape = ptr_ib_kinematics->getShape(ln);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const double* const U_current = &U_current_data[local_idx][0];\n                    const double* const X_current = &X_current_data[local_idx][0];\n                    double* const X_half = &X_half_Euler_data[local_idx][0];\n                    if (position_update_method == \"CONSTRAINT_VELOCITY\")\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            X_half[d] = X_current[d] + 0.5 * dt * U_current[d];\n                        }\n                    }\n                    else if (position_update_method == \"CONSTRAINT_POSITION\")\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            X_half[d] = d_center_of_mass_current[location_struct_handle][d] +\n                                        current_shape[d][lag_idx - offset] +\n                                        0.5 * dt * (d_rigid_trans_vel_current[location_struct_handle][d]);\n                        }\n                    }\n                    else if (position_update_method == \"CONSTRAINT_EXPT_POSITION\")\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            X_half[d] = current_shape[d][lag_idx - offset];\n                        }\n                    }\n                    else\n                    {\n                        TBOX_ERROR(\n                            \"ConstraintIBMethod::updateStructurePositionEulerStep():\"\n                            \": Unknown position update method encountered\\n\"\n                            << \"Supported methods are : CONSTRAINT_VELOCITY, \"\n                               \"CONSTRAINT_POSITION AND \"\n                               \"CONSTRAINT_EXPT_POSITION \"\n                            << std::endl);\n                    }\n                }\n            }\n        } // all structs\n        d_l_data_X_half_Euler[ln]->restoreArrays();\n        d_l_data_U_current[ln]->restoreArrays();\n        d_l_data_manager->getLData(\"X\", ln)->restoreArrays();\n    }\n    return;\n} // updateStructurePositionEulerStep\n\nvoid\nConstraintIBMethod::forwardEulerStep(double current_time, double new_time)\n{\n    IBMethod::forwardEulerStep(current_time, new_time);\n\n    setFuRMoRPTime(current_time, new_time);\n\n    IBTK_TIMER_START(t_eulerStep);\n    updateStructurePositionEulerStep();\n    IBTK_TIMER_STOP(t_eulerStep);\n\n    return;\n} // eulerStep\n\nvoid\nConstraintIBMethod::updateStructurePositionMidPointStep()\n{\n    using StructureParameters = ConstraintIBKinematics::StructureParameters;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = d_FuRMoRP_new_time - d_FuRMoRP_current_time;\n\n    calculateMidPointVelocity();\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        boost::multi_array_ref<double, 2>& X_new_MidPoint_data = *d_l_data_X_new_MidPoint[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_current_data =\n            *d_l_data_manager->getLData(\"X\", ln)->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& U_half_data = *d_l_data_U_half[ln]->getLocalFormVecArray();\n\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            const int offset = lag_idx_range.first;\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n            const StructureParameters& struct_param = ptr_ib_kinematics->getStructureParameters();\n            const std::string position_update_method = struct_param.getPositionUpdateMethod();\n            const std::vector<std::vector<double> >& new_shape = ptr_ib_kinematics->getShape(ln);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const double* const U_half = &U_half_data[local_idx][0];\n                    const double* const X_current = &X_current_data[local_idx][0];\n                    double* const X_new = &X_new_MidPoint_data[local_idx][0];\n\n                    if (position_update_method == \"CONSTRAINT_VELOCITY\")\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            X_new[d] = X_current[d] + dt * U_half[d];\n                        }\n                    }\n                    else if (position_update_method == \"CONSTRAINT_POSITION\")\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            X_new[d] = d_center_of_mass_current[location_struct_handle][d] +\n                                       new_shape[d][lag_idx - offset] +\n                                       dt * 0.5 *\n                                           (d_rigid_trans_vel_current[location_struct_handle][d] +\n                                            d_rigid_trans_vel_new[location_struct_handle][d]);\n                        }\n                    }\n                    else if (position_update_method == \"CONSTRAINT_EXPT_POSITION\")\n                    {\n                        for (int d = 0; d < NDIM; ++d)\n                        {\n                            X_new[d] = new_shape[d][lag_idx - offset];\n                        }\n                    }\n                    else\n                    {\n                        TBOX_ERROR(\n                            \"ConstraintIBMethod::\"\n                            \"updateStructurePositionMidPointStep():: Unknown \"\n                            \"position update method encountered\\n\"\n                            << \"Supported methods are : CONSTRAINT_VELOCITY, \"\n                               \"CONSTRAINT_POSITION AND \"\n                               \"CONSTRAINT_EXPT_POSITION \"\n                            << std::endl);\n                    }\n                }\n            }\n        } // all structs\n        d_l_data_X_new_MidPoint[ln]->restoreArrays();\n        d_l_data_manager->getLData(\"X\", ln)->restoreArrays();\n        d_l_data_U_half[ln]->restoreArrays();\n    }\n    return;\n\n} // updateStructurePositionMidPointStep\n\nvoid\nConstraintIBMethod::midpointStep(double current_time, double new_time)\n{\n    IBMethod::midpointStep(current_time, new_time);\n\n    IBTK_TIMER_START(t_midpointStep);\n\n    updateStructurePositionMidPointStep();\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    int ierr;\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        ierr = VecCopy(d_l_data_X_new_MidPoint[ln]->getVec(), d_X_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n    }\n\n    IBTK_TIMER_STOP(t_midpointStep);\n    return;\n\n} // midpointStep\n\nvoid\nConstraintIBMethod::copyFluidVariable(int copy_from_idx, int copy_to_idx)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n        if (!level->checkAllocated(copy_to_idx)) level->allocatePatchData(copy_to_idx);\n    }\n\n    SAMRAIVectorReal<NDIM, double> u_from(d_object_name + \"from\", d_hierarchy, coarsest_ln, finest_ln);\n    SAMRAIVectorReal<NDIM, double> u_to(d_object_name + \"to\", d_hierarchy, coarsest_ln, finest_ln);\n\n    u_from.addComponent(d_u_fluidSolve_var, copy_from_idx, d_wgt_sc_idx);\n    u_to.addComponent(d_u_fluidSolve_var, copy_to_idx, d_wgt_sc_idx);\n\n    u_to.copyVector(Pointer<SAMRAIVectorReal<NDIM, double> >(&u_from, false));\n\n    using InterpolationTransactionComponent = IBTK::HierarchyGhostCellInterpolation::InterpolationTransactionComponent;\n    std::vector<InterpolationTransactionComponent> transaction_comps;\n    InterpolationTransactionComponent component(copy_to_idx,\n                                                DATA_REFINE_TYPE,\n                                                USE_CF_INTERPOLATION,\n                                                SIDE_DATA_COARSEN_TYPE,\n                                                BDRY_EXTRAP_TYPE,\n                                                CONSISTENT_TYPE_2_BDRY,\n                                                std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>(NDIM, nullptr),\n                                                nullptr);\n    transaction_comps.push_back(component);\n\n    Pointer<HierarchyGhostCellInterpolation> hier_bdry_fill = new HierarchyGhostCellInterpolation();\n    hier_bdry_fill->initializeOperatorState(transaction_comps, d_hierarchy, coarsest_ln, finest_ln);\n    const bool homogeneous_bc = true;\n    hier_bdry_fill->setHomogeneousBc(homogeneous_bc);\n    hier_bdry_fill->fillData(0.0);\n\n    return;\n} // copyFluidVariable\n\nvoid\nConstraintIBMethod::copyDensityVariable(int copy_from_idx, int copy_to_idx)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n        if (!level->checkAllocated(copy_to_idx)) level->allocatePatchData(copy_to_idx);\n    }\n\n    d_hier_sc_data_ops->copyData(copy_to_idx,\n                                 copy_from_idx,\n                                 /*interior_only*/ true);\n\n    return;\n} // copyDensityVariable\n\nvoid\nConstraintIBMethod::interpolateFluidSolveVelocity()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    std::vector<SAMRAI::tbox::Pointer<IBTK::LData> > F_data(finest_ln + 1, SAMRAI::tbox::Pointer<IBTK::LData>(nullptr));\n    std::vector<SAMRAI::tbox::Pointer<IBTK::LData> > X_data(finest_ln + 1, SAMRAI::tbox::Pointer<IBTK::LData>(nullptr));\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        F_data[ln] = d_l_data_U_interp[ln];\n        X_data[ln] = d_l_data_X_half_Euler[ln];\n    }\n\n    d_l_data_manager->interp(d_u_fluidSolve_cib_idx, F_data, X_data);\n\n    return;\n} // interpolateFluidSolveVelocity\n\nvoid\nConstraintIBMethod::spreadCorrectedLagrangianVelocity()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    std::vector<SAMRAI::tbox::Pointer<IBTK::LData> > F_data(finest_ln + 1, SAMRAI::tbox::Pointer<IBTK::LData>(nullptr));\n    std::vector<SAMRAI::tbox::Pointer<IBTK::LData> > X_data(finest_ln + 1, SAMRAI::tbox::Pointer<IBTK::LData>(nullptr));\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        F_data[ln] = d_l_data_U_correction[ln];\n        X_data[ln] = d_l_data_X_half_Euler[ln];\n    }\n\n    // Since we do not want to mess up the boundary values of u_ins, we\n    // zero-out the scratch variable, spread to it and then add the correction\n    // to u_ins. This assumes that the structure is away from the physical\n    // domain.\n    SAMRAIVectorReal<NDIM, double> u_cib(d_object_name + \"cib\", d_hierarchy, coarsest_ln, finest_ln);\n    SAMRAIVectorReal<NDIM, double> u_ins(d_object_name + \"ins\", d_hierarchy, coarsest_ln, finest_ln);\n\n    u_cib.addComponent(d_u_fluidSolve_var, d_u_fluidSolve_cib_idx, d_wgt_sc_idx);\n    u_ins.addComponent(d_u_fluidSolve_var, d_u_fluidSolve_idx, d_wgt_sc_idx);\n\n    u_cib.setToScalar(0.0);\n    d_l_data_manager->spread(d_u_fluidSolve_cib_idx, F_data, X_data, d_u_phys_bdry_op);\n\n    u_ins.add(Pointer<SAMRAIVectorReal<NDIM, double> >(&u_ins, false),\n              Pointer<SAMRAIVectorReal<NDIM, double> >(&u_cib, false));\n\n    return;\n} // spreadCorrectedLagrangianVelocity\n\nvoid\nConstraintIBMethod::calculateMidPointVelocity()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    int ierr;\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        ierr = VecAXPBYPCZ(d_l_data_U_half[ln]->getVec(),\n                           0.5,\n                           0.5,\n                           0.0,\n                           d_l_data_U_current[ln]->getVec(),\n                           d_l_data_U_new[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n    }\n    return;\n\n} // calculateMidPointVelocity\n\nvoid\nConstraintIBMethod::calculateDrag()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = d_FuRMoRP_new_time - d_FuRMoRP_current_time;\n\n    std::vector<std::vector<double> > inertia_force(d_no_structures, std::vector<double>(3, 0.0));\n    std::vector<std::vector<double> > constraint_force(d_no_structures, std::vector<double>(3, 0.0));\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        const boost::multi_array_ref<double, 2>& U_new_data = *d_l_data_U_new[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& U_current_data = *d_l_data_U_current[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& U_correction_data = *d_l_data_U_correction[ln]->getLocalFormVecArray();\n\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const double* const U_new = &U_new_data[local_idx][0];\n                    const double* const U_current = &U_current_data[local_idx][0];\n                    const double* const U_correction = &U_correction_data[local_idx][0];\n\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        inertia_force[location_struct_handle][d] += U_new[d] - U_current[d];\n                        constraint_force[location_struct_handle][d] += U_correction[d];\n                    }\n                }\n            }\n        } // all structs\n        d_l_data_U_new[ln]->restoreArrays();\n        d_l_data_U_current[ln]->restoreArrays();\n        d_l_data_U_correction[ln]->restoreArrays();\n    }\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        IBTK_MPI::sumReduction(&inertia_force[struct_no][0], 3);\n        IBTK_MPI::sumReduction(&constraint_force[struct_no][0], 3);\n        for (int d = 0; d < NDIM; ++d)\n        {\n            inertia_force[struct_no][d] *= (d_rho_solid[struct_no] / dt) * d_vol_element[struct_no];\n            constraint_force[struct_no][d] *= (d_rho_solid[struct_no] / dt);\n        }\n    }\n\n    if (!IBTK_MPI::getRank() && d_print_output && d_output_drag && (d_timestep_counter % d_output_interval) == 0)\n    {\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            *d_drag_force_stream[struct_no]\n                << d_FuRMoRP_new_time << '\\t' << inertia_force[struct_no][0] << '\\t' << inertia_force[struct_no][1]\n                << '\\t' << inertia_force[struct_no][2] << '\\t' << constraint_force[struct_no][0] << '\\t'\n                << constraint_force[struct_no][1] << '\\t' << constraint_force[struct_no][2] << std::endl;\n        }\n    }\n\n    return;\n} // calculateDrag\n\nvoid\nConstraintIBMethod::calculateTorque()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = d_FuRMoRP_new_time - d_FuRMoRP_current_time;\n\n    std::vector<std::vector<double> > inertia_torque(d_no_structures, std::vector<double>(3, 0.0));\n    std::vector<std::vector<double> > constraint_torque(d_no_structures, std::vector<double>(3, 0.0));\n    double R_cross_U_inertia[3] = { 0.0 }, R_cross_U_constraint[3] = { 0.0 };\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        const boost::multi_array_ref<double, 2>& U_new_data = *d_l_data_U_new[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& U_current_data = *d_l_data_U_current[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& U_correction_data = *d_l_data_U_correction[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_data = *d_X_new_data[ln]->getLocalFormVecArray();\n\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const IBTK::Vector& displacement = node_idx->getPeriodicDisplacement();\n                    const double* const U_new = &U_new_data[local_idx][0];\n                    const double* const U_current = &U_current_data[local_idx][0];\n                    const double* const U_correction = &U_correction_data[local_idx][0];\n                    const double* const X = &X_data[local_idx][0];\n#if (NDIM == 2)\n                    double x = displacement[0] + X[0] - d_center_of_mass_unshifted_new[location_struct_handle][0];\n                    double y = displacement[1] + X[1] - d_center_of_mass_unshifted_new[location_struct_handle][1];\n\n                    R_cross_U_inertia[2] = (x * (U_new[1] - U_current[1]) - y * (U_new[0] - U_current[0]));\n                    R_cross_U_constraint[2] = (x * (U_correction[1]) - y * (U_correction[0]));\n#endif\n\n#if (NDIM == 3)\n                    double x = displacement[0] + X[0] - d_center_of_mass_unshifted_new[location_struct_handle][0];\n                    double y = displacement[1] + X[1] - d_center_of_mass_unshifted_new[location_struct_handle][1];\n                    double z = displacement[2] + X[2] - d_center_of_mass_unshifted_new[location_struct_handle][2];\n\n                    R_cross_U_inertia[0] = (y * (U_new[2] - U_current[2]) - z * (U_new[1] - U_current[1]));\n\n                    R_cross_U_inertia[1] = (-x * (U_new[2] - U_current[2]) + z * (U_new[0] - U_current[0]));\n\n                    R_cross_U_inertia[2] = (x * (U_new[1] - U_current[1]) - y * (U_new[0] - U_current[0]));\n\n                    R_cross_U_constraint[0] = (y * (U_correction[2]) - z * (U_correction[1]));\n\n                    R_cross_U_constraint[1] = (-x * (U_correction[2]) + z * (U_correction[0]));\n\n                    R_cross_U_constraint[2] = (x * (U_correction[1]) - y * (U_correction[0]));\n#endif\n\n                    for (int d = 0; d < 3; ++d)\n                    {\n                        inertia_torque[location_struct_handle][d] += R_cross_U_inertia[d];\n                        constraint_torque[location_struct_handle][d] += R_cross_U_constraint[d];\n                    }\n                }\n            }\n        } // all structs\n        d_l_data_U_new[ln]->restoreArrays();\n        d_l_data_U_current[ln]->restoreArrays();\n        d_l_data_U_correction[ln]->restoreArrays();\n        d_X_new_data[ln]->restoreArrays();\n    }\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        IBTK_MPI::sumReduction(&inertia_torque[struct_no][0], 3);\n        IBTK_MPI::sumReduction(&constraint_torque[struct_no][0], 3);\n        for (int d = 0; d < 3; ++d)\n        {\n            inertia_torque[struct_no][d] *= (d_rho_solid[struct_no] / dt) * d_vol_element[struct_no];\n            constraint_torque[struct_no][d] *= (d_rho_solid[struct_no] / dt);\n        }\n    }\n\n    if (!IBTK_MPI::getRank() && d_print_output && d_output_torque && (d_timestep_counter % d_output_interval) == 0)\n    {\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            *d_torque_stream[struct_no] << d_FuRMoRP_new_time << '\\t' << inertia_torque[struct_no][0] << '\\t'\n                                        << inertia_torque[struct_no][1] << '\\t' << inertia_torque[struct_no][2] << '\\t'\n                                        << constraint_torque[struct_no][0] << '\\t' << constraint_torque[struct_no][1]\n                                        << '\\t' << constraint_torque[struct_no][2] << std::endl;\n        }\n    }\n\n    return;\n} // calculateTorque\n\nvoid\nConstraintIBMethod::calculatePower()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = d_FuRMoRP_new_time - d_FuRMoRP_current_time;\n\n    std::vector<std::vector<double> > inertia_power(d_no_structures, std::vector<double>(3, 0.0));\n    std::vector<std::vector<double> > constraint_power(d_no_structures, std::vector<double>(3, 0.0));\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        const boost::multi_array_ref<double, 2>& U_new_data = *d_l_data_U_new[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& U_current_data = *d_l_data_U_current[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& U_correction_data = *d_l_data_U_correction[ln]->getLocalFormVecArray();\n\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const double* const U_new = &U_new_data[local_idx][0];\n                    const double* const U_current = &U_current_data[local_idx][0];\n                    const double* const U_correction = &U_correction_data[local_idx][0];\n\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        inertia_power[location_struct_handle][d] += (U_new[d] - U_current[d]) * U_new[d];\n                        constraint_power[location_struct_handle][d] += U_correction[d] * U_new[d];\n                    }\n                }\n            }\n        } // all structs\n        d_l_data_U_new[ln]->restoreArrays();\n        d_l_data_U_current[ln]->restoreArrays();\n        d_l_data_U_correction[ln]->restoreArrays();\n    }\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        IBTK_MPI::sumReduction(&inertia_power[struct_no][0], 3);\n        IBTK_MPI::sumReduction(&constraint_power[struct_no][0], 3);\n        for (int d = 0; d < NDIM; ++d)\n        {\n            inertia_power[struct_no][d] *= (d_rho_solid[struct_no] / dt) * d_vol_element[struct_no];\n            constraint_power[struct_no][d] *= (d_rho_solid[struct_no] / dt);\n        }\n    }\n\n    if (!IBTK_MPI::getRank() && d_print_output && d_output_drag && (d_timestep_counter % d_output_interval) == 0)\n    {\n        for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n        {\n            *d_power_spent_stream[struct_no]\n                << d_FuRMoRP_new_time << '\\t' << inertia_power[struct_no][0] << '\\t' << inertia_power[struct_no][1]\n                << '\\t' << inertia_power[struct_no][2] << '\\t' << constraint_power[struct_no][0] << '\\t'\n                << constraint_power[struct_no][1] << '\\t' << constraint_power[struct_no][2] << std::endl;\n        }\n    }\n\n    return;\n} // calculatePower\n\nvoid\nConstraintIBMethod::calculateStructureMomentum()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        const boost::multi_array_ref<double, 2>& U_new_data = *d_l_data_U_new[ln]->getLocalFormVecArray();\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const double* const U_new = &U_new_data[local_idx][0];\n\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        d_structure_mom[location_struct_handle][d] += U_new[d];\n                    }\n                }\n            }\n        } // all structs\n        d_l_data_U_new[ln]->restoreArrays();\n    }\n\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        IBTK_MPI::sumReduction(&d_structure_mom[struct_no][0], 3);\n        for (int d = 0; d < NDIM; ++d)\n        {\n            d_structure_mom[struct_no][d] *= d_rho_solid[struct_no] * d_vol_element[struct_no];\n        }\n    }\n\n    return;\n} // calculateStructureMomentum\n\nvoid\nConstraintIBMethod::calculateStructureRotationalMomentum()\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    double R_cross_U[3] = { 0.0 };\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        const boost::multi_array_ref<double, 2>& U_new_data = *d_l_data_U_new[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X_data = *d_X_new_data[ln]->getLocalFormVecArray();\n\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const size_t structs_on_this_ln = structIDs.size();\n\n        for (size_t struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            std::pair<int, int> lag_idx_range =\n                d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], ln);\n            Pointer<ConstraintIBKinematics> ptr_ib_kinematics =\n                *std::find_if(d_ib_kinematics.begin(), d_ib_kinematics.end(), find_struct_handle(lag_idx_range));\n            const int location_struct_handle =\n                find_struct_handle_position(d_ib_kinematics.begin(), d_ib_kinematics.end(), ptr_ib_kinematics);\n\n            for (const auto& node_idx : local_nodes)\n            {\n                const int lag_idx = node_idx->getLagrangianIndex();\n                if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second)\n                {\n                    const int local_idx = node_idx->getLocalPETScIndex();\n                    const IBTK::Vector& displacement = node_idx->getPeriodicDisplacement();\n                    const double* const U_new = &U_new_data[local_idx][0];\n                    const double* const X = &X_data[local_idx][0];\n#if (NDIM == 2)\n                    double x = displacement[0] + X[0] - d_center_of_mass_unshifted_new[location_struct_handle][0];\n                    double y = displacement[1] + X[1] - d_center_of_mass_unshifted_new[location_struct_handle][1];\n                    R_cross_U[2] = (x * (U_new[1]) - y * (U_new[0]));\n#endif\n\n#if (NDIM == 3)\n                    double x = displacement[0] + X[0] - d_center_of_mass_unshifted_new[location_struct_handle][0];\n                    double y = displacement[1] + X[1] - d_center_of_mass_unshifted_new[location_struct_handle][1];\n                    double z = displacement[2] + X[2] - d_center_of_mass_unshifted_new[location_struct_handle][2];\n\n                    R_cross_U[0] = (y * (U_new[2]) - z * (U_new[1]));\n\n                    R_cross_U[1] = (-x * (U_new[2]) + z * (U_new[0]));\n\n                    R_cross_U[2] = (x * (U_new[1]) - y * (U_new[0]));\n#endif\n\n                    for (int d = 0; d < 3; ++d)\n                    {\n                        d_structure_rotational_mom[location_struct_handle][d] += R_cross_U[d];\n                    }\n                }\n            }\n        } // all structs\n        d_l_data_U_new[ln]->restoreArrays();\n        d_X_new_data[ln]->restoreArrays();\n    }\n    for (int struct_no = 0; struct_no < d_no_structures; ++struct_no)\n    {\n        IBTK_MPI::sumReduction(&d_structure_rotational_mom[struct_no][0], 3);\n        for (int d = 0; d < 3; ++d)\n        {\n            d_structure_rotational_mom[struct_no][d] *= d_rho_solid[struct_no] * d_vol_element[struct_no];\n        }\n    }\n\n    return;\n} // calculateStructureRotationalMomentum\n\n} // namespace IBAMR\n", "meta": {"hexsha": "9283849f300d42ededc0919249ee78df8c145a06", "size": 135410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IB/ConstraintIBMethod.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": "src/IB/ConstraintIBMethod.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": "src/IB/ConstraintIBMethod.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": 46.7899101589, "max_line_length": 120, "alphanum_fraction": 0.6213352042, "num_tokens": 33583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.17042328907510318}}
{"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_BITWISE_FUNCTIONS_SIMD_COMMON_RSHL_HPP_INCLUDED\n#define BOOST_SIMD_BITWISE_FUNCTIONS_SIMD_COMMON_RSHL_HPP_INCLUDED\n\n#include <boost/simd/bitwise/functions/rshl.hpp>\n#include <boost/simd/include/functions/simd/is_gtz.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/shift_left.hpp>\n#include <boost/simd/include/functions/simd/shr.hpp>\n#include <boost/simd/include/functions/simd/unary_minus.hpp>\n#include <boost/simd/sdk/meta/cardinal_of.hpp>\n#include <boost/mpl/equal_to.hpp>\n\n#ifndef NDEBUG\n#include <boost/simd/include/functions/simd/max.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT_IF          ( rshl_, tag::cpu_, (A0)(A1)(X)\n                                       , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                                               , boost::simd::meta::cardinal_of<A1>\n                                                               >\n                                         )\n                                       , ((simd_<arithmetic_<A0>,X>))\n                                         ((generic_<integer_<A1> >))\n                                       )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      #ifndef NDEBUG\n      return if_else(is_gtz(a1), shl(a0, max(Zero<A1>(), a1)), shr(a0, max(Zero<A1>(), -a1)));\n      #else\n      return if_else(is_gtz(a1), shl(a0, a1), shr(a0, -a1));\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT_IF          ( rshl_, tag::cpu_, (A0)(A1)(X)\n                                       , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                                               , boost::simd::meta::cardinal_of<A1>\n                                                               >\n                                       )\n                                       , ((simd_<arithmetic_<A0>,X>))\n                                         ((generic_<unsigned_<A1> >))\n                                       )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      return shl(a0, a1);\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "894073380031d7cb4fcba0cbc155e82d17619f4e", "size": 2754, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/bitwise/functions/simd/common/rshl.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/bitwise/functions/simd/common/rshl.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/bitwise/functions/simd/common/rshl.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": 41.1044776119, "max_line_length": 99, "alphanum_fraction": 0.4793028322, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.17042328907510315}}
{"text": "\n#include <upo_rrt_planners/ros/ValidityChecker2.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Core>\n#include <ros/console.h>\n\n\nupo_RRT_ros::ValidityChecker2::ValidityChecker2(nav_msgs::OccupancyGrid* costmap, tf::TransformListener* tf, unsigned int dimensions, int distType) : StateChecker()\n{\n    costmap_mutex_.lock();\n\tcostmap_.clear();\n\tfor(unsigned int i=0; i<costmap->data.size(); i++)\n\t\tcostmap_.push_back((int)costmap->data[i]);\n\n\tresolution_ = (float)costmap->info.resolution; \t//m/cell\n\twidth_ = costmap->info.width;\t\t\t\t\t//cells\n \theight_ = costmap->info.height;\t\t\t\t\t//cells\n\torigin_.clear();\n\torigin_.push_back(costmap->info.origin.position.x); //m\n\torigin_.push_back(costmap->info.origin.position.y); //m\n\torigin_.push_back(tf::getYaw(costmap->info.origin.orientation)); //rad\n\tcostmap_mutex_.unlock();\n\n\ttf_ = tf;\n\tdimensions_ = dimensions;\n\tdistanceType_ = distType;\n\ttime_ = ros::Time::now();\n}\n\n\nupo_RRT_ros::ValidityChecker2::ValidityChecker2(tf::TransformListener* tf, unsigned int dimensions, int distType) : StateChecker()\n{\n\ttf_ = tf;\n\tdimensions_ = dimensions;\n\tdistanceType_ = distType;\n\ttime_ = ros::Time::now();\n\n\t//Build a default costmap\n\tresolution_ = 0.05; \t//m/cell\n\twidth_ = 100;\t\t\t\t\t//cells\n \theight_ = 100;\t\t\t\t\t//cells\n\torigin_.clear();\n\torigin_.push_back(2.5); //m\n\torigin_.push_back(2.5); //m\n\torigin_.push_back(0.0); //rad\n    costmap_mutex_.lock();\n\tcostmap_.clear();\n\tfor(unsigned int i=0; i<(width_*height_); i++)\n\t\tcostmap_.push_back((int)0);\n\tcostmap_mutex_.unlock();\n}\n\n\nupo_RRT_ros::ValidityChecker2::~ValidityChecker2() {\n\t\n\t//delete navfeatures_;\n}\n\n\nvoid upo_RRT_ros::ValidityChecker2::updateCostmap(nav_msgs::OccupancyGrid* costmap)\n{\n\tcostmap_mutex_.lock();\n\tcostmap_.clear();\n\tfor(unsigned int i=0; i<costmap->data.size(); i++)\n\t\tcostmap_.push_back((int)costmap->data[i]);\n\t\n\tresolution_ = (float)costmap->info.resolution;\n\twidth_ = costmap->info.width;\n \theight_ = costmap->info.height;\n\torigin_.clear();\n\torigin_.push_back(costmap->info.origin.position.x);\n\torigin_.push_back(costmap->info.origin.position.y);\n\torigin_.push_back(tf::getYaw(costmap->info.origin.orientation));\n\tcostmap_mutex_.unlock();\n}\n\n\n\n\n\n\n\nstd::vector<int> upo_RRT_ros::ValidityChecker2::poseToCell(std::vector<float> pose) const\n{\n\t//Be careful, I'm not taking into account the rotation because is zero usually.\n\t//Pose is in robot frame coordinates, and the robot is centered in the costmap\n\tint x =  fabs(origin_[0])/resolution_ + pose[0]/resolution_;\n\tint y =  fabs(origin_[1])/resolution_ + pose[1]/resolution_;\n \tstd::vector<int> cell;\n\tcell.push_back(x);\n\tcell.push_back(y);\n\treturn cell;\n}\n\nstd::vector<float> upo_RRT_ros::ValidityChecker2::cellToPose(std::vector<int> cell) const\n{\n\t//Be careful, I'm not taking into account the rotation because is zero usually.\n\tfloat x = (resolution_*cell[1] - origin_[0]); // + (resolution_/2.0); \n\tfloat y = (resolution_*cell[0] - origin_[1]); // + (resolution_/2.0);\n\tstd::vector<float> pose;\n\tpose.push_back(x);\n\tpose.push_back(y);\n\treturn pose;\n}\n\n\n\nbool upo_RRT_ros::ValidityChecker2::isValid(upo_RRT::State* s) const\n{\n\tstd::vector<float> pose;\n\tpose.push_back((float)s->getX());\n\tpose.push_back((float)s->getY());\n\t//costmap_mutex_.lock();\n\tstd::vector<int> cell = poseToCell(pose); \n \t//printf(\"IsValid cell[%i][%i]\\n\", cell[0],cell[1]);\n\tint ind = cell[0]*200 + cell[1];\n    //printf(\"Indice: %i\\n\", ind);\n\tfloat cost = costmap_[ind];\n\t//costmap_mutex_.unlock();\n\n\tif(cost == -1 || cost > 100) //cost == 100\n\t\treturn false;\n\telse\n\t\treturn true;\n\t\n}\n\n\nvoid upo_RRT_ros::ValidityChecker2::preplanning_computations()\n{\n}\n\n\nfloat upo_RRT_ros::ValidityChecker2::distance(upo_RRT::State* s1, upo_RRT::State* s2) const\n{\n\tfloat dx = s1->getX() - s2->getX();\n\tfloat dy = s1->getY() - s2->getY();\n\t//float dist = sqrt(dx*dx + dy*dy);\n\tfloat dist = dx*dx + dy*dy;\n\t\n\tswitch(distanceType_) {\n\t\t\n\t\tcase 1:\n\t\t\treturn dist;\n\n\t\tcase 2:\n\t\t\treturn sqrt(dist);\n\n\t\tcase 3:\n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//SUM w1*|| Pi+1 - Pi|| + w2*(1-|Qi+1 * Qi|)\u00b2\n\t\t\t\tfloat euc_dist = sqrt(dist);\n\t\t\n\t\t\t\ttf::Quaternion q1 = tf::createQuaternionFromYaw(s1->getYaw());\n\t\t\t\ttf::Quaternion q2 = tf::createQuaternionFromYaw(s2->getYaw());\n\t\t\t\tfloat dot_prod = q1.dot(q2);\n\t\t\t\tfloat angle_dist =  (1 - fabs(dot_prod))*(1 - fabs(dot_prod));\n\t\t\t\t//printf(\"eu_dist: %.2f, angle_dist: %.3f, dist: %.3f\\n\", euc_dist, angle_dist, 0.8*euc_dist + 0.2*angle_dist);\n\t\t\t\treturn 0.7*euc_dist + 0.3*angle_dist;\n\t\t\t}\n\t\t\t\n\t\tcase 4:\n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t// Another option\n\t\t\t\t/*\n\t\t\t\tFirst, transform the robot location into person location frame: \n\t\t\t\t\t\t\t\t\t\t\t|cos(th)  sin(th)  0|\n\t\t\t\t\tRotation matrix R(th)= \t|-sin(th) cos(th)  0|\n\t\t\t\t\t\t\t\t\t\t\t|  0        0      1|\n\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\tx' = (xr-xp)*cos(th_p)+(yr-yp)*sin(th_p)\n\t\t\t\t\ty' = (xr-xp)*(-sin(th_p))+(yr-yp)*cos(th_p)\n\t\t\t\t*/\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\treturn (0.8*sqrt(dist)+0.2*fabs(alpha));\n\t\t\t}\n\t\t\t\n\t\tcase 5:  \n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//UPO. Dist + sum of the angles of both points regarding the intersection line\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\tfloat beta = s2->getYaw() - alpha;\n\t\t\t\tbeta = normalizeAngle(beta, -M_PI, M_PI);\n\t\t\t\treturn (0.6*sqrt(dist)+0.4*(fabs(alpha)+fabs(beta)));\n\t\t\t}\n\t\t\t\n\t\tcase 6:  \n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//Paper IROS2015 \"Feedback motion planning via non-holonomic RRT* for mobile robots\"\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\tfloat phi = s2->getYaw() - alpha;\n\t\t\t\tphi = normalizeAngle(phi, -M_PI, M_PI);\n\t\t\t\tfloat ka = 0.5;\n\t\t\t\tfloat ko = ka/8.0;\n\t\t\t\tdist = sqrt(dist);\n\t\t\t\t// two options\n\t\t\t\tfloat alpha_prime = atan(-ko*phi);\n\t\t\t\t//float alpha_prime = atan(-ko*ko * phi/(dist*dist));\n\t\t\t\tfloat r = normalizeAngle((alpha-alpha_prime), -M_PI, M_PI);\n\t\t\t\treturn (sqrt(dist*dist + ko*ko + phi*phi) + ka*fabs(r));\n\t\t\t}\n\t\t\t\n\t\tdefault:\n\t\t\treturn sqrt(dist);\n\t}\n\t\n}\n\n\n\nfloat upo_RRT_ros::ValidityChecker2::getCost(upo_RRT::State* s)\n{\n\t//cell.first = x = column, cell.second = y = row\n\tstd::vector<float> pose;\n\tpose.push_back((float)s->getX());\n\tpose.push_back((float)s->getY());\n\tcostmap_mutex_.lock();\n\tstd::vector<int> cell = poseToCell(pose);\n\tint ind = (cell[1]+1) * cell[0]; //row*column\n\tfloat cost = costmap_[ind];\n\tcostmap_mutex_.unlock();\n\treturn cost;\n\n}\n\n\n\n\n/*void upo_RRT_ros::ValidityChecker::setPeople(upo_msgs::PersonPoseArrayUPO p)\n{\n\tnavfeatures_->setPeople(p);\n}\n\n\nvoid upo_RRT_ros::ValidityChecker::setWeights(std::vector<float> we) {\n\tnavfeatures_->setWeights(we);\n}*/\n\n\ngeometry_msgs::PoseStamped upo_RRT_ros::ValidityChecker2::transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, bool usetime) {\n\t\n\tgeometry_msgs::PoseStamped in = pose_in;\n\tif(!usetime)\n\t\tin.header.stamp = ros::Time();\n\t\t\t\n\tgeometry_msgs::PoseStamped pose_out;\n\t\t\n\ttry {\n\t\ttf_->transformPose(frame_out.c_str(), in, pose_out);\n\t}catch (tf::TransformException ex){\n\t\tROS_WARN(\"ValidityChecker2. TransformException in method transformPoseTo. TargetFrame: %s : %s\", frame_out.c_str(), ex.what());\n\t}\n\treturn pose_out;\n\t\n}\n\nbool upo_RRT_ros::ValidityChecker2::isQuaternionValid(const geometry_msgs::Quaternion q) {\n\t\n\t\n\t\t//first we need to check if the quaternion has nan's or infs\n\t\tif(!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w)){\n\t\t\tROS_ERROR(\"Quaternion has infs!!!!\");\n\t\t\treturn false;\n\t\t}\n\t\tif(std::isnan(q.x) || std::isnan(q.y) || std::isnan(q.z) || std::isnan(q.w)) {\n\t\t\tROS_ERROR(\"Quaternion has nans !!!\");\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(std::fabs(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w - 1) > 0.01) {\n\t\t\tROS_ERROR(\"Quaternion malformed, magnitude: %.3f should be 1.0\", (q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w));\n\t\t\treturn false;\n\t\t}\n\n\t\ttf::Quaternion tf_q(q.x, q.y, q.z, q.w);\n\n\t\t//next, we need to check if the length of the quaternion is close to zero\n\t\tif(tf_q.length2() < 1e-6){\n\t\t  ROS_ERROR(\"Quaternion has length close to zero... discarding.\");\n\t\t  return false;\n\t\t}\n\n\t\t//next, we'll normalize the quaternion and check that it transforms the vertical vector correctly\n\t\ttf_q.normalize();\n\n\t\ttf::Vector3 up(0, 0, 1);\n\n\t\tdouble dot = up.dot(up.rotate(tf_q.getAxis(), tf_q.getAngle()));\n\n\t\tif(fabs(dot - 1) > 1e-3){\n\t\t  ROS_ERROR(\"Quaternion is invalid... for navigation the z-axis of the quaternion must be close to vertical.\");\n\t\t  return false;\n\t\t}\n\n\t\treturn true;\n\t\n}\n\n\n\n\n\n", "meta": {"hexsha": "807f572abef65d3089f87771cab30a7de3f576d2", "size": 9010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rrt_planners/src/ros/ValidityChecker2.cpp", "max_stars_repo_name": "Tutorgaming/indires_navigation", "max_stars_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-07-19T13:44:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:39:15.000Z", "max_issues_repo_path": "rrt_planners/src/ros/ValidityChecker2.cpp", "max_issues_repo_name": "Tutorgaming/indires_navigation", "max_issues_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T07:32:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T09:38:44.000Z", "max_forks_repo_path": "rrt_planners/src/ros/ValidityChecker2.cpp", "max_forks_repo_name": "Tutorgaming/indires_navigation", "max_forks_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T14:43:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T21:39:19.000Z", "avg_line_length": 28.4227129338, "max_line_length": 164, "alphanum_fraction": 0.6512763596, "num_tokens": 2876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.17042093900271077}}
{"text": "#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <cctbx/sgtbx/find_affine.h>\n\nnamespace cctbx { namespace sgtbx {\n\nnamespace {\n\n  struct find_affine_wrappers\n  {\n    typedef find_affine w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"find_affine\", no_init)\n        .def(init<space_group const&, optional<int, bool> >((\n          arg(\"group\"),\n          arg(\"range\")=2,\n          arg(\"use_p1_algorithm\")=false)))\n        .def(\"cb_mx\", &w_t::cb_mx)\n      ;\n    }\n  };\n\n} // namespace <anoymous>\n\nnamespace boost_python {\n\n  void wrap_find_affine()\n  {\n    find_affine_wrappers::wrap();\n  }\n\n}}} // namespace cctbx::sgtbx::boost_python\n", "meta": {"hexsha": "70a4e9a77c8405fcaa46b200ee732c6206a084a5", "size": 707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/sgtbx/boost_python/find_affine.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": "cctbx/sgtbx/boost_python/find_affine.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": "cctbx/sgtbx/boost_python/find_affine.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": 19.1081081081, "max_line_length": 61, "alphanum_fraction": 0.6195190948, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.1703591523345615}}
{"text": "#pragma once\n\n//#include <bmchain/protocol/authority.hpp>\n//#include <bmchain/protocol/bmchain_operations.hpp>\n//\n//#include <bmchain/chain/bmchain_object_types.hpp>\n//#include <bmchain/chain/comment_object.hpp>\n//\n//#include <boost/multi_index/composite_key.hpp>\n//#include <boost/multiprecision/cpp_int.hpp>\n\n#include <bmchain/chain/bmchain_objects.hpp>\n\nnamespace bmchain { namespace chain {\n\n   enum class smt_phase : uint8_t\n   {\n      account_elevated,\n      setup_completed,\n      contribution_begin_time_completed,\n      contribution_end_time_completed,\n      launch_time_completed,              /// launch window opened\n      launch_failed,                      /// launch window closed with either not enough contributions or some cap not revealed\n      launch_success                      /// enough contributions were declared and caps revealed before launch windows closed\n   };\n\n   class custom_token_object : public object< custom_token_object_type, custom_token_object > {\n   public:\n      custom_token_object() = delete;\n\n      template<typename Constructor, typename Allocator>\n      custom_token_object(Constructor &&c, allocator<Allocator> a) {\n         c(*this);\n      }\n\n      id_type id;\n      account_name_type control_account;\n      asset_symbol_type symbol;\n      asset             current_supply;\n      asset             reward_fund;\n      uint16_t          inflation_rate = 0;\n      time_point_sec    generation_time;\n\n      time_point_sec       schedule_time =  BMCHAIN_GENESIS_TIME;;\n      bmchain::protocol::custom_token_emissions_unit emissions_unit;\n      uint32_t             interval_seconds = 0;\n      uint32_t             interval_count = 0;\n\n      /// set_setup_parameters\n      bool              allow_voting = false;\n      bool              allow_vesting = false;\n\n      smt_phase         phase = smt_phase::account_elevated;\n\n      ///parameters for 'setup_operation'\n      int64_t                       max_supply = 0;\n      bmchain::protocol::\n      custom_token_capped_generation_policy  capped_generation_policy;\n      time_point_sec                generation_begin_time;\n      time_point_sec                generation_end_time;\n      time_point_sec                announced_launch_time;\n      time_point_sec                launch_expiration_time;\n   };\n\n   class account_balance_object : public object< account_balance_object_type, account_balance_object > {\n      account_balance_object() = delete;\n\n   public:\n      template<typename Constructor, typename Allocator>\n      account_balance_object(Constructor &&c, allocator <Allocator> a) {\n         c(*this);\n      }\n\n      id_type id;\n      /// Name of the account, the balance is held for.\n      asset_symbol_type symbol;\n      account_name_type owner;\n      asset             balance;\n   };\n\n   class custom_token_event_object : public object< custom_token_event_object_type, custom_token_event_object >   {\n\n      custom_token_event_object() = delete;\n\n   public:\n      template<typename Constructor, typename Allocator>\n      custom_token_event_object(Constructor &&c, allocator <Allocator> a) {\n         c(*this);\n      }\n\n      // id_type is actually oid<smt_event_token_object>\n      id_type id;\n\n      custom_token_event_id_type parent;\n\n      smt_phase phase = smt_phase::setup_completed;\n\n      time_point_sec generation_begin_time;\n      time_point_sec generation_end_time;\n      time_point_sec announced_launch_time;\n      time_point_sec launch_expiration_time;\n   };\n\n   struct by_symbol;\n   struct by_control_account;\n   typedef multi_index_container<\n              custom_token_object,\n              indexed_by<\n                      ordered_unique< tag< by_id >, member< custom_token_object, custom_token_id_type, &custom_token_object::id > >,\n                      ordered_unique< tag< by_control_account >,\n                              composite_key< custom_token_object,\n                                      member< custom_token_object, account_name_type,  &custom_token_object::control_account >,\n                                      member< custom_token_object, custom_token_id_type,  &custom_token_object::id >\n                              >,\n                              composite_key_compare< std::less< account_name_type >, std::greater< custom_token_id_type > >\n                      >,\n                      ordered_unique< tag< by_symbol >,\n                              composite_key< custom_token_object,\n                                      member< custom_token_object, asset_symbol_type, &custom_token_object::symbol >\n                              >\n                      >,\n                      ordered_unique< tag< by_schedule_time >,\n                              composite_key< custom_token_object,\n                                      member< custom_token_object, time_point_sec,  &custom_token_object::schedule_time >,\n                                      member< custom_token_object, custom_token_id_type,  &custom_token_object::id >\n                              >,\n                              composite_key_compare< std::greater< time_point_sec >, std::greater< custom_token_id_type > >\n                      >\n              >,\n              allocator< custom_token_object >\n   > custom_token_index;\n\n   typedef multi_index_container<\n              account_balance_object,\n              indexed_by<\n                      ordered_unique< tag< by_id >, member< account_balance_object, account_balance_id_type, &account_balance_object::id > >,\n                      ordered_unique< tag< by_symbol >,\n                              composite_key< account_balance_object,\n                                      member< account_balance_object, asset_symbol_type,  &account_balance_object::symbol >,\n                                      member< account_balance_object, account_balance_id_type, &account_balance_object::id >\n                              >,\n                              composite_key_compare< std::less< asset_symbol_type >, std::greater< account_balance_id_type > >\n                      >,\n                      ordered_unique< tag< by_owner >,\n                              composite_key< account_balance_object,\n                                      member< account_balance_object, account_name_type,  &account_balance_object::owner >,\n                                      member< account_balance_object, asset_symbol_type,  &account_balance_object::symbol >,\n                                      member< account_balance_object, account_balance_id_type,  &account_balance_object::id >\n                              >,\n                              composite_key_compare< std::less< account_name_type >, std::less< asset_symbol_type >, std::greater< account_balance_id_type > >\n                      >\n              >,\n              allocator< account_balance_object >\n   > account_balance_index;\n\nstruct by_interval_gen_begin;\nstruct by_interval_gen_end;\nstruct by_interval_launch;\nstruct by_interval_launch_exp;\ntypedef multi_index_container <\n   custom_token_event_object,\n   indexed_by <\n      ordered_unique< tag< by_id >,\n         member< custom_token_event_object, custom_token_event_id_type, &custom_token_event_object::id > >,\n\n      ordered_non_unique< tag< by_interval_gen_begin >,\n         composite_key< custom_token_event_object,\n            member< custom_token_event_object, smt_phase, &custom_token_event_object::phase >,\n            member< custom_token_event_object, time_point_sec, &custom_token_event_object::generation_begin_time >\n         >\n      >,\n      ordered_non_unique< tag< by_interval_gen_end >,\n         composite_key< custom_token_event_object,\n            member< custom_token_event_object, smt_phase, &custom_token_event_object::phase >,\n            member< custom_token_event_object, time_point_sec, &custom_token_event_object::generation_end_time >\n         >\n      >,\n      ordered_non_unique< tag< by_interval_launch >,\n         composite_key< custom_token_event_object,\n            member< custom_token_event_object, smt_phase, &custom_token_event_object::phase >,\n            member< custom_token_event_object, time_point_sec, &custom_token_event_object::announced_launch_time >\n         >\n      >,\n      ordered_non_unique< tag< by_interval_launch_exp >,\n         composite_key< custom_token_event_object,\n            member< custom_token_event_object, smt_phase, &custom_token_event_object::phase >,\n            member< custom_token_event_object, time_point_sec, &custom_token_event_object::launch_expiration_time >\n         >\n      >\n   >,\n   allocator< custom_token_event_object >\n> custom_token_event_index;\n\n}}\n\nFC_REFLECT( bmchain::chain::custom_token_object,\n                    (id)(control_account)(symbol)(current_supply)(inflation_rate)(reward_fund)(generation_time)(schedule_time)\n                    (emissions_unit)(interval_seconds)(interval_count)(allow_voting)(allow_vesting) )\nCHAINBASE_SET_INDEX_TYPE( bmchain::chain::custom_token_object, bmchain::chain::custom_token_index )\n\nFC_REFLECT( bmchain::chain::account_balance_object,(id)(owner)(balance) )\nCHAINBASE_SET_INDEX_TYPE( bmchain::chain::account_balance_object, bmchain::chain::account_balance_index )\n\nFC_REFLECT( bmchain::chain::custom_token_event_object, (id)(parent)(phase)(generation_begin_time)(generation_end_time)(announced_launch_time)(launch_expiration_time) )\nCHAINBASE_SET_INDEX_TYPE( bmchain::chain::custom_token_event_object, bmchain::chain::custom_token_event_index )", "meta": {"hexsha": "0b3b23998fdda5faadc73294794e30c04152b736", "size": 9465, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/include/bmchain/chain/custom_token_objects.hpp", "max_stars_repo_name": "igorsoldatov/BuisnessWiki", "max_stars_repo_head_hexsha": "ccafad446c2d5db8b13499b587fc75d71ffeebc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-02-02T12:56:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-17T23:07:39.000Z", "max_issues_repo_path": "libraries/chain/include/bmchain/chain/custom_token_objects.hpp", "max_issues_repo_name": "igorsoldatov/BuisnessWiki", "max_issues_repo_head_hexsha": "ccafad446c2d5db8b13499b587fc75d71ffeebc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/include/bmchain/chain/custom_token_objects.hpp", "max_forks_repo_name": "igorsoldatov/BuisnessWiki", "max_forks_repo_head_hexsha": "ccafad446c2d5db8b13499b587fc75d71ffeebc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-02T12:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-26T11:32:21.000Z", "avg_line_length": 46.1707317073, "max_line_length": 167, "alphanum_fraction": 0.6434231379, "num_tokens": 1815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17035914897391397}}
{"text": "#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"ces.h\"\n#include \"filelib.h\"\n#include \"stringlib.h\"\n#include \"sparse_vector.h\"\n#include \"scorer.h\"\n#include \"viterbi_envelope.h\"\n#include \"inside_outside.h\"\n#include \"error_surface.h\"\n#include \"b64tools.h\"\n#include \"hg_io.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"reference,r\",po::value<vector<string> >(), \"[REQD] Reference translation (tokenized text)\")\n        (\"source,s\",po::value<string>(), \"Source file (ignored, except for AER)\")\n        (\"loss_function,l\",po::value<string>()->default_value(\"ibm_bleu\"), \"Loss function being optimized\")\n        (\"input,i\",po::value<string>()->default_value(\"-\"), \"Input file to map (- is STDIN)\")\n        (\"help,h\", \"Help\");\n  po::options_description dcmdline_options;\n  dcmdline_options.add(opts);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  bool flag = false;\n  if (!conf->count(\"reference\")) {\n    cerr << \"Please specify one or more references using -r <REF.TXT>\\n\";\n    flag = true;\n  }\n  if (flag || conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nbool ReadSparseVectorString(const string& s, SparseVector<double>* v) {\n#if 0\n  // this should work, but untested.\n  std::istringstream i(s);\n  i>>*v;\n#else\n  vector<string> fields;\n  Tokenize(s, ';', &fields);\n  if (fields.empty()) return false;\n  for (int i = 0; i < fields.size(); ++i) {\n    vector<string> pair(2);\n    Tokenize(fields[i], '=', &pair);\n    if (pair.size() != 2) {\n      cerr << \"Error parsing vector string: \" << fields[i] << endl;\n      return false;\n    }\n    v->set_value(FD::Convert(pair[0]), atof(pair[1].c_str()));\n  }\n  return true;\n#endif\n}\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  const string loss_function = conf[\"loss_function\"].as<string>();\n  ScoreType type = ScoreTypeFromString(loss_function);\n  DocScorer ds(type, conf[\"reference\"].as<vector<string> >(), conf[\"source\"].as<string>());\n  cerr << \"Loaded \" << ds.size() << \" references for scoring with \" << loss_function << endl;\n  Hypergraph hg;\n  string last_file;\n  ReadFile in_read(conf[\"input\"].as<string>());\n  istream &in=*in_read.stream();\n  while(in) {\n    string line;\n    getline(in, line);\n    if (line.empty()) continue;\n    istringstream is(line);\n    int sent_id;\n    string file, s_origin, s_axis;\n    // path-to-file (JSON) sent_ed starting-point search-direction\n    is >> file >> sent_id >> s_origin >> s_axis;\n    SparseVector<double> origin;\n    assert(ReadSparseVectorString(s_origin, &origin));\n    SparseVector<double> axis;\n    assert(ReadSparseVectorString(s_axis, &axis));\n    // cerr << \"File: \" << file << \"\\nAxis: \" << axis << \"\\n   X: \" << origin << endl;\n    if (last_file != file) {\n      last_file = file;\n      ReadFile rf(file);\n      HypergraphIO::ReadFromJSON(rf.stream(), &hg);\n    }\n    ViterbiEnvelopeWeightFunction wf(origin, axis);\n    ViterbiEnvelope ve = Inside<ViterbiEnvelope, ViterbiEnvelopeWeightFunction>(hg, NULL, wf);\n    ErrorSurface es;\n    ComputeErrorSurface(*ds[sent_id], ve, &es, type, hg);\n    //cerr << \"Viterbi envelope has \" << ve.size() << \" segments\\n\";\n    // cerr << \"Error surface has \" << es.size() << \" segments\\n\";\n    string val;\n    es.Serialize(&val);\n    cout << 'M' << ' ' << s_origin << ' ' << s_axis << '\\t';\n    B64::b64encode(val.c_str(), val.size(), &cout);\n    cout << endl << flush;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "71dda6d7b236e6237a617643abf5f870a9152298", "size": 3744, "ext": "cc", "lang": "C++", "max_stars_repo_path": "vest/mr_vest_map.cc", "max_stars_repo_name": "agesmundo/FasterCubePruning", "max_stars_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "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": "vest/mr_vest_map.cc", "max_issues_repo_name": "agesmundo/FasterCubePruning", "max_issues_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "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": "vest/mr_vest_map.cc", "max_forks_repo_name": "agesmundo/FasterCubePruning", "max_forks_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T12:44:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:44:54.000Z", "avg_line_length": 33.7297297297, "max_line_length": 107, "alphanum_fraction": 0.6431623932, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17035914897391394}}
{"text": "// Copyright (c) 2015-2019 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 \"ambiguous_read_fraction.hpp\"\n\n#include <algorithm>\n#include <iterator>\n\n#include <boost/variant.hpp>\n\n#include \"core/tools/read_assigner.hpp\"\n#include \"core/types/allele.hpp\"\n#include \"io/variant/vcf_record.hpp\"\n#include \"io/variant/vcf_spec.hpp\"\n#include \"utils/genotype_reader.hpp\"\n#include \"../facets/samples.hpp\"\n#include \"../facets/overlapping_reads.hpp\"\n#include \"../facets/read_assignments.hpp\"\n\nnamespace octopus { namespace csr {\n\nconst std::string AmbiguousReadFraction::name_ = \"ARF\";\n\nstd::unique_ptr<Measure> AmbiguousReadFraction::do_clone() const\n{\n    return std::make_unique<AmbiguousReadFraction>(*this);\n}\n\nMeasure::ResultType AmbiguousReadFraction::get_default_result() const\n{\n    return std::vector<boost::optional<double>> {};\n}\n\nMeasure::ResultType AmbiguousReadFraction::do_evaluate(const VcfRecord& call, const FacetMap& facets) const\n{\n    const auto& samples = get_value<Samples>(facets.at(\"Samples\"));\n    const auto& reads = get_value<OverlappingReads>(facets.at(\"OverlappingReads\"));\n    const auto& assignments = get_value<ReadAssignments>(facets.at(\"ReadAssignments\")).haplotypes;\n    std::vector<boost::optional<double>> result {};\n    result.reserve(samples.size());\n    for (const auto& sample : samples) {\n        boost::optional<double> sample_result {};\n        const auto num_overlapping_reads = count_overlapped(reads.at(sample), call);\n        if (num_overlapping_reads > 0) {\n            if (assignments.count(sample) == 1) {\n                const auto num_ambiguous_reads = count_overlapped(assignments.at(sample).ambiguous_wrt_reference, call);\n                sample_result = static_cast<double>(num_ambiguous_reads) / num_overlapping_reads;\n            } else {\n                sample_result = 0;\n            }\n        }\n        result.push_back(sample_result);\n    }\n    return result;\n}\n\nMeasure::ResultCardinality AmbiguousReadFraction::do_cardinality() const noexcept\n{\n    return ResultCardinality::samples;\n}\n\nconst std::string& AmbiguousReadFraction::do_name() const\n{\n    return name_;\n}\n\nstd::string AmbiguousReadFraction::do_describe() const\n{\n    return \"Fraction of reads overlapping the call that cannot be assigned to a unique haplotype\";\n}\n\nstd::vector<std::string> AmbiguousReadFraction::do_requirements() const\n{\n    return {\"Samples\", \"OverlappingReads\", \"ReadAssignments\"};\n}\n\n} // namespace csr\n} // namespace octopus\n", "meta": {"hexsha": "293bfc2ce279eb21945656493ed49f5c2d4e119c", "size": 2533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/csr/measures/ambiguous_read_fraction.cpp", "max_stars_repo_name": "gunjanbaid/octopus", "max_stars_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "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/csr/measures/ambiguous_read_fraction.cpp", "max_issues_repo_name": "gunjanbaid/octopus", "max_issues_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_issues_repo_licenses": ["MIT"], "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/csr/measures/ambiguous_read_fraction.cpp", "max_forks_repo_name": "gunjanbaid/octopus", "max_forks_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_forks_repo_licenses": ["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.0632911392, "max_line_length": 120, "alphanum_fraction": 0.7193051717, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.17023067221509314}}
{"text": "#ifndef INCLUDED_STDDEFX\n#include \"stddefx.h\"\n#define INCLUDED_STDDEFX\n#endif\n\n// Library headers.\n#ifndef INCLUDED_FUNCTIONAL\n#include <functional>\n#define INCLUDED_FUNCTIONAL\n#endif\n\n#ifndef INCLUDED_BOOST_BIND\n#include <boost/bind.hpp>\n#define INCLUDED_BOOST_BIND\n#endif\n\n// PCRaster library headers.\n#ifndef INCLUDED_DAL_MATHUTILS\n#include \"dal_MathUtils.h\"\n#define INCLUDED_DAL_MATHUTILS\n#endif\n\n#ifndef INCLUDED_DISCR_BLOCK\n#include \"discr_block.h\"\n#define INCLUDED_DISCR_BLOCK\n#endif\n\n#ifndef INCLUDED_DISCR_BLOCKDATA\n#include \"discr_blockdata.h\"\n#define INCLUDED_DISCR_BLOCKDATA\n#endif\n\n#ifndef INCLUDED_DISCR_RASTERDATA\n#include \"discr_rasterdata.h\"\n#define INCLUDED_DISCR_RASTERDATA\n#endif\n\n#ifndef INCLUDED_DISCR_VOXELSTACK\n#include \"discr_voxelstack.h\"\n#define INCLUDED_DISCR_VOXELSTACK\n#endif\n\n// Module headers.\n#ifndef INCLUDED_BLOCK_COMPACTORS\n#include \"block_compactors.h\"\n#define INCLUDED_BLOCK_COMPACTORS\n#endif\n\n#ifndef INCLUDED_BLOCK_DEHAANCOMPACTOR\n#include \"block_dehaancompactor.h\"\n#define INCLUDED_BLOCK_DEHAANCOMPACTOR\n#endif\n\n#ifndef INCLUDED_BLOCK_TYPES\n#include \"block_types.h\"\n#define INCLUDED_BLOCK_TYPES\n#endif\n\n\n\n/*!\n  \\file\n  This file contains the implementation of the Add class.\n*/\n\n\n\nnamespace block {\n\nvoid noCompactionAdd(\n         discr::Block& block,\n         size_t nrVoxels,\n         REAL4 thickness)\n{\n  block.addVoxels(nrVoxels, thickness);\n}\n\n\n\nvoid noCompactionAdd(\n         discr::Block& block,\n         discr::RasterData<REAL4> const& thickness)\n{\n  DEVELOP_PRECOND(\n         thickness.raster() == &static_cast<discr::Raster const&>(block) ||\n         *thickness.raster() == static_cast<discr::Raster const&>(block));\n\n  for(size_t i = 0; i < block.nrCells(); ++i) {\n    if(thickness.isMV(i)) {\n      block.cell(i).setMV();\n    }\n    else if(!block.cell(i).isMV()) {\n      DEVELOP_PRECOND(dal::greaterOrComparable(thickness.cell(i), REAL4(0.0)));\n      if(thickness.cell(i) > REAL4(0.0)) {\n        block.addVoxels(i, 1, thickness.cell(i));\n      }\n    }\n  }\n}\n\n\n\n//!\n/*!\n  \\param     .\n  \\return    .\n  \\exception .\n  \\warning   .\n  \\sa        .\n  \\todo      Document each argument. Handle compaction. Compaction function\n             should be an argument for efficiency.\n  \\todo      Check implementation with Derek.\n\n  This function is called by a function which handles the argument checking.\n  We can assume here that all arguments have valid values.\n*/\nstatic void mackeyBridgeAdd(\n         discr::Block& block,\n         size_t index,\n         std::vector<REAL4>& originalThickness,\n         REAL4 thickness,\n         REAL4 maxVoxelThickness,\n         std::vector<INT4>& sediment,\n         INT4 sedimentToAdd,\n         Compactors<MackeyBridgeCompactor> const& compactors)\n{\n  double depth;\n  double voxelThickness;\n\n  discr::VoxelStack& stack(block.cell(index));\n\n  if(!stack.empty()) {\n\n    // --------------------------------\n    // PROCESS EXISTING STACK OF VOXELS\n    // --------------------------------\n    // Compact existing sediment, from top to bottom. Don't change the\n    // voxel at the top.\n    depth = stack[stack.size() - 1];\n\n    for(int i = stack.size() - 2; i >= 0; --i) {\n\n      // The depth of burial of the voxel is the thickness of\n      // the voxels on top of the current voxel (which are already\n      // compacted in this loop).\n      // Compact the voxel.\n      DEVELOP_PRECOND(!pcr::isMV(originalThickness[i]));\n      DEVELOP_PRECOND(originalThickness[i] > 0.0);\n      // stack[i] = compactors.compact(sedimentToAdd, originalThickness[i],\n      //        depth + thickness);\n      stack[i] = compactors.compactor(sedimentToAdd)(originalThickness[i],\n             depth + thickness);\n\n      // Calculate depth of next voxel.\n      depth += stack[i];\n    }\n\n    DEVELOP_PRECOND(!stack.empty());\n    size_t i = stack.size() - 1;   // Index of top voxel.\n    DEVELOP_PRECOND(!pcr::isMV(originalThickness[i]));\n    DEVELOP_PRECOND(originalThickness[i] > 0.0);\n\n    if(sediment[i] == sedimentToAdd &&\n             dal::comparable(originalThickness[i], stack[i]) &&\n             maxVoxelThickness > originalThickness[i]) {\n\n      // The top voxel:\n      //   - has the same sediment type, and\n      //   - is not compacted, and\n      //   - has room for new material\n\n      // Uncompacted thickness to add, including stuff already in top voxel.\n      thickness += originalThickness[i];\n\n      if(maxVoxelThickness >= thickness) {\n\n        // The current top voxel stays the top voxel. We've just enough\n        // new material to add some to the top voxel and that's it.\n        originalThickness[i] = thickness;\n        stack[i] = originalThickness[i];\n        thickness -= thickness; // Should be 0.0 by now.\n      }\n      else {\n\n        // The current top voxel will be buried with other material.\n        // We fill it untill its maximum original thickness is reached\n        // and compact it.\n        DEVELOP_PRECOND(thickness > maxVoxelThickness);\n        originalThickness[i] = maxVoxelThickness;\n        thickness -= maxVoxelThickness;   // Should be > 0.0 here.\n        // stack[i] = compactors.compact(sediment[i], originalThickness[i],\n        //       thickness);\n        stack[i] = compactors.compactor(sediment[i])(originalThickness[i],\n              thickness);\n        DEVELOP_PRECOND(thickness > REAL4(0.0));\n      }\n    }\n    else {\n\n      // The top voxel:\n      //   - has a different sediment type, or\n      //   - is already compacted, or\n      //   - has no room for new material\n      // We can treat the top voxel as all lower voxels: compact.\n      // stack[i] = compactors.compact(sediment[i], stack[i], thickness);\n      stack[i] = compactors.compactor(sediment[i])(stack[i], thickness);\n    }\n  }\n\n  // Check if there's accomodation space left to fill.\n  if(thickness > REAL4(0.0)) {\n\n    // ------------------\n    // PROCESS NEW VOXELS\n    // ------------------\n    // Add and compact new voxels from bottom to top. Continue untill\n    // the available space left is less than the height of one\n    // uncompacted voxel.\n    voxelThickness = maxVoxelThickness;\n    size_t i = stack.size();\n\n    // Add whole voxels, with thickness maxVoxelThickness.\n    for(; dal::greaterOrComparable(thickness, maxVoxelThickness);\n         thickness -= voxelThickness, ++i) {\n\n      voxelThickness = compactors.compactor(sedimentToAdd)(maxVoxelThickness,\n         thickness - maxVoxelThickness);\n\n      // Add a new voxel with thickness voxelThickness.\n      block.addVoxel(index, voxelThickness);\n      DEVELOP_PRECOND(i == stack.size() - 1);\n      sediment[i] = sedimentToAdd;\n      originalThickness[i] = maxVoxelThickness;\n    }\n\n    // Fails\n    // DEVELOP_PRECOND(dal::greaterOrComparable(thickness, REAL4(0.0)));\n\n    // Now we have filled up thickness except for a small amount of\n    // space left which is less than maxVoxelThickness. Here we add a\n    // uncompacted voxel to fill up the last part of thickness.\n    if(thickness > REAL4(0.0)) {\n\n      // Add a new voxel with thickness thickness.\n      DEVELOP_PRECOND(sediment.size() == stack.size());\n      DEVELOP_PRECOND(originalThickness.size() == stack.size());\n      block.addVoxel(index, thickness);\n      DEVELOP_PRECOND(i == stack.size() - 1);\n      DEVELOP_POSTCOND(sediment.size() == stack.size());\n      DEVELOP_POSTCOND(originalThickness.size() == stack.size());\n      sediment[i] = sedimentToAdd;\n      originalThickness[i] = thickness;\n    }\n  }\n}\n\n\n\n//! Adds sediment to an existing block with sediments, thereby changing the spatial extent of the block and all its data subjects.\n/*!\n  \\param     block Block discretisation to add to. This will be changed.\n  \\param     originalThickness Original thicknesses (before compaction)\n             of the voxels in the block. This will be changed.\n  \\param     sediment Block data with the current values. This will be changed.\n  \\param     thickness Amount of sediment to add to the block data.\n  \\param     maxVoxelThickness Maximum thickness of newly created voxels.\n  \\return    .\n  \\exception .\n  \\warning   .\n  \\sa        .\n\n  Not an easy function to use, requires some bookkeeping by the user.\n  This is also not a general function, it is limited to the domain of\n  sedimentation and refers directly to sediment and compaction.\n\n  New voxels created in the nominal block data will have the default\n  value set for this argument. This is a common rule in this library:\n  when the dicretisation is extended, all data objects are extended\n  too. Newly created voxels will be set to the default value set for\n  each data object.\n\n  add(block, originalThickness, sediment, thickness, maxVoxelThickness);\n*/\nvoid mackeyBridgeAdd(discr::Block& block,\n         discr::BlockData<REAL4>& originalThickness,\n         discr::BlockData<INT4>& sediment,\n         discr::RasterData<REAL4>const & thickness,\n         REAL4 maxVoxelThickness,\n         Compactors<MackeyBridgeCompactor> const& compactors)\n{\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(originalThickness);\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(sediment);\n\n  DEVELOP_PRECOND(\n         originalThickness.block() == &block ||\n         *originalThickness.block() == block);\n  DEVELOP_PRECOND(\n         sediment.block() == &block ||\n         *sediment.block() == block);\n  DEVELOP_PRECOND(\n         thickness.raster() == &static_cast<discr::Raster const&>(block) ||\n         *thickness.raster() == static_cast<discr::Raster const&>(block));\n  PRECOND(!pcr::isMV(maxVoxelThickness));\n  PRECOND(maxVoxelThickness > 0.0);\n\n  for(size_t i = 0; i < block.nrCells(); ++i) {\n    if(!block.cell(i).isMV()) {\n      if(!pcr::isMV(sediment.defaultValue().cell(i)) && (!thickness.isMV(i))) {\n        PRECOND(dal::greaterOrComparable(thickness.cell(i), REAL4(0.0)));\n        mackeyBridgeAdd(block, i,\n           originalThickness.cell(i), thickness.cell(i), maxVoxelThickness,\n           sediment.cell(i), sediment.defaultValue().cell(i), compactors);\n      }\n    }\n  }\n\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(originalThickness);\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(sediment);\n}\n\n\n\nstatic void deHaanAdd(\n         discr::Block& block,\n         size_t index,\n         std::vector<INT4>& sediment,\n         INT4 sedimentToAdd,\n         std::vector<REAL4>& initialThickness,\n         std::vector<REAL4>& cummulativeLoad,\n         std::vector<REAL4>& cummulativeDuration,\n         REAL4 duration,\n         REAL4 thickness,\n         Compactors<DeHaanCompactor> const& compactors)\n{\n  DEVELOP_PRECOND(!(thickness < 0.0));\n\n  if(dal::comparable(thickness, REAL4(0.0))) {\n    return;\n  }\n\n  discr::VoxelStack& stack(block.cell(index));\n\n  DeHaanCompactor const& compactor(compactors.compactor(sedimentToAdd));\n\n  // -----------------\n  // PROCESS NEW VOXEL\n  // -----------------\n\n  // Add new load to current stack of loads.\n  REAL4 load = 0.5 * thickness * compactor.buoyancy();\n  std::transform(cummulativeLoad.begin(), cummulativeLoad.end(),\n         cummulativeLoad.begin(),\n         boost::bind(std::plus<REAL4>(), _1, load));\n  std::transform(cummulativeDuration.begin(), cummulativeDuration.end(),\n         cummulativeDuration.begin(),\n         boost::bind(std::plus<REAL4>(), _1, duration));\n\n  // Add voxel to the discretisation which will signal the attributes.\n  block.addVoxel(index, compactor(thickness, load, duration));\n\n  // Set attribute values for newly create voxels.\n  initialThickness.back() = thickness;\n  cummulativeLoad.back() = load;\n  DEVELOP_PRECOND(dal::comparable(cummulativeDuration.back(), duration));\n  DEVELOP_PRECOND(sediment.back() == sedimentToAdd);\n\n  if(stack.size() > 1) {\n    // --------------------------------\n    // PROCESS EXISTING STACK OF VOXELS\n    // --------------------------------\n    // Compact existing sediment.\n    for(size_t i = 0; i < stack.size() - 1; ++i) {\n      stack[i] = compactor(initialThickness[i], cummulativeLoad[i],\n         cummulativeDuration[i]);\n    }\n  }\n}\n\n\n\nvoid deHaanAdd(\n         discr::Block& block,\n         discr::BlockData<INT4>& sediment,\n         discr::BlockData<REAL4>& initialThickness,\n         discr::BlockData<REAL4>& cummulativeLoad,\n         discr::BlockData<REAL4>& cummulativeDuration,\n         discr::RasterData<REAL4> const& thickness,\n         Compactors<DeHaanCompactor> const& compactors)\n{\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(sediment);\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(initialThickness);\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(cummulativeLoad);\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(cummulativeDuration);\n\n  for(size_t i = 0; i < block.nrCells(); ++i) {\n    if(!block.cell(i).isMV()) {\n      if(!pcr::isMV(sediment.defaultValue().cell(i)) && !thickness.isMV(i)) {\n        PRECOND(dal::greaterOrComparable(thickness.cell(i), REAL4(0.0)));\n        deHaanAdd(block, i, sediment.cell(i), sediment.defaultValue().cell(i),\n              initialThickness.cell(i), cummulativeLoad.cell(i),\n              cummulativeDuration.cell(i),\n              cummulativeDuration.defaultValue().cell(i),\n              thickness.cell(i), compactors);\n      }\n    }\n  }\n\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(sediment);\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(initialThickness);\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(cummulativeLoad);\n  DEVELOP_CHECK_BLOCK_DATA_CONSISTENCY(cummulativeDuration);\n}\n\n} // namespace block\n\n", "meta": {"hexsha": "dd8b85e68abdcaf82e5912cefa0849749e062f0b", "size": 13257, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrblock/block_add.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "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": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrblock/block_add.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrblock/block_add.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.8677884615, "max_line_length": 130, "alphanum_fraction": 0.661537301, "num_tokens": 3281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.17023066539325363}}
{"text": "//\n//  bpp_c.hpp for mammal\n//  PhyloAcc_init2\n//\n//  Created by hzr on 4/19/16.\n//  Copyright \u00a9 2016 hzr. All rights reserved.\n//\n\n#ifndef bpp_c_hpp\n#define bpp_c_hpp\n\n\n#include <stdio.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_sf_gamma.h>\n#include <string>\n#include <armadillo>\n#include <cassert>\n\n#include <cmath>\n#include <sys/time.h>\n\n#include <map>\n#include <fstream>\n#include <vector>\n#include <set>\n#include <sstream>\n#include <algorithm>\n\n#include \"newick.h\"\n#include \"profile.h\"\n#include \"bpp.hpp\"\n#include \"utils.h\"\n\n\nusing namespace std;\nusing namespace arma;\n\nclass BPP_C\n{\n    private:\n    \n    int CC;  //current number of elements\n    int GG; //base pairs current elements\n    \n    int S;\n    int N;\n    \n    vector< vector<vec > > ambiguousS_null;  //base * species# * 4;\n    \n    int    (*children2)[2];  //children from pruned tree\n    double  *distances2;\n    int *parent2;\n    int root;\n    vec pi;\n    vec log_pi;\n    \n    \n    vector<int> nodes;\n    vector<int> internal_nodes;\n    vector<bool> missing;\n    vector<int> upper_c;\n    vector<int> upper_conserve_c;\n    \n   // double prior_glr[3];\n    double prior_l_a, prior_l_b;\n     double prior_l2_a, prior_l2_b;\n     double prior_g_a, prior_g_b;\n    double ratio0;\n    double ratio1;\n    int num_burn;   // num of burn-in updates\n    int num_mcmc;   // num of MCMC updates\n    int num_thin;   // num of updates between two samples\n    int adaptive_freq = 100;\n   \n    vector<int>Z ; //N *0, accelerate(time,0-1), loss(-1)\n    vector<int>fixZ ;\n    vector < vector<int> > Tg; //current history for each element, GG*N\n    \n    \n    \n    //buffer P(zt|zt-1,Hg)\n    vector<vec> log_prob_back;\n    \n    //get P(X|theta)\n    vector< vector<double> >  log_emission; //( N-1)*2\n    \n    \n    \n    // MCMC updating states\n    int m;                                      // current MCMC step\n    \n    vector<mat> log_TM_Int;\n    \n    vec prior_z;\n    \n    vector<mat > log_cache_TM_neut;\n    vector<mat > log_cache_TM_cons;\n    vector<mat > log_cache_TM_null;\n    \n    \n    vector< vector<vec> > lambda;  //GG *N *acgt\n    \n\n    \n    \n    // samples to output\n    double MaxLoglik;\n    int Max_m;\n    vector <int > Max_Z;\n    \n    vector< double >  trace_loglik;  //P(X|Z, TM, r)\n    vector< double >  trace_full_loglik;  //P(X,Z,r|TM)\n    vector< vector<int> > trace_Z;  //iteration * Species * {0,1,2}, only for init\n    vector <double> trace_n_rate;  //iter*element\n    vector <double> trace_c_rate;\n    \n    vector <double> trace_l_rate;  //iter*element\n    vector <double> trace_l2_rate;\n    vector <double> trace_g_rate;\n    \n    int accept_n_rate = 0;\n    int accept_c_rate = 0;  //how many accepted in current cycle\n    \n    double prop_n;  //for adaptive MCMC, changed by acceptance rate\n    double prop_c;\n    \n    \n    \n    // GSL random number generator\n    gsl_rng * RNG;\n    \n    time_t last_time;\n    \n    unsigned long int seed;\n\n    \npublic:\n    bool failure = false;\n    bool verbose; \n    \n    BPP_C(int c, PhyloProf _prof, BPP& bpp, char gapchar, double missing_thres, bool & filter, bool _verbose, double consToMis, bool prune=0, double revgap=0, int min_length =50, double nconsToMis = 1)//, double _indel)\n    {\n        \n        RNG = gsl_rng_alloc(gsl_rng_default);\n        gsl_rng_set(RNG, bpp.seed);\n        \n        num_burn = bpp.num_burn;   // num of burn-in updates\n        num_mcmc = bpp.num_mcmc;   // num of MCMC updates\n        adaptive_freq = bpp.num_thin;   // num of updates between two samples, 100\n        \n       \n        N = bpp.N;\n        CC = c;\n        GG =bpp.element_size[c];\n        \n        if(GG < min_length)\n        {\n            filter = true;\n            return;\n        }\n        \n        Tg = vector<vector<int> > (GG, vector<int>(N, -1));\n        root = N-1;\n        S = bpp.S;\n        \n        lambda = vector< vector<vec> >(GG, vector<vec>(N, zeros<vec>(bpp.num_base)));\n        \n        \n        ratio0 = bpp.ratio0;  //no use\n        ratio1 = bpp.ratio1; //no use\n        \n        verbose = _verbose;\n\n        \n        log_cache_TM_neut = vector<mat >(N, zeros<mat> (bpp.num_base,bpp.num_base));\n        log_cache_TM_cons = vector<mat >(N, zeros<mat> (bpp.num_base,bpp.num_base));\n        log_cache_TM_null = vector<mat >(N, zeros<mat> (bpp.num_base,bpp.num_base));\n        \n        log_TM_Int = vector<mat >(N, zeros<mat>(3,2));\n        \n//        for(size_t i =0 ;i <3; i++)  // hyperparameter for loss and gain rates\n//        {\n//            prior_glr[i] = bpp.prior_glr[i];\n//        }\n       \n        \n        prior_l_a = bpp.prior_l_a;\n        prior_l_b = bpp.prior_l_b;\n        prior_g_a = bpp.prior_g_a;\n        prior_g_b = bpp.prior_g_b;\n        prior_l2_a = bpp.prior_l2_a;\n        prior_l2_b = bpp.prior_l2_b;\n        \n        \n        prior_z = zeros<vec>(3);\n        prior_z[0] = 0.5;  // prior for root\n        prior_z[1] = 0.5;\n        prior_z = log(prior_z);\n        \n        \n        if(verbose) cout << \"Init lambda\" <<endl;\n        vector<int> num_missing = vector<int> (S,0);\n        \n        int st = bpp.element_start[CC];\n        //get leaves lambda\n        for(int s=0; s<S; s++)\n        {\n            //const char* y = bpp.X[c][s].c_str();\n            string y = _prof.X[s].substr(st, st+GG);\n            \n            for(int g=0; g<GG; g++){\n                lambda[g][s].fill(LOG_ZERO);\n//                if( y[g]== gapchar || y[g]=='n')\n//                {\n//                    num_missing[s] ++;\n//                    //Tg[g][s] = 4;  // for missing base pair\n//                }\n                switch (y[g])\n                {\n                    case 'a':\n                        lambda[g][s][0] = 0; Tg[g][s] = 0; break;\n                    case 'c':\n                        lambda[g][s][1] = 0; Tg[g][s] = 1; break;\n                    case 'g':\n                        lambda[g][s][2] = 0; Tg[g][s] = 2; break;\n                    case 't':\n                        lambda[g][s][3] = 0; Tg[g][s] = 3; break;\n                    case 'r':\n                        lambda[g][s][0] = 0;\n                        lambda[g][s][2] = 0;\n                        break;\n                    case 'y':\n                        lambda[g][s][1] = 0;\n                        lambda[g][s][3] = 0;   break;\n                    case 'k':\n                        lambda[g][s][2] = 0;\n                        lambda[g][s][3] = 0;  break;\n                    case 'm':\n                        lambda[g][s][0] = 0;\n                        lambda[g][s][1] = 0;  break;\n                    case 's':\n                        lambda[g][s][1] = 0;\n                        lambda[g][s][2] = 0;   break;\n                    case 'w':\n                        lambda[g][s][0] = 0;\n                        lambda[g][s][3] = 0;   break;\n                    // case gapchar:\n                    //     if(bpp.num_base <= 4){\n                    //         for(int b =0;b<bpp.num_base;b++) lambda[g][s][b] = 0;\n                    //     }\n                    //     else{\n                    //         lambda[g][s][4] = 0;\n                    //     }\n                    //     Tg[g][s] = 4; break;\n                    default:\n                        for(int b =0;b<bpp.num_base;b++) lambda[g][s][b] = 0;\n                        if(y[g] == gapchar) {Tg[g][s] = 4; break;}\n                        Tg[g][s] = 5; \n                }\n            }\n            \n        }\n        \n        \n        // remove columns with nearly all gaps\n        if(revgap < 1)\n        {\n            //remove bases with 'n'/'*' or gap in more than 80% species\n            vector<int> missingBase;\n            for(int g=0; g<GG; g++)\n            {\n                int mis = 0;\n                for(int s=0; s<S; s++){\n                    if(Tg[g][s] >= 4)\n                    {\n                        mis++;\n                    }\n                }\n                if(mis > S*revgap)\n                {\n                    missingBase.push_back(g);\n                }\n                \n            }\n            \n            if(GG - missingBase.size() < min_length)\n            {\n                filter = true;\n                return;\n            }\n            \n            for(vector<int>::reverse_iterator it = missingBase.rbegin(); it!= missingBase.rend(); it ++)\n            {\n                lambda.erase(lambda.begin() + *it);\n                Tg.erase(Tg.begin() + *it);\n            }\n            \n            GG = lambda.size();\n        }\n        \n        // get gap species after filtering\n        for(int s=0; s<S; s++)\n        {\n            for(int g= 0; g < GG; g++)\n            {\n                if( Tg[g][s] == 4)\n                {\n                    num_missing[s] ++;\n                }\n                \n            }\n        }\n\n        ambiguousS_null = vector<vector<vec> > (GG, vector<vec>(S,zeros<vec>(bpp.num_base)));\n        \n        \n        children2    = new int[N][2];\n        parent2      = new int[N];\n        distances2   = new double[N];\n        for(int i=0; i<N; i++)\n        {\n            children2[i][0] = bpp.children[i][0];\n            children2[i][1] = bpp.children[i][1];\n            parent2[i] = bpp.parent[i];\n            distances2[i] = bpp.distances[i];\n        }\n       \n        // set missing\n        missing = vector<bool>(N, false);\n        \n        for(int s=S; s<N; s++)\n        {\n            int* p = children2[s];\n            for(int cc=0;cc<2;cc++)\n            {\n                int chi = p[cc];\n                if(chi<S && num_missing[chi]>missing_thres*GG)\n                {\n                    \n                    missing[chi] = true;\n                    \n                }\n            }\n            \n            if(missing[p[0]] && missing[p[1]]) {\n                missing[s] = true;\n                \n            }\n        }\n        \n//        cout << \"missing: \";\n//        for(int s = 0; s<N;s++)\n//        {\n//            if(missing[s]) cout << s << \" \";\n//        }\n//        cout <<endl;\n        \n        \n        int ct =0;\n        for(vector<int>::iterator it = bpp.conservedgroup.begin(); it<bpp.conservedgroup.end();it++)\n        {\n            if(missing[*it]){\n                ct +=1;\n            }\n        }\n        \n        if(ct > bpp.conserve_prop * bpp.conservedgroup.size())\n        {\n            filter = true;\n            return;\n        }\n        \n        \n        \n        \n        //prune tree if outgroup not conserved, find root\n        if(prune)\n        {\n            set<int> alls;\n            for(int s=0; s<N; s++) alls.insert(s);\n            getSubtree_missing(N-1, alls, -1);\n        }else{\n            getSubtree_missing(N-1, bpp.upper, -1);\n        }\n        \n        \n        \n        parent2[root] = N;  //parent2 not correct for all nodes, but children2 is correct\n    \n        if(verbose) cout << \"root: \" << root << endl;\n        \n        \n        getSubtree(root, nodes);\n        for(vector<int>::iterator it = nodes.begin(); it < nodes.end(); it++)\n        {\n            if(*it>=S)\n            {\n                internal_nodes.push_back(*it);  // internal nodes\n            }\n            \n            if(bpp.upper.find(*it)!=bpp.upper.end())\n            {\n                    upper_c.push_back(*it);\n            }\n            \n            if(bpp.upper_conserve.find(*it)!=bpp.upper_conserve.end())\n            {\n                upper_conserve_c.push_back(*it);\n            }\n\n        }\n        \n        \n        // if both children are missing, can't infer the parent's base pair, just set to 'missing'\n        for(vector<int>::iterator it = internal_nodes.begin(); it < internal_nodes.end(); it++)\n        {\n            int* p = children2[*it];\n            for(int g=0; g<GG; g++){\n                if(Tg[g][p[0]] >= bpp.num_base && Tg[g][p[1]]>= bpp.num_base)\n                {\n                    Tg[g][*it] = bpp.num_base;\n                    \n                }\n            }\n            \n        }\n        \n        log_pi = bpp.log_pi;\n        \n  \n        // from initMCMC\n        trace_loglik = vector<double >(num_burn+num_mcmc, 0); //P(X|Z, r)\n        trace_full_loglik = vector<double >(num_burn+num_mcmc, 0); //P(X, Z, r)\n        trace_Z = vector<vector<int> >(num_burn+num_mcmc, vector<int>(N,1));\n        trace_n_rate = vector<double >(num_burn+num_mcmc, 0);\n        trace_c_rate = vector<double >(num_burn+num_mcmc, 0);\n        trace_l_rate = vector<double >(num_burn+num_mcmc, 0);\n        trace_g_rate = vector<double >(num_burn+num_mcmc, 0);\n        trace_l2_rate = vector<double >(num_burn+num_mcmc, 0);\n\n        //getEmission_ambig();\n        \n        \n        \n        \n        log_emission = vector<vector<double> >(N, vector<double>(3,0));\n        \n        \n        for(int s=0;s<N;s++)  // For all nodes !!! ....only terminal nodes, S\n        {\n            if(missing[s])\n            {\n                //            log_prob_back[s][2] += log(nconsTomis);\n                //            log_prob_back[s][1] = log(consTomis) ;//-INFINITY;\n                //            log_prob_back[s][0] += log(nconsTomis);\n                \n                log_emission[s][2] = log(nconsToMis);\n                log_emission[s][1] = log(consToMis) ;//-INFINITY;\n                log_emission[s][0] = log(nconsToMis);\n                \n                //fixZ[s] = 0; // ?\n                \n            }\n            //        }else{\n            //            \n            //            log_prob_back[s][2] += log(1 - nconsTomis);\n            //            log_prob_back[s][1] = log( 1 - consTomis) ;//-INFINITY;\n            //            log_prob_back[s][0] += log(1 - nconsTomis);\n            //            \n            //\n            //        }\n        }\n\n    }\n    \n    \n    \n    \n    ~BPP_C()\n    {\n        gsl_rng_free(RNG);\n    }\n\n    void getSubtree(int root, set<int>& child, vector<int> & visited_init);\n    void getSubtree(int root, vector<int> & visited_init);\n    void getSubtree_missing(int root, set<int>& upper, int child);\n    \n    void getEmission_ambig();\n    void initMCMC(int iter, BPP&bpp, int resZ);\n    void Update_Tg(int g, vector<bool> visited,BPP& bpp, bool tosample);\n    void getUpdateNode(vector<int> changedZ, vector<bool> & visited_init);\n    void MonitorChain(int m, BPP &bpp, double &loglik, const double add_loglik, const int resZ) ;\n    void getUpdateNode(bool neut,vector<bool> & visited_init);\n    double log_f_Xz(vector<bool> visited, vector<vector<vec>>& lambda_tmp, bool neut, double propos, BPP& bpp);\n    double sample_rate(int resZ, double old_rate, bool neut, vector<bool> visited, double & loglik_old, BPP& bpp, int M =1, bool adaptive = true, double adaptive_factor = 0.5);\n    void Gibbs(int iter, BPP &bpp, ofstream & outZ, string output_path,string output_path2,int resZ, bool UpR, bool UpHyper, double lrate_prop, double grate_prop);\n    vector<int> Update_Z_subtree(int num_base = 5, bool prior = false);\n    void Output_init(string output_path, string output_path2, BPP& bpp,ofstream& outZ, int resZ);\n    void Output_sampling(int iter, string output_path2, BPP &bpp, int resZ);\n    \n    void getEmission(int num_base);\n    \n    vector<int>  Move_Z(int & propConf, int & revConf,  int & changeZ);\n    double log_f_Xz(vec log_pi, int num_base, vector<int>& Z, vector<mat> & log_cache_TM_neut,  vector<mat> & log_cache_TM_cons);\n    double Update_f_Xz(vec log_pi, int num_base, vector<int>& Z, vector<mat> & log_cache_TM_neut, vector<mat> & log_cache_TM_cons, vector<bool> & visited);\n    void log_f_Z(vector<int>& Z, vector<mat> & log_Int, double & MH_ratio_g, double & MH_ratio_l);\n    \n    //void Eval(BPP&bpp,int resZ); //, int numH,int numHZ);\n    void Eval2(BPP&bpp, int resZ);\n    //double prior_Z_subtree(vector<int> & tmpZ) ;\n    vector<double> prior_Z_subtree(vector< vector<int> > & configZ, vector< int > numConfigZ);\n    void sample_transition( double  & gr, double  & lr, double  & lr2);\n    \n};\n\n\n#endif /* bpp_c_hpp */\n", "meta": {"hexsha": "c5a6631407a157b78f8aa781b419c4d441c8892b", "size": 15905, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SRC/bpp_c.hpp", "max_stars_repo_name": "beyondpie/PhyloAcc", "max_stars_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-11T14:34:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T06:58:59.000Z", "max_issues_repo_path": "SRC/bpp_c.hpp", "max_issues_repo_name": "beyondpie/PhyloAcc", "max_issues_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T03:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T09:54:35.000Z", "max_forks_repo_path": "SRC/bpp_c.hpp", "max_forks_repo_name": "beyondpie/PhyloAcc", "max_forks_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-03T18:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T04:39:30.000Z", "avg_line_length": 30.5865384615, "max_line_length": 219, "alphanum_fraction": 0.4681546683, "num_tokens": 4147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.17022757646235456}}
{"text": "// Copyright (c) 2016 The UUV Simulator Authors.\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, 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/// \\file UnderwaterCurrentPlugin.cc\n\n#include <math.h>\n\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/bind.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <gazebo/gazebo.hh>\n#include <gazebo/msgs/msgs.hh>\n#include <gazebo/physics/Link.hh>\n#include <gazebo/physics/Model.hh>\n#include <gazebo/physics/PhysicsEngine.hh>\n#include <gazebo/physics/World.hh>\n#include <gazebo/transport/TransportTypes.hh>\n#include <sdf/sdf.hh>\n#include <dave_world_plugins/UnderwaterCurrentPlugin.hh>\n\nusing namespace gazebo;\n\nGZ_REGISTER_WORLD_PLUGIN(UnderwaterCurrentPlugin)\n\n/////////////////////////////////////////////////\nUnderwaterCurrentPlugin::UnderwaterCurrentPlugin()\n{\n  // Doing nothing for now\n}\n\n/////////////////////////////////////////////////\nUnderwaterCurrentPlugin::~UnderwaterCurrentPlugin()\n{\n#if GAZEBO_MAJOR_VERSION >= 8\n  this->updateConnection.reset();\n#else\n  event::Events::DisconnectWorldUpdateBegin(this->updateConnection);\n#endif\n}\n\n/////////////////////////////////////////////////\nvoid UnderwaterCurrentPlugin::\n  Load(physics::WorldPtr _world, sdf::ElementPtr _sdf)\n{\n  GZ_ASSERT(_world != NULL, \"World pointer is invalid\");\n  GZ_ASSERT(_sdf != NULL, \"SDF pointer is invalid\");\n\n  this->world = _world;\n  this->sdf = _sdf;\n\n  // Read the namespace for topics and services\n  this->ns = _sdf->Get<std::string>(\"namespace\");\n\n  gzmsg << \"Loading underwater world...\" << std::endl;\n  // Initializing the transport node\n  this->node = transport::NodePtr(new transport::Node());\n#if GAZEBO_MAJOR_VERSION >= 8\n  this->node->Init(this->world->Name());\n#else\n  this->node->Init(this->world->GetName());\n#endif\n  // Retrieve the velocity configuration, if existent\n  GZ_ASSERT(this->sdf->HasElement(\"constant_current\"),\n    \"Current configuration not available\");\n  sdf::ElementPtr currentVelocityParams = this->sdf->GetElement(\n    \"constant_current\");\n\n  // Read the topic names from the SDF file\n  if (currentVelocityParams->HasElement(\"topic\"))\n    this->currentVelocityTopic =\n      currentVelocityParams->Get<std::string>(\"topic\");\n  else\n    this->currentVelocityTopic = \"current_velocity\";\n\n  GZ_ASSERT(!this->currentVelocityTopic.empty(),\n    \"Empty ocean current velocity topic\");\n\n  if (currentVelocityParams->HasElement(\"velocity\"))\n  {\n    sdf::ElementPtr elem = currentVelocityParams->GetElement(\"velocity\");\n    if (elem->HasElement(\"mean\"))\n        this->currentVelModel.mean = elem->Get<double>(\"mean\");\n    if (elem->HasElement(\"min\"))\n        this->currentVelModel.min = elem->Get<double>(\"min\");\n    if (elem->HasElement(\"max\"))\n        this->currentVelModel.max = elem->Get<double>(\"max\");\n    if (elem->HasElement(\"mu\"))\n        this->currentVelModel.mu = elem->Get<double>(\"mu\");\n    if (elem->HasElement(\"noiseAmp\"))\n        this->currentVelModel.noiseAmp = elem->Get<double>(\"noiseAmp\");\n\n    GZ_ASSERT(this->currentVelModel.min < this->currentVelModel.max,\n      \"Invalid current velocity limits\");\n    GZ_ASSERT(this->currentVelModel.mean >= this->currentVelModel.min,\n      \"Mean velocity must be greater than minimum\");\n    GZ_ASSERT(this->currentVelModel.mean <= this->currentVelModel.max,\n      \"Mean velocity must be smaller than maximum\");\n    GZ_ASSERT(this->currentVelModel.mu >= 0 && this->currentVelModel.mu < 1,\n      \"Invalid process constant\");\n    GZ_ASSERT(this->currentVelModel.noiseAmp < 1 &&\n      this->currentVelModel.noiseAmp >= 0,\n      \"Noise amplitude has to be smaller than 1\");\n  }\n\n  this->currentVelModel.var = this->currentVelModel.mean;\n  gzmsg << \"Current velocity [m/s] Gauss-Markov process model:\" << std::endl;\n  this->currentVelModel.Print();\n\n  if (currentVelocityParams->HasElement(\"horizontal_angle\"))\n  {\n    sdf::ElementPtr elem =\n      currentVelocityParams->GetElement(\"horizontal_angle\");\n\n    if (elem->HasElement(\"mean\"))\n      this->currentHorzAngleModel.mean = elem->Get<double>(\"mean\");\n    if (elem->HasElement(\"min\"))\n      this->currentHorzAngleModel.min = elem->Get<double>(\"min\");\n    if (elem->HasElement(\"max\"))\n      this->currentHorzAngleModel.max = elem->Get<double>(\"max\");\n    if (elem->HasElement(\"mu\"))\n      this->currentHorzAngleModel.mu = elem->Get<double>(\"mu\");\n    if (elem->HasElement(\"noiseAmp\"))\n      this->currentHorzAngleModel.noiseAmp = elem->Get<double>(\"noiseAmp\");\n\n    GZ_ASSERT(this->currentHorzAngleModel.min <\n      this->currentHorzAngleModel.max,\n      \"Invalid current horizontal angle limits\");\n    GZ_ASSERT(this->currentHorzAngleModel.mean >=\n      this->currentHorzAngleModel.min,\n      \"Mean horizontal angle must be greater than minimum\");\n    GZ_ASSERT(this->currentHorzAngleModel.mean <=\n      this->currentHorzAngleModel.max,\n      \"Mean horizontal angle must be smaller than maximum\");\n    GZ_ASSERT(this->currentHorzAngleModel.mu >= 0 &&\n      this->currentHorzAngleModel.mu < 1,\n      \"Invalid process constant\");\n    GZ_ASSERT(this->currentHorzAngleModel.noiseAmp < 1 &&\n      this->currentHorzAngleModel.noiseAmp >= 0,\n      \"Noise amplitude for horizontal angle has to be between 0 and 1\");\n  }\n\n  this->currentHorzAngleModel.var = this->currentHorzAngleModel.mean;\n  gzmsg <<\n    \"Current velocity horizontal angle [rad] Gauss-Markov process model:\"\n    << std::endl;\n  this->currentHorzAngleModel.Print();\n\n  if (currentVelocityParams->HasElement(\"vertical_angle\"))\n  {\n    sdf::ElementPtr elem = currentVelocityParams->GetElement(\"vertical_angle\");\n\n    if (elem->HasElement(\"mean\"))\n      this->currentVertAngleModel.mean = elem->Get<double>(\"mean\");\n    if (elem->HasElement(\"min\"))\n      this->currentVertAngleModel.min = elem->Get<double>(\"min\");\n    if (elem->HasElement(\"max\"))\n      this->currentVertAngleModel.max = elem->Get<double>(\"max\");\n    if (elem->HasElement(\"mu\"))\n      this->currentVertAngleModel.mu = elem->Get<double>(\"mu\");\n    if (elem->HasElement(\"noiseAmp\"))\n      this->currentVertAngleModel.noiseAmp = elem->Get<double>(\"noiseAmp\");\n\n    GZ_ASSERT(this->currentVertAngleModel.min <\n      this->currentVertAngleModel.max, \"Invalid current vertical angle limits\");\n    GZ_ASSERT(this->currentVertAngleModel.mean >=\n      this->currentVertAngleModel.min,\n      \"Mean vertical angle must be greater than minimum\");\n    GZ_ASSERT(this->currentVertAngleModel.mean <=\n      this->currentVertAngleModel.max,\n      \"Mean vertical angle must be smaller than maximum\");\n    GZ_ASSERT(this->currentVertAngleModel.mu >= 0 &&\n      this->currentVertAngleModel.mu < 1,\n      \"Invalid process constant\");\n    GZ_ASSERT(this->currentVertAngleModel.noiseAmp < 1 &&\n      this->currentVertAngleModel.noiseAmp >= 0,\n      \"Noise amplitude for vertical angle has to be between 0 and 1\");\n  }\n\n  this->currentVertAngleModel.var = this->currentVertAngleModel.mean;\n  gzmsg <<\n    \"Current velocity vertical angle [rad] Gauss-Markov process model:\"\n    << std::endl;\n  this->currentVertAngleModel.Print();\n\n  // Initialize the time update\n#if GAZEBO_MAJOR_VERSION >= 8\n  this->lastUpdate = this->world->SimTime();\n#else\n  this->lastUpdate = this->world->GetSimTime();\n#endif\n  this->currentVelModel.lastUpdate = this->lastUpdate.Double();\n  this->currentHorzAngleModel.lastUpdate = this->lastUpdate.Double();\n  this->currentVertAngleModel.lastUpdate = this->lastUpdate.Double();\n\n  // ----------------------------------------------------------------- //\n  // -------------------- Transient ocean current -------------------- //\n  // ----------------------------------------------------------------- //\n  // Retrieve the transient ocean current configuration, if existent\n  GZ_ASSERT(this->sdf->HasElement(\"transient_current\"),\n    \"Transient current configuration not available\");\n  sdf::ElementPtr transientCurrentParams = this->sdf->GetElement(\n    \"transient_current\");\n\n  if (transientCurrentParams->HasElement(\"topic_stratified_database\"))\n    this->stratifiedCurrentVelocityTopic =\n      transientCurrentParams->Get<std::string>(\"topic_stratified_database\");\n  else\n    this->stratifiedCurrentVelocityTopic = \"stratified_current_velocity\";\n\n  GZ_ASSERT(!this->stratifiedCurrentVelocityTopic.empty(),\n    \"Empty stratified ocean current velocity topic\");\n\n  // Read the depth dependent ocean current file path from the SDF file\n  if (transientCurrentParams->HasElement(\"databasefilePath\"))\n    this->databaseFilePath =\n      transientCurrentParams->Get<std::string>(\"databasefilePath\");\n  else\n  {\n    // Using boost:\n    // boost::filesystem::path\n    //    concatPath(boost::filesystem::initial_path().parent_path());\n    // concatPath +=\n    //    \"/uuv_ws/src/dave/uuv_dave/worlds/transientOceanCurrentDatabase.csv\";\n    // this->databaseFilePath = concatPath.generic_string();\n    //\n    // Use ros package path:\n    this->databaseFilePath = this->db_path +\n      \"/worlds/transientOceanCurrentDatabase.csv\";\n  }\n  GZ_ASSERT(!this->databaseFilePath.empty(),\n    \"Empty stratified ocean current database file path\");\n\n  gzmsg << this->databaseFilePath << std::endl;\n\n  // Read database\n  std::ifstream csvFile; std::string line;\n  csvFile.open(this->databaseFilePath);\n  if (!csvFile)\n  {\n    this->databaseFilePath = this->db_path +\n      \"/worlds/\" + this->databaseFilePath;\n    csvFile.open(this->databaseFilePath);\n  }\n  GZ_ASSERT(csvFile, \"Stratified Ocean database file does not exist\");\n\n  gzmsg << \"Statified Ocean Current Database loaded : \"\n        << this->databaseFilePath << std::endl;\n\n  // skip the 3 lines\n  getline(csvFile, line); getline(csvFile, line); getline(csvFile, line);\n  while (getline(csvFile, line))\n  {\n      if (line.empty())  // skip empty lines:\n      {\n          continue;\n      }\n      std::istringstream iss(line);\n      std::string lineStream;\n      std::string::size_type sz;\n      std::vector <long double> row;\n      while (getline(iss, lineStream, ','))\n      {\n          row.push_back(stold(lineStream, &sz));  // convert to double\n      }\n      ignition::math::Vector3d read;\n      read.X() = row[0]; read.Y() = row[1]; read.Z() = row[2];\n      this->database.push_back(read);\n  }\n  csvFile.close();\n\n\n  // ----------------------------------------------------------------- //\n  // --------------------    Tidal Oscillation    -------------------- //\n  // ----------------------------------------------------------------- //\n  if (this->sdf->HasElement(\"tidal_oscillation\"))\n  {\n    this->tideFlag = true;\n    this->tidalHarmonicFlag = false;\n\n    sdf::ElementPtr tidalOscillationParams\n      = this->sdf->GetElement(\"tidal_oscillation\");\n    sdf::ElementPtr tidalHarmonicParams;\n\n    // Read the tidal oscillation parameter from the SDF file\n    if (tidalOscillationParams->HasElement(\"databasefilePath\"))\n    {\n      this->tidalFilePath =\n        tidalOscillationParams->Get<std::string>(\"databasefilePath\");\n      gzmsg << \"Tidal current database configuration found\" << std::endl;\n    }\n    else\n    {\n      if (tidalOscillationParams->HasElement(\"harmonic_constituents\"))\n      {\n        tidalHarmonicParams =\n          tidalOscillationParams->GetElement(\"harmonic_constituents\");\n        gzmsg << \"Tidal harmonic constituents \"\n              << \"configuration found\" << std::endl;\n        tidalHarmonicFlag = true;\n      }\n      else\n        this->tidalFilePath = ros::package::getPath(\"uuv_dave\") +\n          \"/worlds/ACT1951_predictionMaxSlack_2021-02-24.csv\";\n    }\n\n    // Read the tidal oscillation direction from the SDF file\n    GZ_ASSERT(tidalOscillationParams->HasElement(\"mean_direction\"),\n      \"Tidal mean direction not defined\");\n    if (tidalOscillationParams->HasElement(\"mean_direction\"))\n    {\n      sdf::ElementPtr elem =\n        tidalOscillationParams->GetElement(\"mean_direction\");\n      GZ_ASSERT(elem->HasElement(\"ebb\"),\n        \"Tidal mean ebb direction not defined\");\n      this->ebbDirection = elem->Get<double>(\"ebb\");\n      this->floodDirection = elem->Get<double>(\"flood\");\n      GZ_ASSERT(elem->HasElement(\"flood\"),\n        \"Tidal mean flood direction not defined\");\n    }\n\n    // Read the world start time (GMT) from the SDF file\n    GZ_ASSERT(tidalOscillationParams->HasElement(\"world_start_time_GMT\"),\n      \"World start time (GMT) not defined\");\n    if (tidalOscillationParams->HasElement(\"world_start_time_GMT\"))\n    {\n      sdf::ElementPtr elem =\n        tidalOscillationParams->GetElement(\"world_start_time_GMT\");\n      GZ_ASSERT(elem->HasElement(\"day\"),\n        \"World start time (day) not defined\");\n      this->world_start_time_day = elem->Get<double>(\"day\");\n      GZ_ASSERT(elem->HasElement(\"month\"),\n        \"World start time (month) not defined\");\n      this->world_start_time_month = elem->Get<double>(\"month\");\n      GZ_ASSERT(elem->HasElement(\"year\"),\n        \"World start time (year) not defined\");\n      this->world_start_time_year = elem->Get<double>(\"year\");\n      GZ_ASSERT(elem->HasElement(\"hour\"),\n        \"World start time (hour) not defined\");\n      this->world_start_time_hour = elem->Get<double>(\"hour\");\n      if (elem->HasElement(\"minute\"))\n        this->world_start_time_minute = elem->Get<double>(\"minute\");\n      else\n        this->world_start_time_minute = 0;\n    }\n\n    if (tidalHarmonicFlag)\n    {\n      // Read harmonic constituents\n      GZ_ASSERT(tidalHarmonicParams->HasElement(\"M2\"),\n        \"Harcomnic constituents M2 not found\");\n      sdf::ElementPtr M2Params = tidalHarmonicParams->GetElement(\"M2\");\n      this->M2_amp = M2Params->Get<double>(\"amp\");\n      this->M2_phase = M2Params->Get<double>(\"phase\");\n      this->M2_speed = M2Params->Get<double>(\"speed\");\n      GZ_ASSERT(tidalHarmonicParams->HasElement(\"S2\"),\n        \"Harcomnic constituents S2 not found\");\n      sdf::ElementPtr S2Params = tidalHarmonicParams->GetElement(\"S2\");\n      this->S2_amp = S2Params->Get<double>(\"amp\");\n      this->S2_phase = S2Params->Get<double>(\"phase\");\n      this->S2_speed = S2Params->Get<double>(\"speed\");\n      GZ_ASSERT(tidalHarmonicParams->HasElement(\"N2\"),\n        \"Harcomnic constituents N2 not found\");\n      sdf::ElementPtr N2Params = tidalHarmonicParams->GetElement(\"N2\");\n      this->N2_amp = N2Params->Get<double>(\"amp\");\n      this->N2_phase = N2Params->Get<double>(\"phase\");\n      this->N2_speed = N2Params->Get<double>(\"speed\");\n      gzmsg << \"Tidal harmonic constituents loaded : \" << std::endl;\n      gzmsg << \"M2 amp: \" << this->M2_amp << \" phase: \" << this->M2_phase\n            << \" speed: \" << this->M2_speed << std::endl;\n      gzmsg << \"S2 amp: \" << this->S2_amp << \" phase: \" << this->S2_phase\n            << \" speed: \" << this->S2_speed << std::endl;\n      gzmsg << \"N2 amp: \" << this->N2_amp << \" phase: \" << this->N2_phase\n            << \" speed: \" << this->N2_speed << std::endl;\n    }\n    else\n    {\n      // Read database\n      csvFile.open(this->tidalFilePath);\n      if (!csvFile)\n      {\n        this->tidalFilePath = ros::package::getPath(\"uuv_dave\") +\n          \"/worlds/\" + this->tidalFilePath;\n        csvFile.open(this->tidalFilePath);\n      }\n      GZ_ASSERT(csvFile, \"Tidal Oscillation database file does not exist\");\n\n      gzmsg << \"Tidal Oscillation  Database loaded : \"\n            << this->tidalFilePath << std::endl;\n\n      // skip the first line\n      getline(csvFile, line);\n      while (getline(csvFile, line))\n      {\n          if (line.empty())  // skip empty lines:\n          {\n              continue;\n          }\n          std::istringstream iss(line);\n          std::string lineStream;\n          std::string::size_type sz;\n          std::vector<std::string> row;\n          std::array<int, 5> tmpDateArray;\n          while (getline(iss, lineStream, ','))\n          {\n            row.push_back(lineStream);\n          }\n          if (strcmp(row[1].c_str(), \" slack\"))  // skip 'slack' category\n          {\n            tmpDateArray[0] = std::stoi(row[0].substr(0, 4));\n            tmpDateArray[1] = std::stoi(row[0].substr(5, 7));\n            tmpDateArray[2] = std::stoi(row[0].substr(8, 10));\n            tmpDateArray[3] = std::stoi(row[0].substr(11, 13));\n            tmpDateArray[4] = std::stoi(row[0].substr(14, 16));\n            this->dateGMT.push_back(tmpDateArray);\n\n            this->speedcmsec.push_back(stold(row[2], &sz));\n          }\n      }\n      csvFile.close();\n\n      // Eliminate data with same consecutive type\n      std::vector<int> duplicated;\n      for (int i = 0; i  <this->dateGMT.size(); i++)\n      {\n        // delete latter if same sign\n        if (((this->speedcmsec[i] > 0) - (this->speedcmsec[i] < 0))\n            == ((this->speedcmsec[i+1] > 0) - (this->speedcmsec[i+1] < 0)))\n        {\n          duplicated.push_back(i+1);\n        }\n      }\n      int eraseCount = 0;\n      for (int i = 0; i < duplicated.size(); i++)\n      {\n        this->dateGMT.erase(\n          this->dateGMT.begin()+duplicated[i]-eraseCount);\n        this->speedcmsec.erase(\n          this->speedcmsec.begin()+duplicated[i]-eraseCount);\n        eraseCount++;\n      }\n    }\n  }  // end of tidal oscillation configuration\n\n  // Advertise the current velocity topic\n  this->publishers[this->currentVelocityTopic] =\n    this->node->Advertise<msgs::Vector3d>(\n    this->ns + \"/\" + this->currentVelocityTopic);\n\n  gzmsg << \"Current velocity topic name: \" <<\n    this->ns + \"/\" + this->currentVelocityTopic << std::endl;\n\n  // Connect the update event\n  this->updateConnection = event::Events::ConnectWorldUpdateBegin(\n    boost::bind(&UnderwaterCurrentPlugin::Update,\n    this, _1));\n\n  gzmsg << \"Underwater current plugin loaded!\" << std::endl\n    << \"\\tWARNING: Current velocity calculated in the ENU frame\"\n    << std::endl;\n}\n\n/////////////////////////////////////////////////\nvoid UnderwaterCurrentPlugin::Init()\n{\n  // Doing nothing for now\n}\n\n/////////////////////////////////////////////////\nvoid UnderwaterCurrentPlugin::Update(const common::UpdateInfo & /** _info */)\n{\n#if GAZEBO_MAJOR_VERSION >= 8\n  common::Time time = this->world->SimTime();\n#else\n  common::Time time = this->world->GetSimTime();\n#endif\n\n  // Calculate the flow velocity and the direction using the Gauss-Markov\n  // model\n\n  // Update current velocity\n  double currentVelMag = this->currentVelModel.Update(time.Double());\n\n  // Update current horizontal direction around z axis of flow frame\n  double horzAngle = this->currentHorzAngleModel.Update(time.Double());\n\n  // Update current horizontal direction around z axis of flow frame\n  double vertAngle = this->currentVertAngleModel.Update(time.Double());\n\n  // Generating the current velocity vector as in the NED frame\n  this->currentVelocity = ignition::math::Vector3d(\n      currentVelMag * cos(horzAngle) * cos(vertAngle),\n      currentVelMag * sin(horzAngle) * cos(vertAngle),\n      currentVelMag * sin(vertAngle));\n\n  // Update time stamp\n  this->lastUpdate = time;\n  this->PublishCurrentVelocity();\n}\n\n/////////////////////////////////////////////////\nvoid UnderwaterCurrentPlugin::PublishCurrentVelocity()\n{\n  msgs::Vector3d currentVel;\n  msgs::Set(&currentVel, ignition::math::Vector3d(this->currentVelocity.X(),\n                                                  this->currentVelocity.Y(),\n                                                  this->currentVelocity.Z()));\n  this->publishers[this->currentVelocityTopic]->Publish(currentVel);\n}\n", "meta": {"hexsha": "741159fa696b03b7afc9dc9f6e6aede6019a3516", "size": 19767, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transient_current_dave_plugin/dave_world_plugins/src/UnderwaterCurrentPlugin.cc", "max_stars_repo_name": "wangcongrobot/dave", "max_stars_repo_head_hexsha": "8c2b27462c9628672d71978280a7ad6dbf44eec6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-15T17:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-15T17:10:21.000Z", "max_issues_repo_path": "transient_current_dave_plugin/dave_world_plugins/src/UnderwaterCurrentPlugin.cc", "max_issues_repo_name": "wangcongrobot/dave", "max_issues_repo_head_hexsha": "8c2b27462c9628672d71978280a7ad6dbf44eec6", "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": "transient_current_dave_plugin/dave_world_plugins/src/UnderwaterCurrentPlugin.cc", "max_forks_repo_name": "wangcongrobot/dave", "max_forks_repo_head_hexsha": "8c2b27462c9628672d71978280a7ad6dbf44eec6", "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.7232824427, "max_line_length": 80, "alphanum_fraction": 0.6407143218, "num_tokens": 4889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1699084879309177}}
{"text": "//   Copyright 2015 Patrick Putnam\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 CLOTHO_SIM_ENGINE_PARALLEL_PIPELINE_BATCHED_HPP_\n#define CLOTHO_SIM_ENGINE_PARALLEL_PIPELINE_BATCHED_HPP_\n\n#ifdef DEBUG_MODE\n#define DEBUGGING 0\n#endif  // DEBUG_MODE\n\n#include \"qtlsim_logger.hpp\"\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n#include \"clotho/genetics/population_growth_toolkit.hpp\"\n\n#include \"clotho/data_spaces/allele_space/allele_space_vector.hpp\"\n#include \"clotho/data_spaces/allele_space/allele_generators.hpp\"\n\n#include \"clotho/data_spaces/phenotype_evaluator/trait_space_vector.hpp\"\n#include \"clotho/data_spaces/phenotype_evaluator/trait_space_generator.hpp\"\n\n#include \"clotho/data_spaces/phenotype_evaluator/trait_accumulator.hpp\"\n#include \"clotho/data_spaces/free_space/free_space_accumulator.hpp\"\n\n#include \"clotho/data_spaces/population_space/population_spaces.hpp\"\n#include \"clotho/data_spaces/selection/selection.hpp\"\n\n#include \"clotho/data_spaces/fitness/general_fitness.hpp\"\n\n#include \"clotho/utility/state_object.hpp\"\n#include \"clotho/utility/bit_helper.hpp\"\n\n#include \"clotho/data_spaces/task/thread_count_parameter.hpp\"\n#include \"clotho/data_spaces/task/thread_pool2.hpp\"\n\n#include \"clotho/data_spaces/offspring_generator/offspring_generators.hpp\"\n\n#include \"clotho/recombination/sequence_bias_parameter.hpp\"\n#include \"clotho/recombination/recombination_rate_parameter.hpp\"\n\n#include \"clotho/data_spaces/mutation/mutation_allocator.hpp\"\n\n#include <vector>\n\nstruct parallel_pipeline_batched {};\n\n#ifdef USE_OFF_GEN_PIPELINE\n#define OFF_GEN_METHOD clotho::genetics::off_gen_pipelined\n#else\n#define OFF_GEN_METHOD clotho::genetics::off_gen_default\n#endif  // USE_OFF_GEN_PIPELINE\n\ntemplate < class RNG, class RealType, class BlockType, class SizeType >\nclass Engine< RNG, RealType, BlockType, SizeType, parallel_pipeline_batched > {\npublic:\n    typedef Engine< RNG, RealType, BlockType, SizeType, parallel_pipeline_batched >             self_type;\n\n    typedef RealType                    position_type;\n    typedef RealType                    weight_type;\n    typedef weight_type *               phenotype_type;\n    typedef BlockType                   block_type;\n\n    typedef RNG                         random_engine_type;\n\n    typedef SizeType                    size_type;\n\n    typedef clotho::genetics::thread_pool2< RNG >                                                   thread_pool_type;\n    typedef clotho::genetics::AlleleSpace< position_type, size_type >                   allele_type;\n\n#ifdef USE_VECTOR_ALIGNMENT\n    typedef clotho::genetics::index_vector_alignment< unsigned int, block_type >    alignment_type;\n#else\n    typedef clotho::genetics::row_block_alignment< block_type >                     alignment_type;\n#endif\n\n    typedef clotho::genetics::trait_space_vector< weight_type >                     trait_space_type;\n    typedef clotho::genetics::population_space< alignment_type, trait_space_type >  sequence_space_type;\n\n    typedef clotho::genetics::free_space_accumulator_mt< block_type, size_type >                    free_space_type;\n    typedef typename free_space_type::buffer_type                                                   free_buffer_type;\n\n    typedef clotho::genetics::mutation_allocator< random_engine_type, size_type >                 mutation_alloc_type;\n\n    typedef clotho::genetics::AlleleGenerator< random_engine_type, allele_type >                allele_generator_type;\n    typedef clotho::genetics::TraitSpaceGenerator2< trait_space_type >                          trait_generator_type;\n\n    typedef clotho::genetics::GeneralFitness                                                      fitness_type;\n\n    typedef std::shared_ptr< ipopulation_growth_generator >                                         population_growth_generator_type;\n    typedef std::shared_ptr< ipopulation_growth >                                                   population_growth_type;\n\n    typedef clotho::genetics::batch_offspring_generator< random_engine_type, sequence_space_type, allele_type, fitness_type, trait_space_type, free_buffer_type, OFF_GEN_METHOD >           offspring_generator_type;\n    typedef typename offspring_generator_type::parameter_type parameter_type;\n\n    typedef typename offspring_generator_type::mutation_pool_type                               mutation_pool_type;\n    typedef typename offspring_generator_type::mutation_distribution_type                       mutation_distribution_type;\n\n    typedef typename offspring_generator_type::time_vector  time_vector;\n\n    typedef std::map< std::string, time_vector> time_map;\n\n    friend struct clotho::utility::state_getter< self_type >;\n\n    Engine( random_engine_type * rng, boost::property_tree::ptree & config ) :\n        m_rand( rng )\n        , m_trait_space( config )\n        , m_fixed_traits( config )\n        , m_generation( 0 )\n        , m_pop_growth()\n        , m_thread_count( config )\n        , m_free_space( m_thread_count.m_tc + 1 )\n        , m_worker_rng( NULL )\n        , m_mut_alloc( rng, config )\n        , trait_gen( config )\n        , allele_gen( rng, config )\n        , m_recomb_rate( config )\n        , m_bias_rate( config )\n        , m_main_off_gen( rng, &m_allele_space, &m_trait_space, config )\n        , m_worker_off_gens( NULL )\n    {\n        population_growth_generator_type tmp  = population_growth_toolkit::getInstance()->get_tool( config );\n        if( tmp ) {\n            m_pop_growth = tmp->generate();\n            if( m_pop_growth ) {\n                m_pop_growth->log( std::cerr );\n                std::cerr << std::endl;\n            }\n        } else {\n            population_growth_toolkit::getInstance()->tool_configurations( config );\n        }\n\n        init(0, config);\n    }\n\n    size_t getGeneration() const {\n        return m_generation;\n    }\n\n    void init( size_t aN, boost::property_tree::ptree & config ) {\n        size_t pN = 0;\n        if( m_pop_growth ) {\n            pN = m_pop_growth->operator()( pN, m_generation );\n        }\n\n        boost::property_tree::ptree lconfig;\n\n        lconfig = config.get_child( \"generations\", lconfig);\n\n        unsigned int intermed = lconfig.get< unsigned int>( \"intermediates\", 0 );\n\n        lconfig.put(\"intermediates\", intermed );\n        config.put_child( \"generations\", lconfig );\n\n        for( unsigned int i = 0; i < intermed + 2; ++i ) {\n            sequence_space_type * ss = new sequence_space_type();\n            m_pop.push_back( ss );\n\n            fitness_type * f = new fitness_type( config );\n\n            assert( f->isEmpty() );\n\n            m_fits.push_back( f );\n\n            mutation_pool_type * p = new mutation_pool_type();\n            m_mut_pools.push_back( p );\n\n            mutation_distribution_type * d = new mutation_distribution_type();\n            m_mut_dists.push_back( d );\n        }\n\n\n        if( m_thread_count.m_tc > 0 ) {\n            m_worker_rng = new random_engine_type * [ m_thread_count.m_tc ];\n            m_worker_off_gens = new offspring_generator_type * [ m_thread_count.m_tc ];\n\n            for( int offset = 0; offset < m_thread_count.m_tc; ++offset ) {\n                m_worker_rng[ offset ] = new random_engine_type( (*m_rand)());\n                m_worker_off_gens[ offset ] = new offspring_generator_type( m_worker_rng[ offset ], &m_allele_space, &m_trait_space, config );\n            }\n        }\n\n#ifdef USE_ROW_VECTOR\n        m_pop1.getSequenceSpace().fill_empty();\n        m_pop1.getSequenceSpace().finalize();\n#endif // USE_ROW_VECTOR\n        ++m_generation;\n    }\n\n    void simulate( ) {\n        // use the last population as the first population for the next round\n        std::swap( m_pop[ 0 ], m_pop[ m_pop.size() - 1 ] );\n        std::swap( m_fits[ 0 ], m_fits[ m_fits.size() - 1] );\n\n        size_t all_size = buildProjectedPopulations( );\n\n#ifdef DEBUGGING \n        BOOST_LOG_TRIVIAL( debug ) << \"Generation \" << m_generation << \": \" << pN << \" individuals; \" << pM << \" new alleles\";\n        BOOST_LOG_TRIVIAL( debug ) << \"Free space: \" << free_count << \"; alleles: \" << m_allele_space.size();\n        BOOST_LOG_TRIVIAL( debug ) << \"Rescaling child population to be: \" << pN << \" individuals x \" << all_size << \" alleles\";\n#endif // DEBUGGING\n\n        // grow the free space buffer to a size relative to the last projected population\n        m_free_space.resetBuffers( m_pop.back()->getMaxBlocks() );\n\n//        bool is_all_neutral = m_allele_space.isAllNeutral();\n        bool is_all_neutral = m_trait_space.isAllNeutral();\n\n        thread_pool_type tpool( m_thread_count.m_tc );\n        \n        const size_t TC = m_thread_count.m_tc + 1;\n\n        std::vector< parameter_type * > params;\n\n        for( int j = 0; j < m_thread_count.m_tc; ++j ) {\n            free_buffer_type tbuf = m_free_space.getThreadBuffer( j );\n            m_worker_off_gens[ j ]->reset( tbuf );\n\n            unsigned int prev_start = 0, prev_end = m_pop[ 0 ]->getIndividualCount();\n\n            for( unsigned int p = 1; p < m_pop.size(); ++p ) {\n                unsigned int pN = m_pop[ p ]->getIndividualCount();\n                size_t BATCH_SIZE = (pN / TC) + ((pN % TC > 0) ? 1 : 0);\n\n                unsigned int off_idx = j * BATCH_SIZE;\n                parameter_type * param = new parameter_type( m_pop[ p - 1 ], m_pop[ p ], m_fits[ p - 1], m_fits[ p ], m_mut_pools[ p - 1], m_mut_dists[ p - 1], prev_start, prev_end, off_idx, off_idx + BATCH_SIZE, is_all_neutral );\n\n                m_worker_off_gens[ j ]->addPopulation( param );\n                \n                params.push_back( param );\n\n                prev_start = off_idx;\n                prev_end = off_idx + BATCH_SIZE;\n            }\n        }\n\n        m_main_off_gen.reset( m_free_space.getThreadBuffer( m_thread_count.m_tc ) );\n\n        unsigned int prev_start = 0, prev_end = m_pop[ 0 ]->getIndividualCount();\n        for( unsigned int p = 1; p < m_pop.size(); ++p ) {\n            unsigned int pN = m_pop[ p ]->getIndividualCount();\n            size_t BATCH_SIZE = (pN / TC) + ((pN % TC > 0) ? 1 : 0);\n            unsigned int off_idx = m_thread_count.m_tc * BATCH_SIZE;\n\n            parameter_type * param = new parameter_type( m_pop[ p - 1 ], m_pop[ p ], m_fits[ p - 1], m_fits[ p ], m_mut_pools[ p - 1], m_mut_dists[ p - 1], prev_start, prev_end, off_idx, pN, is_all_neutral );\n            m_main_off_gen.addPopulation( param );\n            params.push_back( param );\n\n            prev_start = off_idx;\n            prev_end = pN;\n        }\n\n        tpool.post_list( m_worker_off_gens, m_thread_count.m_tc );\n\n        m_main_off_gen();\n\n        tpool.sync();\n\n        m_free_space.finalize(all_size);\n\n        recordAlleles();\n\n        while( ! params.empty() ) {\n            parameter_type * p = params.back();\n            params.pop_back();\n            delete p;\n        }\n\n        ++m_generation;\n    }\n\n    sequence_space_type * getChildPopulation() const {\n        return m_pop.back();\n    }\n\n    sequence_space_type * getParentPopulation() const {\n        return m_pop[ 0 ];\n    }\n\n    void recordAlleles() {\n        for( unsigned int i = 1; i < m_pop.size(); ++i ) {\n            clotho::utility::add_value_array( free_sizes, m_free_space.free_size() );\n            clotho::utility::add_value_array( var_sizes, m_free_space.variable_count() );\n            //clotho::utility::add_value_array( fixed_sizes, m_free_space.fixed_size() );\n            clotho::utility::add_value_array( fixed_sizes, m_fixed.size() );\n        }\n    }\n\n    void buildTimeVectorLog( boost::property_tree::ptree & log, time_map & times ) {\n        for( typename time_map::iterator it = times.begin(); it != times.end(); it++ ) {\n            boost::property_tree::ptree starts, stops;\n\n            for( typename time_vector::iterator iter = it->second.begin(); iter != it->second.end(); ++iter ) {\n                clotho::utility::add_value_array( starts, iter->first );\n                clotho::utility::add_value_array( stops, iter->second );\n            }\n\n            boost::property_tree::ptree tmp;\n            tmp.put_child( \"start\", starts );\n            tmp.put_child( \"stop\", stops );\n\n            log.put_child( it->first, tmp );\n        }\n    }\n\n    void getPerformanceResults( boost::property_tree::ptree & log ) {\n\n        for( int i = 0; i < m_thread_count.m_tc; ++i ) {\n            std::ostringstream oss;\n            oss << \"W_\" << (i + 1);\n\n            boost::property_tree::ptree mut, xo, ph, fx, ft;\n            m_worker_off_gens[ i ]->record( xo, mut, ph, fx, ft );\n            \n            log.put_child( \"performance.mutate.\" + oss.str(), mut );\n            log.put_child( \"performance.crossover.\" + oss.str(), xo );\n            log.put_child( \"performance.fixed.\" + oss.str(), fx );\n            log.put_child( \"performance.phenotype.\" + oss.str(), ph );\n            log.put_child( \"performance.fitness.\" + oss.str(), ft );\n        }\n\n        boost::property_tree::ptree mut, xo, ph, fx, ft;\n        m_main_off_gen.record( xo, mut, ph, fx, ft );\n        \n        log.put_child( \"performance.mutate.main\", mut );\n        log.put_child( \"performance.crossover.main\", xo );\n        log.put_child( \"performance.fixed.main\", fx );\n        log.put_child( \"performance.phenotype.main\", ph );\n        log.put_child( \"performance.fitness.main\", ft );\n\n        log.put_child( \"memory.free_count\", free_sizes );\n        log.put_child( \"memory.variable_count\", var_sizes );\n        log.put_child( \"memory.fixed_count\", fixed_sizes );\n    }\n\n    allele_type * getAlleleSpace() {\n        return &m_allele_space;\n    }\n\n    virtual ~Engine() { \n        if( m_worker_rng != NULL ) {\n            for( int i = 0; i < m_thread_count.m_tc; ++i ) {\n                delete m_worker_rng[ i ];\n            }\n            delete [] m_worker_rng;\n            m_worker_rng = NULL;\n        }\n\n        if( m_worker_off_gens != NULL ) {\n            for( int i = 0; i < m_thread_count.m_tc; ++i ) {\n                delete m_worker_off_gens[ i ];\n            }\n\n            delete [] m_worker_off_gens;\n            m_worker_off_gens = NULL;\n        }\n\n        while( !m_pop.empty() ) {\n            sequence_space_type * p = m_pop.back();\n            m_pop.pop_back();\n            delete p;\n\n            mutation_pool_type * pool = m_mut_pools.back();\n            m_mut_pools.pop_back();\n            delete pool;\n\n            mutation_distribution_type * dist = m_mut_dists.back();\n            m_mut_dists.pop_back();\n            delete dist;\n\n            fitness_type * f = m_fits.back();\n            m_fits.pop_back();\n            delete f; \n        }\n    }\n\nprotected:\n\n    size_t buildProjectedPopulations( ) {\n        // remove fixed alleles\n        size_t all_count = m_pop[0]->getMaxAlleles();\n        size_t free_count = removeFixedAlleles( m_pop[0] );\n\n        typename free_space_type::base_type::iterator it = m_free_space.free_begin(), end = m_free_space.free_end();\n\n        unsigned int gen_offset = m_generation * (m_pop.size() - 1);\n\n        for( unsigned int i = 1; i < m_pop.size(); ++i ) {\n            all_count = grow_child_population( m_pop[ i - 1 ], m_pop[ i ], m_fits[ i ], m_mut_pools[ i - 1], m_mut_dists[ i - 1], all_count, free_count, it, end, gen_offset++ );\n\n            free_count = (end - it);\n        }\n\n        return all_count;\n    }\n\n    size_t grow_child_population( sequence_space_type * parent, sequence_space_type * off, fitness_type * fit, mutation_pool_type * mut_pool, mutation_distribution_type * mut_dist, size_t all_count, size_t free_count, typename free_space_type::base_type::iterator & it, typename free_space_type::base_type::iterator & end, unsigned int gen ) {\n        // at the start of each simulate round, m_fit has already been updated from the previous\n        // round with the fitness of the \"then child/now parent\" popualtions fitness\n        //\n        size_t pN = parent->getIndividualCount();\n        if( m_pop_growth ) {\n            pN = m_pop_growth->operator()( pN, m_generation );\n        }\n\n        size_type pM = m_mut_alloc.allocate( 2 * pN );        // generate the number of new mutations\n\n        size_t all_size = child_max_alleles( all_count, free_count, pM );   // rescale allele space for child population given free space from parent population and new allele count (pM)\n        off->grow( pN, all_size, m_trait_space.trait_count() );               // grow the child population accordingly\n\n        fit->resize( pN );\n        generate_child_mutations( off, mut_pool, mut_dist, pM, it, end, gen );\n\n        return all_size;\n    }\n\n    void generate_child_mutations( sequence_space_type * off, mutation_pool_type * mut_pool, mutation_distribution_type * mut_dist, unsigned int N, typename free_space_type::base_type::iterator & it, typename free_space_type::base_type::iterator & end, unsigned int gen ) {\n//        std::cerr << \"Child population size: \" << m_child->haploid_genome_count() << std::endl;\n//        std::cerr << \"Mutation count: \" << N << std::endl;\n//        std::cerr << \"Free space: \" << m_free_space.free_size() << std::endl;\n//\n        resetMutationEvents( mut_pool, mut_dist, N, off->haploid_genome_count() + 1 );\n//        m_allele_space.alignNeutralToPopulation( off->getMaxBlocks() );\n\n        boost::random::uniform_int_distribution< unsigned int > seq_gen( 0, off->haploid_genome_count() - 1);\n\n        unsigned int i = 0;\n        while( i < N ) {\n            typename free_space_type::size_type all_idx = m_allele_space.size();\n\n            if( it != end ) {\n                all_idx = *it++;\n            } else {\n                m_allele_space.grow();\n                m_trait_space.grow();\n            }\n\n            unsigned int seq_idx = seq_gen( *m_rand );\n\n            assert( all_idx < off->getMaxAlleles() );\n\n            mut_pool->at( i ) = all_idx;\n            mut_dist->at( seq_idx + 1 ) += 1;\n\n            allele_gen( m_allele_space, all_idx, gen );\n            trait_gen(*m_rand, m_trait_space, all_idx );\n\n            ++i;\n        }\n\n        // scan right to produce m_mut_pool relative index ranges\n        for( unsigned int i = 2; i < mut_dist->size(); ++i ) {\n            mut_dist->at( i ) += mut_dist->at( i - 1 );\n        }\n        \n    }\n\n    void resetMutationEvents( mutation_pool_type * mut_pool, mutation_distribution_type * mut_dist, unsigned int N, unsigned int S ) {\n        while( mut_pool->size() < N ) {\n            mut_pool->push_back(0);\n        }\n\n        while( mut_dist->size() < S ) {\n            mut_dist->push_back(0);\n        }\n\n        std::fill( mut_dist->begin(), mut_dist->end(), 0 );\n    }\n\n/**\n * estimate the maximum number of alleles in the child\n *\n * N_parent - number of alleles in the parent population\n * F_parent - number of free alleles in the parent population\n * M_child  - number of new alleles to be added the child population\n */\n    size_t child_max_alleles( size_t N_parent, size_t F_parent, size_t M_child ) const {\n#ifdef DEBUGGING\n        BOOST_LOG_TRIVIAL(info) << \"Parent alleles: \" << N_parent << \"; Free: \" << F_parent << \"; New Alleles: \" << M_child;\n        std::cerr << \"Parent alleles: \" << N_parent << \"; Free: \" << F_parent << \"; New Alleles: \" << M_child << std::endl;\n#endif  // DEBUGGING\n\n        if( F_parent >= M_child ) {\n            // if there are more free alleles in the parent generation\n            // than there are new alleles to be added to the child generation\n            // then do not adjust scale of the allele space\n            return N_parent;\n        } else {\n            return N_parent + (M_child - F_parent);\n        }\n    }\n\n    size_type removeFixedAlleles( sequence_space_type * ss ) {\n        typedef typename free_space_type::iterator  fixed_iterator;\n        typedef typename trait_space_type::iterator trait_iterator;\n\n\n        fixed_iterator  fix_it = m_free_space.fixed_begin();\n        fixed_iterator  fix_end = m_free_space.fixed_end();\n\n        while( fix_it != fix_end ) {\n            size_type  fixed_index = *fix_it++;\n\n            ss->remove_fixed_allele( fixed_index );\n\n            m_fixed.append( m_allele_space, fixed_index );\n            \n            trait_iterator tstart = m_trait_space.begin( fixed_index ), tend = m_trait_space.end( fixed_index );\n            m_fixed_traits.append( tstart, tend );\n        }\n\n#ifdef DEBUGGING\n        typedef typename free_space_type::iterator free_iterator;\n        free_iterator fr_it = m_free_space.free_begin();\n        free_iterator fr_end = m_free_space.free_end();\n\n        unsigned int j = 0;\n        while( fr_it != fr_end ) {\n            size_type i = *fr_it++;\n\n            if( !ss->freeColumn( i ) ) {\n                assert(false);\n            }\n            ++j;\n        }\n\n        assert( j == m_free_space.free_size() );\n#endif // DEBUGGING\n\n        return m_free_space.free_size();\n    }\n\n    random_engine_type  * m_rand;\n\n    allele_type          m_allele_space, m_fixed;\n\n    std::vector< sequence_space_type * > m_pop;\n\n    trait_space_type        m_trait_space, m_fixed_traits;\n\n    std::vector< fitness_type * > m_fits;\n\n    size_t                  m_generation;\n\n    population_growth_type  m_pop_growth;\n\n    thread_count_parameter  m_thread_count;\n    free_space_type         m_free_space;\n\n    random_engine_type **   m_worker_rng;\n    mutation_alloc_type     m_mut_alloc;\n    trait_generator_type    trait_gen;\n    allele_generator_type   allele_gen;\n\n    recombination_rate_parameter< double > m_recomb_rate;\n    sequence_bias_parameter< double > m_bias_rate;\n\n    std::vector< mutation_pool_type * > m_mut_pools;\n    std::vector< mutation_distribution_type * >  m_mut_dists;\n\n    offspring_generator_type m_main_off_gen;\n    offspring_generator_type ** m_worker_off_gens;\n\n    time_map m_fixed_times, m_mutate_times, m_xover_times, m_pheno_times;\n    boost::property_tree::ptree free_sizes, var_sizes, fixed_sizes, m_fitness_times;\n};\n\nnamespace clotho {\nnamespace utility {\n\ntemplate < class RNG, class RealType, class BlockType, class SizeType >\nstruct state_getter< Engine< RNG, RealType, BlockType, SizeType, parallel_pipeline_batched > > {\n    typedef Engine< RNG, RealType, BlockType, SizeType, parallel_pipeline_batched >           object_type;\n\n    void operator()( boost::property_tree::ptree & s, object_type & obj ) {\n        boost::property_tree::ptree tr;\n        state_getter< typename object_type::trait_space_type > tr_logger;\n        tr_logger( tr, obj.m_trait_space );\n\n        boost::property_tree::ptree fr;\n        state_getter< typename object_type::free_space_type > free_logger;\n        free_logger( fr, obj.m_free_space );\n\n        boost::property_tree::ptree fx, alls;\n        state_getter< typename object_type::allele_type > all_logger;\n        all_logger( fx, obj.m_fixed );\n        all_logger( alls, obj.m_allele_space );\n\n        boost::property_tree::ptree c_pop;\n        state_getter< typename object_type::sequence_space_type > pop_logger;\n        pop_logger( c_pop, *(obj.m_pop.back()) );\n\n        boost::property_tree::ptree ft;\n        clotho::utility::add_value_array( ft, obj.m_fits.back()->begin(), obj.m_fits.back()->end() );\n        c_pop.put_child( \"fitness\", ft );\n\n        s.put_child( \"free_space\", fr );\n        s.put_child( \"allele_space\", alls );\n        s.put_child( \"trait_space\", tr );\n        s.put_child( \"fixed_alleles\", fx );\n\n        s.put_child( \"child\", c_pop );\n    }\n};\n\n}\n}\n\n#endif  // CLOTHO_SIM_ENGINE_PARALLEL_PIPELINE_BATCHED_HPP_\n", "meta": {"hexsha": "d78952f03540f435b2b85ff397b6848eb0542917", "size": 23951, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/QTLSim/engine_parallel_pipeline_batched.hpp", "max_stars_repo_name": "putnampp/clotho", "max_stars_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T21:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:26:54.000Z", "max_issues_repo_path": "examples/QTLSim/engine_parallel_pipeline_batched.hpp", "max_issues_repo_name": "putnampp/clotho", "max_issues_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T21:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-23T12:41:00.000Z", "max_forks_repo_path": "examples/QTLSim/engine_parallel_pipeline_batched.hpp", "max_forks_repo_name": "putnampp/clotho", "max_forks_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "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": 38.5684380032, "max_line_length": 343, "alphanum_fraction": 0.6248590873, "num_tokens": 5630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1699084845614999}}
{"text": "#ifndef KECCAK_GADGET_H_\n#define KECCAK_GADGET_H_\n\n#include <deque>\n#include <boost/optional.hpp>\n#include <boost/static_assert.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>\n#include <libff/algebra/fields/field_utils.hpp>\n#include <libff/algebra/scalar_multiplication/multiexp.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>\n#include <libff/common/utils.hpp>\n\n#include <libsnark/gadgetlib1/gadgets/hashes/sha256/sha256_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>\n\n#include \"uint256.h\"\n#include \"serialize.h\"\n\nusing namespace libsnark;\n\nnamespace gunero {\n\ntemplate<typename FieldT>\nclass xor10_gadget : public gadget<FieldT> {\nprivate:\n    std::vector<pb_variable<FieldT>> tmp_vars;\npublic:\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Am0;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Am1;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Am2;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Am3;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Am4;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Ap0;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Ap1;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Ap2;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Ap3;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> Ap4;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> result;\n\n    xor10_gadget(protoboard<FieldT> &pb,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Am0,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Am1,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Am2,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Am3,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Am4,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Ap0,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Ap1,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Ap2,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Ap3,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &Ap4,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &result,\n                const std::string &annotation_prefix);\n\n    void generate_r1cs_constraints();\n    void generate_r1cs_witness();\n};\n\ntemplate<typename FieldT>\nclass rot_xor2_gadget : public gadget<FieldT> {\npublic:\n    std::shared_ptr<pb_linear_combination_array<FieldT>> A;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> D;\n    uint64_t r;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> B;\n\n    rot_xor2_gadget(protoboard<FieldT> &pb,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &A,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &D,\n                const uint64_t &r,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &B,\n                const std::string &annotation_prefix);\n\n    void generate_r1cs_constraints();\n    void generate_r1cs_witness();\n};\n\ntemplate<typename FieldT>\nclass xor_not_and_xor : public gadget<FieldT> {\nprivate:\n    std::vector<pb_variable<FieldT>> tmp_vars;\npublic:\n    std::shared_ptr<pb_linear_combination_array<FieldT>> B1;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> B2;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> B3;\n    const uint64_t RC;\n    pb_linear_combination_array<FieldT> RC_bits;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> A_out;\n\n    xor_not_and_xor(protoboard<FieldT> &pb,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &B1,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &B2,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &B3,\n                const uint64_t &RC,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &A_out,\n                const std::string &annotation_prefix);\n\n    void generate_r1cs_constraints();\n    void generate_r1cs_witness();\n};\n\ntemplate<typename FieldT>\nclass xor_not_and : public gadget<FieldT> {\nprivate:\n    std::vector<pb_variable<FieldT>> tmp_vars;\npublic:\n    std::shared_ptr<pb_linear_combination_array<FieldT>> B1;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> B2;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> B3;\n    std::shared_ptr<pb_linear_combination_array<FieldT>> A_out;\n\n    xor_not_and(protoboard<FieldT> &pb,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &B1,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &B2,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &B3,\n                const std::shared_ptr<pb_linear_combination_array<FieldT>> &A_out,\n                const std::string &annotation_prefix);\n\n    void generate_r1cs_constraints();\n    void generate_r1cs_witness();\n};\n\n// ========================================================================================\n// keccakf1600_round algorithm\n// ========================================================================================\ntemplate<typename FieldT>\nclass keccakf1600_round_gadget : public gadget<FieldT> {\npublic:\n    std::vector<std::shared_ptr<xor10_gadget<FieldT>>> compute_xor10;\n    std::vector<std::shared_ptr<rot_xor2_gadget<FieldT>>> compute_rot_xor2;\n    std::vector<std::shared_ptr<pb_linear_combination_array<FieldT>>> D;\n    std::vector<std::shared_ptr<pb_linear_combination_array<FieldT>>> B;\n    std::shared_ptr<xor_not_and_xor<FieldT>> compute_xor_not_and_xor;\n    std::vector<std::shared_ptr<xor_not_and<FieldT>>> compute_xor_not_and;\npublic:\n    std::vector<std::shared_ptr<pb_linear_combination_array<FieldT>>> round_A;\n    std::vector<std::shared_ptr<pb_linear_combination_array<FieldT>>> round_A_out;\n    uint64_t RC;\n\n    keccakf1600_round_gadget(protoboard<FieldT> &pb,\n                                const std::vector<std::shared_ptr<pb_linear_combination_array<FieldT>>> &round_A,\n                                const uint64_t &RC,\n                                const std::vector<std::shared_ptr<pb_linear_combination_array<FieldT>>> &round_A_out,\n                                const std::string &annotation_prefix);\n\n    void generate_r1cs_constraints();\n    void generate_r1cs_witness();\n};\n\ntemplate<typename FieldT>\nclass keccak256_message_schedule_gadget : public gadget<FieldT> {\npublic:\n    std::vector<pb_variable_array<FieldT> > A_bits;\n    std::vector<std::shared_ptr<packing_gadget<FieldT> > > pack_A;\n\npublic:\n    pb_variable_array<FieldT> A;\n    pb_variable_array<FieldT> packed_A;\n    keccak256_message_schedule_gadget(protoboard<FieldT> &pb,\n                                   const pb_variable_array<FieldT> &A,\n                                   const pb_variable_array<FieldT> &packed_A,\n                                   const std::string &annotation_prefix);\n    void generate_r1cs_constraints();\n    void generate_r1cs_witness();\n};\n\n// ========================================================================================\n// keccakf1600 algorithm\n// ========================================================================================\n// IN: A[25]\n// OUT: A_OUT[25]\n// VARIABLES: A_TMP[25](23)\n// CIRCUITS: keccakf1600_round(24)\ntemplate<typename FieldT>\nclass keccakf1600_gadget : public gadget<FieldT> {\npublic:\n    const uint8_t delim;\n    std::vector<std::vector<std::shared_ptr<pb_linear_combination_array<FieldT>>>> round_As;\n    std::vector<keccakf1600_round_gadget<FieldT>> round_functions;\n\n    pb_variable_array<FieldT> packed_A;\n    std::shared_ptr<keccak256_message_schedule_gadget<FieldT> > message_schedule;\n\npublic:\n    block_variable<FieldT> input;\n    digest_variable<FieldT> output;\n\n    keccakf1600_gadget(protoboard<FieldT> &pb,\n                const uint8_t delim,\n                const block_variable<FieldT> &input,\n                const digest_variable<FieldT> &output,\n                const std::string &annotation_prefix);\n\n    void generate_r1cs_constraints();\n    void generate_r1cs_witness();\n};\n\n#define KECCAK256_digest_size   256\n\ntemplate<typename FieldT>\nclass keccak256_gadget : gadget<FieldT> {\npublic:\n    const static uint8_t delim = 0x01;\n    std::shared_ptr<block_variable<FieldT>> block1;\n    std::shared_ptr<block_variable<FieldT>> block2;\n    std::shared_ptr<keccakf1600_gadget<FieldT>> hasher;\n\npublic:\n\n    keccak256_gadget(protoboard<FieldT> &pb,\n                                const digest_variable<FieldT> &left,\n                                const digest_variable<FieldT> &right,\n                                const digest_variable<FieldT> &output,\n                                const std::string &annotation_prefix) :\n        gadget<FieldT>(pb, annotation_prefix)\n    {\n        /* concatenate block = left || right */\n        pb_variable_array<FieldT> input_block;\n        input_block.insert(input_block.end(), left.bits.begin(), left.bits.end());\n        input_block.insert(input_block.end(), right.bits.begin(), right.bits.end());\n\n        /* compute the hash itself */\n        pb_variable<FieldT> ZERO;\n\n        ZERO.allocate(pb, \"ZERO\");\n        pb.val(ZERO) = 0;\n\n        hasher.reset(new keccakf1600_gadget<FieldT>(\n            pb,\n            input_block,\n            output,\n        \"hasher\"));\n    }\n\n    keccak256_gadget(protoboard<FieldT> &pb,\n                                const size_t block_length,\n                                const block_variable<FieldT> &input_block,\n                                const digest_variable<FieldT> &output,\n                                const std::string &annotation_prefix) : gadget<FieldT>(pb, \"sha256_ethereum\") {\n\n        pb_variable<FieldT> ZERO;\n\n        ZERO.allocate(pb, \"ZERO\");\n        pb.val(ZERO) = 0;\n\n        hasher.reset(new keccakf1600_gadget<FieldT>(\n            pb,\n            input_block.bits,\n            output,\n        \"hasher\"));\n    }\n\n    void generate_r1cs_constraints(const bool ensure_output_bitness=true) {\n        libff::UNUSED(ensure_output_bitness);\n        hasher->generate_r1cs_constraints();\n    }\n\n    void generate_r1cs_witness() {\n        hasher->generate_r1cs_witness();\n    }\n\n    static size_t get_digest_len()\n    {\n        return 256;\n    }\n\n    static libff::bit_vector get_hash(const libff::bit_vector &input)\n    {\n        protoboard<FieldT> pb;\n\n        block_variable<FieldT> input_variable(pb, input.size(), \"input\");\n        digest_variable<FieldT> output_variable(pb, KECCAK256_digest_size, \"output\");\n\n        keccakf1600_gadget<FieldT> f(pb, delim, input_variable, output_variable, \"f\");\n\n        input_variable.generate_r1cs_witness(input);\n        f.generate_r1cs_witness();\n\n        return output_variable.get_digest();\n    }\n\n    static size_t expected_constraints(const bool ensure_output_bitness)\n    {\n        libff::UNUSED(ensure_output_bitness);\n        return 54560; /* hardcoded for now */\n    }\n};\n\n\n} // end namespace `gunero`\n\n#endif /* KECCAK_GADGET_H_ */", "meta": {"hexsha": "4332836c50df6ee7ebd9bf89d312dbdc67fa3ae2", "size": 12000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/keccak_gadget.hpp", "max_stars_repo_name": "GunClear/Silencer", "max_stars_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-17T22:27:54.000Z", "max_issues_repo_path": "src/keccak_gadget.hpp", "max_issues_repo_name": "GunClear/Silencer", "max_issues_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T19:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-04T15:49:02.000Z", "max_forks_repo_path": "src/keccak_gadget.hpp", "max_forks_repo_name": "GunClear/Silencer", "max_forks_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_forks_repo_licenses": ["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.7350993377, "max_line_length": 117, "alphanum_fraction": 0.6743333333, "num_tokens": 2917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.16990778279239868}}
{"text": "#include <iostream>\n#include <vector>\n#include <set>\n#include <iterator>\n#include <math.h>\n#include <chrono>\n#include <exception>\n#include <queue>\n#include <boost/math/distributions/normal.hpp>\n#include <sys/time.h>\n#include <rapidcsv.h>\n#include \"ptss_dse.hpp\"\n#include \"ptss_config.hpp\"\n#include \"ptss_pkmin.hpp\"\n\nusing namespace std;\n#define NSAMPLES 100\n\n\n/**\n * Parse a CSV file containing the workloads\n * in the following format\n * Deadline,benchid1,benchid2,...\n */\nint main(int argc, char **argv) {\n    /* Setup the Input/Out File Names */\n    char ifileName[BUFSIZ];\n    char ofileName[BUFSIZ];\n    sprintf(ifileName,\"/home/amaity/Dropbox/workspace/islped_bonmip/workloads-exp1/wkld_%d.csv\",NPH);\n    sprintf(ofileName,\"/home/amaity/Dropbox/workspace/islped_bonmip/workloads-exp1/wkld_%d_cpp.out.csv\",NPH);\n\n    string idata(ifileName);\n    rapidcsv::Document inDoc(idata,rapidcsv::LabelParams(-1,-1));\n    string odata(ofileName);\n    ofstream ofs;\n    ofs.open(ofileName,std::ofstream::out);\n\n    bool done = false;\n    unsigned int idx = 0;\n    while (!done) {\n        ptss_DSE_hrt obj(inDoc,ofs,9.94,idx++,done);\n    }\n    ofs.close();\n}\n", "meta": {"hexsha": "be4df8d7da0c0cc6b765d359aac77d9aee83f5c1", "size": 1152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ptss_test_pkmin3.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_test_pkmin3.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_test_pkmin3.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": 25.6, "max_line_length": 109, "alphanum_fraction": 0.6987847222, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16986847640031713}}
{"text": "#include <boost/hana.hpp>\n#include <mpdef/list.hpp>\n#include <nbdl.hpp>\n#include <string>\n\nnamespace hana = boost::hana;\n\nstruct foo_t { };\nconstexpr hana::type<foo_t> foo{};\n\ntemplate <int i, typename Store>\nvoid make_params_promise(Store const& store)\n{\n  using nbdl::ui_spec::get;\n\n  nbdl::run_sync(\n    nbdl::params_promise(mpdef::make_list(\n      hana::int_c<-1 - i>\n    , get(foo)\n    , hana::int_c<1 + i>\n    , hana::int_c<2 + i>\n    , hana::int_c<3 + i>\n    , hana::int_c<4 + i>\n    ))\n  , store\n  );\n}\n\nint main()\n{\n  auto store = hana::make_map(\n    hana::make_pair(foo, std::string(\"OK!\"))\n  );\n\n#if defined(METABENCH)\n  <%= (0..n).map { |i| \"make_params_promise<#{i}>(store)\" }.join('; ') %>;\n#endif\n}\n", "meta": {"hexsha": "3e4b70543520f918689a48572279571a91e802e9", "size": 714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metabench/params_promise.cpp", "max_stars_repo_name": "ricejasonf/nbdl", "max_stars_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-06-20T01:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:27.000Z", "max_issues_repo_path": "metabench/params_promise.cpp", "max_issues_repo_name": "ricejasonf/nbdl", "max_issues_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T23:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-17T19:01:40.000Z", "max_forks_repo_path": "metabench/params_promise.cpp", "max_forks_repo_name": "ricejasonf/nbdl", "max_forks_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:23:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-09T17:54:25.000Z", "avg_line_length": 18.3076923077, "max_line_length": 74, "alphanum_fraction": 0.5994397759, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16986847291072465}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/Dense>\n#include <boost/hana.hpp>\nnamespace hana = boost::hana;\n\n#include <kontiki/types.h>\n#include <kontiki/measurements/lifting_rscamera_measurement.h>\n#include <kontiki/sfm/landmark.h>\n#include <kontiki/sfm/observation.h>\n\n#include \"../camera_defs.h\"\n#include \"../trajectory_defs.h\"\n\n#include \"measurement_helper.h\"\n\n\nnamespace py = pybind11;\n\nPYBIND11_MODULE(_lifting_rscamera_measurement, m) {\n  m.doc() = \"Lifting rolling shutter projection\";\n\n  // Create one StaticRsMeasurement class for each camera type\n  hana::for_each(camera_types, [&](auto ct) {\n    using CameraModel = typename decltype(ct)::type;\n\n    using Class = kontiki::measurements::LiftingRsCameraMeasurement<CameraModel>;\n    std::string pyclass_name = \"LiftingRsCameraMeasurement_\" + std::string(CameraModel::CLASS_ID);\n    auto cls = py::class_<Class, std::shared_ptr<Class>>(m, pyclass_name.c_str());\n\n    cls.doc() = R\"pbdoc( Rolling shutter projection by time optimization\n\n    Projects a landmark into a rolling shutter camera by adding the projection time\n    as an additional parameter to the optimization problem.\n\n    In general, this does not fulfill the rolling shutter projection time constraint exactly.\n    )pbdoc\";\n\n    declare_measurement_common<Class>(cls);\n    cls.def(py::init<std::shared_ptr<CameraModel>, std::shared_ptr<kontiki::sfm::Observation>, double, double>());\n    cls.def(py::init<std::shared_ptr<CameraModel>, std::shared_ptr<kontiki::sfm::Observation>, double>());\n    cls.def(py::init<std::shared_ptr<CameraModel>, std::shared_ptr<kontiki::sfm::Observation>>());\n\n    cls.def_readonly(\"camera\", &Class::camera);\n    cls.def_readonly(\"observation\", &Class::observation);\n    cls.def_readwrite(\"weight\", &Class::weight, \"Image residual weight (applied before loss)\");\n    cls.def_readonly(\"vt\", &Class::vt_, \"Row projection time (to be optimized)\");\n\n    // Declare the project() function for all trajectory types\n    hana::for_each(trajectory_types, [&](auto tt) {\n      using TrajectoryModel = typename decltype(tt)::type;\n\n      // Use temporary to extract TrajectoryModel from TrajectoryImpl\n      cls.def(\"project\", [](Class &self, const TrajectoryModel &trajectory) {\n        return self.template Project<TrajectoryModel>(trajectory);\n        });\n\n    }); // for_each(trajectory_types)\n  }); // for_each(camera_types)\n}", "meta": {"hexsha": "edf3c38049050c8df2cdaff5e83f0a6339826d2d", "size": 2406, "ext": "cc", "lang": "C++", "max_stars_repo_path": "python/src/kontiki/measurements/py_lifting_rscamera_measurement.cc", "max_stars_repo_name": "copark86/kontiki", "max_stars_repo_head_hexsha": "431349f9500c6ee954bc46c0643f49281163a7f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2018-06-19T05:59:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:25:29.000Z", "max_issues_repo_path": "python/src/kontiki/measurements/py_lifting_rscamera_measurement.cc", "max_issues_repo_name": "copark86/kontiki", "max_issues_repo_head_hexsha": "431349f9500c6ee954bc46c0643f49281163a7f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T06:52:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T15:27:11.000Z", "max_forks_repo_path": "python/src/kontiki/measurements/py_lifting_rscamera_measurement.cc", "max_forks_repo_name": "hovren/kontiki", "max_forks_repo_head_hexsha": "4c44edb7ef041c6abd549e1fe66fe3e9ca255399", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T12:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:34:13.000Z", "avg_line_length": 39.4426229508, "max_line_length": 114, "alphanum_fraction": 0.7256857855, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.16986846942113223}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <eosio/chain/resource_limits.hpp>\n#include <eosio/chain/config.hpp>\n#include <eosio/testing/chainbase_fixture.hpp>\n\n#include <algorithm>\n\nusing namespace eosio::chain::resource_limits;\nusing namespace eosio::testing;\nusing namespace eosio::chain;\n\n\n\nclass resource_limits_fixture_xos: private chainbase_fixture<512*1024>, public resource_limits_manager\n{\n   public:\n      resource_limits_fixture_xos()\n      :chainbase_fixture()\n      ,resource_limits_manager(*chainbase_fixture::_db)\n      {\n         add_indices();\n         initialize_database();\n      }\n\n      ~resource_limits_fixture_xos() {}\n\n      chainbase::database::session start_session() {\n         return chainbase_fixture::_db->start_undo_session(true);\n      }\n};\n\n\nBOOST_AUTO_TEST_SUITE(resource_limits_test_xos)\n\nBOOST_FIXTURE_TEST_CASE(check_block_limits_cpu, resource_limits_fixture_xos) try {\n      const account_name account(1);\n          const uint64_t increment = 1000;\n      initialize_account(account);\n      set_account_limits(account, increment, increment,  increment);\n      process_account_limit_updates();\n\n uint16_t free_resource_limit_per_day = 100;\n//     const auto& chain_config = self.get_global_properties().configuration;\n      uint32_t max_virtual_mult = 1000;\n      uint64_t CPU_TARGET = EOS_PERCENT(config::default_max_block_cpu_usage, config::default_target_block_cpu_usage_pct);\n      set_block_parameters(\n         { CPU_TARGET, config::default_max_block_cpu_usage, config::block_cpu_usage_average_window_ms / config::block_interval_ms, max_virtual_mult, {99, 100}, {1000, 999}},\n         {EOS_PERCENT(config::default_max_transaction_net_usage, config::default_target_block_net_usage_pct), config::default_max_block_net_usage, config::block_size_average_window_ms / config::block_interval_ms, max_virtual_mult, {99, 100}, {1000, 999}}\n      );\n     set_block_parameters_xos(free_resource_limit_per_day\n      );\n\n\n      const uint64_t expected_iterations = config::default_max_block_cpu_usage / increment;\n\n      for (int idx = 0; idx < expected_iterations; idx++) {\n         add_transaction_usage({account}, increment, 0, 0);\n      }\n      int64_t r =0;\n      int64_t n =0;\n      int64_t c =0;\n  \n     std::tie(r,n,c)=   check_account_limits_xos(account,r,n,c);\n      BOOST_REQUIRE_EQUAL(n, 0);\n      BOOST_REQUIRE_THROW(add_transaction_usage({account}, increment, 0, 0), block_resource_exhausted);\n\n   } FC_LOG_AND_RETHROW();\n\nBOOST_FIXTURE_TEST_CASE(check_block_limits_cpu_lowerthan, resource_limits_fixture_xos) try {\n      const account_name account(1);\n          const uint64_t increment = 1000;\n      initialize_account(account);\n      set_account_limits(account, increment, increment,  increment);\n      process_account_limit_updates();\n      \n uint16_t free_resource_limit_per_day = 300;\n//     const auto& chain_config = self.get_global_properties().configuration;\n      uint32_t max_virtual_mult = 1000;\n      uint64_t CPU_TARGET = EOS_PERCENT(config::default_max_block_cpu_usage, config::default_target_block_cpu_usage_pct);\n      set_block_parameters(\n         { CPU_TARGET, config::default_max_block_cpu_usage, config::block_cpu_usage_average_window_ms / config::block_interval_ms, max_virtual_mult, {99, 100}, {1000, 999}},\n         {EOS_PERCENT(config::default_max_transaction_net_usage, config::default_target_block_net_usage_pct), config::default_max_block_net_usage, config::block_size_average_window_ms / config::block_interval_ms, max_virtual_mult, {99, 100}, {1000, 999}}\n        );\n\n     set_block_parameters_xos(free_resource_limit_per_day\n      );\n\n      const uint64_t expected_iterations = config::default_max_block_cpu_usage / increment;\n\n      for (int idx = 0; idx < expected_iterations; idx++) {\n         add_transaction_usage({account}, increment, 0, 0);\n      }\n      int64_t r =0;\n      int64_t n =0;\n      int64_t c =0;\n  \n     std::tie(r,n,c)=   check_account_limits_xos(account,r,n,c);\n      BOOST_REQUIRE_EQUAL(r, 0);\n      BOOST_REQUIRE_EQUAL(n, -1);\n      BOOST_REQUIRE_EQUAL(c, -1);\n      BOOST_REQUIRE_THROW(add_transaction_usage({account}, increment, 0, 0), block_resource_exhausted);\n\n   } FC_LOG_AND_RETHROW();\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8cb6567844cf48260ad49970811f258429e7568b", "size": 4224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/resource_limits_test_xos.cpp", "max_stars_repo_name": "vlbos/myeosblacklist", "max_stars_repo_head_hexsha": "46486cae8ea181bf0c66a080f35177ff5dd9dcfb", "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": "unittests/resource_limits_test_xos.cpp", "max_issues_repo_name": "vlbos/myeosblacklist", "max_issues_repo_head_hexsha": "46486cae8ea181bf0c66a080f35177ff5dd9dcfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/resource_limits_test_xos.cpp", "max_forks_repo_name": "vlbos/myeosblacklist", "max_forks_repo_head_hexsha": "46486cae8ea181bf0c66a080f35177ff5dd9dcfb", "max_forks_repo_licenses": ["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.476635514, "max_line_length": 254, "alphanum_fraction": 0.734375, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.1698542993760029}}
{"text": "/*=============================================================================\n    Copyright (c) 2011 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\n#ifndef HPX_CONFIG_PP_ROUND_UP_HPP\n#define HPX_CONFIG_PP_ROUND_UP_HPP\n\n#include <boost/preprocessor/cat.hpp>\n\n#define HPX_PP_ROUND_UP(N)                                                    \\\n      BOOST_PP_CAT(HPX_PP_DO_ROUND_UP_, N)()                                  \\\n/**/\n\n#define HPX_PP_DO_ROUND_UP_0()   5\n#define HPX_PP_DO_ROUND_UP_1()   5\n#define HPX_PP_DO_ROUND_UP_2()   5\n#define HPX_PP_DO_ROUND_UP_3()   5\n#define HPX_PP_DO_ROUND_UP_4()   5\n#define HPX_PP_DO_ROUND_UP_5()   5\n#define HPX_PP_DO_ROUND_UP_6()  10\n#define HPX_PP_DO_ROUND_UP_7()  10\n#define HPX_PP_DO_ROUND_UP_8()  10\n#define HPX_PP_DO_ROUND_UP_9()  10\n#define HPX_PP_DO_ROUND_UP_10() 10\n#define HPX_PP_DO_ROUND_UP_11() 15\n#define HPX_PP_DO_ROUND_UP_12() 15\n#define HPX_PP_DO_ROUND_UP_13() 15\n#define HPX_PP_DO_ROUND_UP_14() 15\n#define HPX_PP_DO_ROUND_UP_15() 15\n#define HPX_PP_DO_ROUND_UP_16() 20\n#define HPX_PP_DO_ROUND_UP_17() 20\n#define HPX_PP_DO_ROUND_UP_18() 20\n#define HPX_PP_DO_ROUND_UP_19() 20\n#define HPX_PP_DO_ROUND_UP_20() 20\n// #define HPX_PP_DO_ROUND_UP_21() 25\n// #define HPX_PP_DO_ROUND_UP_22() 25\n// #define HPX_PP_DO_ROUND_UP_23() 25\n// #define HPX_PP_DO_ROUND_UP_24() 25\n// #define HPX_PP_DO_ROUND_UP_25() 25\n// #define HPX_PP_DO_ROUND_UP_26() 30\n// #define HPX_PP_DO_ROUND_UP_27() 30\n// #define HPX_PP_DO_ROUND_UP_28() 30\n// #define HPX_PP_DO_ROUND_UP_29() 30\n// #define HPX_PP_DO_ROUND_UP_30() 30\n// #define HPX_PP_DO_ROUND_UP_31() 35\n// #define HPX_PP_DO_ROUND_UP_32() 35\n// #define HPX_PP_DO_ROUND_UP_33() 35\n// #define HPX_PP_DO_ROUND_UP_34() 35\n// #define HPX_PP_DO_ROUND_UP_35() 35\n// #define HPX_PP_DO_ROUND_UP_36() 40\n// #define HPX_PP_DO_ROUND_UP_37() 40\n// #define HPX_PP_DO_ROUND_UP_38() 40\n// #define HPX_PP_DO_ROUND_UP_39() 40\n// #define HPX_PP_DO_ROUND_UP_40() 40\n// #define HPX_PP_DO_ROUND_UP_41() 45\n// #define HPX_PP_DO_ROUND_UP_42() 45\n// #define HPX_PP_DO_ROUND_UP_43() 45\n// #define HPX_PP_DO_ROUND_UP_44() 45\n// #define HPX_PP_DO_ROUND_UP_45() 45\n// #define HPX_PP_DO_ROUND_UP_46() 50\n// #define HPX_PP_DO_ROUND_UP_47() 50\n// #define HPX_PP_DO_ROUND_UP_48() 50\n// #define HPX_PP_DO_ROUND_UP_49() 50\n// #define HPX_PP_DO_ROUND_UP_50() 50\n\n#endif\n", "meta": {"hexsha": "6a8c498e06f5616d38ba980b5e48d90cd80c8011", "size": 2514, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hpx/config/preprocessor/round_up.hpp", "max_stars_repo_name": "Titzi90/hpx", "max_stars_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "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": "hpx/config/preprocessor/round_up.hpp", "max_issues_repo_name": "Titzi90/hpx", "max_issues_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "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": "hpx/config/preprocessor/round_up.hpp", "max_forks_repo_name": "Titzi90/hpx", "max_forks_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "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.9142857143, "max_line_length": 80, "alphanum_fraction": 0.7000795545, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.16975467453676527}}
{"text": "/*\n * 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 */\n\n#include \"RemoveRecursiveLocks.h\"\n\n#include <bitset>\n#include <boost/optional.hpp>\n#include <boost/variant.hpp>\n#include <limits>\n\n#include \"BaseIRAnalyzer.h\"\n#include \"CFGMutation.h\"\n#include \"ConstantAbstractDomain.h\"\n#include \"ControlFlow.h\"\n#include \"IRInstruction.h\"\n#include \"MethodProfiles.h\"\n#include \"PatriciaTreeMapAbstractEnvironment.h\"\n#include \"ReachingDefinitions.h\"\n#include \"ScopedCFG.h\"\n#include \"Trace.h\"\n#include \"Walkers.h\"\n\nnamespace {\n\nusing namespace cfg;\n\nconstexpr bool kDebugPass = false;\n\n// The pass attempts to remove recursive locks which may for example be exposed\n// by inlining of synchronized methods.\n//\n// For simple and safe removal, a method needs to be correct wrt/ structured\n// locking, i.e., locks need to come in pairs and need to be correctly nested.\n// In that case, tracking the lock depth allows a simple decision on whether to\n// remove the lock operations.\n//\n// The datastructures are similar to the Android verifier: locking is tracked as\n// a virtual stack, where each \"source\" has a \"stack\" of bits defining whether\n// it is locked at that level. A key difference is that no alias tracking is\n// done. Instead, a reaching-definitions analysis is run beforehand to derive\n// the (single) \"source\" for each monitor instruction.\n//\n//   Program-State: Lock-Object(as Instruction*) x Lock-State\n//   Lock-State:    Bit-Stack(as int)\n//   Sample meaning:\n//    0=unlocked,\n//    1=0b01 = locked first\n//    2=0b10 = locked second\n//    3=0b11 = locked first and second = recursively locked\n\nnamespace analysis {\n\n// At what levels of the virtual stack is the corresponding\n// object locked? This limits the analysis to a nesting depth,\n// but this is normally enough, and corresponds to Android's\n// verifier.\nusing LockType = uint32_t;\nusing LockDepths = sparta::ConstantAbstractDomain<LockType>;\nconstexpr size_t kMaxLockDepth = sizeof(LockType) * 8;\n\n// It would be nice to have an environment that is automatically TOP\n// if any element is. However, wiring that up seems nontrivial. So\n// this is another test in the `check` function.\nusing LockEnvironment =\n    sparta::PatriciaTreeMapAbstractEnvironment<const IRInstruction*,\n                                               LockDepths>;\n\nsize_t clz(LockType val) {\n  static_assert(sizeof(val) == 4 || sizeof(val) == 8, \"Unsupported type\");\n  return sizeof(val) == 4 ? __builtin_clz(val) : __builtin_clzll(val);\n}\n\nsize_t get_max_depth(LockType val) {\n  if (val != 0) {\n    return kMaxLockDepth - clz(val);\n  }\n  return 0;\n}\n\nsize_t get_max_depth(const LockEnvironment& env) {\n  if (env.is_top() || env.is_bottom()) {\n    return 0;\n  }\n  size_t max = 0;\n  for (const auto& p : env.bindings()) {\n    if (p.second.is_value()) {\n      max = std::max(max, get_max_depth(*p.second.get_constant()));\n    }\n  }\n  return max;\n}\n\n// Computes the number of recursive locks.\nsize_t get_per(LockType val) {\n  // Use bitset. It should generate the optimal architectural instruction.\n  return std::bitset<kMaxLockDepth>(val).count();\n}\n\n// Computes the maximum number of recursive locks.\nsize_t get_max_depth_per(const LockEnvironment& env) {\n  if (env.is_top() || env.is_bottom()) {\n    return 0;\n  }\n  size_t max = 0;\n  for (const auto& p : env.bindings()) {\n    if (p.second.is_value()) {\n      max = std::max(max, get_per(*p.second.get_constant()));\n    }\n  }\n  return max;\n}\n\n// Very simplistic check.\n// We could do more integrity checks, e.g., no two instructions are locked at\n// the same depth, there are no holes, ...\nbool is_valid(const LockEnvironment& env, size_t expected_count) {\n  return env.bindings().size() == expected_count;\n}\n\n// Map a lock operation to the instruction defining the object to be locked on.\nusing RDefs = std::unordered_map<const IRInstruction*, const IRInstruction*>;\n\nstruct LocksIterator : public ir_analyzer::BaseIRAnalyzer<LockEnvironment> {\n  LocksIterator(const cfg::ControlFlowGraph& cfg, const RDefs& rdefs)\n      : ir_analyzer::BaseIRAnalyzer<LockEnvironment>(cfg), rdefs(rdefs) {}\n\n  // Edges are complicated. For MONITOR_ENTER, they indicate the operation\n  // did not actually succeed, so the counted lock must be undone. For\n  // MONITOR_EXIT, however, Android handles this as not-throwing at all,\n  // so the edge needs to be overwritten completely.\n  LockEnvironment analyze_edge(\n      const cfg::GraphInterface::EdgeId& e,\n      const LockEnvironment& exit_state_at_source) const override {\n    if (!exit_state_at_source.is_value()) {\n      return exit_state_at_source;\n    }\n    if (e->type() != EDGE_THROW) {\n      return exit_state_at_source;\n    }\n    // Check whether this is a throw with a MONITOR_ENTER. We'd need\n    // to undo the modification then.\n    const IRInstruction* monitor_insn;\n    {\n      auto src = e->src();\n      auto last_it = src->get_last_insn();\n      if (last_it == src->end()) {\n        return exit_state_at_source;\n      }\n\n      if (!is_monitor(last_it->insn->opcode())) {\n        return exit_state_at_source;\n      }\n      monitor_insn = last_it->insn;\n    }\n\n    auto it = rdefs.find(monitor_insn);\n    if (it == rdefs.end()) {\n      // Uh-oh. Something is wrong, maybe was non-singleton reachable.\n      return LockEnvironment(sparta::AbstractValueKind::Top);\n    }\n\n    auto def = it->second;\n    auto def_state = exit_state_at_source.get(def);\n    if (def_state.is_top() || def_state.is_bottom()) {\n      // Uh-oh. Something is wrong.\n      return LockEnvironment(sparta::AbstractValueKind::Top);\n    }\n\n    LockType locks = *def_state.get_constant();\n    size_t max_all_d = get_max_depth(exit_state_at_source);\n\n    if (monitor_insn->opcode() == OPCODE_MONITOR_EXIT) {\n      // A monitor exit is not actually handled as throwing. See\n      // https://cs.android.com/android/platform/superproject/+/android-4.0.4_r2.1:dalvik/vm/analysis/CodeVerify.cpp;l=4146\n      //\n      // As such, pretend this edge isn't there.\n      return LockEnvironment(sparta::AbstractValueKind::Bottom);\n    }\n\n    size_t max_d = get_max_depth(locks);\n    if (max_d == 0 || max_all_d != max_d) {\n      // Uh-oh. Something is wrong.\n      return LockEnvironment(sparta::AbstractValueKind::Top);\n    }\n\n    // OK, undo and return.\n    LockType new_locks = locks ^ (1 << (max_d - 1));\n    always_assert_log(\n        new_locks < locks, \"%d x %d -> %d\", locks, max_d, new_locks);\n    auto ret = exit_state_at_source;\n    ret.set(def, LockDepths(new_locks));\n    return ret;\n  }\n\n  void analyze_instruction(const IRInstruction* insn,\n                           LockEnvironment* current_state) const override {\n    if (!is_monitor(insn->opcode())) {\n      return;\n    }\n    if (!current_state->is_value()) {\n      return;\n    }\n\n    auto it = rdefs.find(insn);\n    if (it == rdefs.end()) {\n      // Something's bad.\n      current_state->set_to_top();\n      return;\n    }\n    auto def = it->second;\n    auto def_state = current_state->get(def);\n    size_t max_d = get_max_depth(*current_state);\n\n    if (insn->opcode() == OPCODE_MONITOR_ENTER) {\n      if (max_d == kMaxLockDepth) {\n        // Oh well...\n        current_state->set_to_top();\n        return;\n      }\n      LockType base = def_state.is_value() ? *def_state.get_constant() : 0;\n      current_state->set(def, LockDepths(base | (1 << max_d)));\n      return;\n    }\n\n    if (!def_state.is_value()) {\n      // Uh-oh.\n      current_state->set_to_top();\n      return;\n    }\n    LockType old = *def_state.get_constant();\n    size_t max_old_d = get_max_depth(old);\n    if (old == 0 || max_old_d != max_d) {\n      // Uh-oh.\n      current_state->set_to_top();\n      return;\n    }\n\n    LockType new_locks = old ^ (1 << (max_old_d - 1));\n    always_assert_log(new_locks < old, \"%d x %d -> %d\", old, max_d, new_locks);\n    current_state->set(def, LockDepths(new_locks));\n  }\n\n  const RDefs& rdefs;\n};\n\nboost::optional<RDefs> compute_rdefs(ControlFlowGraph& cfg) {\n  std::unique_ptr<reaching_defs::MoveAwareFixpointIterator> rdefs;\n  auto get_defs = [&](Block* b, const IRInstruction* i) {\n    if (!rdefs) {\n      rdefs.reset(new reaching_defs::MoveAwareFixpointIterator(cfg));\n      rdefs->run(reaching_defs::Environment());\n    }\n    auto defs_in = rdefs->get_entry_state_at(b);\n    for (const auto& it : ir_list::InstructionIterable{b}) {\n      if (it.insn == i) {\n        break;\n      }\n      rdefs->analyze_instruction(it.insn, &defs_in);\n    }\n    return defs_in;\n  };\n  auto get_singleton = [](auto& defs, reg_t reg) -> IRInstruction* {\n    auto defs0 = defs.get(reg);\n    if (defs0.is_top() || defs0.is_bottom()) {\n      return nullptr;\n    }\n    if (defs0.elements().size() != 1) {\n      return nullptr;\n    }\n    return *defs0.elements().begin();\n  };\n\n  std::unordered_map<const IRInstruction*, Block*> block_map;\n  auto get_rdef = [&](IRInstruction* insn, reg_t reg) -> IRInstruction* {\n    auto it = block_map.find(insn);\n    redex_assert(it != block_map.end());\n    auto defs = get_defs(it->second, insn);\n    return get_singleton(defs, reg);\n  };\n\n  auto print_rdefs = [&](IRInstruction* insn, reg_t reg) -> std::string {\n    auto it = block_map.find(insn);\n    redex_assert(it != block_map.end());\n    auto defs = get_defs(it->second, insn);\n    auto defs0 = defs.get(reg);\n    if (defs0.is_top()) {\n      return \"top\";\n    }\n    if (defs0.is_bottom()) {\n      return \"bottom\";\n    }\n    std::ostringstream oss;\n    oss << \"{\";\n    for (auto i : defs0.elements()) {\n      oss << \", \" << show(i);\n    }\n    oss << \"}\";\n    return oss.str();\n  };\n\n  std::vector<IRInstruction*> monitor_insns;\n  for (auto* b : cfg.blocks()) {\n    for (auto& mie : *b) {\n      if (mie.type != MFLOW_OPCODE) {\n        continue;\n      }\n      block_map.emplace(mie.insn, b);\n      if (is_monitor(mie.insn->opcode())) {\n        monitor_insns.push_back(mie.insn);\n      }\n    }\n  }\n\n  // Check that there is at most one monitor instruction per block.\n  // We use that simplification later to not have to walk through\n  // blocks.\n  {\n    std::unordered_set<Block*> seen_blocks;\n    for (auto* monitor_insn : monitor_insns) {\n      auto b = block_map.at(monitor_insn);\n      if (seen_blocks.count(b) > 0) {\n        return boost::none;\n      }\n      seen_blocks.insert(b);\n    }\n  }\n\n  RDefs ret;\n  for (auto* monitor_insn : monitor_insns) {\n    auto find_root_def = [&](IRInstruction* cur) -> IRInstruction* {\n      for (;;) {\n        IRInstruction* next;\n        switch (cur->opcode()) {\n        case OPCODE_MONITOR_ENTER:\n        case OPCODE_MONITOR_EXIT:\n          next = get_rdef(cur, cur->src(0));\n          break;\n\n        // Ignore check-cast, go further.\n        case OPCODE_CHECK_CAST:\n          next = get_rdef(cur, cur->src(0));\n          break;\n\n        default:\n          return cur;\n        }\n        if (next == nullptr) {\n          if (kDebugPass || traceEnabled(LOCKS, 4)) {\n            std::cerr << show(cur) << \" has non-singleton rdefs \"\n                      << print_rdefs(cur, cur->src(0)) << std::endl;\n          }\n          return nullptr;\n        }\n        cur = next;\n      }\n    };\n\n    auto root_rdef = find_root_def(monitor_insn);\n    if (root_rdef == nullptr) {\n      return boost::none;\n    }\n    if (root_rdef != nullptr) {\n      ret.emplace(monitor_insn, root_rdef);\n    }\n  }\n\n  return ret;\n}\n\nLockEnvironment create_start(const RDefs& rdefs) {\n  LockEnvironment env;\n  for (const auto& p : rdefs) {\n    env.set(p.second, LockDepths(0));\n  }\n  return env;\n}\n\n} // namespace analysis\n\n// Return `true` if this is an interesting method.\nboost::variant<bool, std::pair<size_t, size_t>> check(\n    analysis::LocksIterator& iter,\n    ControlFlowGraph& cfg,\n    size_t sources_count) {\n  size_t max_d = 0;\n  size_t max_same = 0;\n  for (auto* b : cfg.blocks()) {\n    auto state = iter.get_entry_state_at(b);\n    if (state.is_top()) {\n      return false;\n    }\n    if (state.is_value()) {\n      if (!analysis::is_valid(state, sources_count)) {\n        return false;\n      }\n    }\n    max_d = std::max(max_d, analysis::get_max_depth(state));\n    max_same = std::max(max_same, analysis::get_max_depth_per(state));\n  }\n  return std::make_pair(max_d, max_same);\n}\n\n// Debug helper. Print CFG and after it a list of states.\nvoid print(std::ostream& os,\n           const analysis::RDefs& rdefs,\n           analysis::LocksIterator& iter,\n           ControlFlowGraph& cfg) {\n  os << show(cfg) << std::endl;\n  for (const auto& p : rdefs) {\n    os << \" # \" << p.first << \" -> \" << p.second << std::endl;\n  }\n  os << std::endl;\n  for (auto* b : cfg.blocks()) {\n    os << \" * B\" << b->id() << \": \";\n\n    auto print_state = [&os](const auto& state) {\n      if (state.is_bottom()) {\n        os << \"bot\";\n      } else if (state.is_top()) {\n        os << \"top\";\n      } else {\n        for (const auto& p : state.bindings()) {\n          os << \" \" << p.first << \"=\";\n          if (p.second.is_bottom()) {\n            os << \"bot\";\n          } else if (p.second.is_top()) {\n            os << \"top\";\n          } else {\n            os << *p.second.get_constant();\n          }\n        }\n      }\n    };\n\n    auto entry_state = iter.get_entry_state_at(b);\n    print_state(entry_state);\n    os << \" ===> \";\n\n    for (const auto& it : ir_list::InstructionIterable{b}) {\n      iter.analyze_instruction(it.insn, &entry_state);\n    }\n    print_state(entry_state);\n    os << \" (\";\n    print_state(iter.get_exit_state_at(b));\n    os << \")\";\n\n    os << std::endl;\n    os << \"    \";\n    {\n      analysis::LockEnvironment env(sparta::AbstractValueKind::Bottom);\n      print_state(env);\n      for (auto* edge : GraphInterface::predecessors(cfg, b)) {\n        auto prev_exit =\n            iter.get_exit_state_at(GraphInterface::source(cfg, edge));\n        auto analyzed = iter.analyze_edge(edge, prev_exit);\n        env.join_with(analyzed);\n        os << \" =(\" << edge->src()->id() << \"=\";\n        print_state(prev_exit);\n        os << \"->\";\n        print_state(analyzed);\n        os << \")=> \";\n        print_state(env);\n      }\n    }\n    os << std::endl;\n  }\n}\n\nstruct AnalysisResult {\n  AnalysisResult() = default;\n  AnalysisResult(AnalysisResult&& other) noexcept\n      : rdefs(std::move(other.rdefs)),\n        iter(std::move(other.iter)),\n        method_with_locks(other.method_with_locks),\n        non_singleton_rdefs(other.non_singleton_rdefs),\n        method_with_issues(other.method_with_issues),\n        max_d(other.max_d),\n        max_same(other.max_same) {}\n\n  AnalysisResult& operator=(AnalysisResult&& rhs) noexcept {\n    rdefs = std::move(rhs.rdefs);\n    iter = std::move(rhs.iter);\n    method_with_locks = rhs.method_with_locks;\n    non_singleton_rdefs = rhs.non_singleton_rdefs;\n    method_with_issues = rhs.method_with_issues;\n    max_d = rhs.max_d;\n    max_same = rhs.max_same;\n    return *this;\n  }\n\n  analysis::RDefs rdefs;\n  std::unique_ptr<analysis::LocksIterator> iter;\n\n  bool method_with_locks{false};\n  bool non_singleton_rdefs{false};\n  bool method_with_issues{false};\n\n  size_t max_d{0};\n  size_t max_same{0};\n};\n\nAnalysisResult analyze(ControlFlowGraph& cfg) {\n  AnalysisResult ret;\n  ret.method_with_locks = true;\n  // 2) Run ReachingDefs.\n  auto rdefs_opt = analysis::compute_rdefs(cfg);\n  if (!rdefs_opt) {\n    ret.non_singleton_rdefs = true;\n    return ret;\n  }\n\n  ret.rdefs = std::move(*rdefs_opt);\n\n  // 3) Run our iterator.\n  ret.iter = std::make_unique<analysis::LocksIterator>(cfg, ret.rdefs);\n  size_t sources_count;\n  {\n    auto env = analysis::create_start(ret.rdefs);\n    sources_count = env.bindings().size();\n    ret.iter->run(env);\n  }\n\n  // 4) Go over and see.\n  auto check_res = check(*ret.iter, cfg, sources_count);\n\n  if (check_res.which() == 0) {\n    ret.method_with_issues = true;\n    if (boost::strict_get<bool>(check_res)) {\n      // Diagnostics.\n      print(std::cerr, ret.rdefs, *ret.iter, cfg);\n    };\n    return ret;\n  }\n\n  const auto& p = boost::strict_get<std::pair<size_t, size_t>>(check_res);\n  ret.max_d = p.first;\n  ret.max_same = p.second;\n\n  return ret;\n}\n\nsize_t remove(ControlFlowGraph& cfg, AnalysisResult& analysis) {\n  CFGMutation mutation(cfg);\n  size_t removed = 0;\n  for (auto* b : cfg.blocks()) {\n    auto state = analysis.iter->get_entry_state_at(b);\n    redex_assert(!state.is_top());\n    if (state.is_bottom()) {\n      continue;\n    }\n\n    for (const auto& insn_it : ir_list::InstructionIterable{b}) {\n      if (is_monitor(insn_it.insn->opcode())) {\n        auto it = analysis.rdefs.find(insn_it.insn);\n        redex_assert(it != analysis.rdefs.end());\n        auto def = it->second;\n\n        auto& bindings = state.bindings();\n        auto def_state = bindings.at(def);\n        if (def_state.is_value()) {\n          size_t times = analysis::get_per(*def_state.get_constant());\n          if (times >=\n              (insn_it.insn->opcode() == OPCODE_MONITOR_ENTER ? 1 : 2)) {\n            mutation.remove(cfg.find_insn(insn_it.insn, b));\n            ++removed;\n          }\n        }\n      }\n      analysis.iter->analyze_instruction(insn_it.insn, &state);\n    }\n  }\n  mutation.flush();\n  return removed;\n}\n\n// Verification computes the \"cover\" (set of all locked objects)\n// for all blocks and compares.\nboost::optional<std::string> verify(cfg::ControlFlowGraph& cfg,\n                                    const AnalysisResult& orig,\n                                    const AnalysisResult& removed) {\n  std::ostringstream oss;\n  for (auto* b : cfg.blocks()) {\n    auto new_state = removed.iter->get_entry_state_at(b);\n    redex_assert(!new_state.is_top());\n    auto old_state = orig.iter->get_entry_state_at(b);\n    redex_assert(!old_state.is_top());\n    redex_assert(new_state.is_bottom() || !old_state.is_bottom());\n    if (new_state.is_bottom()) {\n      continue;\n    }\n\n    auto cover = [](const auto& s) {\n      std::unordered_set<const IRInstruction*> res;\n      for (const auto& p : s.bindings()) {\n        if (p.second.is_value() && *p.second.get_constant() != 0) {\n          res.insert(p.first);\n        }\n      }\n      return res;\n    };\n    auto old_cover = cover(old_state);\n    auto new_cover = cover(new_state);\n    if (old_cover != new_cover) {\n      oss << \"Cover difference in block B\" << b->id() << \": \";\n      auto add_cover = [&oss](const auto& c) {\n        auto add = [&oss](auto* i) {\n          oss << \" \" << i << \"(\" << show(i) << \")\";\n        };\n        oss << \"[\";\n        for (auto* i : c) {\n          add(i);\n        }\n        oss << \"]\";\n      };\n      add_cover(old_cover);\n      oss << \" vs \";\n      add_cover(new_cover);\n      oss << std::endl;\n    }\n  }\n  std::string res = oss.str();\n  if (!res.empty()) {\n    return std::move(res);\n  }\n  return boost::none;\n}\n\nstruct Stats {\n  static constexpr size_t kArraySize = analysis::kMaxLockDepth + 1;\n  std::array<std::unordered_set<DexMethod*>, kArraySize> counts;\n  std::array<std::unordered_set<DexMethod*>, kArraySize> counts_per;\n  size_t all_methods{1};\n  size_t methods_with_locks{0};\n  size_t removed{0};\n  std::unordered_set<DexMethod*> methods_with_issues;\n  std::unordered_set<DexMethod*> non_singleton_rdefs;\n\n  Stats& operator+=(const Stats& rhs) {\n    for (size_t i = 0; i < counts.size(); ++i) {\n      counts[i].insert(rhs.counts[i].begin(), rhs.counts[i].end());\n    }\n    for (size_t i = 0; i < counts_per.size(); ++i) {\n      counts_per[i].insert(rhs.counts_per[i].begin(), rhs.counts_per[i].end());\n    }\n    all_methods += rhs.all_methods;\n    methods_with_locks += rhs.methods_with_locks;\n    removed += rhs.removed;\n    methods_with_issues.insert(rhs.methods_with_issues.begin(),\n                               rhs.methods_with_issues.end());\n    non_singleton_rdefs.insert(rhs.non_singleton_rdefs.begin(),\n                               rhs.non_singleton_rdefs.end());\n    return *this;\n  }\n};\n\nbool has_monitor_ops(const IRCode* code) {\n  for (const auto& mie : ir_list::InstructionIterableImpl<true>(code)) {\n    if (is_monitor(mie.insn->opcode())) {\n      return true;\n    }\n  }\n  return false;\n}\n\nStats run_locks_removal(DexMethod* m, IRCode* code) {\n  // 1) Check whether there are MONITOR_ENTER instructions.\n  if (!has_monitor_ops(code)) {\n    return Stats{};\n  }\n\n  cfg::ScopedCFG cfg(code);\n  Stats stats{};\n  auto analysis = analyze(*cfg);\n\n  stats.methods_with_locks = analysis.method_with_locks ? 1 : 0;\n  if (analysis.non_singleton_rdefs) {\n    stats.non_singleton_rdefs.insert(m);\n    return stats;\n  }\n  if (analysis.method_with_issues) {\n    stats.methods_with_issues.insert(m);\n    return stats;\n  }\n\n  stats.counts[analysis.max_d].insert(m);\n  stats.counts_per[analysis.max_same].insert(m);\n\n  if (analysis.max_same > 1) {\n    size_t removed = remove(*cfg, analysis);\n    redex_assert(removed > 0);\n    cfg->simplify(); // Remove dead blocks.\n\n    // Run analysis again just to check.\n    auto analysis2 = analyze(*cfg);\n    always_assert_log(!analysis2.non_singleton_rdefs, \"%s\", SHOW(*cfg));\n    always_assert_log(!analysis2.method_with_issues, \"%s\", SHOW(*cfg));\n    auto verify_res = verify(*cfg, analysis, analysis2);\n    auto print_err = [&m, &verify_res, &analysis2, &cfg]() {\n      std::ostringstream oss;\n      oss << show(m) << \": \" << *verify_res << std::endl;\n      print(oss, analysis2.rdefs, *analysis2.iter, *cfg);\n      return oss.str();\n    };\n    always_assert_log(!verify_res, \"%s\", print_err().c_str());\n\n    stats.removed += removed;\n  }\n\n  return stats;\n}\n\nvoid run_impl(DexStoresVector& stores,\n              ConfigFiles& conf,\n              PassManager& mgr,\n              const char* stats_prefix = nullptr) {\n  auto scope = build_class_scope(stores);\n\n  Stats stats =\n      walk::parallel::methods<Stats>(scope, [](DexMethod* method) -> Stats {\n        auto code = method->get_code();\n        if (code != nullptr) {\n          return run_locks_removal(method, code);\n        }\n        return Stats{};\n      });\n\n  auto print = [&mgr, &stats_prefix](const std::string& name, size_t stat) {\n    mgr.set_metric(stats_prefix == nullptr ? name : stats_prefix + name, stat);\n    if (kDebugPass || traceEnabled(LOCKS, 1)) {\n      std::cerr << (stats_prefix == nullptr ? \"\" : stats_prefix) << name\n                << \" = \" << stat << std::endl;\n    }\n  };\n  auto prof = conf.get_method_profiles();\n  if (!prof.has_stats()) {\n    TRACE(LOCKS, 2, \"No profiles available!\");\n  }\n  auto sorted = [&prof](const std::unordered_set<DexMethod*>& in) {\n    std::vector<DexMethod*> ret(in.begin(), in.end());\n    std::sort(ret.begin(),\n              ret.end(),\n              [&prof](const DexMethod* lhs, const DexMethod* rhs) {\n                auto lhs_prof =\n                    prof.get_method_stat(method_profiles::COLD_START, lhs);\n                auto rhs_prof =\n                    prof.get_method_stat(method_profiles::COLD_START, rhs);\n                if (lhs_prof) {\n                  if (rhs_prof) {\n                    return lhs_prof->call_count > rhs_prof->call_count;\n                  }\n                  return true;\n                }\n                if (rhs_prof) {\n                  return false;\n                }\n\n                return compare_dexmethods(lhs, rhs);\n              });\n    return ret;\n  };\n\n  print(\"all_methods\", stats.all_methods);\n  print(\"methods_with_locks\", stats.methods_with_locks);\n  print(\"methods_with_issues\", stats.methods_with_issues.size());\n  if (!stats.methods_with_issues.empty()) {\n    std::cerr << \"Lock analysis failed for:\" << std::endl;\n    for (auto m : sorted(stats.methods_with_issues)) {\n      std::cerr << \" * \" << show(m) << std::endl;\n    }\n  }\n  print(\"non_singleton_rdefs\", stats.non_singleton_rdefs.size());\n  if (kDebugPass || traceEnabled(LOCKS, 2)) {\n    for (auto m : sorted(stats.non_singleton_rdefs)) {\n      std::cerr << \" * \" << show(m) << std::endl;\n    }\n  }\n  print(\"removed\", stats.removed);\n\n  auto print_counts = [&print](const auto& counts, const std::string& prefix) {\n    size_t last = counts.size() - 1;\n    while (last != 0 && counts[last].empty()) {\n      --last;\n    }\n    for (size_t i = 0; i <= last; ++i) {\n      std::string name = prefix;\n      name += std::to_string(i);\n      print(name, counts[i].size());\n    }\n  };\n  print_counts(stats.counts, \"counts\");\n  print_counts(stats.counts_per, \"counts_per\");\n\n  if (kDebugPass || traceEnabled(LOCKS, 3)) {\n    for (size_t i = 3; i < stats.counts_per.size(); ++i) {\n      if (!stats.counts_per[i].empty()) {\n        std::cerr << \"=== \" << i << \" ===\" << std::endl;\n        for (auto m : sorted(stats.counts_per[i])) {\n          std::cerr << \" * \" << show(m);\n          auto prof_stats =\n              prof.get_method_stat(method_profiles::COLD_START, m);\n          if (prof_stats) {\n            std::cerr << \" \" << prof_stats->call_count << \" / \"\n                      << prof_stats->appear_percent;\n          }\n          std::cerr << std::endl;\n        }\n      }\n    }\n  }\n}\n\n} // namespace\n\nbool RemoveRecursiveLocksPass::run(DexMethod* method, IRCode* code) {\n  auto stats = run_locks_removal(method, code);\n  return stats.methods_with_locks > 0 && stats.methods_with_issues.empty() &&\n         stats.non_singleton_rdefs.empty();\n}\n\nvoid RemoveRecursiveLocksPass::run_pass(DexStoresVector& stores,\n                                        ConfigFiles& conf,\n                                        PassManager& mgr) {\n  run_impl(stores, conf, mgr);\n  if (kDebugPass) {\n    run_impl(stores, conf, mgr, \"debug_2nd_\");\n  }\n}\n\nstatic RemoveRecursiveLocksPass s_pass;\n", "meta": {"hexsha": "3c4efe39dffac2d8ae8dd431b1ea15d146f53c13", "size": 25475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opt/remove-recursive-locks/RemoveRecursiveLocks.cpp", "max_stars_repo_name": "terrorizer1980/redex", "max_stars_repo_head_hexsha": "ccebb0b253518a9094b6da6398e9071f8d7a36f4", "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": "opt/remove-recursive-locks/RemoveRecursiveLocks.cpp", "max_issues_repo_name": "terrorizer1980/redex", "max_issues_repo_head_hexsha": "ccebb0b253518a9094b6da6398e9071f8d7a36f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opt/remove-recursive-locks/RemoveRecursiveLocks.cpp", "max_forks_repo_name": "terrorizer1980/redex", "max_forks_repo_head_hexsha": "ccebb0b253518a9094b6da6398e9071f8d7a36f4", "max_forks_repo_licenses": ["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.5455635492, "max_line_length": 123, "alphanum_fraction": 0.6131501472, "num_tokens": 6554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.16975466749494275}}
{"text": "#ifndef GUNEROMEMBERSHIP_GADGET_H_\n#define GUNEROMEMBERSHIP_GADGET_H_\n\n#include <deque>\n#include <boost/optional.hpp>\n#include <boost/static_assert.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>\n#include <libff/algebra/fields/field_utils.hpp>\n#include <libff/algebra/scalar_multiplication/multiexp.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>\n#include <libff/common/utils.hpp>\n\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>\n\n#include \"uint252.h\"\n#include \"gunero_merkle_tree_gadget.hpp\"\n\nusing namespace libsnark;\n\nnamespace gunero {\n\n///// MEMBERSHIP PROOF /////\n// Public Parameters:\n// Authorization Root Hash (W)\n// Account Status (N_account)\n// Account View Hash (V_account)\n\n// Private Parameters:\n// Account Secret Key (s_account)\n// alt: Account (A_account)\n// Authorization Merkle Path (M_account[160])\n// Account View Randomizer (r_account)\n\n//1) Obtain A_account from s_account through EDCSA (secp256k1) operations\n//1 alt) Obtain P_proof from s_account through PRF operations\n//2) Validate W == calc_root(A_account, N_account, M_account[160]) (User is authorized)\n//2 alt) Validate W == calc_root(A_account, keccak256(P_proof,N_account), M_account[160]) (User is authorized)\n//3) Validate V_account == keccak256(A_account, keccak256(W,r_account) (View Hash is consistent)\n//3 alt) Validate V_account == keccak256(P_proof, keccak256(W,r_account) (View Hash is consistent)\ntemplate<typename FieldT, typename BaseT, typename HashT, size_t tree_depth>\nclass guneromembership_gadget : public gadget<FieldT> {\npublic:\n    // Verifier inputs\n    pb_variable_array<FieldT> zk_packed_inputs;\n    pb_variable_array<FieldT> zk_unpacked_inputs;\n    std::shared_ptr<multipacking_gadget<FieldT>> unpacker;\n    std::shared_ptr<digest_variable<FieldT>> W;\n    std::shared_ptr<digest_variable<FieldT>> N_account;\n    std::shared_ptr<digest_variable<FieldT>> V_account;\n\n    // Aux inputs\n    // pb_variable<FieldT> ZERO;\n    std::shared_ptr<digest_variable<FieldT>> ZERO;\n    std::shared_ptr<digest_variable<FieldT>> s_account;\n    std::shared_ptr<gunero_merkle_tree_gadget<FieldT, HashT, tree_depth>> gunero_merkle_tree;\n    std::shared_ptr<digest_variable<FieldT>> r_account;\n    std::shared_ptr<digest_variable<FieldT>> A_account;\n\n    // Computed variables\n    std::shared_ptr<digest_variable<FieldT>> P_proof;\n    // std::shared_ptr<PRF_addr_a_pk_simple_gadget<FieldT>> spend_authority;\n    std::shared_ptr<HashT> spend_authority;\n    std::shared_ptr<digest_variable<FieldT>> leaf_digest;\n    std::shared_ptr<HashT> leaf_hasher;\n    std::shared_ptr<digest_variable<FieldT>> view_hash_1_digest;\n    std::shared_ptr<HashT> view_hash_1_hasher;\n    std::shared_ptr<HashT> view_hash_2_hasher;\n\n    guneromembership_gadget(protoboard<FieldT>& pb)\n        : gadget<FieldT>(pb, \"guneromembership_gadget\")\n    {\n        // Verifier inputs\n        {\n            // The verification inputs are all bit-strings of various\n            // lengths (256-bit digests and 64-bit integers) and so we\n            // pack them into as few field elements as possible. (The\n            // more verification inputs you have, the more expensive\n            // verification is.)\n            zk_packed_inputs.allocate(pb, verifying_field_element_size());\n            pb.set_input_sizes(verifying_field_element_size());\n\n            alloc_uint256(zk_unpacked_inputs, W);\n            alloc_uint256(zk_unpacked_inputs, N_account);\n            alloc_uint256(zk_unpacked_inputs, V_account);\n\n            assert(zk_unpacked_inputs.size() == verifying_input_bit_size());\n\n            // This gadget will ensure that all of the inputs we provide are\n            // boolean constrained.\n            unpacker.reset(new multipacking_gadget<FieldT>(\n                pb,\n                zk_unpacked_inputs,\n                zk_packed_inputs,\n                FieldT::capacity(),\n                \"unpacker\"\n            ));\n        }\n\n        // We need a constant \"zero\" variable in some contexts. In theory\n        // it should never be necessary, but libsnark does not synthesize\n        // optimal circuits.\n        //\n        // The first variable of our constraint system is constrained\n        // to be one automatically for us, and is known as `ONE`.\n        // ZERO.allocate(pb);\n        ZERO.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        //We enforce 256 bits instead of 252 because of hash size compliance\n        s_account.reset(new digest_variable<FieldT>(pb, 256, \"\"));//252\n\n        P_proof.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        // spend_authority.reset(new PRF_addr_a_pk_simple_gadget<FieldT>(\n        //     pb,\n        //     ZERO,\n        //     s_account->bits,\n        //     P_proof\n        // ));\n        spend_authority.reset(new HashT(\n            pb,\n            *s_account,\n            *ZERO,\n            *P_proof,\n            \"spend_authority\"));\n\n        leaf_digest.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        leaf_hasher.reset(new HashT(\n            pb,\n            *P_proof,\n            *N_account,\n            *leaf_digest,\n            \"leaf_hasher\"));\n\n        gunero_merkle_tree.reset(new gunero_merkle_tree_gadget<FieldT, HashT, tree_depth>(\n            pb,\n            *leaf_digest,\n            *W,\n            ONE,\n            \"gunero_merkle_tree\"));\n\n        r_account.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        view_hash_1_digest.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        view_hash_1_hasher.reset(new HashT(\n            pb,\n            *W,\n            *r_account,\n            *view_hash_1_digest,\n            \"view_hash_1_hasher\"));\n\n        A_account.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        view_hash_2_hasher.reset(new HashT(\n            pb,\n            *P_proof,\n            *view_hash_1_digest,\n            *V_account,\n            \"view_hash_2_hasher\"));\n    }\n\n    ~guneromembership_gadget()\n    {\n\n    }\n\n    static size_t verifying_input_bit_size() {\n        size_t acc = 0;\n\n        //W\n        acc += HashT::get_digest_len(); // the merkle root (anchor) => libff::bit_vector root(digest_len); \n\n        //N_account\n        //acc += 2;\n        acc += 256;\n\n        //V_account\n        acc += HashT::get_digest_len();\n\n        return acc;\n    }\n\n    static size_t verifying_field_element_size() {\n        return div_ceil(verifying_input_bit_size(), FieldT::capacity());\n    }\n\n    void generate_r1cs_constraints(\n        const std::string& r1csPath,\n        const std::string& pkPath,\n        const std::string& vkPath\n        )\n    {\n#ifdef DEBUG\n        libff::print_header(\"Gunero constraints\");\n#endif\n\n        // The true passed here ensures all the inputs\n        // are boolean constrained.\n        unpacker->generate_r1cs_constraints(true);\n\n        // Constrain `ZERO`\n        // generate_r1cs_equals_const_constraint<FieldT>(this->pb, ZERO, FieldT::zero(), \"ZERO\");\n        ZERO->generate_r1cs_constraints();\n\n        s_account->generate_r1cs_constraints();\n\n        P_proof->generate_r1cs_constraints();\n\n        spend_authority->generate_r1cs_constraints();\n\n        leaf_digest->generate_r1cs_constraints();\n\n        leaf_hasher->generate_r1cs_constraints();\n\n        // Constrain bitness of merkle_tree\n        gunero_merkle_tree->generate_r1cs_constraints();\n\n        r_account->generate_r1cs_constraints();\n\n        view_hash_1_digest->generate_r1cs_constraints();\n\n        view_hash_1_hasher->generate_r1cs_constraints();\n\n        A_account->generate_r1cs_constraints();\n\n        view_hash_2_hasher->generate_r1cs_constraints();\n\n        //Calculate constraints\n        r1cs_constraint_system<FieldT> constraint_system = this->pb.get_constraint_system();\n\n        if (r1csPath.length() > 0)\n        {\n            saveToFile(r1csPath, constraint_system);\n        }\n\n#ifdef DEBUG\n        printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after generator\"); libff::print_time(\"after generator\");\n#endif\n\n        r1cs_ppzksnark_keypair<BaseT> keypair = r1cs_ppzksnark_generator<BaseT>(constraint_system);\n\n        //Verify\n        r1cs_ppzksnark_processed_verification_key<BaseT> vk_precomp = r1cs_ppzksnark_verifier_process_vk<BaseT>(keypair.vk);\n\n        if (pkPath.length() > 0)\n        {\n            saveToFile(pkPath, keypair.pk);\n        }\n\n        if (vkPath.length() > 0)\n        {\n            saveToFile(vkPath, keypair.vk);\n        }\n\n#ifdef DEBUG\n        printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after constraints\"); libff::print_time(\"after constraints\");\n#endif\n    }\n\n    // Public Parameters:\n    // Authorization Root Hash (W)\n    // Account Status (N_account)\n    // Account View Hash (V_account)\n\n    // Private Parameters:\n    // alt X: Account Secret Key (s_account)\n    // alt: Proof Secret Key (s_account)\n    // alt: Account (A_account)\n    // Authorization Merkle Path (M_account[160])\n    // Account View Randomizer (r_account)\n    void generate_r1cs_witness(\n        const uint256& pW,\n        const uint8_t pN_account,\n        const uint256& pV_account,\n        const uint252& ps_account,\n        const std::vector<gunero_merkle_authentication_node>& pM_account,\n        const uint160& pA_account,\n        const uint256& pr_account\n    )\n    {\n        // Witness rt. This is not a sanity check.\n        W->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pW)\n        );\n\n        // Witness Status bits\n        N_account->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(uint8_to_uint256(pN_account))\n        );\n\n        // Witness view hash. This is not a sanity check.\n        V_account->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pV_account)\n        );\n\n        // Witness `zero`\n        // this->pb.val(ZERO) = FieldT::zero();\n        ZERO->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(uint256())\n        );\n\n        // Witness s_account for the input\n        s_account->bits.fill_with_bits(\n            this->pb,\n            uint252_to_bool_vector_256(ps_account)\n        );\n\n        // Witness P_proof for s_account with PRF_addr\n        spend_authority->generate_r1cs_witness();\n\n        // Witness hash(P_proof, N_account) = leaf_digest\n        leaf_hasher->generate_r1cs_witness();\n\n        //Trim account to correct size\n        // A_account_padded = libff::bit_vector(HashT::get_digest_len() - A_account.size());\n        // A_account_padded.insert(A_account_padded.begin(), A_account.begin(), A_account.end());\n        libff::bit_vector A_account_padded = uint160_to_bool_vector_256_rpad(pA_account);\n        if (A_account_padded.size() > tree_depth)\n        {\n            A_account_padded.erase(A_account_padded.begin() + tree_depth, A_account_padded.end());\n        }\n        else if (A_account_padded.size() < tree_depth)\n        {\n            throw std::runtime_error(strprintf(\"pA_account cannot be a size less than %lu\", tree_depth));\n        }\n\n        // Witness merkle tree authentication path\n        gunero_merkle_tree->generate_r1cs_witness(pM_account, A_account_padded);\n\n        // Witness r_account for the input\n        r_account->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pr_account)\n        );\n\n        // Witness hash(W, r_account) = view_hash_1_digest\n        view_hash_1_hasher->generate_r1cs_witness();\n\n        // Witness A_account for the input\n        A_account->bits.fill_with_bits(\n            this->pb,\n            uint160_to_bool_vector_256_rpad(pA_account)\n        );\n\n        // Witness hash(P_proof, view_hash_1_digest) = V_account\n        view_hash_2_hasher->generate_r1cs_witness();\n\n        // [SANITY CHECK] Ensure that the intended root\n        // was witnessed by the inputs, even if the read\n        // gadget overwrote it. This allows the prover to\n        // fail instead of the verifier, in the event that\n        // the roots of the inputs do not match the\n        // treestate provided to the proving API.\n        W->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pW)\n        );\n\n        // [SANITY CHECK] Ensure that the intended root\n        // was witnessed by the inputs, even if the read\n        // gadget overwrote it. This allows the prover to\n        // fail instead of the verifier, in the event that\n        // the roots of the inputs do not match the\n        // hash provided to the proving hashers.\n        V_account->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pV_account)\n        );\n\n        // This happens last, because only by now are all the\n        // verifier inputs resolved.\n        unpacker->generate_r1cs_witness_from_bits();\n    }\n\n    static r1cs_primary_input<FieldT> witness_map(\n        const uint256& pW,\n        const uint8_t& pN_account,\n        const uint256& pV_account\n    ) {\n        std::vector<bool> verify_inputs;\n\n        insert_uint256(verify_inputs, pW);\n\n        //insert_uint_bits(verify_inputs, status, 2);\n        insert_uint256(verify_inputs, uint8_to_uint256(pN_account));\n\n        insert_uint256(verify_inputs, pV_account);\n\n        assert(verify_inputs.size() == verifying_input_bit_size());\n        auto verify_field_elements = libff::pack_bit_vector_into_field_element_vector<FieldT>(verify_inputs);\n        assert(verify_field_elements.size() == verifying_field_element_size());\n        return verify_field_elements;\n    }\n\n    void alloc_uint256(\n        pb_variable_array<FieldT>& packed_into,\n        std::shared_ptr<digest_variable<FieldT>>& var\n    ) {\n        var.reset(new digest_variable<FieldT>(this->pb, 256, \"\"));\n        packed_into.insert(packed_into.end(), var->bits.begin(), var->bits.end());\n    }\n};\n\n} // end namespace `gunero`\n\n#endif /* GUNEROMEMBERSHIP_GADGET_H_ */", "meta": {"hexsha": "e49ea348ccd0d7d6870f530a11387fdbbc972632", "size": 14636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/guneromembership_gadget.hpp", "max_stars_repo_name": "GunClear/Silencer", "max_stars_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-17T22:27:54.000Z", "max_issues_repo_path": "src/guneromembership_gadget.hpp", "max_issues_repo_name": "GunClear/Silencer", "max_issues_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T19:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-04T15:49:02.000Z", "max_forks_repo_path": "src/guneromembership_gadget.hpp", "max_forks_repo_name": "GunClear/Silencer", "max_forks_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_forks_repo_licenses": ["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.682464455, "max_line_length": 124, "alphanum_fraction": 0.6563268653, "num_tokens": 3601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.16971140908999655}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <array>\n#include <cmath>\n#include <numeric>\n#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <thread>\n#include <GraphMol/SmilesParse/SmilesParse.h>\n#include <GraphMol/FileParsers/MolSupplier.h>\n#include <GraphMol/MolDrawing/DrawingToSVG.h>\n#include <GraphMol/Fingerprints/MorganFingerprints.h>\n#include <GraphMol/Substruct/SubstructMatch.h>\n#include <Numerics/Alignment/AlignPoints.h>\n#include <GraphMol/MolTransforms/MolTransforms.h>\n#include <GraphMol/FileParsers/MolWriters.h>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <mongo/client/dbclient.h>\n#include \"io_service_pool.hpp\"\n#include \"safe_counter.hpp\"\nusing namespace std;\nusing namespace std::chrono;\nusing namespace RDKit;\nusing namespace RDKit::MolOps;\nusing namespace RDDepict;\nusing namespace RDKit::Drawing;\nusing namespace RDKit::MorganFingerprints;\nusing namespace RDGeom;\nusing namespace RDNumeric::Alignments;\nusing namespace MolTransforms;\nusing namespace boost::filesystem;\nusing namespace boost::gregorian;\nusing namespace boost::posix_time;\nusing namespace mongo;\nusing namespace bson;\n\ninline static auto local_time()\n{\n\treturn to_simple_string(microsec_clock::local_time()) + \" \";\n}\n\ninline static auto milliseconds_since_epoch()\n{\n\treturn Date_t(duration_cast<chrono::milliseconds>(system_clock::now().time_since_epoch()).count());\n}\n\ntemplate <typename T>\ninline vector<T> read(const path src)\n{\n\tboost::filesystem::ifstream ifs(src, ios::binary | ios::ate);\n\tconst size_t num_bytes = ifs.tellg();\n\tcout << local_time() << \"Reading \" << src << \" of \" << num_bytes << \" bytes\" << endl;\n\tvector<T> buf;\n\tbuf.resize(num_bytes / sizeof(T));\n\tifs.seekg(0);\n\tifs.read(reinterpret_cast<char*>(buf.data()), num_bytes);\n\treturn buf;\n}\n\ntemplate <typename size_type>\nclass header_array\n{\npublic:\n\texplicit header_array(path src)\n\t{\n\t\tsrc.replace_extension(\".ftr\");\n\t\tboost::filesystem::ifstream ifs(src, ios::binary | ios::ate);\n\t\tconst size_t num_bytes = ifs.tellg();\n\t\tcout << local_time() << \"Reading \" << src << \" of \" << num_bytes << \" bytes\" << endl;\n\t\thdr.resize(1 + num_bytes / sizeof(size_type));\n\t\thdr.front() = 0;\n\t\tifs.seekg(0);\n\t\tifs.read(reinterpret_cast<char*>(hdr.data() + 1), num_bytes);\n\t}\n\n\tsize_t size() const\n\t{\n\t\treturn hdr.size() - 1;\n\t}\n\nprotected:\n\tvector<size_type> hdr;\n};\n\ntemplate <typename size_type>\nclass string_array : public header_array<size_type>\n{\npublic:\n\texplicit string_array(const path src) : header_array<size_type>(src)\n\t{\n\t\tboost::filesystem::ifstream ifs(src, ios::binary | ios::ate);\n\t\tconst size_t num_bytes = ifs.tellg();\n\t\tcout << local_time() << \"Reading \" << src << \" of \" << num_bytes << \" bytes\" << endl;\n\t\tbuf.resize(num_bytes);\n\t\tifs.seekg(0);\n\t\tifs.read(const_cast<char*>(buf.data()), num_bytes);\n\t}\n\n\tstring operator[](const size_t index) const\n\t{\n\t\tconst auto pos = this->hdr[index];\n\t\tconst auto len = this->hdr[index + 1] - pos;\n\t\treturn buf.substr(pos, len);\n\t}\n\nprotected:\n\tstring buf;\n};\n\ntemplate <typename size_type>\nclass stream_array : public header_array<size_type>\n{\npublic:\n\texplicit stream_array(const path src) : header_array<size_type>(src), ifs(src, ios::binary)\n\t{\n\t}\n\n\tstring operator[](const size_t index)\n\t{\n\t\tconst auto pos = this->hdr[index];\n\t\tconst auto len = this->hdr[index + 1] - pos;\n\t\tstring buf;\n\t\tbuf.resize(len);\n\t\tifs.seekg(pos);\n\t\tifs.read(const_cast<char*>(buf.data()), len);\n\t\treturn buf;\n\t}\n\nprotected:\n\tboost::filesystem::ifstream ifs;\n};\n\ntemplate<typename T>\ndouble dist2(const T& p0, const T& p1)\n{\n\tconst auto d0 = p0[0] - p1[0];\n\tconst auto d1 = p0[1] - p1[1];\n\tconst auto d2 = p0[2] - p1[2];\n\treturn d0 * d0 + d1 * d1 + d2 * d2;\n}\n\narray<Point3D, 4> calcRefPoints(const ROMol& mol, const vector<int>& heavyAtoms)\n{\n\tconst auto num_points = heavyAtoms.size();\n\tassert(num_points == mol.getNumHeavyAtoms());\n\tconst auto& conf = mol.getConformer();\n\tarray<Point3D, 4> refPoints;\n\tfor (auto& ref : refPoints)\n\t{\n\t\tassert(ref[0] == 0);\n\t\tassert(ref[1] == 0);\n\t\tassert(ref[2] == 0);\n\t}\n\tauto& ctd = refPoints[0];\n\tauto& cst = refPoints[1];\n\tauto& fct = refPoints[2];\n\tauto& ftf = refPoints[3];\n\tfor (const auto i : heavyAtoms)\n\t{\n\t\tconst auto& a = conf.getAtomPos(i);\n\t\tctd += a;\n\t}\n\tctd /= num_points;\n\tdouble cst_dist = numeric_limits<double>::max();\n\tdouble fct_dist = numeric_limits<double>::lowest();\n\tdouble ftf_dist = numeric_limits<double>::lowest();\n\tfor (const auto i : heavyAtoms)\n\t{\n\t\tconst auto& a = conf.getAtomPos(i);\n\t\tconst auto this_dist = dist2(a, ctd);\n\t\tif (this_dist < cst_dist)\n\t\t{\n\t\t\tcst = a;\n\t\t\tcst_dist = this_dist;\n\t\t}\n\t\tif (this_dist > fct_dist)\n\t\t{\n\t\t\tfct = a;\n\t\t\tfct_dist = this_dist;\n\t\t}\n\t}\n\tfor (const auto i : heavyAtoms)\n\t{\n\t\tconst auto& a = conf.getAtomPos(i);\n\t\tconst auto this_dist = dist2(a, fct);\n\t\tif (this_dist > ftf_dist)\n\t\t{\n\t\t\tftf = a;\n\t\t\tftf_dist = this_dist;\n\t\t}\n\t}\n\treturn refPoints;\n}\n\nint main(int argc, char* argv[])\n{\n\t// Check the required number of command line arguments.\n\tif (argc != 5)\n\t{\n\t\tcout << \"usr host user pwd jobs_path\" << endl;\n\t\treturn 0;\n\t}\n\n\t// Fetch command line arguments.\n\tconst auto host = argv[1];\n\tconst auto user = argv[2];\n\tconst auto pwd = argv[3];\n\tconst path jobs_path = argv[4];\n\n\tDBClientConnection conn;\n\t{\n\t\t// Connect to host and authenticate user.\n\t\tcout << local_time() << \"Connecting to \" << host << \" and authenticating \" << user << endl;\n\t\tstring errmsg;\n\t\tif ((!conn.connect(host, errmsg)) || (!conn.auth(\"istar\", user, pwd, errmsg)))\n\t\t{\n\t\t\tcerr << local_time() << errmsg << endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t// Initialize constants.\n\tcout << local_time() << \"Initializing\" << endl;\n\tconst auto collection = \"istar.usr2\";\n\tconst size_t num_usrs = 2;\n\tconst array<string, 2> usr_names{{ \"USR\", \"USRCAT\" }};\n\tconstexpr array<size_t, num_usrs> qn{{ 12, 60 }};\n\tconstexpr array<double, num_usrs> qv{{ 1.0 / qn[0], 1.0 / qn[1] }};\n\tconst size_t num_refPoints = 4;\n\tconst size_t num_subsets = 5;\n\tconst array<string, num_subsets> SubsetSMARTS\n\t{{\n\t\t\"[!#1]\", // heavy\n\t\t\"[#6+0!$(*~[#7,#8,F]),SH0+0v2,s+0,S^3,Cl+0,Br+0,I+0]\", // hydrophobic\n\t\t\"[a]\", // aromatic\n\t\t\"[$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N&v3;H1,H2]-[!$(*=[O,N,P,S])]),$([N;v3;H0]),$([n,o,s;+0]),F]\", // acceptor\n\t\t\"[N!H0v3,N!H0+v4,OH+0,SH+0,nH+0]\", // donor\n\t}};\n\tconst size_t num_hits = 100;\n\n\t// Wrap SMARTS strings to RWMol objects.\n\tarray<unique_ptr<ROMol>, num_subsets> SubsetMols;\n\tfor (size_t k = 0; k < num_subsets; ++k)\n\t{\n\t\tSubsetMols[k].reset(reinterpret_cast<ROMol*>(SmartsToMol(SubsetSMARTS[k])));\n\t}\n\n\t// Read ZINC ID file.\n\tconst string_array<size_t> zincids(\"16/zincid.txt\");\n\tconst auto num_ligands = zincids.size();\n\tcout << local_time() << \"Found \" << num_ligands << \" database molecules\" << endl;\n\n\t// Read SMILES file.\n\tconst string_array<size_t> smileses(\"16/smiles.txt\");\n\tassert(smileses.size() == num_ligands);\n\n\t// Read supplier file.\n\tconst string_array<size_t> suppliers(\"16/supplier.txt\");\n\tassert(suppliers.size() == num_ligands);\n\n\t// Read property files of floating point types and integer types.\n\tconst auto zfproperties = read<array<float, 4>>(\"16/zfprop.f32\");\n\tassert(zfproperties.size() == num_ligands);\n\tconst auto ziproperties = read<array<int16_t, 5>>(\"16/ziprop.i16\");\n\tassert(ziproperties.size() == num_ligands);\n\n\t// Read cumulative number of conformers file.\n\tconst auto mconfss = read<size_t>(\"16/mconfs.u64\");\n\tconst auto num_conformers = mconfss.back();\n\tassert(mconfss.size() == num_ligands);\n\tassert(num_conformers >= num_ligands);\n\tcout << local_time() << \"Found \" << num_conformers << \" database conformers\" << endl;\n\n\t// Read feature file.\n\tconst auto features = read<array<double, qn.back()>>(\"16/usrcat.f64\");\n\tassert(features.size() == num_conformers);\n\n\t// Read ligand footer file and open ligand SDF file for seeking and reading.\n\tstream_array<size_t> ligands(\"16/ligand.sdf\");\n\tassert(ligands.size() == num_conformers);\n\n\t// Initialize variables.\n\tarray<vector<int>, num_subsets> subsets;\n\tarray<vector<double>, num_refPoints> dista;\n\talignas(32) array<double, qn.back()> q;\n\n\t// Initialize vectors to store compounds' primary score and their corresponding conformer.\n\tvector<double> scores(num_ligands); // Primary score of molecules.\n\tvector<size_t> cnfids(num_ligands); // ID of conformer with the best primary score.\n\tconst auto compare = [&](const size_t val0, const size_t val1) // Sort by the primary score.\n\t{\n\t\treturn scores[val0] < scores[val1];\n\t};\n\n\t// Initialize an io service pool and create worker threads for later use.\n\tconst size_t num_threads = thread::hardware_concurrency();\n\tcout << local_time() << \"Creating an io service pool of \" << num_threads << \" worker threads\" << endl;\n\tio_service_pool io(num_threads);\n\tsafe_counter<size_t> cnt;\n\n\t// Initialize the number of chunks and the number of molecules per chunk.\n\tconst auto num_chunks = num_threads << 4;\n\tconst auto chunk_size = 1 + (num_ligands - 1) / num_chunks;\n\tassert(chunk_size * num_chunks >= num_ligands);\n\tassert(chunk_size >= num_hits);\n\tcout << local_time() << \"Using \" << num_chunks << \" chunks and a chunk size of \" << chunk_size << endl;\n\tvector<size_t> scase(num_ligands);\n\tvector<size_t> zcase(num_hits * (num_chunks - 1) + min(num_hits, num_ligands - chunk_size * (num_chunks - 1))); // The last chunk might have fewer than num_hits records.\n\n\t// Enter event loop.\n\tcout << local_time() << \"Entering event loop\" << endl;\n\tcout.setf(ios::fixed, ios::floatfield);\n\tbool sleeping = false;\n\twhile (true)\n\t{\n\t\t// Fetch an incompleted job in a first-come-first-served manner.\n\t\tif (!sleeping) cout << local_time() << \"Fetching an incompleted job\" << endl;\n\t\tBSONObj info;\n\t\tconst auto started = milliseconds_since_epoch();\n\t\tconn.runCommand(\"istar\", BSON(\"findandmodify\" << \"usr2\" << \"query\" << BSON(\"started\" << BSON(\"$exists\" << false)) << \"sort\" << BSON(\"submitted\" << 1) << \"update\" << BSON(\"$set\" << BSON(\"started\" << started))), info); // conn.findAndModify() is available since MongoDB C++ Driver legacy-1.0.0\n\t\tconst auto value = info[\"value\"];\n\t\tif (value.isNull())\n\t\t{\n\t\t\t// No incompleted jobs. Sleep for a while.\n\t\t\tif (!sleeping) cout << local_time() << \"Sleeping\" << endl;\n\t\t\tsleeping = true;\n\t\t\tthis_thread::sleep_for(chrono::seconds(2));\n\t\t\tcontinue;\n\t\t}\n\t\tsleeping = false;\n\t\tconst auto job = value.Obj();\n\n\t\t// Obtain job properties.\n\t\tconst auto _id = job[\"_id\"].OID();\n\t\tcout << local_time() << \"Executing job \" << _id.str() << endl;\n\t\tconst auto job_path = jobs_path / _id.str();\n\t\tconst size_t usr0 = job[\"usr\"].Int(); // Specify the primary sorting score. 0: USR; 1: USRCAT.\n\t\tassert(usr0 == 0 || usr0 == 1);\n\t\tconst auto usr1 = usr0 ^ 1;\n\t\tconst auto qnu0 = qn[usr0];\n\t\tconst auto qnu1 = qn[usr1];\n\n\t\t// Read and validate the user-supplied SDF file.\n\t\tcout << local_time() << \"Reading and validating the query file\" << endl;\n\t\tSDMolSupplier sup((job_path / \"query.sdf\").string(), true, false, true); // sanitize, removeHs, strictParsing. Note: setting removeHs=true (which is the default setting) will lead to fewer hydrogen bond acceptors being matched.\n\t\tif (!sup.length() || !sup.atEnd())\n\t\t{\n\t\t\tconst auto error = 1;\n\t\t\tcout << local_time() << \"Failed to parse the query file, error code = \" << error << endl;\n\t\t\tconn.update(collection, BSON(\"_id\" << _id), BSON(\"$set\" << BSON(\"completed\" << milliseconds_since_epoch() << \"error\" << error)));\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Process each of the query molecules sequentially.\n\t\tconst auto num_queries = 1; // Restrict the number of query molecules to 1. Setting num_queries = sup.length() to execute any number of query molecules.\n\t\tfor (unsigned int query_number = 0; query_number < num_queries; ++query_number)\n\t\t{\n\t\t\tcout << local_time() << \"Parsing query molecule \" << query_number << endl;\n\t\t\tconst unique_ptr<ROMol> qry_ptr(sup.next()); // Calling next() may print \"ERROR: Could not sanitize molecule on line XXXX\" to stderr.\n\t\t\tauto& qryMol = *qry_ptr;\n\n\t\t\t// Get the number of atoms, including and excluding hydrogens.\n\t\t\tconst auto num_atoms = qryMol.getNumAtoms();\n\t\t\tconst auto num_heavy_atoms = qryMol.getNumHeavyAtoms();\n\t\t\tassert(num_heavy_atoms);\n\t\t\tcout << local_time() << \"Found \" << num_atoms << \" atoms and \" << num_heavy_atoms << \" heavy atoms\" << endl;\n\n\t\t\t// Create an output directory.\n\t\t\tcout << local_time() << \"Creating output directory\" << endl;\n\t\t\tconst auto output_dir = job_path / to_string(query_number);\n\t\t\tcreate_directory(output_dir);\n\n\t\t\t// Draw a SVG.\n\t\t\tcout << local_time() << \"Drawing a SVG\" << endl;\n\t\t\t{\n\t\t\t\tconst unique_ptr<ROMol> qrz_ptr(removeHs(qryMol));\n\t\t\t\tauto& qrzMol = *qrz_ptr;\n\t\t\t\tcompute2DCoords(qrzMol);\n\t\t\t\tboost::filesystem::ofstream ofs(output_dir / \"query.svg\");\n\t\t\t\tofs << DrawingToSVG(MolToDrawing(qrzMol));\n\t\t\t}\n\n\t\t\t// Calculate Morgan fingerprint.\n\t\t\tcout << local_time() << \"Calculating Morgan fingerprint\" << endl;\n\t\t\tconst unique_ptr<SparseIntVect<uint32_t>> qryFp(getFingerprint(qryMol, 2));\n\n\t\t\t// Classify atoms to pharmacophoric subsets.\n\t\t\tcout << local_time() << \"Classifying atoms into subsets\" << endl;\n\t\t\tfor (size_t k = 0; k < num_subsets; ++k)\n\t\t\t{\n\t\t\t\tvector<vector<pair<int, int>>> matchVect;\n\t\t\t\tSubstructMatch(qryMol, *SubsetMols[k], matchVect);\n\t\t\t\tconst auto num_matches = matchVect.size();\n\t\t\t\tauto& subset = subsets[k];\n\t\t\t\tsubset.resize(num_matches);\n\t\t\t\tfor (size_t i = 0; i < num_matches; ++i)\n\t\t\t\t{\n\t\t\t\t\tsubset[i] = matchVect[i].front().second;\n\t\t\t\t}\n\t\t\t\tcout << local_time() << \"Found \" << num_matches << \" atoms for subset \" << k << endl;\n\t\t\t}\n\t\t\tconst auto& subset0 = subsets.front();\n\t\t\tassert(subset0.size() == num_heavy_atoms);\n\n\t\t\t// Calculate the four reference points.\n\t\t\tcout << local_time() << \"Calculating \" << num_refPoints << \" reference points\" << endl;\n\t\t\tconst auto qryRefPoints = calcRefPoints(qryMol, subset0);\n\t\t\tconst Point3DConstPtrVect qryRefPointv\n\t\t\t{{\n\t\t\t\t&qryRefPoints[0],\n\t\t\t\t&qryRefPoints[1],\n\t\t\t\t&qryRefPoints[2],\n\t\t\t\t&qryRefPoints[3],\n\t\t\t}};\n\n\t\t\t// Precalculate the distances of heavy atoms to the reference points, given that subsets[1 to 4] are subsets of subsets[0].\n\t\t\tcout << local_time() << \"Calculating \" << num_heavy_atoms * num_refPoints << \" pairwise distances\" << endl;\n\t\t\tconst auto& qryCnf = qryMol.getConformer();\n\t\t\tfor (size_t k = 0; k < num_refPoints; ++k)\n\t\t\t{\n\t\t\t\tconst auto& refPoint = qryRefPoints[k];\n\t\t\t\tauto& distp = dista[k];\n\t\t\t\tdistp.resize(num_atoms);\n\t\t\t\tfor (size_t i = 0; i < num_heavy_atoms; ++i)\n\t\t\t\t{\n\t\t\t\t\tdistp[subset0[i]] = sqrt(dist2(qryCnf.getAtomPos(subset0[i]), refPoint));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Loop over pharmacophoric subsets and reference points.\n\t\t\tcout << local_time() << \"Calculating \" << 3 * num_refPoints * num_subsets << \" moments of USRCAT feature\" << endl;\n\t\t\tsize_t qo = 0;\n\t\t\tfor (const auto& subset : subsets)\n\t\t\t{\n\t\t\t\tconst auto n = subset.size();\n\t\t\t\tfor (size_t k = 0; k < num_refPoints; ++k)\n\t\t\t\t{\n\t\t\t\t\t// Load distances from precalculated ones.\n\t\t\t\t\tconst auto& distp = dista[k];\n\t\t\t\t\tvector<double> dists(n);\n\t\t\t\t\tfor (size_t i = 0; i < n; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tdists[i] = distp[subset[i]];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Compute moments.\n\t\t\t\t\tarray<double, 3> m{};\n\t\t\t\t\tif (n > 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst auto v = 1.0 / n;\n\t\t\t\t\t\tfor (size_t i = 0; i < n; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst auto d = dists[i];\n\t\t\t\t\t\t\tm[0] += d;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tm[0] *= v;\n\t\t\t\t\t\tfor (size_t i = 0; i < n; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst auto d = dists[i] - m[0];\n\t\t\t\t\t\t\tm[1] += d * d;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tm[1] = sqrt(m[1] * v);\n\t\t\t\t\t\tfor (size_t i = 0; i < n; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst auto d = dists[i] - m[0];\n\t\t\t\t\t\t\tm[2] += d * d * d;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tm[2] = cbrt(m[2] * v);\n\t\t\t\t\t}\n\t\t\t\t\telse if (n == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tm[0] = 0.5 *     (dists[0] + dists[1]);\n\t\t\t\t\t\tm[1] = 0.5 * fabs(dists[0] - dists[1]);\n\t\t\t\t\t}\n\t\t\t\t\telse if (n == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tm[0] = dists[0];\n\t\t\t\t\t}\n\t\t\t\t\tfor (const auto e : m)\n\t\t\t\t\t{\n\t\t\t\t\t\tq[qo++] = e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(qo == qn.back());\n\n\t\t\t// Compute USR and USRCAT scores.\n\t\t\tcout << local_time() << \"Calculating \" << num_ligands << \" \" << usr_names[usr0] << \" scores\" << endl;\n\t\t\tscores.assign(scores.size(), numeric_limits<double>::max());\n\t\t\tiota(scase.begin(), scase.end(), 0);\n\t\t\tcnt.init(num_chunks);\n\t\t\tfor (size_t l = 0; l < num_chunks; ++l)\n\t\t\t{\n\t\t\t\tio.post([&,l]()\n\t\t\t\t{\n\t\t\t\t\t// Loop over molecules of the current chunk.\n\t\t\t\t\tconst auto chunk_beg = chunk_size * l;\n\t\t\t\t\tconst auto chunk_end = min(chunk_beg + chunk_size, num_ligands);\n\t\t\t\t\tfor (size_t k = chunk_beg; k < chunk_end; ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Loop over conformers of the current molecule and calculate their primary score.\n\t\t\t\t\t\tauto& scorek = scores[k];\n\t\t\t\t\t\tsize_t j = k ? mconfss[k - 1] : 0;\n\t\t\t\t\t\tfor (const auto mconfs = mconfss[k]; j < mconfs; ++j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst auto& d = features[j];\n\t\t\t\t\t\t\tdouble s = 0;\n\t\t\t\t\t\t\tfor (size_t i = 0; i < qnu0; ++i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ts += abs(q[i] - d[i]);\n\t\t\t\t\t\t\t\tif (s >= scorek) break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (s < scorek)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tscorek = s;\n\t\t\t\t\t\t\t\tcnfids[k] = j;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Sort the scores of molecules of the current chunk.\n\t\t\t\t\tsort(scase.begin() + chunk_beg, scase.begin() + chunk_end, compare);\n\n\t\t\t\t\t// Copy the indexes of top hits of the current chunk to a global vector for final sorting.\n\t\t\t\t\tcopy_n(scase.begin() + chunk_beg, min(num_hits, chunk_end - chunk_beg), zcase.begin() + num_hits * l);\n\n\t\t\t\t\tcnt.increment();\n\t\t\t\t});\n\t\t\t}\n\t\t\tcnt.wait();\n\n\t\t\t// Sort the top hits from chunks.\n\t\t\tcout << local_time() << \"Sorting \" << zcase.size() << \" hits by \" << usr_names[usr0] << \" score\" << endl;\n\t\t\tsort(zcase.begin(), zcase.end(), compare);\n\n\t\t\t// Create output directory and write output files.\n\t\t\tcout << local_time() << \"Writing output files\" << endl;\n\t\t\tSDWriter hits_sdf((output_dir / \"hits.sdf\").string());\n\t\t\tboost::filesystem::ofstream hits_csv(output_dir / \"hits.csv\");\n\t\t\thits_csv.setf(ios::fixed, ios::floatfield);\n\t\t\thits_csv << \"ZINC ID,USR score,USRCAT score,2D Tanimoto score,Molecular weight (g/mol),Partition coefficient xlogP,Apolar desolvation (kcal/mol),Polar desolvation (kcal/mol),Hydrogen bond donors,Hydrogen bond acceptors,Polar surface area tPSA (\u00c5^2),Net charge,Rotatable bonds,SMILES,Vendors and annotations\\n\";\n\t\t\tfor (size_t l = 0; l < num_hits; ++l)\n\t\t\t{\n\t\t\t\t// Obtain indexes to the hit molecule and the hit conformer.\n\t\t\t\tconst auto k = zcase[l];\n\t\t\t\tconst auto j = cnfids[k];\n\n\t\t\t\t// Read SDF content of the hit conformer.\n\t\t\t\tconst auto lig = ligands[j];\n\n\t\t\t\t// Construct a RDKit ROMol object.\n\t\t\t\tistringstream iss(lig);\n\t\t\t\tSDMolSupplier sup(&iss, false, true, false, true);\n\t\t\t\tassert(sup.length() == 1);\n\t\t\t\tassert(sup.atEnd());\n\t\t\t\tconst unique_ptr<ROMol> hit_ptr(sup.next());\n\t\t\t\tauto& hitMol = *hit_ptr;\n\n\t\t\t\t// Calculate Morgan fingerprint.\n\t\t\t\tconst unique_ptr<SparseIntVect<uint32_t>> hitFp(getFingerprint(hitMol, 2));\n\n\t\t\t\t// Calculate Tanimoto similarity.\n\t\t\t\tconst auto ts = TanimotoSimilarity(*qryFp, *hitFp);\n\n\t\t\t\t// Find heavy atoms.\n\t\t\t\tvector<vector<pair<int, int>>> matchVect;\n\t\t\t\tSubstructMatch(hitMol, *SubsetMols[0], matchVect);\n\t\t\t\tconst auto num_matches = matchVect.size();\n\t\t\t\tassert(num_matches == hitMol.getNumHeavyAtoms());\n\t\t\t\tvector<int> hitHeavyAtoms(num_matches);\n\t\t\t\tfor (size_t i = 0; i < num_matches; ++i)\n\t\t\t\t{\n\t\t\t\t\thitHeavyAtoms[i] = matchVect[i].front().second;\n\t\t\t\t\tassert(hitHeavyAtoms[i] == i); // hitHeavyAtoms can be constructed using iota(hitHeavyAtoms.begin(), hitHeavyAtoms.end(), 0); because for RDKit-generated SDF molecules, heavy atom are always the first few atoms.\n\t\t\t\t}\n\n\t\t\t\t// Calculate the four reference points.\n\t\t\t\tconst auto hitRefPoints = calcRefPoints(hitMol, hitHeavyAtoms);\n\t\t\t\tconst Point3DConstPtrVect hitRefPointv\n\t\t\t\t{{\n\t\t\t\t\t&hitRefPoints[0],\n\t\t\t\t\t&hitRefPoints[1],\n\t\t\t\t\t&hitRefPoints[2],\n\t\t\t\t\t&hitRefPoints[3],\n\t\t\t\t}};\n\n\t\t\t\t// Calculate a 3D transform from the four reference points of the hit conformer to those of the query molecule.\n\t\t\t\tTransform3D trans;\n\t\t\t\tAlignPoints(qryRefPointv, hitRefPointv, trans);\n\n\t\t\t\t// Apply the 3D transform to all atoms of the hit conformer.\n\t\t\t\tauto& hitCnf = hitMol.getConformer();\n\t\t\t\ttransformConformer(hitCnf, trans);\n\n\t\t\t\t// Write the aligned hit conformer.\n\t\t\t\thits_sdf.write(hitMol);\n\n\t\t\t\t// Calculate the secondary score of the saved conformer, which has the best primary score.\n\t\t\t\tconst auto& d = features[j];\n\t\t\t\tdouble s = 0;\n\t\t\t\tfor (size_t i = 0; i < qnu1; ++i)\n\t\t\t\t{\n\t\t\t\t\ts += abs(q[i] - d[i]);\n\t\t\t\t}\n\n\t\t\t\tconst auto u0score = 1 / (1 + scores[k] * qv[usr0]); // Primary score of the current molecule.\n\t\t\t\tconst auto u1score = 1 / (1 + s         * qv[usr1]); // Secondary score of the current molecule.\n\t\t\t\tconst auto zincid = zincids[k].substr(0, 8); // Take another substr() to get rid of the trailing newline.\n\t\t\t\tconst auto zfp = zfproperties[k];\n\t\t\t\tconst auto zip = ziproperties[k];\n\t\t\t\tconst auto smiles = smileses[k];    // A newline is already included in smileses[k].\n\t\t\t\tconst auto supplier = suppliers[k]; // A newline is already included in suppliers[k].\n\t\t\t\thits_csv\n\t\t\t\t\t<< zincid\n\t\t\t\t\t<< setprecision(8)\n\t\t\t\t\t<< ',' << (usr1 ? u0score : u1score)\n\t\t\t\t\t<< ',' << (usr1 ? u1score : u0score)\n\t\t\t\t\t<< ',' << ts\n\t\t\t\t\t<< setprecision(3)\n\t\t\t\t\t<< ',' << zfp[0]\n\t\t\t\t\t<< ',' << zfp[1]\n\t\t\t\t\t<< ',' << zfp[2]\n\t\t\t\t\t<< ',' << zfp[3]\n\t\t\t\t\t<< ',' << zip[0]\n\t\t\t\t\t<< ',' << zip[1]\n\t\t\t\t\t<< ',' << zip[2]\n\t\t\t\t\t<< ',' << zip[3]\n\t\t\t\t\t<< ',' << zip[4]\n\t\t\t\t\t<< ',' << smiles.substr(0, smiles.length() - 1)     // Get rid of the trailing newline.\n\t\t\t\t\t<< ',' << supplier.substr(0, supplier.length() - 1) // Get rid of the trailing newline.\n\t\t\t\t\t<< '\\n'\n\t\t\t\t;\n\t\t\t}\n\t\t}\n\n\t\t// Update job status.\n\t\tcout << local_time() << \"Setting completed time\" << endl;\n\t\tconst auto completed = milliseconds_since_epoch();\n\t\tconn.update(collection, BSON(\"_id\" << _id), BSON(\"$set\" << BSON(\"completed\" << completed << \"nqueries\" << num_queries)));\n\n\t\t// Calculate runtime in seconds and screening speed in million conformers per second.\n\t\tconst auto runtime = (completed - started) * 0.001;\n\t\tconst auto speed = num_conformers * 0.000001 * num_queries / runtime;\n\t\tcout\n\t\t\t<< local_time() << \"Completed \" << num_queries << \" \" << (num_queries == 1 ? \"query\" : \"queries\") << \" in \" << setprecision(3) << runtime << \" seconds\" << endl\n\t\t\t<< local_time() << \"Screening speed was \" << setprecision(0) << speed << \" M conformers per second\" << endl\n\t\t;\n\t}\n}\n", "meta": {"hexsha": "895ca02a720a2bd9a0e64bda4fb712671e818444", "size": 22342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "HongjianLi/usr", "max_stars_repo_head_hexsha": "41a9aff6cd38123bfe327476ecfe63be6e7991b5", "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/main.cpp", "max_issues_repo_name": "HongjianLi/usr", "max_issues_repo_head_hexsha": "41a9aff6cd38123bfe327476ecfe63be6e7991b5", "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": "HongjianLi/usr", "max_forks_repo_head_hexsha": "41a9aff6cd38123bfe327476ecfe63be6e7991b5", "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.0579268293, "max_line_length": 313, "alphanum_fraction": 0.6449735923, "num_tokens": 6578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.16971140707512353}}
{"text": "/*\n * $Revision: 615 $ $Date: 2011-06-22 12:02:16 -0700 (Wed, 22 Jun 2011) $\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 \"UniverseRenderer.h\"\n#include \"RenderContext.h\"\n#include \"Observer.h\"\n#include \"Geometry.h\"\n#include \"Debug.h\"\n#include \"BoundingSphere.h\"\n#include \"PlanarProjection.h\"\n#include \"Visualizer.h\"\n#include \"PlanetaryRings.h\"\n#include \"OGLHeaders.h\"\n#include \"Framebuffer.h\"\n#include \"CubeMapFramebuffer.h\"\n#include \"TextureFont.h\"\n#include \"GlareOverlay.h\"\n#include \"glhelp/GLFramebuffer.h\"\n#include \"Units.h\"\n#include \"internal/EclipseShadowVolumeSet.h\"\n#include <Eigen/Geometry>\n#include <algorithm>\n\nusing namespace vesta;\nusing namespace Eigen;\nusing namespace std;\n\n\n// Renderer debug settings\n#define DEBUG_SHADOW_MAP      0\n#define DEBUG_OMNI_SHADOW_MAP 0\n#define DEBUG_DEPTH_SPANS     0\n\nconst float UniverseRenderer::MinimumNearDistance = 0.00001f;  // 1 centimeter\nconst float UniverseRenderer::MaximumFarDistance = 1.0e12; // one trillion km (~6700 AU)\n\nstatic const float MinimumNearPlaneDistance = 0.00001f;  // 1 centimeter\nstatic const float MaximumFarPlaneDistance = 1.0e12; // one trillion km (~6700 AU)\nstatic const float MinimumNearFarRatio = 0.001f;\nstatic const float PreferredNearFarRatio = 0.002f;\n\n// Solar radius is used to set the size of the default light source\nstatic const double SolarRadius = 6.96e5;\n\n// Camera rotations used for drawing to the faces of a cube map\nstatic const Quaterniond Z180 = Quaterniond(AngleAxisd(toRadians(180.0), Vector3d::UnitZ()));\nstatic const Quaterniond CubeFaceCameraRotations[6] =\n{\n    Quaterniond(AngleAxisd(toRadians(-90.0), Vector3d::UnitY())) * Z180,\n    Quaterniond(AngleAxisd(toRadians( 90.0), Vector3d::UnitY())) * Z180,\n    Quaterniond(AngleAxisd(toRadians( 90.0), Vector3d::UnitX())) * Z180,\n    Quaterniond(AngleAxisd(toRadians(-90.0), Vector3d::UnitX())) * Z180,\n    Quaterniond(AngleAxisd(toRadians(  0.0), Vector3d::UnitY())) * Z180,\n    Quaterniond(AngleAxisd(toRadians(180.0), Vector3d::UnitY())) * Z180,\n};\n\n\n/** Construct a new UniverseRenderer. The renderer may not be used for drawing\n  * until its initializeGraphics method has been called. Initialization is not\n  * performed in the constructor: a UniverseRenderer can be created at any time,\n  * but the graphics state can only be initialized once an OpenGL context is\n  * available.\n  */\nUniverseRenderer::UniverseRenderer() :\n    m_renderContext(NULL),\n    m_universe(NULL),\n    m_currentTime(0.0),\n    m_shadowsEnabled(false),\n    m_eclipseShadowsEnabled(false),\n    m_visualizersEnabled(true),\n    m_skyLayersEnabled(true),\n    m_defaultSunEnabled(true),\n    m_renderViewport(1, 1),\n    m_viewIndependentInitializationRequired(true),\n    m_lastProjection(PlanarProjection::Perspective, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 10.0f)\n{\n    m_sun = new LightSource();\n    m_sun->setLightType(LightSource::Sun);\n    m_eclipseShadows = new EclipseShadowVolumeSet();\n}\n\n\nUniverseRenderer::~UniverseRenderer()\n{\n    delete m_renderContext;\n}\n\n\n/** Return true if shadows are supported for this renderer. In order to support shadows,\n *  the OpenGL implementation must support both shaders and framebuffer objects.\n */\nbool\nUniverseRenderer::shadowsSupported() const\n{\n    return Framebuffer::supported() && m_renderContext && m_renderContext->shaderCapability() != RenderContext::FixedFunction;\n}\n\n\n/** Return true if omnidirectinoal shadows are supported for this renderer. In order to\n *  support shadows the OpenGL implementation must support shaders, framebuffer objects,\n *  cube maps, and floating point textures.\n */\nbool\nUniverseRenderer::omniShadowsSupported() const\n{\n    return shadowsSupported() && GLEW_ARB_texture_cube_map == GL_TRUE && GLEW_ARB_texture_rg;\n}\n\n\n/** Enable or disable the drawing of shadows. Note that eclipse shadows\n  * cast by planets and moons are enabled separately.\n  */\nvoid\nUniverseRenderer::setShadowsEnabled(bool enable)\n{\n    if (!m_shadowMaps[0].isNull() && m_shadowMaps[0]->isValid())\n    {\n        m_shadowsEnabled = enable;\n    }\n}\n\n\n/** Enable or disable the drawing of eclipse shadows. Any object with an\n  * ellipsoidal geometry is treated specially with regard to shadow. Ellipsoidal\n  * objects will only cast shadows when the eclipse shadows flag is enabled.\n  */\nvoid\nUniverseRenderer::setEclipseShadowsEnabled(bool enable)\n{\n    m_eclipseShadowsEnabled = enable;\n}\n\n\n/** Enable or disable the drawing of visualizers.\n  */\nvoid\nUniverseRenderer::setVisualizersEnabled(bool enable)\n{\n    m_visualizersEnabled = enable;\n}\n\n\n/** Enable or disable the drawing of sky layers. Layers may\n  * also be shown or hidden individually by calling setVisibility()\n  * on the layer. In order for a layer to be drawn, sky layers\n  * must be enabled in the renderer and the visibility of the\n  * layer must be set to true.\n  */\nvoid\nUniverseRenderer::setSkyLayersEnabled(bool enable)\n{\n    m_skyLayersEnabled = enable;\n}\n\n\n/** Set whether the default sun light source should be enabled. This\n  * is enabled when the UniverseRenderer is created and should be disabled\n  * by applications that want more control over lighting. The default\n  * sun light source is located at the origin.\n  */\nvoid\nUniverseRenderer::setDefaultSunEnabled(bool enable)\n{\n    m_defaultSunEnabled = enable;\n}\n\n\n/** Initialize all graphics resources. This method must only be called once OpenGL has\n  * been initialized and a GL context has been set. The renderer cannot be used for\n  * drawing until initializeGraphics is called successfully.\n  *\n  * \\return true if the graphics system was successfully initialized, false otherwise\n  */\nbool\nUniverseRenderer::initializeGraphics()\n{\n    if (m_renderContext)\n    {\n        // The renderer has already been successfully initialized.\n        return true;\n    }\n\n    m_renderContext = RenderContext::Create();\n    if (m_renderContext)\n    {\n        // If there's a default font set, we need to tell the render\n        // context about it.\n        if (m_defaultFont.isValid())\n        {\n            m_renderContext->setDefaultFont(m_defaultFont.ptr());\n            m_defaultFont = NULL;\n        }\n        else\n        {\n            m_renderContext->setDefaultFont(TextureFont::GetDefaultFont());\n        }\n    }\n\n    return m_renderContext != NULL;\n}\n\n\n/** Initialize shadows for this renderer.\n  *\n  * @param shadowMapSize dimension of the square shadow map. A higher value will produce\n  * better shadows but consume more memory. A smaller map may be allocated if the requested\n  * size is larger than the maximum texture size supported by hardware\n  *\n  * @param shadowMapCount number of shadow maps to allocate. The number of shadows cast on\n  *                       any one body is limited by this value.\n  *\n  * \\return true if the shadow map resources were successfully created\n  */\nbool\nUniverseRenderer::initializeShadowMaps(unsigned int shadowMapSize, unsigned int shadowMapCount)\n{\n    if (!m_renderContext)\n    {\n        VESTA_WARNING(\"UniverseRenderer::initializeShadowMaps() called before initializeGraphics()\");\n        return false;\n    }\n\n    if (!shadowsSupported())\n    {\n        VESTA_LOG(\"Shadows not supported by graphic hardware and/or drivers.\");\n        return false;\n    }\n\n    if (shadowMapCount > MaxShadowMaps)\n    {\n        VESTA_LOG(\"Too many shadow maps requested. Using limit of %d\", MaxShadowMaps);\n        shadowMapCount = MaxShadowMaps;\n    }\n\n    // Constrain the shadow map size to the maximum size permitted by the hardware\n    GLint maxTexSize = 0;\n    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTexSize);\n    shadowMapSize = min((unsigned int) maxTexSize, shadowMapSize);\n\n    m_shadowsEnabled = false;\n    m_shadowMaps.clear();\n\n    for (unsigned int i = 0; i < shadowMapCount; ++i)\n    {\n        counted_ptr<Framebuffer> shadowMap(Framebuffer::CreateDepthOnlyFramebuffer(shadowMapSize, shadowMapSize));\n        if (shadowMap.isNull())\n        {\n            VESTA_LOG(\"Failed to create shadow buffer %d. Shadows not enabled.\", i);\n            m_shadowMaps.clear();\n            return false;\n        }\n        m_shadowMaps.push_back(shadowMap);\n    }\n\n    VESTA_LOG(\"Created %d %dx%d shadow buffer(s) for UniverseRenderer.\", shadowMapCount, shadowMapSize, shadowMapSize);\n\n    return true;\n}\n\n\n/** Initialize omnidirectional shadow map resources for this renderer.\n  *\n  * \\param shadowMapSize dimension of the shadow map. A higher value will produce\n  * better shadows but consume more memory. A smaller map may be allocated if the requested\n  * size is larger than the maximum texture size supported by hardware\n  *\n  * \\param shadowMapCount number of shadow maps to allocate. The number of shadows cast on\n  *                       any one body is limited by this value.\n  *\n  * \\return true if the shadow map resources were successfully created\n  */\nbool\nUniverseRenderer::initializeOmniShadowMaps(unsigned int shadowMapSize, unsigned int shadowMapCount)\n{\n    if (!m_renderContext)\n    {\n        VESTA_WARNING(\"UniverseRenderer::initializeOmniShadowMaps() called before initializeGraphics()\");\n        return false;\n    }\n\n    if (!omniShadowsSupported())\n    {\n        VESTA_LOG(\"Omnidirectional shadows not supported by graphic hardware and/or drivers.\");\n        return false;\n    }\n\n    if (shadowMapCount > MaxOmniShadowMaps)\n    {\n        VESTA_LOG(\"Too many shadow maps requested. Using limit of %d\", MaxShadowMaps);\n        shadowMapCount = MaxShadowMaps;\n    }\n\n    // Constrain the shadow map size to the maximum size permitted by the hardware\n    GLint maxTexSize = 0;\n    glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, &maxTexSize);\n    shadowMapSize = min((unsigned int) maxTexSize, shadowMapSize);\n\n    m_omniShadowMaps.clear();\n\n    // Omnidirectional shadows are implemented as cube maps with the camera to fragment distance\n    // stored in the red channel. We require 32-bit floating point precision for storing distances.\n    for (unsigned int i = 0; i < shadowMapCount; ++i)\n    {\n        counted_ptr<CubeMapFramebuffer> shadowMap(CubeMapFramebuffer::CreateCubicReflectionMap(shadowMapSize, TextureMap::R32F));\n        if (shadowMap.isNull())\n        {\n            VESTA_LOG(\"Failed to create omni shadow buffer %d. Omni shadows not enabled.\", i);\n            m_omniShadowMaps.clear();\n            return false;\n        }\n\n        m_omniShadowMaps.push_back(shadowMap);\n    }\n\n    VESTA_LOG(\"Created %d %dx%d cube map shadow buffer(s) for UniverseRenderer.\", shadowMapCount, shadowMapSize, shadowMapSize);\n\n    return true;\n}\n\n\n/** Set up the renderer to draw one or more views at the specified time.\n  * The renderer can perform optimizations that improve performance when\n  * multiple views are rendered within the same view set. These optimizations\n  * assume that no changes are made to objects in the universe in between\n  * beginViewSet / endViewSet. If objects are being changed between calls\n  * to renderView(), the calls should appear in different view sets.\n  *\n  * \\param universe the universe to be rendered\n  * \\param tsec simulation time in seconds since J2000 TDB\n  *\n  * \\return a status code indicating whether the view set was\n  *         set up successfully. If there were no problems, this\n  *         method returns RendererOk. Otherwise, the beginViewSet()\n  *         will return:\n  *         \\list\n  *         \\li RendererUninitialized - if called before initializeGraphics()\n  *         \\li RendererBadParameter - if universe is null\n  *         \\li RendererViewSetAlreadyStarted - if called after a previous\n  *             beginViewSet() call but before endViewSet()\n  */\nUniverseRenderer::RenderStatus\nUniverseRenderer::beginViewSet(const Universe* universe, double tsec)\n{\n    if (!m_renderContext)\n    {\n        return RendererUninitialized;\n    }\n\n    if (universe == NULL)\n    {\n        return RendererBadParameter;\n    }\n\n    if (m_universe)\n    {\n        return RenderViewSetAlreadyStarted;\n    }\n\n    m_universe = universe;\n    m_currentTime = tsec;\n\n    // TODO: maintain a bounding sphere hierarchy in order to avoid having to do a linear\n    // traversal of all objects.\n\n    // Build the light source list\n    m_lightSources.clear();\n\n    // Add a light source for the Sun\n    // TODO: Consider whether it might be good to *not* set this automatically\n    if (m_defaultSunEnabled)\n    {\n        LightSourceItem sunItem;\n        sunItem.lightSource = m_sun.ptr();\n        sunItem.position = Vector3d::Zero();\n        sunItem.radius = SolarRadius;\n        m_lightSources.push_back(sunItem);\n    }\n\n    const vector<Entity*>& entities = m_universe->entities();\n    for (vector<Entity*>::const_iterator iter = entities.begin(); iter != entities.end(); ++iter)\n    {\n        const Entity* entity = *iter;\n        const LightSource* light = entity->lightSource();\n\n        if (light && entity->isVisible(m_currentTime))\n        {\n            Vector3d position = entity->position(m_currentTime);\n\n            LightSourceItem lsi;\n            lsi.lightSource = light;\n            lsi.position = position;\n            lsi.radius = entity->geometry() ? entity->geometry()->boundingSphereRadius() : 0.0;\n            m_lightSources.push_back(lsi);\n        }\n    }\n\n    m_eclipseShadows->clear();\n\n    // Set a flag indicating that we haven't rendered any views in this set yet\n    m_viewIndependentInitializationRequired = true;\n\n    return RenderOk;\n}\n\n\n/** Finish the current view set.\n  *\n  * \\return the render status, which will be RenderNoViewSet if endViewSet() is\n  *         called before beginViewSet(). Otherwise, endViewSet() returns RenderOk.\n  */\nUniverseRenderer::RenderStatus\nUniverseRenderer::endViewSet()\n{\n    if (!m_universe)\n    {\n        return RenderNoViewSet;\n    }\n\n    m_universe = NULL;\n\n    return RenderOk;\n}\n\n\nstatic bool\nvisibleItemPredicate(const vesta::UniverseRenderer::VisibleItem& item0,\n                     const vesta::UniverseRenderer::VisibleItem& item1)\n{\n    return item0.farDistance < item1.farDistance;\n}\n\n\n#if DEBUG_SHADOW_MAP\n// Debugging code for shadows\nstatic void\nshowShadowMap(Framebuffer* shadowMap,\n              float quadSize,\n              float viewportWidth, float viewportHeight)\n{\n    if (shadowMap->isValid())\n    {\n        glMatrixMode(GL_PROJECTION);\n        glLoadIdentity();\n        gluOrtho2D(0, viewportWidth, 0, viewportHeight);\n        glMatrixMode(GL_MODELVIEW);\n        glLoadIdentity();\n        glDisable(GL_LIGHTING);\n        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);\n        glDisable(GL_DEPTH_TEST);\n\n        glEnable(GL_TEXTURE_2D);\n        glBindTexture(GL_TEXTURE_2D, shadowMap->depthTexHandle());\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);\n\n        glBegin(GL_QUADS);\n        glTexCoord2f(0.0f, 0.0f);\n        glVertex2f(0.0f, 0.0f);\n        glTexCoord2f(1.0f, 0.0f);\n        glVertex2f(quadSize, 0.0f);\n        glTexCoord2f(1.0f, 1.0f);\n        glVertex2f(quadSize, quadSize);\n        glTexCoord2f(0.0f, 1.0f);\n        glVertex2f(0.0f, quadSize);\n        glEnd();\n\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);\n    }\n}\n#endif // DEBUG_SHADOW_MAP\n\n\n#if DEBUG_OMNI_SHADOW_MAP\n// Debugging code for omnidirectional shadows\nstatic void\nshowOmniShadowMap(CubeMapFramebuffer* shadowMap,\n                  float quadSize,\n                  float viewportWidth, float viewportHeight)\n{\n    if (shadowMap->colorTexture())\n    {\n        glMatrixMode(GL_PROJECTION);\n        glLoadIdentity();\n        gluOrtho2D(0, viewportWidth, 0, viewportHeight);\n        glMatrixMode(GL_MODELVIEW);\n        glLoadIdentity();\n        glDisable(GL_LIGHTING);\n        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);\n        glDisable(GL_DEPTH_TEST);\n\n        glEnable(GL_TEXTURE_CUBE_MAP);\n        glBindTexture(GL_TEXTURE_CUBE_MAP, shadowMap->colorTexture()->id());\n\n        float halfAngle = toRadians(60.0f);\n        glBegin(GL_QUADS);\n        glTexCoord3f(cos(-halfAngle), sin(-halfAngle), -1.0f);\n        glVertex2f(0.0f, 0.0f);\n        glTexCoord3f(cos(halfAngle), sin(-halfAngle), 1.0f);\n        glVertex2f(quadSize, 0.0f);\n        glTexCoord3f(cos(halfAngle), sin(halfAngle), 1.0f);\n        glVertex2f(quadSize, quadSize);\n        glTexCoord3f(cos(-halfAngle), sin(halfAngle), -1.0f);\n        glVertex2f(0.0f, quadSize);\n        glEnd();\n\n        glBindTexture(GL_TEXTURE_CUBE_MAP, 0);\n        glDisable(GL_TEXTURE_CUBE_MAP);\n    }\n}\n#endif // DEBUG_OMNI_SHADOW_MAP\n\n\nstatic bool skyLayerOrderPredicate(const SkyLayer* layer0, const SkyLayer* layer1)\n{\n    return layer0->drawOrder() < layer1->drawOrder();\n}\n\n\n/** Render visible bodies in the universe using the specified camera position,\n  * orientation, and projection.\n  *\n  * @param lighting information about lights and shadows that could affect objects in view\n  * @param cameraPosition the camera position\n  * @param cameraOrientation the camera orientation\n  * @param projection the camera projection\n  * @param viewport rectangular region of the rendering surface to draw into\n  * @param renderSurface target framebuffer; the default value of NULL means that the default back buffer will be used.\n  */\nUniverseRenderer::RenderStatus\nUniverseRenderer::renderView(const LightingEnvironment* lighting,\n                             const Vector3d& cameraPosition,\n                             const Quaterniond& cameraOrientation,\n                             const PlanarProjection& projection,\n                             const Viewport& viewport,\n                             Framebuffer* renderSurface)\n{\n    if (!m_universe)\n    {\n        return RenderNoViewSet;\n    }\n\n    // Last used projection is required for glare rendering\n    m_lastProjection = projection;\n\n    // Save the viewport and render surface so that they can be reset after\n    // shadow and reflection rendering.\n    m_renderSurface = renderSurface;\n    m_renderViewport = viewport;\n\n    // Save the current color mask\n    GLboolean mask[4];\n    glGetBooleanv(GL_COLOR_WRITEMASK, mask);\n    for (unsigned int i = 0; i < 4; ++i)\n    {\n        m_renderColorMask[i] = mask[i] == GL_TRUE;\n    }\n\n    glViewport(viewport.x(), viewport.y(), viewport.width(), viewport.height());\n\n    Matrix3f toCameraSpace = cameraOrientation.conjugate().cast<float>().toRotationMatrix();\n    float aspectRatio = viewport.aspectRatio();\n    float fieldOfView = projection.fovY();\n\n    // Reverse the vertex winding order if we have a left-handed projection matrix\n    // (because all geometry assumes a right-handed projection.)\n    if (projection.chirality() == PlanarProjection::LeftHanded)\n    {\n        glFrontFace(GL_CW);\n    }\n\n    glShadeModel(GL_SMOOTH);\n    glEnable(GL_CULL_FACE);\n\n    m_renderContext->setCameraOrientation(cameraOrientation.cast<float>());\n    m_renderContext->setPixelSize((float) (2 * tan(fieldOfView / 2.0) / viewport.height()));\n    m_renderContext->setViewportSize(viewport.width(), viewport.height());\n\n    m_renderContext->pushModelView();\n    m_renderContext->rotateModelView(cameraOrientation.conjugate().cast<float>());\n\n    // Draw sky layers grids\n    glDepthMask(GL_FALSE);\n    glDisable(GL_DEPTH_TEST);\n    glDisable(GL_TEXTURE_2D);\n\n    m_renderContext->setProjection(projection.slice(0.1f, 1.0f));\n\n    if (m_skyLayersEnabled)\n    {\n        vector<SkyLayer*> visibleLayers;\n        const Universe::SkyLayerTable* skyLayers = m_universe->layers();\n        for (Universe::SkyLayerTable::const_iterator iter = skyLayers->begin(); iter != skyLayers->end(); ++iter)\n        {\n            SkyLayer* layer = iter->second.ptr();\n            if (layer && layer->isVisible())\n            {\n                visibleLayers.push_back(layer);\n            }\n\n            sort(visibleLayers.begin(), visibleLayers.end(), skyLayerOrderPredicate);\n        }\n\n        for (vector<SkyLayer*>::const_iterator iter = visibleLayers.begin(); iter != visibleLayers.end(); ++iter)\n        {\n            glDisable(GL_LIGHTING);\n            (*iter)->render(*m_renderContext);\n        }\n    }\n\n    glEnable(GL_DEPTH_TEST);\n    glDepthMask(GL_TRUE);\n\n    // Fixed function state setup\n    glEnable(GL_NORMALIZE);\n    glEnable(GL_LIGHTING);\n\n    m_renderContext->setActiveLightCount(1);\n    m_renderContext->setAmbientLight(m_ambientLight);\n\n    m_viewFrustum = projection.frustum();\n\n    // This adjustment factor will ensure that the view frustum near plane\n    // doesn't intersect the geometry of a body.\n    float nearPlaneFovAdjustment = (float) (cos(fieldOfView / 2.0) / sqrt(1.0 + aspectRatio * aspectRatio));\n\n    const vector<Entity*>& entities = m_universe->entities();\n\n    m_visibleItems.clear();\n    m_splittableItems.clear();\n\n    m_lighting = lighting;\n\n    buildVisibleLightSourceList(cameraPosition);\n\n    // Simply scan through all entities in the universe.\n    // TODO: For better performance with many entities, we could maintain a\n    // bounding sphere hierarchy.\n    for (vector<Entity*>::const_iterator iter = entities.begin(); iter != entities.end(); ++iter)\n    {\n        const Entity* entity = *iter;\n\n        if (entity->isVisible(m_currentTime))\n        {\n            Vector3d position = entity->position(m_currentTime);\n\n            // Calculate the difference at double precision, then convert to single\n            // precision for the rest of the work.\n            Vector3d cameraRelativePosition = (position - cameraPosition);\n\n            // Cull objects based on size. If an object is less than one pixel in size,\n            // we don't draw its geometry. Visualizers have sizes that may be unrelated\n            // to the size of the object, so we don't cull them.\n            // TODO: Add a method to the visualizer class that specifies whether the size\n            // culling test (i.e. if the visualizer geometry has a fixed size on screen--such\n            // as a label--then it shouldn't be culled.)\n            bool sizeCull = false;\n            if (entity->geometry())\n            {\n                float projectedSize = (entity->geometry()->boundingSphereRadius() / float(cameraRelativePosition.norm())) / m_renderContext->pixelSize();\n                sizeCull = projectedSize < 0.5f;\n            }\n            else\n            {\n                // Objects without geometry are always culled.\n                sizeCull = true;\n            }\n\n            // We need the camera space position of the object in order to depth\n            // sort the objects.\n            Vector3f cameraSpacePosition = toCameraSpace * cameraRelativePosition.cast<float>();\n\n            if (!sizeCull)\n            {\n                addVisibleItem(entity, entity->geometry(),\n                               position, cameraRelativePosition, cameraSpacePosition,\n                               entity->orientation(m_currentTime).cast<float>(),\n                               nearPlaneFovAdjustment);\n            }\n\n            // Add an eclipse shadow volume for this body if it is ellipsoidal. We only\n            // need to do this for the first view in the set; subsequent views can reuse\n            // the shadow volume set because shadow volumes are not view dependent.\n            if (m_eclipseShadowsEnabled &&\n                m_viewIndependentInitializationRequired &&\n                entity->geometry() &&\n                entity->geometry()->isEllipsoidal() &&\n                entity->geometry()->isShadowCaster() &&\n                !entity->lightSource())\n            {\n                // Add the shadow volume (except when no sun light source is defined.)\n                if (!m_lightSources.empty() && m_lightSources.front().lightSource->lightType() == LightSource::Sun)\n                {\n                    m_eclipseShadows->addShadow(entity,\n                                                position,\n                                                entity->orientation(m_currentTime).cast<float>(),\n                                                m_lightSources.front().position,\n                                                m_lightSources.front().radius);\n                }\n            }\n\n            if (entity->hasVisualizers() && m_visualizersEnabled)\n            {\n                for (Entity::VisualizerTable::const_iterator iter = entity->visualizers()->begin();\n                     iter != entity->visualizers()->end(); ++iter)\n                {\n                    const Visualizer* visualizer = iter->second.ptr();\n                    if (visualizer->isVisible())\n                    {\n                        Vector3d adjustedPosition = cameraRelativePosition;\n                        Vector3f adjustedCameraSpacePosition = cameraSpacePosition;\n\n                        if (visualizer->depthAdjustment() == Visualizer::AdjustToFront)\n                        {\n                            // Adjust the position of the visualizer so that it is drawn in\n                            // front of the object to which it is attached.\n                            if (entity->geometry())\n                            {\n                                float z = -cameraSpacePosition.z() - entity->geometry()->boundingSphereRadius();\n                                float f = z / -cameraSpacePosition.z();\n                                adjustedPosition *= f;\n                                adjustedCameraSpacePosition *= f;\n                            }\n                        }\n\n                        addVisibleItem(entity, visualizer->geometry(),\n                                       position, adjustedPosition, adjustedCameraSpacePosition,\n                                       visualizer->orientation(entity, m_currentTime).cast<float>(),\n                                       nearPlaneFovAdjustment);\n                    }\n                }\n            }\n        }\n    }\n\n    // Depth sort all visible items\n    sort(m_visibleItems.begin(), m_visibleItems.end(), visibleItemPredicate);\n    sort(m_splittableItems.begin(), m_splittableItems.end(), visibleItemPredicate);\n\n    splitDepthBuffer();\n    coalesceDepthBuffer();\n\n    // Expand the non-empty depth buffer spans slightly so that small geometry\n    // (such as labels, which have very small extent in z) doesn't get clipped\n    // when positioned at the back of a span. The symptom of this problem is\n    // flickering geometry.\n    for (unsigned int i = 0; i < m_mergedDepthBufferSpans.size(); ++i)\n    {\n        if (m_mergedDepthBufferSpans[i].itemCount > 0)\n        {\n            if (i == 0)\n            {\n                // This is the farthest span\n                m_mergedDepthBufferSpans[i].farDistance *= 1.01f;\n            }\n            else if (m_mergedDepthBufferSpans[i - 1].itemCount == 0)\n            {\n                // TODO: Possibly expand this span into an adjacent empty span\n            }\n        }\n    }\n\n\n    // If there is splittable geometry, we need to add extra depth spans\n    // at the front and back, otherwise it may be clipped.\n    if (!m_splittableItems.empty())\n    {\n        // Use a different near/far ratio for these extra spans\n        const float MaxFarNearRatio = 10000.0f;\n\n        float furthestDistance = min(m_splittableItems.front().farDistance, projection.farDistance());\n\n        // Handle the case when the only visible geometry is splittable. This can happen\n        // in solar system views where just the planet orbits are visible. The only thing\n        // that we need to do is add the furthest span.\n        if (m_depthBufferSpans.empty())\n        {\n            DepthBufferSpan back;\n            back.backItemIndex = 0;\n            back.itemCount = 0;\n            back.farDistance = projection.farDistance();\n            back.nearDistance = max(projection.nearDistance(), back.farDistance / MaxFarNearRatio);\n            m_mergedDepthBufferSpans.push_back(back);\n        }\n        else if (furthestDistance > m_mergedDepthBufferSpans.front().farDistance)\n        {\n            DepthBufferSpan back;\n            back.backItemIndex = 0;\n            back.itemCount = 0;\n            back.farDistance = furthestDistance;\n            back.nearDistance = m_mergedDepthBufferSpans.front().farDistance;\n            m_mergedDepthBufferSpans.insert(m_mergedDepthBufferSpans.begin(), back);\n        }\n\n        while (m_mergedDepthBufferSpans.back().nearDistance > projection.nearDistance())\n        {\n            // Some potentially confusing naming here: spans are stored in\n            // reverse order, so that the foreground span is actually the\n            // *last* one in the list.\n            DepthBufferSpan front;\n            front.backItemIndex = 0;\n            front.itemCount = 0;\n            front.farDistance = m_mergedDepthBufferSpans.back().nearDistance;\n            front.nearDistance = std::max(projection.nearDistance(), front.farDistance / MaxFarNearRatio);\n            m_mergedDepthBufferSpans.push_back(front);\n        }\n\n        DepthBufferSpan back;\n        back.backItemIndex = 0;\n        back.itemCount = 0;\n        back.nearDistance = m_mergedDepthBufferSpans.front().farDistance;\n        back.farDistance = back.nearDistance * MaxFarNearRatio;\n        m_mergedDepthBufferSpans.insert(m_mergedDepthBufferSpans.begin(), back);\n    }\n\n#if DEBUG_DEPTH_SPANS\n    // cerr << \"split: \" << m_depthBufferSpans.size() << \", merged: \" << m_mergedDepthBufferSpans.size() << endl;\n    cerr << \"spans: \";\n    for (unsigned int i = 0; i < m_depthBufferSpans.size(); ++i)\n    {\n        cerr << \"( \" << m_depthBufferSpans[i].nearDistance << \", \" << m_depthBufferSpans[i].farDistance << \" ) \";\n    }\n    cerr << endl;\n\n    cerr << \"merged: \";\n    for (unsigned int i = 0; i < m_mergedDepthBufferSpans.size(); ++i)\n    {\n        cerr << \"( \" << m_mergedDepthBufferSpans[i].nearDistance << \", \" << m_mergedDepthBufferSpans[i].farDistance << \" ) \";\n    }\n    cerr << endl;\n#endif // DEBUG_DEPTH_SPANS\n\n    if (m_eclipseShadowsEnabled)\n    {\n        m_eclipseShadows->frustumCull(projection.frustum());\n    }\n\n    // Draw depth buffer spans from back to front\n    unsigned int spanIndex = m_mergedDepthBufferSpans.size() - 1;\n    float spanRange = 1.0f;\n    if (!m_mergedDepthBufferSpans.empty())\n    {\n        spanRange /= (float) m_mergedDepthBufferSpans.size();\n    }\n\n    for (vector<DepthBufferSpan>::const_iterator iter = m_mergedDepthBufferSpans.begin();\n         iter != m_mergedDepthBufferSpans.end(); ++iter, --spanIndex)\n    {\n        setDepthRange(spanIndex * spanRange, (spanIndex + 1) * spanRange);\n        renderDepthBufferSpan(*iter, projection);\n    }\n\n    m_renderContext->popModelView();\n    m_renderContext->unbindShader();\n\n    // Reset the front face\n    glFrontFace(GL_CCW);\n\n    setDepthRange(0.0f, 1.0f);\n\n#if DEBUG_SHADOW_MAP\n    if (m_shadowsEnabled && m_shadowMap.isValid())\n    {\n        showShadowMap(m_shadowMap.ptr(), 320.0f, viewport.width(), viewport.height());\n    }\n#endif\n\n#if DEBUG_OMNI_SHADOW_MAP\n    if (m_shadowsEnabled && m_omniShadowMaps[0].isValid())\n    {\n        showOmniShadowMap(m_omniShadowMaps[0].ptr(), 320.0f, viewport.width(), viewport.height());\n    }\n#endif\n\n    // Don't hold on to the lighting environment pointer\n    m_lighting = NULL;\n\n    m_viewIndependentInitializationRequired = false;\n\n    return RenderOk;\n}\n\n\n/** Render visible bodies in the universe from the point of view of the\n  * specified observer.\n  *\n  * @param information about lights and shadows that could affect objects in view\n  * @param observer the observer.\n  * @param fieldOfView the horizontal field of view in radians\n  * @param viewport rectangular region of the rendering surface to draw into\n  * @param renderSurface target framebuffer; the default value of NULL means that the default back buffer will be used.\n  */\nUniverseRenderer::RenderStatus\nUniverseRenderer::renderView(const LightingEnvironment* lighting,\n                             const Observer* observer,\n                             double fieldOfView,\n                             const Viewport& viewport,\n                             Framebuffer* renderSurface)\n{\n    return renderView(lighting,\n                      observer->absolutePosition(m_currentTime),\n                      observer->absoluteOrientation(m_currentTime),\n                      PlanarProjection::CreatePerspective(fieldOfView, viewport.aspectRatio(), MinimumNearPlaneDistance, MaximumFarPlaneDistance),\n                      viewport,\n                      renderSurface);\n}\n\n\n/** Render visible bodies in the universe from the point of view of the\n  * specified observer. This method is just a shortcut for the renderView\n  * method that accepts a render surface and viewport parameter.\n  *\n  * @param observer the observer.\n  * @param fieldOfView the horizontal field of view in radians\n  * @param viewportWidth the width of the viewport in pixels\n  * @param viewportHeight the height of the viewport in pixels\n  */\nUniverseRenderer::RenderStatus\nUniverseRenderer::renderView(const Observer* observer,\n                             double fieldOfView,\n                             int viewportWidth,\n                             int viewportHeight)\n{\n    return renderView(NULL, observer, fieldOfView, Viewport(viewportWidth, viewportHeight), NULL);\n}\n\n\n/** Draw glare for light sources that are directly visible to the camera. This method\n  * should be called immediately after a call to renderView(). A typical calling sequence\n  * is the following:\n  *\n  * \\code\n  * renderer->renderView();\n  * glareOverlay->adjustBrightness();\n  * renderer->renderLightGlare(glareOverlay);\n  * \\endcode\n  *\n  * A separate GlareOverlay instance should be created for each camera used.\n  * \\see createGlareOverlay\n  */\nUniverseRenderer::RenderStatus\nUniverseRenderer::renderLightGlare(GlareOverlay* glareOverlay)\n{\n    if (!m_universe)\n    {\n        return RenderNoViewSet;\n    }\n\n    if (!glareOverlay)\n    {\n        // Nothing to do\n        return RenderOk;\n    }\n\n    float spanRange = 1.0f;\n    if (!m_mergedDepthBufferSpans.empty())\n    {\n        spanRange /= (float) m_mergedDepthBufferSpans.size();\n    }\n\n    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);\n    glDepthMask(GL_FALSE);\n\n    // Track light sources\n    for (unsigned int i = 0; i < m_visibleLightSources.size(); ++i)\n    {\n        VisibleLightSourceItem& light = m_visibleLightSources[i];\n        if (light.lightSource->lightType() == LightSource::Sun)\n        {\n            // The glare occlusion test geometry drawn so that it appears just in front\n            // of the light source geometry.\n            Vector3f direction = light.cameraSpacePosition.normalized();\n            Vector3f glarePosition = light.cameraSpacePosition + (direction * light.radius / direction.z());\n\n            unsigned int spanIndex = m_mergedDepthBufferSpans.size() - 1;\n            for (vector<DepthBufferSpan>::const_iterator iter = m_mergedDepthBufferSpans.begin();\n                 iter != m_mergedDepthBufferSpans.end(); ++iter, --spanIndex)\n            {\n                if (-glarePosition.z() <= iter->farDistance && -glarePosition.z() >= iter->nearDistance)\n                {\n                    setDepthRange(spanIndex * spanRange, (spanIndex + 1) * spanRange);\n                    m_renderContext->setProjection(m_lastProjection.slice(iter->nearDistance, iter->farDistance));\n                    glareOverlay->trackGlare(*m_renderContext, light.lightSource, glarePosition, light.radius);\n                }\n            }\n        }\n    }\n\n    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);\n    glDepthMask(GL_FALSE);\n\n    glDepthRange(0.0f, 1.0f);\n\n    // Render glare geometry\n    for (unsigned int i = 0; i < m_visibleLightSources.size(); ++i)\n    {\n        VisibleLightSourceItem& light = m_visibleLightSources[i];\n        if (light.lightSource->lightType() == LightSource::Sun)\n        {\n            // The glare sprite is drawn\n            Vector3f direction = light.cameraSpacePosition.normalized();\n            Vector3f glarePosition = light.cameraSpacePosition + (direction * light.radius / direction.z());\n            glareOverlay->renderGlare(*m_renderContext, light.lightSource, glarePosition, light.radius);\n        }\n    }\n\n\n    return RenderOk;\n}\n\n\n// Predicate used for sorting light sources in the following priority:\n//   1. Sun light sources (only one supported now)\n//   2. Point lights with shadows\n//   3. Point lights without shadows\n//\n// Sun light sources will always cast shadows.\nstatic bool lightCastsShadowsPredicate(const UniverseRenderer::VisibleLightSourceItem& light0,\n                                       const UniverseRenderer::VisibleLightSourceItem& light1)\n{\n    int priority0 = 0;\n    int priority1 = 0;\n\n    if (light0.lightSource->lightType() == LightSource::Sun)\n    {\n        priority0 = 2;\n    }\n    else\n    {\n        priority0 = light0.lightSource->isShadowCaster() ? 1 : 0;\n    }\n\n    if (light1.lightSource->lightType() == LightSource::Sun)\n    {\n        priority1 = 2;\n    }\n    else\n    {\n        priority1 = light1.lightSource->isShadowCaster() ? 1 : 0;\n    }\n\n    return priority0 > priority1;\n}\n\n\n// Private method to create the visible light source list from the main light\n// source list. Only light sources which interact with objects in the view\n// frustum will appear in the visible light list.\nvoid\nUniverseRenderer::buildVisibleLightSourceList(const Vector3d& cameraPosition)\n{\n    Matrix3f toCameraSpace = m_renderContext->cameraOrientation().conjugate().toRotationMatrix();\n\n    // Create the list of visible light sources. We filter the list of all light sources\n    // and only keep the ones that interact with objects in the view frustum.\n    m_visibleLightSources.clear();\n    for (vector<LightSourceItem>::const_iterator iter = m_lightSources.begin(); iter != m_lightSources.end(); ++iter)\n    {\n        const LightSourceItem& lsi = *iter;\n        Vector3d cameraRelativePosition = lsi.position - cameraPosition;\n        Vector3f cameraSpacePosition = toCameraSpace * cameraRelativePosition.cast<float>();\n\n        bool cull = false;\n        if (lsi.lightSource->lightType() != LightSource::Sun)\n        {\n            float projectedSize = (lsi.lightSource->range() / float(cameraRelativePosition.norm())) / m_renderContext->pixelSize();\n            if (projectedSize < 1.0f)\n            {\n                // Light might be in the view frustum, but it affects a region that occupies less than\n                // a pixel on screen.\n                cull = true;\n            }\n            else\n            {\n                // Check whether the light lies outside the view frustum. We can disregard it if it does.\n                if (!m_viewFrustum.intersects(BoundingSphere<float>(cameraSpacePosition, lsi.lightSource->range())))\n                {\n                    cull = true;\n                }\n            }\n        }\n        else\n        {\n            // Handle the Sun specially--it is never culled.\n        }\n\n        if (!cull)\n        {\n            VisibleLightSourceItem visibleLight;\n            visibleLight.lightSource = lsi.lightSource;\n            visibleLight.position = lsi.position;\n            visibleLight.cameraRelativePosition = cameraRelativePosition;\n            visibleLight.cameraSpacePosition = cameraSpacePosition;\n            visibleLight.radius = float(lsi.radius);\n            m_visibleLightSources.push_back(visibleLight);\n        }\n    }\n\n    // Sort the light sources so that the shadow casters appear first in the visible\n    // light sources list.\n    sort(m_visibleLightSources.begin(), m_visibleLightSources.end(), lightCastsShadowsPredicate);\n}\n\n\nvoid\nUniverseRenderer::setDepthRange(float front, float back)\n{\n    m_depthRangeFront = front;\n    m_depthRangeBack = back;\n    glDepthRange(front, back);\n}\n\n\nvoid\nUniverseRenderer::addVisibleItem(const Entity* entity,\n                                 const Geometry* geometry,\n                                 const Vector3d& position,\n                                 const Vector3d& cameraRelativePosition,\n                                 const Vector3f& cameraSpacePosition,\n                                 const Quaternionf& orientation,\n                                 float nearAdjust)\n{\n    // Compute the signed distance from the camera plane to the most\n    // distant part of the entity. A distance < 0 indicates that the\n    // entity lies completely behind the camera.\n    float boundingRadius = geometry->boundingSphereRadius();\n    float farDistance = -cameraSpacePosition.z() + boundingRadius;\n\n    // Calculate a near distance that's as far from the camera as possible.\n    float nearDistance = geometry->nearPlaneDistance(orientation.conjugate() * -cameraRelativePosition.cast<float>());\n\n    // Generally, the near distance for an individual object will never be less\n    // than MinimumNearFarRatio times the bounding diameter. Exceptions are things\n    // like trajectories, which should never be clipped by the near plane. This\n    // is handled by marking trajectories as splittable, so that they will be\n    // drawn into multiple depth buffer spans when necessary.\n    switch (geometry->clippingPolicy())\n    {\n    case Geometry::PreserveDepthPrecision:\n        nearDistance = std::max(nearDistance, boundingRadius * MinimumNearFarRatio * 2.0f);\n        break;\n\n    case Geometry::PreventClipping:\n    case Geometry::SplitToPreventClipping:\n        nearDistance = std::max(nearDistance, MinimumNearPlaneDistance);\n        break;\n    }\n\n    // ...but make sure that the near plane of the view frustum doesn't\n    // intersect the object's geometry. Note that if nearDistance is greater\n    // farDistance, it means that the object lies outside the view frustum.\n    nearDistance *= nearAdjust;\n\n    bool intersectsFrustum = m_viewFrustum.intersects(BoundingSphere<float>(cameraSpacePosition, boundingRadius));\n\n    // Objects that lie outside the frustum and don't cast shadows don't contribute to the\n    // final scene. They'll be culled eventually, but we can take of them early here. However,\n    // enabling this test causes problems right now with disappearing visualizers when ordinary\n    // objects are in view.\n    /*\n    if (!intersectsFrustum && !geometry->isShadowCaster())\n    {\n        return;\n    }\n    */\n\n    // Add entities in front of the camera to the list of visible items\n    if (farDistance > 0 && nearDistance < farDistance)\n    {\n        VisibleItem visibleItem;\n        visibleItem.entity = entity;\n        visibleItem.geometry = geometry;\n        visibleItem.position = position;\n        visibleItem.cameraRelativePosition = cameraRelativePosition;\n        visibleItem.orientation = orientation;\n        visibleItem.boundingRadius = boundingRadius;\n        visibleItem.nearDistance = nearDistance;\n        visibleItem.farDistance = farDistance;\n        visibleItem.outsideFrustum = !intersectsFrustum;\n\n        if (geometry->clippingPolicy() == Geometry::SplitToPreventClipping)\n        {\n            m_splittableItems.push_back(visibleItem);\n        }\n        else\n        {\n            m_visibleItems.push_back(visibleItem);\n        }\n    }\n}\n\n\n/** Render six views into the faces of a cube map from the specified position. The views are pointed\n  * along the universal coordinate system axes, though this can be modified by passing something\n  * other than identity for the rotation.\n  *\n  * Reflection maps are expected to be in world coordinates. If the cube map is intended to be used\n  * for reflections, the rotation should be identity (the default value)\n  *\n  * In order to avoid obvious visual problems with reflection maps, they should only contain geometry that\n  * is 'distant', i.e. at a much farther away than the size of the reflecting geometry. The nearDistance\n  * can be set to a value greater than the minimum in order to automatically cull nearby objects.\n  *\n  * \\param lighting the lighting environment for rendering\n  * \\param position position of the camera\n  * \\param cubeMap the target cube map framebuffer to draw into\n  * \\param nearDistance distance to the near clipping plane (defaults to MinimumNearDistance)\n  * \\param farDistance distance to the far clipping plane (defaults to MaximumFarDistance)\n  * \\param rotation optional rotation (defaults to identity)\n  */\nUniverseRenderer::RenderStatus\nUniverseRenderer::renderCubeMap(const LightingEnvironment* lighting,\n                                const Vector3d& position,\n                                CubeMapFramebuffer* cubeMap,\n                                double nearDistance,\n                                double farDistance,\n                                const Quaterniond& rotation)\n{\n    Viewport viewport(cubeMap->size(), cubeMap->size());\n    PlanarProjection cubeFaceProjection = PlanarProjection::CreatePerspectiveLH(float(toRadians(90.0)),\n                                                                                1.0f,\n                                                                                nearDistance, farDistance);\n\n    for (int face = 0; face < 6; ++face)\n    {\n        Framebuffer* fb = cubeMap->face(CubeMapFramebuffer::Face(face));\n        if (fb)\n        {\n            fb->bind();\n            glDepthMask(GL_TRUE);\n            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n            RenderStatus status = renderView(lighting, position, rotation * CubeFaceCameraRotations[face], cubeFaceProjection, viewport, fb);\n            if (status != RenderOk)\n            {\n                Framebuffer::unbind();\n                return status;\n            }\n        }\n    }\n\n    Framebuffer::unbind();\n\n    return RenderOk;\n}\n\n\n/** Render six views into the faces of a shadow cube map.\n  */\nUniverseRenderer::RenderStatus\nUniverseRenderer::renderShadowCubeMap(const LightingEnvironment* lighting, const Vector3d& position, CubeMapFramebuffer* cubeMap)\n{\n    RenderStatus status = RenderOk;\n\n    Viewport viewport(cubeMap->size(), cubeMap->size());\n    PlanarProjection cubeFaceProjection = PlanarProjection::CreatePerspectiveLH(float(toRadians(90.0)),\n                                                                                1.0f,\n                                                                                MinimumNearPlaneDistance, MaximumFarPlaneDistance);\n\n    m_renderContext->setRendererOutput(RenderContext::CameraDistance);\n\n    for (int face = 0; face < 6; ++face)\n    {\n        Framebuffer* fb = cubeMap->face(CubeMapFramebuffer::Face(face));\n        if (fb)\n        {\n            fb->bind();\n            glDepthMask(GL_TRUE);\n            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n            status = renderView(lighting, position, CubeFaceCameraRotations[face], cubeFaceProjection, viewport, fb);\n            if (status != RenderOk)\n            {\n                break;\n            }\n        }\n    }\n\n    Framebuffer::unbind();\n    m_renderContext->setRendererOutput(RenderContext::FragmentColor);\n\n    return status;\n}\n\n\n// Split the depth buffer up into one or more spans.\nvoid\nUniverseRenderer::splitDepthBuffer()\n{\n    m_depthBufferSpans.clear();\n\n    // Iterate over the visible items from back to front\n    for (int i = (int) m_visibleItems.size() - 1; i >= 0; --i)\n    {\n        const VisibleItem& item = m_visibleItems[i];\n\n        float nearDistance = item.nearDistance;\n        if (m_depthBufferSpans.empty())\n        {\n            DepthBufferSpan span;\n            span.backItemIndex = (unsigned int) i;\n            span.itemCount = 1;\n            span.farDistance = item.farDistance;\n            span.nearDistance = nearDistance;\n\n            m_depthBufferSpans.push_back(span);\n        }\n        else\n        {\n            DepthBufferSpan& span = m_depthBufferSpans.back();\n            bool isDisjoint = item.farDistance < span.nearDistance;\n\n            if (isDisjoint)\n            {\n                // Item doesn't overlap the current depth buffer span. Create two\n                // new spans: one containing item, and one for the empty range in\n                // between the new span and the current span.\n                DepthBufferSpan emptySpan;\n                emptySpan.farDistance = span.nearDistance;\n                emptySpan.nearDistance = item.farDistance;\n                emptySpan.itemCount = 0;\n                emptySpan.backItemIndex = (unsigned int) i;\n\n                // Start a new span\n                DepthBufferSpan newSpan;\n                newSpan.farDistance = item.farDistance;\n                newSpan.nearDistance = nearDistance;\n                newSpan.backItemIndex = (unsigned int) i;\n                newSpan.itemCount = 1;\n\n                m_depthBufferSpans.push_back(emptySpan);\n                m_depthBufferSpans.push_back(newSpan);\n            }\n            else\n            {\n                span.itemCount++;\n                if (nearDistance < span.nearDistance)\n                {\n                    span.nearDistance = nearDistance;\n                }\n            }\n        }\n    }\n}\n\n\n// Coalesce adjacent depth buffer spans that are of approximately\n// the same size. This will prevent over-partitioning of the the\n// depth buffer while still preserving a maximum far/near ratio.\nvoid\nUniverseRenderer::coalesceDepthBuffer()\n{\n    m_mergedDepthBufferSpans.clear();\n\n    unsigned int i = 0;\n    while (i < m_depthBufferSpans.size())\n    {\n        float farDistance = m_depthBufferSpans[i].farDistance;\n        unsigned int itemCount = m_depthBufferSpans[i].itemCount;\n\n        // Coalesce all spans into a single span that's as large as possible\n        // without near/far being less than the preferred near-far ratio. This\n        // will reduce the number of depth buffer spans without sacrificing\n        // depth buffer precision.\n        unsigned int j = i;\n        while (j < m_depthBufferSpans.size() - 1)\n        {\n            if (m_depthBufferSpans[j + 1].nearDistance / farDistance < PreferredNearFarRatio)\n            {\n                break;\n            }\n\n            itemCount += m_depthBufferSpans[j + 1].itemCount;\n            ++j;\n        }\n\n        DepthBufferSpan span;\n        span.farDistance = farDistance;\n        span.nearDistance = m_depthBufferSpans[j].nearDistance;\n        span.backItemIndex = m_depthBufferSpans[i].backItemIndex;\n        span.itemCount = itemCount;\n\n        m_mergedDepthBufferSpans.push_back(span);\n\n        i = j + 1;\n    }\n}\n\n\nstatic void\nbeginShadowRendering()\n{\n    // Use depth-only rendering for shadows\n    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);\n    glDepthMask(GL_TRUE);\n    glEnable(GL_DEPTH_TEST);\n\n    // Reduce 'shadow acne' by rendering the backfaces. This doesn't\n    // eliminate the artifacts, but moves them to the unilluminated\n    // side of the object, where they're less visible.\n    glCullFace(GL_FRONT);\n}\n\n\nstatic void\nbeginCubicShadowRendering()\n{\n    // Render only the red channel\n    glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);\n    glDepthMask(GL_TRUE);\n    glEnable(GL_DEPTH_TEST);\n\n    // Reduce 'shadow acne' by rendering the backfaces. This doesn't\n    // eliminate the artifacts, but moves them to the unilluminated\n    // side of the object, where they're less visible.\n    glCullFace(GL_FRONT);\n}\n\n\n// Restore GL state after shadow rendering. Shadow rendering\n// affects the render target, color mask, and culling state.\nvoid\nfinishShadowRendering(Framebuffer* renderSurface, bool colorMask[])\n{\n    if (renderSurface)\n    {\n        renderSurface->bind();\n    }\n    else\n    {\n        Framebuffer::unbind();\n    }\n\n    glColorMask(colorMask[0] ? GL_TRUE : GL_FALSE,\n                colorMask[1] ? GL_TRUE : GL_FALSE,\n                colorMask[2] ? GL_TRUE : GL_FALSE,\n                colorMask[3] ? GL_TRUE : GL_FALSE);\n\n    glCullFace(GL_BACK);\n}\n\n\n\n// Render all of the items in a depth buffer span\nvoid UniverseRenderer::renderDepthBufferSpan(const DepthBufferSpan& span, const PlanarProjection& projection)\n{\n    if (span.itemCount == 0 && m_splittableItems.empty())\n    {\n        return;\n    }\n\n    // Enforce the minimum near plane distance\n    float nearDistance = std::max(projection.nearDistance(), span.nearDistance);\n    float farDistance = std::min(projection.farDistance(), span.farDistance);\n    if (farDistance <= nearDistance)\n    {\n        // Entire span lies in front of or behind the view frustum, so skip it\n        return;\n    }\n\n    bool shadowsOn = false;\n    unsigned int omniShadowCount = 0;\n    if (m_shadowsEnabled && !m_visibleLightSources.empty())\n    {\n        // Render shadows from the Sun (currently always the first light source)\n        if (m_visibleLightSources[0].lightSource->lightType() == LightSource::Sun)\n        {\n            shadowsOn = renderDepthBufferSpanShadows(0, span, m_visibleLightSources[0].cameraRelativePosition);\n        }\n\n        // See if there are additional light sources casting shadows.\n        for (unsigned int i = 0; i < m_visibleLightSources.size() && omniShadowCount < m_omniShadowMaps.size(); ++i)\n        {\n            if (m_visibleLightSources[i].lightSource->lightType() == LightSource::PointLight &&\n                m_visibleLightSources[i].lightSource->isShadowCaster())\n            {\n                renderDepthBufferSpanOmniShadows(omniShadowCount,\n                                                 span,\n                                                 m_visibleLightSources[i].lightSource,\n                                                 m_visibleLightSources[i].cameraRelativePosition);\n                ++omniShadowCount;\n            }\n        }\n    }\n\n    // Adjust the far distance slightly to prevent small objects at the back of the view\n    // from being clipped due to roundoff errors. The adjustment factor must be larger than\n    // one ulp of a 32-bit float, but as small as possible to reduce rendering artifacts\n    // caused by frusta that overlap in depth.\n    float safeFarDistance = farDistance * (1.0f + 1.0e-6f);\n\n    m_renderContext->setProjection(projection.slice(nearDistance, safeFarDistance));\n    Frustum viewFrustum = m_renderContext->frustum();\n\n    // Rendering of some translucent objects is order dependent. We can eliminate the\n    // worst artifacts by drawing opaque items first and translucent items second.\n    for (int pass = 0; pass < 2; ++pass)\n    {\n        m_renderContext->setPass(pass == 0 ? RenderContext::OpaquePass : RenderContext::TranslucentPass);\n\n        // Draw all items in the span\n        for (unsigned int i = 0; i < span.itemCount; i++)\n        {\n            const VisibleItem& item = m_visibleItems[span.backItemIndex - i];\n\n            if (pass == 0 || !item.geometry->isOpaque())\n            {\n                if (shadowsOn && item.geometry->isShadowReceiver())\n                {\n                    m_renderContext->setShadowMapCount(1);\n                }\n                else\n                {\n                    m_renderContext->setShadowMapCount(0);\n                }\n\n                if (item.geometry->isShadowReceiver())\n                {\n                    m_renderContext->setOmniShadowMapCount(omniShadowCount);\n                }\n                else\n                {\n                    m_renderContext->setOmniShadowMapCount(0);\n                }\n\n                m_renderContext->setEclipseShadowCount(0);\n                m_renderContext->setRingShadowCount(0);\n\n                if (m_lighting && !m_lighting->reflectionRegions().empty())\n                {\n                    m_renderContext->setEnvironmentMap(m_lighting->reflectionRegions().front().cubeMap);\n                }\n                else\n                {\n                    m_renderContext->setEnvironmentMap(NULL);\n                }\n                drawItem(item);\n            }\n        }\n\n        // Disable all shadows\n        m_renderContext->setShadowMapCount(0);\n        m_renderContext->setOmniShadowMapCount(0);\n\n        // Draw all splittable items that fall at least partly within this span.\n        for (unsigned int i = 0; i < m_splittableItems.size(); ++i)\n        {\n            const VisibleItem& item = m_splittableItems[m_splittableItems.size() - i - 1];\n\n            if (item.nearDistance < span.farDistance && item.farDistance > span.nearDistance)\n            {\n                if (pass == 0 || !item.geometry->isOpaque())\n                {\n                    drawItem(item);\n                }\n            }\n        }\n    }\n}\n\n\n// Render all shadow casters in a depth buffer span into the shadow map. Return true if\n// any shadows were actually drawn.\n//\n// Parameters:\n//   span - the depth buffer span for which to draw shadows\n//   lightPosition - the position of the light source relative to the camera\nbool\nUniverseRenderer::renderDepthBufferSpanShadows(unsigned int shadowIndex,\n                                               const DepthBufferSpan& span,\n                                               const Vector3d& lightPosition)\n{\n    if (!m_shadowsEnabled)\n    {\n        return false;\n    }\n\n    assert(shadowIndex < m_shadowMaps.size());\n\n    // Check for shadow support\n    if (!Framebuffer::supported() ||\n        m_shadowMaps[shadowIndex].isNull() ||\n        !m_shadowMaps[shadowIndex]->isValid())\n    {\n        return false;\n    }\n\n    BoundingSphere<float> shadowReceiverBounds;\n    bool shadowCastersPresent = false;\n\n    // Find the minimum radius bounding sphere that contains all of the\n    // shadow receivers in this span. Also, determine whether there are\n    // any shadow casters in the span.\n    for (unsigned int i = 0; i < span.itemCount; ++i)\n    {\n        const VisibleItem& item = m_visibleItems[span.backItemIndex - i];\n        const Geometry* geometry = item.geometry;\n\n        if (geometry->isShadowReceiver())\n        {\n            shadowReceiverBounds.merge(BoundingSphere<float>(item.cameraRelativePosition.cast<float>(), item.boundingRadius));\n        }\n\n        if (geometry->isShadowCaster() && !geometry->isEllipsoidal())\n        {\n            shadowCastersPresent = true;\n        }\n    }\n\n    // Don't draw shadows if there are no receivers or no casters\n    if (!shadowCastersPresent || shadowReceiverBounds.isEmpty())\n    {\n        return false;\n    }\n\n    glDepthRange(0.0f, 1.0f);\n    beginShadowRendering();\n\n    Vector3f shadowGroupCenter = shadowReceiverBounds.center();\n    float shadowGroupBoundingRadius = shadowReceiverBounds.radius();\n\n    // Compute the light direction. Here it assumed that all objects in the shadow group\n    // are far enough from the light source that the rays are nearly parallel and the\n    // light source direction is effectively constant.\n    Vector3f lightDirection = (lightPosition + shadowGroupCenter.cast<double>()).cast<float>().normalized();\n\n    // Compute the shadow transform, which will convert coordinates from \"shadow group space\" to\n    // shadow space. Shadow group space has axes aligned with world space but has an origin located\n    // at the center of the collection of mutually shadowing objects.\n    Matrix4f invCameraTransform = m_renderContext->modelview().matrix().transpose();\n    Matrix4f shadowTransform = setupShadowRendering(m_shadowMaps[shadowIndex].ptr(), lightDirection, shadowGroupBoundingRadius);\n    shadowTransform = shadowTransform * Transform3f(Translation3f(-shadowGroupCenter)).matrix() * invCameraTransform;\n\n    // Render shadows for all casters\n    for (unsigned int i = 0; i < span.itemCount; ++i)\n    {\n        const VisibleItem& item = m_visibleItems[span.backItemIndex - i];\n        const Geometry* geometry = item.geometry;\n\n        // Note that shadows of ellipsoidal bodies are handled specially by the eclipse shadow code\n        if (geometry->isShadowCaster() && !geometry->isEllipsoidal())\n        {\n            Vector3f itemPosition = item.cameraRelativePosition.cast<float>();\n            m_renderContext->pushModelView();\n            m_renderContext->translateModelView(itemPosition - shadowGroupCenter);\n            m_renderContext->rotateModelView(item.orientation);\n            item.geometry->renderShadow(*m_renderContext, m_currentTime);\n            m_renderContext->popModelView();\n        }\n    }\n\n    // Pop the matrices pushed in setupShadowRendering()\n    m_renderContext->popProjection();\n    m_renderContext->popModelView();\n\n    finishShadowRendering(m_renderSurface.ptr(), m_renderColorMask);\n\n    // Reset the viewport\n    glDepthRange(m_depthRangeFront, m_depthRangeBack);\n    glViewport(m_renderViewport.x(), m_renderViewport.y(), m_renderViewport.width(), m_renderViewport.height());\n\n    // Set shadow state in the render context\n    m_renderContext->setShadowMapMatrix(shadowIndex, shadowTransform);\n    m_renderContext->setShadowMap(shadowIndex, m_shadowMaps[shadowIndex]->glFramebuffer());\n\n    return true;\n}\n\n\n// Render all shadow casters in a depth buffer span into the cubic shadow map.\n// Return true if any shadows were actually drawn.\n//\n// Parameters:\n//   span - the depth buffer span for which to draw shadows\n//   lightPosition - the position of the light source relative to the camera\nbool\nUniverseRenderer::renderDepthBufferSpanOmniShadows(unsigned int shadowIndex,\n                                                   const DepthBufferSpan& span,\n                                                   const LightSource* light,\n                                                   const Vector3d& lightPosition)\n{\n    // Check for shadow support\n    if (!Framebuffer::supported() || !m_shadowsEnabled)\n    {\n        return false;\n    }\n\n    assert(shadowIndex < m_omniShadowMaps.size());\n\n    BoundingSphere<float> shadowReceiverBounds;\n    bool shadowCastersPresent = false;\n\n    // Find the minimum radius bounding sphere that contains all of the\n    // shadow receivers in this span. Also, determine whether there are\n    // any shadow casters in the span.\n    for (unsigned int i = 0; i < span.itemCount; ++i)\n    {\n        const VisibleItem& item = m_visibleItems[span.backItemIndex - i];\n        const Geometry* geometry = item.geometry;\n\n        if (geometry->isShadowReceiver())\n        {\n            shadowReceiverBounds.merge(BoundingSphere<float>(item.cameraRelativePosition.cast<float>(), item.boundingRadius));\n        }\n\n        if (geometry->isShadowCaster() && !geometry->isEllipsoidal())\n        {\n            shadowCastersPresent = true;\n        }\n    }\n\n    // Don't draw shadows if there are no receivers or no casters\n    if (!shadowCastersPresent || shadowReceiverBounds.isEmpty())\n    {\n        return false;\n    }\n\n    // Set up the view port (same for all faces)\n    glViewport(0, 0, m_omniShadowMaps[shadowIndex]->size(), m_omniShadowMaps[shadowIndex]->size());\n    glDepthRange(0.0f, 1.0f);\n\n    // Set up cube map shadow rendering\n    // When rendering to cube faces, we use a left-handed projection, so reverse the triangles (GL_CW)\n    // Also, tell the renderer to output camera distance instead of color\n    beginCubicShadowRendering();\n    glFrontFace(GL_CW);\n    m_renderContext->setRendererOutput(RenderContext::CameraDistance);\n\n    // Pixel distance is stored in the red channel; clear it to a very large value\n    glClearColor(1.0e15f, 0.0f, 0.0f, 0.0f);\n\n    m_renderContext->pushProjection();\n\n    // Draw each face of the cube map. Frustum cull objects to avoid unnecessary\n    // redrawing.\n    for (int face = 0; face < 6; ++face)\n    {\n        Framebuffer* fb = m_omniShadowMaps[shadowIndex]->face(CubeMapFramebuffer::Face(face));\n        if (fb)\n        {\n            fb->bind();\n            glDepthMask(GL_TRUE);\n            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n            glDisable(GL_BLEND);\n\n            Quaternionf cameraOrientation = CubeFaceCameraRotations[face].cast<float>();\n            Matrix3f toCameraSpace = cameraOrientation.conjugate().toRotationMatrix();\n\n            // Set the camera transformation\n            m_renderContext->pushModelView();\n            m_renderContext->setModelView(Matrix4f::Identity());\n            m_renderContext->rotateModelView(cameraOrientation.conjugate().cast<float>());\n\n            // The camera orientation is stored separately; save it so that we can restore\n            // it after rendering all faces.\n            Quaternionf savedCamera = m_renderContext->cameraOrientation();\n            m_renderContext->setCameraOrientation(cameraOrientation);\n\n            PlanarProjection faceProjection = PlanarProjection::CreatePerspectiveLH(float(toRadians(90.0)), 1.0f, light->range() * 0.0001f, light->range());\n            Frustum faceFrustum = faceProjection.frustum();\n\n            m_renderContext->setProjection(faceProjection);\n\n            // Render shadows for all casters\n            for (unsigned int i = 0; i < span.itemCount; ++i)\n            {\n                const VisibleItem& item = m_visibleItems[span.backItemIndex - i];\n                const Geometry* geometry = item.geometry;\n\n                // Note that shadows of ellipsoidal bodies are handled specially by the eclipse shadow code\n                if (geometry->isShadowCaster() && !geometry->isEllipsoidal())\n                {\n                    Vector3f itemPosition = (item.cameraRelativePosition - lightPosition).cast<float>();\n                    Vector3f cameraSpacePosition = toCameraSpace * itemPosition;\n\n                    // Test object bounding sphere against cube face frustum\n                    if (faceFrustum.intersects(BoundingSphere<float>(cameraSpacePosition, light->range())))\n                    {\n                        m_renderContext->pushModelView();\n                        m_renderContext->translateModelView(itemPosition);\n                        m_renderContext->rotateModelView(item.orientation);\n                        item.geometry->renderShadow(*m_renderContext, m_currentTime);\n                        m_renderContext->popModelView();\n                    }\n                }\n            }\n\n            m_renderContext->popModelView();\n            m_renderContext->setCameraOrientation(savedCamera);\n        }\n    }\n\n    m_renderContext->popProjection();\n\n    // Restore normal renderer operation\n    m_renderContext->setRendererOutput(RenderContext::FragmentColor);\n    finishShadowRendering(m_renderSurface.ptr(), m_renderColorMask);\n    glFrontFace(GL_CCW);\n\n    // Reset the viewport\n    glDepthRange(m_depthRangeFront, m_depthRangeBack);\n    glViewport(m_renderViewport.x(), m_renderViewport.y(), m_renderViewport.width(), m_renderViewport.height());\n\n    // Set shadow state in the render context\n    m_renderContext->setOmniShadowMap(shadowIndex, m_omniShadowMaps[shadowIndex]->colorTexture());\n\n    // Restore clear color to black\n    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n\n    return true;\n}\n\n\n// Check for any eclipse shadows that affect an item and set the shadow\n// state in the render context appropriately.\nvoid\nUniverseRenderer::setupEclipseShadows(const VisibleItem &item)\n{\n    if (m_eclipseShadows->findIntersectingShadows(item.entity, item.position, item.boundingRadius))\n    {\n        // The object is affected by at least one shadow\n\n        if (m_eclipseShadows->insideUmbra())\n        {\n            // The object is completely shadowed; don't bother with eclipse shadows in the shader,\n            // just turn off the light source.\n            const VisibleLightSourceItem& light = m_visibleLightSources.front();\n            m_renderContext->setLight(0, RenderContext::Light(RenderContext::DirectionalLight,\n                                                              light.cameraRelativePosition.cast<float>(),\n                                                              Spectrum::Black(),\n                                                              1.0));\n        }\n        else\n        {\n            // The object is only partly shadowed. Set up the lighting.\n            const EclipseShadowVolumeSet::EclipseShadowVector& shadows = m_eclipseShadows->intersectingShadows();\n\n            unsigned int shadowCount = min((unsigned int) RenderContext::MaxEclipseShadows, (unsigned int) shadows.size());\n            Matrix4f invCameraTransform = Transform3f(m_renderContext->cameraOrientation()).matrix();\n\n            unsigned int ellipsoidShadowCount = 0;\n            for (unsigned int i = 0; i < shadowCount; ++i)\n            {\n                const EclipseShadowVolumeSet::EclipseShadow& shadow = shadows[i];\n\n                // Get the position of the shadow center relative to the camera\n                Vector3f shadowCenter = (shadow.position - item.position + item.cameraRelativePosition).cast<float>();\n\n                if (shadow.occluder->geometry()->ellipsoid().isDegenerate())\n                {\n                    // This special case for planetary rings is a bit of a hack; the alternative is\n                    // to add more specialized methods to the Geometry base class.\n                    PlanetaryRings* rings = dynamic_cast<PlanetaryRings*>(shadow.occluder->geometry());\n                    if (rings && rings->texture() && rings->texture()->makeResident())\n                    {\n                        const GeneralEllipse& ringEllipse = shadow.projection;\n                        double radius = ringEllipse.v0().norm();\n                        float radius2 = float(radius * radius);\n\n                        Vector3d planeNormal = (ringEllipse.v0() / radius).cross(ringEllipse.v1() / radius);\n                        double cosLightAngle = planeNormal.dot(shadow.direction);\n                        if (cosLightAngle < 0.0)\n                        {\n                            planeNormal = -planeNormal;\n                        }\n                        else\n                        {\n                            cosLightAngle = -cosLightAngle;\n                        }\n\n                        double shear = 0.0;\n                        if (abs(cosLightAngle) < 0.0001)\n                        {\n                            // Prevent division by zero when rings are nearly edge-on to light source\n                            cosLightAngle = ((cosLightAngle < 0) ? -0.0001 : 0.0001);\n                            shear = 1.0 / cosLightAngle;\n                        }\n                        else\n                        {\n                            //double sinLightAngle = sqrt(max(0.0, 1.0 - cosLightAngle * cosLightAngle));\n                            shear = 1.0 / cosLightAngle;\n                        }\n\n                        // Transformation to rotate from world space into ring plane space\n                        Matrix3f shadowRotation;\n                        shadowRotation << ringEllipse.v0().cast<float>() / radius2,\n                                          ringEllipse.v1().cast<float>() / radius2,\n                                          planeNormal.cast<float>() / float(radius);\n\n                        // Get the position of the light vector in ring plane space\n                        Vector3f l = (shadowRotation.transpose() * shadow.direction.cast<float>()).normalized();\n                        Matrix4f shadowShear;\n                        shadowShear << 1.0f, 0.0f, l.x() * float(shear), 0.0f,\n                                       0.0f, 1.0f, l.y() * float(shear), 0.0f,\n                                       0.0f, 0.0f, 1.0f,                 0.0f,\n                                       0.0f, 0.0f, 0.0f,                 1.0f;\n\n                        Matrix4f shadowTransform = Matrix4f::Identity();\n                        shadowTransform.corner<3, 3>(TopLeft) = shadowRotation.transpose();\n                        shadowTransform = shadowShear * shadowTransform * Transform3f(Translation3f(-shadowCenter)).matrix() * invCameraTransform;\n                        m_renderContext->setRingShadowMatrix(0, shadowTransform, rings->innerRadius() / rings->outerRadius());\n                        m_renderContext->setRingShadowTexture(0, rings->texture());\n                        m_renderContext->setRingShadowCount(1);\n\n                        // Force the border color of ring textures to transparent in order to avoid\n                        // mipmapping artifacts.\n                        glBindTexture(GL_TEXTURE_2D, rings->texture()->id());\n                        float transparent[4] = { 0.0f, 0.0f, 0.0f, 0.0f };\n                        glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, transparent);\n                        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER_ARB);\n                        glBindTexture(GL_TEXTURE_2D, 0);\n                    }\n                }\n                else\n                {\n                    // The shadow rotation matrix transforms a point in world space to shadow space. In shadow space,\n                    // the z-axis points away from the light source along the central shadow axis. The x- and y-axes\n                    // are the principal axes of an elliptical slice of the shadow cone. They are always perpendicular\n                    // to each other and the z-axis.\n\n                    // In order to avoid precision problems, we'll scale the z-axis so that its length is closer to\n                    // the range of the x- and y-axis lengths\n                    float zscale = shadow.projection.v0().norm();\n\n                    Matrix3f shadowRotation;\n                    shadowRotation << shadow.projection.v0().cast<float>() / float(shadow.projection.v0().squaredNorm()),\n                                      shadow.projection.v1().cast<float>() / float(shadow.projection.v1().squaredNorm()),\n                                      shadow.direction.cast<float>() / zscale;\n\n                    Matrix4f shadowTransform = Matrix4f::Identity();\n                    shadowTransform.corner<3, 3>(TopLeft) = shadowRotation.transpose();\n                    shadowTransform = shadowTransform * Transform3f(Translation3f(-shadowCenter)).matrix() * invCameraTransform;\n                    zscale = 1.0f;\n                    m_renderContext->setEclipseShadowMatrix(ellipsoidShadowCount, shadowTransform, shadow.umbraSlope / zscale, shadow.penumbraSlope / zscale);\n\n                    ++ellipsoidShadowCount;\n                }\n            }\n            m_renderContext->setEclipseShadowCount(ellipsoidShadowCount);\n        }\n    }\n\n}\n\n\nvoid\nUniverseRenderer::drawItem(const VisibleItem& item)\n{       \n    if (item.outsideFrustum)\n    {\n        return;\n\n    }\n    m_renderContext->setModelTranslation(m_renderContext->modelview().linear().cast<double>() * item.cameraRelativePosition);\n\n    // Set up the light sources\n    unsigned int lightCount = 0;\n    if (!m_lightSources.empty())\n    {\n        for (vector<VisibleLightSourceItem>::const_iterator iter = m_visibleLightSources.begin(); iter != m_visibleLightSources.end(); ++iter)\n        {\n            if (iter->lightSource->lightType() == LightSource::Sun)\n            {\n                m_renderContext->setLight(lightCount, RenderContext::Light(RenderContext::DirectionalLight,\n                                                                           iter->cameraRelativePosition.cast<float>(),\n                                                                           iter->lightSource->spectrum(),\n                                                                           1.0f));\n                ++lightCount;\n            }\n            else\n            {\n                Vector3f lightPosition = (iter->position - item.position).cast<float>();\n                float distanceToLight = lightPosition.norm() - item.boundingRadius;\n                float attenuation = 1.0f / (256.0f * iter->lightSource->range() * iter->lightSource->range());\n                if (distanceToLight < iter->lightSource->range())\n                {\n                    m_renderContext->setLight(lightCount,\n                                              RenderContext::Light(RenderContext::PointLight,\n                                                                   iter->cameraRelativePosition.cast<float>(),\n                                                                   iter->lightSource->spectrum(),\n                                                                   attenuation));\n                    ++lightCount;\n                }\n            }\n        }\n    }\n\n    m_renderContext->setActiveLightCount(lightCount);\n\n    m_renderContext->pushModelView();\n    m_renderContext->translateModelView(item.cameraRelativePosition.cast<float>());\n    m_renderContext->rotateModelView(item.orientation);\n\n    // TODO: Remove special case for ellipsoidal objects; we should just be able to make\n    // WorldGeometry shadow receivers.\n    if (m_eclipseShadowsEnabled && (item.geometry->isShadowReceiver() || item.geometry->isEllipsoidal()))\n    {\n        setupEclipseShadows(item);\n    }\n\n    item.geometry->render(*m_renderContext, m_currentTime);\n\n    m_renderContext->popModelView();\n}\n\n\n/** Set the color of 'fill light' in the scene. Ambient light is\n  * a crude approximation to the light resulting from multiple\n  * reflections off of diffuse surfaces. By default, the ambient\n  * light is set to black. The default is realistic for space scenes, but\n  * some ambient light may be desirable when clarity of the visualization\n  * is more important than realism.\n  */\nvoid\nUniverseRenderer::setAmbientLight(const Spectrum& spectrum)\n{\n    m_ambientLight = spectrum;\n}\n\n\n// Create a view matrix for drawing the scene from the\n// point of view of a light source.\nstatic Matrix4f\nshadowView(const Vector3f& lightDirection)\n{\n    Vector3f u = lightDirection.unitOrthogonal();\n    Vector3f v = u.cross(lightDirection);\n    Matrix4f lightView;\n    lightView << v.transpose(),              0.0,\n                 u.transpose(),              0.0,\n                 lightDirection.transpose(), 0.0,\n                 0.0, 0.0, 0.0,  1.0;\n\n    return lightView;\n}\n\n\n// Shadow bias matrix for mapping to a unit cube with\n// one corner at the origin (since texture coordinates\n// are in [ 0, 1 ] instead of [ -1, 1 ])\nstatic Matrix4f\nshadowBias()\n{\n    Matrix4f bias;\n    bias << 0.5f, 0.0f, 0.0f, 0.5f,\n            0.0f, 0.5f, 0.0f, 0.5f,\n            0.0f, 0.0f, 0.5f, 0.5f,\n            0.0f, 0.0f, 0.0f, 1.0f;\n\n    return bias;\n}\n\n\n// Set up graphics state for rendering shadows. Return the matrix that\n// should be used for drawing geometry with this shadow map.\nMatrix4f\nUniverseRenderer::setupShadowRendering(const Framebuffer* shadowMap,\n                                       const Vector3f& lightDirection,\n                                       float shadowGroupSize)\n{\n    if (!shadowMap->isValid())\n    {\n        return Matrix4f::Identity();\n    }\n\n    shadowMap->bind();\n\n#if DEBUG_SHADOW_MAP\n    GLenum errCode = glGetError();\n    if (errCode != GL_NO_ERROR)\n    {\n        VESTA_LOG(\"glError in shadow setup: %s\", gluErrorString(errCode));\n    }\n#endif\n\n    PlanarProjection shadowProjection = PlanarProjection::CreateOrthographic(-shadowGroupSize, shadowGroupSize,\n                                                                             -shadowGroupSize, shadowGroupSize,\n                                                                             -shadowGroupSize, shadowGroupSize);\n    Matrix4f modelView = shadowView(lightDirection);\n\n    glClear(GL_DEPTH_BUFFER_BIT);\n\n    m_renderContext->pushProjection();\n    m_renderContext->setProjection(shadowProjection);\n    m_renderContext->pushModelView();\n    m_renderContext->setModelView(modelView);\n\n    glViewport(0, 0, shadowMap->width(), shadowMap->height());\n    glDepthRange(0.0f, 1.0f);\n\n    return shadowBias() * shadowProjection.matrix() * modelView;\n}\n\n\n/** Get the default font used for labels.\n  */\nTextureFont*\nUniverseRenderer::defaultFont() const\n{\n    // The default font is actually stored in the render context. However,\n    // it's possible to set the default font before the render context has been\n    // created (via initializeGraphics). In that case, we return the value\n    // of the default font temporarily stored in UniverseRenderer\n    if (m_renderContext)\n    {\n        return m_renderContext->defaultFont();\n    }\n    else\n    {\n        return m_defaultFont.ptr();\n    }\n}\n\n\n/** Set the default font to be used for labels.\n  */\nvoid\nUniverseRenderer::setDefaultFont(TextureFont* font)\n{\n    if (m_renderContext)\n    {\n        // We have an initialized render context, so set the font there\n        m_renderContext->setDefaultFont(font);\n    }\n    else\n    {\n        // The render context hasn't been initialized yet. Keep track of the\n        // font and set it in the render context when it is eventually initialized.\n        m_defaultFont = font;\n    }\n}\n\n\n/** Create a glare overlay. An overlay may only be created after the\n  * renderer has been initialized. This method returns NULL if there was\n  * an error creating the overlay.\n  *\n  * A glare overlay object retains information about light source visibility\n  * between frames. Because of this, a separate overlay should be created\n  * for each camera used. If the same overlay is reused, the light glare will\n  * flicker whenever lights visible to one camera are not visible to the\n  * other camera.\n  */\nGlareOverlay*\nUniverseRenderer::createGlareOverlay()\n{\n    if (!m_renderContext)\n    {\n        VESTA_LOG(\"Cannot create a glare overlay before UniverseRenderer is initialized.\");\n        return NULL;\n    }\n\n    GlareOverlay* overlay = new GlareOverlay();\n    if (!overlay->initialize())\n    {\n        VESTA_LOG(\"Error creating glare overlay.\");\n        delete overlay;\n        return NULL;\n    }\n\n    return overlay;\n}\n", "meta": {"hexsha": "fcf09c03b592d8fc0c0ce01b989883d7013256c2", "size": 81384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/vesta/UniverseRenderer.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/UniverseRenderer.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/UniverseRenderer.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": 37.5734072022, "max_line_length": 158, "alphanum_fraction": 0.627211737, "num_tokens": 17824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16971140567211837}}
{"text": "/*\n Copyright (C) 2020 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 orea/app/xvarunner.hpp\n    \\brief A class to run the xva analysis\n    \\ingroup app\n*/\n#pragma once\n\n#include <orea/aggregation/postprocess.hpp>\n#include <orea/engine/valuationcalculator.hpp>\n#include <orea/scenario/scenariogeneratordata.hpp>\n#include <orea/scenario/scenariosimmarketparameters.hpp>\n#include <ored/configuration/curveconfigurations.hpp>\n#include <ored/model/crossassetmodeldata.hpp>\n#include <orea/engine/valuationengine.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace ore {\nnamespace analytics {\n\nclass XvaRunner {\npublic:\n    virtual ~XvaRunner() {}\n\n    XvaRunner(QuantLib::Date asof, const std::string& baseCurrency,\n              const boost::shared_ptr<ore::data::Portfolio>& portfolio,\n              const boost::shared_ptr<ore::data::NettingSetManager>& netting,\n              const boost::shared_ptr<ore::data::EngineData>& engineData,\n              const boost::shared_ptr<ore::data::CurveConfigurations>& curveConfigs,\n              const boost::shared_ptr<ore::data::Conventions>& conventions,\n              const boost::shared_ptr<ore::data::TodaysMarketParameters>& todaysMarketParams,\n              const boost::shared_ptr<ScenarioSimMarketParameters>& simMarketData,\n              const boost::shared_ptr<ScenarioGeneratorData>& scenarioGeneratorData,\n              const boost::shared_ptr<ore::data::CrossAssetModelData>& crossAssetModelData,\n              std::vector<boost::shared_ptr<ore::data::LegBuilder>> extraLegBuilders = {},\n              std::vector<boost::shared_ptr<ore::data::EngineBuilder>> extraEngineBuilders = {},\n              const boost::shared_ptr<ReferenceDataManager>& referenceData = nullptr,\n              const IborFallbackConfig& iborFallbackConfig = IborFallbackConfig::defaultConfig(),\n              QuantLib::Real dimQuantile = 0.99, QuantLib::Size dimHorizonCalendarDays = 14,\n              map<string, bool> analytics = {}, string calculationType = \"Symmetric\", string dvaName = \"\",\n              string fvaBorrowingCurve = \"\", string fvaLendingCurve = \"\", bool fullInitialCollateralisation = true,\n              bool storeFlows = false);\n\n    // run xva on full portfolio and build post processor\n    void runXva(const boost::shared_ptr<ore::data::Market>& market, bool continueOnErr = true,\n                const std::map<std::string, QuantLib::Real>& currentIM = std::map<std::string, QuantLib::Real>());\n\n    // get post processor, this requires a previous runXva() or generatePostProcessor() call\n    const boost::shared_ptr<PostProcess>& postProcess() { return postProcess_; }\n\n    // step 1: build cam model\n    void buildCamModel(const boost::shared_ptr<ore::data::Market>& market, bool continueOnErr = true);\n\n    // optional step 2: buffer simulation paths, this is required, if a currency filter is used\n    void bufferSimulationPaths();\n\n    // build sim market, optionally on filtered currencies\n    virtual void buildSimMarket(const boost::shared_ptr<ore::data::Market>& market,\n                        const boost::optional<std::set<std::string>>& currencyFilter = boost::none,\n                        const bool continueOnErr = true);\n\n    // step 5: build npv, netting cube (opionally filtered on trades) and generate scenario data\n    void buildCube(const boost::optional<std::set<std::string>>& tradeIds, bool continueOnErr = true);\n\n    // get generated trade cube from step 5\n    boost::shared_ptr<NPVCube> npvCube() const { return cube_; }\n\n    // get generated netting set cube from step 5\n    boost::shared_ptr<NPVCube> nettingCube() const { return nettingCube_; }\n\n    // get aggregation scenario data from step 5\n    boost::shared_ptr<AggregationScenarioData> aggregationScenarioData() { return scenarioData_; }\n\n    // partial step 3: build post processor on given cubes / agg scen data (requires runXva() or buildCamModel() call)\n    void generatePostProcessor(\n        const boost::shared_ptr<Market>& market, const boost::shared_ptr<NPVCube>& npvCube,\n        const boost::shared_ptr<NPVCube>& nettingCube, const boost::shared_ptr<AggregationScenarioData>& scenarioData,\n        const bool continueOnErr = true,\n        const std::map<std::string, QuantLib::Real>& currentIM = std::map<std::string, QuantLib::Real>());\n\n    // get a vector of netting set ids for the given portfolio sorted in alphabetical order, if no portfolio\n    // is given here, the netting sets for the global portfolio set in the ctor are returned\n    std::vector<std::string> getNettingSetIds(const boost::shared_ptr<Portfolio>& portfolio = nullptr) const;\n\nprotected:\n    virtual boost::shared_ptr<NPVCube>\n    getNettingSetCube(std::vector<boost::shared_ptr<ValuationCalculator>>& calculators,\n                      const boost::shared_ptr<Portfolio>& portfolio) {\n        return nullptr;\n    };\n\n    virtual boost::shared_ptr<NPVCube> getNpvCube(const Date& asof, const std::vector<std::string>& ids,\n                                                  const std::vector<Date>& dates, const Size samples,\n                                                  const Size depth) const;\n\n    virtual boost::shared_ptr<DynamicInitialMarginCalculator>\n    getDimCalculator(const boost::shared_ptr<NPVCube>& cube,\n                     const boost::shared_ptr<CubeInterpretation>& cubeInterpreter,\n                     const boost::shared_ptr<AggregationScenarioData>& scenarioData,\n                     const boost::shared_ptr<QuantExt::CrossAssetModel>& model = nullptr,\n                     const boost::shared_ptr<NPVCube>& nettingCube = nullptr,\n                     const std::map<std::string, QuantLib::Real>& currentIM = std::map<std::string, QuantLib::Real>());\n\n    virtual boost::shared_ptr<ore::analytics::ScenarioSimMarketParameters>\n    projectSsmData(const std::set<std::string>& currencyFilter) const;\n\n    virtual boost::shared_ptr<ore::analytics::ScenarioGenerator> getProjectedScenarioGenerator(\n        const boost::optional<std::set<std::string>>& currencyFilter, const boost::shared_ptr<Market>& market,\n        const boost::shared_ptr<ScenarioSimMarketParameters>& projectedSsmData,\n        const boost::shared_ptr<ScenarioFactory>& scenarioFactory, const bool continueOnErr) const;\n    \n    QuantLib::Date asof_;\n    std::string baseCurrency_;\n    boost::shared_ptr<ore::data::Portfolio> portfolio_;\n    boost::shared_ptr<ore::data::NettingSetManager> netting_;\n    boost::shared_ptr<ore::data::EngineData> engineData_;\n    boost::shared_ptr<ore::data::CurveConfigurations> curveConfigs_;\n    boost::shared_ptr<ore::data::Conventions> conventions_;\n    boost::shared_ptr<ore::data::TodaysMarketParameters> todaysMarketParams_;\n    boost::shared_ptr<ScenarioSimMarketParameters> simMarketData_;\n    boost::shared_ptr<ScenarioGeneratorData> scenarioGeneratorData_;\n    boost::shared_ptr<ore::data::CrossAssetModelData> crossAssetModelData_;\n    std::vector<boost::shared_ptr<ore::data::LegBuilder>> extraLegBuilders_;\n    std::vector<boost::shared_ptr<ore::data::EngineBuilder>> extraEngineBuilders_;\n    boost::shared_ptr<ReferenceDataManager> referenceData_;\n    IborFallbackConfig iborFallbackConfig_;\n    QuantLib::Real dimQuantile_;\n    QuantLib::Size dimHorizonCalendarDays_;\n    map<string, bool> analytics_;\n    string inputCalculationType_;\n    string dvaName_;\n    string fvaBorrowingCurve_;\n    string fvaLendingCurve_;\n    bool fullInitialCollateralisation_;\n    bool storeFlows_;\n\n    // generated data\n    boost::shared_ptr<QuantExt::CrossAssetModel> model_;\n    boost::shared_ptr<ScenarioSimMarket> simMarket_;\n    boost::shared_ptr<EngineFactory> simFactory_;\n    boost::shared_ptr<AggregationScenarioData> scenarioData_;\n    boost::shared_ptr<NPVCube> cube_, nettingCube_;\n    boost::shared_ptr<CubeInterpretation> cubeInterpreter_;\n    std::string calculationType_;\n    boost::shared_ptr<PostProcess> postProcess_;\n\n    boost::shared_ptr<std::vector<std::vector<QuantLib::Path>>> bufferedPaths_;\n};\n\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "6e646e6bf65e01c91a5d01600bd4ac165a0a027a", "size": 8703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/app/xvarunner.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": "OREAnalytics/orea/app/xvarunner.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": "OREAnalytics/orea/app/xvarunner.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": 51.4970414201, "max_line_length": 119, "alphanum_fraction": 0.7165345283, "num_tokens": 1989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.16971139883636213}}
{"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// File generated at Thu 10 May 2018 14:33:31\n\n/**\n * @file MSSM_mAmu_two_scale_ewsb_solver.hpp\n *\n * @brief contains class for solving EWSB when two-scale algorithm is used\n *\n * This file was generated at Thu 10 May 2018 14:33:31 with FlexibleSUSY\n * 2.0.1 (git commit: unknown) and SARAH 4.12.2 .\n */\n\n#ifndef MSSM_mAmu_TWO_SCALE_EWSB_SOLVER_H\n#define MSSM_mAmu_TWO_SCALE_EWSB_SOLVER_H\n\n#include \"MSSM_mAmu_ewsb_solver.hpp\"\n#include \"MSSM_mAmu_ewsb_solver_interface.hpp\"\n#include \"error.hpp\"\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\nclass Two_scale;\n\nclass MSSM_mAmu_mass_eigenstates;\n\ntemplate<>\nclass MSSM_mAmu_ewsb_solver<Two_scale> : public MSSM_mAmu_ewsb_solver_interface {\npublic:\n   MSSM_mAmu_ewsb_solver() = default;\n   MSSM_mAmu_ewsb_solver(const MSSM_mAmu_ewsb_solver&) = default;\n   MSSM_mAmu_ewsb_solver(MSSM_mAmu_ewsb_solver&&) = default;\n   virtual ~MSSM_mAmu_ewsb_solver() {}\n   MSSM_mAmu_ewsb_solver& operator=(const MSSM_mAmu_ewsb_solver&) = default;\n   MSSM_mAmu_ewsb_solver& operator=(MSSM_mAmu_ewsb_solver&&) = default;\n\n   virtual void set_loop_order(int l) override { loop_order = l; }\n   virtual void set_number_of_iterations(int n) override { number_of_iterations = n; }\n   virtual void set_precision(double p) override { precision = p; }\n\n   virtual int get_loop_order() const override { return loop_order; }\n   virtual int get_number_of_iterations() const override { return number_of_iterations; }\n   virtual double get_precision() const override { return precision; }\n\n   virtual int solve(MSSM_mAmu_mass_eigenstates&) override;\nprivate:\n   static const int number_of_ewsb_equations = 2;\n   using EWSB_vector_t = Eigen::Matrix<double,number_of_ewsb_equations,1>;\n\n   class EEWSBStepFailed : public Error {\n   public:\n      virtual ~EEWSBStepFailed() {}\n      virtual std::string what() const { return \"Could not perform EWSB step.\"; }\n   };\n\n   int number_of_iterations{100}; ///< maximum number of iterations\n   int loop_order{2};             ///< loop order to solve EWSB at\n   double precision{1.e-5};       ///< precision goal\n\n   void set_ewsb_solution(MSSM_mAmu_mass_eigenstates&, const EWSB_solver*);\n   template <typename It> void set_best_ewsb_solution(MSSM_mAmu_mass_eigenstates&, It, It);\n\n   int solve_tree_level(MSSM_mAmu_mass_eigenstates&);\n   int solve_iteratively(MSSM_mAmu_mass_eigenstates&);\n   int solve_iteratively_at(MSSM_mAmu_mass_eigenstates&, int);\n   int solve_iteratively_with(MSSM_mAmu_mass_eigenstates&, EWSB_solver*, const EWSB_vector_t&);\n\n   EWSB_vector_t initial_guess(const MSSM_mAmu_mass_eigenstates&) const;\n   EWSB_vector_t tadpole_equations(const MSSM_mAmu_mass_eigenstates&) const;\n   EWSB_vector_t ewsb_step(const MSSM_mAmu_mass_eigenstates&) const;\n};\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "f1b0e2bd9a65b13e72824e1ab34e7e1b681c6e74", "size": 3622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSM_mAmu/MSSM_mAmu_two_scale_ewsb_solver.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSM_mAmu/MSSM_mAmu_two_scale_ewsb_solver.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSM_mAmu/MSSM_mAmu_two_scale_ewsb_solver.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 38.1263157895, "max_line_length": 95, "alphanum_fraction": 0.7355052457, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2974699301485223, "lm_q1q2_score": 0.16951402841111954}}
{"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_GENERIC_FUNCTION_SWAPBYTES_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_SWAPBYTES_HPP_INCLUDED\n\n#include <boost/simd/function/shift_left.hpp>\n#include <boost/simd/function/shr.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  BOOST_DISPATCH_OVERLOAD ( swapbytes_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::ints8_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const & a0) const BOOST_NOEXCEPT\n    {\n      return a0;\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( swapbytes_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::ints16_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const & a0) const BOOST_NOEXCEPT\n    {\n      return shift_left(a0, 8)|shr(a0, 8);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( swapbytes_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::type32_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const & a0) const BOOST_NOEXCEPT\n    {\n      A0 val = ((shift_left(a0, 8) & 0xFF00FF00 ) | (shr(a0, 8) & 0xFF00FF ));\n      return shift_left(val, 16) | shr(val,16);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( swapbytes_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::type64_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const & a0) const BOOST_NOEXCEPT\n    {\n      A0 val = (shift_left(a0, 8) & 0xFF00FF00FF00FF00ULL ) | (shr(a0, 8) & 0x00FF00FF00FF00FFULL );\n      val = (shift_left(val, 16) & 0xFFFF0000FFFF0000ULL ) | (shr(val, 16) & 0x0000FFFF0000FFFFULL );\n      return shift_left(val, 32) | shr(val,32);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "c6cb6f9b06414967f89c7cbe1edcbaa3b7b3e111", "size": 2470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/swapbytes.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/swapbytes.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/swapbytes.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.3783783784, "max_line_length": 101, "alphanum_fraction": 0.5093117409, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.16943948060010972}}
{"text": "//\n// Created by dragos on 28.11.2019.\n//\n\n#include \"BugReport.h\"\n#include \"AnalysisContext.h\"\n#include \"PropagateFormulas.h\"\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <fstream>\n\nnamespace analysis {\n\nBugReport::BugReport(P4::ReferenceMap *refMap, P4::TypeMap *typeMap,\n                     bug_report_options brp)\n    : refMap(refMap), typeMap(typeMap), bugReportOptions(std::move(brp)) {\n  passes.push_back(new VisitFunctor([this](const IR::Node *n) {\n    analyzeProgram(n->to<IR::P4Program>());\n    return n;\n  }));\n}\n\nvoid BugReport::analyzeProgram(const IR::P4Program *program) {\n  Analysis analyzer(refMap, typeMap, program, \"run\");\n  auto main = analyzer.getMain();\n  analysis::node_t basicBlockStart;\n  analysis::EdgeHolder basicBlocks, rBasicBlocks;\n  *main = push_ifs(*main, refMap, typeMap);\n  basic_blocks(main->holder, main->start_node, basicBlocks, rBasicBlocks,\n               basicBlockStart);\n  make_ssa(basicBlocks, rBasicBlocks, basicBlockStart, refMap, typeMap,\n           analyzer.getFunMap());\n  auto sorted = analysis::topo_sort(&basicBlocks, basicBlockStart);\n  auto p_ctx = new z3::context();\n  EdgeFormulas edgeFormulas(typeMap, refMap, p_ctx);\n  z3::solver direct_(*p_ctx);\n  z3::solver dual_(*p_ctx);\n  packet_solver_ direct(direct_, edgeFormulas.packetTheory);\n  packet_solver_ dual(direct_, edgeFormulas.packetTheory);\n  z3::expr_vector bugs(*p_ctx);\n  // ensure reverse postorder holds, will help a lot in debugging\n  for (auto I = sorted.rbegin(); I != sorted.rend(); ++I)\n    (void)edgeFormulas.nodeLabel(*I);\n  std::unordered_set<node_t> dead, buggy;\n  std::vector<node_t> sortedBuggy;\n  for (auto &n : sorted) {\n    auto lst = last(n);\n    if (lst) {\n      if (auto mcs = is_extern_method_call(lst)) {\n        if (is_bug(mcs->methodCallStatement)) {\n          buggy.emplace(n);\n          sortedBuggy.emplace_back(n);\n        } else if (is_terminal(mcs->methodCallStatement)) {\n          // replace basic block ending in send/drop with assume false and\n          // simply continue\n          dead.emplace(n);\n          continue;\n        }\n      }\n    }\n  }\n\n  for (auto &n : sorted) {\n    auto Cl = edgeFormulas.node(n);\n    auto nl = edgeFormulas.nodeLabel(n);\n    z3::expr_vector succv(*p_ctx);\n    auto lst = last(n);\n    if (lst) {\n      if (auto mcs = is_extern_method_call(lst)) {\n        if (is_bug(mcs->methodCallStatement)) {\n          bugs.push_back(edgeFormulas.nodeLabel(n));\n        } else if (is_terminal(mcs->methodCallStatement)) {\n          // replace basic block ending in send/drop with assume false and\n          // simply continue\n          direct.add(!edgeFormulas.nodeLabel(n));\n          continue;\n        }\n      }\n    }\n    auto Isuccs = basicBlocks.find(n);\n    bool empty = true;\n    if (Isuccs != basicBlocks.end()) {\n      for (auto &succ : Isuccs->second) {\n        empty = false;\n        if (!dead.count(succ.first)) {\n          succv.push_back(edgeFormulas.nodeLabel(succ.first));\n        }\n      }\n    }\n    if (!succv.empty()) {\n      direct.add(z3::implies(edgeFormulas.nodeLabel(n),\n                             (Cl && z3::mk_or(succv)).simplify()));\n    } else {\n      if (empty) {\n        direct.add(z3::implies(edgeFormulas.nodeLabel(n), Cl));\n      } else {\n        direct.add(!edgeFormulas.nodeLabel(n));\n      }\n    }\n  }\n  // direct now encodes reachability of bug (see reachability modulo theories\n  // paper - aka Corral). If direct is unsat => no bug there\n  // if direct is sat => need to model check the path. see code below\n  direct.add(edgeFormulas.nodeLabel(basicBlockStart));\n\n  auto get_path = [&](z3::model &model) {\n    std::unordered_set<node_t> active;\n    for (auto &n : sorted) {\n      switch (model.eval(edgeFormulas.nodeLabel(n)).bool_value()) {\n      case Z3_L_TRUE:\n        active.emplace(n);\n      default:\n        break;\n      }\n    }\n    std::function<void(std::vector<node_t> &, bool &)> rec;\n    rec = [&](std::vector<node_t> &crt, bool &ret) {\n      if (auto lst = last(crt.back())) {\n        if (auto mcs = is_extern_method_call(lst)) {\n          if (is_bug(mcs->methodCallStatement)) {\n            ret = true;\n            return;\n          }\n        }\n      }\n      auto Isuccs = basicBlocks.find(crt.back());\n      for (auto &n : Isuccs->second) {\n        if (!active.count(n.first))\n          continue;\n        crt.push_back(n.first);\n        rec(crt, ret);\n        if (ret)\n          return;\n        crt.pop_back();\n      }\n      ret = false;\n    };\n    std::vector<node_t> pth({basicBlockStart});\n    bool found = false;\n    rec(pth, found);\n    BUG_CHECK(found, \"model says path found, but none there\");\n    return pth;\n  };\n  NodeValues<std::unordered_set<z3::expr>> packetAtoms;\n  for (auto &node : sorted) {\n    auto Cl = edgeFormulas.node(node);\n    if (Cl.is_and()) {\n      for (unsigned i = 0, e = Cl.num_args(); i != e; ++i) {\n        auto exp = Cl.arg(i);\n        if (exp.is_eq()) {\n          auto arg0 = exp.arg(0);\n          auto arg1 = exp.arg(1);\n          if (edgeFormulas.packetTheory.isPacket(arg0)) {\n            packetAtoms[node].emplace(exp);\n          }\n        }\n      }\n    }\n  }\n  while (direct.check() == z3::check_result::sat) {\n    auto model = direct.get_model();\n    std::unordered_set<node_t> active;\n    auto pth = get_path(model);\n    std::copy(pth.begin(), pth.end(), std::inserter(active, active.begin()));\n\n    auto smtPrint = [&](std::ostream &os, const node_t &n) {\n      if (dead.count(n)) {\n        os << n.nodeId()\n           << \"[style=filled,label=\\\"dead\\\",filledcolor=gray47];\\n\";\n        return;\n      }\n      os << n.nodeId() << \"[shape=box,label=\\\"\";\n      auto Cl = edgeFormulas.node(n);\n      if (Cl.is_and()) {\n        for (unsigned i = 0, e = Cl.num_args(); i != e; ++i) {\n          os << Cl.arg(i) << \"\\n\";\n        }\n      } else {\n        os << Cl;\n      }\n      os << \"\\\"\";\n      if (active.count(n)) {\n        os << \",style=filled,color=forestgreen\";\n      }\n      os << \"]\\n\";\n    };\n    std::unordered_map<z3::expr, unsigned> termindex;\n    std::vector<z3::expr> revtermindex;\n    std::unordered_map<unsigned, std::set<unsigned>> deps;\n    typedef std::map<unsigned, std::size_t> rank_t; // => order on Element\n    typedef std::map<unsigned, unsigned> parent_t;\n    rank_t rank_map;\n    parent_t parent_map;\n    boost::associative_property_map<rank_t> rank_pmap(rank_map);\n    boost::associative_property_map<parent_t> parent_pmap(parent_map);\n    boost::disjoint_sets<boost::associative_property_map<rank_t>,\n                         boost::associative_property_map<parent_t>>\n        djsets(rank_pmap, parent_pmap);\n    auto mkSet = [&](const z3::expr &e0) -> unsigned {\n      auto EMI0 = termindex.emplace(e0, termindex.size());\n      if (EMI0.second) {\n        revtermindex.push_back(e0);\n        djsets.make_set(EMI0.first->second);\n      }\n      return EMI0.first->second;\n    };\n    auto split = [&](const z3::expr &e) {\n      if (edgeFormulas.packetTheory.isPrepend(e)) {\n        auto e0 = e.arg(0);\n        auto e1 = e.arg(1);\n        deps[mkSet(e)].emplace(mkSet(e0));\n        deps[mkSet(e)].emplace(mkSet(e1));\n      }\n    };\n    z3::expr_vector allConstraints(*p_ctx);\n    auto isPrepend = [&](const z3::expr &e) {\n      return edgeFormulas.packetTheory.isPrepend(e);\n    };\n    auto tmpPack = [&]() {\n      return z3::to_expr(\n          *p_ctx, Z3_mk_fresh_const(*p_ctx, \"pack\",\n                                    edgeFormulas.packetTheory.packetSort));\n    };\n    auto normalizePrepend = [&](const z3::expr &e0,\n                                std::vector<z3::expr> &extra_equalities) {\n      if (isPrepend(e0)) {\n        auto e01 = e0.arg(1);\n        auto rep = djsets.find_set(termindex[e01]);\n        auto &repe = revtermindex[rep];\n        if (isPrepend(repe)) {\n          auto tmp = tmpPack();\n          extra_equalities.push_back(\n              tmp == edgeFormulas.packetTheory.prepend(e0.arg(0), repe.arg(0)));\n          return edgeFormulas.packetTheory.prepend(tmp, repe.arg(1));\n        }\n      }\n      return e0;\n    };\n\n    std::function<void(const z3::expr &)> handleEquality;\n    handleEquality = [&](const z3::expr &eq) {\n      std::vector<z3::expr> extra_equalities;\n      auto e0 = eq.arg(0);\n      auto e1 = eq.arg(1);\n      split(e0);\n      split(e1);\n      // normalize prepends into right normal form:\n      // prepend(a, prepend(b, c)) == prepend(prepend(a, b), c)\n      // add tmp == prepend(a, b) && e0 <- prepend(tmp, c)\n      e0 = normalizePrepend(e0, extra_equalities);\n      e1 = normalizePrepend(e1, extra_equalities);\n      for (auto &xx : extra_equalities) {\n        handleEquality(xx);\n      }\n      auto ei0 = djsets.find_set(mkSet(e0));\n      auto ei1 = djsets.find_set(mkSet(e1));\n      // this is equality is redundant, move on\n      if (ei0 == ei1)\n        return;\n      auto &ax0 = revtermindex[ei0];\n      auto &ax1 = revtermindex[ei1];\n      if (isPrepend(ax0) && isPrepend(ax1)) {\n        // two prepends are trying to get into the same class\n        // xy = ut. Given property of right known length, we know\n        // that y = emit_N (X1) && t = emit_M (X2)\n        // case split on N vs M\n        auto x = ax0.arg(0);\n        auto y = ax0.arg(1);\n        auto u = ax1.arg(0);\n        auto t = ax1.arg(1);\n        auto emN = edgeFormulas.packetTheory.isEmit(y.decl());\n        auto emM = edgeFormulas.packetTheory.isEmit(t.decl());\n        BUG_CHECK(emN && emM,\n                  \"can't handle prepend with unknown rights %1% vs %2%\", ax0,\n                  ax1);\n        if (*emN == *emM) {\n          auto X1 = y.arg(0);\n          auto X2 = t.arg(0);\n          auto propagate = X1 == X2;\n          LOG4(\"propagating \" << propagate);\n          allConstraints.push_back(propagate);\n          handleEquality(x == u);\n        } else {\n          if (*emN > *emM) {\n            std::swap(x, u);\n            std::swap(y, t);\n            emN.swap(emM);\n          }\n          auto X1 = y.arg(0);\n          auto X2 = t.arg(0);\n          auto propagate = X1 == X2.extract(*emM - 1, *emM - *emN);\n          LOG4(\"propagating \" << propagate);\n          allConstraints.push_back(propagate);\n          handleEquality(x ==\n                         edgeFormulas.packetTheory.prepend(\n                             u,\n                             edgeFormulas.packetTheory.emit(*emM - *emN)(\n                                 X2.extract(*emM - *emN - 1, 0))));\n        }\n      } else {\n        // link classes\n        djsets.link(ei0, ei1);\n        auto rep = djsets.find_set(ei0);\n        // if either one of the equated (x, y) are\n        // in the same eq class with eps then ensure\n        // that the representative of the newly formed\n        // set corresponds to eps\n        if (edgeFormulas.packetTheory.isZero(ax0) ||\n            edgeFormulas.packetTheory.isZero(ax1)) {\n          if (!edgeFormulas.packetTheory.isZero(revtermindex[rep])) {\n            auto zerorep =\n                djsets.find_set(mkSet(edgeFormulas.packetTheory.zero()));\n            std::swap(termindex[revtermindex[rep]],\n                      termindex[revtermindex[zerorep]]);\n            std::swap(revtermindex[rep], revtermindex[zerorep]);\n          }\n        }\n      }\n    };\n\n    for (auto &n : pth) {\n      allConstraints.push_back(edgeFormulas.nodeLabel(n));\n      auto &patoms = packetAtoms[n];\n      for (auto &eq : patoms) {\n        handleEquality(eq);\n      }\n    }\n    auto cr = direct.check(allConstraints);\n    if (cr == z3::check_result::sat) {\n      z3::expr_vector block(*p_ctx);\n      for (auto &n : pth) {\n        block.push_back(!edgeFormulas.nodeLabel(n));\n      }\n      {\n        std::ofstream path(refMap->newName(\"path\") + \".dot\");\n        CFG cfg(nullptr, std::move(basicBlocks));\n        cfg.start_node = basicBlockStart;\n        cfg.toDot(path, smtPrint);\n        basicBlocks = std::move(cfg.holder);\n      }\n      auto mdl = direct.get_model();\n      // TODO: find initial packet from program and solve for it\n      // TODO: magic with mdl to get the packet + djsets and friends\n      // TODO: dump packet to options.packet_file\n      // TODO: uncomment if need more examples\n      std::ofstream report(bugReportOptions.packet_file);\n      //      direct.add(z3::mk_or(block));\n      LOG4(\"bug reachable!\");\n      break;\n    } else {\n      LOG4(\"spurious path detected\");\n      auto uc = direct.unsat_core();\n      direct.add(!z3::mk_and(uc));\n    }\n  }\n}\n}", "meta": {"hexsha": "ff76ff66245c8478a4a00f1cc5a9c047b08f5c0a", "size": 12428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "backends/analysis/ub/BugReport.cpp", "max_stars_repo_name": "dragosdmtrsc/bf4", "max_stars_repo_head_hexsha": "2e15e50acc4314737d99093b3d900fa44d795958", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T12:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T02:15:04.000Z", "max_issues_repo_path": "backends/analysis/ub/BugReport.cpp", "max_issues_repo_name": "shellqiqi/bf4", "max_issues_repo_head_hexsha": "6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-09-28T12:17:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T12:23:38.000Z", "max_forks_repo_path": "backends/analysis/ub/BugReport.cpp", "max_forks_repo_name": "shellqiqi/bf4", "max_forks_repo_head_hexsha": "6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-13T07:59:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T21:35:05.000Z", "avg_line_length": 34.81232493, "max_line_length": 80, "alphanum_fraction": 0.5708078532, "num_tokens": 3326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.16943947229111256}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/def.hpp>\n\n#include \"iotbx/xplor/map_reader.h\"\n#include \"iotbx/xplor/map_writer.h\"\n\n#include <cctbx/uctbx.h>\n\nnamespace af = scitbx::af;\n\nnamespace iotbx { namespace boost_python { namespace xplor_ext {\n\n  void init_module()\n  {\n    using namespace boost::python;\n    using namespace iotbx::xplor;\n\n    class_<map_reader>(\"map_reader\", no_init)\n      .def(init<std::string const&, std::size_t, af::flex_grid<> const&>(\n        (arg(\"file_name\"), arg(\"n_header_lines\"), arg(\"grid\"))))\n      .def_readonly(\"data\", &map_reader::data)\n      .def_readonly(\"average\", &map_reader::average)\n      .def_readonly(\"standard_deviation\", &map_reader::standard_deviation)\n    ;\n\n    def(\"map_writer\", map_writer_box,\n      (arg(\"file_name\"), arg(\"unit_cell\"),\n       arg(\"data\"),\n       arg(\"average\"), arg(\"standard_deviation\")));\n    def(\"map_writer\", map_writer_p1_cell,\n      (arg(\"file_name\"), arg(\"unit_cell\"),\n       arg(\"gridding_first\"), arg(\"gridding_last\"), arg(\"data\"),\n       arg(\"average\"), arg(\"standard_deviation\")));\n  }\n\n}}} // namespace iotbx::boost_python::xplor_ext\n\nBOOST_PYTHON_MODULE(iotbx_xplor_ext)\n{\n  iotbx::boost_python::xplor_ext::init_module();\n}\n", "meta": {"hexsha": "327ca3ae445a223cdc5f6a3c9a83d36a20d7c572", "size": 1289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iotbx/xplor/boost_python/xplor_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": "iotbx/xplor/boost_python/xplor_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": "iotbx/xplor/boost_python/xplor_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": 29.2954545455, "max_line_length": 74, "alphanum_fraction": 0.6764934057, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.16943946891347478}}
{"text": "/*\n * ray_predictor.cc\n *\n *  Copyright (C) 2013 Diamond Light Source\n *\n *  Author: James Parkhurst\n *\n *  This code is distributed under the BSD license, a copy of which is\n *  included in the root directory of this package.\n */\n#include <boost/python.hpp>\n#include <boost/python/def.hpp>\n#include <dials/array_family/reflection_table.h>\n#include <dials/algorithms/spot_prediction/ray_predictor.h>\n#include <dxtbx/model/scan.h>\n#include <dxtbx/model/beam.h>\n#include <dxtbx/model/goniometer.h>\n#include <dxtbx/model/detector.h>\n\nnamespace dials { namespace algorithms { namespace boost_python {\n\n  using namespace boost::python;\n\n  static af::reflection_table call_with_miller_index_array(\n    const ScanStaticRayPredictor &self,\n    const af::const_ref<cctbx::miller::index<> > &h,\n    const mat3<double> &UB) {\n    af::reflection_table result;\n    af::shared<cctbx::miller::index<> > hkl = result[\"miller_index\"];\n    af::shared<vec3<double> > s1 = result[\"s1\"];\n    af::shared<bool> entering = result[\"entering\"];\n    af::shared<double> phi = result[\"phi\"];\n    for (std::size_t i = 0; i < h.size(); ++i) {\n      af::small<Ray, 2> rays = self(h[i], UB);\n      for (std::size_t j = 0; j < rays.size(); ++j) {\n        hkl.push_back(h[i]);\n        s1.push_back(rays[j].s1);\n        entering.push_back(rays[j].entering);\n        phi.push_back(rays[j].angle);\n      }\n    }\n    DIALS_ASSERT(result.is_consistent());\n    return result;\n  }\n\n  void export_ray_predictor() {\n    // Create and return the wrapper for the spot predictor object\n    class_<ScanStaticRayPredictor>(\"ScanStaticRayPredictor\", no_init)\n      .def(init<vec3<double>, vec3<double>, mat3<double>, mat3<double>, vec2<double> >(\n        (arg(\"s0\"),\n         arg(\"m2\"),\n         arg(\"fixed_rotation\"),\n         arg(\"setting_rotation\"),\n         arg(\"dphi\"))))\n      .def(\"__call__\",\n           &ScanStaticRayPredictor::operator(),\n           (arg(\"miller_index\"), arg(\"UB\")))\n      .def(\"__call__\", &ScanStaticRayPredictor::from_reciprocal_lattice_vector)\n      .def(\"__call__\", &call_with_miller_index_array);\n  }\n\n}}}  // namespace dials::algorithms::boost_python\n", "meta": {"hexsha": "fd3494cc2ad87ce6747485e2639095f869983e95", "size": 2133, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/spot_prediction/boost_python/ray_predictor.cc", "max_stars_repo_name": "TiankunZhou/dials", "max_stars_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2015-10-15T09:28:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T20:09:38.000Z", "max_issues_repo_path": "algorithms/spot_prediction/boost_python/ray_predictor.cc", "max_issues_repo_name": "TiankunZhou/dials", "max_issues_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1741.0, "max_issues_repo_issues_event_min_datetime": "2015-11-24T08:17:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:46:42.000Z", "max_forks_repo_path": "algorithms/spot_prediction/boost_python/ray_predictor.cc", "max_forks_repo_name": "TiankunZhou/dials", "max_forks_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2015-10-14T13:44:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T14:45:56.000Z", "avg_line_length": 33.8571428571, "max_line_length": 87, "alphanum_fraction": 0.6554149086, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.16943946891347478}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2020.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Douglas McCloskey $\n// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitation.h>\n\n//Kernal classes\n#include <OpenMS/KERNEL/StandardTypes.h>\n#include <OpenMS/KERNEL/MSExperiment.h>\n#include <OpenMS/KERNEL/MSChromatogram.h>\n#include <OpenMS/KERNEL/FeatureMap.h>\n#include <OpenMS/KERNEL/MRMTransitionGroup.h>\n#include <OpenMS/KERNEL/MRMFeature.h>\n\n//OpenSWATH classes\n#include <OpenMS/ANALYSIS/OPENSWATH/MRMRTNormalizer.h>\n\n//Analysis classes\n#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h>\n#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>\n#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>\n\n//Quantitation classes\n#include <OpenMS/METADATA/AbsoluteQuantitationStandards.h>\n#include <OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitationMethod.h>\n\n//Math classes\n#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>\n\n//Standard library\n#include <cstddef> // for size_t & ptrdiff_t\n#include <vector>\n#include <cmath>\n#include <numeric>\n#include <boost/math/special_functions/erf.hpp>\n#include <algorithm>\n\nnamespace OpenMS\n{\n\n  AbsoluteQuantitation::AbsoluteQuantitation() :\n  DefaultParamHandler(\"AbsoluteQuantitation\")\n  {\n    defaults_.setValue(\"min_points\", 4, \"The minimum number of calibrator points.\");\n\n    defaults_.setValue(\"max_bias\", 30.0, \"The maximum percent bias of any point in the calibration curve.\");\n\n    defaults_.setValue(\"min_correlation_coefficient\", 0.9, \"The minimum correlation coefficient value of the calibration curve.\");\n\n    defaults_.setValue(\"max_iters\", 100, \"The maximum number of iterations to find an optimal set of calibration curve points and parameters.\");\n\n    defaults_.setValue(\"outlier_detection_method\", \"iter_jackknife\", \"Outlier detection method to find and remove bad calibration points.\");\n    defaults_.setValidStrings(\"outlier_detection_method\", ListUtils::create<String>(\"iter_jackknife,iter_residual\"));\n\n    defaults_.setValue(\"use_chauvenet\", \"true\", \"Whether to only remove outliers that fulfill Chauvenet's criterion for outliers (otherwise it will remove any outlier candidate regardless of the criterion).\");\n    defaults_.setValidStrings(\"use_chauvenet\", ListUtils::create<String>(\"true,false\"));\n\n    defaults_.setValue(\"optimization_method\", \"iterative\", \"Calibrator optimization method to find the best set of calibration points for each method.\");\n    defaults_.setValidStrings(\"optimization_method\", ListUtils::create<String>(\"iterative\"));\n\n    // write defaults into Param object param_\n    defaultsToParam_();\n    updateMembers_();\n  }\n\n  void AbsoluteQuantitation::updateMembers_()\n  {\n    min_points_ = (size_t)param_.getValue(\"min_points\");\n    max_bias_ = (double)param_.getValue(\"max_bias\");\n    min_correlation_coefficient_ = (double)param_.getValue(\"min_correlation_coefficient\");\n    max_iters_ = (size_t)param_.getValue(\"max_iters\");\n    outlier_detection_method_ = param_.getValue(\"outlier_detection_method\");\n    use_chauvenet_ = (bool)param_.getValue(\"use_chauvenet\").toBool();\n    optimization_method_ = param_.getValue(\"optimization_method\");\n  }\n\n  AbsoluteQuantitation::~AbsoluteQuantitation()\n  {\n  }\n\n  void AbsoluteQuantitation::setQuantMethods(std::vector<AbsoluteQuantitationMethod>& quant_methods)\n  {\n    quant_methods_.clear();\n    for (size_t i = 0; i < quant_methods.size(); i++)\n    {\n      String component_name = quant_methods[i].getComponentName();\n      quant_methods_[component_name] = quant_methods[i];\n    }\n  }\n\n  std::vector<AbsoluteQuantitationMethod> AbsoluteQuantitation::getQuantMethods()\n  {\n    std::vector<AbsoluteQuantitationMethod> quant_methods;\n    for (auto const& quant_method : quant_methods_)\n    {\n      quant_methods.push_back(quant_method.second);\n    }\n    return quant_methods;\n  }\n\n  std::map<String, AbsoluteQuantitationMethod> AbsoluteQuantitation::getQuantMethodsAsMap()\n  {\n    return quant_methods_;\n  }\n\n  double AbsoluteQuantitation::calculateRatio(const Feature & component_1, const Feature & component_2, const String & feature_name)\n  {\n    double ratio = 0.0;\n    // member feature_name access\n    if (feature_name == \"intensity\")\n    {\n      if (component_1.metaValueExists(\"native_id\") && component_2.metaValueExists(\"native_id\"))\n      {\n        const double feature_1 = component_1.getIntensity();\n        const double feature_2 = component_2.getIntensity();\n        ratio = feature_1 / feature_2;\n      }\n      else if (component_1.metaValueExists(\"native_id\"))\n      {\n        OPENMS_LOG_DEBUG << \"Warning: no IS found for component \" << component_1.getMetaValue(\"native_id\") << \".\";\n        const double feature_1 = component_1.getIntensity();\n        ratio = feature_1;\n      }\n    }\n    // metaValue feature_name access\n    else\n    {\n      if (component_1.metaValueExists(feature_name) && component_2.metaValueExists(feature_name))\n      {\n        const double feature_1 = component_1.getMetaValue(feature_name);\n        const double feature_2 = component_2.getMetaValue(feature_name);\n        ratio = feature_1/feature_2;\n      }\n      else if (component_1.metaValueExists(feature_name))\n      {\n        OPENMS_LOG_DEBUG << \"Warning: no IS found for component \" << component_1.getMetaValue(\"native_id\") << \".\";\n        const double feature_1 = component_1.getMetaValue(feature_name);\n        ratio = feature_1;\n      }\n      else\n      {\n        OPENMS_LOG_DEBUG << \"Feature metaValue \" << feature_name << \" not found for components \" << component_1.getMetaValue(\"native_id\") << \" and \" << component_2.getMetaValue(\"native_id\") << \".\";\n      }\n    }\n\n    return ratio;\n  }\n\n  double AbsoluteQuantitation::calculateBias(const double & actual_concentration, const double & calculated_concentration)\n  {\n    double bias = fabs(actual_concentration - calculated_concentration)/actual_concentration*100;\n    return bias;\n  }\n\n  Param AbsoluteQuantitation::fitCalibration(\n    const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations,\n    const String & feature_name,\n    const String & transformation_model,\n    const Param & transformation_model_params)\n  {\n    // extract out the calibration points\n    TransformationModel::DataPoints data;\n    TransformationModel::DataPoint point;\n    for (size_t i = 0; i < component_concentrations.size(); i++)\n    {\n      point.first = component_concentrations[i].actual_concentration / component_concentrations[i].IS_actual_concentration / component_concentrations[i].dilution_factor; // adjust based on the dilution factor\n      double ratio = calculateRatio(component_concentrations[i].feature, component_concentrations[i].IS_feature,feature_name);\n      point.second = ratio;\n      data.push_back(point);\n    }\n\n    // fit the data to the model\n    TransformationDescription tmd(data);\n    // tmd.setDataPoints(data);\n    tmd.fitModel(transformation_model, transformation_model_params);\n    Param params = tmd.getModelParameters();\n    // AbsoluteQuantitationMethod aqm;\n    // Param params = aqm.fitTransformationModel(transformation_model, data, transformation_model_params);\n\n    // store the information about the fit\n    return params;\n  }\n\n  void AbsoluteQuantitation::calculateBiasAndR(\n    const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations,\n    const String & feature_name,\n    const String & transformation_model,\n    const Param & transformation_model_params,\n    std::vector<double> & biases,\n    double & correlation_coefficient)\n  {\n    // reset biases\n    biases.clear();\n\n    // extract out the calibration points\n    std::vector<double> concentration_ratios, feature_amounts_ratios;\n    TransformationModel::DataPoints data;\n    TransformationModel::DataPoint point;\n    for (size_t i = 0; i < component_concentrations.size(); ++i)\n    {\n\n      // calculate the actual and calculated concentration ratios\n      double calculated_concentration_ratio = applyCalibration(component_concentrations[i].feature,\n        component_concentrations[i].IS_feature,\n        feature_name,\n        transformation_model,\n        transformation_model_params);\n\n      double actual_concentration_ratio = component_concentrations[i].actual_concentration/\n        component_concentrations[i].IS_actual_concentration / component_concentrations[i].dilution_factor;\n      concentration_ratios.push_back(component_concentrations[i].actual_concentration);\n\n      // extract out the feature amount ratios\n      double feature_amount_ratio = calculateRatio(component_concentrations[i].feature,\n        component_concentrations[i].IS_feature,\n        feature_name);\n      feature_amounts_ratios.push_back(feature_amount_ratio);\n\n      // calculate the bias\n      double bias = calculateBias(actual_concentration_ratio, calculated_concentration_ratio);\n      biases.push_back(bias);\n\n      point.first = actual_concentration_ratio;\n      point.second = feature_amount_ratio;\n      data.push_back(point);\n    }\n\n    // apply weighting to the feature amounts and actual concentration ratios\n    TransformationModel tm(data, transformation_model_params);\n    tm.weightData(data);\n    std::vector<double> concentration_ratios_weighted, feature_amounts_ratios_weighted;\n    for (size_t i = 0; i < data.size(); ++i)\n    {\n      concentration_ratios_weighted.push_back(data[i].first);\n      feature_amounts_ratios_weighted.push_back(data[i].second);\n    }\n\n    // calculate the R2 (R2 = Pearson_R^2)\n    correlation_coefficient = Math::pearsonCorrelationCoefficient(\n      concentration_ratios_weighted.begin(), concentration_ratios_weighted.begin() + concentration_ratios_weighted.size(),\n      feature_amounts_ratios_weighted.begin(), feature_amounts_ratios_weighted.begin() + feature_amounts_ratios_weighted.size()\n    );\n  }\n\n  double AbsoluteQuantitation::applyCalibration(const Feature & component,\n    const Feature & IS_component,\n    const String & feature_name,\n    const String & transformation_model,\n    const Param & transformation_model_params)\n  {\n    // calculate the ratio\n    double ratio = calculateRatio(component, IS_component, feature_name);\n\n    // calculate the absolute concentration\n    TransformationModel::DataPoints data;\n    TransformationDescription tmd(data);\n    // tmd.setDataPoints(data);\n    tmd.fitModel(transformation_model, transformation_model_params);\n    tmd.invert();\n    double calculated_concentration = tmd.apply(ratio);\n\n    // AbsoluteQuantitationMethod aqm;\n    // double calculated_concentration = aqm.evaluateTransformationModel(\n    //   transformation_model, ratio, transformation_model_params);\n\n    // check for less than zero\n    if (calculated_concentration < 0.0)\n    {\n      calculated_concentration = 0.0;\n    }\n\n    return calculated_concentration;\n  }\n\n  void AbsoluteQuantitation::quantifyComponents(FeatureMap& unknowns)\n  {\n    //Potential Optimizations: create a map for each unknown FeatureMap\n    // to reduce multiple loops\n\n    // initialize all other variables\n    Feature empty_feature;\n    size_t IS_component_it(0), IS_component_group_it(0);\n\n    // // iterate through the unknowns\n    // for (size_t i = 0; i < unknowns.size(); i++)\n    // {\n\n    // iterate through each component_group/feature\n    for (size_t feature_it = 0; feature_it < unknowns.size(); ++feature_it)\n    {\n      String component_group_name = (String)unknowns[feature_it].getMetaValue(\"PeptideRef\");\n      Feature unknowns_quant_feature;\n\n      // iterate through each component/sub-feature\n      for (size_t sub_it = 0; sub_it < unknowns[feature_it].getSubordinates().size(); ++sub_it)\n      {\n        String component_name = (String)unknowns[feature_it].getSubordinates()[sub_it].getMetaValue(\"native_id\");\n\n        // apply the calibration curve to components that are in the quant_method\n        if (quant_methods_.count(component_name)>0)\n        {\n          double calculated_concentration = 0.0;\n          std::map<String,AbsoluteQuantitationMethod>::iterator quant_methods_it = quant_methods_.find(component_name);\n          String quant_component_name = quant_methods_it->second.getComponentName();\n          String quant_IS_component_name = quant_methods_it->second.getISName();\n          String quant_feature_name = quant_methods_it->second.getFeatureName();\n          if (quant_IS_component_name != \"\")\n          {\n            // look up the internal standard for the component\n            bool IS_found = false;\n            // Optimization: 90% of the IS will be in the same component_group/feature\n            for (size_t is_sub_it = 0; is_sub_it < unknowns[feature_it].getSubordinates().size(); ++is_sub_it)\n            {\n              String IS_component_name = (String)unknowns[feature_it].getSubordinates()[is_sub_it].getMetaValue(\"native_id\");\n              if (quant_IS_component_name == IS_component_name)\n              {\n                IS_found = true;\n                IS_component_group_it = feature_it;\n                IS_component_it = is_sub_it;\n                break;\n              }\n            }\n            if (!IS_found)\n            {// expand IS search to all components\n              // iterate through each component_group/feature\n              for (size_t is_feature_it = 0; is_feature_it < unknowns.size(); ++is_feature_it)\n              {\n                //iterate through each component/sub-feature\n                for (size_t is_sub_it = 0; is_sub_it < unknowns[is_feature_it].getSubordinates().size(); ++is_sub_it)\n                {\n                  String IS_component_name = (String)unknowns[is_feature_it].getSubordinates()[is_sub_it].getMetaValue(\"native_id\");\n                  if (quant_IS_component_name == IS_component_name)\n                  {\n                    IS_found = true;\n                    IS_component_group_it = is_feature_it;\n                    IS_component_it = is_sub_it;\n                    break;\n                  }\n                }\n                if (IS_found)\n                {\n                  break;\n                }\n              }\n            }\n            if (IS_found)\n            {\n              String transformation_model = quant_methods_it->second.getTransformationModel();\n              Param transformation_model_params = quant_methods_it->second.getTransformationModelParams();\n              calculated_concentration = applyCalibration(\n                unknowns[feature_it].getSubordinates()[sub_it],\n                unknowns[IS_component_group_it].getSubordinates()[IS_component_it],\n                quant_feature_name,transformation_model,transformation_model_params);\n            }\n            else\n            {\n              OPENMS_LOG_INFO << \"Component \" << component_name << \" IS \" << quant_IS_component_name << \" was not found.\";\n              OPENMS_LOG_INFO << \"No concentration will be calculated.\\n\";\n            }\n          }\n          else\n          {\n            String transformation_model = quant_methods_it->second.getTransformationModel();\n            Param transformation_model_params = quant_methods_it->second.getTransformationModelParams();\n            calculated_concentration = applyCalibration(\n              unknowns[feature_it].getSubordinates()[sub_it],\n              empty_feature,\n              quant_feature_name,transformation_model,transformation_model_params);\n          }\n\n          // add new metadata (calculated_concentration, concentration_units) to the component\n          unknowns[feature_it].getSubordinates()[sub_it].setMetaValue(\"calculated_concentration\",calculated_concentration);\n          String concentration_units = quant_methods_it->second.getConcentrationUnits();\n          unknowns[feature_it].getSubordinates()[sub_it].setMetaValue(\"concentration_units\",concentration_units);\n          // calculate the bias?\n        }\n        else\n        {\n          OPENMS_LOG_INFO << \"Component \" << component_name << \" does not have a quantitation method.\";\n          OPENMS_LOG_INFO << \"No concentration will be calculated.\\n\";\n          unknowns[feature_it].getSubordinates()[sub_it].setMetaValue(\"calculated_concentration\",\"\");\n          unknowns[feature_it].getSubordinates()[sub_it].setMetaValue(\"concentration_units\",\"\");\n        }\n      }\n    }\n    // }\n  }\n\n  bool AbsoluteQuantitation::optimizeCalibrationCurveIterative(\n    std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations,\n    const String & feature_name,\n    const String & transformation_model,\n    const Param & transformation_model_params,\n    Param & optimized_params)\n  {\n\n    // sort from min to max concentration\n    std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations_sorted = component_concentrations;\n    std::sort(component_concentrations_sorted.begin(), component_concentrations_sorted.end(),\n      [](AbsoluteQuantitationStandards::featureConcentration lhs, AbsoluteQuantitationStandards::featureConcentration rhs)\n      {\n        return lhs.actual_concentration < rhs.actual_concentration; //ascending order\n      }\n    );\n\n    // indices of component_concentrations\n    std::vector<size_t> component_concentrations_sorted_indices;// loop from all points to min_points\n    for (size_t index = 0; index < component_concentrations_sorted.size(); ++index)\n    {\n      component_concentrations_sorted_indices.push_back(index);\n    }\n\n    // starting parameters\n    optimized_params = transformation_model_params;\n\n    // for (size_t n_iters = 0; n_iters < max_iters_; ++n_iters)\n    for (size_t n_iters = 0; n_iters < component_concentrations_sorted.size(); ++n_iters)\n    {\n\n      // extract out components\n      const std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations_sub = extractComponents_(\n        component_concentrations_sorted, component_concentrations_sorted_indices);\n\n      // check if the min number of calibration points has been broken\n      if (component_concentrations_sorted_indices.size() < min_points_)\n      {\n        OPENMS_LOG_INFO << \"No optimal calibration found for \" << component_concentrations_sub[0].feature.getMetaValue(\"native_id\") << \" .\";\n        return false;  //no optimal calibration found\n      }\n\n      // fit the model\n      optimized_params = fitCalibration(component_concentrations_sub,\n        feature_name,\n        transformation_model,\n        optimized_params);\n\n      // calculate the R2 and bias\n      std::vector<double> biases; // not needed (method parameters)\n      double correlation_coefficient = 0.0; // not needed (method parameters)\n      calculateBiasAndR(\n        component_concentrations_sub,\n        feature_name,\n        transformation_model,\n        optimized_params,\n        biases,\n        correlation_coefficient);\n\n      // check R2 and biases\n      bool bias_check = true;\n      for (size_t bias_it = 0; bias_it < biases.size(); ++bias_it)\n      {\n        if (biases[bias_it] > max_bias_)\n        {\n          bias_check = false;\n        }\n      }\n      if (bias_check && correlation_coefficient > min_correlation_coefficient_)\n      {\n        OPENMS_LOG_INFO << \"Valid calibration found for \" << component_concentrations_sub[0].feature.getMetaValue(\"native_id\") << \" .\";\n\n        // copy over the final optimized points before exiting\n        component_concentrations = component_concentrations_sub;\n        return true;  //optimal calibration found\n      }\n\n      // R2 and biases check failed, determine potential outlier\n      int pos;\n      if (outlier_detection_method_ == \"iter_jackknife\")\n      {\n        // get candidate outlier: removal of which datapoint results in best rsq?\n        pos = jackknifeOutlierCandidate_(\n          component_concentrations_sub,\n          feature_name,\n          transformation_model,\n          optimized_params);\n      }\n      else if (outlier_detection_method_ == \"iter_residual\")\n      {\n        // get candidate outlier: removal of datapoint with largest residual?\n        pos = residualOutlierCandidate_(\n          component_concentrations_sub,\n          feature_name,\n          transformation_model,\n          optimized_params);\n      }\n      else\n      {\n        throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,\n          String(\"Method \") + outlier_detection_method_ + \" is not a valid method for optimizeCalibrationCurveIterative\");\n      }\n\n      // remove if residual is an outlier according to Chauvenet's criterion\n      // or if testing is turned off\n      if (!use_chauvenet_ || MRMRTNormalizer::chauvenet(biases, pos))\n      {\n        component_concentrations_sorted_indices.erase(component_concentrations_sorted_indices.begin() + pos);\n      }\n      else\n      {\n        return false;  //no optimal calibration found\n      }\n    }\n    return false;  //no optimal calibration found\n  }\n\n  std::vector<AbsoluteQuantitationStandards::featureConcentration> AbsoluteQuantitation::extractComponents_(\n    const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations,\n    const std::vector<size_t>& component_concentrations_indices)\n  {\n    std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations_sub;\n    for (size_t iter = 0; iter < component_concentrations_indices.size(); ++iter)\n    {\n      component_concentrations_sub.push_back(component_concentrations[component_concentrations_indices[iter]]);\n    }\n    return component_concentrations_sub;\n\n  }\n\n  int AbsoluteQuantitation::jackknifeOutlierCandidate_(\n    const std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations,\n    const String & feature_name,\n    const String & transformation_model,\n    const Param & transformation_model_params)\n  {\n    // Returns candidate outlier: A linear regression and rsq is calculated for\n    // the data points with one removed pair. The combination resulting in\n    // highest rsq is considered corresponding to the outlier candidate. The\n    // corresponding iterator position is then returned.\n    std::vector<double> rsq_tmp;\n    Param optimized_params = transformation_model_params;\n\n    for (Size i = 0; i < component_concentrations.size(); i++)\n    {\n      std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations_tmp = component_concentrations;\n      component_concentrations_tmp.erase(component_concentrations_tmp.begin() + i);\n\n      // fit the model\n      optimized_params = fitCalibration(component_concentrations_tmp,\n        feature_name,\n        transformation_model,\n        optimized_params);\n\n      // calculate the R2 and bias\n      std::vector<double> biases;\n      double correlation_coefficient = 0.0;\n      calculateBiasAndR(\n        component_concentrations_tmp,\n        feature_name,\n        transformation_model,\n        optimized_params,\n        biases,\n        correlation_coefficient);\n\n      rsq_tmp.push_back(correlation_coefficient);\n    }\n    return max_element(rsq_tmp.begin(), rsq_tmp.end()) - rsq_tmp.begin();\n  }\n\n  int AbsoluteQuantitation::residualOutlierCandidate_(\n    const std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations,\n    const String & feature_name,\n    const String & transformation_model,\n    const Param & transformation_model_params)\n  {\n    // Returns candidate outlier: A linear regression and residuals are calculated for\n    // the data points. The one with highest residual error is selected as the outlier candidate. The\n    // corresponding iterator position is then returned.\n\n    // fit the model\n    Param optimized_params = fitCalibration(component_concentrations,\n      feature_name,\n      transformation_model,\n      transformation_model_params);\n\n    // calculate the R2 and bias\n    std::vector<double> biases;\n    double correlation_coefficient = 0.0;\n    calculateBiasAndR(\n      component_concentrations,\n      feature_name,\n      transformation_model,\n      optimized_params,\n      biases,\n      correlation_coefficient);\n\n    return max_element(biases.begin(), biases.end()) - biases.begin();\n  }\n\n  void AbsoluteQuantitation::optimizeCalibrationCurves(\n    std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>> & components_concentrations)\n  {\n    std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>>& cc = components_concentrations;\n    for (std::pair<const String, AbsoluteQuantitationMethod>& quant_method : quant_methods_)\n    {\n      const String& component_name = quant_method.first;\n      AbsoluteQuantitationMethod& component_aqm = quant_method.second;\n      if (cc.count(component_name) && optimization_method_ == \"iterative\")\n      {\n        // optimize the calibration curve for the component\n        Param optimized_params;\n        bool optimal_calibration_found = optimizeCalibrationCurveIterative(\n          cc[component_name],\n          component_aqm.getFeatureName(),\n          component_aqm.getTransformationModel(),\n          component_aqm.getTransformationModelParams(),\n          optimized_params);\n\n        // order component concentrations and update the lloq and uloq\n        std::vector<AbsoluteQuantitationStandards::featureConcentration>::const_iterator it;\n        it = std::min_element(cc[component_name].begin(), cc[component_name].end(), [](\n            const AbsoluteQuantitationStandards::featureConcentration& lhs,\n            const AbsoluteQuantitationStandards::featureConcentration& rhs\n          )\n          {\n            return lhs.actual_concentration < rhs.actual_concentration;\n          }\n        );\n        component_aqm.setLLOQ(it->actual_concentration);\n        it = std::max_element(cc[component_name].begin(), cc[component_name].end(), [](\n            const AbsoluteQuantitationStandards::featureConcentration& lhs,\n            const AbsoluteQuantitationStandards::featureConcentration& rhs\n          )\n          {\n            return lhs.actual_concentration < rhs.actual_concentration;\n          }\n        );\n        component_aqm.setULOQ(it->actual_concentration);\n\n        if (optimal_calibration_found)\n        {\n          // calculate the R2 and bias\n          std::vector<double> biases;\n          double correlation_coefficient = 0.0;\n          calculateBiasAndR(\n            cc[component_name],\n            component_aqm.getFeatureName(),\n            component_aqm.getTransformationModel(),\n            optimized_params,\n            biases,\n            correlation_coefficient);\n\n          // record the updated information\n          component_aqm.setCorrelationCoefficient(correlation_coefficient);\n          component_aqm.setTransformationModelParams(optimized_params);\n          component_aqm.setNPoints(cc[component_name].size());\n        }\n        else \n        {\n          component_aqm.setCorrelationCoefficient(0.0);\n          component_aqm.setNPoints(0);\n          component_aqm.setLLOQ(0.0);\n          component_aqm.setULOQ(0.0);\n        }\n      }\n      else if (optimization_method_ != \"iterative\")\n      {\n        throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,\n          \"Unsupported calibration curve optimization method '\" + optimization_method_ + \"'.\");\n      }\n      else\n      {\n        OPENMS_LOG_DEBUG << \"Warning: Standards not found for component \" << component_name << \".\";\n      }\n    }\n  }\n\n  void AbsoluteQuantitation::optimizeSingleCalibrationCurve(\n    const String& component_name,\n    std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations\n  )\n  {\n    std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>> cc_map;\n    cc_map.insert({component_name, component_concentrations});\n    optimizeCalibrationCurves(cc_map);\n    component_concentrations = cc_map.at(component_name);\n  }\n} // namespace\n", "meta": {"hexsha": "70a15cf3b76882da6875cc3a6b6cb140dc683c4a", "size": 29826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/ANALYSIS/QUANTITATION/AbsoluteQuantitation.cpp", "max_stars_repo_name": "noraw61/OpenMS", "max_stars_repo_head_hexsha": "cc53479aceb6f0adebe2178913a24b86fbe538f8", "max_stars_repo_licenses": ["BSL-1.0", "Zlib", "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/openms/source/ANALYSIS/QUANTITATION/AbsoluteQuantitation.cpp", "max_issues_repo_name": "noraw61/OpenMS", "max_issues_repo_head_hexsha": "cc53479aceb6f0adebe2178913a24b86fbe538f8", "max_issues_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-10-29T20:59:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T15:37:14.000Z", "max_forks_repo_path": "src/openms/source/ANALYSIS/QUANTITATION/AbsoluteQuantitation.cpp", "max_forks_repo_name": "noraw61/OpenMS", "max_forks_repo_head_hexsha": "cc53479aceb6f0adebe2178913a24b86fbe538f8", "max_forks_repo_licenses": ["BSL-1.0", "Zlib", "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.1271186441, "max_line_length": 209, "alphanum_fraction": 0.696305237, "num_tokens": 6365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.16943946553583702}}
{"text": "/* Copyright (c) 2012 Cheese and Bacon Games, LLC */\n/* This file is licensed under the MIT License. */\n/* See the file docs/LICENSE.txt for the full license text. */\n\n#include \"special_info.h\"\n#include \"world.h\"\n\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\n\nGPS_Altitude::GPS_Altitude(){\n    interval=0.25;\n    rows=721;\n    columns=1440;\n}\n\nvoid GPS_Altitude::setup(){\n    if(!is_setup()){\n        File_IO_Binary_Load load(\"data/egm96/WW15MGH.DAC\");\n\n        if(load.file_loaded()){\n            string egm96_data=load.get_data();\n\n            for(size_t i=0;i<egm96_data.length();i+=2){\n                if(i+1<egm96_data.length()){\n                    int16_t number=(egm96_data[i]<<8)|(egm96_data[i+1]&0xff);\n\n                    egm96_nums.push_back(number);\n                }\n            }\n        }\n    }\n}\n\nvoid GPS_Altitude::stop(){\n    egm96_nums.clear();\n}\n\nbool GPS_Altitude::is_setup(){\n    return egm96_nums.size()!=0;\n}\n\ndouble GPS_Altitude::get_offset(double gps_latitude,double gps_longitude){\n    double latitude=gps_latitude;\n    double longitude=gps_longitude>=0.0 ? gps_longitude : gps_longitude+360.0;\n\n    int top_row=(int)((90.0-latitude)/interval);\n    if(latitude<=-90.0){\n        top_row=rows-2;\n    }\n    int bottom_row=top_row+1;\n\n    int left_column=(int)(longitude/interval);\n    int right_column=left_column+1;\n    if(longitude>=360.0-interval){\n        left_column=columns-1;\n        right_column=0;\n    }\n\n    double latitude_top=90.0-top_row*interval;\n    double longitude_left=left_column*interval;\n\n    double ul=game.world.gps_altitude.get_post_offset(top_row,left_column);\n    double ll=game.world.gps_altitude.get_post_offset(bottom_row,left_column);\n    double lr=game.world.gps_altitude.get_post_offset(bottom_row,right_column);\n    double ur=game.world.gps_altitude.get_post_offset(top_row,right_column);\n\n    double u=(longitude-longitude_left)/interval;\n    double v=(latitude_top-latitude)/interval;\n\n    double pll=(1.0-u)*(1.0-v);\n    double plr=u*(1.0-v);\n    double pur=u*v;\n    double pul=(1.0-u)*v;\n\n    //meters\n    return (pll*ll+plr*lr+pur*ur+pul*ul)/100.0;\n}\n\ndouble GPS_Altitude::get_post_offset(int row,int column){\n    int k=row*columns+column;\n\n    if(k<egm96_nums.size()){\n        return egm96_nums[k];\n    }\n    else{\n        return 0.0;\n    }\n}\n\nstring Special_Info::get_sensor_string(string sensor_name){\n    string text=\"\";\n\n    if(android.get_sensor_availability(sensor_name)){\n        if(android.get_sensor_state(sensor_name)){\n            float sensor_values[SENSOR_VALUES_MAX];\n            android.get_sensor_values(sensor_name,sensor_values);\n\n            string sensor_value_labels[SENSOR_VALUES_MAX];\n            android.get_sensor_value_labels(sensor_name,sensor_value_labels);\n\n            int sensor_value_count=android.get_sensor_value_count(sensor_name);\n\n            for(int i=0;i<sensor_value_count;i++){\n                string label=\"\";\n                if(sensor_value_labels[i].length()>0){\n                    label=sensor_value_labels[i]+\": \";\n                }\n\n                text+=label+Strings::num_to_string(sensor_values[i])+\" \"+android.get_sensor_units(sensor_name);\n\n                if(i<sensor_value_count-1){\n                    text+=\"\\n\";\n                }\n            }\n        }\n        else{\n            text+=\"Sensor offline\";\n        }\n    }\n    else{\n        text+=\"Sensor unavailable\";\n    }\n\n    return text;\n}\n\nstring Special_Info::get_special_info_text(string special_info){\n    string text=\"\";\n\n    if(special_info.length()>0){\n        if(special_info==\"configure_command\"){\n            if(engine_interface.configure_command!=-1 && engine_interface.configure_command<engine_interface.game_commands.size()){\n                text+=\"Inputs currently bound to \\\"\"+engine_interface.game_commands[engine_interface.configure_command].title+\"\\\":\"+\"\\n\\n\";\n\n                const char* ckey=SDL_GetScancodeName(engine_interface.game_commands[engine_interface.configure_command].key);\n                const char* cbutton=SDL_GameControllerGetStringForButton(engine_interface.game_commands[engine_interface.configure_command].button);\n                const char* caxis=SDL_GameControllerGetStringForAxis(engine_interface.game_commands[engine_interface.configure_command].axis);\n\n                bool allow_keys_and_buttons=true;\n                bool allow_axes=true;\n                if(caxis!=0 && engine_interface.game_commands[engine_interface.configure_command].axis!=SDL_CONTROLLER_AXIS_INVALID){\n                    allow_keys_and_buttons=false;\n                }\n                else{\n                    allow_axes=false;\n                }\n\n                if(allow_keys_and_buttons){\n                    text+=\"Keyboard Key: \";\n                    if(ckey!=0 && engine_interface.game_commands[engine_interface.configure_command].key!=SDL_SCANCODE_UNKNOWN){\n                        text+=Strings::first_letter_capital(ckey);\n                    }\n                    else{\n                        text+=\"<NOT SET>\";\n                    }\n                    text+=\"\\n\\n\";\n\n                    text+=\"Controller Button: \";\n                    if(cbutton!=0 && engine_interface.game_commands[engine_interface.configure_command].button!=SDL_CONTROLLER_BUTTON_INVALID){\n                        text+=Strings::first_letter_capital(cbutton);\n                    }\n                    else{\n                        text+=\"<NOT SET>\";\n                    }\n                    text+=\"\\n\\n\";\n                }\n\n                if(allow_axes){\n                    text+=\"Controller Axis: \";\n                    if(caxis!=0 && engine_interface.game_commands[engine_interface.configure_command].axis!=SDL_CONTROLLER_AXIS_INVALID){\n                        text+=Strings::first_letter_capital(caxis);\n                    }\n                    else{\n                        text+=\"<NOT SET>\";\n                    }\n                    text+=\"\\n\\n\";\n                }\n            }\n        }\n        else if(special_info==\"scan_acceleration\"){\n            text+=get_sensor_string(\"accelerometer\");\n            text+=\"\\n\\n\";\n\n            text+=get_sensor_string(\"gravity\");\n            text+=\"\\n\\n\";\n\n            text+=get_sensor_string(\"linear_acceleration\");\n            text+=\"\\n\\n\";\n        }\n        else if(special_info==\"scan_environment\"){\n            text+=get_sensor_string(\"ambient_temperature\");\n            text+=\"\\n\\n\";\n\n            text+=get_sensor_string(\"pressure\");\n            text+=\"\\n\\n\";\n\n            text+=get_sensor_string(\"light\");\n            text+=\"\\n\\n\";\n\n            text+=get_sensor_string(\"relative_humidity\");\n            text+=\"\\n\\n\";\n\n            if(android.get_sensor_availability(\"ambient_temperature\") && android.get_sensor_state(\"ambient_temperature\") &&\n               android.get_sensor_availability(\"relative_humidity\") && android.get_sensor_state(\"relative_humidity\")){\n                float sensor_values[SENSOR_VALUES_MAX];\n\n                android.get_sensor_values(\"ambient_temperature\",sensor_values);\n                float ambient_temperature=sensor_values[0];\n\n                android.get_sensor_values(\"relative_humidity\",sensor_values);\n                float relative_humidity=sensor_values[0];\n\n                float m=17.62f;\n                float tn=243.12f;\n\n                float a=6.112f;\n                float absolute_humidity=216.7f*(((relative_humidity/100.0f)*a*exp((m*ambient_temperature)/(tn+ambient_temperature)))/(273.15f+ambient_temperature));\n\n                float numerator=log(relative_humidity/100.0f)+(m*ambient_temperature)/(tn+ambient_temperature);\n                float dewpoint=tn*(numerator/(m-numerator));\n\n                text+=\"Dew point: \"+Strings::num_to_string(dewpoint)+\" \"+Symbols::degrees()+\"C\\n\\n\";\n\n                text+=\"Absolute ambient humidity: \"+Strings::num_to_string(absolute_humidity)+\" g/m\"+Symbols::cubed()+\"\\n\\n\";\n            }\n            else{\n                text+=\"Dew point and absolute ambient humidity could not be calculated\\n\\n\";\n            }\n        }\n        else if(special_info==\"scan_magnetic\"){\n            text+=get_sensor_string(\"magnetic_field\");\n            text+=\"\\n\\n\";\n        }\n        else if(special_info==\"scan_rotation\"){\n            text+=get_sensor_string(\"gyroscope\");\n            text+=\"\\n\\n\";\n\n            text+=\"Rotation vector (gyroscope):\\n\";\n            text+=get_sensor_string(\"rotation_vector\");\n            text+=\"\\n\\n\";\n\n            text+=\"Geomagnetic rotation vector (magnetometer):\\n\";\n            text+=get_sensor_string(\"geomagnetic_rotation_vector\");\n            text+=\"\\n\\n\";\n        }\n        else if(special_info==\"scan_other\"){\n            text+=get_sensor_string(\"proximity\");\n            text+=\"\\n\\n\";\n\n            text+=get_sensor_string(\"step_counter\");\n            text+=\"\\n\\n\";\n        }\n        else if(special_info==\"scan_position\"){\n            if(android.get_sensor_availability(\"pressure\") && android.get_sensor_state(\"pressure\")){\n                float sensor_values[SENSOR_VALUES_MAX];\n\n                android.get_sensor_values(\"pressure\",sensor_values);\n                //pascals\n                float pressure=sensor_values[0]*100.0f;\n\n                //pascals\n                float base_pressure=101325.0f;\n                //kelvin\n                float base_temperature=288.15f;\n                //meters/second^2\n                float acceleration_due_to_gravity=9.80665f;\n                //kelvin/meter\n                float lapse_rate=-0.0065f;\n                //joules/(kilogram*kelvin)\n                float gas_constant_for_air=287.053f;\n                //meters\n                float altitude=(base_temperature/lapse_rate)*(pow((pressure/base_pressure),-lapse_rate*gas_constant_for_air/acceleration_due_to_gravity)-1.0f);\n\n                text+=\"Altitude (calculated from pressure): \"+Strings::num_to_string(altitude)+\" m\\n\\n\";\n            }\n            else{\n                text+=\"Altitude could not be calculated from pressure\\n\\n\";\n            }\n\n            if(android.get_gps_availability()){\n                if(android.get_gps_accessibility()){\n                    if(android.get_gps_state()){\n                        Android_GPS gps_data=android.get_gps_readout();\n\n                        if(game.world.gps_altitude.is_setup()){\n                            double offset=game.world.gps_altitude.get_offset(gps_data.latitude,gps_data.longitude);\n\n                            text+=\"Altitude (calculated from GPS): \"+Strings::num_to_string(gps_data.altitude)+\" \"+Android_GPS::UNITS_ALTITUDE+\"\\n\\n\";\n                            text+=\"Altitude (calculated from GPS, adjusted to MSL): \"+Strings::num_to_string(gps_data.altitude+offset)+\" \"+Android_GPS::UNITS_ALTITUDE+\"\\n\\n\";\n                        }\n                        else{\n                            text+=\"Altitude could not be calculated from GPS\\n\\n\";\n                        }\n\n                        text+=\"Latitude: \"+Strings::num_to_string(gps_data.latitude)+Android_GPS::UNITS_LATITUDE+\"\\n\\n\";\n                        text+=\"Longitude: \"+Strings::num_to_string(gps_data.longitude)+Android_GPS::UNITS_LONGITUDE+\"\\n\\n\";\n                        text+=\"Bearing: \"+Strings::num_to_string(gps_data.bearing)+Android_GPS::UNITS_BEARING+\"\\n\\n\";\n                        text+=\"Speed: \"+Strings::num_to_string(gps_data.speed)+\" \"+Android_GPS::UNITS_SPEED+\"\\n\\n\";\n                        text+=\"GPS accuracy: \"+Strings::num_to_string(gps_data.accuracy)+\" \"+Android_GPS::UNITS_ACCURACY+\"\\n\\n\";\n                    }\n                    else{\n                        text+=\"GPS offline\\n\\n\";\n                    }\n                }\n                else{\n                    text+=\"GPS inaccessible\\n\\n\";\n                }\n            }\n            else{\n                text+=\"GPS unavailable\\n\\n\";\n            }\n        }\n        else{\n            Log::add_error(\"Invalid special info text: '\"+special_info+\"'\");\n        }\n    }\n\n    return text;\n}\n\nstring Special_Info::get_special_info_sprite(string special_info){\n    string str_sprite_name=\"\";\n\n    if(special_info.length()>0){\n        if(special_info==\"example\"){\n            str_sprite_name=\"\";\n        }\n        else{\n            Log::add_error(\"Invalid special info sprite: '\"+special_info+\"'\");\n        }\n    }\n\n    return str_sprite_name;\n}\n", "meta": {"hexsha": "e91290d0661491237a8cf08d8c11506a56bf6099", "size": 12337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "special_info.cpp", "max_stars_repo_name": "darkoppressor/scanner", "max_stars_repo_head_hexsha": "c174b95fd5afbf1b54673aad0d9da950727d348f", "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": "special_info.cpp", "max_issues_repo_name": "darkoppressor/scanner", "max_issues_repo_head_hexsha": "c174b95fd5afbf1b54673aad0d9da950727d348f", "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": "special_info.cpp", "max_forks_repo_name": "darkoppressor/scanner", "max_forks_repo_head_hexsha": "c174b95fd5afbf1b54673aad0d9da950727d348f", "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": 36.6083086053, "max_line_length": 174, "alphanum_fraction": 0.5697495339, "num_tokens": 2568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.16943946553583702}}
{"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#ifndef METRO_REGRESSION_FIT_MODEL_HPP\n#define METRO_REGRESSION_FIT_MODEL_HPP\n\n#include <string>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include \"boost/function.hpp\"\n#include \"metro/ModifiedCholesky.hpp\"\n#include \"metro/SmoothFunction.hpp\"\n\nnamespace metro {\n\tstruct Stepper {\n\tpublic:\n\t\ttypedef SmoothFunction Function ;\n\t\ttypedef Eigen::VectorXd Vector ;\n\t\ttypedef Eigen::MatrixXd Matrix ;\n\t\ttypedef boost::function<\n\t\t\tvoid(\n\t\t\t\tint iteration,\n\t\t\t\tdouble ll,\n\t\t\t\tdouble target_ll,\n\t\t\t\tVector const& point,\n\t\t\t\tVector const& derivative,\n\t\t\t\tVector const& step,\n\t\t\t\tbool converged \n\t\t\t)\n\t\t> Tracer ;\n\tpublic:\n\t\tvirtual ~Stepper() ;\n\t\tvirtual bool diverged() const = 0 ;\n\t\tvirtual bool step( Function& function, Vector* result ) = 0 ;\n\t\tvirtual std::size_t number_of_iterations() const = 0 ;\n\t} ;\n\n\tstd::pair< bool, int > fit_model(\n\t\tmetro::SmoothFunction& ll,\n\t\tstd::string const& model_name,\n\t\tEigen::VectorXd const& starting_point,\n\t\tStepper& stopping_condition,\n\t\tstd::vector< std::string >* comments\n\t) ;\n}\n\n#endif\n", "meta": {"hexsha": "8db80ff9a5064b8101722f0c913a32b080fc95a0", "size": 1264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/fit_model.hpp", "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/include/metro/fit_model.hpp", "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/include/metro/fit_model.hpp", "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": 24.3076923077, "max_line_length": 63, "alphanum_fraction": 0.7056962025, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.2658804789168741, "lm_q1q2_score": 0.16937405272124106}}
{"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) 2007-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#ifndef BOOST_UNITS_ANGLE_GRADIAN_BASE_UNIT_HPP\r\n#define BOOST_UNITS_ANGLE_GRADIAN_BASE_UNIT_HPP\r\n\r\n#include <boost/units/conversion.hpp>\r\n#include <boost/units/base_units/angle/radian.hpp>\r\n\r\nBOOST_UNITS_DEFINE_BASE_UNIT_WITH_CONVERSIONS(angle,gradian,\"gradian\",\"grad\",6.28318530718/400.,boost::units::angle::radian_base_unit,-102);\r\n\r\n#if BOOST_UNITS_HAS_BOOST_TYPEOF\r\n\r\n#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()\r\n\r\nBOOST_TYPEOF_REGISTER_TYPE(boost::units::angle::gradian_base_unit)\r\n\r\n#endif\r\n\r\n#endif // BOOST_UNITS_ANGLE_GRADIAN_BASE_UNIT_HPP\r\n", "meta": {"hexsha": "487174a732208727f1a34fb5bf8fad85a6f256b5", "size": 950, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/units/base_units/angle/gradian.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/units/base_units/angle/gradian.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/units/base_units/angle/gradian.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.9285714286, "max_line_length": 141, "alphanum_fraction": 0.7873684211, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.16926798111905897}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n#include <iomanip>\n#include <string.h>\nusing boost::multiprecision::cpp_int;\nusing namespace std;\nint main()\n{\n\tcpp_int n = 123456789;\n\tcpp_int n1 = n;\n\tint i,j,k,len;\n\tstring str;\n\tint x = 5;\n\tfor(i=0;i<1000;i++)\n\t{\n\t   std::string str = boost::lexical_cast<std::string>(n);\n\t   len = str.length();\n\t  \n\t   for(j=0;j<len;j++)\n\t   {\n\t   \t if(j<(len-9) && j==(len-x))\n\t   \t {\n\t   \t \t\n\t   \t \tif(str[j]=='9' && str[j+1]=='3')\n\t   \t \t{\n                if(str[j+8]=='8' && str[j+9] == '6')\n                {\n                    printf(\"Indira's Number = \");\n                \tfor(k=0;k<10;k++)\n                \t{\n                \t\tcout<<\"\"<<str[j+k];\n\t\t\t\t\t}\n                        \n\t\t\t\t}\n                    \n\t\t\t}\n\t   \t\n\t  }   \n\t   \n\t}\n\tn*=n1;\n\tx = x+5;\n}\n\treturn 0;\n}\n", "meta": {"hexsha": "a454a4c3d428ac1024936e1c69fa96f58029edc2", "size": 862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++ Codes/no_brains.cpp", "max_stars_repo_name": "moit-bytes/Coding-Club", "max_stars_repo_head_hexsha": "2d5d7402c661c5fbe25cc037ffd7406be8e5a6af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-23T02:55:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T02:55:23.000Z", "max_issues_repo_path": "C++ Codes/no_brains.cpp", "max_issues_repo_name": "moit-bytes/Coding-Club", "max_issues_repo_head_hexsha": "2d5d7402c661c5fbe25cc037ffd7406be8e5a6af", "max_issues_repo_licenses": ["MIT"], "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++ Codes/no_brains.cpp", "max_forks_repo_name": "moit-bytes/Coding-Club", "max_forks_repo_head_hexsha": "2d5d7402c661c5fbe25cc037ffd7406be8e5a6af", "max_forks_repo_licenses": ["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.3404255319, "max_line_length": 58, "alphanum_fraction": 0.4315545244, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1692679776587329}}
{"text": "#include \"AvatarOptimizer.h\"\n\n#include <Eigen/StdVector>\n#include <atomic>\n#include <boost/thread.hpp>\n#include <ceres/ceres.h>\n#include <iostream>\n#include <mutex>\n#include <nanoflann.hpp>\n#include <thread>\n#include <vector>\n\n#include \"Avatar.h\"\n#include \"AvatarRenderer.h\"\n#include \"Util.h\"\n#include \"Version.h\"\n\n// #define PCL_DEBUG_VISUALIZE\n\n#ifndef OPENARK_PCL_ENABLED\n// If PCL not available then cannot visualize\n#undef PCL_DEBUG_VISUALIZE\n#endif\n\n#ifdef PCL_DEBUG_VISUALIZE\n#include <pcl/visualization/pcl_visualizer.h>\n#endif\n\n#define BEGIN_PROFILE  // auto start = std::chrono::high_resolution_clock::now()\n#define PROFILE( \\\n    x)  // do{printf(\"%s: %f ms\\n\", #x, std::chrono::duration<double,\n        // std::milli>(std::chrono::high_resolution_clock::now() -\n        // start).count()); start =\n        // std::chrono::high_resolution_clock::now(); }while(false)\n\n// Uncomment below line to compare analytic diff results to auto diff\n//#define TEST_COMPARE_AUTO_DIFF\n\nnamespace nanoflann {\n/// KD-tree adaptor for working with data directly stored in a column-major\n/// Eigen Matrix, without duplicating the data storage. This code is adapted\n/// from the KDTreeEigenMatrixAdaptor class of nanoflann.hpp\ntemplate <class MatrixType, int DIM = -1,\n          class Distance = nanoflann::metric_L2_Simple,\n          typename IndexType = int>\nstruct KDTreeEigenColMajorMatrixAdaptor {\n    typedef KDTreeEigenColMajorMatrixAdaptor<MatrixType, DIM, Distance> self_t;\n    typedef typename MatrixType::Scalar num_t;\n    typedef\n        typename Distance::template traits<num_t, self_t>::distance_t metric_t;\n    typedef KDTreeSingleIndexAdaptor<metric_t, self_t, DIM, IndexType> index_t;\n    index_t *index;\n    KDTreeEigenColMajorMatrixAdaptor(const MatrixType &mat,\n                                     const int leaf_max_size = 10)\n        : m_data_matrix(mat) {\n        const size_t dims = mat.rows();\n        index = new index_t(\n            dims, *this,\n            nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size));\n        index->buildIndex();\n    }\n    ~KDTreeEigenColMajorMatrixAdaptor() { delete index; }\n    const MatrixType &m_data_matrix;\n    /// Query for the num_closest closest points to a given point (entered as\n    /// query_point[0:dim-1]).\n    inline void query(const num_t *query_point, const size_t num_closest,\n                      IndexType *out_indices, num_t *out_distances_sq) const {\n        nanoflann::KNNResultSet<typename MatrixType::Scalar, IndexType>\n            resultSet(num_closest);\n        resultSet.init(out_indices, out_distances_sq);\n        index->findNeighbors(resultSet, query_point, nanoflann::SearchParams());\n    }\n    /// Query for the closest points to a given point (entered as\n    /// query_point[0:dim-1]).\n    inline IndexType closest(const num_t *query_point) const {\n        IndexType out_indices;\n        num_t out_distances_sq;\n        query(query_point, 1, &out_indices, &out_distances_sq);\n        return out_indices;\n    }\n    const self_t &derived() const { return *this; }\n    self_t &derived() { return *this; }\n    inline size_t kdtree_get_point_count() const {\n        return m_data_matrix.cols();\n    }\n    /// Returns the distance between the vector \"p1[0:size-1]\" and the data\n    /// point with index \"idx_p2\" stored in the class:\n    inline num_t kdtree_distance(const num_t *p1, const size_t idx_p2,\n                                 size_t size) const {\n        num_t s = 0;\n        for (size_t i = 0; i < size; i++) {\n            const num_t d = p1[i] - m_data_matrix.coeff(i, idx_p2);\n            s += d * d;\n        }\n        return s;\n    }\n    /// Returns the dim'th component of the idx'th point in the class:\n    inline num_t kdtree_get_pt(const size_t idx, int dim) const {\n        return m_data_matrix.coeff(dim, idx);\n    }\n    /// Optional bounding-box computation: return false to default to a standard\n    /// bbox computation loop.\n    template <class BBOX>\n    bool kdtree_get_bbox(BBOX &) const {\n        return false;\n    }\n};\n}  // namespace nanoflann\n\nnamespace ceres {\n/** WHY THIS? For our use case it is desirable to pre-compute the full Jacobian\n * at an earlier stage but make use of the special addition operator for local\n * parameterization. This is because some Jacobians are easier to compute wrt\n * the local 'error' vector than the state. This is a known Ceres limitation,\n * see\n * https://groups.google.com/forum/#!msg/ceres-solver/fs8iNI9_F7Q/gv0R4NGLAwAJ\n *  Here, we set Jacobian to a dummy identity matrix, as suggested by a post on\n * that page. The local Jacobian is multiplied manually in\n * AvatarEvaluationCommonData where required. */\nclass FakeQuaternionParameterization : public ceres::LocalParameterization {\n   public:\n    ~FakeQuaternionParameterization() {}\n    bool Plus(const double *x_ptr, const double *delta,\n              double *x_plus_delta_ptr) const {\n        // Copied from EigenQuaternionParameterization\n        Eigen::Map<Eigen::Quaterniond> x_plus_delta(x_plus_delta_ptr);\n        Eigen::Map<const Eigen::Quaterniond> x(x_ptr);\n\n        const double norm_delta = sqrt(\n            delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2]);\n        if (norm_delta > 0.0) {\n            const double sin_delta_by_delta = sin(norm_delta) / norm_delta;\n\n            // Note, in the constructor w is first.\n            Eigen::Quaterniond delta_q(\n                cos(norm_delta), sin_delta_by_delta * delta[0],\n                sin_delta_by_delta * delta[1], sin_delta_by_delta * delta[2]);\n            x_plus_delta = delta_q * x;\n        } else {\n            x_plus_delta = x;\n        }\n        return true;\n    }\n    bool ComputeJacobian(const double *x, double *jacobian) const {\n        Eigen::Map<Eigen::Matrix<double, 4, 3, Eigen::RowMajor>> J(jacobian);\n        J.topLeftCorner<3, 3>().setIdentity();\n        J.bottomRows<1>().setZero();\n        return true;\n    }\n    int GlobalSize() const { return 4; }\n    int LocalSize() const { return 3; }\n};\n}  // namespace ceres\n\nnamespace ark {\nnamespace {\nusing MatAlloc = Eigen::aligned_allocator<Eigen::Matrix3d>;\nusing VecAlloc = Eigen::aligned_allocator<Eigen::Vector3d>;\n\n/** Evaluation callback for Ceres */\ntemplate <class Cache>\nstruct AvatarEvaluationCommonData : public ceres::EvaluationCallback {\n    /** Max number of joint assignments to consider for each joint */\n    static const int MAX_ASSIGN = 4;\n\n    /** If true, will recalculate shape every update */\n    const bool shapeEnabled;\n\n    AvatarEvaluationCommonData(AvatarOptimizer &opt, bool shape_enabled = false)\n        : opt(opt),\n          ava(opt.ava),\n          numJointSpaces(opt.ava.model.numJoints() + 1),\n          shapeEnabled(shape_enabled) {\n        // _L.resize(nJoints * AvatarOptimizer::ROT_SIZE);\n        localJacobian.resize(numJointSpaces);\n        if (shape_enabled) {\n            S.resize(ava.model.numJoints());\n            Sp.resize(ava.model.numJoints());\n            H.resize(ava.model.numJoints());\n        }\n        _R.resize(numJointSpaces * numJointSpaces);\n        _t.resize(_R.size());\n        shapedCloud.resize(3, ava.model.numPoints());\n\n        CalcShape();\n\n        // Make a list of deduplicated ancestor joints for each point\n        ancestor.resize(ava.model.numPoints());\n        for (int point = 0; point < ava.model.numPoints(); ++point) {\n            auto &ances = ancestor[point];\n            for (auto &weight_joint : ava.model.assignedJoints[point]) {\n                double weight = weight_joint.first;\n                int joint = weight_joint.second;\n                ances.emplace_back(joint, joint, weight);\n                for (int j = ava.model.parent[joint]; j != -1;\n                     j = ava.model.parent[j]) {\n                    ances.emplace_back(j, joint, weight);\n                }\n            }\n            std::sort(ances.begin(), ances.end());\n            int last = 0;\n            for (size_t i = 1; i < ances.size(); ++i) {\n                if (ances[last].jid == ances[i].jid) {\n                    ances[last].merge(ances[i]);\n                } else {\n                    ++last;\n                    if (last < i) {\n                        ances[last] = std::move(ances[i]);\n                    }\n                }\n            }\n            ances.resize(last + 1);\n        }\n\n        if (shape_enabled) {\n            for (int j = 0; j < ava.model.numJoints(); ++j) {\n                Sp[j].resize(3, ava.model.numShapeKeys());\n                S[j].resize(3, ava.model.numShapeKeys());\n                H[j].resize(3, ava.model.numShapeKeys());\n            }\n\n            if (ava.model.useJointShapeRegressor) {\n                for (int j = 0; j < ava.model.numJoints(); ++j) {\n                    S[j].noalias() =\n                        ava.model.jointShapeReg.middleRows<3>(3 * j);\n                }\n            } else {\n                for (int i = 0; i < ava.model.numShapeKeys(); ++i) {\n                    Eigen::MatrixXd::Scalar d;\n                    Eigen::Map<const CloudType> keyCloud(\n                        ava.model.keyClouds.data() +\n                            i * ava.model.numPoints() * 3,\n                        3, ava.model.numPoints());\n                    for (int j = 0; j < ava.model.numJoints(); ++j) {\n                        S[j].col(i).noalias() =\n                            keyCloud * ava.model.jointRegressor.col(j);\n                    }\n                }\n            }\n            for (int j = 1; j < ava.model.numJoints(); ++j) {\n                if (j) Sp[j].noalias() = S[j] - S[ava.model.parent[j]];\n            }\n            Sp[0].setZero();\n            H[0].setZero();\n        }\n    }\n\n    /** Compute joint and point positions after applying shape keys*/\n    void CalcShape() {\n        Eigen::Map<Eigen::VectorXd> shapedCloudVec(shapedCloud.data(),\n                                                   3 * shapedCloud.cols());\n\n        /** Apply shape keys */\n        shapedCloudVec.noalias() =\n            ava.model.keyClouds * ava.w + ava.model.baseCloud;\n\n        /** Apply joint [shape] regressor */\n        // TODO: use dense joint regressor with compressed cloud\n        if (ava.model.useJointShapeRegressor) {\n            jointPosInit.resize(3, ava.model.numJoints());\n            Eigen::Map<Eigen::VectorXd> jointPosVec(jointPosInit.data(),\n                                                    3 * ava.model.numJoints());\n            jointPosVec.noalias() =\n                ava.model.jointShapeRegBase + ava.model.jointShapeReg * ava.w;\n        } else {\n            jointPosInit.noalias() = shapedCloud * ava.model.jointRegressor;\n        }\n\n        /** Ensure root is at origin*/\n        Eigen::Vector3d offset = jointPosInit.col(0);\n        shapedCloud.colwise() -= offset;\n        jointPosInit.colwise() -= offset;\n\n        /** Find relative positions of each joint */\n        jointVecInit.noalias() = jointPosInit;\n        for (int i = ava.model.numJoints() - 1; i >= 1; --i) {\n            jointVecInit.col(i).noalias() -=\n                jointVecInit.col(ava.model.parent[i]);\n        }\n        shapeComputed = true;\n    }\n\n    void PrepareForEvaluation(bool evaluate_jacobians,\n                              bool new_evaluation_point) final {\n        // std::cerr << \"PREP \" << evaluate_jacobians << \", \" <<\n        // new_evaluation_point << \"\\n\";\n        if (new_evaluation_point) {\n            // BEGIN_PROFILE;\n            if (shapeEnabled || !shapeComputed) CalcShape();\n            // PROFILE(CalcShape);\n            jointVecInit.col(0).noalias() = ava.p;\n\n            for (int i = 0; i < numJointSpaces - 1; ++i) {\n                // double * jacobian = localJacobian[i].data();\n                auto &x = opt.r[i].coeffs();\n                /** Jacobian of local parameterization '+' function at 0 */\n                localJacobian[i] << x(3), x(2), -x(1), -x(2), x(3), x(0), x(1),\n                    -x(0), x(3), -x(0), -x(1), -x(2);\n            }\n            // PROFILE(lojac);\n\n            // Compute relative rotations and translations\n            R(-1, -1).setIdentity();  // -1 means 'to global'\n            t(-1, -1).setZero();\n            for (int i = 0; i < numJointSpaces - 1; ++i) {\n                R(i, i).setIdentity();\n                Eigen::Matrix3d rot = opt.r[i].toRotationMatrix();\n                t(i, i).setZero();\n                int p = ava.model.parent[i];\n                for (int j = p;; j = ava.model.parent[j]) {\n                    R(j, i).noalias() = R(j, p) * rot;\n                    t(j, i).noalias() = R(j, p) * jointVecInit.col(i) + t(j, p);\n                    if (j == -1) break;\n                }\n            }\n            // PROFILE(RT);\n\n            if (shapeEnabled) {\n                // Compute joint-to-parent accumulated shape differences\n                for (int j = 1; j < numJointSpaces - 1; ++j) {\n                    H[j].noalias() = R(-1, ava.model.parent[j]) * Sp[j] +\n                                     H[ava.model.parent[j]];\n                }\n            }\n            // PROFILE(H);\n\n            std::atomic<size_t> cacheId(0);\n            auto worker = [evaluate_jacobians, &cacheId, this](int workerId) {\n                size_t workerCacheId;\n                while (true) {\n                    workerCacheId = cacheId++;\n                    if (workerCacheId >= caches.size()) break;\n                    caches[workerCacheId].updateData(evaluate_jacobians);\n                }\n            };\n\n            std::vector<std::thread> threadPool;\n            for (int i = 0; i < numThreads; ++i) {\n                threadPool.emplace_back(worker, i);\n            }\n            for (auto &thread : threadPool) {\n                thread.join();\n            }\n            // PROFILE(Caches);\n            // PROFILE(ALL Prepare);\n        }\n    }\n\n    /** Joint-to-ancestor joint rotation (j_ances=-1 is global) */\n    inline Eigen::Matrix3d &R(int j_ancestor, int j) {\n        return _R[numJointSpaces * (j_ancestor + 1) + j + 1];\n    }\n    /** Joint-to-ancestor joint relative position (j_ances=-1 is global) */\n    inline Eigen::Vector3d &t(int j_ancestor, int j) {\n        return _t[numJointSpaces * (j_ancestor + 1) + j + 1];\n    }\n\n    /** Combined left-side matrix to multiply into Jacobians for joint j,\n     * component t */\n    // inline Eigen::Matrix3d& L(int j, int t) {\n    //     return _L[j * AvatarOptimizer::ROT_SIZE + t];\n    // }\n    AvatarOptimizer &opt;\n    Avatar &ava;\n    /** WARNING: is actual number of joints + 1 */\n    int numJointSpaces;\n\n    struct Ancestor {\n        Ancestor() {}\n        explicit Ancestor(int jid, int assigned = -1,\n                          double assign_weight = 0.0)\n            : jid(jid) {\n            if (assigned >= 0) {\n                assign[0] = assigned;\n                weight[0] = assign_weight;\n                num_assign = 1;\n            } else {\n                num_assign = 0;\n            }\n        }\n\n        /** Joint ID */\n        int jid;\n\n        /** Assigned joints of the skin point corresponding to the joint */\n        int assign[MAX_ASSIGN];\n\n        /** Assignment weight */\n        double weight[MAX_ASSIGN];\n\n        /** Number of assigned joints. */\n        int num_assign;\n\n        /** Compare by joint id */\n        bool operator<(const Ancestor &other) const { return jid < other.jid; }\n\n        /** Merge another ancestor joint */\n        void merge(const Ancestor &other) {\n            for (int i = 0; i < other.num_assign; ++i) {\n                weight[num_assign] = other.weight[i];\n                assign[num_assign++] = other.assign[i];\n            }\n        }\n    };\n\n    /** Max number of threads to use during common pre-evaluation computations\n     */\n    int numThreads = 1;\n\n    /** INTERNAL: Scaled versions of betaPose, betaShape actually\n     * used in the optimization. This accounts for\n     * variations in the number of ICP-type residuals.  */\n    double scaledBetaPose, scaledBetaShape;\n\n    /** Deduped, topo sorted ancestor joints for each skin point,\n     *  combining all joint assignments for the point */\n    std::vector<std::vector<Ancestor>> ancestor;\n\n    /** Joint initial relative/absolute positions */\n    CloudType jointVecInit, jointPosInit;\n\n    /** baseCloud after applying shape keys (3 * num points) */\n    CloudType shapedCloud;\n\n    /** List of point-specific caches */\n    std::vector<Cache> caches;\n\n    /** Local parameterization jacobian */\n    std::vector<\n        Eigen::Matrix<double, 4, 3, Eigen::RowMajor>,\n        Eigen::aligned_allocator<Eigen::Matrix<double, 4, 3, Eigen::RowMajor>>>\n        localJacobian;\n\n    /** Joint-to-parent 'shape deltas' */\n    std::vector<CloudType, Eigen::aligned_allocator<CloudType>> S;\n\n    /** Joint-to-parent 'shape delta difference' */\n    std::vector<CloudType, Eigen::aligned_allocator<CloudType>> Sp;\n\n    /** Accumulated joint-to-parent 'shape delta difference' */\n    std::vector<CloudType, Eigen::aligned_allocator<CloudType>> H;\n\n   private:\n    /** Joint-to-ancestor joint rotation (j_ances=-1 is global) */\n    std::vector<Eigen::Matrix3d, MatAlloc> _R;\n\n    /** Joint-to-ancestor joint relative position (j_ances=-1 is global) */\n    std::vector<Eigen::Vector3d, VecAlloc> _t;\n\n    /** Combined left-side matrix to use for Jacobians for joint j, component t\n     */\n    // std::vector<Eigen::Matrix3d, MatAlloc> _L;\n\n    /** True if CalcShape() has been called, to avoid further calls */\n    bool shapeComputed;\n};\n\n/** Common method for each model point */\nstruct AvatarCostFunctorCache {\n    AvatarCostFunctorCache(\n        AvatarEvaluationCommonData<AvatarCostFunctorCache> &common_data,\n        int point_id)\n        : commonData(common_data),\n          opt(common_data.opt),\n          ava(common_data.opt.ava),\n          pointId(point_id) {\n        icpJacobian.resize(commonData.ancestor[pointId].size());\n        if (commonData.shapeEnabled) {\n            icpShapeJacobian.resize(3, ava.model.numShapeKeys());\n        }\n    }\n\n    bool getICPJacobians(double *residuals, double **jacobians) const {\n        Eigen::Map<Eigen::Vector3d> residualMap(residuals);\n        residualMap.noalias() = resid;\n        if (jacobians != nullptr) {\n            if (jacobians[0] != nullptr) {\n                Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> J(\n                    jacobians[0]);\n                J.setIdentity();\n            }\n            size_t i = 0;\n            for (; i < commonData.ancestor[pointId].size(); ++i) {\n                if (jacobians[i + 1] != nullptr) {\n                    Eigen::Map<Eigen::Matrix<double, 3, 4, Eigen::RowMajor>> J(\n                        jacobians[i + 1]);\n#ifdef TEST_COMPARE_AUTO_DIFF\n                    J.noalias() = icpJacobian[i];\n#else\n                    J.topLeftCorner<3, 3>().noalias() = icpJacobian[i];\n                    J.rightCols<1>().setZero();\n#endif\n                }\n            }\n            if (commonData.shapeEnabled && jacobians[i + 1] != nullptr) {\n                Eigen::Map<\n                    Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor>>\n                    J(jacobians[i + 1], 3, ava.model.numShapeKeys());\n                J.noalias() = icpShapeJacobian;\n            }\n        }\n        return true;\n    }\n\n    void updateData(bool compute_jacobians) {\n        auto pointPosInit = commonData.shapedCloud.col(pointId);\n        resid.setZero();\n        for (auto &assign : ava.model.assignedJoints[pointId]) {\n            int k = assign.second;\n            resid += assign.first *\n                     (commonData.R(-1, k) *\n                          (pointPosInit - commonData.jointPosInit.col(k)) +\n                      commonData.t(-1, k));\n        }\n        if (compute_jacobians) {\n            // Root position derivative is always identity\n            // TODO: precompute point-to-assigned-joint vector, reduce 3 flops\n            // CloudType pointVecs;\n\n            Eigen::Matrix<double, 3, 4> dRot;\n            // Eigen::Matrix3d vCross;\n            Eigen::Vector3d v;\n\n            for (size_t i = 0; i < commonData.ancestor[pointId].size(); ++i) {\n                // Set derivative for each parent rotation\n                auto &ances = commonData.ancestor[pointId][i];\n                int j = ances.jid;  // 'middle' joint we are differenting wrt\n\n                v.setZero();\n                for (int assign = 0; assign < ances.num_assign; ++assign) {\n                    // up to 4 inner loops\n                    int k = ances.assign[assign];  // 'outer' joint assigned to\n                                                   // the point\n                    v += ances.weight[assign] *\n                         (commonData.R(j, k) *\n                              (pointPosInit - commonData.jointPosInit.col(k)) +\n                          commonData.t(j, k));\n                }\n                // std::cerr <<v.transpose<< \"\\n\"\n\n                Eigen::Quaterniond &q = opt.r[j];\n                Eigen::Vector3d u = q.vec() * 2;\n                // Quaternion-vector rotation (pseudo-)Jacobian\n                double w = q.w() * 2;\n                dRot.setZero();\n                dRot << u(1) * v(1) + v(2) * u(2),\n                    w * v(2) + u(0) * v(1) - 2 * u(1) * v(0),\n                    -w * v(1) - 2 * v(0) * u(2) + u(0) * v(2),\n                    u(1) * v(2) - v(1) * u(2),\n\n                    -w * v(2) - 2 * u(0) * v(1) + v(0) * u(1),\n                    v(2) * u(2) + u(0) * v(0),\n                    w * v(0) + u(1) * v(2) - 2 * v(1) * u(2),\n                    v(0) * u(2) - u(0) * v(2),\n\n                    w * v(1) + v(0) * u(2) - 2 * u(0) * v(2),\n                    -w * v(0) - 2 * u(1) * v(2) + v(1) * u(2),\n                    u(0) * v(0) + v(1) * u(1), u(0) * v(1) - v(0) * u(1);\n                icpJacobian[i].setZero();\n                icpJacobian[i].noalias() =\n                    commonData.R(-1, ava.model.parent[j]) * dRot\n#ifndef TEST_COMPARE_AUTO_DIFF\n                    * commonData.localJacobian[j]\n#endif\n                    ;\n            }\n\n            if (commonData.shapeEnabled) {\n                icpShapeJacobian.setZero();\n                for (const std::pair<double, int> &assign :\n                     ava.model.assignedJoints[pointId]) {\n                    const int j = assign.second;\n                    auto pointDeltas =\n                        ava.model.keyClouds.middleRows<3>(pointId * 3);\n                    icpShapeJacobian +=\n                        (commonData.R(-1, j) * (pointDeltas - commonData.S[j]) +\n                         commonData.H[j]) *\n                        assign.first;\n                }\n            }\n        }\n    }\n\n    Eigen::Vector3d resid;\n#ifdef TEST_COMPARE_AUTO_DIFF\n    // For comparing with auto diff, we cannot multiply by the\n    // local param jacobian or result would not be comparable\n    std::vector<\n        Eigen::Matrix<double, 3, 4, Eigen::RowMajor>,\n        Eigen::aligned_allocator<Eigen::Matrix<double, 3, 4, Eigen::RowMajor>>>\n        icpJacobian;\n#else\n    std::vector<\n        Eigen::Matrix<double, 3, 3, Eigen::RowMajor>,\n        Eigen::aligned_allocator<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>>\n        icpJacobian;\n#endif\n\n    Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor> icpShapeJacobian;\n\n    Avatar &ava;\n    AvatarOptimizer &opt;\n    AvatarEvaluationCommonData<AvatarCostFunctorCache> &commonData;\n    int pointId;\n};\n\n/** Ceres analytic derivative cost function for ICP error.\n *  Works for pose parameters only. */\nstruct AvatarICPCostFunctor : ceres::CostFunction {\n    AvatarICPCostFunctor(\n        AvatarEvaluationCommonData<AvatarCostFunctorCache> &common_data,\n        size_t cache_id, const CloudType &data_cloud, int data_point_id)\n        : commonData(common_data),\n          cacheId(cache_id),\n          dataCloud(data_cloud),\n          dataPointId(data_point_id) {\n        set_num_residuals(3);\n        auto &cache = common_data.caches[cache_id];\n\n        std::vector<int> *paramBlockSizes = mutable_parameter_block_sizes();\n        paramBlockSizes->push_back(3);  // Root position\n        for (size_t i = 0; i < cache.commonData.ancestor[cache.pointId].size();\n             ++i) {\n            paramBlockSizes->push_back(\n                4);  // Add rotation block for each ancestor\n        }\n        if (commonData.shapeEnabled)\n            paramBlockSizes->push_back(\n                cache.ava.model.numShapeKeys());  // Shape key weights?\n    }\n\n    bool Evaluate(double const *const *parameters, double *residuals,\n                  double **jacobians) const final {\n        if (!commonData.caches[cacheId].getICPJacobians(residuals, jacobians))\n            return false;\n        Eigen::Map<Eigen::Vector3d> resid(residuals);\n        resid -= dataCloud.col(dataPointId);\n        return true;\n    }\n    const CloudType &dataCloud;\n    int dataPointId;\n    size_t cacheId;\n    AvatarEvaluationCommonData<AvatarCostFunctorCache> &commonData;\n};\n\n/** Ceres analytic derivative cost function for pose prior error */\nstruct AvatarPosePriorCostFunctor : ceres::CostFunction {\n    AvatarPosePriorCostFunctor(\n        AvatarEvaluationCommonData<AvatarCostFunctorCache> &common_data)\n        : commonData(common_data),\n          posePrior(commonData.ava.model.posePrior),\n          nSmplJoints(commonData.ava.model.numJoints() - 1) {\n        set_num_residuals(nSmplJoints * 3 + 1);  // 3 for each joint + 1 extra\n        std::vector<int> *paramBlockSizes = mutable_parameter_block_sizes();\n        for (int i = 0; i < nSmplJoints; ++i) {\n            paramBlockSizes->push_back(\n                4);  // Add rotation block for each non-root joint\n        }\n    }\n\n    bool Evaluate(double const *const *parameters, double *residuals,\n                  double **jacobians) const final {\n        const int nResids = nSmplJoints * 3 + 1;\n        Eigen::VectorXd smplParams(nSmplJoints * 3);\n        for (int i = 0; i < nSmplJoints; ++i) {\n            Eigen::Map<const Eigen::Quaterniond> q(parameters[i]);\n            Eigen::AngleAxisd aa(q);\n            smplParams.segment<3>(i * 3) = aa.axis() * aa.angle();\n        }\n        Eigen::Map<Eigen::VectorXd> resid(residuals, nResids);\n        int compIdx;\n        resid.noalias() = posePrior.residual(smplParams, &compIdx) *\n                          commonData.scaledBetaPose;\n        if (jacobians != nullptr) {\n            const Eigen::MatrixXd &L = posePrior.prec_cho[compIdx];\n            // precision = L L^T\n            for (int i = 0; i < nSmplJoints; ++i) {\n                if (jacobians[i] != nullptr) {\n                    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 4,\n                                             Eigen::RowMajor>>\n                        J(jacobians[i], nResids, 4);\n                    J.topLeftCorner<Eigen::Dynamic, 3>(nResids - 1, 3)\n                        .noalias() = L.middleRows<3>(i * 3).transpose() *\n                                     0.707106781186548 *\n                                     commonData.scaledBetaPose;\n                    J.rightCols<1>().setZero();\n                    J.bottomLeftCorner<1, 3>().setZero();\n                }\n            }\n        }\n        return true;\n    }\n    AvatarEvaluationCommonData<AvatarCostFunctorCache> &commonData;\n    const GaussianMixture &posePrior;\n    const int nSmplJoints;\n};\n\n/** Ceres analytic derivative cost function for shape prior error\n *  (This is extremely simple, just the squared l2-norm of w!) */\nstruct AvatarShapePriorCostFunctor : ceres::CostFunction {\n    AvatarShapePriorCostFunctor(int num_shape_keys, double beta_shape)\n        : numShapeKeys(num_shape_keys), betaShape(beta_shape) {\n        set_num_residuals(numShapeKeys);  // 1 for each shape key\n        std::vector<int> *paramBlockSizes = mutable_parameter_block_sizes();\n        paramBlockSizes->push_back(numShapeKeys);  // 1 for each shape key\n    }\n\n    bool Evaluate(double const *const *parameters, double *residuals,\n                  double **jacobians) const final {\n        Eigen::Map<Eigen::VectorXd> resid(residuals, numShapeKeys);\n        Eigen::Map<const Eigen::VectorXd> w(parameters[0], numShapeKeys);\n        resid.noalias() = w * betaShape;\n        if (jacobians != nullptr) {\n            if (jacobians[0] != nullptr) {\n                Eigen::Map<Eigen::MatrixXd> J(jacobians[0], numShapeKeys,\n                                              numShapeKeys);\n                J.noalias() =\n                    Eigen::MatrixXd::Identity(numShapeKeys, numShapeKeys) *\n                    betaShape;\n            }\n        }\n        return true;\n    }\n    const int numShapeKeys;\n    const double betaShape;\n};\n\n#ifdef TEST_COMPARE_AUTO_DIFF\n/** Auto diff cost function w/ derivative for Ceres\n *  (Extremely poorly optimized, used for checking correctness of analytic\n * derivative) */\nstruct AvatarICPAutoDiffCostFunctor {\n    AvatarICPAutoDiffCostFunctor(\n        AvatarEvaluationCommonData<AvatarCostFunctorCache> &common_data,\n        size_t cache_id, const CloudType &data_cloud, int data_point_id)\n        : commonData(common_data),\n          cacheId(cache_id),\n          dataCloud(data_cloud),\n          dataPointId(data_point_id) {\n        pointId = commonData.caches[cacheId].pointId;\n    }\n    template <class T>\n    bool operator()(T const *const *params, T *residual) const {\n        using VecMap = Eigen::Map<Eigen::Matrix<T, 3, 1>>;\n        using ConstVecMap = Eigen::Map<const Eigen::Matrix<T, 3, 1>>;\n        using ConstQuatMap = Eigen::Map<const Eigen::Quaternion<T>>;\n\n        Eigen::Matrix<T, 3, Eigen::Dynamic> cloud(\n            3, commonData.ava.model.numPoints());\n        Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> cloudVec(\n            cloud.data(), cloud.rows() * cloud.cols());\n\n        if (commonData.shapeEnabled) {\n            Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> wMap(\n                params[commonData.ava.model.numJoints() + 1],\n                commonData.ava.model.numShapeKeys(), 1);\n            cloudVec.noalias() =\n                commonData.ava.model.keyClouds.cast<T>() * wMap +\n                commonData.ava.model.baseCloud;\n        } else {\n            cloudVec.noalias() = commonData.ava.model.keyClouds.cast<T>() *\n                                     commonData.ava.w.cast<T>() +\n                                 commonData.ava.model.baseCloud;\n        }\n\n        Eigen::Matrix<T, 3, Eigen::Dynamic> jointPos =\n            cloud * commonData.ava.model.jointRegressor.cast<T>();\n\n        if (commonData.ava.model.useJointShapeRegressor) {\n            jointPos.resize(3, commonData.ava.model.numJoints());\n            Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> jointPosVec(\n                jointPos.data(), 3 * commonData.ava.model.numJoints());\n\n            if (commonData.shapeEnabled) {\n                Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> wMap(\n                    params[commonData.ava.model.numJoints() + 1],\n                    commonData.ava.model.numShapeKeys(), 1);\n                jointPosVec.noalias() =\n                    commonData.ava.model.jointShapeRegBase.cast<T>() +\n                    commonData.ava.model.jointShapeReg.cast<T>() * wMap;\n            } else {\n                jointPosVec.noalias() =\n                    commonData.ava.model.jointShapeRegBase.cast<T>() +\n                    commonData.ava.model.jointShapeReg.cast<T>() *\n                        commonData.ava.w.cast<T>();\n            }\n        } else {\n            jointPos.noalias() =\n                cloud * commonData.ava.model.jointRegressor.cast<T>();\n        }\n\n        Eigen::Matrix<T, 3, 1> offset = jointPos.col(0);\n        cloud.colwise() -= offset;\n        jointPos.colwise() -= offset;\n\n        VecMap resid(residual);\n        resid.setZero();\n        ConstVecMap rootPos(params[0]);\n        for (auto &assign : commonData.ava.model.assignedJoints[pointId]) {\n            Eigen::Matrix<T, 3, 1> vec =\n                (cloud.col(pointId) - jointPos.col(assign.second))\n                    .template cast<T>();\n            for (int p = assign.second; p != -1;\n                 p = commonData.ava.model.parent[p]) {\n                vec = ConstQuatMap(params[p + 1]).toRotationMatrix() * vec;\n                // Do not add if root joint since we want to add the rootPos\n                // instead in autodiff case\n                if (p)\n                    vec.noalias() +=\n                        jointPos.col(p) -\n                        jointPos.col(commonData.ava.model.parent[p]);\n            }\n            resid.noalias() += assign.first * vec;\n        }\n        resid.noalias() += rootPos;\n        resid.noalias() -= dataCloud.col(dataPointId);\n        return true;\n    }\n\n    const CloudType &dataCloud;\n    int dataPointId, pointId;\n    size_t cacheId;\n    AvatarEvaluationCommonData<AvatarCostFunctorCache> &commonData;\n};\n#endif  // TEST_COMPARE_AUTO_DIFF\n\ntypedef nanoflann::KDTreeEigenColMajorMatrixAdaptor<CloudType, 3,\n                                                    nanoflann::metric_L2_Simple>\n    KdTree;\nvoid findNN(const CloudType &data_cloud,\n            const Eigen::VectorXi &data_part_labels,\n            const std::vector<Eigen::VectorXi> &data_part_indices,\n            const CloudType &model_cloud,\n            const Eigen::VectorXi &model_part_labels,\n            const std::vector<Eigen::VectorXi> &model_part_indices,\n            std::vector<CloudType> &model_part_clouds,\n            std::vector<bool> &point_visible,\n            std::vector<std::vector<int>> &correspondences,\n            std::vector<std::unique_ptr<KdTree>> &part_kd, int nn_step,\n            int num_threads, bool invert = false) {\n    if (invert) {\n        size_t index;\n        double dist;\n        nanoflann::KNNResultSet<double> resultSet(1);\n        // match each data point to a model point\n        typedef nanoflann::KDTreeEigenColMajorMatrixAdaptor<\n            CloudType, 3, nanoflann::metric_L2_Simple>\n            KdTree;\n\n        const size_t numParts = model_part_indices.size();\n        std::vector<KdTree *> modelPartKD(numParts);\n        std::vector<std::vector<int>> newModelPartIndices(numParts);\n        {\n            std::atomic<int> part(0);\n            auto worker = [&]() {\n                int i = 0;\n                while (true) {\n                    i = part++;\n                    if (i >= numParts) break;\n                    const auto &indices = model_part_indices[i];\n                    int cnt = 0;\n                    for (int j = 0; j < indices.rows(); ++j) {\n                        int k = indices[j];\n                        if (point_visible[k]) ++cnt;\n                    }\n                    auto &partCloud = model_part_clouds[i];\n                    if (cnt == 0) {\n                        modelPartKD[i] = nullptr;\n                        continue;\n                    }\n                    partCloud.resize(3, cnt);\n                    cnt = 0;\n                    for (int j = 0; j < indices.rows(); ++j) {\n                        int k = indices[j];\n                        if (!point_visible[k]) continue;\n                        partCloud.col(cnt++).noalias() = model_cloud.col(k);\n                        newModelPartIndices[i].push_back(k);\n                    }\n                    modelPartKD[i] = new KdTree(model_part_clouds[i], 10);\n                    modelPartKD[i]->index->buildIndex();\n                }\n            };\n            std::vector<std::thread> thds;\n            for (int i = 0; i < num_threads; ++i) {\n                thds.emplace_back(worker);\n            }\n            for (int i = 0; i < num_threads; ++i) {\n                thds[i].join();\n            }\n        }\n\n        correspondences.resize(model_cloud.cols());\n        for (int i = 0; i < model_cloud.cols(); ++i) {\n            correspondences[i].clear();\n        }\n        for (int i = 0; i < data_cloud.cols(); ++i) {\n            resultSet.init(&index, &dist);\n            const int partId = data_part_labels[i];\n            if (modelPartKD[partId] == nullptr) continue;\n            modelPartKD[partId]->index->findNeighbors(\n                resultSet, data_cloud.data() + i * 3,\n                nanoflann::SearchParams(10));\n            correspondences[newModelPartIndices[partId][index]].push_back(i);\n        }\n        for (int i = 0; i < numParts; ++i) {\n            delete modelPartKD[i];\n        }\n        // const int MAX_CORRES_PER_POINT = 1;\n        // for (int i = 0; i < model_cloud.cols(); ++i) {\n        //     if (correspondences[i].size() > MAX_CORRES_PER_POINT) {\n        //         //std::cerr << correspondences[i].size() << \"SZ\\n\";\n        //         for (int j = 0; j < MAX_CORRES_PER_POINT; ++j) {\n        //             int r = random_util::randint<int>(j,\n        //             correspondences[i].size()-1);\n        //             std::swap(correspondences[i][j], correspondences[i][r]);\n        //         }\n        //         correspondences[i].resize(MAX_CORRES_PER_POINT);\n        //     }\n        // }\n\n    } else {\n        size_t index;\n        double dist;\n        nanoflann::KNNResultSet<double> resultSet(1);\n\n        // match each model point to a data point\n        correspondences.resize(model_cloud.cols());\n        for (int i = 0; i < model_cloud.cols(); ++i) {\n            correspondences[i].clear();\n        }\n        Eigen::VectorXi perPart(part_kd.size());\n        perPart.setZero();\n        for (int i = 0; i < model_cloud.cols(); i += nn_step) {\n            if (!point_visible[i]) continue;\n            resultSet.init(&index, &dist);\n            int partId = model_part_labels[i];\n            auto *kd_tree = part_kd[partId].get();\n            if (kd_tree) {\n                kd_tree->index->findNeighbors(resultSet,\n                                              model_cloud.data() + i * 3,\n                                              nanoflann::SearchParams(10));\n                correspondences[i].push_back(data_part_indices[partId][index]);\n                ++perPart[partId];\n            }\n        }\n        for (int i = 0; i < perPart.rows(); ++i) {\n            std::cout << perPart(i) << \" \";\n        }\n        std::cout << \"!!\\n\";\n\n        // if (ownTree) {\n        //     delete kd_tree;\n        // }\n        /*\n           const int MAX_CORRES_PER_POINT = 200;\n           for (int i = 0; i < model_cloud.cols(); ++i) {\n           if (correspondences[i].size() > MAX_CORRES_PER_POINT) {\n        //std::cerr << correspondences[i].size() << \"SZ\\n\";\n        for (int j = 0; j < MAX_CORRES_PER_POINT; ++j) {\n        int r = random_util::randint<int>(j, correspondences[i].size()-1);\n        std::swap(correspondences[i][j], correspondences[i][r]);\n        }\n        correspondences[i].resize(MAX_CORRES_PER_POINT);\n        }\n        }\n        */\n    }\n}\n\n#ifdef PCL_DEBUG_VISUALIZE\nvoid debugVisualize(\n    const pcl::visualization::PCLVisualizer::Ptr &viewer,\n    const CloudType &data_cloud, std::vector<std::vector<int>> correspondences,\n    const std::vector<bool> &point_visible,\n    AvatarEvaluationCommonData<AvatarCostFunctorCache> &common) {\n    auto modelPclCloud = pcl::PointCloud<pcl::PointXYZRGBA>::Ptr(\n        new pcl::PointCloud<pcl::PointXYZRGBA>());\n    auto dataPclCloud = pcl::PointCloud<pcl::PointXYZRGBA>::Ptr(\n        new pcl::PointCloud<pcl::PointXYZRGBA>());\n    // auto matchedModelPointsCloud =\n    // pcl::PointCloud<pcl::PointXYZRGBA>::Ptr(new\n    // pcl::PointCloud<pcl::PointXYZRGBA>());\n    modelPclCloud->reserve(common.ava.cloud.cols());\n    for (int i = 0; i < common.ava.cloud.cols(); ++i) {\n        pcl::PointXYZRGBA pt;\n        pt.getVector3fMap() = common.ava.cloud.col(i).cast<float>();\n        if (!point_visible[i]) {\n            // pt.r = pt.g = pt.b = 100;\n            continue;\n        } else {\n            pt.r = 255;\n            pt.g = 0;\n            pt.b = 0;\n        }\n        pt.a = 255;\n        modelPclCloud->push_back(std::move(pt));\n    }\n    dataPclCloud->reserve(data_cloud.cols());\n    for (int i = 0; i < data_cloud.cols(); ++i) {\n        pcl::PointXYZRGBA pt;\n        pt.getVector3fMap() = data_cloud.col(i).cast<float>();\n        pt.r = 100;\n        pt.g = 100;\n        pt.b = 100;\n        pt.a = 200;\n        dataPclCloud->push_back(std::move(pt));\n    }\n    // matchedModelPointsCloud->reserve(common.caches.size());\n    // common.PrepareForEvaluation(true, true);\n    // for (auto& cache : common.caches) {\n    //     cache.updateData(false);\n    //     pcl::PointXYZRGBA pt;\n    //     pt.getVector3fMap() = cache.resid.cast<float>();\n    //     pt.r = 0;\n    //     pt.g = 255;\n    //     pt.b = 0;\n    //     pt.a = 255;\n    //     matchedModelPointsCloud->push_back(std::move(pt));\n    // }\n\n    viewer->setBackgroundColor(0, 0, 0);\n    viewer->removePointCloud(\"cloud\");\n    viewer->removePointCloud(\"cloudData\");\n    viewer->removePointCloud(\"cachesCloud\");\n    viewer->removeAllShapes();\n    viewer->addPointCloud(modelPclCloud, \"cloud\", 0);\n    viewer->addPointCloud(dataPclCloud, \"cloudData\", 0);\n    // viewer->addPointCloud(matchedModelPointsCloud, \"cachesCloud\", 0);\n    /*\n    for (int i = 0; i < common.ava.model.numJoints(); ++i) {\n        pcl::PointXYZRGBA curr;\n        curr.x = common.jointPosInit(0, i);\n        curr.y = common.jointPosInit(1, i);\n        curr.z = common.jointPosInit(2, i);\n        //std::cerr << \"Joint:\" << joints[i]->name << \":\" << curr.x << \",\" <<\n    curr.y << \",\" << curr.z << \"\\n\"; cv::Vec3f colorf(0.f, 0.f, 1.0f);\n    std::string jointName = \"avatarJoint\" + std::to_string(i);\n    viewer->removeShape(jointName, 0); viewer->addSphere(curr, 0.02, colorf[0],\n    colorf[1], colorf[2], jointName, 0);\n        // if (joints[i]->parent) {\n        //     p parent = util::toPCLPoint(joints[i]->parent->posTransformed);\n        //     std::string boneName = pcl_prefix + \"avatarBone\" +\n    std::to_string(i);\n        //     viewer->removeShape(boneName, viewport);\n        //     viewer->addLine(curr, parent, colorf[2], colorf[1], colorf[0],\n    boneName, viewport);\n        // }\n    }\n    */\n\n    for (size_t i = 0; i < correspondences.size(); ++i) {\n        for (size_t j = 0; j < correspondences[i].size(); ++j) {\n            // if (random_util::uniform(0.0, 1.0) > 0.05) continue;\n            pcl::PointXYZ p1, p2;\n            p1.getVector3fMap() = common.ava.cloud.col(i).cast<float>();\n            p2.getVector3fMap() =\n                data_cloud.col(correspondences[i][j]).cast<float>();\n            std::string name = \"nn_line_\" + std::to_string(i) + \"_\" +\n                               std::to_string(correspondences[i][j]);\n            viewer->addLine<pcl::PointXYZ, pcl::PointXYZ>(p2, p1, 0.0, 1.0, 0.0,\n                                                          name, 0);\n        }\n    }\n\n    viewer->spin();\n}\n#endif\n\n#ifdef TEST_COMPARE_AUTO_DIFF\n/** Given a model point-data point pair, this function checks that autodiff\n * gives the same result as the user-supplied analytic derivatives. Useful for\n * verifying correctness. */\nvoid testCompareAutoDiff(AvatarOptimizer &opt, const ark::CloudType &data_cloud,\n                         int model_point_id, int data_point_id) {\n    using namespace ceres;\n    std::cerr << \"INFO: COMPARING AUTO DIFF\\n\";\n\n    std::cerr << data_cloud.col(data_point_id).transpose() << \" DATA POINT\\n\";\n\n    AvatarEvaluation1ommonData<AvatarCostFunctorCache> common(opt, true);\n    common.scaledBetaShape = opt.betaShape;\n    common.scaledBetaPose = opt.betaPose;\n\n    std::cerr << common.shapedCloud.col(model_point_id).transpose()\n              << \" MODEL POINT, init\\n\";\n    for (auto &ances : common.ancestor[model_point_id]) {\n        std::cerr << ances.jid << \", p() = \" << opt.ava.model.parent[ances.jid]\n                  << \"\\n\";\n        std::cerr << common.jointPosInit.col(ances.jid).transpose() << \" t\\n\";\n        std::cerr << opt.r[ances.jid].w() << \": \"\n                  << opt.r[ances.jid].vec().transpose() << \" q\\n\";\n        std::cerr << \"\\n\";\n    }\n    std::cerr << \"\\n\";\n\n    for (auto &assign : opt.ava.model.assignedJoints[model_point_id]) {\n        std::cerr << assign.first << \":\" << assign.second << \" \";\n    }\n    std::cerr << \"\\n\";\n\n    common.caches.emplace_back(common, model_point_id);\n    std::cerr << \"Created dummy caches\\n\";\n\n    DynamicAutoDiffCostFunction<AvatarICPAutoDiffCostFunctor> *cost_function =\n        new DynamicAutoDiffCostFunction<AvatarICPAutoDiffCostFunctor>(\n            new AvatarICPAutoDiffCostFunctor(common, 0, data_cloud,\n                                             data_point_id));\n    cost_function->AddParameterBlock(3);\n    for (int k = 0; k < opt.ava.model.numJoints(); ++k) {\n        cost_function->AddParameterBlock(4);\n    }\n    if (common.shapeEnabled) {\n        cost_function->AddParameterBlock(opt.ava.model.numShapeKeys());\n    }\n    cost_function->SetNumResiduals(3);\n\n    AvatarICPCostFunctor *our_cost_function =\n        new AvatarICPCostFunctor(common, 0, data_cloud, data_point_id);\n    // NULL, pointParams[i]);\n\n    std::vector<double *> params, fullParams;\n    params.reserve(common.ancestor[model_point_id].size() + 1);\n    params.push_back(common.ava.p.data());\n    for (auto &ances : common.ancestor[model_point_id]) {\n        params.push_back(opt.r[ances.jid].coeffs().data());\n    }\n    fullParams.push_back(common.ava.p.data());\n    for (int i = 0; i < opt.ava.model.numJoints(); ++i) {\n        fullParams.push_back(opt.r[i].coeffs().data());\n    }\n\n    if (common.shapeEnabled) {\n        params.push_back(common.ava.w.data());\n        fullParams.push_back(common.ava.w.data());\n    }\n\n    double resid[3];\n    double **jaco = new double *[params.size()];\n    jaco[0] = new double[3 * 3];\n    for (int i = 1; i < params.size() - 1; ++i) {\n        jaco[i] = new double[3 * 4];\n    }\n    jaco[params.size() - 1] = new double[3 * opt.ava.model.numShapeKeys()];\n    common.PrepareForEvaluation(true, true);\n    our_cost_function->Evaluate(&params[0], resid, jaco);\n    std::cerr << \"Residual ours \\n\"\n              << resid[0] << \" \" << resid[1] << \" \" << resid[2] << \"\\n\";\n\n    double **jaco2 = new double *[fullParams.size()];\n    jaco2[0] = new double[3 * 3];\n    for (int i = 1; i < fullParams.size() - 1; ++i) {\n        jaco2[i] = new double[3 * 4];\n    }\n    jaco2[fullParams.size() - 1] = new double[3 * opt.ava.model.numShapeKeys()];\n    cost_function->Evaluate(&fullParams[0], resid, jaco2);\n    std::cerr << \"Residual theirs \\n\"\n              << resid[0] << \" \" << resid[1] << \" \" << resid[2] << \"\\n\";\n\n    std::cerr << \"JACOBIAN ours \\n\";\n    for (int i = 0; i < params.size(); ++i) {\n        int cols = 3 + (i > 0);\n        if (i + 1 == params.size()) cols = opt.ava.model.numShapeKeys();\n        std::cerr << \"BLOCK \" << i;\n        if (i > 0 && (i < params.size() - 1 || !common.shapeEnabled))\n            std::cerr << \" -> \"\n                      << common.ancestor[model_point_id][i - 1].jid + 1;\n        std::cerr << \"\\n\";\n        for (int j = 0; j < 3; ++j) {\n            for (int k = 0; k < cols; ++k) {\n                std::cerr << jaco[i][j * cols + k] << \"\\t\";\n            }\n            std::cerr << \"\\n\";\n        }\n        std::cerr << \"\\n\";\n        delete[] jaco[i];\n    }\n    delete[] jaco;\n    std::cerr << \"JACOBIAN theirs \\n\";\n    for (int i = 0; i < fullParams.size(); ++i) {\n        int cols = 3 + (i > 0);\n        if (i + 1 == fullParams.size()) cols = opt.ava.model.numShapeKeys();\n        bool good = false;\n        if (i && (i < fullParams.size() - 1 || !common.shapeEnabled)) {\n            for (auto &ances : common.ancestor[model_point_id]) {\n                if (ances.jid == i - 1) {\n                    good = true;\n                    break;\n                }\n            }\n        } else\n            good = true;\n        if (good) {\n            std::cerr << \"BLOCK \" << i << \"\\n\";\n            for (int j = 0; j < 3; ++j) {\n                for (int k = 0; k < cols; ++k) {\n                    std::cerr << jaco2[i][j * cols + k] << \"\\t\";\n                }\n                std::cerr << \"\\n\";\n            }\n            std::cerr << \"\\n\";\n        }\n        delete[] jaco2[i];\n    }\n    std::cerr << \"\\n\";\n    delete[] jaco2;\n    delete our_cost_function;\n    delete cost_function;\n    std::exit(0);\n}\n#endif  // TEST_COMPARE_AUTO_DIFF\n}  // namespace\n\nAvatarOptimizer::AvatarOptimizer(Avatar &ava, const CameraIntrin &intrin,\n                                 const cv::Size &image_size, int num_parts,\n                                 const std::vector<int> &part_map)\n    : ava(ava),\n      intrin(intrin),\n      imageSize(image_size),\n      numParts(num_parts),\n      partMap(part_map) {\n    r.resize(ava.model.numJoints());\n\n    modelPartIndices.resize(numParts);\n    modelPartLabelCounts.resize(numParts);\n    modelPartClouds.resize(numParts);\n    modelPartLabelCounts.setZero();\n    for (size_t i = 0; i < ava.model.numPoints(); ++i) {\n        int mainJointId = ava.model.assignedJoints[i][0].second;\n        ++modelPartLabelCounts(partMap[mainJointId]);\n    }\n    for (int i = 0; i < numParts; ++i) {\n        if (modelPartLabelCounts(i) == 0) continue;\n        modelPartClouds[i].resize(3, modelPartLabelCounts(i));\n        modelPartIndices[i].resize(modelPartLabelCounts(i));\n    }\n\n    modelPartLabelCounts.setZero();\n    for (size_t i = 0; i < ava.model.numPoints(); ++i) {\n        int mainJointId = ava.model.assignedJoints[i][0].second;\n        int partId = partMap[mainJointId];\n        modelPartIndices[partId][modelPartLabelCounts(partId)] = i;\n        ++modelPartLabelCounts(partId);\n    }\n}\n\nvoid AvatarOptimizer::optimize(\n    const Eigen::Matrix<double, 3, Eigen::Dynamic> &data_cloud,\n    const Eigen::VectorXi &data_part_labels, int icp_iters, int num_threads) {\n    // Convert to quaternion\n    for (int i = 0; i < ava.model.numJoints(); ++i) {\n        Eigen::AngleAxisd aa;\n        aa.fromRotationMatrix(ava.r[i]);\n        r[i] = aa;\n    }\n\n    AvatarEvaluationCommonData<AvatarCostFunctorCache> common(*this, true);\n    common.numThreads = num_threads;  // boost::thread::hardware_concurrency();;\n    std::vector<std::vector<int>> correspondences;\n\n#ifdef PCL_DEBUG_VISUALIZE\n    auto viewer = pcl::visualization::PCLVisualizer::Ptr(\n        new pcl::visualization::PCLVisualizer(\"3D Viewport\"));\n    viewer->initCameraParameters();\n#endif\n\n#ifdef TEST_COMPARE_AUTO_DIFF\n    testCompareAutoDiff(*this, data_cloud, 0, 0);\n#endif\n\n    // Create separate point cloud for each body part\n    AvatarRenderer renderer(ava, intrin);\n    std::vector<bool> pointVisible(ava.cloud.size());\n\n    std::vector<CloudType> partClouds(numParts);\n    std::vector<Eigen::VectorXi> partIndices(numParts);\n    Eigen::VectorXi partLabelCounts(numParts);\n    partLabelCounts.setZero();\n    for (size_t i = 0; i < data_part_labels.rows(); ++i) {\n        ++partLabelCounts(data_part_labels(i));\n    }\n    for (int i = 0; i < numParts; ++i) {\n        if (partLabelCounts(i) == 0) continue;\n        partClouds[i].resize(3, partLabelCounts(i));\n        partIndices[i].resize(partLabelCounts(i));\n    }\n\n    partLabelCounts.setZero();\n    for (size_t i = 0; i < data_part_labels.rows(); ++i) {\n        int partId = data_part_labels(i);\n        partClouds[partId].col(partLabelCounts(partId)) = data_cloud.col(i);\n        partIndices[partId][partLabelCounts(partId)] = i;\n        ++partLabelCounts(partId);\n    }\n\n    // Build KD tree for each body part\n    std::vector<std::unique_ptr<KdTree>> partKD;\n    for (int i = 0; i < numParts; ++i) {\n        if (partLabelCounts(i) == 0) {\n            partKD.emplace_back(nullptr);\n            continue;\n        }\n        partKD.emplace_back(new KdTree(partClouds[i], 10));\n        partKD.back()->index->buildIndex();\n    }\n\n    // Store labels for each model skin point\n    Eigen::VectorXi modelPartLabels(ava.model.numPoints());\n    for (size_t i = 0; i < ava.model.numPoints(); ++i) {\n        int mainJointId = ava.model.assignedJoints[i][0].second;\n        modelPartLabels[i] = partMap[mainJointId];\n    }\n\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::LinearSolverType::DENSE_NORMAL_CHOLESKY;\n    // options.trust_region_strategy_type =\n    // ceres::TrustRegionStrategyType::LEVENBERG_MARQUARDT;\n    // options.preconditioner_type = ceres::PreconditionerType::CLUSTER_JACOBI;\n    // options.dogleg_type = ceres::DoglegType::SUBSPACE_DOGLEG;\n    // options.initial_trust_region_radius = 1e4;\n    options.minimizer_progress_to_stdout = false;\n    options.logging_type = ceres::LoggingType::SILENT;\n    options.minimizer_type = ceres::LINE_SEARCH;\n    // options.use_approximate_eigenvalue_bfgs_scaling = true;\n    // options.check_gradients = true;\n    options.line_search_direction_type = ceres::BFGS;\n    options.line_search_interpolation_type = ceres::CUBIC;\n    // options.max_num_line_search_direction_restarts = 2;\n    // options.max_num_line_search_step_size_iterations = 10;\n    // options.line_search_type = ceres::ARMIJO;\n    // options.max_linear_solver_iterations = num_subiter;\n    options.max_num_iterations = maxItersPerICP;\n    options.num_threads = 1;  // common.numThreads;\n    options.function_tolerance = 1e-4;\n    options.dense_linear_algebra_library_type =\n        ceres::DenseLinearAlgebraLibraryType::LAPACK;\n#if CERES_VERSION_MAJOR == 1\n    options.evaluation_callback = &common;\n#else\n    ceres::Problem::Options prob_options;\n    prob_options.evaluation_callback = &common;\n#endif\n    if (!enableOcclusion) {\n        std::fill(pointVisible.begin(), pointVisible.end(), true);\n    }\n\n    for (int icp_iter = 0; icp_iter < icp_iters; ++icp_iter) {\n        // Perform point cloud occlusion detection\n        BEGIN_PROFILE;\n        if (enableOcclusion) {\n            std::fill(pointVisible.begin(), pointVisible.end(), false);\n            // Remove back faces\n            for (int f = 0; f < ava.model.mesh.cols(); ++f) {\n                int i1 = ava.model.mesh(0, f);\n                int i2 = ava.model.mesh(1, f);\n                int i3 = ava.model.mesh(2, f);\n                auto p1 = ava.cloud.col(i1);\n                auto p2 = ava.cloud.col(i2);\n                auto p3 = ava.cloud.col(i3);\n\n                if (((p2 - p1).cross(p1 - p3)).z() > 1e-4) {\n                    pointVisible[i1] = pointVisible[i2] = pointVisible[i3] =\n                        true;\n                }\n\n                // pointVisible[faces[ptr[c]].second[0]]\n                //     = pointVisible[faces[ptr[c]].second[1]]\n            }\n\n            /*\n            // True occlusion (e.g. hand occluding the body)\n            // too slow, not useful probably\n            // can perhaps do better\n            // renderer.update();\n            cv::Mat facesMap = renderer.renderFaces(imageSize, num_threads); //\n            12 ms const auto& faces = renderer.getOrderedFaces(); for (int r =\n            0; r < facesMap.rows; ++r) { // loop: 3ms auto* ptr =\n            facesMap.ptr<int32_t>(r); for (int c = 0; c < facesMap.cols; ++c) {\n                    if (~ptr[c]) {\n                        pointVisible[faces[ptr[c]].second[0]]\n                            = pointVisible[faces[ptr[c]].second[1]]\n                            = pointVisible[faces[ptr[c]].second[2]] = true;\n                    }\n                }\n            }\n            */\n            PROFILE(>> Occlusion);\n        }\n\n        // Find correspondences\n        findNN(data_cloud, data_part_labels, partIndices, ava.cloud,\n               modelPartLabels, modelPartIndices, modelPartClouds, pointVisible,\n               correspondences, partKD, nnStep, num_threads,\n               /*invert*/ true);  // 3.3 ms\n        PROFILE(>> NN Corresponences);\n\n        using namespace ceres;\n\n#if CERES_VERSION_MAJOR == 1\n        Problem problem;\n#else\n        // New API uses problem options to specify evaluation_callback\n        Problem problem(prob_options);\n#endif\n\n        auto fakeQuaternionLocalParam =\n            new ceres::FakeQuaternionParameterization();\n        problem.AddParameterBlock(ava.p.data(), 3);\n        for (int i = 0; i < ava.model.numJoints(); ++i) {\n            problem.AddParameterBlock(r[i].coeffs().data(), ROT_SIZE,\n                                      fakeQuaternionLocalParam);\n        }\n        if (common.shapeEnabled) {\n            problem.AddParameterBlock(ava.w.data(), ava.model.numShapeKeys());\n        }\n        PROFILE(>> Construct problem : parameter blocks);\n        common.caches.clear();\n        // std::vector<std::tuple<ceres::ResidualBlockId, int, int> > residuals;\n        std::vector<std::vector<double *>> pointParams(ava.model.numPoints());\n        for (int i = 0; i < ava.model.numPoints(); ++i) {\n            if (correspondences[i].empty()) continue;\n            auto &params = pointParams[i];\n            common.caches.emplace_back(common, i);\n            params.reserve(common.ancestor[i].size() + 1);\n            params.push_back(ava.p.data());\n            for (auto &ances : common.ancestor[i]) {\n                params.push_back(r[ances.jid].coeffs().data());\n            }\n            if (common.shapeEnabled) {\n                params.push_back(ava.w.data());\n            }\n        }\n\n        // // DEBUG\n        // std::vector<double*> params;\n        // params.push_back(ava.p.data());\n        // for (int k = 0; k < ava.model.numJoints(); ++k) {\n        //     params.push_back(r[k].coeffs().data());\n        // }\n        // //END DEBUG\n        int cid = 0;\n        size_t totalResiduals = 0;\n        for (int i = 0; i < ava.model.numPoints(); ++i) {\n            if (correspondences[i].empty()) continue;\n            totalResiduals += correspondences[i].size();\n            for (int j : correspondences[i]) {\n                problem.AddResidualBlock(\n                    new AvatarICPCostFunctor(common, cid, data_cloud, j), NULL,\n                    pointParams[i]);\n            }\n            ++cid;\n        }\n\n        /** Scale the function weights according to number of ICP type\n         * residuals. Otherwise the function terms become extremely imbalanced\n         * in some cases.\n         */\n        common.scaledBetaPose = betaPose * std::sqrt(totalResiduals) / 15.;\n        common.scaledBetaShape = betaShape * std::sqrt(totalResiduals) / 15.;\n\n        std::vector<double *> posePriorParams;\n        posePriorParams.reserve(ava.model.numJoints() - 1);\n        for (int i = 1; i < ava.model.numJoints(); ++i) {\n            posePriorParams.push_back(r[i].coeffs().data());\n        }\n        if (betaPose > 0.) {\n            problem.AddResidualBlock(new AvatarPosePriorCostFunctor(common),\n                                     NULL, posePriorParams);\n        }\n        if (betaShape > 0.) {\n            problem.AddResidualBlock(\n                new AvatarShapePriorCostFunctor(ava.model.numShapeKeys(),\n                                                common.scaledBetaShape),\n                NULL, ava.w.data());\n        }\n        PROFILE(>> Construct problem : residual blocks);\n\n#ifdef PCL_DEBUG_VISUALIZE\n        debugVisualize(viewer, data_cloud, correspondences, pointVisible,\n                       common);\n#endif\n\n        // Run solver\n        Solver::Summary summary;\n        // PROFILE(>> Render in PCL);\n\n        ceres::Solve(options, &problem, &summary);  // 35 ms\n\n        PROFILE(>> Solve);\n\n        // output (for debugging)\n        // std::cout << summary.FullReport() << \"\\n\";\n\n        // Convert from quaternion\n        for (int i = 0; i < ava.model.numJoints(); ++i) {\n            ava.r[i].noalias() = r[i].toRotationMatrix();\n        }\n        ava.update();\n        PROFILE(>> Finish);\n        // std::cout << ava.w.transpose() << \"\\n\";\n\n        /*\n        // This block shows the value of each residual\n        for (auto& res_tup : residuals) {\n            double val;\n            ceres::Problem::EvaluateOptions eo;\n            eo.residual_blocks.push_back(std::get<0>(res_tup));\n            problem.Evaluate(eo, &val, NULL, NULL, NULL);\n            std::cout << val << \" energy = \";\n            std::cout << (ava.cloud.col(std::get<1>(res_tup)) -\n        data_cloud.col(std::get<2>(res_tup))).squaredNorm() * 0.5 << \"\\n\";\n        }*/\n    }\n#ifdef PCL_DEBUG_VISUALIZE\n    viewer->spin();\n    viewer->close();\n#endif\n}\n}  // namespace ark\n", "meta": {"hexsha": "67dac9652ecf3bff566800b1977d18d9eb270cf4", "size": 60093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AvatarOptimizer.cpp", "max_stars_repo_name": "jyuatsfl/avatar", "max_stars_repo_head_hexsha": "8bbb5d72fda0857e04d0c76329f32162f6d98a92", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T09:47:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T01:41:28.000Z", "max_issues_repo_path": "AvatarOptimizer.cpp", "max_issues_repo_name": "jyuatsfl/avatar", "max_issues_repo_head_hexsha": "8bbb5d72fda0857e04d0c76329f32162f6d98a92", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-07-08T03:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T12:24:33.000Z", "max_forks_repo_path": "AvatarOptimizer.cpp", "max_forks_repo_name": "jyuatsfl/avatar", "max_forks_repo_head_hexsha": "8bbb5d72fda0857e04d0c76329f32162f6d98a92", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-06-10T09:47:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T09:54:46.000Z", "avg_line_length": 39.5608953259, "max_line_length": 80, "alphanum_fraction": 0.5523605079, "num_tokens": 14992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1692679741984068}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <boost/optional.hpp>\n#include \"ear/exceptions.hpp\"\n#include \"ear/metadata.hpp\"\n#include \"ear/screen.hpp\"\n\nnamespace ear {\n  class ScreenEdgeLockHandler {\n   public:\n    ScreenEdgeLockHandler(boost::optional<Screen> reproductionScreen)\n        : _reproductionScreen(reproductionScreen){};\n\n    std::pair<double, double> handleAzimuthElevation(\n        double azimuth, double elevation, ScreenEdgeLock screenEdgeLock) {\n      if (screenEdgeLock.horizontal || screenEdgeLock.vertical)\n        throw not_implemented(\"screenEdgeLock\");\n\n      return std::make_pair(azimuth, elevation);\n    }\n\n    std::tuple<double, double, double> handleVector(\n        Eigen::Vector3d pos, ScreenEdgeLock screenEdgeLock) {\n      if (screenEdgeLock.horizontal || screenEdgeLock.vertical)\n        throw not_implemented(\"screenEdgeLock\");\n\n      return std::make_tuple(pos(0), pos(1), pos(2));\n    }\n\n   private:\n    boost::optional<Screen> _reproductionScreen;\n  };\n}  // namespace ear\n", "meta": {"hexsha": "7d9ac2afe091ca0110c3e543a51a6350f295a29b", "size": 1008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/screen_edge_lock.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/screen_edge_lock.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/screen_edge_lock.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": 29.6470588235, "max_line_length": 74, "alphanum_fraction": 0.7103174603, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.30735802955444114, "lm_q1q2_score": 0.1692335949290734}}
{"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/bind.hpp>\n\n#include \"Tudat/Astrodynamics/Aerodynamics/exponentialAtmosphere.h\"\n#include \"Tudat/Astrodynamics/Aerodynamics/tabulatedAtmosphere.h\"\n#if USE_NRLMSISE00\n#include \"Tudat/Astrodynamics/Aerodynamics/nrlmsise00Atmosphere.h\"\n#include \"Tudat/Astrodynamics/Aerodynamics/nrlmsise00InputFunctions.h\"\n#endif\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/InputOutput/solarActivityData.h\"\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createAtmosphereModel.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\n//! Function to create a wind model.\nstd::shared_ptr< aerodynamics::WindModel > createWindModel(\n        const std::shared_ptr< WindModelSettings > windSettings,\n        const std::string& body )\n{\n    std::shared_ptr< aerodynamics::WindModel > windModel;\n\n    // Check wind model type and create requested model\n    switch( windSettings->getWindModelType( ) )\n    {\n    case custom_wind_model:\n    {\n        // Check input consistency\n        std::shared_ptr< CustomWindModelSettings > customWindModelSettings =\n                std::dynamic_pointer_cast< CustomWindModelSettings >( windSettings );\n\n        if( customWindModelSettings == nullptr )\n        {\n            throw std::runtime_error( \"Error when making custom wind model for body \" + body + \", input is incompatible\" );\n        }\n        windModel = std::make_shared< aerodynamics::CustomWindModel >(\n                    customWindModelSettings->getWindFunction( ) );\n        break;\n    }\n    default:\n        throw std::runtime_error( \"Error when making wind model for body \" + body + \", input type not recognized\" );\n    }\n\n    return windModel;\n\n}\n\n//! Function to create an atmosphere model.\nstd::shared_ptr< aerodynamics::AtmosphereModel > createAtmosphereModel(\n        const std::shared_ptr< AtmosphereSettings > atmosphereSettings,\n        const std::string& body )\n{\n    using namespace tudat::aerodynamics;\n\n    // Declare return object.\n    std::shared_ptr< AtmosphereModel > atmosphereModel;\n\n    // Check which type of atmosphere model is to be created.\n    switch( atmosphereSettings->getAtmosphereType( ) )\n    {\n    case exponential_atmosphere:\n    {\n        // Check whether settings for atmosphere are consistent with its type.\n        std::shared_ptr< ExponentialAtmosphereSettings > exponentialAtmosphereSettings =\n                std::dynamic_pointer_cast< ExponentialAtmosphereSettings >( atmosphereSettings );\n\n        if( exponentialAtmosphereSettings == nullptr )\n        {\n            throw std::runtime_error( \"Error, expected exponential atmosphere settings for body \" + body );\n        }\n        else\n        {\n            // Create and initialize exponential atmosphere model.\n            std::shared_ptr< ExponentialAtmosphere > exponentialAtmosphereModel;\n            if ( exponentialAtmosphereSettings->getBodyName( ) == undefined_body )\n            {\n                exponentialAtmosphereModel = std::make_shared< ExponentialAtmosphere >(\n                            exponentialAtmosphereSettings->getDensityScaleHeight( ) ,\n                            exponentialAtmosphereSettings->getConstantTemperature( ),\n                            exponentialAtmosphereSettings->getDensityAtZeroAltitude( ),\n                            exponentialAtmosphereSettings->getSpecificGasConstant( ),\n                            exponentialAtmosphereSettings->getRatioOfSpecificHeats( ) );\n            }\n            else\n            {\n                exponentialAtmosphereModel = std::make_shared< ExponentialAtmosphere >(\n                            exponentialAtmosphereSettings->getBodyName( ) );\n            }\n            atmosphereModel = exponentialAtmosphereModel;\n        }\n        break;\n    }\n    case custom_constant_temperature_atmosphere:\n    {\n        // Check whether settings for atmosphere are consistent with its type.\n        std::shared_ptr< CustomConstantTemperatureAtmosphereSettings > customConstantTemperatureAtmosphereSettings =\n                std::dynamic_pointer_cast< CustomConstantTemperatureAtmosphereSettings >( atmosphereSettings );\n        if( customConstantTemperatureAtmosphereSettings == nullptr )\n        {\n            throw std::runtime_error( \"Error, expected exponential atmosphere settings for body \" + body );\n        }\n        else\n        {\n            // Create and initialize exponential atmosphere model.\n            std::shared_ptr< CustomConstantTemperatureAtmosphere > customConstantTemperatureAtmosphereModel;\n            if ( customConstantTemperatureAtmosphereSettings->getModelSpecificParameters( ).empty( ) )\n            {\n                customConstantTemperatureAtmosphereModel = std::make_shared< CustomConstantTemperatureAtmosphere >(\n                            customConstantTemperatureAtmosphereSettings->getDensityFunction( ) ,\n                            customConstantTemperatureAtmosphereSettings->getConstantTemperature( ),\n                            customConstantTemperatureAtmosphereSettings->getSpecificGasConstant( ),\n                            customConstantTemperatureAtmosphereSettings->getRatioOfSpecificHeats( ) );\n            }\n            else\n            {\n                customConstantTemperatureAtmosphereModel = std::make_shared< CustomConstantTemperatureAtmosphere >(\n                            customConstantTemperatureAtmosphereSettings->getDensityFunctionType( ),\n                            customConstantTemperatureAtmosphereSettings->getConstantTemperature( ),\n                            customConstantTemperatureAtmosphereSettings->getSpecificGasConstant( ),\n                            customConstantTemperatureAtmosphereSettings->getRatioOfSpecificHeats( ),\n                            customConstantTemperatureAtmosphereSettings->getModelSpecificParameters( ) );\n            }\n            atmosphereModel = customConstantTemperatureAtmosphereModel;\n        }\n        break;\n    }\n    case tabulated_atmosphere:\n    {\n        // Check whether settings for atmosphere are consistent with its type\n        std::shared_ptr< TabulatedAtmosphereSettings > tabulatedAtmosphereSettings =\n                std::dynamic_pointer_cast< TabulatedAtmosphereSettings >( atmosphereSettings );\n        if( tabulatedAtmosphereSettings == nullptr )\n        {\n            throw std::runtime_error( \"Error, expected tabulated atmosphere settings for body \" + body );\n        }\n        else\n        {\n            // Create and initialize tabulated atmosphere model.\n            atmosphereModel = std::make_shared< TabulatedAtmosphere >(\n                        tabulatedAtmosphereSettings->getAtmosphereFile( ),\n                        tabulatedAtmosphereSettings->getIndependentVariables( ),\n                        tabulatedAtmosphereSettings->getDependentVariables( ),\n                        tabulatedAtmosphereSettings->getSpecificGasConstant( ),\n                        tabulatedAtmosphereSettings->getRatioOfSpecificHeats( ),\n                        tabulatedAtmosphereSettings->getBoundaryHandling( ),\n                        tabulatedAtmosphereSettings->getDefaultExtrapolationValue( ) );\n        }\n        break;\n    }\n#if USE_NRLMSISE00\n    case nrlmsise00:\n    {\n        std::string spaceWeatherFilePath;\n        std::shared_ptr< NRLMSISE00AtmosphereSettings > nrlmsise00AtmosphereSettings =\n                std::dynamic_pointer_cast< NRLMSISE00AtmosphereSettings >( atmosphereSettings );\n\n        if( nrlmsise00AtmosphereSettings == nullptr )\n        {\n            // Use default space weather file stored in tudatBundle.\n            spaceWeatherFilePath = input_output::getSpaceWeatherDataPath( ) + \"sw19571001.txt\";\n        }\n        else\n        {\n            // Use space weather file specified by user.\n            spaceWeatherFilePath = nrlmsise00AtmosphereSettings->getSpaceWeatherFile( );\n        }\n\n        tudat::input_output::solar_activity::SolarActivityDataMap solarActivityData =\n                tudat::input_output::solar_activity::readSolarActivityData( spaceWeatherFilePath ) ;\n\n        // Create atmosphere model using NRLMISE00 input function\n        std::function< tudat::aerodynamics::NRLMSISE00Input( double, double, double, double ) > inputFunction =\n                std::bind( &tudat::aerodynamics::nrlmsiseInputFunction,\n                           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4,\n                           solarActivityData, false, TUDAT_NAN );\n        atmosphereModel = std::make_shared< aerodynamics::NRLMSISE00Atmosphere >( inputFunction );\n        break;\n    }\n#endif\n    default:\n        throw std::runtime_error( \"Error, did not recognize atmosphere model settings type \" +\n                                  std::to_string( atmosphereSettings->getAtmosphereType( ) ) );\n    }\n\n    if( atmosphereSettings->getWindSettings( ) != nullptr )\n    {\n        atmosphereModel->setWindModel( createWindModel( atmosphereSettings->getWindSettings( ), body ) );\n    }\n\n    return atmosphereModel;\n}\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "1235361225c572d9435ecfbf36a17b9d045a82a9", "size": 9514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/EnvironmentSetup/createAtmosphereModel.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/SimulationSetup/EnvironmentSetup/createAtmosphereModel.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/SimulationSetup/EnvironmentSetup/createAtmosphereModel.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": 45.3047619048, "max_line_length": 123, "alphanum_fraction": 0.6617616145, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.16923358690262408}}
{"text": "#pragma once \n\n#include <paper/utility.hpp>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <unordered_map>\n\nnamespace std\n{\ntemplate <>\nstruct hash <paper::uint256_union>\n{\n\tsize_t operator () (paper::uint256_union const & data_a) const\n\t{\n\t\treturn *reinterpret_cast <size_t const *> (data_a.bytes.data ());\n\t}\n};\ntemplate <>\nstruct hash <paper::uint256_t>\n{\n\tsize_t operator () (paper::uint256_t const & number_a) const\n\t{\n\t\treturn number_a.convert_to <size_t> ();\n\t}\n};\n}\nnamespace boost\n{\ntemplate <>\nstruct hash <paper::uint256_union>\n{\n\tsize_t operator () (paper::uint256_union const & value_a) const\n\t{\n\t\tstd::hash <paper::uint256_union> hash;\n\t\treturn hash (value_a);\n\t}\n};\n}\nnamespace paper\n{\nclass keypair\n{\npublic:\n\tkeypair ();\n\tkeypair (std::string const &);\n\tpaper::public_key pub;\n\tpaper::private_key prv;\n};\nclass block_visitor;\nenum class block_type : uint8_t\n{\n\tinvalid,\n\tnot_a_block,\n\tsend,\n\treceive,\n\topen,\n\tchange\n};\nclass block\n{\npublic:\n\t// Return a digest of the hashables in this block.\n\tpaper::block_hash hash () const;\n\tstd::string to_json ();\n\tvirtual void hash (blake2b_state &) const = 0;\n\tvirtual uint64_t block_work () const = 0;\n\tvirtual void block_work_set (uint64_t) = 0;\n\t// Previous block in account's chain, zero for open block\n\tvirtual paper::block_hash previous () const = 0;\n\t// Source block for open/receive blocks, zero otherwise.\n\tvirtual paper::block_hash source () const = 0;\n\t// Previous block or account number for open blocks\n\tvirtual paper::block_hash root () const = 0;\n\tvirtual paper::account representative () const = 0;\n\tvirtual void serialize (paper::stream &) const = 0;\n\tvirtual void serialize_json (std::string &) const = 0;\n\tvirtual void visit (paper::block_visitor &) const = 0;\n\tvirtual bool operator == (paper::block const &) const = 0;\n\tvirtual std::unique_ptr <paper::block> clone () const = 0;\n\tvirtual paper::block_type type () const = 0;\n\t// Local work threshold for rate-limiting publishing blocks. ~5 seconds of work.\n\tstatic uint64_t const publish_test_threshold = 0xff00000000000000;\n\tstatic uint64_t const publish_full_threshold = 0xfffffe0000000000;\n\tstatic uint64_t const publish_threshold = paper::paper_network == paper::paper_networks::paper_test_network ? publish_test_threshold : publish_full_threshold;\n};\nclass unique_ptr_block_hash\n{\npublic:\n\tsize_t operator () (std::unique_ptr <paper::block> const &) const;\n\tbool operator () (std::unique_ptr <paper::block> const &, std::unique_ptr <paper::block> const &) const;\n};\nstd::unique_ptr <paper::block> deserialize_block (MDB_val const &);\nstd::unique_ptr <paper::block> deserialize_block (paper::stream &);\nstd::unique_ptr <paper::block> deserialize_block (paper::stream &, paper::block_type);\nstd::unique_ptr <paper::block> deserialize_block_json (boost::property_tree::ptree const &);\nvoid serialize_block (paper::stream &, paper::block const &);\nbool work_validate (paper::block &);\nbool work_validate (paper::block_hash const &, uint64_t);\nclass send_hashables\n{\npublic:\n\tsend_hashables (paper::account const &, paper::block_hash const &, paper::amount const &);\n\tsend_hashables (bool &, paper::stream &);\n\tsend_hashables (bool &, boost::property_tree::ptree const &);\n\tvoid hash (blake2b_state &) const;\n\tpaper::block_hash previous;\n\tpaper::account destination;\n\tpaper::amount balance;\n};\nclass send_block : public paper::block\n{\npublic:\n\tsend_block (paper::block_hash const &, paper::account const &, paper::amount const &, paper::private_key const &, paper::public_key const &, uint64_t);\n\tsend_block (bool &, paper::stream &);\n\tsend_block (bool &, boost::property_tree::ptree const &);\n\tusing paper::block::hash;\n\tvoid hash (blake2b_state &) const override;\n\tuint64_t block_work () const override;\n\tvoid block_work_set (uint64_t) override;\n\tpaper::block_hash previous () const override;\n\tpaper::block_hash source () const override;\n\tpaper::block_hash root () const override;\n\tpaper::account representative () const override;\n\tvoid serialize (paper::stream &) const override;\n\tvoid serialize_json (std::string &) const override;\n\tbool deserialize (paper::stream &);\n\tbool deserialize_json (boost::property_tree::ptree const &);\n\tvoid visit (paper::block_visitor &) const override;\n\tstd::unique_ptr <paper::block> clone () const override;\n\tpaper::block_type type () const override;\n\tbool operator == (paper::block const &) const override;\n\tbool operator == (paper::send_block const &) const;\n\tstatic size_t constexpr size = sizeof (paper::account) + sizeof (paper::block_hash) + sizeof (paper::amount) + sizeof (paper::signature) + sizeof (uint64_t);\n\tsend_hashables hashables;\n\tpaper::signature signature;\n\tuint64_t work;\n};\nclass receive_hashables\n{\npublic:\n\treceive_hashables (paper::block_hash const &, paper::block_hash const &);\n\treceive_hashables (bool &, paper::stream &);\n\treceive_hashables (bool &, boost::property_tree::ptree const &);\n\tvoid hash (blake2b_state &) const;\n\tpaper::block_hash previous;\n\tpaper::block_hash source;\n};\nclass receive_block : public paper::block\n{\npublic:\n\treceive_block (paper::block_hash const &, paper::block_hash const &, paper::private_key const &, paper::public_key const &, uint64_t);\n\treceive_block (bool &, paper::stream &);\n\treceive_block (bool &, boost::property_tree::ptree const &);\n\tusing paper::block::hash;\n\tvoid hash (blake2b_state &) const override;\n\tuint64_t block_work () const override;\n\tvoid block_work_set (uint64_t) override;\n\tpaper::block_hash previous () const override;\n\tpaper::block_hash source () const override;\n\tpaper::block_hash root () const override;\n\tpaper::account representative () const override;\n\tvoid serialize (paper::stream &) const override;\n\tvoid serialize_json (std::string &) const override;\n\tbool deserialize (paper::stream &);\n\tbool deserialize_json (boost::property_tree::ptree const &);\n\tvoid visit (paper::block_visitor &) const override;\n\tstd::unique_ptr <paper::block> clone () const override;\n\tpaper::block_type type () const override;\n\tbool operator == (paper::block const &) const override;\n\tbool operator == (paper::receive_block const &) const;\n\tstatic size_t constexpr size = sizeof (paper::block_hash) + sizeof (paper::block_hash) + sizeof (paper::signature) + sizeof (uint64_t);\n\treceive_hashables hashables;\n\tpaper::signature signature;\n\tuint64_t work;\n};\nclass open_hashables\n{\npublic:\n\topen_hashables (paper::block_hash const &, paper::account const &, paper::account const &);\n\topen_hashables (bool &, paper::stream &);\n\topen_hashables (bool &, boost::property_tree::ptree const &);\n\tvoid hash (blake2b_state &) const;\n\tpaper::block_hash source;\n\tpaper::account representative;\n\tpaper::account account;\n};\nclass open_block : public paper::block\n{\npublic:\n\topen_block (paper::block_hash const &, paper::account const &, paper::account const &, paper::private_key const &, paper::public_key const &, uint64_t);\n\topen_block (paper::block_hash const &, paper::account const &, paper::account const &, std::nullptr_t);\n\topen_block (bool &, paper::stream &);\n\topen_block (bool &, boost::property_tree::ptree const &);\n\tusing paper::block::hash;\n\tvoid hash (blake2b_state &) const override;\n\tuint64_t block_work () const override;\n\tvoid block_work_set (uint64_t) override;\n\tpaper::block_hash previous () const override;\n\tpaper::block_hash source () const override;\n\tpaper::block_hash root () const override;\n\tpaper::account representative () const override;\n\tvoid serialize (paper::stream &) const override;\n\tvoid serialize_json (std::string &) const override;\n\tbool deserialize (paper::stream &);\n\tbool deserialize_json (boost::property_tree::ptree const &);\n\tvoid visit (paper::block_visitor &) const override;\n\tstd::unique_ptr <paper::block> clone () const override;\n\tpaper::block_type type () const override;\n\tbool operator == (paper::block const &) const override;\n\tbool operator == (paper::open_block const &) const;\n\tstatic size_t constexpr size = sizeof (paper::block_hash) + sizeof (paper::account) + sizeof (paper::account) + sizeof (paper::signature) + sizeof (uint64_t);\n\tpaper::open_hashables hashables;\n\tpaper::signature signature;\n\tuint64_t work;\n};\nclass change_hashables\n{\npublic:\n\tchange_hashables (paper::block_hash const &, paper::account const &);\n\tchange_hashables (bool &, paper::stream &);\n\tchange_hashables (bool &, boost::property_tree::ptree const &);\n\tvoid hash (blake2b_state &) const;\n\tpaper::block_hash previous;\n\tpaper::account representative;\n};\nclass change_block : public paper::block\n{\npublic:\n\tchange_block (paper::block_hash const &, paper::account const &, paper::private_key const &, paper::public_key const &, uint64_t);\n\tchange_block (bool &, paper::stream &);\n\tchange_block (bool &, boost::property_tree::ptree const &);\n\tusing paper::block::hash;\n\tvoid hash (blake2b_state &) const override;\n\tuint64_t block_work () const override;\n\tvoid block_work_set (uint64_t) override;\n\tpaper::block_hash previous () const override;\n\tpaper::block_hash source () const override;\n\tpaper::block_hash root () const override;\n\tpaper::account representative () const override;\n\tvoid serialize (paper::stream &) const override;\n\tvoid serialize_json (std::string &) const override;\n\tbool deserialize (paper::stream &);\n\tbool deserialize_json (boost::property_tree::ptree const &);\n\tvoid visit (paper::block_visitor &) const override;\n\tstd::unique_ptr <paper::block> clone () const override;\n\tpaper::block_type type () const override;\n\tbool operator == (paper::block const &) const override;\n\tbool operator == (paper::change_block const &) const;\n\tstatic size_t constexpr size = sizeof (paper::block_hash) + sizeof (paper::account) + sizeof (paper::signature) + sizeof (uint64_t);\n\tpaper::change_hashables hashables;\n\tpaper::signature signature;\n\tuint64_t work;\n};\nclass block_visitor\n{\npublic:\n\tvirtual void send_block (paper::send_block const &) = 0;\n\tvirtual void receive_block (paper::receive_block const &) = 0;\n\tvirtual void open_block (paper::open_block const &) = 0;\n\tvirtual void change_block (paper::change_block const &) = 0;\n};\n// Latest information about an account\nclass account_info\n{\npublic:\n\taccount_info ();\n\taccount_info (MDB_val const &);\n\taccount_info (paper::account_info const &) = default;\n\taccount_info (paper::block_hash const &, paper::block_hash const &, paper::amount const &, uint64_t, bool);\n\tvoid serialize (paper::stream &) const;\n\tbool deserialize (paper::stream &);\n\tbool operator == (paper::account_info const &) const;\n\tbool operator != (paper::account_info const &) const;\n\tpaper::mdb_val val () const;\n\tpaper::block_hash head;\n\tpaper::block_hash rep_block;\n\tpaper::amount balance;\n\tuint64_t modified;\n};\nclass store_entry\n{\npublic:\n\tstore_entry ();\n\tvoid clear ();\n\tstore_entry * operator -> ();\n\tMDB_val first;\n\tMDB_val second;\n};\nclass store_iterator\n{\npublic:\n\tstore_iterator (MDB_txn *, MDB_dbi);\n\tstore_iterator (std::nullptr_t);\n\tstore_iterator (MDB_txn *, MDB_dbi, MDB_val const &);\n\tstore_iterator (paper::store_iterator &&);\n\tstore_iterator (paper::store_iterator const &) = delete;\n\t~store_iterator ();\n\tpaper::store_iterator & operator ++ ();\n\tpaper::store_iterator & operator = (paper::store_iterator &&);\n\tpaper::store_iterator & operator = (paper::store_iterator const &) = delete;\n\tpaper::store_entry & operator -> ();\n\tbool operator == (paper::store_iterator const &) const;\n\tbool operator != (paper::store_iterator const &) const;\n\tMDB_cursor * cursor;\n\tpaper::store_entry current;\n};\n// Information on an uncollected send, source account, amount, target account.\nclass receivable\n{\npublic:\n\treceivable ();\n\treceivable (MDB_val const &);\n\treceivable (paper::account const &, paper::amount const &, paper::account const &);\n\tvoid serialize (paper::stream &) const;\n\tbool deserialize (paper::stream &);\n\tbool operator == (paper::receivable const &) const;\n\tpaper::mdb_val val () const;\n\tpaper::account source;\n\tpaper::amount amount;\n\tpaper::account destination;\n};\nclass block_store\n{\npublic:\n\tblock_store (bool &, boost::filesystem::path const &);\n\tuint64_t now ();\n\t\n\tMDB_dbi block_database (paper::block_type);\n\tvoid block_put_raw (MDB_txn *, MDB_dbi, paper::block_hash const &, MDB_val);\n\tvoid block_put (MDB_txn *, paper::block_hash const &, paper::block const &);\n\tMDB_val block_get_raw (MDB_txn *, paper::block_hash const &, paper::block_type &);\n\tpaper::block_hash block_successor (MDB_txn *, paper::block_hash const &);\n\tstd::unique_ptr <paper::block> block_get (MDB_txn *, paper::block_hash const &);\n\tvoid block_del (MDB_txn *, paper::block_hash const &);\n\tbool block_exists (MDB_txn *, paper::block_hash const &);\n\t\n\tvoid frontier_put (MDB_txn *, paper::block_hash const &, paper::account const &);\n\tpaper::account frontier_get (MDB_txn *, paper::block_hash const &);\n\tvoid frontier_del (MDB_txn *, paper::block_hash const &);\n\t\n\tvoid account_put (MDB_txn *, paper::account const &, paper::account_info const &);\n\tbool account_get (MDB_txn *, paper::account const &, paper::account_info &);\n\tvoid account_del (MDB_txn *, paper::account const &);\n\tbool account_exists (paper::account const &);\n\tpaper::store_iterator latest_begin (MDB_txn *, paper::account const &);\n\tpaper::store_iterator latest_begin (MDB_txn *);\n\tpaper::store_iterator latest_end ();\n\t\n\tvoid pending_put (MDB_txn *, paper::block_hash const &, paper::receivable const &);\n\tvoid pending_del (MDB_txn *, paper::block_hash const &);\n\tbool pending_get (MDB_txn *, paper::block_hash const &, paper::receivable &);\n\tbool pending_exists (MDB_txn *, paper::block_hash const &);\n\tpaper::store_iterator pending_begin (MDB_txn *, paper::block_hash const &);\n\tpaper::store_iterator pending_begin (MDB_txn *);\n\tpaper::store_iterator pending_end ();\n\t\n\tpaper::uint128_t representation_get (MDB_txn *, paper::account const &);\n\tvoid representation_put (MDB_txn *, paper::account const &, paper::uint128_t const &);\n\t\n\tvoid unchecked_put (MDB_txn *, paper::block_hash const &, paper::block const &);\n\tstd::unique_ptr <paper::block> unchecked_get (MDB_txn *, paper::block_hash const &);\n\tvoid unchecked_del (MDB_txn *, paper::block_hash const &);\n\tpaper::store_iterator unchecked_begin (MDB_txn *);\n\tpaper::store_iterator unchecked_end ();\n\t\n\tvoid unsynced_put (MDB_txn *, paper::block_hash const &);\n\tvoid unsynced_del (MDB_txn *, paper::block_hash const &);\n\tbool unsynced_exists (MDB_txn *, paper::block_hash const &);\n\tpaper::store_iterator unsynced_begin (MDB_txn *, paper::block_hash const &);\n\tpaper::store_iterator unsynced_begin (MDB_txn *);\n\tpaper::store_iterator unsynced_end ();\n\n\tvoid stack_open ();\n\tvoid stack_push (uint64_t, paper::block_hash const &);\n\tpaper::block_hash stack_pop (uint64_t);\n\t\n\tvoid checksum_put (MDB_txn *, uint64_t, uint8_t, paper::checksum const &);\n\tbool checksum_get (MDB_txn *, uint64_t, uint8_t, paper::checksum &);\n\tvoid checksum_del (MDB_txn *, uint64_t, uint8_t);\n\t\n\tvoid clear (MDB_dbi);\n\t\n\tpaper::mdb_env environment;\n\t// block_hash -> account                                        // Maps head blocks to owning account\n\tMDB_dbi frontiers;\n\t// account -> block_hash, representative, balance, timestamp    // Account to head block, representative, balance, last_change\n\tMDB_dbi accounts;\n\t// block_hash -> send_block\n\tMDB_dbi send_blocks;\n\t// block_hash -> receive_block\n\tMDB_dbi receive_blocks;\n\t// block_hash -> open_block\n\tMDB_dbi open_blocks;\n\t// block_hash -> change_block\n\tMDB_dbi change_blocks;\n\t// block_hash -> sender, amount, destination                    // Pending blocks to sender account, amount, destination account\n\tMDB_dbi pending;\n\t// account -> weight                                            // Representation\n\tMDB_dbi representation;\n\t// block_hash -> block                                          // Unchecked bootstrap blocks\n\tMDB_dbi unchecked;\n\t// block_hash ->                                                // Blocks that haven't been broadcast\n\tMDB_dbi unsynced;\n\t// uint64_t -> block_hash                                       // Block dependency stack while bootstrapping\n\tMDB_dbi stack;\n\t// (uint56_t, uint8_t) -> block_hash                            // Mapping of region to checksum\n\tMDB_dbi checksum;\n};\nenum class process_result\n{\n\tprogress, // Hasn't been seen before, signed correctly\n\tbad_signature, // Signature was bad, forged or transmission error\n\told, // Already seen and was valid\n\toverspend, // Malicious attempt to overspend\n\tfork, // Malicious fork based on previous\n\tunreceivable, // Source block doesn't exist or has already been received\n\tgap_previous, // Block marked as previous is unknown\n\tgap_source, // Block marked as source is unknown\n\tnot_receive_from_send, // Receive does not have a send source\n\taccount_mismatch // Account number in open block doesn't match send destination\n};\nclass process_return\n{\npublic:\n\tpaper::process_result code;\n\tpaper::account account;\n};\nclass vote\n{\npublic:\n\tvote () = default;\n\tvote (bool &, paper::stream &, paper::block_type);\n\tvote (paper::account const &, paper::private_key const &, uint64_t, std::unique_ptr <paper::block>);\n\tpaper::uint256_union hash () const;\n\t// Vote round sequence number\n\tuint64_t sequence;\n\tstd::unique_ptr <paper::block> block;\n\t// Account that's voting\n\tpaper::account account;\n\t// Signature of sequence + block hash\n\tpaper::signature signature;\n};\nclass votes\n{\npublic:\n\tvotes (paper::block_hash const &);\n\tbool vote (paper::vote const &);\n\t// Our vote round sequence number\n\tuint64_t sequence;\n\t// Root block of fork\n\tpaper::block_hash id;\n\t// All votes received by account\n\tstd::unordered_map <paper::account, std::pair <uint64_t, std::unique_ptr <paper::block>>> rep_votes;\n};\nclass ledger\n{\npublic:\n\tledger (paper::block_store &);\n\tstd::pair <paper::uint128_t, std::unique_ptr <paper::block>> winner (MDB_txn *, paper::votes const & votes_a);\n\tstd::map <paper::uint128_t, std::unique_ptr <paper::block>, std::greater <paper::uint128_t>> tally (MDB_txn *, paper::votes const &);\n\tpaper::account account (MDB_txn *, paper::block_hash const &);\n\tpaper::uint128_t amount (MDB_txn *, paper::block_hash const &);\n\tpaper::uint128_t balance (MDB_txn *, paper::block_hash const &);\n\tpaper::uint128_t account_balance (MDB_txn *, paper::account const &);\n\tpaper::uint128_t weight (MDB_txn *, paper::account const &);\n\tstd::unique_ptr <paper::block> successor (MDB_txn *, paper::block_hash const &);\n\tpaper::block_hash latest (MDB_txn *, paper::account const &);\n\tpaper::block_hash latest_root (MDB_txn *, paper::account const &);\n\tpaper::account representative (MDB_txn *, paper::block_hash const &);\n\tpaper::account representative_calculated (MDB_txn *, paper::block_hash const &);\n\tpaper::uint128_t supply (MDB_txn *);\n\tpaper::process_return process (MDB_txn *, paper::block const &);\n\tvoid rollback (MDB_txn *, paper::block_hash const &);\n\tvoid change_latest (MDB_txn *, paper::account const &, paper::block_hash const &, paper::account const &, paper::uint128_union const &);\n\tvoid move_representation (MDB_txn *, paper::account const &, paper::account const &, paper::uint128_t const &);\n\tvoid checksum_update (MDB_txn *, paper::block_hash const &);\n\tpaper::checksum checksum (MDB_txn *, paper::account const &, paper::account const &);\n\tvoid dump_account_chain (paper::account const &);\n\tstatic paper::uint128_t const unit;\n\tpaper::block_store & store;\n};\nextern paper::keypair const zero_key;\nextern paper::keypair const test_genesis_key;\nextern paper::account const paper_test_account;\nextern paper::account const paper_beta_account;\nextern paper::account const paper_live_account;\nextern paper::account const genesis_account;\nextern paper::uint128_t const genesis_amount;\nclass genesis\n{\npublic:\n\texplicit genesis ();\n\tvoid initialize (MDB_txn *, paper::block_store &) const;\n\tpaper::block_hash hash () const;\n\tpaper::open_block open;\n};\n}", "meta": {"hexsha": "8cd865db863dde1e32fa8e4de2f3116e9c1d4e9b", "size": 19690, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "paper/secure.hpp", "max_stars_repo_name": "paper-project/paper", "max_stars_repo_head_hexsha": "d558d26c1df95a13ba8957790e511ced8a62ec73", "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": "paper/secure.hpp", "max_issues_repo_name": "paper-project/paper", "max_issues_repo_head_hexsha": "d558d26c1df95a13ba8957790e511ced8a62ec73", "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": "paper/secure.hpp", "max_forks_repo_name": "paper-project/paper", "max_forks_repo_head_hexsha": "d558d26c1df95a13ba8957790e511ced8a62ec73", "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.5381526104, "max_line_length": 159, "alphanum_fraction": 0.7279329609, "num_tokens": 4627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.16923357642249273}}
{"text": "#include <pcl/pcl_base.h>\n#include <pcl/point_types.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/common/transforms.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <opencv2/core.hpp>\n#include <opencv2/core/persistence.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include <ros/ros.h>\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/PointCloud2.h>\n#include <glog/logging.h>\n#include \"../../downsampling/src/Timer.h\"\n#include \"../../ground_point_removal/src/ground_point_removal.h\"\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\ntypedef pcl::PointXYZI PointT;\ntypedef pcl::PointCloud<PointT> LidarCloudT;\ntypedef sensor_msgs::PointCloud2 MessageCloudT;\n\n\nstruct LidarInfo\n{\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    std::string name;\n    std::string topic_name;\n    std::string lidar_type;\n    cv::Mat extrinsic_cv;\n    Eigen::Matrix4f extrinsics_eigen;\n    void cv2eigen()\n    {\n        for(int x = 0;x<4;x++)\n        {\n            for(int y = 0;y<4;y++)\n            {\n                extrinsics_eigen(x,y) = extrinsic_cv.at<float>(y,x);\n            }\n        }\n    }\n};\n\nclass LidarPointsIntegrationManager\n{\nprivate:\n    std::shared_ptr<ros::NodeHandle> pNH = nullptr;\n    ros::Publisher merged_cloud_pub;\n    double velodyne_downsampling_size=0.1;\n    double livox_downsampling_size=0.1;\n    void sync2VelodyneCallback(const MessageCloudT::ConstPtr cloud_msg1,\n                                      const MessageCloudT::ConstPtr cloud_msg2)\n    {\n        LidarCloudT::Ptr pCurrentCloud1(new LidarCloudT);\n        pcl::fromROSMsg(*cloud_msg1,*pCurrentCloud1);\n\n        LidarCloudT::Ptr pCurrentCloud2(new LidarCloudT);\n        pcl::fromROSMsg(*cloud_msg2,*pCurrentCloud2);\n\n        LidarCloudT::Ptr pDownsampled1(new LidarCloudT),pDownsampled2(new LidarCloudT);\n        pcl::VoxelGrid<PointT> sor_velodyne;\n        sor_velodyne.setInputCloud(pCurrentCloud1);\n        sor_velodyne.setLeafSize(velodyne_downsampling_size, velodyne_downsampling_size, velodyne_downsampling_size);\n        sor_velodyne.filter(*pDownsampled1);\n\n        pcl::VoxelGrid<PointT> sor_livox;\n        sor_livox.setInputCloud(pCurrentCloud2);\n        sor_livox.setLeafSize(livox_downsampling_size, livox_downsampling_size, livox_downsampling_size);\n        sor_livox.filter(*pDownsampled2);\n\n        LidarCloudT::Ptr pTransformed1(new LidarCloudT),pTransformed2(new LidarCloudT);\n        pcl::transformPointCloud(*pDownsampled1,*pTransformed1,this->lidarInfoVec.at(0).extrinsics_eigen);\n        pcl::transformPointCloud(*pDownsampled2,*pTransformed2,this->lidarInfoVec.at(1).extrinsics_eigen);\n\n        LidarCloudT::Ptr pIntegrated(new LidarCloudT);\n        *pIntegrated = (*pTransformed1) + (*pTransformed2);\n        LidarCloudT::Ptr pGroundRemoved(new LidarCloudT);\n\n        {\n            ScopeTimer t(\"[lidar_points_integration] Ground removal timer:\");\n            removeGround(pIntegrated,pGroundRemoved,0.8);\n//            pGroundRemoved = pIntegrated;\n        }\n        MessageCloudT pc;\n        pcl::toROSMsg(*pGroundRemoved,pc);\n//        MessageCloudT pc;\n//        pcl::toROSMsg(*pIntegrated,pc);\n        pc.header.frame_id = \"lidar\";\n        pc.header.stamp = cloud_msg1->header.stamp;\n        merged_cloud_pub.publish(pc);\n    }\npublic:\n    vector<LidarInfo> lidarInfoVec;\n\n    void loadConfigFile()\n    {\n        cv::FileStorage fs;\n        std::string lidar_config_file_path;\n        if(! ros::param::get(\"lidar_config_file_path\",lidar_config_file_path))\n        {\n            LOG(ERROR)<<\"[lidar_points_integration] config file not set!\"<<endl;\n            throw \"ERROR!\";\n        }\n        fs.open(lidar_config_file_path,cv::FileStorage::READ);\n        if(!fs.isOpened())\n        {\n            LOG(ERROR)<<\"[lidar_points_integration] no config file exist!\"<<endl;\n            throw \"ERROR!\";\n        }\n        cv::FileNode lidars_node = fs[\"Lidars\"];\n        if(lidars_node.type()!=cv::FileNode::SEQ)\n        {\n            LOG(ERROR)<<\"[lidar_points_integration] format error!\"<<endl;\n        }\n        cv::FileNodeIterator it = lidars_node.begin(), it_end = lidars_node.end(); // Go through the node\n        for (; it != it_end; ++it)\n        {\n            LidarInfo info;\n            (*it)[\"T_FLUBaselink_Lidar\"]>>info.extrinsic_cv;\n            (*it)[\"topic\"]>>info.topic_name;\n            (*it)[\"type\"]>>info.lidar_type;\n            (*it)[\"name\"]>>info.name;\n            cv::cv2eigen(info.extrinsic_cv,info.extrinsics_eigen);\n            //info.cv2eigen();\n            this->lidarInfoVec.push_back(info);\n        }\n    }\n    void initNode(int argc,char** argv)\n    {\n        ros::init(argc,argv,\"px4_state_reporter_node\");\n        pNH = std::shared_ptr<ros::NodeHandle>(new ros::NodeHandle);\n        loadConfigFile();\n        if(!(ros::param::get(\"velodyne_downsampling_size\",velodyne_downsampling_size)&&\n             ros::param::get(\"livox_downsampling_size\",livox_downsampling_size)))\n        {\n            LOG(ERROR)<<\"Param not set in lidar_points_integration_node, quit!\"<<endl;\n            throw \"Error!\";\n        }\n        //merged_cloud_pub = pNH->advertise<MessageCloudT>(\"/gaas/preprocessing/merged_cloud\",1);\n        merged_cloud_pub = pNH->advertise<MessageCloudT>(\"/gaas/preprocessing/velodyne_downsampled\",1);\n\n        message_filters::Subscriber<MessageCloudT> lidar_sub0(*pNH, this->lidarInfoVec.at(0).topic_name, 1);\n        message_filters::Subscriber<MessageCloudT> lidar_sub1(*pNH, this->lidarInfoVec.at(1).topic_name, 1);\n\n        typedef message_filters::sync_policies::ApproximateTime<MessageCloudT, MessageCloudT> MySyncPolicy;\n        message_filters::Synchronizer<MySyncPolicy> sync(MySyncPolicy(10), lidar_sub0, lidar_sub1);\n        sync.registerCallback(boost::bind(&LidarPointsIntegrationManager::sync2VelodyneCallback,this, _1, _2));\n        ros::spin();\n    }\n};\n\n\nint main(int argc,char** argv)\n{\n    FLAGS_alsologtostderr = 1;\n    google::InitGoogleLogging(argv[0]);\n    LOG(INFO)<<\"Start lidar_points_integration node.\"<<endl;\n    LidarPointsIntegrationManager lpim;\n    lpim.initNode(argc,argv);\n    return 0;\n}\n", "meta": {"hexsha": "bc73377ac02401864e4651733523155ce96eb752", "size": 6386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algorithms/src/Preprocessing/lidar_points_integration/src/lidar_points_integration_with_tf_node.cpp", "max_stars_repo_name": "mfkiwl/GAAS", "max_stars_repo_head_hexsha": "29ab17d3e8a4ba18edef3a57c36d8db6329fac73", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "algorithms/src/Preprocessing/lidar_points_integration/src/lidar_points_integration_with_tf_node.cpp", "max_issues_repo_name": "mfkiwl/GAAS", "max_issues_repo_head_hexsha": "29ab17d3e8a4ba18edef3a57c36d8db6329fac73", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "algorithms/src/Preprocessing/lidar_points_integration/src/lidar_points_integration_with_tf_node.cpp", "max_forks_repo_name": "mfkiwl/GAAS", "max_forks_repo_head_hexsha": "29ab17d3e8a4ba18edef3a57c36d8db6329fac73", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 36.4914285714, "max_line_length": 117, "alphanum_fraction": 0.6705292828, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16917437774328292}}
{"text": "#include <rysq/fock.hpp>\n\n// #include \"fock-impl.hpp\"\n// #include \"fock-eval.hpp\"\n\n#include <map>\n\n#include <boost/preprocessor/seq/for_each_product.hpp>\n#include <boost/preprocessor/seq/to_tuple.hpp>\n#include <boost/typeof/typeof.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/lambda/lambda.hpp>\n#include \"externals/boost/numeric/ublas/storage_adaptors.hpp\"\n\n#include \"externals/cxx/foreach.hpp\"\n#include \"externals/cxx/sugar/unpack.hpp\"\n\n#include \"kernel/new.hpp\"\n#include \"fock-transform.hpp\"\n#include \"transpose.hpp\"\n\nusing namespace rysq;\n\ntypedef kernel::Eri<> kernel_type;\n\nFock::Fock(const Quartet<Shell> &quartet) {\n\n    transpose_ = Transpose(quartet[0].size < quartet[1].size,\n \t\t\t   quartet[2].size < quartet[3].size,\n \t\t\t   quartet.bra().size() < quartet.ket().size());\n    kernel_ = kernel::new_<fock::Transform>(transpose_(quartet));\n    // std::cout << transpose_(quartet) << std::endl;\n}\n\nFock::~Fock() { delete static_cast<kernel_type*>(kernel_); }\n\nvoid Fock::operator()(const Quartet<Center> &centers,\n\t\t      density_set D, fock_set F,\n\t\t      const Parameters &parameters) {\n    // (*pImpl)(centers, D, F, parameters);\n}\n\ntemplate<typename T, size_t N, typename U, class F>\nboost::array<T,N> make_array(U (&input)[N], F unary) {\n    boost::array<T,N> array;\n    std::transform(input, input + N, array.begin(), unary);\n    return array;\n}\n\ntemplate<class I, class O, class F>\nvoid transform2(I begin,I end, O output, F binary) {\n    std::transform(begin, end, output, output, binary);\n}\n\nnamespace ublas =  boost::numeric::ublas;\n\ntemplate<typename T>\nstruct kernel_data {\n    typedef std::pair<int,int> index_type;\n    // matrix types\n    typedef ublas::column_major layout;\n    typedef ublas::readonly_array_adaptor<double> adaptor;\n    typedef ublas::matrix<double, layout, adaptor> matrix;\n    struct block : matrix {\n\tvoid swap(size_t size1, size_t size2, const double *data) {\n\t    matrix tmp(size1, size2, adaptor(size1*size2, data));\n\t    matrix::swap(tmp);\n\t}\n\ttemplate<class F>\n\tvoid for_each(const F &f) {\n\t    double *__restrict__ data_ = const_cast<double*>(&data()[0]);\n    \t    double *__restrict__ buffer_ = const_cast<double*>(buffer);\n\t    size_t m = size1(), n = size2();\n\t    if (is_trans) {\n\t\tfor (size_t j = 0; j < n; ++j) {\n\t\t    for (size_t i = 0; i < m; ++i) {\n\t\t\tf(*data_++, buffer_[j+i*n]);\n\t\t    }\n\t\t}\n\t    }\n\t    else {\n\t\tfor (size_t i = 0; i < m*n; ++i) {\n\t\t    f(*data_++, *buffer_++);\n\t\t}\n\t    }\n\t}\n\tT buffer;\n\tbool is_trans;\n        index_type index, index_;\n    };\n    typedef block* iterator;\n    typedef const block* const_iterator;\n    kernel_data() {\n\tend_ = data_;\n\tfor (int i = 0; i < 4; ++i) {\n\t    std::fill(map_[i], map_[i] + 4, (block*)NULL);\n\t}\n    }\n    iterator begin() { return data_; }\n    iterator end() { return end_; }\n    block& operator[](index_type index) {\n\tblock* &b = map_[index.first][index.second];\n\tif (!b) {\n\t    b = end_++;\n\t    b->index = index;\n\t}\n\treturn *b;\n    }\n    size_t size(){return data_.size(); }\n    operator boost::array<T,6>() {\n\tboost::array<T,6> array;\n\tfor (size_t i = 0; i < array.size(); ++i) {\n\t    index_type index(index_list::at(i)[0], index_list::at(i)[1]);\n\t    array[i] = (*this)[index].buffer;\n\t}\n\treturn array;\n    }\nprivate:\n    block data_[16];\n    block* map_[4][4];\n    block *end_;\n};\n\nvoid Fock::operator()(const std::vector<Center> &centers,\n\t\t      const std::vector<Int4> &quartets,\n\t\t      density_matrix_set D, fock_matrix_set F,\n\t\t      const Parameters &parameters) {\n\n    typedef kernel_data<const double*> density_data;\n    typedef kernel_data<double*> fock_data;\n\n    density_data density_;\n    fock_data fock_;\n\n    for (size_t k = 0; k < index_list::size(); ++k) {\n\tUNPACK((const size_t i, j), index_list::at(k));\n\tstd::pair<int,int> ij(transpose_.index[i], transpose_.index[j]);\n\tbool trans = (ij.first > ij.second);\n\tif (trans) std::swap(ij.first, ij.second);\n\n\tdensity_data::block &density_block = density_[ij];\n\tfock_data::block &fock_block = fock_[ij];\n\n\tdensity_block.index_ = std::make_pair(i,j);\n\tfock_block.index_ = std::make_pair(i,j);\n\tdensity_block.is_trans = trans;\n\tfock_block.is_trans = trans;\n    }\n\n    std::vector<double> buffer;\n\n    foreach (const Int4 &q, quartets) {\n \n\tUNPACK((const int i, j, k, l), q);\n\tQuartet<Center> C(centers[i], centers[j], centers[k], centers[l]);\n\tdouble scale = 1.0/Quartet<Shell>::symmetry(i, j, k, l);\n\n#define BLOCK_SIZE(A,m) (A).get(i,j)->block ## m()\n#define BLOCK(A) (A).get(i,j)->block(q[i] - (A).base_index[i],\t\\\n\t\t\t\t     q[j] - (A).base_index[j])\n\n\tsize_t size = 0;\n\tforeach (density_data::block &block, density_) {\n\t    const size_t i = block.index_.first, j = block.index_.second;\n\t    block.swap(BLOCK_SIZE(D,1), BLOCK_SIZE(D,2), BLOCK(D));\n\t    size += block.data().size();\n\t}\n\tforeach (fock_data::block &block, fock_) {\n\t    const size_t i = block.index_.first, j = block.index_.second;\n\t    block.swap(BLOCK_SIZE(F,1), BLOCK_SIZE(F,2), BLOCK(F));\n\t    size += block.data().size();\n\t}\n\n#undef BLOCK_SIZE\n#undef BLOCK\n\t\n\tbuffer.clear();\n\tbuffer.resize(size, 0);\n\n\tsize_t pos = 0;\n\tforeach (density_data::block &block, density_) {\n\t    block.buffer = &buffer[pos];\n\t    pos += block.data().size();\n\t    using namespace boost::lambda;\n\t    block.for_each(_2 = _1);\n\t}\n\n\tforeach (fock_data::block &block, fock_) {\n\t    block.buffer = &buffer[pos];\n\t    pos += block.data().size();\n\t}\n\n\tParameters p = parameters;\n\tfock::Transform<>::Data data(density_, fock_);\n\t(*static_cast<kernel_type*>(kernel_))(transpose_(C), data, p);\n\n\tforeach (fock_data::block &block, fock_) {\n\t    fock_data::index_type &index = block.index;\n\t    int ij = index.first + index.second;\n\t    double f = ((ij == 1 || ij == 5) ? parameters.scale2 : parameters.scale);\n\t    using namespace boost::lambda;\n\t    block.for_each(_1 = _1 + f*scale*_2);\n\t}\n\n    }\n}\n\nvoid rysq::Fock::eval(const Quartet<type> &quartet,\n\t\t      const std::vector<Int4> &quartets,\n\t\t      density_matrix_set D, fock_matrix_set F,\n\t\t      const double *eri, const Parameters &parameters) {\n\n    foreach (const Int4 &q, quartets) {\n\tUNPACK((const int i, j, k, l), q);\n\n\tdensity_set D6;\n\tfock_set F6;\n\tsize_t s = 0;\t\t\n\n\t// submatrix D_, F_;\n\tforeach (const size_t (&index)[2], index_list()) {\n\t    UNPACK((const size_t i, j), index);\n\t    const double *dij = D.get(i,j)->block(q[i] - D.base_index[i],\n\t\t\t\t\t\t  q[j] - D.base_index[j]);\n\t    double *fij = F.get(i,j)->block(q[i] - F.base_index[i],\n\t\t\t\t\t    q[j] - F.base_index[j]);\n\n\t    F6[s] =  fij;\n\t    D6[s] = const_cast<double*>(dij);\n\t    ++s;\n\t}\n\n\tParameters p = parameters;\n\tp.scale = 1.0/Quartet<Shell>::symmetry(i, j, k, l);\n\teval(quartet, D6, F6, eri, p);\n\n\teri += quartet.size();\n    }\n\n}\n\nvoid rysq::Fock::eval(const Quartet<type> &quartet,\n\t\t      density_set D, fock_set F,\n\t\t      const double *Eri, const Parameters &p) {\n    UNPACK((type a,b,c,d), quartet);\n\n#define _TYPES\t(rysq::SP)(rysq::S)(rysq::P)(rysq::D)(rysq::F)\n\n#define _FOCK(r, types) if (a == BOOST_PP_SEQ_ELEM(0, types) &&\t\\\n\t\t\t    b == BOOST_PP_SEQ_ELEM(1, types)) {\t\\\n\trysq::fock::eval<BOOST_PP_SEQ_ELEM(0, types),\t\t\\\n\t    BOOST_PP_SEQ_ELEM(1, types)>(c, d, D, F, p.scale, Eri);\t\\\n    } else\n\n    BOOST_PP_SEQ_FOR_EACH_PRODUCT(_FOCK, (_TYPES)(_TYPES)) {\n\tstd::cout <<  quartet << std::endl;\n\tthrow std::exception();\n    }\n\n#undef _FOCK\n#undef _TYPES\n\n}\n", "meta": {"hexsha": "58546cbdcd22f754bfa7d463a7a2e905f7b6ec23", "size": 7332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/rysq/src/fock.cpp", "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/fock.cpp", "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/fock.cpp", "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": 27.7727272727, "max_line_length": 78, "alphanum_fraction": 0.6301145663, "num_tokens": 2209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.16917437640121788}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <stdexcept>\n#include <functional>\n#include <random>\n#include <Eigen/Geometry>\n#include <visualization_msgs/Marker.h>\n#include \"arc_utilities/eigen_helpers.hpp\"\n#include \"arc_utilities/eigen_helpers_conversions.hpp\"\n#include \"arc_utilities/pretty_print.hpp\"\n#include \"arc_utilities/voxel_grid.hpp\"\n#include \"arc_utilities/simple_rrt_planner.hpp\"\n#include \"uncertainty_planning_core/simple_pid_controller.hpp\"\n#include \"uncertainty_planning_core/simple_uncertainty_models.hpp\"\n#include \"uncertainty_planning_core/uncertainty_contact_planning.hpp\"\n#include \"uncertainty_planning_core/simple_robot_models.hpp\"\n#include \"uncertainty_planning_core/simple_samplers.hpp\"\n#include \"uncertainty_planning_core/uncertainty_planning_core.hpp\"\n#include \"fast_kinematic_simulator/fast_kinematic_simulator.hpp\"\n#include \"fast_kinematic_simulator/simulator_environment_builder.hpp\"\n#include \"uncertainty_planning_examples/config_common.hpp\"\n\n#ifndef SE2_COMMON_CONFIG_HPP\n#define SE2_COMMON_CONFIG_HPP\n\nnamespace se2_common_config\n{\n    inline uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS GetDefaultOptions()\n    {\n        uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS options;\n        options.clustering_type = uncertainty_contact_planning::CONVEX_REGION_SIGNATURE;\n        options.planner_time_limit = 120.0;\n        options.goal_bias = 0.1;\n        options.step_size = 15.0 * 0.125;\n        options.step_duration = 10.0;\n        options.goal_probability_threshold = 0.51;\n        options.goal_distance_threshold = 2.0 * 0.125;\n        options.connect_after_first_solution = 0.0;\n        options.signature_matching_threshold = 0.75;\n        options.distance_clustering_threshold = 15.0 * 0.125;\n        options.feasibility_alpha = 0.75;\n        options.variance_alpha = 0.75;\n        options.edge_attempt_count = 50u;\n        options.num_particles = 24u;\n        options.use_contact = true;\n        options.use_reverse = true;\n        options.use_spur_actions = true;\n        options.max_exec_actions = 1000u;\n        options.max_policy_exec_time = 300.0;\n        options.num_policy_simulations = 10u;\n        options.num_policy_executions = 0u;\n        options.policy_action_attempt_count = 100u;\n        options.debug_level = 0;\n        options.planner_log_file = \"/tmp/se2_planner_log.txt\";\n        options.policy_log_file = \"/tmp/se2_policy_log.txt\";\n        options.planned_policy_file = \"/tmp/se2_planned_policy.policy\";\n        options.executed_policy_file = \"/dev/null\";\n        return options;\n    }\n\n    inline config_common::TASK_CONFIG_PARAMS GetDefaultExtraOptions()\n    {\n        return config_common::TASK_CONFIG_PARAMS(0.125, 10.0, 0.0, 0.125, \"se2_maze\");\n    }\n\n    inline config_common::TASK_CONFIG_PARAMS GetExtraOptions()\n    {\n        return config_common::GetOptions(GetDefaultExtraOptions());\n    }\n\n    inline uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS GetOptions()\n    {\n        return uncertainty_planning_core::GetOptions(GetDefaultOptions());\n    }\n\n    inline simple_robot_models::SE2_ROBOT_CONFIG GetDefaultRobotConfig(const config_common::TASK_CONFIG_PARAMS& options)\n    {\n        const double kp = 0.5;//1.0; //0.1;\n        const double ki = 0.0;\n        const double kd = 0.0; //0.01;\n        const double i_clamp = 0.0;\n        const double velocity_limit = 1.0;\n        const double angular_velocity_limit = velocity_limit * 0.125;\n        const double max_sensor_noise = options.sensor_error;\n        const double max_angular_sensor_noise = max_sensor_noise * 0.125;\n        const double max_actuator_noise = options.actuator_error;\n        const double max_angular_actuator_noise = max_actuator_noise * 0.125;\n        const simple_robot_models::SE2_ROBOT_CONFIG robot_config(kp, ki, kd, i_clamp, velocity_limit, max_sensor_noise, max_actuator_noise, kp, ki, kd, i_clamp, angular_velocity_limit, max_angular_sensor_noise, max_angular_actuator_noise);\n        return robot_config;\n    }\n\n    inline Eigen::Matrix<double, 3, 1> MakeConfig(const double x, const double y, const double zr)\n    {\n        Eigen::Matrix<double, 3, 1> config;\n        config << x, y, zr;\n        return config;\n    }\n\n    inline std::pair<Eigen::Matrix<double, 3, 1>, Eigen::Matrix<double, 3, 1>> GetStartAndGoal()\n    {\n        // Define the goals of the plan\n        const Eigen::Matrix<double, 3, 1> start = MakeConfig(7.75, 7.75, 0.0);\n        const Eigen::Matrix<double, 3, 1> goal = MakeConfig(0.75, 0.75, 0.0);\n        return std::make_pair(start, goal);\n    }\n\n    inline std::shared_ptr<EigenHelpers::VectorVector4d> GetRobotPoints()\n    {\n        std::shared_ptr<EigenHelpers::VectorVector4d> robot_points(new EigenHelpers::VectorVector4d());\n        const std::vector<double> x_pos = {-0.1875, -0.0625, 0.0625, 0.1875, 0.3125, 0.4375, 0.5625, 0.6875, 0.8125, 0.9375, 1.0625, 1.1875, 1.3125, 1.4375};\n        const std::vector<double> y_pos = {-0.1875, -0.0625, 0.0625, 0.1875, 0.3125, 0.4375, 0.5625, 0.6875, 0.8125, 0.9375, 1.0625, 1.1875, 1.3125, 1.4375};\n        const std::vector<double> z_pos = {-0.4375, -0.3125, -0.1875, -0.0625, 0.0625, 0.1875, 0.3125, 0.4375};\n        for (size_t xpdx = 0; xpdx < x_pos.size(); xpdx++)\n        {\n            for (size_t ypdx = 0; ypdx < y_pos.size(); ypdx++)\n            {\n                if (xpdx <= 3 || ypdx <= 3)\n                {\n                    for (size_t zpdx = 0; zpdx < z_pos.size(); zpdx++)\n                    {\n                        robot_points->push_back(Eigen::Vector4d(x_pos[xpdx], y_pos[ypdx], z_pos[zpdx], 1.0));\n                    }\n                }\n            }\n        }\n        return robot_points;\n    }\n\n    inline simple_robot_models::SimpleSE2Robot GetRobot(const simple_robot_models::SE2_ROBOT_CONFIG& robot_config)\n    {\n        // Make the actual robot\n        const Eigen::Matrix<double, 3, 1> initial_config = Eigen::Matrix<double, 3, 1>::Zero();\n        const simple_robot_models::SimpleSE2Robot robot(GetRobotPoints(), initial_config, robot_config);\n        return robot;\n    }\n\n    inline uncertainty_planning_core::SE2SamplerPtr GetSampler()\n    {\n        const double env_resolution = 0.125;\n        const double env_min_x = 0.0 + (env_resolution);\n        const double env_max_x = 10.0 - (env_resolution);\n        const double env_min_y = 0.0 + (env_resolution);\n        const double env_max_y = 10.0 - (env_resolution);\n        // Make the sampler\n        return uncertainty_planning_core::SE2SamplerPtr(new simple_samplers::SimpleSE2BaseSampler<uncertainty_planning_core::PRNG>(std::pair<double, double>(env_min_x, env_max_x), std::pair<double, double>(env_min_y, env_max_y)));\n    }\n\n    inline uncertainty_planning_core::SE2SimulatorPtr GetSimulator(const config_common::TASK_CONFIG_PARAMS& options, const int32_t debug_level)\n    {\n        const int32_t real_debug_level = std::max(0, debug_level - 10);\n        const simulator_environment_builder::EnvironmentComponents environment_components = simulator_environment_builder::BuildCompleteEnvironment(options.environment_id, options.environment_resolution);\n        const fast_kinematic_simulator::SolverParameters solver_params = fast_kinematic_simulator::GetDefaultSolverParameters();\n        return fast_kinematic_simulator::MakeSE2Simulator(environment_components.GetEnvironment(), environment_components.GetEnvironmentSDF(), environment_components.GetSurfaceNormalsGrid(), solver_params, options.simulation_controller_frequency, real_debug_level);\n    }\n}\n\n#endif // SE2_COMMON_CONFIG_HPP\n", "meta": {"hexsha": "44466a4615d8f2e5bcadddbb4e95d243127c702c", "size": 7651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uncertainty_planning_examples/se2_common_config.hpp", "max_stars_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_stars_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T05:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T02:12:02.000Z", "max_issues_repo_path": "include/uncertainty_planning_examples/se2_common_config.hpp", "max_issues_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_issues_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "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/uncertainty_planning_examples/se2_common_config.hpp", "max_forks_repo_name": "UM-ARM-Lab/uncertainty_planning_examples", "max_forks_repo_head_hexsha": "0be4bf50db1539e8f79d9225d387270e67bcc2a2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-04-17T03:08:47.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-04T13:08:59.000Z", "avg_line_length": 46.6524390244, "max_line_length": 265, "alphanum_fraction": 0.7038295648, "num_tokens": 1991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.16917437640121785}}
{"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#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP\n\n\n#include <cstddef>\n\n#include <boost/range.hpp>\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/point_type.hpp>\n\n#include <boost/geometry/algorithms/covered_by.hpp>\n#include <boost/geometry/extensions/strategies/buffer_side.hpp>\n\n#include <boost/geometry/algorithms/detail/overlay/backtrack_check_si.hpp>\n#include <boost/geometry/algorithms/detail/overlay/calculate_distance_policy.hpp>\n#include <boost/geometry/algorithms/detail/overlay/turn_info.hpp>\n\n\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace buffer\n{\n\n\nenum intersection_location_type\n{\n    location_ok, inside_buffer, inside_original\n};\n\nclass backtrack_for_buffer\n{\npublic :\n    typedef detail::overlay::backtrack_state state_type;\n\n    template <typename Operation, typename Rings, typename Turns, typename Geometry>\n    static inline void apply(std::size_t size_at_start, \n                Rings& rings, typename boost::range_value<Rings>::type& ring,\n                Turns& turns, Operation& operation,\n                std::string const& reason,\n                Geometry const& ,\n                Geometry const& ,\n                state_type& state\n                )\n    {\n#if defined(BOOST_GEOMETRY_COUNT_BACKTRACK_WARNINGS)\nextern int g_backtrack_warning_count;\ng_backtrack_warning_count++;\n#endif\n//std::cout << \"!\";\n//std::cout << \"WARNING \" << reason << std::endl;\n\n        // TODO this is a copy of dissolve, check this for buffer\n        state.m_good = false;\n        \n        // Make bad output clean\n        rings.resize(size_at_start);\n        ring.clear();\n\n        // Reject this as a starting point\n        operation.visited.set_rejected();\n\n        // And clear all visit info\n        clear_visit_info(turns);\n    }\n};\n\nstruct turn_assign_for_buffer\n{\n    static bool const include_no_turn = false;\n    static bool const include_degenerate = false;\n    static bool const include_opposite = true;\n\n    template <typename Point1, typename Point2, typename Turn, typename IntersectionInfo, typename DirInfo>\n    static inline void apply(Turn& turn, Point1 const& p1, Point2 const& p2, IntersectionInfo const& intersection_info, DirInfo const& dir_info)\n    {\n        detail::overlay::calculate_distance_policy::apply(turn, p1, p2,\n                        intersection_info, dir_info);\n        if (dir_info.opposite && intersection_info.count == 2)\n        {\n            turn.is_opposite = true;\n        }\n    }\n};\n\n// Should follow traversal-turn-concept (enrichment, visit structure)\n// and adds index in piece vector to find it back\ntemplate <typename Point>\nstruct buffer_turn_operation : public detail::overlay::traversal_turn_operation<Point>\n{\n    int piece_index;\n    bool include_in_occupation_map;\n\n    inline buffer_turn_operation()\n        : piece_index(-1)\n        , include_in_occupation_map(false)\n    {}\n};\n\n// Version for buffer including type of location, is_opposite, and helper variables\ntemplate <typename Point>\nstruct buffer_turn_info : public detail::overlay::turn_info<Point, buffer_turn_operation<Point> >\n{\n    bool is_opposite;\n    \n    intersection_location_type location;\n    \n    int priority;\n    int count_within, count_on_helper, count_on_offsetted, count_on_corner;\n    int count_on_occupied;\n    int count_on_multi;\n#if defined(BOOST_GEOMETRY_COUNT_DOUBLE_UU)\n    int count_on_uu;\n#endif\n\n    std::set<int> piece_indices_to_skip;\n    \n#ifdef BOOST_GEOMETRY_DEBUG_WITH_MAPPER\n    std::string debug_string;\n#endif\n\n    inline buffer_turn_info()\n        : is_opposite(false)\n        , location(location_ok)\n        , priority(0)\n        , count_within(0)\n        , count_on_helper(0)\n        , count_on_offsetted(0)\n        , count_on_corner(0)\n        , count_on_occupied(0)\n        , count_on_multi(0)\n#if defined(BOOST_GEOMETRY_COUNT_DOUBLE_UU)\n        , count_on_uu(0)\n#endif\n    {}\n};\n\n\n}} // namespace detail::buffer\n#endif // DOXYGEN_NO_DETAIL\n\n\nclass si\n{\nprivate :\n    segment_identifier m_id;\n\npublic :\n    inline si(segment_identifier const& id)\n        : m_id(id)\n    {}\n\n    template <typename Char, typename Traits>\n    inline friend std::basic_ostream<Char, Traits>& operator<<(\n            std::basic_ostream<Char, Traits>& os,\n            si const& s)\n    {\n        os << s.m_id.multi_index << \".\" << s.m_id.segment_index;\n        return os;\n    }\n};\n\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP\n", "meta": {"hexsha": "fa05ac3e2cca1c8890e78549676321fb917ca434", "size": 4912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/algorithms/buffer/buffer_policies.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/algorithms/buffer/buffer_policies.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/algorithms/buffer/buffer_policies.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": 27.138121547, "max_line_length": 144, "alphanum_fraction": 0.6989006515, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16917437297694204}}
{"text": "#include <cstdint>\n#include <thread>\n#include <random>\n#include <boost/signals2.hpp>\n\ninline bool IsPrime(uint64_t number)\n{\n\tif (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3))\t\t\n\t{\n\t\treturn false;\n\t}\n\n\tfor (uint64_t k = 1; 36*k*k-12*k < number; ++k)\t\t\n\t{\n\t\tif ((number % (6*k+1) == 0) || (number % (6*k-1) == 0))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nclass ThreadStart\n{\n\tpublic:\n\t\texplicit ThreadStart()\n\t\t{\n\t\t}\n\n\t\tvirtual ~ThreadStart()\n\t\t{\n\t\t}\n\n\tpublic:\n\t\tvoid doWork(long long number)\n\t\t{\n\n\t\t}\n};\n\n\nconst size_t n = 100000;\n\nconst size_t max = std::numeric_limits<uint64_t>::max();\nconst size_t min = max / 2;\n\nstd::random_device rd;   // non-deterministic generator\nstd::mt19937 gen(rd());  // to seed mersenne twister.\nstd::uniform_int_distribution<> dist(min, max); // distribute results between 1 and 10 inclusive.\n\n std::vector<uint64_t>\t&& createLargeVector()\n {\n\treturn dist(gen);\n }\n\n\nint test6_threads()\n{\n\n\t// Typedefs for beautiful code\n\ttypedef boost::signals2::signal<bool(uint64_t)>\tregistration_manager;\n\ttypedef registration_manager::slot_type\t\t\tregistration_request;\n\n\t// Our commander\n\tregistration_manager signalHandler;\n\n\t// Create work for threads\n\tsize_t numThreads = std::thread::hardware_concurrency();\n\tstd::vector<\n\n\t// Create n-threads and connect them\n\n\n\n\tstd::thread t(&threadstart, 20);\n\tt.join();\n\n\n\treturn 0;\n}", "meta": {"hexsha": "2331385606c8c63c9a231f450e8714e7e451bf2e", "size": 1394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/boost-signals/signals-threads.cpp", "max_stars_repo_name": "Studiofreya/code-samples", "max_stars_repo_head_hexsha": "4057c5204d7d37c29ded306861ef6eaded7527e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-08-13T05:30:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T16:03:28.000Z", "max_issues_repo_path": "samples/boost-signals/signals-threads.cpp", "max_issues_repo_name": "Studiofreya/code-samples", "max_issues_repo_head_hexsha": "4057c5204d7d37c29ded306861ef6eaded7527e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/boost-signals/signals-threads.cpp", "max_forks_repo_name": "Studiofreya/code-samples", "max_forks_repo_head_hexsha": "4057c5204d7d37c29ded306861ef6eaded7527e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-02-22T16:36:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T00:04:39.000Z", "avg_line_length": 17.2098765432, "max_line_length": 97, "alphanum_fraction": 0.6585365854, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.16907209722606073}}
{"text": "#include \"drake/manipulation/kinova_jaco/jaco_status_sender.h\"\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n\nnamespace drake {\nnamespace manipulation {\nnamespace kinova_jaco {\nnamespace {\n\nusing Eigen::VectorXd;\n\nclass JacoStatusSenderTest : public testing::Test {\n public:\n  JacoStatusSenderTest()\n      : dut_(),\n        context_ptr_(dut_.CreateDefaultContext()),\n        context_(*context_ptr_) {}\n\n  const lcmt_jaco_status& output() const {\n    const lcmt_jaco_status& result =\n        dut_.get_output_port().Eval<lcmt_jaco_status>(context_);\n    DRAKE_DEMAND(result.num_joints == kJacoDefaultArmNumJoints);\n    DRAKE_DEMAND(result.joint_position.size() == kJacoDefaultArmNumJoints);\n    DRAKE_DEMAND(result.joint_velocity.size() == kJacoDefaultArmNumJoints);\n    DRAKE_DEMAND(result.joint_torque.size() == kJacoDefaultArmNumJoints);\n    DRAKE_DEMAND(\n        result.joint_torque_external.size() == kJacoDefaultArmNumJoints);\n    DRAKE_DEMAND(result.num_fingers == kJacoDefaultArmNumFingers);\n    DRAKE_DEMAND(result.finger_position.size() == kJacoDefaultArmNumFingers);\n    DRAKE_DEMAND(result.finger_velocity.size() == kJacoDefaultArmNumFingers);\n    DRAKE_DEMAND(result.finger_torque.size() == kJacoDefaultArmNumFingers);\n    DRAKE_DEMAND(\n        result.finger_torque_external.size() == kJacoDefaultArmNumFingers);\n    return result;\n  }\n\n  static std::vector<double> as_vector(const Eigen::VectorXd& v) {\n    return {v.data(), v.data() + v.size()};\n  }\n\n  void Fix(const systems::InputPort<double>& port, const Eigen::VectorXd& v) {\n    port.FixValue(&context_, v);\n  }\n\n protected:\n  JacoStatusSender dut_;\n  std::unique_ptr<systems::Context<double>> context_ptr_;\n  systems::Context<double>& context_;\n};\n\nTEST_F(JacoStatusSenderTest, AcceptanceTest) {\n  constexpr int total_dof =\n      kJacoDefaultArmNumJoints + kJacoDefaultArmNumFingers;\n\n  const VectorXd state = VectorXd::LinSpaced(total_dof * 2, 0.0, 1.0);\n  const VectorXd torque = VectorXd::LinSpaced(total_dof, 2.0, 3.0);\n  const VectorXd torque_external = VectorXd::LinSpaced(total_dof, 4.0, 5.0);\n  const VectorXd current = VectorXd::LinSpaced(total_dof, 6.0, 7.0);\n\n  // Fix only the required inputs ...\n  Fix(dut_.get_state_input_port(), state);\n\n  // ... so that some outputs have passthrough values ...\n  EXPECT_EQ(output().joint_position,\n            as_vector(state.head(kJacoDefaultArmNumJoints)));\n  EXPECT_EQ(output().joint_velocity,\n            as_vector(state.segment(total_dof, kJacoDefaultArmNumJoints) / 2));\n  EXPECT_EQ(output().finger_position,\n            as_vector(\n                state.segment(kJacoDefaultArmNumJoints,\n                              kJacoDefaultArmNumFingers) * kFingerUrdfToSdk));\n  EXPECT_EQ(output().finger_velocity,\n            as_vector(\n                state.tail(kJacoDefaultArmNumFingers) * kFingerUrdfToSdk));\n  // ... and some outputs have default values.\n  EXPECT_EQ(output().joint_torque,\n            std::vector<double>(kJacoDefaultArmNumJoints, 0.0));\n  EXPECT_EQ(output().joint_torque_external,\n            std::vector<double>(kJacoDefaultArmNumJoints, 0.0));\n  EXPECT_EQ(output().joint_current,\n            std::vector<double>(kJacoDefaultArmNumJoints, 0.0));\n  EXPECT_EQ(output().finger_torque,\n            std::vector<double>(kJacoDefaultArmNumFingers, 0.0));\n  EXPECT_EQ(output().finger_torque_external,\n            std::vector<double>(kJacoDefaultArmNumFingers, 0.0));\n  EXPECT_EQ(output().finger_current,\n            std::vector<double>(kJacoDefaultArmNumFingers, 0.0));\n\n  // Fix all of the inputs ...\n  Fix(dut_.get_torque_input_port(), torque);\n  Fix(dut_.get_torque_external_input_port(), torque_external);\n  Fix(dut_.get_current_input_port(), current);\n\n  // ... so all ouputs have values.\n  EXPECT_EQ(output().joint_torque,\n            as_vector(torque.head(kJacoDefaultArmNumJoints)));\n  EXPECT_EQ(output().joint_torque_external,\n            as_vector(torque_external.head(kJacoDefaultArmNumJoints)));\n  EXPECT_EQ(output().joint_current,\n            as_vector(current.head(kJacoDefaultArmNumJoints)));\n  EXPECT_EQ(output().finger_torque,\n            as_vector(torque.tail(kJacoDefaultArmNumFingers)));\n  EXPECT_EQ(output().finger_torque_external,\n            as_vector(torque_external.tail(kJacoDefaultArmNumFingers)));\n  EXPECT_EQ(output().finger_current,\n            as_vector(current.tail(kJacoDefaultArmNumFingers)));\n}\n\n}  // namespace\n}  // namespace kinova_jaco\n}  // namespace manipulation\n}  // namespace drake\n", "meta": {"hexsha": "ac7550985eff52fe3b3b89e616f2903153935b37", "size": 4524, "ext": "cc", "lang": "C++", "max_stars_repo_path": "manipulation/kinova_jaco/test/jaco_status_sender_test.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": "manipulation/kinova_jaco/test/jaco_status_sender_test.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": "manipulation/kinova_jaco/test/jaco_status_sender_test.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": 39.0, "max_line_length": 79, "alphanum_fraction": 0.7181697613, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.16895230991745847}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017, 2018, 2019.\r\n// Modifications copyright (c) 2017-2019, Oracle and/or its affiliates.\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// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 5.0.0\r\n\r\n// Original copyright notice:\r\n\r\n// Purpose:  Implementation of the aitoff (Aitoff) and wintri (Winkel Tripel)\r\n//           projections.\r\n// Author:   Gerald Evenden (1995)\r\n//           Drazen Tutic, Lovro Gradiser (2015) - add inverse\r\n//           Thomas Knudsen (2016) - revise/add regression tests\r\n// Copyright (c) 1995, Gerald Evenden\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 MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE 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\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_AITOFF_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_AITOFF_HPP\r\n\r\n#include <boost/core/ignore_unused.hpp>\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail { namespace aitoff\r\n    {\r\n            enum mode_type {\r\n                mode_aitoff = 0,\r\n                mode_winkel_tripel = 1\r\n            };\r\n\r\n            template <typename T>\r\n            struct par_aitoff\r\n            {\r\n                T    cosphi1;\r\n                mode_type mode;\r\n            };\r\n\r\n            template <typename T, typename Parameters>\r\n            struct base_aitoff_spheroid\r\n            {\r\n                par_aitoff<T> m_proj_parm;\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(Parameters const& , T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    T c, d;\r\n\r\n                    if((d = acos(cos(lp_lat) * cos(c = 0.5 * lp_lon)))) {/* basic Aitoff */\r\n                        xy_x = 2. * d * cos(lp_lat) * sin(c) * (xy_y = 1. / sin(d));\r\n                        xy_y *= d * sin(lp_lat);\r\n                    } else\r\n                        xy_x = xy_y = 0.;\r\n                    if (this->m_proj_parm.mode == mode_winkel_tripel) { /* Winkel Tripel */\r\n                        xy_x = (xy_x + lp_lon * this->m_proj_parm.cosphi1) * 0.5;\r\n                        xy_y = (xy_y + lp_lat) * 0.5;\r\n                    }\r\n                }\r\n                /***********************************************************************************\r\n                *\r\n                * Inverse functions added by Drazen Tutic and Lovro Gradiser based on paper:\r\n                *\r\n                * I.\u00d6zbug Biklirici and Cengizhan Ipb\u00fcker. A General Algorithm for the Inverse\r\n                * Transformation of Map Projections Using Jacobian Matrices. In Proceedings of the\r\n                * Third International Symposium Mathematical & Computational Applications,\r\n                * pages 175{182, Turkey, September 2002.\r\n                *\r\n                * Expected accuracy is defined by epsilon = 1e-12. Should be appropriate for\r\n                * most applications of Aitoff and Winkel Tripel projections.\r\n                *\r\n                * Longitudes of 180W and 180E can be mixed in solution obtained.\r\n                *\r\n                * Inverse for Aitoff projection in poles is undefined, longitude value of 0 is assumed.\r\n                *\r\n                * Contact : dtutic@geof.hr\r\n                * Date: 2015-02-16\r\n                *\r\n                ************************************************************************************/\r\n\r\n                // INVERSE(s_inverse)  sphere\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(Parameters const& , T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    static const T pi = detail::pi<T>();\r\n                    static const T two_pi = detail::two_pi<T>();\r\n                    static const T epsilon = 1e-12;\r\n\r\n                    int iter, max_iter = 10, round = 0, max_round = 20;\r\n                    T D, C, f1, f2, f1p, f1l, f2p, f2l, dp, dl, sl, sp, cp, cl, x, y;\r\n\r\n                    if ((fabs(xy_x) < epsilon) && (fabs(xy_y) < epsilon )) {\r\n                        lp_lat = 0.; lp_lon = 0.;\r\n                        return;\r\n                    }\r\n\r\n                    /* intial values for Newton-Raphson method */\r\n                    lp_lat = xy_y; lp_lon = xy_x;\r\n                    do {\r\n                        iter = 0;\r\n                        do {\r\n                            sl = sin(lp_lon * 0.5); cl = cos(lp_lon * 0.5);\r\n                            sp = sin(lp_lat); cp = cos(lp_lat);\r\n                            D = cp * cl;\r\n                            C = 1. - D * D;\r\n                            D = acos(D) / math::pow(C, T(1.5));\r\n                            f1 = 2. * D * C * cp * sl;\r\n                            f2 = D * C * sp;\r\n                            f1p = 2.* (sl * cl * sp * cp / C - D * sp * sl);\r\n                            f1l = cp * cp * sl * sl / C + D * cp * cl * sp * sp;\r\n                            f2p = sp * sp * cl / C + D * sl * sl * cp;\r\n                            f2l = 0.5 * (sp * cp * sl / C - D * sp * cp * cp * sl * cl);\r\n                            if (this->m_proj_parm.mode == mode_winkel_tripel) { /* Winkel Tripel */\r\n                                f1 = 0.5 * (f1 + lp_lon * this->m_proj_parm.cosphi1);\r\n                                f2 = 0.5 * (f2 + lp_lat);\r\n                                f1p *= 0.5;\r\n                                f1l = 0.5 * (f1l + this->m_proj_parm.cosphi1);\r\n                                f2p = 0.5 * (f2p + 1.);\r\n                                f2l *= 0.5;\r\n                            }\r\n                            f1 -= xy_x; f2 -= xy_y;\r\n                            dl = (f2 * f1p - f1 * f2p) / (dp = f1p * f2l - f2p * f1l);\r\n                            dp = (f1 * f2l - f2 * f1l) / dp;\r\n                            dl = fmod(dl, pi); /* set to interval [-M_PI, M_PI] */\r\n                            lp_lat -= dp;    lp_lon -= dl;\r\n                        } while ((fabs(dp) > epsilon || fabs(dl) > epsilon) && (iter++ < max_iter));\r\n                        if (lp_lat > two_pi) lp_lat -= 2.*(lp_lat-two_pi); /* correct if symmetrical solution for Aitoff */\r\n                        if (lp_lat < -two_pi) lp_lat -= 2.*(lp_lat+two_pi); /* correct if symmetrical solution for Aitoff */\r\n                        if ((fabs(fabs(lp_lat) - two_pi) < epsilon) && (!this->m_proj_parm.mode)) lp_lon = 0.; /* if pole in Aitoff, return longitude of 0 */\r\n\r\n                        /* calculate x,y coordinates with solution obtained */\r\n                        if((D = acos(cos(lp_lat) * cos(C = 0.5 * lp_lon))) != 0.0) {/* Aitoff */\r\n                            x = 2. * D * cos(lp_lat) * sin(C) * (y = 1. / sin(D));\r\n                            y *= D * sin(lp_lat);\r\n                        } else\r\n                            x = y = 0.;\r\n                        if (this->m_proj_parm.mode == mode_winkel_tripel) { /* Winkel Tripel */\r\n                            x = (x + lp_lon * this->m_proj_parm.cosphi1) * 0.5;\r\n                            y = (y + lp_lat) * 0.5;\r\n                        }\r\n                    /* if too far from given values of x,y, repeat with better approximation of phi,lam */\r\n                    } while (((fabs(xy_x-x) > epsilon) || (fabs(xy_y-y) > epsilon)) && (round++ < max_round));\r\n\r\n                    if (iter == max_iter && round == max_round)\r\n                    {\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_non_convergent) );\r\n                        //fprintf(stderr, \"Warning: Accuracy of 1e-12 not reached. Last increments: dlat=%e and dlon=%e\\n\", dp, dl);\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"aitoff_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            template <typename Parameters>\r\n            inline void setup(Parameters& par)\r\n            {\r\n                par.es = 0.;\r\n            }\r\n\r\n\r\n            // Aitoff\r\n            template <typename Parameters, typename T>\r\n            inline void setup_aitoff(Parameters& par, par_aitoff<T>& proj_parm)\r\n            {\r\n                proj_parm.mode = mode_aitoff;\r\n                setup(par);\r\n            }\r\n\r\n            // Winkel Tripel\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_wintri(Params& params, Parameters& par, par_aitoff<T>& proj_parm)\r\n            {\r\n                static const T two_div_pi = detail::two_div_pi<T>();\r\n\r\n                T phi1;\r\n\r\n                proj_parm.mode = mode_winkel_tripel;\r\n                if (pj_param_r<srs::spar::lat_1>(params, \"lat_1\", srs::dpar::lat_1, phi1)) {\r\n                    if ((proj_parm.cosphi1 = cos(phi1)) == 0.)\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_larger_than_90) );\r\n                } else /* 50d28' or phi1=acos(2/pi) */\r\n                    proj_parm.cosphi1 = two_div_pi;\r\n                setup(par);\r\n            }\r\n\r\n    }} // namespace detail::aitoff\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Aitoff projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Miscellaneous\r\n         - Spheroid\r\n        \\par Example\r\n        \\image html ex_aitoff.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct aitoff_spheroid : public detail::aitoff::base_aitoff_spheroid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline aitoff_spheroid(Params const& , Parameters & par)\r\n        {\r\n            detail::aitoff::setup_aitoff(par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Winkel Tripel projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Miscellaneous\r\n         - Spheroid\r\n        \\par Projection parameters\r\n         - lat_1: Latitude of first standard parallel (degrees)\r\n        \\par Example\r\n        \\image html ex_wintri.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct wintri_spheroid : public detail::aitoff::base_aitoff_spheroid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline wintri_spheroid(Params const& params, Parameters & par)\r\n        {\r\n            detail::aitoff::setup_wintri(params, par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail\r\n    {\r\n\r\n        // Static projection\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION_FI(srs::spar::proj_aitoff, aitoff_spheroid)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION_FI(srs::spar::proj_wintri, wintri_spheroid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(aitoff_entry, aitoff_spheroid)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(wintri_entry, wintri_spheroid)\r\n\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(aitoff_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(aitoff, aitoff_entry)\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(wintri, wintri_entry)\r\n        }\r\n\r\n    } // namespace detail\r\n    #endif // doxygen\r\n\r\n} // namespace projections\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_AITOFF_HPP\r\n\r\n", "meta": {"hexsha": "9c314e7c252edaf60edfd6b89e1f810e31f3f9ae", "size": 13643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/srs/projections/proj/aitoff.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/geometry/srs/projections/proj/aitoff.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/geometry/srs/projections/proj/aitoff.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": 44.4397394137, "max_line_length": 158, "alphanum_fraction": 0.5208531848, "num_tokens": 3148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.1689523084248904}}
{"text": "#include <exchange/market_state.hpp>\n#include <boost/math/special_functions/relative_difference.hpp>\n\nnamespace eosio {\n\n   market_state::market_state( account_name this_contract, symbol_type market_symbol, exchange_accounts& acnts )\n   :marketid( market_symbol.name() ),\n    market_table( this_contract, marketid ),\n    base_margins( this_contract,  (marketid<<4) + 1),\n    quote_margins( this_contract, (marketid<<4) + 2),\n    base_loans( this_contract,    (marketid<<4) + 1),\n    quote_loans( this_contract,   (marketid<<4) + 2),\n    _accounts(acnts),\n    market_state_itr( market_table.find(marketid) )\n   {\n      eosio_assert( market_state_itr != market_table.end(), \"unknown market\" );\n      exstate = *market_state_itr;\n   }\n\n   void market_state::margin_call( extended_symbol debt_type ) {\n      if( debt_type == exstate.base.balance.get_extended_symbol() )\n         margin_call( exstate.base, base_margins );\n      else\n         margin_call( exstate.quote, quote_margins );\n   }\n\n   void market_state::margin_call( exchange_state::connector& c, margins& marginstable ) {\n      auto price_idx = marginstable.get_index<N(callprice)>();\n      auto pos = price_idx.begin();\n      if( pos == price_idx.end() )\n         return;\n\n      auto receipt = exstate.convert( pos->collateral, pos->borrowed.get_extended_symbol() );\n      eosio_assert( receipt.amount >= pos->borrowed.amount, \"programmer error: insufficient collateral to cover\" );/// VERY BAD, SHOULD NOT HAPPEN\n      auto change_debt = receipt - pos->borrowed;\n\n      auto change_collat = exstate.convert( change_debt, pos->collateral.get_extended_symbol() );\n\n      _accounts.adjust_balance( pos->owner, change_collat );\n\n      c.peer_margin.total_lent.amount -= pos->borrowed.amount;\n      price_idx.erase(pos);\n\n      pos = price_idx.begin();\n      if( pos != price_idx.end() )\n         c.peer_margin.least_collateralized = pos->call_price;\n      else\n         c.peer_margin.least_collateralized = double(uint64_t(-1));\n   }\n\n\n   const exchange_state& market_state::initial_state()const {\n      return *market_state_itr;\n   }\n\n   void market_state::lend( account_name lender, const extended_asset& quantity ) {\n      auto sym = quantity.get_extended_symbol();\n      _accounts.adjust_balance( lender, -quantity );\n\n      if( sym == exstate.base.balance.get_extended_symbol() ) {\n         double new_shares = exstate.base.peer_margin.lend( quantity.amount );\n         adjust_lend_shares( lender, base_loans, new_shares );\n      }\n      else if( sym == exstate.quote.balance.get_extended_symbol() ) {\n         double new_shares = exstate.quote.peer_margin.lend( quantity.amount );\n         adjust_lend_shares( lender, quote_loans, new_shares );\n      }\n      else eosio_assert( false, \"unable to lend to this market\" );\n   }\n\n   void market_state::unlend( account_name lender, double ishares, const extended_symbol& sym ) {\n      eosio_assert( ishares > 0, \"cannot unlend negative balance\" );\n      adjust_lend_shares( lender, base_loans, -ishares );\n\n      print( \"sym: \", sym );\n\n      if( sym == exstate.base.balance.get_extended_symbol() ) {\n         extended_asset unlent  = exstate.base.peer_margin.unlend( ishares );\n         _accounts.adjust_balance( lender, unlent );\n      }\n      else if( sym == exstate.quote.balance.get_extended_symbol() ) {\n         extended_asset unlent  = exstate.quote.peer_margin.unlend( ishares );\n         _accounts.adjust_balance( lender, unlent );\n      }\n      else eosio_assert( false, \"unable to lend to this market\" );\n   }\n\n\n\n   void market_state::adjust_lend_shares( account_name lender, loans& l, double delta ) {\n      auto existing = l.find( lender );\n      if( existing == l.end() ) {\n         l.emplace( lender, [&]( auto& obj ) {\n            obj.owner = lender;\n            obj.interest_shares = delta;\n            eosio_assert( delta >= 0, \"underflow\" );\n         });\n      } else {\n         l.modify( existing, 0, [&]( auto& obj ) {\n            obj.interest_shares += delta;\n            eosio_assert( obj.interest_shares >= 0, \"underflow\" );\n         });\n      }\n   }\n\n   void market_state::cover_margin( account_name borrower, const extended_asset& cover_amount ) {\n      if( cover_amount.get_extended_symbol() == exstate.base.balance.get_extended_symbol() ) {\n         cover_margin( borrower, base_margins, exstate.base, cover_amount );\n      } else if( cover_amount.get_extended_symbol() == exstate.quote.balance.get_extended_symbol() ) {\n         cover_margin( borrower, quote_margins, exstate.quote, cover_amount );\n      } else {\n         eosio_assert( false, \"invalid debt asset\" );\n      }\n   }\n\n\n   /**\n    *  This method will use the collateral to buy the borrowed asset from the market\n    *  with collateral to cancel the debt.\n    */\n   void market_state::cover_margin( account_name borrower, margins& m, exchange_state::connector& c,\n                                    const extended_asset& cover_amount )\n   {\n      auto existing = m.find( borrower );\n      eosio_assert( existing != m.end(), \"no known margin position\" );\n      eosio_assert( existing->borrowed.amount >= cover_amount.amount, \"attempt to cover more than user has\" );\n\n      auto tmp = exstate;\n      auto estcol  = tmp.convert( cover_amount, existing->collateral.get_extended_symbol() );\n      auto debpaid = exstate.convert( estcol, cover_amount.get_extended_symbol() );\n      eosio_assert( debpaid.amount >= cover_amount.amount, \"unable to cover debt\" );\n\n      auto refundcover = debpaid - cover_amount;\n\n      auto refundcol = exstate.convert( refundcover, existing->collateral.get_extended_symbol() );\n      estcol.amount -= refundcol.amount;\n\n      if( existing->borrowed.amount == cover_amount.amount ) {\n         auto freedcollateral = existing->collateral - estcol;\n         m.erase( existing );\n         existing = m.begin();\n         _accounts.adjust_balance( borrower, freedcollateral );\n      }\n      else {\n         m.modify( existing, 0, [&]( auto& obj ) {\n             obj.collateral.amount -= estcol.amount;\n             obj.borrowed.amount -= cover_amount.amount;\n             obj.call_price = double(obj.borrowed.amount) / obj.collateral.amount;\n         });\n      }\n      c.peer_margin.total_lent.amount -= cover_amount.amount;\n\n      if( existing != m.end() ) {\n         if( existing->call_price < c.peer_margin.least_collateralized )\n            c.peer_margin.least_collateralized = existing->call_price;\n      } else {\n         c.peer_margin.least_collateralized = std::numeric_limits<double>::max();\n      }\n   }\n\n   void market_state::update_margin( account_name borrower, const extended_asset& delta_debt, const extended_asset& delta_col )\n   {\n      if( delta_debt.get_extended_symbol() == exstate.base.balance.get_extended_symbol() ) {\n         adjust_margin( borrower, base_margins, exstate.base, delta_debt, delta_col );\n      } else if( delta_debt.get_extended_symbol() == exstate.quote.balance.get_extended_symbol() ) {\n         adjust_margin( borrower, quote_margins, exstate.quote, delta_debt, delta_col );\n      } else {\n         eosio_assert( false, \"invalid debt asset\" );\n      }\n   }\n\n   void market_state::adjust_margin( account_name borrower, margins& m, exchange_state::connector& c,\n                                     const extended_asset& delta_debt, const extended_asset& delta_col )\n   {\n      auto existing = m.find( borrower );\n      if( existing == m.end() ) {\n         eosio_assert( delta_debt.amount > 0, \"cannot borrow neg\" );\n         eosio_assert( delta_col.amount > 0, \"cannot have neg collat\" );\n\n         existing = m.emplace( borrower, [&]( auto& obj ) {\n            obj.owner      = borrower;\n            obj.borrowed   = delta_debt;\n            obj.collateral = delta_col;\n            obj.call_price = double(obj.borrowed.amount) / obj.collateral.amount;\n         });\n      } else {\n         if( existing->borrowed.amount == -delta_debt.amount ) {\n            eosio_assert( existing->collateral.amount == -delta_col.amount, \"user failed to claim all collateral\" );\n\n            m.erase( existing );\n            existing = m.begin();\n         } else {\n            m.modify( existing, 0, [&]( auto& obj ) {\n               obj.borrowed   += delta_debt;\n               obj.collateral += delta_col;\n               obj.call_price = double(obj.borrowed.amount) / obj.collateral.amount;\n            });\n         }\n      }\n\n      c.peer_margin.total_lent += delta_debt;\n      eosio_assert( c.peer_margin.total_lent.amount <= c.peer_margin.total_lendable.amount, \"insufficient funds availalbe to borrow\" );\n\n      if( existing != m.end() ) {\n         if( existing->call_price < c.peer_margin.least_collateralized )\n            c.peer_margin.least_collateralized = existing->call_price;\n\n         eosio_assert( !exstate.requires_margin_call( c ), \"this update would trigger a margin call\" );\n      } else {\n         c.peer_margin.least_collateralized = std::numeric_limits<double>::max();\n      }\n\n   }\n\n\n\n   void market_state::save() {\n      market_table.modify( market_state_itr, 0, [&]( auto& s ) {\n         s = exstate;\n      });\n   }\n\n}\n", "meta": {"hexsha": "78fa7ba9f872a94fc5a74871ce82eb3b6c78bfa0", "size": 9091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contracts/exchange/market_state.cpp", "max_stars_repo_name": "BreakingSiam/avid", "max_stars_repo_head_hexsha": "796511999b46063640396e9cd691a5262bab8207", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-07-21T21:43:00.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-13T02:00:05.000Z", "max_issues_repo_path": "contracts/exchange/market_state.cpp", "max_issues_repo_name": "zhaopufeng/eos", "max_issues_repo_head_hexsha": "c9b7a2472dc3c138e64d07ec388e64340577bb34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-09-28T16:48:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-24T04:14:10.000Z", "max_forks_repo_path": "contracts/exchange/market_state.cpp", "max_forks_repo_name": "zhaopufeng/eos", "max_forks_repo_head_hexsha": "c9b7a2472dc3c138e64d07ec388e64340577bb34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-03-23T18:11:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T02:51:28.000Z", "avg_line_length": 40.5848214286, "max_line_length": 146, "alphanum_fraction": 0.6431635684, "num_tokens": 2115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.16895230503958533}}
{"text": "#pragma once\n\n#include <openssl/bio.h>\n#include <openssl/dh.h>\n#include <openssl/dsa.h>\n#include <openssl/err.h>\n#include <openssl/evp.h>\n#include <openssl/pem.h>\n#include <openssl/rand.h>\n#include <openssl/rsa.h>\n#include <openssl/ssl.h>\n\n#include <boost/asio/ssl/context.hpp>\n#include <random.hpp>\n\n#include <random>\n\nnamespace ensuressl\n{\nconstexpr char const* trustStorePath = \"/etc/ssl/certs/authority\";\nconstexpr char const* x509Comment = \"Generated from OpenBMC service\";\nstatic void initOpenssl();\nstatic EVP_PKEY* createEcKey();\n\n// Trust chain related errors.`\ninline bool isTrustChainError(int errnum)\n{\n    return (errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) ||\n           (errnum == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) ||\n           (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) ||\n           (errnum == X509_V_ERR_CERT_UNTRUSTED) ||\n           (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);\n}\n\ninline bool validateCertificate(X509* const cert)\n{\n    // Create an empty X509_STORE structure for certificate validation.\n    X509_STORE* x509Store = X509_STORE_new();\n    if (x509Store == nullptr)\n    {\n        BMCWEB_LOG_ERROR << \"Error occurred during X509_STORE_new call\";\n        return false;\n    }\n\n    // Load Certificate file into the X509 structure.\n    X509_STORE_CTX* storeCtx = X509_STORE_CTX_new();\n    if (storeCtx == nullptr)\n    {\n        BMCWEB_LOG_ERROR << \"Error occurred during X509_STORE_CTX_new call\";\n        X509_STORE_free(x509Store);\n        return false;\n    }\n\n    int errCode = X509_STORE_CTX_init(storeCtx, x509Store, cert, nullptr);\n    if (errCode != 1)\n    {\n        BMCWEB_LOG_ERROR << \"Error occurred during X509_STORE_CTX_init call\";\n        X509_STORE_CTX_free(storeCtx);\n        X509_STORE_free(x509Store);\n        return false;\n    }\n\n    errCode = X509_verify_cert(storeCtx);\n    if (errCode == 1)\n    {\n        BMCWEB_LOG_INFO << \"Certificate verification is success\";\n        X509_STORE_CTX_free(storeCtx);\n        X509_STORE_free(x509Store);\n        return true;\n    }\n    if (errCode == 0)\n    {\n        errCode = X509_STORE_CTX_get_error(storeCtx);\n        X509_STORE_CTX_free(storeCtx);\n        X509_STORE_free(x509Store);\n        if (isTrustChainError(errCode))\n        {\n            BMCWEB_LOG_DEBUG << \"Ignoring Trust Chain error. Reason: \"\n                             << X509_verify_cert_error_string(errCode);\n            return true;\n        }\n        BMCWEB_LOG_ERROR << \"Certificate verification failed. Reason: \"\n                         << X509_verify_cert_error_string(errCode);\n        return false;\n    }\n\n    BMCWEB_LOG_ERROR\n        << \"Error occurred during X509_verify_cert call. ErrorCode: \"\n        << errCode;\n    X509_STORE_CTX_free(storeCtx);\n    X509_STORE_free(x509Store);\n    return false;\n}\n\ninline bool verifyOpensslKeyCert(const std::string& filepath)\n{\n    bool privateKeyValid = false;\n    bool certValid = false;\n\n    std::cout << \"Checking certs in file \" << filepath << \"\\n\";\n\n    FILE* file = fopen(filepath.c_str(), \"r\");\n    if (file != nullptr)\n    {\n        EVP_PKEY* pkey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);\n        if (pkey != nullptr)\n        {\n#if (OPENSSL_VERSION_NUMBER < 0x30000000L)\n            RSA* rsa = EVP_PKEY_get1_RSA(pkey);\n            if (rsa != nullptr)\n            {\n                std::cout << \"Found an RSA key\\n\";\n                if (RSA_check_key(rsa) == 1)\n                {\n                    privateKeyValid = true;\n                }\n                else\n                {\n                    std::cerr << \"Key not valid error number \"\n                              << ERR_get_error() << \"\\n\";\n                }\n                RSA_free(rsa);\n            }\n            else\n            {\n                EC_KEY* ec = EVP_PKEY_get1_EC_KEY(pkey);\n                if (ec != nullptr)\n                {\n                    std::cout << \"Found an EC key\\n\";\n                    if (EC_KEY_check_key(ec) == 1)\n                    {\n                        privateKeyValid = true;\n                    }\n                    else\n                    {\n                        std::cerr << \"Key not valid error number \"\n                                  << ERR_get_error() << \"\\n\";\n                    }\n                    EC_KEY_free(ec);\n                }\n            }\n#else\n            EVP_PKEY_CTX* pkeyCtx =\n                EVP_PKEY_CTX_new_from_pkey(nullptr, pkey, nullptr);\n\n            if (pkeyCtx == nullptr)\n            {\n                std::cerr << \"Unable to allocate pkeyCtx \" << ERR_get_error()\n                          << \"\\n\";\n            }\n            else if (EVP_PKEY_check(pkeyCtx) == 1)\n            {\n                privateKeyValid = true;\n            }\n            else\n            {\n\n                std::cerr << \"Key not valid error number \" << ERR_get_error()\n                          << \"\\n\";\n            }\n#endif\n\n            if (privateKeyValid)\n            {\n                // If the order is certificate followed by key in input file\n                // then, certificate read will fail. So, setting the file\n                // pointer to point beginning of file to avoid certificate and\n                // key order issue.\n                fseek(file, 0, SEEK_SET);\n\n                X509* x509 = PEM_read_X509(file, nullptr, nullptr, nullptr);\n                if (x509 == nullptr)\n                {\n                    std::cout << \"error getting x509 cert \" << ERR_get_error()\n                              << \"\\n\";\n                }\n                else\n                {\n                    certValid = validateCertificate(x509);\n                    X509_free(x509);\n                }\n            }\n\n#if (OPENSSL_VERSION_NUMBER > 0x30000000L)\n            EVP_PKEY_CTX_free(pkeyCtx);\n#endif\n            EVP_PKEY_free(pkey);\n        }\n        fclose(file);\n    }\n    return certValid;\n}\n\ninline X509* loadCert(const std::string& filePath)\n{\n    BIO* certFileBio = BIO_new_file(filePath.c_str(), \"rb\");\n    if (certFileBio == nullptr)\n    {\n        BMCWEB_LOG_ERROR << \"Error occured during BIO_new_file call, \"\n                         << \"FILE= \" << filePath;\n        return nullptr;\n    }\n\n    X509* cert = X509_new();\n    if (cert == nullptr)\n    {\n        BMCWEB_LOG_ERROR << \"Error occured during X509_new call, \"\n                         << ERR_get_error();\n        BIO_free(certFileBio);\n        return nullptr;\n    }\n\n    if (PEM_read_bio_X509(certFileBio, &cert, nullptr, nullptr) == nullptr)\n    {\n        BMCWEB_LOG_ERROR << \"Error occured during PEM_read_bio_X509 call, \"\n                         << \"FILE= \" << filePath;\n\n        BIO_free(certFileBio);\n        X509_free(cert);\n        return nullptr;\n    }\n    BIO_free(certFileBio);\n    return cert;\n}\n\ninline int addExt(X509* cert, int nid, const char* value)\n{\n    X509_EXTENSION* ex = nullptr;\n    X509V3_CTX ctx{};\n    X509V3_set_ctx(&ctx, cert, cert, nullptr, nullptr, 0);\n\n    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)\n    ex = X509V3_EXT_conf_nid(nullptr, &ctx, nid, const_cast<char*>(value));\n    if (ex == nullptr)\n    {\n        BMCWEB_LOG_ERROR << \"Error: In X509V3_EXT_conf_nidn: \" << value;\n        return -1;\n    }\n    X509_add_ext(cert, ex, -1);\n    X509_EXTENSION_free(ex);\n    return 0;\n}\n\ninline void generateSslCertificate(const std::string& filepath,\n                                   const std::string& cn)\n{\n    FILE* pFile = nullptr;\n    std::cout << \"Generating new keys\\n\";\n    initOpenssl();\n\n    std::cerr << \"Generating EC key\\n\";\n    EVP_PKEY* pPrivKey = createEcKey();\n    if (pPrivKey != nullptr)\n    {\n        std::cerr << \"Generating x509 Certificate\\n\";\n        // Use this code to directly generate a certificate\n        X509* x509 = X509_new();\n        if (x509 != nullptr)\n        {\n            // get a random number from the RNG for the certificate serial\n            // number If this is not random, regenerating certs throws broswer\n            // errors\n            bmcweb::OpenSSLGenerator gen;\n            std::uniform_int_distribution<int> dis(\n                1, std::numeric_limits<int>::max());\n            int serial = dis(gen);\n\n            ASN1_INTEGER_set(X509_get_serialNumber(x509), serial);\n\n            // not before this moment\n            X509_gmtime_adj(X509_get_notBefore(x509), 0);\n            // Cert is valid for 10 years\n            X509_gmtime_adj(X509_get_notAfter(x509),\n                            60L * 60L * 24L * 365L * 10L);\n\n            // set the public key to the key we just generated\n            X509_set_pubkey(x509, pPrivKey);\n\n            // get the subject name\n            X509_NAME* name = X509_get_subject_name(x509);\n\n            using x509String = const unsigned char;\n            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)\n            x509String* country = reinterpret_cast<x509String*>(\"US\");\n            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)\n            x509String* company = reinterpret_cast<x509String*>(\"OpenBMC\");\n            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)\n            x509String* cnStr = reinterpret_cast<x509String*>(cn.c_str());\n\n            X509_NAME_add_entry_by_txt(name, \"C\", MBSTRING_ASC, country, -1, -1,\n                                       0);\n            X509_NAME_add_entry_by_txt(name, \"O\", MBSTRING_ASC, company, -1, -1,\n                                       0);\n            X509_NAME_add_entry_by_txt(name, \"CN\", MBSTRING_ASC, cnStr, -1, -1,\n                                       0);\n            // set the CSR options\n            X509_set_issuer_name(x509, name);\n\n            X509_set_version(x509, 2);\n            addExt(x509, NID_basic_constraints, (\"critical,CA:TRUE\"));\n            addExt(x509, NID_subject_alt_name, (\"DNS:\" + cn).c_str());\n            addExt(x509, NID_subject_key_identifier, (\"hash\"));\n            addExt(x509, NID_authority_key_identifier, (\"keyid\"));\n            addExt(x509, NID_key_usage, (\"digitalSignature, keyEncipherment\"));\n            addExt(x509, NID_ext_key_usage, (\"serverAuth\"));\n            addExt(x509, NID_netscape_comment, (x509Comment));\n\n            // Sign the certificate with our private key\n            X509_sign(x509, pPrivKey, EVP_sha256());\n\n            pFile = fopen(filepath.c_str(), \"wt\");\n\n            if (pFile != nullptr)\n            {\n                PEM_write_PrivateKey(pFile, pPrivKey, nullptr, nullptr, 0,\n                                     nullptr, nullptr);\n\n                PEM_write_X509(pFile, x509);\n                fclose(pFile);\n                pFile = nullptr;\n            }\n\n            X509_free(x509);\n        }\n\n        EVP_PKEY_free(pPrivKey);\n        pPrivKey = nullptr;\n    }\n\n    // cleanup_openssl();\n}\n\nEVP_PKEY* createEcKey()\n{\n    EVP_PKEY* pKey = nullptr;\n\n#if (OPENSSL_VERSION_NUMBER < 0x30000000L)\n    int eccgrp = 0;\n    eccgrp = OBJ_txt2nid(\"secp384r1\");\n\n    EC_KEY* myecc = EC_KEY_new_by_curve_name(eccgrp);\n    if (myecc != nullptr)\n    {\n        EC_KEY_set_asn1_flag(myecc, OPENSSL_EC_NAMED_CURVE);\n        EC_KEY_generate_key(myecc);\n        pKey = EVP_PKEY_new();\n        if (pKey != nullptr)\n        {\n            if (EVP_PKEY_assign(pKey, EVP_PKEY_EC, myecc) != 0)\n            {\n                /* pKey owns myecc from now */\n                if (EC_KEY_check_key(myecc) <= 0)\n                {\n                    std::cerr << \"EC_check_key failed.\\n\";\n                }\n            }\n        }\n    }\n#else\n    // Create context for curve parameter generation.\n    std::unique_ptr<EVP_PKEY_CTX, decltype(&::EVP_PKEY_CTX_free)> ctx{\n        EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr), &::EVP_PKEY_CTX_free};\n    if (!ctx)\n    {\n        return nullptr;\n    }\n\n    // Set up curve parameters.\n    EVP_PKEY* params = nullptr;\n    if ((EVP_PKEY_paramgen_init(ctx.get()) <= 0) ||\n        (EVP_PKEY_CTX_set_ec_param_enc(ctx.get(), OPENSSL_EC_NAMED_CURVE) <=\n         0) ||\n        (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx.get(), NID_secp384r1) <=\n         0) ||\n        (EVP_PKEY_paramgen(ctx.get(), &params) <= 0))\n    {\n        return nullptr;\n    }\n\n    // Set up RAII holder for params.\n    std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)> pparams{\n        params, &::EVP_PKEY_free};\n\n    // Set new context for key generation, using curve parameters.\n    ctx.reset(EVP_PKEY_CTX_new_from_pkey(nullptr, params, nullptr));\n    if (!ctx || (EVP_PKEY_keygen_init(ctx.get()) <= 0))\n    {\n        return nullptr;\n    }\n\n    // Generate key.\n    if (EVP_PKEY_keygen(ctx.get(), &pKey) <= 0)\n    {\n        return nullptr;\n    }\n#endif\n\n    return pKey;\n}\n\nvoid initOpenssl()\n{\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    SSL_load_error_strings();\n    OpenSSL_add_all_algorithms();\n    RAND_load_file(\"/dev/urandom\", 1024);\n#endif\n}\n\ninline void ensureOpensslKeyPresentAndValid(const std::string& filepath)\n{\n    bool pemFileValid = false;\n\n    pemFileValid = verifyOpensslKeyCert(filepath);\n\n    if (!pemFileValid)\n    {\n        std::cerr << \"Error in verifying signature, regenerating\\n\";\n        generateSslCertificate(filepath, \"testhost\");\n    }\n}\n\ninline std::shared_ptr<boost::asio::ssl::context>\n    getSslContext(const std::string& sslPemFile)\n{\n    std::shared_ptr<boost::asio::ssl::context> mSslContext =\n        std::make_shared<boost::asio::ssl::context>(\n            boost::asio::ssl::context::tls_server);\n    mSslContext->set_options(boost::asio::ssl::context::default_workarounds |\n                             boost::asio::ssl::context::no_sslv2 |\n                             boost::asio::ssl::context::no_sslv3 |\n                             boost::asio::ssl::context::single_dh_use |\n                             boost::asio::ssl::context::no_tlsv1 |\n                             boost::asio::ssl::context::no_tlsv1_1);\n\n    // BIG WARNING: This needs to stay disabled, as there will always be\n    // unauthenticated endpoints\n    // mSslContext->set_verify_mode(boost::asio::ssl::verify_peer);\n\n    SSL_CTX_set_options(mSslContext->native_handle(), SSL_OP_NO_RENEGOTIATION);\n\n    BMCWEB_LOG_DEBUG << \"Using default TrustStore location: \" << trustStorePath;\n    mSslContext->add_verify_path(trustStorePath);\n\n    mSslContext->use_certificate_file(sslPemFile,\n                                      boost::asio::ssl::context::pem);\n    mSslContext->use_private_key_file(sslPemFile,\n                                      boost::asio::ssl::context::pem);\n\n    // Set up EC curves to auto (boost asio doesn't have a method for this)\n    // There is a pull request to add this.  Once this is included in an asio\n    // drop, use the right way\n    // http://stackoverflow.com/questions/18929049/boost-asio-with-ecdsa-certificate-issue\n    if (SSL_CTX_set_ecdh_auto(mSslContext->native_handle(), 1) != 1)\n    {\n        BMCWEB_LOG_ERROR << \"Error setting tmp ecdh list\\n\";\n    }\n\n    std::string mozillaModern = \"ECDHE-ECDSA-AES256-GCM-SHA384:\"\n                                \"ECDHE-RSA-AES256-GCM-SHA384:\"\n                                \"ECDHE-ECDSA-CHACHA20-POLY1305:\"\n                                \"ECDHE-RSA-CHACHA20-POLY1305:\"\n                                \"ECDHE-ECDSA-AES128-GCM-SHA256:\"\n                                \"ECDHE-RSA-AES128-GCM-SHA256:\"\n                                \"ECDHE-ECDSA-AES256-SHA384:\"\n                                \"ECDHE-RSA-AES256-SHA384:\"\n                                \"ECDHE-ECDSA-AES128-SHA256:\"\n                                \"ECDHE-RSA-AES128-SHA256\";\n\n    if (SSL_CTX_set_cipher_list(mSslContext->native_handle(),\n                                mozillaModern.c_str()) != 1)\n    {\n        BMCWEB_LOG_ERROR << \"Error setting cipher list\\n\";\n    }\n    return mSslContext;\n}\n} // namespace ensuressl\n", "meta": {"hexsha": "431dd84d3ac98adb2746445a66f3b42c20c8a061", "size": 15723, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ssl_key_handler.hpp", "max_stars_repo_name": "cjcain/bmcweb", "max_stars_repo_head_hexsha": "80badf7ceff486ef2bcb912309563919fc5326ea", "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/ssl_key_handler.hpp", "max_issues_repo_name": "cjcain/bmcweb", "max_issues_repo_head_hexsha": "80badf7ceff486ef2bcb912309563919fc5326ea", "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/ssl_key_handler.hpp", "max_forks_repo_name": "cjcain/bmcweb", "max_forks_repo_head_hexsha": "80badf7ceff486ef2bcb912309563919fc5326ea", "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.8933054393, "max_line_length": 90, "alphanum_fraction": 0.5591808179, "num_tokens": 3834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.16895230503958528}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <moreorg/OrganizationModel.hpp>\n#include <moreorg/OrganizationModelAsk.hpp>\n#include <moreorg/facades/Robot.hpp>\n#include <moreorg/PropertyConstraintSolver.hpp>\n#include <moreorg/vocabularies/OM.hpp>\n#include \"test_utils.hpp\"\n\nusing namespace moreorg;\nusing namespace owlapi::model;\n\nBOOST_AUTO_TEST_SUITE(property_constraint_solver)\n\nBOOST_AUTO_TEST_CASE(value_bound)\n{\n    owlapi::model::IRI propertyA(\"http://test/propertyA\");\n    PropertyConstraint pcA0(propertyA, PropertyConstraint::GREATER_EQUAL, 3.0);\n    PropertyConstraint pcA1(propertyA, PropertyConstraint::LESS_THAN, 10.0);\n    PropertyConstraint pcA2(propertyA, PropertyConstraint::LESS_THAN, 8.5);\n    PropertyConstraint pcA3(propertyA, PropertyConstraint::LESS_THAN, 2.5);\n\n    {\n        PropertyConstraint::List constraints =  { pcA0, pcA1, pcA2 };\n        ValueBound vb = PropertyConstraintSolver::merge(constraints);\n\n        BOOST_REQUIRE_MESSAGE(vb.getMin() == 3.0, \"Min is set to \" << vb.getMin() << \" expected \" << 3.0);\n        BOOST_REQUIRE_MESSAGE(vb.getMax() == 8.5, \"Max is set to \" << vb.getMax() << \" expected \" << 8.5);\n    }\n    {\n        PropertyConstraint::List constraints =  { pcA0, pcA1, pcA2, pcA3 };\n        BOOST_REQUIRE_THROW(PropertyConstraintSolver::merge(constraints), std::invalid_argument);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(fulfillment)\n{\n    //std::string filename = \"\" + getRootDir() +\n    //    \"/test/data/om-robot-sherpa-tt.ttl\";\n    std::string filename = \"\" + getRootDir() + \"/test/data/test-load-area.ttl\";\n    OrganizationModel::Ptr organizationModel = make_shared<OrganizationModel>(filename);\n\n    owlapi::model::IRI sherpaTT = vocabulary::OM::resolve(\"SherpaTT\");\n\n    ModelPool pool;\n    pool[sherpaTT] = 1;\n\n    OrganizationModelAsk ask(organizationModel, pool, true);\n    facades::Robot robot = facades::Robot::getInstance(pool, ask);\n\n\n    BOOST_REQUIRE_MESSAGE( robot.getPowerSourceCapacity() != 0, \"SherpaTT has \"\n            \" power source capacity\");\n\n    BOOST_REQUIRE_MESSAGE( robot.getLoadArea() == 0.15*0.15, \"SherpaTT has load area\");\n    {\n        PropertyConstraint massC0(vocabulary::OM::mass(), PropertyConstraint::GREATER_EQUAL, 100.0);\n        BOOST_REQUIRE_MESSAGE(!massC0.usesPropertyReference(), \"Is not a self referencing constraint\");\n        BOOST_REQUIRE_MESSAGE(massC0.getReferenceValue(robot) == 100.0, \"Property reference mass\");\n\n        Fulfillment f = PropertyConstraintSolver::fulfills(robot, PropertyConstraint::Set{ massC0 });\n        BOOST_REQUIRE_MESSAGE(f.isMet(), \"SherpaTT has a mass greater than 100.0 kg\");\n    }\n\n    {\n        PropertyConstraint massC1(vocabulary::OM::mass(), PropertyConstraint::LESS_THAN, 50.0);\n        Fulfillment f = PropertyConstraintSolver::fulfills(robot, PropertyConstraint::List{ massC1 });\n        BOOST_REQUIRE_MESSAGE(!f.isMet(), \"SherpaTT has not a mass less than 50.0 kg\");\n    }\n\n    {\n        PropertyConstraint massC1(vocabulary::OM::resolve(\"loadAreaSize\"), PropertyConstraint::GREATER_THAN, 0.1);\n        Fulfillment f = PropertyConstraintSolver::fulfills(robot, PropertyConstraint::List{ massC1 });\n        BOOST_REQUIRE_MESSAGE(!f.isMet(), \"SherpaTT has a load area > 0.1 cm^2\");\n    }\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "98646fe977ce27910d19d5dcbf6d7c06afbf7e0a", "size": 3251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_PropertyConstraintSolver.cpp", "max_stars_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_stars_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "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": "test/test_PropertyConstraintSolver.cpp", "max_issues_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_issues_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-26T11:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T19:16:10.000Z", "max_forks_repo_path": "test/test_PropertyConstraintSolver.cpp", "max_forks_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_forks_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T13:02:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T13:02:49.000Z", "avg_line_length": 40.6375, "max_line_length": 114, "alphanum_fraction": 0.7074746232, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.16895230165428024}}
{"text": "#ifndef BASECORRESPONDENCEFILTER_HPP\n#define BASECORRESPONDENCEFILTER_HPP\n\n\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include \"../global.hpp\"\n#include <iostream>\n\ntypedef Eigen::VectorXf VecDynFloat;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat; //matrix Mx6 of type float\ntypedef Eigen::Matrix< float, 1, registration::NUM_FEATURES> FeatureVec; //matrix Mx6 of type float\ntypedef Eigen::Vector3f Vec3Float;\ntypedef Eigen::SparseMatrix<float, 0, int> SparseMat;\ntypedef Eigen::Triplet<float> Triplet;\ntypedef Eigen::Matrix< int, Eigen::Dynamic, Eigen::Dynamic> MatDynInt; //matrix MxN of type unsigned int\ntypedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic> MatDynFloat;\n\nnamespace registration {\n\nclass BaseCorrespondenceFilter\n{\n    /*\n    # GOAL\n    This class serves as the base class for the correspondence filter classes.\n\n    */\n\n    public:\n        BaseCorrespondenceFilter();\n        virtual ~BaseCorrespondenceFilter();\n\n        virtual void set_floating_input(const FeatureMat * const inFloatingFeatures,\n                                const VecDynFloat * const inFloatingFlags){}\n        virtual void set_target_input(const FeatureMat * const inTargetFeatures,\n                            const VecDynFloat * const inTargetFlags){}\n        void set_output(FeatureMat * const ioCorrespondingFeatures,\n                        VecDynFloat * const ioCorrespondingFlags);\n        SparseMat get_affinity() const {return _affinity;}\n        virtual void set_parameters(const size_t numNeighbours,\n                                    const float flagThreshold){}\n        virtual void set_parameters(const size_t numNeighbours,\n                                    const float flagThreshold,\n                                    const bool equalizePushPull){}\n        virtual void update(){}\n\n    protected:\n\n        //# Inputs\n        const FeatureMat * _inFloatingFeatures = NULL;\n        const VecDynFloat * _inFloatingFlags = NULL; //currently never used (only in the symmetric version)\n        const FeatureMat * _inTargetFeatures = NULL;\n        const VecDynFloat * _inTargetFlags = NULL;\n\n        //# Outputs\n        FeatureMat * _ioCorrespondingFeatures = NULL;\n        VecDynFloat * _ioCorrespondingFlags = NULL;\n\n        //# User Parameters\n        size_t _numNeighbours = 3;\n        float _flagThreshold = 0.99f;\n\n        //# Internal Data structures\n        SparseMat _affinity;\n\n        //# Internal Parameters\n        size_t _numFloatingElements = 0;\n        size_t _numTargetElements = 0;\n\n        //# Internal functions\n        //## Function to update the sparse affinity matrix\n        virtual void _update_affinity(){};\n        //## Function to convert the sparse affinity weights into corresponding\n        //## features and flags\n        void _affinity_to_correspondences();\n\n    private:\n\n\n};\n\n}//namespace registration\n#endif // BASECORRESPONDENCEFILTER_HPP\n", "meta": {"hexsha": "dfc23936b89cc776f46a5c439eaaf9edf4651ff9", "size": 2942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/BaseCorrespondenceFilter.hpp", "max_stars_repo_name": "brisyramshere/meshmonk", "max_stars_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T14:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T05:40:58.000Z", "max_issues_repo_path": "src/BaseCorrespondenceFilter.hpp", "max_issues_repo_name": "brisyramshere/meshmonk", "max_issues_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T10:34:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T04:37:12.000Z", "max_forks_repo_path": "src/BaseCorrespondenceFilter.hpp", "max_forks_repo_name": "brisyramshere/meshmonk", "max_forks_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-07-05T14:59:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T07:01:47.000Z", "avg_line_length": 35.0238095238, "max_line_length": 112, "alphanum_fraction": 0.6692726037, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.16878478377959708}}
{"text": "#include <iostream>\n#include <ros/ros.h>\n#include \"humanoid_league_msgs/GoalRelative.h\"\n#include \"humanoid_league_msgs/LineInformationRelative.h\"\n#include <sensor_msgs/PointCloud2.h>\n#include <nav_msgs/Odometry.h>//quick walking node \n#include \"humanoid_league_msgs/TeamData.h\"\n#include \"humanoid_league_msgs/GameState.h\"\n#include \"humanoid_league_msgs/ObstaclesRelative.h\"\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n\nint main( int argc, char **argv )\n{\n\tros::init(argc, argv, \"test_node\");\n\tros::NodeHandle n;\n\n\t/*\u901a\u8fc7\"testData\"Node\u4eff\u771f\u53d1\u9001\u4e0b\u5217messages\uff0c\u5176\u4e2d\"visual_odometry\" \"visualCompass\"\u5728bitbots_meta\u4e2d\u5c1a\u672a\u66f4\u65b0\u3002*/\n\tros::Publisher pubTeamData = n.advertise<humanoid_league_msgs::TeamData>(\"teamdata_topic\",10);\n\tros::Publisher pubGoalRelative = n.advertise<humanoid_league_msgs::GoalRelative>(\"goal_relative\",10);\n\tros::Publisher pubObsRelative = n.advertise<humanoid_league_msgs::ObstaclesRelative>(\"obstacles_relative\",10);\n\tros::Publisher pubLineInformationRelative = n.advertise<humanoid_league_msgs::LineInformationRelative>(\"line_relative\",10);\n\tros::Publisher pubWlakOdometry = n.advertise<nav_msgs::Odometry>(\"walk_odometry\",10);\n\tros::Publisher pubVisualOdometry = n.advertise<nav_msgs::Odometry>(\"visual_odometry\",10);\n\tros::Publisher pubPointCloud2 = n.advertise<sensor_msgs::PointCloud2>(\"line_relative_pc\",10);\n\tros::Publisher pubGameState = n.advertise<humanoid_league_msgs::GameState>(\"gamestate\",10);\n//\tros::Publisher pubVisualCompass = n.advertise<>();\n//\tros::Publisher pubBallRelative = n.advertise<humanoid_league_msgs::BallRelative>(\"ball_relative\",10);\n\n\tMatrix<float, 24, 7> MatrixGoal;\n\tMatrix<float,  9, 6> MatrixObs;\n\tMatrix<float,  6, 2> MatrixSegstart;\n\tMatrix<float,  6, 2> MatrixSegend;\n\tMatrix<float,  6, 6> MatrixCircle;\n\t//lx, ly, rx, ry, cx, cy, c\n\tMatrixGoal << //fake data:\u4e03\u4e2a\u4e00\u7ec4\uff0c\u5206\u522b\u5bf9\u5e94\u4e0a\u8ff0\u503c\u3002\n\t\t4, 2, 4, 4, 4, 3, 1, \t      4, 2, 4, 4, 4, 3, 1, \t\t4, 2, 4, 4, 4, 3, 1, \t\t4, 2, 4, 4, 4, 3, 1,\n            \t4, 2, 4, 4, 4, 3, 1, \t      4, 2, 4, 4, 4, 3, 1, \t\t4, 2, 4, 4, 4, 3, 1, \t\t4, 2, 4, 4, 4, 3, 1,\n            \t4, 2, 4, 4, 4, 3, 1, \t      4, 2, 4, 4, 4, 3, 1, \t\t4, 2, 4, 4, 4, 3, 1, \t\t4, 2, 4, 4, 4, 3, 1,\n            \t4, 2, 4, 4, 4, 3, 1, \t      4, 2, 4, 4, 4, 3, 1, \t\t4, 2, 4, 4, 4, 3, 1, \t\t4, 2, 4, 4, 4, 3, 1,\n            \t3.9, 2, 3.9, 3.9, 4, 3, 1,    3.7, 2, 3.7, 4, 3.7, 3, 1,        3.5, 2, 3.5, 4, 3.5, 3, 1,\n            \t3.3, 2, 3.3, 4, 3.3, 3, 1,    3.1, 2, 3.1, 4, 3.1, 3, 1,        2.9, 2, 2.9, 4, 2.9, 3, 1,\n            \t2.7, 2, 2.7, 4, 2.7, 3, 1,    2.5, 2, 2.5, 4, 2.5, 3, 1;\n\n\t//x, y, w, h, t, c\n\tMatrixObs <<    0.5, -2,   0.5, 0.5, 3, 0.7, \t0.8, -2,   0.5, 0.5, 3, 0.7,\n            \t\t1,   -2,   0.5, 0.5, 3, 0.7, \t1.2, -2,   0.5, 0.5, 3, 0.7,\n            \t\t1.2, -2.2, 0.5, 0.5, 3, 0.7, \t1.2, -2.5, 0.5, 0.5, 3, 0.7,\n            \t\t1.2, -2.7, 0.5, 0.5, 3, 0.7, \t1.0, -2.5, 0.5, 0.5, 3, 0.7,\n        \t\t0.8, -2.3, 0.5, 0.5, 3, 0.7 ;\n\t\n\t//\u7ebf\u7684\u8d77\u70b9\u5750\u6807\uff0c\u4e24\u4e2a\u503c\u4e00\u7ec4\n\tMatrixSegstart <<  0,0,   0,0,   0,0,   0,0,   0,0,   0,0;//TODO:1.make data,2.declear it\n\t//\u7ebf\u7684\u7ec8\u70b9\uff0c\u4e24\u4e2a\u503c\u4e00\u7ec4\n\tMatrixSegend   <<  0,0,   0,0,   0,0,   0,0,   0,0,   0,0;\n\t//\u4e09\u4e2a\u70b9\u786e\u5b9a\u4e00\u4e2a\u5706\uff0c\u516d\u4e2a\u503c\u4e00\u7ec4\uff0c\u5206\u522b\u662f\u5de6\u70b9\uff0c\u4e2d\u70b9\uff0c\u53f3\u70b9\n\tMatrixCircle <<    0,0,0,0,0,0,   0,0,0,0,0,0,   0,0,0,0,0,0,   0,0,0,0,0,0,   0,0,0,0,0,0,   0,0,0,0,0,0;\n\t\n\thumanoid_league_msgs::GoalRelative goal;\n\thumanoid_league_msgs::TeamData team;\n\thumanoid_league_msgs::ObstacleRelative obs;\n\tstd::vector<humanoid_league_msgs::ObstacleRelative> Obs;\n\thumanoid_league_msgs::ObstaclesRelative obstacle;\n\thumanoid_league_msgs::LineSegmentRelative linesegment;\n\tstd::vector<humanoid_league_msgs::LineSegmentRelative> lineSegment;\n\thumanoid_league_msgs::LineIntersectionRelative lineinter;\n\tstd::vector<humanoid_league_msgs::LineIntersectionRelative> lineInter;\n\thumanoid_league_msgs::LineCircleRelative linecircle;\n\tstd::vector<humanoid_league_msgs::LineCircleRelative> lineCircle;\n\thumanoid_league_msgs::LineInformationRelative line;\n\thumanoid_league_msgs::GameState gamestate;\n\tint timeCounter = 30;\n\tbool firsthalf = true; \n\tint durationHalfGame = 60;\n\n\tros::Rate loop_rate(10);\n\twhile(ros::ok())\n\t{\n\t\tfor(int i = 0; i < MatrixGoal.rows(); i++)\n\t\t{\n\t\t\tgoal.header.seq = i;\n\t\t\tgoal.header.stamp = ros::Time::now();\n\t\t\tgoal.header.frame_id = \"base_footprint\";\n\t\t\tgoal.left_post.x = MatrixGoal(i,0);\n\t\t\tgoal.left_post.y = MatrixGoal(i,1);\n\t\t\tgoal.right_post.x = MatrixGoal(i,2);\n\t\t\tgoal.right_post.y = MatrixGoal(i,3);\n\t\t\tgoal.center_direction.x = MatrixGoal(i,4);\n\t\t\tgoal.center_direction.y = MatrixGoal(i,5);\n\t\t\tgoal.confidence = MatrixGoal(i,6);\n\n\t\t\tif(i<MatrixObs.rows())\n\t\t\t{\n\t\t\t\tobs.playerNumber = -1;\n\t\t\t\tobs.position.x = MatrixObs(i,0);//Point\n\t\t\t\tobs.position.y = MatrixObs(i,1);\n\t\t\t\tobs.width = MatrixObs(i,2);\n\t\t\t\tobs.height = MatrixObs(i,3);\n\t\t\t\tobs.color = MatrixObs(i,4);\n\t\t\t\tobs.confidence = MatrixObs(i,5);\n\t\t\t\tObs.push_back(obs);\n\t\t\t\tobstacle.header.stamp = ros::Time::now();\n\t\t\t\tobstacle.header.frame_id = \"base_footprint\";\n\t\t\t\tobstacle.obstacles = Obs;\n\t\t\t}\n\t\t\n\t\t\tif(i<6)\n\t\t\t{\t\n\t\t\t\tfor(int j = 0; j < 6; j++ )\t\n\t\t\t\t{\n\t\t\t\t\tfor(int k = 0; k < 6; k++ )\n\t\t\t\t\t{\t\n\t\t\t\t\t\tlinesegment.start.x = MatrixSegstart(k,0);\n\t\t\t\t\t\tlinesegment.start.y = MatrixSegstart(k,1);\n\t\t\t\t\t\tlinesegment.end.x = MatrixSegend(k,0);\n\t\t\t\t\t\tlinesegment.end.y = MatrixSegend(k,1);\n\t\t\t\t\t\tlinesegment.confidence = 1;\n\t\t\t\t\t\tlineSegment.push_back(linesegment);\n\t\t\t\t\t}\n\t\t\t\t\tlineinter.segments = lineSegment;\n\t\t\t\t\tlineinter.type = 0;\n\t\t\t\t\tlineinter.confidence = 1;\n\t\t\t\t}\n\t\t\t\tlineInter.push_back(lineinter);\n\t\t\t}\n\n\t\t\tif(i<6)\n\t\t\t{\n\t\t\t\tlinecircle.left.x = MatrixCircle(i,0);\n\t\t\t\tlinecircle.left.y = MatrixCircle(i,1);\n\t\t\t\tlinecircle.middle.x = MatrixCircle(i,2);\n\t\t\t\tlinecircle.middle.y = MatrixCircle(i,3);\n\t\t\t\tlinecircle.right.x = MatrixCircle(i,4);\n\t\t\t\tlinecircle.right.y = MatrixCircle(i,5);\n\t\t\t\tlinecircle.confidence = 1;\n\t\t\t\tlineCircle.push_back(linecircle);\n\t\t\t}\n\t\t\n\t\t\t\n\t\t\tgamestate.header.frame_id = i;\n\t\t\tgamestate.header.stamp = ros::Time::now();\n\t\t\tgamestate.secondaryState = 0;\n\t\t\tgamestate.secondsTillUnpenalized = timeCounter;\n        \t\t// Penalty boolean\n        \t\tgamestate.penalized = timeCounter > 0\t;\n        \t\t// Sets halftime and rest secs\n        \t\tgamestate.firstHalf = firsthalf;\n        \t\tgamestate.secondsRemaining = durationHalfGame;\n        \t\t// Sets Score\n        \t\tgamestate.ownScore = 7;\n        \t\tgamestate.rivalScore = 1;\n        \t\t// team colors\n        \t\tgamestate.teamColor = 1;// magenta\t\n\t\t\ttimeCounter -= 1;\n       \t\t\tif(timeCounter < 0)\n\t\t\t{\n\t\t\t\ttimeCounter = 0;\n\t\t\t}\n      \t \t \tdurationHalfGame -= 1;\n       \t\t \tif(durationHalfGame == 0)\n\t\t\t{\n\t\t\t\tdurationHalfGame = 60;\n            \t\t\tfirsthalf = false;\n\t\t\t}\n\t\t\tline.intersections = lineInter;\n\t\t\tline.segments = lineSegment;\n\t\t\tline.circles = lineCircle;\n\t\t\tobstacle.obstacles = Obs;\n\t\t\tpubGoalRelative.publish(goal);\n\t\t\tpubObsRelative.publish(obstacle);\n\t\t\tpubLineInformationRelative.publish(line);\n\t\t\tpubGameState.publish(gamestate);\n\t\t\tloop_rate.sleep();\n\t\t}\n\t}\n}\n                        /*\n                        //bitbots_meta TODO;\n                        iteam.header.seq = ;\n                        team.header.stamp = ros::Time::now();\n                        team.header.frame_id = ;\n                        team.robot_ids[3];\n                        team.role[2];\n                        team.action[1];\n                        team.state[1];\n                        team.robot_positions = ;//\u6570\u7ec4\n                        team.oppgoal_relative = ;//\u6570\u7ec4\n                        team.avg_walking_speed = ;\n                        team.time_to_position_at_ball = ;\n                        team.max_kicking_distance = ;\n                        pubTeamData.publish(team);\n\n                        nav_msgs::Odometry walkodom;\n                        walkodom.header.seq = ;\n                        walkodom.header.stamp = ros::Time::now();\n                        walkodomm.header.frame_id = ;\n                        walkodom.string_child_frame_id = ;\n                        walkodom.pose = ;//geometry_msgs/PoseWithCovariance\n                        walkodom.twist = ;//geometry_msgs/TwistWithCovariance\n                        pubWlakOdometry.publish(walkodom);\n\n                        sensor_msgs::PointCloud2 line;\n                        line.header.seq = ;\n                        line.header.stamp = ros::Time::now();\n                        line.header.frame_id = ;\n                        line.height = ;\n                        line.width = ;\n                        line.fields = ;//sensor_msgs/PointField[]\n                        line.is_bigendian = ;//bool\n                        line.point_step = ;\n                        line.row_step = ;\n                        line.data = ;\n                        line.is_dense = ;//bool\n                        */\n\n", "meta": {"hexsha": "b4f122c84b4be80350fd06a0438d336144648c2b", "size": 8692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "msgs/src/Pubmsgs.cpp", "max_stars_repo_name": "Zcyyy/bitbots_meta", "max_stars_repo_head_hexsha": "7e921d2f46d2e196d3b8212fcaeeca5df5291134", "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": "msgs/src/Pubmsgs.cpp", "max_issues_repo_name": "Zcyyy/bitbots_meta", "max_issues_repo_head_hexsha": "7e921d2f46d2e196d3b8212fcaeeca5df5291134", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "msgs/src/Pubmsgs.cpp", "max_forks_repo_name": "Zcyyy/bitbots_meta", "max_forks_repo_head_hexsha": "7e921d2f46d2e196d3b8212fcaeeca5df5291134", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-01T11:30:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-01T11:30:25.000Z", "avg_line_length": 39.6894977169, "max_line_length": 124, "alphanum_fraction": 0.5801886792, "num_tokens": 2947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.16878478377959705}}
{"text": "//\n// Created by James on 10/31/2021.\n//\n\n#include <stakepool.h>\n\n#include <validator.h>\n#include <stakeparams.h>\n#include <consensus/amount.h>\n#include <chain.h>\n#include <cmath>\n#include <crypto/sha256.h>\n#include <script/script.h>\n#include <boost/crc.hpp>\n#include <float.h>\n#include <vector>\n#include <unordered_map>\n#include <script/script.h>\n\nStakePool::StakePool() {\n    totalStake = 0;\n    lastValidationTime = 0;\n}\n\nbool StakePool::addValidator(Validator* validator, int nHeight, std::vector<std::string>* rterror) {\n    if (validatorExists(validator)) {\n        rterror->push_back(\"Validator exists\");\n        return false;\n    }\n\n    validatorPool.push_back(validator);\n    validatorPoolScript[validator->scriptPubKey.ToString()] = validator;\n    return recalculateProbabilities(nHeight, rterror);\n}\n\nbool StakePool::removeValidator(Validator* validator, int nHeight, std::vector<std::string>* rterror) {\n    if (validator->suspended) {\n        rterror->push_back(\"Validator suspended\");\n        return false;\n    }\n\n    if (!validatorExists(validator)) {\n        rterror->push_back(\"Validator does not exist\");\n        return false;\n    }\n\n    auto it = validatorPoolScript.find(validator->scriptPubKey.ToString());\n    for (size_t i = 0; i < validatorPool.size(); i++) {\n        if (it->second == validatorPool.at(i)) {\n            validatorPool.erase(validatorPool.begin()+i);\n            break;\n        }\n    }\n    validatorPoolScript.erase(it);\n    return recalculateProbabilities(nHeight, rterror);\n}\n\nbool StakePool::recalculateProbabilities(int nHeight, std::vector<std::string>* rterror) {\n    totalStake = 0;\n    for (Validator* v : validatorPool) {\n        if (v->suspended) {\n            int elapsedTime = nHeight - v->suspendedBlock;\n            if (elapsedTime >= VALIDATOR_SUSPENSION_DURATION) {\n                unsuspendValidator(v, nHeight, rterror);\n\n            }\n        }\n\n        if (!v->suspended){\n            v->adjustStake(nHeight);\n            totalStake += v->adjustedStake;\n        }\n    }\n\n    for (Validator* v : validatorPool) {\n        v->calculateProbability(totalStake);\n    }\n    sort(nHeight);\n    return true;\n}\n\nValidator* StakePool::retrieveNextValidator(int nHeight, std::vector<std::string>* rterror) {\n    recalculateProbabilities(nHeight, rterror);\n    \n    vData.clear();\n    serialize();\n\n    boost::crc_32_type hasher;\n    std::string s(vData.begin(), vData.end());\n    hasher.process_bytes(s.data(), s.length());\n    double result = abs((double) hasher.checksum());\n\n    double selection = result / DBL_MAX;\n    Validator* selectedValidator = nullptr;\n\n    double probabilitiesSummed = 0.0;\n    for (Validator* v : validatorPool) {\n        probabilitiesSummed += v->probability;\n        if (selection <= probabilitiesSummed) {\n            selectedValidator = v;\n            break;\n        }\n    }\n\n    if (selectedValidator == nullptr) {\n        rterror->push_back(\"No validator found\");\n    }\n\n    return selectedValidator;\n}\n\nvoid StakePool::serialize() {\n    vData.clear();\n    for (Validator* v : validatorPool) {\n        std::vector<unsigned char> s = ToByteVector(v->scriptPubKey);\n        vData.insert(vData.end(), s.front(), s.back());\n    }\n}\n\nvoid StakePool::sort(int nHeight) {\n    std::sort(validatorPool.begin(), validatorPool.end(), std::greater<Validator*>());\n}\n\nbool StakePool::validatorExists(Validator* v) {\n    return validatorPoolScript.count(v->scriptPubKey.ToString()) == 1;\n}\n\nbool StakePool::suspendValidator(Validator *v, int nHeight, std::vector <std::string>* rterror) {\n    if(!validatorExists(v)) {\n        rterror->push_back(\"Validator does not exist\");\n        return false;\n    }\n\n    v->suspended = true;\n    v->suspendedBlock = nHeight;\n    v->adjustedStake = 0;\n    recalculateProbabilities(nHeight, rterror);\n}\n\nbool StakePool::unsuspendValidator(Validator *v, int nHeight, std::vector <std::string>* rterror) {\n    v->suspended = false;\n    v->suspendedBlock = 0;\n    v->lastBlockHeight = nHeight;\n    return true;\n}\n\nbool StakePool::viable() {\n    bool viable = false;\n    \n    for (Validator* v : validatorPool) {\n        if (!v->suspended) {\n            viable = true;\n        }\n    }\n    \n    return viable;\n}", "meta": {"hexsha": "590b980eec38df1d4657fbc65f1f9af74819c2e6", "size": 4210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stakepool.cpp", "max_stars_repo_name": "Askia-Blockchain/Reserve", "max_stars_repo_head_hexsha": "014333e48f5edfbcd04da8af17bdf362f9d98789", "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/stakepool.cpp", "max_issues_repo_name": "Askia-Blockchain/Reserve", "max_issues_repo_head_hexsha": "014333e48f5edfbcd04da8af17bdf362f9d98789", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-08T14:38:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-08T14:38:57.000Z", "max_forks_repo_path": "src/stakepool.cpp", "max_forks_repo_name": "Askia-Blockchain/Reserve", "max_forks_repo_head_hexsha": "014333e48f5edfbcd04da8af17bdf362f9d98789", "max_forks_repo_licenses": ["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.8152866242, "max_line_length": 103, "alphanum_fraction": 0.6382422803, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.16866456947024844}}
{"text": "// Copyright (c) 2011-2013, Pacific Biosciences of California, Inc.\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\n// disclaimer 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\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 Pacific Biosciences 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// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY PACIFIC\n// BIOSCIENCES AND ITS CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL PACIFIC BIOSCIENCES OR ITS\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 AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n// 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\n// SUCH DAMAGE.\n\n// Author: David Alexander\n\n#include <ConsensusCore/Quiver/Diploid.hpp>\n\n#include <ConsensusCore/Mutation.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <cfloat>\n#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <utility>\n#include <vector>\n\n#include <boost/numeric/ublas/vector.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\n\n\nusing std::vector;\nusing std::accumulate;\nusing std::pair;\nusing std::make_pair;\nusing std::cout;\nusing std::endl;\n\ntypedef boost::numeric::ublas::vector<float> fvec;\ntypedef boost::numeric::ublas::matrix<float> fmat;\ntypedef boost::numeric::ublas::matrix_column<const fmat> fmat_column;\n\n#if defined(_MSC_VER) && _MSC_VER < 1800\n\n// compute log(1+x) without losing precision for small values of x\nfloat log1p(float x)\n{\n    if (x <= -1.0)\n    {\n        std::stringstream os;\n        os << \"Invalid input argument (\" << x\n           << \"); must be greater than -1.0\";\n        throw std::invalid_argument(os.str());\n    }\n\n    if (fabs(x) > 1e-4)\n    {\n        // x is large enough that the obvious evaluation is OK\n        return log(1.0 + x);\n    }\n\n    // Use Taylor approx. log(1 + x) = x - x^2/2 with error roughly x^3/3\n    // Since |x| < 10^-4, |x|^3 < 10^-12, relative error less than 10^-8\n\n    return (-0.5*x + 1.0)*x;\n}\n\n#endif\n\nnamespace ConsensusCore {\n\n    // This needs to be configurable.\n    DEBUG_ONLY( const int MUTATIONS_PER_SITE = 9; ) // NOLINT\n    const int LENGTH_DIFFS[] = { 0, 0, 0, 0, 1, 1, 1, 1, -1 };\n\n    DiploidSite::DiploidSite(int allele0, int allele1,\n                             float logBayesFactor,\n                             std::vector<int> alleleForRead)\n        : Allele0(allele0),\n          Allele1(allele1),\n          LogBayesFactor(logBayesFactor),\n          AlleleForRead(alleleForRead)\n    {}\n\n    static inline float logaddexp(float x, float y)\n    {\n         float diff = x - y;\n         if (diff > 0)  {\n             return x + log1p(exp(-diff));\n         } else {\n             return y + log1p(exp(diff));\n         }\n    }\n\n    //\n    // Computes Pr(R | hom)\n    //\n    static float HomozygousLogLikelihood(const fmat& siteScores)\n    {\n        int G = siteScores.size2();\n        fvec gScores(G);\n        for (int g = 0; g < G; g++)\n        {\n            gScores(g) = sum(column(siteScores, g));\n        }\n       return accumulate(gScores.begin(),  gScores.end(), -FLT_MAX, logaddexp);\n    }\n\n    //\n    // Computes: Pr(R | het)\n    //\n    static float HeterozygousLogLikelihood(const fmat& siteScores,\n                                            int* allele0, int* allele1)\n    {\n        assert (siteScores.size2() == MUTATIONS_PER_SITE);\n\n        int I = siteScores.size1();\n        int G = siteScores.size2();\n        float log2 = log(2);\n\n        vector<float> varScores;\n        float runningMax = -FLT_MAX;\n        int runningAllele0 = -1;\n        int runningAllele1 = -1;\n        for (int g0 = 0; g0 < G; g0++)\n        {\n            for (int g1 = g0 + 1; g1 < G; g1++)\n            {\n                if (LENGTH_DIFFS[g0] == LENGTH_DIFFS[g1])\n                {\n                    float total = -I * log2;\n                    for (int i = 0; i < I; i++)\n                    {\n                        total += logaddexp(siteScores(i, g0),\n                                           siteScores(i, g1));\n                    }\n                    varScores.push_back(total);\n                    if (total > runningMax)\n                    {\n                        runningMax = total;\n                        runningAllele0 = g0;\n                        runningAllele1 = g1;\n                    }\n                }\n            }\n        }\n        if (allele0 != NULL && allele1 != NULL)\n        {\n            *allele0 = runningAllele0;\n            *allele1 = runningAllele1;\n        }\n        return accumulate(varScores.begin(),  varScores.end(), -FLT_MAX, logaddexp);\n    }\n\n\n    static inline fmat ToMatrix(const float *siteScores, int dim1, int dim2)\n    {\n        // Kind of kludgy.  I blame ublas--a pretty crummy matrix library.\n        fmat M(dim1, dim2);\n        std::copy(siteScores, siteScores + dim1*dim2, M.data().begin());\n        return M;\n    }\n\n#if 0\n    static void PrintMatrix(const fmat& siteScores)\n    {\n        for (int i = 0; i < (int)siteScores.size1(); i++)\n        {\n            for (int j = 0; j < (int)siteScores.size2(); j++)\n            {\n                cout << siteScores(i, j) << \" \";\n            }\n            cout << endl;\n        }\n        cout << endl;\n    }\n#endif  // 0\n\n    vector<int> AssignReadsToAlleles(const fmat& siteScores, int allele0, int allele1)\n    {\n        int I = siteScores.size1();\n        vector<int> assignment(I, -1);\n        for (int i = 0; i < I; i++)\n        {\n            assignment[i] = (siteScores(i, allele0) > siteScores(i, allele1) ? 0 : 1);\n        }\n        return assignment;\n    }\n\n    // Is the site detected as a heterozygote?\n    //  - If not, return NULL.\n    //  - If so, return a pointer to a new DiploidSite object\n    // logPriorRatio >= 0 is log {Pr(hom)/Pr(het)}\n    DiploidSite* IsSiteHeterozygous(const float *siteScores, int dim1, int dim2,\n                                    float logPriorRatio)\n    {\n        // First column of siteScores must correspond to no-op mutation.\n        int allele0, allele1;\n\n        fmat M = ToMatrix(siteScores, dim1, dim2);\n        float homScore = HomozygousLogLikelihood(M);\n        float hetScore = HeterozygousLogLikelihood(M, &allele0, &allele1);\n        float logBF = hetScore - homScore;\n\n        if (logBF - logPriorRatio > 0)\n        {\n            return new DiploidSite(allele0, allele1, logBF,\n                                   AssignReadsToAlleles(M, allele0, allele1));\n        }\n        else\n        {\n            return NULL;\n        }\n    }\n}\n", "meta": {"hexsha": "48f448e6d6481aa294a1e390b9ffce06b0aa5a1f", "size": 7665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ConsensusCore/src/C++/Quiver/Diploid.cpp", "max_stars_repo_name": "pb-cdunn/pbccs", "max_stars_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ConsensusCore/src/C++/Quiver/Diploid.cpp", "max_issues_repo_name": "pb-cdunn/pbccs", "max_issues_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "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": "ConsensusCore/src/C++/Quiver/Diploid.cpp", "max_forks_repo_name": "pb-cdunn/pbccs", "max_forks_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "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": 31.673553719, "max_line_length": 86, "alphanum_fraction": 0.5817351598, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.168619815776904}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <float.h>\n#include <string.h>\n#include <stdarg.h>\n\n#include <sys/stat.h>\n#include <sys/types.h>\n\n#include <algorithm>\n#include <cmath>\nusing namespace std;\n\n#include <boost/interprocess/file_mapping.hpp>\n#include <boost/interprocess/mapped_region.hpp>\n\n#include \"search.h\"\n\n#ifndef __S_IFMT\n#define __S_IFMT 0170000\n#endif\n\n#ifndef __S_IFDIR\n#define __S_IFDIR 0040000\n#endif\n\ninline bool operator<(const search_result &a, const search_result &b)\n{\n    return a.value < b.value;\n}\n\n/*\nsearch_model *load_model(const char *model_file_name, const UInt64 dim, const UInt64 nimages)\n{\n    using namespace boost::interprocess;\n\n    FILE *fp = fopen(model_file_name, \"rb\");\n    if (0 == fp) {\n        fprintf(stderr, \"[search.load_model] failed to open model_file %s\\n\", model_file_name);\n        return 0;\n    }\n\n    struct stat info;\n    stat(model_file_name, &info);\n    if( (info.st_mode & __S_IFMT ) == __S_IFDIR) {\n        fprintf(stderr, \"[search.load_model] %s is a directory\\n\",  model_file_name);\n        fclose(fp);\n        return 0;\n    }\n\n    //printf(\"%d %d %d %d\\n\", sizeof(dim), sizeof(nimages), dim, nimages);\n\n    UInt64 count = dim * nimages;\n    search_model *model = new search_model;\n\n    //printf(\"%d %d\\n\", sizeof(count), count);\n\n    //fprintf(stdout, \"[search.load model] requesting %llu bytes memory ...\\n\", count * sizeof(DataType));\n    model->feature_ptr = new DataType[count];\n\n    if (0 == model->feature_ptr)\n    {\n        fprintf(stderr, \"[search.load_model] Memory error!\\n\");\n        fclose(fp);\n        free_model(&model);\n        return 0;\n    }\n\n    fread((char *)(model->feature_ptr), sizeof(DataType), count, fp);\n    fclose(fp);\n    model->dim = dim;\n    model->nimages = nimages;\n\n    //print_model(model);\n\n    return model;\n}\n*/\n\nsearch_model *load_model(const char *model_file_name, const UInt64 dim, const UInt64 nimages)\n{\n    using namespace boost::interprocess;\n\n    FILE *fp = fopen(model_file_name, \"rb\");\n    if (0 == fp) {\n        fprintf(stderr, \"[search.load_model] failed to open model_file %s\\n\", model_file_name);\n        return 0;\n    }\n    fclose(fp);\n\n    struct stat info;\n    stat(model_file_name, &info);\n    if( (info.st_mode & __S_IFMT ) == __S_IFDIR) {\n        fprintf(stderr, \"[search.load_model] %s is a directory\\n\",  model_file_name);\n        fclose(fp);\n        return 0;\n    }\n\n    file_mapping *m_file = new file_mapping(model_file_name, read_only);\n    mapped_region *region = new mapped_region(*m_file, read_only);\n\n    UInt64 count = dim * nimages * sizeof(DataType);\n\n    search_model *model = new search_model;\n    model->m_file = m_file;\n    model->region = region;\n    //Get the address of the mapped region\n    model->feature_ptr = (DataType*)region->get_address();\n    UInt64 region_size  = region->get_size();\n\n    if (0 == model->feature_ptr)\n    {\n        fprintf(stderr, \"[search.load_model] Memory error!\\n\");\n        free_model(&model);\n        return 0;\n    }\n\n/*    if (count != region_size) {\n        fprintf(stderr, \"[search.load_model] File size mis-match number of images!\\n\");\n        printf(\"nimages: %llu\\n\", nimages);\n        printf(\"dim: %llu\\n\", dim);\n        printf(\"region_size: %llu\\n\", region_size);\n        printf(\"count: %llu\\n\", count);\n        free_model(&model);\n        return 0;\n    }\n*/\n    model->dim = dim;\n    model->nimages = nimages;\n\n    return model;\n}\n\nvoid free_model_contents(search_model* model_ptr)\n{\n     /*\n     if (0 != model_ptr->feature_ptr)\n     {\n         //fprintf(stdout, \"[search.free_model_contents]\\n\");\n         delete [] model_ptr->feature_ptr;\n         model_ptr->feature_ptr = 0;\n     }\n     */\n     if (0 != model_ptr->feature_ptr)\n     {\n         //fprintf(stdout, \"[search.free_model_contents]\\n\");\n         delete model_ptr->region;\n         delete model_ptr->m_file;\n         model_ptr->feature_ptr = 0;\n     }\n}\n\n\nvoid free_model(search_model** model_ptr_ptr)\n{\n     search_model* model_ptr = *model_ptr_ptr;\n\n     if(0 != model_ptr)\n     {\n         free_model_contents(model_ptr);\n         delete model_ptr;\n         model_ptr = 0;\n         //fprintf(stdout, \"[search.free_model]\\n\");\n     }\n}\n\nvoid print_model(const search_model* model_ptr)\n{\n    fprintf(stdout, \"[search.print_model] %llu images, %llu dims\\n\", model_ptr->nimages, model_ptr->dim);\n}\n\n\nUInt64 get_dim(const search_model* model_ptr)\n{\n    return model_ptr->dim;\n}\n\nUInt64 get_nr_images(const search_model* model_ptr)\n{\n    return model_ptr->nimages;\n}\n\n// 1 - ((xi * yi) / (norm(x) * norm(y)))\n\nvoid compute_cosine_distance(const search_model *model, const DataType* query_ptr, double* dist_values)\n{\n    const DataType *ptr = model->feature_ptr;\n\n    for (UInt64 i=0; i<model->nimages; i++)\n    {\n        double norm_query = 0;\n        double norm_ptr = 0;\n        double dist = 0;\n        for (UInt64 j=0; j<model->dim; j++)\n        {\n            norm_query += query_ptr[j] * query_ptr[j];\n            norm_ptr += ptr[j] * ptr[j];\n            dist += query_ptr[j] * ptr[j];\n        }\n        ptr += model->dim;\n        //fprintf(stdout, \"%d %f %f\\n\", i, dist, sqrt(dist));\n        if (norm_query < 1e-8 || norm_ptr < 1e-8) {\n            dist_values[i] = (norm_query < 1e-8 && norm_ptr < 1e-8) ? 0 : 1; // define a value for zero input\n         } else {\n            dist_values[i] = 1. - (dist / (sqrt(norm_query) * sqrt(norm_ptr)));\n         }\n         //dist_values[i] = 1. - (dist / (sqrt(norm_query) * sqrt(norm_ptr)));\n    }\n}\n\nvoid compute_l2_distance(const search_model *model, const DataType* query_ptr, double* dist_values)\n{\n    const DataType *ptr = model->feature_ptr;\n\n    for (UInt64 i=0; i<model->nimages; i++)\n    {\n        double dist = 0;\n        for (UInt64 j=0; j<model->dim; j++)\n        {\n            double d = query_ptr[j] - ptr[j];\n            dist += (d * d);\n            //if (0 == i) fprintf(stdout, \"%d %f %f %f\\n\", j, query_ptr[j], ptr[j], d);\n        }\n        ptr += model->dim;\n        //fprintf(stdout, \"%d %f %f\\n\", i, dist, sqrt(dist));\n        dist_values[i] = sqrt(dist);\n    }\n}\n\nvoid compute_l1_distance(const search_model *model, const DataType* query_ptr, double* dist_values)\n{\n    const DataType *ptr = model->feature_ptr;\n\n    for (UInt64 i=0; i<model->nimages; i++)\n    {\n        double dist = 0;\n        for (UInt64 j=0; j<model->dim; j++)\n        {\n            double d = query_ptr[j] - ptr[j];\n            dist += fabs(d);\n        }\n        ptr += model->dim;\n        //fprintf(stdout, \"%d %f %f\\n\", i, dist, sqrt(dist));\n        dist_values[i] = dist;\n    }\n}\n\n/*\n * chi2(x,y) = sum( (xi-yi)^2 / (xi+yi) ) / 2\n */\nvoid compute_chi2_distance(const search_model *model, const DataType* query_ptr, double* dist_values)\n{\n    const DataType *ptr = model->feature_ptr;\n    double dist = 0;\n    double d = 0;\n    double s = 0;\n\n    for (UInt64 i=0; i<model->nimages; i++)\n    {\n        dist = 0.0;\n        for (UInt64 j=0; j<model->dim; j++)\n        {\n            d = query_ptr[j] - ptr[j];\n            s = query_ptr[j] + ptr[j];\n            if (s > 1e-8) {\n                dist += (d*d)/s;\n            }\n        }\n        dist /= 2;\n        ptr += model->dim;\n        //fprintf(stdout, \"%d %f %f\\n\", i, dist, sqrt(dist));\n        dist_values[i] = dist;\n    }\n}\n\n\nvoid search_knn(const struct search_model *model, const DataType* query_ptr, const UInt64 k, const int dfunc, struct search_result *results)\n{\n    double * dist_values = new double[model->nimages];\n\n    switch (dfunc) {\n        case 0:\n            compute_l1_distance(model, query_ptr, dist_values);\n            break;\n        case 2:\n            compute_chi2_distance(model, query_ptr, dist_values);\n            break;\n        case 4:\n            compute_cosine_distance(model, query_ptr, dist_values);\n            break;\n        default:\n            compute_l2_distance(model, query_ptr, dist_values);\n            break;\n    }\n    /*if (1 == l2) {\n        compute_distance(model, query_ptr, dist_values);\n    } else {\n        compute_l1_distance(model, query_ptr, dist_values);\n    } */\n    struct search_result *tosort = new search_result[model->nimages];\n    for (UInt64 i=0; i<model->nimages; i++)\n    {\n        tosort[i].index = i;\n        tosort[i].value = dist_values[i];\n    }\n    delete [] dist_values;\n\n    if (k <= (model->nimages >> 1)) {\n        partial_sort(tosort, tosort + k, tosort + model->nimages);\n    }\n    else {\n        sort(tosort, tosort + model->nimages);\n    }\n\n    for (UInt64 i=0; i<k; i++)\n    {\n        results[i].index = tosort[i].index;\n        results[i].value = tosort[i].value;\n    }\n    delete [] tosort;\n}\n", "meta": {"hexsha": "cd0a11583e0ac6675af141c99d09961bcb62ecd0", "size": 8649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/simpleknn/cpp/search.cpp", "max_stars_repo_name": "vohoaiviet/tag-image-retrieval", "max_stars_repo_head_hexsha": "0a257560581f702cd394f3f28c9e0f6202827ce8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74.0, "max_stars_repo_stars_event_min_datetime": "2018-05-08T06:38:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T03:57:28.000Z", "max_issues_repo_path": "util/simpleknn/cpp/search.cpp", "max_issues_repo_name": "vohoaiviet/tag-image-retrieval", "max_issues_repo_head_hexsha": "0a257560581f702cd394f3f28c9e0f6202827ce8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-06-08T07:19:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T08:17:21.000Z", "max_forks_repo_path": "util/simpleknn/cpp/search.cpp", "max_forks_repo_name": "vohoaiviet/tag-image-retrieval", "max_forks_repo_head_hexsha": "0a257560581f702cd394f3f28c9e0f6202827ce8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-10-26T03:41:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T08:11:05.000Z", "avg_line_length": 26.6944444444, "max_line_length": 140, "alphanum_fraction": 0.5833044283, "num_tokens": 2333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1686198110653126}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2018 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_0.txt)\n\n#ifndef BOOST_MP_EIGEN_HPP\n#define BOOST_MP_EIGEN_HPP\n\n#include <boost/multiprecision/number.hpp>\n#include <Eigen/Core>\n\n//\n// Generic Eigen support code:\n//\nnamespace Eigen {\ntemplate <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>\nstruct NumTraits<boost::multiprecision::number<Backend, ExpressionTemplates> >\n{\n   using self_type = boost::multiprecision::number<Backend, ExpressionTemplates>                         ;\n   using Real = typename boost::multiprecision::scalar_result_from_possible_complex<self_type>::type;\n   using NonInteger = self_type                                                                           ; // Not correct but we can't do much better??\n   using Literal = double                                                                              ;\n   using Nested = self_type                                                                           ;\n   enum\n   {\n      IsComplex             = boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_complex,\n      IsInteger             = boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer,\n      ReadCost              = 1,\n      AddCost               = 4,\n      MulCost               = 8,\n      IsSigned              = std::numeric_limits<self_type>::is_specialized ? std::numeric_limits<self_type>::is_signed : true,\n      RequireInitialization = 1,\n   };\n   static Real epsilon()\n   {\n      return std::numeric_limits<Real>::epsilon();\n   }\n   static Real dummy_precision()\n   {\n      return 1000 * epsilon();\n   }\n   static Real highest()\n   {\n      return (std::numeric_limits<Real>::max)();\n   }\n   static Real lowest()\n   {\n      return (std::numeric_limits<Real>::min)();\n   }\n   static int digits10_imp(const std::integral_constant<bool, true>&)\n   {\n      return std::numeric_limits<Real>::digits10;\n   }\n   template <bool B>\n   static int digits10_imp(const std::integral_constant<bool, B>&)\n   {\n      return Real::default_precision();\n   }\n   static int digits10()\n   {\n      return digits10_imp(std::integral_constant<bool, std::numeric_limits<Real>::digits10 && (std::numeric_limits<Real>::digits10 != INT_MAX) ? true : false > ());\n   }\n};\ntemplate <class tag, class Arg1, class Arg2, class Arg3, class Arg4>\nstruct NumTraits<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4> > : public NumTraits<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type>\n{\n};\n\n#define BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(A)                                                                                                                                                                           \\\n   template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, typename BinaryOp>                                                                                                  \\\n   struct ScalarBinaryOpTraits<boost::multiprecision::number<Backend, ExpressionTemplates>, A, BinaryOp>                                                                                                               \\\n   {                                                                                                                                                                                                                   \\\n      /*static_assert(boost::multiprecision::is_compatible_arithmetic_type<A, boost::multiprecision::number<Backend, ExpressionTemplates> >::value, \"Interoperability with this arithmetic type is not supported.\");*/ \\\n      using ReturnType = boost::multiprecision::number<Backend, ExpressionTemplates>;                                                                                                                                  \\\n   };                                                                                                                                                                                                                  \\\n   template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, typename BinaryOp>                                                                                                  \\\n   struct ScalarBinaryOpTraits<A, boost::multiprecision::number<Backend, ExpressionTemplates>, BinaryOp>                                                                                                               \\\n   {                                                                                                                                                                                                                   \\\n      /*static_assert(boost::multiprecision::is_compatible_arithmetic_type<A, boost::multiprecision::number<Backend, ExpressionTemplates> >::value, \"Interoperability with this arithmetic type is not supported.\");*/ \\\n      using ReturnType = boost::multiprecision::number<Backend, ExpressionTemplates>;                                                                                                                                  \\\n   };\n\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(float)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(double)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(long double)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(char)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(unsigned char)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(signed char)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(short)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(unsigned short)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(int)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(unsigned int)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(long)\nBOOST_MP_EIGEN_SCALAR_TRAITS_DECL(unsigned long)\n\n#if 0    \n      template<class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, class Backend2, boost::multiprecision::expression_template_option ExpressionTemplates2, typename BinaryOp>\n   struct ScalarBinaryOpTraits<boost::multiprecision::number<Backend, ExpressionTemplates>, boost::multiprecision::number<Backend2, ExpressionTemplates2>, BinaryOp>\n   {\n      static_assert(\n         boost::multiprecision::is_compatible_arithmetic_type<boost::multiprecision::number<Backend2, ExpressionTemplates2>, boost::multiprecision::number<Backend, ExpressionTemplates> >::value\n         || boost::multiprecision::is_compatible_arithmetic_type<boost::multiprecision::number<Backend, ExpressionTemplates>, boost::multiprecision::number<Backend2, ExpressionTemplates2> >::value, \"Interoperability with this arithmetic type is not supported.\");\n      using ReturnType = typename std::conditional<std::is_convertible<boost::multiprecision::number<Backend2, ExpressionTemplates2>, boost::multiprecision::number<Backend, ExpressionTemplates> >::value,\n         boost::multiprecision::number<Backend, ExpressionTemplates>, boost::multiprecision::number<Backend2, ExpressionTemplates2> >::type;\n   };\n\n   template<unsigned D, typename BinaryOp>\n   struct ScalarBinaryOpTraits<boost::multiprecision::number<boost::multiprecision::backends::mpc_complex_backend<D>, boost::multiprecision::et_on>, boost::multiprecision::mpfr_float, BinaryOp>\n   {\n      using ReturnType = boost::multiprecision::number<boost::multiprecision::backends::mpc_complex_backend<D>, boost::multiprecision::et_on>;\n   };\n\n   template<typename BinaryOp>\n   struct ScalarBinaryOpTraits<boost::multiprecision::mpfr_float, boost::multiprecision::mpc_complex, BinaryOp>\n   {\n      using ReturnType = boost::multiprecision::number<boost::multiprecision::backends::mpc_complex_backend<0>, boost::multiprecision::et_on>;\n   };\n\n   template<class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, typename BinaryOp>\n   struct ScalarBinaryOpTraits<boost::multiprecision::number<Backend, ExpressionTemplates>, boost::multiprecision::number<Backend, ExpressionTemplates>, BinaryOp>\n   {\n      using ReturnType = boost::multiprecision::number<Backend, ExpressionTemplates>;\n   };\n#endif\n\ntemplate <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, class tag, class Arg1, class Arg2, class Arg3, class Arg4, typename BinaryOp>\nstruct ScalarBinaryOpTraits<boost::multiprecision::number<Backend, ExpressionTemplates>, boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>, BinaryOp>\n{\n   static_assert(std::is_convertible<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, boost::multiprecision::number<Backend, ExpressionTemplates> >::value, \"Interoperability with this arithmetic type is not supported.\");\n   using ReturnType = boost::multiprecision::number<Backend, ExpressionTemplates>;\n};\n\ntemplate <class tag, class Arg1, class Arg2, class Arg3, class Arg4, class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, typename BinaryOp>\nstruct ScalarBinaryOpTraits<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>, boost::multiprecision::number<Backend, ExpressionTemplates>, BinaryOp>\n{\n   static_assert(std::is_convertible<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, boost::multiprecision::number<Backend, ExpressionTemplates> >::value, \"Interoperability with this arithmetic type is not supported.\");\n   using ReturnType = boost::multiprecision::number<Backend, ExpressionTemplates>;\n};\n\nnamespace internal {\ntemplate <typename Scalar>\nstruct conj_retval;\n\ntemplate <typename Scalar, bool IsComplex>\nstruct conj_impl;\n\ntemplate <class tag, class Arg1, class Arg2, class Arg3, class Arg4>\nstruct conj_retval<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4> >\n{\n   using type = typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type;\n};\n\ntemplate <class tag, class Arg1, class Arg2, class Arg3, class Arg4>\nstruct conj_impl<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>, true>\n{\n   EIGEN_DEVICE_FUNC\n   static inline typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type run(const typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& x)\n   {\n      return conj(x);\n   }\n};\n\n} // namespace internal\n\n} // namespace Eigen\n\n#endif\n", "meta": {"hexsha": "105d7f50050984a6321bf27f267f161bc97efafb", "size": 10544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/multiprecision/eigen.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/multiprecision/eigen.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/multiprecision/eigen.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": 62.7619047619, "max_line_length": 265, "alphanum_fraction": 0.6320182094, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1686198076352008}}
{"text": "/*\n * Copyright (c) 2016, Georgia Tech Research Corporation\n * All rights reserved.\n *\n * Author(s): Michael X. Grey <mxgrey@gatech.edu>\n *\n * Georgia Tech Graphics Lab and AMBER Lab\n *\n * Directed by Prof. C. Karen Liu and Prof. Aaron D. Ames\n * <karenliu@cc.gatech.edu> <ames@gatech.edu>\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#include <vector>\n#include <Eigen/Core>\n#include <dart/dynamics/Skeleton.h>\n#include <dart/dynamics/EndEffector.h>\n#include <dart/dynamics/DegreeOfFreedom.h>\n#include <dart/simulation/World.h>\n#include <osgDart/osgDart.h>\n#include <hubo/DrcModel.hpp>\n#include <hubo/RelaxedPosture.hpp>\n\n#include <HuboPath/Operator.hpp>\n\nusing Trajectory = std::vector<Eigen::VectorXd>;\nusing namespace dart::dynamics;\nusing namespace dart::simulation;\n\n//const double DefaultStepLength = 0.13;\nconst double DefaultStepLength = 0.155;\nconst double frequency = 200.0;\n\n//==============================================================================\nstruct StepContext\n{\n  StepContext(EndEffector* stance, EndEffector* swing,\n              size_t index, double t0, double dist)\n    : stance_foot(stance),\n      swing_foot(swing),\n      route_index(index),\n      start_t(t0),\n      distance(dist),\n      attempts(0)\n  {\n    // Do nothing\n  }\n\n\n  EndEffector* stance_foot;\n  EndEffector* swing_foot;\n  size_t route_index;\n  double start_t;\n\n  Eigen::VectorXd start_q;\n  Eigen::VectorXd end_q;\n\n  double distance;\n  size_t attempts;\n};\n\n//==============================================================================\nstd::tuple<size_t, double> getNextRouteLocation(\n    const std::vector<Eigen::VectorXd>& route,\n    double stepDist,\n    size_t start_index,\n    double start_t)\n{\n  assert(start_t < 1.0);\n\n  double remaining_D = stepDist;\n  while(remaining_D > 0)\n  {\n    if(start_index == route.size()-1)\n    {\n      return std::tuple<size_t, double>(start_index, 0);\n    }\n\n    Eigen::VectorXd q0 = route[start_index];\n    Eigen::VectorXd q1 = route[start_index+1];\n\n    Eigen::Vector2d p0 = q0.block<2,1>(3,0);\n    Eigen::Vector2d p1 = q1.block<2,1>(3,0);\n\n    double D = (p1-p0).norm();\n    double t = start_t + remaining_D/D;\n    if(t >= 1)\n    {\n      remaining_D = remaining_D - D*(1.0-start_t);\n      ++start_index;\n      start_t = 0.0;\n    }\n    else\n    {\n      start_t = t;\n      remaining_D = 0.0;\n    }\n  }\n\n  return std::tuple<size_t, double>(start_index, start_t);\n}\n\n//==============================================================================\nEigen::VectorXd getStepConfig(const std::vector<Eigen::VectorXd>& route,\n                              const StepContext& step)\n{\n  Eigen::VectorXd q = route[step.route_index];\n  if(step.route_index < route.size()-1 && step.start_t > 0.0)\n    q += step.start_t*(route[step.route_index+1]-route[step.route_index]);\n\n  return q;\n}\n\n//==============================================================================\nbool confirmStepReachability(const dart::dynamics::SkeletonPtr& robot,\n                             const std::vector<Eigen::VectorXd>& route,\n                             const StepContext& step0,\n                             StepContext& step1)\n{\n//  std::cout << step0.route_index << \":\" << step0.start_t\n//            << \" | \" << step1.route_index << \":\" << step1.start_t << std::endl;\n\n  std::shared_ptr<hubo::RelaxedPosture> posture =\n      std::dynamic_pointer_cast<hubo::RelaxedPosture>(robot->getIK(true)->getObjective());\n\n  Eigen::VectorXd q0 = getStepConfig(route, step0);\n  robot->setPositions(q0);\n  const Eigen::Isometry3d tf_foot0 = step0.stance_foot->getWorldTransform();\n  step0.stance_foot->getIK(true)->getTarget()->setTransform(tf_foot0);\n  step0.stance_foot->getIK(true)->setActive(true);\n\n//  std::cout << \"\\n------------------\\n\"\n//            << step0.stance_foot->getName() <<\"\\n\"\n//            << tf_foot0.matrix() << std::endl;\n\n  Eigen::VectorXd q1 = getStepConfig(route, step1);\n  robot->setPositions(q1);\n  const Eigen::Isometry3d tf_foot1 = step1.stance_foot->getWorldTransform();\n  step1.stance_foot->getIK(true)->getTarget()->setTransform(tf_foot1);\n  step1.stance_foot->getIK(true)->setActive(true);\n\n//  std::cout << \"\\n\" << step1.stance_foot->getName() << \"\\n\"\n//            << tf_foot1.matrix() << std::endl;\n\n  assert(step0.stance_foot != step1.stance_foot);\n\n  // Solve while leaning on first foot\n  step0.stance_foot->getSupport()->setActive(true);\n  step1.stance_foot->getSupport()->setActive(false);\n  robot->setPositions(q0);\n\n  if(posture)\n    posture->enforceIdealPosture = true;\n\n  robot->getIK(true)->solve();\n//  if(posture)\n//    posture->enforceIdealPosture = false;\n//  if(!robot->getIK(true)->solve())\n//    return false;\n\n  step1.start_q = robot->getPositions();\n\n  // Solve while leaning on second foot\n  step1.stance_foot->getSupport()->setActive(true);\n  step0.stance_foot->getSupport()->setActive(false);\n  robot->setPositions(q1);\n\n  if(posture)\n    posture->enforceIdealPosture = true;\n\n  robot->getIK(true)->solve();\n//  if(posture)\n//    posture->enforceIdealPosture = false;\n\n//  if(!robot->getIK(true)->solve())\n//    return false;\n\n  step1.end_q = robot->getPositions();\n\n  return true;\n}\n\n//==============================================================================\nbool testNextStepContext(const dart::dynamics::SkeletonPtr& robot,\n                         const std::vector<Eigen::VectorXd>& route,\n                         const StepContext& lastStep,\n                         StepContext& nextStep)\n{\n  size_t start_index = lastStep.route_index;\n\n  if(start_index >= route.size())\n    return true;\n\n  std::tie(nextStep.route_index, nextStep.start_t) =\n      getNextRouteLocation(route, nextStep.distance,\n                           start_index, lastStep.start_t);\n\n  return confirmStepReachability(robot, route, lastStep, nextStep);\n}\n\n//==============================================================================\nbool getNextStepContext(const dart::dynamics::SkeletonPtr& robot,\n                        const std::vector<Eigen::VectorXd>& route,\n                        const StepContext& lastStep,\n                        StepContext& nextStep)\n{\n  const size_t maxAttempts = 20;\n  size_t attempts = 0;\n  while(!testNextStepContext(robot, route, lastStep, nextStep))\n  {\n    nextStep.distance /= 2.0;\n\n    ++attempts;\n//    std::cout << \"Attempt #\" << attempts << \" out of \" << maxAttempts << std::endl;\n    if(attempts > maxAttempts)\n    {\n//      std::cout << \"[getNextStepContext] ERROR: Tried \" << attempts << \" times \"\n//                << \"to find the next step, but it keeps failing! Reverting!\"\n//                << std::endl;\n\n      return false;\n    }\n  }\n\n  return true;\n}\n\n//==============================================================================\nstd::vector<StepContext> generateSteps(\n    const dart::dynamics::SkeletonPtr& robot,\n    const std::vector<Eigen::VectorXd>& route,\n    double stepDistance = DefaultStepLength)\n{\n  robot->setPositions(route.front());\n\n  StepContext lastStep(robot->getEndEffector(\"l_foot\"),\n                       robot->getEndEffector(\"r_foot\"),\n                       0, 0, stepDistance);\n  lastStep.start_q = robot->getPositions();\n  lastStep.end_q = lastStep.start_q;\n\n  std::vector<StepContext> steps;\n  steps.push_back(lastStep);\n\n  std::swap(lastStep.stance_foot, lastStep.swing_foot);\n  steps.push_back(lastStep);\n\n  const size_t maxAttempts = 3;\n  while(steps.back().route_index < route.size()-1\n        && steps.size() > 1)\n  {\n    std::cout << \"Steps: \" << steps.size() << \" (\" <<\n              100*steps.back().route_index/route.size() << \"%)\" << std::endl;\n    StepContext& previousStep = steps[steps.size()-2];\n    StepContext& currentStep = steps.back();\n    if(!getNextStepContext(robot, route, previousStep, currentStep))\n    {\n      previousStep.distance /= 2.0;\n      ++previousStep.attempts;\n      steps.pop_back();\n//      std::cout << \" === stepping failed \" << std::endl;\n//      return steps;\n\n      if(previousStep.attempts >= maxAttempts)\n      {\n//        steps.pop_back();\n//        steps.back().distance /= 2.0;\n//        ++steps.back().attempts;\n\n        std::cout << \" ==== Failing to generate steps!\" << std::endl;\n\n//        osgDart::Viewer viewer;\n//        viewer.addWorldNode(new osgDart::WorldNode(world));\n//        viewer.setUpViewInWindow(0, 0, 640, 480);\n//        viewer.run();\n\n        return steps;\n      }\n      continue;\n    }\n\n    StepContext nextStep(currentStep);\n    std::swap(nextStep.stance_foot, nextStep.swing_foot);\n    nextStep.distance = stepDistance;\n\n    steps.push_back(nextStep);\n  }\n\n  if(steps.size() < 2)\n  {\n//    std::cout << \" ======= Failed to generate steps! ===== \" << std::endl;\n    return steps;\n  }\n\n  // The last step is extraneous\n  steps.pop_back();\n\n//  std::cout << \" --- Generating finish --- \" << std::endl;\n//  std::cout << \"Last \" << steps.back().route_index << \" : \" << steps.back().start_t << std::endl;\n  // One last finishing step\n  StepContext nextStep(steps.back());\n  std::swap(nextStep.stance_foot, nextStep.swing_foot);\n  nextStep.distance = stepDistance;\n  getNextStepContext(robot, route, steps.back(), nextStep);\n  nextStep.end_q = route.back();\n  steps.push_back(nextStep);\n\n  return steps;\n}\n\n//==============================================================================\nvoid interpolateSteps(const dart::dynamics::SkeletonPtr& robot,\n                      std::vector<Eigen::VectorXd>& walk,\n                      std::vector<size_t>& stepRanges,\n                      const StepContext& stepFrom,\n                      const StepContext& stepTo,\n                      bool excludeStep = false)\n{\n  std::shared_ptr<hubo::RelaxedPosture> posture =\n      std::dynamic_pointer_cast<hubo::RelaxedPosture>(robot->getIK(true)->getObjective());\n\n  dart::dynamics::EndEffector* stance = stepFrom.stance_foot;\n  dart::dynamics::EndEffector* swing = stepFrom.swing_foot;\n\n  if(!excludeStep)\n  {\n    stance->getSupport()->setActive(true);\n    swing->getSupport()->setActive(false);\n\n    robot->setPositions(stepFrom.end_q);\n    stance->getIK(true)->getTarget()->setTransform(\n          stance->getWorldTransform());\n    const Eigen::Isometry3d swingStart = swing->getWorldTransform();\n\n    robot->setPositions(stepTo.start_q);\n    const Eigen::Isometry3d swingGoal = swing->getWorldTransform();\n\n    const Eigen::Vector2d v =\n        (swingGoal.translation()-swingStart.translation()).block<2,1>(0,0)/(2*M_PI);\n    const double D = v.norm();\n\n    Eigen::AngleAxisd aa(swingStart.linear().transpose()*swingGoal.linear());\n    const double R = aa.angle()/(2*M_PI);\n    const Eigen::Vector3d axis = aa.axis();\n\n    const size_t res = 10;\n    stepRanges.push_back(walk.size());\n    for(size_t i=0; i < res+1; ++i)\n    {\n      const double t = (double)(i)/(double)(res)*2*M_PI;\n      const Eigen::Vector2d x = v*(t - sin(t));\n      const double z = D*(1 - cos(t));\n      const double theta = t*R;\n\n      Eigen::Isometry3d swingTarget = swingStart;\n      swingTarget.translation().block<2,1>(0,0) += x;\n      swingTarget.translation()[2] += z;\n      swingTarget.rotate(Eigen::AngleAxisd(theta, axis));\n\n      swing->getIK(true)->getTarget()->setTransform(swingTarget);\n\n      if(posture)\n        posture->enforceIdealPosture = true;\n\n      robot->getIK(true)->solve();\n\n      if(posture)\n        posture->enforceIdealPosture = false;\n\n      if(!robot->getIK(true)->solve())\n      {\n        walk.push_back(robot->getPositions());\n        std::cout <<\" ===== COULD NOT SOLVE FOOT STEP AT INDEX \" << walk.size()-1 << std::endl;\n        return;\n      }\n\n      walk.push_back(robot->getPositions());\n    }\n  }\n\n  const Eigen::VectorXd& start_q = stepTo.start_q;\n  const Eigen::VectorXd& end_q = stepTo.end_q;\n\n  if(excludeStep)\n  {\n    robot->setPositions(start_q);\n    stance->getIK(true)->getTarget()->setTransform(\n          stance->getWorldTransform());\n\n    swing->getIK(true)->getTarget()->setTransform(\n          swing->getWorldTransform());\n  }\n\n  const Eigen::Vector6d x0 = start_q.block<6,1>(0,0);\n  const Eigen::Vector6d xf = end_q.block<6,1>(0,0);\n  const Eigen::Vector6d dx = xf - x0;\n\n  // Consider disabling the IK from moving the hips during this stage\n  stance->getSupport()->setActive(true);\n  swing->getSupport()->setActive(true);\n\n  const size_t res = 10;\n  stepRanges.push_back(walk.size());\n  for(size_t i=0; i < res+1; ++i)\n  {\n    const double t = (double)(i)/(double)(res);\n\n    const Eigen::Vector6d x = x0 + t*dx;\n    robot->getJoint(0)->setPositions(x);\n\n    if(!robot->getIK(true)->solve())\n    {\n      walk.push_back(robot->getPositions());\n      std::cout <<\" ===== COULD NOT SOLVE FOOT STEP AT INDEX \" << walk.size()-1 << std::endl;\n      return;\n    }\n\n    walk.push_back(robot->getPositions());\n  }\n}\n\n//==============================================================================\nstd::vector<Eigen::VectorXd> convertRouteToWalk(\n    const dart::dynamics::SkeletonPtr& robot,\n    const Trajectory& trajectory,\n    std::vector<size_t>& stepRanges)\n{\n  const std::vector<Eigen::VectorXd>& route = trajectory;\n\n  auto originalBoundsLeft =\n      robot->getEndEffector(\"l_foot\")->getIK(true)->getErrorMethod().getBounds();\n  auto originalBoundsRight =\n      robot->getEndEffector(\"r_foot\")->getIK(true)->getErrorMethod().getBounds();\n\n  Eigen::Vector6d bounds(Eigen::Vector6d::Constant(\n                          dart::dynamics::DefaultIKTolerance));\n  robot->getEndEffector(\"l_foot\")->getIK(true)->getErrorMethod().setBounds(-bounds, bounds);\n  robot->getEndEffector(\"r_foot\")->getIK(true)->getErrorMethod().setBounds(-bounds, bounds);\n\n  std::shared_ptr<hubo::RelaxedPosture> posture =\n      std::dynamic_pointer_cast<hubo::RelaxedPosture>(\n        robot->getIK(true)->getObjective());\n  if(posture)\n    posture->enforceIdealPosture = true;\n\n//  std::cout << \"Generate steps\" << std::endl;\n  std::vector<StepContext> steps = generateSteps(robot, route);\n\n  std::vector<Eigen::VectorXd> walk;\n\n  StepContext firstStep = steps[0];\n  firstStep.start_q = route[0];\n  firstStep.end_q = steps[1].start_q;\n  interpolateSteps(robot, walk, stepRanges, firstStep, firstStep, true);\n  stepRanges.clear();\n  for(size_t i=0; i < steps.size()-1; ++i)\n  {\n    const StepContext& stepFrom = steps[i];\n    const StepContext& stepTo = i < steps.size()-1? steps[i+1] : steps[i];\n    interpolateSteps(robot, walk, stepRanges, stepFrom, stepTo);\n  }\n\n  robot->getEndEffector(\"l_foot\")->getIK(true)->getErrorMethod().setBounds(originalBoundsLeft);\n  robot->getEndEffector(\"r_foot\")->getIK(true)->getErrorMethod().setBounds(originalBoundsRight);\n\n  return walk;\n}\n\n//==============================================================================\nclass TrajectoryDisplayWorld : public osgDart::WorldNode\n{\npublic:\n\n  TrajectoryDisplayWorld(dart::simulation::WorldPtr world,\n                         const std::vector<Eigen::VectorXd>& traj)\n    : osgDart::WorldNode(world), mTrajectory(traj)\n  {\n    hubo = world->getSkeleton(0);\n    LSR = hubo->getDof(\"LSR\")->getIndexInSkeleton();\n    RSR = hubo->getDof(\"RSR\")->getIndexInSkeleton();\n\n    firstLoop = true;\n  }\n\n  void customPreRefresh() override\n  {\n    if(mTrajectory.size() == 0)\n    {\n      if(firstLoop)\n      {\n        std::cerr << \"No trajectory was generated!\" << std::endl;\n        firstLoop = false;\n      }\n      return;\n    }\n\n    if(firstLoop)\n    {\n      mTimer.setStartTick();\n      firstLoop = false;\n    }\n\n    double time = mTimer.time_s();\n    size_t count = (size_t)(floor(frequency*time)) % mTrajectory.size();\n\n    double dt = 1.0/frequency;\n\n    size_t last_1 = count <= 0? 0 : count - 1;\n    size_t last_2 = count <= 1? 0 : count - 2;\n    size_t last_3 = count <= 2? 0 : count - 3;\n    size_t last_4 = count <= 3? 0 : count - 4;\n\n    size_t next_1 = count < mTrajectory.size() - 1? count + 1 : count;\n    size_t next_2 = count < mTrajectory.size() - 2? count + 2 : count;\n    size_t next_3 = count < mTrajectory.size() - 3? count + 3 : count;\n    size_t next_4 = count < mTrajectory.size() - 4? count + 4 : count;\n\n    Eigen::VectorXd velocities =\n        (0.5*mTrajectory[next_1] - 0.5*mTrajectory[last_1])/dt;\n\n    Eigen::Matrix<double, 5, 1> c;\n    c << -205.0/72.0, 8.0/5.0, -1.0/5.0, 8.0/315.0, -1.0/560.0;\n\n    Eigen::VectorXd accelerations =\n        (  c[1]*mTrajectory[next_1] + c[2]*mTrajectory[next_2] + c[3]*mTrajectory[next_3] + c[4]*mTrajectory[next_4]\n         + c[0]*mTrajectory[count]\n         + c[1]*mTrajectory[last_1] + c[2]*mTrajectory[last_2] + c[3]*mTrajectory[last_3] + c[4]*mTrajectory[last_4])/pow(dt,2);\n\n\n//    accelerations.head<6>().setZero();\n\n    hubo->setPositions(mTrajectory[count]);\n    hubo->setVelocities(velocities);\n    hubo->setAccelerations(accelerations);\n\n//    hubo->setPositions(mMapping, positions);\n//    clone->setPositions(mMapping, mRaw[count]);\n  }\n\nprotected:\n\n  SkeletonPtr hubo;\n  std::vector<Eigen::VectorXd> mTrajectory;\n  size_t LSR;\n  size_t RSR;\n\n  bool firstLoop;\n  osg::Timer mTimer;\n};\n\n//==============================================================================\nint main()\n{\n  SkeletonPtr robot = hubo::DrcModel::create();\n  robot->getIK(true)->getSolver()->setNumMaxIterations(1000);\n//  std::cout << robot->getIK(true)->getSolver()->getNumMaxIterations() << std::endl;\n  std::vector<Eigen::VectorXd> locations;\n  locations.push_back(robot->getPositions());\n  locations.push_back(robot->getPositions());\n\n//  locations[1][3] += 3*DefaultStepLength;\n  locations[1][3] += 6*DefaultStepLength;\n//  locations[1][3] += 2.0;\n\n  std::vector<size_t> stepRanges;\n  std::vector<Eigen::VectorXd> walk = convertRouteToWalk(robot, locations, stepRanges);\n  std::cout << \"waypoints: \" << walk.size() << std::endl;\n  std::cout << \"Step Ranges: \";\n  for(size_t i=0; i < stepRanges.size(); ++i)\n    std::cout << stepRanges[i] << \", \";\n  std::cout << std::endl;\n\n  HuboPath::Operator mOperator;\n  std::vector<size_t> opIndices;\n  std::vector<std::string> indexNames;\n  for(size_t i=6; i < robot->getNumDofs(); ++i)\n  {\n    DegreeOfFreedom* dof = robot->getDof(i);\n    opIndices.push_back(i);\n    indexNames.push_back(dof->getName());\n  }\n  mOperator.setJointIndices(indexNames);\n\n  HuboPath::Trajectory trajectory;\n  for(size_t r=0; r < stepRanges.size()+1; ++r)\n  {\n    size_t start_i = r==0? 0 : stepRanges[r-1]-1;\n    size_t end_i = r==stepRanges.size()? walk.size() : stepRanges[r];\n    std::cout << \"step from \" << start_i << \" to \" << end_i << std::endl;\n\n    mOperator.clearWaypoints();\n    for(size_t i=start_i; i < end_i; ++i)\n    {\n      robot->setPositions(walk[i]);\n      mOperator.addWaypoint(robot->getPositions(opIndices));\n    }\n\n    HuboPath::Trajectory partial_trajectory = mOperator.getCurrentTrajectory();\n\n    if(r > 0)\n      partial_trajectory.elements.erase(partial_trajectory.elements.begin());\n\n    HuboCan::HuboDescription& desc = partial_trajectory.desc;\n    for(size_t i=0; i < desc.getJointCount(); ++i)\n    {\n      hubo_joint_info_t& info = desc.joints[i]->info;\n      hubo_joint_limits_t& limits = info.limits;\n\n      limits.nominal_speed /= 5.0;\n      limits.nominal_accel /= 5.0;\n    }\n\n    std::cout << \"Initial size of partial: \" << partial_trajectory.elements.size() << std::endl;\n    std::cout << \"Interpolating #\" << r << \"...\" << std::endl;\n    if(!partial_trajectory.interpolate(HUBO_PATH_OPTIMAL))\n    {\n      break;\n    }\n    std::cout << \"Size of partial: \" << partial_trajectory.elements.size() << std::endl;\n\n    if(r==0)\n    {\n      trajectory = partial_trajectory;\n    }\n    else\n    {\n      for(size_t k=0; k < partial_trajectory.size(); ++k)\n        trajectory.elements.push_back(partial_trajectory.elements[k]);\n    }\n  }\n\n\n  bool operate = true;\n//  operate = false;\n\n  if(operate)\n  {\n    if(!trajectory.check_limits())\n    {\n      std::cout << \"Not sending walk trajectory, because it violates limits!\" << std::endl;\n      return 1;\n    }\n\n    mOperator.sendNewTrajectory(trajectory);\n  }\n  else\n  {\n    if(!trajectory.check_limits())\n    {\n      std::cout << \"Walk trajectory violates limits!\" << std::endl;\n    }\n\n    std::vector<Eigen::VectorXd> fullwalk;\n\n    std::cout << \"Converting back to trajectory (\" << trajectory.size() << \")...\"\n              << std::endl;\n    for(size_t i=0; i < trajectory.size(); ++i)\n    {\n      Eigen::VectorXd q(robot->getNumDofs());\n      for(size_t j=0; j < 6; ++j)\n        q[j] = 0.0;\n\n      const IndexArray& indexMap = mOperator.getIndexMap();\n      for(size_t j=6; j < robot->getNumDofs(); ++j)\n        q[j] = trajectory[i].references[indexMap[j-6]];\n\n      fullwalk.push_back(q);\n    }\n    std::cout << \"... converted!\" << std::endl;\n\n    auto world = std::make_shared<World>();\n    world->addSkeleton(robot);\n\n    osg::ref_ptr<TrajectoryDisplayWorld> display =\n        new TrajectoryDisplayWorld(world, fullwalk);\n\n    osgDart::Viewer viewer;\n    viewer.addWorldNode(display);\n    viewer.allowSimulation(false);\n\n    viewer.addAttachment(new osgDart::SupportPolygonVisual(robot, -0.97+0.02));\n\n    viewer.setUpViewInWindow(0, 0, 1280, 960);\n\n    // Set up the default viewing position\n    viewer.getCameraManipulator()->setHomePosition(osg::Vec3( 5.34,  3.00, 1.00),\n                                                   osg::Vec3( 0.00,  0.00, 0.00),\n                                                   osg::Vec3(-0.20, -0.08, 0.98));\n\n    // Reset the camera manipulator so that it starts in the new viewing position\n    viewer.setCameraManipulator(viewer.getCameraManipulator());\n    std::cout << \"Launching viewer\" << std::endl;\n    viewer.run();\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": "62c7c5b28f63560944de1a5041e79ecf04677888", "size": 22884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/hubo-quasi-walk.cpp", "max_stars_repo_name": "mxgrey/protoHuboGUI", "max_stars_repo_head_hexsha": "3384c5e40c544bd472199da9cd6e90e28321a77f", "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": "apps/hubo-quasi-walk.cpp", "max_issues_repo_name": "mxgrey/protoHuboGUI", "max_issues_repo_head_hexsha": "3384c5e40c544bd472199da9cd6e90e28321a77f", "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": "apps/hubo-quasi-walk.cpp", "max_forks_repo_name": "mxgrey/protoHuboGUI", "max_forks_repo_head_hexsha": "3384c5e40c544bd472199da9cd6e90e28321a77f", "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": 30.8409703504, "max_line_length": 128, "alphanum_fraction": 0.6123929383, "num_tokens": 5935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16861980292360948}}
{"text": "// Copyright (c) 2017 - 2019 - The SmartCash Developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"consensus/consensus.h\"\n#include \"init.h\"\n#include \"smartrewards/rewards.h\"\n#include \"smartrewards/rewardspayments.h\"\n#include \"smarthive/hive.h\"\n#include \"smartnode/spork.h\"\n#include \"smartnode/smartnodepayments.h\"\n#include \"ui_interface.h\"\n#include \"validation.h\"\n\n#include <boost/thread.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n\nCSmartRewards *prewards = NULL;\n\nCCriticalSection cs_rewardsdb;\nCCriticalSection cs_rewardrounds;\n\n// Used for time conversions.\nboost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));\n\n// Estimate or return the current block height.\nint GetBlockHeight(const CBlockIndex *index)\n{\n    int64_t syncDiff = std::time(0) - index->GetBlockTime();\n    int64_t firstTxDiff;\n    if( MainNet() ) firstTxDiff = std::time(0) - nStartRewardTime; // Diff from the reward blocks start till now on mainnet.\n    else firstTxDiff = std::time(0) - nFirstTxTimestamp_Testnet; // Diff from the first transaction till now on testnet.\n    return syncDiff > 1200 ? firstTxDiff / 55 : index->nHeight; // If we are 20 minutes near now use the current height.\n}\n\nint ParseScript(const CScript &script, std::vector<CSmartAddress> &ids){\n\n    std::vector<CTxDestination> addresses;\n    txnouttype type;\n    int nRequired;\n\n    if (!ExtractDestinations(script, type, addresses, nRequired)) {\n        return 0;\n    }\n\n    BOOST_FOREACH(const CTxDestination &d, addresses)\n    {\n        ids.push_back(CSmartAddress(d));\n    }\n\n    return nRequired;\n}\n\nvoid CalculateRewardRatio(CSmartRewardRound &round)\n{\n    int64_t time = GetTime();\n    int64_t start = round.startBlockHeight;\n    round.rewards = 0;\n\n    while( start <= round.endBlockHeight) round.rewards += GetBlockValue(start++,0,time) * 0.15;\n\n    CAmount nCalcSmart = round.eligibleSmart - round.disqualifiedSmart;\n\n    if( nCalcSmart ){\n        round.percent = double(round.rewards) / nCalcSmart;\n    }else{\n        round.percent = 0;\n    }\n}\n\nbool CSmartRewards::Verify()\n{\n    LOCK(cs_rewardsdb);\n    return pdb->Verify(rewardHeight);\n}\n\n\nvoid CSmartRewards::UpdatePayoutParameter(CSmartRewardRound &round)\n{\n\n    int64_t nPayeeCount = round.eligibleEntries - round.disqualifiedEntries;\n    int nFirst_1_3_Round = Params().GetConsensus().nRewardsFirst_1_3_Round;\n\n    if( round.number < nFirst_1_3_Round ){\n        round.nBlockPayees  = Params().GetConsensus().nRewardsPayouts_1_2_BlockPayees;\n        round.nBlockInterval = Params().GetConsensus().nRewardsPayouts_1_2_BlockInterval;\n    }else if( nPayeeCount ){\n\n        int64_t nBlockStretch = Params().GetConsensus().nRewardsPayouts_1_3_BlockStretch;\n        int64_t nBlocksPerRound = Params().GetConsensus().nRewardsBlocksPerRound_1_3;\n        int64_t nBlockPayees = Params().GetConsensus().nRewardsPayouts_1_3_BlockPayees;\n\n        round.nBlockPayees = std::max<int>(nBlockPayees, (nPayeeCount / nBlockStretch * nBlockPayees) + 1);\n\n        if( nPayeeCount > round.nBlockPayees ){\n\n            int64_t nStartDelayBlocks = Params().GetConsensus().nRewardsPayoutStartDelay;\n            int64_t nBlocksTarget = nStartDelayBlocks + nBlocksPerRound;\n            round.nBlockInterval = ((nBlockStretch * round.nBlockPayees) / nPayeeCount) + 1;\n            int64_t nStretchedLength = nPayeeCount / round.nBlockPayees * (round.nBlockInterval);\n\n            if( nStretchedLength > nBlocksTarget ){\n                round.nBlockInterval--;\n            }else if( nStretchedLength < nBlockStretch ){\n                round.nBlockInterval++;\n            }\n\n        }else{\n            // If its only one block to pay\n            round.nBlockInterval = 1;\n        }\n\n    }else{\n        // If there are no eligible smartreward entries\n        round.nBlockPayees = 0;\n        round.nBlockInterval = 0;\n    }\n\n}\n\nvoid CSmartRewards::EvaluateRound(CSmartRewardRound &current, CSmartRewardRound &next, CSmartRewardEntryList &entries, CSmartRewardRoundResultList &results)\n{\n    LOCK(cs_rewardsdb);\n    results.clear();\n\n    UpdatePayoutParameter(current);\n\n    int nFirst_1_3_Round = Params().GetConsensus().nRewardsFirst_1_3_Round;\n\n    CAmount nReward;\n\n    BOOST_FOREACH(CSmartRewardEntry &entry, entries) {\n\n        if( current.number ){\n\n            if( current.number < nFirst_1_3_Round ){\n                nReward = entry.balanceEligible > 0 && entry.disqualifyingTx.IsNull() ? CAmount(entry.balanceEligible * current.percent) : 0;\n            }else{\n                nReward = entry.IsEligible() ? CAmount(entry.balanceEligible * current.percent) : 0;\n            }\n\n            results.push_back(CSmartRewardRoundResult(entry, nReward));\n        }\n\n        entry.balanceAtStart = entry.balance;\n\n        if( entry.balance >= SMART_REWARDS_MIN_BALANCE && !SmartHive::IsHive(entry.id) ){\n            entry.balanceEligible = entry.balance;\n        }\n\n        // Reset outgoing transaction with every cycle.\n        entry.disqualifyingTx.SetNull();\n        // Reset SmartNode payment tx with every cycle in case a node was shut down during the cycle.\n        entry.smartnodePaymentTx.SetNull();\n        // Reset the vote proof tx with every cycle to force a new vote for eligibility\n        entry.voteProof.SetNull();\n\n        if( next.number < nFirst_1_3_Round && entry.balanceEligible ){\n            ++next.eligibleEntries;\n            next.eligibleSmart += entry.balanceEligible;\n        }\n    }\n}\n\nbool CSmartRewards::StartFirstRound(const CSmartRewardRound &first, const CSmartRewardEntryList &entries)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->StartFirstRound(first,entries);\n}\n\nbool CSmartRewards::FinalizeRound(const CSmartRewardRound &current, const CSmartRewardRound &next, const CSmartRewardEntryList &entries, const CSmartRewardRoundResultList &results)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->FinalizeRound(current, next, entries, results);\n}\n\nbool CSmartRewards::UndoFinalizeRound(const CSmartRewardRound &current, const CSmartRewardRoundResultList &results)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->UndoFinalizeRound(current, results);\n}\n\nbool CSmartRewards::GetRewardRoundResults(const int16_t round, CSmartRewardRoundResultList &results)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardRoundResults(round, results);\n}\n\nbool CSmartRewards::GetRewardPayouts(const int16_t round, CSmartRewardRoundResultList &payouts)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardPayouts(round, payouts);\n}\n\nbool CSmartRewards::GetRewardPayouts(const int16_t round, CSmartRewardRoundResultPtrList &payouts)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardPayouts(round, payouts);\n}\n\nbool CSmartRewards::GetCachedRewardEntry(const CSmartAddress &id, CSmartRewardEntry *&entry)\n{\n    LOCK(cs_rewardsdb);\n\n    // Return the entry if its already in cache.\n    auto findResult = rewardEntries.find(id);\n\n    if( findResult != rewardEntries.end() ){\n        entry = findResult->second;\n        return true;\n    }\n\n    return false;\n}\n\nbool CSmartRewards::ReadRewardEntry(const CSmartAddress &id, CSmartRewardEntry &entry)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardEntry(id,entry);\n}\n\nbool CSmartRewards::GetRewardEntry(const CSmartAddress &id, CSmartRewardEntry &entry)\n{\n    LOCK(cs_rewardsdb);\n\n    CSmartRewardEntry * pReadEntry;\n\n    if( GetCachedRewardEntry(id,pReadEntry) ){\n        entry = *pReadEntry;\n        return true;\n    }\n\n    return ReadRewardEntry(id,entry);\n}\n\nbool CSmartRewards::GetRewardEntries(CSmartRewardEntryList &entries)\n{\n    LOCK(cs_rewardsdb);\n    return pdb->ReadRewardEntries(entries);\n}\n\nbool CSmartRewards::SyncCached(bool fUndo)\n{\n    return SyncCached(CSmartRewardBlock(), fUndo);\n}\n\nbool CSmartRewards::SyncCached(const CSmartRewardBlock &block, bool fUndo)\n{\n    LOCK2(cs_rewardsdb, cs_rewardrounds);\n\n    bool ret =  pdb->SyncCached(block, currentRound, rewardEntries, transactionEntries, fUndo);\n\n    for( std::pair<CSmartAddress, CSmartRewardEntry*> it : rewardEntries ){\n        delete it.second;\n    }\n\n    rewardEntries.clear();\n    transactionEntries.clear();\n\n    return ret;\n}\n\nbool CSmartRewards::IsSynced()\n{\n    int nSyncDistance = MainNet() ? nRewardsSyncDistance : nRewardsSyncDistance_Testnet;\n    return (chainHeight - rewardHeight) <= nSyncDistance - 1;\n}\n\ndouble CSmartRewards::GetProgress()\n{\n    int nSyncDistance = MainNet() ? nRewardsSyncDistance : nRewardsSyncDistance_Testnet;\n    double progress = chainHeight > nSyncDistance ? double(rewardHeight) / double(chainHeight - nSyncDistance) : 0.0;\n    return progress > 1 ? 1 : progress;\n}\n\nint CSmartRewards::GetLastHeight()\n{\n    return rewardHeight;\n}\n\nint CSmartRewards::GetBlocksPerRound(const int nRound)\n{\n    LOCK(cs_rewardrounds);\n\n    const CChainParams& chainparams = Params();\n\n    if( nRound < chainparams.GetConsensus().nRewardsFirst_1_3_Round ){\n        return chainparams.GetConsensus().nRewardsBlocksPerRound_1_2;\n    }else{\n        return chainparams.GetConsensus().nRewardsBlocksPerRound_1_3;\n    }\n\n}\n\nvoid CSmartRewards::AddTransaction(const CSmartRewardTransaction &transaction)\n{\n    LOCK(cs_rewardsdb);\n    transactionEntries.push_back(transaction);\n}\n\nCSmartRewards::CSmartRewards(CSmartRewardsDB *prewardsdb)  : pdb(prewardsdb)\n{\n    LOCK(cs_rewardsdb);\n\n    // Get the last written block of the rewards database.\n    if(!pdb->ReadLastBlock(currentBlock)){\n        // If there is no one available yet\n        // Use 0 to get 1 as start below.\n        currentBlock.nHeight = 0;\n        currentBlock.blockHash = uint256();\n        currentBlock.blockTime = 0;\n    }\n\n    pdb->ReadRounds(finishedRounds);\n\n    std::sort(finishedRounds.begin(), finishedRounds.end());\n\n    if( finishedRounds.size() ){\n        lastRound = finishedRounds.back();\n    }\n\n    pdb->ReadCurrentRound(currentRound);\n}\n\nvoid CSmartRewards::Lock()\n{\n    LOCK(cs_rewardsdb);\n    pdb->Lock();\n}\n\nbool CSmartRewards::IsLocked()\n{\n    LOCK(cs_rewardsdb);\n    return pdb->IsLocked();\n}\n\nbool CSmartRewards::GetLastBlock(CSmartRewardBlock &block)\n{\n    LOCK(cs_rewardsdb);\n    // Read the last block stored in the rewards database.\n    return pdb->ReadLastBlock(block);\n}\n\nbool CSmartRewards::GetTransaction(const uint256 hash, CSmartRewardTransaction &transaction)\n{\n    // If the transaction is already in the cache use this one.\n    BOOST_FOREACH(CSmartRewardTransaction t, transactionEntries) {\n        if(t.hash == hash){\n            transaction = t;\n            return true;\n        }\n    }\n\n    return pdb->ReadTransaction(hash, transaction);\n}\n\nconst CSmartRewardRound& CSmartRewards::GetCurrentRound()\n{\n    return currentRound;\n}\n\nconst CSmartRewardRound& CSmartRewards::GetLastRound()\n{\n    return lastRound;\n}\n\nconst CSmartRewardRoundList& CSmartRewards::GetRewardRounds()\n{\n    return finishedRounds;\n}\n\nvoid CSmartRewards::UpdateHeights(const int nHeight, const int nRewardHeight)\n{\n    chainHeight = nHeight;\n    rewardHeight = nRewardHeight;\n}\n\nvoid CSmartRewards::StartBlock()\n{\n    rewardEntries.clear();\n    transactionEntries.clear();\n}\n\nvoid CSmartRewards::ProcessTransaction(CBlockIndex* pIndex, const CTransaction& tx, CCoinsViewCache& coins, const CChainParams& chainparams, CSmartRewardsUpdateResult &result)\n{\n    LogPrint(\"smartrewards-tx\", \"CSmartRewards::ProcessTransaction - %s\", tx.GetHash().ToString());\n\n    CSmartRewardEntry *rEntry = nullptr;\n    int nFirst_1_3_Round = chainparams.GetConsensus().nRewardsFirst_1_3_Round;\n\n    int nCurrentRound;\n\n    {\n        LOCK(cs_rewardrounds);\n        nCurrentRound = currentRound.number;\n    }\n\n    int nHeight = pIndex->nHeight;\n\n    if(nHeight > sporkManager.GetSporkValue(SPORK_15_SMARTREWARDS_BLOCKS_ENABLED)){\n        return;\n    }\n\n    int nTime1 = GetTimeMicros();\n\n    CSmartRewardTransaction testTx;\n\n    // First check if the transaction hash did already come up in the past.\n    if( GetTransaction(tx.GetHash(), testTx) ){\n\n        // If yes we want to ignore it! There are some double appearing transactions in the history due to zerocoin exploits.\n        LogPrint(\"smartrewards-tx\", \"CSmartRewards::ProcessTransaction - [%s] Double appearance! First in %d - Now in %d\\n\", testTx.hash.ToString(), testTx.blockHeight, pIndex->nHeight);\n        return;\n\n    }else{\n        // If not save add it to the database.\n        AddTransaction(CSmartRewardTransaction(pIndex->nHeight, tx.GetHash()));\n    }\n\n    CSmartAddress *voteProofCheck = nullptr;\n    CAmount nVoteProofIn = 0;\n    unsigned char cProofOption = 0;\n\n    // No reason to check the input here for new coins.\n    if( !tx.IsCoinBase() ){\n\n        BOOST_FOREACH(const CTxIn &in, tx.vin) {\n\n            if( in.scriptSig.IsZerocoinSpend() ) continue;\n\n            const Coin &coin = coins.AccessCoin(in.prevout);\n            const CTxOut &rOut = coin.out;\n\n            std::vector<CSmartAddress> ids;\n\n            int required = ParseScript(rOut.scriptPubKey ,ids);\n\n            if( !required || required > 1 || ids.size() > 1 ){\n                LogPrint(\"smartrewards-tx\", \"CSmartRewards::ProcessTransaction - Process Inputs: Could't parse CSmartAddress: %s\\n\",rOut.ToString());\n                continue;\n            }\n\n            if(!GetCachedRewardEntry(ids.at(0),rEntry)){\n\n                rEntry = new CSmartRewardEntry(ids.at(0));\n\n                if(!ReadRewardEntry(rEntry->id, *rEntry)){\n                    delete rEntry;\n                    LogPrint(\"smartrewards-tx\", \"CSmartRewards::ProcessTransaction - Spend without previous receive - %s\", tx.ToString());\n                    continue;\n                }\n\n                rewardEntries.insert(make_pair(ids.at(0), rEntry));\n            }\n\n            // If its a voteproof transaction not instantly make the\n            // balance ineligible. First check if the change is sent back\n            // to the address or not to avoid exploiting fund sending\n            // with voteproof transactions\n            if( nCurrentRound >= nFirst_1_3_Round && tx.IsVoteProof() && voteProofCheck == nullptr ){\n                voteProofCheck = new CSmartAddress(rEntry->id);\n                nVoteProofIn += rOut.nValue;\n            }\n\n            rEntry->balance -= rOut.nValue;\n\n            // If its a voteproof transaction not instantly make the\n            // balance ineligible. First check if the change is sent back\n            // to the address or not to avoid exploiting fund sending\n            // with voteproof transactions\n            if( nCurrentRound >= nFirst_1_3_Round && voteProofCheck == nullptr && rEntry->disqualifyingTx.IsNull() ){\n\n                if( rEntry->IsEligible() ){\n                    result.disqualifiedEntries++;\n                    result.disqualifiedSmart += rEntry->balanceEligible;\n                }\n\n                rEntry->disqualifyingTx = tx.GetHash();\n\n            }else if( nCurrentRound < nFirst_1_3_Round && rEntry->disqualifyingTx.IsNull() ){\n\n                rEntry->disqualifyingTx = tx.GetHash();\n\n                if( rEntry->balanceEligible ){\n                    result.disqualifiedEntries++;\n                    result.disqualifiedSmart += rEntry->balanceEligible;\n                }\n\n            }\n\n            if(rEntry->balance < 0 ){\n                LogPrint(\"smartrewards-tx\", \"CSmartRewards::ProcessTransaction - Negative amount?! - %s\", rEntry->ToString());\n                rEntry->balance = 0;\n            }\n\n        }\n    }\n\n    int nTime2 = GetTimeMicros();\n\n    BOOST_FOREACH(const CTxOut &out, tx.vout) {\n\n        if(out.scriptPubKey.IsZerocoinMint() ) continue;\n\n        std::vector<CSmartAddress> ids;\n        int required = ParseScript(out.scriptPubKey ,ids);\n\n        if( !required || required > 1 || ids.size() > 1 ){\n            LogPrint(\"smartrewards-tx\", \"CSmartRewards::ProcessTransaction - Process Outputs: Could't parse CSmartAddress: %s\\n\",out.ToString());\n            continue;\n        }else{\n\n            if(!GetCachedRewardEntry(ids.at(0),rEntry)){\n                rEntry = new CSmartRewardEntry(ids.at(0));\n                ReadRewardEntry(rEntry->id, *rEntry);\n                rewardEntries.insert(make_pair(ids.at(0), rEntry));\n            }\n\n            if( voteProofCheck ){\n\n                if( !out.IsVoteProofData() &&\n                    !(*voteProofCheck == rEntry->id) ){\n\n                    CSmartRewardEntry *vkEntry = nullptr;\n\n                    if(!GetCachedRewardEntry(*voteProofCheck,vkEntry)){\n                        vkEntry = new CSmartRewardEntry(*voteProofCheck);\n                        ReadRewardEntry(vkEntry->id, *vkEntry);\n                        rewardEntries.insert(make_pair(vkEntry->id, vkEntry));\n                    }\n\n                    if( vkEntry->IsEligible() ){\n                        result.disqualifiedEntries++;\n                        result.disqualifiedSmart += vkEntry->balanceEligible;\n                    }\n\n                    // Finally invalidate the balance since the change was not sent\n                    // back to the sender! We don't want to allow\n                    // a exploit to send around funds withouht breaking smartrewards.\n                    vkEntry->disqualifyingTx = tx.GetHash();\n\n                }else if( !out.IsVoteProofData() &&\n                          (*voteProofCheck == rEntry->id) ){\n\n                    CSmartRewardEntry *proofEntry = nullptr;\n                    unsigned char cAddressType = 0;\n                    uint32_t nProofRound;\n                    uint160 addressHash;\n                    uint256 nProposalHash; // Placeholder only for now\n                    CSmartAddress proofAddress;\n\n                    BOOST_FOREACH(const CTxOut &outData, tx.vout) {\n\n                        if( outData.IsVoteProofData() ){\n\n                            std::vector<unsigned char> scriptData;\n                            scriptData.insert(scriptData.end(), outData.scriptPubKey.begin() + 3, outData.scriptPubKey.end());\n                            CDataStream ss(scriptData, SER_NETWORK, 0);\n\n                            ss >> cProofOption;\n                            ss >> nProofRound;\n                            ss >> nProposalHash;\n\n                            if( cProofOption == 0x01 &&\n                                voteProofCheck->ToString(false) != Params().GetConsensus().strRewardsGlobalVoteProofAddress){\n                                proofAddress = *voteProofCheck;\n                                proofEntry = rEntry;\n                            }else if( cProofOption == 0x02 &&\n                                      voteProofCheck->ToString(false) == Params().GetConsensus().strRewardsGlobalVoteProofAddress ){\n\n                                ss >> cAddressType;\n                                ss >> addressHash;\n\n                                if( cAddressType == 0x01 ){\n                                    proofAddress = CSmartAddress(CKeyID(addressHash));\n                                }else if( cAddressType == 0x02){\n                                    proofAddress = CSmartAddress(CScriptID(addressHash));\n                                }else{\n                                    proofAddress = CSmartAddress(); // Invalid address type\n                                }\n\n                                if(!GetCachedRewardEntry(proofAddress, proofEntry)){\n                                    proofEntry = new CSmartRewardEntry(proofAddress);\n                                    ReadRewardEntry(proofEntry->id, *proofEntry);\n                                    rewardEntries.insert(make_pair(proofEntry->id, proofEntry));\n                                }\n\n                            }else{\n                                proofAddress = CSmartAddress(); // Invalid option\n                            }\n                        }\n                    }\n\n                    if( proofAddress.IsValid() && proofEntry != nullptr && !SmartHive::IsHive(*voteProofCheck) ){\n\n                        if( cProofOption == 0x01 && proofEntry->balanceEligible ){\n                            proofEntry->balanceEligible -= nVoteProofIn - tx.GetValueOut();\n\n                            if( proofEntry->balanceEligible < 0 ){\n                                proofEntry->balanceEligible = 0;\n                            }\n                        }\n\n                        if( proofEntry->voteProof.IsNull() ){\n\n                            if( nProofRound == currentRound.number ){\n                                proofEntry->voteProof = tx.GetHash();\n                            }\n\n                            // If the entry is eligible now after the vote proof update the results\n                            if( proofEntry->IsEligible() ){\n                                result.qualifiedEntries++;\n                                result.qualifiedSmart += proofEntry->balanceEligible;\n                            }\n\n                        }\n                    }\n                }\n\n                delete voteProofCheck;\n            }\n\n            rEntry->balance += out.nValue;\n\n            // If we are in the 1.3 cycles check for node rewards to remove node addresses from lists\n            if( nCurrentRound >= nFirst_1_3_Round && tx.IsCoinBase() ){\n\n                int nInterval = SmartNodePayments::PayoutInterval(nHeight);\n                int nPayoutsPerBlock = SmartNodePayments::PayoutsPerBlock(nHeight);\n                // Just to avoid potential zero divisions\n                nPayoutsPerBlock = std::max(1,nPayoutsPerBlock);\n\n                CAmount nNodeReward = SmartNodePayments::Payment(nHeight) / nPayoutsPerBlock;\n\n                // If we have an interval check if this is a node payout block\n                if( nInterval && !(nHeight % nInterval) ){\n\n                    // If the amount matches and the entry is not yet marked as node do it\n                    if( abs(out.nValue - nNodeReward ) < 2 ){\n\n                        if( rEntry->smartnodePaymentTx.IsNull() ){\n\n                            // If it is currently eligible adjust the round's results\n                            if( rEntry->IsEligible() ){\n                                ++result.disqualifiedEntries;\n                                result.disqualifiedSmart += rEntry->balanceEligible;\n                            }\n\n                            rEntry->smartnodePaymentTx = tx.GetHash();\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    int nTime3 = GetTimeMicros();\n    int nTimeTx = nTime3 - nTime1;\n\n    if( LogAcceptCategory(\"smartrewards-tx\") ){\n        LogPrint(\"smartrewards-tx\", \"CSmartRewards::ProcessTransaction - TX %s - %.2fms\\n\",HexStr(tx.GetHash()), nTimeTx * 0.001);\n        LogPrint(\"smartrewards-tx\", \" inputs - %.2fms\\n\", (nTime2 - nTime1) * 0.001);\n        LogPrint(\"smartrewards-tx\", \" outputs - %.2fms\\n\", (nTime3 - nTime2) * 0.001);\n    }\n}\n\nvoid CSmartRewards::UndoTransaction(CBlockIndex* pIndex, const CTransaction& tx, CCoinsViewCache& coins, const CChainParams& chainparams, CSmartRewardsUpdateResult &result)\n{\n    LogPrint(\"smartrewards-tx\", \"CSmartRewards::UndoTransaction - %s\", tx.GetHash().ToString());\n\n    CSmartRewardEntry *rEntry = nullptr;\n    int nFirst_1_3_Round = chainparams.GetConsensus().nRewardsFirst_1_3_Round;\n\n    int nCurrentRound;\n\n    {\n        LOCK(cs_rewardrounds);\n        nCurrentRound = currentRound.number;\n    }\n\n    int nHeight = pIndex->nHeight;\n\n    if(nHeight > sporkManager.GetSporkValue(SPORK_15_SMARTREWARDS_BLOCKS_ENABLED)){\n        return;\n    }\n\n    int nTime1 = GetTimeMicros();\n\n    CSmartRewardTransaction testTx;\n\n    // First check if the transaction hash did already come up in the past.\n    if( GetTransaction(tx.GetHash(), testTx) && testTx.blockHeight == pIndex->nHeight ){\n        AddTransaction(testTx);\n    }else{\n        return;\n    }\n\n    CSmartAddress *voteProofCheck = nullptr;\n    unsigned char cProofOption = 0;\n    CAmount nVoteProofIn = 0, nVoteProofOut = 0;\n\n    if( nCurrentRound >= nFirst_1_3_Round && tx.IsVoteProof() ){\n\n        const Coin &coin = coins.AccessCoin(tx.vin[0].prevout);\n        const CTxOut &rOut = coin.out;\n\n        std::vector<CSmartAddress> ids;\n\n        int required = ParseScript(rOut.scriptPubKey ,ids);\n\n        if( !required || required > 1 || ids.size() > 1 ){\n            LogPrint(\"smartrewards-tx\", \"CSmartRewards::UndoTransaction - Process VoteProof: Could't parse CSmartAddress: %s\\n\",rOut.ToString());\n            return;\n        }\n\n        nVoteProofIn = rOut.nValue;\n        voteProofCheck = new CSmartAddress(ids[0]);\n    }\n\n    BOOST_REVERSE_FOREACH(const CTxOut &out, tx.vout) {\n\n        if(out.scriptPubKey.IsZerocoinMint() ) continue;\n\n        std::vector<CSmartAddress> ids;\n        int required = ParseScript(out.scriptPubKey ,ids);\n\n        if( !required || required > 1 || ids.size() > 1 ){\n            LogPrint(\"smartrewards-tx\", \"CSmartRewards::UndoTransaction - Process Outputs: Could't parse CSmartAddress: %s\\n\",out.ToString());\n            continue;\n        }else{\n\n            if(!GetCachedRewardEntry(ids.at(0),rEntry)){\n                rEntry = new CSmartRewardEntry(ids.at(0));\n                ReadRewardEntry(rEntry->id, *rEntry);\n                rewardEntries.insert(make_pair(ids.at(0), rEntry));\n            }\n\n            if( voteProofCheck ){\n\n                nVoteProofOut += out.nValue;\n\n                if( !out.IsVoteProofData() &&\n                    !(*voteProofCheck == rEntry->id) ){\n\n                    CSmartRewardEntry *vkEntry = nullptr;\n\n                    if(!GetCachedRewardEntry(*voteProofCheck,vkEntry)){\n                        vkEntry = new CSmartRewardEntry(*voteProofCheck);\n                        ReadRewardEntry(vkEntry->id, *vkEntry);\n                        rewardEntries.insert(make_pair(vkEntry->id, vkEntry));\n                    }\n\n                    if( vkEntry->disqualifyingTx == tx.GetHash() ){\n\n                        vkEntry->disqualifyingTx.SetNull();\n\n                        if( vkEntry->IsEligible() ){\n                            --result.disqualifiedEntries;\n                            result.disqualifiedSmart -= vkEntry->balanceEligible;\n                        }\n                    }\n\n                }else if( !out.IsVoteProofData() &&\n                         (*voteProofCheck == rEntry->id) ){\n\n                    CSmartRewardEntry *proofEntry = nullptr;\n                    unsigned char cAddressType = 0;\n                    uint32_t nProofRound;\n                    uint160 addressHash;\n                    uint256 nProposalHash; // Placeholder only for now\n                    CSmartAddress proofAddress;\n\n                    BOOST_FOREACH(const CTxOut &outData, tx.vout) {\n\n                        if( outData.IsVoteProofData() ){\n\n                            std::vector<unsigned char> scriptData;\n                            scriptData.insert(scriptData.end(), outData.scriptPubKey.begin() + 3, outData.scriptPubKey.end());\n                            CDataStream ss(scriptData, SER_NETWORK, 0);\n\n                            ss >> cProofOption;\n                            ss >> nProofRound;\n                            ss >> nProposalHash;\n\n                            if( cProofOption == 0x01 &&\n                                voteProofCheck->ToString(false) != Params().GetConsensus().strRewardsGlobalVoteProofAddress){\n                                proofAddress = *voteProofCheck;\n                                proofEntry = rEntry;\n                            }else if( cProofOption == 0x02 &&\n                                      voteProofCheck->ToString(false) == Params().GetConsensus().strRewardsGlobalVoteProofAddress ){\n\n                                ss >> cAddressType;\n                                ss >> addressHash;\n\n                                if( cAddressType == 0x01 ){\n                                    proofAddress = CSmartAddress(CKeyID(addressHash));\n                                }else if( cAddressType == 0x02){\n                                    proofAddress = CSmartAddress(CScriptID(addressHash));\n                                }else{\n                                    proofAddress = CSmartAddress(); // Invalid address type\n                                }\n\n                                if(!GetCachedRewardEntry(proofAddress, proofEntry)){\n                                    proofEntry = new CSmartRewardEntry(proofAddress);\n                                    ReadRewardEntry(proofEntry->id, *proofEntry);\n                                    rewardEntries.insert(make_pair(proofEntry->id, proofEntry));\n                                }\n\n                            }else{\n                                proofAddress = CSmartAddress(); // Invalid option\n                            }\n                        }\n                    }\n\n                    if( proofAddress.IsValid() && proofEntry != nullptr && !SmartHive::IsHive(*voteProofCheck) ){\n\n                        if( proofEntry->voteProof == tx.GetHash() ){\n\n                            proofEntry->voteProof.SetNull();\n\n                            --result.qualifiedEntries;\n                            result.qualifiedSmart -= proofEntry->balanceEligible;\n\n                            if( cProofOption == 0x01 ){\n                                proofEntry->balanceEligible += nVoteProofIn - nVoteProofOut;\n                            }\n\n                        }\n                    }\n                }\n\n                delete voteProofCheck;\n            }\n\n            rEntry->balance -= out.nValue;\n\n            // If we are in the 1.3 cycles check for node rewards to remove node addresses from lists\n            if( nCurrentRound >= nFirst_1_3_Round && tx.IsCoinBase() ){\n\n                if( rEntry->smartnodePaymentTx == tx.GetHash() ){\n\n                    rEntry->smartnodePaymentTx.SetNull();\n\n                    // If it is eligible now adjust the round's results\n                    if( rEntry->IsEligible() ){\n                        --result.disqualifiedEntries;\n                        result.disqualifiedSmart -= rEntry->balanceEligible;\n                    }\n                }\n            }\n        }\n    }\n\n    int nTime2 = GetTimeMicros();\n\n    // No reason to check the input here for new coins.\n    if( !tx.IsCoinBase() ){\n\n        BOOST_REVERSE_FOREACH(const CTxIn &in, tx.vin) {\n\n            if( in.scriptSig.IsZerocoinSpend() ) continue;\n\n            const Coin &coin = coins.AccessCoin(in.prevout);\n            const CTxOut &rOut = coin.out;\n\n            std::vector<CSmartAddress> ids;\n\n            int required = ParseScript(rOut.scriptPubKey ,ids);\n\n            if( !required || required > 1 || ids.size() > 1 ){\n                LogPrint(\"smartrewards-tx\", \"CSmartRewards::UndoTransaction - Process Inputs: Could't parse CSmartAddress: %s\\n\",rOut.ToString());\n                continue;\n            }\n\n            if(!GetCachedRewardEntry(ids.at(0),rEntry)){\n\n                rEntry = new CSmartRewardEntry(ids.at(0));\n\n                if(!ReadRewardEntry(rEntry->id, *rEntry)){\n                    delete rEntry;\n                    LogPrint(\"smartrewards-tx\", \"CSmartRewards::UndoTransaction - Spend without previous receive - %s\", tx.ToString());\n                    continue;\n                }\n\n                rewardEntries.insert(make_pair(ids.at(0), rEntry));\n            }\n\n            rEntry->balance += rOut.nValue;\n\n            // If its a voteproof transaction not instantly make the\n            // balance ineligible. First check if the change is sent back\n            // to the address or not to avoid exploiting fund sending\n            // with voteproof transactions\n            if( nCurrentRound >= nFirst_1_3_Round && voteProofCheck == nullptr && rEntry->disqualifyingTx == tx.GetHash() ){\n\n                rEntry->disqualifyingTx.SetNull();\n\n                if( rEntry->IsEligible() ){\n                    --result.disqualifiedEntries;\n                    result.disqualifiedSmart -= rEntry->balanceEligible;\n                }\n\n            }else if( nCurrentRound < nFirst_1_3_Round && rEntry->disqualifyingTx == tx.GetHash() ){\n\n                rEntry->disqualifyingTx.SetNull();\n\n                if( rEntry->balanceEligible ){\n                    --result.disqualifiedEntries;\n                    result.disqualifiedSmart -= rEntry->balanceEligible;\n                }\n\n            }\n\n            if(rEntry->balance < 0 ){\n                LogPrint(\"smartrewards-tx\", \"CSmartRewards::UndoTransaction - Negative amount?! - %s\", rEntry->ToString());\n                rEntry->balance = 0;\n            }\n\n        }\n    }\n\n    int nTime3 = GetTimeMicros();\n    int nTimeTx = nTime3 - nTime1;\n\n    if( LogAcceptCategory(\"smartrewards-tx\") ){\n        LogPrint(\"smartrewards-tx\", \"CSmartRewards::UndoTransaction - TX %s - %.2fms\\n\",HexStr(tx.GetHash()), nTimeTx * 0.001);\n        LogPrint(\"smartrewards-tx\", \" outputs - %.2fms\\n\", (nTime2 - nTime1) * 0.001);\n        LogPrint(\"smartrewards-tx\", \" inputs - %.2fms\\n\", (nTime3 - nTime2) * 0.001);\n    }\n}\n\nbool CSmartRewards::CommitBlock(CBlockIndex* pIndex, const CSmartRewardsUpdateResult& result)\n{\n    int nTime1 = GetTimeMicros();\n\n    if(pIndex && pIndex->nHeight > sporkManager.GetSporkValue(SPORK_15_SMARTREWARDS_BLOCKS_ENABLED)){\n        return true;\n    }\n\n    if(!pIndex || pIndex->nHeight != currentBlock.nHeight + 1 ){\n        LogPrintf(\"CSmartRewards::CommitBlock - Invalid next block!\");\n        return false;\n    }\n\n    if(!SyncCached(result.block, false)){\n        LogPrintf(\"CSmartRewards::CommitBlock - Failed to sync cache - Initial!\");\n        return false;\n    }\n\n    // Update the current block to the processed one\n    currentBlock = result.block;\n\n    // For the first round we have special parameter..\n    if( !currentRound.number ){\n\n        if( (MainNet() && pIndex->GetBlockTime() > nFirstRoundStartTime) ||\n            (TestNet() && pIndex->nHeight >= nFirstRoundStartBlock_Testnet) ){\n\n            // Create the very first smartrewards round.\n            CSmartRewardRound first;\n            first.number = 1;\n            first.startBlockTime = pIndex->GetBlockTime();\n            first.startBlockHeight = MainNet() ? nFirstRoundStartBlock : nFirstRoundStartBlock_Testnet;\n            first.endBlockTime = MainNet() ? nFirstRoundEndTime : nFirstRoundEndTime_Testnet;\n            // Estimate the block, gets updated on the end of the round to the real one.\n            first.endBlockHeight = MainNet() ? nFirstRoundEndBlock : nFirstRoundEndBlock_Testnet;\n\n            CSmartRewardEntryList entries;\n            CSmartRewardRoundResultList results;\n\n            // Get the current entries\n            if( !GetRewardEntries(entries) ){\n                LogPrintf(\"CSmartRewards::CommitBlock - Failed to read all reward entries!\");\n                return false;\n            }\n\n            // Evaluate the round and update the next rounds parameter.\n            EvaluateRound(currentRound, first, entries, results );\n\n            CalculateRewardRatio(first);\n\n            if( !StartFirstRound(first, entries) ){\n                LogPrintf(\"CSmartRewards::CommitBlock - Failed to finalize round!\");\n                return false;\n            }\n\n            currentRound = first;\n        }\n\n    }else if( result.disqualifiedEntries || result.disqualifiedSmart ||\n              result.qualifiedEntries || result.qualifiedSmart ){\n\n        // If there were disqualification during the last block processing\n        // update the current round stats.\n\n        currentRound.disqualifiedEntries += result.disqualifiedEntries;\n        currentRound.disqualifiedSmart += result.disqualifiedSmart;\n\n        currentRound.eligibleEntries += result.qualifiedEntries;\n        currentRound.eligibleSmart += result.qualifiedSmart;\n\n        CalculateRewardRatio(currentRound);\n    }\n\n    // If just hit the next round threshold\n    if( ( MainNet() && currentRound.number < nRewardsFirstAutomatedRound - 1 && pIndex->GetBlockTime() > currentRound.endBlockTime ) ||\n        ( ( TestNet() || currentRound.number >= nRewardsFirstAutomatedRound - 1 ) && pIndex->nHeight == currentRound.endBlockHeight ) ){\n\n        // Write the round to the history\n        currentRound.endBlockHeight = pIndex->nHeight;\n        currentRound.endBlockTime = pIndex->GetBlockTime();\n\n        CSmartRewardEntryList entries;\n        CSmartRewardRoundResultList results;\n\n        // Create the next round.\n        CSmartRewardRound next;\n        next.number = currentRound.number + 1;\n        next.startBlockTime = currentRound.endBlockTime;\n        next.startBlockHeight = currentRound.endBlockHeight + 1;\n\n        int nBlocksPerRound = GetBlocksPerRound(next.number);\n        time_t startTime = (time_t)next.startBlockTime;\n\n        if( MainNet() ){\n\n            if( next.number == nRewardsFirstAutomatedRound - 1 ){\n                // Let the round 12 end at height 574099 so that round 13 starts at 574100\n                next.endBlockHeight = HF_V1_2_SMARTREWARD_HEIGHT - 1;\n                next.endBlockTime = startTime + ( (next.endBlockHeight - next.startBlockHeight) * 55 );\n            }else if(next.number < nRewardsFirstAutomatedRound){\n\n                boost::gregorian::date endDate = boost::posix_time::from_time_t(startTime).date();\n\n                endDate += boost::gregorian::months(1);\n                // End date at 00:00:00 + 25200 seconds (7 hours) to match the date at 07:00 UTC\n                next.endBlockTime = time_t((boost::posix_time::ptime(endDate, boost::posix_time::seconds(25200)) - epoch).total_seconds());\n                next.endBlockHeight = next.startBlockHeight + ( (next.endBlockTime - next.startBlockTime) / 55 );\n            }else{\n                next.endBlockHeight = next.startBlockHeight + nBlocksPerRound - 1;\n                next.endBlockTime = startTime + nBlocksPerRound * 55;\n            }\n\n        }else{\n            next.endBlockHeight = next.startBlockHeight + nBlocksPerRound - 1;\n            next.endBlockTime = startTime + nBlocksPerRound * 55;\n        }\n\n        // Get the current entries\n        if( !GetRewardEntries(entries) ){\n            LogPrintf(\"CSmartRewards::CommitBlock - Failed to read all reward entries!\");\n            return false;\n        }\n\n        CalculateRewardRatio(currentRound);\n\n        // Evaluate the round and update the next rounds parameter.\n        EvaluateRound(currentRound, next, entries, results);\n\n        CalculateRewardRatio(next);\n\n        if( !FinalizeRound(currentRound, next, entries, results) ){\n            LogPrintf(\"CSmartRewards::CommitBlock - Failed to finalize round!\");\n            return false;\n        }\n\n        LOCK(cs_rewardrounds);\n\n        finishedRounds.push_back(currentRound);\n        lastRound = currentRound;\n        currentRound = next;\n    }\n\n    if(!SyncCached()){\n        LogPrintf(\"CSmartRewards::CommitBlock - Failed to sync cached - Processed!\");\n        return false;\n    }\n\n    prewards->UpdateHeights(GetBlockHeight(pIndex), currentBlock.nHeight);\n\n    int nTime2 = GetTimeMicros();\n\n    if( LogAcceptCategory(\"smartrewards-block\") ){\n            LogPrint(\"smartrewards-block\", \"Round %d - Block: %d - Progress %d%%\\n\",currentRound.number, currentBlock.nHeight, int(prewards->GetProgress() * 100));\n            LogPrint(\"smartrewards-block\", \"  Commit block: %.2fms\\n\", (nTime2 - nTime1) * 0.001);\n    }\n\n    // If we are synced notify the UI on each new block.\n    // If not notify the UI every nRewardsUISyncUpdateRate blocks to let it update the\n    // loading screen.\n    if( IsSynced() || !(currentBlock.nHeight % nRewardsUISyncUpdateRate) )\n        uiInterface.NotifySmartRewardUpdate();\n\n    return true;\n}\n\nbool CSmartRewards::CommitUndoBlock(CBlockIndex *pIndex, const CSmartRewardsUpdateResult &result)\n{\n    int nTime1 = GetTimeMicros();\n\n    if(pIndex && pIndex->nHeight > sporkManager.GetSporkValue(SPORK_15_SMARTREWARDS_BLOCKS_ENABLED)){\n        return true;\n    }\n\n    if(!pIndex || pIndex->nHeight != currentBlock.nHeight ){\n        LogPrintf(\"CSmartRewards::CommitUndoBlock - Invalid next block!\");\n        return false;\n    }\n\n    if(!SyncCached(result.block, true)){\n        LogPrintf(\"CSmartRewards::CommitUndoBlock - Failed to sync cache - Initial!\");\n        return false;\n    }\n\n    currentBlock = CSmartRewardBlock(pIndex->pprev->nHeight, pIndex->pprev->GetBlockHash(), pIndex->pprev->GetBlockTime() );\n\n    if( result.disqualifiedEntries || result.disqualifiedSmart ||\n        result.qualifiedEntries || result.qualifiedSmart ){\n\n        // If there were disqualification during the last block processing\n        // update the current round stats.\n\n        currentRound.disqualifiedEntries += result.disqualifiedEntries;\n        currentRound.disqualifiedSmart += result.disqualifiedSmart;\n\n        currentRound.eligibleEntries += result.qualifiedEntries;\n        currentRound.eligibleSmart += result.qualifiedSmart;\n\n        CalculateRewardRatio(currentRound);\n    }\n\n    // If just hit the last round's threshold\n    if( ( MainNet() && currentRound.number < nRewardsFirstAutomatedRound - 1 && pIndex->GetBlockTime() < currentRound.endBlockTime ) ||\n            ( ( TestNet() || currentRound.number >= nRewardsFirstAutomatedRound - 1 ) && pIndex->nHeight == currentRound.startBlockHeight ) ){\n\n        LOCK2(cs_rewardsdb, cs_rewardrounds);\n\n        // Recover the last round from the history as current round\n        currentRound = finishedRounds.back();\n        finishedRounds.pop_back();\n\n        lastRound = finishedRounds.back();\n\n        CSmartRewardEntryList entries;\n        CSmartRewardRoundResultList results;\n\n        // Get the current entries\n        if( !GetRewardRoundResults(currentRound.number, results) ){\n            LogPrintf(\"CSmartRewards::CommitUndoBlock - Failed to read last round's results!\");\n            return false;\n        }\n\n        CalculateRewardRatio(currentRound);\n\n        if( !UndoFinalizeRound(currentRound, results) ){\n            LogPrintf(\"CSmartRewards::CommitUndoBlock - Failed to finalize round!\");\n            return false;\n        }\n\n    }\n\n    if(!SyncCached(true)){\n        LogPrintf(\"CSmartRewards::CommitUndoBlock - Failed to sync cached - Processed!\");\n        return false;\n    }\n\n    prewards->UpdateHeights(GetBlockHeight(pIndex), currentBlock.nHeight);\n\n    int nTime2 = GetTimeMicros();\n\n    if( LogAcceptCategory(\"smartrewards-block\") ){\n        LogPrint(\"smartrewards-block\", \"Round %d - Block: %d - Progress %d%%\\n\",currentRound.number, currentBlock.nHeight, int(prewards->GetProgress() * 100));\n        LogPrint(\"smartrewards-block\", \"  Commit undo block: %.2fms\\n\", (nTime2 - nTime1) * 0.001);\n    }\n\n    // If we are synced notify the UI on each new block.\n    // If not notify the UI every nRewardsUISyncUpdateRate blocks to let it update the\n    // loading screen.\n    if( IsSynced() || !(currentBlock.nHeight % nRewardsUISyncUpdateRate) )\n        uiInterface.NotifySmartRewardUpdate();\n\n    return true;\n}\n", "meta": {"hexsha": "caeb527e5cd534f12d8f63402d3485f88fb093a1", "size": 42935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/smartrewards/rewards.cpp", "max_stars_repo_name": "thesolarminer/Core-Smart", "max_stars_repo_head_hexsha": "e3d2be76a40cecca8726e0b05d9a3424891801e5", "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/smartrewards/rewards.cpp", "max_issues_repo_name": "thesolarminer/Core-Smart", "max_issues_repo_head_hexsha": "e3d2be76a40cecca8726e0b05d9a3424891801e5", "max_issues_repo_licenses": ["MIT"], "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/smartrewards/rewards.cpp", "max_forks_repo_name": "thesolarminer/Core-Smart", "max_forks_repo_head_hexsha": "e3d2be76a40cecca8726e0b05d9a3424891801e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-15T21:39:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T21:39:45.000Z", "avg_line_length": 36.2320675105, "max_line_length": 186, "alphanum_fraction": 0.5997670898, "num_tokens": 9797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.16861980077497735}}
{"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#include <thrust/device_ptr.h>\n#include <thrust/sort.h>\n\n#define EXPORT \n#define INFO\n#define _USE_MATH_DEFINES\n#define  NOMINMAX \n#include <GL/glew.h>\n#include <cuda.h>\n#include <cuda_gl_interop.h>\n#include <cuda_runtime_api.h>\n//stl\n#include <iostream>\n#include <string>\n#include <vector>\n#include <limits>\n\n#ifdef __gnu_linux__\n#include <sys/types.h>\n#include <sys/stat.h>\n#elif _WIN32\n#include <direct.h>\n#else \n#error \"OS not supported!\"\n#endif\n\n#include <math.h>\n#include <limits>\n//boost\n#include <boost/lexical_cast.hpp>\n#include <boost/random.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/math/special_functions/fpclassify.hpp> //isnan\n#include <boost/lexical_cast.hpp>\n#include <boost/iostreams/device/file.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/filesystem.hpp>\n\n//openncv\n#include <opencv2/opencv.hpp>\n#include <opencv2/xfeatures2d/nonfree.hpp>\n#include <opencv2/xfeatures2d.hpp>\n#include <opencv2/cudaarithm.hpp>\n#include <opencv2/cudaimgproc.hpp>\n#include <opencv2/cudafilters.hpp>\n#include <opencv2/cudafeatures2d.hpp>\n#include <opencv2/cudawarping.hpp>\n\n#include <se3.hpp>\n\n#include <utility>\n#include <OpenNI.h>\n#include \"Converters.hpp\"\n#include \"GLUtil.hpp\"\n#include \"CVUtil.hpp\"\n#include \"EigenUtil.hpp\"\n#include \"pcl/internal.h\"\n#include \"Camera.h\"\n#include \"IntrinsicAnalysis.cuh\"\n#include \"KeyFrame.h\"\n#include \"VideoSourceKinect.hpp\"\n#include \"TSDF.h\"\n\n#include \"KinfuTracker.h\"\n#include \"CudaLib.cuh\" \n\n#include \"DVOICP.cuh\"\n#include \"DirectOrientation.cuh\"\n#include \"ExposureEstimation.cuh\"\n#include \"Utility.hpp\"\n#include \"Kinect.h\"\n#include \"pcl/vector_math.hpp\"\n#include \"Converters.hpp\"\n\nusing namespace cv;\nusing namespace cv::cuda;\nusing namespace std;\nusing namespace btl::kinect;\nusing namespace btl::utility;\nusing namespace btl::image;\nusing namespace btl::device;\n//using namespace pcl::device;\nusing namespace Eigen;\nusing namespace Sophus;\n\nnamespace btl{ namespace geometry\n{\n\nCKinFuTracker::CKinFuTracker(CKeyFrame::tp_ptr pKeyFrame_, CTsdfBlock::tp_shared_ptr pGlobalMap_, int nResolution_/*=0*/, int nPyrHeight_/*=3*/)\n\t:_pGlobalMap(pGlobalMap_),_nResolution(nResolution_),_nPyrHeight(nPyrHeight_)\n{\n\t_v_T_cw_tracking.clear();\n\n\t_aMinEnergy[0] = .5f;//6.f;\n\t_aMinEnergy[1] = .5f;//100.f;\n\t_aMinEnergy[2] = .1f;//2000.f;\n\t_aMinEnergy[3] = 1.f;// 2000.f;\n\t_aMinEnergy[4] = 2000.f;//1000.f;\n\n}\n\nbool CKinFuTracker::init(const CKeyFrame::tp_ptr pCurFrame_){\n\t_nCols = pCurFrame_->_agPyrPts[0]->cols;\n\t_nRows = pCurFrame_->_agPyrPts[0]->rows;\n\n\tostringstream directory;\n\tdirectory << \"..//data//\" << _serial_number << \"//crf.yml\";\n\tif (!_pIAPrev)\n\t\t_pIAPrev.reset(new btl::device::CIntrinsicsAnalysisMult(directory.str(), _nRows, _nCols, .25, 40));\n\tif (!_pIACurr)\n\t\t_pIACurr.reset(new btl::device::CIntrinsicsAnalysisMult(directory.str(), _nRows, _nCols, .25, 40));\n\tGpuMat bgr;\n\tcuda::cvtColor(pCurFrame_->_gRGB, bgr, CV_RGB2BGR);\n\t_pIACurr->analysis(bgr);\n\tconstructLivePyr();\n\n\t_pRefFrame.reset();\n\t_pRefFrame.reset(new CKeyFrame(pCurFrame_));\t//copy pKeyFrame_ to _pPrevFrameWorld\n\t\n\t//integrate the frame into the world\n\tGpuMat radiance;\n\tcuda::merge(_pIACurr->_vRadianceBGR, radiance);\n\tGpuMat er;\n\tcuda::merge(_pIACurr->_error_bgr, 3, er);\n\tGpuMat normal_radiance;\n\tcuda::merge(_pIACurr->_normalized_bgr, 3, normal_radiance);\n\t_pGlobalMap->gpuIntegrateDepth(*pCurFrame_->_agPyrDepths[0], *pCurFrame_->_agPyrNls[0], normal_radiance, radiance, er, \n\t\t\t\t\t\t\t\t\tSE3Group<double>(pCurFrame_->_R_cw, pCurFrame_->_Tw));\n\n\t//initialize pose\n\tpCurFrame_->getPrjCfW(&_pose_refined_c_f_w);\n\t_v_T_cw_tracking.push_back(_pose_refined_c_f_w);\n\n\t//store current key point\n\tstoreCurrFrameSynthetic(pCurFrame_);\n\t//storeCurrFrameReal(pCurFrame_);\n\tPRINTSTR(\"End of init\");\n\n\treturn true;\n}\n\nvoid CKinFuTracker::storeCurrFrameSynthetic(CKeyFrame::tp_ptr pCurFrame_){\n\tpCurFrame_->copyTo(&*_pRefFrame);\n\t_n_rad_origin_2_ref = _n_rad_live[2].clone();\n\t_pIACurr->copyTo(*_pIAPrev);\n\n\tif (_pRefFrame->_gRadiance.empty()){\n\t\t_pRefFrame->_gRadiance.create(_pRefFrame->_agPyrPts[0]->size(), CV_32FC3);\n\t}\n\tif (_pRefFrame->_gNR.empty()){\n\t\t_pRefFrame->_gNR.create(_pRefFrame->_agPyrPts[0]->size(), CV_32FC3);\n\t}\n\n\t_pGlobalMap->gpuRayCastingAll( _pRefFrame->_pRGBCamera->getIntrinsics(0), _pRefFrame->_R_cw, _pRefFrame->_Tw,\n\t\t\t\t\t\t\t\t\t\t&*_pRefFrame->_agPyrPts[0], &*_pRefFrame->_agPyrNls[0], &_pRefFrame->_gRadiance, &_pRefFrame->_gNR); \n\tcuda::split(_pRefFrame->_gNR, _pIAPrev->_normalized_bgr);\n\tcuda::split(_pRefFrame->_gRadiance, _pIAPrev->_vRadianceBGR);\n\n\tconstructRefePyr();\n\t\n\tpCurFrame_->getPrjCfW(&_pose_refined_c_f_w);\n\t_v_T_cw_tracking.push_back(_pose_refined_c_f_w);\n\n\treturn;\n}\n\nvoid CKinFuTracker::displayCameraPath() const{\n\tvector<Eigen::Affine3d>::const_iterator cit = _v_T_cw_tracking.begin(); //from world to camera\n\t\n\tglDisable(GL_LIGHTING);\n\tglColor3f ( 0.f,0.f,1.f); \n\tglLineWidth(2.f);\n\tglBegin(GL_LINE_STRIP);\n\tfor (; cit != _v_T_cw_tracking.end(); cit++ )\n\t{\n\t\tSO3Group<double> mR = cit->linear();\n\t\tVector3d vT = cit->translation();\n\t\tVector3d vC = mR.inverse() *(-vT);\n\t\tvC = mR.inverse()*(-vT);\n\t\tglVertex3dv( vC.data() );\n\t}\n\tglEnd();\n\treturn;\n}\n\nvoid CKinFuTracker::getPrevView( Eigen::Affine3d* pSystemPose_ ){\n\tint s = _v_T_cw_tracking.size();\n\t*pSystemPose_ = _v_T_cw_tracking[s-2];\n\treturn;\n}\nvoid CKinFuTracker::getNextView( Eigen::Affine3d* pSystemPose_ ){\n\t*pSystemPose_ = _v_T_cw_tracking.front();\n\tPRINT(_v_T_cw_tracking.front().matrix());\n\treturn;\n}\n\ndouble CKinFuTracker::dvoICPIC(const CKeyFrame::tp_ptr pRefeFrame_, CKeyFrame::tp_ptr pLiveFrame_, const short asICPIterations_[], SE3Group<double>* pT_rl_, Eigen::Vector4i* pActualIter_) const\n{\n\tSE3Group<double> PrevT_rl = *pT_rl_;\n\tSE3Group<double> NewT_rl = *pT_rl_;\n\t//get R,T of previous \n\tMatrix3d R_rl_t_tmp = PrevT_rl.so3().inverse().matrix();\n\tconst Matd33&  devR_rl = pcl::device::device_cast<pcl::device::Matd33> (R_rl_t_tmp); //implicit inverse\n\n\tVector3d t_rl = PrevT_rl.translation();\n\tconst double3& devT_rl = pcl::device::device_cast<double3> (t_rl);\n\n\t//from low resolution to high\n\tdouble dCurEnergy = numeric_limits<double>::max();\n\tfor (short sPyrLevel = pLiveFrame_->pyrHeight() - 1; sPyrLevel >= 0; sPyrLevel--){\n\t\t// for each pyramid level we have a min energy and corresponding best R t\n\t\tif (asICPIterations_[sPyrLevel] > 0){\n\t\t\tdCurEnergy = btl::device::dvo_icp_energy(pLiveFrame_->_pRGBCamera->getIntrinsics(sPyrLevel),\n\t\t\t\tdevR_rl, devT_rl,\n\t\t\t\t*pRefeFrame_->_agPyrPts[sPyrLevel], *pRefeFrame_->_agPyrNls[sPyrLevel], _n_rad_ref[sPyrLevel],\n\t\t\t\t*pLiveFrame_->_agPyrPts[sPyrLevel], *pLiveFrame_->_agPyrNls[sPyrLevel], _n_rad_live[sPyrLevel],\n\t\t\t\t*pLiveFrame_->_agPyrDepths[sPyrLevel], _err_live[sPyrLevel], *pLiveFrame_->_pry_mask[sPyrLevel]);\n\t\t\t//PRINT(dMinEnergy);\n\t\t}\n\n\t\tSE3Group<double> MinT_rl = NewT_rl;\n\t\tdouble dMin = dCurEnergy;\n\t\tdouble dPrevEnergy = dCurEnergy;\n\t\tfor (short sIter = 0; sIter < asICPIterations_[sPyrLevel]; ++sIter) {\n\t\t\t//get R and T\n\t\t\tGpuMat cvgmSumBuf = btl::device::dvo_icp(pLiveFrame_->_pRGBCamera->getIntrinsics(sPyrLevel),\n\t\t\t\tdevR_rl, devT_rl,\n\t\t\t\t*pRefeFrame_->_agPyrPts[sPyrLevel], *pRefeFrame_->_agPyrNls[sPyrLevel], _n_rad_ref[sPyrLevel],\n\t\t\t\t*pLiveFrame_->_agPyrPts[sPyrLevel], *pLiveFrame_->_agPyrNls[sPyrLevel], _n_rad_live[sPyrLevel],\n\t\t\t\t*pLiveFrame_->_agPyrDepths[sPyrLevel], _err_live[sPyrLevel], *pLiveFrame_->_pry_mask[sPyrLevel]);\n\t\t\tMat Buf; cvgmSumBuf.download(Buf);\n\t\t\tSE3Group<double> Tran_nc = btl::utility::extractRTFromBuffer<double>((double*)Buf.data);\n\t\t\tNewT_rl = Tran_nc * PrevT_rl;\n\t\t\tR_rl_t_tmp = NewT_rl.so3().inverse().matrix();\n\t\t\tt_rl = NewT_rl.translation();\n\t\t\tdCurEnergy = btl::device::dvo_icp_energy(pLiveFrame_->_pRGBCamera->getIntrinsics(sPyrLevel),\n\t\t\t\tdevR_rl, devT_rl,\n\t\t\t\t*pRefeFrame_->_agPyrPts[sPyrLevel], *pRefeFrame_->_agPyrNls[sPyrLevel], _n_rad_ref[sPyrLevel],\n\t\t\t\t*pLiveFrame_->_agPyrPts[sPyrLevel], *pLiveFrame_->_agPyrNls[sPyrLevel], _n_rad_live[sPyrLevel],\n\t\t\t\t*pLiveFrame_->_agPyrDepths[sPyrLevel], _err_live[sPyrLevel], *pLiveFrame_->_pry_mask[sPyrLevel]);\n\t\t\t//cout << sIter << \": \" << dPrevEnergy << \" \" << dCurEnergy << endl;\n\t\t\tif (dCurEnergy < dMin){\n\t\t\t\tdMin = dCurEnergy;\n\t\t\t\tMinT_rl = NewT_rl;\n\t\t\t}\n\t\t\tif (dMin / dCurEnergy > 1.125){ //diverges\n\t\t\t\t//cout << \"Diverge Warning:\" << endl;\n\t\t\t\t//cout <<\"New \"<< NewT_rl.matrix() << endl;\n\t\t\t\t//cout <<\"Prev\" <<PrevT_rl.matrix() << endl;\n\t\t\t\tNewT_rl = MinT_rl;\n\t\t\t\tdCurEnergy = dMin;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tPrevT_rl = NewT_rl;\n\t\t\tif (fabs(dPrevEnergy / dCurEnergy - 1) < 1e-6f){ //converges\n\t\t\t\t//cout << \"Converges\" << endl;\n\t\t\t\tdCurEnergy = dMin;\n\t\t\t\tNewT_rl = MinT_rl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdPrevEnergy = dCurEnergy;\n\t\t}//for each iteration\n\t}//for pyrlevel\n\t*pT_rl_ = NewT_rl;\n\tSE3Group<double> T_rw(pRefeFrame_->_R_cw, pRefeFrame_->_Tw);\n\tT_rw = NewT_rl.inverse()*T_rw;\n\tpLiveFrame_->_R_cw = T_rw.so3();\n\tpLiveFrame_->_Tw = T_rw.translation();\n\n\treturn dCurEnergy;\n}\n\ndouble CKinFuTracker::directRotation(const CKeyFrame::tp_ptr pRefeFrame_, const CKeyFrame::tp_ptr pLiveFrame_, SO3Group<double>* pR_rl_)\n{\n\tIntr sCamIntr_ = pRefeFrame_->_pRGBCamera->getIntrinsics(2);\n\tMatrix3d K = Matrix3d::Identity();\n\t//note that camera parameters are \n\tK(0, 0) = sCamIntr_.fx;\n\tK(1, 1) = sCamIntr_.fy;\n\tK(0, 2) = sCamIntr_.cx;\n\tK(1, 2) = sCamIntr_.cy;\n\tSO3Group<double> CurR_rl_ = *pR_rl_;\n\tSO3Group<double> PrevR_rl_ = *pR_rl_;\n\tSO3Group<double> MinR_rl_ = *pR_rl_;\n\tMatrix3d R_rl_Kinv = PrevR_rl_.matrix() *K.inverse();\n\tMatrix3d H_rl = K * R_rl_Kinv;\n\n\t//get R,T of previous \n\tMatrix3d H_rl_t = H_rl.transpose();\n\tMatrix3d R_rl_Kinv_t = R_rl_Kinv.transpose();\n\tconst Matd33&  devH_rl = pcl::device::device_cast<pcl::device::Matd33> (H_rl_t);\n\tconst Matd33&  devR_rl_Kinv = pcl::device::device_cast<pcl::device::Matd33> (R_rl_Kinv_t);\n\tdouble dMinEnergy = numeric_limits<double>::max();\n\tdouble dPrevEnergy = numeric_limits<double>::max();\n\tdPrevEnergy = energy_direct_radiance_rotation(sCamIntr_, devR_rl_Kinv, devH_rl, _n_rad_origin_2_ref, _n_rad_live[2], _err_live[2]);\n\tdMinEnergy = dPrevEnergy;\n\t//cout << setprecision(15) << dMinEnergy << endl;\n\tfor (short sIter = 0; sIter < 5; ++sIter) {\n\t\t//get R and T\n\t\tGpuMat gSumBuf = btl::device::direct_rotation(sCamIntr_, devR_rl_Kinv, devH_rl, _n_rad_origin_2_ref, _n_rad_live[2], _err_live[2]);\n\t\tMat Buf; gSumBuf.download(Buf);\n\t\tSO3Group<double> R_rl = btl::utility::extractRFromBuffer<double>((double*)Buf.data);\n\t\t//cout << Tran_nc.matrix() << endl;\n\t\tCurR_rl_ = R_rl *PrevR_rl_;\n\t\tR_rl_Kinv = CurR_rl_.matrix()*K.inverse();\n\t\tH_rl = K * R_rl_Kinv;\n\n\t\tH_rl_t = H_rl.transpose();\n\t\tR_rl_Kinv_t = R_rl_Kinv.transpose();\n\t\tdouble dCurEnergy = energy_direct_radiance_rotation(sCamIntr_, devR_rl_Kinv, devH_rl, _n_rad_origin_2_ref, _n_rad_live[2], _err_live[2]);\n\t\t//cout << sIter << \": \" << dPrevEnergy << \" \" << dCurEnergy << endl;\n\t\tif (dCurEnergy < dMinEnergy){\n\t\t\tdMinEnergy = dCurEnergy;\n\t\t\tMinR_rl_ = CurR_rl_;\n\t\t}\n\t\tif (dMinEnergy / dCurEnergy < 0.25){ //divereges\n\t\t\t//cout << \"Diverge Warning:\" << endl;\n\t\t\tdCurEnergy = dMinEnergy;\n\t\t\tCurR_rl_ = MinR_rl_;\n\t\t\tbreak;\n\t\t}\n\t\tPrevR_rl_ = CurR_rl_;\n\t\tif (fabs(dPrevEnergy / dCurEnergy - 1) < 0.01f){ //converges\n\t\t\t//cout << \"Converges\" << endl;\n\t\t\tdCurEnergy = dMinEnergy;\n\t\t\tCurR_rl_ = MinR_rl_;\n\t\t\tbreak;\n\t\t}\n\t\tdPrevEnergy = dCurEnergy;\n\t}\n\t*pR_rl_ = CurR_rl_;\n\treturn dMinEnergy;\n}\n\ndouble CKinFuTracker::icp(CKeyFrame::tp_ptr pRefeFrame_, CKeyFrame::tp_ptr pLiveFrame_){\n\tusing namespace btl::device;\n\t//using the ICP to refine each hypotheses and store their alignment score\n\tdouble dICPEnergy = numeric_limits<double>::max();\n\t//do ICP as one of pose hypotheses\n\tSO3Group<double> R_rl; Vector3d T(0, 0, 0);\n\t//calc low for rotation estimation\n\t//Newcombe, R. A., Lovegrove, S. J., & Davison, A. J. (2011). DTAM : Dense Tracking and Mapping in Real-Time. In ICCV. Retrieved from http://www.youtube.com/watch?v=Df9WhgibCQA\n\tdouble E = directRotation(pRefeFrame_, pLiveFrame_, &R_rl);\n\t//cout << R_rl.matrix() << endl;\n\tEigen::Vector4i eivIter;\n\tSE3Group<double> T_rl(R_rl, T);\n\tshort asICPIterations[4] = { 4, 3, 3, 1 };\n\tdICPEnergy = dvoICPIC(pRefeFrame_, pLiveFrame_, asICPIterations, &T_rl, &eivIter);\n\t//estimate dt\n\testimateExposure(pLiveFrame_, T_rl);\n\n\treturn dICPEnergy;\n}\n\nvoid CKinFuTracker::estimateExposure(CKeyFrame::tp_ptr pCurFrame_, const SE3Group<double>& T_rl){\n\tSE3Group<double> T_lr = T_rl.inverse();\n\t//get R,T of previous \n\tMatrix3d R_lr_t_tmp = T_lr.so3().inverse().matrix();\n\tconst Matd33&  devR_lr = pcl::device::device_cast<pcl::device::Matd33> (R_lr_t_tmp); //implicit inverse\n\n\tVector3d tt = T_lr.translation();\n\tconst double3& devT_lr = pcl::device::device_cast<double3> (tt);\n\n\tGpuMat mask;\n\tif(true){\n\t\t_avg_exposure = btl::device::exposure_est2(pCurFrame_->_pRGBCamera->getIntrinsics(0), devR_lr, devT_lr,\n\t\t\t_pIACurr->_vRadianceBGR[0], _pIACurr->_error_bgr[0],\n\t\t\t_pIACurr->_vRadianceBGR[1], _pIACurr->_error_bgr[1], \n\t\t\t_pIACurr->_vRadianceBGR[2], _pIACurr->_error_bgr[2], \n\t\t\t*_pRefFrame->_agPyrPts[0], _pIAPrev->_vRadianceBGR[0], _pIAPrev->_vRadianceBGR[1], _pIAPrev->_vRadianceBGR[2], mask);\n\t\t//cout << \"avg exposure: \" << _avg_exposure << endl;\n\t}\n\n\tfor (int ch = 0; ch < 3; ch++) {\n\t\t_pIACurr->_vRadianceBGR[ch].convertTo(_pIACurr->_vRadianceBGR[ch], CV_32FC1, _avg_exposure);\n\t}\n\n\tif(false){\n\t\tbtl::device::remove_outlier(pCurFrame_->_pRGBCamera->getIntrinsics(0), devR_lr, devT_lr,\n\t\t\t_pIACurr->_vRadianceBGR[0], _pIACurr->_error_bgr[0],\n\t\t\t_pIACurr->_vRadianceBGR[1], _pIACurr->_error_bgr[1],\n\t\t\t_pIACurr->_vRadianceBGR[2], _pIACurr->_error_bgr[2],\n\t\t\t*_pRefFrame->_agPyrPts[0], _pIAPrev->_vRadianceBGR[0], _pIAPrev->_vRadianceBGR[1], _pIAPrev->_vRadianceBGR[2], mask);\n\t}\n\n\treturn;\n}\n\nvoid CKinFuTracker::constructLivePyr(){\n\t//construct pyramid of normalized_radiance;\n\tcalc_avg_min_frame( _pIACurr->_normalized_bgr[0], _pIACurr->_normalized_bgr[1], _pIACurr->_normalized_bgr[2], &(_n_rad_live[0]),\n\t\t\t\t\t\t_pIACurr->_error_bgr[0], _pIACurr->_error_bgr[1], _pIACurr->_error_bgr[2], &(_err_live[0]));\n\n\tcuda::pyrDown(_n_rad_live[0], _n_rad_live[1]);\n\tcuda::pyrDown(_n_rad_live[1], _n_rad_live[2]);\n\tcuda::pyrDown(_err_live[0], _err_live[1]);\n\tcuda::pyrDown(_err_live[1], _err_live[2]);\n\n}\n\nvoid CKinFuTracker::constructRefePyr(){\n\t//construct pyramid of normalized_radiance;\n\tcalc_avg_frame(_pIAPrev->_normalized_bgr[0], _pIAPrev->_normalized_bgr[1], _pIAPrev->_normalized_bgr[2], &(_n_rad_ref[0]));\n\n\tcuda::pyrDown(_n_rad_ref[0], _n_rad_ref[1]);\n\tcuda::pyrDown(_n_rad_ref[1], _n_rad_ref[2]);\n}\n\nvoid CKinFuTracker::tracking(CKeyFrame::tp_ptr pCurFrame_)\n{\n\tGpuMat bgr;\n\tcuda::cvtColor(pCurFrame_->_gRGB, bgr, CV_RGB2BGR);\n\t_pIACurr->analysis(bgr);\n\n\tconstructLivePyr();\n\n\tif (icp(_pRefFrame.get(), pCurFrame_) < _aMinEnergy[_nResolution])\n\t{\n\t\tSE3Group<double> T_cw(pCurFrame_->_R_cw, pCurFrame_->_Tw);\n\t\tGpuMat radiance;\n\t\tcuda::merge(_pIACurr->_vRadianceBGR, radiance);\n\t\tGpuMat er;\n\t\tcuda::merge(_pIACurr->_error_bgr, 3, er);\n\t\tGpuMat normal_radiance;\n\t\tcuda::merge(_pIACurr->_normalized_bgr, 3, normal_radiance);\n\t\t_pGlobalMap->gpuIntegrateDepth(*pCurFrame_->_agPyrDepths[0], *pCurFrame_->_agPyrNls[0], normal_radiance, radiance, er, \n\t\t\t\t\t\t\t\t\t\tSE3Group<double>(pCurFrame_->_R_cw, pCurFrame_->_Tw));\n\t\t//insert features into feature-base\n\t\tpCurFrame_->getPrjCfW(&_pose_refined_c_f_w);\n\t\t_v_T_cw_tracking.push_back(_pose_refined_c_f_w);\n\n\t\tstoreCurrFrameSynthetic(pCurFrame_);\n\t}//if current frame is lost aligned\n\n\treturn;\n}//track\n\n}//geometry\n}//btl\n", "meta": {"hexsha": "ffbec868bd9ca705816a9638b74b89fc7dec1ec4", "size": 16616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hdr_fusion/rgbd/KinfuTracker.cpp", "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/rgbd/KinfuTracker.cpp", "max_issues_repo_name": "ShudaLi/HDRFusion", "max_issues_repo_head_hexsha": "ab7242cd9b1686900c9bdc525f3f300740672ba0", "max_issues_repo_licenses": ["MIT"], "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/rgbd/KinfuTracker.cpp", "max_forks_repo_name": "ShudaLi/HDRFusion", "max_forks_repo_head_hexsha": "ab7242cd9b1686900c9bdc525f3f300740672ba0", "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": 35.8876889849, "max_line_length": 193, "alphanum_fraction": 0.7324265768, "num_tokens": 5629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.16860168404135767}}
{"text": "/*\n * Copyright 2014 RWTH Aachen University. All rights reserved.\n *\n * Licensed under the RWTH LM License (the \"License\");\n * you may not use this file except in compliance with 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#include <cmath>\n#include <memory>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/filesystem/operations.hpp>\n#include \"fast.h\"\n#include \"identity.h\"\n#include \"linear.h\"\n#include \"output.h\"\n#include \"sigmoid.h\"\n#include \"softmax.h\"\n#include \"tablelookup.h\"\n#include \"tanh.h\"\n#include \"trainer.h\"\n\nconst Real Trainer::kAutoInitialLearningRate = 0.05;\nconst Real Trainer::kMaxRelativeIncrease = 2.0;\n\nnamespace bp = boost::posix_time;\n\nTrainer::Trainer(const int max_epoch,\n                 const bool shuffle,\n                 const bool verbose,\n                 const bool is_feedforward,\n                 const std::string &net_config,\n                 const NetPointer &net,\n                 ConstVocabularyPointer vocabulary,\n                 DataPointer training_data,\n                 DataPointer dev_data,\n                 Random *random)\n    : net_(std::move(net)),\n      training_data_(training_data),\n      dev_data_(dev_data),\n      net_config_(net_config),\n      vocabulary_(vocabulary),\n      verbose_(verbose),\n      is_feedforward_(is_feedforward),\n      random_(random),\n      shuffle_(shuffle),\n      max_epoch_(max_epoch) {\n}\n\nvoid Trainer::Train(const uint32_t seed) {\n  // Note: rwthlm will train forever unless you stop it ...\n  std::cout << \"Training ...\" << std::endl;\n  while (max_epoch_ == 0 || net_->epoch() < max_epoch_) {\n    Shuffle(seed);\n    const bp::ptime time(bp::second_clock::local_time());\n    TrainEpoch();\n    net_->set_epoch(net_->epoch() + 1);\n    std::cout << \"epoch \" << net_->epoch() << \" took \" << std::fixed <<\n                 std::setprecision(2) << (bp::second_clock::local_time() -\n\t\t\t\t time).total_seconds() / 60. << \" minutes\" << std::endl;\n    const Real perplexity = ComputePerplexity(dev_data_);\n    std::cout << \"development perplexity = \" << std::setw(20) << std::fixed <<\n                 std::setprecision(15) << perplexity << std::scientific <<\n                 \", learning rate = \" << net_->learning_rate();\n    if (net_->momentum() > 0.0)\n      std::cout << \", momentum = \" << std::fixed << net_->momentum();\n    std::cout << std::endl;\n    if (net_->best_perplexity() > perplexity) {\n      net_->set_best_perplexity(perplexity);\n      net_->Write(net_config_);\n    } else {\n      const int new_epoch = net_->epoch();\n      const Real new_learning_rate = 0.5 * net_->learning_rate();\n      net_->Read(net_config_);\n      net_->set_learning_rate(new_learning_rate);\n      net_->set_epoch(new_epoch);\n      net_->Write(net_config_);\n    }\n  }\n}\n\nvoid Trainer::TrainEpoch() {\n  Real log_probability = 0.;\n  int64_t num_running_words = 0;\n  for (const Batch &batch : *training_data_) {\n    net_->Reset(false);\n    net_->ResetHistories();\n    bp::ptime time;\n    if (verbose_)\n      time = bp::microsec_clock::local_time();\n    if (is_feedforward_)\n      TrainBatchFeedforward(batch, &log_probability, &num_running_words);\n    else\n      TrainBatch(batch, &log_probability, &num_running_words);\n    if (verbose_) {\n      std::cout << \"training perplexity = \" << std::fixed <<\n                   std::setprecision(2) << exp(-log_probability /\n                   num_running_words) << std::endl;\n      std::cout << \"time = \" << std::fixed << std::setprecision(3) <<\n                   (bp::microsec_clock::local_time() - time).\n                   total_milliseconds() / 1000. << \" seconds\" << std::endl;\n    }\n  }\n}\n\nvoid Trainer::TrainBatch(const Batch &batch,\n                         Real *log_probability,\n                         int64_t *num_running_words) {\n  // forward pass\n  auto previous_slice(*batch.Begin(0));\n  for (auto next_slice : batch) {\n    const Real *x = net_->Evaluate(next_slice, Caster(previous_slice).Cast());\n    *log_probability += net_->ComputeLogProbability(next_slice, x, false);\n    *num_running_words += next_slice.size();\n    previous_slice = next_slice;\n  }\n\n  // backward pass\n  auto slice = batch.End(1);\n  do {\n    --slice;\n    net_->ComputeDelta(*slice, FunctionPointer());\n  } while (slice != batch.Begin(1));\n  net_->ResetHistories();\n\n  // weight update\n  previous_slice = *batch.Begin(0);\n  for (auto next_slice : batch) {\n    net_->UpdateWeights(next_slice, Caster(previous_slice).Cast());\n    previous_slice = next_slice;\n  }\n  net_->UpdateMomentumWeights();\n}\n\nvoid Trainer::TrainBatchFeedforward(const Batch &batch,\n                                    Real *log_probability,\n                                    int64_t *num_running_words) {\n  // forward pass\n  auto previous_slice(*batch.Begin(0));\n  for (auto next_slice : batch) {\n    net_->Reset(false);\n    const Real *x = net_->Evaluate(next_slice, Caster(previous_slice).Cast());\n    *log_probability += net_->ComputeLogProbability(next_slice, x, false);\n    *num_running_words += next_slice.size();\n    net_->ComputeDelta(next_slice, FunctionPointer());\n    net_->UpdateWeights(next_slice, Caster(previous_slice).Cast());\n    previous_slice = next_slice;\n    net_->UpdateMomentumWeights();\n  }\n}\n\nReal Trainer::AutoAdjustLearningRate(const Real factor,\n                                     const int seed,\n                                     Real learning_rate) {\n  assert(factor != 1.);\n  assert(kMinNumDecreases < kMaxNumBatches);\n  Real ppl, candidate_learning_rate = -1.;\n  while (true) {\n    ppl = std::numeric_limits<Real>::max();\n    int num_batches = 0, num_decreases = 0;\n    int64_t num_running_words = 0;\n    Real log_probability = 0.;\n    learning_rate *= factor;\n    net_->set_learning_rate(learning_rate);\n    std::cout << std::scientific << std::setprecision(2) << learning_rate <<\n                 ':' << std::endl;\n    for (const Batch &batch : *training_data_) {\n      net_->Reset(false);\n      net_->ResetHistories();\n      if (is_feedforward_)\n        TrainBatchFeedforward(batch, &log_probability, &num_running_words);\n      else\n        TrainBatch(batch, &log_probability, &num_running_words);\n      const Real new_ppl = exp(-log_probability / num_running_words);\n      // keep track of whether error falls consistently\n      if (new_ppl < ppl)\n        ++num_decreases;\n      // reject learning rate in case of wild oscillations\n      if (new_ppl / ppl > kMaxRelativeIncrease)\n        num_decreases = -kMaxNumBatches;\n      ppl = new_ppl;\n      std::cout << \"  \" << std::fixed << std::setw(10) <<\n                   std::setprecision(2) << ppl << std::endl;\n      std::cout.flush();\n      ++num_batches;\n      if (!IsFiniteNumber(ppl))\n        break;\n      if (kMaxNumBatches - num_batches < kMinNumDecreases - num_decreases)\n        break;\n      // no infinity and enough decreases? -> candidate found!\n      if (num_batches == kMaxNumBatches) {\n        assert(num_decreases >= kMinNumDecreases);\n        candidate_learning_rate = learning_rate;\n        break;\n      }\n    }\n    net_->ResetMomentum();\n    random_->Reset(seed);\n    net_->RandomizeWeights(random_);\n    if (factor > 1. && candidate_learning_rate != learning_rate)\n      break;\n    if (factor < 1. && candidate_learning_rate > 0.)\n      break;\n  }\n  return candidate_learning_rate;\n}\n\nvoid Trainer::AutoInitializeLearningRate(const int seed) {\n  std::cout << \"Determining initial learning rate ...\" << std::endl;\n  assert(training_data_->GetNumBatches() >= kMaxNumBatches);\n  Shuffle(seed);\n\n  // increase learning rate until strong perplexity increase/fluctuation\n  std::cout << \"Increasing ...\" << std::endl;\n  Real learning_rate = AutoAdjustLearningRate(2.,\n                                              seed,\n                                              kAutoInitialLearningRate);\n  if (learning_rate < 0.) {\n    // decrease learning rate until perplexity drops satisfactorily\n    std::cout << \"Decreasing ...\" << std::endl;\n    learning_rate = AutoAdjustLearningRate(0.5,\n                                           seed,\n                                           2. * kAutoInitialLearningRate);\n  }\n  net_->set_learning_rate(learning_rate);\n  std::cout << \"initial learning rate: \" << std::scientific <<\n               std::setprecision(2) << learning_rate << std::endl;\n  random_->Reset(seed);\n  net_->RandomizeWeights(random_);\n}\n\nReal Trainer::ComputePerplexity(DataPointer data) {\n  int num_running_words = 0;\n  Real log_probability = 0.;\n  for (auto &batch : *data) {\n    net_->Reset(false);\n    net_->ResetHistories();\n    Sequence slice(*batch.Begin(0));\n    for (auto next_slice : batch) {\n      if (is_feedforward_)\n        net_->Reset(false);\n      const Real *x = net_->Evaluate(next_slice, Caster(slice).Cast());\n      log_probability += net_->ComputeLogProbability(next_slice, x, verbose_);\n      slice = next_slice;\n      num_running_words += next_slice.size();\n    }\n  }\n  return exp(-log_probability / num_running_words);\n}\n", "meta": {"hexsha": "a923f6b70f1b01d47441069ea823be45fccfa530", "size": 9291, "ext": "cc", "lang": "C++", "max_stars_repo_path": "rwthlm/trainer.cc", "max_stars_repo_name": "darongliu/Input_Method", "max_stars_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-03T07:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-03T07:42:42.000Z", "max_issues_repo_path": "rwthlm/trainer.cc", "max_issues_repo_name": "darongliu/Input_Method", "max_issues_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rwthlm/trainer.cc", "max_forks_repo_name": "darongliu/Input_Method", "max_forks_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_forks_repo_licenses": ["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.1517509728, "max_line_length": 78, "alphanum_fraction": 0.6256592401, "num_tokens": 2194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1686016806978548}}
{"text": "// Copyright (c) 2014-2015 The Dash developers\n// Copyright (c) 2015-2017 The PIVX 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 \"masternode-payments.h\"\n#include \"addrman.h\"\n#include \"masternode-budget.h\"\n#include \"chainparamsbase.h\"\n#include \"masternode-sync.h\"\n#include \"masternodeman.h\"\n#include \"obfuscation.h\"\n#include \"spork.h\"\n#include \"sync.h\"\n#include \"util.h\"\n#include \"utilmoneystr.h\"\n#include \"netfulfilledman.h\"\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <algorithm>\n#include <numeric>\n\n/** Object for who's going to get paid on which blocks */\nCMasternodePayments masternodePayments;\n\nCCriticalSection cs_vecPayments;\nCCriticalSection cs_mapMasternodeBlocks;\nCCriticalSection cs_mapMasternodePayeeVotes;\n\nconst std::string TREASURY_PAYMENT_ADDRESS(\"AYVfYRD2nLUzJnBYbaLWXXYN6frBS7FZeo\");\nconst std::string CHARITY_PAYMENT_ADDRESS(\"AYDTFuYkFbX9A1WCFf7uCSMHUhX5KdCma9\");\n\nconst std::string TREASURY_PAYMENT_ADDRESS_TESTNET(\"xw7G6toCcLr2J7ZK8zTfVRhAPiNc8AyxCd\");\nconst std::string CHARITY_PAYMENT_ADDRESS_TESTNET(\"y8zytdJziDeXcdk48Wv7LH6FgnF4zDiXM5\");\n\nbool IsValidLotteryBlockHeight(int nBlockHeight)\n{\n    return nBlockHeight >= Params().GetLotteryBlockStartBlock() &&\n            ((nBlockHeight % Params().GetLotteryBlockCycle()) == 0);\n}\n\nstatic bool IsValidTreasuryBlockHeight(int nBlockHeight)\n{\n    return nBlockHeight >= Params().GetTreasuryPaymentsStartBlock() &&\n            ((nBlockHeight % Params().GetTreasuryPaymentsCycle()) == 0);\n}\n\nstatic int64_t GetTreasuryReward(const CBlockRewards &rewards)\n{\n    return rewards.nTreasuryReward * Params().GetTreasuryPaymentsCycle();\n}\n\nstatic int64_t GetCharityReward(const CBlockRewards &rewards)\n{\n    return rewards.nCharityReward * Params().GetTreasuryPaymentsCycle();\n}\n\nstatic CBitcoinAddress TreasuryPaymentAddress()\n{\n    return CBitcoinAddress(Params().NetworkID() == CBaseChainParams::MAIN ? TREASURY_PAYMENT_ADDRESS : TREASURY_PAYMENT_ADDRESS_TESTNET);\n}\n\nstatic CBitcoinAddress CharityPaymentAddress()\n{\n    return CBitcoinAddress(Params().NetworkID() == CBaseChainParams::MAIN ? CHARITY_PAYMENT_ADDRESS : CHARITY_PAYMENT_ADDRESS_TESTNET);\n}\n\n\nstatic void FillTreasuryPayment(CMutableTransaction &tx, int nHeight)\n{\n    auto rewards = GetBlockSubsidity(nHeight - 1);\n    tx.vout.emplace_back(GetTreasuryReward(rewards), GetScriptForDestination(TreasuryPaymentAddress().Get()));\n    tx.vout.emplace_back(GetCharityReward(rewards), GetScriptForDestination(CharityPaymentAddress().Get()));\n}\n\nstatic int64_t GetLotteryReward(const CBlockRewards &rewards)\n{\n    // 50 coins every block for lottery\n    return Params().GetLotteryBlockCycle() * rewards.nLotteryReward;\n}\n\nstatic CScript GetScriptForLotteryPayment(const uint256 &hashWinningCoinstake)\n{\n    CTransaction coinbaseTx;\n    uint256 hashBlock;\n    assert(GetTransaction(hashWinningCoinstake, coinbaseTx, hashBlock));\n    assert(coinbaseTx.IsCoinBase() || coinbaseTx.IsCoinStake());\n\n    return coinbaseTx.IsCoinBase() ? coinbaseTx.vout[0].scriptPubKey : coinbaseTx.vout[1].scriptPubKey;\n    }\n\n    static void FillLotteryPayment(CMutableTransaction &tx, const CBlockRewards &rewards, const CBlockIndex *currentBlockIndex)\n    {\n    auto lotteryWinners = currentBlockIndex->vLotteryWinnersCoinstakes;\n    // when we call this we need to have exactly 11 winners\n\n    auto nLotteryReward = GetLotteryReward(rewards);\n    auto nBigReward = nLotteryReward / 2;\n    auto nSmallReward = nBigReward / 10;\n\n    LogPrintf(\"%s : Paying lottery reward\\n\", __func__);\n    for(size_t i = 0; i < lotteryWinners.size(); ++i) {\n        CAmount reward = i == 0 ? nBigReward : nSmallReward;\n        const auto &winner = lotteryWinners[i];\n        LogPrintf(\"%s: Winner: %s\\n\", __func__, winner.ToString());\n        auto scriptLotteryWinner = GetScriptForLotteryPayment(winner);\n        tx.vout.emplace_back(reward, scriptLotteryWinner); // pay winners\n    }\n}\n\nstatic bool IsValidLotteryPayment(const CTransaction &tx, int nHeight, const std::vector<WinnerCoinStake> vRequiredWinnersCoinstake)\n{\n    if(vRequiredWinnersCoinstake.empty()) {\n        return true;\n    }\n\n    auto verifyPayment = [&tx](CScript scriptPayment, CAmount amount) {\n        CTxOut outPayment(amount, scriptPayment);\n        return std::find(std::begin(tx.vout), std::end(tx.vout), outPayment) != std::end(tx.vout);\n    };\n\n    auto nLotteryReward = GetLotteryReward(GetBlockSubsidity(nHeight));\n    auto nBigReward = nLotteryReward / 2;\n    auto nSmallReward = nBigReward / 10;\n\n    for(size_t i = 0; i < vRequiredWinnersCoinstake.size(); ++i) {\n        CScript scriptPayment = GetScriptForLotteryPayment(vRequiredWinnersCoinstake[i]);\n        CAmount reward = i == 0 ? nBigReward : nSmallReward;\n        if(!verifyPayment(scriptPayment, reward)) {\n            LogPrintf(\"%s: No payment for winner: %s\\n\", vRequiredWinnersCoinstake[i].ToString());\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic bool IsValidTreasuryPayment(const CTransaction &tx, int nHeight)\n{\n    auto rewards = GetBlockSubsidity(nHeight);\n    auto charityPart = GetCharityReward(rewards);\n    auto treasuryPart = GetTreasuryReward(rewards);\n\n    auto verifyPayment = [&tx](CBitcoinAddress address, CAmount amount) {\n\n        CScript scriptPayment = GetScriptForDestination(address.Get());\n        CTxOut outPayment(amount, scriptPayment);\n        return std::find(std::begin(tx.vout), std::end(tx.vout), outPayment) != std::end(tx.vout);\n    };\n\n    if(!verifyPayment(TreasuryPaymentAddress(), treasuryPart))\n    {\n        LogPrint(\"masternode\", \"Expecting treasury payment, no payment address detected, rejecting\\n\");\n        return false;\n    }\n\n    if(!verifyPayment(CharityPaymentAddress(), charityPart))\n    {\n        LogPrint(\"masternode\", \"Expecting charity payment, no payment address detected, rejecting\\n\");\n        return false;\n    }\n\n    return true;\n}\n\nbool IsBlockValueValid(const CBlock& block, const CBlockRewards &nExpectedValue, CAmount nMinted)\n{\n    CBlockIndex* pindexPrev = chainActive.Tip();\n    if (pindexPrev == NULL) return true;\n\n    int nHeight = 0;\n    if (pindexPrev->GetBlockHash() == block.hashPrevBlock) {\n        nHeight = pindexPrev->nHeight + 1;\n    } else { //out of order\n        BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);\n        if (mi != mapBlockIndex.end() && (*mi).second)\n            nHeight = (*mi).second->nHeight + 1;\n    }\n\n    if (nHeight == 0) {\n        LogPrint(\"masternode\",\"IsBlockValueValid() : WARNING: Couldn't find previous block\\n\");\n    }\n\n    //LogPrintf(\"XX69----------> IsBlockValueValid(): nMinted: %d, nExpectedValue: %d\\n\", FormatMoney(nMinted), FormatMoney(nExpectedValue));\n\n    auto nExpectedMintCombined = nExpectedValue.nStakeReward + nExpectedValue.nMasternodeReward;\n\n    // here we expect treasury block payment\n    if(IsValidTreasuryBlockHeight(nHeight)) {\n        nExpectedMintCombined += (GetTreasuryReward(nExpectedValue) + GetCharityReward(nExpectedValue));\n    }\n    else if(IsValidLotteryBlockHeight(nHeight)) {\n        nExpectedMintCombined += GetLotteryReward(nExpectedValue);\n    }\n\n    if (nMinted > nExpectedMintCombined) {\n        return false;\n    }\n\n    return true;\n}\n\nbool IsBlockPayeeValid(const CTransaction &txNew, int nBlockHeight, CBlockIndex *prevIndex)\n{\n    if (!masternodeSync.IsSynced()) { //there is no budget data to use to check anything -- find the longest chain\n        LogPrintf(\"%s : Client not synced, skipping block payee checks\\n\", __func__);\n        return true;\n    }\n\n    if(IsValidTreasuryBlockHeight(nBlockHeight)) {\n        return IsValidTreasuryPayment(txNew, nBlockHeight);\n    }\n\n    if(IsValidLotteryBlockHeight(nBlockHeight)) {\n        return IsValidLotteryPayment(txNew, nBlockHeight, prevIndex->vLotteryWinnersCoinstakes);\n    }\n\n    //check for masternode payee\n    if (masternodePayments.IsTransactionValid(txNew, nBlockHeight))\n        return true;\n    LogPrintf(\"%s : Invalid mn payment detected %s\\n\", __func__, txNew.ToString().c_str());\n\n    if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT))\n        return false;\n    LogPrintf(\"%s : Masternode payment enforcement is disabled, accepting block\\n\", __func__);\n\n    return true;\n}\n\n\nvoid FillBlockPayee(CMutableTransaction& txNew, const CBlockRewards &payments, bool fProofOfStake)\n{\n    CBlockIndex* pindexPrev = chainActive.Tip();\n    if (!pindexPrev) return;\n\n    if (IsValidTreasuryBlockHeight(pindexPrev->nHeight + 1)) {\n        FillTreasuryPayment(txNew, pindexPrev->nHeight + 1);\n    }\n    else if(IsValidLotteryBlockHeight(pindexPrev->nHeight + 1)) {\n        FillLotteryPayment(txNew, payments, pindexPrev);\n    }\n    else {\n        masternodePayments.FillBlockPayee(txNew, payments, fProofOfStake);\n    }\n}\n\nstd::string GetRequiredPaymentsString(int nBlockHeight)\n{\n    return masternodePayments.GetRequiredPaymentsString(nBlockHeight);\n}\n\nvoid CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, const CBlockRewards &rewards, bool fProofOfStake)\n{\n    CBlockIndex* pindexPrev = chainActive.Tip();\n    if (!pindexPrev) return;\n\n    bool hasPayment = true;\n    CScript payee;\n\n    //spork\n    if (!masternodePayments.GetBlockPayee(pindexPrev->nHeight + 1, payee)) {\n        //no masternode detected\n        CMasternode* winningNode = mnodeman.GetCurrentMasterNode(1);\n        if (winningNode) {\n            payee = GetScriptForDestination(winningNode->pubKeyCollateralAddress.GetID());\n        } else {\n            LogPrint(\"masternode\",\"CreateNewBlock: Failed to detect masternode to pay\\n\");\n            hasPayment = false;\n        }\n    }\n\n    if (hasPayment) {\n        CAmount masternodePayment = rewards.nMasternodeReward;\n        txNew.vout.emplace_back(masternodePayment, payee);\n\n        CTxDestination address1;\n        ExtractDestination(payee, address1);\n        CBitcoinAddress address2(address1);\n\n        LogPrint(\"masternode\",\"Masternode payment of %s to %s\\n\", FormatMoney(masternodePayment).c_str(), address2.ToString().c_str());\n    }\n}\n\nint CMasternodePayments::GetMinMasternodePaymentsProto()\n{\n    //    if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES))\n    return ActiveProtocol();                          // Allow only updated peers\n}\n\nvoid CMasternodePayments::ProcessMessageMasternodePayments(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)\n{\n    if (!masternodeSync.IsBlockchainSynced()) return;\n\n    if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality\n\n\n    if (strCommand == \"mnget\") { //Masternode Payments Request Sync\n        if (fLiteMode) return;   //disable all Obfuscation/Masternode related functionality\n\n        int nCountNeeded;\n        vRecv >> nCountNeeded;\n\n        if (Params().NetworkID() == CBaseChainParams::MAIN) {\n            if (netfulfilledman.HasFulfilledRequest(pfrom->addr, \"mnget\")) {\n                LogPrintf(\"%s : mnget - peer already asked me for the list\\n\", __func__);\n                Misbehaving(pfrom->GetId(), 20);\n                return;\n            }\n        }\n\n        netfulfilledman.AddFulfilledRequest(pfrom->addr, \"mnget\");\n        masternodePayments.Sync(pfrom, nCountNeeded);\n        LogPrint(\"mnpayments\", \"mnget - Sent Masternode winners to peer %i\\n\", pfrom->GetId());\n    } else if (strCommand == \"mnw\") { //Masternode Payments Declare Winner\n        //this is required in litemodef\n        CMasternodePaymentWinner winner;\n        vRecv >> winner;\n\n        if (pfrom->nVersion < ActiveProtocol()) return;\n\n        int nHeight;\n        {\n            TRY_LOCK(cs_main, locked);\n            if (!locked || chainActive.Tip() == NULL) return;\n            nHeight = chainActive.Tip()->nHeight;\n        }\n\n        if (masternodePayments.mapMasternodePayeeVotes.count(winner.GetHash())) {\n            LogPrint(\"mnpayments\", \"mnw - Already seen - %s bestHeight %d\\n\", winner.GetHash().ToString().c_str(), nHeight);\n            masternodeSync.AddedMasternodeWinner(winner.GetHash());\n            return;\n        }\n\n        int nFirstBlock = nHeight - (mnodeman.CountEnabled() * 1.25);\n        if (winner.nBlockHeight < nFirstBlock || winner.nBlockHeight > nHeight + 20) {\n            LogPrint(\"mnpayments\", \"mnw - winner out of range - FirstBlock %d Height %d bestHeight %d\\n\", nFirstBlock, winner.nBlockHeight, nHeight);\n            return;\n        }\n\n        std::string strError = \"\";\n        if (!winner.IsValid(pfrom, strError)) {\n            // if(strError != \"\") LogPrint(\"masternode\",\"mnw - invalid message - %s\\n\", strError);\n            return;\n        }\n\n        if (!masternodePayments.CanVote(winner.vinMasternode.prevout, winner.nBlockHeight)) {\n            //  LogPrint(\"masternode\",\"mnw - masternode already voted - %s\\n\", winner.vinMasternode.prevout.ToStringShort());\n            return;\n        }\n\n        if (!winner.SignatureValid()) {\n            LogPrintf(\"%s : - invalid signature\\n\", __func__);\n            if (masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20);\n            // it could just be a non-synced masternode\n            mnodeman.AskForMN(pfrom, winner.vinMasternode);\n            return;\n        }\n\n        CTxDestination address1;\n        ExtractDestination(winner.payee, address1);\n        CBitcoinAddress address2(address1);\n\n        //   LogPrint(\"mnpayments\", \"mnw - winning vote - Addr %s Height %d bestHeight %d - %s\\n\", address2.ToString().c_str(), winner.nBlockHeight, nHeight, winner.vinMasternode.prevout.ToStringShort());\n\n        if (masternodePayments.AddWinningMasternode(winner)) {\n            winner.Relay();\n            masternodeSync.AddedMasternodeWinner(winner.GetHash());\n        }\n    }\n}\n\nbool CMasternodePaymentWinner::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode)\n{\n    std::string errorMessage;\n    std::string strMasterNodeSignMessage;\n\n    std::string strMessage = vinMasternode.prevout.ToStringShort() +\n            boost::lexical_cast<std::string>(nBlockHeight) +\n            payee.ToString();\n\n    if (!CObfuScationSigner::SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) {\n        LogPrint(\"masternode\",\"CMasternodePing::Sign() - Error: %s\\n\", errorMessage.c_str());\n        return false;\n    }\n\n    if (!CObfuScationSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) {\n        LogPrint(\"masternode\",\"CMasternodePing::Sign() - Error: %s\\n\", errorMessage.c_str());\n        return false;\n    }\n\n    return true;\n}\n\nbool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee)\n{\n    if (mapMasternodeBlocks.count(nBlockHeight)) {\n        return mapMasternodeBlocks[nBlockHeight].GetPayee(payee);\n    }\n\n    return false;\n}\n\n// Is this masternode scheduled to get paid soon?\n// -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 winners\nbool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight)\n{\n    LOCK(cs_mapMasternodeBlocks);\n\n    int nHeight;\n    {\n        TRY_LOCK(cs_main, locked);\n        if (!locked || chainActive.Tip() == NULL) return false;\n        nHeight = chainActive.Tip()->nHeight;\n    }\n\n    CScript mnpayee;\n    mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID());\n\n    CScript payee;\n    for (int64_t h = nHeight; h <= nHeight + 8; h++) {\n        if (h == nNotBlockHeight) continue;\n        if (mapMasternodeBlocks.count(h)) {\n            if (mapMasternodeBlocks[h].GetPayee(payee)) {\n                if (mnpayee == payee) {\n                    return true;\n                }\n            }\n        }\n    }\n\n    return false;\n}\n\nbool CMasternodePayments::AddWinningMasternode(const CMasternodePaymentWinner& winnerIn)\n{\n    uint256 blockHash = 0;\n    if (!GetBlockHash(blockHash, winnerIn.nBlockHeight - 100)) {\n        return false;\n    }\n\n    {\n        LOCK2(cs_mapMasternodePayeeVotes, cs_mapMasternodeBlocks);\n\n        if (mapMasternodePayeeVotes.count(winnerIn.GetHash())) {\n            return false;\n        }\n\n        mapMasternodePayeeVotes[winnerIn.GetHash()] = winnerIn;\n\n        if (!mapMasternodeBlocks.count(winnerIn.nBlockHeight)) {\n            CMasternodeBlockPayees blockPayees(winnerIn.nBlockHeight);\n            mapMasternodeBlocks[winnerIn.nBlockHeight] = blockPayees;\n        }\n    }\n\n    mapMasternodeBlocks[winnerIn.nBlockHeight].AddPayee(winnerIn.payee, 1);\n\n    return true;\n}\n\nbool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew)\n{\n    LOCK(cs_vecPayments);\n\n    int nMaxSignatures = 0;\n    int nMasternode_Drift_Count = 0;\n\n    std::string strPayeesPossible = \"\";\n\n    auto rewards = GetBlockSubsidity(nBlockHeight);\n\n    if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {\n        // Get a stable number of masternodes by ignoring newly activated (< 8000 sec old) masternodes\n        nMasternode_Drift_Count = mnodeman.stable_size() + Params().MasternodeCountDrift();\n    }\n    else {\n        //account for the fact that all peers do not see the same masternode count. A allowance of being off our masternode count is given\n        //we only need to look at an increased masternode count because as count increases, the reward decreases. This code only checks\n        //for mnPayment >= required, so it only makes sense to check the max node count allowed.\n        nMasternode_Drift_Count = mnodeman.size() + Params().MasternodeCountDrift();\n    }\n\n    CAmount requiredMasternodePayment = rewards.nMasternodeReward;\n\n    //require at least 6 signatures\n    for(CMasternodePayee& payee : vecPayments)\n        if (payee.nVotes >= nMaxSignatures && payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED)\n            nMaxSignatures = payee.nVotes;\n\n    // if we don't have at least 6 signatures on a payee, approve whichever is the longest chain\n    if (nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true;\n\n    for (CMasternodePayee& payee : vecPayments) {\n        bool found = false;\n        for (CTxOut out : txNew.vout) {\n            if (payee.scriptPubKey == out.scriptPubKey) {\n                if(out.nValue >= requiredMasternodePayment)\n                    found = true;\n                else\n                    LogPrint(\"masternode\",\"Masternode payment is out of drift range. Paid=%s Min=%s\\n\", FormatMoney(out.nValue).c_str(), FormatMoney(requiredMasternodePayment).c_str());\n            }\n        }\n\n        if (payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED) {\n            if (found) return true;\n\n            CTxDestination address1;\n            ExtractDestination(payee.scriptPubKey, address1);\n            CBitcoinAddress address2(address1);\n\n            if (strPayeesPossible == \"\") {\n                strPayeesPossible += address2.ToString();\n            } else {\n                strPayeesPossible += \",\" + address2.ToString();\n            }\n        }\n    }\n\n    LogPrint(\"masternode\",\"CMasternodePayments::IsTransactionValid - Missing required payment of %s to %s\\n\", FormatMoney(requiredMasternodePayment).c_str(), strPayeesPossible.c_str());\n    return false;\n}\n\nstd::string CMasternodeBlockPayees::GetRequiredPaymentsString()\n{\n    LOCK(cs_vecPayments);\n\n    std::string ret = \"Unknown\";\n\n    BOOST_FOREACH (CMasternodePayee& payee, vecPayments) {\n        CTxDestination address1;\n        ExtractDestination(payee.scriptPubKey, address1);\n        CBitcoinAddress address2(address1);\n\n        if (ret != \"Unknown\") {\n            ret += \", \" + address2.ToString() + \":\" + boost::lexical_cast<std::string>(payee.nVotes);\n        } else {\n            ret = address2.ToString() + \":\" + boost::lexical_cast<std::string>(payee.nVotes);\n        }\n    }\n\n    return ret;\n}\n\nstd::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight)\n{\n    LOCK(cs_mapMasternodeBlocks);\n\n    if (mapMasternodeBlocks.count(nBlockHeight)) {\n        return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString();\n    }\n\n    return \"Unknown\";\n}\n\nbool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight)\n{\n    LOCK(cs_mapMasternodeBlocks);\n\n    if (mapMasternodeBlocks.count(nBlockHeight)) {\n        return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew);\n    }\n\n    return true;\n}\n\nvoid CMasternodePayments::CheckAndRemove()\n{\n    LOCK2(cs_mapMasternodePayeeVotes, cs_mapMasternodeBlocks);\n\n    int nHeight;\n    {\n        TRY_LOCK(cs_main, locked);\n        if (!locked || chainActive.Tip() == NULL) return;\n        nHeight = chainActive.Tip()->nHeight;\n    }\n\n    //keep up to five cycles for historical sake\n    int nLimit = std::max(int(mnodeman.size() * 1.25), 1000);\n\n    std::map<uint256, CMasternodePaymentWinner>::iterator it = mapMasternodePayeeVotes.begin();\n    while (it != mapMasternodePayeeVotes.end()) {\n        CMasternodePaymentWinner winner = (*it).second;\n\n        if (nHeight - winner.nBlockHeight > nLimit) {\n            LogPrint(\"mnpayments\", \"CMasternodePayments::CleanPaymentList - Removing old Masternode payment - block %d\\n\", winner.nBlockHeight);\n            masternodeSync.mapSeenSyncMNW.erase((*it).first);\n            mapMasternodePayeeVotes.erase(it++);\n            mapMasternodeBlocks.erase(winner.nBlockHeight);\n        } else {\n            ++it;\n        }\n    }\n}\n\nbool CMasternodePaymentWinner::IsValid(CNode* pnode, std::string& strError)\n{\n    CMasternode* pmn = mnodeman.Find(vinMasternode);\n\n    if (!pmn) {\n        strError = strprintf(\"Unknown Masternode %s\", vinMasternode.prevout.hash.ToString());\n        LogPrint(\"masternode\",\"CMasternodePaymentWinner::IsValid - %s\\n\", strError);\n        mnodeman.AskForMN(pnode, vinMasternode);\n        return false;\n    }\n\n    if (pmn->protocolVersion < ActiveProtocol()) {\n        strError = strprintf(\"Masternode protocol too old %d - req %d\", pmn->protocolVersion, ActiveProtocol());\n        LogPrint(\"masternode\",\"CMasternodePaymentWinner::IsValid - %s\\n\", strError);\n        return false;\n    }\n\n    int n = mnodeman.GetMasternodeRank(vinMasternode, nBlockHeight - 100, ActiveProtocol());\n\n    if (n > MNPAYMENTS_SIGNATURES_TOTAL) {\n        //It's common to have masternodes mistakenly think they are in the top 10\n        // We don't want to print all of these messages, or punish them unless they're way off\n        if (n > MNPAYMENTS_SIGNATURES_TOTAL * 2) {\n            strError = strprintf(\"Masternode not in the top %d (%d)\", MNPAYMENTS_SIGNATURES_TOTAL * 2, n);\n            LogPrint(\"masternode\",\"CMasternodePaymentWinner::IsValid - %s\\n\", strError);\n            //if (masternodeSync.IsSynced()) Misbehaving(pnode->GetId(), 20);\n        }\n        return false;\n    }\n\n    return true;\n}\n\nbool CMasternodePayments::ProcessBlock(int nBlockHeight)\n{\n    if (!fMasterNode) return false;\n\n    //reference node - hybrid mode\n\n    int n = mnodeman.GetMasternodeRank(activeMasternode.vin, nBlockHeight - 100, ActiveProtocol());\n\n    if (n == -1) {\n        LogPrint(\"mnpayments\", \"CMasternodePayments::ProcessBlock - Unknown Masternode\\n\");\n        return false;\n    }\n\n    if (n > MNPAYMENTS_SIGNATURES_TOTAL) {\n        LogPrint(\"mnpayments\", \"CMasternodePayments::ProcessBlock - Masternode not in the top %d (%d)\\n\", MNPAYMENTS_SIGNATURES_TOTAL, n);\n        return false;\n    }\n\n    if (nBlockHeight <= nLastBlockHeight) return false;\n\n    CMasternodePaymentWinner newWinner(activeMasternode.vin);\n\n    LogPrint(\"masternode\",\"CMasternodePayments::ProcessBlock() Start nHeight %d - vin %s. \\n\", nBlockHeight, activeMasternode.vin.prevout.hash.ToString());\n\n    // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough\n    int nCount = 0;\n    CMasternode* pmn = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount);\n\n    if (pmn != NULL) {\n        LogPrint(\"masternode\",\"CMasternodePayments::ProcessBlock() Found by FindOldestNotInVec \\n\");\n\n        newWinner.nBlockHeight = nBlockHeight;\n\n        CScript payee = GetScriptForDestination(pmn->pubKeyCollateralAddress.GetID());\n        newWinner.AddPayee(payee);\n\n        CTxDestination address1;\n        ExtractDestination(payee, address1);\n        CBitcoinAddress address2(address1);\n\n        LogPrint(\"masternode\",\"CMasternodePayments::ProcessBlock() Winner payee %s nHeight %d. \\n\", address2.ToString().c_str(), newWinner.nBlockHeight);\n    } else {\n        LogPrint(\"masternode\",\"CMasternodePayments::ProcessBlock() Failed to find masternode to pay\\n\");\n    }\n\n    std::string errorMessage;\n    CPubKey pubKeyMasternode;\n    CKey keyMasternode;\n\n    if (!CObfuScationSigner::SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) {\n        LogPrint(\"masternode\",\"CMasternodePayments::ProcessBlock() - Error upon calling SetKey: %s\\n\", errorMessage.c_str());\n        return false;\n    }\n\n    LogPrint(\"masternode\",\"CMasternodePayments::ProcessBlock() - Signing Winner\\n\");\n    if (newWinner.Sign(keyMasternode, pubKeyMasternode)) {\n        LogPrint(\"masternode\",\"CMasternodePayments::ProcessBlock() - AddWinningMasternode\\n\");\n\n        if (AddWinningMasternode(newWinner)) {\n            newWinner.Relay();\n            nLastBlockHeight = nBlockHeight;\n            return true;\n        }\n    }\n\n    return false;\n}\n\nvoid CMasternodePaymentWinner::Relay()\n{\n    CInv inv(MSG_MASTERNODE_WINNER, GetHash());\n    RelayInv(inv);\n}\n\nbool CMasternodePaymentWinner::SignatureValid()\n{\n    CMasternode* pmn = mnodeman.Find(vinMasternode);\n\n    if (pmn != NULL) {\n        std::string strMessage = vinMasternode.prevout.ToStringShort() +\n                boost::lexical_cast<std::string>(nBlockHeight) +\n                payee.ToString();\n\n        std::string errorMessage = \"\";\n        if (!CObfuScationSigner::VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) {\n            return error(\"CMasternodePaymentWinner::SignatureValid() - Got bad Masternode address signature %s\\n\", vinMasternode.prevout.hash.ToString());\n        }\n\n        return true;\n    }\n\n    return false;\n}\n\nvoid CMasternodePayments::Sync(CNode* node, int nCountNeeded)\n{\n    LOCK(cs_mapMasternodePayeeVotes);\n\n    int nHeight;\n    {\n        TRY_LOCK(cs_main, locked);\n        if (!locked || chainActive.Tip() == NULL) return;\n        nHeight = chainActive.Tip()->nHeight;\n    }\n\n    int nCount = (mnodeman.CountEnabled() * 1.25);\n    if (nCountNeeded > nCount) nCountNeeded = nCount;\n\n    int nInvCount = 0;\n    std::map<uint256, CMasternodePaymentWinner>::iterator it = mapMasternodePayeeVotes.begin();\n    while (it != mapMasternodePayeeVotes.end()) {\n        CMasternodePaymentWinner winner = (*it).second;\n        if (winner.nBlockHeight >= nHeight - nCountNeeded && winner.nBlockHeight <= nHeight + 20) {\n            node->PushInventory(CInv(MSG_MASTERNODE_WINNER, winner.GetHash()));\n            nInvCount++;\n        }\n        ++it;\n    }\n    node->PushMessage(\"ssc\", MASTERNODE_SYNC_MNW, nInvCount);\n}\n\nstd::string CMasternodePayments::ToString() const\n{\n    std::ostringstream info;\n\n    info << \"Votes: \" << (int)mapMasternodePayeeVotes.size() << \", Blocks: \" << (int)mapMasternodeBlocks.size();\n\n    return info.str();\n}\n\n\nint CMasternodePayments::GetOldestBlock()\n{\n    LOCK(cs_mapMasternodeBlocks);\n\n    int nOldestBlock = std::numeric_limits<int>::max();\n\n    std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin();\n    while (it != mapMasternodeBlocks.end()) {\n        if ((*it).first < nOldestBlock) {\n            nOldestBlock = (*it).first;\n        }\n        it++;\n    }\n\n    return nOldestBlock;\n}\n\n\nint CMasternodePayments::GetNewestBlock()\n{\n    LOCK(cs_mapMasternodeBlocks);\n\n    int nNewestBlock = 0;\n\n    std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin();\n    while (it != mapMasternodeBlocks.end()) {\n        if ((*it).first > nNewestBlock) {\n            nNewestBlock = (*it).first;\n        }\n        it++;\n    }\n\n    return nNewestBlock;\n}\n\nstatic uint256 CalculateLotteryScore(const uint256 &hashCoinbaseTx, const uint256 &hashLastLotteryBlock)\n{\n    // Deterministically calculate a \"score\" for a Masternode based on any given (block)hash\n    CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);\n    ss << hashCoinbaseTx << hashLastLotteryBlock;\n    return ss.GetHash();\n}\n\nstatic bool IsCoinstakeValidForLottery(const CTransaction &tx, int nHeight)\n{\n    CAmount nAmount = 0;\n    if(tx.IsCoinBase()) {\n        nAmount = tx.vout[0].nValue;\n    }\n    else {\n        auto payee = tx.vout[1].scriptPubKey;\n        nAmount = std::accumulate(std::begin(tx.vout), std::end(tx.vout), CAmount(0), [payee](CAmount accum, const CTxOut &out) {\n                return out.scriptPubKey == payee ? accum + out.nValue : accum;\n    });\n    }\n\n    int nMinStakeValue = 10000; // default is 10k\n\n    if(sporkManager.IsSporkActive(SPORK_16_LOTTERY_TICKET_MIN_VALUE)) {\n        MultiValueSporkList<LotteryTicketMinValueSporkValue> vValues;\n        CSporkManager::ConvertMultiValueSporkVector(sporkManager.GetMultiValueSpork(SPORK_16_LOTTERY_TICKET_MIN_VALUE), vValues);\n        auto nBlockTime = chainActive[nHeight] ? chainActive[nHeight]->nTime : GetAdjustedTime();\n        LotteryTicketMinValueSporkValue activeSpork = CSporkManager::GetActiveMultiValueSpork(vValues, nHeight, nBlockTime);\n\n        if(activeSpork.IsValid()) {\n            // we expect that this value is in coins, not in satoshis\n            nMinStakeValue = activeSpork.nEntryTicketValue;\n        }\n    }\n\n    return nAmount > nMinStakeValue * COIN; // only if stake is more than 10k\n}\n\nstd::vector<WinnerCoinStake> CalculateLotteryWinners(const CBlock &block, const CBlockIndex *prevBlockIndex, int nHeight)\n{\n    std::vector<WinnerCoinStake> result;\n    // if that's a block when lottery happens, reset score for whole cycle\n    if(IsValidLotteryBlockHeight(nHeight))\n        return result;\n\n    if(!prevBlockIndex)\n        return result;\n\n    int nLastLotteryHeight = std::max(Params().GetLotteryBlockStartBlock(), Params().GetLotteryBlockCycle() * ((nHeight - 1) / Params().GetLotteryBlockCycle()));\n\n    if(nHeight <= nLastLotteryHeight) {\n        return result;\n    }\n\n    const auto& coinbaseTx = (nHeight > Params().LAST_POW_BLOCK() ? block.vtx[1] : block.vtx[0]);\n\n    if(!IsCoinstakeValidForLottery(coinbaseTx, nHeight)) {\n        return prevBlockIndex->vLotteryWinnersCoinstakes; // return last if we have no lotter participant in this block\n    }\n\n    CBlockIndex* pblockindex = chainActive[nLastLotteryHeight];\n    auto hashLastLotteryBlock = pblockindex->GetBlockHash();\n    // lotteryWinnersCoinstakes has hashes of coinstakes, let calculate old scores + new score\n    using LotteryScore = uint256;\n    std::vector<std::pair<LotteryScore, WinnerCoinStake>> scores;\n    for(auto &&hashCoinstake : prevBlockIndex->vLotteryWinnersCoinstakes) {\n        scores.emplace_back(CalculateLotteryScore(hashCoinstake, hashLastLotteryBlock), hashCoinstake);\n    }\n\n    auto newScore = CalculateLotteryScore(coinbaseTx.GetHash(), hashLastLotteryBlock);\n    scores.emplace_back(newScore, coinbaseTx.GetHash());\n\n    // biggest entry at the begining\n    if(scores.size() > 1)\n    {\n        std::sort(std::begin(scores), std::end(scores), [](const std::pair<LotteryScore, WinnerCoinStake> &lhs, const std::pair<LotteryScore, WinnerCoinStake> &rhs) {\n            return lhs.first > rhs.first;\n        });\n    }\n\n    scores.resize(std::min<size_t>(scores.size(), 11)); // don't go over 11 entries, since we will have only 11 winners\n\n    // prepare new coinstakes vector\n    for(auto &&score : scores) {\n        result.push_back(score.second);\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "731c273e73fc2532693db2e356967d7916b88e08", "size": 31530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Astra/src/masternode-payments.cpp", "max_stars_repo_name": "KingricharVD/Astra-Coin", "max_stars_repo_head_hexsha": "a0bde2b8548d36fca8ab23cd5ae7b777bb4e1c4c", "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": "Astra/src/masternode-payments.cpp", "max_issues_repo_name": "KingricharVD/Astra-Coin", "max_issues_repo_head_hexsha": "a0bde2b8548d36fca8ab23cd5ae7b777bb4e1c4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Astra/src/masternode-payments.cpp", "max_forks_repo_name": "KingricharVD/Astra-Coin", "max_forks_repo_head_hexsha": "a0bde2b8548d36fca8ab23cd5ae7b777bb4e1c4c", "max_forks_repo_licenses": ["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.7078142695, "max_line_length": 204, "alphanum_fraction": 0.6820805582, "num_tokens": 8395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.16814653563250703}}
{"text": "#include \"TransportNetwork.hpp\"\n#include <base-logging/Logging.hpp>\n#include <numeric/Combinatorics.hpp>\n#include <numeric/Stats.hpp>\n#include <gecode/minimodel.hh>\n#include <gecode/set.hh>\n#include <gecode/gist.hh>\n#include <gecode/search.hh>\n\n#include <iterator>\n#include <iomanip>\n#include <fstream>\n#include <Eigen/Dense>\n\n#include <moreorg/Algebra.hpp>\n#include <moreorg/vocabularies/OM.hpp>\n#include <moreorg/facades/Robot.hpp>\n\n#include <graph_analysis/GraphIO.hpp>\n#include <graph_analysis/algorithms/LPSolver.hpp>\n\n#include \"../../SharedPtr.hpp\"\n#include \"../../symbols/object_variables/LocationCardinality.hpp\"\n#include \"../../SpaceTime.hpp\"\n#include \"ConstraintMatrix.hpp\"\n#include \"branchers/TimelineBrancher.hpp\"\n#include \"propagators/IsPath.hpp\"\n#include \"propagators/InEdgesRestriction.hpp\"\n#include \"propagators/IsValidTransportEdge.hpp\"\n#include \"propagators/MultiCommodityFlow.hpp\"\n#include \"utils/Formatter.hpp\"\n#include \"utils/Converter.hpp\"\n#include \"../../utils/CSVLogger.hpp\"\n#include \"MissionConstraints.hpp\"\n#include \"Search.hpp\"\n#include \"../SolutionAnalysis.hpp\"\n#include \"MissionConstraintManager.hpp\"\n#include \"../../constraints/ModelConstraint.hpp\"\n\nusing namespace templ::solvers::csp::utils;\nusing namespace owlapi::model;\n\nnamespace templ {\nnamespace solvers {\nnamespace csp {\n\nbool TransportNetwork::msInteractive = false;\nTransportNetwork::FlowSolutions TransportNetwork::msMinCostFlowSolutions;\n\nstd::string TransportNetwork::Solution::toString(uint32_t indent) const\n{\n    std::stringstream ss;\n    std::string hspace(indent,' ');\n    {\n        ModelDistribution::const_iterator cit = mModelDistribution.begin();\n        size_t count = 0;\n        ss << hspace << \"ModelDistribution\" << std::endl;\n        for(; cit != mModelDistribution.end(); ++cit)\n        {\n            const FluentTimeResource& fts = cit->first;\n            ss << hspace << \"--- requirement #\" << count++ << std::endl;\n            ss << hspace << fts.toString() << std::endl;\n\n            const moreorg::ModelPool& modelPool = cit->second;\n            ss << modelPool.toString(indent) << std::endl;\n        }\n    }\n    {\n        RoleDistribution::const_iterator cit = mRoleDistribution.begin();\n        size_t count = 0;\n        ss << hspace << \"RoleDistribution\" << std::endl;\n        for(; cit != mRoleDistribution.end(); ++cit)\n        {\n            const FluentTimeResource& fts = cit->first;\n            ss << hspace << \"--- requirement #\" << count++ << std::endl;\n            ss << hspace << fts.toString() << std::endl;\n\n            const Role::List& roles = cit->second;\n            ss << hspace << Role::toString(roles) << std::endl;\n        }\n    }\n    {\n        ss << hspace << \"Timelines (\" << mTimelines.size() << \")\" << std::endl;\n        ss << hspace  << RoleTimeline::toString(mTimelines, 4);\n    }\n    return ss.str();\n}\n\nSpaceTime::Network TransportNetwork::Solution::toNetwork() const\n{\n    return SpaceTime::toNetwork(mLocations, mTimepoints,\n            RoleTimeline::collectTimelines(mTimelines) );\n}\n\n// return true in order to enforce a restart\n// return false would continue search without a restart\nbool TransportNetwork::master(const Gecode::MetaInfo& mi)\n{\n    switch(mi.type())\n    {\n        case Gecode::MetaInfo::RESTART:\n            if(mi.last() != NULL)\n            {\n                constrain(*mi.last());\n            }\n            mi.nogoods().post(*this);\n            return true;\n        case Gecode::MetaInfo::PORTFOLIO:\n            Gecode::BrancherGroup::all.kill(*this);\n            break;\n        default:\n            break;\n    }\n    return true;\n}\n\nvoid TransportNetwork::next(const TransportNetwork& lastSpace, const Gecode::MetaInfo& mi)\n{\n    breakpoint(\"BEGIN next()\");\n\n    // constrain the next space // but not the first\n    if(mi.last() != NULL)\n    {\n        constrainSlave(*mi.last());\n\n        // the last space is the result of the 'first' slave so this\n        // is our basic (master) solution to start from\n        mMinCostFlowFlaws = lastSpace.mMinCostFlowFlaws;\n        mFlawResolution = lastSpace.mFlawResolution;\n        mRequiredResolutionOptions = lastSpace.mRequiredResolutionOptions;\n    }\n\n    breakpointStart()\n        << \"next():\" << std::endl\n        << \"    # flaws: \" << mMinCostFlowFlaws.size() << std::endl\n        << \"    # resolution options: \" <<\n        mFlawResolution.remainingDraws().size() << std::endl\n        ;\n    breakpointEnd();\n\n    namespace ga = graph_analysis::algorithms;\n\n    Constraint::PtrList constraints = FlawResolution::selectBestResolution(*this, lastSpace, lastSpace.cost().val(), mFlawResolution.getResolutionOptions());\n    if(constraints.empty())\n    {\n        std::cout << \"    # no applicable resolvers better than \" << lastSpace.cost().val() <<\n            \"-- failing search\" << std::endl;\n        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\\n' );\n\n        this->fail();\n        return;\n    }\n\n    //FlawResolution::ResolutionOptions resolutionOptions = mFlawResolution.current();\n    // Update the existing set of resolution options\n    // this set will be propagated to any clones (and thus slaves that will\n    // improve any solution of this)\n    //\n    // Now assuming we only improve an existing solution, but not to a perfect\n    // solution then what?\n    //\n    // Goal: we want to record the benefit of fixing a flaw for a 'master'\n    // solution\n\n    for(const Constraint::Ptr& constraint : constraints)\n    {\n        addConstraint(constraint, *this);\n    }\n    // Recompute unary resource usage since constraints have changed\n    enforceUnaryResourceUsage();\n}\n\n// Constrain function is called with the last solution found as argument (if a\n// solution has already been found\nvoid TransportNetwork::constrain(const Gecode::Space& lastSpace)\n{\n    const TransportNetwork& lastTransportNetwork = static_cast<const TransportNetwork&>(lastSpace);\n\n    breakpointStart()\n        << \"constrain()\" << std::endl\n        << \"Last state: \" << std::endl\n        << \"    # cost: \"<< lastTransportNetwork.mCost.val() << std::endl\n        << \"    # flaws: \"<< lastTransportNetwork.mMinCostFlowFlaws.size() << std::endl\n        << \"    # resolution options: \" << lastTransportNetwork.mFlawResolution.remainingDraws().size() <<\n        std::endl\n        << \"Current: \" << std::endl\n        << \"    # cost: \" << cost() << std::endl;\n    breakpointEnd();\n\n\n    bool hillClimbing = mpContext->configuration().getValueAs<bool>(\"TransportNetwork/search/options/hill-climbing\",false);\n    if(hillClimbing)\n    {\n        rel(*this, cost(), Gecode::IRT_LE, lastTransportNetwork.cost().val());\n        // TODO:\n        // check on the number of flows and the cost of the solution in order to\n        // find an improved solution\n    }\n}\n\nvoid TransportNetwork::constrainSlave(const Gecode::Space& lastSpace)\n{\n    const TransportNetwork& lastTransportNetwork = static_cast<const TransportNetwork&>(lastSpace);\n\n    breakpointStart()\n         << \"constrainSlave()\" << std::endl\n         << \"Last state: \" << std::endl\n         << \"    # flaws: \"<< lastTransportNetwork.mMinCostFlowFlaws.size() << std::endl\n         << \"    # resolution options: \" << lastTransportNetwork.mFlawResolution.remainingDraws().size() << std::endl;\n    breakpointEnd();\n\n    //rel(*this, cost(), Gecode::IRT_LE, lastTransportNetwork.cost().val());\n\n    // Approach 1: BFS Style\n    // Slaves have to provide optimal (zero flaw) solutions\n    // This has the effect that an iteration of the slave either returns a\n    // perfect solution or none;\n    // yet it would be beneficial to improve any 'best slave'\n    rel(*this, mNumberOfFlaws, Gecode::IRT_EQ, 0);\n\n    // Approach 2: DFS Style\n    // improve any existing solution\n    rel(*this, mNumberOfFlaws, Gecode::IRT_LE, lastTransportNetwork.mNumberOfFlaws);\n\n    // TODO:\n    // check on the number of flows and the cost of the solution in order to\n    // find an improved solution\n}\n\n// Gecode 9.4.4\n// The default slave() function does nothing and returns true , indicating that\n// the search in the slave space is going to be complete. This means that if the\n// search in the slave space finishes exhaustively, the meta search will also\n// finish. Returning false instead would indicate that the slave search is\n// incomplete, for example if it only explores a limited neighborhood of the\n// previous solution\nbool TransportNetwork::slave(const Gecode::MetaInfo& mi)\n{\n    if(!mUseMasterSlave)\n    {\n        // using default implementation of slave, i.e. search is complete\n        return true;\n    } else {\n        mpMission->getLogger()->incrementSessionId();\n    }\n\n    breakpointStart()\n        << \"slave() with restarts: \" << mi.restart() << std::endl;\n    breakpointEnd();\n\n    if(mi.type() == Gecode::MetaInfo::RESTART)\n    {\n        if(!mi.last())\n        {\n            // the previous call with initialize the selected draw\n            breakpointStart()\n                    << \"No last space available, thus slave search is complete\" << std::endl;\n            breakpointEnd();\n\n            // slave should only expand an existing solution,\n            // but search is not complete at this stage\n            return false;\n        }\n\n        // Last space the slave will improve upon\n        // this should be consistent with the master of this slave\n        const TransportNetwork& lastSpace = static_cast<const TransportNetwork&>(*mi.last());\n        if(!lastSpace.mFlawResolution.next(true))\n        {\n            // the previous call with initialize the selected draw\n            breakpointStart()\n                << \"Flaw resolution: options are exhausted slave search is complete\" << std::endl;\n            breakpointEnd();\n\n            // Options are exhausted Search is complete\n            mpMission->getLogger()->incrementSessionId();\n            return false;\n        } else {\n            std::cout << \"Calling next with last space\" << std::endl;\n            next(lastSpace, mi);\n            return false;\n        }\n    }\n    return false;\n}\n\nTransportNetwork::Solution TransportNetwork::getSolution() const\n{\n    Solution solution;\n    try {\n        solution.mModelDistribution = getModelDistribution();\n        solution.mRoleDistribution = getRoleDistribution();\n        solution.mTimelines = getTimelines();\n        solution.mLocations = mpContext->locations();\n        solution.mTimepoints = mTimepoints;\n        solution.mMinCostFlowSolution = mMinCostFlowSolution;\n        solution.mSolutionAnalysis = mSolutionAnalysis;\n    } catch(std::exception& e)\n    {\n        LOG_WARN_S << e.what();\n    }\n    return solution;\n}\n\nvoid TransportNetwork::saveSolution(const Solution& solution, const Mission::Ptr& mission)\n{\n    std::string filename;\n    int i = mission->getLogger()->getSessionId();\n    try {\n        std::stringstream ss;\n        ss << \"transport-network-solution-\" << i << \".dot\";\n        filename = mission->getLogger()->filename(ss.str());\n        graph_analysis::io::GraphIO::write(filename, solution.getMinCostFlowSolution().getGraph());\n    } catch(const std::exception& e)\n    {\n        LOG_WARN_S << \"Saving file \" << filename << \" failed: -- \" << e.what();\n    }\n\n    try {\n        std::stringstream ss;\n        ss << \"transport-network-solution-\" << i << \".gexf\";\n        filename = mission->getLogger()->filename(ss.str());\n        solution.getMinCostFlowSolution().save(filename, \"gexf\");\n    } catch(const std::exception& e)\n    {\n        LOG_WARN_S << \"Saving file \" << filename << \" failed: -- \" << e.what();\n    }\n\n    try {\n        solution.getSolutionAnalysis().save();\n    } catch(const std::exception& e)\n    {\n        LOG_WARN_S << \"Saving solution analysis failed: -- \" << e.what();\n    }\n}\n\nTransportNetwork::ModelDistribution TransportNetwork::getModelDistribution() const\n{\n    ModelDistribution solution;\n\n    Gecode::Matrix<Gecode::IntVarArray> resourceDistribution(mModelUsage,\n            mpMission->getAvailableResources().size(), mResourceRequirements.size());\n\n    // Check if resource requirements holds\n    for(size_t i = 0; i < mResourceRequirements.size(); ++i)\n    {\n        moreorg::ModelPool modelPool;\n        for(size_t mi = 0; mi < mpMission->getAvailableResources().size(); ++mi)\n        {\n            Gecode::IntVar var = resourceDistribution(mi, i);\n            if(!var.assigned())\n            {\n                throw std::runtime_error(\"templ::solvers::csp::TransportNetwork::getSolution: value has not been assigned\");\n            }\n\n            Gecode::IntVarValues v( var );\n\n            modelPool[ mpMission->getModels()[mi] ] = v.val();\n        }\n\n        solution[ mResourceRequirements[i] ] = modelPool;\n    }\n    return solution;\n}\n\nTransportNetwork::RoleDistribution TransportNetwork::getRoleDistribution() const\n{\n    RoleDistribution solution;\n\n    Gecode::Matrix<Gecode::IntVarArray> roleDistribution(mRoleUsage, /*width --> col*/ mRoles.size(), /*height --> row*/ mResourceRequirements.size());\n\n    // Check if resource requirements holds\n    for(size_t i = 0; i < mResourceRequirements.size(); ++i)\n    {\n        Role::List roles;\n        for(size_t r = 0; r < mRoles.size(); ++r)\n        {\n            Gecode::IntVar var = roleDistribution(r, i);\n            if(!var.assigned())\n            {\n                throw std::runtime_error(\"templ::solvers::csp::RoleDistribution::getSolution: value has not been assigned for role: '\" + mRoles[r].toString() + \"'\");\n            }\n\n            Gecode::IntVarValues v( var );\n\n            if( v.val() == 1 )\n            {\n                roles.push_back( mRoles[r] );\n            }\n        }\n\n        solution[ mResourceRequirements[i] ] = roles;\n    }\n\n    return solution;\n}\n\nstd::map<Role, csp::RoleTimeline> TransportNetwork::getTimelines() const\n{\n    std::map<Role, csp::RoleTimeline> roleTimelines;\n    for(size_t i = 0; i < mActiveRoleList.size(); ++i)\n    {\n        const Role& role = mActiveRoleList[i];\n        LOG_INFO_S << \"Active role: \" << i << \" of \" << mActiveRoleList.size() << \" \" << mActiveRoleList[i].toString() << std::endl\n            << Formatter::toString(mTimelines[i],\n                    mpContext->locations(),\n                    mTimepoints)\n            << std::endl;\n\n        bool doThrow = false;\n        SpaceTime::Timeline timeline = TypeConversion::toTimeline(mTimelines[i],\n                mpContext->locations(),\n                mTimepoints,\n                doThrow);\n\n        csp::RoleTimeline roleTimeline(role, mpContext->ask());\n        roleTimeline.setTimeline(timeline);\n\n        roleTimelines[role] = roleTimeline;\n\n    }\n    return roleTimelines;\n}\n\nTransportNetwork::TransportNetwork()\n    : Gecode::Space()\n    , Solver(Solver::CSP_TRANSPORT_NETWORK)\n{}\n\nTransportNetwork::TransportNetwork(const templ::Mission::Ptr& mission, const qxcfg::Configuration& configuration)\n    : Gecode::Space()\n    , Solver(Solver::CSP_TRANSPORT_NETWORK)\n    , mpMission(mission)\n    , mpContext(make_shared<Context>(mission, configuration))\n    , mTimepoints(mission->getUnorderedTimepoints())\n    , mResourceRequirements()\n    , mQualitativeTimepoints(*this, mpMission->getQualitativeTemporalConstraintNetwork()->getTimepoints().size(), 0, mpMission->getQualitativeTemporalConstraintNetwork()->getTimepoints().size()-1)\n    , mModelUsage()\n    , mRoleUsage()\n    , mRoles(mission->getRoles())\n    , mCost(*this,0, Gecode::Int::Limits::max)\n    , mNumberOfFlaws(*this,0, Gecode::Int::Limits::max)\n    , mUseMasterSlave(false)\n    , mpCurrentMaster(NULL)\n{\n    // FIXME: make sure we use the the same configuration of the ask object\n    mpMission->setOrganizationModelAsk(mpContext->ask());\n\n    assert( mpMission->getOrganizationModel() );\n    assert(!mpContext->intervals().empty());\n    LOG_INFO_S << \"TransportNetwork CSP Problem Construction\" << std::endl\n    << \"    requested resources: \" << mpMission->getRequestedResources() << std::endl\n    << \"    intervals: \" << mpContext->intervals().size() << std::endl\n    << \"    # requirements: \" << mResourceRequirements.size() << std::endl;\n\n    initializeTemporalConstraintNetwork();\n}\n\nvoid TransportNetwork::initializeTemporalConstraintNetwork()\n{\n    // Allow branching of temporal constraint network\n    // Initialize constraint network after mQualitativeTimepoints has been\n    // properly constructed -- otherwise we will trigger segfaults\n    mTemporalConstraintNetwork = TemporalConstraintNetworkBase(*mpMission->getQualitativeTemporalConstraintNetwork(),*this, mQualitativeTimepoints);\n\n    bool nooverlap = mpContext->configuration().getValueAs<bool>(\"TransportNetwork/intervals-nooverlap\",false);\n    if(nooverlap)\n    {\n        LOG_WARN_S << \"Configuration: no interval overlaps are allowed\";\n        mTemporalConstraintNetwork.addNoOverlap(mpContext->intervals(), *this, mQualitativeTimepoints);\n    }\n    // making sure we get a fully assigned temporal constraint network, i.e.\n    // one without gaps before we proceed\n    Gecode::Rnd temporalNetworkRnd;\n    temporalNetworkRnd.hw();\n    Gecode::branch(*this, mQualitativeTimepoints, Gecode::INT_VAR_RND(temporalNetworkRnd), Gecode::INT_VAL_MIN());\n    Gecode::branch(*this, &TransportNetwork::doPostTemporalConstraints);\n}\n\n\nvoid TransportNetwork::initializeMinMaxConstraints()\n{\n    Gecode::Matrix<Gecode::IntVarArray> resourceDistribution(mModelUsage, /*width --> col*/ mpMission->getAvailableResources().size(), /*height --> row*/ mResourceRequirements.size());\n\n\n    const IRIList& availableModels = mpMission->getModels();\n    const moreorg::ModelPool& modelPool = mpMission->getAvailableResources();\n\n    // TODO: change to using MissionConstraintManager\n    // For debugging purposes\n    ConstraintMatrix constraintMatrix(availableModels);\n    using namespace solvers::temporal;\n    std::vector<FluentTimeResource>::const_iterator fit = mResourceRequirements.begin();\n    for(; fit != mResourceRequirements.end(); ++fit)\n    {\n        const FluentTimeResource& fts = *fit;\n        // row: index of requirement\n        // col: index of model type\n        size_t requirementIndex = fit - mResourceRequirements.begin();\n        for(size_t mi = 0; mi < availableModels.size(); ++mi)\n        {\n            Gecode::IntVar v = resourceDistribution(mi, requirementIndex);\n            uint32_t minCardinality = 0;\n            const IRI& model = availableModels[mi];\n            {\n                // default min requirement is 0 for a model\n                /// Consider resource cardinality constraint\n                /// Check what is set for the given model\n                moreorg::ModelPool::const_iterator cardinalityIt =\n                    fts.getMinCardinalities().find(model);\n                if(cardinalityIt != fts.getMinCardinalities().end())\n                {\n                    minCardinality = cardinalityIt->second;\n                }\n                constraintMatrix.setMin(requirementIndex, mi, minCardinality);\n                rel(*this, v, Gecode::IRT_GQ, minCardinality);\n            }\n\n            uint32_t maxCardinality = modelPool.at(model);\n            // setting the upper bound for this model and this service\n            // based on what the model pool can provide\n            constraintMatrix.setMax(requirementIndex, mi, maxCardinality);\n            rel(*this, v, Gecode::IRT_LQ, maxCardinality);\n\n            LOG_DEBUG_S << \"requirement: \" << requirementIndex\n                << \", model: \" << model\n                << \" IRT_GQ \" << minCardinality << \", IRT_LQ: \" << maxCardinality;\n        }\n\n        // there can be no empty assignment for resource requirement\n        rel(*this, sum( resourceDistribution.row(requirementIndex) ) > 0);\n        if(this->failed())\n        {\n            LOG_WARN_S << \"Encountered an empty assignment for a resource requirement\" << std::endl\n                << \"requirement index: \" << requirementIndex << std::endl\n                << resourceDistribution.row(requirementIndex) << std::endl\n                << fts.toString(4);\n            return;\n        }\n    }\n\n    std::vector<std::string> rowNames =\n        FluentTimeResource::toQualificationStringList(mResourceRequirements.begin(),\n            mResourceRequirements.end());\n    LOG_INFO_S << constraintMatrix.toString(rowNames);\n\n    breakpointStart()\n        << \"InitializeMinMax: final constraint matrix: \" << constraintMatrix.toString(rowNames) << std::endl;\n    breakpointEnd();\n}\n\nvoid TransportNetwork::addExtensionalConstraints()\n{\n    size_t availableResourceCount = mpMission->getAvailableResources().size();\n    Gecode::Matrix<Gecode::IntVarArray> resourceDistribution(mModelUsage,\n            /*width --> col*/ availableResourceCount,\n            /*height --> row*/ mResourceRequirements.size());\n\n   size_t requirementIndex = 0;\n   for(const FluentTimeResource& ftr: mResourceRequirements)\n   {\n        // Prepare the extensional constraints, i.e. specifying the allowed\n        // combinations for each requirement\n        moreorg::ModelPool::Set allowedCombinations = ftr.getDomain();\n        if(allowedCombinations.empty())\n        {\n            LOG_WARN_S << \"No allowed combinations available with the given constraints: failing this space\";\n            this->fail();\n            return;\n        }\n        LOG_INFO_S << \"Adding extensional constraint:\\n\" << ftr.toString(4);\n\n        // A tuple set is a fully expanded vector describing the cardinality for\n        // all available resources\n        Gecode::TupleSet tupleSet(availableResourceCount);\n        appendToTupleSet(tupleSet, allowedCombinations);\n        tupleSet.finalize();\n        extensional(*this, resourceDistribution.row(requirementIndex), tupleSet);\n        if(this->failed())\n        {\n            LOG_WARN_S  << \"Adding extensional constraint lead to failed space\"\n                << ftr.toString(4);\n            return;\n        }\n        ++requirementIndex;\n   }\n}\n\nvoid TransportNetwork::setUpperBoundForConcurrentRequirements()\n{\n    Gecode::Matrix<Gecode::IntVarArray> resourceDistribution(mModelUsage, /*width --> col*/ mpMission->getAvailableResources().size(), /*height --> row*/ mResourceRequirements.size());\n\n    // - identify overlapping fts, limit resources for these\n    std::vector< std::vector<FluentTimeResource> > concurrentRequirements;\n    bool nooverlap = mpContext->configuration().getValueAs<bool>(\"TransportNetwork/intervals-nooverlap\",false);\n\n    if(nooverlap)\n    {\n        for(const FluentTimeResource& ftr : mResourceRequirements)\n        {\n            concurrentRequirements.push_back( { ftr } );\n        }\n    } else {\n        // Make sure the correct constraints network is used for comparison\n        temporal::point_algebra::TimePointComparator tpc(mpQualitativeTemporalConstraintNetwork);\n        // Make sure the assignments are within resource bounds for concurrent requirements\n        concurrentRequirements = FluentTimeResource::getMutualExclusive(mResourceRequirements, tpc);\n    }\n\n    const moreorg::ModelPool& modelPool = mpMission->getAvailableResources();\n    const IRIList& availableModels = mpMission->getModels();\n\n    for(const std::vector<FluentTimeResource>& concurrentFluents :\n            concurrentRequirements)\n    {\n        for(size_t mi = 0; mi < availableModels.size(); ++mi)\n        {\n            const IRI& model = availableModels[mi];\n            Gecode::IntVarArgs args;\n\n            std::vector<FluentTimeResource>::const_iterator fit = concurrentFluents.begin();\n            for(; fit != concurrentFluents.end(); ++fit)\n            {\n                size_t fluentIdx = FluentTimeResource::getIndex(mResourceRequirements, *fit);\n                Gecode::IntVar v = resourceDistribution(mi,fluentIdx);\n                args << v;\n            }\n\n            uint32_t maxCardinality = modelPool.at(model);\n            LOG_DEBUG_S << \"Add general resource usage constraint: \" << std::endl\n                << \"     \" << availableModels[mi].toString() << \"# <= \" << maxCardinality;\n            rel(*this, sum(args) <= maxCardinality);\n        }\n    }\n}\n\nvoid TransportNetwork::initializeRoleDistributionConstraints()\n{\n    bool forceMinimumRoleUsage = mpContext->configuration().getValueAs<bool>(\"TransportNetwork/search/options/role-usage/force-min\",false);\n    int mobileRoleUsageBoundOffset = mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/role-usage/mobile/bound-offset\",0);\n    bool mobileBoundedRoleUsage = mpContext->configuration().getValueAs<bool>(\"TransportNetwork/search/options/role-usage/mobile/bounded\",false);\n    int immobileRoleUsageBoundOffset = mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/role-usage/immobile/bound-offset\",0);\n    bool immobileBoundedRoleUsage = mpContext->configuration().getValueAs<bool>(\"TransportNetwork/search/options/role-usage/immobile/bounded\",false);\n\n    // Role distribution\n    Gecode::Matrix<Gecode::IntVarArray> resourceDistribution(mModelUsage, /*width --> col*/ mpMission->getAvailableResources().size(), /*height --> row*/ mResourceRequirements.size());\n    Gecode::Matrix<Gecode::IntVarArray> roleDistribution(mRoleUsage, /*width --> col*/ mRoles.size(), /*height --> row*/ mResourceRequirements.size());\n    {\n        Gecode::IntVarArgs mobileModelBounds;\n        Gecode::IntVarArgs immobileModelBounds;\n\n        Gecode::IntVarArgs mobileModelMaxOffsets;\n        Gecode::IntVarArgs immobileModelMaxOffsets;\n\n        const IRIList& availableModels = mpMission->getModels();\n        const moreorg::ModelPool& modelPool = mpMission->getAvailableResources();\n\n        // Sum of all models' instances (role) has to correspond to the model count\n        for(size_t modelIndex = 0; modelIndex < availableModels.size(); ++modelIndex)\n        {\n            const IRI& model = availableModels[modelIndex];\n\n            Gecode::IntVar mobileModelBound(*this,0, mobileRoleUsageBoundOffset);\n            mobileModelBounds << mobileModelBound;\n            Gecode::IntVar immobileModelBound(*this,0, immobileRoleUsageBoundOffset);\n            immobileModelBounds << immobileModelBound;\n\n            using namespace moreorg::facades;\n            Robot robot = Robot::getInstance(model, mpContext->ask());\n            bool isMobile = robot.isMobile();\n            uint32_t maxCardinality = modelPool.at(model);\n\n            // Enforce bound per requirement\n            for(uint32_t requirementIndex = 0; requirementIndex < mResourceRequirements.size(); ++requirementIndex)\n            {\n                Gecode::IntVar modelCount = resourceDistribution(modelIndex,requirementIndex);\n                Gecode::IntVarArgs args;\n                for(uint32_t roleIndex = 0; roleIndex < mRoles.size(); ++roleIndex)\n                {\n                    if(isRoleForModel(roleIndex, modelIndex))\n                    {\n                        Gecode::IntVar roleActivation = roleDistribution(roleIndex, requirementIndex);\n                        args << roleActivation;\n                    }\n                }\n                Gecode::IntVar z(*this, 0, maxCardinality);\n                rel(*this, z == sum(args) );\n\n                // The following constraint allow to relax the least commitment\n                // and allows to relax the number of immobile / mobile agent\n                // assigned\n                if(forceMinimumRoleUsage)\n                {\n                    // This tries to solve the problem with the fewest instances\n                    // possible\n                    rel(*this, z == modelCount);\n                } else\n                {\n                    rel(*this, z >= modelCount);\n                    // This tries to bound the problem using the number of\n                    // available instances\n                    LOG_DEBUG_S << \"Constraint general role usage: \" << std::endl\n                        << \"     \" << model.toString() << \"# <= \" << maxCardinality;\n                    // Limit mobile / immobile systems\n                    if(isMobile)\n                    {\n\n                        if(mobileBoundedRoleUsage)\n                        {\n                            // This tries to bound the problem using the number of\n                            // available instances\n                            rel(*this, z <= (modelCount + mobileModelBound) );\n                            LOG_DEBUG_S << \"Constraint mobile role usage: \" << std::endl\n                                << \"     \" << model.toString() << \"#: \" << modelCount << \"<= x <= \" << modelCount << \"+ \" << mobileRoleUsageBoundOffset;\n                        } else {\n                            rel(*this, z == modelCount);\n                        }\n                    } else\n                    { // not mobile\n                        if(immobileBoundedRoleUsage)\n                        {\n                            // This tries to bound the problem using the number of\n                            // available instances\n                            rel(*this, z <= (modelCount + immobileModelBound) );\n                            LOG_DEBUG_S << \"Constraint immobile role usage: \" << std::endl\n                                << \"     \" << model.toString() << \"#: \" << modelCount << \"<= x <= \" << modelCount << \"+ \" << immobileRoleUsageBoundOffset;\n                        } else {\n                            rel(*this, z == modelCount);\n                        }\n                    }\n                }\n            }\n\n            Gecode::IntVar mobileModelOffsetMax(*this,0, mobileRoleUsageBoundOffset);\n            Gecode::max(*this, mobileModelBounds, mobileModelOffsetMax);\n            mobileModelMaxOffsets << mobileModelOffsetMax;\n\n            Gecode::IntVar immobileModelOffsetMax(*this,0, immobileRoleUsageBoundOffset);\n            Gecode::max(*this, immobileModelBounds, immobileModelOffsetMax);\n            immobileModelMaxOffsets << immobileModelOffsetMax;\n        }\n\n        if(!forceMinimumRoleUsage)\n        {\n            // Making sure the total offset of model instances does not exceed the\n            // given bound, i.e. if model bound is 2, that means only two\n            // additional model instances will be available\n            if(mobileBoundedRoleUsage)\n            {\n                rel(*this, sum(mobileModelMaxOffsets) <= mobileRoleUsageBoundOffset);\n            }\n            if(immobileBoundedRoleUsage)\n            {\n                rel(*this, sum(immobileModelMaxOffsets) <= immobileRoleUsageBoundOffset);\n            }\n        }\n    }\n}\n\nvoid TransportNetwork::applyMissionConstraints()\n{\n    for(const Constraint::Ptr& constraint : mpMission->getConstraints())\n    {\n        MissionConstraintManager::apply(constraint, *this);\n    }\n}\n\nvoid TransportNetwork::applyExtraConstraints()\n{\n    for(const Constraint::Ptr& constraint : mConstraints)\n    {\n        MissionConstraintManager::apply(constraint, *this);\n    }\n}\n\nvoid TransportNetwork::applyAccessConstraints(ListOfAdjacencyLists& timelines,\n        size_t numberOfTimepoints,\n        size_t numberOfLocations,\n        const Role::List& roles)\n{\n    // Location access contraints -- currently restricted to a single model\n    using namespace moreorg;\n    typedef std::map<symbols::constants::Location::Ptr, std::pair<ModelPool, ModelPool> >\n        LocationConstraints;\n    LocationConstraints locationMinMax;\n\n    Constraint::PtrList constraints = mpMission->getConstraints();\n    constraints.insert(constraints.begin(),mConstraints.begin(), mConstraints.end());\n\n    for(const Constraint::Ptr& constraint : constraints)\n    {\n        using namespace templ::constraints;\n        if(constraint->getCategory() == Constraint::MODEL)\n        {\n            ModelConstraint::Ptr modelConstraint =\n                dynamic_pointer_cast<ModelConstraint>(constraint);\n\n            ModelConstraint::Type modelConstraintType =\n                modelConstraint->getModelConstraintType();\n\n            if(modelConstraintType != ModelConstraint::MIN_ACCESS\n                    && modelConstraintType != ModelConstraint::MAX_ACCESS)\n            {\n                continue;\n            }\n\n            bool isGeneralAccessConstraint = false;\n            std::pair<ModelPool, ModelPool> minMax;\n            symbols::constants::Location::Ptr affectedLocation;\n\n            for(const SpaceTime::SpaceIntervalTuple& t :\n                    modelConstraint->getSpaceIntervalTuples())\n            {\n                if(SpaceTime::isFullMissionInterval(t.second()))\n                {\n                    isGeneralAccessConstraint = true;\n                    affectedLocation = t.first();\n                    LocationConstraints::const_iterator cit =\n                        locationMinMax.find(affectedLocation);\n                    if(cit != locationMinMax.end())\n                    {\n                        minMax = cit->second;\n                        break;\n                    }\n                }\n            }\n            if(!isGeneralAccessConstraint)\n            {\n                // this is not covers\n                continue;\n            }\n\n            using namespace templ::constraints;\n            const IRI& model = modelConstraint->getModel();\n\n            // min and max entries are maintained in parallel\n            if(minMax.first.count(model) == 0)\n            {\n                minMax.first[model] = 0;\n                minMax.second[model] = std::numeric_limits<size_t>::max();\n            }\n            size_t& min = minMax.first[model];\n            size_t& max = minMax.second[model];\n\n            switch(modelConstraint->getModelConstraintType())\n            {\n                case ModelConstraint::MIN_ACCESS:\n                    min = std::max(min, static_cast<size_t>(modelConstraint->getValue()));\n                    break;\n                case ModelConstraint::MAX_ACCESS:\n                    max = std::min(max, static_cast<size_t>(modelConstraint->getValue()));\n                    break;\n                default:\n                    continue;\n            }\n            // update the set of constraints\n            locationMinMax[affectedLocation] = minMax;\n        } // end for constraints\n    }\n\n    for(const LocationConstraints::value_type& locationConstraint : locationMinMax)\n    {\n        ListOfAdjacencyLists selectedTimelines;\n        const symbols::constants::Location::Ptr& location = locationConstraint.first;\n        const ModelPool& minPool = locationConstraint.second.first;\n        const ModelPool& maxPool = locationConstraint.second.second;\n\n        // handle location constraints for each model\n        for(const ModelPool::value_type& v : minPool)\n        {\n            // Get all models that are a subclass of the given\n            const IRI& model = v.first;\n            for(size_t i = 0; i < roles.size(); ++i)\n            {\n                if(mpContext->ask().ontology().isSubClassOf( roles[i].getModel(), model ))\n                {\n                    selectedTimelines.push_back(timelines[i]);\n                }\n            }\n\n            symbols::constants::Location::PtrList::const_iterator cit =\n                std::find(mpContext->locations().begin(), mpContext->locations().end(), location);\n            if(cit == mpContext->locations().end())\n            {\n                throw std::runtime_error(\"templ::solvers::csp::TransportNetwork::applyAccessConstraints:\"\n                            \" failed to find location \" + location->toString());\n            }\n            size_t locationIdx = cit - mpContext->locations().begin();\n            size_t min = minPool.at(model);\n            size_t max = maxPool.at(model);\n\n            propagators::restrictInEdges(*this,\n                    selectedTimelines,\n                    numberOfTimepoints,\n                    numberOfLocations,\n                    locationIdx,\n                    min,\n                    max,\n                    location->toString() + \"-\" + model.toString());\n        }\n    }\n}\n\nvoid TransportNetwork::enforceUnaryResourceUsage()\n{\n    // Role distribution\n    Gecode::Matrix<Gecode::IntVarArray> roleDistribution(mRoleUsage, /*width --> col*/ mRoles.size(), /*height --> row*/ mResourceRequirements.size());\n\n    // Set of available models: mModelPool\n    // Make sure the assignments are within resource bounds for concurrent requirements\n    temporal::point_algebra::TimePointComparator tpc(mpQualitativeTemporalConstraintNetwork);\n    std::vector< std::vector<FluentTimeResource> > concurrentRequirements =\n        FluentTimeResource::getMutualExclusive(mResourceRequirements, tpc);\n\n    for(const FluentTimeResource::List& concurrentFluents : concurrentRequirements)\n    {\n        if(mRoles.size() < concurrentFluents.size())\n        {\n            std::stringstream ss;\n            ss << \"The number for agent instances (\" << mRoles.size() << \") is too low,\"\n               << \" to resolve the concurrent requirements (\"\n               << concurrentFluents.size() << \") \" << std::endl;\n\n            throw std::runtime_error(\"templ::solvers::csp::TransportNetwork::enforceUnaryResourceUsage: \"\n                        + ss.str());\n        }\n\n        for(size_t roleIndex = 0; roleIndex < mRoles.size(); ++roleIndex)\n        {\n            Gecode::IntVarArgs args;\n            for(const FluentTimeResource& fts : concurrentFluents)\n            {\n                size_t row = FluentTimeResource::getIndex(mResourceRequirements, fts);\n                Gecode::IntVar v = roleDistribution(roleIndex, row);\n                args << v;\n            }\n            // A role can only be available for one of the concurrent\n            // constraints\n            rel(*this, sum(args) <= 1);\n        }\n    }\n}\n\nGecode::Symmetries TransportNetwork::identifySymmetries()\n{\n    Gecode::Matrix<Gecode::IntVarArray> roleDistribution(mRoleUsage, /*width --> col*/ mRoles.size(), /*height --> row*/ mResourceRequirements.size());\n\n    Gecode::Symmetries symmetries;\n    // define interchangeable columns for roles of the same model type\n    for(const IRI& currentModel : mpMission->getModels())\n    {\n        LOG_INFO_S << \"Starting symmetry column for model: \" << currentModel.toString();\n        Gecode::IntVarArgs sameModelColumns;\n        for(int c = 0; c < roleDistribution.width(); ++c)\n        {\n            if( mRoles[c].getModel() == currentModel)\n            {\n                LOG_DEBUG_S << \"Adding column of \" << mRoles[c].toString() << \" for symmetry\";\n                sameModelColumns << roleDistribution.col(c);\n            }\n        }\n        symmetries << VariableSequenceSymmetry(sameModelColumns, roleDistribution.height());\n    }\n    return symmetries;\n}\n\nTransportNetwork::TransportNetwork(TransportNetwork& other)\n    : Gecode::Space(other)\n    , mpMission(other.mpMission)\n    , mpContext(other.mpContext)\n    , mResourceRequirements(other.mResourceRequirements)\n    , mTemporalConstraintNetwork(other.mTemporalConstraintNetwork)\n    , mTimepoints(other.mTimepoints)\n    , mpQualitativeTemporalConstraintNetwork(other.mpQualitativeTemporalConstraintNetwork)\n    , mRoles(other.mRoles)\n    , mActiveRoles(other.mActiveRoles)\n    , mActiveRoleList(other.mActiveRoleList)\n    , mMinRequiredTimelines(other.mMinRequiredTimelines)\n    , mSupplyDemand(other.mSupplyDemand)\n    , mMinCostFlowSolution(other.mMinCostFlowSolution)\n    , mMinCostFlowFlaws(other.mMinCostFlowFlaws)\n    , mFlawResolution(other.mFlawResolution)\n    , mUseMasterSlave(other.mUseMasterSlave)\n    , mpCurrentMaster(other.mpCurrentMaster)\n    , mSolutionAnalysis(other.mSolutionAnalysis)\n{\n    breakpointStart()\n        << \"Space \" << std::endl\n        << \"    size: \" << sizeof(TransportNetwork) << std::endl\n        << \"Mission: \" << std::endl\n        << \"    use count: \" << mpMission.use_count() << std::endl\n        << \"QualitativeTemporalConstraintNetwork\" << std::endl\n        << \"    use count: \" << mpQualitativeTemporalConstraintNetwork.use_count() << std::endl;\n    breakpointEnd();\n\n    assert( mpMission->getOrganizationModel() );\n    assert(!mpContext->intervals().empty());\n    mModelUsage.update(*this, other.mModelUsage);\n    mRoleUsage.update(*this, other.mRoleUsage);\n    mCost.update(*this, other.mCost);\n    mNumberOfFlaws.update(*this, other.mNumberOfFlaws);\n    mQualitativeTimepoints.update(*this, other.mQualitativeTimepoints);\n\n    for(size_t i = 0; i < other.mTimelines.size(); ++i)\n    {\n        AdjacencyList array;\n        mTimelines.push_back(array);\n        mTimelines[i].update(*this, other.mTimelines[i]);\n    }\n\n    //mCapacities.update(*this, other.mCapacities);\n}\n\nGecode::Space* TransportNetwork::copy()\n{\n    return new TransportNetwork(*this);\n}\n\nstd::vector<TransportNetwork::Solution> TransportNetwork::solve(const templ::Mission::Ptr& mission, uint32_t minNumberOfSolutions, const qxcfg::Configuration& configuration)\n{\n    SolutionList solutions;\n    mission->prepareForPlanning();\n\n    assert(mission->getOrganizationModel());\n    assert(!mission->getTimeIntervals().empty());\n\n    /// Allow to log the final results into a csv file\n    CSVLogger csvLogger({\"session\",\n            \"alpha\",\n            \"beta\",\n            \"sigma\",\n            \"efficacy\",\n            \"efficiency\",\n            \"safety\",\n            \"timehorizon\",\n            \"travel-distance\",\n            \"reconfiguration-cost\",\n            \"overall-runtime\",\n            \"solution-runtime\",\n            \"solution-runtime-mean\",\n            \"solution-runtime-stdev\",\n            \"solution-found\",\n            \"solution-stopped\",\n            \"propagate\",\n            \"fail\",\n            \"node\",\n            \"depth\",\n            \"restart\",\n            \"nogood\",\n            \"flaws\",\n            \"cost\"});\n\n    std::string baseDir = configuration.getValue(\"TransportNetwork/logging/basedir\",\"/tmp\");\n    mission->getLogger()->setBaseDirectory(baseDir);\n\n    if( configuration.getValueAs<bool>(\"TransportNetwork/use-transfer-location\"))\n    {\n        mission->enableTransferLocation();\n    }\n\n    /// Check if interactive mode should be used during the solution process\n    TransportNetwork::msInteractive = configuration.getValueAs<bool>(\"TransportNetwork/search/interactive\",false);\n\n    TransportNetwork* distribution = new TransportNetwork(mission, configuration);\n    distribution->mUseMasterSlave = configuration.getValueAs<bool>(\"TransportNetwork/search/options/master-slave\",false);\n\n    // Search options: Gecode 9.3.1\n    // threads (double) number of parallel threads to use\n    // c_d (unsigned int) commit recomputation distance\n    // a_d                adaptive recomputation distance\n    // clone (bool)  whether engine uses a clone when created\n    // d_l           discrepancy limit when using LDS\n    // nogoods_limit depth limit for no-good generation\n    // assets        number of assets in a portfolio\n    // share_rbs     (bool) whether AFC is shared between restarts\n    // share_pbs     (bool) whether AFC is shared between assets\n    // stop                 Stop object   (NULL if none)\n    // cutoff               cutoff object (NULL if none)\n    int threads = distribution->mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/threads\",1);\n\n    int cutoff = distribution->mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/cutoff\",10);\n    int nogoods_limit = distribution->mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/nogoods_limit\",128);\n    int epochTimeoutInS = distribution->mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/epoch_timeout_in_s\",180000);\n    int abortTimeoutInS = distribution->mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/total_timeout_in_s\",600000);\n\n    Gecode::Search::Options options;\n    options.threads = threads;\n    // p 172 \"the value of nogoods_limit described to which depth limit\n    // no-goods should be extracted from the path of the search tree\n    // maintained by the search engine\n    options.nogoods_limit = nogoods_limit;\n    // recomputation distance\n    options.c_d = distribution->mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/computation_distance\", options.c_d);\n    // adaptive recomputation distance\n    options.a_d = distribution->mpContext->configuration().getValueAs<int>(\"TransportNetwork/search/options/adaptive_computation_distance\", options.a_d);\n    // default failure cutoff\n    // options.fail\n\n    base::Time allStart = base::Time::now();\n    bool stop = false;\n    int numberOfEpochs = 0;\n    while(!stop)\n    {\n        ++numberOfEpochs;\n        //Cutoff::geometric: s*b^i, for i = 0,1,2,3,4\n        // when the corresponding number of failure has been reached\n        // restart and continue\n        options.cutoff = Gecode::Search::Cutoff::geometric(cutoff,2);\n        options.stop = Gecode::Search::Stop::time(epochTimeoutInS*1000.0);\n        Gecode::RBS< TransportNetwork, Gecode::DFS > searchEngine(distribution, options);\n\n        //Gecode::TemplRBS< TransportNetwork, Gecode::DFS > searchEngine(distribution, options);\n\n        TransportNetwork* best = NULL;\n        size_t solutionCount = 0;\n        int i = 0;\n        base::Time start = base::Time::now();\n        base::Time allElapsed;\n        base::Time elapsed;\n        numeric::Stats<double> stats;\n        while(TransportNetwork* current = searchEngine.next())\n        {\n            allElapsed = (base::Time::now() - allStart);\n            elapsed = (base::Time::now() - start);\n            stats.update(elapsed.toSeconds());\n            delete best;\n            best = current;\n\n            using namespace moreorg;\n\n            LOG_INFO_S << \"#\" << i << \"/\" << minNumberOfSolutions << \" solution found:\" << current->toString();\n            std::cout << \"Solution found:\" << std::endl;\n            std::cout << \"    # session id \" << current->mpMission->getLogger()->getSessionId() << std::endl;\n            std::cout << \"    # flaws: \" << current->mNumberOfFlaws.val() << std::endl;\n            std::cout << \"    # cost: \" << current->mCost.val() << std::endl;\n            std::cout << std::endl;\n\n            csvLogger.addToRow(current->mpMission->getLogger()->getSessionId(),\"session\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getAlpha(), \"alpha\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getBeta(), \"beta\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getSigma(), \"sigma\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getEfficacy(), \"efficacy\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getEfficiency(), \"efficiency\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getSafety(), \"safety\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getTimeHorizon(), \"timehorizon\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getTravelledDistance(),\"travel-distance\");\n            csvLogger.addToRow(current->mSolutionAnalysis.getReconfigurationCost(),\"reconfiguration-cost\");\n            csvLogger.addToRow(allElapsed.toSeconds(), \"overall-runtime\");\n            csvLogger.addToRow(elapsed.toSeconds(), \"solution-runtime\");\n            csvLogger.addToRow(stats.mean(), \"solution-runtime-mean\");\n            csvLogger.addToRow(stats.stdev(), \"solution-runtime-stdev\");\n            csvLogger.addToRow(searchEngine.stopped(), \"solution-stopped\");\n            csvLogger.addToRow(searchEngine.statistics().propagate, \"propagate\");\n            csvLogger.addToRow(searchEngine.statistics().fail, \"fail\");\n            csvLogger.addToRow(searchEngine.statistics().node, \"node\");\n            csvLogger.addToRow(searchEngine.statistics().depth, \"depth\");\n            csvLogger.addToRow(searchEngine.statistics().restart, \"restart\");\n            csvLogger.addToRow(searchEngine.statistics().nogood, \"nogood\");\n            csvLogger.addToRow(1.0, \"solution-found\");\n            csvLogger.addToRow(best->mMinCostFlowFlaws.size(), \"flaws\");\n            csvLogger.addToRow(best->cost().val(), \"cost\");\n            csvLogger.commitRow();\n\n            std::string filename =\n                mission->getLogger()->getBasePath() + \"search-statistics.log\";\n            std::cout << \"Saving stats in: \" << filename << std::endl;\n            csvLogger.save(filename);\n\n            Solution solution = current->getSolution();\n            saveSolution(solution, mission);\n            // TODO: use serialization to filesystem for later retrieval\n            solutions.push_back(solution);\n            ++solutionCount;\n\n            if(minNumberOfSolutions >= 0)\n            {\n                if(solutionCount >= minNumberOfSolutions)\n                {\n                    LOG_INFO_S << \"Found minimum required number of solutions: \" << solutions.size();\n                    stop = true;\n                    break;\n                }\n            }\n\n            current->mpMission->getLogger()->incrementSessionId();\n            start = base::Time::now();\n        }\n\n        std::cout << \"Solution Search (epoch: \" << numberOfEpochs << \")\" << std::endl;\n        std::cout << \"    was stopped (e.g. timeout): \";\n        if(searchEngine.stopped())\n        {\n            std::cout << \" yes\" << std::endl;\n        } else {\n            std::cout << \" no\" << std::endl;\n        }\n        std::cout << \"    found # solutions: \" << solutions.size() << std::endl;\n        std::cout << \"    minimum # requested: \" << minNumberOfSolutions << std::endl;\n\n        if((base::Time::now() - allStart).toSeconds() >= abortTimeoutInS)\n        {\n            stop = true;\n        }\n    } // end while all\n\n    delete distribution;\n    return solutions;\n}\n\nsolvers::Session::Ptr TransportNetwork::run(const templ::Mission::Ptr& mission, uint32_t minNumberOfSolutions, const qxcfg::Configuration& configuration)\n{\n    Session::Ptr session = make_shared<Session>(mission);\n    SolutionList solutionList = TransportNetwork::solve(mission, minNumberOfSolutions, configuration);\n\n    solvers::Solution::List solutions;\n    session->setSolutions(solutions);\n    return session;\n}\n\nvoid TransportNetwork::addConstraint(const Constraint::Ptr& constraint, TransportNetwork& network)\n{\n    mConstraints.push_back(constraint);\n    MissionConstraintManager::apply(constraint, network);\n}\n\nConstraint::PtrList TransportNetwork::getAssignmentsAsConstraints() const\n{\n    using namespace moreorg;\n    Constraint::PtrList constraints;\n    Gecode::Matrix<Gecode::IntVarArray> roleDistribution(mRoleUsage, /*width --> col*/ mRoles.size(), /*height --> row*/ mResourceRequirements.size());\n\n\n    // Min resource model constraints\n    for(size_t f = 0; f < mResourceRequirements.size(); ++f)\n    {\n        const FluentTimeResource& ftr = mResourceRequirements[f];\n\n        ModelPool modelPool = currentMinModelAssignment(ftr);\n        for(const ModelPool::value_type& v : modelPool)\n        {\n            constraints::ModelConstraint::Ptr constraint = make_shared<constraints::ModelConstraint>(\n                    constraints::ModelConstraint::MIN,\n                    v.first,\n                    MissionConstraintManager::mapToSpaceTime(ftr),\n                    v.second\n                    );\n            constraints.push_back(constraint);\n        }\n    }\n\n    for(size_t r = 0; r < mRoles.size(); ++r)\n    {\n        FluentTimeResource::List presentAt;\n        for(size_t f = 0; f < mResourceRequirements.size(); ++f)\n        {\n            Gecode::IntVar var = roleDistribution(r,f);\n            if(var.assigned() && var.val() == 1)\n            {\n                presentAt.push_back( mResourceRequirements[f] );\n            }\n        }\n\n        if(!presentAt.empty())\n        {\n            constraints::ModelConstraint::Ptr constraint = make_shared<constraints::ModelConstraint>(\n                    constraints::ModelConstraint::MIN_EQUAL,\n                    mRoles[r].getModel(),\n                    MissionConstraintManager::mapToSpaceTime( presentAt ),\n                    1\n                    );\n            constraints.push_back(constraint);\n        }\n    }\n\n    return constraints;\n\n}\n\nMission::Ptr TransportNetwork::getAugmentedMission() const\n{\n    Mission::Ptr augmentedMission = make_shared<Mission>(*mpMission);\n    Constraint::PtrList constraints = getAssignmentsAsConstraints();\n    for(Constraint::Ptr& constraint : constraints)\n    {\n        augmentedMission->addConstraint(constraint);\n    }\n    return augmentedMission;\n}\n\nvoid TransportNetwork::appendToTupleSet(Gecode::TupleSet& tupleSet, const moreorg::ModelPool::Set& combinations) const\n{\n    std::set< std::vector<uint32_t> > csp = utils::Converter::toCSP(mpMission, combinations);\n    std::set< std::vector<uint32_t> >::const_iterator cit = csp.begin();\n\n    for(; cit != csp.end(); ++cit)\n    {\n        Gecode::IntArgs args;\n\n        const std::vector<uint32_t>& tuple = *cit;\n        std::vector<uint32_t>::const_iterator tit = tuple.begin();\n        for(; tit != tuple.end(); ++tit)\n        {\n            args << *tit;\n        }\n        LOG_DEBUG_S << \"TupleSet: intargs: \" << args;\n\n        tupleSet.add( args );\n    }\n}\n\nsize_t TransportNetwork::getResourceModelIndex(const IRI& model) const\n{\n    const IRIList& availableModels = mpMission->getModels();\n    IRIList::const_iterator cit =\n        std::find(availableModels.begin(), availableModels.end(), model);\n    if(cit != availableModels.end())\n    {\n        int index = cit - availableModels.begin();\n        assert(index >= 0);\n        return (size_t) index;\n    }\n\n    throw std::runtime_error(\"templ::solvers::csp::TransportNetwork::getResourceModelIndex: could not find model index for '\" + model.toString() + \"'\");\n}\n\nconst IRI& TransportNetwork::getResourceModelFromIndex(size_t index) const\n{\n    const IRIList& availableModels = mpMission->getModels();\n    if(index < availableModels.size())\n    {\n        return availableModels.at(index);\n    }\n    throw std::invalid_argument(\"templ::solvers::csp::TransportNetwork::getResourceModelIndex: index is out of bounds\");\n}\n\nsize_t TransportNetwork::getResourceModelMaxCardinality(size_t index) const\n{\n    const moreorg::ModelPool& modelPool = mpMission->getAvailableResources();\n    moreorg::ModelPool::const_iterator cit = modelPool.find(getResourceModelFromIndex(index));\n    if(cit != modelPool.end())\n    {\n        return cit->second;\n    }\n    throw std::invalid_argument(\"templ::solvers::csp::TransportNetwork::getResourceModelMaxCardinality: model not found\");\n}\n\nbool TransportNetwork::isRoleForModel(uint32_t roleIndex, uint32_t modelIndex) const\n{\n    return mRoles.at(roleIndex).getModel() == mpMission->getModels().at(modelIndex);\n}\n\nstd::vector<uint32_t> TransportNetwork::computeActiveRoles() const\n{\n    std::vector<uint32_t> activeRoles;\n    // Identify active roles\n    Gecode::Matrix<Gecode::IntVarArray> roleDistribution(mRoleUsage, /*width --> col*/ mRoles.size(), /*height --> row*/ mResourceRequirements.size());\n    for(size_t r = 0; r < mRoles.size(); ++r)\n    {\n        size_t requirementCount = 0;\n        for(size_t i = 0; i < mResourceRequirements.size(); ++i)\n        {\n            Gecode::IntVar var = roleDistribution(r,i);\n            if(!var.assigned())\n            {\n                throw std::runtime_error(\"templ::solvers::csp::TransportNetwork::postRoleAssignments: value has not been assigned for role: '\" + mRoles[r].toString() + \"'\");\n            }\n            Gecode::IntVarValues v(var);\n            if(v.val() == 1)\n            {\n                ++requirementCount;\n            }\n\n            // Only if the resource is required at more than its current start\n            // position, we consider it to be active\n            if(requirementCount > 1)\n            {\n                activeRoles.push_back(r);\n                break;\n            }\n        }\n    }\n    return activeRoles;\n}\n\nmoreorg::ModelPool TransportNetwork::currentMinModelAssignment(const FluentTimeResource& ftr) const\n{\n    moreorg::ModelPool modelPool;\n    Gecode::Matrix<Gecode::IntVarArray> roleDistribution(mRoleUsage, /*width --> col*/ mRoles.size(), /*height --> row*/ mResourceRequirements.size());\n\n    size_t ftrIdx = FluentTimeResource::getIndex(mResourceRequirements, ftr);\n\n    for(size_t r = 0; r < mRoles.size(); ++r)\n    {\n        Gecode::IntVar var = roleDistribution(r,ftrIdx);\n        if(var.assigned() && var.val() == 1)\n        {\n            modelPool[ mRoles[r].getModel() ] += 1;\n        }\n    }\n    return modelPool;\n}\n\nvoid TransportNetwork::doPostTemporalConstraints(Gecode::Space& home)\n{\n    static_cast<TransportNetwork&>(home).postTemporalConstraints();\n}\n\nvoid TransportNetwork::postTemporalConstraints()\n{\n    (void) status();\n    // Update temporal constraint network after the solution has been computed\n    mpQualitativeTemporalConstraintNetwork = mTemporalConstraintNetwork.translate(mQualitativeTimepoints);\n    temporal::point_algebra::TimePointComparator tcp(mpQualitativeTemporalConstraintNetwork);\n\n    // Sort the timepoints according\n    TemporalConstraintNetworkBase::sort(*mpQualitativeTemporalConstraintNetwork, mTimepoints);\n\n    mResourceRequirements = Mission::getResourceRequirements(mpMission);\n    if(mResourceRequirements.empty())\n    {\n        throw std::invalid_argument(\"templ::solvers::csp::TransportNetwork: no resource requirements given\");\n    }\n    breakpointStart()\n        << \"Requirements:\" << std::endl\n        << FluentTimeResource::toString(mResourceRequirements, 4)\n        << \"Timepoints: \" << mTimepoints << std::endl\n        << mQualitativeTimepoints << std::endl;\n    breakpointEnd();\n\n    // update timepoint comparator for intervals\n    FluentTimeResource::updateIndices(mResourceRequirements,\n            mpContext->locations());\n\n    mModelUsage = Gecode::IntVarArray(*this,\n            /*# of models*/ mpMission->getAvailableResources().size()*\n            /*# of fluent time services*/mResourceRequirements.size(), 0,\n            mpMission->getAvailableResources().getMaxResourceCount());\n\n    mRoleUsage = Gecode::IntVarArray(*this,\n            /*width --> col */ mpMission->getRoles().size()* /*height --> row*/ mResourceRequirements.size(),\n            0, 1);// Domain 0,1 to represent activation\n\n    Gecode::Matrix<Gecode::IntVarArray> resourceDistribution(mModelUsage, /*width --> col*/ mpMission->getAvailableResources().size(), /*height --> row*/ mResourceRequirements.size());\n\n    // Limit roles to resource availability\n    initializeRoleDistributionConstraints();\n\n    // Mission additional constraints\n    applyMissionConstraints();\n    applyExtraConstraints();\n\n    // (C) Avoid computation of solutions that are redunant\n    // Gecode documentation says however in 8.10.2 that \"Symmetry breaking by\n    // LDSB is not guaranteed to be complete. That is, a search may still return\n    // two distinct solutions that are symmetric.\"\n    //\n    Gecode::Symmetries symmetries = identifySymmetries();\n\n    // For each requirement add the min/max and extensional constraints\n    // for all overlapping requirements create maximum resource constraints\n    Gecode::branch(*this, &TransportNetwork::doPostMinMaxConstraints);\n\n    // Allow only composite agents, i.e. combinations of models, that provide a particular functionality\n    Gecode::branch(*this, &TransportNetwork::doPostExtensionalConstraints);\n\n    Gecode::IntAFC modelUsageAfc(*this, mModelUsage, 0.99);\n    double modelAfcDecay = mpContext->configuration().getValueAs<double>(\"TransportNetwork/search/options/model-usage/afc-decay\",0.95);\n    modelUsageAfc.decay(*this, modelAfcDecay);\n    branch(*this, mModelUsage, Gecode::INT_VAR_AFC_MIN(modelUsageAfc), Gecode::INT_VAL_SPLIT_MIN());\n    //Gecode::Gist::stopBranch(*this);\n\n    Gecode::Rnd modelUsageRnd;\n    modelUsageRnd.hw();\n    branch(*this, mModelUsage, Gecode::INT_VAR_AFC_MIN(modelUsageAfc), Gecode::INT_VAL_RND(modelUsageRnd));\n\n    branch(*this, mModelUsage, Gecode::tiebreak(Gecode::INT_VAR_DEGREE_MAX(),\n                                Gecode::INT_VAR_SIZE_MIN()),\n                                Gecode::INT_VAL_SPLIT_MIN());\n    //Gecode::Gist::stopBranch(*this);\n\n    // Regarding the use of INT_VALUES_MIN() and INT_VALUES_MAX(): \"This is\n    // typically a poor choice, as none of the alternatives can benefit from\n    // propagation that arises when other values of the same variable are tried.\n    // These branchings exist for instructional purposes\" p.123 Tip 8.2\n    // variable which is unassigned and assigned the smallest value\n    //branch(*this, mRoleUsage, Gecode::INT_VAR_NONE(), Gecode::INT_VAL_MIN(), symmetries);\n    // variable with the smallest domain size first, and assign the smallest\n    // value of the selected variable\n    //branch(*this, mRoleUsage, Gecode::INT_VAR_SIZE_MAX(), Gecode::INT_VAL_MIN(), symmetries);\n    //branch(*this, mRoleUsage, Gecode::INT_VAR_MIN_MIN(), Gecode::INT_VAL_MIN(), symmetries);\n\n    Gecode::IntAFC roleUsageAfc(*this, mRoleUsage, 0.99);\n    double roleAfcDecay = mpContext->configuration().getValueAs<double>(\"TransportNetwork/search/options/role-usage/afc-decay\",0.95);\n    roleUsageAfc.decay(*this, roleAfcDecay);\n    //branch(*this, mRoleUsage, Gecode::INT_VAR_AFC_MIN(roleUsageAfc), Gecode::INT_VAL_SPLIT_MIN());\n\n    Gecode::Rnd rnd;\n    rnd.hw();\n    branch(*this, mRoleUsage, Gecode::INT_VAR_AFC_MIN(roleUsageAfc), Gecode::INT_VAL_RND(rnd), symmetries);\n    branch(*this, mRoleUsage, Gecode::INT_VAR_RND(rnd), Gecode::INT_VAL_RND(rnd), symmetries);\n    branch(*this, mRoleUsage, Gecode::tiebreak(Gecode::INT_VAR_DEGREE_MAX(),\n                                Gecode::INT_VAR_SIZE_MIN()),\n                                Gecode::INT_VAL_SPLIT_MIN());\n\n    //Gecode::Gist::stopBranch(*this);\n    // see 8.14 Executing code between branchers\n    Gecode::branch(*this, &TransportNetwork::doPostRoleAssignments);\n\n    //Gecode::Gist::Print<TransportNetwork> p(\"Print solution\");\n    //Gecode::Gist::Options options;\n    //options.threads = 1;\n    //Gecode::Search::Cutoff * c = Gecode::Search::Cutoff::constant(2);\n    //options.cutoff = c;\n    //options.inspect.click(&p);\n    ////Gecode::Gist::bab(this, o);\n    //Gecode::Gist::dfs(this, options);\n\n\n    // General resource constraints\n    //  - identify overlapping fts, limit resources for these (TODO: better\n    //    identification of overlapping requirements)\n    //\n    setUpperBoundForConcurrentRequirements();\n    // There can be only one assignment per role\n    enforceUnaryResourceUsage();\n}\n\nvoid TransportNetwork::doPostMinMaxConstraints(Gecode::Space& home)\n{\n    static_cast<TransportNetwork&>(home).initializeMinMaxConstraints();\n}\n\nvoid TransportNetwork::doPostExtensionalConstraints(Gecode::Space& home)\n{\n    static_cast<TransportNetwork&>(home).addExtensionalConstraints();\n}\n\nvoid TransportNetwork::doPostRoleAssignments(Gecode::Space& home)\n{\n    breakpoint(\"doPostRoleAssignments()\");\n    static_cast<TransportNetwork&>(home).postRoleAssignments();\n}\n\nvoid TransportNetwork::postRoleAssignments()\n{\n    (void) status();\n\n    LOG_WARN_S << \"Posting Role Assignments: request status\" << std::endl\n        << modelUsageToString() << std::endl\n        << roleUsageToString();\n\n    Gecode::Matrix<Gecode::IntVarArray> roleDistribution(mRoleUsage, /*width --> col*/ mRoles.size(), /*height --> row*/ mResourceRequirements.size());\n\n    //#############################################\n    // construct timelines\n    // ############################################\n    // 0: l0-t0: {}\n    // 1: l1-t0: {2}\n    // 2: l0-t1: {4}\n    // 3: l1-t1: {}\n    // 4: l0-t2: {..}\n    // ...\n    size_t numberOfFluents = mpContext->locations().size();\n    size_t numberOfTimepoints = mTimepoints.size();\n    size_t locationTimeSize = numberOfFluents*numberOfTimepoints;\n\n    mActiveRoles = computeActiveRoles();\n\n    LOG_INFO_S << std::endl\n        << mTimepoints << std::endl\n        << symbols::constants::Location::toString(mpContext->locations());\n\n    if(mActiveRoles.empty())\n    {\n        this->fail();\n        return;\n    }\n\n    assert(mTimelines.empty());\n\n    Role::List activeRoles;\n    std::vector<uint32_t>::const_iterator rit = mActiveRoles.begin();\n    for(; rit != mActiveRoles.end(); ++rit)\n    {\n        uint32_t roleIndex = *rit;\n        const Role& role = mRoles[roleIndex];\n        activeRoles.push_back(role);\n\n        // A timeline describes the transitions in space time for a given role\n        // A timeline is represented by an adjacency list, pointing from the current node\n        // to the next -- given some temporal constraints\n        // An empty list assignment means, there is no transition and at\n        // maximum there can be one transition\n\n        /// Initialize timelines for all roles, i.e. here the current one\n        /// Ajacencylist\n        unsigned int minCard = 0;\n        unsigned int maxCard = 1;\n        Gecode::SetVarArray timeline(*this, locationTimeSize, Gecode::IntSet::empty, Gecode::IntSet(0,locationTimeSize-1),minCard, maxCard);\n        mTimelines.push_back(timeline);\n\n        // Setup the basic constraints for the timeline\n        // i.e. only edges from one timestep to the next are allowed\n        for(size_t t = 0; t < numberOfTimepoints; ++t)\n        {\n            Gecode::IntVarArray cardinalities(*this, numberOfFluents, 0, 1);\n            for(size_t l = 0; l < numberOfFluents; ++l)\n            {\n                int idx = t*numberOfFluents + l;\n                const Gecode::SetVar& edgeActivation = timeline[idx];\n                // Use SetView to manipulate the edgeActivation in the\n                // timeline\n                Gecode::Set::SetView v(edgeActivation);\n                // http://www.gecode.org/doc-latest/reference/classGecode_1_1Set_1_1SetView.html\n                // set value to 'col' which represents the next target\n                // space-time-point\n                v.cardMin(*this, 0);\n                v.cardMax(*this, 1);\n                // exclude space-time-points outside the next step\n                v.exclude(*this, 0, (t+1)*numberOfFluents - 1);\n                v.exclude(*this, (t+2)*numberOfFluents, numberOfTimepoints*numberOfFluents);\n\n                Gecode::cardinality(*this, edgeActivation, cardinalities[l]);\n            }\n\n            // Require exactly one outgoing edge per timestep except for the last\n            // cardinality of 1 for sum of cardinalities\n            if(t < numberOfTimepoints - 1)\n            {\n                Gecode::linear(*this, cardinalities, Gecode::IRT_EQ, 1);\n            }\n        }\n        using namespace solvers::temporal;\n\n        // Link the edge activation to the role requirement, i.e. make sure that\n        // for each requirement the interval is 'activated'\n        for(uint32_t requirementIndex = 0; requirementIndex < mResourceRequirements.size(); ++requirementIndex)\n        {\n            // Check if the current role (identified by roleIndex) is required to fulfil the\n            // requirement\n            Gecode::IntVar roleRequirement = roleDistribution(roleIndex, requirementIndex);\n            if(!roleRequirement.assigned())\n            {\n                throw std::runtime_error(\"TransportNetwork: roleRequirement is not assigned\");\n            }\n            Gecode::IntVarValues var(roleRequirement);\n            // Check if role is required, i.e., does it map to the interval\n            // then the assigned value is one\n            if(var.val() == 1)\n            {\n                const FluentTimeResource& fts = mResourceRequirements[requirementIndex];\n                // index of the location is: fts.fluent\n                point_algebra::TimePoint::Ptr from = fts.getInterval().getFrom();\n                point_algebra::TimePoint::Ptr to = fts.getInterval().getTo();\n                uint32_t fromIndex = getTimepointIndex( from );\n                uint32_t toIndex = getTimepointIndex( to );\n\n                // index of the location is fts.fluent\n                size_t fluentIdx = fts.getFluentIdx();\n\n                // self edge\n                if(fromIndex == toIndex)\n                {\n                    size_t col = FluentTimeIndex::toRowOrColumnIndex(fluentIdx, fromIndex, numberOfFluents, numberOfFluents);\n                    // since (due to the existing path constraint) the incoming\n                    // edge has to have this space-timepoint as target\n                    if(fromIndex < numberOfTimepoints)\n                    {\n                        size_t offset = fromIndex*numberOfFluents;\n                        for(size_t f = 0; f < numberOfFluents; ++f)\n                        {\n                            size_t idx = offset + f;\n                            if(idx != col)\n                            {\n                                Gecode::SetVar& excludeVar = timeline[idx];\n                                Gecode::Set::SetView excludeView(excludeVar);\n                                excludeView.cardMax(*this, 0);\n                            }\n                        }\n                        // adapt all edges starting at previous timepoint to\n                        // point to location at current timepoint\n                        if(fromIndex > 0)\n                        {\n                            for(size_t f = 0; f < numberOfFluents; ++f)\n                            {\n                                size_t row = FluentTimeIndex::toRowOrColumnIndex(f, fromIndex-1, numberOfFluents, numberOfFluents);\n                                Gecode::SetVar& edgeActivation = timeline[row];\n                                Gecode::Set::SetView v(edgeActivation);\n\n                                v.intersect(*this, col,col);\n                                v.cardMax(*this, 1);\n                            }\n                        }\n                    }\n                }\n\n                // requirement is covering\n                uint32_t timeIndex = fromIndex;\n                for(; timeIndex < toIndex; ++timeIndex)\n                {\n                    // edge index:\n                    // row = timepointIdx*#ofLocations + from-location-offset\n                    // col = (timepointIdx + 1) *#ofLocations + to-location-offset\n                    //\n                    // location (offset) = row % #ofLocations\n                    // timepointIndex = (row - location(offset)) / #ofLocations\n                    size_t row = FluentTimeIndex::toRowOrColumnIndex(fluentIdx, timeIndex, numberOfFluents, numberOfTimepoints);\n                    // Always connect to the next timestep\n                    size_t col = FluentTimeIndex::toRowOrColumnIndex(fluentIdx, timeIndex + 1, numberOfFluents, numberOfFluents);\n\n\n                    LOG_INFO_S << \"EdgeActivation for col: \" << col << \", row: \" << row << \" requirement for: \" << role.toString() << \" roleRequirement: \" << roleRequirement;\n                    LOG_INFO_S << \"Translates to: \" << from->toString() << \" to \" << to->toString();\n                    LOG_INFO_S << \"Fluent: \" << mpContext->locations()[fluentIdx]->toString();\n\n\n                    // constraint between timeline and roleRequirement\n                    // if 'roleRequirement' is given, then edgeActivation = col,\n                    // else edgeActivation restricted only using standard time\n                    LOG_DEBUG_S << \"Set SetVar in col: \" << col << \" and row \" << row;\n                    Gecode::SetVar& edgeActivation = timeline[row];\n                    // Use SetView to manipulate the edgeActivation in the\n                    // timeline\n                    Gecode::Set::SetView v(edgeActivation);\n                    // http://www.gecode.org/doc-latest/reference/classGecode_1_1Set_1_1SetView.html\n                    // set value to 'col'\n                    // workaround to set {col} as target for this edge\n                    v.intersect(*this, col,col);\n                    v.cardMin(*this, 1);\n                    v.cardMax(*this, 1);\n\n                    // now limit parallel values of the edge target\n                    // since (due to the existing path constraint) the next\n                    // edge has to have this target as source\n                    //\n                    // do this only if we have not reached end of time horizon\n                    if(timeIndex < numberOfTimepoints - 1)\n                    {\n                        size_t offset = (timeIndex+1)*numberOfFluents;\n                        for(size_t f = 0; f < numberOfFluents; ++f)\n                        {\n                            size_t idx = offset + f;\n                            if(idx != col)\n                            {\n                                Gecode::SetVar& excludeVar = timeline[idx];\n                                Gecode::Set::SetView excludeView(excludeVar);\n\n                                excludeView.cardMax(*this, 0);\n                            }\n                        }\n                    } // end of time horizon\n                }\n            } // end if(v.val() == 1)\n        } // for loop requirements\n    } // for loop active roles\n\n    mActiveRoleList = activeRoles;\n    if(mActiveRoleList.empty())\n    {\n        throw\n            std::runtime_error(\"templ::solvers::csp::TransportNetwork::getTimelines: \"\n                    \"active roles could not be computed. Please ensure that all\"\n                    \"resources are assigned to a starting location\");\n    }\n    // Construct the basic timeline\n    //\n    // Map role requirements back to activation in general network\n    // requirement = location t0--tN, role-0, role-1\n    //\n    // foreach involved role\n    //     foreach requirement\n    //          from lX,t0 --> tN\n    //              request edge activation (referring to the role is active during that interval)\n    //              by >= value of the requirement( which is typically 0 or 1),\n    //              whereas activation can be 0 or 1 as well\n    //\n    // Compute a network with proper activation\n    //branch(*this, &TransportNetwork::postRoleTimelines);\n    std::vector<int32_t> supplyDemand;\n    if( mpContext->configuration().getValueAs<bool>(\"TransportNetwork/search/options/timeline-brancher/supply-demand\",false) )\n    {\n        for(uint32_t roleIdx = 0; roleIdx < mActiveRoles.size(); ++roleIdx)\n        {\n            const Role& role = mRoles[ mActiveRoles[roleIdx] ];\n            using namespace moreorg::facades;\n            Robot robot = Robot::getInstance(role.getModel(), mpContext->ask());\n            if(robot.isMobile())\n            {\n                uint32_t transportCapacity = robot.getTransportCapacity();\n                supplyDemand.push_back(transportCapacity);\n            } else {\n                uint32_t transportDemand = robot.getTransportDemand();\n                if(transportDemand == 0)\n                {\n                    throw std::invalid_argument(\"templ::solvers::csp::TransportNetwork: \" +  role.getModel().toString() + \" has\"\n                            \" a transportSupplyDemand of 0 -- must be either positive of negative integer\");\n                }\n                supplyDemand.push_back(-transportDemand);\n            }\n        }\n        mSupplyDemand = supplyDemand;\n        assert(!supplyDemand.empty());\n    }\n\n    Gecode::Rnd rnd;\n    rnd.hw();\n    double timelineAfcDecay = mpContext->configuration().getValueAs<double>(\"TransportNetwork/search/options/timeline-brancher/afc-decay\");\n    size_t numberOfLocations = mpContext->locations().size();\n    for(size_t i = 0; i < mActiveRoles.size(); ++i)\n    {\n        const Role& role = mActiveRoleList[i];\n\n        propagators::isPath(*this, mTimelines[i], role.toString(),\n                numberOfTimepoints, numberOfLocations);\n\n        // Only branch on the mobile systems\n        using namespace moreorg::facades;\n        Robot robot = Robot::getInstance(role.getModel(), mpContext->ask());\n        if(robot.isMobile())\n        {\n            Gecode::SetAFC timelineUsageAfc(*this, mTimelines[i], timelineAfcDecay);\n            branch(*this, mTimelines[i],Gecode::SET_VAR_AFC_MIN(timelineAfcDecay), Gecode::SET_VAL_RND_EXC(rnd));\n            branch(*this, mTimelines[i],Gecode::SET_VAR_RND(rnd),Gecode::SET_VAL_RND_EXC(rnd));\n            branch(*this, mTimelines[i], Gecode::tiebreak(\n                        Gecode::SET_VAR_DEGREE_MAX(),\n                        Gecode::SET_VAR_SIZE_MIN()),\n                    Gecode::SET_VAL_RND_EXC(rnd));\n        }\n    }\n\n    // Record the minimal required timeline for this role, before branching\n    // expansion of the timeline takes place\n    mMinRequiredTimelines = getTimelines();\n\n    // BEGIN LOCATION ACCESS\n    applyAccessConstraints(mTimelines,\n            numberOfTimepoints,\n            numberOfLocations,\n            mActiveRoleList);\n    // END LOCATION ACCESS\n    // Only the check whether a feasible approach is to use a heuristic\n    // to draw system by supply demand\n    //branchTimelines(*this, mTimelines, mSupplyDemand);\n    Gecode::branch(*this,&TransportNetwork::doPostMinCostFlow);\n    Gecode::Gist::stopBranch(*this);\n}\n\n\nvoid TransportNetwork::doPostMinCostFlow(Gecode::Space& home)\n{\n    static_cast<TransportNetwork&>(home).postMinCostFlow();\n}\n\nvoid TransportNetwork::postMinCostFlow()\n{\n    save();\n\n    try {\n        breakpointStart()\n            << \"Remaining flaws computation: \" << mMinCostFlowFlaws.size() << std::endl\n            << \"     cost: \" << mCost << std::endl\n            << \"     flaws: \" << mNumberOfFlaws << std::endl;\n        breakpointEnd();\n\n        std::string solver =\n            mpContext->configuration().getValueAs<std::string>(\"TransportNetwork/search/options/lp/solver\",\"CBC_SOLVER\");\n\n        namespace ga = graph_analysis::algorithms;\n        ga::LPSolver::Type solverType = ga::LPSolver::UNKNOWN_LP_SOLVER;\n        for(const std::pair<ga::LPSolver::Type, std::string>& p :\n                graph_analysis::algorithms::LPSolver::TypeTxt)\n        {\n            if(p.second == solver)\n            {\n                solverType = p.first;\n                break;\n            }\n        }\n\n        double feasibilityTimeoutInMs = 1000*mpContext->configuration().getValueAs<double>(\"TransportNetwork/search/options/coalition-feasibility/timeout_in_s\",1);\n\n        std::map<Role, RoleTimeline> expandedTimelines = getTimelines();\n\n\n        LOG_INFO_S << \"Min required: \" <<\n            RoleTimeline::toString(mMinRequiredTimelines,4,false);\n        LOG_INFO_S << \"Expanded: \" <<\n            RoleTimeline::toString(expandedTimelines,4,false);\n\n        std::pair< std::map<Role, csp::RoleTimeline>, std::map<Role, csp::RoleTimeline> >\n            key(expandedTimelines, mMinRequiredTimelines);\n\n        transshipment::MinCostFlow minCostFlow(expandedTimelines,\n                mMinRequiredTimelines,\n                mpContext->locations(),\n                mTimepoints,\n                mpContext->ask(),\n                mpMission->getLogger(),\n                solverType,\n                feasibilityTimeoutInMs);\n\n        breakpointStart()\n            << \"Min cost flow to start\" << std::endl;\n        breakpointEnd();\n\n        FlowSolutions::iterator it = msMinCostFlowSolutions.find(key);\n        if(it == msMinCostFlowSolutions.end())\n        {\n            std::vector<transshipment::Flaw> flaws = minCostFlow.run();\n\n            breakpointStart()\n                << \"Min cost flow to start\" << std::endl;\n            breakpointEnd();\n\n            transshipment::FlowNetwork flowNetwork = minCostFlow.getFlowNetwork();\n            mMinCostFlowSolution = flowNetwork.getSpaceTimeNetwork();\n\n            if(flaws.empty())\n            {\n                if(propagateImmobileAgentConstraints(mMinCostFlowSolution) ==\n                        Gecode::ES_FAILED)\n                {\n                    LOG_WARN_S << \"Immobile agent constraints not maintained by\"\n                        << \" local search\";\n                    return;\n                }\n            }\n\n            flowNetwork.save();\n\n            // store all flaws\n            mMinCostFlowFlaws = flaws;\n\n            if(mpContext->configuration().getValueAs<bool>(\"TransportNetwork/search/options/lp/cache-solution\",\n                        false))\n            {\n                msMinCostFlowSolutions[key] = FlowSolutionValue(flaws, mMinCostFlowSolution);\n            }\n        } else {\n            breakpointStart()\n                << \"Found existing solution .. (skipping recomputation and taking from cache)\" << std::endl;\n            breakpointEnd();\n\n            mMinCostFlowFlaws = it->second.first;\n            mMinCostFlowSolution = it->second.second;\n        }\n        // compute all feasible resolution that might allow\n        // to improve the solution\n        mFlawResolution.prepare(mMinCostFlowFlaws);\n\n        std::cout << \"Session \" << mpMission->getLogger()->getSessionId() << \": remaining flaws: \" << mMinCostFlowFlaws.size() << std::endl;\n        breakpointStart()\n            << \"Remaining flaws: \" << mMinCostFlowFlaws.size() << std::endl;\n        breakpointEnd();\n\n        // Set flaws as current cost of this solution\n        rel(*this, mCost, Gecode::IRT_EQ, mMinCostFlowFlaws.size());\n        rel(*this, mNumberOfFlaws, Gecode::IRT_EQ, mMinCostFlowFlaws.size());\n\n        mSolutionAnalysis = solvers::SolutionAnalysis(mpMission, mMinCostFlowSolution, mpContext->configuration());\n        mSolutionAnalysis.analyse();\n\n        // Set flaws as well\n        bool allowFlaws = mpContext->configuration().getValueAs<bool>(\"TransportNetwork/search/options/allow-flaws\", true);\n        if(!mMinCostFlowFlaws.empty() && !allowFlaws)\n        {\n            this->fail();\n            return;\n        }\n\n    } catch(const std::runtime_error& e)\n    {\n        // Min cost flow optimization or negative cycle checking\n        LOG_WARN_S << \"templ::solvers::csp::TransportNetwork: could not find\"\n            << \" solution: \" << e.what();\n        this->fail();\n        return;\n    }\n}\n\nvoid TransportNetwork::doPostTimelines(Gecode::Space& home)\n{\n    static_cast<TransportNetwork&>(home).postTimelines();\n}\n\nvoid TransportNetwork::postTimelines()\n{\n    breakpointStart()\n        << \"Post timelines\" << std::endl;\n    breakpointEnd();\n\n    branchTimelines(*this, mTimelines, mSupplyDemand);\n}\n\nstd::string TransportNetwork::toString() const\n{\n\n    size_t modelPoolSize = mpMission->getAvailableResources().size();\n\n    std::stringstream ss;\n    ss << \"TransportNetwork: #\" << std::endl;\n    ss << \"    Timepoints: \" << mQualitativeTimepoints << std::endl;\n    Gecode::Matrix<Gecode::IntVarArray> resourceDistribution(mModelUsage,\n            modelPoolSize, mResourceRequirements.size());\n    for(size_t m = 0; m < modelPoolSize; ++m)\n    {\n        const IRI& model = getResourceModelFromIndex(m);\n        ss << std::setw(30) << std::left << model.getFragment() << \": \";\n        for(size_t i = 0; i < mResourceRequirements.size(); ++i)\n        {\n            ss << std::setw(10) << std::left << resourceDistribution(m,i);\n        }\n        ss << std::endl;\n    }\n\n    Gecode::Matrix<Gecode::IntVarArray> rolesDistribution(mRoleUsage, mRoles.size(), mResourceRequirements.size());\n    size_t width = 30;\n    for(size_t m = 0; m < mRoles.size(); ++m)\n    {\n        width = std::min(mRoles[m].toString().size() + 5, width);\n    }\n\n    for(size_t m = 0; m < mRoles.size(); ++m)\n    {\n        ss << std::setw(width) << mRoles[m].toString() << \": \";\n        for(size_t i = 0; i < mResourceRequirements.size(); ++i)\n        {\n            ss << std::setw(10) << std::left << rolesDistribution(m,i);\n        }\n        ss << std::endl;\n    }\n    try {\n        for(size_t i = 0; i < mTimelines.size(); ++i)\n        {\n            ss << mActiveRoleList[i].toString() << std::endl;\n            ss << Formatter::toString(mTimelines[i], mpContext->locations(), mTimepoints) << std::endl;\n        }\n\n    } catch(const std::exception& e)\n    {\n        ss << \"Number of timelines: n/a -- \" << e.what() << std::endl;\n        ss << \"Current timelines: n/a \" << std::endl;\n    }\n\n    //ss << \"Capacities: \" << std::endl << Formatter::toString(mCapacities,\n    //        toPtrList<Symbol,symbols::constants::Location>(mpContext->locations()),\n    //        toPtrList<Variable, temporal::point_algebra::TimePoint>(mTimepoints)\n    //        ) << std::endl;\n\n    return ss.str();\n}\n\nstd::string TransportNetwork::modelUsageToString() const\n{\n    size_t firstcolumnwidth = 30;\n    size_t columnwidth = 20;\n    std::stringstream ss;\n    ss << \"Model usage:\" << std::endl;\n    ss << std::setw(firstcolumnwidth) << std::right << \"    FluentTimeResource: \";\n    for(size_t r = 0; r < mResourceRequirements.size(); ++r)\n    {\n        const FluentTimeResource& fts = mResourceRequirements[r];\n        /// construct string for proper alignment\n        std::string s = fts.getFluent()->getInstanceName();\n        s += \"@[\" + fts.getInterval().toString(0,true) + \"]\";\n\n        ss << std::setw(columnwidth) << std::left << s;\n    }\n    ss << std::endl;\n\n    const moreorg::ModelPool& modelPool = mpMission->getAvailableResources();\n\n    int modelIndex = 0;\n    moreorg::ModelPool::const_iterator cit = modelPool.begin();\n    for(; cit != modelPool.end(); ++cit, ++modelIndex)\n    {\n        const IRI& model = cit->first;\n        ss << std::setw(firstcolumnwidth) << std::left << model.getFragment() << \": \";\n        for(size_t r = 0; r < mResourceRequirements.size(); ++r)\n        {\n            ss << std::setw(columnwidth) << mModelUsage[r*modelPool.size() + modelIndex] << \" \";\n        }\n        ss << std::endl;\n    }\n    return ss.str();\n}\n\nstd::string TransportNetwork::roleUsageToString() const\n{\n    return Formatter::toString(mRoleUsage, mRoles, mResourceRequirements);\n}\n\nstd::string TransportNetwork::toString(const std::vector<Gecode::IntVarArray>& timelines) const\n{\n    std::vector<uint32_t> activeRoles = getActiveRoles();\n    std::vector<std::string> labels;\n    for(size_t i = 0; i < timelines.size(); ++i)\n    {\n        labels.push_back( mRoles[ activeRoles[i] ] .toString());\n    }\n    return Formatter::toString(timelines,\n            toPtrList<Symbol,symbols::constants::Location>(mpContext->locations()),\n            toPtrList<Variable, temporal::point_algebra::TimePoint>(mTimepoints),\n            labels);\n}\n\nuint32_t TransportNetwork::getTimepointIndex(const temporal::point_algebra::TimePoint::Ptr& timePoint) const\n{\n    using namespace templ::solvers::temporal;\n\n    std::vector<point_algebra::TimePoint::Ptr>::const_iterator timepointIt =\n        std::find(mTimepoints.begin(), mTimepoints.end(), timePoint);\n    if(timepointIt != mTimepoints.end())\n    {\n        return timepointIt - mTimepoints.begin();\n    }\n    throw std::invalid_argument(\"templ::solvers::csp::TransportNetwork::getTimepointIndex: unknown timepoint '\" + timePoint->toString() + \"' given\");\n}\n\nstd::ostream& operator<<(std::ostream& os, const TransportNetwork::Solution& solution)\n{\n    os << solution.toString();\n    return os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const TransportNetwork::SolutionList& solutions)\n{\n    TransportNetwork::SolutionList::const_iterator cit = solutions.begin();\n    os << std::endl << \"BEGIN SolutionList (#\" << solutions.size() << \" solutions)\" << std::endl;\n    size_t count = 0;\n    for(; cit != solutions.end(); ++cit)\n    {\n        os << \"#\" << count++ << \" \";\n        os << *cit;\n    }\n    os << \"END SolutionList\" << std::endl;\n    return os;\n}\n\nvoid TransportNetwork::save(const std::string& _filename) const\n{\n    std::string filename = _filename;\n    if(filename.empty())\n    {\n        base::Time timestamp = base::Time::now();\n        filename = mpMission->getLogger()->filename(timestamp.toString(base::Time::Seconds) + \"-transport-network.status\");\n    }\n    std::ofstream file;\n    file.open(filename );\n    file << toString();\n    file.close();\n}\n\nGecode::ExecStatus TransportNetwork::propagateImmobileAgentConstraints(const SpaceTime::Network& network)\n{\n    std::map<symbols::constants::Location::Ptr, size_t> mLocationIdxMap;\n    size_t numberOfLocations = mpContext->locations().size();\n    for(size_t idx = 0; idx < numberOfLocations; ++idx)\n    {\n        mLocationIdxMap[ mpContext->locations()[idx] ] = idx;\n    }\n    std::map<temporal::point_algebra::TimePoint::Ptr, size_t> mTimepointIdxMap;\n    size_t numberOfTimepoints = mTimepoints.size();\n    for(size_t idx = 0; idx < numberOfTimepoints; ++idx)\n    {\n        mTimepointIdxMap[ mTimepoints[idx] ] = idx;\n    }\n\n    Role::List activeImmobileRoles;\n    std::vector<size_t> activeImmobileRolesIdx;\n    for(size_t idx = 0; idx < mActiveRoleList.size(); ++idx)\n    {\n        const Role& role = mActiveRoleList[idx];\n        using namespace moreorg::facades;\n        Robot robot = Robot::getInstance(role.getModel(), mpContext->ask());\n        if(!robot.isMobile())\n        {\n            activeImmobileRoles.push_back(role);\n            activeImmobileRolesIdx.push_back(idx);\n        }\n    }\n\n    using namespace graph_analysis;\n    BaseGraph::Ptr graph = network.getGraph();\n    VertexIterator::Ptr vertexIt = graph->getVertexIterator();\n    while(vertexIt->next())\n    {\n        SpaceTime::Network::tuple_t::Ptr tuple =\n            dynamic_pointer_cast<SpaceTime::Network::tuple_t>(vertexIt->current());\n\n        Role::Set roles = tuple->getRoles(RoleInfo::ASSIGNED);\n        for(const Role& role : roles)\n        {\n            for(size_t idx : activeImmobileRolesIdx)\n            {\n                if(role == activeImmobileRoles[idx])\n                {\n                    if(updateTimeline(idx,\n                                mLocationIdxMap[tuple->first()],\n                                mTimepointIdxMap[tuple->second()],\n                                numberOfLocations,\n                                numberOfTimepoints) == Gecode::ES_FAILED)\n                    {\n                        LOG_WARN_S << \"Constraint could not be maintained for\"\n                            << \" role '\" << role.toString() << \"' at \"\n                            << \" location \" << tuple->first()->getInstanceName()\n                            << \" timepoint \" << tuple->second()->getLabel();\n                        return Gecode::ES_FAILED;\n                    }\n                }\n            }\n        }\n    }\n    return Gecode::ES_OK;\n}\n\nGecode::ExecStatus TransportNetwork::updateTimeline(size_t timelineIdx,\n        size_t locationIdx,\n        size_t timepointIdx,\n        size_t numberOfLocations,\n        size_t numberOfTimepoints)\n{\n    if(timepointIdx == 0 || timelineIdx >= numberOfTimepoints)\n    {\n        return Gecode::ES_OK;\n    }\n\n    for(size_t i = 0; i < numberOfLocations; ++i)\n    {\n        if(i != locationIdx)\n        {\n            Gecode::Set::SetView view(mTimelines[timelineIdx][timepointIdx*numberOfLocations + i]);\n            // only the given locations should have an outgoing edge,\n            // thus all other locations with empty sets\n            view.cardMax(*this, 0);\n        }\n\n        Gecode::SetVar var = mTimelines[timelineIdx][(timepointIdx-1)*numberOfLocations + i];\n\n        // Already assigned value have been propagated before local search,\n        // so no need to revalidate\n        if(var.assigned())\n        {\n            continue;\n        }\n\n        Gecode::Set::SetView view(var);\n        if(locationIdx > 0)\n        {\n            if(view.cardMax() != 0)\n            {\n                size_t lower = timepointIdx*numberOfLocations;\n                size_t upper = timepointIdx*numberOfLocations + locationIdx -1;\n                for(size_t l = lower; l <= upper; ++l)\n                {\n                    GECODE_ME_CHECK(view.exclude(*this, l));\n                }\n            }\n        }\n        if(locationIdx < numberOfLocations - 1)\n        {\n            if(view.cardMax() != 0)\n            {\n                size_t lower = timepointIdx*numberOfLocations + locationIdx + 1;\n                size_t upper = timepointIdx*numberOfLocations + numberOfLocations + 1;\n                for(size_t l = lower; l <= upper; ++l)\n                {\n                    GECODE_ME_CHECK(view.exclude(*this, l));\n                }\n            }\n        }\n    }\n    return Gecode::ES_OK;\n}\n\nvoid TransportNetwork::breakpoint(const std::string& msg)\n{\n    if(msInteractive)\n    {\n        std::cout << msg << std::endl;\n        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\\n' );\n    }\n}\n\nstd::ostream& TransportNetwork::breakpointStart()\n{\n    mInteractiveMessageStream.clear();\n    return mInteractiveMessageStream;\n}\n\nvoid TransportNetwork::breakpointEnd()\n{\n    breakpoint(mInteractiveMessageStream.str());\n}\n\n} // end namespace csp\n} // end namespace solvers\n} // end namespace templ\n", "meta": {"hexsha": "7acb955050ae3afc5f8dc2e9937ddaad923ec650", "size": 92281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/csp/TransportNetwork.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/solvers/csp/TransportNetwork.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/solvers/csp/TransportNetwork.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": 40.1396259243, "max_line_length": 196, "alphanum_fraction": 0.6092586773, "num_tokens": 20648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.1681465322806429}}
{"text": "#pragma once\n\n#include <utility>\n\n\n#include <boost/operators.hpp>\n\n#include <elle/attribute.hh>\n#include <elle/operator.hh>\n#include <elle/serialization.hh>\n#include <elle/cryptography/fwd.hh>\n#include <elle/cryptography/types.hh>\n#include <elle/cryptography/Oneway.hh>\n#include <elle/cryptography/Cipher.hh>\n\n//\n// ---------- Class -----------------------------------------------------------\n//\n\nnamespace elle\n{\n  namespace cryptography\n  {\n    namespace dsa\n    {\n      /// A private key in the DSA asymmetric cryptosystem.\n      class PrivateKey\n        : public elle::Printable\n        , private boost::totally_ordered<PrivateKey>\n      {\n        /*-------------.\n        | Construction |\n        `-------------*/\n      public:\n        /// Construct a private key based on the given EVP_PKEY key whose\n        /// ownership is transferred.\n        explicit\n        PrivateKey(::EVP_PKEY* key,\n                   Oneway const digest_algorithm);\n        /// Construct a private key based on the given DSA key whose\n        /// ownership is transferred to the private key.\n        explicit\n        PrivateKey(::DSA* dsa,\n                   Oneway const digest_algorithm);\n        PrivateKey(PrivateKey const& other);\n        PrivateKey(PrivateKey&& other);\n        virtual\n        ~PrivateKey() = default;\n\n        /*--------.\n        | Methods |\n        `--------*/\n      private:\n        /// Construct the object based on the given DSA structure whose\n        /// ownership is transferred to the callee.\n        void\n        _construct(::DSA* dsa);\n        /// Check that the key is valid.\n        void\n        _check() const;\n      public:\n        /// Return a signature of the given plain text.\n        elle::Buffer\n        sign(elle::ConstWeakBuffer const& plain) const;\n        /// Sign a stream-based plain text.\n        elle::Buffer\n        sign(std::istream& plain) const;\n        /// Return the private key's size in bytes.\n        uint32_t\n        size() const;\n        /// Return the private key's length in bits.\n        uint32_t\n        length() const;\n\n        /*----------.\n        | Operators |\n        `----------*/\n      public:\n        bool\n        operator ==(PrivateKey const& other) const;\n        ELLE_OPERATOR_NO_ASSIGNMENT(PrivateKey);\n\n        /*----------.\n        | Printable |\n        `----------*/\n      public:\n        void\n        print(std::ostream& stream) const override;\n\n        /*-------------.\n        | Serializable |\n        `-------------*/\n      public:\n        PrivateKey(elle::serialization::SerializerIn& serializer);\n        void\n        serialize(elle::serialization::Serializer& serializer);\n        using serialization_tag = elle::serialization_tag;\n\n        /*-----------.\n        | Attributes |\n        `-----------*/\n      private:\n        ELLE_ATTRIBUTE_R(types::EVP_PKEY, key);\n        ELLE_ATTRIBUTE_R(Oneway, digest_algorithm);\n      };\n    }\n  }\n}\n\nnamespace std\n{\n  template <>\n  struct hash<elle::cryptography::dsa::PrivateKey>\n  {\n    size_t\n    operator ()(elle::cryptography::dsa::PrivateKey const& value) const;\n  };\n}\n", "meta": {"hexsha": "ff51fd1316a49722e3249f20f0be9d788d8dd534", "size": 3086, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/elle/cryptography/dsa/PrivateKey.hh", "max_stars_repo_name": "infinitio/elle", "max_stars_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 521.0, "max_stars_repo_stars_event_min_datetime": "2016-02-14T00:39:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T22:39:25.000Z", "max_issues_repo_path": "src/elle/cryptography/dsa/PrivateKey.hh", "max_issues_repo_name": "infinitio/elle", "max_issues_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-02-21T11:47:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-01T09:37:14.000Z", "max_forks_repo_path": "src/elle/cryptography/dsa/PrivateKey.hh", "max_forks_repo_name": "infinitio/elle", "max_forks_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2017-02-21T10:18:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:35:20.000Z", "avg_line_length": 25.9327731092, "max_line_length": 79, "alphanum_fraction": 0.5401814647, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.1681465322806429}}
{"text": "//   GUM: GAMBIT Universal Model Machine\n//   ************************************\n///  \\file\n///\n///  Definitions of SARAH class\n///\n///  **********************************\n///\n///  \\author Sanjay Bloor\n///          (sanjay.bloor12@imperial.ac.uk)\n///  \\date 2018, 2019\n///\n///  \\author Tomas Gonzalo\n///          (tomas.gonzalo@monash.edu)\n///  \\date 2019 July, Aug\n///\n///  ***********************************\n\n#include <set>\n#include <algorithm>\n#include <cstring>\n\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <boost/python/suite/indexing/map_indexing_suite.hpp>\n#include <boost/python/raw_function.hpp>\n\n#include <boost/filesystem.hpp>\n\n#include \"sarah.hpp\"\n\nnamespace GUM\n{\n\n  // SARAH constructor, loads SARAH and the model\n  SARAH::SARAH(std::string model) : Math_Package(model)\n  {\n    // Math_Package constructor already creates the WSTP link\n\n    try\n    {\n      // Load SARAH\n      load_sarah();\n\n      // Load model\n      load_model(model);\n    }\n    catch(...) { throw; }\n    \n  }\n   \n  // Load SARAH\n  void SARAH::load_sarah()\n  {\n\n    std::cout << \"Loading SARAH... \";\n    std::cout.flush();\n\n    std::string input;\n    input+= \"SetDirectory[\\\"\" + std::string(SARAH_PATH) + \"\\\"]\";\n    send_to_math(input);\n\n    const char* out;\n    if (!WSGetString(link, &out))\n    {\n        throw std::runtime_error(\"SARAH Error: Error loading SARAH. Please check that Mathematica\\n\" \n                                 \"is working and that SARAH actually lives where CMake put it, in:\\n\"\n                                 \"  \" + std::string(SARAH_PATH) + \"\\n\" \n                                 \"Please try rebuilding.\");\n    }\n    else\n    {\n        std::cout << \"SARAH loaded from \" << out << \".\" << std::endl;\n    }\n\n    input = \"<<SARAH`\";\n    send_to_math(input);\n\n  }\n\n  void SARAH::load_model(std::string model)\n  {\n    try\n    {\n      std::cout << \"Loading model \" + model + \" in SARAH... \" << std::endl;\n\n      // Check if model is in SARAH's or GUM's list of models\n      if(!model_exists(model))\n      {\n        throw std::runtime_error(\"SARAH Error: Could not load model \" + model + \". Model is not recognised by SARAH or GUM.\");\n      }\n\n      // Load it up.\n      std::string command = \"Start[\\\"\" + model + \"\\\"];\";\n      send_to_math(command);\n\n      // Check the model has been loaded by querying the model name. If it has changed from the default then we're set.\n      std::string modelname = get_modelname();\n\n      // ...Assuming someone hasn't set the model name to 'ModelName' which would be unbelievably annoying and vastly silly.\n      if (modelname == \"ModelName\")\n        throw std::runtime_error(\"SARAH Error: Could not load model \" + model + \". Please check your SARAH file.\");\n\n      // All good.\n      std::cout << \"Model \" + model + \" loaded successfully, with model name \" << modelname << \".\" << std::endl;\n    } catch(...) { throw; }\n  }\n\n  void SARAH::check_model(std::string model, std::vector<std::string> &backends)\n  {\n    try\n    {\n      std::cout << \"Checking your model... \" << std::endl;\n\n      // Check whether CalcHEP or MicrOmegas have been requested as backend\n      bool need_ch = false;\n      if (std::find(backends.begin(), backends.end(), \"calchep\") != backends.end()   ||\n          std::find(backends.begin(), backends.end(), \"micromegas\") != backends.end() )\n        need_ch = true;\n      \n      // Redirect output to catch them after checking model\n      send_to_math(\"streams = AppendTo[$Output, OpenWrite[]];\");\n   \n      send_to_math(\"CheckModel[]; messages = $MessageList;\");\n\n      // Close the output stream and restore to stdout\n      std::string command = \"Close@Last@streams;\"\\\n                \"$Output = Most@streams;\"\\\n                \"output = ReadList@First@Last@streams;\";\n      send_to_math(command);\n\n      // Process the output to find anomaly warnings\n      int noutput;\n      send_to_math(\"Length[output]\");\n      get_from_math(noutput);\n      for(int i=1; i<=noutput; i++)\n      {\n        std::string output;\n        send_to_math(\"ToString[output[[\" + std::to_string(i) + \"]]]\");\n        get_from_math(output);\n\n        size_t pos = output.find(\"WARNING\");\n        if(pos != std::string::npos)\n          std::cout << output.substr(pos) << std::endl;\n      }\n\n      // Get the messages and processes them\n      int nmessages;\n      send_to_math(\"Length[messages]\");\n      get_from_math(nmessages);\n      for(int i=1; i<=nmessages; i++)\n      {\n        std::string error, message;\n        send_to_math(\"ToString[messages[[\" + std::to_string(i) + \"]]]\");\n        get_from_math(error);\n\n        // If the error is a Mathematica error rather than a SARAH error (e.g. Part::partw) skip\n        if(error == \"Part::partw\" or error == \"Part::pkspec1\") continue;\n\n        // Else, carry on analysing the error\n        send_to_math(\"ToString[ReleaseHold[messages[[\" + std::to_string(i) + \"]]]]\");\n        get_from_math(message);\n\n        //CheckAnomalies\n        // This is handled above as it does not produce error messages, only prints\n\n        //CheckChargeConservation;\n        if(error == \"ChargeConservation::NoSUN\")\n          std::cout << \"Warning! \" << message << std::endl;\n        else if(error == \"Superpotential::ChargeViolation\")\n          throw std::runtime_error(\"SARAH Error: Model violates charge conservation. Please fix your superpotential\");\n        else if(error == \"Superpotential::MaybeChargeViolation\")\n          std::cout << \"Warning! The superpotential may violate charge conservation.\" << std::endl;\n        else if(error == \"Superpotential::ViolationGlobal\")\n          throw std::runtime_error(\"SARAH Error: Model violates global symmetry. Please fix your superpotential\");\n\n        //CheckPossibleTermsSuperPotential, CheckPossibleTermsPotential\n        else if(error == \"Lagrange:ChargeViolation\")\n          throw std::runtime_error(\"SARAH Error: Model violates charge conservation. Please fix your Lagrangian\");\n        else if(error == \"Lagrange::MaybeChargeViolation\")\n          std::cout << \"Warning! The Lagrangian may violate charge conservation.\" << std::endl;\n        else if(error == \"PossibleTerms::IncludeGlobal\")\n          std::cout << \"Warning! The superpotential does not include all possible terms.\" << std::endl;\n        else if(error == \"PossibleTerms::NonSUSY\")\n          std::cout << \"Warning! The Lagrangian does not include all possible terms. Note that this functionality does not work perfectly for non-susy models, so check your Lagrangian\" << std::endl;\n\n\n        //CheckParticleMixingAndVEVs\n        else if(error == \"Mixing::DifferentQN\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your model file.\");\n        else if(error == \"VEV::UnbrokenSymmetries\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your model file.\");\n\n        //CheckMassMatrices\n        else if(error == \"MassMatrix::OnlyZero\")\n          std::cout << \"Warning! \" << message << \".\" << std::endl;\n        else if(error == \"MassMatrix::Reducible\")\n          std::cout << \"Warning! \" << message << \".\" << std::endl;\n\n        //CheckMissingMixing\n        else if(error == \"Lagrangian::PossibleMixing\")\n          std::cout << \"Warning! Possible mixing between fields has been found.\" << std::endl;    \n\n\n        //CheckDiracSpinors\n        else if(error == \"DiracSpinor::missing\")\n          std::cout << \"Warning! Missing Dirac spinor definitions for some Weyl spinors.\" << std::endl;\n\n        //CheckParameterDefinitionsFinal\n        else if(error == \"CheckModelFiles::MissingParameter\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your parameters file.\");\n        else if(error == \"CheckModelFiles::MissingLH\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your parameters file.\");\n        else if(error == \"CheckModelFiles::MissingOutputNameParameter\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your parameters file.\");\n        else if(error == \"ParameterNames::TooLong\")\n          if(need_ch)\n            throw std::runtime_error(\"SARAH Error: Some parameter OutputName is too long for a valid CalcHEP output.\");\n          else\n            std::cout << \"Warning! The OutputNames of some parameters are too long for CalcHEP output. If using CalcHEP please reduce their length.\" << std::endl;\n        else if(error == \"ParameterNames::DefinedTwice\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your parameters file.\");\n\n        //CheckParticleDefinitionsFinal\n        else if(error == \"CheckModelFiles::MissingParticle\")\n          std::cout << \"Warning! Some particle definitions are missing from the particles file.\" << std::endl;\n          //throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your particles file.\");\n        else if(error == \"CheckModelFiles::MissingOutputName\")\n          std::cout << \"Warning! Some particle are missing a definition of OutputName in the particles file.\" << std::endl;\n          //throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your particles file.\");\n        else if(error == \"CheckModelFiles::MissingRParity\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your particles file.\");\n        else if(error == \"CheckModelFiles::WrongPDG\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your particles file.\");\n        else if(error == \"CheckModelFiles::ElectricCharge\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your particles file.\");\n        else if(error == \"ParticleNames::TooLong\")\n          if(need_ch)\n            throw std::runtime_error(\"SARAH Error: Some particle OutputName is too long for a valid CalcHEP output.\");\n          else\n            std::cout << \"Warning! The OutputNames of some particles are too long for CalcHEP output. If using CalcHEP please reduce their length.\" << std::endl;\n        else if(error == \"ParticleNames::DefinedTwice\")\n          std::cout << \"Warning! Some particle OutputNames are defined twice.\" << std::endl;\n          //throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your particles file.\");\n        else if(error == \"FeynArts::NN\")\n          std::cout << \"Warning! \" << message << \". If using FeynArts please add missing numbers.\" << std::endl;\n        else if(error == \"FeynArts::NumberDefinedTwiceF\")\n          std::cout << \"Warning! \" << message << \". If using FeynArts please change duplicated numbers.\" << std::endl;\n        else if(error == \"FeynArts::NumberDefinedTwiceS\")\n          std::cout << \"Warning! \" << message << \". If using FeynArts please change duplicated numbers.\" << std::endl;\n        else if(error == \"FeynArts::NumberDefinedTwiceV\")\n          std::cout << \"Warning! \" << message << \". If using FeynArts please change duplicated numbers.\" << std::endl;\n        else if(error == \"FeynArts::NumberDefinedTwiceG\")\n          std::cout << \"Warning! \" << message << \". If using FeynArts please change duplicated numbers.\" << std::endl;\n        else if(error == \"Model::NoEC\")\n          throw std::runtime_error(\"SARAH Error: \" + message + \". Please fix your particles file.\");\n\n        // This seems to be a recurring bug in SARAH, so ignore it\n        else if(error == \"Transpose::nmtx\")\n        {\n          // Do nothing\n        }\n\n        // Ignore messages about suppression of messages\n        else if(error == \"General::stop\")\n        {\n          // Do nothing\n        }\n\n        // If error is unknown throw exception\n        else\n          throw std::runtime_error(\"SARAH Error: \" + error + \" : \" + message);\n      }\n\n      // All good.\n      std::cout << \"Model \" + model + \" successfully passed SARAH's checks. Please address any warnings issued.\" << std::endl;\n    } catch(...) { throw; }\n  }\n\n\n\n  // The model may have a different \"internal\" name than what's on the package.\n  // Need this info for output files, etc.\n  std::string SARAH::get_modelname()\n  {\n\n    std::string command = \"ModelName\";\n    send_to_math(command);\n\n    const char* out;\n    if (!WSGetString(link, &out))\n        throw std::runtime_error(\"SARAH Error: Error getting Model name.\");\n\n    return std::string(out);\n  }\n\n  // Check if model is SARAH's database or in GUM's\n  bool SARAH::model_exists(std::string modelname)\n  {\n    try\n    {\n      // Check if the model is in the SARAH database\n      std::string command = \"MemberQ[ShowModels[[1]],\\\"\" + modelname + \"\\\"]\";\n      send_to_math(command);\n      \n      // Get the boolean result\n      bool is_SARAH_model;\n      get_from_math(is_SARAH_model);\n      if(is_SARAH_model)\n      {\n        return true;\n      }\n\n      // If not check if it's in the GUM model database\n      std::string modelpath = std::string(GUM_DIR) + \"/Models/\" + modelname + \"/\" + modelname + \".m\";\n\n      // If it exists, then copy the folder to the SARAH model dir\n      if (!boost::filesystem::exists(modelpath))\n      {\n        std::cout << \"Copying SARAH files from GUM directory to SARAH directory...\" << std::endl;\n        std::string dest = std::string(SARAH_PATH) + \"/Models/\" + modelname;\n        std::string src = std::string(GUM_DIR) + \"/Models/\" + modelname;\n\n        // Create the folder in SARAH...\n        if (!boost::filesystem::create_directory(dest))\n        {\n            throw std::runtime_error(\"Unable to create new model folder in SARAH: \" + dest + \".\");\n        }\n        // Copy all files from the GUM dir to the SARAH dir\n        for (boost::filesystem::directory_iterator file(src); file != boost::filesystem::directory_iterator();\n             ++ file)\n        {\n            try\n            {\n                boost::filesystem::path current(file->path());\n                // Leave folders behind\n                if(boost::filesystem::is_directory(current)) {  continue; }\n                else\n                {\n                    boost::filesystem::copy_file(current, dest / current.filename());\n                }\n            }\n            catch(boost::filesystem::filesystem_error const & e)\n            {\n                throw std::runtime_error( e.what() );\n            }\n        }\n      }\n\n      // Let's try that again.\n      get_from_math(is_SARAH_model);\n      if(is_SARAH_model)\n      {\n        return true;\n      }\n      else\n      {\n        return false;\n      }\n    }\n    catch(...) { throw; }\n  }\n\n  // Computes the vertices at EWSB\n  void SARAH::calculate_vertices()\n  {\n    std::cout << \"Calculating vertices...\" << std::endl;\n\n    std::string command = \"\";\n\n    try\n    {\n      command = \"MakeVertexList[EWSB];\";\n      send_to_math(command);\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Get particles list\n  void SARAH::get_partlist(std::vector<Particle> &partlist)\n  {\n\n    std::cout << \"Extracting particles from SARAH model.\" << std::endl;\n\n    std::string command = \"\";\n\n    try\n    {\n\n      // Command to get a list with (most) particle info.\n      command = \"plgum = ParticleDefinitions[EWSB];\";\n      send_to_math(command);\n\n      // Find out how many particles we have to get.\n      command = \"Length[plgum]\";\n      send_to_math(command);\n\n      int lenpl;\n      get_from_math(lenpl);\n\n      // Save some stuff for in a minute.\n\n      // Fermions\n      std::vector<std::string> dFs;\n      command = \"PART[F][[All,1]]\";\n      // command = \"diracFermions[ALL]\";\n      send_to_math(command);\n      get_from_math(dFs);\n\n      // Scalar\n      std::vector<std::string> scs;\n      command = \"PART[S][[All,1]]\";\n      send_to_math(command);\n      get_from_math(scs);\n      \n      // Vector\n      std::vector<std::string> vecs;\n      command = \"PART[V][[All,1]]\";\n      send_to_math(command);\n      get_from_math(scs);\n      \n      std::cout << \"Found \" << lenpl << \" particle sets.\" << std::endl;\n\n      // Get to parsing this monster.\n      for (int i=0; i<lenpl; i++)\n      {\n      \n        // First things first, check to see if we are dealing with multiplets.\n        // e.g., l = (e, mu, tau).\n        int numelements;\n        command = \"Length[getPDG[plgum[[\" + std::to_string(i+1) + \", 1]]]]\";\n        send_to_math(command);\n        get_from_math(numelements);\n\n        // If there's no associated PDG code.\n        if (numelements == 0)\n        {\n            continue;\n        }\n\n        for (int j=0; j<numelements; j++)\n        {\n            // Initialise all properties we wish to find out about a particle.\n            std::string name;\n            std::string alt_name;\n            std::string outputname;\n            std::string antiname;\n            std::string antioutputname;\n            std::string mass;\n            std::string colorrep;\n            int spinX2 = -1; // Set to -1 for error catching\n            int chargeX3 = 0;\n            int color = 0;\n            int pdg;\n            int num;\n            bool SM;\n            bool capitalise = false;\n\n            // Assume a particle is SC unless we spot it.\n            bool self_conjugate = true;\n\n            // Get SARAH name of the particle\n            send_to_math(\"plgum[[\" + std::to_string(i+1) + \", 1]]\");\n            get_from_math(alt_name);\n\n            // Use this to get the spin of the particle\n\n            // Get the PDG\n            command = \"Part[getPDG[plgum[[\" + std::to_string(i+1) + \", 1]]], \" + std::to_string(j+1) + \"]\";\n            send_to_math(command);\n            get_from_math(pdg);\n\n            // If it's got a PDG of 0 it's not a physical particle. Don't care about it.\n            if (pdg == 0) { continue; }\n\n            command = \"Length[getOutputName[plgum[[\" + std::to_string(i+1) + \", 1]]]]\";\n            send_to_math(command);\n            get_from_math(num);\n\n            if (num == 2)\n            {\n                self_conjugate = false;\n                command = \"Part[getOutputName[plgum[[\" + std::to_string(i+1) + \", 1]]], 1]\";\n                send_to_math(command);\n                get_from_math(name);\n\n                command = \"Part[getOutputName[plgum[[\" + std::to_string(i+1) + \", 1]]], 2]\";\n                send_to_math(command);\n                get_from_math(antiname);\n            }\n            else if (num == 0)\n            {\n                command = \"getOutputName[plgum[[\" + std::to_string(i+1) + \", 1]]]\";\n                send_to_math(command);\n                get_from_math(name);\n\n                // Probe to see if it is self-conjugate\n                command = \"TrueQ[plgum[[\" + std::to_string(i+1) + \", 1]] == conj[plgum[[\" + std::to_string(i+1) + \", 1]]]]\";\n                send_to_math(command);\n                bool is_sc;\n                get_from_math(is_sc);\n                if (not is_sc)\n                {\n                    self_conjugate = false;\n                    capitalise = true;\n                    antiname = name; // This will get changed in a minute\n                }\n            }\n            else\n            {\n                std::stringstream err;\n                err << \"More than 2 particles here; \"\n                    << \"what weird symmetries have you got???\" \n                    << std::endl;\n                throw std::runtime_error(err.str());\n            }\n\n            if (numelements > 1)\n            {\n                outputname = name + std::to_string(j+1);\n                alt_name = alt_name + std::to_string(j+1);\n            }\n            else\n            {\n                outputname = name;\n                antioutputname = antiname;\n            }\n\n            if (not self_conjugate && capitalise)\n            {\n                antioutputname = outputname;\n                if (isupper(antioutputname[0])) { antioutputname = tolower(antioutputname[0]); }\n                else { antioutputname[0] = toupper(antioutputname[0]); }\n            }\n            else if (not self_conjugate && not capitalise)\n            {\n                antioutputname = antiname;\n            }\n            else { antioutputname = outputname; }\n\n            mass = \"M\" + outputname;\n\n            // Get the color rep\n            command = \"getColorRep[plgum[[\"+std::to_string(i+1)+\",1]]] // ToString\";\n            send_to_math(command);\n            get_from_math(colorrep);\n\n            // Translate this to a color that GAMBIT particle DB can use\n            if (colorrep == \"S\") color = 1;\n            else if(colorrep == \"T\") color = 3;\n            else if(colorrep == \"O\") color = 8;\n            else if(colorrep == \"Six\") color = 6;\n            else throw std::runtime_error(\"Unrecognised color - \" + colorrep + \" - found.\");\n\n            // Electric charge\n            command = \"getElectricCharge[plgum[[\"+std::to_string(i+1)+\",1]]] * 3\";\n            send_to_math(command);\n            get_from_math(chargeX3);\n\n            // Spin\n            std::string spinentry;\n            command = \"getType[plgum[[\"+std::to_string(i+1)+\",1]]]\";\n            send_to_math(command);\n            get_from_math(spinentry);\n\n            if (spinentry == \"S\") spinX2 = 0;\n            else if(spinentry == \"F\") spinX2 = 1;\n            else if(spinentry == \"V\") spinX2 = 2;\n            // Get Spinformation for EWSB particles that come from mixings in either\n            // matter/gauge sectors or are from VEVs\n            else if(spinentry == \"NoField\") \n            {\n              // Strip any trailing digits first\n              size_t last_index = alt_name.find_last_not_of(\"0123456789\");\n              std::string strippedname = alt_name.substr(0, last_index + 1);\n\n              // Check to see if it's in the list of fermions we have\n              if (std::find(dFs.begin(), dFs.end(), strippedname) != dFs.end())\n                spinX2 = 1;\n              // If not - how about a scalar?\n              else if (std::find(scs.begin(), scs.end(), strippedname) != scs.end())\n                spinX2 = 0;\n              // Or a vector?\n              else if (std::find(vecs.begin(), vecs.end(), strippedname) != vecs.end())\n                spinX2 = 2;\n            }\n            else throw std::runtime_error(\"Unrecognised spin - \" + spinentry + \" - found.\");\n\n            // If we haven't found a spin...\n            if (spinX2 == -1)\n              throw std::runtime_error(\"Unable to extract spin for particle: \" + alt_name + \".\");\n\n            std::set<int> SM_pdgs = {1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 21, 22, 23, 24};\n            if (SM_pdgs.count(abs(pdg)))\n            {\n                SM = true;\n            }\n            else\n            {\n                SM = false;\n            }\n\n            // If it's not SM, get the tree-level mass relation\n            std::string treelevelmass = \"\";\n\n            if (not SM)\n            {\n              // If there are multiplets, the tree-level masses cannot give the mixings or the EWSB conditions\n              // In these cases one should use a spectrum generator\n              // Hence, flag the tree level mass as not valid so an error can be thrown later if there's no spec gen\n              if (numelements > 1)\n              {\n                treelevelmass = \"NotValid\";\n              }\n              else\n              {\n                // Use Mathematica's terrible CForm output, amend this in GUM -- string replacement is nicer in Python :-)\n                command = \"TreeMass[\" + alt_name + \",EWSB] // CForm // ToString\";\n                send_to_math(command);\n                get_from_math(treelevelmass);\n              }\n            }\n\n            // Add the particle to the list.\n            Particle particle(pdg, outputname, spinX2, chargeX3, color, \n                              SM, mass, antioutputname, alt_name, \"\", treelevelmass);  // Blank space is for SPheno mass (alt_mass)\n            partlist.push_back(particle);\n\n        }\n\n      }\n\n      std::cout << \"Done.\" << std::endl;\n\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Get parameters list\n  void SARAH::get_paramlist(std::vector<Parameter> &paramlist, std::vector<Parameter> &sphenodependences)\n  {\n\n    std::cout << \"Extracting parameters from SARAH model.\" << std::endl;\n\n    std::string command = \"\";\n\n    try\n    {\n\n      // Get list of parameters\n      command = \"pdgum = ParameterDefinitions;\";\n      send_to_math(command);\n\n      // Here's another parameter list which has, crucically,\n      // the size of mixing matrices.\n      command = \"pgum = parameters;\";\n      send_to_math(command);\n\n      // Find out how many parameters we have to get.\n      command = \"Length[pdgum]\";\n      send_to_math(command);\n\n      int lenpl;\n      get_from_math(lenpl);\n\n      std::cout << \"Found \" << lenpl << \" parameter sets.\" << std::endl;\n\n      for (int i=0; i<lenpl; i++)\n      {\n        std::string block;\n        std::string paramname;\n        std::string alt_paramname;\n        bool real = false; // Assume it's complex unless we figure out that it's not.\n        int index = 1;\n        bool sphenodeps = false; // Do we want to save this as a SPheno dep?\n\n        // Whether we've found an LH block\n        bool LHblock = false;\n\n        // Whether the LHblock is a mixing matrix [of some size]\n        bool ismixing = false;\n\n        command = \"pdgum[[\" + std::to_string(i+1) + \",1]]//ToString\";\n        send_to_math(command);\n\n        // Get the parameter name as it is known in SARAH. This\n        // might change later.\n        get_from_math(paramname);\n\n        command = \"Length[pdgum[[\" + std::to_string(i+1) + \",2]]]\";\n        send_to_math(command);\n\n        // Each entry will be some sort of descriptor for\n        // a particle. Discard things like LaTeX entries, \n        // descriptions in prose, etc.\n        std::string entry;\n\n        // Here are the useful things we want to query:\n        // - blockname & index\n        // - parameter name\n        // - dependences\n        // - if a parameter is *definitely* real\n\n        command = \"Real /. pdgum[[\" + std::to_string(i+1) + \", 2]] // ToString\";\n        send_to_math(command);\n        get_from_math(entry);\n\n        // If it's definitely a real parameter, store this information\n        if (entry == \"True\") real = true;\n\n        // With DependenceSPheno -- flag it, so we can save it for later; we'll want it\n        command = \"DependenceSPheno /. pdgum[[\" + std::to_string(i+1) + \",2]] // ToString\";\n        send_to_math(command);\n        get_from_math(entry);\n        if (entry != \"DependenceSPheno\" and entry != \"None\") \n        {\n          sphenodeps = true;\n        }\n\n        // Otherwise -- if we don't want to save it: \n        // If it has a dependence -- not interested. Bin it.\n\n        // Numerical dependence?\n        // Parameters with DependenceNum are acutally needed, so keep these\n        \n        // Same with just Dependence\n        command = \"Dependence /. pdgum[[\" + std::to_string(i+1) + \",2]] // ToString\";\n        send_to_math(command); \n        get_from_math(entry);\n        if (entry != \"Dependence\" and entry != \"None\" and sphenodeps != true) continue;\n\n        // Get block name\n        command = \"Head[LesHouches /. pdgum[[\" + std::to_string(i+1) + \",2]]]\";\n        send_to_math(command);\n        get_from_math(entry);\n\n        // If we have a list, then there's a blockname and an index.\n        if (entry == \"List\") \n        { \n            command = \"LesHouches /. pdgum[[\" + std::to_string(i+1) + \",2]]\";\n            send_to_math(command);\n            std::vector<std::string> leshouches;\n            get_from_math(leshouches);\n\n            // blockname\n            block = leshouches[0];\n            // index\n            index = std::stoi(leshouches[1]);\n            LHblock = true;\n\n            // If blockname is PHASES then it's effectively a mixing\n            if (block == \"phases\" or block == \"Phases\")\n              ismixing = true;\n        }\n        // If not a list, but a symbol, then we've got a mixing block\n        else if(entry == \"Symbol\") \n        {\n            // Get the blockname\n            command = \"LesHouches /. pdgum[[\" + std::to_string(i+1) + \",2]]\";\n            send_to_math(command);\n            get_from_math(block);\n\n            if(block != \"None\")\n            {\n              ismixing = true;\n              LHblock = true;\n            }\n        }\n        else\n        {\n          throw std::runtime_error(\"Error in LesHouches block for the entry \"\n                                   + paramname + \" in SARAH -- please check \"\n                                   \"your SARAH model file.\");\n        }\n\n        // Does the parameter have a different external\n        // name than the internal SARAH name? If so, use it.\n        command = \"OutputName /. pdgum[[\" + std::to_string(i+1) + \",2]] // ToString\";\n        send_to_math(command);\n        get_from_math(entry);\n\n        // If it has a different output name to \n        // internal, we'd better use it, seeing as GAMBIT\n        // is... output, I guess.\n        if (entry != \"OutputName\") \n        { \n            alt_paramname = paramname;\n            paramname = entry;\n        }\n\n        // If it's a fundamental parameter of our theory, \n        // add it to the list (if it has an LH block!)\n        if (LHblock && !ismixing && !sphenodeps)\n        {\n            Parameter parameter(paramname, block, index, alt_paramname, real);\n            paramlist.push_back(parameter);\n        }\n        // If it's a mixing block then save it as as such \n        else if (LHblock && ismixing && !sphenodeps)\n        {\n            std::string shape;\n            std::vector<std::string> shapesize;\n\n            // Get the position of the mixing block in the other param list\n            command = \"pos = Position[pgum, \" + alt_paramname + \"]\";\n            send_to_math(command);\n\n            // Extract the size of the matrix\n            command = \"Extract[pgum, pos[[1,1]]][[3]]\";\n            send_to_math(command);\n            get_from_math(shapesize);\n\n            // If it's a phase, then it's a scalar\n            if(shapesize.size())\n              shape = \"m\" + shapesize[0] + \"x\" + shapesize[1];\n            else\n              shape = \"scalar\";\n            \n            // Add to the paramlist -- but only as an *output* parameter, \n            // and with the shape of the matrix\n            bool is_output = true;\n\n            Parameter parameter(paramname, block, index, alt_paramname, \n                                real, shape, is_output);\n            paramlist.push_back(parameter);\n        }\n        // Save to the SPheno dependencies\n        else if (LHblock && sphenodeps)\n        {\n          // If there's a SPheno dep., use Mathematica's terrible CForm output.\n          // We'll amend this in GUM -- string replacement is nicer in Python :-)\n          command = \"DependenceSPheno /. pdgum[[\" + std::to_string(i+1) + \",2]] // CForm // ToString\";\n          send_to_math(command);\n          get_from_math(entry);\n          // Here we are storing the alt_paramname as the definition. Be careful!\n          Parameter sphenodep(paramname, block, index, entry, real);\n          sphenodependences.push_back(sphenodep);\n        }\n\n      }\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Get minpar and extpar parameters and add them to the parameter list\n  void SARAH::get_minpar_extpar(std::vector<Parameter> &parameters)\n  {\n    std::cout << \"Extracting MINPAR and EXTPAR parameters from SPheno\" << std::endl;\n\n    std::vector<std::vector<std::string> > minpar;\n    std::vector<std::vector<std::string> > extpar;\n\n    std::string defaultlist;\n    std::string command = \"\";\n\n    try\n    {\n      \n\n      // Check if MINPAR is a list\n      bool is_list;\n      command = \"Head[MINPAR]===List\";\n      send_to_math(command);\n      get_from_math(is_list);\n\n      // Find out how many parameters we have...\n      command = \"Length[pdgum]\";\n      send_to_math(command);\n      int lenpl;\n      get_from_math(lenpl);\n\n      // Get default parameters\n      bool default_is_list;\n      command = \"Head[DefaultInputValues]===List\";\n      send_to_math(command);\n      get_from_math(default_is_list);\n\n      // If there's no 'DefaultInputValues' list, try \n      // DefaultInputValues[1] -- sometimes models have\n      // different benchmark points. \n      if(default_is_list)\n      {\n        defaultlist = \"DefaultInputValues\";\n      }\n      else\n      {\n        bool please_be_list;\n        command = \"Head[DefaultInputValues[1]]===List\";\n        send_to_math(command);\n        get_from_math(please_be_list);\n        if(please_be_list)\n        {\n          defaultlist = \"DefaultInputValues[1]\";\n        }\n        else\n        {\n          defaultlist = \"NONE\";\n        }\n      }\n\n      if(is_list)\n      {\n        // Get the MINPAR list\n        command = \"MINPAR\";\n        send_to_math(command);\n        get_from_math(minpar);\n\n        // Add MINPAR parameters to the parameter list\n        for(std::vector<std::string> par : minpar)\n        {\n          // Query the parameter list, as the MINPAR entry may end up being a BC already,\n          // such as TanBeta. Then we should find out if it's real or not.\n          std::string paramname;\n          bool real = false;\n          for (int i=0; i<lenpl; i++)\n          {\n            command = \"pdgum[[\" + std::to_string(i+1) + \",1]] // ToString\";\n            send_to_math(command);\n            get_from_math(paramname);\n\n            if(par[1] == paramname)\n            {\n              command = \"Real /. pdgum[[\" + std::to_string(i+1) + \", 2]] // ToString\";\n              send_to_math(command);\n              std::string entry;\n              get_from_math(entry);\n              if(entry == \"True\") real = true;\n            }\n          }\n          \n          Parameter param(par[1], \"MINPAR\", std::stoi(par[0]), par[1], real);\n \n          // Get default values (if there are any)\n          if (defaultlist != \"NONE\")\n          {\n            std::string value;\n            command = par[1] + \"/.\" + defaultlist;\n            send_to_math(command);\n            get_from_math(value);\n            if(value != par[1])\n              param.set_default(std::stod(value));\n          }\n\n          parameters.push_back(param);\n        }\n      }\n\n      // Check if EXTPAR is a list\n      command = \"Head[EXTPAR]===List\";\n      send_to_math(command);\n      get_from_math(is_list);\n\n      if(is_list)\n      {\n        // Get the EXTPAR list\n        command = \"EXTPAR\";\n        send_to_math(command);\n        get_from_math(extpar);\n\n        // Add EXTPAR parameters to the parameter list\n        for(std::vector<std::string> par : extpar)\n        {\n          // Query the parameter list, as the EXTPAR entry may end up being a BC already,\n          // such as TanBeta. Then we should find out if it's real or not.\n          std::string paramname;\n          bool real = false;\n          for (int i=0; i<lenpl; i++)\n          {\n            command = \"pdgum[[\" + std::to_string(i+1) + \",1]] // ToString\";\n            send_to_math(command);\n            get_from_math(paramname);\n\n            if(par[1] == paramname)\n            {\n              command = \"Real /. pdgum[[\" + std::to_string(i+1) + \", 2]] // ToString\";\n              std::cout << command << std::endl;\n              send_to_math(command);\n              std::string entry;\n              get_from_math(entry);\n              if(entry == \"True\") real = true;\n            }\n          }\n          Parameter param(par[1], \"EXTPAR\", std::stoi(par[0]), par[1], real);\n\n          // Get default values (if there are any)\n          if (defaultlist != \"NONE\")\n          {\n            std::string value;\n            command = par[1] + \"/.\" + defaultlist;\n            send_to_math(command);\n            get_from_math(value);\n            if(value != par[1])\n              param.set_default(std::stod(value));\n          }\n\n          parameters.push_back(param);\n        }\n      }\n\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n\n  }\n\n  // Get the blocks, entries and parameter names of the in-out blocks\n  void SARAH::get_inout_blocks(std::vector<Parameter> &parameters)\n  {\n    std::cout << \"Extracting in-out blocks from SPheno\" << std::endl;\n\n    std::string command = \"\";\n\n    try\n    {\n\n      // Get the length of the CombindedBlock, as the shape is not a vector<string>\n      int length;\n      command = \"Length[CombindedBlock]\";\n      send_to_math(command);\n      get_from_math(length);\n\n      for(int i=1; i<=length; i++)\n      {\n        // Get the name of the block\n        std::string blockname;\n        command = \"CombindedBlock[[\"+std::to_string(i)+\",1]]\";\n        send_to_math(command);\n        get_from_math(blockname);\n        blockname = blockname + \"IN\";\n\n        // Now get the parameters in the block\n        int block_length;\n        command = \"Length[CombindedBlock[[\"+std::to_string(i)+\"]]]\";\n        send_to_math(command);\n        get_from_math(block_length);\n\n        for(int j=2; j<=block_length; j++)\n        {\n\n          std::string parname;\n          command = \"CombindedBlock[[\"+std::to_string(i)+\",\"+std::to_string(j)+\",1]] // ToString\";\n          send_to_math(command);\n          get_from_math(parname);\n\n          std::string parindex;\n          command = \"CombindedBlock[[\"+std::to_string(i)+\",\"+std::to_string(j)+\",2]]\";\n          send_to_math(command);\n          get_from_math(parindex);\n\n          // Get the output name and remove params that have dependencies\n          int pdlength;\n          command = \"Length[pdgum]\";\n          send_to_math(command);\n          get_from_math(pdlength);\n\n          for(int j=1; j<=pdlength; j++)\n          {\n            std::string name;\n            command = \"pdgum[[\"+std::to_string(j)+\",1]]//ToString\";\n            send_to_math(command);\n            get_from_math(name);\n\n            if(name == parname)\n            {\n              std::string entry;\n\n              command = \"DependenceNum /. pdgum[[\" + std::to_string(j) + \",2]] // ToString\";\n              send_to_math(command);\n              get_from_math(entry);\n              if (entry != \"DependenceNum\" and entry != \"None\") continue;\n\n              command = \"DependenceSPheno /. pdgum[[\" + std::to_string(j) + \",2]] // ToString\";\n              send_to_math(command);\n              get_from_math(entry);\n              if (entry != \"DependenceSPheno\" and entry != \"None\") continue;\n\n              command = \"Dependence /. pdgum[[\" + std::to_string(j) + \",2]] // ToString\";\n              send_to_math(command);\n              get_from_math(entry);\n              if (entry != \"Dependence\" and entry != \"None\") continue;\n\n              std::string outputname;\n              command = \"OutputName /. pdgum[[\" + std::to_string(j) + \",2]] // ToString\";\n              send_to_math(command);\n              get_from_math(outputname);\n              if(outputname == \"OutputName\") outputname = parname;\n\n              bool real = false;\n              command = \"Real /. pdgum[[\" + std::to_string(j) + \", 2]] // ToString\";\n              send_to_math(command);\n              get_from_math(entry);\n              if(entry == \"True\") real = true;\n\n              parameters.push_back(Parameter(outputname, blockname, std::stoi(parindex), outputname, real));\n\n            }\n          }\n        }\n\n      }\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Get the boundary conditions for all parameters in the parameter list\n  void SARAH::get_boundary_conditions(std::map<std::string, std::string> &bcs, \n                                      std::vector<Parameter> parameters)\n  {\n    std::cout << \"Getting boundary conditions\" << std::endl;\n\n    std::string command = \"\";\n\n    try\n    {\n      // TODO: Expand this for other types of boundary conditions \n      int bc_len;\n      command = \"Length[BoundaryLowScaleInput]\";\n      send_to_math(command);\n      get_from_math(bc_len);\n      for(int i=1; i<=bc_len; i++)\n      {\n        std::string bc_name;\n        command = \"BoundaryLowScaleInput[[\"+std::to_string(i)+\",1]] // ToString\";\n        send_to_math(command);\n        get_from_math(bc_name);\n\n        std::string bc;\n        command = \"BoundaryLowScaleInput[[\"+std::to_string(i)+\",2]] // ToString\";\n        send_to_math(command);\n        get_from_math(bc);\n\n        for(auto param = parameters.begin(); param != parameters.end(); param++)\n        {\n          if (param->name() == bc_name or param->alt_name() == bc_name)\n          {\n              bcs[bc] = param->name();\n          }\n        }\n      }\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Extract parameters used to solve tadpoles and mark them as output\n  void SARAH::get_tadpoles(std::vector<Parameter> &parameters)\n  {\n    std::cout << \"Extracting parameters to solve tadpoles\" << std::endl;\n\n    std::string command = \"\";\n\n    try\n    {\n      bool is_list; \n      command = \"Head[ParametersToSolveTadpoles]===List\";\n      send_to_math(command);\n      get_from_math(is_list);\n      if(is_list)\n      {\n        std::vector<std::string> tadpoles;\n        command = \"ParametersToSolveTadpoles\";\n        send_to_math(command);\n        get_from_math(tadpoles);\n\n        for(auto param = parameters.begin(); param != parameters.end(); param++)\n          for(auto tp : tadpoles)\n            if (param->name() == tp or param->alt_name() == tp)\n            {\n              param->set_output(true);\n            }\n      }\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Add the names of spheno masses to all particles\n  void SARAH::add_SPheno_mass_names(std::vector<Particle> &particles)\n  {\n    std::cout << \"Adding SPheno masses\" << std::endl;\n\n    std::string command = \"\";\n\n    try\n    {\n      std::vector<Particle> newParticles;\n      for (auto part = particles.begin(); part != particles.end(); part++)\n      {\n        std::string sarah_mass;\n\n        command = \"SPhenoMass[\" + part->alt_name() + \"]\";\n        send_to_math(command);\n        get_from_math(sarah_mass);\n\n        newParticles.push_back(Particle(part->pdg(), part->name(), part->spinX2(), part->chargeX3(), part->color(), part->SM(), part->mass(), part->antiname(), part->alt_name(), sarah_mass, part->tree_mass()));\n      }\n      particles = newParticles;\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Leave only the parameters that SPheno uses\n  void SARAH::SPheno_parameters(std::vector<Parameter> &parameters)\n  {\n    std::cout << \"Getting SPheno parameters\" << std::endl;\n\n    std::string command;\n\n    try\n    {\n      bool is_list;\n      std::vector<std::string> SPhenoparams;\n      std::vector<std::string> SPhenomassparams;\n      std::vector<std::string> MCparams;\n      std::vector<std::string> MCvars;\n\n      // Get the list of parameters and vevs used by SPheno\n      command = \"Head[listAllParametersAndVEVs]===List\";\n      send_to_math(command);\n      get_from_math(is_list);\n      if(is_list)\n      {\n        command = \"SPhenoForm/@listAllParametersAndVEVs\";\n        send_to_math(command);\n        get_from_math(SPhenoparams);\n\n      }\n\n      // Get the mixing parameters\n      command = \"Head[NewMassParameters]===List\";\n      send_to_math(command);\n      get_from_math(is_list);\n      if(is_list)\n      {\n        command = \"SPhenoForm/@NewMassParameters\";\n        send_to_math(command);\n        get_from_math(SPhenomassparams);\n      }\n\n      // Check if any of the parameters have a matching condition\n      command = \"mcgum = DEFINITION[MatchingConditions]\";\n      send_to_math(command);\n \n      int size = 0;\n      command = \"Length[mcgum]\";\n      send_to_math(command);\n      get_from_math(size);\n      for(int i=1; i<=size; i++)\n      {\n        std::string par;\n        command = \"mcgum[[\" + std::to_string(i) + \",1]]\";\n        send_to_math(command);\n        get_from_math(par);\n        MCparams.push_back(par);\n\n        std::vector<std::string> vars;\n        command = \"Variables[mcgum[[\" + std::to_string(i) + \",2]]]\";\n        send_to_math(command);\n        get_from_math(vars);\n        MCvars.insert(MCvars.end(),vars.begin(), vars.end());\n      }\n\n      std::vector<Parameter> newParameters;\n      for(auto param : parameters)\n      {\n\n        for(auto mcv: MCvars)\n        {\n          if(param.name() == mcv or param.alt_name() == mcv)\n          {\n            if(std::find(SPhenoparams.begin(), SPhenoparams.end(), param.name()) == SPhenoparams.end() and\n               std::find(SPhenoparams.begin(), SPhenoparams.end(), param.alt_name()) == SPhenoparams.end())\n            {\n              // If the param is in the matching conditions, we always want the name in the matching conditions\n              SPhenoparams.push_back(mcv);\n            }\n          }\n        }\n\n        for(auto SPhenoparam :  SPhenoparams)\n        {\n          if(param.name() == SPhenoparam or param.alt_name() == SPhenoparam)\n          {\n            bool is_output = param.is_output();\n            if(std::find(MCparams.begin(), MCparams.end(), param.name()) != MCparams.end() or\n               std::find(MCparams.begin(), MCparams.end(), param.alt_name()) != MCparams.end())\n              is_output = true;\n            newParameters.push_back(Parameter(SPhenoparam, param.block(), param.index(), param.alt_name(), param.is_real(), param.shape(), is_output, param.bcs()));\n          }\n        }\n\n        for(auto SPhenomassparam :  SPhenomassparams)\n        {\n          if(param.name() == SPhenomassparam or param.alt_name() == SPhenomassparam)\n          {\n            newParameters.push_back(Parameter(SPhenomassparam, param.block(), param.index(), param.alt_name(), param.is_real(), param.shape(), param.is_output(), param.bcs()));\n          }\n        }\n      }\n\n      parameters = newParameters;\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Returns the eigenstate & mixing matrix after EWSB \n  void SARAH::get_mixing_matrices(std::map<std::string, std::string> &mixings)\n  {\n    std::cout << \"Getting mixing matrices from SARAH...\" << std::endl;\n\n    std::string command = \"\";\n\n    try\n    {\n      command = \"dgum = DEFINITION[EWSB][MatterSector];\";\n      send_to_math(command);\n\n      // Find out how many (sets of) mixing matrices there are...\n      int len;\n      command = \"Length[dgum]\";\n      send_to_math(command);\n      get_from_math(len);\n  \n      for(int i=1; i<=len; i++)\n      {\n        std::vector<std::string> eigenpairs;\n        // Make this one list, easier to parse\n        command = \"agum = Flatten[dgum[[\" + std::to_string(i) + \",2]]]\";\n        send_to_math(command);\n        get_from_math(eigenpairs);\n\n        // Check we haven't got additional entries\n        int size = eigenpairs.size();\n\n        if(size % 2)\n          throw std::runtime_error(\"Not an even number of matrix-eigenstate pairs! Check your SARAH file.\");\n\n        // List should look like: {<EIGENSTATE_1>, <MIXING_MATRIX_1>, <EIGENSTATE_2>, <MIXING_MATRIX_2>, ...}\n        for(int i=0; i<size; i++)\n        {\n          std::string eigenstate = eigenpairs[i];\n          std::string mixingmat = eigenpairs[i+1];\n \n          int len2;\n\n          // Check to see if the particle name is a Weyl fermion\n          bool is_weyl;\n          command = \"MemberQ[WeylFermionAndIndermediate[[;;,1]],\"+eigenstate+\"]\";\n          send_to_math(command);\n          get_from_math(is_weyl);\n\n          // If it's a Weyl fermion, get the Dirac fermion\n          if(is_weyl)\n          {\n            command = \"Select[DEFINITION[EWSB][DiracSpinors], MemberQ[#[[2]],\"+eigenstate+\", 2] &][[1,1]]\";\n            send_to_math(command);\n            get_from_math(eigenstate);\n          }\n\n          // Check to see if the mixing matrix has a different OutputName\n          command = \"Length[pdgum]\";\n          send_to_math(command);\n          get_from_math(len2);\n          \n          for(int j=0; j<len2; j++)\n          {\n            std::string pname;\n            command = \"pdgum[[\" + std::to_string(j+1) + \",1]] // ToString\";\n            send_to_math(command);\n            get_from_math(pname);\n\n            if(pname == mixingmat)\n            {\n              std::string oname;\n              command = \"OutputName /. pdgum[[\" + std::to_string(j+1) + \",2]] // ToString\";\n              send_to_math(command);\n              get_from_math(oname);\n\n              if(oname == \"OutputName\")\n              {\n                mixings[mixingmat] = eigenstate;\n              }\n              else\n              {\n               mixings[oname] = eigenstate;\n              }\n              continue;\n            }\n          }\n          // Increment again; need to do +2 each iteration.\n          i++;\n        }\n      }\n    }\n    catch (std::runtime_error &e)\n    {\n      std::stringstream ss;\n      ss << e.what() << \": Last command: \" << command;\n      throw std::runtime_error(ss.str());\n    }\n  }\n\n  // Write CalcHEP output.\n  void SARAH::write_ch_output()\n  {\n    std::cout << \"Writing CalcHEP output.\" << std::endl;\n\n    // Options for the CH output.\n    std::string options;\n    // This is currently hard-coded, because GAMBIT needs to interface with CalcHEP \n    // in a specific way.\n    /* do not read from SLHA file |  let alphaS run  |  all masses computed externally */\n    options = \"SLHAinput -> False, UseRunningCoupling -> True, CalculateMasses -> False\";\n\n    // Write output.\n    std::string command = \"MakeCHep[\" + options + \"];\";\n    send_to_math(command);\n\n    std::cout << \"CalcHEP files written.\" << std::endl;\n  }\n\n  // Write MadGraph output.\n  void SARAH::write_madgraph_output()\n  {\n    std::cout << \"Writing MadGraph (UFO) output for Pythia/MadDM.\" << std::endl;\n\n    // Write output.\n    std::string command = \"MakeUFO[];\";\n    send_to_math(command);\n\n    std::cout << \"MadGraph files written.\" << std::endl;\n  }\n\n  // Write SPheno output.\n  void SARAH::write_spheno_output(std::map<std::string,std::string> options)\n  {\n      std::cout << \"Writing SPheno output.\" << std::endl;\n      std::cout << \"Strap in tight -- this might take a while...\" << std::endl;\n      \n      // Options for SPheno output.\n      std::string SPhenoOptions = \"\";\n      // - InputFile (default $MODEL/SPheno.m)\n      // - StandardCompiler -> <COMPILER> (default gfortran) // TG: This should be handled by GM cmake system, so no need\n      // - IncludeLoopDecays (default True)\n      // - ReadLists (default False) \n      // - IncludeFlavourKit (default True but we set it to False cause FlavourKit will be a different backend)\n      //options = \"IncludeLoopDecays->False, IncludeFlavorKit->False, ReadLists->True\";\n      for(auto it = options.begin(); it != options.end(); it++)\n      {\n        SPhenoOptions += it->first + \"->\" + it->second + \", \";\n      }\n      SPhenoOptions += \"IncludeFlavorKit->False\";\n\n      std::cout << \"Options for SPheno given as: \" << SPhenoOptions << std::endl;\n\n      // Write output.\n      std::string command = \"MakeSPheno[\" + SPhenoOptions + \"];\";\n      send_to_math(command);\n\n      std::cout << \"SPheno files written.\" << std::endl;\n  }\n\n  // Write Vevacious output.\n  void SARAH::write_vevacious_output()\n  {\n      std::cout << \"Writing Vevacious output.\" << std::endl;  \n\n      // Options for Vevacious output.\n      std::string options;\n      options = \"Version->\\\"++\\\", ReadLists->True\";\n\n      // Write output.\n      std::string command = \"MakeVevacious[\" + options + \"];\";\n      send_to_math(command);  \n\n      std::cout << \"Vevacious files written.\" << std::endl;\n  }\n\n  // Do all operations with SARAH\n  void all_sarah(Options opts, std::vector<Particle> &partlist, std::vector<Parameter> &paramlist,\n                 Outputs &outputs, std::vector<std::string> &backends,\n                 std::map<std::string,bool> &flags, std::map<std::string, std::string> &mixings,\n                 std::map<std::string, std::string> &bcs,\n                 std::vector<Parameter> &sphenodependences, Error &error)\n  {\n\n    try\n    {\n      std::cout << \"Calling SARAH with model \" << opts.model() << \"...\" << std::endl;\n\n      // Create SARAH object, open link to Mathematica, load SARAH and the model\n      SARAH model(opts.model());\n\n      // Get the options to pass to backends\n      std::map<std::string, std::map<std::string, std::string> > BEoptions = opts.options();\n\n      // Check the model using SARAH's CheckModel function\n      // Note: this is necessary, as it initilizes some variables used later, do not remove\n      model.check_model(opts.model(), backends);\n\n      // Get all of the particles\n      model.get_partlist(partlist);\n\n      // And all parameters\n      model.get_paramlist(paramlist, sphenodependences);\n\n      // And mixings\n      model.get_mixing_matrices(mixings);\n\n      // Where the outputs all live\n      std::string outputdir = std::string(SARAH_PATH) + \"/Output/\" + opts.model() + \"/EWSB/\";\n\n      /// Write CalcHEP output (for MicrOmegas also)\n      if (std::find(backends.begin(), backends.end(), \"calchep\") != backends.end()   ||\n          std::find(backends.begin(), backends.end(), \"micromegas\") != backends.end() )\n      {\n        model.write_ch_output();\n\n        // Location of CalcHEP files\n        std::string chdir = outputdir + \"CHep\";\n        std::replace(chdir.begin(), chdir.end(), ' ', '-');\n        outputs.set_ch(chdir);\n      }\n \n      /// Write MadGraph output\n      if (std::find(backends.begin(), backends.end(), \"pythia\") != backends.end() ||\n          std::find(backends.begin(), backends.end(), \"ufo\") != backends.end() )\n      {\n        model.write_madgraph_output();\n\n        // Location of MadGraph (UFO) files\n        std::string mgdir = outputdir + \"UFO\";\n        std::replace(mgdir.begin(), mgdir.end(), ' ', '-');\n        outputs.set_mg(mgdir);\n      }\n\n      /// Write SPheno output\n      if (std::find(backends.begin(), backends.end(), \"spheno\") != backends.end() )\n      {\n       \n        std::map<std::string, std::string> sphenoopts;\n\n        // If there's SPheno options in the map, pass them over...\n        if ( BEoptions.find(\"spheno\") != BEoptions.end() ) \n        {\n          sphenoopts = BEoptions.at(\"spheno\");\n        }\n\n        model.write_spheno_output(sphenoopts);\n\n        // Leave only the parameters that SPheno uses\n        model.SPheno_parameters(paramlist);\n \n        // Get minpar and extpar parameters\n        model.get_minpar_extpar(paramlist);\n\n        // Get useful SPheno flags, default to False\n        flags = {\n          {\"SupersymmetricModel\",false}, \n          {\"OnlyLowEnergySPheno\", false},\n          {\"UseHiggs2LoopMSSM\", false},\n          {\"SA`AddOneLoopDecay\", false}\n        };\n        model.get_flags(flags);\n\n        // Get the boundary conditions for the parameters\n        model.get_boundary_conditions(bcs, paramlist);\n\n        // Get the parameters used to solve tadpoles and remove them from the list\n        model.get_tadpoles(paramlist);\n\n        // Get in-out blocks\n        model.get_inout_blocks(paramlist);\n\n        // Add SPheno mass names for all particles\n        model.add_SPheno_mass_names(partlist);\n\n        // Location of SPheno files\n        std::string sphdir = outputdir + \"SPheno\";\n        std::replace(sphdir.begin(), sphdir.end(), ' ', '-');\n        outputs.set_sph(sphdir);\n      }\n\n\n      /// Write Vevacious output\n      if (std::find(backends.begin(), backends.end(), \"vevacious\") != backends.end() )\n      {\n        model.write_vevacious_output();        \n\n        // Location of Vevacious (.vin + .xml) files\n        // Note these do not live in the same place the other output files do.\n        std::string vevdir = std::string(SARAH_PATH) + \"/Output/\" + opts.model() + \"/Vevacious\";\n        std::replace(vevdir.begin(), vevdir.end(), ' ', '-');\n        outputs.set_vev(vevdir);\n      }\n\n    }\n    catch(std::exception &e)\n    {\n      error.raise(\"SARAH Error: \" + std::string(e.what()));\n    }\n  }\n\n   \n} // namespace GUM\n\n// Now all the grizzly stuff, so Python can call C++ (which can call Mathematica...)\nusing namespace boost::python;\n\n// Nasty function to translate python dictionaries to maps\nobject setOptions(tuple args, dict kwargs)\n{\n    Options& self = extract<Options&>(args[0]);\n\n    list keys = kwargs.keys();\n\n    std::map<std::string,std::map<std::string,std::string> > outMap;\n    for(int i = 0; i < len(keys); ++i)\n    {\n        dict secondLayer = extract<dict>(kwargs[keys[i]]);\n        list keys2 = secondLayer.keys();\n\n        std::map<std::string,std::string> tempMap;\n        for(int j=0; j < len(keys2); ++j)\n        {\n          std::string value = extract<std::string>(str(secondLayer[keys2[j]]));\n          tempMap[extract<std::string>(keys2[j])] = value;\n        }\n        outMap[extract<std::string>(keys[i])] = tempMap;\n    }\n    self.setOptions(outMap);\n\n    return object();\n}\n\nBOOST_PYTHON_MODULE(libsarah)\n{\n\n  class_<Particle>(\"SARAHParticle\", init<int, std::string, int, int, int, bool, std::string, std::string, std::string, std::string, std::string>())\n    .def(\"pdg\",      &Particle::pdg)\n    .def(\"name\",     &Particle::name)\n    .def(\"SM\",       &Particle::SM)\n    .def(\"spinX2\",   &Particle::spinX2)\n    .def(\"chargeX3\", &Particle::chargeX3)\n    .def(\"color\",    &Particle::color)\n    .def(\"mass\",     &Particle::mass)\n    .def(\"SC\",       &Particle::SC)\n    .def(\"antiname\", &Particle::antiname)\n    .def(\"alt_name\", &Particle::alt_name)\n    .def(\"alt_mass\", &Particle::alt_mass)\n    .def(\"tree_mass\", &Particle::tree_mass)\n    ;\n\n  class_<Parameter>(\"SARAHParameter\", init<std::string, std::string, int, std::string, bool, std::string, bool, std::string>())\n    .def(\"name\",      &Parameter::name)\n    .def(\"block\",     &Parameter::block)\n    .def(\"index\",     &Parameter::index)\n    .def(\"alt_name\",  &Parameter::alt_name)\n    .def(\"is_real\",   &Parameter::is_real)\n    .def(\"shape\",     &Parameter::shape)\n    .def(\"is_output\", &Parameter::is_output)\n    .def(\"bcs\",       &Parameter::bcs)\n    .def(\"defvalue\",  &Parameter::defvalue)\n    ;\n\n  class_<Options>(\"SARAHOptions\", init<std::string, std::string>())\n    .def(\"package\",     &Options::package)\n    .def(\"model\",       &Options::model)\n    .def(\"setOptions\",  raw_function(&setOptions,1))\n    ;\n\n  class_<Outputs>(\"SARAHOutputs\", init<>())\n    .def(\"get_ch\",   &Outputs::get_ch)\n    .def(\"get_mg\",   &Outputs::get_mg)\n    .def(\"get_sph\",  &Outputs::get_sph)\n    .def(\"get_vev\",  &Outputs::get_vev)    \n    .def(\"set_ch\",   &Outputs::set_ch)\n    .def(\"set_mg\",   &Outputs::set_mg)\n    .def(\"set_sph\",  &Outputs::set_sph)\n    .def(\"set_vev\",  &Outputs::set_vev)\n    ;\n\n  class_<Error>(\"SARAHError\", init<>())\n    .def(\"is_error\", &Error::is_error)\n    .def(\"what\", &Error::what)\n    ;\n\n  class_< std::vector<Particle> >(\"SARAHVectorOfParticles\")\n    .def(vector_indexing_suite< std::vector<Particle> >() )\n    ;\n\n  class_< std::vector<Parameter> >(\"SARAHVectorOfParameters\")\n    .def(vector_indexing_suite< std::vector<Parameter> >() )\n    ;\n\n  class_< std::map<std::string,bool> >(\"SARAHMapStrBool\")\n    .def(map_indexing_suite< std::map<std::string,bool> >() )\n    ;\n\n  class_< std::vector<std::string> >(\"SARAHBackends\")\n    .def(vector_indexing_suite< std::vector<std::string> >() )\n    ;\n\n  class_< std::map<std::string, std::string> >(\"SARAHMapStrStr\")\n    .def(map_indexing_suite< std::map<std::string, std::string>, true>() )\n    ;\n\n  def(\"all_sarah\", GUM::all_sarah);\n\n}\n", "meta": {"hexsha": "8fe80699c15fff04e09b6d5bccf3857bbe7502b0", "size": 60089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gum/src/sarah.cpp", "max_stars_repo_name": "GambitBSM/gambit_2.0", "max_stars_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T22:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T22:53:26.000Z", "max_issues_repo_path": "gum/src/sarah.cpp", "max_issues_repo_name": "GambitBSM/gambit_2.0", "max_issues_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T11:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T17:24:41.000Z", "max_forks_repo_path": "gum/src/sarah.cpp", "max_forks_repo_name": "GambitBSM/gambit_2.0", "max_forks_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:31:41.000Z", "avg_line_length": 34.2778094695, "max_line_length": 210, "alphanum_fraction": 0.5579390571, "num_tokens": 15080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.16814652892877885}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_CompleteDopplerBroadenedPhotonEnergyDistribution.hpp\n//! \\author Alex Robinson\n//! \\brief  The complete Doppler broadened photon energy distribution decl.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n#define MONTE_CARLO_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n\n// Boost Includes\n#include <boost/scoped_ptr.hpp>\n\n// FRENSIE Includes\n#include <Teuchos_Array.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_DopplerBroadenedPhotonEnergyDistribution.hpp\"\n#include \"MonteCarlo_SubshellType.hpp\"\n#include \"Utility_TabularOneDDistribution.hpp\"\n\nnamespace MonteCarlo{\n\n//! The complete (all subshells) Doppler broadened photon energy dist. class\nclass CompleteDopplerBroadenedPhotonEnergyDistribution : public DopplerBroadenedPhotonEnergyDistribution\n{\n\npublic:\n\n  //! Constructor\n  CompleteDopplerBroadenedPhotonEnergyDistribution(\n\t\t     const Teuchos::Array<double>& endf_subshell_occupancies,\n\t\t     const Teuchos::Array<SubshellType>& endf_subshell_order );\n\n  //! Destructor\n  virtual ~CompleteDopplerBroadenedPhotonEnergyDistribution()\n  { /* ... */ }\n\n  //! Evaluate the subshell distribution\n  virtual double evaluateSubshell( const double incoming_energy,\n\t\t\t\t   const double outgoing_energy,\n\t\t\t\t   const double scattering_angle_cosine,\n\t\t\t\t   const SubshellType subshell ) const = 0;\n\n  //! Evaluate the PDF\n  virtual double evaluateSubshellPDF( const double incoming_energy,\n\t\t\t\t      const double outgoing_energy,\n\t\t\t\t      const double scattering_angle_cosine,\n\t\t\t\t      const SubshellType subshell ) const = 0;\n\n  //! Evaluate the integrated cross section (b/mu)\n  virtual double evaluateSubshellIntegratedCrossSection( \n\t\t\t\t          const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const SubshellType subshell,\n\t\t\t\t\t  const double precision ) const = 0;\n\nprotected:\n  \n  // Sample an ENDF subshell\n  void sampleENDFInteractionSubshell( SubshellType& shell_of_interaction,\n\t\t\t\t      unsigned& shell_index ) const;\n\nprivate:\n\n  // The ENDF subshell interaction probabilities\n  boost::scoped_ptr<const Utility::TabularOneDDistribution>\n  d_endf_subshell_occupancy_distribution;\n\n  // The ENDF subshell order\n  Teuchos::Array<SubshellType> d_endf_subshell_order;\n};\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_CompleteDopplerBroadenedPhotonEnergyDistribution.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "9ea5ff5fb9ccd47f5ccceedba3fbb74bde5086f5", "size": 2794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_CompleteDopplerBroadenedPhotonEnergyDistribution.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/monte_carlo/collision/native/src/MonteCarlo_CompleteDopplerBroadenedPhotonEnergyDistribution.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/monte_carlo/collision/native/src/MonteCarlo_CompleteDopplerBroadenedPhotonEnergyDistribution.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": 34.0731707317, "max_line_length": 104, "alphanum_fraction": 0.6954187545, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.16814652892877882}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cstring>\n#include <limits>\n#include <mpi.h>\n//#include <Eigen/Eigenvalues>\n\nenum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};\n\n#include \"particle_simulator.hpp\"\n#include \"hdr_time.hpp\"\n#include \"hdr_run.hpp\"\n#ifdef USE_INTRINSICS\n#include \"vector_x86.hpp\"\n#endif\n#include \"hdr_dimension.hpp\"\n#include \"hdr_kernel.hpp\"\n#include \"hdr_sph.hpp\"\n#include \"hdr_hgas.hpp\"\n#include \"hdr_bhns.hpp\"\n\nclass SPHAnalysis : public HelmholtzGas {\npublic:\n    SPHAnalysis() {\n        this->id    = 0;\n        this->istar = 0;\n        this->mass  = 0.;\n        this->pos   = 0.;\n        this->vel   = 0.;\n        this->uene  = 0.;\n        this->alph  = 0.;\n        this->alphu = 0.;\n        this->ksr   = 0.;\n        for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->cmps[k] = 0.;\n        }        \n    }\n\n    void readAscii(FILE * fp) {\n        fscanf(fp, \"%lld%lld%lf\", &this->id, &this->istar, &this->mass);      //  3\n        fscanf(fp, \"%lf%lf%lf\", &this->pos[0], &this->pos[1], &this->pos[2]); //  6\n        fscanf(fp, \"%lf%lf%lf\", &this->vel[0], &this->vel[1], &this->vel[2]); //  9\n        fscanf(fp, \"%lf%lf%lf\", &this->acc[0], &this->acc[1], &this->acc[2]); // 12\n        fscanf(fp, \"%lf%lf%lf\", &this->uene, &this->alph, &this->alphu);      // 15\n        fscanf(fp, \"%lf%lf%6d\", &this->dens, &this->ksr,  &this->np);         // 18\n        fscanf(fp, \"%lf%lf%lf\", &this->vsnd, &this->pres, &this->temp);       // 21\n        fscanf(fp, \"%lf%lf%lf\", &this->divv, &this->rotv, &this->bswt);       // 24\n        fscanf(fp, \"%lf%lf%lf\", &this->pot,  &this->abar, &this->zbar);       // 27\n        fscanf(fp, \"%lf\",       &this->enuc);                                 // 28\n        fscanf(fp, \"%lf%lf%lf\", &this->vsmx, &this->udot, &this->dnuc);       // 31\n        for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) {       // 32 -- 44\n            fscanf(fp, \"%lf\", &this->cmps[k]);\n        }\n        fscanf(fp, \"%lf\", &this->pot3);\n        fscanf(fp, \"%lf%lf%lf\", &this->tempmax[0], &this->tempmax[1], &this->tempmax[2]);\n        fscanf(fp, \"%lf\", &this->entr);\n    }\n\n    void writeAscii(FILE *fp) const {\n        fprintf(fp, \"%6d %2d %+e\", this->id, this->istar, this->mass);\n        fprintf(fp, \" %+e %+e %+e\", this->pos[0], this->pos[1], this->pos[2]);\n        fprintf(fp, \" %+e %+e %+e\", this->vel[0], this->vel[1], this->vel[2]);\n        fprintf(fp, \" %+e %+e %+e\", this->acc[0], this->acc[1], this->acc[2]);\n        fprintf(fp, \" %+e %+e %+e\", this->uene, this->alph, this->alphu);\n        fprintf(fp, \" %+e %+e %6d\", this->dens, this->ksr,  this->np);\n        fprintf(fp, \" %+e %+e %+e\", this->vsnd, this->pres, this->temp);\n        fprintf(fp, \" %+e %+e %+e\", this->divv, this->rotv, this->bswt);\n        fprintf(fp, \" %+e %+e %+e\", this->pot, this->abar, this->zbar);\n        fprintf(fp, \" %+e\",         this->enuc);\n        fprintf(fp, \" %+e %+e %+e\", this->vsmx, this->udot, this->dnuc);\n        for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) {\n            fprintf(fp, \" %+.3e\", this->cmps[k]);\n        }\n        fprintf(fp, \" %+e\", this->pot3);\n        fprintf(fp, \" %+e %+e %+e\", this->tempmax[0], this->tempmax[1], this->tempmax[2]);\n        fprintf(fp, \" %+e\", this->entr);\n        fprintf(fp, \"\\n\");\n    }\n\n    inline PS::F64mat calcMomentOfInertia(PS::F64vec xc) {\n        PS::F64mat qq = 0.;\n        PS::F64vec dx = this->pos - xc;\n        PS::F64 r2 = dx * dx;\n        qq.xx = this->mass * (r2 - dx[0] * dx[0]);\n        qq.xy = this->mass * (   - dx[0] * dx[1]);\n        qq.xz = this->mass * (   - dx[0] * dx[2]);\n        qq.yy = this->mass * (r2 - dx[1] * dx[1]);\n        qq.yz = this->mass * (   - dx[1] * dx[2]);\n        qq.zz = this->mass * (r2 - dx[2] * dx[2]);\n        return qq;\n    }\n};\n\n\nclass BlackHoleNeutronStarAnalysis : public BlackHoleNeutronStar {\npublic:\n    BlackHoleNeutronStarAnalysis() {\n        this->id    = 0;\n        this->istar = 0;\n        this->mass  = 0.;\n        this->pos   = 0.;\n        this->vel   = 0.;\n        this->acc   = 0.;\n        this->eps   = 0.;\n        this->pot   = 0.;\n    }\n\n    void readAscii(FILE * fp) {\n        fscanf(fp, \"%lld%lld%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf\",\n               &this->id, &this->istar, &this->mass,\n               &this->pos[0], &this->pos[1], &this->pos[2],\n               &this->vel[0], &this->vel[1], &this->vel[2],\n               &this->acc[0], &this->acc[1], &this->acc[2],\n               &this->eps, &this->pot);\n    }\n\n    inline PS::F64mat calcMomentOfInertia(PS::F64vec xc) {\n        PS::F64mat qq = 0.;\n        PS::F64vec dx = this->pos - xc;\n        PS::F64 r2 = dx * dx;\n        qq.xx = this->mass * (r2 - dx[0] * dx[0]);\n        qq.xy = this->mass * (   - dx[0] * dx[1]);\n        qq.xz = this->mass * (   - dx[0] * dx[2]);\n        qq.yy = this->mass * (r2 - dx[1] * dx[1]);\n        qq.yz = this->mass * (   - dx[1] * dx[2]);\n        qq.zz = this->mass * (r2 - dx[2] * dx[2]);\n        return qq;\n    }\n};\n\ntemplate <class Tsph,\n          class Tbhns>\nvoid projectOnOrbitalPlane(char * ofile,\n                           Tsph  & sph,\n                           Tbhns & bhns,\n                           PS::F64vec xmin,\n                           PS::F64    wdth,\n                           PS::S64    nmax) {\n\n    PS::F64 dx    = wdth / (PS::F64)nmax;\n    PS::F64 dxinv = 1. / dx;\n\n#if 1\n    PS::S64 **ptcl;\n    PS::F64 **dens;\n    PS::F64 **temp;\n    PS::F64 **divv;\n    ptcl = (PS::S64 **) malloc(sizeof(PS::S64 *) * nmax);\n    dens = (PS::F64 **) malloc(sizeof(PS::F64 *) * nmax);\n    temp = (PS::F64 **) malloc(sizeof(PS::F64 *) * nmax);\n    divv = (PS::F64 **) malloc(sizeof(PS::F64 *) * nmax);\n    for(PS::S64 i = 0; i < nmax; i++) {\n        ptcl[i] = (PS::S64 *) malloc(sizeof(PS::S64) * nmax);\n        dens[i] = (PS::F64 *) malloc(sizeof(PS::F64) * nmax);\n        temp[i] = (PS::F64 *) malloc(sizeof(PS::F64) * nmax);\n        divv[i] = (PS::F64 *) malloc(sizeof(PS::F64) * nmax);\n    }\n#else    \n    const PS::S64 nmaxmax = 512;\n    assert(nmaxmax > nmax);\n    static PS::S64 ptcl[nmaxmax][nmaxmax];\n    static PS::F64 dens[nmaxmax][nmaxmax];\n    static PS::F64 temp[nmaxmax][nmaxmax];\n    static PS::F64 divv[nmaxmax][nmaxmax];\n#endif\n\n    for(PS::S64 i = 0; i < nmax; i++) {\n        for(PS::S64 j = 0; j < nmax; j++) {\n            ptcl[i][j] = 0;\n            dens[i][j] = 0.;\n            temp[i][j] = 0.;\n            divv[i][j] = 0.;\n        }\n    }\n\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        //PS::F64vec px = sph[i].pos - bhns[0].pos;\n        PS::F64vec px = sph[i].pos;\n        if(fabs(px[2]) > fabs(sph[i].ksr)) {\n            continue;\n        }\n        PS::S64 nxi = (PS::S64)((px[0] - xmin[0]) * dxinv);\n        if(nxi < 0 || nmax <= nxi) {\n            continue;\n        }\n        PS::S64 nyi = (PS::S64)((px[1] - xmin[1]) * dxinv);\n        if(nyi < 0 || nmax <= nyi) {\n            continue;\n        }\n        ptcl[nxi][nyi] += 1;\n        dens[nxi][nyi] += sph[i].dens;\n        temp[nxi][nyi] += sph[i].temp;\n        divv[nxi][nyi] += sph[i].divv;\n    }\n\n    for(PS::S64 i = 0; i < nmax; i++) {\n        for(PS::S64 j = 0; j < nmax; j++) {\n            ptcl[i][j] = PS::Comm::getSum(ptcl[i][j]);\n            dens[i][j] = PS::Comm::getSum(dens[i][j]);\n            temp[i][j] = PS::Comm::getSum(temp[i][j]);\n            divv[i][j] = PS::Comm::getSum(divv[i][j]);;\n        }\n    }\n\n    for(PS::S64 i = 0; i < nmax; i++) {\n        for(PS::S64 j = 0; j < nmax; j++) {\n            PS::F64 pinv = ((ptcl[i][j] != 0) ? (1. / ptcl[i][j]) : 0.);\n            dens[i][j] *= pinv;\n            temp[i][j] *= pinv;\n            divv[i][j] *= pinv;\n        }\n    }\n\n    if(PS::Comm::getRank() == 0) {\n        FILE * fp = fopen(ofile, \"w\");\n        for(PS::S64 i = 0; i < nmax; i++) {\n            for(PS::S64 j = 0; j < nmax; j++) {\n                if(ptcl[i][j] == 0) {\n                    continue;\n                }\n                PS::F64 px = xmin[0] + dx * (PS::F64)i;\n                PS::F64 py = xmin[1] + dx * (PS::F64)j;\n                fprintf(fp, \"%+e %+e %+e %+e %+e %8lld\\n\",\n                        px, py,\n                        dens[i][j], temp[i][j], divv[i][j],\n                        ptcl[i][j]);\n            }\n        }\n        fclose(fp);\n    }\n\n}\n\nint main(int argc, char ** argv) {\n    MPI_Init(&argc, &argv);\n\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n    PS::ParticleSystem<BlackHoleNeutronStarAnalysis> bhns;\n    bhns.initialize();\n    bhns.createParticle(0);\n    bhns.setNumberOfParticleLocal(0);\n\n    char idir[1024], otype[1024];\n    PS::S32 fflag, nfile;\n    PS::S64 ibgn, iend;\n    PS::F64vec xmin;\n    PS::F64    wdth;\n    PS::S64    nnxx;\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", idir);\n    fscanf(fp, \"%s\", otype);\n    fscanf(fp, \"%d %d\", &fflag, &nfile);\n    fscanf(fp, \"%lld%lld\", &ibgn, &iend);\n    fscanf(fp, \"%lf%lf%lf\", &xmin[0], &xmin[1], &xmin[2]);\n    fscanf(fp, \"%lf%lld\", &wdth, &nnxx);\n    fclose(fp);\n\n    for(PS::S64 itime = ibgn; itime <= iend; itime++) {\n        if(fflag == 0) {\n            /*\n            char sfile[1024], bfile[1024];\n            sprintf(sfile, \"%s/sph_t%04d.dat\",  idir, itime);\n            sprintf(bfile, \"%s/bhns_t%04d.dat\", idir, itime);\n            fp = fopen(sfile, \"r\");\n            assert(fp);\n            sph.readParticleAscii(sfile);\n            fclose(fp);\n            fp = fopen(bfile, \"r\");\n            if(fp == NULL) {\n                sprintf(bfile, \"%s/origin.dat\", idir);\n                fp = fopen(bfile, \"r\");\n            }\n            bhns.readParticleAscii(bfile);\n            fclose(fp);\n            */\n        } else {\n            SPHAnalysis tmpsph;\n            PS::S64 nrank = PS::Comm::getNumberOfProc();\n            PS::S64 irank = PS::Comm::getRank();\n            PS::S64 ihead = nfile *  irank      / nrank;\n            PS::S64 itail = nfile * (irank + 1) / nrank;\n            PS::S64 ntot = 0;\n            for(PS::S64 ifile = ihead; ifile < itail; ifile++) {\n                char sfile[1024];\n                sprintf(sfile, \"%s/sph_t%04d_p%06d_i%06d.dat\",  idir, itime, nfile, ifile);\n                fp = fopen(sfile, \"r\");\n                assert(fp);\n                PS::S64 ntmp = 0;\n                for(PS::S32 c; (c = getc(fp)) != EOF; ntmp += ('\\n' == c ? 1 : 0)) {\n                    ;\n                }\n                fclose(fp);\n                sph.setNumberOfParticleLocal(ntot+ntmp);\n                fp = fopen(sfile, \"r\");\n                for(PS::S64 i = 0; i < ntmp; i++) {\n                    sph[ntot+i].readAscii(fp);\n                }\n                fclose(fp);\n                ntot += ntmp;\n            }\n        }\n\n        char ofile[1024];\n        sprintf(ofile, \"%s_t%04d.dat\", otype, itime);\n        projectOnOrbitalPlane(ofile, sph, bhns, xmin, wdth, nnxx);\n    }\n\n    MPI_Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "d319a31e55cdc0ceaa4f71004cc6797deba2c86a", "size": 10983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.imbh/xyplane/main.cpp", "max_stars_repo_name": "atrtnkw/sph", "max_stars_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-11T00:43:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T13:41:50.000Z", "max_issues_repo_path": "tool.imbh/xyplane/main.cpp", "max_issues_repo_name": "atrtnkw/sph", "max_issues_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_issues_repo_licenses": ["MIT"], "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.imbh/xyplane/main.cpp", "max_forks_repo_name": "atrtnkw/sph", "max_forks_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-06T14:22:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T14:22:25.000Z", "avg_line_length": 34.7563291139, "max_line_length": 91, "alphanum_fraction": 0.4521533279, "num_tokens": 3746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.16804813928204956}}
{"text": "/*! \\file breastMass.hxx\n *  \\brief breastMass header file\n *  \\author Christian G. Graff\n *  \\version 1.0\n *  \\date 2018\n *  \n *  \\copyright To the extent possible under law, the author(s) have\n *  dedicated all copyright and related and neighboring rights to this\n *  software to the public domain worldwide. This software is\n *  distributed without any warranty.  You should have received a copy\n *  of the CC0 Public Domain Dedication along with this software.\n *  If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.\n * \n */\n\n#ifndef BREASTMASS_HXX_\n#define BREASTMASS_HXX_\n\n// boost\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <boost/program_options.hpp>\n\n#include <iostream>\n#include <math.h>\n#include <unistd.h>\n#include <sys/stat.h>\n\n#include <omp.h>\n\n// vtk\n#include <vtkVersion.h>\n#include <vtkSmartPointer.h>\n#include <vtkMath.h>\n#include <vtkPNGWriter.h>\n#include <vtkImageData.h>\n#include <vtkXMLImageDataWriter.h>\n#include <vtkMinimalStandardRandomSequence.h>\n#include <vtkBoxMuellerRandomSequence.h>\n#include <vtkImageInterpolator.h>\n\n// create spiculation segments\nvoid createBranch(double, double, double, double, double, double, double, double, \n\tdouble, vtkImageData*, vtkMinimalStandardRandomSequence*, vtkBoxMuellerRandomSequence*, boost::program_options::variables_map);\n\n\n#endif /* BREASTMASS_HXX_ */\n", "meta": {"hexsha": "fb3287f70ed624527763f978bdf770b0f20dabae", "size": 1365, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "breastMass.hxx", "max_stars_repo_name": "DIDSR/breastMass", "max_stars_repo_head_hexsha": "65e646619086d8006fbe02efd2e115d61f7932f6", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T23:57:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T01:23:04.000Z", "max_issues_repo_path": "Victre/breastMass/breastMass.hxx", "max_issues_repo_name": "DIDSR/VICTRE_PIPELINE", "max_issues_repo_head_hexsha": "e4108430705ad0e4c8d51fe360f999929dcc9a92", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-21T11:23:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-21T11:23:06.000Z", "max_forks_repo_path": "Victre/breastMass/breastMass.hxx", "max_forks_repo_name": "DIDSR/VICTRE_PIPELINE", "max_forks_repo_head_hexsha": "e4108430705ad0e4c8d51fe360f999929dcc9a92", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T18:53:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T20:34:15.000Z", "avg_line_length": 29.0425531915, "max_line_length": 128, "alphanum_fraction": 0.7597069597, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.31405053215160816, "lm_q1q2_score": 0.16804794626367667}}
{"text": "//  Copyright (c) 2021 DNV AS\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#include \"Units\\Reflection\\ReflectQuantities.h\"\n\n#include \"Units\\Quantity.h\"\n#include \"Units\\Length.h\"\n#include \"Units\\Time.h\"\n#include \"Units\\Force.h\"\n#include \"Units\\Angle.h\"\n#include \"Units\\Mass.h\"\n#include \"Units\\Area.h\"\n#include \"Units\\Volume.h\"\n#include \"Units\\Curvature.h\"\n#include \"Units\\Energy.h\"\n#include \"Units\\TempDiff.h\"\n#include \"Units\\Acceleration.h\"\n#include \"Units\\ForcePerUnitArea.h\"\n#include \"Units\\ForcePerUnitLength.h\"\n#include \"Units\\Velocity.h\"\n#include \"Units\\MassDensity.h\"\n#include \"Units\\Runtime\\DynamicQuantity.h\"\n#include \"Units\\ForAllDimensions.h\"\n\n#include \"Reflection\\Classes\\Class.h\"\n#include \"Reflection\\TypeConversions\\UserConversion.h\"\n\n#include \"Units\\Reflection\\Details\\ReflectAcceleration.h\"\n#include \"Units\\Reflection\\Details\\ReflectAngle.h\"\n#include \"Units\\Reflection\\Details\\ReflectArea.h\"\n#include \"Units\\Reflection\\Details\\ReflectAxialStiffness.h\"\n#include \"Units\\Reflection\\Details\\ReflectBendingStiffness.h\"\n#include \"Units\\Reflection\\Details\\ReflectCoupledDamping.h\"\n#include \"Units\\Reflection\\Details\\ReflectCoupledMass.h\"\n#include \"Units\\Reflection\\Details\\ReflectCoupledQuadraticDamping.h\"\n#include \"Units\\Reflection\\Details\\ReflectCoupledQuadraticDampingForce.h\"\n#include \"Units\\Reflection\\Details\\ReflectCoupledQuadraticDampingMoment.h\"\n#include \"Units\\Reflection\\Details\\ReflectCoupledStiffness.h\"\n#include \"Units\\Reflection\\Details\\ReflectCurvature.h\"\n#include \"Units\\Reflection\\Details\\ReflectCurvatureResponseSpectrum.h\"\n#include \"Units\\Reflection\\Details\\ReflectDampingPerUnitLength.h\"\n#include \"Units\\Reflection\\Details\\ReflectDisplacementResponseSpectrum.h\"\n#include \"Units\\Reflection\\Details\\ReflectEnergy.h\"\n#include \"Units\\Reflection\\Details\\ReflectEnergyDensity.h\"\n#include \"Units\\Reflection\\Details\\ReflectFirstMomentOfArea.h\"\n#include \"Units\\Reflection\\Details\\ReflectForce.h\"\n#include \"Units\\Reflection\\Details\\ReflectForceEnergyDensity.h\"\n#include \"Units\\Reflection\\Details\\ReflectForcePerUnitArea.h\"\n#include \"Units\\Reflection\\Details\\ReflectForcePerUnitAreaPerAngle.h\"\n#include \"Units\\Reflection\\Details\\ReflectForcePerUnitLength.h\"\n#include \"Units\\Reflection\\Details\\ReflectForcePerUnitVolume.h\"\n#include \"Units\\Reflection\\Details\\ReflectForceResponseSpectrum.h\"\n#include \"Units\\Reflection\\Details\\ReflectFrequency.h\"\n#include \"Units\\Reflection\\Details\\ReflectKinematicViscosity.h\"\n#include \"Units\\Reflection\\Details\\ReflectLength.h\"\n#include \"Units\\Reflection\\Details\\ReflectMass.h\"\n#include \"Units\\Reflection\\Details\\ReflectMassDensity.h\"\n#include \"Units\\Reflection\\Details\\ReflectMassMomentOfInertia.h\"\n#include \"Units\\Reflection\\Details\\ReflectMassPerUnitArea.h\"\n#include \"Units\\Reflection\\Details\\ReflectMassPerUnitLength.h\"\n#include \"Units\\Reflection\\Details\\ReflectMomentOfForce.h\"\n#include \"Units\\Reflection\\Details\\ReflectMomentOfForceEnergyDensity.h\"\n#include \"Units\\Reflection\\Details\\ReflectMomentResponseSpectrum.h\"\n#include \"Units\\Reflection\\Details\\ReflectPressure.h\"\n#include \"Units\\Reflection\\Details\\ReflectQuadraticDampingPerUnitLength.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationalAcceleration.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationalDamping.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationalFlexibility.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationalQuadraticDamping.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationalResponseSpectrum.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationalStiffness.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationalStiffnessPerUnitLength.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationalVelocity.h\"\n#include \"Units\\Reflection\\Details\\ReflectRotationPerLength.h\"\n#include \"Units\\Reflection\\Details\\ReflectSecondMomentOfArea.h\"\n#include \"Units\\Reflection\\Details\\ReflectSectionModulus.h\"\n#include \"Units\\Reflection\\Details\\ReflectSpecificHeat.h\"\n#include \"Units\\Reflection\\Details\\ReflectStress.h\"\n#include \"Units\\Reflection\\Details\\ReflectTempDiff.h\"\n#include \"Units\\Reflection\\Details\\ReflectTempGradient.h\"\n#include \"Units\\Reflection\\Details\\ReflectThermalExpansionCoeff.h\"\n#include \"Units\\Reflection\\Details\\ReflectTime.h\"\n#include \"Units\\Reflection\\Details\\ReflectTorsionalStiffness.h\"\n#include \"Units\\Reflection\\Details\\ReflectTranslationalDamping.h\"\n#include \"Units\\Reflection\\Details\\ReflectTranslationalFlexibility.h\"\n#include \"Units\\Reflection\\Details\\ReflectTranslationalQuadraticDamping.h\"\n#include \"Units\\Reflection\\Details\\ReflectTranslationalStiffness.h\"\n#include \"Units\\Reflection\\Details\\ReflectTranslationalStiffnessPerUnitLength.h\"\n#include \"Units\\Reflection\\Details\\ReflectVelocity.h\"\n#include \"Units\\Reflection\\Details\\ReflectVelocityResponseSpectrum.h\"\n#include \"Units\\Reflection\\Details\\ReflectVolume.h\"\n#include \"Units\\Reflection\\ReflectCommon.h\"\n#include \"Units\\Reflection\\ReflectOperators.h\"\n#include \"Units\\Runtime\\UnitParser.h\"\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 \"Reflection\\Attributes\\UndefinedAttribute.h\"\n\n\n\nusing namespace DNVS::MoFa::Reflection::Variants;\nusing namespace DNVS::MoFa::Reflection::Operators;\nusing namespace DNVS::MoFa::Reflection::TypeLibraries;\nusing namespace DNVS::MoFa::Reflection::Types;\nusing namespace DNVS::MoFa::Reflection::TypeConversions;\nusing namespace DNVS::MoFa::Reflection::Classes;\n\nnamespace DNVS {namespace MoFa {namespace Units { namespace Reflection {\n    void ReflectQuantities(TypeLibraryPointer typeLibrary)\n    {           \n        ReflectAcceleration(typeLibrary);\n        ReflectAngle(typeLibrary);\n        ReflectArea(typeLibrary);\n        ReflectAxialStiffness(typeLibrary);\n        ReflectBendingStiffness(typeLibrary);\n        ReflectCoupledDamping(typeLibrary);\n        ReflectCoupledMass(typeLibrary);\n        ReflectCoupledQuadraticDamping(typeLibrary);\n        ReflectCoupledQuadraticDampingForce(typeLibrary);\n        ReflectCoupledQuadraticDampingMoment(typeLibrary);\n        ReflectCoupledStiffness(typeLibrary);\n        ReflectCurvature(typeLibrary);\n        ReflectCurvatureResponseSpectrum(typeLibrary);\n        ReflectDampingPerUnitLength(typeLibrary);\n        ReflectDisplacementResponseSpectrum(typeLibrary);\n        ReflectEnergy(typeLibrary);\n        ReflectEnergyDensity(typeLibrary);\n        ReflectFirstMomentOfArea(typeLibrary);\n        ReflectForce(typeLibrary);\n        ReflectForceEnergyDensity(typeLibrary);\n        ReflectForcePerUnitArea(typeLibrary);\n        ReflectForcePerUnitAreaPerAngle(typeLibrary);\n        ReflectForcePerUnitLength(typeLibrary);\n        ReflectForcePerUnitVolume(typeLibrary);\n        ReflectForceResponseSpectrum(typeLibrary);\n        ReflectFrequency(typeLibrary);\n        ReflectKinematicViscosity(typeLibrary);\n        ReflectLength(typeLibrary);\n        ReflectMass(typeLibrary);\n        ReflectMassDensity(typeLibrary);\n        ReflectMassMomentOfInertia(typeLibrary);\n        ReflectMassPerUnitArea(typeLibrary);\n        ReflectMassPerUnitLength(typeLibrary);\n        ReflectMomentOfForce(typeLibrary);\n        ReflectMomentOfForceEnergyDensity(typeLibrary);\n        ReflectMomentResponseSpectrum(typeLibrary);\n        ReflectPressure(typeLibrary);\n        ReflectQuadraticDampingPerUnitLength(typeLibrary);\n        ReflectRotationalAcceleration(typeLibrary);\n        ReflectRotationalDamping(typeLibrary);\n        ReflectRotationalFlexibility(typeLibrary);\n        ReflectRotationalQuadraticDamping(typeLibrary);\n        ReflectRotationalResponseSpectrum(typeLibrary);\n        ReflectRotationalStiffness(typeLibrary);\n        ReflectRotationalStiffnessPerUnitLength(typeLibrary);\n        ReflectRotationalVelocity(typeLibrary);\n        ReflectRotationPerLength(typeLibrary);\n        ReflectSecondMomentOfArea(typeLibrary);\n        ReflectSectionModulus(typeLibrary);\n        ReflectSpecificHeat(typeLibrary);\n        ReflectStress(typeLibrary);\n        ReflectTempDiff(typeLibrary);\n        ReflectTempGradient(typeLibrary);\n        ReflectThermalExpansionCoeff(typeLibrary);\n        ReflectTime(typeLibrary);\n        ReflectTorsionalStiffness(typeLibrary);\n        ReflectTranslationalDamping(typeLibrary);\n        ReflectTranslationalFlexibility(typeLibrary);\n        ReflectTranslationalQuadraticDamping(typeLibrary);\n        ReflectTranslationalStiffness(typeLibrary);\n        ReflectTranslationalStiffnessPerUnitLength(typeLibrary);\n        ReflectVelocity(typeLibrary);\n        ReflectVelocityResponseSpectrum(typeLibrary);\n        ReflectVolume(typeLibrary);\n\n        ReflectCommon(typeLibrary);\n\n        ReflectAllOperators<Quantity<Dimension<0, 0, 0, 0, 2> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<-2, 0, 0, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<2, -2, 0, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<2, 0, 1, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<0, 0, 2, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<2, 0, 2, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<0, 1, 1, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<-1, 0, 1, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<0, 2, 1, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<0, 0, 0, 0, 0> > >(typeLibrary);\n        ReflectAllOperators<Quantity<Dimension<-3, 0, 1, 0, 0> > >(typeLibrary);\n\n        AddUserConversion<Quantity<NoDimension>, double>(typeLibrary->GetConversionGraph(), ConversionType::StandardConversion, &Quantity<NoDimension>::operator double);\n        AddConstructorConversion<double, Quantity<NoDimension>>(typeLibrary->GetConversionGraph(), ConversionType::StandardConversion);\n    }\n\n    struct ConverterFromDynamicQuantityToStaticQuantity\n    {\n    public:\n        ConverterFromDynamicQuantityToStaticQuantity(const Variant& dynamicQuantity)\n            :   m_dynamicQuantity(InternalVariantService::UnreflectUnchecked<Runtime::DynamicQuantity>(dynamicQuantity))\n            ,   m_staticQuantity(dynamicQuantity)\n        {\n        }\n        template<typename DimensionT>\n        struct StaticQuantityComputer \n        {\n            typedef Quantity<DimensionT> Type;\n        };\n        template<>\n        struct StaticQuantityComputer<Dimension<0, 0, 0, 0, 0>>\n        {\n            typedef double Type;\n        };\n        template<typename DimensionT>\n        void Apply()\n        {\n            typedef typename StaticQuantityComputer<DimensionT>::Type StaticQuantity;\n            if(Runtime::DynamicDimension(DimensionT()) == m_dynamicQuantity.GetSimplifiedUnit().GetDimension())   \n                m_staticQuantity = VariantService::ReflectType<StaticQuantity>(StaticQuantity(m_dynamicQuantity.GetNeutralValue()));\n        }\n        Variant GetStaticQuantity() const\n        {\n            return m_staticQuantity;\n        }\n    private:\n        Variant m_staticQuantity;\n        Runtime::DynamicQuantity m_dynamicQuantity;\n    };\n\n    struct FallbackUnitConverter : public IConversion\n    {\n        virtual Variant Convert(const Variant& other)\n        {\n            ConverterFromDynamicQuantityToStaticQuantity converter(other);\n            ForAllUsedDimensions(converter);\n            converter.Apply<Dimension<0, 0, 0, 0, 0>>();\n            return converter.GetStaticQuantity();\n        }\n        virtual void IntrusiveConvert( Variant& variable ) \n        {\n            ConverterFromDynamicQuantityToStaticQuantity converter(variable);\n            ForAllUsedDimensions(converter);\n            converter.Apply<Dimension<0, 0, 0, 0, 0>>();\n            variable = converter.GetStaticQuantity();\n        }\n    };\n    Runtime::DynamicQuantity DivideDynamicQuantities(const Runtime::DynamicQuantity& lhs, const Runtime::DynamicQuantity& rhs)\n    {\n        Runtime::DynamicQuantity result = lhs / rhs;\n        result.TrySimplifyUnit();\n        return result;\n    }\n    Runtime::DynamicQuantity MultiplyDynamicQuantities(const Runtime::DynamicQuantity& lhs, const Runtime::DynamicQuantity& rhs)\n    {\n        Runtime::DynamicQuantity result = lhs * rhs;\n        result.TrySimplifyUnit();\n        return result;\n    }\n    class StringToQuantityConversion : public IConversion\n    {\n    public:\n        // creates copy of variable, converts it and returns converted copy\n        virtual Variant Convert(const Variant& variable)\n        {\n            const std::string& quantity = InternalVariantService::UnreflectUnchecked<const std::string&>(variable);\n            using boost::spirit::qi::double_;\n            using boost::spirit::qi::char_;\n            using boost::spirit::qi::phrase_parse;\n            using boost::spirit::qi::_1;\n            using boost::spirit::qi::space;\n\n            double value;\n            std::vector<char> unitVect;\n            if (phrase_parse(quantity.begin(), quantity.end(), double_[boost::phoenix::ref(value) = _1] >> (*char_)[boost::phoenix::ref(unitVect) = _1], space))\n            {\n                if (unitVect.empty())\n                    return VariantService::Reflect(std::move(value));\n                else\n                {\n                    std::string unit(&unitVect.front(), unitVect.size());\n                    return VariantService::Reflect(Runtime::DynamicQuantity(value, unit));\n                }\n            }\n            else\n                throw std::runtime_error(\"Unable to convert '\" + quantity + \"' to a quantity\");\n        }\n\n        // converts variable itself (it is overwritten)\n        virtual void IntrusiveConvert(Variant& variable) {\n            variable = Convert(variable);\n        }\n    };\n\n    void ReflectDynamicQuantities(TypeLibraryPointer typeLibrary)\n    {\n        Class<Runtime::DynamicQuantity> cls(typeLibrary, \"DynamicQuantity\");\n        cls.AddAttribute<UndefinedAttribute>([](const Runtime::DynamicQuantity& q) {return !!_isnan(q.GetValue()); });\n        cls.Constructor<double>();\n        cls.Operator(This.Const + This.Const);\n        cls.Operator(This.Const - This.Const);\n        cls.Operator(This.Const * This.Const, &MultiplyDynamicQuantities);\n        cls.Operator(This.Const / This.Const, &DivideDynamicQuantities);\n        cls.Operator(This.Const / double());\n        cls.Operator(double() / This.Const);\n        cls.Operator(This.Const * double());\n        cls.Operator(double() * This.Const);\n        cls.Operator(-This.Const);\n        cls.Operator( + This.Const);\n        cls.Operator(This.Const < This.Const);\n        cls.Operator(This.Const <= This.Const);\n        cls.Operator(This.Const > This.Const);\n        cls.Operator(This.Const >= This.Const);\n        cls.Operator(This.Const == This.Const);\n        cls.Operator(This.Const != This.Const);\n\n        typeLibrary->GetConversionGraph()->AddConversion(\n            TypeId<Runtime::DynamicQuantity>(), \n            TypeId<void>(), \n            ConversionType::FallbackConversion, \n            ConversionPointer(new FallbackUnitConverter)\n            );\n        typeLibrary->GetConversionGraph()->AddConversion(\n            TypeId<const std::string>(),\n            TypeId<void>(),\n            ConversionType::FallbackConversion,\n            ConversionPointer(new StringToQuantityConversion)\n        );\n    }\n}}}}", "meta": {"hexsha": "368e4539bb7c9424dd0f88bee178db18cbd04ad5", "size": 15399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Units.Reflection/Units/Reflection/ReflectQuantities.cpp", "max_stars_repo_name": "dnv-opensource/Reflection", "max_stars_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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": "Units.Reflection/Units/Reflection/ReflectQuantities.cpp", "max_issues_repo_name": "dnv-opensource/Reflection", "max_issues_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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": "Units.Reflection/Units/Reflection/ReflectQuantities.cpp", "max_forks_repo_name": "dnv-opensource/Reflection", "max_forks_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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": 46.6636363636, "max_line_length": 169, "alphanum_fraction": 0.7266056237, "num_tokens": 3379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.1680443621473711}}
{"text": "/*\n *\n * Copyright (c) 2006 The Apache Software 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 \"qpid/acl/AclValidator.h\"\n#include \"qpid/acl/AclData.h\"\n#include \"qpid/acl/AclLexer.h\"\n#include \"qpid/Exception.h\"\n#include \"qpid/log/Statement.h\"\n#include \"qpid/sys/IntegerTypes.h\"\n#include \"qpid/StringUtils.h\"\n#include <boost/lexical_cast.hpp>\n#include <boost/bind.hpp>\n#include <numeric>\n#include <sstream>\n#include <iomanip>\n\nnamespace qpid {\nnamespace acl {\n\n    AclValidator::IntPropertyType::IntPropertyType(int64_t i,int64_t j) : min(i), max(j){\n    }\n\n    bool AclValidator::IntPropertyType::validate(const std::string& val) {\n        int64_t v;\n        try\n        {\n            v = boost::lexical_cast<int64_t>(val);\n        }catch(const boost::bad_lexical_cast&){\n            return 0;\n        }\n\n        if (v < min || v >= max){\n            return 0;\n        }else{\n            return 1;\n        }\n    }\n\n    std::string AclValidator::IntPropertyType::allowedValues() {\n        return \"values should be between \" +\n            boost::lexical_cast<std::string>(min) + \" and \" +\n            boost::lexical_cast<std::string>(max);\n    }\n\n    AclValidator::EnumPropertyType::EnumPropertyType(std::vector<std::string>& allowed): values(allowed){\n    }\n\n    bool AclValidator::EnumPropertyType::validate(const std::string& val) {\n        for (std::vector<std::string>::iterator itr = values.begin(); itr != values.end(); ++itr ){\n            if (val.compare(*itr) == 0){\n                return 1;\n            }\n        }\n\n        return 0;\n    }\n\n    std::string AclValidator::EnumPropertyType::allowedValues() {\n        std::ostringstream oss;\n        oss << \"possible values are one of { \";\n        for (std::vector<std::string>::iterator itr = values.begin(); itr != values.end(); itr++ ){\n            oss << \"'\" << *itr << \"' \";\n        }\n        oss << \"}\";\n        return oss.str();\n    }\n\n    AclValidator::AclValidator() : propertyIndex(1) {\n        validators.insert(Validator(acl::SPECPROP_MAXQUEUESIZELOWERLIMIT,\n                          boost::shared_ptr<PropertyType>(\n                            new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXQUEUESIZEUPPERLIMIT,\n                          boost::shared_ptr<PropertyType>(\n                            new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXQUEUECOUNTLOWERLIMIT,\n                                    boost::shared_ptr<PropertyType>(\n                                        new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXQUEUECOUNTUPPERLIMIT,\n                                    boost::shared_ptr<PropertyType>(\n                                        new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXFILESIZELOWERLIMIT,\n                                    boost::shared_ptr<PropertyType>(\n                                        new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXFILESIZEUPPERLIMIT,\n                                    boost::shared_ptr<PropertyType>(\n                                        new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXFILECOUNTLOWERLIMIT,\n                                    boost::shared_ptr<PropertyType>(\n                                        new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXFILECOUNTUPPERLIMIT,\n                                    boost::shared_ptr<PropertyType>(\n                                        new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXPAGESLOWERLIMIT,\n                          boost::shared_ptr<PropertyType>(\n                            new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXPAGESUPPERLIMIT,\n                          boost::shared_ptr<PropertyType>(\n                            new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXPAGEFACTORLOWERLIMIT,\n                          boost::shared_ptr<PropertyType>(\n                            new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        validators.insert(Validator(acl::SPECPROP_MAXPAGEFACTORUPPERLIMIT,\n                          boost::shared_ptr<PropertyType>(\n                            new IntPropertyType(0,std::numeric_limits<int64_t>::max()))));\n\n        std::string policyTypes[] = {\"ring\", \"self-destruct\", \"reject\"};\n        std::vector<std::string> v(policyTypes, policyTypes + sizeof(policyTypes) / sizeof(std::string));\n        validators.insert(Validator(acl::SPECPROP_POLICYTYPE,\n                          boost::shared_ptr<PropertyType>(\n                            new EnumPropertyType(v))));\n\n        // Insert allowed action/object/property sets (generated manually 20140712)\n#define RP registerProperties\n        RP( \"Broker::getTimestampConfig\",\n            \"User querying message timestamp setting \",\n            ACT_ACCESS,  OBJ_BROKER);\n        RP( \"ExchangeHandlerImpl::query\",\n            \"AMQP 0-10 protocol received 'query'     \",\n            ACT_ACCESS,  OBJ_EXCHANGE, \"name\");\n        RP( \"ExchangeHandlerImpl::bound\",\n            \"AMQP 0-10 query binding                 \",\n            ACT_ACCESS,  OBJ_EXCHANGE, \"name queuename routingkey\");\n        RP( \"ExchangeHandlerImpl::declare\",\n            \"AMQP 0-10 exchange declare              \",\n            ACT_ACCESS,  OBJ_EXCHANGE, \"name type alternate durable autodelete\");\n        RP( \"Authorise::access\",\n            \"AMQP 1.0 exchange access                \",\n            ACT_ACCESS,  OBJ_EXCHANGE, \"name type durable\");\n        RP( \"Authorise::access\",\n            \"AMQP 1.0 node resolution                \",\n            ACT_ACCESS,  OBJ_EXCHANGE, \"name\");\n        RP( \"ManagementAgent::handleMethodRequest\",\n            \"Management method request               \",\n            ACT_ACCESS,  OBJ_METHOD, \"name schemapackage schemaclass\");\n        RP( \"ManagementAgent::authorizeAgentMessage\",\n            \"Management agent method request         \",\n            ACT_ACCESS,  OBJ_METHOD, \"name schemapackage schemaclass\");\n        RP( \"ManagementAgent::handleGetQuery\",\n            \"Management agent query                  \",\n            ACT_ACCESS,  OBJ_QUERY, \"name schemaclass\");\n        RP( \"Broker::queryQueue\",\n            \"QMF 'query queue' method                \",\n            ACT_ACCESS,  OBJ_QUEUE, \"name\");\n        RP( \"QueueHandlerImpl::query\",\n            \"AMQP 0-10 query                         \",\n            ACT_ACCESS,  OBJ_QUEUE, \"name\");\n        RP( \"QueueHandlerImpl::declare\",\n            \"AMQP 0-10 queue declare                 \",\n            ACT_ACCESS,  OBJ_QUEUE, \"name alternate durable exclusive autodelete policytype maxqueuecount maxqueuesize\");\n        RP( \"Authorise::access\",\n            \"AMQP 1.0 queue access                   \",\n            ACT_ACCESS,  OBJ_QUEUE, \"name alternate durable exclusive autodelete policytype maxqueuecount maxqueuesize\");\n        RP( \"Authorise::access\",\n            \"AMQP 1.0 node resolution                \",\n            ACT_ACCESS,  OBJ_QUEUE, \"name\");\n        RP( \"Broker::bind\",\n            \"AMQP 0-10 or QMF bind request           \",\n            ACT_BIND,    OBJ_EXCHANGE, \"name queuename routingkey\");\n        RP( \"Authorise::outgoing\",\n            \"AMQP 1.0 new outgoing link from exchange\",\n            ACT_BIND,    OBJ_EXCHANGE, \"name queuename routingkey\");\n        RP( \"MessageHandlerImpl::subscribe\",\n            \"AMQP 0-10 subscribe request             \",\n            ACT_CONSUME, OBJ_QUEUE, \"name\");\n        RP( \"Authorise::outgoing\",\n            \"AMQP 1.0 new outgoing link from queue   \",\n            ACT_CONSUME, OBJ_QUEUE, \"name\");\n        RP( \"ConnectionHandler\",\n            \"TCP/IP connection creation              \",\n            ACT_CREATE,  OBJ_CONNECTION, \"host\");\n        RP( \"Broker::createExchange\",\n            \"Create exchange                         \",\n            ACT_CREATE,  OBJ_EXCHANGE, \"name type alternate durable autodelete\");\n        RP( \"ConnectionHandler::Handler::open\",\n            \"Interbroker link creation               \",\n            ACT_CREATE,  OBJ_LINK);\n        RP( \"Authorise::interlink\",\n            \"Interbroker link creation               \",\n            ACT_CREATE,  OBJ_LINK);\n        RP( \"Broker::createQueue\",\n            \"Create queue                            \",\n            ACT_CREATE,  OBJ_QUEUE, \"name alternate durable exclusive autodelete policytype paging maxpages maxpagefactor maxqueuecount maxqueuesize maxfilecount maxfilesize\");\n        RP( \"Broker::deleteExchange\",\n            \"Delete exchange                         \",\n            ACT_DELETE,  OBJ_EXCHANGE, \"name type alternate durable\");\n        RP( \"Broker::deleteQueue\",\n            \"Delete queue                            \",\n            ACT_DELETE,  OBJ_QUEUE, \"name alternate durable exclusive autodelete policytype\");\n        RP( \"Broker::queueMoveMessages\",\n            \"Management 'move queue' request         \",\n            ACT_MOVE,    OBJ_QUEUE, \"name queuename\");\n        RP( \"SemanticState::route\",\n            \"AMQP 0-10 received message processing   \",\n            ACT_PUBLISH, OBJ_EXCHANGE, \"name routingkey\");\n        RP( \"Authorise::incoming\",\n            \"AMQP 1.0 establish sender link to queue \",\n            ACT_PUBLISH, OBJ_EXCHANGE, \"routingkey\");\n        RP( \"Authorise::route\",\n            \"AMQP 1.0 received message processing    \",\n            ACT_PUBLISH, OBJ_EXCHANGE, \"name routingkey\");\n        RP( \"Queue::ManagementMethod\",\n            \"Management 'purge queue' request        \",\n            ACT_PURGE,   OBJ_QUEUE, \"name\");\n        RP( \"QueueHandlerImpl::purge\",\n            \"Management 'purge queue' request        \",\n            ACT_PURGE,   OBJ_QUEUE, \"name\");\n        RP( \"Broker::queueRedirect\",\n            \"Management 'redirect queue' request     \",\n            ACT_REDIRECT,OBJ_QUEUE, \"name queuename\");\n        RP( \"Queue::ManagementMethod\",\n            \"Management 'reroute queue' request      \",\n            ACT_REROUTE, OBJ_QUEUE, \"name exchangename\");\n        RP( \"Broker::unbind\",\n            \"Management 'unbind exchange' request    \",\n            ACT_UNBIND,  OBJ_EXCHANGE, \"name queuename routingkey\");\n        RP( \"Broker::setTimestampConfig\",\n            \"User modifying message timestamp setting\",\n            ACT_UPDATE,  OBJ_BROKER);\n    }\n\n    AclValidator::~AclValidator(){\n    }\n\n    /* Iterate through the data model and validate the parameters. */\n    void AclValidator::validate(boost::shared_ptr<AclData> d) {\n\n        for (unsigned int cnt=0; cnt< qpid::acl::ACTIONSIZE; cnt++){\n\n            if (d->actionList[cnt]){\n\n                for (unsigned int cnt1=0; cnt1< qpid::acl::OBJECTSIZE; cnt1++){\n\n                    if (d->actionList[cnt][cnt1]){\n\n                        std::for_each(d->actionList[cnt][cnt1]->begin(),\n                                      d->actionList[cnt][cnt1]->end(),\n                                      boost::bind(&AclValidator::validateRuleSet, this, _1));\n                    }\n                }\n            }\n        }\n    }\n\n    void AclValidator::validateRuleSet(std::pair<const std::string, qpid::acl::AclData::ruleSet>& rules){\n        std::for_each(rules.second.begin(),\n            rules.second.end(),\n            boost::bind(&AclValidator::validateRule, this, _1));\n    }\n\n    void AclValidator::validateRule(qpid::acl::AclData::Rule& rule){\n        std::for_each(rule.props.begin(),\n            rule.props.end(),\n            boost::bind(&AclValidator::validateProperty, this, _1));\n    }\n\n    void AclValidator::validateProperty(std::pair<const qpid::acl::SpecProperty, std::string>& prop){\n        ValidatorItr itr = validators.find(prop.first);\n        if (itr != validators.end()){\n            QPID_LOG(debug,\"ACL: Found validator for property '\" << acl::AclHelper::getPropertyStr(itr->first)\n                     << \"'. \" << itr->second->allowedValues());\n\n            if (!itr->second->validate(prop.second)){\n                QPID_LOG(debug, \"ACL: Property failed validation. '\" << prop.second << \"' is not a valid value for '\"\n                    << AclHelper::getPropertyStr(prop.first) << \"'\");\n\n                throw Exception( prop.second + \" is not a valid value for '\" +\n                    AclHelper::getPropertyStr(prop.first) + \"', \" +\n                    itr->second->allowedValues());\n            }\n        }\n    }\n\n    /**\n     * validateAllowedProperties\n     * verify that at least one lookup definition can satisfy this\n     * action/object/props tuple.\n     * Return false and conditionally emit a warning log entry if the\n     * incoming definition can not be matched.\n     */\n    bool AclValidator::validateAllowedProperties(qpid::acl::Action action,\n                                                 qpid::acl::ObjectType object,\n                                                 const AclData::specPropertyMap& props,\n                                                 bool emitLog) const {\n        // No rules defined means no match\n        if (!allowedSpecProperties[action][object].get()) {\n            if (emitLog) {\n                QPID_LOG(warning, \"ACL rule ignored: Broker never checks for rules with action: '\"\n                    << AclHelper::getActionStr(action) << \"' and object: '\"\n                    << AclHelper::getObjectTypeStr(object) << \"'\");\n            }\n            return false;\n        }\n        // two empty property sets is a match\n        if (allowedSpecProperties[action][object]->size() == 0) {\n            if ((props.size() == 0) ||\n                (props.size() == 1 && props.find(acl::SPECPROP_NAME) != props.end())) {\n                return true;\n            }\n        }\n        // Scan vector of rules looking for one that matches all properties\n        bool validRuleFound = false;\n        for (std::vector<AclData::Rule>::const_iterator\n            ruleItr  = allowedSpecProperties[action][object]->begin();\n            ruleItr != allowedSpecProperties[action][object]->end() && !validRuleFound;\n            ruleItr++) {\n            // Scan one rule\n            validRuleFound = true;\n            for(AclData::specPropertyMapItr itr = props.begin();\n                itr != props.end();\n                itr++) {\n                if ((*itr).first != acl::SPECPROP_NAME &&\n                    ruleItr->props.find((*itr).first) ==\n                    ruleItr->props.end()) {\n                    // Test property not found in this rule\n                    validRuleFound = false;\n                    break;\n                }\n            }\n        }\n        if (!validRuleFound) {\n            if (emitLog) {\n                QPID_LOG(warning, \"ACL rule ignored: Broker checks for rules with action: '\"\n                    << AclHelper::getActionStr(action) << \"' and object: '\"\n                    << AclHelper::getObjectTypeStr(object)\n                    << \"' but will never match with property set: \"\n                    << AclHelper::propertyMapToString(&props));\n            }\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * Return a list of indexes of definitions that this lookup might match\n     */\n    void AclValidator::findPossibleLookupMatch(qpid::acl::Action action,\n                                               qpid::acl::ObjectType object,\n                                               const AclData::specPropertyMap& props,\n                                               std::vector<int>& result) const {\n        if (!allowedSpecProperties[action][object].get()) {\n            return;\n        } else {\n            // Scan vector of rules returning the indexes of all that match\n            bool validRuleFound;\n            for (std::vector<AclData::Rule>::const_iterator\n                ruleItr  = allowedSpecProperties[action][object]->begin();\n                ruleItr != allowedSpecProperties[action][object]->end();\n                ruleItr++) {\n                // Scan one rule\n                validRuleFound = true;\n                for(AclData::specPropertyMapItr\n                    itr = props.begin(); itr != props.end(); itr++) {\n                    if ((*itr).first != acl::SPECPROP_NAME &&\n                        ruleItr->props.find((*itr).first) ==\n                        ruleItr->props.end()) {\n                        // Test property not found in this rule\n                        validRuleFound = false;\n                        break;\n                    }\n                }\n                if (validRuleFound) {\n                    result.push_back(ruleItr->rawRuleNum);\n                }\n            }\n        }\n        return;\n    }\n\n    /**\n     * Emit trace log of original property definitions\n     */\n    void AclValidator::tracePropertyDefs() {\n        QPID_LOG(trace, \"ACL: Definitions of action, object, (allowed properties) lookups\");\n        for (int iA=0; iA<acl::ACTIONSIZE; iA++) {\n            for (int iO=0; iO<acl::OBJECTSIZE; iO++) {\n                if (allowedSpecProperties[iA][iO].get()) {\n                    for (std::vector<AclData::Rule>::const_iterator\n                        ruleItr  = allowedSpecProperties[iA][iO]->begin();\n                        ruleItr != allowedSpecProperties[iA][iO]->end();\n                        ruleItr++) {\n                        std::string pstr;\n                        for (AclData::specPropertyMapItr pMItr  = ruleItr->props.begin();\n                            pMItr != ruleItr->props.end();\n                            pMItr++) {\n                            pstr += AclHelper::getPropertyStr((SpecProperty) pMItr-> first);\n                            pstr += \",\";\n                        }\n                        QPID_LOG(trace, \"ACL: Lookup \"\n                            << std::setfill(' ') << std::setw(2)\n                            << ruleItr->rawRuleNum << \": \"\n                            << ruleItr->lookupHelp << \" \"\n                            << std::setfill(' ') << std::setw(acl::ACTION_STR_WIDTH +1) << std::left\n                            << AclHelper::getActionStr(acl::Action(iA))\n                            << std::setfill(' ') << std::setw(acl::OBJECTTYPE_STR_WIDTH) << std::left\n                            << AclHelper::getObjectTypeStr(acl::ObjectType(iO))\n                            << \" (\" << pstr.substr(0, pstr.length()-1) << \")\");\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Construct a record of all the calls that the broker will\n     * make to acl::authorize and the properties for each call.\n     * From that create the list of all the spec properties that\n     * users are then allowed to specify in acl rule files.\n     */\n    void AclValidator::registerProperties(\n        const std::string& source,\n        const std::string& description,\n        Action action,\n        ObjectType object,\n        const std::string& properties) {\n        if (!allowedProperties[action][object].get()) {\n            boost::shared_ptr<std::set<Property> > t1(new std::set<Property>());\n            allowedProperties[action][object] = t1;\n            boost::shared_ptr<std::vector<AclData::Rule> > t2(new std::vector<AclData::Rule>());\n            allowedSpecProperties[action][object] = t2;\n        }\n        std::vector<std::string> props = split(properties, \" \");\n        AclData::specPropertyMap spm;\n        for (size_t i=0; i<props.size(); i++) {\n            Property prop = AclHelper::getProperty(props[i]);\n            allowedProperties[action][object]->insert(prop);\n            // Given that the broker will be calling with this property,\n            // determine what user rule settings are allowed.\n            switch (prop) {\n                // Cases where broker and Acl file share property name and meaning\n                case PROP_NAME:\n                    spm[SPECPROP_NAME]=\"\";\n                    break;\n                case PROP_DURABLE:\n                    spm[SPECPROP_DURABLE]=\"\";\n                    break;\n                case PROP_OWNER:\n                    spm[SPECPROP_OWNER]=\"\";\n                    break;\n                case PROP_ROUTINGKEY:\n                    spm[SPECPROP_ROUTINGKEY]=\"\";\n                    break;\n                case PROP_AUTODELETE:\n                    spm[SPECPROP_AUTODELETE]=\"\";\n                    break;\n                case PROP_EXCLUSIVE:\n                    spm[SPECPROP_EXCLUSIVE]=\"\";\n                    break;\n                case PROP_TYPE:\n                    spm[SPECPROP_TYPE]=\"\";\n                    break;\n                case PROP_ALTERNATE:\n                    spm[SPECPROP_ALTERNATE]=\"\";\n                    break;\n                case PROP_QUEUENAME:\n                    spm[SPECPROP_QUEUENAME]=\"\";\n                    break;\n                case PROP_EXCHANGENAME:\n                    spm[SPECPROP_EXCHANGENAME]=\"\";\n                    break;\n                case PROP_SCHEMAPACKAGE:\n                    spm[SPECPROP_SCHEMAPACKAGE]=\"\";\n                    break;\n                case PROP_SCHEMACLASS:\n                    spm[SPECPROP_SCHEMACLASS]=\"\";\n                    break;\n                case PROP_POLICYTYPE:\n                    spm[SPECPROP_POLICYTYPE]=\"\";\n                    break;\n                case PROP_PAGING:\n                    spm[SPECPROP_PAGING]=\"\";\n                    break;\n                case PROP_HOST:\n                    spm[SPECPROP_HOST]=\"\";\n                    break;\n                // Cases where broker supplies a property but Acl has upper/lower limit for it\n                case PROP_MAXPAGES:\n                    spm[SPECPROP_MAXPAGESLOWERLIMIT]=\"\";\n                    spm[SPECPROP_MAXPAGESUPPERLIMIT]=\"\";\n                    break;\n                case PROP_MAXPAGEFACTOR:\n                    spm[SPECPROP_MAXPAGEFACTORLOWERLIMIT]=\"\";\n                    spm[SPECPROP_MAXPAGEFACTORUPPERLIMIT]=\"\";\n                    break;\n                case PROP_MAXQUEUESIZE:\n                    spm[SPECPROP_MAXQUEUESIZELOWERLIMIT]=\"\";\n                    spm[SPECPROP_MAXQUEUESIZEUPPERLIMIT]=\"\";\n                    break;\n                case PROP_MAXQUEUECOUNT:\n                    spm[SPECPROP_MAXQUEUECOUNTLOWERLIMIT]=\"\";\n                    spm[SPECPROP_MAXQUEUECOUNTUPPERLIMIT]=\"\";\n                    break;\n                case PROP_MAXFILESIZE:\n                    spm[SPECPROP_MAXFILESIZELOWERLIMIT]=\"\";\n                    spm[SPECPROP_MAXFILESIZEUPPERLIMIT]=\"\";\n                    break;\n                case PROP_MAXFILECOUNT:\n                    spm[SPECPROP_MAXFILECOUNTLOWERLIMIT]=\"\";\n                    spm[SPECPROP_MAXFILECOUNTUPPERLIMIT]=\"\";\n                    break;\n                default:\n                    throw Exception( \"acl::RegisterProperties no case for property: \" +\n                        AclHelper::getPropertyStr(prop) );\n            }\n        }\n        AclData::Rule someProps(propertyIndex, acl::ALLOW, spm, source, description);\n        propertyIndex++;\n        allowedSpecProperties[action][object]->push_back(someProps);\n    }\n\n}}\n", "meta": {"hexsha": "f905b4aca5bcd8802d39467d7b02559d8105cebe", "size": 23976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/qpid/acl/AclValidator.cpp", "max_stars_repo_name": "irinabov/debian-qpid-cpp-1.35.0", "max_stars_repo_head_hexsha": "98b0597071c0a5f0cc407a35d5a4690d9189065e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T09:19:02.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-29T09:19:02.000Z", "max_issues_repo_path": "src/qpid/acl/AclValidator.cpp", "max_issues_repo_name": "irinabov/debian-qpid-cpp-1.35.0", "max_issues_repo_head_hexsha": "98b0597071c0a5f0cc407a35d5a4690d9189065e", "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/qpid/acl/AclValidator.cpp", "max_forks_repo_name": "irinabov/debian-qpid-cpp-1.35.0", "max_forks_repo_head_hexsha": "98b0597071c0a5f0cc407a35d5a4690d9189065e", "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.6480446927, "max_line_length": 176, "alphanum_fraction": 0.525025025, "num_tokens": 5116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.16792440402177114}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <node/protocol/exceptions.hpp>\n\n#include <node/chain/database.hpp>\n#include <node/chain/hardfork.hpp>\n#include <node/chain/node_objects.hpp>\n\n#include <fc/crypto/digest.hpp>\n\n#include \"../common/database_fixture.hpp\"\n\n#include <iostream>\n\nusing namespace node;\nusing namespace node::chain;\nusing namespace node::protocol;\n\n#ifndef IS_TEST_NET\n\nBOOST_FIXTURE_TEST_SUITE( live_tests, live_database_fixture )\n\n/*\nBOOST_AUTO_TEST_CASE( SCORE_stock_split )\n{\n   try\n   {\n      BOOST_TEST_MESSAGE( \"Gathering state prior to split\" );\n\n      uint32_t magnitude = 1000000;\n\n      flat_map< string, share_type > accountSCORE;\n      flat_map< string, share_type > account_SCOREfundTMEbalance_votes;\n      const auto& acnt_idx = db.get_index< account_index >().indices().get< by_name >();\n      auto acnt_itr = acnt_idx.begin();\n\n      BOOST_TEST_MESSAGE( \"Saving account VESTS\" );\n\n      while( acnt_itr != acnt_idx.end() )\n      {\n         accountSCORE[acnt_itr->name] = acnt_itr->SCORE.amount;\n         account_SCOREfundTMEbalance_votes[acnt_itr->name] = acnt_itr->proxied_SCOREfundTMEbalance_votes_total().value;\n         acnt_itr++;\n      }\n\n      auto old_virtual_supply = db.get_dynamic_global_properties().virtual_supply;\n      auto old_current_supply = db.get_dynamic_global_properties().current_supply;\n      auto old_SCORE_fund = db.get_dynamic_global_properties().totalTMEfundForSCORE;\n      auto old_SCORE = db.get_dynamic_global_properties().totalSCORE;\n      auto old_SCOREreward2 = db.get_dynamic_global_properties().totalSCOREreward2;\n      auto old_reward_fund = db.get_dynamic_global_properties().total_reward_fund_TME;\n\n      flat_map< std::tuple< account_name_type, string >, share_type > comment_net_SCOREreward;\n      flat_map< std::tuple< account_name_type, string >, share_type > comment_abs_SCOREreward;\n      flat_map< comment_id_type, uint64_t > total_vote_weights;\n      flat_map< comment_id_type, uint64_t > orig_vote_weight;\n      flat_map< comment_id_type, uint64_t > expected_reward;\n      fc::uint128_t totalSCOREreward2 = 0;\n      const auto& com_idx = db.get_index< comment_index >().indices().get< by_permlink >();\n      auto com_itr = com_idx.begin();\n      auto gpo = db.get_dynamic_global_properties();\n\n      BOOST_TEST_MESSAGE( \"Saving comment rshare values\" );\n\n      while( com_itr != com_idx.end() )\n      {\n         comment_net_SCOREreward[ std::make_tuple( com_itr->author, com_itr->permlink ) ] = com_itr->net_SCOREreward;\n         comment_abs_SCOREreward[ std::make_tuple( com_itr->author, com_itr->permlink ) ] = com_itr->abs_SCOREreward;\n         total_vote_weights[ com_itr->id ] = 0;\n         orig_vote_weight[ com_itr->id ] = com_itr->total_vote_weight;\n\n         if( com_itr->net_SCOREreward.value > 0 )\n         {\n            totalSCOREreward2 += com_itr->net_SCOREreward.value > 0 ? fc::uint128_t( com_itr->net_SCOREreward.value ) * com_itr->net_SCOREreward.value * magnitude * magnitude : 0;\n            u256 rs( com_itr->net_SCOREreward.value );\n            u256 rf( gpo.total_reward_fund_TME.amount.value );\n            auto rs2 = rs * rs;\n            u256 SCOREreward2 = old_SCOREreward2.hi;\n            SCOREreward2 = SCOREreward2 << 64;\n            SCOREreward2 += old_SCOREreward2.lo;\n            expected_reward[ com_itr->id ] = static_cast< uint64_t >( rf * rs2 / SCOREreward2 );\n         }\n         com_itr++;\n      }\n\n      BOOST_TEST_MESSAGE( \"Saving category SCOREreward\" );\n\n      const auto& cat_idx = db.get_index< category_index >().indices();\n      flat_map< category_id_type, share_type > category_SCOREreward;\n\n      for( auto cat_itr = cat_idx.begin(); cat_itr != cat_idx.end(); cat_itr++ )\n      {\n         category_SCOREreward[ cat_itr->id ] = cat_itr->abs_SCOREreward;\n      }\n\n      BOOST_TEST_MESSAGE( \"Perform split\" );\n      fc::time_point start = fc::time_point::now();\n      db.perform_SCORE_split( magnitude );\n      fc::time_point end = fc::time_point::now();\n      ilog( \"VESTS split execution time: ${t} us\", (\"t\",end - start) );\n\n      BOOST_TEST_MESSAGE( \"Verify split took place correctly\" );\n\n      BOOST_REQUIRE( db.get_dynamic_global_properties().current_supply == old_current_supply );\n      BOOST_REQUIRE( db.get_dynamic_global_properties().virtual_supply == old_virtual_supply );\n      BOOST_REQUIRE( db.get_dynamic_global_properties().totalTMEfundForSCORE == old_SCORE_fund );\n      BOOST_REQUIRE( db.get_dynamic_global_properties().totalSCORE.amount == old_SCORE.amount * magnitude );\n      BOOST_REQUIRE( db.get_dynamic_global_properties().totalSCOREreward2 == totalSCOREreward2 );\n      BOOST_REQUIRE( db.get_dynamic_global_properties().total_reward_fund_TME == old_reward_fund );\n\n      BOOST_TEST_MESSAGE( \"Check accounts were updated\" );\n      acnt_itr = acnt_idx.begin();\n      while( acnt_itr != acnt_idx.end() )\n      {\n         BOOST_REQUIRE( acnt_itr->SCORE.amount == accountSCORE[ acnt_itr->name ] * magnitude );\n         BOOST_REQUIRE( acnt_itr->proxied_SCOREfundTMEbalance_votes_total().value == account_SCOREfundTMEbalance_votes[ acnt_itr->name ] * magnitude );\n         acnt_itr++;\n      }\n\n      gpo = db.get_dynamic_global_properties();\n\n      com_itr = com_idx.begin();\n      while( com_itr != com_idx.end() )\n      {\n         BOOST_REQUIRE( com_itr->net_SCOREreward == comment_net_SCOREreward[ std::make_tuple( com_itr->author, com_itr->permlink ) ] * magnitude );\n         BOOST_REQUIRE( com_itr->abs_SCOREreward == comment_abs_SCOREreward[ std::make_tuple( com_itr->author, com_itr->permlink ) ] * magnitude );\n         BOOST_REQUIRE( com_itr->total_vote_weight == total_vote_weights[ com_itr->id ] );\n\n         if( com_itr->net_SCOREreward.value > 0 )\n         {\n            u256 rs( com_itr->net_SCOREreward.value );\n            u256 rf( gpo.total_reward_fund_TME.amount.value );\n            u256 SCOREreward2 = totalSCOREreward2.hi;\n            SCOREreward2 = ( SCOREreward2 << 64 ) + totalSCOREreward2.lo;\n            auto rs2 = rs * rs;\n\n            BOOST_REQUIRE( static_cast< uint64_t >( ( rf * rs2 ) / SCOREreward2 ) == expected_reward[ com_itr->id] );\n         }\n         com_itr++;\n      }\n\n      for( auto cat_itr = cat_idx.begin(); cat_itr != cat_idx.end(); cat_itr++ )\n      {\n         BOOST_REQUIRE( cat_itr->abs_SCOREreward.value == category_SCOREreward[ cat_itr->id ].value * magnitude );\n      }\n\n      validate_database();\n   }\n   FC_LOG_AND_RETHROW()\n}*/\n\nBOOST_AUTO_TEST_CASE( retally_votes )\n{\n   try\n   {\n      flat_map< witness_id_type, share_type > expected_votes;\n\n      const auto& by_account_witness_idx = db.get_index< witness_vote_index >().indices();\n\n      for( auto vote: by_account_witness_idx )\n      {\n         if( expected_votes.find( vote.witness ) == expected_votes.end() )\n            expected_votes[ vote.witness ] = db.get( vote.account ).witness_vote_weight();\n         else\n            expected_votes[ vote.witness ] += db.get( vote.account ).witness_vote_weight();\n      }\n\n      db.retally_witness_votes();\n\n      const auto& witness_idx = db.get_index< witness_index >().indices();\n\n      for( auto witness: witness_idx )\n      {\n         BOOST_REQUIRE_EQUAL( witness.votes.value, expected_votes[ witness.id ].value );\n      }\n   }\n   FC_LOG_AND_RETHROW()\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#endif\n", "meta": {"hexsha": "a49bef25750f6d44b51a0017f454d72dacc0a5bd", "size": 7299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tests/live_tests.cpp", "max_stars_repo_name": "weyoume/wenode", "max_stars_repo_head_hexsha": "5e725aeaaa8aeecf626d235823684bd5744379f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-28T16:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-25T19:24:18.000Z", "max_issues_repo_path": "tests/tests/live_tests.cpp", "max_issues_repo_name": "weyoume/wenode", "max_issues_repo_head_hexsha": "5e725aeaaa8aeecf626d235823684bd5744379f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-18T23:26:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T23:26:36.000Z", "max_forks_repo_path": "tests/tests/live_tests.cpp", "max_forks_repo_name": "weyoume/wenode", "max_forks_repo_head_hexsha": "5e725aeaaa8aeecf626d235823684bd5744379f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-09-10T04:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T14:48:58.000Z", "avg_line_length": 39.8852459016, "max_line_length": 179, "alphanum_fraction": 0.6800931634, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.16792440062279618}}
{"text": "#ifndef FAST_GICP_FAST_VGICP_CUDA_HPP\n#define FAST_GICP_FAST_VGICP_CUDA_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/registration/registration.h>\n\n#include <sophus/so3.hpp>\n#include <fast_gicp/gicp/gicp_settings.hpp>\n\nnamespace fast_gicp {\n\nclass FastVGICPCudaCore;\n\nenum NearestNeighborMethod { CPU_PARALLEL_KDTREE, GPU_BRUTEFORCE };\n\n/**\n * @brief Fast Voxelized GICP algorithm boosted with CUDA\n */\ntemplate<typename PointSource, typename PointTarget>\nclass FastVGICPCuda : public pcl::Registration<PointSource, PointTarget, float> {\npublic:\n  using Scalar = float;\n  using Matrix4 = typename pcl::Registration<PointSource, PointTarget, Scalar>::Matrix4;\n\n  using PointCloudSource = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudSource;\n  using PointCloudSourcePtr = typename PointCloudSource::Ptr;\n  using PointCloudSourceConstPtr = typename PointCloudSource::ConstPtr;\n\n  using PointCloudTarget = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudTarget;\n  using PointCloudTargetPtr = typename PointCloudTarget::Ptr;\n  using PointCloudTargetConstPtr = typename PointCloudTarget::ConstPtr;\n\n  using Ptr = boost::shared_ptr<FastVGICPCuda<PointSource, PointTarget>>;\n\n  using pcl::Registration<PointSource, PointTarget, Scalar>::reg_name_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::input_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::target_;\n\n  using pcl::Registration<PointSource, PointTarget, Scalar>::nr_iterations_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::max_iterations_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::final_transformation_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::transformation_epsilon_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::converged_;\n  using pcl::Registration<PointSource, PointTarget, Scalar>::corr_dist_threshold_;\n\n  FastVGICPCuda();\n  virtual ~FastVGICPCuda() override;\n\n  void setRotationEpsilon(double eps);\n\n  void setResolution(double resolution);\n\n  void setCorrespondenceRandomness(int k);\n\n  void setRegularizationMethod(RegularizationMethod method);\n\n  void setNearesetNeighborSearchMethod(NearestNeighborMethod method);\n\n  void swapSourceAndTarget();\n\n  void clearSource();\n\n  void clearTarget();\n\n  virtual void setInputSource(const PointCloudSourceConstPtr& cloud) override;\n\n  virtual void setInputTarget(const PointCloudTargetConstPtr& cloud) override;\n\nprotected:\n  virtual void computeTransformation(PointCloudSource& output, const Matrix4& guess) override;\n\n  template<typename PointT>\n  std::vector<int> find_neighbors_parallel_kdtree(int k, const boost::shared_ptr<const pcl::PointCloud<PointT>>& cloud, pcl::search::KdTree<PointT>& kdtree) const;\n\nprivate:\nprivate:\n  int k_correspondences_;\n  double rotation_epsilon_;\n\n  pcl::search::KdTree<PointSource> source_kdtree;\n  pcl::search::KdTree<PointTarget> target_kdtree;\n\n  double voxel_resolution_;\n  RegularizationMethod regularization_method_;\n  NearestNeighborMethod neighbor_search_method_;\n\n  std::unique_ptr<FastVGICPCudaCore> vgicp_cuda;\n  };\n}  // namespace fast_gicp\n\n#endif\n", "meta": {"hexsha": "e343b5f7b9b078b8a8ac18d601ae92d459b140d5", "size": 3264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fast_gicp/gicp/fast_vgicp_cuda.hpp", "max_stars_repo_name": "zcbmlijygrdwa/fast_gicp", "max_stars_repo_head_hexsha": "a48f0338d9f8166e8734aa01b045bdb1797364a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-27T08:15:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T11:47:21.000Z", "max_issues_repo_path": "include/fast_gicp/gicp/fast_vgicp_cuda.hpp", "max_issues_repo_name": "shuoshuoxu/fast_gicp", "max_issues_repo_head_hexsha": "ff50fd65b79fa49351e2b44ebd5f9d6a337a7090", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T09:15:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-07T09:15:20.000Z", "max_forks_repo_path": "include/fast_gicp/gicp/fast_vgicp_cuda.hpp", "max_forks_repo_name": "MrBoriska/fast_gicp", "max_forks_repo_head_hexsha": "9dd47c28b6b475b3a518e6ab1f5fa7c915594445", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-04T06:23:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T06:23:19.000Z", "avg_line_length": 33.6494845361, "max_line_length": 163, "alphanum_fraction": 0.8005514706, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.16792440062279612}}
{"text": "#pragma once\n#include \"criteria.hpp\"\n#include <boost/heap/pairing_heap.hpp>\n\nnamespace sssp {\n\nclass smallest_tentative_distance : public criteria {\n  public:\n    smallest_tentative_distance(const sssp::graph* graph, size_t start_node);\n    virtual void relaxable_nodes(todo_output& output) const override;\n    virtual void changed_predecessor(size_t node, size_t predecessor, double distance) override;\n    virtual void relaxed_node(size_t node) override;\n    virtual bool is_complete() const override { return true; }\n\n  private:\n    struct node_info;\n\n    struct node_info_compare {\n        bool operator()(const node_info* a, const node_info* b) const;\n    };\n\n    using queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare>>;\n\n    struct node_info {\n        node_info(size_t index) : index(index) {}\n        size_t index;\n        double tentative_distance = INFINITY;\n        queue::handle_type queue_handle;\n    };\n\n    node_map<node_info> m_node_info;\n    queue m_queue;\n};\n\n} // namespace sssp", "meta": {"hexsha": "053dd9fc85362166d20f6d128e50ca312c64beff", "size": 1033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "crit_dijkstra.hpp", "max_stars_repo_name": "kaini/sssp-simulation", "max_stars_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "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": "crit_dijkstra.hpp", "max_issues_repo_name": "kaini/sssp-simulation", "max_issues_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crit_dijkstra.hpp", "max_forks_repo_name": "kaini/sssp-simulation", "max_forks_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_forks_repo_licenses": ["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.5142857143, "max_line_length": 97, "alphanum_fraction": 0.7173281704, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1679243972238212}}
{"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#ifndef FILECOIN_STORAGE_PROOFS_POREP_STACKED_VANILLA_PROOF_HPP\n#define FILECOIN_STORAGE_PROOFS_POREP_STACKED_VANILLA_PROOF_HPP\n\n#include <boost/filesystem/path.hpp>\n#include <boost/assert.hpp>\n#include <boost/log/trivial.hpp>\n\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/column.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/params.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/porep.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/challenges.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/create_label.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/encoding_proof.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/labelling_proof.hpp>\n\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/detail/processing/naive/params.hpp>\n#include <nil/filecoin/storage/proofs/porep/stacked/vanilla/detail/processing/naive/labelling_proof.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        namespace stacked {\n            namespace vanilla {\n                constexpr static const std::size_t TOTAL_PARENTS = 37;\n\n                template<typename MerkleTreeType, typename Hash>\n                struct StackedDrg {\n                    typedef MerkleTreeType tree_type;\n                    typedef Hash hash_type;\n\n                    typedef typename tree_type::hash_type tree_hash_type;\n\n                    using merkle_proof_type = merkletree::MerkleProof<merkletree::MerkleTree<hash_type>::Hasher,\n                                                                      merkletree::MerkleTree<hash_type>::Arity,\n                                                                      merkletree::MerkleTree<hash_type>::SubTreeArity,\n                                                                      merkletree::MerkleTree<hash_type>::TopTreeArity>;\n\n                    std::vector<std::vector<Proof<tree_type, hash_type>>> prove_layers(\n                        const StackedBucketGraph<tree_hash_type> &graph,\n                        const PublicInputs<typename tree_hash_type::digest_type, typename hash_type::digest_type>\n                            &pub_inputs,\n                        const PersistentAux<typename tree_hash_type::digest_type> &p_aux,\n                        const TemporaryAuxCache<tree_type, hash_type> &t_aux,\n                        const LayerChallenges &layer_challenges,\n                        std::size_t layers,\n                        std::size_t total_layers,\n                        std::size_t partition_count) {\n\n                        assert(layers > 0);\n                        assert(t_aux.labels.size() == layers);\n\n                        std::size_t graph_size = graph.size();\n\n                        // Sanity checks on restored trees.\n                        assert(pub_inputs.tau.is_some());\n                        assert(pub_inputs.tau.comm_d == t_aux.tree_d.root());\n\n                        auto get_drg_parents_columns = [&](std::size_t x) -> std::vector<Column<tree_hash_type>> {\n                            std::size_t base_degree = graph.base_graph().degree();\n\n                            std::vector<Column<tree_hash_type>> columns(base_degree);\n\n                            std::vector<std::uint64_t> parents(0, base_degree);\n                            graph.base_parents(x, parents);\n\n                            for (parents::iterator parent_it = parents.begin(); parent_it != parents.end();\n                                 ++parent_it) {\n                                columns.push_back(t_aux.column(*parent_it));\n                            }\n\n                            assert(columns.size() == base_degree);\n\n                            return columns;\n                        };\n\n                        std::vector<Column<tree_hash_type>> get_exp_parents_columns(std::size_t x) {\n                            std::vector<auto> parents(graph.expansion_degree(), 0);\n                            graph.expanded_parents(x, parents);\n\n                            std::vector<Column<tree_hash_type>> result;\n                            result.reserve(parents.size());\n\n                            for (parents::iterator parent_it = parents.begin(); parent_it != parents.end();\n                                 ++parent_it) {\n                                result.push_back(t_aux.column(*parent_it));\n                            }\n\n                            return result;\n                        }\n\n                        std::vector<std::vector<>> result;\n\n                        for (std::size_t k = 0; k < partition_count; k++) {\n                            std::vector<auto> result_k;\n                            result_k.reserve(challenges.size());    // not sure about actual size of result_k\n\n                            BOOST_LOG_TRIVIAL(trace) << std::format(\"proving partition %d/%d\", k + 1, partition_count);\n\n                            // Derive the set of challenges we are proving over.\n                            std::vector<std::size_t> challenges =\n                                pub_inputs.challenges(layer_challenges, graph_size, Some(k));\n\n                            // Stacked commitment specifics\n                            for (std::size_t challenge_index = 0,\n                                             challenges::iterator challenge_it = challenges.begin();\n                                 challenge_it != challenges.end(); ++challenge_index, ++challenge_it) {\n\n                                BOOST_LOG_TRIVIAL(trace)\n                                    << std::format(\" challenge %d (%d)\", *challenge_it, challenge_index);\n                                BOOST_ASSERT_MSG(*challenge_it < graph.size(), \"Invalid challenge\");\n                                BOOST_ASSERT_MSG(*challenge_it > 0, \"Invalid challenge\");\n\n                                // Initial data layer openings (c_X in Comm_D)\n                                merkle_proof_type<auto> comm_d_proof =\n                                    merkletree::processing::naive::MerkleTree_gen_proof(t_aux.tree_d, *challenge_it);\n\n                                BOOST_ASSERT(comm_d_proof.validate(*challenge_it));\n\n                                // Stacked replica column openings\n                                BOOST_ASSERT(p_aux.comm_c == t_aux.tree_c.root());\n                                auto tree_c = &t_aux.tree_c;\n\n                                // All labels in C_X\n                                BOOST_LOG_TRIVIAL(trace) << \"  c_x\";\n                                auto c_x = t_aux.column(std::uint32_t(*challenge_it)).into_proof(tree_c);\n\n                                // All labels in the DRG parents.\n                                BOOST_LOG_TRIVIAL(trace) << \"  drg_parents\";\n                                std::vector<auto> drg_parents;\n                                drg_parents.reserve();\n\n                                std::vector<auto> drg_parents_columns = get_drg_parents_columns(*challenge_it);\n\n                                for (drg_parents_columns::iterator column_it = drg_parents_columns.begin();\n                                     column_it != drg_parents_columns.end();\n                                     ++column_it) {\n                                    drg_parents.push((*column_it).into_proof(tree_c));\n                                }\n\n                                // Labels for the expander parents\n                                BOOST_LOG_TRIVIAL(trace) << \"  exp_parents\";\n                                std::vector<auto> exp_parents;\n                                exp_parents.reserve();\n\n                                std::vector<auto> exp_parents_columns = get_exp_parents_columns(*challenge_it);\n\n                                for (exp_parents_columns::iterator column_it = exp_parents_columns.begin();\n                                     column_it != exp_parents_columns.end();\n                                     ++column_it) {\n                                    exp_parents.push((*column_it).into_proof(tree_c));\n                                }\n\n                                ReplicaColumnProof rcp = {c_x, drg_parents, exp_parents};\n\n                                // Final replica layer openings\n                                BOOST_LOG_TRIVIAL(trace) << \"final replica layer openings\";\n\n                                merkle_proof_type<auto> comm_r_last_proof =\n                                    merkletree::processing::naive::MerkleTree_gen_cached_proof(\n                                        t_aux.tree_r_last, *challenge_it,\n                                        Some(t_aux.tree_r_last_config_rows_to_discard), );\n\n                                BOOST_ASSERT(comm_r_last_proof.validate(*challenge_it));\n\n                                // Labeling Proofs Layer 1..l\n                                std::vector<auto> labeling_proofs;\n                                labeling_proofs.reserve(layers);\n                                auto encoding_proof = None;\n\n                                for (int layer = 1; layer != layers; layer++) {\n                                    BOOST_LOG_TRIVIAL(trace) << std::format(\"  encoding proof layer %d\", layer);\n                                    std::vector<typename tree_hash_type::digest_type> parents_data;\n\n                                    if (layer == 1) {\n                                        std::vector<auto> parents(graph.base_graph().degree(), 0);\n                                        graph.base_parents(*challenge_it, parents);\n\n                                        parents_data.reserve(parents.size());\n\n                                        for (parents::iterator parent_it = parents.begin(); parent_it != parents.end();\n                                             ++parent_it) {\n\n                                            parents_data.push_back(t_aux.domain_node_at_layer(layer, *parent_it));\n                                        }\n                                    } else {\n                                        std::vector<auto> parents(graph.degree(), 0);\n                                        graph.parents(*challenge_it, parents);\n                                        auto base_parents_count = graph.base_graph().degree();\n\n                                        parents_data.reserve(parents.size());\n\n                                        for (std::size_t i = 0, parents::iterator parent_it = parents.begin();\n                                             parent_it != parents.end(); ++i, ++parent_it) {\n\n                                            if (i < base_parents_count) {\n                                                // parents data for base parents is from the current\n                                                // layer\n                                                parents_data.push_back(t_aux.domain_node_at_layer(layer, *parent_it));\n                                            } else {\n                                                // parents data for exp parents is from the previous\n                                                // layer\n                                                parents_data.push_back(\n                                                    t_aux.domain_node_at_layer(layer - 1, *parent_it));\n                                            }\n                                        }\n                                    }\n\n                                    // repeat parents\n                                    std::vector<auto> parents_data_full(TOTAL_PARENTS, Default::default());\n                                    for (chunk : parents_data_full.chunks_mut(parents_data.size())) {\n                                        chunk.copy_from_slice(&parents_data[..chunk.size()]);\n                                    }\n\n                                    const LabelingProof<typename MerkleTreeType::hash_type> labeling_proof(\n                                        std::uint32_t(layer), std::uint64_t(*challenge_it), parents_data_full.clone());\n\n                                    const auto labeled_node = rcp.c_x.get_node_at_layer(layer);\n                                    BOOST_ASSERT_MSG(\n                                        LabelingProof_naive_verify(labeling_proof, &pub_inputs.replica_id,\n                                                                   &labeled_node),\n                                        std::format(\"Invalid encoding proof generated at layer {}\", layer));\n                                    BOOST_LOG_TRIVIAL(trace)\n                                        << std::format(\"Valid encoding proof generated at layer %d\", layer);\n\n                                    labeling_proofs.push(labeling_proof);\n\n                                    if (layer == layers) {\n                                        encoding_proof = Some(EncodingProof(\n                                            std::uint32_t(layer), std::uint64_t(*challenge_it), parents_data_full));\n                                    }\n                                }\n\n                                result_k.push_back(Proof({.comm_d_proofs = comm_d_proof,\n                                                          .replica_column_proofs = rcp,\n                                                          .comm_r_last_proof,\n                                                          .labeling_proofs,\n                                                          .encoding_proof = encoding_proof}));\n                            }\n                            result.push_back(result_k);\n                        }\n                    }\n\n                    void extract_and_invert_transform_layers(const StackedBucketGraph<tree_hash_type> &graph,\n                                                             const LayerChallenges &layer_challenges,\n                                                             const typename tree_hash_type::digest_type &replica_id,\n                                                             const std::vector<std::uint8_t> &data,\n                                                             const StoreConfig &config) {\n                        BOOST_LOG_TRIVIAL(trace) << \"extract_and_invert_transform_layers\";\n\n                        const auto layers = layer_challenges.layers();\n                        assert(layers > 0);\n\n                        // generate labels\n                        const auto labels = std::get<0>(generate_labels(graph, layer_challenges, replica_id, config));\n\n                        const auto last_layer_labels = labels.labels_for_last_layer();\n                        const auto size = merkletree::store::Store::len(last_layer_labels);\n\n                        for ((key, encoded_node_bytes) :\n                             last_layer_labels.read_range(0..size).into_iter().zip(data.chunks_mut(NODE_SIZE))) {\n\n                            const auto encoded_node =\n                                MerkleTreeType::hash_type::digest_type::try_from_bytes(encoded_node_bytes);\n                            const auto data_node =\n                                decode::<typename MerkleTreeType::hash_type::digest_type>(key, encoded_node);\n\n                            // store result in the data\n                            encoded_node_bytes.copy_from_slice(AsRef::<[u8]>::as_ref(&data_node));\n                        }\n                    }\n\n                    std::tuple<LabelsCache<tree_type>, Labels<tree_type>> generate_labels(\n                        const StackedBucketGraph<tree_hash_type> &graph, const LayerChallenges &layer_challenges,\n                        const typename tree_hash_type::digest_type &replica_id, const StoreConfig &config) {\n\n                        BOOST_LOG_TRIVIAL(info) << \"generate labels\";\n\n                        const auto layers = layer_challenges.layers();\n                        // For now, we require it due to changes in encodings structure.\n                        std::vector<DiskStore<typename MerkleTreeType::hash_type::digest_type>> labels;\n                        labels.reserve(layers);\n\n                        std::vector<StoreConfig> label_configs;\n                        label_configs.reserve(layers);\n\n                        const auto layer_size = graph.size() * NODE_SIZE;\n                        // NOTE: this means we currently keep 2x sector size around, to improve speed.\n                        std::vector<auto> labels_buffer(2 * layer_size, 0u8);\n\n                        const auto use_cache = settings::SETTINGS.lock().maximize_caching;\n                        auto cache = use_cache ? Some(graph.parent_cache()) : None;\n\n                        for (std::size_t layer = 1; layer <= layers; ++layer) {\n                            BOOST_LOG_TRIVIAL(info) << std::format(\"generating layer: %d\", layer);\n                            if (const auto Some(ref mut cache) = cache) {\n                                cache.reset();\n                            }\n\n                            if (layer == 1) {\n                                const auto layer_labels = labels_buffer[..layer_size];\n                                for (std::size_t node = 0; node < graph.size(); ++node) {\n                                    create_label(graph, cache, replica_id, layer_labels, layer, node);\n                                }\n                            } else {\n                                const auto(layer_labels, exp_labels) = labels_buffer.split_at_mut(layer_size);\n                                for (std::size_t node = 0; node < graph.size(); ++node) {\n                                    create_label_exp(graph, cache, replica_id, exp_labels, layer_labels, layer, node);\n                                }\n                            }\n\n                            BOOST_LOG_TRIVIAL(info) << \"  setting exp parents\";\n                            labels_buffer.copy_within(..layer_size, layer_size);\n\n                            // Write the result to disk to avoid keeping it in memory all the time.\n                            const auto layer_config =\n                                StoreConfig::from_config(&config, cache_key::label_layer(layer), Some(graph.size()));\n\n                            BOOST_LOG_TRIVIAL(info) << \"  storing labels on disk\";\n                            // Construct and persist the layer data.\n                            DiskStore<typename tree_hash_type::digest_type> layer_store =\n                                DiskStore::new_from_slice_with_config(graph.size(), MerkleTreeType::base_arity,\n                                                                      &labels_buffer[..layer_size],\n                                                                      layer_config.clone());\n                            BOOST_LOG_TRIVIAL(info)\n                                << std::format(\"  generated layer {} store with id {}\", layer, layer_config.id);\n\n                            // Track the layer specific store and StoreConfig for later retrieval.\n                            labels.push(layer_store);\n                            label_configs.push(layer_config);\n                        }\n\n                        BOOST_ASSERT_MSG(labels.len() == layers, \"Invalid amount of layers encoded expected\");\n\n                        return (LabelsCache<Tree> {labels}, Labels<Tree> {.labels = label_configs});\n                    }\n\n                    template<typename TreeHash>\n                    BinaryMerkleTree<TreeHash> build_binary_tree(const std::vector<std::uint8_t> &tree_data,\n                                                                 const StoreConfig &config) {\n                        BOOST_LOG_TRIVIAL(trace) << std::format(\"building tree (size: %d)\", tree_data.len());\n\n                        std::size_t leafs = tree_data.size() / NODE_SIZE;\n                        assert(tree_data.size() % NODE_SIZE == 0);\n\n                        std::vector<auto> build_tree_vector;\n                        build_tree_vector.reserve(leafs);\n\n                        for (std::size_t i = 0; i < leafs; ++i) {\n                            build_tree_vector.push(get_node::<K>(tree_data, i));\n                        }\n\n                        return MerkleTree::from_par_iter_with_config(build_tree_vector, config);\n                    }\n\n                    template<typename MerkleTreeType>\n                    DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                             MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>\n                        generate_tree_c(std::size_t layers, std::size_t nodes_count, std::size_t tree_count,\n                                        const std::vector<StoreConfig> &configs, const LabelsCache<tree_type> &labels) {\n                        if (settings ::SETTINGS.lock().use_gpu_column_builder) {\n                            return generate_tree_c_gpu<MerkleTreeType>(layers, nodes_count, tree_count, configs,\n                                                                       labels);\n                        } else {\n                            return generate_tree_c_cpu<MerkleTreeType>(layers, nodes_count, tree_count, configs,\n                                                                       labels);\n                        }\n                    }\n\n                    // gather all layer data in parallel.\n                    static auto generate_tree_c_gpu_spawn_0 (???) {\n                        for (std::size_t layer_index = 0, layer_data::iterator layer_elements_it = layer_data.begin();\n                             layer_elements_it != layer_data.end(); ++layer_index, ++layer_elements_it) {\n\n                            const auto store = labels.labels_for_layer(layer_index + 1);\n                            const auto start = (i * nodes_count) + node_index;\n                            const auto end = start + chunked_nodes_count;\n                            const std::vector<typename MerkleTreeType::hash_type::digest_type> elements =\n                                store.read_range(std::ops::Range {start, end});\n                            (*layer_elements_it).extend(elements);\n                        }\n                    }\n\n                    static auto generate_tree_c_gpu_spawn_1 (???) {\n\n                        auto column_tree_builder = ColumnTreeBuilder::<ColumnArity, TreeArity>(\n                            Some(BatcherType::GPU), nodes_count, max_gpu_column_batch_size, max_gpu_tree_batch_size);\n\n                        std::size_t i = 0;\n                        auto config = &configs[i];\n\n                        // Loop until all trees for all configs have been built.\n                        while (i < configs.size()) {\n                            std::vector<GenericArray<Fr, ColumnArity>> columns;\n                            bool is_final;\n\n                            std::tie(columns, is_final) = builder_rx.recv();\n\n                            // Just add non-final column batches.\n                            if (!is_final) {\n                                column_tree_builder.add_columns(&columns);\n                                continue;\n                            };\n\n                            // If we get here, this is a final column: build a sub-tree.\n                            auto base_data, tree_data;\n\n                            std::tie(base_data, tree_data) = column_tree_builder.add_final_columns(&columns);\n                            BOOST_LOG_TRIVIAL(trace)\n                                << std::format(\"base data len {}, tree data len {}\", base_data.len(), tree_data.len());\n\n                            const auto tree_len = base_data.len() + tree_data.len();\n\n                            BOOST_LOG_TRIVIAL(info) << std::format(\"persisting base tree_c {}/{} of length {}\", i + 1,\n                                                                   tree_count, tree_len);\n                            BOOST_ASSERT(base_data.len() == nodes_count);\n                            BOOST_ASSERT(tree_len == config.size);\n\n                            // Persist the base and tree data to disk based using the current store config.\n                            const auto tree_c_store =\n                                DiskStore::<typename MerkleTreeType::hash_type::digest_type>::new_with_config(\n                                    tree_len, MerkleTreeType::base_arity, config.clone());\n\n                            const auto store = Arc(RwLock(tree_c_store));\n                            const auto batch_size = std::cmp::min(base_data.len(), column_write_batch_size);\n                            const auto flatten_and_write_store = | data : &Vec<Fr>,\n                                       offset | {data.into_par_iter()\n                                                     .chunks(column_write_batch_size)\n                                                     .enumerate()\n                                                     .try_for_each(| (index, fr_elements) | {\n                                                         std::vector<auto> buf buf.reserve(batch_size * NODE_SIZE);\n\n                                                         for (fr_elements::iterator fr_it = fr_elements.begin();\n                                                              fr_it != fr_elements.end();\n                                                              ++fr_it) {\n\n                                                             buf.extend(fr_into_bytes(*fr_it));\n                                                         }\n                                                         store.write().copy_from_slice(&buf[..],\n                                                                                       offset + (batch_size * index))\n                                                     })};\n\n                            BOOST_LOG_TRIVIAL(trace)\n                                << std::format(\"flattening tree_c base data of {} nodes using batch size {}\",\n                                               base_data.len(),\n                                               batch_size);\n                            flatten_and_write_store(&base_data, 0);\n                            BOOST_LOG_TRIVIAL(trace) << \"done flattening tree_c base data\";\n\n                            const auto base_offset = base_data.len();\n                            BOOST_LOG_TRIVIAL(trace) << std::format(\n                                \"flattening tree_c tree data of {} nodes using batch size {} and base \"\n                                \"offset \"\n                                \"{}\",\n                                tree_data.len(), batch_size, base_offset);\n                            flatten_and_write_store(&tree_data, base_offset);\n                            BOOST_LOG_TRIVIAL(trace) << \"done flattening tree_c tree data\";\n\n                            BOOST_LOG_TRIVIAL(trace) << \"writing tree_c store data\";\n                            store.write().sync();\n                            BOOST_LOG_TRIVIAL(trace) << \"done writing tree_c store data\";\n\n                            // Move on to the next config.\n                            i += 1;\n                            if (i == configs.size()) {\n                                break;\n                            }\n                            config = &configs[i];\n                        }\n\n                        return ? ? ? ;\n                    }\n\n                    static auto generate_tree_c_gpu_spawn_2 (???) {\n\n                        for (int i = 0; i < config_count; ++i) {\n                            auto node_index = 0;\n                            const auto builder_tx = builder_tx.clone();\n                            while (node_index != nodes_count) {\n                                const auto chunked_nodes_count =\n                                    std::cmp::min(nodes_count - node_index, max_gpu_column_batch_size);\n                                BOOST_LOG_TRIVIAL(trace) << std::format(\"processing config {}/{} with column nodes {}\",\n                                                                        i + 1, tree_count, chunked_nodes_count);\n                                std::vector<GenericArray<Fr, ColumnArity>> columns(\n                                    chunked_nodes_count,\n                                    GenericArray::<Fr, ColumnArity>::generate(| _i\n                                                                              : usize | Fr::zero()));\n\n                                // Allocate layer data array and insert a placeholder for each layer.\n                                std::vector<std::vector<Fr>> layer_data(layers);\n                                std::vector<Fr> layer_data_internal;\n                                layer_data_internal.reserve(chunked_nodes_count);\n                                layer_data.fill(layer_data.begin(), layer_data.end(), layer_data_internal);\n\n                                auto ? ? ? = generate_tree_c_gpu_spawn_0(? ? ?);\n\n                                // Copy out all layer data arranged into columns.\n                                for (int layer_index = 0; layer_index < layer; layer_index++) {\n                                    for (int index = 0; index < chunked_nodes_count) {\n                                        columns[index][layer_index] = layer_data[layer_index][index];\n                                    }\n                                }\n\n                                drop(layer_data);\n\n                                node_index += chunked_nodes_count;\n                                BOOST_LOG_TRIVIAL(trace)\n                                    << std::format(\"node index {}/{}/{}\", node_index, chunked_nodes_count, nodes_count);\n\n                                const auto is_final = node_index == nodes_count;\n                                builder_tx.send((columns, is_final));\n                            }\n                        }\n\n                        auto ? ? ? = generate_tree_c_gpu_spawn_1(? ? ?);\n\n                        return ? ? ? ;\n                    }\n\n                    template<typename MerkleTreeType>\n                    DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                             MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>\n                        generate_tree_c_gpu(std::size_t layers, std::size_t nodes_count, std::size_t tree_count,\n                                            const std::vector<StoreConfig> &configs,\n                                            const LabelsCache<tree_type> &labels) {\n                        BOOST_LOG_TRIVIAL(info) << \"generating tree c using the GPU\";\n                        // Build the tree for CommC\n\n                        BOOST_LOG_TRIVIAL(info) << \"Building column hashes\";\n\n                        // NOTE: The max number of columns we recommend sending to the GPU at once is\n                        // 400000 for columns and 700000 for trees (conservative soft-limits discussed).\n                        //\n                        // 'column_write_batch_size' is how many nodes to chunk the base layer of data\n                        // into when persisting to disk.\n                        //\n                        // Override these values with care using environment variables:\n                        // FIL_PROOFS_MAX_GPU_COLUMN_BATCH_SIZE, FIL_PROOFS_MAX_GPU_TREE_BATCH_SIZE, and\n                        // FIL_PROOFS_COLUMN_WRITE_BATCH_SIZE respectively.\n                        const auto max_gpu_column_batch_size = settings::SETTINGS.lock().max_gpu_column_batch_size;\n                        const auto max_gpu_tree_batch_size = settings::SETTINGS.lock().max_gpu_tree_batch_size;\n                        const auto column_write_batch_size = settings::SETTINGS.lock().column_write_batch_size;\n\n                        // This channel will receive batches of columns and add them to the ColumnTreeBuilder.\n                        const auto(builder_tx, builder_rx) = mpsc::sync_channel(0);\n                        mpsc::sync_channel::<(std::vector<GenericArray<Fr, ColumnArity>>, bool)>(\n                            max_gpu_column_batch_size * ColumnArity::to_usize() * 32);\n\n                        const auto config_count = configs.len();    // Don't move config into closure below.\n\n                        auto ? ? ? = generate_tree_c_gpu_spawn_2(? ? ?);\n\n                        return create_disk_tree<\n                            DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                     MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>>(configs[0].size,\n                                                                                                      &configs);\n                    }\n\n                    static void generate_tree_c_cpu_spawn_0(stf::size_t chunk, auto &hashes_chunk) {\n                        for (std::size_t j = 0, hashes_chunk::iterator hash_it = hashes_chunk.begin();\n                             hash_it != hashes_chunk.end(); ++j, ++hash_it) {\n\n                            const std::vector<auto> data;\n                            data.reserve(layers);\n\n                            for (std::size_t layer = 1; layer <= layers; ++layer) {\n                                const auto store = labels.labels_for_layer(layer);\n                                const typename MerkleTreeType::hash_type::digest_type el =\n                                    store.read_at((i * nodes_count) + j + chunk * chunk_size);\n                                data.push(el);\n                            }\n\n                            (*hash_it) = hash_single_column(data.begin(), data.end());\n                        }\n                    }\n\n                    template<typename MerkleTreeType>\n                    DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                             MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>\n                        generate_tree_c_cpu(std::size_t layers, std::size_t nodes_count, std::size_t tree_count,\n                                            const std::vector<StoreConfig> &configs,\n                                            const LabelsCache<tree_type> &labels) {\n                        BOOST_LOG_TRIVIAL(info) << \"generating tree c using the CPU\";\n\n                        BOOST_LOG_TRIVIAL(info) << \"Building column hashes\";\n\n                        std::vector<auto> trees;\n                        trees.reserve(tree_count);\n\n                        for (std::size_t i = 0, configs::iterator config_it = configs.begin();\n                             config_it != configs.end(); ++i, ++config_it) {\n\n                            std::vector<typename MerkleTreeType::hash_type::digest_type> hashes(\n                                nodes_count, MerkleTreeType::hash_type::digest_type::default());\n\n                            const auto n = num_cpus::get();\n\n                            // only split if we have at least two elements per thread\n                            std::size_t num_chunks = (n > nodes_count * 2) ? 1 : n;\n\n                            // chunk into n chunks\n                            std::size_t chunk_size =\n                                std::ceil(static_cast<double>(nodes_count) / static_cast<double>(num_chunks));\n\n                            // calculate all n chunks in parallel\n                            for ((chunk, hashes_chunk) : hashes.chunks_mut(chunk_size).enumerate()) {\n\n                                generate_tree_c_cpu_spawn_0(chunk, hashes_chunk);\n                            }\n\n                            BOOST_LOG_TRIVIAL(info) << std::format(\"building base tree_c %d/%d\", i + 1, tree_count);\n                            trees.push(DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                                MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>::\n                                           from_par_iter_with_config(hashes.into_par_iter(), (*config_it).clone()));\n                        }\n\n                        BOOST_ASSERT(tree_count == trees.len());\n                        return create_disk_tree<\n                            DiskTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                     MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>>(configs[0].size,\n                                                                                                      &configs);\n                    }\n\n                    static auto generate_tree_r_last_spawn_0(\n                            const DiskStore<typename MerkleTreeType::hash_type::digest_type> last_layer_labels,\n                            ???){\n\n                        for (int i = 0; i < config_count; i++) {\n                            std::size_t node_index = 0;\n                            while (node_index != nodes_count) {\n                                const std::size_t chunked_nodes_count =\n                                    std::cmp::min(nodes_count - node_index, max_gpu_tree_batch_size);\n                                const std::size_t start = (i * nodes_count) + node_index;\n                                const std::size_t end = start + chunked_nodes_count;\n\n                                BOOST_LOG_TRIVIAL(trace) << std::format(\n                                    \"processing config %d/%d with leaf nodes {} [%d, %d, %d-%d]\", i + 1, tree_count,\n                                    chunked_nodes_count, node_index, nodes_count, start, end);\n\n                                const auto encoded_data =\n                                    last_layer_labels.read_range(start..end)\n                                        .into_par_iter()\n                                        .zip(data[(start * NODE_SIZE)..(end * NODE_SIZE)].par_chunks_mut(NODE_SIZE))\n                                        .map(| (key, data_node_bytes) | {\n                                            const auto data_node =\n                                                MerkleTreeType::hash_type::digest_type::try_from_bytes(data_node_bytes);\n                                            const auto encoded_node =\n                                                encode::<typename MerkleTreeType::hash_type::digest_type>(key,\n                                                                                                          data_node);\n                                            data_node_bytes.copy_from_slice(AsRef::<[u8]>::as_ref(&encoded_node));\n\n                                            encoded_node\n                                        });\n\n                                node_index += chunked_nodes_count;\n                                BOOST_LOG_TRIVIAL(trace)\n                                    << std::format(\"node index %d/%d/%d\", node_index, chunked_nodes_count, nodes_count);\n\n                                std::vector<_> encoded = encoded_data.into_par_iter().map(| x | x.into()).collect();\n\n                                const auto is_final = node_index == nodes_count;\n                                builder_tx.send((encoded, is_final));\n                            }\n                        }\n                    }\n\n                    static auto generate_tree_r_last_spawn_1(StoreConfig &tree_r_last_config, ???){\n\n                        auto tree_builder = TreeBuilder::<MerkleTreeType::base_arity>(\n                            Some(BatcherType::GPU), nodes_count, max_gpu_tree_batch_size,\n                            tree_r_last_config.rows_to_discard);\n\n                        std::size_t i = 0;\n                        auto config = &configs[i];\n\n                        // Loop until all trees for all configs have been built.\n                        while (i < configs.size()) {\n\n                            const auto(encoded, is_final) = builder_rx.recv();\n\n                            // Just add non-final leaf batches.\n                            if (!is_final) {\n                                tree_builder.add_leaves(&encoded);\n                                continue;\n                            };\n\n                            // If we get here, this is a final leaf batch: build a sub-tree.\n                            BOOST_LOG_TRIVIAL(info)\n                                << std::format(\"building base tree_r_last with GPU %d/%d\", i + 1, tree_count);\n                            const auto tree_data = std::get<1>(tree_builder.add_final_leaves(&encoded));\n\n                            const auto tree_data_len = tree_data.len();\n                            const auto cache_size = get_merkle_tree_cache_size(\n                                get_merkle_tree_leafs(config.size, MerkleTreeType::base_arity),\n                                MerkleTreeType::base_arity, config.rows_to_discard);\n\n                            BOOST_ASSERT(tree_data_len == cache_size);\n\n                            const std::vector<_> flat_tree_data =\n                                tree_data.into_par_iter().flat_map(| el | fr_into_bytes(&el)).collect();\n\n                            // Persist the data to the store based on the current config.\n                            const boost::filesystem::path tree_r_last_path =\n                                StoreConfig::data_path(&config.path, &config.id);\n\n                            BOOST_LOG_TRIVIAL(trace)\n                                << std::format(\"persisting tree r of len %d with {} rows to discard at path %s\",\n                                               tree_data_len,\n                                               config.rows_to_discard,\n                                               tree_r_last_path.string());\n\n                            boost::filesystem::ofstream f(tree_r_last_path);\n\n                            f << flat_tree_data;\n\n                            // Move on to the next config.\n                            i += 1;\n                            if (i == configs.size()) {\n                                break;\n                            }\n                            config = &configs[i];\n                        }\n                    }\n\n                    template<typename TreeArity = PoseidonArity>\n                    LCTree<tree_hash_type, typename tree_type::Arity, typename tree_type::SubTreeArity,\n                           typename tree_type::TopTreeArity>\n                        generate_tree_r_last(Data &data, std::size_t nodes_count, std::size_t tree_count,\n                                             const StoreConfig &tree_r_last_config,\n                                             const boost::filesystem::path &replica_path,\n                                             const LabelsCache<Tree> &labels) {\n\n                        std::vector<StoreConfig> configs;\n                        ReplicaConfig replica_config;\n                        std::tie(configs, replica_config) =\n                            split_config_and_replica(tree_r_last_config.clone(), replica_path, nodes_count, tree_count);\n\n                        data.ensure_data();\n                        const DiskStore<typename MerkleTreeType::hash_type::digest_type> last_layer_labels =\n                            labels.labels_for_last_layer();\n\n                        if (settings ::SETTINGS.lock().use_gpu_tree_builder) {\n\n                            BOOST_LOG_TRIVIAL(info) << \"generating tree r last using the GPU\";\n\n                            std::uint max_gpu_tree_batch_size = settings::SETTINGS.lock().max_gpu_tree_batch_size;\n\n                            auto builder_tx, builder_rx;\n                            // This channel will receive batches of leaf nodes and add them to the TreeBuilder.\n                            std::tie(builder_tx, builder_rx) = mpsc::sync_channel::<(Vec<Fr>, bool)>(0);\n                            const auto config_count = configs.len();    // Don't move config into closure below.\n\n                            auto ? ? ? = generate_tree_r_last_spawn_0(last_layer_labels, ? ? ?);\n\n                            auto ? ? ? = generate_tree_r_last_spawn_1(tree_r_last_config, ? ? ?);\n                        } else {\n                            BOOST_LOG_TRIVIAL(info) << \"generating tree r last using the CPU\";\n\n                            const auto size = Store::len(last_layer_labels);\n\n                            auto start = 0;\n                            auto end = size / tree_count;\n\n                            for (std::size_t i = 0, configs::iterator config_it = configs.begin();\n                                 config_it != configs.end(); ++i, ++config_it) {\n\n                                const auto encoded_data =\n                                    last_layer_labels.read_range(start..end)\n                                        .into_par_iter()\n                                        .zip(data[(start * NODE_SIZE)..(end * NODE_SIZE)].par_chunks_mut(NODE_SIZE))\n                                        .map(| (key, data_node_bytes) | {\n                                            const auto data_node =\n                                                MerkleTreeType::hash_type::digest_type::try_from_bytes(data_node_bytes);\n\n                                            const auto encoded_node =\n                                                encode::<typename MerkleTreeType::hash_type::digest_type>(key,\n                                                                                                          data_node);\n                                            data_node_bytes.copy_from_slice(AsRef::<[u8]>::as_ref(&encoded_node));\n\n                                            encoded_node\n                                        });\n\n                                BOOST_LOG_TRIVIAL(info)\n                                    << std::format(\"building base tree_r_last with CPU %d/%d\", i + 1, tree_count);\n                                LCTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity, 0,\n                                       0>::from_par_iter_with_config(encoded_data, (*config_it).clone());\n\n                                start = end;\n                                end += size / tree_count;\n                            }\n                        };\n\n                        return create_lc_tree<LCTree<typename MerkleTreeType::hash_type, MerkleTreeType::base_arity,\n                                                     MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>>(\n                            tree_r_last_config.size, &configs, &replica_config);\n                    }\n\n                    TransformedLayers<tree_type, hash_type> transform_and_replicate_layers(\n                        const StackedBucketGraph<tree_hash_type> &graph, const LayerChallenges &layer_challenges,\n                        const typename hash_type::digest_type &replica_id, const Data &data,\n                        const BinaryMerkleTree<G> &data_tree, const StoreConfig &config,\n                        const boost::filesystem::path &replica_path) {\n                        // Generate key layers.\n                        const Labels<tree_type> labels =\n                            std::get<1>(generate_labels(graph, layer_challenges, replica_id, config.clone()));\n\n                        return transform_and_replicate_layers_inner(graph, layer_challenges, data, data_tree, config,\n                                                                    replica_path, labels);\n                    }\n\n                    TransformedLayers<tree_type, hash_type> transform_and_replicate_layers_inner(\n                        const StackedBucketGraph<tree_hash_type> &graph, const LayerChallenges &layer_challenges,\n                        const typename hash_type::digest_type &replica_id, const Data &data,\n                        const BinaryMerkleTree<G> &data_tree, const StoreConfig &config,\n                        const boost::filesystem::path &replica_path, const Labels<tree_type> &label_configs) {\n\n                        BOOST_LOG_TRIVIAL(trace) << \"transform_and_replicate_layers\";\n\n                        std::size_t nodes_count = graph.size();\n\n                        assert(data.len() == nodes_count * NODE_SIZE);\n                        BOOST_LOG_TRIVIAL(trace) << std::format(\"nodes count %d, data len {}\", nodes_count, data.len());\n\n                        std::size_t tree_count = get_base_tree_count::<Tree>();\n                        std::size_t nodes_count = graph.size() / tree_count;\n\n                        // Ensure that the node count will work for binary and oct arities.\n                        bool binary_arity_valid = is_merkle_tree_size_valid(nodes_count, BINARY_ARITY);\n                        bool other_arity_valid = is_merkle_tree_size_valid(nodes_count, MerkleTreeType::base_arity);\n\n                        BOOST_LOG_TRIVIAL(trace) << std::format(\"is_merkle_tree_size_valid(%d, BINARY_ARITY) = {}\",\n                                                                nodes_count, binary_arity_valid);\n                        BOOST_LOG_TRIVIAL(trace) << std::format(\"is_merkle_tree_size_valid(%d, {}) = {}\", nodes_count,\n                                                                MerkleTreeType::base_arity, other_arity_valid);\n\n                        assert(binary_arity_valid);\n                        assert(other_arity_valid);\n\n                        std::size_t layers = layer_challenges.layers();\n                        assert(layers > 0);\n\n                        // Generate all store configs that we need based on the\n                        // cache_path in the specified config.\n                        StoreConfig tree_d_config = StoreConfig::from_config(\n                            config, cache_key::CommDTree.to_string(), get_merkle_tree_len(nodes_count, BINARY_ARITY));\n                        tree_d_config.rows_to_discard = default_rows_to_discard(nodes_count, BINARY_ARITY);\n\n                        StoreConfig tree_r_last_config =\n                            StoreConfig::from_config(config, cache_key::CommRLastTree.to_string(),\n                                                     get_merkle_tree_len(nodes_count, MerkleTreeType::base_arity));\n\n                        // A default 'rows_to_discard' value will be chosen for tree_r_last, unless the user overrides\n                        // this value via the environment setting (FIL_PROOFS_ROWS_TO_DISCARD).  If this value is\n                        // specified, no checking is done on it and it may result in a broken configuration.  Use with\n                        // caution.\n                        tree_r_last_config.rows_to_discard =\n                            default_rows_to_discard(nodes_count, MerkleTreeType::base_arity);\n\n                        BOOST_LOG_TRIVIAL(trace)\n                            << std::format(\"tree_r_last using rows_to_discard={}\", tree_r_last_config.rows_to_discard);\n\n                        StoreConfig tree_c_config = StoreConfig::from_config(\n                            &config, cache_key::CommCTree.to_string(),\n                            Some(get_merkle_tree_len(nodes_count, MerkleTreeType::base_arity)), );\n                        tree_c_config.rows_to_discard =\n                            default_rows_to_discard(nodes_count, MerkleTreeType::base_arity);\n\n                        LabelsCache<tree_type> labels(&label_configs);\n                        const auto configs = split_config(tree_c_config.clone(), tree_count);\n\n                        typename tree_hash_type::digest_type tree_c_root;\n                        if (layers == 2) {\n                            const auto tree_c = generate_tree_c::<U2, MerkleTreeType::base_arity>(\n                                layers, nodes_count, tree_count, configs, &labels);\n                            tree_c_root = tree_c.root();\n                        } else if (layers == 8) {\n                            const auto tree_c = generate_tree_c::<U8, MerkleTreeType::base_arity>(\n                                layers, nodes_count, tree_count, configs, &labels);\n                            tree_c_root = tree_c.root();\n                        } else if (layers == 11) {\n                            const auto tree_c = generate_tree_c::<U11, MerkleTreeType::base_arity>(\n                                layers, nodes_count, tree_count, configs, &labels);\n                            tree_c_root = tree_c.root();\n                        } else {\n                            throw \"Unsupported column arity\";\n                        }\n\n                        BOOST_LOG_TRIVIAL(info) << \"tree_c done\";\n\n                        // Build the MerkleTree over the original data (if needed).\n                        BinaryMerkleTree<Hash> tree_d;\n                        if (data_tree.empty()) {\n                            BOOST_LOG_TRIVIAL(trace) << \"building merkle tree for the original data\";\n                            data.ensure_data();\n                            build_binary_tree::<G>(data, tree_d_config.clone());\n                        } else {\n                            BOOST_LOG_TRIVIAL(trace) << \"using existing original data merkle tree\";\n                            BOOST_ASSERT(t.len() == 2 * (data.len() / NODE_SIZE) - 1);\n                            tree_d = t;\n                        }    // namespace stacked\n\n                        tree_d_config.size = Some(tree_d.len());\n                        BOOST_ASSERT(tree_d_config.size == tree_d.size());\n                        auto tree_d_root = tree_d.root();\n                        drop(tree_d);\n\n                        // Encode original data into the last layer.\n                        BOOST_LOG_TRIVIAL(info) << \"building tree_r_last\";\n                        auto tree_r_last = generate_tree_r_last::<MerkleTreeType::base_arity>(\n                            data, nodes_count, tree_count, tree_r_last_config.clone(), replica_path.clone(), &labels);\n\n                        BOOST_LOG_TRIVIAL(info) << \"tree_r_last done\";\n\n                        const auto tree_r_last_root = tree_r_last.root();\n                        drop(tree_r_last);\n\n                        data.drop_data();\n\n                        // comm_r = H(comm_c || comm_r_last)\n                        typename MerkleTreeType::hash_type::digest_type comm_r =\n                            <typename MerkleTreeType::hash_type>::Function::hash2(&tree_c_root, &tree_r_last_root);\n\n                        return std::make_tuple(\n                            Tau<typename MerkleTreeType::hash_type::digest_type, typename Hash::digest_type>(\n                                {.comm_d = tree_d_root, .comm_r}),\n                            PersistentAux<typename MerkleTreeType::hash_type::digest_type>(\n                                {.comm_c = tree_c_root, .comm_r_last = tree_r_last_root}),\n                            TemporaryAux<MerkleTreeType, Hash>(\n                                {.labels = label_configs, .tree_d_config, .tree_r_last_config, .tree_c_config}));\n                    }\n\n                    /// Phase1 of replication.\n                    Labels<tree_type> replicate_phase1(const PublicParams<tree_type> &pp,\n                                                       const typename tree_hash_type::digest_type &replica_id,\n                                                       const StoreConfig &config) {\n                        BOOST_LOG_TRIVIAL(info) << \"replicate_phase1\";\n\n                        return std::get<1>(generate_labels(&pp.graph, &pp.layer_challenges, replica_id, config));\n                    }\n\n                    std::tuple << Self as PoRep <'a, typename MerkleTreeType::hash_type, G>>::Tau,  <\n                        Self as PoRep <'a, typename MerkleTreeType::hash_type, G> >::ProverAux >  replicate_phase2(\n                            const PublicParams<tree_type> &pp, const Labels<tree_type> &labels, const Data &data,\n                            const BinaryMerkleTree<hash_type> &data_tree, const StoreConfig &config,\n                            const boost::filesystem::path &replica_path) {\n                        BOOST_LOG_TRIVIAL(info) << \"replicate_phase2\";\n\n                        return transform_and_replicate_layers_inner(&pp.graph, &pp.layer_challenges, data,\n                                                                    Some(data_tree), config, replica_path, labels);\n                    }\n\n                    tree_type &_a;\n                    hash_type &_b;\n                };    // StackedDrg\n            }         // namespace vanilla\n        }             // namespace stacked\n    }                 // namespace filecoin\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "22c418aa323d8c3b02478f09b064dd1f6cd7c027", "size": 58206, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/porep/stacked/vanilla/proof.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/porep/stacked/vanilla/proof.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/porep/stacked/vanilla/proof.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": 59.0923857868, "max_line_length": 120, "alphanum_fraction": 0.4656908223, "num_tokens": 9777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1679243972238212}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <list>\n#include <cstdlib>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <future>\n#include <assert.h>\n#include <boost/algorithm/clamp.hpp>\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/util/work_sharder.h\"\n\nusing namespace tensorflow;\nusing namespace std;\ntypedef Eigen::ThreadPoolDevice CPUDevice;\nREGISTER_OP(\"CellEncodeLabel\")\n    .Attr(\"T: {int32, int64}\")\n \t.Attr(\"num_classes: int\")\n    .Input(\"tensor: T\")\n\t.Output(\"tensor_o:T\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tconst auto batch_size = c->Dim(c->input(0),0);\n            int num_classes = 0;\n            c->GetAttr(\"num_classes\",&num_classes);\n            auto shape = c->MakeShape({batch_size,num_classes});\n            c->set_output(0,shape);\n    return Status::OK();\n    });\n\ntemplate <typename Device, typename T>\nclass CellEncodeLabelOp: public OpKernel {\n\tpublic:\n\t\texplicit CellEncodeLabelOp(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"num_classes\", &num_classes_));\n            //\u7b2c\u4e00\u7ea7\u5206\u9cde\uff0c\u817a\uff0cTRI,CC,....\n            //0-7\u8868\u793a\u7b2c\u4e00\u7ea7\n            label_map_level0_[1] = 0;\n            label_map_level0_[2] = 0;\n            label_map_level0_[3] = 2;\n            label_map_level0_[4] = 3;\n            label_map_level0_[5] = 1;\n            label_map_level0_[6] = 4;\n            label_map_level0_[7] = 5;\n            label_map_level0_[8] = 0;\n            label_map_level0_[9] = 6;\n            label_map_level0_[10] = 7;\n            label_map_level0_[11] = 0;\n            label_map_level0_[12] = 0;\n            //\u7b2c\u4e8c\u7ea7\u5206\u4f4e\u7ea7\u522b\u9cde\u72b6\u75c5\u53d8,\u9ad8\u7ea7\u522b\u9cde\u72b6\u75c5\u53d8\n            //8-9\u8868\u793a\u7b2c\u4e8c\u7ea7\n            label_map_level1_[1] = 9;\n            label_map_level1_[11] = 9;\n            label_map_level1_[2] = 8;\n            label_map_level1_[8] = 8;\n            label_map_level1_[12] = 8;\n            //\u7b2c\u4e09\u7ea7\u5206\uff08ASCUS,LSIL0,(ASCH,HSIL,SCC)\n            //10-14\u8868\u793a\u7b2c\u4e09\u7ea7\n            label_map_level2_[1] = 11;\n            label_map_level2_[11] = 10;\n            label_map_level2_[2] = 13;\n            label_map_level2_[8] = 14;\n            label_map_level2_[12] = 12;\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n        {\n            const Tensor &_tensor     = context->input(0);\n            auto          tensor_flat = _tensor.flat<T>().data();\n            const auto    batch_size  = _tensor.dim_size(0);\n            const auto    data_nr     = _tensor.NumElements();\n\n\t\t\tOP_REQUIRES(context, _tensor.dims() == 1, errors::InvalidArgument(\"input must be 1-dimensional\"));\n\n            int dims_2d[] = {batch_size,num_classes_};\n\n            TensorShape outshape;\n            TensorShapeUtils::MakeShape(dims_2d, 2, &outshape);\n\n            Tensor      *output_tensor = nullptr;\n\n            OP_REQUIRES_OK(context,context->allocate_output(0,outshape,&output_tensor));\n\n            auto o_tensor = output_tensor->template tensor<T,2>();\n\n            o_tensor.setZero();\n\n            for(auto i=0; i<data_nr; ++i) {\n                const auto l = tensor_flat[i];\n\n                if(0 == l)\n                    continue;\n\n                auto kt = label_map_level0_.find(l);\n                if(kt == label_map_level0_.end()) {\n                    cout<<\"Error label \"<<l<<endl;\n                    continue;\n                }\n\n                o_tensor(i,kt->second) = 1;\n\n                auto it = label_map_level1_.find(l);\n\n                if(label_map_level1_.end() == it) \n                    continue;\n                o_tensor(i,it->second) = 1;\n                auto jt = label_map_level2_.find(l);\n                if(label_map_level2_.end() == jt) \n                    continue;\n                o_tensor(i,jt->second) = 1;\n            }\n        }\n\tprivate:\n        int num_classes_ = 0;\n        unordered_map<int,int> label_map_level0_;\n        unordered_map<int,int> label_map_level1_;\n        unordered_map<int,int> label_map_level2_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"CellEncodeLabel\").Device(DEVICE_CPU).TypeConstraint<int>(\"T\"), CellEncodeLabelOp<CPUDevice, int>);\nREGISTER_KERNEL_BUILDER(Name(\"CellEncodeLabel\").Device(DEVICE_CPU).TypeConstraint<tensorflow::int64>(\"T\"), CellEncodeLabelOp<CPUDevice, tensorflow::int64>);\n\nREGISTER_OP(\"CellDecodeLabel\")\n    .Attr(\"T: {float, double}\")\n    .Input(\"tensor: T\") //probability\n\t.Output(\"tensor_o:T\")\n\t.SetShapeFn(shape_inference::UnchangedShape);\n\ntemplate <typename Device, typename T>\nclass CellDecodeLabelOp: public OpKernel {\n\tpublic:\n\t\texplicit CellDecodeLabelOp(OpKernelConstruction* context) : OpKernel(context) {\n            //\u7b2c\u4e00\u7ea7\u5206\u9cde\uff0c\u817a\uff0cTRI,CC,....\n            //0-7\u8868\u793a\u7b2c\u4e00\u7ea7\n            label_map_level0_[1] = 5;\n            label_map_level0_[2] = 3;\n            label_map_level0_[3] = 4;\n            label_map_level0_[4] = 6;\n            label_map_level0_[5] = 7;\n            label_map_level0_[6] = 9;\n            label_map_level0_[7] = 10;\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n        {\n            const Tensor &_tensor    = context->input(0);\n\n\t\t\tOP_REQUIRES(context, _tensor.dims() == 2, errors::InvalidArgument(\"input must be 2-dimensional\"));\n\n            auto          tensor     = _tensor.template tensor<T,2>();\n            const auto    batch_size = _tensor.dim_size(0);\n            const auto    C          = _tensor.dim_size(1);\n            const auto    kThreadNr  = 512;\n\n\n            TensorShape  output_shape  = _tensor.shape();\n            Tensor      *output_tensor = nullptr;\n\n            OP_REQUIRES_OK(context,context->allocate_output(0,output_shape,&output_tensor));\n\n            auto o_tensor = output_tensor->template tensor<T,2>();\n            auto i_data = _tensor.template flat<T>().data();\n\n            o_tensor.setZero();\n\n            auto fn = [&](int begin,int end) {\n                for(auto i=begin; i<end; ++i) {\n                    for(auto it=label_map_level0_.begin(); it!=label_map_level0_.end(); ++it) {\n                        o_tensor(i,it->second) = tensor(i,it->first);\n                    }\n                    if(tensor(i,8)>=tensor(i,9)) { //H\n                        auto d = i_data+i*C+12;\n                        auto it = max_element(d,d+3);\n                        auto dis = it-d;\n                        //auto p = max<T>(d[dis],tensor(i,0));\n                        //auto p = tensor(i,0);\n                        auto p = min<T>(d[dis],tensor(i,0));\n\n                        if(dis==0){\n                            o_tensor(i,12) = p;\n                        } else if(dis==1) {\n                            o_tensor(i,2) = p;\n                        } else {\n                            o_tensor(i,8) = p;\n                        }\n                    } else {\n                        if(tensor(i,10)>=tensor(i,11)) {\n                            //o_tensor(i,11) = max<T>(tensor(i,0),tensor(i,10));\n                            //o_tensor(i,11) = tensor(i,0);\n                            o_tensor(i,11) = min<T>(tensor(i,0),tensor(i,10));\n                        } else {\n                            //o_tensor(i,1) = max<T>(tensor(i,0),tensor(i,11));\n                            //o_tensor(i,1) = tensor(i,0);\n                            o_tensor(i,1) = min<T>(tensor(i,0),tensor(i,11));\n                        }\n                    }\n                }\n            };\n\n            list<future<void>> furs;\n\n            for(auto i=0; i<batch_size; i += kThreadNr) {\n                furs.push_back(std::async(std::launch::async,fn,i,min<int>(i+kThreadNr,batch_size)));\n            }\n        }\n\tprivate:\n        unordered_map<int,int> label_map_level0_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"CellDecodeLabel\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), CellDecodeLabelOp<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"CellDecodeLabel\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), CellDecodeLabelOp<CPUDevice, double>);\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\nREGISTER_OP(\"CellEncodeLabel2\")\n    .Attr(\"T: {int32, int64}\")\n    .Input(\"tensor: T\")\n\t.Output(\"tensor_o0:T\")\n\t.Output(\"tensor_o1:T\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tconst auto batch_size = c->Dim(c->input(0),0);\n            int num_classes = 0;\n            auto shape = c->MakeShape({batch_size});\n            c->set_output(0,shape);\n            auto shape1 = c->MakeShape({batch_size});\n            c->set_output(1,shape1);\n    return Status::OK();\n    });\n\ntemplate <typename Device, typename T>\nclass CellEncodeLabel2Op: public OpKernel {\n\tpublic:\n\t\texplicit CellEncodeLabel2Op(OpKernelConstruction* context) : OpKernel(context) {\n            //\u7b2c\u4e00\u7ea7\u5206\u9cde\uff0c\u817a\uff0cTRI,CC,....\n            //0-8\u8868\u793a\u7b2c\u4e00\u7ea7, 0 \u8868\u793a\u80cc\u666f\n            label_map_level0_[1] = 8;\n            label_map_level0_[2] = 8;\n            label_map_level0_[3] = 2;\n            label_map_level0_[4] = 3;\n            label_map_level0_[5] = 1;\n            label_map_level0_[6] = 4;\n            label_map_level0_[7] = 5;\n            label_map_level0_[8] = 8;\n            label_map_level0_[9] = 6;\n            label_map_level0_[10] = 7;\n            label_map_level0_[11] = 8;\n            label_map_level0_[12] = 8;\n            //\u7b2c\u4e8c\u7ea7\u5206\u4f4e\u7ea7\u522b\u9cde\u72b6\u75c5\u53d8,\u9ad8\u7ea7\u522b\u9cde\u72b6\u75c5\u53d8\n            //8-9\u8868\u793a\u7b2c\u4e8c\u7ea7\n            label_map_level1_[11] = 0;\n            label_map_level1_[1] = 1;\n            label_map_level1_[12] = 3; //\u589e\u52a0\u4e86LSIL\u4e0eASCH\u4e4b\u95f4\u7684\u8ddd\u79bb\n            label_map_level1_[2] = 4;\n            label_map_level1_[8] = 5;\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n        {\n            const Tensor &_tensor     = context->input(0);\n            auto          tensor_flat = _tensor.flat<T>().data();\n            const auto    batch_size  = _tensor.dim_size(0);\n            const auto    data_nr     = _tensor.NumElements();\n\n\t\t\tOP_REQUIRES(context, _tensor.dims() == 1, errors::InvalidArgument(\"input must be 1-dimensional\"));\n\n            int dims_1d0[] = {batch_size};\n            int dims_1d1[] = {batch_size};\n\n            TensorShape outshape0;\n            TensorShape outshape1;\n            TensorShapeUtils::MakeShape(dims_1d0, 1, &outshape0);\n            TensorShapeUtils::MakeShape(dims_1d1, 1, &outshape1);\n\n            Tensor      *output_tensor0 = nullptr;\n            Tensor      *output_tensor1 = nullptr;\n\n            OP_REQUIRES_OK(context,context->allocate_output(0,outshape0,&output_tensor0));\n            OP_REQUIRES_OK(context,context->allocate_output(1,outshape1,&output_tensor1));\n\n            auto o_tensor0 = output_tensor0->template tensor<T,1>();\n            auto o_tensor1 = output_tensor1->template tensor<T,1>();\n\n            o_tensor0.setZero();\n            o_tensor1.setZero();\n\n            for(auto i=0; i<data_nr; ++i) {\n                const auto l = tensor_flat[i];\n                auto tp = label_map_level0_[l];\n\n                o_tensor0(i) = tp;\n                if(8 == tp) {\n                    auto it = label_map_level1_.find(l);\n\n                    if(label_map_level1_.end() == it) {\n                        cout<<\"Error label \"<<l<<endl;\n                        continue;\n                    }\n                    o_tensor1(i) = it->second;\n                } else {\n                    o_tensor1(i) = -1; //\u5982\u679c\u4e0d\u662f\u9cde\u72b6\u75c5\u53d8\uff0c\u9ed8\u8ba4\u4e3a-1\n                }\n            }\n        }\n\tprivate:\n        unordered_map<int,int> label_map_level0_;\n        unordered_map<int,int> label_map_level1_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"CellEncodeLabel2\").Device(DEVICE_CPU).TypeConstraint<int>(\"T\"), CellEncodeLabel2Op<CPUDevice, int>);\nREGISTER_KERNEL_BUILDER(Name(\"CellEncodeLabel2\").Device(DEVICE_CPU).TypeConstraint<tensorflow::int64>(\"T\"), CellEncodeLabel2Op<CPUDevice, tensorflow::int64>);\n\nREGISTER_OP(\"CellDecodeLabel2\")\n    .Attr(\"T: {float, double}\")\n \t.Attr(\"num_classes: int\")\n    .Input(\"tensor0: T\") //probability\n    .Input(\"tensor1: T\") //regs\n\t.Output(\"tensor_o:T\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tconst auto batch_size = c->Dim(c->input(0),0);\n            int num_classes = 0;\n            c->GetAttr(\"num_classes\",&num_classes);\n            auto shape = c->MakeShape({batch_size,num_classes});\n            c->set_output(0,shape);\n    return Status::OK();\n    });\n\ntemplate <typename Device, typename T>\nclass CellDecodeLabel2Op: public OpKernel {\n\tpublic:\n\t\texplicit CellDecodeLabel2Op(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"num_classes\", &num_classes_));\n            //\u7b2c\u4e00\u7ea7\u5206\u9cde\uff0c\u817a\uff0cTRI,CC,....\n            //0-7\u8868\u793a\u7b2c\u4e00\u7ea7\n            label_map_level0_[1] = 5;\n            label_map_level0_[2] = 3;\n            label_map_level0_[3] = 4;\n            label_map_level0_[4] = 6;\n            label_map_level0_[5] = 7;\n            label_map_level0_[6] = 9;\n            label_map_level0_[7] = 10;\n            //\n            label_map_level1_[0] = 11;\n            label_map_level1_[1] = 1;\n            label_map_level1_[3] = 12;\n            label_map_level1_[4] = 2;\n            label_map_level1_[5] = 8;\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n        {\n            const Tensor &_tensor0    = context->input(0);\n            const Tensor &_tensor1    = context->input(1);\n\n\t\t\tOP_REQUIRES(context, _tensor0.dims() == 2, errors::InvalidArgument(\"input0 must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, _tensor1.dims() == 2, errors::InvalidArgument(\"input1 must be 2-dimensional\"));\n\n            auto          tensor0     = _tensor0.template tensor<T,2>();\n            auto          tensor1     = _tensor1.template tensor<T,2>();\n            const auto    batch_size = _tensor0.dim_size(0);\n            const auto    kThreadNr  = 512;\n\n\n            int dims_2d[] = {batch_size,num_classes_};\n            TensorShape outshape;\n            Tensor      *output_tensor = nullptr;\n\n            TensorShapeUtils::MakeShape(dims_2d, 2, &outshape);\n\n            OP_REQUIRES_OK(context,context->allocate_output(0,outshape,&output_tensor));\n\n            auto o_tensor = output_tensor->template tensor<T,2>();\n\n            o_tensor.setZero();\n\n            auto fn = [&](int begin,int end) {\n                for(auto i=begin; i<end; ++i) {\n                    for(auto it=label_map_level0_.begin(); it!=label_map_level0_.end(); ++it) {\n                        o_tensor(i,it->second) = tensor0(i,it->first);\n                    }\n                    auto index = int(tensor1(i,0)+0.5);\n                    float scale = 1.0;\n                    if(2 == index) {\n                        index = int(tensor1(i,0));\n                        if(2 == index)\n                            index = 3;\n                    } else if(index<=-1) {\n                        scale = 0.5;\n                    }\n                    index = max(min(index,5),0);\n                    auto idx = label_map_level1_[index];\n                    o_tensor(i,idx) = tensor0(i,8)*scale;\n                }\n            };\n\n            list<future<void>> furs;\n\n            for(auto i=0; i<batch_size; i += kThreadNr) {\n                furs.push_back(std::async(std::launch::async,fn,i,min<int>(i+kThreadNr,batch_size)));\n            }\n        }\n\tprivate:\n        unordered_map<int,int> label_map_level0_;\n        unordered_map<int,int> label_map_level1_;\n        int num_classes_ = 0;\n};\nREGISTER_KERNEL_BUILDER(Name(\"CellDecodeLabel2\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), CellDecodeLabel2Op<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"CellDecodeLabel2\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), CellDecodeLabel2Op<CPUDevice, double>);\n", "meta": {"hexsha": "ec9db96e39cecc5b38adc817848ff0583eb5648e", "size": 15610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tfop/cell_ops.cpp", "max_stars_repo_name": "vghost2008/wml", "max_stars_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-10T17:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T01:00:35.000Z", "max_issues_repo_path": "tfop/cell_ops.cpp", "max_issues_repo_name": "vghost2008/wml", "max_issues_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T16:16:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T05:21:19.000Z", "max_forks_repo_path": "tfop/cell_ops.cpp", "max_forks_repo_name": "vghost2008/wml", "max_forks_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-07T09:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T04:58:10.000Z", "avg_line_length": 38.1662591687, "max_line_length": 158, "alphanum_fraction": 0.5495836003, "num_tokens": 4034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16792439042587137}}
{"text": "#ifndef PROPOSALTARGET_OP_HPP\n#define PROPOSALTARGET_OP_HPP\n\n#include \"bbox.h\"\n#include \"proposaltarget_op.h\"\n\n#include <Eigen/Dense>\n#include <tuple>\n\nnamespace mxnet {\nnamespace op {\n\ntemplate <typename xpu>\nclass ProposalTargetOp : public Operator {\n public:\n  explicit ProposalTargetOp(ProposalTargetParam param) { this->param_ = param; }\n\n  virtual void Forward(const OpContext& ctx,\n                       const std::vector<TBlob>& in_data,\n                       const std::vector<OpReqType>& req,\n                       const std::vector<TBlob>& out_data,\n                       const std::vector<TBlob>& /*aux_states*/) override {\n    using namespace mshadow;\n    using namespace mshadow::expr;\n    CHECK_EQ(param_.batch_images, in_data[1].shape_[0]);\n    using namespace mshadow;\n    mshadow::Stream<xpu>* s = ctx.get_stream<xpu>();\n\n    // get input tensors\n    // rois [n, 5] (batch_index, x1, y1, x2, y2)\n    Tensor<xpu, 2> all_rois_x = in_data[0].get<xpu, 2, real_t>(s);\n    // gt_boxes [b, n, 5] (x1, y1, x2, y2, cls)\n    Tensor<xpu, 3> all_gt_boxes_x = in_data[1].get<xpu, 3, real_t>(s);\n\n    // define result shapes\n    auto rois_shape = Shape2(static_cast<index_t>(param_.batch_rois), 5);\n    auto label_shape = Shape1(static_cast<index_t>(param_.batch_rois));\n    auto bbox_target_shape =\n        Shape2(static_cast<index_t>(param_.batch_rois),\n               static_cast<index_t>(param_.num_classes * 4));\n    auto bbox_weight_shape =\n        Shape2(static_cast<index_t>(param_.batch_rois),\n               static_cast<index_t>(param_.num_classes * 4));\n\n    // ---------------- Main logic - cpu version ----------------------------\n    auto rois_per_image = param_.batch_rois / param_.batch_images;\n    auto fg_rois_per_image =\n        static_cast<int>(std::round(param_.fg_fraction * rois_per_image));\n    std::vector<float> box_stds;\n    box_stds.assign(param_.box_stds.begin(), param_.box_stds.end());\n\n    using EigenMatrix =\n        Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    EigenMatrix rois(rois_shape[0], rois_shape[1]);\n    EigenMatrix labels(label_shape[0], 1);\n    EigenMatrix bbox_targets(bbox_target_shape[0], bbox_target_shape[1]);\n    EigenMatrix bbox_weights(bbox_weight_shape[0], bbox_weight_shape[1]);\n\n    EigenMatrix all_rois(all_rois_x.shape_[0], all_rois_x.shape_[1]);\n    Tensor<cpu, 2, real_t> all_rois_t(all_rois.data(), all_rois_x.shape_);\n    Copy(all_rois_t, all_rois_x, s);\n\n    EigenMatrix batch_gt_boxes(all_gt_boxes_x.shape_[1],\n                               all_gt_boxes_x.shape_[2]);\n    for (int batch_idx = 0; batch_idx < param_.batch_images; ++batch_idx) {\n      //----------------------------------------------\n      // select gt boxes related to the current batch element\n      Tensor<cpu, 2, real_t> all_gt_boxes_t(\n          batch_gt_boxes.data(),\n          Shape2(all_gt_boxes_x.shape_[1], all_gt_boxes_x.shape_[2]));\n      Copy(all_gt_boxes_t, all_gt_boxes_x[static_cast<index_t>(batch_idx)], s);\n\n      // select gt boxes with foreground class\n      auto gt_boxes_count = (batch_gt_boxes.col(4).array() > 0).count();\n      Eigen::MatrixXf gt_boxes(gt_boxes_count, all_gt_boxes_x.shape_[2]);\n      for (Eigen::Index i = 0, j = 0; i < batch_gt_boxes.rows();\n           ++i) {  // col major\n        if (batch_gt_boxes(i, 4) > 0)\n          gt_boxes.row(j++) = batch_gt_boxes.row(i);\n      }\n      //----------------------------------------------\n      // select rois related to the current batch element, images have different\n      // size so rois count can also be different\n      auto batch_rois_count =\n          (all_rois.col(0).array() == static_cast<float>(batch_idx)).count();\n\n      Eigen::MatrixXf batch_rois(\n          batch_rois_count,\n          all_rois.cols() - 1);  // exclude batch index col\n      for (Eigen::Index i = 0, j = 0; i < all_rois.rows(); ++i) {  // col major\n        if (static_cast<int>(all_rois(i, 0)) == batch_idx)\n          batch_rois.row(j++) = all_rois.row(i).rightCols(4);\n      }\n\n      //----------------------------------------------\n      // Include ground-truth boxes in the set of candidate rois\n      {\n        Eigen::MatrixXf rois_and_gt(batch_rois.rows() + gt_boxes.rows(),\n                                    rois.cols() - 1);\n        rois_and_gt << batch_rois,\n            gt_boxes.block(0, 0, gt_boxes.rows(), gt_boxes.cols() - 1);\n        batch_rois = rois_and_gt;\n      }\n\n      //----------------------------------------------\n      // mark rois for this batch\n      rois.block(batch_idx * rois_per_image, 0, rois_per_image, 1).array() =\n          batch_idx;\n\n      //----------------------------------------------\n      // generate random sample of ROIs comprising foreground and background\n      // examples\n      auto b_rois = rois.block(batch_idx * rois_per_image, 1, rois_per_image,\n                               rois.cols() - 1);\n      auto b_labels = labels.block(batch_idx * rois_per_image, 0,\n                                   rois_per_image, labels.cols());\n      auto b_bbox_targets = bbox_targets.block(\n          batch_idx * rois_per_image, 0, rois_per_image, bbox_targets.cols());\n      auto b_bbox_weights = bbox_weights.block(\n          batch_idx * rois_per_image, 0, rois_per_image, bbox_weights.cols());\n      std::tie(b_rois, b_labels, b_bbox_targets, b_bbox_weights) =\n          SampleRois(batch_rois, gt_boxes, param_.num_classes, rois_per_image,\n                     fg_rois_per_image, param_.fg_overlap, box_stds);\n    }\n\n    Tensor<cpu, 2, real_t> rois_t(rois.data(), rois_shape);\n    Tensor<cpu, 1, real_t> labels_t(labels.data(), label_shape);\n    Tensor<cpu, 2, real_t> bbox_targets_t(bbox_targets.data(),\n                                          bbox_target_shape);\n    Tensor<cpu, 2, real_t> bbox_weights_t(bbox_weights.data(),\n                                          bbox_weight_shape);\n\n    // ---------------- Main logic end --------------------------\n\n    // get destination tensors\n    Tensor<xpu, 2> out0 =\n        out_data[0].get_with_shape<xpu, 2, real_t>(rois_shape, s);\n    Tensor<xpu, 1> out1 =\n        out_data[1].get_with_shape<xpu, 1, real_t>(label_shape, s);\n    Tensor<xpu, 2> out2 =\n        out_data[2].get_with_shape<xpu, 2, real_t>(bbox_target_shape, s);\n    Tensor<xpu, 2> out3 =\n        out_data[3].get_with_shape<xpu, 2, real_t>(bbox_weight_shape, s);\n\n    // copy results\n    for (auto r : req) {\n      CHECK_EQ(kWriteTo, r);\n    }\n\n    Copy(out0, rois_t, s);\n    Copy(out1, labels_t, s);\n    Copy(out2, bbox_targets_t, s);\n    Copy(out3, bbox_weights_t, s);\n  }\n\n  void Backward(const OpContext& ctx,\n                const std::vector<TBlob>& /*out_grad*/,\n                const std::vector<TBlob>& /*in_data*/,\n                const std::vector<TBlob>& /*out_data*/,\n                const std::vector<OpReqType>& req,\n                const std::vector<TBlob>& in_grad,\n                const std::vector<TBlob>& /*aux_states*/) override {\n    using namespace mshadow;\n    using namespace mshadow::expr;\n    CHECK_EQ(in_grad.size(), 2);\n\n    Stream<xpu>* s = ctx.get_stream<xpu>();\n    auto grad0 = in_grad[0].get<xpu, 2, real_t>(s);\n    auto grad1 = in_grad[1].get<xpu, 3, real_t>(s);\n\n    // can not assume the grad would be zero\n    Assign(grad0, req[0], 0);\n    Assign(grad1, req[1], 0);\n  }\n\n private:\n  ProposalTargetParam param_;\n};  // class ProposalOp\n\n}  // namespace op\n}  // namespace mxnet\n#endif  // PROPOSALTARGET_OP_HPP\n", "meta": {"hexsha": "d9da36a3a74c35db3138686b7e83501a8d05114e", "size": 7437, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rcnn-mxnet/proposaltarget_op.hpp", "max_stars_repo_name": "yf225/mlcpp", "max_stars_repo_head_hexsha": "12d6f8224d7d6305a191c7afd2d5510e0a15299f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 268.0, "max_stars_repo_stars_event_min_datetime": "2018-04-11T15:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:18:03.000Z", "max_issues_repo_path": "rcnn-mxnet/proposaltarget_op.hpp", "max_issues_repo_name": "soma2000-lang/mlcpp", "max_issues_repo_head_hexsha": "afb08c0c81bdd2c68710831e8d4b233005ab3750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-02-10T22:19:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-23T05:55:50.000Z", "max_forks_repo_path": "rcnn-mxnet/proposaltarget_op.hpp", "max_forks_repo_name": "soma2000-lang/mlcpp", "max_forks_repo_head_hexsha": "afb08c0c81bdd2c68710831e8d4b233005ab3750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2018-04-19T21:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T17:11:00.000Z", "avg_line_length": 40.6393442623, "max_line_length": 80, "alphanum_fraction": 0.5975527767, "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16792438565575052}}
{"text": "/* Copyright Institute of Sound and Vibration Research - All rights reserved */\n\n#include <libsignalflows/baseline_renderer.hpp>\n\n#include <libefl/basic_matrix.hpp>\n\n#include <libpanning/LoudspeakerArray.h>\n\n#include <libvisr/signal_flow_context.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/filesystem/operations.hpp>\n\n#include <ciso646>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <sstream>\n\nnamespace visr\n{\nnamespace objectmodel\n{\nnamespace test\n{\n\nBOOST_AUTO_TEST_CASE( InstantiateRenderer )\n{\n  boost::filesystem::path const arrayConfigFile( CMAKE_SOURCE_DIR \"/config/generic/bs2051-9+10+3.xml\" );\n  BOOST_CHECK( exists( arrayConfigFile ) and not is_directory( arrayConfigFile ) );\n\n  panning::LoudspeakerArray arrayConfig;\n  arrayConfig.loadXmlFile( arrayConfigFile.string() );\n\n  std::size_t const numberOfInputs = 16;\n  std::size_t const numberOfOutputs = 40;\n  std::size_t const period = 128;\n  std::size_t const interpolationPeriod = 16 * period;\n  std::size_t const numRealLoudspeakers = arrayConfig.getNumRegularSpeakers();\n  std::size_t const diffusionFilterLength = 512;\n  efl::BasicMatrix<SampleType> const diffusionFilters( numRealLoudspeakers, diffusionFilterLength );\n\n  std::string const trackingConfig( \"\" );\n\n  // Construct the reverb configuration\n  std::size_t const numReverbObjects = 5;\n  std::size_t const discreteReflectionsPerObject = 4;\n  double const lateFilterLengthSeconds = 0.05;\n  std::string const lateDiffusionFilters( CMAKE_SOURCE_DIR \"/config/filters/random_phase_allpass_64ch_512taps.wav\" );\n  double const maximumDiscreteReflectionDelay = 0.23456f;\n\n  std::size_t const numInputEqSections = 0;\n\n  std::stringstream reverbConfig;\n  reverbConfig << \"{ \\\"numReverbObjects\\\": \" << numReverbObjects\n               << \", \\\"discreteReflectionsPerObject\\\": \" << discreteReflectionsPerObject\n               << \", \\\"lateReverbFilterLength\\\": \" << lateFilterLengthSeconds\n               << \", \\\"maxDiscreteReflectionDelay\\\": \" << maximumDiscreteReflectionDelay\n               << \", \\\"lateReverbDecorrelationFilters\\\": \\\"\" << lateDiffusionFilters\n               << \"\\\" }\";\n\n  SignalFlowContext context( period, 48000 );\n\n  signalflows::BaselineRenderer( context, \"\", nullptr,\n                                 arrayConfig,\n                                 numberOfInputs,\n                                 numberOfOutputs,\n                                 interpolationPeriod,\n                                 diffusionFilters,\n                                 trackingConfig,\n                                 8888,\n                                 numInputEqSections,\n                                 reverbConfig.str(),\n                                 false // No frequency-dependent panning.\n                                 );\n}\n\n} // namespace test\n} // namespace objectmodel\n} // namespce visr\n", "meta": {"hexsha": "d33ebad41c128894c6eaca31f7619f87951d8508", "size": 2901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libsignalflows/test/baseline_renderer.cpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/libsignalflows/test/baseline_renderer.cpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_issues_repo_licenses": ["ISC"], "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/libsignalflows/test/baseline_renderer.cpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 35.3780487805, "max_line_length": 117, "alphanum_fraction": 0.6525336091, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.16791437864915126}}
{"text": "\n// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com>\n// Distributed under the Modified BSD License, see license.txt.\n\n#include \"highres_time_stamp.h\"\n\n#include <cassert>\n\n#include <boost/cast.hpp>\n\n#include <scm/log.h>\n\nnamespace scm {\nnamespace time {\nnamespace detail {\n\nhigh_res_time_stamp::~high_res_time_stamp()\n{\n}\n\n\ninline time_duration high_res_time_stamp::get_overhead() const\n{\n    return (_overhead);\n}\n\n#if SCM_PLATFORM == SCM_PLATFORM_WINDOWS\n\n#include <scm/core/platform/windows.h>\n\nnamespace\n{\n\ntime_stamp get_pfc_frequency()\n{\n    LARGE_INTEGER       frequency;\n\n    if (!QueryPerformanceFrequency(&frequency)) {\n        char* error_msg;\n\n        FormatMessage(  FORMAT_MESSAGE_IGNORE_INSERTS\n                      | FORMAT_MESSAGE_FROM_SYSTEM\n                      | FORMAT_MESSAGE_ALLOCATE_BUFFER,\n                      0,\n                      GetLastError(),\n                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n                      (LPTSTR)&error_msg,\n                      1024,\n                      0);\n\n        scm::err() << log::error\n                   << \"high_res_time_stamp::initialize(): \"\n                   << \"error obtaining performance counter frequency\" << log::nline\n                   << \" - system error message: \" << log::nline << \"    \"\n                   << error_msg\n                   << log::end;\n\n        LocalFree(error_msg);\n\n        return (false);\n    }\n\n    return (boost::numeric_cast<time_stamp>(frequency.QuadPart));\n}\n\ntime_stamp      pfc_frequency = time_stamp(0);\n\n} // namespace \n\nhigh_res_time_stamp::high_res_time_stamp()\n    : _overhead(time_duration(0, 0, 0, 0))\n{\n    pfc_frequency = get_pfc_frequency();\n}\n\nbool high_res_time_stamp::initialize()\n{\n    // calculate overhead of 'now' funktion\n\n    return (true);\n}\n\ntime_stamp high_res_time_stamp::ticks_per_second()\n{\n    return (pfc_frequency);\n}\n\ntime_stamp high_res_time_stamp::now()\n{\n    static LARGE_INTEGER       current_time_counter;\n\n    if (!QueryPerformanceCounter(&current_time_counter)) {\n        char* error_msg;\n\n        FormatMessage(  FORMAT_MESSAGE_IGNORE_INSERTS\n                      | FORMAT_MESSAGE_FROM_SYSTEM\n                      | FORMAT_MESSAGE_ALLOCATE_BUFFER,\n                      0,\n                      GetLastError(),\n                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n                      (LPTSTR)&error_msg,\n                      1024,\n                      0);\n\n        scm::err() << log::error\n                   << \"high_res_time_stamp::now(): \"\n                   << \"error obtaining performance counter\" << log::nline\n                   << \" - system error message: \" << log::nline << \"    \"\n                   << error_msg\n                   << log::end;\n\n        LocalFree(error_msg);\n\n        return (0);\n    }\n\n    return (boost::numeric_cast<time_stamp>(current_time_counter.QuadPart));\n}\n\n#elif    SCM_PLATFORM == SCM_PLATFORM_LINUX \\\n      || SCM_PLATFORM == SCM_PLATFORM_APPLE\n\n#include <ctime>\n\nhigh_res_time_stamp::high_res_time_stamp()\n    : _overhead(time_duration(0, 0, 0, 0))\n{\n}\n\nbool high_res_time_stamp::initialize()\n{\n    // calculate overhead of 'now' funktion\n\n    return (true);\n}\n\ntime_stamp high_res_time_stamp::ticks_per_second()\n{\n    return (1000000000);\n}\n\ntime_stamp high_res_time_stamp::now()\n{\n    static timespec current_time;\n    \n    clock_gettime(CLOCK_MONOTONIC, &current_time);\n\n    return (  boost::numeric_cast<time_stamp>(current_time.tv_sec) * 1000000000\n            + boost::numeric_cast<time_stamp>(current_time.tv_nsec));\n}\n\n#endif // SCM_PLATFORM == SCM_PLATFORM_WINDOWS\n\n} // namespace detail\n} // namespace time\n} // namespace scm\n\n", "meta": {"hexsha": "9b78162866df7d0bb36d3344cfb49de01700e096", "size": 3675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scm_core/src/scm/core/time/detail/highres_time_stamp.cpp", "max_stars_repo_name": "Nyran/schism", "max_stars_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-09-17T06:01:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T07:10:20.000Z", "max_issues_repo_path": "scm_core/src/scm/core/time/detail/highres_time_stamp.cpp", "max_issues_repo_name": "Nyran/schism", "max_issues_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T14:11:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-12T10:26:53.000Z", "max_forks_repo_path": "scm_core/src/scm/core/time/detail/highres_time_stamp.cpp", "max_forks_repo_name": "Nyran/schism", "max_forks_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T20:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-02T19:03:20.000Z", "avg_line_length": 23.2594936709, "max_line_length": 83, "alphanum_fraction": 0.5991836735, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1676733152451158}}
{"text": "#include \"base.hpp\"\n#include \"constants.hpp\"\n\n#include <boost/math/special_functions/round.hpp>\n#include <cmath>\n#include <jngl.hpp>\n#include <sstream>\n#include <thread>\n\nJNGL_MAIN_BEGIN {\n\tjngl::setScaleFactor(\n\t    std::floor(std::min(jngl::getDesktopWidth() / 800, jngl::getDesktopHeight() / 600)));\n\tjngl::showWindow(\"Bike\", boost::math::iround(screenWidth * jngl::getScaleFactor()),\n\t                 boost::math::iround(screenHeight * jngl::getScaleFactor()));\n\tBase base;\n\tdouble oldTime = jngl::getTime();\n\tbool needDraw = true;\n\twhile (jngl::running()) {\n\t\tif (jngl::getTime() - oldTime > timePerFrame) {\n\t\t\t// This stuff needs to be done 100 times per second\n\t\t\toldTime += timePerFrame;\n\t\t\tneedDraw = true;\n\t\t\tbase.DoFrame();\n\t\t} else {\n\t\t\tif (needDraw) {\n\t\t\t\tneedDraw = false;\n\t\t\t\t// This needs to be done when \"needDraw\" is true\n\t\t\t\tjngl::updateInput();\n\t\t\t\tjngl::translate(-jngl::getScreenWidth() / 2.0, -jngl::getScreenHeight() / 2.0);\n\t\t\t\tbase.Draw();\n\t\t\t\tjngl::swapBuffers();\n\t\t\t} else {\n\t\t\t\t// Nothing to do? Okay let's Sleep.\n\t\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\t\t\t}\n\t\t}\n\t}\n} JNGL_MAIN_END\n", "meta": {"hexsha": "2ca2e55ff563c7d0dd4766021c91d76eed2a1bf5", "size": 1136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/bike/main.cpp", "max_stars_repo_name": "jhasse/jngl", "max_stars_repo_head_hexsha": "1aab1bb5b9712eca50786418d44e9559373441a8", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T14:42:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:56:54.000Z", "max_issues_repo_path": "examples/bike/main.cpp", "max_issues_repo_name": "jhasse/jngl", "max_issues_repo_head_hexsha": "1aab1bb5b9712eca50786418d44e9559373441a8", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-08-10T19:28:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T07:18:00.000Z", "max_forks_repo_path": "examples/bike/main.cpp", "max_forks_repo_name": "jhasse/jngl", "max_forks_repo_head_hexsha": "1aab1bb5b9712eca50786418d44e9559373441a8", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-14T18:08:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:29:19.000Z", "avg_line_length": 29.1282051282, "max_line_length": 90, "alphanum_fraction": 0.6549295775, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.16767331372483668}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ 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 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 \"grid_function.hpp\"\n\n#include \"abstract_boundary_operator_pseudoinverse.hpp\"\n#include \"assembly_options.hpp\"\n#include \"boundary_operator.hpp\"\n#include \"context.hpp\"\n#include \"discrete_boundary_operator.hpp\"\n#include \"identity_operator.hpp\"\n#include \"local_assembler_construction_helper.hpp\"\n\n#include \"../common/complex_aux.hpp\"\n#include \"../common/deprecated.hpp\"\n#include \"../fiber/collection_of_3d_arrays.hpp\"\n#include \"../fiber/basis.hpp\"\n#include \"../fiber/basis_data.hpp\"\n#include \"../fiber/collection_of_basis_transformations.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../fiber/function.hpp\"\n#include \"../fiber/local_assembler_for_grid_functions.hpp\"\n#include \"../fiber/opencl_handler.hpp\"\n#include \"../fiber/quadrature_strategy.hpp\"\n#include \"../fiber/raw_grid_geometry.hpp\"\n#include \"../grid/geometry_factory.hpp\"\n#include \"../grid/grid.hpp\"\n#include \"../grid/grid_view.hpp\"\n#include \"../grid/entity_iterator.hpp\"\n#include \"../grid/entity.hpp\"\n#include \"../grid/mapper.hpp\"\n#include \"../grid/vtk_writer_helper.hpp\"\n#include \"../space/space.hpp\"\n#include \"identity_operator.hpp\"\n#include \"../io/gmsh.hpp\"\n\n#include <boost/array.hpp>\n#include <fstream>\n#include <set>\n#include <sstream>\n\nnamespace Bempp {\n\n// Internal routines\n\nnamespace {\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<arma::Col<ResultType>> reallyCalculateProjections(\n    const Space<BasisFunctionType> &dualSpace,\n    Fiber::LocalAssemblerForGridFunctions<ResultType> &assembler,\n    const AssemblyOptions &options) {\n  // TODO: parallelise using TBB (the parameter options will then start be used)\n\n  // Get the grid's leaf view so that we can iterate over elements\n  const GridView &view = dualSpace.gridView();\n  const size_t elementCount = view.entityCount(0);\n\n  // Global DOF indices corresponding to local DOFs on elements\n  std::vector<std::vector<GlobalDofIndex>> testGlobalDofs(elementCount);\n  std::vector<std::vector<BasisFunctionType>> testLocalDofWeights(elementCount);\n\n  // Gather global DOF lists\n  const Mapper &mapper = view.elementMapper();\n  std::unique_ptr<EntityIterator<0>> it = view.entityIterator<0>();\n  while (!it->finished()) {\n    const Entity<0> &element = it->entity();\n    const int elementIndex = mapper.entityIndex(element);\n    dualSpace.getGlobalDofs(element, testGlobalDofs[elementIndex],\n                            testLocalDofWeights[elementIndex]);\n    it->next();\n  }\n\n  // Make a vector of all element indices\n  std::vector<int> testIndices(elementCount);\n  for (size_t i = 0; i < elementCount; ++i)\n    testIndices[i] = i;\n\n  // Create the weak form's column vector\n  shared_ptr<arma::Col<ResultType>> result(\n      new arma::Col<ResultType>(dualSpace.globalDofCount()));\n  result->fill(0.);\n\n  std::vector<arma::Col<ResultType>> localResult;\n  // Evaluate local weak forms\n  assembler.evaluateLocalWeakForms(testIndices, localResult);\n\n  // Loop over test indices\n  for (size_t testIndex = 0; testIndex < elementCount; ++testIndex)\n    // Add the integrals to appropriate entries in the global weak form\n    for (size_t testDof = 0; testDof < testGlobalDofs[testIndex].size();\n         ++testDof) {\n      int testGlobalDof = testGlobalDofs[testIndex][testDof];\n      if (testGlobalDof >= 0) // if it's negative, it means that this\n                              // local dof is constrained (not used)\n        (*result)(testGlobalDof) +=\n            conj(testLocalDofWeights[testIndex][testDof]) *\n            localResult[testIndex](testDof);\n    }\n\n  // Return the vector of projections <phi_i, f>\n  return result;\n}\n\n/** \\brief Calculate projections of the function on the basis functions of\n  the given dual space. */\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<arma::Col<ResultType>>\ncalculateProjections(const Context<BasisFunctionType, ResultType> &context,\n                     const Function<ResultType> &globalFunction,\n                     const Space<BasisFunctionType> &dualSpace) {\n  const AssemblyOptions &options = context.assemblyOptions();\n\n  // Prepare local assembler\n  typedef typename Fiber::ScalarTraits<ResultType>::RealType CoordinateType;\n  typedef Fiber::RawGridGeometry<CoordinateType> RawGridGeometry;\n  typedef std::vector<const Fiber::Shapeset<BasisFunctionType> *>\n  ShapesetPtrVector;\n  typedef LocalAssemblerConstructionHelper Helper;\n\n  shared_ptr<RawGridGeometry> rawGeometry;\n  shared_ptr<GeometryFactory> geometryFactory;\n  shared_ptr<Fiber::OpenClHandler> openClHandler;\n  shared_ptr<ShapesetPtrVector> testShapesets;\n\n  Helper::collectGridData(dualSpace, rawGeometry, geometryFactory);\n  Helper::makeOpenClHandler(options.parallelizationOptions().openClOptions(),\n                            rawGeometry, openClHandler);\n  Helper::collectShapesets(dualSpace, testShapesets);\n\n  // Get reference to the test shapeset transformation\n  const Fiber::CollectionOfShapesetTransformations<CoordinateType> &\n  testTransformations = dualSpace.basisFunctionValue();\n\n  typedef Fiber::LocalAssemblerForGridFunctions<ResultType> LocalAssembler;\n  std::unique_ptr<LocalAssembler> assembler =\n      context.quadStrategy()->makeAssemblerForGridFunctions(\n          geometryFactory, rawGeometry, testShapesets,\n          make_shared_from_ref(testTransformations),\n          make_shared_from_ref(globalFunction), openClHandler);\n\n  return reallyCalculateProjections(dualSpace, *assembler, options);\n}\n\n/** \\brief Evaluate the function at the interpolation points of the chosen\n * space. */\ntemplate <typename BasisFunctionType, typename ResultType>\narma::Col<ResultType> interpolate(const Function<ResultType> &globalFunction,\n                                  const Space<BasisFunctionType> &space) {\n  size_t deps = 0;\n  globalFunction.addGeometricalDependencies(deps);\n  if (deps & ~(Fiber::GLOBALS | Fiber::NORMALS))\n    throw std::invalid_argument(\n        \"interpolate(): functions to be interpolated \"\n        \"must not depend on any geometrical data besides global \"\n        \"coordinates and normal vectors\");\n\n  typedef typename Fiber::ScalarTraits<ResultType>::RealType CoordinateType;\n  Fiber::GeometricalData<CoordinateType> geomData;\n  if (deps & Fiber::GLOBALS) {\n    space.getGlobalDofInterpolationPoints(geomData.globals);\n  }\n  if (deps & Fiber::NORMALS) {\n    space.getNormalsAtGlobalDofInterpolationPoints(geomData.normals);\n  }\n  arma::Mat<ResultType> values;\n  globalFunction.evaluate(geomData, values);\n\n  const size_t componentCount = values.n_rows;\n  const size_t pointCount = values.n_cols;\n\n  arma::Mat<CoordinateType> directions;\n  space.getGlobalDofInterpolationDirections(directions);\n  assert(directions.n_rows == values.n_rows);\n  assert(directions.n_cols == pointCount);\n\n  arma::Col<ResultType> result(pointCount);\n  result.fill(0);\n  for (size_t p = 0; p < pointCount; ++p)\n    for (size_t d = 0; d < componentCount; ++d)\n      result(p) += values(d, p) * directions(d, p);\n  return result;\n}\n\n} // namespace\n\n// Recommended constructors\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>::GridFunction() {}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>::GridFunction(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &space,\n    const arma::Col<ResultType> &coefficients) {\n  initializeFromCoefficients(context, space, coefficients);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>::GridFunction(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &space,\n    const shared_ptr<const Space<BasisFunctionType>> &dualSpace,\n    const arma::Col<ResultType> &projections) {\n\n  initializeFromProjections(context, space, dualSpace, projections);\n  m_dualSpace = dualSpace;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>::GridFunction(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &space,\n    const shared_ptr<const Space<BasisFunctionType>> &dualSpace,\n    const Function<ResultType> &function, ConstructionMode mode)\n    : m_context(context), m_space(space), m_dualSpace(dualSpace) {\n  if (!context)\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): context must not be null\");\n  if (!space)\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): space must not be null\");\n  if (!dualSpace)\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): dualSpace must not be null\");\n\n  if (space->codomainDimension() != dualSpace->codomainDimension())\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): \"\n        \"functions from 'space' and 'dualSpace' have a different \"\n        \"number of components\");\n  if (function.codomainDimension() != space->codomainDimension())\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): \"\n        \"functions from 'space' have a different number of \"\n        \"components than 'function'\");\n  if (mode != APPROXIMATE && mode != INTERPOLATE)\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): \"\n        \"'mode' must be either APPROXIMATE or INTERPOLATE\");\n\n  bool isBarycentricSpace =\n      (space->isBarycentric() || dualSpace->isBarycentric());\n  if (isBarycentricSpace) {\n    m_space = space->barycentricSpace(space);\n    m_dualSpace = dualSpace->barycentricSpace(dualSpace);\n  }\n  if (m_space->grid() != m_dualSpace->grid())\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): \"\n        \"space and dualSpace must be defined on the same grid\");\n\n  if (mode == APPROXIMATE)\n    setProjections(m_dualSpace,\n                   *calculateProjections(*context, function, *m_dualSpace));\n  else // mode == INTERPOLATE\n    setCoefficients(interpolate(function, *m_space));\n}\n\n// Deprecated constructors\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>::GridFunction(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &space,\n    const shared_ptr<const Space<BasisFunctionType>> &dualSpace,\n    const arma::Col<ResultType> &data, DataType dataType) {\n  bool isBarycentricSpace = false;\n  if (space && space->isBarycentric())\n    isBarycentricSpace = true;\n\n  if (dualSpace && dualSpace->isBarycentric())\n    isBarycentricSpace = true;\n\n  shared_ptr<const Space<BasisFunctionType>> newSpace(space);\n  shared_ptr<const Space<BasisFunctionType>> newDualSpace(dualSpace);\n  if (isBarycentricSpace) {\n    newSpace = space->barycentricSpace(space);\n    if (dualSpace)\n      newDualSpace = dualSpace->barycentricSpace(dualSpace);\n  }\n\n  if (dataType == COEFFICIENTS) {\n    if (newDualSpace && newSpace->grid() != newDualSpace->grid())\n      throw std::invalid_argument(\n          \"GridFunction::GridFunction(): \"\n          \"space and dualSpace must be defined on the same grid\");\n    initializeFromCoefficients(context, newSpace, data);\n    m_dualSpace = newDualSpace;\n  } else if (dataType == PROJECTIONS) {\n    initializeFromProjections(context, newSpace, newDualSpace, data);\n    m_dualSpace = newDualSpace;\n  } else\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): invalid dataType\");\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>::GridFunction(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &space,\n    const shared_ptr<const Space<BasisFunctionType>> &dualSpace,\n    const arma::Col<ResultType> &coefficients,\n    const arma::Col<ResultType> &projections) {\n  bool isBarycentricSpace = false;\n  if (space && space->isBarycentric())\n    isBarycentricSpace = true;\n\n  if (dualSpace && dualSpace->isBarycentric())\n    isBarycentricSpace = true;\n\n  shared_ptr<const Space<BasisFunctionType>> newSpace(space);\n  shared_ptr<const Space<BasisFunctionType>> newDualSpace(dualSpace);\n  if (isBarycentricSpace) {\n    newSpace = space->barycentricSpace(space);\n    if (dualSpace)\n      newDualSpace = dualSpace->barycentricSpace(dualSpace);\n  }\n\n  // We ignore the vector of projections.\n  initializeFromCoefficients(context, newSpace, coefficients);\n  if (newDualSpace && newSpace->grid() != newDualSpace->grid())\n    throw std::invalid_argument(\n        \"GridFunction::GridFunction(): \"\n        \"space and dualSpace must be defined on the same grid\");\n  m_dualSpace = newDualSpace;\n}\n\n// Member functions\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::initializeFromCoefficients(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &space,\n    const arma::Col<ResultType> &coefficients) {\n  if (!context)\n    throw std::invalid_argument(\n        \"GridFunction::initializeFromCoefficients(): context must not be null\");\n  if (!space)\n    throw std::invalid_argument(\n        \"GridFunction::initializeFromCoefficients(): space must not be null\");\n  if (coefficients.n_rows != space->globalDofCount())\n    throw std::invalid_argument(\"GridFunction::initializeFromCoefficients(): \"\n                                \"the coefficients vector has incorrect length\");\n  m_context = context;\n  m_space = space;\n  setCoefficients(coefficients);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::initializeFromProjections(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &space,\n    const shared_ptr<const Space<BasisFunctionType>> &dualSpace,\n    const arma::Col<ResultType> &projections) {\n  if (!context)\n    throw std::invalid_argument(\n        \"GridFunction::initializeFromProjections(): context must not be null\");\n  if (!space)\n    throw std::invalid_argument(\n        \"GridFunction::initializeFromProjections(): space must not be null\");\n  if (!dualSpace)\n    throw std::invalid_argument(\"GridFunction::initializeFromProjections(): \"\n                                \"dualSpace must not be null\");\n  bool isBarycentricSpace =\n      (space->isBarycentric() || dualSpace->isBarycentric());\n  if (isBarycentricSpace) {\n    m_space = space->barycentricSpace(space);\n    m_dualSpace = dualSpace->barycentricSpace(dualSpace);\n  } else {\n    m_space = space;\n    m_dualSpace = dualSpace;\n  }\n  if (m_space->grid() != m_dualSpace->grid())\n    throw std::invalid_argument(\n        \"GridFunction::initializeFromProjections(): \"\n        \"space and dualSpace must be defined on the same grid\");\n\n  if (projections.n_rows != dualSpace->globalDofCount())\n    throw std::invalid_argument(\"GridFunction::initializeFromProjections(): \"\n                                \"the projections vector has incorrect length\");\n  m_context = context;\n  setProjections(m_dualSpace, projections);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nbool GridFunction<BasisFunctionType, ResultType>::isInitialized() const {\n  return (bool)m_space;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nbool\nGridFunction<BasisFunctionType, ResultType>::wasInitializedFromCoefficients()\n    const {\n  return m_wasInitializedFromCoefficients;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const Grid>\nGridFunction<BasisFunctionType, ResultType>::grid() const {\n  if (!m_space)\n    throw std::runtime_error(\"GridFunction::grid() must not be called \"\n                             \"on an uninitialized GridFunction object\");\n\n  return m_space->grid();\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const Space<BasisFunctionType>>\nGridFunction<BasisFunctionType, ResultType>::space() const {\n  return m_space;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const Space<BasisFunctionType>>\nGridFunction<BasisFunctionType, ResultType>::dualSpace() const {\n  return m_dualSpace;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const Context<BasisFunctionType, ResultType>>\nGridFunction<BasisFunctionType, ResultType>::context() const {\n  return m_context;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nint GridFunction<BasisFunctionType, ResultType>::componentCount() const {\n  if (!m_space)\n    throw std::runtime_error(\n        \"GridFunction::componentCount() must not be called \"\n        \"on an uninitialized GridFunction object\");\n\n  return m_space->codomainDimension();\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>\nGridFunction<BasisFunctionType, ResultType>::approximateInSpace(\n    const shared_ptr<Space<BasisFunctionType>> &space) const {\n\n  BoundaryOperator<BasisFunctionType, ResultType> id =\n      identityOperator<BasisFunctionType, ResultType>(m_context, m_space, space,\n                                                      space);\n  return id * (*this);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nconst arma::Col<ResultType> &\nGridFunction<BasisFunctionType, ResultType>::coefficients() const {\n  if (!m_space || (!m_coefficients && !m_projections))\n    throw std::runtime_error(\"GridFunction::coefficients() must not be called \"\n                             \"on an uninitialized GridFunction object\");\n  if (!m_coefficients)\n    updateCoefficientsFromProjections();\n  return *m_coefficients;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::setCoefficients(\n    const arma::Col<ResultType> &coeffs) {\n  if (!m_space)\n    throw std::runtime_error(\n        \"GridFunction::setCoefficients() must not be called \"\n        \"on an uninitialized GridFunction object\");\n  if (coeffs.n_rows != m_space->globalDofCount())\n    throw std::invalid_argument(\n        \"GridFunction::setCoefficients(): dimension of the provided \"\n        \"vector does not match the number of global DOFs in the primal space\");\n  m_coefficients.reset(new arma::Col<ResultType>(coeffs));\n  m_projections.reset();\n  m_wasInitializedFromCoefficients = true;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\narma::Col<ResultType> GridFunction<BasisFunctionType, ResultType>::projections(\n    const shared_ptr<const Space<BasisFunctionType>> &dualSpace_) const {\n  if (!m_space)\n    throw std::runtime_error(\"GridFunction::projections() must not be called \"\n                             \"on an uninitialized GridFunction object\");\n  if (m_space->grid() != dualSpace_->grid())\n    if (!m_space->grid()->isBarycentricRepresentationOf(*dualSpace_->grid()) &&\n        !dualSpace_->grid()->isBarycentricRepresentationOf(*m_space->grid()))\n      throw std::invalid_argument(\n          \"GridFunction::projections(): \"\n          \"space and dual space must be defined on the same grid\");\n\n  if (!m_coefficients && !m_projections)\n    throw std::runtime_error(\"GridFunction::projections() must not be called \"\n                             \"on an uninitialized GridFunction object\");\n  if (!m_projections || !m_dualSpace->spaceIsCompatible(*dualSpace_))\n    updateProjectionsFromCoefficients(dualSpace_);\n  return *m_projections;\n}\n\n// Deprecated version\ntemplate <typename BasisFunctionType, typename ResultType>\narma::Col<ResultType> GridFunction<BasisFunctionType, ResultType>::projections(\n    const Space<BasisFunctionType> &dualSpace_) const {\n  if (!m_dualSpace)\n    throw std::runtime_error(\n        \"You must provide the dualSpace_ argument in the call to \"\n        \"GridFunction::projections() if you did not specify the \"\n        \"dual space when constructing the GridFunction.\");\n  arma::Col<ResultType> result = projections(make_shared_from_ref(dualSpace_));\n  // update the coefficients because we can't guarantee\n  // dualSpace_ will stay alive until they are needed\n  coefficients();\n  return result;\n}\n\n// Deprecated version\ntemplate <typename BasisFunctionType, typename ResultType>\narma::Col<ResultType>\nGridFunction<BasisFunctionType, ResultType>::projections() const {\n  if (!m_dualSpace)\n    throw std::runtime_error(\n        \"You must provide the dualSpace_ argument in the call to \"\n        \"GridFunction::projections() if you did not specify the \"\n        \"dual space when constructing the GridFunction.\");\n  return projections(m_dualSpace);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::setProjections(\n    const shared_ptr<const Space<BasisFunctionType>> &dualSpace_,\n    const arma::Col<ResultType> &projects) {\n  if (!m_space)\n    throw std::runtime_error(\n        \"GridFunction::setProjections() must not be called \"\n        \"on an uninitialized GridFunction object\");\n  if (m_space->grid() != dualSpace_->grid())\n    throw std::invalid_argument(\n        \"GridFunction::setProjections(): \"\n        \"space and dual space must be defined on the same grid\");\n  if (projects.n_rows != dualSpace_->globalDofCount())\n    throw std::invalid_argument(\n        \"GridFunction::setProjections(): dimension of the provided \"\n        \"vector does not match the number of global DOFs in the dual space\");\n\n  m_projections = boost::make_shared<arma::Col<ResultType>>(projects);\n  m_dualSpace = dualSpace_;\n  m_coefficients.reset();\n  m_wasInitializedFromCoefficients = false;\n}\n\n// Deprecated version\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::setProjections(\n    const Space<BasisFunctionType> &dualSpace_,\n    const arma::Col<ResultType> &projects) {\n  setProjections(make_shared_from_ref(dualSpace_), projects);\n  // update the coefficients because we can't guarantee\n  // dualSpace_ will stay alive until they are needed\n  coefficients();\n}\n\n// Deprecated version\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::setProjections(\n    const arma::Col<ResultType> &projects) {\n  if (!m_dualSpace)\n    throw std::runtime_error(\n        \"You must provide the dualSpace_ argument in the call to \"\n        \"GridFunction::setProjections() if you did not specify the \"\n        \"dual space when constructing the GridFunction.\");\n  setProjections(m_dualSpace, projects);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid\nGridFunction<BasisFunctionType, ResultType>::updateProjectionsFromCoefficients(\n    const shared_ptr<const Space<BasisFunctionType>> &dualSpace_) const {\n  // This should have been checked beforehand, this is after all a private\n  // function. So omit these checks in release mode.\n  assert(isInitialized());\n  assert(dualSpace_);\n  assert(m_coefficients);\n\n  // Calculate the mass matrix\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n  BoundaryOp id = identityOperator(m_context, m_space, m_space, dualSpace_);\n\n  shared_ptr<arma::Col<ResultType>> newProjections(\n      new arma::Col<ResultType>(dualSpace_->globalDofCount()));\n  id.weakForm()->apply(NO_TRANSPOSE, *m_coefficients, *newProjections,\n                       static_cast<ResultType>(1.),\n                       static_cast<ResultType>(0.));\n  m_projections = newProjections;\n  m_dualSpace = dualSpace_;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid\nGridFunction<BasisFunctionType, ResultType>::updateCoefficientsFromProjections()\n    const {\n  // This should have been checked beforehand, this is after all a private\n  // function. So omit these checks in release mode.\n  assert(isInitialized());\n  assert(m_projections);\n  assert(m_dualSpace);\n\n  // Calculate the (pseudo)inverse mass matrix\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n  BoundaryOp id = identityOperator(m_context, m_space, m_space, m_dualSpace);\n  BoundaryOp pinvId = pseudoinverse(id);\n\n  shared_ptr<arma::Col<ResultType>> newCoefficients(\n      new arma::Col<ResultType>(m_space->globalDofCount()));\n  pinvId.weakForm()->apply(NO_TRANSPOSE, *m_projections, *newCoefficients,\n                           static_cast<ResultType>(1.),\n                           static_cast<ResultType>(0.));\n  m_coefficients = newCoefficients;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\ntypename GridFunction<BasisFunctionType, ResultType>::MagnitudeType\nGridFunction<BasisFunctionType, ResultType>::L2Norm() const {\n  // The L^2 norm is given by\n  //   sqrt(u^\\dagger M u),\n  // where u is the coefficient vector and M the mass matrix of m_space\n\n  if (!m_space)\n    throw std::runtime_error(\"GridFunction::L2_Norm() must not be called \"\n                             \"on an uninitialized GridFunction object\");\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n\n  // Get the vector of coefficients\n  const arma::Col<ResultType> &coeffs = coefficients();\n\n  // Calculate the mass matrix\n  BoundaryOp id = identityOperator(m_context, m_space, m_space, m_space);\n  shared_ptr<const DiscreteBoundaryOperator<ResultType>> massMatrix =\n      id.weakForm();\n\n  arma::Col<ResultType> product(coeffs.n_rows);\n  massMatrix->apply(NO_TRANSPOSE, coeffs, product, 1., 0.);\n  ResultType result = arma::cdot(coeffs, product);\n  if (fabs(imagPart(result)) >\n      1000. * std::numeric_limits<MagnitudeType>::epsilon())\n    std::cout << \"Warning: squared L2Norm has non-negligible imaginary part: \"\n              << imagPart(result) << std::endl;\n  return sqrt(realPart(result));\n}\n\n// Redundant, in fact -- can be obtained directly from Space\ntemplate <typename BasisFunctionType, typename ResultType>\nconst Fiber::Shapeset<BasisFunctionType> &\nGridFunction<BasisFunctionType, ResultType>::shapeset(const Entity<0> &element)\n    const {\n  BOOST_ASSERT_MSG(m_space, \"GridFunction::shapeset() must not be \"\n                            \"called on an uninitialized GridFunction object\");\n  return m_space->shapeset(element);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::getLocalCoefficients(\n    const Entity<0> &element, std::vector<ResultType> &coeffs) const {\n  BOOST_ASSERT_MSG(m_space, \"GridFunction::getLocalCoefficients() must not be \"\n                            \"called on an uninitialized GridFunction object\");\n  std::vector<GlobalDofIndex> gdofIndices;\n  std::vector<BasisFunctionType> ldofWeights;\n  m_space->getGlobalDofs(element, gdofIndices, ldofWeights);\n  const int gdofCount = gdofIndices.size();\n  coeffs.resize(gdofCount);\n  const arma::Col<ResultType> &globalCoefficients = coefficients();\n  for (int i = 0; i < gdofCount; ++i) {\n    int gdof = gdofIndices[i];\n    if (gdof >= 0)\n      coeffs[i] = globalCoefficients(gdof) * ldofWeights[i];\n    else\n      coeffs[i] = 0.;\n  }\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::exportToVtk(\n    VtkWriter::DataType dataType, const char *dataLabel,\n    const char *fileNamesBase, const char *filesPath,\n    VtkWriter::OutputType outputType) const {\n  Bempp::exportToVtk(*this, dataType, dataLabel, fileNamesBase, filesPath,\n                     outputType);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::evaluateAtSpecialPoints(\n    VtkWriter::DataType dataType, arma::Mat<ResultType> &result_) const {\n  arma::Mat<CoordinateType> points;\n  evaluateAtSpecialPoints(dataType, points, result_);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::evaluateAtSpecialPoints(\n    VtkWriter::DataType dataType, arma::Mat<CoordinateType> &points,\n    arma::Mat<ResultType> &values) const {\n  if (!m_space)\n    throw std::runtime_error(\n        \"GridFunction::evaluateAtSpecialPoints() must \"\n        \"not be called on an uninitialized GridFunction object\");\n  if (dataType != VtkWriter::CELL_DATA && dataType != VtkWriter::VERTEX_DATA)\n    throw std::invalid_argument(\"GridFunction::evaluateAtSpecialPoints(): \"\n                                \"invalid data type\");\n\n  const GridView &view = m_space->gridView();\n  const int gridDim = m_space->gridDimension();\n  const int worldDim = m_space->worldDimension();\n  const int elementCodim = 0;\n  const int vertexCodim = gridDim;\n  const int nComponents = componentCount();\n\n  const size_t elementCount = view.entityCount(elementCodim);\n  const size_t vertexCount = view.entityCount(vertexCodim);\n\n  values.set_size(nComponents, dataType == VtkWriter::CELL_DATA ? elementCount\n                                                                : vertexCount);\n  values.fill(0.);\n  points.set_size(worldDim, values.n_cols);\n\n  // Number of elements contributing to each column in result\n  // (this will be greater than 1 for VERTEX_DATA)\n  std::vector<int> multiplicities(vertexCount);\n  std::fill(multiplicities.begin(), multiplicities.end(), 0);\n\n  // Gather geometric data\n  Fiber::RawGridGeometry<CoordinateType> rawGeometry(gridDim,\n                                                     m_space->worldDimension());\n  view.getRawElementData(rawGeometry.vertices(),\n                         rawGeometry.elementCornerIndices(),\n                         rawGeometry.auxData(), rawGeometry.domainIndices());\n\n  // Make geometry factory\n  shared_ptr<const Grid> grid = m_space->grid();\n  std::unique_ptr<GeometryFactory> geometryFactory =\n      grid->elementGeometryFactory();\n  std::unique_ptr<typename GeometryFactory::Geometry> geometry(\n      geometryFactory->make());\n  Fiber::GeometricalData<CoordinateType> geomData;\n\n  // For each element, get its shapeset and corner count (this is sufficient\n  // to identify its geometry) as well as its local coefficients\n  typedef std::pair<const Fiber::Shapeset<BasisFunctionType> *, int>\n  ShapesetAndCornerCount;\n  typedef std::vector<ShapesetAndCornerCount> ShapesetAndCornerCountVector;\n  ShapesetAndCornerCountVector basesAndCornerCounts(elementCount);\n  std::vector<std::vector<ResultType>> localCoefficients(elementCount);\n  {\n    const Mapper &mapper = view.elementMapper();\n    std::unique_ptr<EntityIterator<0>> it = view.entityIterator<0>();\n    for (size_t e = 0; e < elementCount; ++e) {\n      const Entity<0> &element = it->entity();\n      const int elementIndex = mapper.entityIndex(element);\n      basesAndCornerCounts[elementIndex] =\n          ShapesetAndCornerCount(&m_space->shapeset(element),\n                                 rawGeometry.elementCornerCount(elementIndex));\n      getLocalCoefficients(element, localCoefficients[elementIndex]);\n      it->next();\n    }\n  }\n\n  typedef std::set<ShapesetAndCornerCount> ShapesetAndCornerCountSet;\n  ShapesetAndCornerCountSet uniqueShapesetsAndCornerCounts(\n      basesAndCornerCounts.begin(), basesAndCornerCounts.end());\n\n  // Find out which basis data need to be calculated\n  size_t basisDeps = 0, geomDeps = Fiber::GLOBALS;\n  // Find out which geometrical data need to be calculated, in addition\n  // to those needed by the kernel\n  const Fiber::CollectionOfShapesetTransformations<CoordinateType> &\n  transformations = m_space->basisFunctionValue();\n  assert(nComponents == transformations.resultDimension(0));\n  transformations.addDependencies(basisDeps, geomDeps);\n\n  // Loop over unique combinations of basis and element corner count\n  typedef typename ShapesetAndCornerCountSet::const_iterator\n  BasisAndCornerCountSetConstIt;\n  for (BasisAndCornerCountSetConstIt it =\n           uniqueShapesetsAndCornerCounts.begin();\n       it != uniqueShapesetsAndCornerCounts.end(); ++it) {\n    const ShapesetAndCornerCount &activeBasisAndCornerCount = *it;\n    const Fiber::Shapeset<BasisFunctionType> &activeShapeset =\n        *activeBasisAndCornerCount.first;\n    int activeCornerCount = activeBasisAndCornerCount.second;\n\n    // Set the local coordinates of either all vertices or the barycentre\n    // of the active element type\n    arma::Mat<CoordinateType> local;\n    if (dataType == VtkWriter::CELL_DATA) {\n      local.set_size(gridDim, 1);\n\n      // We could actually use Dune for these assignements\n      if (gridDim == 1 && activeCornerCount == 2) {\n        // linear segment\n        local(0, 0) = 0.5;\n      } else if (gridDim == 2 && activeCornerCount == 3) {\n        // triangle\n        local(0, 0) = 1. / 3.;\n        local(1, 0) = 1. / 3.;\n      } else if (gridDim == 2 && activeCornerCount == 4) {\n        // quadrilateral\n        local(0, 0) = 0.5;\n        local(1, 0) = 0.5;\n      } else\n        throw std::runtime_error(\"GridFunction::evaluateAtVertices(): \"\n                                 \"unsupported element type\");\n    } else { // VERTEX_DATA\n      local.set_size(gridDim, activeCornerCount);\n\n      // We could actually use Dune for these assignements\n      if (gridDim == 1 && activeCornerCount == 2) {\n        // linear segment\n        local(0, 0) = 0.;\n        local(0, 1) = 1.;\n      } else if (gridDim == 2 && activeCornerCount == 3) {\n        // triangle\n        local.fill(0.);\n        local(0, 1) = 1.;\n        local(1, 2) = 1.;\n      } else if (gridDim == 2 && activeCornerCount == 4) {\n        // quadrilateral\n        local.fill(0.);\n        local(0, 1) = 1.;\n        local(1, 2) = 1.;\n        local(0, 3) = 1.;\n        local(1, 3) = 1.;\n      } else\n        throw std::runtime_error(\"GridFunction::evaluateAtVertices(): \"\n                                 \"unsupported element type\");\n    }\n\n    // Get basis data\n    Fiber::BasisData<BasisFunctionType> basisData;\n    activeShapeset.evaluate(basisDeps, local, ALL_DOFS, basisData);\n\n    Fiber::BasisData<ResultType> functionData;\n    if (basisDeps & Fiber::VALUES)\n      functionData.values.set_size(basisData.values.extent(0),\n                                   1, // just one function\n                                   basisData.values.extent(2));\n    if (basisDeps & Fiber::DERIVATIVES)\n      functionData.derivatives.set_size(basisData.derivatives.extent(0),\n                                        basisData.derivatives.extent(1),\n                                        1, // just one function\n                                        basisData.derivatives.extent(3));\n    Fiber::CollectionOf3dArrays<ResultType> functionValues;\n\n    // Loop over elements and process those that use the active shapeset\n    for (size_t e = 0; e < elementCount; ++e) {\n      if (basesAndCornerCounts[e].first != &activeShapeset)\n        continue;\n\n      // Local coefficients of the argument in the current element\n      const std::vector<ResultType> &activeLocalCoefficients =\n          localCoefficients[e];\n\n      // Calculate the function's values and/or derivatives\n      // at the requested points in the current element\n      if (basisDeps & Fiber::VALUES) {\n        std::fill(functionData.values.begin(), functionData.values.end(), 0.);\n        for (size_t point = 0; point < basisData.values.extent(2); ++point)\n          for (size_t dim = 0; dim < basisData.values.extent(0); ++dim)\n            for (size_t fun = 0; fun < basisData.values.extent(1); ++fun)\n              functionData.values(dim, 0, point) +=\n                  basisData.values(dim, fun, point) *\n                  activeLocalCoefficients[fun];\n      }\n      if (basisDeps & Fiber::DERIVATIVES) {\n        std::fill(functionData.derivatives.begin(),\n                  functionData.derivatives.end(), 0.);\n        for (size_t point = 0; point < basisData.derivatives.extent(3); ++point)\n          for (size_t dim = 0; dim < basisData.derivatives.extent(1); ++dim)\n            for (size_t comp = 0; comp < basisData.derivatives.extent(0);\n                 ++comp)\n              for (size_t fun = 0; fun < basisData.derivatives.extent(2); ++fun)\n                functionData.derivatives(comp, dim, 0, point) +=\n                    basisData.derivatives(comp, dim, fun, point) *\n                    activeLocalCoefficients[fun];\n      }\n\n      // Get geometrical data\n      rawGeometry.setupGeometry(e, *geometry);\n      geometry->getData(geomDeps, local, geomData);\n      if (geomDeps & Fiber::DOMAIN_INDEX)\n        geomData.domainIndex = rawGeometry.domainIndex(e);\n\n      transformations.evaluate(functionData, geomData, functionValues);\n      assert(functionValues[0].extent(1) == 1); // one function\n\n      if (dataType == VtkWriter::CELL_DATA) {\n        for (int dim = 0; dim < nComponents; ++dim)\n          values(dim, e) = functionValues[0]( // array index\n              dim,                            // component\n              0,                              // function index\n              0);                             // point index\n        for (int dim = 0; dim < worldDim; ++dim)\n          points(dim, e) = geomData.globals(dim, 0);\n      } else { // VERTEX_DATA\n        // Add the calculated values to the columns of the result array\n        // corresponding to the active element's vertices\n        for (int c = 0; c < activeCornerCount; ++c) {\n          int vertexIndex = rawGeometry.elementCornerIndices()(c, e);\n          for (int dim = 0; dim < nComponents; ++dim)\n            values(dim, vertexIndex) += functionValues[0](dim, 0, c);\n          ++multiplicities[vertexIndex];\n        }\n        for (int c = 0; c < activeCornerCount; ++c) {\n          int vertexIndex = rawGeometry.elementCornerIndices()(c, e);\n          for (int dim = 0; dim < worldDim; ++dim)\n            points(dim, vertexIndex) = geomData.globals(dim, c);\n        }\n      }\n    } // end of loop over elements\n  }   // end of loop over unique combinations of shapeset and corner count\n\n  // Take average of the vertex values obtained in each of the adjacent elements\n  if (dataType == VtkWriter::VERTEX_DATA)\n    for (size_t v = 0; v < vertexCount; ++v)\n      values.col(v) /= multiplicities[v];\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::evaluate(\n    const Entity<0> &element, const arma::Mat<CoordinateType> &local,\n    arma::Mat<ResultType> &values) const {\n  if (local.n_rows != m_space->grid()->dim())\n    throw std::invalid_argument(\"evaluate(): points in 'local' have an \"\n                                \"invalid number of coordinates\");\n\n  const int nComponents = componentCount();\n  // Find out which basis data need to be calculated\n  size_t basisDeps = 0, geomDeps = 0;\n  // Find out which geometrical data need to be calculated,\n  const Fiber::CollectionOfShapesetTransformations<CoordinateType> &\n  transformations = m_space->basisFunctionValue();\n  assert(transformations.transformationCount() == 1);\n  assert(nComponents == transformations.resultDimension(0));\n  transformations.addDependencies(basisDeps, geomDeps);\n\n  // Get basis data\n  const Fiber::Shapeset<BasisFunctionType> &shapeset =\n      m_space->shapeset(element);\n  Fiber::BasisData<BasisFunctionType> basisData;\n  shapeset.evaluate(basisDeps, local, ALL_DOFS, basisData);\n  // Get geometrical data\n  Fiber::GeometricalData<CoordinateType> geomData;\n  element.geometry().getData(geomDeps, local, geomData);\n  values.set_size(nComponents, local.n_cols);\n  // Get shape function values\n  Fiber::CollectionOf3dArrays<BasisFunctionType> functionValues;\n  transformations.evaluate(basisData, geomData, functionValues);\n  assert(functionValues.size() == 1);\n\n  // Get local coefficients\n  std::vector<ResultType> localCoefficients(shapeset.size());\n  getLocalCoefficients(element, localCoefficients);\n  assert(localCoefficients.size() == shapeset.size());\n\n  // Calculate grid function values\n  values.set_size(functionValues[0].extent(0), local.n_cols);\n  values.fill(static_cast<ResultType>(0.));\n  for (size_t p = 0; p < functionValues[0].extent(2); ++p)\n    for (size_t f = 0; f < functionValues[0].extent(1); ++f)\n      for (size_t dim = 0; dim < functionValues[0].extent(0); ++dim)\n        values(dim, p) += functionValues[0](dim, f, p) * localCoefficients[f];\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid GridFunction<BasisFunctionType, ResultType>::exportToGmsh(\n    const char *dataLabel, const char *fileName) const {\n  Bempp::exportToGmsh(*this, dataLabel, fileName);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>\noperator+(const GridFunction<BasisFunctionType, ResultType> &g) {\n  return g;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>\noperator-(const GridFunction<BasisFunctionType, ResultType> &g) {\n  return static_cast<ResultType>(-1.) * g;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType, typename ScalarType>\ntypename boost::enable_if<\n    typename boost::mpl::has_key<\n        boost::mpl::set<float, double, std::complex<float>,\n                        std::complex<double>>,\n        ScalarType>,\n    GridFunction<BasisFunctionType, ResultType>>::type\noperator*(const ScalarType &scalar,\n          const GridFunction<BasisFunctionType, ResultType> &g2) {\n  return g2 * scalar;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType, typename ScalarType>\nGridFunction<BasisFunctionType, ResultType>\noperator/(const GridFunction<BasisFunctionType, ResultType> &g1,\n          const ScalarType &scalar) {\n  if (scalar == static_cast<ScalarType>(0.))\n    throw std::runtime_error(\"GridFunction::operator/(): Divide by zero\");\n  return (static_cast<ScalarType>(1.) / scalar) * g1;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid\nexportToVtk(const GridFunction<BasisFunctionType, ResultType> &gridFunction,\n            VtkWriter::DataType dataType, const char *dataLabel,\n            const char *fileNamesBase, const char *filesPath,\n            VtkWriter::OutputType outputType) {\n  shared_ptr<const Space<BasisFunctionType>> space = gridFunction.space();\n  if (!space)\n    throw std::runtime_error(\"exportToVtk(): gridFunction must not be \"\n                             \"an uninitialized GridFunction object\");\n  arma::Mat<ResultType> data;\n  gridFunction.evaluateAtSpecialPoints(dataType, data);\n\n  std::unique_ptr<GridView> view = space->grid()->leafView();\n  std::unique_ptr<VtkWriter> vtkWriter = view->vtkWriter();\n\n  exportSingleDataSetToVtk(*vtkWriter, data, dataType, dataLabel, fileNamesBase,\n                           filesPath, outputType);\n}\n\nBEMPP_GCC_DIAG_OFF(deprecated - declarations);\n\n// Redundant, in fact -- can be obtained directly from Space\ntemplate <typename BasisFunctionType, typename ResultType>\nconst Fiber::Basis<BasisFunctionType> &\nGridFunction<BasisFunctionType, ResultType>::basis(const Entity<0> &element)\n    const {\n  BOOST_ASSERT_MSG(m_space, \"GridFunction::basis() must not be \"\n                            \"called on an uninitialized GridFunction object\");\n  return m_space->basis(element);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>\noperator+(const GridFunction<BasisFunctionType, ResultType> &g1,\n          const GridFunction<BasisFunctionType, ResultType> &g2) {\n  if (g1.space() != g2.space())\n    throw std::runtime_error(\"GridFunction::operator+(): spaces don't match\");\n  if (g1.wasInitializedFromCoefficients() ||\n      g2.wasInitializedFromCoefficients() || g1.dualSpace() != g2.dualSpace())\n    return GridFunction<BasisFunctionType, ResultType>(\n        g1.context(), // arbitrary choice...\n        g1.space(), g1.coefficients() + g2.coefficients());\n  else {\n    shared_ptr<const Space<BasisFunctionType>> dualSpace = g1.dualSpace();\n    return GridFunction<BasisFunctionType, ResultType>(\n        g1.context(), // arbitrary choice...\n        g1.space(), dualSpace,\n        g1.projections(dualSpace) + g2.projections(dualSpace));\n  }\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nGridFunction<BasisFunctionType, ResultType>\noperator-(const GridFunction<BasisFunctionType, ResultType> &g1,\n          const GridFunction<BasisFunctionType, ResultType> &g2) {\n  if (g1.space() != g2.space())\n    throw std::runtime_error(\"GridFunction::operator-(): spaces don't match\");\n  // For the sake of old-style code (with dualSpace stored in the GridFunction),\n  // we try to provide a sensible dual space to the composite GridFunction.\n  if (g1.wasInitializedFromCoefficients() ||\n      g2.wasInitializedFromCoefficients() || g1.dualSpace() != g2.dualSpace())\n    return GridFunction<BasisFunctionType, ResultType>(\n        g1.context(), // arbitrary choice...\n        g1.space(), g1.coefficients() - g2.coefficients());\n  else {\n    shared_ptr<const Space<BasisFunctionType>> dualSpace = g1.dualSpace();\n    return GridFunction<BasisFunctionType, ResultType>(\n        g1.context(), // arbitrary choice...\n        g1.space(), dualSpace,\n        g1.projections(dualSpace) - g2.projections(dualSpace));\n  }\n}\n\ntemplate <typename BasisFunctionType, typename ResultType, typename ScalarType>\nGridFunction<BasisFunctionType, ResultType>\noperator*(const GridFunction<BasisFunctionType, ResultType> &g1,\n          const ScalarType &scalar) {\n  if (g1.wasInitializedFromCoefficients())\n    return GridFunction<BasisFunctionType, ResultType>(\n        g1.context(), g1.space(),\n        static_cast<ResultType>(scalar) * g1.coefficients());\n  else {\n    shared_ptr<const Space<BasisFunctionType>> dualSpace = g1.dualSpace();\n    return GridFunction<BasisFunctionType, ResultType>(\n        g1.context(), g1.space(), dualSpace,\n        static_cast<ResultType>(scalar) * g1.projections(dualSpace));\n  }\n}\n\nBEMPP_GCC_DIAG_ON(deprecated - declarations);\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(GridFunction);\n\n#define INSTANTIATE_FREE_FUNCTIONS(BASIS, RESULT)                              \\\n  template GridFunction<BASIS, RESULT> operator+(                              \\\n      const GridFunction<BASIS, RESULT> &op);                                  \\\n  template GridFunction<BASIS, RESULT> operator-(                              \\\n      const GridFunction<BASIS, RESULT> &op);                                  \\\n  template GridFunction<BASIS, RESULT> operator+(                              \\\n      const GridFunction<BASIS, RESULT> &op1,                                  \\\n      const GridFunction<BASIS, RESULT> &op2);                                 \\\n  template GridFunction<BASIS, RESULT> operator-(                              \\\n      const GridFunction<BASIS, RESULT> &op1,                                  \\\n      const GridFunction<BASIS, RESULT> &op2);                                 \\\n  template void exportToVtk(const GridFunction<BASIS, RESULT> &gridFunction,   \\\n                            VtkWriter::DataType dataType,                      \\\n                            const char *dataLabel, const char *fileNamesBase,  \\\n                            const char *filesPath,                             \\\n                            VtkWriter::OutputType outputType)\n#define INSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(BASIS, RESULT, SCALAR)          \\\n  template GridFunction<BASIS, RESULT> operator*(                              \\\n      const GridFunction<BASIS, RESULT> &op, const SCALAR &scalar);            \\\n  template GridFunction<BASIS, RESULT> operator*(                              \\\n      const SCALAR &scalar, const GridFunction<BASIS, RESULT> &op);            \\\n  template GridFunction<BASIS, RESULT> operator/(                              \\\n      const GridFunction<BASIS, RESULT> &op, const SCALAR &scalar)\n\n#if defined(ENABLE_SINGLE_PRECISION)\nINSTANTIATE_FREE_FUNCTIONS(float, float);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(float, float, float);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(float, float, double);\n// INSTANTIATE_FREE_FUNCTIONS_FOR_REAL_BASIS(float);\n#endif\n\n#if defined(ENABLE_SINGLE_PRECISION) &&                                        \\\n    (defined(ENABLE_COMPLEX_KERNELS) ||                                        \\\n     defined(ENABLE_COMPLEX_BASIS_FUNCTIONS))\nINSTANTIATE_FREE_FUNCTIONS(float, std::complex<float>);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(float, std::complex<float>, float);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(float, std::complex<float>, double);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(float, std::complex<float>,\n                                       std::complex<float>);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(float, std::complex<float>,\n                                       std::complex<double>);\n#endif\n\n#if defined(ENABLE_SINGLE_PRECISION) && defined(ENABLE_COMPLEX_BASIS_FUNCTIONS)\nINSTANTIATE_FREE_FUNCTIONS(std::complex<float>, std::complex<float>);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(std::complex<float>, std::complex<float>,\n                                       float);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(std::complex<float>, std::complex<float>,\n                                       double);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(std::complex<float>, std::complex<float>,\n                                       std::complex<float>);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(std::complex<float>, std::complex<float>,\n                                       std::complex<double>);\n// INSTANTIATE_FREE_FUNCTIONS_FOR_COMPLEX_BASIS(std::complex<float>);\n#endif\n\n#if defined(ENABLE_DOUBLE_PRECISION)\nINSTANTIATE_FREE_FUNCTIONS(double, double);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(double, double, float);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(double, double, double);\n// INSTANTIATE_FREE_FUNCTIONS_FOR_REAL_BASIS(double);\n#endif\n\n#if defined(ENABLE_DOUBLE_PRECISION) &&                                        \\\n    (defined(ENABLE_COMPLEX_KERNELS) ||                                        \\\n     defined(ENABLE_COMPLEX_BASIS_FUNCTIONS))\nINSTANTIATE_FREE_FUNCTIONS(double, std::complex<double>);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(double, std::complex<double>, float);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(double, std::complex<double>, double);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(double, std::complex<double>,\n                                       std::complex<float>);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(double, std::complex<double>,\n                                       std::complex<double>);\n#endif\n\n#if defined(ENABLE_DOUBLE_PRECISION) && defined(ENABLE_COMPLEX_BASIS_FUNCTIONS)\nINSTANTIATE_FREE_FUNCTIONS(std::complex<double>, std::complex<double>);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(std::complex<double>,\n                                       std::complex<double>, float);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(std::complex<double>,\n                                       std::complex<double>, double);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(std::complex<double>,\n                                       std::complex<double>,\n                                       std::complex<float>);\nINSTANTIATE_FREE_FUNCTIONS_WITH_SCALAR(std::complex<double>,\n                                       std::complex<double>,\n                                       std::complex<double>);\n// INSTANTIATE_FREE_FUNCTIONS_FOR_COMPLEX_BASIS(std::complex<double>);\n#endif\n\n} // namespace Bempp\n", "meta": {"hexsha": "529ea58bf10a87a029767fc72f6c464ef8a26314", "size": 52198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/grid_function.cpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/assembly/grid_function.cpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/assembly/grid_function.cpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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.246064623, "max_line_length": 80, "alphanum_fraction": 0.6970765163, "num_tokens": 12075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1676733103651588}}
{"text": "#include \"FollowLeaderSOB.h\"\n#include \"BookTools.h\"\n#include \"OrderStateTracker.h\"\n#include \"ModelTracker.h\"\n\n#include <boost/dynamic_bitset.hpp>\nusing boost::dynamic_bitset;\n\nconst int DEFAULT_TIMEOUT = 3600*8;\n//const OrderPlacementSuggestion::PlacementReason FollowLeaderSOB::_default_reason = OrderPlacementSuggestion::FOLLOW_LEADER_SOB;\nconst OrderPlacementSuggestion::PlacementReason _defaultReason = OrderPlacementSuggestion::FOLLOW_LEADER_SOB;\n\nconst ECN::ECN ECNS_we_can_follow[] = { ECN::ISLD, ECN::BATS,ECN::ARCA,ECN::NYSE,ECN::BSX}; \n\nconst int N_ECNS_we_can_follow = sizeof(ECNS_we_can_follow) / sizeof(ECN::ECN);\nFollowLeaderSOB::FollowLeaderSOB() :\n  _logPrinter( factory<debug_stream>::get(std::string(\"trader\")) ),\n  _sobRepo( factory<SOBOrderRepo>::get(componentId())),\n  _fvSignal(factory<UCS1>::get(only::one)),\n  _maxQSizeT( factory<MaxQueueSizeTracker>::get(_defaultReason) ),\n  _modelTracker( factory<ModelTracker>::get(only::one))\n  //_defaultReason(OrderPlacementSuggestion::FOLLOW_LEADER_SOB)\n{\n  TAEL_PRINTF(_logPrinter.get(), TAEL_ERROR, \"Init FLW_SOB with defRes=%s\",OrderPlacementSuggestion::PlacementReasonDesc[_defaultReason]);\n}\n\n\n\n\nbool FollowLeaderSOB::queuePositionUnfavorable( const Order* order )\n{\n  \n  double normFV;\n  // Switch between model and heuristic \n  if ((order->ecn()==ECN::ISLD) && (_modelTracker->modelApplies(order->cid())))\n    return _sobRepo->queuePositionUnfavorable(order,&normFV);\n  if (order->ecn()==ECN::NYSE){\n    SingleStockState *ss = _stocksState->getState(order->cid());\n    double mid = ss->mid();\n    // Adjust mid for signal, if present.\n    double alpha = 0.0;\n    if (_fvSignal == NULL || !_fvSignal->getAlpha(order->cid(), alpha)) \n      return false;\n    if (isnan(alpha)) \n      return false;\n    double fv = mid * (1.0 + alpha);\n    if (HFUtils::moreAggressive(order->side(),order->price(),fv)){\n      return true;\n    }\n    return false;\n  }\n  else{\n    int currQSize = getMarketOrders( _dm->subBook(order->ecn()), order->cid(), order->side(), order->price() );\n    if( currQSize == 0 )\n      // this should never happen because we assume we have an outstanding order at this px\n      // Returning false. We should probably cancel for a different reason\n      return false;\n    \n    int maxQSize = _maxQSizeT -> getMaxQueueSize( order->id() );\n    if( maxQSize <= 0 ) {\n      // This should not happen\n      TAEL_PRINTF(_logPrinter.get(), TAEL_ERROR,  \"%-5s ERROR: in FollowLeaderComponentKH::queuePositionUnfavorable, max-Q-size for order Id %d \"\n\t\t\t   \"is 0\", _dm->symbol(order->cid()), order->id() );\n      return false;\n    }\n    \n    // Try to guess the position of our order in the queue\n    int positionInQ;\n    if( !MaxQueueSizeTracker::guessPositionInQueue(_dm.get(), order, positionInQ) )\n      // couldn't guess position\n      return false;\n    \n    int ourPositionFromEnd = currQSize - positionInQ;\n    if( (currQSize<maxQSize) && (((double)ourPositionFromEnd)/currQSize < K_ALLOWED_QUEUE_POSITION) ) {\n      return true;\n    }\n    return false;\n    \n  }\n  // not needed\n  return false;\n}\n\nvoid FollowLeaderSOB::suggestOrderPlacements( int cid, Mkt::Side side, int tradeLogicId, \n\t\t\t\t\t\t    int numShares, double priority,\n\t\t\t\t\t\t    vector<OrderPlacementSuggestion> &suggestions ) {\n  // Empty out suggestions vector in case it's being re-used.\n  suggestions.clear();\n\n  // No capacity allocated - no orders to place.\n  if (numShares <= 0)\n    return;\n\n  // Check that specified priority/aggressiveness is high enough that we guesstimate that this trading algo will work.\n  if( cmp<6>::LT(priority,expectedTC()) ) \n    return;\n\n  // Don't follow on invalid market\n  SingleStockState *ss;\n  ss = _stocksState->getState(cid);\n  if( !ss->haveNormalOrLockedMarket() )\n    return;\n\n  // Check if we got any followable leader orders for specified stock x side.\n  bitset<ECN::ECN_size> ecns;\n  double loPrice;\n  bool afl = anyFollowableLeaders( cid, side, ecns, &loPrice );\n\n  if( afl ) {\n    ECN::ECN e = chooseECN( cid, side, tradeLogicId, numShares, priority, loPrice, ecns );\n    if( e != ECN::UNKN ) {\n      // Calculate order size.\n      int osize = calculateOrderSize(cid, side, numShares, e, loPrice); // truncate big-odd-lots on NYSE to round-lots\n      // Allocate logical order sequence number.  Used to group physical orders that represent smaller\n      //   pieces of large logical order.\n      int csqn = allocateSeqNum();\n      // Break order up into (mostly) round-lot sized chunks to reduce information leakage.\n      vector<int> chunkSizes;\n      HFUtils::chunkOrderShares(osize, 100, chunkSizes);\n      for (unsigned int i =0 ; i < chunkSizes.size(); i++) {\n\tif (chunkSizes[i] <= 0) continue;\n\tOrderPlacementSuggestion ops( cid, e, side, chunkSizes[i], loPrice, DEFAULT_TIMEOUT,\n\t\t\t\t      tradeLogicId, _componentId, csqn, _defaultReason,\n\t\t\t\t      _dm->curtv(), ss->bestPrice(Mkt::BID), ss->bestPrice(Mkt::ASK),\n\t\t\t\t      priority);\n\tsuggestions.push_back(ops);\n      }\n    }\n  }\n  return;\n}\n", "meta": {"hexsha": "20fd70c9ca0fe59c8db1ef1730fe373182aae361", "size": 4992, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/secretcode/FollowLeaderSOB.cc", "max_stars_repo_name": "CodeApprenticeRai/newt", "max_stars_repo_head_hexsha": "0e07a87aa6b8d4b238c1a9fd3fef363133866c57", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T12:23:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T12:23:55.000Z", "max_issues_repo_path": "cpp/secretcode/FollowLeaderSOB.cc", "max_issues_repo_name": "CodeApprenticeRai/newt", "max_issues_repo_head_hexsha": "0e07a87aa6b8d4b238c1a9fd3fef363133866c57", "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/secretcode/FollowLeaderSOB.cc", "max_forks_repo_name": "CodeApprenticeRai/newt", "max_forks_repo_head_hexsha": "0e07a87aa6b8d4b238c1a9fd3fef363133866c57", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-10-17T21:16:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T08:27:01.000Z", "avg_line_length": 37.8181818182, "max_line_length": 145, "alphanum_fraction": 0.6901041667, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.16767330364580316}}
{"text": "#include <btcb/node/common.hpp>\n#include <btcb/node/wallet.hpp>\n#include <btcb/secure/blockstore.hpp>\n\n#include <boost/polymorphic_cast.hpp>\n\nbtcb::summation_visitor::summation_visitor (btcb::transaction const & transaction_a, btcb::block_store & store_a) :\ntransaction (transaction_a),\nstore (store_a)\n{\n}\n\nvoid btcb::summation_visitor::send_block (btcb::send_block const & block_a)\n{\n\tassert (current->type != summation_type::invalid && current != nullptr);\n\tif (current->type == summation_type::amount)\n\t{\n\t\tsum_set (block_a.hashables.balance.number ());\n\t\tcurrent->balance_hash = block_a.hashables.previous;\n\t\tcurrent->amount_hash = 0;\n\t}\n\telse\n\t{\n\t\tsum_add (block_a.hashables.balance.number ());\n\t\tcurrent->balance_hash = 0;\n\t}\n}\n\nvoid btcb::summation_visitor::state_block (btcb::state_block const & block_a)\n{\n\tassert (current->type != summation_type::invalid && current != nullptr);\n\tsum_set (block_a.hashables.balance.number ());\n\tif (current->type == summation_type::amount)\n\t{\n\t\tcurrent->balance_hash = block_a.hashables.previous;\n\t\tcurrent->amount_hash = 0;\n\t}\n\telse\n\t{\n\t\tcurrent->balance_hash = 0;\n\t}\n}\n\nvoid btcb::summation_visitor::receive_block (btcb::receive_block const & block_a)\n{\n\tassert (current->type != summation_type::invalid && current != nullptr);\n\tif (current->type == summation_type::amount)\n\t{\n\t\tcurrent->amount_hash = block_a.hashables.source;\n\t}\n\telse\n\t{\n\t\tbtcb::block_info block_info;\n\t\tif (!store.block_info_get (transaction, block_a.hash (), block_info))\n\t\t{\n\t\t\tsum_add (block_info.balance.number ());\n\t\t\tcurrent->balance_hash = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurrent->amount_hash = block_a.hashables.source;\n\t\t\tcurrent->balance_hash = block_a.hashables.previous;\n\t\t}\n\t}\n}\n\nvoid btcb::summation_visitor::open_block (btcb::open_block const & block_a)\n{\n\tassert (current->type != summation_type::invalid && current != nullptr);\n\tif (current->type == summation_type::amount)\n\t{\n\t\tif (block_a.hashables.source != btcb::genesis_account)\n\t\t{\n\t\t\tcurrent->amount_hash = block_a.hashables.source;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsum_set (btcb::genesis_amount);\n\t\t\tcurrent->amount_hash = 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\tcurrent->amount_hash = block_a.hashables.source;\n\t\tcurrent->balance_hash = 0;\n\t}\n}\n\nvoid btcb::summation_visitor::change_block (btcb::change_block const & block_a)\n{\n\tassert (current->type != summation_type::invalid && current != nullptr);\n\tif (current->type == summation_type::amount)\n\t{\n\t\tsum_set (0);\n\t\tcurrent->amount_hash = 0;\n\t}\n\telse\n\t{\n\t\tbtcb::block_info block_info;\n\t\tif (!store.block_info_get (transaction, block_a.hash (), block_info))\n\t\t{\n\t\t\tsum_add (block_info.balance.number ());\n\t\t\tcurrent->balance_hash = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurrent->balance_hash = block_a.hashables.previous;\n\t\t}\n\t}\n}\n\nbtcb::summation_visitor::frame btcb::summation_visitor::push (btcb::summation_visitor::summation_type type_a, btcb::block_hash const & hash_a)\n{\n\tframes.emplace (type_a, type_a == summation_type::balance ? hash_a : 0, type_a == summation_type::amount ? hash_a : 0);\n\treturn frames.top ();\n}\n\nvoid btcb::summation_visitor::sum_add (btcb::uint128_t addend_a)\n{\n\tcurrent->sum += addend_a;\n\tresult = current->sum;\n}\n\nvoid btcb::summation_visitor::sum_set (btcb::uint128_t value_a)\n{\n\tcurrent->sum = value_a;\n\tresult = current->sum;\n}\n\nbtcb::uint128_t btcb::summation_visitor::compute_internal (btcb::summation_visitor::summation_type type_a, btcb::block_hash const & hash_a)\n{\n\tpush (type_a, hash_a);\n\n\t/*\n\t Invocation loop representing balance and amount computations calling each other.\n\t This is usually better done by recursion or something like boost::coroutine2, but\n\t segmented stacks are not supported on all platforms so we do it manually to avoid\n\t stack overflow (the mutual calls are not tail-recursive so we cannot rely on the\n\t compiler optimizing that into a loop, though a future alternative is to do a\n\t CPS-style implementation to enforce tail calls.)\n\t*/\n\twhile (frames.size () > 0)\n\t{\n\t\tcurrent = &frames.top ();\n\t\tassert (current->type != summation_type::invalid && current != nullptr);\n\n\t\tif (current->type == summation_type::balance)\n\t\t{\n\t\t\tif (current->awaiting_result)\n\t\t\t{\n\t\t\t\tsum_add (current->incoming_result);\n\t\t\t\tcurrent->awaiting_result = false;\n\t\t\t}\n\n\t\t\twhile (!current->awaiting_result && (!current->balance_hash.is_zero () || !current->amount_hash.is_zero ()))\n\t\t\t{\n\t\t\t\tif (!current->amount_hash.is_zero ())\n\t\t\t\t{\n\t\t\t\t\t// Compute amount\n\t\t\t\t\tcurrent->awaiting_result = true;\n\t\t\t\t\tpush (summation_type::amount, current->amount_hash);\n\t\t\t\t\tcurrent->amount_hash = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto block (store.block_get (transaction, current->balance_hash));\n\t\t\t\t\tassert (block != nullptr);\n\t\t\t\t\tblock->visit (*this);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tepilogue ();\n\t\t}\n\t\telse if (current->type == summation_type::amount)\n\t\t{\n\t\t\tif (current->awaiting_result)\n\t\t\t{\n\t\t\t\tsum_set (current->sum < current->incoming_result ? current->incoming_result - current->sum : current->sum - current->incoming_result);\n\t\t\t\tcurrent->awaiting_result = false;\n\t\t\t}\n\n\t\t\twhile (!current->awaiting_result && (!current->amount_hash.is_zero () || !current->balance_hash.is_zero ()))\n\t\t\t{\n\t\t\t\tif (!current->amount_hash.is_zero ())\n\t\t\t\t{\n\t\t\t\t\tauto block (store.block_get (transaction, current->amount_hash));\n\t\t\t\t\tif (block != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tblock->visit (*this);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (current->amount_hash == btcb::genesis_account)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsum_set (std::numeric_limits<btcb::uint128_t>::max ());\n\t\t\t\t\t\t\tcurrent->amount_hash = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tassert (false);\n\t\t\t\t\t\t\tsum_set (0);\n\t\t\t\t\t\t\tcurrent->amount_hash = 0;\n\t\t\t\t\t\t}\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\t// Compute balance\n\t\t\t\t\tcurrent->awaiting_result = true;\n\t\t\t\t\tpush (summation_type::balance, current->balance_hash);\n\t\t\t\t\tcurrent->balance_hash = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tepilogue ();\n\t\t}\n\t}\n\n\treturn result;\n}\n\nvoid btcb::summation_visitor::epilogue ()\n{\n\tif (!current->awaiting_result)\n\t{\n\t\tframes.pop ();\n\t\tif (frames.size () > 0)\n\t\t{\n\t\t\tframes.top ().incoming_result = current->sum;\n\t\t}\n\t}\n}\n\nbtcb::uint128_t btcb::summation_visitor::compute_amount (btcb::block_hash const & block_hash)\n{\n\treturn compute_internal (summation_type::amount, block_hash);\n}\n\nbtcb::uint128_t btcb::summation_visitor::compute_balance (btcb::block_hash const & block_hash)\n{\n\treturn compute_internal (summation_type::balance, block_hash);\n}\n\nbtcb::representative_visitor::representative_visitor (btcb::transaction const & transaction_a, btcb::block_store & store_a) :\ntransaction (transaction_a),\nstore (store_a),\nresult (0)\n{\n}\n\nvoid btcb::representative_visitor::compute (btcb::block_hash const & hash_a)\n{\n\tcurrent = hash_a;\n\twhile (result.is_zero ())\n\t{\n\t\tauto block (store.block_get (transaction, current));\n\t\tassert (block != nullptr);\n\t\tblock->visit (*this);\n\t}\n}\n\nvoid btcb::representative_visitor::send_block (btcb::send_block const & block_a)\n{\n\tcurrent = block_a.previous ();\n}\n\nvoid btcb::representative_visitor::receive_block (btcb::receive_block const & block_a)\n{\n\tcurrent = block_a.previous ();\n}\n\nvoid btcb::representative_visitor::open_block (btcb::open_block const & block_a)\n{\n\tresult = block_a.hash ();\n}\n\nvoid btcb::representative_visitor::change_block (btcb::change_block const & block_a)\n{\n\tresult = block_a.hash ();\n}\n\nvoid btcb::representative_visitor::state_block (btcb::state_block const & block_a)\n{\n\tresult = block_a.hash ();\n}\n", "meta": {"hexsha": "bb96606afda4d54b1d38411ebdcfdf95c51eda3b", "size": 7326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "btcb/secure/blockstore.cpp", "max_stars_repo_name": "melnaquib/btcb", "max_stars_repo_head_hexsha": "f55c9867113d403118c3028d5ba11a0debcd7609", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-01T13:33:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T04:42:38.000Z", "max_issues_repo_path": "btcb/secure/blockstore.cpp", "max_issues_repo_name": "melnaquib/btcb", "max_issues_repo_head_hexsha": "f55c9867113d403118c3028d5ba11a0debcd7609", "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": "btcb/secure/blockstore.cpp", "max_forks_repo_name": "melnaquib/btcb", "max_forks_repo_head_hexsha": "f55c9867113d403118c3028d5ba11a0debcd7609", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-04-03T14:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-22T17:14:28.000Z", "avg_line_length": 25.6153846154, "max_line_length": 142, "alphanum_fraction": 0.6935571936, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.16767330212552403}}
{"text": "#include \"segmatch/recognizers/partitioned_geometric_consistency_recognizer.hpp\"\n\n#include <algorithm>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <glog/logging.h>\n#include <laser_slam/benchmarker.hpp>\n\n#include \"segmatch/common.hpp\"\n#include \"segmatch/recognizers/graph_utilities.hpp\"\n#include \"segmatch/recognizers/matches_partitioner.hpp\"\n\nnamespace segmatch {\n\nPartitionedGeometricConsistencyRecognizer::PartitionedGeometricConsistencyRecognizer(\n    const GeometricConsistencyParams& params, float max_model_radius) noexcept\n  : GraphBasedGeometricConsistencyRecognizer(params), partition_size_(max_model_radius * 2.0f) {\n}\n\ninline size_t PartitionedGeometricConsistencyRecognizer::findAndAddInPartitionConsistencies(\n    const PairwiseMatches& predicted_matches, const std::vector<size_t>& partition_indices,\n    ConsistencyGraph& consistency_graph) const {\n  size_t num_consistency_tests = 0u;\n  for (size_t i2 = 0u; i2 < partition_indices.size(); ++i2) {\n    size_t i = partition_indices[i2];\n    const Eigen::Vector3f& scene_point_i = predicted_matches[i].centroids_.first.getVector3fMap();\n    const Eigen::Vector3f& model_point_i = predicted_matches[i].centroids_.second.getVector3fMap();\n    for (size_t j2 = i2 + 1u; j2 < partition_indices.size(); ++j2) {\n      size_t j = partition_indices[j2];\n      const Eigen::Vector3f& scene_point_j =\n          predicted_matches[j].centroids_.first.getVector3fMap();\n      const Eigen::Vector3f& model_point_j =\n          predicted_matches[j].centroids_.second.getVector3fMap();\n\n      // Compute the difference between the distances and add edge to the consistency graph if the\n      // matches are consistent.\n      ++num_consistency_tests;\n      float dist_scene = (scene_point_i - scene_point_j).norm();\n      float dist_model = (model_point_i - model_point_j).norm();\n      float distance = fabs(dist_scene - dist_model);\n      if (distance <= static_cast<float>(params_.resolution))\n        boost::add_edge(i, j, consistency_graph);\n    }\n  }\n  return num_consistency_tests;\n}\n\ninline size_t PartitionedGeometricConsistencyRecognizer::findAndAddCrossPartitionConsistencies(\n    const PairwiseMatches& predicted_matches, const std::vector<size_t>& partition_indices_1,\n    const std::vector<size_t>& partition_indices_2, ConsistencyGraph& consistency_graph) const {\n  size_t num_consistency_tests = 0u;\n  for (size_t i2 = 0u; i2 < partition_indices_1.size(); ++i2) {\n    size_t i = partition_indices_1[i2];\n    const Eigen::Vector3f& scene_point_i = predicted_matches[i].centroids_.first.getVector3fMap();\n    const Eigen::Vector3f& model_point_i = predicted_matches[i].centroids_.second.getVector3fMap();\n    for (size_t j2 = 0u; j2 < partition_indices_2.size(); ++j2) {\n      size_t j = partition_indices_2[j2];\n      const Eigen::Vector3f& scene_point_j =\n          predicted_matches[j].centroids_.first.getVector3fMap();\n      const Eigen::Vector3f& model_point_j =\n          predicted_matches[j].centroids_.second.getVector3fMap();\n\n      // Compute the difference between the distances and add edge to the consistency graph if the\n      // matches are consistent.\n      ++num_consistency_tests;\n      float dist_scene = (scene_point_i - scene_point_j).norm();\n      float dist_model = (model_point_i - model_point_j).norm();\n      float distance = fabs(dist_scene - dist_model);\n      if (distance <= static_cast<float>(params_.resolution))\n        boost::add_edge(i, j, consistency_graph);\n    }\n  }\n  return num_consistency_tests;\n}\n\nPartitionedGeometricConsistencyRecognizer::ConsistencyGraph\nPartitionedGeometricConsistencyRecognizer::buildConsistencyGraph(\n    const PairwiseMatches& predicted_matches) {\n  BENCHMARK_BLOCK(\"SM.Worker.Recognition.BuildConsistencyGraph\");\n\n  // Partition the matches in a grid by the position of the scene points. The size of the\n  // partitions is greater or equal the size of the model. This way we can safely assume that, if\n  // the model is actually present in the scene, all matches will be contained in a 2x2 group of\n  // adjacent partitions.\n  BENCHMARK_START(\"SM.Worker.Recognition.BuildConsistencyGraph.Partitioning\");\n  MatchesGridPartitioning<PartitionData> partitioning =\n      MatchesPartitioner::computeGridPartitioning<PartitionData>(predicted_matches,\n                                                                 partition_size_);\n  BENCHMARK_RECORD_VALUE(\"SM.Worker.Recognition.BuildConsistencyGraph.NumPartitions\",\n                         partitioning.getHeight() * partitioning.getWidth());\n  BENCHMARK_STOP(\"SM.Worker.Recognition.BuildConsistencyGraph.Partitioning\");\n  ConsistencyGraph consistency_graph(predicted_matches.size());\n  size_t num_consistency_tests = 0u;\n\n  // Find all possible consistency within a partition and within neighbor partitions.\n  for (size_t i = 0; i < partitioning.getHeight(); ++i) {\n    for (size_t j = 0; j < partitioning.getWidth(); ++j) {\n      // Find in-partition consistencies and add them to the consistency graph.\n      findAndAddInPartitionConsistencies(\n          predicted_matches, partitioning(i, j).match_indices, consistency_graph);\n\n      // Determine which neighbor partitions exist.\n      bool has_right_neighbors = j < partitioning.getWidth() - 1u;\n      bool has_bottom_neighbors = i < partitioning.getHeight() - 1u;\n      bool has_left_neighbors = j > 0u;\n\n      // Find possible cross-partition consistencies and add them to the consistency graph.\n      if (has_right_neighbors) {\n        num_consistency_tests += findAndAddCrossPartitionConsistencies(\n            predicted_matches, partitioning(i, j).match_indices,\n            partitioning(i, j + 1u).match_indices, consistency_graph);\n      }\n      if (has_right_neighbors && has_bottom_neighbors) {\n        num_consistency_tests += findAndAddCrossPartitionConsistencies(\n            predicted_matches, partitioning(i, j).match_indices,\n            partitioning(i + 1u, j + 1u).match_indices, consistency_graph);\n      }\n      if (has_bottom_neighbors) {\n        num_consistency_tests += findAndAddCrossPartitionConsistencies(\n            predicted_matches, partitioning(i, j).match_indices,\n            partitioning(i + 1u, j).match_indices, consistency_graph);\n      }\n      if (has_bottom_neighbors && has_left_neighbors) {\n        num_consistency_tests += findAndAddCrossPartitionConsistencies(\n            predicted_matches, partitioning(i, j).match_indices,\n            partitioning(i + 1u, j - 1u).match_indices, consistency_graph);\n      }\n    }\n  }\n  BENCHMARK_RECORD_VALUE(\"SM.Worker.Recognition.BuildConsistencyGraph.NumConsistencyTests\",\n                         num_consistency_tests);\n\n  return consistency_graph;\n}\n\n} // namespace segmatch\n", "meta": {"hexsha": "dea5ba9d31ce8e12aa7706b7a9aedf22774cf954", "size": 6715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "segmatch/src/recognizers/partitioned_geometric_consistency_recognizer.cpp", "max_stars_repo_name": "Oofs/segmap", "max_stars_repo_head_hexsha": "98f1fddc15b863c781b78f59c65487be5e0dc497", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 771.0, "max_stars_repo_stars_event_min_datetime": "2018-04-21T06:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:49:32.000Z", "max_issues_repo_path": "segmatch/src/recognizers/partitioned_geometric_consistency_recognizer.cpp", "max_issues_repo_name": "Oofs/segmap", "max_issues_repo_head_hexsha": "98f1fddc15b863c781b78f59c65487be5e0dc497", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 111.0, "max_issues_repo_issues_event_min_datetime": "2018-04-22T10:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T02:16:12.000Z", "max_forks_repo_path": "segmatch/src/recognizers/partitioned_geometric_consistency_recognizer.cpp", "max_forks_repo_name": "Oofs/segmap", "max_forks_repo_head_hexsha": "98f1fddc15b863c781b78f59c65487be5e0dc497", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 287.0, "max_forks_repo_forks_event_min_datetime": "2018-04-21T06:43:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T17:45:05.000Z", "avg_line_length": 48.6594202899, "max_line_length": 99, "alphanum_fraction": 0.7322412509, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.32766828768970435, "lm_q1q2_score": 0.16767329876584633}}
{"text": "#ifndef JHMI_LIVER_MACROCELL_TREE_HPP_NRC_20150803\n#define JHMI_LIVER_MACROCELL_TREE_HPP_NRC_20150803\n\n#include \"liver/cell_list.hpp\"\n#include \"liver/physical_vessel_tree.hpp\"\n#include \"shape/voxelized_shape.hpp\"\n#include \"utility/protobuf_zip_ostream.hpp\"\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/rolling_mean.hpp>\n#include <boost/filesystem.hpp>\n#include <chrono>\n#include <vector>\n\nnamespace jhmi {\n\n  class macrocell_tree {\n    std::mt19937 gen_;\n    voxelized_shape const& liver_;\n    physical_vessel_tree vessels_;\n    cell_list cells_;\n\n    int update_macrocells(float grow_prob, float die_prob) {\n      std::uniform_real_distribution<> dist;\n      auto rand = std::bind(dist, std::ref(gen_));\n\n      //Determine which cells die\n      std::vector<cell_id> dying;\n      RANGES_FOR(auto& cell, cells_.list()) {\n        if (rand() < die_prob && vessels_.remove(cell.parent_vessel))\n          dying.push_back(cell.id);\n      }\n      //For each mc (in random order) attempt to fill empty spaces;\n      std::vector<m3> clone_cells;\n      RANGES_FOR(auto& cell, cells_.list()) {\n        if (rand() < grow_prob)\n          clone_cells.push_back(cell.center);\n      }\n      int num_died = dying.size();\n      RANGES_FOR(auto id, dying) {\n        cells_.erase(id);\n      }\n      ranges::shuffle(clone_cells, gen_);\n      int num_created = 0;\n      RANGES_FOR(auto center, clone_cells) {\n        auto new_id = cells_.add_cell_near(center);\n        if (new_id.valid()) {\n          if (vessels_.connect_cell(cells_.at(new_id), gen_).valid()) {\n            ++num_created;\n          }\n          else\n            cells_.erase(new_id);\n        }\n      }\n#define PER_SUBCYCLE\n#ifdef PER_SUBCYCLE\n      fmt::print(\"total: {:8} | attempted: {:6} | created: {:6} | died: {:6} | net: {:6}\",\n        vessels_.size(), clone_cells.size(), num_created, num_died, num_created - num_died);\n#endif\n      return num_created - num_died;\n    }\n    void fill_with_pcts(float grow_prob, float die_prob) {\n#if 0\n      using namespace boost::accumulators;\n      //auto acc = accumulator_set<int, stats<tag::rolling_mean>>{tag::rolling_window::window_size = 20};\n      do {\n        acc(update_macrocells(grow_prob, die_prob));\n# ifdef PER_SUBCYCLE\n        fmt::print(\" | avg: {}\\n\", rolling_mean(acc));\n# endif\n      } while (std::abs(rolling_mean(acc)) > 1);\n#else\n      while (update_macrocells(grow_prob, die_prob) > 0)\n        fmt::print(\"\\n\");\n      fmt::print(\"\\n\");\n#endif\n    }\n    void normalize_all() {\n      vessels_.normalize_all();\n      //If we're solving for flow, we need to update the cell values afterward\n    }\n\n  public:\n    static m initial_size() { return 5_mm / .3679; }\n    macrocell_tree(build_tree_tag, boost::filesystem::path const& vesselfile,\n                   voxelized_shape const& liver,\n                   std::random_device::result_type seed,\n                   cubic_meters_per_second proper_ha_flow,\n                   double gamma, Pa cell_pressure, bool initial_fill = true)\n      : gen_{seed}, liver_{liver},\n        vessels_{build_tree, vesselfile, extents(liver_), gamma, cell_pressure, proper_ha_flow / 1868346., gen_},\n        cells_{build_tree, gen_, liver_, initial_size(), proper_ha_flow, cell_pressure} {\n      //We now add macrocells to each terminal vessel in the liver model.\n      auto terminal_vessels = vessels_.terminal_vessels() | ranges::to_vector;\n      for (auto&& v : terminal_vessels) {\n        auto new_id = cells_.add_cell_near(v.start(), boost::optional<m3>{v.end()});\n        if (!new_id.valid() || !vessels_.connect_cell_initial(cells_.at(new_id), v.id()).valid())\n          throw std::runtime_error(\"Error adding an initial terminal cell\");\n      }\n      //Finally, fill the liver with macrocells and connect them to this\n      // initial map.\n      if (initial_fill)\n        fill_with_pcts(1.f, 0.f);\n      normalize_all();\n      if (!validate()) {\n        throw std::runtime_error(fmt::format(\"Invalid tree detected!\\n\"));\n      }\n    }\n    macrocell_tree(load_tree_tag, boost::filesystem::path const& treefile,\n          voxelized_shape const& liver = voxelized_shape{})\n      : gen_{0}, liver_{liver}, vessels_{load_tree, treefile, gen_},\n        cells_{load_tree, treefile, liver, gen_} {\n      //Takes a really long time, not strictly necessary\n      //validate();\n    }\n\n    auto const& macrocells() const { return cells_; }\n    physical_vessel_tree const& vessel_tree() const { return vessels_; }\n\n    void write(boost::filesystem::path const& filename) const {\n      namespace io = google::protobuf::io;\n      jhmi_message::VesselTree vt;\n      vessels_.store(vt);\n      cells_.store(vt);\n      protobuf_zip_ostream out_stream{filename};\n      if (!vt.SerializeToZeroCopyStream(out_stream.get()))\n        throw std::runtime_error(\"Failed to write macrocell tree.\");\n    }\n    auto const& liver_shape() const { return liver_; }\n\n    void reduce_cell_size(double scale, bool final) {\n      assert((scale > 0 && scale < 1) || final);\n      cells_.reduce_cell_size(scale, final);\n    }\n    void build(int cycles, m final_radius,\n               boost::filesystem::path const& p = boost::filesystem::path{},\n               std::string const& filestem = \"\") {\n      float m1 = 1.f, m2 = 9.8f, n1 = .3f, n2 = 9.f;\n      auto t = (final_radius - macrocell_tree::initial_size()) / double(cycles);\n      RANGES_FOR(int cycle, ranges::view::ints(0, cycles)) {\n        auto grow_prob = m1 * expf(-cycle / m2);\n        auto die_prob = n1 * expf(-cycle / n2);\n        bool fit_to_lobules = cycle == cycles - 1 && final_radius < 2_mm;\n        reduce_cell_size(\n          1. + t / (macrocell_tree::initial_size() + double(cycle) * t), fit_to_lobules);\n        auto start_num_cells = ranges::size(macrocells().list());\n        auto start = std::chrono::high_resolution_clock::now();\n\n        fill_with_pcts(grow_prob, die_prob);\n        vessels_.normalize_all();\n        auto stop = std::chrono::high_resolution_clock::now();\n        auto end_num_cells = ranges::size(macrocells().list());\n        if (!validate()) {\n          fmt::print(\"Invalid tree detected!\\n\");\n        }\n#if 1\n        fmt::print(\"Cycle {:2} | Mitosis: {:10} | Necrosis: {:10} | Change: {:6} | Time: {} s\\n\",\n          cycle + 1, grow_prob, die_prob, int(end_num_cells) - int(start_num_cells),\n          std::chrono::duration<float>(stop - start).count());\n#endif\n        if (!filestem.empty() && cycle < cycles - 1) {\n          write(p / fmt::format(filestem, cycle));\n        }\n      }\n\n      auto start = std::chrono::high_resolution_clock::now();\n      //How could this be necessary?\n      vessels_.normalize_all();\n      auto stop = std::chrono::high_resolution_clock::now();\n      fmt::print(\"Time to normalize: {} s\\n\", std::chrono::duration<float>(stop - start).count());\n    }\n\n    bool validate() const {\n      bool no_errors = vessels_.validate(ranges::empty(cells_.list())) && cells_.validate();\n      //Verify each cell matches the exit pressure and flow of the parent_vessel\n      RANGES_FOR(auto& cell, cells_.list()) {\n        auto& v = vessels_.at(cell.parent_vessel);\n//        no_errors &= check_close(v.flow(), cell.flow, 1e-8, v.id(),\n//          \"vessel flow\", \"cell flow\");\n        no_errors &= check_close(v.exit_pressure(), cell.pressure, 1e-4, v.id(),\n          \"vessel exit pressure\", \"cell pressure\");\n      }\n      RANGES_FOR(auto& vessel, vessels_.vessels()) {\n        try {\n          if (vessel.cell().valid())\n            cells_.at(vessel.cell());\n        }\n        catch(std::exception& e) {\n          fmt::print(\"Vessel references non-existent cell\\n\");\n          no_errors = false;\n        }\n      }\n      if (!no_errors)\n        fmt::print(\"Errors found in tree\\n\");\n      return no_errors;\n    }\n  };\n\n  bool operator==(macrocell_tree const& lhs, macrocell_tree const& rhs) {\n    return lhs.macrocells() == rhs.macrocells() &&\n           lhs.vessel_tree() == rhs.vessel_tree();\n  }\n}//jhmi\n#endif\n", "meta": {"hexsha": "e1f33c052bf8c12c9f98b63e8472a8c305436611", "size": 8030, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "liver/macrocell_tree.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/macrocell_tree.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/macrocell_tree.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": 39.1707317073, "max_line_length": 113, "alphanum_fraction": 0.6261519303, "num_tokens": 2039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.16765917844627284}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_BIPC_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_BIPC_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// This file was modified by Oracle on 2017.\n// Modifications copyright (c) 2017, 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// 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// 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/geometry/util/math.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct bipc {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace bipc\n    {\n\n            static const double EPS = 1e-10;\n            static const double EPS10 = 1e-10;\n            static const double ONEEPS = 1.000000001;\n            static const int NITER = 10;\n            static const double lamB = -.34894976726250681539;\n            static const double n = .63055844881274687180;\n            static const double F = 1.89724742567461030582;\n            static const double Azab = .81650043674686363166;\n            static const double Azba = 1.82261843856185925133;\n            static const double T = 1.27246578267089012270;\n            static const double rhoc = 1.20709121521568721927;\n            static const double cAzc = .69691523038678375519;\n            static const double sAzc = .71715351331143607555;\n            static const double C45 = .70710678118654752469;\n            static const double S45 = .70710678118654752410;\n            static const double C20 = .93969262078590838411;\n            static const double S20 = -.34202014332566873287;\n            static const double R110 = 1.91986217719376253360;\n            static const double R104 = 1.81514242207410275904;\n\n            struct par_bipc\n            {\n                int    noskew;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_bipc_spheroid : public base_t_fi<base_bipc_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_bipc m_proj_parm;\n\n                inline base_bipc_spheroid(const Parameters& par)\n                    : base_t_fi<base_bipc_spheroid<CalculationType, Parameters>,\n                     CalculationType, 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                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n                    static const CalculationType ONEPI = detail::ONEPI<CalculationType>();\n\n                    CalculationType cphi, sphi, tphi, t, al, Az, z, Av, cdlam, sdlam, r;\n                    int tag;\n\n                    cphi = cos(lp_lat);\n                    sphi = sin(lp_lat);\n                    cdlam = cos(sdlam = lamB - lp_lon);\n                    sdlam = sin(sdlam);\n                    if (fabs(fabs(lp_lat) - HALFPI) < EPS10) {\n                        Az = lp_lat < 0. ? ONEPI : 0.;\n                        tphi = HUGE_VAL;\n                    } else {\n                        tphi = sphi / cphi;\n                        Az = atan2(sdlam , C45 * (tphi - cdlam));\n                    }\n                    if( (tag = (Az > Azba)) ) {\n                        cdlam = cos(sdlam = lp_lon + R110);\n                        sdlam = sin(sdlam);\n                        z = S20 * sphi + C20 * cphi * cdlam;\n                        if (fabs(z) > 1.) {\n                            if (fabs(z) > ONEEPS)\n                                BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                            else\n                                z = z < 0. ? -1. : 1.;\n                        } else\n                            z = acos(z);\n                        if (tphi != HUGE_VAL)\n                            Az = atan2(sdlam, (C20 * tphi - S20 * cdlam));\n                        Av = Azab;\n                        xy_y = rhoc;\n                    } else {\n                        z = S45 * (sphi + cphi * cdlam);\n                        if (fabs(z) > 1.) {\n                            if (fabs(z) > ONEEPS)\n                                BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                            else\n                                z = z < 0. ? -1. : 1.;\n                        } else\n                            z = acos(z);\n                        Av = Azba;\n                        xy_y = -rhoc;\n                    }\n                    if (z < 0.) BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                    r = F * (t = pow(tan(.5 * z), n));\n                    if ((al = .5 * (R104 - z)) < 0.)\n                        BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                    al = (t + pow(al, n)) / T;\n                    if (fabs(al) > 1.) {\n                        if (fabs(al) > ONEEPS)\n                            BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                        else\n                            al = al < 0. ? -1. : 1.;\n                    } else\n                        al = acos(al);\n                    if (fabs(t = n * (Av - Az)) < al)\n                        r /= cos(al + (tag ? t : -t));\n                    xy_x = r * sin(t);\n                    xy_y += (tag ? -r : r) * cos(t);\n                    if (this->m_proj_parm.noskew) {\n                        t = xy_x;\n                        xy_x = -xy_x * cAzc - xy_y * sAzc;\n                        xy_y = -xy_y * cAzc + t * sAzc;\n                    }\n                }\n\n                // INVERSE(s_inverse)  spheroid\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                    CalculationType t, r, rp, rl, al, z, fAz, Az, s, c, Av;\n                    int neg, i;\n\n                    if (this->m_proj_parm.noskew) {\n                        t = xy_x;\n                        xy_x = -xy_x * cAzc + xy_y * sAzc;\n                        xy_y = -xy_y * cAzc - t * sAzc;\n                    }\n                    if( (neg = (xy_x < 0.)) ) {\n                        xy_y = rhoc - xy_y;\n                        s = S20;\n                        c = C20;\n                        Av = Azab;\n                    } else {\n                        xy_y += rhoc;\n                        s = S45;\n                        c = C45;\n                        Av = Azba;\n                    }\n                    rl = rp = r = boost::math::hypot(xy_x, xy_y);\n                    fAz = fabs(Az = atan2(xy_x, xy_y));\n                    for (i = NITER; i ; --i) {\n                        z = 2. * atan(pow(r / F,1 / n));\n                        al = acos((pow(tan(.5 * z), n) +\n                           pow(tan(.5 * (R104 - z)), n)) / T);\n                        if (fAz < al)\n                            r = rp * cos(al + (neg ? Az : -Az));\n                        if (fabs(rl - r) < EPS)\n                            break;\n                        rl = r;\n                    }\n                    if (! i)\n                        BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                    Az = Av - Az / n;\n                    lp_lat = asin(s * cos(z) + c * sin(z) * cos(Az));\n                    lp_lon = atan2(sin(Az), c / tan(z) - s * cos(Az));\n                    if (neg)\n                        lp_lon -= R110;\n                    else\n                        lp_lon = lamB - lp_lon;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"bipc_spheroid\";\n                }\n\n            };\n\n            // Bipolar conic of western hemisphere\n            template <typename Parameters>\n            inline void setup_bipc(Parameters& par, par_bipc& proj_parm)\n            {\n                proj_parm.noskew = pj_param(par.params, \"bns\").i;\n                par.es = 0.;\n            }\n\n    }} // namespace detail::bipc\n    #endif // doxygen\n\n    /*!\n        \\brief Bipolar conic of western hemisphere 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         - Conic\n         - Spheroid\n        \\par Projection parameters\n         - ns (boolean)\n        \\par Example\n        \\image html ex_bipc.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct bipc_spheroid : public detail::bipc::base_bipc_spheroid<CalculationType, Parameters>\n    {\n        inline bipc_spheroid(const Parameters& par) : detail::bipc::base_bipc_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::bipc::setup_bipc(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::bipc, bipc_spheroid, bipc_spheroid)\n\n        // Factory entry(s)\n        template <typename CalculationType, typename Parameters>\n        class bipc_entry : public detail::factory_entry<CalculationType, Parameters>\n        {\n            public :\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<bipc_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void bipc_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"bipc\", new bipc_entry<CalculationType, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_BIPC_HPP\n\n", "meta": {"hexsha": "6f014d0e66ecb0118a59280fb0ba6751bf93e2dc", "size": 12316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/bipc.hpp", "max_stars_repo_name": "ramcn/gemmx", "max_stars_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2018-08-13T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:37:20.000Z", "max_issues_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/bipc.hpp", "max_issues_repo_name": "ramcn/gemmx", "max_issues_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/bipc.hpp", "max_forks_repo_name": "ramcn/gemmx", "max_forks_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T12:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:39.000Z", "avg_line_length": 41.3288590604, "max_line_length": 131, "alphanum_fraction": 0.5181877233, "num_tokens": 2803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.16758371933355545}}
{"text": "/*\n* TS Elements\n* Copyright 2015-2018 M. Newhouse\n* Released under the MIT license.\n*/\n\n\n#include \"world.hpp\"\n#include \"car.hpp\"\n#include \"world_limits.hpp\"\n#include \"control_point_manager_detail.hpp\"\n#include \"entity_id_conversion.hpp\"\n#include \"world_event_interface.hpp\"\n\n#include \"resources/terrain_library.hpp\"\n#include \"resources/car_definition.hpp\"\n#include \"resources/terrain_definition.hpp\"\n#include \"resources/collision_mask_detail.hpp\"\n\n#include \"utility/random.hpp\"\n#include \"utility/line_plotter.hpp\"\n#include \"utility/debug_log.hpp\"\n#include \"utility/math_utilities.hpp\"\n\n#include <boost/function_output_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/optional.hpp>\n\n#include <chipmunk/chipmunk.h>\n\n#include <vector>\n#include <iostream>\n#include <cmath>\n\nnamespace ts\n{\n  namespace world\n  {\n    static void update_body_position(cpBody* body, cpFloat dt)\n    {\n      cpBodyUpdatePosition(body, dt);\n\n      auto pos = cpBodyGetPosition(body);\n      auto space = cpBodyGetSpace(body);\n      \n      auto user_data = static_cast<const PhysicsSpace::UserData*>(cpSpaceGetUserData(space));      \n\n      pos.x = cpfclamp(pos.x, 0.0, user_data->size.x);\n      pos.y = cpfclamp(pos.y, 0.0, user_data->size.y);\n      cpBodySetPosition(body, pos);\n    }\n\n    PhysicsSpace::PhysicsSpace(Vector2d size)\n      : physics_space_(static_cast<void*>(cpSpaceNew())),\n      user_data_(std::make_unique<UserData>())\n    {     \n      auto space = static_cast<cpSpace*>(physics_space_.get());\n      cpSpaceSetUserData(space, user_data_.get());      \n\n      user_data_->size = size;\n    }\n\n    void PhysicsSpace::update(std::uint32_t frame_duration)\n    {\n      auto fd = frame_duration * 0.001;\n\n      cpSpaceStep(static_cast<cpSpace*>(physics_space_.get()), fd);\n    }\n\n    void PhysicsSpace::add_entity(Entity* entity)\n    {\n      auto body = static_cast<cpBody*>(entity->physics_body_.get());\n\n      cpSpaceAddBody(static_cast<cpSpace*>(physics_space_.get()), body);\n\n      cpBodySetPositionUpdateFunc(body, update_body_position);\n    }\n\n    void PhysicsSpace::Deleter::operator()(void* space) const\n    {\n      cpSpaceFree(static_cast<cpSpace*>(space));\n    }\n\n    World::World(resources::Track track, TerrainMap terrain_map)\n      : track_(std::move(track)),\n      terrain_map_(std::move(terrain_map)),\n      control_point_manager_(track_.control_points().data(), track_.control_points().size()),\n      physics_space_(vector2_cast<double>(track_.size()))\n    {\n      entity_map_.resize(limits::max_car_count);\n      cars_.reserve(limits::max_car_count);\n    }\n\n    Car* World::create_car(const CarDefinition& car_definition, std::uint8_t car_id, std::uint16_t start_pos)\n    {\n      auto entity_id = car_id_to_entity_id(car_id);\n\n      const auto& start_points = track_.start_points();\n      if (cars_.size() >= limits::max_car_count || entity_map_[entity_id] != nullptr || start_pos >= start_points.size())\n        return nullptr;\n\n      auto position = make_vector2(0.0, 0.0);\n      auto rotation = degrees(0.0);\n      auto z_position = 0.0;\n\n      auto point = start_points[start_pos];\n      position = vector2_cast<double>(point.position);\n      rotation = degrees(static_cast<double>(point.rotation));\n      z_position = static_cast<double>(point.level);\n\n      auto car = std::make_unique<Car>(car_definition, entity_id);\n      auto car_ptr = car.get();\n\n      cars_.push_back(car_ptr);\n      entity_map_[entity_id] = std::move(car);\n\n      physics_space_.add_entity(car_ptr);\n\n      car_ptr->set_position(position);\n      car_ptr->set_rotation(rotation);\n      car_ptr->set_z_position(z_position);\n\n      return car_ptr;\n    }\n\n    void World::update(std::uint32_t frame_duration, world::EventInterface& event_interface)\n    {\n      double fd = frame_duration * 0.001;\n\n      auto max_corner = vector2_cast<std::int32_t>(world_size()) - make_vector2(1, 1);\n\n      const auto& terrain_lib = track_.terrain_library();\n\n      entity_states_.clear();      \n      for (auto* car : cars_)\n      {\n        entity_states_.push_back({ car, car->position() });\n\n        car->update(*this, fd);\n      }\n\n      physics_space_.update(frame_duration);\n\n      for (auto& es : entity_states_)\n      {\n        auto cp_hit_callback = [&](const ControlPoint& point, double time_point)\n        {\n          auto frame_offset = static_cast<std::uint32_t>(frame_duration * time_point);\n\n          event_interface.on_control_point_hit(es.entity, point, frame_offset);\n        };\n\n        control_point_manager_.test_control_point_intersections(es.old_position, es.entity->position(), cp_hit_callback);\n      }\n    }\n\n    Car* World::find_car(std::uint8_t car_id)\n    {\n      auto entity_id = car_id_to_entity_id(car_id);\n      return static_cast<Car*>(entity_map_[entity_id].get());\n    }\n\n    const Car* World::find_car(std::uint8_t car_id) const\n    {\n      auto entity_id = car_id_to_entity_id(car_id);\n      return static_cast<const Car*>(entity_map_[entity_id].get());\n    }\n\n    World::car_range World::cars() const\n    {\n      return car_range(cars_.data(), cars_.data() + cars_.size());\n    }\n\n    Vector2<double> World::world_size() const\n    {\n      return vector2_cast<double>(track().size());\n    }\n\n    const resources::Track& World::track() const noexcept\n    {\n      return track_;\n    }\n\n    resources::TerrainDefinition World::terrain_at(Vector2i position) const\n    {      \n      return terrain_at(position, 0);\n    }\n\n    resources::TerrainDefinition World::terrain_at(Vector2i position, std::int32_t level) const\n    {\n      return terrain_map_.terrain_at(position, level, track_.terrain_library());\n    }\n\n    resources::TerrainDefinition World::terrain_at(Vector2d position) const\n    {\n      return terrain_at(position, 0);\n    }\n\n    resources::TerrainDefinition World::terrain_at(Vector2d position, std::int32_t level) const\n    {\n      return terrain_at(vector2_cast<std::int32_t>(position), level);\n    }\n  }\n}", "meta": {"hexsha": "7291c494c0ee47c1ba392f6dce265320d4f60137", "size": 5948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/world/world.cpp", "max_stars_repo_name": "mnewhouse/tselements", "max_stars_repo_head_hexsha": "bd1c6724018e862156948a680bb1bc70dd28bef6", "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/world/world.cpp", "max_issues_repo_name": "mnewhouse/tselements", "max_issues_repo_head_hexsha": "bd1c6724018e862156948a680bb1bc70dd28bef6", "max_issues_repo_licenses": ["MIT"], "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/world/world.cpp", "max_forks_repo_name": "mnewhouse/tselements", "max_forks_repo_head_hexsha": "bd1c6724018e862156948a680bb1bc70dd28bef6", "max_forks_repo_licenses": ["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.1568627451, "max_line_length": 121, "alphanum_fraction": 0.6770342972, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16745906275464995}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017, 2018.\r\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\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// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 5.0.0\r\n\r\n// Original copyright notice:\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 MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE 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\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_NSPER_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_NSPER_HPP\r\n\r\n#include <boost/config.hpp>\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#include <boost/math/special_functions/hypot.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail { namespace nsper\r\n    {\r\n\r\n            static const double epsilon10 = 1.e-10;\r\n            enum mode_type {\r\n                n_pole = 0,\r\n                s_pole = 1,\r\n                equit  = 2,\r\n                obliq  = 3\r\n            };\r\n\r\n            template <typename T>\r\n            struct par_nsper\r\n            {\r\n                T   height;\r\n                T   sinph0;\r\n                T   cosph0;\r\n                T   p;\r\n                T   rp;\r\n                T   pn1;\r\n                T   pfact;\r\n                T   h;\r\n                T   cg;\r\n                T   sg;\r\n                T   sw;\r\n                T   cw;\r\n                mode_type mode;\r\n                int tilt;\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_nsper_spheroid\r\n                : public base_t_fi<base_nsper_spheroid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_nsper<T> m_proj_parm;\r\n\r\n                inline base_nsper_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_nsper_spheroid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    T  coslam, cosphi, sinphi;\r\n\r\n                    sinphi = sin(lp_lat);\r\n                    cosphi = cos(lp_lat);\r\n                    coslam = cos(lp_lon);\r\n                    switch (this->m_proj_parm.mode) {\r\n                    case obliq:\r\n                        xy_y = this->m_proj_parm.sinph0 * sinphi + this->m_proj_parm.cosph0 * cosphi * coslam;\r\n                        break;\r\n                    case equit:\r\n                        xy_y = cosphi * coslam;\r\n                        break;\r\n                    case s_pole:\r\n                        xy_y = - sinphi;\r\n                        break;\r\n                    case n_pole:\r\n                        xy_y = sinphi;\r\n                        break;\r\n                    }\r\n                    if (xy_y < this->m_proj_parm.rp) {\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                    }\r\n                    xy_y = this->m_proj_parm.pn1 / (this->m_proj_parm.p - xy_y);\r\n                    xy_x = xy_y * cosphi * sin(lp_lon);\r\n                    switch (this->m_proj_parm.mode) {\r\n                    case obliq:\r\n                        xy_y *= (this->m_proj_parm.cosph0 * sinphi -\r\n                           this->m_proj_parm.sinph0 * cosphi * coslam);\r\n                        break;\r\n                    case equit:\r\n                        xy_y *= sinphi;\r\n                        break;\r\n                    case n_pole:\r\n                        coslam = - coslam;\r\n                        BOOST_FALLTHROUGH;\r\n                    case s_pole:\r\n                        xy_y *= cosphi * coslam;\r\n                        break;\r\n                    }\r\n                    if (this->m_proj_parm.tilt) {\r\n                        T yt, ba;\r\n\r\n                        yt = xy_y * this->m_proj_parm.cg + xy_x * this->m_proj_parm.sg;\r\n                        ba = 1. / (yt * this->m_proj_parm.sw * this->m_proj_parm.h + this->m_proj_parm.cw);\r\n                        xy_x = (xy_x * this->m_proj_parm.cg - xy_y * this->m_proj_parm.sg) * this->m_proj_parm.cw * ba;\r\n                        xy_y = yt * ba;\r\n                    }\r\n                }\r\n\r\n                // INVERSE(s_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T xy_x, T xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    T  rh, cosz, sinz;\r\n\r\n                    if (this->m_proj_parm.tilt) {\r\n                        T bm, bq, yt;\r\n\r\n                        yt = 1./(this->m_proj_parm.pn1 - xy_y * this->m_proj_parm.sw);\r\n                        bm = this->m_proj_parm.pn1 * xy_x * yt;\r\n                        bq = this->m_proj_parm.pn1 * xy_y * this->m_proj_parm.cw * yt;\r\n                        xy_x = bm * this->m_proj_parm.cg + bq * this->m_proj_parm.sg;\r\n                        xy_y = bq * this->m_proj_parm.cg - bm * this->m_proj_parm.sg;\r\n                    }\r\n                    rh = boost::math::hypot(xy_x, xy_y);\r\n                    if ((sinz = 1. - rh * rh * this->m_proj_parm.pfact) < 0.) {\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                    }\r\n                    sinz = (this->m_proj_parm.p - sqrt(sinz)) / (this->m_proj_parm.pn1 / rh + rh / this->m_proj_parm.pn1);\r\n                    cosz = sqrt(1. - sinz * sinz);\r\n                    if (fabs(rh) <= epsilon10) {\r\n                        lp_lon = 0.;\r\n                        lp_lat = this->m_par.phi0;\r\n                    } else {\r\n                        switch (this->m_proj_parm.mode) {\r\n                        case obliq:\r\n                            lp_lat = asin(cosz * this->m_proj_parm.sinph0 + xy_y * sinz * this->m_proj_parm.cosph0 / rh);\r\n                            xy_y = (cosz - this->m_proj_parm.sinph0 * sin(lp_lat)) * rh;\r\n                            xy_x *= sinz * this->m_proj_parm.cosph0;\r\n                            break;\r\n                        case equit:\r\n                            lp_lat = asin(xy_y * sinz / rh);\r\n                            xy_y = cosz * rh;\r\n                            xy_x *= sinz;\r\n                            break;\r\n                        case n_pole:\r\n                            lp_lat = asin(cosz);\r\n                            xy_y = -xy_y;\r\n                            break;\r\n                        case s_pole:\r\n                            lp_lat = - asin(cosz);\r\n                            break;\r\n                        }\r\n                        lp_lon = atan2(xy_x, xy_y);\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"nsper_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup(Params const& params, Parameters& par, par_nsper<T>& proj_parm) \r\n            {\r\n                proj_parm.height = pj_get_param_f<T, srs::spar::h>(params, \"h\", srs::dpar::h);\r\n                if (proj_parm.height <= 0.)\r\n                    BOOST_THROW_EXCEPTION( projection_exception(error_h_less_than_zero) );\r\n\r\n                if (fabs(fabs(par.phi0) - geometry::math::half_pi<T>()) < epsilon10)\r\n                    proj_parm.mode = par.phi0 < 0. ? s_pole : n_pole;\r\n                else if (fabs(par.phi0) < epsilon10)\r\n                    proj_parm.mode = equit;\r\n                else {\r\n                    proj_parm.mode = obliq;\r\n                    proj_parm.sinph0 = sin(par.phi0);\r\n                    proj_parm.cosph0 = cos(par.phi0);\r\n                }\r\n                proj_parm.pn1 = proj_parm.height / par.a; /* normalize by radius */\r\n                proj_parm.p = 1. + proj_parm.pn1;\r\n                proj_parm.rp = 1. / proj_parm.p;\r\n                proj_parm.h = 1. / proj_parm.pn1;\r\n                proj_parm.pfact = (proj_parm.p + 1.) * proj_parm.h;\r\n                par.es = 0.;\r\n            }\r\n\r\n\r\n            // Near-sided perspective\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_nsper(Params const& params, Parameters& par, par_nsper<T>& proj_parm)\r\n            {\r\n                proj_parm.tilt = 0;\r\n\r\n                setup(params, par, proj_parm);\r\n            }\r\n\r\n            // Tilted perspective\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_tpers(Params const& params, Parameters& par, par_nsper<T>& proj_parm)\r\n            {\r\n                T const omega = pj_get_param_r<T, srs::spar::tilt>(params, \"tilt\", srs::dpar::tilt);\r\n                T const gamma = pj_get_param_r<T, srs::spar::azi>(params, \"azi\", srs::dpar::azi);\r\n                proj_parm.tilt = 1;\r\n                proj_parm.cg = cos(gamma); proj_parm.sg = sin(gamma);\r\n                proj_parm.cw = cos(omega); proj_parm.sw = sin(omega);\r\n\r\n                setup(params, par, proj_parm);\r\n            }\r\n\r\n    }} // namespace detail::nsper\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Near-sided perspective projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Azimuthal\r\n         - Spheroid\r\n        \\par Projection parameters\r\n         - h: Height\r\n        \\par Example\r\n        \\image html ex_nsper.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct nsper_spheroid : public detail::nsper::base_nsper_spheroid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline nsper_spheroid(Params const& params, Parameters const& par)\r\n            : detail::nsper::base_nsper_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::nsper::setup_nsper(params, this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Tilted perspective projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Azimuthal\r\n         - Spheroid\r\n        \\par Projection parameters\r\n         - tilt: Tilt, or Omega (real)\r\n         - azi: Azimuth (or Gamma) (real)\r\n         - h: Height\r\n        \\par Example\r\n        \\image html ex_tpers.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct tpers_spheroid : public detail::nsper::base_nsper_spheroid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline tpers_spheroid(Params const& params, Parameters const& par)\r\n            : detail::nsper::base_nsper_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::nsper::setup_tpers(params, this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail\r\n    {\r\n\r\n        // Static projection\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_nsper, nsper_spheroid, nsper_spheroid)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_tpers, tpers_spheroid, tpers_spheroid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(nsper_entry, nsper_spheroid)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(tpers_entry, tpers_spheroid)\r\n\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(nsper_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(nsper, nsper_entry)\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(tpers, tpers_entry)\r\n        }\r\n\r\n    } // namespace detail\r\n    #endif // doxygen\r\n\r\n} // namespace projections\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_NSPER_HPP\r\n\r\n", "meta": {"hexsha": "73c2562bd6f305f1fec7b97ecd2029b3ae448237", "size": 13939, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dep/win/include/boost/geometry/srs/projections/proj/nsper.hpp", "max_stars_repo_name": "Netis/packet-agent", "max_stars_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "dep/win/include/boost/geometry/srs/projections/proj/nsper.hpp", "max_issues_repo_name": "Netis/packet-agent", "max_issues_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "dep/win/include/boost/geometry/srs/projections/proj/nsper.hpp", "max_forks_repo_name": "Netis/packet-agent", "max_forks_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 41.1179941003, "max_line_length": 123, "alphanum_fraction": 0.5224191118, "num_tokens": 3076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.16738412632490443}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2010 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <vw/gui/TileGenerator.h>\n#include <vw/Image/ViewImageResource.h>\n#include <vw/Image/ImageResourceView.h>\n#include <vw/Image/Statistics.h>\n#include <vw/Image/MaskViews.h>\n\n#include <QUrl>\n#include <QBuffer>\n#include <QImage>\n#include <QHttp>\n#include <QByteArray>\n\nusing namespace vw;\nusing namespace vw::gui;\nusing namespace vw::platefile;\n\n#include <boost/filesystem.hpp>\nnamespace fs = boost::filesystem;\n\n// --------------------------------------------------------------------------------\n//                                Utility Functions\n// --------------------------------------------------------------------------------\n\nBBox2i vw::gui::tile_to_bbox(Vector2i tile_size, int col, int row, int level, int max_level) {\n  if (col < 0 || row < 0 || col >= pow(2, max_level) || row >= pow(2, max_level) ) {\n    return BBox2i();\n  } else {\n    BBox2i result(tile_size[0]*col, tile_size[1]*row, tile_size[0], tile_size[1]);\n    return result * pow(2,max_level - level);\n  }\n}\n\nstd::list<TileLocator> vw::gui::bbox_to_tiles(Vector2i tile_size, BBox2i bbox, int level, int max_level, int transaction_id, bool exact_transaction_id_match) {\n  std::list<TileLocator> results;\n\n  // Compute the bounding box at the current level.\n  BBox2i level_bbox = bbox / pow(2,max_level - level);\n\n  // Grow that bounding box to align with tile boundaries\n  BBox2i aligned_level_bbox = level_bbox;\n  aligned_level_bbox.min().x() = ( (level_bbox.min().x() / tile_size[0]) * tile_size[0] );\n  aligned_level_bbox.min().y() = ( (level_bbox.min().y() / tile_size[1]) * tile_size[1] );\n  aligned_level_bbox.max().x() = ( int(ceilf( float(level_bbox.max().x()) / tile_size[0] ))\n                                   * tile_size[0] );\n  aligned_level_bbox.max().y() = ( int(ceilf( float(level_bbox.max().y()) / tile_size[1] ))\n                                   * tile_size[1] );\n\n  int tile_y = aligned_level_bbox.min().y() / tile_size[1];\n  int dest_row = 0;\n  while ( tile_y < aligned_level_bbox.max().y() / tile_size[1] ) {\n\n    int tile_x = aligned_level_bbox.min().x() / tile_size[0];\n    int dest_col = 0;\n    while ( tile_x < aligned_level_bbox.max().x() / tile_size[0] ) {\n      BBox2i tile_bbox(dest_col, dest_row, tile_size[0], tile_size[1]);\n      TileLocator loc;\n      loc.col = tile_x;\n      loc.row = tile_y;\n      loc.level = level;\n      loc.transaction_id = transaction_id;\n      loc.exact_transaction_id_match = exact_transaction_id_match;\n      results.push_back(loc);\n\n      ++tile_x;\n      dest_col += tile_size[0];\n    }\n    ++tile_y;\n    dest_row += tile_size[1];\n  }\n  return results;\n}\n\n\n\n// --------------------------------------------------------------------------\n//                              TILE GENERATOR\n// --------------------------------------------------------------------------\n\nboost::shared_ptr<TileGenerator> TileGenerator::create(std::string filename) {\n\n  // Strip off any trailing slashes to make sure we aren't\n  // accidentally misparsing a platefile name.\n  if (filename[filename.size()-1] == '/')\n    filename.erase(filename.size()-1, 1);\n\n  try {\n\n    // If ends in .plate, then assume platefile.\n    if ( fs::extension(filename) == \".plate\") {\n\n      return boost::shared_ptr<TileGenerator>( new PlatefileTileGenerator(filename) );\n\n    // If begins with http://, then assume web tiles.\n    } else if ( filename.find(\"http://\") == 0) {\n\n      return boost::shared_ptr<TileGenerator>( new WebTileGenerator(filename,17));\n\n    // If testpattern, then we use the testpattern tile generator\n    } else if (filename == \"testpattern\") {\n\n      vw_out() << \"\\t--> Starting vwv in testpattern mode.\\n\";\n      return boost::shared_ptr<TileGenerator>( new TestPatternTileGenerator(256) );\n\n    // Otherwise, assume an image.\n    } else {\n      return boost::shared_ptr<TileGenerator>( new ImageTileGenerator(filename) );\n    }\n  } catch (vw::IOErr &e) {\n    std::cout << \"An error occurred opening \\\"\" << filename << \"\\\":\\n\\t\" << e.what() << \"\\n\";\n    exit(0);\n  }\n}\n\n\n// --------------------------------------------------------------------------\n//                         TEST PATTERN TILE GENERATOR\n// --------------------------------------------------------------------------\n\nboost::shared_ptr<ViewImageResource> TestPatternTileGenerator::generate_tile(TileLocator const& /*tile_info*/) {\n  ImageView<PixelRGBA<uint8> > tile(m_tile_size, m_tile_size);\n  for (int j = 0; j < m_tile_size; ++j){\n    for (int i = 0; i < m_tile_size; ++i){\n      if (abs(i - j) < 10 || abs(i - (m_tile_size - j)) < 10)\n        tile(i,j) = PixelRGBA<uint8>(255,0,0,255);\n      else\n        tile(i,j) = PixelRGBA<uint8>(0,0,0,255);\n    }\n  }\n  boost::shared_ptr<ViewImageResource> result( new ViewImageResource(tile) );\n  return result;\n}\n\nVector2 TestPatternTileGenerator::minmax() { return Vector2(0.0, 1.0); }\n\nPixelRGBA<float32> TestPatternTileGenerator::sample(int /*x*/, int /*y*/, int /*level*/, int /*transaction_id*/) {\n  PixelRGBA<float32> result;\n  return result;\n}\n\nint TestPatternTileGenerator::cols() const { return 2048; }\nint TestPatternTileGenerator::rows() const { return 2048; }\nPixelFormatEnum TestPatternTileGenerator::pixel_format() const { return VW_PIXEL_RGBA; }\nChannelTypeEnum TestPatternTileGenerator::channel_type() const { return VW_CHANNEL_UINT8; }\nVector2i TestPatternTileGenerator::tile_size() const {\n  return Vector2i(m_tile_size, m_tile_size);\n}\nint32 TestPatternTileGenerator::num_levels() const {\n  return 4;\n}\n\n// --------------------------------------------------------------------------\n//                            WEB TILE GENERATOR\n// --------------------------------------------------------------------------\n\nHttpDownloadThread::HttpDownloadThread() {\n  m_http = new QHttp(NULL);\n  connect(m_http, SIGNAL(requestStarted(int)),this, SLOT(request_started(int)));  \n  connect(m_http, SIGNAL(requestFinished(int, bool)),this, SLOT(request_finished(int, bool)));  \n  connect(m_http, SIGNAL(responseHeaderReceived(QHttpResponseHeader)),this, SLOT(response_header_received(QHttpResponseHeader)));  \n  connect(m_http, SIGNAL(stateChanged(int)),this, SLOT(state_changed(int)));  \n}\n\nvoid HttpDownloadThread::run() {\n  QThread::exec();\n}\n\nHttpDownloadThread::~HttpDownloadThread() {\n  if (m_http)\n    delete m_http;\n}\n\nint HttpDownloadThread::get(std::string url_string, int transaction_id,\n                            bool exact_transaction_id_match) {\n  Mutex::Lock lock(m_mutex);\n  QUrl url(url_string.c_str());\n\n  /// XXX: Hard coding file_type as PNG for now. FIXME!!!!\n  std::string file_type = \"png\";\n\n  int request_id;\n  if (m_http) {\n    m_http->setHost(url.host(),url.port());\n\n    // Set up request buffer\n    RequestBuffer buf;\n    buf.file_type = file_type;\n    buf.url = url_string;\n\n    std::ostringstream path_with_opts;\n    path_with_opts << url.path().toStdString() << \"?nocache=1&transaction_id=\" << transaction_id;\n    if (exact_transaction_id_match)\n      path_with_opts << \"&exact=1\";\n    vw_out() << \"\\t --> Fetching http://\" << url.host().toStdString() << path_with_opts.str() << \"\\n\";\n    QString final_path_str(path_with_opts.str().c_str());\n    request_id = m_http->get (final_path_str, buf.buffer.get());\n    m_requests[request_id] = buf;\n    m_current_request = request_id;\n  }\n  return request_id;\n}\n\nbool HttpDownloadThread::result_available(int request_id) {\n  Mutex::Lock lock(m_mutex);\n  return m_requests[request_id].finished;\n}\n\nvw::ImageView<vw::PixelRGBA<float> > HttpDownloadThread::pop_result(int request_id) {\n  Mutex::Lock lock(m_mutex);\n  vw::ImageView<vw::PixelRGBA<float> > result = m_requests[request_id].result;\n  m_requests.erase(request_id);\n  return result;\n}\n\nvoid HttpDownloadThread::request_started(int /*request_id*/) {\n  //  std::cout << \"Request \" << request_id << \" started\\n\";\n}\n\nvoid HttpDownloadThread::response_header_received( const QHttpResponseHeader & resp ) {\n  Mutex::Lock lock(m_mutex);\n  //  std::cout << \"Header received...\\n\";\n\n  std::map<int, RequestBuffer>::iterator request_iter = m_requests.find(m_current_request);\n  if (request_iter != m_requests.end()) {\n    RequestBuffer &buf = request_iter->second;\n    buf.status = resp.statusCode();\n    if (resp.contentType() == \"image/png\")\n      buf.file_type = \"png\";\n    else if (resp.contentType() == \"image/jpeg\" || resp.contentType() == \"image/jpg\")\n      buf.file_type = \"jpg\";\n    else if (resp.contentType() == \"image/tiff\" || resp.contentType() == \"image/tif\")\n      buf.file_type = \"tif\";\n    else if (resp.contentType() == \"text/html\") {\n      /* do nothing... this is likely a 404 */\n    } else\n      vw_out() << \"WARNING: unrecognized content-type: \" << resp.contentType().toStdString() << \"\\n\";\n  }\n}\n\nvoid HttpDownloadThread::state_changed(int /*state*/) {\n  Mutex::Lock lock(m_mutex);\n  //  std::cout << \"HTTP State changed: \" << state << \"\\n\";\n}\n\nvoid HttpDownloadThread::request_finished(int request_id, bool error) {\n  Mutex::Lock lock(m_mutex);\n  std::map<int, RequestBuffer>::iterator request_iter = m_requests.find(request_id);\n  if (request_iter != m_requests.end()) {\n    RequestBuffer &buf = request_iter->second;\n\n    if (error || (buf.status != 404 && buf.status != 200)) {\n      std::cout << \"WARNING: Request \" << request_id << \" failed for URL: \" \n                << buf.url << \"\\n\\t\" << m_http->errorString().toStdString() << \"\\n\";\n      ImageView<PixelRGBA<float> > vw_image(1,1);\n      vw_image(0,0) = PixelRGBA<float>(1.0,0.0,0.0,1.0);\n      buf.result = vw_image;\n    } else if (buf.status == 404) {\n      ImageView<PixelRGBA<float> > vw_image(1,1);\n      vw_image(0,0) = PixelRGBA<float>(0.0,0.1,0.0,1.0);\n      buf.result = vw_image;\n    }\n\n    // Handle the error case.\n    if (error || buf.buffer->buffer().length() == 0 || buf.status != 200) {\n      buf.finished = true;\n      return;\n    }\n\n    // Save the data to a temporary file, and then read the image file\n    // using the Vision Workbench FileIO subsystem.\n    std::string temp_filename = platefile::TemporaryTileFile::unique_tempfile_name(buf.file_type);\n    std::ofstream of(temp_filename.c_str());\n    if ( !(of.good()) )\n      vw_throw(IOErr() << \"Could not open temporary tile file for writing: \" << temp_filename);\n    of.write(buf.buffer->buffer().data(), buf.buffer->buffer().length());\n    of.close();\n    TemporaryTileFile temp_tile_file(temp_filename);\n\n    // Now read the image out of the tempfile and save the decoded\n    // pixels as the result.\n    try {\n      boost::shared_ptr<DiskImageResource> rsrc(DiskImageResource::open(temp_filename));\n      if (rsrc->channel_type() == VW_CHANNEL_UINT8) {\n        ImageView<PixelRGBA<uint8> > vw_image = temp_tile_file.read<PixelRGBA<uint8> >();\n        buf.result = channel_cast_rescale<float>(vw_image);\n      } else if (rsrc->channel_type() == VW_CHANNEL_UINT16) {\n        ImageView<PixelRGBA<int16> > vw_image = temp_tile_file.read<PixelRGBA<int16> >();\n        buf.result = channel_cast_rescale<float>(vw_image);\n      } else {\n        vw_out() << \"WARNING: Image contains unsupported channel type: \"\n                 << rsrc->channel_type() << \"\\n\";\n      }\n      buf.finished = true;\n    } catch (IOErr &e) {\n      vw_out(WarningMessage) << \"Could not read data from temporary file: \"\n                             << temp_filename << \"\\n\";\n      buf.finished = true;\n    }\n  }\n}\n\n\nWebTileGenerator::WebTileGenerator(std::string url, int levels) :\n  m_tile_size(256), m_levels(levels), m_url(url) {\n  m_download_thread.start();\n}\n\nboost::shared_ptr<ViewImageResource> WebTileGenerator::generate_tile(TileLocator const& tile_info) {\n\n  std::ostringstream full_url;\n  full_url << m_url << \"/\" << tile_info.level\n           << \"/\" << tile_info.col\n           << \"/\" << tile_info.row << \".png\";\n  int request_id = m_download_thread.get(full_url.str(),\n                                         tile_info.transaction_id,\n                                         tile_info.exact_transaction_id_match);\n  while(!m_download_thread.result_available(request_id));\n\n  vw::ImageView<vw::PixelRGBA<float> > result = m_download_thread.pop_result(request_id);\n  return boost::shared_ptr<ViewImageResource>( new ViewImageResource( result ) );\n}\n\nVector2 WebTileGenerator::minmax() { return Vector2(0.0, 1.0); }\n\nPixelRGBA<float32> WebTileGenerator::sample(int /*x*/, int /*y*/, int /*level*/, int /*transaction_id*/) {\n  PixelRGBA<float32> result;\n  return result;\n}\n\nint WebTileGenerator::cols() const { return m_tile_size * pow(2,m_levels-1); }\nint WebTileGenerator::rows() const { return m_tile_size * pow(2,m_levels-1); }\nPixelFormatEnum WebTileGenerator::pixel_format() const { return VW_PIXEL_RGBA; }\nChannelTypeEnum WebTileGenerator::channel_type() const { return VW_CHANNEL_UINT8; }\nVector2i WebTileGenerator::tile_size() const {\n  return Vector2i(m_tile_size, m_tile_size);\n}\nint32 WebTileGenerator::num_levels() const {\n  return m_levels;\n}\n\n// --------------------------------------------------------------------------\n//                         PLATE FILE TILE GENERATOR\n// --------------------------------------------------------------------------\n\nPlatefileTileGenerator::PlatefileTileGenerator(std::string platefile_name) :\n  m_platefile(new vw::platefile::PlateFile(platefile_name)) {\n  m_num_levels = m_platefile->num_levels();\n  std::cout << \"\\t--> Loading platefile \\\"\" << platefile_name << \"\\\" with \"\n            << m_num_levels << \" levels.\\n\";\n}\n\n\n#define VW_DELEGATE_BY_PIXEL_TYPE(func, arg1, arg2)                                  \\\n  switch (this->pixel_format()) {                                                    \\\n  case VW_PIXEL_GRAY:                                                                \\\n  case VW_PIXEL_GRAYA:                                                               \\\n      if (this->channel_type() == VW_CHANNEL_UINT8) {                                \\\n        return func<PixelGrayA<uint8> >(arg1, arg2);                                 \\\n      } else if (this->channel_type() == VW_CHANNEL_INT16) {                         \\\n        return func<PixelGrayA<int16> >(arg1, arg2);                                 \\\n      } else if (this->channel_type() == VW_CHANNEL_FLOAT32) {                       \\\n        return func<PixelGrayA<float> >(arg1, arg2);                                 \\\n      } else {                                                                       \\\n        std::cout << \"This platefile has a channel type that is not yet support by vwv.\\n\"; \\\n        std::cout << \"Exiting...\\n\\n\";                                               \\\n        exit(0);                                                                     \\\n      }                                                                              \\\n      break;                                                                         \\\n    case VW_PIXEL_RGB:                                                               \\\n    case VW_PIXEL_RGBA:                                                              \\\n      if (this->channel_type() == VW_CHANNEL_UINT8) {                                \\\n        return func<PixelRGBA<uint8> >(arg1, arg2);                                  \\\n      } else if (this->channel_type() == VW_CHANNEL_UINT16) {                        \\\n        return func<PixelRGBA<uint16> >(arg1, arg2);                                 \\\n      } else {                                                                       \\\n        std::cout << \"This platefile has a channel type that is not yet support by vwv.\\n\"; \\\n        std::cout << \"Exiting...\\n\\n\";                                               \\\n        exit(0);                                                                     \\\n      }                                                                              \\\n      break;                                                                         \\\n    default:                                                                         \\\n      std::cout << \"This platefile has a pixel format that is not yet support by vwv.\\n\"; \\\n      std::cout << \"Exiting...\\n\\n\";                                                 \\\n      exit(0);                                                                       \\\n    }                                                                                \\\n\ntemplate<class PixelT>\nVector2 minmax_impl(TileLocator const& tile_info,\n                    boost::shared_ptr<vw::platefile::PlateFile> platefile) {\n  ImageView<PixelT> tile;\n  platefile->read(tile, tile_info.col, tile_info.row, tile_info.level, tile_info.transaction_id);\n  typename PixelChannelType<PixelT>::type min, max;\n  min_max_channel_values(alpha_to_mask(tile), min, max);\n  Vector2 result(min, max);\n  std::cout << \"Here is the original answer: \" << result << \"\\n\";\n  result /= ChannelRange<typename PixelChannelType<PixelT>::type>::max();\n  std::cout << \"NEW MIN AND MAX: \" << result << \"\\n\";\n  return result;\n}\n\nVector2 PlatefileTileGenerator::minmax() {\n  try {\n    TileLocator loc;\n    loc.col = 0;\n    loc.row = 0;\n    loc.level = 0;\n    VW_DELEGATE_BY_PIXEL_TYPE(minmax_impl, loc, m_platefile)\n  } catch (platefile::TileNotFoundErr &e) {\n    return Vector2(0,1);\n  }\n}\n\n// template<class PixelT>\n// std::string sample_impl(TileLocator const& tile_info,\n//                         Vector2 const& px_loc) {\n//   ImageView<PixelT> tile;\n//   platefile->read(tile, tile_info.col, tile_info.row, tile_info.level, tile_info.transaction_id);\n//   VW_ASSERT(px_loc[0] >= 0 && px_loc[0] < tile.cols() &&\n//             px_loc[1] >= 0 && px_loc[1] < tile.rows(),\n//             ArgumentErr() << \"sample_impl() invalid pixel location\");\n//   return tile(px_loc[0], px_loc[1]);\n// }\n\nPixelRGBA<float32> PlatefileTileGenerator::sample(int /*x*/, int /*y*/, int /*level*/, int /*transaction_id*/) {\n  // TileLocator tile_loc;\n  // tile_loc.col = floor(x/this->tile_size[0]);\n  // tile_loc.row = floor(y/this->tile_size[1]);\n  // tile_loc.level = this->num_levels();\n  // px_loc = Vector2(x % this->tile_size[0],\n  //                  y % this->tile_size[1]);\n\n  try {\n    return PixelRGBA<float32>(1.0, 0.0, 0.0, 1.0);\n    //    VW_DELEGATE_BY_PIXEL_TYPE(sample_tile_impl, tile_loc, px_loc)\n  } catch (platefile::TileNotFoundErr &e) {\n    ImageView<PixelGrayA<uint8> > blank_tile(1,1);\n    return PixelRGBA<float32>();\n  }\n}\n\ntemplate <class PixelT>\nboost::shared_ptr<ViewImageResource> generate_tile_impl(TileLocator const& tile_info,\n                                      boost::shared_ptr<vw::platefile::PlateFile> platefile) {\n  ImageView<PixelT> tile(1,1);\n  try {\n\n    platefile->read(tile, tile_info.col, tile_info.row,\n                    tile_info.level, tile_info.transaction_id,\n                    tile_info.exact_transaction_id_match);\n\n  } catch (platefile::TileNotFoundErr &e) {\n\n    ImageView<PixelRGBA<uint8> > blank_tile(1,1);\n    blank_tile(0,0) = PixelRGBA<uint8>(0, 20, 0, 255);\n    return boost::shared_ptr<ViewImageResource>( new ViewImageResource(blank_tile) );\n\n  } catch (vw::IOErr &e) {\n\n    std::cout << \"WARNING: AMQP ERROR -- \" << e.what() << \"\\n\";\n\n  }\n  return boost::shared_ptr<ViewImageResource>( new ViewImageResource(tile) );\n}\n\nboost::shared_ptr<ViewImageResource> PlatefileTileGenerator::generate_tile(TileLocator const& tile_info) {\n\n  vw_out(DebugMessage, \"gui\") << \"Request to generate platefile tile \"\n                              << tile_info.col << \" \" << tile_info.row\n                              << \" @ \" << tile_info.level << \"\\n\";\n\n  VW_DELEGATE_BY_PIXEL_TYPE(generate_tile_impl, tile_info, m_platefile)\n\n  // If we get to here, then there was no support for the pixel format.\n  vw_throw(NoImplErr() << \"Unsupported pixel format or channel type in TileGenerator.\\n\");\n}\n\nint PlatefileTileGenerator::cols() const {\n  return this->tile_size()[0] * pow(2, m_num_levels-1);\n}\n\nint PlatefileTileGenerator::rows() const {\n  return this->tile_size()[1] * pow(2, m_num_levels-1);\n}\n\nPixelFormatEnum PlatefileTileGenerator::pixel_format() const {\n  return m_platefile->pixel_format();\n}\n\nChannelTypeEnum PlatefileTileGenerator::channel_type() const {\n  return m_platefile->channel_type();\n}\n\nVector2i PlatefileTileGenerator::tile_size() const {\n  return Vector2i(m_platefile->default_tile_size(),\n                  m_platefile->default_tile_size());\n}\n\nint32 PlatefileTileGenerator::num_levels() const {\n  return m_num_levels;\n}\n\n\n// --------------------------------------------------------------------------\n//                             IMAGE TILE GENERATOR\n// --------------------------------------------------------------------------\n\nImageTileGenerator::ImageTileGenerator(std::string filename) :\n  m_filename(filename), m_rsrc( DiskImageResource::open(filename) ) {\n  vw_out() << \"\\t--> Loading image: \" << filename << \".\\n\";\n}\n\n\n// This little template makes the code below much cleaner.\ntemplate <class PixelT>\nboost::shared_ptr<ViewImageResource> do_image_tilegen(boost::shared_ptr<SrcImageResource> rsrc,\n                                                      BBox2i tile_bbox,\n                                                      int level, int num_levels) {\n  ImageView<PixelT> tile(tile_bbox.width(), tile_bbox.height());\n  rsrc->read(tile.buffer(), tile_bbox);\n  ImageView<PixelT> reduced_tile = subsample(tile, pow(2,(num_levels-1) - level));\n  return boost::shared_ptr<ViewImageResource>( new ViewImageResource(reduced_tile) );\n}\n\nboost::shared_ptr<ViewImageResource> ImageTileGenerator::generate_tile(TileLocator const& tile_info) {\n\n  // Compute the bounding box of the image and the tile that is being\n  // requested.  The bounding box of the tile depends on the pyramid\n  // level we are looking at.\n  BBox2i image_bbox(0,0,m_rsrc->cols(),m_rsrc->rows());\n  BBox2i tile_bbox = tile_to_bbox(this->tile_size(), tile_info.col,\n                                  tile_info.row, tile_info.level, this->num_levels());\n\n  // Check to make sure the image intersects the bounding box.  Print\n  // an error to screen and return an empty tile if it does not.\n  if (!image_bbox.intersects(tile_bbox)) {\n    vw_out() << \"WARNING in ImageTileGenerator: a tile was requested that doesn't exist.\";\n    ImageView<PixelGray<uint8> > blank_tile(this->tile_size()[0], this->tile_size()[1]);\n    return boost::shared_ptr<ViewImageResource>( new ViewImageResource(blank_tile) );\n  }\n\n  // Make sure we don't access any pixels outside the image boundary\n  // by cropping the tile to the image dimensions.\n  tile_bbox.crop(image_bbox);\n\n  switch (this->pixel_format()) {\n  case VW_PIXEL_GRAY:\n    if (this->channel_type() == VW_CHANNEL_UINT8) {\n      return do_image_tilegen<PixelGray<uint8> >(m_rsrc, tile_bbox,\n                                                 tile_info.level, this->num_levels());\n    } else if (this->channel_type() == VW_CHANNEL_INT16) {\n      return do_image_tilegen<PixelGray<int16> >(m_rsrc, tile_bbox,\n                                                 tile_info.level, this->num_levels());\n    } else if (this->channel_type() == VW_CHANNEL_UINT16) {\n      return do_image_tilegen<PixelGray<uint16> >(m_rsrc, tile_bbox,\n                                                  tile_info.level, this->num_levels());\n    } else if (this->channel_type() == VW_CHANNEL_FLOAT32) {\n      return do_image_tilegen<PixelGray<float> >(m_rsrc, tile_bbox,\n                                                  tile_info.level, this->num_levels());\n    } else {\n      std::cout << \"This platefile has a channel type that is not yet support by vwv.\\n\";\n      std::cout << \"Exiting...\\n\\n\";\n      exit(0);\n  }\n  break;\n\n  case VW_PIXEL_GRAYA:\n    if (this->channel_type() == VW_CHANNEL_UINT8) {\n      return do_image_tilegen<PixelGrayA<uint8> >(m_rsrc, tile_bbox,\n                                                  tile_info.level, this->num_levels());\n    } else if (this->channel_type() == VW_CHANNEL_INT16) {\n      return do_image_tilegen<PixelGrayA<int16> >(m_rsrc, tile_bbox,\n                                                  tile_info.level, this->num_levels());\n    } else if (this->channel_type() == VW_CHANNEL_UINT16) {\n      return do_image_tilegen<PixelGrayA<uint16> >(m_rsrc, tile_bbox,\n                                                   tile_info.level, this->num_levels());\n    } else if (this->channel_type() == VW_CHANNEL_FLOAT32) {\n      return do_image_tilegen<PixelGrayA<float> >(m_rsrc, tile_bbox,\n                                                  tile_info.level, this->num_levels());\n    } else {\n      std::cout << \"This image has a channel type that is not yet support by vwv.\\n\";\n      std::cout << \"Exiting...\\n\\n\";\n      exit(0);\n      }\n\n    break;\n\n  case VW_PIXEL_RGB:\n    if (this->channel_type() == VW_CHANNEL_UINT8) {\n      return do_image_tilegen<PixelRGB<uint8> >(m_rsrc, tile_bbox,\n                                                tile_info.level, this->num_levels());\n    } else if (this->channel_type() == VW_CHANNEL_UINT16) {\n      return do_image_tilegen<PixelRGB<uint16> >(m_rsrc, tile_bbox,\n                                                tile_info.level, this->num_levels());\n    } else {\n      std::cout << \"This image has a channel type that is not yet support by vwv.\\n\";\n      std::cout << \"Exiting...\\n\\n\";\n      exit(0);\n    }\n\n    break;\n\n  case VW_PIXEL_RGBA:\n    if (this->channel_type() == VW_CHANNEL_UINT8) {\n      return do_image_tilegen<PixelRGBA<uint8> >(m_rsrc, tile_bbox,\n                                                 tile_info.level, this->num_levels());\n    } else if (this->channel_type() == VW_CHANNEL_UINT16) {\n      return do_image_tilegen<PixelRGBA<uint16> >(m_rsrc, tile_bbox,\n                                                  tile_info.level, this->num_levels());\n    } else {\n      std::cout << \"This image has a channel type that is not yet support by vwv.\\n\";\n      std::cout << \"Exiting...\\n\\n\";\n      exit(0);\n    }\n\n    break;\n\n  default:\n    std::cout << \"This image has a pixel format that is not yet support by vwv.\\n\";\n    std::cout << \"Exiting...\\n\\n\";\n    exit(0);\n  }\n\n  vw_throw(NoImplErr() << \"Unsupported pixel format or channel type in TileGenerator.\\n\");\n\n}\n\nVector2 ImageTileGenerator::minmax() {\n  return Vector2(0,1.0); // TODO: Implement this properly\n}\n\nPixelRGBA<float32> ImageTileGenerator::sample(int /*x*/, int /*y*/, int /*level*/, int /*transaction_id*/) {\n  PixelRGBA<float32> result; // TODO: Implement this properly\n  return result;\n}\n\n\nint ImageTileGenerator::cols() const {\n  return m_rsrc->cols();\n}\n\nint ImageTileGenerator::rows() const {\n  return m_rsrc->rows();\n}\n\nPixelFormatEnum ImageTileGenerator::pixel_format() const {\n  return m_rsrc->pixel_format();\n}\n\nChannelTypeEnum ImageTileGenerator::channel_type() const {\n  return m_rsrc->channel_type();\n}\n\nVector2i ImageTileGenerator::tile_size() const {\n  return m_rsrc->block_read_size();\n}\n\nint32 ImageTileGenerator::num_levels() const {\n  int32 max_dimension = std::max(this->cols(), this->rows());\n  int32 max_tilesize = std::max(this->tile_size()[0], this->tile_size()[1]);\n  return ceil(log(float(max_dimension) / max_tilesize) / log(2));\n}\n", "meta": {"hexsha": "bda84c27b7379ec054de20555cab53db9e977ddf", "size": 27220, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/gui/TileGenerator.cc", "max_stars_repo_name": "tkeemon/visionworkbench", "max_stars_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T04:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T04:06:43.000Z", "max_issues_repo_path": "src/vw/gui/TileGenerator.cc", "max_issues_repo_name": "tkeemon/visionworkbench", "max_issues_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_issues_repo_licenses": ["NASA-1.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": "src/vw/gui/TileGenerator.cc", "max_forks_repo_name": "tkeemon/visionworkbench", "max_forks_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.748502994, "max_line_length": 159, "alphanum_fraction": 0.5843130051, "num_tokens": 6367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16738411820402732}}
{"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 <cctype>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include <boost/timer.hpp>\n\n#include \"rangecoder.hh\"\n\ntemplate <class UInt>\nvoid encode(std::vector<double> const& data,\n\t    Alphabet<UInt> const& alphabet,\n\t    std::ostream& out) {\n  UInt const N=alphabet.size();\n  RangeEncoder<UInt> encoder(out);\n\n  for (size_t i=0; i<data.size(); ++i) {\n    UInt s = static_cast<UInt>(floor(N*data[i]));\n    s = std::min(s,N-1);\n    encodeSymbol(encoder,alphabet,s);\n  }\n  // std::cerr << \"compression rate: \"\n  //           << (double)data.size()*sizeof(double)/encoder.size()\n  //           << '\\n';\n  // std::cerr.flush();\n}\n\ntemplate <class UInt>\nvoid basic(std::vector<double> const& data,\n\t    std::ostream& out) {\n  out.write((char const*)(&data[0]),data.size()*sizeof(double));\n}\n\n \ntemplate <class UInt>\ndouble test(size_t n, char const* fname, bool renc=true) {\n  std::vector<double> data(n);\n  for (size_t i=0; i<n; ++i) {\n    data[i] = (random()%1000000)/1000000.0;\n    data[i] = std::pow(data[i],3.0);\n  }\n\n  UInt N = 1000;\n  std::vector<UInt> count(N);\n  for (size_t i=0; i<N; ++i) \n    count[i] = (UInt) floor(20*std::pow((i+.5)/N,-0.6667));\n\n  \n  Alphabet<UInt> alphabet(count.begin(),count.end());\n  \n\n  std::ofstream out(fname,std::ios::binary);  \n  boost::timer timer;\n  if (renc)\n    encode(data,alphabet,out);\n  else\n    basic<UInt>(data,out);\n  return timer.elapsed();\n}\n\n  \n\n\nint main(int argc, char const* argv[]) {\n  size_t n=100000;\n  for (int i=0; i<45; ++i) {\n    std::cout << n << ' ' << test<unsigned long>(n,\"/dev/null\")\n\t      << ' ' << test<unsigned long>(n,\"/tmp/nix2\")\n\t      << ' ' << test<unsigned long>(n,\"/tmp/nix2\",false)\n\t      << '\\n';\n    std::cout.flush();\n    \n    n = 6*n/5;\n  }\n  \n    \n  return 0;\n}\n\n", "meta": {"hexsha": "6aac14d4a194aa435a7abe96dc55e56479501c78", "size": 2680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tests/rangecoderperftest.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/rangecoderperftest.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/rangecoderperftest.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": 28.5106382979, "max_line_length": 79, "alphanum_fraction": 0.4645522388, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.16738410798910255}}
{"text": "#pragma once\n\n#include <boost/accumulators/statistics/sum.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/any.hpp>\n\n#include \"AlloShared/StatsUtils.hpp\"\n\nnamespace AlloReceiver\n{\n\tconst int FACE_COUNT = 12;\n\n\tStats::StatValsMaker statValsMaker = [](boost::chrono::microseconds             window,\n\t                                        boost::chrono::steady_clock::time_point now)\n\t{\n\t\tstd::list<Stats::StatVal> statVals;\n\n\t\tstatVals.insert(statVals.end(),\n\t\t{\n\t\t\tStatsUtils::cubemapsCount(\"cubemapsCount\",\n\t\t\twindow,\n\t\t\tnow)/*,\n\t\t\tStatsUtils::nalusBitSum(\"droppedNALUsBitSum\",\n\t\t\t-1,\n\t\t\tStatsUtils::NALU::DROPPED,\n\t\t\twindow,\n\t\t\tnow),\n\t\t\tStatsUtils::nalusBitSum(\"addedNALUsBitSum\",\n\t\t\t-1,\n\t\t\tStatsUtils::NALU::ADDED,\n\t\t\twindow,\n\t\t\tnow),\n\t\t\tStatsUtils::nalusBitSum(\"sentNALUsBitSum\",\n\t\t\t-1,\n\t\t\tStatsUtils::NALU::SENT,\n\t\t\twindow,\n\t\t\tnow)*/\n\t\t});\n\n\t\tfor (int face = -1; face < FACE_COUNT; face++)\n\t\t{\n            std::string faceStr = std::to_string(face);\n            \n\t\t\tstatVals.insert(statVals.end(),\n\t\t\t{\n\t\t\t\tStatsUtils::facesCount(\"facesCount\" + faceStr,\n                    face,\n                    window,\n                    now),\n                Stats::StatVal::makeStatVal(StatsUtils::andFilter(\n                    {\n                        StatsUtils::timeFilter(window,\n                                               now),\n                        StatsUtils::typeFilter(typeid(StatsUtils::Frame)),\n                        [face](Stats::TimeValueDatum datum)\n                        {\n                            return (face == -1) ? true : boost::any_cast<StatsUtils::Frame>(datum.value).face == face;\n                        },\n                        [face](Stats::TimeValueDatum datum)\n                        {\n                            return boost::any_cast<StatsUtils::Frame>(datum.value).status == StatsUtils::Frame::RECEIVED;\n                        }\n                    }),\n                    [](Stats::TimeValueDatum datum)\n                    {\n                        return 0.0;\n                    },\n                    boost::accumulators::tag::count(),\n                    \"receivedFrames\" + faceStr),\n                Stats::StatVal::makeStatVal(StatsUtils::andFilter(\n                    {\n                        StatsUtils::timeFilter(window,\n                                               now),\n                        StatsUtils::typeFilter(typeid(StatsUtils::Frame)),\n                        [face](Stats::TimeValueDatum datum)\n                        {\n                          return (face == -1) ? true : boost::any_cast<StatsUtils::Frame>(datum.value).face == face;\n                        },\n                        [face](Stats::TimeValueDatum datum)\n                        {\n                            return boost::any_cast<StatsUtils::Frame>(datum.value).status == StatsUtils::Frame::DECODED;\n                        }\n                    }),\n                    [](Stats::TimeValueDatum datum)\n                    {\n                        return 0.0;\n                    },\n                    boost::accumulators::tag::count(),\n                    \"decodedFrames\" + faceStr),\n                Stats::StatVal::makeStatVal(StatsUtils::andFilter(\n                                                                  {\n                                                                      StatsUtils::timeFilter(window,\n                                                                                             now),\n                                                                      StatsUtils::typeFilter(typeid(StatsUtils::Frame)),\n                                                                      [face](Stats::TimeValueDatum datum)\n                                                                      {\n                                                                          return (face == -1) ? true : boost::any_cast<StatsUtils::Frame>(datum.value).face == face;\n                                                                      },\n                                                                      [face](Stats::TimeValueDatum datum)\n                                                                      {\n                                                                          return boost::any_cast<StatsUtils::Frame>(datum.value).status == StatsUtils::Frame::COLOR_CONVERTED;\n                                                                      }\n                                                                  }),\n                                            [](Stats::TimeValueDatum datum)\n                                            {\n                                                return 0.0;\n                                            },\n                                            boost::accumulators::tag::count(),\n                                            \"colorConvertedFrames\" + faceStr),\n                Stats::StatVal::makeStatVal(StatsUtils::andFilter(\n                    {\n                        [window, now, face](Stats::TimeValueDatum datum)\n                        {\n                            return (now - datum.time) < window && // time filter\n                                datum.value.type() == typeid(StatsUtils::CubemapFace) && // type filter\n                                boost::any_cast<StatsUtils::CubemapFace>(datum.value).status == StatsUtils::CubemapFace::ADDED && // status filter\n                                (face == -1 || boost::any_cast<StatsUtils::CubemapFace>(datum.value).face == face); // face filter\n                        }\n                    }),\n                    [](Stats::TimeValueDatum datum)\n                    {\n                        return 0.0;\n                    },\n                    boost::accumulators::tag::count(),\n                    \"addedFacesCount\" + faceStr),\n                Stats::StatVal::makeStatVal(StatsUtils::andFilter(\n                    {\n                        [window, now, face](Stats::TimeValueDatum datum)\n                        {\n                          return (now - datum.time) < window && // time filter\n                            datum.value.type() == typeid(StatsUtils::CubemapFace) && // type filter\n                            boost::any_cast<StatsUtils::CubemapFace>(datum.value).status == StatsUtils::CubemapFace::SCHEDULED && // status filter\n                            (face == -1 || boost::any_cast<StatsUtils::CubemapFace>(datum.value).face == face); // face filter\n                        }\n                    }),\n                    [](Stats::TimeValueDatum datum)\n                    {\n                        return 0.0;\n                    },\n                    boost::accumulators::tag::count(),\n                    \"scheduledFacesCount\" + faceStr)\n\t\t\t\t/*StatsUtils::nalusCount(\"droppedNALUsCount\" + std::to_string(face),\n\t\t\t\tface,\n\t\t\t\tStatsUtils::NALU::DROPPED,\n\t\t\t\twindow,\n\t\t\t\tnow),\n\t\t\t\tStatsUtils::nalusCount(\"addedNALUsCount\" + std::to_string(face),\n\t\t\t\tface,\n\t\t\t\tStatsUtils::NALU::ADDED,\n\t\t\t\twindow,\n\t\t\t\tnow),\n\t\t\t\tStatsUtils::nalusCount(\"sentNALUsCount\" + std::to_string(face),\n\t\t\t\tface,\n\t\t\t\tStatsUtils::NALU::SENT,\n\t\t\t\twindow,\n\t\t\t\tnow)*/\n\t\t\t});\n\t\t}\n\n\t\treturn statVals;\n\t};\n\n\tStats::PostProcessorMaker postProcessorMaker = [](boost::chrono::microseconds             window,\n\t\t                                              boost::chrono::steady_clock::time_point now)\n\t{\n\t\tStats::PostProcessor postProcessor = [window, now](std::map<std::string, double>& results)\n\t\t{\n\t\t\tunsigned long seconds = boost::chrono::duration_cast<boost::chrono::seconds>(window).count();\n\n\t\t\tresults[\"fps\"] = results[\"cubemapsCount\"] / seconds;\n\n\t\t\t//results.insert(\n\t\t\t//{\n\t\t\t\t\n\n\t\t\t\t/*{\n\t\t\t\t\t\"naluDropRate\",\n\t\t\t\t\tresults[\"droppedNALUsCount-1\"] / results[\"addedNALUsCount-1\"]\n\t\t\t\t},*/\n\t\t\t\t/*{\n\t\t\t\t\t\"fps\",\n\t\t\t\t\tresults[\"cubemapsCount\"] / seconds\n\t\t\t\t},*/\n\t\t\t\t/*{\n\t\t\t\t\t\"receivedNALUsBitS\",\n\t\t\t\t\t(results[\"droppedNALUsBitSum\"] + results[\"addedNALUsBitSum\"]) / seconds\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"processedNALUsBitS\",\n\t\t\t\t\tresults[\"addedNALUsBitSum\"] / seconds\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"sentNALUsBitS\",\n\t\t\t\t\tresults[\"sentNALUsBitSum\"] / seconds\n\t\t\t\t},*/\n\t\t\t//});\n\n\t\t\tfor (int face = -1; face < FACE_COUNT; face++)\n\t\t\t{\n\t\t\t\tstd::string faceStr = std::to_string(face);\n\n\t\t\t\tresults.insert(\n\t\t\t\t{\n\t\t\t\t\t{\n\t\t\t\t\t\t\"facesPS\" + faceStr,\n\t\t\t\t\t\tresults[\"facesCount\" + faceStr] / seconds\n\t\t\t\t\t},\n\t\t\t\t\t/*{\n\t\t\t\t\t\t\"receivedNALUsPS\" + faceStr,\n\t\t\t\t\t\t(results[\"droppedNALUsCount\" + faceStr] + results[\"addedNALUsCount\" + faceStr]) / seconds\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"processedNALUsPS\" + faceStr,\n\t\t\t\t\t\tresults[\"addedNALUsCount\" + faceStr] / seconds\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"sentNALUsPS\" + faceStr,\n\t\t\t\t\t\tresults[\"sentNALUsCount\" + faceStr] / seconds\n\t\t\t\t\t},*/\n                    {\n                        \"receivedFrames\" + faceStr + \"PS\",\n                        results[\"receivedFrames\" + faceStr] / seconds\n                    },\n                    {\n                        \"decodedFrames\" + faceStr + \"PS\",\n                        results[\"decodedFrames\" + faceStr] / seconds\n                    },\n                    {\n                        \"colorConvertedFrames\" + faceStr + \"PS\",\n                        results[\"colorConvertedFrames\" + faceStr] / seconds\n                    },\n                    {\n                        \"addedFaces\" + faceStr + \"PS\",\n                        results[\"addedFacesCount\" + faceStr] / seconds\n                    },\n                    {\n                        \"scheduledFaces\" + faceStr + \"PS\",\n                        results[\"scheduledFacesCount\" + faceStr] / seconds\n                    }\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\treturn postProcessor;\n\t};\n\n\tauto formatStringMaker = []()\n\t{\n\t\tstd::stringstream stream;\n\t\t/*stream << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\tstream << \"NALU drop rate: {naluDropRate:0.1f}\" << std::endl;\n\t\tstream << \"received NALUs/s: {receivedNALUsPS-1:0.1f}; {receivedNALUsBitS:0.1f} MBit/s;\" << std::endl;\n\t\tfor (int j = 0; j < (std::min) (2, FACE_COUNT); j++)\n\t\t{\n\t\t\tstream << \"recvd NALUs/s per face (\" << ((j == 0) ? \"left\" : \"right\") << \"):\";\n\t\t\tfor (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n\t\t\t{\n\t\t\t\tstream << \"\\t{receivedNALUsPS\" << j * 6 + i << \":0.1f}\";\n\t\t\t}\n\t\t\tstream << \";\" << std::endl;\n\t\t}\n\t\tstream << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\tstream << \"processed NALUs/s: {processedNALUsPS-1:0.1f}; {processedNALUsBitS:0.1f} MBit/s;\" << std::endl;\n\t\tfor (int j = 0; j < (std::min) (2, FACE_COUNT); j++)\n\t\t{\n\t\t\tstream << \"prced NALUs/s per face (\" << ((j == 0) ? \"left\" : \"right\") << \"):\";\n\t\t\tfor (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n\t\t\t{\n\t\t\t\tstream << \"\\t{processedNALUsPS\" << j * 6 + i << \":0.1f}\";\n\t\t\t}\n\t\t\tstream << \";\" << std::endl;\n\t\t}\n\n\t\tstream << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\tstream << \"sent NALUs/s: {sentNALUsPS-1:0.1f}; {sentNALUsBitS:0.1f} MBit/s;\" << std::endl;\n\t\tfor (int j = 0; j < (std::min) (2, FACE_COUNT); j++)\n\t\t{\n\t\t\tstream << \"sent NALUs/s per face (\" << ((j == 0) ? \"left\" : \"right\") << \"):\";\n\t\t\tfor (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n\t\t\t{\n\t\t\t\tstream << \"\\t{sentNALUsPS\" << j * 6 + i << \":0.1f}\";\n\t\t\t}\n\t\t\tstream << \";\" << std::endl;\n\t\t}*/\n        \n        stream << \"-------------------------------------------------------------------------------\" << std::endl;\n        stream << \"Received frames/s:\" << std::endl;\n        for (int j = 0; j < (std::min) (2, FACE_COUNT); j++)\n        {\n            stream << ((j == 0) ? \"left\" : \"right\") << \":\";\n            for (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n            {\n                stream << \"\\t{receivedFrames\" << j * 6 + i << \"PS:0.1f}\";\n            }\n            stream << \";\" << std::endl;\n        }\n        \n        stream << \"-------------------------------------------------------------------------------\" << std::endl;\n        stream << \"Decoded frames/s:\" << std::endl;\n        for (int j = 0; j < (std::min) (2, FACE_COUNT); j++)\n        {\n            stream << ((j == 0) ? \"left\" : \"right\") << \":\";\n            for (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n            {\n                stream << \"\\t{decodedFrames\" << j * 6 + i << \"PS:0.1f}\";\n            }\n            stream << \";\" << std::endl;\n        }\n        \n        stream << \"-------------------------------------------------------------------------------\" << std::endl;\n        stream << \"Color converted frames/s:\" << std::endl;\n        for (int j = 0; j < (std::min) (2, FACE_COUNT); j++)\n        {\n            stream << ((j == 0) ? \"left\" : \"right\") << \":\";\n            for (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n            {\n                stream << \"\\t{colorConvertedFrames\" << j * 6 + i << \"PS:0.1f}\";\n            }\n            stream << \";\" << std::endl;\n        }\n        \n        /*stream << \"Decoded:\\t\";\n        for (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n        {\n            stream << \"{receivedFrames\" << faceStr << \"PS:0.1f}\\t\";\n        }\n        stream << \";\" << std::endl;*/\n        \n\t\tstream << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\tstream << \"Added faces/s:\" << std::endl;\n        for (int j = 0; j < (std::min) (2, FACE_COUNT); j++)\n        {\n            stream << ((j == 0) ? \"left\" : \"right\") << \":\";\n            for (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n            {\n                stream << \"\\t{addedFaces\" << j * 6 + i << \"PS:0.1f}\";\n            }\n            stream << \";\" << std::endl;\n        }\n        \n        stream << \"-------------------------------------------------------------------------------\" << std::endl;\n        stream << \"Scheduled faces/s:\" << std::endl;\n        for (int j = 0; j < (std::min) (2, FACE_COUNT); j++)\n        {\n            stream << ((j == 0) ? \"left\" : \"right\") << \":\";\n            for (int i = 0; i < (std::min) (6, FACE_COUNT - j * 6); i++)\n            {\n                stream << \"\\t{scheduledFaces\" << j * 6 + i << \"PS:0.1f}\";\n            }\n            stream << \";\" << std::endl;\n        }\n        \n        stream << \"-------------------------------------------------------------------------------\" << std::endl;\n        stream << \"cubemap face 0-5 (left ) fps:\";\n        for (int i = 0; i < 6; i++)\n        {\n            stream << \"\\t{facesPS\" << i << \":0.1f}\";\n        }\n        stream << \";\" << std::endl;\n        \n        stream << \"cubemap face 0-5 (right) fps:\";\n        for (int i = 6; i < 12; i++)\n        {\n            stream << \"\\t{facesPS\" << i << \":0.1f}\";\n        }\n        stream << \";\" << std::endl;\n        stream << \"fps: {fps:0.1f}\" << std::endl;\n\n\t\treturn stream.str();\n\t};\n}\n", "meta": {"hexsha": "d3787a2ec98c27ddcb80baef16b25ac8f1c24155", "size": 14941, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AlloReceiver/Stats.hpp", "max_stars_repo_name": "tiborgo/AlloStreamer", "max_stars_repo_head_hexsha": "bf91586a88c3aec8e5603e5606caf3c3d0d53139", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-04-01T09:43:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-09T19:04:18.000Z", "max_issues_repo_path": "AlloReceiver/Stats.hpp", "max_issues_repo_name": "tiborgo/AlloStreamer", "max_issues_repo_head_hexsha": "bf91586a88c3aec8e5603e5606caf3c3d0d53139", "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": "AlloReceiver/Stats.hpp", "max_forks_repo_name": "tiborgo/AlloStreamer", "max_forks_repo_head_hexsha": "bf91586a88c3aec8e5603e5606caf3c3d0d53139", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-04-08T00:34:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-15T19:21:13.000Z", "avg_line_length": 39.949197861, "max_line_length": 174, "alphanum_fraction": 0.3998393682, "num_tokens": 3533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.1673189941500973}}
{"text": "// Copyright (c) 2019 Graphcore Ltd. All rights reserved.\n#include <memory>\n#include <numeric>\n#include <popart/graph.hpp>\n#include <popart/ir.hpp>\n#include <popart/op/concat.hpp>\n#include <popart/op/gather.hpp>\n#include <popart/op/reshape.hpp>\n#include <popart/op/slice.hpp>\n#include <popart/op/transpose.hpp>\n#include <popart/patterns/pattern.hpp>\n#include <popart/patterns/splitgather.hpp>\n#include <popart/tensor.hpp>\n#include <popart/tensordata.hpp>\n#include <popart/tensorindex.hpp>\n#include <popart/tensors.hpp>\n\n#include <boost/integer/common_factor.hpp>\n\nnamespace popart {\n\n// Private gather op class\nnamespace {\nclass SplitGatherOp : public GatherOp {\npublic:\n  using GatherOp::GatherOp;\n};\n} // namespace\n\nbool SplitGatherPattern::matches(Op *op) const {\n  // Isn't a gather op\n  if (!op->isConvertibleTo<GatherOp>()) {\n    return false;\n  }\n\n  // Is an already split gather op\n  if (op->isConvertibleTo<SplitGatherOp>()) {\n    return false;\n  }\n\n  // The op doesn't have a vgraph id\n  if (!op->hasVirtualGraphId()) {\n    return false;\n  }\n\n  if (op->input->tensor(GatherOp::dataInIndex())->tensorType() !=\n      TensorType::Const) {\n    return false;\n  }\n\n  auto gather = dynamic_cast<GatherOp *>(op);\n\n  const auto inputShape = gather->inShape(GatherOp::dataInIndex());\n  const auto axis       = gather->getAxis();\n\n  const int64_t virtualGraphCount = op->getIr().getDeviceInfo()->getNumIpus();\n\n  // We aren't using vgraphs\n  if (!op->getIr().virtualGraphsEnabled()) {\n    return false;\n  }\n\n  // We don't have any vgraphs to split on\n  if (virtualGraphCount < 2) {\n    return false;\n  }\n\n  const auto numElements = std::accumulate(\n      inputShape.begin(), inputShape.end(), 1, std::multiplies<int64_t>());\n\n  const auto split =\n      boost::integer::gcd(virtualGraphCount, numElements / inputShape[axis]);\n\n  // We won't split the gather\n  if (split < 2) {\n    return false;\n  }\n\n  return true;\n}\n\nstd::vector<const Tensor *> SplitGatherPattern::touches(Op *) const {\n  return {};\n}\n\nstatic std::unique_ptr<TransposeOp>\ncanonicalizeTranspose(const int64_t axis,\n                      const Shape &inputShape,\n                      const Op::Settings &settings) {\n  std::vector<int64_t> permutation(inputShape.size());\n  std::iota(permutation.begin(), permutation.end(), 0);\n  std::swap(permutation.front(), permutation[axis]);\n\n  return std::make_unique<TransposeOp>(\n      Onnx::Operators::Transpose_1, permutation, settings);\n}\n\nstatic std::unique_ptr<ReshapeOp>\ncanonicalizeShape(const int64_t axis,\n                  const Shape &inputShape,\n                  const Op::Settings &settings) {\n  const auto numElements = std::accumulate(\n      inputShape.begin(), inputShape.end(), 1, std::multiplies<int64_t>());\n\n  const Shape canonShape = {inputShape[axis], numElements / inputShape[axis]};\n  return std::make_unique<ReshapeOp>(\n      Onnx::Operators::Reshape_5, canonShape, settings);\n}\n\nstatic std::vector<std::unique_ptr<SliceOp>>\ncreateSlices(const int64_t count, const int64_t stride, Op::Settings settings) {\n  std::vector<std::unique_ptr<SliceOp>> slices;\n  slices.reserve(count);\n\n  for (int i = 0; i < count; ++i) {\n    settings.vgraphId = i;\n\n    const std::vector<int64_t> starts_ = {i * stride};\n    const std::vector<int64_t> ends_   = {(i + 1) * stride};\n    const std::vector<int64_t> axes_   = {1};\n    const std::vector<int64_t> steps_  = {};\n\n    slices.push_back(std::make_unique<SliceOp>(\n        Onnx::Operators::Slice_1, starts_, ends_, axes_, steps_, settings));\n  }\n\n  return slices;\n}\n\nstatic std::vector<std::unique_ptr<SplitGatherOp>>\ncreateGathers(const int64_t count,\n              Op::Settings settings,\n              const nonstd::optional<float> &availMemProp) {\n  std::vector<std::unique_ptr<SplitGatherOp>> gathers;\n  gathers.reserve(count);\n\n  for (int i = 0; i < count; ++i) {\n    settings.vgraphId = i;\n    gathers.push_back(std::make_unique<SplitGatherOp>(\n        Onnx::Operators::Gather_1, 0, settings, availMemProp));\n  }\n\n  return gathers;\n}\n\nstatic std::unique_ptr<ReshapeOp>\ndecanonicalizeShape(const int64_t axis,\n                    Shape origShape,\n                    Shape indicesShape,\n                    const Op::Settings &settings) {\n  std::swap(origShape.front(), origShape[axis]);\n  origShape.erase(origShape.begin());\n  origShape.insert(origShape.begin(), indicesShape.begin(), indicesShape.end());\n\n  return std::make_unique<ReshapeOp>(\n      Onnx::Operators::Reshape_5, origShape, settings);\n}\n\nstatic std::unique_ptr<TransposeOp>\ndecanonicalizeTranspose(const int64_t axis,\n                        Shape inputShape,\n                        Shape indicesShape,\n                        const Op::Settings &settings) {\n  std::vector<int64_t> permutation(inputShape.size() + indicesShape.size() - 1);\n  std::iota(permutation.begin(), permutation.end(), 0);\n  std::rotate(permutation.begin(),\n              permutation.begin() + indicesShape.size(),\n              permutation.begin() + indicesShape.size() + axis);\n\n  return std::make_unique<TransposeOp>(\n      Onnx::Operators::Transpose_1, permutation, settings);\n}\n\nbool SplitGatherPattern::apply(Op *op) const {\n  auto gather = dynamic_cast<GatherOp *>(op);\n\n  const auto inputShape           = gather->inShape(GatherOp::dataInIndex());\n  const auto axis                 = gather->getAxis();\n  const auto availMemProp         = gather->getAvailableMemoryProportion();\n  const int64_t virtualGraphCount = op->getIr().getDeviceInfo()->getNumIpus();\n\n  const auto numElements = std::accumulate(\n      inputShape.begin(), inputShape.end(), 1, std::multiplies<int64_t>());\n\n  const auto split =\n      boost::integer::gcd(virtualGraphCount, numElements / inputShape[axis]);\n  const auto stride      = (numElements / inputShape[axis]) / split;\n  const auto inTensorId  = op->input->id(GatherOp::dataInIndex());\n  const auto idxTensorId = op->input->id(GatherOp::indicesInIndex());\n  auto output            = op->outTensor(GatherOp::outIndex());\n  op->disconnectOutTensor(output);\n  const auto outTensorId = output->id;\n\n  logging::pattern::trace(\"Splitting {} into {} gathers of size [{}, {}]\",\n                          op->str(),\n                          split,\n                          inputShape[axis],\n                          (numElements / inputShape[axis]) / split);\n\n  auto t0        = inTensorId;\n  auto transpose = canonicalizeTranspose(axis, inputShape, op->settings);\n  auto t1        = output->getIr().createIntermediateTensorId(outTensorId);\n  transpose->connectInTensor(0, t0);\n  transpose->createAndConnectOutTensor(0, t1);\n  transpose->setup();\n\n  // Reshape the input tensor to a 2D tensor with the gather axis at the front\n  auto reshape = canonicalizeShape(axis, inputShape, op->settings);\n  auto t2      = transpose->getIr().createIntermediateTensorId(outTensorId);\n  reshape->connectInTensor(0, t1);\n  reshape->createAndConnectOutTensor(0, t2);\n  reshape->setup();\n\n  // Slice the input tensor along the sequence dimension for each IPU\n  auto slices = createSlices(split, stride, op->settings);\n  std::vector<TensorId> slicedts;\n  slicedts.reserve(split);\n  for (int i = 0; i < split; ++i) {\n    auto tid = reshape->getIr().createIntermediateTensorId(outTensorId);\n    slicedts.push_back(tid);\n    slices[i]->connectInTensor(0, t2);\n    slices[i]->createAndConnectOutTensor(0, tid);\n    slices[i]->setup();\n  }\n\n  // Gather the slice fragments on each IPU\n  auto gathers = createGathers(split, op->settings, availMemProp);\n  std::vector<TensorId> gatheredts;\n  gatheredts.reserve(split);\n  for (int i = 0; i < split; ++i) {\n    auto tid = gathers[i]->getIr().createIntermediateTensorId(outTensorId);\n    gatheredts.push_back(tid);\n    gathers[i]->connectInTensor(0, slicedts[i]);\n    gathers[i]->connectInTensor(1, idxTensorId);\n    gathers[i]->createAndConnectOutTensor(0, tid);\n    gathers[i]->setup();\n  }\n\n  // Concatenate the gathered fragments\n  const auto concatDim = gather->inRank(1);\n  auto concat          = std::make_unique<ConcatOp>(\n      Onnx::Operators::Concat_4, concatDim, op->settings);\n  auto t3 = concat->getIr().createIntermediateTensorId(outTensorId);\n  for (int i = 0; i < split; ++i) {\n    concat->connectInTensor(i, gatheredts[i]);\n  }\n  concat->createAndConnectOutTensor(0, t3);\n  concat->setup();\n\n  const auto indicesShape = gather->inShape(1);\n\n  // Reshape back to the original shape, with the gather axis at the front\n  auto unreshape =\n      decanonicalizeShape(axis, inputShape, indicesShape, op->settings);\n  auto t4 = concat->getIr().createIntermediateTensorId(outTensorId);\n  unreshape->connectInTensor(0, t3);\n  unreshape->createAndConnectOutTensor(0, t4);\n  unreshape->setup();\n\n  // Put the gather axis back in original position\n  auto untranspose =\n      decanonicalizeTranspose(axis, inputShape, indicesShape, op->settings);\n  auto t5 = outTensorId;\n  untranspose->connectInTensor(0, t4);\n  untranspose->connectOutTensor(0, t5);\n  untranspose->setup();\n\n  // Insert the ops into the IR\n  auto &graph = op->getGraph();\n  graph.moveIntoGraph(std::move(transpose));\n  graph.moveIntoGraph(std::move(reshape));\n  for (auto &s : slices) {\n    graph.moveIntoGraph(std::move(s));\n  }\n  for (auto &g : gathers) {\n    graph.moveIntoGraph(std::move(g));\n  }\n  graph.moveIntoGraph(std::move(concat));\n  graph.moveIntoGraph(std::move(unreshape));\n  graph.moveIntoGraph(std::move(untranspose));\n\n  // Remove the old op\n  op->disconnectAllInputs();\n  op->getGraph().eraseOp(op->id);\n\n  return true;\n}\n\nnamespace {\nstatic PatternCreator<SplitGatherPattern> splitGatherer(\"SplitGather\", false);\n}\n\n} // namespace popart\n", "meta": {"hexsha": "c605aea929f8a07f48a978b96758b4fb26ba2d96", "size": 9596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "willow/src/patterns/splitgather.cpp", "max_stars_repo_name": "gglin001/popart", "max_stars_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:51.000Z", "max_issues_repo_path": "willow/src/patterns/splitgather.cpp", "max_issues_repo_name": "gglin001/popart", "max_issues_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T01:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T11:13:14.000Z", "max_forks_repo_path": "willow/src/patterns/splitgather.cpp", "max_forks_repo_name": "gglin001/popart", "max_forks_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T06:55:00.000Z", "avg_line_length": 32.6394557823, "max_line_length": 80, "alphanum_fraction": 0.6740308462, "num_tokens": 2482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.16718223246391922}}
{"text": "#include <math.h>\n#include <vector>\n#include <ros/ros.h>\n#include <iomanip>\n#include <iostream>\n#include <boost/thread.hpp> \n\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"sensor_msgs/Joy.h\"\n#include \"std_srvs/Empty.h\"\n\n#include \"wam_msgs/RTCartVel.h\"\n#include \"wam_msgs/RTOrtnVel.h\"\n#include \"wam_srvs/GravityComp.h\"\n#include \"wam_srvs/Hold.h\"\n#include \"wam_srvs/BHandGraspVel.h\"\n#include \"wam_srvs/BHandSpreadVel.h\"\n#include \"wam_srvs/ForceTorqueTool.h\"\n#include \"wam_srvs/ForceTorqueBase.h\"\n#include \"wam_srvs/ForceTorque.h\"\n\n#define MODE_DISCONNECT 0\n#define MODE_FREE 1\n#define MODE_BASE_CONNECT 2\n#define MODE_BASE_UPDATE 3\n#define MODE_TOOL_CONNECT 4\n#define MODE_FORCE_UPDATE 5\n#define MODE_TORQUE_UPDATE 6\n#define BUTTON_A 0\n#define BUTTON_B 1\n#define BUTTON_X 2\n#define BUTTON_Y 3\n#define BUTTON_LB 4\n#define BUTTON_RB 5\n#define BUTTON_BACK 6\n#define BUTTON_START 7\n#define BUTTON_LEFT_STICK 9\n#define BUTTON_RIGHT_STICK 10\n\nusing namespace std;\n\nconst int CNTRL_FREQ = 50; // Frequency at which we will publish our control messages.\nconst double MAX_FORCE = 6.0;\nconst double MAX_TORQUE = 0.2;\n\n//WamTeleop Class\nclass WamTeleop {\n  public:\n    ros::NodeHandle n_, nh_wam, nh_bhand; // NodeHandles for publishing / subscribing on topics \"/... & /wam/...\" & \"/bhand/...\"\n    // Boolean statuses for commanded states\n    // bool cart_publish, ortn_publish, home_publish;\n    // bool hold_publish, home_st, hold_st, ortn_mode;\n    // bool open_grasp, close_grasp;\n    // bool open_spread, close_spread;\n    // bool open_grasp_state, close_grasp_state;\n    // bool open_spread_state, close_spread_state;\n    // bool stop;\n    bool grasp;\n    bool spread;\n    bool lock_joints;\n    bool new_command;\n    // bool rt_control;\n    // Integer status for BarrettHand commanded state\n    // int bh_cmd_st;\n    int mode;\n    //variables to describe buttons on Joystick and their assignments\n    // int deadman_btn, guardian_deadman_btn;\n    // int gpr_open_btn, gpr_close_btn;\n    // int sprd_open_btn, sprd_close_btn;\n    // int ortn_btn, home_btn, hold_btn;\n    // int axis_x, axis_y, axis_z;\n    // int axis_r, axis_p, axis_yaw;\n    int button_pressed;\n    //variables to describe velocity commands\n    // double max_grsp_vel, max_sprd_vel;\n    // double cart_mag, ortn_mag;\n    double req_xdir, req_ydir, req_zdir;\n    double req_rdir, req_pdir, req_yawdir;\n    //Subscribers\n    ros::Subscriber joy_sub;\n    //Services\n    wam_srvs::BHandGraspVel grasp_vel;\n    wam_srvs::BHandSpreadVel spread_vel;\n    wam_srvs::Hold hold;\n    std_srvs::Empty go_home;\n    std_srvs::Empty empty;\n    //Service Clients\n    ros::ServiceClient bhand_init_srv;\n    ros::ServiceClient grasp_open_srv;\n    ros::ServiceClient grasp_close_srv;\n    ros::ServiceClient grasp_vel_srv;\n    ros::ServiceClient spread_open_srv;\n    ros::ServiceClient spread_close_srv;\n    ros::ServiceClient spread_vel_srv;\n    ros::ServiceClient go_home_srv;\n    ros::ServiceClient hold_srv;\n    ros::ServiceClient force_torque_base_srv;\n    ros::ServiceClient joy_force_torque_base_srv;\n    ros::ServiceClient joy_force_torque_tool_srv;\n    ros::ServiceClient disconnect_srv;\n    //Messages\n    // wam_msgs::RTCartVel cart_vel;\n    // wam_msgs::RTOrtnVel ortn_vel;\n    //Publishers\n    // ros::Publisher cart_vel_pub, ortn_vel_pub;\n    // Name our nodehandle \"wam\" to preceed our messages/services\n    WamTeleop() : nh_wam(\"zeus/wam\"), nh_bhand(\"zeus/bhand\") {}\n\n    void init();\n    void joyCallback(const sensor_msgs::Joy::ConstPtr& joy_msg);\n    void updateRT();\n    void updateCommand();\n\n    ~WamTeleop() {}\n};\n\n// WAM Teleoperation Initialization Function\nvoid WamTeleop::init() {\n    hold.request.hold = false; // Default Start for joint hold command is false\n    mode = MODE_DISCONNECT;\n    lock_joints = false;\n    grasp = true;\n    spread = false;\n    new_command = false;\n\n    joy_sub = n_.subscribe < sensor_msgs::Joy > (\"joy\", 1, &WamTeleop::joyCallback, this); // /joy\n\n    bhand_init_srv = nh_bhand.serviceClient<std_srvs::Empty>(\"initialize\");\n    grasp_open_srv = nh_bhand.serviceClient<std_srvs::Empty>(\"open_grasp\");\n    grasp_close_srv = nh_bhand.serviceClient<std_srvs::Empty>(\"close_grasp\");\n    spread_open_srv = nh_bhand.serviceClient<std_srvs::Empty>(\"open_spread\");\n    spread_close_srv = nh_bhand.serviceClient<std_srvs::Empty>(\"close_spread\");\n    spread_vel_srv = nh_bhand.serviceClient<wam_srvs::BHandSpreadVel>(\"spread_vel\");\n    grasp_vel_srv = nh_bhand.serviceClient<wam_srvs::BHandGraspVel>(\"grasp_vel\");\n    go_home_srv = nh_wam.serviceClient<std_srvs::Empty>(\"go_home\");                  // /wam/go_home\n    hold_srv = nh_wam.serviceClient<wam_srvs::Hold>(\"hold_joint_pos\");               // /wam/hold_joint_pos\n    force_torque_base_srv = nh_wam.serviceClient<wam_srvs::ForceTorqueBase>(\"force_torque_base\");\n    joy_force_torque_base_srv = nh_wam.serviceClient<wam_srvs::ForceTorque>(\"joy_force_torque_base\");\n    joy_force_torque_tool_srv = nh_wam.serviceClient<wam_srvs::ForceTorque>(\"joy_force_torque_tool\");\n    disconnect_srv = nh_wam.serviceClient<std_srvs::Empty>(\"disconnect_systems\");\n    // cout << \"MODE_FREE\" << endl;\n    // cart_vel_pub = nh_wam.advertise<wam_msgs::RTCartVel>(\"cart_vel_cmd\", 1);         // /wam/cart_vel_cmd\n    // ortn_vel_pub = nh_wam.advertise<wam_msgs::RTOrtnVel>(\"ortn_vel_cmd\", 1);         // /wam/ortn_vel_cmd\n}\n\nvoid WamTeleop::joyCallback(const sensor_msgs::Joy::ConstPtr& joy_msg) {\n    //Set our publishing states back to false for new commands\n    std::vector<int> input;\n    input = joy_msg->buttons;\n    for (int i = 0; i < joy_msg->buttons.size(); ++i) {\n        if (!new_command && joy_msg->buttons[i]) { \n            button_pressed = i;\n            new_command = true;\n        }\n    }\n    if (-0.25 < joy_msg->axes[1] && joy_msg->axes[1] < 0.25) {\n        req_xdir = 0.0;\n    } else {\n        req_xdir = joy_msg->axes[1];\n    }\n\n    if (-0.25 < joy_msg->axes[0] && joy_msg->axes[0] < 0.25) {\n        req_ydir = 0.0;\n    } else {\n        req_ydir = joy_msg->axes[0];\n    }\n\n    if (-0.25 < joy_msg->axes[4] && joy_msg->axes[4] < 0.25) {\n        req_zdir = 0.0;\n    } else {\n        req_zdir = joy_msg->axes[4];\n    }\n    // //RPY Velocity Portion\n    // if ((joy_msg->axes[axis_r] > 0.25 || joy_msg->axes[axis_r] < -0.25) && ortn_mode) {\n    //     req_rdir = -joy_msg->axes[axis_r];\n    //     ortn_publish = true;\n    // } else {\n    //     req_rdir = 0.0;\n    // }\n\n    // if ((joy_msg->axes[axis_y] > 0.25 || joy_msg->axes[axis_y] < -0.25) && ortn_mode) {\n    //     req_pdir = -joy_msg->axes[axis_p];\n    //     ortn_publish = true;\n    // } else {\n    //     req_pdir = 0.0;\n    // }\n    // if ((joy_msg->axes[axis_z] > 0.25 || joy_msg->axes[axis_z] < -0.25) && ortn_mode) {\n    //     req_yawdir = joy_msg->axes[axis_yaw];\n    //     ortn_publish = true;\n    // } else {\n    //     req_yawdir = 0.0;\n    // }\n\n}\n\nvoid WamTeleop::updateRT() {\n    ros::Rate r(CNTRL_FREQ); // Setting the publishing rate to CNTRL_FREQ (50Hz by default)\n    while (ros::ok()) {\n        wam_srvs::ForceTorque ft;\n        // cout << \"Mode: \" << mode << endl;\n        switch (mode) {\n            case MODE_DISCONNECT:\n                disconnect_srv.call(empty);\n                mode = MODE_FREE;\n                cout << \"\\tFREE\" << endl;\n                break;\n            case MODE_FREE:\n                break;\n            case MODE_BASE_CONNECT:\n                ft.request.torque.push_back(0.0);\n                ft.request.torque.push_back(0.0);\n                ft.request.torque.push_back(0.0);\n                ft.request.force.push_back(req_xdir);\n                ft.request.force.push_back(req_ydir);\n                ft.request.force.push_back(req_zdir);\n                ft.request.kp.push_back(4.0);\n                ft.request.kp.push_back(4.0);\n                ft.request.kp.push_back(4.0);\n                ft.request.kd.push_back(0.2);\n                ft.request.kd.push_back(0.2);\n                ft.request.kd.push_back(0.2);\n                ft.request.initialize = true;\n                joy_force_torque_base_srv.call(ft);\n                mode = MODE_BASE_UPDATE;\n                cout << \"\\tBASE FORCE UPDATE\" << endl;\n                break;\n            case MODE_BASE_UPDATE:\n                ft.request.torque.push_back(0.0);\n                ft.request.torque.push_back(0.0);\n                ft.request.torque.push_back(0.0);\n                ft.request.force.push_back(req_xdir);\n                ft.request.force.push_back(req_ydir);\n                ft.request.force.push_back(req_zdir);\n                ft.request.kp.push_back(150.0);                    \n                ft.request.kp.push_back(150.0);                    \n                ft.request.kp.push_back(150.0);  \n                ft.request.kd.push_back(5.0);\n                ft.request.kd.push_back(5.0);\n                ft.request.kd.push_back(5.0);\n                ft.request.initialize = false;                \n                joy_force_torque_base_srv.call(ft);\n                break;      \n            case MODE_TOOL_CONNECT:\n                ft.request.torque.push_back(0.0);\n                ft.request.torque.push_back(0.0);\n                ft.request.torque.push_back(0.0);\n                ft.request.force.push_back(0.0);\n                ft.request.force.push_back(0.0);\n                ft.request.force.push_back(0.0);\n                ft.request.kp.push_back(0.0);\n                ft.request.kp.push_back(0.0);\n                ft.request.kp.push_back(0.0);\n                ft.request.kd.push_back(0.0);\n                ft.request.kd.push_back(0.0);\n                ft.request.kd.push_back(0.0);\n                ft.request.initialize = true;\n                joy_force_torque_tool_srv.call(ft);\n                mode = MODE_FORCE_UPDATE;\n                cout << \"\\tTOOL FORCE UPDATE\" << endl;\n                break;\n            case MODE_FORCE_UPDATE:\n                ft.request.torque.push_back(0.0);\n                ft.request.torque.push_back(0.0);\n                ft.request.torque.push_back(0.0);\n                ft.request.force.push_back(req_xdir);\n                ft.request.force.push_back(req_ydir);\n                ft.request.force.push_back(req_zdir);\n                ft.request.kp.push_back(50.0);\n                ft.request.kp.push_back(50.0);\n                ft.request.kp.push_back(50.0);\n                ft.request.kd.push_back(5.0);\n                ft.request.kd.push_back(5.0);\n                ft.request.kd.push_back(5.0);\n                ft.request.initialize = false;\n                joy_force_torque_tool_srv.call(ft);\n                break;\n            case MODE_TORQUE_UPDATE:\n                ft.request.torque.push_back(req_ydir);\n                ft.request.torque.push_back(req_xdir);\n                ft.request.torque.push_back(req_zdir);\n                ft.request.force.push_back(0.0);\n                ft.request.force.push_back(0.0);\n                ft.request.force.push_back(0.0);\n                ft.request.kp.push_back(50.0);\n                ft.request.kp.push_back(50.0);\n                ft.request.kp.push_back(50.0);\n                ft.request.kd.push_back(5.0);\n                ft.request.kd.push_back(5.0);\n                ft.request.kd.push_back(5.0);\n                ft.request.initialize = false;\n                joy_force_torque_tool_srv.call(ft);              \n                break;\n            }\n        r.sleep();\n    }\n}\n\n// Function for updating the commands and publishing\nvoid WamTeleop::updateCommand() {\n    if (new_command) {\n        switch (button_pressed) {\n            case BUTTON_A:\n                grasp = !grasp;\n                if (grasp) {\n                    cout << \"\\t\\tcalling grasp open\" << endl;\n                    grasp_open_srv.call(empty);\n                } else {\n                    cout << \"\\t\\tcalling grasp close\" << endl;\n                    grasp_close_srv.call(empty);\n                }\n                break;\n            case BUTTON_B:\n                spread = !spread;\n                if (spread) {\n                    cout << \"\\t\\tcalling spread open\" << endl;\n                    spread_open_srv.call(empty);\n                } else {\n                    cout << \"\\t\\tcalling spread close\" << endl;\n                    spread_close_srv.call(empty);\n                }\n                break;\n            case BUTTON_X:\n                break; \n            case BUTTON_Y:\n                break;\n            case BUTTON_LB:\n                mode = (mode + 1) % 7;\n                switch (mode) {\n                    case MODE_DISCONNECT:\n                        // cout << \"MODE_DISCONNECT\" << endl;\n                        break;\n                    case MODE_FREE:\n                        cout << \"\\tFREE\" << endl;\n                        break;\n                    case MODE_BASE_CONNECT:\n                        // cout << \"MODE_BASE_CONNECT\" << endl;\n                        break;\n                    case MODE_BASE_UPDATE:\n                        cout << \"\\tBASE FORCE UPDATE\" << endl;\n                        break;      \n                    case MODE_TOOL_CONNECT:\n                        // cout << \"MODE_TOOL_CONNECT\" << endl;\n                        break;\n                    case MODE_FORCE_UPDATE:\n                        cout << \"\\tTOOL FORCE UPDATE\" << endl;\n                        break;\n                    case MODE_TORQUE_UPDATE:\n                        cout << \"\\tTOOL TORQUE UPDATE\" << endl;          \n                        break;\n                }\n                break;\n            case BUTTON_RB:\n                lock_joints = !lock_joints;\n                cout << \"\\t\\tjoints locked: \" << boolalpha << lock_joints << endl;\n                hold.request.hold = lock_joints;\n                hold_srv.call(hold); \n                break;            \n            case BUTTON_BACK:\n                disconnect_srv.call(empty);\n                mode = MODE_FREE;\n                cout << \"\\t\\tcalling go home\" << endl;\n                go_home_srv.call(empty); \n                lock_joints = true;\n                break;\n            case BUTTON_START:\n                cout << \"\\t\\tinitializing hand and setting velocities to 16\" << endl;\n                bhand_init_srv.call(empty);\n                spread_vel.request.velocity = 16;\n                spread_vel_srv.call(spread_vel);\n                grasp_vel.request.velocity = 16;\n                grasp_vel_srv.call(grasp_vel);\n                spread_close_srv.call(empty);\n                break;\n            case BUTTON_LEFT_STICK:\n                break;\n            case BUTTON_RIGHT_STICK:\n                break;\n        }\n        new_command = false;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"wam_teleop\"); // Start our wam_node and name it \"wam_teleop\"\n    // don't remove spinner lines or arm won't subscribe to wam topics\n    ros::AsyncSpinner spinner(0);\n    spinner.start();\n\n    WamTeleop wam_teleop; // Declare a member of WamTeleop \"wam_teleop\"\n    wam_teleop.init(); // Initialize our teleoperation\n    boost::thread feedback_thread(&WamTeleop::updateRT, &wam_teleop);\n\n    ros::Rate pub_rate(CNTRL_FREQ); // Setting the publishing rate to CNTRL_FREQ (50Hz by default)\n    // Looping at the specified frequency while our ros node is ok\n    cout << \"******************************************************************\" << endl;\n    cout << \"* WAM Teleoperation Node with the Logitech Controller            *\" << endl;\n    cout << \"******************************************************************\" << endl;\n    cout << \"* LB BUTTON:     Mode Switch                                     *\" << endl;\n    cout << \"* RB BUTTON:     Toggle Hold Joints                              *\" << endl;\n    cout << \"* START BUTTON:  Initialize Hand                                 *\" << endl;\n    cout << \"* BACK BUTTON:   Go Home                                         *\" << endl;\n    cout << \"* A BUTTON:      Toggle Grasp                                    *\" << endl;\n    cout << \"* B BUTTON:      Toggle Spread                                   *\" << endl;\n    cout << \"* LEFT STICK:    X & Y Axis Motion                               *\" << endl;\n    cout << \"* RIGHT STICK:   Z Axis Motion                                   *\" << endl;\n    cout << \"******************************************************************\" << endl;\n    cout << \"Current Mode:\" << endl;\n    while (wam_teleop.n_.ok()) {\n        ros::spinOnce();\n        wam_teleop.updateCommand();\n        pub_rate.sleep();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "7cc002d483f0a2168809d2f0d192f885a741c4fa", "size": 16492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wam_joystick_teleop.cpp", "max_stars_repo_name": "ualberta-robotics/wam_teleop", "max_stars_repo_head_hexsha": "d28b1c3c7ec4a5216cde477834791139ce9974a7", "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/wam_joystick_teleop.cpp", "max_issues_repo_name": "ualberta-robotics/wam_teleop", "max_issues_repo_head_hexsha": "d28b1c3c7ec4a5216cde477834791139ce9974a7", "max_issues_repo_licenses": ["MIT"], "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/wam_joystick_teleop.cpp", "max_forks_repo_name": "ualberta-robotics/wam_teleop", "max_forks_repo_head_hexsha": "d28b1c3c7ec4a5216cde477834791139ce9974a7", "max_forks_repo_licenses": ["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.6442307692, "max_line_length": 128, "alphanum_fraction": 0.5490540868, "num_tokens": 3970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16718222909697703}}
{"text": "//          Copyright Camille Gillot 2012 - 2015.\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 RTTI_MMETHOD_DECLARE_TRAITS_HPP\n#define RTTI_MMETHOD_DECLARE_TRAITS_HPP\n\n#include \"mmethod/config.hpp\"\n#include \"mmethod/traits/tags.hpp\"\n\n#include <boost/mpl/next.hpp>\n#include <boost/mpl/times.hpp>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/reverse_fold.hpp>\n\nnamespace rtti {\nnamespace mmethod {\nnamespace detail {\n\ntemplate<typename Ret, typename Policy, typename Args>\nstruct make_declare_traits\n{\n  typedef typename boost::mpl::transform<Args, tags::unwrap>::type unwrapped_args;\n  typedef typename boost::mpl::transform<Args, tags::is_virtual>::type type_tags;\n\n  BOOST_STATIC_CONSTANT(std::size_t, vsize = tags::virtual_size<Args>::value);\n  BOOST_STATIC_CONSTANT(std::size_t, type_bitset = (boost::mpl::reverse_fold<\n      type_tags,\n      boost::mpl::size_t<0>,\n      boost::mpl::if_<mpl_::_2\n      , boost::mpl::next<boost::mpl::times<mpl_::_1, boost::mpl::size_t<2> > >\n      , boost::mpl::times<mpl_::_1, boost::mpl::size_t<2> >\n      >\n    >::type::value\n  ));\n\n  typedef Policy policy;\n\n  BOOST_STATIC_ASSERT_MSG( (vsize > 0), \"At least one virtual parameter must be provided.\" );\n};\n\n} // namespace detail\n} // namespace mmethod\n} // namespace rtti\n\n#endif\n", "meta": {"hexsha": "0882ee08acb2f17459ef6f32846a629b847b9a06", "size": 1444, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmethod/declare/traits.hpp", "max_stars_repo_name": "cjgillot/rtti", "max_stars_repo_head_hexsha": "271c4429a4904afad858bf2464f3544314a6c69e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T21:34:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-04T15:11:02.000Z", "max_issues_repo_path": "include/mmethod/declare/traits.hpp", "max_issues_repo_name": "cjgillot/rtti", "max_issues_repo_head_hexsha": "271c4429a4904afad858bf2464f3544314a6c69e", "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/mmethod/declare/traits.hpp", "max_forks_repo_name": "cjgillot/rtti", "max_forks_repo_head_hexsha": "271c4429a4904afad858bf2464f3544314a6c69e", "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.4693877551, "max_line_length": 93, "alphanum_fraction": 0.7112188366, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16718222909697703}}
{"text": "/* Search within a matrix of neighbours for similar segments\n *\n * author: Bjoern Krueger (kruegerb@cs.uni-bonn.de)\n *\n * example (Matlab) call:\n * res = C_findPathsTrellisGlobalOptimization(ind,dist,max(ind(:)));\n */\n\n#include \"mex.h\"\n#include <float.h>\n#include <cmath>\n#include <limits>\n\n#include \"path.h\"\n// #include \"TrellisTree.h\"\n#include \"SimpleHashUnsafe.h\"\n\n/******* included for boost library *******/\n#include <boost/config.hpp>\n#include <iostream>\n#include <fstream>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nusing namespace boost;\n/******* included for boost library *******/\n\n#define getSub(i,j)   (iFrames*(j)+(i))\n#define vuiInd(i,j)   (*(puiInd + iNeigh*(j) + (i)))\n#define  vfDis(i,j)   (*( pfDis + iNeigh*(j) + (i)))\n\nclass BKNode{\n    public:\n    unsigned int\t frame;\n    unsigned int\t neighbour;\n    unsigned int     value;\n    double           distance;\n    std::vector<unsigned int> childs;\n\n    BKNode(unsigned int f,unsigned int n,unsigned int v, double d)\n    {\n        frame     = f;\n        neighbour = n;\n        value     = v;\n        distance  = d;\n    }\n    \n    ~BKNode(){}\n    \n    void addChild(int childNode){\n        childs.push_back(childNode);\n//         mexPrintf(\"\\naddChild: %i -> %i\\n\", value, childNode);\n    }\n    \n    void writeNode(){\n        mexPrintf(\"\\nNode: frame=%i neigh=%i value=%i dist=%f\", frame,neighbour,value,distance);\n    }\n};\n\n\n\n// Bin Seek search:\nint binsuch(unsigned int* feld,unsigned int l,unsigned int zusuchen )\n{\n//     mexPrintf(\"\\n\");\n//   for(int b=0;b<l;b++)  \n//       mexPrintf(\" %i\",feld[b]);\n    \n  if( l<1 )\n  {\n    // leeres Feld? Nichts gefunden!\n//        mexPrintf(\"leer\");\n    return -1000000000;\n  }\n  else if( l==1 )\n  {\n    // nur ein Element; vergleichen und ggf. zur\u00fcckgeben:\n//      mexPrintf(\"eins\");\n    return ( feld[0]==zusuchen ? 0 : -100000000 );\n  }\n  else\n  {\n    // Mehr als ein Element\n    // Mitte suchen, und ggf. links oder rechts suchen:\n    int index_Mitte = l/2;\n    if( feld[index_Mitte]==zusuchen )\n    {\n      // Zuf\u00e4llig getroffen!\n      return index_Mitte;\n    }\n    else if( feld[index_Mitte]>zusuchen )\n    {\n//          mexPrintf(\" >%i \",index_Mitte);\n//          mexPrintf(\"\\n l=%i\",l);\n      // Mitte ist zu gro\u00df, also links weitersuchen\n      return binsuch( feld, index_Mitte, zusuchen );\n    }\n    else\n    {\n      // Mitte zu klein, also in rechter H\u00e4lfte suchen:\n//         mexPrintf(\" <%i \",index_Mitte);\n//         mexPrintf(\"\\n l=%i\",l);\n      return binsuch( &feld[index_Mitte+1], l - index_Mitte - 1, zusuchen )+index_Mitte+1;\n    }\n  }\n\n} // int *binsuch( int feld[], size_t l, int zusuchen )\n\n\n/* Path finding algorithm */\nvoid getPaths(mxArray* pInd, mxArray* pDis, mxArray* pPaths, int iNeigh, int iFrames, int iDBSize, mxArray* pathDists){\n\n    // Some usefull variables\n    double        dLengthFac = 0.75;\n    unsigned int  uiGap      = 2;\n    int           iNumPaths  = 0;\n    int           iTreeCount = 1;\n    \n    // Frame list: stores where a frame occurs\n//     int          *pFrameList = new int[iDBSize];\n\n    unsigned int* puiInd     = (unsigned int*)mxGetPr(pInd);\n    double*       pfDis      = (double*)      mxGetPr(pDis);\n    double*       pfPathDist = (double*)      mxGetPr(pathDists);\n    \n    // Lookup table: Which neighbours correspond to which node?\n    unsigned int* lookup=new unsigned int[iNeigh*iFrames];\n\n    for(int j =0;j<iFrames;j++)\n        for(int i=0;i<iNeigh;i++)\n            lookup[j*iNeigh + i]=100000000;\n    \n    typedef adjacency_list < listS, vecS, directedS, no_property, property < edge_weight_t, int > > graph_t;\n    typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\n    typedef graph_traits < graph_t >::edge_descriptor edge_descriptor;\n    typedef std::pair<int, int> Edge;\n    \n   \n    // Find out number of nodes and create them.\n    int numNodes=0;\n    int numEdges=0;\n    \n    std::vector<BKNode> Nodes;\n    \n    mexPrintf(\"\\nInit done.\\n\");\n\n\n    \n    for(int j=0;j<iFrames;j++){\n         //mexPrintf(\"Neigh=%i\",j);\n        for(int i=0;i<iNeigh;i++){\n             //mexPrintf(\"Frame=%i\",i);\n            if(vuiInd(i,j)!=0){\n                numNodes++;\n                BKNode newNode(j,i,vuiInd(i,j),vfDis(i,j));\n                Nodes.push_back(newNode);\n                \n                lookup[j*iNeigh + i]=Nodes.size()-1;\n                //mexPrintf(\"%i \",numNodes);\n            }\n        }\n    }\n    /*\n\t mexPrintf(\"\\nDebug Lookup:\\n\");\n     for(int i=0;i<iNeigh;i++){\n         mexPrintf(\"\\n\");\n         for(int j=0;j<iFrames;j++)\n             mexPrintf(\" %i\",lookup[j*iNeigh + i]);\n     }*/\n    \n    mexPrintf(\"\\nNodes built!\");\n//     mexPrintf(\"\\nSearch Edges:\");\n    \n    for(int curNode=0;curNode<Nodes.size();curNode++){\n         //mexPrintf(\"\\nNode %i: Frame = %i, Neigh = %i, Value = %i\",curNode,Nodes[curNode].frame,Nodes[curNode].neighbour,Nodes[curNode].value);\n        int position = -1;\n        \n      /*  mexPrintf(\"\\n\");\n        for(int i=0;i<iNeigh;i++)\n            mexPrintf(\" %i \",*(puiInd + iNeigh*(Nodes[curNode].frame+1) + i));\n      */  \n        \n        position = binsuch(puiInd + iNeigh*(Nodes[curNode].frame+1),iNeigh,Nodes[curNode].value+1);\n        if(position>-1){\n            if(lookup[position+iNeigh*(Nodes[curNode].frame+1)]!=100000000){\n                Nodes[curNode].addChild(lookup[position+iNeigh*(Nodes[curNode].frame+1)]);\n                numEdges++;\n                //mexPrintf(\"\\n   \\\\ %i %i Value=%i Node=%i\",position,Nodes[curNode].frame+1,Nodes[curNode].value+1,lookup[position+iNeigh*(Nodes[curNode].frame+1)]);\n            }\n        }\n\n        // Vert\n        position = -1;\n        position = binsuch(puiInd + iNeigh*(Nodes[curNode].frame+1),iNeigh,Nodes[curNode].value);\n        if(position>-1){\n            if(lookup[position+iNeigh*(Nodes[curNode].frame+1)]!=100000000){\n                Nodes[curNode].addChild(lookup[position+iNeigh*(Nodes[curNode].frame+1)]);\n                numEdges++;\n                 //mexPrintf(\"\\n   - %i %i Value=%i Node=%i\",position,Nodes[curNode].frame+1,Nodes[curNode].value,lookup[position+iNeigh*(Nodes[curNode].frame+1)]);\n            }\n        }\n        // Horz\n        position = -1;\n        position = binsuch(puiInd + iNeigh*(Nodes[curNode].frame),iNeigh,Nodes[curNode].value+1);\n        if(position>-1){\n            if(lookup[position+iNeigh*Nodes[curNode].frame]!=100000000){\n                Nodes[curNode].addChild(lookup[position+iNeigh*Nodes[curNode].frame]);\n                numEdges++;\n                 //mexPrintf(\"\\n   | %i %i Value=%i Node=%i\",position,Nodes[curNode].frame,Nodes[curNode].value+1,lookup[position+iNeigh*Nodes[curNode].frame]);\n            }\n        }\n    }\n    /*\n    mexPrintf(\"\\nNeighbours found!\");\n    */\n    mexPrintf(\"\\nnumEdges = %i\\n\",numEdges);\n    \n    Edge*   edge_array=new Edge[numEdges+iNeigh];//\n//     double     weights[numEdges+iNeigh];\n    int*       weights=new int[numEdges+iNeigh];\n    \n    int curEdge=0;\n    \n    for(int node=0;node<Nodes.size();node++){\n        \n//          mexPrintf(\".\");\n        \n        for(int edge=0;edge<Nodes[node].childs.size();edge++){\n             //mexPrintf(\"\\n Edge = %i\", curEdge);\n            edge_array[curEdge] = Edge(node,Nodes[node].childs[edge]);\n//             mexPrintf(\" : %i --> %i\",      node       ,      Nodes[node].childs[edge]       );\n//             mexPrintf(\" : %i,%i --> %i,%i = %i\",Nodes[node].value,Nodes[node].frame,Nodes[Nodes[node].childs[edge]].value, Nodes[Nodes[node].childs[edge]].frame,(int) (Nodes[Nodes[node].childs[edge]].distance*1000+Nodes[node].distance*1000));\n//             mexPrintf(\"\\nDist Check: Node.dist=%f Node->child.dist=%f\",Nodes[node].distance,Nodes[Nodes[node].childs[edge]].distance);\n            weights   [curEdge] = (int) (Nodes[node].distance*1000);\n            curEdge++;\n        }\n        if(Nodes[node].frame==iFrames-1){\n             //mexPrintf(\"\\n Edge = %i\", curEdge);\n            edge_array[curEdge] = Edge(node,numNodes);\n             //mexPrintf(\" : %i --> TARGET\",Nodes[node].value);\n            weights   [curEdge] = (int) 0;//(Nodes[node].distance*1000);\n            curEdge++;\n        }\n    }\n//     mexPrintf(\"\\nEdege Array constructed\");\n//     for(int ew=0;ew<curEdge;ew++) mexPrintf(\"\\nw(%i)=%i\",ew,weights[ew]);\n    \n//     mexPrintf(\"\\nNumNodes = %i\\n\",numNodes);\n    \n//     mexPrintf(\"\\n\\nNumNodes = %i\\n\",numNodes);\n    \n    \n     mexPrintf(\"Edges built\\n\");\n    // Create edges\n//     Edge edge_array[] = {Edge(1,2),Edge(2,3),Edge(3,4),Edge(1,5),Edge(3,6),Edge(6,4),Edge(4,9)};\n    //int weih[] = { 1, 2, 1, 2, 7, 3, 1, 1, 2, 1, 2, 7, 3, 1};\n    int num_arcs = curEdge;//sizeof(edge_array) / sizeof(Edge);\n    \n    graph_t g(edge_array, edge_array + num_arcs, weights, numNodes+1);\n    property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n    \n    \n// //     graph_t g(numNodes+1);\n// //     property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n// //     for (std::size_t j = 0; j < num_arcs; ++j) {\n// //         edge_descriptor e; \n// //         bool inserted;\n// //         \n// //         mexPrintf(\"\\nedge_array.first=%i edge_array.second%i\",edge_array[j].first,edge_array[j].second);\n// //         \n// //         tie(e, inserted) = add_edge(edge_array[j].first, edge_array[j].second, g);\n// //         weightmap[e] = weights[j];\n// //     }\n\n    std::vector<vertex_descriptor>  p(num_vertices(g));\n    std::vector<int>                d(num_vertices(g));\n    \n// \tmexPrintf(\"size(d) = %i\\n\",d.size());\n\n    for(int startNode=0;startNode<iNeigh;startNode++){\n    \n//         mexPrintf(\".\");\n\n        vertex_descriptor s = vertex(startNode, g);\n\n        dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));\n\n\n        \n\n//          mexPrintf(\"distances and parents:\\n\");\n        graph_traits < graph_t >::vertex_iterator vi, vend;\n        int* parents=new int[numNodes+1];\n        int* dists  =new int[numNodes+1];\n        \n        for (tie(vi, vend) = vertices(g); vi != vend; ++vi) {\n//              mexPrintf(\"distance(%i) = %i Parent = %i \\n\",*vi,d[*vi],p[*vi]);\n            parents[*vi]=p[*vi];\n              dists[*vi]=d[*vi];\n        }\n\n        int depth=1;\n        int curNode=numNodes;\n        \n        *pfPathDist =(double) dists[curNode];\n         pfPathDist++;\n        \n        while(parents[curNode]!=startNode && parents[curNode] < numNodes && parents[curNode] > 0){\n            depth++;\n            curNode=parents[curNode];\n        }\n\n//          mexPrintf(\"PathDepth = %i\",depth);\n\n        mwSize dims[2];\n        dims[0] = (mwSize)2;\n        dims[1] = (mwSize)depth;\n\n        mxArray *pSteps=mxCreateNumericArray(2,(const mwSize*)&dims,mxUINT32_CLASS,mxREAL);\n        unsigned int* puiSteps=(unsigned int*)mxGetPr(pSteps);  \n\n        curNode=parents[numNodes];\n        while(parents[curNode]!=startNode && parents[curNode] < numNodes && parents[curNode] > 0){\n\n            *puiSteps = Nodes[curNode].frame+1; puiSteps++;\n            *puiSteps = Nodes[curNode].value;   puiSteps++;\n\n            curNode=parents[curNode];\n        }\n\n\t\t\n\n        *puiSteps = Nodes[curNode].frame+1; puiSteps++;\n        *puiSteps = Nodes[curNode].value;   puiSteps++;\n        curNode=parents[curNode];\n//          mexPrintf(\"\\nPING\\n\");\n        *puiSteps = Nodes[curNode].frame+1; puiSteps++;\n        *puiSteps = Nodes[curNode].value;   puiSteps++;\n        curNode=parents[curNode];\n\n//         mexPrintf(\"C\");\n        \n        mxSetCell(pPaths, (mwIndex)getSub(startNode,0), pSteps);\n        \n        delete parents;\n        delete dists  ;\n// \t\tmexPrintf(\"D\");\n    }\n    mexPrintf(\"Search Done\");\n\n\tdelete lookup;\n\tdelete edge_array;\n\tdelete weights;\n    \n\n//     mexPrintf(\"\\nDone!\");\n}\n\n/* The gateway routine */\nvoid mexFunction(int nlhs, mxArray *plhs[],\n                 int nrhs, const mxArray *prhs[])\n{\n    \n    double    *pDis;\n\n    int   \t  *pInd,\n              *pDBSize;\n\n    unsigned int iNeigh,\n                 iFrames;\n\n    /*  Check for proper number of arguments. */\n    if (nrhs != 3) \n    mexErrMsgTxt(\"Three inputs required.\");\n\n    if (nlhs != 2) \n    mexErrMsgTxt(\"Two outputs required.\");\n\n    /* Get Pointers to input arguments */\n    pInd     = (int*)    mxGetPr(prhs[0]);\n    pDis     = (double*) mxGetPr(prhs[1]);\n    pDBSize  = (int*)    mxGetPr(prhs[2]);\n\n    /* Get the dimensions of the input array. */\n    iNeigh   = mxGetM(prhs[0]);\n    iFrames  = mxGetN(prhs[0]);\n\n    /* Create output cell array */\n    mwSize pDims[2];\n    pDims[0] = (mwSize)1;\n    pDims[1] = (mwSize)iNeigh; // max Number of possible paths\n\n    plhs[0]  = mxCreateCellArray(2, (const mwSize*)pDims);\n    plhs[1]  = mxCreateDoubleMatrix(1, iNeigh, mxREAL);\n\n    /* Call Path finding algorithm */\n    getPaths((mxArray*)prhs[0], (mxArray*)prhs[1], plhs[0], iNeigh, iFrames, *pDBSize, plhs[1]);\n\n}", "meta": {"hexsha": "5bce7b0414723e40f80f02f69bd05cf0596ad515", "size": 12912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools_intern/efficiency/efficiency_linux64/C_findPathsTrellisGlobalOptimization.cpp", "max_stars_repo_name": "umariqb/3D_Pose_Estimation_CVPR2016", "max_stars_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-07-25T00:48:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T09:19:03.000Z", "max_issues_repo_path": "tools_intern/efficiency/efficiency_linux64/C_findPathsTrellisGlobalOptimization.cpp", "max_issues_repo_name": "umariqb/3D_Pose_Estimation_CVPR2016", "max_issues_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-09-17T19:40:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-07T06:49:02.000Z", "max_forks_repo_path": "tools_intern/efficiency/efficiency_linux64/C_findPathsTrellisGlobalOptimization.cpp", "max_forks_repo_name": "iqbalu/3D_Pose_Estimation_CVPR2016", "max_forks_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2016-07-21T09:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-13T14:11:37.000Z", "avg_line_length": 32.1995012469, "max_line_length": 245, "alphanum_fraction": 0.561105948, "num_tokens": 3678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.16718222763715035}}
{"text": "// Copyright (c) 2017 Andreas Geiger, Philip Lenz, Raquel Urtasun\n// Copyright (c) 2020-2021 Arm Limited\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// This is a modified version of the Kitti \"object development kit\"\n// available from http://www.cvlibs.net/datasets/kitti/eval_object.php\n\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\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/adapted/c_array.hpp>\n#include <common/filesystem.hpp>\n#include <common/types.hpp>\n\n#include <cstdio>\n#include <cmath>\n#include <cstring>\n#include <cassert>\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <numeric>\n#include <string>\n#include <functional>\n\n#include \"kittiobjevalmodule.hpp\"\n\n#ifdef BOOST_GEOMETRY_REGISTER_C_ARRAY_CS\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\n#endif\n\nusing autoware::common::types::bool8_t;\nusing autoware::common::types::char8_t;\nusing autoware::common::types::float64_t;\nusing std::size_t;\n\ntypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<float64_t>> Polygon;\n\n/*=======================================================================\nSTATIC EVALUATION PARAMETERS\n=======================================================================*/\n\n// easy, moderate and hard evaluation level\nenum class DIFFICULTY {EASY = 0, MODERATE = 1, HARD = 2};\n\n// evaluation metrics: image, ground or 3D\nenum class METRIC {IMAGE = 0, GROUND = 1, BOX3D = 2};\n\n// evaluation parameter\n// minimum height for evaluated groundtruth/detections\nconstexpr int32_t MIN_HEIGHT[3] = {40, 25, 25};\n// maximum occlusion level of the groundtruth used for evaluation\nconstexpr int32_t MAX_OCCLUSION[3] = {0, 1, 2};\n// maximum truncation level of the groundtruth used for evaluation\nconstexpr float64_t MAX_TRUNCATION[3] = {0.15, 0.3, 0.5};\n\n// evaluated object classes\nenum class CLASSES {CAR = 0, PEDESTRIAN = 1, CYCLIST = 2};\nconstexpr int NUM_CLASS = 3;\n\n// parameters varying per class\nstd::vector<std::basic_string<char8_t>> CLASS_NAMES;\nstd::vector<std::basic_string<char8_t>> CLASS_NAMES_CAP;\n// the minimum overlap required for 2D evaluation on the image/ground plane and 3D evaluation\nconstexpr float64_t MIN_OVERLAP[3][3] = {{0.7, 0.5, 0.5}, {0.7, 0.5, 0.5}, {0.7, 0.5, 0.5}};\n\n// no. of recall steps that should be evaluated (discretized)\nconstexpr float64_t N_SAMPLE_PTS = 41;\n\n// initialize class names\nvoid initGlobals()\n{\n  CLASS_NAMES.push_back(\"car\");\n  CLASS_NAMES.push_back(\"pedestrian\");\n  CLASS_NAMES.push_back(\"cyclist\");\n  CLASS_NAMES_CAP.push_back(\"Car\");\n  CLASS_NAMES_CAP.push_back(\"Pedestrian\");\n  CLASS_NAMES_CAP.push_back(\"Cyclist\");\n}\n\n/*=======================================================================\nDATA TYPES FOR EVALUATION\n=======================================================================*/\n\n// holding data needed for precision-recall and precision-aos\nstruct tPrData\n{\n  std::vector<float64_t> v;           // detection score for computing score thresholds\n  float64_t similarity;          // orientation similarity\n  int32_t tp;                 // true positives\n  int32_t fp;                 // false positives\n  int32_t fn;                 // false negatives\n  tPrData()\n  : similarity(0), tp(0), fp(0), fn(0) {}\n};\n\n// holding bounding boxes for ground truth and detections\nstruct tBox\n{\n  std::basic_string<char8_t> type;      // object type as car, pedestrian or cyclist,...\n  float64_t x1;        // left corner\n  float64_t y1;        // top corner\n  float64_t x2;        // right corner\n  float64_t y2;        // bottom corner\n  float64_t alpha;     // image orientation\n  tBox(\n    std::basic_string<char8_t> type, float64_t x1, float64_t y1, float64_t x2, float64_t y2,\n    float64_t alpha)\n  : type(type), x1(x1), y1(y1), x2(x2), y2(y2), alpha(alpha) {}\n};\n\n// holding ground truth data\nstruct tGroundtruth\n{\n  tBox box;           // object type, box, orientation\n  float64_t truncation;  // truncation 0..1\n  int32_t occlusion;  // occlusion 0,1,2 (non, partly, fully)\n  float64_t ry;\n  float64_t t1, t2, t3;\n  float64_t h, w, l;\n  tGroundtruth()\n  : box(tBox(\"invalild\", -1, -1, -1, -1, -10)), truncation(-1), occlusion(-1) {}\n  tGroundtruth(tBox box, float64_t truncation, int32_t occlusion)\n  : box(box), truncation(truncation), occlusion(occlusion) {}\n  tGroundtruth(\n    std::basic_string<char8_t> type, float64_t x1, float64_t y1, float64_t x2,\n    float64_t y2, float64_t alpha, float64_t truncation, int32_t occlusion)\n  : box(tBox(type, x1, y1, x2, y2, alpha)), truncation(truncation), occlusion(occlusion) {}\n};\n\n// holding detection data\nstruct tDetection\n{\n  tBox box;       // object type, box, orientation\n  float64_t thresh;  // detection score\n  float64_t ry;\n  float64_t t1, t2, t3;\n  float64_t h, w, l;\n  tDetection()\n  : box(tBox(\"invalid\", -1, -1, -1, -1, -10)), thresh(-1000) {}\n  tDetection(tBox box, float64_t thresh)\n  : box(box), thresh(thresh) {}\n  tDetection(\n    std::basic_string<char8_t> type, float64_t x1, float64_t y1, float64_t x2,\n    float64_t y2, float64_t alpha, float64_t thresh)\n  : box(tBox(type, x1, y1, x2, y2, alpha)), thresh(thresh) {}\n};\n\n\n/*=======================================================================\nFUNCTIONS TO LOAD DETECTION AND GROUND TRUTH DATA ONCE, SAVE RESULTS\n=======================================================================*/\nstd::vector<tDetection> loadDetections(\n  std::basic_string<char8_t> file_name, bool8_t & compute_aos,\n  std::vector<bool8_t> & eval_image, std::vector<bool8_t> & eval_ground,\n  std::vector<bool8_t> & eval_3d, bool8_t & success)\n{\n  // holds all detections (ignored detections are indicated by an index vector\n  std::vector<tDetection> detections;\n  FILE * fp = fopen(file_name.c_str(), \"r\");\n  if (!fp) {\n    success = false;\n    return detections;\n  }\n  while (!feof(fp)) {\n    tDetection d;\n    float64_t trash;\n    char8_t str[255];\n    if (fscanf(\n        fp, \"%s %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n        str, &trash, &trash, &d.box.alpha, &d.box.x1, &d.box.y1,\n        &d.box.x2, &d.box.y2, &d.h, &d.w, &d.l, &d.t1, &d.t2, &d.t3,\n        &d.ry, &d.thresh) == 16)\n    {\n      d.box.type = str;\n      detections.push_back(d);\n\n      // orientation=-10 is invalid, AOS is not evaluated if at least one orientation is invalid\n      if (d.box.alpha == -10) {\n        compute_aos = false;\n      }\n\n      // a class is only evaluated if it is detected at least once\n      for (size_t c = 0; c < NUM_CLASS; c++) {\n        if (!strcasecmp(\n            d.box.type.c_str(),\n            CLASS_NAMES[c].c_str()) || !strcasecmp(d.box.type.c_str(), CLASS_NAMES_CAP[c].c_str()))\n        {\n          if (!eval_image[c] && d.box.x1 >= 0) {\n            eval_image[c] = true;\n          }\n          if (!eval_ground[c] && d.t1 != -1000 && d.t3 != -1000 && d.w > 0 && d.l > 0) {\n            eval_ground[c] = true;\n          }\n          if (!eval_3d[c] && d.t1 != -1000 && d.t2 != -1000 && d.t3 != -1000 && d.h > 0 &&\n            d.w > 0 && d.l > 0)\n          {\n            eval_3d[c] = true;\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  fclose(fp);\n  success = true;\n  return detections;\n}\n\nstd::vector<tGroundtruth> loadGroundtruth(std::basic_string<char8_t> file_name, bool8_t & success)\n{\n  // holds all ground truth (ignored ground truth is indicated by an index vector\n  std::vector<tGroundtruth> groundtruth;\n  FILE * fp = fopen(file_name.c_str(), \"r\");\n  if (!fp) {\n    success = false;\n    return groundtruth;\n  }\n  while (!feof(fp)) {\n    tGroundtruth g;\n    char8_t str[255];\n    if (fscanf(\n        fp, \"%s %lf %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n        str, &g.truncation, &g.occlusion, &g.box.alpha,\n        &g.box.x1, &g.box.y1, &g.box.x2, &g.box.y2,\n        &g.h, &g.w, &g.l, &g.t1,\n        &g.t2, &g.t3, &g.ry) == 15)\n    {\n      g.box.type = str;\n      groundtruth.push_back(g);\n    }\n  }\n  fclose(fp);\n  success = true;\n  return groundtruth;\n}\n\nvoid saveStats(\n  const std::vector<float64_t> & precision, const std::vector<float64_t> & aos, FILE * fp_det,\n  FILE * fp_ori)\n{\n  // save precision to file\n  if (precision.empty()) {\n    return;\n  }\n  for (uint32_t i = 0; i < precision.size(); i++) {\n    fprintf(fp_det, \"%f \", precision[i]);\n  }\n  fprintf(fp_det, \"\\n\");\n\n  // save orientation similarity, only if there were no invalid orientation entries in submission\n  // (alpha=-10)\n  if (aos.empty()) {\n    return;\n  }\n  for (uint32_t i = 0; i < aos.size(); i++) {\n    fprintf(fp_ori, \"%f \", aos[i]);\n  }\n  fprintf(fp_ori, \"\\n\");\n}\n\n/*=======================================================================\nEVALUATION HELPER FUNCTIONS\n=======================================================================*/\n\n// criterion defines whether the overlap is computed with respect to both areas (ground truth and\n// detection) or with respect to box a or b (detection and \"dontcare\" areas)\ninline float64_t imageBoxOverlap(tBox a, tBox b, int32_t criterion = -1)\n{\n  // overlap is invalid in the beginning\n  float64_t o = -1;\n\n  // get overlapping area\n  float64_t x1 = std::max(a.x1, b.x1);\n  float64_t y1 = std::max(a.y1, b.y1);\n  float64_t x2 = std::min(a.x2, b.x2);\n  float64_t y2 = std::min(a.y2, b.y2);\n\n  // compute width and height of overlapping area\n  float64_t w = x2 - x1;\n  float64_t h = y2 - y1;\n\n  // set invalid entries to 0 overlap\n  if (w <= 0 || h <= 0) {\n    return 0;\n  }\n\n  // get overlapping areas\n  float64_t inter = w * h;\n  float64_t a_area = (a.x2 - a.x1) * (a.y2 - a.y1);\n  float64_t b_area = (b.x2 - b.x1) * (b.y2 - b.y1);\n\n  // intersection over union overlap depending on users choice\n  if (criterion == -1) {   // union\n    o = inter / (a_area + b_area - inter);\n  } else if (criterion == 0) {  // bbox_a\n    o = inter / a_area;\n  } else if (criterion == 1) {  // bbox_b\n    o = inter / b_area;\n  }\n\n  // overlap\n  return o;\n}\n\ninline float64_t imageBoxOverlap(tDetection a, tGroundtruth b, int32_t criterion = -1)\n{\n  return imageBoxOverlap(a.box, b.box, criterion);\n}\n\n// compute polygon of an oriented bounding box\ntemplate<typename T>\nPolygon toPolygon(const T & g)\n{\n  boost::numeric::ublas::matrix<float64_t> mref(2, 2);\n  mref(0, 0) = cos(g.ry); mref(0, 1) = sin(g.ry);\n  mref(1, 0) = -sin(g.ry); mref(1, 1) = cos(g.ry);\n\n  boost::numeric::ublas::matrix<float64_t> corners(2, 4);\n  float64_t data[] = {g.l / 2, g.l / 2, -g.l / 2, -g.l / 2,\n    g.w / 2, -g.w / 2, -g.w / 2, g.w / 2};\n  std::copy(data, data + 8, corners.data().begin());\n  boost::numeric::ublas::matrix<float64_t> gc = prod(mref, corners);\n  for (size_t i = 0; i < 4; ++i) {\n    gc(0, i) += g.t1;\n    gc(1, i) += g.t3;\n  }\n\n  float64_t points[][2] =\n  {{gc(0, 0), gc(1, 0)}, {gc(0, 1), gc(1, 1)}, {gc(0, 2), gc(1, 2)}, {gc(0, 3), gc(1, 3)}, {gc(\n        0,\n        0),\n      gc(1, 0)}};\n  Polygon poly;\n  boost::geometry::append(poly, points);\n  return poly;\n}\n\n// measure overlap between bird's eye view bounding boxes, parametrized by (ry, l, w, tx, tz)\ninline float64_t groundBoxOverlap(tDetection d, tGroundtruth g, int32_t criterion = -1)\n{\n  Polygon gp = toPolygon(g);\n  Polygon dp = toPolygon(d);\n\n  std::vector<Polygon> in, un;\n  boost::geometry::intersection(gp, dp, in);\n  boost::geometry::union_(gp, dp, un);\n\n  float64_t inter_area = in.empty() ? 0 : boost::geometry::area(in.front());\n  float64_t union_area = boost::geometry::area(un.front());\n  float64_t o = 0;\n  if (criterion == -1) {  // union\n    o = inter_area / union_area;\n  } else if (criterion == 0) {  // bbox_a\n    o = inter_area / boost::geometry::area(dp);\n  } else if (criterion == 1) {  // bbox_b\n    o = inter_area / boost::geometry::area(gp);\n  }\n\n  return o;\n}\n\n// measure overlap between 3D bounding boxes, parametrized by (ry, h, w, l, tx, ty, tz)\ninline float64_t box3DOverlap(tDetection d, tGroundtruth g, int32_t criterion = -1)\n{\n  Polygon gp = toPolygon(g);\n  Polygon dp = toPolygon(d);\n\n  std::vector<Polygon> in, un;\n  boost::geometry::intersection(gp, dp, in);\n  boost::geometry::union_(gp, dp, un);\n\n  float64_t ymax = std::min(d.t2, g.t2);\n  float64_t ymin = std::max(d.t2 - d.h, g.t2 - g.h);\n\n  float64_t inter_area = in.empty() ? 0 : boost::geometry::area(in.front());\n  float64_t inter_vol = inter_area * std::max(0.0, ymax - ymin);\n\n  float64_t det_vol = d.h * d.l * d.w;\n  float64_t gt_vol = g.h * g.l * g.w;\n\n  float64_t o = 0;\n  if (criterion == -1) {  // union\n    o = inter_vol / (det_vol + gt_vol - inter_vol);\n  } else if (criterion == 0) {  // bbox_a\n    o = inter_vol / det_vol;\n  } else if (criterion == 1) {  // bbox_b\n    o = inter_vol / gt_vol;\n  }\n\n  return o;\n}\n\nstd::vector<float64_t> getThresholds(std::vector<float64_t> & v, float64_t n_groundtruth)\n{\n  // holds scores needed to compute N_SAMPLE_PTS recall values\n  std::vector<float64_t> t;\n\n  // sort scores in descending order\n  // (highest score is assumed to give best/most confident detections)\n  sort(v.begin(), v.end(), std::greater<float64_t>());\n\n  // get scores for linearly spaced recall\n  float64_t current_recall = 0;\n  for (uint32_t i = 0; i < v.size(); i++) {\n    // check if right-hand-side recall with respect to current recall is close than left-hand-side\n    // one. In this case, skip the current detection score\n    float64_t l_recall, r_recall /*, recall*/;\n    l_recall = static_cast<float64_t>(i + 1) / n_groundtruth;\n    if (i < (v.size() - 1)) {\n      r_recall = static_cast<float64_t>(i + 2) / n_groundtruth;\n    } else {\n      r_recall = l_recall;\n    }\n\n    if ( (r_recall - current_recall) < (current_recall - l_recall) && i < (v.size() - 1)) {\n      continue;\n    }\n\n    // left recall is the best approximation, so use this and goto next recall step for\n    // approximation recall = l_recall;\n\n    // the next recall step was reached\n    t.push_back(v[i]);\n    current_recall += 1.0 / (N_SAMPLE_PTS - 1.0);\n  }\n  return t;\n}\n\nvoid cleanData(\n  CLASSES current_class, const std::vector<tGroundtruth> & gt,\n  const std::vector<tDetection> & det, std::vector<int32_t> & ignored_gt,\n  std::vector<tGroundtruth> & dc, std::vector<int32_t> & ignored_det, int32_t & n_gt,\n  DIFFICULTY difficulty)\n{\n  // extract ground truth bounding boxes for current evaluation class\n  for (uint32_t i = 0; i < gt.size(); i++) {\n    // only bounding boxes with a minimum height are used for evaluation\n    float64_t height = gt[i].box.y2 - gt[i].box.y1;\n\n    // neighboring classes are ignored (\"van\" for \"car\" and \"person_sitting\" for \"pedestrian\")\n    // (lower/upper cases are ignored)\n    int32_t valid_class;\n    const char8_t * class_name = CLASS_NAMES[static_cast<size_t>(current_class)].c_str();\n    const char8_t * box_type = gt[i].box.type.c_str();\n\n    // all classes without a neighboring class\n    if (!strcasecmp(box_type, class_name)) {\n      valid_class = 1;\n    } else if (!strcasecmp(class_name, \"Pedestrian\") && !strcasecmp(\"Person_sitting\", box_type)) {\n      // classes with a neighboring class\n      valid_class = 0;\n    } else if (!strcasecmp(class_name, \"Car\") && !strcasecmp(\"Van\", box_type)) {\n      valid_class = 0;\n    } else {\n      // classes not used for evaluation\n      valid_class = -1;\n    }\n\n    // ground truth is ignored, if occlusion, truncation exceeds the difficulty or ground truth is\n    // too small (doesn't count as FN nor TP, although detections may be assigned)\n    bool8_t ignore = false;\n    if (gt[i].occlusion > MAX_OCCLUSION[static_cast<size_t>(difficulty)] ||\n      gt[i].truncation > MAX_TRUNCATION[static_cast<size_t>(difficulty)] ||\n      height <= MIN_HEIGHT[static_cast<size_t>(difficulty)])\n    {\n      ignore = true;\n    }\n\n    // set ignored vector for ground truth\n    // current class and not ignored (total no. of ground truth is detected for recall denominator)\n    if (valid_class == 1 && !ignore) {\n      ignored_gt.push_back(0);\n      n_gt++;\n    } else if (valid_class == 0 || (ignore && valid_class == 1)) {\n      // neighboring class, or current class but ignored\n      ignored_gt.push_back(1);\n    } else {\n      // all other classes which are FN in the evaluation\n      ignored_gt.push_back(-1);\n    }\n  }\n\n  // extract dontcare areas\n  for (uint32_t i = 0; i < gt.size(); i++) {\n    if (!strcasecmp(\"DontCare\", gt[i].box.type.c_str())) {\n      dc.push_back(gt[i]);\n    }\n  }\n\n  // extract detections bounding boxes of the current class\n  for (uint32_t i = 0; i < det.size(); i++) {\n    // neighboring classes are not evaluated\n    int32_t valid_class;\n    if (!strcasecmp(\n        det[i].box.type.c_str(),\n        CLASS_NAMES[static_cast<size_t>(current_class)].c_str()))\n    {\n      valid_class = 1;\n    } else {\n      valid_class = -1;\n    }\n\n    auto height = fabs(det[i].box.y1 - det[i].box.y2);\n\n    // set ignored vector for detections\n    if (height < MIN_HEIGHT[static_cast<size_t>(difficulty)]) {\n      ignored_det.push_back(1);\n    } else if (valid_class == 1) {\n      ignored_det.push_back(0);\n    } else {\n      ignored_det.push_back(-1);\n    }\n  }\n}\n\ntPrData computeStatistics(\n  CLASSES current_class, const std::vector<tGroundtruth> & gt,\n  const std::vector<tDetection> & det, const std::vector<tGroundtruth> & dc,\n  const std::vector<int32_t> & ignored_gt, const std::vector<int32_t> & ignored_det,\n  bool8_t compute_fp, float64_t (* boxoverlap)(tDetection, tGroundtruth, int32_t),\n  METRIC metric, bool8_t compute_aos = false, float64_t thresh = 0)\n{\n  tPrData stat = tPrData();\n  const float64_t NO_DETECTION = -10000000;\n  // holds angular difference for TPs (needed for AOS evaluation)\n  std::vector<float64_t> delta;\n  // holds wether a detection was assigned to a valid or ignored ground truth\n  std::vector<bool8_t> assigned_detection;\n  assigned_detection.assign(det.size(), false);\n  std::vector<bool8_t> ignored_threshold;\n  // holds detections with a threshold lower than thresh if FP are computed\n  ignored_threshold.assign(det.size(), false);\n\n  // detections with a low score are ignored for computing precision (needs FP)\n  if (compute_fp) {\n    for (uint32_t i = 0; i < det.size(); i++) {\n      if (det[i].thresh < thresh) {\n        ignored_threshold[i] = true;\n      }\n    }\n  }\n\n  // evaluate all ground truth boxes\n  for (uint32_t i = 0; i < gt.size(); i++) {\n    // this ground truth is not of the current or a neighboring class and therefore ignored\n    if (ignored_gt[i] == -1) {\n      continue;\n    }\n\n    /*=======================================================================\n    find candidates (overlap with ground truth > 0.5) (logical len(det))\n    =======================================================================*/\n    uint32_t det_idx = 0;\n    float64_t valid_detection = NO_DETECTION;\n    float64_t max_overlap = 0;\n\n    // search for a possible detection\n    bool8_t assigned_ignored_det = false;\n    for (uint32_t j = 0; j < det.size(); j++) {\n      // detections not of the current class, already assigned or with a low threshold are ignored\n      if (ignored_det[j] == -1) {\n        continue;\n      }\n      if (assigned_detection[j]) {\n        continue;\n      }\n      if (ignored_threshold[j]) {\n        continue;\n      }\n\n      // find the maximum score for the candidates and get idx of respective detection\n      float64_t overlap = boxoverlap(det[j], gt[i], -1);\n\n      // for computing recall thresholds, the candidate with highest score is considered\n      if (!compute_fp &&\n        overlap > MIN_OVERLAP[static_cast<size_t>(metric)][static_cast<size_t>(current_class)] &&\n        det[j].thresh > valid_detection)\n      {\n        det_idx = j;\n        valid_detection = det[j].thresh;\n      } else if (compute_fp &&  // NOLINT\n        overlap > MIN_OVERLAP[static_cast<size_t>(metric)][static_cast<size_t>(current_class)] &&\n        (overlap > max_overlap || assigned_ignored_det) && ignored_det[j] == 0)\n      {\n        // for computing pr curve values, the candidate with the greatest overlap is considered\n        // if the greatest overlap is an ignored detection (min_height), the overlapping detection\n        // is used\n        max_overlap = overlap;\n        det_idx = j;\n        valid_detection = 1;\n        assigned_ignored_det = false;\n      } else if (compute_fp &&  // NOLINT\n        overlap > MIN_OVERLAP[static_cast<size_t>(metric)][static_cast<size_t>(current_class)] &&\n        valid_detection == NO_DETECTION && ignored_det[j] == 1)\n      {\n        det_idx = j;\n        valid_detection = 1;\n        assigned_ignored_det = true;\n      }\n    }\n\n    /*=======================================================================\n    compute TP, FP and FN\n    =======================================================================*/\n\n    // nothing was assigned to this valid ground truth\n    if (valid_detection == NO_DETECTION && ignored_gt[i] == 0) {\n      stat.fn++;\n    } else if (valid_detection != NO_DETECTION &&  // NOLINT\n      (ignored_gt[i] == 1 || ignored_det[det_idx] == 1))\n    {\n      // only evaluate valid ground truth <=> detection assignments (considering difficulty level)\n      assigned_detection[det_idx] = true;\n    } else if (valid_detection != NO_DETECTION) {\n      // found a valid true positive\n      // write highest score to threshold vector\n      stat.tp++;\n      stat.v.push_back(det[det_idx].thresh);\n\n      // compute angular difference of detection and ground truth if valid detection orientation was\n      // provided\n      if (compute_aos) {\n        delta.push_back(gt[i].box.alpha - det[det_idx].box.alpha);\n      }\n\n      // clean up\n      assigned_detection[det_idx] = true;\n    }\n  }\n\n  // if FP are requested, consider stuff area\n  if (compute_fp) {\n    // count fp\n    for (uint32_t i = 0; i < det.size(); i++) {\n      // count false positives if required (height smaller than required is ignored (ignored_det==1)\n      if (!(assigned_detection[i] || ignored_det[i] == -1 || ignored_det[i] == 1 ||\n        ignored_threshold[i]))\n      {\n        stat.fp++;\n      }\n    }\n\n    // do not consider detections overlapping with stuff area\n    int32_t nstuff = 0;\n    for (uint32_t i = 0; i < dc.size(); i++) {\n      for (uint32_t j = 0; j < det.size(); j++) {\n        // detections not of the current class, already assigned, with a low threshold or a low\n        // minimum height are ignored\n        if (assigned_detection[j]) {\n          continue;\n        }\n        if (ignored_det[j] == -1 || ignored_det[j] == 1) {\n          continue;\n        }\n        if (ignored_threshold[j]) {\n          continue;\n        }\n\n        // compute overlap and assign to stuff area, if overlap exceeds class specific value\n        float64_t overlap = boxoverlap(det[j], dc[i], 0);\n        auto metric_s = static_cast<size_t>(metric);\n        auto current_class_s = static_cast<size_t>(current_class);\n        if (overlap > MIN_OVERLAP[metric_s][current_class_s]) {\n          assigned_detection[j] = true;\n          nstuff++;\n        }\n      }\n    }\n\n    // FP = no. of all not to ground truth assigned detections - detections assigned to stuff areas\n    stat.fp -= nstuff;\n\n    // if all orientation values are valid, the AOS is computed\n    if (compute_aos) {\n      std::vector<float64_t> tmp;\n\n      // FP have a similarity of 0, for all TP compute AOS\n      tmp.assign(static_cast<size_t>(stat.fp), 0);\n      for (uint32_t i = 0; i < delta.size(); i++) {\n        tmp.push_back((1.0 + cos(delta[i])) / 2.0);\n      }\n\n      // be sure, that all orientation deltas are computed\n      assert(tmp.size() == static_cast<size_t>(stat.fp + stat.tp));\n      assert(delta.size() == static_cast<size_t>(stat.tp));\n\n      // get the mean orientation similarity for this image\n      if (stat.tp > 0 || stat.fp > 0) {\n        stat.similarity = accumulate(tmp.begin(), tmp.end(), 0.0);\n      } else {\n        // there was neither a FP nor a TP, so the similarity is ignored in the evaluation\n        stat.similarity = -1;\n      }\n    }\n  }\n  return stat;\n}\n\n/*=======================================================================\nEVALUATE CLASS-WISE\n=======================================================================*/\n\nbool8_t eval_class(\n  FILE * fp_det, FILE * fp_ori, CLASSES current_class,\n  const std::vector<std::vector<tGroundtruth>> & groundtruth,\n  const std::vector<std::vector<tDetection>> & detections, bool8_t compute_aos,\n  float64_t (* boxoverlap)(tDetection, tGroundtruth, int32_t),\n  std::vector<float64_t> & precision, std::vector<float64_t> & aos,\n  DIFFICULTY difficulty, METRIC metric)\n{\n  assert(groundtruth.size() == detections.size());\n\n  // init\n  // total no. of gt (denominator of recall)\n  int32_t n_gt = 0;\n  // detection scores, evaluated for recall discretization\n  std::vector<float64_t> v, thresholds;\n  // index of ignored gt detection for current class/difficulty\n  std::vector<std::vector<int32_t>> ignored_gt, ignored_det;\n  // index of dontcare areas, included in ground truth\n  std::vector<std::vector<tGroundtruth>> dontcare;\n\n  // for all test images do\n  for (uint32_t i = 0; i < groundtruth.size(); i++) {\n    // holds ignored ground truth, ignored detections and dontcare areas for current frame\n    std::vector<int32_t> i_gt, i_det;\n    std::vector<tGroundtruth> dc;\n\n    // only evaluate objects of current class and ignore occluded, truncated objects\n    cleanData(current_class, groundtruth[i], detections[i], i_gt, dc, i_det, n_gt, difficulty);\n    ignored_gt.push_back(i_gt);\n    ignored_det.push_back(i_det);\n    dontcare.push_back(dc);\n\n    // compute statistics to get recall values\n    tPrData pr_tmp = tPrData();\n    pr_tmp = computeStatistics(\n      current_class, groundtruth[i], detections[i], dc, i_gt, i_det, false,\n      boxoverlap, metric);\n\n    // add detection scores to vector over all images\n    for (uint32_t j = 0; j < pr_tmp.v.size(); j++) {\n      v.push_back(pr_tmp.v[j]);\n    }\n  }\n\n  // get scores that must be evaluated for recall discretization\n  thresholds = getThresholds(v, n_gt);\n\n  // compute TP,FP,FN for relevant scores\n  std::vector<tPrData> pr;\n  pr.assign(thresholds.size(), tPrData());\n  for (uint32_t i = 0; i < groundtruth.size(); i++) {\n    // for all scores/recall thresholds do:\n    for (uint32_t t = 0; t < thresholds.size(); t++) {\n      tPrData tmp = tPrData();\n      tmp = computeStatistics(\n        current_class, groundtruth[i], detections[i], dontcare[i],\n        ignored_gt[i], ignored_det[i], true, boxoverlap, metric,\n        compute_aos, thresholds[t]);\n\n      // add no. of TP, FP, FN, AOS for current frame to total evaluation for current threshold\n      pr[t].tp += tmp.tp;\n      pr[t].fp += tmp.fp;\n      pr[t].fn += tmp.fn;\n      if (tmp.similarity != -1) {\n        pr[t].similarity += tmp.similarity;\n      }\n    }\n  }\n\n  // compute recall, precision and AOS\n  std::vector<float64_t> recall;\n  precision.assign(N_SAMPLE_PTS, 0);\n  if (compute_aos) {\n    aos.assign(N_SAMPLE_PTS, 0);\n  }\n  float64_t r = 0;\n  for (uint32_t i = 0; i < thresholds.size(); i++) {\n    r = pr[i].tp / static_cast<float64_t>(pr[i].tp + pr[i].fn);\n    recall.push_back(r);\n    precision[i] = pr[i].tp / static_cast<float64_t>(pr[i].tp + pr[i].fp);\n    if (compute_aos) {\n      aos[i] = pr[i].similarity / static_cast<float64_t>(pr[i].tp + pr[i].fp);\n    }\n  }\n\n  // filter precision and AOS using max_{i..end}(precision)\n  for (uint32_t i = 0; i < thresholds.size(); i++) {\n    precision[i] = *max_element(precision.begin() + i, precision.end());\n    if (compute_aos) {\n      aos[i] = *max_element(aos.begin() + i, aos.end());\n    }\n  }\n\n  // save statisics and finish with success\n  saveStats(precision, aos, fp_det, fp_ori);\n  return true;\n}\n\nvoid saveAndPlotPlots(\n  std::basic_string<char8_t> dir_name, std::basic_string<char8_t> file_name,\n  std::basic_string<char8_t> obj_type, std::vector<float64_t> vals[], bool8_t is_aos)\n{\n  // save plot data to file\n  FILE * fp = fopen((dir_name + \"/\" + file_name + \".txt\").c_str(), \"w\");\n  printf(\"save %s\\n\", (dir_name + \"/\" + file_name + \".txt\").c_str());\n  for (size_t i = 0; i < static_cast<size_t>(N_SAMPLE_PTS); i++) {\n    fprintf(\n      fp, \"%f %f %f %f\\n\", static_cast<float64_t>(i) / (N_SAMPLE_PTS - 1.0), vals[0][i], vals[1][i],\n      vals[2][i]);\n  }\n  fclose(fp);\n\n  // create png + eps\n  for (int32_t j = 0; j < 2; j++) {\n    std::basic_string<char8_t> type = \"_png\";\n\n    if (j != 0) {\n      type = \"_pdf\";\n    }\n    // open file\n    FILE * fp = fopen((dir_name + \"/\" + file_name + type + \".gp\").c_str(), \"w\");\n\n    // save gnuplot instructions\n    if (j == 0) {\n      fprintf(fp, \"set term png size 450,315 font \\\"Helvetica\\\" 11\\n\");\n      fprintf(fp, \"set output \\\"%s.png\\\"\\n\", file_name.c_str());\n    } else {\n      fprintf(fp, \"set term postscript eps enhanced color font \\\"Helvetica\\\" 20\\n\");\n      fprintf(fp, \"set output \\\"%s.eps\\\"\\n\", file_name.c_str());\n    }\n\n    // set labels and ranges\n    fprintf(fp, \"set size ratio 0.7\\n\");\n    fprintf(fp, \"set xrange [0:1]\\n\");\n    fprintf(fp, \"set yrange [0:1]\\n\");\n    fprintf(fp, \"set xlabel \\\"Recall\\\"\\n\");\n    if (!is_aos) {fprintf(fp, \"set ylabel \\\"Precision\\\"\\n\");} else {\n      fprintf(fp, \"set ylabel \\\"Orientation Similarity\\\"\\n\");\n    }\n    obj_type[0] = static_cast<char8_t>(toupper(obj_type[0]));\n    fprintf(fp, \"set title \\\"%s\\\"\\n\", obj_type.c_str());\n\n    // line width\n    int32_t lw = 5;\n    if (j == 0) {lw = 3;}\n\n    // plot error curve\n    fprintf(fp, \"plot \");\n    fprintf(fp, \"\\\"%s.txt\\\" using 1:2 title 'Easy' with lines ls 1 lw %d,\", file_name.c_str(), lw);\n    fprintf(\n      fp, \"\\\"%s.txt\\\" using 1:3 title 'Moderate' with lines ls 2 lw %d,\",\n      file_name.c_str(), lw);\n    fprintf(fp, \"\\\"%s.txt\\\" using 1:4 title 'Hard' with lines ls 3 lw %d\", file_name.c_str(), lw);\n\n    // close file\n    fclose(fp);\n  }\n}\n\nnamespace kittisdk\n{\n\nextern \"C\"\nint32_t eval(\n  std::basic_string<char8_t> ground_truth_path, std::basic_string<char8_t> detection_path,\n  std::basic_string<char8_t> output_path, bool8_t eval_2d_res, bool8_t eval_ground_red,\n  bool8_t eval_3d_res, bool8_t print_stdout, bool8_t create_plot, int32_t n_testimages)\n{\n  // set some global parameters\n  initGlobals();\n\n  // ground truth and result directories\n  std::basic_string<char8_t> result_dir = output_path;\n  std::basic_string<char8_t> plot_dir = result_dir + \"/plot\";\n\n  // Check folder existance\n  if (!ghc::filesystem::is_directory(ghc::filesystem::path(ground_truth_path)) ||\n    !ghc::filesystem::is_directory(ghc::filesystem::path(detection_path)) ||\n    !ghc::filesystem::is_directory(ghc::filesystem::path(result_dir)) )\n  {\n    if (print_stdout) {\n      printf(\"Folder structure error, please check the existance of: \\n\");\n      printf(\"%s\\n\", ground_truth_path.c_str());\n      printf(\"%s\\n\", detection_path.c_str());\n      printf(\"%s\\n\", result_dir.c_str());\n    }\n    return 0;\n  }\n\n  if (create_plot && !ghc::filesystem::is_directory(ghc::filesystem::path(plot_dir))) {\n    printf(\"Folder structure error, please check the existance of: \\n\");\n    printf(\"%s\\n\", plot_dir.c_str());\n  }\n\n  // hold detections and ground truth in memory\n  std::vector<std::vector<tGroundtruth>> groundtruth;\n  std::vector<std::vector<tDetection>> detections;\n\n  // holds wether orientation similarity shall be computed (might be set to false while loading\n  // detections) and which labels where provided by this submission\n  bool8_t compute_aos = true;\n  std::vector<bool8_t> eval_image(NUM_CLASS, false);\n  std::vector<bool8_t> eval_ground(NUM_CLASS, false);\n  std::vector<bool8_t> eval_3d(NUM_CLASS, false);\n\n  // for all images read groundtruth and detections\n  if (print_stdout) {\n    printf(\"Loading detections...\\n\");\n  }\n\n  for (int32_t i = 0; i < n_testimages; i++) {\n    // file name\n    char8_t file_name[256];\n    snprintf(file_name, sizeof(file_name), \"%06d.txt\", i);\n\n    // read ground truth and result poses\n    bool8_t gt_success, det_success;\n    std::vector<tGroundtruth> gt = loadGroundtruth(ground_truth_path + \"/\" + file_name, gt_success);\n    std::vector<tDetection> det = loadDetections(\n      detection_path + \"/\" + file_name,\n      compute_aos, eval_image, eval_ground, eval_3d, det_success);\n    groundtruth.push_back(gt);\n    detections.push_back(det);\n\n    // check for errors\n    if (!gt_success) {\n      if (print_stdout) {\n        printf(\"ERROR: Couldn't read: %s of ground truth.\\n\", file_name);\n      }\n      return 0;\n    }\n    if (!det_success) {\n      if (print_stdout) {\n        printf(\"ERROR: Couldn't read: %s\\n\", file_name);\n      }\n      return 0;\n    }\n  }\n  if (print_stdout) {\n    printf(\"  done.\\n\");\n  }\n\n  // holds pointers for result files\n  FILE * fp_det = 0, * fp_ori = 0;\n\n  if (eval_2d_res) {\n    // eval image 2D bounding boxes\n    for (size_t c = 0; c < static_cast<size_t>(NUM_CLASS); c++) {\n      CLASSES cls = (CLASSES)c;\n\n      if (eval_image[c]) {\n        if (print_stdout) {\n          printf(\"Starting 2D evaluation (%s) ...\\n\", CLASS_NAMES[c].c_str());\n        }\n        fp_det = fopen((result_dir + \"/stats_\" + CLASS_NAMES[c] + \"_detection.txt\").c_str(), \"w\");\n        if (compute_aos) {\n          fp_ori =\n            fopen((result_dir + \"/stats_\" + CLASS_NAMES[c] + \"_orientation.txt\").c_str(), \"w\");\n        }\n        std::vector<float64_t> precision[3], aos[3];\n        if (!eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, imageBoxOverlap,\n            precision[0], aos[0], DIFFICULTY::EASY, METRIC::IMAGE) ||\n          !eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, imageBoxOverlap,\n            precision[1], aos[1], DIFFICULTY::MODERATE, METRIC::IMAGE) ||\n          !eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, imageBoxOverlap,\n            precision[2], aos[2], DIFFICULTY::HARD, METRIC::IMAGE))\n        {\n          if (print_stdout) {\n            printf(\"%s evaluation failed.\\n\", CLASS_NAMES[c].c_str());\n          }\n          return 0;\n        }\n        fclose(fp_det);\n        if (create_plot) {\n          saveAndPlotPlots(plot_dir, CLASS_NAMES[c] + \"_detection\", CLASS_NAMES[c], precision, 0);\n        }\n        if (compute_aos) {\n          if (create_plot) {\n            saveAndPlotPlots(plot_dir, CLASS_NAMES[c] + \"_orientation\", CLASS_NAMES[c], aos, 1);\n          }\n          fclose(fp_ori);\n        }\n        if (print_stdout) {\n          printf(\"  done.\\n\");\n        }\n      }\n    }\n  }\n\n  // don't evaluate AOS for birdview boxes and 3D boxes\n  compute_aos = false;\n\n  if (eval_ground_red) {\n    // eval bird's eye view bounding boxes\n    for (size_t c = 0; c < static_cast<size_t>(NUM_CLASS); c++) {\n      CLASSES cls = (CLASSES)c;\n\n      if (eval_ground[c]) {\n        if (print_stdout) {\n          printf(\"Starting bird's eye evaluation (%s) ...\\n\", CLASS_NAMES[c].c_str());\n        }\n        fp_det = fopen(\n          (result_dir + \"/stats_\" + CLASS_NAMES[c] + \"_detection_ground.txt\").c_str(), \"w\");\n        std::vector<float64_t> precision[3], aos[3];\n        if (!eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, groundBoxOverlap,\n            precision[0], aos[0], DIFFICULTY::EASY, METRIC::GROUND) ||\n          !eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, groundBoxOverlap,\n            precision[1], aos[1], DIFFICULTY::MODERATE, METRIC::GROUND) ||\n          !eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, groundBoxOverlap,\n            precision[2], aos[2], DIFFICULTY::HARD, METRIC::GROUND))\n        {\n          if (print_stdout) {\n            printf(\"%s evaluation failed.\\n\", CLASS_NAMES[c].c_str());\n          }\n          return 0;\n        }\n        fclose(fp_det);\n        if (create_plot) {\n          saveAndPlotPlots(\n            plot_dir, CLASS_NAMES[c] + \"_detection_ground\", CLASS_NAMES[c],\n            precision, 0);\n        }\n        if (print_stdout) {\n          printf(\"  done.\\n\");\n        }\n      }\n    }\n  }\n\n  if (eval_3d_res) {\n    // eval 3D bounding boxes\n    for (size_t c = 0; c < static_cast<size_t>(NUM_CLASS); c++) {\n      CLASSES cls = (CLASSES)c;\n\n      if (eval_3d[c]) {\n        if (print_stdout) {\n          printf(\"Starting 3D evaluation (%s) ...\\n\", CLASS_NAMES[c].c_str());\n        }\n        fp_det =\n          fopen((result_dir + \"/stats_\" + CLASS_NAMES[c] + \"_detection_3d.txt\").c_str(), \"w\");\n        std::vector<float64_t> precision[3], aos[3];\n        if (!eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, box3DOverlap,\n            precision[0], aos[0], DIFFICULTY::EASY, METRIC::BOX3D) ||\n          !eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, box3DOverlap,\n            precision[1], aos[1], DIFFICULTY::MODERATE, METRIC::BOX3D) ||\n          !eval_class(\n            fp_det, fp_ori, cls, groundtruth, detections, compute_aos, box3DOverlap,\n            precision[2], aos[2], DIFFICULTY::HARD, METRIC::BOX3D))\n        {\n          if (print_stdout) {\n            printf(\"%s evaluation failed.\\n\", CLASS_NAMES[c].c_str());\n          }\n          return 0;\n        }\n        fclose(fp_det);\n        if (create_plot) {\n          saveAndPlotPlots(\n            plot_dir, CLASS_NAMES[c] + \"_detection_3d\", CLASS_NAMES[c], precision,\n            0);\n        }\n        if (print_stdout) {\n          printf(\"  done.\\n\");\n        }\n      }\n    }\n  }\n\n  // success\n  return 1;\n}\n\n}  // namespace kittisdk\n", "meta": {"hexsha": "8e375eebd7aed068c27ba52abe353bde98be0d83", "size": 38399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools/benchmark_tool/benchmark_tool/kittiobjdetsdk/src/evaluate_object.cpp", "max_stars_repo_name": "ruvus/auto", "max_stars_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T10:03:08.000Z", "max_issues_repo_path": "src/tools/benchmark_tool/benchmark_tool/kittiobjdetsdk/src/evaluate_object.cpp", "max_issues_repo_name": "ruvus/auto", "max_issues_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-23T16:45:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T16:59:40.000Z", "max_forks_repo_path": "src/tools/benchmark_tool/benchmark_tool/kittiobjdetsdk/src/evaluate_object.cpp", "max_forks_repo_name": "ruvus/auto", "max_forks_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T14:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:03:09.000Z", "avg_line_length": 34.7188065099, "max_line_length": 100, "alphanum_fraction": 0.6121774005, "num_tokens": 10726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.16718222236309277}}
{"text": "#include <algorithm>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/foreach.hpp>\n#include <map>\n#include \"enigma.h\"\n#include \"main.h\"\n#include \"key.h\"\n#include \"net.h\"\n#include \"init.h\"\n#include \"util.h\"\n#include \"wallet.h\"\n#include \"ui_interface.h\"\n\n#include <openssl/ecdsa.h>\n#include <openssl/obj_mac.h>\n#include <openssl/rand.h>\n#include <openssl/ecdh.h>\n#include <openssl/hmac.h>\n#include <openssl/aes.h>\n#include \"encryption.h\"\n\nextern bool lightCloakShieldIcon ; // should we light the cloak shield icon on the main gui status area?\n\nvoid CCloakingSecret::SetNull()\n{\n    memset(&chKey, 0, sizeof chKey);\n    memset(&chIV, 0, sizeof chIV);\n    userPubKeyForHash = \"\";\n    userPubKeyHashHex = \"\";\n}\n\nconst std::string CCloakingSecret::GetKeyHash()\n{\n    // need to regen hash ?\n    if (userPubKeyForHash.compare(userPubKey) != 0){\n        userPubKeyHashHex = Hash160(vchFromString(userPubKey)).GetHex();\n    }\n    return userPubKeyHashHex;\n}\n\n// CCloakingEncryptionKey is our per-session pub/priv keypair for ECDH communication with peers\nCCloakingEncryptionKey::CCloakingEncryptionKey() : CKey()\n{\n    try\n    {\n        MakeNewKey(true);\n        pubkeyHex = HexStr(this->GetPubKey().Raw());\n        pubkeyHexHash = Hash160(vchFromString(pubkeyHex)).GetHex();\n\n    }catch (std::exception& e){\n        error(\"CCloakingEncryptionKey::CCloakingEncryptionKey: %s.\", e.what());\n    }\n}\n\n\n// create (or return existing) hex encoded ECDH secret for a public key (using our current Enigma priv-key)\nbool CCloakingEncryptionKey::GetSecret(std::string targetPubKey, CCloakingSecret& cloakSecretOut, bool addToMap)\n{\n    try\n    {\n        LOCK(pwalletMain->cs_CloakingSecrets);\n        CCloakShield* cs = CCloakShield::GetShield();\n\n        // return existing?\n        if (cs->mapCloakSecrets.count(targetPubKey)){\n            cloakSecretOut = cs->mapCloakSecrets[targetPubKey];\n            return true;\n        }\n\n        EC_KEY *peerkey;\n        int field_size;\n        unsigned char *secret;\n        size_t secret_len;\n\n        std::vector<unsigned char> vchPubKey = ParseHex(targetPubKey.c_str());\n        const unsigned char* pbegin = &vchPubKey[0];\n\n        peerkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n        if (o2i_ECPublicKey(&peerkey, &pbegin, vchPubKey.size()))\n        {\n            // In testing, d2i_ECPrivateKey can return true\n            // but fill in pkey with a key that fails\n            // EC_KEY_check_key, so:\n            if (!EC_KEY_check_key(peerkey))\n            {\n                printf(\"CreateSecretECDH: EC_KEY_check_key failed\");\n                return false;\n            }\n        }\n\n        // Calculate the size of the buffer for the shared secret\n        field_size = EC_GROUP_get_degree(EC_KEY_get0_group(this->pkey));\n        secret_len = (field_size+7)/8;\n\n        // Allocate the memory for the shared secret\n        if(NULL == (secret = (unsigned char*)OPENSSL_malloc(secret_len)))\n        {\n            printf(\"CreateSecretECDH: OPENSSL_malloc failed\");\n        }\n\n        // Derive the shared secret\n        secret_len = ECDH_compute_key(secret, secret_len, EC_KEY_get0_public_key(peerkey),\n                            this->pkey, NULL);\n\n        // Clean up\n        EC_KEY_free(peerkey);\n\n        if(secret_len <= 0)\n        {\n            if(GetBoolArg(\"-printenigma\", false))\n                OutputDebugStringF(\"CreateSecretECDH: secret_len <= 0\");\n            OPENSSL_free(secret);\n            return NULL;\n        }\n\n        vector<unsigned char> vchSecret;\n        vchSecret.insert( vchSecret.end(), secret, secret+(secret_len));\n\n        vector<unsigned char> vchSecretHash;\n        uint256 secretHash = Hash(vchSecret.begin(), vchSecret.end());\n        vchSecretHash.insert( vchSecretHash.end(), secretHash.begin(), secretHash.end());\n\n        // create the key and IV that we will use to encrypt the shared Enigma encryption key for this user.\n        EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), NULL,\n                          (unsigned char *)&vchSecretHash[0], vchSecretHash.size(), 25000, &cloakSecretOut.chKey[0], &cloakSecretOut.chIV[0]);\n\n        cloakSecretOut.secretHex = HexStr(vchSecretHash.begin(), vchSecretHash.end());\n\n        cloakSecretOut.keyHex = HexStr(&cloakSecretOut.chKey[0], &cloakSecretOut.chKey[32]);\n        cloakSecretOut.ivHex = HexStr(&cloakSecretOut.chIV[0], &cloakSecretOut.chIV[16]);\n\n        cloakSecretOut.userPubKey = targetPubKey;\n\n        if (addToMap)\n            cs->mapCloakSecrets[targetPubKey] = cloakSecretOut;\n\n        return true;\n\n    }catch (std::exception& e){\n        error(\"CCloakingEncryptionKey::GetSecretECDH: %s.\", e.what());\n        return false;\n    }\n}\n", "meta": {"hexsha": "8d3af24ba3346d9ac92b4cc61dddd95f6ef63e4d", "size": 4736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/enigma/encryption.cpp", "max_stars_repo_name": "fradow-cloak/CloakCoin", "max_stars_repo_head_hexsha": "42bd57b6c3f87064281b52f2cf99d0b6c9e43de1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2017-06-12T17:32:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T13:29:03.000Z", "max_issues_repo_path": "src/enigma/encryption.cpp", "max_issues_repo_name": "fradow-cloak/CloakCoin", "max_issues_repo_head_hexsha": "42bd57b6c3f87064281b52f2cf99d0b6c9e43de1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-02-20T12:42:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-20T04:53:35.000Z", "max_forks_repo_path": "src/enigma/encryption.cpp", "max_forks_repo_name": "fradow-cloak/CloakCoin", "max_forks_repo_head_hexsha": "42bd57b6c3f87064281b52f2cf99d0b6c9e43de1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T18:34:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T20:36:54.000Z", "avg_line_length": 32.6620689655, "max_line_length": 142, "alphanum_fraction": 0.6456925676, "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.16692943992931947}}
{"text": "// -*- mode: c++; indent-tabs-mode: nil; -*-\n//\n// Copyright (c) 2009-2013 Illumina, Inc.\n//\n// This software is provided under the terms and conditions of the\n// Illumina Open Source Software License 1.\n//\n// You should have received a copy of the Illumina Open Source\n// Software License 1 along with this program. If not, see\n// <https://github.com/sequencing/licenses/>\n//\n\n/// \\file\n\n/// \\author Chris Saunders\n///\n#ifndef __POSITION_SNP_CALL_PPROB_DIGT_HH\n#define __POSITION_SNP_CALL_PPROB_DIGT_HH\n\n#include \"blt_common/blt_shared.hh\"\n#include \"blt_common/snp_pos_info.hh\"\n\n#include \"blt_util/digt.hh\"\n#include \"blt_util/qscore.hh\"\n\n#include <boost/array.hpp>\n#include <boost/utility.hpp>\n\n#include <iosfwd>\n\n\n\nstruct diploid_genotype {\n\n    diploid_genotype() { reset(); }\n\n    void reset() {\n        is_snp=false;\n        ref_gt=0;\n        genome.reset();\n        poly.reset();\n    }\n\n    struct result_set {\n\n        result_set() { reset(); }\n\n        void\n        reset() {\n            max_gt=0;\n            static const blt_float_t p(1./static_cast<blt_float_t>(DIGT::SIZE));\n            static const int qp(error_prob_to_qphred((1.-p)));\n            snp_qphred=qp;\n            max_gt_qphred=qp;\n            for (unsigned i(0); i<DIGT::SIZE; ++i) {\n                pprob[i] = p;\n            }\n        }\n\n        unsigned max_gt;\n        int snp_qphred;\n        int max_gt_qphred;\n        boost::array<double,DIGT::SIZE> pprob; // note this is intentionally stored at higher float resolution than the rest of the computation\n    };\n\n    bool is_snp;\n    unsigned ref_gt;\n    result_set genome;\n    result_set poly;\n    double sb;\n};\n\n\n// debuging output -- produces labels\n//\nstd::ostream& operator<<(std::ostream& os,const diploid_genotype& dgt);\n\n\n// more debuging output:\nvoid\ndebug_dump_digt_lhood(const blt_float_t* lhood,\n                      std::ostream& os);\n\n\n// allele call output:\n//\nvoid\nwrite_diploid_genotype_allele(const blt_options& opt,\n                              const snp_pos_info& pi,\n                              const diploid_genotype& dgt,\n                              std::ostream& os,\n                              const unsigned hpol);\n\n// snp call output:\n//\ninline\nvoid\nwrite_diploid_genotype_snp(const blt_options& opt,\n                           const snp_pos_info& pi,\n                           const diploid_genotype& dgt,\n                           std::ostream& os,\n                           const unsigned hpol) {\n\n    write_diploid_genotype_allele(opt,pi,dgt,os,hpol);\n}\n\n\n// Use caller object to precalculate prior distributions based on\n// theta value:\n//\nstruct pprob_digt_caller : private boost::noncopyable {\n\n    pprob_digt_caller(const blt_float_t theta);\n\n    /// \\brief call a snp @ pos by calculating the posterior probability\n    /// of all possible genotypes for a diploid individual.\n    ///\n    /// When is_always_test is true, probabilities are calculated even\n    /// when a snp could not exist at the site.\n    ///\n    void\n    position_snp_call_pprob_digt(const blt_options& opt,\n                                 const extended_pos_info& epi,\n                                 diploid_genotype& dgt,\n                                 const bool is_always_test = false) const;\n\n\n    const blt_float_t*\n    lnprior_genomic(const unsigned ref_id) const {\n        return _lnprior[ref_id].genome;\n    }\n\n    const blt_float_t*\n    lnprior_polymorphic(const unsigned ref_id) const {\n        return _lnprior[ref_id].poly;\n    }\n\n    static\n    void\n    get_diploid_gt_lhood(const blt_options& opt,\n                         const extended_pos_info& epi,\n                         const bool is_het_bias,\n                         const blt_float_t het_bias,\n                         blt_float_t* const lhood,\n                         const bool is_strand_specific = false,\n                         const bool is_ss_fwd = false);\n\n    static\n    void\n    calculate_result_set(const blt_float_t* lhood,\n                         const blt_float_t* lnprior,\n                         const unsigned ref_gt,\n                         diploid_genotype::result_set& rs);\n\nprivate:\n    struct prior_set {\n        blt_float_t genome[DIGT::SIZE];\n        blt_float_t poly[DIGT::SIZE];\n    };\n\n    prior_set _lnprior[N_BASE+1];\n};\n\n#endif\n", "meta": {"hexsha": "48be2c90f1a75e30e0e3a0fafcb626cf1085c122", "size": 4287, "ext": "hh", "lang": "C++", "max_stars_repo_path": "isaac_variant_caller/src/lib/blt_common/position_snp_call_pprob_digt.hh", "max_stars_repo_name": "sequencing/isaac_variant_caller", "max_stars_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T01:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-04T03:48:21.000Z", "max_issues_repo_path": "isaac_variant_caller/src/lib/blt_common/position_snp_call_pprob_digt.hh", "max_issues_repo_name": "sequencing/isaac_variant_caller", "max_issues_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-07-23T09:38:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-01T05:37:26.000Z", "max_forks_repo_path": "isaac_variant_caller/src/lib/blt_common/position_snp_call_pprob_digt.hh", "max_forks_repo_name": "sequencing/isaac_variant_caller", "max_forks_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:41:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:42:32.000Z", "avg_line_length": 25.9818181818, "max_line_length": 143, "alphanum_fraction": 0.5915558666, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16692943640203087}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <mmtbx/rsr/rsr.h>\n#include <scitbx/array_family/boost_python/shared_wrapper.h>\n#include <scitbx/boost_python/is_polymorphic_workaround.h>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/return_by_value.hpp>\n\nnamespace mmtbx { namespace rsr {\nnamespace {\n\n  void init_module()\n  {\n    using namespace boost::python;\n    using boost::python::arg;\n    typedef return_value_policy<return_by_value> rbv;\n    class_<manager<> >(\"manager\",\n      init<int const&,\n           int const&,\n           int const&,\n           cctbx::xray::scattering_type_registry const&,\n           cctbx::uctbx::unit_cell const&,\n           af::const_ref<cctbx::xray::scatterer<> > const&,\n           optional<double const&,\n                    double const&> >((\n                                  arg(\"nx\"),\n                                  arg(\"ny\"),\n                                  arg(\"nz\"),\n                                  arg(\"scattering_type_registry\"),\n                                  arg(\"unit_cell\"),\n                                  arg(\"scatterers\"),\n                                  arg(\"exp_table_one_over_step_size\")=-100,\n                                  arg(\"wing_cutoff\")=1.e-3)))\n      .add_property(\"density_array\", make_getter(&manager<>::density_array, rbv()))\n    ;\n\n    class_<manager_BCR<> >(\"manager_BCR\",\n      init<int const&,\n           int const&,\n           int const&,\n           cctbx::xray::scattering_type_registry const&,\n           cctbx::uctbx::unit_cell const&,\n           boost::python::list const&, // BCRscatterers\n           optional<double const&,\n                    double const&> >((\n                                  arg(\"nx\"),\n                                  arg(\"ny\"),\n                                  arg(\"nz\"),\n                                  arg(\"scattering_type_registry\"),\n                                  arg(\"unit_cell\"),\n                                  arg(\"BCRscatterers\"),\n                                  arg(\"exp_table_one_over_step_size\")=-100,\n                                  arg(\"wing_cutoff\")=1.e-3)))\n      .add_property(\"density_array\", make_getter(&manager_BCR<>::density_array, rbv()))\n    ;\n\n  }\n\n} // namespace <anonymous>\n}} // namespace mmtbx::rsr\n\nBOOST_PYTHON_MODULE(mmtbx_rsr_ext)\n{\n  mmtbx::rsr::init_module();\n}\n", "meta": {"hexsha": "965868e42cafd857d3b8e48ddae2a370002437e4", "size": 2492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mmtbx/rsr/rsr_ext.cpp", "max_stars_repo_name": "Anthchirp/cctbx", "max_stars_repo_head_hexsha": "b8064f755b1dbadf05b8fbf806b7d50d73ef69bf", "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": "mmtbx/rsr/rsr_ext.cpp", "max_issues_repo_name": "Anthchirp/cctbx", "max_issues_repo_head_hexsha": "b8064f755b1dbadf05b8fbf806b7d50d73ef69bf", "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": "mmtbx/rsr/rsr_ext.cpp", "max_forks_repo_name": "Anthchirp/cctbx", "max_forks_repo_head_hexsha": "b8064f755b1dbadf05b8fbf806b7d50d73ef69bf", "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": 35.6, "max_line_length": 87, "alphanum_fraction": 0.5108346709, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.16685338558911159}}
{"text": "#include \"../include/Dictionary.h\"\n#include \"../include/kbhit.h\"\n\n#include <fstream>\n#include <omp.h>\n\n#include \"../include/exceptions.h\"\n#include \"../include/Words.h\"\n#include \"../include/Timer.h\"\n#include \"../include/utility.h\"\n\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/copy.hpp>\n#include <boost/iostreams/filter/zlib.hpp>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef vector< wstring > splitVec;\n\nstring Dictionary::ending = \"dictionary\";\n\nDictionary::Dictionary(Corpus* co) : Model<Dictionary>(co)\n{\n    systemMessage(\"Creating dictionary\");\n\n    // create dictionary parts t and c: f -> e\n    size2 = co->getEwords()->size();\n    size1 = co->getFwords()->size();\n    int esize = size2;\n    int fsize = size1;\n    model = new float*[fsize];\n    float** c;\n    c = new float*[fsize];\n    for (int i = 0; i < fsize; i++)\n    {\n        model[i] = new float[esize];\n        c[i] = new float[esize];\n        for (int j = 0; j < esize; j++)\n        {\n            c[i][j] = SMOOTH;\n            model[i][j] = 0.0005;\n        }\n    }\n\n    int loops = 0;\n    int** fit;\n    int** eit;\n    vector<wstring>::iterator ewit;\n    vector<wstring>::iterator fwit;\n    splitVec ew;\n    splitVec fw;\n    vector<int*>* flines = co->getFlines();\n    vector<int*>* elines = co->getElines();\n    float normalize[esize];\n    float norm = SMOOTH*fsize;\n    while (!kbhit())\n    {\n        for(int i = 0; i<esize; i++)\n        {\n            normalize[i] = norm;\n        }\n        loops++;\n        stringstream s;\n        s << loops << \". loop\";\n        systemMessage(s.str().c_str());\n\n#pragma omp parallel for\n        for(unsigned int x=0; x<elines->size(); x++)\n        {\n            fit = &(flines->at(x));\n            eit = &(elines->at(x));\n            for(int i=1; i<(*fit)[0]; i++)\n            {\n                float s = 0.0;\n                float* tpointer = model[(*fit)[i]];\n                float* cpointer = c[(*fit)[i]];\n                for(int j=1; j<(*eit)[0]; j++)\n                {\n                    s += tpointer[(*eit)[j]];\n                }\n\n                for(int j=1; j<(*eit)[0]; j++)\n                {\n                    float tmp = tpointer[(*eit)[j]]/s;\n                    cpointer[(*eit)[j]] += tmp;\n                    normalize[(*eit)[j]] += tmp;\n                }\n            }\n        }\n#pragma omp parallel for\n        for(int i = 0; i<fsize; i++)\n        {\n            for(int j = 0; j<esize; j++)\n            {\n                model[i][j] = c[i][j]/normalize[j];\n                c[i][j] = SMOOTH;\n            }\n\n        }\n    }\n    for (int j = 0; j < fsize ; j++)\n    {\n        delete [] c[j];\n    }\n    delete [] c;\n    saveModel();\n}\n\nmap<float, int>* Dictionary::getNBestTranslations(int word, unsigned int n)\n{\n    float last = 0.0;\n    map<float, int>* tr = new map<float,int>();\n    for(int i=0; i<size1; i++)\n    {\n        float p = lookup(i,word);\n        if(tr->size()<n)\n        {\n            tr->insert(pair<float,int>(p, i));\n            if(tr->size()==n)\n                last = tr->begin()->first;\n        }\n        else if(p > last)\n        {\n            tr->insert(pair<float,int>(p, i));\n            if(tr->size()>n)\n                tr->erase(last);\n            last = tr->begin()->first;\n        }\n    }\n    return tr;\n}\n\nint Dictionary::getBestTranslation(int f)\n{\n    float last = 0.0;\n    int tr = 0;\n    for(int i=0; i<size2; i++)\n    {\n        float p = lookup(f,i);\n        if(p > last)\n        {\n            tr=i;\n            last = p;\n        }\n    }\n    return tr;\n}\n", "meta": {"hexsha": "79ca2c119548a8bc01a7d1148a50e166db9d6d4d", "size": 3626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "share/packages/implementations/jobst-ibm1/src/Dictionary.cpp", "max_stars_repo_name": "tud-fop/vanda-studio", "max_stars_repo_head_hexsha": "b636a695d5ba1f199c07aa0950bfeacede4fdf19", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T12:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T12:07:50.000Z", "max_issues_repo_path": "share/packages/implementations/jobst-ibm1/src/Dictionary.cpp", "max_issues_repo_name": "tud-fop/vanda-studio", "max_issues_repo_head_hexsha": "b636a695d5ba1f199c07aa0950bfeacede4fdf19", "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": "share/packages/implementations/jobst-ibm1/src/Dictionary.cpp", "max_forks_repo_name": "tud-fop/vanda-studio", "max_forks_repo_head_hexsha": "b636a695d5ba1f199c07aa0950bfeacede4fdf19", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-08T14:51:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T14:51:01.000Z", "avg_line_length": 24.0132450331, "max_line_length": 75, "alphanum_fraction": 0.4663541092, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.16685337071004647}}
{"text": "// Copyright (c) 2014 Stefan Walk\n//\n// This file is part of CGAL (www.cgal.org).\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: LicenseRef-RFL\n// License notice in Installation/LICENSE.RFL\n//\n// Author(s)     : Stefan Walk\n\n// Modifications from original library:\n//  * changed inclusion protection tag\n//  * moved to namespace CGAL::internal::\n//  * fix computation of node_dist[label] so that results are always <= 1.0\n//  * change serialization functions to avoid a bug with boost and some\n//    compilers (that leads to dereferencing a null pointer)\n//  * add a method to get feature usage\n\n#ifndef CGAL_INTERNAL_LIBLEARNING_RANDOMFORESTS_NODE_H\n#define CGAL_INTERNAL_LIBLEARNING_RANDOMFORESTS_NODE_H\n#include \"../dataview.h\"\n#include \"common-libraries.hpp\"\n\n#if defined(CGAL_LINKED_WITH_BOOST_IOSTREAMS) && defined(CGAL_LINKED_WITH_BOOST_SERIALIZATION)\n#include <boost/serialization/scoped_ptr.hpp>\n#include <boost/serialization/vector.hpp>\n#else\n#include <boost/scoped_ptr.hpp>\n#include <vector>\n#endif\n\n#if VERBOSE_NODE_LEARNING\n#include <cstdio>\n#endif\n\nnamespace CGAL { namespace internal {\n\nnamespace liblearning {\nnamespace RandomForest {\n\ntemplate <typename Derived, typename ParamT, typename Splitter>\nclass Node {\npublic:\n    typedef typename Splitter::FeatureType FeatureType;\n    bool is_leaf;\n    size_t n_samples;\n    size_t depth;\n    typedef ParamT ParamType;\n    ParamType const* params;\n    Splitter splitter;\n\n    boost::scoped_ptr<Derived> left;\n    boost::scoped_ptr<Derived> right;\n    std::vector<float> node_dist;\n\n    Node() : is_leaf(true), n_samples(0), depth(-1), params(0) {}\n    Node(size_t depth, ParamType const* params) :\n        is_leaf(true), n_samples(0), depth(depth), params(params)\n    {}\n\n    bool pure(DataView2D<int> labels, int* sample_idxes) const {\n        if (n_samples < 2)\n            return true; // an empty node is by definition pure\n        int first_sample_idx = sample_idxes[0];\n        int seen_class = labels(first_sample_idx, 0);\n        // check if all classes are equal to the first class\n        for (size_t i_sample = 1; i_sample < n_samples; ++i_sample) {\n            int sample_idx = sample_idxes[i_sample];\n            if (labels(sample_idx, 0) != seen_class)\n                return false;\n        }\n        return true;\n    }\n\n    float const* votes() const {\n        return (float const*)&node_dist[0];\n    }\n\n    int partition_samples(DataView2D<FeatureType> samples, int* sample_idxes) {\n        // sort samples in bag so that left-samples precede right-samples\n        // works like std::partition\n        int low  = 0;\n        int high = n_samples;\n\n        while (true) {\n            while (true) {\n                if (low == high) {\n                    return low;\n                } else if (!splitter.classify_sample(samples.row_pointer(sample_idxes[low]))) {\n                    ++low;\n                } else {\n                    break;\n                }\n            }\n            --high;\n            while (true) {\n                if (low == high) {\n                    return low;\n                } else if (splitter.classify_sample(samples.row_pointer(sample_idxes[high]))) {\n                    --high;\n                } else {\n                    break;\n                }\n            }\n            std::swap(sample_idxes[low], sample_idxes[high]);\n            ++low;\n        }\n    }\n\n    Derived const* split (FeatureType const* sample) const {\n        if (splitter.classify_sample(sample)) {\n            return right.get();\n        } else {\n            return left.get();\n        }\n    }\n\n    typedef std::list<Derived const*> NodeList;\n\n    NodeList get_all_childs() {\n        NodeList ret;\n        ret.push_back(this);\n        if (!is_leaf) {\n            NodeList left_childs  = left->get_all_childs();\n            ret.splice(ret.end(), left_childs);\n            NodeList right_childs = right->get_all_childs();\n            ret.splice(ret.end(), right_childs);\n        }\n        return ret;\n    }\n\n    template<typename SplitGenerator>\n    void determine_best_split(DataView2D<FeatureType> samples,\n                              DataView2D<int>         labels,\n                              int*                  sample_idxes,\n                              SplitGenerator        split_generator,\n                              RandomGen&            gen\n                              )\n    {\n        typename Splitter::FeatureClassData data_points;\n        init_feature_class_data(data_points, params->n_classes, n_samples);\n        float best_loss = std::numeric_limits<float>::infinity();\n\n        std::vector<uint64_t> classes_l;\n        std::vector<uint64_t> classes_r;\n\n        // pass information about data to split generator\n        split_generator.init(samples,\n                             labels,\n                             sample_idxes,\n                             n_samples,\n                             params->n_classes,\n                             gen);\n\n        size_t n_proposals = split_generator.num_proposals();\n\n        std::pair<FeatureType, float> results; // (threshold, loss)\n\n        for (size_t i_proposal = 0; i_proposal < n_proposals; ++i_proposal) {\n            // generate proposal\n            Splitter split = split_generator.gen_proposal(gen);\n            // map samples to numbers using proposal\n            split.map_points(samples, labels, sample_idxes, n_samples, data_points);\n            // check best loss using this proposal\n            results = static_cast<Derived*>(this)->determine_best_threshold(data_points, classes_l, classes_r, gen);\n            if (results.second < best_loss) {\n                // Proposal resulted into new optimum\n                best_loss = results.second;\n                split.set_threshold(results.first);\n                splitter = split;\n            }\n        }\n    }\n\n    template<typename SplitGenerator>\n    void train(DataView2D<FeatureType> samples,\n               DataView2D<int> labels,\n               int* sample_idxes,\n               size_t n_samples_,\n               SplitGenerator const& split_generator,\n               RandomGen& gen\n               )\n    {\n        n_samples = n_samples_;\n        node_dist.resize(params->n_classes, 0.0f);\n        for (size_t i_sample = 0; i_sample < n_samples; ++i_sample) {\n            int label = labels(sample_idxes[i_sample], 0);\n            node_dist[label] += 1.0f;\n        }\n\n        if (n_samples != 0)\n          for (std::size_t i = 0; i < node_dist.size(); ++ i)\n            node_dist[i] /= n_samples;\n\n        bool do_split = // Only split if ...\n            (n_samples >= params->min_samples_per_node) && // enough samples are available\n            !pure(labels, sample_idxes) && // this node is not already pure\n            (depth < params->max_depth); // we did not reach max depth\n        if (!do_split) {\n            splitter.threshold = 0.0;\n            return;\n        }\n\n        is_leaf = false;\n\n#if VERBOSE_NODE_LEARNING\n        std::printf(\"Determining the best split at depth %zu/%zu\\n\", depth, params->max_depth);\n#endif\n        determine_best_split(samples, labels, sample_idxes, split_generator, gen);\n\n        left.reset(new Derived(depth + 1, params));\n        right.reset(new Derived(depth + 1, params));\n\n        // sort samples in bag so that left-samples precede right-samples\n        int low = partition_samples(samples, sample_idxes);\n        int n_samples_left  = low;\n        int n_samples_right = n_samples - low;\n        int offset_left     = 0;\n        int offset_right    = low;\n#ifdef TREE_GRAPHVIZ_STREAM\n        if (depth <= TREE_GRAPHVIZ_MAX_DEPTH) {\n            TREE_GRAPHVIZ_STREAM << \"p\" << std::hex << (unsigned long)this\n                << \" -> \"\n                << \"p\" << std::hex << (unsigned long)left.get()\n                << std::dec << \" [label=\\\"\" << n_samples_left << \"\\\"];\" <<  std::endl;\n            TREE_GRAPHVIZ_STREAM << \"p\" << std::hex << (unsigned long)this\n                << \" -> \"\n                << \"p\" << std::hex << (unsigned long)right.get()\n                << std::dec << \" [label=\\\"\" << n_samples_right << \"\\\"];\" << std::endl;\n        }\n#endif\n        // train left and right side of split\n        left->train (samples, labels, sample_idxes + offset_left,  n_samples_left,  split_generator, gen);\n        right->train(samples, labels, sample_idxes + offset_right, n_samples_right, split_generator, gen);\n    }\n\n#if defined(CGAL_LINKED_WITH_BOOST_IOSTREAMS) && defined(CGAL_LINKED_WITH_BOOST_SERIALIZATION)\n    template <typename Archive>\n    void serialize(Archive& ar, unsigned /*version*/)\n    {\n        ar & BOOST_SERIALIZATION_NVP(is_leaf);\n        ar & BOOST_SERIALIZATION_NVP(n_samples);\n        ar & BOOST_SERIALIZATION_NVP(depth);\n        ar & BOOST_SERIALIZATION_NVP(params);\n        ar & BOOST_SERIALIZATION_NVP(splitter);\n        ar & BOOST_SERIALIZATION_NVP(node_dist);\n        if (!is_leaf)\n        {\n          ar & BOOST_SERIALIZATION_NVP(left);\n          ar & BOOST_SERIALIZATION_NVP(right);\n        }\n    }\n#endif\n\n    void get_feature_usage (std::vector<std::size_t>& count) const\n    {\n      if (!is_leaf)\n      {\n        count[std::size_t(splitter.feature)] ++;\n        left->get_feature_usage(count);\n        right->get_feature_usage(count);\n      }\n    }\n};\n\n}\n}\n\n}} // namespace CGAL::internal::\n\n#endif\n", "meta": {"hexsha": "f510119a557d813fe22f77b4473c78a7246e8526", "size": 9313, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libigl/include/CGAL/Classification/ETHZ/internal/random-forest/node.hpp", "max_stars_repo_name": "sjokic/WallDestruction", "max_stars_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "libigl/include/CGAL/Classification/ETHZ/internal/random-forest/node.hpp", "max_issues_repo_name": "sjokic/WallDestruction", "max_issues_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libigl/include/CGAL/Classification/ETHZ/internal/random-forest/node.hpp", "max_forks_repo_name": "sjokic/WallDestruction", "max_forks_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_forks_repo_licenses": ["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.1135531136, "max_line_length": 116, "alphanum_fraction": 0.5803715237, "num_tokens": 2093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.16685328330911547}}
{"text": "#include \"Fuser.h\"\n\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n\n#include <boost/foreach.hpp>\n\n#include \"Found_NMS.h\"\n\n#include <time.h>\n\nvoid Fuser::Load_Kernel(std::string input, const int in, const int out, float* &h_kernel, float* &d_kernel)\n{\n  std::string input_path;\n  _nh.getParam(input, input_path);\n  std::vector<std::vector<float> > vector_kernel = Populate_Weights(input_path);\n  h_kernel = Columate_Matrix(vector_kernel);\n  d_kernel = cublas_Set_Matrix(h_kernel, in, out);\n}\n\nvoid Fuser::Load_Bias(std::string input, const int out, float* &h_bias, float* &d_bias)\n{\n  std::string input_path;\n  _nh.getParam(input, input_path);\n  std::vector<float> vector_bias = Populate_Biases(input_path);\n  h_bias = Vectorize(vector_bias);\n  d_bias = cublas_Set_Vector(h_bias, out);\n}\n\nvoid Fuser::Load_Layer(std::string input, const int in, const int out, float* &h_kernel, float* &d_kernel, float* &h_bias, float* &d_bias)\n{\n  std::string bias_input, kernel_input;\n\n  bias_input = input + \"_bias\";\n  kernel_input = input + \"_weight\";\n\n  Load_Kernel(kernel_input, in, out, h_kernel, d_kernel);\n  Load_Bias(bias_input, out, h_bias, d_bias);\n}\n\nFuser::Fuser()\n{\n/*\n  Input(s): N/A\n  Output(s): N/A\n  Function: Construct the Fuser object\n*/\n  std::string input_path;\n\n  // Populate the transform matrices to be used\n  _nh.getParam(\"transforms\", input_path);\n  _Tr_velo_to_cam = Populate_Transform(input_path, \"Tr_velo_to_cam: \");\n  _P = Populate_Transform(input_path, \"P2: \");\n  _R = Populate_Transform(input_path, \"R0_rect: \");\n\n  // Populate the class layer in GPU memory\n  Load_Layer(\"class\", _layer1_size, _class_size, _h_class_kernel, _d_class_kernel, _h_class_bias, _d_class_bias);\n\n  // Populate the length layer in GPU memory\n  Load_Layer(\"length\", _layer1_size, _length_size, _h_length_kernel, _d_length_kernel, _h_length_bias, _d_length_bias);\n\n  // Populate the z layer in GPU memory\n  Load_Layer(\"z\", _layer1_size, _z_size, _h_z_kernel, _d_z_kernel, _h_z_bias, _d_z_bias);\n\n  // Populate the hidden layer\n  Load_Layer(\"layer\", _input_size, _layer1_size, _h_layer_kernel, _d_layer_kernel, _h_layer_bias, _d_layer_bias);\n\n  // Populate the rotation layer\n  Load_Layer(\"rotation\", _layer1_size, _rotation_size, _h_rotation_kernel, _d_rotation_kernel, _h_rotation_bias, _d_rotation_bias);\n\n  // Create the CUBLAS handle used in the CUBLAS API\n  cublasCreate(&_cublas_handle);\n\n  // Preallocate space for the outputs of the MLP\n  _d_input = Allocate_MLP(_input_size);\n  _d_layer1_ouput = Allocate_MLP(_layer1_size);\n  _d_class_output = Allocate_MLP(_class_size);\n  _d_z_output = Allocate_MLP(_z_size);\n  _d_length_output = Allocate_MLP(_length_size);\n  _d_rotation_output = Allocate_MLP(_rotation_size);\n\n  _h_input = (float*)malloc(_input_size * sizeof(float));\n}\n\nFuser::~Fuser()\n{\n/*\n  Input(s): N/A\n  Output(s): N/A\n  Function: Destroy the Fuser object\n*/\n  // Destroy the CUBLAS handle\n  cublasDestroy(_cublas_handle);\n\n  // Destroy GPU memory\n  destroy_memory(_d_class_kernel);\n  destroy_memory(_d_length_kernel);\n  destroy_memory(_d_z_kernel);\n  destroy_memory(_d_layer_kernel);\n  destroy_memory(_d_class_bias);\n  destroy_memory(_d_length_bias);\n  destroy_memory(_d_z_bias);\n  destroy_memory(_d_layer_bias);\n  destroy_memory(_d_input);\n  destroy_memory(_d_layer1_ouput);\n  destroy_memory(_d_class_output);\n  destroy_memory(_d_z_output);\n  destroy_memory(_d_length_output);\n  destroy_memory(_d_rotation_output);\n\n  free(_h_input);\n}\n\nvoid Fuser::Publish_Cloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud)\n{\n/*\n  Input(s): Point Cloud colored according to clusters\n  Output(s): N/A\n  Function: Publish a point cloud in ROS\n*/\n  sensor_msgs::PointCloud2 output;\n  pcl::toROSMsg(*cloud, output);\n\n  output.header.frame_id = \"map\";\n\n  _cloud_pub.publish(output);\n}\n\nvoid Fuser::debug_pub(std::vector<Fuser::Sample> samples)\n{\n/*\n  Input(s): Vector of potential samples found in the world\n  Output(s): N/A\n  Function: Combine all clusters from each sample in a single Point Cloud and publish it using ROS\n*/\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);\n\n  int r, g, b;\n  int N = 0;\n  for (int i = 0; i < samples.size(); i++)\n  {\n    r = rand() % 255;\n    g = rand() % 255;\n    b = rand() % 255;\n\n    for (int j = 0; j < samples[i].cluster.size(); j++)\n    {\n      pcl::PointXYZRGB point;\n      point.x = samples[i].cluster[j].x;\n      point.y = samples[i].cluster[j].y;\n      point.z = samples[i].cluster[j].z;\n      point.r = r;\n      point.g = g;\n      point.b = b;\n      cloud->points.push_back(point);\n      N++;\n    }\n  }\n  cloud->height = 1;\n  cloud->width = N;\n\n  Publish_Cloud(cloud);\n}\n\nvoid Fuser::_publish_image(std::vector<detection_fusion::Detection3D> detections)\n{\n/*\n  Input(s): Vector of detections from the output of the fusion algorithm\n  Output(s): N/A\n  Function: Publish an annotated image of the final fused detections from the algorithm\n*/\n  cv::Point p1, p2;\n  cv::Scalar Blue(255, 0, 0);\n  cv::Scalar Green(0, 255, 0);\n  cv::Scalar Red(0, 0, 255);\n\n  int x1, x2, y1, y2;\n\n  for (int i = 0; i < detections.size(); i++)\n  {\n    x1 = detections[i].bbox.x1;\n    x2 = detections[i].bbox.x2;\n    y1 = detections[i].bbox.y1;\n    y2 = detections[i].bbox.y2;\n\n    p1.x = x1;\n    p1.y = y1;\n\n    p2.x = x2;\n    p2.y = y2;\n\n    if (detections[i].bbox.obj_class == 1) { cv::rectangle(_cv_ptr->image, p1, p2, Blue, 3); } //Car\n    else if (detections[i].bbox.obj_class == 2) { cv::rectangle(_cv_ptr->image, p1, p2, Green, 3); } //Pedestrian\n    else if (detections[i].bbox.obj_class == 3) { cv::rectangle(_cv_ptr->image, p1, p2, Red, 3); } //Cyclist\n  }\n\n  cv_bridge::CvImage img_bridge;\n  img_bridge = cv_bridge::CvImage(_cv_ptr->header, _cv_ptr->encoding, _cv_ptr->image);\n\n  sensor_msgs::Image ros_image;\n  img_bridge.toImageMsg(ros_image);\n\n  _image_pub.publish(ros_image);\n}\n\nvoid Fuser::incoming_data_callback(const detection_fusion::Detections_Cloud::ConstPtr& msg)\n{\n/*\n  Input(s): Message recieved from the image only CNN ROS node\n  Output(s): N/A\n  Function: Perform the point cloud processing on the data collected from the world\n*/\n  clock_t tStart = clock();\n\n  // To get the detections from the msg data\n  detection_fusion::Image_Detections detections = msg->detections;\n\n  std::string filename = msg->filename;\n\n  // Get the image from the msg\n  try\n  {\n    _cv_ptr = cv_bridge::toCvCopy(msg->image, sensor_msgs::image_encodings::BGR8);\n  }\n  catch (cv_bridge::Exception& e)\n  {\n    ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n    return;\n  }\n\n  if (detections.detections.size() != 0)\n  {\n    // To populate a point cloud with the msg data\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PCLPointCloud2 pcl_pc2;\n    pcl_conversions::toPCL(msg->pcloud,pcl_pc2);\n    pcl::fromPCLPointCloud2(pcl_pc2,*cloud);\n\n    double t1 = (double)(clock() - tStart)/CLOCKS_PER_SEC;\n\n    // Only reason about points that are roughly in the same space as the image\n    cloud = _mask_cloud(cloud);\n    double t2 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);// - t1;\n\n    // Segment out the ground plane\n    cloud = _segment_ground_plane(cloud);\n    double t3 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);// - t2;\n\n    // Transform the point cloud from LiDAR coordinates to camera coordinates\n    cloud = _transform_coords(cloud);\n    double t4 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);// - t3;\n\n    // Seperate the cloud into clusters\n    std::vector<std::vector<pcl::PointXYZ> > clusters = _cluster_incoming_cloud(cloud);\n    double t5 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);//- t4;\n\n    // Combine clusters and image based detections\n    std::vector<Sample> samples = _filter_clusters(clusters, detections);\n    double t6 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);// - t5;\n\n    // If any clusters and image detections matched up\n    if (samples.size() != 0)\n    {\n      // Perform feature extraction on the clusters\n      samples = _extract_features(samples);\n      double t7 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);// - t6;\n\n      // Run the features through the MLP\n      samples = _classify(samples);\n      double t8 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);// - t7;\n\n      // Adjust the confidence of the image detections based upon the output of the LiDAR MLP\n      std::vector<detection_fusion::Detection3D> combined_detections = _combine_detections(samples);\n      double t9 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);// - t8;\n\n      // Perform  2D NMS on the combined detections\n      std::vector<detection_fusion::Detection3D> fusion_output = _nms(combined_detections);\n      double t10 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);// - t9;\n      double t11 = ((double)(clock() - tStart)/CLOCKS_PER_SEC);\n\n      // Publish the clustered cloud\n      debug_pub(samples);\n\n      // Publish the final annotated image\n      _publish_image(fusion_output);\n\n      // Publish the final output msg of the fusion algorithm of 3D detections\n      if (fusion_output.size() != 0)\n      {\n        detection_fusion::Fusion output_msg;\n        output_msg.detections = fusion_output;\n        output_msg.filename = filename;\n        output_msg.image_detections = detections;\n\n        _fusion_pub.publish(output_msg);\n      }\n      //printf(\"t1=%.2f, t2=%.2f, t3=%.2f, t4=%.2f, t5=%.2f, t6=%.2f, t7=%.2f, t8=%.2f, t9=%.2f, t10=%.2f, t11=%.2f\\n\", t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11);\n      //printf(\"t1=%.4f, t2=%.4f, t3=%.4f, t4=%.4f, t5=%.4f, t6=%.4f, t7=%.4f, t8=%.4f, t9=%.4f, t10=%.4f, t11=%.3f\\n\\n\\n\", t1, t2-t1, t3-t2, t4-t3, t5-t4, t6-t5, t7-t6, t8-t7, t9-t8, t10-t9, t11);\n    }\n  }\n}\n\npcl::PointCloud<pcl::PointXYZ>::Ptr Fuser::_mask_cloud(pcl::PointCloud<pcl::PointXYZ>::Ptr input)\n{\n/*\n  Input(s): Point cloud\n  Output(s): Point cloud\n  Function: Apply a mask to the point cloud that removes points roughly not in the cameras view\n*/\n  pcl::PointCloud<pcl::PointXYZ>::Ptr output (new pcl::PointCloud<pcl::PointXYZ>);\n  float x, y, z, theta;\n  const float theta_thresh = 3.14 / 4;\n  const float theta_middle = 0;\n  for (size_t i = 0; i < input->points.size(); i++)\n  {\n    x = input->points[i].x;\n    y = input->points[i].y;\n    z = input->points[i].z;\n    theta = atan2(y, x);        //IF IN VELO COORDINATES\n    //theta = atan2(x, z);          //IF IN CAMERA COORDINATES\n    if ((theta >= theta_middle - theta_thresh) && (theta <= theta_middle + theta_thresh))\n    {\n      output->points.push_back(input->points[i]);\n    }\n  }\n  output->width = output->points.size ();\n  output->height = 1;\n  output->is_dense = true;\n\n  return output;\n}\n\npcl::PointCloud<pcl::PointXYZ>::Ptr Fuser::_segment_ground_plane(pcl::PointCloud<pcl::PointXYZ>::Ptr input)\n{\n/*\n  Input(s): Point cloud\n  Output(s): Point cloud\n  Function: Segment out the ground plane based on a planar RANSAC model\n\n  http://pointclouds.org/documentation/tutorials/planar_segmentation.php\n*/\n  pcl::PointCloud<pcl::PointXYZ>::Ptr output (new pcl::PointCloud<pcl::PointXYZ>);\n\n  // Do the plane fit\n  pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients);\n  pcl::PointIndices::Ptr inliers (new pcl::PointIndices);\n  // Create the segmentation object\n  pcl::SACSegmentation<pcl::PointXYZ> seg;\n  // Optional\n  seg.setOptimizeCoefficients (true);\n  // Mandatory\n  seg.setModelType (pcl::SACMODEL_PLANE);\n  seg.setMethodType (pcl::SAC_RANSAC);\n  seg.setDistanceThreshold (0.2);\n\n  seg.setInputCloud (input);\n  seg.segment (*inliers, *coefficients);\n\n  if (inliers->indices.size () == 0)\n  {\n    PCL_ERROR (\"Could not estimate a planar model for the given dataset.\");\n  }\n\n\n  // Get all points not in the plane\n  pcl::ExtractIndices<pcl::PointXYZ> extract;\n  extract.setInputCloud (input);\n  extract.setIndices (inliers);\n  extract.setNegative (true);\n  extract.filter (*output);\n\n  return output;\n}\n\npcl::PointCloud<pcl::PointXYZ>::Ptr Fuser::_transform_coords(pcl::PointCloud<pcl::PointXYZ>::Ptr input)\n{\n/*\n  Input(s): Point cloud\n  Output(s): Point cloud\n  Function: Transform the point cloud from LiDAR coordinate frame to camera coordinate frame\n*/\n  Eigen::VectorXd temp(4);\n\n  for (size_t i = 0; i < input->points.size(); i++)\n  {\n    temp(0) = input->points[i].x;\n    temp(1) = input->points[i].y;\n    temp(2) = input->points[i].z;\n    temp(3) = 1;\n\n    temp = _Tr_velo_to_cam * temp;\n\n    input->points[i].x = temp(0);\n    input->points[i].y = temp(1);\n    input->points[i].z = temp(2);\n  }\n\n  return input;\n}\n\nstd::vector<std::vector<pcl::PointXYZ> > Fuser::_cluster_incoming_cloud(pcl::PointCloud<pcl::PointXYZ>::Ptr input)\n{\n/*\n  Input(s): Point cloud\n  Output(s): Vector of clusters which are vectors of points\n  Function: Seperate the cloud into clusters based upon Euclidean distance\n\n  http://www.pointclouds.org/documentation/tutorials/cluster_extraction.php\n*/\n  std::vector<std::vector<pcl::PointXYZ> > output;\n\n  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);\n  tree->setInputCloud (input);\n\n  std::vector<pcl::PointIndices> cluster_indices;\n  pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec;\n  ec.setClusterTolerance (0.25); // 25cm\n  ec.setMinClusterSize (5);\n  //ec.setMinClusterSize (25);\n  //ec.setMaxClusterSize (2500);\n  ec.setMaxClusterSize (25000);\n  ec.setSearchMethod (tree);\n  ec.setInputCloud (input);\n  ec.extract (cluster_indices);\n\n  for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it)\n  {\n    std::vector<pcl::PointXYZ> temp_cluster;\n    for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit)\n    {\n      temp_cluster.push_back(input->points[*pit]);\n    }\n    output.push_back(temp_cluster);\n  }\n\n  return output;\n}\n\nvoid Fuser::Project_Cluster(float x_mean, float y_mean, float z_mean, int &u_centroid, int &v_centroid)\n{\n/*\n  Input(s): The x, y, and z, values of the cluster centroid, the pixel space locations for the centroid\n  Output(s): N/A\n  Function: Find where the cluster would appear in image space\n*/\n  Eigen::VectorXd input(4);\n  Eigen::VectorXd output(3);\n\n  // This is for the shift between camera 0 and camera 2\n  input(0) = x_mean - .06;\n  input(1) = y_mean + .0003;\n  input(2) = z_mean - .0025;\n  input(3) = 1.;\n\n  output = _P * input;\n  //output = _P * _R * input;\n  u_centroid = (int)(output(0) / output(2));\n  v_centroid = (int)(output(1) / output(2));\n}\n\nstd::vector<Fuser::Sample> Fuser::_filter_clusters(std::vector<std::vector<pcl::PointXYZ> > clusters, detection_fusion::Image_Detections detections)\n{\n/*\n  Input(s): Point clusters, image detections\n  Output(s): Combined detections of clusters that are close to the image detections\n  Function: To match up possible image detections with point clusters based upon image space distance\n*/\n  std::vector<Sample> output;\n  float x_mean, y_mean, z_mean;\n  int u_center, v_center;\n  float x_center, y_center;\n  float dist;\n\n  int u_centroid, v_centroid;\n\n  // Compute the centroid of the cluster\n  for (int i = 0; i < clusters.size(); i++)\n  {\n    x_mean = y_mean = z_mean = 0;\n\n    for (int j = 0; j < clusters[i].size(); j++)\n    {\n      x_mean += clusters[i][j].x;\n      y_mean += clusters[i][j].y;\n      z_mean += clusters[i][j].z;\n    }\n    x_mean /= clusters[i].size();\n    y_mean /= clusters[i].size();\n    z_mean /= clusters[i].size();\n\n    // Find the pixel location of the cluster's centroid\n    Project_Cluster(x_mean, y_mean, z_mean, u_centroid, v_centroid);\n\n    for (int j = 0; j < detections.detections.size(); j++)\n    {\n      u_center = (detections.detections[j].x2 + detections.detections[j].x1) / 2;\n      v_center = (detections.detections[j].y2 + detections.detections[j].y1) / 2;\n\n      // Determine the distance of the cluster centroid the the bounding box centroid\n      dist = sqrt(pow(u_center - u_centroid, 2) + pow(v_center - v_centroid, 2));\n      if (dist < _radial_thresh)\n      {\n        Sample iter;\n        iter.cluster = clusters[i];\n        iter.detection = detections.detections[j];\n        output.push_back(iter);\n      }\n    }\n  }\n\n  return output;\n}\n\nstd::vector<Fuser::Sample> Fuser::_extract_features(std::vector<Fuser::Sample> input)\n{\n/*\n  Input(s): Combined clusters and detections\n  Output(s): Combined clusters and detections\n  Function: Extract features from each of the clusters\n*/\n  float x_mean, y_mean, z_mean;\n  float x_sqr, y_sqr, z_sqr;\n  float x_std, y_std, z_std;\n  float x_range, y_range, z_range;\n  float x_y, y_x, x_z, z_x, y_z, z_y;\n\n  float x_min, x_max, y_min, y_max, z_min, z_max;\n\n  int N;\n\n  std::vector<float> cluster_features;\n  for (int i = 0; i < input.size(); i++)\n  {\n    N = input[i].cluster.size();\n    x_mean = y_mean = z_mean = 0;\n    x_sqr = y_sqr = z_sqr = 0;\n    x_std = y_std = z_std = 0;\n    x_range = y_range = z_range = 0;\n    x_y = y_x = x_z = z_x = y_z = z_y = 0;\n    x_min = y_min = z_min = 1000000;\n    x_max = y_max = z_max = -1000000;\n\n    for (int j = 0; j < N; j++)\n    {\n      // X Points\n      x_mean += input[i].cluster[j].x;\n      x_sqr += pow(input[i].cluster[j].x, 2);\n      if (input[i].cluster[j].x < x_min)\n      {\n        x_min = input[i].cluster[j].x;\n      }\n      else if (input[i].cluster[j].x > x_max)\n      {\n        x_max = input[i].cluster[j].x;\n      }\n\n      // Y Points\n      y_mean += input[i].cluster[j].y;\n      y_sqr += pow(input[i].cluster[j].y, 2);\n      if (input[i].cluster[j].y < y_min)\n      {\n        y_min = input[i].cluster[j].y;\n      }\n      else if (input[i].cluster[j].y > y_max)\n      {\n        y_max = input[i].cluster[j].y;\n      }\n\n      // Z Points\n      z_mean += input[i].cluster[j].z;\n      z_sqr += pow(input[i].cluster[j].z, 2);\n      if (input[i].cluster[j].z < z_min)\n      {\n        z_min = input[i].cluster[j].z;\n      }\n      else if (input[i].cluster[j].z > z_max)\n      {\n        z_max = input[i].cluster[j].z;\n      }\n    }\n    x_mean /= N;\n    y_mean /= N;\n    z_mean /= N;\n\n    x_sqr /= N;\n    y_sqr /= N;\n    z_sqr /= N;\n\n    x_std = x_sqr - pow(x_mean, 2);\n    y_std = y_sqr - pow(y_mean, 2);\n    z_std = z_sqr - pow(z_mean, 2);\n\n    x_range = x_max - x_min;\n    y_range = y_max - y_min;\n    z_range = z_max - z_min;\n\n    x_y = x_range / y_range;\n    y_x = y_range / x_range;\n    x_z = x_range / z_range;\n    z_x = z_range / x_range;\n    y_z = y_range / z_range;\n    z_y = z_range / y_range;\n\n    cluster_features.push_back(x_mean);\n    cluster_features.push_back(y_mean);\n    cluster_features.push_back(z_mean);\n\n    cluster_features.push_back(x_std);\n    cluster_features.push_back(y_std);\n    cluster_features.push_back(z_std);\n\n    cluster_features.push_back(x_range);\n    cluster_features.push_back(y_range);\n    cluster_features.push_back(z_range);\n\n    cluster_features.push_back(x_y);\n    cluster_features.push_back(y_x);\n    cluster_features.push_back(x_z);\n    cluster_features.push_back(z_x);\n    cluster_features.push_back(y_z);\n    cluster_features.push_back(z_y);\n\n    input[i].feature = cluster_features;\n    cluster_features.clear();\n  }\n  return input;\n}\n\nstd::vector<Fuser::Sample> Fuser::_classify(std::vector<Fuser::Sample> input)\n{\n/*\n  Input(s): Combined clusters and detections\n  Output(s): Combined clusters and detections\n  Function: Push each cluster feature vector through the MLP and populate the output\n*/\n  std::vector<float> temp;\n  for (int i = 0; i < _input_size; i++)\n  {\n    temp.push_back((float)i);\n  }\n\n  for (int i = 0; i < input.size(); i++)\n  {\n    cublas_Set_Input(_h_input, input[i].feature, _d_input, _input_size);\n\n    blas_layer(_d_input, _d_layer_kernel, _d_layer_bias, _d_layer1_ouput, _layer1_size, _input_size, _cublas_handle);\n    RELU(_d_layer1_ouput, _layer1_size);\n\n    blas_layer(_d_layer1_ouput, _d_class_kernel, _d_class_bias, _d_class_output, _class_size, _layer1_size, _cublas_handle);\n    Softmax(_d_class_output, _class_size);\n\n    blas_layer(_d_layer1_ouput, _d_length_kernel, _d_length_bias, _d_length_output, _length_size, _layer1_size, _cublas_handle);\n    Sigmoid(_d_length_output, _length_size);\n\n    blas_layer(_d_layer1_ouput, _d_z_kernel, _d_z_bias, _d_z_output, _z_size, _layer1_size, _cublas_handle);\n    Sigmoid(_d_z_output, _z_size);\n\n    blas_layer(_d_layer1_ouput, _d_rotation_kernel, _d_rotation_bias, _d_rotation_output, _rotation_size, _layer1_size, _cublas_handle);\n\n    classification_output iter_output = populate_output(_d_class_output, _d_length_output, _d_z_output, _d_rotation_output);\n    input[i].output = iter_output;\n  }\n\n  return input;\n}\n\nstd::vector<detection_fusion::Detection3D> Fuser::_combine_detections(std::vector<Fuser::Sample> input)\n{\n/*\n  Input(s): Combined clusters and detections\n  Output(s): 3D detections\n  Function: Filter out detections and clusters that do not agree and adjust confidence of those that do\n*/\n  std::vector<detection_fusion::Detection3D> output;\n\n  detection_fusion::BBox2D camera_detection;\n  classification_output lidar_detection;\n  std::vector<float> feature;\n\n  int camera_class, lidar_class;\n  float camera_prob, lidar_prob;\n\n  detection_fusion::Detection3D iter;\n\n  for (int i = 0; i < input.size(); i++)\n  {\n    camera_detection = input[i].detection;\n    lidar_detection = input[i].output;\n    feature = input[i].feature;\n\n    camera_class = camera_detection.obj_class;\n    lidar_class = lidar_detection.obj_class;\n\n    camera_prob = camera_detection.probability;\n    lidar_prob = lidar_detection.probability;\n\n    if (camera_class == lidar_class)\n    {\n      iter.bbox = camera_detection;\n      iter.x = feature[0];\n      iter.y = feature[1];\n      iter.z = lidar_detection.z * _scale;\n      iter.w = feature[6];\n      iter.h = feature[7];\n      iter.l = lidar_detection.l * _scale;\n      iter.a = lidar_detection.a * _rotation_scale;\n\n\n      iter.bbox.probability += .5;\n      if (iter.bbox.probability > 1.) iter.bbox.probability = 1.0;\n\n      output.push_back(iter);\n    }\n    else\n    { continue; }\n  }\n\n  return output;\n}\n\nstd::vector<detection_fusion::Detection3D> Fuser::_nms(std::vector<detection_fusion::Detection3D> temp_input)\n{\n/*\n  Input(s): 3D detections\n  Output(s): Final 3D detections\n  Function: Convert box forms to run the NMS algorithm on the detections\n*/\n  std::vector<detection_fusion::Detection3D> output;\n  for (int i = 0; i < temp_input.size(); i ++)\n  {\n    if (temp_input[i].bbox.probability > .6)\n    {\n      output.push_back(temp_input[i]);\n    }\n  }\n\n  std::vector<std::vector<float> > temp_boxes;\n  std::vector<float> temp;\n  float x1, x2, y1, y2;\n  for (int i = 0; i < output.size(); i++)\n  {\n    x1 = (float)output[i].bbox.x1;\n    x2 = (float)output[i].bbox.x2;\n    y1 = (float)output[i].bbox.y1;\n    y2 = (float)output[i].bbox.y2;\n\n    temp.push_back(x1);\n    temp.push_back(y1);\n    temp.push_back(x2);\n    temp.push_back(y2);\n    temp_boxes.push_back(temp);\n    temp.clear();\n  }\n  std::vector<cv::Rect> reducedRectangle = nms(temp_boxes, .3);\n\n  int nms_x1, nms_x2, nms_y1, nms_y2, box_x1, box_x2, box_y1, box_y2;\n  std::vector<detection_fusion::Detection3D> real_output;\n  for (int i = 0; i < reducedRectangle.size(); i++)\n  {\n    for (int j = 0; j < output.size(); j++)\n    {\n      nms_x1 = (int)reducedRectangle[i].x;\n      nms_x2 = (int)reducedRectangle[i].width + nms_x1;\n      nms_y1 = (int)reducedRectangle[i].y;\n      nms_y2 = (int)reducedRectangle[i].height + nms_y1;\n      box_x1 = output[j].bbox.x1;\n      box_x2 = output[j].bbox.x2;\n      box_y1 = output[j].bbox.y1;\n      box_y2 = output[j].bbox.y2;\n      if (box_x1 == nms_x1 && box_y1 == nms_y1 && box_x2 == nms_x2 && box_y2 == nms_y2)\n      {\n        real_output.push_back(output[j]);\n      }\n    }\n  }\n\n  return real_output;\n}\n", "meta": {"hexsha": "b1db834b8ad5546b94c22d194a9011708bc87d9e", "size": 23657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/Detection_Fusion/src/Fuser.cpp", "max_stars_repo_name": "MichaelX99/Camera_LiDAR_Fusion", "max_stars_repo_head_hexsha": "24927aaaa818c8fc3dc5aa714d807a27c719e4ac", "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": "catkin_ws/src/Detection_Fusion/src/Fuser.cpp", "max_issues_repo_name": "MichaelX99/Camera_LiDAR_Fusion", "max_issues_repo_head_hexsha": "24927aaaa818c8fc3dc5aa714d807a27c719e4ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-30T13:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T14:59:39.000Z", "max_forks_repo_path": "catkin_ws/src/Detection_Fusion/src/Fuser.cpp", "max_forks_repo_name": "MichaelX99/Camera_LiDAR_Fusion", "max_forks_repo_head_hexsha": "24927aaaa818c8fc3dc5aa714d807a27c719e4ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-04-18T14:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-18T14:50:46.000Z", "avg_line_length": 30.3684210526, "max_line_length": 197, "alphanum_fraction": 0.6700342393, "num_tokens": 6909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.16685328330911547}}
{"text": "//\n// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)\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#ifndef BEAST_WEBSOCKET_DETAIL_MASK_HPP\n#define BEAST_WEBSOCKET_DETAIL_MASK_HPP\n\n#include <boost/asio/buffer.hpp>\n#include <array>\n#include <climits>\n#include <cstdint>\n#include <random>\n#include <type_traits>\n\nnamespace beast {\nnamespace websocket {\nnamespace detail {\n\n// Pseudo-random source of mask keys\n//\ntemplate<class Generator>\nclass maskgen_t\n{\n    Generator g_;\n\npublic:\n    using result_type =\n        typename Generator::result_type;\n\n    maskgen_t();\n\n    result_type\n    operator()() noexcept;\n\n    void\n    rekey();\n};\n\ntemplate<class Generator>\nmaskgen_t<Generator>::maskgen_t()\n{\n    rekey();\n}\n\ntemplate<class Generator>\nauto\nmaskgen_t<Generator>::operator()() noexcept ->\n    result_type\n{\n    for(;;)\n        if(auto key = g_())\n            return key;\n}\n\ntemplate<class _>\nvoid\nmaskgen_t<_>::rekey()\n{\n    std::random_device rng;\n#if 0\n    std::array<std::uint32_t, 32> e;\n    for(auto& i : e)\n        i = rng();\n    // VFALCO This constructor causes\n    //        address sanitizer to fail, no idea why.\n    std::seed_seq ss(e.begin(), e.end());\n    g_.seed(ss);\n#else\n    g_.seed(rng());\n#endif\n}\n\n// VFALCO NOTE This generator has 5KB of state!\n//using maskgen = maskgen_t<std::mt19937>;\nusing maskgen = maskgen_t<std::minstd_rand>;\n\n//------------------------------------------------------------------------------\n\nusing prepared_key =\n    std::conditional<sizeof(void*) == 8,\n        std::uint64_t, std::uint32_t>::type;\n\ninline\nvoid\nprepare_key(std::uint32_t& prepared, std::uint32_t key)\n{\n    prepared = key;\n}\n\ninline\nvoid\nprepare_key(std::uint64_t& prepared, std::uint32_t key)\n{\n    prepared =\n        (static_cast<std::uint64_t>(key) << 32) | key;\n}\n\ntemplate<class T>\ninline\ntypename std::enable_if<std::is_integral<T>::value, T>::type\nror(T t, unsigned n = 1)\n{\n    auto constexpr bits =\n        static_cast<unsigned>(\n            sizeof(T) * CHAR_BIT);\n    n &= bits-1;\n    return static_cast<T>((t << (bits - n)) | (\n        static_cast<typename std::make_unsigned<T>::type>(t) >> n));\n}\n\n// 32-bit optimized\n//\ntemplate<class = void>\nvoid\nmask_inplace_fast(\n    boost::asio::mutable_buffer const& b,\n        std::uint32_t& key)\n{\n    using boost::asio::buffer_cast;\n    using boost::asio::buffer_size;\n    auto n = buffer_size(b);\n    auto p = buffer_cast<std::uint8_t*>(b);\n    if(n >= sizeof(key))\n    {\n        // Bring p to 4-byte alignment\n        auto const i = reinterpret_cast<\n            std::uintptr_t>(p) & (sizeof(key)-1);\n        switch(i)\n        {\n        case 1: p[2] ^= static_cast<std::uint8_t>(key >> 16);\n        case 2: p[1] ^= static_cast<std::uint8_t>(key >> 8);\n        case 3: p[0] ^= static_cast<std::uint8_t>(key);\n        {\n            auto const d = static_cast<\n                unsigned>(sizeof(key) - i);\n            key = ror(key, 8*d);\n            n -= d;\n            p += d;\n        }\n        default:\n            break;\n        }\n    }\n\n    // Mask 4 bytes at a time\n    for(auto i = n / sizeof(key); i; --i)\n    {\n        *reinterpret_cast<\n            std::uint32_t*>(p) ^= key;\n        p += sizeof(key);\n    }\n\n    // Leftovers\n    n &= sizeof(key)-1;\n    switch(n)\n    {\n    case 3: p[2] ^= static_cast<std::uint8_t>(key >> 16);\n    case 2: p[1] ^= static_cast<std::uint8_t>(key >> 8);\n    case 1: p[0] ^= static_cast<std::uint8_t>(key);\n        key = ror(key, static_cast<unsigned>(8*n));\n    default:\n        break;\n    }\n}\n\n// 64-bit optimized\n//\ntemplate<class = void>\nvoid\nmask_inplace_fast(\n    boost::asio::mutable_buffer const& b,\n        std::uint64_t& key)\n{\n    using boost::asio::buffer_cast;\n    using boost::asio::buffer_size;\n    auto n = buffer_size(b);\n    auto p = buffer_cast<std::uint8_t*>(b);\n    if(n >= sizeof(key))\n    {\n        // Bring p to 8-byte alignment\n        auto const i = reinterpret_cast<\n            std::uintptr_t>(p) & (sizeof(key)-1);\n        switch(i)\n        {\n        case 1: p[6] ^= static_cast<std::uint8_t>(key >> 48);\n        case 2: p[5] ^= static_cast<std::uint8_t>(key >> 40);\n        case 3: p[4] ^= static_cast<std::uint8_t>(key >> 32);\n        case 4: p[3] ^= static_cast<std::uint8_t>(key >> 24);\n        case 5: p[2] ^= static_cast<std::uint8_t>(key >> 16);\n        case 6: p[1] ^= static_cast<std::uint8_t>(key >> 8);\n        case 7: p[0] ^= static_cast<std::uint8_t>(key);\n        {\n            auto const d = static_cast<\n                unsigned>(sizeof(key) - i);\n            key = ror(key, 8*d);\n            n -= d;\n            p += d;\n        }\n        default:\n            break;\n        }\n    }\n\n    // Mask 8 bytes at a time\n    for(auto i = n / sizeof(key); i; --i)\n    {\n        *reinterpret_cast<\n            std::uint64_t*>(p) ^= key;\n        p += sizeof(key);\n    }\n\n    // Leftovers\n    n &= sizeof(key)-1;\n    switch(n)\n    {\n    case 7: p[6] ^= static_cast<std::uint8_t>(key >> 48);\n    case 6: p[5] ^= static_cast<std::uint8_t>(key >> 40);\n    case 5: p[4] ^= static_cast<std::uint8_t>(key >> 32);\n    case 4: p[3] ^= static_cast<std::uint8_t>(key >> 24);\n    case 3: p[2] ^= static_cast<std::uint8_t>(key >> 16);\n    case 2: p[1] ^= static_cast<std::uint8_t>(key >> 8);\n    case 1: p[0] ^= static_cast<std::uint8_t>(key);\n        key = ror(key, static_cast<unsigned>(8*n));\n    default:\n        break;\n    }\n}\n\ninline\nvoid\nmask_inplace(\n    boost::asio::mutable_buffer const& b,\n        std::uint32_t& key)\n{\n    mask_inplace_fast(b, key);\n}\n\ninline\nvoid\nmask_inplace(\n    boost::asio::mutable_buffer const& b,\n        std::uint64_t& key)\n{\n    mask_inplace_fast(b, key);\n}\n\n// Apply mask in place\n//\ntemplate<class MutableBuffers, class KeyType>\nvoid\nmask_inplace(\n    MutableBuffers const& bs, KeyType& key)\n{\n    for(auto const& b : bs)\n        mask_inplace(b, key);\n}\n\n} // detail\n} // websocket\n} // beast\n\n#endif\n", "meta": {"hexsha": "fdb8e86f49add1ba7bcfdb740fbbce3229a47574", "size": 6012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/beast/include/beast/websocket/detail/mask.hpp", "max_stars_repo_name": "MassICTBV/casinocoind", "max_stars_repo_head_hexsha": "81d6a15a0578c086c1812dd2203c0973099b0061", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-02-15T23:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-16T19:51:46.000Z", "max_issues_repo_path": "src/beast/include/beast/websocket/detail/mask.hpp", "max_issues_repo_name": "MassICTBV/casinocoind", "max_issues_repo_head_hexsha": "81d6a15a0578c086c1812dd2203c0973099b0061", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-06-06T13:03:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-22T17:03:05.000Z", "max_forks_repo_path": "src/beast/include/beast/websocket/detail/mask.hpp", "max_forks_repo_name": "MassICTBV/casinocoind", "max_forks_repo_head_hexsha": "81d6a15a0578c086c1812dd2203c0973099b0061", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T12:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T07:44:49.000Z", "avg_line_length": 22.6015037594, "max_line_length": 80, "alphanum_fraction": 0.5652029275, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.16685327998303132}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 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_ACCUMULATORS_BLOCK_HPP\n#define CRYPTO3_ACCUMULATORS_BLOCK_HPP\n\n#include <boost/container/static_vector.hpp>\n\n#include <boost/parameter/value_type.hpp>\n\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n\n#include <nil/crypto3/detail/make_array.hpp>\n#include <nil/crypto3/detail/digest.hpp>\n#include <nil/crypto3/detail/inject.hpp>\n\n#include <nil/crypto3/block/accumulators/bits_count.hpp>\n\n#include <nil/crypto3/block/accumulators/parameters/cipher.hpp>\n#include <nil/crypto3/block/accumulators/parameters/bits.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <nil/crypto3/block/detail/cipher_modes.hpp>\n\n#include <nil/crypto3/block/cipher.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace accumulators {\n            namespace impl {\n                template<typename Mode>\n                struct block_impl : boost::accumulators::accumulator_base {\n                protected:\n                    typedef Mode mode_type;\n                    typedef typename Mode::cipher_type cipher_type;\n                    typedef typename Mode::padding_type padding_type;\n\n                    typedef typename mode_type::endian_type endian_type;\n\n                    constexpr static const std::size_t word_bits = mode_type::word_bits;\n                    typedef typename mode_type::word_type word_type;\n\n                    constexpr static const std::size_t block_bits = mode_type::block_bits;\n                    constexpr static const std::size_t block_words = mode_type::block_words;\n                    typedef typename mode_type::block_type block_type;\n\n                    constexpr static const std::size_t value_bits = sizeof(typename block_type::value_type) * CHAR_BIT;\n                    constexpr static const std::size_t block_values = block_bits / value_bits;\n\n                    typedef ::nil::crypto3::detail::injector<endian_type, value_bits, block_values, block_bits>\n                        injector_type;\n\n                public:\n                    typedef digest<block_bits> result_type;\n\n                    template<typename Args>\n                    block_impl(const Args &args) :\n                        total_seen(0), filled(false), mode(args[boost::accumulators::sample]) {\n                    }\n\n                    template<typename ArgumentPack>\n                    inline void operator()(const ArgumentPack &args) {\n                        resolve_type(args[boost::accumulators::sample],\n                                     args[::nil::crypto3::accumulators::bits | std::size_t()]);\n                    }\n\n                    inline result_type result(boost::accumulators::dont_care) const {\n                        using namespace ::nil::crypto3::detail;\n\n                        result_type res = dgst;\n\n                        block_type processed_block = mode.end_message(cache, total_seen);\n\n                        res = ::nil::crypto3::resize<block_bits>(res, res.size() + block_values);\n\n                        pack<endian_type, endian_type, value_bits, octet_bits>(\n                            processed_block.begin(), processed_block.end(), res.end() - block_values);\n\n                        return res;\n                    }\n\n                protected:\n                    inline void resolve_type(const block_type &value, std::size_t bits) {\n                        process(value, bits == 0 ? block_bits : bits);\n                    }\n\n                    inline void resolve_type(const word_type &value, std::size_t bits) {\n                        process(value, bits == 0 ? word_bits : bits);\n                    }\n\n                    inline void process_block() {\n                        using namespace ::nil::crypto3::detail;\n\n                        block_type processed_block;\n                        if (dgst.empty()) {\n                            processed_block = mode.begin_message(cache, total_seen);\n                        } else {\n                            processed_block = mode.process_block(cache, total_seen);\n                        }\n\n                        dgst = ::nil::crypto3::resize<block_bits>(dgst, dgst.size() + block_values);\n\n                        pack<endian_type, endian_type, value_bits, octet_bits>(\n                            processed_block.begin(), processed_block.end(), dgst.end() - block_values);\n\n                        filled = false;\n                    }\n\n                    inline void process(const block_type &value, std::size_t value_seen) {\n                        using namespace ::nil::crypto3::detail;\n\n                        if (filled) {\n                            process_block();\n                        }\n\n                        std::size_t cached_bits = total_seen % block_bits;\n\n                        if (cached_bits != 0) {\n                            // If there are already any bits in the cache\n\n                            std::size_t needed_to_fill_bits = block_bits - cached_bits;\n                            std::size_t new_bits_to_append =\n                                (needed_to_fill_bits > value_seen) ? value_seen : needed_to_fill_bits;\n\n                            injector_type::inject(value, new_bits_to_append, cache, cached_bits);\n                            total_seen += new_bits_to_append;\n\n                            if (cached_bits == block_bits) {\n                                // If there are enough bits in the incoming value to fill the block\n                                filled = true;\n\n                                if (value_seen > new_bits_to_append) {\n\n                                    process_block();\n\n                                    // If there are some remaining bits in the incoming value - put them into the cache,\n                                    // which is now empty\n\n                                    cached_bits = 0;\n\n                                    injector_type::inject(value, value_seen - new_bits_to_append, cache, cached_bits,\n                                                          new_bits_to_append);\n\n                                    total_seen += value_seen - new_bits_to_append;\n                                }\n                            }\n\n                        } else {\n\n                            total_seen += value_seen;\n\n                            // If there are no bits in the cache\n                            if (value_seen == block_bits) {\n                                // The incoming value is a full block\n                                filled = true;\n\n                                std::move(value.begin(), value.end(), cache.begin());\n\n                            } else {\n                                // The incoming value is not a full block\n                                std::move(value.begin(),\n                                          value.begin() + value_seen / word_bits + (value_seen % word_bits ? 1 : 0),\n                                          cache.begin());\n                            }\n                        }\n                    }\n\n                    inline void process(const word_type &value, std::size_t value_seen) {\n                        using namespace ::nil::crypto3::detail;\n\n                        if (filled) {\n                            process_block();\n                        }\n\n                        std::size_t cached_bits = total_seen % block_bits;\n\n                        if (cached_bits % word_bits != 0) {\n                            std::size_t needed_to_fill_bits = block_bits - cached_bits;\n                            std::size_t new_bits_to_append =\n                                (needed_to_fill_bits > value_seen) ? value_seen : needed_to_fill_bits;\n\n                            injector_type::inject(value, new_bits_to_append, cache, cached_bits);\n                            total_seen += new_bits_to_append;\n\n                            if (cached_bits == block_bits) {\n                                // If there are enough bits in the incoming value to fill the block\n\n                                filled = true;\n\n                                if (value_seen > new_bits_to_append) {\n\n                                    process_block();\n\n                                    // If there are some remaining bits in the incoming value - put them into the cache,\n                                    // which is now empty\n                                    cached_bits = 0;\n\n                                    injector_type::inject(value, value_seen - new_bits_to_append, cache, cached_bits,\n                                                          new_bits_to_append);\n\n                                    total_seen += value_seen - new_bits_to_append;\n                                }\n                            }\n\n                        } else {\n                            cache[cached_bits / word_bits] = value;\n\n                            total_seen += value_seen;\n                        }\n                    }\n\n                    mode_type mode;\n\n                    bool filled;\n                    std::size_t total_seen;\n                    block_type cache;\n                    result_type dgst;\n                };\n            }    // namespace impl\n\n            namespace tag {\n                template<typename Mode>\n                struct block : boost::accumulators::depends_on<bits_count> {\n                    typedef Mode mode_type;\n\n                    /// INTERNAL ONLY\n                    ///\n\n                    typedef boost::mpl::always<accumulators::impl::block_impl<mode_type>> impl;\n                };\n            }    // namespace tag\n\n            namespace extract {\n                template<typename Mode, typename AccumulatorSet>\n                typename boost::mpl::apply<AccumulatorSet, tag::block<Mode>>::type::result_type\n                    block(const AccumulatorSet &acc) {\n                    return boost::accumulators::extract_result<tag::block<Mode>>(acc);\n                }\n            }    // namespace extract\n        }        // namespace accumulators\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_ACCUMULATORS_BLOCK_HPP\n", "meta": {"hexsha": "e919deee715497dff5ed3d219d8d5142426b3f68", "size": 11661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/block/accumulators/block.hpp", "max_stars_repo_name": "NilFoundation/crypto3-block", "max_stars_repo_head_hexsha": "94f9cc42ac0fa62c5ee54e7d678abf48ffa9eec5", "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/block/accumulators/block.hpp", "max_issues_repo_name": "tonlabs/crypto3-block", "max_issues_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-16T18:04:20.000Z", "max_forks_repo_path": "include/nil/crypto3/block/accumulators/block.hpp", "max_forks_repo_name": "tonlabs/crypto3-block", "max_forks_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T21:47:05.000Z", "avg_line_length": 43.5111940299, "max_line_length": 120, "alphanum_fraction": 0.5044164308, "num_tokens": 1967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33111972642778714, "lm_q1q2_score": 0.166853273330863}}
{"text": "// -*- C++ -*-\n//\n// Copyright Sylvain Bougerel 2009 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file COPYING or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_DYN_LINK\n#define SPATIAL_ENABLE_ASSERT // detect interal issues that should not occur\n\n#include <boost/test/unit_test.hpp>\n#include <utility> // std::make_pair\n#include \"../../src/idle_box_multimap.hpp\"\n#include \"spatial_test_types.hpp\"\n\nusing namespace spatial;\n\nBOOST_AUTO_TEST_CASE( test_idle_box_map_constructors )\n{\n  idle_box_multimap<2, int2, int> idle_boxes;\n  idle_box_multimap<0, int2, int> runtime_idle_boxes;\n}\n\nBOOST_AUTO_TEST_CASE( test_idle_box_map_copy_assignment )\n{\n  idle_box_multimap<2, int2, int> idle_boxes;\n  idle_boxes.insert(std::make_pair(zeros, 0));\n  idle_boxes.insert(std::make_pair(ones, 1));\n  idle_boxes.insert(std::make_pair(twos, 2));\n  idle_box_multimap<2, int2, int> copy(idle_boxes);\n  BOOST_CHECK_EQUAL(idle_boxes.size(), copy.size());\n  BOOST_CHECK(*idle_boxes.begin() == *copy.begin());\n  idle_boxes = copy;\n  BOOST_CHECK_EQUAL(idle_boxes.size(), copy.size());\n  BOOST_CHECK(*idle_boxes.begin() == *copy.begin());\n}\n\nBOOST_AUTO_TEST_CASE( test_zero_idle_box_map_copy_assignment )\n{\n  idle_box_multimap<0, int2, int> idle_boxes;\n  idle_boxes.insert(std::make_pair(zeros, 0));\n  idle_boxes.insert(std::make_pair(ones, 1));\n  idle_boxes.insert(std::make_pair(twos, 2));\n  idle_box_multimap<0, int2, int> copy(idle_boxes);\n  BOOST_CHECK_EQUAL(idle_boxes.size(), copy.size());\n  BOOST_CHECK(*idle_boxes.begin() == *copy.begin());\n  idle_boxes = copy;\n  BOOST_CHECK_EQUAL(idle_boxes.size(), copy.size());\n  BOOST_CHECK(*idle_boxes.begin() == *copy.begin());\n}\n", "meta": {"hexsha": "5a0a359f78f3b1f19b9b8429b58f10bbc72a5a79", "size": 1723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/verify/verify_idle_box_multimap.cpp", "max_stars_repo_name": "Roboauto/spatial", "max_stars_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-12-07T02:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T05:39:05.000Z", "max_issues_repo_path": "tests/verify/verify_idle_box_multimap.cpp", "max_issues_repo_name": "Roboauto/spatial", "max_issues_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-28T15:07:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T15:07:42.000Z", "max_forks_repo_path": "tests/verify/verify_idle_box_multimap.cpp", "max_forks_repo_name": "Roboauto/spatial", "max_forks_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T13:30:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:22:03.000Z", "avg_line_length": 33.7843137255, "max_line_length": 76, "alphanum_fraction": 0.7411491584, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33111972642778714, "lm_q1q2_score": 0.166853273330863}}
{"text": "// TODO Rewrite these tests once the 'MultiReaderPointSource' can work with\n// in-memory files\n\n// #include \"catch.hpp\"\n\n// #include \"datastructures/SparseGrid.h\"\n// #include \"io/BinaryPersistence.h\"\n// #include \"io/MemoryPersistence.h\"\n// #include \"process/Tiler.h\"\n// #include \"tiling/OctreeAlgorithms.h\"\n// #include <debug/ProgressReporter.h>\n\n// #include <boost/algorithm/string/predicate.hpp>\n// #include <boost/format.hpp>\n// #include <boost/functional/hash.hpp>\n// #include <boost/scope_exit.hpp>\n// #include <random>\n// #include <unordered_set>\n\n// namespace std {\n// template<>\n// struct hash<Vector3<double>>\n// {\n//   typedef Vector3<double> argument_type;\n//   typedef std::size_t result_type;\n\n//   result_type operator()(Vector3<double> const& s) const noexcept\n//   {\n//     size_t seed = std::hash<double>{}(s.x);\n//     boost::hash_combine(seed, std::hash<double>{}(s.y));\n//     boost::hash_combine(seed, std::hash<double>{}(s.z));\n//     return seed;\n//   }\n// };\n// } // namespace std\n\n// static PointBuffer\n// create_random_dataset(size_t num_points)\n// {\n//   std::default_random_engine rnd{ static_cast<uint32_t>(time(nullptr)) };\n//   std::uniform_real_distribution<float> dist;\n\n//   // Create num_points random points in [0;1]\u00b3\n//   std::vector<Vector3<double>> positions;\n//   positions.reserve(num_points);\n//   std::generate_n(std::back_inserter(positions), num_points, [&]() ->\n//   Vector3<double> {\n//     return { dist(rnd), dist(rnd), dist(rnd) };\n//   });\n\n//   PointBuffer point_buffer{ num_points, std::move(positions) };\n//   return point_buffer;\n// }\n\n// // static bool\n// // points_obey_minimum_distance(const PointBuffer& points, const AABB&\n// bounds,\n// // float min_distance)\n// // {\n// //   SparseGrid grid{ bounds, min_distance };\n\n// //   for (auto& pos : points.positions()) {\n// //     if (!grid.add(pos))\n// //       return false;\n// //   }\n// //   return true;\n// // }\n\n// static bool\n// points_are_contained_in_bounds(const PointBuffer& points,\n//                                const AABB& bounds,\n//                                Vector3<double>* fail_point = nullptr)\n// {\n//   for (auto& pos : points.positions()) {\n//     if (!bounds.isInside(pos)) {\n//       if (fail_point) {\n//         *fail_point = pos;\n//       }\n//       return false;\n//     }\n//   }\n//   return true;\n// }\n\n// TEST_CASE(\"Tiler works\", \"[Tiler]\")\n// {\n//   constexpr size_t NumPoints = 1'000'000;\n//   constexpr size_t MaxPointsPerNode = 20'000;\n\n//   const auto dataset = create_random_dataset(NumPoints);\n//   AABB bounds{ { 0, 0, 0 }, { 1, 1, 1 } };\n//   auto spacing_at_root = 0.1f;\n//   const auto sampling_strategy =\n//   make_sampling_strategy<RandomSortedGridSampling>(MaxPointsPerNode);\n//   PointsPersistence persistence{ MemoryPersistence{} };\n\n//   TilerMetaParameters tiler_meta_parameters;\n//   tiler_meta_parameters.spacing_at_root = spacing_at_root;\n//   tiler_meta_parameters.max_depth = 40;\n//   tiler_meta_parameters.max_points_per_node = MaxPointsPerNode;\n//   tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal\n//   cache size to guarantee\n//                                                        // out-of-core\n//                                                        processing\n\n//   Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr,\n//   persistence, \".\" };\n\n//   writer.cache(dataset);\n//   writer.index();\n//   writer.close();\n\n//   // Two properties have to hold:\n//   //  1) The converter processes and stores ALL points (except when the tree\n//   is\n//   //  too shallow due to max_depth) 2) All points of each node must be\n//   contained\n//   //  within the bounds of their respective node\n\n//   // There is also the spacing property (min distance), however this depends\n//   on\n//   // the sampling strategy used. The naive version of my algorithm uses the\n//   // 'random sorted grid' approach, which can result in arbitrarily close\n//   // points. Once other sampling strategies are implemented, there will be\n//   tests\n//   // for their correctness!\n\n//   // For fast matching of processed points with existing points we use\n//   // unordered_set\n//   std::unordered_set<Vector3<double>> expected_points;\n//   expected_points.reserve(NumPoints);\n//   for (auto& pos : dataset.positions()) {\n//     expected_points.insert(pos);\n//   }\n\n//   const auto processed_points =\n//   persistence.get<MemoryPersistence>().get_points(); for (auto& kv :\n//   processed_points) {\n//     const auto& node_name = kv.first;\n//     const auto& points = kv.second;\n\n//     const auto node_key = from_string<21>(node_name);\n//     const auto node_level = node_name.size() - 1; // Node level, root = -1\n//     const auto node_bounds = get_bounds_from_morton_index(node_key, bounds,\n//     node_level);\n//     // const auto min_distance_at_node = spacing_at_root / std::pow(2,\n//     // node_level + 1); REQUIRE(points_obey_minimum_distance(points,\n//     // node_bounds, min_distance_at_node));\n//     REQUIRE(points_are_contained_in_bounds(points, node_bounds));\n\n//     for (auto& pos : points.positions()) {\n//       const auto point_iter = expected_points.find(pos);\n//       const auto point_exists_in_dataset = (expected_points.find(pos) !=\n//       expected_points.end()); REQUIRE(point_exists_in_dataset);\n//       expected_points.erase(point_iter); // Make sure we don't allow\n//       duplicate points!\n//     }\n//   }\n\n//   const auto num_processed_points = (dataset.count() -\n//   expected_points.size()); REQUIRE(num_processed_points == NumPoints);\n// }\n\n// TEST_CASE(\"Tiler with deep tree works\", \"[Tiler]\")\n// {\n//   constexpr size_t NumPoints = 1'000'000;\n//   constexpr size_t MaxPointsPerNode = 20'000;\n\n//   const auto dataset = create_random_dataset(NumPoints);\n//   // Very large bounds will force the octree to become deeper than the 21\n//   levels\n//   // that MortonIndex64 can support. This should trigger the re-indexing\n//   // mechanism, which is what we want to test with this test case! What we\n//   don't\n//   // want is dropped points, everything should still be indexed correctly!\n//   AABB bounds{ { 0, 0, 0 }, { 1 << 20, 1 << 20, 1 << 20 } };\n//   auto spacing_at_root = (1 << 20) / 10.f;\n//   const auto sampling_strategy =\n//   make_sampling_strategy<RandomSortedGridSampling>(MaxPointsPerNode);\n//   PointsPersistence persistence{ MemoryPersistence{} };\n\n//   TilerMetaParameters tiler_meta_parameters;\n//   tiler_meta_parameters.spacing_at_root = spacing_at_root;\n//   tiler_meta_parameters.max_depth = 40;\n//   tiler_meta_parameters.max_points_per_node = MaxPointsPerNode;\n//   tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal\n//   cache size to guarantee\n//                                                        // out-of-core\n//                                                        processing\n//   Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr,\n//   persistence, \".\" };\n\n//   writer.cache(dataset);\n//   writer.index();\n//   writer.close();\n\n//   // Two properties have to hold:\n//   //  1) The converter processes and stores ALL points (except when the tree\n//   is\n//   //  too shallow due to max_depth) 2) All points of each node must be\n//   contained\n//   //  within the bounds of their respective node\n\n//   // There is also the spacing property (min distance), however this depends\n//   on\n//   // the sampling strategy used. The naive version of my algorithm uses the\n//   // 'random sorted grid' approach, which can result in arbitrarily close\n//   // points. Once other sampling strategies are implemented, there will be\n//   tests\n//   // for their correctness!\n\n//   // For fast matching of processed points with existing points we use\n//   // unordered_set\n//   std::unordered_set<Vector3<double>> expected_points;\n//   expected_points.reserve(NumPoints);\n//   for (auto& pos : dataset.positions()) {\n//     expected_points.insert(pos);\n//   }\n\n//   const auto processed_points =\n//   persistence.get<MemoryPersistence>().get_points(); for (auto& kv :\n//   processed_points) {\n//     const auto& node_name = kv.first;\n//     const auto& points = kv.second;\n\n//     const auto node_key = from_string<21>(node_name);\n//     const auto node_level = node_name.size() - 1; // Node level, root = -1\n//     const auto node_bounds = get_bounds_from_morton_index(node_key, bounds,\n//     node_level);\n//     // const auto min_distance_at_node = spacing_at_root / std::pow(2,\n//     // node_level + 1); REQUIRE(points_obey_minimum_distance(points,\n//     // node_bounds, min_distance_at_node));\n//     REQUIRE(points_are_contained_in_bounds(points, node_bounds));\n\n//     for (auto& pos : points.positions()) {\n//       const auto point_iter = expected_points.find(pos);\n//       const auto point_exists_in_dataset = (expected_points.find(pos) !=\n//       expected_points.end()); REQUIRE(point_exists_in_dataset);\n//       expected_points.erase(point_iter); // Make sure we don't allow\n//       duplicate points!\n//     }\n//   }\n\n//   const auto num_processed_points = (dataset.count() -\n//   expected_points.size()); REQUIRE(num_processed_points == NumPoints);\n// }\n\n// TEST_CASE(\"Tiler with GridCenter sampling\", \"[Tiler]\")\n// {\n//   constexpr size_t NumPoints = 1'000'000;\n//   constexpr size_t MaxPointsPerNode = 20'000;\n\n//   const auto dataset = create_random_dataset(NumPoints);\n//   AABB bounds{ { 0, 0, 0 }, { 1, 1, 1 } };\n//   auto spacing_at_root = 0.1f;\n//   const auto sampling_strategy =\n//   make_sampling_strategy<GridCenterSampling>(MaxPointsPerNode);\n//   PointsPersistence persistence{ MemoryPersistence{} };\n\n//   TilerMetaParameters tiler_meta_parameters;\n//   tiler_meta_parameters.spacing_at_root = spacing_at_root;\n//   tiler_meta_parameters.max_depth = 40;\n//   tiler_meta_parameters.max_points_per_node = MaxPointsPerNode;\n//   tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal\n//   cache size to guarantee\n//                                                        // out-of-core\n//                                                        processing\n//   Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr,\n//   persistence, \".\" };\n\n//   writer.cache(dataset);\n//   writer.index();\n//   writer.close();\n\n//   // Two properties have to hold:\n//   //  1) The converter processes and stores ALL points (except when the tree\n//   is\n//   //  too shallow due to max_depth) 2) All points of each node must be\n//   contained\n//   //  within the bounds of their respective node\n\n//   // For fast matching of processed points with existing points we use\n//   // unordered_set\n//   std::unordered_set<Vector3<double>> expected_points;\n//   expected_points.reserve(NumPoints);\n//   for (auto& pos : dataset.positions()) {\n//     expected_points.insert(pos);\n//   }\n\n//   const auto processed_points =\n//   persistence.get<MemoryPersistence>().get_points(); for (auto& kv :\n//   processed_points) {\n//     const auto& node_name = kv.first;\n//     const auto& points = kv.second;\n\n//     const auto node_key = from_string<21>(node_name);\n//     const auto node_level = node_name.size() - 1; // Node level, root = -1\n//     const auto node_bounds = get_bounds_from_morton_index(node_key, bounds,\n//     node_level);\n//     // const auto min_distance_at_node = spacing_at_root / std::pow(2,\n//     // node_level + 1); REQUIRE(points_obey_minimum_distance(points,\n//     // node_bounds, min_distance_at_node));\n//     REQUIRE(points_are_contained_in_bounds(points, node_bounds));\n\n//     for (auto& pos : points.positions()) {\n//       const auto point_iter = expected_points.find(pos);\n//       const auto point_exists_in_dataset = (expected_points.find(pos) !=\n//       expected_points.end()); REQUIRE(point_exists_in_dataset);\n//       expected_points.erase(point_iter); // Make sure we don't allow\n//       duplicate points!\n//     }\n//   }\n\n//   const auto num_processed_points = (dataset.count() -\n//   expected_points.size()); REQUIRE(num_processed_points == NumPoints);\n// }\n\n// TEST_CASE(\"Tiler with PossionDisk sampling\", \"[Tiler]\")\n// {\n//   constexpr size_t NumPoints = 1'000'000;\n//   constexpr size_t MaxPointsPerNode = 20'000;\n\n//   const auto dataset = create_random_dataset(NumPoints);\n//   AABB bounds{ { 0, 0, 0 }, { 1, 1, 1 } };\n//   auto spacing_at_root = 0.05f;\n//   const auto sampling_strategy =\n//   make_sampling_strategy<PoissonDiskSampling>(MaxPointsPerNode);\n//   PointsPersistence persistence{ MemoryPersistence{} };\n\n//   TilerMetaParameters tiler_meta_parameters;\n//   tiler_meta_parameters.spacing_at_root = spacing_at_root;\n//   tiler_meta_parameters.max_depth = 40;\n//   tiler_meta_parameters.max_points_per_node = MaxPointsPerNode;\n//   tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal\n//   cache size to guarantee\n//                                                        // out-of-core\n//                                                        processing\n\n//   Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr,\n//   persistence, \".\" };\n\n//   writer.cache(dataset);\n//   writer.index();\n//   writer.close();\n\n//   // Two properties have to hold:\n//   //  1) The converter processes and stores ALL points (except when the tree\n//   is\n//   //  too shallow due to max_depth) 2) All points of each node must be\n//   contained\n//   //  within the bounds of their respective node\n\n//   // For fast matching of processed points with existing points we use\n//   // unordered_set\n//   std::unordered_set<Vector3<double>> expected_points;\n//   expected_points.reserve(NumPoints);\n//   for (auto& pos : dataset.positions()) {\n//     expected_points.insert(pos);\n//   }\n\n//   const auto points_obey_minimum_distance =\n//     [](const auto& points, const auto& bounds, double min_distance) -> bool {\n//     SparseGrid grid{ bounds, static_cast<float>(min_distance) };\n//     for (auto& point : points) {\n//       if (!grid.add(point))\n//         return false;\n//     }\n//     return true;\n//   };\n\n//   const auto is_leaf_node = [](const std::string& node_name, const auto&\n//   all_nodes) {\n//     for (auto& kv : all_nodes) {\n//       const auto& other_node_name = kv.first;\n//       if (other_node_name.size() != (node_name.size() + 1))\n//         continue;\n//       if (boost::starts_with(other_node_name, node_name))\n//         return false;\n//     }\n//     return true;\n//   };\n\n//   const auto processed_points =\n//   persistence.get<MemoryPersistence>().get_points(); for (auto& kv :\n//   processed_points) {\n//     const auto& node_name = kv.first;\n//     const auto& points = kv.second;\n\n//     const auto node_key = from_string<21>(node_name);\n//     const auto node_level = static_cast<int32_t>(node_name.size()) - 2; //\n//     Node level, root = -1 const auto node_bounds =\n//     get_bounds_from_morton_index(node_key, bounds, node_level + 1); const\n//     auto min_distance_at_node = spacing_at_root / std::pow(2, node_level +\n//     1);\n\n//     const auto is_leaf = is_leaf_node(node_name, processed_points);\n//     if (!is_leaf) {\n//       REQUIRE(points_obey_minimum_distance(points.positions(), node_bounds,\n//       min_distance_at_node));\n//     }\n//     Vector3<double> fail_point;\n//     const auto points_all_contained =\n//       points_are_contained_in_bounds(points, node_bounds, &fail_point);\n//     if (!points_all_contained) {\n//       UNSCOPED_INFO(\"Position \" << fail_point.x << \" \" << fail_point.y << \" \"\n//       << fail_point.z\n//                                 << \" not contained in bounds!\");\n//     }\n//     REQUIRE(points_all_contained);\n\n//     for (auto& pos : points.positions()) {\n//       const auto point_iter = expected_points.find(pos);\n//       const auto point_exists_in_dataset = (expected_points.find(pos) !=\n//       expected_points.end()); REQUIRE(point_exists_in_dataset);\n//       expected_points.erase(point_iter); // Make sure we don't allow\n//       duplicate points!\n//     }\n//   }\n\n//   const auto num_processed_points = (dataset.count() -\n//   expected_points.size()); REQUIRE(num_processed_points == NumPoints);\n// }\n\n// TEST_CASE(\"Tiler with BinaryPersistence writer\", \"[Tiler]\")\n// {\n//   constexpr size_t NumPoints = 1'000'000;\n//   constexpr size_t MaxPointsPerNode = 20'000;\n\n//   const auto dataset = create_random_dataset(NumPoints);\n//   AABB bounds{ { 0, 0, 0 }, { 1, 1, 1 } };\n//   auto spacing_at_root = 0.1f;\n//   const auto sampling_strategy =\n//   make_sampling_strategy<RandomSortedGridSampling>(MaxPointsPerNode);\n//   // MemoryPersistence persistence;\n//   PointAttributes attributes;\n//   attributes.insert(PointAttribute::Position);\n\n//   const auto tmp_directory =\n//     (boost::format(\"./tmp_%1%\") %\n//      (std::chrono::high_resolution_clock::now().time_since_epoch().count()))\n//       .str();\n//   if (!fs::exists(tmp_directory)) {\n//     if (!fs::create_directories(tmp_directory)) {\n//       FAIL(\"Could not create temporary output directory\");\n//     }\n//   }\n\n//   BOOST_SCOPE_EXIT(&tmp_directory)\n//   {\n//     std::error_code ec;\n//     fs::remove_all(tmp_directory, ec);\n//     if (ec) {\n//       UNSCOPED_INFO(\"Could not remove temporary output directory\");\n//     }\n//   }\n//   BOOST_SCOPE_EXIT_END\n\n//   PointsPersistence persistence{ BinaryPersistence{ tmp_directory, attributes\n//   } };\n\n//   TilerMetaParameters tiler_meta_parameters;\n//   tiler_meta_parameters.spacing_at_root = spacing_at_root;\n//   tiler_meta_parameters.max_depth = 40;\n//   tiler_meta_parameters.max_points_per_node = MaxPointsPerNode;\n//   tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal\n//   cache size to guarantee\n//                                                        // out-of-core\n//                                                        processing\n\n//   Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr,\n//   persistence, \".\" };\n\n//   writer.cache(dataset);\n//   writer.index();\n//   writer.close();\n// }\n", "meta": {"hexsha": "3ce9681d61a403f9610c09575378d4c40eda99ff", "size": 17966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "schwarzwald/test/TestTiler.cpp", "max_stars_repo_name": "igd-geo/schwarzwald", "max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z", "max_issues_repo_path": "schwarzwald/test/TestTiler.cpp", "max_issues_repo_name": "igd-geo/schwarzwald", "max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z", "max_forks_repo_path": "schwarzwald/test/TestTiler.cpp", "max_forks_repo_name": "igd-geo/schwarzwald", "max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z", "avg_line_length": 37.6645702306, "max_line_length": 80, "alphanum_fraction": 0.6472225314, "num_tokens": 4336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.16682658980236753}}
{"text": "#include \"Connection.h\"\r\n#include <boost/range/algorithm.hpp>\r\n\r\n#include \"Angle.h\"\r\n#include \"Quaternion.h\"\r\n#include \"Part.h\"\r\n#include \"Vector.h\"\r\n\r\nvoid Connection::connectTo(Connection *targetCon)\r\n{\r\n\tQuaternion targetQuat(targetCon->angles());\r\n\r\n\ttargetQuat = targetQuat * Quaternion{ 0, 0, 1, 0 };\r\n\r\n\tAngle newAngle = angles();\r\n\r\n\tauto rotmat = newAngle.calcRotation(targetQuat);\r\n\r\n\tparent->rotate(rotmat);\r\n\tVector mov = Vector::diff(origin(), targetCon->origin());\r\n\tparent->move(mov);\r\n\r\n\tneighbour = targetCon;\r\n\ttargetCon->neighbour = this;\r\n}\r\n\r\nbool Connection::isConnected() const\r\n{\r\n\treturn neighbour != nullptr;\r\n}\r\n\r\nConnection::Connection(Entity&& entity)\r\n{\r\n\tthis->solids = std::move(entity.solids);\r\n\tthis->keyvals = std::move(entity.keyvals);\r\n\tif (keyvals.count(\"classname\") > 0)\r\n\t{\r\n\t\tstd::string val = keyvals[\"classname\"];\r\n\r\n\t\tif (val.length() > 12)\r\n\t\t\tconnectstr = val.substr(12);\r\n\t}\r\n}\r\n", "meta": {"hexsha": "135b196d7e3d1cc1c0b47bb23508dab0f4078160", "size": 926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rndlevelsource/Connection.cpp", "max_stars_repo_name": "Telefragged/rndlevelsource", "max_stars_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "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": "rndlevelsource/Connection.cpp", "max_issues_repo_name": "Telefragged/rndlevelsource", "max_issues_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rndlevelsource/Connection.cpp", "max_forks_repo_name": "Telefragged/rndlevelsource", "max_forks_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_forks_repo_licenses": ["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.0454545455, "max_line_length": 59, "alphanum_fraction": 0.6641468683, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.1668265898023675}}
{"text": "/**\n ** Copyright (c) 2014 Illumina, Inc.\n **\n ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE),\n ** covered by the \"BSD 2-Clause License\" (see accompanying LICENSE file)\n **\n ** \\author Lilian Janin\n **/\n\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/bind.hpp>\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"common/Exceptions.hh\"\n#include \"io/Text.hh\"\n#include \"model/Phred.hh\"\n#include \"genome/QualityModel.hh\"\n#include \"libzoo/util/AutoGrowVector.hh\"\n\nusing namespace std;\n\n//#define DEBUG_QUALITIES\n\n\nnamespace eagle\n{\nnamespace genome\n{\n\nclass MyDiscreteDist\n{\npublic:\n    MyDiscreteDist() {}\n\n    MyDiscreteDist( const vector<double> w )\n    {\n        setWeights( w );\n    }\n\n    void setWeights( const vector<double> w )\n    {\n        weights_.reserve( w.size() );\n        double sum = std::accumulate( w.begin(), w.end(), 0.0 );\n        double cur = 0;\n        for (unsigned int i=0; i<w.size(); ++i)\n        {\n            cur += w[i];\n            weights_.push_back( cur?cur/sum:-1 );\n        }\n    }\n\n    unsigned int operator()( const double val ) {\n        vector<double>::iterator it = lower_bound( weights_.begin(), weights_.end(), val );\n        if ( it != weights_.end() )\n            return (&*it - &weights_[0]);\n        else\n            return weights_.size() - 1;\n    }\n\nprivate:\n    vector<double> weights_;\n};\n\n\nQualityModel::QualityModel( const vector<boost::filesystem::path>& qualityTableFiles )\n{ \n    useNewStuff_ = false;\n    if (useNewStuff_)\n    {\n        parseBigQualityTableFile( qualityTableFiles.front() );\n        return;\n    }\n    unsigned int lastCycle = 0;\n    BOOST_FOREACH( const boost::filesystem::path& file, qualityTableFiles)\n    {\n        lastCycle = parseQualityTableFile( file, lastCycle );\n    }\n}\n\nunsigned int QualityModel::parseBigQualityTableFile( const boost::filesystem::path& filename )\n{\n    assert (useNewStuff_);\n    unsigned long totalSize = boost::filesystem::file_size( filename );\n    bigTable_.resize( totalSize / sizeof(unsigned int) );\n    ifstream is( filename.string().c_str(), ios_base::binary );\n    is.read( reinterpret_cast<char*>(&bigTable_[0]), totalSize );\n    return 0;\n}\n\nunsigned int QualityModel::parseQualityTableFile( const boost::filesystem::path& filename, const int cycleOffset )\n// Returns last cycle processed + 1 (= first cycle of next file to process)\n{\n    assert (!useNewStuff_);\n\n    io::DsvReader tsvReader( filename );\n    vector<string> tokens;\n    unsigned int cycle = cycleOffset;\n/*\n    double overallExpectedErrors = 0.0;\n    double overallOutOf = 0.0;\n    double overallExpectedErrorsForCurrentRead = 0.0;\n    double overallOutOfForCurrentRead = 0.0;\n*/\n\n    if ( boost::algorithm::ends_with( filename.string(), \".qtable2\" ) )\n    {\n        // Parsing of new file format\n\n        AutoGrowVector< AutoGrowVector< AutoGrowVector< double > > > qualityTable;\n        while( tsvReader.getNextLineFields<'\\t'>(tokens) )\n        {\n            assert( tokens.size() >= 3 && \"Quality table should have at least 3 entries per line (profileId, cycle, and 1 or more quality:count)\" );\n\n            unsigned int profileId = boost::lexical_cast<unsigned int>( tokens[0] );\n            cycle = boost::lexical_cast<unsigned int>( tokens[1] );\n            if (cycle == 0 && profileId == 0)\n            {\n                cycle = 1; // just a convention that profileId 0 and cycle 1 determines the proportion of profileIds\n            }\n            assert( cycle > 0 ); // cycles are 1-based by convention\n            cycle += cycleOffset;\n\n            for (unsigned int i=2; i<tokens.size(); ++i)\n            {\n                if ( tokens[i].empty() )\n                    continue;\n\n                unsigned int quality;\n                double count = 0;\n                istringstream ss( tokens[i] );\n                char colon;\n                ss >> quality >> colon >> count;\n                assert( colon == ':' && count > 0 && \"quality:count pairs must be separated by ':' in quality table files\" );\n                qualityTable[profileId][cycle][quality] = count;\n            }\n\n            // Extend quality vector as appropriate\n            if (qualityDistPerCyclePerLastQuality.size() <= cycle)\n            {\n                qualityDistPerCyclePerLastQuality.resize( cycle+1 );\n            }\n            if (qualityDistPerCyclePerLastQuality[cycle].size() <= profileId)\n            {\n                qualityDistPerCyclePerLastQuality[cycle].resize( profileId+1 );\n            }\n            qualityDistPerCyclePerLastQuality[cycle][profileId] = boost::random::discrete_distribution<>(qualityTable[profileId][cycle]);\n        }\n        return cycle;\n    }\n\n    // Parsing of old file format\n    while( tsvReader.getNextLineFields<'\\t'>(tokens) )\n    {\n        assert( (tokens.size() == 43 || tokens.size() == 53) && \"Quality table should have 43 or 53 entries per line\" );\n\n        cycle = boost::lexical_cast<unsigned int>( tokens[0] );\n        assert( cycle > 0 ); // cycles are 1-based by convention\n        cycle += cycleOffset;\n        unsigned int lastQ = boost::lexical_cast<unsigned int>( tokens[1] );\n\n        vector<double> values;\n        try\n        {\n            std::transform( tokens.begin()+2, tokens.end(), std::back_inserter(values), boost::bind( &boost::lexical_cast<double,std::string>, _1) );\n        }\n        catch (const boost::bad_lexical_cast &e)\n        {\n            EAGLE_ERROR(\"Error while reading quality table: a numerical field seems to contain non-numerical characters\");\n        }\n        assert( values.size() == 41 || values.size() == 51 );\n\n        // Ensure that the distribution to determine the quality level cannot generate a value of zero\n        if (lastQ==0 && values[0]!=0)\n        {\n            EAGLE_ERROR(\"Error while reading quality table: Column 3 must be zero if column 2 is zero (the distribution to determine the quality level cannot generate a value of zero)\");\n        }\n\n        // Extend quality vector as appropriate\n        if (qualityDistPerCyclePerLastQuality.size() <= cycle)\n        {\n            qualityDistPerCyclePerLastQuality.resize( cycle+1 );\n        }\n        if (qualityDistPerCyclePerLastQuality[cycle].size() <= lastQ)\n        {\n            qualityDistPerCyclePerLastQuality[cycle].resize( lastQ+1 );\n        }\n        qualityDistPerCyclePerLastQuality[cycle][lastQ] = boost::random::discrete_distribution<>(values);\n/*\n        // Expected errors statistics\n        double expectedErrors = 0.0;\n        double outOf = 0.0;\n\n        if (cycle==102 && lastQ==0)\n        {\n            cout << (boost::format(\"Quality stats for read 1: expected mismatch rate = %f%%\") % (100.0*overallExpectedErrorsForCurrentRead/overallOutOfForCurrentRead) ).str() << endl;\n            overallExpectedErrorsForCurrentRead = 0.0;\n            overallOutOfForCurrentRead = 0.0;\n        }\n\n        for (unsigned int qValue=0; qValue<=40; ++qValue)\n        {\n            double qCount = values[qValue];\n            expectedErrors += qValue?(model::Phred::qualToProb(qValue)*qCount):0; // don't include Q0 in error count\n            outOf += qCount;\n#ifdef DEBUG_QUALITIES\n            cout << (boost::format(\"Q=%d count=%d => error-rate=%f => %f expected mismatches out of %f bases = %f%%\") % qValue % qCount % qualToProb(qValue) % expectedErrors % outOf % (100.0*expectedErrors/outOf) ).str() << endl;\n#endif // DEBUG_QUALITIES\n        }\n\n        if (outOf > 0)\n        {\n            overallExpectedErrors += expectedErrors;\n            overallOutOf += outOf;\n            overallExpectedErrorsForCurrentRead += expectedErrors;\n            overallOutOfForCurrentRead += outOf;\n        }\n#ifdef DEBUG_QUALITIES\n        cout << (boost::format(\"Quality stats for cycle %d: %f expected mismatches out of %f bases = %f%%\") % cycle % expectedErrors % outOf % (100.0*expectedErrors/outOf) ).str() << endl;\n        cout << (boost::format(\"Quality stats over all cycles : %f expected mismatches out of %f bases = %f%%\") % overallExpectedErrors % overallOutOf % (100.0*overallExpectedErrors/overallOutOf) ).str() << endl;\n#endif // DEBUG_QUALITIES\n*/\n    }\n/*\n    cout << (boost::format(\"Quality stats for read 2: expected mismatch rate = %f%%\") % (100.0*overallExpectedErrorsForCurrentRead/overallOutOfForCurrentRead) ).str() << endl;\n    cout << (boost::format(\"Quality stats overall   : expected mismatch rate = %f%%\") % (100.0*overallExpectedErrors/overallOutOf) ).str() << endl;\n*/\n    return cycle;\n}\n\n/*\nstatic int Qbins[41] = {\n        0, 0, 0, 0, 1, 1, 1, 1, 1, 1,\n        2, 2, 2, 2, 2, 2, 2, 2, 2, 3,\n        3, 3, 3, 3, 3, 4, 4, 4, 4, 4,\n        4, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7 };\nstatic int bin2Q[8] = { 0, 6, 15, 22, 27, 33, 37, 40 };\n*/\n\n/*\nunsigned int QualityModel::getQuality( boost::mt19937& randomGen, const unsigned int cycle, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext )\n{\n    unsigned int result = bin2Q[ 5 ];\n    assert (useNewStuff_);\n\n    unsigned int cycleNum = cycle;\n    unsigned int precedingKmer = clusterErrorModelContext.qualityModelContext.kmer & 0x3FF;\n    unsigned int newBaseNum = bclBase;\n    unsigned int prevQualityBin = Qbins[ clusterErrorModelContext.qualityModelContext.profileNumber ];\n    vector<unsigned int> counts(8);\n    unsigned int sum = 0;\n    for (unsigned int newQualityBin = 0; newQualityBin<8; ++newQualityBin)\n    {\n//        assert( cycleNum >= 1 && cycleNum <= cycleCount );\n        assert( precedingKmer < 1024 );\n        assert( newBaseNum < 4 );\n        assert( prevQualityBin < 8 );\n        assert( newQualityBin < 8 );\n        unsigned int entryNum =\n            (cycleNum-1) * (1024*4*8*8) + \n            precedingKmer * (4*8*8) +\n            newBaseNum * (8*8) +\n            prevQualityBin * (8) +\n            newQualityBin;\n        assert( entryNum < bigTable_.size() );\n        unsigned int val = bigTable_[entryNum];\n        counts[newQualityBin] = val;\n        sum += val;\n    }\n\n    if (sum != 0)\n    {\n        unsigned int rnd = (unsigned int)( (double)randomGen() / randomGen.max() * sum );\n        for (unsigned int newQualityBin = 0; newQualityBin<8; ++newQualityBin)\n        {\n            if (rnd >= counts[newQualityBin])\n            {\n                rnd -= counts[newQualityBin];\n            }\n            else\n            {\n                result = bin2Q[ newQualityBin ];\n                break;\n            }\n        }\n    }\n    else\n    {\n        result = bin2Q[ 5 ]; //clusterErrorModelContext.qualityModelContext.profileNumber;\n    }\n\n    clusterErrorModelContext.qualityModelContext.kmer = (clusterErrorModelContext.qualityModelContext.kmer << 2 ) | (bclBase & 3);\n    clusterErrorModelContext.qualityModelContext.profileNumber = result;\n\n    return result;\n}\n*/\n\nunsigned int QualityModel::getQuality( boost::mt19937& randomGen, const unsigned int cycle, ClusterErrorModelContext& clusterErrorModelContext )\n{\n    assert (!useNewStuff_);\n\n    if (cycle >= qualityDistPerCyclePerLastQuality.size())\n    {\n        EAGLE_ERROR( \"The quality table doesn't model as many cycles as necessary for this simulation\" );\n    }\n\n    if (clusterErrorModelContext.qualityModelContext.profileNumber == 0)\n    {\n        // No profile number assigned to this read => find the last cycle containing a profile spec and use it\n        unsigned int cycleForProfileNumber = cycle;\n        while (qualityDistPerCyclePerLastQuality[cycleForProfileNumber][0].max() == 0)\n        {\n            if (cycleForProfileNumber == 0)\n            {\n                EAGLE_ERROR(\"Cannot find quality level distribution in quality tables (there should at least be an entry for {cycle=0, profile=0})\");\n            }\n            --cycleForProfileNumber;\n        }\n        clusterErrorModelContext.qualityModelContext.profileNumber = qualityDistPerCyclePerLastQuality[cycleForProfileNumber][0](randomGen);\n        assert( clusterErrorModelContext.qualityModelContext.profileNumber > 0 );\n    }\n    unsigned int profileNumber = clusterErrorModelContext.qualityModelContext.profileNumber;\n    assert( profileNumber > 0 );\n    if (profileNumber >= qualityDistPerCyclePerLastQuality[cycle].size())\n    {\n        EAGLE_ERROR( (boost::format(\"The quality table doesn't contain the required entry for {cycle=%d, profileNumber=%d}\") % cycle % profileNumber).str() );\n    }\n    unsigned int quality = qualityDistPerCyclePerLastQuality[cycle][profileNumber](randomGen);\n\n#ifdef DEBUG_QUALITIES\n    cout << (boost::format(\"Q=%d => error-rate=%f\") % quality % model::Phred::qualToProb(quality)).str() << endl;\n#endif // DEBUG_QUALITIES\n    return quality;\n}\n\n\nSequencingMismatchModel::SequencingMismatchModel( const boost::filesystem::path& mismatchTableFilename )\n{\n    // Mismatch model for base 'x': x->A, x->C, x->G, x->T, del, x->insertedA, x->insertedC, x->insertedG, x->insertedT (dup=='x->insertedx')\n    // Parse mismatch table file: each line based on the model, for x={A,C,G,T}\n    if (mismatchTableFilename == \"\")\n    { // Use default values\n        vector< double > errorA = boost::assign::list_of(0.0)(1.0)(1.0)(1.0)(0.0)(0.0)(0.0)(0.0)(0.0);\n        vector< double > errorC = boost::assign::list_of(1.0)(0.0)(1.0)(1.0)(0.0)(0.0)(0.0)(0.0)(0.0);\n        vector< double > errorG = boost::assign::list_of(1.0)(1.0)(0.0)(1.0)(0.0)(0.0)(0.0)(0.0)(0.0);\n        vector< double > errorT = boost::assign::list_of(1.0)(1.0)(1.0)(0.0)(0.0)(0.0)(0.0)(0.0)(0.0);\n\n        errorDistPerBase.push_back( boost::random::discrete_distribution<>(errorA) );\n        errorDistPerBase.push_back( boost::random::discrete_distribution<>(errorC) );\n        errorDistPerBase.push_back( boost::random::discrete_distribution<>(errorG) );\n        errorDistPerBase.push_back( boost::random::discrete_distribution<>(errorT) );\n    }\n    else\n    { // Parse mismatch table file\n        io::DsvReader tsvReader( mismatchTableFilename );\n        vector<string> tokens;\n        const vector<string> expectedRowHeaders = boost::assign::list_of(\"A\")(\"C\")(\"G\")(\"T\");\n        BOOST_FOREACH( const string& expectedRowHeader, expectedRowHeaders)\n        {\n            (void)expectedRowHeader; // prevents \"unused variable\" warning when asserts are not compiled\n            tsvReader.getNextLineFields<'\\t'>(tokens);\n            assert( tokens.size() == 10 && \"There should be 10 entries per line\" );\n            assert( tokens[0] == expectedRowHeader && \"Unexpected value in first column (The first 4 entries - ignoring the lines starting with '#' - should be A,C,G,T)\" );\n            vector<double> values;\n            try\n            {\n                std::transform( tokens.begin()+1, tokens.end(), std::back_inserter(values), boost::bind( &boost::lexical_cast<double,std::string>, _1) );\n            }\n            catch (const boost::bad_lexical_cast &e)\n            {\n                EAGLE_ERROR(\"Error while reading mismatch table: a numerical field seems to contain non-numerical characters\");\n            }\n            assert( values.size() == 9 );\n            errorDistPerBase.push_back( boost::random::discrete_distribution<>(values) );\n        }\n    }\n}\n\nvoid SequencingMismatchModel::apply( boost::mt19937& randomGen, const double errorRate, unsigned int& randomErrorType, char& bclBase, ClusterErrorModelContext& clusterErrorModelContext )\n{\n    if (randomGen() > errorRate * randomGen.max())\n    {\n        randomErrorType = ErrorModel::NoError;\n    }\n    else\n    {\n        unsigned char errorType = errorDistPerBase[bclBase](randomGen);\n        switch (errorType)\n        {\n        case 0: // x->A\n        case 1: // x->C\n        case 2: // x->G\n        case 3: // x->T\n            randomErrorType = ErrorModel::BaseSubstitution;\n            bclBase = errorType;\n            break;\n\n        case 4: // del\n            randomErrorType = ErrorModel::BaseDeletion;\n            break;\n\n        case 5: // x->insertedA\n        case 6: // x->insertedC\n        case 7: // x->insertedG\n        case 8: // x->insertedT\n            randomErrorType = ErrorModel::BaseInsertion;\n            bclBase = errorType-5;\n            break;\n\n        default:\n            assert( false );\n        }\n    }\n\n#ifdef DEBUG_QUALITIES\n    // Debugging stats\n    static unsigned long mismatches = 0;\n    static unsigned long noMismatches = 0;\n    if (randomErrorType == ErrorModel::NoError)\n    {\n        noMismatches++;\n    }\n    else\n    {\n        mismatches++;\n    }\n    cout << (boost::format(\"mismatch rate = %d mismatches and %d noMismatch out of %d => %f%%\") % mismatches % noMismatches % (mismatches + noMismatches) % (100.0*(float)mismatches/(float)(mismatches + noMismatches))).str() << endl;\n#endif // DEBUG_QUALITIES\n}\n\n\nHomopolymerIndelModel::HomopolymerIndelModel( const boost::filesystem::path& homopolymerIndelTableFilename )\n{\n    if (homopolymerIndelTableFilename == \"\")\n    { // Use default values: no indels\n        homoDeletionTable_.push_back(0.0);\n        homoInsertionTable_.push_back(0.0); // homopolymer of size 0 or more\n    }\n    else\n    { // Parse homopolymer indel table file\n        io::DsvReader tsvReader( homopolymerIndelTableFilename );\n        vector<string> tokens;\n        while ( tsvReader.getNextLineFields<'\\t'>(tokens) )\n        {\n            if ( tokens.size() == 0 ) { continue; }\n            assert ( tokens.size() == 3 && \"There should be 3 entries per line\" );\n            vector<double> values;\n            try\n            {\n                std::transform( tokens.begin(), tokens.end(), std::back_inserter(values), boost::bind( &boost::lexical_cast<double,std::string>, _1) );\n            }\n            catch (const boost::bad_lexical_cast &e)\n            {\n                EAGLE_ERROR(\"Error while reading homopolymer indel table: a numerical field seems to contain non-numerical characters\");\n            }\n            assert( values.size() == 3 );\n            assert( values[0] == homoDeletionTable_.size() && values[0] == homoInsertionTable_.size() && \"First column should contain consecutive numbers starting from 0\" );\n            homoDeletionTable_.push_back ( values[1] );\n            homoInsertionTable_.push_back( values[2] );\n        }\n    }\n}\n\nvoid HomopolymerIndelModel::apply( boost::mt19937& randomGen, const double errorRate, unsigned int& randomErrorType, char& bclBase, ClusterErrorModelContext& clusterErrorModelContext )\n{\n    if (bclBase != clusterErrorModelContext.homopolymerModelContext.lastBase)\n    {\n        clusterErrorModelContext.homopolymerModelContext.lastBase = bclBase;\n        clusterErrorModelContext.homopolymerModelContext.homopolymerLength = 1;\n    }\n    else\n    {\n        ++(clusterErrorModelContext.homopolymerModelContext.homopolymerLength);\n        unsigned int length = clusterErrorModelContext.homopolymerModelContext.homopolymerLength;\n        assert( length >= 1 );\n        unsigned int tableEntry = std::min<unsigned int>( length, homoDeletionTable_.size()-1 );\n        double delErrorRate = homoDeletionTable_ [tableEntry];\n        double insErrorRate = homoInsertionTable_[tableEntry];\n        double randomValue = (double)randomGen() / (double)randomGen.max();\n        switch (clusterErrorModelContext.homopolymerModelContext.errorDirection)\n        {\n        case 0: // This homopolymer didn't get any insertion or deletion yet\n            if (randomValue < delErrorRate )\n            {\n                randomErrorType = ErrorModel::BaseDeletion;\n                clusterErrorModelContext.homopolymerModelContext.errorDirection = -1;\n            }\n            else if (randomValue < delErrorRate + insErrorRate )\n            {\n                randomErrorType = ErrorModel::BaseInsertion;\n                clusterErrorModelContext.homopolymerModelContext.errorDirection = +1;\n            }\n            break;\n        case +1: // This homopolymer already got one or more insertions\n            if (randomValue < insErrorRate )\n            {\n                randomErrorType = ErrorModel::BaseInsertion;\n            }\n            break;\n        case -1: // This homopolymer already got one or more deletions\n            if (randomValue < delErrorRate )\n            {\n                randomErrorType = ErrorModel::BaseDeletion;\n            }\n            break;\n        }\n    }\n}\n\n\nclass MotifRepeatQualityDropInfo\n{\npublic:\n   MotifRepeatQualityDropInfo()\n       : meanQualityDrop( 0 )\n        {}\n\n    float meanQualityDrop;\n    MyDiscreteDist distribution;\n};\n\neagle::model::IUPAC baseConverter_;\n\nuint64_t kmerStringToInt64( const string &s )\n{\n    uint64_t result = 0;\n    for (unsigned int i=0; i<s.size(); ++i)\n    {\n        unsigned int binValue;\n        if (s[i]>='0' && s[i] <='3')\n            binValue = s[i] - '0';\n        else\n            binValue = baseConverter_.bin(s[i]);\n        result = (result << 2) | binValue;\n    }\n    return result;\n}\n\n#define MAX_MOTIF_KMER_LENGTH 10\n#define AVERAGE_QUALITY 34\nMotifQualityDropModel::MotifQualityDropModel( const boost::filesystem::path& tableFilename )\n    : active_( false )\n{\n    if (tableFilename != \"\")\n    {\n        tableData_.resize( MAX_MOTIF_KMER_LENGTH+1 );\n\n        // Parse motif quality drop table file\n        io::DsvReader tsvReader( tableFilename );\n        vector<string> tokens;\n        while ( tsvReader.getNextLineFields<'\\t'>(tokens) )\n        {\n            if ( tokens.size() == 0 ) { continue; }\n            assert ( tokens.size() > 3 && \"There should be more than 4 entries per line: {kmer, repeatCount, coveredBaseCount, meanQ, (quality:count)+}\" );\n            uint64_t kmer = kmerStringToInt64( tokens[0] );\n            unsigned int repeatCount = boost::lexical_cast<unsigned int, string>( tokens[1] );\n            float meanQualityDrop = boost::lexical_cast<double, string>( tokens[2] );\n            unsigned int kmerLength = tokens[0].size();\n            unsigned int kmerLengthInBits = 2 * kmerLength;\n            uint64_t kmerMask = (1ull << kmerLengthInBits) - 1;\n\n            AutoGrowVector<double> distribution;\n            for (unsigned int i=3; i<tokens.size(); ++i)\n            {\n                unsigned int quality;\n                double count = 0;\n                istringstream ss( tokens[i] );\n                char colon;\n                ss >> quality >> colon >> count;\n                assert( colon == ':' && count > 0 && \"quality:count pairs must be separated by ':' in motif Qdrop table\" );\n                distribution[quality] = count;\n            }\n\n            active_ = true;\n            boost::shared_ptr< std::vector< MotifRepeatQualityDropInfo > > &mapData = tableData_[kmerLength][ kmer ];\n            if (mapData.get() == NULL)\n            {\n                mapData.reset( new std::vector< MotifRepeatQualityDropInfo > );\n\n                uint64_t kmerPermutation = kmer;\n                for (unsigned int permutation=1; permutation < kmerLength; ++permutation)\n                {\n                    // Permute kmer\n                    uint64_t leftMostBase = kmerPermutation >> (kmerLengthInBits - 2);\n                    kmerPermutation = ((kmerPermutation << 2) & kmerMask) | leftMostBase;\n\n                    //            cout << \"MotifQualityDropModel constructor: Adding \" << kmer << \"\\t\" << repeatCount << \"\\t\" << roundf(37 - meanQualityDrop) << endl;\n                    boost::shared_ptr< std::vector< MotifRepeatQualityDropInfo > > &mapDataPermutation = tableData_[kmerLength][ kmerPermutation ];\n                    assert (mapDataPermutation.get() == NULL);\n                    mapDataPermutation = mapData;\n                }\n            }\n\n            if (repeatCount >= mapData->size())\n            {\n                mapData->resize( repeatCount+1 );\n            }\n            assert( (*mapData)[repeatCount].meanQualityDrop == 0 && \"Same motif repeat is described in 2 lines of motif Qdrop table\" );\n            (*mapData)[repeatCount].meanQualityDrop = AVERAGE_QUALITY - meanQualityDrop;\n            (*mapData)[repeatCount].distribution.setWeights( distribution );\n        }\n    }\n}\n\nMotifRepeatQualityDropInfo* MotifQualityDropModel::getMotifRepeatQualityDrop( const uint64_t kmer1, const unsigned int repeatKmerLength, const unsigned int repeatCount )\n{\n//    cout << \"getMotifRepeatQualityDrop:\" << endl;\n//    cout << \"  kmer1=\" << kmer1 << endl;\n//    cout << \"  repeatKmerLength=\" << repeatKmerLength << endl;\n//    cout << \"  repeatCount=\" << repeatCount << endl;\n\n//    int result = ( repeatCount - 1 ) * repeatKmerLength;\n//    cout << \" => result=\" << result << endl;\n\n    std::map< uint64_t, boost::shared_ptr< std::vector< MotifRepeatQualityDropInfo > > >::iterator it = tableData_[repeatKmerLength].find( kmer1 );\n    if (it != tableData_[repeatKmerLength].end())\n    {\n//        cout << \"kmer found up to repeat \" << it->second->size() << endl;\n        unsigned int repeatCount2 = min<unsigned int>( repeatCount, it->second->size() );\n        if (repeatCount2 > 0)\n        {\n            if ( (*it->second).size() <= repeatCount2 )\n                repeatCount2 = (*it->second).size() - 1;\n            MotifRepeatQualityDropInfo *info = &((*it->second)[repeatCount2]);\n//            int result2 = (int)(info.meanQualityDrop);\n//            cout << \" => result2=\" << result2 << endl;\n            return info;\n        }\n    }\n\n    return 0;\n}\n\nvoid MotifQualityDropModel::applyQualityDrop( unsigned int& quality, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext, const unsigned int cycle, boost::mt19937& randomGen )\n{\n    if (!active_) { return; }\n\n    uint64_t &kmer = clusterErrorModelContext.motifQualityDropModelContext.kmer;\n    unsigned int &kmerLength = clusterErrorModelContext.motifQualityDropModelContext.kmerLength;\n    double &qualityDropLevel = clusterErrorModelContext.motifQualityDropModelContext.qualityDropLevel;\n    MotifRepeatQualityDropInfo* &shortTermEffect = clusterErrorModelContext.motifQualityDropModelContext.shortTermEffect;\n    float &shortTermQualityDrop = clusterErrorModelContext.motifQualityDropModelContext.shortTermQualityDrop;\n    int &qualityDropDueToPhasing = clusterErrorModelContext.phasingContext.qualityDrop;\n\n    bool repeatDetected = false;\n    MotifRepeatQualityDropInfo *strongestRepeat_effect = 0;\n    unsigned int strongestRepeat_repeatLengthExcludingFirst = 0;\n\n    if (kmerLength >= 5) // No point looking for short repeats\n    {\n        // detect repeated kmer\n        const unsigned int maxKmerLength = min<unsigned int>( MAX_MOTIF_KMER_LENGTH, kmerLength );\n\n        for ( unsigned int repeatKmerLength = 1; repeatKmerLength <= maxKmerLength; ++repeatKmerLength )\n        {\n            unsigned int repeatKmerLengthInBits = 2 * repeatKmerLength;\n            uint64_t kmerMask = (1ull << repeatKmerLengthInBits) - 1;\n            uint64_t kmer0 = kmer;\n            uint64_t kmer1 = kmer & kmerMask;\n            uint64_t kmer2;\n            unsigned int repeatCount = 0;\n            do\n            {\n                kmer0 >>= repeatKmerLengthInBits;\n                ++repeatCount;\n                kmer2 = kmer0 & kmerMask;\n            } while (kmer1 == kmer2 &&\n                     repeatKmerLength * (repeatCount + 1) <= kmerLength &&\n                     repeatKmerLengthInBits * (repeatCount + 1) <= 64\n                );\n\n            unsigned int repeatLengthExcludingFirst = ( repeatCount - 1 ) * repeatKmerLength;\n            const unsigned int repeatLengthThreshold = 4;\n            if ( repeatLengthExcludingFirst >= repeatLengthThreshold\n                 && repeatLengthExcludingFirst > strongestRepeat_repeatLengthExcludingFirst )\n            {\n                MotifRepeatQualityDropInfo *effect = getMotifRepeatQualityDrop( kmer1, repeatKmerLength, repeatCount );\n                if ( ( effect && strongestRepeat_effect && (int)effect->meanQualityDrop > (int)strongestRepeat_effect->meanQualityDrop )\n                     || ( effect && !strongestRepeat_effect && (int)effect->meanQualityDrop > 0 ) )\n                {\n                    repeatDetected = true;\n                    strongestRepeat_effect = effect;\n                    strongestRepeat_repeatLengthExcludingFirst = repeatLengthExcludingFirst;\n                }\n            }\n        }\n\n        if ( repeatDetected\n             && strongestRepeat_effect->meanQualityDrop > (shortTermEffect?shortTermEffect->meanQualityDrop:0) )\n        {\n            if (qualityDropLevel == 0)\n            {\n                qualityDropLevel = (double)randomGen() / randomGen.max();\n            }\n            int newQuality = strongestRepeat_effect->distribution( qualityDropLevel );\n            assert( newQuality != 0 );\n            int newQualityDrop = max<int>(AVERAGE_QUALITY - newQuality, 0);\n\n            if (shortTermQualityDrop < newQualityDrop)\n            {\n                qualityDropDueToPhasing -= (int)shortTermQualityDrop;\n                qualityDropDueToPhasing += newQualityDrop;\n                shortTermQualityDrop = newQualityDrop;\n            }\n            shortTermEffect = strongestRepeat_effect;\n        }\n        else\n        {\n            // Pulls down the \"quality drop effect to cancel\"\n            float reducedMeanQualityDrop = strongestRepeat_effect?strongestRepeat_effect->meanQualityDrop:0;\n            double newShortTermQualityDrop;\n            if (shortTermEffect && shortTermEffect->meanQualityDrop)\n            {\n                assert( reducedMeanQualityDrop <= shortTermEffect->meanQualityDrop );\n                newShortTermQualityDrop = shortTermQualityDrop * reducedMeanQualityDrop / shortTermEffect->meanQualityDrop;\n            }\n            else\n            {\n                assert( reducedMeanQualityDrop <= 0 );\n                newShortTermQualityDrop = reducedMeanQualityDrop;\n            }\n            const double attenuation = 1.0;\n            shortTermQualityDrop = (shortTermQualityDrop * (1.0 - attenuation)) + (newShortTermQualityDrop * attenuation);\n            shortTermEffect = strongestRepeat_effect;\n        }\n    }\n\n    kmer = (kmer << 2) | (bclBase & 3);\n    ++kmerLength;\n}\n\n\nRandomQualityDropModel::RandomQualityDropModel( /*const boost::filesystem::path& tableFilename*/ )\n{\n}\n\nvoid RandomQualityDropModel::applyQualityDrop( unsigned int& quality, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext )\n{\n}\n\n\nQualityGlitchModel::QualityGlitchModel( /*const boost::filesystem::path& tableFilename*/ )\n{\n}\n\nvoid QualityGlitchModel::applyQualityDrop( unsigned int& quality, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext )\n{\n}\n\n\nHappyPhasingModel::HappyPhasingModel( /*const boost::filesystem::path& tableFilename*/ )\n{\n}\n\nvoid HappyPhasingModel::applyQualityDrop( unsigned int& quality, const char bclBase, ClusterErrorModelContext& clusterErrorModelContext )\n{\n    // Use the values from the MotifQualityDrop plugin, if available\n    const int qualityDropDueToPhasing = clusterErrorModelContext.phasingContext.qualityDrop;\n    if (qualityDropDueToPhasing < 5)\n        return; // Such a small quality drop is not worth correcting\n\n    const unsigned int kmerLength = clusterErrorModelContext.motifQualityDropModelContext.kmerLength;\n    if (kmerLength > 3)\n    {\n        uint64_t kmer = clusterErrorModelContext.motifQualityDropModelContext.kmer;\n        float concordance = 0.0;\n        float maxConcordance = 0.0;\n        float concordanceWeight = 1.0;\n        float decay = 0.7;\n        for (int i=0; i<3; ++i)\n        {\n            kmer >>= 2;\n            if ((unsigned char)bclBase == (kmer & 3))\n                concordance += concordanceWeight;\n            maxConcordance += concordanceWeight;\n            concordanceWeight *= decay;\n        }\n        concordance /= maxConcordance;\n        concordance *= concordance; // squared seems nice\n\n        // restore quality in happy phasing areas\n        quality += (int)(qualityDropDueToPhasing * concordance);\n    }\n}\n\n\nQQTable::QQTable( const boost::filesystem::path& qqTableFilename )\n{\n    if (qqTableFilename == \"\")\n    { // Use default Phred values\n        for (unsigned int q=0; q<model::Phred::QUALITY_MAX; ++q)\n        {\n            qualityToProbability_.push_back( model::Phred::qualToProb( q ) );\n        }\n        qualityToProbability_.push_back( 0.0 ); // QUALITY_MAX has this special property\n    }\n    else\n    { // Parse QQ table file\n        io::DsvReader tsvReader( qqTableFilename );\n        vector<string> tokens;\n        while ( tsvReader.getNextLineFields<'\\t'>(tokens) )\n        {\n            if ( tokens.size() == 0 ) { continue; }\n            assert ( tokens.size() == 2 && \"There should be 2 entries per line\" );\n            vector<double> values;\n            try\n            {\n                std::transform( tokens.begin(), tokens.end(), std::back_inserter(values), boost::bind( &boost::lexical_cast<double,std::string>, _1) );\n            }\n            catch (const boost::bad_lexical_cast &e)\n            {\n                EAGLE_ERROR(\"Error while reading QQ table: a numerical field seems to contain non-numerical characters\");\n            }\n            assert( values.size() == 2 );\n            assert( values[0] == qualityToProbability_.size() && \"First column should contain consecutive numbers starting from 0\" );\n            qualityToProbability_.push_back ( values[1] );\n        }\n    }\n\n    if (qualityToProbability_.size() < model::Phred::QUALITY_MAX+1)\n    {\n        EAGLE_ERROR(\"QQ table doesn't contain enough values\");\n    }\n}\n\ndouble QQTable::qualToErrorRate( const unsigned int qual )\n{\n    if (qual >= qualityToProbability_.size())\n    {\n        BOOST_THROW_EXCEPTION( eagle::common::EagleException( 0, \"Requested quality is higher than allowed max\") );\n    }\n    double prob = qualityToProbability_[qual];\n    return prob;\n}\n\n\nErrorModel::ErrorModel( const vector<boost::filesystem::path>& qualityTableFilenames, const boost::filesystem::path& mismatchTableFilename, const boost::filesystem::path& homopolymerIndelTableFilename, const boost::filesystem::path& motifQualityDropTableFilename, const boost::filesystem::path& qqTableFilename, const std::vector< std::string >& errorModelOptions )\n    : qualityModel_           ( qualityTableFilenames )\n    , sequencingMismatchModel_( mismatchTableFilename )\n    , homopolymerIndelModel_  ( homopolymerIndelTableFilename )\n    , motifQualityDropModel_  ( motifQualityDropTableFilename )\n    , randomQualityDropModel_ ()\n    , qualityGlitchModel_     ()\n    , happyPhasingModel_      ()\n    , longreadBaseDuplicationModel_( errorModelOptions )\n    , longreadDeletionModel_       ( errorModelOptions )\n    , qqTable_                ( qqTableFilename )\n{\n}\n\nvoid ErrorModel::getQualityAndRandomError( boost::mt19937& randomGen, const unsigned int cycle, const char base, unsigned int& quality, unsigned int& randomErrorType, char& bclBase, ClusterErrorModelContext& clusterErrorModelContext )\n{\n    bclBase = baseConverter_.normalizedBcl( base );\n    if (bclBase==4)\n    {\n        // base is N\n        randomErrorType = NoError;\n        bclBase = 0;\n        quality = 0;\n        return;\n    }\n    assert( bclBase >= 0 && bclBase < 4 );\n\n//    quality = qualityModel_.getQuality( randomGen, cycle, bclBase, clusterErrorModelContext );\n    quality = qualityModel_.getQuality( randomGen, cycle, clusterErrorModelContext );\n    motifQualityDropModel_.applyQualityDrop( quality, bclBase, clusterErrorModelContext, cycle, randomGen );\n    randomQualityDropModel_.applyQualityDrop( quality, bclBase, clusterErrorModelContext );\n    qualityGlitchModel_.applyQualityDrop( quality, bclBase, clusterErrorModelContext );\n    happyPhasingModel_.applyQualityDrop( quality, bclBase, clusterErrorModelContext );\n\n    // Apply quality drop due to phasing, using an additive strategy\n    // This quality drop was calculated as part of the previous \"applyQualityDrop\" methods\n    if ((int)quality > clusterErrorModelContext.phasingContext.qualityDrop)\n    {\n      quality -= clusterErrorModelContext.phasingContext.qualityDrop;\n    }\n    else\n    {\n      quality = 0;\n    }\n\n    // Make sure quality scores stay above 2\n    if ( quality < 2 )\n        quality = 2;\n\n    double errorRate = qqTable_.qualToErrorRate( quality );\n\n//#define REPORT_ERROR_RATE\n#ifdef REPORT_ERROR_RATE\n    static double totalErrors = 0;\n    static double totalBases  = 0;\n    static double threshold   = 1;\n    totalErrors += errorRate;\n    totalBases++;\n    if (totalBases >= threshold)\n    {\n        clog << (boost::format(\"%f @ %f => %f\") % totalErrors % totalBases % (totalErrors/totalBases)).str() << endl;\n        threshold *= 2;\n    }\n#endif //ifdef REPORT_ERROR_RATE\n\n    sequencingMismatchModel_.apply( randomGen, errorRate, randomErrorType, bclBase, clusterErrorModelContext );\n    homopolymerIndelModel_.apply( randomGen, errorRate, randomErrorType, bclBase, clusterErrorModelContext );\n    longreadBaseDuplicationModel_.apply( randomGen, errorRate, randomErrorType, bclBase, clusterErrorModelContext );\n    longreadDeletionModel_.apply( randomGen, errorRate, randomErrorType, bclBase, clusterErrorModelContext );\n}\n\n} // namespace genome\n} // namespace eagle\n", "meta": {"hexsha": "6f005318adb27db354315e71ad528b32719d7368", "size": 37062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/c++/lib/genome/QualityModel.cpp", "max_stars_repo_name": "sequencing/EAGLE", "max_stars_repo_head_hexsha": "6da0438c1f7620ea74dec1f34baf20bb0b14b110", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-05-22T16:03:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T12:12:46.000Z", "max_issues_repo_path": "src/c++/lib/genome/QualityModel.cpp", "max_issues_repo_name": "sequencing/EAGLE", "max_issues_repo_head_hexsha": "6da0438c1f7620ea74dec1f34baf20bb0b14b110", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-10-21T11:19:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T05:01:12.000Z", "max_forks_repo_path": "src/c++/lib/genome/QualityModel.cpp", "max_forks_repo_name": "sequencing/EAGLE", "max_forks_repo_head_hexsha": "6da0438c1f7620ea74dec1f34baf20bb0b14b110", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-01-21T00:31:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-12T13:28:57.000Z", "avg_line_length": 40.5936473165, "max_line_length": 365, "alphanum_fraction": 0.6293777994, "num_tokens": 9182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.16675454099034306}}
{"text": "#include <Python.h>  // NOLINT(build/include_alpha)\n\n// Produce deprecation warnings (needs to come before arrayobject.h inclusion).\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include <boost/make_shared.hpp>\n#include <boost/python.hpp>\n#include <boost/python/raw_function.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <numpy/arrayobject.h>\n#include \"boost/algorithm/string.hpp\"\n#include \"boost/pointer_cast.hpp\"\n#include \"google/protobuf/text_format.h\"\n\n// these need to be included after boost on OS X\n#include <string>  // NOLINT(build/include_order)\n#include <vector>  // NOLINT(build/include_order)\n#include <map>\n#include <algorithm>  // NOLINT(build/include_order)\n\n#include \"caffe/blob.hpp\"\n#include \"caffe/common.hpp\"\n#include \"caffe/net.hpp\"\n#include \"caffe/layer.hpp\"\n#include \"caffe/layers/image_data_layer.hpp\"\n#include \"caffe/proto/caffe.pb.h\"\n#include \"caffe/util/db.hpp\"\n#include \"caffe/util/format.hpp\"\n#include \"caffe/util/io.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\n// Temporary solution for numpy < 1.7 versions: old macro, no promises.\n// You're strongly advised to upgrade to >= 1.7.\n#ifndef NPY_ARRAY_C_CONTIGUOUS\n#define NPY_ARRAY_C_CONTIGUOUS NPY_C_CONTIGUOUS\n#define PyArray_SetBaseObject(arr, x) (PyArray_BASE(arr) = (x))\n#endif\n\n// for python, we'll just use float as the type\ntypedef float Dtype;\n\nusing caffe::Blob;\nusing caffe::Caffe;\nusing caffe::Datum;\nusing caffe::Net;\nusing caffe::ImageDataLayer;\nusing std::string;\n\nnamespace db = caffe::db;\nnamespace bp = boost::python;\n\ntemplate<typename Dtype>\nbp::list feature_extraction_pipeline_raw(bp::tuple args, bp::dict kwargs) {\n\n  if (bp::len(kwargs) > 0) {\n    throw std::runtime_error(\"main_raw takes no kwargs\");\n  }\n\n  const int num_required_args = 7;\n  if (bp::len(args) < num_required_args) {\n    LOG(ERROR)<<\n    \"This program takes in a trained network and an input data layer, and then\"\n    \" extract features of the input data produced by the net.\\n\"\n    \"Usage: extract_features  pretrained_net_param\"\n    \"  feature_extraction_proto_file  extract_feature_blob_name1[,name2,...]\"\n    \"  save_feature_dataset_name1[,name2,...]  num_mini_batches  db_type\"\n    \"  [CPU/GPU] [DEVICE_ID=0]\\n\"\n    \"Note: you can extract multiple features in one pass by specifying\"\n    \" multiple feature blob names and dataset names separated by ','.\"\n    \" The names cannot contain white space characters and the number of blobs\"\n    \" and datasets must be equal.\";\n    return bp::list();\n  }\n\n  // force to use CPU\n  Caffe::set_mode(Caffe::CPU);\n\n  std::string pretrained_binary_proto( (bp::extract<std::string>(args[1])) );\n\n  // Expected prototxt contains at least one data layer such as\n  //  the layer data_layer_name and one feature blob such as the\n  //  fc7 top blob to extract features.\n  /*\n   layers {\n     name: \"data_layer_name\"\n     type: DATA\n     data_param {\n       source: \"/path/to/your/images/to/extract/feature/images_leveldb\"\n       mean_file: \"/path/to/your/image_mean.binaryproto\"\n       batch_size: 128\n       crop_size: 227\n       mirror: false\n     }\n     top: \"data_blob_name\"\n     top: \"label_blob_name\"\n   }\n   layers {\n     name: \"drop7\"\n     type: DROPOUT\n     dropout_param {\n       dropout_ratio: 0.5\n     }\n     bottom: \"fc7\"\n     top: \"fc7\"\n   }\n   */\n\n  std::string feature_extraction_proto( (bp::extract<std::string>(args[2])) );\n  boost::shared_ptr<Net<Dtype> > feature_extraction_net(\n      new Net<Dtype>(feature_extraction_proto, caffe::TEST));\n  feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);\n\n  std::string extract_feature_blob_names( (bp::extract<std::string>(args[3])) );\n  std::vector<std::string> blob_names;\n  boost::split(blob_names, extract_feature_blob_names, boost::is_any_of(\",\"));\n\n  std::string save_feature_dataset_names( (bp::extract<std::string>(args[4])) ) ;\n  std::vector<std::string> dataset_names;\n  boost::split(dataset_names, save_feature_dataset_names,\n               boost::is_any_of(\",\"));\n  size_t num_features = blob_names.size();\n\n\n  int num_mini_batches = bp::extract<int>(args[5]);\n\n  std::vector<boost::shared_ptr<db::DB> > feature_dbs;\n  std::vector<boost::shared_ptr<db::Transaction> > txns;\n  const char* db_type = bp::extract<const char*>(args[6]);\n  for (size_t i = 0; i < dataset_names.size(); ++i) {\n    //LOG(INFO)<< \"Opening dataset \" << dataset_names[i];\n    boost::shared_ptr<db::DB> db(db::GetDB(db_type));\n    db->Open(dataset_names.at(i), db::WRITE);\n    feature_dbs.push_back(db);\n    boost::shared_ptr<db::Transaction> txn(db->NewTransaction());\n    txns.push_back(txn);\n  }\n\n  // storing \"fc7\" features (in C++)\n  Datum datum; \n  // sorting \"prob\" features (in Python)\n  bp::list prob_list;\n\n  // the name of the image as the 'key' for feature db\n  const boost::shared_ptr<ImageDataLayer<Dtype> > layer_ptr = boost::static_pointer_cast<ImageDataLayer<Dtype> >(feature_extraction_net->layer_by_name(\"data\"));\n  const std::vector<std::pair<std::string, int> >& data_names_labels = layer_ptr->GetDataNameLabel();\n\n  std::vector<int> image_indices(num_features, 0);\n  for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {\n    feature_extraction_net->Forward();\n    for (int i = 0; i < num_features; ++i) {\n      const boost::shared_ptr<Blob<Dtype> > feature_blob =\n        feature_extraction_net->blob_by_name(blob_names[i]);\n      int batch_size = feature_blob->num();\n      int dim_features = feature_blob->count() / batch_size;\n      const Dtype* feature_blob_data;\n      // blob \"fc7\"\n      if(i == 0){\n        for (int n = 0; n < batch_size; ++n) {\n          datum.set_height(feature_blob->height());\n          datum.set_width(feature_blob->width());\n          datum.set_channels(feature_blob->channels());\n          datum.clear_data();\n          datum.clear_float_data();\n          feature_blob_data = feature_blob->cpu_data() +\n              feature_blob->offset(n);\n          for (int d = 0; d < dim_features; ++d) {\n            datum.add_float_data(feature_blob_data[d]);\n          }\n          string key_str = data_names_labels[batch_index].first;\n\n          // const string ready to be stored\n          string out;\n          datum.SerializeToString(&out);\n\n          txns.at(i)->Put(key_str, out);\n          ++image_indices[i];\n          if (image_indices[i] % 1000 == 0) {\n            txns.at(i)->Commit();\n            txns.at(i).reset(feature_dbs.at(i)->NewTransaction());\n          }\n        } // for (int n = 0; n < batch_size; ++n)\n      } // if(i == 0)\n      // blob \"prob\"\n      else{\n        for (int n = 0; n < batch_size; ++n) {\n          feature_blob_data = feature_blob->cpu_data() +\n              feature_blob->offset(n);\n          for (int d = 0; d < dim_features; ++d) {\n            prob_list.append(feature_blob_data[d]);\n            //datum.add_float_data(feature_blob_data[d]);\n          }\n        } // for (int n = 0; n < batch_size; ++n)\n      }\n    }  // for (int i = 0; i < num_features; ++i)\n  }  // for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)\n  // write the last batch\n  for (int i = 0; i < dataset_names.size(); ++i) {\n    if (image_indices[i] % 1000 != 0) {\n      txns.at(i)->Commit();\n    }\n    feature_dbs.at(i)->Close();\n  }\n\n  printf(\"%s\\n\", \"Successfully extracted the features!\");\n  return prob_list;\n}\n\n// costum compare object \ntemplate <typename K, typename V>\nbool cmp(const std::pair<K, V>& lhs, const std::pair<K,V>& rhs)\n{\n  return lhs.second > rhs.second;\n}\n\n// using STL pair for argSort                                                                                                                                      \ntemplate <typename Dtype>\nstd::vector<size_t> argsort_using_stlMap(std::vector<Dtype> const& values) {\n  std::vector<size_t> indices(values.size());\n  std::vector<std::pair<size_t, Dtype> > pairs;\n  for(size_t i=0; i<values.size(); ++i){\n    pairs.push_back(std::make_pair(i, values[i]));\n  }\n\n  std::sort(pairs.begin(), pairs.end(), cmp<size_t, Dtype> );\n\n  for(size_t i=0; i<pairs.size(); ++i){\n    indices[i] = pairs[i].first;\n  }\n  return indices;\n}\n\n// Computing the similarity of two features (e.g. *Cosine similarity or L2-norm)\ntemplate <typename Dtype>\nfloat similarity(Datum& datum_1, Datum& datum_2){\n\n  int feature_dim = datum_1.channels();\n  Dtype* ptr_1 = datum_1.mutable_float_data()->mutable_data();\n  Dtype* ptr_2 = datum_2.mutable_float_data()->mutable_data();\n\n  Dtype dot_val, norm_1, norm_2;\n\n  // L2-norm\n  norm_1 = sqrt( caffe::caffe_cpu_dot(feature_dim, ptr_1, ptr_1) );\n  norm_2 = sqrt( caffe::caffe_cpu_dot(feature_dim, ptr_2, ptr_2) );\n  // dot product\n  dot_val = caffe::caffe_cpu_dot(feature_dim, ptr_1, ptr_2);\n\n  return dot_val / (norm_1 * norm_2); \n}\n\n/* DEBUG -> dislay Datum instance @Wei-Lin */\ntemplate <typename Dtype>\nvoid listDatum(const Datum& datum){\n  if(datum.has_height())  std::cout << \"H:\\t\" << datum.height() << std::endl;\n  if(datum.has_width())  std::cout << \"W:\\t\" << datum.width() << std::endl;\n  if(datum.has_channels())  std::cout << \"C:\\t\" << datum.channels() << std::endl;\n  std::cout << \"size of float data:\\t\" << datum.float_data_size() << std::endl;\n\n  // display fc7 floating features\n  google::protobuf::RepeatedField<Dtype> data = datum.float_data();\n  for( google::protobuf::RepeatedField<float>::iterator iter=data.begin(); iter<data.end(); ++iter ){\n    std::cout << *iter << \" \";\n  }\n  std::cout << \"\\n\" << std::endl;\n}\n\ntemplate <typename Dtype>\nbp::object matching_pipeline_raw(bp::tuple args, bp::dict kwargs) {\n\n  if (bp::len(kwargs) > 0) {\n    throw std::runtime_error(\"main_raw takes no kwargs\");\n  }\n\n  const int num_required_args = 3;\n  if (bp::len(args) < num_required_args) {\n    LOG(ERROR)<<\n    \"This program takes in an image feature database (stored in leveldb/lmdb format)\" \n    \"and a query image feature, and then\"\n    \" compare database features with the query feature to give a short list of relavence.\\n\"\n\n    \"@TODO: define the usage of retrieval interface\"\n    \n    \"Usage: retrieval path_to_feature_db db_type\\n\"\n\n    \"@TODO: modify the notes for retrieval process\"\n\n    \"Note: you can extract multiple features in one pass by specifying\"\n    \" multiple feature blob names and dataset names separated by ','.\"\n    \" The names cannot contain white space characters and the number of blobs\"\n    \" and datasets must be equal.\";\n    return bp::object();\n  }\n \n  // 1st argument: the path to feature db\n  std::string feature_db_name( (bp::extract<std::string>(args[1])) );\n  std::cout << \"feature_db_name: \" << feature_db_name << std::endl;\n  // 2nd argument: the type of the feature db\n  const char* db_type = bp::extract<const char*>(args[2]);\n\n  // Open the feature db\n  boost::shared_ptr<db::DB> feature_db(db::GetDB(db_type));\n  feature_db->Open(feature_db_name, db::READ);\n\n  // Visit all the features\n  std::vector<boost::shared_ptr<Datum> > Datum_vec;\n  db::Cursor* db_cursor(feature_db->NewCursor());\n  for(db_cursor->SeekToFirst(); db_cursor->valid(); db_cursor->Next()){\n    // get the current string value\n    std::string s = db_cursor->value();\n\n    // convert to the feature (floating)\n    boost::shared_ptr<Datum> datum(new Datum);\n    datum->ParseFromString(s);\n\n    Datum_vec.push_back(datum);\n  }\n  printf(\"Total feat. is #%zd\\n\", Datum_vec.size());\n\n  // similarity measure of two features\n  Dtype dot_val = similarity<Dtype>(*Datum_vec[0], *Datum_vec[1]);\n  std::cout << \"The similarity of vector[0] and vector[1] is \" << dot_val << std::endl;\n\n  // close the feature db\n  feature_db->Close();\n\n\n  return bp::object();\n}\n\ntemplate<typename Dtype>\nbp::list retrieval_pipeline_raw(bp::tuple args, bp::dict kwargs) {\n\n  if (bp::len(kwargs) > 0) {\n    throw std::runtime_error(\"main_raw takes no kwargs\");\n  }\n\n  const int num_required_args = 7;\n  if (bp::len(args) < num_required_args) {\n    LOG(ERROR)<<\n    \"This program takes in a trained network and an input data layer, and then\"\n    \" extract features of the input data produced by the net.\\n\"\n    \"Usage: extract_features  pretrained_net_param\"\n    \"  feature_extraction_proto_file  extract_feature_blob_name1[,name2,...]\"\n    \"  save_feature_dataset_name1[,name2,...]  num_mini_batches  db_type\"\n    \"  [CPU/GPU] [DEVICE_ID=0]\\n\"\n    \"Note: you can extract multiple features in one pass by specifying\"\n    \" multiple feature blob names and dataset names separated by ','.\"\n    \" The names cannot contain white space characters and the number of blobs\"\n    \" and datasets must be equal.\";\n    return bp::list();\n  }\n\n  // Expected prototxt contains at least one data layer such as\n  //  the layer data_layer_name and one feature blob such as the\n  //  fc7 top blob to extract features.\n  /*\n   layers {\n     name: \"data_layer_name\"\n     type: DATA\n     data_param {\n       source: \"/path/to/your/images/to/extract/feature/images_leveldb\"\n       mean_file: \"/path/to/your/image_mean.binaryproto\"\n       batch_size: 128\n       crop_size: 227\n       mirror: false\n     }\n     top: \"data_blob_name\"\n     top: \"label_blob_name\"\n   }\n   layers {\n     name: \"drop7\"\n     type: DROPOUT\n     dropout_param {\n       dropout_ratio: 0.5\n     }\n     bottom: \"fc7\"\n     top: \"fc7\"\n   }\n   */\n\n  // force caffe to use CPU\n  Caffe::set_mode(Caffe::CPU);\n\n  // 1st argument: excutable binary name (ingored)\n\n  // 2nd argument: model binary\n  std::string pretrained_binary_proto( (bp::extract<std::string>(args[1])) );\n\n  // 3rd argument: model proto txt\n  std::string feature_extraction_proto( (bp::extract<std::string>(args[2])) );\n  boost::shared_ptr<Net<Dtype> > feature_extraction_net(\n      new Net<Dtype>(feature_extraction_proto, caffe::TEST));\n  feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);\n\n  // 4nd argument: blob names (features to be extracted)\n  std::string extract_feature_blob_names( (bp::extract<std::string>(args[3])) );\n  std::vector<std::string> blob_names;\n  boost::split(blob_names, extract_feature_blob_names, boost::is_any_of(\",\"));\n  size_t num_features = blob_names.size();\n\n  // 5nd argument: size of mini patch\n  int num_mini_batches = bp::extract<int>(args[4]);\n\n  // 6nd argument: feature db path\n  std::string feature_db_name( (bp::extract<std::string>(args[5])) );\n\n  // 7nd argument: feature db type\n  const char* db_type = bp::extract<const char*>(args[6]);\n\n  // storing \"fc7\" features (in C++)\n  Datum query;\n  // storing sorted \"filenames\" (in Python)\n  bp::list result_list; \n  // storing \"prob\" features (in Python)\n  bp::list prob_list;\n\n  // the name of the image as the 'key' for feature db\n  const boost::shared_ptr<ImageDataLayer<Dtype> > layer_ptr = boost::static_pointer_cast<ImageDataLayer<Dtype> >(feature_extraction_net->layer_by_name(\"data\"));\n  const std::vector<std::pair<std::string, int> >& data_names_labels = layer_ptr->GetDataNameLabel();\n\n  /* ==== Feature Extraction ==== */\n  std::vector<int> image_indices(num_features, 0);\n  for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {\n    feature_extraction_net->Forward();\n    for (int i = 0; i < num_features; ++i) {\n      const boost::shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net->blob_by_name(blob_names[i]);\n      int batch_size = feature_blob->num();\n      int dim_features = feature_blob->count() / batch_size;\n      const Dtype* feature_blob_data;\n      // blob[fc7]\n      if(i == 0){\n        for (int n = 0; n < batch_size; ++n) {\n          query.set_height(feature_blob->height());\n          query.set_width(feature_blob->width());\n          query.set_channels(feature_blob->channels());\n          query.clear_data();\n          query.clear_float_data();\n          feature_blob_data = feature_blob->cpu_data() + feature_blob->offset(n);\n          for (int d = 0; d < dim_features; ++d) {\n            query.add_float_data(feature_blob_data[d]);\n          }\n\n          // const string ready to be stored\n          string out;\n          query.SerializeToString(&out);\n        }\n      }\n      // blob[prob]\n      else{\n        for (int n = 0; n < batch_size; ++n) {\n          feature_blob_data = feature_blob->cpu_data() +\n              feature_blob->offset(n);\n          for (int d = 0; d < dim_features; ++d) {\n            prob_list.append(feature_blob_data[d]);\n            //datum.add_float_data(feature_blob_data[d]);\n          }\n        } // for (int n = 0; n < batch_size; ++n)\n      }\n    }  // for (int i = 0; i < num_features; ++i)\n  }  // for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)\n\n  /* ==== Retrieval ==== */\n  // Open the feature db\n  boost::shared_ptr<db::DB> feature_db(db::GetDB(db_type));\n  feature_db->Open(feature_db_name, db::READ);\n  db::Cursor* db_cursor(feature_db->NewCursor());\n  \n  // Visit all the features\n  std::vector<std::string> name_vec;\n  std::vector<boost::shared_ptr<Datum> > Datum_vec;\n  for(db_cursor->SeekToFirst(); db_cursor->valid(); db_cursor->Next()){\n    std::string name = db_cursor->key();\n    // get the current string value\n    std::string feat = db_cursor->value();\n\n    // convert to the feature (floating)\n    boost::shared_ptr<Datum> datum(new Datum);\n    datum->ParseFromString(feat);\n\n    name_vec.push_back(name);\n    Datum_vec.push_back(datum);\n  }\n  printf(\"#feature in DB = #%zd\\n\", Datum_vec.size());\n\n  // similarity measure of features against query\n  std::vector<Dtype> scores;\n  for(std::vector< boost::shared_ptr<Datum> >::iterator iter=Datum_vec.begin(); iter<Datum_vec.end(); ++iter){\n    Dtype dot_val = similarity<Dtype>(query, **iter);\n    scores.push_back(dot_val);\n    std::cout << \"The similarity of two vectors is \" << dot_val << std::endl;\n  }\n\n  // sort by similarity measures\n  std::vector<size_t> indices = argsort_using_stlMap(scores);\n  for(std::vector<size_t>::iterator iter=indices.begin(); iter<indices.end(); ++iter){\n    std::cout << \"Sorted Indices: \" << *iter << std::endl;\n  }\n\n  // map sorted filename into python list\n  for (size_t i=0; i<indices.size(); ++i) {\n    result_list.append(name_vec[ indices[i] ]);\n  }\n\n  // close the feature db\n  feature_db->Close();\n\n  printf(\"%s\\n\", \"Successfully retrieved similar images!\");\n  return result_list;\n}\n\n\nBOOST_PYTHON_MODULE(_django_CV){\n  bp::def(\"feature_extraction_pipeline\", bp::raw_function(&feature_extraction_pipeline_raw<Dtype>));\n  bp::def(\"matching_pipeline\", bp::raw_function(&matching_pipeline_raw<Dtype>));\n  bp::def(\"retrieval_pipeline\", bp::raw_function(&retrieval_pipeline_raw<Dtype>));\n  // boost python expects a void (missing) return value, while import_array\n  // returns NULL for python3. import_array1() forces a void return value.\n  import_array1();\n}\n", "meta": {"hexsha": "5759561aee2696684f16c0f8486ceef28fb773eb", "size": 18614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/py_caffe_module/_django_CV.cpp", "max_stars_repo_name": "HughKu/caffe-retrieval", "max_stars_repo_head_hexsha": "20085014a7422445cd45d53c3e7b5742d3a242c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T19:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T19:10:32.000Z", "max_issues_repo_path": "python/py_caffe_module/_django_CV.cpp", "max_issues_repo_name": "HughKu/caffe-retrieval", "max_issues_repo_head_hexsha": "20085014a7422445cd45d53c3e7b5742d3a242c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/py_caffe_module/_django_CV.cpp", "max_forks_repo_name": "HughKu/caffe-retrieval", "max_forks_repo_head_hexsha": "20085014a7422445cd45d53c3e7b5742d3a242c9", "max_forks_repo_licenses": ["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.7961538462, "max_line_length": 163, "alphanum_fraction": 0.6603094445, "num_tokens": 4871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.16675453751527755}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/PrimitiveFromConservative.hpp\"\n\n#include <boost/none.hpp>\n#include <boost/optional/optional.hpp>\n#include <iomanip>\n#include <limits>\n#include <ostream>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/EagerMath/DotProduct.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"ErrorHandling/Error.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/NewmanHamlin.hpp\"  // IWYU pragma: keep\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/PalenzuelaEtAl.hpp\"  // IWYU pragma: keep\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/PrimitiveRecoveryData.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/Tags.hpp\"  // IWYU pragma: keep\n#include \"PointwiseFunctions/GeneralRelativity/IndexManipulation.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Tags.hpp\"  // IWYU pragma: keep\n#include \"PointwiseFunctions/Hydro/SpecificEnthalpy.hpp\"\n#include \"PointwiseFunctions/Hydro/Tags.hpp\"  // IWYU pragma: keep\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/Overloader.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n// IWYU pragma: no_forward_declare EquationsOfState::EquationOfState\n// IWYU pragma: no_forward_declare Tensor\n// IWYU pragma: no_include <array>\n\n/// \\cond\nnamespace grmhd {\nnamespace ValenciaDivClean {\n\ntemplate <typename OrderedListOfPrimitiveRecoverySchemes,\n          size_t ThermodynamicDim>\nvoid PrimitiveFromConservative<OrderedListOfPrimitiveRecoverySchemes,\n                               ThermodynamicDim>::\n    apply(\n        gsl::not_null<Scalar<DataVector>*> rest_mass_density,\n        gsl::not_null<Scalar<DataVector>*> specific_internal_energy,\n        gsl::not_null<tnsr::I<DataVector, 3, Frame::Inertial>*>\n            spatial_velocity,\n        gsl::not_null<tnsr::I<DataVector, 3, Frame::Inertial>*> magnetic_field,\n        gsl::not_null<Scalar<DataVector>*> divergence_cleaning_field,\n        gsl::not_null<Scalar<DataVector>*> lorentz_factor,\n        gsl::not_null<Scalar<DataVector>*> pressure,\n        gsl::not_null<Scalar<DataVector>*> specific_enthalpy,\n        const Scalar<DataVector>& tilde_d, const Scalar<DataVector>& tilde_tau,\n        const tnsr::i<DataVector, 3, Frame::Inertial>& tilde_s,\n        const tnsr::I<DataVector, 3, Frame::Inertial>& tilde_b,\n        const Scalar<DataVector>& tilde_phi,\n        const tnsr::ii<DataVector, 3, Frame::Inertial>& spatial_metric,\n        const tnsr::II<DataVector, 3, Frame::Inertial>& inv_spatial_metric,\n        const Scalar<DataVector>& sqrt_det_spatial_metric,\n        const EquationsOfState::EquationOfState<true, ThermodynamicDim>&\n            equation_of_state) noexcept {\n  get(*divergence_cleaning_field) =\n      get(tilde_phi) / get(sqrt_det_spatial_metric);\n  for (size_t i = 0; i < 3; ++i) {\n    magnetic_field->get(i) = tilde_b.get(i) / get(sqrt_det_spatial_metric);\n  }\n  const DataVector total_energy_density =\n      (get(tilde_tau) + get(tilde_d)) / get(sqrt_det_spatial_metric);\n  const auto tilde_s_upper = raise_or_lower_index(tilde_s, inv_spatial_metric);\n  const DataVector momentum_density_squared =\n      get(dot_product(tilde_s, tilde_s_upper)) /\n      square(get(sqrt_det_spatial_metric));\n  const DataVector momentum_density_dot_magnetic_field =\n      get(dot_product(tilde_s, *magnetic_field)) / get(sqrt_det_spatial_metric);\n  const DataVector magnetic_field_squared =\n      get(dot_product(*magnetic_field, *magnetic_field, spatial_metric));\n  const DataVector rest_mass_density_times_lorentz_factor =\n      get(tilde_d) / get(sqrt_det_spatial_metric);\n\n  for (size_t s = 0; s < total_energy_density.size(); ++s) {\n    boost::optional<PrimitiveRecoverySchemes::PrimitiveRecoveryData>\n        primitive_data = boost::none;\n    tmpl::for_each<OrderedListOfPrimitiveRecoverySchemes>(\n        [&primitive_data, &total_energy_density, &momentum_density_squared,\n         &momentum_density_dot_magnetic_field, &magnetic_field_squared,\n         &rest_mass_density_times_lorentz_factor,\n         &equation_of_state, &s](auto scheme) noexcept {\n          using primitive_recovery_scheme = tmpl::type_from<decltype(scheme)>;\n          if (not primitive_data) {\n            primitive_data =\n                primitive_recovery_scheme::template apply<ThermodynamicDim>(\n                    total_energy_density[s], momentum_density_squared[s],\n                    momentum_density_dot_magnetic_field[s],\n                    magnetic_field_squared[s],\n                    rest_mass_density_times_lorentz_factor[s],\n                    equation_of_state);\n          }\n        });\n\n    if (primitive_data) {\n      get(*rest_mass_density)[s] = primitive_data.get().rest_mass_density;\n      const double coefficient_of_b =\n          momentum_density_dot_magnetic_field[s] /\n          (primitive_data.get().rho_h_w_squared *\n           (primitive_data.get().rho_h_w_squared + magnetic_field_squared[s]));\n      const double coefficient_of_s =\n          1.0 /\n          (get(sqrt_det_spatial_metric)[s] *\n           (primitive_data.get().rho_h_w_squared + magnetic_field_squared[s]));\n      for (size_t i = 0; i < 3; ++i) {\n        spatial_velocity->get(i)[s] =\n            coefficient_of_b * magnetic_field->get(i)[s] +\n            coefficient_of_s * tilde_s_upper.get(i)[s];\n      }\n      get(*lorentz_factor)[s] = primitive_data.get().lorentz_factor;\n      get(*pressure)[s] = primitive_data.get().pressure;\n    } else {\n      ERROR(\"All primitive inversion schemes failed at s = \"\n            << s << \".\\n\"\n            << std::setprecision(std::numeric_limits<double>::digits10 + 1)\n            << \"total_energy_density = \" << total_energy_density[s] << \"\\n\"\n            << \"momentum_density_squared = \" << momentum_density_squared[s]\n            << \"\\n\"\n            << \"momentum_density_dot_magnetic_field = \"\n            << momentum_density_dot_magnetic_field[s] << \"\\n\"\n            << \"magnetic_field_squared = \" << magnetic_field_squared[s] << \"\\n\"\n            << \"rest_mass_density_times_lorentz_factor = \"\n            << rest_mass_density_times_lorentz_factor[s] << \"\\n\"\n            << \"previous_rest_mass_density = \" << get(*rest_mass_density)[s]\n            << \"\\n\"\n            << \"previous_pressure = \" << get(*pressure)[s] << \"\\n\"\n            << \"previous_lorentz_factor = \" << get(*lorentz_factor)[s] << \"\\n\");\n    }\n  }\n  *specific_internal_energy = make_overloader(\n      [&rest_mass_density](const EquationsOfState::EquationOfState<true, 1>&\n                               the_equation_of_state) noexcept {\n        return the_equation_of_state.specific_internal_energy_from_density(\n            *rest_mass_density);\n      },\n      [&rest_mass_density,\n       &pressure ](const EquationsOfState::EquationOfState<true, 2>&\n                       the_equation_of_state) noexcept {\n        return the_equation_of_state\n            .specific_internal_energy_from_density_and_pressure(\n                *rest_mass_density, *pressure);\n      })(equation_of_state);\n  *specific_enthalpy = hydro::specific_enthalpy(\n      *rest_mass_density, *specific_internal_energy, *pressure);\n}\n}  // namespace ValenciaDivClean\n}  // namespace grmhd\n\n#define RECOVERY(data) BOOST_PP_TUPLE_ELEM(0, data)\n#define THERMODIM(data) BOOST_PP_TUPLE_ELEM(1, data)\n\n#define INSTANTIATION(_, data)                                        \\\n  template struct grmhd::ValenciaDivClean::PrimitiveFromConservative< \\\n      RECOVERY(data), THERMODIM(data)>;\n\nusing NewmanHamlinThenPalenzuelaEtAl = tmpl::list<\n    grmhd::ValenciaDivClean::PrimitiveRecoverySchemes::NewmanHamlin,\n    grmhd::ValenciaDivClean::PrimitiveRecoverySchemes::PalenzuelaEtAl>;\n\nGENERATE_INSTANTIATIONS(\n    INSTANTIATION,\n    (tmpl::list<\n         grmhd::ValenciaDivClean::PrimitiveRecoverySchemes::NewmanHamlin>,\n     tmpl::list<\n         grmhd::ValenciaDivClean::PrimitiveRecoverySchemes::PalenzuelaEtAl>,\n     NewmanHamlinThenPalenzuelaEtAl),\n    (1, 2))\n\n#undef INSTANTIATION\n#undef THERMODIM\n#undef RECOVERY\n/// \\endcond\n", "meta": {"hexsha": "4b59862fd1fd52708a5995258bda9e80b3addb85", "size": 8123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/GrMhd/ValenciaDivClean/PrimitiveFromConservative.cpp", "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/Evolution/Systems/GrMhd/ValenciaDivClean/PrimitiveFromConservative.cpp", "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/Evolution/Systems/GrMhd/ValenciaDivClean/PrimitiveFromConservative.cpp", "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": 45.8926553672, "max_line_length": 92, "alphanum_fraction": 0.6943247569, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.24798742068237778, "lm_q1q2_score": 0.16672980392247147}}
{"text": "\n//  (C) Copyright Edward Diener 2011-2015\n//  Use, modification and distribution are 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#include <boost/vmd/is_number.hpp>\n#include <boost/detail/lightweight_test.hpp>\n\nint main()\n  {\n\n#if BOOST_PP_VARIADICS\n\n BOOST_TEST(BOOST_VMD_IS_NUMBER(0));\n BOOST_TEST(BOOST_VMD_IS_NUMBER(44));\n BOOST_TEST(!BOOST_VMD_IS_NUMBER(SQUARE));\n BOOST_TEST(!BOOST_VMD_IS_NUMBER(44 DATA));\n BOOST_TEST(!BOOST_VMD_IS_NUMBER(044));\n BOOST_TEST(BOOST_VMD_IS_NUMBER(256));\n BOOST_TEST(!BOOST_VMD_IS_NUMBER(257));\n BOOST_TEST(!BOOST_VMD_IS_NUMBER(245e2));\n BOOST_TEST(!BOOST_VMD_IS_NUMBER((44)));\n\n#else\n\nBOOST_ERROR(\"No variadic macro support\");\n\n#endif\n\n  return boost::report_errors();\n\n  }\n", "meta": {"hexsha": "14f0cdee293525074ee850feec46e1e035f71900", "size": 818, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/vmd/test/test_doc_number.cxx", "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/vmd/test/test_doc_number.cxx", "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/vmd/test/test_doc_number.cxx", "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": 24.0588235294, "max_line_length": 81, "alphanum_fraction": 0.7616136919, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.16667350968844552}}
{"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// 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_ALGORITHMS_SIMPLIFY_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_SIMPLIFY_HPP\n\n#include <cstddef>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/range.hpp>\n\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/static_visitor.hpp>\n#include <boost/variant/variant_fwd.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n#include <boost/geometry/core/mutable_range.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/geometries/concepts/check.hpp>\n#include <boost/geometry/strategies/agnostic/simplify_douglas_peucker.hpp>\n#include <boost/geometry/strategies/concepts/simplify_concept.hpp>\n#include <boost/geometry/strategies/default_strategy.hpp>\n#include <boost/geometry/strategies/distance.hpp>\n\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/clear.hpp>\n#include <boost/geometry/algorithms/convert.hpp>\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\n#include <boost/geometry/algorithms/not_implemented.hpp>\n#include <boost/geometry/algorithms/is_empty.hpp>\n#include <boost/geometry/algorithms/perimeter.hpp>\n\n#include <boost/geometry/algorithms/detail/distance/default_strategies.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace simplify\n{\n\ntemplate <typename Range>\ninline bool is_degenerate(Range const& range)\n{\n    return boost::size(range) == 2\n        && detail::equals::equals_point_point(geometry::range::front(range),\n                                              geometry::range::back(range));\n}\n\nstruct simplify_range_insert\n{\n    template<typename Range, typename Strategy, typename OutputIterator, typename Distance>\n    static inline void apply(Range const& range, OutputIterator out,\n                             Distance const& max_distance, Strategy const& strategy)\n    {\n        boost::ignore_unused(strategy);\n\n        if (is_degenerate(range))\n        {\n            std::copy(boost::begin(range), boost::begin(range) + 1, out);\n        }\n        else if (boost::size(range) <= 2 || max_distance < 0)\n        {\n            std::copy(boost::begin(range), boost::end(range), out);\n        }\n        else\n        {\n            strategy.apply(range, out, max_distance);\n        }\n    }\n};\n\n\nstruct simplify_copy\n{\n    template <typename RangeIn, typename RangeOut, typename Strategy, typename Distance>\n    static inline void apply(RangeIn const& range, RangeOut& out,\n                             Distance const& , Strategy const& )\n    {\n        std::copy\n            (\n                boost::begin(range), boost::end(range),\n                    geometry::range::back_inserter(out)\n            );\n    }\n};\n\n\ntemplate <std::size_t MinimumToUseStrategy>\nstruct simplify_range\n{\n    template <typename RangeIn, typename RangeOut, typename Strategy, typename Distance>\n    static inline void apply(RangeIn const& range, RangeOut& out,\n                    Distance const& max_distance, Strategy const& strategy)\n    {\n        // For a RING:\n        // Note that, especially if max_distance is too large,\n        // the output ring might be self intersecting while the input ring is\n        // not, although chances are low in normal polygons\n\n        if (boost::size(range) <= MinimumToUseStrategy || max_distance < 0)\n        {\n            simplify_copy::apply(range, out, max_distance, strategy);\n        }\n        else\n        {\n            simplify_range_insert::apply\n                (\n                    range, geometry::range::back_inserter(out), max_distance, strategy\n                );\n        }\n\n        // Verify the two remaining points are equal. If so, remove one of them.\n        // This can cause the output being under the minimum size\n        if (is_degenerate(out))\n        {\n            range::resize(out, 1);\n        }\n    }\n};\n\nstruct simplify_ring\n{\nprivate :\n    template <typename Area>\n    static inline int area_sign(Area const& area)\n    {\n        return area > 0 ? 1 : area < 0 ? -1 : 0;\n    }\n\n    template <typename Strategy, typename Ring>\n    static std::size_t get_opposite(std::size_t index, Ring const& ring)\n    {\n        typename Strategy::distance_strategy_type distance_strategy;\n\n        // Verify if it is NOT the case that all points are less than the\n        // simplifying distance. If so, output is empty.\n        typename Strategy::distance_type max_distance(-1);\n\n        typename geometry::point_type<Ring>::type point = range::at(ring, index);\n        std::size_t i = 0;\n        for (typename boost::range_iterator<Ring const>::type\n                it = boost::begin(ring); it != boost::end(ring); ++it, ++i)\n        {\n            // This actually is point-segment distance but will result\n            // in point-point distance\n            typename Strategy::distance_type dist = distance_strategy.apply(*it, point, point);\n            if (dist > max_distance)\n            {\n                max_distance = dist;\n                index = i;\n            }\n        }\n        return index;\n    }\n\npublic :\n    template <typename Ring, typename Strategy, typename Distance>\n    static inline void apply(Ring const& ring, Ring& out,\n                    Distance const& max_distance, Strategy const& strategy)\n    {\n        std::size_t const size = boost::size(ring);\n        if (size == 0)\n        {\n            return;\n        }\n\n        int const input_sign = area_sign(geometry::area(ring));\n\n        std::set<std::size_t> visited_indexes;\n\n        // Rotate it into a copied vector\n        // (vector, because source type might not support rotation)\n        // (duplicate end point will be simplified away)\n        typedef typename geometry::point_type<Ring>::type point_type;\n\n        std::vector<point_type> rotated(size);\n\n        // Closing point (but it will not start here)\n        std::size_t index = 0;\n\n        // Iterate (usually one iteration is enough)\n        for (std::size_t iteration = 0; iteration < 4u; iteration++)\n        {\n            // Always take the opposite. Opposite guarantees that no point\n            // \"halfway\" is chosen, creating an artefact (very narrow triangle)\n            // Iteration 0: opposite to closing point (1/2, = on convex hull)\n            //              (this will start simplification with that point\n            //               and its opposite ~0)\n            // Iteration 1: move a quarter on that ring, then opposite to 1/4\n            //              (with its opposite 3/4)\n            // Iteration 2: move an eight on that ring, then opposite (1/8)\n            // Iteration 3: again move a quarter, then opposite (7/8)\n            // So finally 8 \"sides\" of the ring have been examined (if it were\n            // a semi-circle). Most probably, there are only 0 or 1 iterations.\n            switch (iteration)\n            {\n                case 1 : index = (index + size / 4) % size; break;\n                case 2 : index = (index + size / 8) % size; break;\n                case 3 : index = (index + size / 4) % size; break;\n            }\n            index = get_opposite<Strategy>(index, ring);\n\n            if (visited_indexes.count(index) > 0)\n            {\n                // Avoid trying the same starting point more than once\n                continue;\n            }\n\n            std::rotate_copy(boost::begin(ring), range::pos(ring, index),\n                             boost::end(ring), rotated.begin());\n\n            // Close the rotated copy\n            rotated.push_back(range::at(ring, index));\n\n            simplify_range<0>::apply(rotated, out, max_distance, strategy);\n\n            // Verify that what was positive, stays positive (or goes to 0)\n            // and what was negative stays negative (or goes to 0)\n            int const output_sign = area_sign(geometry::area(out));\n            if (output_sign == input_sign)\n            {\n                // Result is considered as satisfactory (usually this is the\n                // first iteration - only for small rings, having a scale\n                // similar to simplify_distance, next iterations are tried\n                return;\n            }\n\n            // Original is simplified away. Possibly there is a solution\n            // when another starting point is used\n            geometry::clear(out);\n\n            if (iteration == 0\n                && geometry::perimeter(ring) < 3 * max_distance)\n            {\n                // Check if it is useful to iterate. A minimal triangle has a\n                // perimeter of a bit more than 3 times the simplify distance\n                return;\n            }\n\n            // Prepare next try\n            visited_indexes.insert(index);\n            rotated.resize(size);\n        }\n    }\n};\n\n\nstruct simplify_polygon\n{\nprivate:\n\n    template\n    <\n        typename IteratorIn,\n        typename InteriorRingsOut,\n        typename Distance,\n        typename Strategy\n    >\n    static inline void iterate(IteratorIn begin, IteratorIn end,\n                    InteriorRingsOut& interior_rings_out,\n                    Distance const& max_distance, Strategy const& strategy)\n    {\n        typedef typename boost::range_value<InteriorRingsOut>::type single_type;\n        for (IteratorIn it = begin; it != end; ++it)\n        {\n            single_type out;\n            simplify_ring::apply(*it, out, max_distance, strategy);\n            if (! geometry::is_empty(out))\n            {\n                range::push_back(interior_rings_out, out);\n            }\n        }\n    }\n\n    template\n    <\n        typename InteriorRingsIn,\n        typename InteriorRingsOut,\n        typename Distance,\n        typename Strategy\n    >\n    static inline void apply_interior_rings(\n                    InteriorRingsIn const& interior_rings_in,\n                    InteriorRingsOut& interior_rings_out,\n                    Distance const& max_distance, Strategy const& strategy)\n    {\n        range::clear(interior_rings_out);\n\n        iterate(\n            boost::begin(interior_rings_in), boost::end(interior_rings_in),\n            interior_rings_out,\n            max_distance, strategy);\n    }\n\npublic:\n    template <typename Polygon, typename Strategy, typename Distance>\n    static inline void apply(Polygon const& poly_in, Polygon& poly_out,\n                    Distance const& max_distance, Strategy const& strategy)\n    {\n        // Note that if there are inner rings, and distance is too large,\n        // they might intersect with the outer ring in the output,\n        // while it didn't in the input.\n        simplify_ring::apply(exterior_ring(poly_in), exterior_ring(poly_out),\n            max_distance, strategy);\n\n        apply_interior_rings(interior_rings(poly_in),\n            interior_rings(poly_out), max_distance, strategy);\n    }\n};\n\n\ntemplate<typename Policy>\nstruct simplify_multi\n{\n    template <typename MultiGeometry, typename Strategy, typename Distance>\n    static inline void apply(MultiGeometry const& multi, MultiGeometry& out,\n                    Distance const& max_distance, Strategy const& strategy)\n    {\n        range::clear(out);\n\n        typedef typename boost::range_value<MultiGeometry>::type single_type;\n\n        for (typename boost::range_iterator<MultiGeometry const>::type\n                it = boost::begin(multi); it != boost::end(multi); ++it)\n        {\n            single_type single_out;\n            Policy::apply(*it, single_out, max_distance, strategy);\n            if (! geometry::is_empty(single_out))\n            {\n                range::push_back(out, single_out);\n            }\n        }\n    }\n};\n\n\n}} // namespace detail::simplify\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate\n<\n    typename Geometry,\n    typename Tag = typename tag<Geometry>::type\n>\nstruct simplify: not_implemented<Tag>\n{};\n\ntemplate <typename Point>\nstruct simplify<Point, point_tag>\n{\n    template <typename Distance, typename Strategy>\n    static inline void apply(Point const& point, Point& out,\n                    Distance const& , Strategy const& )\n    {\n        geometry::convert(point, out);\n    }\n};\n\n// Linestring, keep 2 points (unless those points are the same)\ntemplate <typename Linestring>\nstruct simplify<Linestring, linestring_tag>\n    : detail::simplify::simplify_range<2>\n{};\n\ntemplate <typename Ring>\nstruct simplify<Ring, ring_tag>\n    : detail::simplify::simplify_ring\n{};\n\ntemplate <typename Polygon>\nstruct simplify<Polygon, polygon_tag>\n    : detail::simplify::simplify_polygon\n{};\n\n\ntemplate\n<\n    typename Geometry,\n    typename Tag = typename tag<Geometry>::type\n>\nstruct simplify_insert: not_implemented<Tag>\n{};\n\n\ntemplate <typename Linestring>\nstruct simplify_insert<Linestring, linestring_tag>\n    : detail::simplify::simplify_range_insert\n{};\n\ntemplate <typename Ring>\nstruct simplify_insert<Ring, ring_tag>\n    : detail::simplify::simplify_range_insert\n{};\n\ntemplate <typename MultiPoint>\nstruct simplify<MultiPoint, multi_point_tag>\n    : detail::simplify::simplify_copy\n{};\n\n\ntemplate <typename MultiLinestring>\nstruct simplify<MultiLinestring, multi_linestring_tag>\n    : detail::simplify::simplify_multi<detail::simplify::simplify_range<2> >\n{};\n\n\ntemplate <typename MultiPolygon>\nstruct simplify<MultiPolygon, multi_polygon_tag>\n    : detail::simplify::simplify_multi<detail::simplify::simplify_polygon>\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy\n{\n\nstruct simplify\n{\n    template <typename Geometry, typename Distance, typename Strategy>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             Strategy const& strategy)\n    {\n        dispatch::simplify<Geometry>::apply(geometry, out, max_distance, strategy);\n    }\n\n    template <typename Geometry, typename Distance>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             default_strategy)\n    {\n        typedef typename point_type<Geometry>::type point_type;\n\n        typedef typename strategy::distance::services::default_strategy\n        <\n            point_tag, segment_tag, point_type\n        >::type ds_strategy_type;\n\n        typedef strategy::simplify::douglas_peucker\n        <\n            point_type, ds_strategy_type\n        > strategy_type;\n\n        BOOST_CONCEPT_ASSERT(\n            (concepts::SimplifyStrategy<strategy_type, point_type>)\n        );\n\n        apply(geometry, out, max_distance, strategy_type());\n    }\n};\n\nstruct simplify_insert\n{\n    template\n    <\n        typename Geometry,\n        typename OutputIterator,\n        typename Distance,\n        typename Strategy\n    >\n    static inline void apply(Geometry const& geometry,\n                             OutputIterator& out,\n                             Distance const& max_distance,\n                             Strategy const& strategy)\n    {\n        dispatch::simplify_insert<Geometry>::apply(geometry, out, max_distance, strategy);\n    }\n\n    template <typename Geometry, typename OutputIterator, typename Distance>\n    static inline void apply(Geometry const& geometry,\n                             OutputIterator& out,\n                             Distance const& max_distance,\n                             default_strategy)\n    {\n        typedef typename point_type<Geometry>::type point_type;\n\n        typedef typename strategy::distance::services::default_strategy\n        <\n            point_tag, segment_tag, point_type\n        >::type ds_strategy_type;\n\n        typedef strategy::simplify::douglas_peucker\n        <\n            point_type, ds_strategy_type\n        > strategy_type;\n\n        BOOST_CONCEPT_ASSERT(\n            (concepts::SimplifyStrategy<strategy_type, point_type>)\n        );\n\n        apply(geometry, out, max_distance, strategy_type());\n    }\n};\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_variant {\n\ntemplate <typename Geometry>\nstruct simplify\n{\n    template <typename Distance, typename Strategy>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             Strategy const& strategy)\n    {\n        resolve_strategy::simplify::apply(geometry, out, max_distance, strategy);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct simplify<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    template <typename Distance, typename Strategy>\n    struct visitor: boost::static_visitor<void>\n    {\n        Distance const& m_max_distance;\n        Strategy const& m_strategy;\n\n        visitor(Distance const& max_distance, Strategy const& strategy)\n            : m_max_distance(max_distance)\n            , m_strategy(strategy)\n        {}\n\n        template <typename Geometry>\n        void operator()(Geometry const& geometry, Geometry& out) const\n        {\n            simplify<Geometry>::apply(geometry, out, m_max_distance, m_strategy);\n        }\n    };\n\n    template <typename Distance, typename Strategy>\n    static inline void\n    apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry,\n          boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>& out,\n          Distance const& max_distance,\n          Strategy const& strategy)\n    {\n        boost::apply_visitor(\n            visitor<Distance, Strategy>(max_distance, strategy),\n            geometry,\n            out\n        );\n    }\n};\n\n} // namespace resolve_variant\n\n\n/*!\n\\brief Simplify a geometry using a specified strategy\n\\ingroup simplify\n\\tparam Geometry \\tparam_geometry\n\\tparam Distance A numerical distance measure\n\\tparam Strategy A type fulfilling a SimplifyStrategy concept\n\\param strategy A strategy to calculate simplification\n\\param geometry input geometry, to be simplified\n\\param out output geometry, simplified version of the input geometry\n\\param max_distance distance (in units of input coordinates) of a vertex\n    to other segments to be removed\n\\param strategy simplify strategy to be used for simplification, might\n    include point-distance strategy\n\n\\image html svg_simplify_country.png \"The image below presents the simplified country\"\n\\qbk{distinguish,with strategy}\n*/\ntemplate<typename Geometry, typename Distance, typename Strategy>\ninline void simplify(Geometry const& geometry, Geometry& out,\n                     Distance const& max_distance, Strategy const& strategy)\n{\n    concepts::check<Geometry>();\n\n    geometry::clear(out);\n\n    resolve_variant::simplify<Geometry>::apply(geometry, out, max_distance, strategy);\n}\n\n\n\n\n/*!\n\\brief Simplify a geometry\n\\ingroup simplify\n\\tparam Geometry \\tparam_geometry\n\\tparam Distance \\tparam_numeric\n\\note This version of simplify simplifies a geometry using the default\n    strategy (Douglas Peucker),\n\\param geometry input geometry, to be simplified\n\\param out output geometry, simplified version of the input geometry\n\\param max_distance distance (in units of input coordinates) of a vertex\n    to other segments to be removed\n\n\\qbk{[include reference/algorithms/simplify.qbk]}\n */\ntemplate<typename Geometry, typename Distance>\ninline void simplify(Geometry const& geometry, Geometry& out,\n                     Distance const& max_distance)\n{\n    concepts::check<Geometry>();\n\n    geometry::simplify(geometry, out, max_distance, default_strategy());\n}\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace simplify\n{\n\n\n/*!\n\\brief Simplify a geometry, using an output iterator\n    and a specified strategy\n\\ingroup simplify\n\\tparam Geometry \\tparam_geometry\n\\param geometry input geometry, to be simplified\n\\param out output iterator, outputs all simplified points\n\\param max_distance distance (in units of input coordinates) of a vertex\n    to other segments to be removed\n\\param strategy simplify strategy to be used for simplification,\n    might include point-distance strategy\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/simplify.qbk]}\n*/\ntemplate<typename Geometry, typename OutputIterator, typename Distance, typename Strategy>\ninline void simplify_insert(Geometry const& geometry, OutputIterator out,\n                            Distance const& max_distance, Strategy const& strategy)\n{\n    concepts::check<Geometry const>();\n\n    resolve_strategy::simplify_insert::apply(geometry, out, max_distance, strategy);\n}\n\n/*!\n\\brief Simplify a geometry, using an output iterator\n\\ingroup simplify\n\\tparam Geometry \\tparam_geometry\n\\param geometry input geometry, to be simplified\n\\param out output iterator, outputs all simplified points\n\\param max_distance distance (in units of input coordinates) of a vertex\n    to other segments to be removed\n\n\\qbk{[include reference/algorithms/simplify_insert.qbk]}\n */\ntemplate<typename Geometry, typename OutputIterator, typename Distance>\ninline void simplify_insert(Geometry const& geometry, OutputIterator out,\n                            Distance const& max_distance)\n{\n    // Concept: output point type = point type of input geometry\n    concepts::check<Geometry const>();\n    concepts::check<typename point_type<Geometry>::type>();\n\n    simplify_insert(geometry, out, max_distance, default_strategy());\n}\n\n}} // namespace detail::simplify\n#endif // DOXYGEN_NO_DETAIL\n\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_SIMPLIFY_HPP\n", "meta": {"hexsha": "298f9c640aaf0d12e614a0e9d9242c5e39348002", "size": 22082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/boost/geometry/algorithms/simplify.hpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "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/boost/boost/geometry/algorithms/simplify.hpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "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/boost/boost/geometry/algorithms/simplify.hpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "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.9565846599, "max_line_length": 95, "alphanum_fraction": 0.6491712707, "num_tokens": 4609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.16667350968844546}}
{"text": "// Copyright (C) 2011-2012 by the Bem++ 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 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#ifndef fiber_default_local_assembler_for_integral_operators_on_surfaces_hpp\n#define fiber_default_local_assembler_for_integral_operators_on_surfaces_hpp\n\n#include \"../common/common.hpp\"\n\n#include \"local_assembler_for_operators.hpp\"\n\n#include \"_2d_array.hpp\"\n#include \"accuracy_options.hpp\"\n#include \"default_local_assembler_for_operators_on_surfaces_utilities.hpp\"\n#include \"element_pair_topology.hpp\"\n#include \"numerical_quadrature.hpp\"\n#include \"parallelization_options.hpp\"\n#include \"shared_ptr.hpp\"\n#include \"test_kernel_trial_integrator.hpp\"\n#include \"verbosity_level.hpp\"\n\n#include <boost/static_assert.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <tbb/concurrent_unordered_map.h>\n#include <cstring>\n#include <climits>\n#include <set>\n#include <utility>\n#include <vector>\n\nnamespace Fiber\n{\n\n/** \\cond FORWARD_DECL */\nclass OpenClHandler;\ntemplate <typename CoordinateType> class CollectionOfBasisTransformations;\ntemplate <typename ValueType> class CollectionOfKernels;\ntemplate <typename BasisFunctionType, typename KernelType, typename ResultType>\nclass TestKernelTrialIntegral;\ntemplate <typename CoordinateType> class RawGridGeometry;\n/** \\endcond */\n\ntemplate <typename BasisFunctionType, typename KernelType,\n          typename ResultType, typename GeometryFactory>\nclass DefaultLocalAssemblerForIntegralOperatorsOnSurfaces :\n        public LocalAssemblerForOperators<ResultType>\n{\npublic:\n    typedef typename ScalarTraits<ResultType>::RealType CoordinateType;\n\n    DefaultLocalAssemblerForIntegralOperatorsOnSurfaces(\n            const shared_ptr<const GeometryFactory>& testGeometryFactory,\n            const shared_ptr<const GeometryFactory>& trialGeometryFactory,\n            const shared_ptr<const RawGridGeometry<CoordinateType> >& testRawGeometry,\n            const shared_ptr<const RawGridGeometry<CoordinateType> >& trialRawGeometry,\n            const shared_ptr<const std::vector<const Basis<BasisFunctionType>*> >& testBases,\n            const shared_ptr<const std::vector<const Basis<BasisFunctionType>*> >& trialBases,\n            const shared_ptr<const CollectionOfBasisTransformations<CoordinateType> >& testTransformations,\n            const shared_ptr<const CollectionOfKernels<KernelType> >& kernel,\n            const shared_ptr<const CollectionOfBasisTransformations<CoordinateType> >& trialTransformations,\n            const shared_ptr<const TestKernelTrialIntegral<BasisFunctionType, KernelType, ResultType> >& integral,\n            const shared_ptr<const OpenClHandler>& openClHandler,\n            const ParallelizationOptions& parallelizationOptions,\n            VerbosityLevel::Level verbosityLevel,\n            bool cacheSingularIntegrals,\n            const AccuracyOptionsEx& accuracyOptions);\n    virtual ~DefaultLocalAssemblerForIntegralOperatorsOnSurfaces();\n\npublic:\n    virtual void evaluateLocalWeakForms(\n            CallVariant callVariant,\n            const std::vector<int>& elementIndicesA,\n            int elementIndexB,\n            LocalDofIndex localDofIndexB,\n            std::vector<arma::Mat<ResultType> >& result,\n            CoordinateType nominalDistance = -1.);\n\n    virtual void evaluateLocalWeakForms(\n            const std::vector<int>& testElementIndices,\n            const std::vector<int>& trialElementIndices,\n            Fiber::_2dArray<arma::Mat<ResultType> >& result,\n            CoordinateType nominalDistance = -1.);\n\n    virtual void evaluateLocalWeakForms(\n            const std::vector<int>& elementIndices,\n            std::vector<arma::Mat<ResultType> >& result);\n\n    virtual CoordinateType estimateRelativeScale(CoordinateType minDist) const;\n\nprivate:\n    /** \\cond PRIVATE */\n    typedef TestKernelTrialIntegrator<BasisFunctionType, KernelType, ResultType> Integrator;\n    typedef typename Integrator::ElementIndexPair ElementIndexPair;\n    typedef DefaultLocalAssemblerForOperatorsOnSurfacesUtilities<\n    BasisFunctionType> Utilities;\n\n    /** \\brief Alternative comparison functor for pairs.\n     *\n     *  This functor can be used to sort pairs according to the second member\n     *  and then, in case of equality, according to the first member. */\n    template <typename T1, typename T2>\n    struct alternative_less {\n        bool operator() (const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) const {\n            return a.second < b.second\n                || (!(b.second < a.second) && a.first < b.first);\n        }\n    };\n\n    /** \\brief Comparison functor for element-index pairs.\n     *\n     *  This functor sorts element index pairs first after the trial element\n     *  index (second member) and then, in case of equality, after the test\n     *  element index (first member) */\n    typedef alternative_less<\n        typename ElementIndexPair::first_type,\n        typename ElementIndexPair::second_type> ElementIndexPairCompare;\n\n    /** \\brief Set of element index pairs.\n     *\n     *  The alternative sorting (first after the trial element index) is used\n     *  because profiling has shown that evaluateLocalWeakForms is called more\n     *  often in the TEST_TRIAL mode (with a single trial element index) than\n     *  in the TRIAL_TEST mode. Therefore the singular integral cache is\n     *  indexed with trial element index, and this sorting mode makes it easier\n     *  to construct such cache. */\n    typedef std::set<ElementIndexPair, ElementIndexPairCompare> ElementIndexPairSet;\n\n    bool testAndTrialGridsAreIdentical() const;\n\n    void cacheSingularLocalWeakForms();\n    void findPairsOfAdjacentElements(ElementIndexPairSet& pairs) const;\n    void cacheLocalWeakForms(const ElementIndexPairSet& elementIndexPairs);\n\n    const Integrator& selectIntegrator(\n            int testElementIndex, int trialElementIndex,\n            CoordinateType nominalDistance = -1.);\n\n    enum ElementType {\n        TEST, TRIAL\n    };\n\n    const Integrator& getIntegrator(const DoubleQuadratureDescriptor& index);\n\n    void getRegularOrders(int testElementIndex, int trialElementIndex,\n                          int& testQuadOrder, int& trialQuadOrder,\n                          CoordinateType nominalDistance) const;\n    int singularOrder(int elementIndex, ElementType elementType) const;\n\n    CoordinateType elementDistanceSquared(\n            int testElementIndex, int trialElementIndex) const;\n\n    void precalculateElementSizesAndCenters();\n\nprivate:\n    shared_ptr<const GeometryFactory> m_testGeometryFactory;\n    shared_ptr<const GeometryFactory> m_trialGeometryFactory;\n    shared_ptr<const RawGridGeometry<CoordinateType> > m_testRawGeometry;\n    shared_ptr<const RawGridGeometry<CoordinateType> > m_trialRawGeometry;\n    shared_ptr<const std::vector<const Basis<BasisFunctionType>*> > m_testBases;\n    shared_ptr<const std::vector<const Basis<BasisFunctionType>*> > m_trialBases;\n    shared_ptr<const CollectionOfBasisTransformations<CoordinateType> > m_testTransformations;\n    shared_ptr<const CollectionOfKernels<KernelType> > m_kernels;\n    shared_ptr<const CollectionOfBasisTransformations<CoordinateType> > m_trialTransformations;\n    shared_ptr<const TestKernelTrialIntegral<BasisFunctionType, KernelType, ResultType> > m_integral;\n    shared_ptr<const OpenClHandler> m_openClHandler;\n    ParallelizationOptions m_parallelizationOptions;\n    VerbosityLevel::Level m_verbosityLevel;\n    AccuracyOptionsEx m_accuracyOptions;\n\n    typedef tbb::concurrent_unordered_map<DoubleQuadratureDescriptor,\n    Integrator*> IntegratorMap;\n    IntegratorMap m_testKernelTrialIntegrators;\n\n    enum { INVALID_INDEX = INT_MAX };\n    typedef _2dArray<std::pair<int, arma::Mat<ResultType> > > Cache;\n    /** \\brief Singular integral cache.\n     *\n     *  This cache stores the preevaluated local weak forms expressed by\n     *  singular integrals. A particular item it stored in r'th row and c'th\n     *  column stores, in its second member, the local weak form calculated for\n     *  the test element with index it.first and the trial element with index\n     *  c. In each column, the items are sorted after increasing test element\n     *  index. At the end of each column there can be unused items with test\n     *  element index set to INVALID_INDEX (= INT_MAX, so that the sorting is\n     *  preserved). */\n    Cache m_cache;\n    std::vector<CoordinateType> m_testElementSizesSquared;\n    std::vector<CoordinateType> m_trialElementSizesSquared;\n    arma::Mat<CoordinateType> m_testElementCenters;\n    arma::Mat<CoordinateType> m_trialElementCenters;\n    CoordinateType m_averageElementSize;\n\n    // tbb::atomic<size_t> m_foundInCache;\n    /** \\endcond */\n};\n\n} // namespace Fiber\n\n#include \"default_local_assembler_for_integral_operators_on_surfaces_imp.hpp\"\n\n#endif\n", "meta": {"hexsha": "ce1fec81f7e40c8db1bdd643a5c18a12a4242fc9", "size": 9797, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/fiber/default_local_assembler_for_integral_operators_on_surfaces.hpp", "max_stars_repo_name": "UCL/bempp", "max_stars_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T13:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T13:35:20.000Z", "max_issues_repo_path": "lib/fiber/default_local_assembler_for_integral_operators_on_surfaces.hpp", "max_issues_repo_name": "UCL/bempp", "max_issues_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "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": "lib/fiber/default_local_assembler_for_integral_operators_on_surfaces.hpp", "max_forks_repo_name": "UCL/bempp", "max_forks_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "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": 44.9403669725, "max_line_length": 114, "alphanum_fraction": 0.7464529958, "num_tokens": 2098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.16667350968844544}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\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_COLOR_CONVERT_HPP\n#define BOOST_GIL_COLOR_CONVERT_HPP\n\n#include <boost/gil/channel_algorithm.hpp>\n#include <boost/gil/cmyk.hpp>\n#include <boost/gil/color_base_algorithm.hpp>\n#include <boost/gil/gray.hpp>\n#include <boost/gil/metafunctions.hpp>\n#include <boost/gil/pixel.hpp>\n#include <boost/gil/rgb.hpp>\n#include <boost/gil/rgba.hpp>\n#include <boost/gil/utilities.hpp>\n\n#include <algorithm>\n#include <functional>\n\nnamespace boost { namespace gil {\n\n/// Support for fast and simple color conversion.\n/// Accurate color conversion using color profiles can be supplied separately in a dedicated module.\n\n// Forward-declare\ntemplate <typename P> struct channel_type;\n\n////////////////////////////////////////////////////////////////////////////////////////\n///\n///                 COLOR SPACE CONVERSION\n///\n////////////////////////////////////////////////////////////////////////////////////////\n\n/// \\ingroup ColorConvert\n/// \\brief Color Convertion function object. To be specialized for every src/dst color space\ntemplate <typename C1, typename C2>\nstruct default_color_converter_impl {};\n\n/// \\ingroup ColorConvert\n/// \\brief When the color space is the same, color convertion performs channel depth conversion\ntemplate <typename C>\nstruct default_color_converter_impl<C,C> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        static_for_each(src,dst,default_channel_converter());\n    }\n};\n\nnamespace detail {\n\n/// red * .3 + green * .59 + blue * .11 + .5\n\n// The default implementation of to_luminance uses float0..1 as the intermediate channel type\ntemplate <typename RedChannel, typename GreenChannel, typename BlueChannel, typename GrayChannelValue>\nstruct rgb_to_luminance_fn {\n    GrayChannelValue operator()(const RedChannel& red, const GreenChannel& green, const BlueChannel& blue) const {\n        return channel_convert<GrayChannelValue>(float32_t(\n            channel_convert<float32_t>(red  )*0.30f +\n            channel_convert<float32_t>(green)*0.59f +\n            channel_convert<float32_t>(blue )*0.11f) );\n    }\n};\n\n// performance specialization for unsigned char\ntemplate <typename GrayChannelValue>\nstruct rgb_to_luminance_fn<uint8_t,uint8_t,uint8_t, GrayChannelValue> {\n    GrayChannelValue operator()(uint8_t red, uint8_t green, uint8_t blue) const {\n        return channel_convert<GrayChannelValue>(uint8_t(\n            ((uint32_t(red  )*4915 + uint32_t(green)*9667 + uint32_t(blue )*1802) + 8192) >> 14));\n    }\n};\n\ntemplate <typename GrayChannel, typename RedChannel, typename GreenChannel, typename BlueChannel>\ntypename channel_traits<GrayChannel>::value_type rgb_to_luminance(const RedChannel& red, const GreenChannel& green, const BlueChannel& blue) {\n    return rgb_to_luminance_fn<RedChannel,GreenChannel,BlueChannel,\n                               typename channel_traits<GrayChannel>::value_type>()(red,green,blue);\n}\n\n}   // namespace detail\n\n/// \\ingroup ColorConvert\n/// \\brief Gray to RGB\ntemplate <>\nstruct default_color_converter_impl<gray_t,rgb_t> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        get_color(dst,red_t())  =\n            channel_convert<typename color_element_type<P2, red_t  >::type>(get_color(src,gray_color_t()));\n        get_color(dst,green_t())=\n            channel_convert<typename color_element_type<P2, green_t>::type>(get_color(src,gray_color_t()));\n        get_color(dst,blue_t()) =\n            channel_convert<typename color_element_type<P2, blue_t >::type>(get_color(src,gray_color_t()));\n    }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief Gray to CMYK\ntemplate <>\nstruct default_color_converter_impl<gray_t,cmyk_t> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        get_color(dst,cyan_t())=\n            channel_traits<typename color_element_type<P2, cyan_t   >::type>::min_value();\n        get_color(dst,magenta_t())=\n            channel_traits<typename color_element_type<P2, magenta_t>::type>::min_value();\n        get_color(dst,yellow_t())=\n            channel_traits<typename color_element_type<P2, yellow_t >::type>::min_value();\n        get_color(dst,black_t())=\n            channel_convert<typename color_element_type<P2, black_t >::type>(get_color(src,gray_color_t()));\n    }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief RGB to Gray\ntemplate <>\nstruct default_color_converter_impl<rgb_t,gray_t> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        get_color(dst,gray_color_t()) =\n            detail::rgb_to_luminance<typename color_element_type<P2,gray_color_t>::type>(\n                get_color(src,red_t()), get_color(src,green_t()), get_color(src,blue_t())\n            );\n    }\n};\n\n\n/// \\ingroup ColorConvert\n/// \\brief RGB to CMYK (not the fastest code in the world)\n///\n/// k = min(1 - r, 1 - g, 1 - b)\n/// c = (1 - r - k) / (1 - k)\n/// m = (1 - g - k) / (1 - k)\n/// y = (1 - b - k) / (1 - k)\ntemplate <>\nstruct default_color_converter_impl<rgb_t,cmyk_t> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        using T2 = typename channel_type<P2>::type;\n        get_color(dst,cyan_t())    = channel_invert(channel_convert<T2>(get_color(src,red_t())));          // c = 1 - r\n        get_color(dst,magenta_t()) = channel_invert(channel_convert<T2>(get_color(src,green_t())));        // m = 1 - g\n        get_color(dst,yellow_t())  = channel_invert(channel_convert<T2>(get_color(src,blue_t())));         // y = 1 - b\n        get_color(dst,black_t())   = (std::min)(get_color(dst,cyan_t()),\n                                                (std::min)(get_color(dst,magenta_t()),\n                                                           get_color(dst,yellow_t())));   // k = minimum(c, m, y)\n        T2 x = channel_traits<T2>::max_value()-get_color(dst,black_t());                  // x = 1 - k\n        if (x>0.0001f) {\n            float x1 = channel_traits<T2>::max_value()/float(x);\n            get_color(dst,cyan_t())    = (T2)((get_color(dst,cyan_t())    - get_color(dst,black_t()))*x1);                // c = (c - k) / x\n            get_color(dst,magenta_t()) = (T2)((get_color(dst,magenta_t()) - get_color(dst,black_t()))*x1);                // m = (m - k) / x\n            get_color(dst,yellow_t())  = (T2)((get_color(dst,yellow_t())  - get_color(dst,black_t()))*x1);                // y = (y - k) / x\n        } else {\n            get_color(dst,cyan_t())=get_color(dst,magenta_t())=get_color(dst,yellow_t())=0;\n        }\n    }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief CMYK to RGB (not the fastest code in the world)\n///\n/// r = 1 - min(1, c*(1-k)+k)\n/// g = 1 - min(1, m*(1-k)+k)\n/// b = 1 - min(1, y*(1-k)+k)\ntemplate <>\nstruct default_color_converter_impl<cmyk_t,rgb_t> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        using T1 = typename channel_type<P1>::type;\n        get_color(dst,red_t())  =\n            channel_convert<typename color_element_type<P2,red_t>::type>(\n                channel_invert<T1>(\n                    (std::min)(channel_traits<T1>::max_value(),\n                             T1(channel_multiply(get_color(src,cyan_t()),channel_invert(get_color(src,black_t())))+get_color(src,black_t())))));\n        get_color(dst,green_t())=\n            channel_convert<typename color_element_type<P2,green_t>::type>(\n                channel_invert<T1>(\n                    (std::min)(channel_traits<T1>::max_value(),\n                             T1(channel_multiply(get_color(src,magenta_t()),channel_invert(get_color(src,black_t())))+get_color(src,black_t())))));\n        get_color(dst,blue_t()) =\n            channel_convert<typename color_element_type<P2,blue_t>::type>(\n                channel_invert<T1>(\n                    (std::min)(channel_traits<T1>::max_value(),\n                             T1(channel_multiply(get_color(src,yellow_t()),channel_invert(get_color(src,black_t())))+get_color(src,black_t())))));\n    }\n};\n\n\n/// \\ingroup ColorConvert\n/// \\brief CMYK to Gray\n///\n/// gray = (1 - 0.212c - 0.715m - 0.0722y) * (1 - k)\ntemplate <>\nstruct default_color_converter_impl<cmyk_t,gray_t> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const  {\n        get_color(dst,gray_color_t())=\n            channel_convert<typename color_element_type<P2,gray_color_t>::type>(\n                channel_multiply(\n                    channel_invert(\n                       detail::rgb_to_luminance<typename color_element_type<P1,black_t>::type>(\n                            get_color(src,cyan_t()),\n                            get_color(src,magenta_t()),\n                            get_color(src,yellow_t())\n                       )\n                    ),\n                    channel_invert(get_color(src,black_t()))));\n    }\n};\n\nnamespace detail {\ntemplate <typename Pixel>\ntypename channel_type<Pixel>::type alpha_or_max_impl(const Pixel& p, mpl::true_) {\n    return get_color(p,alpha_t());\n}\ntemplate <typename Pixel>\ntypename channel_type<Pixel>::type alpha_or_max_impl(const Pixel&  , mpl::false_) {\n    return channel_traits<typename channel_type<Pixel>::type>::max_value();\n}\n} // namespace detail\n\n// Returns max_value if the pixel has no alpha channel. Otherwise returns the alpha.\ntemplate <typename Pixel>\ntypename channel_type<Pixel>::type alpha_or_max(const Pixel& p) {\n    return detail::alpha_or_max_impl(p, mpl::contains<typename color_space_type<Pixel>::type,alpha_t>());\n}\n\n\n/// \\ingroup ColorConvert\n/// \\brief Converting any pixel type to RGBA. Note: Supports homogeneous pixels only.\ntemplate <typename C1>\nstruct default_color_converter_impl<C1,rgba_t> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        using T2 = typename channel_type<P2>::type;\n        pixel<T2,rgb_layout_t> tmp;\n        default_color_converter_impl<C1,rgb_t>()(src,tmp);\n        get_color(dst,red_t())  =get_color(tmp,red_t());\n        get_color(dst,green_t())=get_color(tmp,green_t());\n        get_color(dst,blue_t()) =get_color(tmp,blue_t());\n        get_color(dst,alpha_t())=channel_convert<T2>(alpha_or_max(src));\n    }\n};\n\n/// \\ingroup ColorConvert\n///  \\brief Converting RGBA to any pixel type. Note: Supports homogeneous pixels only.\n///\n/// Done by multiplying the alpha to get to RGB, then converting the RGB to the target pixel type\n/// Note: This may be slower if the compiler doesn't optimize out constructing/destructing a temporary RGB pixel.\n///       Consider rewriting if performance is an issue\ntemplate <typename C2>\nstruct default_color_converter_impl<rgba_t,C2> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        using T1 = typename channel_type<P1>::type;\n        default_color_converter_impl<rgb_t,C2>()(\n            pixel<T1,rgb_layout_t>(channel_multiply(get_color(src,red_t()),  get_color(src,alpha_t())),\n                                   channel_multiply(get_color(src,green_t()),get_color(src,alpha_t())),\n                                   channel_multiply(get_color(src,blue_t()), get_color(src,alpha_t())))\n            ,dst);\n    }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief Unfortunately RGBA to RGBA must be explicitly provided - otherwise we get ambiguous specialization error.\ntemplate <>\nstruct default_color_converter_impl<rgba_t,rgba_t> {\n    template <typename P1, typename P2>\n    void operator()(const P1& src, P2& dst) const {\n        static_for_each(src,dst,default_channel_converter());\n    }\n};\n\n/// @defgroup ColorConvert Color Space Converion\n/// \\ingroup ColorSpaces\n/// \\brief Support for conversion between pixels of different color spaces and channel depths\n\n/// \\ingroup PixelAlgorithm ColorConvert\n/// \\brief class for color-converting one pixel to another\nstruct default_color_converter {\n    template <typename SrcP, typename DstP>\n    void operator()(const SrcP& src,DstP& dst) const {\n        using SrcColorSpace = typename color_space_type<SrcP>::type;\n        using DstColorSpace = typename color_space_type<DstP>::type;\n        default_color_converter_impl<SrcColorSpace,DstColorSpace>()(src,dst);\n    }\n};\n\n/// \\ingroup PixelAlgorithm\n/// \\brief helper function for converting one pixel to another using GIL default color-converters\n///     where ScrP models HomogeneousPixelConcept\n///           DstP models HomogeneousPixelValueConcept\ntemplate <typename SrcP, typename DstP>\ninline void color_convert(const SrcP& src, DstP& dst) {\n    default_color_converter()(src,dst);\n}\n\n} }  // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "815bc48ecdc4cad410bfba0f1f8eed093fbdeee6", "size": 12824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/gil/color_convert.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/gil/color_convert.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/gil/color_convert.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": 42.3234323432, "max_line_length": 147, "alphanum_fraction": 0.6460542732, "num_tokens": 3113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16667350631478992}}
{"text": "#ifndef OSRM_ENGINE_ROUTING_BASE_MLD_HPP\n#define OSRM_ENGINE_ROUTING_BASE_MLD_HPP\n\n#include \"engine/algorithm.hpp\"\n#include \"engine/datafacade.hpp\"\n#include \"engine/routing_algorithms/routing_base.hpp\"\n#include \"engine/search_engine_data.hpp\"\n\n#include \"util/typedefs.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <algorithm>\n#include <iterator>\n#include <limits>\n#include <tuple>\n#include <vector>\n\nnamespace osrm\n{\nnamespace engine\n{\nnamespace routing_algorithms\n{\nnamespace mld\n{\n\nnamespace\n{\n// Unrestricted search (Args is const PhantomNodes &):\n//   * use partition.GetQueryLevel to find the node query level based on source and target phantoms\n//   * allow to traverse all cells\ntemplate <typename MultiLevelPartition>\ninline LevelID getNodeQueryLevel(const MultiLevelPartition &partition,\n                                 NodeID node,\n                                 const PhantomNodes &phantom_nodes)\n{\n    auto level = [&partition, node](const SegmentID &source, const SegmentID &target) {\n        if (source.enabled && target.enabled)\n            return partition.GetQueryLevel(source.id, target.id, node);\n        return INVALID_LEVEL_ID;\n    };\n    return std::min(std::min(level(phantom_nodes.source_phantom.forward_segment_id,\n                                   phantom_nodes.target_phantom.forward_segment_id),\n                             level(phantom_nodes.source_phantom.forward_segment_id,\n                                   phantom_nodes.target_phantom.reverse_segment_id)),\n                    std::min(level(phantom_nodes.source_phantom.reverse_segment_id,\n                                   phantom_nodes.target_phantom.forward_segment_id),\n                             level(phantom_nodes.source_phantom.reverse_segment_id,\n                                   phantom_nodes.target_phantom.reverse_segment_id)));\n}\n\ninline bool checkParentCellRestriction(CellID, const PhantomNodes &) { return true; }\n\n// Restricted search (Args is LevelID, CellID):\n//   * use the fixed level for queries\n//   * check if the node cell is the same as the specified parent onr\ntemplate <typename MultiLevelPartition>\ninline LevelID getNodeQueryLevel(const MultiLevelPartition &, NodeID, LevelID level, CellID)\n{\n    return level;\n}\n\ninline bool checkParentCellRestriction(CellID cell, LevelID, CellID parent)\n{\n    return cell == parent;\n}\n}\n\n// Heaps only record for each node its predecessor (\"parent\") on the shortest path.\n// For re-constructing the actual path we need to trace back all parent \"pointers\".\n// In contrast to the CH code MLD needs to know the edges (with clique arc property).\n\nusing PackedEdge = std::tuple</*from*/ NodeID, /*to*/ NodeID, /*from_clique_arc*/ bool>;\nusing PackedPath = std::vector<PackedEdge>;\n\ntemplate <bool DIRECTION, typename OutIter>\ninline void retrievePackedPathFromSingleHeap(const SearchEngineData<Algorithm>::QueryHeap &heap,\n                                             const NodeID middle,\n                                             OutIter out)\n{\n    NodeID current = middle;\n    NodeID parent = heap.GetData(current).parent;\n\n    while (current != parent)\n    {\n        const auto &data = heap.GetData(current);\n\n        if (DIRECTION == FORWARD_DIRECTION)\n        {\n            *out = std::make_tuple(parent, current, data.from_clique_arc);\n            ++out;\n        }\n        else if (DIRECTION == REVERSE_DIRECTION)\n        {\n            *out = std::make_tuple(current, parent, data.from_clique_arc);\n            ++out;\n        }\n\n        current = parent;\n        parent = heap.GetData(parent).parent;\n    }\n}\n\ntemplate <bool DIRECTION>\ninline PackedPath\nretrievePackedPathFromSingleHeap(const SearchEngineData<Algorithm>::QueryHeap &heap,\n                                 const NodeID middle)\n{\n    PackedPath packed_path;\n    retrievePackedPathFromSingleHeap<DIRECTION>(heap, middle, std::back_inserter(packed_path));\n    return packed_path;\n}\n\n// Trace path from middle to start in the forward search space (in reverse)\n// and from middle to end in the reverse search space. Middle connects paths.\n\ninline PackedPath\nretrievePackedPathFromHeap(const SearchEngineData<Algorithm>::QueryHeap &forward_heap,\n                           const SearchEngineData<Algorithm>::QueryHeap &reverse_heap,\n                           const NodeID middle)\n{\n    // Retrieve start -> middle. Is in reverse order since tracing back starts from middle.\n    auto packed_path = retrievePackedPathFromSingleHeap<FORWARD_DIRECTION>(forward_heap, middle);\n    std::reverse(begin(packed_path), end(packed_path));\n\n    // Retrieve middle -> end. Is already in correct order, tracing starts from middle.\n    auto into = std::back_inserter(packed_path);\n    retrievePackedPathFromSingleHeap<REVERSE_DIRECTION>(reverse_heap, middle, into);\n\n    return packed_path;\n}\n\ntemplate <bool DIRECTION, typename Algorithm, typename... Args>\nvoid relaxOutgoingEdges(const DataFacade<Algorithm> &facade,\n                        typename SearchEngineData<Algorithm>::QueryHeap &forward_heap,\n                        const NodeID node,\n                        const EdgeWeight weight,\n                        Args... args)\n{\n    const auto &partition = facade.GetMultiLevelPartition();\n    const auto &cells = facade.GetCellStorage();\n    const auto &metric = facade.GetCellMetric();\n\n    const auto level = getNodeQueryLevel(partition, node, args...);\n\n    if (level >= 1 && !forward_heap.GetData(node).from_clique_arc)\n    {\n        if (DIRECTION == FORWARD_DIRECTION)\n        {\n            // Shortcuts in forward direction\n            const auto &cell = cells.GetCell(metric, level, partition.GetCell(level, node));\n            auto destination = cell.GetDestinationNodes().begin();\n            for (auto shortcut_weight : cell.GetOutWeight(node))\n            {\n                BOOST_ASSERT(destination != cell.GetDestinationNodes().end());\n                const NodeID to = *destination;\n\n                if (shortcut_weight != INVALID_EDGE_WEIGHT && node != to)\n                {\n                    const EdgeWeight to_weight = weight + shortcut_weight;\n                    BOOST_ASSERT(to_weight >= weight);\n                    if (!forward_heap.WasInserted(to))\n                    {\n                        forward_heap.Insert(to, to_weight, {node, true});\n                    }\n                    else if (to_weight < forward_heap.GetKey(to))\n                    {\n                        forward_heap.GetData(to) = {node, true};\n                        forward_heap.DecreaseKey(to, to_weight);\n                    }\n                }\n                ++destination;\n            }\n        }\n        else\n        {\n            // Shortcuts in backward direction\n            const auto &cell = cells.GetCell(metric, level, partition.GetCell(level, node));\n            auto source = cell.GetSourceNodes().begin();\n            for (auto shortcut_weight : cell.GetInWeight(node))\n            {\n                BOOST_ASSERT(source != cell.GetSourceNodes().end());\n                const NodeID to = *source;\n\n                if (shortcut_weight != INVALID_EDGE_WEIGHT && node != to)\n                {\n                    const EdgeWeight to_weight = weight + shortcut_weight;\n                    BOOST_ASSERT(to_weight >= weight);\n                    if (!forward_heap.WasInserted(to))\n                    {\n                        forward_heap.Insert(to, to_weight, {node, true});\n                    }\n                    else if (to_weight < forward_heap.GetKey(to))\n                    {\n                        forward_heap.GetData(to) = {node, true};\n                        forward_heap.DecreaseKey(to, to_weight);\n                    }\n                }\n                ++source;\n            }\n        }\n    }\n\n    // Boundary edges\n    for (const auto edge : facade.GetBorderEdgeRange(level, node))\n    {\n        const auto &edge_data = facade.GetEdgeData(edge);\n        if (DIRECTION == FORWARD_DIRECTION ? edge_data.forward : edge_data.backward)\n        {\n            const NodeID to = facade.GetTarget(edge);\n\n            if (!facade.ExcludeNode(to) &&\n                checkParentCellRestriction(partition.GetCell(level + 1, to), args...))\n            {\n                BOOST_ASSERT_MSG(edge_data.weight > 0, \"edge_weight invalid\");\n                const EdgeWeight to_weight = weight + edge_data.weight;\n\n                if (!forward_heap.WasInserted(to))\n                {\n                    forward_heap.Insert(to, to_weight, {node, false});\n                }\n                else if (to_weight < forward_heap.GetKey(to))\n                {\n                    forward_heap.GetData(to) = {node, false};\n                    forward_heap.DecreaseKey(to, to_weight);\n                }\n            }\n        }\n    }\n}\n\ntemplate <bool DIRECTION, typename Algorithm, typename... Args>\nvoid routingStep(const DataFacade<Algorithm> &facade,\n                 typename SearchEngineData<Algorithm>::QueryHeap &forward_heap,\n                 typename SearchEngineData<Algorithm>::QueryHeap &reverse_heap,\n                 NodeID &middle_node,\n                 EdgeWeight &path_upper_bound,\n                 const bool force_loop_forward,\n                 const bool force_loop_reverse,\n                 Args... args)\n{\n    const auto node = forward_heap.DeleteMin();\n    const auto weight = forward_heap.GetKey(node);\n\n    BOOST_ASSERT(!facade.ExcludeNode(node));\n\n    // Upper bound for the path source -> target with\n    // weight(source -> node) = weight weight(to -> target) \u2264 reverse_weight\n    // is weight + reverse_weight\n    // More tighter upper bound requires additional condition reverse_heap.WasRemoved(to)\n    // with weight(to -> target) = reverse_weight and all weights \u2265 0\n    if (reverse_heap.WasInserted(node))\n    {\n        auto reverse_weight = reverse_heap.GetKey(node);\n        auto path_weight = weight + reverse_weight;\n\n        // MLD uses loops forcing only to prune single node paths in forward and/or\n        // backward direction (there is no need to force loops in MLD but in CH)\n        if (!(force_loop_forward && forward_heap.GetData(node).parent == node) &&\n            !(force_loop_reverse && reverse_heap.GetData(node).parent == node) &&\n            (path_weight >= 0) && (path_weight < path_upper_bound))\n        {\n            middle_node = node;\n            path_upper_bound = path_weight;\n        }\n    }\n\n    // Relax outgoing edges from node\n    relaxOutgoingEdges<DIRECTION>(facade, forward_heap, node, weight, args...);\n}\n\n// With (s, middle, t) we trace back the paths middle -> s and middle -> t.\n// This gives us a packed path (node ids) from the base graph around s and t,\n// and overlay node ids otherwise. We then have to unpack the overlay clique\n// edges by recursively descending unpacking the path down to the base graph.\n\nusing UnpackedNodes = std::vector<NodeID>;\nusing UnpackedEdges = std::vector<EdgeID>;\nusing UnpackedPath = std::tuple<EdgeWeight, UnpackedNodes, UnpackedEdges>;\n\ntemplate <typename Algorithm, typename... Args>\nUnpackedPath search(SearchEngineData<Algorithm> &engine_working_data,\n                    const DataFacade<Algorithm> &facade,\n                    typename SearchEngineData<Algorithm>::QueryHeap &forward_heap,\n                    typename SearchEngineData<Algorithm>::QueryHeap &reverse_heap,\n                    const bool force_loop_forward,\n                    const bool force_loop_reverse,\n                    EdgeWeight weight_upper_bound,\n                    Args... args)\n{\n    if (forward_heap.Empty() || reverse_heap.Empty())\n    {\n        return std::make_tuple(INVALID_EDGE_WEIGHT, std::vector<NodeID>(), std::vector<EdgeID>());\n    }\n\n    const auto &partition = facade.GetMultiLevelPartition();\n\n    BOOST_ASSERT(!forward_heap.Empty() && forward_heap.MinKey() < INVALID_EDGE_WEIGHT);\n    BOOST_ASSERT(!reverse_heap.Empty() && reverse_heap.MinKey() < INVALID_EDGE_WEIGHT);\n\n    // run two-Target Dijkstra routing step.\n    NodeID middle = SPECIAL_NODEID;\n    EdgeWeight weight = weight_upper_bound;\n    EdgeWeight forward_heap_min = forward_heap.MinKey();\n    EdgeWeight reverse_heap_min = reverse_heap.MinKey();\n    while (forward_heap.Size() + reverse_heap.Size() > 0 &&\n           forward_heap_min + reverse_heap_min < weight)\n    {\n        if (!forward_heap.Empty())\n        {\n            routingStep<FORWARD_DIRECTION>(facade,\n                                           forward_heap,\n                                           reverse_heap,\n                                           middle,\n                                           weight,\n                                           force_loop_forward,\n                                           force_loop_reverse,\n                                           args...);\n            if (!forward_heap.Empty())\n                forward_heap_min = forward_heap.MinKey();\n        }\n        if (!reverse_heap.Empty())\n        {\n            routingStep<REVERSE_DIRECTION>(facade,\n                                           reverse_heap,\n                                           forward_heap,\n                                           middle,\n                                           weight,\n                                           force_loop_reverse,\n                                           force_loop_forward,\n                                           args...);\n            if (!reverse_heap.Empty())\n                reverse_heap_min = reverse_heap.MinKey();\n        }\n    };\n\n    // No path found for both target nodes?\n    if (weight >= weight_upper_bound || SPECIAL_NODEID == middle)\n    {\n        return std::make_tuple(INVALID_EDGE_WEIGHT, std::vector<NodeID>(), std::vector<EdgeID>());\n    }\n\n    // Get packed path as edges {from node ID, to node ID, from_clique_arc}\n    auto packed_path = retrievePackedPathFromHeap(forward_heap, reverse_heap, middle);\n\n    // Beware the edge case when start, middle, end are all the same.\n    // In this case we return a single node, no edges. We also don't unpack.\n    const NodeID source_node = !packed_path.empty() ? std::get<0>(packed_path.front()) : middle;\n\n    // Unpack path\n    std::vector<NodeID> unpacked_nodes;\n    std::vector<EdgeID> unpacked_edges;\n    unpacked_nodes.reserve(packed_path.size());\n    unpacked_edges.reserve(packed_path.size());\n\n    unpacked_nodes.push_back(source_node);\n\n    for (auto const &packed_edge : packed_path)\n    {\n        NodeID source, target;\n        bool overlay_edge;\n        std::tie(source, target, overlay_edge) = packed_edge;\n        if (!overlay_edge)\n        { // a base graph edge\n            unpacked_nodes.push_back(target);\n            unpacked_edges.push_back(facade.FindEdge(source, target));\n        }\n        else\n        { // an overlay graph edge\n            LevelID level = getNodeQueryLevel(partition, source, args...);\n            CellID parent_cell_id = partition.GetCell(level, source);\n            BOOST_ASSERT(parent_cell_id == partition.GetCell(level, target));\n\n            LevelID sublevel = level - 1;\n\n            // Here heaps can be reused, let's go deeper!\n            forward_heap.Clear();\n            reverse_heap.Clear();\n            forward_heap.Insert(source, 0, {source});\n            reverse_heap.Insert(target, 0, {target});\n\n            // TODO: when structured bindings will be allowed change to\n            // auto [subpath_weight, subpath_source, subpath_target, subpath] = ...\n            EdgeWeight subpath_weight;\n            std::vector<NodeID> subpath_nodes;\n            std::vector<EdgeID> subpath_edges;\n            std::tie(subpath_weight, subpath_nodes, subpath_edges) = search(engine_working_data,\n                                                                            facade,\n                                                                            forward_heap,\n                                                                            reverse_heap,\n                                                                            force_loop_forward,\n                                                                            force_loop_reverse,\n                                                                            INVALID_EDGE_WEIGHT,\n                                                                            sublevel,\n                                                                            parent_cell_id);\n            BOOST_ASSERT(!subpath_edges.empty());\n            BOOST_ASSERT(subpath_nodes.size() > 1);\n            BOOST_ASSERT(subpath_nodes.front() == source);\n            BOOST_ASSERT(subpath_nodes.back() == target);\n            unpacked_nodes.insert(\n                unpacked_nodes.end(), std::next(subpath_nodes.begin()), subpath_nodes.end());\n            unpacked_edges.insert(unpacked_edges.end(), subpath_edges.begin(), subpath_edges.end());\n        }\n    }\n\n    return std::make_tuple(weight, std::move(unpacked_nodes), std::move(unpacked_edges));\n}\n\n// Alias to be compatible with the CH-based search\ntemplate <typename Algorithm>\ninline void search(SearchEngineData<Algorithm> &engine_working_data,\n                   const DataFacade<Algorithm> &facade,\n                   typename SearchEngineData<Algorithm>::QueryHeap &forward_heap,\n                   typename SearchEngineData<Algorithm>::QueryHeap &reverse_heap,\n                   EdgeWeight &weight,\n                   std::vector<NodeID> &unpacked_nodes,\n                   const bool force_loop_forward,\n                   const bool force_loop_reverse,\n                   const PhantomNodes &phantom_nodes,\n                   const EdgeWeight weight_upper_bound = INVALID_EDGE_WEIGHT)\n{\n    // TODO: change search calling interface to use unpacked_edges result\n    std::tie(weight, unpacked_nodes, std::ignore) = search(engine_working_data,\n                                                           facade,\n                                                           forward_heap,\n                                                           reverse_heap,\n                                                           force_loop_forward,\n                                                           force_loop_reverse,\n                                                           weight_upper_bound,\n                                                           phantom_nodes);\n}\n\n// TODO: refactor CH-related stub to use unpacked_edges\ntemplate <typename RandomIter, typename FacadeT>\nvoid unpackPath(const FacadeT &facade,\n                RandomIter packed_path_begin,\n                RandomIter packed_path_end,\n                const PhantomNodes &phantom_nodes,\n                std::vector<PathData> &unpacked_path)\n{\n    const auto nodes_number = std::distance(packed_path_begin, packed_path_end);\n    BOOST_ASSERT(nodes_number > 0);\n\n    std::vector<NodeID> unpacked_nodes;\n    std::vector<EdgeID> unpacked_edges;\n    unpacked_nodes.reserve(nodes_number);\n    unpacked_edges.reserve(nodes_number);\n\n    unpacked_nodes.push_back(*packed_path_begin);\n    if (nodes_number > 1)\n    {\n        util::for_each_pair(\n            packed_path_begin,\n            packed_path_end,\n            [&facade, &unpacked_nodes, &unpacked_edges](const auto from, const auto to) {\n                unpacked_nodes.push_back(to);\n                unpacked_edges.push_back(facade.FindEdge(from, to));\n            });\n    }\n\n    annotatePath(facade, phantom_nodes, unpacked_nodes, unpacked_edges, unpacked_path);\n}\n\ntemplate <typename Algorithm>\ndouble getNetworkDistance(SearchEngineData<Algorithm> &engine_working_data,\n                          const DataFacade<Algorithm> &facade,\n                          typename SearchEngineData<Algorithm>::QueryHeap &forward_heap,\n                          typename SearchEngineData<Algorithm>::QueryHeap &reverse_heap,\n                          const PhantomNode &source_phantom,\n                          const PhantomNode &target_phantom,\n                          EdgeWeight weight_upper_bound = INVALID_EDGE_WEIGHT)\n{\n    forward_heap.Clear();\n    reverse_heap.Clear();\n\n    const PhantomNodes phantom_nodes{source_phantom, target_phantom};\n    insertNodesInHeaps(forward_heap, reverse_heap, phantom_nodes);\n\n    EdgeWeight weight = INVALID_EDGE_WEIGHT;\n    std::vector<NodeID> unpacked_nodes;\n    std::vector<EdgeID> unpacked_edges;\n    std::tie(weight, unpacked_nodes, unpacked_edges) = search(engine_working_data,\n                                                              facade,\n                                                              forward_heap,\n                                                              reverse_heap,\n                                                              DO_NOT_FORCE_LOOPS,\n                                                              DO_NOT_FORCE_LOOPS,\n                                                              weight_upper_bound,\n                                                              phantom_nodes);\n\n    if (weight == INVALID_EDGE_WEIGHT)\n    {\n        return std::numeric_limits<double>::max();\n    }\n\n    std::vector<PathData> unpacked_path;\n\n    annotatePath(facade, phantom_nodes, unpacked_nodes, unpacked_edges, unpacked_path);\n\n    return getPathDistance(facade, unpacked_path, source_phantom, target_phantom);\n}\n\n} // namespace mld\n} // namespace routing_algorithms\n} // namespace engine\n} // namespace osrm\n\n#endif // OSRM_ENGINE_ROUTING_BASE_MLD_HPP\n", "meta": {"hexsha": "cd4f0846a6afb8d2a9f69fc0a3f27e02cfdfc58b", "size": 21378, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/engine/routing_algorithms/routing_base_mld.hpp", "max_stars_repo_name": "antoinegiret/osrm-backend-1", "max_stars_repo_head_hexsha": "c4eff6cd656b49e3cb5fc841e868031e12a97465", "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/engine/routing_algorithms/routing_base_mld.hpp", "max_issues_repo_name": "antoinegiret/osrm-backend-1", "max_issues_repo_head_hexsha": "c4eff6cd656b49e3cb5fc841e868031e12a97465", "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/engine/routing_algorithms/routing_base_mld.hpp", "max_forks_repo_name": "antoinegiret/osrm-backend-1", "max_forks_repo_head_hexsha": "c4eff6cd656b49e3cb5fc841e868031e12a97465", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-23T22:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T22:49:07.000Z", "avg_line_length": 41.9176470588, "max_line_length": 100, "alphanum_fraction": 0.5751239592, "num_tokens": 4009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.16667350294113445}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <list>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n#include <boost/algorithm/clamp.hpp>\n#include <random>\n#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"unsupported/Eigen/CXX11/src/Tensor/TensorDeviceCuda.h\"\n//#include \"unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\" \n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include \"tensorflow/core/util/work_sharder.h\"\n#include \"bboxes.h\"\n#include \"matcher.h\"\n#include \"wtoolkit.h\"\n#include \"wtoolkit_cuda.h\"\n#include <future>\n\nusing namespace tensorflow;\nusing namespace std;\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;\nREGISTER_OP(\"TopPool\")\n    .Attr(\"T: {float,double}\")\n    .Input(\"tensor: T\")\n\t.Output(\"output_tensor:T\")\n\t.SetShapeFn(shape_inference::UnchangedShape);\nREGISTER_OP(\"TopPoolGrad\")\n    .Attr(\"T: {float,double}\")\n    .Input(\"tensor: T\")\n    .Input(\"fw_output: T\")\n    .Input(\"backprop: T\")\n\t.Output(\"output_tensor:T\")\n\t.SetShapeFn(shape_inference::UnchangedShape);\n\ntemplate <typename Device, typename T>\nclass TopPoolOp: public OpKernel {\n};\ntemplate <typename T>\nclass TopPoolOp<CPUDevice,T>: public OpKernel {\n\tpublic:\n\t\texplicit TopPoolOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"TopPool\");\n\t\t\tconst Tensor &_tensor = context->input(0);\n\n\t\t\tOP_REQUIRES(context, _tensor.dims() == 4, errors::InvalidArgument(\"tensor must be 4-dimensional\"));\n\n\t\t\tauto         tensor        = _tensor.template tensor<T,4>();\n\t\t\tTensorShape  outshape      = _tensor.shape();\n\t\t\tTensor      *output_tensor = nullptr;\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape, &output_tensor));\n\n\t\t\tauto           output      = output_tensor->template tensor<T,4>();\n\t\t\tconstexpr auto kProcessDim = 1;\n\t\t\tconst auto     process_nr  = _tensor.dim_size(kProcessDim);\n\n            output.chip(process_nr-1,kProcessDim) = tensor.chip(process_nr-1,kProcessDim);\n\n            for(auto i=process_nr-2; i>=0; --i){\n                output.chip(i,kProcessDim) = output.chip(i+1,kProcessDim).cwiseMax(tensor.chip(i,kProcessDim));\n            }\n        }\n};\ntemplate <typename Device, typename T>\nclass TopPoolGradOp: public OpKernel {\n};\ntemplate <typename T>\nclass TopPoolGradOp<CPUDevice,T>: public OpKernel {\n\tpublic:\n\t\texplicit TopPoolGradOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"TopPoolGrad\");\n\t\t\tconst Tensor &_tensor    = context->input(0);\n\t\t\tconst Tensor &_fw_output = context->input(1);\n\t\t\tconst Tensor &_backprop  = context->input(2);\n\n\t\t\tOP_REQUIRES(context, _tensor.dims() == 4, errors::InvalidArgument(\"tensor must be 4-dimensional\"));\n\t\t\tOP_REQUIRES(context, _fw_output.dims() == 4, errors::InvalidArgument(\"forward output must be 4-dimensional\"));\n\t\t\tOP_REQUIRES(context, _backprop.dims() == 4, errors::InvalidArgument(\"backprop must be 4-dimensional\"));\n\n\t\t\tauto         tensor        = _tensor.template tensor<T,4>();\n\t\t\tauto         fw_output     = _fw_output.template tensor<T,4>();\n\t\t\tauto         backprop      = _backprop.template tensor<T,4>();\n\t\t\tTensorShape  outshape      = _tensor.shape();\n\t\t\tTensor      *output_tensor = nullptr;\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape, &output_tensor));\n\n\t\t\tauto           output      = output_tensor->template tensor<T,4>();\n\t\t\tconstexpr auto kProcessDim = 1;\n\t\t\tconst auto     process_nr  = _tensor.dim_size(kProcessDim);\n            Eigen::Tensor<int,3> index(_tensor.dim_size(0),_tensor.dim_size(2),_tensor.dim_size(3));\n\n            output.setZero();\n            output.chip(process_nr-1,kProcessDim) = backprop.chip(process_nr-1,kProcessDim);\n            index.setConstant(process_nr-1);\n\n            for(auto i=process_nr-2; i>=0; --i){\n                Eigen::Tensor<bool,3,Eigen::RowMajor> t = (fw_output.chip(i+1,kProcessDim) < tensor.chip(i,kProcessDim));\n                assign_grad(t,i,index,backprop,output);\n            }\n        }\n\n        template<typename IT,typename BPT,typename OT,typename ST>\n        void assign_grad(const ST& select,int cur_index,IT& index, const BPT& backprop,OT& output) {\n            auto idx = 0;\n            for(auto i=0; i<index.dimension(0); ++i) {\n                for(auto j=0; j<index.dimension(1); ++j) {\n                    for(auto k=0; k<index.dimension(2); ++k) {\n                        if(select(i,j,k)){\n                                idx = cur_index;\n                                index(i,j,k) = idx;\n                          } else {\n                                idx = index(i,j,k);\n                          }\n                        output(i,idx,j,k) += backprop(i,idx,j,k);\n                    }\n                }\n            }\n        }\n};\nREGISTER_KERNEL_BUILDER(Name(\"TopPool\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), TopPoolOp<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"TopPool\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), TopPoolOp<CPUDevice, double>);\nREGISTER_KERNEL_BUILDER(Name(\"TopPoolGrad\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), TopPoolGradOp<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"TopPoolGrad\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), TopPoolGradOp<CPUDevice, double>);\n", "meta": {"hexsha": "3b51e0650063512e9c0469ef6530afa56d95f0b9", "size": 5517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tfop/top_pool.cpp", "max_stars_repo_name": "vghost2008/wml", "max_stars_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-10T17:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T01:00:35.000Z", "max_issues_repo_path": "tfop/top_pool.cpp", "max_issues_repo_name": "vghost2008/wml", "max_issues_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T16:16:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T05:21:19.000Z", "max_forks_repo_path": "tfop/top_pool.cpp", "max_forks_repo_name": "vghost2008/wml", "max_forks_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-07T09:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T04:58:10.000Z", "avg_line_length": 39.1276595745, "max_line_length": 126, "alphanum_fraction": 0.6521660323, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1666735029411344}}
{"text": "#include \"v4r/registration/MultiSessionModelling.h\"\n#include <pcl/common/transforms.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <v4r/common/miscellaneous.h>\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include \"v4r/common/visibility_reasoning.h\"\n\ntemplate <class PointT>\nfloat v4r::Registration::MultiSessionModelling<PointT>::computeFSV(\n    const typename pcl::PointCloud<PointT>::ConstPtr& cloud, pcl::PointCloud<pcl::Normal>::ConstPtr& normals,\n    const std::vector<int>& indices, const Eigen::Matrix4f& pose,\n    const typename pcl::PointCloud<PointT>::ConstPtr& range_image) {\n  v4r::VisibilityReasoning<PointT> vr(Intrinsics::PrimeSense());\n  vr.setThresholdTSS(0.01f);\n\n  typename pcl::PointCloud<PointT>::Ptr model(new pcl::PointCloud<PointT>());\n  pcl::transformPointCloud(*cloud, indices, *model, pose);\n\n  pcl::PointCloud<pcl::Normal>::Ptr model_normals(new pcl::PointCloud<pcl::Normal>);\n  v4r::transformNormals(*normals, *model_normals, indices, pose);\n\n  // Eigen::Matrix4f identity = Eigen::Matrix4f::Identity();\n\n  float fsv = vr.computeFSVWithNormals(range_image, model, model_normals);\n\n  // the more points on the same surface the more reliable this is, so increase fsv if not many points\n  int ss = vr.getFSVUsedPoints();\n  float ratio = 1.f - ss / static_cast<float>(model->points.size());\n\n  // std::cout << model->points.size() << \" \" << indices.size() << \" fsv:\" << fsv << std::endl;\n\n  /*if(fsv > 0.1)\n  {*/\n  /*    ///debug\n      pcl::visualization::PCLVisualizer vis(\"correspondences\");\n      //int v1,v2;\n      //vis.createViewPort(0,0,0.5,1,v1);\n      //vis.createViewPort(0.5,0,1,1,v2);\n\n      pcl::visualization::PointCloudColorHandlerCustom<PointT> handler(model, 255, 0, 0);\n      vis.addPointCloud(range_image, \"cloud_2\");\n      vis.addPointCloud(model, handler, \"cloud_1\");\n\n      vis.spin();\n  */\n  /*}*/\n\n  return fsv * ratio;\n}\n\ntemplate <class PointT>\nvoid v4r::Registration::MultiSessionModelling<PointT>::computeCost(EdgeBetweenPartialModels& edge) {\n  // fsv computation\n  // take all views of edge_i with respective indices and compute FSV with respect to the views of j_\n  // do i need normals?\n\n  float fsv = 0.f;\n  int non_valid = 0;\n  int total = 0;\n  for (int ii = session_ranges_[edge.i_].first; ii <= session_ranges_[edge.i_].second; ii++) {\n    typename pcl::PointCloud<PointT>::ConstPtr cloud = clouds_[ii];\n    std::vector<int>& indices = getIndices(ii);\n    Eigen::Matrix4f pose = edge.transformation_.inverse() * getPose(ii);\n\n    for (int jj = session_ranges_[edge.j_].first; jj <= session_ranges_[edge.j_].second; jj++) {\n      Eigen::Matrix4f pose_to_jj = poses_[jj].inverse() * pose;\n      float fsv_loc = computeFSV(cloud, normals_[ii], indices, pose_to_jj, clouds_[jj]);\n      if (fsv_loc < 0) {\n        non_valid++;\n      } else {\n        fsv += fsv_loc;\n      }\n\n      total++;\n    }\n  }\n\n  if (non_valid == total) {\n    std::cout << \"No valid edge...\" << std::endl;\n    edge.cost_ = std::numeric_limits<float>::infinity();\n  } else {\n    edge.cost_ = fsv / (total - non_valid);\n  }\n}\n\ntemplate <class PointT>\nvoid v4r::Registration::MultiSessionModelling<PointT>::compute() {\n  for (size_t a = 0; a < reg_algos_.size(); a++) {\n    reg_algos_[a]->setMSM(this);\n    reg_algos_[a]->initialize(session_ranges_);\n  }\n\n  std::vector<std::vector<std::vector<EdgeBetweenPartialModels>>> edges;\n  edges.resize(session_ranges_.size());\n  for (size_t i = 0; i < session_ranges_.size(); i++) {\n    edges[i].resize(session_ranges_.size());\n  }\n\n  // for each session pair, call the class that registers two partial models and returns a set of poses\n  for (size_t i = 0; i < session_ranges_.size(); i++) {\n    std::pair<int, int> pair_i = session_ranges_[i];\n    for (size_t j = (i + 1); j < session_ranges_.size(); j++) {\n      std::pair<int, int> pair_j = session_ranges_[j];\n\n      for (size_t a = 0; a < reg_algos_.size(); a++) {\n        reg_algos_[a]->setSessions(pair_i, pair_j);\n        reg_algos_[a]->compute(i, j);\n\n        // poses transform the RF of pair_j to the RF of pair_i\n        std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> poses;\n        reg_algos_[a]->getPoses(poses);\n\n        std::cout << \"poses between \" << j << \" and \" << i << \" :\" << poses.size() << std::endl;\n\n        for (size_t p = 0; p < poses.size(); p++) {\n          EdgeBetweenPartialModels ebpm;\n          ebpm.transformation_ = poses[p];\n          ebpm.cost_ = -1;\n          ebpm.i_ = i;\n          ebpm.j_ = j;\n\n          edges[i][j].push_back(ebpm);\n        }\n      }\n    }\n  }\n\n  // for each edge in the graph, compute a score quantifying quality of alignment\n  // overlap? number of outliers? fsv average?\n\n  for (size_t i = 0; i < session_ranges_.size(); i++) {\n    for (size_t j = (i + 1); j < session_ranges_.size(); j++) {\n      if (edges[i][j].size() > 0) {\n        std::cout << \"Number of edges:\" << edges[i][j].size() << std::endl;\n        // iterate over the edges and compute cost_ (the higher, the worse)\n\n#pragma omp parallel for schedule(dynamic, 1) num_threads(4)\n        for (size_t k = 0; k < edges[i][j].size(); k++) {\n          computeCost(edges[i][j][k]);\n        }\n      }\n    }\n  }\n\n  // final alignment between partial models? MST\n  int final_alignment = 0;  // 0-MST, 1-something fancy?\n\n  switch (final_alignment) {\n    case 0: {\n      std::vector<typename pcl::PointCloud<PointT>::Ptr> partial_model_clouds(session_ranges_.size());\n\n      for (size_t i = 0; i < session_ranges_.size(); i++) {\n        partial_model_clouds[i].reset(new pcl::PointCloud<PointT>);\n\n        for (int t = session_ranges_[i].first; t <= session_ranges_[i].second; t++) {\n          typename pcl::PointCloud<PointT>::Ptr transformed(new pcl::PointCloud<PointT>);\n          pcl::copyPointCloud(*getCloud(static_cast<size_t>(t)), getIndices(static_cast<size_t>(t)), *transformed);\n          Eigen::Matrix4f pose_inv = getPose(static_cast<size_t>(t));\n          pcl::transformPointCloud(*transformed, *transformed, pose_inv);\n          *partial_model_clouds[i] += *transformed;\n        }\n      }\n\n      Graph G;\n      for (size_t i = 0; i < session_ranges_.size(); i++) {\n        boost::add_vertex((int)i, G);\n      }\n\n      for (size_t i = 0; i < session_ranges_.size(); i++) {\n        for (size_t j = (i + 1); j < session_ranges_.size(); j++) {\n          if (edges[i][j].size() > 0) {\n            float min_cost = std::numeric_limits<float>::infinity();\n            int min_k = -1;\n\n            for (size_t k = 0; k < edges[i][j].size(); k++) {\n              // std::cout << \"cost:\" << edges[i][j][k].cost_ << std::endl;\n              if (edges[i][j][k].cost_ < min_cost) {\n                min_cost = edges[i][j][k].cost_;\n                min_k = static_cast<int>(k);\n              }\n            }\n\n            std::cout << j << \" => \" << i << \" \" << min_cost << \" \" << min_k << std::endl;\n            // add edge to graph... transformation maps from j to i (otherwise invert)\n            myEdge e;\n            e.edge_weight = edges[i][j][min_k].cost_;\n            e.transformation = edges[i][j][min_k].transformation_;\n            e.source_id = j;\n            e.target_id = i;\n            boost::add_edge((int)j, (int)i, e, G);\n\n            /*std::stringstream title_str;\n            title_str << \"best pw from \" << j << \" \" << i;\n            pcl::visualization::PCLVisualizer vis(title_str.str().c_str());\n            vis.addCoordinateSystem(0.1);\n            for(size_t k=0; k < edges[i][j].size(); k++)\n            {\n                if(edges[i][j][k].cost_ * 0.25 <= min_cost)\n                {\n                    std::cout << \"cost:\" << edges[i][j][k].cost_ << std::endl;\n\n                    {\n                        pcl::visualization::PointCloudColorHandlerRGBField<PointT> handler(partial_model_clouds[i]);\n                        vis.addPointCloud(partial_model_clouds[i], handler, \"cloud_i\");\n                    }\n\n                    typename pcl::PointCloud<PointT>::Ptr transformed(new pcl::PointCloud<PointT>);\n                    pcl::transformPointCloud(*partial_model_clouds[j], *transformed, edges[i][j][k].transformation_);\n\n                    {\n                        pcl::visualization::PointCloudColorHandlerRGBField<PointT> handler(transformed);\n                        vis.addPointCloud(transformed, handler, \"cloud_j\");\n                    }\n\n                    vis.spin();\n                    vis.removeAllPointClouds();\n                }\n            }*/\n          }\n        }\n      }\n\n      boost::property_map<Graph, boost::edge_weight_t>::type weightmap = boost::get(boost::edge_weight, G);\n      Graph MST;\n      for (size_t i = 0; i < session_ranges_.size(); i++)\n        boost::add_vertex((int)i, MST);\n\n      // there is a bug in boost 1.54 that causes negative weights error (even though weights are positive)\n      /*std::vector < boost::graph_traits<Graph>::vertex_descriptor > p (boost::num_vertices (G));\n      boost::prim_minimum_spanning_tree (G, &p[0]);\n\n      for (std::size_t i = 0; i != p.size (); ++i)\n      {\n          if (p[i] != i)\n              std::cout << \"parent[\" << i << \"] = \" << p[i] << std::endl;\n          else\n              std::cout << \"parent[\" << i << \"] = no parent\" << std::endl;\n      }\n\n\n      typedef typename Graph::edge_iterator EdgeIterator;\n      std::pair<EdgeIterator, EdgeIterator> edges = boost::edges(G);\n      EdgeIterator edge;\n\n      for (edge = edges.first; edge != edges.second; edge++)\n      {\n          typename boost::graph_traits<Graph>::vertex_descriptor s, t;\n          s = boost::source(*edge, G);\n          t = boost::target(*edge, G);\n\n          if(p[s] == t || p[t] == s)\n          {\n              //edge in prim\n              boost::add_edge ((int)s, (int)t, weightmap[*edge], MST);\n          }\n      }*/\n\n      std::vector<Edge> spanning_tree;\n      boost::kruskal_minimum_spanning_tree(G, std::back_inserter(spanning_tree));\n\n      std::cout << \"Print the edges in the MST:\" << std::endl;\n      for (std::vector<Edge>::iterator ei = spanning_tree.begin(); ei != spanning_tree.end(); ++ei) {\n        std::cout << source(*ei, G) << \" \" << target(*ei, G) << std::endl;\n        boost::add_edge(source(*ei, G), target(*ei, G), weightmap[*ei], MST);\n      }\n\n      std::cout << boost::num_edges(MST) << \" \" << boost::num_vertices(MST) << std::endl;\n      output_session_poses_.resize(boost::num_vertices(MST));\n\n      computeAbsolutePoses(MST, output_session_poses_);\n\n      // finally, define output_cloud_poses_\n      output_cloud_poses_.resize(clouds_.size());\n\n      for (size_t i = 0; i < output_session_poses_.size(); i++) {\n        std::cout << output_session_poses_[i] << std::endl;\n        for (int j = session_ranges_[i].first; j <= session_ranges_[i].second; j++) {\n          Eigen::Matrix4f trans = output_session_poses_[i] * poses_[j];\n          output_cloud_poses_[j] = trans;\n        }\n      }\n\n      break;\n    }\n\n    default: { break; }\n  }\n}\n\ntemplate class V4R_EXPORTS v4r::Registration::MultiSessionModelling<pcl::PointXYZRGB>;\n", "meta": {"hexsha": "1b75ebb59008a877f24cc3a2819d3cab811a938f", "size": 11184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/registration/src/MultiSessionModelling.cpp", "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/registration/src/MultiSessionModelling.cpp", "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/registration/src/MultiSessionModelling.cpp", "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": 38.0408163265, "max_line_length": 117, "alphanum_fraction": 0.5914699571, "num_tokens": 2986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.16667349816781182}}
{"text": "#pragma once\n\n#include \"keyboard_optimizer/layout.hpp\"\n#include \"keyboard_optimizer/utils.hpp\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/property_map/function_property_map.hpp>\n#include <iostream>\n#include <random>\n#include <stdexcept>\n\nnamespace KeyboardOptimizer {\n\nclass InvalidConstraints final : public std::invalid_argument {\npublic:\n  std::unordered_set<Sym> syms;\n  std::unordered_set<Key> keys;\n  std::unordered_map<Sym, Key> matchedSyms;\n  Layer layer;\n  constexpr static auto msg =\n      \"Found set of syms which are matched to a smaller set of keys. \\n Note: \"\n      \"some keys could be unavailable due to sym bonds.\";\n  InvalidConstraints(std::unordered_set<Sym> &&syms,\n                     std::unordered_set<Key> &&keys,\n                     std::unordered_map<Sym, Key> &&matchedSyms, Layer layer)\n      : syms(std::move(syms)), keys(std::move(keys)),\n        matchedSyms(std::move(matchedSyms)),\n        layer(layer), std::invalid_argument(msg) {\n    assert(this->syms.size() > this->keys.size());\n  }\n};\n\nclass UnsatisfiedConstraints : public std::invalid_argument {\npublic:\n  Layout layout;\n\nprotected:\n  UnsatisfiedConstraints(Layout &&layout)\n      : layout(std::move(layout)), std::invalid_argument(\"\"){};\n};\nclass MissingEdge final : public UnsatisfiedConstraints {\npublic:\n  Sym sym;\n  Key key;\n  MissingEdge(Layout &&layout, Sym sym, Key key)\n      : UnsatisfiedConstraints(std::move(layout)), sym(sym), key(key) {}\n  char const *what() const {\n    return \"Found sym-key pair which is restricted by provided constraints.\";\n  }\n};\nclass MismatchedLayer final : public UnsatisfiedConstraints {\npublic:\n  Sym sym;\n  Layer actualLayer;\n  Layer constraintsLayer;\n  MismatchedLayer(Layout &&layout, Sym sym, Layer actualLayer,\n                  Layer constraintsLayer)\n      : UnsatisfiedConstraints(std::move(layout)), sym(sym),\n        actualLayer(actualLayer), constraintsLayer(constraintsLayer) {}\n  char const *what() const {\n    return \"Found sym which is located on different layer than in provided \"\n           \"constraints.\";\n  }\n};\nclass UnsatisfiedSymBond final : public UnsatisfiedConstraints {\npublic:\n  Sym sym1;\n  Key key1;\n  Sym sym2;\n  Key key2;\n  UnsatisfiedSymBond(Layout &&layout, Sym sym1, Key key1, Sym sym2, Key key2)\n      : UnsatisfiedConstraints(std::move(layout)), sym1(sym1), key1(key1),\n        sym2(sym2), key2(key2) {}\n  char const *what() const {\n    return \"Found syms which are located on different keys, which is \"\n           \"restricted by provided constraints.\";\n  }\n};\n\nstruct GraphTypes final {\n  using Capacity = int;\n  using Weight = int;\n  using Edge = boost::graph_traits<boost::adjacency_list<\n      boost::vecS, boost::vecS, boost::directedS>>::edge_descriptor;\n  using Vertex = boost::graph_traits<boost::adjacency_list<\n      boost::vecS, boost::vecS, boost::directedS>>::vertex_descriptor;\n  struct VertexProperties final {\n    size_t index;\n    std::variant<Sym, Key> symOrKey;\n  };\n  using EdgeProperties = boost::property<\n      boost::edge_capacity_t, Capacity,\n      boost::property<boost::edge_index_t, size_t,\n                      boost::property<boost::edge_reverse_t, Edge>>>;\n  using Graph =\n      boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n                            VertexProperties, EdgeProperties>;\n};\n\ninline auto GetEdgeIndexMap(GraphTypes::Graph const &g) {\n  return boost::get(boost::edge_index, g);\n}\ninline auto GetEdgeIndexMap(GraphTypes::Graph &g) {\n  return boost::get(boost::edge_index, g);\n}\ninline auto GetVertexIndexMap(GraphTypes::Graph const &g) {\n  return boost::make_function_property_map<GraphTypes::Vertex>(\n      [&](GraphTypes::Vertex v) { return g[v].index; });\n}\ninline auto GetVertexIndexMap(GraphTypes::Graph &g) {\n  return boost::make_function_property_map<GraphTypes::Vertex>(\n      [&](GraphTypes::Vertex v) { return g[v].index; });\n}\ninline auto GetCapacityMap(GraphTypes::Graph const &g) {\n  return boost::get(boost::edge_capacity, g);\n}\ninline auto GetCapacityMap(GraphTypes::Graph &g) {\n  return boost::get(boost::edge_capacity, g);\n}\ninline auto GetReverseEdgeMap(GraphTypes::Graph const &g) {\n  return boost::get(boost::edge_reverse, g);\n}\ninline auto GetReverseEdgeMap(GraphTypes::Graph &g) {\n  return boost::get(boost::edge_reverse, g);\n}\ninline auto\nGetResidualCapacityMap(GraphTypes::Graph const &g,\n                       std::vector<GraphTypes::Capacity> &residualCapacityVec) {\n  return boost::make_iterator_property_map(residualCapacityVec.begin(),\n                                           GetEdgeIndexMap(g));\n}\ninline auto GetColorMap(GraphTypes::Graph const &g,\n                        std::vector<boost::default_color_type> &colorVec) {\n  return boost::make_iterator_property_map(colorVec.begin(),\n                                           GetVertexIndexMap(g));\n}\ninline auto GetPredcessorMap(GraphTypes::Graph const &g,\n                             std::vector<GraphTypes::Edge> &predcessorVec) {\n  return boost::make_iterator_property_map(predcessorVec.begin(),\n                                           GetVertexIndexMap(g));\n}\ninline auto GetDistanceMap(GraphTypes::Graph const &g,\n                           std::vector<GraphTypes::Capacity> &distanceVec) {\n  return boost::make_iterator_property_map(distanceVec.begin(),\n                                           GetVertexIndexMap(g));\n}\ninline auto GetWeightMap(GraphTypes::Graph const &g,\n                         std::vector<GraphTypes::Weight> const &weightVec) {\n  return boost::make_iterator_property_map(weightVec.begin(),\n                                           GetEdgeIndexMap(g));\n}\n\nclass GraphContainer final {\npublic:\n  using Capacity = GraphTypes::Capacity;\n  using Weight = GraphTypes::Weight;\n  using Edge = GraphTypes::Edge;\n  using Vertex = GraphTypes::Vertex;\n  using Graph = GraphTypes::Graph;\n\nprivate:\n  std::unique_ptr<Graph> gptr;\n\npublic:\n  GraphContainer() : gptr{std::make_unique<Graph>()} {}\n  GraphContainer(GraphContainer const &gc) : gptr{Copy(gc)} {}\n  GraphContainer(GraphContainer &&gc) noexcept = default;\n  GraphContainer &operator=(GraphContainer const &gc) & { gptr = Copy(gc); }\n  GraphContainer &operator=(GraphContainer &&gc) &noexcept = default;\n  ~GraphContainer() = default;\n  Graph &GetGraph() noexcept { return *gptr; }\n  operator Graph &() noexcept { return *gptr; }\n  Graph const &GetGraph() const noexcept { return *gptr; }\n  operator Graph const &() const noexcept { return *gptr; }\n\nprivate:\n  static std::unique_ptr<Graph> Copy(GraphContainer const &gc) {\n    // Vertices are value types, but edges behave more like references\n    // Thus it requires rebinding in some properties\n    auto gptr = std::make_unique<Graph>();\n    auto &&g1 = *gptr;\n    auto const &g2 = *gc.gptr;\n    auto const &vertexIndexMap = GetVertexIndexMap(g2);\n    auto props = boost::vertex_index1_map(vertexIndexMap);\n    boost::copy_graph(g2, g1, props);\n\n    auto indices1 = std::vector<Edge>(boost::num_edges(g1));\n    auto &&edgeIndexMap1 = GetEdgeIndexMap(g1);\n    auto const &edgeIndexMap2 = GetEdgeIndexMap(g2);\n    auto &&capacityMap1 = GetCapacityMap(g1);\n    auto const &capacityMap2 = GetCapacityMap(g2);\n    auto &&reverseEdgeMap1 = GetReverseEdgeMap(g1);\n    auto const &reverseEdgeMap2 = GetReverseEdgeMap(g2);\n    assert(boost::num_edges(g1) == boost::num_edges(g2));\n    auto const &edges1 = boost::edges(g1);\n    auto const &edges2 = boost::edges(g2);\n    auto it1 = edges1.first;\n    auto it2 = edges2.first;\n    for (auto i = size_t{0}, e = boost::num_edges(g1); i != e; ++i) {\n      edgeIndexMap1[*it1] = edgeIndexMap2[*it2];\n      capacityMap1[*it1] = capacityMap2[*it2];\n      indices1[edgeIndexMap1[*it1]] = *it1;\n      ++it1;\n      ++it2;\n    }\n    it1 = edges1.first;\n    it2 = edges2.first;\n    for (auto i = size_t{0}, e = boost::num_edges(g1); i != e; ++i) {\n      reverseEdgeMap1[*it1] = indices1[edgeIndexMap2[reverseEdgeMap2[*it2]]];\n      ++it1;\n      ++it2;\n    }\n    return std::move(gptr);\n  }\n};\n\nclass LayoutGraph final {\npublic:\n  using Capacity = GraphTypes::Capacity;\n  using Weight = GraphTypes::Weight;\n  using Edge = GraphTypes::Edge;\n  using Vertex = GraphTypes::Vertex;\n  using Graph = GraphTypes::Graph;\n  using Weights = std::vector<Weight>;\n\nprivate:\n  using SymVertexMap = std::unordered_map<Sym, Vertex>;\n  using KeyVertexMap = std::unordered_map<Key, Vertex>;\n\n  GraphContainer gc;\n  Vertex symSource = Vertex{};\n  Vertex keySink = Vertex{};\n  SymVertexMap symVertices;\n  KeyVertexMap keyVertices;\n  std::unordered_set<size_t> reverseEdges;\n  std::set<size_t> directEdges;\n  Graph &G() { return gc.GetGraph(); }\n  Graph const &G() const { return gc.GetGraph(); }\n  void AddSource() {\n    symSource = boost::add_vertex({boost::num_vertices(G()), Sym{}}, G());\n  }\n  void AddSink() {\n    keySink = boost::add_vertex({boost::num_vertices(G()), Sym{}}, G());\n  }\n\npublic:\n  LayoutGraph() {\n    AddSource();\n    AddSink();\n  }\n\n  size_t GetNEdges() const { return boost::num_edges(G()); }\n  size_t GetNVertices() const { return boost::num_vertices(G()); }\n  auto GetEdges() const {\n    return boost::make_iterator_range(boost::edges(G()));\n  }\n  auto GetVertices() const {\n    return boost::make_iterator_range(boost::vertices(G()));\n  }\n  Vertex GetSource() const { return symSource; }\n  Vertex GetSink() const { return keySink; }\n  std::optional<Vertex> GetVertex(Sym sym) const {\n    if (symVertices.contains(sym))\n      return symVertices.at(sym);\n    return {};\n  }\n  std::optional<Vertex> GetVertex(Key key) const {\n    if (keyVertices.contains(key))\n      return keyVertices.at(key);\n    return {};\n  }\n  Vertex GetSource(Edge e) const { return boost::source(e, G()); }\n  Vertex GetTarget(Edge e) const { return boost::target(e, G()); }\n  Vertex GetOrAddVertex(Sym sym) {\n    if (!symVertices.contains(sym)) {\n      auto v = boost::add_vertex({boost::num_vertices(G()), sym}, G());\n      symVertices.emplace(sym, v);\n      AddEdge(symSource, v);\n    }\n    return symVertices.at(sym);\n  }\n  Vertex GetOrAddVertex(Key key) {\n    if (!keyVertices.contains(key)) {\n      auto v = boost::add_vertex({boost::num_vertices(G()), key}, G());\n      keyVertices.emplace(key, v);\n      AddEdge(v, keySink);\n    }\n    return keyVertices.at(key);\n  }\n  std::optional<Edge> GetEdge(Vertex v1, Vertex v2) const {\n    auto const &[e, isExist] = boost::edge(v1, v2, G());\n    if (isExist)\n      return e;\n    return {};\n  }\n  Edge AddEdge(Vertex v1, Vertex v2) {\n#ifndef NDEBUG\n    assert(v1 != v2);\n    assert(!IsSource(v2));\n    assert(!IsSink(v1));\n    assert(!IsSource(v1) || IsSym(v2));\n    assert(!IsSink(v2) || IsKey(v1));\n    assert(!((IsSym(v1) || IsKey(v1)) && (IsSym(v2) || IsKey(v2))) ||\n           (IsSym(v1) && IsKey(v2)));\n    auto const &[tmp, isExist] = boost::edge(v1, v2, G());\n    assert(!isExist);\n#endif // !NDEBUG\n    auto &&edgeIndexMap = boost::get(boost::edge_index, G());\n    auto &&capacityMap = boost::get(boost::edge_capacity, G());\n    auto &&reverseEdgeMap = boost::get(boost::edge_reverse, G());\n    auto const &[direct, success1] = boost::add_edge(v1, v2, G());\n    assert(success1);\n    assert(boost::num_edges(G()) > 0);\n    edgeIndexMap[direct] = boost::num_edges(G()) - 1;\n    capacityMap[direct] = 1;\n    auto const &[reverse, success2] = boost::add_edge(v2, v1, G());\n    assert(success2);\n    edgeIndexMap[reverse] = boost::num_edges(G()) - 1;\n    capacityMap[reverse] = 0;\n    reverseEdgeMap[direct] = reverse;\n    reverseEdgeMap[reverse] = direct;\n    reverseEdges.insert(edgeIndexMap[reverse]);\n    auto ind = edgeIndexMap[direct];\n    directEdges.insert(edgeIndexMap[direct]);\n    return direct;\n  }\n  bool IsSource(Vertex v) const { return v == symSource; }\n  bool IsSink(Vertex v) const { return v == keySink; }\n  bool IsSym(Vertex v) const {\n    return !IsSource(v) && !IsSink(v) &&\n           std::holds_alternative<Sym>(G()[v].symOrKey);\n  }\n  bool IsKey(Vertex v) const {\n    return !IsSource(v) && !IsSink(v) &&\n           std::holds_alternative<Key>(G()[v].symOrKey);\n  }\n  bool IsReverse(Edge e) const {\n    auto const &edgeIndexMap = boost::get(boost::edge_index, G());\n    return reverseEdges.contains(edgeIndexMap[e]);\n  }\n  Sym GetSym(Vertex v) const {\n    assert(IsSym(v));\n    return std::get<Sym>(G()[v].symOrKey);\n  }\n  Key GetKey(Vertex v) const {\n    assert(IsKey(v));\n    return std::get<Key>(G()[v].symOrKey);\n  }\n\n  Weights ScaleDirectWeights(Weights const &userWeights) const {\n    assert(userWeights.size() == directEdges.size());\n    auto weights = Weights(GetNEdges());\n    auto ind = size_t{0};\n    for (auto directInd : directEdges)\n      weights[directInd] = userWeights[ind++];\n    auto const &edgeIndexMap = boost::get(boost::edge_index, G());\n    auto const &reverseEdgeMap = boost::get(boost::edge_reverse, G());\n    for (auto const &e : GetEdges()) {\n      if (!IsReverse(e))\n        continue;\n      auto i1 = edgeIndexMap[e];\n      auto i2 = edgeIndexMap[reverseEdgeMap[e]];\n      weights[edgeIndexMap[e]] = -weights[edgeIndexMap[reverseEdgeMap[e]]];\n    }\n    return weights;\n  }\n\n  Weights GenerateDirectWeights(Layout const &layout, Weight min,\n                                Weight max) const {\n    auto weights = Weights(directEdges.size(), max);\n    auto const &edgeIndexMap = boost::get(boost::edge_index, G());\n    for (auto sym = Sym{}, e = layout.size(); sym != e; ++sym) {\n      auto const &p = layout[sym];\n      auto sv = GetVertex(sym);\n      auto kv = GetVertex(p.key);\n      if (!sv || !kv)\n        continue;\n      auto edge = GetEdge(sv.value(), kv.value());\n      if (!edge)\n        continue;\n      auto se = GetEdge(GetSource(), sv.value()).value();\n      auto te = GetEdge(kv.value(), GetSink()).value();\n      weights[edgeIndexMap[edge.value()]] = min;\n      weights[edgeIndexMap[se]] = min;\n      weights[edgeIndexMap[te]] = min;\n    }\n  }\n\n  Graph const &GetGraph() const noexcept { return G(); }\n  operator Graph const &() const noexcept { return G(); }\n};\n\nclass GraphProperties final {\n  using Graph = GraphTypes::Graph;\n  using Capacity = GraphTypes::Capacity;\n  using Vertex = GraphTypes::Vertex;\n  using Edge = GraphTypes::Edge;\n\n  using EdgeIndexMap = decltype(GetEdgeIndexMap(std::declval<Graph const &>()));\n  using VertexIndexMap =\n      decltype(GetVertexIndexMap(std::declval<Graph const &>()));\n  using CapacityMap = decltype(GetCapacityMap(std::declval<Graph const &>()));\n  using ReverseEdgeMap =\n      decltype(GetReverseEdgeMap(std::declval<Graph const &>()));\n  using ResidualCapacityMap = decltype(GetResidualCapacityMap(\n      std::declval<Graph const &>(), std::declval<std::vector<Capacity> &>()));\n  using ColorMap = decltype(\n      GetColorMap(std::declval<Graph const &>(),\n                  std::declval<std::vector<boost::default_color_type> &>()));\n  using PredcessorMap = decltype(GetPredcessorMap(\n      std::declval<Graph const &>(), std::declval<std::vector<Edge> &>()));\n  using DistanceMap = decltype(GetDistanceMap(\n      std::declval<Graph const &>(), std::declval<std::vector<Capacity> &>()));\n\n  LayoutGraph const &g;\n  size_t nEdges;\n  size_t nVertices;\n  Vertex source;\n  Vertex sink;\n  std::vector<Capacity> residualCapacityVec;\n  std::vector<boost::default_color_type> colorVec;\n  std::vector<Capacity> distanceVec;\n  std::vector<Capacity> distanceVec2;\n  std::vector<Edge> predcessorVec;\n  EdgeIndexMap edgeIndexMap;\n  VertexIndexMap vertexIndexMap;\n  CapacityMap capacityMap;\n  ReverseEdgeMap reverseEdgeMap;\n  ResidualCapacityMap residualCapacityMap;\n  ColorMap colorMap;\n  PredcessorMap predcessorMap;\n  DistanceMap distanceMap;\n  DistanceMap distanceMap2;\n\npublic:\n  GraphProperties(LayoutGraph const &layoutGraph, Vertex source, Vertex sink)\n      : g(layoutGraph), nEdges(g.GetNEdges()), nVertices(g.GetNVertices()),\n        source(source), sink(sink),\n        residualCapacityVec(std::vector<Capacity>(nEdges)),\n        colorVec(std::vector<boost::default_color_type>(nVertices)),\n        distanceVec(std::vector<Capacity>(nVertices)),\n        distanceVec2(std::vector<Capacity>(nVertices)),\n        predcessorVec(std::vector<Edge>(nVertices)),\n        edgeIndexMap(KeyboardOptimizer::GetEdgeIndexMap(g)),\n        vertexIndexMap(KeyboardOptimizer::GetVertexIndexMap(g)),\n        capacityMap(KeyboardOptimizer::GetCapacityMap(g)),\n        reverseEdgeMap(KeyboardOptimizer::GetReverseEdgeMap(g)),\n        residualCapacityMap(\n            KeyboardOptimizer::GetResidualCapacityMap(g, residualCapacityVec)),\n        colorMap(KeyboardOptimizer::GetColorMap(g, colorVec)),\n        predcessorMap(KeyboardOptimizer::GetPredcessorMap(g, predcessorVec)),\n        distanceMap(KeyboardOptimizer::GetDistanceMap(g, distanceVec)),\n        distanceMap2(KeyboardOptimizer::GetDistanceMap(g, distanceVec2)) {}\n  // Other ctors are deleted because most of fields in this class are\n  // effectively references, which require non-trivial copying\n  GraphProperties(GraphProperties const &) = delete;\n  GraphProperties(GraphProperties &&) = delete;\n  GraphProperties &operator=(GraphProperties const &) = delete;\n  GraphProperties &operator=(GraphProperties &&) = delete;\n  Vertex GetSource() const { return source; }\n  Vertex GetSink() const { return sink; }\n  LayoutGraph const &GetLayoutGraph() const { return g; }\n  EdgeIndexMap const &GetEdgeIndexMap() const { return edgeIndexMap; }\n  VertexIndexMap const &GetVertexIndexMap() const { return vertexIndexMap; }\n  CapacityMap const &GetCapacityMap() const { return capacityMap; }\n  ReverseEdgeMap const &GetReverseEdgeMap() const { return reverseEdgeMap; }\n  ResidualCapacityMap const &GetResidualCapacityMap() const {\n    return residualCapacityMap;\n  }\n  ColorMap const &GetColorMap() const { return colorMap; }\n  PredcessorMap const &GetPredcessorMap() const { return predcessorMap; }\n  DistanceMap const &GetDistanceMap() const { return distanceMap; }\n  DistanceMap const &GetDistanceMap2() const { return distanceMap2; }\n  ResidualCapacityMap &GetResidualCapacityMap() {\n    return residualCapacityMap;\n  }\n  ColorMap &GetColorMap() { return colorMap; }\n  PredcessorMap &GetPredcessorMap() { return predcessorMap; }\n  DistanceMap &GetDistanceMap() { return distanceMap; }\n  DistanceMap &GetDistanceMap2() { return distanceMap2; }\n\n  auto GetProperties() {\n    return boost::color_map(colorMap)\n        .residual_capacity_map(residualCapacityMap)\n        .distance_map(distanceMap)\n        .distance_map2(distanceMap2)\n        .vertex_index_map(vertexIndexMap)\n        .predecessor_map(predcessorMap);\n  }\n};\n\nclass Filter final {\npublic:\n  using SymLayers = SymMap<Layer>;\n  using SymKeyMap = std::unordered_map<Sym, Key>;\n  using FilteredGraph =\n      boost::filtered_graph<LayoutGraph::Graph, Filter, Filter>;\n\nprivate:\n  using Vertex = LayoutGraph::Vertex;\n  using Edge = LayoutGraph::Edge;\n\n  LayoutGraph const *g;\n  SymLayers symLayers;\n  SymKeyMap matchedSyms;\n  std::unordered_set<Key> matchedKeys;\n  Layer layer;\n  bool isShowSym(Sym sym) const {\n    return (symLayers[sym] == layer) && (!matchedSyms.contains(sym));\n  }\n  bool isShowKey(Key key) const { return !matchedKeys.contains(key); }\n  bool isShow(Vertex v) const {\n    if (g->IsSym(v))\n      return isShowSym(g->GetSym(v));\n    if (g->IsKey(v))\n      return isShowKey(g->GetKey(v));\n    return true;\n  }\n\npublic:\n  // Default ctor is required for boost::filtered_graph\n  Filter() : g{nullptr}, layer{Layer{}} {}\n  Filter(LayoutGraph const &g, SymLayers const &symLayers)\n      : g{&g}, symLayers{symLayers}, layer{Layer{}} {}\n  void Set(Layer layer_, SymKeyMap &&matchedSyms_) {\n    auto matchedKeys_ = std::unordered_set<Key>{};\n    for (auto &&[sym, key] : matchedSyms_)\n      if (symLayers[sym] == layer)\n        matchedKeys_.insert(key);\n    matchedSyms = std::move(matchedSyms_);\n    matchedKeys = std::move(matchedKeys_);\n    layer = layer_;\n  }\n  bool operator()(Edge e) const {\n    assert(g);\n    return isShow(g->GetSource(e)) && isShow(g->GetTarget(e));\n  }\n  bool operator()(Vertex v) const {\n    assert(g);\n    return isShow(v);\n  }\n  Layer GetLayer() const noexcept { return layer; }\n  LayoutGraph const &GetLayoutGraph() const { return *g; }\n  FilteredGraph GetFilteredGraph() { return FilteredGraph(*g, *this, *this); }\n};\n\nclass StandartConstraintsGraph final {\npublic:\n  using Weight = LayoutGraph::Weight;\n  using Weights = LayoutGraph::Weights;\n  using AllowedKeys = std::unordered_set<Key>;\n  using SymConstraints = SymMap<AllowedKeys>;\n  using SymLayers = Filter::SymLayers;\n  using SymKeyMap = Filter::SymKeyMap;\n  using SymBonds = SymVector;\n\nprivate:\n  Keyboard keyboard;\n  SymLayers symLayers;\n  SymBonds symBonds;\n  SymConstraints constraints;\n  size_t nLayers;\n  LayersMap<Layer> layersComputeOrder;\n  LayoutGraph layoutGraph;\n  using FilteredGraph = Filter::FilteredGraph;\n\npublic:\n  StandartConstraintsGraph(SymLayers &&symLayers_, SymBonds &&symBonds_,\n                           SymConstraints &&constraints_, Keyboard &&keyboard)\n      : keyboard{std::move(keyboard)}, symLayers{std::move(symLayers_)},\n        symBonds{std::move(symBonds_)}, constraints{std::move(constraints_)},\n        nLayers{EvaluateNLayers(symLayers)} {\n    CheckSymKeyNumber();\n    RegularizeSymBonds(symBonds);\n    layersComputeOrder = GetBestLayersPermutation();\n    GenerateGraph(constraints);\n  }\n\n  size_t GetRequiredWeightsSize() const {\n    auto nEdges = layoutGraph.GetNEdges();\n    assert(nEdges % 2 == 0);\n    return nEdges / 2;\n  }\n\n  Weights GenerateWeights(Layout const &layout, Weight min, Weight max) const {\n    return layoutGraph.GenerateDirectWeights(layout, min, max);\n  }\n\n  void CheckConstraints(Layout const &layout) const {\n    assert(layout.size() == symLayers.size());\n    for (auto sym = Sym{}, e = layout.size(); sym != e; ++sym) {\n      auto const &p = layout[sym];\n      if (symLayers[sym] != p.layer)\n        throw MismatchedLayer(Layout(layout), sym, p.layer, symLayers[sym]);\n      auto sv = layoutGraph.GetVertex(sym).value();\n      auto kv = layoutGraph.GetVertex(p.key);\n      if (!kv || !layoutGraph.GetEdge(sv, kv.value()))\n        throw MissingEdge(Layout(layout), sym, p.key);\n    }\n    for (auto sym = Sym{}, e = symBonds.size(); sym != e; ++sym) {\n      auto key = layout[sym].key;\n      auto sym2 = symBonds[sym];\n      auto key2 = layout[sym2].key;\n      if (!(key == key2))\n        throw UnsatisfiedSymBond(Layout(layout), sym, key, sym2, key2);\n    }\n  }\n\n  Layout GenerateLayout(Weights const &weights,\n                        bool allowBreakingConstraints) const {\n    auto matchedSyms = SymKeyMap{};\n    auto filter = Filter{layoutGraph, symLayers};\n    auto props = GraphProperties{layoutGraph, layoutGraph.GetSource(),\n                                 layoutGraph.GetSink()};\n    auto adaptedWeigths = layoutGraph.ScaleDirectWeights(weights);\n    for (auto layer : layersComputeOrder) {\n      filter.Set(layer, SymKeyMap{matchedSyms});\n      auto &&g = filter.GetFilteredGraph();\n      EvaluateMaxFlow(g, props);\n      if (!allowBreakingConstraints)\n        CheckMaxFlow(g, props, matchedSyms);\n      EvaluateMinCostMaxFlow(g, props, adaptedWeigths);\n      UpdateMatchedSyms(g, props, matchedSyms);\n    }\n    return GenerateLayout_(matchedSyms);\n  }\n\n  Keyboard const &GetKeyboard() const { return keyboard; }\n  size_t GetNSyms() const {\n    assert(symLayers.size() == symBonds.size());\n    assert(constraints.size() == symBonds.size());\n    return symLayers.size();\n  }\n\nprivate:\n  void CheckSymKeyNumber() const {\n#ifndef NDEBUG\n    auto nSyms = LayersMap<size_t>(nLayers);\n    for (auto sym = Sym{}, e = symLayers.size(); sym != e; ++sym)\n      ++nSyms[symLayers[sym]];\n    for (auto layer = size_t{0}; layer != nLayers; ++layer)\n      assert(nSyms[layer] <= keyboard.size());\n#endif // !NDEBUG\n  }\n  static size_t EvaluateNLayers(SymLayers const &symLayers) {\n    auto mentioned = LayersMap<bool>{};\n    for (auto layer : symLayers) {\n      if (mentioned.size() <= layer)\n        mentioned.resize(layer + 1, false);\n      mentioned[layer] = true;\n    }\n    assert(std::all_of(mentioned.begin(), mentioned.end(),\n                       [](bool m) { return m; }));\n    return mentioned.size();\n  }\n  static void RegularizeSymBonds(SymBonds &symBonds) {\n    assert(*std::max_element(symBonds.begin(), symBonds.end()) <\n           symBonds.size());\n    for (auto &&parent : symBonds)\n      while (parent != symBonds[parent])\n        parent = symBonds[parent];\n  }\n\n  void GenerateGraph(SymConstraints const &constraints) {\n    assert(*std::max_element(symBonds.begin(), symBonds.end()) <\n           symBonds.size());\n    assert(symLayers.size() == symBonds.size());\n    assert(symLayers.size() == constraints.size());\n#ifndef NDEBUG\n    for (auto sym = Sym{}; sym != symBonds.size(); ++sym)\n      assert((symBonds[sym] == sym) ==\n             (symLayers[symBonds[sym]] == symLayers[sym]));\n#endif // !NDEBUG\n    for (auto sym = Sym{}; sym != constraints.size(); ++sym) {\n      auto const &keys = constraints[sym];\n      auto symV = layoutGraph.GetOrAddVertex(sym);\n      for (auto const &key : keys) {\n        auto keyV = layoutGraph.GetOrAddVertex(key);\n        layoutGraph.AddEdge(symV, keyV);\n      }\n    }\n  }\n\n  // Since min-const max-flow problem is solved iteratively\n  // This function provides an order of layers\n  LayersMap<Layer> GetBestLayersPermutation() const {\n    auto layers = LayersMap<Layer>(nLayers);\n    std::iota(layers.begin(), layers.end(), 0);\n    return layers;\n  }\n\n  static void EvaluateMaxFlow(FilteredGraph &g, GraphProperties &p) {\n    boost::boykov_kolmogorov_max_flow(g, p.GetSource(), p.GetSink(),\n                                      p.GetProperties());\n  }\n\n  void CheckMaxFlow(FilteredGraph const &g, GraphProperties const &p,\n                    SymKeyMap const &matchedSyms) const {\n    auto whiteSyms = std::unordered_set<Sym>{};\n    auto keys = std::unordered_set<Key>{};\n    for (auto v : boost::make_iterator_range(boost::vertices(g))) {\n      if (!layoutGraph.IsSym(v))\n        continue;\n      if (p.GetColorMap()[v] != boost::default_color_type::white_color)\n        continue;\n      whiteSyms.insert(layoutGraph.GetSym(v));\n      for (auto const &ke :\n           boost::make_iterator_range(boost::out_edges(v, g))) {\n        auto kv = boost::target(ke, g);\n        if (layoutGraph.IsSource(kv))\n          continue;\n        keys.insert(layoutGraph.GetKey(kv));\n      }\n    }\n    if (whiteSyms.size() == 0)\n      return;\n    assert(whiteSyms.size() > keys.size());\n    auto layer = symLayers[*whiteSyms.begin()];\n    throw InvalidConstraints(std::move(whiteSyms), std::move(keys),\n                             SymKeyMap(matchedSyms), layer);\n  }\n  static void EvaluateMinCostMaxFlow(FilteredGraph &g, GraphProperties &p,\n                                     Weights const &weights) {\n    auto props =\n        p.GetProperties().weight_map(GetWeightMap(p.GetLayoutGraph(), weights));\n    boost::successive_shortest_path_nonnegative_weights(g, p.GetSource(),\n                                                        p.GetSink(), props);\n  }\n  void UpdateMatchedSyms(FilteredGraph &g, GraphProperties &p,\n                         SymKeyMap &matchedSyms) const {\n    for (auto const &e : boost::make_iterator_range(boost::edges(g))) {\n      if (layoutGraph.IsReverse(e))\n        continue;\n      auto s = layoutGraph.GetSource(e);\n      auto t = layoutGraph.GetTarget(e);\n      if (!layoutGraph.IsSym(s))\n        continue;\n      auto chosen =\n          (p.GetCapacityMap()[e] - p.GetResidualCapacityMap()[e]) == 1;\n      if (!chosen)\n        continue;\n      auto sym = layoutGraph.GetSym(s);\n      auto key = layoutGraph.GetKey(t);\n      matchedSyms.emplace(sym, std::move(key));\n    }\n\n    // Now, propagate all new sym matches to other layers\n    for (auto sym = Sym{}, e = symBonds.size(); sym != e; ++sym)\n      if (matchedSyms.contains(sym))\n        matchedSyms.emplace(symBonds[sym], matchedSyms.at(sym));\n    for (auto sym = Sym{}, e = matchedSyms.size(); sym != e; ++sym)\n      if (matchedSyms.contains(symBonds[sym]))\n        matchedSyms.emplace(sym, matchedSyms.at(symBonds[sym]));\n  }\n\n  std::vector<Key> GetNonMatchedKeys(SymKeyMap const &matchedSyms) const {\n    auto availableKeys = std::vector<Key>{};\n    auto matchedKeys = std::unordered_set<Key>{};\n    availableKeys.reserve(keyboard.size());\n    matchedKeys.reserve(matchedSyms.size());\n    for (auto const &[sym, key] : matchedSyms)\n      matchedKeys.insert(key);\n    for (auto const &key : keyboard)\n      if (!matchedKeys.contains(key))\n        availableKeys.push_back(key);\n    return availableKeys;\n  }\n\n  Layout GenerateLayout_(SymKeyMap const &matchedSyms) const {\n    using std::swap;\n    auto availableKeys = std::optional<std::vector<Key>>{};\n    if (symLayers.size() != matchedSyms.size())\n      availableKeys = GetNonMatchedKeys(matchedSyms);\n    auto layout = Layout{};\n    auto &&gen = Utility::GetRandomGenerator();\n    auto rand = std::uniform_int_distribution<size_t>();\n    layout.reserve(symLayers.size());\n    for (auto sym = Sym{}, e = symLayers.size(); sym != e; ++sym) {\n      auto layer = symLayers[sym];\n      if (matchedSyms.contains(sym))\n        layout.emplace_back(matchedSyms.at(sym), layer);\n      else {\n        auto i = rand(gen) % availableKeys.value().size();\n        swap(availableKeys.value()[i], availableKeys.value().back());\n        auto key = availableKeys.value().back();\n        availableKeys.value().pop_back();\n        layout.emplace_back(key, layer);\n      }\n    }\n    return layout;\n  }\n};\n} // namespace KeyboardOptimizer\n", "meta": {"hexsha": "7d6868ae02a6fc54b897f2a29b42583122a0685e", "size": 29643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "keyboard_optimizer/include/keyboard_optimizer/standart_constraints_graph.hpp", "max_stars_repo_name": "RudenkoRNK/keyboard_optimizer", "max_stars_repo_head_hexsha": "016d228a448001493e2b27ca8ad342d9e2ff0e21", "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": "keyboard_optimizer/include/keyboard_optimizer/standart_constraints_graph.hpp", "max_issues_repo_name": "RudenkoRNK/keyboard_optimizer", "max_issues_repo_head_hexsha": "016d228a448001493e2b27ca8ad342d9e2ff0e21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "keyboard_optimizer/include/keyboard_optimizer/standart_constraints_graph.hpp", "max_forks_repo_name": "RudenkoRNK/keyboard_optimizer", "max_forks_repo_head_hexsha": "016d228a448001493e2b27ca8ad342d9e2ff0e21", "max_forks_repo_licenses": ["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.2399497487, "max_line_length": 80, "alphanum_fraction": 0.6607968154, "num_tokens": 7525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.26894142136999516, "lm_q1q2_score": 0.16641568936701315}}
{"text": "#include <cstdlib>\n#include <list>\n#include <string>\n#include <iostream>\n#include <map>\n#include <regex>\n#include <xercesc/dom/DOM.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include \"Error.h\"\n#include \"Array.h\"\n#include \"cstringtools.h\"\n#include \"BitArray.h\"\n#include \"charptr_map.h\"\n\n#include \"Pool.h\"\n#include \"InputPool.h\"\n\n#include \"UnicodeTools.h\"\n#include \"XMLException.h\"\n#include \"XMLElement.h\"\n\n#include \"FluxMLContentObject.h\"\n#include \"FluxMLUnicodeConstants.h\"\n#include \"FluxMLInput.h\"\n\n#include \"FluxMLDocument.h\"\n\n#include \"ExprTree.h\"\n#include \"LinearExpression.h\"\n\n#include \"MathML.h\"\n#include \"MathMLDocument.h\"\n#include \"MathMLDeclare.h\"\n#include \"MathMLExpression.h\"\n\n// Xerces C++ Namespace einbinden\nXERCES_CPP_NAMESPACE_USE\n\nusing namespace flux::symb;\n\nnamespace flux {\nnamespace xml {\n\n    \n/**\n * Parst ein Input-Element aus einem DOM-Tree eines FluxML-Dokuments.\n *\n * @param node Knoten des Input-Elements\n */\nvoid FluxMLInput::parseInput(DOMNode * input)\n{\n\tDOMNode * label;\n\tDOMNamedNodeMap * nnm;\n\tDOMAttr * poolAttr, * typeAttr, * cfgAttr, * purityAttr, * costAttr, * idAttr;\n        /*** Neue Prfoile-Version **/\n        /** List der Bedingungen des Profiles */\n\tstd::list<double> profile_conditions_;\n        DOMAttr *profileAttr;\n        profile_defined=false;\n        /*** Ende: Neue Prfoile-Version **/\n\tint natoms = 0;\n\tdouble cost;\n        Array< double > purity;\n\tcharptr_map< Array< double > > values;        \n        charptr_map< Array< double > > purities;\n        charptr_map< double > costs;\n        charptr_map< data::InputProfile> profiles;        \n\tBitArray mask;\n\tdata::InputPool::Type ip_type =\n        data::InputPool::ip_isotopomer; // \"isotopomer\" ist default\n        \n\tif (input_pool_)\n\t\tfTHROW(XMLException,input,\"FluxMLInput object already initialized!\");\n\n\tif (not XMLElement::match(input,fml_input,fml_xmlns_uri))\n\t\tfTHROW(XMLException,input,\"element node (input) expected.\");\n\n\tnnm = input->getAttributes();\n\tif (nnm == 0)\n\t\tfTHROW(XMLException,input,\"element node (input) lacks attributes.\");\n\n\t// Attribut pool (Pool-Bezeichnung)\n\tpoolAttr = static_cast< DOMAttr* >(nnm->getNamedItem(fml_pool));\n\tif (poolAttr == 0)\n\t\tfTHROW(XMLException,input,\"element node (input) lacks pool attribute.\");\n\tU2A utf_pool_name(poolAttr->getValue());\n\n\t// Gibt es den Pool?\n\tdata::Pool * ipool = lookupPool(utf_pool_name);\n\tif (ipool == 0)\n\t{\n\t\tfTHROW(XMLException,input,\n\t\t\t\t\"unknown pool %s in input substrate spec\",\n\t\t\t\t(char const*)utf_pool_name);\n\t}                        \n        data::Configuration * cfg = doc_->getRootConfiguration();\n\tstd::list< data::Constraint > const & eqConstraints = cfg->getEqualities();\n\tstd::list< data::Constraint >::const_iterator eqConstraints_it;\n\n\tfor (eqConstraints_it=eqConstraints.begin(); eqConstraints_it!=eqConstraints.end(); eqConstraints_it++)\n\t{\n\t\tcharptr_array constraintsVars = eqConstraints_it->getConstraint()->getVarNames();\n\t\tif(constraintsVars.find((char const*)utf_pool_name)!=constraintsVars.end())\n\t\t\tfTHROW(XMLException,input,\n\t\t\t\t\"input pool \\\"%s\\\" specified in equality constraint\",\n\t\t\t\t(char const*)utf_pool_name);\n\t}\n\t\n\t\n\tstd::list< data::Constraint > const & ineqConstraints = cfg->getInEqualities();\n\tstd::list< data::Constraint >::const_iterator ineqConstraints_it;\n\t\n\tfor (ineqConstraints_it=ineqConstraints.begin(); ineqConstraints_it!=ineqConstraints.end(); ineqConstraints_it++)\n\t{\n\t\tcharptr_array constraintsVars = ineqConstraints_it->getConstraint()->getVarNames();\n\t\tif(constraintsVars.find((char const*)utf_pool_name)!=constraintsVars.end()) \n\t\t\tfTHROW(XMLException,input,\n\t\t\t\t\"input pool \\\"%s\\\" specified in inequality constraint\",\n\t\t\t\t(char const*)utf_pool_name);\n\t}\n\t// Anzahl der Atome / Init. der Maske\n\tnatoms = ipool->getNumAtoms();\n\tmask.resize(natoms,false);\n\n\t// Attribut id (Experimental Design)\n\tidAttr = static_cast< DOMAttr* >(nnm->getNamedItem(fml_id));\n\tU2A utf_id(idAttr ? idAttr->getValue() : 0);\n\n\t// Attribut type (isotopomer/cumomer/emu)\n\ttypeAttr = static_cast< DOMAttr* >(nnm->getNamedItem(fml_type));\n\tif (typeAttr != 0)\n\t{\n\t\tif (XMLString::equals(typeAttr->getValue(), fml_isotopomer))\n\t\t\tip_type = data::InputPool::ip_isotopomer;\n\t\telse if (XMLString::equals(typeAttr->getValue(),fml_cumomer))\n\t\t\tip_type = data::InputPool::ip_cumomer;\n\t\telse if (XMLString::equals(typeAttr->getValue(),fml_emu))\n\t\t\tip_type = data::InputPool::ip_emu;\n\t\telse\n\t\t{\n\t\t\tfTHROW(XMLException,input,\n\t\t\t\t\"input pool %s: type is restricted to \\\"isotopomer\\\", \"\n\t\t\t\t\"\\\"cumomer\\\" or \\\"emu\\\"\",\n\t\t\t\tipool->getName());\n\t\t}\n\t}\n        \n        // Zweite Version der Input-Proflie definiert \u00fcber profile-Attribut \n        // gilt f\u00fcr alle Labels\n\tprofileAttr = static_cast< DOMAttr* >(nnm->getNamedItem(fml_profile));\n\tif (profileAttr != 0)\n\t{   \n            // profile definiert\n            profile_defined=true;\n\n        // f\u00fcge den Startpunkt Null zu Bedinngungsliste hinzu\n        profile_conditions_.push_back(0.);\n\n        // Profile-Bedingungen parsen\n        U2A utf_profile(profileAttr->getValue());\n        charptr_array expr_list = charptr_array::split(utf_profile,\",\");\n        charptr_array::const_iterator i;\n        double prv_val= 0., act_val=0.;\n\n        for (i=expr_list.begin(); i!=expr_list.end(); i++)\n        {\n            char const * w;\n            for (w=*i; *w!='\\0'; w++)\n                if (*w > 32) break;\n            if (*w == '\\0')\n                continue;\n\n            act_val= std::atof(*i);\n\n            // \u00dcberpr\u00fcfung der INF und Null-Zeitangabe\n            if(act_val==0. or std::isinf(act_val))\n                fTHROW(XMLException,input,\n                       \"parse error in input profile attribute (%s): \"\n                       \"The timestamp \\\"t=0\\\" and \\\"t=inf\\\" must not be explicitly stated!\", *i);\n\n            // \u00dcberpr\u00fcfung von streng monoton aufsteigender kommagetrennter Zeiten\n            if(act_val<= prv_val)\n                fTHROW(XMLException,input,\n                       \"parse error in input profile attribute (%s): \"\n                       \"The timestamps must be specified in a strictly monotonously manner\", *i);\n\n            profile_conditions_.push_back(act_val);\n            prv_val= act_val;\n        }\n\t} else // Pr\u00fcfe die Input-Substrate ob es sich um eine Substrate-Profile handelt\n    {\n        label = XMLElement::skipJunkNodes(input->getFirstChild());\n        do\n        {\n            if(label!= 0)\n            {\n                DOMNode * child = XMLElement::skipJunkNodes(label->getFirstChild());\n                U2A data(static_cast< DOMText* >(child)->getData());\n                std::string str= (char * )data;\n                if (str.find(\"t\") != std::string::npos)\n                {\n                    profile_defined=true;\n\n                    // f\u00fcge den Startpunkt Null zu Bedinngungsliste hinzu\n                    profile_conditions_.push_back(0.);\n\n                    break;\n                }\n            }\n\n            // Next label-Element\n            label = XMLElement::nextNode(label);\n        }\n        while (label != 0);\n    }\n\t\n\tlabel = XMLElement::skipJunkNodes(input->getFirstChild());\n\tdo\n\t{\n\t\tif (not XMLElement::match(label,fml_label,fml_xmlns_uri))\n\t\t{\n\t\t\tif (label == 0)\n\t\t\t{\n\t\t\t\t// keine label-Kinder\n\t\t\t\t// => pool als nat\u00fcrlich markierten\n\t\t\t\t// Isotopomer-Pool initialisieren\n\t\t\t\tinput_pool_ = new data::InputPool(\n\t\t\t\t\tutf_id,\n\t\t\t\t\tipool->getName(),\n\t\t\t\t\tmask,\n\t\t\t\t\tdata::InputPool::ip_isotopomer\n\t\t\t\t\t);\n\t\t\t\tif (mask.size())\n                                {\n\t\t\t\t\t// Registrierung von eingesetzten Isotope zur Erm\u00f6glichung von\n                                        // multi-Isotopic Tracer MFA Simulation,\n                                        charptr_map<int> iso_map = ipool->getIsotopesCfg();\n                                        if(iso_map.size())\n                                        {\n                                            input_pool_->setIsotopeCfg(iso_map);\n                                            charptr_map<int>::const_iterator ii =iso_map.begin(); \n                                            std::stringstream iso_elem;\n                                            iso_elem<<\" for [\" <<ii->key;\n                                            ii++;\n                                            while(ii!=iso_map.end())\n                                            {\n                                               iso_elem<<\", \"<< ii->key;\n                                               ii++;\n                                            }\n                                            iso_elem<<\"]\";\n                                            fNOTICE(\"assuming natural abundance %s in pool \\\"%s\\\"\", iso_elem.str().c_str(),\n                                                    ipool->getName());\n                                        }\n                                        else\n                                            fNOTICE(\"assuming natural abundance 13C in pool \\\"%s\\\"\", \n                                                    ipool->getName());\n                                }\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfTHROW(XMLException,label,\n\t\t\t\t\t\"input pool %s: element node (label) expected\",\n\t\t\t\t\tipool->getName()\n\t\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tnnm = label->getAttributes();\n\t\tif (nnm == 0)\n\t\t\tfTHROW(XMLException,label,\"element node (label) lacks attributes.\");\n\t\t\n                cfgAttr = static_cast< DOMAttr* >(nnm->getNamedItem(fml_cfg));\n\t\tif (cfgAttr == 0)\n\t\t\tfTHROW(XMLException,label,\"element node (label) lacks cfg attribute.\");\n\t\tU2A utf_cfg(cfgAttr->getValue());\n\n\t\t// das cfg-Attribut mu\u00df einem speziellen Format entsprechen\n\t\tif (strlen(utf_cfg) != (size_t)natoms)\n\t\t{\n\t\t\tfTHROW(XMLException,label,\n\t\t\t\t\"label spec. of pool %s [%s] with wrong size; expected size %i.\",\n\t\t\t\t(char const *)utf_pool_name, (char const*)utf_cfg, natoms);\n\t\t}\n\t\tfor (int i=0; i<natoms; i++)\n\t\t{\n\t\t\tswitch (ip_type)\n\t\t\t{\n\t\t\tcase data::InputPool::ip_cumomer:\n\t\t\tcase data::InputPool::ip_emu:\n\t\t\t\tif (not (((char const*)utf_cfg)[i]=='x' or ((char const *)utf_cfg)[i]=='1'))\n\t\t\t\t{\n\t\t\t\t\tfTHROW(XMLException,label,\n\t\t\t\t\t\t\"illegal %s label spec. [%s] for pool %s\",\n\t\t\t\t\t\tip_type == data::InputPool::ip_emu\n\t\t\t\t\t\t\t? \"EMU\" : \"Cumomer\",\n\t\t\t\t\t\t(char const*)utf_cfg,\n\t\t\t\t\t\t(char const*)utf_pool_name\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase data::InputPool::ip_isotopomer:\n\t\t\t\tif (not (((char const*)utf_cfg)[i]=='0' or ((char const*)utf_cfg)[i]=='1'))\n\t\t\t\t{\n\t\t\t\t\tfTHROW(XMLException,label,\n\t\t\t\t\t\t\"illegal Isotopomer label spec. [%s] for pool %s\",\n\t\t\t\t\t\t(char const*)utf_cfg, (char const*)utf_pool_name\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n                \n\t\t// den Wert aus [0,1] bzw. die Werteliste parsen\n\t\tsize_t fvalues_len_exp;\n\t\tchar const * w;      \n               \n                Array< double > fvalues = parseLabel(static_cast< DOMElement * >(label)); \n               \n                // Substrate profile soll zun\u00e4chst nur f\u00fcr Isotopomer unterst\u00fctzen\n                if((ip_type!= data::InputPool::ip_isotopomer) && (profile_defined==true))\n                    fTHROW(XMLException,label,\n                            \"the used substrate profiling in pool \\\"%s\\\" is only supported for isotopomer type yet!\",\n                            (char const*)utf_pool_name);\n\t\tswitch (ip_type)\n\t\t{\n                    case data::InputPool::ip_cumomer:\n                    case data::InputPool::ip_isotopomer:\n                            if ((fvalues.size() != 1) and not profile_defined)\n                            {\n                                    fTHROW(XMLException,label,\n                                            \"illegal label spec. (expecting exactly \"\n                                            \"one fraction value).\"\n                                            );\n                            }\n                            break;\n                    case data::InputPool::ip_emu:\n                            for (w = (char const *)utf_cfg, fvalues_len_exp = 1;\n                                    *w != '\\0'; ++w)\n                            {\n                                    if (*w == '1') ++fvalues_len_exp;\n                            }\n                            if (fvalues.size() != fvalues_len_exp)\n                            {\n                                    fTHROW(XMLException,label,\n                                            \"invalid number of mass isotopomer fractions; \"\n                                            \"found %i, expected %i\",\n                                            int(fvalues.size()), int(fvalues_len_exp));\n                            }\n\t\t}\n\n\t\t// das purity-Attribut\n\t\tif ((purityAttr = static_cast< DOMAttr* >(nnm->getNamedItem(fml_purity))) != 0)\n\t\t{\n\t\t\tif (ip_type != data::InputPool::ip_isotopomer)\n\t\t\t{\t\n\t\t\t\tfTHROW(XMLException,label,\n\t\t\t\t\t\"the \\\"purity\\\" attribute is allowed only for \"\n\t\t\t\t\t\"isotopomer substrate specifications.\");\n\t\t\t}\n                        U2A utf_purity(purityAttr->getValue());\n                        charptr_array purityList= charptr_array::split(utf_purity,\" \");\n                        size_t i=0,size = purityList.size();\n                        if(size!= ipool->getNumOfActiveIsotope())\n                            fTHROW(XMLException,label,\n                                            \"label spec. of pool %s [%s]: illegal number of values \"\n                                            \"in attribute purity: %s\",\n                                            (char const *)utf_pool_name,\n                                            (char const *)utf_cfg,\n                                            (char const *)utf_purity\n                                            );\n                        purity= Array<double>(size);\n                        if(size==1)\n                        {\n                            if (not XMLElement::parseDouble(purityAttr->getValue(),purity[0])\n\t\t\t\tor (purity[0] < 0. or purity[0] > 1.))\n                            {\n                                    U2A utf_purity(purityAttr->getValue());\n                                    fTHROW(XMLException,label,\n                                            \"label spec. of pool %s [%s]: illegal value \"\n                                            \"for attribute purity: %s\",\n                                            (char const *)utf_pool_name,\n                                            (char const *)utf_cfg,\n                                            (char const *)utf_purity\n                                            );\n                            }\n                        }\n                        else if(size>1)\n                        {\n                            charptr_array::const_iterator pli;\n                            for (pli=purityList.begin(), i=0; pli!=purityList.end(); ++pli,++i)\n                            {\n                                purity[i]= atof(*pli);\n                                if ((purity[i] < 0. or purity[i] > 1.))\n                                {\n                                        U2A utf_purity(purityAttr->getValue());\n                                        fTHROW(XMLException,label,\n                                                \"label spec. of pool %s [%s]: illegal value \"\n                                                \"for attribute purity: %s\",\n                                                (char const *)utf_pool_name,\n                                                (char const *)utf_cfg,\n                                                (char const *)utf_purity\n                                                );\n                                }\n                                \n                            }\n                        }\n                        else\n                        {\n                            fTHROW(XMLException,label,\n\t\t\t\t\t\"error parsing the \\\"purity\\\" attribute.\");\n                        }\n\t\t}\n\t\telse \n                {\n                    purity=Array<double>(1);\n                    purity[0]= 2.; // Berechnung abschalten (default)\n                }\n\t\t\n\t\t// das cost-Attribut\n\t\tif ((costAttr = static_cast< DOMAttr* >(nnm->getNamedItem(fml_cost))) != 0)\n\t\t{\n\t\t\tif (ip_type != data::InputPool::ip_isotopomer)\n\t\t\t{\t\n\t\t\t\tfTHROW(XMLException,label,\n\t\t\t\t\t\"the \\\"cost\\\" attribute is allowed only for \"\n\t\t\t\t\t\"isotopomer substrate specifications.\");\n\t\t\t}\n\n\t\t\tif (not XMLElement::parseDouble(costAttr->getValue(),cost))\n\t\t\t{\n\t\t\t\tU2A utf_cost(costAttr->getValue());\n\t\t\t\tfTHROW(XMLException,label,\n\t\t\t\t\t\"label spec. of pool %s [%s]: illegal value \"\n\t\t\t\t\t\"for attribute cost: %s\",\n\t\t\t\t\t(char const *)utf_pool_name,\n\t\t\t\t\t(char const *)utf_cfg,\n\t\t\t\t\t(char const *)utf_cost\n\t\t\t\t        );\n\t\t\t}\n\t\t}\n\t\telse cost = 0.; // kostenlos\n\n\t\t// Konfiguration mit Fraction-Wert registrieren\n\t\tif (values.exists(utf_cfg))\n\t\t\tfTHROW(XMLException,label,\"duplicate specification of fraction %s\",\n\t\t\t\t(char const *)utf_cfg);\n\t\tvalues.insert(utf_cfg,fvalues);\n                purities.insert(utf_cfg,purity);\n\t\tcosts.insert(utf_cfg,cost);\n        if(profile_defined)\n        {\n            /** Check duplicate **/\n            if (profiles.exists(utf_cfg))\n                fTHROW(XMLException,label,\"duplicate profile specification of fraction %s in pool %s\",\n                       (char const *)utf_cfg, (char const *)utf_pool_name);\n\n            /* add profile conditions to parsed label values*/\n            std::list<double>::iterator pc;\n            for(pc=profile_conditions_.begin(); pc!=profile_conditions_.end();++pc)\n                input_profile_->addCondition(*pc);\n\n            /** Check profile consistency **/\n            fWARNING(\"#cond= %d  vs. #val= %d\", int(input_profile_->getConditions().size()), int(input_profile_->getValues().size()));\n            if(input_profile_->getConditions().size()!=input_profile_->getValues().size())\n                fTHROW(XMLException,label,\"The specified profile values of fraction %s and profile conditions are inconsistent with each other!\",\n                       (char const *)utf_cfg);\n\n            profiles.insert(utf_cfg,*input_profile_);\n        }\n                // Next Sep-Element\n\t\tlabel = XMLElement::nextNode(label);\n\t}\n\twhile (label != 0);\n                         \n\t// Konfigurationen der Fractions pr\u00fcfen und Maske konfigurieren\n\tcharptr_map< Array< double > >::const_iterator vi;\n\tfor (vi=values.begin(); vi!=values.end(); vi++)\n\t{\n            BitArray * vi_cfg = BitArray::parseBin(vi->key);\n            fASSERT(vi_cfg);\n            vi_cfg->resize(natoms,false);\n            mask = mask | (*vi_cfg);\n            delete vi_cfg;\n\t}\n        \n\t// InputPool-Objekt anlegen\n\tinput_pool_ = new data::InputPool(\n\t\t\tutf_id,\n\t\t\t(char const *)utf_pool_name,\n\t\t\tmask,\n\t\t\tip_type\n\t\t\t);\n        \n\t// Fractions eintragen\n\tfor (vi=values.begin(); vi!=values.end(); vi++)\n\t{\n\t\tBitArray * vi_cfg = BitArray::parseBin(vi->key);\n\t\tfASSERT(vi_cfg);\n\t\tvi_cfg->resize(natoms,false);\n\t\tswitch (ip_type)\n\t\t{\n\t\tcase data::InputPool::ip_isotopomer:\n\t\t\tinput_pool_->setIsotopomerValue(\n\t\t\t\t\t*vi_cfg,\n\t\t\t\t\tvi->value[0],\n\t\t\t\t\tpurities[vi->key],\n\t\t\t\t\tcosts[vi->key]\n\t\t\t\t\t);\n\t\t\tbreak;\n\t\tcase data::InputPool::ip_cumomer:\n\t\t\tinput_pool_->setCumomerValue(\n\t\t\t\t\t*vi_cfg,\n\t\t\t\t\tvi->value[0]\n\t\t\t\t\t);\n\t\t\tbreak;\n\t\tcase data::InputPool::ip_emu:\n\t\t\tinput_pool_->setEMUValue(\n\t\t\t\t\t*vi_cfg,\n\t\t\t\t\tvi->value\n\t\t\t\t\t);\n\t\t\tbreak;\n\t\t}\n\t\tdelete vi_cfg;\n\t}\n        \n\t// der geparste Pool wird bei der sp\u00e4ter folgenden Validierung ggfs.\n\t// von der Isotopomer-Form in die Cumomer-Form konvertiert\n        \n        // Profile eintragen\n        charptr_map< data::InputProfile >::const_iterator pi;\n\tfor (pi=profiles.begin(); pi!=profiles.end();pi++)\n\t{\n            BitArray * vi_cfg = BitArray::parseBin(pi->key);\n            fASSERT(vi_cfg);\n            vi_cfg->resize(natoms,false);\n                    input_pool_->setInputProfileValue(\n                                    *vi_cfg,\n                                    pi->value,\n                                    purities[pi->key],\n                                    costs[pi->key]\n                                    );\n            delete vi_cfg;\n\t}\n        \n        // Registrierung von Isotope-Konfigurationens zur Erm\u00f6glichung von\n        // multi-Isotopic Tracer MFA Simulation,\n        input_pool_->setIsotopeCfg(ipool->getIsotopesCfg());\n}\n\ndata::Pool * FluxMLInput::lookupPool(char const * pool_name)\n{\n\tcharptr_map< data::Pool* > * pmap = doc_->getPoolMap();\n\tdata::Pool ** pptr = pmap->findPtr(pool_name);\n\tif (pptr == 0)\n\t\treturn 0;\n\treturn *pptr;\n}\n\nArray< double > FluxMLInput::parseLabel(DOMElement * label)\n{   \n\tstruct val_list_t\n\t{\n\t\tdouble value;\n\t\tval_list_t * next;\n\t\t\n\t\tval_list_t() : value(0),next(0) { }\n\t\t~val_list_t() { delete next; }\n\t} head, * walk;        \n\tbool next_is_sep = false;\n        double sum;\n\tsize_t size = 0;\n\t\n        DOMNode * child = XMLElement::skipJunkNodes(label->getFirstChild());  \n        walk = &head;\n        while (child != 0)\n        {\n        \tif(profile_defined) // parse the profile and skip this while loop\n        \t{\n        \t\tparseProfile(child);\n        \t}\n            // standard labeling specification\n        \telse if (next_is_sep)\n        \t{\n        \t\tif (not XMLElement::match(child,fml_sep,fml_xmlns_uri))\n        \t\t\tfTHROW(XMLException,child,\"element node (sep) expected.\");\n        \t}\n        \telse\n        \t{\n        \t\tif (child->getNodeType() != DOMNode::TEXT_NODE)\n        \t\t\tfTHROW(XMLException,child,\"#PCDATA element expected.\");\n\n        \t\tif (not XMLElement::parseDouble(\n        \t\t\t\tstatic_cast< DOMText* >(child)->getData(),\n\t\t\t\t\t\twalk->value))\n        \t\t{\n        \t\t\tU2A utf_value(static_cast< DOMText* >(child)->getData());\n        \t\t\tfTHROW(XMLException,child,\n        \t\t\t\t\t\"error parsing fraction value: %s\",\n\t\t\t\t\t\t\t(char const*)utf_value\n        \t\t\t);\n        \t\t}\n\n        \t\tif (walk->value < 0. or walk->value > 1.)\n        \t\t{\n        \t\t\tU2A utf_value(static_cast< DOMText* >(child)->getData());\n        \t\t\tfTHROW(XMLException,child,\n        \t\t\t\t\t\"labeling fraction value %s is out of range [0,1]\",\n\t\t\t\t\t\t\t(char const*)utf_value\n        \t\t\t);\n        \t\t}\n\n        \t\t++size;\n        \t\twalk->next = new val_list_t;\n        \t\twalk = walk->next;\n        \t}\n        \tnext_is_sep = not next_is_sep;\n        \tchild = XMLElement::nextNode(child);\n        }\n\n        Array< double >values(size);\n        walk = &head;\n        sum = 0.;\n        for (size_t k=0; k<size; ++k)\n        {\n        \tvalues[k] = walk->value;\n        \tsum += walk->value;\n        \twalk = walk->next;\n        }\n        if (size > 1 and fabs(1.-sum) > 1e-5)\n        {\n        \tfTHROW(XMLException,label,\n        \t\t\t\"labeling fraction values are out of range [0,1]\");\n        }\n        return values;\n}\n\nvoid  FluxMLInput::parseProfile(DOMNode * profile)\n{\n\tinput_profile_ =  new data::InputProfile();\n\n\tif (XMLElement::match(profile,fml_math,fml_xmlns_mathml_uri))\n\t\tparseProfileMathML(profile);\n\telse if (XMLElement::match(profile,fml_textual,fml_xmlns_uri))\n\t\tparseProfileTextual(profile);\n\telse\n\t\tfTHROW(XMLException,profile,\n\t\t\t\t\"values in textual or MathML notation expected\");\n}\n\n\nvoid FluxMLInput::parseProfileMathML(\n\tDOMNode * node\n\t)\n{\n\tMathMLDocument * mathml;\n\tMathMLDeclare const * mathml_def;\n\tMathMLContentObject const * mathml_cont;\n\tMathMLExpression const * mathml_expr;\n\tstd::string mathml_cname;\n\tExprTree * expr;\n\n\t// den MathML-Parser anwerfen:\n\ttry\n\t{\n\t\tmathml = new MathMLDocument( node );\n\t}\n\tcatch (XMLException & e)\n\t{\n\t\t// MathML-Fehler in FluxML-Fehler konvertieren:\n\t\tfTHROW(XMLException,node,\"MathML-error in profile: %s\", e.toString());\n\t}\n\n\t// handelt es sich bei den Profile aus dem MathML-Dokument wirklich\n\t// um Profile?\n\tstd::list< MathMLDeclare const * > mml_constr = mathml->getDefinitionsByRegExp(\".*\");\n\t\n\t// Sinn\u00fcberpr\u00fcfung der Profile\n\tstd::list< MathMLDeclare const * >::iterator l_iter = mml_constr.begin();\n\twhile (l_iter != mml_constr.end())\n\t{\n\t\tmathml_def = *l_iter;\n\t\tmathml_cont = mathml_def->getValue();\n\t\tmathml_cname = mathml_def->getName();\n\n\t\t// Profile sind einfache MathMLExpressions:\n\t\tif (mathml_cont->getType() != MathMLContentObject::co_expression)\n\t\t\tfTHROW(XMLException,node,\"Profile %s: simple MathML-expression expected.\",\n\t\t\t\t\tmathml_cname.c_str());\n\n\t\tmathml_expr = static_cast<MathMLExpression const*>(mathml_cont);\n\t\texpr = mathml_expr->get();\n                // \u00dcberpr\u00fcfung der Variablennamen\n                charptr_array vnames = expr->getVarNames();\n                charptr_array::const_iterator vni;\n\n                for (vni = vnames.begin(); vni != vnames.end(); vni++)\n                {\n                    if((std::strcmp(*vni,\"t\") != 0) and (std::strcmp(*vni,\"otherwise\") != 0) )\n                            fTHROW(XMLException,node,\n                                    \"invalid variable name \\\"%s\\\" in \"\n                                    \"profile specification \\\"%s\\\" (%s)\",\n                                    *vni, input_profile_->getName(), expr->toString().c_str());\n                };\n                \n                input_profile_->addValue(expr);\n                l_iter++;\n\t}\n\n\t// MathML-Dokument freigeben:\n\tdelete mathml;\n}\n\nvoid FluxMLInput::parseProfileTextual(\n\tDOMNode * node\n\t)\n{\n\tDOMNode * child;\n\tchar const anon[] = \"anonymous\";\n\tif (not XMLElement::match(node,fml_textual,fml_xmlns_uri))\n\t\tfTHROW(XMLException,node,\"element node (textual) expected.\");\n\tchild = node->getFirstChild();\n\n\twhile (child != 0)\n\t{\n\t\t// unter Element textual ist alles erlaubt -- ausgewertet\n\t\t// werden nur TEXT_NODEs\n\t\twhile (child != 0 && child->getNodeType() != DOMNode::TEXT_NODE)\n\t\t\tchild = child->getNextSibling();\n\n\t\tif (child == 0)\n\t\t\tbreak;\n\n\t\tU2A cblock(static_cast< DOMText* >(child)->getData());\n\t\tcharptr_array expr_list = charptr_array::split((char const*)cblock,\";\");\n\t\tcharptr_array::const_iterator i;\n\n\t\tfor (i=expr_list.begin(); i!=expr_list.end(); i++)\n\t\t{\n\t\t\tExprTree * expr;\n\t\t\tint ci;\n\t\t\tchar * cname, * u;\n\t\t\tchar const * w;\n\t\t\tfor (w=*i; *w!='\\0'; w++)\n\t\t\t\tif (*w > 32) break;\n\t\t\tif (*w == '\\0')\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tcharptr_array nv_pair = charptr_array::split(*i,\":\");\n\t\t\tswitch (nv_pair.size())\n\t\t\t{\n\t\t\tcase 1:\n\t\t\t\tci = 0;\n\t\t\t\tcname = strdup_alloc(anon);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tci = 1;\n\t\t\t\tcname = strdup_alloc(nv_pair[0]);\n\t\t\t\tfor (u=cname; *u!='\\0'; u++)\n\t\t\t\t\tif (*u < 32) *u = ' ';\n\t\t\t\tstrtrim_inplace(cname);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tfTHROW(XMLException,child,\n\t\t\t\t\t\"parse error in profile (%s): \"\n\t\t\t\t\t\"confused by too many ':'\", *i);\n\t\t\t}\n\t\t\t\n\t\t\ttry\n\t\t\t{\n\t\t\t\texpr = ExprTree::parse(nv_pair[ci]);\n\t\t\t}\n\t\t\tcatch (ExprParserException &)\n\t\t\t{\n\t\t\t\tfTHROW(XMLException,child,\"parse error in profile %s(%s)\",\n\t\t\t\t\tcname, nv_pair[ci]);\n\t\t\t}\n\n                        // \u00dcberpr\u00fcfung der Variablennamen\n                        charptr_array vnames = expr->getVarNames();\n                        charptr_array::const_iterator vni;\n                        \n                        for (vni = vnames.begin(); vni != vnames.end(); vni++)\n                        {\n                            if((std::strcmp(*vni,\"t\") != 0) and (std::strcmp(*vni,\"otherwise\") != 0) )\n                                    fTHROW(XMLException,child,\n                                            \"invalid variable name \\\"%s\\\" in \"\n                                            \"profile specification \\\"%s\\\" (%s)\",\n                                            *vni, input_profile_->getName(), nv_pair[ci]);\n                        };\n                        \n                        input_profile_->addValue(expr);\n                        \n\t\t\tdelete[] cname;\n\t\t\tdelete expr;\n\t\t}\n\t\tchild = child->getNextSibling();\n\t}\n}\n} // namespace flux::xml\n} // namespace flux\n\n", "meta": {"hexsha": "edc7bbf930407b6cc8e59bab9b308a2f4a72e722", "size": 27527, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fluxml/FluxMLInput.cc", "max_stars_repo_name": "ANTS-ON/FluxML", "max_stars_repo_head_hexsha": "6feb6f1da638db450351acc664964f5659197bd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T18:01:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T11:26:52.000Z", "max_issues_repo_path": "fluxml/FluxMLInput.cc", "max_issues_repo_name": "ANTS-ON/FluxML", "max_issues_repo_head_hexsha": "6feb6f1da638db450351acc664964f5659197bd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T16:53:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T07:20:45.000Z", "max_forks_repo_path": "fluxml/FluxMLInput.cc", "max_forks_repo_name": "ANTS-ON/FluxML", "max_forks_repo_head_hexsha": "6feb6f1da638db450351acc664964f5659197bd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-07-12T10:26:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T09:46:44.000Z", "avg_line_length": 34.3229426434, "max_line_length": 145, "alphanum_fraction": 0.5261743016, "num_tokens": 6517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1663938507049659}}
{"text": "#include \"liver/fill_liver_volume.hpp\"\n#include \"liver/physical_vessel.hpp\"\n#include \"liver/physical_vessel_tree_updater.hpp\"\n#include \"messages/vessel_tree.pb.h\"\n#include \"shape/voxelized_shape.hpp\"\n#include \"utility/binary_tree.hpp\"\n#include \"utility/git_hash.hpp\"\n#include \"utility/options.hpp\"\n#include \"utility/protobuf_zip_ostream.hpp\"\n#include <boost/filesystem.hpp>\n#include <boost/optional.hpp>\n#include <boost/program_options.hpp>\n#include <fmt/ostream.h>\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl.h>\n#include <chrono>\n#include <iostream>\n#include <random>\n\nusing namespace jhmi;\nnamespace fs = boost::filesystem;\nnamespace po = boost::program_options;\n\nstruct node {\n  m3 pt;\n  binary_node_t<physical_vessel> n;\n};\nint main(int argc, char* argv[]) {\n  try {\n    GOOGLE_PROTOBUF_VERIFY_VERSION;\n    auto opts = options<data_directory_option, output_path_option>{};\n    if (!opts.parse(argc, argv))\n      return 1;\n\n\n    auto liver = voxelized_shape{opts.data_directory() / \"liver_extents.datz\", adjust::do_open};\n    auto full_start = std::chrono::high_resolution_clock::now();\n    auto tracts = tracts_in(liver) | ranges::view::transform([](m3 pt) { return node{pt, {}}; }) | ranges::to_vector;\n    auto num_levels = std::ceil(std::log2(tracts.size())) + 1;\n    auto levels = std::vector<std::vector<node>>(num_levels);\n    levels.back() = std::move(tracts);\n\n    auto vend = dbl3{45.447, 85.777, 54.023} * mm;\n    for (int lvl = 1; lvl < num_levels; ++lvl) {\n      auto& old_lvl = levels[num_levels - lvl];\n      auto& new_lvl = levels[num_levels - lvl - 1];\n      auto p = double(lvl) / (num_levels - 1);\n      new_lvl = old_lvl | ranges::view::chunk(2)\n        | ranges::view::transform([=](auto&& pts) {\n            auto ctr = ranges::accumulate(pts | ranges::view::transform(&node::pt), m3{}) / double(pts.size());\n            return node{ctr * (1. - p) + vend * p, {}};\n        }) | ranges::to_vector;\n    }\n    int idx = 0;\n    auto cell_pressure = Pa{25_mmHg};\n    auto proper_ha_flow = 400. * mL / minutes;\n    auto cell_flow = cubic_meters_per_second{proper_ha_flow / double(tracts.size())};\n    auto vessels = binary_tree<physical_vessel>{\n      physical_vessel{dbl3{50.143, 78.571, 47.562} * mm, vend, 10_um,\n          cell_id::invalid(), cell_flow, cell_pressure, vessel_id{++idx}}};\n    levels[0][0].n = vessels.root();\n    for (int r = 1; r < num_levels; ++r) {\n      for (int c = 0; c < levels[r].size(); ++c) {\n        auto& parent = levels[r - 1][c / 2];\n        auto& child = levels[r][c];\n        auto dv = physical_vessel{parent.n.value().end(), vend, 10_um,\n              cell_id::invalid(), cell_flow, cell_pressure, vessel_id{++idx}};\n        if (c % 2 == 0)\n          child.n = parent.n.set_left_child(dv);\n        else\n          child.n = parent.n.set_right_child(dv);\n      }\n    }\n    //Now, update flow, pressure, and radii.\n    auto vu = physical_vessel_tree_updater{vessels, 2.7, cell_pressure};\n    vu.normalize_all();\n\n    //tree is populated now, write to disk.\n    auto p = opts.output_path() / \"run_50_50\";\n    fs::create_directories(p);\n\n    protobuf_zip_ostream out_stream{p / \"fifty_tree.pbz\"};\n    jhmi_message::VesselTree vt;\n    RANGES_FOR(auto&& n, vessels | view::node_level_order) {\n      auto p = n.parent();\n      auto r = n.right_child();\n      auto l = n.left_child();\n      auto vtv = vt.add_vessels();\n      auto& v = n.value();\n      vtv->set_id(v.id().value());\n      vtv->set_parent((p ? p.value().id() : vessel_id::invalid()).value());\n      vtv->set_left(  (l ? l.value().id() : vessel_id::invalid()).value());\n      vtv->set_right( (r ? r.value().id() : vessel_id::invalid()).value());\n      vtv->set_radius(v.radius().value());\n      vtv->set_cell(v.cell().value());\n      vtv->set_flow(v.flow().value());\n      vtv->set_entry_pressure(v.entry_pressure().value());\n      vtv->set_exit_pressure(v.exit_pressure().value());\n      vtv->set_sx(v.start().x.value());\n      vtv->set_sy(v.start().y.value());\n      vtv->set_sz(v.start().z.value());\n      vtv->set_ex(v.end().x.value());\n      vtv->set_ey(v.end().y.value());\n      vtv->set_ez(v.end().z.value());\n      vtv->set_is_const(false);\n    }\n    if (!vt.SerializeToZeroCopyStream(out_stream.get()))\n      throw std::runtime_error(\"Failed to write 50/50 tree.\");\n\n    auto full_stop = std::chrono::high_resolution_clock::now();\n    fmt::print(\"Done in {} s!\\n\",\n      std::chrono::duration<float>(full_stop - full_start).count());\n    google::protobuf::ShutdownProtobufLibrary();\n  }\n  catch(std::exception const& e) {\n    fmt::print(\"Caught exception: {}\\n\", e.what());\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "0a3c3c1dfd9214f169bcd82c050773e60ead6634", "size": 4664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "artery_tree/build_50_50_tree.cpp", "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": "artery_tree/build_50_50_tree.cpp", "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": "artery_tree/build_50_50_tree.cpp", "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": 38.5454545455, "max_line_length": 117, "alphanum_fraction": 0.631432247, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.16639384403688348}}
{"text": "\ufeff// I hate this, might rewrite in future\n\n#include <iostream>\n#include <bass.h>\n#include <thread>\n#include <future>\n#include <string>\n#include <Windows.h>\n#include <random>\n#include <iomanip>\n#include <cmath>\n#include <boost/filesystem.hpp>\n#include \"clearscreen.h\"\n#include \"saveandload.h\"\n#include \"buydrugs.h\"\n#include \"selldrugs.h\"\n\n// global code yes i know plz dont kill me >.<\ntypedef int(__cdecl* MYPROC)(int);\nHINSTANCE hinstLib;\nMYPROC dlcMagic;\nBOOL fFreeResult, fRunTimeLinkSuccess = FALSE;\n\n// dll exporting lmao\n__declspec(dllexport) std::string name;\nbool globalexit = FALSE;\nbool musicon = TRUE;\nbool gameprestart = FALSE;\nbool gamestarted = FALSE;\n__declspec(dllexport) float money = 1000;\n__declspec(dllexport) int debt = 1000;\n__declspec(dllexport) int days = 0;\nint weedprice;\nint cocaineprice;\nint acidprice;\nint lsdprice;\nint condomprice;\nint raid;\n__declspec(dllexport) int weedpocket = 0;\n__declspec(dllexport) int cocainepocket = 0;\n__declspec(dllexport) int acidpocket = 0;\n__declspec(dllexport) int lsdpocket = 0;\n__declspec(dllexport) int condompocket = 0;\nint cheatused = 0;\nbool dlc = FALSE;\n__declspec(dllexport) int dlcPocket;\n__declspec(dllexport) int dlcPrice;\n__declspec(dllexport) std::string dlcDrugName;\n__declspec(dllexport) std::string dlcDrugLetter;\n__declspec(dllexport) std::random_device rd;\n__declspec(dllexport) std::mt19937 eng(rd());\n\nvoid dubstep()\n{\n\tBASS_Free();\n\tBASS_Init(-1, 48000, 0, 0, 0);\n\tHSTREAM stream = BASS_StreamCreateFile(FALSE, \"resource.bin\", 0, 0, BASS_SAMPLE_LOOP);\n\tBASS_ChannelPlay(stream, true);\n\twhile (true)\n\t\t\n\t\tif (globalexit == TRUE)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\telse if (musicon == TRUE)\n\t\t{\n\t\t\tDWORD playing = BASS_ChannelIsActive(stream);\n\t\t\tif (playing == BASS_ACTIVE_PAUSED)\n\t\t\t{\n\t\t\t\tBASS_ChannelPlay(stream, true);\n\t\t\t}\n\t\t\telse\n\t\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\t}\n\t\telse if (musicon == FALSE)\n\t\t{\n\t\t\tBASS_ChannelPause(stream);\n\t\t}\n\n\n}\n\nvoid makedrugprice()\n{\n\tstd::uniform_int_distribution<> weedpricerange(230, 700);\n\tweedprice = weedpricerange(eng);\n\t// std::cout << weedprice << '\\n';\n\n\tstd::uniform_int_distribution<> cocainepricerange(8000, 18000);\n\tcocaineprice = cocainepricerange(eng);\n\t// std::cout << cocaineprice << '\\n';\n\n\tstd::uniform_int_distribution<> acidpricerange(700, 3000);\n\tacidprice = acidpricerange(eng);\n\t// std::cout << acidprice << '\\n';\n\n\tstd::uniform_int_distribution<> lsdpricerange(2500, 3500);\n\tlsdprice = lsdpricerange(eng);\n\t// std::cout << lsdprice << '\\n';\n\n\tstd::uniform_int_distribution<> condompricerange(7, 50);\n\tcondomprice = condompricerange(eng);\n\t// std::cout << condomprice << '\\n';\n\n\tstd::uniform_int_distribution<> raidchance(1, 100);\n\traid = raidchance(eng);\n\n\tif (dlc == TRUE)\n\t{\n\t\tdlcMagic(8);\n\t}\n\tif (raid == 1 && days != 1)\n\t{\n\t\tweedprice = weedprice + 300;\n\t\tcocaineprice = cocaineprice + 3200;\n\t\tacidprice = acidprice + 600;\n\t\tlsdprice = lsdprice + 2000;\n\t\tif (dlc == TRUE)\n\t\t{\n\t\t\tdlcMagic(9);\n\t\t}\n\t\tstd::cout << \"damn, a police raid. prices have gone through the roof\" << '\\n';\n\t}\n\n\treturn;\n}\n\nvoid nextday()\n{\n\tclearscreen();\n\tif (debt < 0)\n\t{\n\t\tdebt = 0;\n\t}\n\tif (debt != 0)\n\t{\n\t\tdebt = debt*pow((1+0.01),days);\n\t}\n\tdays++;\n\tmakedrugprice();\n\treturn;\n}\n\nvoid payloan()\n{\n\tclearscreen();\n\tif (debt == 0)\n\t{\n\t\tstd::cout << \"you dont have a loan to pay!\" << '\\n';\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"how much of your loan do you want to pay? \\nyou owe $\" << debt << \" and you have $\" << money << '\\n';\n\t\tint loanpay;\n\t\tstd::cin >> loanpay;\n\t\tif (loanpay > money)\n\t\t{\n\t\t\tstd::cout << \"you dont have enough money\" << '\\n';\n\t\t\treturn;\n\t\t}\n\t\tif (loanpay <= money && loanpay <= debt)\n\t\t{\n\t\t\tstd::cout << \"you will have a debt of $\" << debt - loanpay << \" and you will have $\" << money - loanpay << \" in cash\" << '\\n' << '\\n';\n\t\t\tstd::cout << \"do you want to pay off your debt? y for yes, n for no\" << '\\n';\n\t\t\tchar loanpayconfirm;\n\t\t\tstd::cin >> loanpayconfirm;\n\t\t\tswitch (loanpayconfirm)\n\t\t\t{\n\t\t\tcase 'y':\n\t\t\t\tclearscreen();\n\t\t\t\tdebt = debt - loanpay;\n\t\t\t\tmoney = money - loanpay;\n\t\t\t\tbreak;\n\t\t\tcase 'n':\n\t\t\t\tclearscreen();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tclearscreen();\n\t\t\t\tstd::cout << \"invalid option\" <<'\\n';\n\t\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n}\n\nvoid sellmenu2()\n{\n\tstd::cout << \"okay, which drug would you like to sell? type in the drug initial then press enter.\" << '\\n';\n\tif (dlc == TRUE)\n\t{\n\t\tstd::cout << \"type d for the dlc menu (yeah it sucks idk how to do this better unless i rewrite the whole thing \\n\";\n\t}\n\tchar sellmenu2;\n\tstd::cin >> sellmenu2;\n\tswitch (sellmenu2)\n\t{\n\tcase 'w':\n\t\tsellweed();\n\t\tbreak;\n\tcase 'c':\n\t\tsellcocaine();\n\t\tbreak;\n\tcase 'a':\n\t\tsellacid();\n\t\tbreak;\n\tcase 'l':\n\t\tselllsd();\n\t\tbreak;\n\tcase 'C':\n\t\tsellcondoms();\n\t\tbreak;\n\tcase 'd':\n\t\tif (dlc == TRUE)\n\t\t{\n\t\t\tdlcMagic(6);\n\t\t\tbreak;\n\t\t}\n\t\telse {\n\t\t\tstd::cout << \"no dlc \\n\";\n\t\t\tbreak;\n\t\t}\n\tdefault:\n\t\tstd::cout << \"invalid drug name. make sure you type in the initial letter of the drug then press enter. cocaine is c and condoms are C\" << '\\n';\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\tbreak;\n\t}\n\treturn;\n}\n\nvoid sellmenu1()\n{\n\tclearscreen();\n\tbool selling = TRUE;\n\twhile (selling == TRUE)\n\t{\n\t\tstd::cout << \"welcome to the sell menu. you have $\" << money << '\\n' << '\\n';\n\t\tstd::cout << \"current drugs in your pockets\" << '\\n';\n\t\tstd::cout << \"weed: \" << weedpocket << '\\n';\n\t\tstd::cout << \"cocaine: \" << cocainepocket << '\\n';\n\t\tstd::cout << \"acid: \" << acidpocket << '\\n';\n\t\tstd::cout << \"lsd: \" << lsdpocket << '\\n';\n\t\tstd::cout << \"Condoms: \" << condompocket << '\\n';\n\t\tif (dlc == TRUE)\n\t\t{\n\t\t\tstd::cout << dlcDrugName << \": \" << dlcPocket << '\\n' << '\\n';\n\t\t}\n\t\telse std::cout << '\\n';\n\t\tstd::cout << \"current drug prices\" << '\\n';\n\t\tif (raid == 1)\n\t\t\tstd::cout << \"there has been a police raid, prices are increased\" << '\\n';\n\t\tstd::cout << \"weed: $\" << weedprice << '\\n';\n\t\tstd::cout << \"cocaine: $\" << cocaineprice << '\\n';\n\t\tstd::cout << \"acid: $\" << acidprice << '\\n';\n\t\tstd::cout << \"lsd: $\" << lsdprice << '\\n';\n\t\tstd::cout << \"Condoms: $\" << condomprice << '\\n';\n\t\tif (dlc == TRUE)\n\t\t{\n\t\t\tstd::cout << dlcDrugName << \": $\" << dlcPrice << '\\n' << '\\n';\n\t\t}\n\t\telse std::cout << '\\n';\n\t\tstd::cout <<\n\t\t\t\"s: sell some drugs \\n\"\n\t\t\t\"e: exit the buy menu \\n\" << '\\n';\n\t\tchar sellmenu1;\n\t\tstd::cin >> sellmenu1;\n\t\tswitch (sellmenu1)\n\t\t{\n\t\tcase 's':\n\t\t\tsellmenu2();\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\tselling = FALSE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tstd::cout << \"invalid option\" << '\\n';\n\t\t\tbreak;\n\t\t}\n\t}\n\tclearscreen();\n\treturn;\n}\n\nvoid buymenu2()\n{\n\tstd::cout << \"okay, which drug would you like to buy? type in the drug initial then press enter.\" << '\\n';\n\tif (dlc == TRUE)\n\t{\n\t\tstd::cout << \"type d for the dlc menu (yeah it sucks idk how to do this better unless i rewrite the whole thing \\n\";\n\t}\n\n\t\tchar buymenu2menu;\n\t\tstd::cin >> buymenu2menu;\n\t\tswitch (buymenu2menu)\n\t\t{\n\t\tcase 'w':\n\t\t\tbuyweed();\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tbuycocaine();\n\t\t\tbreak;\n\t\tcase 'a':\n\t\t\tbuyacid();\n\t\t\tbreak;\n\t\tcase 'l':\n\t\t\tbuylsd();\n\t\t\tbreak;\n\t\tcase 'C':\n\t\t\tbuycondoms();\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tif (dlc == TRUE)\n\t\t\t{\n\t\t\t\tdlcMagic(5);\n\t\t\t\tbreak;\n\t\t\t}\t\t\t\t\n\t\t\telse {\n\t\t\t\tstd::cout << \"no dlc \\n\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\tdefault:\n\t\t\tstd::cout << \"invalid drug name. make sure you type in the initial letter of the drug then press enter. cocaine is c and condoms are C\" << '\\n';\n\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\t\tbreak;\n\t\t}\n\t\n\n\treturn;\n}\n\nvoid buymenu1()\n{\n\tclearscreen();\n\tbool buying = TRUE;\n\twhile (buying == TRUE)\n\t{\n\t\tstd::cout << \"welcome to the buy menu. you have $\" << money << '\\n' << '\\n';\n\t\tstd::cout << \"current drugs in your pockets\" << '\\n';\n\t\tstd::cout << \"weed: \" << weedpocket << '\\n';\n\t\tstd::cout << \"cocaine: \" << cocainepocket << '\\n';\n\t\tstd::cout << \"acid: \" << acidpocket << '\\n';\n\t\tstd::cout << \"lsd: \" << lsdpocket << '\\n';\n\t\tstd::cout << \"Condoms: \" << condompocket << '\\n';\n\t\tif (dlc == TRUE)\n\t\t{\n\t\t\tstd::cout << dlcDrugName << \": \" << dlcPocket << '\\n' <<'\\n';\n\t\t}\n\t\telse std::cout << '\\n';\n\t\tstd::cout << \"current drug prices\" << '\\n';\n\t\tif (raid == 1)\n\t\t\tstd::cout << \"there has been a police raid, prices are increased\" << '\\n';\n\t\tstd::cout << \"weed: $\" << weedprice << '\\n';\n\t\tstd::cout << \"cocaine: $\" << cocaineprice << '\\n';\n\t\tstd::cout << \"acid: $\" << acidprice << '\\n';\n\t\tstd::cout << \"lsd: $\" << lsdprice << '\\n';\n\t\tstd::cout << \"Condoms: $\" << condomprice << '\\n';\n\t\tif (dlc == TRUE)\n\t\t{\n\t\t\tstd::cout << dlcDrugName << \": $\" << dlcPrice << '\\n' << '\\n';\n\t\t}\n\t\telse std::cout << '\\n';\n\t\tstd::cout <<\n\t\t\t\"b: buy some drugs \\n\"\n\t\t\t\"e: exit the buy menu \\n\" << '\\n';\n\t\tchar buymenu1;\n\t\tstd::cin >> buymenu1;\n\t\tswitch (buymenu1)\n\t\t{\n\t\tcase 'b':\n\t\t\tbuymenu2();\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\tbuying = FALSE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tstd::cout << \"invalid option\" << '\\n';\n\t\t\tbreak;\n\t\t}\n\t}\n\tclearscreen();\n\treturn;\n}\n\nint main(int argc, char** argv)\n{\n\t// DLC checking but im lazy to seperate it\n\t// i also don't know what this code does or how it works :^)\n\t// ms dev docs ftw\n\tif (argc == 2) {\n\t\tstd::string dlcFileName = argv[1];\n\t\tstd::wstring dlcFileNameWide(dlcFileName.begin(), dlcFileName.end());\n\t\tif (boost::filesystem::exists(dlcFileName))\n\t\t{\n\t\t\tLPCWSTR lpcwstrLMAO = dlcFileNameWide.c_str();\n\t\t\thinstLib = LoadLibrary(lpcwstrLMAO);\n\t\t\tif (hinstLib != NULL)\n\t\t\t{\n\t\t\t\tdlcMagic = (MYPROC)GetProcAddress(hinstLib, \"dlcMagic\"); // ?dlcMagic@@YAXH@Z\n\t\t\t\tif (dlcMagic == NULL)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"loading DLC failed, GetProcAddress error code: \\n\";\n\t\t\t\t\tstd::cout << GetLastError() << '\\n';\n\t\t\t\t}\n\t\t\t\tif (NULL != dlcMagic)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"we have successfully loaded function from DLL \\n\";\n\t\t\t\t\tdlc = TRUE;\n\t\t\t\t\tint pirate = dlcMagic(1);\n\t\t\t\t\tif (pirate == 202)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\telse if (pirate == 0)\n\t\t\t\t\t\tstd::cout << '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << \"what is your name?\" << '\\n';\n\tstd::getline(std::cin, name);\n\tclearscreen();\n\t\n\tauto music = std::async(std::launch::async, dubstep);\n\n\t// main menu\n\tif (days == 0)\n\t{\n\t\tbool validoption = FALSE;\n\t\twhile (validoption == FALSE)\n\t\t{\n\t\t\tstd::cout << \"hi \" << name << \" and welcome to cpp dope wars\" << '\\n';\n\t\t\tif (dlc == TRUE)\n\t\t\t{\n\t\t\t\tstd::cout << \"you have the following DLC loaded \\n\";\n\t\t\t\tdlcMagic(2);\n\t\t\t\tstd::cout << '\\n' << '\\n';\n\t\t\t}\n\t\t\telse std::cout << '\\n';\n\t\t\tstd::cout <<\n\t\t\t\t\"p: start new game \\n\"\n\t\t\t\t\"l: load game \\n\"\n\t\t\t\t\"e: exit program :( \\n\"\n\t\t\t\t\"m: toggle music \\n\"\n\t\t\t\t\"a: about \\n\"\n\t\t\t\t\"make your selection then press enter \\n\";\n\n\t\t\tchar mainmenu;\n\t\t\tstd::cin >> mainmenu;\n\n\t\t\tswitch (mainmenu)\n\t\t\t{\n\t\t\tcase 'p':\n\t\t\t\tstd::cout << \"starting game\";\n\t\t\t\tdays++;\n\t\t\t\tgameprestart = TRUE;\n\t\t\t\tvalidoption = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase 'e':\n\t\t\t\tglobalexit = TRUE;\n\t\t\t\tvalidoption = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tif (musicon == TRUE)\n\t\t\t\t{\n\t\t\t\t\tmusicon = FALSE;\n\t\t\t\t\tclearscreen();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (musicon == FALSE)\n\t\t\t\t{\n\t\t\t\t\tmusicon = TRUE;\n\t\t\t\t\tclearscreen();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tcase 'l':\n\t\t\t\tstd::cout << \"attempting to load save file \\n\";\n\t\t\t\tif (dlc == TRUE)\n\t\t\t\t{\n\t\t\t\t\tif (dlcMagic(3) == 201)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"exiting.... \\n\";\n\t\t\t\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\t\t\t\t\tglobalexit = TRUE;\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\telse if (dlcMagic(3) == 200)\n\t\t\t\t\t\tstd::cout << ' ';\n\t\t\t\t}\n\t\t\t\telse loadfromfile();\t\t\t\n\t\t\t\tgameprestart = TRUE;\n\t\t\t\tvalidoption = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\t\tclearscreen();\n\t\t\t\tstd::cout << \"help is on the way soon tm (mfw its been like 1 year and still no help)\" << '\\n';\n\t\t\t\tbreak;\n\t\t\tcase 'a':\n\t\t\t\tstd::cout << \"version 7, dlc aware with dlc compatible logic\" << '\\n';\n\t\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\t\t\tclearscreen();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tclearscreen();\n\t\t\t\tstd::cout << \"you did not select any of the listed options, please try again\" << '\\n' << '\\n';\n\t\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// initialise game\n\tif (gameprestart == TRUE)\n\t{\n\t\tclearscreen();\n\t\tmakedrugprice();\n\t\tgamestarted = TRUE;\n\t}\n\n\t// game menu\n\twhile (gamestarted == TRUE)\n\t{\n\t\t{\n\t\t\tstd::cout << \"Welcome to day \" << days << \" of CPP Dope Wars. You owe $\" << debt << \" to the loan shark. You currently have $\" << money << '\\n';\n\t\t\tstd::cout <<\n\t\t\t\t\"b: buy menu \\n\"\n\t\t\t\t\"v: sell menu \\n\"\n\t\t\t\t\"p: pay off your loan (if you have one) \\n\"\n\t\t\t\t\"n: next day \\n\"\n\t\t\t\t\"m: toggle music \\n\"\n\t\t\t\t\"e: exit :( \\n\"\n\t\t\t\t\"l: load game \\n\"\n\t\t\t\t\"s: save game \\n\"\n\t\t\t\t\"make your selection then press enter \\n\";\n\t\t\tchar gamemenu;\n\t\t\tstd::cin >> gamemenu;\n\n\t\t\tswitch (gamemenu)\n\t\t\t{\n\t\t\tcase 'b':\n\t\t\t\tbuymenu1();\n\t\t\t\tbreak;\n\t\t\tcase 'v':\n\t\t\t\tsellmenu1();\n\t\t\t\tbreak;\n\t\t\tcase 'n':\n\t\t\t\tnextday();\n\t\t\t\tbreak;\n\t\t\tcase 'p':\n\t\t\t\tpayloan();\n\t\t\t\tbreak;\n\t\t\tcase 'e':\n\t\t\t\tglobalexit = TRUE;\n\t\t\t\tgamestarted = FALSE;\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tif (musicon == TRUE)\n\t\t\t\t{\n\t\t\t\t\tmusicon = FALSE;\n\t\t\t\t\tclearscreen();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (musicon == FALSE)\n\t\t\t\t{\n\t\t\t\t\tmusicon = TRUE;\n\t\t\t\t\tclearscreen();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tcase 'l':\n\t\t\t\tstd::cout << \"attempting to load save file \\n\";\n\t\t\t\tif (dlc == TRUE)\n\t\t\t\t{\n\t\t\t\t\tif (dlcMagic(3) == 201)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"exiting.... \\n\";\n\t\t\t\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\t\t\t\t\tglobalexit = TRUE;\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\telse if (dlcMagic(3) == 200)\n\t\t\t\t\t\tstd::cout << ' ';\n\t\t\t\t}\n\t\t\t\telse loadfromfile();\n\t\t\t\tclearscreen();\n\t\t\t\tbreak;\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tstd::cout << \"saving game progress to file...\" << '\\n';\n\t\t\t\tif (dlc == TRUE)\n\t\t\t\t{\n\t\t\t\t\tdlcMagic(4);\n\t\t\t\t}\n\t\t\t\telse savetofile();\t\t\t\t\n\t\t\t\tclearscreen();\n\t\t\t\tbreak;\n\t\t\tcase '=':\n\t\t\t\tif (cheatused < 4)\n\t\t\t\t{\n\t\t\t\t\tcheatused = cheatused + 1;\n\t\t\t\t\tmoney = money + 1000;\n\t\t\t\t\tclearscreen();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (cheatused > 4)\n\t\t\t\t{\n\t\t\t\t\tclearscreen();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tclearscreen();\n\t\t\t\tstd::cout << \"you did not select any of the listed options, please try again\" << '\\n';\n\t\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(2));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfFreeResult = FreeLibrary(hinstLib);\n\treturn 0;\n}\n", "meta": {"hexsha": "206aa5800b31b280da0a1bc845387a96e098bede", "size": 14053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "penguin2233/cpp-dopewars", "max_stars_repo_head_hexsha": "886ac7d0d3c723e078bea433953419589c4f4712", "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": "penguin2233/cpp-dopewars", "max_issues_repo_head_hexsha": "886ac7d0d3c723e078bea433953419589c4f4712", "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": "penguin2233/cpp-dopewars", "max_forks_repo_head_hexsha": "886ac7d0d3c723e078bea433953419589c4f4712", "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.4848, "max_line_length": 147, "alphanum_fraction": 0.5761047463, "num_tokens": 4542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.16631090683231908}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Ion Gaztanaga 2005-2013. 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// See http://www.boost.org/libs/container for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_IMPL_HPP\n#define BOOST_CONTAINER_DETAIL_NODE_POOL_IMPL_HPP\n\n#ifndef BOOST_CONFIG_HPP\n#  include <boost/config.hpp>\n#endif\n\n#if defined(BOOST_HAS_PRAGMA_ONCE)\n#  pragma once\n#endif\n\n#include <boost/container/detail/config_begin.hpp>\n#include <boost/container/detail/workaround.hpp>\n#include <boost/container/container_fwd.hpp>\n\n#include <boost/container/detail/math_functions.hpp>\n#include <boost/container/detail/mpl.hpp>\n#include <boost/container/detail/pool_common.hpp>\n#include <boost/container/detail/to_raw_pointer.hpp>\n#include <boost/container/detail/type_traits.hpp>\n\n#include <boost/intrusive/pointer_traits.hpp>\n#include <boost/intrusive/set.hpp>\n#include <boost/intrusive/slist.hpp>\n\n#include <boost/core/no_exceptions_support.hpp>\n#include <boost/assert.hpp>\n#include <cstddef>\n\nnamespace boost {\nnamespace container {\nnamespace container_detail {\n\ntemplate<class SegmentManagerBase>\nclass private_node_pool_impl\n{\n   //Non-copyable\n   private_node_pool_impl();\n   private_node_pool_impl(const private_node_pool_impl &);\n   private_node_pool_impl &operator=(const private_node_pool_impl &);\n\n   //A node object will hold node_t when it's not allocated\n   public:\n   typedef typename SegmentManagerBase::void_pointer              void_pointer;\n   typedef typename node_slist<void_pointer>::slist_hook_t        slist_hook_t;\n   typedef typename node_slist<void_pointer>::node_t              node_t;\n   typedef typename node_slist<void_pointer>::node_slist_t        free_nodes_t;\n   typedef typename SegmentManagerBase::multiallocation_chain     multiallocation_chain;\n   typedef typename SegmentManagerBase::size_type                 size_type;\n\n   private:\n   typedef typename bi::make_slist\n      < node_t, bi::base_hook<slist_hook_t>\n      , bi::linear<true>\n      , bi::constant_time_size<false> >::type      blockslist_t;\n\n   static size_type get_rounded_size(size_type orig_size, size_type round_to)\n   {  return ((orig_size-1)/round_to+1)*round_to;  }\n\n   public:\n\n   //!Segment manager typedef\n   typedef SegmentManagerBase segment_manager_base_type;\n\n   //!Constructor from a segment manager. Never throws\n   private_node_pool_impl(segment_manager_base_type *segment_mngr_base, size_type node_size, size_type nodes_per_block)\n   :  m_nodes_per_block(nodes_per_block)\n   ,  m_real_node_size(lcm(node_size, size_type(alignment_of<node_t>::value)))\n      //General purpose allocator\n   ,  mp_segment_mngr_base(segment_mngr_base)\n   ,  m_blocklist()\n   ,  m_freelist()\n      //Debug node count\n   ,  m_allocated(0)\n   {}\n\n   //!Destructor. Deallocates all allocated blocks. Never throws\n   ~private_node_pool_impl()\n   {  this->purge_blocks();  }\n\n   size_type get_real_num_node() const\n   {  return m_nodes_per_block; }\n\n   //!Returns the segment manager. Never throws\n   segment_manager_base_type* get_segment_manager_base()const\n   {  return container_detail::to_raw_pointer(mp_segment_mngr_base);  }\n\n   void *allocate_node()\n   {  return this->priv_alloc_node();  }\n\n   //!Deallocates an array pointed by ptr. Never throws\n   void deallocate_node(void *ptr)\n   {  this->priv_dealloc_node(ptr); }\n\n   //!Allocates a singly linked list of n nodes ending in null pointer.\n   void allocate_nodes(const size_type n, multiallocation_chain &chain)\n   {\n      //Preallocate all needed blocks to fulfill the request\n      size_type cur_nodes = m_freelist.size();\n      if(cur_nodes < n){\n         this->priv_alloc_block(((n - cur_nodes) - 1)/m_nodes_per_block + 1);\n      }\n\n      //We just iterate the needed nodes to get the last we'll erase\n      typedef typename free_nodes_t::iterator free_iterator;\n      free_iterator before_last_new_it = m_freelist.before_begin();\n      for(size_type j = 0; j != n; ++j){\n         ++before_last_new_it;\n      }\n\n      //Cache the first node of the allocated range before erasing\n      free_iterator first_node(m_freelist.begin());\n      free_iterator last_node (before_last_new_it);\n\n      //Erase the range. Since we already have the distance, this is O(1)\n      m_freelist.erase_after( m_freelist.before_begin()\n                            , ++free_iterator(before_last_new_it)\n                            , n);\n\n      //Now take the last erased node and just splice it in the end\n      //of the intrusive list that will be traversed by the multialloc iterator.\n      chain.incorporate_after(chain.before_begin(), &*first_node, &*last_node, n);\n      m_allocated += n;\n   }\n\n   void deallocate_nodes(multiallocation_chain &chain)\n   {\n      typedef typename multiallocation_chain::iterator iterator;\n      iterator it(chain.begin()), itend(chain.end());\n      while(it != itend){\n         void *pElem = &*it;\n         ++it;\n         this->priv_dealloc_node(pElem);\n      }\n   }\n\n   //!Deallocates all the free blocks of memory. Never throws\n   void deallocate_free_blocks()\n   {\n      typedef typename free_nodes_t::iterator nodelist_iterator;\n      typename blockslist_t::iterator bit(m_blocklist.before_begin()),\n                                      it(m_blocklist.begin()),\n                                      itend(m_blocklist.end());\n      free_nodes_t backup_list;\n      nodelist_iterator backup_list_last = backup_list.before_begin();\n\n      //Execute the algorithm and get an iterator to the last value\n      size_type blocksize = (get_rounded_size)\n         (m_real_node_size*m_nodes_per_block, (size_type) alignment_of<node_t>::value);\n\n      while(it != itend){\n         //Collect all the nodes from the block pointed by it\n         //and push them in the list\n         free_nodes_t free_nodes;\n         nodelist_iterator last_it = free_nodes.before_begin();\n         const void *addr = get_block_from_hook(&*it, blocksize);\n\n         m_freelist.remove_and_dispose_if\n            (is_between(addr, blocksize), push_in_list(free_nodes, last_it));\n\n         //If the number of nodes is equal to m_nodes_per_block\n         //this means that the block can be deallocated\n         if(free_nodes.size() == m_nodes_per_block){\n            //Unlink the nodes\n            free_nodes.clear();\n            it = m_blocklist.erase_after(bit);\n            mp_segment_mngr_base->deallocate((void*)addr);\n         }\n         //Otherwise, insert them in the backup list, since the\n         //next \"remove_if\" does not need to check them again.\n         else{\n            //Assign the iterator to the last value if necessary\n            if(backup_list.empty() && !m_freelist.empty()){\n               backup_list_last = last_it;\n            }\n            //Transfer nodes. This is constant time.\n            backup_list.splice_after\n               ( backup_list.before_begin()\n               , free_nodes\n               , free_nodes.before_begin()\n               , last_it\n               , free_nodes.size());\n            bit = it;\n            ++it;\n         }\n      }\n      //We should have removed all the nodes from the free list\n      BOOST_ASSERT(m_freelist.empty());\n\n      //Now pass all the node to the free list again\n      m_freelist.splice_after\n         ( m_freelist.before_begin()\n         , backup_list\n         , backup_list.before_begin()\n         , backup_list_last\n         , backup_list.size());\n   }\n\n   size_type num_free_nodes()\n   {  return m_freelist.size();  }\n\n   //!Deallocates all used memory. Precondition: all nodes allocated from this pool should\n   //!already be deallocated. Otherwise, undefined behaviour. Never throws\n   void purge_blocks()\n   {\n      //check for memory leaks\n      BOOST_ASSERT(m_allocated==0);\n      size_type blocksize = (get_rounded_size)\n         (m_real_node_size*m_nodes_per_block, (size_type)alignment_of<node_t>::value);\n\n      //We iterate though the NodeBlock list to free the memory\n      while(!m_blocklist.empty()){\n         void *addr = get_block_from_hook(&m_blocklist.front(), blocksize);\n         m_blocklist.pop_front();\n         mp_segment_mngr_base->deallocate((void*)addr);\n      }\n      //Just clear free node list\n      m_freelist.clear();\n   }\n\n   void swap(private_node_pool_impl &other)\n   {\n      BOOST_ASSERT(m_nodes_per_block == other.m_nodes_per_block);\n      BOOST_ASSERT(m_real_node_size == other.m_real_node_size);\n      std::swap(mp_segment_mngr_base, other.mp_segment_mngr_base);\n      m_blocklist.swap(other.m_blocklist);\n      m_freelist.swap(other.m_freelist);\n      std::swap(m_allocated, other.m_allocated);\n   }\n\n   private:\n\n   struct push_in_list\n   {\n      push_in_list(free_nodes_t &l, typename free_nodes_t::iterator &it)\n         :  slist_(l), last_it_(it)\n      {}\n\n      void operator()(typename free_nodes_t::pointer p) const\n      {\n         slist_.push_front(*p);\n         if(slist_.size() == 1){ //Cache last element\n            ++last_it_ = slist_.begin();\n         }\n      }\n\n      private:\n      free_nodes_t &slist_;\n      typename free_nodes_t::iterator &last_it_;\n   };\n\n   struct is_between\n   {\n      typedef typename free_nodes_t::value_type argument_type;\n      typedef bool                              result_type;\n\n      is_between(const void *addr, std::size_t size)\n         :  beg_(static_cast<const char *>(addr)), end_(beg_+size)\n      {}\n\n      bool operator()(typename free_nodes_t::const_reference v) const\n      {\n         return (beg_ <= reinterpret_cast<const char *>(&v) &&\n                 end_ >  reinterpret_cast<const char *>(&v));\n      }\n      private:\n      const char *      beg_;\n      const char *      end_;\n   };\n\n   //!Allocates one node, using single segregated storage algorithm.\n   //!Never throws\n   node_t *priv_alloc_node()\n   {\n      //If there are no free nodes we allocate a new block\n      if (m_freelist.empty())\n         this->priv_alloc_block(1);\n      //We take the first free node\n      node_t *n = (node_t*)&m_freelist.front();\n      m_freelist.pop_front();\n      ++m_allocated;\n      return n;\n   }\n\n   //!Deallocates one node, using single segregated storage algorithm.\n   //!Never throws\n   void priv_dealloc_node(void *pElem)\n   {\n      //We put the node at the beginning of the free node list\n      node_t * to_deallocate = static_cast<node_t*>(pElem);\n      m_freelist.push_front(*to_deallocate);\n      BOOST_ASSERT(m_allocated>0);\n      --m_allocated;\n   }\n\n   //!Allocates several blocks of nodes. Can throw\n   void priv_alloc_block(size_type num_blocks)\n   {\n      BOOST_ASSERT(num_blocks > 0);\n      size_type blocksize =\n         (get_rounded_size)(m_real_node_size*m_nodes_per_block, (size_type)alignment_of<node_t>::value);\n\n      BOOST_TRY{\n         for(size_type i = 0; i != num_blocks; ++i){\n            //We allocate a new NodeBlock and put it as first\n            //element in the free Node list\n            char *pNode = reinterpret_cast<char*>\n               (mp_segment_mngr_base->allocate(blocksize + sizeof(node_t)));\n            char *pBlock = pNode;\n            m_blocklist.push_front(get_block_hook(pBlock, blocksize));\n\n            //We initialize all Nodes in Node Block to insert\n            //them in the free Node list\n            for(size_type j = 0; j < m_nodes_per_block; ++j, pNode += m_real_node_size){\n               m_freelist.push_front(*new (pNode) node_t);\n            }\n         }\n      }\n      BOOST_CATCH(...){\n         //to-do: if possible, an efficient way to deallocate allocated blocks\n         BOOST_RETHROW\n      }\n      BOOST_CATCH_END\n   }\n\n   //!Deprecated, use deallocate_free_blocks\n   void deallocate_free_chunks()\n   {  this->deallocate_free_blocks(); }\n\n   //!Deprecated, use purge_blocks\n   void purge_chunks()\n   {  this->purge_blocks(); }\n\n   private:\n   //!Returns a reference to the block hook placed in the end of the block\n   static node_t & get_block_hook (void *block, size_type blocksize)\n   {\n      return *reinterpret_cast<node_t*>(reinterpret_cast<char*>(block) + blocksize);\n   }\n\n   //!Returns the starting address of the block reference to the block hook placed in the end of the block\n   void *get_block_from_hook (node_t *hook, size_type blocksize)\n   {\n      return (reinterpret_cast<char*>(hook) - blocksize);\n   }\n\n   private:\n   typedef typename boost::intrusive::pointer_traits\n      <void_pointer>::template rebind_pointer<segment_manager_base_type>::type   segment_mngr_base_ptr_t;\n\n   const size_type m_nodes_per_block;\n   const size_type m_real_node_size;\n   segment_mngr_base_ptr_t mp_segment_mngr_base;   //Segment manager\n   blockslist_t      m_blocklist;      //Intrusive container of blocks\n   free_nodes_t      m_freelist;       //Intrusive container of free nods\n   size_type       m_allocated;      //Used nodes for debugging\n};\n\n\n}  //namespace container_detail {\n}  //namespace container {\n}  //namespace boost {\n\n#include <boost/container/detail/config_end.hpp>\n\n#endif   //#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP\n", "meta": {"hexsha": "4febf19e905695f62f26c4155384c1659923c936", "size": 13204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/container/detail/node_pool_impl.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/container/detail/node_pool_impl.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/container/detail/node_pool_impl.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 35.1170212766, "max_line_length": 119, "alphanum_fraction": 0.6604059376, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.16625208307182446}}
{"text": "#include <ros/ros.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <boost/algorithm/string.hpp>\n#include <tf/transform_datatypes.h>\n#include <math.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <sys/ioctl.h>\n#include <fcntl.h>\n#include <termios.h>\n#include <unistd.h>\n#include <time.h>\n#include \"kalman-Ndof.hpp\"\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <tms_msg_db/TmsdbGetData.h>\n#include <tms_msg_db/TmsdbStamped.h>\n#include <tms_msg_db/Tmsdb.h>\n#include <visualization_msgs/Marker.h>\n\n#define DEVNAME \"/dev/arduino\"\n#define BAUDRATE B115200\n#define BUFSIZE 256\n\n#define PI 3.14159265\n#define DEG2RAD(x) ((x)*(PI/180))\n\nusing namespace std;\nusing namespace boost;\n\nKalman *kalman;\n\n#define BED_X1 9.33\n#define BED_X2 10.7\n#define BED_Y1 2.3\n#define BED_Y2 3.1\n\nint main(int argc, char **argv)\n{\n  ros::init(argc,argv,\"tms_ss_pozyx\");\n  ros::NodeHandle n;\n  ros::Publisher db_pub = n.advertise<tms_msg_db::TmsdbStamped> (\"tms_db_data\",1000);\n  ros::Publisher pos_pub = n.advertise<visualization_msgs::Marker> (\"pozyx\",1000);\n  std::string frame_id(\"/world\");\n\n\tint fd = open(DEVNAME, O_RDWR | O_NOCTTY);\n\tif(fd<0){\n\t\tROS_ERROR(\"cannot open device\");\n\t\treturn 0;\n\t}\n\tROS_INFO(\"device opened\");\n\n\tstruct termios tio;\n\tmemset(&tio,0,sizeof(tio));\n\ttio.c_cflag = CS8 | CLOCAL | CREAD;\n\ttio.c_cc[VTIME]=0;\n\ttio.c_lflag=ICANON;\n\ttio.c_iflag=IGNPAR | ICRNL;\n\tcfsetspeed(&tio,BAUDRATE);\n\ttcsetattr(fd,TCSANOW,&tio);\n\n  kalman = new Kalman(6,6,3);\n  ros::Time last_time,now;\n  now = ros::Time::now();\n\n\tint len;\n\tchar buf[BUFSIZE];\n  double X,Y,Z,qx,qy,qz,qw;\n  double preX,preY,preZ,preqx,preqy,preqz,preqw;\n  double kfX=0;\n  double kfY=0;\n  double kfZ=0;\n\twhile(ros::ok()){\n\t\tmemset(&buf,0,sizeof(buf));\n\t\tlen = read(fd,buf,BUFSIZE);\n\t\tif(len==0)\n\t\t\tcontinue;\n\t  std::string data(buf);\n\t  std::vector<std::string> v_data;\n\t  v_data.clear();\n    boost::split(v_data,data,boost::is_any_of(\",\"));\n    if(v_data.size()==8){\n      preX=X;\n      preY=Y;\n      preZ=Z;\n      preqx=qx;\n      preqy=qy;\n      preqz=qz;\n      preqw=qw;\n      int id = atoi(v_data.at(0).c_str());\n      X = 0.001*atoi(v_data.at(1).c_str());\n      Y = 0.001*atoi(v_data.at(2).c_str());\n      Z = 0.001*atoi(v_data.at(3).c_str());\n      qx = atof(v_data.at(4).c_str());\n      qy = atof(v_data.at(5).c_str());\n      qz = atof(v_data.at(6).c_str());\n      qw = atof(v_data.at(7).c_str());\n      if(qx==0&&qy==0&&qz==0&&qw==0){\n        qx=preqx;\n        qy=preqy;\n        qz=preqz;\n        qw=preqw;\n      }\n\n      ROS_INFO(\"%d,%f,%f,%f,%f,%f,%f,%f\",id,X,Y,Z,qx,qy,qz,qw);\n\n      tf::Quaternion q0(qx,qy,qz,qw);\n      tf::Matrix3x3 m(q0);\n      double roll,pitch,yaw;\n      m.getRPY(roll,pitch,yaw);\n      yaw-=1.144898;\n      double roll2,pitch2,yaw2;\n      roll2=-pitch;\n      pitch2=roll-PI/2;\n      yaw2=yaw-PI/2;\n\n      //kalman_filter\n      last_time = now;\n      now = ros::Time::now();\n      double delta_t = (now.sec+now.nsec*0.000000001)-(last_time.sec+last_time.nsec*0.000000001);\n      double velX = (X-preX)/delta_t;\n      double velY = (Y-preY)/delta_t;\n      double velZ = (Z-preZ)/delta_t;\n\n      static int count = 0;\n\n      if(kalman==NULL)return 0;\n      if(count==0){\n        count++;\n        continue;\n      }else if(count==1){\n        // \u521d\u671f\u5316 (\u30b7\u30b9\u30c6\u30e0\u96d1\u97f3\uff0c\u89b3\u6e2c\u96d1\u97f3\uff0c\u7a4d\u5206\u6642\u9593)\n        kalman->init(0.15,0.7,0.08);\n        double C[6][6];\n        memset(C,0,sizeof(C));\n        C[0][0]=C[1][1]=C[2][2]=1;\n        kalman->setC((double *)&C);\n        kalman->setX(0,X);\n        kalman->setX(1,Y);\n        kalman->setX(2,Z);\n        kalman->setX(3,velX);\n        kalman->setX(4,velY);\n        kalman->setX(5,velZ);\n        count++;\n      }\n\n      double A[3][6];\n      memset(A,0,sizeof(A));\n      A[0][0]=A[1][1]=A[2][2]=1;\n      A[0][3]=A[1][4]=A[2][5]=delta_t;\n      double obs[6]={X,Y,Z,velX,velY,velZ};\n      double input[3]={0,0,0};\n\n      kalman->update(obs,input);\n\n      kfX=kalman->getX(0);\n      kfY=kalman->getX(1);\n      kfZ=kalman->getX(2);\n\n      ROS_INFO(\"kfX=%f kfY=%f kfZ=%f\",kfX,kfY,kfZ);\n\n      //----------------\n\n      ros::Time db_time = ros::Time::now() + ros::Duration(9*60*60);\n      tms_msg_db::TmsdbStamped db_msg;\n\n      db_msg.header.frame_id = frame_id;\n      db_msg.header.stamp = db_time;\n      db_msg.tmsdb.clear();\n      tms_msg_db::Tmsdb tmpData;\n\n      tmpData.time = boost::posix_time::to_iso_extended_string(db_time.toBoost());\n      tmpData.name = \"person_pozyx1\";\n      tmpData.id = 1100;\n      tmpData.sensor = 0;\n      tmpData.state = 1;\n      tmpData.x = kfX;\n      tmpData.y = kfY;\n      tmpData.rr = roll2;\n      tmpData.rp = pitch2;\n      tmpData.ry = yaw2;\n      double height = 1.1*cos(pitch2)*cos(roll2);\n      if(height<0.1) height = 0.1;\n\n      if(kfX > BED_X1 && kfX < BED_X2 && kfY > BED_Y1 && kfY < BED_Y2){\n        tmpData.place = 6017;\n        tmpData.z = height+0.3;\n      }else{\n        tmpData.place = 5001;\n        tmpData.z = height;\n      }\n\n      db_msg.tmsdb.push_back(tmpData);\n      db_pub.publish(db_msg);\n\n      visualization_msgs::Marker msg;\n      msg.header.frame_id = \"world_link\";\n      msg.header.stamp = ros::Time();\n      msg.type = visualization_msgs::Marker::SPHERE;\n      msg.pose.position.x = kfX;\n      msg.pose.position.y = kfY;\n      msg.pose.position.z = kfZ;\n      msg.pose.orientation.x = qx;\n      msg.pose.orientation.y = qy;\n      msg.pose.orientation.z = qz;\n      msg.pose.orientation.w = qw;\n      msg.scale.x = 0.5;\n      msg.scale.y = 0.5;\n      msg.scale.z = 0.5;\n      msg.color.a = 0.5;\n      msg.color.r = 1.0;\n      pos_pub.publish(msg);\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "14e3943f990e135dbf6f7694e6ccd3f871354cc2", "size": 5618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tms_ss/tms_ss_pozyx/src/main.cpp", "max_stars_repo_name": "robotpilot/ros_tms", "max_stars_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T06:58:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T07:49:37.000Z", "max_issues_repo_path": "tms_ss/tms_ss_pozyx/src/main.cpp", "max_issues_repo_name": "robotpilot/ros_tms", "max_issues_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 114.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T06:42:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T05:54:04.000Z", "max_forks_repo_path": "tms_ss/tms_ss_pozyx/src/main.cpp", "max_forks_repo_name": "robotpilot/ros_tms", "max_forks_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-03-27T08:35:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T13:05:31.000Z", "avg_line_length": 25.6529680365, "max_line_length": 97, "alphanum_fraction": 0.5879316483, "num_tokens": 1917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.16625207743281462}}
{"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// 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_ALGORITHMS_DISTANCE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DISTANCE_HPP\n\n\n#include <boost/concept_check.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/range.hpp>\n#include <boost/typeof/typeof.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/reverse_dispatch.hpp>\n#include <boost/geometry/core/tag_cast.hpp>\n\n#include <boost/geometry/algorithms/not_implemented.hpp>\n#include <boost/geometry/algorithms/detail/throw_on_empty_input.hpp>\n\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/geometries/concepts/check.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/default_distance_result.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n\n#include <boost/geometry/views/closeable_view.hpp>\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace distance\n{\n\n// To avoid spurious namespaces here:\nusing strategy::distance::services::return_type;\n\ntemplate <typename P1, typename P2, typename Strategy>\nstruct point_to_point\n{\n    static inline typename return_type<Strategy>::type apply(P1 const& p1,\n                P2 const& p2, Strategy const& strategy)\n    {\n        boost::ignore_unused_variable_warning(strategy);\n        return strategy.apply(p1, p2);\n    }\n};\n\n\ntemplate<typename Point, typename Segment, typename Strategy>\nstruct point_to_segment\n{\n    static inline typename return_type<Strategy>::type apply(Point const& point,\n                Segment const& segment, Strategy const& )\n    {\n        typename strategy::distance::services::default_strategy\n            <\n                segment_tag,\n                Point,\n                typename point_type<Segment>::type,\n                typename cs_tag<Point>::type,\n                typename cs_tag<typename point_type<Segment>::type>::type,\n                Strategy\n            >::type segment_strategy;\n\n        typename point_type<Segment>::type p[2];\n        geometry::detail::assign_point_from_index<0>(segment, p[0]);\n        geometry::detail::assign_point_from_index<1>(segment, p[1]);\n        return segment_strategy.apply(point, p[0], p[1]);\n    }\n};\n\n\ntemplate\n<\n    typename Point,\n    typename Range,\n    closure_selector Closure,\n    typename PPStrategy,\n    typename PSStrategy\n>\nstruct point_to_range\n{\n    typedef typename return_type<PSStrategy>::type return_type;\n\n    static inline return_type apply(Point const& point, Range const& range,\n            PPStrategy const& pp_strategy, PSStrategy const& ps_strategy)\n    {\n        return_type const zero = return_type(0);\n\n        if (boost::size(range) == 0)\n        {\n            return zero;\n        }\n\n        typedef typename closeable_view<Range const, Closure>::type view_type;\n\n        view_type view(range);\n\n        // line of one point: return point distance\n        typedef typename boost::range_iterator<view_type const>::type iterator_type;\n        iterator_type it = boost::begin(view);\n        iterator_type prev = it++;\n        if (it == boost::end(view))\n        {\n            return pp_strategy.apply(point, *boost::begin(view));\n        }\n\n        // Create comparable (more efficient) strategy\n        typedef typename strategy::distance::services::comparable_type<PSStrategy>::type eps_strategy_type;\n        eps_strategy_type eps_strategy = strategy::distance::services::get_comparable<PSStrategy>::apply(ps_strategy);\n\n        // start with first segment distance\n        return_type d = eps_strategy.apply(point, *prev, *it);\n        return_type rd = ps_strategy.apply(point, *prev, *it);\n\n        // check if other segments are closer\n        for (++prev, ++it; it != boost::end(view); ++prev, ++it)\n        {\n            return_type const ds = eps_strategy.apply(point, *prev, *it);\n            if (geometry::math::equals(ds, zero))\n            {\n                return ds;\n            }\n            else if (ds < d)\n            {\n                d = ds;\n                rd = ps_strategy.apply(point, *prev, *it);\n            }\n        }\n\n        return rd;\n    }\n};\n\n\ntemplate\n<\n    typename Point,\n    typename Ring,\n    closure_selector Closure,\n    typename PPStrategy,\n    typename PSStrategy\n>\nstruct point_to_ring\n{\n    typedef std::pair\n        <\n            typename return_type<PPStrategy>::type, bool\n        > distance_containment;\n\n    static inline distance_containment apply(Point const& point,\n                Ring const& ring,\n                PPStrategy const& pp_strategy, PSStrategy const& ps_strategy)\n    {\n        return distance_containment\n            (\n                point_to_range\n                    <\n                        Point,\n                        Ring,\n                        Closure,\n                        PPStrategy,\n                        PSStrategy\n                    >::apply(point, ring, pp_strategy, ps_strategy),\n                geometry::within(point, ring)\n            );\n    }\n};\n\n\n\ntemplate\n<\n    typename Point,\n    typename Polygon,\n    closure_selector Closure,\n    typename PPStrategy,\n    typename PSStrategy\n>\nstruct point_to_polygon\n{\n    typedef typename return_type<PPStrategy>::type return_type;\n    typedef std::pair<return_type, bool> distance_containment;\n\n    static inline distance_containment apply(Point const& point,\n                Polygon const& polygon,\n                PPStrategy const& pp_strategy, PSStrategy const& ps_strategy)\n    {\n        // Check distance to all rings\n        typedef point_to_ring\n            <\n                Point,\n                typename ring_type<Polygon>::type,\n                Closure,\n                PPStrategy,\n                PSStrategy\n            > per_ring;\n\n        distance_containment dc = per_ring::apply(point,\n                        exterior_ring(polygon), pp_strategy, ps_strategy);\n\n        typename interior_return_type<Polygon const>::type rings\n                    = interior_rings(polygon);\n        for (BOOST_AUTO_TPL(it, boost::begin(rings)); it != boost::end(rings); ++it)\n        {\n            distance_containment dcr = per_ring::apply(point,\n                            *it, pp_strategy, ps_strategy);\n            if (dcr.first < dc.first)\n            {\n                dc.first = dcr.first;\n            }\n            // If it was inside, and also inside inner ring,\n            // turn off the inside-flag, it is outside the polygon\n            if (dc.second && dcr.second)\n            {\n                dc.second = false;\n            }\n        }\n        return dc;\n    }\n};\n\n\n// Helper metafunction for default strategy retrieval\ntemplate <typename Geometry1, typename Geometry2>\nstruct default_strategy\n    : strategy::distance::services::default_strategy\n          <\n              point_tag,\n              typename point_type<Geometry1>::type,\n              typename point_type<Geometry2>::type\n          >\n{};\n\n\n}} // namespace detail::distance\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\nusing strategy::distance::services::return_type;\n\n\ntemplate\n<\n    typename Geometry1, typename Geometry2,\n    typename Strategy = typename detail::distance::default_strategy<Geometry1, Geometry2>::type,\n    typename Tag1 = typename tag_cast<typename tag<Geometry1>::type, multi_tag>::type,\n    typename Tag2 = typename tag_cast<typename tag<Geometry2>::type, multi_tag>::type,\n    typename StrategyTag = typename strategy::distance::services::tag<Strategy>::type,\n    bool Reverse = reverse_dispatch<Geometry1, Geometry2>::type::value\n>\nstruct distance: not_implemented<Tag1, Tag2>\n{};\n\n\n// If reversal is needed, perform it\ntemplate\n<\n    typename Geometry1, typename Geometry2, typename Strategy,\n    typename Tag1, typename Tag2, typename StrategyTag\n>\nstruct distance\n<\n    Geometry1, Geometry2, Strategy,\n    Tag1, Tag2, StrategyTag,\n    true\n>\n    : distance<Geometry2, Geometry1, Strategy, Tag2, Tag1, StrategyTag, false>\n{\n    static inline typename return_type<Strategy>::type apply(\n        Geometry1 const& g1,\n        Geometry2 const& g2,\n        Strategy const& strategy)\n    {\n        return distance\n            <\n                Geometry2, Geometry1, Strategy,\n                Tag2, Tag1, StrategyTag,\n                false\n            >::apply(g2, g1, strategy);\n    }\n};\n\n// If reversal is needed and we got the strategy by default, invert it before\n// proceeding to the reversal.\ntemplate\n<\n    typename Geometry1, typename Geometry2,\n    typename Tag1, typename Tag2, typename StrategyTag\n>\nstruct distance\n<\n    Geometry1, Geometry2,\n    typename detail::distance::default_strategy<Geometry1, Geometry2>::type,\n    Tag1, Tag2, StrategyTag,\n    true\n>\n    : distance\n          <\n              Geometry2, Geometry1,\n              typename detail::distance::default_strategy<Geometry2, Geometry1>::type,\n              Tag2, Tag1, StrategyTag,\n              false\n          >\n{\n    typedef typename detail::distance::default_strategy<Geometry2, Geometry1>::type reversed_strategy;\n\n    static inline typename strategy::distance::services::return_type<reversed_strategy>::type apply(\n        Geometry1 const& g1,\n        Geometry2 const& g2,\n        typename detail::distance::default_strategy<Geometry1, Geometry2>::type const&)\n    {\n        return distance\n            <\n                Geometry2, Geometry1, reversed_strategy,\n                Tag2, Tag1, StrategyTag,\n                false\n            >::apply(g2, g1, reversed_strategy());\n    }\n};\n\n\n// Point-point\ntemplate <typename P1, typename P2, typename Strategy>\nstruct distance\n    <\n        P1, P2, Strategy,\n        point_tag, point_tag, strategy_tag_distance_point_point,\n        false\n    >\n    : detail::distance::point_to_point<P1, P2, Strategy>\n{};\n\n\n// Point-line version 1, where point-point strategy is specified\ntemplate <typename Point, typename Linestring, typename Strategy>\nstruct distance\n<\n    Point, Linestring, Strategy,\n    point_tag, linestring_tag, strategy_tag_distance_point_point,\n    false\n>\n{\n\n    static inline typename return_type<Strategy>::type apply(Point const& point,\n            Linestring const& linestring,\n            Strategy const& strategy)\n    {\n        typedef typename strategy::distance::services::default_strategy\n                    <\n                        segment_tag,\n                        Point,\n                        typename point_type<Linestring>::type,\n                        typename cs_tag<Point>::type,\n                        typename cs_tag<typename point_type<Linestring>::type>::type,\n                        Strategy\n                    >::type ps_strategy_type;\n\n        return detail::distance::point_to_range\n            <\n                Point, Linestring, closed, Strategy, ps_strategy_type\n            >::apply(point, linestring, strategy, ps_strategy_type());\n    }\n};\n\n\n// Point-line version 2, where point-segment strategy is specified\ntemplate <typename Point, typename Linestring, typename Strategy>\nstruct distance\n<\n    Point, Linestring, Strategy,\n    point_tag, linestring_tag, strategy_tag_distance_point_segment,\n    false\n>\n{\n    static inline typename return_type<Strategy>::type apply(Point const& point,\n            Linestring const& linestring,\n            Strategy const& strategy)\n    {\n        typedef typename Strategy::point_strategy_type pp_strategy_type;\n        return detail::distance::point_to_range\n            <\n                Point, Linestring, closed, pp_strategy_type, Strategy\n            >::apply(point, linestring, pp_strategy_type(), strategy);\n    }\n};\n\n// Point-ring , where point-segment strategy is specified\ntemplate <typename Point, typename Ring, typename Strategy>\nstruct distance\n<\n    Point, Ring, Strategy,\n    point_tag, ring_tag, strategy_tag_distance_point_point,\n    false\n>\n{\n    typedef typename return_type<Strategy>::type return_type;\n\n    static inline return_type apply(Point const& point,\n            Ring const& ring,\n            Strategy const& strategy)\n    {\n        typedef typename strategy::distance::services::default_strategy\n            <\n                segment_tag,\n                Point,\n                typename point_type<Ring>::type\n            >::type ps_strategy_type;\n\n        std::pair<return_type, bool>\n            dc = detail::distance::point_to_ring\n            <\n                Point, Ring,\n                geometry::closure<Ring>::value,\n                Strategy, ps_strategy_type\n            >::apply(point, ring, strategy, ps_strategy_type());\n\n        return dc.second ? return_type(0) : dc.first;\n    }\n};\n\n\n// Point-polygon , where point-segment strategy is specified\ntemplate <typename Point, typename Polygon, typename Strategy>\nstruct distance\n<\n    Point, Polygon, Strategy,\n    point_tag, polygon_tag, strategy_tag_distance_point_point,\n    false\n>\n{\n    typedef typename return_type<Strategy>::type return_type;\n\n    static inline return_type apply(Point const& point,\n            Polygon const& polygon,\n            Strategy const& strategy)\n    {\n        typedef typename strategy::distance::services::default_strategy\n            <\n                segment_tag,\n                Point,\n                typename point_type<Polygon>::type\n            >::type ps_strategy_type;\n\n        std::pair<return_type, bool>\n            dc = detail::distance::point_to_polygon\n            <\n                Point, Polygon,\n                geometry::closure<Polygon>::value,\n                Strategy, ps_strategy_type\n            >::apply(point, polygon, strategy, ps_strategy_type());\n\n        return dc.second ? return_type(0) : dc.first;\n    }\n};\n\n\n\n// Point-segment version 1, with point-point strategy\ntemplate <typename Point, typename Segment, typename Strategy>\nstruct distance\n<\n    Point, Segment, Strategy,\n    point_tag, segment_tag, strategy_tag_distance_point_point,\n    false\n> : detail::distance::point_to_segment<Point, Segment, Strategy>\n{};\n\n// Point-segment version 2, with point-segment strategy\ntemplate <typename Point, typename Segment, typename Strategy>\nstruct distance\n<\n    Point, Segment, Strategy,\n    point_tag, segment_tag, strategy_tag_distance_point_segment,\n    false\n>\n{\n    static inline typename return_type<Strategy>::type apply(Point const& point,\n                Segment const& segment, Strategy const& strategy)\n    {\n        \n        typename point_type<Segment>::type p[2];\n        geometry::detail::assign_point_from_index<0>(segment, p[0]);\n        geometry::detail::assign_point_from_index<1>(segment, p[1]);\n        return strategy.apply(point, p[0], p[1]);\n    }\n};\n\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n/*!\n\\brief \\brief_calc2{distance} \\brief_strategy\n\\ingroup distance\n\\details\n\\details \\details_calc{area}. \\brief_strategy. \\details_strategy_reasons\n\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\tparam Strategy \\tparam_strategy{Distance}\n\\param geometry1 \\param_geometry\n\\param geometry2 \\param_geometry\n\\param strategy \\param_strategy{distance}\n\\return \\return_calc{distance}\n\\note The strategy can be a point-point strategy. In case of distance point-line/point-polygon\n    it may also be a point-segment strategy.\n\n\\qbk{distinguish,with strategy}\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\\* [link geometry.reference.strategies.strategy_distance_cross_track Cross track (spherical\\, point-to-segment)]\n\\* [link geometry.reference.strategies.strategy_distance_projected_point Projected point (cartesian\\, point-to-segment)]\n\\* more (currently extensions): Vincenty\\, Andoyer (geographic)\n}\n */\n\n/*\nNote, in case of a Compilation Error:\nif you get:\n - \"Failed to specialize function template ...\"\n - \"error: no matching function for call to ...\"\nfor distance, it is probably so that there is no specialization\nfor return_type<...> for your strategy.\n*/\ntemplate <typename Geometry1, typename Geometry2, typename Strategy>\ninline typename strategy::distance::services::return_type<Strategy>::type distance(\n                Geometry1 const& geometry1, Geometry2 const& geometry2,\n                Strategy const& strategy)\n{\n    concept::check<Geometry1 const>();\n    concept::check<Geometry2 const>();\n    \n    detail::throw_on_empty_input(geometry1);\n    detail::throw_on_empty_input(geometry2);\n\n    return dispatch::distance\n               <\n                   Geometry1,\n                   Geometry2,\n                   Strategy\n               >::apply(geometry1, geometry2, strategy);\n}\n\n\n/*!\n\\brief \\brief_calc2{distance}\n\\ingroup distance\n\\details The default strategy is used, corresponding to the coordinate system of the geometries\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\param geometry1 \\param_geometry\n\\param geometry2 \\param_geometry\n\\return \\return_calc{distance}\n\n\\qbk{[include reference/algorithms/distance.qbk]}\n */\ntemplate <typename Geometry1, typename Geometry2>\ninline typename default_distance_result<Geometry1, Geometry2>::type distance(\n                Geometry1 const& geometry1, Geometry2 const& geometry2)\n{\n    concept::check<Geometry1 const>();\n    concept::check<Geometry2 const>();\n\n    return distance(geometry1, geometry2,\n                    typename detail::distance::default_strategy<Geometry1, Geometry2>::type());\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DISTANCE_HPP\n", "meta": {"hexsha": "0fd5c43f4a837709f689143038c98d16453207fd", "size": 18175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/algorithms/distance.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/geometry/algorithms/distance.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/geometry/algorithms/distance.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": 30.4438860972, "max_line_length": 120, "alphanum_fraction": 0.6528198074, "num_tokens": 3856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.16623119143633355}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2016-2017, 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_STRATEGIES_GEOGRAPHIC_INTERSECTION_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_INTERSECTION_HPP\n\n#include <algorithm>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/srs.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/algorithms/detail/assign_values.hpp>\n#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\n#include <boost/geometry/algorithms/detail/recalculate.hpp>\n\n#include <boost/geometry/formulas/andoyer_inverse.hpp>\n#include <boost/geometry/formulas/sjoberg_intersection.hpp>\n#include <boost/geometry/formulas/spherical.hpp>\n#include <boost/geometry/formulas/unit_spheroid.hpp>\n\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n#include <boost/geometry/geometries/concepts/segment_concept.hpp>\n\n#include <boost/geometry/policies/robustness/segment_ratio.hpp>\n\n#include <boost/geometry/strategies/geographic/area.hpp>\n#include <boost/geometry/strategies/geographic/distance.hpp>\n#include <boost/geometry/strategies/geographic/envelope_segment.hpp>\n#include <boost/geometry/strategies/geographic/parameters.hpp>\n#include <boost/geometry/strategies/geographic/point_in_poly_winding.hpp>\n#include <boost/geometry/strategies/geographic/side.hpp>\n#include <boost/geometry/strategies/intersection.hpp>\n#include <boost/geometry/strategies/intersection_result.hpp>\n#include <boost/geometry/strategies/side_info.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace intersection\n{\n\n// CONSIDER: Improvement of the robustness/accuracy/repeatability by\n// moving all segments to 0 longitude\n// picking latitudes closer to 0\n// etc.\n\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    unsigned int Order = strategy::default_order<FormulaPolicy>::value,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nstruct geographic_segments\n{\n    typedef side::geographic\n        <\n            FormulaPolicy, Spheroid, CalculationType\n        > side_strategy_type;\n\n    inline side_strategy_type get_side_strategy() const\n    {\n        return side_strategy_type(m_spheroid);\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    struct point_in_geometry_strategy\n    {\n        typedef strategy::within::geographic_winding\n            <\n                typename point_type<Geometry1>::type,\n                typename point_type<Geometry2>::type,\n                FormulaPolicy,\n                Spheroid,\n                CalculationType\n            > type;\n    };\n\n    template <typename Geometry1, typename Geometry2>\n    inline typename point_in_geometry_strategy<Geometry1, Geometry2>::type\n        get_point_in_geometry_strategy() const\n    {\n        typedef typename point_in_geometry_strategy\n            <\n                Geometry1, Geometry2\n            >::type strategy_type;\n        return strategy_type(m_spheroid);\n    }\n\n    template <typename Geometry>\n    struct area_strategy\n    {\n        typedef area::geographic\n            <\n                typename point_type<Geometry>::type,\n                FormulaPolicy,\n                Order,\n                Spheroid,\n                CalculationType\n            > type;\n    };\n\n    template <typename Geometry>\n    inline typename area_strategy<Geometry>::type get_area_strategy() const\n    {\n        typedef typename area_strategy<Geometry>::type strategy_type;\n        return strategy_type(m_spheroid);\n    }\n\n    template <typename Geometry>\n    struct distance_strategy\n    {\n        typedef distance::geographic\n            <\n                FormulaPolicy,\n                Spheroid,\n                CalculationType\n            > type;\n    };\n\n    template <typename Geometry>\n    inline typename distance_strategy<Geometry>::type get_distance_strategy() const\n    {\n        typedef typename distance_strategy<Geometry>::type strategy_type;\n        return strategy_type(m_spheroid);\n    }\n\n    typedef envelope::geographic_segment<FormulaPolicy, Spheroid, CalculationType>\n        envelope_strategy_type;\n\n    inline envelope_strategy_type get_envelope_strategy() const\n    {\n        return envelope_strategy_type(m_spheroid);\n    }\n\n    enum intersection_point_flag { ipi_inters = 0, ipi_at_a1, ipi_at_a2, ipi_at_b1, ipi_at_b2 };\n\n    template <typename CoordinateType, typename SegmentRatio>\n    struct segment_intersection_info\n    {\n        typedef typename select_most_precise\n            <\n                CoordinateType, double\n            >::type promoted_type;\n\n        promoted_type comparable_length_a() const\n        {\n            return robust_ra.denominator();\n        }\n\n        promoted_type comparable_length_b() const\n        {\n            return robust_rb.denominator();\n        }\n\n        template <typename Point, typename Segment1, typename Segment2>\n        void assign_a(Point& point, Segment1 const& a, Segment2 const& b) const\n        {\n            assign(point, a, b);\n        }\n        template <typename Point, typename Segment1, typename Segment2>\n        void assign_b(Point& point, Segment1 const& a, Segment2 const& b) const\n        {\n            assign(point, a, b);\n        }\n\n        template <typename Point, typename Segment1, typename Segment2>\n        void assign(Point& point, Segment1 const& a, Segment2 const& b) const\n        {\n            if (ip_flag == ipi_inters)\n            {\n                // TODO: assign the rest of coordinates\n                set_from_radian<0>(point, lon);\n                set_from_radian<1>(point, lat);\n            }\n            else if (ip_flag == ipi_at_a1)\n            {\n                detail::assign_point_from_index<0>(a, point);\n            }\n            else if (ip_flag == ipi_at_a2)\n            {\n                detail::assign_point_from_index<1>(a, point);\n            }\n            else if (ip_flag == ipi_at_b1)\n            {\n                detail::assign_point_from_index<0>(b, point);\n            }\n            else // ip_flag == ipi_at_b2\n            {\n                detail::assign_point_from_index<1>(b, point);\n            }\n        }\n\n        CoordinateType lon;\n        CoordinateType lat;\n        SegmentRatio robust_ra;\n        SegmentRatio robust_rb;\n        intersection_point_flag ip_flag;\n    };\n\n    explicit geographic_segments(Spheroid const& spheroid = Spheroid())\n        : m_spheroid(spheroid)\n    {}\n\n    // Relate segments a and b\n    template\n    <\n        typename Segment1,\n        typename Segment2,\n        typename Policy,\n        typename RobustPolicy\n    >\n    inline typename Policy::return_type apply(Segment1 const& a, Segment2 const& b,\n                                              Policy const& policy,\n                                              RobustPolicy const& robust_policy) const\n    {\n        typedef typename point_type<Segment1>::type point1_t;\n        typedef typename point_type<Segment2>::type point2_t;\n        point1_t a1, a2;\n        point2_t b1, b2;\n\n        detail::assign_point_from_index<0>(a, a1);\n        detail::assign_point_from_index<1>(a, a2);\n        detail::assign_point_from_index<0>(b, b1);\n        detail::assign_point_from_index<1>(b, b2);\n\n        return apply(a, b, policy, robust_policy, a1, a2, b1, b2);\n    }\n\n    // Relate segments a and b\n    template\n    <\n        typename Segment1,\n        typename Segment2,\n        typename Policy,\n        typename RobustPolicy,\n        typename Point1,\n        typename Point2\n    >\n    inline typename Policy::return_type apply(Segment1 const& a, Segment2 const& b,\n                                              Policy const&, RobustPolicy const&,\n                                              Point1 a1, Point1 a2, Point2 b1, Point2 b2) const\n    {\n        bool is_a_reversed = get<1>(a1) > get<1>(a2);\n        bool is_b_reversed = get<1>(b1) > get<1>(b2);\n                           \n        if (is_a_reversed)\n        {\n            std::swap(a1, a2);\n        }\n\n        if (is_b_reversed)\n        {\n            std::swap(b1, b2);\n        }\n\n        return apply<Policy>(a, b, a1, a2, b1, b2, is_a_reversed, is_b_reversed);\n    }\n\nprivate:\n    // Relate segments a and b\n    template\n    <\n        typename Policy,\n        typename Segment1,\n        typename Segment2,\n        typename Point1,\n        typename Point2\n    >\n    inline typename Policy::return_type apply(Segment1 const& a, Segment2 const& b,\n                                              Point1 const& a1, Point1 const& a2,\n                                              Point2 const& b1, Point2 const& b2,\n                                              bool is_a_reversed, bool is_b_reversed) const\n    {\n        BOOST_CONCEPT_ASSERT( (concepts::ConstSegment<Segment1>) );\n        BOOST_CONCEPT_ASSERT( (concepts::ConstSegment<Segment2>) );\n\n        typedef typename select_calculation_type\n            <Segment1, Segment2, CalculationType>::type calc_t;\n\n        typedef srs::spheroid<calc_t> spheroid_type;\n\n        static const calc_t c0 = 0;\n\n        // normalized spheroid\n        spheroid_type spheroid = formula::unit_spheroid<spheroid_type>(m_spheroid);\n\n        // TODO: check only 2 first coordinates here?\n        using geometry::detail::equals::equals_point_point;\n        bool a_is_point = equals_point_point(a1, a2);\n        bool b_is_point = equals_point_point(b1, b2);\n\n        if(a_is_point && b_is_point)\n        {\n            return equals_point_point(a1, b2)\n                ? Policy::degenerate(a, true)\n                : Policy::disjoint()\n                ;\n        }\n        \n        calc_t const a1_lon = get_as_radian<0>(a1);\n        calc_t const a1_lat = get_as_radian<1>(a1);\n        calc_t const a2_lon = get_as_radian<0>(a2);\n        calc_t const a2_lat = get_as_radian<1>(a2);\n        calc_t const b1_lon = get_as_radian<0>(b1);\n        calc_t const b1_lat = get_as_radian<1>(b1);\n        calc_t const b2_lon = get_as_radian<0>(b2);\n        calc_t const b2_lat = get_as_radian<1>(b2);\n\n        side_info sides;\n\n        // NOTE: potential optimization, don't calculate distance at this point\n        // this would require to reimplement inverse strategy to allow\n        // calculation of distance if needed, probably also storing intermediate\n        // results somehow inside an object.\n        typedef typename FormulaPolicy::template inverse<calc_t, true, true, false, false, false> inverse_dist_azi;\n        typedef typename inverse_dist_azi::result_type inverse_result;\n\n        // TODO: no need to call inverse formula if we know that the points are equal\n        // distance can be set to 0 in this case and azimuth may be not calculated\n        bool is_equal_a1_b1 = equals_point_point(a1, b1);\n        bool is_equal_a2_b1 = equals_point_point(a2, b1);\n        bool degen_neq_coords = false;\n\n        inverse_result res_b1_b2, res_b1_a1, res_b1_a2;\n        if (! b_is_point)\n        {\n            res_b1_b2 = inverse_dist_azi::apply(b1_lon, b1_lat, b2_lon, b2_lat, spheroid);\n            if (math::equals(res_b1_b2.distance, c0))\n            {\n                b_is_point = true;\n                degen_neq_coords = true;\n            }\n            else\n            {\n                res_b1_a1 = inverse_dist_azi::apply(b1_lon, b1_lat, a1_lon, a1_lat, spheroid);\n                if (math::equals(res_b1_a1.distance, c0))\n                {\n                    is_equal_a1_b1 = true;\n                }\n                res_b1_a2 = inverse_dist_azi::apply(b1_lon, b1_lat, a2_lon, a2_lat, spheroid);\n                if (math::equals(res_b1_a2.distance, c0))\n                {\n                    is_equal_a2_b1 = true;\n                }\n                sides.set<0>(is_equal_a1_b1 ? 0 : formula::azimuth_side_value(res_b1_a1.azimuth, res_b1_b2.azimuth),\n                             is_equal_a2_b1 ? 0 : formula::azimuth_side_value(res_b1_a2.azimuth, res_b1_b2.azimuth));\n                if (sides.same<0>())\n                {\n                    // Both points are at the same side of other segment, we can leave\n                    return Policy::disjoint();\n                }\n            }\n        }\n\n        bool is_equal_a1_b2 = equals_point_point(a1, b2);\n\n        inverse_result res_a1_a2, res_a1_b1, res_a1_b2;\n        if (! a_is_point)\n        {\n            res_a1_a2 = inverse_dist_azi::apply(a1_lon, a1_lat, a2_lon, a2_lat, spheroid);\n            if (math::equals(res_a1_a2.distance, c0))\n            {\n                a_is_point = true;\n                degen_neq_coords = true;\n            }\n            else\n            {\n                res_a1_b1 = inverse_dist_azi::apply(a1_lon, a1_lat, b1_lon, b1_lat, spheroid);\n                if (math::equals(res_a1_b1.distance, c0))\n                {\n                    is_equal_a1_b1 = true;\n                }\n                res_a1_b2 = inverse_dist_azi::apply(a1_lon, a1_lat, b2_lon, b2_lat, spheroid);\n                if (math::equals(res_a1_b2.distance, c0))\n                {\n                    is_equal_a1_b2 = true;\n                }\n                sides.set<1>(is_equal_a1_b1 ? 0 : formula::azimuth_side_value(res_a1_b1.azimuth, res_a1_a2.azimuth),\n                             is_equal_a1_b2 ? 0 : formula::azimuth_side_value(res_a1_b2.azimuth, res_a1_a2.azimuth));\n                if (sides.same<1>())\n                {\n                    // Both points are at the same side of other segment, we can leave\n                    return Policy::disjoint();\n                }\n            }\n        }\n\n        if(a_is_point && b_is_point)\n        {\n            return is_equal_a1_b2\n                ? Policy::degenerate(a, true)\n                : Policy::disjoint()\n                ;\n        }\n\n        // NOTE: at this point the segments may still be disjoint\n        // NOTE: at this point one of the segments may be degenerated\n\n        bool collinear = sides.collinear();       \n\n        if (! collinear)\n        {\n            // WARNING: the side strategy doesn't have the info about the other\n            // segment so it may return results inconsistent with this intersection\n            // strategy, as it checks both segments for consistency\n\n            if (sides.get<0, 0>() == 0 && sides.get<0, 1>() == 0)\n            {\n                collinear = true;\n                sides.set<1>(0, 0);\n            }\n            else if (sides.get<1, 0>() == 0 && sides.get<1, 1>() == 0)\n            {\n                collinear = true;\n                sides.set<0>(0, 0);\n            }\n        }\n\n        if (collinear)\n        {\n            if (a_is_point)\n            {\n                return collinear_one_degenerated<Policy, calc_t>(a, true, b1, b2, a1, a2, res_b1_b2, res_b1_a1, res_b1_a2, is_b_reversed, degen_neq_coords);\n            }\n            else if (b_is_point)\n            {\n                return collinear_one_degenerated<Policy, calc_t>(b, false, a1, a2, b1, b2, res_a1_a2, res_a1_b1, res_a1_b2, is_a_reversed, degen_neq_coords);\n            }\n            else\n            {\n                calc_t dist_a1_a2, dist_a1_b1, dist_a1_b2;\n                calc_t dist_b1_b2, dist_b1_a1, dist_b1_a2;\n                // use shorter segment\n                if (res_a1_a2.distance <= res_b1_b2.distance)\n                {\n                    calculate_collinear_data(a1, a2, b1, b2, res_a1_a2, res_a1_b1, res_a1_b2, dist_a1_a2, dist_a1_b1);\n                    calculate_collinear_data(a1, a2, b1, b2, res_a1_a2, res_a1_b2, res_a1_b1, dist_a1_a2, dist_a1_b2);\n                    dist_b1_b2 = dist_a1_b2 - dist_a1_b1;\n                    dist_b1_a1 = -dist_a1_b1;\n                    dist_b1_a2 = dist_a1_a2 - dist_a1_b1;\n                }\n                else\n                {\n                    calculate_collinear_data(b1, b2, a1, a2, res_b1_b2, res_b1_a1, res_b1_a2, dist_b1_b2, dist_b1_a1);\n                    calculate_collinear_data(b1, b2, a1, a2, res_b1_b2, res_b1_a2, res_b1_a1, dist_b1_b2, dist_b1_a2);\n                    dist_a1_a2 = dist_b1_a2 - dist_b1_a1;\n                    dist_a1_b1 = -dist_b1_a1;\n                    dist_a1_b2 = dist_b1_b2 - dist_b1_a1;\n                }\n\n                // NOTE: this is probably not needed\n                calc_t const c0 = 0;\n                int a1_on_b = position_value(c0, dist_a1_b1, dist_a1_b2);\n                int a2_on_b = position_value(dist_a1_a2, dist_a1_b1, dist_a1_b2);\n                int b1_on_a = position_value(c0, dist_b1_a1, dist_b1_a2);\n                int b2_on_a = position_value(dist_b1_b2, dist_b1_a1, dist_b1_a2);\n\n                if ((a1_on_b < 1 && a2_on_b < 1) || (a1_on_b > 3 && a2_on_b > 3))\n                {\n                    return Policy::disjoint();\n                }\n\n                if (a1_on_b == 1)\n                {\n                    dist_b1_a1 = 0;\n                    dist_a1_b1 = 0;\n                }\n                else if (a1_on_b == 3)\n                {\n                    dist_b1_a1 = dist_b1_b2;\n                    dist_a1_b2 = 0;\n                }\n\n                if (a2_on_b == 1)\n                {\n                    dist_b1_a2 = 0;\n                    dist_a1_b1 = dist_a1_a2;\n                }\n                else if (a2_on_b == 3)\n                {\n                    dist_b1_a2 = dist_b1_b2;\n                    dist_a1_b2 = dist_a1_a2;\n                }\n\n                bool opposite = ! same_direction(res_a1_a2.azimuth, res_b1_b2.azimuth);\n\n                // NOTE: If segment was reversed opposite, positions and segment ratios has to be altered\n                if (is_a_reversed)\n                {\n                    // opposite\n                    opposite = ! opposite;\n                    // positions\n                    std::swap(a1_on_b, a2_on_b);\n                    b1_on_a = 4 - b1_on_a;\n                    b2_on_a = 4 - b2_on_a;\n                    // distances for ratios\n                    std::swap(dist_b1_a1, dist_b1_a2);\n                    dist_a1_b1 = dist_a1_a2 - dist_a1_b1;\n                    dist_a1_b2 = dist_a1_a2 - dist_a1_b2;\n                }\n                if (is_b_reversed)\n                {\n                    // opposite\n                    opposite = ! opposite;\n                    // positions\n                    a1_on_b = 4 - a1_on_b;\n                    a2_on_b = 4 - a2_on_b;\n                    std::swap(b1_on_a, b2_on_a);\n                    // distances for ratios\n                    dist_b1_a1 = dist_b1_b2 - dist_b1_a1;\n                    dist_b1_a2 = dist_b1_b2 - dist_b1_a2;\n                    std::swap(dist_a1_b1, dist_a1_b2);\n                }\n\n                segment_ratio<calc_t> ra_from(dist_b1_a1, dist_b1_b2);\n                segment_ratio<calc_t> ra_to(dist_b1_a2, dist_b1_b2);\n                segment_ratio<calc_t> rb_from(dist_a1_b1, dist_a1_a2);\n                segment_ratio<calc_t> rb_to(dist_a1_b2, dist_a1_a2);\n\n                return Policy::segments_collinear(a, b, opposite,\n                    a1_on_b, a2_on_b, b1_on_a, b2_on_a,\n                    ra_from, ra_to, rb_from, rb_to);\n            }\n        }\n        else // crossing or touching\n        {\n            if (a_is_point || b_is_point)\n            {\n                return Policy::disjoint();\n            }\n\n            calc_t lon = 0, lat = 0;\n            intersection_point_flag ip_flag;\n            calc_t dist_a1_a2, dist_a1_i1, dist_b1_b2, dist_b1_i1;\n            if (calculate_ip_data(a1, a2, b1, b2,\n                                  a1_lon, a1_lat, a2_lon, a2_lat,\n                                  b1_lon, b1_lat, b2_lon, b2_lat,\n                                  res_a1_a2, res_a1_b1, res_a1_b2,\n                                  res_b1_b2, res_b1_a1, res_b1_a2,\n                                  sides, spheroid,\n                                  lon, lat,\n                                  dist_a1_a2, dist_a1_i1, dist_b1_b2, dist_b1_i1,\n                                  ip_flag))\n            {\n                // NOTE: If segment was reversed sides and segment ratios has to be altered\n                if (is_a_reversed)\n                {\n                    // sides\n                    sides_reverse_segment<0>(sides);\n                    // distance for ratio\n                    dist_a1_i1 = dist_a1_a2 - dist_a1_i1;\n                    // ip flag\n                    ip_flag_reverse_segment(ip_flag, ipi_at_a1, ipi_at_a2);\n                }\n                if (is_b_reversed)\n                {\n                    // sides\n                    sides_reverse_segment<1>(sides);\n                    // distance for ratio\n                    dist_b1_i1 = dist_b1_b2 - dist_b1_i1;\n                    // ip flag\n                    ip_flag_reverse_segment(ip_flag, ipi_at_b1, ipi_at_b2);\n                }\n\n                // intersects\n                segment_intersection_info\n                    <\n                        calc_t,\n                        segment_ratio<calc_t>\n                    > sinfo;\n\n                sinfo.lon = lon;\n                sinfo.lat = lat;\n                sinfo.robust_ra.assign(dist_a1_i1, dist_a1_a2);\n                sinfo.robust_rb.assign(dist_b1_i1, dist_b1_b2);\n                sinfo.ip_flag = ip_flag;\n\n                return Policy::segments_crosses(sides, sinfo, a, b);\n            }\n            else\n            {\n                return Policy::disjoint();\n            }\n        }\n    }\n\n    template <typename Policy, typename CalcT, typename Segment, typename Point1, typename Point2, typename ResultInverse>\n    static inline typename Policy::return_type\n        collinear_one_degenerated(Segment const& segment, bool degenerated_a,\n                                  Point1 const& a1, Point1 const& a2,\n                                  Point2 const& b1, Point2 const& b2,\n                                  ResultInverse const& res_a1_a2,\n                                  ResultInverse const& res_a1_b1,\n                                  ResultInverse const& res_a1_b2,\n                                  bool is_other_reversed,\n                                  bool degen_neq_coords)\n    {\n        CalcT dist_1_2, dist_1_o;\n        if (! calculate_collinear_data(a1, a2, b1, b2, res_a1_a2, res_a1_b1, res_a1_b2, dist_1_2, dist_1_o, degen_neq_coords))\n        {\n            return Policy::disjoint();\n        }\n\n        // NOTE: If segment was reversed segment ratio has to be altered\n        if (is_other_reversed)\n        {\n            // distance for ratio\n            dist_1_o = dist_1_2 - dist_1_o;\n        }\n        \n        return Policy::one_degenerate(segment, segment_ratio<CalcT>(dist_1_o, dist_1_2), degenerated_a);\n    }\n\n    // TODO: instead of checks below test bi against a1 and a2 here?\n    //       in order to make this independent from is_near()\n    template <typename Point1, typename Point2, typename ResultInverse, typename CalcT>\n    static inline bool calculate_collinear_data(Point1 const& a1, Point1 const& a2, // in\n                                                Point2 const& b1, Point2 const& b2, // in\n                                                ResultInverse const& res_a1_a2,     // in\n                                                ResultInverse const& res_a1_b1,     // in\n                                                ResultInverse const& res_a1_b2,     // in\n                                                CalcT& dist_a1_a2,                  // out\n                                                CalcT& dist_a1_bi,                  // out\n                                                bool degen_neq_coords = false)      // in\n    {\n        dist_a1_a2 = res_a1_a2.distance;\n\n        dist_a1_bi = res_a1_b1.distance;\n        if (! same_direction(res_a1_b1.azimuth, res_a1_a2.azimuth))\n        {\n            dist_a1_bi = -dist_a1_bi;\n        }\n\n        // if i1 is close to a1 and b1 or b2 is equal to a1\n        if (is_endpoint_equal(dist_a1_bi, a1, b1, b2))\n        {\n            dist_a1_bi = 0;\n            return true;\n        }\n        // or i1 is close to a2 and b1 or b2 is equal to a2\n        else if (is_endpoint_equal(dist_a1_a2 - dist_a1_bi, a2, b1, b2))\n        {\n            dist_a1_bi = dist_a1_a2;\n            return true;\n        }\n\n        // check the other endpoint of a very short segment near the pole\n        if (degen_neq_coords)\n        {\n            static CalcT const c0 = 0;\n            if (math::equals(res_a1_b2.distance, c0))\n            {\n                dist_a1_bi = 0;\n                return true;\n            }\n            else if (math::equals(dist_a1_a2 - res_a1_b2.distance, c0))\n            {\n                dist_a1_bi = dist_a1_a2;\n                return true;\n            }\n        }\n\n        // or i1 is on b\n        return segment_ratio<CalcT>(dist_a1_bi, dist_a1_a2).on_segment();\n    }\n\n    template <typename Point1, typename Point2, typename CalcT, typename ResultInverse, typename Spheroid_>\n    static inline bool calculate_ip_data(Point1 const& a1, Point1 const& a2,       // in\n                                         Point2 const& b1, Point2 const& b2,       // in\n                                         CalcT const& a1_lon, CalcT const& a1_lat, // in\n                                         CalcT const& a2_lon, CalcT const& a2_lat, // in\n                                         CalcT const& b1_lon, CalcT const& b1_lat, // in\n                                         CalcT const& b2_lon, CalcT const& b2_lat, // in\n                                         ResultInverse const& res_a1_a2,           // in\n                                         ResultInverse const& res_a1_b1,           // in\n                                         ResultInverse const& res_a1_b2,           // in\n                                         ResultInverse const& res_b1_b2,           // in\n                                         ResultInverse const& res_b1_a1,           // in\n                                         ResultInverse const& res_b1_a2,           // in\n                                         side_info const& sides,                   // in\n                                         Spheroid_ const& spheroid,                // in\n                                         CalcT & lon, CalcT & lat,             // out\n                                         CalcT& dist_a1_a2, CalcT& dist_a1_ip, // out\n                                         CalcT& dist_b1_b2, CalcT& dist_b1_ip, // out\n                                         intersection_point_flag& ip_flag)     // out\n    {\n        dist_a1_a2 = res_a1_a2.distance;\n        dist_b1_b2 = res_b1_b2.distance;\n\n        // assign the IP if some endpoints overlap\n        using geometry::detail::equals::equals_point_point;\n        if (equals_point_point(a1, b1))\n        {\n            lon = a1_lon;\n            lat = a1_lat;\n            dist_a1_ip = 0;\n            dist_b1_ip = 0;\n            ip_flag = ipi_at_a1;\n            return true;\n        }\n        else if (equals_point_point(a1, b2))\n        {\n            lon = a1_lon;\n            lat = a1_lat;\n            dist_a1_ip = 0;\n            dist_b1_ip = dist_b1_b2;\n            ip_flag = ipi_at_a1;\n            return true;\n        }\n        else if (equals_point_point(a2, b1))\n        {\n            lon = a2_lon;\n            lat = a2_lat;\n            dist_a1_ip = dist_a1_a2;\n            dist_b1_ip = 0;\n            ip_flag = ipi_at_a2;\n            return true;\n        }\n        else if (equals_point_point(a2, b2))\n        {\n            lon = a2_lon;\n            lat = a2_lat;\n            dist_a1_ip = dist_a1_a2;\n            dist_b1_ip = dist_b1_b2;\n            ip_flag = ipi_at_a2;\n            return true;\n        }\n\n        // at this point we know that the endpoints doesn't overlap\n        // check cases when an endpoint lies on the other geodesic\n        if (sides.template get<0, 0>() == 0) // a1 wrt b\n        {\n            if (res_b1_a1.distance <= res_b1_b2.distance\n                && same_direction(res_b1_a1.azimuth, res_b1_b2.azimuth))\n            {\n                lon = a1_lon;\n                lat = a1_lat;\n                dist_a1_ip = 0;\n                dist_b1_ip = res_b1_a1.distance;\n                ip_flag = ipi_at_a1;\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n        else if (sides.template get<0, 1>() == 0) // a2 wrt b\n        {\n            if (res_b1_a2.distance <= res_b1_b2.distance\n                && same_direction(res_b1_a2.azimuth, res_b1_b2.azimuth))\n            {\n                lon = a2_lon;\n                lat = a2_lat;\n                dist_a1_ip = res_a1_a2.distance;\n                dist_b1_ip = res_b1_a2.distance;\n                ip_flag = ipi_at_a2;\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n        else if (sides.template get<1, 0>() == 0) // b1 wrt a\n        {\n            if (res_a1_b1.distance <= res_a1_a2.distance\n                && same_direction(res_a1_b1.azimuth, res_a1_a2.azimuth))\n            {\n                lon = b1_lon;\n                lat = b1_lat;\n                dist_a1_ip = res_a1_b1.distance;\n                dist_b1_ip = 0;\n                ip_flag = ipi_at_b1;\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n        else if (sides.template get<1, 1>() == 0) // b2 wrt a\n        {\n            if (res_a1_b2.distance <= res_a1_a2.distance\n                && same_direction(res_a1_b2.azimuth, res_a1_a2.azimuth))\n            {\n                lon = b2_lon;\n                lat = b2_lat;\n                dist_a1_ip = res_a1_b2.distance;\n                dist_b1_ip = res_b1_b2.distance;\n                ip_flag = ipi_at_b2;\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        // At this point neither the endpoints overlaps\n        // nor any andpoint lies on the other geodesic\n        // So the endpoints should lie on the opposite sides of both geodesics\n\n        bool const ok = formula::sjoberg_intersection<CalcT, FormulaPolicy::template inverse, Order>\n                        ::apply(a1_lon, a1_lat, a2_lon, a2_lat, res_a1_a2.azimuth,\n                                b1_lon, b1_lat, b2_lon, b2_lat, res_b1_b2.azimuth,\n                                lon, lat, spheroid);\n\n        if (! ok)\n        {\n            return false;\n        }\n\n        typedef typename FormulaPolicy::template inverse<CalcT, true, true, false, false, false> inverse_dist_azi;\n        typedef typename inverse_dist_azi::result_type inverse_result;\n\n        inverse_result const res_a1_ip = inverse_dist_azi::apply(a1_lon, a1_lat, lon, lat, spheroid);\n        dist_a1_ip = res_a1_ip.distance;\n        if (! same_direction(res_a1_ip.azimuth, res_a1_a2.azimuth))\n        {\n            dist_a1_ip = -dist_a1_ip;\n        }\n\n        bool is_on_a = segment_ratio<CalcT>(dist_a1_ip, dist_a1_a2).on_segment();\n        // NOTE: not fully consistent with equals_point_point() since radians are always used.\n        bool is_on_a1 = math::equals(lon, a1_lon) && math::equals(lat, a1_lat);\n        bool is_on_a2 = math::equals(lon, a2_lon) && math::equals(lat, a2_lat);\n\n        if (! (is_on_a || is_on_a1 || is_on_a2))\n        {\n            return false;\n        }\n\n        inverse_result const res_b1_ip = inverse_dist_azi::apply(b1_lon, b1_lat, lon, lat, spheroid);\n        dist_b1_ip = res_b1_ip.distance;\n        if (! same_direction(res_b1_ip.azimuth, res_b1_b2.azimuth))\n        {\n            dist_b1_ip = -dist_b1_ip;\n        }\n\n        bool is_on_b = segment_ratio<CalcT>(dist_b1_ip, dist_b1_b2).on_segment();\n        // NOTE: not fully consistent with equals_point_point() since radians are always used.\n        bool is_on_b1 = math::equals(lon, b1_lon) && math::equals(lat, b1_lat);\n        bool is_on_b2 = math::equals(lon, b2_lon) && math::equals(lat, b2_lat);\n\n        if (! (is_on_b || is_on_b1 || is_on_b2))\n        {\n            return false;\n        }\n        \n        ip_flag = ipi_inters;\n\n        if (is_on_b1)\n        {\n            lon = b1_lon;\n            lat = b1_lat;\n            dist_b1_ip = 0;\n            ip_flag = ipi_at_b1;\n        }\n        else if (is_on_b2)\n        {\n            lon = b2_lon;\n            lat = b2_lat;\n            dist_b1_ip = res_b1_b2.distance;\n            ip_flag = ipi_at_b2;\n        }\n\n        if (is_on_a1)\n        {\n            lon = a1_lon;\n            lat = a1_lat;\n            dist_a1_ip = 0;\n            ip_flag = ipi_at_a1;\n        }\n        else if (is_on_a2)\n        {\n            lon = a2_lon;\n            lat = a2_lat;\n            dist_a1_ip = res_a1_a2.distance;\n            ip_flag = ipi_at_a2;\n        }        \n\n        return true;\n    }\n\n    template <typename CalcT, typename P1, typename P2>\n    static inline bool is_endpoint_equal(CalcT const& dist,\n                                         P1 const& ai, P2 const& b1, P2 const& b2)\n    {\n        static CalcT const c0 = 0;\n        using geometry::detail::equals::equals_point_point;\n        return is_near(dist) && (equals_point_point(ai, b1) || equals_point_point(ai, b2) || math::equals(dist, c0));\n    }\n\n    template <typename CalcT>\n    static inline bool is_near(CalcT const& dist)\n    {\n        // NOTE: This strongly depends on the Inverse method\n        CalcT const small_number = CalcT(boost::is_same<CalcT, float>::value ? 0.0001 : 0.00000001);\n        return math::abs(dist) <= small_number;\n    }\n\n    template <typename ProjCoord1, typename ProjCoord2>\n    static inline int position_value(ProjCoord1 const& ca1,\n                                     ProjCoord2 const& cb1,\n                                     ProjCoord2 const& cb2)\n    {\n        // S1x  0   1    2     3   4\n        // S2       |---------->\n        return math::equals(ca1, cb1) ? 1\n             : math::equals(ca1, cb2) ? 3\n             : cb1 < cb2 ?\n                ( ca1 < cb1 ? 0\n                : ca1 > cb2 ? 4\n                : 2 )\n              : ( ca1 > cb1 ? 0\n                : ca1 < cb2 ? 4\n                : 2 );\n    }\n\n    template <typename CalcT>\n    static inline bool same_direction(CalcT const& azimuth1, CalcT const& azimuth2)\n    {\n        // distance between two angles normalized to (-180, 180]\n        CalcT const angle_diff = math::longitude_distance_signed<radian>(azimuth1, azimuth2);\n        return math::abs(angle_diff) <= math::half_pi<CalcT>();\n    }\n\n    template <int Which>\n    static inline void sides_reverse_segment(side_info & sides)\n    {\n        // names assuming segment A is reversed (Which == 0)\n        int a1_wrt_b = sides.template get<Which, 0>();\n        int a2_wrt_b = sides.template get<Which, 1>();\n        std::swap(a1_wrt_b, a2_wrt_b);\n        sides.template set<Which>(a1_wrt_b, a2_wrt_b);\n        int b1_wrt_a = sides.template get<1 - Which, 0>();\n        int b2_wrt_a = sides.template get<1 - Which, 1>();\n        sides.template set<1 - Which>(-b1_wrt_a, -b2_wrt_a);\n    }\n\n    static inline void ip_flag_reverse_segment(intersection_point_flag & ip_flag,\n                                               intersection_point_flag const& ipi_at_p1,\n                                               intersection_point_flag const& ipi_at_p2)\n    {\n        ip_flag = ip_flag == ipi_at_p1 ? ipi_at_p2 :\n                  ip_flag == ipi_at_p2 ? ipi_at_p1 :\n                  ip_flag;\n    }\n\nprivate:\n    Spheroid m_spheroid;\n};\n\n\n}} // namespace strategy::intersection\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_INTERSECTION_HPP\n", "meta": {"hexsha": "e91659d40e8dc17856b31e19781dbb2be04f4bcf", "size": 36044, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tether/boost/geometry/strategies/geographic/intersection.hpp", "max_stars_repo_name": "fictheader/fcolorwheel", "max_stars_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 918.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T02:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:21:35.000Z", "max_issues_repo_path": "tether/boost/geometry/strategies/geographic/intersection.hpp", "max_issues_repo_name": "fictheader/fcolorwheel", "max_issues_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 203.0, "max_issues_repo_issues_event_min_datetime": "2016-12-27T12:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:46:55.000Z", "max_forks_repo_path": "tether/boost/geometry/strategies/geographic/intersection.hpp", "max_forks_repo_name": "fictheader/fcolorwheel", "max_forks_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T17:38:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T14:25:49.000Z", "avg_line_length": 36.8925281474, "max_line_length": 157, "alphanum_fraction": 0.530185329, "num_tokens": 8874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.16623118694534675}}
{"text": "/*\n * Copyright 2016 Malte Splietker\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\n#include <boost/log/trivial.hpp>\n\n#include \"BrightnessNotifier.h\"\n\nBrightnessNotifier::BrightnessNotifier() {\n    display = XOpenDisplay(0);\n    screen = XRRGetScreenResources(display, DefaultRootWindow(display));\n}\n\nvoid BrightnessNotifier::notificationStart() {\n    oscillationStartTime = system_clock::now();\n}\n\nvoid BrightnessNotifier::notificationLoop() {\n    system_clock::time_point now = system_clock::now();\n    milliseconds diffTime = duration_cast<milliseconds>(now - oscillationStartTime);\n\n    /* Next oscillation wave */\n    if (diffTime.count() > oscillationIntervalLength * 1000) {\n        diffTime = milliseconds(0);\n        oscillationStartTime = system_clock::now();\n    }\n\n    double rad = (diffTime.count() / (oscillationIntervalLength * 1000)) * 2 * M_PI;\n    double newBrightness = 1 - (intensity / 2) + cos(rad) * (intensity / 2);\n    BOOST_LOG_TRIVIAL(debug) << \"new brightness: \" << newBrightness << std::endl;\n    setBrightness(newBrightness);\n}\n\nvoid BrightnessNotifier::notificationStop() {\n    setBrightness(1);\n}\n\ndouble BrightnessNotifier::getBrightness() {\n    double brightness = 0;\n\n    int size = XRRGetCrtcGammaSize(display, screen->crtcs[0]);\n\n    XRRCrtcGamma *gamma = XRRGetCrtcGamma(display, screen->crtcs[0]);\n\n    unsigned short *array = gamma->red;\n    int maxIndex = 0;\n    for (int i = size - 1; i > 0; i--) {\n        if (array[i] < 0xffff) {\n            maxIndex = i;\n            break;\n        }\n    }\n\n    int middle = maxIndex / 2;\n    double i1 = (double) (middle + 1) / size;\n    double v1 = (double) (array[middle]) / 65535;\n    double i2 = (double) (maxIndex + 1) / size;\n    double v2 = (double) (array[maxIndex]) / 65535;\n    if (v2 < 0.0001) { /* The screen is black */\n        brightness = 0;\n    } else {\n        if ((maxIndex + 1) == size)\n            brightness = v2;\n        else\n            brightness = exp((log(v2) * log(i1) - log(v1) * log(i2)) / log(i1 / i2));\n    }\n\n    XRRFreeGamma(gamma);\n\n    if (brightness > 1) {\n        brightness = 1;\n    }\n\n    return brightness;\n}\n\nvoid BrightnessNotifier::setBrightness(double brightness) {\n    if (brightness > 1) {\n        brightness = 1;\n    } else if (brightness < 0) {\n        brightness = 0;\n    }\n\n    for (int crtcIndex = 0; crtcIndex < screen->ncrtc; crtcIndex++) {\n        int size = XRRGetCrtcGammaSize(display, screen->crtcs[crtcIndex]);\n\n        XRRCrtcGamma *gamma = XRRAllocGamma(size);\n\n        for (int i = 0; i < size; i++) {\n            unsigned short gammaValue = (unsigned short) ((double) i / (double) (size - 1) * brightness * 65535.0);\n            gamma->red[i] = gammaValue;\n            gamma->green[i] = gammaValue;\n            gamma->blue[i] = gammaValue;\n        }\n\n        XRRSetCrtcGamma(display, screen->crtcs[crtcIndex], gamma);\n\n        free(gamma);\n    }\n}\n", "meta": {"hexsha": "0134d8540e44f7200786ee17c737aed3e65802e9", "size": 3434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ReFuel/src/BrightnessNotifier.cpp", "max_stars_repo_name": "splietker/ReFuel", "max_stars_repo_head_hexsha": "2345dc871c1c5d296cf8721b02574ed300cdd3d9", "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": "ReFuel/src/BrightnessNotifier.cpp", "max_issues_repo_name": "splietker/ReFuel", "max_issues_repo_head_hexsha": "2345dc871c1c5d296cf8721b02574ed300cdd3d9", "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": "ReFuel/src/BrightnessNotifier.cpp", "max_forks_repo_name": "splietker/ReFuel", "max_forks_repo_head_hexsha": "2345dc871c1c5d296cf8721b02574ed300cdd3d9", "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.8608695652, "max_line_length": 115, "alphanum_fraction": 0.6290040769, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.16623117660185693}}
{"text": "//\r\n// Copyright (c) 2018 Lo\u00efc HAMOT\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#include \"stdafx.h\"\r\n#include \"Skills.h\"\r\n#include \"Rules.h\"\r\n\r\n#include <boost/locale.hpp>\r\n\r\nsize_t powInt(size_t val, size_t power)\r\n{\r\n\treturn size_t(pow(val, power) + 0.5);\r\n}\r\n\r\n\r\n//! Skill non abstrait de rempacement, pour ceux qui ne sont pas encore cod\u00e9s\r\nclass DummySkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const&) const {return true;};\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const&) const\r\n\t{\r\n\t\treturn std::string();\r\n\t}\r\npublic:\r\n\t//! Constructeur\r\n\t//! @param name Nom du skill (avant traduction)\r\n\texplicit DummySkill(std::string const& name): ISkill(name) {}\r\n};\r\n\r\n//! Comp\u00e9tance Conquest\r\nclass ConquestSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const&) const {return true;};\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn (format(translate(\"You can create up to {1} planets.\")) %\r\n\t\t        getMaxPlanetCount(player)).str();\r\n\t}\r\npublic:\r\n\tConquestSkill(): ISkill(\"Conquest\") {}\r\n};\r\n\r\n//! Comp\u00e9tance Strategy\r\nclass StrategySkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const&) const {return true;};\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn (format(translate(\"You can create up to {1} fleets.\")) %\r\n\t\t        getMaxFleetCount(player)).str();\r\n\t}\r\npublic:\r\n\tStrategySkill(): ISkill(\"Strategy\") {}\r\n};\r\n\r\n//! Comp\u00e9tance Cohesion\r\nclass CohesionSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const&) const {return true;};\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn (format(translate(\"Your fleets can contains up to {1} ships.\")) %\r\n\t\t        getMaxFleetSize(player)).str();\r\n\t}\r\npublic:\r\n\tCohesionSkill(): ISkill(\"Cohesion\") {}\r\n};\r\n\r\n//! Comp\u00e9tance Service d'information\r\n//! @toto: tout\r\nclass InfoServiceSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& player) const\r\n\t{\r\n\t\treturn player.skilltab[Skill::InformationService] < 1;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& //player\r\n\t                                     ) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn translate(\"You can filter your messages\");\r\n\t}\r\npublic:\r\n\tInfoServiceSkill(): ISkill(\"InformationService\") {}\r\n};\r\n\r\n//! Comp\u00e9tance Ferme de serveur\r\nclass ServerFarmSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const&) const {return true;};\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn (format(translate(\"You can now store up to {1} events.\")) %\r\n\t\t        getMaxEventCount(player)).str();\r\n\t}\r\npublic:\r\n\tServerFarmSkill(): ISkill(\"ServerFarm\") {}\r\n};\r\n\r\n//! Comp\u00e9tance Chronos\r\nclass ChronosSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& player) const\r\n\t{\r\n\t\treturn player.skilltab[Skill::Chronos] < 1;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel\r\n\t                            ) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& //player\r\n\t                                     ) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn translate(\"You can use the \\\"age()\\\" procedure \"\r\n\t\t                 \"on your fleets and planets\");\r\n\t}\r\npublic:\r\n\tChronosSkill(): ISkill(\"Chronos\") {}\r\n};\r\n\r\n//! Comp\u00e9tance Memoire\r\nclass MemorySkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& //player\r\n\t                           ) const\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel + 1);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn (format(translate(\"Your store up to {1} items in the \\\"memory\\\"\"\r\n\t\t                         \" of your fleets and planets\")) %\r\n\t\t        memoryPtreeSize(player)).str();\r\n\t}\r\npublic:\r\n\tMemorySkill(): ISkill(\"Memory\") {}\r\n};\r\n\r\n\r\n//! Comp\u00e9tance Port\u00e9e d'Emition\r\nclass EmissionRangeSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& //player\r\n\t                           ) const\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(3, skillCurrentLevel + 1);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn (format(translate(\"Your messages can reachs up to {1} cases\")) %\r\n\t\t        playerEmissionRange(player)).str();\r\n\t}\r\npublic:\r\n\tEmissionRangeSkill() : ISkill(\"EmissionRange\") {}\r\n};\r\n\r\n\r\n//! Comp\u00e9tance Evasion\r\nclass EvasionSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& //player\r\n\t                           ) const\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\tsize_t const level = player.skilltab[Skill::Escape];\r\n\t\treturn (format(translate( //xgettext:no-c-format\r\n\t\t                 \"A fleet with {1} ships has 50% of probability to escape.\")) %\r\n\t\t        (level * level)).str();\r\n\t}\r\npublic:\r\n\tEvasionSkill(): ISkill(\"Evasion\") {}\r\n};\r\n\r\n\r\n//! Comp\u00e9tance Journal\r\nclass LogSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& player) const\r\n\t{\r\n\t\treturn player.skilltab[Skill::Log] < 1;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\tif(player.skilltab[Skill::Log])\r\n\t\t\treturn translate(\"You can use the \\\"log\\\" \"\r\n\t\t\t                 \"function to create custom events\");\r\n\t\telse\r\n\t\t\treturn translate(\"You can't use the \\\"log\\\" \"\r\n\t\t\t                 \"function to create custom events\");\r\n\t}\r\npublic:\r\n\tLogSkill() : ISkill(\"Log\") {}\r\n};\r\n\r\n\r\n//! Comp\u00e9tance Simulation\r\n//! @toto: tout\r\nclass SimulationSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& //player\r\n\t                           ) const\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel + 1);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\tif(player.skilltab[Skill::Simulation])\r\n\t\t\treturn (format(translate(\"Each call to \\\"simulates\\\" \"\r\n\t\t\t                         \"function process {1} simulations\")) %\r\n\t\t\t        playerFightSimulationCount(player)).str();\r\n\t\telse\r\n\t\t\treturn translate(\r\n\t\t\t         \"Each call to \\\"simulates\\\" function return false\");\r\n\t}\r\npublic:\r\n\tSimulationSkill() : ISkill(\"Simulation\") {}\r\n};\r\n\r\n//! Comp\u00e9tance Boite noir\r\nclass BlackBoxSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& player) const\r\n\t{\r\n\t\treturn player.skilltab[Skill::BlackBox] < 1;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel + 1);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn player.skilltab[Skill::BlackBox] == 0 ?\r\n\t\t       (format(translate(\"You can't receive fight report from destroyed fleets\"))).str() :\r\n\t\t       (format(translate(\"You receive fight report from destroyed fleets\"))).str();\r\n\t}\r\n\r\npublic:\r\n\tBlackBoxSkill() : ISkill(\"BlackBox\") {}\r\n};\r\n\r\n\r\n//! Comp\u00e9tance D\u00e9bit d'Emition\r\nclass EmissionRateSkill : public ISkill\r\n{\r\n\tvirtual bool canUpgradeImpl(Player const& //player\r\n\t                           ) const\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\tvirtual size_t skillCostImpl(size_t skillCurrentLevel) const\r\n\t{\r\n\t\treturn powInt(2, skillCurrentLevel + 2);\r\n\t}\r\n\tvirtual std::string effectMessageImpl(Player const& player) const\r\n\t{\r\n\t\tusing namespace boost::locale;\r\n\t\treturn (format(translate(\"Your messages emit up to {1} values per round\")) %\r\n\t\t        emitionPTreeSize(player)).str();\r\n\t}\r\npublic:\r\n\tEmissionRateSkill() : ISkill(\"EmissionRate\") {}\r\n};\r\n\r\n\r\n//! Initialise la liste de skill\r\nstd::vector<std::shared_ptr<ISkill> > InitSkills()\r\n{\r\n\tstd::vector<std::shared_ptr<ISkill> > list;\r\n\tlist.push_back(std::make_shared<ConquestSkill>());\r\n\tlist.push_back(std::make_shared<StrategySkill>());\r\n\tlist.push_back(std::make_shared<CohesionSkill>());\r\n\tlist.push_back(std::make_shared<InfoServiceSkill>());\r\n\tlist.push_back(std::make_shared<ServerFarmSkill>());\r\n\tlist.push_back(std::make_shared<ChronosSkill>());\r\n\tlist.push_back(std::make_shared<MemorySkill>());\r\n\tlist.push_back(std::make_shared<EmissionRangeSkill>());\r\n\tlist.push_back(std::make_shared<SimulationSkill>());\r\n\tlist.push_back(std::make_shared<BlackBoxSkill>());\r\n\tlist.push_back(std::make_shared<LogSkill>());\r\n\tlist.push_back(std::make_shared<EvasionSkill>());\r\n\tlist.push_back(std::make_shared<EmissionRateSkill>());\r\n\treturn list;\r\n};\r\n\r\nstd::vector<std::shared_ptr<ISkill> > const Skill::List = InitSkills();", "meta": {"hexsha": "f1487e0f71c4dbe4e0606392588a905f53ac2611", "size": 9924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Skills.cpp", "max_stars_repo_name": "lhamot/DroneWars", "max_stars_repo_head_hexsha": "6f457064395c61e37b8f2c162b7bec64ed6f277b", "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": "src/Skills.cpp", "max_issues_repo_name": "lhamot/DroneWars", "max_issues_repo_head_hexsha": "6f457064395c61e37b8f2c162b7bec64ed6f277b", "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/Skills.cpp", "max_forks_repo_name": "lhamot/DroneWars", "max_forks_repo_head_hexsha": "6f457064395c61e37b8f2c162b7bec64ed6f277b", "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.5172413793, "max_line_length": 93, "alphanum_fraction": 0.6724103184, "num_tokens": 2410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.23651623106411432, "lm_q1q2_score": 0.16615976138436986}}
{"text": "/**\n * Code to compute CNN (ImageNet) features for a given image using CAFFE\n * (c) Rohit Girdhar\n */\n\n#include <memory>\n#include <chrono>\n#include <algorithm>\n#include <opencv2/opencv.hpp>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp> // for to_lower\n#include \"caffe/caffe.hpp\"\n#include \"utils.hpp\"\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace caffe;\nusing namespace cv;\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\ntemplate<typename Dtype>\nvoid computeFeaturesPipeline(Net<Dtype>& caffe_test_net,\n    const vector<Mat>& Is,\n    const vector<string>& layers,\n    int BATCH_SIZE,\n    vector<vector<vector<Dtype>>>& output,\n    bool verbose,\n    const string& POOLTYPE,\n    bool NORMALIZE);\nvoid genSegImg(float xmin, float ymin, float xmax, float ymax, const Mat& S, Mat& res, int, int);\n\nint\nmain(int argc, char *argv[]) {\n  ::google::InitGoogleLogging(argv[0]);\n#ifdef CPU_ONLY\n  Caffe::set_mode(Caffe::CPU);\n  LOG(INFO) << \"Extracting Features in CPU mode\";\n#else\n  Caffe::set_mode(Caffe::GPU);\n#endif\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"Show this help\")\n    (\"loc-network-path,n\", po::value<string>()->required(),\n     \"Path to the localization prototxt file\")\n    (\"loc-model-path,m\", po::value<string>()->required(),\n     \"Path to localization caffemodel\")\n    (\"seg-network-path,p\", po::value<string>()->required(),\n     \"Path to the segmentation prototxt file\")\n    (\"seg-model-path,q\", po::value<string>()->required(),\n     \"Path to segmentation caffemodel\")\n    ;\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n  if (vm.count(\"help\")) {\n    LOG(INFO) << desc;\n    return -1;\n  }\n  try {\n    po::notify(vm);\n  } catch(po::error& e) {\n    LOG(ERROR) << e.what();\n    return -1;\n  }\n\n  fs::path LOC_NETWORK_PATH = fs::path(vm[\"loc-network-path\"].as<string>());\n  fs::path LOC_MODEL_PATH = \n    fs::path(vm[\"loc-model-path\"].as<string>());\n  fs::path SEG_NETWORK_PATH = fs::path(vm[\"seg-network-path\"].as<string>());\n  fs::path SEG_MODEL_PATH = \n    fs::path(vm[\"seg-model-path\"].as<string>());\n\n  Net<float> loc_caffe_test_net(LOC_NETWORK_PATH.string(), caffe::TEST);\n  loc_caffe_test_net.CopyTrainedLayersFrom(LOC_MODEL_PATH.string());\n  int LOC_BATCH_SIZE = loc_caffe_test_net.blob_by_name(\"data\")->num();\n  vector<string> loc_layers = {\"fc8_loc\"};\n  Net<float> seg_caffe_test_net(SEG_NETWORK_PATH.string(), caffe::TEST);\n  seg_caffe_test_net.CopyTrainedLayersFrom(SEG_MODEL_PATH.string());\n  int SEG_BATCH_SIZE = seg_caffe_test_net.blob_by_name(\"data\")->num();\n  vector<string> seg_layers = {\"fc8_seg\"};\n\n  string imgpath = \"/srv2/rgirdhar/Work/Datasets/processed/0006_ExtendedPAL/corpus/AbuSimbel/people_1.jpg\";\n  //string imgpath = \"/home/rgirdhar/memexdata/Dataset/processed/0001_Backpage/Images/corpus/ImagesTexas/Texas_2012_10_10_1349841918000_4_0.jpg\";\n  //string imgpath = \"/home/rgirdhar/memexdata/Dataset/processed/0001_Backpage/Images/corpus/ImagesTexas/Texas_2012_10_10_1349846732000_6_5.jpg\";\n  //string imgpath = \"/home/rgirdhar/memexdata/Dataset/processed/0001_Backpage/Images/corpus/ImagesCalifornia/California_image_2012_7_9_1341859695000_2_0.jpg\";\n  vector<Mat> Is;\n  Mat I = imread(imgpath);\n  if (!I.data) {\n    LOG(ERROR) << \"Unable to read \" << imgpath;\n    return -1;\n  }\n  resize(I, I, Size(256, 256));\n  Is.push_back(I);\n  // [layer[image[feature]]]\n  vector<vector<vector<float>>> loc_output;\n  computeFeaturesPipeline(loc_caffe_test_net, Is, loc_layers, \n      LOC_BATCH_SIZE, loc_output, /* verbose= */ false, \n      /* POOLTYPE= */ \"\", /* NORMALIZE= */ false);\n \n  float OFFSET = (256 - 227) / 2.0;\n  /*\n  loc_output[0][0][0] += OFFSET;\n  loc_output[0][0][1] += OFFSET;\n  loc_output[0][0][2] += OFFSET;\n  loc_output[0][0][3] += OFFSET;\n  */\n   \n  cout << loc_output[0][0][0] << \" \"\n       << loc_output[0][0][1] << \" \"\n       << loc_output[0][0][2] << \" \"\n       << loc_output[0][0][3];\n  \n  int width = I.cols;\n  int height = I.rows;\n  float xmin = std::min(width - 1.0f, std::max(0.0f, loc_output[0][0][0] + OFFSET));\n  float ymin = std::min(height - 1.0f, std::max(0.0f, loc_output[0][0][1] + OFFSET));\n  float xmax = std::min(width - 1.0f, std::max(0.0f, loc_output[0][0][2] + OFFSET));\n  float ymax = std::min(height - 1.0f, std::max(0.0f, loc_output[0][0][3] + OFFSET));\n\n  Rect roi(xmin,\n           ymin,\n           xmax - xmin,\n           ymax - ymin);\n  Mat T = I(roi);\n  resize(T, T, Size(55, 55));\n\n  caffe::BlobProto mean_blob_proto;\n  Mat mean;\n  caffe::ReadProtoFromBinaryFile(\"/home/rgirdhar/data/Work/Code/0005_ObjSegment/nips14_loc_seg_testonly/Caffe_Segmentation/segscripts/models/mean.binaryproto\", &mean_blob_proto);\n  caffe::Blob<unsigned int> mean_blob;\n  mean_blob.FromProto(mean_blob_proto);\n  convertBlobToMat(mean_blob, mean);\n  mean = mean(roi);\n  resize(mean, mean, Size(55, 55));\n  /*\n  double minEl, maxEl;\n  minMaxLoc(mean, &minEl, &maxEl);\n  cout << \" mx  \" << minEl << \" \" << maxEl << endl;\n  minMaxLoc(T, &minEl, &maxEl);\n  cout << \" mx  \" << minEl << \" \" << maxEl << endl;\n  */\n  \n  for (int c = 0; c < 3; c++) {\n    for (int h = 0; h < 55; h++) {\n      for (int w = 0; w < 55; w++) {\n        T.at<Vec3b>(h, w)[c] = (uint8_t) T.at<Vec3b>(h, w)[c] - mean.at<Vec3b>(h, w)[c];\n      }\n    }\n  }\n  \n\n  //T = T - mean;\n  flip(T, T, 1);\n//  cout << T;\n  imwrite(\"mean.jpg\", T);\n\n  vector<Mat> Ts;\n  Ts.push_back(T);\n  vector<vector<vector<float>>> seg_output;\n  computeFeaturesPipeline(seg_caffe_test_net, Ts, seg_layers, \n      SEG_BATCH_SIZE, seg_output, /* verbose= */ false, \n      /* POOLTYPE= */ \"\", /* NORMALIZE= */ false);\n  Mat Res(50, 50, CV_32FC1);\n  for (int i = 0; i < 50; i++) {\n    for (int j = 0; j < 50; j++) {\n      Res.at<float>(i, j) = seg_output[0][0][i * 50 + j];\n    }\n  }\n//  flip(Res, Res, 1);\n  Mat seg;\n  genSegImg(xmin, ymin, xmax, ymax, Res, seg, I.rows, I.cols);\n  Mat seg_uint;\n  seg.convertTo(seg_uint, CV_8UC1);\n  equalizeHist(seg_uint, seg_uint);\n  //resize(seg_uint, seg_uint, I.size());\n  imwrite(\"final.jpg\", seg_uint);\n  vector<Mat> channels(3);\n  split(I, channels);\n  divide(seg_uint, Scalar(255), seg_uint);\n  multiply(seg_uint, channels[0], channels[0]);\n  multiply(seg_uint, channels[1], channels[1]);\n  multiply(seg_uint, channels[2], channels[2]);\n  merge(channels, I);\n  // normalize(Res, Res, 0, 255, NORM_MINMAX, CV_8UC1);\n  \n  // equalizeHist(Res, Res);\n  imwrite(\"over.jpg\", I);\n  return 0;\n}\n\ntemplate<typename Dtype>\nvoid computeFeaturesPipeline(Net<Dtype>& caffe_test_net,\n    const vector<Mat>& Is,\n    const vector<string>& layers,\n    int BATCH_SIZE,\n    vector<vector<vector<Dtype>>>& output,\n    bool verbose,\n    const string& POOLTYPE,\n    bool NORMALIZE) {\n  computeFeatures(caffe_test_net, Is, layers, BATCH_SIZE, output, verbose);\n  if (! POOLTYPE.empty()) {\n    // assuming all layers need to be pooled\n    for (int l = 0; l < output.size(); l++) {\n      poolFeatures(output[l], POOLTYPE);\n    }\n  }\n  if (NORMALIZE) {\n    // assuming all layers need to be normalized\n    for (int i = 0; i < output.size(); i++) {\n      l2NormalizeFeatures(output[i]);\n    }\n  }\n}\n\nvoid genSegImg(float xmin, float ymin, float xmax, float ymax, const Mat& S, Mat& res,\n    int NW_IMG_HT, int NW_IMG_WID) {\n  res = Mat(NW_IMG_HT, NW_IMG_WID, CV_32FC1);\n  res.setTo(0);\n  int x1 = xmin;\n  int y1 = ymin;\n  int x2 = xmax;\n  int y2 = ymax;\n  int height = MAX(1, y2 - y1 + 1);\n  int width = MAX(1, x2 - x1 + 1);\n  Mat extractedImage = res(Rect(x1, y1, width, height));\n  Mat S2;\n  resize(S, S2, Size(width, height));\n  S2.copyTo(extractedImage);\n}\n\n", "meta": {"hexsha": "f5811e5ecb9ff25469eeddc6ca4b52cc17e08551", "size": 7675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ComputeFeatures/Features/CNN/Deploy/computeSegmentation.cpp", "max_stars_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_stars_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-04-13T21:40:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T11:32:31.000Z", "max_issues_repo_path": "ComputeFeatures/Features/CNN/Deploy/computeSegmentation.cpp", "max_issues_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_issues_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "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": "ComputeFeatures/Features/CNN/Deploy/computeSegmentation.cpp", "max_forks_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_forks_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "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.6595744681, "max_line_length": 178, "alphanum_fraction": 0.6485993485, "num_tokens": 2386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.16614737345508895}}
{"text": "\n// Copyright Henrik Steffen Ga\u00dfmann 2020.\n//\n// Distributed under the Boost Software License, Version 1.0.\n//         (See accompanying file LICENSE or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n\n#include <cstdint>\n\n#include <algorithm>\n#include <array>\n#include <compare>\n#include <type_traits>\n#include <utility>\n\n#include <boost/mp11/algorithm.hpp>\n\n#include <dplx/cncr/math_supplement.hpp>\n#include <dplx/cncr/type_utils.hpp>\n\n#include <dplx/dp/decoder/api.hpp>\n#include <dplx/dp/decoder/std_string.hpp>\n#include <dplx/dp/decoder/utils.hpp>\n#include <dplx/dp/detail/hash.hpp>\n#include <dplx/dp/detail/perfect_hash.hpp>\n#include <dplx/dp/detail/type_utils.hpp>\n#include <dplx/dp/fwd.hpp>\n#include <dplx/dp/layout_descriptor.hpp>\n#include <dplx/dp/object_def.hpp>\n#include <dplx/dp/tag_invoke.hpp>\n\nnamespace dplx::dp\n{\n\ninline constexpr struct property_id_hash_fn\n{\n    template <typename T>\n        requires tag_invocable<property_id_hash_fn, T const &>\n    constexpr auto operator()(T const &value) const\n            noexcept(nothrow_tag_invocable<property_id_hash_fn, T const &>)\n                    -> std::uint64_t\n    {\n        return cpo::tag_invoke(*this, value);\n    }\n    template <typename T>\n        requires tag_invocable<property_id_hash_fn, T const &, std::uint64_t>\n    constexpr auto operator()(T const &value, std::uint64_t seed) const\n            noexcept(nothrow_tag_invocable<property_id_hash_fn,\n                                           T const &,\n                                           std::uint64_t>) -> std::uint64_t\n    {\n        return cpo::tag_invoke(*this, value, seed);\n    }\n\n    template <cncr::integer T>\n    friend constexpr auto tag_invoke(property_id_hash_fn, T value) noexcept\n            -> std::uint64_t\n    {\n        return static_cast<std::uint64_t>(value);\n    }\n    template <cncr::integer T>\n    friend constexpr auto\n    tag_invoke(property_id_hash_fn, T value, std::uint64_t seed) noexcept\n            -> std::uint64_t\n    {\n        return detail::xxhash3(value, seed);\n    }\n\n    friend constexpr auto tag_invoke(property_id_hash_fn,\n                                     std::u8string_view str,\n                                     std::uint64_t const seed = 0) noexcept\n            -> std::uint64_t\n    {\n        return detail::fnvx_hash(str.data(), str.size(), seed);\n    }\n\n} property_id_hash;\n\ntemplate <std::size_t N, input_stream Stream>\nclass basic_decoder<fixed_u8string<N>, Stream>\n{\n    using parse = item_parser<Stream>;\n\npublic:\n    auto operator()(Stream &inStream, fixed_u8string<N> &out) const\n            -> result<void>\n    {\n        DPLX_TRY(parse::u8string_finite(inStream, out, N));\n        return oc::success();\n    }\n};\n\n} // namespace dplx::dp\n\nnamespace dplx::dp::detail\n{\n\ntemplate <std::size_t NumBits>\nconstexpr auto compress_bitset(std::initializer_list<bool> vs) noexcept\n{\n    constexpr auto digits = static_cast<std::size_t>(digits_v<std::size_t>);\n\n    constexpr auto numBuckets = cncr::div_ceil(NumBits, digits);\n    std::array<std::size_t, numBuckets> buckets{};\n\n    auto const *it = vs.begin();\n    auto const *const end = vs.end();\n    for (std::size_t shift = 0, offset = 0; it != end; ++it, ++shift)\n    {\n        if (shift == digits)\n        {\n            shift = 0;\n            offset += 1;\n        }\n\n        buckets[offset] |= static_cast<std::size_t>(*it) << shift;\n    }\n    return buckets;\n}\n\ntemplate <template <auto...> typename ObjectDefLike, auto... Properties>\nconstexpr auto\ncompress_optional_props(ObjectDefLike<Properties...> const &) noexcept\n{\n    return detail::compress_bitset<sizeof...(Properties)>(\n            {Properties.required...});\n}\n\ntemplate <auto const &descriptor>\ninline constexpr auto required_prop_mask_for\n        = detail::compress_optional_props(descriptor);\n\ninline constexpr std::size_t unknown_property_id = ~static_cast<std::size_t>(0);\n\ntemplate <typename IdType, std::size_t NumIds, bool use_perfect_hash>\nstruct property_id_lookup_fn;\n\ntemplate <typename IdType, std::size_t NumIds>\nstruct property_id_lookup_fn<IdType, NumIds, true>\n{\nprivate:\n    using id_type = IdType;\n    using array_type = std::array<id_type, NumIds>;\n\n    perfect_hasher<id_type, NumIds, property_id_hash_fn> hash;\n    array_type const &ids;\n\npublic:\n    constexpr property_id_lookup_fn(array_type const &ids)\n        : hash(ids)\n        , ids(ids)\n    {\n    }\n\n    template <typename TLike>\n    constexpr auto operator()(TLike &&id) const noexcept -> std::size_t\n    {\n        std::size_t const idx = hash(id);\n        if (ids[idx] != id)\n        {\n            return unknown_property_id;\n        }\n        return idx;\n    }\n};\n\ntemplate <typename IdType, std::size_t NumIds>\nstruct property_id_lookup_fn<IdType, NumIds, false>\n{\nprivate:\n    using id_type = IdType;\n    using array_type = std::array<id_type, NumIds>;\n\n    array_type const &ids;\n\npublic:\n    constexpr property_id_lookup_fn(array_type const &ids)\n        : ids(ids)\n    {\n    }\n\n    template <typename TLike>\n    constexpr auto operator()(TLike &&id) const noexcept -> std::size_t\n    {\n        auto const *const begin = ids.data();\n        auto const *const end = ids.data() + ids.size();\n        id_type const *it;\n        if constexpr (NumIds <= 64)\n        {\n            if (it = std::find(begin, end, id); it == end)\n            {\n                return unknown_property_id;\n            }\n        }\n        else\n        {\n            if (it = std::lower_bound(begin, end, id); it == end || *it != id)\n            {\n                return unknown_property_id;\n            }\n        }\n        return static_cast<std::size_t>(it - begin);\n    }\n};\n\ntemplate <auto const &Descriptor, typename T, input_stream Stream>\nclass decode_object_property_fn\n{\n    static constexpr auto const &descriptor = Descriptor;\n    static constexpr auto ids = descriptor.ids;\n    static constexpr std::size_t const num_prop_ids = descriptor.ids.size();\n\n#if DPLX_DP_WORKAROUND(DPLX_COMP_GNUC, <=, 10, 1, 0)\n    // fixed_u8string id comparison operator is borked\n#else\n    static_assert(std::is_sorted(descriptor.ids.begin(), descriptor.ids.end()));\n#endif\n\n    using odef_type = cncr::remove_cref_t<decltype(descriptor)>;\n    using id_type = typename odef_type::id_type;\n    using id_runtime_type = typename odef_type::id_runtime_type;\n\n    static constexpr property_id_lookup_fn<id_type,\n                                           descriptor.ids.size(),\n                                           false>\n            lookup{descriptor.ids};\n\n    using decode_value_fn = mp_decode_value_fn<T, Stream>;\n\n    struct decode_prop_fn : public decode_value_fn\n    {\n        template <std::size_t I>\n        auto operator()(boost::mp11::mp_size_t<I>) -> result<std::size_t>\n        {\n            constexpr auto &propertyDef = descriptor.template property<I>();\n            DPLX_TRY(decode_value_fn::operator()(propertyDef));\n            return I;\n        }\n    };\n\npublic:\n    auto operator()(Stream &inStream, T &dest) const -> result<std::size_t>\n    {\n        DPLX_TRY(auto &&id, decode(as_value<id_runtime_type>, inStream));\n\n        auto const idx = lookup(id);\n        if (idx == unknown_property_id)\n        {\n            return errc::unknown_property;\n        }\n\n        return boost::mp11::mp_with_index<num_prop_ids>(\n                idx, decode_prop_fn{{inStream, dest}});\n    }\n};\n\ntemplate <auto const &Descriptor, typename T, input_stream Stream>\ninline constexpr decode_object_property_fn<Descriptor, T, Stream>\n        decode_object_property{};\n\ntemplate <typename T>\nconstexpr auto index_of_limit(T const *elems,\n                              std::size_t const num,\n                              T const limit) noexcept -> std::size_t\n{\n    for (std::size_t i = 0; i < num; ++i)\n    {\n        if (elems[i] >= limit)\n        {\n            return i;\n        }\n    }\n    return num;\n}\n\ntemplate <auto const &descriptor, typename T, input_stream Stream>\n    requires cncr::unsigned_integer<\n            typename cncr::remove_cref_t<decltype(descriptor)>::id_type>\nclass decode_object_property_fn<descriptor, T, Stream>\n{\n    using parse = item_parser<Stream>;\n    using descriptor_type = cncr::remove_cref_t<decltype(descriptor)>;\n    using id_type = typename descriptor_type::id_type;\n\n#if DPLX_DP_WORKAROUND(DPLX_COMP_GNUC, <=, 10, 1, 0)\n    // fixed_u8string id comparison operator is borked\n#else\n    static_assert(std::is_sorted(descriptor.ids.begin(), descriptor.ids.end()));\n#endif\n    static_assert(detail::digits_v<id_type> <= detail::digits_v<std::uint64_t>);\n\n    static constexpr id_type small_id_limit = detail::inline_value_max + 1;\n    static constexpr auto small_ids_end = detail::index_of_limit(\n            descriptor.ids.data(), descriptor.ids.size(), small_id_limit);\n\n    static constexpr std::size_t id_map_size\n            = descriptor.ids.size() - small_ids_end;\n\n    static constexpr auto copy_large_ids() noexcept\n            -> std::array<id_type, id_map_size>\n    {\n        std::array<id_type, id_map_size> ids{};\n        for (std::size_t i = 0; i < id_map_size; ++i)\n        {\n            ids[i] = descriptor.ids[i + small_ids_end];\n        }\n        return ids;\n    }\n    static constexpr auto large_ids = copy_large_ids();\n    static constexpr property_id_lookup_fn<id_type, id_map_size, false> lookup{\n            large_ids};\n\n    using decode_value_fn = mp_decode_value_fn<T, Stream>;\n\n    struct decode_prop_small_id_fn : decode_value_fn\n    {\n        template <std::size_t I>\n        auto operator()(boost::mp11::mp_size_t<I>) -> result<std::size_t>\n        {\n            constexpr auto propPos = static_cast<std::size_t>(\n                    std::find(descriptor.ids.data(),\n                              descriptor.ids.data() + small_ids_end,\n                              static_cast<id_type>(I))\n                    - descriptor.ids.data());\n\n            if constexpr (propPos == small_ids_end)\n            {\n                return errc::unknown_property;\n            }\n            else\n            {\n                constexpr auto &propertyDef\n                        = descriptor.template property<propPos>();\n                DPLX_TRY(decode_value_fn::operator()(propertyDef));\n                return propPos;\n            }\n        }\n    };\n\n    struct decode_prop_large_id_fn : public decode_value_fn\n    {\n        template <std::size_t I>\n        auto operator()(boost::mp11::mp_size_t<I>) -> result<std::size_t>\n        {\n            constexpr auto &propertyDef\n                    = descriptor.template property<I + small_ids_end>();\n            DPLX_TRY(decode_value_fn::operator()(propertyDef));\n            return I + small_ids_end;\n        }\n    };\n\npublic:\n    auto operator()(Stream &inStream, T &dest) const -> result<std::size_t>\n    {\n        DPLX_TRY(auto id, parse::template integer<id_type>(inStream));\n\n        if (id < small_id_limit)\n        {\n            if constexpr (small_ids_end == 0)\n            {\n                return errc::unknown_property;\n            }\n            else\n            {\n                return boost::mp11::mp_with_index<small_id_limit>(\n                        static_cast<std::size_t>(id),\n                        decode_prop_small_id_fn{{inStream, dest}});\n            }\n        }\n        else\n        {\n            if constexpr (small_ids_end == descriptor.ids.size())\n            {\n                return errc::unknown_property;\n            }\n            else\n            {\n                auto const idx = lookup(static_cast<id_type>(id));\n                if (idx == unknown_property_id)\n                {\n                    return errc::unknown_property;\n                }\n\n                return boost::mp11::mp_with_index<id_map_size>(\n                        idx, decode_prop_large_id_fn{{inStream, dest}});\n            }\n        }\n    }\n};\n\n} // namespace dplx::dp::detail\n\nnamespace dplx::dp\n{\n\nstruct object_head_info\n{\n    std::int32_t num_properties;\n    std::uint32_t version;\n};\n\ntemplate <input_stream Stream, bool isVersioned = true>\ninline auto parse_object_head(Stream &inStream,\n                              std::bool_constant<isVersioned> = {})\n        -> result<object_head_info>\n{\n    using parse = item_parser<Stream>;\n    DPLX_TRY(auto &&mapInfo, parse::generic(inStream));\n    if (mapInfo.type != type_code::map || mapInfo.indefinite())\n    {\n        return errc::item_type_mismatch;\n    }\n    if (mapInfo.value == 0)\n    {\n        return object_head_info{0, null_def_version};\n    }\n\n    DPLX_TRY(auto &&remainingBytes, dp::available_input_size(inStream));\n    // every prop consists of two items each being at least 1B big\n    if (mapInfo.value > (remainingBytes / 2))\n    {\n        return errc::end_of_stream;\n    }\n    if (mapInfo.value >= static_cast<std::uint64_t>(\n                std::numeric_limits<std::int32_t>::max() / 2))\n    {\n        return errc::too_many_properties;\n    }\n    auto numProps = static_cast<std::int32_t>(mapInfo.value);\n\n    if constexpr (!isVersioned)\n    {\n        return object_head_info{numProps, null_def_version};\n    }\n    else\n    {\n        // the version property id is posint 0\n        // and always encoded as a single byte\n        DPLX_TRY(auto &&maybeVersionReadProxy, dp::read(inStream, 1));\n        if (std::ranges::data(maybeVersionReadProxy)[0] != std::byte{})\n        {\n            DPLX_TRY(dp::consume(inStream, maybeVersionReadProxy, 0));\n            return object_head_info{numProps, null_def_version};\n        }\n\n        if constexpr (dp::lazy_input_stream<Stream>)\n        {\n            DPLX_TRY(dp::consume(inStream, maybeVersionReadProxy));\n        }\n\n        // 0xffff'ffff => max() is reserved as null_def_version\n        DPLX_TRY(auto version, parse::template integer<std::uint32_t>(\n                                       inStream, 0xffff'fffeU));\n\n        return object_head_info{numProps - 1, version};\n    }\n}\n\ntemplate <auto const &descriptor, typename T, input_stream Stream>\ninline auto decode_object_property(Stream &stream, T &dest)\n        -> result<std::size_t>\n{\n    return detail::decode_object_property<descriptor, T, Stream>(stream, dest);\n}\n\ntemplate <auto const &descriptor, typename T, input_stream Stream>\ninline auto decode_object_properties(Stream &stream,\n                                     T &dest,\n                                     std::int32_t numProperties) -> result<void>\n{\n    constexpr auto &decode_object_property\n            = detail::decode_object_property<descriptor, T, Stream>;\n\n    if constexpr (descriptor.has_optional_properties)\n    {\n        std::array<std::size_t,\n                   detail::required_prop_mask_for<descriptor>.size()>\n                foundProps{};\n\n        for (std::int32_t i = 0; i < numProperties; ++i)\n        {\n            DPLX_TRY(auto &&which, decode_object_property(stream, dest));\n\n            auto const offset = which / detail::digits_v<std::size_t>;\n            auto const shift = which % detail::digits_v<std::size_t>;\n\n            foundProps[offset] |= static_cast<std::size_t>(1) << shift;\n        }\n\n        std::size_t acc = 0;\n        for (std::size_t i = 0; i < foundProps.size(); ++i)\n        {\n            auto const requiredProps\n                    = detail::required_prop_mask_for<descriptor>[i];\n\n            acc += (foundProps[i] & requiredProps) == requiredProps;\n        }\n        if (acc != foundProps.size())\n        {\n            return errc::required_object_property_missing;\n        }\n    }\n    else\n    {\n        if (descriptor.num_properties != numProperties)\n        {\n            return errc::required_object_property_missing;\n        }\n\n        for (std::int32_t i = 0; i < numProperties; ++i)\n        {\n            DPLX_TRY(decode_object_property(stream, dest));\n        }\n    }\n    return success();\n}\n\ntemplate <packable_object T, input_stream Stream>\n    requires(detail::versioned_decoder_enabled(layout_descriptor_for_v<T>))\nclass basic_decoder<T, Stream>\n{\npublic:\n    auto operator()(Stream &inStream, T &dest) const -> result<void>\n    {\n        DPLX_TRY(\n                auto &&headInfo,\n                dp::parse_object_head<Stream, layout_descriptor_for_v<T>.version\n                                                      != null_def_version>(\n                        inStream));\n\n        if constexpr (layout_descriptor_for_v<T>.version != null_def_version)\n        {\n            if (layout_descriptor_for_v<T>.version != headInfo.version)\n            {\n                return errc::item_version_mismatch;\n            }\n        }\n\n        return dp::decode_object_properties<layout_descriptor_for_v<T>, T,\n                                            Stream>(inStream, dest,\n                                                    headInfo.num_properties);\n    }\n};\n\n} // namespace dplx::dp\n", "meta": {"hexsha": "df155cf85a778f99010e5890c23704a0b5979b66", "size": 16775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dplx/dp/decoder/object_utils.hpp", "max_stars_repo_name": "deeplex/deeppack", "max_stars_repo_head_hexsha": "0a94f61ee441eba7f0b280d2493505860c5b89cd", "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/dplx/dp/decoder/object_utils.hpp", "max_issues_repo_name": "deeplex/deeppack", "max_issues_repo_head_hexsha": "0a94f61ee441eba7f0b280d2493505860c5b89cd", "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/dplx/dp/decoder/object_utils.hpp", "max_forks_repo_name": "deeplex/deeppack", "max_forks_repo_head_hexsha": "0a94f61ee441eba7f0b280d2493505860c5b89cd", "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.6113138686, "max_line_length": 80, "alphanum_fraction": 0.5977943368, "num_tokens": 3870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.16614737345508895}}
{"text": "/********************************************************************************\nCopyright (c) 2015, TRACLabs, Inc.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\n 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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n********************************************************************************/\n\n\n#include <trac_ik/trac_ik.hpp>\n#include <boost/date_time.hpp>\n#include <boost/make_shared.hpp>\n#include <Eigen/Geometry>\n#include <ros/ros.h>\n#include <limits>\n\nnamespace TRAC_IK {\n\n  TRAC_IK::TRAC_IK(const KDL::Chain& _chain, const KDL::JntArray& _q_min, const KDL::JntArray& _q_max, double _maxtime, double _eps, SolveType _type):\n    chain(_chain),\n    jacsolver(_chain),\n    eps(_eps),\n    maxtime(_maxtime),\n    solvetype(_type),\n    nl_solver(chain,_q_min,_q_max,maxtime,eps, NLOPT_IK::SumSq),\n    iksolver(chain,_q_min,_q_max,maxtime,eps,true,true),\n    work(io_service)\n  {\n\n\n    assert(chain.getNrOfJoints()==_q_min.data.size());\n    assert(chain.getNrOfJoints()==_q_max.data.size());\n\n    for (uint i=0; i<chain.getNrOfJoints(); i++) {\n      lb.push_back(_q_min(i));\n      ub.push_back(_q_max(i));\n    }\n\n    for (uint i=0; i<chain.segments.size(); i++) {\n      std::string type = chain.segments[i].getJoint().getTypeName();\n      if (type.find(\"Rot\")!=std::string::npos) {\n        if ((_q_max(types.size())==0 && _q_min(types.size())==0) ||\n            (_q_max(types.size())>=std::numeric_limits<float>::max() && \n             _q_min(types.size())<=-std::numeric_limits<float>::max()))\n          types.push_back(KDL::BasicJointType::Continuous);\n        else\n          types.push_back(KDL::BasicJointType::RotJoint);\n      }\n      else if (type.find(\"Trans\")!=std::string::npos)\n        types.push_back(KDL::BasicJointType::TransJoint);\n    }\n    \n    assert(types.size()==lb.size());\n\n\n    threads.create_thread(boost::bind(&boost::asio::io_service::run,\n                                      &io_service));\n    threads.create_thread(boost::bind(&boost::asio::io_service::run,\n                                      &io_service));\n\n  }\n\n  bool TRAC_IK::unique_solution(const KDL::JntArray& sol) {\n\n    for (uint i=0; i< solutions.size(); i++)\n      if (myEqual(sol,solutions[i]))\n        return false;\n    return true;\n\n  }\n\n  bool TRAC_IK::runKDL(const KDL::JntArray &q_init, const KDL::Frame &p_in)\n  {\n    KDL::JntArray q_out;\n\n    double fulltime = maxtime;\n    KDL::JntArray seed = q_init;\n\n    boost::posix_time::time_duration timediff;\n    double time_left;\n\n    while (true) {\n      timediff=boost::posix_time::microsec_clock::local_time()-start_time;\n      time_left = fulltime - timediff.total_nanoseconds()/1000000000.0;\n\n      if (time_left <= 0)\n        break;\n\n      iksolver.setMaxtime(time_left);\n\n      int kdlRC = iksolver.CartToJnt(seed,p_in,q_out,bounds);\n      if (kdlRC >=0) {\n        switch (solvetype) {\n        case Manip1:\n        case Manip2:\n          normalize_limits(q_init, q_out);\n          break;\n        default:\n          normalize_seed(q_init, q_out);\n          break;\n        }\n        mtx_.lock();\n        if (unique_solution(q_out)) {\n          solutions.push_back(q_out);\n          uint curr_size=solutions.size();\n          errors.resize(curr_size);\n          mtx_.unlock();\n          double err, penalty;\n          switch (solvetype) {\n          case Manip1:\n            penalty = manipPenalty(q_out);\n            err = penalty*TRAC_IK::ManipValue1(q_out);\n            break;\n          case Manip2:\n            penalty = manipPenalty(q_out);\n            err = penalty*TRAC_IK::ManipValue2(q_out);\n            break;\n          default:\n            err = TRAC_IK::JointErr(q_init,q_out);\n            break;\n          }\n          mtx_.lock();\n          errors[curr_size-1] = std::make_pair(err,curr_size-1);\n        }\n        mtx_.unlock();\n      }\n      \n      if (!solutions.empty() && solvetype == Speed)\n        break;\n      \n      for (unsigned int j=0; j<seed.data.size(); j++)\n        if (types[j]==KDL::BasicJointType::Continuous)\n          seed(j)=fRand(q_init(j)-2*M_PI, q_init(j)+2*M_PI);\n        else\n          seed(j)=fRand(lb[j], ub[j]);\n    }\n    nl_solver.abort();\n\n    iksolver.setMaxtime(fulltime);\n\n    return true;\n  }\n\n  bool TRAC_IK::runNLOPT(const KDL::JntArray &q_init, const KDL::Frame &p_in)\n  {\n    KDL::JntArray q_out;\n\n    double fulltime = maxtime;\n    KDL::JntArray seed = q_init;\n\n    boost::posix_time::time_duration timediff;\n    double time_left;\n\n    while (true) {\n      timediff=boost::posix_time::microsec_clock::local_time()-start_time;\n      time_left = fulltime - timediff.total_nanoseconds()/1000000000.0;\n\n      if (time_left <= 0)\n        break;\n\n      nl_solver.setMaxtime(time_left);\n\n      int nloptRC = nl_solver.CartToJnt(seed,p_in,q_out,bounds);\n      if (nloptRC >=0) {\n        switch (solvetype) {\n        case Manip1:\n        case Manip2:\n          normalize_limits(q_init, q_out);\n          break;\n        default:\n          normalize_seed(q_init, q_out);\n          break;\n        }\n        mtx_.lock();\n        if (unique_solution(q_out)) {\n          solutions.push_back(q_out);\n          uint curr_size=solutions.size();\n          errors.resize(curr_size);\n          mtx_.unlock();\n          double err, penalty;\n          switch (solvetype) {\n          case Manip1:\n            penalty = manipPenalty(q_out);\n            err = penalty*TRAC_IK::ManipValue1(q_out);\n            break;\n          case Manip2:\n            penalty = manipPenalty(q_out);\n            err = penalty*TRAC_IK::ManipValue2(q_out);\n            break;\n          default:\n            err = TRAC_IK::JointErr(q_init,q_out);\n            break;\n          }\n          mtx_.lock();\n          errors[curr_size-1] = std::make_pair(err,curr_size-1);\n        }\n        mtx_.unlock();\n      }\n      \n      if (!solutions.empty() && solvetype == Speed)\n        break;\n      \n      for (unsigned int j=0; j<seed.data.size(); j++)\n        if (types[j]==KDL::BasicJointType::Continuous)\n          seed(j)=fRand(q_init(j)-2*M_PI, q_init(j)+2*M_PI);\n        else\n          seed(j)=fRand(lb[j], ub[j]);\n    }\n\n    iksolver.abort();\n\n    nl_solver.setMaxtime(fulltime);\n\n    return true;\n  }\n\n  void TRAC_IK::normalize_seed(const KDL::JntArray& seed, KDL::JntArray& solution) {\n    // Make sure rotational joint values are within 1 revolution of seed; then\n    // ensure joint limits are met.\n\n    bool improved = false;\n\n    for (uint i=0; i<lb.size(); i++) {\n\n      if (types[i]==KDL::BasicJointType::TransJoint)\n        continue;\n\n      double target = seed(i);\n      double val = solution(i);\n\n      if (val > target+M_PI) {\n        //Find actual angle offset\n        double diffangle = fmod(val-target,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = target + diffangle - 2*M_PI;\n      }\n\n      if (val < target-M_PI) {\n        //Find actual angle offset\n        double diffangle = fmod(target-val,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = target - diffangle + 2*M_PI;\n      }\n\n      if (types[i]==KDL::BasicJointType::Continuous) {\n        solution(i) = val;\n        continue;\n      }\n\n      if (val > ub[i]) {\n        //Find actual angle offset\n        double diffangle = fmod(val-ub[i],2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = ub[i] + diffangle - 2*M_PI;\n      }\n\n      if (val < lb[i]) {\n        //Find actual angle offset\n        double diffangle = fmod(lb[i]-val,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = lb[i] - diffangle + 2*M_PI;\n      }\n\n      solution(i) = val;\n    }\n  }\n\n  void TRAC_IK::normalize_limits(const KDL::JntArray& seed, KDL::JntArray& solution) {\n    // Make sure rotational joint values are within 1 revolution of middle of\n    // limits; then ensure joint limits are met.\n\n    bool improved = false;\n\n    for (uint i=0; i<lb.size(); i++) {\n\n      if (types[i] == KDL::BasicJointType::TransJoint)\n        continue;\n\n      double target = seed(i);\n\n      if (types[i] == KDL::BasicJointType::RotJoint)\n        target = (ub[i]+lb[i])/2.0;\n\n      double val = solution(i);\n\n      if (val > target+M_PI) {\n        //Find actual angle offset\n        double diffangle = fmod(val-target,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = target + diffangle - 2*M_PI;\n      }\n\n      if (val < target-M_PI) {\n        //Find actual angle offset\n        double diffangle = fmod(target-val,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = target - diffangle + 2*M_PI;\n      }\n\n      if (types[i]==KDL::BasicJointType::Continuous) {\n        solution(i) = val;\n        continue;\n      }\n\n      if (val > ub[i]) {\n        //Find actual angle offset\n        double diffangle = fmod(val-ub[i],2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = ub[i] + diffangle - 2*M_PI;\n      }\n\n      if (val < lb[i]) {\n        //Find actual angle offset\n        double diffangle = fmod(lb[i]-val,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = lb[i] - diffangle + 2*M_PI;\n      }\n\n      solution(i) = val;\n    }\n\n  }\n\n\n  double TRAC_IK::manipPenalty(const KDL::JntArray& arr) {\n    double penalty = 1.0;\n    for (uint i=0; i< arr.data.size(); i++) {\n      if (types[i] == KDL::BasicJointType::Continuous)\n        continue;\n      double range = ub[i]-lb[i];\n      penalty *= ((arr(i)-lb[i])*(ub[i]-arr(i))/(range*range));\n    }\n    return (1.0 - exp(-1*penalty));\n  }\n\n\n  double TRAC_IK::ManipValue1(const KDL::JntArray& arr) {\n    KDL::Jacobian jac(arr.data.size());\n\n    jacsolver.JntToJac(arr,jac);\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svdsolver(jac.data);\n    Eigen::MatrixXd singular_values = svdsolver.singularValues();\n\n    double error = 1.0;\n    for(unsigned int i=0; i < singular_values.rows(); ++i)\n      error *= singular_values(i,0);\n    return error;\n  }\n\n  double TRAC_IK::ManipValue2(const KDL::JntArray& arr) {\n    KDL::Jacobian jac(arr.data.size());\n\n    jacsolver.JntToJac(arr,jac);\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svdsolver(jac.data);\n    Eigen::MatrixXd singular_values = svdsolver.singularValues();\n\n    return singular_values.minCoeff()/singular_values.maxCoeff();\n  }\n\n\n  int TRAC_IK::CartToJnt(const KDL::JntArray &q_init, const KDL::Frame &p_in, KDL::JntArray &q_out, const KDL::Twist& _bounds) {\n\n    static uint calls =0;\n    static uint inconsistent =0;\n\n    start_time = boost::posix_time::microsec_clock::local_time();\n\n    nl_solver.reset();\n    iksolver.reset();\n\n    solutions.clear();\n    errors.clear();\n\n\n    bounds=_bounds;\n\n    std::vector<boost::shared_future<bool> > pending_data;\n\n    typedef boost::packaged_task<bool> task_t;\n    boost::shared_ptr<task_t> task1 = boost::make_shared<task_t>(boost::bind(&TRAC_IK::runKDL, this, boost::cref(q_init), boost::cref(p_in)));\n\n    boost::shared_ptr<task_t> task2 = boost::make_shared<task_t>(boost::bind(&TRAC_IK::runNLOPT, this, boost::cref(q_init), boost::cref(p_in)));\n\n    boost::shared_future<bool> fut1(task1->get_future());\n    boost::shared_future<bool> fut2(task2->get_future());\n\n    /*\n    // this was for pre-c++11\n    pending_data.push_back(boost::move(fut1));\n    pending_data.push_back(boost::move(fut2));\n    */\n    pending_data.push_back(fut1);\n    pending_data.push_back(fut2);\n\n    io_service.post(boost::bind(&task_t::operator(), task1));\n    io_service.post(boost::bind(&task_t::operator(), task2));\n\n    boost::wait_for_all(pending_data.begin(), pending_data.end());\n\n    if (solutions.empty()) {\n      q_out=q_init;\n      return -3;\n    }\n\n    switch (solvetype) {\n    case Manip1:\n    case Manip2:\n      std::sort(errors.rbegin(),errors.rend()); // rbegin/rend to sort by max\n      break;\n    default:\n      std::sort(errors.begin(),errors.end());\n      break;\n    }\n\n    q_out = solutions[errors[0].second];\n\n    return solutions.size();\n  }\n\n\n  TRAC_IK::~TRAC_IK(){\n    // Force all threads to return from io_service::run().\n    io_service.stop();\n\n    // Suppress all exceptions.\n    try\n      {\n        threads.join_all();\n      }\n    catch ( ... ) {}\n\n  }\n\n}\n", "meta": {"hexsha": "c6366bd14e32e04e34f88350c33a0c543f98ebf0", "size": 13557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vector_common/vector_third_party/trac_ik/trac_ik_lib/src/trac_ik.cpp", "max_stars_repo_name": "PeterMitrano/vector_v1", "max_stars_repo_head_hexsha": "2cea9b4b1f2f59ab4d97abf8b3c9f9c6ab93d514", "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": "vector_common/vector_third_party/trac_ik/trac_ik_lib/src/trac_ik.cpp", "max_issues_repo_name": "PeterMitrano/vector_v1", "max_issues_repo_head_hexsha": "2cea9b4b1f2f59ab4d97abf8b3c9f9c6ab93d514", "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": "vector_common/vector_third_party/trac_ik/trac_ik_lib/src/trac_ik.cpp", "max_forks_repo_name": "PeterMitrano/vector_v1", "max_forks_repo_head_hexsha": "2cea9b4b1f2f59ab4d97abf8b3c9f9c6ab93d514", "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.5359477124, "max_line_length": 150, "alphanum_fraction": 0.6027144649, "num_tokens": 3522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.16608550591432467}}
{"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\u00e4nkt), 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_MATRIX_UMFPACK_SOLVE_INCLUDE\n#define MTL_MATRIX_UMFPACK_SOLVE_INCLUDE\n\n#ifdef MTL_HAS_UMFPACK\n\n#include <iostream>\n\n\n#include <cassert>\n#include <algorithm>\n#include <boost/mpl/bool.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/make_copy_or_reference.hpp>\n#include <boost/numeric/mtl/operation/merge_complex_vector.hpp>\n#include <boost/numeric/mtl/operation/split_complex_vector.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nextern \"C\" {\n#  include <umfpack.h>\n}\n\nnamespace mtl { namespace matrix {\n\n    /// Namespace for Umfpack solver\n    namespace umfpack {\n\n\t// conversion for value_type needed if not double or complex<double> (where possible)\n\ttemplate <typename Value> struct value         \t    {};\n\ttemplate<> struct value<long double>           \t    { typedef double               type; };\n\ttemplate<> struct value<double>                \t    { typedef double               type; };\n\ttemplate<> struct value<float>                 \t    { typedef double               type; };\n\ttemplate<> struct value<std::complex<long double> > { typedef std::complex<double> type; };\n\ttemplate<> struct value<std::complex<double> > \t    { typedef std::complex<double> type; };\n\ttemplate<> struct value<std::complex<float> >  \t    { typedef std::complex<double> type; };\n\n\ttemplate <typename Value> struct use_long { static const bool value= sizeof(Value) > sizeof(int); };\n\n\ttemplate <bool Larger> struct index_aux   { typedef int     type; };\n#if defined(UF_long)\n\ttemplate<> struct index_aux<true>         { typedef UF_long type; };\n#elif defined(SuiteSparse_long)\n\ttemplate<> struct index_aux<true>         { typedef SuiteSparse_long type; };\n#else\n\ttemplate<> struct index_aux<true>         { typedef long type; };\n#endif\n\n\ttemplate <typename Value> struct index\n          : index_aux<use_long<Value>::value> {};\n\n\ttemplate <typename Matrix, typename Value, typename Orientation>\n\tstruct matrix_copy {};\n\n\t// If arbitrary compressed matrix -> copy\n\ttemplate <typename Value, typename Parameters, typename Orientation>\n\tstruct matrix_copy<compressed2D<Value, Parameters>, Value, Orientation>\n\t{\n\t    typedef typename value<Value>::type                      value_type;\n\t    typedef compressed2D<value_type, parameters<col_major> > matrix_type;\n\t    typedef compressed2D<Value, Parameters>                  in_matrix_type;\n\n\t    matrix_copy(const in_matrix_type& A) : matrix(A) {}\n\t    matrix_type matrix;\n\t};\n\n\tstruct error : public domain_error\n\t{\n\t    error(const char *s, int code) : domain_error(s), code(code) {}\n\t    int code;\n\t};\n\n\tinline void check(int res, const char* s)\n\t{\n\t    MTL_THROW_IF(res != UMFPACK_OK, error(s, res));\n\t}\n\n\t/// Class for repeated Umfpack solutions\n\t/** Keeps symbolic and numeric preprocessing. Numeric part can be updated.\n\t    Only defined for compressed2D<double> and compressed2D<complex<double> >. **/\n\ttemplate <typename T>\n\tclass solver {\n\t  public:\n\t    /// Constructor referring to matrix \\p A (not changed) and optionally Umfpack's strategy and alloc_init (look for the specializations)\n\t    // \\ref solver<compressed2D<double, Parameters> > and \\ref solver<compressed2D<std::complex<double>, Parameters> >)\n\t    explicit solver(const T& /*A*/) {}\n\n\t    /// Update numeric part, for matrices that kept the sparsity and changed the values\n\t    void update_numeric() {}\n\n\t    /// Update symbolic and numeric part\n\t    void update() {}\n\n\t    /// Solve system A*x == b with matrix passed in constructor\n\t    /** Please note that the order of b and x is different than in solve() !!! **/\n\t    template <typename VectorX, typename VectorB>\n\t    int operator()(VectorX& /*x*/, const VectorB& /*b*/) const {return 0;}\n\n\t    /// Solve system A*x == b with matrix passed in constructor\n\t    /** Please note that the order of b and x is different than in operator() !!! **/\n\t    template <typename VectorB, typename VectorX>\n\t    int operator()(const VectorB& /*b*/, VectorX& /*x*/) const {return 0;}\n\t};\n\n\t/// Speciatization of solver for \\ref matrix::compressed2D with double values\n\ttemplate <typename Parameters>\n\tclass solver<compressed2D<double, Parameters> >\n\t{\n\t    typedef double                                    value_type;\n\t    typedef compressed2D<value_type, Parameters>      matrix_type;\n\t    typedef typename matrix_type::size_type           size_type;\n\t    typedef typename index<size_type>::type           index_type;\n\n\t    static const bool copy_indices= sizeof(index_type) != sizeof(size_type),\n\t\t              long_indices= use_long<size_type>::value;\n\t    typedef boost::mpl::bool_<long_indices>           blong;\n\t    typedef boost::mpl::true_                         true_;\n\t    typedef boost::mpl::false_                        false_;\n\n\t    // typedef parameters<col_major>     Parameters;\n\n\t    void assign_pointers()\n\t    {\n\t\tif (copy_indices) {\n\t\t    if (Apc == 0) Apc= new index_type[n + 1];\n\t\t    if (my_nnz != A.nnz() && Aic) { delete[] Aic; Aic= 0; }\n\t\t    if (Aic == 0) Aic= new index_type[A.nnz()];\n\t\t    std::copy(A.address_major(), A.address_major() + n + 1, Apc);\n\t\t    std::copy(A.address_minor(), A.address_minor() + A.nnz(), Aic);\n\t\t    Ap= Apc;\n\t\t    Ai= Aic;\n\t\t} else {\n\t\t    Ap= reinterpret_cast<const index_type*>(A.address_major());\n\t\t    Ai= reinterpret_cast<const index_type*>(A.address_minor());\n\t\t}\n\t\tAx= A.address_data();\n\t    }\n\n\t    void init_aux(true_)\n\t    {\n\t      check(umfpack_dl_symbolic(n, n, Ap, Ai, Ax, &Symbolic, Control, Info), \"Error in dl_symbolic\");\n\t      check(umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info), \"Error in dl_numeric\");\n\t    }\n\n\t    void init_aux(false_)\n\t    {\n\t\tcheck(umfpack_di_symbolic(n, n, Ap, Ai, Ax, &Symbolic, Control, Info), \"Error in di_symbolic\");\n#if 0\n\t\tstd::cout << \"=== INFO of umfpack_*_symbolic ===\\n\";\n\t\tstd::cout << \"    UMFPACK_STATUS: \" << (Info[UMFPACK_STATUS] == UMFPACK_OK ? \"OK\" : \"ERROR\") << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NROW: \" << Info[UMFPACK_NROW] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NCOL: \" << Info[UMFPACK_NCOL] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NZ: \" << Info[UMFPACK_NZ] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SIZE_OF_UNIT: \" << Info[UMFPACK_SIZE_OF_UNIT] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NDENSE_ROW: \" << Info[UMFPACK_NDENSE_ROW] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NEMPTY_ROW: \" << Info[UMFPACK_NEMPTY_ROW] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NDENSE_COL: \" << Info[UMFPACK_NDENSE_COL] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NEMPTY_COL: \" << Info[UMFPACK_NEMPTY_COL] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMBOLIC_DEFRAG: \" << Info[UMFPACK_SYMBOLIC_DEFRAG] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMBOLIC_PEAK_MEMORY: \" << Info[UMFPACK_SYMBOLIC_PEAK_MEMORY] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMBOLIC_SIZE: \" << Info[UMFPACK_SYMBOLIC_SIZE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_VARIABLE_PEAK_ESTIMATE: \" << Info[UMFPACK_VARIABLE_PEAK_ESTIMATE]  << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NUMERIC_SIZE_ESTIMATE: \" << Info[UMFPACK_NUMERIC_SIZE_ESTIMATE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_PEAK_MEMORY_ESTIMATE: \" << Info[UMFPACK_PEAK_MEMORY_ESTIMATE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_FLOPS_ESTIMATE: \" << Info[UMFPACK_FLOPS_ESTIMATE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_LNZ_ESTIMATE: \" << Info[UMFPACK_LNZ_ESTIMATE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_UNZ_ESTIMATE: \" << Info[UMFPACK_UNZ_ESTIMATE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_MAX_FRONT_SIZE_ESTIMATE: \" << Info[UMFPACK_MAX_FRONT_SIZE_ESTIMATE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMBOLIC_TIME: \" << Info[UMFPACK_SYMBOLIC_TIME] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMBOLIC_WALLTIME: \" << Info[UMFPACK_SYMBOLIC_WALLTIME] << \"\\n\";\n\n\t\tif (Info[UMFPACK_STRATEGY_USED] == UMFPACK_STRATEGY_SYMMETRIC)\n\t\t  std::cout << \"    UMFPACK_STRATEGY_USED: SYMMETRIC\\n\";\n\t\telse {\n\t\t  if(Info[UMFPACK_STRATEGY_USED] == UMFPACK_STRATEGY_UNSYMMETRIC)\n\t\t    std::cout << \"    UMFPACK_STRATEGY_USED: UNSYMMETRIC\\n\";\n\t\t  else {\n\t\t    if (Info[UMFPACK_STRATEGY_USED] == UMFPACK_STRATEGY_2BY2)\n\t\t      std::cout << \"    UMFPACK_STRATEGY_USED: 2BY2\\n\";\n\t\t    else\n\t\t      std::cout << \"    UMFPACK_STRATEGY_USED: UNKOWN STRATEGY \" << Info[UMFPACK_STRATEGY_USED] << \"\\n\";\n\t\t  }\n\t\t}\n\n\t\tstd::cout << \"    UMFPACK_ORDERING_USED: \" << Info[UMFPACK_ORDERING_USED] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_QFIXED: \" << Info[UMFPACK_QFIXED] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_DIAG_PREFERRED: \" << Info[UMFPACK_DIAG_PREFERRED] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_ROW_SINGLETONS: \" << Info[UMFPACK_ROW_SINGLETONS] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_COL_SINGLETONS: \" << Info[UMFPACK_COL_SINGLETONS] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_PATTERN_SYMMETRY: \" << Info[UMFPACK_PATTERN_SYMMETRY] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NZ_A_PLUS_AT: \" << Info[UMFPACK_NZ_A_PLUS_AT] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NZDIAG: \" << Info[UMFPACK_NZDIAG] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_N2: \" << Info[UMFPACK_N2] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_S_SYMMETRIC: \" << Info[UMFPACK_S_SYMMETRIC] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_MAX_FRONT_NROWS_ESTIMATE: \" << Info[UMFPACK_MAX_FRONT_NROWS_ESTIMATE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_MAX_FRONT_NCOLS_ESTIMATE: \" << Info[UMFPACK_MAX_FRONT_NCOLS_ESTIMATE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMMETRIC_LUNZ: \" << Info[UMFPACK_SYMMETRIC_LUNZ] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMMETRIC_FLOPS: \" << Info[UMFPACK_SYMMETRIC_FLOPS] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMMETRIC_NDENSE: \" << Info[UMFPACK_SYMMETRIC_NDENSE] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_SYMMETRIC_DMAX: \" << Info[UMFPACK_SYMMETRIC_DMAX] << \"\\n\";\n#endif\n\n\t\tcheck(umfpack_di_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info), \"Error in di_numeric\");\n\n#if 0\n\t\tstd::cout << \"=== INFO of umfpack_*_numeric ===\\n\";\n\t\tstd::cout << \"    UMFPACK_STATUS: \" << (Info[UMFPACK_STATUS] == UMFPACK_OK ? \"OK\" : \"ERROR\") << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_VARIABLE_PEAK: \" << Info[UMFPACK_VARIABLE_PEAK]  << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_PEAK_MEMORY: \" << Info[UMFPACK_PEAK_MEMORY] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_FLOPS: \" << Info[UMFPACK_FLOPS] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_LNZ: \" << Info[UMFPACK_LNZ] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_UNZ: \" << Info[UMFPACK_UNZ] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NUMERIC_DEFRAG: \" << Info[UMFPACK_NUMERIC_DEFRAG] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NUMERIC_REALLOC: \" << Info[UMFPACK_NUMERIC_REALLOC] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NUMERIC_COSTLY_REALLOC: \" << Info[UMFPACK_NUMERIC_COSTLY_REALLOC] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_COMPRESSED_PATTERN: \" << Info[UMFPACK_COMPRESSED_PATTERN] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_LU_ENTRIES: \" << Info[UMFPACK_LU_ENTRIES] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_NUMERIC_TIME: \" << Info[UMFPACK_NUMERIC_TIME] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_RCOND: \" << Info[UMFPACK_RCOND] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_UDIAG_NZ: \" << Info[UMFPACK_UDIAG_NZ] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_UMIN: \" << Info[UMFPACK_UMIN] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_UMAX: \" << Info[UMFPACK_UMAX] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_MAX_FRONT_NROWS: \" << Info[UMFPACK_MAX_FRONT_NROWS] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_MAX_FRONT_NCOLS: \" << Info[UMFPACK_MAX_FRONT_NCOLS] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_ALL_LNZ: \" << Info[UMFPACK_ALL_LNZ] << \"\\n\";\n\t\tstd::cout << \"    UMFPACK_ALL_UNZ: \" << Info[UMFPACK_ALL_UNZ] << \"\\n\";\n#endif\n\t    }\n\n\t    void init()\n\t    {\n\t\tMTL_THROW_IF(num_rows(A) != num_cols(A), matrix_not_square());\n\t\tn= num_rows(A);\n\t\tassign_pointers();\n\t\tinit_aux(blong());\n\t    }\n\n\n\n\t  public:\n\t    /// Constructor referring to matrix \\p A (not changed) and optionally Umfpack's strategy and alloc_init\n\t    solver(const matrix_type& A, int strategy = UMFPACK_STRATEGY_AUTO, double alloc_init = 0.7)\n\t      : A(A), Apc(0), Aic(0), my_nnz(0), Symbolic(0), Numeric(0)\n\t    {\n\t\tvampir_trace<5060> trace;\n\t\t// Use default setings.\n\t\tif (long_indices)\n\t\t    umfpack_dl_defaults(Control);\n\t\telse\n\t\t    umfpack_di_defaults(Control);\n\n\t\tControl[UMFPACK_STRATEGY] = strategy;\n\t\tControl[UMFPACK_ALLOC_INIT] = alloc_init;\n\t\tinit();\n\t    }\n\n\t    ~solver()\n\t    {\n\t\tvampir_trace<5061> trace;\n\t\tif (long_indices) {\n\t\t    umfpack_dl_free_numeric(&Numeric);\n\t\t    umfpack_dl_free_symbolic(&Symbolic);\n\t\t} else {\n\t\t    umfpack_di_free_numeric(&Numeric);\n\t\t    umfpack_di_free_symbolic(&Symbolic);\n\t\t}\n\t\tif (Apc) delete[] Apc;\n\t\tif (Aic) delete[] Aic;\n\t    }\n\n\t    void update_numeric_aux(true_)\n\t    {\n\t\tumfpack_dl_free_numeric(&Numeric);\n\t\tcheck(umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info), \"Error in dl_numeric\");\n\t    }\n\n\t    void update_numeric_aux(false_)\n\t    {\n\t\tumfpack_di_free_numeric(&Numeric);\n\t\tcheck(umfpack_di_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info), \"Error in di_numeric\");\n\t    }\n\n\t    /// Update numeric part, for matrices that kept the sparsity and changed the values\n\t    void update_numeric()\n\t    {\n\t\tassign_pointers();\n\t\tupdate_numeric_aux(blong());\n\t    }\n\n\t    /// Update symbolic and numeric part\n\t    void update()\n\t    {\n\t\tif (long_indices) {\n\t\t    umfpack_dl_free_numeric(&Numeric);\n\t\t    umfpack_dl_free_symbolic(&Symbolic);\n\t\t} else {\n\t\t    umfpack_di_free_numeric(&Numeric);\n\t\t    umfpack_di_free_symbolic(&Symbolic);\n\t\t}\n\t\tinit();\n\t    }\n\n\t    template <typename VectorX, typename VectorB>\n\t    void solve_aux(int sys, VectorX& xx, const VectorB& bb, true_)\n\t    {\n\t      check(umfpack_dl_solve(sys, Ap, Ai, Ax, &xx.value[0], &bb.value[0], Numeric, Control, Info), \"Error in dl_solve\");\n\t    }\n\n\t    template <typename VectorX, typename VectorB>\n\t    void solve_aux(int sys, VectorX& xx, const VectorB& bb, false_)\n\t    {\n\t\tcheck(umfpack_di_solve(sys, Ap, Ai, Ax, &xx.value[0], &bb.value[0], Numeric, Control, Info), \"Error in di_solve\");\n\t    }\n\n\t    /// Solve double system\n\t    template <typename VectorX, typename VectorB>\n\t    int operator()(VectorX& x, const VectorB& b)\n\t    {\n\t\tvampir_trace<5062> trace;\n\t\tMTL_THROW_IF(num_rows(A) != size(x) || num_rows(A) != size(b), incompatible_size());\n\t\tmake_in_out_copy_or_reference<dense_vector<value_type>, VectorX> xx(x);\n\t\tmake_in_copy_or_reference<dense_vector<value_type>, VectorB>     bb(b);\n\t\tint sys= mtl::traits::is_row_major<Parameters>::value ? UMFPACK_At : UMFPACK_A;\n\t\tsolve_aux(sys, xx, bb, blong());\n\t\treturn UMFPACK_OK;\n\t    }\n\n\t    /// Solve double system\n\t    template <typename VectorB, typename VectorX>\n\t    int solve(const VectorB& b, VectorX& x) const\n\t    {\n\t\t// return (*this)(x, b);\n\t\treturn const_cast<solver&>(*this)(x, b); // evil hack because Umfpack has no const\n\t    }\n\n\t  private:\n\t    const matrix_type&  A;\n\t    int                 n;\n\t    const index_type    *Ap, *Ai;\n\t    index_type          *Apc, *Aic;\n\t    size_type           my_nnz;\n\t    const double        *Ax;\n\t    double              Control[UMFPACK_CONTROL], Info[UMFPACK_INFO];\n\t    void                *Symbolic, *Numeric;\n\t};\n\n\t/// Speciatization of solver for \\ref matrix::compressed2D with double values\n\ttemplate <typename Parameters>\n\tclass solver<compressed2D<std::complex<double>, Parameters> >\n\t{\n\t    typedef std::complex<double>                      value_type;\n\t    typedef compressed2D<value_type, Parameters>      matrix_type;\n\t    typedef typename matrix_type::size_type           size_type;\n\t    typedef typename index<size_type>::type           index_type;\n\n\t    static const bool copy_indices= sizeof(index_type) != sizeof(size_type),\n\t\t              long_indices= use_long<size_type>::value;\n\n\t    typedef boost::mpl::bool_<long_indices>           blong;\n\t    typedef boost::mpl::true_                         true_;\n\t    typedef boost::mpl::false_                        false_;\n\n\n\t    void assign_pointers()\n\t    {\n\t\tif (copy_indices) {\n\t\t    if (Apc == 0) Apc= new index_type[n + 1];\n\t\t    if (Aic == 0) Aic= new index_type[A.nnz()];\n\t\t    std::copy(A.address_major(), A.address_major() + n + 1, Apc);\n\t\t    std::copy(A.address_minor(), A.address_minor() + A.nnz(), Aic);\n\t\t    Ap= Apc;\n\t\t    Ai= Aic;\n\t\t} else {\n\t\t    Ap= reinterpret_cast<const index_type*>(A.address_major());\n\t\t    Ai= reinterpret_cast<const index_type*>(A.address_minor());\n\t\t}\n\t\tsplit_complex_vector(A.data, Ax, Az);\n\t    }\n\n\t    void init_aux(true_)\n\t    {\n\t\tcheck(umfpack_zl_symbolic(n, n, Ap, Ai, &Ax[0], &Az[0], &Symbolic, Control, Info), \"Error in zl_symbolic\");\n\t\tcheck(umfpack_zl_numeric(Ap, Ai, &Ax[0], &Az[0], Symbolic, &Numeric, Control, Info), \"Error in zl_numeric\");\n\t    }\n\n\t    void init_aux(false_)\n\t    {\n\t\tcheck(umfpack_zi_symbolic(n, n, Ap, Ai, &Ax[0], &Az[0], &Symbolic, Control, Info), \"Error in zi_symbolic\");\n\t\tcheck(umfpack_zi_numeric(Ap, Ai, &Ax[0], &Az[0], Symbolic, &Numeric, Control, Info), \"Error in zi_numeric\");\n\t    }\n\n\t    void initialize()\n\t    {\n\t\tMTL_THROW_IF(num_rows(A) != num_cols(A), matrix_not_square());\n\t\tn= num_rows(A);\n\t\tassign_pointers();\n\t\tinit_aux(blong());\n\t    }\n\tpublic:\n\t    /// Constructor referring to matrix \\p A (not changed) and optionally Umfpack's strategy and alloc_init (look for the specializations)\n\t    explicit solver(const compressed2D<value_type, Parameters>& A, int strategy = UMFPACK_STRATEGY_AUTO, double alloc_init = 0.7)\n\t      : A(A), Apc(0), Aic(0)\n\t    {\n\t\tvampir_trace<5060> trace;\n\t\t// Use default setings.\n\t\tif (long_indices)\n\t\t    umfpack_zl_defaults(Control);\n\t\telse\n\t\t    umfpack_zi_defaults(Control);\n\t\t// umfpack_zi_defaults(Control);\n\n\t\tControl[UMFPACK_STRATEGY] = strategy;\n\t\tControl[UMFPACK_ALLOC_INIT] = alloc_init;\n\t\tinitialize();\n\t    }\n\n\t    ~solver()\n\t    {\n\t\tvampir_trace<5061> trace;\n\t\tif (long_indices) {\n\t\t    umfpack_zl_free_numeric(&Numeric);\n\t\t    umfpack_zl_free_symbolic(&Symbolic);\n\t\t} else {\n\t\t    umfpack_zi_free_numeric(&Numeric);\n\t\t    umfpack_zi_free_symbolic(&Symbolic);\n\t\t}\n\t\tif (Apc) delete[] Apc;\n\t\tif (Aic) delete[] Aic;\n\t    }\n\n\t    void update_numeric_aux(true_)\n\t    {\n\t\tumfpack_zl_free_numeric(&Numeric);\n\t\tcheck(umfpack_zl_numeric(Ap, Ai, &Ax[0], &Az[0], Symbolic, &Numeric, Control, Info), \"Error in dl_numeric D\");\n\t    }\n\n\t    void update_numeric_aux(false_)\n\t    {\n\t\tumfpack_zi_free_numeric(&Numeric);\n\t\tcheck(umfpack_zi_numeric(Ap, Ai, &Ax[0], &Az[0], Symbolic, &Numeric, Control, Info), \"Error in di_numeric\");\n\t    }\n\n\t    /// Update numeric part, for matrices that kept the sparsity and changed the values\n\t    void update_numeric()\n\t    {\n\t\tassign_pointers();\n\t\tupdate_numeric_aux(blong());\n\t    }\n\n\t    /// Update symbolic and numeric part\n\t    void update()\n\t    {\n\t\tAx.change_dim(0); Az.change_dim(0);\n\t\tif (long_indices) {\n\t\t    umfpack_zl_free_numeric(&Numeric);\n\t\t    umfpack_zl_free_symbolic(&Symbolic);\n\t\t} else {\n\t\t    umfpack_zi_free_numeric(&Numeric);\n\t\t    umfpack_zi_free_symbolic(&Symbolic);\n\t\t}\n\t\tinitialize();\n\t    }\n\n\t    template <typename VectorX, typename VectorB>\n\t    void solve_aux(int sys, VectorX& Xx, VectorX& Xz, const VectorB& Bx, const VectorB& Bz, true_)\n\t    {\n\t\tcheck(umfpack_zl_solve(sys, Ap, Ai, &Ax[0], &Az[0], &Xx[0], &Xz[0], &Bx[0], &Bz[0], Numeric, Control, Info),\n\t\t      \"Error in zi_solve\");\n\t    }\n\n\t    template <typename VectorX, typename VectorB>\n\t    void solve_aux(int sys, VectorX& Xx, VectorX& Xz, const VectorB& Bx, const VectorB& Bz, false_)\n\t    {\n\t\tcheck(umfpack_zi_solve(sys, Ap, Ai, &Ax[0], &Az[0], &Xx[0], &Xz[0], &Bx[0], &Bz[0], Numeric, Control, Info),\n\t\t      \"Error in zi_solve\");\n\t    }\n\n\t    /// Solve complex system\n\t    template <typename VectorX, typename VectorB>\n\t    int operator()(VectorX& x, const VectorB& b)\n\t    {\n\t\tvampir_trace<5062> trace;\n\t\tMTL_THROW_IF(num_rows(A) != size(x) || num_rows(A) != size(b), incompatible_size());\n\t\tdense_vector<double> Xx(size(x)), Xz(size(x)), Bx, Bz;\n\t\tsplit_complex_vector(b, Bx, Bz);\n\t\tint sys= mtl::traits::is_row_major<Parameters>::value ? UMFPACK_Aat : UMFPACK_A;\n\t\tsolve_aux(sys, Xx, Xz, Bx, Bz, blong());\n\t\tmerge_complex_vector(Xx, Xz, x);\n\t\treturn UMFPACK_OK;\n\t    }\n\n\t    /// Solve complex system\n\t    template <typename VectorB, typename VectorX>\n\t    int solve(const VectorB& b, VectorX& x)\n\t    {\n\t\treturn (*this)(x, b);\n\t    }\n\n\tprivate:\n\t    const matrix_type&   A;\n\t    int                  n;\n\t    const index_type     *Ap, *Ai;\n\t    index_type          *Apc, *Aic;\n\t    dense_vector<double> Ax, Az;\n\t    double               Control[UMFPACK_CONTROL], Info[UMFPACK_INFO];\n\t    void                 *Symbolic, *Numeric;\n\t};\n\n\ttemplate <typename Value, typename Parameters>\n\tclass solver<compressed2D<Value, Parameters> >\n\t  : matrix_copy<compressed2D<Value, Parameters>, Value, typename Parameters::orientation>,\n\t    public solver<typename matrix_copy<compressed2D<Value, Parameters>, Value, typename Parameters::orientation>::matrix_type >\n\t{\n\t    typedef matrix_copy<compressed2D<Value, Parameters>, Value, typename Parameters::orientation> copy_type;\n\t    typedef solver<typename matrix_copy<compressed2D<Value, Parameters>, Value, typename Parameters::orientation>::matrix_type > solver_type;\n\tpublic:\n\t    explicit solver(const compressed2D<Value, Parameters>& A)\n\t\t: copy_type(A), solver_type(copy_type::matrix), A(A)\n\t    {}\n\n\t    void update()\n\t    {\n\t\tcopy_type::matrix= A;\n\t\tsolver_type::update();\n\t    }\n\n\t    void update_numeric()\n\t    {\n\t\tcopy_type::matrix= A;\n\t\tsolver_type::update_numeric();\n\t    }\n\tprivate:\n\t    const compressed2D<Value, Parameters>& A;\n\t};\n    } // umfpack\n\n/// Solve A*x == b with umfpack\n/** Only available when compiled with enabled macro MTL_HAS_UMFPACK.\n    Uses classes umfpack::solver internally.\n    If you want more control on single operations or to keep umfpack's\n    internal factorization, use this class.\n **/\ntemplate <typename Value, typename Parameters, typename VectorX, typename VectorB>\nint umfpack_solve(const compressed2D<Value, Parameters>& A, VectorX& x, const VectorB& b)\n{\n    umfpack::solver<compressed2D<Value, Parameters> > solver(A);\n    return solver(x, b);\n}\n\n}} // namespace mtl::matrix\n\n#endif\n\n#endif // MTL_MATRIX_UMFPACK_SOLVE_INCLUDE\n", "meta": {"hexsha": "0bdcba48167abd60cf2d47c88ae6aa54b2fb565c", "size": 22443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/interface/umfpack_solve.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/interface/umfpack_solve.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/interface/umfpack_solve.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": 39.5123239437, "max_line_length": 142, "alphanum_fraction": 0.6486655082, "num_tokens": 6524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.1659166441743414}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <mmtbx/rotamer/fit.h>\n\n#include <boost/python.hpp>\n\n#include <cctbx/boost_python/flex_fwd.h>\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n//#include <boost/python/args.hpp>\n#include <scitbx/array_family/boost_python/shared_wrapper.h>\n#include <scitbx/boost_python/is_polymorphic_workaround.h>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/return_by_value.hpp>\n\nnamespace mmtbx { namespace rotamer {\nnamespace {\n\n  boost::python::tuple\n  getinitargs(xyzrad<> const& self)\n  {\n    return boost::python::make_tuple(self.sites_cart, self.radii);\n  }\n\n  void init_module()\n  {\n    using namespace boost::python;\n\n    //\n    typedef return_value_policy<return_by_value> rbv;\n    class_<xyzrad<> >(\"xyzrad\")\n      .def(init<af::shared<scitbx::vec3<double> > const&,\n                af::shared<double> const&,\n                af::shared<double> const& >((arg(\"sites_cart\"),\n                                             arg(\"radii\"),\n                                             arg(\"weights\"))))\n      .add_property(\"sites_cart\", make_getter(&xyzrad<>::sites_cart, rbv()))\n      .add_property(\"radii\",      make_getter(&xyzrad<>::radii, rbv()))\n      .add_property(\"weights\",    make_getter(&xyzrad<>::weights, rbv()))\n      .enable_pickling()\n      .def(\"__getinitargs__\", getinitargs)\n\n      .def(init<af::shared<scitbx::vec3<double> > const&,\n                af::shared<double> const& >((arg(\"sites_cart\"),\n                                             arg(\"radii\"))))\n      .add_property(\"sites_cart\", make_getter(&xyzrad<>::sites_cart, rbv()))\n      .add_property(\"radii\",    make_getter(&xyzrad<>::weights, rbv()))\n      .enable_pickling()\n      .def(\"__getinitargs__\", getinitargs)\n    ;\n    //\n\n    class_<fit<> >(\"fit\")\n\n     .def(init<       double,\n                      xyzrad<double> const&,\n                      //af::shared<scitbx::vec3<double> >,\n                      boost::python::list const&,\n                      boost::python::list const&,\n                      boost::python::list const&,\n                      af::const_ref<double, af::c_grid_padded<3> > const&,\n                      //af::shared<scitbx::vec3<double> >,\n                      xyzrad<double> const&,\n\n                      cctbx::uctbx::unit_cell const&,\n                      af::const_ref<std::size_t> const& ,\n                      af::const_ref<std::size_t> const& ,\n                      af::const_ref<double> const&,\n                      af::const_ref<double> const&,\n                      double,\n                      int >\n                       ((arg(\"target_value\"),\n                         arg(\"xyzrad_bumpers\"),\n                         //arg(\"sites_cart_bumpers\"),\n                         arg(\"axes\"),\n                         arg(\"rotatable_points_indices\"),\n                         arg(\"angles_array\"),\n                         arg(\"density_map\"),\n                         arg(\"all_points\"),\n                         arg(\"unit_cell\"),\n                         arg(\"selection_clash\"),\n                         arg(\"selection_rsr\"),\n                         arg(\"sin_table\"),\n                         arg(\"cos_table\"),\n                         arg(\"step\"),\n                         arg(\"n\"))))\n\n     .def(init<double,\n                      boost::python::list const&,\n                      boost::python::list const&,\n                      boost::python::list const&,\n                      af::const_ref<double, af::c_grid_padded<3> > const&,\n                      af::shared<scitbx::vec3<double> >,\n                      cctbx::uctbx::unit_cell const&,\n                      af::const_ref<std::size_t> const& ,\n                      af::const_ref<double> const&,\n                      af::const_ref<double> const&,\n                      double,\n                      int >\n                       ((arg(\"target_value\"),\n                         arg(\"axes\"),\n                         arg(\"rotatable_points_indices\"),\n                         arg(\"angles_array\"),\n                         arg(\"density_map\"),\n                         arg(\"all_points\"),\n                         arg(\"unit_cell\"),\n                         arg(\"selection\"),\n                         arg(\"sin_table\"),\n                         arg(\"cos_table\"),\n                         arg(\"step\"),\n                         arg(\"n\"))))\n\n     .def(init<af::shared<scitbx::vec3<double> > const&,\n                      boost::python::list const&,\n                      boost::python::list const&,\n                      boost::python::list const&,\n                      af::shared<scitbx::vec3<double> >,\n                      af::const_ref<double> const&,\n                      af::const_ref<double> const&,\n                      double,\n                      int >\n                       ((arg(\"sites_cart_start\"),\n                         arg(\"axes\"),\n                         arg(\"rotatable_points_indices\"),\n                         arg(\"angles_array\"),\n                         arg(\"all_points\"),\n                         arg(\"sin_table\"),\n                         arg(\"cos_table\"),\n                         arg(\"step\"),\n                         arg(\"n\"))))\n\n      .def(\"result\", &fit<>::result)\n      .def(\"score\", &fit<>::score)\n    ;\n\n  }\n\n} // namespace <anonymous>\n}} // namespace mmtbx::rotamer\n\nBOOST_PYTHON_MODULE(mmtbx_rotamer_fit_ext)\n{\n  mmtbx::rotamer::init_module();\n}\n", "meta": {"hexsha": "7382b320c10f952fd91e6bd5f144e9d7e2794432", "size": 5572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mmtbx/rotamer/fit_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": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "mmtbx/rotamer/fit_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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mmtbx/rotamer/fit_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": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T15:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T15:39:06.000Z", "avg_line_length": 37.6486486486, "max_line_length": 76, "alphanum_fraction": 0.4580043073, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.16591664083288737}}
{"text": "/// @file\n///\n/// XXX Notes on program XXX\n///\n/// @copyright (c) 2010 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// 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, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author XXX XXX <XXX.XXX@csiro.au>\n///\n\n#include <askap_analysis.h>\n\n#include <askap/AskapLogging.h>\n#include <askap/AskapError.h>\n\n#include <sourcefitting/SubThresholder.h>\n#include <sourcefitting/RadioSource.h>\n#include <sourcefitting/SubComponent.h>\n\n#include <duchamp/Cubes/cubes.hh>\n#include <casacore/casa/Arrays/Slicer.h>\n#include <casacore/casa/Arrays/Vector.h>\n#include <casacore/casa/Arrays/Matrix.h>\n\n#include <boost/scoped_ptr.hpp>\n\n#include <math.h>\n#include <vector>\n\n///@brief Where the log messages go.\nASKAP_LOGGER(logger, \".subthresholder\");\n\nnamespace askap {\n\nnamespace analysis {\n\nnamespace sourcefitting {\n\nSubThresholder::~SubThresholder()\n{\n}\n\n// SubThresholder::SubThresholder(const SubThresholder &s) {\n//     operator=(s);\n// }\n\n// SubThresholder& SubThresholder::operator=(const SubThresholder &s) {\n//     if(this == &s) return *this;\n//     this->itsFirstGuess = s.itsFirstGuess;\n//     this->itsSourceBox = s.itsSourceBox;\n//     this->itsBaseThreshold = s.itsBaseThreshold;\n//     this->itsThreshIncrement = s.itsThreshIncrement;\n//     this->itsPeakFlux = s.itsPeakFlux;\n//     this->itsSourceSize = s.itsSourceSize;\n//     this->itsDim = s.itsDim;\n//     this->itsFluxArray = s.itsFluxArray;\n//     this->itsCurrentThreshold = s.itsCurrentThreshold;\n//     this->itsFitParams = s.itsFitParams;\n//     return *this;\n\n// }\n\nvoid SubThresholder::define(RadioSource &src,\n                            casa::Matrix<casa::Double> pos,\n                            casa::Vector<casa::Double> &array)\n{\n    this->saveArray(src, pos, array);\n    this->define(src);\n}\n\n\nvoid SubThresholder::saveArray(RadioSource &src,\n                               casa::Matrix<casa::Double> pos,\n                               casa::Vector<casa::Double> &f)\n{\n    int xmin = src.boxXmin();\n    int ymin = src.boxYmin();\n    int xsize = src.boxXsize();\n    int ysize = src.boxYsize();\n    size_t size = xsize * ysize;\n    itsFluxArray = std::vector<float>(size, 0.);\n    PixelInfo::Object2D spatMap = src.getSpatialMap();\n    for (size_t i = 0; i < f.size(); i++) {\n        int x = int(pos(i, 0));\n        int y = int(pos(i, 1));\n\n        if (spatMap.isInObject(x, y)) {\n            int loc = (x - xmin) + xsize * (y - ymin);\n            itsFluxArray[loc] = float(f(i));\n        }\n    }\n\n}\n\n\nvoid SubThresholder::define(RadioSource &src)\n{\n\n    itsPeakFlux = src.getPeakFlux();\n    itsSourceSize = src.getSize();\n\n    itsDim = std::vector<size_t>(2);\n    itsDim[0] = src.boxXsize();\n    itsDim[1] = src.boxYsize();\n\n    this->setFirstGuess(src);\n    itsFitParams = src.fitparams();\n    itsSourceBox = src.box();\n\n    if (itsFitParams.flagLogarithmicIncrements()) {\n        itsBaseThreshold = src.detectionThreshold() > 0 ?\n                           log10(src.detectionThreshold()) : -6.;\n        itsThreshIncrement = (log10(itsPeakFlux) - itsBaseThreshold) /\n                             float(itsFitParams.numSubThresholds() + 1);\n        itsCurrentThreshold = pow(10., itsBaseThreshold + itsThreshIncrement);\n    } else {\n        itsBaseThreshold = src.detectionThreshold();\n        itsThreshIncrement = (itsPeakFlux - itsBaseThreshold) /\n                             float(itsFitParams.numSubThresholds() + 1);\n        itsCurrentThreshold = itsBaseThreshold + itsThreshIncrement;\n    }\n\n}\n\nvoid SubThresholder::setFirstGuess(RadioSource &src)\n{\n\n    itsFirstGuess.setPeak(src.getPeakFlux());\n    itsFirstGuess.setX(src.getXPeak());\n    itsFirstGuess.setY(src.getYPeak());\n    double a, b, c;\n\n    if (src.getSize() < 3) {\n        itsFirstGuess.setPA(0);\n        itsFirstGuess.setMajor(1.);\n        itsFirstGuess.setMinor(1.);\n    } else {\n        src.getFWHMestimate(itsFluxArray, a, b, c);\n        itsFirstGuess.setPA(a);\n        itsFirstGuess.setMajor(b);\n        itsFirstGuess.setMinor(c);\n    }\n\n\n}\n\n\nvoid SubThresholder::keepObject(PixelInfo::Object2D &obj)\n{\n\n    for (size_t i = 0; i < itsDim[0]*itsDim[1]; i++) {\n        int xbox = i % itsDim[0];\n        int ybox = i / itsDim[0];\n\n        if (!obj.isInObject(xbox, ybox)) {\n            itsFluxArray[i] = 0.;\n        }\n    }\n\n}\n\nvoid SubThresholder::incrementThreshold()\n{\n\n    if (itsFitParams.flagLogarithmicIncrements()) {\n        itsCurrentThreshold *= pow(10., itsThreshIncrement);\n    } else {\n        itsCurrentThreshold += itsThreshIncrement;\n    }\n\n}\n\n\nstd::vector<SubComponent> SubThresholder::find()\n{\n\n    std::vector<SubComponent> fullList;\n\n    if (itsSourceSize < 3) {\n        fullList.push_back(itsFirstGuess);\n        return fullList;\n    }\n\n    std::vector<PixelInfo::Object2D> objlist;\n    std::vector<PixelInfo::Object2D>::iterator obj;\n    bool keepGoing = true;\n\n    boost::scoped_ptr<duchamp::Image> theImage(new duchamp::Image(itsDim.data()));\n\n    if (itsFluxArray.size() > 0) {\n        ASKAPCHECK(itsFluxArray.size() == (itsDim[0]*itsDim[1]),\n                   \"Size of flux array (\" << itsFluxArray.size() <<\n                   \") doesn't match dimension (\" << itsDim[0] <<\n                   \"x\" << itsDim[1] << \"=\" << itsDim[0]*itsDim[1] << \")!\");\n        theImage->saveArray(&(itsFluxArray[0]), itsFluxArray.size());\n    }\n    theImage->setMinSize(1);\n    theImage->pars().setFlagUserThreshold(true);\n\n    while (itsCurrentThreshold <= itsPeakFlux && keepGoing) {\n        theImage->stats().setThreshold(itsCurrentThreshold);\n        theImage->pars().setThreshold(itsCurrentThreshold);\n        objlist = theImage->findSources2D();\n        keepGoing = (objlist.size() == 1);\n        this->incrementThreshold();\n    }\n\n    if (!keepGoing) {\n\n        if (objlist.size() == 0) {\n            fullList.push_back(itsFirstGuess);\n        } else {\n\n            for (obj = objlist.begin(); obj < objlist.end(); obj++) {\n\n                RadioSource src;\n                src.addChannel(0, *obj);\n                src.setFitParams(itsFitParams);\n                src.setDetectionThreshold(itsCurrentThreshold);\n                src.setBox(itsSourceBox);\n                src.calcFluxes(&(itsFluxArray[0]), &(itsDim[0]));\n                duchamp::Param par;\n                par.setXOffset(itsSourceBox.start()[0]);\n                par.setYOffset(itsSourceBox.start()[1]);\n                src.setOffsets(par);\n                src.addOffsets();\n                SubThresholder newthresher(*this);\n                newthresher.setFirstGuess(src);\n                newthresher.keepObject(*obj);\n                std::vector<SubComponent> newlist = newthresher.find();\n                for (uInt i = 0; i < newlist.size(); i++) {\n                    fullList.push_back(newlist[i]);\n                }\n            }\n        }\n    } else {\n        fullList.push_back(itsFirstGuess);\n    }\n\n    if (fullList.size() > 1) {\n        std::sort(fullList.begin(), fullList.end());\n        std::reverse(fullList.begin(), fullList.end());\n    }\n\n    return fullList;\n\n}\n\n}\n}\n\n}\n", "meta": {"hexsha": "b420f6374fe92e35b5dd269465ff54ef279dea77", "size": 7925, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Code/Components/Analysis/analysis/current/sourcefitting/SubThresholder.cc", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Analysis/analysis/current/sourcefitting/SubThresholder.cc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "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/Components/Analysis/analysis/current/sourcefitting/SubThresholder.cc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1360294118, "max_line_length": 82, "alphanum_fraction": 0.6107255521, "num_tokens": 2083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1659166341499794}}
{"text": "/**\n * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * This program is free software: you can redistribute it and/or modify\n * it 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 * 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 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 this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n#include <bitcoin/bitcoin/wallet/ec_private.hpp>\n\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <boost/program_options.hpp>\n#include <bitcoin/bitcoin/formats/base_58.hpp>\n#include <bitcoin/bitcoin/math/checksum.hpp>\n#include <bitcoin/bitcoin/math/elliptic_curve.hpp>\n#include <bitcoin/bitcoin/math/hash.hpp>\n#include <bitcoin/bitcoin/utility/data.hpp>\n#include <bitcoin/bitcoin/wallet/ec_public.hpp>\n#include <bitcoin/bitcoin/wallet/hd_private.hpp>\n#include <bitcoin/bitcoin/wallet/payment_address.hpp>\n\nnamespace libbitcoin {\nnamespace wallet {\n\nconst uint8_t ec_private::compressed_sentinel = 0x01;\n\nconst uint8_t ec_private::mainnet_wif = 0x80;\nconst uint8_t ec_private::mainnet_p2kh = 0x00;\nconst uint16_t ec_private::mainnet = to_version(mainnet_p2kh, mainnet_wif);\n\nconst uint8_t ec_private::testnet_wif = 0xef;\nconst uint8_t ec_private::testnet_p2kh = 0x6f;\nconst uint16_t ec_private::testnet = to_version(testnet_p2kh, testnet_wif);\n\nec_private::ec_private()\n  : valid_(false), compress_(true), version_(0), secret_(null_hash)\n{\n}\n\nec_private::ec_private(const ec_private& other)\n  : valid_(other.valid_), compress_(other.compress_), version_(other.version_),\n    secret_(other.secret_)\n{\n}\n\nec_private::ec_private(const data_chunk& seed, uint8_t address_version)\n  : ec_private(from_seed(seed, address_version))\n{\n}\n\nec_private::ec_private(const std::string& wif, uint8_t address_version)\n  : ec_private(from_string(wif, address_version))\n{\n}\n\nec_private::ec_private(const wif_compressed& wif, uint8_t address_version)\n  : ec_private(from_compressed(wif, address_version))\n{\n}\n\nec_private::ec_private(const wif_uncompressed& wif, uint8_t address_version)\n  : ec_private(from_uncompressed(wif, address_version))\n{\n}\n\nec_private::ec_private(const ec_secret& secret, uint16_t version, bool compress)\n  : valid_(true), compress_(compress), version_(version), secret_(secret)\n{\n}\n\n// Validators.\n// ----------------------------------------------------------------------------\n\nbool ec_private::is_wif(data_slice decoded)\n{\n    const auto size = decoded.size();\n    if (size != wif_compressed_size && size != wif_uncompressed_size)\n        return false;\n\n    if (!verify_checksum(decoded))\n        return false;\n\n    return (size == wif_uncompressed_size) ||\n        decoded.data()[1 + ec_secret_size] == compressed_sentinel;\n}\n\n// Factories.\n// ----------------------------------------------------------------------------\n\nec_private ec_private::from_seed(const data_chunk& seed,\n    uint8_t address_version)\n{\n    // This technique ensures consistent secrets with BIP32 from a given seed.\n    const hd_private key(seed);\n\n    // The key is invalid if parse256(IL) >= n or 0:\n    return key ? ec_private{ key.secret(), address_version } : ec_private{};\n}\n\nec_private ec_private::from_string(const std::string& wif,\n    uint8_t address_version)\n{\n    data_chunk decoded;\n    if (!decode_base58(decoded, wif) || !is_wif(decoded))\n        return ec_private();\n\n    const auto compressed = decoded.size() == wif_compressed_size;\n    return compressed ?\n        ec_private(to_array<wif_compressed_size>(decoded), address_version) :\n        ec_private(to_array<wif_uncompressed_size>(decoded), address_version);\n}\n\nec_private ec_private::from_compressed(const wif_compressed& wif,\n    uint8_t address_version)\n{\n    if (!is_wif(wif))\n        return ec_private();\n\n    const uint16_t version = to_version(address_version, wif.front());\n    const auto secret = slice<1, ec_secret_size + 1>(wif);\n    return ec_private(secret, version, true);\n}\n\nec_private ec_private::from_uncompressed(const wif_uncompressed& wif,\n    uint8_t address_version)\n{\n    if (!is_wif(wif))\n        return ec_private();\n\n    const uint16_t version = to_version(address_version, wif.front());\n    const auto secret = slice<1, ec_secret_size + 1>(wif);\n    return ec_private(secret, version, false);\n}\n\n// Cast operators.\n// ----------------------------------------------------------------------------\n\nec_private::operator const bool() const\n{\n    return valid_;\n}\n\nec_private::operator const ec_secret&() const\n{\n    return secret_;\n}\n\n// Serializer.\n// ----------------------------------------------------------------------------\n\n// Conversion to WIF loses payment address version info.\nstd::string ec_private::encoded() const\n{\n    if (compressed())\n    {\n        wif_compressed wif;\n        const auto prefix = to_array(wif_version());\n        const auto compressed = to_array(compressed_sentinel);\n        build_checked_array(wif, { prefix, secret_, compressed });\n        return encode_base58(wif);\n    }\n\n    wif_uncompressed wif;\n    const auto prefix = to_array(wif_version());\n    build_checked_array(wif, { prefix, secret_ });\n    return encode_base58(wif);\n}\n\n// Accessors.\n// ----------------------------------------------------------------------------\n\nconst ec_secret& ec_private::secret() const\n{\n    return secret_;\n}\n\nconst uint16_t ec_private::version() const\n{\n    return version_;\n}\n\nconst uint8_t ec_private::payment_version() const\n{\n    return to_address_prefix(version_);\n}\n\nconst uint8_t ec_private::wif_version() const\n{\n    return to_wif_prefix(version_);\n}\n\nconst bool ec_private::compressed() const\n{\n    return compress_;\n}\n\n// Methods.\n// ----------------------------------------------------------------------------\n\n// Conversion to ec_public loses all version information.\n// In the case of failure the key is always compressed (ec_compressed_null).\nec_public ec_private::to_public() const\n{\n    ec_compressed point;\n    return valid_ && secret_to_public(point, secret_) ?\n        ec_public(point, compressed()) : ec_public();\n}\n\npayment_address ec_private::to_payment_address() const\n{\n    return payment_address(*this);\n}\n\n// Operators.\n// ----------------------------------------------------------------------------\n\nec_private& ec_private::operator=(const ec_private& other)\n{\n    valid_ = other.valid_;\n    compress_ = other.compress_;\n    version_ = other.version_;\n    secret_ = other.secret_;\n    return *this;\n}\n\nbool ec_private::operator<(const ec_private& other) const\n{\n    return encoded() < other.encoded();\n}\n\nbool ec_private::operator==(const ec_private& other) const\n{\n    return valid_ == other.valid_ && compress_ == other.compress_ &&\n        version_ == other.version_ && secret_ == other.secret_;\n}\n\nbool ec_private::operator!=(const ec_private& other) const\n{\n    return !(*this == other);\n}\n\nstd::istream& operator>>(std::istream& in, ec_private& to)\n{\n    std::string value;\n    in >> value;\n    to = ec_private(value);\n\n    if (!to)\n    {\n        using namespace boost::program_options;\n        BOOST_THROW_EXCEPTION(invalid_option_value(value));\n    }\n\n    return in;\n}\n\nstd::ostream& operator<<(std::ostream& out, const ec_private& of)\n{\n    out << of.encoded();\n    return out;\n}\n\n} // namespace wallet\n} // namespace libbitcoin\n", "meta": {"hexsha": "7b97a7fc083d0c6c069474bf855fcd0d79a74b04", "size": 7665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vendor/libbitcoin/src/wallet/ec_private.cpp", "max_stars_repo_name": "X9Developers/xsn-wallet", "max_stars_repo_head_hexsha": "7b5aaf6de15928c8cf5b86a844e56710c301df1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T11:15:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-20T11:15:45.000Z", "max_issues_repo_path": "vendor/libbitcoin/src/wallet/ec_private.cpp", "max_issues_repo_name": "X9Developers/xsn-wallet", "max_issues_repo_head_hexsha": "7b5aaf6de15928c8cf5b86a844e56710c301df1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vendor/libbitcoin/src/wallet/ec_private.cpp", "max_forks_repo_name": "X9Developers/xsn-wallet", "max_forks_repo_head_hexsha": "7b5aaf6de15928c8cf5b86a844e56710c301df1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-08-30T08:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-29T15:36:26.000Z", "avg_line_length": 27.6714801444, "max_line_length": 80, "alphanum_fraction": 0.6694063927, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.16571670355214227}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution.hpp\n//! \\author Alex Robinson\n//! \\brief  The standard complete Doppler broadened photon energy dist. decl.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n#define MONTE_CARLO_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n\n// Std Lib Includes\n#include <memory>\n\n// Boost Includes\n#include <boost/bimap.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_CompleteDopplerBroadenedPhotonEnergyDistribution.hpp\"\n#include \"Data_SubshellType.hpp\"\n#include \"MonteCarlo_ComptonProfileSubshellConverter.hpp\"\n#include \"MonteCarlo_ComptonProfilePolicy.hpp\"\n#include \"Utility_TabularUnivariateDistribution.hpp\"\n\nnamespace MonteCarlo{\n\n//! The standard complete (all subshells) Doppler broadened photon energy dist.\ntemplate<typename ComptonProfilePolicy>\nclass StandardCompleteDopplerBroadenedPhotonEnergyDistribution : public CompleteDopplerBroadenedPhotonEnergyDistribution\n{\n\npublic:\n\n  //! The trials counter type\n  typedef CompleteDopplerBroadenedPhotonEnergyDistribution::Counter Counter;\n\n  //! Constructor\n  StandardCompleteDopplerBroadenedPhotonEnergyDistribution(\n               const std::vector<double>& endf_subshell_occupancies,\n               const std::vector<Data::SubshellType>& endf_subshell_order,\n               const std::shared_ptr<const ComptonProfileSubshellConverter>&\n               subshell_converter,\n               const ComptonProfileArray& compton_profile_array );\n\n  //! Destructor\n  virtual ~StandardCompleteDopplerBroadenedPhotonEnergyDistribution()\n  { /* .. */ }\n\n  //! Check if the subshell is valid\n  bool isValidSubshell( const Data::SubshellType subshell ) const override;\n\n  //! Return the occupancy of a subshell (default is the ENDF occupancy)\n  virtual double getSubshellOccupancy( const Data::SubshellType subshell ) const override;\n\n  //! Evaluate the distribution with electron momentum projection\n  virtual double evaluateWithElectronMomentumProjection(\n                              const double incoming_energy,\n                              const double electron_momentum_projection,\n                              const double scattering_angle_cosine ) const override;\n\n  //! Evaluate the exact distribution\n  virtual double evaluateExact( const double incoming_energy,\n                                const double outgoing_energy,\n                                const double scattering_angle_cosine ) const override;\n\n  //! Evaluate the subshell with the electron momentum projection\n  double evaluateSubshellWithElectronMomentumProjection(\n                                     const double incoming_energy,\n                                     const double electron_momentum_projection,\n                                     const double scattering_angle_cosine,\n                                     const Data::SubshellType subshell ) const override;\n\n  //! Evaluate the exact subshell distribution\n  double evaluateSubshellExact( const double incoming_energy,\n                                const double outgoing_energy,\n                                const double scattering_angle_cosine,\n                                const Data::SubshellType subshell ) const override;\n\n  //! Evaluate the PDF with electron momentum projection\n  double evaluatePDFWithElectronMomentumProjection(\n                                   const double incoming_energy,\n                                   const double electron_momentum_projection,\n                                   const double scattering_angle_cosine,\n                                   const double precision ) const override;\n\n  //! Evaluate the exact PDF\n  double evaluatePDFExact( const double incoming_energy,\n                           const double outgoing_energy,\n                           const double scattering_angle_cosine,\n                           const double precision ) const override;\n\n  //! Evaluate the subshell PDF with electron momentum projection\n  double evaluateSubshellPDFWithElectronMomentumProjection(\n                                     const double incoming_energy,\n                                     const double electron_momentum_projection,\n                                     const double scattering_angle_cosine,\n                                     const Data::SubshellType subshell,\n                                     const double precision ) const override;\n\n  //! Evaluate the exact subshell PDF\n  double evaluateSubshellPDFExact( const double incoming_energy,\n                                   const double outgoing_energy,\n                                   const double scattering_angle_cosine,\n                                   const Data::SubshellType subshell,\n                                   const double precision ) const override;\n\n  //! Evaluate the integrated cross section (b/mu)\n  virtual double evaluateIntegratedCrossSection(\n                                          const double incoming_energy,\n                                          const double scattering_angle_cosine,\n                                          const double precision ) const override;\n\n  //! Evaluate the exact integrated cross section (b/mu)\n  virtual double evaluateIntegratedCrossSectionExact(\n                                          const double incoming_energy,\n                                          const double scattering_angle_cosine,\n                                          const double precision ) const override;\n\n  //! Evaluate the subshell integrated cross section (b/mu)\n  double evaluateSubshellIntegratedCrossSection(\n\t\t\t\t          const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const Data::SubshellType subshell,\n\t\t\t\t\t  const double precision ) const override;\n\n  //! Evaluate the exact subshell integrated cross section (b/mu)\n  double evaluateSubshellIntegratedCrossSectionExact(\n                                          const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const Data::SubshellType subshell,\n\t\t\t\t\t  const double precision ) const override;\n\n  //! Sample an outgoing energy from the distribution\n  void sample( const double incoming_energy,\n\t       const double scattering_angle_cosine,\n\t       double& outgoing_energy,\n\t       Data::SubshellType& shell_of_interaction ) const override;\n\n  //! Sample an outgoing energy and record the number of trials\n  void sampleAndRecordTrials( const double incoming_energy,\n\t\t\t      const double scattering_angle_cosine,\n\t\t\t      double& outgoing_energy,\n\t\t\t      Data::SubshellType& shell_of_interaction,\n\t\t\t      Counter& trials ) const override;\n\n  //! Sample an electron momentum from the distribution\n  void sampleMomentumAndRecordTrials(\n                                    const double incoming_energy,\n                                    const double scattering_angle_cosine,\n                                    double& electron_momentum,\n                                    Data::SubshellType& shell_of_interaction,\n                                    Counter& trials ) const override;\n\n  //! Sample an electron momentum from the subshell distribution\n  double sampleSubshellMomentum( const double incoming_energy,\n                                 const double scattering_angle_cosine,\n                                 const Data::SubshellType subshell ) const override;\n\nprotected:\n\n  //! Return the old subshell index corresponding to the subshell\n  unsigned getOldSubshellIndex( const Data::SubshellType subshell ) const;\n\n  //! Return the endf subshell index corresponding to the subshell\n  unsigned getENDFSubshellIndex( const Data::SubshellType subshell ) const;\n\n  //! Return the subshell corresponding to the endf subshell index\n  Data::SubshellType getSubshell( const size_t endf_subshell_index ) const;\n\n  //! Return the Compton profile for a subshell\n  const ComptonProfile& getComptonProfile( const Data::SubshellType& subshell) const;\n\n  //! Return the Compton profile for an old subshell index\n  const ComptonProfile& getComptonProfile(\n                                    const unsigned& old_subshell_index ) const;\n\n  //! Sample an ENDF subshell\n  Data::SubshellType sampleENDFInteractionSubshell() const;\n\n  //! Sample an interaction subshell\n  virtual void sampleInteractionSubshell( size_t& old_subshell_index,\n                                          double& subshell_binding_energy,\n                                          Data::SubshellType& subshell ) const = 0;\n\nprivate:\n\n  // Sample an electron momentum from the subshell distribution\n  double sampleSubshellMomentum( const double incoming_energy,\n                                 const double scattering_angle_cosine,\n                                 const double subshell_binding_energy,\n                                 const ComptonProfile& compton_profile ) const;\n\n  // The ENDF subshell interaction probabilities\n  std::unique_ptr<const Utility::TabularUnivariateDistribution>\n  d_endf_subshell_occupancy_distribution;\n\n  // The ENDF subshell order\n  typedef boost::bimap<unsigned,Data::SubshellType> SubshellOrderMapType;\n  boost::bimap<unsigned,Data::SubshellType> d_endf_subshell_order;\n\n  // The ENDF subshell occupancies\n  std::vector<double> d_endf_subshell_occupancies;\n\n  // The Compton profile subshell converter\n  std::shared_ptr<const ComptonProfileSubshellConverter> d_subshell_converter;\n\n  // The electron momentum dist array\n  ComptonProfileArray d_compton_profile_array;\n};\n\n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end MONTE_CARLO_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "85b21c0ab6ba0e6caaaeab9f5fbc4da037207f75", "size": 10388, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution.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/monte_carlo/collision/photon/src/MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution.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/monte_carlo/collision/photon/src/MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution.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": 45.9646017699, "max_line_length": 120, "alphanum_fraction": 0.6314978822, "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.16566081383421943}}
{"text": "#pragma once\n\n#include <scorum/chain/database/block_tasks/block_tasks.hpp>\n\n#include <scorum/chain/services/comment.hpp>\n#include <scorum/chain/services/comment_statistic.hpp>\n#include <scorum/chain/services/reward_funds.hpp>\n#include <scorum/chain/services/comment_vote.hpp>\n#include <scorum/chain/services/dynamic_global_property.hpp>\n#include <scorum/chain/services/account.hpp>\n#include <scorum/chain/services/account_blogging_statistic.hpp>\n#include <scorum/chain/services/hardfork_property.hpp>\n\n#include <scorum/chain/schema/scorum_objects.hpp>\n#include <scorum/chain/schema/comment_objects.hpp>\n#include <scorum/chain/schema/account_objects.hpp>\n#include <scorum/chain/schema/reward_objects.hpp>\n\n#include <scorum/rewards_math/curve.hpp>\n#include <scorum/rewards_math/formulas.hpp>\n\n#include <boost/range/adaptor/reversed.hpp>\n#include <map>\n\nnamespace scorum {\nnamespace chain {\nnamespace database_ns {\n\nusing scorum::rewards_math::shares_vector_type;\nusing comment_refs_type = scorum::chain::comment_service_i::comment_refs_type;\n\nclass process_comments_cashout_impl\n{\npublic:\n    struct comment_payout_result\n    {\n        /// amount of tokens distributed within particular comment across author, beneficiars and curators\n        asset total_claimed_reward;\n        asset parent_comment_reward;\n    };\n\n    struct curators_author_rewards\n    {\n        asset curators_reward;\n        asset author_reward;\n    };\n\n    explicit process_comments_cashout_impl(block_task_context& ctx);\n\n    template <typename FundService> void update_decreasing_total_claims(FundService& fund_service)\n    {\n        using fund_object_type = typename FundService::object_type;\n\n        const auto& rf = fund_service.get();\n\n        auto now = dgp_service.head_block_time();\n\n        fc::uint128_t total_claims = rewards_math::calculate_decreasing_total_claims(\n            rf.recent_claims, now, rf.last_update, SCORUM_RECENT_RSHARES_DECAY_RATE);\n\n        fund_service.update([&](fund_object_type& rfo) {\n            rfo.recent_claims = total_claims;\n            rfo.last_update = now;\n        });\n    }\n\n    template <typename TFundService> void reward(TFundService& fund_service, const comment_refs_type& comments);\n\n    asset pay_for_comments(const comment_refs_type& comments, const std::vector<asset>& fund_rewards);\n\n    /// These two methods distribute comments reward across all parent comments\n    asset pay_for_comments_legacy(const comment_refs_type& comments, const std::vector<asset>& fund_rewards);\n    comment_payout_result pay_for_comment_legacy(const comment_object& comment,\n                                                 const asset& publication_reward,\n                                                 const asset& parent_payout_value);\n\n    void close_comment_payout(const comment_object& comment);\n\nprivate:\n    std::vector<asset> calculate_comments_payout(const comment_refs_type& comments,\n                                                 const asset& reward_fund_balance,\n                                                 fc::uint128_t total_claims,\n                                                 curve_id reward_curve) const;\n\n    fc::uint128_t\n    get_total_claims(const comment_refs_type& comments, curve_id reward_curve, fc::uint128_t recent_claims) const;\n\n    curators_author_rewards pay_curators(const comment_object& comment, const asset& fund_reward);\n    asset pay_beneficiaries(const comment_object& comment, const asset& author_reward);\n\n    void pay_account(const account_object& recipient, const asset& reward);\n\n    template <class CommentStatisticService>\n    void accumulate_comment_statistic(CommentStatisticService& stat_service,\n                                      const comment_object& comment,\n                                      const asset& fund_reward,\n                                      const asset& total_payout,\n                                      const asset& author_payout,\n                                      const asset& curation_payout,\n                                      const asset& payout_from_children,\n                                      const asset& payout_to_parent,\n                                      const asset& beneficiary_payout)\n    {\n        using comment_object_type = typename CommentStatisticService::object_type;\n\n        const auto& stat = stat_service.get(comment.id);\n        stat_service.update(stat, [&](comment_object_type& c) {\n            c.fund_reward_value += fund_reward;\n            c.total_payout_value += total_payout;\n            c.author_payout_value += author_payout;\n            c.curator_payout_value += curation_payout;\n            c.beneficiary_payout_value += beneficiary_payout;\n            c.from_children_payout_value += payout_from_children;\n            c.to_parent_payout_value += payout_to_parent;\n        });\n    }\n\n    void accumulate_statistic(const comment_object& comment,\n                              const account_object& author,\n                              const asset& fund_reward,\n                              const asset& author_payout,\n                              const asset& curation_payout,\n                              const asset& payout_from_children,\n                              const asset& payout_to_parent,\n                              const asset& beneficiary_payout,\n                              asset_symbol_type reward_symbol);\n\n    void accumulate_statistic(const account_object& voter, const asset& curation_payout);\n\n    comment_refs_type collect_parents(const comment_refs_type& comments);\n\n    fc::shared_string get_permlink(const fc::shared_string& str) const;\n\nprivate:\n    block_task_context& _ctx;\n    dynamic_global_property_service_i& dgp_service;\n    account_service_i& account_service;\n    account_blogging_statistic_service_i& account_blogging_statistic_service;\n    comment_service_i& comment_service;\n    comment_statistic_scr_service_i& comment_statistic_scr_service;\n    comment_statistic_sp_service_i& comment_statistic_sp_service;\n    comment_vote_service_i& comment_vote_service;\n    hardfork_property_service_i& hardfork_service;\n};\n}\n}\n}\n", "meta": {"hexsha": "15842d808d5d170a2292361851d7b82dfe14694a", "size": 6113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/include/scorum/chain/database/block_tasks/comments_cashout_impl.hpp", "max_stars_repo_name": "scorum/scorum", "max_stars_repo_head_hexsha": "1da00651f2fa14bcf8292da34e1cbee06250ae78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:20:48.000Z", "max_issues_repo_path": "libraries/chain/include/scorum/chain/database/block_tasks/comments_cashout_impl.hpp", "max_issues_repo_name": "Scorum/Scorum", "max_issues_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2017-11-25T09:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T09:17:22.000Z", "max_forks_repo_path": "libraries/chain/include/scorum/chain/database/block_tasks/comments_cashout_impl.hpp", "max_forks_repo_name": "Scorum/Scorum", "max_forks_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T19:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:50:42.000Z", "avg_line_length": 41.3040540541, "max_line_length": 114, "alphanum_fraction": 0.6739734991, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.1656040394454387}}
{"text": "/*\n * Copyright (C) 2019-2020 LEIDOS.\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\n#include <ros/ros.h>\n#include <string>\n#include <algorithm>\n#include <memory>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <lanelet2_core/geometry/Point.h>\n#include <trajectory_utils/trajectory_utils.h>\n#include <trajectory_utils/conversions/conversions.h>\n#include <sstream>\n#include <carma_utils/containers/containers.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <unordered_set>\n#include <vector>\n#include <cav_msgs/Trajectory.h>\n#include <cav_msgs/StopAndWaitManeuver.h>\n#include <lanelet2_core/primitives/Lanelet.h>\n#include <lanelet2_core/geometry/LineString.h>\n#include <carma_wm/CARMAWorldModel.h>\n#include <carma_utils/containers/containers.h>\n#include <carma_wm/Geometry.h>\n#include <cav_msgs/TrajectoryPlanPoint.h>\n#include <cav_msgs/TrajectoryPlan.h>\n#include <math.h>\n#include <std_msgs/Float64.h>\n#include <math.h>\n#include <stop_controlled_intersection_plugin.h>\n\nusing oss = std::ostringstream;\n\nnamespace stop_controlled_intersection_transit_plugin\n{\nStopControlledIntersectionTacticalPlugin::StopControlledIntersectionTacticalPlugin(carma_wm::WorldModelConstPtr wm,const StopControlledIntersectionTacticalPluginConfig& config,\n                                    const PublishPluginDiscoveryCB& plugin_discovery_publisher)\n  : wm_(wm), config_(config), plugin_discovery_publisher_(plugin_discovery_publisher)\n  {\n    plugin_discovery_msg_.name = \"StopControlledIntersectionTacticalPlugin\";\n    plugin_discovery_msg_.versionId = \"v1.0\";\n    plugin_discovery_msg_.available = true;\n    plugin_discovery_msg_.activated = false;\n    plugin_discovery_msg_.type = cav_msgs::Plugin::TACTICAL;\n    plugin_discovery_msg_.capability = \"tactical_plan/plan_trajectory\";\n  }\n\nbool StopControlledIntersectionTacticalPlugin::onSpin()\n{\n    plugin_discovery_publisher_(plugin_discovery_msg_);\n    return true;\n}\n\nbool StopControlledIntersectionTacticalPlugin::plan_trajectory_cb(cav_srvs::PlanTrajectoryRequest& req, cav_srvs::PlanTrajectoryResponse& resp)\n{\n    ROS_DEBUG_STREAM(\"Starting stop controlled intersection trajectory planning\");\n    \n    if(req.maneuver_index_to_plan >= req.maneuver_plan.maneuvers.size())\n    {\n    throw std::invalid_argument(\n        \"Stop Control Intersection Plugin asked to plan invalid maneuver index: \" + std::to_string(req.maneuver_index_to_plan) + \n        \" for plan of size: \" + std::to_string(req.maneuver_plan.maneuvers.size()));\n    }\n    std::vector<cav_msgs::Maneuver> maneuver_plan;\n    for(size_t i = req.maneuver_index_to_plan; i < req.maneuver_plan.maneuvers.size(); i++){\n        \n        if((req.maneuver_plan.maneuvers[i].type == cav_msgs::Maneuver::LANE_FOLLOWING || req.maneuver_plan.maneuvers[i].type == cav_msgs::Maneuver::INTERSECTION_TRANSIT_STRAIGHT\n        || req.maneuver_plan.maneuvers[i].type == cav_msgs::Maneuver::INTERSECTION_TRANSIT_LEFT_TURN || req.maneuver_plan.maneuvers[i].type ==cav_msgs::Maneuver::INTERSECTION_TRANSIT_RIGHT_TURN) \n        && GET_MANEUVER_PROPERTY(req.maneuver_plan.maneuvers[i], parameters.string_valued_meta_data.front()) == stop_controlled_intersection_strategy_)\n        {\n            maneuver_plan.push_back(req.maneuver_plan.maneuvers[i]);\n            resp.related_maneuvers.push_back(req.maneuver_plan.maneuvers[i].type);\n        }\n        else\n        {\n            break;\n        }\n    }\n\n    lanelet::BasicPoint2d veh_pos(req.vehicle_state.X_pos_global, req.vehicle_state.Y_pos_global);\n    ROS_DEBUG_STREAM(\"Planning state x:\"<<req.vehicle_state.X_pos_global <<\" , y: \" << req.vehicle_state.Y_pos_global);\n\n    double current_downtrack = wm_->routeTrackPos(veh_pos).downtrack;\n    ROS_DEBUG_STREAM(\"Current_downtrack\"<< current_downtrack);\n\n    std::vector<PointSpeedPair> points_and_target_speeds = maneuvers_to_points( maneuver_plan, wm_, req.vehicle_state);\n\n    //Trajectory Plan\n    cav_msgs::TrajectoryPlan trajectory;\n    trajectory.header.frame_id = \"map\";\n    trajectory.header.stamp = req.header.stamp;\n    trajectory.trajectory_id = boost::uuids::to_string(boost::uuids::random_generator()());\n\n    //Add compose trajectory from centerline\n    trajectory.trajectory_points = compose_trajectory_from_centerline(points_and_target_speeds, req.vehicle_state, req.header.stamp);\n    trajectory.initial_longitudinal_velocity = req.vehicle_state.longitudinal_vel;\n\n    resp.trajectory_plan = trajectory;\n    \n    resp.maneuver_status.push_back(cav_srvs::PlanTrajectory::Response::MANEUVER_IN_PROGRESS);\n\n    return true;\n}\n\nstd::vector<PointSpeedPair> StopControlledIntersectionTacticalPlugin::maneuvers_to_points(const std::vector<cav_msgs::Maneuver>& maneuvers,\n                                                            const carma_wm::WorldModelConstPtr& wm, const cav_msgs::VehicleState& state)\n{\n    std::vector<PointSpeedPair> points_and_target_speeds;\n    std::unordered_set<lanelet::Id> visited_lanelets;\n\n    lanelet::BasicPoint2d veh_pos(state.X_pos_global, state.Y_pos_global);\n    double max_starting_downtrack = wm_->routeTrackPos(veh_pos).downtrack; //The vehicle position\n    double starting_speed = state.longitudinal_vel;\n\n    bool first = true;    \n    double starting_downtrack;\n    for (const auto& maneuver : maneuvers)\n    {\n        if(maneuver.type != cav_msgs::Maneuver::LANE_FOLLOWING && maneuver.type != cav_msgs::Maneuver::INTERSECTION_TRANSIT_STRAIGHT && maneuver.type != cav_msgs::Maneuver::INTERSECTION_TRANSIT_LEFT_TURN\n        && maneuver.type !=cav_msgs::Maneuver::INTERSECTION_TRANSIT_RIGHT_TURN ){\n            throw std::invalid_argument(\"Stop Controlled Intersection Tactical Plugin does not support this maneuver type\");\n        }\n    \n        if(first)\n        {\n            starting_downtrack = GET_MANEUVER_PROPERTY(maneuver, start_dist);\n            if (starting_downtrack > max_starting_downtrack)\n            {\n                starting_downtrack = max_starting_downtrack;\n            }\n            first = false;\n        }\n\n        // Sample the lanelet centerline at fixed increments.\n        // std::min call here is a guard against starting_downtrack being within 1m of the maneuver end_dist\n        // in this case the sampleRoutePoints method will return a single point allowing execution to continue\n        std::vector<lanelet::BasicPoint2d> route_points = wm->sampleRoutePoints(\n            std::min(starting_downtrack + config_.centerline_sampling_spacing, GET_MANEUVER_PROPERTY(maneuver,end_dist)),\n            GET_MANEUVER_PROPERTY(maneuver, end_dist), config_.centerline_sampling_spacing);\n        \n        route_points.insert(route_points.begin(), veh_pos);\n\n        //get case num from maneuver parameters\n        if(GET_MANEUVER_PROPERTY(maneuver,parameters.int_valued_meta_data).empty()){\n            throw std::invalid_argument(\"No case number specified for stop controlled intersection maneuver\");\n        }\n        \n        int case_num = GET_MANEUVER_PROPERTY(maneuver,parameters.int_valued_meta_data[0]);\n        if(case_num == 1){\n            points_and_target_speeds = create_case_one_speed_profile(wm, maneuver, route_points, starting_speed);\n        }\n        else if(case_num == 2){\n            points_and_target_speeds = create_case_two_speed_profile(wm, maneuver, route_points, starting_speed);\n        }\n        else if(case_num == 3)\n        {\n            points_and_target_speeds = create_case_three_speed_profile(wm, maneuver, route_points, starting_speed);\n        }\n        else{\n            throw std::invalid_argument(\"The stop controlled intersection tactical plugin doesn't handle the case number requested\");\n        }\n        \n        \n    }\n\n    return points_and_target_speeds;\n}\n\nstd::vector<PointSpeedPair> StopControlledIntersectionTacticalPlugin::create_case_one_speed_profile(const carma_wm::WorldModelConstPtr& wm,\nconst cav_msgs::Maneuver& maneuver, std::vector<lanelet::BasicPoint2d>& route_geometry_points, double starting_speed){\n    //Derive meta data values from maneuver message - Using order in sci_strategic_plugin\n    double a_acc = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[0]);\n    double a_dec = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[1]); //a_dec is a -ve value\n    double t_acc = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[2]);\n    double t_dec = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[3]);\n    double speed_before_decel = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[4]);\n    \n    //Derive start and end dist from maneuver\n    double start_dist = GET_MANEUVER_PROPERTY(maneuver, start_dist);\n    double end_dist = GET_MANEUVER_PROPERTY(maneuver, end_dist);\n\n    //Checking route geometry start against start_dist and adjust profile\n    double route_starting_downtrack = wm->routeTrackPos(route_geometry_points[0]).downtrack;  //Starting downtrack based on geometry points\n    double dist_acc;        //Distance for which acceleration lasts\n\n    if(route_starting_downtrack < start_dist){\n        //Update parameters\n        //Keeping the deceleration part the same\n        double dist_decel = pow(speed_before_decel, 2)/(2*std::abs(a_dec));\n\n        dist_acc = end_dist - dist_decel;\n        a_acc = (pow(speed_before_decel, 2) - pow(starting_speed,2))/(2*dist_acc);\n    }\n    else{\n        //Use parameters from maneuver message\n        dist_acc = (pow(speed_before_decel, 2) - pow(starting_speed, 2))/(2*a_acc);\n    }\n\n    std::vector<PointSpeedPair> points_and_target_speeds;\n    PointSpeedPair first_point;\n    first_point.point = route_geometry_points[0];\n    first_point.speed = starting_speed;\n    points_and_target_speeds.push_back(first_point);\n\n    lanelet::BasicPoint2d prev_point = route_geometry_points[0];\n    double total_dist_covered = 0;                  //Starting dist for maneuver treated as 0.0\n\n    for(size_t i = 1; i < route_geometry_points.size(); i++){\n        lanelet::BasicPoint2d current_point = route_geometry_points[i];\n        double delta_d = lanelet::geometry::distance2d(prev_point, current_point);\n        total_dist_covered += delta_d;      \n        //Find speed at dist covered\n        double speed_i; \n        if(total_dist_covered <= dist_acc){\n            //Acceleration part\n            speed_i = sqrt(pow(starting_speed,2) + 2*a_acc*total_dist_covered);\n        }\n        else{\n            //Deceleration part\n            speed_i = sqrt(std::max(pow(speed_before_decel,2) + 2*a_dec*(total_dist_covered - dist_acc),0.0)); //std::max to ensure negative value is not sqrt\n            if(speed_i < epsilon_){\n                speed_i = 0.0;\n            }\n        }\n\n        PointSpeedPair p;\n        p.point = route_geometry_points[i];\n        p.speed = speed_i;\n        points_and_target_speeds.push_back(p);\n\n        prev_point = route_geometry_points[i];\n    }\n\n    return points_and_target_speeds;\n\n}\n\nstd::vector<PointSpeedPair> StopControlledIntersectionTacticalPlugin::create_case_two_speed_profile(const carma_wm::WorldModelConstPtr& wm,\nconst cav_msgs::Maneuver& maneuver, std::vector<lanelet::BasicPoint2d>& route_geometry_points, double starting_speed){\n    \n    //Derive meta data values from maneuver message - Using order in sci_strategic_plugin\n    double a_acc = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[0]);\n    double a_dec = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[1]); //a_dec is a -ve value\n    double t_acc = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[2]);\n    double t_dec = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[3]);\n    double t_cruise = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[4]);\n    double speed_before_decel = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[5]);\n\n    //Derive start and end dist from maneuver\n    double start_dist = GET_MANEUVER_PROPERTY(maneuver, start_dist);\n    double end_dist = GET_MANEUVER_PROPERTY(maneuver, end_dist);\n\n    //Checking route geometry start against start_dist and adjust profile\n    double route_starting_downtrack = wm->routeTrackPos(route_geometry_points[0]).downtrack;  //Starting downtrack based on geometry points\n    double dist_acc;        //Distance over which acceleration happens\n    double dist_cruise;     //Distance over which cruising happens\n    double dist_decel;      //Distance over which deceleration happens\n\n    if(route_starting_downtrack < start_dist){\n        //update parameters\n        //Keeping acceleration and deceleration part same as planned in strategic plugin\n        dist_acc = starting_speed*t_acc + 0.5 * a_acc * pow(t_acc,2);\n        dist_decel = speed_before_decel*t_dec + 0.5 * a_dec * pow(t_dec,2);\n        dist_cruise = end_dist - route_starting_downtrack - (dist_acc + dist_decel);\n    }\n    else{   \n        //Use maneuver parameters to create speed profile\n        dist_acc = starting_speed*t_acc + 0.5 * a_acc * pow(t_acc,2);\n        dist_cruise = speed_before_decel*t_cruise;\n        dist_decel = speed_before_decel*t_dec + 0.5 * a_dec * pow(t_dec,2);\n    }\n\n    //Check calculated total dist against maneuver limits\n    double total_distance_needed = dist_acc + dist_cruise + dist_decel;\n    if(total_distance_needed - (end_dist - start_dist) > epsilon_ ){\n        //Requested maneuver needs to be modified to meet start and end dist req\n        //Sacrifice on cruising and then acceleration if needed\n        double delta_total_dist = total_distance_needed - (end_dist - start_dist);\n        dist_cruise -= delta_total_dist;\n        if(dist_cruise < 0){\n            dist_acc += dist_cruise;\n            dist_cruise = 0;\n        }\n        //Not considering dist_acc < 0 after this.\n    }\n\n    std::vector<PointSpeedPair> points_and_target_speeds;\n    PointSpeedPair first_point;\n    first_point.point = route_geometry_points[0];\n    first_point.speed = starting_speed;\n    points_and_target_speeds.push_back(first_point);\n\n    lanelet::BasicPoint2d prev_point = route_geometry_points.front();\n    double total_dist_planned = 0;                  //Starting dist for maneuver treated as 0.0\n    double prev_speed = starting_speed;\n    for(auto route_point : route_geometry_points){\n        lanelet::BasicPoint2d current_point = route_point;\n        double delta_d = lanelet::geometry::distance2d(prev_point, current_point);\n        total_dist_planned += delta_d;  \n\n        //Find speed at dist covered\n        double speed_i;\n        if(total_dist_planned < dist_acc){\n            //Acceleration part\n            speed_i = sqrt(pow(starting_speed,2) + 2*a_acc*total_dist_planned);\n        }\n        else if(dist_cruise > 0 && total_dist_planned >= dist_acc && total_dist_planned <= (dist_acc + dist_cruise)){\n            //Cruising part\n            speed_i = prev_speed;\n        }\n        else{\n            //Deceleration part\n            speed_i = sqrt(std::max(pow(speed_before_decel,2) + 2*a_dec*(total_dist_planned - dist_acc - dist_cruise),0.0));//std::max to ensure negative value is not sqrt\n        }\n        \n        PointSpeedPair p;\n        p.point = route_point;\n        p.speed = std::min(speed_i,speed_before_decel);\n        points_and_target_speeds.push_back(p);\n\n        prev_point = route_point;\n        prev_speed = speed_i;\n    }\n\n    return points_and_target_speeds;\n\n}\n\nstd::vector<PointSpeedPair> StopControlledIntersectionTacticalPlugin::create_case_three_speed_profile(const carma_wm::WorldModelConstPtr& wm,\nconst cav_msgs::Maneuver& maneuver, std::vector<lanelet::BasicPoint2d>& route_geometry_points, double starting_speed){\n    //Derive meta data values from maneuver message - Using order in sci_strategic_plugin\n    double a_dec = GET_MANEUVER_PROPERTY(maneuver, parameters.float_valued_meta_data[0]);\n\n    //Derive start and end dist from maneuver\n    double start_dist = GET_MANEUVER_PROPERTY(maneuver, start_dist);\n    double end_dist = GET_MANEUVER_PROPERTY(maneuver, end_dist);\n\n    //Checking route geometry start against start_dist and adjust profile\n    double route_starting_downtrack = wm->routeTrackPos(route_geometry_points[0]).downtrack;  //Starting downtrack based on geometry points\n\n    if(route_starting_downtrack < start_dist){\n        //update parameter\n        a_dec = pow(starting_speed, 2)/(2*(end_dist - route_starting_downtrack));\n    }\n\n    std::vector<PointSpeedPair> points_and_target_speeds;\n    PointSpeedPair first_point;\n    first_point.point = route_geometry_points[0];\n    first_point.speed = starting_speed;\n    points_and_target_speeds.push_back(first_point);\n\n    lanelet::BasicPoint2d prev_point = route_geometry_points[0];\n    double total_dist_covered = 0;          //Starting dist for maneuver treated as 0.0\n\n    for(size_t i = 0;i < route_geometry_points.size(); i++){\n        lanelet::BasicPoint2d current_point = route_geometry_points[i];\n        double delta_d = lanelet::geometry::distance2d(prev_point, current_point);\n        total_dist_covered +=delta_d;\n        //Find speed at dist covered\n        double speed_i = sqrt(std::max(pow(starting_speed,2) + 2 * a_dec * total_dist_covered, 0.0)); //std::max to ensure negative value is not sqrt\n        \n        if(speed_i < epsilon_){\n            speed_i = 0.0;\n        }\n    \n        PointSpeedPair p;\n        p.point = route_geometry_points[i];\n        p.speed = speed_i;\n        points_and_target_speeds.push_back(p);\n\n        prev_point = current_point;\n    }\n\n    return points_and_target_speeds;\n}\n\nstd::vector<cav_msgs::TrajectoryPlanPoint> StopControlledIntersectionTacticalPlugin::compose_trajectory_from_centerline(\n    const std::vector<PointSpeedPair>& points, const cav_msgs::VehicleState& state, const ros::Time& state_time){\n    \n    std::vector<cav_msgs::TrajectoryPlanPoint> trajectory;\n    ROS_DEBUG_STREAM(\"VehicleState: \"\n                        << \" x: \" << state.X_pos_global << \" y: \" << state.Y_pos_global << \" yaw: \" << state.orientation\n                        << \" speed: \" << state.longitudinal_vel);\n    \n    int nearest_pt_index = basic_autonomy::waypoint_generation::get_nearest_point_index(points, state);\n\n    std::vector<PointSpeedPair> future_points(points.begin() + nearest_pt_index + 1, points.end()); //Points in front of current vehicle position\n    auto time_bound_points = basic_autonomy::waypoint_generation::constrain_to_time_boundary(future_points, config_.trajectory_time_length);\n\n    ROS_DEBUG_STREAM(\"Got time bound points with size:\" << time_bound_points.size());\n\n    //Attach past points\n    std::vector<PointSpeedPair> back_and_future = attach_past_points(points, time_bound_points, nearest_pt_index, config_.back_distance);\n    ROS_DEBUG_STREAM(\"Got back_and_future points with size: \"<<back_and_future.size());\n\n    std::vector<double> speed_limits;\n    std::vector<lanelet::BasicPoint2d> curve_points;\n    split_point_speed_pairs(time_bound_points, &curve_points, &speed_limits);\n\n    std::unique_ptr<basic_autonomy::smoothing::SplineI> fit_curve = basic_autonomy::waypoint_generation::compute_fit(curve_points); //Compute splines based on curve points\n    if(!fit_curve)\n    {\n        throw std::invalid_argument(\"Could not fit a spline curve along the trajectory!\");\n    }\n\n    ROS_DEBUG(\"Got fit\");\n    ROS_DEBUG_STREAM(\"Speed_limits.size(): \"<<speed_limits.size());\n\n    std::vector<lanelet::BasicPoint2d> all_sampling_points;\n    all_sampling_points.reserve(1 + curve_points.size() * 2);\n\n    std::vector<double> distributed_speed_limits;\n    distributed_speed_limits.reserve(1+ curve_points.size() * 2);\n\n    //Compute total length of the trajectory to get correct number of points\n    // we expect using curve resample step size\n    std::vector<double> downtracks_raw = carma_wm::geometry::compute_arc_lengths(curve_points);\n\n    auto total_step_along_curve = static_cast<int>(downtracks_raw.back() / config_.curve_resample_step_size);\n\n    int current_speed_index = 0;\n    size_t total_point_size = curve_points.size();\n\n    double step_threshold_for_next_speed = (double)total_step_along_curve / (double)total_point_size;\n    double scaled_steps_along_curve = 0.0; // from 0 (start) to 1 (end) for the whole trajectory\n    std::vector<double> better_curvature;\n    better_curvature.reserve(1 + curve_points.size() * 2);\n\n    for (size_t steps_along_curve = 0; steps_along_curve < total_step_along_curve; steps_along_curve++) // Resample curve at tighter resolution\n    {\n        lanelet::BasicPoint2d p = (*fit_curve)(scaled_steps_along_curve);\n        all_sampling_points.push_back(p);\n        double c = basic_autonomy::waypoint_generation::compute_curvature_at((*fit_curve), scaled_steps_along_curve);\n        better_curvature.push_back(c);\n\n        if((double) steps_along_curve > step_threshold_for_next_speed)\n        {\n            step_threshold_for_next_speed += (double)total_step_along_curve / (double)total_point_size;\n            current_speed_index++;\n        }\n        distributed_speed_limits.push_back(speed_limits[current_speed_index]);  //Identify speed limits for resampled points\n        scaled_steps_along_curve += 1.0 / total_step_along_curve;               //adding steps_along_curve_step_size\n    }\n\n    ROS_DEBUG_STREAM(\"Got sampled points with size:\" << all_sampling_points.size());\n\n    std::vector<double> final_yaw_values = carma_wm::geometry::compute_tangent_orientations(all_sampling_points);\n\n    std::vector<double> curvatures = basic_autonomy::smoothing::moving_average_filter(better_curvature, config_.curvature_moving_average_window_size, false);\n    std::vector<double> ideal_speeds =\n        trajectory_utils::constrained_speeds_for_curvatures(curvatures, config_.lateral_accel_limit);\n\n    std::vector<double> constrained_speed_limits = basic_autonomy::waypoint_generation::apply_speed_limits(ideal_speeds, distributed_speed_limits); //Speed min(ideal, calculated)\n    ROS_DEBUG(\"Processed all points in computed fit\");\n    std::vector<double> final_actual_speeds = constrained_speed_limits;\n\n    if (all_sampling_points.empty())\n    {\n        ROS_WARN_STREAM(\"No trajectory points could be generated\");\n        return {};\n    }\n\n    //Drop Past points\n    nearest_pt_index = basic_autonomy::waypoint_generation::get_nearest_index_by_downtrack(all_sampling_points, wm_, state);\n    std::vector<lanelet::BasicPoint2d> future_basic_points(all_sampling_points.begin() + nearest_pt_index + 1,\n                                                            all_sampling_points.end());\n    std::vector<double> future_speeds(final_actual_speeds.begin() + nearest_pt_index + 1, \n                                    final_actual_speeds.end());                                                            \n    std::vector<double> future_yaw(final_yaw_values.begin() + nearest_pt_index + 1,\n                                    final_yaw_values.end());\n\n    // Add current vehicle point to front of the trajectory\n    lanelet::BasicPoint2d cur_veh_point(state.X_pos_global, state.Y_pos_global);\n\n    future_basic_points.insert(future_basic_points.begin(),\n                                cur_veh_point); // Add current vehicle position to front of sample points\n    future_speeds.insert(future_speeds.begin(), state.longitudinal_vel);\n    future_yaw.insert(future_yaw.begin(), state.orientation);\n\n    // Compute points to local downtracks\n    std::vector<double> downtracks = carma_wm::geometry::compute_arc_lengths(future_basic_points);\n\n    final_actual_speeds = basic_autonomy::smoothing::moving_average_filter(future_speeds, config_.speed_moving_average_window_size);\n\n    // Convert speeds to times\n    std::vector<double> times;\n\n    //Force last point speed to 0.0 if close to end\n    if(lanelet::geometry::distance2d(future_basic_points.back(), points.back().point) < epsilon_){\n        final_actual_speeds.back() = 0.0;\n    }\n\n    trajectory_utils::conversions::speed_to_time(downtracks, final_actual_speeds, &times);\n\n    // Build trajectory points\n    std::vector<cav_msgs::TrajectoryPlanPoint> traj_points =\n        basic_autonomy::waypoint_generation::trajectory_from_points_times_orientations(future_basic_points, times, future_yaw, state_time);\n\n    return traj_points;\n}\n\n\n}", "meta": {"hexsha": "7d45fc4ba79222e8acafcb796895eac13f976de7", "size": 24737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stop_controlled_intersection_tactical_plugin/src/stop_controlled_intersection_tactical_plugin.cpp", "max_stars_repo_name": "usdot-fhwa-stol/carma-platform", "max_stars_repo_head_hexsha": "d45a1afbf1efdb0b8cd62fcec5a3033b7306df33", "max_stars_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2020-04-27T17:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:27:14.000Z", "max_issues_repo_path": "stop_controlled_intersection_tactical_plugin/src/stop_controlled_intersection_tactical_plugin.cpp", "max_issues_repo_name": "usdot-fhwa-stol/carma-platform", "max_issues_repo_head_hexsha": "d45a1afbf1efdb0b8cd62fcec5a3033b7306df33", "max_issues_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_issues_count": 982.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T11:28:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:12:19.000Z", "max_forks_repo_path": "stop_controlled_intersection_tactical_plugin/src/stop_controlled_intersection_tactical_plugin.cpp", "max_forks_repo_name": "usdot-fhwa-stol/carma-platform", "max_forks_repo_head_hexsha": "d45a1afbf1efdb0b8cd62fcec5a3033b7306df33", "max_forks_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_forks_count": 57.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T15:48:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T23:31:45.000Z", "avg_line_length": 47.6628131021, "max_line_length": 203, "alphanum_fraction": 0.7222379432, "num_tokens": 5784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.16560403477968896}}
{"text": "#ifdef USE_CUDNN\n#include <algorithm>\n#include <vector>\n\n#include \"caffe/filler.hpp\"\n#include \"caffe/layer.hpp\"\n#include \"caffe/util/im2col.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/vision_layers.hpp\"\n\n#include <boost/unordered_map.hpp>\n#include <cudnn.h>\n\nusing boost::unordered_map;\n\nnamespace caffe {\n\n// Set to three for the benefit of the backward pass, which\n// can use separate streams for calculating the gradient w.r.t.\n// bias, filter weights, and bottom data for each group independently\n#define CUDNN_FWD_STREAMS_PER_GROUP 1\n#define CUDNN_BWD_STREAMS_PER_GROUP 2\n\ntemplate <typename Dtype>\nshared_ptr<SyncedMemory> CuDNNConvolutionLayer<Dtype>::workspaceData_fwd;\ntemplate <typename Dtype>\nshared_ptr<SyncedMemory> CuDNNConvolutionLayer<Dtype>::workspaceData_bwd_filter;\ntemplate <typename Dtype>\nshared_ptr<SyncedMemory> CuDNNConvolutionLayer<Dtype>::workspaceData_bwd_data;\n\ntemplate <typename Dtype>\nsize_t CuDNNConvolutionLayer<Dtype>::conv_layer_count = 0;\n\n\n/**\n * TODO(dox) explain cuDNN interface\n */\ntemplate <typename Dtype>\nvoid CuDNNConvolutionLayer<Dtype>::LayerSetUp(\n    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {\n  ConvolutionLayer<Dtype>::LayerSetUp(bottom, top);\n\n  if (conv_layer_count == 0){\n    workspaceData_fwd = shared_ptr<SyncedMemory>(new SyncedMemory());\n    workspaceData_bwd_filter = shared_ptr<SyncedMemory>(new SyncedMemory());\n    workspaceData_bwd_data = shared_ptr<SyncedMemory>(new SyncedMemory());\n  }\n  conv_layer_count++;\n\n  // Initialize CUDA streams and cuDNN.\n  int total_streams_per_group = CUDNN_FWD_STREAMS_PER_GROUP + CUDNN_BWD_STREAMS_PER_GROUP;\n  stream_         = new cudaStream_t[this->group_ * total_streams_per_group];\n  handle_         = new cudnnHandle_t[this->group_ * total_streams_per_group];\n\n\n  // initialize size arrays\n  workspace_fwd_offsets_ = new size_t[bottom.size()];\n  workspace_bwd_filter_offsets_ = new size_t[bottom.size()];\n  workspace_bwd_data_offsets_ = new size_t[bottom.size()];\n\n\n  for (size_t i = 0; i < bottom.size(); ++i) {\n    // initialize all to default algorithms\n    fwd_algo_.push_back((cudnnConvolutionFwdAlgo_t)0);\n    bwd_filter_algo_.push_back((cudnnConvolutionBwdFilterAlgo_t)0);\n    bwd_data_algo_.push_back((cudnnConvolutionBwdDataAlgo_t)0);\n    // default algorithms don't require workspace\n    workspace_fwd_offsets_[i] = 0;\n    workspace_bwd_filter_offsets_[i] = 0;\n    workspace_bwd_data_offsets_[i] = 0;\n  }\n\n  for (int g = 0; g < this->group_ * total_streams_per_group; g++) {\n    CUDA_CHECK(cudaStreamCreate(&stream_[g]));\n    CUDNN_CHECK(cudnnCreate(&handle_[g]));\n    CUDNN_CHECK(cudnnSetStream(handle_[g], stream_[g]));\n  }\n\n  // Set the indexing parameters.\n\n  bias_offset_ = (this->num_output_ / this->group_);\n\n  std::vector<int> kernel_shape;\n  kernel_shape.push_back(this->num_output_ / this->group_);\n  kernel_shape.push_back(this->channels_ / this->group_);\n  for (unsigned int i = 0; i < this->num_spatial_axes_; ++i)\n    kernel_shape.push_back(this->kernel_shape_.cpu_data()[i]);\n\n  cudnn::createNdFilterDesc<Dtype>(&filter_desc_, kernel_shape);\n\n  // Create tensor descriptor(s) for data and corresponding convolution(s).\n  for (int i = 0; i < bottom.size(); i++) {\n    cudnnTensorDescriptor_t bottom_desc;\n    cudnn::createTensorDesc<Dtype>(&bottom_desc);\n    bottom_descs_.push_back(bottom_desc);\n    cudnnTensorDescriptor_t top_desc;\n    cudnn::createTensorDesc<Dtype>(&top_desc);\n    top_descs_.push_back(top_desc);\n    cudnnConvolutionDescriptor_t conv_desc;\n    cudnn::createConvolutionDesc<Dtype>(&conv_desc);\n    conv_descs_.push_back(conv_desc);\n  }\n\n  // Tensor descriptor for bias.\n  if (this->bias_term_) {\n    cudnn::createTensorDesc<Dtype>(&bias_desc_);\n  }\n\n  handles_setup_ = true;\n  need_benchmark_ = true;\n\n}\n\ntemplate <typename Dtype>\nvoid CuDNNConvolutionLayer<Dtype>::Reshape(\n    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {\n  ConvolutionLayer<Dtype>::Reshape(bottom, top);\n\n  bottom_offset_ = this->bottom_dim_ / this->group_;\n  top_offset_ = this->top_dim_ / this->group_;\n\n  std::vector<int> bottom_tensor_shape(bottom[0]->shape());\n  bottom_tensor_shape[1] /= this->group_;\n  std::vector<int> bottom_tensor_stride(bottom[0]->shape().size(), 1);\n  for (int i = bottom[0]->shape().size() - 2; i >= 0; --i) {\n    bottom_tensor_stride[i] =\n        bottom[0]->shape(i + 1) * bottom_tensor_stride[i + 1];\n  }\n\n  std::vector<int> top_tensor_shape(top[0]->shape());\n  top_tensor_shape[1] /= this->group_;\n  std::vector<int> top_tensor_stride(top[0]->shape().size(), 1);\n  for (int i = top[0]->shape().size() - 2; i >= 0; --i) {\n    top_tensor_stride[i] = top[0]->shape(i + 1) * top_tensor_stride[i + 1];\n  }\n\n  std::vector<int> pad, stride;\n  for (unsigned int i = 0; i < this->num_spatial_axes_; ++i) {\n    pad.push_back(this->pad_.cpu_data()[i]);\n    stride.push_back(this->stride_.cpu_data()[i]);\n  }\n  // Specify workspace limit for kernels directly until we have a\n  // planning strategy and a rewrite of Caffe's GPU memory mangagement.\n  //\n  // However this can be tuned by the \"richness\" parameter in the solver protobuf\n  // By setting richness, you can increase the memory available to cuDNN and thus\n  // let it choose fast but space consuming algorithms.\n  for (int i = 0; i < bottom.size(); i++) {\n\n\n    cudnn::setTensorNdDesc<Dtype>(&bottom_descs_[i],\n        bottom_tensor_shape, bottom_tensor_stride);\n    cudnn::setTensorNdDesc<Dtype>(&top_descs_[i],\n        top_tensor_shape, top_tensor_stride);\n    cudnn::setNdConvolutionDesc<Dtype>(&conv_descs_[i], bottom_descs_[i],\n        filter_desc_, pad, stride);\n\n  if (need_benchmark_){\n      // choose forward and backward algorithms + workspace(s)\n      const int kRequestedForwardAlgoCount = 6;\n      vector<cudnnConvolutionFwdAlgoPerf_t> fwd_perf;\n      fwd_perf.resize(kRequestedForwardAlgoCount);\n      int returnedAlgoCount;\n      size_t mem_limit = 200*1024*1024;\n      CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm (handle_[0], bottom_descs_[i], filter_desc_, conv_descs_[i], top_descs_[i],CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,mem_limit, &fwd_algo_[i]));\n/*\n      CUDNN_CHECK(cudnnGetConvolutionForwardWorkspaceSize(handle_[0],\n                                                       bottom_descs_[i],\n                                                       filter_desc_,\n                                                       conv_descs_[i],\n                                                       top_descs_[i],\n                                                       kRequestedForwardAlgoCount,\n                                                       &returnedAlgoCount,\n                                                       &fwd_perf[0]));\n\n      // choose the fastest within limit\n      // if all algorithms exceed memory limit, we will use the 0 algorithm with no workspace\n      for (int a = 0; a < kRequestedForwardAlgoCount; ++a){\n        if (fwd_perf[a].memory * this->group_ < (Caffe::cudnn_mem_richness() * 1024 * 1024)\n            || Caffe::cudnn_mem_richness() == 0){\n          fwd_algo_[i] = fwd_perf[a].algo;\n          break;\n        }\n      }\n*/\n\n      // choose backward algorithm for filter\n      const int kRequestedBackwardFilterAlgoCount = 4;\n      vector<cudnnConvolutionBwdFilterAlgoPerf_t> bwd_filter_perf;\n      bwd_filter_perf.resize(kRequestedBackwardFilterAlgoCount);\n      CUDNN_CHECK(cudnnGetConvolutionBackwardFilterAlgorithm(handle_[0], bottom_descs_[i], top_descs_[i], conv_descs_[i], filter_desc_,\n                                                                   CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,\n                                                                   mem_limit,\n                                                                   &bwd_filter_algo_[i]));\n\n \n/*\n      CUDNN_CHECK(cudnnFindConvolutionBackwardFilterAlgorithm(handle_[0],\n                                                              bottom_descs_[i],\n                                                              top_descs_[i],\n                                                              conv_descs_[i],\n                                                              filter_desc_,\n                                                              kRequestedBackwardFilterAlgoCount,\n                                                              &returnedAlgoCount,\n                                                              &bwd_filter_perf[0]));\n\n      // choose the fastest within limit\n      // if all algorithms exceed memory limit, we will use the 0 algorithm with no workspace\n      for (int a = 0; a < kRequestedBackwardFilterAlgoCount; ++a){\n        if (bwd_filter_perf[a].memory * this->group_ < (Caffe::cudnn_mem_richness() * 1024 * 1024)\n            || Caffe::cudnn_mem_richness() == 0){\n          bwd_filter_algo_[i] = bwd_filter_perf[a].algo;\n          break;\n        }\n      }\n\n*/\n      // choose backward algo for data\n      const int kRequestedBackwardDataAlgoCount = 4;\n      vector<cudnnConvolutionBwdDataAlgoPerf_t> bwd_data_perf;\n      bwd_data_perf.resize(kRequestedBackwardDataAlgoCount);\n\n           //backward data\n            CUDNN_CHECK(cudnnGetConvolutionBackwardDataAlgorithm(handle_[0],\n                                                                 filter_desc_, top_descs_[i], conv_descs_[i], bottom_descs_[i],\n                                                                 CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,\n                                                                 mem_limit,\n                                                                 &bwd_data_algo_[i]));\n/*\n      CUDNN_CHECK(cudnnFindConvolutionBackwardDataAlgorithm(handle_[0],\n                                                            filter_desc_,\n                                                            top_descs_[i],\n                                                            conv_descs_[i],\n                                                            bottom_descs_[i],\n                                                            kRequestedBackwardDataAlgoCount,\n                                                            &returnedAlgoCount,\n                                                            &bwd_data_perf[0]));\n\n      // choose the fastest within limit\n      // if all algorithms exceed memory limit, we will use the 0 algorithm with no workspace\n      for (int a = 0; a < kRequestedBackwardDataAlgoCount; ++a){\n        if (bwd_data_perf[a].memory * this->group_ <(Caffe::cudnn_mem_richness() * 1024 * 1024)\n            || Caffe::cudnn_mem_richness() == 0){\n          bwd_data_algo_[i] = bwd_data_perf[a].algo;\n          break;\n        }\n      }\n*/\n\n      need_benchmark_ = false;\n    }\n  }\n\n\n  // Tensor descriptor for bias.\n  if (this->bias_term_) {\n\n    vector<int> bias_shape(bottom[0]->shape().size(), 1);\n    bias_shape[1] = this->num_output_ / this->group_;\n    cudnn::setTensorNdDesc<Dtype>(&bias_desc_, bias_shape);\n  }\n\n  AdjustWorkSpaces();\n}\n\ntemplate<typename Dtype>\nvoid CuDNNConvolutionLayer<Dtype>::AdjustWorkSpaces() {\n\n  size_t workspace_size_fwd = 0;\n  size_t workspace_size_bwd_data = 0;\n  size_t workspace_size_bwd_filter = 0;\n\n  for (int i = 0; i < fwd_algo_.size(); ++i){\n    size_t workspace_size;\n    cudnnGetConvolutionForwardWorkspaceSize(handle_[0],\n                                            bottom_descs_[i], filter_desc_,\n                                            conv_descs_[i],\n                                            top_descs_[i],\n                                            fwd_algo_[i], &workspace_size);\n    workspace_fwd_offsets_[i] = workspace_size;\n    workspace_size_fwd = std::max(workspace_size * this->group_, workspace_size_fwd);\n\n    cudnnGetConvolutionBackwardFilterWorkspaceSize(handle_[1],\n                                                   bottom_descs_[i], top_descs_[i],\n                                                   conv_descs_[i],\n                                                   filter_desc_,\n                                                   bwd_filter_algo_[i], &workspace_size);\n    workspace_bwd_filter_offsets_[i] = workspace_size;\n    workspace_size_bwd_filter = std::max(workspace_size * this->group_, workspace_size_bwd_filter);\n\n    cudnnGetConvolutionBackwardDataWorkspaceSize(handle_[2],\n                                                 filter_desc_,\n                                                 top_descs_[i],\n                                                 conv_descs_[i],\n                                                 bottom_descs_[i],\n                                                 bwd_data_algo_[i], &workspace_size);\n    workspace_bwd_data_offsets_[i] = workspace_size;\n    workspace_size_bwd_data = std::max(workspace_size * this->group_, workspace_size_bwd_data);\n  }\n\n  workspaceData_fwd->Resize(workspace_size_fwd);\n  workspaceData_bwd_filter->Resize(workspace_size_bwd_filter);\n  workspaceData_bwd_data->Resize(workspace_size_bwd_data);\n}\n\ntemplate <typename Dtype>\nCuDNNConvolutionLayer<Dtype>::~CuDNNConvolutionLayer() {\n  // Check that handles have been setup before destroying.\n  if (!handles_setup_) { return; }\n\n  for (int i = 0; i < bottom_descs_.size(); i++) {\n    cudnnDestroyTensorDescriptor(bottom_descs_[i]);\n    cudnnDestroyTensorDescriptor(top_descs_[i]);\n    cudnnDestroyConvolutionDescriptor(conv_descs_[i]);\n  }\n  if (this->bias_term_) {\n    cudnnDestroyTensorDescriptor(bias_desc_);\n  }\n  cudnnDestroyFilterDescriptor(filter_desc_);\n\n  int total_stream_per_group = CUDNN_FWD_STREAMS_PER_GROUP + CUDNN_BWD_STREAMS_PER_GROUP;\n  for (int g = 0; g < this->group_ * total_stream_per_group; g++) {\n    cudaStreamDestroy(stream_[g]);\n    cudnnDestroy(handle_[g]);\n  }\n\n  --conv_layer_count;\n  if (conv_layer_count == 0){\n    workspaceData_fwd.reset();\n    workspaceData_bwd_filter.reset();\n    workspaceData_bwd_data.reset();\n  }\n\n  delete [] stream_;\n  delete [] handle_;\n  delete [] workspace_fwd_offsets_;\n  delete [] workspace_bwd_data_offsets_;\n  delete [] workspace_bwd_filter_offsets_;\n\n}\n\nINSTANTIATE_CLASS(CuDNNConvolutionLayer);\n\n}   // namespace caffe\n#endif\n", "meta": {"hexsha": "15b1c468650aea460b19c620791f673d570319a9", "size": 14153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "caffe_3d/src/caffe/layers/cudnn_conv_layer.cpp", "max_stars_repo_name": "Vanu1/ECO-efficient-video-understanding", "max_stars_repo_head_hexsha": "f7d407db9d615c1eb67e06f09b8a02f524ae6431", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 449.0, "max_stars_repo_stars_event_min_datetime": "2018-04-23T16:11:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T02:31:26.000Z", "max_issues_repo_path": "caffe_3d/src/caffe/layers/cudnn_conv_layer.cpp", "max_issues_repo_name": "Vanu1/ECO-efficient-video-understanding", "max_issues_repo_head_hexsha": "f7d407db9d615c1eb67e06f09b8a02f524ae6431", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2018-05-08T01:36:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-31T23:08:11.000Z", "max_forks_repo_path": "caffe_3d/src/caffe/layers/cudnn_conv_layer.cpp", "max_forks_repo_name": "Vanu1/ECO-efficient-video-understanding", "max_forks_repo_head_hexsha": "f7d407db9d615c1eb67e06f09b8a02f524ae6431", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 101.0, "max_forks_repo_forks_event_min_datetime": "2018-04-30T01:44:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T15:39:45.000Z", "avg_line_length": 40.9046242775, "max_line_length": 202, "alphanum_fraction": 0.6078569915, "num_tokens": 3292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.16559273436806177}}
{"text": "\n#include <cry/cry.h>\n\n#include <iostream>\n#include <sstream>\n\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nnamespace cry\n{\n    const char* defualt_crypt_string = CRY_DEFAULT_IV;\n    \n    struct CryptDetail\n    {\n        size_t          keylength;\n        std::string     key;\n        size_t          blocklength;\n        std::string     block;\n    };\n\n\n    class CryPrivate\n    {\n        public:\n            CryPrivate ( Cry *q )\n                :   _password ( CRY_DEFAULT_PASSWORD )\n            {\n                _q = q;\n            }\n\n        public:\n            // ==========================================================================\n\n            void encryptImpl ( std::string file, EncryptionType type=GPG_ALGO )\n            {\n#if CRY_ENCRYPT\n                size_t filesize = identifyFile ( file );\n\n                if ( filesize == 0 )\n                {\n#if DBG\n                    std::cerr << \"Could not find file\" << std::endl;\n#endif\n                    return;\n                }\n\n                gcry_cipher_hd_t hd;\n\n                gcry_error_t err = gcry_cipher_open ( &hd, type, GCRY_CIPHER_MODE_CBC, 0 );\n\n                CryptDetail cd = getCryptDetails ( type );\n\n                err = gcry_cipher_setkey ( hd, cd.key.c_str(), cd.keylength );\n\n                err = gcry_cipher_setiv ( hd, cd.block.c_str(), cd.blocklength );\n\n                fs::path p ( file );\n\n                if ( !fs::exists ( p )\n                        && !fs::is_regular_file ( p ) )\n                {\n                    return;\n                }\n\n                std::fstream fs;\n                fs.open ( p.string(), std::fstream::in | std::fstream::binary );\n\n                std::stringstream ss;\n                ss << file << CRY_EXT;\n\n                std::fstream fsout;\n                fsout.open ( ss.str(), std::fstream::out | std::fstream::binary );\n\n\n                size_t cnt = CRY_BUFFER_MULT * cd.blocklength;\n\n                CryHeader hdr;\n                hdr.filesize = filesize;\n                hdr.filenamesize = file.size();\n                hdr.filename = new char[hdr.filenamesize + 1];\n\n                memset ( hdr.filename, 0, hdr.filenamesize + 1 );\n                char *fnptr = hdr.filename;\n\n                for ( char cc : file )\n                {\n                    *fnptr = cc;\n                    ++fnptr;\n                }\n\n                *fnptr = 0;\n\n                size_t hdrsz = sizeof ( uint64_t ) * 2 + hdr.filenamesize + 2;\n\n                unsigned char *filebuffer = new unsigned char[cnt];\n                unsigned char *sbuff = new unsigned char[cnt];\n\n                memset ( sbuff, 0, cnt );\n\n                size_t sz = writeHeader ( sbuff, hdr );\n\n                size_t buffer_count = cnt;\n\n                if ( ( int64_t ) hdr.filesize - ( int64_t ) hdrsz < ( int64_t ) cnt )\n                {\n                    buffer_count = hdr.filesize;\n\n                    fs.read ( ( char * ) filebuffer, buffer_count );\n                }\n                else\n                {\n                    buffer_count = buffer_count - sz;\n\n                    fs.read ( ( char * ) filebuffer, buffer_count );\n                }\n\n                if ( sz <= 0 )\n                {\n#if DBG\n                    std::cerr << \"Unable to write header\" << std::endl;\n#endif\n                    return;\n                }\n\n                uint8_t *ptr = sbuff;\n                ptr += hdrsz;\n\n                for ( size_t i = 0; i < buffer_count; ++i )   //fill from file contents\n                {\n                    *ptr = filebuffer[i];\n                    ++ptr;\n                }\n\n                size_t bblk = buffer_count + sz;\n\n                size_t mult = bblk / cd.blocklength;\n                size_t remainder = bblk % cd.blocklength;\n\n                size_t r = mult;\n                remainder ? ++r : r;\n\n                size_t outcnt = r * cd.blocklength;\n\n                if ( outcnt > cnt )\n                {\n#if DBG\n                    std::cerr << \"Buffer not large enough\" << std::endl;\n#endif\n                    return;\n                }\n\n                unsigned char *cryptbuffer = new unsigned char[cnt];\n                memset ( cryptbuffer, 0, cnt );\n\n                err = gcry_cipher_encrypt ( hd, cryptbuffer, outcnt, sbuff, outcnt );\n\n                if ( err )\n                {\n#if DBG\n                    auto ec = gcry_err_code ( err );\n                    std::cerr << \"Gcrypt Error: \" << ec << std::endl;\n#endif\n                    delete[] filebuffer;\n                    delete[] cryptbuffer;\n                    delete[] sbuff;\n                    return;\n                }\n\n                fsout.write ( ( char * ) cryptbuffer, outcnt );\n\n                int64_t fileoutcount = hdr.filesize - buffer_count - hdrsz;\n\n                while ( fileoutcount > 0 )\n                {\n                    buffer_count = cnt;\n\n                    if ( fileoutcount < cnt )\n                    {\n                        buffer_count = fileoutcount;\n                    }\n\n                    fs.read ( ( char * ) filebuffer, buffer_count );\n\n\n                    memset ( cryptbuffer, 0, cnt );\n\n                    bblk = buffer_count;\n\n                    mult = bblk / cd.blocklength;\n                    remainder = bblk % cd.blocklength;\n\n                    r = mult;\n                    remainder ? ++r : r;\n\n                    outcnt = r * cd.blocklength;\n\n                    if ( r == 0 )\n                    {\n                        break;\n                    }\n\n                    if ( remainder != 0 )\n                    {\n#if DBG\n                        std::cout << \"remainder not 0, filesize remaining: \" << fileoutcount;\n#endif\n                    }\n\n                    if ( outcnt > cnt )\n                    {\n#if DBG\n                        std::cerr << \"Buffer not large enough\" << std::endl;\n#endif\n                        delete[] filebuffer;\n\n                        if ( cryptbuffer )\n                        {\n                            delete[] cryptbuffer;\n                            cryptbuffer = nullptr;\n                        }\n\n                        delete[] sbuff;\n                        return;\n                    }\n\n                    memset ( cryptbuffer, 0, cnt );\n\n                    err = gcry_cipher_encrypt ( hd, cryptbuffer, outcnt, filebuffer, outcnt );\n\n                    if ( err )\n                    {\n#if DBG\n                        auto ec = gcry_err_code ( err );\n                        std::cerr << \"Gcrypt Error: \" << ec << std::endl;\n#endif\n                        delete[] filebuffer;\n\n                        if ( cryptbuffer )\n                        {\n                            delete[] cryptbuffer;\n                            cryptbuffer = nullptr;\n                        }\n\n                        delete[] sbuff;\n                        return;\n                    }\n\n                    fsout.write ( ( char * ) cryptbuffer, outcnt );\n\n                    fileoutcount -= buffer_count;\n                }\n\n                fsout.close();\n                fs.close();\n\n                delete[] filebuffer;\n\n                if ( cryptbuffer )\n                {\n                    delete[] cryptbuffer;\n                    cryptbuffer = nullptr;\n                }\n\n                delete[] sbuff;\n\n#if DBG\n                decryptImpl( ss.str() );\n#endif\n\n#endif // CRY_ENCRYPT\n            }\n\n// ==========================================================================\n\n            void decryptImpl ( std::string file, EncryptionType type =GPG_ALGO)\n            {\n#if CRY_DECRYPT\n                gcry_cipher_hd_t hd;\n\n                gcry_error_t err = gcry_cipher_open ( &hd, type, GCRY_CIPHER_MODE_CBC, 0 );\n\n                CryptDetail cd = getCryptDetails ( type );\n\n                err = gcry_cipher_setkey ( hd, cd.key.c_str(), cd.keylength );\n\n                err = gcry_cipher_setiv ( hd, cd.block.c_str(), cd.blocklength );\n\n                fs::path p ( file );\n\n                if ( !fs::exists ( p )\n                        && !fs::is_regular_file ( p ) )\n                {\n                    return;\n                }\n\n                std::fstream fs;\n                fs.open ( p.string(), std::fstream::in | std::fstream::binary );\n\n                size_t cnt = CRY_BUFFER_MULT * cd.blocklength;\n\n                unsigned char *cryptbuffer = new unsigned char[cnt];\n                unsigned char *buffer = new unsigned char[cnt];\n\n                memset ( buffer, 0, cnt );\n\n                size_t buffer_count = cnt;\n\n                size_t filesz = fs::file_size ( file );\n\n                if ( filesz <= cnt )\n                {\n                    buffer_count = filesz;\n                }\n\n                fs.read ( ( char * ) buffer, buffer_count );\n\n                memset ( cryptbuffer, 0, cnt );\n\n                err = gcry_cipher_decrypt ( hd, cryptbuffer, buffer_count, buffer, buffer_count );\n\n                if ( err > 0 )\n                {\n                    auto e = gcry_err_code ( err );\n#if DBG\n                    std::cerr << \"Could not decrypt - error code: \" << e << std::endl;\n#endif\n                }\n\n                CryHeader ch;\n                size_t sz = readHeader ( cryptbuffer, &ch );\n\n                buffer_count -= sz;\n\n                if ( sz <= 0 )\n                {\n#if DBG\n                    std::cerr << \"Could not read header\" << std::endl;\n#endif\n                    return;\n                }\n\n                if ( ch.filesize < buffer_count )\n                {\n                    buffer_count = ch.filesize;\n                }\n\n                char *cptr = ( char * ) cryptbuffer;\n                cptr += sz;\n\n                std::stringstream ssout;\n\n                //Filename of output file\n                ssout << ch.filename;\n\n                if ( fs::exists ( ssout.str() ) )\n                {\n                    std::cout << \"File: \\\"\" << ssout.str() << \" already exists!\" << std::endl;\n                    std::cout << \"Do you want me to overwrite? (Y/N)\" << std::endl;\n                    std::string input;\n                    std::cin >> input;\n\n                    if ( input == \"Y\" || input == \"y\" )\n                    {\n                        //do nothing\n                    }\n                    else\n                    {\n                        ssout << \".out\";\n                    }\n                }\n\n                std::fstream fsout;\n\n                if ( _output.empty() )\n                {\n                    fsout.open ( ssout.str(), std::fstream::out | std::fstream::binary );\n                }\n                else\n                {\n                    fsout.open ( _output, std::fstream::out | std::fstream::binary );\n                }\n\n                fsout.write ( cptr, buffer_count );\n\n                cptr += buffer_count;\n\n\n                int64_t filesizecount = ch.filesize - buffer_count;\n\n                while ( filesizecount > 0 )\n                {\n                    if ( filesizecount > cnt )\n                    {\n                        buffer_count = cnt;\n                    }\n                    else\n                    {\n                        buffer_count = filesizecount;\n\n                        size_t bblk = buffer_count;\n\n                        size_t mult = bblk / cd.blocklength;\n                        size_t remainder = bblk % cd.blocklength;\n\n                        size_t r = mult;\n                        remainder ? ++r : r;\n\n                        buffer_count = r * cd.blocklength;\n                    }\n\n                    fs.read ( ( char * ) buffer, buffer_count );\n\n                    memset ( cryptbuffer, 0, buffer_count );\n\n                    err = gcry_cipher_decrypt ( hd, cryptbuffer, buffer_count, buffer, buffer_count );\n\n                    if ( err > 0 )\n                    {\n#if DBG\n                        auto ec = gcry_err_code ( err );\n                        std::cerr << \"Error while decrypting: \" << ec << std::endl;\n#endif\n                    }\n\n                    if ( filesizecount >= buffer_count )\n                    {\n                        fsout.write ( ( char * ) cryptbuffer, buffer_count );\n                    }\n                    else\n                    {\n                        fsout.write ( ( char * ) cryptbuffer, filesizecount );\n                    }\n\n                    filesizecount -= buffer_count;\n                }\n\n                fsout.close();\n                fs.close();\n\n                delete[] buffer;\n                delete[] cryptbuffer;\n\n#endif // CRY_DECRYPT\n            }\n\n            //==========================================================\n\n            size_t identifyFile ( std::string file )\n            {\n                fs::path p ( file );\n\n                size_t filesize = 0;\n\n                if ( !fs::exists ( p ) )\n                {\n                    return 0;\n                }\n\n                filesize = fs::file_size ( p );\n                return filesize;\n            }\n\n            //=============================================================\n\n            CryptDetail getCryptDetails ( EncryptionType type )\n            {\n                CryptDetail c;\n\n                c.keylength = gcry_cipher_get_algo_keylen ( type );\n\n                c.key = cryptToLength ( _password, c.keylength );\n\n                c.blocklength = gcry_cipher_get_algo_blklen ( type );\n\n                c.block = cryptToLength ( CRY_DEFAULT_IV, c.blocklength );\n\n                return c;\n            }\n\n            //===================================================\n\n            std::string cryptToLength ( std::string in, size_t len )\n            {\n                size_t l = in.size();\n\n                if ( l == len )\n                {\n                    return in;\n                }\n                else if ( l > len )\n                {\n                    return std::string ( in.begin(), in.begin() + len );\n                }\n                else\n                {\n                    std::stringstream ss;\n                    ss << in;\n\n                    size_t i = 0;\n\n                    while ( ss.str().size() < len )\n                    {\n                        ss << defualt_crypt_string[i];\n\n                        ++i;\n\n                        if ( i >= strlen ( defualt_crypt_string ) )\n                        {\n                            i = 0;\n                        }\n\n                    }\n\n                    return ss.str();\n                }\n            }\n\n            // ==========================================================================\n\n            size_t writeHeader ( unsigned char *buffer, const CryHeader &hdr )\n            {\n                uint64_t *ptr64 = ( uint64_t * ) buffer;\n                ptr64[0] = hdr.filesize;\n                ptr64[1] = hdr.filenamesize;\n\n                uint8_t *ptr = buffer;\n                ptr += ( 2 * sizeof ( uint64_t ) );\n                *ptr = '\\n';\n                ++ptr;\n\n                for ( size_t i = 0; i < hdr.filenamesize; ++i )\n                {\n                    uint8_t cs = ( uint8_t ) hdr.filename[i];\n                    *ptr = cs;\n                    ++ptr;\n                }\n\n                *ptr = 0;\n\n                size_t sz = sizeof ( uint64_t ) * 2 + 2 + hdr.filenamesize;\n\n                return sz;\n            }\n\n            // ==========================================================================\n\n            size_t readHeader ( const unsigned char *buffer, CryHeader *headr )\n            {\n                CryHeader *hdr = headr;\n\n                uint64_t *ptr64 = ( uint64_t * ) buffer;\n                hdr->filesize = ptr64[0];\n                hdr->filenamesize = ptr64[1];\n\n                if ( hdr->filenamesize >= FILENAME_MAX )\n                {\n#if DBG\n                    std::cerr << \"Filename size too large\" << std::endl;\n#endif\n                    memset ( headr, 0, sizeof ( CryHeader ) );\n                    return 0;\n                }\n\n                hdr->filename = new char[hdr->filenamesize + 1];\n\n                uint8_t *ptr = ( uint8_t * ) buffer;\n                ptr += 2 * sizeof ( uint64_t );\n\n                if ( *ptr != '\\n' )\n                {\n                    delete[] hdr->filename;\n                    hdr->filename = nullptr;\n                    return 0;\n                }\n\n                ++ptr;\n\n                for ( size_t i = 0; i < hdr->filenamesize; ++i )\n                {\n                    hdr->filename[i] = * ( ptr + i );\n                }\n\n                hdr->filename[hdr->filenamesize] = 0;\n\n                if ( strlen ( hdr->filename ) != hdr->filenamesize )\n                {\n#if DBG\n                    std::cerr << \"Not a Cry encrypted file\" << std::endl;\n#endif\n                    delete[] hdr->filename;\n                    hdr->filename = nullptr;\n                    return 0;\n                }\n\n                uint64_t headersz = 2 * sizeof ( uint64_t );\n                headersz += strlen ( hdr->filename ) + 2;\n\n                return headersz;\n            }\n\n            // ===============================================================\n\n        public:\n            std::string     _password;\n            std::string     _output;\n\n        private:\n            Cry *_q;\n    };\n}\n\nusing namespace cry;\n\n//***************************************************************************************\n//\n//                                      CRY\n//\n//***************************************************************************************\n\nCry::Cry()\n{\n    _p = new CryPrivate ( this );\n}\n\n//===========================================================\n\nCry::~Cry()\n{\n    delete _p;\n    _p = nullptr;\n}\n\n//===========================================================\n\nvoid Cry::encrypt ( std::string file, EncryptionType type )\n{\n#if CRY_ENCRYPT\n    _p->encryptImpl ( file, type );\n#endif\n}\n\n//===========================================================\n\nvoid Cry::decrypt ( std::string file, EncryptionType type )\n{\n#if CRY_DECRYPT\n    _p->decryptImpl ( file, type );\n#endif\n}\n\n//===========================================================\n\nvoid Cry::setOutput ( std::string output )\n{\n    _p->_output = output;\n}\n\n//===========================================================\n\nvoid Cry::setPassword ( std::string password )\n{\n    _p->_password = password;\n}\n\n//===========================================================\n", "meta": {"hexsha": "a8547a3d091faf1c93ff89f71510aa71ca0bfc75", "size": 18478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cry.cpp", "max_stars_repo_name": "TrevorMellon/Cry", "max_stars_repo_head_hexsha": "c62c11d121c1de927f005b7adfa28b8c82742d1b", "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/cry.cpp", "max_issues_repo_name": "TrevorMellon/Cry", "max_issues_repo_head_hexsha": "c62c11d121c1de927f005b7adfa28b8c82742d1b", "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/cry.cpp", "max_forks_repo_name": "TrevorMellon/Cry", "max_forks_repo_head_hexsha": "c62c11d121c1de927f005b7adfa28b8c82742d1b", "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.6616766467, "max_line_length": 102, "alphanum_fraction": 0.3623768806, "num_tokens": 3498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.16559272845104772}}
{"text": "// Copyright 2015, Sensics, Inc.\n// Copyright 2021, Collabora, Ltd.\n// SPDX-License-Identifier: Apache-2.0\n//\n// latency-testing hardware firmware source code.\n// Code for \"motion onset\" test.\n// Original author: Russell Taylor working for Sensics.com through ReliaSolve.com\n// Ported to PlatformIO and multi-board, multi-app framework by Ryan Pavlik for Collabora.\n\n#ifdef APP_ONSET\n// Must come before Arduino because of abs\n#include <Eigen/Core>\n#include \"apps.h\"\n\nusing Eigen::Vector3f;\n\n#include <Arduino.h>\n#include \"defines.h\"\n#include \"gyroProc.h\"\n\n#include \"motionShared.h\"\n\nGyroProc gyroProc{};\n\n#define VERBOSE\n#undef abs\n// Thresholds\nconst int BRIGHTNESS_CHANGE_THRESHOLD = 3;\nconst unsigned long TIMEOUT_USEC = 1000000L;\n\n// Keeps track of delays so we can do an average.\nconst int NUM_DELAYS = 16;\nunsigned long delays[NUM_DELAYS];\nstatic int count = 0, odd_count = 0, even_count = 0;\n\nvoid onsetSetup()\n{\n\n    Serial.println(\"latency_hardware_firmware onset test v04.00.00\");\n    Serial.println(\" Mount the photosensor rigidly on the screen.\");\n    Serial.println(\" Move the inertial sensor along with the tracking hardware.\");\n    Serial.println(\" Make the app change the brightness in front of the photosensor.\");\n    Serial.println(\" Latencies reported in microseconds, 1-second timeout\");\n}\n\n//*****************************************************\nvoid onsetLoop(Board &board)\n//*****************************************************\n{\n    // We run a finite-state machine that cycles through cases of waiting for\n    // a period of non motion, detecting a sudden motion, waiting until there\n    // is a change in brightness, and reporting the time passed in microseconds\n    // between the motion and the brightness change.\n    static enum { S_CALM,\n                  S_MOTION,\n                  S_BRIGHTNESS } state = S_CALM;\n    static unsigned long start;\n    static int initial_brightness;\n    if (state == S_CALM)\n    {\n        startupImu(board, gyroProc);\n    }\n\n    switch (state)\n    {\n    case S_CALM:\n    {\n        // Wait for a period of at least 100 cycles where there is no motion above\n        // the motion threshold.\n        static int calm_cycles = 0;\n        auto data = doRead(board, gyroProc);\n        if (moving(data.gyro))\n        {\n            calm_cycles = 0;\n        }\n        else if (++calm_cycles >= 50)\n        {\n            Serial.println(\"waiting for calm...\");\n            state = S_MOTION;\n            calm_cycles = 0;\n        }\n        else\n        {\n            Serial.println(\"Make sure we stay calm for a while\");\n            // Make sure we stay calm for a while (half a second)\n            delay(10);\n        }\n    }\n    break;\n\n    case S_MOTION:\n    {\n        // Wait for a sudden motion.  When we find it, record the time in microseconds\n        // so we can compare it to when the brightness changes.  Also record the brightness\n        // so we can look for changes.\n        auto data = doRead(board, gyroProc);\n        if (moving(data.gyro))\n        {\n            start = data.timestamp;\n            initial_brightness = readBrightness();\n            state = S_BRIGHTNESS;\n#ifdef VERBOSE\n            Serial.println(\"Moving\");\n#endif\n        }\n    }\n    break;\n\n    case S_BRIGHTNESS:\n    {\n        // Wait for a change in brightness compared to the original value that\n        // passes a threshold.  When we get it, report the latency.\n        // If it takes too long, then we time out and start over.\n        int brightness = readBrightness();\n        unsigned long now = micros();\n\n        // Keep track of how many values we got for odd and even rows and\n        // compute a running average when we get a full complement for each.\n        // Ignore timeout values\n        if (abs(brightness - initial_brightness) > BRIGHTNESS_CHANGE_THRESHOLD)\n        {\n            // Print the result for this time\n            Serial.println(now - start);\n            if (count % 2 == 0)\n            {\n                odd_count++; // This is the first one (zero indexed) or off by twos\n            }\n            else\n            {\n                even_count++;\n            }\n            delays[count++] = now - start;\n            state = S_CALM;\n        }\n        else if (now - start > TIMEOUT_USEC)\n        {\n            Serial.println(\"Timeout: no brightness change after motion, restarting\");\n            // We don't increment the counter and we set the reading to 0 so we ignore it.\n            delays[count++] = 0;\n            state = S_CALM;\n        }\n\n        // See if it is time to print the average result.\n        if (count == NUM_DELAYS)\n        {\n            unsigned long even_average = 0;\n            unsigned long odd_average = 0;\n            for (int i = 0; i < NUM_DELAYS / 2; i++)\n            {\n                odd_average += delays[2 * i];\n                even_average += delays[2 * i + 1];\n            }\n\n            odd_average /= odd_count;\n            Serial.print(\"Average of last \");\n            Serial.print(NUM_DELAYS / 2);\n            Serial.print(\" odd counts (ignoring timeouts) = \");\n            Serial.println(odd_average);\n            even_average /= even_count;\n            Serial.print(\"Average of last \");\n            Serial.print(NUM_DELAYS / 2);\n            Serial.print(\" even counts (ignoring timeouts) = \");\n            Serial.println(even_average);\n\n            count = 0;\n            odd_count = 0;\n            even_count = 0;\n        }\n    }\n    break;\n\n    default:\n        Serial.println(\"Error: Unrecognized state; restarting\");\n        state = S_CALM;\n        break;\n    }\n}\n#endif", "meta": {"hexsha": "938d0f878799a3f4afe40d93c27e2f2e7aa03a48", "size": 5586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Latency_Hardware/src/motionOnset.cpp", "max_stars_repo_name": "rpavlik/Latency-Test", "max_stars_repo_head_hexsha": "9c2c324c60b5f176bfa8481bf7b958a5f8f01830", "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": "Latency_Hardware/src/motionOnset.cpp", "max_issues_repo_name": "rpavlik/Latency-Test", "max_issues_repo_head_hexsha": "9c2c324c60b5f176bfa8481bf7b958a5f8f01830", "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": "Latency_Hardware/src/motionOnset.cpp", "max_forks_repo_name": "rpavlik/Latency-Test", "max_forks_repo_head_hexsha": "9c2c324c60b5f176bfa8481bf7b958a5f8f01830", "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": 31.3820224719, "max_line_length": 91, "alphanum_fraction": 0.5757250269, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.16559272746635356}}
{"text": "#ifndef JHMI_LIVER_PHYSICAL_VESSEL_TREE_HPP_NRC_20150831\n#define JHMI_LIVER_PHYSICAL_VESSEL_TREE_HPP_NRC_20150831\n\n#include \"liver/build_vessel_map.hpp\"\n#include \"liver/get_split_point.hpp\"\n#include \"liver/load_vessel_protobuf.hpp\"\n#include \"liver/distance_vessel.hpp\"\n#include \"liver/physical_vessel.hpp\"\n#include \"liver/physical_vessel_tree_updater.hpp\"\n#include \"utility/binary_tree.hpp\"\n#include \"utility/line.hpp\"\n#include \"utility/octtree.hpp\"\n#include <boost/filesystem.hpp>\n#include <range/v3/algorithm/equal.hpp>\n#include <range/v3/view.hpp>\n#include <set>\n\nnamespace jhmi {\n  class physical_vessel_tree {\n    binary_tree<physical_vessel> vessels_;\n    vidx_to<binary_node_t<physical_vessel>> to_vessels_;\n    id_generator<vessel_tag> get_vessel_id_;\n    octtree<distance_vessel> grid_;\n    physical_vessel_tree_updater vessel_updater_;\n    double gamma_;\n\n    struct forward_distance_squared {\n      auto operator()(distance_vessel const& sv, m3 const& pt) -> boost::optional<decltype(pt.x*pt.x)> {\n        auto t = dot(pt - sv.l.p1, sv.loff) / sv.ld;\n        if (t < 0)\n          return boost::none;\n        auto lpt = t > 1 ? sv.l.p2 : (sv.l.p1 + t * sv.loff);\n        return boost::make_optional(distance_squared(lpt, pt));\n      }\n    };\n\n    auto get_nearest_vessel(m3 const& loc, std::mt19937& gen) {\n      //Randomly select one item of many\n      auto items = grid_.find_n_nearest_items(loc, 10, forward_distance_squared());\n      assert(!items.empty());\n#if 1\n      auto dist = make_balanced_sampler(items | ranges::view::transform([&](distance_vessel const& sv) {\n        return int(std::lround(sv.l.p2.z / lobule::cell_thickness));\n      }) | ranges::to_vector);\n#else\n#if 1\n      auto w = items | ranges::view::transform([&](distance_vessel const& sv) {\n        return abs(sv.l.p2.z - loc.z) < lobule::cell_thickness / 2. ? 0. : 1.;\n      }) | ranges::to_vector;\n      auto dist = std::discrete_distribution<>(w.begin(), w.end());\n#else\n      std::uniform_int_distribution<> dist(0, items.size() - 1);\n#endif\n#endif\n      return to_vessels_.at(items[dist(gen)].id);\n    }\n\n    void record_vessel(binary_node_t<physical_vessel> node) {\n      grid_.add_item(node.value());\n      to_vessels_.insert(std::make_pair(node.value().id(), node));\n    }\n\n    vessel_id split_existing_vessel(binary_node_t<physical_vessel> node, macrocell& cell) {\n      auto& v = node.value();\n\n      grid_.remove_item(v);\n      auto new_start = get_split_point(v, cell.center, cell.flow, gamma_);\n      auto old_start = v.start();\n      v.set_start(new_start);\n      grid_.add_item(v);\n\n      auto new_parent = node.make_left_child_of(physical_vessel{old_start, new_start,\n         1_mm, cell_id::invalid(), v.flow(), v.entry_pressure(),\n         get_vessel_id_(), v.is_const()});\n      record_vessel(new_parent);\n      auto cell_vessel = new_parent.set_right_child(physical_vessel{new_start,\n        cell.center, 1_mm, cell.id, cell.flow, cell.pressure, get_vessel_id_()});\n      cell.parent_vessel = cell_vessel.value().id();\n      record_vessel(cell_vessel);\n      return cell.parent_vessel;\n    }\n\n  public:\n    physical_vessel_tree(build_tree_tag, boost::filesystem::path const& filename, cube<m3> const& extents, double gamma, Pa cell_pressure, cubic_meters_per_second cell_flow, std::mt19937& gen)\n      : vessels_{}, to_vessels_{}, get_vessel_id_{},\n        grid_{extents, 16}, vessel_updater_{vessels_, gamma, cell_pressure, cell_flow, gen}, gamma_{gamma} {\n      auto vessel_generator = build_vessel_map(filename);\n      get_vessel_id_ = vessel_generator.second;\n      auto vessel_map = vessel_generator.first;\n      //Organize the map into a binary tree.\n      auto parent_id = jhmi_detail::find_parent_vessel(vessel_map);\n      vessels_ = binary_tree<physical_vessel>{vessel_map.at(parent_id).v};\n      add_children_vessels(vessels_.root(), [&](auto n) {\n          record_vessel(n);\n        }, vessel_map);\n      vessel_updater_.normalize_all();\n    }\n\n    physical_vessel_tree(load_tree_tag, boost::filesystem::path const& filename, std::mt19937& gen)\n      : vessels_{}, to_vessels_{}, get_vessel_id_{}, grid_{cube<m3>{}},\n        vessel_updater_{vessels_, 2.7, Pa{}, cubic_meters_per_second{}, gen}, gamma_{} {\n      auto vt = load_protobuf<jhmi_message::VesselTree>(filename);\n      gamma_ = vt.gamma();\n      if (std::abs(gamma_) < 1e-2)\n        gamma_ = 2.7;\n      auto vns = load_vessel_protobuf(vt);\n      vessel_id max_id{0};\n      boost::optional<cube<m3>> ext;\n      RANGES_FOR(auto&& v, vns) {\n        max_id = std::max(max_id, v.second.v.id());\n        ext = ext ? expand(*ext, v.second.v.start())\n                  : cube<m3>{v.second.v.start(), v.second.v.start()};\n        ext = expand(*ext, v.second.v.end());\n      }\n      grid_ = octtree<distance_vessel>{*ext};\n\n      auto parent_id = jhmi_detail::find_parent_vessel(vns);\n      vessels_ = binary_tree<physical_vessel>{vns.at(parent_id).v};\n      add_children_vessels(vessels_.root(), [&](auto n) { record_vessel(n); }, vns);\n      get_vessel_id_ = id_generator<vessel_tag>{max_id};\n      //No need to use vessel_updater_ here, it should have been saved with\n      // desried radii, pressures, etc.\n\n      RANGES_FOR(auto&& n, vessels_ | view::node_post_order) {\n        int so = 1;\n        if (n.left_child()) {\n          so = n.left_child().value().strahler_order;\n        }\n        if (n.right_child()) {\n          int rso = n.right_child().value().strahler_order;\n          if (rso == so)\n            so++;\n          else if (rso > so)\n            so = rso;\n        }\n        n.value().strahler_order = so;\n      }\n      fmt::print(\"Highest order: {}\\n\", vessels_.root().value().strahler_order);\n    }\n\n    auto terminal_vessels() const {\n      return vessels_ | view::node_in_order\n        | ranges::view::filter([](binary_const_node_t<physical_vessel> n) {\n           return !n.left_child() && !n.right_child(); })\n        | ranges::view::transform([](binary_const_node_t<physical_vessel> n) {\n           return n.value(); });\n    }\n\n    auto terminal_vessel_nodes() const {\n      return vessels_ | view::node_in_order\n        | ranges::view::filter([](binary_const_node_t<physical_vessel> n) {\n           return !n.left_child() && !n.right_child(); });\n    }\n\n    vessel_id connect_cell_initial(macrocell& cell, vessel_id id) {\n      auto min_vessel = to_vessels_.at(id);\n      auto& mv = min_vessel.value();\n      auto v = physical_vessel{mv.end(), cell.center, 1_mm, cell.id, cell.flow, cell.pressure, get_vessel_id_()};\n      //Don't adjust any positions, this should only happen on the initial\n      // population of microspheres, so min_vessel should be const.\n      auto n = min_vessel.set_left_child(v);\n      cell.parent_vessel = jhmi::id(v);\n      record_vessel(n);\n      for (n = n.parent(); n; n = n.parent())\n        n.value().flow_ -= cell.flow;\n      return cell.parent_vessel;\n    }\n    vessel_id connect_cell(macrocell& cell, std::mt19937& gen) {\n      auto min_vessel = get_nearest_vessel(cell.center, gen);\n      assert(min_vessel);\n      split_existing_vessel(min_vessel, cell);\n\n      auto n = to_vessels_.at(cell.parent_vessel);\n      for (n = n.parent(); n; n = n.parent())\n        n.value().flow_ -= cell.flow;\n\n      return cell.parent_vessel;\n    }\n    auto gamma() const { return gamma_; }\n    auto size() const { return to_vessels_.size(); }\n    auto vessels() const { return vessels_ | view::pre_order; }\n    auto vessel_nodes() const { return vessels_ | view::node_pre_order; }\n    auto post_order_vessel_nodes() const { return vessels_ | view::node_post_order; }\n\n    physical_vessel const& at(vessel_id id) const {\n      return to_vessels_.at(id).value();\n    }\n    binary_node_t<physical_vessel> at_node(vessel_id id) {\n      return to_vessels_.at(id);\n    }\n    auto at_node(vessel_id id) const {\n      return binary_const_node_t<physical_vessel>{to_vessels_.at(id)};\n    }\n\n    void normalize_all() {\n      vessel_updater_.normalize_all();\n    }\n\n    bool remove(vessel_id id) {\n      auto node = to_vessels_.at(id);\n      assert(node.value().cell().valid());\n      auto flow = node.value().flow();\n      bool remove_left = true;\n      std::vector<binary_node_t<physical_vessel>> remove_vessels;\n      while (node) {\n        if (node.left_child() && node.right_child()) {\n          assert(!node.value().cell().valid());\n          break;\n        }\n        if (node.value().is_const())\n          return false;\n        remove_vessels.push_back(node);\n        remove_left = node.is_left_child();\n        node = node.parent();\n      }\n      //node now holds what should continue to exist, and id et al. may be\n      // removed.\n      RANGES_FOR(auto const& vessel, remove_vessels) {\n        grid_.remove_item(vessel.value());\n        to_vessels_.erase(vessel.value().id());\n      }\n\n      if (remove_left)\n        node.set_left_child(nullptr);\n      else\n        node.set_right_child(nullptr);\n\n      if (!node.value().is_const()) {\n        auto remove_node = node;\n        node = node.left_child() ? node.left_child() : node.right_child();\n        grid_.remove_item(remove_node.value());\n        grid_.remove_item(node.value());\n        to_vessels_.erase(remove_node.value().id());\n        node.value().set_start(remove_node.value().start());\n        node.replace_parent();\n        grid_.add_item(node.value());\n      }\n      for (; node; node = node.parent())\n        node.value().flow_ -= flow;\n      return true;\n    }\n\n    void store(jhmi_message::VesselTree& vt) const {\n      vt.set_gamma(gamma_);\n      RANGES_FOR(auto&& v, vessels_ | view::node_level_order) {\n        auto p = v.parent();\n        auto r = v.right_child();\n        auto l = v.left_child();\n        auto vtv = vt.add_vessels();\n        vtv->set_id(v.value().id().value());\n        vtv->set_parent((p ? p.value().id() : vessel_id::invalid()).value());\n        vtv->set_left(  (l ? l.value().id() : vessel_id::invalid()).value());\n        vtv->set_right( (r ? r.value().id() : vessel_id::invalid()).value());\n        vtv->set_radius(v.value().radius().value());\n        vtv->set_cell(v.value().cell().value());\n        vtv->set_flow(v.value().flow().value());\n        vtv->set_entry_pressure(v.value().entry_pressure().value());\n        vtv->set_exit_pressure(v.value().exit_pressure().value());\n        vtv->set_sx(v.value().start().x.value());\n        vtv->set_sy(v.value().start().y.value());\n        vtv->set_sz(v.value().start().z.value());\n        vtv->set_ex(v.value().end().x.value());\n        vtv->set_ey(v.value().end().y.value());\n        vtv->set_ez(v.value().end().z.value());\n        vtv->set_is_const(v.value().is_const());\n      }\n    }\n\n    bool validate(bool ignore_unconnected_vessels) const {\n      bool no_errors = true;\n      auto check_errors = [&](binary_const_node_t<physical_vessel> cn, physical_vessel const& v) {\n        if (cn) {\n          auto const& c = cn.value();\n          if (distance(c.start() - v.end()) >= 1e-8_mm) {\n            fmt::print(\"Invalid spatial distance: {} to {}\\n\", v.id(), c.id());\n            no_errors = false;\n          }\n        }\n      };\n      RANGES_FOR(auto n, vessels_ | view::node_in_order) {\n        check_errors(n.left_child(), n.value());\n        check_errors(n.right_child(), n.value());\n      }\n      std::set<vessel_id> all_vessels;\n      RANGES_FOR(auto const& v, vessels_ | view::in_order) {\n        all_vessels.insert(v.id());\n      }\n      auto grid_vessels = grid_.get_all();\n      std::set<vessel_id> map_vessels;\n      RANGES_FOR(auto& v, to_vessels_ | ranges::view::keys) {\n        map_vessels.insert(v);\n      }\n      if (!ranges::equal(all_vessels, grid_vessels)) {\n        fmt::print(\"Some vessels not found in the grid:\\n\");\n        std::set_difference(all_vessels.begin(), all_vessels.end(), grid_vessels.begin(), grid_vessels.end(), std::ostream_iterator<vessel_id>{std::cout, \" \"});\n        no_errors = false;\n      }\n      if (!ranges::includes(map_vessels, all_vessels, std::less<>{})) {\n        fmt::print(\"Some vessels not found in the map\\n\");\n        no_errors = false;\n      }\n      no_errors &= check_close(vessels_.root().value().entry_pressure(), input_pressure,\n        1e-3, vessels_.root().value().id(), \"root pressure\", \"model pressure\");\n\n      //Now we need to verify that radii and pressures match our expectations.\n      RANGES_FOR(auto n, vessels_ | view::node_level_order) {\n        auto& v = n.value();\n        if (v.cell().valid() && (n.left_child() || n.right_child())) {\n          fmt::print(\"Vessel {} connects macrocell {} and has child vessels\\n\",\n            v.id(), v.cell());\n          no_errors = false;\n        }\n        if (n.left_child()) {\n          no_errors &= check_close(v.exit_pressure(),\n            n.left_child().value().entry_pressure(), 1e-3,\n            v.id(), \"node exit pressure\", \"left_child entry pressure\");\n        }\n        if (n.right_child()) {\n          no_errors &= check_close(v.exit_pressure(),\n            n.right_child().value().entry_pressure(), 1e-3,\n            v.id(), \"node exit pressure\", \"right_child entry pressure\");\n        }\n\n        if (n.right_child() && n.left_child()) {\n          no_errors &= check_close(v.radius(),\n            std::pow(std::pow(n.left_child().value().radius().value(), gamma_)\n                   + std::pow(n.right_child().value().radius().value(), gamma_), 1./gamma_) * meters,\n            1e-5, v.id(), \"node radius\", \"children-derived radius\");\n          no_errors &= check_close(v.flow(),\n            n.left_child().value().flow() + n.right_child().value().flow(),\n            1e-5, v.id(), \"children flows\", \"node flow\");\n        }\n        else if (n.right_child()) {\n          no_errors &= check_close(n.right_child().value().radius(), v.radius(),\n            1e-5, v.id(), \"right child radius\", \"node radius\");\n          no_errors &= check_close(v.flow(), n.right_child().value().flow(),\n            1e-4, v.id(), \"right child flow\", \"node flow\");\n        }\n        else if (n.left_child()) {\n          no_errors &= check_close(v.radius(), n.left_child().value().radius(),\n            1e-5, v.id(), \"node radius\", \"left child radius\");\n          no_errors &= check_close(v.flow(), n.left_child().value().flow(),\n            1e-4, v.id(), \"node flow\", \"left child flow\");\n        }\n\n        no_errors &= v.validate();\n      }\n\n      if (!ignore_unconnected_vessels) {\n        auto unconnected_vessels = vessels_ | view::node_in_order\n          | ranges::view::filter([](binary_const_node_t<physical_vessel> n) {\n             return !n.left_child() && !n.right_child() && !n.value().cell().valid(); })\n          | ranges::to_vector;\n        if (!unconnected_vessels.empty()) {\n          no_errors = false;\n          fmt::print(\"Unconnected vessels found: \");\n          RANGES_FOR(auto n, unconnected_vessels) {\n            fmt::print(\"{} \", n.value().id());\n          }\n          fmt::print(\"\\n\");\n        }\n      }\n      return no_errors;\n    }\n  };\n  bool operator==(physical_vessel_tree const& lhs, physical_vessel_tree const& rhs) {\n    return ranges::equal(lhs.vessels(), rhs.vessels(), std::equal_to<physical_vessel>{});\n  }\n}\n#endif\n", "meta": {"hexsha": "ddc6a6471c3692e9bbf0af22051a9e789d86edc5", "size": 15111, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "liver/physical_vessel_tree.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/physical_vessel_tree.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/physical_vessel_tree.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": 40.730458221, "max_line_length": 192, "alphanum_fraction": 0.6126000926, "num_tokens": 3940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.16549977784446326}}
{"text": "#include <cyber.stake/cyber.stake.hpp>\n#include <cyber.token/cyber.token.hpp>\n#include <cyber.govern/cyber.govern.hpp>\n#include <eosio/privileged.hpp>\n#include <common/util.hpp>\n#include <eosio/event.hpp>\n#include <boost/container/flat_map.hpp>\n#include <boost/container/flat_set.hpp>\n\nusing namespace cyber::config;\n\nnamespace cyber {\n\nvoid govern::onblock(name producer, eosio::binary_extension<uint32_t> schedule_version) {\n    require_auth(_self);\n    \n    auto state = state_singleton(_self, _self.value);\n    auto s = state.get_or_default(structures::state_info { .last_schedule_increase = eosio::current_time_point() });\n\n    s.block_num++;\n\n    int64_t block_reward = 0;\n    if (producer != config::internal_name) {\n        auto supply     = eosio::token::get_supply    (config::token_name, system_token.code()).amount;\n        auto max_supply = eosio::token::get_max_supply(config::token_name, system_token.code()).amount;\n        eosio::check(max_supply >= supply, \"SYSTEM: incorrect supply\");\n        \n        if ((s.block_num % config::update_emission_per_block_interval == 0) || !s.target_emission_per_block) {\n            s.target_emission_per_block = get_target_emission_per_block(supply);\n        }\n        auto cur_block_emission = std::min(max_supply - supply, s.target_emission_per_block);\n        block_reward = safe_pct(cur_block_emission, config::block_reward_pct);\n        s.funds += cur_block_emission - block_reward;\n    }\n\n    producers producers_table(_self, _self.value);\n\n    if (producer != config::internal_name && s.block_num != 1) {\n        auto utr = producers_table.find(producer.value);\n        if (utr != producers_table.end()) {\n            producers_table.modify(utr, eosio::same_payer, [&](auto& u) {\n                u.amount += block_reward + u.unconfirmed_amount;\n                u.unconfirmed_amount = 0;\n                u.omission_resets = 0;\n                u.omission_count = 0;\n                u.is_oblidged = false;\n                u.last_time = eosio::current_time_point();\n            });\n        } else if (block_reward > 0) {\n            producers_table.emplace(_self, [&](auto& u) {\n                u.account = producer;\n                u.amount = block_reward;\n                u.is_oblidged = false;\n                u.last_time = eosio::current_time_point();\n            });\n        }\n    }\n    \n    if (s.block_num % config::reward_interval == 0) {\n        reward_producers(producers_table, s);\n        reward_workers(s);\n    }\n    \n    if ((s.block_num >= s.last_producers_num * schedule_period_factor + s.last_propose_block_num) || !s.last_propose_block_num) {\n        propose_producers(s);\n    }\n\n    // the schedule version temporarily has the binary extension type only for the upgrade phase\n    if (schedule_version.has_value()) {\n        if (s.schedule_version.has_value() && s.schedule_version.value() != schedule_version.value()) {\n            promote_producers(producers_table);\n            remove_old_producers(producers_table);\n        }\n        s.schedule_version.emplace(schedule_version.value());\n    } else {\n        s.schedule_version.emplace(0);\n    }\n\n    state.set(std::move(s), _self);\n}\n\nvoid govern::reward_workers(structures::state_info& s) {\n    if (s.funds) {\n        INLINE_ACTION_SENDER(eosio::token, issue)(config::token_name, {config::issuer_name, config::active_name}, \n            {config::worker_name, asset(s.funds, system_token), \"\"});\n        s.funds = 0;\n    }\n}\n\nvoid govern::burn_reward(const eosio::name& account, const int64_t& amount) const {\n    if (amount > 0) {\n        auto data = structures::balance_struct{account, amount};\n        eosio::event(_self, \"burnreward\"_n, data).send();\n    }\n}\n\nvoid govern::reward_producers(producers& producers_table, structures::state_info& s) {\n    static constexpr auto token_code = system_token.code();\n    std::vector<std::pair<eosio::name, int64_t>> unconfirmed_rewards;\n    std::vector<std::pair<eosio::name, int64_t>> rewards;\n\n    unconfirmed_rewards.reserve(config::max_producers_num + 16);\n    rewards.reserve(config::max_producers_num + 16);\n\n    auto top = stake::get_top(system_token.code(), s.required_producers_num + rewarded_for_votes_limit_displ, 0);\n    int64_t votes_sum = 0;\n    for (const auto& t : top) {\n        votes_sum += t.votes;\n    }\n\n    auto reward_of_elected = safe_pct(s.funds, config::_100percent - config::workers_reward_pct);\n    if (votes_sum && reward_of_elected) {\n        s.funds -= reward_of_elected;\n\n        auto change = reward_of_elected;\n        for (const auto& t : top) {\n            auto cur_reward = safe_prop(reward_of_elected, t.votes, votes_sum);\n            if (cur_reward) {\n                unconfirmed_rewards.emplace_back(t.account, cur_reward);\n                change -= cur_reward;\n            } else {\n                break;\n            }\n        }\n\n        if (change) {\n            if (!unconfirmed_rewards.empty()) {\n                auto idx = s.block_num % unconfirmed_rewards.size();\n                unconfirmed_rewards[idx].second += change;\n            } else {\n                auto idx = s.block_num % top.size();\n                unconfirmed_rewards.emplace_back(top[idx].account, change);\n            }\n        }\n\n        for (auto& r: unconfirmed_rewards) {\n            auto btr = producers_table.find(r.first.value);\n            int64_t amount = 0;\n\n            if (btr != producers_table.end()) {\n                producers_table.modify(btr, name(), [&](auto& b) {\n                    amount += b.amount;\n                    b.amount = 0;\n                    b.unconfirmed_amount += r.second;\n                });\n            } else {\n                producers_table.emplace(_self, [&](auto& b) {\n                    b.is_oblidged = false;\n                    b.account = r.first;\n                    b.unconfirmed_amount = r.second;\n                });\n            }\n\n            if (amount > 0) {\n                rewards.emplace_back(r.first, amount);\n            }\n        }\n    }\n\n    auto balances_idx = producers_table.get_index<\"bybalance\"_n>();\n    for (auto itr = balances_idx.begin(); itr != balances_idx.end() && itr->amount; ++itr) {\n        rewards.emplace_back(itr->account, itr->amount);\n        balances_idx.modify(itr, eosio::same_payer, [&](auto& u){\n            u.amount = 0;\n        });\n    }\n\n    if (rewards.size()) {\n        INLINE_ACTION_SENDER(cyber::stake, reward)(config::stake_name, {config::issuer_name, config::active_name},\n            {rewards, system_token});\n    }\n}\n\nvoid govern::propose_producers(structures::state_info& s) {\n    s.last_propose_block_num = s.block_num;\n\n    if (!s.last_resize_step.has_value()) {\n        s.last_resize_step.emplace(eosio::current_time_point());\n    }\n    if (!s.resize_shift.has_value()) {\n        s.resize_shift.emplace(1);\n    }\n\n    if ((eosio::current_time_point() - s.last_resize_step.value()).to_seconds() >= schedule_resize_min_delay) {\n        s.required_producers_num = s.last_producers_num + 1;\n        s.required_producers_num = std::min(std::max(s.required_producers_num, min_producers_num), max_producers_num);\n        s.last_resize_step.emplace(eosio::current_time_point());\n    }\n\n    auto new_producers = stake::get_top(system_token.code(), s.required_producers_num - active_reserve_producers_num, active_reserve_producers_num);\n    auto new_producers_num = new_producers.size();\n    \n    auto min_new_producers_num = std::min(s.last_producers_num, min_producers_num);\n    if (new_producers_num < min_new_producers_num) {\n        return;\n    }\n    \n    std::vector<eosio::producer_key> schedule;\n    schedule.reserve(new_producers_num + 16);\n    for (const auto& t : new_producers) {\n        schedule.emplace_back(eosio::producer_key{t.account, t.signing_key});\n    }\n    if (!eosio::set_proposed_producers(schedule)) {\n        return;\n    }\n    s.last_producers_num = new_producers_num;\n    std::vector<name> accounts;\n    accounts.reserve(new_producers_num + 16);\n    for (const auto& t : new_producers) {\n        accounts.emplace_back(t.account);\n    }\n    \n    INLINE_ACTION_SENDER(cyber::stake, pick)(config::stake_name, {config::issuer_name, config::active_name},\n        {system_token.code(), accounts});\n}\n\nint64_t govern::get_target_emission_per_block(int64_t supply) const {\n    auto votes_sum = cyber::stake::get_votes_sum(system_token.code());\n    eosio::check(votes_sum <= supply, \"SYSTEM: incorrect votes_sum val\");\n    auto not_involved_pct = static_cast<decltype(config::_100percent)>(safe_prop(config::_100percent, supply - votes_sum, supply));\n    auto arg = std::min(std::max(not_involved_pct, config::emission_min_arg), config::emission_max_arg);\n    arg -= config::emission_min_arg;\n    arg = safe_prop(config::_100percent, arg, config::emission_max_arg - config::emission_min_arg);\n    auto emission_per_year_pct = (((arg * config::emission_factor) / config::_100percent) + config::emission_addition);  \n    int64_t emission_per_year = safe_pct(emission_per_year_pct, supply);\n    return emission_per_year / config::blocks_per_year;\n}\n\nvoid govern::promote_producers(producers& producers_table) {\n    static constexpr auto token_code = system_token.code();\n    auto obliged_idx = producers_table.get_index<\"byoblidged\"_n>();\n    boost::container::flat_set<eosio::name> active_producers;\n\n    active_producers.reserve(config::max_producers_num + 16);\n    for (const auto& acc: eosio::get_active_producers()) {\n        active_producers.insert(acc);\n    }\n    for (auto itr = obliged_idx.begin(); itr != obliged_idx.end() && itr->is_oblidged; ) {\n        bool should_erase = false;\n        if (!cyber::stake::candidate_exists(itr->account, token_code)) {\n            should_erase = true;\n        } else if (itr->omission_resets >= config::resets_limit) {\n            INLINE_ACTION_SENDER(cyber::stake, setproxylvl)(config::stake_name, {config::issuer_name, config::active_name},\n                {itr->account, token_code, stake::get_max_level(token_code)}); // agent cannot disappear\n            should_erase = true;\n        }\n\n        auto atr = active_producers.find(itr->account);\n        if (should_erase) {\n            if (active_producers.end() != atr) {\n                active_producers.erase(atr);\n            }\n            burn_reward(itr->account, itr->amount + itr->unconfirmed_amount);\n            itr = obliged_idx.erase(itr);\n            continue;\n        }\n\n        burn_reward(itr->account, itr->unconfirmed_amount);\n\n        obliged_idx.modify(itr, eosio::same_payer, [&](auto& o){\n            if (active_producers.end() != atr) {\n                active_producers.erase(atr);\n            } else {\n                o.is_oblidged = false;\n            }\n\n            o.unconfirmed_amount = 0;\n            o.omission_count += 1;\n\n            if (o.omission_count >= config::omission_limit) {\n                INLINE_ACTION_SENDER(cyber::stake, setkey)(config::stake_name, {config::issuer_name, config::active_name},\n                    {o.account, token_code, public_key{}});\n\n                o.omission_count = 0;\n                o.omission_resets += 1;\n            }\n        });\n        ++itr;\n    }\n\n    for (const auto& acc : active_producers) {\n        auto itr = producers_table.find(acc.value);\n        if (producers_table.end() == itr) {\n            producers_table.emplace(_self, [&](auto& p) {\n                p.account = acc;\n                p.is_oblidged = true;\n                p.last_time = eosio::current_time_point();\n            });\n        } else if (!itr->is_oblidged) {\n            producers_table.modify(itr, eosio::same_payer, [&](auto& p) {\n                p.is_oblidged = true;\n            });\n        }\n    }\n}\n\nvoid govern::remove_old_producers(producers& producers_table) {\n    static constexpr auto token_code = system_token.code();\n    auto last_time_idx = producers_table.get_index<\"bytime\"_n>();\n    auto itr = last_time_idx.begin();\n    if (last_time_idx.end() == itr) {\n        return;\n    }\n    if (!cyber::stake::candidate_exists(itr->account, token_code)) {\n        burn_reward(itr->account, itr->unconfirmed_amount + itr->amount);\n        last_time_idx.erase(itr);\n    } else {\n        last_time_idx.modify(itr, eosio::same_payer, [&](auto& p){\n           p.last_time = eosio::current_time_point();\n        });\n    }\n}\n\n}\n", "meta": {"hexsha": "88dd1212c18d56a65b7d0264c5593cfbf5574ec2", "size": 12280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cyber.govern/src/cyber.govern.cpp", "max_stars_repo_name": "cyberway/cyberway.contracts", "max_stars_repo_head_hexsha": "a6a7d6e25a225a1de2537f5a224decdea2066d77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-16T04:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-16T05:01:01.000Z", "max_issues_repo_path": "cyber.govern/src/cyber.govern.cpp", "max_issues_repo_name": "GolosChain/cyberway.contracts", "max_issues_repo_head_hexsha": "a6a7d6e25a225a1de2537f5a224decdea2066d77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 110.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T09:18:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-25T03:16:21.000Z", "max_forks_repo_path": "cyber.govern/src/cyber.govern.cpp", "max_forks_repo_name": "cyberway/cyberway.contracts", "max_forks_repo_head_hexsha": "a6a7d6e25a225a1de2537f5a224decdea2066d77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-28T14:49:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T15:33:18.000Z", "avg_line_length": 38.9841269841, "max_line_length": 148, "alphanum_fraction": 0.6214983713, "num_tokens": 2899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.256831980010821, "lm_q1q2_score": 0.16545760967157633}}
{"text": "/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\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 <miopen/config.h>\n#include <miopen/convolution.hpp>\n#include <miopen/env.hpp>\n#include <miopen/errors.hpp>\n#include <miopen/handle.hpp>\n#include <miopen/logger.hpp>\n#include <miopen/miopen.h>\n#include <miopen/mlo_internal.hpp>\n#include <miopen/solver.hpp>\n#include <miopen/tensor.hpp>\n#include <miopen/algorithm.hpp>\n#include <miopen/scgemm_utils.hpp>\n\n#include <cassert>\n#include <cstddef>\n#include <algorithm>\n#include <cmath>\n#include <ostream>\n\n#include <boost/range/combine.hpp>\n#include <boost/range/adaptors.hpp>\n\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_IMPLICIT_GEMM)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_SCGEMM)\n\n// Workaround for issue 1430.\n// Vega20 fails to access GPU memory larger than the return value of GetMaxMemoryAllocSize() of\n// Vega10\n#define MAX_MEM_ALLOC_SZ (std::min(handle.GetMaxMemoryAllocSize(), size_t(7287183769)))\n\nnamespace miopen {\n\nConvolutionDescriptor::ConvolutionDescriptor(std::size_t spatial_dim,\n                                             miopenConvolutionMode_t c_mode,\n                                             miopenPaddingMode_t p_mode,\n                                             const std::vector<int>& p_pads,\n                                             const std::vector<int>& p_strides,\n                                             const std::vector<int>& p_dilations,\n                                             const std::vector<int>& p_trans_output_pads,\n                                             int p_group_count,\n                                             float p_lowp_quant)\n    : spatialDim(spatial_dim),\n      mode(c_mode),\n      paddingMode(p_mode),\n      pads(p_pads),\n      strides(p_strides),\n      dilations(p_dilations),\n      trans_output_pads(p_trans_output_pads),\n      group_count(p_group_count),\n      lowp_quant(p_lowp_quant)\n{\n    if(pads.size() != spatial_dim || strides.size() != spatial_dim ||\n       dilations.size() != spatial_dim || trans_output_pads.size() != spatial_dim ||\n       miopen::any_of(pads, [](auto v) { return v < 0; }) ||\n       miopen::any_of(strides, [](auto v) { return v < 1; }) ||\n       miopen::any_of(dilations, [](auto v) { return v < 1; }))\n    {\n        MIOPEN_THROW(miopenStatusBadParm,\n                     \"Invalid parameters, check usage. MIOPEN expects padding \"\n                     \">= 0, stride >= 1, dilation >= 1 and the same dilation \"\n                     \"factor for horizontal and vertical direction\");\n    }\n    if(!(mode == miopenConvolution || mode == miopenTranspose))\n    {\n        if(mode == miopenGroupConv || mode == miopenDepthwise)\n        {\n            mode = miopenConvolution;\n        }\n        else\n        {\n            MIOPEN_THROW(miopenStatusBadParm, \"Convolution mode not supported\");\n        }\n    }\n    if(!(paddingMode == miopenPaddingSame || paddingMode == miopenPaddingValid ||\n         paddingMode == miopenPaddingDefault))\n    {\n        MIOPEN_THROW(miopenStatusBadParm, \"Padding mode not supported\");\n    }\n}\n\nConvolutionDescriptor::ConvolutionDescriptor(const std::vector<int>& p_pads,\n                                             const std::vector<int>& p_strides,\n                                             const std::vector<int>& p_dilations,\n                                             const std::vector<int>& p_trans_output_pads,\n                                             int p_group_count,\n                                             float p_lowp_quant)\n    : ConvolutionDescriptor{p_pads.size(),\n                            miopenConvolution,\n                            miopenPaddingDefault,\n                            p_pads,\n                            p_strides,\n                            p_dilations,\n                            p_trans_output_pads,\n                            p_group_count,\n                            p_lowp_quant}\n{\n}\n\nstd::size_t ConvolutionDescriptor::GetSpatialDimension() const { return spatialDim; }\n\nconst std::vector<int>& ConvolutionDescriptor::GetConvPads() const { return pads; }\n\nconst std::vector<int>& ConvolutionDescriptor::GetConvStrides() const { return strides; }\n\nconst std::vector<int>& ConvolutionDescriptor::GetConvDilations() const { return dilations; }\n\nconst std::vector<int>& ConvolutionDescriptor::GetTransposeConvPads() const\n{\n    return trans_output_pads;\n}\n\nint ConvolutionDescriptor::GetGroupCount() const { return group_count; }\n\nTensorDescriptor ConvolutionDescriptor::GetForwardOutputTensor(const TensorDescriptor& xDesc,\n                                                               const TensorDescriptor& wDesc,\n                                                               miopenDataType_t yType) const\n{\n    const std::size_t spatial_dim = GetSpatialDimension();\n\n    assert(xDesc.GetLengths().size() == spatial_dim + 2);\n    assert(wDesc.GetLengths().size() == spatial_dim + 2);\n\n    if(xDesc.GetType() != wDesc.GetType())\n    {\n        MIOPEN_THROW(miopenStatusBadParm, \"Types do not match for the filter\");\n    }\n\n    std::size_t in_n, in_c;\n    std::tie(in_n, in_c) = miopen::tie_pick<0, 1>{}(xDesc.GetLengths());\n\n    auto in_spatial = boost::adaptors::slice(xDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    std::size_t wei_k, wei_c;\n    std::tie(wei_k, wei_c) = miopen::tie_pick<0, 1>{}(wDesc.GetLengths());\n\n    auto wei_spatial = boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    if(mode == miopenConvolution)\n    {\n        // for depthwise conv wei_c must be 1 while group_count must be wei_c\n        if((group_count == 1 && in_c != wei_c) ||\n           (group_count > 1 && (in_c % wei_c != 0 || wei_k % (in_c / wei_c) != 0)))\n        {\n            MIOPEN_THROW(miopenStatusBadParm, \"Channels do not match for the filter\");\n        }\n    }\n    else if(mode == miopenTranspose)\n    {\n        if(in_c != wei_k || (group_count > 1 && (wei_k % group_count != 0)))\n        {\n            MIOPEN_THROW(miopenStatusBadParm, \"Channels do not match for the filter\");\n        }\n\n        if(miopen::any_of(boost::combine(GetTransposeConvPads(), GetConvStrides()), [](auto v) {\n               auto trans_conv_pad = boost::get<0>(v);\n               auto stride         = boost::get<1>(v);\n               return trans_conv_pad >= stride;\n           }))\n        {\n            MIOPEN_THROW(miopenStatusBadParm,\n                         \"Output shape doesn't match due to invalid output padding\");\n        }\n    }\n\n    std::size_t out_c;\n    std::vector<std::size_t> out_lens(spatial_dim + 2);\n\n    auto out_spatial = boost::adaptors::slice(out_lens, 2, 2 + spatial_dim);\n\n    if(paddingMode == miopenPaddingSame && mode == miopenConvolution &&\n       miopen::all_of(GetConvDilations(), [](auto v) { return v == 1; }))\n    {\n        out_c = wei_k;\n\n        for(int i = 0; i < spatial_dim; ++i)\n        {\n            out_spatial[i] = miopen::integer_division_ceil(in_spatial[i], GetConvStrides()[i]);\n        }\n    }\n    else if(paddingMode == miopenPaddingValid && mode == miopenConvolution &&\n            miopen::all_of(GetConvDilations(), [](auto v) { return v == 1; }))\n    {\n        out_c = wei_k;\n\n        for(int i = 0; i < spatial_dim; ++i)\n        {\n            out_spatial[i] = miopen::integer_division_ceil(\n                std::ptrdiff_t(in_spatial[i]) - wei_spatial[i] + 1, GetConvStrides()[i]);\n        }\n    }\n    else if(paddingMode == miopenPaddingDefault || paddingMode == miopenPaddingSame ||\n            paddingMode == miopenPaddingValid)\n    {\n        if(mode == miopenTranspose)\n        {\n            out_c = wei_c * group_count;\n\n            for(int i = 0; i < spatial_dim; ++i)\n            {\n                out_spatial[i] = std::max<std::ptrdiff_t>(\n                    1,\n                    GetConvStrides()[i] * (std::ptrdiff_t(in_spatial[i]) - 1) + 1 +\n                        GetConvDilations()[i] * (std::ptrdiff_t(wei_spatial[i]) - 1) -\n                        2 * GetConvPads()[i] + GetTransposeConvPads()[i]);\n            }\n        }\n        else\n        {\n            out_c = wei_k;\n\n            for(int i = 0; i < spatial_dim; ++i)\n            {\n                out_spatial[i] = std::max<std::ptrdiff_t>(\n                    1,\n                    (ptrdiff_t(in_spatial[i]) -\n                     (1 + GetConvDilations()[i] * (std::ptrdiff_t(wei_spatial[i]) - 1)) +\n                     2 * GetConvPads()[i]) /\n                            GetConvStrides()[i] +\n                        1);\n            }\n        }\n    }\n    else\n        MIOPEN_THROW(miopenStatusInvalidValue, \"Invalid Padding Mode!\");\n\n    out_lens[0] = in_n;\n    out_lens[1] = out_c;\n\n    return TensorDescriptor((xDesc.GetType() == miopenInt8 || xDesc.GetType() == miopenInt8x4\n                                 ? (yType == miopenInt32 ? yType : miopenFloat)\n                                 : xDesc.GetType()),\n                            out_lens);\n}\n\nstd::size_t ConvolutionDescriptor::ForwardGetWorkSpaceSizeGEMM(const TensorDescriptor& wDesc,\n                                                               const TensorDescriptor& yDesc) const\n{\n    const std::size_t spatial_dim = GetSpatialDimension();\n\n    auto wei_spatial = boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + spatial_dim);\n    auto out_spatial = boost::adaptors::slice(yDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    const std::size_t wei_c = wDesc.GetLengths()[1];\n\n    const std::size_t workspace_size = wei_c * std::accumulate(wei_spatial.begin(),\n                                                               wei_spatial.end(),\n                                                               std::size_t(1),\n                                                               std::multiplies<std::size_t>()) *\n                                       std::accumulate(out_spatial.begin(),\n                                                       out_spatial.end(),\n                                                       std::size_t(1),\n                                                       std::multiplies<std::size_t>()) *\n                                       GetTypeSize(wDesc.GetType());\n\n    // No workspace is needed for 1x1 convolutions\n    if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n       miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; }))\n    {\n        if(wDesc.GetType() == miopenInt8)\n            return workspace_size;\n        else\n            return 0;\n    }\n\n    return (wDesc.GetType() == miopenInt8 ? 2 * workspace_size : workspace_size);\n}\n\nstd::size_t\nConvolutionDescriptor::ForwardGetWorkSpaceSizeGEMMTranspose(const TensorDescriptor& xDesc,\n                                                            const TensorDescriptor& yDesc) const\n{\n    std::size_t in_n, in_c;\n    std::tie(in_n, in_c) = miopen::tie_pick<0, 1>{}(xDesc.GetLengths());\n\n    auto out_spatial = boost::adaptors::slice(yDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n\n    std::size_t x_t_size = in_n * in_c * std::accumulate(out_spatial.begin(),\n                                                         out_spatial.end(),\n                                                         std::size_t(1),\n                                                         std::multiplies<std::size_t>()) *\n                           GetTypeSize(xDesc.GetType());\n\n    // Int8 also does \"transpose_packed_MN2NM\" which need additional workspace\n    if(xDesc.GetType() == miopenInt8)\n        x_t_size *= 2;\n\n    const std::size_t y_t_size = yDesc.GetElementSize() * GetTypeSize(yDesc.GetType());\n\n    return x_t_size + y_t_size;\n}\n\n/// There is assumption that if Winograd is applicable and granularity loss is low, then there is no\n/// advantage in trying other algorithms as those either slower or use more workspace. This allows\n/// for some related host-side optimizations.\n///\n/// These optimizations are kind of cutting corners, but advantages are quite high.\nbool ConvolutionDescriptor::IsWinograd3x3SupportedAndFast(miopen::ConvolutionContext& ctx) const\n{\n    // Filter out configs where 3x3 Winograd does not have high WTI.\n    if(!(ctx.n_outputs >= 16 && ctx.n_outputs % 2 == 0))\n        return false;\n\n    return solver::ConvBinWinograd3x3U{}.IsApplicable(ctx);\n}\n\n/// \\todo Merge with ForwardGetWorkSpaceSizeGEMM\n/// Use it instead of ForwardGetWorkSpaceSizeGEMM in ForwardGetWorkSpaceSize\nstd::size_t\nConvolutionDescriptor::ForwardGetValidWorkSpaceSizeGemm(Handle& handle,\n                                                        const TensorDescriptor& wDesc,\n                                                        const TensorDescriptor& xDesc,\n                                                        const TensorDescriptor& yDesc) const\n{\n\n#if MIOPEN_USE_GEMM\n    const std::size_t spatial_dim = GetSpatialDimension();\n    auto wei_spatial              = boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + spatial_dim);\n    auto in_spatial               = boost::adaptors::slice(xDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    // Use transpose path if input ht and width <= 14 for 1x1_stride=1 convolutions OR for\n    // 1x1_stride=2\n    if(GetSpatialDimension() == 2 &&\n       (miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n        miopen::all_of(GetConvPads(), [](auto v) { return v == 0; })) &&\n       ((miopen::all_of(in_spatial, [](auto v) { return v <= 14; }) &&\n         miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; })) ||\n        miopen::all_of(GetConvStrides(), [](auto v) { return v == 2; })))\n    {\n        size_t gemm_trans = ForwardGetWorkSpaceSizeGEMMTranspose(xDesc, yDesc);\n        /// \\todo WORKAROUND for issue 1430\n        if(gemm_trans > MAX_MEM_ALLOC_SZ /* handle.GetMaxMemoryAllocSize() */)\n            gemm_trans = 0;\n        return gemm_trans;\n    }\n\n    size_t workspace_size_gemm = ForwardGetWorkSpaceSizeGEMM(wDesc, yDesc) * group_count;\n    /// \\todo WORKAROUND for issue 1430\n    if(workspace_size_gemm > MAX_MEM_ALLOC_SZ /* handle.GetMaxMemoryAllocSize() */)\n        workspace_size_gemm = 0;\n\n    return workspace_size_gemm;\n#else\n    (void)handle;\n    (void)wDesc;\n    (void)xDesc;\n    (void)yDesc;\n    return 0;\n#endif\n}\n\nstd::size_t\nConvolutionDescriptor::WrwGetValidWorkSpaceSizeGemm(const TensorDescriptor& dyDesc,\n                                                    const TensorDescriptor& /*xDesc*/,\n                                                    const TensorDescriptor& dwDesc) const\n{\n#if MIOPEN_USE_GEMM\n    const std::size_t spatial_dim = GetSpatialDimension();\n    const auto wei_spatial        = boost::adaptors::slice(dwDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    // if not 1x1\n    if((miopen::any_of(wei_spatial, [](auto v) { return v != 1; }) ||\n        miopen::any_of(GetConvPads(), [](auto v) { return v != 0; }) ||\n        miopen::any_of(GetConvStrides(), [](auto v) { return v != 1; })))\n        return BackwardWeightsGetWorkSpaceSizeGEMM(dyDesc, dwDesc) * group_count;\n\n    if(miopen::any_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::any_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n       miopen::any_of(GetConvStrides(), [](auto v) { return v == 1; }))\n        return 0;\n\n    MIOPEN_THROW(miopenStatusNotImplemented);\n#else\n    std::ignore = dwDesc;\n    std::ignore = dyDesc;\n    return 0;\n#endif\n}\n\nstd::size_t ConvolutionDescriptor::ForwardGetWorkSpaceSize(Handle& handle,\n                                                           const TensorDescriptor& wDesc,\n                                                           const TensorDescriptor& xDesc,\n                                                           const TensorDescriptor& yDesc) const\n{\n    MIOPEN_LOG_I(\"\");\n\n    auto ctx = ConvolutionContext{xDesc, wDesc, yDesc, *this, 1}; // Forward\n    ctx.SetStream(&handle);\n    ctx.DetectRocm();\n\n    if(IsWinograd3x3SupportedAndFast(ctx))\n        return 0;\n\n    ctx.SetupFloats();\n    ctx.do_search             = false;\n    ctx.disable_perfdb_access = true;\n\n    const size_t direct_workspace = ForwardBackwardDataGetWorkSpaceSizeDirect(ctx);\n\n    const size_t implicit_gemm_workspace = ForwardGetWorkSpaceSizeImplicitGemm(ctx);\n\n    const size_t workspace_size_scgemm = ForwardBackwardDataGetWorkSpaceSizeSCGemm(handle, ctx);\n\n#if MIOPEN_USE_GEMM\n    const std::size_t spatial_dim = GetSpatialDimension();\n    const auto wei_spatial        = boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + spatial_dim);\n    const auto in_spatial         = boost::adaptors::slice(xDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    size_t workspace_size_gemm = ForwardGetWorkSpaceSizeGEMM(wDesc, yDesc) * group_count;\n    /// \\todo WORKAROUND for issue 1430\n    if(workspace_size_gemm > MAX_MEM_ALLOC_SZ /* handle.GetMaxMemoryAllocSize() */)\n        workspace_size_gemm = 0;\n\n    // Use transpose path if input ht and width <= 14 for 1x1_stride=1 convolutions OR for\n    // 1x1_stride=2\n    if(GetSpatialDimension() == 2 &&\n       (miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n        miopen::all_of(GetConvPads(), [](auto v) { return v == 0; })) &&\n       ((miopen::all_of(in_spatial, [](auto v) { return v <= 14; }) &&\n         miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; })) ||\n        miopen::all_of(GetConvStrides(), [](auto v) { return v == 2; })))\n    {\n        size_t gemm_trans = ForwardGetWorkSpaceSizeGEMMTranspose(xDesc, yDesc);\n        /// \\todo WORKAROUND for issue 1430\n        if(gemm_trans > MAX_MEM_ALLOC_SZ /* handle.GetMaxMemoryAllocSize() */)\n            gemm_trans = 0;\n        return std::max({gemm_trans, direct_workspace, workspace_size_scgemm});\n    }\n\n    if(miopen::any_of(GetConvDilations(), [](auto v) { return v > 1; }))\n    {\n        return std::max({workspace_size_gemm, direct_workspace, workspace_size_scgemm});\n    }\n#else\n    size_t workspace_size_gemm = 0;\n#endif\n\n    const bool is_datatype_int8 =\n        (wDesc.GetType() == miopenInt8 || wDesc.GetType() == miopenInt8x4);\n\n    const size_t workspace_size_fft =\n        (GetSpatialDimension() == 2 &&\n         miopen::all_of(GetConvDilations(), [](auto v) { return v == 1; }) && !is_datatype_int8)\n            ? ForwardGetWorkSpaceSizeFFT(wDesc, xDesc, yDesc)\n            : 0;\n\n    return std::max({workspace_size_fft,\n                     workspace_size_gemm,\n                     direct_workspace,\n                     implicit_gemm_workspace,\n                     workspace_size_scgemm});\n}\n\nstd::size_t\nConvolutionDescriptor::BackwardDataGetWorkSpaceSize(Handle& handle,\n                                                    const TensorDescriptor& wDesc,\n                                                    const TensorDescriptor& dyDesc,\n                                                    const TensorDescriptor& dxDesc) const\n{\n    MIOPEN_LOG_I(\"\");\n\n    auto ctx = ConvolutionContext{dxDesc, wDesc, dyDesc, *this, 0}; // Backward\n    ctx.SetStream(&handle);\n    ctx.DetectRocm();\n\n    if(IsWinograd3x3SupportedAndFast(ctx))\n        return 0;\n\n    ctx.SetupFloats();\n    ctx.do_search             = false;\n    ctx.disable_perfdb_access = true;\n\n    const size_t direct_workspace = ForwardBackwardDataGetWorkSpaceSizeDirect(ctx);\n\n#if MIOPEN_USE_GEMM\n    size_t workspace_size_gemm = BackwardDataGetWorkSpaceSizeGEMM(wDesc, dyDesc) * group_count;\n    /// \\todo WORKAROUND for issue 1430\n    if(workspace_size_gemm > MAX_MEM_ALLOC_SZ /*  handle.GetMaxMemoryAllocSize() */)\n        workspace_size_gemm = 0;\n\n    const auto wei_spatial =\n        boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n\n    if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n       miopen::all_of(GetConvStrides(), [](auto v) { return v == 2; }))\n    {\n        size_t gemm_trans = BackwardDataGetWorkSpaceSizeGEMMTranspose(dyDesc, dxDesc);\n        /// \\todo WORKAROUND for issue 1430\n        if(gemm_trans > MAX_MEM_ALLOC_SZ /*  handle.GetMaxMemoryAllocSize() */)\n            gemm_trans = 0;\n        return std::max(gemm_trans, direct_workspace);\n    }\n    if(miopen::any_of(GetConvDilations(), [](auto v) { return v > 1; }))\n        return std::max(workspace_size_gemm, direct_workspace);\n#else\n    size_t workspace_size_gemm = 0;\n#endif\n\n    const size_t workspace_size_fft =\n        (GetSpatialDimension() == 2 &&\n         miopen::all_of(GetConvDilations(), [](auto v) { return v == 1; }) &&\n         wDesc.GetType() != miopenInt8)\n            ? BackwardGetWorkSpaceSizeFFT(wDesc, dyDesc, dxDesc)\n            : 0;\n\n    return std::max({workspace_size_fft, workspace_size_gemm, direct_workspace});\n}\n\nstd::size_t\nConvolutionDescriptor::BackwardDataGetWorkSpaceSizeGEMM(const TensorDescriptor& wDesc,\n                                                        const TensorDescriptor& dyDesc) const\n{\n    const std::size_t spatial_dim = GetSpatialDimension();\n\n    auto wei_spatial = boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + spatial_dim);\n    auto out_spatial = boost::adaptors::slice(dyDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    const std::size_t wei_c = wDesc.GetLengths()[1];\n\n    std::size_t gemm_size = wei_c * std::accumulate(wei_spatial.begin(),\n                                                    wei_spatial.end(),\n                                                    std::size_t(1),\n                                                    std::multiplies<std::size_t>()) *\n                            std::accumulate(out_spatial.begin(),\n                                            out_spatial.end(),\n                                            std::size_t(1),\n                                            std::multiplies<std::size_t>()) *\n                            GetTypeSize(dyDesc.GetType());\n\n    // No workspace is needed for 1x1_stride=1 convolutions\n    if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }))\n    {\n        return 0;\n    }\n\n    return gemm_size;\n}\n\nstd::size_t ConvolutionDescriptor::BackwardDataGetWorkSpaceSizeGEMMTranspose(\n    const TensorDescriptor& dyDesc, const TensorDescriptor& dxDesc) const\n{\n    std::size_t in_n, in_c;\n    std::tie(in_n, in_c) = miopen::tie_pick<0, 1>{}(dxDesc.GetLengths());\n\n    auto out_spatial = boost::adaptors::slice(dyDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n\n    const std::size_t dx_t_size = in_n * in_c * std::accumulate(out_spatial.begin(),\n                                                                out_spatial.end(),\n                                                                std::size_t(1),\n                                                                std::multiplies<std::size_t>()) *\n                                  GetTypeSize(dxDesc.GetType());\n\n    const std::size_t dy_t_size = dyDesc.GetElementSize() * GetTypeSize(dyDesc.GetType());\n\n    return dx_t_size + dy_t_size;\n}\n\nstd::size_t\nConvolutionDescriptor::BackwardWeightsGetWorkSpaceSizeGEMM(const TensorDescriptor& dyDesc,\n                                                           const TensorDescriptor& dwDesc) const\n{\n    const std::size_t spatial_dim = GetSpatialDimension();\n\n    auto out_spatial = boost::adaptors::slice(dyDesc.GetLengths(), 2, 2 + spatial_dim);\n    auto wei_spatial = boost::adaptors::slice(dwDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    const std::size_t wei_c = dwDesc.GetLengths()[1];\n\n    const std::size_t gemm_size =\n        GetTypeSize(dyDesc.GetType()) * wei_c * std::accumulate(out_spatial.begin(),\n                                                                out_spatial.end(),\n                                                                std::size_t(1),\n                                                                std::multiplies<std::size_t>()) *\n        std::accumulate(\n            wei_spatial.begin(), wei_spatial.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n    // No workspace is needed for 1x1_stride=1 convolutions\n    if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }))\n    {\n        return 0;\n    }\n\n    return gemm_size;\n}\n\nstd::size_t ConvolutionDescriptor::ForwardGetWorkSpaceSizeImplicitGemm(\n    const miopen::ConvolutionContext& ctx) const\n{\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMPLICIT_GEMM{}))\n    {\n        return 0;\n    }\n\n    try\n    {\n        const auto ss  = FindAllImplicitGemmSolutions(ctx);\n        std::size_t sz = 0;\n        for(const auto& solution : ss)\n        {\n            if(sz < solution.workspce_sz)\n            {\n                MIOPEN_LOG_I2(sz << \" < \" << solution.workspce_sz);\n                sz = solution.workspce_sz;\n            }\n        }\n        return sz;\n    }\n    catch(const miopen::Exception&)\n    {\n        MIOPEN_LOG_E(\"failed in ForwardGetWorkSpaceSizeImplicitGemm\");\n        return 0;\n    }\n}\n\nstd::size_t ConvolutionDescriptor::ForwardBackwardDataGetWorkSpaceSizeDirect(\n    const miopen::ConvolutionContext& ctx) const\n{\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_DIRECT{}))\n    {\n        return 0;\n    }\n\n    try\n    {\n        const auto sz_v = AllDirectForwardBackwardDataWorkspaceSize(ctx);\n        std::size_t sz  = 0;\n        for(const auto& pr : sz_v)\n        {\n            if(sz < pr.second)\n            {\n                MIOPEN_LOG_I2(sz << \" < \" << pr.second); // solution.workspce_sz);\n                sz = pr.second;                          // solution.workspce_sz;\n            }\n        }\n        return sz;\n    }\n    catch(const miopen::Exception&)\n    {\n        return 0;\n    }\n}\n\nstd::size_t ConvolutionDescriptor::ForwardBackwardDataGetWorkSpaceSizeSCGemm(\n    Handle& handle, const miopen::ConvolutionContext& ctx) const\n{\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_SCGEMM{}))\n    {\n        return 0;\n    }\n\n    std::size_t sz = 0;\n\n#if MIOPEN_USE_SCGEMM\n    sz = GetMaximumSCGemmConvFwdWorkSpaceSize(ctx);\n    if(sz > MAX_MEM_ALLOC_SZ)\n        sz = 0;\n#else\n    (void)handle;\n    (void)ctx;\n#endif\n\n    return sz;\n}\n\nstd::size_t\nConvolutionDescriptor::BackwardWeightsGetWorkSpaceSizeDirect(Handle& handle,\n                                                             const TensorDescriptor& dyDesc,\n                                                             const TensorDescriptor& xDesc,\n                                                             const TensorDescriptor& dwDesc) const\n{\n    auto ctx = ConvolutionContext(xDesc, dwDesc, dyDesc, *this, 0);\n    ctx.direction.SetBackwardWrW();\n    ctx.do_search = false;\n    ctx.SetStream(&handle);\n    ctx.disable_perfdb_access = true;\n    ctx.SetupFloats();\n    ctx.DetectRocm();\n\n    try\n    {\n        const auto sz_v = AllDirectBwdWrW2DWorkspaceSize(ctx);\n        std::size_t sz  = 0;\n        for(const auto& pr : sz_v)\n        {\n            if(sz < pr.second)\n            {\n                MIOPEN_LOG_I2(sz << \" < \" << pr.second);\n                sz = pr.second;\n            }\n        }\n        return sz;\n    }\n    catch(const miopen::Exception&)\n    {\n        return 0;\n    }\n}\n\nstd::size_t\nConvolutionDescriptor::BackwardWeightsGetWorkSpaceSizeWinograd(Handle& handle,\n                                                               const TensorDescriptor& dyDesc,\n                                                               const TensorDescriptor& xDesc,\n                                                               const TensorDescriptor& dwDesc) const\n{\n    auto ctx = ConvolutionContext(xDesc, dwDesc, dyDesc, *this, 0);\n    ctx.direction.SetBackwardWrW();\n    ctx.do_search = false;\n    ctx.SetStream(&handle);\n    ctx.disable_perfdb_access = true;\n    ctx.DetectRocm();\n\n    try\n    {\n        const auto ss  = FindWinogradWrWAllSolutions(ctx);\n        std::size_t sz = 0;\n        for(const auto& solution : ss)\n        {\n            if(sz < solution.workspce_sz)\n            {\n                MIOPEN_LOG_I2(sz << \" < \" << solution.workspce_sz);\n                sz = solution.workspce_sz;\n            }\n        }\n        return sz;\n    }\n    catch(const miopen::Exception&)\n    {\n        return 0;\n    }\n}\nstd::size_t\nConvolutionDescriptor::BackwardWeightsGetWorkSpaceSize(Handle& handle,\n                                                       const TensorDescriptor& dyDesc,\n                                                       const TensorDescriptor& xDesc,\n                                                       const TensorDescriptor& dwDesc) const\n{\n    MIOPEN_LOG_I(\"\");\n\n    std::size_t workspace_size = 0;\n    {\n        std::size_t workspace_size_gemm =\n#if MIOPEN_USE_GEMM\n            BackwardWeightsGetWorkSpaceSizeGEMM(dyDesc, dwDesc) * group_count;\n        /// \\todo WORKAROUND for issue 1430\n        if(workspace_size_gemm > MAX_MEM_ALLOC_SZ /*  handle.GetMaxMemoryAllocSize() */)\n            workspace_size_gemm =\n#endif\n                0;\n\n        size_t direct_workspace =\n            BackwardWeightsGetWorkSpaceSizeDirect(handle, dyDesc, xDesc, dwDesc);\n\n        size_t winograd_workspace =\n            BackwardWeightsGetWorkSpaceSizeWinograd(handle, dyDesc, xDesc, dwDesc);\n\n        workspace_size =\n            std::max(winograd_workspace, std::max(direct_workspace, workspace_size_gemm));\n    }\n\n    return workspace_size;\n}\n\nstd::ostream& operator<<(std::ostream& stream, const ConvolutionDescriptor& c)\n{\n    stream << \"conv\" << c.spatialDim << \"d, \";\n    MIOPEN_LOG_ENUM(stream, c.mode, miopenConvolution, miopenTranspose) << \", \";\n    MIOPEN_LOG_ENUM(\n        stream, c.paddingMode, miopenPaddingDefault, miopenPaddingSame, miopenPaddingValid)\n        << \", \";\n\n    LogRange(stream << \"{\", c.GetConvPads(), \", \") << \"}, \";\n    LogRange(stream << \"{\", c.GetConvStrides(), \", \") << \"}, \";\n    LogRange(stream << \"{\", c.GetConvDilations(), \", \") << \"}, \";\n\n    if(c.group_count > 1)\n    {\n        stream << c.group_count << \", \";\n    }\n\n    if(c.mode == miopenTranspose)\n    {\n        LogRange(stream << \"{\", c.GetTransposeConvPads(), \", \") << \"}, \";\n    }\n\n    return stream;\n}\n} // namespace miopen\n", "meta": {"hexsha": "c8e5cb63074f67cad47bab52ddfb1bc9d3f8408b", "size": 31415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/convolution.cpp", "max_stars_repo_name": "whchung/MIOpen", "max_stars_repo_head_hexsha": "011b36541032b8979ad78c8f52606a2b8d36502d", "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/convolution.cpp", "max_issues_repo_name": "whchung/MIOpen", "max_issues_repo_head_hexsha": "011b36541032b8979ad78c8f52606a2b8d36502d", "max_issues_repo_licenses": ["MIT"], "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/convolution.cpp", "max_forks_repo_name": "whchung/MIOpen", "max_forks_repo_head_hexsha": "011b36541032b8979ad78c8f52606a2b8d36502d", "max_forks_repo_licenses": ["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.3577533578, "max_line_length": 100, "alphanum_fraction": 0.5655896865, "num_tokens": 7424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.16542491077427615}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <signal.h>\n#include \"xboxctrl.h\"\n#include \"slambot.h\"\n#include <armadillo>\n#include <pthread.h>\n\nstatic int stopsig;\nusing namespace arma;\n\nstatic xboxctrl_t ctrl;\nstatic pthread_t thread;\nvoid *thread_ctrl_update(void *args) {\n  while (!stopsig) {\n    xboxctrl_update(&ctrl);\n  }\n  return NULL;\n}\n\nvoid stop(int signo) {\n  printf(\"yo\\n\");\n  stopsig = 1;\n}\n\ndouble deadzone(double v) {\n  if (-0.3 < v && v < 0.3) {\n    return 0.0;\n  }\n  return v;\n}\n\nint main() {\n  signal(SIGINT, stop);\n  xboxctrl_connect(&ctrl);\n  slambot bot;\n\n  pthread_create(&thread, NULL, thread_ctrl_update, NULL);\n\n  while (!stopsig) {\n    double lx = deadzone(ctrl.LJOY.x);\n    double ly = deadzone(ctrl.LJOY.y);\n    double rx = deadzone(ctrl.RJOY.x);\n//    double ry = deadzone(ctrl.RJOY.y);\n    bot.send(vec({\n      -ly - lx - rx,\n      -ly + lx + rx,\n      -ly + lx - rx,\n      -ly - lx + rx,\n      0}));\n  }\n\n  pthread_join(thread, NULL);\n\n  xboxctrl_disconnect(&ctrl);\n  return 0;\n}\n", "meta": {"hexsha": "a3af1dde63f6e895d118ca5445e0ace699f6f3a9", "size": 1032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robot/slambot/test.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "robot/slambot/test.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "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/slambot/test.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4915254237, "max_line_length": 58, "alphanum_fraction": 0.6182170543, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.16542185544165283}}
{"text": "#pragma once\n\n#include <utility>\n\n#include <boost/operators.hpp>\n\n#include <elle/cryptography/dh/PrivateKey.hh>\n#include <elle/cryptography/fwd.hh>\n#include <elle/cryptography/types.hh>\n#include <elle/cryptography/Oneway.hh>\n#include <elle/cryptography/Cipher.hh>\n\n#include <elle/attribute.hh>\n#include <elle/operator.hh>\n\n//\n// ---------- Class -----------------------------------------------------------\n//\n\nnamespace elle\n{\n  namespace cryptography\n  {\n    namespace dh\n    {\n      /// Represent a public key in the DH asymmetric cryptosystem.\n      class PublicKey\n        : public elle::Printable\n        , private boost::totally_ordered<PublicKey>\n      {\n        /*-------------.\n        | Construction |\n        `-------------*/\n      public:\n        /// Construct a public key out of its private counterpart.\n        explicit\n        PublicKey(PrivateKey const& k);\n        /// Construct a public key based on the given EVP_PKEY key whose\n        /// ownership is transferred.\n        explicit\n        PublicKey(::EVP_PKEY* key);\n        /// Construct a public key based on the given DH key whose\n        /// ownership is transferred to the public key.\n        explicit\n        PublicKey(::DH* dh);\n        PublicKey(PublicKey const& other);\n        PublicKey(PublicKey&& other);\n        virtual\n        ~PublicKey() = default;\n\n        /*--------.\n        | Methods |\n        `--------*/\n      private:\n        /// Construct the object based on the given DH structure whose\n        /// ownership is transferred to the callee.\n        void\n        _construct(::DH* dh);\n        /// Check that the key is valid.\n        void\n        _check() const;\n      public:\n        /// Return the public key's size in bytes.\n        uint32_t\n        size() const;\n        /// Return the public key's length in bits.\n        uint32_t\n        length() const;\n\n        /*----------.\n        | Operators |\n        `----------*/\n      public:\n        bool\n        operator ==(PublicKey const& other) const;\n        ELLE_OPERATOR_NO_ASSIGNMENT(PublicKey);\n\n        /*----------.\n        | Printable |\n        `----------*/\n      public:\n        void\n        print(std::ostream& stream) const override;\n\n        /*-----------.\n        | Attributes |\n        `-----------*/\n      public:\n        ELLE_ATTRIBUTE_R(types::EVP_PKEY, key);\n      };\n    }\n  }\n}\n\nnamespace std\n{\n  template <>\n  struct hash<elle::cryptography::dh::PublicKey>\n  {\n    size_t\n    operator ()(elle::cryptography::dh::PublicKey const& value) const;\n  };\n}\n", "meta": {"hexsha": "dc0d3d429996358c2a061da554dce2ebfeb33602", "size": 2519, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/elle/cryptography/dh/PublicKey.hh", "max_stars_repo_name": "infinitio/elle", "max_stars_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 521.0, "max_stars_repo_stars_event_min_datetime": "2016-02-14T00:39:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T22:39:25.000Z", "max_issues_repo_path": "src/elle/cryptography/dh/PublicKey.hh", "max_issues_repo_name": "infinitio/elle", "max_issues_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-02-21T11:47:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-01T09:37:14.000Z", "max_forks_repo_path": "src/elle/cryptography/dh/PublicKey.hh", "max_forks_repo_name": "infinitio/elle", "max_forks_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2017-02-21T10:18:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:35:20.000Z", "avg_line_length": 24.2211538462, "max_line_length": 79, "alphanum_fraction": 0.5323541088, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.16542185544165278}}
{"text": "#include <boost/algorithm/string/predicate.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/lexical_cast.hpp>\n#include <ignition/math/Vector3.hh>\n#include <gazebo/physics/physics.hh>\n#include \"gazebo_waypoint_plugin.h\"\n#include <gazebo/msgs/msgs.hh>\n#include \"waypoint.pb.h\"\n\nusing namespace std;\n\nnamespace gazebo {\n\nGZ_REGISTER_MODEL_PLUGIN(GazeboWaypointPlugin);\n\nGazeboWaypointPlugin::~GazeboWaypointPlugin()\n{\n  event::Events::DisconnectWorldUpdateBegin(this->_updateConnection);\n}\n\nvoid GazeboWaypointPlugin::Load(physics::ModelPtr model, sdf::ElementPtr sdf) {\n  auto _name = sdf->GetAttribute(\"name\")->GetAsString();\n  boost::to_upper(_name);\n  if (boost::starts_with(_name, \"WAYPOINT\")) {\n    this->_no = atoi(_name.substr(strlen(\"WAYPOINT\")).c_str());\n  } else {\n    gzerr << \"[waypoint] Waypoint N must be named 'waypointN'\\n\";\n    this->_no = -1;\n    return;\n  }\n\n  if(sdf->HasElement(\"radius\")) {\n    this->_radius = sdf->GetElement(\"radius\")->Get<double>();\n  } else {\n    this->_radius = 2;\n  }\n\n  this->_visual_name = \"__WAYPOINT__VISUAL__NO__\" + this->_no;\n  this->_model = model;\n  this->_node = gazebo::transport::NodePtr(new gazebo::transport::Node());\n  this->_node->Init(_model->GetWorld()->GetName());\n  this->_updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&GazeboWaypointPlugin::OnUpdate, this, _1));\n  this->_visual_pub = this->_node->Advertise<msgs::Visual>(\"~/visual\", 10);\n  this->_waypoint_pub = this->_node\n          ->Advertise<waypoint_msgs::msgs::Waypoint>(\"~/waypoint\", 10);\n  this->_waypoint_sub = this->_node\n          ->Subscribe(\"~/waypoint\", &GazeboWaypointPlugin::OnWaypointUpdate, this);\n\n  /* Waypoint no 0 is active by default */\n  this->SetActive(this->_no == 0);\n  this->SetValid(false);\n  this->UpdateVisual(this->_color);\n}\n\nvoid GazeboWaypointPlugin::OnUpdate(const common::UpdateInfo& /*_info*/) {\n  if(this->_active && !this->_valid) {\n    /* Retrieve position of drone and waypoint */\n    ignition::math::Vector3d pose = _model->GetWorld()\n          ->GetModel(\"iris_dronecourse\")\n          ->GetWorldPose().Ign().Pos();\n    ignition::math::Vector3d wp_pose = _model\n          ->GetWorldPose().Ign().Pos();\n    /* Compute distance from center waypoint */\n    double distance = (pose - wp_pose).Length();\n    /* Validate waypoint if drone is inside the waypoint radius */\n    this->SetValid(distance < this->_radius);\n  }\n  this->UpdateVisual(this->_color);\n}\n\nvoid GazeboWaypointPlugin::UpdateVisual(std::string color) {\n  msgs::Visual visualMsg;\n\n  visualMsg.set_name(this->_visual_name);\n\n  visualMsg.set_parent_name(_model->GetScopedName());\n  msgs::Geometry *geomMsg = visualMsg.mutable_geometry();\n  geomMsg->set_type(msgs::Geometry::SPHERE);\n  geomMsg->mutable_sphere()->set_radius(this->_radius);\n  visualMsg.mutable_material()->mutable_script()\n        ->set_name(color);\n  msgs::Set(visualMsg.mutable_pose(),\n    _model->GetWorldPose().Ign());\n  visualMsg.set_cast_shadows(false);\n  visualMsg.set_transparency(0.5);\n\n  this->_visual_pub->Publish(visualMsg);\n}\n\nvoid GazeboWaypointPlugin::SetValid(bool valid) {\n  bool old_valid = this->_valid;\n  this->_valid = valid;\n  if(old_valid != valid) {\n    this->FireValid(valid);\n    if(this->_valid) {\n      this->SetColor(GAZEBO_COLOR_VALIDATED);\n    } else {\n      if(this->_active) {\n        this->SetColor(GAZEBO_COLOR_ACTIVE);\n      } else {\n        this->SetColor(GAZEBO_COLOR_INACTIVE);\n      }\n    }\n  }\n}\n\nvoid GazeboWaypointPlugin::SetActive(bool active) {\n  bool old_active = this->_active;\n  this->_active = active;\n  if(old_active != active) {\n    if(this->_valid) {\n      this->SetColor(GAZEBO_COLOR_VALIDATED);\n    } else {\n      if(this->_active) {\n        this->SetColor(GAZEBO_COLOR_ACTIVE);\n      } else {\n        this->SetColor(GAZEBO_COLOR_INACTIVE);\n      }\n    }\n  }\n}\n\nvoid GazeboWaypointPlugin::SetColor(std::string color) {\n  this->_color = color;\n}\n\nvoid GazeboWaypointPlugin::FireValid(bool valid) {\n  /* Only notify validation. Do not notify de-validation. */\n  if(!valid) {\n    return;\n  }\n  waypoint_msgs::msgs::Waypoint msg;\n  msg.set_waypoint_no(this->_no);\n  msg.set_validated(valid);\n  _waypoint_pub->Publish(msg);\n}\n\nvoid GazeboWaypointPlugin::OnWaypointUpdate(WaypointPtr &msg) {\n  if(msg->has_waypoint_no() && msg->waypoint_no() + 1 == this->_no) {\n    this->SetActive(true);\n  }\n}\n}\n", "meta": {"hexsha": "6e74fffbb63d60f51e8653d45e8715487b6e3563", "size": 4370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tools/sitl_gazebo/src/gazebo_waypoint_plugin.cpp", "max_stars_repo_name": "janbenzing/Drone-Simulation", "max_stars_repo_head_hexsha": "40950f6db989c432116aa2c40042abd648dfc470", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-10T23:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-10T23:14:44.000Z", "max_issues_repo_path": "Tools/sitl_gazebo/src/gazebo_waypoint_plugin.cpp", "max_issues_repo_name": "janbenzing/Drone-Simulation", "max_issues_repo_head_hexsha": "40950f6db989c432116aa2c40042abd648dfc470", "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": "Tools/sitl_gazebo/src/gazebo_waypoint_plugin.cpp", "max_forks_repo_name": "janbenzing/Drone-Simulation", "max_forks_repo_head_hexsha": "40950f6db989c432116aa2c40042abd648dfc470", "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.3472222222, "max_line_length": 123, "alphanum_fraction": 0.6853546911, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1654218520933321}}
{"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\u00e4nkt), 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 <boost/numeric/mtl/mtl.hpp>\n#include <boost/rational.hpp>\n\nint main(int argc, char* argv[]) \n{\n#if 0\n    boost::rational<long> test(1,2);\n    test += boost::rational<long>(1,3);\n    std::cout << test;\n\n    mtl::dense_vector< boost::rational<long> > testVec(2);\n    testVec(0) = boost::rational<long>(1,3);\n    testVec[1] = boost::rational<long>(1,4);\n\n    std::cout << testVec(0) << \"\\n\";\n    std::cout << testVec[1] << \"\\n\";\n    std::cout << testVec << \"\\n\";\n#endif\n}\n", "meta": {"hexsha": "55116b75567a5e01e0a02778f14a7de9e6ffb3dd", "size": 942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/boost_rational_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/experimental/boost_rational_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/experimental/boost_rational_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": 28.5454545455, "max_line_length": 94, "alphanum_fraction": 0.6433121019, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.16540073660071225}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\n#include <scitbx/random/mersenne_twister.h>\n\nnamespace scitbx { namespace random { namespace boost_python {\n\n  void wrap_random();\n\n  /*! This is intentionally kept useless as a generator\n   in order to discourage use directly from python.\n   Instead use variate_generators.\n   */\n  struct mt19937_wrappers\n  {\n    typedef boost_random::mt19937 wt;\n\n    static void wrap() {\n      using namespace boost::python;\n      class_<wt>(\"mersenne_twister_19937\", no_init)\n        .def(init<wt::result_type>(arg(\"value\")))\n        .def(\"seed\", (void(wt::*)()) &wt::seed)\n        .def(\"seed\", (void(wt::*)(const wt::result_type&)) &wt::seed)\n        ;\n    }\n  };\n\n  namespace {\n    void init_module() {\n      mt19937_wrappers::wrap();\n      wrap_random();\n    }\n  }\n}}}\n\nBOOST_PYTHON_MODULE(scitbx_random_ext)\n{\n  scitbx::random::boost_python::init_module();\n}\n", "meta": {"hexsha": "e963a2bcf65e79f621179dcc3c4a62b7736fd64c", "size": 954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/random/boost_python/random_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": "scitbx/random/boost_python/random_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": "scitbx/random/boost_python/random_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": 23.2682926829, "max_line_length": 69, "alphanum_fraction": 0.6561844864, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.16511407867033676}}
{"text": "#pragma once\n\n#include <rai/lib/blocks.hpp>\n#include <rai/node/utility.hpp>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <unordered_map>\n\n#include <blake2/blake2.h>\n\nnamespace boost\n{\ntemplate <>\nstruct hash<rai::uint256_union>\n{\n\tsize_t operator() (rai::uint256_union const & value_a) const\n\t{\n\t\tstd::hash<rai::uint256_union> hash;\n\t\treturn hash (value_a);\n\t}\n};\n}\nnamespace rai\n{\nclass block_store;\n/**\n * Determine the balance as of this block\n */\nclass balance_visitor : public rai::block_visitor\n{\npublic:\n\tbalance_visitor (MDB_txn *, rai::block_store &);\n\tvirtual ~balance_visitor () = default;\n\tvoid compute (rai::block_hash const &);\n\tvoid send_block (rai::send_block const &) override;\n\tvoid receive_block (rai::receive_block const &) override;\n\tvoid open_block (rai::open_block const &) override;\n\tvoid change_block (rai::change_block const &) override;\n\tMDB_txn * transaction;\n\trai::block_store & store;\n\trai::block_hash current;\n\trai::uint128_t result;\n};\n\n/**\n * Determine the amount delta resultant from this block\n */\nclass amount_visitor : public rai::block_visitor\n{\npublic:\n\tamount_visitor (MDB_txn *, rai::block_store &);\n\tvirtual ~amount_visitor () = default;\n\tvoid compute (rai::block_hash const &);\n\tvoid send_block (rai::send_block const &) override;\n\tvoid receive_block (rai::receive_block const &) override;\n\tvoid open_block (rai::open_block const &) override;\n\tvoid change_block (rai::change_block const &) override;\n\tvoid from_send (rai::block_hash const &);\n\tMDB_txn * transaction;\n\trai::block_store & store;\n\trai::uint128_t result;\n};\n\n/**\n * Determine the representative for this block\n */\nclass representative_visitor : public rai::block_visitor\n{\npublic:\n\trepresentative_visitor (MDB_txn * transaction_a, rai::block_store & store_a);\n\tvirtual ~representative_visitor () = default;\n\tvoid compute (rai::block_hash const & hash_a);\n\tvoid send_block (rai::send_block const & block_a) override;\n\tvoid receive_block (rai::receive_block const & block_a) override;\n\tvoid open_block (rai::open_block const & block_a) override;\n\tvoid change_block (rai::change_block const & block_a) override;\n\tMDB_txn * transaction;\n\trai::block_store & store;\n\trai::block_hash current;\n\trai::block_hash result;\n};\n\n/**\n * A key pair. The private key is generated from the random pool, or passed in\n * as a hex string. The public key is derived using ed25519.\n */\nclass keypair\n{\npublic:\n\tkeypair ();\n\tkeypair (std::string const &);\n\trai::public_key pub;\n\trai::raw_key prv;\n};\n\nstd::unique_ptr<rai::block> deserialize_block (MDB_val const &);\n\n/**\n * Latest information about an account\n */\nclass account_info\n{\npublic:\n\taccount_info ();\n\taccount_info (MDB_val const &);\n\taccount_info (rai::account_info const &) = default;\n\taccount_info (rai::block_hash const &, rai::block_hash const &, rai::block_hash const &, rai::amount const &, uint64_t, uint64_t);\n\tvoid serialize (rai::stream &) const;\n\tbool deserialize (rai::stream &);\n\tbool operator== (rai::account_info const &) const;\n\tbool operator!= (rai::account_info const &) const;\n\trai::mdb_val val () const;\n\trai::block_hash head;\n\trai::block_hash rep_block;\n\trai::block_hash open_block;\n\trai::amount balance;\n\t/** Seconds since posix epoch */\n\tuint64_t modified;\n\tuint64_t block_count;\n};\n\n/**\n * Information on an uncollected send, source account, amount, target account.\n */\nclass pending_info\n{\npublic:\n\tpending_info ();\n\tpending_info (MDB_val const &);\n\tpending_info (rai::account const &, rai::amount const &);\n\tvoid serialize (rai::stream &) const;\n\tbool deserialize (rai::stream &);\n\tbool operator== (rai::pending_info const &) const;\n\trai::mdb_val val () const;\n\trai::account source;\n\trai::amount amount;\n};\nclass pending_key\n{\npublic:\n\tpending_key (rai::account const &, rai::block_hash const &);\n\tpending_key (MDB_val const &);\n\tvoid serialize (rai::stream &) const;\n\tbool deserialize (rai::stream &);\n\tbool operator== (rai::pending_key const &) const;\n\trai::mdb_val val () const;\n\trai::account account;\n\trai::block_hash hash;\n};\nclass block_info\n{\npublic:\n\tblock_info ();\n\tblock_info (MDB_val const &);\n\tblock_info (rai::account const &, rai::amount const &);\n\tvoid serialize (rai::stream &) const;\n\tbool deserialize (rai::stream &);\n\tbool operator== (rai::block_info const &) const;\n\trai::mdb_val val () const;\n\trai::account account;\n\trai::amount balance;\n};\nclass block_counts\n{\npublic:\n\tblock_counts ();\n\tsize_t sum ();\n\tsize_t send;\n\tsize_t receive;\n\tsize_t open;\n\tsize_t change;\n};\nclass vote\n{\npublic:\n\tvote () = default;\n\tvote (rai::vote const &);\n\tvote (bool &, rai::stream &);\n\tvote (bool &, rai::stream &, rai::block_type);\n\tvote (rai::account const &, rai::raw_key const &, uint64_t, std::shared_ptr<rai::block>);\n\tvote (MDB_val const &);\n\trai::uint256_union hash () const;\n\tbool operator== (rai::vote const &) const;\n\tbool operator!= (rai::vote const &) const;\n\tvoid serialize (rai::stream &, rai::block_type);\n\tvoid serialize (rai::stream &);\n\tstd::string to_json () const;\n\t// Vote round sequence number\n\tuint64_t sequence;\n\tstd::shared_ptr<rai::block> block;\n\t// Account that's voting\n\trai::account account;\n\t// Signature of sequence + block hash\n\trai::signature signature;\n};\nenum class vote_code\n{\n\tinvalid, // Vote is not signed correctly\n\treplay, // Vote does not have the highest sequence number, it's a replay\n\tvote // Vote has the highest sequence number\n};\nclass vote_result\n{\npublic:\n\trai::vote_code code;\n\tstd::shared_ptr<rai::vote> vote;\n};\n\nenum class process_result\n{\n\tprogress, // Hasn't been seen before, signed correctly\n\tbad_signature, // Signature was bad, forged or transmission error\n\told, // Already seen and was valid\n\tnegative_spend, // Malicious attempt to spend a negative amount\n\tfork, // Malicious fork based on previous\n\tunreceivable, // Source block doesn't exist or has already been received\n\tgap_previous, // Block marked as previous is unknown\n\tgap_source, // Block marked as source is unknown\n\tnot_receive_from_send, // Receive does not have a send source\n\taccount_mismatch, // Account number in open block doesn't match send destination\n\topened_burn_account // The impossible happened, someone found the private key associated with the public key '0'.\n};\nclass process_return\n{\npublic:\n\trai::process_result code;\n\trai::account account;\n\trai::amount amount;\n\trai::account pending_account;\n};\nenum class tally_result\n{\n\tvote,\n\tchanged,\n\tconfirm\n};\nclass votes\n{\npublic:\n\tvotes (std::shared_ptr<rai::block>);\n\trai::tally_result vote (std::shared_ptr<rai::vote>);\n\t// Root block of fork\n\trai::block_hash id;\n\t// All votes received by account\n\tstd::unordered_map<rai::account, std::shared_ptr<rai::block>> rep_votes;\n};\nextern rai::keypair const & zero_key;\nextern rai::keypair const & test_genesis_key;\nextern rai::account const & rai_test_account;\nextern rai::account const & rai_beta_account;\nextern rai::account const & rai_live_account;\nextern std::string const & rai_test_genesis;\nextern std::string const & rai_beta_genesis;\nextern std::string const & rai_live_genesis;\nextern std::string const & genesis_block;\nextern rai::account const & genesis_account;\nextern rai::account const & burn_account;\nextern rai::uint128_t const & genesis_amount;\n// A block hash that compares inequal to any real block hash\nextern rai::block_hash const & not_a_block;\n// An account number that compares inequal to any real account number\nextern rai::block_hash const & not_an_account;\nclass genesis\n{\npublic:\n\texplicit genesis ();\n\tvoid initialize (MDB_txn *, rai::block_store &) const;\n\trai::block_hash hash () const;\n\tstd::unique_ptr<rai::open_block> open;\n};\n}\n", "meta": {"hexsha": "3a05ebf9bc45c4bde0944cb9fdb5c052ec7004aa", "size": 7575, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rai/common.hpp", "max_stars_repo_name": "scotthconner/LiteBlocks", "max_stars_repo_head_hexsha": "fae7835054008d87fd12d21cc7023b9b6a937fa0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T10:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-09T21:34:05.000Z", "max_issues_repo_path": "rai/common.hpp", "max_issues_repo_name": "scotthconner/LiteBlocks", "max_issues_repo_head_hexsha": "fae7835054008d87fd12d21cc7023b9b6a937fa0", "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": "rai/common.hpp", "max_forks_repo_name": "scotthconner/LiteBlocks", "max_forks_repo_head_hexsha": "fae7835054008d87fd12d21cc7023b9b6a937fa0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-25T08:22:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-25T08:22:54.000Z", "avg_line_length": 27.7472527473, "max_line_length": 131, "alphanum_fraction": 0.7318811881, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.16511407536193834}}
{"text": "// Copyright (c) 2020-2021 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace frc3512 {\n\n/**\n * A base class for subsystem controllers.\n *\n * State, Inputs, and Outputs indices should be specified what they represent in\n * the derived class.\n *\n * @tparam States the number of state estimates in the state vector\n * @tparam Inputs the number of control inputs in the input vector\n * @tparam Outputs the number of local outputs in the output vector\n */\ntemplate <int States, int Inputs, int Outputs>\nclass ControllerBase {\npublic:\n    ControllerBase() = default;\n\n    /**\n     * Move constructor.\n     */\n    ControllerBase(ControllerBase&&) = default;\n\n    /**\n     * Move assignment operator.\n     */\n    ControllerBase& operator=(ControllerBase&&) = default;\n\n    virtual ~ControllerBase() = default;\n\n    /**\n     * Returns the current references.\n     *\n     * See the State class in the derived class for what each element\n     * corresponds to.\n     */\n    const Eigen::Matrix<double, States, 1>& GetReferences() const {\n        return m_r;\n    }\n\n    /**\n     * Returns the control inputs.\n     *\n     * See the Input class in the derived class for what each element\n     * corresponds to.\n     */\n    const Eigen::Matrix<double, Inputs, 1>& GetInputs() const { return m_u; }\n\n    /**\n     * Returns the next output of the controller.\n     *\n     * @param x The current state x.\n     */\n    virtual Eigen::Matrix<double, Inputs, 1> Calculate(\n        const Eigen::Matrix<double, States, 1>& x) = 0;\n\n    /**\n     * Returns the next output of the controller.\n     *\n     * @param x The current state x.\n     * @param r The next reference r.\n     */\n    Eigen::Matrix<double, Inputs, 1> Calculate(\n        const Eigen::Matrix<double, States, 1>& x,\n        const Eigen::Matrix<double, States, 1>& r) {\n        m_nextR = r;\n        Eigen::Matrix<double, Inputs, 1> u = Calculate(x);\n        m_r = m_nextR;\n        return u;\n    }\n\nprotected:\n    /**\n     * Controller reference for current timestep.\n     */\n    Eigen::Matrix<double, States, 1> m_r =\n        Eigen::Matrix<double, States, 1>::Zero();\n\n    /**\n     * Controller reference for next timestep.\n     */\n    Eigen::Matrix<double, States, 1> m_nextR =\n        Eigen::Matrix<double, States, 1>::Zero();\n\n    /**\n     * Controller output.\n     */\n    Eigen::Matrix<double, Inputs, 1> m_u =\n        Eigen::Matrix<double, Inputs, 1>::Zero();\n};\n\n}  // namespace frc3512\n", "meta": {"hexsha": "59c541f92c2d3aa101bd40168408a95d4c13365c", "size": 2463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/ControllerBase.hpp", "max_stars_repo_name": "frc3512/Robot-2020", "max_stars_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T04:13:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:13:39.000Z", "max_issues_repo_path": "src/main/include/controllers/ControllerBase.hpp", "max_issues_repo_name": "frc3512/Robot-2020", "max_issues_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T03:05:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T02:14:38.000Z", "max_forks_repo_path": "src/main/include/controllers/ControllerBase.hpp", "max_forks_repo_name": "frc3512/Robot-2020", "max_forks_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:24:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:10:01.000Z", "avg_line_length": 25.1326530612, "max_line_length": 80, "alphanum_fraction": 0.6134794965, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.32766828768970435, "lm_q1q2_score": 0.16511407205354}}
{"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#include \"bark/world/map/map_interface.hpp\"\n#include <math.h>\n#include <boost/tokenizer.hpp>\n#include <memory>\n#include <random>\n\nnamespace bark {\nnamespace world {\nnamespace map {\n\nusing LineSegment = boost::geometry::model::segment<Point2d>;\nbool MapInterface::interface_from_opendrive(\n    const OpenDriveMapPtr& open_drive_map) {\n  open_drive_map_ = open_drive_map;\n\n  RoadgraphPtr roadgraph(new Roadgraph());\n  roadgraph->Generate(open_drive_map);\n  roadgraph_ = roadgraph;\n\n  rtree_lane_.clear();\n  for (auto& road : open_drive_map_->GetRoads()) {\n    for (auto& lane_section : road.second->GetLaneSections()) {\n      for (auto& lane : lane_section->GetLanes()) {\n        if (lane.second->GetLanePosition() == 0) continue;\n        LineSegment lane_segment(*lane.second->GetLine().begin(),\n                                 *(lane.second->GetLine().end() - 1));\n        rtree_lane_.insert(std::make_pair(lane_segment, lane.second));\n      }\n    }\n  }\n\n  bounding_box_ = open_drive_map_->BoundingBox();\n  return true;\n}\n\nbool MapInterface::interface_from_csvtable(\n  const std::string csvfile, double x_offset, double y_offset) {\n  // Read map data\n  std::ifstream file(csvfile);\n  if (!file.is_open()) {\n    LOG(ERROR) << \"Error reading mapfile \" << csvfile;\n    return false;\n  }\n  std::vector<double> cx, cy, lx, ly, rx, ry;\n  typedef boost::tokenizer<boost::escaped_list_separator<char>> Tokenizer;\n  std::string line;\n  std::vector<std::string> row;\n  bool toprow = true;\n\n  while (getline(file, line)) {\n    if (!toprow) {\n      Tokenizer tok(line);\n      row.assign(tok.begin(), tok.end());\n      cx.push_back(stod(row[1]) - x_offset);\n      cy.push_back(stod(row[2]) - y_offset);\n      rx.push_back(stod(row[3]) - x_offset);\n      ry.push_back(stod(row[4]) - y_offset);\n      lx.push_back(stod(row[5]) - x_offset);\n      ly.push_back(stod(row[6]) - y_offset);\n    } else {\n      toprow = false;\n    }\n  }\n  const int nr_points = cx.size();\n\n  // Generate centerline\n  using bark::geometry::Line;\n  using bark::geometry::Point2d;\n  Line centerline;\n  for (int idx = 0; idx < nr_points; ++idx) {\n    centerline.AddPoint(Point2d(cx[idx], cy[idx]));\n  }\n\n  // Generate road polygon\n  using bark::geometry::Polygon;\n  Polygon lanepoly;\n  for (int idx = 0; idx < nr_points; ++idx) {\n    lanepoly.AddPoint(Point2d(lx[idx], ly[idx]));\n  }\n  for (int idx = nr_points-1; idx >= 0; --idx) {  // reverse\n    lanepoly.AddPoint(Point2d(rx[idx], ry[idx]));\n  }\n  // lanepoly.correct(); //@todo do we need this?\n\n  // Generate Lane\n  double speed = 30 / 3.6;\n  int laneid = 0;\n  XodrLanePtr xodrlane = std::make_shared<XodrLane>();\n  xodrlane->SetId(laneid);\n  xodrlane->SetLanePosition(-1);  //@todo how to assign? Type: XodrLanePosition\n  // xodrlane->link_; //not needed\n  xodrlane->SetLine(centerline);\n  // xodrlane->junction_id_ //not needed\n  xodrlane->SetIsInJunction(false);\n  xodrlane->SetLaneType(XodrLaneType::DRIVING);\n  xodrlane->SetDrivingDirection(XodrDrivingDirection::FORWARD);\n  // xodrlane->road_mark_ // @todo do we need this to be assigned= Type:\n  // XodrRoadMark\n  xodrlane->SetSpeed(speed);\n  // xodrlane->lane_count//@todo how to assign?\n\n  LanePtr lane = std::make_shared<Lane>(xodrlane);\n  // lane->left_lane_ = nullptr; //@todo do we have to assign?\n  // lane->right_lane_ = nullptr; //@todo do we have to assign?\n  // lane->next_lane_ = nullptr; //@todo do we have to assign?\n  lane->center_line_ = centerline;\n  lane->polygon_ = lanepoly;\n  // Boundary left_boundary_; //@todo do we need this?\n  // Boundary right_boundary_; //@todo do we need this?\n\n  // Generate LaneCorridorPtr!\n  LaneCorridorPtr lanecorridor = std::make_shared<LaneCorridor>();\n  lanecorridor->lanes_[0] = lane;  // s_end: @todo what is the key? is zero ok??\n  lanecorridor->center_line_ = centerline;\n  lanecorridor->fine_center_line_ = centerline;\n  lanecorridor->merged_polygon_ = lanepoly;\n  // Line left_boundary_; //@todo do we need this?\n  // Line right_boundary_; //@todo do we need this?\n\n  // Generate PlanView\n  // @todo if we need the planview make a constructor from line!\n  PlanViewPtr xodrplanview = std::make_shared<PlanView>();\n\n  // Generate XodrLaneSection\n  double s = 0;\n  XodrLaneSectionPtr xodrlanesection = std::make_shared<XodrLaneSection>(s);\n  xodrlanesection->AddLane(lane);\n\n  // Generate XodrRoad\n  const int roadid = 0;\n  XodrRoadPtr xodrroad = std::make_shared<XodrRoad>();\n  xodrroad->SetId(roadid);\n  xodrroad->SetName(\"dummy_name\");\n  // xodrroad->SetLink(); //not needed\n  xodrroad->SetPlanView(xodrplanview);\n  xodrroad->AddLaneSection({xodrlanesection});\n\n  // Generate Road\n  RoadPtr road = std::make_shared<Road>(xodrroad);\n  road->next_road_ = nullptr;\n  road->lanes_[laneid] = lane;\n\n  // Generate road corridor\n  RoadCorridorPtr rc = std::make_shared<RoadCorridor>();\n  rc->roads_[roadid] = road;\n  rc->road_polygon_ = lanepoly;\n  rc->unique_lane_corridors_ = {lanecorridor};\n  rc->road_ids_ = {roadid};\n  rc->driving_direction_ = XodrDrivingDirection::FORWARD;\n  rc->lane_corridors_[laneid] = lanecorridor;\n\n  // Generate roadgraph\n  RoadgraphPtr roadgraph(new Roadgraph());\n  roadgraph->AddLane(roadid, xodrlane);\n  bark::world::map::PolygonPtr lanepolyptr =\n      std::make_shared<Polygon>(lanepoly);\n  bool lanepoly_set = roadgraph->SetPolygonForVertexFromId(laneid, lanepolyptr);\n  if (!lanepoly_set) {\n    return false;\n  }\n\n  // Generate lane rtree\n  rtree_lane_.clear();\n  using LineSegment = boost::geometry::model::segment<Point2d>;\n  LineSegment lane_segment(\n      *centerline.begin(),\n      *(centerline.end() - 1));  //@todo ERROR! should be the boundary here, but\n                                 // which? I did not model the planview\n  rtree_lane_.insert(std::make_pair(lane_segment, lane));\n\n  // Generate bounding box\n  boost::geometry::model::box<Point2d> box;\n  boost::geometry::envelope(lanepoly.obj_, box);\n  boost::geometry::correct(box);\n  bounding_box_ = std::make_pair(\n      Point2d(boost::geometry::get<boost::geometry::min_corner, 0>(box),\n              bg::get<bg::min_corner, 1>(box)),\n      Point2d(boost::geometry::get<boost::geometry::max_corner, 0>(box),\n              bg::get<bg::max_corner, 1>(box)));\n\n  // Generate (dummy) Open Drive Map\n  OpenDriveMapPtr open_drive_map = std::make_shared<OpenDriveMap>();\n  open_drive_map->AddRoad(xodrroad);\n\n  // Generate map interface\n  open_drive_map_ = open_drive_map;\n  road_from_csvtable_ = true;\n  roadgraph_ = roadgraph;\n  // rtree_lane_ assigned above\n\n  // TODO THIS IS A HACK!!!\n  std::vector<XodrRoadId> road_ids = {static_cast<XodrRoadId>(roadid)};\n  XodrDrivingDirection driving_direction = XodrDrivingDirection::FORWARD;\n  std::size_t road_corridor_hash = RoadCorridor::GetHash(driving_direction, road_ids);\n\n  road_corridors_[road_corridor_hash] = rc;\n  // bounding_box_ assigned above\n  return true;\n}\n\nbool MapInterface::FindNearestXodrLanes(const Point2d& point,\n                                        const unsigned& num_lanes,\n                                        std::vector<XodrLanePtr>& lanes,\n                                        bool type_driving_only) const {\n  std::vector<rtree_lane_value> results_n;\n  if (type_driving_only) {\n    rtree_lane_.query(\n        boost::geometry::index::nearest(point, num_lanes) &&\n            boost::geometry::index::satisfies(IsLaneType),  // NOLINT\n        std::back_inserter(results_n));\n  } else {\n    rtree_lane_.query(boost::geometry::index::nearest(point, num_lanes),\n                      std::back_inserter(results_n));\n  }\n  if (results_n.empty()) {\n    return false;\n  }\n  lanes.clear();\n  for (auto& result : results_n) {\n    lanes.push_back(result.second);\n  }\n  return true;\n}\n\nXodrLanePtr MapInterface::FindXodrLane(const Point2d& point) const {\n  XodrLanePtr lane;\n  std::vector<XodrLanePtr> nearest_lanes;\n  if (!FindNearestXodrLanes(point, num_points_nearest_lane_, nearest_lanes,\n                            false)) {\n    return nullptr;\n  }\n  for (auto& close_lane : nearest_lanes) {\n    if (IsInXodrLane(point, close_lane->GetId())) {\n      lane = close_lane;\n      return lane;\n    }\n  }\n  return nullptr;\n}\n\nbool MapInterface::IsInXodrLane(const Point2d& point, XodrLaneId id) const {\n  std::pair<vertex_t, bool> v = roadgraph_->GetVertexByLaneId(id);\n  if (v.second) {\n    auto polygon = roadgraph_->GetLaneGraph()[v.first].polygon;\n    if (!polygon) {\n      // found vertex has no polygon\n      return false;\n    } else {\n      // found vertex has a polygon\n      bool point_in_polygon = bark::geometry::Collide(*polygon, point);\n      if (point_in_polygon) {\n        return true;\n      } else {\n        return false;\n      }\n    }\n  } else {\n    // no vertex found\n    return false;\n  }\n}\n\nstd::vector<PathBoundaries> MapInterface::ComputeAllPathBoundaries(\n    const std::vector<XodrLaneId>& lane_ids) const {\n  std::vector<XodrLaneEdgeType> LANE_SUCCESSOR_EDGEs = {\n      XodrLaneEdgeType::LANE_SUCCESSOR_EDGE};\n  std::vector<std::vector<XodrLaneId>> all_paths =\n      roadgraph_->FindAllPathsInSubgraph(LANE_SUCCESSOR_EDGEs, lane_ids);\n\n  std::vector<PathBoundaries> all_path_boundaries;\n  for (auto const& path : all_paths) {\n    std::vector<std::pair<XodrLanePtr, XodrLanePtr>> path_boundaries;\n    for (auto const& path_segment : path) {\n      std::pair<XodrLanePtr, XodrLanePtr> lane_boundaries =\n          roadgraph_->ComputeXodrLaneBoundaries(path_segment);\n      path_boundaries.push_back(lane_boundaries);\n    }\n    all_path_boundaries.push_back(path_boundaries);\n  }\n  return all_path_boundaries;\n}\n\nstd::pair<XodrLanePtr, bool> MapInterface::GetInnerNeighbor(\n    const XodrLaneId lane_id) const {\n  std::pair<XodrLaneId, bool> inner_neighbor =\n      roadgraph_->GetInnerNeighbor(lane_id);\n  if (inner_neighbor.second)\n    return std::make_pair(roadgraph_->GetLanePtr(inner_neighbor.first), true);\n  return std::make_pair(nullptr, false);\n}\n\nstd::pair<XodrLanePtr, bool> MapInterface::GetOuterNeighbor(\n    const XodrLaneId lane_id) const {\n  std::pair<XodrLaneId, bool> outer_neighbor =\n      roadgraph_->GetOuterNeighbor(lane_id);\n  if (outer_neighbor.second)\n    return std::make_pair(roadgraph_->GetLanePtr(outer_neighbor.first), true);\n  return std::make_pair(nullptr, false);\n}\n\nstd::vector<XodrLaneId> MapInterface::GetSuccessorLanes(\n    const XodrLaneId lane_id) const {\n  return roadgraph_->GetSuccessorLanes(lane_id);\n}\n\nvoid MapInterface::CalculateLaneCorridors(RoadCorridorPtr& road_corridor,\n                                          const RoadPtr& road) {\n  Lanes lanes = road->GetLanes();\n\n  for (auto& lane : lanes) {\n    // only add lane if it has not been added already\n    if (road_corridor->GetLaneCorridor(lane.first) ||\n        lane.second->GetLanePosition() == 0)\n      continue;\n    // only add if type is drivable\n    if (lane.second->GetLaneType() != XodrLaneType::DRIVING) continue;\n\n    LaneCorridorPtr lane_corridor = std::make_shared<LaneCorridor>();\n    LanePtr current_lane = lane.second;\n    double total_s = current_lane->GetCenterLine().Length();\n    lane_corridor->SetCenterLine(current_lane->GetCenterLine());\n    lane_corridor->SetFineCenterLine(current_lane->GetCenterLine());\n    // lane_corridor->SetMergedPolygon(current_lane->GetPolygon());\n    lane_corridor->SetLeftBoundary(current_lane->GetLeftBoundary().line_);\n    lane_corridor->SetRightBoundary(current_lane->GetRightBoundary().line_);\n    lane_corridor->SetLane(total_s, current_lane);\n\n    // add initial lane\n    road_corridor->SetLaneCorridor(current_lane->GetId(), lane_corridor);\n    // std::cout << \"Current Poly\" << std::endl;\n    // std::cout << current_lane->GetPolygon().ToArray() << std::endl;\n    LanePtr next_lane = current_lane;\n    for (;;) {\n      next_lane = next_lane->GetNextLane();\n      if (next_lane == nullptr) break;\n      Line new_center = bark::geometry::ConcatenateLinestring(\n          lane_corridor->GetCenterLine(), next_lane->GetCenterLine());\n      lane_corridor->SetCenterLine(new_center);\n      lane_corridor->SetFineCenterLine(new_center);\n\n      Line new_left = bark::geometry::ConcatenateLinestring(\n          lane_corridor->GetLeftBoundary(), next_lane->GetLeftBoundary().line_);\n      lane_corridor->SetLeftBoundary(new_left);\n\n      Line new_right = bark::geometry::ConcatenateLinestring(\n          lane_corridor->GetRightBoundary(),\n          next_lane->GetRightBoundary().line_);\n      lane_corridor->SetRightBoundary(new_right);\n      // std::cout << \"New Poly\" << std::endl;\n      // std::cout << next_lane->GetPolygon().ToArray() << std::endl;\n      // lane_corridor->GetMergedPolygon().ConcatenatePolygons(\n      //   next_lane->GetPolygon());\n\n      total_s = lane_corridor->GetCenterLine().Length();\n      lane_corridor->SetLane(total_s, next_lane);\n      // all following lanes should point to the same LaneCorridor\n      road_corridor->SetLaneCorridor(next_lane->GetId(), lane_corridor);\n    }\n\n    // \\note \\kessler: setting max_simplification_dist_ too small can yield\n    // self-intersecting road polygons. why? in curves on the inner radius due\n    // to sampling inaccuracy the boundaries of two segments can overlap. The\n    // code below just copies each point to the lane polygon without checking\n    // this.\n\n    Line simplf_center =\n        Simplify(lane_corridor->GetCenterLine(), max_simplification_dist_);\n    lane_corridor->SetCenterLine(simplf_center);\n\n    Line simplf_fine_center =\n        Simplify(lane_corridor->GetFineCenterLine(), 0.001);\n    lane_corridor->SetFineCenterLine(simplf_fine_center);\n\n    Line simplf_right =\n        Simplify(lane_corridor->GetRightBoundary(), max_simplification_dist_);\n    lane_corridor->SetRightBoundary(simplf_right);\n\n    Line simplf_left =\n        Simplify(lane_corridor->GetLeftBoundary(), max_simplification_dist_);\n    lane_corridor->SetLeftBoundary(simplf_left);\n\n    // TODO hier ist der self intersection bug: magic number 0.5 durch sampling\n    // distance ersetzen!!!\n\n    // merged polygons\n    PolygonPtr polygon = std::make_shared<bark::geometry::Polygon>();\n\n    // \\todo (\\kessler): before adding a point, check if this produces a\n    // self-intersection.\n    for (auto const& p : lane_corridor->GetLeftBoundary()) {\n      polygon->AddPoint(p);\n    }\n    auto reversed_outer = lane_corridor->GetRightBoundary();\n    reversed_outer.Reverse();\n    for (auto const& p : reversed_outer) {\n      polygon->AddPoint(p);\n    }\n    // Polygons need to be closed!\n    polygon->AddPoint(*(lane_corridor->GetLeftBoundary().begin()));\n    boost::geometry::correct(polygon->obj_);\n\n    if (!polygon->Valid()) {\n      LOG(ERROR) << \"Producing a non-valid lane corridor for lane id = \"\n                 << lane.first;\n    }\n\n    lane_corridor->SetMergedPolygon(*polygon);\n  }\n}\n\nvoid MapInterface::CalculateLaneCorridors(RoadCorridorPtr& road_corridor,\n                                          const XodrRoadId& road_id) {\n  RoadPtr first_road = road_corridor->GetRoads()[road_id];\n  CalculateLaneCorridors(road_corridor, first_road);\n  for (auto& road : road_corridor->GetRoads()) {\n    CalculateLaneCorridors(road_corridor, road.second);\n  }\n}\n\nLanePtr MapInterface::GenerateRoadCorridorLane(const XodrLanePtr& xodr_lane) {\n  LanePtr lane = std::make_shared<Lane>(xodr_lane);\n  // polygons\n  if (xodr_lane->GetLanePosition() != 0) {\n    std::pair<PolygonPtr, bool> polygon_success =\n        roadgraph_->ComputeXodrLanePolygon(xodr_lane->GetId());\n    // Cannot compute polygon for planview!!\n    if (polygon_success.second) lane->SetPolygon(*polygon_success.first);\n  }\n  return lane;\n}\n\nRoadPtr MapInterface::GenerateRoadCorridorRoad(const XodrRoadId& road_id) {\n  XodrRoadPtr xodr_road = open_drive_map_->GetRoad(road_id);\n  RoadPtr road = std::make_shared<Road>(xodr_road);\n  Lanes lanes;\n  for (auto& lane_section : xodr_road->GetLaneSections()) {\n    for (auto& lane : lane_section->GetLanes()) {\n      // TODO(@hart): only add driving lanes\n      // if (lane.second->GetLaneType() == XodrLaneType::DRIVING)\n      lanes[lane.first] = GenerateRoadCorridorLane(lane.second);\n    }\n  }\n  road->SetLanes(lanes);\n  return road;\n}\n\nvoid MapInterface::GenerateRoadCorridor(\n    const std::vector<XodrRoadId>& road_ids,\n    const XodrDrivingDirection& driving_direction) {\n  std::size_t road_corridor_hash =\n      RoadCorridor::GetHash(driving_direction, road_ids);\n\n  // only compute if it has not been computed yet\n  if (road_corridors_.count(road_corridor_hash) > 0) return;\n\n  Roads roads;\n  for (auto& road_id : road_ids)\n    roads[road_id] = GenerateRoadCorridorRoad(road_id);\n\n  // links can only be set once all roads have been calculated\n  int count = 0;\n  for (auto& road_id : road_ids) {\n    // road successor\n    RoadPtr next_road;\n    if (count < road_ids.size() - 1) next_road = roads[road_ids[++count]];\n    roads[road_id]->SetNextRoad(next_road);\n    for (auto& lane : roads[road_id]->GetLanes()) {\n      // lane successor\n      // auto local_driving_direction = driving_direction;\n      // if (lane.second->GetDrivingDirection() != driving_direction)\n      //   local_driving_direction = lane.second->GetDrivingDirection();\n\n      if (count + 1 <= road_ids.size()) {\n        std::vector<XodrRoadId> vec;\n        std::copy(road_ids.begin() + count, road_ids.begin() + count + 1,\n                  std::back_inserter(vec));\n\n        // for (auto v: vec)\n        //   std::cout << v << std::endl;\n\n        std::pair<XodrLaneId, bool> next_lane =\n            roadgraph_->GetNextLane(vec, lane.first);\n        if (next_lane.second && next_road)\n          lane.second->SetNextLane(next_road->GetLane(next_lane.first));\n      }\n\n      // left and right lanes\n      LanePtr left_lane, right_lane;\n      std::pair<XodrLaneId, bool> left_lane_id = roadgraph_->GetLeftLane(\n          lane.first, lane.second->GetDrivingDirection());\n      if (left_lane_id.second) {\n        left_lane = roads[road_id]->GetLane(left_lane_id.first);\n        lane.second->SetLeftLane(left_lane);\n      }\n\n      std::pair<XodrLaneId, bool> right_lane_id = roadgraph_->GetRightLane(\n          lane.first, lane.second->GetDrivingDirection());\n      if (right_lane_id.second) {\n        right_lane = roads[road_id]->GetLane(right_lane_id.first);\n        lane.second->SetRightLane(right_lane);\n      }\n\n      // set boundaries for lane\n      std::pair<XodrLaneId, bool> left_boundary_lane_id =\n          roadgraph_->GetLeftBoundary(lane.first,\n                                      lane.second->GetDrivingDirection());\n      if (left_boundary_lane_id.second) {\n        LanePtr left_lane_boundary =\n            roads[road_id]->GetLane(left_boundary_lane_id.first);\n        Boundary left_bound;\n        left_bound.SetLine(left_lane_boundary->GetLine());\n        left_bound.SetType(left_lane_boundary->GetRoad_mark());\n        lane.second->SetLeftBoundary(left_bound);\n      }\n      std::pair<XodrLaneId, bool> right_boundary_lane_id =\n          roadgraph_->GetRightBoundary(lane.first,\n                                       lane.second->GetDrivingDirection());\n      if (right_boundary_lane_id.second) {\n        LanePtr right_lane_boundary =\n            roads[road_id]->GetLane(right_boundary_lane_id.first);\n        Boundary right_bound;\n        right_bound.SetLine(right_lane_boundary->GetLine());\n        right_bound.SetType(right_lane_boundary->GetRoad_mark());\n        lane.second->SetRightBoundary(right_bound);\n      }\n\n      // compute center line\n      if (left_boundary_lane_id.second && right_boundary_lane_id.second)\n        lane.second->SetCenterLine(\n            ComputeCenterLine(lane.second->GetLeftBoundary().line_,\n                              lane.second->GetRightBoundary().line_));\n    }\n  }\n\n  if (roads.size() == 0) return;\n  RoadCorridorPtr road_corridor = std::make_shared<RoadCorridor>();\n  road_corridor->SetRoads(roads);\n  CalculateLaneCorridors(road_corridor, road_ids[0]);\n  road_corridor->ComputeRoadPolygon();\n  if (full_junction_area_) {\n    for (auto& junction : road_corridor->GetJunctionIds()) {\n      const Polygon poly = ComputeJunctionArea(junction);\n      road_corridor->AddPolygonToRoadCorridor(std::move(poly));\n    }\n  }\n  road_corridor->SetRoadIds(road_ids);\n  road_corridor->SetDrivingDirection(driving_direction);\n  road_corridors_[road_corridor_hash] = road_corridor;\n}\n\nRoadCorridorPtr MapInterface::GenerateRoadCorridor(\n    const bark::geometry::Point2d& start_point,\n    const bark::geometry::Polygon& goal_region) {\n  std::vector<XodrLanePtr> lanes;\n  XodrLaneId goal_lane_id;\n  bool nearest_start_lane_found = FindNearestXodrLanes(start_point, 1, lanes);\n  bool nearest_goal_lane_found = XodrLaneIdAtPolygon(goal_region, goal_lane_id);\n  if (!nearest_start_lane_found || !nearest_goal_lane_found) {\n    LOG(INFO) << \"Could not generate road corridor based on geometric start \"\n                 \"and goal definitions.\";  // NOLINT\n    return nullptr;\n  }\n\n  const auto start_lane_id = lanes.at(0)->GetId();\n  const XodrDrivingDirection driving_direction =\n      lanes.at(0)->GetDrivingDirection();\n\n  std::vector<XodrRoadId> road_ids;\n  std::vector<XodrLaneId> lane_ids =\n      roadgraph_->FindDrivableLanePath(start_lane_id, goal_lane_id);\n  for (auto lid : lane_ids) {\n    std::pair<vertex_t, bool> v_des = roadgraph_->GetVertexByLaneId(lid);\n    XodrLaneVertex lv = roadgraph_->GetVertex(v_des.first);\n    road_ids.push_back(lv.road_id);\n    // std::cout << \"lane_id: \" << lid << \", road_id: \";\n    // std::cout << lv.road_id << std::endl;\n  }\n  GenerateRoadCorridor(road_ids, driving_direction);\n  return GetRoadCorridor(road_ids, driving_direction);\n}\n\nRoadCorridorPtr MapInterface::GenerateRoadCorridor(\n    const XodrRoadId& start_road_id, const XodrRoadId& end_road_id) {\n  std::vector<XodrRoadId> road_ids =\n      roadgraph_->FindRoadPath(start_road_id, end_road_id);\n\n  std::pair<std::vector<XodrDrivingDirection>, bool> directions =\n      roadgraph_->GetDrivingDirectionsForRoadId(start_road_id);\n  if (!directions.second) {\n    LOG(ERROR) << \"No lanes for start road id \" << start_road_id << \" found.\";\n    return nullptr;\n  }\n  XodrDrivingDirection driving_direction = directions.first.at(0);\n  GenerateRoadCorridor(road_ids, driving_direction);\n  return GetRoadCorridor(road_ids, driving_direction);\n}\n\nbool MapInterface::XodrLaneIdAtPolygon(const bark::geometry::Polygon& polygon,\n                                       XodrLaneId& found_lane_id) const {\n  bark::geometry::Point2d goal_center(polygon.center_(0), polygon.center_(1));\n  std::vector<opendrive::XodrLanePtr> nearest_lanes;\n  if (FindNearestXodrLanes(goal_center, 1, nearest_lanes)) {\n    found_lane_id = nearest_lanes[0]->GetId();\n    return true;\n  }\n  LOG(INFO) << \"No matching lane for goal definition found\";\n  return false;\n}\n\nRoadPtr MapInterface::GetNextRoad(\n    const XodrRoadId& current_road_id, const Roads& roads,\n    const std::vector<XodrRoadId>& road_ids) const {\n  auto it = std::find(road_ids.begin(), road_ids.end(), current_road_id);\n  if (road_ids.back() == current_road_id) return nullptr;\n  return roads.at(*std::next(it, 1));\n}\n\nbark::geometry::Polygon MapInterface::ComputeJunctionArea(\n    uint32_t junction_id) {\n  PolygonPtr poly = roadgraph_->ComputeJunctionArea(junction_id);\n  return *poly.get();\n}\n\n}  // namespace map\n}  // namespace world\n}  // namespace bark\n", "meta": {"hexsha": "8c2c2b9aed607cb534462b108a031f3e80c46037", "size": 23477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bark/world/map/map_interface.cpp", "max_stars_repo_name": "xmyqsh/bark", "max_stars_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174.0, "max_stars_repo_stars_event_min_datetime": "2019-04-03T11:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T09:14:38.000Z", "max_issues_repo_path": "bark/world/map/map_interface.cpp", "max_issues_repo_name": "xmyqsh/bark", "max_issues_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 192.0, "max_issues_repo_issues_event_min_datetime": "2019-04-05T09:41:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T14:14:28.000Z", "max_forks_repo_path": "bark/world/map/map_interface.cpp", "max_forks_repo_name": "xmyqsh/bark", "max_forks_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2019-04-05T13:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T07:03:41.000Z", "avg_line_length": 36.9716535433, "max_line_length": 86, "alphanum_fraction": 0.6878221238, "num_tokens": 6290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.16511407205354}}
{"text": "//   Copyright 2015 Patrick Putnam\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 CLOTHO_SIM_ENGINE_MT_HPP_\n#define CLOTHO_SIM_ENGINE_MT_HPP_\n\n#ifdef DEBUG_MODE\n#define DEBUGGING 0\n#endif  // DEBUG_MODE\n\n#include \"qtlsim_logger.hpp\"\n\n#include <boost/property_tree/ptree.hpp>\n\n#include \"clotho/genetics/population_growth_toolkit.hpp\"\n\n#include \"clotho/data_spaces/allele_space/allele_space_vector.hpp\"\n#include \"clotho/data_spaces/allele_space/allele_generator_vector.hpp\"\n\n#include \"clotho/data_spaces/phenotype_evaluator/trait_space_vector.hpp\"\n#include \"clotho/data_spaces/phenotype_evaluator/trait_space_generator.hpp\"\n\n#include \"clotho/data_spaces/phenotype_evaluator/trait_accumulator.hpp\"\n#include \"clotho/data_spaces/free_space/free_space_mts.hpp\"\n\n#ifdef USE_BATCH_JOBS\n#include \"clotho/data_spaces/crossover/batch_crossover_mt.hpp\"\n#define CROSSOVER_TYPE clotho::genetics::BatchCrossoverMT\n\n#include \"clotho/data_spaces/phenotype_evaluator/batch_phenotype_mts.hpp\"\n#define PHENOTYPE_TYPE clotho::genetics::BatchPhenotypeMT\n\n#else\n#include \"clotho/data_spaces/crossover/crossover_mt.hpp\"\n#define CROSSOVER_TYPE clotho::genetics::CrossoverMT\n\n#include \"clotho/data_spaces/phenotype_evaluator/phenotype_mt.hpp\"\n#define PHENOTYPE_TYPE clotho::genetics::PhenotypeMT\n#endif  // USE_BATCH_JOBS\n\n#include \"clotho/data_spaces/population_space/population_spaces.hpp\"\n#include \"clotho/data_spaces/selection/selection.hpp\"\n\n#include \"clotho/data_spaces/mutation/mutation_generators.hpp\"\n#include \"clotho/data_spaces/mutation/mutation_allocator.hpp\"\n\n#include \"clotho/data_spaces/fitness/general_fitness.hpp\"\n\n#include \"clotho/utility/state_object.hpp\"\n\n#include \"clotho/data_spaces/task/thread_pool.hpp\"\n\ntemplate < class RNG, class RealType = double, class BlockType = unsigned long long, class SizeType = unsigned int >\nclass EngineMT2 {\npublic:\n    typedef EngineMT2< RNG >             self_type;\n\n    typedef RealType                    position_type;\n    typedef RealType                    weight_type;\n    typedef weight_type *               phenotype_type;\n    typedef BlockType                   block_type;\n\n    typedef RNG                         random_engine_type;\n\n    typedef SizeType                    size_type;\n\n    typedef clotho::genetics::thread_pool< RNG >                                                    thread_pool_type;\n    typedef clotho::genetics::AlleleSpace< position_type, size_type >                               allele_type;\n//    typedef clotho::genetics::association_matrix< block_type, __ALIGNMENT_TYPE__ >                  sequence_space_type;\n//\n    typedef clotho::genetics::population_space< block_type, weight_type >                           sequence_space_type;\n    typedef clotho::genetics::trait_space_vector< weight_type >                                     trait_space_type;\n    typedef clotho::genetics::FreeSpaceAnalyzerMT< sequence_space_type, size_type >                 free_space_type;\n\n    typedef clotho::genetics::mutation_allocator< random_engine_type, size_type >                 mutation_alloc_type;\n\n    typedef clotho::genetics::MutationGenerator2< random_engine_type, sequence_space_type >       mutation_type;\n\n    typedef clotho::genetics::AlleleGenerator< random_engine_type, allele_type >                  allele_generator_type;\n    typedef clotho::genetics::TraitSpaceGenerator< random_engine_type, trait_space_type >         trait_generator_type;\n\n    typedef clotho::genetics::GeneralFitness                                                      fitness_type;\n    typedef clotho::genetics::SelectionGenerator< random_engine_type, clotho::genetics::fitness_selection< fitness_type > >          selection_type;\n    typedef CROSSOVER_TYPE< random_engine_type, sequence_space_type, allele_type >                crossover_type;\n\n    typedef PHENOTYPE_TYPE< sequence_space_type, trait_space_type >                               phenotype_eval_type;\n\n    typedef std::shared_ptr< ipopulation_growth_generator >                                         population_growth_generator_type;\n    typedef std::shared_ptr< ipopulation_growth >                                                   population_growth_type;\n\n    friend struct clotho::utility::state_getter< self_type >;\n\n    EngineMT2( random_engine_type * rng, boost::property_tree::ptree & config ) :\n        m_rand( rng )\n        , m_parent( &m_pop0 )\n        , m_child( &m_pop1 )\n        , m_trait_space( config )\n        , m_fixed_traits( config )\n        , m_thread_pool( rng, config )\n        , m_free_space( )\n        , select_gen( rng, config )\n        , mutate_gen( rng, config )\n        , cross_gen( rng, config )\n        , m_fit( config )\n        , m_generation( 0 )\n        , m_pop_growth()\n        , m_mut_alloc( rng, config )\n        , trait_gen( rng, config )\n        , allele_gen( rng, config )\n    {\n        population_growth_generator_type tmp  = population_growth_toolkit::getInstance()->get_tool( config );\n        if( tmp ) {\n            m_pop_growth = tmp->generate();\n            if( m_pop_growth ) {\n                m_pop_growth->log( std::cerr );\n                std::cerr << std::endl;\n            }\n        } else {\n            population_growth_toolkit::getInstance()->tool_configurations( config );\n        }\n\n//        m_pop0.getSequenceSpace().clear();\n//        m_pop1.getSequenceSpace().clear();\n\n//        size_t acount = m_pop0.getAlleleSpace().allele_count();\n//        m_pop0.getAlleleSpace().grow(acount, m_pheno.trait_count());\n//        m_pop1.getAlleleSpace().grow(acount, m_pheno.trait_count());\n\n        init(0);\n    }\n\n    size_t getGeneration() const {\n        return m_generation;\n    }\n\n    void init( size_t aN ) {\n//        size_t pN = m_parent->individual_count();\n        size_t pN = 0;\n        if( m_pop_growth ) {\n            pN = m_pop_growth->operator()( pN, m_generation );\n        }\n\n        m_pop1.grow( pN, aN );\n\n#ifdef USE_ROW_VECTOR\n        m_pop1.getSequenceSpace().fill_empty();\n        m_pop1.getSequenceSpace().finalize();\n#endif // USE_ROW_VECTOR\n        ++m_generation;\n    }\n\n    void simulate( ) {\n        std::swap( m_child, m_parent );     // use the current child population as the parent population for the next round\n\n        // at the start of each simulate round, m_fit has already been updated from the previous\n        // round with the fitness of the \"then child/now parent\" popualtions fitness\n        //\n        size_t pN = select_gen.individual_count();\n        if( m_pop_growth ) {\n            pN = m_pop_growth->operator()( pN, m_generation );\n        }\n\n        size_type pM = m_mut_alloc.allocate( 2 * pN );        // generate the number of new mutations\n        size_type free_count = updateFixedAlleles( m_parent );    // update the fixed alleles with those of parent population\n        size_t all_size = child_max_alleles( m_allele_space.size(), free_count, pM );   // rescale allele space for child population given free space from parent population and new allele count (pM)\n\n#ifdef DEBUGGING \n        BOOST_LOG_TRIVIAL( debug ) << \"Generation \" << m_generation << \": \" << pN << \" individuals; \" << pM << \" new alleles\";\n        BOOST_LOG_TRIVIAL( debug ) << \"Free space: \" << free_count << \"; alleles: \" << m_allele_space.size();\n        BOOST_LOG_TRIVIAL( debug ) << \"Rescaling child population to be: \" << pN << \" individuals x \" << all_size << \" alleles\";\n        std::cerr << \"Rescaling child population to be: \" << pN << \" individuals x \" << all_size << \" alleles\" << std::endl;\n#endif // DEBUGGING\n\n        m_child->grow( pN, all_size );                        // grow the child population accordingly\n\n        select_gen.update( m_fit, pN );\n\n        cross_gen( select_gen, m_parent, m_child, &m_allele_space, m_thread_pool );\n\n        generate_child_mutations( pM );\n\n        if( !m_allele_space.isAllNeutral() ) {\n            m_pheno( m_child, &m_trait_space, m_thread_pool );\n        } else {\n            m_pheno.constant_phenotype( m_child, &m_trait_space );\n        }\n        m_fit( m_pheno.begin(), m_pheno.end() );\n\n        m_child->finalize();\n\n        ++m_generation;\n    }\n\n    sequence_space_type * getChildPopulation() const {\n        return m_child;\n    }\n\n    sequence_space_type * getParentPopulation() const {\n        return m_parent;\n    }\n\n    allele_type * getAlleleSpace() {\n        return &m_allele_space;\n    }\n\n    virtual ~EngineMT2() { }\n\nprotected:\n\n    void generate_child_mutations( unsigned int N ) {\n        std::cerr << \"Child population size: \" << m_child->haploid_genome_count() << std::endl;\n        typename mutation_type::sequence_distribution_type seq_gen( 0, m_child->haploid_genome_count() - 1);\n\n        typename free_space_type::base_type::iterator it = m_free_space.free_begin(), end = m_free_space.free_end();\n        while( N && it != end ) {\n            typename free_space_type::size_type all_idx = *it++;\n            unsigned int seq_idx = seq_gen( *m_rand );\n\n            mutate_gen( m_child, seq_idx, all_idx );\n            allele_gen( m_allele_space, all_idx, m_generation );\n            trait_gen( m_trait_space, all_idx );\n            --N;\n        }\n\n        while( N ) {\n            typename free_space_type::size_type all_idx = m_allele_space.size();\n            unsigned int seq_idx = seq_gen( *m_rand );\n\n            assert( all_idx < m_child->getMaxAlleles() );\n\n            mutate_gen( m_child, seq_idx, all_idx );\n            allele_gen( m_allele_space, all_idx, m_generation );\n            trait_gen( m_trait_space, all_idx );\n            --N;\n        }\n    }\n\n/**\n * estimate the maximum number of alleles in the child\n *\n * N_parent - number of alleles in the parent population\n * F_parent - number of free alleles in the parent population\n * M_child  - number of new alleles to be added the child population\n */\n    size_t child_max_alleles( size_t N_parent, size_t F_parent, size_t M_child ) const {\n        BOOST_LOG_TRIVIAL(info) << \"Parent alleles: \" << N_parent << \"; Free: \" << F_parent << \"; New Alleles: \" << M_child;\n\n        if( F_parent >= M_child ) {\n            // if there are more free alleles in the parent generation\n            // than there are new alleles to be added to the child generation\n            // then do not adjust scale of the allele space\n            return N_parent;\n        } else {\n            return N_parent + (M_child - F_parent);\n        }\n    }\n\n    size_type updateFixedAlleles( sequence_space_type * ss ) {\n        m_free_space( ss, m_thread_pool );               // analyze the parent population sequence space\n\n        typedef typename free_space_type::iterator  fixed_iterator;\n        typedef typename trait_space_type::iterator trait_iterator;\n\n\n        std::cerr << \"Fixed count: \" << m_free_space.fixed_size() << std::endl;\n\n        fixed_iterator  fix_it = m_free_space.fixed_begin();\n        fixed_iterator  fix_end = m_free_space.fixed_end();\n\n        while( fix_it != fix_end ) {\n            size_type  fixed_index = *fix_it++;\n\n            ss->remove_fixed_allele( fixed_index );\n\n            m_fixed.append( m_allele_space, fixed_index );\n            \n            trait_iterator tstart = m_trait_space.begin( fixed_index ), tend = m_trait_space.end( fixed_index );\n            m_fixed_traits.append( tstart, tend );\n        }\n\n#ifdef DEBUGGING\n        typedef typename free_space_type::iterator free_iterator;\n        free_iterator fr_it = m_free_space.free_begin();\n        free_iterator fr_end = m_free_space.free_end();\n\n        unsigned int j = 0;\n        while( fr_it != fr_end ) {\n            size_type i = *fr_it++;\n\n            if( !ss->freeColumn( i ) ) {\n                assert(false);\n            }\n            ++j;\n        }\n\n        assert( j == m_free_space.free_size() );\n#endif // DEBUGGING\n\n        return m_free_space.free_size();\n    }\n\n    random_engine_type  * m_rand;\n\n    allele_type             m_allele_space, m_fixed;\n    sequence_space_type  m_pop0, m_pop1;\n    sequence_space_type  * m_parent, * m_child;\n\n    trait_space_type        m_trait_space, m_fixed_traits;\n\n    thread_pool_type        m_thread_pool;\n    phenotype_eval_type     m_pheno;\n    free_space_type         m_free_space;\n\n    selection_type          select_gen;\n    mutation_type           mutate_gen;\n    crossover_type          cross_gen;\n    fitness_type            m_fit;\n\n    size_t                  m_generation;\n\n    population_growth_type  m_pop_growth;\n    mutation_alloc_type     m_mut_alloc;\n\n    trait_generator_type    trait_gen;\n    allele_generator_type   allele_gen;\n};\n\nnamespace clotho {\nnamespace utility {\n\ntemplate < class RNG, class RealType, class BlockType, class SizeType >\nstruct state_getter< EngineMT2< RNG, RealType, BlockType, SizeType > > {\n    typedef EngineMT2< RNG, RealType, BlockType, SizeType >           object_type;\n\n    void operator()( boost::property_tree::ptree & s, object_type & obj ) {\n        boost::property_tree::ptree tr;\n        state_getter< typename object_type::trait_space_type > tr_logger;\n        tr_logger( tr, obj.m_trait_space );\n\n        boost::property_tree::ptree ph;\n        state_getter< typename object_type::phenotype_eval_type > pheno_logger;\n        pheno_logger( ph, obj.m_pheno );\n\n        boost::property_tree::ptree fr;\n        state_getter< typename object_type::free_space_type > free_logger;\n        free_logger( fr, obj.m_free_space );\n\n        boost::property_tree::ptree fx, alls;\n        state_getter< typename object_type::allele_type > all_logger;\n        all_logger( fx, obj.m_fixed );\n        all_logger( alls, obj.m_allele_space );\n\n//        boost::property_tree::ptree c_pop;\n//        state_getter< typename object_type::sequence_space_type > pop_logger;\n//        pop_logger( c_pop, *(obj.m_child) );\n\n        s.put_child( \"phenotypes\", ph );\n        s.put_child( \"free_space\", fr );\n        s.put_child( \"allele_space\", alls );\n        s.put_child( \"trait_space\", tr );\n        s.put_child( \"fixed_alleles\", fx );\n\n//        s.put_child( \"child\", c_pop );\n    }\n};\n\n}\n}\n\n#endif  // CLOTHO_SIM_ENGINE_MT_HPP_\n", "meta": {"hexsha": "f405d2fa241c9063c251c72c44d5a61784f65077", "size": 14565, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/QTLSim/qtlsim_engine_mt2.hpp", "max_stars_repo_name": "putnampp/clotho", "max_stars_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T21:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:26:54.000Z", "max_issues_repo_path": "examples/QTLSim/qtlsim_engine_mt2.hpp", "max_issues_repo_name": "putnampp/clotho", "max_issues_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T21:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-23T12:41:00.000Z", "max_forks_repo_path": "examples/QTLSim/qtlsim_engine_mt2.hpp", "max_forks_repo_name": "putnampp/clotho", "max_forks_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "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": 38.2283464567, "max_line_length": 198, "alphanum_fraction": 0.6458633711, "num_tokens": 3327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.16504378001077644}}
{"text": "#include <iostream>\n#include <sstream>\n#include <sys/resource.h>\n#include <thread>\n#include <algorithm>\n//#include <boost/asio/thread_pool.hpp>\n//#include <boost/asio/post.hpp>\n//#include <boost/bind.hpp>\n#include <mutex>\n#include \"kmercounter.hpp\"\n#include \"jellyfishreader.hpp\"\n#include \"jellyfishcounter.hpp\"\n#include \"emissionprobabilitycomputer.hpp\"\n#include \"copynumber.hpp\"\n#include \"variantreader.hpp\"\n#include \"uniquekmercomputer.hpp\"\n#include \"hmm.hpp\"\n#include \"commandlineparser.hpp\"\n#include \"timer.hpp\"\n#include \"threadpool.hpp\"\n\nusing namespace std;\n\n/** version of the main algorithm that uses uniform transition probabilities and genotypes only based on kmer information.**/\n\nstruct Results {\n\tmutex result_mutex;\n\tmap<string, vector<GenotypingResult>> result;\n\tmap<string, double> runtimes;\n};\n\nvoid run_genotyping_kmers(string chromosome, KmerCounter* genomic_kmer_counts, KmerCounter* read_kmer_counts, VariantReader* variant_reader, ProbabilityTable* probs, size_t kmer_abundance_peak, bool only_genotyping, bool only_phasing, Results* results) {\n\tTimer timer;\n\t// determine sets of kmers unique to each variant region\n\tUniqueKmerComputer kmer_computer(genomic_kmer_counts, read_kmer_counts, variant_reader, chromosome, kmer_abundance_peak);\n\tstd::vector<UniqueKmers*> unique_kmers;\n\tkmer_computer.compute_unique_kmers(&unique_kmers, probs);\n\t// construct HMM and run genotyping/phasing\n\tHMM hmm(&unique_kmers, probs, !only_phasing, !only_genotyping, 1.26, true);\n\t// store the results\n\t{\n\t\tlock_guard<mutex> lock (results->result_mutex);\n\t\tresults->result.insert(pair<string, vector<GenotypingResult>> (chromosome, move(hmm.get_genotyping_result())));\n\t}\n\t// destroy unique kmers\n\tfor (size_t i = 0; i < unique_kmers.size(); ++i) {\n\t\tdelete unique_kmers[i];\n\t\tunique_kmers[i] = nullptr;\n\t}\n\tlock_guard<mutex> lock (results->result_mutex);\n\tresults->runtimes.insert(pair<string,double>(chromosome, timer.get_total_time()));\n}\n\nint main (int argc, char* argv[])\n{\n\tTimer timer;\n\tdouble time_preprocessing;\n\tdouble time_kmer_counting;\n\tdouble time_writing;\n\tdouble time_total;\n\n\tcerr << endl;\n\tcerr << \"program: PanGenie-kmers - genotyping based on kmer-counting.\" << endl;\n\tcerr << \"author: Jana Ebler\" << endl << endl;\n\tstring readfile = \"\";\n\tstring reffile = \"\";\n\tstring vcffile = \"\";\n\tsize_t kmersize = 31;\n\tstring outname = \"result\";\n\tstring sample_name = \"sample\";\n\tsize_t nr_jellyfish_threads = 1;\n\tsize_t nr_core_threads = 1;\n\tbool only_genotyping = false;\n\tbool only_phasing = false;\n\tlong double regularization = 0.001L;;\n\tbool count_only_graph = true;\n\tbool ignore_imputed = false;\n\n\t// parse the command line arguments\n\tCommandLineParser argument_parser;\n\targument_parser.add_command(\"PanGenie-kmers [options] -i <reads.fa/fq> -r <reference.fa> -v <variants.vcf>\");\n\targument_parser.add_mandatory_argument('i', \"sequencing reads in FASTA/FASTQ format\");\n\targument_parser.add_mandatory_argument('r', \"reference genome in FASTA format\");\n\targument_parser.add_mandatory_argument('v', \"variants in VCF format\");\n\targument_parser.add_optional_argument('o', \"result\", \"prefix of the output files\");\n\targument_parser.add_optional_argument('k', \"31\", \"kmer size\");\n\targument_parser.add_optional_argument('s', \"sample\", \"name of the sample (will be used in the output VCFs)\");\n\targument_parser.add_optional_argument('j', \"1\", \"number of threads to use for kmer-counting\");\n\targument_parser.add_optional_argument('t', \"1\", \"number of threads to use for core algorithm. Largest number of threads possible is the number of chromosomes given in the VCF\");\n\targument_parser.add_flag_argument('g', \"only run genotyping (Forward backward algorithm)\");\n\targument_parser.add_flag_argument('p', \"only run phasing (Viterbi algorithm)\");\n\targument_parser.add_optional_argument('m', \"0.001\", \"regularization constant for copynumber probabilities\");\n\targument_parser.add_flag_argument('c', \"count all kmers instead of only those located in graph..\");\n\targument_parser.add_flag_argument('u', \"output genotype ./. for variants not covered by any unique kmers.\");\n\n\ttry {\n\t\targument_parser.parse(argc, argv);\n\t} catch (const runtime_error& e) {\n\t\targument_parser.usage();\n\t\tcerr << e.what() << endl;\n\t\treturn 1;\n\t} catch (const exception& e) {\n\t\treturn 0;\n\t}\n\treadfile = argument_parser.get_argument('i');\n\treffile = argument_parser.get_argument('r');\n\tvcffile = argument_parser.get_argument('v');\n\tkmersize = stoi(argument_parser.get_argument('k'));\n\toutname = argument_parser.get_argument('o');\n\tsample_name = argument_parser.get_argument('s');\n\tnr_jellyfish_threads = stoi(argument_parser.get_argument('j'));\n\tnr_core_threads = stoi(argument_parser.get_argument('t'));\n\tonly_genotyping = argument_parser.get_flag('g');\n\tonly_phasing = argument_parser.get_flag('p');\n\tregularization = stold(argument_parser.get_argument('m'));\n\tcount_only_graph = !argument_parser.get_flag('c');\n\tignore_imputed = argument_parser.get_flag('u');\n\n\t// print info\n\tcerr << \"Files and parameters used:\" << endl;\n\targument_parser.info();\n\n\t// read allele sequences and unitigs inbetween, write them into file\n\tcerr << \"Determine allele sequences ...\" << endl;\n\tVariantReader variant_reader (vcffile, reffile, kmersize, false, sample_name);\n\tstring segment_file = outname + \"_path_segments.fasta\";\n\tcerr << \"Write path segments to file: \" << segment_file << \" ...\" << endl;\n\tvariant_reader.write_path_segments(segment_file);\n\n\t// determine chromosomes present in VCF\n\tvector<string> chromosomes;\n\tvariant_reader.get_chromosomes(&chromosomes);\n\tcerr << \"Found \" << chromosomes.size() << \" chromosome(s) in the VCF.\" << endl;\n\n\t// TODO: only for analysis\n\tstruct rusage r_usage0;\n\tgetrusage(RUSAGE_SELF, &r_usage0);\n\tcerr << \"#### Memory usage until now: \" << (r_usage0.ru_maxrss / 1E6) << \" GB ####\" << endl;\n\n\ttime_preprocessing = timer.get_interval_time();\n\n\tKmerCounter* read_kmer_counts = nullptr;\n\t// determine kmer copynumbers in reads\n\tif (readfile.substr(std::max(3, (int) readfile.size())-3) == std::string(\".jf\")) {\n\t\tcerr << \"Read pre-computed read kmer counts ...\" << endl;\n\t\tjellyfish::mer_dna::k(kmersize);\n\t\tread_kmer_counts = new JellyfishReader(readfile, kmersize);\n\t} else {\n\t\tcerr << \"Count kmers in reads ...\" << endl;\n\t\tif (count_only_graph) {\n\t\t\tread_kmer_counts = new JellyfishCounter(readfile, segment_file, kmersize, nr_jellyfish_threads);\n\t\t} else {\n\t\t\tread_kmer_counts = new JellyfishCounter(readfile, kmersize, nr_jellyfish_threads);\n\t\t}\n\t}\n\n\tsize_t kmer_abundance_peak = read_kmer_counts->computeHistogram(10000, count_only_graph, outname + \"_histogram.histo\");\n\tcerr << \"Computed kmer abundance peak: \" << kmer_abundance_peak << endl;\n\n\t// count kmers in allele + reference sequence\n\tcerr << \"Count kmers in genome ...\" << endl;\n\n\tJellyfishCounter genomic_kmer_counts (segment_file, kmersize, nr_jellyfish_threads);\n\n\t// TODO: only for analysis\n\tstruct rusage r_usage1;\n\tgetrusage(RUSAGE_SELF, &r_usage1);\n\tcerr << \"#### Memory usage until now: \" << (r_usage1.ru_maxrss / 1E6) << \" GB ####\" << endl;\n\n\t// prepare output files\n\tif (! only_phasing) variant_reader.open_genotyping_outfile(outname + \"_genotyping.vcf\");\n\tif (! only_genotyping) variant_reader.open_phasing_outfile(outname + \"_phasing.vcf\");\n\n\ttime_kmer_counting = timer.get_interval_time();\n\n\tcerr << \"Construct HMM and run core algorithm ...\" << endl;\n\tProbabilityTable probabilities (kmer_abundance_peak / 4, kmer_abundance_peak*4, 2*kmer_abundance_peak, regularization);\n\n\t// determine max number of available threads (at most one thread per chromosome possible)\n\tsize_t available_threads = min(thread::hardware_concurrency(), (unsigned int) chromosomes.size());\n\tif (nr_core_threads > available_threads) {\n\t\tcerr << \"Warning: set nr_core_threads to \" << available_threads << \".\" << endl;\n\t\tnr_core_threads = available_threads;\n \t}\n\tResults results;\n\t{\n\t\t// create thread pool\n\t\tThreadPool threadPool (nr_core_threads);\n\t\tfor (auto chromosome : chromosomes) {\n\t\t\tKmerCounter* genomic = &genomic_kmer_counts;\n\t\t\tVariantReader* variants = &variant_reader;\n\t\t\tResults* r = &results;\n\t\t\tProbabilityTable* probs = &probabilities;\n\t\t\tfunction<void()> f_genotyping = bind(run_genotyping_kmers, chromosome, genomic, read_kmer_counts, variants, probs, kmer_abundance_peak, only_genotyping, only_phasing, r);\n\t\t\tthreadPool.submit(f_genotyping);\n\t\t}\n\t}\n\n/**\n\t// create thread pool\n\tboost::asio::thread_pool threadPool(nr_core_threads);\n\tfor (auto chromosome : chromosomes) {\n\t\tboost::asio::post(threadPool, boost::bind(run_genotyping_kmers, chromosome, &genomic_kmer_counts, read_kmer_counts, &variant_reader, kmer_abundance_peak, only_genotyping, only_phasing, &results));\n\t} \n\tthreadPool.join();\n**/\n\n\ttimer.get_interval_time();\n\n\t// output VCF\n\tcerr << \"Write results to VCF ...\" << endl;\n\tassert (results.result.size() == chromosomes.size());\n\t// write VCF\n\tfor (auto it = results.result.begin(); it != results.result.end(); ++it) {\n\t\tif (!only_phasing) {\n\t\t\t// output genotyping results\n\t\t\tvariant_reader.write_genotypes_of(it->first, it->second, ignore_imputed);\n\t\t}\n\t\tif (!only_genotyping) {\n\t\t\t// output phasing results\n\t\t\tvariant_reader.write_phasing_of(it->first, it->second, ignore_imputed);\n\t\t}\n\t}\n\n\tif (! only_phasing) variant_reader.close_genotyping_outfile();\n\tif (! only_genotyping) variant_reader.close_phasing_outfile();\n\n\ttime_writing = timer.get_interval_time();\n\ttime_total = timer.get_total_time();\n\n\tcerr << endl << \"###### Summary ######\" << endl;\n\t// output times\n\tcerr << \"time spent reading input files:\\t\" << time_preprocessing << \" sec\" << endl;\n\tcerr << \"time spent counting kmers:\\t\" << time_kmer_counting << \" sec\" << endl;\n\t// output per chromosome time\n\tdouble time_hmm = time_writing;\n\tfor (auto chromosome : chromosomes) {\n\t\tdouble time_chrom = results.runtimes.at(chromosome);\n\t\tcerr << \"time spent genotyping chromosome \" << chromosome << \":\\t\" << time_chrom << endl;\n\t\ttime_hmm += time_chrom;\n\t}\n\tcerr << \"total running time:\\t\" << time_preprocessing + time_kmer_counting + time_hmm << \" sec\"<< endl;\n\tcerr << \"total wallclock time: \" << time_total  << \" sec\" << endl;\n\n\t// memory usage\n\tstruct rusage r_usage;\n\tgetrusage(RUSAGE_SELF, &r_usage);\n\tcerr << \"Total maximum memory usage: \" << (r_usage.ru_maxrss / 1E6) << \" GB\" << endl;\n\n\tdelete read_kmer_counts;\n\treturn 0;\n}\n\n", "meta": {"hexsha": "81196fe0dbebf0c3e7ac1d8bb7a29a66ac4a9beb", "size": 10280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pggtyper-kmers.cpp", "max_stars_repo_name": "ASLeonard/pangenie", "max_stars_repo_head_hexsha": "aeb0c2aa28bf69041755855306d32f5523371274", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:49:01.000Z", "max_issues_repo_path": "src/pggtyper-kmers.cpp", "max_issues_repo_name": "ASLeonard/pangenie", "max_issues_repo_head_hexsha": "aeb0c2aa28bf69041755855306d32f5523371274", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-09T15:28:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T10:12:50.000Z", "max_forks_repo_path": "src/pggtyper-kmers.cpp", "max_forks_repo_name": "ASLeonard/pangenie", "max_forks_repo_head_hexsha": "aeb0c2aa28bf69041755855306d32f5523371274", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T09:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T09:56:36.000Z", "avg_line_length": 40.4724409449, "max_line_length": 254, "alphanum_fraction": 0.7380350195, "num_tokens": 2612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.16504376522766995}}
{"text": "#ifndef OPENGM_PYTHON_INTERFACE\n#define OPENGM_PYTHON_INTERFACE 1\n#endif\n\n#include <stdexcept>\n#include <stddef.h>\n#include <string>\n#include <boost/python.hpp>\n#include <opengm/graphicalmodel/graphicalmodel.hxx>\n#include <opengm/inference/inference.hxx>\n#include <opengm/inference/dynamicprogramming.hxx>\n#include \"nifty_iterator.hxx\"\n#include \"inferencehelpers.hxx\"\n#include \"../export_typedes.hxx\"\nusing namespace boost::python;\n\n// Py Inference Types \nnamespace pydynp{\n   template<class PARAM>\n   inline void set(PARAM & p){}\n}\n\ntemplate<class GM,class ACC>\nvoid export_dynp(){\n   import_array(); \n   typedef opengm::DynamicProgramming<GM, ACC>  PyDynamicProgramming;\n   typedef typename PyDynamicProgramming::Parameter PyDynamicProgrammingParameter;\n   typedef typename PyDynamicProgramming::VerboseVisitorType PyDynamicProgrammingVerboseVisitor;\n\n   class_<PyDynamicProgrammingParameter > ( \"DynamicProgrammingParameter\" , init< > ())\n   .def(\"set\",&pydynp::set<PyDynamicProgrammingParameter>)\n   ;\n   OPENGM_PYTHON_VERBOSE_VISITOR_EXPORTER(PyDynamicProgrammingVerboseVisitor,\"DynamicProgrammingVerboseVisitor\" );\n   OPENGM_PYTHON_INFERENCE_NO_RESET_EXPORTER(PyDynamicProgramming,\"DynamicProgramming\");\n}\n\ntemplate void export_dynp<GmAdder,opengm::Minimizer>();\ntemplate void export_dynp<GmAdder,opengm::Maximizer>();\ntemplate void export_dynp<GmMultiplier,opengm::Minimizer>();\ntemplate void export_dynp<GmMultiplier,opengm::Maximizer>();", "meta": {"hexsha": "02b26077dc64d0e531b8ffaaa6c299383670dd96", "size": 1446, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/interfaces/python/opengm/inference/pyDynp.cxx", "max_stars_repo_name": "amueller/opengm", "max_stars_repo_head_hexsha": "bf2d0c611ade9bbf1d2ae537fee0df4cb6553777", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T20:56:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-13T20:56:48.000Z", "max_issues_repo_path": "src/interfaces/python/opengm/inference/pyDynp.cxx", "max_issues_repo_name": "amueller/opengm", "max_issues_repo_head_hexsha": "bf2d0c611ade9bbf1d2ae537fee0df4cb6553777", "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/interfaces/python/opengm/inference/pyDynp.cxx", "max_forks_repo_name": "amueller/opengm", "max_forks_repo_head_hexsha": "bf2d0c611ade9bbf1d2ae537fee0df4cb6553777", "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.15, "max_line_length": 114, "alphanum_fraction": 0.805670816, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.16490971982970554}}
{"text": "#include <v4r/features/global_alexnet_cnn_estimator.h>\n\n#include <stdio.h>  // for snprintf\n#include <string>\n#include <vector>\n\n#include <boost/algorithm/string.hpp>\n#include <google/protobuf/text_format.h>\n\n#include <caffe/blob.hpp>\n#include <caffe/common.hpp>\n//#include <caffe/proto/caffe.pb.h>\n#include <caffe/util/db.hpp>\n#include <caffe/util/io.hpp>\n#include <caffe/layer.hpp>\n#include <caffe/layers/memory_data_layer.hpp>\n#include <caffe/net.hpp>\n\n#include <v4r/common/img_utils.h>\n#include <v4r/common/pcl_opencv.h>\n\nusing caffe::Blob;\nusing caffe::Caffe;\nusing caffe::Datum;\nusing caffe::Net;\nusing std::string;\nnamespace db = caffe::db;\n\nnamespace v4r\n{\n\ntemplate<typename PointT, typename Dtype>\nvoid\nCNN_Feat_Extractor<PointT, Dtype>::WrapInputLayer(std::vector<cv::Mat>* input_channels)\n{\n    caffe::Blob<float>* input_layer = net_->input_blobs()[0];\n\n    int width = input_layer->width();\n    int height = input_layer->height();\n    Dtype* input_data = input_layer->mutable_cpu_data();\n    for (int i = 0; i < input_layer->channels(); ++i)\n    {\n        cv::Mat channel(height, width, CV_32FC1, input_data);\n        input_channels->push_back(channel);\n        input_data += width * height;\n    }\n}\n\ntemplate<typename PointT, typename Dtype>\nvoid\nCNN_Feat_Extractor<PointT, Dtype>::Preprocess(const cv::Mat& img, std::vector<cv::Mat>* input_channels) {\n    /* Convert the input image to the input image format of the network. */\n    cv::Mat sample;\n    if (img.channels() == 3 && num_channels_ == 1)\n        cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);\n    else if (img.channels() == 4 && num_channels_ == 1)\n        cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);\n    else if (img.channels() == 4 && num_channels_ == 3)\n        cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);\n    else if (img.channels() == 1 && num_channels_ == 3)\n        cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);\n    else\n        sample = img;\n\n    cv::Mat sample_resized;\n    if (sample.size() != input_geometry_)\n        cv::resize(sample, sample_resized, input_geometry_);\n    else\n        sample_resized = sample;\n\n    cv::Mat sample_float;\n    if (num_channels_ == 3)\n        sample_resized.convertTo(sample_float, CV_32FC3);\n    else\n        sample_resized.convertTo(sample_float, CV_32FC1);\n\n    cv::Mat sample_normalized;\n    cv::subtract(sample_float, mean_, sample_normalized);\n\n    /* This operation will write the separate BGR planes directly to the\n   * input layer of the network because it is wrapped by the cv::Mat\n   * objects in input_channels. */\n    cv::split(sample_normalized, *input_channels);\n\n    CHECK(reinterpret_cast<Dtype*>(input_channels->at(0).data)\n          == net_->input_blobs()[0]->cpu_data())\n            << \"Input channels are not wrapping the input layer of the network.\";\n}\n\n\n/* Load the mean file in binaryproto format. */\ntemplate<typename PointT, typename Dtype>\nvoid\nCNN_Feat_Extractor<PointT, Dtype>::SetMean(const std::string& mean_file)\n{\n    caffe::BlobProto blob_proto;\n    ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);\n\n    /* Convert from BlobProto to Blob<float> */\n    Blob<float> mean_blob;\n    mean_blob.FromProto(blob_proto);\n    CHECK_EQ(mean_blob.channels(), num_channels_)\n            << \"Number of channels of mean file doesn't match input layer.\";\n\n    /* The format of the mean file is planar 32-bit float BGR or grayscale. */\n    std::vector<cv::Mat> channels;\n    float* data = mean_blob.mutable_cpu_data();\n    for (int i = 0; i < num_channels_; i++)\n    {\n        /* Extract an individual channel. */\n        cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);\n        channels.push_back(channel);\n        data += mean_blob.height() * mean_blob.width();\n    }\n\n    /* Merge the separate channels into a single image. */\n    cv::Mat mean;\n    cv::merge(channels, mean);\n\n    /* Compute the global mean pixel value and create a mean image\n   * filled with this value. */\n    cv::Scalar channel_mean = cv::mean(mean);\n    mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);\n}\n\ntemplate<typename PointT, typename Dtype>\nint\nCNN_Feat_Extractor<PointT, Dtype>::init(){\n\n  if (strcmp(param_.device_name_.c_str(), \"GPU\") == 0)\n  {\n    Caffe::SetDevice(param_.device_id_);\n    Caffe::set_mode(Caffe::GPU);\n  }\n  else\n    Caffe::set_mode(Caffe::CPU);\n\n  net_.reset(new Net<Dtype>(param_.feature_extraction_proto_, caffe::TEST));\n  net_->CopyTrainedLayersFrom(param_.pretrained_binary_proto_);\n\n  caffe::Blob<Dtype>* input_layer = net_->input_blobs()[0];\n  num_channels_ = input_layer->channels();\n  CHECK(num_channels_ == 3 || num_channels_ == 1) << \"Input layer should have 1 or 3 channels.\";\n  input_geometry_ = cv::Size(input_layer->width(), input_layer->height());\n\n  /* Load the binaryproto mean file. */\n  SetMean(param_.input_mean_file_);\n  return 0;\n}\n\n\ntemplate<typename PointT, typename Dtype>\nbool\nCNN_Feat_Extractor<PointT, Dtype>::compute (const cv::Mat &img, Eigen::MatrixXf &signature)\n{\n    if(!init_)\n    {\n        init();\n        init_ = true;\n    }\n\n    Blob<Dtype>* input_layer = net_->input_blobs()[0];\n    input_layer->Reshape(1, num_channels_,\n                         input_geometry_.height, input_geometry_.width);\n    /* Forward dimension change to all layers. */\n    net_->Reshape();\n\n    std::vector<cv::Mat> input_channels;\n    WrapInputLayer(&input_channels);\n\n    Preprocess(img, &input_channels);\n\n    net_->Forward();\n\n    /* Copy the output layer to a std::vector */\n//    Blob<float>* output_layer = net_->output_blobs()[0];\n    boost::shared_ptr<Blob<Dtype> > output_layer = net_->blob_by_name(param_.output_layer_name_);\n    const float* begin = output_layer->cpu_data();\n    const float* end = begin + output_layer->channels();\n    std::vector<float> sign_f = std::vector<float>(begin, end);\n\n    signature = Eigen::MatrixXf (1, sign_f.size());\n\n    for(size_t i=0; i<sign_f.size(); i++)\n        signature(0,i) = sign_f[i];\n\n    indices_.clear();\n    cloud_.reset();\n    return true;\n}\n\ntemplate<typename PointT, typename Dtype>\nbool\nCNN_Feat_Extractor<PointT, Dtype>::compute (Eigen::MatrixXf &signature)\n{\n    CHECK( cloud_ && cloud_->isOrganized() && !cloud_->points.empty() && !indices_.empty());\n    PCLOpenCVConverter<PointT> pcl_opencv_converter;\n    pcl_opencv_converter.setInputCloud(cloud_);\n    pcl_opencv_converter.setIndices(indices_);\n    pcl_opencv_converter.setBackgroundColor( param_.background_color_(0), param_.background_color_(1), param_.background_color_(2) );\n    pcl_opencv_converter.setRemoveBackground( param_.remove_background_ );\n    cv::Mat img = pcl_opencv_converter.getRGBImage();\n    cv::Rect roi = pcl_opencv_converter.getROI();\n    cv::Mat img_cropped = cropImage(img, roi, param_.margin_, true);\n\n    std::cerr << \"Closing operation not implemented right now!\" << std::endl;   ///TODO: re-implement closing operation to avoid sharp transitions from noisy measurements\n\n    compute(img_cropped, signature);\n    indices_.clear();\n    return true;\n}\n    template class V4R_EXPORTS CNN_Feat_Extractor<pcl::PointXYZRGB>;\n}\n", "meta": {"hexsha": "ab55078d231e82c5b75a5563a0434a8f835ee0a4", "size": 7082, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/features/src/global_alexnet_cnn_estimator.cpp", "max_stars_repo_name": "ToMadoRe/v4r", "max_stars_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T14:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T02:57:33.000Z", "max_issues_repo_path": "modules/features/src/global_alexnet_cnn_estimator.cpp", "max_issues_repo_name": "ToMadoRe/v4r", "max_issues_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T15:04:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T10:52:35.000Z", "max_forks_repo_path": "modules/features/src/global_alexnet_cnn_estimator.cpp", "max_forks_repo_name": "ToMadoRe/v4r", "max_forks_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T09:26:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T01:31:00.000Z", "avg_line_length": 33.0934579439, "max_line_length": 170, "alphanum_fraction": 0.686529229, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16490971647506547}}
{"text": "#include <gtest/gtest.h>\n\n#include \"converter/fixml2fix_converter.hxx\"\n#include \"converter/xml_element_helper.hxx\"\n#include \"converter/fix_helper.hxx\"\n#include \"util/fix_env.hxx\"\n#include \"tools/test_util.hxx\"\n\n#include <boost/log/trivial.hpp>\n\n#include <quickfix/fix50sp2/Confirmation.h>\n\n#include <list>\n#include <set>\n#include <string>\n#include <utility>\n\nusing namespace std;\nusing namespace fix2xml;\n\nTEST ( Confirmation, set_fields)\n{\n\n  fixml2fix_converter converter {\"../spec/fix/FIX50SP2.xml\", \"../spec/xsd/fixml-main-5-0-SP2.xsd\"};\n  auto& fixml_dict = converter.fixml_dico();\n  ASSERT_TRUE(converter.init());\n  ASSERT_TRUE(converter.parse_fixt_dico(\"../spec/fix/FIXT11.xml\"));\n  FIX50SP2::Confirmation msg;\n\n  list<multiset<string>> all_values;\n  multiset<string> all_compo_names;\n  multiset<string> Confirmation_0;\n  FIX::AccruedInterestAmt AccruedInterestAmt_8;\n  AccruedInterestAmt_8.setString(\"10106632\");\nset_field(msg, AccruedInterestAmt_8, Confirmation_0);\n  FIX::AccruedInterestRate AccruedInterestRate_3;\n  AccruedInterestRate_3.setString(\"93.770000\");\nset_field(msg, AccruedInterestRate_3, Confirmation_0);\n  set_field(msg, FIX::AllocAccount{\"STRING_1767761837\"}, Confirmation_0);\n  set_field(msg, FIX::AllocAccountType{1}, Confirmation_0);\n  set_field(msg, FIX::AllocAcctIDSource{1898224372}, Confirmation_0);\n  set_field(msg, FIX::AllocID{\"STRING_1718053725\"}, Confirmation_0);\n  FIX::AllocQty AllocQty_13;\n  AllocQty_13.setString(\"9272930\");\nset_field(msg, AllocQty_13, Confirmation_0);\n  FIX::AvgParPx AvgParPx_3;\n  AvgParPx_3.setString(\"14729936\");\nset_field(msg, AvgParPx_3, Confirmation_0);\n  FIX::AvgPx AvgPx_3;\n  AvgPx_3.setString(\"10302959\");\nset_field(msg, AvgPx_3, Confirmation_0);\n  set_field(msg, FIX::AvgPxPrecision{643298040}, Confirmation_0);\n  FIX::Concession Concession_3;\n  Concession_3.setString(\"11397832\");\nset_field(msg, Concession_3, Confirmation_0);\n  set_field(msg, FIX::ConfirmID{\"STRING_1617646372\"}, Confirmation_0);\n  set_field(msg, FIX::ConfirmRefID{\"STRING_1992123294\"}, Confirmation_0);\n  set_field(msg, FIX::ConfirmReqID{\"STRING_1683343010\"}, Confirmation_0);\n  set_field(msg, FIX::ConfirmStatus{5}, Confirmation_0);\n  set_field(msg, FIX::ConfirmTransType{1}, Confirmation_0);\n  set_field(msg, FIX::ConfirmType{1}, Confirmation_0);\n  set_field(msg, FIX::CopyMsgIndicator{false}, Confirmation_0);\n  set_field(msg, FIX::Currency{\"CHF\"}, Confirmation_0);\n  set_field(msg, FIX::EncodedText{\"DATA_1072977068\"}, Confirmation_0);\n  set_field(msg, FIX::EncodedTextLen{226667298}, Confirmation_0);\n  FIX::EndAccruedInterestAmt EndAccruedInterestAmt_8;\n  EndAccruedInterestAmt_8.setString(\"1008242\");\nset_field(msg, EndAccruedInterestAmt_8, Confirmation_0);\n  FIX::EndCash EndCash_8;\n  EndCash_8.setString(\"4598226\");\nset_field(msg, EndCash_8, Confirmation_0);\n  set_field(msg, FIX::ExDate{\"LOCALMKTDATE_144059962\"}, Confirmation_0);\n  FIX::GrossTradeAmt GrossTradeAmt_3;\n  GrossTradeAmt_3.setString(\"20908466\");\nset_field(msg, GrossTradeAmt_3, Confirmation_0);\n  set_field(msg, FIX::IndividualAllocID{\"STRING_1512273886\"}, Confirmation_0);\n  FIX::InterestAtMaturity InterestAtMaturity_3;\n  InterestAtMaturity_3.setString(\"21219895\");\nset_field(msg, InterestAtMaturity_3, Confirmation_0);\n  set_field(msg, FIX::LastMkt{\"EXCHANGE_1960680719\"}, Confirmation_0);\n  set_field(msg, FIX::LegalConfirm{true}, Confirmation_0);\n  FIX::MaturityNetMoney MaturityNetMoney_0;\n  MaturityNetMoney_0.setString(\"14352280\");\nset_field(msg, MaturityNetMoney_0, Confirmation_0);\n  FIX::NetMoney NetMoney_3;\n  NetMoney_3.setString(\"8238603\");\nset_field(msg, NetMoney_3, Confirmation_0);\n  set_field(msg, FIX::NumDaysInterest{1174681741}, Confirmation_0);\n  set_field(msg, FIX::PriceType{10}, Confirmation_0);\n  set_field(msg, FIX::ProcessCode{'0'}, Confirmation_0);\n  set_field(msg, FIX::QtyType{1}, Confirmation_0);\n  FIX::ReportedPx ReportedPx_0;\n  ReportedPx_0.setString(\"6260762\");\nset_field(msg, ReportedPx_0, Confirmation_0);\n  set_field(msg, FIX::SecondaryAllocID{\"STRING_157497628\"}, Confirmation_0);\n  FIX::SettlCurrAmt SettlCurrAmt_8;\n  SettlCurrAmt_8.setString(\"2509324\");\nset_field(msg, SettlCurrAmt_8, Confirmation_0);\n  FIX::SettlCurrFxRate SettlCurrFxRate_8;\n  SettlCurrFxRate_8.setString(\"16563722\");\nset_field(msg, SettlCurrFxRate_8, Confirmation_0);\n  set_field(msg, FIX::SettlCurrFxRateCalc{'M'}, Confirmation_0);\n  set_field(msg, FIX::SettlCurrency{\"USD\"}, Confirmation_0);\n  set_field(msg, FIX::SettlDate{\"LOCALMKTDATE_645435315\"}, Confirmation_0);\n  set_field(msg, FIX::SettlType{\"STRING_7\"}, Confirmation_0);\n  FIX::SharedCommission SharedCommission_0;\n  SharedCommission_0.setString(\"18121276\");\nset_field(msg, SharedCommission_0, Confirmation_0);\n  set_field(msg, FIX::Side{'1'}, Confirmation_0);\n  FIX::StartCash StartCash_8;\n  StartCash_8.setString(\"19830917\");\nset_field(msg, StartCash_8, Confirmation_0);\n  set_field(msg, FIX::Text{\"STRING_260974961\"}, Confirmation_0);\n  FIX::TotalTakedown TotalTakedown_3;\n  TotalTakedown_3.setString(\"15517949\");\nset_field(msg, TotalTakedown_3, Confirmation_0);\n  set_field(msg, FIX::TradeDate{\"LOCALMKTDATE_1766491263\"}, Confirmation_0);\n  set_field(msg, FIX::TransactTime{FIX::UTCTIMESTAMP(18, 32, 25, 17, 10, 2015)}, Confirmation_0);\n  all_values.push_back(Confirmation_0);\n\n  all_compo_names.insert(\"Confirmation\");\n\n  // CommissionData\n  multiset<string> CommissionData_10;\n  set_field(msg, FIX::CommCurrency{\"USD\"}, CommissionData_10);\n  set_field(msg, FIX::CommType{'3'}, CommissionData_10);\n  FIX::Commission Commission_10;\n  Commission_10.setString(\"11847725\");\nset_field(msg, Commission_10, CommissionData_10);\n  set_field(msg, FIX::FundRenewWaiv{'N'}, CommissionData_10);\n  all_values.push_back(CommissionData_10);\n  all_compo_names.insert(\".\");\n\n  // CpctyConfGrp\n  // Group CpctyConfGrp.NoCapacities\n  {\n    FIX50SP2::Confirmation::NoCapacities noCapacities_0_0;\n    // CpctyConfGrp.NoCapacities\n    multiset<string> CpctyConfGrp_NoCapacities_0;\n    set_field(noCapacities_0_0, FIX::OrderCapacity{'P'}, CpctyConfGrp_NoCapacities_0);\n    FIX::OrderCapacityQty OrderCapacityQty_0;\n    OrderCapacityQty_0.setString(\"16779405\");\nset_field(noCapacities_0_0, OrderCapacityQty_0, CpctyConfGrp_NoCapacities_0);\n    set_field(noCapacities_0_0, FIX::OrderRestrictions{\"MULTIPLECHARVALUE_3\"}, CpctyConfGrp_NoCapacities_0);\n    all_values.push_back(CpctyConfGrp_NoCapacities_0);\n    all_compo_names.insert(\"...NoCapacities\");\n\n    msg.addGroup(noCapacities_0_0);\n  }\n  // FinancingDetails\n  multiset<string> FinancingDetails_9;\n  set_field(msg, FIX::AgreementCurrency{\"CAN\"}, FinancingDetails_9);\n  set_field(msg, FIX::AgreementDate{\"LOCALMKTDATE_1050310292\"}, FinancingDetails_9);\n  set_field(msg, FIX::AgreementDesc{\"STRING_227759998\"}, FinancingDetails_9);\n  set_field(msg, FIX::AgreementID{\"STRING_488750168\"}, FinancingDetails_9);\n  set_field(msg, FIX::DeliveryType{2}, FinancingDetails_9);\n  set_field(msg, FIX::EndDate{\"LOCALMKTDATE_1354294991\"}, FinancingDetails_9);\n  FIX::MarginRatio MarginRatio_9;\n  MarginRatio_9.setString(\"54.830000\");\nset_field(msg, MarginRatio_9, FinancingDetails_9);\n  set_field(msg, FIX::StartDate{\"LOCALMKTDATE_1220117337\"}, FinancingDetails_9);\n  set_field(msg, FIX::TerminationType{1}, FinancingDetails_9);\n  all_values.push_back(FinancingDetails_9);\n  all_compo_names.insert(\".\");\n\n  // InstrmtLegGrp\n  // Group InstrmtLegGrp.NoLegs\n  {\n    FIX50SP2::Confirmation::NoLegs noLegs_0_0;\n    // InstrmtLegGrp.NoLegs\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_20;\n    set_field(noLegs_0_0, FIX::EncodedLegIssuer{\"DATA_1055725467\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::EncodedLegIssuerLen{1279913985}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDesc{\"DATA_1380471043\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDescLen{674733082}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegCFICode{\"STRING_466382367\"}, InstrumentLeg_20);\n    FIX::LegContractMultiplier LegContractMultiplier_20;\n    LegContractMultiplier_20.setString(\"10114496\");\nset_field(noLegs_0_0, LegContractMultiplier_20, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegContractMultiplierUnit{394564906}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegContractSettlMonth{\"MONTHYEAR_112673384\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegCountryOfIssue{\"COUNTRY_786488210\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_57759767\"}, InstrumentLeg_20);\n    FIX::LegCouponRate LegCouponRate_20;\n    LegCouponRate_20.setString(\"82.870000\");\nset_field(noLegs_0_0, LegCouponRate_20, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegCreditRating{\"STRING_536032684\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegCurrency{\"EUR\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegDatedDate{\"LOCALMKTDATE_1720805189\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegExerciseStyle{1981887618}, InstrumentLeg_20);\n    FIX::LegFactor LegFactor_20;\n    LegFactor_20.setString(\"19919509\");\nset_field(noLegs_0_0, LegFactor_20, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegFlowScheduleType{1813600268}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegInstrRegistry{\"STRING_1512344489\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_643845096\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegIssueDate{\"LOCALMKTDATE_384987998\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegIssuer{\"STRING_1200298988\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegLocaleOfIssue{\"STRING_1694155389\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegMaturityDate{\"LOCALMKTDATE_612747997\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegMaturityMonthYear{\"MONTHYEAR_1689049156\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegMaturityTime{\"TZTIMEONLY_1987697699\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegOptAttribute{'1'}, InstrumentLeg_20);\n    FIX::LegOptionRatio LegOptionRatio_20;\n    LegOptionRatio_20.setString(\"6757509\");\nset_field(noLegs_0_0, LegOptionRatio_20, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegPool{\"STRING_1060331388\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegPriceUnitOfMeasure{\"STRING_838498364\"}, InstrumentLeg_20);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_20;\n    LegPriceUnitOfMeasureQty_20.setString(\"5044270\");\nset_field(noLegs_0_0, LegPriceUnitOfMeasureQty_20, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegProduct{2116056855}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegPutOrCall{2118412350}, InstrumentLeg_20);\n    FIX::LegRatioQty LegRatioQty_20;\n    LegRatioQty_20.setString(\"18848981\");\nset_field(noLegs_0_0, LegRatioQty_20, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegRedemptionDate{\"LOCALMKTDATE_643306289\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegRepoCollateralSecurityType{\"STRING_437311069\"}, InstrumentLeg_20);\n    FIX::LegRepurchaseRate LegRepurchaseRate_20;\n    LegRepurchaseRate_20.setString(\"41.230000\");\nset_field(noLegs_0_0, LegRepurchaseRate_20, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegRepurchaseTerm{1037871195}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSecurityDesc{\"STRING_549984453\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSecurityExchange{\"EXCHANGE_1535352333\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSecurityID{\"STRING_1095630963\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSecurityIDSource{\"STRING_1821222740\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSecuritySubType{\"STRING_2071385017\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSecurityType{\"STRING_629782663\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSide{'1'}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegStateOrProvinceOfIssue{\"STRING_1644706559\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegStrikeCurrency{\"CHF\"}, InstrumentLeg_20);\n    FIX::LegStrikePrice LegStrikePrice_20;\n    LegStrikePrice_20.setString(\"13108231\");\nset_field(noLegs_0_0, LegStrikePrice_20, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSymbol{\"STRING_1976531122\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegSymbolSfx{\"STRING_132563365\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegTimeUnit{\"STRING_1695811178\"}, InstrumentLeg_20);\n    set_field(noLegs_0_0, FIX::LegUnitOfMeasure{\"STRING_1029346462\"}, InstrumentLeg_20);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_20;\n    LegUnitOfMeasureQty_20.setString(\"18267187\");\nset_field(noLegs_0_0, LegUnitOfMeasureQty_20, InstrumentLeg_20);\n    all_values.push_back(InstrumentLeg_20);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::Confirmation::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_44;\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltID{\"STRING_570911971\"}, LegSecAltIDGrp_NoLegSecurityAltID_44);\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltIDSource{\"STRING_1666932805\"}, LegSecAltIDGrp_NoLegSecurityAltID_44);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_44);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_45;\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltID{\"STRING_2128118515\"}, LegSecAltIDGrp_NoLegSecurityAltID_45);\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltIDSource{\"STRING_1246662962\"}, LegSecAltIDGrp_NoLegSecurityAltID_45);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_45);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_1);\n    }\n    msg.addGroup(noLegs_0_0);\n  }\n  // Instrument\n  multiset<string> Instrument_14;\n  FIX::AttachmentPoint AttachmentPoint_14;\n  AttachmentPoint_14.setString(\"5.460000\");\nset_field(msg, AttachmentPoint_14, Instrument_14);\n  set_field(msg, FIX::CFICode{\"STRING_819133231\"}, Instrument_14);\n  set_field(msg, FIX::CPProgram{99}, Instrument_14);\n  set_field(msg, FIX::CPRegType{\"STRING_548353753\"}, Instrument_14);\n  FIX::CapPrice CapPrice_14;\n  CapPrice_14.setString(\"7900619\");\nset_field(msg, CapPrice_14, Instrument_14);\n  FIX::ContractMultiplier ContractMultiplier_14;\n  ContractMultiplier_14.setString(\"14885045\");\nset_field(msg, ContractMultiplier_14, Instrument_14);\n  set_field(msg, FIX::ContractMultiplierUnit{1}, Instrument_14);\n  set_field(msg, FIX::ContractSettlMonth{\"MONTHYEAR_1227373002\"}, Instrument_14);\n  set_field(msg, FIX::CountryOfIssue{\"COUNTRY_89884997\"}, Instrument_14);\n  set_field(msg, FIX::CouponPaymentDate{\"LOCALMKTDATE_82047590\"}, Instrument_14);\n  FIX::CouponRate CouponRate_14;\n  CouponRate_14.setString(\"74.550000\");\nset_field(msg, CouponRate_14, Instrument_14);\n  set_field(msg, FIX::CreditRating{\"STRING_1625237331\"}, Instrument_14);\n  set_field(msg, FIX::DatedDate{\"LOCALMKTDATE_1177678553\"}, Instrument_14);\n  FIX::DetachmentPoint DetachmentPoint_14;\n  DetachmentPoint_14.setString(\"65.480000\");\nset_field(msg, DetachmentPoint_14, Instrument_14);\n  set_field(msg, FIX::EncodedIssuer{\"DATA_1549138700\"}, Instrument_14);\n  set_field(msg, FIX::EncodedIssuerLen{1807461216}, Instrument_14);\n  set_field(msg, FIX::EncodedSecurityDesc{\"DATA_1095347548\"}, Instrument_14);\n  set_field(msg, FIX::EncodedSecurityDescLen{1046361611}, Instrument_14);\n  set_field(msg, FIX::ExerciseStyle{0}, Instrument_14);\n  FIX::Factor Factor_14;\n  Factor_14.setString(\"5840658\");\nset_field(msg, Factor_14, Instrument_14);\n  set_field(msg, FIX::FlexProductEligibilityIndicator{false}, Instrument_14);\n  set_field(msg, FIX::FlexibleIndicator{false}, Instrument_14);\n  FIX::FloorPrice FloorPrice_14;\n  FloorPrice_14.setString(\"7166291\");\nset_field(msg, FloorPrice_14, Instrument_14);\n  set_field(msg, FIX::FlowScheduleType{1}, Instrument_14);\n  set_field(msg, FIX::InstrRegistry{\"STRING_982558138\"}, Instrument_14);\n  set_field(msg, FIX::InstrmtAssignmentMethod{'3'}, Instrument_14);\n  set_field(msg, FIX::InterestAccrualDate{\"LOCALMKTDATE_2066587848\"}, Instrument_14);\n  set_field(msg, FIX::IssueDate{\"LOCALMKTDATE_1553470109\"}, Instrument_14);\n  set_field(msg, FIX::Issuer{\"STRING_2062797094\"}, Instrument_14);\n  set_field(msg, FIX::ListMethod{1}, Instrument_14);\n  set_field(msg, FIX::LocaleOfIssue{\"STRING_652649423\"}, Instrument_14);\n  set_field(msg, FIX::MaturityDate{\"LOCALMKTDATE_495093992\"}, Instrument_14);\n  set_field(msg, FIX::MaturityMonthYear{\"MONTHYEAR_718872298\"}, Instrument_14);\n  set_field(msg, FIX::MaturityTime{\"TZTIMEONLY_256255820\"}, Instrument_14);\n  FIX::MinPriceIncrement MinPriceIncrement_14;\n  MinPriceIncrement_14.setString(\"10434477\");\nset_field(msg, MinPriceIncrement_14, Instrument_14);\n  FIX::MinPriceIncrementAmount MinPriceIncrementAmount_14;\n  MinPriceIncrementAmount_14.setString(\"15089342\");\nset_field(msg, MinPriceIncrementAmount_14, Instrument_14);\n  set_field(msg, FIX::NTPositionLimit{1744760343}, Instrument_14);\n  FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_14;\n  NotionalPercentageOutstanding_14.setString(\"41.410000\");\nset_field(msg, NotionalPercentageOutstanding_14, Instrument_14);\n  set_field(msg, FIX::OptAttribute{'5'}, Instrument_14);\n  FIX::OptPayoutAmount OptPayoutAmount_14;\n  OptPayoutAmount_14.setString(\"18346453\");\nset_field(msg, OptPayoutAmount_14, Instrument_14);\n  set_field(msg, FIX::OptPayoutType{3}, Instrument_14);\n  FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_14;\n  OriginalNotionalPercentageOutstanding_14.setString(\"73.940000\");\nset_field(msg, OriginalNotionalPercentageOutstanding_14, Instrument_14);\n  set_field(msg, FIX::Pool{\"STRING_1312399023\"}, Instrument_14);\n  set_field(msg, FIX::PositionLimit{1347350285}, Instrument_14);\n  set_field(msg, FIX::PriceQuoteMethod{\"STRING_INT\"}, Instrument_14);\n  set_field(msg, FIX::PriceUnitOfMeasure{\"STRING_714054076\"}, Instrument_14);\n  FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_14;\n  PriceUnitOfMeasureQty_14.setString(\"10073278\");\nset_field(msg, PriceUnitOfMeasureQty_14, Instrument_14);\n  set_field(msg, FIX::Product{10}, Instrument_14);\n  set_field(msg, FIX::ProductComplex{\"STRING_1760415687\"}, Instrument_14);\n  set_field(msg, FIX::PutOrCall{1}, Instrument_14);\n  set_field(msg, FIX::RedemptionDate{\"LOCALMKTDATE_1201723659\"}, Instrument_14);\n  set_field(msg, FIX::RepoCollateralSecurityType{\"STRING_1970116830\"}, Instrument_14);\n  FIX::RepurchaseRate RepurchaseRate_14;\n  RepurchaseRate_14.setString(\"37.300000\");\nset_field(msg, RepurchaseRate_14, Instrument_14);\n  set_field(msg, FIX::RepurchaseTerm{1918352841}, Instrument_14);\n  set_field(msg, FIX::RestructuringType{\"STRING_XR\"}, Instrument_14);\n  set_field(msg, FIX::SecurityDesc{\"STRING_2067261868\"}, Instrument_14);\n  set_field(msg, FIX::SecurityExchange{\"EXCHANGE_166733482\"}, Instrument_14);\n  set_field(msg, FIX::SecurityGroup{\"STRING_1647249703\"}, Instrument_14);\n  set_field(msg, FIX::SecurityID{\"STRING_1473248329\"}, Instrument_14);\n  set_field(msg, FIX::SecurityIDSource{\"STRING_K\"}, Instrument_14);\n  set_field(msg, FIX::SecurityStatus{\"STRING_1\"}, Instrument_14);\n  set_field(msg, FIX::SecuritySubType{\"STRING_2125897753\"}, Instrument_14);\n  set_field(msg, FIX::SecurityType{\"STRING_MPT\"}, Instrument_14);\n  set_field(msg, FIX::Seniority{\"STRING_SR\"}, Instrument_14);\n  set_field(msg, FIX::SettlMethod{'P'}, Instrument_14);\n  set_field(msg, FIX::SettleOnOpenFlag{\"STRING_1620588667\"}, Instrument_14);\n  set_field(msg, FIX::StateOrProvinceOfIssue{\"STRING_1627311653\"}, Instrument_14);\n  set_field(msg, FIX::StrikeCurrency{\"JPY\"}, Instrument_14);\n  FIX::StrikeMultiplier StrikeMultiplier_14;\n  StrikeMultiplier_14.setString(\"686515\");\nset_field(msg, StrikeMultiplier_14, Instrument_14);\n  FIX::StrikePrice StrikePrice_14;\n  StrikePrice_14.setString(\"16665919\");\nset_field(msg, StrikePrice_14, Instrument_14);\n  set_field(msg, FIX::StrikePriceBoundaryMethod{1}, Instrument_14);\n  FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_14;\n  StrikePriceBoundaryPrecision_14.setString(\"89.850000\");\nset_field(msg, StrikePriceBoundaryPrecision_14, Instrument_14);\n  set_field(msg, FIX::StrikePriceDeterminationMethod{1}, Instrument_14);\n  FIX::StrikeValue StrikeValue_14;\n  StrikeValue_14.setString(\"10777511\");\nset_field(msg, StrikeValue_14, Instrument_14);\n  set_field(msg, FIX::Symbol{\"STRING_1957142927\"}, Instrument_14);\n  set_field(msg, FIX::SymbolSfx{\"STRING_CD\"}, Instrument_14);\n  set_field(msg, FIX::TimeUnit{\"STRING_Yr\"}, Instrument_14);\n  set_field(msg, FIX::UnderlyingPriceDeterminationMethod{2}, Instrument_14);\n  set_field(msg, FIX::UnitOfMeasure{\"STRING_Alw\"}, Instrument_14);\n  FIX::UnitOfMeasureQty UnitOfMeasureQty_14;\n  UnitOfMeasureQty_14.setString(\"10690874\");\nset_field(msg, UnitOfMeasureQty_14, Instrument_14);\n  set_field(msg, FIX::ValuationMethod{\"STRING_EQTY\"}, Instrument_14);\n  all_values.push_back(Instrument_14);\n  all_compo_names.insert(\".\");\n\n  // ComplexEvents\n  // Group ComplexEvents.NoComplexEvents\n  {\n    FIX50SP2::Confirmation::NoComplexEvents noComplexEvents_0_0;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_25;\n    set_field(noComplexEvents_0_0, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_25);\n    FIX::ComplexEventPrice ComplexEventPrice_25;\n    ComplexEventPrice_25.setString(\"13999099\");\nset_field(noComplexEvents_0_0, ComplexEventPrice_25, ComplexEvents_NoComplexEvents_25);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceBoundaryMethod{1}, ComplexEvents_NoComplexEvents_25);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_25;\n    ComplexEventPriceBoundaryPrecision_25.setString(\"93.880000\");\nset_field(noComplexEvents_0_0, ComplexEventPriceBoundaryPrecision_25, ComplexEvents_NoComplexEvents_25);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceTimeType{2}, ComplexEvents_NoComplexEvents_25);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventType{9}, ComplexEvents_NoComplexEvents_25);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_25;\n    ComplexOptPayoutAmount_25.setString(\"13993340\");\nset_field(noComplexEvents_0_0, ComplexOptPayoutAmount_25, ComplexEvents_NoComplexEvents_25);\n    all_values.push_back(ComplexEvents_NoComplexEvents_25);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_51;\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(23, 19, 17, 20, 3, 2014)}, ComplexEventDates_NoComplexEventDates_51);\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(23, 13, 54, 15, 12, 2012)}, ComplexEventDates_NoComplexEventDates_51);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_51);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_124;\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(15, 58, 40)}, ComplexEventTimes_NoComplexEventTimes_124);\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(0, 12, 53)}, ComplexEventTimes_NoComplexEventTimes_124);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_124);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_0);\n      }\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_125;\n        set_field(noComplexEventTimes_0_0_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(10, 23, 48)}, ComplexEventTimes_NoComplexEventTimes_125);\n        set_field(noComplexEventTimes_0_0_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(17, 10, 12)}, ComplexEventTimes_NoComplexEventTimes_125);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_125);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_1);\n      }\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_126;\n        set_field(noComplexEventTimes_0_0_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(9, 31, 46)}, ComplexEventTimes_NoComplexEventTimes_126);\n        set_field(noComplexEventTimes_0_0_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(14, 48, 51)}, ComplexEventTimes_NoComplexEventTimes_126);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_126);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_2);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_52;\n      set_field(noComplexEventDates_0_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(17, 45, 48, 20, 8, 2006)}, ComplexEventDates_NoComplexEventDates_52);\n      set_field(noComplexEventDates_0_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(10, 26, 55, 17, 3, 2017)}, ComplexEventDates_NoComplexEventDates_52);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_52);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_127;\n        set_field(noComplexEventTimes_0_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(22, 42, 3)}, ComplexEventTimes_NoComplexEventTimes_127);\n        set_field(noComplexEventTimes_0_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(3, 13, 9)}, ComplexEventTimes_NoComplexEventTimes_127);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_127);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_0);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_1);\n    }\n    {\n      FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_2;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_53;\n      set_field(noComplexEventDates_0_1_2, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(15, 33, 18, 9, 12, 2010)}, ComplexEventDates_NoComplexEventDates_53);\n      set_field(noComplexEventDates_0_1_2, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(16, 52, 57, 16, 5, 2008)}, ComplexEventDates_NoComplexEventDates_53);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_53);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_2_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_128;\n        set_field(noComplexEventTimes_0_2_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(11, 26, 38)}, ComplexEventTimes_NoComplexEventTimes_128);\n        set_field(noComplexEventTimes_0_2_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(9, 30, 11)}, ComplexEventTimes_NoComplexEventTimes_128);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_128);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_2.addGroup(noComplexEventTimes_0_2_2_0);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_2);\n    }\n    msg.addGroup(noComplexEvents_0_0);\n  }\n  {\n    FIX50SP2::Confirmation::NoComplexEvents noComplexEvents_0_1;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_26;\n    set_field(noComplexEvents_0_1, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_26);\n    FIX::ComplexEventPrice ComplexEventPrice_26;\n    ComplexEventPrice_26.setString(\"14203760\");\nset_field(noComplexEvents_0_1, ComplexEventPrice_26, ComplexEvents_NoComplexEvents_26);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceBoundaryMethod{2}, ComplexEvents_NoComplexEvents_26);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_26;\n    ComplexEventPriceBoundaryPrecision_26.setString(\"49.220000\");\nset_field(noComplexEvents_0_1, ComplexEventPriceBoundaryPrecision_26, ComplexEvents_NoComplexEvents_26);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceTimeType{2}, ComplexEvents_NoComplexEvents_26);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventType{2}, ComplexEvents_NoComplexEvents_26);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_26;\n    ComplexOptPayoutAmount_26.setString(\"11105501\");\nset_field(noComplexEvents_0_1, ComplexOptPayoutAmount_26, ComplexEvents_NoComplexEvents_26);\n    all_values.push_back(ComplexEvents_NoComplexEvents_26);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_54;\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(7, 7, 40, 24, 11, 2015)}, ComplexEventDates_NoComplexEventDates_54);\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(18, 23, 1, 2, 4, 2003)}, ComplexEventDates_NoComplexEventDates_54);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_54);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_129;\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(8, 57, 5)}, ComplexEventTimes_NoComplexEventTimes_129);\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(18, 35, 56)}, ComplexEventTimes_NoComplexEventTimes_129);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_129);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_0);\n      }\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_130;\n        set_field(noComplexEventTimes_1_0_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(3, 42, 44)}, ComplexEventTimes_NoComplexEventTimes_130);\n        set_field(noComplexEventTimes_1_0_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(12, 32, 55)}, ComplexEventTimes_NoComplexEventTimes_130);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_130);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_1);\n      }\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_131;\n        set_field(noComplexEventTimes_1_0_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(3, 54, 26)}, ComplexEventTimes_NoComplexEventTimes_131);\n        set_field(noComplexEventTimes_1_0_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(5, 57, 51)}, ComplexEventTimes_NoComplexEventTimes_131);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_131);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_2);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_55;\n      set_field(noComplexEventDates_1_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(8, 52, 54, 24, 6, 2006)}, ComplexEventDates_NoComplexEventDates_55);\n      set_field(noComplexEventDates_1_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(18, 21, 44, 27, 8, 2008)}, ComplexEventDates_NoComplexEventDates_55);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_55);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_132;\n        set_field(noComplexEventTimes_1_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(15, 58, 29)}, ComplexEventTimes_NoComplexEventTimes_132);\n        set_field(noComplexEventTimes_1_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(22, 53, 23)}, ComplexEventTimes_NoComplexEventTimes_132);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_132);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_0);\n      }\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_133;\n        set_field(noComplexEventTimes_1_1_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(0, 17, 26)}, ComplexEventTimes_NoComplexEventTimes_133);\n        set_field(noComplexEventTimes_1_1_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(2, 24, 26)}, ComplexEventTimes_NoComplexEventTimes_133);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_133);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_1);\n      }\n      {\n        FIX50SP2::Confirmation::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_134;\n        set_field(noComplexEventTimes_1_1_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(12, 18, 36)}, ComplexEventTimes_NoComplexEventTimes_134);\n        set_field(noComplexEventTimes_1_1_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(3, 0, 11)}, ComplexEventTimes_NoComplexEventTimes_134);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_134);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_2);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_1);\n    }\n    msg.addGroup(noComplexEvents_0_1);\n  }\n  // EvntGrp\n  // Group EvntGrp.NoEvents\n  {\n    FIX50SP2::Confirmation::NoEvents noEvents_0_0;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_35;\n    set_field(noEvents_0_0, FIX::EventDate{\"LOCALMKTDATE_442817654\"}, EvntGrp_NoEvents_35);\n    FIX::EventPx EventPx_35;\n    EventPx_35.setString(\"15379158\");\nset_field(noEvents_0_0, EventPx_35, EvntGrp_NoEvents_35);\n    set_field(noEvents_0_0, FIX::EventText{\"STRING_809329072\"}, EvntGrp_NoEvents_35);\n    set_field(noEvents_0_0, FIX::EventTime{FIX::UTCTIMESTAMP(20, 8, 42, 23, 7, 2017)}, EvntGrp_NoEvents_35);\n    set_field(noEvents_0_0, FIX::EventType{12}, EvntGrp_NoEvents_35);\n    all_values.push_back(EvntGrp_NoEvents_35);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_0);\n  }\n  // InstrumentParties\n  // Group InstrumentParties.NoInstrumentParties\n  {\n    FIX50SP2::Confirmation::NoInstrumentParties noInstrumentParties_0_0;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_28;\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyID{\"STRING_1702777324\"}, InstrumentParties_NoInstrumentParties_28);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyIDSource{'2'}, InstrumentParties_NoInstrumentParties_28);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyRole{856923620}, InstrumentParties_NoInstrumentParties_28);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_28);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::Confirmation::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_57;\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubID{\"STRING_1054874004\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_57);\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubIDType{1875962566}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_57);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_57);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_58;\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubID{\"STRING_1865489547\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_58);\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubIDType{1478170550}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_58);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_58);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_1);\n    }\n    msg.addGroup(noInstrumentParties_0_0);\n  }\n  {\n    FIX50SP2::Confirmation::NoInstrumentParties noInstrumentParties_0_1;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_29;\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyID{\"STRING_1378430042\"}, InstrumentParties_NoInstrumentParties_29);\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_29);\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyRole{1564019672}, InstrumentParties_NoInstrumentParties_29);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_29);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::Confirmation::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_59;\n      set_field(noInstrumentPartySubIDs_1_1_0, FIX::InstrumentPartySubID{\"STRING_1723203963\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_59);\n      set_field(noInstrumentPartySubIDs_1_1_0, FIX::InstrumentPartySubIDType{574182540}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_59);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_59);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_1.addGroup(noInstrumentPartySubIDs_1_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_60;\n      set_field(noInstrumentPartySubIDs_1_1_1, FIX::InstrumentPartySubID{\"STRING_1497710351\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_60);\n      set_field(noInstrumentPartySubIDs_1_1_1, FIX::InstrumentPartySubIDType{684122687}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_60);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_60);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_1.addGroup(noInstrumentPartySubIDs_1_1_1);\n    }\n    msg.addGroup(noInstrumentParties_0_1);\n  }\n  {\n    FIX50SP2::Confirmation::NoInstrumentParties noInstrumentParties_0_2;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_30;\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyID{\"STRING_15880313\"}, InstrumentParties_NoInstrumentParties_30);\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_30);\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyRole{672637332}, InstrumentParties_NoInstrumentParties_30);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_30);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::Confirmation::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_61;\n      set_field(noInstrumentPartySubIDs_2_1_0, FIX::InstrumentPartySubID{\"STRING_1119183491\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_61);\n      set_field(noInstrumentPartySubIDs_2_1_0, FIX::InstrumentPartySubIDType{1481966405}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_61);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_61);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_2.addGroup(noInstrumentPartySubIDs_2_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_62;\n      set_field(noInstrumentPartySubIDs_2_1_1, FIX::InstrumentPartySubID{\"STRING_1425988504\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_62);\n      set_field(noInstrumentPartySubIDs_2_1_1, FIX::InstrumentPartySubIDType{2146286119}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_62);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_62);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_2.addGroup(noInstrumentPartySubIDs_2_1_1);\n    }\n    msg.addGroup(noInstrumentParties_0_2);\n  }\n  // SecAltIDGrp\n  // Group SecAltIDGrp.NoSecurityAltID\n  {\n    FIX50SP2::Confirmation::NoSecurityAltID noSecurityAltID_0_0;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_36;\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltID{\"STRING_72117759\"}, SecAltIDGrp_NoSecurityAltID_36);\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltIDSource{\"STRING_117779786\"}, SecAltIDGrp_NoSecurityAltID_36);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_36);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_0);\n  }\n  {\n    FIX50SP2::Confirmation::NoSecurityAltID noSecurityAltID_0_1;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_37;\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltID{\"STRING_2085904751\"}, SecAltIDGrp_NoSecurityAltID_37);\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltIDSource{\"STRING_1456537430\"}, SecAltIDGrp_NoSecurityAltID_37);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_37);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_1);\n  }\n  {\n    FIX50SP2::Confirmation::NoSecurityAltID noSecurityAltID_0_2;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_38;\n    set_field(noSecurityAltID_0_2, FIX::SecurityAltID{\"STRING_1595689278\"}, SecAltIDGrp_NoSecurityAltID_38);\n    set_field(noSecurityAltID_0_2, FIX::SecurityAltIDSource{\"STRING_1166358743\"}, SecAltIDGrp_NoSecurityAltID_38);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_38);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_2);\n  }\n  // SecurityXML\n  multiset<string> SecurityXML_28;\n  set_field(msg, FIX::SecurityXML{\"XMLDATA_1011831107\"}, SecurityXML_28);\n  set_field(msg, FIX::SecurityXMLLen{1472092644}, SecurityXML_28);\n  set_field(msg, FIX::SecurityXMLSchema{\"STRING_2023282363\"}, SecurityXML_28);\n  all_values.push_back(SecurityXML_28);\n  all_compo_names.insert(\"..\");\n\n  // InstrumentExtension\n  multiset<string> InstrumentExtension_3;\n  set_field(msg, FIX::DeliveryForm{2}, InstrumentExtension_3);\n  FIX::PctAtRisk PctAtRisk_3;\n  PctAtRisk_3.setString(\"30.000000\");\nset_field(msg, PctAtRisk_3, InstrumentExtension_3);\n  all_values.push_back(InstrumentExtension_3);\n  all_compo_names.insert(\".\");\n\n  // AttrbGrp\n  // Group AttrbGrp.NoInstrAttrib\n  {\n    FIX50SP2::Confirmation::NoInstrAttrib noInstrAttrib_0_0;\n    // AttrbGrp.NoInstrAttrib\n    multiset<string> AttrbGrp_NoInstrAttrib_5;\n    set_field(noInstrAttrib_0_0, FIX::InstrAttribType{22}, AttrbGrp_NoInstrAttrib_5);\n    set_field(noInstrAttrib_0_0, FIX::InstrAttribValue{\"STRING_1857653551\"}, AttrbGrp_NoInstrAttrib_5);\n    all_values.push_back(AttrbGrp_NoInstrAttrib_5);\n    all_compo_names.insert(\"....NoInstrAttrib\");\n\n    msg.addGroup(noInstrAttrib_0_0);\n  }\n  // MiscFeesGrp\n  // Group MiscFeesGrp.NoMiscFees\n  {\n    FIX50SP2::Confirmation::NoMiscFees noMiscFees_0_0;\n    // MiscFeesGrp.NoMiscFees\n    multiset<string> MiscFeesGrp_NoMiscFees_25;\n    FIX::MiscFeeAmt MiscFeeAmt_25;\n    MiscFeeAmt_25.setString(\"2743441\");\nset_field(noMiscFees_0_0, MiscFeeAmt_25, MiscFeesGrp_NoMiscFees_25);\n    set_field(noMiscFees_0_0, FIX::MiscFeeBasis{1}, MiscFeesGrp_NoMiscFees_25);\n    set_field(noMiscFees_0_0, FIX::MiscFeeCurr{\"JPY\"}, MiscFeesGrp_NoMiscFees_25);\n    set_field(noMiscFees_0_0, FIX::MiscFeeType{\"STRING_11\"}, MiscFeesGrp_NoMiscFees_25);\n    all_values.push_back(MiscFeesGrp_NoMiscFees_25);\n    all_compo_names.insert(\"...NoMiscFees\");\n\n    msg.addGroup(noMiscFees_0_0);\n  }\n  {\n    FIX50SP2::Confirmation::NoMiscFees noMiscFees_0_1;\n    // MiscFeesGrp.NoMiscFees\n    multiset<string> MiscFeesGrp_NoMiscFees_26;\n    FIX::MiscFeeAmt MiscFeeAmt_26;\n    MiscFeeAmt_26.setString(\"5584511\");\nset_field(noMiscFees_0_1, MiscFeeAmt_26, MiscFeesGrp_NoMiscFees_26);\n    set_field(noMiscFees_0_1, FIX::MiscFeeBasis{1}, MiscFeesGrp_NoMiscFees_26);\n    set_field(noMiscFees_0_1, FIX::MiscFeeCurr{\"CAN\"}, MiscFeesGrp_NoMiscFees_26);\n    set_field(noMiscFees_0_1, FIX::MiscFeeType{\"STRING_6\"}, MiscFeesGrp_NoMiscFees_26);\n    all_values.push_back(MiscFeesGrp_NoMiscFees_26);\n    all_compo_names.insert(\"...NoMiscFees\");\n\n    msg.addGroup(noMiscFees_0_1);\n  }\n  // OrdAllocGrp\n  // Group OrdAllocGrp.NoOrders\n  {\n    FIX50SP2::Confirmation::NoOrders noOrders_0_0;\n    // OrdAllocGrp.NoOrders\n    multiset<string> OrdAllocGrp_NoOrders_7;\n    set_field(noOrders_0_0, FIX::ClOrdID{\"STRING_1258902256\"}, OrdAllocGrp_NoOrders_7);\n    set_field(noOrders_0_0, FIX::ListID{\"STRING_541307248\"}, OrdAllocGrp_NoOrders_7);\n    FIX::OrderAvgPx OrderAvgPx_7;\n    OrderAvgPx_7.setString(\"16014552\");\nset_field(noOrders_0_0, OrderAvgPx_7, OrdAllocGrp_NoOrders_7);\n    FIX::OrderBookingQty OrderBookingQty_7;\n    OrderBookingQty_7.setString(\"12577047\");\nset_field(noOrders_0_0, OrderBookingQty_7, OrdAllocGrp_NoOrders_7);\n    set_field(noOrders_0_0, FIX::OrderID{\"STRING_589918533\"}, OrdAllocGrp_NoOrders_7);\n    FIX::OrderQty OrderQty_7;\n    OrderQty_7.setString(\"16735730\");\nset_field(noOrders_0_0, OrderQty_7, OrdAllocGrp_NoOrders_7);\n    set_field(noOrders_0_0, FIX::SecondaryClOrdID{\"STRING_1375484514\"}, OrdAllocGrp_NoOrders_7);\n    set_field(noOrders_0_0, FIX::SecondaryOrderID{\"STRING_528339636\"}, OrdAllocGrp_NoOrders_7);\n    all_values.push_back(OrdAllocGrp_NoOrders_7);\n    all_compo_names.insert(\"...NoOrders\");\n\n    // NestedParties2\n    // Group NestedParties2.NoNested2PartyIDs\n    {\n      FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs noNested2PartyIDs_0_1_0;\n      // NestedParties2.NoNested2PartyIDs\n      multiset<string> NestedParties2_NoNested2PartyIDs_12;\n      set_field(noNested2PartyIDs_0_1_0, FIX::Nested2PartyID{\"STRING_823690144\"}, NestedParties2_NoNested2PartyIDs_12);\n      set_field(noNested2PartyIDs_0_1_0, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_12);\n      set_field(noNested2PartyIDs_0_1_0, FIX::Nested2PartyRole{1994457901}, NestedParties2_NoNested2PartyIDs_12);\n      all_values.push_back(NestedParties2_NoNested2PartyIDs_12);\n      all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs\");\n\n      // NstdPtys2SubGrp\n      // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n      {\n        FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_2_0;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_22;\n        set_field(noNested2PartySubIDs_0_0_2_0, FIX::Nested2PartySubID{\"STRING_1570497094\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_22);\n        set_field(noNested2PartySubIDs_0_0_2_0, FIX::Nested2PartySubIDType{559997844}, NstdPtys2SubGrp_NoNested2PartySubIDs_22);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_22);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_0.addGroup(noNested2PartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_2_1;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_23;\n        set_field(noNested2PartySubIDs_0_0_2_1, FIX::Nested2PartySubID{\"STRING_527782141\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_23);\n        set_field(noNested2PartySubIDs_0_0_2_1, FIX::Nested2PartySubIDType{1174774728}, NstdPtys2SubGrp_NoNested2PartySubIDs_23);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_23);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_0.addGroup(noNested2PartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_2_2;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_24;\n        set_field(noNested2PartySubIDs_0_0_2_2, FIX::Nested2PartySubID{\"STRING_991027335\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_24);\n        set_field(noNested2PartySubIDs_0_0_2_2, FIX::Nested2PartySubIDType{237952044}, NstdPtys2SubGrp_NoNested2PartySubIDs_24);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_24);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_0.addGroup(noNested2PartySubIDs_0_0_2_2);\n      }\n      noOrders_0_0.addGroup(noNested2PartyIDs_0_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs noNested2PartyIDs_0_1_1;\n      // NestedParties2.NoNested2PartyIDs\n      multiset<string> NestedParties2_NoNested2PartyIDs_13;\n      set_field(noNested2PartyIDs_0_1_1, FIX::Nested2PartyID{\"STRING_9998756\"}, NestedParties2_NoNested2PartyIDs_13);\n      set_field(noNested2PartyIDs_0_1_1, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_13);\n      set_field(noNested2PartyIDs_0_1_1, FIX::Nested2PartyRole{1512141619}, NestedParties2_NoNested2PartyIDs_13);\n      all_values.push_back(NestedParties2_NoNested2PartyIDs_13);\n      all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs\");\n\n      // NstdPtys2SubGrp\n      // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n      {\n        FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_2_0;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_25;\n        set_field(noNested2PartySubIDs_0_1_2_0, FIX::Nested2PartySubID{\"STRING_1115435964\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_25);\n        set_field(noNested2PartySubIDs_0_1_2_0, FIX::Nested2PartySubIDType{1213030087}, NstdPtys2SubGrp_NoNested2PartySubIDs_25);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_25);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_1.addGroup(noNested2PartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_2_1;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_26;\n        set_field(noNested2PartySubIDs_0_1_2_1, FIX::Nested2PartySubID{\"STRING_1776674313\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_26);\n        set_field(noNested2PartySubIDs_0_1_2_1, FIX::Nested2PartySubIDType{1649623123}, NstdPtys2SubGrp_NoNested2PartySubIDs_26);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_26);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_1.addGroup(noNested2PartySubIDs_0_1_2_1);\n      }\n      noOrders_0_0.addGroup(noNested2PartyIDs_0_1_1);\n    }\n    {\n      FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs noNested2PartyIDs_0_1_2;\n      // NestedParties2.NoNested2PartyIDs\n      multiset<string> NestedParties2_NoNested2PartyIDs_14;\n      set_field(noNested2PartyIDs_0_1_2, FIX::Nested2PartyID{\"STRING_929798868\"}, NestedParties2_NoNested2PartyIDs_14);\n      set_field(noNested2PartyIDs_0_1_2, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_14);\n      set_field(noNested2PartyIDs_0_1_2, FIX::Nested2PartyRole{708963966}, NestedParties2_NoNested2PartyIDs_14);\n      all_values.push_back(NestedParties2_NoNested2PartyIDs_14);\n      all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs\");\n\n      // NstdPtys2SubGrp\n      // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n      {\n        FIX50SP2::Confirmation::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_2_2_0;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_27;\n        set_field(noNested2PartySubIDs_0_2_2_0, FIX::Nested2PartySubID{\"STRING_1027811687\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_27);\n        set_field(noNested2PartySubIDs_0_2_2_0, FIX::Nested2PartySubIDType{1250271215}, NstdPtys2SubGrp_NoNested2PartySubIDs_27);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_27);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_2.addGroup(noNested2PartySubIDs_0_2_2_0);\n      }\n      noOrders_0_0.addGroup(noNested2PartyIDs_0_1_2);\n    }\n    msg.addGroup(noOrders_0_0);\n  }\n  // Parties\n  // Group Parties.NoPartyIDs\n  {\n    FIX50SP2::Confirmation::NoPartyIDs noPartyIDs_0_0;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_32;\n    set_field(noPartyIDs_0_0, FIX::PartyID{\"STRING_138032767\"}, Parties_NoPartyIDs_32);\n    set_field(noPartyIDs_0_0, FIX::PartyIDSource{'E'}, Parties_NoPartyIDs_32);\n    set_field(noPartyIDs_0_0, FIX::PartyRole{58}, Parties_NoPartyIDs_32);\n    all_values.push_back(Parties_NoPartyIDs_32);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::Confirmation::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_69;\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubID{\"STRING_221045737\"}, PtysSubGrp_NoPartySubIDs_69);\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubIDType{20}, PtysSubGrp_NoPartySubIDs_69);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_69);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_1;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_70;\n      set_field(noPartySubIDs_0_1_1, FIX::PartySubID{\"STRING_189723777\"}, PtysSubGrp_NoPartySubIDs_70);\n      set_field(noPartySubIDs_0_1_1, FIX::PartySubIDType{1}, PtysSubGrp_NoPartySubIDs_70);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_70);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_1);\n    }\n    msg.addGroup(noPartyIDs_0_0);\n  }\n  // SettlInstructionsData\n  multiset<string> SettlInstructionsData_11;\n  set_field(msg, FIX::SettlDeliveryType{3}, SettlInstructionsData_11);\n  set_field(msg, FIX::StandInstDbID{\"STRING_338022917\"}, SettlInstructionsData_11);\n  set_field(msg, FIX::StandInstDbName{\"STRING_1338757563\"}, SettlInstructionsData_11);\n  set_field(msg, FIX::StandInstDbType{1}, SettlInstructionsData_11);\n  all_values.push_back(SettlInstructionsData_11);\n  all_compo_names.insert(\".\");\n\n  // DlvyInstGrp\n  // Group DlvyInstGrp.NoDlvyInst\n  {\n    FIX50SP2::Confirmation::NoDlvyInst noDlvyInst_0_0;\n    // DlvyInstGrp.NoDlvyInst\n    multiset<string> DlvyInstGrp_NoDlvyInst_18;\n    set_field(noDlvyInst_0_0, FIX::DlvyInstType{'S'}, DlvyInstGrp_NoDlvyInst_18);\n    set_field(noDlvyInst_0_0, FIX::SettlInstSource{'3'}, DlvyInstGrp_NoDlvyInst_18);\n    all_values.push_back(DlvyInstGrp_NoDlvyInst_18);\n    all_compo_names.insert(\"....NoDlvyInst\");\n\n    // SettlParties\n    // Group SettlParties.NoSettlPartyIDs\n    {\n      FIX50SP2::Confirmation::NoDlvyInst::NoSettlPartyIDs noSettlPartyIDs_0_1_0;\n      // SettlParties.NoSettlPartyIDs\n      multiset<string> SettlParties_NoSettlPartyIDs_33;\n      set_field(noSettlPartyIDs_0_1_0, FIX::SettlPartyID{\"STRING_376047399\"}, SettlParties_NoSettlPartyIDs_33);\n      set_field(noSettlPartyIDs_0_1_0, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_33);\n      set_field(noSettlPartyIDs_0_1_0, FIX::SettlPartyRole{468415074}, SettlParties_NoSettlPartyIDs_33);\n      all_values.push_back(SettlParties_NoSettlPartyIDs_33);\n      all_compo_names.insert(\"....NoDlvyInst...NoSettlPartyIDs\");\n\n      // SettlPtysSubGrp\n      // Group SettlPtysSubGrp.NoSettlPartySubIDs\n      {\n        FIX50SP2::Confirmation::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_2_0;\n        // SettlPtysSubGrp.NoSettlPartySubIDs\n        multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_66;\n        set_field(noSettlPartySubIDs_0_0_2_0, FIX::SettlPartySubID{\"STRING_551792971\"}, SettlPtysSubGrp_NoSettlPartySubIDs_66);\n        set_field(noSettlPartySubIDs_0_0_2_0, FIX::SettlPartySubIDType{1681445161}, SettlPtysSubGrp_NoSettlPartySubIDs_66);\n        all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_66);\n        all_compo_names.insert(\"....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n        noSettlPartyIDs_0_1_0.addGroup(noSettlPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::Confirmation::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_2_1;\n        // SettlPtysSubGrp.NoSettlPartySubIDs\n        multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_67;\n        set_field(noSettlPartySubIDs_0_0_2_1, FIX::SettlPartySubID{\"STRING_1223461247\"}, SettlPtysSubGrp_NoSettlPartySubIDs_67);\n        set_field(noSettlPartySubIDs_0_0_2_1, FIX::SettlPartySubIDType{53932446}, SettlPtysSubGrp_NoSettlPartySubIDs_67);\n        all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_67);\n        all_compo_names.insert(\"....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n        noSettlPartyIDs_0_1_0.addGroup(noSettlPartySubIDs_0_0_2_1);\n      }\n      noDlvyInst_0_0.addGroup(noSettlPartyIDs_0_1_0);\n    }\n    msg.addGroup(noDlvyInst_0_0);\n  }\n  // SpreadOrBenchmarkCurveData\n  multiset<string> SpreadOrBenchmarkCurveData_8;\n  set_field(msg, FIX::BenchmarkCurveCurrency{\"USD\"}, SpreadOrBenchmarkCurveData_8);\n  set_field(msg, FIX::BenchmarkCurveName{\"STRING_EUREPO\"}, SpreadOrBenchmarkCurveData_8);\n  set_field(msg, FIX::BenchmarkCurvePoint{\"STRING_1569025998\"}, SpreadOrBenchmarkCurveData_8);\n  FIX::BenchmarkPrice BenchmarkPrice_8;\n  BenchmarkPrice_8.setString(\"20201823\");\nset_field(msg, BenchmarkPrice_8, SpreadOrBenchmarkCurveData_8);\n  set_field(msg, FIX::BenchmarkPriceType{2013167628}, SpreadOrBenchmarkCurveData_8);\n  set_field(msg, FIX::BenchmarkSecurityID{\"STRING_2128263219\"}, SpreadOrBenchmarkCurveData_8);\n  set_field(msg, FIX::BenchmarkSecurityIDSource{\"STRING_10731485\"}, SpreadOrBenchmarkCurveData_8);\n  FIX::Spread Spread_8;\n  Spread_8.setString(\"17058737\");\nset_field(msg, Spread_8, SpreadOrBenchmarkCurveData_8);\n  all_values.push_back(SpreadOrBenchmarkCurveData_8);\n  all_compo_names.insert(\".\");\n\n  // Stipulations\n  // Group Stipulations.NoStipulations\n  {\n    FIX50SP2::Confirmation::NoStipulations noStipulations_0_0;\n    // Stipulations.NoStipulations\n    multiset<string> Stipulations_NoStipulations_20;\n    set_field(noStipulations_0_0, FIX::StipulationType{\"STRING_WALA\"}, Stipulations_NoStipulations_20);\n    set_field(noStipulations_0_0, FIX::StipulationValue{\"STRING_1926919465\"}, Stipulations_NoStipulations_20);\n    all_values.push_back(Stipulations_NoStipulations_20);\n    all_compo_names.insert(\"...NoStipulations\");\n\n    msg.addGroup(noStipulations_0_0);\n  }\n  {\n    FIX50SP2::Confirmation::NoStipulations noStipulations_0_1;\n    // Stipulations.NoStipulations\n    multiset<string> Stipulations_NoStipulations_21;\n    set_field(noStipulations_0_1, FIX::StipulationType{\"STRING_LOT\"}, Stipulations_NoStipulations_21);\n    set_field(noStipulations_0_1, FIX::StipulationValue{\"STRING_1713972543\"}, Stipulations_NoStipulations_21);\n    all_values.push_back(Stipulations_NoStipulations_21);\n    all_compo_names.insert(\"...NoStipulations\");\n\n    msg.addGroup(noStipulations_0_1);\n  }\n  // TrdRegTimestamps\n  // Group TrdRegTimestamps.NoTrdRegTimestamps\n  {\n    FIX50SP2::Confirmation::NoTrdRegTimestamps noTrdRegTimestamps_0_0;\n    // TrdRegTimestamps.NoTrdRegTimestamps\n    multiset<string> TrdRegTimestamps_NoTrdRegTimestamps_13;\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskOrderHandlingInst{\"MULTIPLESTRINGVALUE_IO\"}, TrdRegTimestamps_NoTrdRegTimestamps_13);\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskType{\"STRING_S\"}, TrdRegTimestamps_NoTrdRegTimestamps_13);\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskTypeSource{1}, TrdRegTimestamps_NoTrdRegTimestamps_13);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestamp{FIX::UTCTIMESTAMP(7, 32, 37, 9, 12, 2003)}, TrdRegTimestamps_NoTrdRegTimestamps_13);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestampOrigin{\"STRING_195005399\"}, TrdRegTimestamps_NoTrdRegTimestamps_13);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestampType{4}, TrdRegTimestamps_NoTrdRegTimestamps_13);\n    all_values.push_back(TrdRegTimestamps_NoTrdRegTimestamps_13);\n    all_compo_names.insert(\"...NoTrdRegTimestamps\");\n\n    msg.addGroup(noTrdRegTimestamps_0_0);\n  }\n  // UndInstrmtGrp\n  // Group UndInstrmtGrp.NoUnderlyings\n  {\n    FIX50SP2::Confirmation::NoUnderlyings noUnderlyings_0_0;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_21;\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuer{\"DATA_1876450561\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuerLen{151314424}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDesc{\"DATA_1736980583\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDescLen{192727295}, UnderlyingInstrument_21);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_21;\n    UnderlyingAdjustedQuantity_21.setString(\"11436851\");\nset_field(noUnderlyings_0_0, UnderlyingAdjustedQuantity_21, UnderlyingInstrument_21);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_21;\n    UnderlyingAllocationPercent_21.setString(\"33.480000\");\nset_field(noUnderlyings_0_0, UnderlyingAllocationPercent_21, UnderlyingInstrument_21);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_21;\n    UnderlyingAttachmentPoint_21.setString(\"32.930000\");\nset_field(noUnderlyings_0_0, UnderlyingAttachmentPoint_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCFICode{\"STRING_1016383821\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPProgram{\"STRING_218077328\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPRegType{\"STRING_1742532865\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingCapValue UnderlyingCapValue_21;\n    UnderlyingCapValue_21.setString(\"10271153\");\nset_field(noUnderlyings_0_0, UnderlyingCapValue_21, UnderlyingInstrument_21);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_21;\n    UnderlyingCashAmount_21.setString(\"19239510\");\nset_field(noUnderlyings_0_0, UnderlyingCashAmount_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCashType{\"STRING_DIFF\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_21;\n    UnderlyingContractMultiplier_21.setString(\"4038804\");\nset_field(noUnderlyings_0_0, UnderlyingContractMultiplier_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingContractMultiplierUnit{1703386874}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCountryOfIssue{\"COUNTRY_795214907\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_2117852967\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_21;\n    UnderlyingCouponRate_21.setString(\"31.600000\");\nset_field(noUnderlyings_0_0, UnderlyingCouponRate_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCreditRating{\"STRING_696718425\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCurrency{\"EUR\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_21;\n    UnderlyingCurrentValue_21.setString(\"20731474\");\nset_field(noUnderlyings_0_0, UnderlyingCurrentValue_21, UnderlyingInstrument_21);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_21;\n    UnderlyingDetachmentPoint_21.setString(\"80.020000\");\nset_field(noUnderlyings_0_0, UnderlyingDetachmentPoint_21, UnderlyingInstrument_21);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_21;\n    UnderlyingDirtyPrice_21.setString(\"12425558\");\nset_field(noUnderlyings_0_0, UnderlyingDirtyPrice_21, UnderlyingInstrument_21);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_21;\n    UnderlyingEndPrice_21.setString(\"16205619\");\nset_field(noUnderlyings_0_0, UnderlyingEndPrice_21, UnderlyingInstrument_21);\n    FIX::UnderlyingEndValue UnderlyingEndValue_21;\n    UnderlyingEndValue_21.setString(\"3717883\");\nset_field(noUnderlyings_0_0, UnderlyingEndValue_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingExerciseStyle{723622096}, UnderlyingInstrument_21);\n    FIX::UnderlyingFXRate UnderlyingFXRate_21;\n    UnderlyingFXRate_21.setString(\"6043334\");\nset_field(noUnderlyings_0_0, UnderlyingFXRate_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFXRateCalc{'M'}, UnderlyingInstrument_21);\n    FIX::UnderlyingFactor UnderlyingFactor_21;\n    UnderlyingFactor_21.setString(\"17989589\");\nset_field(noUnderlyings_0_0, UnderlyingFactor_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFlowScheduleType{139897934}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingInstrRegistry{\"STRING_295760640\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_1950273345\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssuer{\"STRING_1876878517\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingLocaleOfIssue{\"STRING_488487935\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_946474800\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_81788217\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_102757581\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_21;\n    UnderlyingNotionalPercentageOutstanding_21.setString(\"86.210000\");\nset_field(noUnderlyings_0_0, UnderlyingNotionalPercentageOutstanding_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingOptAttribute{'2'}, UnderlyingInstrument_21);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_21;\n    UnderlyingOriginalNotionalPercentageOutstanding_21.setString(\"4.460000\");\nset_field(noUnderlyings_0_0, UnderlyingOriginalNotionalPercentageOutstanding_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_842490279\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_21;\n    UnderlyingPriceUnitOfMeasureQty_21.setString(\"763329\");\nset_field(noUnderlyings_0_0, UnderlyingPriceUnitOfMeasureQty_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingProduct{1506445819}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPutOrCall{1246370703}, UnderlyingInstrument_21);\n    FIX::UnderlyingPx UnderlyingPx_21;\n    UnderlyingPx_21.setString(\"17797198\");\nset_field(noUnderlyings_0_0, UnderlyingPx_21, UnderlyingInstrument_21);\n    FIX::UnderlyingQty UnderlyingQty_21;\n    UnderlyingQty_21.setString(\"1541770\");\nset_field(noUnderlyings_0_0, UnderlyingQty_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_1216740022\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_883319340\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_21;\n    UnderlyingRepurchaseRate_21.setString(\"55.040000\");\nset_field(noUnderlyings_0_0, UnderlyingRepurchaseRate_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepurchaseTerm{1091621154}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRestructuringType{\"STRING_873372701\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityDesc{\"STRING_776559275\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityExchange{\"EXCHANGE_1736819156\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityID{\"STRING_2115928554\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityIDSource{\"STRING_249637556\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecuritySubType{\"STRING_2108607484\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityType{\"STRING_692067002\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSeniority{\"STRING_853971002\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlMethod{\"STRING_527917564\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlementType{5}, UnderlyingInstrument_21);\n    FIX::UnderlyingStartValue UnderlyingStartValue_21;\n    UnderlyingStartValue_21.setString(\"9938689\");\nset_field(noUnderlyings_0_0, UnderlyingStartValue_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_823678204\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStrikeCurrency{\"JPY\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_21;\n    UnderlyingStrikePrice_21.setString(\"13121661\");\nset_field(noUnderlyings_0_0, UnderlyingStrikePrice_21, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbol{\"STRING_1092806773\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbolSfx{\"STRING_805052024\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingTimeUnit{\"STRING_1414923721\"}, UnderlyingInstrument_21);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingUnitOfMeasure{\"STRING_908181746\"}, UnderlyingInstrument_21);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_21;\n    UnderlyingUnitOfMeasureQty_21.setString(\"11049175\");\nset_field(noUnderlyings_0_0, UnderlyingUnitOfMeasureQty_21, UnderlyingInstrument_21);\n    all_values.push_back(UnderlyingInstrument_21);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_43;\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltID{\"STRING_1750672026\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_43);\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_1181250523\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_43);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_43);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_0);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_36;\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipType{\"STRING_849559081\"}, UnderlyingStipulations_NoUnderlyingStips_36);\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipValue{\"STRING_813486703\"}, UnderlyingStipulations_NoUnderlyingStips_36);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_36);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_1;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_37;\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipType{\"STRING_625869768\"}, UnderlyingStipulations_NoUnderlyingStips_37);\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipValue{\"STRING_2066299104\"}, UnderlyingStipulations_NoUnderlyingStips_37);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_37);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_1);\n    }\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_2;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_38;\n      set_field(noUnderlyingStips_0_1_2, FIX::UnderlyingStipType{\"STRING_1696806043\"}, UnderlyingStipulations_NoUnderlyingStips_38);\n      set_field(noUnderlyingStips_0_1_2, FIX::UnderlyingStipValue{\"STRING_1476765272\"}, UnderlyingStipulations_NoUnderlyingStips_38);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_38);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_2);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_43;\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_422695096\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_43);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_43);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyRole{599772118}, UndlyInstrumentParties_NoUndlyInstrumentParties_43);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_43);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_82;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_355478456\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_82);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{560895955}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_82);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_82);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_83;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1083207004\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_83);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{1209449459}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_83);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_83);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_84;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_1088813519\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_84);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_2, FIX::UnderlyingInstrumentPartySubIDType{1426749279}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_84);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_84);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_2);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_44;\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_55834748\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_44);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_44);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyRole{1573081252}, UndlyInstrumentParties_NoUndlyInstrumentParties_44);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_44);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_85;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1077174215\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_85);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{518404377}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_85);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_85);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_0);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_1);\n    }\n    msg.addGroup(noUnderlyings_0_0);\n  }\n  {\n    FIX50SP2::Confirmation::NoUnderlyings noUnderlyings_0_1;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_22;\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuer{\"DATA_1584150578\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuerLen{344614288}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDesc{\"DATA_1426586123\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDescLen{541584500}, UnderlyingInstrument_22);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_22;\n    UnderlyingAdjustedQuantity_22.setString(\"14573448\");\nset_field(noUnderlyings_0_1, UnderlyingAdjustedQuantity_22, UnderlyingInstrument_22);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_22;\n    UnderlyingAllocationPercent_22.setString(\"45.010000\");\nset_field(noUnderlyings_0_1, UnderlyingAllocationPercent_22, UnderlyingInstrument_22);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_22;\n    UnderlyingAttachmentPoint_22.setString(\"50.230000\");\nset_field(noUnderlyings_0_1, UnderlyingAttachmentPoint_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCFICode{\"STRING_1929037497\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPProgram{\"STRING_1879333583\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPRegType{\"STRING_388838079\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingCapValue UnderlyingCapValue_22;\n    UnderlyingCapValue_22.setString(\"4074236\");\nset_field(noUnderlyings_0_1, UnderlyingCapValue_22, UnderlyingInstrument_22);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_22;\n    UnderlyingCashAmount_22.setString(\"17981490\");\nset_field(noUnderlyings_0_1, UnderlyingCashAmount_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCashType{\"STRING_FIXED\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_22;\n    UnderlyingContractMultiplier_22.setString(\"18841888\");\nset_field(noUnderlyings_0_1, UnderlyingContractMultiplier_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingContractMultiplierUnit{661102001}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCountryOfIssue{\"COUNTRY_360855571\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_1990029790\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_22;\n    UnderlyingCouponRate_22.setString(\"41.190000\");\nset_field(noUnderlyings_0_1, UnderlyingCouponRate_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCreditRating{\"STRING_751995573\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCurrency{\"JPY\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_22;\n    UnderlyingCurrentValue_22.setString(\"18352025\");\nset_field(noUnderlyings_0_1, UnderlyingCurrentValue_22, UnderlyingInstrument_22);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_22;\n    UnderlyingDetachmentPoint_22.setString(\"40.580000\");\nset_field(noUnderlyings_0_1, UnderlyingDetachmentPoint_22, UnderlyingInstrument_22);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_22;\n    UnderlyingDirtyPrice_22.setString(\"7630999\");\nset_field(noUnderlyings_0_1, UnderlyingDirtyPrice_22, UnderlyingInstrument_22);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_22;\n    UnderlyingEndPrice_22.setString(\"11144682\");\nset_field(noUnderlyings_0_1, UnderlyingEndPrice_22, UnderlyingInstrument_22);\n    FIX::UnderlyingEndValue UnderlyingEndValue_22;\n    UnderlyingEndValue_22.setString(\"14633088\");\nset_field(noUnderlyings_0_1, UnderlyingEndValue_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingExerciseStyle{528108021}, UnderlyingInstrument_22);\n    FIX::UnderlyingFXRate UnderlyingFXRate_22;\n    UnderlyingFXRate_22.setString(\"5400658\");\nset_field(noUnderlyings_0_1, UnderlyingFXRate_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFXRateCalc{'D'}, UnderlyingInstrument_22);\n    FIX::UnderlyingFactor UnderlyingFactor_22;\n    UnderlyingFactor_22.setString(\"16052822\");\nset_field(noUnderlyings_0_1, UnderlyingFactor_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFlowScheduleType{1058470190}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingInstrRegistry{\"STRING_1679074291\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_1949896525\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssuer{\"STRING_337572666\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingLocaleOfIssue{\"STRING_73175143\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_1259757684\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_1367347167\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_1796010166\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_22;\n    UnderlyingNotionalPercentageOutstanding_22.setString(\"15.340000\");\nset_field(noUnderlyings_0_1, UnderlyingNotionalPercentageOutstanding_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_22);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_22;\n    UnderlyingOriginalNotionalPercentageOutstanding_22.setString(\"45.970000\");\nset_field(noUnderlyings_0_1, UnderlyingOriginalNotionalPercentageOutstanding_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_1448735152\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_22;\n    UnderlyingPriceUnitOfMeasureQty_22.setString(\"7498624\");\nset_field(noUnderlyings_0_1, UnderlyingPriceUnitOfMeasureQty_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingProduct{2123008720}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPutOrCall{1185440394}, UnderlyingInstrument_22);\n    FIX::UnderlyingPx UnderlyingPx_22;\n    UnderlyingPx_22.setString(\"14109644\");\nset_field(noUnderlyings_0_1, UnderlyingPx_22, UnderlyingInstrument_22);\n    FIX::UnderlyingQty UnderlyingQty_22;\n    UnderlyingQty_22.setString(\"3363806\");\nset_field(noUnderlyings_0_1, UnderlyingQty_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_1027986537\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_524354966\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_22;\n    UnderlyingRepurchaseRate_22.setString(\"62.160000\");\nset_field(noUnderlyings_0_1, UnderlyingRepurchaseRate_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepurchaseTerm{1226011136}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRestructuringType{\"STRING_198641392\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityDesc{\"STRING_776095146\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityExchange{\"EXCHANGE_486001546\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityID{\"STRING_961741338\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityIDSource{\"STRING_1890563356\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecuritySubType{\"STRING_1949310352\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityType{\"STRING_1489849359\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSeniority{\"STRING_283145521\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlMethod{\"STRING_2044234064\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlementType{2}, UnderlyingInstrument_22);\n    FIX::UnderlyingStartValue UnderlyingStartValue_22;\n    UnderlyingStartValue_22.setString(\"13416157\");\nset_field(noUnderlyings_0_1, UnderlyingStartValue_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_1575824707\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStrikeCurrency{\"JPY\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_22;\n    UnderlyingStrikePrice_22.setString(\"16489998\");\nset_field(noUnderlyings_0_1, UnderlyingStrikePrice_22, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbol{\"STRING_2009818509\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbolSfx{\"STRING_899051897\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingTimeUnit{\"STRING_1297526369\"}, UnderlyingInstrument_22);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingUnitOfMeasure{\"STRING_903646395\"}, UnderlyingInstrument_22);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_22;\n    UnderlyingUnitOfMeasureQty_22.setString(\"19982490\");\nset_field(noUnderlyings_0_1, UnderlyingUnitOfMeasureQty_22, UnderlyingInstrument_22);\n    all_values.push_back(UnderlyingInstrument_22);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_1_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_44;\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltID{\"STRING_204897899\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_44);\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_600627845\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_44);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_44);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingSecurityAltID_1_1_0);\n    }\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_1_1_1;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_45;\n      set_field(noUnderlyingSecurityAltID_1_1_1, FIX::UnderlyingSecurityAltID{\"STRING_1310416038\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_45);\n      set_field(noUnderlyingSecurityAltID_1_1_1, FIX::UnderlyingSecurityAltIDSource{\"STRING_1390338293\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_45);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_45);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingSecurityAltID_1_1_1);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_1_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_39;\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipType{\"STRING_1646796681\"}, UnderlyingStipulations_NoUnderlyingStips_39);\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipValue{\"STRING_270841182\"}, UnderlyingStipulations_NoUnderlyingStips_39);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_39);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingStips_1_1_0);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_45;\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_587689250\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_45);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_45);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyRole{587105050}, UndlyInstrumentParties_NoUndlyInstrumentParties_45);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_45);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_86;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1982853864\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_86);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{1548846388}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_86);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_86);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_87;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1106864104\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_87);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{1784680568}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_87);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_87);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::Confirmation::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_88;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_891212099\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_88);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_2, FIX::UnderlyingInstrumentPartySubIDType{1390009626}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_88);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_88);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_2);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_0);\n    }\n    msg.addGroup(noUnderlyings_0_1);\n  }\n  // YieldData\n  multiset<string> YieldData_3;\n  FIX::Yield Yield_3;\n  Yield_3.setString(\"9.850000\");\nset_field(msg, Yield_3, YieldData_3);\n  set_field(msg, FIX::YieldCalcDate{\"LOCALMKTDATE_1838860047\"}, YieldData_3);\n  set_field(msg, FIX::YieldRedemptionDate{\"LOCALMKTDATE_584141690\"}, YieldData_3);\n  FIX::YieldRedemptionPrice YieldRedemptionPrice_3;\n  YieldRedemptionPrice_3.setString(\"11097720\");\nset_field(msg, YieldRedemptionPrice_3, YieldData_3);\n  set_field(msg, FIX::YieldRedemptionPriceType{441437223}, YieldData_3);\n  set_field(msg, FIX::YieldType{\"STRING_OPENAVG\"}, YieldData_3);\n  all_values.push_back(YieldData_3);\n  all_compo_names.insert(\".\");\n\n  // header\n  multiset<string> header_20;\n  set_header_field(msg.getHeader(), FIX::ApplVerID{\"STRING_7\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::BeginString{\"STRING_303772084\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::BodyLength{1014898317}, header_20);\n  set_header_field(msg.getHeader(), FIX::CstmApplVerID{\"STRING_1908814616\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::DeliverToCompID{\"STRING_1207418479\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{\"STRING_865663669\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::DeliverToSubID{\"STRING_1096221934\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{1412316378}, header_20);\n  set_header_field(msg.getHeader(), FIX::MessageEncoding{\"STRING_UTF-8\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::MsgSeqNum{259154325}, header_20);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{\"STRING_655171024\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{\"STRING_1330400207\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{\"STRING_1905951006\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(17, 48, 17, 3, 10, 2009)}, header_20);\n  set_header_field(msg.getHeader(), FIX::PossDupFlag{true}, header_20);\n  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_20);\n  set_header_field(msg.getHeader(), FIX::SecureData{\"DATA_1895431662\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::SecureDataLen{451060107}, header_20);\n  set_header_field(msg.getHeader(), FIX::SenderCompID{\"STRING_2059331087\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::SenderLocationID{\"STRING_1429378999\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::SenderSubID{\"STRING_142436506\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(19, 50, 9, 10, 7, 2013)}, header_20);\n  set_header_field(msg.getHeader(), FIX::TargetCompID{\"STRING_764286610\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::TargetLocationID{\"STRING_2095064294\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::TargetSubID{\"STRING_344913888\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::XmlData{\"DATA_1860508545\"}, header_20);\n  set_header_field(msg.getHeader(), FIX::XmlDataLen{1359897024}, header_20);\n  all_values.push_back(header_20);\n  all_compo_names.insert(\".header\");\n\n\n  xml_element elt;\n  converter.fix2fixml(msg, elt);\n  BOOST_LOG_TRIVIAL(debug) << \"The resulting XML is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << elt.to_string() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n\n  BOOST_LOG_TRIVIAL(debug) << \"Quickfix XML representation is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << msg.toXML() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n  list<multiset<string>> elt_lists;\n  elt.to_list(elt_lists);\n  EXPECT_EQ(elt_lists.size(), all_values.size());\n\n  if (elt_lists.size() != all_values.size())  {\n    multiset<string> elt_compo_name;\n    elt.all_components(elt_compo_name);\n    BOOST_LOG_TRIVIAL(debug) << \"XML Elements are:\";\n    cout << \"\t[\";\n    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n    BOOST_LOG_TRIVIAL(debug) << \"FIX Components are:\"; \n    cout << \"\t[\";\n    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All FIX components\";\n  for (const auto& l : all_values) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All XML components\";\n  for (const auto& l : elt_lists) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n\n  }\n\n  for (const auto& xml_l : elt_lists) {\n    bool found = false;\n    for (const auto& l : all_values) {\n      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {\n        found = true;\n        break;\n      } // end if includes\n    } // end for all_values\n    EXPECT_TRUE(found);\n    if ( ! found) {\n      BOOST_LOG_TRIVIAL(debug) << \"[TO CHECK] This XML component was not found in FIX message\";\n      cout << \"\t ---> [\";\n      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, \" \"));      cout << \"]\" << endl << endl;\n    } // end if ! found\n  } // end for elt_lists\n}\n", "meta": {"hexsha": "312337b4b806c0aecb22dde8f0dc2d78b29765c9", "size": 105411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/generated/fix2xml/test_fix2xml_Confirmation.cpp", "max_stars_repo_name": "abdelkaderamar/fix2xml", "max_stars_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T12:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T12:08:19.000Z", "max_issues_repo_path": "tools/generated/fix2xml/test_fix2xml_Confirmation.cpp", "max_issues_repo_name": "abdelkaderamar/fix2xml", "max_issues_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_issues_repo_licenses": ["MIT"], "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/generated/fix2xml/test_fix2xml_Confirmation.cpp", "max_forks_repo_name": "abdelkaderamar/fix2xml", "max_forks_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T04:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T04:11:44.000Z", "avg_line_length": 61.5359019264, "max_line_length": 173, "alphanum_fraction": 0.8023261329, "num_tokens": 31350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.2814055953761019, "lm_q1q2_score": 0.16465073865380467}}
{"text": "// Copyright (c) 2014 The Bitcoin Core developers\n// Copyright (c) 2014-2015 The Dash developers\n// Copyright (c) 2015-2017 The PIVX developers \n// Copyright (c) 2015-2017 The ALQO developers\n// Copyright (C) 2019 The ICC 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 \"primitives/transaction.h\"\n#include \"main.h\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(main_tests)\n\nCAmount nMoneySupplyPoWEnd = 5000 * COIN;\n\nBOOST_AUTO_TEST_CASE(subsidy_limit_test)\n{\n    CAmount nSum = 0;\n    for (int nHeight = 0; nHeight < 1; nHeight += 1) {\n        /* premine in block 1 */\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 200000 * COIN);\n        nSum += nSubsidy;\n    }\n\n    for (int nHeight = 1; nHeight < 501; nHeight += 1) {\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 0 * COIN);\n        nSum += nSubsidy;\n    }\n    for (int nHeight = 501; nHeight < 20001; nHeight += 1) {\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 10 * COIN);\n        nSum += nSubsidy;\n    }\n    for (int nHeight = 20001; nHeight < 40001; nHeight += 1) {\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 15 * COIN);\n        nSum += nSubsidy;\n    }\n    for (int nHeight = 40001; nHeight < 262801; nHeight += 1) {\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 20 * COIN);\n        nSum += nSubsidy;\n    }\n    for (int nHeight = 262801; nHeight < 525601; nHeight += 1) {\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 10 * COIN);\n        nSum += nSubsidy;\n    }\n    for (int nHeight = 525601; nHeight < 788401; nHeight += 1) {\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 8 * COIN);\n        nSum += nSubsidy;\n    }\n    for (int nHeight = 788401; nHeight < 1051201; nHeight += 1) {\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 6 * COIN);\n        nSum += nSubsidy;\n    }\n    for (int nHeight = 1051201; nHeight < 1314001; nHeight += 1) {\n        CAmount nSubsidy = GetBlockValue(nHeight);\n        BOOST_CHECK(nSubsidy <= 4 * COIN);\n        nSum += nSubsidy;\n    }\n\tBOOST_CHECK(nSum > 0 && nSum <= nMoneySupplyPoWEnd);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e90a595e8f39df6befa7dd4765d125f24a582832", "size": 2437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/main_tests.cpp", "max_stars_repo_name": "InternetCafeCoin/ICC-CORE-OLD", "max_stars_repo_head_hexsha": "b63046643b40db1abd623a03a8f921ec306b1190", "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/test/main_tests.cpp", "max_issues_repo_name": "InternetCafeCoin/ICC-CORE-OLD", "max_issues_repo_head_hexsha": "b63046643b40db1abd623a03a8f921ec306b1190", "max_issues_repo_licenses": ["MIT"], "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/main_tests.cpp", "max_forks_repo_name": "InternetCafeCoin/ICC-CORE-OLD", "max_forks_repo_head_hexsha": "b63046643b40db1abd623a03a8f921ec306b1190", "max_forks_repo_licenses": ["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.8472222222, "max_line_length": 71, "alphanum_fraction": 0.6286417727, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1646505872521337}}
{"text": "#include <fstream>\n#include <iostream>\n#include <algorithm>\n#include <thread>\n#include <numeric>\n\n#include \"succinct/mapper.hpp\"\n\n#include \"configuration.hpp\"\n#include \"util.hpp\"\n#include \"verify_collection.hpp\"\n#include \"index_build_utils.hpp\"\n\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/copy.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"clustered_index_types.hpp\"\n#include \"clustered_binary_freq_collection.hpp\"\n#include \"partitioned_sequence.hpp\"\n#include \"reference_selector.hpp\"\n\nusing ds2i::logger;\n\nvoid create_clustered_collection(ds2i::clustered_binary_freq_collection& input,\n                                 ds2i::global_parameters const& params,\n                                 const char* cluster_filename,\n                                 const char* output_filename,\n                                 bool check,\n                                 uint32_t MAX_REF_SIZE,\n                                 uint32_t divisor)\n{\n    using namespace ds2i;\n    uint64_t universe = input.num_docs();\n    logger() << \"Processing \" << universe << \" documents\" << std::endl;\n    double tick = get_time_usecs();\n    double user_tick = get_user_time_usecs();\n    clustered_opt_index::builder builder(universe, params);\n    progress_logger plog;\n\n    std::ifstream file(cluster_filename, std::ios_base::in | std::ios_base::binary);\n    boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;\n    inbuf.push(boost::iostreams::gzip_decompressor());\n    inbuf.push(file);\n    std::istream instream(&inbuf);\n\n    std::string line;\n    uint32_t c = 1;\n    std::vector<sequence_t> partitions;\n    std::vector<pos_t> docs_positions;\n    std::vector<pos_t> freqs_positions;\n    while (std::getline(instream, line))\n    {\n        std::vector<std::string> data;\n        boost::split(data, line, boost::is_any_of(\" \"));\n        uint32_t cluster_size = std::atoi(data.front().data());\n\n        std::cout << \"cluster_size: \" << cluster_size << std::endl;\n\n        docs_positions.reserve(cluster_size);\n        freqs_positions.reserve(cluster_size);\n\n        std::for_each(++data.begin(), data.end(),\n            [&docs_positions, &freqs_positions](const std::string& s)\n            {\n                pos_t p = std::stoull(s.data());\n                docs_positions.push_back(p);\n                freqs_positions.push_back(p - 2);\n            });\n\n        input.add_positions(docs_positions, freqs_positions);\n        input.set_positions();\n\n        partitions.clear();\n        partitions.reserve(cluster_size);\n\n        for (auto const& plist : input)\n        {\n            auto const& docs = plist.docs;\n            partitions.push_back(\n                std::move(\n                    ds2i::partitioned_sequence<>::compute_partition(docs.begin(),\n                                                                    universe,\n                                                                    docs.size(),\n                                                                    params)\n                        )\n                );\n        }\n\n        reference_selector rs(input, partitions, params, cluster_size, MAX_REF_SIZE);\n        sequence_t reference = rs.select_reference(divisor);\n\n        std::cout << \"reference size: \" << reference.size() << std::endl;\n\n        builder.add_reference(reference.size(), reference.begin());\n        uint32_t i = 0;\n        for (auto const& plist : input)\n        {\n            uint64_t freqs_sum =\n                std::accumulate(plist.freqs.begin(),\n                                plist.freqs.end(),\n                                uint64_t(0));\n            builder.add_posting_list(plist.docs,\n                                     plist.freqs,\n                                     freqs_sum,\n                                     partitions[i++]);\n            plog.done_sequence(plist.docs.size());\n        }\n        logger() << \"cluster-\" << c++ << \" encoded\" << std::endl;\n\n        docs_positions.clear();\n        freqs_positions.clear();\n    }\n\n    file.close();\n    plog.log();\n    clustered_opt_index coll;\n    builder.build(coll);\n    double elapsed_secs = (get_time_usecs() - tick) / 1000000;\n    double user_elapsed_secs = (get_user_time_usecs() - user_tick) / 1000000;\n    logger() << \"clustered_opt collection built in \"\n             << elapsed_secs << \" seconds\" << std::endl;\n\n    stats_line()\n        (\"type\", \"clustered_opt_greedy\")\n        (\"worker_threads\", configuration::get().worker_threads)\n        (\"construction_time\", elapsed_secs)\n        (\"construction_user_time\", user_elapsed_secs)\n        ;\n\n    dump_stats(coll, \"clustered_opt\", plog.postings);\n\n    if (output_filename) {\n        succinct::mapper::freeze(coll, output_filename);\n        if (check) {\n            verify_clustered_collection(input, output_filename);\n        }\n    }\n}\n\nint main(int argc, const char** argv)\n{\n    using namespace ds2i;\n\n    if (argc < 5) {\n        std::cerr << \"Usage: \" << argv[0]\n                  << \" <collection basename> <cluster filename> <MAX_REF_SIZE> <divisor> [<output filename>] [--check]\"\n                  << std::endl;\n        std::cerr << \"<divisor> represents the amount by which the number of candidates is divided to define the length of an apoch\"\n                  << std::endl;\n        return 1;\n    }\n\n    const char* input_basename = argv[1];\n    const char* cluster_filename = argv[2];\n    const uint32_t MAX_REF_SIZE = std::atoi(argv[3]);\n    const uint32_t divisor = std::atoi(argv[4]);\n\n    const char* output_filename = nullptr;\n    if (argc > 5) {\n        output_filename = argv[5];\n    }\n\n    bool check = false;\n    if (argc > 6 && std::string(argv[6]) == \"--check\") {\n        check = true;\n    }\n\n    clustered_binary_freq_collection input(input_basename, check);\n    global_parameters params;\n    params.log_partition_size = configuration::get().log_partition_size;\n    create_clustered_collection(\n        input, params, cluster_filename,\n        output_filename, check, MAX_REF_SIZE, divisor\n    );\n\n    return 0;\n}\n", "meta": {"hexsha": "7960522b36ab814c36e9b70ca0a8e2bdd36f6464", "size": 6087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "create_clustered_freq_index_sb.cpp", "max_stars_repo_name": "jermp/clustered_elias_fano_indexes", "max_stars_repo_head_hexsha": "545323c40a503cc8a61e0a765843a9edcbdd217d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-09-03T04:14:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:45:48.000Z", "max_issues_repo_path": "create_clustered_freq_index_sb.cpp", "max_issues_repo_name": "jermp/clustered_elias_fano_indexes", "max_issues_repo_head_hexsha": "545323c40a503cc8a61e0a765843a9edcbdd217d", "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": "create_clustered_freq_index_sb.cpp", "max_forks_repo_name": "jermp/clustered_elias_fano_indexes", "max_forks_repo_head_hexsha": "545323c40a503cc8a61e0a765843a9edcbdd217d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-12-16T06:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T09:52:11.000Z", "avg_line_length": 33.8166666667, "max_line_length": 132, "alphanum_fraction": 0.5736816166, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.16465058573778557}}
{"text": "#include \"conditional_algorithm.h\"\n\n#include <Eigen/Dense>\n\n#include \"base_algorithm.h\"\n#include \"src/collectors/base_collector.h\"\n#include \"src/mixings/conditional_mixing.h\"\n\nvoid ConditionalAlgorithm::initialize() {\n  BaseAlgorithm::initialize();\n  cond_mixing = std::dynamic_pointer_cast<ConditionalMixing>(mixing);\n}\n\n//! \\param grid Grid of points in matrix form to evaluate the density on\n//! \\param coll Collector containing the algorithm chain\nEigen::MatrixXd ConditionalAlgorithm::eval_lpdf(\n    BaseCollector *const collector, const Eigen::MatrixXd &grid,\n    const Eigen::MatrixXd &hier_covariates /*= Eigen::MatrixXd(0, 0)*/,\n    const Eigen::MatrixXd &mix_covariates /*= Eigen::MatrixXd(0, 0)*/) {\n  return Eigen::MatrixXd::Zero(1, 1);  // TODO\n}\n", "meta": {"hexsha": "9928516947322c4b97daf1d00dc39f75d703454a", "size": 760, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/algorithms/conditional_algorithm.cc", "max_stars_repo_name": "ricardaxel/bayesmix", "max_stars_repo_head_hexsha": "c9fb79c2f6fb05783adf31dd31030440413ae9cb", "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/algorithms/conditional_algorithm.cc", "max_issues_repo_name": "ricardaxel/bayesmix", "max_issues_repo_head_hexsha": "c9fb79c2f6fb05783adf31dd31030440413ae9cb", "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/algorithms/conditional_algorithm.cc", "max_forks_repo_name": "ricardaxel/bayesmix", "max_forks_repo_head_hexsha": "c9fb79c2f6fb05783adf31dd31030440413ae9cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T21:24:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T21:24:49.000Z", "avg_line_length": 34.5454545455, "max_line_length": 72, "alphanum_fraction": 0.7473684211, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.16465058573778557}}
{"text": "//\n// Copyright (c) 2011-2012 Krzysztof Jusiak (krzysztof at jusiak dot net)\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef QFSM_BACK_DETAIL_ORTHOGONALREGIONS_HPP\n#define QFSM_BACK_DETAIL_ORTHOGONALREGIONS_HPP\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/is_sequence.hpp>\n#include <boost/mpl/size.hpp>\n\nnamespace QFsm\n{\nnamespace Back\n{\n\ntemplate<typename TDerived>\nclass OrthogonalRegions\n{\npublic:\n    typedef boost::mpl::int_<1> OneRegion;\n    typedef boost::mpl::int_<0> FirstRegion;\n\n    QFSM_UML_EXTENSIONS\n    (\n        struct GetNumberOfOrthogonalRegions : boost::mpl::if_\n            <\n                boost::mpl::is_sequence<typename TDerived::InitialState>,\n                boost::mpl::size<typename TDerived::InitialState>,\n                boost::mpl::int_<1>\n            >\n        { };\n\n        typedef boost::mpl::int_<GetNumberOfOrthogonalRegions::type::value> NumberOfOrthogonalRegions;\n    )\n\n    QFSM_UML_EXTENSIONS_ELSE(\n        typedef OneRegion NumberOfOrthogonalRegions;\n    )\n\n    template<typename Size = NumberOfOrthogonalRegions, typename Region = FirstRegion, bool dummy = false> class ForEachRegion\n    {\n        typedef boost::mpl::int_<Region::value + OneRegion::value> NextRegion;\n\n    public:\n        template<typename T, typename Arg1> static void execute(Arg1& p_arg1)\n        {\n            T::template execute<Region>(p_arg1);\n            ForEachRegion<Size, NextRegion>::template execute<T>(p_arg1);\n        }\n\n        template<typename T, typename Arg1, typename Arg2> static void execute(Arg1& p_arg1, Arg2& p_arg2)\n        {\n            T::template execute<Region>(p_arg1, p_arg2);\n            ForEachRegion<Size, NextRegion>::template execute<T>(p_arg1, p_arg2);\n        }\n\n        template<typename T, typename Arg1, typename Arg2, typename Arg3> static void execute(Arg1& p_arg1, Arg2& p_arg2, Arg3& p_arg3)\n        {\n            T::template execute<Region>(p_arg1, p_arg2, p_arg3);\n            ForEachRegion<Size, NextRegion>::template execute<T>(p_arg1, p_arg2, p_arg3);\n        }\n    };\n\n    template<bool dummy> class ForEachRegion<OneRegion, FirstRegion, dummy>\n    {\n    public:\n        template<typename T, typename Arg1> static void execute(Arg1& p_arg1)\n        {\n            T::template execute<FirstRegion>(p_arg1);\n        }\n\n        template<typename T, typename Arg1, typename Arg2> static void execute(Arg1& p_arg1, Arg2& p_arg2)\n        {\n            T::template execute<FirstRegion>(p_arg1, p_arg2);\n        }\n\n        template<typename T, typename Arg1, typename Arg2, typename Arg3> static void execute(Arg1& p_arg1, Arg2& p_arg2, Arg3& p_arg3)\n        {\n            T::template execute<FirstRegion>(p_arg1, p_arg2, p_arg3);\n        }\n    };\n\n    template<bool dummy> class ForEachRegion<NumberOfOrthogonalRegions, NumberOfOrthogonalRegions, dummy>\n    {\n    public:\n        template<typename T, typename Arg1> static void execute(Arg1&) { }\n        template<typename T, typename Arg1, typename Arg2> static void execute(Arg1&, Arg2&) { }\n        template<typename T, typename Arg1, typename Arg2, typename Arg3> static void execute(Arg1&, Arg2&, Arg3&) { }\n    };\n};\n\n} // namespace Back\n} // namespace QFsm\n\n#endif\n\n", "meta": {"hexsha": "d23d2d293ec7cc8377ae41b6bc03f1d6441413af", "size": 3304, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QFsm/Back/Detail/OrthogonalRegions.hpp", "max_stars_repo_name": "krzysztof-jusiak/qfsm", "max_stars_repo_head_hexsha": "b339f8bdb7f4d2c65dc943cc84e0e0038552190c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T20:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T20:43:20.000Z", "max_issues_repo_path": "QFsm/Back/Detail/OrthogonalRegions.hpp", "max_issues_repo_name": "krzysztof-jusiak/qfsm", "max_issues_repo_head_hexsha": "b339f8bdb7f4d2c65dc943cc84e0e0038552190c", "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": "QFsm/Back/Detail/OrthogonalRegions.hpp", "max_forks_repo_name": "krzysztof-jusiak/qfsm", "max_forks_repo_head_hexsha": "b339f8bdb7f4d2c65dc943cc84e0e0038552190c", "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.04, "max_line_length": 135, "alphanum_fraction": 0.6619249395, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.16465057910587272}}
{"text": "\ufeff/* ============================================================================================== *\n *                                                                                                *\n *                                     Galaxia Blockchain                                         *\n *                                                                                                *\n * ---------------------------------------------------------------------------------------------- *\n * This file is part of the Xi framework.                                                         *\n * ---------------------------------------------------------------------------------------------- *\n *                                                                                                *\n * Copyright 2018-2019 Xi Project Developers <support.xiproject.io>                               *\n *                                                                                                *\n * This program is free software: you can redistribute it and/or modify it under the terms of the *\n * GNU General Public License as published by the Free Software Foundation, either version 3 of   *\n * the License, or (at your option) any later version.                                            *\n *                                                                                                *\n * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;      *\n * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.      *\n * See the GNU General Public License for more details.                                           *\n *                                                                                                *\n * You should have received a copy of the GNU General Public License along with this program.     *\n * If not, see <https://www.gnu.org/licenses/>.                                                   *\n *                                                                                                *\n * ============================================================================================== */\n\n#include \"Xi/Crypto/PasswordContainer.h\"\n\n#include <algorithm>\n#include <limits>\n\n#include <Xi/ExternalIncludePush.h>\n#include <openssl/evp.h>\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <Xi/ExternalIncludePop.h>\n\nXi::Crypto::PasswordContainer::PasswordContainer(const std::string &password) {\n  generateConfig();\n  m_hash = computeHash(password);\n}\n\nbool Xi::Crypto::PasswordContainer::validate(const std::string &password) const {\n  return hashEqual(m_hash, computeHash(password));\n}\n\nXi::Crypto::PasswordContainer::hash_t Xi::Crypto::PasswordContainer::computeHash(const std::string &password) const {\n  hash_t hash;\n  PKCS5_PBKDF2_HMAC_SHA1(password.data(), static_cast<int>(password.size()),\n                         reinterpret_cast<const uint8_t *>(m_salt.data()), static_cast<int>(m_salt.size()),\n                         static_cast<int>(m_iterations), static_cast<int>(hash.size()), hash.data());\n  return hash;\n}\n\nvoid Xi::Crypto::PasswordContainer::generateConfig() {\n  boost::random::random_device rng;\n  rng.generate(m_salt.begin(), m_salt.end());\n  boost::random::uniform_int_distribution<uint32_t> dist{std::numeric_limits<uint16_t>::max(),\n                                                         2u * std::numeric_limits<uint16_t>::max()};\n  m_iterations = dist(rng);\n}\n\nbool Xi::Crypto::PasswordContainer::hashEqual(const PasswordContainer::hash_t &lhs,\n                                              const PasswordContainer::hash_t &rhs) {\n  return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n}\n", "meta": {"hexsha": "3009117a147f2bc82b9631dde7dde534d5738c83", "size": 3793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Xi-Crypto/source/PasswordContainer.cpp", "max_stars_repo_name": "ElSamaritan/blockchain-OLD", "max_stars_repo_head_hexsha": "ca3422c8873613226db99b7e6735c5ea1fac9f1a", "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/Xi-Crypto/source/PasswordContainer.cpp", "max_issues_repo_name": "ElSamaritan/blockchain-OLD", "max_issues_repo_head_hexsha": "ca3422c8873613226db99b7e6735c5ea1fac9f1a", "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/Xi-Crypto/source/PasswordContainer.cpp", "max_forks_repo_name": "ElSamaritan/blockchain-OLD", "max_forks_repo_head_hexsha": "ca3422c8873613226db99b7e6735c5ea1fac9f1a", "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": 59.265625, "max_line_length": 117, "alphanum_fraction": 0.440284735, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.30735802955444114, "lm_q1q2_score": 0.1644667986403531}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SCALAR_TAN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SCALAR_TAN_HPP_INCLUDED\n\n#include <boost/simd/function/definition/tan.hpp>\n#include <boost/simd/arch/common/scalar/function/tan.hpp>\n\n#endif\n", "meta": {"hexsha": "d24105321afe7bb98d92341cd13ca1606e151a9b", "size": 605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/scalar/tan.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/scalar/tan.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/scalar/tan.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": 35.5882352941, "max_line_length": 100, "alphanum_fraction": 0.5338842975, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.16446679185039426}}
{"text": "#include \"mwoibn/hierarchical_control/controllers/wheels.h\"\n#include \"mwoibn/hierarchical_control/tasks/castor_angle_task.h\"\n#include <boost/range/adaptor/reversed.hpp>\n\nbool mwoibn::hierarchical_control::controllers::Wheels::_checkStack()\n{\n        _last_state.noalias() = _state;\n        bool stack = true;\n        for (int i = 0; i < _size; i++)\n        {\n//    bool high =\n//        _inversers_ptrs[_id_high]->getJacobian().row(i).isApproxToConstant(\n//            0, 1e-3);\n//    bool low =\n//        _inversers_ptrs[_id_low]->getJacobian().row(i).isApproxToConstant(0,\n//                                                                          1e-3);\n\n                if (_state[i] && _inversers_ptrs[_id_high]->getJacobian().row(i).cwiseAbs().maxCoeff() < 6e-3)\n                {\n                        //      std::cout << \"!high\\t\" <<\n                        //      _inversers_ptrs[_id_high]->getJacobian().row(i) << std::endl;\n                        _state[i] = 0;\n//      _values[i] = 0;\n                }\n                else if (!_state[i] && _inversers_ptrs[_id_high]->getJacobian().row(i).cwiseAbs().maxCoeff() > 8e-3)\n                {\n                        //      std::cout << \"!high\\t\" <<\n                        //      _inversers_ptrs[_id_high]->getJacobian().row(i) << std::endl;\n                        _state[i] = 1;\n//      _values[i] = 0;\n                }\n//    else if ()_state[i] = 1;\n//    else if (low)\n//    {\n//      //      std::cout << \"!low\\t\" <<\n//      //      _inversers_ptrs[_id_low]->getJacobian().row(i) << std::endl;\n\n//      _state[i] = 1;\n//      _values[i] = 100;\n//    }\n//    else\n//    {\n//      //      std::cout << \"compare\" << std::endl;\n//      double max_high =\n//          _inversers_ptrs[_id_high]->getJacobian().row(i).cwiseAbs().maxCoeff();\n//      double max_low =\n//          _inversers_ptrs[_id_low]->getJacobian().row(i).cwiseAbs().maxCoeff();\n\n                //      std::cout << \"max_high\" << max_high << std::endl;\n                //      std::cout << \"max_low\" << max_low<< std::endl;\n\n//      double value = max_high / max_low;\n//      if (value > 1.05)\n//        _state[i] = 1;\n//      else if (value < 0.95)\n//        _state[i] = 0;\n\n//      _values[i] = value;\n\n//          std::cout << \"high\\t\" << high << \"\\t\" <<\n//      //              <<\n//      //              << \"\\t\" <<\n//                    _inversers_ptrs[_id_high]->getJacobian().row(i)\n//                    << std::endl;\n//          std::cout << \"jacobian\\t\" << high << \"\\t\" <<\n//      //              <<\n//      //              << \"\\t\" <<\n//                    _task_high.getJacobian().row(i)\n//                    << std::endl;\n\n//          std::cout << \"low\\t\" << low << \"\\t\"\n//                    <<\n//                    _inversers_ptrs[_id_low]->getJacobian().row(i)  << std::endl;\n//    }\n\n                if(_state[i] != _last_state[i]) {\n                        tasks::CastorAngleTask& cast = dynamic_cast<tasks::CastorAngleTask&>(_task_low);\n                        if(!_state[i])\n                                cast.setReference(i, cast.getCurrent()[i]);\n//      else\n//        cast.setReference(i, -mwoibn::PI);\n                }\n\n                stack = stack && (_state[i] == _last_state[i]);\n        }\n\n////  if (!stack)\n////  {\n//    std::cout << _values.transpose() << \",\\t\" << _state.transpose()\n//              << std::endl;\n        std::cout << _state.transpose() << \"\\t\";\n//                << std::endl;\n        for (int i = 0; i < _size; i++) {\n                std::cout\n                << \"high: \"\n                << _inversers_ptrs[_id_high]->getJacobian().row(i).cwiseAbs().maxCoeff()\n                << \",\\t\"\n                << \" low: \"\n                << _inversers_ptrs[_id_low]->getJacobian().row(i).cwiseAbs().maxCoeff()         << \",\\t\";\n        }\n//    }\n//    std::cout << std::endl;\n//  //  std::cout << stack << std::endl;\n\n        return stack;\n}\n\nvoid mwoibn::hierarchical_control::controllers::Wheels::_findTasks()\n{\n        auto it = std::find_if(_tasks.begin(), _tasks.end(), [this](auto task){ return &task.get() == &(this->_task_high); });\n\n        if (it == _tasks.end())\n                throw(std::invalid_argument(\"mwoibn::hierarchical_control::controllers::Wheels: couldn't find a \"\n                                            \"task_high in a tasks stack.\"));\n        _id_high = it - _tasks.begin();\n\n        it = std::find_if(_tasks.begin(), _tasks.end(), [this](auto task){ return &task.get() == &(this->_task_low); });\n        // it = std::find(_tasks.begin(), _tasks.end(), _task_low);\n\n        if (it == _tasks.end())\n                throw(std::invalid_argument(\"mwoibn::hierarchical_control::controllers::Wheels: couldn't find a \"\n                                            \"task_low in a tasks stack.\"));\n        _id_low = it - _tasks.begin();\n}\n\n//void mwoibn::hierarchical_control::HierarchicalControllerWheels::_updateTask(\n//    int i, mwoibn::hierarchical_control::BasicTask* task)\n//{\n//  _errors[i].noalias() = -(_gains[i].asDiagonal() * task->getError());\n//  _errors[i].noalias() -= task->getJacobian() * _command;\n\n//  if (_errors[i].size())\n//  {\n//    _inversers_ptrs[i]->compute(task->getJacobian(), _P);\n//    _command.noalias() += _inversers_ptrs[i]->getInverse() * _errors[i];\n//  }\n//}\n\n\nvoid mwoibn::hierarchical_control::controllers::Wheels::compute()\n{\n        _command.setZero();\n        _P.setIdentity();\n\n        mwoibn::Matrix P_1 = _P, P_2 = _P;\n        int i = 0;\n\n        for (auto& task : _tasks)\n        {\n                if (_errors[i].size())\n                {\n                        if(&task.get() == &_task_high) {\n                                std::cout << i << std::endl;\n                                P_1 = _P; // just for now\n                        }\n                        if(&task.get() == &_task_low)\n                                P_2 = _P;  // just for now\n                        _inversers_ptrs[i]->compute(task.get().getJacobian(), _P);\n                }\n                ++i;\n        }\n\n        if (!_checkStack()) {\n                _P = P_2;\n                _task_low.update();\n                _inversers_ptrs[_id_low]->compute(_task_low.getJacobian(), _P);\n\n                _last_stack_change = 0;\n                std::cout << \"stack change detected\" << std::endl;\n        }\n\n//  i = 0;\n\n        for (int k = 0; k < _tasks.size()-2; k++)\n        {\n                auto& task = _tasks[k];\n\n                _errors[k].noalias() = -(_gains[k].asDiagonal() * task.get().getError());\n                _errors[k].noalias() -= task.get().getJacobian() * _command;\n\n                _command.noalias() += _inversers_ptrs[k]->getInverse() * _errors[k];\n\n        }\n\n//  i = _tasks_ptr.size()-2;\n        _errors[_id_high].noalias() = -(_gains[_id_high].asDiagonal() * _task_high.getError());\n        _errors[_id_high].noalias() -= _task_high.getJacobian() * _command;\n        _command.noalias() += _inversers_ptrs[_id_high]->getInverse() * _errors[_id_high];\n\n\n\n        _errors[_id_low].noalias() = -(_gains[_id_low].asDiagonal() * _task_low.getError());\n        _errors[_id_low].noalias() -= _task_low.getJacobian() * _command;\n\n        for (int j = 0; j < _task_low.getTaskSize(); j++) {\n                if(_state[j])\n                        _errors[_id_low][j] = 0;\n        }\n\n        _command.noalias() += _inversers_ptrs[_id_low]->getInverse() * _errors[_id_low];\n\n\n        if (!_last_stack_change)\n                _resetCorrection();\n\n        _g.setZero();\n        int cols = _g.cols();\n        _g_it.setIdentity();\n        i = _tasks.size()-1;\n        for (auto& task : boost::adaptors::reverse(_tasks))\n        {\n                cols -= task.get().getTaskSize();\n\n                __n_by_n1.setIdentity();\n                __n_by_n2.noalias() = _inversers_ptrs[i]->getInverse() * task.get().getJacobian();\n                __n_by_n1.noalias() -= __n_by_n2;\n                __n_by_n2.noalias() = _g_it * __n_by_n1;\n\n                _g_it.noalias() = __n_by_n2;\n\n                _g.block(0, cols, _robot.getDofs(), task.get().getTaskSize()) =\n                        _g_it * _inversers_ptrs[i]->getInverse();\n                i--;\n        }\n\n        ++_last_stack_change;\n\n        std::cout << \"exp\" << exp(-_mu * _last_stack_change *_robot.rate()) << std::endl;\n//   change with respect to the original\n        _command.noalias() +=\n                _g * _e * exp(-_mu * _last_stack_change *\n                              _robot.rate()); //! \\todo ** frequency should be an outside argument\n}\n", "meta": {"hexsha": "ef89ce1981e7d3d8b0f46a28bfeac5a0dfd620a4", "size": 8531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "locomotion_framework/controllers/hierarchical_control/src/controllers/wheels.cpp", "max_stars_repo_name": "ADVRHumanoids/DrivingFramework", "max_stars_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-02T07:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T07:10:42.000Z", "max_issues_repo_path": "locomotion_framework/controllers/hierarchical_control/src/controllers/wheels.cpp", "max_issues_repo_name": "ADVRHumanoids/DrivingFramework", "max_issues_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "locomotion_framework/controllers/hierarchical_control/src/controllers/wheels.cpp", "max_forks_repo_name": "ADVRHumanoids/DrivingFramework", "max_forks_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T19:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T03:32:52.000Z", "avg_line_length": 36.4572649573, "max_line_length": 126, "alphanum_fraction": 0.4755597234, "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.16446678050301278}}
{"text": "/**\n * @file envelope_generator.cc\n * Computes reverberation envelopes from eigenverbs.\n */\n#include <usml/eigenverb/envelope_generator.h>\n#include <usml/eigenverb/eigenverb.h>\n#include <usml/sensors/beam_pattern_map.h>\n#include <usml/sensors/beam_pattern_model.h>\n#include <usml/threads/smart_ptr.h>\n#include <boost/foreach.hpp>\n\nusing namespace usml::eigenverb ;\nusing namespace usml::sensors ;\n\n/**\n * Minimum intensity level for valid reverberation contributions (dB).\n */\ndouble envelope_generator::intensity_threshold = -300.0 ;\n\n/**\n * Maximum distance between the peaks of the source and receiver eigenverbs.\n */\ndouble envelope_generator::distance_threshold = 6.0 ;\n\n/**\n * The mutex for static properties.\n */\nread_write_lock envelope_generator::_property_mutex;\n\n/**\n * Time axis for reverberation calculation.  Defaults to\n * a linear sequence out to 400 sec with a sampling period of 0.1 sec.\n */\nunique_ptr<const seq_vector> envelope_generator::_travel_time( new seq_linear(0.0,0.1,400.0) ) ;\n\n/**\n * Copies envelope computation parameters from static memory into\n * this specific task.\n */\nenvelope_generator::envelope_generator(\n\tsensor_pair* sensor_pair,\n\tdouble initial_time,\n\tsize_t src_freq_first,\n\tsize_t num_azimuths\n):\n    _done(false),\n    _initial_time(initial_time),\n    _ocean( ocean_shared::current() ),\n    _sensor_pair(sensor_pair),\n    _src_eigenverbs(sensor_pair->source()->eigenverbs()),\n    _rcv_eigenverbs(sensor_pair->receiver()->eigenverbs()),\n    _eigenverb_interpolator(sensor_pair->receiver()->frequencies(),sensor_pair->frequencies())\n{\n    write_lock_guard guard(_property_mutex);\n\n    // Get source_params for reverb_duration and pulse_length, and beam_list size\n    source_params::reference src_params = _sensor_pair->source()->source();\n    _src_beam_list = src_params->beam_list();\n\n    // Get receiver_params for beam_list size\n    sensor_params::id_type rcv_params_ID = _sensor_pair->receiver()->paramsID();\n    receiver_params::reference rcv_params =\n        receiver_params_map::instance()->find(rcv_params_ID);\n\n    _rcv_beam_list = rcv_params->beam_list();\n\n    add_envelope_listener(_sensor_pair);\n\n    _envelopes = envelope_collection::reference( new envelope_collection(\n    \t_sensor_pair->frequencies(),\n        src_freq_first,\n        _travel_time.get(),\n        src_params->reverb_duration(),\n        src_params->pulse_length(),\n        pow(10.0,intensity_threshold/10.0),\n        num_azimuths,\n        _src_beam_list.size(),\n        _rcv_beam_list.size(),\n        _initial_time,\n        _sensor_pair->source()->sensorID(),\n        _sensor_pair->receiver()->sensorID(),\n        _sensor_pair->source()->position(),\n        _sensor_pair->receiver()->position() ) ) ;\n}\n\n/**\n * Executes the Eigenverb reverberation model.\n */\nvoid envelope_generator::run() {\n\n\t// create memory for work products\n\n    const seq_vector* freq = _envelopes->envelope_freq() ;\n    const size_t num_freq = freq->size() ;\n\n\tvector<double> scatter( num_freq, 1.0 ) ;\n\tmatrix<double> src_beam( num_freq, _envelopes->num_src_beams(), 1.0 ) ;\n\tmatrix<double> rcv_beam( num_freq, _envelopes->num_rcv_beams(), 1.0 ) ;\n\n\teigenverb rcv_verb ;\n\trcv_verb.frequencies = freq ;\n\trcv_verb.power = vector<double>( num_freq ) ;\n\n\t// loop through eigenrays for each interface\n\n\tfor ( size_t interface=0 ; interface < _rcv_eigenverbs->num_interfaces() ; ++interface) {\n\n\t\tBOOST_FOREACH( eigenverb verb, _rcv_eigenverbs->eigenverbs(interface) ) {\n\t\t\t_eigenverb_interpolator.interpolate(verb,&rcv_verb) ;\n\n\t\t\t// Cull eigenverbs down with rtree.query\n\t\t\tstd::vector<value_pair> result_s;\n\t\t\t_src_eigenverbs->query_rtree(interface, rcv_verb, result_s);\n\n\t\t\tBOOST_FOREACH( value_pair const& vp, result_s ) {\n\n\t\t\t\teigenverb src_verb = *(vp.second);\n\n\t\t\t\t// determine relative range and bearing between the projected Gaussians\n\t\t\t\t// skip this combo if source peak too far away\n\n\t\t\t    double bearing ;\n\t\t\t    const double range = rcv_verb.position.gc_range( src_verb.position, &bearing ) ;\n\t\t\t    if ( range > distance_threshold * max(rcv_verb.length,rcv_verb.width)) continue ;\n\n\t\t\t    if ( range < 1e-6 ) bearing = 0 ;\t// fixes bearing = NaN\n\t\t\t    bearing -= rcv_verb.direction ;\t\t// relative bearing\n\n\t\t\t    const double ys = range * cos( bearing ) ;\n\t\t\t    const double ys2 = ys * ys ;\n\t\t\t    if ( abs(ys) > distance_threshold * rcv_verb.length ) continue ;\n\n\t\t\t    const double xs = range * sin( bearing ) ;\n\t\t\t    const double xs2 = xs * xs ;\n\t\t\t    if ( abs(xs) > distance_threshold * rcv_verb.width ) continue ;\n\n\t\t\t\t// compute interface scattering strength\n\t\t\t    // skip this combo if scattering strength is trivial\n\n\t\t\t\tif ( ! scattering( interface,\n\t\t\t\t\t rcv_verb.position, *freq,\n\t\t\t\t\t src_verb.grazing, rcv_verb.grazing,\n\t\t\t\t\t src_verb.direction, rcv_verb.direction,\n\t\t\t\t\t &scatter ) ) continue ;\n\n\t\t\t\t// compute beam levels\n\n\t\t\t\tsrc_beam = beam_gain(_src_beam_list, freq, src_verb.source_de,\n\t\t\t\t\tsrc_verb.source_az, _sensor_pair->source()->orient());\n\t\t\t\trcv_beam = beam_gain(_rcv_beam_list, freq, rcv_verb.source_de,\n\t\t\t\t\trcv_verb.source_az, _sensor_pair->receiver()->orient());\n\n\t\t\t\t// create envelope contribution\n\n\t\t\t\t_envelopes->add_contribution( src_verb, rcv_verb,\n\t\t\t\t\t\tsrc_beam, rcv_beam, scatter, xs2, ys2 ) ;\n\t\t\t}\n\t\t}\n\t}\n\tthis->notify_envelope_listeners(_envelopes) ;\n}\n\n/**\n * Computes the beam_gain\n */\nmatrix<double> envelope_generator::beam_gain(\n    sensor_params::beam_pattern_list beam_list,\n    const seq_vector* freq, double de_rad, double az_rad, orientation orient)\n{\n    const vector<double> frequencies = *freq;\t// beam_level requires ublas vector\n    matrix<double> beam_matrix( freq->size(), beam_list.size() ) ;\n    vector<double> level( freq->size(), 0.0 ) ;\n    BOOST_FOREACH( beam_pattern_model::id_type id, beam_list) {\n        beam_pattern_model::reference bp = beam_pattern_map::instance()->find(id);\n        bp->beam_level(de_rad, az_rad, orient, frequencies, &level ) ;\n\n        std::copy(level.begin(), level.end(), beam_matrix.begin1());\n    }\n    return beam_matrix;\n}\n\n/**\n * Computes the broadband scattering strength for a specific interface.\n */\nbool envelope_generator::scattering( size_t interface, const wposition1& location,\n\t\tconst seq_vector& frequencies, double de_incident,\n\t\tdouble de_scattered, double az_incident, double az_scattered,\n\t\tvector<double>* amplitude)\n{\n\tswitch ( interface ) {\n\tcase eigenverb::BOTTOM:\n\t\t_ocean->bottom().scattering(location,frequencies,\n\t\t\t\tde_incident,de_scattered,az_incident,az_scattered,\n\t\t\t\tamplitude) ;\n\t\tbreak;\n\tcase eigenverb::SURFACE:\n\t\t_ocean->surface().scattering(location,frequencies,\n\t\t\t\tde_incident,de_scattered,az_incident,az_scattered,\n\t\t\t\tamplitude) ;\n\t\tbreak;\n\tdefault:\n\t\tsize_t layer = (size_t) floor( (interface-2.0)/2.0 ) ;\n\t\t_ocean->volume( layer ).scattering(location,frequencies,\n\t\t\t\tde_incident,de_scattered,az_incident,az_scattered,\n\t\t\t\tamplitude) ;\n\t\tbreak;\n\t}\n\n\t// check to see that scattering strenght is not trivial\n\n\tBOOST_FOREACH (double amp, *amplitude){\n        if (amp >= intensity_threshold ) {\n            return true;\n        }\n    }\n    return true;\n}\n", "meta": {"hexsha": "b155e0313acaa5457bd0af65de1e7d70ce2055f3", "size": 7100, "ext": "cc", "lang": "C++", "max_stars_repo_path": "eigenverb/envelope_generator.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "eigenverb/envelope_generator.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "eigenverb/envelope_generator.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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.5688073394, "max_line_length": 96, "alphanum_fraction": 0.7087323944, "num_tokens": 1789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.16442907519466857}}
{"text": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n#include \"EvaluateKey.h\"\n#include \"IonH5Eigen.h\"\n#include \"ZeromerMatDiff.h\"\n#include <malloc.h>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\nusing namespace Eigen;\n#define NUM_STATS_FIELDS 9\n#define SNR_IDX 0\n#define MAD_IDX 1\n#define OK_IDX 2\n#define TRACE_SD_IDX 3\n#define PROJ_RES_IDX 4\n#define PEAK_IDX 5\n#define TAUE_IDX 6\n#define TAUB_IDX 7\n#define MEAN_SIG_IDX 8\n#define MIN_CRAZY_PEAK_VAL 0\n#define MAX_CRAZY_PEAK_VAL 2000\n#define MIN_INTEGRATION_WINDOW 15\n#define DEFAULT_INTEGRATION_WINDOW 20\n#define MIN_SAMPLES_FOR_STATS .05\n#define MIN_SNR_FOR_STATS 8\n#define MIN_PEAK_FOR_STATS 35\n#define MAX_PEAK_FOR_STATS 1000\n#define MAX_MAD_FOR_STATS 12\n#define MIN_PEAK_SEARCH_END 15\n#define MAX_PEAK_WINDOW 2\n\nEvaluateKey::EvaluateKey() {\n  Init();\n}\n\nvoid EvaluateKey::Init() {\n  m_debug = false;\n  m_trace_data = m_ref_data = m_zeromer_est = m_shifted_ref = NULL;\n  m_avg_0mer = m_sd_0mer = m_avg_1mer = m_sd_1mer = NULL;\n  m_num_wells = m_num_well_flows = m_num_frames = m_num_flows = 0;\n  m_integration_start = m_integration_end = m_peak_start = m_peak_end = 0;\n  m_min_integration = 0;\n  m_flow_avg_1mer = NULL;\n  m_flow_count_1mer = NULL;\n  m_doing_darkmatter = m_use_projection = m_peak_signal_frames = m_integration_width = m_normalize_1mers = false;\n  fill(m_flow_key_avg.begin(), m_flow_key_avg.end(), 0.0f);\n  m_flow_key_avg.resize(0);\n}\n\nvoid EvaluateKey::Alloc(size_t num_well_flows, size_t num_frames, size_t num_flows, int num_wells) {\n  size_t total_size = num_well_flows * num_frames;\n  if (m_num_well_flows != num_well_flows || m_num_frames != num_frames) {\n    if (m_trace_data != NULL) {\n      Cleanup();\n    }\n    m_num_wells = num_wells;\n    m_num_well_flows = num_well_flows;\n    m_num_frames = num_frames;\n    m_num_flows = num_flows;\n    m_trace_data = (float *) memalign(32, sizeof(float) * total_size);\n    m_ref_data = (float *) memalign(32, sizeof(float) * total_size);\n    m_zeromer_est = (float *) memalign(32, sizeof(float) * total_size);\n    m_shifted_ref = (float *) memalign(32, sizeof(float) * total_size);\n    m_avg_0mer = (float *) memalign(32, sizeof(float) * num_frames);\n    m_sd_0mer = (float *) memalign(32, sizeof(float) * num_frames);\n    m_avg_1mer = (float *) memalign(32, sizeof(float) * num_frames);\n    m_sd_1mer = (float *) memalign(32, sizeof(float) * num_frames);\n    m_flow_avg_1mer = (float *) memalign(32, sizeof(float) * num_frames * num_flows);\n    m_flow_count_1mer = (int *) memalign(32, sizeof(int) * num_flows);\n    // these are small, just for sanity initialize them\n    memset(m_avg_0mer,0,sizeof(float) * num_frames);\n    memset(m_sd_0mer,0,sizeof(float) * num_frames);\n    memset(m_avg_1mer,0,sizeof(float) * num_frames);\n    memset(m_sd_1mer,0,sizeof(float) * num_frames);\n    memset(m_flow_avg_1mer, 0, sizeof(float) * num_frames * num_flows);\n    memset(m_flow_count_1mer, 0, sizeof(int) * num_flows);\n  }\n}\n\nvoid EvaluateKey::Cleanup() {\n    if (m_trace_data != NULL) {\n      free(m_trace_data);\n      free(m_ref_data);\n      free(m_zeromer_est);\n      free(m_shifted_ref);\n      free(m_avg_0mer);\n      free(m_sd_0mer);\n      free(m_avg_1mer);\n      free(m_sd_1mer);\n      free(m_flow_avg_1mer);\n      free(m_flow_count_1mer);\n      Init();\n    }\n  }\n\nvoid EvaluateKey::SetSizes(int row_start, int row_end, \n                           int col_start, int col_end,\n                           int flow_start, int flow_end,\n                           int frame_start, int frame_end) {\n  size_t num_wells = (row_end - row_start) * (col_end - col_start);\n  size_t num_well_flows = num_wells * (flow_end - flow_start);\n  size_t num_frames = frame_end - frame_start;\n  size_t num_flows = flow_end - flow_start;\n  Alloc( num_well_flows, num_frames, num_flows, num_wells);\n  m_peak_start = m_integration_start = 0;\n  m_min_integration = min((size_t)DEFAULT_INTEGRATION_WINDOW, num_frames);\n  m_integration_end = min(m_num_frames, (size_t)DEFAULT_INTEGRATION_WINDOW);\n  m_peak_end = min(m_num_frames, (size_t)MIN_PEAK_SEARCH_END);\n  // these are small, just for sanity initialize them\n  memset(m_avg_0mer,0,sizeof(float) * num_frames);\n  memset(m_sd_0mer,0,sizeof(float) * num_frames);\n  memset(m_avg_1mer,0,sizeof(float) * num_frames);\n  memset(m_sd_1mer,0,sizeof(float) * num_frames);\n}\n\nvoid EvaluateKey::SetUpMatrices(TraceStoreCol &trace_store, \n                                int col_stride, int flow_stride,\n                                int row_start, int row_end, int col_start, int col_end,\n                                int flow_start, int flow_end,\n                                int frame_start, int frame_end,\n                                float *trace_data,\n                                float *ref_data) {\n  int row_size = row_end - row_start;\n  int col_size = col_end - col_start;\n  int flow_size = flow_end - flow_start;\n  int frame_size = frame_end - frame_start;\n  size_t local_flow_stride = row_size * col_size;\n  size_t total_rows = local_flow_stride * flow_size;\n\n  std::vector<float> trace(trace_store.GetNumFrames());\n  std::vector<float> ref_trace(trace_store.GetNumFrames());\n\n  for (int flow_ix = flow_start; flow_ix < flow_end; flow_ix++) {\n    for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n      for (int col_ix = col_start; col_ix < col_end; col_ix++) {\n        int well_ix =  row_ix * col_stride + col_ix;\n        int local_well_ix = (flow_ix - flow_start) * local_flow_stride + (row_ix - row_start) * col_size + (col_ix - col_start);\n        trace_store.GetReferenceTrace(well_ix, flow_ix, &ref_trace[0]);\n        for (int frame_ix = frame_start; frame_ix < frame_end; frame_ix++) {\n          ref_data[local_well_ix + (frame_ix - frame_start) * total_rows] = ref_trace[frame_ix];\n        }\n      }\n      for (int frame_ix = frame_start; frame_ix < frame_end; frame_ix++) {\n        int well_ix = row_ix * col_stride + col_start;\n        int local_well_ix = (row_ix - row_start) * col_size;\n        int16_t *__restrict store_start = trace_store.GetMemPtr() + flow_ix * trace_store.mFrameStride + frame_ix * trace_store.mFlowFrameStride + well_ix;\n        int16_t *__restrict store_end = store_start + col_size;\n        float *__restrict out_start = trace_data + (frame_ix - frame_start) * total_rows + (flow_ix-flow_start) * local_flow_stride + local_well_ix;\n        while(store_start != store_end) {\n          *out_start++ = *store_start++;\n        }\n      }\n    }\n  }\n}\n\n\nvoid EvaluateKey::FitTauB(KeySeq &key, const float *time, float taue_est, int frame_start, int frame_end, float *__restrict taub) {\n  if (m_flow_order.size() >= m_num_flows) {\n    ZeromerMatDiff::FitTauBNuc(&key.zeroFlows[0], key.zeroFlows.size(),\n                               m_trace_data, m_shifted_ref,\n                               &m_flow_order[0],\n                               m_num_wells, m_num_flows, m_num_well_flows,\n                               m_num_frames, taue_est, taub);\n  }\n  else {\n    ZeromerMatDiff::FitTauB(&key.zeroFlows[0], key.zeroFlows.size(),\n                            m_trace_data, m_shifted_ref,\n                            m_num_wells, m_num_flows, m_num_well_flows,\n                            m_num_frames, taue_est, taub);\n  }\n}\n\nvoid EvaluateKey::PredictZeromersVec(const float *time, float taue_est, float * __restrict taub) {\n  ZeromerMatDiff::PredictZeromersSignal(time, m_num_frames,\n                                        m_trace_data, m_shifted_ref, m_zeromer_est,\n                                        m_num_wells, m_num_flows, m_num_well_flows,\n                                        taue_est, taub, \"\");\n}\n\nvoid EvaluateKey::ScoreKeySignals(KeySeq &key, float *__restrict key_signal_ptr, \n                                  int integration_start, int integration_end,\n                                  int peak_start, int peak_end,\n                                  float *onemer_norm,\n                                  float *__restrict key_results_ptr, \n                                  int num_result_cols, float *__restrict taub, float taue_est) {\n  Map<MatrixXf, Aligned> key_signal(key_signal_ptr, m_num_well_flows, m_num_frames);\n  Map<MatrixXf, Aligned> key_results(key_results_ptr, m_num_wells, num_result_cols);\n\n  // Calculate basics per well for integral, mad, max for each well/flow\n  VectorXf key_integrals(m_num_well_flows), key_mad(m_num_well_flows), key_max(m_num_well_flows);\n  key_integrals.setZero();\n  key_mad.setZero();\n  key_max.setZero();\n  for (int frame_ix = peak_start; frame_ix < peak_end; frame_ix++) {\n    float *__restrict key_sig_start = key_signal.data() + frame_ix * m_num_well_flows;\n    //    float *__restrict one_forward = key_signal.data() + min(frame_ix+1,(int)m_num_frames-1) * m_num_well_flows;\n    float *__restrict one_backward = key_signal.data() + max(frame_ix-1,0) * m_num_well_flows;\n    float *__restrict key_sig_end = key_sig_start + m_num_well_flows;\n    float *__restrict peak = key_max.data();\n    while (key_sig_start != key_sig_end) {\n      float value = (*key_sig_start + *one_backward) / 2;\n      *peak = max(*peak, value);\n      peak++;\n      one_backward++;\n      key_sig_start++;\n    }\n  }\n\n  for (int frame_ix = integration_start; frame_ix < integration_end; frame_ix++) {\n    key_integrals.array() += key_signal.col(frame_ix).array();\n    key_mad.array() += key_signal.col(frame_ix).array().abs();\n  }\n\n  // Our summary statistics for onemers and zeromers.\n  VectorXf onemer_mean(m_num_wells), onemer_m2(m_num_wells), zeromer_mean(m_num_wells), zeromer_m2(m_num_wells);\n  VectorXf all_mean(m_num_wells), all_m2(m_num_wells);\n\n  all_mean.setZero();\n  all_m2.setZero();\n  onemer_mean.setZero();\n  onemer_m2.setZero();\n  zeromer_mean.setZero();\n  zeromer_m2.setZero();\n\n  int n_onemer = 0;\n  // loop through all the onemers and calculate the mean and sd\n  for (size_t i = 0; i < key.onemerFlows.size(); i++) {\n    n_onemer++;\n    int flow_ix = key.onemerFlows[i];\n    float norm_factor = 1.0f;\n    if (onemer_norm != NULL) { \n      norm_factor = onemer_norm[i];\n    }\n    size_t offset = m_num_wells * flow_ix;\n    float *__restrict integral_start = key_integrals.data() + offset;\n    float *__restrict integral_end = integral_start + m_num_wells;\n    float *__restrict max_key = key_max.data() + offset;\n    float *__restrict mean = onemer_mean.data();\n    float *__restrict m2 = onemer_m2.data();\n    float *__restrict mean_peak = key_results.col(PEAK_IDX).data();\n    float delta;\n    while (integral_start != integral_end) {\n      *integral_start = *integral_start * norm_factor;\n      delta = (*integral_start) - *mean;\n      *mean += delta/n_onemer;\n      *m2 += delta * (*integral_start - *mean);\n      *mean_peak++ += *max_key++;\n      integral_start++;\n      mean++;\n      m2++;\n    }\n  }\n\n  int n_flow = 0;\n  for (size_t flow_ix = 0; flow_ix < key.usableKeyFlows; flow_ix++) {\n    n_flow++;\n    size_t offset = m_num_wells * flow_ix;\n    float *__restrict integral_start = key_integrals.data() + offset;\n    float *__restrict integral_end = integral_start + m_num_wells;\n    float *__restrict mean = all_mean.data();\n    float *__restrict m2 = all_m2.data();\n    float delta;\n    while (integral_start != integral_end) {\n      delta = *integral_start - *mean;\n      *mean += delta/n_flow;\n      *m2 += delta * (*integral_start - *mean);\n      integral_start++;\n      mean++;\n      m2++;\n    }\n  }\n\n\n  int num_col = m_num_frames;\n  int n_zeromer = 0;\n  // loop through all the zeromers and calculate the mean and sd\n  for (size_t i = 0; i < key.zeroFlows.size(); i++) {\n    n_zeromer++;\n    int flow_ix = key.zeroFlows[i];\n    size_t offset = m_num_wells * flow_ix;\n    float *__restrict integral_start = key_integrals.data() + offset;\n    float *__restrict integral_end = integral_start + m_num_wells;\n    float *__restrict mad = key_mad.data() + offset;\n    float *__restrict mean = zeromer_mean.data();\n    float *__restrict m2 = zeromer_m2.data();\n    float *__restrict mean_mad = key_results.col(MAD_IDX).data();\n\n    float delta;\n    while (integral_start != integral_end) {\n      delta = *integral_start - *mean;\n      *mean += delta/n_zeromer;\n      *m2 += delta * (*integral_start - *mean);\n      *mean_mad++ += *mad++ / num_col;\n      integral_start++;\n      mean++;\n      m2++;\n    }\n  }\n    \n  /* combine all the stats into final summaries. */\n  float *__restrict snr_start = key_results.col(SNR_IDX).data();\n  float *__restrict snr_end = snr_start + m_num_wells;\n  float *__restrict o_mean = onemer_mean.data();\n  float *__restrict o_m2 = onemer_m2.data();\n  float *__restrict z_mean = zeromer_mean.data();\n  float *__restrict z_m2 = zeromer_m2.data();\n  float *__restrict a_m2 = all_m2.data();\n  float *__restrict ok = key_results.col(OK_IDX).data();\n  float *__restrict trace_sd = key_results.col(TRACE_SD_IDX).data();\n  float *__restrict taub_out = key_results.col(TAUB_IDX).data();\n  float *__restrict taue_out = key_results.col(TAUE_IDX).data();\n  float *__restrict mean_mad = key_results.col(MAD_IDX).data();\n  float *__restrict mean_peak = key_results.col(PEAK_IDX).data();\n  float *__restrict onemer_sig = key_results.col(MEAN_SIG_IDX).data();\n  while(snr_start != snr_end) {\n    float sig = *o_mean++ - *z_mean++;\n    float o_sd = sqrt(*o_m2++/n_onemer);\n    float z_sd = sqrt(*z_m2++/n_zeromer);\n    *onemer_sig++ = sig;\n    *snr_start = sig/((o_sd +z_sd)/2.0f);\n    *ok = isfinite(*snr_start) ? 1 : 0;\n    *trace_sd++ = sqrt(*a_m2++ / n_flow);\n    //    *trace_sd++ = sig;\n    *taub_out++ = *taub++;\n    *taue_out++ = taue_est;\n    ok++;\n    snr_start++;\n    *mean_peak /= n_onemer;\n    *mean_mad /= n_zeromer;\n    mean_peak++;\n    mean_mad++;\n  }\n}\n\nvoid PickBestKey(std::vector<Eigen::MatrixXf> &key_results, std::vector<KeySeq> &keys, int local_index, int global_index, KeyFit &fit) {\n  fit.keyIndex = -1;\n  for (size_t key_ix = 0; key_ix < keys.size(); key_ix++) {\n    Eigen::MatrixXf &results = key_results[key_ix];\n    float snr = results.coeff(local_index, SNR_IDX);\n    float peak = results.coeff(local_index, PEAK_IDX);\n    if (key_ix == 0 || ((snr > fit.snr && snr > keys[key_ix].minSnr))) { // || (peak > keys[key_ix].good_enough_peak && snr > keys[key_ix].good_enough_snr))) {\n      fit.snr = results.coeff(local_index, SNR_IDX);\n      fit.mad = results.coeff(local_index, MAD_IDX);\n      fit.ok = results.coeff(local_index, OK_IDX);\n      fit.peakSig = results.coeff(local_index, PEAK_IDX);\n      fit.sd = results.coeff(local_index, TRACE_SD_IDX);\n      fit.tauE = results.coeff(local_index, TAUE_IDX);\n      fit.tauB = results.coeff(local_index, TAUB_IDX);\n      fit.onemerAvg = results.coeff(local_index, MEAN_SIG_IDX);\n    }\n    if (isfinite(snr) && (snr >= fit.snr && snr >= keys[key_ix].minSnr && peak >= keys[key_ix].minPeak)) { // || (peak > keys[key_ix].good_enough_peak && snr > keys[key_ix].good_enough_snr))) {\n      fit.keyIndex = key_ix;\n      fit.snr = snr;\n    }\n  }\n}\n\nvoid CalculateIntegrationWindow(float *avg_1mer, float *sd_1mer, float *avg_0mer, float *sd_0mer, int n_frames,\n                                int min_integration, size_t &integration_start, size_t &integration_end) {\n  integration_start = 0;\n  integration_end = min_integration;\n  while (integration_end < (size_t)n_frames) {\n    float signal = avg_1mer[integration_end] - avg_0mer[integration_end];\n    float noise_0mer = sd_0mer[integration_end]; // @todo cws - should we have a multiple on noise or avg with 1mer noise?\n    float noise_1mer = sd_1mer[integration_end]; // @todo cws - should we have a multiple on noise or avg with 1mer noise?\n    if (signal < (noise_0mer + noise_1mer) || (integration_end + 1) == (size_t) n_frames) {\n      break;\n    }\n    integration_end++;\n  }\n  //  fprintf(stdout, \"Finishing on frame %d with signal %.2f and noise %.2f 1mer noise %.2f 0mer signal %.2f\\n\", integration_end, avg_1mer[integration_end] - avg_0mer[integration_end], sd_0mer[integration_end], sd_1mer[integration_end], avg_0mer[integration_end]);\n}\n\n// @todo - cws don't use our soft filtred wells for this\nint CalculateIncorporationStats(std::vector<Eigen::MatrixXf> &key_results,  \n                                std::vector<Eigen::MatrixXf> &key_signals,\n                                std::vector<KeySeq> &keys, \n                                int num_wells, int num_flows, int num_well_flows, int num_frames,\n                                float min_snr, float min_peak,\n                                float *avg_0mer, float *sd_0mer, float *avg_1mer, \n                                float *sd_1mer,\n                                float *flow_avg_1mer, int *flow_count_1mer) {\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> flow_avg(flow_avg_1mer, num_flows, num_frames);\n  VectorXf flow_onemer_mean(num_frames), onemer_mean(num_frames), onemer_m2(num_frames), zeromer_mean(num_frames), zeromer_m2(num_frames);\n  VectorXi flow_onemer_counts(num_frames), onemer_counts(num_frames), zeromer_counts(num_frames);\n  VectorXi well_counts(num_wells);\n  memset(flow_count_1mer, 0, sizeof(int) * num_flows);\n  onemer_mean.setZero();\n  onemer_m2.setZero();\n  zeromer_mean.setZero();\n  zeromer_m2.setZero();\n  onemer_counts.setZero();\n  zeromer_counts.setZero();\n  flow_avg.setZero();\n  well_counts.setZero();\n  int too_low_snr = 0, too_low_peak = 0, too_high_peak = 0, too_mad = 0;\n  for (int flow_ix = 0; flow_ix < num_flows; flow_ix++) {\n    flow_onemer_mean.setZero();\n    flow_onemer_counts.setZero();\n    for (int frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n      for (size_t key_ix = 0; key_ix < keys.size(); key_ix++) {\n        float *m2 = NULL;\n        float *mean = NULL;\n        int *count = NULL;\n        float *flow_mean = NULL;\n        int *flow_count = NULL;\n        KeySeq &key = keys[key_ix];\n        if (key.flows[flow_ix] == 0) {\n          mean = &zeromer_mean[frame_ix];\n          m2 = &zeromer_m2[frame_ix];\n          count = &zeromer_counts[frame_ix];\n        }\n        else if (key.flows[flow_ix] == 1) {\n          mean = &onemer_mean[frame_ix];\n          m2 = &onemer_m2[frame_ix];\n          count = &onemer_counts[frame_ix];\n          flow_mean = &flow_onemer_mean[frame_ix];\n          flow_count = &flow_onemer_counts[frame_ix];\n        }\n        else {\n          continue;\n        }\n        MatrixXf &results = key_results[key_ix];\n        float *__restrict signal_start = key_signals[key_ix].data() + frame_ix * num_well_flows + num_wells * flow_ix;\n        float *__restrict signal_end = signal_start + num_wells;\n        float *__restrict snr = results.col(SNR_IDX).data();\n        float *__restrict peak = results.col(PEAK_IDX).data();\n        float *__restrict mad = results.col(MAD_IDX).data();\n        int *__restrict well_counts_start =well_counts.data();\n        float delta;\n        while (signal_start != signal_end) {\n          if (*snr >= key.minSnr ) {\n            if (*snr >= min_snr && *peak >= min_peak && *peak < MAX_PEAK_FOR_STATS && *mad < MAX_MAD_FOR_STATS) {\n              if (flow_mean != NULL) {\n                *flow_mean += *signal_start;\n                *flow_count += 1;\n              }\n              if (frame_ix == 0 && flow_ix == 0) {\n                (*well_counts_start)++;\n              }\n              (*count)++;\n              delta = *signal_start - *mean;\n              *mean += delta / *count;\n              *m2 += delta * (*signal_start - *mean);\n            }\n          }\n          well_counts_start++;\n          mad++;\n          signal_start++;\n          snr++;\n          peak++;\n        }\n      }\n    }\n    for (int frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n      flow_avg(flow_ix, frame_ix) = flow_onemer_counts.coeff(frame_ix) > 0 ? flow_onemer_mean.coeff(frame_ix)/flow_onemer_counts.coeff(frame_ix) : 0.0f;\n    }\n    flow_count_1mer[flow_ix] = flow_onemer_counts[0];\n  }\n  //  fprintf(stdout, \"Filters for summary stats: %d low_snr %d low_peak %d high_peak %d mad\\n\",too_low_snr , too_low_peak, too_high_peak, too_mad);\n  for (int frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n    avg_0mer[frame_ix] = zeromer_mean[frame_ix];\n    sd_0mer[frame_ix] = sqrt(zeromer_m2[frame_ix]/zeromer_counts[frame_ix]);\n    avg_1mer[frame_ix] = onemer_mean[frame_ix];\n    sd_1mer[frame_ix] = sqrt(onemer_m2[frame_ix]/onemer_counts[frame_ix]);\n  }\n  // let the calling function set thresholds for using resulting statistics\n  return well_counts.sum();\n}\n\nvoid EvaluateKey::Calculate1MerNormalization(size_t num_flows, size_t num_frames,\n                                             std::vector<int> &onemer_flows,\n                                             float *flow_1mer_avg, int *flow_1mer_count,\n                                             float *norm_factors,\n                                             size_t integration_start, size_t integration_end) {\n\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> flow_avg(flow_1mer_avg, num_flows, num_frames);\n  std::fill(norm_factors, norm_factors + onemer_flows.size(), 1.0f);\n  int onemer_count = onemer_flows.size();\n  float integration_sum[onemer_count];\n  float mean_integration = 0;\n  int threshold = MIN_SAMPLES_FOR_STATS * m_num_wells;\n  int seen = 0;\n  std::fill(integration_sum, integration_sum + onemer_count, 0);\n  for (int i = 0; i < onemer_count; i++) {\n    if (flow_1mer_count[onemer_flows[i]] < threshold) {\n      continue;\n    }\n    for (int frame_ix = integration_start; frame_ix < (int)integration_end; frame_ix++) {\n      integration_sum[i] += flow_avg(onemer_flows[i], frame_ix);\n    }\n  }\n  \n  for (int i = 0; i < onemer_count; i++) {\n    mean_integration += integration_sum[i];\n  }\n  \n  mean_integration = mean_integration / onemer_count;\n  \n\n  if (mean_integration > 0) {\n    for (int i = 0; i < onemer_count; i++) {\n      norm_factors[i] = mean_integration / integration_sum[i];\n    }\n  }\n}\n\nvoid EvaluateKey::FindBestKey(int row_start, int row_end, int col_start, int col_end,\n                              int frame_start, int frame_end,\n                              int flow_stride, int col_stride, \n                              const float *time, std::vector<KeySeq> &keys, float taue_est, \n                              float shift, char *bad_wells,\n                              std::vector<KeyFit> &key_fits) {\n  Eigen::Matrix<float, Dynamic, Dynamic, AutoAlign | ColMajor> zeromer_buffer;\n  // allocate some scratch buffers for our intermediate results\n  std::vector<Eigen::MatrixXf> key_results(keys.size());\n  std::vector<Eigen::MatrixXf> key_signals(keys.size());\n  std::vector<Eigen::VectorXf> key_taub(keys.size());\n  std::vector<std::vector<float> > key_norm_signals(keys.size());\n  for (size_t key_ix = 0; key_ix < keys.size(); key_ix++) {\n    // 8 for snr, mad, ok, traceSd, projResid, peakSig, taue, taub\n    key_results[key_ix].resize(m_num_wells, NUM_STATS_FIELDS);\n    key_results[key_ix].setZero(); // clean out.\n    key_signals[key_ix].resize(m_num_well_flows, m_num_frames); // this will be initialized every time.\n    key_taub[key_ix].resize(m_num_well_flows);\n    \n  }\n  // for each key calculate our estimated signals m_num_well_flows, a no-op currently as we don't shift reference\n  ZeromerMatDiff::ShiftReference(m_num_frames, m_num_well_flows, shift, m_ref_data, m_shifted_ref);\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> trace_data(m_trace_data, m_num_well_flows, m_num_frames);\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> zeromer_est(m_zeromer_est, m_num_well_flows, m_num_frames);\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> shifted_ref(m_shifted_ref, m_num_well_flows, m_num_frames);\n  for (size_t key_ix = 0; key_ix < keys.size(); key_ix++) {\n    // Fit taub for each well assuming that key 0mers are 0mers\n    FitTauB(keys[key_ix], time, taue_est, frame_start, frame_end, key_taub[key_ix].data());\n    // Predict the zeromers\n    PredictZeromersVec(time, taue_est, key_taub[key_ix].data());\n    // Calculate our \"signal\" after subtracting estimated zeromer\n    key_signals[key_ix] = trace_data - zeromer_est;\n    // Normalization default to 1.0 (no normalization)\n    key_norm_signals[key_ix].resize(keys[key_ix].onemerFlows.size());\n    fill(key_norm_signals[key_ix].begin(), key_norm_signals[key_ix].end(), 1.0f);\n    // Gather summary stats about each key fit\n    ScoreKeySignals(keys[key_ix], key_signals[key_ix].data(), \n                    m_integration_start, m_integration_end,\n                    m_peak_start, m_peak_end,\n                    &key_norm_signals[key_ix][0],\n                    key_results[key_ix].data(), key_results[key_ix].cols(), \n                    key_taub[key_ix].data(), taue_est);\n\n  }\n\n  // If we're doing any modifications to fitting try rescoring with new modifications\n  if (m_doing_darkmatter || m_use_projection || m_peak_signal_frames || m_integration_width) {\n    int num_samples = CalculateIncorporationStats(key_results, key_signals, keys,\n                                                  m_num_wells, m_num_flows, m_num_well_flows, m_num_frames,\n                                                  MIN_SNR_FOR_STATS, MIN_PEAK_FOR_STATS,\n                                                  m_avg_0mer, m_sd_0mer, m_avg_1mer, m_sd_1mer, m_flow_avg_1mer,\n                                                  m_flow_count_1mer);\n    //    fprintf(stdout, \"Num good samples: %d\\n\", num_samples);\n    if (num_samples >= MIN_SAMPLES_FOR_STATS * m_num_wells) {\n      Eigen::MatrixXf proj_signal;\n      if (m_integration_width) {\n        CalculateIntegrationWindow(m_avg_1mer, m_sd_1mer, m_avg_0mer, m_sd_0mer, m_num_frames, \n                                   MIN_INTEGRATION_WINDOW,m_integration_start, m_integration_end);\n      }\n      for (size_t key_ix = 0; key_ix < keys.size(); key_ix++) {\n        key_results[key_ix].setZero(); // reset anything learned last time...\n        \n        if (m_doing_darkmatter) {\n          for (int i = 0; i < key_signals[key_ix].cols(); i++) {\n            key_signals[key_ix].col(i).array() -= m_avg_0mer[i];\n          }\n        }\n        if (m_use_projection) {\n          Eigen::VectorXf proj_1mer(m_num_frames);\n          std::copy(m_avg_1mer, m_avg_1mer + m_num_frames, proj_1mer.data());\n          proj_1mer.normalize();\n          Eigen::VectorXf coefficients(key_signals[key_ix].rows());\n          coefficients.setZero();\n          // Should be faster to do this at the column level than row by row\n          for (int i = 0; i < key_signals[key_ix].cols(); i++) {\n            coefficients.array() += key_signals[key_ix].col(i).array() * proj_1mer[i];\n          }\n          // Replace signal with coefficient projection of 1mer\n          proj_signal.resize(key_signals[key_ix].rows(),key_signals[key_ix].cols());\n          for (int i = 0; i < key_signals[key_ix].cols(); i++) {\n            //key_signals[key_ix].col(i).array() = coefficients.array() * proj_1mer[i];\n            proj_signal.col(i).array() = coefficients.array() * proj_1mer[i];\n          }\n        }\n        if (m_peak_signal_frames) {\n          int max_frame = 0;\n          float max_value = 0;\n          for (int i = 0; i < (int)m_num_frames; i++) {\n            if (max_value < m_avg_1mer[i]) {\n              max_value = m_avg_1mer[i];\n              max_frame = i;\n            }\n          }\n          m_peak_start = max(max_frame - MAX_PEAK_WINDOW,0);\n          m_peak_end = min((size_t)(max_frame+ MAX_PEAK_WINDOW),m_num_frames);\n        }\n        if (m_normalize_1mers) {\n          float * norm_1mer = &key_norm_signals[key_ix][0];\n          Calculate1MerNormalization(m_num_flows, m_num_frames, \n                                     keys[key_ix].onemerFlows,\n                                     m_flow_avg_1mer, m_flow_count_1mer,\n                                     norm_1mer,\n                                     m_integration_start, \n                                     m_integration_end);\n        }          \n        Eigen::MatrixXf *signal = &key_signals[key_ix];\n        if (m_use_projection) {\n          signal = &proj_signal;\n        }\n        // rescore the key signals after all modifications\n        ScoreKeySignals(keys[key_ix], signal->data(),\n                        m_integration_start, m_integration_end,\n                        m_peak_start, m_peak_end,\n                        &(key_norm_signals[key_ix][0]),\n                        key_results[key_ix].data(), key_results[key_ix].cols(), \n                        key_taub[key_ix].data(), taue_est);\n      }\n    }\n  }\n\n  // For each well pick the best key... \n  int col_size = col_end - col_start;\n  int sum_flow_frame_stride = m_num_frames * m_num_flows;\n  std::vector<float> key_flow_avg_sum(keys.size() * sum_flow_frame_stride, 0);\n  m_key_counts.resize(keys.size(), 0);\n  std::fill(m_key_counts.begin(), m_key_counts.end(), 0);\n  m_flow_key_avg.resize(keys.size() * m_num_flows * m_num_frames);\n  std::fill(m_flow_key_avg.begin(), m_flow_key_avg.end(), 0.0f);\n  Eigen::Map<Eigen::VectorXf, Eigen::Aligned> dark_matter(m_avg_0mer, m_num_frames);\n  for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n    for (int col_ix = col_start; col_ix < col_end; col_ix++) {\n      int global_index = row_ix * col_stride + col_ix;\n      int local_index = (row_ix - row_start) * col_size + (col_ix - col_start);\n      key_fits[global_index].wellIdx = global_index;\n      // @todo cws copy in the best signal here as well, with library or best key if not called though?\n      PickBestKey(key_results, keys, local_index, global_index, key_fits[global_index]);\n      // store the preferred zeromer and stats for chosen key if we're doing a dump of data\n      int key_ix = key_fits[global_index].keyIndex;\n      bool no_nan = true;\n      if (key_ix >= 0) {\n        for (size_t frame_ix = 0; frame_ix < m_num_frames; frame_ix++) {\n          for (size_t flow_ix = 0; flow_ix < m_num_flows; flow_ix++) {\n            size_t z_ix = flow_ix * m_num_wells + local_index;\n            if (!isfinite(key_signals[key_ix].coeff(z_ix, frame_ix))) {\n              no_nan = false;\n            }\n          }\n        }\n      }\n      if (no_nan) {\n        if (key_ix >= 0 && bad_wells[global_index] == 0 && \n            key_results[key_ix].coeff(local_index, PEAK_IDX) > MIN_CRAZY_PEAK_VAL &&\n            key_results[key_ix].coeff(local_index, PEAK_IDX) < MAX_CRAZY_PEAK_VAL) {\n          m_key_counts[key_ix]++;\n          int sum_index = key_ix * sum_flow_frame_stride;\n          for (size_t frame_ix = 0; frame_ix < m_num_frames; frame_ix++) {\n            for (size_t flow_ix = 0; flow_ix < m_num_flows; flow_ix++) {\n              size_t z_ix = flow_ix * m_num_wells + local_index;\n              key_flow_avg_sum[sum_index + flow_ix * m_num_frames + frame_ix] += key_signals[key_ix].coeff(z_ix, frame_ix);\n            }\n          }\n        }\n      }\n      if (m_debug) {\n        key_ix = max(0,key_ix);\n        for (size_t flow_ix = 0; flow_ix < m_num_flows; flow_ix++) {\n          size_t z_ix = flow_ix * m_num_wells + local_index;\n          zeromer_est.row(z_ix).array()  = trace_data.row(z_ix).array() - key_signals[key_ix].row(z_ix).array();\n          zeromer_est.row(z_ix).array() -= dark_matter.array(); // set\n        }\n        // for (size_t frame_ix = 0; frame_ix < m_num_frames; frame_ix++) {\n        //   zeromer_est.col(frame_ix).array() = zeromer_est.col(frame_ix).array() + m_avg_0mer[frame_ix]; // add back the dark matter, should be zeros if not using\n        // }\n      }\n    }\n  }\n  for (size_t key_ix = 0; key_ix < keys.size(); key_ix++) {\n    if (m_key_counts[key_ix] > 0) {\n      int sum_index = key_ix * sum_flow_frame_stride;\n      int sum_index_end = sum_index + sum_flow_frame_stride;\n      for (int i = sum_index; i < sum_index_end; i++) {\n        m_flow_key_avg[i] = key_flow_avg_sum[i] / m_key_counts[key_ix];\n      }\n    }\n  }                                                        \n}\n", "meta": {"hexsha": "cd7dcc4916503d858d5a3cfb0d52a5d8f2341bbb", "size": 31715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/Separator/EvaluateKey.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/EvaluateKey.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/EvaluateKey.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": 45.6330935252, "max_line_length": 265, "alphanum_fraction": 0.6350622734, "num_tokens": 8499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16438044920366546}}
{"text": "//\n// Created by judith on 08.03.19.\n//\n\n#include \"bitbots_localization/map.h\"\n#include <boost/filesystem.hpp>\n#include <ros/package.h>\n\nnamespace fs = boost::filesystem;\n\nMap::Map(const std::string& name, const std::string& type, const bl::LocalizationConfig &config) {\n  // Set config\n  config_ = config;\n  //get package path\n  std::string package_path = ros::package::getPath(\"bitbots_localization\");\n  //make boost path\n  fs::path map_path = fs::path(\"config/fields\") / fs::path(name) / fs::path(type);\n  //convert to absolute path\n  fs::path absolute_map_path = fs::absolute(map_path, package_path);\n  //load map\n  map = cv::imread(absolute_map_path.string(), cv::IMREAD_GRAYSCALE);\n  if (!map.data) {\n    ROS_ERROR(\"No image data '%s'\", map_path.c_str());\n  }\n}\n\ndouble Map::get_occupancy(double x, double y) {\n  //get dimensions of field\n  int mapWidth = map.cols;\n  int mapHeight = map.rows;\n\n  // m to pixel (=cm)\n  x = x * 100;\n  y = y * 100;\n\n  // ursprung in feldmitte\n  x = std::round(x + mapWidth / 2.0); //assuming lines are centered on map\n  y = std::round(y + mapHeight / 2.0);\n\n  double occupancy = -config_.measurement_out_of_map_punishment; // punish points outside the map\n\n  if (x < mapWidth && x >= 0 && y < mapHeight && y >= 0) {\n    occupancy = 100 - map.at<uchar>(y, x);\n  }\n  return occupancy;\n}\n\nstd::vector<double> Map::provideRating(const RobotState &state,\n                                       const std::vector<std::pair<double, double>> &observations) {\n  std::vector<double> rating;\n  for (const std::pair<double, double> &observation : observations) {\n    //lines are in polar form!\n    std::pair<double, double> lineRelative;\n\n    // get rating per line\n    lineRelative = observationRelative(observation, state.getXPos(), state.getYPos(), state.getTheta());\n    double occupancy = get_occupancy(lineRelative.first, lineRelative.second);\n\n    rating.push_back(occupancy);\n  }\n  return rating;\n}\n\nstd::pair<double, double> Map::observationRelative(std::pair<double, double> observation,\n                                                   double stateX,\n                                                   double stateY,\n                                                   double stateT) { // todo rename to a more correct name like observationonmap?\n  // transformes observation from particle to map (assumes particle is correct)\n  // input: obsservation relative in polar coordinates and particle\n  // output: hypothetical observation on map\n\n  // add theta and convert back to cartesian\n  std::pair<double, double> observationWithTheta = polarToCartesian(observation.first + stateT, observation.second);\n\n  // add to particle\n  std::pair<double, double>\n      observationRelative = std::make_pair(stateX + observationWithTheta.first, stateY + observationWithTheta.second);\n\n  //alternativ:\n  //Thrun 6.32, seite 169\n  // but both equivalent\n  //double xGlobal = stateX + observation.second * (cos(stateT + observation.first));\n  //double yGlobal = stateY + observation.second * (sin(stateT + observation.first));\n\n  //std::pair<double, double> observationRelative = std::make_pair(xGlobal, yGlobal);\n\n  return observationRelative; // in cartesian\n\n\n}\n\n\n\n\n", "meta": {"hexsha": "08e0857be11c21c5be6f6d39531806d17483b810", "size": 3192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bitbots_navigation/bitbots_localization/src/map.cpp", "max_stars_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_stars_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-30T06:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:48:43.000Z", "max_issues_repo_path": "bitbots_navigation/bitbots_localization/src/map.cpp", "max_issues_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_issues_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 83.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T16:34:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T17:02:06.000Z", "max_forks_repo_path": "bitbots_navigation/bitbots_localization/src/map.cpp", "max_forks_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_forks_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-07-28T11:24:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T16:20:20.000Z", "avg_line_length": 33.6, "max_line_length": 128, "alphanum_fraction": 0.6616541353, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.16438044248284375}}
{"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_X86_AVX_LIMITS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_AVX_LIMITS_HPP_INCLUDED\n\n#include <boost/simd/arch/x86/tags.hpp>\n#include <boost/simd/arch/common/limits.hpp>\n#include <boost/simd/detail/brigand.hpp>\n\nnamespace boost { namespace simd\n{\n  template<> struct limits<boost::simd::avx_>\n  {\n    struct largest_integer\n    {\n      template<typename Sign> struct apply : boost::dispatch::make_integer<8,Sign> {};\n    };\n\n    struct smallest_integer\n    {\n      template<typename Sign> struct apply : boost::dispatch::make_integer<1,Sign> {};\n    };\n\n    using parent = boost::simd::sse2_;\n\n    using smallest_real = float;\n    using largest_real  = double;\n\n    enum { bits = 256, bytes = 32 };\n  };\n} }\n\n#endif\n\n", "meta": {"hexsha": "ac620787802683ee372046ccd4402d525959b773", "size": 1120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/avx/limits.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/x86/avx/limits.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/x86/avx/limits.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": 27.3170731707, "max_line_length": 100, "alphanum_fraction": 0.5785714286, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.16416959009771503}}
{"text": "/*\n * Copyright (C) 2012 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#include <algorithm>\n#include <fstream>\n#include <sstream>\n#include <memory>\n\n#include <boost/algorithm/string.hpp>\n#include <ignition/math/Helpers.hh>\n#include <ignition/math/Vector3.hh>\n#include <ignition/math/Matrix4.hh>\n\n#include \"gazebo/common/CommonIface.hh\"\n#include \"gazebo/common/BVHLoader.hh\"\n#include \"gazebo/common/SystemPaths.hh\"\n#include \"gazebo/common/Skeleton.hh\"\n#include \"gazebo/common/SkeletonAnimation.hh\"\n#include \"gazebo/common/Console.hh\"\n\nusing namespace gazebo;\nusing namespace common;\n\n/////////////////////////////////////////////////\nBVHLoader::BVHLoader()\n{\n}\n\n/////////////////////////////////////////////////\nBVHLoader::~BVHLoader()\n{\n}\n\n/////////////////////////////////////////////////\nSkeleton *BVHLoader::Load(const std::string &_filename, double _scale)\n{\n  std::string fullname = common::find_file(_filename);\n  if (fullname.empty())\n    return nullptr;\n\n  std::unique_ptr<Skeleton> skeleton;\n  std::ifstream file;\n  file.open(fullname.c_str());\n  std::vector<SkeletonNode*> nodes;\n  std::vector<std::vector<std::string> > nodeChannels;\n  unsigned int totalChannels = 0;\n  std::string line;\n  if (file.is_open())\n  {\n    getline(file, line);\n    if (line.find(\"HIERARCHY\") == std::string::npos)\n    {\n      file.close();\n      return nullptr;\n    }\n\n    SkeletonNode *parent = nullptr;\n    SkeletonNode *node = nullptr;\n    while (!file.eof())\n    {\n      getline(file, line);\n      std::vector<std::string> words;\n      boost::trim(line);\n      boost::split(words, line, boost::is_any_of(\" \\t\"));\n      if (words[0] == \"ROOT\" || words[0] == \"JOINT\")\n      {\n        if (words.size() < 2)\n        {\n          file.close();\n          return nullptr;\n        }\n        SkeletonNode::SkeletonNodeType type = SkeletonNode::JOINT;\n        std::string name = words[1];\n        node = new SkeletonNode(parent, name, name, type);\n        if (words[0] != \"End\")\n          nodes.push_back(node);\n      }\n      else\n        if (words[0] == \"OFFSET\")\n        {\n          if (words.size() < 4)\n          {\n            file.close();\n            return nullptr;\n          }\n          ignition::math::Vector3d offset = ignition::math::Vector3d(\n              ignition::math::parseFloat(words[1]) * _scale,\n              ignition::math::parseFloat(words[2]) * _scale,\n              ignition::math::parseFloat(words[3]) * _scale);\n          ignition::math::Matrix4d transform(\n              ignition::math::Matrix4d::Identity);\n          transform.SetTranslation(offset);\n          node->SetTransform(transform);\n        }\n        else\n          if (words[0] == \"CHANNELS\")\n          {\n            if (words.size() < 3 ||\n                static_cast<size_t>(ignition::math::parseInt(words[1]) + 2) >\n                 words.size())\n            {\n              file.close();\n              return nullptr;\n            }\n            nodeChannels.push_back(words);\n            totalChannels += ignition::math::parseInt(words[1]);\n          }\n          else\n            if (words[0] == \"{\")\n              parent = node;\n            else\n              if (words[0] == \"}\")\n                parent = parent->GetParent();\n              else\n                if (words.size() == 2 && words[0] == \"End\"\n                        && words[1] == \"Site\")\n                {\n                  /// ignore End Sites\n                  getline(file, line);  /// read {\n                  getline(file, line);  /// read OFFSET\n                  getline(file, line);  /// read }\n                }\n                else\n                {\n                  if (nodes.empty())\n                  {\n                    file.close();\n                    return nullptr;\n                  }\n                  skeleton.reset(new Skeleton(nodes[0]));\n                  break;\n                }\n    }\n  }\n  getline(file, line);\n  std::vector<std::string> words;\n  boost::trim(line);\n  boost::split(words, line, boost::is_any_of(\" \\t\"));\n  unsigned int frameCount = 0;\n  double frameTime = 0.0;\n  if (words[0] != \"Frames:\" || words.size() < 2)\n  {\n    file.close();\n    return nullptr;\n  }\n  else\n    frameCount = ignition::math::parseInt(words[1]);\n\n  getline(file, line);\n  words.clear();\n  boost::trim(line);\n  boost::split(words, line, boost::is_any_of(\" \\t\"));\n\n  if (words.size() < 3 || words[0] != \"Frame\" || words[1] != \"Time:\")\n  {\n    file.close();\n    return nullptr;\n  }\n  else\n    frameTime = ignition::math::parseFloat(words[2]);\n\n  double time = 0.0;\n  unsigned int frameNo = 0;\n\n  SkeletonAnimation *animation = new SkeletonAnimation(_filename);\n\n  while (!file.eof())\n  {\n    getline(file, line);\n    words.clear();\n    boost::trim(line);\n    boost::split(words, line, boost::is_any_of(\" \\t\"));\n    if (words.size() < totalChannels)\n    {\n      gzwarn << \"Frame \" << frameNo << \" invalid.\\n\";\n      frameNo++;\n      time += frameTime;\n      continue;\n    }\n\n    unsigned int cursor = 0;\n    for (unsigned int i = 0; i < nodes.size(); ++i)\n    {\n      SkeletonNode *node = nodes[i];\n      std::vector<std::string> channels = nodeChannels[i];\n      ignition::math::Vector3d translation = node->Transform().Translation();\n      ignition::math::Vector3d xAxis(1, 0, 0);\n      ignition::math::Vector3d yAxis(0, 1, 0);\n      ignition::math::Vector3d zAxis(0, 0, 1);\n      double xAngle = 0.0;\n      double yAngle = 0.0;\n      double zAngle = 0.0;\n      ignition::math::Matrix4d transform(ignition::math::Matrix4d::Identity);\n      std::vector<ignition::math::Matrix4d> mats;\n      unsigned int chanCount = ignition::math::parseInt(channels[1]);\n      for (unsigned int j = 2; j < (2 + chanCount); ++j)\n      {\n        double value = ignition::math::parseFloat(words[cursor]);\n        cursor++;\n        std::string channel = channels[j];\n        if (channel == \"Xposition\")\n          translation.X(value * _scale);\n        else\n          if (channel == \"Yposition\")\n            translation.Y(value * _scale);\n          else\n          {\n            if (channel == \"Zposition\")\n            {\n              translation.Z(value * _scale);\n            }\n            else\n            {\n              if (channel == \"Zrotation\")\n              {\n                zAngle = IGN_DTOR(value);\n                mats.push_back(ignition::math::Matrix4d(\n                      ignition::math::Quaterniond(zAxis, zAngle)));\n              }\n              else\n              {\n                if (channel == \"Xrotation\")\n                {\n                  xAngle = IGN_DTOR(value);\n                  mats.push_back(ignition::math::Matrix4d(\n                    ignition::math::Quaterniond(xAxis, xAngle)));\n                }\n                else\n                {\n                  if (channel == \"Yrotation\")\n                  {\n                    yAngle = IGN_DTOR(value);\n                    mats.push_back(ignition::math::Matrix4d(\n                      ignition::math::Quaterniond(yAxis, yAngle)));\n                  }\n                }\n              }\n            }\n          }\n      }\n      while (!mats.empty())\n      {\n        transform = mats.back() * transform;\n        mats.pop_back();\n      }\n      ignition::math::Matrix4d pos(ignition::math::Matrix4d::Identity);\n      pos.SetTranslation(translation);\n      transform = pos * transform;\n      animation->AddKeyFrame(node->GetName(), time, transform);\n    }\n\n    frameNo++;\n    time += frameTime;\n    if (frameNo == frameCount)\n      break;\n  }\n  if (frameNo < frameCount - 1)\n    gzwarn << \"BVH file ended unexpectedly.\\n\";\n\n  skeleton->AddAnimation(animation);\n\n  file.close();\n  return skeleton.release();\n}\n", "meta": {"hexsha": "a3fabe546e367b47edcd474f89f455b16bd07bbe", "size": 8167, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gazebo/common/BVHLoader.cc", "max_stars_repo_name": "traversaro/gazebo", "max_stars_repo_head_hexsha": "6fd426b3949c4ca73fa126cde68f5cc4a59522eb", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 887.0, "max_stars_repo_stars_event_min_datetime": "2020-04-18T08:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:58:50.000Z", "max_issues_repo_path": "gazebo/common/BVHLoader.cc", "max_issues_repo_name": "traversaro/gazebo", "max_issues_repo_head_hexsha": "6fd426b3949c4ca73fa126cde68f5cc4a59522eb", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 462.0, "max_issues_repo_issues_event_min_datetime": "2020-04-21T21:59:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:23:21.000Z", "max_forks_repo_path": "gazebo/common/BVHLoader.cc", "max_forks_repo_name": "traversaro/gazebo", "max_forks_repo_head_hexsha": "6fd426b3949c4ca73fa126cde68f5cc4a59522eb", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T09:13:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T02:22:01.000Z", "avg_line_length": 29.3776978417, "max_line_length": 77, "alphanum_fraction": 0.5250397943, "num_tokens": 1915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16416958677474155}}
{"text": "/**\n * Copyright (c) 2017 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 <numeric>\n#include <sstream>\n\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"dbglog/dbglog.hpp\"\n\n#include \"utility/binaryio.hpp\"\n#include \"utility/streams.hpp\"\n\n#include \"math/math.hpp\"\n\n#include \"../vts/tileset/driver.hpp\"\n#include \"../vts/opencv/atlas.hpp\"\n#include \"../vts/tileset/config.hpp\"\n\n#include \"tmptileset.hpp\"\n\nnamespace fs = boost::filesystem;\nnamespace bin = utility::binaryio;\n\nnamespace vtslibs { namespace vts { namespace tools {\n\nnamespace {\n\n// mesh proper\nconst char MAGIC[2] = { 'S', 'M' };\nconst std::uint16_t VERSION_ORIGINAL = 1;\nconst std::uint16_t VERSION_ZINDEX = 2;\nconst std::uint16_t VERSION = VERSION_ZINDEX;\n\nbool isShort(std::size_t size) {\n    return size <= std::numeric_limits<std::uint16_t>::max();\n}\n\nvoid saveSimpleMesh(std::ostream &out, const Mesh &mesh)\n{\n    // helper functions\n    auto saveVertexComponent([&out](double v, double o, double s) -> void\n    {\n        bin::write\n            (out, std::uint32_t\n             (std::round\n              (((v - o) * std::numeric_limits<std::uint32_t>::max()) / s)));\n    });\n\n    auto saveTexCoord([&out](double v)\n    {\n        v = std::round(math::clamp(v, 0.0, 1.0)\n                       * std::numeric_limits<std::uint32_t>::max());\n        bin::write(out, std::uint32_t(v));\n    });\n\n    // write header\n    bin::write(out, MAGIC);\n    bin::write(out, std::uint16_t(VERSION));\n\n    bin::write(out, std::uint16_t(mesh.submeshes.size()));\n\n    // write submeshes\n    for (const auto &sm : mesh) {\n        // compute extents\n        const auto bbox(extents(sm));\n        const math::Point3d bbsize(bbox.ur - bbox.ll);\n\n        // write extents\n        bin::write(out, bbox.ll(0));\n        bin::write(out, bbox.ll(1));\n        bin::write(out, bbox.ll(2));\n        bin::write(out, bbox.ur(0));\n        bin::write(out, bbox.ur(1));\n        bin::write(out, bbox.ur(2));\n\n        // write vertices\n        bin::write(out, std::uint32_t(sm.vertices.size()));\n        const bool shortVertices(isShort(sm.vertices.size()));\n        for (const auto &vertex : sm.vertices) {\n            saveVertexComponent(vertex(0), bbox.ll(0), bbsize(0));\n            saveVertexComponent(vertex(1), bbox.ll(1), bbsize(1));\n            saveVertexComponent(vertex(2), bbox.ll(2), bbsize(2));\n        }\n\n        // write tc\n        bin::write(out, std::uint32_t(sm.tc.size()));\n        const bool shortTc(isShort(sm.tc.size()));\n        for (const auto &tc : sm.tc) {\n            saveTexCoord(tc(0));\n            saveTexCoord(tc(1));\n        }\n\n        // save faces\n        bin::write(out, std::uint32_t(sm.faces.size()));\n\n        auto ifacesTc(sm.facesTc.begin());\n        for (auto &face : sm.faces) {\n            // face\n            if (shortVertices) {\n                bin::write(out, std::uint16_t(face(0)));\n                bin::write(out, std::uint16_t(face(1)));\n                bin::write(out, std::uint16_t(face(2)));\n            } else {\n                bin::write(out, std::uint32_t(face(0)));\n                bin::write(out, std::uint32_t(face(1)));\n                bin::write(out, std::uint32_t(face(2)));\n            }\n\n            // tc face\n            if (shortTc) {\n                bin::write(out, std::uint16_t((*ifacesTc)(0)));\n                bin::write(out, std::uint16_t((*ifacesTc)(1)));\n                bin::write(out, std::uint16_t((*ifacesTc)(2)));\n            } else {\n                bin::write(out, std::uint32_t((*ifacesTc)(0)));\n                bin::write(out, std::uint32_t((*ifacesTc)(1)));\n                bin::write(out, std::uint32_t((*ifacesTc)(2)));\n            }\n\n            ++ifacesTc;\n        }\n\n        // write zIndex\n        bin::write(out, std::uint32_t(sm.zIndex));\n    }\n}\n\nMesh loadSimpleMesh(std::istream &in, const fs::path &path)\n{\n    // helper functions\n    auto loadVertexComponent([&in](double o, double s) -> double\n    {\n        std::uint32_t v;\n        bin::read(in, v);\n        return o + ((v * s) / std::numeric_limits<std::uint32_t>::max());\n    });\n\n    auto loadTexCoord([&in]() -> double\n    {\n        std::uint32_t v;\n        bin::read(in, v);\n        return (double(v) / std::numeric_limits<std::uint32_t>::max());\n    });\n\n    // Load mesh headers first\n    char magic[sizeof(MAGIC)];\n    std::uint16_t version;\n\n    bin::read(in, magic);\n    bin::read(in, version);\n\n    LOG(info1) << \"Mesh version: \" << version;\n\n    if (std::memcmp(magic, MAGIC, sizeof(MAGIC))) {\n        LOGTHROW(err1, storage::BadFileFormat)\n            << \"File \" << path << \" is not a VTS simplemesh file.\";\n    }\n    if (version > VERSION) {\n        LOGTHROW(err1, storage::VersionError)\n            << \"File \" << path\n            << \" has unsupported version (\" << version << \").\";\n    }\n\n    auto versionedSize([&]() -> std::uint32_t\n    {\n        if (version > 0) {\n            return bin::read<std::uint32_t>(in);\n        }\n\n        return bin::read<std::uint16_t>(in);\n    });\n\n    std::uint16_t subMeshCount;\n    bin::read(in, subMeshCount);\n\n    Mesh mesh;\n\n    mesh.submeshes.resize(subMeshCount);\n    for (auto &sm : mesh) {\n        // load sub-mesh bounding box\n        math::Extents3 bbox;\n        bin::read(in, bbox.ll(0));\n        bin::read(in, bbox.ll(1));\n        bin::read(in, bbox.ll(2));\n        bin::read(in, bbox.ur(0));\n        bin::read(in, bbox.ur(1));\n        bin::read(in, bbox.ur(2));\n\n        const math::Point3d bbsize(bbox.ur - bbox.ll);\n\n        // load vertices\n        auto vertexCount(versionedSize());\n        const bool shortVertices(isShort(vertexCount));\n        sm.vertices.resize(vertexCount);\n        for (auto &vertex : sm.vertices) {\n            vertex(0) = loadVertexComponent(bbox.ll(0), bbsize(0));\n            vertex(1) = loadVertexComponent(bbox.ll(1), bbsize(1));\n            vertex(2) = loadVertexComponent(bbox.ll(2), bbsize(2));\n        }\n\n        // load tc\n        auto tcCount(versionedSize());\n        const bool shortTc(isShort(tcCount));\n        sm.tc.resize(tcCount);\n        for (auto &tc : sm.tc) {\n            tc(0) = loadTexCoord();\n            tc(1) = loadTexCoord();\n        }\n\n        // load faces\n        std::uint32_t faceCount(versionedSize());\n        sm.faces.resize(faceCount);\n        sm.facesTc.resize(faceCount);\n        auto ifacesTc(sm.facesTc.begin());\n\n        for (auto &face : sm.faces) {\n            if (shortVertices) {\n                face(0) = bin::read<std::uint16_t>(in);\n                face(1) = bin::read<std::uint16_t>(in);\n                face(2) = bin::read<std::uint16_t>(in);\n            } else {\n                face(0) = bin::read<std::uint32_t>(in);\n                face(1) = bin::read<std::uint32_t>(in);\n                face(2) = bin::read<std::uint32_t>(in);\n            }\n\n            if (shortTc) {\n                (*ifacesTc)(0) = bin::read<std::uint16_t>(in);\n                (*ifacesTc)(1) = bin::read<std::uint16_t>(in);\n                (*ifacesTc)(2) = bin::read<std::uint16_t>(in);\n            } else {\n                (*ifacesTc)(0) = bin::read<std::uint32_t>(in);\n                (*ifacesTc)(1) = bin::read<std::uint32_t>(in);\n                (*ifacesTc)(2) = bin::read<std::uint32_t>(in);\n            }\n\n            ++ifacesTc;\n        }\n\n        if (version >= VERSION_ZINDEX) {\n            sm.zIndex = bin::read<std::uint32_t>(in);\n        }\n    }\n\n    return mesh;\n}\n\n} // namespace\n\nclass TmpTileset::Slice {\npublic:\n    typedef std::shared_ptr<Slice> pointer;\n    struct OpenTag {};\n\n    Slice(const fs::path &root)\n        : driver_(Driver::create(root, driver::PlainOptions(5), {}))\n    {}\n\n    Slice(const fs::path &root, const OpenTag&)\n        : driver_(Driver::open(root, Driver::BareConfigTag{}, {}))\n    {\n        index_.load(driver_->input(File::tileIndex)->get());\n    }\n\n    bool hasTile(const TileId &tileId) const {\n        return index_.get(tileId);\n    }\n\n    TileIndex::Flag::value_type getTile(const TileId &tileId) const {\n        return index_.get(tileId);\n    }\n\n    void setTile(const TileId &tileId\n                 , const TileIndex::Flag::value_type extraFlags)\n    {\n        index_.set(tileId\n                   , (extraFlags | TileIndex::Flag::mesh\n                      | TileIndex::Flag::atlas));\n    }\n\n    Driver::pointer driver() { return driver_; }\n\n    Driver::pointer driver() const { return driver_; }\n\n    const TileIndex& index() { return index_; }\n\n    void flush() {\n        {\n            auto f(driver_->output(File::tileIndex));\n            index_.save(f->get());\n            f->close();\n        }\n        {\n            auto f(driver_->output(File::config));\n            vts::tileset::saveDriver(f->get(), driver_->options());\n            f->close();\n        }\n        driver_->flush();\n    }\n\n    void saveMesh(const TileId &tileId, const Mesh &mesh);\n    void saveAtlas(const TileId &tileId, const Atlas &atlas);\n\n    IStream::pointer input(const TileId &tileId, TileFile type) {\n        std::unique_lock<std::mutex> lock(mutex_);\n        return driver_->input(tileId, type);\n    }\n\nprivate:\n    std::mutex mutex_;\n    TileIndex index_;\n    Driver::pointer driver_;\n};\n\nvoid TmpTileset::Slice::saveMesh(const TileId &tileId, const Mesh &mesh)\n{\n    std::stringstream tmp;\n    saveSimpleMesh(tmp, mesh);\n\n    {\n        std::unique_lock<std::mutex> lock(mutex_);\n        auto os(driver_->output(tileId, storage::TileFile::mesh));\n        copyFile(tmp, os);\n        os->close();\n    }\n}\n\nvoid TmpTileset::Slice::saveAtlas(const TileId &tileId, const Atlas &atlas)\n{\n    std::stringstream tmp;\n    atlas.serialize(tmp);\n    {\n        std::unique_lock<std::mutex> lock(mutex_);\n        auto os(driver_->output(tileId, storage::TileFile::atlas));\n        copyFile(tmp, os);\n        os->close();\n    }\n}\n\nTmpTileset::TmpTileset(const boost::filesystem::path &root\n                       , bool create)\n    : root_(root), keep_(false)\n{\n    if (create) {\n        // make room for tilesets\n        fs::remove_all(root_);\n        // create root for tilesets\n        fs::create_directories(root_);\n        return;\n    }\n\n    for (int i(0);; ++i) {\n        auto path(root_ / boost::lexical_cast<std::string>(i));\n        if (!exists(path)) { break; }\n        slices_.push_back(std::make_shared<Slice>(path, Slice::OpenTag{}));\n    }\n\n    if (slices_.empty()) {\n        LOGTHROW(err1, std::runtime_error)\n            << \"No tileset slice found in temporary tileset \" << root_ << \".\";\n    }\n}\n\nTmpTileset::~TmpTileset()\n{\n    // cleanup\n    if (!keep_) {\n        fs::remove_all(root_);\n    }\n}\n\nvoid TmpTileset::store(const TileId &tileId, const Mesh &mesh\n                       , const Atlas &atlas\n                       , const TileIndex::Flag::value_type extraFlags)\n{\n    LOG(debug)\n        << tileId << \" Storing mesh with \"\n        << std::accumulate(mesh.begin(), mesh.end(), std::size_t(0)\n                           , [](std::size_t v, const SubMesh &sm) {\n                               return v + sm.faces.size();\n                           })\n        << \" faces.\";\n\n    // get driver for tile\n    auto slice([&]() -> Slice::pointer\n    {\n        std::unique_lock<std::mutex> lock(mutex_);\n        for (auto &slice : slices_) {\n            // TODO: make get/set in one pass\n            if (!slice->hasTile(tileId)) {\n                slice->setTile(tileId, extraFlags);\n                return slice;\n            }\n        }\n\n        // no available slice for this tile, create new\n        // path\n        auto path(root_ / boost::lexical_cast<std::string>(slices_.size()));\n        LOG(info3) << \"Creating temporary tileset at \" << path << \".\";\n        slices_.push_back(std::make_shared<Slice>(path));\n        auto &slice(slices_.back());\n        slice->setTile(tileId, extraFlags);\n        return slice;\n    }());\n\n    slice->saveMesh(tileId, mesh);\n    slice->saveAtlas(tileId, atlas);\n}\n\nTmpTileset::Tile\nTmpTileset::load(const TileId &tileId, int quality) const\n{\n    Tile tile;\n    auto &mesh(std::get<0>(tile));\n    auto &atlas(std::get<1>(tile));\n    auto &flags(std::get<2>(tile));\n\n    flags = 0;\n\n    for (const auto &slice : slices_) {\n        auto sliceFlags(slice->getTile(tileId));\n        if (!sliceFlags) { continue; }\n\n        // remember flags\n        flags |= sliceFlags;\n\n        auto driver(slice->driver());\n\n        auto is(slice->input(tileId, storage::TileFile::mesh));\n        Mesh m(loadSimpleMesh(is->get(), is->name()));\n\n        opencv::HybridAtlas a(quality);\n        {\n            auto is(slice->input(tileId, storage::TileFile::atlas));\n            a.deserialize(is->get(), is->name());\n        }\n\n        if (!mesh) {\n            mesh = std::make_shared<Mesh>(m);\n        } else {\n            mesh->submeshes.insert(mesh->submeshes.end(), m.submeshes.begin()\n                                   , m.submeshes.end());\n        }\n\n        if (!atlas) {\n            atlas = std::make_shared<opencv::HybridAtlas>(a);\n        } else {\n            atlas->append(a);\n        }\n    }\n\n    return tile;\n}\n\nvoid TmpTileset::flush()\n{\n    // unlocked!\n    for (const auto &slice : slices_) {\n        slice->flush();\n    }\n}\n\nTileIndex TmpTileset::tileIndex() const\n{\n    TileIndex ti;\n    for (const auto &slice : slices_) {\n        ti = unite(ti, slice->index());\n    }\n    return ti;\n}\n\n} } } // namespace vtslibs::vts::tools\n", "meta": {"hexsha": "04ab6819501496010f9edfe1f45d6be64dac5a1e", "size": 14623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/browser/externals/browser/externals/vts-libs/vts-libs/tools-support/tmptileset.cpp", "max_stars_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_stars_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T08:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T08:42:59.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/vts-libs/vts-libs/tools-support/tmptileset.cpp", "max_issues_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_issues_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "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": "externals/browser/externals/browser/externals/vts-libs/vts-libs/tools-support/tmptileset.cpp", "max_forks_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_forks_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "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.3634538153, "max_line_length": 78, "alphanum_fraction": 0.5570676332, "num_tokens": 3732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.16416958345176813}}
{"text": "// Ogonek\n//\n// Written in 2012-2013 by Martinho Fernandes <martinho.fernandes@gmail.com>\n//\n// To the extent possible under law, the author(s) have dedicated all copyright and related\n// and neighboring rights to this software to the public domain worldwide. This software is\n// distributed without any warranty.\n//\n// You should have received a copy of the CC0 Public Domain Dedication along with this software.\n// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.\n\n// UTF-8 encoding form\n\n#ifndef OGONEK_ENCODING_UTF8_HPP\n#define OGONEK_ENCODING_UTF8_HPP\n\n#include <ogonek/encoding/iterator.h++>\n#include <ogonek/types.h++>\n#include <ogonek/error.h++>\n#include <ogonek/error/unicode_error.h++>\n#include <ogonek/detail/ranges.h++>\n#include <ogonek/detail/constants.h++>\n#include <ogonek/detail/container/partial_array.h++>\n#include <ogonek/detail/container/encoded_character.h++>\n\n#include <taussig/primitives.h++>\n\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/sub_range.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n#include <boost/range/empty.hpp>\n\n#include <array>\n#include <utility>\n\nnamespace ogonek {\n    struct utf8 {\n    private:\n        static constexpr auto last_1byte_value = 0x7Fu;\n        static constexpr auto last_2byte_value = 0x7FFu;\n        static constexpr auto last_3byte_value = 0xFFFFu;\n\n        static constexpr auto start_2byte_mask = 0x80u;\n        static constexpr auto start_3byte_mask = 0xE0u;\n        static constexpr auto start_4byte_mask = 0xF0u;\n\n        static constexpr auto continuation_mask = 0xC0u;\n        static constexpr auto continuation_signature = 0x80u;\n\n        static constexpr int sequence_length(byte b) {\n            return (b & start_2byte_mask) == 0? 1\n                 : (b & start_3byte_mask) != start_3byte_mask? 2\n                 : (b & start_4byte_mask) != start_4byte_mask? 3\n                 : 4;\n        }\n\n        static constexpr code_point decode(byte b0, byte b1) {\n            return ((b0 & 0x1F) << 6) | (b1 & 0x3F);\n        }\n        static constexpr code_point decode(byte b0, byte b1, byte b2) {\n            return ((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F);\n        }\n        static constexpr code_point decode(byte b0, byte b1, byte b2, byte b3) {\n            return ((b0 & 0x07) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F);\n        }\n\n    public:\n        using code_unit = char;\n        static constexpr bool is_fixed_width = false;\n        static constexpr std::size_t max_width = 4;\n        static constexpr bool is_self_synchronizing = true;\n        struct state {};\n\n        template <typename ErrorHandler>\n        static detail::encoded_character<utf8> encode_one(code_point u, state&, ErrorHandler) {\n            if(u <= last_1byte_value) {\n                return { static_cast<code_unit>(u) };\n            } else if(u <= last_2byte_value) {\n                return {\n                    static_cast<code_unit>(0xC0 | ((u & 0x7C0) >> 6)),\n                    static_cast<code_unit>(0x80 | (u & 0x3F)),\n                };\n            } else if(u <= last_3byte_value) {\n                return {\n                    static_cast<code_unit>(0xE0 | ((u & 0xF000) >> 12)),\n                    static_cast<code_unit>(0x80 | ((u & 0xFC0) >> 6)),\n                    static_cast<code_unit>(0x80 | (u & 0x3F)),\n                };\n            }\n            return {\n                static_cast<code_unit>(0xF0 | ((u & 0x1C0000) >> 18)),\n                static_cast<code_unit>(0x80 | ((u & 0x3F000) >> 12)),\n                static_cast<code_unit>(0x80 | ((u & 0xFC0) >> 6)),\n                static_cast<code_unit>(0x80 | (u & 0x3F)),\n            };\n        }\n        template <typename Range>\n        static boost::sub_range<Range> decode_one(Range const& r, code_point& out, state&, assume_valid_t) {\n            auto first = boost::begin(r);\n            byte b0 = *first++;\n            auto length = sequence_length(b0);\n            if(length == 1) {\n                out = b0;\n                return { first, boost::end(r) };\n            }\n            byte b1 = *first++;\n            if(length == 2) {\n                out = decode(b0, b1);\n                return { first, boost::end(r) };\n            }\n            byte b2 = *first++;\n            if(length == 3) {\n                out = decode(b0, b1, b2);\n                return { first, boost::end(r) };\n            }\n            byte b3 = *first++;\n            out = decode(b0, b1, b2, b3);\n            return { first, boost::end(r) };\n        }\n        template <typename Range, typename ErrorHandler>\n        static boost::sub_range<Range> decode_one(Range const& r, code_point& out, state& s, ErrorHandler) {\n            auto first = boost::begin(r);\n            byte b0 = *first++;\n            auto length = sequence_length(b0);\n\n            if(length == 1) {\n                out = b0;\n                return { first, boost::end(r) };\n            }\n\n            auto is_invalid = [](byte b) { return b == 0xC0 || b == 0xC1 || b > 0xF4; };\n            auto is_continuation = [](byte b) {\n                return (b & continuation_mask) == continuation_signature;\n            };\n\n            if(is_invalid(b0) || is_continuation(b0)) {\n                return ErrorHandler::template apply_decode<utf8>(r, s, out);\n            }\n\n            std::array<byte, 4> b = {{ b0, }};\n            for(int i = 1; i < length; ++i) {\n                b[i] = *first++;\n                if(!is_continuation(b[i])) {\n                    return ErrorHandler::template apply_decode<utf8>(r, s, out);\n                }\n            }\n\n            if(length == 2) {\n                out = decode(b[0], b[1]);\n            } else if(length == 3) {\n                out = decode(b[0], b[1], b[2]);\n            } else {\n                out = decode(b[0], b[1], b[2], b[3]);\n            }\n\n            auto is_overlong = [](code_point u, int bytes) {\n                return u <= last_1byte_value\n                    || (u <= last_2byte_value && bytes > 2)\n                    || (u <= last_3byte_value && bytes > 3);\n            };\n            if(is_overlong(out, length)) {\n                return ErrorHandler::template apply_decode<utf8>(r, s, out);\n            }\n            if(detail::is_surrogate(out) || out > detail::last_code_point) {\n                return ErrorHandler::template apply_decode<utf8>(r, s, out);\n            }\n            return { first, boost::end(r) };\n        }\n        template <typename Sequence>\n        static std::pair<Sequence, code_point> decode_one_ex(Sequence s, state&, assume_valid_t) {\n            byte b0 = seq::front(s);\n            seq::pop_front(s);\n            auto length = sequence_length(b0);\n\n            if(length == 1) {\n                return { s, b0 };\n            }\n\n            std::array<byte, 4> b = {{ b0, }};\n            for(int i = 1; i < length; ++i) {\n                b[i] = seq::front(s);\n                seq::pop_front(s);\n            }\n\n            code_point decoded;\n            if(length == 2) {\n                decoded = decode(b[0], b[1]);\n            } else if(length == 3) {\n                decoded = decode(b[0], b[1], b[2]);\n            } else {\n                decoded = decode(b[0], b[1], b[2], b[3]);\n            }\n\n            return { s, decoded };\n        }\n        template <typename Sequence, typename ErrorHandler>\n        static std::pair<Sequence, code_point> decode_one_ex(Sequence s, state& state, ErrorHandler handler) {\n            byte b0 = seq::front(s);\n            seq::pop_front(s);\n            auto length = sequence_length(b0);\n\n            if(length == 1) {\n                return { s, b0 };\n            }\n\n            auto is_invalid = [](byte b) { return b == 0xC0 || b == 0xC1 || b > 0xF4; };\n            auto is_continuation = [](byte b) {\n                return (b & continuation_mask) == continuation_signature;\n            };\n\n            if(is_invalid(b0) || is_continuation(b0)) {\n                decode_error<Sequence, utf8> error { s, state };\n                wheels::optional<code_point> u;\n                std::tie(s, state, u) = handler.handle(error);\n                return { s, *u };\n            }\n\n            std::array<byte, 4> b = {{ b0, }};\n            for(int i = 1; i < length; ++i) {\n                b[i] = seq::front(s);\n                if(!is_continuation(b[i])) {\n                    decode_error<Sequence, utf8> error { s, state };\n                    wheels::optional<code_point> u;\n                    std::tie(s, state, u) = handler.handle(error);\n                    return { s, *u };\n                }\n                seq::pop_front(s);\n            }\n\n            code_point decoded;\n            if(length == 2) {\n                decoded = decode(b[0], b[1]);\n            } else if(length == 3) {\n                decoded = decode(b[0], b[1], b[2]);\n            } else {\n                decoded = decode(b[0], b[1], b[2], b[3]);\n            }\n\n            auto is_overlong = [](code_point u, int bytes) {\n                return u <= last_1byte_value\n                    || (u <= last_2byte_value && bytes > 2)\n                    || (u <= last_3byte_value && bytes > 3);\n            };\n            if(is_overlong(decoded, length)) {\n                decode_error<Sequence, utf8> error { s, state };\n                wheels::optional<code_point> u;\n                std::tie(s, state, u) = handler.handle(error);\n                return { s, *u };\n            }\n            if(detail::is_surrogate(decoded) || decoded > detail::last_code_point) {\n                decode_error<Sequence, utf8> error { s, state };\n                wheels::optional<code_point> u;\n                std::tie(s, state, u) = handler.handle(error);\n                return { s, *u };\n            }\n            return { s, decoded };\n        }\n    };\n} // namespace ogonek\n\n#endif // OGONEK_ENCODING_UTF8_HPP\n\n", "meta": {"hexsha": "2b2bd6001c5d4c2a663ab007fa0ded8780e45bb2", "size": 9887, "ext": "h++", "lang": "C++", "max_stars_repo_path": "include/ogonek/encoding/utf8.h++", "max_stars_repo_name": "libogonek/ogonek", "max_stars_repo_head_hexsha": "46b7edbf6b7ff89892f5ba25494749b442e771b3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2016-10-21T12:37:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T05:46:46.000Z", "max_issues_repo_path": "include/ogonek/encoding/utf8.h++", "max_issues_repo_name": "libogonek/ogonek", "max_issues_repo_head_hexsha": "46b7edbf6b7ff89892f5ba25494749b442e771b3", "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": "include/ogonek/encoding/utf8.h++", "max_forks_repo_name": "libogonek/ogonek", "max_forks_repo_head_hexsha": "46b7edbf6b7ff89892f5ba25494749b442e771b3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-09-05T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T19:37:37.000Z", "avg_line_length": 37.4507575758, "max_line_length": 110, "alphanum_fraction": 0.4992414281, "num_tokens": 2527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16416958012879473}}
{"text": "#include \"modules/bio_base/kmer.h\"\n#include \"modules/bio_mapred/align_kmer.h\"\n#include \"modules/bio_base/astar.h\"\n#include \"modules/io/log.h\"\n#include <boost/operators.hpp>\n\nstatic int best_pow(int loc)\n{\n\tfor(int i = 0; i < 16; i++)\n\t{\n\t\tif ((loc & (1 << i)) != 0)\n\t\t\treturn i;\n\t}\n\treturn 16;\n}\n\nstruct kmer_astar_state\n\t: boost::less_than_comparable<kmer_astar_state>\n\t, boost::equality_comparable<kmer_astar_state>\n{\n\tkmer_astar_state(int _start, int _end, kmer_t _ks, kmer_t _ke)\n\t\t: start(_start)\n\t\t, end(_end)\n\t\t, ks(_ks)\n\t\t, ke(_ke)\n\t{\n\t\tpow2s = best_pow(start);\n\t\tpow2e = best_pow(end);\n\t\tmin_pow = std::min(pow2s, pow2e);\n\t\tmax_pow = std::max(pow2s, pow2e);\n\t}\n\t\t\n\tint start;\n\tint end;\n\tkmer_t ks;\n\tkmer_t ke;\n\tint pow2s;\n\tint pow2e;\n\tint min_pow;\n\tint max_pow;\n\tbool operator<(const kmer_astar_state& rhs) const\n\t{\n\t\tif (min_pow != rhs.min_pow)\n\t\t\treturn min_pow < rhs.min_pow;\n\t\tif (max_pow != rhs.max_pow)\n\t\t\treturn max_pow < rhs.max_pow;\n\t\tif (start != rhs.start)\n\t\t\treturn start < rhs.start;\n\t\tif (end != rhs.end)\n\t\t\treturn end < rhs.end;\n\t\treturn false;\n\t}\n\tbool operator==(const kmer_astar_state& rhs) const\n\t{\n\t\treturn (start == rhs.start && end == rhs.end);\n\t}\n};\n\nstruct kmer_astar_context\n{\n\ttypedef kmer_astar_state location_t;\n\ttypedef double dist_t;\n\tkmer_astar_context(const dna_sequence& read, const std::string& qual, const kmer_set& kmers, double min_base_quality)\n\t\t: m_read(read)\n\t\t, m_qual(qual)\n\t\t, m_kmers(kmers)\n\t\t, m_min_base_quality(min_base_quality)\n\t\t, m_ks(kmers.kmer_size())\n\t{}\n\n\tdouble estimate(const kmer_astar_state& a, const kmer_astar_state& b) const { return 0.0; }\n\n\tstd::vector<std::pair<double, kmer_astar_state> > nearby(const kmer_astar_state& loc) const\n\t{\n\t\tstd::vector<std::pair<double, kmer_astar_state> > r;\n\t\tif (loc.start == loc.end) \n\t\t{\n\t\t\t// Initial state, find all matching kmers\n\t\t\tfor(size_t i = 0; i <= m_read.size() - m_ks; i++)\n\t\t\t{\n\t\t\t\tkmer_t k = make_kmer(m_read.begin() + i, m_ks);\n\t\t\t\tif (m_kmers.count(canonicalize(k, m_ks)))\n\t\t\t\t\tr.push_back(std::make_pair(0.0,\n\t\t\t\t\t\tkmer_astar_state(i, i + m_ks, k, k)));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//SPLOG(\"Processing rs=%d (%d:%d) %s:%s\", m_read.size(), loc.start, loc.end, \n\t\t\t//\tdna_sequence(loc.ks, m_ks).as_string().c_str(),\n\t\t\t//\tdna_sequence(loc.ke, m_ks).as_string().c_str());\n\t\t\tif (loc.pow2s < loc.pow2e && loc.start > 0)\n\t\t\t{\n\t\t\t\t// Try adding in reverse direction\n\t\t\t\tkmer_t k = loc.ks;\n\t\t\t\tfor(int base = 0; base < 4; base++)\n\t\t\t\t{\n\t\t\t\t\tkmer_t k2 = append(base, left(k, m_ks, m_ks-1), m_ks-1);\n\t\t\t\t\tif (m_kmers.count(canonicalize(k2, m_ks)))\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble cost = (dna_base(base) == m_read[loc.start - 1]) ? 0.0 \n\t\t\t\t\t\t\t: std::max(m_min_base_quality, double(m_qual[loc.start - 1] - 33));\n\t\t\t\t\t\tr.push_back(std::make_pair(cost,\n\t\t\t\t\t\t\tkmer_astar_state(loc.start - 1, loc.end, k2, loc.ke)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (loc.end < (int) m_read.size())\n\t\t\t{\n\t\t\t\t// Try adding in forward direction\n\t\t\t\tkmer_t k = loc.ke;\n\t\t\t\tfor(int base = 0; base < 4; base++)\n\t\t\t\t{\n\t\t\t\t\tkmer_t k2 = append(right(k, m_ks-1), base, 1);\n\t\t\t\t\tif (m_kmers.count(canonicalize(k2, m_ks)))\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble cost = (dna_base(base) == m_read[loc.end]) ? 0.0 \n\t\t\t\t\t\t\t: std::max(m_min_base_quality, double(m_qual[loc.end] - 33));\n\t\t\t\t\t\tr.push_back(std::make_pair(cost,\n\t\t\t\t\t\t\tkmer_astar_state(loc.start, loc.end +1, loc.ks, k2)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (loc.start == 0 && loc.end == (int) m_read.size() && loc.ks && loc.ke)\n\t\t\t{\n\t\t\t\tr.push_back(std::make_pair(0.0, kmer_astar_state(0, m_read.size() + 1, 0, 0)));\n\t\t\t}\n\t\t}\n\t\treturn r;\n\t}\n\n\tconst dna_sequence& m_read;\n\tstd::string m_qual;\n\tconst kmer_set& m_kmers;\n\tdouble m_min_base_quality;\n\tsize_t m_ks;\n};\n\nunsigned verify_kmers(const dna_sequence& read, const kmer_set& kmers) {\n  size_t kmer_size = kmers.kmer_size();\n  if (read.size() < kmer_size) return 0;\n  for (size_t i = 0; i <= read.size() - kmer_size; i++) {\n    kmer_t k = make_kmer(read.begin() + i, kmer_size);\n    k = canonicalize(k, kmer_size);\n    if (!kmers.count(k)) {\n      return i + kmer_size - 1;\n    }\n  }\n  return read.size();\n  return true;\n}\n\ndouble align_kmer(std::vector<kmer_t>& out, const dna_sequence& read, const std::string& qual, \n\t\tconst kmer_set& kmers, double min_base_quality, double max_cost)\n{\n\tif (read.size() < kmers.kmer_size()) return max_cost;\n\t\n\tkmer_astar_context ctx(read, qual, kmers, min_base_quality);\n\tkmer_astar_state start(0, 0, 0, 0);\n\tkmer_astar_state end(0, read.size() + 1, 0, 0);\n\tastar_state<kmer_astar_context> as(ctx, start, end, max_cost);\n\tdouble cost = as.run();\n\tif (cost >= max_cost)\n\t\treturn max_cost;\n\tstd::vector<kmer_astar_state> r;\n\tas.get_path(r);\n\tout.resize(read.size() - kmers.kmer_size() + 1);\n\tfor(size_t i = 0; i < r.size(); i++)\n\t{\n\t\tif (r[i].end == 0 || r[i].end > (int) read.size()) continue;\n\t\t//printf(\"Adding (%d, %d) = (%s, %s)\\n\", r[i].start, r[i].end, \n\t\t//\t\tdna_sequence(r[i].ks, kmers.kmer_size()).as_string().c_str(), dna_sequence(r[i].ke, kmers.kmer_size()).as_string().c_str());\n\t\tout[r[i].start] = r[i].ks;\n\t\tout[r[i].end - kmers.kmer_size()] = r[i].ke;\n\t}\n\treturn cost;\n}\n\ndna_sequence get_corrected(const std::vector<kmer_t>& in, size_t kmer_size)\n{\n\tdna_sequence start(in[0], kmer_size);\n\tfor(size_t i = 1; i < in.size(); i++)\n\t{\n\t\tstart.push_back(dna_base((int) right(in[i], 1)));\n\t}\n\treturn start;\n}\n\n", "meta": {"hexsha": "f5117bff6fc5d09dcd912279183f042e4db8df34", "size": 5306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/bio_mapred/align_kmer.cpp", "max_stars_repo_name": "spiralgenetics/biograph", "max_stars_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T23:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:25:15.000Z", "max_issues_repo_path": "modules/bio_mapred/align_kmer.cpp", "max_issues_repo_name": "spiralgenetics/biograph", "max_issues_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-07-20T20:39:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T20:57:59.000Z", "max_forks_repo_path": "modules/bio_mapred/align_kmer.cpp", "max_forks_repo_name": "spiralgenetics/biograph", "max_forks_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-07-15T19:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T19:24:56.000Z", "avg_line_length": 28.0740740741, "max_line_length": 130, "alphanum_fraction": 0.637580098, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.16387336569978145}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n// What's this file supposed to do ?\n//\n// (Pho)tometry (It)eration (Error) Update\n//\n// Equation:\n//\n// e = Sumk( Sumij( ((I - A*T*R)*S)^2 ))\n//\n// If there's no reflectance, don't multiply by it.\n\n#include <vw/Image.h>\n#include <photk/Macros.h>\n#include <photk/Common.h>\n#include <photk/RemoteProjectFile.h>\n#include <photk/ErrorAccumulators.h>\nusing namespace vw;\nusing namespace vw::platefile;\nusing namespace photk;\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nusing namespace std;\n\nstruct Options : photk::BaseOptions {\n  Url ptk_url;\n\n  // For spawning multiple jobs\n  int job_id, num_jobs, level;\n};\n\nvoid update_error( Options& opt ) {\n  RemoteProjectFile remote_ptk( opt.ptk_url );\n  ProjectMeta project_info;\n  remote_ptk.get_project( project_info );\n\n  // Load platefile\n  boost::shared_ptr<PlateFile> drg_plate, albedo_plate, reflect_plate;\n\n  // Deciding what cameras\n  int minidx, maxidx;\n  if (opt.num_jobs > 0) {\n    minidx = float(project_info.num_cameras()*opt.job_id)/float(opt.num_jobs);\n    maxidx = float(project_info.num_cameras()*(opt.job_id+1))/float(opt.num_jobs);\n  \n    remote_ptk.get_platefiles(drg_plate,albedo_plate,reflect_plate);\n\n    if (opt.level < 0 )\n      opt.level = drg_plate->num_levels() - 1;\n  } else {\n    minidx = 0;\n    maxidx = 0;\n  }\n\n  for(int j = minidx; j < maxidx; j++) {\n    CameraMeta cam_info;\n    remote_ptk.get_camera(j, cam_info);\n\n    ErrorNRAccumulatorFunc<double,Vector2i> funcProto(opt.level, j+1, cam_info.exposure_t(), drg_plate, albedo_plate);\n\n    int32 full = 1 << opt.level;\n    BBox2i affected_tiles(0,0,full-1,full-1);\n\n    RecursiveBBoxAccumulator<ErrorNRAccumulatorFunc<double,Vector2i> > accum(32, funcProto);\n\n    ErrorNRAccumulatorFunc<double,Vector2i> funcResult = accum(affected_tiles);\n\n    vw_out() << \"cam[\" << j << \"] error=[\" << funcResult.value() << \"]\\n\";\n\n    // Once I have the API, call funcResult.value() and\n    // add it to the existing value in the current camera\n    if (project_info.current_iteration() == 0) {\n      cam_info.set_init_error(funcResult.value());\n    } else {\n      cam_info.set_last_error(cam_info.curr_error());\n      cam_info.set_curr_error(funcResult.value());\n    }\n\n    remote_ptk.set_camera(j, cam_info);\n  }\n\n  if (opt.num_jobs <= 0) {\n    // Save last error before we overwrite it\n    float32 initError = remote_ptk.get_init_error();\n    float32 lastError = remote_ptk.get_last_error();\n    float32 currError = remote_ptk.get_curr_error();\n\n    // Compare init error and most recent error:\n    vw_out() << \"Init error=[\" << initError << \"]\\n\";\n    vw_out() << \"Last error=[\" << lastError << \"]\\n\";\n    vw_out() << \"Curr error=[\" << currError << \"]\\n\";\n  }\n}\n\nvoid handle_arguments( int argc, char *argv[], Options& opt ) {\n  po::options_description general_options(\"\");\n  general_options.add_options()\n    (\"level,l\", po::value(&opt.level)->default_value(-1), \"Default is to process lowest level.\")\n    (\"job_id,j\", po::value(&opt.job_id)->default_value(0), \"\")\n    (\"num_jobs,n\", po::value(&opt.num_jobs)->default_value(1), \"If num_jobs is 0, don't process anything, just output the error values for the full plate\");\n  general_options.add( photk::BaseOptionsDescription(opt) );\n\n  po::options_description positional(\"\");\n  positional.add_options()\n    (\"ptk_url\",  po::value(&opt.ptk_url),  \"Input PTK Url\");\n\n  po::positional_options_description positional_desc;\n  positional_desc.add(\"ptk_url\", 1);\n\n  std::ostringstream usage;\n  usage << \"Usage: \" << argv[0] << \" <ptk-url>\\n\";\n\n  po::variables_map vm =\n    photk::check_command_line( argc, argv, opt, general_options,\n                             positional, positional_desc, usage.str() );\n\n  if ( opt.ptk_url == Url() )\n    vw_throw( ArgumentErr() << \"Missing project file url!\\n\"\n              << usage.str() << general_options );\n}\n\nint main( int argc, char *argv[] ) {\n\n  Options opt;\n  try {\n    handle_arguments( argc, argv, opt );\n    update_error( opt );\n  } PHOTK_STANDARD_CATCHES;\n\n  return 0;\n}\n", "meta": {"hexsha": "fa675366fe9bfac805814916d01a5b0ce8fd1cbe", "size": 4225, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src_plate_old/tools/phoiterror.cc", "max_stars_repo_name": "NeoGeographyToolkit/PhotometryTK", "max_stars_repo_head_hexsha": "edbfc3fa05ff5dd1c2905843f8f67e8f8f8bffe9", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-13T22:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:09:25.000Z", "max_issues_repo_path": "src_plate_old/tools/phoiterror.cc", "max_issues_repo_name": "NeoGeographyToolkit/PhotometryTK", "max_issues_repo_head_hexsha": "edbfc3fa05ff5dd1c2905843f8f67e8f8f8bffe9", "max_issues_repo_licenses": ["NASA-1.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": "src_plate_old/tools/phoiterror.cc", "max_forks_repo_name": "NeoGeographyToolkit/PhotometryTK", "max_forks_repo_head_hexsha": "edbfc3fa05ff5dd1c2905843f8f67e8f8f8bffe9", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T12:36:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T01:04:32.000Z", "avg_line_length": 30.3956834532, "max_line_length": 156, "alphanum_fraction": 0.6769230769, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.16383427862462493}}
{"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 \"utilities.hpp\"\n\n#include \"toplevelfixture.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <qle/models/cdsoptionhelper.hpp>\n#include <qle/models/cpicapfloorhelper.hpp>\n#include <qle/models/crlgm1fparametrization.hpp>\n#include <qle/models/crossassetanalytics.hpp>\n#include <qle/models/crossassetanalyticsbase.hpp>\n#include <qle/models/crossassetmodel.hpp>\n#include <qle/models/crossassetmodelimpliedeqvoltermstructure.hpp>\n#include <qle/models/crossassetmodelimpliedfxvoltermstructure.hpp>\n#include <qle/models/dkimpliedyoyinflationtermstructure.hpp>\n#include <qle/models/dkimpliedzeroinflationtermstructure.hpp>\n#include <qle/models/eqbsconstantparametrization.hpp>\n#include <qle/models/eqbsparametrization.hpp>\n#include <qle/models/eqbspiecewiseconstantparametrization.hpp>\n#include <qle/models/fxbsconstantparametrization.hpp>\n#include <qle/models/fxbsparametrization.hpp>\n#include <qle/models/fxbspiecewiseconstantparametrization.hpp>\n#include <qle/models/fxeqoptionhelper.hpp>\n#include <qle/models/gaussian1dcrossassetadaptor.hpp>\n#include <qle/models/infdkparametrization.hpp>\n#include <qle/models/irlgm1fconstantparametrization.hpp>\n#include <qle/models/irlgm1fparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiseconstanthullwhiteadaptor.hpp>\n#include <qle/models/irlgm1fpiecewiseconstantparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiselinearparametrization.hpp>\n#include <qle/models/lgm.hpp>\n#include <qle/models/lgmimplieddefaulttermstructure.hpp>\n#include <qle/models/lgmimpliedyieldtermstructure.hpp>\n#include <qle/models/linkablecalibratedmodel.hpp>\n#include <qle/models/parametrization.hpp>\n#include <qle/models/piecewiseconstanthelper.hpp>\n#include <qle/models/pseudoparameter.hpp>\n#include <qle/pricingengines/analyticcclgmfxoptionengine.hpp>\n#include <qle/pricingengines/analyticdkcpicapfloorengine.hpp>\n#include <qle/pricingengines/analyticlgmcdsoptionengine.hpp>\n#include <qle/pricingengines/analyticlgmswaptionengine.hpp>\n#include <qle/pricingengines/analyticxassetlgmeqoptionengine.hpp>\n#include <qle/pricingengines/blackcdsoptionengine.hpp>\n#include <qle/pricingengines/crossccyswapengine.hpp>\n#include <qle/pricingengines/depositengine.hpp>\n#include <qle/pricingengines/discountingcommodityforwardengine.hpp>\n#include <qle/pricingengines/discountingcurrencyswapengine.hpp>\n#include <qle/pricingengines/discountingequityforwardengine.hpp>\n#include <qle/pricingengines/discountingfxforwardengine.hpp>\n#include <qle/pricingengines/discountingriskybondengine.hpp>\n#include <qle/pricingengines/discountingswapenginemulticurve.hpp>\n#include <qle/pricingengines/midpointcdsengine.hpp>\n#include <qle/pricingengines/numericlgmswaptionengine.hpp>\n#include <qle/pricingengines/oiccbasisswapengine.hpp>\n#include <qle/pricingengines/paymentdiscountingengine.hpp>\n\n#include <ql/currencies/europe.hpp>\n#include <ql/indexes/swap/euriborswap.hpp>\n#include <ql/instruments/makeswaption.hpp>\n#include <ql/math/array.hpp>\n#include <ql/math/comparison.hpp>\n#include <ql/models/shortrate/onefactormodels/gsr.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <ql/pricingengines/swaption/fdhullwhiteswaptionengine.hpp>\n#include <ql/pricingengines/swaption/gaussian1dswaptionengine.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/time/calendars/target.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\n\nnamespace {\nstruct F : public qle::test::TopLevelFixture {\n    F() { Settings::instance().evaluationDate() = Date(20, March, 2019); }\n    ~F() {}\n};\n} // namespace\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_FIXTURE_TEST_SUITE(AnalyticLgmSwaptionEngineTest, F)\n\nBOOST_AUTO_TEST_CASE(testMonoCurve) {\n\n    BOOST_TEST_MESSAGE(\"Testing analytic LGM swaption engine coupon \"\n                       \"adjustments in mono curve setup...\");\n\n    Handle<YieldTermStructure> flatCurve(boost::make_shared<FlatForward>(0, NullCalendar(), 0.02, Actual365Fixed()));\n\n    const boost::shared_ptr<IrLgm1fConstantParametrization> irlgm1f =\n        boost::make_shared<IrLgm1fConstantParametrization>(EURCurrency(), flatCurve, 0.01, 0.01);\n\n    // no curve attached\n    boost::shared_ptr<SwapIndex> index_nocurves = boost::make_shared<EuriborSwapIsdaFixA>(10 * Years);\n\n    // forward curve attached\n    boost::shared_ptr<SwapIndex> index_monocurve = boost::make_shared<EuriborSwapIsdaFixA>(10 * Years, flatCurve);\n\n    Swaption swaption_nocurves = MakeSwaption(index_nocurves, 10 * Years, 0.02);\n    Swaption swaption_monocurve = MakeSwaption(index_monocurve, 10 * Years, 0.02);\n\n    boost::shared_ptr<PricingEngine> engine_nodisc = boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1f);\n    boost::shared_ptr<PricingEngine> engine_monocurve =\n        boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1f, flatCurve);\n\n    swaption_nocurves.setPricingEngine(engine_nodisc);\n    swaption_nocurves.NPV();\n    std::vector<Real> fixedAmountCorrections1 = swaption_nocurves.result<std::vector<Real> >(\"fixedAmountCorrections\");\n    Real fixedAmountCorrectionSettlement1 = swaption_nocurves.result<Real>(\"fixedAmountCorrectionSettlement\");\n    swaption_nocurves.setPricingEngine(engine_monocurve);\n    swaption_nocurves.NPV();\n    std::vector<Real> fixedAmountCorrections2 = swaption_nocurves.result<std::vector<Real> >(\"fixedAmountCorrections\");\n    Real fixedAmountCorrectionSettlement2 = swaption_nocurves.result<Real>(\"fixedAmountCorrectionSettlement\");\n    swaption_monocurve.setPricingEngine(engine_nodisc);\n    swaption_monocurve.NPV();\n    std::vector<Real> fixedAmountCorrections3 = swaption_nocurves.result<std::vector<Real> >(\"fixedAmountCorrections\");\n    Real fixedAmountCorrectionSettlement3 = swaption_nocurves.result<Real>(\"fixedAmountCorrectionSettlement\");\n    swaption_monocurve.setPricingEngine(engine_monocurve);\n    swaption_monocurve.NPV();\n    std::vector<Real> fixedAmountCorrections4 = swaption_nocurves.result<std::vector<Real> >(\"fixedAmountCorrections\");\n    Real fixedAmountCorrectionSettlement4 = swaption_nocurves.result<Real>(\"fixedAmountCorrectionSettlement\");\n\n    if (fixedAmountCorrections1.size() != 10) {\n        BOOST_ERROR(\"fixed coupon adjustment vector 1 should have size 10, \"\n                    \"but actually has size \"\n                    << fixedAmountCorrections1.size());\n    }\n    if (fixedAmountCorrections2.size() != 10) {\n        BOOST_ERROR(\"fixed coupon adjustment vector 2 should have size 10, \"\n                    \"but actually has size \"\n                    << fixedAmountCorrections2.size());\n    }\n    if (fixedAmountCorrections3.size() != 10) {\n        BOOST_ERROR(\"fixed coupon adjustment vector 3 should have size 10, \"\n                    \"but actually has size \"\n                    << fixedAmountCorrections3.size());\n    }\n    if (fixedAmountCorrections4.size() != 10) {\n        BOOST_ERROR(\"fixed coupon adjustment vector 4 should have size 10, \"\n                    \"but actually has size \"\n                    << fixedAmountCorrections4.size());\n    }\n\n    for (Size i = 0; i < 10; ++i) {\n        if (!close_enough(fixedAmountCorrections1[i], 0.0)) {\n            BOOST_ERROR(\"fixed coupon adjustment (1) should be zero in mono \"\n                        \"curve setup, but component \"\n                        << i << \" is \" << fixedAmountCorrections1[i]);\n        }\n        if (!close_enough(fixedAmountCorrections2[i], 0.0)) {\n            BOOST_ERROR(\"fixed coupon adjustment (2) should be zero in mono \"\n                        \"curve setup, but component \"\n                        << i << \" is \" << fixedAmountCorrections2[i]);\n        }\n        if (!close_enough(fixedAmountCorrections3[i], 0.0)) {\n            BOOST_ERROR(\"fixed coupon adjustment (3) should be zero in mono \"\n                        \"curve setup, but component \"\n                        << i << \" is \" << fixedAmountCorrections3[i]);\n        }\n        if (!close_enough(fixedAmountCorrections4[i], 0.0)) {\n            BOOST_ERROR(\"fixed coupon adjustment (4) should be zero in mono \"\n                        \"curve setup, but component \"\n                        << i << \" is \" << fixedAmountCorrections4[i]);\n        }\n    }\n\n    if (!close_enough(fixedAmountCorrectionSettlement1, 0.0)) {\n        BOOST_ERROR(\"fixed amount correction on settlement (1) should be \"\n                    \"zero in mono curve setup, but is \"\n                    << fixedAmountCorrectionSettlement1);\n    }\n    if (!close_enough(fixedAmountCorrectionSettlement2, 0.0)) {\n        BOOST_ERROR(\"fixed amount correction on settlement (2) should be \"\n                    \"zero in mono curve setup, but is \"\n                    << fixedAmountCorrectionSettlement2);\n    }\n    if (!close_enough(fixedAmountCorrectionSettlement3, 0.0)) {\n        BOOST_ERROR(\"fixed amount correction on settlement (3) should be \"\n                    \"zero in mono curve setup, but is \"\n                    << fixedAmountCorrectionSettlement3);\n    }\n    if (!close_enough(fixedAmountCorrectionSettlement4, 0.0)) {\n        BOOST_ERROR(\"fixed amount correction on settlement (4) should be \"\n                    \"zero in mono curve setup, but is \"\n                    << fixedAmountCorrectionSettlement4);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(testDualCurve) {\n\n    BOOST_TEST_MESSAGE(\"Testing analytic LGM swaption engine coupon \"\n                       \"adjustments in dual curve setup...\");\n\n    // discounting curve\n    Handle<YieldTermStructure> discCurve(boost::make_shared<FlatForward>(0, NullCalendar(), 0.02, Actual365Fixed()));\n    // forward (+10bp)\n    Handle<YieldTermStructure> forwardCurve1(\n        boost::make_shared<FlatForward>(0, NullCalendar(), 0.0210, Actual365Fixed()));\n    // forward (-10bp)\n    Handle<YieldTermStructure> forwardCurve2(\n        boost::make_shared<FlatForward>(0, NullCalendar(), 0.0190, Actual365Fixed()));\n\n    const boost::shared_ptr<IrLgm1fConstantParametrization> irlgm1f =\n        boost::make_shared<IrLgm1fConstantParametrization>(EURCurrency(), discCurve, 0.01, 0.01);\n\n    // forward curve attached\n    boost::shared_ptr<SwapIndex> index1 = boost::make_shared<EuriborSwapIsdaFixA>(10 * Years, forwardCurve1);\n    boost::shared_ptr<SwapIndex> index2 = boost::make_shared<EuriborSwapIsdaFixA>(10 * Years, forwardCurve2);\n\n    Swaption swaption1 = MakeSwaption(index1, 10 * Years, 0.02);\n    Swaption swaption2 = MakeSwaption(index2, 10 * Years, 0.02);\n\n    boost::shared_ptr<PricingEngine> engine_a =\n        boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1f, discCurve, AnalyticLgmSwaptionEngine::nextCoupon);\n\n    boost::shared_ptr<PricingEngine> engine_b =\n        boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1f, discCurve, AnalyticLgmSwaptionEngine::proRata);\n\n    swaption1.setPricingEngine(engine_a);\n    swaption1.NPV();\n    std::vector<Real> fixedAmountCorrections1a = swaption1.result<std::vector<Real> >(\"fixedAmountCorrections\");\n    Real fixedAmountCorrectionSettlement1a = swaption1.result<Real>(\"fixedAmountCorrectionSettlement\");\n    swaption2.setPricingEngine(engine_a);\n    swaption2.NPV();\n    std::vector<Real> fixedAmountCorrections2a = swaption2.result<std::vector<Real> >(\"fixedAmountCorrections\");\n    Real fixedAmountCorrectionSettlement2a = swaption2.result<Real>(\"fixedAmountCorrectionSettlement\");\n    swaption1.setPricingEngine(engine_b);\n    swaption1.NPV();\n    std::vector<Real> fixedAmountCorrections1b = swaption1.result<std::vector<Real> >(\"fixedAmountCorrections\");\n    Real fixedAmountCorrectionSettlement1b = swaption1.result<Real>(\"fixedAmountCorrectionSettlement\");\n    swaption2.setPricingEngine(engine_b);\n    swaption2.NPV();\n    std::vector<Real> fixedAmountCorrections2b = swaption2.result<std::vector<Real> >(\"fixedAmountCorrections\");\n    Real fixedAmountCorrectionSettlement2b = swaption2.result<Real>(\"fixedAmountCorrectionSettlement\");\n\n    // check corrections on settlement for plausibility\n\n    Real tolerance = 0.000025; // 0.25 bp\n\n    if (!close_enough(fixedAmountCorrectionSettlement1a, 0.0)) {\n        BOOST_ERROR(\"fixed amount correction on settlement (1) should be \"\n                    \"0 for nextCoupon, but is \"\n                    << fixedAmountCorrectionSettlement1a);\n    }\n    if (!close_enough(fixedAmountCorrectionSettlement2a, 0.0)) {\n        BOOST_ERROR(\"fixed amount correction on settlement (2) should be \"\n                    \"0 for nextCoupon, but is \"\n                    << fixedAmountCorrectionSettlement2a);\n    }\n    if (std::abs(fixedAmountCorrectionSettlement1b - 0.00025) > tolerance) {\n        BOOST_ERROR(\"fixed amount correction on settlement (1) should be \"\n                    \"close to 2.5bp for proRata, but is \"\n                    << fixedAmountCorrectionSettlement1b);\n    }\n    if (std::abs(fixedAmountCorrectionSettlement2b + 0.00025) > tolerance) {\n        BOOST_ERROR(\"fixed amount correction on settlement (2) should be \"\n                    \"close to -2.5bp for proRata, but is \"\n                    << fixedAmountCorrectionSettlement2b);\n    }\n\n    // we can assume that the result vectors have the correct size, this\n    // was tested above\n\n    for (Size i = 0; i < 10; ++i) {\n        // amount correction should be close to +10bp (-10bp)\n        // up to conventions, check this for plausibility\n        if (std::abs(fixedAmountCorrections1a[i] - 0.0010) > tolerance) {\n            BOOST_ERROR(\"fixed coupon adjustment (1, nextCoupon) should \"\n                        \"be close to 10bp for \"\n                        \"a 10bp curve spread, but is \"\n                        << fixedAmountCorrections1a[i] << \" for component \" << i);\n        }\n        if (std::abs(fixedAmountCorrections2a[i] + 0.0010) > tolerance) {\n            BOOST_ERROR(\"fixed coupon adjustment (2, nextCoupon) should \"\n                        \"be close to -10bp for \"\n                        \"a -10bp curve spread, but is \"\n                        << fixedAmountCorrections2a[i] << \" for component \" << i);\n        }\n        if (std::abs(fixedAmountCorrections1b[i] - (i == 9 ? 0.00075 : 0.0010)) > tolerance) {\n            BOOST_ERROR(\"fixed coupon adjustment (1, proRata) should \"\n                        \"be close to 10bp (7.5bp for component 9) for \"\n                        \"a 10bp curve spread, but is \"\n                        << fixedAmountCorrections1b[i] << \" for component \" << i);\n        }\n        if (std::abs(fixedAmountCorrections2b[i] + (i == 9 ? 0.00075 : 0.0010)) > tolerance) {\n            BOOST_ERROR(\"fixed coupon adjustment (2, proRata) should \"\n                        \"be close to -10bp (-7.5bp for component 9) for \"\n                        \"a -10bp curve spread, but is \"\n                        << fixedAmountCorrections2b[i] << \" for component \" << i);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(testAgainstOtherEngines) {\n\n    BOOST_TEST_MESSAGE(\"Testing analytic LGM swaption engine against \"\n                       \"G1d adaptor / Gsr integral and Hull White fd engines...\");\n\n    Real discountingRateLevel[] = { -0.0050, 0.01, 0.03, 0.10 };\n    Real forwardingRateLevel[] = { -0.0100, 0.01, 0.04, 0.12 };\n\n    // Hull White only allows for positive reversion levels\n    Real kappa[] = { 0.01, 0.00001, 0.01, 0.05 };\n\n    // the model volatilities are meant to be Hull White volatilities\n    // they are fed into the LGM model via the HW adaptor below\n    // the rationale is to have another independent model\n    // (QuantLib::HullWhite) and pricing engine\n    // (QUantLib::FdHullWhiteSwaptionEngine) available for validation\n\n    Real sigma[] = { 0.0001, 0.01, 0.02 };\n\n    Real strikeOffset[] = { -0.05, -0.02, -0.01, 0.0, 0.01, 0.02, 0.05 };\n\n    Size no = 0;\n\n    // tolerance for comparision fd engine vs integral engines\n    Real tol1 = 3.0E-4;\n\n    // tolerance for comparision of integral engines based\n    // on GSR and LGM model\n    Real tol2 = 1.0E-4;\n\n    // tolerance for LGM integral engine and analytical engine\n    // in the case of no basis between discounting and forwarding\n    Real tol3 = 0.6E-4;\n\n    // tolerance for LGM integral engine and analytical engine\n    // in the case of a non zero basis between discounting and\n    // forwarding curve (mapping type a and b)\n    // this scales with sigma, the tolerances here are\n    // for sigma = 0.01\n    Real tol4a = 6.0E-4, tol4b = 4.0E-4;\n\n    for (Size i = 0; i < LENGTH(discountingRateLevel); ++i) {\n        for (Size k = 0; k < LENGTH(kappa); ++k) {\n            for (Size l = 0; l < LENGTH(sigma); ++l) {\n\n                Handle<YieldTermStructure> discountingCurve(\n                    boost::make_shared<FlatForward>(0, NullCalendar(), discountingRateLevel[i], Actual365Fixed()));\n                Handle<YieldTermStructure> forwardingCurve(\n                    boost::make_shared<FlatForward>(0, NullCalendar(), forwardingRateLevel[i], Actual365Fixed()));\n\n                Array times(0);\n                Array sigma_a(1, sigma[l]);\n                Array kappa_a(1, kappa[k]);\n                std::vector<Date> dates(0);\n                std::vector<Real> sigma_v(1, sigma[l]);\n                std::vector<Real> kappa_v(1, kappa[k]);\n\n                const boost::shared_ptr<IrLgm1fPiecewiseConstantHullWhiteAdaptor> irlgm1f =\n                    boost::make_shared<IrLgm1fPiecewiseConstantHullWhiteAdaptor>(EURCurrency(), discountingCurve, times,\n                                                                                 sigma_a, times, kappa_a);\n\n                std::vector<boost::shared_ptr<Parametrization> > params;\n                params.push_back(irlgm1f);\n                Matrix rho(1, 1);\n                rho[0][0] = 1.0;\n                const boost::shared_ptr<CrossAssetModel> crossasset = boost::make_shared<CrossAssetModel>(params, rho);\n\n                const boost::shared_ptr<Gaussian1dModel> g1d =\n                    boost::make_shared<Gaussian1dCrossAssetAdaptor>(0, crossasset);\n\n                const boost::shared_ptr<Gsr> gsr = boost::make_shared<Gsr>(discountingCurve, dates, sigma_v, kappa_v);\n\n                const boost::shared_ptr<HullWhite> hw =\n                    boost::make_shared<HullWhite>(discountingCurve, kappa[k], sigma[l]);\n\n                boost::shared_ptr<PricingEngine> engine_map_a = boost::make_shared<AnalyticLgmSwaptionEngine>(\n                    irlgm1f, discountingCurve, AnalyticLgmSwaptionEngine::nextCoupon);\n                boost::shared_ptr<PricingEngine> engine_map_b = boost::make_shared<AnalyticLgmSwaptionEngine>(\n                    irlgm1f, discountingCurve, AnalyticLgmSwaptionEngine::proRata);\n\n                boost::shared_ptr<PricingEngine> engine_g1d =\n                    boost::make_shared<Gaussian1dSwaptionEngine>(g1d, 128, 7.0, true, false, discountingCurve);\n\n                boost::shared_ptr<PricingEngine> engine_gsr =\n                    boost::make_shared<Gaussian1dSwaptionEngine>(gsr, 128, 7.0, true, false, discountingCurve);\n\n                boost::shared_ptr<PricingEngine> engine_fd =\n                    boost::make_shared<FdHullWhiteSwaptionEngine>(hw, 400, 400, 0, 1.0E-8);\n\n                boost::shared_ptr<SwapIndex> index =\n                    boost::make_shared<EuriborSwapIsdaFixA>(10 * Years, forwardingCurve, discountingCurve);\n                Real atmStrike = index->fixing(TARGET().advance(Settings::instance().evaluationDate(), 5 * Years));\n\n                for (Size s = 0; s < LENGTH(strikeOffset); ++s) {\n\n                    // we have to ensure positive effective fixed flows for\n                    // the analytic engine (this is checked there, but we\n                    // want to avoid exceptions thrown during testing)\n                    if (atmStrike + strikeOffset[s] - (forwardingRateLevel[i] - discountingRateLevel[i]) < 0.0001) {\n                        continue;\n                    }\n\n                    Swaption swaption =\n                        MakeSwaption(index, 5 * Years, atmStrike + strikeOffset[s])\n                            .withUnderlyingType(strikeOffset[s] > 0.0 ? VanillaSwap::Payer : VanillaSwap::Receiver);\n\n                    swaption.setPricingEngine(engine_map_a);\n                    Real npv_map_a = swaption.NPV();\n                    swaption.setPricingEngine(engine_map_b);\n                    Real npv_map_b = swaption.NPV();\n                    swaption.setPricingEngine(engine_g1d);\n                    Real npv_g1d = swaption.NPV();\n                    swaption.setPricingEngine(engine_gsr);\n                    Real npv_gsr = swaption.NPV();\n                    swaption.setPricingEngine(engine_fd);\n                    Real npv_fd = swaption.NPV();\n\n                    if (std::abs(npv_fd - npv_gsr) > tol1) {\n                        BOOST_ERROR(\"inconsistent swaption npvs (fd=\"\n                                    << npv_fd << \", gsr=\" << npv_gsr << \") for case #\" << no\n                                    << \" with discounting rate=\" << discountingRateLevel[i]\n                                    << \", forwarding rate=\" << forwardingRateLevel[i] << \", kappa=\" << kappa[k]\n                                    << \", sigma=\" << sigma[l] << \", strike offset=\" << strikeOffset[s]);\n                    }\n\n                    if (std::abs(npv_gsr - npv_g1d) > tol2) {\n                        BOOST_ERROR(\"inconsistent swaption npvs (gsr=\"\n                                    << npv_gsr << \", npv_g1d=\" << npv_g1d << \") for case #\" << no\n                                    << \" with discounting rate=\" << discountingRateLevel[i]\n                                    << \", forwarding rate=\" << forwardingRateLevel[i] << \", kappa=\" << kappa[k]\n                                    << \", sigma=\" << sigma[l] << \", strike offset=\" << strikeOffset[s]);\n                    }\n\n                    Real tolTmpA = 0.0, tolTmpB = 0.0;\n                    if (std::abs(discountingRateLevel[i] - forwardingRateLevel[i]) < 1.0E-6) {\n                        tolTmpA = tolTmpB = tol3;\n                    } else {\n                        tolTmpA = tol4a * std::max(sigma[l], 0.01) / 0.01; // see above\n                        tolTmpB = tol4b * std::max(sigma[l], 0.01) / 0.01; // see above\n                    }\n\n                    if (std::abs(npv_g1d - npv_map_a) > tolTmpA) {\n                        BOOST_ERROR(\"inconsistent swaption npvs (g1d=\"\n                                    << npv_g1d << \", map_a=\" << npv_map_a << \"), tolerance is \" << tolTmpA\n                                    << \", for case #\" << no << \" with discounting rate=\" << discountingRateLevel[i]\n                                    << \", forwarding rate=\" << forwardingRateLevel[i] << \", kappa=\" << kappa[k]\n                                    << \", sigma=\" << sigma[l] << \", strike offset=\" << strikeOffset[s]);\n                    }\n\n                    if (std::abs(npv_g1d - npv_map_b) > tolTmpB) {\n                        BOOST_ERROR(\"inconsistent swaption npvs (g1d=\"\n                                    << npv_g1d << \", map_b=\" << npv_map_b << \"), tolerance is \" << tolTmpB\n                                    << \", for case #\" << no << \" with discounting rate=\" << discountingRateLevel[i]\n                                    << \", forwarding rate=\" << forwardingRateLevel[i] << \", kappa=\" << kappa[k]\n                                    << \", sigma=\" << sigma[l] << \", strike offset=\" << strikeOffset[s]);\n                    }\n\n                    no++;\n                }\n            }\n        }\n    }\n} // testAgainstOtherEngines\n\nBOOST_AUTO_TEST_CASE(testLgmInvariances) {\n\n    BOOST_TEST_MESSAGE(\"Testing LGM model invariances in the analytic LGM \"\n                       \"swaption engine...\");\n\n    Real shift[] = { -2.0, -1.0, 0.0, 1.0, 2.0 };\n    Real scaling[] = { 5.0, 2.0, 1.0, 0.1, 0.01, -0.01, -0.1, -1.0, -2.0, -5.0 };\n\n    Handle<YieldTermStructure> discountingCurve(\n        boost::make_shared<FlatForward>(0, NullCalendar(), 0.03, Actual365Fixed()));\n    Handle<YieldTermStructure> forwardingCurve(\n        boost::make_shared<FlatForward>(0, NullCalendar(), 0.05, Actual365Fixed()));\n\n    Array times(0);\n    Array sigma_a(1, 0.01);\n    Array alpha_a(1, 0.01);\n    Array kappa_a(1, 0.01);\n\n    boost::shared_ptr<SwapIndex> index =\n        boost::make_shared<EuriborSwapIsdaFixA>(10 * Years, forwardingCurve, discountingCurve);\n    Swaption swaption = MakeSwaption(index, 5 * Years, 0.07); // otm\n\n    for (Size i = 0; i < LENGTH(shift); ++i) {\n        for (Size j = 0; j < LENGTH(scaling); ++j) {\n\n            const boost::shared_ptr<IrLgm1fParametrization> irlgm1f0 =\n                boost::make_shared<IrLgm1fConstantParametrization>(EURCurrency(), discountingCurve, 0.01, 0.01);\n\n            const boost::shared_ptr<IrLgm1fParametrization> irlgm1fa =\n                boost::make_shared<IrLgm1fConstantParametrization>(EURCurrency(), discountingCurve, 0.01, 0.01);\n            irlgm1fa->shift() = shift[i];\n            irlgm1fa->scaling() = scaling[j];\n\n            const boost::shared_ptr<IrLgm1fParametrization> irlgm1fb =\n                boost::make_shared<IrLgm1fPiecewiseConstantParametrization>(EURCurrency(), discountingCurve, times,\n                                                                            alpha_a, times, kappa_a);\n            irlgm1fb->shift() = shift[i];\n            irlgm1fb->scaling() = scaling[j];\n\n            const boost::shared_ptr<IrLgm1fParametrization> irlgm1f0c =\n                boost::make_shared<IrLgm1fPiecewiseConstantHullWhiteAdaptor>(EURCurrency(), discountingCurve, times,\n                                                                             sigma_a, times, kappa_a);\n\n            const boost::shared_ptr<IrLgm1fParametrization> irlgm1fc =\n                boost::make_shared<IrLgm1fPiecewiseConstantHullWhiteAdaptor>(EURCurrency(), discountingCurve, times,\n                                                                             sigma_a, times, kappa_a);\n            irlgm1fc->shift() = shift[i];\n            irlgm1fc->scaling() = scaling[j];\n\n            const boost::shared_ptr<LinearGaussMarkovModel> lgm0 = boost::make_shared<LinearGaussMarkovModel>(irlgm1f0);\n            const boost::shared_ptr<LinearGaussMarkovModel> lgma = boost::make_shared<LinearGaussMarkovModel>(irlgm1fa);\n            const boost::shared_ptr<LinearGaussMarkovModel> lgmb = boost::make_shared<LinearGaussMarkovModel>(irlgm1fb);\n            const boost::shared_ptr<LinearGaussMarkovModel> lgm0c =\n                boost::make_shared<LinearGaussMarkovModel>(irlgm1f0c);\n            const boost::shared_ptr<LinearGaussMarkovModel> lgmc = boost::make_shared<LinearGaussMarkovModel>(irlgm1fc);\n\n            boost::shared_ptr<PricingEngine> engine0 = boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1f0);\n            boost::shared_ptr<PricingEngine> enginea = boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1fa);\n            boost::shared_ptr<PricingEngine> engineb = boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1fb);\n            boost::shared_ptr<PricingEngine> engine0c = boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1f0c);\n            boost::shared_ptr<PricingEngine> enginec = boost::make_shared<AnalyticLgmSwaptionEngine>(irlgm1fc);\n\n            swaption.setPricingEngine(engine0);\n            Real npv0 = swaption.NPV();\n            swaption.setPricingEngine(enginea);\n            Real npva = swaption.NPV();\n            swaption.setPricingEngine(engineb);\n            Real npvb = swaption.NPV();\n            swaption.setPricingEngine(engine0c);\n            Real npv0c = swaption.NPV();\n            swaption.setPricingEngine(enginec);\n            Real npvc = swaption.NPV();\n\n            Real tol = 1.0E-10;\n            if (std::fabs(npva - npv0) > tol) {\n                BOOST_ERROR(\"price is not invariant under (shift,scaling)=(\" << shift[i] << \",\" << scaling[i]\n                                                                             << \"), difference is \" << (npva - npv0)\n                                                                             << \" (constant parametrization)\");\n            }\n            if (std::fabs(npvb - npv0) > tol) {\n                BOOST_ERROR(\"price is not invariant under (shift,scaling)=(\"\n                            << shift[i] << \",\" << scaling[i] << \"), difference is \" << (npvb - npv0)\n                            << \" (piecewise constant parametrization)\");\n            }\n            if (std::fabs(npvc - npv0c) > tol) {\n                BOOST_ERROR(\"price is not invariant under (shift,scaling)=(\"\n                            << shift[i] << \",\" << scaling[i] << \"), difference is \" << (npvc - npv0c)\n                            << \" (hull white adaptor parametrization)\");\n            }\n        }\n    }\n} // testInvariances\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e75263f860722999b9b4add209209e80d6666352", "size": 29521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/analyticlgmswaptionengine.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/test/analyticlgmswaptionengine.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/test/analyticlgmswaptionengine.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": 51.4303135889, "max_line_length": 120, "alphanum_fraction": 0.6287388639, "num_tokens": 7427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.1638342786246249}}
{"text": "// Copyright (c) 2014-2015 The ShadowCoin 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/*\nNotes:\n    Running with -debug could leave to and from address hashes and public keys in the log.\n\n\n    parameters:\n        -nosmsg             Disable secure messaging (fNoSmsg)\n        -debugsmsg          Show extra debug messages (fDebugSmsg)\n        -smsgscanchain      Scan the block chain for public key addresses on startup\n\n\n    Wallet Locked\n        A copy of each incoming message is stored in bucket files ending in _wl.dat\n        wl (wallet locked) bucket files are deleted if they expire, like normal buckets\n        When the wallet is unlocked all the messages in wl files are scanned.\n\n\n    Address Whitelist\n        Owned Addresses are stored in smsgAddresses vector\n        Saved to smsg.ini\n        Modify options using the smsglocalkeys rpc command or edit the smsg.ini file (with client closed)\n\n\n    TODO:\n        For buckets older than current, only need to store no. messages and hash in memory\n\n*/\n\n#include \"smessage.h\"\n\n#include <stdint.h>\n#include <time.h>\n#include <map>\n#include <stdexcept>\n#include <sstream>\n#include <errno.h>\n\n#include <openssl/crypto.h>\n#include <openssl/ec.h>\n#include <openssl/ecdh.h>\n#include <openssl/sha.h>\n#include <openssl/aes.h>\n#include <openssl/evp.h>\n#include <openssl/hmac.h>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/algorithm/string/replace.hpp>\n\n#include \"base58.h\"\n#include \"db.h\"\n#include \"init.h\" // pwalletMain\n#include \"txdb.h\"\n#include \"sync.h\"\n#include \"eckey.h\"\n\n#include \"lz4/lz4.c\"\n\n#include \"xxhash/xxhash.h\"\n#include \"xxhash/xxhash.c\"\n\n\nboost::thread_group threadGroupSmsg;\n\nboost::signals2::signal<void (SecMsgStored& inboxHdr)>  NotifySecMsgInboxChanged;\nboost::signals2::signal<void (SecMsgStored& outboxHdr)> NotifySecMsgOutboxChanged;\nboost::signals2::signal<void ()> NotifySecMsgWalletUnlocked;\n\nbool fSecMsgEnabled = false;\n\nstd::map<int64_t, SecMsgBucket> smsgBuckets;\nstd::vector<SecMsgAddress>      smsgAddresses;\nSecMsgOptions                   smsgOptions;\n\n\nCCriticalSection cs_smsg;\nCCriticalSection cs_smsgDB;\nCCriticalSection cs_smsgThreads;\n\nleveldb::DB *smsgDB = NULL;\n\n\nnamespace fs = boost::filesystem;\n\nbool SecMsgCrypter::SetKey(const std::vector<uint8_t>& vchNewKey, uint8_t* chNewIV)\n{\n    if (vchNewKey.size() < sizeof(chKey))\n        return false;\n\n    return SetKey(&vchNewKey[0], chNewIV);\n};\n\nbool SecMsgCrypter::SetKey(const uint8_t* chNewKey, uint8_t* chNewIV)\n{\n    // -- for EVP_aes_256_cbc() key must be 256 bit, iv must be 128 bit.\n    memcpy(&chKey[0], chNewKey, sizeof(chKey));\n    memcpy(chIV, chNewIV, sizeof(chIV));\n\n    fKeySet = true;\n    return true;\n};\n\nbool SecMsgCrypter::Encrypt(uint8_t* chPlaintext, uint32_t nPlain, std::vector<uint8_t> &vchCiphertext)\n{\n    if (!fKeySet)\n        return false;\n\n    // -- max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE - 1 bytes\n    int nLen = nPlain;\n\n    int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;\n    vchCiphertext = std::vector<uint8_t> (nCLen);\n\n    EVP_CIPHER_CTX ctx;\n\n    bool fOk = true;\n\n    EVP_CIPHER_CTX_init(&ctx);\n    if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, &chKey[0], &chIV[0]);\n    if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, chPlaintext, nLen);\n    if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);\n    EVP_CIPHER_CTX_cleanup(&ctx);\n\n    if (!fOk)\n        return false;\n\n    vchCiphertext.resize(nCLen + nFLen);\n\n    return true;\n};\n\nbool SecMsgCrypter::Decrypt(uint8_t* chCiphertext, uint32_t nCipher, std::vector<uint8_t>& vchPlaintext)\n{\n    if (!fKeySet)\n        return false;\n\n    // plaintext will always be equal to or lesser than length of ciphertext\n    int nPLen = nCipher, nFLen = 0;\n\n    vchPlaintext.resize(nCipher);\n\n    EVP_CIPHER_CTX ctx;\n\n    bool fOk = true;\n\n    EVP_CIPHER_CTX_init(&ctx);\n    if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, &chKey[0], &chIV[0]);\n    if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &chCiphertext[0], nCipher);\n    if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);\n    EVP_CIPHER_CTX_cleanup(&ctx);\n\n    if (!fOk)\n        return false;\n\n    vchPlaintext.resize(nPLen + nFLen);\n\n    return true;\n};\n\nvoid SecMsgBucket::hashBucket()\n{\n    if (fDebugSmsg)\n        LogPrintf(\"SecMsgBucket::hashBucket()\\n\");\n\n\n    std::set<SecMsgToken>::iterator it;\n\n    void* state = XXH32_init(1);\n\n    for (it = setTokens.begin(); it != setTokens.end(); ++it)\n    {\n        XXH32_update(state, it->sample, 8);\n    };\n\n    uint32_t hash_new = XXH32_digest(state);\n\n    if(hash != hash_new)\n    {\n\n        if(fDebugSmsg)\n            LogPrintf(\"Bucket hash updated from %u to %u.\\n\", hash, hash_new);\n\n        hash = hash_new; //use memcpy here?\n\n        timeChanged = GetTime();\n    }\n\n    if (fDebugSmsg)\n        LogPrintf(\"Hashed %u messages, hash %u\\n\", setTokens.size(), hash_new);\n};\n\n\nbool SecMsgDB::Open(const char* pszMode)\n{\n    if (smsgDB)\n    {\n        pdb = smsgDB;\n        return true;\n    };\n\n    bool fCreate = strchr(pszMode, 'c');\n\n    fs::path fullpath = GetDataDir() / \"smsgDB\";\n\n    if (!fCreate\n        && (!fs::exists(fullpath)\n            || !fs::is_directory(fullpath)))\n    {\n        LogPrintf(\"SecMsgDB::open() - DB does not exist.\\n\");\n        return false;\n    };\n\n    leveldb::Options options;\n    options.create_if_missing = fCreate;\n    leveldb::Status s = leveldb::DB::Open(options, fullpath.string(), &smsgDB);\n\n    if (!s.ok())\n    {\n        LogPrintf(\"SecMsgDB::open() - Error opening db: %s.\\n\", s.ToString().c_str());\n        return false;\n    };\n\n    pdb = smsgDB;\n\n    return true;\n};\n\n\nclass SecMsgBatchScanner : public leveldb::WriteBatch::Handler\n{\npublic:\n    std::string needle;\n    bool* deleted;\n    std::string* foundValue;\n    bool foundEntry;\n\n    SecMsgBatchScanner() : foundEntry(false) {}\n\n    virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value)\n    {\n        if (key.ToString() == needle)\n        {\n            foundEntry = true;\n            *deleted = false;\n            *foundValue = value.ToString();\n        };\n    };\n\n    virtual void Delete(const leveldb::Slice& key)\n    {\n        if (key.ToString() == needle)\n        {\n            foundEntry = true;\n            *deleted = true;\n        };\n    };\n};\n\n// When performing a read, if we have an active batch we need to check it first\n// before reading from the database, as the rest of the code assumes that once\n// a database transaction begins reads are consistent with it. It would be good\n// to change that assumption in future and avoid the performance hit, though in\n// practice it does not appear to be large.\nbool SecMsgDB::ScanBatch(const CDataStream& key, std::string* value, bool* deleted) const\n{\n    if (!activeBatch)\n        return false;\n\n    *deleted = false;\n    SecMsgBatchScanner scanner;\n    scanner.needle = key.str();\n    scanner.deleted = deleted;\n    scanner.foundValue = value;\n    leveldb::Status s = activeBatch->Iterate(&scanner);\n    if (!s.ok())\n    {\n        LogPrintf(\"SecMsgDB ScanBatch error: %s\\n\", s.ToString().c_str());\n        return false;\n    };\n\n    return scanner.foundEntry;\n}\n\nbool SecMsgDB::TxnBegin()\n{\n    if (activeBatch)\n        return true;\n    activeBatch = new leveldb::WriteBatch();\n    return true;\n};\n\nbool SecMsgDB::TxnCommit()\n{\n    if (!activeBatch)\n        return false;\n\n    leveldb::WriteOptions writeOptions;\n    writeOptions.sync = true;\n    leveldb::Status status = pdb->Write(writeOptions, activeBatch);\n    delete activeBatch;\n    activeBatch = NULL;\n\n    if (!status.ok())\n    {\n        LogPrintf(\"SecMsgDB batch commit failure: %s\\n\", status.ToString().c_str());\n        return false;\n    };\n\n    return true;\n};\n\nbool SecMsgDB::TxnAbort()\n{\n    delete activeBatch;\n    activeBatch = NULL;\n    return true;\n};\n\nbool SecMsgDB::ReadPK(CKeyID& addr, CPubKey& pubkey)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.reserve(sizeof(addr) + 2);\n    ssKey << 'p';\n    ssKey << 'k';\n    ssKey << addr;\n    std::string strValue;\n\n    bool readFromDb = true;\n    if (activeBatch)\n    {\n        // -- check activeBatch first\n        bool deleted = false;\n        readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;\n        if (deleted)\n            return false;\n    };\n\n    if (readFromDb)\n    {\n        leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue);\n        if (!s.ok())\n        {\n            if (s.IsNotFound())\n                return false;\n            LogPrintf(\"LevelDB read failure: %s\\n\", s.ToString().c_str());\n            return false;\n        };\n    };\n\n    try {\n        CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);\n        ssValue >> pubkey;\n    } catch (std::exception& e) {\n        LogPrintf(\"SecMsgDB::ReadPK() unserialize threw: %s.\\n\", e.what());\n        return false;\n    }\n\n    return true;\n};\n\nbool SecMsgDB::WritePK(CKeyID& addr, CPubKey& pubkey)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.reserve(sizeof(addr) + 2);\n    ssKey << 'p';\n    ssKey << 'k';\n    ssKey << addr;\n    CDataStream ssValue(SER_DISK, CLIENT_VERSION);\n    ssValue.reserve(sizeof(pubkey));\n    ssValue << pubkey;\n\n    if (activeBatch)\n    {\n        activeBatch->Put(ssKey.str(), ssValue.str());\n        return true;\n    };\n\n    leveldb::WriteOptions writeOptions;\n    writeOptions.sync = true;\n    leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str());\n    if (!s.ok())\n    {\n        LogPrintf(\"SecMsgDB write failure: %s\\n\", s.ToString().c_str());\n        return false;\n    };\n\n    return true;\n};\n\nbool SecMsgDB::ExistsPK(CKeyID& addr)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.reserve(sizeof(addr)+2);\n    ssKey << 'p';\n    ssKey << 'k';\n    ssKey << addr;\n    std::string unused;\n\n    if (activeBatch)\n    {\n        bool deleted;\n        if (ScanBatch(ssKey, &unused, &deleted) && !deleted)\n        {\n            return true;\n        };\n    };\n\n    leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);\n    return s.IsNotFound() == false;\n};\n\n\nbool SecMsgDB::NextSmesg(leveldb::Iterator* it, std::string& prefix, uint8_t* chKey, SecMsgStored& smsgStored)\n{\n    if (!pdb)\n        return false;\n\n    if (!it->Valid()) // first run\n        it->Seek(prefix);\n    else\n        it->Next();\n\n    if (!(it->Valid()\n        && it->key().size() == 18\n        && memcmp(it->key().data(), prefix.data(), 2) == 0))\n        return false;\n\n    memcpy(chKey, it->key().data(), 18);\n\n    try {\n        CDataStream ssValue(it->value().data(), it->value().data() + it->value().size(), SER_DISK, CLIENT_VERSION);\n        ssValue >> smsgStored;\n    } catch (std::exception& e) {\n        LogPrintf(\"SecMsgDB::NextSmesg() unserialize threw: %s.\\n\", e.what());\n        return false;\n    }\n\n    return true;\n};\n\nbool SecMsgDB::NextSmesgKey(leveldb::Iterator* it, std::string& prefix, uint8_t* chKey)\n{\n    if (!pdb)\n        return false;\n\n    if (!it->Valid()) // first run\n        it->Seek(prefix);\n    else\n        it->Next();\n\n    if (!(it->Valid()\n        && it->key().size() == 18\n        && memcmp(it->key().data(), prefix.data(), 2) == 0))\n        return false;\n\n    memcpy(chKey, it->key().data(), 18);\n\n    return true;\n};\n\nbool SecMsgDB::ReadSmesg(uint8_t* chKey, SecMsgStored& smsgStored)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.write((const char*)chKey, 18);\n    std::string strValue;\n\n    bool readFromDb = true;\n    if (activeBatch)\n    {\n        // -- check activeBatch first\n        bool deleted = false;\n        readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;\n        if (deleted)\n            return false;\n    };\n\n    if (readFromDb)\n    {\n        leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue);\n        if (!s.ok())\n        {\n            if (s.IsNotFound())\n                return false;\n            LogPrintf(\"LevelDB read failure: %s\\n\", s.ToString().c_str());\n            return false;\n        };\n    };\n\n    try {\n        CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);\n        ssValue >> smsgStored;\n    } catch (std::exception& e) {\n        LogPrintf(\"SecMsgDB::ReadSmesg() unserialize threw: %s.\\n\", e.what());\n        return false;\n    }\n\n    return true;\n};\n\nbool SecMsgDB::WriteSmesg(uint8_t* chKey, SecMsgStored& smsgStored)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.write((const char*)chKey, 18);\n    CDataStream ssValue(SER_DISK, CLIENT_VERSION);\n    ssValue << smsgStored;\n\n    if (activeBatch)\n    {\n        activeBatch->Put(ssKey.str(), ssValue.str());\n        return true;\n    };\n\n    leveldb::WriteOptions writeOptions;\n    writeOptions.sync = true;\n    leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str());\n    if (!s.ok())\n    {\n        LogPrintf(\"SecMsgDB write failed: %s\\n\", s.ToString().c_str());\n        return false;\n    };\n\n    return true;\n};\n\nbool SecMsgDB::ExistsSmesg(uint8_t* chKey)\n{\n    if (!pdb)\n        return false;\n\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.write((const char*)chKey, 18);\n    std::string unused;\n\n    if (activeBatch)\n    {\n        bool deleted;\n        if (ScanBatch(ssKey, &unused, &deleted) && !deleted)\n        {\n            return true;\n        };\n    };\n\n    leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);\n    return s.IsNotFound() == false;\n    return true;\n};\n\nbool SecMsgDB::EraseSmesg(uint8_t* chKey)\n{\n    CDataStream ssKey(SER_DISK, CLIENT_VERSION);\n    ssKey.write((const char*)chKey, 18);\n\n    if (activeBatch)\n    {\n        activeBatch->Delete(ssKey.str());\n        return true;\n    };\n\n    leveldb::WriteOptions writeOptions;\n    writeOptions.sync = true;\n    leveldb::Status s = pdb->Delete(writeOptions, ssKey.str());\n\n    if (s.ok() || s.IsNotFound())\n        return true;\n    LogPrintf(\"SecMsgDB erase failed: %s\\n\", s.ToString().c_str());\n    return false;\n};\n\nvoid ThreadSecureMsg()\n{\n    // -- bucket management thread\n    SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);\n\n    uint32_t nLoop = 0;\n    std::vector<std::pair<int64_t, NodeId> > vTimedOutLocks;\n    while (fSecMsgEnabled)\n    {\n        nLoop++;\n        int64_t now = GetTime();\n\n        if (fDebugSmsg && nLoop % SMSG_THREAD_LOG_GAP == 0) // log every SMSG_THREAD_LOG_GAP instance, is useful source of timestamps\n            LogPrintf(\"SecureMsgThread %d \\n\", now);\n\n        vTimedOutLocks.resize(0);\n\n        int64_t cutoffTime = now - SMSG_RETENTION;\n        {\n            LOCK(cs_smsg);\n            for (std::map<int64_t, SecMsgBucket>::iterator it(smsgBuckets.begin()); it != smsgBuckets.end(); )\n            {\n                //if (fDebugSmsg)\n                //    LogPrintf(\"Checking bucket %d, size %u \\n\", it->first, it->second.setTokens.size());\n\n                if (it->first < cutoffTime)\n                {\n                    if (fDebugSmsg)\n                        LogPrintf(\"Removing bucket %d \\n\", it->first);\n\n                    std::string fileName = boost::lexical_cast<std::string>(it->first);\n\n                    fs::path fullPath = GetDataDir() / \"smsgStore\" / (fileName + \"_01.dat\");\n                    if (fs::exists(fullPath))\n                    {\n                        try { fs::remove(fullPath);\n                        } catch (const fs::filesystem_error& ex)\n                        {\n                            LogPrintf(\"Error removing bucket file %s.\\n\", ex.what());\n                        };\n                    } else\n                    {\n                        LogPrintf(\"Path %s does not exist \\n\", fullPath.string().c_str());\n                    };\n\n                    // -- look for a wl file, it stores incoming messages when wallet is locked\n                    fullPath = GetDataDir() / \"smsgStore\" / (fileName + \"_01_wl.dat\");\n                    if (fs::exists(fullPath))\n                    {\n                        try { fs::remove(fullPath);\n                        } catch (const fs::filesystem_error& ex)\n                        {\n                            LogPrintf(\"Error removing wallet locked file %s.\\n\", ex.what());\n                        };\n                    };\n\n                    smsgBuckets.erase(it++);\n                } else\n                {\n                    if (it->second.nLockCount > 0) // -- tick down nLockCount, so will eventually expire if peer never sends data\n                    {\n                        it->second.nLockCount--;\n\n                        if (it->second.nLockCount == 0)     // lock timed out\n                        {\n                            vTimedOutLocks.push_back(std::make_pair(it->first, it->second.nLockPeerId)); // cs_vNodes\n\n                            it->second.nLockPeerId = 0;\n                        }; // if (it->second.nLockCount == 0)\n                    }; // ! if (it->first < cutoffTime)\n                    ++it;\n                }\n            };\n        } // cs_smsg\n\n        for (std::vector<std::pair<int64_t, NodeId> >::iterator it(vTimedOutLocks.begin()); it != vTimedOutLocks.end(); it++)\n        {\n            NodeId nPeerId = it->second;\n            uint32_t fExists = 0;\n\n            if (fDebugSmsg)\n                LogPrintf(\"Lock on bucket %d for peer %d timed out.\\n\", it->first, nPeerId);\n\n            // -- look through the nodes for the peer that locked this bucket\n\n            {\n                LOCK(cs_vNodes);\n                BOOST_FOREACH(CNode* pnode, vNodes)\n                {\n                    if (pnode->id != nPeerId)\n                        continue;\n\n                    fExists = 1; //found in vNodes\n\n                    LOCK(pnode->smsgData.cs_smsg_net);\n                    int64_t ignoreUntil = GetTime() + SMSG_TIME_IGNORE;\n                    pnode->smsgData.ignoreUntil = ignoreUntil;\n\n                    // -- alert peer that they are being ignored\n                    std::vector<uint8_t> vchData;\n                    vchData.resize(8);\n                    memcpy(&vchData[0], &ignoreUntil, 8);\n                    pnode->PushMessage(\"smsgIgnore\", vchData);\n\n                    if (fDebugSmsg)\n                        LogPrintf(\"This node will ignore peer %d until %d.\\n\", nPeerId, ignoreUntil);\n                    break;\n                };\n            } // cs_vNodes\n\n            if(fDebugSmsg)\n                LogPrintf(\"shadow-smsg thread: ignoring - looked peer %d, status on search %u\\n\", nPeerId, fExists);\n        };\n\n        MilliSleep(SMSG_THREAD_DELAY * 1000); //  // check every SMSG_THREAD_DELAY seconds\n    };\n};\n\nvoid ThreadSecureMsgPow()\n{\n    // -- proof of work thread\n\n    int rv;\n    std::vector<uint8_t> vchKey;\n    SecMsgStored smsgStored;\n\n    std::string sPrefix(\"qm\");\n    uint8_t chKey[18];\n\n\n    while (fSecMsgEnabled)\n    {\n        // -- sleep at end, then fSecMsgEnabled is tested on wake\n\n        SecMsgDB dbOutbox;\n        leveldb::Iterator* it;\n        {\n            LOCK(cs_smsgDB);\n\n            if (!dbOutbox.Open(\"cr+\"))\n                continue;\n\n            // -- fifo (smallest key first)\n            it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions());\n        }\n        // -- break up lock, SecureMsgSetHash will take long\n\n        for (;;)\n        {\n            {\n                LOCK(cs_smsgDB);\n                if (!dbOutbox.NextSmesg(it, sPrefix, chKey, smsgStored))\n                    break;\n            }\n\n            uint8_t* pHeader = &smsgStored.vchMessage[0];\n            uint8_t* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];\n            SecureMessage* psmsg = (SecureMessage*) pHeader;\n\n            // -- do proof of work\n            rv = SecureMsgSetHash(pHeader, pPayload, psmsg->nPayload);\n            if (rv == 2)\n                break; // leave message in db, if terminated due to shutdown\n\n            // -- message is removed here, no matter what\n            {\n                LOCK(cs_smsgDB);\n                dbOutbox.EraseSmesg(chKey);\n            }\n            if (rv != 0)\n            {\n                LogPrintf(\"SecMsgPow: Could not get proof of work hash, message removed.\\n\");\n                continue;\n            };\n\n            // -- add to message store\n            {\n                LOCK(cs_smsg);\n                if (SecureMsgStore(pHeader, pPayload, psmsg->nPayload, true) != 0)\n                {\n                    LogPrintf(\"SecMsgPow: Could not place message in buckets, message removed.\\n\");\n                    continue;\n                };\n            }\n\n            // -- test if message was sent to self\n            if (SecureMsgScanMessage(pHeader, pPayload, psmsg->nPayload, true) != 0)\n            {\n                // message recipient is not this node (or failed)\n            };\n        };\n\n        delete it;\n\n        // -- shutdown thread waits 5 seconds, this should be less\n        MilliSleep(2000); // seconds\n    };\n};\n\nint SecureMsgBuildBucketSet()\n{\n    /*\n        Build the bucket set by scanning the files in the smsgStore dir.\n\n        smsgBuckets should be empty\n    */\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgBuildBucketSet()\\n\");\n\n    int64_t  now            = GetTime();\n    uint32_t nFiles         = 0;\n    uint32_t nMessages      = 0;\n\n    fs::path pathSmsgDir = GetDataDir() / \"smsgStore\";\n    fs::directory_iterator itend;\n\n\n    if (!fs::exists(pathSmsgDir)\n        || !fs::is_directory(pathSmsgDir))\n    {\n        LogPrintf(\"Message store directory does not exist.\\n\");\n        return 0; // not an error\n    }\n\n\n    for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd)\n    {\n        if (!fs::is_regular_file(itd->status()))\n            continue;\n\n        std::string fileType = (*itd).path().extension().string();\n\n        if (fileType.compare(\".dat\") != 0)\n            continue;\n\n        std::string fileName = (*itd).path().filename().string();\n\n        if (fDebugSmsg)\n            LogPrintf(\"Processing file: %s.\\n\", fileName.c_str());\n\n        nFiles++;\n\n        // TODO files must be split if > 2GB\n        // time_noFile.dat\n        size_t sep = fileName.find_first_of(\"_\");\n        if (sep == std::string::npos)\n            continue;\n\n        std::string stime = fileName.substr(0, sep);\n\n        int64_t fileTime = boost::lexical_cast<int64_t>(stime);\n\n        if (fileTime < now - SMSG_RETENTION)\n        {\n            LogPrintf(\"Dropping file %s, expired.\\n\", fileName.c_str());\n            try {\n                fs::remove((*itd).path());\n            } catch (const fs::filesystem_error& ex)\n            {\n                LogPrintf(\"Error removing bucket file %s, %s.\\n\", fileName.c_str(), ex.what());\n            };\n            continue;\n        };\n\n        if (boost::algorithm::ends_with(fileName, \"_wl.dat\"))\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"Skipping wallet locked file: %s.\\n\", fileName.c_str());\n            continue;\n        };\n\n        size_t nTokenSetSize = 0;\n        SecureMessage smsg;\n        {\n            LOCK(cs_smsg);\n\n            std::set<SecMsgToken>& tokenSet = smsgBuckets[fileTime].setTokens;\n\n            FILE *fp;\n\n            if (!(fp = fopen((*itd).path().string().c_str(), \"rb\")))\n            {\n                LogPrintf(\"Error opening file: %s\\n\", strerror(errno));\n                continue;\n            };\n\n            for (;;)\n            {\n                long int ofs = ftell(fp);\n                SecMsgToken token;\n                token.offset = ofs;\n                errno = 0;\n                if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN)\n                {\n                    if (errno != 0)\n                    {\n                        LogPrintf(\"fread header failed: %s\\n\", strerror(errno));\n                    } else\n                    {\n                        //LogPrintf(\"End of file.\\n\");\n                    };\n                    break;\n                };\n                token.timestamp = smsg.timestamp;\n\n                if (smsg.nPayload < 8)\n                    continue;\n\n                if (fread(token.sample, sizeof(uint8_t), 8, fp) != 8)\n                {\n                    LogPrintf(\"fread data failed: %s\\n\", strerror(errno));\n                    break;\n                };\n\n                if (fseek(fp, smsg.nPayload-8, SEEK_CUR) != 0)\n                {\n                    LogPrintf(\"fseek, strerror: %s.\\n\", strerror(errno));\n                    break;\n                };\n\n                tokenSet.insert(token);\n            };\n\n            fclose(fp);\n\n            smsgBuckets[fileTime].hashBucket();\n\n            nTokenSetSize = tokenSet.size();\n        } // LOCK(cs_smsg);\n\n        nMessages += nTokenSetSize;\n        if (fDebugSmsg)\n            LogPrintf(\"Bucket %d contains %u messages.\\n\", fileTime, nTokenSetSize);\n    };\n\n    LogPrintf(\"Processed %u files, loaded %u buckets containing %u messages.\\n\", nFiles, smsgBuckets.size(), nMessages);\n\n    return 0;\n};\n\n/*\nSecureMsgAddWalletAddresses\nEnumerates the AddressBook, filters out anon outputs and checks the \"real addresses\"\nAdds these to the vector smsgAddresses to be used for decryption\n\nReturns  on success!\n*/\n\nint SecureMsgAddWalletAddresses()\n{\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgAddWalletAddresses()\\n\");\n\n    std::string sAnonPrefix(\"ao \");\n\n    uint32_t nAdded = 0;\n\n\n    BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook)\n    {\n        if (!IsDestMine(*pwalletMain, entry.first))\n            continue;\n\n        // -- skip addresses for anon outputs\n        if (entry.second.compare(0, sAnonPrefix.length(), sAnonPrefix) == 0)\n            continue;\n\n        // TODO: skip addresses for stealth transactions\n\n        CBitcoinAddress coinAddress(entry.first);\n        if (!coinAddress.IsValid())\n            continue;\n\n        std::string address;\n        std::string strPublicKey;\n        address = coinAddress.ToString();\n\n        bool fExists        = 0;\n        for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)\n        {\n            if (address != it->sAddress)\n                continue;\n            fExists = 1;\n            break;\n        };\n\n        if (fExists)\n            continue;\n\n        bool recvEnabled    = 1;\n        bool recvAnon       = 1;\n\n        smsgAddresses.push_back(SecMsgAddress(address, recvEnabled, recvAnon));\n        nAdded++;\n    };\n\n    if (fDebugSmsg)\n        LogPrintf(\"Added %u addresses to whitelist.\\n\", nAdded);\n\n    return 0;\n};\n\n\nint SecureMsgReadIni()\n{\n    if (!fSecMsgEnabled)\n        return false;\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgReadIni()\\n\");\n\n    fs::path fullpath = GetDataDir() / \"smsg.ini\";\n\n\n    FILE *fp;\n    errno = 0;\n    if (!(fp = fopen(fullpath.string().c_str(), \"r\")))\n    {\n        LogPrintf(\"Error opening file: %s\\n\", strerror(errno));\n        return 1;\n    };\n\n    char cLine[512];\n    char *pName, *pValue;\n\n    char cAddress[64];\n    int addrRecv, addrRecvAnon;\n\n    while (fgets(cLine, 512, fp))\n    {\n        cLine[strcspn(cLine, \"\\n\")] = '\\0';\n        cLine[strcspn(cLine, \"\\r\")] = '\\0';\n        cLine[511] = '\\0'; // for safety\n\n        // -- check that line contains a name value pair and is not a comment, or section header\n        if (cLine[0] == '#' || cLine[0] == '[' || strcspn(cLine, \"=\") < 1)\n            continue;\n\n        if (!(pName = strtok(cLine, \"=\"))\n            || !(pValue = strtok(NULL, \"=\")))\n            continue;\n\n        if (strcmp(pName, \"newAddressRecv\") == 0)\n        {\n            smsgOptions.fNewAddressRecv = (strcmp(pValue, \"true\") == 0) ? true : false;\n        } else\n        if (strcmp(pName, \"newAddressAnon\") == 0)\n        {\n            smsgOptions.fNewAddressAnon = (strcmp(pValue, \"true\") == 0) ? true : false;\n        } else\n        if (strcmp(pName, \"scanIncoming\") == 0)\n        {\n            smsgOptions.fScanIncoming = (strcmp(pValue, \"true\") == 0) ? true : false;\n        } else\n        if (strcmp(pName, \"key\") == 0)\n        {\n            int rv = sscanf(pValue, \"%64[^|]|%d|%d\", cAddress, &addrRecv, &addrRecvAnon);\n            if (rv == 3)\n            {\n                smsgAddresses.push_back(SecMsgAddress(std::string(cAddress), addrRecv, addrRecvAnon));\n            } else\n            {\n                LogPrintf(\"Could not parse key line %s, rv %d.\\n\", pValue, rv);\n            }\n        } else\n        {\n            LogPrintf(\"Unknown setting name: '%s'.\", pName);\n        };\n    };\n\n    LogPrintf(\"Loaded %u addresses.\\n\", smsgAddresses.size());\n\n    fclose(fp);\n\n    return 0;\n};\n\nint SecureMsgWriteIni()\n{\n    if (!fSecMsgEnabled)\n        return false;\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgWriteIni()\\n\");\n\n    fs::path fullpath = GetDataDir() / \"smsg.ini~\";\n\n    FILE *fp;\n    errno = 0;\n    if (!(fp = fopen(fullpath.string().c_str(), \"w\")))\n    {\n        LogPrintf(\"Error opening file: %s\\n\", strerror(errno));\n        return 1;\n    };\n\n    if (fwrite(\"[Options]\\n\", sizeof(char), 10, fp) != 10)\n    {\n        LogPrintf(\"fwrite error: %s\\n\", strerror(errno));\n        fclose(fp);\n        return false;\n    };\n\n    if (fprintf(fp, \"newAddressRecv=%s\\n\", smsgOptions.fNewAddressRecv ? \"true\" : \"false\") < 0\n        || fprintf(fp, \"newAddressAnon=%s\\n\", smsgOptions.fNewAddressAnon ? \"true\" : \"false\") < 0\n        || fprintf(fp, \"scanIncoming=%s\\n\", smsgOptions.fScanIncoming ? \"true\" : \"false\") < 0)\n    {\n        LogPrintf(\"fprintf error: %s\\n\", strerror(errno));\n        fclose(fp);\n        return false;\n    }\n\n    if (fwrite(\"\\n[Keys]\\n\", sizeof(char), 8, fp) != 8)\n    {\n        LogPrintf(\"fwrite error: %s\\n\", strerror(errno));\n        fclose(fp);\n        return false;\n    };\n    for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)\n    {\n        errno = 0;\n        if (fprintf(fp, \"key=%s|%d|%d\\n\", it->sAddress.c_str(), it->fReceiveEnabled, it->fReceiveAnon) < 0)\n        {\n            LogPrintf(\"fprintf error: %s\\n\", strerror(errno));\n            continue;\n        };\n    };\n\n\n    fclose(fp);\n\n\n    try {\n        fs::path finalpath = GetDataDir() / \"smsg.ini\";\n        fs::rename(fullpath, finalpath);\n    } catch (const fs::filesystem_error& ex)\n    {\n        LogPrintf(\"Error renaming file %s, %s.\\n\", fullpath.string().c_str(), ex.what());\n    };\n    return 0;\n};\n\n\n/** called from AppInit2() in init.cpp */\nbool SecureMsgStart(bool fDontStart, bool fScanChain)\n{\n    if (fDontStart)\n    {\n        LogPrintf(\"Secure messaging not started.\\n\");\n        return false;\n    };\n\n    LogPrintf(\"Secure messaging starting.\\n\");\n\n    fSecMsgEnabled = true;\n\n    if (SecureMsgReadIni() != 0)\n        LogPrintf(\"Failed to read smsg.ini\\n\");\n\n    if (smsgAddresses.size() < 1)\n    {\n        LogPrintf(\"No address keys loaded.\\n\");\n        if (SecureMsgAddWalletAddresses() != 0)\n            LogPrintf(\"Failed to load addresses from wallet.\\n\");\n        else\n            LogPrintf(\"Loaded addresses from wallet.\\n\");\n\n    } else {\n            LogPrintf(\"Loaded addresses from SMSG.ini\\n\");\n    }\n\n    if (fScanChain)\n    {\n        SecureMsgScanBlockChain();\n    };\n\n    if (SecureMsgBuildBucketSet() != 0)\n    {\n        LogPrintf(\"SecureMsg could not load bucket sets, secure messaging disabled.\\n\");\n        fSecMsgEnabled = false;\n        return false;\n    };\n\n    threadGroupSmsg.create_thread(boost::bind(&TraceThread<void (*)()>, \"smsg\", &ThreadSecureMsg));\n    threadGroupSmsg.create_thread(boost::bind(&TraceThread<void (*)()>, \"smsg-pow\", &ThreadSecureMsgPow));\n\n    return true;\n};\n\nbool SecureMsgShutdown()\n{\n    if (!fSecMsgEnabled)\n        return false;\n\n    LogPrintf(\"Stopping secure messaging.\\n\");\n\n\n    if (SecureMsgWriteIni() != 0)\n        LogPrintf(\"Failed to save smsg.ini\\n\");\n\n    fSecMsgEnabled = false;\n\n    threadGroupSmsg.interrupt_all();\n    threadGroupSmsg.join_all();\n\n    if (smsgDB)\n    {\n        LOCK(cs_smsgDB);\n        delete smsgDB;\n        smsgDB = NULL;\n    };\n\n    return true;\n};\n\nbool SecureMsgEnable()\n{\n    // -- start secure messaging at runtime\n    if (fSecMsgEnabled)\n    {\n        LogPrintf(\"SecureMsgEnable: secure messaging is already enabled.\\n\");\n        return false;\n    };\n\n    {\n        LOCK(cs_smsg);\n        fSecMsgEnabled = true;\n\n        smsgAddresses.clear(); // should be empty already\n        if (SecureMsgReadIni() != 0)\n            LogPrintf(\"Failed to read smsg.ini\\n\");\n\n        if (smsgAddresses.size() < 1)\n        {\n            LogPrintf(\"No address keys loaded.\\n\");\n            if (SecureMsgAddWalletAddresses() != 0)\n                LogPrintf(\"Failed to load addresses from wallet.\\n\");\n        };\n\n        smsgBuckets.clear(); // should be empty already\n\n        if (SecureMsgBuildBucketSet() != 0)\n        {\n            LogPrintf(\"SecureMsgEnable: could not load bucket sets, secure messaging disabled.\\n\");\n            fSecMsgEnabled = false;\n            return false;\n        };\n\n    } // cs_smsg\n\n    // -- start threads\n    threadGroupSmsg.create_thread(boost::bind(&TraceThread<void (*)()>, \"smsg\", &ThreadSecureMsg));\n    threadGroupSmsg.create_thread(boost::bind(&TraceThread<void (*)()>, \"smsg-pow\", &ThreadSecureMsgPow));\n\n    /*\n    if (!NewThread(ThreadSecureMsg, NULL)\n        || !NewThread(ThreadSecureMsgPow, NULL))\n    {\n        LogPrintf(\"SecureMsgEnable could not start threads, secure messaging disabled.\\n\");\n        fSecMsgEnabled = false;\n        return false;\n    };\n    */\n    // -- ping each peer, don't know which have messaging enabled\n    {\n        LOCK(cs_vNodes);\n        BOOST_FOREACH(CNode* pnode, vNodes)\n        {\n            pnode->PushMessage(\"smsgPing\");\n            pnode->PushMessage(\"smsgPong\"); // Send pong as have missed initial ping sent by peer when it connected\n        };\n    } // cs_vNodes\n    LogPrintf(\"Secure messaging enabled.\\n\");\n    return true;\n};\n\nbool SecureMsgDisable()\n{\n    // -- stop secure messaging at runtime\n    if (!fSecMsgEnabled)\n    {\n        LogPrintf(\"SecureMsgDisable: secure messaging is already disabled.\\n\");\n        return false;\n    };\n\n    {\n        LOCK(cs_smsg);\n        fSecMsgEnabled = false;\n\n        threadGroupSmsg.interrupt_all();\n        threadGroupSmsg.join_all();\n\n        // -- clear smsgBuckets\n        std::map<int64_t, SecMsgBucket>::iterator it;\n        it = smsgBuckets.begin();\n        for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it)\n        {\n            it->second.setTokens.clear();\n        };\n        smsgBuckets.clear();\n        smsgAddresses.clear();\n    } // cs_smsg\n\n    // -- tell each smsg enabled peer that this node is disabling\n    {\n        LOCK(cs_vNodes);\n        BOOST_FOREACH(CNode* pnode, vNodes)\n        {\n            if (!pnode->smsgData.fEnabled)\n                continue;\n            LOCK(pnode->smsgData.cs_smsg_net);\n            pnode->PushMessage(\"smsgDisabled\");\n            pnode->smsgData.fEnabled = false;\n        };\n    } // cs_vNodes\n\n\n    if (SecureMsgWriteIni() != 0)\n        LogPrintf(\"Failed to save smsg.ini\\n\");\n\n    // -- allow time for threads to stop\n    MilliSleep(3000); // seconds\n    // TODO be certain that threads have stopped\n\n    if (smsgDB)\n    {\n        LOCK(cs_smsgDB);\n        delete smsgDB;\n        smsgDB = NULL;\n    };\n\n\n    LogPrintf(\"Secure messaging disabled.\\n\");\n    return true;\n};\n\n\nbool SecureMsgReceiveData(CNode* pfrom, std::string strCommand, CDataStream& vRecv)\n{\n    /*\n        Called from ProcessMessage\n        Runs in ThreadMessageHandler2\n    */\n\n    /*\n        Commands\n        + smsgInv =\n            (1) received inventory of other node.\n                (1.1) sanity checks\n            (2) loop through buckets\n                (2.1) sanity checks\n                (2.2) check if bucket is locked to another node, if so continue but don't match. TODO: handle this properly, add critical section, lock on write. On read: nothing changes = no lock\n                    (2.2.3) If our bucket is not locked to another node then add hash to buffer to be requested..\n            (3) send smsgShow with list of hashes to request.\n\n        + smsgShow =\n        + smsgHave =\n        + smsgWant =\n        + smsgMsg = ??\n        + smsgPing\n        + smsgPong\n        + smsgMatch\n\n    */\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgReceiveData() %s %s.\\n\", pfrom->addrName.c_str(), strCommand.c_str());\n\n\n\n    if (strCommand == \"smsgInv\")\n    {\n        std::vector<uint8_t> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 4)\n        {\n            pfrom->Misbehaving(1);\n            return false; // not enough data received to be a valid smsgInv\n        };\n\n        int64_t now = GetTime();\n\n        {\n            LOCK(pfrom->smsgData.cs_smsg_net);\n\n            if (now < pfrom->smsgData.ignoreUntil)\n            {\n                if (fDebugSmsg)\n                    LogPrintf(\"Node is ignoring peer %d until %d.\\n\", pfrom->id, pfrom->smsgData.ignoreUntil);\n                return false;\n            };\n        }\n\n        uint32_t nBuckets       = smsgBuckets.size();\n        uint32_t nLocked        = 0;    // no. of locked buckets on this node\n        uint32_t nInvBuckets;           // no. of bucket headers sent by peer in smsgInv\n        memcpy(&nInvBuckets, &vchData[0], 4);\n        if (fDebugSmsg)\n            LogPrintf(\"Remote node sent %d bucket headers, this has %d.\\n\", nInvBuckets, nBuckets);\n\n\n        // -- Check no of buckets:\n        if (nInvBuckets > (SMSG_RETENTION / SMSG_BUCKET_LEN) + 1) // +1 for some leeway\n        {\n            LogPrintf(\"Peer sent more bucket headers than possible %u, %u.\\n\", nInvBuckets, (SMSG_RETENTION / SMSG_BUCKET_LEN));\n            pfrom->Misbehaving(1);\n            return false;\n        };\n\n        if (vchData.size() < 4 + nInvBuckets*16)\n        {\n            LogPrintf(\"Remote node did not send enough data.\\n\");\n            pfrom->Misbehaving(1);\n            return false;\n        };\n\n        std::vector<uint8_t> vchDataOut;\n        vchDataOut.reserve(4 + 8 * nInvBuckets); // reserve max possible size\n        vchDataOut.resize(4);\n        uint32_t nShowBuckets = 0;\n\n\n        uint8_t *p = &vchData[4];\n        for (uint32_t i = 0; i < nInvBuckets; ++i)\n        {\n            int64_t time;\n            uint32_t ncontent, hash;\n            memcpy(&time, p, 8);\n            memcpy(&ncontent, p+8, 4);\n            memcpy(&hash, p+12, 4);\n\n            p += 16;\n\n            // Check time valid:\n            if (time < now - SMSG_RETENTION)\n            {\n                if (fDebugSmsg)\n                    LogPrintf(\"Not interested in peer bucket %d, has expired.\\n\", time);\n\n                if (time < now - SMSG_RETENTION - SMSG_TIME_LEEWAY)\n                    pfrom->Misbehaving(1);\n                continue;\n            };\n            if (time > now + SMSG_TIME_LEEWAY)\n            {\n                if (fDebugSmsg)\n                    LogPrintf(\"Not interested in peer bucket %d, in the future.\\n\", time);\n                pfrom->Misbehaving(1);\n                continue;\n            };\n\n            if (ncontent < 1)\n            {\n                if (fDebugSmsg)\n                    LogPrintf(\"Peer sent empty bucket, ignore %d %u %u.\\n\", time, ncontent, hash);\n                continue;\n            };\n\n            if (fDebugSmsg)\n            {\n                LogPrintf(\"peer bucket %d %u %u.\\n\", time, ncontent, hash);\n                LogPrintf(\"this bucket %d %u %u.\\n\", time, smsgBuckets[time].setTokens.size(), smsgBuckets[time].hash);\n            };\n            {\n            LOCK(cs_smsg);\n                if (smsgBuckets[time].nLockCount > 0)\n                {\n                    if (fDebugSmsg)\n                        LogPrintf(\"Bucket is locked %u, waiting for peer %u to send data.\\n\", smsgBuckets[time].nLockCount, smsgBuckets[time].nLockPeerId);\n                    nLocked++;\n                    continue;\n                };\n\n                // -- if this node has more than the peer node, peer node will pull from this\n                //    if then peer node has more this node will pull fom peer\n                if (smsgBuckets[time].setTokens.size() < ncontent\n                    || (smsgBuckets[time].setTokens.size() == ncontent\n                        && smsgBuckets[time].hash != hash)) // if same amount in buckets check hash\n                {\n                    if (fDebugSmsg)\n                        LogPrintf(\"Requesting contents of bucket %d.\\n\", time);\n\n                    uint32_t sz = vchDataOut.size();\n                    vchDataOut.resize(sz + 8);\n                    memcpy(&vchDataOut[sz], &time, 8);\n\n                    nShowBuckets++;\n                };\n            } // LOCK(cs_smsg);\n        };\n\n        // TODO: should include hash?\n        memcpy(&vchDataOut[0], &nShowBuckets, 4);\n        if (vchDataOut.size() > 4)\n        {\n            pfrom->PushMessage(\"smsgShow\", vchDataOut);\n        } else\n        if (nLocked < 1) // Don't report buckets as matched if any are locked\n        {\n            // -- peer has no buckets we want, don't send them again until something changes\n            //    peer will still request buckets from this node if needed (< ncontent)\n            vchDataOut.resize(8);\n            memcpy(&vchDataOut[0], &now, 8);\n            pfrom->PushMessage(\"smsgMatch\", vchDataOut);\n            if (fDebugSmsg)\n                LogPrintf(\"Sending smsgMatch, no locked buckets, time= %d.\\n\", now);\n        } else\n        if (nLocked >= 1)\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"%u buckets were locked, time= %d.\\n\", nLocked, now);\n        };\n\n    } else\n    if (strCommand == \"smsgShow\")\n    {\n        std::vector<uint8_t> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 4)\n            return false;\n\n        uint32_t nBuckets;\n        memcpy(&nBuckets, &vchData[0], 4);\n\n        if (vchData.size() < 4 + nBuckets * 8)\n            return false;\n\n        if (fDebugSmsg)\n            LogPrintf(\"smsgShow: peer wants to see content of %u buckets.\\n\", nBuckets);\n\n        std::map<int64_t, SecMsgBucket>::iterator itb;\n        std::set<SecMsgToken>::iterator it;\n\n        std::vector<uint8_t> vchDataOut;\n        int64_t time;\n        uint8_t* pIn = &vchData[4];\n        for (uint32_t i = 0; i < nBuckets; ++i, pIn += 8)\n        {\n            memcpy(&time, pIn, 8);\n\n            {\n                LOCK(cs_smsg);\n                itb = smsgBuckets.find(time);\n                if (itb == smsgBuckets.end())\n                {\n                    if (fDebugSmsg)\n                        LogPrintf(\"Don't have bucket %d.\\n\", time);\n                    continue;\n                };\n\n                std::set<SecMsgToken>& tokenSet = (*itb).second.setTokens;\n\n                try { vchDataOut.resize(8 + 16 * tokenSet.size()); } catch (std::exception& e)\n                {\n                    LogPrintf(\"vchDataOut.resize %u threw: %s.\\n\", 8 + 16 * tokenSet.size(), e.what());\n                    continue;\n                };\n                memcpy(&vchDataOut[0], &time, 8);\n\n                uint8_t* p = &vchDataOut[8];\n                for (it = tokenSet.begin(); it != tokenSet.end(); ++it)\n                {\n                    memcpy(p, &it->timestamp, 8);\n                    memcpy(p+8, &it->sample, 8);\n\n                    p += 16;\n                };\n            }\n            pfrom->PushMessage(\"smsgHave\", vchDataOut);\n        };\n\n\n    } else\n    if (strCommand == \"smsgHave\")\n    {\n        // -- peer has these messages in bucket\n        std::vector<uint8_t> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 8)\n            return false;\n\n        int n = (vchData.size() - 8) / 16;\n\n        int64_t time;\n        memcpy(&time, &vchData[0], 8);\n\n        // -- Check time valid:\n        int64_t now = GetTime();\n        if (time < now - SMSG_RETENTION)\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"Not interested in peer bucket %d, has expired.\\n\", time);\n            return false;\n        };\n        if (time > now + SMSG_TIME_LEEWAY)\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"Not interested in peer bucket %d, in the future.\\n\", time);\n            pfrom->Misbehaving(1);\n            return false;\n        };\n\n        std::vector<uint8_t> vchDataOut;\n\n        {\n            LOCK(cs_smsg);\n            if (smsgBuckets[time].nLockCount > 0)\n            {\n                if (fDebugSmsg)\n                    LogPrintf(\"Bucket %d lock count %u, waiting for message data from peer %u.\\n\", time, smsgBuckets[time].nLockCount, smsgBuckets[time].nLockPeerId);\n                return false;\n            };\n\n            if (fDebugSmsg)\n                LogPrintf(\"Sifting through bucket %d.\\n\", time);\n\n            vchDataOut.resize(8);\n            memcpy(&vchDataOut[0], &vchData[0], 8);\n\n            std::set<SecMsgToken>& tokenSet = smsgBuckets[time].setTokens;\n            std::set<SecMsgToken>::iterator it;\n            SecMsgToken token;\n            uint8_t* p = &vchData[8];\n\n            for (int i = 0; i < n; ++i)\n            {\n                memcpy(&token.timestamp, p, 8);\n                memcpy(&token.sample, p+8, 8);\n\n                it = tokenSet.find(token);\n                if (it == tokenSet.end())\n                {\n                    int nd = vchDataOut.size();\n                    try {\n                        vchDataOut.resize(nd + 16);\n                    } catch (std::exception& e) {\n                        LogPrintf(\"vchDataOut.resize %d threw: %s.\\n\", nd + 16, e.what());\n                        continue;\n                    };\n\n                    memcpy(&vchDataOut[nd], p, 16);\n                };\n\n                p += 16;\n            };\n        }\n\n        if (vchDataOut.size() > 8)\n        {\n            if (fDebugSmsg)\n            {\n                LogPrintf(\"Asking peer for %u messages.\\n\", (vchDataOut.size() - 8) / 16);\n                LogPrintf(\"Locking bucket %u for peer %d.\\n\", time, pfrom->id);\n            };\n            {\n                LOCK(cs_smsg);\n                smsgBuckets[time].nLockCount   = 3; // lock this bucket for at most 3 * SMSG_THREAD_DELAY seconds, unset when peer sends smsgMsg\n                smsgBuckets[time].nLockPeerId  = pfrom->id;\n            }\n            pfrom->PushMessage(\"smsgWant\", vchDataOut);\n        };\n    } else\n    if (strCommand == \"smsgWant\")\n    {\n        std::vector<uint8_t> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 8)\n            return false;\n\n        std::vector<uint8_t> vchOne;\n        std::vector<uint8_t> vchBunch;\n\n        vchBunch.resize(4+8); // nmessages + bucketTime\n\n        int n = (vchData.size() - 8) / 16;\n\n        int64_t time;\n        uint32_t nBunch = 0;\n        memcpy(&time, &vchData[0], 8);\n\n\n        std::map<int64_t, SecMsgBucket>::iterator itb;\n\n        {\n            LOCK(cs_smsg);\n            itb = smsgBuckets.find(time);\n            if (itb == smsgBuckets.end())\n            {\n                if (fDebugSmsg)\n                    LogPrintf(\"Don't have bucket %d.\\n\", time);\n                return false;\n            };\n\n            std::set<SecMsgToken>& tokenSet = itb->second.setTokens;\n            std::set<SecMsgToken>::iterator it;\n            SecMsgToken token;\n            uint8_t* p = &vchData[8];\n            for (int i = 0; i < n; ++i)\n            {\n                memcpy(&token.timestamp, p, 8);\n                memcpy(&token.sample, p+8, 8);\n\n                it = tokenSet.find(token);\n                if (it == tokenSet.end())\n                {\n                    if (fDebugSmsg)\n                        LogPrintf(\"Don't have wanted message %d.\\n\", token.timestamp);\n                } else\n                {\n                    //LogPrintf(\"Have message at %d.\\n\", it->offset); // DEBUG\n                    token.offset = it->offset;\n                    //LogPrintf(\"winb before SecureMsgRetrieve %d.\\n\", token.timestamp);\n\n                    // -- place in vchOne so if SecureMsgRetrieve fails it won't corrupt vchBunch\n                    if (SecureMsgRetrieve(token, vchOne) == 0)\n                    {\n                        nBunch++;\n                        vchBunch.insert(vchBunch.end(), vchOne.begin(), vchOne.end()); // append\n                    } else\n                    {\n                        LogPrintf(\"SecureMsgRetrieve failed %d.\\n\", token.timestamp);\n                    };\n\n                    if (nBunch >= 500\n                        || vchBunch.size() >= 96000)\n                    {\n                        if (fDebugSmsg)\n                            LogPrintf(\"Break bunch %u, %u.\\n\", nBunch, vchBunch.size());\n                        break; // end here, peer will send more want messages if needed.\n                    };\n                };\n                p += 16;\n            };\n        } // LOCK(cs_smsg);\n\n        if (nBunch > 0)\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"Sending block of %u messages for bucket %d.\\n\", nBunch, time);\n\n            memcpy(&vchBunch[0], &nBunch, 4);\n            memcpy(&vchBunch[4], &time, 8);\n            pfrom->PushMessage(\"smsgMsg\", vchBunch);\n        };\n    } else\n    if (strCommand == \"smsgMsg\")\n    {\n        std::vector<uint8_t> vchData;\n        vRecv >> vchData;\n\n        if (fDebugSmsg)\n            LogPrintf(\"smsgMsg vchData.size() %u.\\n\", vchData.size());\n\n        SecureMsgReceive(pfrom, vchData);\n    } else\n    if (strCommand == \"smsgMatch\")\n    {\n        /*\n        Basically all this code has to go..\n        For now we can use it to punish nodes running the older version, not that it's really need because the overhead is small.\n        TODO: remove this code.\n        */\n        std::vector<uint8_t> vchData;\n        vRecv >> vchData;\n\n\n        if (vchData.size() < 8)\n        {\n            LogPrintf(\"smsgMatch, not enough data %u.\\n\", vchData.size());\n            pfrom->Misbehaving(1);\n            return false;\n        };\n\n        int64_t time;\n        memcpy(&time, &vchData[0], 8);\n\n        int64_t now = GetTime();\n        if (time > now + SMSG_TIME_LEEWAY)\n        {\n            LogPrintf(\"Warning: Peer buckets matched in the future: %d.\\nEither this node or the peer node has the incorrect time set.\\n\", time);\n            if (fDebugSmsg)\n                LogPrintf(\"Peer match time set to now.\\n\");\n            time = now;\n        };\n        /*\n        {\n            LOCK(pfrom->smsgData.cs_smsg_net);\n            pfrom->smsgData.lastMatched = time;\n        }*/\n        if (fDebugSmsg)\n            LogPrintf(\"[BLOCKED] Peer buckets matched in smsgWant at %d.\\n\", time);\n\n    } else\n    if (strCommand == \"smsgPing\")\n    {\n        // -- smsgPing is the initial message, send reply\n        pfrom->PushMessage(\"smsgPong\");\n    } else\n    if (strCommand == \"smsgPong\")\n    {\n        if (fDebugSmsg)\n             LogPrintf(\"Peer replied, secure messaging enabled.\\n\");\n\n        {\n            LOCK(pfrom->smsgData.cs_smsg_net);\n            pfrom->smsgData.fEnabled = true;\n        }\n\n    } else\n    if (strCommand == \"smsgDisabled\")\n    {\n        // -- peer has disabled secure messaging.\n\n        {\n            LOCK(pfrom->smsgData.cs_smsg_net);\n            pfrom->smsgData.fEnabled = false;\n        }\n\n        if (fDebugSmsg)\n            LogPrintf(\"Peer %d has disabled secure messaging.\\n\", pfrom->id);\n\n    } else\n    if (strCommand == \"smsgIgnore\")\n    {\n        // -- peer is reporting that it will ignore this node until time.\n        //    Ignore peer too\n        std::vector<uint8_t> vchData;\n        vRecv >> vchData;\n\n        if (vchData.size() < 8)\n        {\n            LogPrintf(\"smsgIgnore, not enough data %u.\\n\", vchData.size());\n            pfrom->Misbehaving(1);\n            return false;\n        };\n\n        int64_t time;\n        memcpy(&time, &vchData[0], 8);\n\n        {\n            LOCK(pfrom->smsgData.cs_smsg_net);\n            pfrom->smsgData.ignoreUntil = time;\n        }\n\n\n        if (fDebugSmsg)\n            LogPrintf(\"Peer %d is ignoring this node until %d, ignore peer too.\\n\", pfrom->id, time);\n    } else\n    {\n        // Unknown message\n    };\n\n    return true;\n};\n\nbool SecureMsgSendData(CNode* pto, bool fSendTrickle)\n{\n    /*\n        Called from ProcessMessage\n        Runs in ThreadMessageHandler2\n    */\n\n    LOCK(pto->smsgData.cs_smsg_net);\n\n    //LogPrintf(\"SecureMsgSendData() %s.\\n\", pto->addrName.c_str());\n\n    int64_t now = GetTime();\n\n    if (pto->smsgData.lastSeen == 0)\n    {\n        // -- first contact\n        if (fDebugSmsg)\n            LogPrintf(\"SecureMsgSendData() new node %s, peer id %u.\\n\", pto->addrName.c_str(), pto->id);\n        // -- Send smsgPing once, do nothing until receive 1st smsgPong (then set fEnabled)\n        pto->PushMessage(\"smsgPing\");\n        pto->smsgData.lastSeen = GetTime();\n        return true;\n    } else\n    if (!pto->smsgData.fEnabled\n        || now - pto->smsgData.lastSeen < SMSG_SEND_DELAY\n        || now < pto->smsgData.ignoreUntil)\n    {\n        return true;\n    };\n\n    // -- When nWakeCounter == 0, resend bucket inventory.\n    /*\n    if (pto->smsgData.nWakeCounter < 1)\n    {\n        pto->smsgData.lastMatched = GetTime(); //used to be 0.\n        pto->smsgData.nWakeCounter = 10 + GetRandInt(300);  // set to a random time between [10, 300] * SMSG_SEND_DELAY seconds\n\n        if (fDebugSmsg)\n            LogPrintf(\"SecureMsgSendData(): nWakeCounter expired, sending bucket inventory to %s.\\n\"\n            \"Now %d next wake counter %u\\n\", pto->addrName.c_str(), now, pto->smsgData.nWakeCounter);\n    };\n    pto->smsgData.nWakeCounter--;\n    */\n\n    /*Why resend the whole bucket inventory?\n        Seems like a very odd way to handle it.\n        TODO: remove this code.\n\n    */\n\n\n\n    {\n        LOCK(cs_smsg);\n        std::map<int64_t, SecMsgBucket>::iterator it;\n\n        uint32_t nBuckets = smsgBuckets.size();\n        if (nBuckets > 0) // no need to send keep alive pkts, coin messages already do that\n        {\n            std::vector<uint8_t> vchData;\n            // should reserve?\n            vchData.reserve(4 + nBuckets*16); // timestamp + size + hash\n\n            uint32_t nBucketsShown = 0;\n            vchData.resize(4);\n            uint8_t* p = &vchData[4];\n\n\n        /*\n                Get time before loop and after looping through messages set nLastMatched to time before loop.\n                This prevents scenario where:\n                    Loop()\n                        message = locked and  thus skipped\n                       message become free and nTimeChanged is updated\n                    End loop\n\n                    nLastMatched = GetTime()\n                    => bucket that became free in loop is now skipped :/\n\n                Scenario 2:\n                    Same as one but time is updated before\n\n                        bucket nTimeChanged is updated but not unlocked yet\n                        now = GetTime()\n                        Loop of buckets skips message\n\n                    But this is nanoseconds, very unlikely.\n\n             */\n\n            for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it)\n            {\n                SecMsgBucket &bkt = it->second;\n\n                uint32_t nMessages = bkt.setTokens.size();\n\n                if (bkt.timeChanged < pto->smsgData.lastMatched     // peer was last sent all buckets at time of lastMatched. It should have this bucket\n                    || nMessages < 1)                               // this bucket is empty\n                    continue;\n\n                uint32_t hash = bkt.hash;\n\n                if(fDebugSmsg)\n                    LogPrintf(\"Preparing bucket with hash %d for transfer to node %u. timeChanged=%d > lastMatched=%d\\n\", hash, pto->id, bkt.timeChanged, pto->smsgData.lastMatched);\n\n                try { vchData.resize(vchData.size() + 16); } catch (std::exception& e)\n                {\n                    LogPrintf(\"vchData.resize %u threw: %s.\\n\", vchData.size() + 16, e.what());\n                    continue;\n                };\n                memcpy(p, &it->first, 8);\n                memcpy(p+8, &nMessages, 4);\n                memcpy(p+12, &hash, 4);\n\n                p += 16;\n                nBucketsShown++;\n                //if (fDebug)\n                //    LogPrintf(\"Sending bucket %d, size %d \\n\", it->first, it->second.size());\n            };\n\n            if (vchData.size() > 4)\n            {\n                memcpy(&vchData[0], &nBucketsShown, 4);\n                if (fDebugSmsg)\n                    LogPrintf(\"Sending %d bucket headers.\\n\", nBucketsShown);\n\n                pto->PushMessage(\"smsgInv\", vchData);\n            };\n        };\n    } // cs_smsg\n\n    pto->smsgData.lastSeen = now;\n    pto->smsgData.lastMatched = now; //bug fix smsg 3\n\n    return true;\n};\n\n\nstatic int SecureMsgInsertAddress(CKeyID& hashKey, CPubKey& pubKey, SecMsgDB& addrpkdb)\n{\n    /* Insert key hash and public key to addressdb.\n\n        (+) Called when receiving a message, it will automatically add the public key of the sender to our database so we can reply.\n\n        should have LOCK(cs_smsg) where db is opened\n\n        returns\n            0 success\n            1 error\n            4 address is already in db\n    */\n\n\n    if (addrpkdb.ExistsPK(hashKey))\n    {\n        //LogPrintf(\"DB already contains public key for address.\\n\");\n        CPubKey cpkCheck;\n        if (!addrpkdb.ReadPK(hashKey, cpkCheck))\n        {\n            LogPrintf(\"addrpkdb.Read failed.\\n\");\n        } else\n        {\n            if (cpkCheck != pubKey)\n                LogPrintf(\"DB already contains existing public key that does not match .\\n\");\n        };\n        return 4;\n    };\n\n    if (!addrpkdb.WritePK(hashKey, pubKey))\n    {\n        LogPrintf(\"Write pair failed.\\n\");\n        return 1;\n    };\n\n    return 0;\n};\n\nint SecureMsgInsertAddress(CKeyID& hashKey, CPubKey& pubKey)\n{\n    int rv;\n    {\n        LOCK(cs_smsgDB);\n        SecMsgDB addrpkdb;\n\n        if (!addrpkdb.Open(\"cr+\"))\n            return 1;\n\n        rv = SecureMsgInsertAddress(hashKey, pubKey, addrpkdb);\n    }\n    return rv;\n};\n\n\nstatic bool ScanBlock(CBlock& block, CTxDB& txdb, SecMsgDB& addrpkdb,\n    uint32_t& nTransactions, uint32_t& nElements, uint32_t& nPubkeys, uint32_t& nDuplicates)\n{\n    AssertLockHeld(cs_smsgDB);\n\n    valtype vch;\n    opcodetype opcode;\n\n    // -- only scan inputs of standard txns and coinstakes\n    BOOST_FOREACH(CTransaction& tx, block.vtx)\n    {\n        // - harvest public keys from coinstake txns\n        if (tx.IsCoinStake())\n        {\n            const CTxOut& txout = tx.vout[1];\n            CScript::const_iterator pc = txout.scriptPubKey.begin();\n            while (pc < txout.scriptPubKey.end())\n            {\n                if (!txout.scriptPubKey.GetOp(pc, opcode, vch))\n                    break;\n\n                if (vch.size() == 33) // pubkey\n                {\n                    CPubKey pubKey(vch);\n\n                    if (!pubKey.IsValid()\n                        || !pubKey.IsCompressed())\n                    {\n                        LogPrintf(\"Public key is invalid %s.\\n\", HexStr(pubKey).c_str());\n                        continue;\n                    };\n\n                    CKeyID addrKey = pubKey.GetID();\n                    switch (SecureMsgInsertAddress(addrKey, pubKey, addrpkdb))\n                    {\n                        case 0: nPubkeys++; break;      // added key\n                        case 4: nDuplicates++; break;   // duplicate key\n                    }\n                    break;\n                };\n            };\n            nElements++;\n        } else\n        if (tx.IsStandard())\n        {\n            for (uint32_t i = 0; i < tx.vin.size(); i++)\n            {\n                if (tx.nVersion == ANON_TXN_VERSION\n                    && tx.vin[i].IsAnonInput())\n                    continue; // skip anon inputs\n\n                CScript *script = &tx.vin[i].scriptSig;\n                CScript::const_iterator pc = script->begin();\n                CScript::const_iterator pend = script->end();\n\n                CKey key;\n\n                while (pc < pend)\n                {\n                    if (!script->GetOp(pc, opcode, vch))\n                        break;\n                    // - opcode is the length of the following data, compressed public key is always 33\n                    if (opcode == 33)\n                    {\n                        CPubKey pubKey(vch);\n\n                        if (!pubKey.IsValid()\n                            || !pubKey.IsCompressed())\n                        {\n                            LogPrintf(\"Public key is invalid %s.\\n\", HexStr(pubKey).c_str());\n                            continue;\n                        };\n\n                        CKeyID addrKey = pubKey.GetID();\n                        switch (SecureMsgInsertAddress(addrKey, pubKey, addrpkdb))\n                        {\n                            case 0: nPubkeys++; break;      // added key\n                            case 4: nDuplicates++; break;   // duplicate key\n                        }\n                        break;\n                    };\n\n                    //LogPrintf(\"opcode %d, %s, value %s.\\n\", opcode, GetOpName(opcode), ValueString(vch).c_str());\n                };\n                nElements++;\n            };\n        };\n        nTransactions++;\n\n        if (nTransactions % 10000 == 0) // for ScanChainForPublicKeys\n        {\n            LogPrintf(\"Scanning transaction no. %u.\\n\", nTransactions);\n        };\n    };\n    return true;\n};\n\n\nbool SecureMsgScanBlock(CBlock& block)\n{\n    // - scan block for public key addresses\n\n    if (!smsgOptions.fScanIncoming)\n        return true;\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgScanBlock().\\n\");\n\n    uint32_t nTransactions  = 0;\n    uint32_t nElements      = 0;\n    uint32_t nPubkeys       = 0;\n    uint32_t nDuplicates    = 0;\n\n    {\n        LOCK(cs_smsgDB);\n        CTxDB txdb(\"r\");\n\n        SecMsgDB addrpkdb;\n        if (!addrpkdb.Open(\"cw\")\n            || !addrpkdb.TxnBegin())\n            return false;\n\n        ScanBlock(block, txdb, addrpkdb,\n            nTransactions, nElements, nPubkeys, nDuplicates);\n\n        addrpkdb.TxnCommit();\n    } // cs_smsgDB\n\n    if (fDebugSmsg)\n        LogPrintf(\"Found %u transactions, %u elements, %u new public keys, %u duplicates.\\n\", nTransactions, nElements, nPubkeys, nDuplicates);\n\n    return true;\n};\n\nbool ScanChainForPublicKeys(CBlockIndex* pindexStart)\n{\n    LogPrintf(\"Scanning block chain for public keys.\\n\");\n    int64_t nStart = GetTimeMillis();\n\n    if (fDebugSmsg)\n        LogPrintf(\"From height %u.\\n\", pindexStart->nHeight);\n\n    // -- public keys are in txin.scriptSig\n    //    matching addresses are in scriptPubKey of txin's referenced output\n\n    uint32_t nBlocks        = 0;\n    uint32_t nTransactions  = 0;\n    uint32_t nInputs        = 0;\n    uint32_t nPubkeys       = 0;\n    uint32_t nDuplicates    = 0;\n\n    {\n        LOCK(cs_smsgDB);\n\n        CTxDB txdb(\"r\");\n\n        SecMsgDB addrpkdb;\n        if (!addrpkdb.Open(\"cw\")\n            || !addrpkdb.TxnBegin())\n            return false;\n\n        CBlockIndex* pindex = pindexStart;\n        while (pindex)\n        {\n            nBlocks++;\n            CBlock block;\n            block.ReadFromDisk(pindex, true);\n\n            ScanBlock(block, txdb, addrpkdb,\n                nTransactions, nInputs, nPubkeys, nDuplicates);\n\n            pindex = pindex->pnext;\n        };\n\n        addrpkdb.TxnCommit();\n    } // cs_smsgDB\n\n    LogPrintf(\"Scanned %u blocks, %u transactions, %u inputs\\n\", nBlocks, nTransactions, nInputs);\n    LogPrintf(\"Found %u public keys, %u duplicates.\\n\", nPubkeys, nDuplicates);\n    LogPrintf(\"Took %d ms\\n\", GetTimeMillis() - nStart);\n\n    return true;\n};\n\nbool SecureMsgScanBlockChain()\n{\n    TRY_LOCK(cs_main, lockMain);\n    if (lockMain)\n    {\n        CBlockIndex *pindexScan = pindexGenesisBlock;\n        if (pindexScan == NULL)\n        {\n            LogPrintf(\"Error: pindexGenesisBlock not set.\\n\");\n            return false;\n        };\n\n\n        try { // -- in try to catch errors opening db,\n            if (!ScanChainForPublicKeys(pindexScan))\n                return false;\n        } catch (std::exception& e)\n        {\n            LogPrintf(\"ScanChainForPublicKeys() threw: %s.\\n\", e.what());\n            return false;\n        };\n    } else\n    {\n        LogPrintf(\"ScanChainForPublicKeys() Could not lock main.\\n\");\n        return false;\n    };\n\n    return true;\n};\n\nbool SecureMsgScanBuckets()\n{\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgScanBuckets()\\n\");\n\n    if (!fSecMsgEnabled\n        || pwalletMain->IsLocked())\n        return false;\n\n    int64_t  mStart         = GetTimeMillis();\n    int64_t  now            = GetTime();\n    uint32_t nFiles         = 0;\n    uint32_t nMessages      = 0;\n    uint32_t nFoundMessages = 0;\n\n    fs::path pathSmsgDir = GetDataDir() / \"smsgStore\";\n    fs::directory_iterator itend;\n\n    if (!fs::exists(pathSmsgDir)\n        || !fs::is_directory(pathSmsgDir))\n    {\n        LogPrintf(\"Message store directory does not exist.\\n\");\n        return 0; // not an error\n    };\n\n    SecureMessage smsg;\n    std::vector<uint8_t> vchData;\n\n    for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd)\n    {\n        if (!fs::is_regular_file(itd->status()))\n            continue;\n\n        std::string fileType = (*itd).path().extension().string();\n\n        if (fileType.compare(\".dat\") != 0)\n            continue;\n\n        std::string fileName = (*itd).path().filename().string();\n\n\n        if (fDebugSmsg)\n            LogPrintf(\"Processing file: %s.\\n\", fileName.c_str());\n\n        nFiles++;\n\n        // TODO files must be split if > 2GB\n        // time_noFile.dat\n        size_t sep = fileName.find_first_of(\"_\");\n        if (sep == std::string::npos)\n            continue;\n\n        std::string stime = fileName.substr(0, sep);\n\n        int64_t fileTime = boost::lexical_cast<int64_t>(stime);\n\n        if (fileTime < now - SMSG_RETENTION)\n        {\n            LogPrintf(\"Dropping file %s, expired.\\n\", fileName.c_str());\n            try {\n                fs::remove((*itd).path());\n            } catch (const fs::filesystem_error& ex)\n            {\n                LogPrintf(\"Error removing bucket file %s, %s.\\n\", fileName.c_str(), ex.what());\n            };\n            continue;\n        };\n\n        if (boost::algorithm::ends_with(fileName, \"_wl.dat\"))\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"Skipping wallet locked file: %s.\\n\", fileName.c_str());\n            continue;\n        };\n\n        {\n            LOCK(cs_smsg);\n            FILE *fp;\n            errno = 0;\n            if (!(fp = fopen((*itd).path().string().c_str(), \"rb\")))\n            {\n                LogPrintf(\"Error opening file: %s\\n\", strerror(errno));\n                continue;\n            };\n\n            for (;;)\n            {\n                errno = 0;\n                if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN)\n                {\n                    if (errno != 0)\n                    {\n                        LogPrintf(\"fread header failed: %s\\n\", strerror(errno));\n                    } else\n                    {\n                        //LogPrintf(\"End of file.\\n\");\n                    };\n                    break;\n                };\n\n                try { vchData.resize(smsg.nPayload); } catch (std::exception& e)\n                {\n                    LogPrintf(\"SecureMsgWalletUnlocked(): Could not resize vchData, %u, %s\\n\", smsg.nPayload, e.what());\n                    fclose(fp);\n                    return 1;\n                };\n\n                if (fread(&vchData[0], sizeof(uint8_t), smsg.nPayload, fp) != smsg.nPayload)\n                {\n                    LogPrintf(\"fread data failed: %s\\n\", strerror(errno));\n                    break;\n                };\n\n                // -- don't report to gui,\n                int rv = SecureMsgScanMessage(&smsg.hash[0], &vchData[0], smsg.nPayload, false);\n\n                if (rv == 0)\n                {\n                    nFoundMessages++;\n                } else\n                if (rv != 0)\n                {\n                    // SecureMsgScanMessage failed\n                };\n\n                nMessages++;\n            };\n\n            fclose(fp);\n\n            // -- remove wl file when scanned\n            try {\n                fs::remove((*itd).path());\n            } catch (const boost::filesystem::filesystem_error& ex)\n            {\n                LogPrintf(\"Error removing wl file %s - %s\\n\", fileName.c_str(), ex.what());\n                return 1;\n            };\n        } // cs_smsg\n    };\n\n    LogPrintf(\"Processed %u files, scanned %u messages, received %u messages.\\n\", nFiles, nMessages, nFoundMessages);\n    LogPrintf(\"Took %d ms\\n\", GetTimeMillis() - mStart);\n\n    return true;\n}\n\n\nint SecureMsgWalletUnlocked()\n{\n    /*\n    When the wallet is unlocked, scan messages received while wallet was locked.\n    */\n    if (!fSecMsgEnabled)\n        return 0;\n\n    LogPrintf(\"SecureMsgWalletUnlocked()\\n\");\n\n    if (pwalletMain->IsLocked())\n    {\n        LogPrintf(\"Error: Wallet is locked.\\n\");\n        return 1;\n    };\n\n    int64_t  now            = GetTime();\n    uint32_t nFiles         = 0;\n    uint32_t nMessages      = 0;\n    uint32_t nFoundMessages = 0;\n\n    fs::path pathSmsgDir = GetDataDir() / \"smsgStore\";\n    fs::directory_iterator itend;\n\n    if (!fs::exists(pathSmsgDir)\n        || !fs::is_directory(pathSmsgDir))\n    {\n        LogPrintf(\"Message store directory does not exist.\\n\");\n        return 0; // not an error\n    };\n\n    SecureMessage smsg;\n    std::vector<uint8_t> vchData;\n\n    for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd)\n    {\n        if (!fs::is_regular_file(itd->status()))\n            continue;\n\n        std::string fileName = (*itd).path().filename().string();\n\n        if (!boost::algorithm::ends_with(fileName, \"_wl.dat\"))\n            continue;\n\n        if (fDebugSmsg)\n            LogPrintf(\"Processing file: %s.\\n\", fileName.c_str());\n\n        nFiles++;\n\n        // TODO files must be split if > 2GB\n        // time_noFile_wl.dat\n        size_t sep = fileName.find_first_of(\"_\");\n        if (sep == std::string::npos)\n            continue;\n\n        std::string stime = fileName.substr(0, sep);\n\n        int64_t fileTime = boost::lexical_cast<int64_t>(stime);\n\n        if (fileTime < now - SMSG_RETENTION)\n        {\n            LogPrintf(\"Dropping wallet locked file %s, expired.\\n\", fileName.c_str());\n            try {\n                fs::remove((*itd).path());\n            } catch (const boost::filesystem::filesystem_error& ex)\n            {\n                LogPrintf(\"Error removing wl file %s - %s\\n\", fileName.c_str(), ex.what());\n                return 1;\n            };\n            continue;\n        };\n\n        {\n            LOCK(cs_smsg);\n            FILE *fp;\n            errno = 0;\n            if (!(fp = fopen((*itd).path().string().c_str(), \"rb\")))\n            {\n                LogPrintf(\"Error opening file: %s\\n\", strerror(errno));\n                continue;\n            };\n\n            for (;;)\n            {\n                errno = 0;\n                if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN)\n                {\n                    if (errno != 0)\n                    {\n                        LogPrintf(\"fread header failed: %s\\n\", strerror(errno));\n                    } else\n                    {\n                        //LogPrintf(\"End of file.\\n\");\n                    };\n                    break;\n                };\n\n                try { vchData.resize(smsg.nPayload); } catch (std::exception& e)\n                {\n                    LogPrintf(\"SecureMsgWalletUnlocked(): Could not resize vchData, %u, %s\\n\", smsg.nPayload, e.what());\n                    fclose(fp);\n                    return 1;\n                };\n\n                if (fread(&vchData[0], sizeof(uint8_t), smsg.nPayload, fp) != smsg.nPayload)\n                {\n                    LogPrintf(\"fread data failed: %s\\n\", strerror(errno));\n                    break;\n                };\n\n                // -- don't report to gui,\n                int rv = SecureMsgScanMessage(&smsg.hash[0], &vchData[0], smsg.nPayload, false);\n\n                if (rv == 0)\n                {\n                    nFoundMessages++;\n                } else\n                if (rv != 0)\n                {\n                    // SecureMsgScanMessage failed\n                };\n\n                nMessages++;\n            };\n\n            fclose(fp);\n\n            // -- remove wl file when scanned\n            try {\n                fs::remove((*itd).path());\n            } catch (const boost::filesystem::filesystem_error& ex)\n            {\n                LogPrintf(\"Error removing wl file %s - %s\\n\", fileName.c_str(), ex.what());\n                return 1;\n            };\n        } // cs_smsg\n    };\n\n    LogPrintf(\"Processed %u files, scanned %u messages, received %u messages.\\n\", nFiles, nMessages, nFoundMessages);\n\n    // -- notify gui\n    NotifySecMsgWalletUnlocked();\n    return 0;\n};\n\n\nint SecureMsgWalletKeyChanged(std::string sAddress, std::string sLabel, ChangeType mode)\n{\n    /*\n        SecureMsgWalletKeyChanged():\n        When a key changes in the wallet, this function should be called to update the smsgAddresses vector.\n\n        mode:\n            CT_NEW : a new key was added\n            CT_DELETED : delete an existing key from vector.\n    */\n\n    if (!fSecMsgEnabled)\n        return 0;\n\n    LogPrintf(\"SecureMsgWalletKeyChanged()\\n\");\n\n    // TODO: default recv and recvAnon\n\n    {\n        LOCK(cs_smsg);\n\n        switch(mode)\n        {\n            case CT_NEW:\n                smsgAddresses.push_back(SecMsgAddress(sAddress, smsgOptions.fNewAddressRecv, smsgOptions.fNewAddressAnon));\n                break;\n            case CT_DELETED:\n                for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)\n                {\n                    if (sAddress != it->sAddress)\n                        continue;\n                    smsgAddresses.erase(it);\n                    break;\n                };\n                break;\n            default:\n                break;\n        }\n\n    } // cs_smsg\n\n\n    return 0;\n};\n\nint SecureMsgScanMessage(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, bool reportToGui)\n{\n    /*\n    Check if message belongs to this node.\n    If so add to inbox db.\n\n    if !reportToGui don't fire NotifySecMsgInboxChanged\n     - loads messages received when wallet locked in bulk.\n\n    returns\n        0 success,\n        1 error\n        2 no match\n        3 wallet is locked - message stored for scanning later.\n    */\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgScanMessage()\\n\");\n\n    if (pwalletMain->IsLocked())\n    {\n        if (fDebugSmsg)\n            LogPrintf(\"ScanMessage: Wallet is locked, storing message to scan later.\\n\");\n\n        int rv;\n        if ((rv = SecureMsgStoreUnscanned(pHeader, pPayload, nPayload)) != 0)\n            return 1;\n\n        return 3;\n    };\n\n    std::string addressTo;\n    MessageData msg; // placeholder\n    bool fOwnMessage = false;\n\n    for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)\n    {\n        if (!it->fReceiveEnabled)\n            continue;\n\n        CBitcoinAddress coinAddress(it->sAddress);\n        addressTo = coinAddress.ToString();\n\n        if (!it->fReceiveAnon)\n        {\n            // -- have to do full decrypt to see address from\n            if (SecureMsgDecrypt(false, addressTo, pHeader, pPayload, nPayload, msg) == 0)\n            {\n                if (fDebugSmsg)\n                    LogPrintf(\"Decrypted message with %s.\\n\", addressTo.c_str());\n\n                if (msg.sFromAddress.compare(\"anon\") != 0)\n                    fOwnMessage = true;\n                break;\n            };\n        } else\n        {\n\n            if (SecureMsgDecrypt(true, addressTo, pHeader, pPayload, nPayload, msg) == 0)\n            {\n                if (fDebugSmsg)\n                    LogPrintf(\"Decrypted message with %s.\\n\", addressTo.c_str());\n\n                fOwnMessage = true;\n                break;\n            };\n        }\n    };\n\n    if (fOwnMessage)\n    {\n        // -- save to inbox\n        SecureMessage* psmsg = (SecureMessage*) pHeader;\n        std::string sPrefix(\"im\");\n        uint8_t chKey[18];\n        memcpy(&chKey[0],  sPrefix.data(),    2);\n        memcpy(&chKey[2],  &psmsg->timestamp, 8);\n        memcpy(&chKey[10], pPayload,          8);\n\n        SecMsgStored smsgInbox;\n        smsgInbox.timeReceived  = GetTime();\n        smsgInbox.status        = (SMSG_MASK_UNREAD) & 0xFF;\n        smsgInbox.sAddrTo       = addressTo;\n\n        // -- data may not be contiguous\n        try {\n            smsgInbox.vchMessage.resize(SMSG_HDR_LEN + nPayload);\n        } catch (std::exception& e) {\n            LogPrintf(\"SecureMsgScanMessage(): Could not resize vchData, %u, %s\\n\", SMSG_HDR_LEN + nPayload, e.what());\n            return 1;\n        };\n        memcpy(&smsgInbox.vchMessage[0], pHeader, SMSG_HDR_LEN);\n        memcpy(&smsgInbox.vchMessage[SMSG_HDR_LEN], pPayload, nPayload);\n\n        {\n            LOCK(cs_smsgDB);\n            SecMsgDB dbInbox;\n\n            if (dbInbox.Open(\"cw\"))\n            {\n                if (dbInbox.ExistsSmesg(chKey))\n                {\n                    if (fDebugSmsg)\n                        LogPrintf(\"Message already exists in inbox db.\\n\");\n                } else\n                {\n                    dbInbox.WriteSmesg(chKey, smsgInbox);\n\n                    if (reportToGui)\n                        NotifySecMsgInboxChanged(smsgInbox);\n                    LogPrintf(\"SecureMsg saved to inbox, received with %s.\\n\", addressTo.c_str());\n                };\n            };\n        } // cs_smsgDB\n\n        // notify an external script when a message comes in\n        std::string strCmd = GetArg(\"-smsgnotify\", \"\");\n\n        //TODO: Format message\n        if (!strCmd.empty())\n        {\n            boost::replace_all(strCmd, \"%s\", addressTo);\n            boost::thread t(runCommand, strCmd); // thread runs free\n        };\n\n    };\n\n    return 0;\n};\n\nint SecureMsgGetLocalKey(CKeyID& ckid, CPubKey& cpkOut)\n{\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgGetLocalKey()\\n\");\n\n    if (!pwalletMain->GetPubKey(ckid, cpkOut))\n        return 4;\n\n    if (!cpkOut.IsValid()\n        || !cpkOut.IsCompressed())\n    {\n        LogPrintf(\"Public key is invalid %s.\\n\", HexStr(cpkOut).c_str());\n        return 1;\n    };\n\n    return 0;\n};\n\nint SecureMsgGetLocalPublicKey(std::string& strAddress, std::string& strPublicKey)\n{\n    /* returns\n        0 success,\n        1 error\n        2 invalid address\n        3 address does not refer to a key\n        4 address not in wallet\n    */\n    //if (fDebugSmsg)\n    //   LogPrintf(\"SecureMsgGetLocalPublicKey().\\n\");\n\n    CBitcoinAddress address;\n    if (!address.SetString(strAddress))\n        return 2; // Invalid coin address\n\n    CKeyID keyID;\n    if (!address.GetKeyID(keyID))\n        return 3;\n\n    int rv;\n    CPubKey pubKey;\n    if ((rv = SecureMsgGetLocalKey(keyID, pubKey)) != 0)\n        return rv;\n\n    strPublicKey = EncodeBase58(pubKey.begin(), pubKey.end());\n\n    return 0;\n};\n\nint SecureMsgGetStoredKey(CKeyID& ckid, CPubKey& cpkOut)\n{\n    /* returns\n        0 success,\n        1 error\n        2 public key not in database\n    */\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgGetStoredKey().\\n\");\n\n    {\n        LOCK(cs_smsgDB);\n        SecMsgDB addrpkdb;\n\n        if (!addrpkdb.Open(\"r\"))\n            return 1;\n\n        if (!addrpkdb.ReadPK(ckid, cpkOut))\n        {\n            //LogPrintf(\"addrpkdb.Read failed: %s.\\n\", coinAddress.ToString().c_str());\n            return 2;\n        };\n    } // cs_smsgDB\n\n    return 0;\n};\n\nint SecureMsgAddAddress(std::string& address, std::string& publicKey)\n{\n    /*\n        Add address and matching public key to the database\n        address and publicKey are in base58\n\n        returns\n            0 success\n            1 error\n            2 publicKey is invalid\n            3 publicKey != address\n            4 address is already in db\n            5 address is invalid\n    */\n\n    CBitcoinAddress coinAddress(address);\n\n    if (!coinAddress.IsValid())\n    {\n        LogPrintf(\"%s - Address is not valid: %s.\\n\", __func__, address.c_str());\n        return 5;\n    };\n\n    CKeyID hashKey;\n\n    if (!coinAddress.GetKeyID(hashKey))\n    {\n        LogPrintf(\"%s - coinAddress.GetKeyID failed: %s.\\n\", __func__, coinAddress.ToString().c_str());\n        return 5;\n    };\n\n    std::vector<uint8_t> vchTest;\n    DecodeBase58(publicKey, vchTest);\n    CPubKey pubKey(vchTest);\n\n    // -- check that public key matches address hash\n    CPubKey pubKeyT(pubKey);\n    if (!pubKeyT.IsValid())\n    {\n        LogPrintf(\"%s - Invalid PubKey.\\n\", __func__);\n        return 2;\n    };\n\n    CKeyID keyIDT = pubKeyT.GetID();\n    CBitcoinAddress addressT(keyIDT);\n\n    if (addressT.ToString().compare(address) != 0)\n    {\n        LogPrintf(\"%s - Public key does not hash to address, addressT %s.\\n\", __func__, addressT.ToString().c_str());\n        return 3;\n    };\n\n    return SecureMsgInsertAddress(hashKey, pubKey);\n};\n\nint SecureMsgRetrieve(SecMsgToken &token, std::vector<uint8_t>& vchData)\n{\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgRetrieve() %d.\\n\", token.timestamp);\n\n    // -- has cs_smsg lock from SecureMsgReceiveData\n\n    fs::path pathSmsgDir = GetDataDir() / \"smsgStore\";\n\n    //LogPrintf(\"token.offset %d.\\n\", token.offset); // DEBUG\n    int64_t bucket = token.timestamp - (token.timestamp % SMSG_BUCKET_LEN);\n    std::string fileName = boost::lexical_cast<std::string>(bucket) + \"_01.dat\";\n    fs::path fullpath = pathSmsgDir / fileName;\n\n    //LogPrintf(\"bucket %d.\\n\", bucket);\n    //LogPrintf(\"bucket d %d.\\n\", bucket);\n    //LogPrintf(\"fileName %s.\\n\", fileName.c_str());\n\n    FILE *fp;\n    errno = 0;\n    if (!(fp = fopen(fullpath.string().c_str(), \"rb\")))\n    {\n        LogPrintf(\"Error opening file: %s\\nPath %s\\n\", strerror(errno), fullpath.string().c_str());\n        return 1;\n    };\n\n    errno = 0;\n    if (fseek(fp, token.offset, SEEK_SET) != 0)\n    {\n        LogPrintf(\"fseek, strerror: %s.\\n\", strerror(errno));\n        fclose(fp);\n        return 1;\n    };\n\n    SecureMessage smsg;\n    errno = 0;\n    if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN)\n    {\n        LogPrintf(\"fread header failed: %s\\n\", strerror(errno));\n        fclose(fp);\n        return 1;\n    };\n\n    try {\n        vchData.resize(SMSG_HDR_LEN + smsg.nPayload);\n    } catch (std::exception& e) {\n        LogPrintf(\"SecureMsgRetrieve(): Could not resize vchData, %u, %s\\n\", SMSG_HDR_LEN + smsg.nPayload, e.what());\n        return 1;\n    };\n\n    memcpy(&vchData[0], &smsg.hash[0], SMSG_HDR_LEN);\n    errno = 0;\n    if (fread(&vchData[SMSG_HDR_LEN], sizeof(uint8_t), smsg.nPayload, fp) != smsg.nPayload)\n    {\n        LogPrintf(\"fread data failed: %s. Wanted %u bytes.\\n\", strerror(errno), smsg.nPayload);\n        fclose(fp);\n        return 1;\n    };\n\n\n    fclose(fp);\n\n    return 0;\n};\n\nint SecureMsgReceive(CNode* pfrom, std::vector<uint8_t>& vchData)\n{\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgReceive().\\n\");\n\n    if (vchData.size() < 12) // nBunch4 + timestamp8\n    {\n        LogPrintf(\"Error: not enough data.\\n\");\n        return 1;\n    };\n\n    uint32_t nBunch;\n    int64_t bktTime;\n\n    memcpy(&nBunch, &vchData[0], 4);\n    memcpy(&bktTime, &vchData[4], 8);\n\n\n    // -- check bktTime ()\n    //    bucket may not exist yet - will be created when messages are added\n    int64_t now = GetTime();\n    if (bktTime > now + SMSG_TIME_LEEWAY)\n    {\n        if (fDebugSmsg)\n            LogPrintf(\"bktTime > now.\\n\");\n        // misbehave?\n        return 1;\n    } else\n    if (bktTime < now - SMSG_RETENTION)\n    {\n        if (fDebugSmsg)\n            LogPrintf(\"bktTime < now - SMSG_RETENTION.\\n\");\n        // misbehave?\n        return 1;\n    };\n\n    std::map<int64_t, SecMsgBucket>::iterator itb;\n\n    if (nBunch == 0 || nBunch > 500)\n    {\n        LogPrintf(\"Error: Invalid no. messages received in bunch %u, for bucket %d.\\n\", nBunch, bktTime);\n        pfrom->Misbehaving(1);\n\n        {\n            LOCK(cs_smsg);\n            // -- release lock on bucket if it exists\n            itb = smsgBuckets.find(bktTime);\n            if (itb != smsgBuckets.end())\n                itb->second.nLockCount = 0;\n        } // cs_smsg\n        return 1;\n    };\n\n    uint32_t n = 12;\n\n    for (uint32_t i = 0; i < nBunch; ++i)\n    {\n        if (vchData.size() - n < SMSG_HDR_LEN)\n        {\n            LogPrintf(\"Error: not enough data sent, n = %u.\\n\", n);\n            break;\n        };\n\n        SecureMessage *psmsg = (SecureMessage*) &vchData[n];\n\n        int rv;\n        if ((rv = SecureMsgValidate(&vchData[n], &vchData[n + SMSG_HDR_LEN], psmsg->nPayload)) != 0)\n        {\n            // message dropped\n            if (rv == 2) // invalid proof of work\n            {\n                pfrom->Misbehaving(10);\n            } else\n            {\n                pfrom->Misbehaving(1);\n            };\n            continue;\n        };\n\n        {\n            LOCK(cs_smsg);\n            // -- store message, but don't hash bucket\n            if (SecureMsgStore(&vchData[n], &vchData[n + SMSG_HDR_LEN], psmsg->nPayload, false) != 0)\n            {\n                // message dropped\n                break; // continue?\n            };\n\n            if (SecureMsgScanMessage(&vchData[n], &vchData[n + SMSG_HDR_LEN], psmsg->nPayload, true) != 0)\n            {\n                // message recipient is not this node (or failed)\n            };\n        } // cs_smsg\n\n        n += SMSG_HDR_LEN + psmsg->nPayload;\n    };\n\n    {\n        LOCK(cs_smsg);\n        // -- if messages have been added, bucket must exist now\n        itb = smsgBuckets.find(bktTime);\n        if (itb == smsgBuckets.end())\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"Don't have bucket %d.\\n\", bktTime);\n            return 1;\n        };\n\n        itb->second.nLockCount  = 0; // this node has received data from peer, release lock\n        itb->second.nLockPeerId = 0;\n        itb->second.hashBucket();\n    } // cs_smsg\n    return 0;\n};\n\nint SecureMsgStoreUnscanned(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload)\n{\n    /*\n    When the wallet is locked a copy of each received message is stored to be scanned later if wallet is unlocked\n    */\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgStoreUnscanned()\\n\");\n\n    if (!pHeader\n        || !pPayload)\n    {\n        LogPrintf(\"Error: null pointer to header or payload.\\n\");\n        return 1;\n    };\n\n    SecureMessage* psmsg = (SecureMessage*) pHeader;\n\n    fs::path pathSmsgDir;\n    try {\n        pathSmsgDir = GetDataDir() / \"smsgStore\";\n        fs::create_directory(pathSmsgDir);\n    } catch (const boost::filesystem::filesystem_error& ex)\n    {\n        LogPrintf(\"Error: Failed to create directory %s - %s\\n\", pathSmsgDir.string().c_str(), ex.what());\n        return 1;\n    };\n\n    int64_t now = GetTime();\n    if (psmsg->timestamp > now + SMSG_TIME_LEEWAY)\n    {\n        LogPrintf(\"Message > now.\\n\");\n        return 1;\n    } else\n    if (psmsg->timestamp < now - SMSG_RETENTION)\n    {\n        LogPrintf(\"Message < SMSG_RETENTION.\\n\");\n        return 1;\n    };\n\n    int64_t bucket = psmsg->timestamp - (psmsg->timestamp % SMSG_BUCKET_LEN);\n\n    std::string fileName = boost::lexical_cast<std::string>(bucket) + \"_01_wl.dat\";\n    fs::path fullpath = pathSmsgDir / fileName;\n\n    FILE *fp;\n    errno = 0;\n    if (!(fp = fopen(fullpath.string().c_str(), \"ab\")))\n    {\n        LogPrintf(\"Error opening file: %s\\n\", strerror(errno));\n        return 1;\n    };\n\n    if (fwrite(pHeader, sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN\n        || fwrite(pPayload, sizeof(uint8_t), nPayload, fp) != nPayload)\n    {\n        LogPrintf(\"fwrite failed: %s\\n\", strerror(errno));\n        fclose(fp);\n        return 1;\n    };\n\n    fclose(fp);\n\n    return 0;\n};\n\n\nint SecureMsgStore(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, bool fUpdateBucket)\n{\n    if (fDebugSmsg)\n    {\n        LogPrintf(\"SecureMsgStore()\\n\");\n        AssertLockHeld(cs_smsg);\n    };\n\n\n    if (!pHeader\n        || !pPayload)\n    {\n        return errorN(1, \"null pointer to header or payload.\");\n    };\n\n    SecureMessage* psmsg = (SecureMessage*) pHeader;\n\n\n    long int ofs;\n    fs::path pathSmsgDir;\n    try {\n        pathSmsgDir = GetDataDir() / \"smsgStore\";\n        fs::create_directory(pathSmsgDir);\n    } catch (const boost::filesystem::filesystem_error& ex)\n    {\n        return errorN(1, \"Failed to create directory %s - %s.\", pathSmsgDir.string().c_str(), ex.what());\n    };\n\n    int64_t now = GetTime();\n    if (psmsg->timestamp > now + SMSG_TIME_LEEWAY)\n    {\n        LogPrintf(\"Message > now.\\n\");\n        return 1;\n    } else\n    if (psmsg->timestamp < now - SMSG_RETENTION)\n    {\n        LogPrintf(\"Message < SMSG_RETENTION.\\n\");\n        return 1;\n    };\n\n    int64_t bucket = psmsg->timestamp - (psmsg->timestamp % SMSG_BUCKET_LEN);\n\n    SecMsgToken token(psmsg->timestamp, pPayload, nPayload, 0);\n\n    std::set<SecMsgToken>& tokenSet = smsgBuckets[bucket].setTokens;\n    std::set<SecMsgToken>::iterator it;\n    it = tokenSet.find(token);\n    if (it != tokenSet.end())\n    {\n        LogPrintf(\"Already have message.\\n\");\n        if (fDebugSmsg)\n        {\n            LogPrintf(\"nPayload: %u\\n\", nPayload);\n            LogPrintf(\"bucket: %d\\n\", bucket);\n\n            LogPrintf(\"message ts: %d\", token.timestamp);\n            std::vector<uint8_t> vchShow;\n            vchShow.resize(8);\n            memcpy(&vchShow[0], token.sample, 8);\n            LogPrintf(\" sample %s\\n\", ValueString(vchShow).c_str());\n            /*\n            LogPrintf(\"\\nmessages in bucket:\\n\");\n            for (it = tokenSet.begin(); it != tokenSet.end(); ++it)\n            {\n                LogPrintf(\"message ts: %d\", (*it).timestamp);\n                vchShow.resize(8);\n                memcpy(&vchShow[0], (*it).sample, 8);\n                LogPrintf(\" sample %s\\n\", ValueString(vchShow).c_str());\n            };\n            */\n        };\n        return 1;\n    };\n\n    std::string fileName = boost::lexical_cast<std::string>(bucket) + \"_01.dat\";\n    fs::path fullpath = pathSmsgDir / fileName;\n\n    FILE *fp;\n    errno = 0;\n    if (!(fp = fopen(fullpath.string().c_str(), \"ab\")))\n    {\n        return errorN(1, \"fopen failed: %s.\", strerror(errno));\n    };\n\n    // -- on windows ftell will always return 0 after fopen(ab), call fseek to set.\n    errno = 0;\n    if (fseek(fp, 0, SEEK_END) != 0)\n        return errorN(1, \"fseek failed: %s.\", strerror(errno));\n\n    ofs = ftell(fp);\n\n    if (fwrite(pHeader,  sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN\n     || fwrite(pPayload, sizeof(uint8_t),     nPayload, fp) != nPayload)\n    {\n        fclose(fp);\n        return errorN(1, \"fwrite failed: %s.\", strerror(errno));\n    };\n\n    fclose(fp);\n\n    token.offset = ofs;\n\n    //LogPrintf(\"token.offset: %d\\n\", token.offset); // DEBUG\n    tokenSet.insert(token);\n\n    if (fUpdateBucket)\n        smsgBuckets[bucket].hashBucket();\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsg added to bucket %d.\\n\", bucket);\n\n    return 0;\n};\n\nint SecureMsgStore(SecureMessage& smsg, bool fUpdateBucket)\n{\n    return SecureMsgStore(&smsg.hash[0], smsg.pPayload, smsg.nPayload, fUpdateBucket);\n};\n\nint SecureMsgValidate(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload)\n{\n    /*\n    returns\n        0 success\n        1 error\n        2 invalid hash\n        3 checksum mismatch\n        4 invalid version\n        5 payload is too large\n    */\n    SecureMessage *psmsg = (SecureMessage*) pHeader;\n\n    if (psmsg->version[0] != 1)\n        return 4;\n\n    if (nPayload > SMSG_MAX_MSG_WORST)\n        return 5;\n\n    uint8_t civ[32];\n    uint8_t sha256Hash[32];\n    int rv = 2; // invalid\n\n    uint32_t nonce;\n    memcpy(&nonce, &psmsg->nonce[0], 4);\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgValidate() nonce %u.\\n\", nonce);\n\n    for (int i = 0; i < 32; i+=4)\n        memcpy(civ+i, &nonce, 4);\n\n    HMAC_CTX ctx;\n    HMAC_CTX_init(&ctx);\n\n    uint32_t nBytes;\n    if (!HMAC_Init_ex(&ctx, &civ[0], 32, EVP_sha256(), NULL)\n        || !HMAC_Update(&ctx, (uint8_t*) pHeader+4, SMSG_HDR_LEN-4)\n        || !HMAC_Update(&ctx, (uint8_t*) pPayload, nPayload)\n        || !HMAC_Update(&ctx, pPayload, nPayload)\n        || !HMAC_Final(&ctx, sha256Hash, &nBytes)\n        || nBytes != 32)\n    {\n        if (fDebugSmsg)\n            LogPrintf(\"HMAC error.\\n\");\n        rv = 1; // error\n    } else\n    {\n        if (sha256Hash[31] == 0\n            && sha256Hash[30] == 0\n            && (~(sha256Hash[29]) & ((1<<0) | (1<<1) | (1<<2)) ))\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"Hash Valid.\\n\");\n            rv = 0; // smsg is valid\n        };\n\n        if (edu::memcmp_nta(psmsg->hash, sha256Hash, 4) != 0)\n        {\n             if (fDebugSmsg)\n                LogPrintf(\"Checksum mismatch.\\n\");\n            rv = 3; // checksum mismatch\n        }\n    }\n    HMAC_CTX_cleanup(&ctx);\n\n    return rv;\n};\n\nint SecureMsgSetHash(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload)\n{\n    /*  proof of work and checksum\n\n        May run in a thread, if shutdown detected, return.\n\n        returns:\n            0 success\n            1 error\n            2 stopped due to node shutdown\n\n    */\n\n    SecureMessage* psmsg = (SecureMessage*) pHeader;\n\n    int64_t nStart = GetTimeMillis();\n    uint8_t civ[32];\n    uint8_t sha256Hash[32];\n\n    bool found = false;\n    HMAC_CTX ctx;\n    HMAC_CTX_init(&ctx);\n\n    uint32_t nonce = 0;\n\n    //CBigNum bnTarget(2);\n    //bnTarget = bnTarget.pow(256 - 40);\n\n    // -- break for HMAC_CTX_cleanup\n    for (;;)\n    {\n        if (!fSecMsgEnabled)\n           break;\n\n        //psmsg->timestamp = GetTime();\n        //memcpy(&psmsg->timestamp, &now, 8);\n        memcpy(&psmsg->nonce[0], &nonce, 4);\n\n        for (int i = 0; i < 32; i+=4)\n            memcpy(civ+i, &nonce, 4);\n\n        uint32_t nBytes;\n        if (!HMAC_Init_ex(&ctx, &civ[0], 32, EVP_sha256(), NULL)\n            || !HMAC_Update(&ctx, (uint8_t*) pHeader+4, SMSG_HDR_LEN-4)\n            || !HMAC_Update(&ctx, (uint8_t*) pPayload, nPayload)\n            || !HMAC_Update(&ctx, pPayload, nPayload)\n            || !HMAC_Final(&ctx, sha256Hash, &nBytes)\n            //|| !HMAC_Final(&ctx, &vchHash[0], &nBytes)\n            || nBytes != 32)\n            break;\n\n        /*\n        if (CBigNum(vchHash) <= bnTarget)\n        {\n            found = true;\n            if (fDebugSmsg)\n                LogPrintf(\"Match %u\\n\", nonce);\n            break;\n        };\n        */\n\n        if (sha256Hash[31] == 0\n            && sha256Hash[30] == 0\n            && (~(sha256Hash[29]) & ((1<<0) | (1<<1) | (1<<2)) ))\n        //    && sha256Hash[29] == 0)\n        {\n            found = true;\n            //if (fDebugSmsg)\n            //    LogPrintf(\"Match %u\\n\", nonce);\n            break;\n        }\n\n        //if (nonce >= UINT32_MAX)\n        if (nonce >= 4294967295U)\n        {\n            if (fDebugSmsg)\n                LogPrintf(\"No match %u\\n\", nonce);\n            break;\n            //return 1;\n        }\n        nonce++;\n    };\n\n    HMAC_CTX_cleanup(&ctx);\n\n    if (!fSecMsgEnabled)\n    {\n        if (fDebugSmsg)\n            LogPrintf(\"SecureMsgSetHash() stopped, shutdown detected.\\n\");\n        return 2;\n    };\n\n    if (!found)\n    {\n        if (fDebugSmsg)\n            LogPrintf(\"SecureMsgSetHash() failed, took %d ms, nonce %u\\n\", GetTimeMillis() - nStart, nonce);\n        return 1;\n    };\n\n    memcpy(psmsg->hash, sha256Hash, 4);\n    //memcpy(psmsg->hash, &vchHash[0], 4);\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgSetHash() took %d ms, nonce %u\\n\", GetTimeMillis() - nStart, nonce);\n\n    return 0;\n};\n\nint SecureMsgEncrypt(SecureMessage &smsg, const std::string &addressFrom, const std::string &addressTo, const std::string &message)\n{\n    /* Create a secure message\n\n        Using similar method to bitmessage.\n        If bitmessage is secure this should be too.\n        https://bitmessage.org/wiki/Encryption\n\n        Some differences:\n        bitmessage seems to use curve sect283r1\n        *coin addresses use secp256k1\n\n        returns\n            2       message is too long.\n            3       addressFrom is invalid.\n            4       addressTo is invalid.\n            5       Could not get public key for addressTo.\n            6       ECDH_compute_key failed\n            7       Could not get private key for addressFrom.\n            8       Could not allocate memory.\n            9       Could not compress message data.\n            10      Could not generate MAC.\n            11      Encrypt failed.\n    */\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgEncrypt(%s, %s, ...)\\n\", addressFrom.c_str(), addressTo.c_str());\n\n    bool fSendAnonymous = (addressFrom.compare(\"anon\") == 0);\n\n\n    if (message.size() > (fSendAnonymous ? SMSG_MAX_AMSG_BYTES : SMSG_MAX_MSG_BYTES))\n    {\n        return errorN(2, \"%s: Message is too long, %u.\", __func__, message.size());\n    };\n\n    smsg.version[0] = 1;\n    smsg.version[1] = 1;\n    smsg.timestamp = GetTime();\n\n    CBitcoinAddress coinAddrFrom;\n    CKeyID ckidFrom;\n    CKey keyFrom;\n\n\n    if(!fSendAnonymous)\n    {\n        if (!coinAddrFrom.SetString(addressFrom))\n        {\n            return errorN(3, \"%s: addressFrom is not valid.\", __func__);\n        };\n\n        if (!coinAddrFrom.GetKeyID(ckidFrom))\n        {\n            return errorN(4, \"%s: coinAddrFrom.GetKeyID failed: %s.\", __func__, coinAddrFrom.ToString().c_str());\n        };\n    };\n\n\n    CBitcoinAddress coinAddrDest;\n    CKeyID ckidDest;\n\n    if (!coinAddrDest.SetString(addressTo))\n    {\n        return errorN(4, \"%s: addressTo is not valid.\", __func__);\n    };\n\n    if (!coinAddrDest.GetKeyID(ckidDest))\n    {\n        return errorN(4, \"%s: coinAddrDest.GetKeyID failed: %s.\", __func__, coinAddrDest.ToString().c_str());\n    };\n\n    // -- public key K is the destination address\n    CPubKey cpkDestK;\n    if (SecureMsgGetStoredKey(ckidDest, cpkDestK) != 0\n        && SecureMsgGetLocalKey(ckidDest, cpkDestK) != 0) // maybe it's a local key (outbox?)\n    {\n        return errorN(5, \"%s: Could not get public key for destination address.\", __func__);\n    };\n\n\n    // -- Generate 16 random bytes as IV.\n    RandAddSeedPerfmon();\n    RAND_bytes(&smsg.iv[0], 16);\n\n\n    // -- Generate a new random EC key pair with private key called r and public key called R.\n    CKey keyR;\n    keyR.MakeNewKey(true); // make compressed key\n\n    CECKey ecKeyR;\n    ecKeyR.SetSecretBytes(keyR.begin());\n\n    // -- Do an EC point multiply with public key K and private key r. This gives you public key P.\n    CECKey ecKeyK;\n    if (!ecKeyK.SetPubKey(cpkDestK))\n    {\n        // address to is invalid\n        return errorN(4, \"%s: Could not set pubkey for K: %s.\", __func__, HexStr(cpkDestK).c_str());\n    };\n\n    std::vector<uint8_t> vchP;\n    vchP.resize(32);\n    EC_KEY *pkeyr = ecKeyR.GetECKey();\n    EC_KEY *pkeyK = ecKeyK.GetECKey();\n\n    // always seems to be 32, worth checking?\n    //int field_size = EC_GROUP_get_degree(EC_KEY_get0_group(pkeyr));\n    //int secret_len = (field_size+7)/8;\n    //LogPrintf(\"secret_len %d.\\n\", secret_len);\n\n    // -- ECDH_compute_key returns the same P if fed compressed or uncompressed public keys\n    ECDH_set_method(pkeyr, ECDH_OpenSSL());\n    int lenP = ECDH_compute_key(&vchP[0], 32, EC_KEY_get0_public_key(pkeyK), pkeyr, NULL);\n\n    if (lenP != 32)\n    {\n        return errorN(6, \"%s: ECDH_compute_key failed, lenP: %d.\", __func__, lenP);\n    };\n\n    CPubKey cpkR = keyR.GetPubKey();\n    if (!cpkR.IsValid()\n        || !cpkR.IsCompressed())\n    {\n        return errorN(1, \"%s: Could not get public key for key R.\", __func__);\n    };\n\n    memcpy(smsg.cpkR, cpkR.begin(), 33);\n\n\n    // -- Use public key P and calculate the SHA512 hash H.\n    //    The first 32 bytes of H are called key_e and the last 32 bytes are called key_m.\n    std::vector<uint8_t> vchHashed;\n    vchHashed.resize(64); // 512\n    SHA512(&vchP[0], vchP.size(), (uint8_t*)&vchHashed[0]);\n    std::vector<uint8_t> key_e(&vchHashed[0], &vchHashed[0]+32);\n    std::vector<uint8_t> key_m(&vchHashed[32], &vchHashed[32]+32);\n\n\n    std::vector<uint8_t> vchPayload;\n    std::vector<uint8_t> vchCompressed;\n    uint8_t *pMsgData;\n    uint32_t lenMsgData;\n\n    uint32_t lenMsg = message.size();\n    if (lenMsg > 128)\n    {\n        // -- only compress if over 128 bytes\n        int worstCase = LZ4_compressBound(message.size());\n        try { vchCompressed.resize(worstCase); } catch (std::exception& e)\n        {\n            return errorN(8, \"%s: vchCompressed.resize %u threw: %s.\", __func__, worstCase, e.what());\n        };\n\n        int lenComp = LZ4_compress((char*)message.c_str(), (char*)&vchCompressed[0], lenMsg);\n        if (lenComp < 1)\n        {\n            return errorN(9, \"%s: Could not compress message data.\", __func__);\n        };\n\n        pMsgData = &vchCompressed[0];\n        lenMsgData = lenComp;\n\n    } else\n    {\n        // -- no compression\n        pMsgData = (uint8_t*)message.c_str();\n        lenMsgData = lenMsg;\n    };\n\n    if (fSendAnonymous)\n    {\n        try { vchPayload.resize(9 + lenMsgData); } catch (std::exception& e)\n        {\n            return errorN(8, \"%s: vchPayload.resize %u threw: %s.\", __func__, 9 + lenMsgData, e.what());\n        };\n\n        memcpy(&vchPayload[9], pMsgData, lenMsgData);\n\n        vchPayload[0] = 250; // id as anonymous message\n        // -- next 4 bytes are unused - there to ensure encrypted payload always > 8 bytes\n        memcpy(&vchPayload[5], &lenMsg, 4); // length of uncompressed plain text\n    } else\n    {\n        try { vchPayload.resize(SMSG_PL_HDR_LEN + lenMsgData); } catch (std::exception& e)\n        {\n            return errorN(8, \"%s: vchPayload.resize %u threw: %s.\", __func__, SMSG_PL_HDR_LEN + lenMsgData, e.what());\n        };\n\n        memcpy(&vchPayload[SMSG_PL_HDR_LEN], pMsgData, lenMsgData);\n        // -- compact signature proves ownership of from address and allows the public key to be recovered, recipient can always reply.\n        if (!pwalletMain->GetKey(ckidFrom, keyFrom))\n        {\n            return errorN(7, \"%s: Could not get private key for addressFrom.\", __func__);\n        };\n\n        // -- sign the plaintext\n        std::vector<uint8_t> vchSignature;\n        vchSignature.resize(65);\n        keyFrom.SignCompact(Hash(message.begin(), message.end()), vchSignature);\n\n        // -- Save some bytes by sending address raw\n        vchPayload[0] = (static_cast<CBitcoinAddress_B*>(&coinAddrFrom))->getVersion(); // vchPayload[0] = coinAddrDest.nVersion;\n        memcpy(&vchPayload[1], (static_cast<CKeyID_B*>(&ckidFrom))->GetPPN(), 20); // memcpy(&vchPayload[1], ckidDest.pn, 20);\n\n        memcpy(&vchPayload[1+20], &vchSignature[0], vchSignature.size());\n        memcpy(&vchPayload[1+20+65], &lenMsg, 4); // length of uncompressed plain text\n    };\n\n\n    SecMsgCrypter crypter;\n    crypter.SetKey(key_e, smsg.iv);\n    std::vector<uint8_t> vchCiphertext;\n\n    if (!crypter.Encrypt(&vchPayload[0], vchPayload.size(), vchCiphertext))\n    {\n        return errorN(11, \"%s: crypter.Encrypt failed.\", __func__);\n    };\n\n    try { smsg.pPayload = new uint8_t[vchCiphertext.size()]; } catch (std::exception& e)\n    {\n        return errorN(8, \"%s: Could not allocate pPayload, exception: %s.\", __func__, e.what());\n    };\n\n    memcpy(smsg.pPayload, &vchCiphertext[0], vchCiphertext.size());\n    smsg.nPayload = vchCiphertext.size();\n\n\n    // -- Calculate a 32 byte MAC with HMACSHA256, using key_m as salt\n    //    Message authentication code, (hash of timestamp + destination + payload)\n    bool fHmacOk = true;\n    uint32_t nBytes = 32;\n    HMAC_CTX ctx;\n    HMAC_CTX_init(&ctx);\n\n    if (!HMAC_Init_ex(&ctx, &key_m[0], 32, EVP_sha256(), NULL)\n        || !HMAC_Update(&ctx, (uint8_t*) &smsg.timestamp, sizeof(smsg.timestamp))\n        || !HMAC_Update(&ctx, &vchCiphertext[0], vchCiphertext.size())\n        || !HMAC_Final(&ctx, smsg.mac, &nBytes)\n        || nBytes != 32)\n        fHmacOk = false;\n\n    HMAC_CTX_cleanup(&ctx);\n\n    if (!fHmacOk)\n    {\n        return errorN(10, \"%s: Could not generate MAC.\", __func__);\n    };\n\n    return 0;\n};\n\nint SecureMsgSend(std::string &addressFrom, std::string &addressTo, std::string &message, std::string &sError)\n{\n    /* Encrypt secure message, and place it on the network\n        Make a copy of the message to sender's first address and place in send queue db\n        proof of work thread will pick up messages from  send queue db\n    */\n\n    if (fDebugSmsg)\n        LogPrintf(\"SecureMsgSend(%s, %s, ...)\\n\", addressFrom.c_str(), addressTo.c_str());\n\n    if (pwalletMain->IsLocked())\n    {\n        sError = \"Wallet is locked, wallet must be unlocked to send and recieve messages.\";\n        LogPrintf(\"%s\\n\", sError);\n        return 1;\n    };\n\n    bool fSendAnonymous = (addressFrom.compare(\"anon\") == 0);\n\n    if (message.size() > (fSendAnonymous ? SMSG_MAX_AMSG_BYTES : SMSG_MAX_MSG_BYTES))\n    {\n        std::ostringstream oss;\n        oss << message.size() << \" > \" << (fSendAnonymous ? SMSG_MAX_AMSG_BYTES : SMSG_MAX_MSG_BYTES);\n        sError = \"Message is too long, \" + oss.str();\n        LogPrintf(\"Message is too long, %u.\\n\", message.size());\n        return 1;\n    };\n\n    int rv;\n    SecureMessage smsg;\n\n    if ((rv = SecureMsgEncrypt(smsg, addressFrom, addressTo, message)) != 0)\n    {\n        LogPrintf(\"SecureMsgSend(), encrypt for recipient failed.\\n\");\n\n        switch(rv)\n        {\n            case 2:  sError = \"Message is too long.\";                       break;\n            case 3:  sError = \"Invalid addressFrom.\";                       break;\n            case 4:  sError = \"Invalid addressTo.\";                         break;\n            case 5:  sError = \"Could not get public key for addressTo.\";    break;\n            case 6:  sError = \"ECDH_compute_key failed.\";                   break;\n            case 7:  sError = \"Could not get private key for addressFrom.\"; break;\n            case 8:  sError = \"Could not allocate memory.\";                 break;\n            case 9:  sError = \"Could not compress message data.\";           break;\n            case 10: sError = \"Could not generate MAC.\";                    break;\n            case 11: sError = \"Encrypt failed.\";                            break;\n            default: sError = \"Unspecified Error.\";                         break;\n        };\n\n        return rv;\n    };\n\n\n    // -- Place message in send queue, proof of work will happen in a thread.\n    std::string sPrefix(\"qm\");\n    uint8_t chKey[18];\n    memcpy(&chKey[0],  sPrefix.data(),  2);\n    memcpy(&chKey[2],  &smsg.timestamp, 8);\n    memcpy(&chKey[10], &smsg.pPayload,  8);\n\n    SecMsgStored smsgSQ;\n\n    smsgSQ.timeReceived  = GetTime();\n    smsgSQ.sAddrTo       = addressTo;\n\n    try { smsgSQ.vchMessage.resize(SMSG_HDR_LEN + smsg.nPayload); } catch (std::exception& e)\n    {\n        LogPrintf(\"smsgSQ.vchMessage.resize %u threw: %s.\\n\", SMSG_HDR_LEN + smsg.nPayload, e.what());\n        sError = \"Could not allocate memory.\";\n        return 8;\n    };\n\n    memcpy(&smsgSQ.vchMessage[0], &smsg.hash[0], SMSG_HDR_LEN);\n    memcpy(&smsgSQ.vchMessage[SMSG_HDR_LEN], smsg.pPayload, smsg.nPayload);\n\n    {\n        LOCK(cs_smsgDB);\n        SecMsgDB dbSendQueue;\n        if (dbSendQueue.Open(\"cw\"))\n        {\n            dbSendQueue.WriteSmesg(chKey, smsgSQ);\n            //NotifySecMsgSendQueueChanged(smsgOutbox);\n        };\n    } // cs_smsgDB\n\n    // TODO: only update outbox when proof of work thread is done.\n\n    //  -- for outbox create a copy encrypted for owned address\n    //     if the wallet is encrypted private key needed to decrypt will be unavailable\n\n    if (fDebugSmsg)\n        LogPrintf(\"Encrypting message for outbox.\\n\");\n\n    std::string addressOutbox = \"None\";\n    CBitcoinAddress coinAddrOutbox;\n\n    BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook)\n    {\n        // -- get first owned address\n        if (!IsDestMine(*pwalletMain, entry.first))\n            continue;\n\n        const CBitcoinAddress& address = entry.first;\n\n        addressOutbox = address.ToString();\n        if (!coinAddrOutbox.SetString(addressOutbox)) // test valid\n            continue;\n        break;\n    };\n\n    if (addressOutbox == \"None\")\n    {\n        LogPrintf(\"Warning: SecureMsgSend() could not find an address to encrypt outbox message with.\\n\");\n    } else\n    {\n        if (fDebugSmsg)\n            LogPrintf(\"Encrypting a copy for outbox, using address %s\\n\", addressOutbox.c_str());\n\n        SecureMessage smsgForOutbox;\n        if ((rv = SecureMsgEncrypt(smsgForOutbox, addressFrom, addressOutbox, message)) != 0)\n        {\n            LogPrintf(\"SecureMsgSend(), encrypt for outbox failed, %d.\\n\", rv);\n        } else\n        {\n            // -- save sent message to db\n            std::string sPrefix(\"sm\");\n            uint8_t chKey[18];\n            memcpy(&chKey[0],  sPrefix.data(),           2);\n            memcpy(&chKey[2],  &smsgForOutbox.timestamp, 8);\n            memcpy(&chKey[10], &smsgForOutbox.pPayload,  8);   // sample\n\n            SecMsgStored smsgOutbox;\n\n            smsgOutbox.timeReceived  = GetTime();\n            smsgOutbox.sAddrTo       = addressTo;\n            smsgOutbox.sAddrOutbox   = addressOutbox;\n\n            try {\n                smsgOutbox.vchMessage.resize(SMSG_HDR_LEN + smsgForOutbox.nPayload);\n            } catch (std::exception& e) {\n                LogPrintf(\"smsgOutbox.vchMessage.resize %u threw: %s.\\n\", SMSG_HDR_LEN + smsgForOutbox.nPayload, e.what());\n                sError = \"Could not allocate memory.\";\n                return 8;\n            };\n            memcpy(&smsgOutbox.vchMessage[0], &smsgForOutbox.hash[0], SMSG_HDR_LEN);\n            memcpy(&smsgOutbox.vchMessage[SMSG_HDR_LEN], smsgForOutbox.pPayload, smsgForOutbox.nPayload);\n\n\n            {\n                LOCK(cs_smsgDB);\n                SecMsgDB dbSent;\n\n                if (dbSent.Open(\"cw\"))\n                {\n                    dbSent.WriteSmesg(chKey, smsgOutbox);\n                    NotifySecMsgOutboxChanged(smsgOutbox);\n                };\n            } // cs_smsgDB\n        };\n    };\n\n    if (fDebugSmsg)\n        LogPrintf(\"Secure message queued for sending to %s.\\n\", addressTo.c_str());\n\n    return 0;\n};\n\n\nint SecureMsgDecrypt(bool fTestOnly, std::string &address, uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, MessageData &msg)\n{\n    /* Decrypt secure message\n\n        address is the owned address to decrypt with.\n\n        validate first in SecureMsgValidate\n\n        returns\n            1       Error\n            2       Unknown version number\n            3       Decrypt address is not valid.\n            8       Could not allocate memory\n    */\n\n    if (fDebugSmsg)\n        LogPrintf(\"%s: using %s, testonly %d.\\n\", __func__, address.c_str(), fTestOnly);\n\n    if (!pHeader\n        || !pPayload)\n    {\n        return errorN(1, \"%s: null pointer to header or payload.\", __func__);\n    };\n\n    SecureMessage* psmsg = (SecureMessage*) pHeader;\n\n\n    if (psmsg->version[0] != 1)\n    {\n        return errorN(2, \"%s: Unknown version number.\", __func__);\n    };\n\n\n\n    // -- Fetch private key k, used to decrypt\n    CBitcoinAddress coinAddrDest;\n    CKeyID ckidDest;\n    CKey keyDest;\n    if (!coinAddrDest.SetString(address))\n    {\n        return errorN(3, \"%s: Address is not valid.\", __func__);\n    };\n    if (!coinAddrDest.GetKeyID(ckidDest))\n    {\n        return errorN(3, \"%s: coinAddrDest.GetKeyID failed: %s.\", __func__, coinAddrDest.ToString().c_str());\n    };\n    if (!pwalletMain->GetKey(ckidDest, keyDest))\n    {\n        return errorN(3, \"%s: Could not get private key for addressDest.\", __func__);\n    };\n\n\n\n    CPubKey cpkR(psmsg->cpkR, psmsg->cpkR+33);\n    if (!cpkR.IsValid())\n    {\n        return errorN(1, \"%s: Could not get pubkey for key R.\", __func__);\n    };\n\n    CECKey ecKeyR;\n    if (!ecKeyR.SetPubKey(cpkR))\n    {\n        return errorN(1, \"%s: Could not set pubkey for key R: %s.\", __func__, HexStr(cpkR).c_str());\n    };\n\n    CECKey ecKeyDest;\n    ecKeyDest.SetSecretBytes(keyDest.begin());\n\n    // -- Do an EC point multiply with private key k and public key R. This gives you public key P.\n    std::vector<uint8_t> vchP;\n    vchP.resize(32);\n    EC_KEY* pkeyk = ecKeyDest.GetECKey();\n    EC_KEY* pkeyR = ecKeyR.GetECKey();\n\n    ECDH_set_method(pkeyk, ECDH_OpenSSL());\n    int lenPdec = ECDH_compute_key(&vchP[0], 32, EC_KEY_get0_public_key(pkeyR), pkeyk, NULL);\n\n    if (lenPdec != 32)\n    {\n        return errorN(1, \"%s: ECDH_compute_key failed, lenPdec: %d.\", __func__, lenPdec);\n    };\n\n\n    // -- Use public key P to calculate the SHA512 hash H.\n    //    The first 32 bytes of H are called key_e and the last 32 bytes are called key_m.\n    std::vector<uint8_t> vchHashedDec;\n    vchHashedDec.resize(64);    // 512 bits\n    SHA512(&vchP[0], vchP.size(), (uint8_t*)&vchHashedDec[0]);\n    std::vector<uint8_t> key_e(&vchHashedDec[0], &vchHashedDec[0]+32);\n    std::vector<uint8_t> key_m(&vchHashedDec[32], &vchHashedDec[32]+32);\n\n\n    // -- Message authentication code, (hash of timestamp + destination + payload)\n    uint8_t MAC[32];\n    bool fHmacOk = true;\n    uint32_t nBytes = 32;\n    HMAC_CTX ctx;\n    HMAC_CTX_init(&ctx);\n\n    if (!HMAC_Init_ex(&ctx, &key_m[0], 32, EVP_sha256(), NULL)\n        || !HMAC_Update(&ctx, (uint8_t*) &psmsg->timestamp, sizeof(psmsg->timestamp))\n        || !HMAC_Update(&ctx, pPayload, nPayload)\n        || !HMAC_Final(&ctx, MAC, &nBytes)\n        || nBytes != 32)\n        fHmacOk = false;\n\n    HMAC_CTX_cleanup(&ctx);\n\n    if (!fHmacOk)\n    {\n        return errorN(1, \"%s: Could not generate MAC.\", __func__);\n    };\n\n    if (edu::memcmp_nta(MAC, psmsg->mac, 32) != 0)\n    {\n        if (fDebugSmsg)\n            LogPrintf(\"MAC does not match.\\n\"); // expected if message is not to address on node\n\n        return 1;\n    };\n\n    if (fTestOnly)\n        return 0;\n\n    SecMsgCrypter crypter;\n    crypter.SetKey(key_e, psmsg->iv);\n    std::vector<uint8_t> vchPayload;\n    if (!crypter.Decrypt(pPayload, nPayload, vchPayload))\n    {\n        return errorN(1, \"%s: Decrypt failed.\", __func__);\n    };\n\n    msg.timestamp = psmsg->timestamp;\n    uint32_t lenData;\n    uint32_t lenPlain;\n\n    uint8_t* pMsgData;\n    bool fFromAnonymous;\n    if ((uint32_t)vchPayload[0] == 250)\n    {\n        fFromAnonymous = true;\n        lenData = vchPayload.size() - (9);\n        memcpy(&lenPlain, &vchPayload[5], 4);\n        pMsgData = &vchPayload[9];\n    } else\n    {\n        fFromAnonymous = false;\n        lenData = vchPayload.size() - (SMSG_PL_HDR_LEN);\n        memcpy(&lenPlain, &vchPayload[1+20+65], 4);\n        pMsgData = &vchPayload[SMSG_PL_HDR_LEN];\n    };\n\n    try {\n        msg.vchMessage.resize(lenPlain + 1);\n    } catch (std::exception& e) {\n        return errorN(8, \"%s: msg.vchMessage.resize %u threw: %s.\", __func__, lenPlain + 1, e.what());\n    };\n\n\n    if (lenPlain > 128)\n    {\n        // -- decompress\n        if (LZ4_decompress_safe((char*) pMsgData, (char*) &msg.vchMessage[0], lenData, lenPlain) != (int) lenPlain)\n        {\n            return errorN(1, \"%s: Could not decompress message data.\", __func__);\n        };\n    } else\n    {\n        // -- plaintext\n        memcpy(&msg.vchMessage[0], pMsgData, lenPlain);\n    };\n\n    msg.vchMessage[lenPlain] = '\\0';\n\n    if (fFromAnonymous)\n    {\n        // -- Anonymous sender\n        msg.sFromAddress = \"anon\";\n    } else\n    {\n        std::vector<uint8_t> vchUint160;\n        vchUint160.resize(20);\n\n        memcpy(&vchUint160[0], &vchPayload[1], 20);\n\n        uint160 ui160(vchUint160);\n        CKeyID ckidFrom(ui160);\n\n        CBitcoinAddress coinAddrFrom;\n        coinAddrFrom.Set(ckidFrom);\n        if (!coinAddrFrom.IsValid())\n        {\n            return errorN(1, \"%s: From Address is invalid.\", __func__);\n        };\n\n        std::vector<uint8_t> vchSig;\n        vchSig.resize(65);\n\n        memcpy(&vchSig[0], &vchPayload[1+20], 65);\n\n        CPubKey cpkFromSig;\n        cpkFromSig.RecoverCompact(Hash(msg.vchMessage.begin(), msg.vchMessage.end()-1), vchSig);\n        if (!cpkFromSig.IsValid())\n        {\n            return errorN(1, \"%s: Signature validation failed.\", __func__);\n        };\n\n        // -- get address for the compressed public key\n        CBitcoinAddress coinAddrFromSig;\n        coinAddrFromSig.Set(cpkFromSig.GetID());\n\n        if (!(coinAddrFrom == coinAddrFromSig))\n        {\n            return errorN(1, \"%s: Signature validation failed.\", __func__);\n        };\n\n        int rv = 5;\n        try {\n            rv = SecureMsgInsertAddress(ckidFrom, cpkFromSig);\n        } catch (std::exception& e) {\n            LogPrintf(\"SecureMsgInsertAddress(), exception: %s.\\n\", e.what());\n            //return 1;\n        };\n\n        switch(rv)\n        {\n            case 0:\n                LogPrintf(\"Sender public key added to db.\\n\");\n                break;\n            case 4:\n                LogPrintf(\"Sender public key already in db.\\n\");\n                break;\n            default:\n                LogPrintf(\"Error adding sender public key to db.\\n\");\n                break;\n        };\n\n        msg.sFromAddress = coinAddrFrom.ToString();\n    };\n\n    if (fDebugSmsg)\n        LogPrintf(\"Decrypted message for %s.\\n\", address.c_str());\n\n    return 0;\n};\n\nint SecureMsgDecrypt(bool fTestOnly, std::string &address, SecureMessage &smsg, MessageData &msg)\n{\n    return SecureMsgDecrypt(fTestOnly, address, &smsg.hash[0], smsg.pPayload, smsg.nPayload, msg);\n};\n", "meta": {"hexsha": "4f21df32b7d9a6815eb238c0962e4c50e3498ff0", "size": 117815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/smessage.cpp", "max_stars_repo_name": "sp00lin9/lyra2", "max_stars_repo_head_hexsha": "fa5c1d8eb5e6e5331977faa62c2e06e06ea046d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-06T18:57:58.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-07T00:17:51.000Z", "max_issues_repo_path": "src/smessage.cpp", "max_issues_repo_name": "sp00lin9/lyra2", "max_issues_repo_head_hexsha": "fa5c1d8eb5e6e5331977faa62c2e06e06ea046d2", "max_issues_repo_licenses": ["MIT"], "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/smessage.cpp", "max_forks_repo_name": "sp00lin9/lyra2", "max_forks_repo_head_hexsha": "fa5c1d8eb5e6e5331977faa62c2e06e06ea046d2", "max_forks_repo_licenses": ["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.9685271699, "max_line_length": 196, "alphanum_fraction": 0.5385392352, "num_tokens": 30860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.29746994260479465, "lm_q1q2_score": 0.16378914142354514}}
{"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_SWAR_FUNCTIONS_DETAILS_PERM_HPP_INCLUDED\n#define BOOST_SIMD_SWAR_FUNCTIONS_DETAILS_PERM_HPP_INCLUDED\n\n#include <boost/simd/include/functions/simd/make.hpp>\n#include <boost/integer/static_log2.hpp>\n#include <boost/mpl/apply.hpp>\n#include <boost/mpl/int.hpp>\n\nnamespace boost { namespace simd { namespace details\n{\n  // Result of the meta permutation\n  template<class P, class Card, int I>\n  struct index_ : boost::mpl::apply < P\n                                    , boost::mpl::int_<I>\n                                    , Card\n                                    >::type\n  {};\n\n  // Generate the the correct mask\n  template<class P, class Card, char Offset, char Idx, char Inc>\n  struct  generate_\n        : boost::mpl::int_<((0>index_<P,Card,Idx>::value)?-1:(Offset+Inc))>\n  {};\n\n  template<std::size_t Bytes, int N>\n  struct  bit_count\n        : boost::mpl::int_< 1 <<  ( boost::static_log2<Bytes>::value\n                                  - boost::static_log2<N>::value\n                                  )\n                          >\n  {};\n\n  // Permute specialization\n  template<class P, class Type, int N> struct permute\n  {\n    static const std::size_t Bytes = sizeof(Type);\n\n    template<char I>\n    struct  mask_\n          : generate_ < P\n                      , boost::mpl::int_<N>\n                      , index_<P, boost::mpl::int_<N>, (I / (Bytes/N))>::value\n                      * bit_count<Bytes,N>::value\n                      , I / (Bytes/N)\n                      , I % (Bytes/N)\n                      >\n    {};\n\n    static BOOST_FORCEINLINE Type call()\n    {\n      return call(boost::mpl::int_<Bytes>());\n    }\n\n    static BOOST_FORCEINLINE Type call(boost::mpl::int_<16> const&)\n    {\n      return make<Type> ( mask_< 0>::value, mask_< 1>::value\n                        , mask_< 2>::value, mask_< 3>::value\n                        , mask_< 4>::value, mask_< 5>::value\n                        , mask_< 6>::value, mask_< 7>::value\n                        , mask_< 8>::value, mask_< 9>::value\n                        , mask_<10>::value, mask_<11>::value\n                        , mask_<12>::value, mask_<13>::value\n                        , mask_<14>::value, mask_<15>::value\n                        );\n    }\n\n    static BOOST_FORCEINLINE Type call(boost::mpl::int_<8> const&)\n    {\n      return make<Type> ( mask_< 0>::value, mask_< 1>::value\n                        , mask_< 2>::value, mask_< 3>::value\n                        , mask_< 4>::value, mask_< 5>::value\n                        , mask_< 6>::value, mask_< 7>::value\n                        );\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "9b72cee4646c8e6e9748858006d37c6a0509bfed", "size": 3122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/swar/functions/details/perm.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/swar/functions/details/perm.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/swar/functions/details/perm.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.8850574713, "max_line_length": 80, "alphanum_fraction": 0.4753363229, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.16378914046556514}}
{"text": "#include <boost/rational.hpp>   /// For calculations related to sampling coefficients.\n#include <optional>\n\n#include <Common/FieldVisitors.h>\n#include <Storages/MergeTree/MergeTreeDataSelectExecutor.h>\n#include <Storages/MergeTree/MergeTreeBlockInputStream.h>\n#include <Storages/MergeTree/MergeTreeReadPool.h>\n#include <Storages/MergeTree/MergeTreeThreadBlockInputStream.h>\n#include <Storages/MergeTree/KeyCondition.h>\n#include <Parsers/ASTIdentifier.h>\n#include <Parsers/ASTFunction.h>\n#include <Parsers/ASTSampleRatio.h>\n\n/// Allow to use __uint128_t as a template parameter for boost::rational.\n// https://stackoverflow.com/questions/41198673/uint128-t-not-working-with-clang-and-libstdc\n#if !defined(__GLIBCXX_BITSIZE_INT_N_0) && defined(__SIZEOF_INT128__)\nnamespace std\n{\n    template <>\n    struct numeric_limits<__uint128_t>\n    {\n        static constexpr bool is_specialized = true;\n        static constexpr bool is_signed = false;\n        static constexpr bool is_integer = true;\n        static constexpr int radix = 2;\n        static constexpr int digits = 128;\n        static constexpr __uint128_t min () { return 0; } // used in boost 1.65.1+\n    };\n}\n#endif\n\n#include <DataStreams/ExpressionBlockInputStream.h>\n#include <DataStreams/FilterBlockInputStream.h>\n#include <DataStreams/CollapsingFinalBlockInputStream.h>\n#include <DataStreams/AddingConstColumnBlockInputStream.h>\n#include <DataStreams/CreatingSetsBlockInputStream.h>\n#include <DataStreams/NullBlockInputStream.h>\n#include <DataStreams/SummingSortedBlockInputStream.h>\n#include <DataStreams/ReplacingSortedBlockInputStream.h>\n#include <DataStreams/AggregatingSortedBlockInputStream.h>\n#include <DataStreams/VersionedCollapsingSortedBlockInputStream.h>\n#include <DataTypes/DataTypesNumber.h>\n#include <DataTypes/DataTypeDate.h>\n#include <DataTypes/DataTypeEnum.h>\n#include <Storages/VirtualColumnUtils.h>\n\n\nnamespace ProfileEvents\n{\n    extern const Event SelectedParts;\n    extern const Event SelectedRanges;\n    extern const Event SelectedMarks;\n}\n\n\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int INDEX_NOT_USED;\n    extern const int SAMPLING_NOT_SUPPORTED;\n    extern const int ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER;\n    extern const int ILLEGAL_COLUMN;\n    extern const int ARGUMENT_OUT_OF_BOUND;\n}\n\n\nMergeTreeDataSelectExecutor::MergeTreeDataSelectExecutor(MergeTreeData & data_)\n    : data(data_), log(&Logger::get(data.getLogName() + \" (SelectExecutor)\"))\n{\n}\n\n\n/// Construct a block consisting only of possible values of virtual columns\nstatic Block getBlockWithPartColumn(const MergeTreeData::DataPartsVector & parts)\n{\n    auto column = ColumnString::create();\n\n    for (const auto & part : parts)\n        column->insert(part->name);\n\n    return Block{ColumnWithTypeAndName(std::move(column), std::make_shared<DataTypeString>(), \"_part\")};\n}\n\n\nsize_t MergeTreeDataSelectExecutor::getApproximateTotalRowsToRead(\n    const MergeTreeData::DataPartsVector & parts, const KeyCondition & key_condition, const Settings & settings) const\n{\n    size_t full_marks_count = 0;\n\n    /// We will find out how many rows we would have read without sampling.\n    LOG_DEBUG(log, \"Preliminary index scan with condition: \" << key_condition.toString());\n\n    for (size_t i = 0; i < parts.size(); ++i)\n    {\n        const MergeTreeData::DataPartPtr & part = parts[i];\n        MarkRanges ranges = markRangesFromPKRange(part->index, key_condition, settings);\n\n        /** In order to get a lower bound on the number of rows that match the condition on PK,\n          *  consider only guaranteed full marks.\n          * That is, do not take into account the first and last marks, which may be incomplete.\n          */\n        for (size_t j = 0; j < ranges.size(); ++j)\n            if (ranges[j].end - ranges[j].begin > 2)\n                full_marks_count += ranges[j].end - ranges[j].begin - 2;\n    }\n\n    return full_marks_count * data.index_granularity;\n}\n\n\nusing RelativeSize = boost::rational<ASTSampleRatio::BigNum>;\n\nstd::string toString(const RelativeSize & x)\n{\n    return ASTSampleRatio::toString(x.numerator()) + \"/\" + ASTSampleRatio::toString(x.denominator());\n}\n\n/// Converts sample size to an approximate number of rows (ex. `SAMPLE 1000000`) to relative value (ex. `SAMPLE 0.1`).\nstatic RelativeSize convertAbsoluteSampleSizeToRelative(const ASTPtr & node, size_t approx_total_rows)\n{\n    if (approx_total_rows == 0)\n        return 1;\n\n    const ASTSampleRatio & node_sample = typeid_cast<const ASTSampleRatio &>(*node);\n\n    auto absolute_sample_size = node_sample.ratio.numerator / node_sample.ratio.denominator;\n    return std::min(RelativeSize(1), RelativeSize(absolute_sample_size) / RelativeSize(approx_total_rows));\n}\n\n\nBlockInputStreams MergeTreeDataSelectExecutor::read(\n    const Names & column_names_to_return,\n    const SelectQueryInfo & query_info,\n    const Context & context,\n    QueryProcessingStage::Enum & processed_stage,\n    const size_t max_block_size,\n    const unsigned num_streams,\n    Int64 max_block_number_to_read) const\n{\n    size_t part_index = 0;\n\n    MergeTreeData::DataPartsVector parts = data.getDataPartsVector();\n\n    /// If query contains restrictions on the virtual column `_part` or `_part_index`, select only parts suitable for it.\n    /// The virtual column `_sample_factor` (which is equal to 1 / used sample rate) can be requested in the query.\n    Names virt_column_names;\n    Names real_column_names;\n\n    bool part_column_queried = false;\n\n    bool sample_factor_column_queried = false;\n    Float64 used_sample_factor = 1;\n\n    for (const String & name : column_names_to_return)\n    {\n        if (name == \"_part\")\n        {\n            part_column_queried = true;\n            virt_column_names.push_back(name);\n        }\n        else if (name == \"_part_index\")\n        {\n            virt_column_names.push_back(name);\n        }\n        else if (name == \"_sample_factor\")\n        {\n            sample_factor_column_queried = true;\n            virt_column_names.push_back(name);\n        }\n        else\n        {\n            real_column_names.push_back(name);\n        }\n    }\n\n    NamesAndTypesList available_real_columns = data.getColumns().getAllPhysical();\n\n    NamesAndTypesList available_real_and_virtual_columns = available_real_columns;\n    for (const auto & name : virt_column_names)\n        available_real_and_virtual_columns.emplace_back(data.getColumn(name));\n\n    /// If there are only virtual columns in the query, you must request at least one non-virtual one.\n    if (real_column_names.empty())\n        real_column_names.push_back(ExpressionActions::getSmallestColumn(available_real_columns));\n\n    /// If `_part` virtual column is requested, we try to use it as an index.\n    Block virtual_columns_block = getBlockWithPartColumn(parts);\n    if (part_column_queried)\n        VirtualColumnUtils::filterBlockWithQuery(query_info.query, virtual_columns_block, context);\n\n    std::multiset<String> part_values = VirtualColumnUtils::extractSingleValueFromBlock<String>(virtual_columns_block, \"_part\");\n\n    data.check(real_column_names);\n    processed_stage = QueryProcessingStage::FetchColumns;\n\n    const Settings & settings = context.getSettingsRef();\n    SortDescription sort_descr = data.getPrimarySortDescription();\n\n    KeyCondition key_condition(query_info, context, available_real_and_virtual_columns, sort_descr,\n        data.getPrimaryExpression());\n\n    if (settings.force_primary_key && key_condition.alwaysUnknownOrTrue())\n    {\n        std::stringstream exception_message;\n        exception_message << \"Primary key (\";\n        for (size_t i = 0, size = sort_descr.size(); i < size; ++i)\n            exception_message << (i == 0 ? \"\" : \", \") << sort_descr[i].column_name;\n        exception_message << \") is not used and setting 'force_primary_key' is set.\";\n\n        throw Exception(exception_message.str(), ErrorCodes::INDEX_NOT_USED);\n    }\n\n    std::optional<KeyCondition> minmax_idx_condition;\n    if (data.minmax_idx_expr)\n    {\n        minmax_idx_condition.emplace(\n            query_info, context, available_real_and_virtual_columns,\n            data.minmax_idx_sort_descr, data.minmax_idx_expr);\n\n        if (settings.force_index_by_date && minmax_idx_condition->alwaysUnknownOrTrue())\n        {\n            String msg = \"MinMax index by columns (\";\n            bool first = true;\n            for (const String & col : data.minmax_idx_columns)\n            {\n                if (first)\n                    first = false;\n                else\n                    msg += \", \";\n                msg += col;\n            }\n            msg += \") is not used and setting 'force_index_by_date' is set\";\n\n            throw Exception(msg, ErrorCodes::INDEX_NOT_USED);\n        }\n    }\n\n    /// Select the parts in which there can be data that satisfy `minmax_idx_condition` and that match the condition on `_part`,\n    ///  as well as `max_block_number_to_read`.\n    {\n        auto prev_parts = parts;\n        parts.clear();\n\n        for (const auto & part : prev_parts)\n        {\n            if (part_values.find(part->name) == part_values.end())\n                continue;\n\n            if (minmax_idx_condition && !minmax_idx_condition->mayBeTrueInRange(\n                    data.minmax_idx_columns.size(),\n                    &part->minmax_idx.min_values[0], &part->minmax_idx.max_values[0],\n                    data.minmax_idx_column_types))\n                continue;\n\n            if (max_block_number_to_read && part->info.max_block > max_block_number_to_read)\n                continue;\n\n            parts.push_back(part);\n        }\n    }\n\n    /// Sampling.\n    Names column_names_to_read = real_column_names;\n    std::shared_ptr<ASTFunction> filter_function;\n    ExpressionActionsPtr filter_expression;\n\n    RelativeSize relative_sample_size = 0;\n    RelativeSize relative_sample_offset = 0;\n\n    ASTSelectQuery & select = typeid_cast<ASTSelectQuery &>(*query_info.query);\n\n    auto select_sample_size = select.sample_size();\n    auto select_sample_offset = select.sample_offset();\n\n    if (select_sample_size)\n    {\n        relative_sample_size.assign(\n            typeid_cast<const ASTSampleRatio &>(*select_sample_size).ratio.numerator,\n            typeid_cast<const ASTSampleRatio &>(*select_sample_size).ratio.denominator);\n\n        if (relative_sample_size < 0)\n            throw Exception(\"Negative sample size\", ErrorCodes::ARGUMENT_OUT_OF_BOUND);\n\n        relative_sample_offset = 0;\n        if (select_sample_offset)\n            relative_sample_offset.assign(\n                typeid_cast<const ASTSampleRatio &>(*select_sample_offset).ratio.numerator,\n                typeid_cast<const ASTSampleRatio &>(*select_sample_offset).ratio.denominator);\n\n        if (relative_sample_offset < 0)\n            throw Exception(\"Negative sample offset\", ErrorCodes::ARGUMENT_OUT_OF_BOUND);\n\n        /// Convert absolute value of the sampling (in form `SAMPLE 1000000` - how many rows to read) into the relative `SAMPLE 0.1` (how much data to read).\n        size_t approx_total_rows = 0;\n        if (relative_sample_size > 1 || relative_sample_offset > 1)\n            approx_total_rows = getApproximateTotalRowsToRead(parts, key_condition, settings);\n\n        if (relative_sample_size > 1)\n        {\n            relative_sample_size = convertAbsoluteSampleSizeToRelative(select_sample_size, approx_total_rows);\n            LOG_DEBUG(log, \"Selected relative sample size: \" << toString(relative_sample_size));\n        }\n\n        /// SAMPLE 1 is the same as the absence of SAMPLE.\n        if (relative_sample_size == RelativeSize(1))\n            relative_sample_size = 0;\n\n        if (relative_sample_offset > 0 && 0 == relative_sample_size)\n            throw Exception(\"Sampling offset is incorrect because no sampling\", ErrorCodes::ARGUMENT_OUT_OF_BOUND);\n\n        if (relative_sample_offset > 1)\n        {\n            relative_sample_offset = convertAbsoluteSampleSizeToRelative(select_sample_offset, approx_total_rows);\n            LOG_DEBUG(log, \"Selected relative sample offset: \" << toString(relative_sample_offset));\n        }\n    }\n\n    /** Which range of sampling key values do I need to read?\n      * First, in the whole range (\"universe\") we select the interval\n      *  of relative `relative_sample_size` size, offset from the beginning by `relative_sample_offset`.\n      *\n      * Example: SAMPLE 0.4 OFFSET 0.3\n      *\n      * [------********------]\n      *        ^ - offset\n      *        <------> - size\n      *\n      * If the interval passes through the end of the universe, then cut its right side.\n      *\n      * Example: SAMPLE 0.4 OFFSET 0.8\n      *\n      * [----------------****]\n      *                  ^ - offset\n      *                  <------> - size\n      *\n      * Next, if the `parallel_replicas_count`, `parallel_replica_offset` settings are set,\n      *  then it is necessary to break the received interval into pieces of the number `parallel_replicas_count`,\n      *  and select a piece with the number `parallel_replica_offset` (from zero).\n      *\n      * Example: SAMPLE 0.4 OFFSET 0.3, parallel_replicas_count = 2, parallel_replica_offset = 1\n      *\n      * [----------****------]\n      *        ^ - offset\n      *        <------> - size\n      *        <--><--> - pieces for different `parallel_replica_offset`, select the second one.\n      *\n      * It is very important that the intervals for different `parallel_replica_offset` cover the entire range without gaps and overlaps.\n      * It is also important that the entire universe can be covered using SAMPLE 0.1 OFFSET 0, ... OFFSET 0.9 and similar decimals.\n      */\n\n    bool use_sampling = relative_sample_size > 0 || settings.parallel_replicas_count > 1;\n    bool no_data = false;   /// There is nothing left after sampling.\n\n    if (use_sampling)\n    {\n        if (!data.sampling_expression)\n            throw Exception(\"Illegal SAMPLE: table doesn't support sampling\", ErrorCodes::SAMPLING_NOT_SUPPORTED);\n\n        if (sample_factor_column_queried && relative_sample_size != 0)\n            used_sample_factor = 1.0 / boost::rational_cast<Float64>(relative_sample_size);\n\n        RelativeSize size_of_universum = 0;\n        DataTypePtr type = data.getPrimaryExpression()->getSampleBlock().getByName(data.sampling_expression->getColumnName()).type;\n\n        if (typeid_cast<const DataTypeUInt64 *>(type.get()))\n            size_of_universum = RelativeSize(std::numeric_limits<UInt64>::max()) + RelativeSize(1);\n        else if (typeid_cast<const DataTypeUInt32 *>(type.get()))\n            size_of_universum = RelativeSize(std::numeric_limits<UInt32>::max()) + RelativeSize(1);\n        else if (typeid_cast<const DataTypeUInt16 *>(type.get()))\n            size_of_universum = RelativeSize(std::numeric_limits<UInt16>::max()) + RelativeSize(1);\n        else if (typeid_cast<const DataTypeUInt8 *>(type.get()))\n            size_of_universum = RelativeSize(std::numeric_limits<UInt8>::max()) + RelativeSize(1);\n        else\n            throw Exception(\"Invalid sampling column type in storage parameters: \" + type->getName() + \". Must be unsigned integer type.\",\n                ErrorCodes::ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER);\n\n        if (settings.parallel_replicas_count > 1)\n        {\n            if (relative_sample_size == RelativeSize(0))\n                relative_sample_size = 1;\n\n            relative_sample_size /= settings.parallel_replicas_count.value;\n            relative_sample_offset += relative_sample_size * RelativeSize(settings.parallel_replica_offset.value);\n        }\n\n        if (relative_sample_offset >= RelativeSize(1))\n            no_data = true;\n\n        /// Calculate the half-interval of `[lower, upper)` column values.\n        bool has_lower_limit = false;\n        bool has_upper_limit = false;\n\n        RelativeSize lower_limit_rational = relative_sample_offset * size_of_universum;\n        RelativeSize upper_limit_rational = (relative_sample_offset + relative_sample_size) * size_of_universum;\n\n        UInt64 lower = boost::rational_cast<ASTSampleRatio::BigNum>(lower_limit_rational);\n        UInt64 upper = boost::rational_cast<ASTSampleRatio::BigNum>(upper_limit_rational);\n\n        if (lower > 0)\n            has_lower_limit = true;\n\n        if (upper_limit_rational < size_of_universum)\n            has_upper_limit = true;\n\n        /*std::cerr << std::fixed << std::setprecision(100)\n            << \"relative_sample_size: \" << relative_sample_size << \"\\n\"\n            << \"relative_sample_offset: \" << relative_sample_offset << \"\\n\"\n            << \"lower_limit_float: \" << lower_limit_rational << \"\\n\"\n            << \"upper_limit_float: \" << upper_limit_rational << \"\\n\"\n            << \"lower: \" << lower << \"\\n\"\n            << \"upper: \" << upper << \"\\n\";*/\n\n        if ((has_upper_limit && upper == 0)\n            || (has_lower_limit && has_upper_limit && lower == upper))\n            no_data = true;\n\n        if (no_data || (!has_lower_limit && !has_upper_limit))\n        {\n            use_sampling = false;\n        }\n        else\n        {\n            /// Let's add the conditions to cut off something else when the index is scanned again and when the request is processed.\n\n            std::shared_ptr<ASTFunction> lower_function;\n            std::shared_ptr<ASTFunction> upper_function;\n\n            if (has_lower_limit)\n            {\n                if (!key_condition.addCondition(data.sampling_expression->getColumnName(), Range::createLeftBounded(lower, true)))\n                    throw Exception(\"Sampling column not in primary key\", ErrorCodes::ILLEGAL_COLUMN);\n\n                ASTPtr args = std::make_shared<ASTExpressionList>();\n                args->children.push_back(data.sampling_expression);\n                args->children.push_back(std::make_shared<ASTLiteral>(lower));\n\n                lower_function = std::make_shared<ASTFunction>();\n                lower_function->name = \"greaterOrEquals\";\n                lower_function->arguments = args;\n                lower_function->children.push_back(lower_function->arguments);\n\n                filter_function = lower_function;\n            }\n\n            if (has_upper_limit)\n            {\n                if (!key_condition.addCondition(data.sampling_expression->getColumnName(), Range::createRightBounded(upper, false)))\n                    throw Exception(\"Sampling column not in primary key\", ErrorCodes::ILLEGAL_COLUMN);\n\n                ASTPtr args = std::make_shared<ASTExpressionList>();\n                args->children.push_back(data.sampling_expression);\n                args->children.push_back(std::make_shared<ASTLiteral>(upper));\n\n                upper_function = std::make_shared<ASTFunction>();\n                upper_function->name = \"less\";\n                upper_function->arguments = args;\n                upper_function->children.push_back(upper_function->arguments);\n\n                filter_function = upper_function;\n            }\n\n            if (has_lower_limit && has_upper_limit)\n            {\n                ASTPtr args = std::make_shared<ASTExpressionList>();\n                args->children.push_back(lower_function);\n                args->children.push_back(upper_function);\n\n                filter_function = std::make_shared<ASTFunction>();\n                filter_function->name = \"and\";\n                filter_function->arguments = args;\n                filter_function->children.push_back(filter_function->arguments);\n            }\n\n            filter_expression = ExpressionAnalyzer(filter_function, context, nullptr, available_real_columns).getActions(false);\n\n            /// Add columns needed for `sampling_expression` to `column_names_to_read`.\n            std::vector<String> add_columns = filter_expression->getRequiredColumns();\n            column_names_to_read.insert(column_names_to_read.end(), add_columns.begin(), add_columns.end());\n            std::sort(column_names_to_read.begin(), column_names_to_read.end());\n            column_names_to_read.erase(std::unique(column_names_to_read.begin(), column_names_to_read.end()), column_names_to_read.end());\n        }\n    }\n\n    if (no_data)\n    {\n        LOG_DEBUG(log, \"Sampling yields no data.\");\n        return {};\n    }\n\n    LOG_DEBUG(log, \"Key condition: \" << key_condition.toString());\n    if (minmax_idx_condition)\n        LOG_DEBUG(log, \"MinMax index condition: \" << minmax_idx_condition->toString());\n\n    /// PREWHERE\n    ExpressionActionsPtr prewhere_actions;\n    String prewhere_column;\n    if (select.prewhere_expression)\n    {\n        ExpressionAnalyzer analyzer(select.prewhere_expression, context, nullptr, available_real_columns);\n        prewhere_actions = analyzer.getActions(false);\n        prewhere_column = select.prewhere_expression->getColumnName();\n        SubqueriesForSets prewhere_subqueries = analyzer.getSubqueriesForSets();\n\n        /** Compute the subqueries right now.\n          * NOTE Disadvantage - these calculations do not fit into the query execution pipeline.\n          * They are done before the execution of the pipeline; they can not be interrupted; during the computation, packets of progress are not sent.\n          */\n        if (!prewhere_subqueries.empty())\n            CreatingSetsBlockInputStream(std::make_shared<NullBlockInputStream>(Block()), prewhere_subqueries,\n                SizeLimits(settings.max_rows_to_transfer, settings.max_bytes_to_transfer, settings.transfer_overflow_mode)).read();\n    }\n\n    RangesInDataParts parts_with_ranges;\n\n    /// Let's find what range to read from each part.\n    size_t sum_marks = 0;\n    size_t sum_ranges = 0;\n    for (auto & part : parts)\n    {\n        RangesInDataPart ranges(part, part_index++);\n\n        if (data.hasPrimaryKey())\n            ranges.ranges = markRangesFromPKRange(part->index, key_condition, settings);\n        else\n            ranges.ranges = MarkRanges{MarkRange{0, part->marks_count}};\n\n        if (!ranges.ranges.empty())\n        {\n            parts_with_ranges.push_back(ranges);\n\n            sum_ranges += ranges.ranges.size();\n            for (const auto & range : ranges.ranges)\n                sum_marks += range.end - range.begin;\n        }\n    }\n\n    LOG_DEBUG(log, \"Selected \" << parts.size() << \" parts by date, \" << parts_with_ranges.size() << \" parts by key, \"\n        << sum_marks << \" marks to read from \" << sum_ranges << \" ranges\");\n\n    if (parts_with_ranges.empty())\n        return {};\n\n    ProfileEvents::increment(ProfileEvents::SelectedParts, parts_with_ranges.size());\n    ProfileEvents::increment(ProfileEvents::SelectedRanges, sum_ranges);\n    ProfileEvents::increment(ProfileEvents::SelectedMarks, sum_marks);\n\n    BlockInputStreams res;\n\n    if (select.final())\n    {\n        /// Add columns needed to calculate primary key and the sign.\n        std::vector<String> add_columns = data.getPrimaryExpression()->getRequiredColumns();\n        column_names_to_read.insert(column_names_to_read.end(), add_columns.begin(), add_columns.end());\n\n        if (!data.merging_params.sign_column.empty())\n            column_names_to_read.push_back(data.merging_params.sign_column);\n        if (!data.merging_params.version_column.empty())\n            column_names_to_read.push_back(data.merging_params.version_column);\n\n        std::sort(column_names_to_read.begin(), column_names_to_read.end());\n        column_names_to_read.erase(std::unique(column_names_to_read.begin(), column_names_to_read.end()), column_names_to_read.end());\n\n        res = spreadMarkRangesAmongStreamsFinal(\n            std::move(parts_with_ranges),\n            column_names_to_read,\n            max_block_size,\n            settings.use_uncompressed_cache,\n            prewhere_actions,\n            prewhere_column,\n            virt_column_names,\n            settings);\n    }\n    else\n    {\n        res = spreadMarkRangesAmongStreams(\n            std::move(parts_with_ranges),\n            num_streams,\n            column_names_to_read,\n            max_block_size,\n            settings.use_uncompressed_cache,\n            prewhere_actions,\n            prewhere_column,\n            virt_column_names,\n            settings);\n    }\n\n    if (use_sampling)\n        for (auto & stream : res)\n            stream = std::make_shared<FilterBlockInputStream>(stream, filter_expression, filter_function->getColumnName());\n\n    /// By the way, if a distributed query or query to a Merge table is made, then the `_sample_factor` column can have different values.\n    if (sample_factor_column_queried)\n        for (auto & stream : res)\n            stream = std::make_shared<AddingConstColumnBlockInputStream<Float64>>(\n                stream, std::make_shared<DataTypeFloat64>(), used_sample_factor, \"_sample_factor\");\n\n    return res;\n}\n\n\nBlockInputStreams MergeTreeDataSelectExecutor::spreadMarkRangesAmongStreams(\n    RangesInDataParts && parts,\n    size_t num_streams,\n    const Names & column_names,\n    size_t max_block_size,\n    bool use_uncompressed_cache,\n    ExpressionActionsPtr prewhere_actions,\n    const String & prewhere_column,\n    const Names & virt_columns,\n    const Settings & settings) const\n{\n    const size_t min_marks_for_concurrent_read =\n        (settings.merge_tree_min_rows_for_concurrent_read + data.index_granularity - 1) / data.index_granularity;\n    const size_t max_marks_to_use_cache =\n        (settings.merge_tree_max_rows_to_use_cache + data.index_granularity - 1) / data.index_granularity;\n\n    /// Count marks for each part.\n    std::vector<size_t> sum_marks_in_parts(parts.size());\n    size_t sum_marks = 0;\n    for (size_t i = 0; i < parts.size(); ++i)\n    {\n        /// Let the ranges be listed from right to left so that the leftmost range can be dropped using `pop_back()`.\n        std::reverse(parts[i].ranges.begin(), parts[i].ranges.end());\n\n        for (const auto & range : parts[i].ranges)\n            sum_marks_in_parts[i] += range.end - range.begin;\n\n        sum_marks += sum_marks_in_parts[i];\n    }\n\n    if (sum_marks > max_marks_to_use_cache)\n        use_uncompressed_cache = false;\n\n    BlockInputStreams res;\n\n    if (sum_marks > 0 && settings.merge_tree_uniform_read_distribution == 1)\n    {\n        /// Reduce the number of num_streams if the data is small.\n        if (sum_marks < num_streams * min_marks_for_concurrent_read && parts.size() < num_streams)\n            num_streams = std::max((sum_marks + min_marks_for_concurrent_read - 1) / min_marks_for_concurrent_read, parts.size());\n\n        MergeTreeReadPoolPtr pool = std::make_shared<MergeTreeReadPool>(\n            num_streams, sum_marks, min_marks_for_concurrent_read, parts, data, prewhere_actions, prewhere_column, true,\n            column_names, MergeTreeReadPool::BackoffSettings(settings), settings.preferred_block_size_bytes, false);\n\n        /// Let's estimate total number of rows for progress bar.\n        const size_t total_rows = data.index_granularity * sum_marks;\n        LOG_TRACE(log, \"Reading approx. \" << total_rows << \" rows\");\n\n        for (size_t i = 0; i < num_streams; ++i)\n        {\n            res.emplace_back(std::make_shared<MergeTreeThreadBlockInputStream>(\n                i, pool, min_marks_for_concurrent_read, max_block_size, settings.preferred_block_size_bytes,\n                settings.preferred_max_column_in_block_size_bytes, data, use_uncompressed_cache,\n                prewhere_actions, prewhere_column, settings, virt_columns));\n\n            if (i == 0)\n            {\n                /// Set the approximate number of rows for the first source only\n                static_cast<IProfilingBlockInputStream &>(*res.front()).addTotalRowsApprox(total_rows);\n            }\n        }\n    }\n    else if (sum_marks > 0)\n    {\n        const size_t min_marks_per_stream = (sum_marks - 1) / num_streams + 1;\n\n        for (size_t i = 0; i < num_streams && !parts.empty(); ++i)\n        {\n            size_t need_marks = min_marks_per_stream;\n\n            /// Loop over parts.\n            /// We will iteratively take part or some subrange of a part from the back\n            ///  and assign a stream to read from it.\n            while (need_marks > 0 && !parts.empty())\n            {\n                RangesInDataPart part = parts.back();\n                size_t & marks_in_part = sum_marks_in_parts.back();\n\n                /// We will not take too few rows from a part.\n                if (marks_in_part >= min_marks_for_concurrent_read &&\n                    need_marks < min_marks_for_concurrent_read)\n                    need_marks = min_marks_for_concurrent_read;\n\n                /// Do not leave too few rows in the part.\n                if (marks_in_part > need_marks &&\n                    marks_in_part - need_marks < min_marks_for_concurrent_read)\n                    need_marks = marks_in_part;\n\n                MarkRanges ranges_to_get_from_part;\n\n                /// We take the whole part if it is small enough.\n                if (marks_in_part <= need_marks)\n                {\n                    /// Restore the order of segments.\n                    std::reverse(part.ranges.begin(), part.ranges.end());\n\n                    ranges_to_get_from_part = part.ranges;\n\n                    need_marks -= marks_in_part;\n                    parts.pop_back();\n                    sum_marks_in_parts.pop_back();\n                }\n                else\n                {\n                    /// Loop through ranges in part. Take enough ranges to cover \"need_marks\".\n                    while (need_marks > 0)\n                    {\n                        if (part.ranges.empty())\n                            throw Exception(\"Unexpected end of ranges while spreading marks among streams\", ErrorCodes::LOGICAL_ERROR);\n\n                        MarkRange & range = part.ranges.back();\n\n                        const size_t marks_in_range = range.end - range.begin;\n                        const size_t marks_to_get_from_range = std::min(marks_in_range, need_marks);\n\n                        ranges_to_get_from_part.emplace_back(range.begin, range.begin + marks_to_get_from_range);\n                        range.begin += marks_to_get_from_range;\n                        marks_in_part -= marks_to_get_from_range;\n                        need_marks -= marks_to_get_from_range;\n                        if (range.begin == range.end)\n                            part.ranges.pop_back();\n                    }\n                }\n\n                BlockInputStreamPtr source_stream = std::make_shared<MergeTreeBlockInputStream>(\n                    data, part.data_part, max_block_size, settings.preferred_block_size_bytes,\n                    settings.preferred_max_column_in_block_size_bytes, column_names, ranges_to_get_from_part,\n                    use_uncompressed_cache, prewhere_actions, prewhere_column, true, settings.min_bytes_to_use_direct_io,\n                    settings.max_read_buffer_size, true, virt_columns, part.part_index_in_query);\n\n                res.push_back(source_stream);\n            }\n        }\n\n        if (!parts.empty())\n            throw Exception(\"Couldn't spread marks among streams\", ErrorCodes::LOGICAL_ERROR);\n    }\n\n    return res;\n}\n\nBlockInputStreams MergeTreeDataSelectExecutor::spreadMarkRangesAmongStreamsFinal(\n    RangesInDataParts && parts,\n    const Names & column_names,\n    size_t max_block_size,\n    bool use_uncompressed_cache,\n    ExpressionActionsPtr prewhere_actions,\n    const String & prewhere_column,\n    const Names & virt_columns,\n    const Settings & settings) const\n{\n    const size_t max_marks_to_use_cache =\n        (settings.merge_tree_max_rows_to_use_cache + data.index_granularity - 1) / data.index_granularity;\n\n    size_t sum_marks = 0;\n    for (size_t i = 0; i < parts.size(); ++i)\n        for (size_t j = 0; j < parts[i].ranges.size(); ++j)\n            sum_marks += parts[i].ranges[j].end - parts[i].ranges[j].begin;\n\n    if (sum_marks > max_marks_to_use_cache)\n        use_uncompressed_cache = false;\n\n    BlockInputStreams to_merge;\n\n    /// NOTE `merge_tree_uniform_read_distribution` is not used for FINAL\n\n    for (size_t part_index = 0; part_index < parts.size(); ++part_index)\n    {\n        RangesInDataPart & part = parts[part_index];\n\n        BlockInputStreamPtr source_stream = std::make_shared<MergeTreeBlockInputStream>(\n            data, part.data_part, max_block_size, settings.preferred_block_size_bytes,\n            settings.preferred_max_column_in_block_size_bytes, column_names, part.ranges, use_uncompressed_cache,\n            prewhere_actions, prewhere_column, true, settings.min_bytes_to_use_direct_io, settings.max_read_buffer_size, true,\n            virt_columns, part.part_index_in_query);\n\n        to_merge.emplace_back(std::make_shared<ExpressionBlockInputStream>(source_stream, data.getPrimaryExpression()));\n    }\n\n    BlockInputStreamPtr merged;\n\n    switch (data.merging_params.mode)\n    {\n        case MergeTreeData::MergingParams::Ordinary:\n            merged = std::make_shared<MergingSortedBlockInputStream>(to_merge, data.getSortDescription(), max_block_size);\n            break;\n\n        case MergeTreeData::MergingParams::Collapsing:\n            merged = std::make_shared<CollapsingFinalBlockInputStream>(\n                    to_merge, data.getSortDescription(), data.merging_params.sign_column);\n            break;\n\n        case MergeTreeData::MergingParams::Summing:\n            merged = std::make_shared<SummingSortedBlockInputStream>(to_merge,\n                    data.getSortDescription(), data.merging_params.columns_to_sum, max_block_size);\n            break;\n\n        case MergeTreeData::MergingParams::Aggregating:\n            merged = std::make_shared<AggregatingSortedBlockInputStream>(to_merge, data.getSortDescription(), max_block_size);\n            break;\n\n        case MergeTreeData::MergingParams::Replacing:    /// TODO Make ReplacingFinalBlockInputStream\n            merged = std::make_shared<ReplacingSortedBlockInputStream>(to_merge,\n                    data.getSortDescription(), data.merging_params.version_column, max_block_size);\n            break;\n\n        case MergeTreeData::MergingParams::VersionedCollapsing: /// TODO Make VersionedCollapsingFinalBlockInputStream\n            merged = std::make_shared<VersionedCollapsingSortedBlockInputStream>(\n                    to_merge, data.getSortDescription(), data.merging_params.sign_column, max_block_size, true);\n            break;\n\n        case MergeTreeData::MergingParams::Graphite:\n            throw Exception(\"GraphiteMergeTree doesn't support FINAL\", ErrorCodes::LOGICAL_ERROR);\n    }\n\n    return {merged};\n}\n\n\nvoid MergeTreeDataSelectExecutor::createPositiveSignCondition(\n    ExpressionActionsPtr & out_expression, String & out_column, const Context & context) const\n{\n    auto function = std::make_shared<ASTFunction>();\n    auto arguments = std::make_shared<ASTExpressionList>();\n    auto sign = std::make_shared<ASTIdentifier>(data.merging_params.sign_column);\n    auto one = std::make_shared<ASTLiteral>(Field(static_cast<Int64>(1)));\n\n    function->name = \"equals\";\n    function->arguments = arguments;\n    function->children.push_back(arguments);\n\n    arguments->children.push_back(sign);\n    arguments->children.push_back(one);\n\n    out_expression = ExpressionAnalyzer(function, context, {}, data.getColumns().getAllPhysical()).getActions(false);\n    out_column = function->getColumnName();\n}\n\n\n/// Calculates a set of mark ranges, that could possibly contain keys, required by condition.\n/// In other words, it removes subranges from whole range, that definitely could not contain required keys.\nMarkRanges MergeTreeDataSelectExecutor::markRangesFromPKRange(\n    const MergeTreeData::DataPart::Index & index, const KeyCondition & key_condition, const Settings & settings) const\n{\n    size_t min_marks_for_seek = (settings.merge_tree_min_rows_for_seek + data.index_granularity - 1) / data.index_granularity;\n\n    MarkRanges res;\n\n    size_t used_key_size = key_condition.getMaxKeyColumn() + 1;\n    size_t marks_count = index.at(0)->size();\n\n    /// If index is not used.\n    if (key_condition.alwaysUnknownOrTrue())\n    {\n        res.push_back(MarkRange(0, marks_count));\n    }\n    else\n    {\n        /** There will always be disjoint suspicious segments on the stack, the leftmost one at the top (back).\n            * At each step, take the left segment and check if it fits.\n            * If fits, split it into smaller ones and put them on the stack. If not, discard it.\n            * If the segment is already of one mark length, add it to response and discard it.\n            */\n        std::vector<MarkRange> ranges_stack{ {0, marks_count} };\n\n        /// NOTE Creating temporary Field objects to pass to KeyCondition.\n        Row index_left(used_key_size);\n        Row index_right(used_key_size);\n\n        while (!ranges_stack.empty())\n        {\n            MarkRange range = ranges_stack.back();\n            ranges_stack.pop_back();\n\n            bool may_be_true;\n            if (range.end == marks_count)\n            {\n                for (size_t i = 0; i < used_key_size; ++i)\n                {\n                    index[i]->get(range.begin, index_left[i]);\n                }\n\n                may_be_true = key_condition.mayBeTrueAfter(\n                    used_key_size, &index_left[0], data.primary_key_data_types);\n            }\n            else\n            {\n                for (size_t i = 0; i < used_key_size; ++i)\n                {\n                    index[i]->get(range.begin, index_left[i]);\n                    index[i]->get(range.end, index_right[i]);\n                }\n\n                may_be_true = key_condition.mayBeTrueInRange(\n                    used_key_size, &index_left[0], &index_right[0], data.primary_key_data_types);\n            }\n\n            if (!may_be_true)\n                continue;\n\n            if (range.end == range.begin + 1)\n            {\n                /// We saw a useful gap between neighboring marks. Either add it to the last range, or start a new range.\n                if (res.empty() || range.begin - res.back().end > min_marks_for_seek)\n                    res.push_back(range);\n                else\n                    res.back().end = range.end;\n            }\n            else\n            {\n                /// Break the segment and put the result on the stack from right to left.\n                size_t step = (range.end - range.begin - 1) / settings.merge_tree_coarse_index_granularity + 1;\n                size_t end;\n\n                for (end = range.end; end > range.begin + step; end -= step)\n                    ranges_stack.push_back(MarkRange(end - step, end));\n\n                ranges_stack.push_back(MarkRange(range.begin, end));\n            }\n        }\n    }\n\n    return res;\n}\n\n}\n", "meta": {"hexsha": "333f9c7cc6026c062023e1c8883cd18127a663ed", "size": 38608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp", "max_stars_repo_name": "ywandy/ClickHouse", "max_stars_repo_head_hexsha": "a4093f2b1aba01eca7aa901bd0543f17c178b796", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-05-10T14:40:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-13T11:43:15.000Z", "max_issues_repo_path": "dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp", "max_issues_repo_name": "ywandy/ClickHouse", "max_issues_repo_head_hexsha": "a4093f2b1aba01eca7aa901bd0543f17c178b796", "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": "dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp", "max_forks_repo_name": "ywandy/ClickHouse", "max_forks_repo_head_hexsha": "a4093f2b1aba01eca7aa901bd0543f17c178b796", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-23T04:55:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T11:30:51.000Z", "avg_line_length": 41.5139784946, "max_line_length": 157, "alphanum_fraction": 0.6521705346, "num_tokens": 8223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.16378913799428746}}
{"text": "/*\n * Tree node obbox file\n * \n * This file is part of the \"SoftPixel Engine\" (Copyright (c) 2008 by Lukas Hermanns)\n * See \"SoftPixelEngine.hpp\" for license information.\n */\n\n#include \"Base/spTreeNodeOBB.hpp\"\n#include \"Base/spMathCollisionLibrary.hpp\"\n\n#include <boost/foreach.hpp>\n\n\nnamespace sp\n{\nnamespace scene\n{\n\n\nOBBTreeNode::OBBTreeNode(OBBTreeNode* Parent, const dim::obbox3df &Box) :\n    TreeNode    (Parent, TREENODE_OBBTREE   ),\n    Box_        (Box                        )\n{\n}\nOBBTreeNode::~OBBTreeNode()\n{\n    MemoryManager::deleteList(Children_);\n}\n\nu32 OBBTreeNode::getNumChildren() const\n{\n    if (!Children_.empty())\n    {\n        u32 Num = Children_.size();\n        \n        foreach (TreeNode* Node, Children_)\n            Num += Node->getNumChildren();\n        \n        return Num;\n    }\n    return 0;\n}\n\nbool OBBTreeNode::isLeaf() const\n{\n    return Children_.empty();\n}\n\nconst TreeNode* OBBTreeNode::findLeaf(const dim::vector3df &Point) const\n{\n    if (Box_.isPointInside(Point))\n    {\n        foreach (TreeNode* Node, Children_)\n        {\n            const TreeNode* Leaf = Node->findLeaf(Point);\n            if (Leaf)\n                return Leaf;\n        }\n        return this;\n    }\n    return 0;\n}\n\nvoid OBBTreeNode::findLeafList(std::list<const TreeNode*> &TreeNodeList, const dim::vector3df &Point, f32 Radius) const\n{\n    if (math::CollisionLibrary::getPointBoxDistanceSq(Box_, Point) < math::pow2(Radius))\n    {\n        if (!Children_.empty())\n        {\n            foreach (TreeNode* Node, Children_)\n                Node->findLeafList(TreeNodeList, Point, Radius);\n        }\n        else\n            TreeNodeList.push_back(this);\n    }\n}\n\nvoid OBBTreeNode::findLeafList(std::list<const TreeNode*> &TreeNodeList, const dim::line3df &Line) const\n{\n    if (math::CollisionLibrary::checkLineBoxOverlap(InvBoxTransformation_ * Line, dim::aabbox3df::IDENTITY))\n    {\n        if (!Children_.empty())\n        {\n            foreach (TreeNode* Node, Children_)\n                Node->findLeafList(TreeNodeList, Line);\n        }\n        else\n            TreeNodeList.push_back(this);\n    }\n}\n\nvoid OBBTreeNode::findLeafList(std::list<const TreeNode*> &TreeNodeList, const dim::line3df &Line, f32 Radius) const\n{\n    if (math::CollisionLibrary::getLineBoxDistanceSq(dim::aabbox3df::IDENTITY, InvBoxTransformation_ * Line) < math::pow2(Radius))\n    {\n        if (!Children_.empty())\n        {\n            foreach (TreeNode* Node, Children_)\n                Node->findLeafList(TreeNodeList, Line, Radius);\n        }\n        else\n            TreeNodeList.push_back(this);\n    }\n}\n\nOBBTreeNode* OBBTreeNode::insertBoundingBox(const dim::obbox3df &Box)\n{\n    /* Check if the box can be inserted into this box */\n    if (Box_.isBoxInside(Box))\n    {\n        /* Check if the box can be inserted into a child */\n        foreach (TreeNode* Child, Children_)\n        {\n            if (Child->getType() == TREENODE_OBBTREE)\n            {\n                OBBTreeNode* Node = static_cast<OBBTreeNode*>(Child)->insertBoundingBox(Box);\n                if (Node)\n                    return Node;\n            }\n        }\n        \n        /* Create a new child */\n        return createChild(Box);\n    }\n    return 0;\n}\n\nbool OBBTreeNode::insertBoundingBox(OBBTreeNode* Node)\n{\n    /* Check if the box can be inserted into this box */\n    if (Node && Box_.isBoxInside(Node->getBox()))\n    {\n        /* Check if the box can be inserted into a child */\n        foreach (TreeNode* Child, Children_)\n        {\n            if (Child->getType() == TREENODE_OBBTREE && static_cast<OBBTreeNode*>(Child)->insertBoundingBox(Node))\n                return true;\n        }\n        \n        /* Add to this children list */\n        addChild(Node);\n        \n        return true;\n    }\n    return false;\n}\n\nvoid OBBTreeNode::setBox(const dim::obbox3df &Box)\n{\n    Box_ = Box;\n    InvBoxTransformation_ = dim::matrix4f(Box_).getInverse();\n}\n\nvoid OBBTreeNode::update(bool UpdateChildren)\n{\n    /* Root nodes must not be updated */\n    if (!Parent_ || Parent_->getType() != TREENODE_OBBTREE)\n        return;\n    \n    OBBTreeNode* Parent = static_cast<OBBTreeNode*>(Parent_);\n    \n    if (UpdateChildren)\n    {\n        /* Check for each child if it's no longer inside this box and must be updated */\n        for (std::list<TreeNode*>::iterator it = Children_.begin(); it != Children_.end();)\n        {\n            if ((*it)->getType() == TREENODE_OBBTREE && !Box_.isBoxInside(static_cast<OBBTreeNode*>(*it)->getBox()))\n            {\n                /* Exchange the child to the upper parent */\n                Parent->addChild(static_cast<OBBTreeNode*>(*it));\n                it = Children_.erase(it);\n            }\n            else\n                ++it;\n        }\n    }\n    \n    /* Check if this box is still inside it's parent box */\n    insertThisUpper(Parent);\n}\n\n\n/*\n * ======= Private: =======\n */\n\nOBBTreeNode* OBBTreeNode::createChild(const dim::obbox3df &Box)\n{\n    return addChild(new OBBTreeNode(this, Box));\n}\n\nvoid OBBTreeNode::removeFromParent()\n{\n    if (Parent_ && Parent_->getType() == TREENODE_OBBTREE)\n    {\n        TreeNode* Child = this;\n        MemoryManager::removeElement(static_cast<OBBTreeNode*>(Parent_)->Children_, Child);\n    }\n}\n\nvoid OBBTreeNode::insertThisUpper(OBBTreeNode* Parent)\n{\n    if (Parent->getBox().isBoxInside(Box_))\n    {\n        /* Check if the box can be inserted into a parent's child */\n        foreach (TreeNode* Child, Parent->Children_)\n        {\n            if (Child && Child != this && Child->getType() == TREENODE_OBBTREE &&\n                static_cast<OBBTreeNode*>(Child)->insertBoundingBox(this))\n            {\n                removeFromParent();\n                return;\n            }\n        }\n    }\n    else if (Parent->getParent() && Parent->getParent()->getType() == TREENODE_OBBTREE)\n    {\n        insertThisUpper(static_cast<OBBTreeNode*>(Parent->getParent()));\n        return;\n    }\n    \n    /* Check if this box must be inserted into the current parent */\n    if (Parent != Parent_)\n    {\n        removeFromParent();\n        Parent->addChild(this);\n    }\n}\n\n\n} // /namespace scene\n\n} // /namespace sp\n\n\n\n// ================================================================================\n", "meta": {"hexsha": "b400b231d446e99886025c0adb8cb79803750219", "size": 6237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/Base/spTreeNodeOBB.cpp", "max_stars_repo_name": "rontrek/softpixel", "max_stars_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-08-16T21:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-21T17:22:01.000Z", "max_issues_repo_path": "sources/Base/spTreeNodeOBB.cpp", "max_issues_repo_name": "rontrek/softpixel", "max_issues_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/Base/spTreeNodeOBB.cpp", "max_forks_repo_name": "rontrek/softpixel", "max_forks_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-15T09:17:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T14:10:40.000Z", "avg_line_length": 26.2058823529, "max_line_length": 130, "alphanum_fraction": 0.5776815777, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16367130764003693}}
{"text": "// Copyright (c) 2009-2010 Satoshi Nakamoto\n// Copyright (c) 2009-2014 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or https://www.opensource.org/licenses/mit-license.php .\n\n#include \"miner.h\"\n#ifdef ENABLE_MINING\n#include \"pow/tromp/equi_miner.h\"\n#endif\n\n#include \"amount.h\"\n#include \"chainparams.h\"\n#include \"cc/StakeGuard.h\"\n#include \"importcoin.h\"\n#include \"consensus/consensus.h\"\n#include \"consensus/upgrades.h\"\n#include \"consensus/validation.h\"\n#ifdef ENABLE_MINING\n#include \"crypto/equihash.h\"\n#include \"crypto/verus_hash.h\"\n#endif\n#include \"hash.h\"\n#include \"key_io.h\"\n#include \"main.h\"\n#include \"metrics.h\"\n#include \"net.h\"\n#include \"pow.h\"\n#include \"primitives/transaction.h\"\n#include \"random.h\"\n#include \"timedata.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#include \"utilmoneystr.h\"\n#include \"validationinterface.h\"\n\n#include \"zcash/Address.hpp\"\n#include \"transaction_builder.h\"\n\n#include \"sodium.h\"\n\n#include <boost/thread.hpp>\n#include <boost/tuple/tuple.hpp>\n#ifdef ENABLE_MINING\n#include <functional>\n#endif\n#include <mutex>\n\n#include \"pbaas/pbaas.h\"\n#include \"pbaas/notarization.h\"\n#include \"pbaas/identity.h\"\n#include \"rpc/pbaasrpc.h\"\n#include \"transaction_builder.h\"\n\nusing namespace std;\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// BitcoinMiner\n//\n\n//\n// Unconfirmed transactions in the memory pool often depend on other\n// transactions in the memory pool. When we select transactions from the\n// pool, we select by highest priority or fee rate, so we might consider\n// transactions that depend on transactions that aren't yet in the block.\n// The COrphan class keeps track of these 'temporary orphans' while\n// CreateBlock is figuring out which transactions to include.\n//\nclass COrphan\n{\npublic:\n    const CTransaction* ptx;\n    set<uint256> setDependsOn;\n    CFeeRate feeRate;\n    double dPriority;\n    \n    COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)\n    {\n    }\n};\n\nuint64_t nLastBlockTx = 0;\nuint64_t nLastBlockSize = 0;\n\n// We want to sort transactions by priority and fee rate, so:\ntypedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;\nclass TxPriorityCompare\n{\n    bool byFee;\n    \npublic:\n    TxPriorityCompare(bool _byFee) : byFee(_byFee) { }\n    \n    bool operator()(const TxPriority& a, const TxPriority& b)\n    {\n        if (byFee)\n        {\n            if (a.get<1>() == b.get<1>())\n                return a.get<0>() < b.get<0>();\n            return a.get<1>() < b.get<1>();\n        }\n        else\n        {\n            if (a.get<0>() == b.get<0>())\n                return a.get<1>() < b.get<1>();\n            return a.get<0>() < b.get<0>();\n        }\n    }\n};\n\nvoid UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)\n{\n    pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());\n\n    // Updating time can change work required on testnet:\n    if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) {\n        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);\n    }\n}\n\n#include \"komodo_defs.h\"\n\nextern CCriticalSection cs_metrics;\nextern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;\nextern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;\nextern bool VERUS_MINTBLOCKS;\nextern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];\nextern const char *ASSETCHAINS_ALGORITHMS[];\nextern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];\nextern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];\nextern uint160 ASSETCHAINS_CHAINID;\nextern uint160 VERUS_CHAINID;\nextern std::string VERUS_CHAINNAME;\nextern int32_t PBAAS_STARTBLOCK, PBAAS_ENDBLOCK;\nextern string PBAAS_HOST, PBAAS_USERPASS, ASSETCHAINS_RPCHOST, ASSETCHAINS_RPCCREDENTIALS;;\nextern int32_t PBAAS_PORT;\nextern uint16_t ASSETCHAINS_RPCPORT;\nextern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;\nvoid vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);\n\nextern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];\nuint32_t Mining_start,Mining_height;\nint32_t My_notaryid = -1;\nint32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);\nint32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);\nint32_t komodo_baseid(char *origbase);\nint32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);\nint64_t komodo_block_unlocktime(uint32_t nHeight);\nuint64_t komodo_commission(const CBlock *block);\nint32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);\nint32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk);\nint32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);\n\nvoid IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int &nExtraNonce, bool buildMerkle, uint32_t *pSaveBits)\n{\n    // Update nExtraNonce\n    static uint256 hashPrevBlock;\n    if (hashPrevBlock != pblock->hashPrevBlock)\n    {\n        nExtraNonce = 0;\n        hashPrevBlock = pblock->hashPrevBlock;\n    }\n    ++nExtraNonce;\n\n    if (pSaveBits)\n    {\n        *pSaveBits = pblock->nBits;\n    }\n\n    int32_t nHeight = pindexPrev->GetHeight() + 1;\n\n    if (CConstVerusSolutionVector::activationHeight.ActiveVersion(nHeight) >= CConstVerusSolutionVector::activationHeight.ACTIVATE_PBAAS)\n    {\n        // coinbase should already be finalized in the new version\n        if (buildMerkle)\n        {\n            pblock->hashMerkleRoot = pblock->BuildMerkleTree();\n        }\n\n        UpdateTime(pblock, Params().GetConsensus(), pindexPrev);\n\n        uint256 mmvRoot;\n        {\n            LOCK(cs_main);\n            // set the PBaaS header\n            ChainMerkleMountainView mmv = chainActive.GetMMV();\n            mmvRoot = mmv.GetRoot();\n        }\n\n        pblock->AddUpdatePBaaSHeader(mmvRoot);\n\n        // POS blocks have already had their solution space filled, and there is no actual extra nonce, extradata is used\n        // for POS proof, so don't modify it\n        if (!pblock->IsVerusPOSBlock())\n        {\n            uint8_t dummy;\n            // clear extra data to allow adding more PBaaS headers\n            pblock->SetExtraData(&dummy, 0);\n\n            // combine blocks and set compact difficulty if necessary\n            uint32_t savebits;\n            if ((savebits = ConnectedChains.CombineBlocks(*pblock)) && pSaveBits)\n            {\n                arith_uint256 ours, merged;\n                ours.SetCompact(pblock->nBits);\n                merged.SetCompact(savebits);\n                if (merged > ours)\n                {\n                    *pSaveBits = savebits;\n                }\n            }\n\n            // extra nonce is kept in the header, not in the coinbase any longer\n            // this allows instant spend transactions to use coinbase funds for\n            // inputs by ensuring that once final, the coinbase transaction hash\n            // will not continue to change\n            CDataStream s(SER_NETWORK, PROTOCOL_VERSION);\n            s << nExtraNonce;\n            std::vector<unsigned char> vENonce(s.begin(), s.end());\n\n            assert(pblock->ExtraDataLen() >= vENonce.size());\n            pblock->SetExtraData(vENonce.data(), vENonce.size());\n        }\n    }\n    else\n    {\n        // finalize input of coinbase\n        CMutableTransaction txcb(pblock->vtx[0]);\n        txcb.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;\n        assert(txcb.vin[0].scriptSig.size() <= 100);\n        pblock->vtx[0] = txcb;\n        if (buildMerkle)\n        {\n            pblock->hashMerkleRoot = pblock->BuildMerkleTree();\n        }\n\n        UpdateTime(pblock, Params().GetConsensus(), pindexPrev);\n    }\n}\n\nextern CWallet *pwalletMain;\n\nCPubKey GetSolutionPubKey(const std::vector<std::vector<unsigned char>> &vSolutions, txnouttype txType)\n{\n    CPubKey pk;\n\n    if (txType == TX_PUBKEY)\n    {\n        pk = CPubKey(vSolutions[0]);\n    }\n    else if(txType == TX_PUBKEYHASH)\n    {\n        // we need to have this in our wallet to get the public key\n        LOCK(pwalletMain->cs_wallet);\n        pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk);\n    }\n    else if (txType == TX_CRYPTOCONDITION)\n    {\n        if (vSolutions[0].size() == 33)\n        {\n            pk = CPubKey(vSolutions[0]);\n        }\n        else if (vSolutions[0].size() == 34 && vSolutions[0][0] == COptCCParams::ADDRTYPE_PK)\n        {\n            pk = CPubKey(std::vector<unsigned char>(vSolutions[0].begin() + 1, vSolutions[0].end()));\n        }\n        else if (vSolutions[0].size() == 20)\n        {\n            LOCK(pwalletMain->cs_wallet);\n            pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk);\n        }\n        else if (vSolutions[0].size() == 21 && vSolutions[0][0] == COptCCParams::ADDRTYPE_ID)\n        {\n            // destination is an identity, see if we can get its first public key\n            std::pair<CIdentityMapKey, CIdentityMapValue> identity;\n\n            if (pwalletMain->GetIdentity(CIdentityID(uint160(std::vector<unsigned char>(vSolutions[0].begin() + 1, vSolutions[0].end()))), identity) && \n                identity.second.IsValidUnrevoked() && \n                identity.second.primaryAddresses.size())\n            {\n                CPubKey pkTmp = boost::apply_visitor<GetPubKeyForPubKey>(GetPubKeyForPubKey(), identity.second.primaryAddresses[0]);\n                if (pkTmp.IsValid())\n                {\n                    pk = pkTmp;\n                }\n                else\n                {\n                    LOCK(pwalletMain->cs_wallet);\n                    pwalletMain->GetPubKey(CKeyID(GetDestinationID(identity.second.primaryAddresses[0])), pk);\n                }\n            }\n        }\n    }\n    return pk;\n}\n\nCPubKey GetScriptPublicKey(const CScript &scriptPubKey)\n{\n    txnouttype typeRet;\n    std::vector<std::vector<unsigned char>> vSolutions;\n    if (Solver(scriptPubKey, typeRet, vSolutions))\n    {\n        return GetSolutionPubKey(vSolutions, typeRet);\n    }\n    return CPubKey();\n}\n\nCBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake)\n{\n    CScript scriptPubKeyIn(_scriptPubKeyIn);\n\n    // instead of one scriptPubKeyIn, we take a vector of them along with relative weight. each is assigned a percentage of the block subsidy and\n    // mining reward based on its weight relative to the total\n    std::vector<pair<int, CScript>> minerOutputs = scriptPubKeyIn.size() ? std::vector<pair<int, CScript>>({make_pair((int)1, scriptPubKeyIn)}) : std::vector<pair<int, CScript>>();\n\n    CTxDestination firstDestination;\n    if (!(scriptPubKeyIn.size() && ConnectedChains.SetLatestMiningOutputs(minerOutputs, firstDestination) || isStake))\n    {\n        fprintf(stderr,\"%s: Must have valid miner outputs, including script with valid PK, PKH, or Verus ID destination.\\n\", __func__);\n        return NULL;\n    }\n\n    CPubKey pk;\n\n    if (minerOutputs.size())\n    {\n        int64_t shareCheck = 0;\n        for (auto output : minerOutputs)\n        {\n            shareCheck += output.first;\n            if (shareCheck < 0 || shareCheck > INT_MAX)\n            {\n                fprintf(stderr,\"Invalid miner outputs share specifications\\n\");\n                return NULL;\n            }\n        }\n        pk = GetScriptPublicKey(minerOutputs[0].second);\n    }\n\n    uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime;\n    //fprintf(stderr,\"create new block\\n\");\n    // Create new block\n    if ( gpucount < 0 )\n        gpucount = KOMODO_MAXGPUCOUNT;\n    std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());\n    if(!pblocktemplate.get())\n    {\n        fprintf(stderr,\"pblocktemplate.get() failure\\n\");\n        return NULL;\n    }\n    CBlock *pblock = &pblocktemplate->block; // pointer for convenience\n\n    // set version according to the current tip height, add solution if it is\n    // VerusHash\n    if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH)\n    {\n        pblock->nSolution.resize(Eh200_9.SolutionWidth);\n    }\n    else\n    {\n        pblock->nSolution.clear();\n    }\n    pblock->SetVersionByHeight(chainActive.LastTip()->GetHeight() + 1);\n\n    // -regtest only: allow overriding block.nVersion with\n    // -blockversion=N to test forking scenarios\n    if (chainparams.MineBlocksOnDemand())\n        pblock->nVersion = GetArg(\"-blockversion\", pblock->nVersion);\n    \n    // Add dummy coinbase tx placeholder as first transaction\n    pblock->vtx.push_back(CTransaction());\n\n    pblocktemplate->vTxFees.push_back(-1); // updated at end\n    pblocktemplate->vTxSigOps.push_back(-1); // updated at end\n    \n    // Largest block you're willing to create:\n    unsigned int nBlockMaxSize = GetArg(\"-blockmaxsize\", DEFAULT_BLOCK_MAX_SIZE);\n    // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:\n    nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));\n\n    unsigned int nMaxIDSize = nBlockMaxSize / 2;\n    unsigned int nCurrentIDSize = 0;\n    \n    // How much of the block should be dedicated to high-priority transactions,\n    // included regardless of the fees they pay\n    unsigned int nBlockPrioritySize = GetArg(\"-blockprioritysize\", DEFAULT_BLOCK_PRIORITY_SIZE);\n    nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);\n    \n    // Minimum block size you want to create; block will be filled with free transactions\n    // until there are no more or the block reaches this size:\n    unsigned int nBlockMinSize = GetArg(\"-blockminsize\", DEFAULT_BLOCK_MIN_SIZE);\n    nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);\n    \n    // Collect memory pool transactions into the block\n    CAmount nFees = 0;\n\n    // if this is a reserve currency, update the currency state from the coinbase of the last block\n    bool isVerusActive = IsVerusActive();\n    CPBaaSChainDefinition &thisChain = ConnectedChains.ThisChain();\n    CCoinbaseCurrencyState currencyState = CCoinbaseCurrencyState(CCurrencyState(thisChain.conversion, thisChain.premine, 0, 0, 0), 0, 0, CReserveOutput(), 0, 0, 0);\n    CAmount exchangeRate;\n\n    // we will attempt to spend any cheats we see\n    CTransaction cheatTx;\n    boost::optional<CTransaction> cheatSpend;\n    uint256 cbHash;\n\n    CBlockIndex* pindexPrev = 0;\n    {\n        LOCK2(cs_main, mempool.cs);\n        pindexPrev = chainActive.LastTip();\n        const int nHeight = pindexPrev->GetHeight() + 1;\n        const Consensus::Params &consensusParams = chainparams.GetConsensus();\n        uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams);\n        bool sapling = consensusParams.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_SAPLING);\n\n        const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();\n        uint32_t proposedTime = GetAdjustedTime();\n        if (proposedTime == nMedianTimePast)\n        {\n            // too fast or stuck, this addresses the too fast issue, while moving\n            // forward as quickly as possible\n            for (int i; i < 100; i++)\n            {\n                proposedTime = GetAdjustedTime();\n                if (proposedTime == nMedianTimePast)\n                    MilliSleep(10);\n            }\n        }\n        pblock->nTime = GetAdjustedTime();\n\n        CCoinsViewCache view(pcoinsTip);\n        uint32_t expired; uint64_t commission;\n        \n        SaplingMerkleTree sapling_tree;\n        assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));\n\n        // Priority order to process transactions\n        list<COrphan> vOrphan; // list memory doesn't move\n        map<uint256, vector<COrphan*> > mapDependers;\n        bool fPrintPriority = GetBoolArg(\"-printpriority\", false);\n        \n        // This vector will be sorted into a priority queue:\n        vector<TxPriority> vecPriority;\n        vecPriority.reserve(mempool.mapTx.size() + 1);\n\n        // check if we should add cheat transaction\n        CBlockIndex *ppast;\n        CTransaction cb;\n        int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY;\n        if (cheatCatcher &&\n            sapling && chainActive.Height() > 100 && \n            (ppast = chainActive[cheatHeight]) && \n            ppast->IsVerusPOSBlock() && \n            cheatList.IsHeightOrGreaterInList(cheatHeight))\n        {\n            // get the block and see if there is a cheat candidate for the stake tx\n            CBlock b;\n            if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, chainparams.GetConsensus(), 1))\n            {\n                CTransaction &stakeTx = b.vtx[b.vtx.size() - 1];\n\n                if (cheatList.IsCheatInList(stakeTx, &cheatTx))\n                {\n                    // make and sign the cheat transaction to spend the coinbase to our address\n                    CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);\n\n                    uint32_t voutNum;\n                    // get the first vout with value\n                    for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++)\n                    {\n                        if (b.vtx[0].vout[voutNum].nValue > 0)\n                            break;\n                    }\n\n                    // send to the same pub key as the destination of this block reward\n                    if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx))\n                    {\n                        LOCK(pwalletMain->cs_wallet);\n                        TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight);\n                        cb = b.vtx[0];\n                        cbHash = cb.GetHash();\n\n                        bool hasInput = false;\n                        for (uint32_t i = 0; i < cb.vout.size(); i++)\n                        {\n                            // add the spends with the cheat\n                            if (cb.vout[i].nValue > 0)\n                            {\n                                tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue);\n                                hasInput = true;\n                            }\n                        }\n\n                        if (hasInput)\n                        {\n                            // this is a send from a t-address to a sapling address, which we don't have an ovk for.\n                            // Instead, generate a common one from the HD seed. This ensures the data is\n                            // recoverable, at least for us, while keeping it logically separate from the ZIP 32\n                            // Sapling key hierarchy, which the user might not be using.\n                            uint256 ovk;\n                            HDSeed seed;\n                            if (pwalletMain->GetHDSeed(seed)) {\n                                ovk = ovkForShieldingFromTaddr(seed);\n\n                                // send everything to Sapling address\n                                tb.SendChangeTo(cheatCatcher.value(), ovk);\n\n                                tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey);\n\n                                TransactionBuilderResult buildResult(tb.Build());\n                                if (!buildResult.IsError() && buildResult.IsTx())\n                                {\n                                    cheatSpend = buildResult.GetTxOrThrow();\n                                }\n                                else\n                                {\n                                    LogPrintf(\"Error building cheat catcher transaction: %s\\n\", buildResult.GetError().c_str());\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (cheatSpend)\n        {\n            cheatTx = cheatSpend.value();\n            std::list<CTransaction> removed;\n            mempool.removeConflicts(cheatTx, removed);\n            printf(\"Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\\n%s\\n\",\n                (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str());\n\n            // add to mem pool and relay\n            if (myAddtomempool(cheatTx))\n            {\n                RelayTransaction(cheatTx);\n            }\n        }\n\n        //\n        // Now start solving the block\n        //\n\n        uint64_t nBlockSize = 1000;             // initial size\n        uint64_t nBlockTx = 1;                  // number of transactions - always have a coinbase\n        uint32_t autoTxSize = 0;                // extra transaction overhead that we will add while creating the block\n        int nBlockSigOps = 100;\n\n        // VerusPoP staking transaction data\n        CMutableTransaction txStaked;           // if this is a stake operation, the staking transaction that goes at the end\n        uint32_t nStakeTxSize = 0;              // serialized size of the stake transaction\n\n        // if this is not for mining, first determine if we have a right to bother\n        if (isStake)\n        {\n            uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;\n            txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight);\n\n            //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )\n            //    blocktime = pindexPrev->GetMedianTimePast() + 60;\n            if (ASSETCHAINS_LWMAPOS != 0)\n            {\n                uint32_t nBitsPOS;\n                arith_uint256 posHash;\n\n                siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk);\n                blocktime = GetAdjustedTime();\n\n                // change the default scriptPubKeyIn to the same output script exactly as the staking transaction\n                // TODO: improve this and just implement stake guard here rather than keeping this legacy\n                if (siglen > 0)\n                    scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey);\n            }\n            else\n            {\n                siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);\n            }\n\n            if (siglen <= 0)\n            {\n                return NULL;\n            }\n\n            pblock->nTime = blocktime;\n            nStakeTxSize = GetSerializeSize(txStaked, SER_NETWORK, PROTOCOL_VERSION);\n            nBlockSize += nStakeTxSize;\n\n            // get the public key and make a miner output if needed for this\n            if (!minerOutputs.size())\n            {\n                minerOutputs.push_back(make_pair((int)1, txStaked.vout[0].scriptPubKey));\n                pk = GetScriptPublicKey(txStaked.vout[0].scriptPubKey);\n                ExtractDestination(minerOutputs[0].second, firstDestination);\n            }\n        }\n\n        ConnectedChains.AggregateChainTransfers(firstDestination, nHeight);\n\n        // Now the coinbase -\n        // A PBaaS coinbase must have some additional outputs to enable certain chain state and functions to be properly\n        // validated. All but currency state and the first chain definition are either optional or not valid on non-fractional reserve PBaaS blockchains\n        // All of these are instant spend outputs that have no maturity wait time and may be spent in the same block.\n        //\n        // 1. (required) currency state - current state of currency supply and optionally reserve, premine, etc. This is primarily a data output to provide\n        //    cross check for coin minting and burning operations, making it efficient to determine up-to-date supply, reserves, and conversions. To provide\n        //    an extra level of supply cross-checking and fast data retrieval, this is part of all PBaaS chains' protocol, not just reserves.\n        //    This output also includes reserve and native amounts for total conversions, less fees, of any conversions between Verus reserve and the\n        //    native currency.\n        //\n        // 2. (block 1 required) chain definition - in order to confirm the amount of coins converted and issued within the possible range, before chain start,\n        //    new PBaaS chains have a zero-amount, unspendable chain definition output.\n        //\n        // 3. (block 1 optional) initial import utxo - for any chain with conversion or pre-conversion, the first coinbase must include an initial import utxo. \n        //    Pre-conversions are handled on the launch chain before the PBaaS chain starts, so they are an additional output, which begins\n        //    as a fixed amount and is spent with as many outputs as necessary to the recipients of the pre-conversion transactions when those pre-conversions\n        //    are imported. All pre-converted outputs get their source currency from a thread that starts with this output in block 1.\n        //\n        // 4. (block 1 optional) initial export utxo - reserve chains, or any chain that will use exports to another chain must have an initial export utxo, any chain\n        //    may have one, but currently, they can only be spent with valid exports, which only occur on reserve chains\n        //\n        // 5. (optional) notarization output - in order to ensure that notarization can occur independent of the availability of fungible\n        //    coins on the network, and also that the notarization can provide a spendable finalization output and possible reward\n        //\n        // In addition, each PBaaS block can be mined with optional, fee-generating transactions. Inporting transactions from the reserve chain or sending\n        // exported transactions to the reserve chain are optional fee-generating steps that would be easy to do when running multiple daemons.\n        // The types of transactions miners/stakers may facilitate or create for fees are as follows:\n        //\n        // 1. Earned notarization of Verus chain - spends the notarization instant out. must be present and spend the notarization output if there is a notarization output\n        //\n        // 2. Imported transactions from the export thread for this PBaaS chain on the Verus blockchain - imported transactions must spend the import utxo\n        //    thread, represent the export from the alternate chain which spends the export output from the prior import transaction, carry a notary proof, and\n        //    include outputs that map to each of its inputs on the source chain. Outputs can include unconverted reserve outputs only on fractional\n        //    reserve chains, pre-converted outputs for any chain with launch conversion, and post launch outputs to be converted on fractional reserve\n        //    chains. Each are handled in the following way:\n        //      a. Unconverted outputs are left as outputs to the intended destination of Verus reserve token and do not pass through the coinbase\n        //      b. Pre-converted outputs require that the import transaction spend the last pre-conversion output starting at block 1 as the source for\n        //         pre-converted currency.\n        //\n        // 3. Zero or more aggregated exports that combine individual cross-chain transactions and reserve transfer outputs for export to the Verus chain. \n        //\n        // 4. Conversion distribution transactions for all native and reserve currency conversions, including reserve transfer outputs without conversion as\n        //    a second step for reserve transfers that have conversion included. Any remaining pre-converted reserve must always remain in a change output\n        //    until it is exhausted\n        CTxOut premineOut, chainDefinitionOut, importThreadOut, exportThreadOut, currencyStateOut, notarizationOut;\n        CMutableTransaction newNotarizationTx, newConversionOutputTx;\n\n        // size of conversion tx\n        std::vector<CInputDescriptor> conversionInputs;\n\n        // if we are a PBaaS chain, first make sure we don't start prematurely, and if\n        // we should make an earned notarization, make it and set index to non-zero value\n        int32_t notarizationTxIndex = 0;                            // index of notarization if it is added\n        int32_t conversionTxIndex = 0;                              // index of conversion transaction if it is added\n\n        // export transactions can be created here by aggregating all pending transfer requests and either getting 10 or more together, or\n        // waiting n (10) blocks since the last one. each export must spend the output of the one before it\n        std::vector<CMutableTransaction> exportTransactions;\n\n        // all transaction outputs requesting conversion to another currency (PBaaS fractional reserve only)\n        // these will be used to calculate conversion price, fees, and generate coinbase conversion output as well as the\n        // conversion output transaction\n        std::vector<CTxOut> reserveConversionTo;\n        std::vector<CTxOut> reserveConversionFrom;\n\n        int64_t pbaasTransparentIn = 0;\n        int64_t pbaasTransparentOut = 0;\n        int64_t blockSubsidy = GetBlockSubsidy(nHeight, consensusParams);\n\n        uint160 thisChainID = ConnectedChains.ThisChain().GetChainID();\n\n        uint256 mmrRoot;\n        vector<CInputDescriptor> notarizationInputs;\n\n        // used as scratch for making CCs, should be reinitialized each time\n        CCcontract_info CC;\n        CCcontract_info *cp;\n        vector<CTxDestination> vKeys;\n        CPubKey pkCC;\n\n        // Create coinbase tx and set up the null input with height\n        CMutableTransaction coinbaseTx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);\n        coinbaseTx.vin.push_back(CTxIn(uint256(), (uint32_t)-1, CScript() << nHeight << OP_0));\n\n        // default outputs for mining and before stake guard or fee calculation\n        // store the relative weight in the amount output to convert later to a relative portion\n        // of the reward + fees\n        for (auto &spk : minerOutputs)\n        {\n            coinbaseTx.vout.push_back(CTxOut(spk.first, spk.second));\n        }\n\n        // we will update amounts and fees later, but convert the guarded output now for validity checking and size estimate\n        if (isStake)\n        {\n            // if there is a specific destination, use it\n            CTransaction stakeTx(txStaked);\n            CStakeParams p;\n            if (ValidateStakeTransaction(stakeTx, p, false))\n            {\n                if (!p.pk.IsValid())\n                {\n                    LogPrintf(\"CreateNewBlock: invalid public key\\n\");\n                    fprintf(stderr,\"CreateNewBlock: invalid public key\\n\");\n                    return NULL;\n                }\n                for (auto &cbOutput : coinbaseTx.vout)\n                {\n                    if (!MakeGuardedOutput(cbOutput.nValue, p.pk, stakeTx, cbOutput))\n                    {\n                        LogPrintf(\"CreateNewBlock: failed to make GuardedOutput on staking coinbase\\n\");\n                        fprintf(stderr,\"CreateNewBlock: failed to make GuardedOutput on staking coinbase\\n\");\n                        return NULL;\n                    }\n                }\n            }\n            else\n            {\n                LogPrintf(\"CreateNewBlock: invalid stake transaction\\n\");\n                fprintf(stderr,\"CreateNewBlock: invalid stake transaction\\n\");\n                return NULL;\n            }\n        }\n\n        CAmount totalEmission = blockSubsidy;\n\n        // make earned notarization only if this is not the notary chain and we have enough subsidy\n        if (!isVerusActive)\n        {\n            // if we don't have a connected root PBaaS chain, we can't properly check\n            // and notarize the start block, so we have to pass the notarization and cross chain steps\n            bool notaryConnected = ConnectedChains.IsVerusPBaaSAvailable() && ConnectedChains.notaryChainHeight >= PBAAS_STARTBLOCK;\n\n            // get current currency state differently, depending on height\n            if (nHeight == 1)\n            {\n                blockSubsidy -= GetBlockOnePremine();       // separate subsidy, which can go to miner, from premine\n\n                if (!notaryConnected)\n                {\n                    // cannt make block 1 unless we can properly notarize that the launch chain is past the start block\n                    return NULL;\n                }\n\n                // if some amount of pre-conversion was allowed\n                if (thisChain.maxpreconvert)\n                {\n                    // this is invalid\n                    if (thisChain.conversion <= 0)\n                    {\n                        return NULL;\n                    }\n\n                    // get the total amount pre-converted\n                    UniValue params(UniValue::VARR);\n                    params.push_back(ASSETCHAINS_CHAINID.GetHex());\n\n                    UniValue result;\n                    try\n                    {\n                        result = find_value(RPCCallRoot(\"getinitialcurrencystate\", params), \"result\");\n                    } catch (exception e)\n                    {\n                        result = NullUniValue;\n                    }\n\n                    if (!result.isNull())\n                    {\n                        currencyState = CCoinbaseCurrencyState(result);\n                    }\n\n                    if (result.isNull() || !currencyState.IsValid())\n                    {\n                        // no matter what happens, we should be able to get a valid currency state of some sort, if not, fail\n                        LogPrintf(\"Unable to get initial currency state to create block.\\n\");\n                        printf(\"Failure to get initial currency state. Cannot create block.\\n\");\n                        return NULL;\n                    }\n\n                    if (currencyState.ReserveIn < ConnectedChains.ThisChain().minpreconvert)\n                    {\n                        // no matter what happens, we should be able to get a valid currency state of some sort, if not, fail\n                        LogPrintf(\"This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\\n\");\n                        printf(\"This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\\n\");\n                        return NULL;\n                    }\n                }\n\n                // add needed block one coinbase outputs\n                // send normal reward to the miner, premine to the address in the chain definition, and pre-converted to the\n                // import thread out\n                if (GetBlockOnePremine())\n                {\n                    premineOut = CTxOut(GetBlockOnePremine(), GetScriptForDestination(CTxDestination(ConnectedChains.ThisChain().address)));\n                    coinbaseTx.vout.push_back(premineOut);\n                }\n\n                // chain definition - always\n                // make the chain definition output\n                vKeys.clear();\n                cp = CCinit(&CC, EVAL_PBAASDEFINITION);\n\n                // send this to EVAL_PBAASDEFINITION address as a destination, locked by the default pubkey\n                pkCC = CPubKey(ParseHex(CC.CChexstr));\n                vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_PBAASDEFINITION)));\n                thisChain.preconverted = currencyState.ReserveIn;   // update known, preconverted amount\n\n                chainDefinitionOut = MakeCC1of1Vout(EVAL_PBAASDEFINITION, 0, pkCC, vKeys, thisChain);\n                coinbaseTx.vout.push_back(chainDefinitionOut);\n\n                // import - only spendable for reserve currency or currency with preconversion to allow import of conversions, this output will include\n                // all pre-converted coins and all pre-conversion fees, denominated in Verus reserve currency\n                vKeys.clear();\n                cp = CCinit(&CC, EVAL_CROSSCHAIN_IMPORT);\n\n                pkCC = CPubKey(ParseHex(CC.CChexstr));\n\n                // import thread is specific to the chain importing from\n                vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.notaryChain.GetChainID(), EVAL_CROSSCHAIN_IMPORT)));\n\n                // log import of all reserve in as well as the fees that are passed through the initial ReserveOut in the initial import\n                importThreadOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_IMPORT, \n                                                 currencyState.ReserveToNative(thisChain.preconverted, thisChain.conversion), pkCC, vKeys, \n                                                 CCrossChainImport(ConnectedChains.NotaryChain().GetChainID(), currencyState.ReserveIn + currencyState.ReserveOut.nValue));\n\n                coinbaseTx.vout.push_back(importThreadOut);\n\n                // export - currently only spendable for reserve currency, but added for future capabilities\n                vKeys.clear();\n                cp = CCinit(&CC, EVAL_CROSSCHAIN_EXPORT);\n\n                pkCC = CPubKey(ParseHex(CC.CChexstr));\n                vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.NotaryChain().GetChainID(), EVAL_CROSSCHAIN_EXPORT)));\n\n                exportThreadOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_EXPORT, 0, pkCC, vKeys, \n                                                 CCrossChainExport(ConnectedChains.NotaryChain().GetChainID(), 0, 0, 0));\n\n                coinbaseTx.vout.push_back(exportThreadOut);\n            }\n            else\n            {\n                CBlock block;\n                assert(nHeight > 1);\n                currencyState = ConnectedChains.GetCurrencyState(nHeight - 1);\n                currencyState.Fees = 0;\n                currencyState.ConversionFees = 0;\n                currencyState.NativeIn = 0;\n                currencyState.ReserveIn = 0;\n                currencyState.ReserveOut.nValue = 0;\n\n                if (!currencyState.IsValid())\n                {\n                    // we should be able to get a valid currency state, if not, fail\n                    LogPrintf(\"Unable to get initial currency state to create block #%d.\\n\", nHeight);\n                    printf(\"Failure to get initial currency state. Cannot create block #%d.\\n\", nHeight);\n                    return NULL;\n                }\n            }\n\n            // update the currency state to include emissions before calculating conversions\n            // premine is an emission that is factored in before this\n            currencyState.UpdateWithEmission(totalEmission);\n\n            // always add currency state output for coinbase\n            vKeys.clear();\n            cp = CCinit(&CC, EVAL_CURRENCYSTATE);\n\n            CPubKey currencyOutPK(ParseHex(cp->CChexstr));\n            vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_CURRENCYSTATE))));\n\n            // make an output that either carries zero coins pre-converting, or the initial supply for block 1, conversion amounts will be adjusted later\n            currencyStateOut = MakeCC1of1Vout(EVAL_CURRENCYSTATE, 0, currencyOutPK, vKeys, currencyState);\n\n            coinbaseTx.vout.push_back(currencyStateOut);\n\n            if (notaryConnected)\n            {\n                // if we have access to our notary daemon\n                // create a notarization if we would qualify, and add it to the mempool and block\n                CTransaction prevTx, crossTx, lastConfirmed, lastImportTx;\n                ChainMerkleMountainView mmv = chainActive.GetMMV();\n                mmrRoot = mmv.GetRoot();\n                int32_t confirmedInput = -1;\n                CTxDestination confirmedDest;\n                if (CreateEarnedNotarization(newNotarizationTx, notarizationInputs, prevTx, crossTx, lastConfirmed, nHeight, &confirmedInput, &confirmedDest))\n                {\n                    // we have a valid, earned notarization transaction. we still need to complete it as follows:\n                    // 1. Add an instant-spend input from the coinbase transaction to fund the finalization output\n                    //\n                    // 2. if we are spending finalization outputs, create an output of the same amount as a finalization output \n                    //    plus and any excess from the other, orphaned finalizations to the creator of the confirmed notarization\n                    //\n                    // 3. make sure the currency state is correct\n\n                    // input should either be 0 or PBAAS_MINNOTARIZATIONOUTPUT + all finalized outputs\n                    // we will add PBAAS_MINNOTARIZATIONOUTPUT from a coinbase instant spend in all cases and double that when it is 0 for block 1\n                    for (const CTxIn& txin : newNotarizationTx.vin)\n                    {\n                        const uint256& prevHash = txin.prevout.hash;\n                        const CCoins *pcoins = view.AccessCoins(prevHash);\n                        pbaasTransparentIn += pcoins && (pcoins->vout.size() > txin.prevout.n) ? pcoins->vout[txin.prevout.n].nValue : 0;\n                    }\n\n                    // calculate the amount that will be sent to the confirmed notary address\n                    // this will only be non-zero if we have finalized inputs\n                    if (pbaasTransparentIn > 0)\n                    {\n                        pbaasTransparentOut = pbaasTransparentIn - PBAAS_MINNOTARIZATIONOUTPUT;\n                    }\n\n                    if (pbaasTransparentOut)\n                    {\n                        // if we are on a non-fungible chain, reward out must be unspendable\n                        // make a normal output to the confirmed notary with the excess right behind the op_return\n                        // TODO: make this a cc out to only allow spending on a fungible chain\n                        CTxOut rewardOut = CTxOut(pbaasTransparentOut, GetScriptForDestination(confirmedDest));\n                        newNotarizationTx.vout.insert(newNotarizationTx.vout.begin() + newNotarizationTx.vout.size() - 1, rewardOut);\n                    }\n\n                    // make the earned notarization coinbase output\n                    vKeys.clear();\n                    cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION);\n\n                    // send this to EVAL_EARNEDNOTARIZATION address as a destination, locked by the default pubkey\n                    pkCC = CPubKey(ParseHex(cp->CChexstr));\n                    vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(VERUS_CHAINID, EVAL_EARNEDNOTARIZATION))));\n\n                    int64_t needed = nHeight == 1 ? PBAAS_MINNOTARIZATIONOUTPUT << 1 : PBAAS_MINNOTARIZATIONOUTPUT;\n\n                    // output duplicate notarization as coinbase output for instant spend to notarization\n                    // the output amount is considered part of the total value of this coinbase\n                    CPBaaSNotarization pbn(newNotarizationTx);\n                    notarizationOut = MakeCC1of1Vout(EVAL_EARNEDNOTARIZATION, needed, pkCC, vKeys, pbn);\n                    coinbaseTx.vout.push_back(notarizationOut);\n\n                    // place the notarization\n                    pblock->vtx.push_back(CTransaction(newNotarizationTx));\n                    pblocktemplate->vTxFees.push_back(0);\n                    pblocktemplate->vTxSigOps.push_back(-1); // updated at end\n                    nBlockSize += GetSerializeSize(newNotarizationTx, SER_NETWORK, PROTOCOL_VERSION);\n                    notarizationTxIndex = pblock->vtx.size() - 1;\n                    nBlockTx++;\n                }\n                else if (nHeight == 1)\n                {\n                    // failed to notarize at block 1\n                    return NULL;\n                }\n\n                // if we have a last confirmed notarization, then check for new imports from the notary chain\n                if (lastConfirmed.vout.size())\n                {\n                    // we need to find the last unspent import transaction\n                    std::vector<CAddressUnspentDbEntry> unspentOutputs;\n\n                    bool found = false;\n\n                    // we cannot get export to a chain that has shut down\n                    // if the chain definition is spent, a chain is inactive\n                    if (GetAddressUnspent(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.NotaryChain().GetChainID(), EVAL_CROSSCHAIN_IMPORT)), 1, unspentOutputs))\n                    {\n                        // if one spends the prior one, get the one that is not spent\n                        for (auto txidx : unspentOutputs)\n                        {\n                            uint256 blkHash;\n                            CTransaction itx;\n                            if (myGetTransaction(txidx.first.txhash, lastImportTx, blkHash) &&\n                                CCrossChainImport(lastImportTx).IsValid() &&\n                                (lastImportTx.IsCoinBase() ||\n                                (myGetTransaction(lastImportTx.vin[0].prevout.hash, itx, blkHash) &&\n                                CCrossChainImport(itx).IsValid())))\n                            {\n                                found = true;\n                                break;\n                            }\n                        }\n                    }\n\n                    if (found && pwalletMain)\n                    {\n                        UniValue params(UniValue::VARR);\n                        UniValue param(UniValue::VOBJ);\n\n                        CMutableTransaction txTemplate = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight);\n                        int i;\n                        for (i = 0; i < lastImportTx.vout.size(); i++)\n                        {\n                            COptCCParams p;\n                            if (lastImportTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.evalCode == EVAL_CROSSCHAIN_IMPORT)\n                            {\n                                txTemplate.vin.push_back(CTxIn(lastImportTx.GetHash(), (uint32_t)i));\n                                break;\n                            }\n                        }\n\n                        UniValue result = NullUniValue;\n                        if (i < lastImportTx.vout.size())\n                        {\n                            param.push_back(Pair(\"name\", thisChain.name));\n                            param.push_back(Pair(\"lastimporttx\", EncodeHexTx(lastImportTx)));\n                            param.push_back(Pair(\"lastconfirmednotarization\", EncodeHexTx(lastConfirmed)));\n                            param.push_back(Pair(\"importtxtemplate\", EncodeHexTx(txTemplate)));\n                            param.push_back(Pair(\"totalimportavailable\", lastImportTx.vout[txTemplate.vin[0].prevout.n].nValue));\n                            params.push_back(param);\n\n                            try\n                            {\n                                result = find_value(RPCCallRoot(\"getlatestimportsout\", params), \"result\");\n                            } catch (exception e)\n                            {\n                                printf(\"Could not get latest imports from notary chain\\n\");\n                            }\n                        }\n\n                        if (result.isArray() && result.size())\n                        {\n                            LOCK(pwalletMain->cs_wallet);\n\n                            uint256 lastImportHash = lastImportTx.GetHash();\n                            for (int i = 0; i < result.size(); i++)\n                            {\n                                CTransaction itx;\n                                if (result[i].isStr() && DecodeHexTx(itx, result[i].get_str()) && itx.vin.size() && itx.vin[0].prevout.hash == lastImportHash)\n                                {\n                                    // sign the transaction spending the last import and add to mempool\n                                    CMutableTransaction mtx(itx);\n                                    CCrossChainImport cci(lastImportTx);\n\n                                    bool signSuccess;\n                                    SignatureData sigdata;\n                                    CAmount value;\n                                    const CScript *pScriptPubKey;\n\n                                    signSuccess = ProduceSignature(\n                                        TransactionSignatureCreator(pwalletMain, &itx, 0, lastImportTx.vout[itx.vin[0].prevout.n].nValue, SIGHASH_ALL), lastImportTx.vout[itx.vin[0].prevout.n].scriptPubKey, sigdata, consensusBranchId);\n\n                                    if (!signSuccess)\n                                    {\n                                        break;\n                                    }\n\n                                    UpdateTransaction(mtx, 0, sigdata);\n                                    itx = CTransaction(mtx);\n\n                                    // commit to mempool and remove any conflicts\n                                    std::list<CTransaction> removed;\n                                    mempool.removeConflicts(itx, removed);\n                                    CValidationState state;\n                                    if (!myAddtomempool(itx, &state))\n                                    {\n                                        LogPrintf(\"Failed to add import transactions to the mempool due to: %s\\n\", state.GetRejectReason().c_str());\n                                        printf(\"Failed to add import transactions to the mempool due to: %s\\n\", state.GetRejectReason().c_str());\n                                        break;  // if we failed to add one, the others will fail to spend it\n                                    }\n\n                                    lastImportTx = itx;\n                                    lastImportHash = itx.GetHash();\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        else\n        {\n            currencyState.UpdateWithEmission(totalEmission);\n        }\n\n        // coinbase should have all necessary outputs (TODO: timelock is not supported or finished yet)\n        uint32_t nCoinbaseSize = GetSerializeSize(coinbaseTx, SER_NETWORK, PROTOCOL_VERSION);\n        nBlockSize += nCoinbaseSize;\n\n        // now create the priority array, including market order reserve transactions, since they can always execute, leave limits for later\n        bool haveReserveTransactions = false;\n        uint32_t reserveExchangeLimitSize = 0;\n        std::vector<const CTransaction *> limitOrders;\n\n        // now add transactions from the mem pool to the priority heap\n        for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();\n             mi != mempool.mapTx.end(); ++mi)\n        {\n            const CTransaction& tx = mi->GetTx();\n            uint256 hash = tx.GetHash();\n            \n            int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)\n            ? nMedianTimePast\n            : pblock->GetBlockTime();\n\n            if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))\n            {\n                //fprintf(stderr,\"coinbase.%d finaltx.%d expired.%d\\n\",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));\n                continue;\n            }\n\n            if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )\n            {\n                //fprintf(stderr,\"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\\n\",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);\n                continue;\n            }\n\n            COrphan* porphan = NULL;\n            double dPriority = 0;\n            CAmount nTotalIn = 0;\n            CAmount nTotalReserveIn = 0;\n            bool fMissingInputs = false;\n            CReserveTransactionDescriptor rtxd;\n            bool isReserve = mempool.IsKnownReserveTransaction(hash, rtxd);\n\n            if (tx.IsCoinImport())\n            {\n                CAmount nValueIn = GetCoinImportValue(tx);\n                nTotalIn += nValueIn;\n                dPriority += (double)nValueIn * 1000;  // flat multiplier\n            } else {\n                // separate limit orders to be added later, we add them at the end, failed fill or kills are normal transactions, consider them reserve txs\n                if (isReserve && rtxd.IsReserveExchange() && rtxd.IsLimit())\n                {\n                    // if we might expire, refresh and check again\n                    if (rtxd.IsFillOrKill())\n                    {\n                        rtxd = CReserveTransactionDescriptor(tx, view, nHeight);\n                        mempool.PrioritiseReserveTransaction(rtxd, currencyState);\n                    }\n\n                    // if is is a failed conversion, drop through\n                    if (!rtxd.IsFillOrKillFail())\n                    {\n                        limitOrders.push_back(&tx);\n                        reserveExchangeLimitSize += GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n                        continue;\n                    }\n                }\n                if (isReserve)\n                {\n                    nTotalIn += rtxd.nativeIn;\n                    nTotalReserveIn += rtxd.reserveIn;\n                    if (rtxd.IsIdentity() && CNameReservation(tx).IsValid())\n                    {\n                        nCurrentIDSize += GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n                        if (nCurrentIDSize > nMaxIDSize)\n                        {\n                            continue;\n                        }\n                    }\n                }\n                BOOST_FOREACH(const CTxIn& txin, tx.vin)\n                {\n                    CAmount nValueIn = 0, nReserveValueIn = 0;\n\n                    // Read prev transaction\n                    if (!view.HaveCoins(txin.prevout.hash))\n                    {\n                        // This should never happen; all transactions in the memory\n                        // pool should connect to either transactions in the chain\n                        // or other transactions in the memory pool.\n                        if (!mempool.mapTx.count(txin.prevout.hash))\n                        {\n                            LogPrintf(\"ERROR: mempool transaction missing input\\n\");\n                            if (fDebug) assert(\"mempool transaction missing input\" == 0);\n                            fMissingInputs = true;\n                            if (porphan)\n                                vOrphan.pop_back();\n                            break;\n                        }\n\n                        // Has to wait for dependencies\n                        if (!porphan)\n                        {\n                            // Use list for automatic deletion\n                            vOrphan.push_back(COrphan(&tx));\n                            porphan = &vOrphan.back();\n                        }\n                        mapDependers[txin.prevout.hash].push_back(porphan);\n                        porphan->setDependsOn.insert(txin.prevout.hash);\n\n                        const CTransaction &otx = mempool.mapTx.find(txin.prevout.hash)->GetTx();\n                        // consider reserve outputs and set priority according to their value here as well\n                        if (!isReserve)\n                        {\n                            nTotalIn += otx.vout[txin.prevout.n].nValue;\n                        }\n                        continue;\n                    }\n                    const CCoins* coins = view.AccessCoins(txin.prevout.hash);\n                    assert(coins);\n\n                    // consider reserve outputs and set priority according to their value here as well\n                    if (isReserve)\n                    {\n                        nReserveValueIn = coins->vout[txin.prevout.n].ReserveOutValue();\n                    }\n\n                    nValueIn = coins->vout[txin.prevout.n].nValue;\n                    int nConf = nHeight - coins->nHeight;\n\n                    dPriority += ((double)((nReserveValueIn ? currencyState.ReserveToNative(nReserveValueIn) : 0) + nValueIn)) * nConf;\n\n                    // reserve is totaled differently\n                    if (!isReserve)\n                    {\n                        nTotalIn += nValueIn;\n                        nTotalReserveIn += nReserveValueIn;\n                    }\n                }\n                nTotalIn += tx.GetShieldedValueIn();\n            }\n\n            if (fMissingInputs) continue;\n            \n            // Priority is sum(valuein * age) / modified_txsize\n            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n            dPriority = tx.ComputePriority(dPriority, nTxSize);\n            \n            CAmount nDeltaValueIn = nTotalIn + (nTotalReserveIn ? currencyState.ReserveToNative(nTotalReserveIn) : 0);\n            CAmount nFeeValueIn = nDeltaValueIn;\n            mempool.ApplyDeltas(hash, dPriority, nDeltaValueIn);\n\n            CAmount nativeEquivalentOut = 0;\n\n            // if there is reserve in, or this is a reserveexchange transaction, calculate fee properly\n            if (isReserve & rtxd.reserveOut)\n            {\n                // if this has reserve currency out, convert it to native currency for fee calculation\n                nativeEquivalentOut = currencyState.ReserveToNative(rtxd.reserveOut);\n            }\n\n            CFeeRate feeRate(isReserve ? rtxd.AllFeesAsNative(currencyState) + currencyState.ReserveToNative(rtxd.reserveConversionFees) + rtxd.nativeConversionFees : nFeeValueIn - (tx.GetValueOut() + nativeEquivalentOut), nTxSize);\n\n            if (porphan)\n            {\n                porphan->dPriority = dPriority;\n                porphan->feeRate = feeRate;\n            }\n            else\n                vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));\n        }\n\n        //\n        // NOW -- REALLY START TO FILL THE BLOCK\n        //\n        // estimate number of conversions, staking transaction size, and additional coinbase outputs that will be required\n\n        int32_t maxPreLimitOrderBlockSize = nBlockMaxSize - std::min(nBlockMaxSize >> 2, reserveExchangeLimitSize);\n\n        int64_t interest;\n        bool fSortedByFee = (nBlockPrioritySize <= 0);\n\n        TxPriorityCompare comparer(fSortedByFee);\n        std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);\n\n        std::vector<int> reservePositions;\n\n        // now loop and fill the block, leaving space for reserve exchange limit transactions\n        while (!vecPriority.empty())\n        {\n            // Take highest priority transaction off the priority queue:\n            double dPriority = vecPriority.front().get<0>();\n            CFeeRate feeRate = vecPriority.front().get<1>();\n            const CTransaction& tx = *(vecPriority.front().get<2>());\n            \n            std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);\n            vecPriority.pop_back();\n            \n            // Size limits\n            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n            if (nBlockSize + nTxSize >= maxPreLimitOrderBlockSize - autoTxSize) // room for extra autotx\n            {\n                //fprintf(stderr,\"nBlockSize %d + %d nTxSize >= %d maxPreLimitOrderBlockSize\\n\",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)maxPreLimitOrderBlockSize);\n                continue;\n            }\n            \n            // Legacy limits on sigOps:\n            unsigned int nTxSigOps = GetLegacySigOpCount(tx);\n            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)\n            {\n                //fprintf(stderr,\"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\\n\",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);\n                continue;\n            }\n            // Skip free transactions if we're past the minimum block size:\n            const uint256& hash = tx.GetHash();\n            double dPriorityDelta = 0;\n            CAmount nFeeDelta = 0;\n            mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);\n            if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))\n            {\n                //fprintf(stderr,\"fee rate skip\\n\");\n                continue;\n            }\n\n            // Prioritise by fee once past the priority size or we run out of high-priority\n            // transactions:\n            if (!fSortedByFee &&\n                ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))\n            {\n                fSortedByFee = true;\n                comparer = TxPriorityCompare(fSortedByFee);\n                std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);\n            }\n            \n            if (!view.HaveInputs(tx))\n            {\n                //fprintf(stderr,\"dont have inputs\\n\");\n                continue;\n            }\n            CAmount nTxFees;\n            CReserveTransactionDescriptor txDesc;\n            bool isReserve = mempool.IsKnownReserveTransaction(hash, txDesc);\n\n            nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut();\n            \n            nTxSigOps += GetP2SHSigOpCount(tx, view);\n            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)\n            {\n                //fprintf(stderr,\"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\\n\",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);\n                continue;\n            }\n\n            // Note that flags: we don't want to set mempool/IsStandard()\n            // policy here, but we still have to ensure that the block we\n            // create only contains transactions that are valid in new blocks.\n            CValidationState state;\n            PrecomputedTransactionData txdata(tx);\n            if (!ContextualCheckInputs(tx, state, view, nHeight, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))\n            {\n                //fprintf(stderr,\"context failure\\n\");\n                continue;\n            }\n\n            UpdateCoins(tx, view, nHeight);\n\n            if (isReserve)\n            {\n                nTxFees = 0;            // we will adjust all reserve transaction fees when we get an accurate conversion rate\n                reservePositions.push_back(nBlockTx);\n                haveReserveTransactions = true;\n            }\n\n            BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {\n                sapling_tree.append(outDescription.cm);\n            }\n\n            // Added\n            pblock->vtx.push_back(tx);\n            pblocktemplate->vTxFees.push_back(nTxFees);\n            pblocktemplate->vTxSigOps.push_back(nTxSigOps);\n            nBlockSize += nTxSize;\n            ++nBlockTx;\n            nBlockSigOps += nTxSigOps;\n            nFees += nTxFees;\n            \n            if (fPrintPriority)\n            {\n                LogPrintf(\"priority %.1f fee %s txid %s\\n\",dPriority, feeRate.ToString(), tx.GetHash().ToString());\n            }\n            \n            // Add transactions that depend on this one to the priority queue\n            if (mapDependers.count(hash))\n            {\n                BOOST_FOREACH(COrphan* porphan, mapDependers[hash])\n                {\n                    if (!porphan->setDependsOn.empty())\n                    {\n                        porphan->setDependsOn.erase(hash);\n                        if (porphan->setDependsOn.empty())\n                        {\n                            vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));\n                            std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);\n                        }\n                    }\n                }\n            }\n        }\n\n        // if we have reserve transactions or limit transactions to add:\n        // 1. collect all the reserve transactions from the block and add them to the reserveFills vector\n        // 2. add all limit transactions to the orders vector\n        // 3. match orders to include all limit transactions that qualify and will fit\n        CAmount conversionFees = 0;\n\n        if (haveReserveTransactions)\n        {\n            std::vector<CReserveTransactionDescriptor> reserveFills;\n            std::vector<const CTransaction *> expiredFillOrKills;\n            std::vector<const CTransaction *> noFills;\n            std::vector<const CTransaction *> rejects;\n\n            // identify all reserve transactions in the block to calculate fees\n            for (int i = 0; i < reservePositions.size(); i++)\n            {\n                CReserveTransactionDescriptor txDesc;\n                if (mempool.IsKnownReserveTransaction(pblock->vtx[reservePositions[i]].GetHash(), txDesc))\n                {\n                    reserveFills.push_back(txDesc);\n                }\n            }\n\n            // now, we need to have room for the transaction which will spend the coinbase\n            // and output all conversions mined/staked\n            newConversionOutputTx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight);\n            newConversionOutputTx.vin.resize(1); // placeholder for size calculation\n\n            int64_t newBlockSize = nBlockSize;\n\n            // TODO:PBAAS - NEED TO ADD SIGOPS LIMIT TO THIS FOR HARDENING\n            CCoinbaseCurrencyState newState = currencyState.MatchOrders(limitOrders,\n                                                                        reserveFills,\n                                                                        expiredFillOrKills,\n                                                                        noFills,\n                                                                        rejects,\n                                                                        exchangeRate, nHeight, conversionInputs,\n                                                                        nBlockMaxSize - autoTxSize, &newBlockSize, &newConversionOutputTx);\n\n            // TODO:PBAAS - account for the edge case where we have too large expected fills and have no room\n            // for transactions that we would otherwise take\n            assert(reserveFills.size() >= reservePositions.size());\n\n            // create the conversion transaction and all outputs indicated by every single mined transaction\n            if (reserveFills.size())\n            {\n                currencyState = newState;\n            }\n\n            int oldRPSize = reservePositions.size();\n\n            // add the rest of the reserve fills that have not yet been added to the block,\n            for (int i = oldRPSize; i < reserveFills.size(); i++)\n            {\n                // add these transactions to the block\n                reservePositions.push_back(nBlockTx);\n                pblock->vtx.push_back(*reserveFills[i].ptx);\n                const CTransaction &tx = pblock->vtx.back();\n\n                UpdateCoins(tx, view, nHeight);\n\n                BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {\n                    sapling_tree.append(outDescription.cm);\n                }\n\n                CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate);\n                uint32_t nTxSigOps = GetLegacySigOpCount(tx);\n\n                // size was already updated\n                pblocktemplate->vTxFees.push_back(nTxFees);\n                pblocktemplate->vTxSigOps.push_back(nTxSigOps);\n                ++nBlockTx;\n                nBlockSigOps += nTxSigOps;\n                nFees += nTxFees;\n            }\n\n            // update block size with the calculation from the function called, which includes all additional transactions, \n            // but does not include the conversion transaction, since its final size is still unknown\n            nBlockSize = newBlockSize;\n\n            // fixup the transaction block template fees that were added before we knew the correct exchange rate and\n            // add them to the block fee total\n            for (int i = 0; i < oldRPSize; i++)\n            {\n                assert(pblocktemplate->vTxFees.size() > reservePositions[i]);\n                CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate);\n                pblocktemplate->vTxFees[reservePositions[i]] = nTxFees;\n                nFees += nTxFees;\n            }\n\n            // remake the newConversionOutputTx, right now, it has dummy inputs and placeholder outputs, just remake it correctly\n            newConversionOutputTx.vin.resize(1);\n            newConversionOutputTx.vout.clear();\n            conversionInputs.clear();\n\n            // keep one placeholder for txCoinbase output as input and remake with the correct exchange rate\n            for (auto fill : reserveFills)\n            {\n                fill.AddConversionInOuts(newConversionOutputTx, conversionInputs, exchangeRate, &currencyState);\n            }\n        }\n\n        // first calculate and distribute block rewards, including fees in the minerOutputs vector\n        CAmount rewardTotalShareAmount = 0;\n        CAmount rewardTotal = blockSubsidy + currencyState.ConversionFees + nFees;\n\n        CAmount rewardLeft = notarizationTxIndex ? rewardTotal - notarizationOut.nValue : rewardTotal;\n\n        for (auto &outputShare : minerOutputs)\n        {\n            rewardTotalShareAmount += outputShare.first;\n        }\n\n        int cbOutIdx;\n        for (cbOutIdx = 0; cbOutIdx < minerOutputs.size(); cbOutIdx++)\n        {\n            CAmount amount = (arith_uint256(rewardTotal) * arith_uint256(minerOutputs[cbOutIdx].first) / arith_uint256(rewardTotalShareAmount)).GetLow64();\n            if (rewardLeft <= amount || (cbOutIdx + 1) == minerOutputs.size())\n            {\n                amount = rewardLeft;\n            }\n            rewardLeft -= amount;\n            coinbaseTx.vout[cbOutIdx].nValue = amount;\n            // the only valid CC output we currently support on coinbases is stake guard, which does not need to be modified for this\n        }\n\n        // premineOut - done\n        if (premineOut.scriptPubKey.size())\n        {\n            cbOutIdx++;\n        }\n\n        // chainDefinitionOut - done\n        if (chainDefinitionOut.scriptPubKey.size())\n        {\n            cbOutIdx++;\n        }\n\n        // importThreadOut - done\n        if (importThreadOut.scriptPubKey.size())\n        {\n            cbOutIdx++;\n        }\n\n        // exportThreadOut - done\n        if (exportThreadOut.scriptPubKey.size())\n        {\n            cbOutIdx++;\n        }\n\n        // currencyStateOut - update currency state, output is present whether or not there is a conversion transaction\n        // the transaction itself pays no fees, but all conversion fees are included for each conversion transaction between its input and this output\n        if (currencyStateOut.scriptPubKey.size())\n        {\n            COptCCParams p;\n            currencyStateOut.scriptPubKey.IsPayToCryptoCondition(p);\n            p.vData[0] = currencyState.AsVector();\n            currencyStateOut.scriptPubKey.ReplaceCCParams(p);\n\n            if (conversionInputs.size())\n            {\n                CTransaction convertTx(newConversionOutputTx);\n                currencyStateOut.nValue = convertTx.GetValueOut();\n                currencyState.ReserveOut.nValue = convertTx.GetReserveValueOut();\n\n                // the coinbase is not finished, store index placeholder here now and fixup hash later\n                newConversionOutputTx.vin[0] = CTxIn(uint256(), cbOutIdx);\n            }\n            else\n            {\n                newConversionOutputTx.vin.clear();\n                newConversionOutputTx.vout.clear();\n            }\n\n            coinbaseTx.vout[cbOutIdx] = currencyStateOut;\n            cbOutIdx++;\n        }\n\n        // notarizationOut - update currencyState in notarization\n        if (notarizationTxIndex)\n        {\n            COptCCParams p;\n            int i;\n            for (i = 0; i < newNotarizationTx.vout.size(); i++)\n            {\n                if (newNotarizationTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.evalCode == EVAL_EARNEDNOTARIZATION)\n                {\n                    break;\n                }\n            }\n            if (i >= newNotarizationTx.vout.size())\n            {\n                LogPrintf(\"CreateNewBlock: bad notarization\\n\");\n                fprintf(stderr,\"CreateNewBlock: bad notarization\\n\");\n                return NULL;\n            }\n            CPBaaSNotarization nz(p.vData[0]);\n            nz.currencyState = currencyState;\n            p.vData[0] = nz.AsVector();\n            newNotarizationTx.vout[i].scriptPubKey.ReplaceCCParams(p);\n\n            notarizationOut.scriptPubKey.IsPayToCryptoCondition(p);\n            p.vData[0] = nz.AsVector();\n            notarizationOut.scriptPubKey.ReplaceCCParams(p);\n\n            coinbaseTx.vout[cbOutIdx] = notarizationOut;\n\n            // now that the coinbase is finished, finish and place conversion transaction before the stake transaction\n            newNotarizationTx.vin.push_back(CTxIn(uint256(), cbOutIdx));\n\n            cbOutIdx++;\n\n            pblock->vtx[notarizationTxIndex] = newNotarizationTx;\n        }\n\n        // this should be the end of the outputs\n        assert(cbOutIdx == coinbaseTx.vout.size());\n\n        nLastBlockTx = nBlockTx;\n        nLastBlockSize = nBlockSize;\n\n        blocktime = std::max(pindexPrev->GetMedianTimePast(), GetAdjustedTime());\n\n        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());\n\n        coinbaseTx.nExpiryHeight = 0;\n        coinbaseTx.nLockTime = blocktime;\n\n        if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )\n            coinbaseTx.vout[0].nValue += 5000;\n\n        /*\n        // check if coinbase transactions must be time locked at current subsidy and prepend the time lock\n        // to transaction if so, cast for GTE operator\n        CAmount cbValueOut = 0;\n        for (auto txout : coinbaseTx.vout)\n        {\n            cbValueOut += txout.nValue;\n        }\n        if (cbValueOut >= ASSETCHAINS_TIMELOCKGTE)\n        {\n            int32_t opretlen, p2shlen, scriptlen;\n            CScriptExt opretScript = CScriptExt();\n\n            coinbaseTx.vout.push_back(CTxOut());\n\n            // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins\n            // protected only by the time lock rather than 100% inaccessible\n            opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));\n            if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition())\n            {\n                LogPrintf(\"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\\n\");\n                fprintf(stderr,\"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\\n\");\n                return 0;\n            }\n            \n            opretScript += scriptPubKeyIn;\n\n            coinbaseTx.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));\n            coinbaseTx.vout.back().scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);\n            coinbaseTx.vout.back().nValue = 0;\n        } // timelocks and commissions are currently incompatible due to validation complexity of the combination\n        else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )\n        {\n            int32_t i; uint8_t *ptr;\n            coinbaseTx.vout.resize(2);\n            coinbaseTx.vout[1].nValue = commission;\n            coinbaseTx.vout[1].scriptPubKey.resize(35);\n            ptr = (uint8_t *)&coinbaseTx.vout[1].scriptPubKey[0];\n            ptr[0] = 33;\n            for (i=0; i<33; i++)\n                ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];\n            ptr[34] = OP_CHECKSIG;\n            //printf(\"autocreate commision vout\\n\");\n        }\n        */\n\n        // finalize input of coinbase\n        coinbaseTx.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(0)) + COINBASE_FLAGS;\n        assert(coinbaseTx.vin[0].scriptSig.size() <= 100);\n\n        // coinbase is done\n        pblock->vtx[0] = coinbaseTx;\n        uint256 cbHash = coinbaseTx.GetHash();\n\n        // if there is a conversion, update the correct coinbase hash and add it to the block\n        // we also need to sign the conversion transaction\n        if (newConversionOutputTx.vin.size() > 1)\n        {\n            // put the coinbase into the updated coins, since we will spend from it\n            UpdateCoins(pblock->vtx[0], view, nHeight);\n\n            newConversionOutputTx.vin[0].prevout.hash = cbHash;\n\n            CTransaction ncoTx(newConversionOutputTx);\n\n            // sign transaction for cb output and conversions\n            for (int i = 0; i < ncoTx.vin.size(); i++)\n            {\n                bool signSuccess;\n                SignatureData sigdata;\n                CAmount value;\n                const CScript *pScriptPubKey;\n\n                // if this is our coinbase input, different signing\n                if (i)\n                {\n                    pScriptPubKey = &conversionInputs[i - 1].scriptPubKey;\n                    value = conversionInputs[i - 1].nValue;\n                }\n                else\n                {\n                    pScriptPubKey = &coinbaseTx.vout[ncoTx.vin[i].prevout.n].scriptPubKey;\n                    value = coinbaseTx.vout[ncoTx.vin[i].prevout.n].nValue;\n                }\n\n                signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ncoTx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId);\n\n                if (!signSuccess)\n                {\n                    if (ncoTx.vin[i].prevout.hash == coinbaseTx.GetHash())\n                    {\n                        LogPrintf(\"Coinbase conversion source tx id: %s\\n\", coinbaseTx.GetHash().GetHex().c_str());\n                        printf(\"Coinbase conversion source tx - amount: %lu, n: %d, id: %s\\n\", coinbaseTx.vout[ncoTx.vin[i].prevout.n].nValue, ncoTx.vin[i].prevout.n, coinbaseTx.GetHash().GetHex().c_str());\n                    }\n                    LogPrintf(\"CreateNewBlock: failure to sign conversion tx for input %d from output %d of %s\\n\", i, ncoTx.vin[i].prevout.n, ncoTx.vin[i].prevout.hash.GetHex().c_str());\n                    printf(\"CreateNewBlock: failure to sign conversion tx for input %d from output %d of %s\\n\", i, ncoTx.vin[i].prevout.n, ncoTx.vin[i].prevout.hash.GetHex().c_str());\n                    return NULL;\n                } else {\n                    UpdateTransaction(newConversionOutputTx, i, sigdata);\n                }\n            }\n\n            UpdateCoins(newConversionOutputTx, view, nHeight);\n            pblock->vtx.push_back(newConversionOutputTx);\n            pblocktemplate->vTxFees.push_back(0);\n            int txSigOps = GetLegacySigOpCount(newConversionOutputTx);\n            pblocktemplate->vTxSigOps.push_back(txSigOps);\n            nBlockSize += GetSerializeSize(newConversionOutputTx, SER_NETWORK, PROTOCOL_VERSION);\n            ++nBlockTx;\n            nBlockSigOps += txSigOps;\n        }\n\n        // if there is a stake transaction, add it to the very end\n        if (isStake)\n        {\n            UpdateCoins(txStaked, view, nHeight);\n            pblock->vtx.push_back(txStaked);\n            pblocktemplate->vTxFees.push_back(0);\n            int txSigOps = GetLegacySigOpCount(txStaked);\n            pblocktemplate->vTxSigOps.push_back(txSigOps);\n            // already added to the block size above\n            ++nBlockTx;\n            nBlockSigOps += txSigOps;\n        }\n\n        extern CWallet *pwalletMain;\n\n        // add final notarization and instant spend coinbase output hash fixup\n        if (notarizationTxIndex)\n        {\n            LOCK(pwalletMain->cs_wallet);\n\n            newNotarizationTx.vin.back().prevout.hash = cbHash;\n\n            CTransaction ntx(newNotarizationTx);\n\n            for (int i = 0; i < ntx.vin.size(); i++)\n            {\n                bool signSuccess;\n                SignatureData sigdata;\n                CAmount value;\n                const CScript *pScriptPubKey;\n\n                // if this is our coinbase input, we won't find it elsewhere\n                if (i < notarizationInputs.size())\n                {\n                    pScriptPubKey = &notarizationInputs[i].scriptPubKey;\n                    value = notarizationInputs[i].nValue;\n                }\n                else\n                {\n                    pScriptPubKey = &coinbaseTx.vout[ntx.vin[i].prevout.n].scriptPubKey;\n                    value = coinbaseTx.vout[ntx.vin[i].prevout.n].nValue;\n                }\n\n                signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ntx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId);\n\n                if (!signSuccess)\n                {\n                    if (ntx.vin[i].prevout.hash == coinbaseTx.GetHash())\n                    {\n                        LogPrintf(\"Coinbase source tx id: %s\\n\", coinbaseTx.GetHash().GetHex().c_str());\n                        printf(\"Coinbase source tx - amount: %lu, n: %d, id: %s\\n\", coinbaseTx.vout[ntx.vin[i].prevout.n].nValue, ntx.vin[i].prevout.n, coinbaseTx.GetHash().GetHex().c_str());\n                    }\n                    LogPrintf(\"CreateNewBlock: failure to sign earned notarization for input %d from output %d of %s\\n\", i, ntx.vin[i].prevout.n, ntx.vin[i].prevout.hash.GetHex().c_str());\n                    printf(\"CreateNewBlock: failure to sign earned notarization for input %d from output %d of %s\\n\", i, ntx.vin[i].prevout.n, ntx.vin[i].prevout.hash.GetHex().c_str());\n                    return NULL;\n                } else {\n                    UpdateTransaction(newNotarizationTx, i, sigdata);\n                }\n            }\n            pblocktemplate->vTxSigOps[notarizationTxIndex] = GetLegacySigOpCount(newNotarizationTx);\n\n            // put now signed notarization back in the block\n            pblock->vtx[notarizationTxIndex] = newNotarizationTx;\n\n            LogPrintf(\"Coinbase source tx id: %s\\n\", coinbaseTx.GetHash().GetHex().c_str());\n            //printf(\"Coinbase source tx id: %s\\n\", coinbaseTx.GetHash().GetHex().c_str());\n            LogPrintf(\"adding notarization tx at height %d, index %d, id: %s\\n\", nHeight, notarizationTxIndex, newNotarizationTx.GetHash().GetHex().c_str());\n            //printf(\"adding notarization tx at height %d, index %d, id: %s\\n\", nHeight, notarizationTxIndex, mntx.GetHash().GetHex().c_str());\n            {\n                LOCK(cs_main);\n                for (auto input : newNotarizationTx.vin)\n                {\n                    LogPrintf(\"Earned notarization input n: %d, hash: %s, HaveCoins: %s\\n\", input.prevout.n, input.prevout.hash.GetHex().c_str(), pcoinsTip->HaveCoins(input.prevout.hash) ? \"true\" : \"false\");\n                    //printf(\"Earned notarization input n: %d, hash: %s, HaveCoins: %s\\n\", input.prevout.n, input.prevout.hash.GetHex().c_str(), pcoinsTip->HaveCoins(input.prevout.hash) ? \"true\" : \"false\");\n                }\n            }\n        }\n\n        pblock->vtx[0] = coinbaseTx;\n        pblocktemplate->vTxFees[0] = -nFees;\n        pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);\n\n        // if not Verus stake, setup nonce, otherwise, leave it alone\n        if (!isStake || ASSETCHAINS_LWMAPOS == 0)\n        {\n            // Randomize nonce\n            arith_uint256 nonce = UintToArith256(GetRandHash());\n\n            // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)\n            nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];\n            nonce >>= 16;\n            pblock->nNonce = ArithToUint256(nonce);\n        }\n        \n        // Fill in header\n        pblock->hashPrevBlock  = pindexPrev->GetBlockHash();\n        pblock->hashFinalSaplingRoot   = sapling_tree.root();\n\n        // all Verus PoS chains need this data in the block at all times\n        if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 )\n        {\n            UpdateTime(pblock, Params().GetConsensus(), pindexPrev);\n            pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());\n        }\n\n        if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )\n        {\n            uint32_t r;\n            CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);\n            if ( pblock->nTime < pindexPrev->nTime+60 )\n                pblock->nTime = pindexPrev->nTime + 60;\n            if ( gpucount < 33 )\n            {\n                uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals;\n                memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid);\n                memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height);\n                memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock);\n                vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n);\n                memcpy(&r,&randvals,sizeof(r));\n                pblock->nTime += (r % (33 - gpucount)*(33 - gpucount));\n            }\n            if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )\n            {\n                CAmount txfees = 5000;\n                pblock->vtx.push_back(txNotary);\n                pblocktemplate->vTxFees.push_back(txfees);\n                pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));\n                nFees += txfees;\n                pblocktemplate->vTxFees[0] = -nFees;\n                //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;\n                //fprintf(stderr,\"added notaryvin\\n\");\n            }\n            else\n            {\n                fprintf(stderr,\"error adding notaryvin, need to create 0.0001 utxos\\n\");\n                return(0);\n            }\n        }\n        else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )\n        {\n            CValidationState state;\n            //fprintf(stderr,\"check validity\\n\");\n            if ( !TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) // invokes CC checks\n            {\n                throw std::runtime_error(\"CreateNewBlock(): TestBlockValidity failed\");\n            }\n            //fprintf(stderr,\"valid\\n\");\n        }\n    }\n    //fprintf(stderr,\"done new block\\n\");\n\n    // setup the header and buid the Merkle tree\n    unsigned int extraNonce;\n    IncrementExtraNonce(pblock, pindexPrev, extraNonce, true);\n\n    return pblocktemplate.release();\n}\n \n/*\n #ifdef ENABLE_WALLET\n boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)\n #else\n boost::optional<CScript> GetMinerScriptPubKey()\n #endif\n {\n CKeyID keyID;\n CBitcoinAddress addr;\n if (addr.SetString(GetArg(\"-mineraddress\", \"\"))) {\n addr.GetKeyID(keyID);\n } else {\n #ifdef ENABLE_WALLET\n CPubKey pubkey;\n if (!reservekey.GetReservedKey(pubkey)) {\n return boost::optional<CScript>();\n }\n keyID = pubkey.GetID();\n #else\n return boost::optional<CScript>();\n #endif\n }\n \n CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;\n return scriptPubKey;\n }\n \n #ifdef ENABLE_WALLET\n CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)\n {\n boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);\n #else\n CBlockTemplate* CreateNewBlockWithKey()\n {\n boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();\n #endif\n \n if (!scriptPubKey) {\n return NULL;\n }\n return CreateNewBlock(*scriptPubKey);\n }*/\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Internal miner\n//\n\n#ifdef ENABLE_MINING\n\nclass MinerAddressScript : public CReserveScript\n{\n    // CReserveScript requires implementing this function, so that if an\n    // internal (not-visible) wallet address is used, the wallet can mark it as\n    // important when a block is mined (so it then appears to the user).\n    // If -mineraddress is set, the user already knows about and is managing the\n    // address, so we don't need to do anything here.\n    void KeepScript() {}\n};\n\nvoid GetScriptForMinerAddress(boost::shared_ptr<CReserveScript> &script)\n{\n    CTxDestination addr = DecodeDestination(GetArg(\"-mineraddress\", \"\"));\n    if (!IsValidDestination(addr)) {\n        return;\n    }\n\n    boost::shared_ptr<MinerAddressScript> mAddr(new MinerAddressScript());\n    CKeyID keyID = boost::get<CKeyID>(addr);\n\n    script = mAddr;\n    script->reserveScript = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;\n}\n\n#ifdef ENABLE_WALLET\n//////////////////////////////////////////////////////////////////////////////\n//\n// Internal miner\n//\n\nCBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake)\n{\n    CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i;\n    if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )\n    {\n        scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;\n    }\n    else if ( USE_EXTERNAL_PUBKEY != 0 )\n    {\n        //fprintf(stderr,\"use notary pubkey\\n\");\n        scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;\n    }\n    else\n    {\n        if (!isStake)\n        {\n            if (!reservekey.GetReservedKey(pubkey))\n            {\n                return NULL;\n            }\n            scriptPubKey.resize(35);\n            ptr = (uint8_t *)pubkey.begin();\n            scriptPubKey[0] = 33;\n            for (i=0; i<33; i++)\n                scriptPubKey[i+1] = ptr[i];\n            scriptPubKey[34] = OP_CHECKSIG;\n            //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;\n        }\n    }\n    return CreateNewBlock(Params(), scriptPubKey, gpucount, isStake);\n}\n\nvoid komodo_broadcast(const CBlock *pblock,int32_t limit)\n{\n    int32_t n = 1;\n    //fprintf(stderr,\"broadcast new block t.%u\\n\",(uint32_t)time(NULL));\n    {\n        LOCK(cs_vNodes);\n        BOOST_FOREACH(CNode* pnode, vNodes)\n        {\n            if ( pnode->hSocket == INVALID_SOCKET )\n                continue;\n            if ( (rand() % n) == 0 )\n            {\n                pnode->PushMessage(\"block\", *pblock);\n                if ( n++ > limit )\n                    break;\n            }\n        }\n    }\n    //fprintf(stderr,\"finished broadcast new block t.%u\\n\",(uint32_t)time(NULL));\n}\n\nstatic bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)\n#else\nstatic bool ProcessBlockFound(CBlock* pblock)\n#endif // ENABLE_WALLET\n{\n    int32_t height = chainActive.LastTip()->GetHeight()+1;\n    LogPrintf(\"%s\\n\", pblock->ToString());\n    LogPrintf(\"generated %s height.%d\\n\", FormatMoney(pblock->vtx[0].vout[0].nValue), height);\n    \n    // Found a solution\n    {\n        if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())\n        {\n            uint256 hash; int32_t i;\n            hash = pblock->hashPrevBlock;\n            for (i=31; i>=0; i--)\n                fprintf(stderr,\"%02x\",((uint8_t *)&hash)[i]);\n            fprintf(stderr,\" <- prev (stale)\\n\");\n            hash = chainActive.LastTip()->GetBlockHash();\n            for (i=31; i>=0; i--)\n                fprintf(stderr,\"%02x\",((uint8_t *)&hash)[i]);\n            fprintf(stderr,\" <- chainTip (stale)\\n\");\n            \n            return error(\"VerusMiner: generated block is stale\");\n        }\n    }\n    \n#ifdef ENABLE_WALLET\n    // Remove key from key pool\n    if ( IS_KOMODO_NOTARY == 0 )\n    {\n        if (GetArg(\"-mineraddress\", \"\").empty()) {\n            // Remove key from key pool\n            reservekey.KeepKey();\n        }\n    }\n    // Track how many getdata requests this block gets\n    //if ( 0 )\n    {\n        //fprintf(stderr,\"lock cs_wallet\\n\");\n        LOCK(wallet.cs_wallet);\n        wallet.mapRequestCount[pblock->GetHash()] = 0;\n    }\n#endif\n    //fprintf(stderr,\"process new block\\n\");\n\n    // Process this block (almost) the same as if we had received it from another node\n    CValidationState state;\n    if (!ProcessNewBlock(1, chainActive.LastTip()->GetHeight()+1, state, Params(), NULL, pblock, true, NULL))\n        return error(\"VerusMiner: ProcessNewBlock, block not accepted\");\n    \n    TrackMinedBlock(pblock->GetHash());\n    komodo_broadcast(pblock,16);\n    return true;\n}\n\nint32_t komodo_baseid(char *origbase);\nint32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);\narith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);\nint32_t FOUND_BLOCK,KOMODO_MAYBEMINED;\nextern int32_t KOMODO_LASTMINED,KOMODO_INSYNC;\nint32_t roundrobin_delay;\narith_uint256 HASHTarget,HASHTarget_POW;\nint32_t komodo_longestchain();\n\n// wait for peers to connect\nvoid waitForPeers(const CChainParams &chainparams)\n{\n    if (chainparams.MiningRequiresPeers())\n    {\n        bool fvNodesEmpty;\n        {\n            boost::this_thread::interruption_point();\n            LOCK(cs_vNodes);\n            fvNodesEmpty = vNodes.empty();\n        }\n        int longestchain = komodo_longestchain();\n        int lastlongest = 0;\n        if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight()))\n        {\n            int loops = 0, blockDiff = 0, newDiff = 0;\n            \n            do {\n                if (fvNodesEmpty)\n                {\n                    MilliSleep(1000 + rand() % 4000);\n                    boost::this_thread::interruption_point();\n                    LOCK(cs_vNodes);\n                    fvNodesEmpty = vNodes.empty();\n                    loops = 0;\n                    blockDiff = 0;\n                    lastlongest = 0;\n                }\n                else if ((newDiff = IsNotInSync()) > 0)\n                {\n                    if (blockDiff != newDiff)\n                    {\n                        blockDiff = newDiff;\n                    }\n                    else\n                    {\n                        if (++loops <= 5)\n                        {\n                            MilliSleep(1000);\n                        }\n                        else break;\n                    }\n                    lastlongest = 0;\n                }\n                else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight())\n                {\n                    // the only thing may be that we are seeing a long chain that we'll never get\n                    // don't wait forever\n                    if (lastlongest == 0)\n                    {\n                        MilliSleep(3000);\n                        lastlongest = longestchain;\n                    }\n                }\n            } while (fvNodesEmpty || IsNotInSync());\n            MilliSleep(100 + rand() % 400);\n        }\n    }\n}\n\n#ifdef ENABLE_WALLET\nCBlockIndex *get_chainactive(int32_t height)\n{\n    if ( chainActive.LastTip() != 0 )\n    {\n        if ( height <= chainActive.LastTip()->GetHeight() )\n        {\n            LOCK(cs_main);\n            return(chainActive[height]);\n        }\n        // else fprintf(stderr,\"get_chainactive height %d > active.%d\\n\",height,chainActive.Tip()->GetHeight());\n    }\n    //fprintf(stderr,\"get_chainactive null chainActive.Tip() height %d\\n\",height);\n    return(0);\n}\n\n/*\n * A separate thread to stake, while the miner threads mine.\n */\nvoid static VerusStaker(CWallet *pwallet)\n{\n    LogPrintf(\"Verus staker thread started\\n\");\n    RenameThread(\"verus-staker\");\n\n    const CChainParams& chainparams = Params();\n    auto consensusParams = chainparams.GetConsensus();\n\n    // Each thread has its own key\n    CReserveKey reservekey(pwallet);\n\n    // Each thread has its own counter\n    unsigned int nExtraNonce = 0;\n\n    uint8_t *script; uint64_t total,checktoshis; int32_t i,j;\n\n    while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&\n    {\n        sleep(1);\n        if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )\n            break;\n    }\n\n    // try a nice clean peer connection to start\n    CBlockIndex *pindexPrev, *pindexCur;\n    do {\n        pindexPrev = chainActive.LastTip();\n        MilliSleep(5000 + rand() % 5000);\n        waitForPeers(chainparams);\n        pindexCur = chainActive.LastTip();\n    } while (pindexPrev != pindexCur);\n\n    try {\n        static int32_t lastStakingHeight = 0;\n\n        while (true)\n        {\n            waitForPeers(chainparams);\n            CBlockIndex* pindexPrev = chainActive.LastTip();\n\n            // Create new block\n            unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();\n\n            if ( Mining_height != pindexPrev->GetHeight()+1 )\n            {\n                Mining_height = pindexPrev->GetHeight()+1;\n                Mining_start = (uint32_t)time(NULL);\n            }\n\n            // Check for stop or if block needs to be rebuilt\n            boost::this_thread::interruption_point();\n\n            // try to stake a block\n            CBlockTemplate *ptr = NULL;\n            if (Mining_height > VERUS_MIN_STAKEAGE)\n                ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true);\n\n            // TODO - putting this output here tends to help mitigate announcing a staking height earlier than\n            // announcing the last block win when we start staking before a block's acceptance has been\n            // acknowledged by the mining thread - a better solution may be to put the output on the submission\n            // thread.\n            if ( ptr == 0 && Mining_height != lastStakingHeight )\n            {\n                printf(\"Staking height %d for %s\\n\", Mining_height, ASSETCHAINS_SYMBOL);\n            }\n            lastStakingHeight = Mining_height;\n\n            if ( ptr == 0 )\n            {\n                // wait to try another staking block until after the tip moves again\n                while ( chainActive.LastTip() == pindexPrev )\n                    MilliSleep(250);\n                continue;\n            }\n\n            unique_ptr<CBlockTemplate> pblocktemplate(ptr);\n            if (!pblocktemplate.get())\n            {\n                if (GetArg(\"-mineraddress\", \"\").empty()) {\n                    LogPrintf(\"Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\\n\",\n                              ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n                } else {\n                    // Should never reach here, because -mineraddress validity is checked in init.cpp\n                    LogPrintf(\"Error in %s staker: Invalid %s -mineraddress\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);\n                }\n                return;\n            }\n\n            CBlock *pblock = &pblocktemplate->block;\n            LogPrintf(\"Staking with %u transactions in block (%u bytes)\\n\", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));\n            //\n            // Search\n            //\n            int64_t nStart = GetTime();\n\n            if (vNodes.empty() && chainparams.MiningRequiresPeers())\n            {\n                if ( Mining_height > ASSETCHAINS_MINHEIGHT )\n                {\n                    fprintf(stderr,\"no nodes, attempting reconnect\\n\");\n                    continue;\n                }\n            }\n\n            if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)\n            {\n                fprintf(stderr,\"timeout, retrying\\n\");\n                continue;\n            }\n\n            if ( pindexPrev != chainActive.LastTip() )\n            {\n                printf(\"Block %d added to chain\\n\", chainActive.LastTip()->GetHeight());\n                MilliSleep(250);\n                continue;\n            }\n\n            int32_t unlockTime = komodo_block_unlocktime(Mining_height);\n            int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);\n\n            uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));\n\n            pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);\n\n            UpdateTime(pblock, consensusParams, pindexPrev);\n\n            if (ProcessBlockFound(pblock, *pwallet, reservekey))\n            {\n                LogPrintf(\"Using %s algorithm:\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n                LogPrintf(\"Staked block found  \\n  hash: %s  \\ntarget: %s\\n\", pblock->GetHash().GetHex(), hashTarget.GetHex());\n                printf(\"Found block %d \\n\", Mining_height );\n                printf(\"staking reward %.8f %s!\\n\", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);\n                arith_uint256 post;\n                post.SetCompact(pblock->GetVerusPOSTarget());\n                pindexPrev = get_chainactive(Mining_height - 100);\n                CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1];\n                printf(\"POS hash: %s  \\ntarget:   %s\\n\", \n                    CTransaction::_GetVerusPOSHash(&(pblock->nNonce), sTx.vin[0].prevout.hash, sTx.vin[0].prevout.n, Mining_height, pindexPrev->GetBlockHeader().GetVerusEntropyHash(Mining_height - 100), sTx.vout[0].nValue).GetHex().c_str(), ArithToUint256(post).GetHex().c_str());\n                if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)\n                    printf(\"- timelocked until block %i\\n\", unlockTime);\n                else\n                    printf(\"\\n\");\n            }\n            else\n            {\n                LogPrintf(\"Found block rejected at staking height: %d\\n\", Mining_height);\n                printf(\"Found block rejected at staking height: %d\\n\", Mining_height);\n            }\n\n            // Check for stop or if block needs to be rebuilt\n            boost::this_thread::interruption_point();\n\n            sleep(3);\n\n            // In regression test mode, stop mining after a block is found.\n            if (chainparams.MineBlocksOnDemand()) {\n                throw boost::thread_interrupted();\n            }\n        }\n    }\n    catch (const boost::thread_interrupted&)\n    {\n        LogPrintf(\"VerusStaker terminated\\n\");\n        throw;\n    }\n    catch (const std::runtime_error &e)\n    {\n        LogPrintf(\"VerusStaker runtime error: %s\\n\", e.what());\n        return;\n    }\n}\n\ntypedef bool (*minefunction)(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);\nbool mine_verus_v2(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);\nbool mine_verus_v2_port(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);\n\nvoid static BitcoinMiner_noeq(CWallet *pwallet)\n#else\nvoid static BitcoinMiner_noeq()\n#endif\n{\n    LogPrintf(\"%s miner started\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n    RenameThread(\"verushash-miner\");\n\n#ifdef ENABLE_WALLET\n    // Each thread has its own key\n    CReserveKey reservekey(pwallet);\n#endif\n\n    miningTimer.clear();\n\n    const CChainParams& chainparams = Params();\n    // Each thread has its own counter\n    unsigned int nExtraNonce = 0;\n\n    uint8_t *script; uint64_t total,checktoshis; int32_t i,j;\n\n    while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&\n    {\n        sleep(1);\n        if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )\n            break;\n    }\n\n    SetThreadPriority(THREAD_PRIORITY_LOWEST);\n\n    // try a nice clean peer connection to start\n    CBlockIndex *pindexPrev, *pindexCur;\n    do {\n        pindexPrev = chainActive.LastTip();\n        MilliSleep(5000 + rand() % 5000);\n        waitForPeers(chainparams);\n        pindexCur = chainActive.LastTip();\n    } while (pindexPrev != pindexCur);\n\n    // make sure that we have checked for PBaaS availability\n    ConnectedChains.CheckVerusPBaaSAvailable();\n\n    // this will not stop printing more than once in all cases, but it will allow us to print in all cases\n    // and print duplicates rarely without having to synchronize\n    static CBlockIndex *lastChainTipPrinted;\n    static int32_t lastMiningHeight = 0;\n\n    miningTimer.start();\n\n    try {\n        printf(\"Mining %s with %s\\n\", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n\n        while (true)\n        {\n            miningTimer.stop();\n            waitForPeers(chainparams);\n\n            pindexPrev = chainActive.LastTip();\n\n            // prevent forking on startup before the diff algorithm kicks in,\n            // but only for a startup Verus test chain. PBaaS chains have the difficulty inherited from\n            // their parent\n            if (chainparams.MiningRequiresPeers() && ((IsVerusActive() && pindexPrev->GetHeight() < 50) || pindexPrev != chainActive.LastTip()))\n            {\n                do {\n                    pindexPrev = chainActive.LastTip();\n                    MilliSleep(2000 + rand() % 2000);\n                } while (pindexPrev != chainActive.LastTip());\n            }\n\n            // Create new block\n            unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();\n            if ( Mining_height != pindexPrev->GetHeight()+1 )\n            {\n                Mining_height = pindexPrev->GetHeight()+1;\n                if (lastMiningHeight != Mining_height)\n                {\n                    lastMiningHeight = Mining_height;\n                    printf(\"Mining %s at height %d\\n\", ASSETCHAINS_SYMBOL, Mining_height);\n                }\n                Mining_start = (uint32_t)time(NULL);\n            }\n\n            miningTimer.start();\n\n#ifdef ENABLE_WALLET\n            CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);\n#else\n            CBlockTemplate *ptr = CreateNewBlockWithKey();\n#endif\n            if ( ptr == 0 )\n            {\n                static uint32_t counter;\n                if ( counter++ % 40 == 0 )\n                {\n                    if (!IsVerusActive() &&\n                        ConnectedChains.IsVerusPBaaSAvailable() &&\n                        ConnectedChains.notaryChainHeight < ConnectedChains.ThisChain().startBlock)\n                    {\n                        fprintf(stderr,\"Waiting for block %d on %s chain to start. Current block is %d\\n\", ConnectedChains.ThisChain().startBlock,\n                                                                                                           ConnectedChains.notaryChain.chainDefinition.name.c_str(),\n                                                                                                           ConnectedChains.notaryChainHeight);\n                    }\n                    else\n                    {\n                        fprintf(stderr,\"Unable to create valid block... will continue to try\\n\");\n                    }\n                }\n                MilliSleep(2000);\n                continue;\n            }\n\n            unique_ptr<CBlockTemplate> pblocktemplate(ptr);\n            if (!pblocktemplate.get())\n            {\n                if (GetArg(\"-mineraddress\", \"\").empty()) {\n                    LogPrintf(\"Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\\n\",\n                              ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n                } else {\n                    // Should never reach here, because -mineraddress validity is checked in init.cpp\n                    LogPrintf(\"Error in %s miner: Invalid %s -mineraddress\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);\n                }\n                miningTimer.stop();\n                miningTimer.clear();\n                return;\n            }\n            CBlock *pblock = &pblocktemplate->block;\n\n            uint32_t savebits;\n            bool mergeMining = false;\n            savebits = pblock->nBits;\n\n            uint32_t solutionVersion = CConstVerusSolutionVector::Version(pblock->nSolution);\n            if (pblock->nVersion != CBlockHeader::VERUS_V2)\n            {\n                // must not be in sync\n                printf(\"Mining on incorrect block version.\\n\");\n                sleep(2);\n                continue;\n            }\n            bool verusSolutionPBaaS = solutionVersion >= CActivationHeight::ACTIVATE_PBAAS;\n\n            // v2 hash writer with adjustments for the current height\n            CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION, solutionVersion);\n\n            if ( ASSETCHAINS_SYMBOL[0] != 0 )\n            {\n                if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )\n                {\n                    if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )\n                    {\n                        static uint32_t counter;\n                        if ( counter++ < 10 )\n                            fprintf(stderr,\"skip generating %s on-demand block, no tx avail\\n\",ASSETCHAINS_SYMBOL);\n                        sleep(10);\n                        continue;\n                    } else fprintf(stderr,\"%s vouts.%d mining.%d vs %d\\n\",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);\n                }\n            }\n\n            // set our easiest target, if V3+, no need to rebuild the merkle tree\n            IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, verusSolutionPBaaS ? false : true, &savebits);\n\n            // update PBaaS header\n            if (verusSolutionPBaaS)\n            {\n                if (!IsVerusActive() && ConnectedChains.IsVerusPBaaSAvailable())\n                {\n\n                    UniValue params(UniValue::VARR);\n                    UniValue error(UniValue::VARR);\n                    params.push_back(EncodeHexBlk(*pblock));\n                    params.push_back(ASSETCHAINS_SYMBOL);\n                    params.push_back(ASSETCHAINS_RPCHOST);\n                    params.push_back(ASSETCHAINS_RPCPORT);\n                    params.push_back(ASSETCHAINS_RPCCREDENTIALS);\n                    try\n                    {\n                        ConnectedChains.lastSubmissionFailed = false;\n                        params = RPCCallRoot(\"addmergedblock\", params);\n                        params = find_value(params, \"result\");\n                        error = find_value(params, \"error\");\n                    } catch (std::exception e)\n                    {\n                        printf(\"Failed to connect to %s chain\\n\", ConnectedChains.notaryChain.chainDefinition.name.c_str());\n                        params = UniValue(e.what());\n                    }\n                    if (mergeMining = (params.isNull() && error.isNull()))\n                    {\n                        printf(\"Merge mining %s with %s as the hashing chain\\n\", ASSETCHAINS_SYMBOL, ConnectedChains.notaryChain.chainDefinition.name.c_str());\n                        LogPrintf(\"Merge mining with %s as the hashing chain\\n\", ConnectedChains.notaryChain.chainDefinition.name.c_str());\n                    }\n                }\n            }\n\n            LogPrintf(\"Running %s miner with %u transactions in block (%u bytes)\\n\",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],\n                       pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));\n            //\n            // Search\n            //\n            int64_t nStart = GetTime();\n\n            arith_uint256 hashTarget = arith_uint256().SetCompact(savebits);\n            uint256 uintTarget = ArithToUint256(hashTarget);\n            arith_uint256 ourTarget;\n            ourTarget.SetCompact(pblock->nBits);\n\n            Mining_start = 0;\n\n            if ( pindexPrev != chainActive.LastTip() )\n            {\n                if (lastChainTipPrinted != chainActive.LastTip())\n                {\n                    lastChainTipPrinted = chainActive.LastTip();\n                    printf(\"Block %d added to chain\\n\", lastChainTipPrinted->GetHeight());\n                }\n                MilliSleep(100);\n                continue;\n            }\n\n            if ( ASSETCHAINS_STAKED != 0 )\n            {\n                int32_t percPoS,z;\n                hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED);\n                for (z=31; z>=0; z--)\n                    fprintf(stderr,\"%02x\",((uint8_t *)&hashTarget)[z]);\n                fprintf(stderr,\" PoW for staked coin PoS %d%% vs target %d%%\\n\",percPoS,(int32_t)ASSETCHAINS_STAKED);\n            }\n\n            uint64_t count;\n            uint64_t hashesToGo = 0;\n            uint64_t totalDone = 0;\n\n            int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);\n            count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];\n            CVerusHashV2 *vh2 = &ss2.GetState();\n            u128 *hashKey;\n            verusclhasher &vclh = vh2->vclh;\n            minefunction mine_verus;\n            mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port;\n\n            while (true)\n            {\n                uint256 hashResult = uint256();\n\n                unsigned char *curBuf;\n\n                if (mergeMining)\n                {\n                    // loop for a few minutes before refreshing the block\n                    while (true)\n                    {\n                        uint256 ourMerkle = pblock->hashMerkleRoot;\n                        if ( pindexPrev != chainActive.LastTip() )\n                        {\n                            if (lastChainTipPrinted != chainActive.LastTip())\n                            {\n                                lastChainTipPrinted = chainActive.LastTip();\n                                printf(\"Block %d added to chain\\n\\n\", lastChainTipPrinted->GetHeight());\n                                arith_uint256 target;\n                                target.SetCompact(lastChainTipPrinted->nBits);\n                                if (ourMerkle == lastChainTipPrinted->hashMerkleRoot)\n                                {\n                                    LogPrintf(\"proof-of-work found  \\n  hash: %s  \\ntarget: %s\\n\", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str());\n                                    printf(\"Found block %d \\n\", lastChainTipPrinted->GetHeight());\n                                    printf(\"mining reward %.8f %s!\\n\", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);\n                                    printf(\"  hash: %s\\ntarget: %s\\n\", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str());\n                                }\n                            }\n                            break;\n                        }\n\n                        // if PBaaS is no longer available, we can't count on merge mining\n                        if (!ConnectedChains.IsVerusPBaaSAvailable())\n                        {\n                            break;\n                        }\n\n                        if (vNodes.empty() && chainparams.MiningRequiresPeers())\n                        {\n                            if ( Mining_height > ASSETCHAINS_MINHEIGHT )\n                            {\n                                fprintf(stderr,\"no nodes, attempting reconnect\\n\");\n                                break;\n                            }\n                        }\n\n                        // update every few minutes, regardless\n                        int64_t elapsed = GetTime() - nStart;\n\n                        if ((mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && elapsed > 60) || elapsed > 60 || ConnectedChains.lastSubmissionFailed)\n                        {\n                            break;\n                        }\n\n                        boost::this_thread::interruption_point();\n                        MilliSleep(500);\n                    }\n                    break;\n                }\n                else\n                {\n                    // check NONCEMASK at a time\n                    for (uint64_t i = 0; i < count; i++)\n                    {\n                        // this is the actual mining loop, which enables us to drop out and queue a header anytime we earn a block that is good enough for a\n                        // merge mined block, but not our own\n                        bool blockFound;\n                        arith_uint256 arithHash;\n                        totalDone = 0;\n                        do\n                        {\n                            // pickup/remove any new/deleted headers\n                            if (ConnectedChains.dirty || (pblock->NumPBaaSHeaders() < ConnectedChains.mergeMinedChains.size() + 1))\n                            {\n                                IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, verusSolutionPBaaS ? false : true, &savebits);\n\n                                hashTarget.SetCompact(savebits);\n                                uintTarget = ArithToUint256(hashTarget);\n                            }\n\n                            // hashesToGo gets updated with actual number run for metrics\n                            hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];\n                            uint64_t start = i * hashesToGo + totalDone;\n                            hashesToGo -= totalDone;\n\n                            if (verusSolutionPBaaS)\n                            {\n                                // mine on canonical header for merge mining\n                                CPBaaSPreHeader savedHeader(*pblock);\n\n                                pblock->ClearNonCanonicalData();\n                                blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);\n                                savedHeader.SetBlockData(*pblock);\n                            }\n                            else\n                            {\n                                blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);\n                            }\n\n                            arithHash = UintToArith256(hashResult);\n                            totalDone += hashesToGo + 1;\n                            if (blockFound && IsVerusActive())\n                            {\n                                ConnectedChains.QueueNewBlockHeader(*pblock);\n                                if (arithHash > ourTarget)\n                                {\n                                    // all blocks qualified with this hash will be submitted\n                                    // until we redo the block, we might as well not try again with anything over this hash\n                                    hashTarget = arithHash;\n                                    uintTarget = ArithToUint256(hashTarget);\n                                }\n                            }\n                        } while (blockFound && arithHash > ourTarget);\n\n                        if (!blockFound || arithHash > ourTarget)\n                        {\n                            // Check for stop or if block needs to be rebuilt\n                            boost::this_thread::interruption_point();\n                            if ( pindexPrev != chainActive.LastTip() )\n                            {\n                                if (lastChainTipPrinted != chainActive.LastTip())\n                                {\n                                    lastChainTipPrinted = chainActive.LastTip();\n                                    printf(\"Block %d added to chain\\n\", lastChainTipPrinted->GetHeight());\n                                }\n                                break;\n                            }\n                            else if ((i + 1) < count)\n                            {\n                                // if we'll not drop through, update hashcount\n                                {\n                                    miningTimer += totalDone;\n                                    totalDone = 0;\n                                }\n                            }\n                        }\n                        else\n                        {\n                            // Check for stop or if block needs to be rebuilt\n                            boost::this_thread::interruption_point();\n\n                            if (pblock->nSolution.size() != 1344)\n                            {\n                                LogPrintf(\"ERROR: Block solution is not 1344 bytes as it should be\");\n                                break;\n                            }\n\n                            SetThreadPriority(THREAD_PRIORITY_NORMAL);\n\n                            int32_t unlockTime = komodo_block_unlocktime(Mining_height);\n\n#ifdef VERUSHASHDEBUG\n                            std::string validateStr = hashResult.GetHex();\n                            std::string hashStr = pblock->GetHash().GetHex();\n                            uint256 *bhalf1 = (uint256 *)vh2->CurBuffer();\n                            uint256 *bhalf2 = bhalf1 + 1;\n#else\n                            std::string hashStr = hashResult.GetHex();\n#endif\n\n                            LogPrintf(\"Using %s algorithm:\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n                            LogPrintf(\"proof-of-work found  \\n  hash: %s  \\ntarget: %s\\n\", hashStr, ArithToUint256(ourTarget).GetHex());\n                            printf(\"Found block %d \\n\", Mining_height );\n                            printf(\"mining reward %.8f %s!\\n\", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);\n#ifdef VERUSHASHDEBUG\n                            printf(\"  hash: %s\\n   val: %s  \\ntarget: %s\\n\\n\", hashStr.c_str(), validateStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());\n                            printf(\"intermediate %lx\\n\", intermediate);\n                            printf(\"Curbuf: %s%s\\n\", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());\n                            bhalf1 = (uint256 *)verusclhasher_key.get();\n                            bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5);\n                            printf(\"   Key: %s%s\\n\", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());\n#else\n                            printf(\"  hash: %s\\ntarget: %s\", hashStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());\n#endif\n                            if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)\n                                printf(\" - timelocked until block %i\\n\", unlockTime);\n                            else\n                                printf(\"\\n\");\n#ifdef ENABLE_WALLET\n                            ProcessBlockFound(pblock, *pwallet, reservekey);\n#else\n                            ProcessBlockFound(pblock);\n#endif\n                            SetThreadPriority(THREAD_PRIORITY_LOWEST);\n                            break;\n                        }\n                    }\n\n                    {\n                        miningTimer += totalDone;\n                    }\n                }\n                \n\n                // Check for stop or if block needs to be rebuilt\n                boost::this_thread::interruption_point();\n\n                if (vNodes.empty() && chainparams.MiningRequiresPeers())\n                {\n                    if ( Mining_height > ASSETCHAINS_MINHEIGHT )\n                    {\n                        fprintf(stderr,\"no nodes, attempting reconnect\\n\");\n                        break;\n                    }\n                }\n\n                if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)\n                {\n                    fprintf(stderr,\"timeout, retrying\\n\");\n                    break;\n                }\n\n                if ( pindexPrev != chainActive.LastTip() )\n                {\n                    if (lastChainTipPrinted != chainActive.LastTip())\n                    {\n                        lastChainTipPrinted = chainActive.LastTip();\n                        printf(\"Block %d added to chain\\n\\n\", lastChainTipPrinted->GetHeight());\n                    }\n                    break;\n                }\n\n                // totalDone now has the number of hashes actually done since starting on one nonce mask worth\n                uint64_t hashesPerNonceMask = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3;\n                if (!(totalDone < hashesPerNonceMask))\n                {\n#ifdef _WIN32\n                    printf(\"%llu mega hashes complete - working\\n\", (hashesPerNonceMask + 1) / 1048576);\n#else\n                    printf(\"%lu mega hashes complete - working\\n\", (hashesPerNonceMask + 1) / 1048576);\n#endif\n                }\n                break;\n\n            }\n        }\n    }\n    catch (const boost::thread_interrupted&)\n    {\n        miningTimer.stop();\n        miningTimer.clear();\n        LogPrintf(\"%s miner terminated\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);\n        throw;\n    }\n    catch (const std::runtime_error &e)\n    {\n        miningTimer.stop();\n        miningTimer.clear();\n        LogPrintf(\"%s miner runtime error: %s\\n\", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());\n        return;\n    }\n    miningTimer.stop();\n    miningTimer.clear();\n}\n\nvoid static BitcoinMiner(CWallet *pwallet)\n{\n    LogPrintf(\"KomodoMiner started\\n\");\n    SetThreadPriority(THREAD_PRIORITY_LOWEST);\n    RenameThread(\"komodo-miner\");\n\n    const CChainParams& chainparams = Params();\n\n#ifdef ENABLE_WALLET\n    // Each thread has its own key\n    CReserveKey reservekey(pwallet);\n#endif\n    \n    // Each thread has its own counter\n    unsigned int nExtraNonce = 0;\n    \n    unsigned int n = chainparams.GetConsensus().EquihashN();\n    unsigned int k = chainparams.GetConsensus().EquihashK();\n    uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;\n    while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) )\n    {\n        sleep(1);\n        if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )\n            break;\n    }\n    if ( ASSETCHAINS_SYMBOL[0] == 0 )\n        komodo_chosennotary(&notaryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());\n    if ( notaryid != My_notaryid )\n        My_notaryid = notaryid;\n    std::string solver;\n    //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )\n    solver = \"tromp\";\n    //else solver = \"default\";\n    assert(solver == \"tromp\" || solver == \"default\");\n    LogPrint(\"pow\", \"Using Equihash solver \\\"%s\\\" with n = %u, k = %u\\n\", solver, n, k);\n    if ( ASSETCHAINS_SYMBOL[0] != 0 )\n        fprintf(stderr,\"notaryid.%d Mining.%s with %s\\n\",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());\n    std::mutex m_cs;\n    bool cancelSolver = false;\n    boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(\n                                                                       [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {\n                                                                           std::lock_guard<std::mutex> lock{m_cs};\n                                                                           cancelSolver = true;\n                                                                       }\n                                                                       );\n    miningTimer.start();\n    \n    try {\n        if ( ASSETCHAINS_SYMBOL[0] != 0 )\n            fprintf(stderr,\"try %s Mining with %s\\n\",ASSETCHAINS_SYMBOL,solver.c_str());\n        while (true)\n        {\n            if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 &&\n            {\n                //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 )\n                //    break;\n                // Busy-wait for the network to come online so we don't waste time mining\n                // on an obsolete chain. In regtest mode we expect to fly solo.\n                miningTimer.stop();\n                do {\n                    bool fvNodesEmpty;\n                    {\n                        //LOCK(cs_vNodes);\n                        fvNodesEmpty = vNodes.empty();\n                    }\n                    if (!fvNodesEmpty && !IsInitialBlockDownload(chainparams))\n                        break;\n                    MilliSleep(15000);\n                    //fprintf(stderr,\"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\\n\",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());\n                    \n                } while (true);\n                //fprintf(stderr,\"%s Found peers\\n\",ASSETCHAINS_SYMBOL);\n                miningTimer.start();\n            }\n            //\n            // Create new block\n            //\n            unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();\n            CBlockIndex* pindexPrev = chainActive.LastTip();\n            if ( Mining_height != pindexPrev->GetHeight()+1 )\n            {\n                Mining_height = pindexPrev->GetHeight()+1;\n                Mining_start = (uint32_t)time(NULL);\n            }\n            if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )\n            {\n                //fprintf(stderr,\"%s create new block ht.%d\\n\",ASSETCHAINS_SYMBOL,Mining_height);\n                //sleep(3);\n            }\n\n#ifdef ENABLE_WALLET\n            // notaries always default to staking\n            CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg(\"-genproclimit\", 0) == 0);\n#else\n            CBlockTemplate *ptr = CreateNewBlockWithKey();\n#endif\n            if ( ptr == 0 )\n            {\n                static uint32_t counter;\n                if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )\n                    fprintf(stderr,\"created illegal block, retry\\n\");\n                sleep(1);\n                continue;\n            }\n            //fprintf(stderr,\"get template\\n\");\n            unique_ptr<CBlockTemplate> pblocktemplate(ptr);\n            if (!pblocktemplate.get())\n            {\n                if (GetArg(\"-mineraddress\", \"\").empty()) {\n                    LogPrintf(\"Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\\n\");\n                } else {\n                    // Should never reach here, because -mineraddress validity is checked in init.cpp\n                    LogPrintf(\"Error in KomodoMiner: Invalid -mineraddress\\n\");\n                }\n                return;\n            }\n            CBlock *pblock = &pblocktemplate->block;\n            if ( ASSETCHAINS_SYMBOL[0] != 0 )\n            {\n                if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )\n                {\n                    if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )\n                    {\n                        static uint32_t counter;\n                        if ( counter++ < 10 )\n                            fprintf(stderr,\"skip generating %s on-demand block, no tx avail\\n\",ASSETCHAINS_SYMBOL);\n                        sleep(10);\n                        continue;\n                    } else fprintf(stderr,\"%s vouts.%d mining.%d vs %d\\n\",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);\n                }\n            }\n            IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);\n            //fprintf(stderr,\"Running KomodoMiner.%s with %u transactions in block\\n\",solver.c_str(),(int32_t)pblock->vtx.size());\n            LogPrintf(\"Running KomodoMiner.%s with %u transactions in block (%u bytes)\\n\",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));\n            //\n            // Search\n            //\n            uint8_t pubkeys[66][33]; arith_uint256 bnMaxPoSdiff; uint32_t blocktimes[66]; int mids[256],nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();\n            pblock->nBits         = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());\n            savebits = pblock->nBits;\n            HASHTarget = arith_uint256().SetCompact(savebits);\n            roundrobin_delay = ROUNDROBIN_DELAY;\n            if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )\n            {\n                j = 65;\n                if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )\n                {\n                    int32_t dispflag = 0;\n                    if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )\n                        dispflag = 1;\n                    komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight());\n                    if ( nonzpkeys > 0 )\n                    {\n                        for (i=0; i<33; i++)\n                            if( pubkeys[0][i] != 0 )\n                                break;\n                        if ( i == 33 )\n                            externalflag = 1;\n                        else externalflag = 0;\n                        if ( IS_KOMODO_NOTARY != 0 )\n                        {\n                            for (i=1; i<66; i++)\n                                if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )\n                                    break;\n                            if ( externalflag == 0 && i != 66 && mids[i] >= 0 )\n                                printf(\"VIOLATION at %d, notaryid.%d\\n\",i,mids[i]);\n                            for (j=gpucount=0; j<65; j++)\n                            {\n                                if ( dispflag != 0 )\n                                {\n                                    if ( mids[j] >= 0 )\n                                        fprintf(stderr,\"%d \",mids[j]);\n                                    else fprintf(stderr,\"GPU \");\n                                }\n                                if ( mids[j] == -1 )\n                                    gpucount++;\n                            }\n                            if ( dispflag != 0 )\n                                fprintf(stderr,\" <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\\n\",pindexPrev->GetHeight(),notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL));\n                        }\n                        for (j=0; j<65; j++)\n                            if ( mids[j] == notaryid )\n                                break;\n                        if ( j == 65 )\n                            KOMODO_LASTMINED = 0;\n                    } else fprintf(stderr,\"no nonz pubkeys\\n\");\n                    if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )\n                    {\n                        HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);\n                        fprintf(stderr,\"I am the chosen one for %s ht.%d\\n\",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1);\n                    } //else fprintf(stderr,\"duplicate at j.%d\\n\",j);\n                } else Mining_start = 0;\n            } else Mining_start = 0;\n            if ( ASSETCHAINS_STAKED != 0 )\n            {\n                int32_t percPoS,z; bool fNegative,fOverflow;\n                HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);\n                HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);\n                if ( ASSETCHAINS_STAKED < 100 )\n                {\n                    for (z=31; z>=0; z--)\n                        fprintf(stderr,\"%02x\",((uint8_t *)&HASHTarget_POW)[z]);\n                    fprintf(stderr,\" PoW for staked coin PoS %d%% vs target %d%%\\n\",percPoS,(int32_t)ASSETCHAINS_STAKED);\n                }\n            }\n            while (true)\n            {\n                if ( KOMODO_INSYNC == 0 )\n                {\n                    fprintf(stderr,\"Mining when blockchain might not be in sync longest.%d vs %d\\n\",KOMODO_LONGESTCHAIN,Mining_height);\n                    if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN )\n                        KOMODO_INSYNC = 1;\n                    sleep(3);\n                }\n                // Hash state\n                KOMODO_CHOSEN_ONE = 0;\n                \n                crypto_generichash_blake2b_state state;\n                EhInitialiseState(n, k, state);\n                // I = the block header minus nonce and solution.\n                CEquihashInput I{*pblock};\n                CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n                ss << I;\n                // H(I||...\n                crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());\n                // H(I||V||...\n                crypto_generichash_blake2b_state curr_state;\n                curr_state = state;\n                crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());\n                // (x_1, x_2, ...) = A(I, V, n, k)\n                LogPrint(\"pow\", \"Running Equihash solver \\\"%s\\\" with nNonce = %s\\n\",solver, pblock->nNonce.ToString());\n                arith_uint256 hashTarget;\n                if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )\n                    hashTarget = HASHTarget_POW;\n                else hashTarget = HASHTarget;\n                std::function<bool(std::vector<unsigned char>)> validBlock =\n#ifdef ENABLE_WALLET\n                [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]\n#else\n                [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]\n#endif\n                (std::vector<unsigned char> soln) {\n                    int32_t z; arith_uint256 h; CBlock B;\n                    // Write the solution to the hash and compute the result.\n                    LogPrint(\"pow\", \"- Checking solution against target\\n\");\n                    pblock->nSolution = soln;\n                    solutionTargetChecks.increment();\n                    B = *pblock;\n                    h = UintToArith256(B.GetHash());\n                    /*for (z=31; z>=16; z--)\n                        fprintf(stderr,\"%02x\",((uint8_t *)&h)[z]);\n                    fprintf(stderr,\" mined \");\n                    for (z=31; z>=16; z--)\n                        fprintf(stderr,\"%02x\",((uint8_t *)&HASHTarget)[z]);\n                    fprintf(stderr,\" hashTarget \");\n                    for (z=31; z>=16; z--)\n                        fprintf(stderr,\"%02x\",((uint8_t *)&HASHTarget_POW)[z]);\n                    fprintf(stderr,\" POW\\n\");*/\n                    if ( h > hashTarget )\n                    {\n                        //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 )\n                        //    sleep(1);\n                        return false;\n                    }\n                    if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )\n                    {\n                        //fprintf(stderr,\"need to wait %d seconds to submit block\\n\",(int32_t)(B.nTime - GetAdjustedTime()));\n                        while ( GetAdjustedTime() < B.nTime-2 )\n                        {\n                            sleep(1);\n                            if ( chainActive.LastTip()->GetHeight() >= Mining_height )\n                            {\n                                fprintf(stderr,\"new block arrived\\n\");\n                                return(false);\n                            }\n                        }\n                    }\n                    if ( ASSETCHAINS_STAKED == 0 )\n                    {\n                        if ( IS_KOMODO_NOTARY != 0 )\n                        {\n                            int32_t r;\n                            if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )\n                                MilliSleep((rand() % (r * 1000)) + 1000);\n                        }\n                    }\n                    else\n                    {\n                        while ( B.nTime-57 > GetAdjustedTime() )\n                        {\n                            sleep(1);\n                            if ( chainActive.LastTip()->GetHeight() >= Mining_height )\n                                return(false);\n                        }\n                        uint256 tmp = B.GetHash();\n                        int32_t z; for (z=31; z>=0; z--)\n                            fprintf(stderr,\"%02x\",((uint8_t *)&tmp)[z]);\n                        fprintf(stderr,\" mined %s block %d!\\n\",ASSETCHAINS_SYMBOL,Mining_height);\n                    }\n                    CValidationState state;\n                    if ( !TestBlockValidity(state, Params(), B, chainActive.LastTip(), true, false))\n                    {\n                        h = UintToArith256(B.GetHash());\n                        for (z=31; z>=0; z--)\n                            fprintf(stderr,\"%02x\",((uint8_t *)&h)[z]);\n                        fprintf(stderr,\" Invalid block mined, try again\\n\");\n                        return(false);\n                    }\n                    KOMODO_CHOSEN_ONE = 1;\n                    // Found a solution\n                    SetThreadPriority(THREAD_PRIORITY_NORMAL);\n                    LogPrintf(\"KomodoMiner:\\n\");\n                    LogPrintf(\"proof-of-work found  \\n  hash: %s  \\ntarget: %s\\n\", B.GetHash().GetHex(), HASHTarget.GetHex());\n#ifdef ENABLE_WALLET\n                    if (ProcessBlockFound(&B, *pwallet, reservekey)) {\n#else\n                        if (ProcessBlockFound(&B)) {\n#endif\n                            // Ignore chain updates caused by us\n                            std::lock_guard<std::mutex> lock{m_cs};\n                            cancelSolver = false;\n                        }\n                        KOMODO_CHOSEN_ONE = 0;\n                        SetThreadPriority(THREAD_PRIORITY_LOWEST);\n                        // In regression test mode, stop mining after a block is found.\n                        if (chainparams.MineBlocksOnDemand()) {\n                            // Increment here because throwing skips the call below\n                            ehSolverRuns.increment();\n                            throw boost::thread_interrupted();\n                        }\n                        return true;\n                    };\n                    std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {\n                        std::lock_guard<std::mutex> lock{m_cs};\n                        return cancelSolver;\n                    };\n                    \n                    // TODO: factor this out into a function with the same API for each solver.\n                    if (solver == \"tromp\" ) { //&& notaryid >= 0 ) {\n                        // Create solver and initialize it.\n                        equi eq(1);\n                        eq.setstate(&curr_state);\n                        \n                        // Initialization done, start algo driver.\n                        eq.digit0(0);\n                        eq.xfull = eq.bfull = eq.hfull = 0;\n                        eq.showbsizes(0);\n                        for (u32 r = 1; r < WK; r++) {\n                            (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);\n                            eq.xfull = eq.bfull = eq.hfull = 0;\n                            eq.showbsizes(r);\n                        }\n                        eq.digitK(0);\n                        ehSolverRuns.increment();\n                        \n                        // Convert solution indices to byte array (decompress) and pass it to validBlock method.\n                        for (size_t s = 0; s < eq.nsols; s++) {\n                            LogPrint(\"pow\", \"Checking solution %d\\n\", s+1);\n                            std::vector<eh_index> index_vector(PROOFSIZE);\n                            for (size_t i = 0; i < PROOFSIZE; i++) {\n                                index_vector[i] = eq.sols[s][i];\n                            }\n                            std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);\n                            \n                            if (validBlock(sol_char)) {\n                                // If we find a POW solution, do not try other solutions\n                                // because they become invalid as we created a new block in blockchain.\n                                break;\n                            }\n                        }\n                    } else {\n                        try {\n                            // If we find a valid block, we rebuild\n                            bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);\n                            ehSolverRuns.increment();\n                            if (found) {\n                                int32_t i; uint256 hash = pblock->GetHash();\n                                for (i=0; i<32; i++)\n                                    fprintf(stderr,\"%02x\",((uint8_t *)&hash)[i]);\n                                fprintf(stderr,\" <- %s Block found %d\\n\",ASSETCHAINS_SYMBOL,Mining_height);\n                                FOUND_BLOCK = 1;\n                                KOMODO_MAYBEMINED = Mining_height;\n                                break;\n                            }\n                        } catch (EhSolverCancelledException&) {\n                            LogPrint(\"pow\", \"Equihash solver cancelled\\n\");\n                            std::lock_guard<std::mutex> lock{m_cs};\n                            cancelSolver = false;\n                        }\n                    }\n                    \n                    // Check for stop or if block needs to be rebuilt\n                    boost::this_thread::interruption_point();\n                    // Regtest mode doesn't require peers\n                    if ( FOUND_BLOCK != 0 )\n                    {\n                        FOUND_BLOCK = 0;\n                        fprintf(stderr,\"FOUND_BLOCK!\\n\");\n                        //sleep(2000);\n                    }\n                    if (vNodes.empty() && chainparams.MiningRequiresPeers())\n                    {\n                        if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )\n                        {\n                            fprintf(stderr,\"no nodes, break\\n\");\n                            break;\n                        }\n                    }\n                    if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)\n                    {\n                        //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )\n                        fprintf(stderr,\"0xffff, break\\n\");\n                        break;\n                    }\n                    if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)\n                    {\n                        if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )\n                            fprintf(stderr,\"timeout, break\\n\");\n                        break;\n                    }\n                    if ( pindexPrev != chainActive.LastTip() )\n                    {\n                        if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )\n                            fprintf(stderr,\"Tip advanced, break\\n\");\n                        break;\n                    }\n                    // Update nNonce and nTime\n                    pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);\n                    pblock->nBits = savebits;\n                    /*if ( NOTARY_PUBKEY33[0] == 0 )\n                    {\n                        int32_t percPoS;\n                        UpdateTime(pblock, consensusParams, pindexPrev);\n                        if (consensusParams.fPowAllowMinDifficultyBlocks)\n                        {\n                            // Changing pblock->nTime can change work required on testnet:\n                            HASHTarget.SetCompact(pblock->nBits);\n                            HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);\n                        }\n                    }*/\n                }\n            }\n        }\n        catch (const boost::thread_interrupted&)\n        {\n            miningTimer.stop();\n            c.disconnect();\n            LogPrintf(\"KomodoMiner terminated\\n\");\n            throw;\n        }\n        catch (const std::runtime_error &e)\n        {\n            miningTimer.stop();\n            c.disconnect();\n            LogPrintf(\"KomodoMiner runtime error: %s\\n\", e.what());\n            return;\n        }\n        miningTimer.stop();\n        c.disconnect();\n    }\n\n#ifdef ENABLE_WALLET\n    void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)\n#else\n    void GenerateBitcoins(bool fGenerate, int nThreads)\n#endif\n    {\n        static CCriticalSection cs_startmining;\n\n        LOCK(cs_startmining);\n        if (!AreParamsInitialized())\n        {\n            return;\n        }\n\n        // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at\n        // initialization, and this is the first time we can get it. store the Sapling address here\n        extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher;\n        extern std::string VERUS_CHEATCATCHER;\n        libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER);\n        if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr))\n        {\n            try\n            {\n                cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr);\n            } \n            catch (...)\n            {\n            }\n        }\n\n        VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0);\n\n        if (fGenerate == true || VERUS_MINTBLOCKS)\n        {\n            mapArgs[\"-gen\"] = \"1\";\n\n            if (VERUS_CHEATCATCHER.size() > 0)\n            {\n                if (cheatCatcher == boost::none)\n                {\n                    LogPrintf(\"ERROR: -cheatcatcher parameter is invalid Sapling payment address\\n\");\n                    fprintf(stderr, \"-cheatcatcher parameter is invalid Sapling payment address\\n\");\n                }\n                else\n                {\n                    LogPrintf(\"StakeGuard searching for double stakes on %s\\n\", VERUS_CHEATCATCHER.c_str());\n                    fprintf(stderr, \"StakeGuard searching for double stakes on %s\\n\", VERUS_CHEATCATCHER.c_str());\n                }\n            }\n        }\n\n        static boost::thread_group* minerThreads = NULL;\n\n        if (nThreads < 0)\n            nThreads = GetNumCores();\n\n        if (minerThreads != NULL)\n        {\n            minerThreads->interrupt_all();\n            minerThreads->join_all();\n            delete minerThreads;\n            minerThreads = NULL;\n        }\n\n        //fprintf(stderr,\"nThreads.%d fGenerate.%d\\n\",(int32_t)nThreads,fGenerate);\n        if ( nThreads == 0 && ASSETCHAINS_STAKED )\n            nThreads = 1;\n\n        if (!fGenerate)\n            return;\n\n        minerThreads = new boost::thread_group();\n\n        // add the PBaaS thread when mining or staking\n        minerThreads->create_thread(boost::bind(&CConnectedChains::SubmissionThreadStub));\n\n#ifdef ENABLE_WALLET\n        if (VERUS_MINTBLOCKS && pwallet != NULL)\n        {\n            minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));\n        }\n#endif\n\n        for (int i = 0; i < nThreads; i++) {\n\n#ifdef ENABLE_WALLET\n            if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)\n                minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));\n            else\n                minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));\n#else\n            if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)\n                minerThreads->create_thread(&BitcoinMiner);\n            else\n                minerThreads->create_thread(&BitcoinMiner_noeq);\n#endif\n        }\n    }\n    \n#endif // ENABLE_MINING\n", "meta": {"hexsha": "aa5c91212ccad42a33395e1fc315f88a5fecf630", "size": 153587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/miner.cpp", "max_stars_repo_name": "DavidLDawes/VerusCoin", "max_stars_repo_head_hexsha": "925fe06aac13471fd6dcdce39848d9a9b3f3e9ae", "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/miner.cpp", "max_issues_repo_name": "DavidLDawes/VerusCoin", "max_issues_repo_head_hexsha": "925fe06aac13471fd6dcdce39848d9a9b3f3e9ae", "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/miner.cpp", "max_forks_repo_name": "DavidLDawes/VerusCoin", "max_forks_repo_head_hexsha": "925fe06aac13471fd6dcdce39848d9a9b3f3e9ae", "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": 45.3460289342, "max_line_length": 280, "alphanum_fraction": 0.5408270231, "num_tokens": 33938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.16367130098114113}}
{"text": "#include <prc/range.hpp>\n\n#include <chrono>\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <ostream>\n#include <sstream>\n#include <utility>\n\n#include <boost/algorithm/string/join.hpp>\n\nnamespace prc\n{\nnamespace\n{\nconstexpr auto nb_total_combos = 1326;\nconstexpr auto minimum_weight = 0.001;\n\nstd::vector<range::weighted_elems> weights_to_weighted_elems(\n    std::vector<double> const& weights)\n{\n  std::map<double, std::vector<combo>> m;\n  auto const& any_two = any_two_combos();\n\n  for (auto i = 0; i < nb_total_combos; ++i)\n  {\n    // do not include folded combos ever\n    // it can be reconstituted by expanding combos of all subranges, then\n    // set_difference between that and the parent combos\n    if (weights[i] > minimum_weight)\n      m[weights[i] * 100.0].push_back(any_two[i]);\n  }\n\n  std::vector<range::weighted_elems> ret;\n  for (auto const& [weight, combos] : m)\n    ret.push_back({weight, reduce_combos(combos)});\n  return ret;\n}\n\nstd::vector<range::weighted_elems> weights_to_weighted_elems(\n    std::vector<double> const& weights,\n    std::vector<double> const& parent_weights)\n{\n  std::vector<double> adjusted_weights;\n\n  // pio weights are absolute, e.g. parent has 0.8, child has 0.7, it means 70%\n  // of 100%, not 70% of 80%\n  // equilab stores relative values and transform them in absolute ones when the\n  // user selects a range to bring to the main window\n  //\n  // I do like equilab to allow easy replacing of parent ranges later on\n  std::transform(weights.begin(),\n                 weights.end(),\n                 parent_weights.begin(),\n                 std::back_inserter(adjusted_weights),\n                 [](auto a, auto b) {\n                   auto const margin = 1.0 - b;\n                   return a + margin;\n                 });\n  return weights_to_weighted_elems(adjusted_weights);\n}\n\nusing weight_by_combo_t = std::map<prc::combo, double>;\n\nweight_by_combo_t weight_by_combos(\n    std::vector<range::weighted_elems> const& elems)\n{\n  weight_by_combo_t ret;\n  for (auto const& [weight, e] : elems)\n  {\n    for (auto const& combo : expand_combos(e))\n    {\n      auto& w = ret[combo];\n      w += weight;\n      if (w + minimum_weight >= 100.0)\n        w = 100.0;\n    }\n  }\n  return ret;\n}\n\nstd::vector<range::weighted_elems> unassigned_combos_to_weighted_elems(\n    weight_by_combo_t const& combos)\n{\n  std::map<double, std::vector<prc::combo>> m;\n  std::vector<range::weighted_elems> ret;\n\n  for (auto const& [combo, weight] : combos)\n  {\n    if (weight > minimum_weight)\n      m[weight].push_back(combo);\n  }\n  for (auto const& [weight, combos] : m)\n    ret.push_back(range::weighted_elems{weight, reduce_combos(combos)});\n  return ret;\n}\n\nstd::vector<range::weighted_elems> equilab_weighted_hands_to_weighted_elems(\n    std::vector<equilab::parser::ast::weighted_hands> const& weighted_hands)\n{\n  std::vector<range::weighted_elems> ret;\n  for (auto const& [weight, hands] : weighted_hands)\n  {\n    if (weight <= minimum_weight)\n      continue;\n    range::weighted_elems e{weight, {}};\n    std::transform(\n        hands.begin(), hands.end(), std::back_inserter(e.elems), [](auto& e) {\n          return prc::range_elem{e};\n        });\n    std::sort(e.elems.begin(), e.elems.end());\n    ret.push_back(std::move(e));\n  }\n  return ret;\n}\ntemplate <typename Iterator>\nIterator order_equilab_groups(Iterator begin, Iterator end)\n{\n  std::sort(begin, end, [](auto& lhs, auto& rhs) {\n    if (lhs.info.value().nesting_index != rhs.info.value().nesting_index)\n      return lhs.info.value().nesting_index < rhs.info.value().nesting_index;\n    return lhs.info.value().index < rhs.info.value().index;\n  });\n  std::stable_sort(begin, end, [](auto& lhs, auto& rhs) {\n    return lhs.info.value().nesting_index > rhs.info.value().nesting_index;\n  });\n  return std::find_if(\n      begin, end, [](auto& g) { return g.info.value().nesting_index == 0; });\n}\n\ntemplate <typename Iterator, typename Sentinel>\nstd::vector<range> nest_equilab_ranges(Iterator begin, Sentinel end)\n{\n  // far from being optimized nor pretty, but heh\n  auto const first_non_nested = order_equilab_groups(begin, end);\n\n  std::map<int, int> index_to_pos;\n  for (auto it = begin; it != end; ++it)\n    index_to_pos[it->info->index] = std::distance(begin, it);\n\n  std::vector<range> subranges;\n  std::transform(begin, end, std::back_inserter(subranges), [](auto& g) {\n    auto elems = equilab_weighted_hands_to_weighted_elems(g.weighted_hands);\n    return range{g.info->name, std::move(elems), g.info->rgb};\n  });\n  for (auto it = begin; it != end; ++it)\n  {\n    if (it->info->nesting_index > 0)\n    {\n      auto const parent_pos = index_to_pos[it->info->parent_index];\n      // copy, to be able to erase remove after\n      subranges[parent_pos].add_subrange(\n          subranges[index_to_pos[it->info->index]]);\n    }\n  }\n  auto const first_non_nested_pos = std::distance(begin, first_non_nested);\n  return std::vector<range>(\n      std::make_move_iterator(subranges.begin() + first_non_nested_pos),\n      std::make_move_iterator(subranges.end()));\n}\n}\n\nrange::range(std::string name,\n             std::vector<weighted_elems> elems,\n             int rgb,\n             std::vector<range> subranges)\n  : _name(std::move(name)),\n    _elems(std::move(elems)),\n    _rgb(rgb),\n    _subranges(std::move(subranges))\n{\n}\n\nrange::range(equilab::parser::ast::range const& r) : _name(r.name), _rgb(0)\n{\n  if (r.groups.empty())\n    throw std::runtime_error{\"there must be at least one group in range\"};\n  auto& base_range = r.groups.front();\n  _elems = equilab_weighted_hands_to_weighted_elems(base_range.weighted_hands);\n  if (r.groups.size() > 1)\n  {\n    std::vector groups(r.groups.begin() + 1, r.groups.end());\n    _subranges = nest_equilab_ranges(groups.begin(), groups.end());\n  }\n}\n\nrange::range(pio::parser::ast::range const& r) : _rgb(0)\n{\n  if (r.base_range.weights.size() != nb_total_combos)\n    throw std::runtime_error{\"base_range does not have 1326 weights\"};\n  _elems = weights_to_weighted_elems(r.base_range.weights);\n  for (auto const& s : r.subranges)\n  {\n    if (s.weights.size() != nb_total_combos)\n      throw std::runtime_error{\"subrange does not have 1326 weights\"};\n    auto sub_elems = weights_to_weighted_elems(s.weights, r.base_range.weights);\n    if (!sub_elems.empty())\n      add_subrange({s.name, std::move(sub_elems), s.rgb});\n  }\n}\n\nvoid range::add_subrange(range const& r)\n{\n  _subranges.push_back(r);\n}\n\nvoid range::add_subrange(range&& r)\n{\n  _subranges.push_back(std::move(r));\n}\n\nrange* range::find_subrange(std::string const& name)\n{\n  auto it = std::find_if(_subranges.begin(), _subranges.end(), [&](auto& s) {\n    return s.name() == name;\n  });\n  if (it == _subranges.end())\n    return nullptr;\n  return std::addressof(*it);\n}\n\nrange const* range::find_subrange(std::string const& name) const\n{\n  return const_cast<range const*>(\n      (*const_cast<range const*>(this)).find_subrange(name));\n}\n\nvoid range::set_rgb(int rgb)\n{\n  _rgb = rgb;\n}\n\nvoid range::set_name(std::string name)\n{\n  _name = std::move(name);\n}\n\nvoid range::set_elems(std::vector<weighted_elems> elems)\n{\n  _elems = std::move(elems);\n}\n\nstd::string const& range::name() const\n{\n  return _name;\n}\n\nauto range::elems() const -> std::vector<weighted_elems> const&\n{\n  return _elems;\n}\n\nint range::rgb() const\n{\n  return _rgb;\n}\n\nstd::vector<range> const& range::subranges() const\n{\n  return _subranges;\n}\n\nstd::vector<range>& range::subranges()\n{\n  return _subranges;\n}\n\nbool operator==(range const& lhs, range const& rhs)\n{\n  return lhs.rgb() == rhs.rgb() &&\n         std::tie(lhs.name(), lhs.elems(), lhs.subranges()) ==\n             std::tie(rhs.name(), rhs.elems(), rhs.subranges());\n}\n\nbool operator!=(range const& lhs, range const& rhs)\n{\n  return !(lhs == rhs);\n}\n\nbool operator==(range::weighted_elems const& lhs,\n                range::weighted_elems const& rhs)\n{\n  return std::tie(lhs.weight, lhs.elems) == std::tie(rhs.weight, rhs.elems);\n}\n\nbool operator!=(range::weighted_elems const& lhs,\n                range::weighted_elems const& rhs)\n{\n  return !(lhs == rhs);\n}\n\nstd::vector<range::weighted_elems> unassigned_elems(range const& r)\n{\n  if (r.subranges().empty())\n    return {};\n  auto current = weight_by_combos(r.elems());\n  for (auto const& sub : r.subranges())\n  {\n    for (auto const& [combo, weight] : weight_by_combos(sub.elems()))\n    {\n      auto& w = current[combo];\n      w -= weight;\n      if (w <= minimum_weight)\n        w = 0;\n    }\n  }\n\n  return unassigned_combos_to_weighted_elems(current);\n}\n\nstd::vector<range::weighted_elems> adjust_weights(\n    std::vector<range::weighted_elems> const& base_range_elems, range const& r)\n{\n  auto const base_range_combos = weight_by_combos(base_range_elems);\n  auto const range_combos = weight_by_combos(r.elems());\n\n  std::map<double, std::vector<prc::combo>> tmp;\n  for (auto const& [combo, weight] : range_combos)\n  {\n    if (auto it = base_range_combos.find(combo); it != base_range_combos.end())\n      tmp[(it->second * weight) / 100.0].push_back(combo);\n  }\n  std::vector<range::weighted_elems> ret;\n  for (auto const& [weight, combos] : tmp)\n    ret.push_back(range::weighted_elems{weight, reduce_combos(combos)});\n  return ret;\n}\n\nstd::ostream& operator<<(std::ostream& os, range::weighted_elems const& elems)\n{\n  std::vector<std::string> strs;\n  for (auto const& elem : elems.elems)\n  {\n    std::stringstream ss;\n    ss << elem;\n    strs.push_back(ss.str());\n  }\n  os << elems.weight << \":\";\n  os << boost::algorithm::join(strs, \",\");\n  return os;\n}\n}\n", "meta": {"hexsha": "9ea145d423f6423e6268c11ac160a939c1c207a2", "size": 9534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/src/range.cpp", "max_stars_repo_name": "theodelrieu/prc", "max_stars_repo_head_hexsha": "199942ed8365f6e49a7e9667d587d1ae06f14999", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-04T22:37:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T22:37:00.000Z", "max_issues_repo_path": "lib/src/range.cpp", "max_issues_repo_name": "theodelrieu/prc", "max_issues_repo_head_hexsha": "199942ed8365f6e49a7e9667d587d1ae06f14999", "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": "lib/src/range.cpp", "max_forks_repo_name": "theodelrieu/prc", "max_forks_repo_head_hexsha": "199942ed8365f6e49a7e9667d587d1ae06f14999", "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.6347826087, "max_line_length": 80, "alphanum_fraction": 0.6596391861, "num_tokens": 2598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.16367130098114113}}
{"text": "#include <boost/hana/ext/boost/mpl/list.hpp>\n#include <boost/hana/type.hpp>\n\n<% list = Benchcc::MPL::List.new((0...x).map { |i| \"x<#{i}>\" }) %>\n<%= list.includes %>\n\n\nstruct f {\n    template <typename>\n    struct apply { struct type; };\n};\n\ntemplate <int> struct x;\n\nint main() {\n    auto go = boost::hana::fmap(\n        boost::hana::metafunction_class<f>,\n        <%= list %>{}\n    );\n}\n", "meta": {"hexsha": "090b600a7cac4123d76132eec6381147e6b0b783", "size": 388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/todo.fmap_mpl_list.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "benchmark/todo.fmap_mpl_list.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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": "benchmark/todo.fmap_mpl_list.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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": 18.4761904762, "max_line_length": 66, "alphanum_fraction": 0.5618556701, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3242354120407358, "lm_q1q2_score": 0.1633842248313657}}
{"text": "/*******************************************************************************\n*\n*  Filename    : MakeErrHist.cc\n*  Description : Implementatin of functions defined in include/MakeErrHist.hpp\n*  Author      : Yi-Mu \"Enoch\" Chen [ ensc@hep1.phys.ntu.edu.tw ]\n*\n*******************************************************************************/\n#include \"TstarAnalysis/CompareDataMC/interface/MakeErrHist.hpp\"\n#include \"TstarAnalysis/CompareDataMC/interface/SampleErrHistMgr.hpp\"\n\n#include \"ManagerUtils/Maths/interface/Parameter.hpp\"\n#include \"ManagerUtils/PlotUtils/interface/Common.hpp\"\n#include \"TstarAnalysis/Common/interface/NameParse.hpp\"\n#include \"TstarAnalysis/Common/interface/PlotStyle.hpp\"\n#include \"TstarAnalysis/CompareDataMC/interface/Compare_Common.hpp\"\n#include \"TstarAnalysis/CompareDataMC/interface/MakeHist.hpp\"\n#include \"TstarAnalysis/CompareDataMC/interface/SampleHistMgr.hpp\"\n\n#include <boost/format.hpp>\n#include <boost/range/adaptor/reversed.hpp>\nusing namespace std;\nusing namespace mgr;\n\nvoid\nMakeFullComparePlot(\n  SampleErrHistMgr*          datamgr,\n  vector<SampleErrHistMgr*>& background,\n  SampleErrHistMgr*          signalmgr,\n  const string&              label\n  )\n{\n  SetBkgColor( background );\n\n  for( const auto& histname : histnamelist ){\n\n    // Declaring Histograms, for construction look below.\n    THStack* stack = MakeBkgStack( background, histname );\n    TH1D* bkgerror = MakeBkgError( background, histname );\n    TH1D* datahist = (TH1D*)datamgr->Hist( histname )->Clone();\n    TH1D* bkgrel   = MakeBkgRelHist( bkgerror );\n    TH1D* datarel  = MakeDataRelHist( datahist, bkgerror );\n    TH1D* sighist  = (TH1D*)signalmgr->Hist( histname )->Clone();\n\n    cout << bkgerror->Integral() << \" \" << datahist->Integral() << endl;\n\n    // Scaling signal plot for clarity\n    const unsigned datanum = datamgr->ExpectedYield();\n    const double signum    = signalmgr->ExpectedYield();\n    const double sigscale  = datanum / signum / 2.;\n    if( sighist->Integral() < datahist->Integral() /4.0 ){\n      sighist->Scale( sigscale );\n    }\n\n    // Legend settings\n    TLegend* l = mgr::NewLegend( 0.6, 0.5 );\n    l->AddEntry( datahist, datamgr->RootName().c_str(), \"pe\" );\n\n    for( const auto& entry : background ){\n      l->AddEntry( entry->Hist( histname ), entry->RootName().c_str(), \"f\" );\n    }\n\n    l->AddEntry( bkgerror, \"Unc. (stat #oplus sys)\",                                                                \"fl\" );\n    l->AddEntry( sighist,  boost::str( boost::format( \"%s(#times%.0lf)\" )%signalmgr->RootName()%sigscale ).c_str(), \"fl\" );\n\n    MakePlot(\n      stack,\n      bkgerror,\n      datahist,\n      sighist,\n      bkgrel,\n      datarel,\n      l,\n      \"fullcomp\",\n      {histname, label}\n      );\n    delete l;\n    delete stack;\n    delete bkgerror;\n    delete datahist;\n    delete bkgrel;\n    delete datarel;\n    delete sighist;\n  }\n\n}\n\n/******************************************************************************/\n\nextern void\nNormalize(\n  SampleErrHistMgr*               data,\n  std::vector<SampleErrHistMgr*>& bg\n  )\n{\n  const double datayield = data->ExpectedYield();\n  double bgyield         = 0;\n\n  for( const auto& sample : bg ){\n    bgyield += sample->ExpectedYield();\n  }\n\n  const double scale = datayield / bgyield;\n\n  for( auto& sample : bg ){\n    sample->Scale( scale );\n  }\n}\n\n/******************************************************************************/\n\nTH1D*\nMakeSumHistogram(\n  const vector<SampleErrHistMgr*>& samplelist,\n  const string&                    histname\n  )\n{\n  const TH1D* temphist = samplelist.front()->Hist( histname );\n  const unsigned bins  = temphist->GetXaxis()->GetNbins();\n  const double xmin    = temphist->GetXaxis()->GetXmin();\n  const double xmax    = temphist->GetXaxis()->GetXmax();\n\n  const string newname = samplelist.front()->Name() + histname + \"sum\";\n  const string title   = \";\" + string( temphist->GetXaxis()->GetTitle() ) + \";\" + string( temphist->GetYaxis()->GetTitle() );\n  TH1D* sumhist        = new TH1D( newname.c_str(), title.c_str(), bins, xmin, xmax );\n\n  for( const auto& sample : samplelist ){\n    sumhist->Add( sample->Hist( histname ) );\n  }\n\n  sumhist->SetStats( 0 );\n  return sumhist;\n}\n\n\n/******************************************************************************/\n\nParameter\nExpectedYield( const vector<SampleErrHistMgr*>& samplelist )\n{\n  Parameter ans;\n\n  for( const auto& group : samplelist ){\n    for( const auto& sample : group->SampleList() ){\n      ans += sample.CrossSection()\n             * sample.SelectionEfficiency()\n             * sample.PDFUncertainty()\n             * sample.QCDScaleUncertainty();\n    }\n  }\n\n  return ans;\n}\n\n/******************************************************************************/\n\nvoid\nSetBkgColor( vector<SampleErrHistMgr*>& bkg )\n{\n  bkg[0]->SetColor( TColor::GetColor( \"#FFCC88\" ) );\n  bkg[1]->SetColor( TColor::GetColor( \"#996600\" ) );\n  bkg[2]->SetColor( TColor::GetColor( \"#FF3333\" ) );\n  bkg[3]->SetColor( TColor::GetColor( \"#33EEEE\" ) );\n  // bkg[4]->SetColor( TColor::GetColor( \"#0066EE\" ) );\n}\n\n/******************************************************************************/\n\nTHStack*\nMakeBkgStack(\n  const vector<SampleErrHistMgr*>& samplelist,\n  const string&                    histname\n  )\n{\n  THStack* stack = new THStack( ( histname+\"bkgstack\" ).c_str(), \"\" );\n\n  for( const auto& sample : boost::adaptors::reverse( samplelist ) ){\n    stack->Add( sample->Hist( histname ), \"HIST\" );\n  }\n\n  return stack;\n}\n\n/******************************************************************************/\n\nTH1D*\nMakeBkgError(\n  const vector<SampleErrHistMgr*>& samplelist,\n  const string&                    histname\n  )\n{\n  TH1D* central = MakeSumHistogram( samplelist, histname );\n  vector<pair<TH1D*, TH1D*> > errorhistlist;\n\n  for( const auto& err : histerrlist ){\n\n    // rescaling object for PDF and QCD scale errors\n    if( err.tag == \"pdf\" || err.tag == \"scale \" ){\n      for( const auto sample : samplelist ){\n        TH1D* central  = sample->Hist( histname );\n        TH1D* uphist   = sample->Hist( histname + err.tag + \"up\" );\n        TH1D* downhist = sample->Hist( histname + err.tag + \"down\" );\n        uphist->Scale( central->Integral()/uphist->Integral() );\n        downhist->Scale( central->Integral()/downhist->Integral() );\n      }\n    }\n\n    // Creating the summed results.\n    errorhistlist.emplace_back(\n      MakeSumHistogram( samplelist, histname + err.tag + \"up\" ),\n      MakeSumHistogram( samplelist, histname + err.tag + \"down\" )\n      );\n  }\n\n  const Parameter expyield = ExpectedYield( samplelist );\n  const Parameter normerr  = Parameter(\n    1,\n    expyield.RelUpperError(),\n    expyield.RelLowerError()\n    );\n\n  for( int i = 1; i <= central->GetSize(); ++i ){\n    const double bincont = central->GetBinContent( i );\n    const double binerr  = central->GetBinError( i );\n\n    Parameter errtot( 1, binerr/bincont, binerr/bincont );\n\n    for( const auto pair : errorhistlist ){\n      const double upbincont   = pair.first->GetBinContent( i );\n      const double downbincont = pair.second->GetBinContent( i );\n      const double upabserr    = std::max( 0.0, upbincont-bincont );\n      const double downabserr  = std::max( 0.0, bincont-downbincont );\n      errtot *= Parameter( 1, upabserr/bincont, downabserr/bincont );\n    }\n\n    // Additional errors\n    errtot *= ( normerr );// cross section and selection eff\n    errtot *= compnamer.MasterConfig().GetStaticParameter( \"Lumi Error\" );// lumierror\n    errtot *= compnamer.GetChannel().find( \"Electron\" ) == string::npos ?  // leptonic systematic error\n              compnamer.MasterConfig().GetStaticParameter( \"Muon Systematic\" ) :\n              compnamer.MasterConfig().GetStaticParameter( \"Electron Systematic\" );\n\n\n    if( bincont == 0 ){\n      central->SetBinError( i, 0 );\n    } else if( errtot.RelAvgError() >= 0.6 ){\n      central->SetBinError( i, bincont * 0.6 );\n    } else {\n      central->SetBinError( i, bincont * errtot.RelAvgError() );\n    }\n\n  }\n\n\n  for( auto& pair : errorhistlist ){\n    delete pair.first;\n    delete pair.second;\n  }\n\n  return central;\n}\n\n/******************************************************************************/\n\nvoid\nPlotErrCompare(\n  const vector<SampleErrHistMgr*>& samplelist,\n  const string&                    histname,\n  const ErrorSource&               err\n  )\n{\n  TH1D* central = MakeSumHistogram( samplelist, histname );\n  TH1D* errup   = MakeSumHistogram( samplelist, histname + err.tag + \"up\" );\n  TH1D* errdown = MakeSumHistogram( samplelist, histname + err.tag + \"down\" );\n\n  // Normailizing plots if err is the pdf error or scale errors\n  if( err.tag == \"scale\" || err.tag == \"pdf\" ){\n    errup->Scale( central->Integral() / errup->Integral() );\n    errdown->Scale( central->Integral() / errdown->Integral() );\n  }\n  // Making duplicate objects\n  TH1* uprel   = mgr::DivideHist( errup, central );\n  TH1* downrel = mgr::DivideHist( errdown, central );\n\n  const double xmin = central->GetXaxis()->GetXmin();\n  const double xmax = central->GetXaxis()->GetXmax();\n  // Setting plot range\n  const double ymax     = mgr::GetYmax( central, errup, errdown );\n  const double relymax  = std::min( 2.0, std::max( uprel->GetMaximum(), downrel->GetMaximum() ) );\n  const double bpaddist = std::ceil( ( relymax-1 )*10 )/10.;\n\n  // Plotting\n  TCanvas* c = mgr::NewCanvas();\n\n  // TOPPAD\n  TPad* pad1 = mgr::NewTopPad();\n  pad1->Draw();\n  pad1->cd();\n  central->Draw( PS_AXIS );\n  errup->Draw( PS_HIST PS_SAME );\n  errdown->Draw( PS_HIST PS_SAME );\n  central->Draw( PS_HIST PS_SAME );\n  c->cd();\n\n  // Bottom pad\n  TPad* pad2      = mgr::NewBottomPad();\n  TLine* line     = new TLine( xmin, 1, xmax, 1 );\n  TLine* line_top = new TLine( xmin, 1+bpaddist, xmax, 1+bpaddist );\n  TLine* line_bot = new TLine( xmin, 1-bpaddist, xmax, 1-bpaddist );\n  pad2->Draw();\n  pad2->cd();\n\n  uprel->Draw( PS_AXIS );\n  uprel->Draw( PS_HIST PS_SAME );\n  downrel->Draw( PS_HIST PS_SAME );\n  line->Draw( PS_SAME );\n  line_top->Draw( PS_SAME );\n  line_bot->Draw( PS_SAME );\n  c->cd();\n\n\n  // Drawing legend\n  const double legxmin = 0.5;\n  const double legymin = 0.7;\n  TLegend* tl          = mgr::NewLegend( legxmin, legymin );\n  const string label   = ( err.label != \"\" ) ? err.label : \"1#sigma\";\n  tl->AddEntry( central, \"Central Value\",                               \"l\" );\n  tl->AddEntry( errup,   ( err.rootname + \"(+\" + label + \")\" ).c_str(), \"l\" );\n  tl->AddEntry( errdown, ( err.rootname + \"(-\" + label + \")\" ).c_str(), \"l\" );\n\n  tl->Draw( PS_SAME );\n\n  // Common styling\n  central->SetLineColor( kBlack );\n  errup->SetLineColor( KRED );\n  errdown->SetLineColor( KBLUE );\n  uprel->SetLineColor( KRED );\n  downrel->SetLineColor( KBLUE );\n\n  // accessory styling\n  line->SetLineColor( kBlack );\n  line->SetLineStyle( 1 );\n  line->SetLineWidth( 2 );\n  line_top->SetLineColor( kBlack );\n  line_bot->SetLineColor( kBlack );\n  line_top->SetLineStyle( 3 );\n  line_bot->SetLineStyle( 3 );\n\n  mgr::SetTopPlotAxis( central );\n  mgr::SetBottomPlotAxis( uprel );\n\n  // Setting plot range\n  central->SetMaximum( ymax * 1.5 );\n  uprel->SetMaximum( 1+( bpaddist+0.05 ) );\n  uprel->SetMinimum( 1-( bpaddist+0.05 ) );\n  uprel->GetYaxis()->SetTitle( \"#frac{up,down}{Norm}\" );\n\n  mgr::LatexMgr latex;\n  latex.SetOrigin( PLOT_X_MIN, PLOT_Y_MAX + ( TEXT_MARGIN/2 ), BOTTOM_LEFT )\n  .WriteLine( compnamer.GetChannelEXT( \"Root Name\" ) );\n\n  latex.SetOrigin( PLOT_X_TEXT_MAX, legymin - 0.02, TOP_RIGHT );\n  if( compnamer.GetInput<string>( \"group\" ).find( \"Tstar\" ) != string::npos ){\n    latex.WriteLine( boost::str( boost::format( \"M_{t*}=%dGeV/c^{2}\" )%GetInt( compnamer.GetInput<string>( \"group\" ) ) ) );\n  } else {\n    latex.WriteLine( compnamer.GetInput<string>( \"group\" ) );\n  }\n\n  // cleaning up\n  mgr::DrawCMSLabel( SIMULATION );\n  mgr::DrawLuminosity( mgr::SampleMgr::TotalLuminosity() );\n\n  mgr::SaveToPDF( c, compnamer.PlotFileName( \"errcomp\", histname, err.tag ) );\n  mgr::SaveToROOT(\n    c,\n    compnamer.PlotRootFile(),\n    compnamer.OptFileName( \"\", \"errcomp\", histname, err.tag )\n    );\n\n  delete tl;\n  delete uprel;\n  delete downrel;\n  delete central;\n  delete errup;\n  delete errdown;\n  delete c;\n}\n", "meta": {"hexsha": "cb73424abc4e10c99606ab6dae90719086ce9727", "size": 12170, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CompareDataMC/src/MakeErrHist.cc", "max_stars_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_stars_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "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": "CompareDataMC/src/MakeErrHist.cc", "max_issues_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_issues_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CompareDataMC/src/MakeErrHist.cc", "max_forks_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_forks_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "max_forks_repo_licenses": ["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.4470284238, "max_line_length": 125, "alphanum_fraction": 0.5959737058, "num_tokens": 3397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.16327145954039723}}
{"text": "// Velodyne HDL Packet Bundle Decoder\n// Nick Rypkema (rypkema@mit.edu), MIT 2017\n// shared library to decode a bundle of velodyne packets\n\n#include <cmath>\n#include <stdint.h>\n#include <iostream>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/foreach.hpp>\n\n#include \"PacketBundleDecoder.h\"\n\nPacketBundleDecoder::PacketBundleDecoder()\n{\n  _max_num_of_frames = 10;\n  UnloadData();\n  InitTables();\n  LoadHDL32Corrections();\n}\n\nPacketBundleDecoder::~PacketBundleDecoder()\n{\n\n}\n\nvoid PacketBundleDecoder::SetMaxNumberOfFrames(unsigned int max_num_of_frames)\n{\n\n  if (max_num_of_frames <= 0) {\n    return;\n  } else {\n    _max_num_of_frames = max_num_of_frames;\n  }\n  while (_frames.size() >= _max_num_of_frames) {\n    _frames.pop_front();\n  }\n}\n\nvoid PacketBundleDecoder::DecodeBundle(std::string* bundle, unsigned int* bundle_length)\n{\n  unsigned int num_packets = *bundle_length/1206;\n\n  for (int i = 0; i < num_packets; i++) {\n    std::string data = bundle->substr(i*1206, 1206);\n    const unsigned char* data_char = reinterpret_cast<const unsigned char*>(data.c_str());\n    ProcessHDLPacket(const_cast<unsigned char*>(data_char), 1206);\n  }\n\n  if (_frames.size() == _max_num_of_frames-1) {\n    _frames.pop_front();\n  }\n  _frames.push_back(*_frame);\n  delete _frame;\n  _frame = new HDLFrame();\n}\n\nvoid PacketBundleDecoder::ProcessHDLPacket(unsigned char *data, unsigned int data_length)\n{\n  if (data_length != 1206) {\n    std::cout << \"PacketDecoder: Warning, data packet is not 1206 bytes\" << std::endl;\n    return;\n  }\n\n  HDLDataPacket* dataPacket = reinterpret_cast<HDLDataPacket *>(data);\n\n  for (int i = 0; i < HDL_FIRING_PER_PKT; ++i) {\n    HDLFiringData firingData = dataPacket->firingData[i];\n    int offset = (firingData.blockIdentifier == BLOCK_0_TO_31) ? 0 : 32;\n\n    for (int j = 0; j < HDL_LASER_PER_FIRING; j++) {\n      unsigned char laserId = static_cast<unsigned char>(j + offset);\n      if (firingData.laserReturns[j].distance != 0.0) {\n        PushFiringData(laserId, firingData.rotationalPosition, dataPacket->gpsTimestamp, firingData.laserReturns[j], laser_corrections_[j + offset]);\n      }\n    }\n  }\n}\n\nvoid PacketBundleDecoder::PushFiringData(unsigned char laserId, unsigned short azimuth, unsigned int timestamp, HDLLaserReturn laserReturn, HDLLaserCorrection correction)\n{\n  double cosAzimuth, sinAzimuth;\n  if (correction.azimuthCorrection == 0) {\n    cosAzimuth = cos_lookup_table_[azimuth];\n    sinAzimuth = sin_lookup_table_[azimuth];\n  } else {\n    double azimuthInRadians = HDL_Grabber_toRadians((static_cast<double> (azimuth) / 100.0) - correction.azimuthCorrection);\n    cosAzimuth = std::cos(azimuthInRadians);\n    sinAzimuth = std::sin(azimuthInRadians);\n  }\n\n  double distanceM = laserReturn.distance * 0.002 + correction.distanceCorrection;\n  double xyDistance = distanceM * correction.cosVertCorrection - correction.sinVertOffsetCorrection;\n\n  double x = (xyDistance * sinAzimuth - correction.horizontalOffsetCorrection * cosAzimuth);\n  double y = (xyDistance * cosAzimuth + correction.horizontalOffsetCorrection * sinAzimuth);\n  double z = (distanceM * correction.sinVertCorrection + correction.cosVertOffsetCorrection);\n  unsigned char intensity = laserReturn.intensity;\n\n  _frame->x.push_back(x);\n  _frame->y.push_back(y);\n  _frame->z.push_back(z);\n  _frame->intensity.push_back(intensity);\n  _frame->laser_id.push_back(laserId);\n  _frame->azimuth.push_back(azimuth);\n  _frame->distance.push_back(distanceM);\n  _frame->ms_from_top_of_hour.push_back(timestamp);\n}\n\nvoid PacketBundleDecoder::SetCorrectionsFile(const std::string& corrections_file)\n{\n  if (corrections_file == _corrections_file) {\n    return;\n  }\n\n  if (corrections_file.length()) {\n    LoadCorrectionsFile(corrections_file);\n  } else {\n    LoadHDL32Corrections();\n  }\n\n  _corrections_file = corrections_file;\n  UnloadData();\n}\n\nvoid PacketBundleDecoder::UnloadData()\n{\n  _frame = new HDLFrame();\n  _frames.clear();\n}\n\nvoid PacketBundleDecoder::InitTables()\n{\n  if (cos_lookup_table_ == NULL && sin_lookup_table_ == NULL) {\n    cos_lookup_table_ = static_cast<double *> (malloc (HDL_NUM_ROT_ANGLES * sizeof (*cos_lookup_table_)));\n    sin_lookup_table_ = static_cast<double *> (malloc (HDL_NUM_ROT_ANGLES * sizeof (*sin_lookup_table_)));\n    for (unsigned int i = 0; i < HDL_NUM_ROT_ANGLES; i++) {\n      double rad = HDL_Grabber_toRadians(i / 100.0);\n      cos_lookup_table_[i] = std::cos(rad);\n      sin_lookup_table_[i] = std::sin(rad);\n    }\n  }\n}\n\nvoid PacketBundleDecoder::LoadCorrectionsFile(const std::string& correctionsFile)\n{\n\n  boost::property_tree::ptree pt;\n  try {\n    read_xml(correctionsFile, pt, boost::property_tree::xml_parser::trim_whitespace);\n  } catch (boost::exception const&) {\n    std::cout << \"PacketDecoder: Error reading calibration file - \" << correctionsFile << std::endl;\n    return;\n  }\n\n  BOOST_FOREACH (boost::property_tree::ptree::value_type &v, pt.get_child(\"boost_serialization.DB.points_\")) {\n    if (v.first == \"item\") {\n      boost::property_tree::ptree points = v.second;\n      BOOST_FOREACH (boost::property_tree::ptree::value_type &px, points) {\n        if (px.first == \"px\") {\n          boost::property_tree::ptree calibrationData = px.second;\n          int index = -1;\n          double azimuth = 0;\n          double vertCorrection = 0;\n          double distCorrection = 0;\n          double vertOffsetCorrection = 0;\n          double horizOffsetCorrection = 0;\n\n          BOOST_FOREACH (boost::property_tree::ptree::value_type &item, calibrationData) {\n            if (item.first == \"id_\")\n              index = atoi(item.second.data().c_str());\n            if (item.first == \"rotCorrection_\")\n              azimuth = atof(item.second.data().c_str());\n            if (item.first == \"vertCorrection_\")\n              vertCorrection = atof(item.second.data().c_str());\n            if (item.first == \"distCorrection_\")\n              distCorrection = atof(item.second.data().c_str());\n            if (item.first == \"vertOffsetCorrection_\")\n              vertOffsetCorrection = atof(item.second.data().c_str());\n            if (item.first == \"horizOffsetCorrection_\")\n              horizOffsetCorrection = atof(item.second.data().c_str());\n          }\n          if (index != -1) {\n            laser_corrections_[index].azimuthCorrection = azimuth;\n            laser_corrections_[index].verticalCorrection = vertCorrection;\n            laser_corrections_[index].distanceCorrection = distCorrection / 100.0;\n            laser_corrections_[index].verticalOffsetCorrection = vertOffsetCorrection / 100.0;\n            laser_corrections_[index].horizontalOffsetCorrection = horizOffsetCorrection / 100.0;\n\n            laser_corrections_[index].cosVertCorrection = std::cos (HDL_Grabber_toRadians(laser_corrections_[index].verticalCorrection));\n            laser_corrections_[index].sinVertCorrection = std::sin (HDL_Grabber_toRadians(laser_corrections_[index].verticalCorrection));\n          }\n        }\n      }\n    }\n  }\n\n  SetCorrectionsCommon();\n}\n\nvoid PacketBundleDecoder::LoadHDL32Corrections()\n{\n  double hdl32VerticalCorrections[] = {\n    -30.67, -9.3299999, -29.33, -8, -28,\n    -6.6700001, -26.67, -5.3299999, -25.33, -4, -24, -2.6700001, -22.67,\n    -1.33, -21.33, 0, -20, 1.33, -18.67, 2.6700001, -17.33, 4, -16, 5.3299999,\n    -14.67, 6.6700001, -13.33, 8, -12, 9.3299999, -10.67, 10.67 };\n\n  for (int i = 0; i < HDL_LASER_PER_FIRING; i++) {\n    laser_corrections_[i].azimuthCorrection = 0.0;\n    laser_corrections_[i].distanceCorrection = 0.0;\n    laser_corrections_[i].horizontalOffsetCorrection = 0.0;\n    laser_corrections_[i].verticalOffsetCorrection = 0.0;\n    laser_corrections_[i].verticalCorrection = hdl32VerticalCorrections[i];\n    laser_corrections_[i].sinVertCorrection = std::sin(HDL_Grabber_toRadians(hdl32VerticalCorrections[i]));\n    laser_corrections_[i].cosVertCorrection = std::cos(HDL_Grabber_toRadians(hdl32VerticalCorrections[i]));\n  }\n\n  for (int i = HDL_LASER_PER_FIRING; i < HDL_MAX_NUM_LASERS; i++) {\n    laser_corrections_[i].azimuthCorrection = 0.0;\n    laser_corrections_[i].distanceCorrection = 0.0;\n    laser_corrections_[i].horizontalOffsetCorrection = 0.0;\n    laser_corrections_[i].verticalOffsetCorrection = 0.0;\n    laser_corrections_[i].verticalCorrection = 0.0;\n    laser_corrections_[i].sinVertCorrection = 0.0;\n    laser_corrections_[i].cosVertCorrection = 1.0;\n  }\n\n  SetCorrectionsCommon();\n}\n\nvoid PacketBundleDecoder::SetCorrectionsCommon()\n{\n  for (int i = 0; i < HDL_MAX_NUM_LASERS; i++) {\n    HDLLaserCorrection correction = laser_corrections_[i];\n    laser_corrections_[i].sinVertOffsetCorrection = correction.verticalOffsetCorrection\n                                       * correction.sinVertCorrection;\n    laser_corrections_[i].cosVertOffsetCorrection = correction.verticalOffsetCorrection\n                                       * correction.cosVertCorrection;\n  }\n}\n\nstd::deque<PacketBundleDecoder::HDLFrame> PacketBundleDecoder::GetFrames()\n{\n  return _frames;\n}\n\nvoid PacketBundleDecoder::ClearFrames()\n{\n  _frames.clear();\n}\n\nbool PacketBundleDecoder::GetLatestFrame(PacketBundleDecoder::HDLFrame* frame)\n{\n  if (_frames.size()) {\n    *frame = _frames.back();\n    _frames.clear();\n    return(true);\n  }\n  return(false);\n}\n", "meta": {"hexsha": "e0d5a1081cad8518eefb4d142c2f4481bf970377", "size": 9284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PacketBundleDecoder.cpp", "max_stars_repo_name": "provizio/VelodyneHDL", "max_stars_repo_head_hexsha": "506d89cc112653184daea47fc04c6687377347ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42.0, "max_stars_repo_stars_event_min_datetime": "2017-06-19T17:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T20:44:45.000Z", "max_issues_repo_path": "PacketBundleDecoder.cpp", "max_issues_repo_name": "provizio/VelodyneHDL", "max_issues_repo_head_hexsha": "506d89cc112653184daea47fc04c6687377347ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-06-23T15:19:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T10:10:52.000Z", "max_forks_repo_path": "PacketBundleDecoder.cpp", "max_forks_repo_name": "provizio/VelodyneHDL", "max_forks_repo_head_hexsha": "506d89cc112653184daea47fc04c6687377347ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T07:32:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T04:46:49.000Z", "avg_line_length": 35.4351145038, "max_line_length": 170, "alphanum_fraction": 0.697005601, "num_tokens": 2472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.1632714561700923}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Evolution/Systems/NewtonianEuler/Limiters/Weno.hpp\"\n\n#include <array>\n#include <boost/functional/hash.hpp>  // IWYU pragma: keep\n#include <cstddef>\n#include <optional>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tags/TempTensor.hpp\"\n#include \"DataStructures/Tensor/EagerMath/DotProduct.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/SizeOfElement.hpp\"\n#include \"Domain/Structure/Direction.hpp\"  // IWYU pragma: keep\n#include \"Domain/Structure/Element.hpp\"    // IWYU pragma: keep\n#include \"Domain/Structure/ElementId.hpp\"  // IWYU pragma: keep\n#include \"Domain/Tags.hpp\"                 // IWYU pragma: keep\n#include \"Evolution/DiscontinuousGalerkin/Limiters/HwenoImpl.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodTci.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/SimpleWenoImpl.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/Weno.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoType.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Limiters/CharacteristicHelpers.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Limiters/Flattener.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Limiters/KxrcfTci.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Limiters/VariablesToLimit.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Limiters/Weno.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Tags.hpp\"\n#include \"NumericalAlgorithms/Interpolation/RegularGridInterpolant.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace {\ntemplate <size_t VolumeDim, size_t ThermodynamicDim>\nbool characteristic_simple_weno_impl(\n    const gsl::not_null<Scalar<DataVector>*> mass_density_cons,\n    const gsl::not_null<tnsr::I<DataVector, VolumeDim>*> momentum_density,\n    const gsl::not_null<Scalar<DataVector>*> energy_density,\n    const double tvb_constant, const double neighbor_linear_weight,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const std::array<double, VolumeDim>& element_size,\n    const EquationsOfState::EquationOfState<false, ThermodynamicDim>&\n        equation_of_state,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n        typename NewtonianEuler::Limiters::Weno<VolumeDim>::PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) noexcept {\n  // Storage for transforming neighbor_data into char variables\n  using CharacteristicVarsWeno =\n      Limiters::Weno<VolumeDim,\n                     tmpl::list<NewtonianEuler::Tags::VMinus,\n                                NewtonianEuler::Tags::VMomentum<VolumeDim>,\n                                NewtonianEuler::Tags::VPlus>>;\n  std::unordered_map<\n      std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n      typename CharacteristicVarsWeno::PackagedData,\n      boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n      neighbor_char_data{};\n  for (const auto& [key, data] : neighbor_data) {\n    neighbor_char_data[key].volume_data.initialize(\n        mesh.number_of_grid_points());\n    neighbor_char_data[key].mesh = data.mesh;\n    neighbor_char_data[key].element_size = data.element_size;\n  }\n\n  // Buffers for TCI\n  Limiters::Minmod_detail::BufferWrapper<VolumeDim> tci_buffer(mesh);\n  const auto effective_neighbor_sizes =\n      Limiters::Minmod_detail::compute_effective_neighbor_sizes(element,\n                                                                neighbor_data);\n\n  // Buffers for SimpleWeno extrapolated poly\n  std::unordered_map<\n      std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n      intrp::RegularGrid<VolumeDim>,\n      boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n      interpolator_buffer{};\n  std::unordered_map<\n      std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, DataVector,\n      boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n      modified_neighbor_solution_buffer{};\n\n  // Outer lambda: wraps applying SimpleWeno to the NewtonianEuler\n  // characteristics for one particular choice of characteristic decomposition\n  const auto simple_weno_convert_neighbor_data_then_limit =\n      [&tci_buffer, &interpolator_buffer, &modified_neighbor_solution_buffer,\n       &tvb_constant, &neighbor_linear_weight, &mesh, &element, &element_size,\n       &neighbor_data, &neighbor_char_data, &effective_neighbor_sizes](\n          const gsl::not_null<Scalar<DataVector>*> char_v_minus,\n          const gsl::not_null<tnsr::I<DataVector, VolumeDim>*> char_v_momentum,\n          const gsl::not_null<Scalar<DataVector>*> char_v_plus,\n          const Matrix& left_eigenvectors) noexcept -> bool {\n    // Convert neighbor data to characteristics\n    for (const auto& [key, data] : neighbor_data) {\n      NewtonianEuler::Limiters::characteristic_fields(\n          make_not_null(&(neighbor_char_data[key].volume_data)),\n          data.volume_data, left_eigenvectors);\n      NewtonianEuler::Limiters::characteristic_fields(\n          make_not_null(&(neighbor_char_data[key].means)), data.means,\n          left_eigenvectors);\n    }\n\n    bool some_component_was_limited_with_this_normal = false;\n\n    // Inner lambda: apply SimpleWeno to one particular tensor\n    const auto wrap_minmod_tci_and_simple_weno =\n        [&some_component_was_limited_with_this_normal, &tci_buffer,\n         &interpolator_buffer, &modified_neighbor_solution_buffer,\n         &tvb_constant, &neighbor_linear_weight, &mesh, &element, &element_size,\n         &neighbor_char_data,\n         &effective_neighbor_sizes](auto tag, const auto tensor) noexcept {\n          for (size_t tensor_storage_index = 0;\n               tensor_storage_index < tensor->size(); ++tensor_storage_index) {\n            // Check TCI\n            const auto effective_neighbor_means =\n                Limiters::Minmod_detail::compute_effective_neighbor_means<\n                    decltype(tag)>(tensor_storage_index, element,\n                                   neighbor_char_data);\n            const bool component_needs_limiting =\n                Limiters::Tci::tvb_minmod_indicator(\n                    make_not_null(&tci_buffer), tvb_constant,\n                    (*tensor)[tensor_storage_index], mesh, element,\n                    element_size, effective_neighbor_means,\n                    effective_neighbor_sizes);\n\n            if (component_needs_limiting) {\n              if (modified_neighbor_solution_buffer.empty()) {\n                // Allocate the neighbor solution buffers only if the limiter is\n                // triggered. This reduces allocation when no limiting occurs.\n                for (const auto& [neighbor, data] : neighbor_char_data) {\n                  (void)data;\n                  modified_neighbor_solution_buffer.insert(std::make_pair(\n                      neighbor, DataVector(mesh.number_of_grid_points())));\n                }\n              }\n              Limiters::Weno_detail::simple_weno_impl<decltype(tag)>(\n                  make_not_null(&interpolator_buffer),\n                  make_not_null(&modified_neighbor_solution_buffer), tensor,\n                  neighbor_linear_weight, tensor_storage_index, mesh, element,\n                  neighbor_char_data);\n              some_component_was_limited_with_this_normal = true;\n            }\n          }\n        };\n    wrap_minmod_tci_and_simple_weno(NewtonianEuler::Tags::VMinus{},\n                                    char_v_minus);\n    wrap_minmod_tci_and_simple_weno(\n        NewtonianEuler::Tags::VMomentum<VolumeDim>{}, char_v_momentum);\n    wrap_minmod_tci_and_simple_weno(NewtonianEuler::Tags::VPlus{}, char_v_plus);\n    return some_component_was_limited_with_this_normal;\n  };\n\n  return NewtonianEuler::Limiters::\n      apply_limiter_to_characteristic_fields_in_all_directions(\n          mass_density_cons, momentum_density, energy_density, mesh,\n          equation_of_state, simple_weno_convert_neighbor_data_then_limit);\n}\n\ntemplate <size_t VolumeDim, size_t ThermodynamicDim>\nbool characteristic_hweno_impl(\n    const gsl::not_null<Scalar<DataVector>*> mass_density_cons,\n    const gsl::not_null<tnsr::I<DataVector, VolumeDim>*> momentum_density,\n    const gsl::not_null<Scalar<DataVector>*> energy_density,\n    const double kxrcf_constant, const double neighbor_linear_weight,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const std::array<double, VolumeDim>& element_size,\n    const Scalar<DataVector>& det_logical_to_inertial_jacobian,\n    const typename evolution::dg::Tags::NormalCovectorAndMagnitude<\n        VolumeDim>::type& normals_and_magnitudes,\n    const EquationsOfState::EquationOfState<false, ThermodynamicDim>&\n        equation_of_state,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n        typename NewtonianEuler::Limiters::Weno<VolumeDim>::PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) noexcept {\n  // Hweno checks TCI before limiting any tensors\n  const bool cell_is_troubled = NewtonianEuler::Limiters::Tci::kxrcf_indicator(\n      kxrcf_constant, *mass_density_cons, *momentum_density, *energy_density,\n      mesh, element, element_size, det_logical_to_inertial_jacobian,\n      normals_and_magnitudes, neighbor_data);\n  if (not cell_is_troubled) {\n    // No limiting is needed\n    return false;\n  }\n\n  // Storage for transforming neighbor_data into char variables\n  using CharacteristicVarsWeno =\n      Limiters::Weno<VolumeDim,\n                     tmpl::list<NewtonianEuler::Tags::VMinus,\n                                NewtonianEuler::Tags::VMomentum<VolumeDim>,\n                                NewtonianEuler::Tags::VPlus>>;\n  std::unordered_map<\n      std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n      typename CharacteristicVarsWeno::PackagedData,\n      boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n      neighbor_char_data{};\n  for (const auto& [key, data] : neighbor_data) {\n    neighbor_char_data[key].volume_data.initialize(\n        mesh.number_of_grid_points());\n    neighbor_char_data[key].mesh = data.mesh;\n    neighbor_char_data[key].element_size = data.element_size;\n  }\n\n  // Buffers for Hweno extrapolated poly\n  std::unordered_map<\n      std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, DataVector,\n      boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n      modified_neighbor_solution_buffer{};\n  for (const auto& [neighbor, data] : neighbor_char_data) {\n    (void)data;\n    modified_neighbor_solution_buffer.insert(\n        std::make_pair(neighbor, DataVector(mesh.number_of_grid_points())));\n  }\n\n  // Lambda wraps applying Hweno to the NewtonianEuler characteristics for one\n  // particular choice of characteristic decomposition\n  const auto hweno_convert_neighbor_data_then_limit =\n      [&modified_neighbor_solution_buffer, &neighbor_linear_weight, &mesh,\n       &element, &neighbor_data, &neighbor_char_data](\n          const gsl::not_null<Scalar<DataVector>*> char_v_minus,\n          const gsl::not_null<tnsr::I<DataVector, VolumeDim>*> char_v_momentum,\n          const gsl::not_null<Scalar<DataVector>*> char_v_plus,\n          const Matrix& left_eigenvectors) noexcept -> bool {\n    // Convert neighbor data to characteristics\n    for (const auto& [key, data] : neighbor_data) {\n      NewtonianEuler::Limiters::characteristic_fields(\n          make_not_null(&(neighbor_char_data[key].volume_data)),\n          data.volume_data, left_eigenvectors);\n      NewtonianEuler::Limiters::characteristic_fields(\n          make_not_null(&(neighbor_char_data[key].means)), data.means,\n          left_eigenvectors);\n    }\n\n    ::Limiters::Weno_detail::hweno_impl<NewtonianEuler::Tags::VMinus>(\n        make_not_null(&modified_neighbor_solution_buffer), char_v_minus,\n        neighbor_linear_weight, mesh, element, neighbor_char_data);\n    ::Limiters::Weno_detail::hweno_impl<\n        NewtonianEuler::Tags::VMomentum<VolumeDim>>(\n        make_not_null(&modified_neighbor_solution_buffer), char_v_momentum,\n        neighbor_linear_weight, mesh, element, neighbor_char_data);\n    ::Limiters::Weno_detail::hweno_impl<NewtonianEuler::Tags::VPlus>(\n        make_not_null(&modified_neighbor_solution_buffer), char_v_plus,\n        neighbor_linear_weight, mesh, element, neighbor_char_data);\n    return true;  // all components were limited\n  };\n\n  NewtonianEuler::Limiters::\n      apply_limiter_to_characteristic_fields_in_all_directions(\n          mass_density_cons, momentum_density, energy_density, mesh,\n          equation_of_state, hweno_convert_neighbor_data_then_limit);\n  return true;  // all components were limited\n}\n\ntemplate <size_t VolumeDim>\nbool conservative_hweno_impl(\n    const gsl::not_null<Scalar<DataVector>*> mass_density_cons,\n    const gsl::not_null<tnsr::I<DataVector, VolumeDim>*> momentum_density,\n    const gsl::not_null<Scalar<DataVector>*> energy_density,\n    const double kxrcf_constant, const double neighbor_linear_weight,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const std::array<double, VolumeDim>& element_size,\n    const Scalar<DataVector>& det_logical_to_inertial_jacobian,\n    const typename evolution::dg::Tags::NormalCovectorAndMagnitude<\n        VolumeDim>::type& normals_and_magnitudes,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n        typename NewtonianEuler::Limiters::Weno<VolumeDim>::PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) noexcept {\n  // Hweno checks TCI before limiting any tensors\n  const bool cell_is_troubled = NewtonianEuler::Limiters::Tci::kxrcf_indicator(\n      kxrcf_constant, *mass_density_cons, *momentum_density, *energy_density,\n      mesh, element, element_size, det_logical_to_inertial_jacobian,\n      normals_and_magnitudes, neighbor_data);\n  if (not cell_is_troubled) {\n    // No limiting is needed\n    return false;\n  }\n\n  // Buffers for Hweno extrapolated poly\n  std::unordered_map<\n      std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, DataVector,\n      boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n      modified_neighbor_solution_buffer{};\n  for (const auto& [neighbor, data] : neighbor_data) {\n    (void)data;\n    modified_neighbor_solution_buffer.insert(\n        std::make_pair(neighbor, DataVector(mesh.number_of_grid_points())));\n  }\n\n  ::Limiters::Weno_detail::hweno_impl<NewtonianEuler::Tags::MassDensityCons>(\n      make_not_null(&modified_neighbor_solution_buffer), mass_density_cons,\n      neighbor_linear_weight, mesh, element, neighbor_data);\n  ::Limiters::Weno_detail::hweno_impl<\n      NewtonianEuler::Tags::MomentumDensity<VolumeDim>>(\n      make_not_null(&modified_neighbor_solution_buffer), momentum_density,\n      neighbor_linear_weight, mesh, element, neighbor_data);\n  ::Limiters::Weno_detail::hweno_impl<NewtonianEuler::Tags::EnergyDensity>(\n      make_not_null(&modified_neighbor_solution_buffer), energy_density,\n      neighbor_linear_weight, mesh, element, neighbor_data);\n  return true;  // all components were limited\n}\n\n}  // namespace\n\nnamespace NewtonianEuler::Limiters {\n\ntemplate <size_t VolumeDim>\nWeno<VolumeDim>::Weno(\n    const ::Limiters::WenoType weno_type,\n    const NewtonianEuler::Limiters::VariablesToLimit vars_to_limit,\n    const double neighbor_linear_weight,\n    const std::optional<double> tvb_constant,\n    const std::optional<double> kxrcf_constant, const bool apply_flattener,\n    const bool disable_for_debugging, const Options::Context& context)\n    : weno_type_(weno_type),\n      vars_to_limit_(vars_to_limit),\n      neighbor_linear_weight_(neighbor_linear_weight),\n      tvb_constant_(tvb_constant),\n      kxrcf_constant_(kxrcf_constant),\n      apply_flattener_(apply_flattener),\n      disable_for_debugging_(disable_for_debugging),\n      conservative_vars_weno_(\n          weno_type_, neighbor_linear_weight_,\n          tvb_constant_.value_or(std::numeric_limits<double>::signaling_NaN()),\n          disable_for_debugging_) {\n  if (weno_type == ::Limiters::WenoType::Hweno) {\n    if (tvb_constant.has_value() or not kxrcf_constant.has_value()) {\n      PARSE_ERROR(context,\n                  \"The Hweno limiter uses the KXRCF TCI. The TvbConstant must \"\n                  \"be set to 'None', and the KxrcfConstant must be set to a \"\n                  \"non-negative value.\");\n    }\n    if (kxrcf_constant.value() < 0.0) {\n      PARSE_ERROR(context, \"The KXRCF constant must be non-negative, but got: \"\n                               << kxrcf_constant.value());\n    }\n  } else {  // SimpleWeno\n    if (not tvb_constant.has_value() or kxrcf_constant.has_value()) {\n      PARSE_ERROR(context,\n                  \"The SimpleWeno limiter uses the TVB minmod TCI. The \"\n                  \"TvbConstant must be set to a non-negative value, and the \"\n                  \"KxrcfConstant must be set to 'None'.\");\n    }\n    if (tvb_constant.value() < 0.0) {\n      PARSE_ERROR(context, \"The TVB constant must be non-negative, but got: \"\n                               << tvb_constant.value());\n    }\n  }\n}\n\ntemplate <size_t VolumeDim>\n// NOLINTNEXTLINE(google-runtime-references)\nvoid Weno<VolumeDim>::pup(PUP::er& p) noexcept {\n  p | weno_type_;\n  p | vars_to_limit_;\n  p | neighbor_linear_weight_;\n  p | tvb_constant_;\n  p | kxrcf_constant_;\n  p | apply_flattener_;\n  p | disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim>\nvoid Weno<VolumeDim>::package_data(\n    const gsl::not_null<PackagedData*> packaged_data,\n    const Scalar<DataVector>& mass_density_cons,\n    const tnsr::I<DataVector, VolumeDim>& momentum_density,\n    const Scalar<DataVector>& energy_density, const Mesh<VolumeDim>& mesh,\n    const std::array<double, VolumeDim>& element_size,\n    const OrientationMap<VolumeDim>& orientation_map) const noexcept {\n  conservative_vars_weno_.package_data(packaged_data, mass_density_cons,\n                                       momentum_density, energy_density, mesh,\n                                       element_size, orientation_map);\n}\n\ntemplate <size_t VolumeDim>\ntemplate <size_t ThermodynamicDim>\nbool Weno<VolumeDim>::operator()(\n    const gsl::not_null<Scalar<DataVector>*> mass_density_cons,\n    const gsl::not_null<tnsr::I<DataVector, VolumeDim>*> momentum_density,\n    const gsl::not_null<Scalar<DataVector>*> energy_density,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const std::array<double, VolumeDim>& element_size,\n    const Scalar<DataVector>& det_inv_logical_to_inertial_jacobian,\n    const typename evolution::dg::Tags::NormalCovectorAndMagnitude<\n        VolumeDim>::type& normals_and_magnitudes,\n    const EquationsOfState::EquationOfState<false, ThermodynamicDim>&\n        equation_of_state,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) const noexcept {\n  if (UNLIKELY(disable_for_debugging_)) {\n    // Do not modify input tensors\n    return false;\n  }\n\n  // Enforce restrictions on h-refinement, p-refinement\n  if (UNLIKELY(alg::any_of(element.neighbors(),\n                           [](const auto& direction_neighbors) noexcept {\n                             return direction_neighbors.second.size() != 1;\n                           }))) {\n    ERROR(\"The Weno limiter does not yet support h-refinement\");\n    // Removing this limitation will require:\n    // - Generalizing the computation of the modified neighbor solutions.\n    // - Generalizing the WENO weighted sum for multiple neighbors in each\n    //   direction.\n  }\n  alg::for_each(neighbor_data, [&mesh](const auto& neighbor_and_data) noexcept {\n    if (UNLIKELY(neighbor_and_data.second.mesh != mesh)) {\n      ERROR(\"The Weno limiter does not yet support p-refinement\");\n      // Removing this limitation will require generalizing the\n      // computation of the modified neighbor solutions.\n    }\n  });\n\n  // Checks for the post-timestep, pre-limiter NewtonianEuler state:\n#ifdef SPECTRE_DEBUG\n  const double mean_density = mean_value(get(*mass_density_cons), mesh);\n  ASSERT(mean_density > 0.0,\n         \"Positivity was violated on a cell-average level.\");\n  if (ThermodynamicDim == 2) {\n    const double mean_energy = mean_value(get(*energy_density), mesh);\n    ASSERT(mean_energy > 0.0,\n           \"Positivity was violated on a cell-average level.\");\n  }\n#endif  // SPECTRE_DEBUG\n\n  bool limiter_activated = false;\n\n  // Small possible optimization: only compute this if needed\n  const Scalar<DataVector> det_logical_to_inertial_jacobian{\n      1. / get(det_inv_logical_to_inertial_jacobian)};\n\n  if (weno_type_ == ::Limiters::WenoType::Hweno) {\n    if (vars_to_limit_ ==\n        NewtonianEuler::Limiters::VariablesToLimit::Characteristic) {\n      // impl function handles specialized TCI + char transform\n      limiter_activated = characteristic_hweno_impl(\n          mass_density_cons, momentum_density, energy_density,\n          kxrcf_constant_.value(), neighbor_linear_weight_, mesh, element,\n          element_size, det_logical_to_inertial_jacobian,\n          normals_and_magnitudes, equation_of_state, neighbor_data);\n    } else {\n      // impl function handles specialized TCI\n      limiter_activated = conservative_hweno_impl(\n          mass_density_cons, momentum_density, energy_density,\n          kxrcf_constant_.value(), neighbor_linear_weight_, mesh, element,\n          element_size, det_logical_to_inertial_jacobian,\n          normals_and_magnitudes, neighbor_data);\n    }\n  } else if (weno_type_ == ::Limiters::WenoType::SimpleWeno) {\n    if (vars_to_limit_ ==\n        NewtonianEuler::Limiters::VariablesToLimit::Characteristic) {\n      // impl function handles char transform\n      limiter_activated = characteristic_simple_weno_impl(\n          mass_density_cons, momentum_density, energy_density,\n          tvb_constant_.value(), neighbor_linear_weight_, mesh, element,\n          element_size, equation_of_state, neighbor_data);\n    } else {\n      // Fall back to generic SimpleWeno\n      limiter_activated = conservative_vars_weno_(\n          mass_density_cons, momentum_density, energy_density, mesh, element,\n          element_size, neighbor_data);\n    }\n  }\n\n  if (apply_flattener_) {\n    const auto flattener_action = flatten_solution(\n        mass_density_cons, momentum_density, energy_density, mesh,\n        det_logical_to_inertial_jacobian, equation_of_state);\n    if (flattener_action != FlattenerAction::NoOp) {\n      limiter_activated = true;\n    }\n  }\n\n  // Checks for the post-limiter NewtonianEuler state:\n#ifdef SPECTRE_DEBUG\n  ASSERT(min(get(*mass_density_cons)) > 0.0, \"Bad density after limiting.\");\n  if constexpr (ThermodynamicDim == 2) {\n    const auto specific_internal_energy = Scalar<DataVector>{\n        get(*energy_density) / get(*mass_density_cons) -\n        0.5 * get(dot_product(*momentum_density, *momentum_density)) /\n            square(get(*mass_density_cons))};\n    const auto pressure = equation_of_state.pressure_from_density_and_energy(\n        *mass_density_cons, specific_internal_energy);\n    ASSERT(min(get(pressure)) > 0.0, \"Bad energy after limiting.\");\n  }\n#endif  // SPECTRE_DEBUG\n\n  return limiter_activated;\n}\n\ntemplate <size_t LocalDim>\nbool operator==(const Weno<LocalDim>& lhs, const Weno<LocalDim>& rhs) noexcept {\n  // No need to compare the conservative_vars_weno_ member variable because\n  // it is constructed from the other member variables.\n  return lhs.weno_type_ == rhs.weno_type_ and\n         lhs.vars_to_limit_ == rhs.vars_to_limit_ and\n         lhs.neighbor_linear_weight_ == rhs.neighbor_linear_weight_ and\n         lhs.tvb_constant_ == rhs.tvb_constant_ and\n         lhs.kxrcf_constant_ == rhs.kxrcf_constant_ and\n         lhs.apply_flattener_ == rhs.apply_flattener_ and\n         lhs.disable_for_debugging_ == rhs.disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim>\nbool operator!=(const Weno<VolumeDim>& lhs,\n                const Weno<VolumeDim>& rhs) noexcept {\n  return not(lhs == rhs);\n}\n\n#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)\n#define THERMO_DIM(data) BOOST_PP_TUPLE_ELEM(1, data)\n\n#define INSTANTIATE(_, data)                                                \\\n  template class Weno<DIM(data)>;                                           \\\n  template bool operator==(const Weno<DIM(data)>&, const Weno<DIM(data)>&); \\\n  template bool operator!=(const Weno<DIM(data)>&, const Weno<DIM(data)>&);\n\nGENERATE_INSTANTIATIONS(INSTANTIATE, (1, 2, 3))\n\n#undef INSTANTIATE\n\n#define INSTANTIATE(_, data)                                                   \\\n  template bool Weno<DIM(data)>::operator()(                                   \\\n      const gsl::not_null<Scalar<DataVector>*>,                                \\\n      const gsl::not_null<tnsr::I<DataVector, DIM(data)>*>,                    \\\n      const gsl::not_null<Scalar<DataVector>*>, const Mesh<DIM(data)>&,        \\\n      const Element<DIM(data)>&, const std::array<double, DIM(data)>&,         \\\n      const Scalar<DataVector>&,                                               \\\n      const typename evolution::dg::Tags::NormalCovectorAndMagnitude<DIM(      \\\n          data)>::type&,                                                       \\\n      const EquationsOfState::EquationOfState<false, THERMO_DIM(data)>&,       \\\n      const std::unordered_map<                                                \\\n          std::pair<Direction<DIM(data)>, ElementId<DIM(data)>>, PackagedData, \\\n          boost::hash<                                                         \\\n              std::pair<Direction<DIM(data)>, ElementId<DIM(data)>>>>&)        \\\n      const noexcept;\n\nGENERATE_INSTANTIATIONS(INSTANTIATE, (1, 2, 3), (1, 2))\n\n#undef INSTANTIATE\n#undef DIM\n#undef THERMO_DIM\n\n}  // namespace NewtonianEuler::Limiters\n", "meta": {"hexsha": "d78465b8aaa9383ea4d8bfa169b338ae9241e4cc", "size": 26374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/NewtonianEuler/Limiters/Weno.cpp", "max_stars_repo_name": "nring21/spectre", "max_stars_repo_head_hexsha": "9e702db4d7ca729e12e724294d2f06cc7f3cfae0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-01T06:07:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-01T06:07:16.000Z", "max_issues_repo_path": "src/Evolution/Systems/NewtonianEuler/Limiters/Weno.cpp", "max_issues_repo_name": "nring21/spectre", "max_issues_repo_head_hexsha": "9e702db4d7ca729e12e724294d2f06cc7f3cfae0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-06-04T20:26:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-27T14:54:55.000Z", "max_forks_repo_path": "src/Evolution/Systems/NewtonianEuler/Limiters/Weno.cpp", "max_forks_repo_name": "nring21/spectre", "max_forks_repo_head_hexsha": "9e702db4d7ca729e12e724294d2f06cc7f3cfae0", "max_forks_repo_licenses": ["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.0124777184, "max_line_length": 80, "alphanum_fraction": 0.6975430348, "num_tokens": 6156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.16326373918829656}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017-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// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 5.0.0\n\n// Original copyright notice:\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_PROJECTIONS_LAEA_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_LAEA_HPP\n\n#include <boost/config.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_auth.hpp>\n#include <boost/geometry/srs/projections/impl/pj_qsfn.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace laea\n    {\n            static const double epsilon10 = 1.e-10;\n\n            enum mode_type {\n                n_pole = 0,\n                s_pole = 1,\n                equit  = 2,\n                obliq  = 3\n            };\n\n            template <typename T>\n            struct par_laea\n            {\n                T   sinb1;\n                T   cosb1;\n                T   xmf;\n                T   ymf;\n                T   mmf;\n                T   qp;\n                T   dd;\n                T   rq;\n                detail::apa<T> apa;\n                mode_type mode;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_laea_ellipsoid\n                : public base_t_fi<base_laea_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                par_laea<T> m_proj_parm;\n\n                inline base_laea_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_laea_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(e_forward)  ellipsoid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n\n                    T coslam, sinlam, sinphi, q, sinb=0.0, cosb=0.0, b=0.0;\n\n                    coslam = cos(lp_lon);\n                    sinlam = sin(lp_lon);\n                    sinphi = sin(lp_lat);\n                    q = pj_qsfn(sinphi, this->m_par.e, this->m_par.one_es);\n\n                    if (this->m_proj_parm.mode == obliq || this->m_proj_parm.mode == equit) {\n                        sinb = q / this->m_proj_parm.qp;\n                        cosb = sqrt(1. - sinb * sinb);\n                    }\n\n                    switch (this->m_proj_parm.mode) {\n                    case obliq:\n                        b = 1. + this->m_proj_parm.sinb1 * sinb + this->m_proj_parm.cosb1 * cosb * coslam;\n                        break;\n                    case equit:\n                        b = 1. + cosb * coslam;\n                        break;\n                    case n_pole:\n                        b = half_pi + lp_lat;\n                        q = this->m_proj_parm.qp - q;\n                        break;\n                    case s_pole:\n                        b = lp_lat - half_pi;\n                        q = this->m_proj_parm.qp + q;\n                        break;\n                    }\n                    if (fabs(b) < epsilon10) {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    }\n\n                    switch (this->m_proj_parm.mode) {\n                    case obliq:\n                        b = sqrt(2. / b);\n                        xy_y = this->m_proj_parm.ymf * b * (this->m_proj_parm.cosb1 * sinb - this->m_proj_parm.sinb1 * cosb * coslam);\n                        goto eqcon;\n                        break;\n                    case equit:\n                        b = sqrt(2. / (1. + cosb * coslam));\n                        xy_y = b * sinb * this->m_proj_parm.ymf;\n                eqcon:\n                        xy_x = this->m_proj_parm.xmf * b * cosb * sinlam;\n                        break;\n                    case n_pole:\n                    case s_pole:\n                        if (q >= 0.) {\n                            b = sqrt(q);\n                            xy_x = b * sinlam;\n                            xy_y = coslam * (this->m_proj_parm.mode == s_pole ? b : -b);\n                        } else\n                            xy_x = xy_y = 0.;\n                        break;\n                    }\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T xy_x, T xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    T cCe, sCe, q, rho, ab=0.0;\n\n                    switch (this->m_proj_parm.mode) {\n                    case equit:\n                    case obliq:\n                        xy_x /= this->m_proj_parm.dd;\n                        xy_y *=  this->m_proj_parm.dd;\n                        rho = boost::math::hypot(xy_x, xy_y);\n                        if (rho < epsilon10) {\n                            lp_lon = 0.;\n                            lp_lat = this->m_par.phi0;\n                            return;\n                        }\n                        sCe = 2. * asin(.5 * rho / this->m_proj_parm.rq);\n                        cCe = cos(sCe);\n                        sCe = sin(sCe);\n                        xy_x *= sCe;\n                        if (this->m_proj_parm.mode == obliq) {\n                            ab = cCe * this->m_proj_parm.sinb1 + xy_y * sCe * this->m_proj_parm.cosb1 / rho;\n                            xy_y = rho * this->m_proj_parm.cosb1 * cCe - xy_y * this->m_proj_parm.sinb1 * sCe;\n                        } else {\n                            ab = xy_y * sCe / rho;\n                            xy_y = rho * cCe;\n                        }\n                        break;\n                    case n_pole:\n                        xy_y = -xy_y;\n                        BOOST_FALLTHROUGH;\n                    case s_pole:\n                        q = (xy_x * xy_x + xy_y * xy_y);\n                        if (q == 0.0) {\n                            lp_lon = 0.;\n                            lp_lat = this->m_par.phi0;\n                            return;\n                        }\n                        ab = 1. - q / this->m_proj_parm.qp;\n                        if (this->m_proj_parm.mode == s_pole)\n                            ab = - ab;\n                        break;\n                    }\n                    lp_lon = atan2(xy_x, xy_y);\n                    lp_lat = pj_authlat(asin(ab), this->m_proj_parm.apa);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"laea_ellipsoid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_laea_spheroid\n                : public base_t_fi<base_laea_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_laea<T> m_proj_parm;\n\n                inline base_laea_spheroid(const Parameters& par)\n                    : base_t_fi<base_laea_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    static const T fourth_pi = detail::fourth_pi<T>();\n\n                    T  coslam, cosphi, sinphi;\n\n                    sinphi = sin(lp_lat);\n                    cosphi = cos(lp_lat);\n                    coslam = cos(lp_lon);\n                    switch (this->m_proj_parm.mode) {\n                    case equit:\n                        xy_y = 1. + cosphi * coslam;\n                        goto oblcon;\n                    case obliq:\n                        xy_y = 1. + this->m_proj_parm.sinb1 * sinphi + this->m_proj_parm.cosb1 * cosphi * coslam;\n                oblcon:\n                        if (xy_y <= epsilon10) {\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                        }\n                        xy_y = sqrt(2. / xy_y);\n                        xy_x = xy_y * cosphi * sin(lp_lon);\n                        xy_y *= this->m_proj_parm.mode == equit ? sinphi :\n                           this->m_proj_parm.cosb1 * sinphi - this->m_proj_parm.sinb1 * cosphi * coslam;\n                        break;\n                    case n_pole:\n                        coslam = -coslam;\n                        BOOST_FALLTHROUGH;\n                    case s_pole:\n                        if (fabs(lp_lat + this->m_par.phi0) < epsilon10) {\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                        }\n                        xy_y = fourth_pi - lp_lat * .5;\n                        xy_y = 2. * (this->m_proj_parm.mode == s_pole ? cos(xy_y) : sin(xy_y));\n                        xy_x = xy_y * sin(lp_lon);\n                        xy_y *= coslam;\n                        break;\n                    }\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T xy_x, T xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n\n                    T  cosz=0.0, rh, sinz=0.0;\n\n                    rh = boost::math::hypot(xy_x, xy_y);\n                    if ((lp_lat = rh * .5 ) > 1.) {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    }\n                    lp_lat = 2. * asin(lp_lat);\n                    if (this->m_proj_parm.mode == obliq || this->m_proj_parm.mode == equit) {\n                        sinz = sin(lp_lat);\n                        cosz = cos(lp_lat);\n                    }\n                    switch (this->m_proj_parm.mode) {\n                    case equit:\n                        lp_lat = fabs(rh) <= epsilon10 ? 0. : asin(xy_y * sinz / rh);\n                        xy_x *= sinz;\n                        xy_y = cosz * rh;\n                        break;\n                    case obliq:\n                        lp_lat = fabs(rh) <= epsilon10 ? this->m_par.phi0 :\n                           asin(cosz * this->m_proj_parm.sinb1 + xy_y * sinz * this->m_proj_parm.cosb1 / rh);\n                        xy_x *= sinz * this->m_proj_parm.cosb1;\n                        xy_y = (cosz - sin(lp_lat) * this->m_proj_parm.sinb1) * rh;\n                        break;\n                    case n_pole:\n                        xy_y = -xy_y;\n                        lp_lat = half_pi - lp_lat;\n                        break;\n                    case s_pole:\n                        lp_lat -= half_pi;\n                        break;\n                    }\n                    lp_lon = (xy_y == 0. && (this->m_proj_parm.mode == equit || this->m_proj_parm.mode == obliq)) ?\n                        0. : atan2(xy_x, xy_y);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"laea_spheroid\";\n                }\n\n            };\n\n            // Lambert Azimuthal Equal Area\n            template <typename Parameters, typename T>\n            inline void setup_laea(Parameters& par, par_laea<T>& proj_parm)\n            {\n                static const T half_pi = detail::half_pi<T>();\n\n                T t;\n\n                t = fabs(par.phi0);\n                if (fabs(t - half_pi) < epsilon10)\n                    proj_parm.mode = par.phi0 < 0. ? s_pole : n_pole;\n                else if (fabs(t) < epsilon10)\n                    proj_parm.mode = equit;\n                else\n                    proj_parm.mode = obliq;\n                if (par.es != 0.0) {\n                    double sinphi;\n\n                    par.e = sqrt(par.es);\n                    proj_parm.qp = pj_qsfn(1., par.e, par.one_es);\n                    proj_parm.mmf = .5 / (1. - par.es);\n                    proj_parm.apa = pj_authset<T>(par.es);\n                    switch (proj_parm.mode) {\n                    case n_pole:\n                    case s_pole:\n                        proj_parm.dd = 1.;\n                        break;\n                    case equit:\n                        proj_parm.dd = 1. / (proj_parm.rq = sqrt(.5 * proj_parm.qp));\n                        proj_parm.xmf = 1.;\n                        proj_parm.ymf = .5 * proj_parm.qp;\n                        break;\n                    case obliq:\n                        proj_parm.rq = sqrt(.5 * proj_parm.qp);\n                        sinphi = sin(par.phi0);\n                        proj_parm.sinb1 = pj_qsfn(sinphi, par.e, par.one_es) / proj_parm.qp;\n                        proj_parm.cosb1 = sqrt(1. - proj_parm.sinb1 * proj_parm.sinb1);\n                        proj_parm.dd = cos(par.phi0) / (sqrt(1. - par.es * sinphi * sinphi) *\n                           proj_parm.rq * proj_parm.cosb1);\n                        proj_parm.ymf = (proj_parm.xmf = proj_parm.rq) / proj_parm.dd;\n                        proj_parm.xmf *= proj_parm.dd;\n                        break;\n                    }\n                } else {\n                    if (proj_parm.mode == obliq) {\n                        proj_parm.sinb1 = sin(par.phi0);\n                        proj_parm.cosb1 = cos(par.phi0);\n                    }\n                }\n            }\n\n    }} // namespace laea\n    #endif // doxygen\n\n    /*!\n        \\brief Lambert Azimuthal Equal Area 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         - Azimuthal\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_laea.gif\n    */\n    template <typename T, typename Parameters>\n    struct laea_ellipsoid : public detail::laea::base_laea_ellipsoid<T, Parameters>\n    {\n        template <typename Params>\n        inline laea_ellipsoid(Params const& , Parameters const& par)\n            : detail::laea::base_laea_ellipsoid<T, Parameters>(par)\n        {\n            detail::laea::setup_laea(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Lambert Azimuthal Equal Area 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         - Azimuthal\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_laea.gif\n    */\n    template <typename T, typename Parameters>\n    struct laea_spheroid : public detail::laea::base_laea_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline laea_spheroid(Params const& , Parameters const& par)\n            : detail::laea::base_laea_spheroid<T, Parameters>(par)\n        {\n            detail::laea::setup_laea(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_laea, laea_spheroid, laea_ellipsoid)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI2(laea_entry, laea_spheroid, laea_ellipsoid)\n        \n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(laea_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(laea, laea_entry)\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_LAEA_HPP\n\n", "meta": {"hexsha": "9c4560a949c748ecf34ed42dfabf21bae9f16af5", "size": 17860, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/laea.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/geometry/srs/projections/proj/laea.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/geometry/srs/projections/proj/laea.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": 40.5909090909, "max_line_length": 134, "alphanum_fraction": 0.4775475924, "num_tokens": 3962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.28457601635158564, "lm_q1q2_score": 0.163255115859757}}
{"text": "/*********************************************************************\n *\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 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 * Author: TKruse\n *********************************************************************/\n\n#include <ursa_local_planner/ursa_obstacle_cost_function.h>\n#include <cmath>\n#include <Eigen/Core>\n#include <ros/console.h>\n#include <costmap_2d/cost_values.h>\n#include <iostream>\nusing namespace std;\nusing namespace costmap_2d;\n\nnamespace ursa_local_planner {\n\nUrsaObstacleCostFunction::UrsaObstacleCostFunction(costmap_2d::Costmap2D* costmap) \n    : costmap_(costmap), sum_scores_(false) {\n  if (costmap != NULL) {\n    world_model_ = new ursa_local_planner::UrsaCostmapModel(*costmap_);\n  }\n}\n\nUrsaObstacleCostFunction::~UrsaObstacleCostFunction() {\n  if (world_model_ != NULL) {\n    delete world_model_;\n  }\n}\n\nvoid UrsaObstacleCostFunction::setParams(double max_trans_vel, double max_scaling_factor, double scaling_speed) {\n  // TODO: move this to prepare if possible\n  max_trans_vel_ = max_trans_vel;\n  max_scaling_factor_ = max_scaling_factor;\n  scaling_speed_ = scaling_speed;\n}\n\nvoid UrsaObstacleCostFunction::setFootprint(std::vector<geometry_msgs::Point> footprint_spec) {\n  footprint_spec_ = footprint_spec;\n}\n\nbool UrsaObstacleCostFunction::prepare() {\n  return true;\n}\n\ninline bool checkIfInsideRadius(double x, double y, double pose_x, double pose_y, double multiplier, double radius){\n    // get global orientation at robot radius\n    int i = 0;\n    while   (((pose_x - radius*multiplier) <= x) &&\n             (x < (pose_x + radius*multiplier))  &&\n             ((pose_y - radius*multiplier) <= y) &&\n             (y < (pose_y + radius*multiplier))) {\n                return 1;\n            }\n    return 0;\n}\n\ndouble UrsaObstacleCostFunction::scoreTrajectory(base_local_planner::Trajectory &traj) {\n  double cost = 0;\n  double scale = getScalingFactor(traj, scaling_speed_, max_trans_vel_, max_scaling_factor_);\n  double px, py, pth;\n  if (footprint_spec_.size() == 0) {\n    // Bug, should never happen\n    ROS_ERROR(\"Footprint spec is empty, maybe missing call to setFootprint?\");\n    return -9;\n  }\n\n  double dx, dy, dth;\n  traj.getPoint(0, dx, dy, dth);\n  for (unsigned int i = 0; i < traj.getPointsSize(); ++i) {\n    traj.getPoint(i, px, py, pth);\n    double f_cost = footprintCost(px, py, pth,\n        scale, footprint_spec_,\n        costmap_, world_model_);\n\n    if(f_cost < 0){\n        return f_cost;\n    }\n    // return the cost of a point just outside the radius of drone\n    if (checkIfInsideRadius(px,py,dx,dy,1,footprint_spec_[0].x)){\n      cost=f_cost;\n      continue;\n      //ROS_INFO(\"obstacle cost -- 1 -- %f\", f_cost); // returns cost of last point on trajectory\n      //return f_cost;\n    }\n    // if(sum_scores_)\n    //     cost +=  f_cost;\n    // else\n    //     cost = f_cost;\n    // if (f_cost > cost){\n    //   cost = f_cost;      \n    // }\n    if (f_cost>cost){\n      cost=f_cost;\n    }\n    \n  }\n  // cost = cost / traj.getPointsSize();\n  // ROS_INFO(\"obstacle cost -- %f\", cost); // returns cost of last point on trajectory\n  return cost;\n}\n\ndouble UrsaObstacleCostFunction::getScalingFactor(base_local_planner::Trajectory &traj, double scaling_speed, double max_trans_vel, double max_scaling_factor) {\n  double vmag = hypot(traj.xv_, traj.yv_);\n\n  //if we're over a certain speed threshold, we'll scale the robot's\n  //footprint to make it either slow down or stay further from walls\n  double scale = 1.0;\n  if (vmag > scaling_speed) {\n    //scale up to the max scaling factor linearly... this could be changed later\n    double ratio = (vmag - scaling_speed) / (max_trans_vel - scaling_speed);\n    scale = max_scaling_factor * ratio + 1.0;\n  }\n  return scale;\n}\n\ndouble UrsaObstacleCostFunction::footprintCost (\n    const double& x,\n    const double& y,\n    const double& th,\n    double scale,\n    std::vector<geometry_msgs::Point> footprint_spec,\n    costmap_2d::Costmap2D* costmap,\n    base_local_planner::WorldModel* world_model) {\n\n  //check if the footprint is legal\n  // TODO: Cache inscribed radius\n  //double footprint_cost = world_model->footprintCost(x, y, th, footprint_spec);\n\n  unsigned int cell_x, cell_y;\n  //we won't allow trajectories that go off the map... shouldn't happen that often anyways\n  if ( ! costmap->worldToMap(x, y, cell_x, cell_y)) {\n    return -7.0;\n  }\n  double footprint_cost = costmap->getCost(cell_x, cell_y);\n  if (footprint_cost < 0) {\n    return -6.0;\n  }\n  //if(cost == LETHAL_OBSTACLE || cost == INSCRIBED_INFLATED_OBSTACLE)\n  if(footprint_cost == LETHAL_OBSTACLE || footprint_cost == INSCRIBED_INFLATED_OBSTACLE || footprint_cost == NO_INFORMATION)\n    return -1.0;\n  return footprint_cost;\n\n  // return the max of (cell cost at footprint (last two points)) and (cell cost at centre of robot)\n  // double occ_cost = std::max(std::max(0.0, footprint_cost), double(costmap->getCost(cell_x, cell_y)));\n\n  // return occ_cost;\n\n}\n\n} /* namespace ursa_local_planner */\n", "meta": {"hexsha": "c45f268a5174ff2809366f79927b3fc793ac5342", "size": 6575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ursa_navigation/ursa_local_planner/src/ursa_obstacle_cost_function.cpp", "max_stars_repo_name": "BillYJT/RR1-IP", "max_stars_repo_head_hexsha": "06946f9c79ae7c5e128d83bded3dafd848d49f58", "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/ursa_navigation/ursa_local_planner/src/ursa_obstacle_cost_function.cpp", "max_issues_repo_name": "BillYJT/RR1-IP", "max_issues_repo_head_hexsha": "06946f9c79ae7c5e128d83bded3dafd848d49f58", "max_issues_repo_licenses": ["MIT"], "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/ursa_navigation/ursa_local_planner/src/ursa_obstacle_cost_function.cpp", "max_forks_repo_name": "BillYJT/RR1-IP", "max_forks_repo_head_hexsha": "06946f9c79ae7c5e128d83bded3dafd848d49f58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-07T00:38:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T00:38:19.000Z", "avg_line_length": 35.9289617486, "max_line_length": 160, "alphanum_fraction": 0.6862357414, "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.16315595095854038}}
{"text": "#include <gtest/gtest.h>\n\n#include \"converter/fixml2fix_converter.hxx\"\n#include \"converter/xml_element_helper.hxx\"\n#include \"converter/fix_helper.hxx\"\n#include \"util/fix_env.hxx\"\n#include \"tools/test_util.hxx\"\n\n#include <boost/log/trivial.hpp>\n\n#include <quickfix/fix50sp2/QuoteResponse.h>\n\n#include <list>\n#include <set>\n#include <string>\n#include <utility>\n\nusing namespace std;\nusing namespace fix2xml;\n\nTEST ( QuoteResponse, set_fields)\n{\n\n  fixml2fix_converter converter {\"../spec/fix/FIX50SP2.xml\", \"../spec/xsd/fixml-main-5-0-SP2.xsd\"};\n  auto& fixml_dict = converter.fixml_dico();\n  ASSERT_TRUE(converter.init());\n  ASSERT_TRUE(converter.parse_fixt_dico(\"../spec/fix/FIXT11.xml\"));\n  FIX50SP2::QuoteResponse msg;\n\n  list<multiset<string>> all_values;\n  multiset<string> all_compo_names;\n  multiset<string> QuoteResponse_0;\n  set_field(msg, FIX::Account{\"STRING_1191853753\"}, QuoteResponse_0);\n  set_field(msg, FIX::AccountType{4}, QuoteResponse_0);\n  set_field(msg, FIX::AcctIDSource{4}, QuoteResponse_0);\n  FIX::BidForwardPoints BidForwardPoints_13;\n  BidForwardPoints_13.setString(\"4426009\");\nset_field(msg, BidForwardPoints_13, QuoteResponse_0);\n  FIX::BidForwardPoints2 BidForwardPoints2_13;\n  BidForwardPoints2_13.setString(\"9248974\");\nset_field(msg, BidForwardPoints2_13, QuoteResponse_0);\n  FIX::BidPx BidPx_13;\n  BidPx_13.setString(\"6586670\");\nset_field(msg, BidPx_13, QuoteResponse_0);\n  FIX::BidSize BidSize_13;\n  BidSize_13.setString(\"16236773\");\nset_field(msg, BidSize_13, QuoteResponse_0);\n  FIX::BidSpotRate BidSpotRate_13;\n  BidSpotRate_13.setString(\"18517968\");\nset_field(msg, BidSpotRate_13, QuoteResponse_0);\n  FIX::BidYield BidYield_13;\n  BidYield_13.setString(\"50.160000\");\nset_field(msg, BidYield_13, QuoteResponse_0);\n  set_field(msg, FIX::ClOrdID{\"STRING_1488001758\"}, QuoteResponse_0);\n  set_field(msg, FIX::CommType{'5'}, QuoteResponse_0);\n  FIX::Commission Commission_25;\n  Commission_25.setString(\"11991652\");\nset_field(msg, Commission_25, QuoteResponse_0);\n  set_field(msg, FIX::Currency{\"CHF\"}, QuoteResponse_0);\n  set_field(msg, FIX::CustOrderCapacity{4}, QuoteResponse_0);\n  set_field(msg, FIX::EncodedText{\"DATA_432031813\"}, QuoteResponse_0);\n  set_field(msg, FIX::EncodedTextLen{1834846204}, QuoteResponse_0);\n  set_field(msg, FIX::ExDestination{\"EXCHANGE_703152177\"}, QuoteResponse_0);\n  set_field(msg, FIX::ExDestinationIDSource{'C'}, QuoteResponse_0);\n  set_field(msg, FIX::IOIID{\"STRING_190741324\"}, QuoteResponse_0);\n  FIX::MidPx MidPx_13;\n  MidPx_13.setString(\"15660840\");\nset_field(msg, MidPx_13, QuoteResponse_0);\n  FIX::MidYield MidYield_13;\n  MidYield_13.setString(\"13.200000\");\nset_field(msg, MidYield_13, QuoteResponse_0);\n  FIX::MinBidSize MinBidSize_1;\n  MinBidSize_1.setString(\"19361755\");\nset_field(msg, MinBidSize_1, QuoteResponse_0);\n  FIX::MinOfferSize MinOfferSize_1;\n  MinOfferSize_1.setString(\"417746\");\nset_field(msg, MinOfferSize_1, QuoteResponse_0);\n  FIX::MinQty MinQty_17;\n  MinQty_17.setString(\"8031855\");\nset_field(msg, MinQty_17, QuoteResponse_0);\n  FIX::MktBidPx MktBidPx_1;\n  MktBidPx_1.setString(\"18658783\");\nset_field(msg, MktBidPx_1, QuoteResponse_0);\n  FIX::MktOfferPx MktOfferPx_1;\n  MktOfferPx_1.setString(\"13072265\");\nset_field(msg, MktOfferPx_1, QuoteResponse_0);\n  FIX::OfferForwardPoints OfferForwardPoints_13;\n  OfferForwardPoints_13.setString(\"10744694\");\nset_field(msg, OfferForwardPoints_13, QuoteResponse_0);\n  FIX::OfferForwardPoints2 OfferForwardPoints2_13;\n  OfferForwardPoints2_13.setString(\"18660084\");\nset_field(msg, OfferForwardPoints2_13, QuoteResponse_0);\n  FIX::OfferPx OfferPx_13;\n  OfferPx_13.setString(\"5537417\");\nset_field(msg, OfferPx_13, QuoteResponse_0);\n  FIX::OfferSize OfferSize_13;\n  OfferSize_13.setString(\"16050306\");\nset_field(msg, OfferSize_13, QuoteResponse_0);\n  FIX::OfferSpotRate OfferSpotRate_13;\n  OfferSpotRate_13.setString(\"9103786\");\nset_field(msg, OfferSpotRate_13, QuoteResponse_0);\n  FIX::OfferYield OfferYield_13;\n  OfferYield_13.setString(\"61.050000\");\nset_field(msg, OfferYield_13, QuoteResponse_0);\n  set_field(msg, FIX::OrdType{'M'}, QuoteResponse_0);\n  set_field(msg, FIX::OrderCapacity{'G'}, QuoteResponse_0);\n  FIX::OrderQty2 OrderQty2_22;\n  OrderQty2_22.setString(\"17644435\");\nset_field(msg, OrderQty2_22, QuoteResponse_0);\n  set_field(msg, FIX::OrderRestrictions{\"MULTIPLECHARVALUE_5\"}, QuoteResponse_0);\n  set_field(msg, FIX::PreTradeAnonymity{true}, QuoteResponse_0);\n  FIX::Price Price_23;\n  Price_23.setString(\"14687567\");\nset_field(msg, Price_23, QuoteResponse_0);\n  set_field(msg, FIX::PriceType{13}, QuoteResponse_0);\n  set_field(msg, FIX::QuoteID{\"STRING_169691342\"}, QuoteResponse_0);\n  set_field(msg, FIX::QuoteMsgID{\"STRING_1952478130\"}, QuoteResponse_0);\n  set_field(msg, FIX::QuoteRespID{\"STRING_280584846\"}, QuoteResponse_0);\n  set_field(msg, FIX::QuoteRespType{4}, QuoteResponse_0);\n  set_field(msg, FIX::QuoteType{3}, QuoteResponse_0);\n  FIX::SettlCurrBidFxRate SettlCurrBidFxRate_1;\n  SettlCurrBidFxRate_1.setString(\"13031809\");\nset_field(msg, SettlCurrBidFxRate_1, QuoteResponse_0);\n  set_field(msg, FIX::SettlCurrFxRateCalc{'M'}, QuoteResponse_0);\n  FIX::SettlCurrOfferFxRate SettlCurrOfferFxRate_1;\n  SettlCurrOfferFxRate_1.setString(\"9760908\");\nset_field(msg, SettlCurrOfferFxRate_1, QuoteResponse_0);\n  set_field(msg, FIX::SettlDate{\"LOCALMKTDATE_2006333130\"}, QuoteResponse_0);\n  set_field(msg, FIX::SettlDate2{\"LOCALMKTDATE_859741660\"}, QuoteResponse_0);\n  set_field(msg, FIX::SettlType{\"STRING_0\"}, QuoteResponse_0);\n  set_field(msg, FIX::Side{'9'}, QuoteResponse_0);\n  set_field(msg, FIX::Text{\"STRING_1321422981\"}, QuoteResponse_0);\n  set_field(msg, FIX::TradingSessionID{\"STRING_5\"}, QuoteResponse_0);\n  set_field(msg, FIX::TradingSessionSubID{\"STRING_6\"}, QuoteResponse_0);\n  set_field(msg, FIX::TransactTime{FIX::UTCTIMESTAMP(13, 56, 26, 20, 12, 2000)}, QuoteResponse_0);\n  set_field(msg, FIX::ValidUntilTime{FIX::UTCTIMESTAMP(4, 55, 28, 24, 9, 2002)}, QuoteResponse_0);\n  all_values.push_back(QuoteResponse_0);\n\n  all_compo_names.insert(\"QuoteResponse\");\n\n  // FinancingDetails\n  multiset<string> FinancingDetails_22;\n  set_field(msg, FIX::AgreementCurrency{\"GBP\"}, FinancingDetails_22);\n  set_field(msg, FIX::AgreementDate{\"LOCALMKTDATE_1507182802\"}, FinancingDetails_22);\n  set_field(msg, FIX::AgreementDesc{\"STRING_762966521\"}, FinancingDetails_22);\n  set_field(msg, FIX::AgreementID{\"STRING_1889098976\"}, FinancingDetails_22);\n  set_field(msg, FIX::DeliveryType{1}, FinancingDetails_22);\n  set_field(msg, FIX::EndDate{\"LOCALMKTDATE_2051694856\"}, FinancingDetails_22);\n  FIX::MarginRatio MarginRatio_22;\n  MarginRatio_22.setString(\"62.820000\");\nset_field(msg, MarginRatio_22, FinancingDetails_22);\n  set_field(msg, FIX::StartDate{\"LOCALMKTDATE_1852694445\"}, FinancingDetails_22);\n  set_field(msg, FIX::TerminationType{1}, FinancingDetails_22);\n  all_values.push_back(FinancingDetails_22);\n  all_compo_names.insert(\".\");\n\n  // Instrument\n  multiset<string> Instrument_72;\n  FIX::AttachmentPoint AttachmentPoint_72;\n  AttachmentPoint_72.setString(\"57.640000\");\nset_field(msg, AttachmentPoint_72, Instrument_72);\n  set_field(msg, FIX::CFICode{\"STRING_564952458\"}, Instrument_72);\n  set_field(msg, FIX::CPProgram{2}, Instrument_72);\n  set_field(msg, FIX::CPRegType{\"STRING_181095692\"}, Instrument_72);\n  FIX::CapPrice CapPrice_72;\n  CapPrice_72.setString(\"18863754\");\nset_field(msg, CapPrice_72, Instrument_72);\n  FIX::ContractMultiplier ContractMultiplier_72;\n  ContractMultiplier_72.setString(\"8551748\");\nset_field(msg, ContractMultiplier_72, Instrument_72);\n  set_field(msg, FIX::ContractMultiplierUnit{1}, Instrument_72);\n  set_field(msg, FIX::ContractSettlMonth{\"MONTHYEAR_1863500295\"}, Instrument_72);\n  set_field(msg, FIX::CountryOfIssue{\"COUNTRY_1529093701\"}, Instrument_72);\n  set_field(msg, FIX::CouponPaymentDate{\"LOCALMKTDATE_126771388\"}, Instrument_72);\n  FIX::CouponRate CouponRate_72;\n  CouponRate_72.setString(\"9.930000\");\nset_field(msg, CouponRate_72, Instrument_72);\n  set_field(msg, FIX::CreditRating{\"STRING_1921537437\"}, Instrument_72);\n  set_field(msg, FIX::DatedDate{\"LOCALMKTDATE_1306964247\"}, Instrument_72);\n  FIX::DetachmentPoint DetachmentPoint_72;\n  DetachmentPoint_72.setString(\"23.870000\");\nset_field(msg, DetachmentPoint_72, Instrument_72);\n  set_field(msg, FIX::EncodedIssuer{\"DATA_1076876130\"}, Instrument_72);\n  set_field(msg, FIX::EncodedIssuerLen{1179219564}, Instrument_72);\n  set_field(msg, FIX::EncodedSecurityDesc{\"DATA_1391795002\"}, Instrument_72);\n  set_field(msg, FIX::EncodedSecurityDescLen{1585194359}, Instrument_72);\n  set_field(msg, FIX::ExerciseStyle{2}, Instrument_72);\n  FIX::Factor Factor_72;\n  Factor_72.setString(\"17714058\");\nset_field(msg, Factor_72, Instrument_72);\n  set_field(msg, FIX::FlexProductEligibilityIndicator{false}, Instrument_72);\n  set_field(msg, FIX::FlexibleIndicator{false}, Instrument_72);\n  FIX::FloorPrice FloorPrice_72;\n  FloorPrice_72.setString(\"12324363\");\nset_field(msg, FloorPrice_72, Instrument_72);\n  set_field(msg, FIX::FlowScheduleType{1}, Instrument_72);\n  set_field(msg, FIX::InstrRegistry{\"STRING_241889720\"}, Instrument_72);\n  set_field(msg, FIX::InstrmtAssignmentMethod{'9'}, Instrument_72);\n  set_field(msg, FIX::InterestAccrualDate{\"LOCALMKTDATE_525082219\"}, Instrument_72);\n  set_field(msg, FIX::IssueDate{\"LOCALMKTDATE_146100928\"}, Instrument_72);\n  set_field(msg, FIX::Issuer{\"STRING_2018847959\"}, Instrument_72);\n  set_field(msg, FIX::ListMethod{1}, Instrument_72);\n  set_field(msg, FIX::LocaleOfIssue{\"STRING_1026403028\"}, Instrument_72);\n  set_field(msg, FIX::MaturityDate{\"LOCALMKTDATE_775010076\"}, Instrument_72);\n  set_field(msg, FIX::MaturityMonthYear{\"MONTHYEAR_795245475\"}, Instrument_72);\n  set_field(msg, FIX::MaturityTime{\"TZTIMEONLY_926053696\"}, Instrument_72);\n  FIX::MinPriceIncrement MinPriceIncrement_72;\n  MinPriceIncrement_72.setString(\"9561057\");\nset_field(msg, MinPriceIncrement_72, Instrument_72);\n  FIX::MinPriceIncrementAmount MinPriceIncrementAmount_72;\n  MinPriceIncrementAmount_72.setString(\"5341372\");\nset_field(msg, MinPriceIncrementAmount_72, Instrument_72);\n  set_field(msg, FIX::NTPositionLimit{1781228512}, Instrument_72);\n  FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_72;\n  NotionalPercentageOutstanding_72.setString(\"60.400000\");\nset_field(msg, NotionalPercentageOutstanding_72, Instrument_72);\n  set_field(msg, FIX::OptAttribute{'2'}, Instrument_72);\n  FIX::OptPayoutAmount OptPayoutAmount_72;\n  OptPayoutAmount_72.setString(\"11628385\");\nset_field(msg, OptPayoutAmount_72, Instrument_72);\n  set_field(msg, FIX::OptPayoutType{3}, Instrument_72);\n  FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_72;\n  OriginalNotionalPercentageOutstanding_72.setString(\"49.060000\");\nset_field(msg, OriginalNotionalPercentageOutstanding_72, Instrument_72);\n  set_field(msg, FIX::Pool{\"STRING_936892355\"}, Instrument_72);\n  set_field(msg, FIX::PositionLimit{1890161676}, Instrument_72);\n  set_field(msg, FIX::PriceQuoteMethod{\"STRING_INT\"}, Instrument_72);\n  set_field(msg, FIX::PriceUnitOfMeasure{\"STRING_2013768485\"}, Instrument_72);\n  FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_72;\n  PriceUnitOfMeasureQty_72.setString(\"9218975\");\nset_field(msg, PriceUnitOfMeasureQty_72, Instrument_72);\n  set_field(msg, FIX::Product{7}, Instrument_72);\n  set_field(msg, FIX::ProductComplex{\"STRING_1451479196\"}, Instrument_72);\n  set_field(msg, FIX::PutOrCall{0}, Instrument_72);\n  set_field(msg, FIX::RedemptionDate{\"LOCALMKTDATE_1162750867\"}, Instrument_72);\n  set_field(msg, FIX::RepoCollateralSecurityType{\"STRING_79197720\"}, Instrument_72);\n  FIX::RepurchaseRate RepurchaseRate_72;\n  RepurchaseRate_72.setString(\"55.990000\");\nset_field(msg, RepurchaseRate_72, Instrument_72);\n  set_field(msg, FIX::RepurchaseTerm{247703568}, Instrument_72);\n  set_field(msg, FIX::RestructuringType{\"STRING_MM\"}, Instrument_72);\n  set_field(msg, FIX::SecurityDesc{\"STRING_1311145319\"}, Instrument_72);\n  set_field(msg, FIX::SecurityExchange{\"EXCHANGE_1221755246\"}, Instrument_72);\n  set_field(msg, FIX::SecurityGroup{\"STRING_739181265\"}, Instrument_72);\n  set_field(msg, FIX::SecurityID{\"STRING_1457246248\"}, Instrument_72);\n  set_field(msg, FIX::SecurityIDSource{\"STRING_E\"}, Instrument_72);\n  set_field(msg, FIX::SecurityStatus{\"STRING_1\"}, Instrument_72);\n  set_field(msg, FIX::SecuritySubType{\"STRING_336165628\"}, Instrument_72);\n  set_field(msg, FIX::SecurityType{\"STRING_CORP\"}, Instrument_72);\n  set_field(msg, FIX::Seniority{\"STRING_SD\"}, Instrument_72);\n  set_field(msg, FIX::SettlMethod{'P'}, Instrument_72);\n  set_field(msg, FIX::SettleOnOpenFlag{\"STRING_676751754\"}, Instrument_72);\n  set_field(msg, FIX::StateOrProvinceOfIssue{\"STRING_151373375\"}, Instrument_72);\n  set_field(msg, FIX::StrikeCurrency{\"JPY\"}, Instrument_72);\n  FIX::StrikeMultiplier StrikeMultiplier_72;\n  StrikeMultiplier_72.setString(\"4015272\");\nset_field(msg, StrikeMultiplier_72, Instrument_72);\n  FIX::StrikePrice StrikePrice_72;\n  StrikePrice_72.setString(\"20588027\");\nset_field(msg, StrikePrice_72, Instrument_72);\n  set_field(msg, FIX::StrikePriceBoundaryMethod{4}, Instrument_72);\n  FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_72;\n  StrikePriceBoundaryPrecision_72.setString(\"21.950000\");\nset_field(msg, StrikePriceBoundaryPrecision_72, Instrument_72);\n  set_field(msg, FIX::StrikePriceDeterminationMethod{3}, Instrument_72);\n  FIX::StrikeValue StrikeValue_72;\n  StrikeValue_72.setString(\"14590532\");\nset_field(msg, StrikeValue_72, Instrument_72);\n  set_field(msg, FIX::Symbol{\"STRING_1566325841\"}, Instrument_72);\n  set_field(msg, FIX::SymbolSfx{\"STRING_WI\"}, Instrument_72);\n  set_field(msg, FIX::TimeUnit{\"STRING_D\"}, Instrument_72);\n  set_field(msg, FIX::UnderlyingPriceDeterminationMethod{2}, Instrument_72);\n  set_field(msg, FIX::UnitOfMeasure{\"STRING_USD\"}, Instrument_72);\n  FIX::UnitOfMeasureQty UnitOfMeasureQty_72;\n  UnitOfMeasureQty_72.setString(\"18237995\");\nset_field(msg, UnitOfMeasureQty_72, Instrument_72);\n  set_field(msg, FIX::ValuationMethod{\"STRING_CDSD\"}, Instrument_72);\n  all_values.push_back(Instrument_72);\n  all_compo_names.insert(\".\");\n\n  // ComplexEvents\n  // Group ComplexEvents.NoComplexEvents\n  {\n    FIX50SP2::QuoteResponse::NoComplexEvents noComplexEvents_0_0;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_147;\n    set_field(noComplexEvents_0_0, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_147);\n    FIX::ComplexEventPrice ComplexEventPrice_147;\n    ComplexEventPrice_147.setString(\"2206416\");\nset_field(noComplexEvents_0_0, ComplexEventPrice_147, ComplexEvents_NoComplexEvents_147);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceBoundaryMethod{5}, ComplexEvents_NoComplexEvents_147);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_147;\n    ComplexEventPriceBoundaryPrecision_147.setString(\"68.660000\");\nset_field(noComplexEvents_0_0, ComplexEventPriceBoundaryPrecision_147, ComplexEvents_NoComplexEvents_147);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceTimeType{2}, ComplexEvents_NoComplexEvents_147);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventType{1}, ComplexEvents_NoComplexEvents_147);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_147;\n    ComplexOptPayoutAmount_147.setString(\"13664794\");\nset_field(noComplexEvents_0_0, ComplexOptPayoutAmount_147, ComplexEvents_NoComplexEvents_147);\n    all_values.push_back(ComplexEvents_NoComplexEvents_147);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_293;\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(15, 50, 11, 12, 9, 2005)}, ComplexEventDates_NoComplexEventDates_293);\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(7, 7, 28, 6, 3, 2014)}, ComplexEventDates_NoComplexEventDates_293);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_293);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_599;\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(6, 52, 17)}, ComplexEventTimes_NoComplexEventTimes_599);\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(15, 58, 38)}, ComplexEventTimes_NoComplexEventTimes_599);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_599);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_0);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_294;\n      set_field(noComplexEventDates_0_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(15, 32, 25, 23, 4, 2009)}, ComplexEventDates_NoComplexEventDates_294);\n      set_field(noComplexEventDates_0_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(5, 10, 10, 5, 3, 2005)}, ComplexEventDates_NoComplexEventDates_294);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_294);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_600;\n        set_field(noComplexEventTimes_0_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(10, 15, 44)}, ComplexEventTimes_NoComplexEventTimes_600);\n        set_field(noComplexEventTimes_0_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(22, 39, 41)}, ComplexEventTimes_NoComplexEventTimes_600);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_600);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_601;\n        set_field(noComplexEventTimes_0_1_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(9, 33, 54)}, ComplexEventTimes_NoComplexEventTimes_601);\n        set_field(noComplexEventTimes_0_1_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(12, 44, 1)}, ComplexEventTimes_NoComplexEventTimes_601);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_601);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_1);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_602;\n        set_field(noComplexEventTimes_0_1_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(16, 25, 28)}, ComplexEventTimes_NoComplexEventTimes_602);\n        set_field(noComplexEventTimes_0_1_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(4, 31, 31)}, ComplexEventTimes_NoComplexEventTimes_602);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_602);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_2);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_1);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_2;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_295;\n      set_field(noComplexEventDates_0_1_2, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(18, 33, 7, 16, 9, 2013)}, ComplexEventDates_NoComplexEventDates_295);\n      set_field(noComplexEventDates_0_1_2, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(10, 22, 29, 26, 1, 2008)}, ComplexEventDates_NoComplexEventDates_295);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_295);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_2_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_603;\n        set_field(noComplexEventTimes_0_2_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(21, 8, 56)}, ComplexEventTimes_NoComplexEventTimes_603);\n        set_field(noComplexEventTimes_0_2_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(13, 33, 45)}, ComplexEventTimes_NoComplexEventTimes_603);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_603);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_2.addGroup(noComplexEventTimes_0_2_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_2_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_604;\n        set_field(noComplexEventTimes_0_2_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(13, 2, 44)}, ComplexEventTimes_NoComplexEventTimes_604);\n        set_field(noComplexEventTimes_0_2_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(6, 7, 11)}, ComplexEventTimes_NoComplexEventTimes_604);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_604);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_2.addGroup(noComplexEventTimes_0_2_2_1);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_2_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_605;\n        set_field(noComplexEventTimes_0_2_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(13, 36, 15)}, ComplexEventTimes_NoComplexEventTimes_605);\n        set_field(noComplexEventTimes_0_2_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(13, 14, 10)}, ComplexEventTimes_NoComplexEventTimes_605);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_605);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_2.addGroup(noComplexEventTimes_0_2_2_2);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_2);\n    }\n    msg.addGroup(noComplexEvents_0_0);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoComplexEvents noComplexEvents_0_1;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_148;\n    set_field(noComplexEvents_0_1, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_148);\n    FIX::ComplexEventPrice ComplexEventPrice_148;\n    ComplexEventPrice_148.setString(\"2002556\");\nset_field(noComplexEvents_0_1, ComplexEventPrice_148, ComplexEvents_NoComplexEvents_148);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceBoundaryMethod{5}, ComplexEvents_NoComplexEvents_148);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_148;\n    ComplexEventPriceBoundaryPrecision_148.setString(\"61.140000\");\nset_field(noComplexEvents_0_1, ComplexEventPriceBoundaryPrecision_148, ComplexEvents_NoComplexEvents_148);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceTimeType{3}, ComplexEvents_NoComplexEvents_148);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventType{4}, ComplexEvents_NoComplexEvents_148);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_148;\n    ComplexOptPayoutAmount_148.setString(\"9634916\");\nset_field(noComplexEvents_0_1, ComplexOptPayoutAmount_148, ComplexEvents_NoComplexEvents_148);\n    all_values.push_back(ComplexEvents_NoComplexEvents_148);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_296;\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(6, 44, 44, 23, 6, 2003)}, ComplexEventDates_NoComplexEventDates_296);\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(10, 23, 35, 6, 11, 2000)}, ComplexEventDates_NoComplexEventDates_296);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_296);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_606;\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(0, 57, 2)}, ComplexEventTimes_NoComplexEventTimes_606);\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(10, 16, 52)}, ComplexEventTimes_NoComplexEventTimes_606);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_606);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_607;\n        set_field(noComplexEventTimes_1_0_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(21, 24, 32)}, ComplexEventTimes_NoComplexEventTimes_607);\n        set_field(noComplexEventTimes_1_0_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(15, 1, 26)}, ComplexEventTimes_NoComplexEventTimes_607);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_607);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_1);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_608;\n        set_field(noComplexEventTimes_1_0_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(23, 2, 48)}, ComplexEventTimes_NoComplexEventTimes_608);\n        set_field(noComplexEventTimes_1_0_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(11, 2, 49)}, ComplexEventTimes_NoComplexEventTimes_608);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_608);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_2);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_297;\n      set_field(noComplexEventDates_1_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(1, 24, 15, 15, 12, 2000)}, ComplexEventDates_NoComplexEventDates_297);\n      set_field(noComplexEventDates_1_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(3, 34, 52, 5, 9, 2008)}, ComplexEventDates_NoComplexEventDates_297);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_297);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::QuoteResponse::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_609;\n        set_field(noComplexEventTimes_1_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(10, 57, 22)}, ComplexEventTimes_NoComplexEventTimes_609);\n        set_field(noComplexEventTimes_1_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(17, 16, 35)}, ComplexEventTimes_NoComplexEventTimes_609);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_609);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_0);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_1);\n    }\n    msg.addGroup(noComplexEvents_0_1);\n  }\n  // EvntGrp\n  // Group EvntGrp.NoEvents\n  {\n    FIX50SP2::QuoteResponse::NoEvents noEvents_0_0;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_145;\n    set_field(noEvents_0_0, FIX::EventDate{\"LOCALMKTDATE_812001759\"}, EvntGrp_NoEvents_145);\n    FIX::EventPx EventPx_145;\n    EventPx_145.setString(\"8389006\");\nset_field(noEvents_0_0, EventPx_145, EvntGrp_NoEvents_145);\n    set_field(noEvents_0_0, FIX::EventText{\"STRING_1370433937\"}, EvntGrp_NoEvents_145);\n    set_field(noEvents_0_0, FIX::EventTime{FIX::UTCTIMESTAMP(5, 39, 27, 23, 10, 2002)}, EvntGrp_NoEvents_145);\n    set_field(noEvents_0_0, FIX::EventType{19}, EvntGrp_NoEvents_145);\n    all_values.push_back(EvntGrp_NoEvents_145);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_0);\n  }\n  // InstrumentParties\n  // Group InstrumentParties.NoInstrumentParties\n  {\n    FIX50SP2::QuoteResponse::NoInstrumentParties noInstrumentParties_0_0;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_134;\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyID{\"STRING_1861073983\"}, InstrumentParties_NoInstrumentParties_134);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_134);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyRole{166002170}, InstrumentParties_NoInstrumentParties_134);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_134);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::QuoteResponse::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_276;\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubID{\"STRING_1665327889\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_276);\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubIDType{619722882}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_276);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_276);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_277;\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubID{\"STRING_1425311679\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_277);\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubIDType{1093548961}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_277);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_277);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_1);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_2;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_278;\n      set_field(noInstrumentPartySubIDs_0_1_2, FIX::InstrumentPartySubID{\"STRING_499756543\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_278);\n      set_field(noInstrumentPartySubIDs_0_1_2, FIX::InstrumentPartySubIDType{1781955912}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_278);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_278);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_2);\n    }\n    msg.addGroup(noInstrumentParties_0_0);\n  }\n  // SecAltIDGrp\n  // Group SecAltIDGrp.NoSecurityAltID\n  {\n    FIX50SP2::QuoteResponse::NoSecurityAltID noSecurityAltID_0_0;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_146;\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltID{\"STRING_6358761\"}, SecAltIDGrp_NoSecurityAltID_146);\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltIDSource{\"STRING_985515722\"}, SecAltIDGrp_NoSecurityAltID_146);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_146);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_0);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoSecurityAltID noSecurityAltID_0_1;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_147;\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltID{\"STRING_1428211034\"}, SecAltIDGrp_NoSecurityAltID_147);\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltIDSource{\"STRING_117592710\"}, SecAltIDGrp_NoSecurityAltID_147);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_147);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_1);\n  }\n  // SecurityXML\n  multiset<string> SecurityXML_144;\n  set_field(msg, FIX::SecurityXML{\"XMLDATA_1210329715\"}, SecurityXML_144);\n  set_field(msg, FIX::SecurityXMLLen{2045416170}, SecurityXML_144);\n  set_field(msg, FIX::SecurityXMLSchema{\"STRING_57151857\"}, SecurityXML_144);\n  all_values.push_back(SecurityXML_144);\n  all_compo_names.insert(\"..\");\n\n  // LegQuotGrp\n  // Group LegQuotGrp.NoLegs\n  {\n    FIX50SP2::QuoteResponse::NoLegs noLegs_0_0;\n    // LegQuotGrp.NoLegs\n    multiset<string> LegQuotGrp_NoLegs_2;\n    FIX::LegBidForwardPoints LegBidForwardPoints_2;\n    LegBidForwardPoints_2.setString(\"7099342\");\nset_field(noLegs_0_0, LegBidForwardPoints_2, LegQuotGrp_NoLegs_2);\n    FIX::LegBidPx LegBidPx_2;\n    LegBidPx_2.setString(\"8960525\");\nset_field(noLegs_0_0, LegBidPx_2, LegQuotGrp_NoLegs_2);\n    FIX::LegOfferForwardPoints LegOfferForwardPoints_2;\n    LegOfferForwardPoints_2.setString(\"19301073\");\nset_field(noLegs_0_0, LegOfferForwardPoints_2, LegQuotGrp_NoLegs_2);\n    FIX::LegOfferPx LegOfferPx_2;\n    LegOfferPx_2.setString(\"12985000\");\nset_field(noLegs_0_0, LegOfferPx_2, LegQuotGrp_NoLegs_2);\n    FIX::LegOrderQty LegOrderQty_16;\n    LegOrderQty_16.setString(\"2287486\");\nset_field(noLegs_0_0, LegOrderQty_16, LegQuotGrp_NoLegs_2);\n    set_field(noLegs_0_0, FIX::LegPriceType{1557058553}, LegQuotGrp_NoLegs_2);\n    FIX::LegQty LegQty_16;\n    LegQty_16.setString(\"19582142\");\nset_field(noLegs_0_0, LegQty_16, LegQuotGrp_NoLegs_2);\n    set_field(noLegs_0_0, FIX::LegRefID{\"STRING_1766631092\"}, LegQuotGrp_NoLegs_2);\n    set_field(noLegs_0_0, FIX::LegSettlDate{\"LOCALMKTDATE_503096562\"}, LegQuotGrp_NoLegs_2);\n    set_field(noLegs_0_0, FIX::LegSettlType{'3'}, LegQuotGrp_NoLegs_2);\n    set_field(noLegs_0_0, FIX::LegSwapType{4}, LegQuotGrp_NoLegs_2);\n    all_values.push_back(LegQuotGrp_NoLegs_2);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_104;\n    set_field(noLegs_0_0, FIX::EncodedLegIssuer{\"DATA_1485168222\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::EncodedLegIssuerLen{1899352826}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDesc{\"DATA_1722427697\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDescLen{1651170393}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegCFICode{\"STRING_648467828\"}, InstrumentLeg_104);\n    FIX::LegContractMultiplier LegContractMultiplier_104;\n    LegContractMultiplier_104.setString(\"12402719\");\nset_field(noLegs_0_0, LegContractMultiplier_104, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegContractMultiplierUnit{123409627}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegContractSettlMonth{\"MONTHYEAR_2073779507\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegCountryOfIssue{\"COUNTRY_186337252\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_623166170\"}, InstrumentLeg_104);\n    FIX::LegCouponRate LegCouponRate_104;\n    LegCouponRate_104.setString(\"17.720000\");\nset_field(noLegs_0_0, LegCouponRate_104, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegCreditRating{\"STRING_902595224\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegCurrency{\"JPY\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegDatedDate{\"LOCALMKTDATE_183322610\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegExerciseStyle{747117641}, InstrumentLeg_104);\n    FIX::LegFactor LegFactor_104;\n    LegFactor_104.setString(\"17566135\");\nset_field(noLegs_0_0, LegFactor_104, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegFlowScheduleType{81255133}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegInstrRegistry{\"STRING_804269499\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_168803297\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegIssueDate{\"LOCALMKTDATE_791189415\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegIssuer{\"STRING_1700322006\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegLocaleOfIssue{\"STRING_2098910618\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegMaturityDate{\"LOCALMKTDATE_2089689475\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegMaturityMonthYear{\"MONTHYEAR_1929070687\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegMaturityTime{\"TZTIMEONLY_1508485523\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegOptAttribute{'1'}, InstrumentLeg_104);\n    FIX::LegOptionRatio LegOptionRatio_104;\n    LegOptionRatio_104.setString(\"15482181\");\nset_field(noLegs_0_0, LegOptionRatio_104, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegPool{\"STRING_2011582085\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegPriceUnitOfMeasure{\"STRING_1938698918\"}, InstrumentLeg_104);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_104;\n    LegPriceUnitOfMeasureQty_104.setString(\"20373359\");\nset_field(noLegs_0_0, LegPriceUnitOfMeasureQty_104, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegProduct{1349266660}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegPutOrCall{1690568096}, InstrumentLeg_104);\n    FIX::LegRatioQty LegRatioQty_104;\n    LegRatioQty_104.setString(\"16122799\");\nset_field(noLegs_0_0, LegRatioQty_104, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegRedemptionDate{\"LOCALMKTDATE_852953405\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegRepoCollateralSecurityType{\"STRING_191552277\"}, InstrumentLeg_104);\n    FIX::LegRepurchaseRate LegRepurchaseRate_104;\n    LegRepurchaseRate_104.setString(\"82.540000\");\nset_field(noLegs_0_0, LegRepurchaseRate_104, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegRepurchaseTerm{976363032}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSecurityDesc{\"STRING_117848136\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSecurityExchange{\"EXCHANGE_891405506\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSecurityID{\"STRING_1599529203\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSecurityIDSource{\"STRING_1826099908\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSecuritySubType{\"STRING_1794000730\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSecurityType{\"STRING_81570486\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSide{'2'}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegStateOrProvinceOfIssue{\"STRING_1977323340\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegStrikeCurrency{\"CAN\"}, InstrumentLeg_104);\n    FIX::LegStrikePrice LegStrikePrice_104;\n    LegStrikePrice_104.setString(\"20585784\");\nset_field(noLegs_0_0, LegStrikePrice_104, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSymbol{\"STRING_1632957627\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegSymbolSfx{\"STRING_2833316\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegTimeUnit{\"STRING_702284240\"}, InstrumentLeg_104);\n    set_field(noLegs_0_0, FIX::LegUnitOfMeasure{\"STRING_1185795985\"}, InstrumentLeg_104);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_104;\n    LegUnitOfMeasureQty_104.setString(\"21017439\");\nset_field(noLegs_0_0, LegUnitOfMeasureQty_104, InstrumentLeg_104);\n    all_values.push_back(InstrumentLeg_104);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_205;\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltID{\"STRING_967383025\"}, LegSecAltIDGrp_NoLegSecurityAltID_205);\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltIDSource{\"STRING_1462745810\"}, LegSecAltIDGrp_NoLegSecurityAltID_205);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_205);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_206;\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltID{\"STRING_397426494\"}, LegSecAltIDGrp_NoLegSecurityAltID_206);\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltIDSource{\"STRING_368117508\"}, LegSecAltIDGrp_NoLegSecurityAltID_206);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_206);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_1);\n    }\n    // LegBenchmarkCurveData\n    multiset<string> LegBenchmarkCurveData_10;\n    set_field(noLegs_0_0, FIX::LegBenchmarkCurveCurrency{\"USD\"}, LegBenchmarkCurveData_10);\n    set_field(noLegs_0_0, FIX::LegBenchmarkCurveName{\"STRING_257969774\"}, LegBenchmarkCurveData_10);\n    set_field(noLegs_0_0, FIX::LegBenchmarkCurvePoint{\"STRING_528627260\"}, LegBenchmarkCurveData_10);\n    FIX::LegBenchmarkPrice LegBenchmarkPrice_10;\n    LegBenchmarkPrice_10.setString(\"18792098\");\nset_field(noLegs_0_0, LegBenchmarkPrice_10, LegBenchmarkCurveData_10);\n    set_field(noLegs_0_0, FIX::LegBenchmarkPriceType{1870249738}, LegBenchmarkCurveData_10);\n    all_values.push_back(LegBenchmarkCurveData_10);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegStipulations noLegStipulations_0_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_36;\n      set_field(noLegStipulations_0_1_0, FIX::LegStipulationType{\"STRING_2070762137\"}, LegStipulations_NoLegStipulations_36);\n      set_field(noLegStipulations_0_1_0, FIX::LegStipulationValue{\"STRING_427834344\"}, LegStipulations_NoLegStipulations_36);\n      all_values.push_back(LegStipulations_NoLegStipulations_36);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegStipulations noLegStipulations_0_1_1;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_37;\n      set_field(noLegStipulations_0_1_1, FIX::LegStipulationType{\"STRING_210460049\"}, LegStipulations_NoLegStipulations_37);\n      set_field(noLegStipulations_0_1_1, FIX::LegStipulationValue{\"STRING_41126626\"}, LegStipulations_NoLegStipulations_37);\n      all_values.push_back(LegStipulations_NoLegStipulations_37);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_1);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_131;\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyID{\"STRING_1809989252\"}, NestedParties_NoNestedPartyIDs_131);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_131);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyRole{965756932}, NestedParties_NoNestedPartyIDs_131);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_131);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_273;\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubID{\"STRING_2092126641\"}, NstdPtysSubGrp_NoNestedPartySubIDs_273);\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubIDType{795596624}, NstdPtysSubGrp_NoNestedPartySubIDs_273);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_273);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_0);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_1;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_132;\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyID{\"STRING_572764219\"}, NestedParties_NoNestedPartyIDs_132);\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_132);\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyRole{706691450}, NestedParties_NoNestedPartyIDs_132);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_132);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_274;\n        set_field(noNestedPartySubIDs_0_1_2_0, FIX::NestedPartySubID{\"STRING_1928989977\"}, NstdPtysSubGrp_NoNestedPartySubIDs_274);\n        set_field(noNestedPartySubIDs_0_1_2_0, FIX::NestedPartySubIDType{1408975690}, NstdPtysSubGrp_NoNestedPartySubIDs_274);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_274);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_275;\n        set_field(noNestedPartySubIDs_0_1_2_1, FIX::NestedPartySubID{\"STRING_1244034183\"}, NstdPtysSubGrp_NoNestedPartySubIDs_275);\n        set_field(noNestedPartySubIDs_0_1_2_1, FIX::NestedPartySubIDType{1883250264}, NstdPtysSubGrp_NoNestedPartySubIDs_275);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_275);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_1);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_276;\n        set_field(noNestedPartySubIDs_0_1_2_2, FIX::NestedPartySubID{\"STRING_2053465758\"}, NstdPtysSubGrp_NoNestedPartySubIDs_276);\n        set_field(noNestedPartySubIDs_0_1_2_2, FIX::NestedPartySubIDType{63933560}, NstdPtysSubGrp_NoNestedPartySubIDs_276);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_276);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_2);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_1);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_2;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_133;\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyID{\"STRING_1198512426\"}, NestedParties_NoNestedPartyIDs_133);\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyIDSource{'3'}, NestedParties_NoNestedPartyIDs_133);\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyRole{432051069}, NestedParties_NoNestedPartyIDs_133);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_133);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_2_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_277;\n        set_field(noNestedPartySubIDs_0_2_2_0, FIX::NestedPartySubID{\"STRING_492050368\"}, NstdPtysSubGrp_NoNestedPartySubIDs_277);\n        set_field(noNestedPartySubIDs_0_2_2_0, FIX::NestedPartySubIDType{690020843}, NstdPtysSubGrp_NoNestedPartySubIDs_277);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_277);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_2.addGroup(noNestedPartySubIDs_0_2_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_2_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_278;\n        set_field(noNestedPartySubIDs_0_2_2_1, FIX::NestedPartySubID{\"STRING_906500286\"}, NstdPtysSubGrp_NoNestedPartySubIDs_278);\n        set_field(noNestedPartySubIDs_0_2_2_1, FIX::NestedPartySubIDType{223776580}, NstdPtysSubGrp_NoNestedPartySubIDs_278);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_278);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_2.addGroup(noNestedPartySubIDs_0_2_2_1);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_2);\n    }\n    msg.addGroup(noLegs_0_0);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoLegs noLegs_0_1;\n    // LegQuotGrp.NoLegs\n    multiset<string> LegQuotGrp_NoLegs_3;\n    FIX::LegBidForwardPoints LegBidForwardPoints_3;\n    LegBidForwardPoints_3.setString(\"4127869\");\nset_field(noLegs_0_1, LegBidForwardPoints_3, LegQuotGrp_NoLegs_3);\n    FIX::LegBidPx LegBidPx_3;\n    LegBidPx_3.setString(\"1405973\");\nset_field(noLegs_0_1, LegBidPx_3, LegQuotGrp_NoLegs_3);\n    FIX::LegOfferForwardPoints LegOfferForwardPoints_3;\n    LegOfferForwardPoints_3.setString(\"1470550\");\nset_field(noLegs_0_1, LegOfferForwardPoints_3, LegQuotGrp_NoLegs_3);\n    FIX::LegOfferPx LegOfferPx_3;\n    LegOfferPx_3.setString(\"8406212\");\nset_field(noLegs_0_1, LegOfferPx_3, LegQuotGrp_NoLegs_3);\n    FIX::LegOrderQty LegOrderQty_17;\n    LegOrderQty_17.setString(\"3510573\");\nset_field(noLegs_0_1, LegOrderQty_17, LegQuotGrp_NoLegs_3);\n    set_field(noLegs_0_1, FIX::LegPriceType{188181696}, LegQuotGrp_NoLegs_3);\n    FIX::LegQty LegQty_17;\n    LegQty_17.setString(\"123774\");\nset_field(noLegs_0_1, LegQty_17, LegQuotGrp_NoLegs_3);\n    set_field(noLegs_0_1, FIX::LegRefID{\"STRING_13562957\"}, LegQuotGrp_NoLegs_3);\n    set_field(noLegs_0_1, FIX::LegSettlDate{\"LOCALMKTDATE_2055408230\"}, LegQuotGrp_NoLegs_3);\n    set_field(noLegs_0_1, FIX::LegSettlType{'9'}, LegQuotGrp_NoLegs_3);\n    set_field(noLegs_0_1, FIX::LegSwapType{1}, LegQuotGrp_NoLegs_3);\n    all_values.push_back(LegQuotGrp_NoLegs_3);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_105;\n    set_field(noLegs_0_1, FIX::EncodedLegIssuer{\"DATA_2000051223\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::EncodedLegIssuerLen{1773731036}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::EncodedLegSecurityDesc{\"DATA_330403267\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::EncodedLegSecurityDescLen{1778724236}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegCFICode{\"STRING_332938838\"}, InstrumentLeg_105);\n    FIX::LegContractMultiplier LegContractMultiplier_105;\n    LegContractMultiplier_105.setString(\"3886414\");\nset_field(noLegs_0_1, LegContractMultiplier_105, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegContractMultiplierUnit{1560230565}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegContractSettlMonth{\"MONTHYEAR_1741914528\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegCountryOfIssue{\"COUNTRY_1632675649\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_1295997181\"}, InstrumentLeg_105);\n    FIX::LegCouponRate LegCouponRate_105;\n    LegCouponRate_105.setString(\"66.380000\");\nset_field(noLegs_0_1, LegCouponRate_105, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegCreditRating{\"STRING_1696609209\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegCurrency{\"GBP\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegDatedDate{\"LOCALMKTDATE_2128660278\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegExerciseStyle{724898986}, InstrumentLeg_105);\n    FIX::LegFactor LegFactor_105;\n    LegFactor_105.setString(\"2958719\");\nset_field(noLegs_0_1, LegFactor_105, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegFlowScheduleType{671197474}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegInstrRegistry{\"STRING_1631399272\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_519648543\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegIssueDate{\"LOCALMKTDATE_1083984407\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegIssuer{\"STRING_1771996576\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegLocaleOfIssue{\"STRING_666703613\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegMaturityDate{\"LOCALMKTDATE_1924605685\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegMaturityMonthYear{\"MONTHYEAR_2123053929\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegMaturityTime{\"TZTIMEONLY_854885309\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegOptAttribute{'1'}, InstrumentLeg_105);\n    FIX::LegOptionRatio LegOptionRatio_105;\n    LegOptionRatio_105.setString(\"21366168\");\nset_field(noLegs_0_1, LegOptionRatio_105, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegPool{\"STRING_762809891\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegPriceUnitOfMeasure{\"STRING_767633928\"}, InstrumentLeg_105);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_105;\n    LegPriceUnitOfMeasureQty_105.setString(\"18942559\");\nset_field(noLegs_0_1, LegPriceUnitOfMeasureQty_105, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegProduct{615377467}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegPutOrCall{393881316}, InstrumentLeg_105);\n    FIX::LegRatioQty LegRatioQty_105;\n    LegRatioQty_105.setString(\"771755\");\nset_field(noLegs_0_1, LegRatioQty_105, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegRedemptionDate{\"LOCALMKTDATE_246618055\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegRepoCollateralSecurityType{\"STRING_726820154\"}, InstrumentLeg_105);\n    FIX::LegRepurchaseRate LegRepurchaseRate_105;\n    LegRepurchaseRate_105.setString(\"70.200000\");\nset_field(noLegs_0_1, LegRepurchaseRate_105, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegRepurchaseTerm{1806848620}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSecurityDesc{\"STRING_321251034\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSecurityExchange{\"EXCHANGE_2098492669\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSecurityID{\"STRING_955362153\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSecurityIDSource{\"STRING_1969147673\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSecuritySubType{\"STRING_1647618230\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSecurityType{\"STRING_1302388112\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSide{'1'}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegStateOrProvinceOfIssue{\"STRING_1628794861\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegStrikeCurrency{\"JPY\"}, InstrumentLeg_105);\n    FIX::LegStrikePrice LegStrikePrice_105;\n    LegStrikePrice_105.setString(\"1525086\");\nset_field(noLegs_0_1, LegStrikePrice_105, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSymbol{\"STRING_1511202723\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegSymbolSfx{\"STRING_441006125\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegTimeUnit{\"STRING_1236493094\"}, InstrumentLeg_105);\n    set_field(noLegs_0_1, FIX::LegUnitOfMeasure{\"STRING_1135715651\"}, InstrumentLeg_105);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_105;\n    LegUnitOfMeasureQty_105.setString(\"11077097\");\nset_field(noLegs_0_1, LegUnitOfMeasureQty_105, InstrumentLeg_105);\n    all_values.push_back(InstrumentLeg_105);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_207;\n      set_field(noLegSecurityAltID_1_1_0, FIX::LegSecurityAltID{\"STRING_1111285932\"}, LegSecAltIDGrp_NoLegSecurityAltID_207);\n      set_field(noLegSecurityAltID_1_1_0, FIX::LegSecurityAltIDSource{\"STRING_1962595047\"}, LegSecAltIDGrp_NoLegSecurityAltID_207);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_207);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_208;\n      set_field(noLegSecurityAltID_1_1_1, FIX::LegSecurityAltID{\"STRING_803114648\"}, LegSecAltIDGrp_NoLegSecurityAltID_208);\n      set_field(noLegSecurityAltID_1_1_1, FIX::LegSecurityAltIDSource{\"STRING_1100419170\"}, LegSecAltIDGrp_NoLegSecurityAltID_208);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_208);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_1);\n    }\n    // LegBenchmarkCurveData\n    multiset<string> LegBenchmarkCurveData_11;\n    set_field(noLegs_0_1, FIX::LegBenchmarkCurveCurrency{\"GBP\"}, LegBenchmarkCurveData_11);\n    set_field(noLegs_0_1, FIX::LegBenchmarkCurveName{\"STRING_847191457\"}, LegBenchmarkCurveData_11);\n    set_field(noLegs_0_1, FIX::LegBenchmarkCurvePoint{\"STRING_1193298757\"}, LegBenchmarkCurveData_11);\n    FIX::LegBenchmarkPrice LegBenchmarkPrice_11;\n    LegBenchmarkPrice_11.setString(\"19646298\");\nset_field(noLegs_0_1, LegBenchmarkPrice_11, LegBenchmarkCurveData_11);\n    set_field(noLegs_0_1, FIX::LegBenchmarkPriceType{924367012}, LegBenchmarkCurveData_11);\n    all_values.push_back(LegBenchmarkCurveData_11);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegStipulations noLegStipulations_1_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_38;\n      set_field(noLegStipulations_1_1_0, FIX::LegStipulationType{\"STRING_543966398\"}, LegStipulations_NoLegStipulations_38);\n      set_field(noLegStipulations_1_1_0, FIX::LegStipulationValue{\"STRING_1390184032\"}, LegStipulations_NoLegStipulations_38);\n      all_values.push_back(LegStipulations_NoLegStipulations_38);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_1.addGroup(noLegStipulations_1_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegStipulations noLegStipulations_1_1_1;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_39;\n      set_field(noLegStipulations_1_1_1, FIX::LegStipulationType{\"STRING_1099281784\"}, LegStipulations_NoLegStipulations_39);\n      set_field(noLegStipulations_1_1_1, FIX::LegStipulationValue{\"STRING_865217432\"}, LegStipulations_NoLegStipulations_39);\n      all_values.push_back(LegStipulations_NoLegStipulations_39);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_1.addGroup(noLegStipulations_1_1_1);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegStipulations noLegStipulations_1_1_2;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_40;\n      set_field(noLegStipulations_1_1_2, FIX::LegStipulationType{\"STRING_1341193053\"}, LegStipulations_NoLegStipulations_40);\n      set_field(noLegStipulations_1_1_2, FIX::LegStipulationValue{\"STRING_2054643937\"}, LegStipulations_NoLegStipulations_40);\n      all_values.push_back(LegStipulations_NoLegStipulations_40);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_1.addGroup(noLegStipulations_1_1_2);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_1_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_134;\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyID{\"STRING_841327635\"}, NestedParties_NoNestedPartyIDs_134);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_134);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyRole{312367077}, NestedParties_NoNestedPartyIDs_134);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_134);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_279;\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubID{\"STRING_1089351852\"}, NstdPtysSubGrp_NoNestedPartySubIDs_279);\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubIDType{233724659}, NstdPtysSubGrp_NoNestedPartySubIDs_279);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_279);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_280;\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubID{\"STRING_475147535\"}, NstdPtysSubGrp_NoNestedPartySubIDs_280);\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubIDType{453070927}, NstdPtysSubGrp_NoNestedPartySubIDs_280);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_280);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_281;\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubID{\"STRING_674730784\"}, NstdPtysSubGrp_NoNestedPartySubIDs_281);\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubIDType{1711640630}, NstdPtysSubGrp_NoNestedPartySubIDs_281);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_281);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_2);\n      }\n      noLegs_0_1.addGroup(noNestedPartyIDs_1_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_1_1_1;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_135;\n      set_field(noNestedPartyIDs_1_1_1, FIX::NestedPartyID{\"STRING_1588786578\"}, NestedParties_NoNestedPartyIDs_135);\n      set_field(noNestedPartyIDs_1_1_1, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_135);\n      set_field(noNestedPartyIDs_1_1_1, FIX::NestedPartyRole{577772113}, NestedParties_NoNestedPartyIDs_135);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_135);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_1_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_282;\n        set_field(noNestedPartySubIDs_1_1_2_0, FIX::NestedPartySubID{\"STRING_1597551921\"}, NstdPtysSubGrp_NoNestedPartySubIDs_282);\n        set_field(noNestedPartySubIDs_1_1_2_0, FIX::NestedPartySubIDType{1380886761}, NstdPtysSubGrp_NoNestedPartySubIDs_282);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_282);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_1.addGroup(noNestedPartySubIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_1_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_283;\n        set_field(noNestedPartySubIDs_1_1_2_1, FIX::NestedPartySubID{\"STRING_1653008033\"}, NstdPtysSubGrp_NoNestedPartySubIDs_283);\n        set_field(noNestedPartySubIDs_1_1_2_1, FIX::NestedPartySubIDType{27989563}, NstdPtysSubGrp_NoNestedPartySubIDs_283);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_283);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_1.addGroup(noNestedPartySubIDs_1_1_2_1);\n      }\n      noLegs_0_1.addGroup(noNestedPartyIDs_1_1_1);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_1_1_2;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_136;\n      set_field(noNestedPartyIDs_1_1_2, FIX::NestedPartyID{\"STRING_804151689\"}, NestedParties_NoNestedPartyIDs_136);\n      set_field(noNestedPartyIDs_1_1_2, FIX::NestedPartyIDSource{'3'}, NestedParties_NoNestedPartyIDs_136);\n      set_field(noNestedPartyIDs_1_1_2, FIX::NestedPartyRole{1221288321}, NestedParties_NoNestedPartyIDs_136);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_136);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_2_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_284;\n        set_field(noNestedPartySubIDs_1_2_2_0, FIX::NestedPartySubID{\"STRING_1277082854\"}, NstdPtysSubGrp_NoNestedPartySubIDs_284);\n        set_field(noNestedPartySubIDs_1_2_2_0, FIX::NestedPartySubIDType{513721485}, NstdPtysSubGrp_NoNestedPartySubIDs_284);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_284);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_2.addGroup(noNestedPartySubIDs_1_2_2_0);\n      }\n      noLegs_0_1.addGroup(noNestedPartyIDs_1_1_2);\n    }\n    msg.addGroup(noLegs_0_1);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoLegs noLegs_0_2;\n    // LegQuotGrp.NoLegs\n    multiset<string> LegQuotGrp_NoLegs_4;\n    FIX::LegBidForwardPoints LegBidForwardPoints_4;\n    LegBidForwardPoints_4.setString(\"11652643\");\nset_field(noLegs_0_2, LegBidForwardPoints_4, LegQuotGrp_NoLegs_4);\n    FIX::LegBidPx LegBidPx_4;\n    LegBidPx_4.setString(\"5197832\");\nset_field(noLegs_0_2, LegBidPx_4, LegQuotGrp_NoLegs_4);\n    FIX::LegOfferForwardPoints LegOfferForwardPoints_4;\n    LegOfferForwardPoints_4.setString(\"16130032\");\nset_field(noLegs_0_2, LegOfferForwardPoints_4, LegQuotGrp_NoLegs_4);\n    FIX::LegOfferPx LegOfferPx_4;\n    LegOfferPx_4.setString(\"20304817\");\nset_field(noLegs_0_2, LegOfferPx_4, LegQuotGrp_NoLegs_4);\n    FIX::LegOrderQty LegOrderQty_18;\n    LegOrderQty_18.setString(\"18609762\");\nset_field(noLegs_0_2, LegOrderQty_18, LegQuotGrp_NoLegs_4);\n    set_field(noLegs_0_2, FIX::LegPriceType{1520163559}, LegQuotGrp_NoLegs_4);\n    FIX::LegQty LegQty_18;\n    LegQty_18.setString(\"5698795\");\nset_field(noLegs_0_2, LegQty_18, LegQuotGrp_NoLegs_4);\n    set_field(noLegs_0_2, FIX::LegRefID{\"STRING_554820279\"}, LegQuotGrp_NoLegs_4);\n    set_field(noLegs_0_2, FIX::LegSettlDate{\"LOCALMKTDATE_582228313\"}, LegQuotGrp_NoLegs_4);\n    set_field(noLegs_0_2, FIX::LegSettlType{'8'}, LegQuotGrp_NoLegs_4);\n    set_field(noLegs_0_2, FIX::LegSwapType{5}, LegQuotGrp_NoLegs_4);\n    all_values.push_back(LegQuotGrp_NoLegs_4);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_106;\n    set_field(noLegs_0_2, FIX::EncodedLegIssuer{\"DATA_1671580166\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::EncodedLegIssuerLen{1115971309}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::EncodedLegSecurityDesc{\"DATA_1352606663\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::EncodedLegSecurityDescLen{2124651093}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegCFICode{\"STRING_1790702093\"}, InstrumentLeg_106);\n    FIX::LegContractMultiplier LegContractMultiplier_106;\n    LegContractMultiplier_106.setString(\"9167636\");\nset_field(noLegs_0_2, LegContractMultiplier_106, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegContractMultiplierUnit{1565954024}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegContractSettlMonth{\"MONTHYEAR_1425658967\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegCountryOfIssue{\"COUNTRY_1494535758\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_2118542886\"}, InstrumentLeg_106);\n    FIX::LegCouponRate LegCouponRate_106;\n    LegCouponRate_106.setString(\"72.400000\");\nset_field(noLegs_0_2, LegCouponRate_106, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegCreditRating{\"STRING_727938872\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegCurrency{\"GBP\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegDatedDate{\"LOCALMKTDATE_1532090561\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegExerciseStyle{1976783114}, InstrumentLeg_106);\n    FIX::LegFactor LegFactor_106;\n    LegFactor_106.setString(\"21250051\");\nset_field(noLegs_0_2, LegFactor_106, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegFlowScheduleType{5904847}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegInstrRegistry{\"STRING_1106382320\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_491242962\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegIssueDate{\"LOCALMKTDATE_1171169178\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegIssuer{\"STRING_1626165559\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegLocaleOfIssue{\"STRING_2104246232\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegMaturityDate{\"LOCALMKTDATE_1054167294\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegMaturityMonthYear{\"MONTHYEAR_1339658202\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegMaturityTime{\"TZTIMEONLY_1476926144\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegOptAttribute{'1'}, InstrumentLeg_106);\n    FIX::LegOptionRatio LegOptionRatio_106;\n    LegOptionRatio_106.setString(\"18944784\");\nset_field(noLegs_0_2, LegOptionRatio_106, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegPool{\"STRING_2059154457\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegPriceUnitOfMeasure{\"STRING_358809870\"}, InstrumentLeg_106);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_106;\n    LegPriceUnitOfMeasureQty_106.setString(\"6244539\");\nset_field(noLegs_0_2, LegPriceUnitOfMeasureQty_106, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegProduct{1583250975}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegPutOrCall{1474781180}, InstrumentLeg_106);\n    FIX::LegRatioQty LegRatioQty_106;\n    LegRatioQty_106.setString(\"19770606\");\nset_field(noLegs_0_2, LegRatioQty_106, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegRedemptionDate{\"LOCALMKTDATE_1560418421\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegRepoCollateralSecurityType{\"STRING_1117999625\"}, InstrumentLeg_106);\n    FIX::LegRepurchaseRate LegRepurchaseRate_106;\n    LegRepurchaseRate_106.setString(\"6.210000\");\nset_field(noLegs_0_2, LegRepurchaseRate_106, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegRepurchaseTerm{978888797}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSecurityDesc{\"STRING_396174945\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSecurityExchange{\"EXCHANGE_93392731\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSecurityID{\"STRING_949948035\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSecurityIDSource{\"STRING_1271902185\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSecuritySubType{\"STRING_821331603\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSecurityType{\"STRING_426531659\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSide{'2'}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegStateOrProvinceOfIssue{\"STRING_205938517\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegStrikeCurrency{\"USD\"}, InstrumentLeg_106);\n    FIX::LegStrikePrice LegStrikePrice_106;\n    LegStrikePrice_106.setString(\"2118433\");\nset_field(noLegs_0_2, LegStrikePrice_106, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSymbol{\"STRING_1362213445\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegSymbolSfx{\"STRING_496899781\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegTimeUnit{\"STRING_1383012542\"}, InstrumentLeg_106);\n    set_field(noLegs_0_2, FIX::LegUnitOfMeasure{\"STRING_840895356\"}, InstrumentLeg_106);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_106;\n    LegUnitOfMeasureQty_106.setString(\"4536623\");\nset_field(noLegs_0_2, LegUnitOfMeasureQty_106, InstrumentLeg_106);\n    all_values.push_back(InstrumentLeg_106);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegSecurityAltID noLegSecurityAltID_2_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_209;\n      set_field(noLegSecurityAltID_2_1_0, FIX::LegSecurityAltID{\"STRING_33069911\"}, LegSecAltIDGrp_NoLegSecurityAltID_209);\n      set_field(noLegSecurityAltID_2_1_0, FIX::LegSecurityAltIDSource{\"STRING_1930588509\"}, LegSecAltIDGrp_NoLegSecurityAltID_209);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_209);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_2.addGroup(noLegSecurityAltID_2_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegSecurityAltID noLegSecurityAltID_2_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_210;\n      set_field(noLegSecurityAltID_2_1_1, FIX::LegSecurityAltID{\"STRING_1913743057\"}, LegSecAltIDGrp_NoLegSecurityAltID_210);\n      set_field(noLegSecurityAltID_2_1_1, FIX::LegSecurityAltIDSource{\"STRING_1927548392\"}, LegSecAltIDGrp_NoLegSecurityAltID_210);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_210);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_2.addGroup(noLegSecurityAltID_2_1_1);\n    }\n    // LegBenchmarkCurveData\n    multiset<string> LegBenchmarkCurveData_12;\n    set_field(noLegs_0_2, FIX::LegBenchmarkCurveCurrency{\"CAN\"}, LegBenchmarkCurveData_12);\n    set_field(noLegs_0_2, FIX::LegBenchmarkCurveName{\"STRING_404518705\"}, LegBenchmarkCurveData_12);\n    set_field(noLegs_0_2, FIX::LegBenchmarkCurvePoint{\"STRING_1278026646\"}, LegBenchmarkCurveData_12);\n    FIX::LegBenchmarkPrice LegBenchmarkPrice_12;\n    LegBenchmarkPrice_12.setString(\"15998504\");\nset_field(noLegs_0_2, LegBenchmarkPrice_12, LegBenchmarkCurveData_12);\n    set_field(noLegs_0_2, FIX::LegBenchmarkPriceType{234095681}, LegBenchmarkCurveData_12);\n    all_values.push_back(LegBenchmarkCurveData_12);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoLegStipulations noLegStipulations_2_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_41;\n      set_field(noLegStipulations_2_1_0, FIX::LegStipulationType{\"STRING_570366437\"}, LegStipulations_NoLegStipulations_41);\n      set_field(noLegStipulations_2_1_0, FIX::LegStipulationValue{\"STRING_980436302\"}, LegStipulations_NoLegStipulations_41);\n      all_values.push_back(LegStipulations_NoLegStipulations_41);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_2.addGroup(noLegStipulations_2_1_0);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_2_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_137;\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyID{\"STRING_966541382\"}, NestedParties_NoNestedPartyIDs_137);\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_137);\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyRole{472314604}, NestedParties_NoNestedPartyIDs_137);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_137);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_285;\n        set_field(noNestedPartySubIDs_2_0_2_0, FIX::NestedPartySubID{\"STRING_1895160637\"}, NstdPtysSubGrp_NoNestedPartySubIDs_285);\n        set_field(noNestedPartySubIDs_2_0_2_0, FIX::NestedPartySubIDType{898846263}, NstdPtysSubGrp_NoNestedPartySubIDs_285);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_285);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_0.addGroup(noNestedPartySubIDs_2_0_2_0);\n      }\n      noLegs_0_2.addGroup(noNestedPartyIDs_2_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_2_1_1;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_138;\n      set_field(noNestedPartyIDs_2_1_1, FIX::NestedPartyID{\"STRING_119095261\"}, NestedParties_NoNestedPartyIDs_138);\n      set_field(noNestedPartyIDs_2_1_1, FIX::NestedPartyIDSource{'2'}, NestedParties_NoNestedPartyIDs_138);\n      set_field(noNestedPartyIDs_2_1_1, FIX::NestedPartyRole{1154677388}, NestedParties_NoNestedPartyIDs_138);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_138);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_1_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_286;\n        set_field(noNestedPartySubIDs_2_1_2_0, FIX::NestedPartySubID{\"STRING_165458870\"}, NstdPtysSubGrp_NoNestedPartySubIDs_286);\n        set_field(noNestedPartySubIDs_2_1_2_0, FIX::NestedPartySubIDType{369407185}, NstdPtysSubGrp_NoNestedPartySubIDs_286);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_286);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_1.addGroup(noNestedPartySubIDs_2_1_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_1_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_287;\n        set_field(noNestedPartySubIDs_2_1_2_1, FIX::NestedPartySubID{\"STRING_621651860\"}, NstdPtysSubGrp_NoNestedPartySubIDs_287);\n        set_field(noNestedPartySubIDs_2_1_2_1, FIX::NestedPartySubIDType{1548471413}, NstdPtysSubGrp_NoNestedPartySubIDs_287);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_287);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_1.addGroup(noNestedPartySubIDs_2_1_2_1);\n      }\n      noLegs_0_2.addGroup(noNestedPartyIDs_2_1_1);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs noNestedPartyIDs_2_1_2;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_139;\n      set_field(noNestedPartyIDs_2_1_2, FIX::NestedPartyID{\"STRING_1210302542\"}, NestedParties_NoNestedPartyIDs_139);\n      set_field(noNestedPartyIDs_2_1_2, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_139);\n      set_field(noNestedPartyIDs_2_1_2, FIX::NestedPartyRole{1838167602}, NestedParties_NoNestedPartyIDs_139);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_139);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_2_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_288;\n        set_field(noNestedPartySubIDs_2_2_2_0, FIX::NestedPartySubID{\"STRING_858419087\"}, NstdPtysSubGrp_NoNestedPartySubIDs_288);\n        set_field(noNestedPartySubIDs_2_2_2_0, FIX::NestedPartySubIDType{1604427011}, NstdPtysSubGrp_NoNestedPartySubIDs_288);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_288);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_2.addGroup(noNestedPartySubIDs_2_2_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_2_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_289;\n        set_field(noNestedPartySubIDs_2_2_2_1, FIX::NestedPartySubID{\"STRING_1023437197\"}, NstdPtysSubGrp_NoNestedPartySubIDs_289);\n        set_field(noNestedPartySubIDs_2_2_2_1, FIX::NestedPartySubIDType{553194758}, NstdPtysSubGrp_NoNestedPartySubIDs_289);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_289);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_2.addGroup(noNestedPartySubIDs_2_2_2_1);\n      }\n      noLegs_0_2.addGroup(noNestedPartyIDs_2_1_2);\n    }\n    msg.addGroup(noLegs_0_2);\n  }\n  // OrderQtyData\n  multiset<string> OrderQtyData_25;\n  FIX::CashOrderQty CashOrderQty_25;\n  CashOrderQty_25.setString(\"17294962\");\nset_field(msg, CashOrderQty_25, OrderQtyData_25);\n  FIX::OrderPercent OrderPercent_25;\n  OrderPercent_25.setString(\"59.030000\");\nset_field(msg, OrderPercent_25, OrderQtyData_25);\n  FIX::OrderQty OrderQty_34;\n  OrderQty_34.setString(\"18312214\");\nset_field(msg, OrderQty_34, OrderQtyData_25);\n  set_field(msg, FIX::RoundingDirection{'1'}, OrderQtyData_25);\n  FIX::RoundingModulus RoundingModulus_25;\n  RoundingModulus_25.setString(\"16620515\");\nset_field(msg, RoundingModulus_25, OrderQtyData_25);\n  all_values.push_back(OrderQtyData_25);\n  all_compo_names.insert(\".\");\n\n  // Parties\n  // Group Parties.NoPartyIDs\n  {\n    FIX50SP2::QuoteResponse::NoPartyIDs noPartyIDs_0_0;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_120;\n    set_field(noPartyIDs_0_0, FIX::PartyID{\"STRING_1752229539\"}, Parties_NoPartyIDs_120);\n    set_field(noPartyIDs_0_0, FIX::PartyIDSource{'5'}, Parties_NoPartyIDs_120);\n    set_field(noPartyIDs_0_0, FIX::PartyRole{63}, Parties_NoPartyIDs_120);\n    all_values.push_back(Parties_NoPartyIDs_120);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::QuoteResponse::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_240;\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubID{\"STRING_1568833273\"}, PtysSubGrp_NoPartySubIDs_240);\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubIDType{31}, PtysSubGrp_NoPartySubIDs_240);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_240);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_0);\n    }\n    msg.addGroup(noPartyIDs_0_0);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoPartyIDs noPartyIDs_0_1;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_121;\n    set_field(noPartyIDs_0_1, FIX::PartyID{\"STRING_662247192\"}, Parties_NoPartyIDs_121);\n    set_field(noPartyIDs_0_1, FIX::PartyIDSource{'6'}, Parties_NoPartyIDs_121);\n    set_field(noPartyIDs_0_1, FIX::PartyRole{74}, Parties_NoPartyIDs_121);\n    all_values.push_back(Parties_NoPartyIDs_121);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::QuoteResponse::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_241;\n      set_field(noPartySubIDs_1_1_0, FIX::PartySubID{\"STRING_1270125769\"}, PtysSubGrp_NoPartySubIDs_241);\n      set_field(noPartySubIDs_1_1_0, FIX::PartySubIDType{10}, PtysSubGrp_NoPartySubIDs_241);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_241);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_1;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_242;\n      set_field(noPartySubIDs_1_1_1, FIX::PartySubID{\"STRING_906094533\"}, PtysSubGrp_NoPartySubIDs_242);\n      set_field(noPartySubIDs_1_1_1, FIX::PartySubIDType{28}, PtysSubGrp_NoPartySubIDs_242);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_242);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_1);\n    }\n    msg.addGroup(noPartyIDs_0_1);\n  }\n  // QuotQualGrp\n  // Group QuotQualGrp.NoQuoteQualifiers\n  {\n    FIX50SP2::QuoteResponse::NoQuoteQualifiers noQuoteQualifiers_0_0;\n    // QuotQualGrp.NoQuoteQualifiers\n    multiset<string> QuotQualGrp_NoQuoteQualifiers_11;\n    set_field(noQuoteQualifiers_0_0, FIX::QuoteQualifier{'1'}, QuotQualGrp_NoQuoteQualifiers_11);\n    all_values.push_back(QuotQualGrp_NoQuoteQualifiers_11);\n    all_compo_names.insert(\"...NoQuoteQualifiers\");\n\n    msg.addGroup(noQuoteQualifiers_0_0);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoQuoteQualifiers noQuoteQualifiers_0_1;\n    // QuotQualGrp.NoQuoteQualifiers\n    multiset<string> QuotQualGrp_NoQuoteQualifiers_12;\n    set_field(noQuoteQualifiers_0_1, FIX::QuoteQualifier{'8'}, QuotQualGrp_NoQuoteQualifiers_12);\n    all_values.push_back(QuotQualGrp_NoQuoteQualifiers_12);\n    all_compo_names.insert(\"...NoQuoteQualifiers\");\n\n    msg.addGroup(noQuoteQualifiers_0_1);\n  }\n  // SpreadOrBenchmarkCurveData\n  multiset<string> SpreadOrBenchmarkCurveData_28;\n  set_field(msg, FIX::BenchmarkCurveCurrency{\"EUR\"}, SpreadOrBenchmarkCurveData_28);\n  set_field(msg, FIX::BenchmarkCurveName{\"STRING_SWAP\"}, SpreadOrBenchmarkCurveData_28);\n  set_field(msg, FIX::BenchmarkCurvePoint{\"STRING_951018884\"}, SpreadOrBenchmarkCurveData_28);\n  FIX::BenchmarkPrice BenchmarkPrice_28;\n  BenchmarkPrice_28.setString(\"13139960\");\nset_field(msg, BenchmarkPrice_28, SpreadOrBenchmarkCurveData_28);\n  set_field(msg, FIX::BenchmarkPriceType{2131683369}, SpreadOrBenchmarkCurveData_28);\n  set_field(msg, FIX::BenchmarkSecurityID{\"STRING_1974456082\"}, SpreadOrBenchmarkCurveData_28);\n  set_field(msg, FIX::BenchmarkSecurityIDSource{\"STRING_1867190817\"}, SpreadOrBenchmarkCurveData_28);\n  FIX::Spread Spread_28;\n  Spread_28.setString(\"17136960\");\nset_field(msg, Spread_28, SpreadOrBenchmarkCurveData_28);\n  all_values.push_back(SpreadOrBenchmarkCurveData_28);\n  all_compo_names.insert(\".\");\n\n  // Stipulations\n  // Group Stipulations.NoStipulations\n  {\n    FIX50SP2::QuoteResponse::NoStipulations noStipulations_0_0;\n    // Stipulations.NoStipulations\n    multiset<string> Stipulations_NoStipulations_47;\n    set_field(noStipulations_0_0, FIX::StipulationType{\"STRING_LOT\"}, Stipulations_NoStipulations_47);\n    set_field(noStipulations_0_0, FIX::StipulationValue{\"STRING_748075466\"}, Stipulations_NoStipulations_47);\n    all_values.push_back(Stipulations_NoStipulations_47);\n    all_compo_names.insert(\"...NoStipulations\");\n\n    msg.addGroup(noStipulations_0_0);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoStipulations noStipulations_0_1;\n    // Stipulations.NoStipulations\n    multiset<string> Stipulations_NoStipulations_48;\n    set_field(noStipulations_0_1, FIX::StipulationType{\"STRING_PXSOURCE\"}, Stipulations_NoStipulations_48);\n    set_field(noStipulations_0_1, FIX::StipulationValue{\"STRING_1925627751\"}, Stipulations_NoStipulations_48);\n    all_values.push_back(Stipulations_NoStipulations_48);\n    all_compo_names.insert(\"...NoStipulations\");\n\n    msg.addGroup(noStipulations_0_1);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoStipulations noStipulations_0_2;\n    // Stipulations.NoStipulations\n    multiset<string> Stipulations_NoStipulations_49;\n    set_field(noStipulations_0_2, FIX::StipulationType{\"STRING_PPC\"}, Stipulations_NoStipulations_49);\n    set_field(noStipulations_0_2, FIX::StipulationValue{\"STRING_1264500512\"}, Stipulations_NoStipulations_49);\n    all_values.push_back(Stipulations_NoStipulations_49);\n    all_compo_names.insert(\"...NoStipulations\");\n\n    msg.addGroup(noStipulations_0_2);\n  }\n  // UndInstrmtGrp\n  // Group UndInstrmtGrp.NoUnderlyings\n  {\n    FIX50SP2::QuoteResponse::NoUnderlyings noUnderlyings_0_0;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_106;\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuer{\"DATA_924108630\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuerLen{685850137}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDesc{\"DATA_44590197\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDescLen{1586355822}, UnderlyingInstrument_106);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_106;\n    UnderlyingAdjustedQuantity_106.setString(\"20023604\");\nset_field(noUnderlyings_0_0, UnderlyingAdjustedQuantity_106, UnderlyingInstrument_106);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_106;\n    UnderlyingAllocationPercent_106.setString(\"68.090000\");\nset_field(noUnderlyings_0_0, UnderlyingAllocationPercent_106, UnderlyingInstrument_106);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_106;\n    UnderlyingAttachmentPoint_106.setString(\"46.280000\");\nset_field(noUnderlyings_0_0, UnderlyingAttachmentPoint_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCFICode{\"STRING_1125002521\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPProgram{\"STRING_1588237161\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPRegType{\"STRING_1126309161\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingCapValue UnderlyingCapValue_106;\n    UnderlyingCapValue_106.setString(\"4131035\");\nset_field(noUnderlyings_0_0, UnderlyingCapValue_106, UnderlyingInstrument_106);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_106;\n    UnderlyingCashAmount_106.setString(\"855810\");\nset_field(noUnderlyings_0_0, UnderlyingCashAmount_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCashType{\"STRING_FIXED\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_106;\n    UnderlyingContractMultiplier_106.setString(\"12496759\");\nset_field(noUnderlyings_0_0, UnderlyingContractMultiplier_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingContractMultiplierUnit{1940711130}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCountryOfIssue{\"COUNTRY_962148878\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_1776932275\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_106;\n    UnderlyingCouponRate_106.setString(\"63.660000\");\nset_field(noUnderlyings_0_0, UnderlyingCouponRate_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCreditRating{\"STRING_128661289\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCurrency{\"GBP\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_106;\n    UnderlyingCurrentValue_106.setString(\"19958521\");\nset_field(noUnderlyings_0_0, UnderlyingCurrentValue_106, UnderlyingInstrument_106);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_106;\n    UnderlyingDetachmentPoint_106.setString(\"43.610000\");\nset_field(noUnderlyings_0_0, UnderlyingDetachmentPoint_106, UnderlyingInstrument_106);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_106;\n    UnderlyingDirtyPrice_106.setString(\"18261471\");\nset_field(noUnderlyings_0_0, UnderlyingDirtyPrice_106, UnderlyingInstrument_106);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_106;\n    UnderlyingEndPrice_106.setString(\"13992970\");\nset_field(noUnderlyings_0_0, UnderlyingEndPrice_106, UnderlyingInstrument_106);\n    FIX::UnderlyingEndValue UnderlyingEndValue_106;\n    UnderlyingEndValue_106.setString(\"20754198\");\nset_field(noUnderlyings_0_0, UnderlyingEndValue_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingExerciseStyle{448159763}, UnderlyingInstrument_106);\n    FIX::UnderlyingFXRate UnderlyingFXRate_106;\n    UnderlyingFXRate_106.setString(\"11774411\");\nset_field(noUnderlyings_0_0, UnderlyingFXRate_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFXRateCalc{'D'}, UnderlyingInstrument_106);\n    FIX::UnderlyingFactor UnderlyingFactor_106;\n    UnderlyingFactor_106.setString(\"17126602\");\nset_field(noUnderlyings_0_0, UnderlyingFactor_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFlowScheduleType{852650984}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingInstrRegistry{\"STRING_1204866166\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_251026765\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssuer{\"STRING_897241181\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingLocaleOfIssue{\"STRING_643738340\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_105903517\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_62574342\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_863952968\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_106;\n    UnderlyingNotionalPercentageOutstanding_106.setString(\"60.380000\");\nset_field(noUnderlyings_0_0, UnderlyingNotionalPercentageOutstanding_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_106);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_106;\n    UnderlyingOriginalNotionalPercentageOutstanding_106.setString(\"21.290000\");\nset_field(noUnderlyings_0_0, UnderlyingOriginalNotionalPercentageOutstanding_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_1644009550\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_106;\n    UnderlyingPriceUnitOfMeasureQty_106.setString(\"17363925\");\nset_field(noUnderlyings_0_0, UnderlyingPriceUnitOfMeasureQty_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingProduct{349350388}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPutOrCall{746201819}, UnderlyingInstrument_106);\n    FIX::UnderlyingPx UnderlyingPx_106;\n    UnderlyingPx_106.setString(\"15296200\");\nset_field(noUnderlyings_0_0, UnderlyingPx_106, UnderlyingInstrument_106);\n    FIX::UnderlyingQty UnderlyingQty_106;\n    UnderlyingQty_106.setString(\"13114992\");\nset_field(noUnderlyings_0_0, UnderlyingQty_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_375650447\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_126382754\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_106;\n    UnderlyingRepurchaseRate_106.setString(\"5.550000\");\nset_field(noUnderlyings_0_0, UnderlyingRepurchaseRate_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepurchaseTerm{2136782444}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRestructuringType{\"STRING_697601554\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityDesc{\"STRING_1288529013\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityExchange{\"EXCHANGE_1316643157\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityID{\"STRING_376265044\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityIDSource{\"STRING_540342398\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecuritySubType{\"STRING_1244579336\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityType{\"STRING_824424807\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSeniority{\"STRING_1717783534\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlMethod{\"STRING_1525336872\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlementType{5}, UnderlyingInstrument_106);\n    FIX::UnderlyingStartValue UnderlyingStartValue_106;\n    UnderlyingStartValue_106.setString(\"4229508\");\nset_field(noUnderlyings_0_0, UnderlyingStartValue_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_582719390\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStrikeCurrency{\"CHF\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_106;\n    UnderlyingStrikePrice_106.setString(\"12264577\");\nset_field(noUnderlyings_0_0, UnderlyingStrikePrice_106, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbol{\"STRING_746531716\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbolSfx{\"STRING_1382766393\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingTimeUnit{\"STRING_2090410699\"}, UnderlyingInstrument_106);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingUnitOfMeasure{\"STRING_1977437754\"}, UnderlyingInstrument_106);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_106;\n    UnderlyingUnitOfMeasureQty_106.setString(\"8860942\");\nset_field(noUnderlyings_0_0, UnderlyingUnitOfMeasureQty_106, UnderlyingInstrument_106);\n    all_values.push_back(UnderlyingInstrument_106);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_220;\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltID{\"STRING_1473963657\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_220);\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_475003154\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_220);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_220);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_1;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_221;\n      set_field(noUnderlyingSecurityAltID_0_1_1, FIX::UnderlyingSecurityAltID{\"STRING_135055920\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_221);\n      set_field(noUnderlyingSecurityAltID_0_1_1, FIX::UnderlyingSecurityAltIDSource{\"STRING_72681828\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_221);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_221);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_1);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_210;\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipType{\"STRING_1446555186\"}, UnderlyingStipulations_NoUnderlyingStips_210);\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipValue{\"STRING_448332275\"}, UnderlyingStipulations_NoUnderlyingStips_210);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_210);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_1;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_211;\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipType{\"STRING_2131005943\"}, UnderlyingStipulations_NoUnderlyingStips_211);\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipValue{\"STRING_739232093\"}, UnderlyingStipulations_NoUnderlyingStips_211);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_211);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_1);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_2;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_212;\n      set_field(noUnderlyingStips_0_1_2, FIX::UnderlyingStipType{\"STRING_437631071\"}, UnderlyingStipulations_NoUnderlyingStips_212);\n      set_field(noUnderlyingStips_0_1_2, FIX::UnderlyingStipValue{\"STRING_681123850\"}, UnderlyingStipulations_NoUnderlyingStips_212);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_212);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_2);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_227;\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_1754274228\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_227);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_227);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyRole{420619857}, UndlyInstrumentParties_NoUndlyInstrumentParties_227);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_227);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_456;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1881813701\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_456);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{2138403392}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_456);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_456);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_0);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_0);\n    }\n    msg.addGroup(noUnderlyings_0_0);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoUnderlyings noUnderlyings_0_1;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_107;\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuer{\"DATA_229223140\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuerLen{123931487}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDesc{\"DATA_413870614\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDescLen{811942530}, UnderlyingInstrument_107);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_107;\n    UnderlyingAdjustedQuantity_107.setString(\"7645596\");\nset_field(noUnderlyings_0_1, UnderlyingAdjustedQuantity_107, UnderlyingInstrument_107);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_107;\n    UnderlyingAllocationPercent_107.setString(\"26.660000\");\nset_field(noUnderlyings_0_1, UnderlyingAllocationPercent_107, UnderlyingInstrument_107);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_107;\n    UnderlyingAttachmentPoint_107.setString(\"2.610000\");\nset_field(noUnderlyings_0_1, UnderlyingAttachmentPoint_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCFICode{\"STRING_1511091403\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPProgram{\"STRING_969345411\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPRegType{\"STRING_1981327312\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingCapValue UnderlyingCapValue_107;\n    UnderlyingCapValue_107.setString(\"13410455\");\nset_field(noUnderlyings_0_1, UnderlyingCapValue_107, UnderlyingInstrument_107);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_107;\n    UnderlyingCashAmount_107.setString(\"18554396\");\nset_field(noUnderlyings_0_1, UnderlyingCashAmount_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCashType{\"STRING_FIXED\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_107;\n    UnderlyingContractMultiplier_107.setString(\"6675255\");\nset_field(noUnderlyings_0_1, UnderlyingContractMultiplier_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingContractMultiplierUnit{182959166}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCountryOfIssue{\"COUNTRY_1902088765\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_740207347\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_107;\n    UnderlyingCouponRate_107.setString(\"87.070000\");\nset_field(noUnderlyings_0_1, UnderlyingCouponRate_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCreditRating{\"STRING_1201160303\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCurrency{\"CAN\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_107;\n    UnderlyingCurrentValue_107.setString(\"19403923\");\nset_field(noUnderlyings_0_1, UnderlyingCurrentValue_107, UnderlyingInstrument_107);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_107;\n    UnderlyingDetachmentPoint_107.setString(\"6.940000\");\nset_field(noUnderlyings_0_1, UnderlyingDetachmentPoint_107, UnderlyingInstrument_107);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_107;\n    UnderlyingDirtyPrice_107.setString(\"7047448\");\nset_field(noUnderlyings_0_1, UnderlyingDirtyPrice_107, UnderlyingInstrument_107);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_107;\n    UnderlyingEndPrice_107.setString(\"18206698\");\nset_field(noUnderlyings_0_1, UnderlyingEndPrice_107, UnderlyingInstrument_107);\n    FIX::UnderlyingEndValue UnderlyingEndValue_107;\n    UnderlyingEndValue_107.setString(\"12329612\");\nset_field(noUnderlyings_0_1, UnderlyingEndValue_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingExerciseStyle{1762133747}, UnderlyingInstrument_107);\n    FIX::UnderlyingFXRate UnderlyingFXRate_107;\n    UnderlyingFXRate_107.setString(\"938060\");\nset_field(noUnderlyings_0_1, UnderlyingFXRate_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFXRateCalc{'M'}, UnderlyingInstrument_107);\n    FIX::UnderlyingFactor UnderlyingFactor_107;\n    UnderlyingFactor_107.setString(\"14964638\");\nset_field(noUnderlyings_0_1, UnderlyingFactor_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFlowScheduleType{84725809}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingInstrRegistry{\"STRING_166070684\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_1620395287\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssuer{\"STRING_498596424\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingLocaleOfIssue{\"STRING_978013214\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_237471326\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_85175442\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_868929827\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_107;\n    UnderlyingNotionalPercentageOutstanding_107.setString(\"27.300000\");\nset_field(noUnderlyings_0_1, UnderlyingNotionalPercentageOutstanding_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_107);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_107;\n    UnderlyingOriginalNotionalPercentageOutstanding_107.setString(\"34.910000\");\nset_field(noUnderlyings_0_1, UnderlyingOriginalNotionalPercentageOutstanding_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_942124592\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_107;\n    UnderlyingPriceUnitOfMeasureQty_107.setString(\"7624768\");\nset_field(noUnderlyings_0_1, UnderlyingPriceUnitOfMeasureQty_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingProduct{322322688}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPutOrCall{1609650111}, UnderlyingInstrument_107);\n    FIX::UnderlyingPx UnderlyingPx_107;\n    UnderlyingPx_107.setString(\"9454360\");\nset_field(noUnderlyings_0_1, UnderlyingPx_107, UnderlyingInstrument_107);\n    FIX::UnderlyingQty UnderlyingQty_107;\n    UnderlyingQty_107.setString(\"769278\");\nset_field(noUnderlyings_0_1, UnderlyingQty_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_202373810\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_985534739\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_107;\n    UnderlyingRepurchaseRate_107.setString(\"81.080000\");\nset_field(noUnderlyings_0_1, UnderlyingRepurchaseRate_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepurchaseTerm{1390913433}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRestructuringType{\"STRING_1009155742\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityDesc{\"STRING_1070996857\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityExchange{\"EXCHANGE_869600480\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityID{\"STRING_1713900595\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityIDSource{\"STRING_744183065\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecuritySubType{\"STRING_2102561755\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityType{\"STRING_1328550694\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSeniority{\"STRING_837989131\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlMethod{\"STRING_2039409298\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlementType{4}, UnderlyingInstrument_107);\n    FIX::UnderlyingStartValue UnderlyingStartValue_107;\n    UnderlyingStartValue_107.setString(\"9227149\");\nset_field(noUnderlyings_0_1, UnderlyingStartValue_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_57996334\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStrikeCurrency{\"GBP\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_107;\n    UnderlyingStrikePrice_107.setString(\"10360095\");\nset_field(noUnderlyings_0_1, UnderlyingStrikePrice_107, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbol{\"STRING_387913812\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbolSfx{\"STRING_1506486806\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingTimeUnit{\"STRING_1904939376\"}, UnderlyingInstrument_107);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingUnitOfMeasure{\"STRING_2136476542\"}, UnderlyingInstrument_107);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_107;\n    UnderlyingUnitOfMeasureQty_107.setString(\"4135240\");\nset_field(noUnderlyings_0_1, UnderlyingUnitOfMeasureQty_107, UnderlyingInstrument_107);\n    all_values.push_back(UnderlyingInstrument_107);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_1_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_222;\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltID{\"STRING_931117486\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_222);\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_1176000877\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_222);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_222);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingSecurityAltID_1_1_0);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_1_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_213;\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipType{\"STRING_393283949\"}, UnderlyingStipulations_NoUnderlyingStips_213);\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipValue{\"STRING_2121436909\"}, UnderlyingStipulations_NoUnderlyingStips_213);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_213);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingStips_1_1_0);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_228;\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_595657759\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_228);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyIDSource{'9'}, UndlyInstrumentParties_NoUndlyInstrumentParties_228);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyRole{2137567821}, UndlyInstrumentParties_NoUndlyInstrumentParties_228);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_228);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_457;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1968643742\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_457);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{1061081031}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_457);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_457);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_458;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_708688025\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_458);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{1535060689}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_458);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_458);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_459;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_1805264096\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_459);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_2, FIX::UnderlyingInstrumentPartySubIDType{663766132}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_459);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_459);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_2);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_229;\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_716127735\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_229);\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyIDSource{'4'}, UndlyInstrumentParties_NoUndlyInstrumentParties_229);\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyRole{555691782}, UndlyInstrumentParties_NoUndlyInstrumentParties_229);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_229);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_460;\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1418484520\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_460);\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{613688117}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_460);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_460);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_1.addGroup(noUndlyInstrumentPartySubIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_1_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_461;\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1544101066\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_461);\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_1, FIX::UnderlyingInstrumentPartySubIDType{692312236}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_461);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_461);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_1.addGroup(noUndlyInstrumentPartySubIDs_1_1_2_1);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_1);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_2;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_230;\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyID{\"STRING_1649697666\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_230);\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_230);\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyRole{51315395}, UndlyInstrumentParties_NoUndlyInstrumentParties_230);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_230);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_2_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_462;\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1921007772\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_462);\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_0, FIX::UnderlyingInstrumentPartySubIDType{464839407}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_462);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_462);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_2.addGroup(noUndlyInstrumentPartySubIDs_1_2_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_2_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_463;\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1867382614\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_463);\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_1, FIX::UnderlyingInstrumentPartySubIDType{704641610}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_463);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_463);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_2.addGroup(noUndlyInstrumentPartySubIDs_1_2_2_1);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_2);\n    }\n    msg.addGroup(noUnderlyings_0_1);\n  }\n  {\n    FIX50SP2::QuoteResponse::NoUnderlyings noUnderlyings_0_2;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_108;\n    set_field(noUnderlyings_0_2, FIX::EncodedUnderlyingIssuer{\"DATA_1640840284\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::EncodedUnderlyingIssuerLen{502450874}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::EncodedUnderlyingSecurityDesc{\"DATA_1097925559\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::EncodedUnderlyingSecurityDescLen{1614793545}, UnderlyingInstrument_108);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_108;\n    UnderlyingAdjustedQuantity_108.setString(\"13619305\");\nset_field(noUnderlyings_0_2, UnderlyingAdjustedQuantity_108, UnderlyingInstrument_108);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_108;\n    UnderlyingAllocationPercent_108.setString(\"33.190000\");\nset_field(noUnderlyings_0_2, UnderlyingAllocationPercent_108, UnderlyingInstrument_108);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_108;\n    UnderlyingAttachmentPoint_108.setString(\"78.970000\");\nset_field(noUnderlyings_0_2, UnderlyingAttachmentPoint_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingCFICode{\"STRING_1352014761\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingCPProgram{\"STRING_1532670864\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingCPRegType{\"STRING_247957991\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingCapValue UnderlyingCapValue_108;\n    UnderlyingCapValue_108.setString(\"2656121\");\nset_field(noUnderlyings_0_2, UnderlyingCapValue_108, UnderlyingInstrument_108);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_108;\n    UnderlyingCashAmount_108.setString(\"938752\");\nset_field(noUnderlyings_0_2, UnderlyingCashAmount_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingCashType{\"STRING_FIXED\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_108;\n    UnderlyingContractMultiplier_108.setString(\"20708762\");\nset_field(noUnderlyings_0_2, UnderlyingContractMultiplier_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingContractMultiplierUnit{757641373}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingCountryOfIssue{\"COUNTRY_351662767\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_419162172\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_108;\n    UnderlyingCouponRate_108.setString(\"31.550000\");\nset_field(noUnderlyings_0_2, UnderlyingCouponRate_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingCreditRating{\"STRING_1745321348\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingCurrency{\"USD\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_108;\n    UnderlyingCurrentValue_108.setString(\"11419387\");\nset_field(noUnderlyings_0_2, UnderlyingCurrentValue_108, UnderlyingInstrument_108);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_108;\n    UnderlyingDetachmentPoint_108.setString(\"52.800000\");\nset_field(noUnderlyings_0_2, UnderlyingDetachmentPoint_108, UnderlyingInstrument_108);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_108;\n    UnderlyingDirtyPrice_108.setString(\"14292352\");\nset_field(noUnderlyings_0_2, UnderlyingDirtyPrice_108, UnderlyingInstrument_108);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_108;\n    UnderlyingEndPrice_108.setString(\"9264699\");\nset_field(noUnderlyings_0_2, UnderlyingEndPrice_108, UnderlyingInstrument_108);\n    FIX::UnderlyingEndValue UnderlyingEndValue_108;\n    UnderlyingEndValue_108.setString(\"4337906\");\nset_field(noUnderlyings_0_2, UnderlyingEndValue_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingExerciseStyle{688905037}, UnderlyingInstrument_108);\n    FIX::UnderlyingFXRate UnderlyingFXRate_108;\n    UnderlyingFXRate_108.setString(\"6999941\");\nset_field(noUnderlyings_0_2, UnderlyingFXRate_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingFXRateCalc{'D'}, UnderlyingInstrument_108);\n    FIX::UnderlyingFactor UnderlyingFactor_108;\n    UnderlyingFactor_108.setString(\"4088040\");\nset_field(noUnderlyings_0_2, UnderlyingFactor_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingFlowScheduleType{1404635732}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingInstrRegistry{\"STRING_391986719\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_911254878\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingIssuer{\"STRING_355077644\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingLocaleOfIssue{\"STRING_2006780264\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_125701817\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_2048660963\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_286094514\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_108;\n    UnderlyingNotionalPercentageOutstanding_108.setString(\"65.780000\");\nset_field(noUnderlyings_0_2, UnderlyingNotionalPercentageOutstanding_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_108);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_108;\n    UnderlyingOriginalNotionalPercentageOutstanding_108.setString(\"25.050000\");\nset_field(noUnderlyings_0_2, UnderlyingOriginalNotionalPercentageOutstanding_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_1743328722\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_108;\n    UnderlyingPriceUnitOfMeasureQty_108.setString(\"15277234\");\nset_field(noUnderlyings_0_2, UnderlyingPriceUnitOfMeasureQty_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingProduct{169587538}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingPutOrCall{1666721315}, UnderlyingInstrument_108);\n    FIX::UnderlyingPx UnderlyingPx_108;\n    UnderlyingPx_108.setString(\"1378811\");\nset_field(noUnderlyings_0_2, UnderlyingPx_108, UnderlyingInstrument_108);\n    FIX::UnderlyingQty UnderlyingQty_108;\n    UnderlyingQty_108.setString(\"5212503\");\nset_field(noUnderlyings_0_2, UnderlyingQty_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_2085883487\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_1451214300\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_108;\n    UnderlyingRepurchaseRate_108.setString(\"80.060000\");\nset_field(noUnderlyings_0_2, UnderlyingRepurchaseRate_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingRepurchaseTerm{1776046531}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingRestructuringType{\"STRING_1230751925\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSecurityDesc{\"STRING_1261026773\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSecurityExchange{\"EXCHANGE_11038163\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSecurityID{\"STRING_512503567\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSecurityIDSource{\"STRING_40013122\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSecuritySubType{\"STRING_444828839\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSecurityType{\"STRING_1201408604\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSeniority{\"STRING_740007244\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSettlMethod{\"STRING_1343458921\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSettlementType{2}, UnderlyingInstrument_108);\n    FIX::UnderlyingStartValue UnderlyingStartValue_108;\n    UnderlyingStartValue_108.setString(\"21446429\");\nset_field(noUnderlyings_0_2, UnderlyingStartValue_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_1735445640\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingStrikeCurrency{\"EUR\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_108;\n    UnderlyingStrikePrice_108.setString(\"15947422\");\nset_field(noUnderlyings_0_2, UnderlyingStrikePrice_108, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSymbol{\"STRING_499685655\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingSymbolSfx{\"STRING_253414288\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingTimeUnit{\"STRING_1880836771\"}, UnderlyingInstrument_108);\n    set_field(noUnderlyings_0_2, FIX::UnderlyingUnitOfMeasure{\"STRING_1977402234\"}, UnderlyingInstrument_108);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_108;\n    UnderlyingUnitOfMeasureQty_108.setString(\"16872624\");\nset_field(noUnderlyings_0_2, UnderlyingUnitOfMeasureQty_108, UnderlyingInstrument_108);\n    all_values.push_back(UnderlyingInstrument_108);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_2_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_223;\n      set_field(noUnderlyingSecurityAltID_2_1_0, FIX::UnderlyingSecurityAltID{\"STRING_1573247308\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_223);\n      set_field(noUnderlyingSecurityAltID_2_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_1067502239\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_223);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_223);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_2.addGroup(noUnderlyingSecurityAltID_2_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_2_1_1;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_224;\n      set_field(noUnderlyingSecurityAltID_2_1_1, FIX::UnderlyingSecurityAltID{\"STRING_436993166\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_224);\n      set_field(noUnderlyingSecurityAltID_2_1_1, FIX::UnderlyingSecurityAltIDSource{\"STRING_1092484975\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_224);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_224);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_2.addGroup(noUnderlyingSecurityAltID_2_1_1);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_2_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_214;\n      set_field(noUnderlyingStips_2_1_0, FIX::UnderlyingStipType{\"STRING_958243472\"}, UnderlyingStipulations_NoUnderlyingStips_214);\n      set_field(noUnderlyingStips_2_1_0, FIX::UnderlyingStipValue{\"STRING_1030884814\"}, UnderlyingStipulations_NoUnderlyingStips_214);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_214);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_2.addGroup(noUnderlyingStips_2_1_0);\n    }\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_2_1_1;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_215;\n      set_field(noUnderlyingStips_2_1_1, FIX::UnderlyingStipType{\"STRING_509114036\"}, UnderlyingStipulations_NoUnderlyingStips_215);\n      set_field(noUnderlyingStips_2_1_1, FIX::UnderlyingStipValue{\"STRING_1077331478\"}, UnderlyingStipulations_NoUnderlyingStips_215);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_215);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_2.addGroup(noUnderlyingStips_2_1_1);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_2_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_231;\n      set_field(noUndlyInstrumentParties_2_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_1739865961\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_231);\n      set_field(noUndlyInstrumentParties_2_1_0, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_231);\n      set_field(noUndlyInstrumentParties_2_1_0, FIX::UnderlyingInstrumentPartyRole{670485861}, UndlyInstrumentParties_NoUndlyInstrumentParties_231);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_231);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_2_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_464;\n        set_field(noUndlyInstrumentPartySubIDs_2_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_230887725\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_464);\n        set_field(noUndlyInstrumentPartySubIDs_2_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{1115314700}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_464);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_464);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_2_1_0.addGroup(noUndlyInstrumentPartySubIDs_2_0_2_0);\n      }\n      {\n        FIX50SP2::QuoteResponse::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_2_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_465;\n        set_field(noUndlyInstrumentPartySubIDs_2_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1306294485\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_465);\n        set_field(noUndlyInstrumentPartySubIDs_2_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{970894970}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_465);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_465);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_2_1_0.addGroup(noUndlyInstrumentPartySubIDs_2_0_2_1);\n      }\n      noUnderlyings_0_2.addGroup(noUndlyInstrumentParties_2_1_0);\n    }\n    msg.addGroup(noUnderlyings_0_2);\n  }\n  // YieldData\n  multiset<string> YieldData_23;\n  FIX::Yield Yield_23;\n  Yield_23.setString(\"99.730000\");\nset_field(msg, Yield_23, YieldData_23);\n  set_field(msg, FIX::YieldCalcDate{\"LOCALMKTDATE_769023445\"}, YieldData_23);\n  set_field(msg, FIX::YieldRedemptionDate{\"LOCALMKTDATE_968054299\"}, YieldData_23);\n  FIX::YieldRedemptionPrice YieldRedemptionPrice_23;\n  YieldRedemptionPrice_23.setString(\"20467356\");\nset_field(msg, YieldRedemptionPrice_23, YieldData_23);\n  set_field(msg, FIX::YieldRedemptionPriceType{1143007283}, YieldData_23);\n  set_field(msg, FIX::YieldType{\"STRING_COMPOUND\"}, YieldData_23);\n  all_values.push_back(YieldData_23);\n  all_compo_names.insert(\".\");\n\n  // header\n  multiset<string> header_72;\n  set_header_field(msg.getHeader(), FIX::ApplVerID{\"STRING_3\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::BeginString{\"STRING_1642692939\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::BodyLength{1573705560}, header_72);\n  set_header_field(msg.getHeader(), FIX::CstmApplVerID{\"STRING_1227347346\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::DeliverToCompID{\"STRING_1472611525\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{\"STRING_1113484379\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::DeliverToSubID{\"STRING_1494752974\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{898375185}, header_72);\n  set_header_field(msg.getHeader(), FIX::MessageEncoding{\"STRING_SHIFT_JIS\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::MsgSeqNum{1931746141}, header_72);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{\"STRING_1990860161\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{\"STRING_1238886354\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{\"STRING_742505965\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(14, 3, 5, 24, 3, 2006)}, header_72);\n  set_header_field(msg.getHeader(), FIX::PossDupFlag{false}, header_72);\n  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_72);\n  set_header_field(msg.getHeader(), FIX::SecureData{\"DATA_1172025938\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::SecureDataLen{604079422}, header_72);\n  set_header_field(msg.getHeader(), FIX::SenderCompID{\"STRING_1065011093\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::SenderLocationID{\"STRING_1483315911\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::SenderSubID{\"STRING_1373102868\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(21, 3, 36, 4, 7, 2016)}, header_72);\n  set_header_field(msg.getHeader(), FIX::TargetCompID{\"STRING_1956425798\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::TargetLocationID{\"STRING_1336447319\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::TargetSubID{\"STRING_1745579307\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::XmlData{\"DATA_1303695125\"}, header_72);\n  set_header_field(msg.getHeader(), FIX::XmlDataLen{87338857}, header_72);\n  all_values.push_back(header_72);\n  all_compo_names.insert(\".header\");\n\n\n  xml_element elt;\n  converter.fix2fixml(msg, elt);\n  BOOST_LOG_TRIVIAL(debug) << \"The resulting XML is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << elt.to_string() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n\n  BOOST_LOG_TRIVIAL(debug) << \"Quickfix XML representation is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << msg.toXML() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n  list<multiset<string>> elt_lists;\n  elt.to_list(elt_lists);\n  EXPECT_EQ(elt_lists.size(), all_values.size());\n\n  if (elt_lists.size() != all_values.size())  {\n    multiset<string> elt_compo_name;\n    elt.all_components(elt_compo_name);\n    BOOST_LOG_TRIVIAL(debug) << \"XML Elements are:\";\n    cout << \"\t[\";\n    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n    BOOST_LOG_TRIVIAL(debug) << \"FIX Components are:\"; \n    cout << \"\t[\";\n    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All FIX components\";\n  for (const auto& l : all_values) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All XML components\";\n  for (const auto& l : elt_lists) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n\n  }\n\n  for (const auto& xml_l : elt_lists) {\n    bool found = false;\n    for (const auto& l : all_values) {\n      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {\n        found = true;\n        break;\n      } // end if includes\n    } // end for all_values\n    EXPECT_TRUE(found);\n    if ( ! found) {\n      BOOST_LOG_TRIVIAL(debug) << \"[TO CHECK] This XML component was not found in FIX message\";\n      cout << \"\t ---> [\";\n      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, \" \"));      cout << \"]\" << endl << endl;\n    } // end if ! found\n  } // end for elt_lists\n}\n", "meta": {"hexsha": "23a3832dc5553d89cd752288e99cd644a229cf65", "size": 151091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/generated/fix2xml/test_fix2xml_QuoteResponse.cpp", "max_stars_repo_name": "abdelkaderamar/fix2xml", "max_stars_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T12:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T12:08:19.000Z", "max_issues_repo_path": "tools/generated/fix2xml/test_fix2xml_QuoteResponse.cpp", "max_issues_repo_name": "abdelkaderamar/fix2xml", "max_issues_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_issues_repo_licenses": ["MIT"], "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/generated/fix2xml/test_fix2xml_QuoteResponse.cpp", "max_forks_repo_name": "abdelkaderamar/fix2xml", "max_forks_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T04:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T04:11:44.000Z", "avg_line_length": 63.1123642439, "max_line_length": 174, "alphanum_fraction": 0.804343078, "num_tokens": 45318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.16313351584488725}}
{"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// File generated at Sat 27 Aug 2016 12:50:19\n\n#ifndef MSSMNoFVatMGUT_PHYSICAL_H\n#define MSSMNoFVatMGUT_PHYSICAL_H\n\n#include \"linalg2.hpp\"\n#include <Eigen/Core>\n\n#include <iosfwd>\n#include <string>\n\nnamespace flexiblesusy {\n\nstruct MSSMNoFVatMGUT_physical {\n   MSSMNoFVatMGUT_physical();\n   void clear();\n   void convert_to_hk();   ///< converts pole masses to HK convention\n   void convert_to_slha(); ///< converts pole masses to SLHA convention\n   Eigen::ArrayXd get() const; ///< returns array with all masses and mixings\n   void set(const Eigen::ArrayXd&); ///< set all masses and mixings\n   Eigen::ArrayXd get_masses() const; ///< returns array with all masses\n   void set_masses(const Eigen::ArrayXd&); ///< set all masses\n   void print(std::ostream&) const;\n\n   double MVG;\n   double MGlu;\n   double MFd;\n   double MFs;\n   double MFb;\n   double MFu;\n   double MFc;\n   double MFt;\n   double MFve;\n   double MFvm;\n   double MFvt;\n   double MFe;\n   double MFm;\n   double MFtau;\n   double MSveL;\n   double MSvmL;\n   double MSvtL;\n   Eigen::Array<double,2,1> MSd;\n   Eigen::Array<double,2,1> MSu;\n   Eigen::Array<double,2,1> MSe;\n   Eigen::Array<double,2,1> MSm;\n   Eigen::Array<double,2,1> MStau;\n   Eigen::Array<double,2,1> MSs;\n   Eigen::Array<double,2,1> MSc;\n   Eigen::Array<double,2,1> MSb;\n   Eigen::Array<double,2,1> MSt;\n   Eigen::Array<double,2,1> Mhh;\n   Eigen::Array<double,2,1> MAh;\n   Eigen::Array<double,2,1> MHpm;\n   Eigen::Array<double,4,1> MChi;\n   Eigen::Array<double,2,1> MCha;\n   double MVWm;\n   double MVP;\n   double MVZ;\n\n   Eigen::Matrix<double,2,2> ZD;\n   Eigen::Matrix<double,2,2> ZU;\n   Eigen::Matrix<double,2,2> ZE;\n   Eigen::Matrix<double,2,2> ZM;\n   Eigen::Matrix<double,2,2> ZTau;\n   Eigen::Matrix<double,2,2> ZS;\n   Eigen::Matrix<double,2,2> ZC;\n   Eigen::Matrix<double,2,2> ZB;\n   Eigen::Matrix<double,2,2> ZT;\n   Eigen::Matrix<double,2,2> ZH;\n   Eigen::Matrix<double,2,2> ZA;\n   Eigen::Matrix<double,2,2> ZP;\n   Eigen::Matrix<std::complex<double>,4,4> ZN;\n   Eigen::Matrix<std::complex<double>,2,2> UM;\n   Eigen::Matrix<std::complex<double>,2,2> UP;\n   Eigen::Matrix<double,2,2> ZZ;\n\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMNoFVatMGUT_physical&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "b7b84cd76fe4893796275e363985f918f54c3e69", "size": 3069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_physical.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/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_physical.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/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_physical.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": 30.0882352941, "max_line_length": 77, "alphanum_fraction": 0.6572173346, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.16306020192351592}}
{"text": "/*\nCopyright 2016-2017 Robotics and Biology Lab, TU Berlin. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project.\n*/ \n\n#include <ecto_pcl/ecto_pcl.hpp>\n#include <ecto_pcl/pcl_cell.hpp>\n#include <ecto_pcl/pcl_cell_with_normals.hpp>\n\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/common/common.h>\n#include <pcl/common/transforms.h>\n#include <pcl/common/io.h>\n#include <pcl/common/angles.h>\n#include <pcl/common/centroid.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/common/eigen.h>\n\n#include <pcl_conversions/pcl_conversions.h>\n\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <tf_conversions/tf_eigen.h>\n#include <tf/transform_broadcaster.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\n#include <pregrasp_msgs/GraspStrategyArray.h>\n#include <ecto_rbo_grasping/PoseSet.h>\n\n#include <Eigen/Geometry>\n\nusing namespace ecto;\n\nnamespace ecto_rbo_grasping\n{\n\ntypedef Eigen::Matrix<float, 4, 1, Eigen::DontAlign> UnalignedVector4f;\ntypedef Eigen::Matrix<float, 3, 1, Eigen::DontAlign> UnalignedVector3f;\ntypedef Eigen::Matrix<float, 2, 1, Eigen::DontAlign> UnalignedVector2f;\ntypedef Eigen::Transform<float,3,Eigen::Affine,Eigen::DontAlign> UnalignedAffine3f;\n\nstruct PushingMotions\n{\n    ecto::spore<pregrasp_msgs::GraspStrategyArrayConstPtr> pushing_pregrasp_messages_;\n    ecto::spore< ::posesets::PoseSetArrayConstPtr> pushing_manifolds_;\n\n    spore<std::vector< ::pcl::PointIndices > > clusters_;\n    spore<std::vector< ::pcl::PointIndices > > cluster_seeds_;\n    spore<std::vector< ::pcl::PointIndices > > cluster_borders_;\n\n    ros::Time last_marker_message_;\n\n    // parameters\n    //  spore<double> distance_threshold_;\n    //  spore<double> min_inlier_ratio_;\n    //  spore<double> weight_contour_;\n    //  spore<double> min_boxness_;\n    //  spore<double> max_size_;\n    //  spore<double> min_size_;\n\n    static void declare_params(ecto::tendrils& params)\n    {\n        //    params.declare<double>(\"min_inlier_ratio\", \"Minimum number of inlier points per plane.\", 0.5);\n        //    params.declare<double>(\"distance_threshold\", \"Maximum mean error a plane fit may have.\", 0.05);\n        //    params.declare<double>(\"min_boxness\", \"\", 0.8);\n        //    params.declare<double>(\"weight_contour\", \"\", 0.5);\n        //    params.declare<double>(\"max_size\", \"\", 0.24);\n        //    params.declare<double>(\"min_size\", \"\", 0.08);\n    }\n\n    static void declare_io(const tendrils& params, tendrils& inputs, tendrils& outputs)\n    {\n        inputs.declare<std::vector< ::pcl::PointIndices> >(\"clusters\", \"Clusters.\");\n        inputs.declare<std::vector< ::pcl::PointIndices> >(\"cluster_seeds\", \"Clusters.\");\n        inputs.declare<std::vector< ::pcl::PointIndices> >(\"cluster_borders\", \"Clusters.\");\n\n        outputs.declare<pregrasp_msgs::GraspStrategyArrayConstPtr>(\"pushing_pregrasp_messages\", \"All the grasps that should be used.\");\n        outputs.declare< ::posesets::PoseSetArrayConstPtr>(\"pushing_manifolds\", \"All the grasps that should be used.\");\n    }\n\n    void configure(const tendrils& params, const tendrils& inputs, const tendrils& outputs)\n    {\n        clusters_ = inputs[\"clusters\"];\n        cluster_seeds_ = inputs[\"cluster_seeds\"];\n        cluster_borders_ = inputs[\"cluster_borders\"];\n\n        pushing_pregrasp_messages_ = outputs[\"pushing_pregrasp_messages\"];\n        pushing_manifolds_ = outputs[\"pushing_manifolds\"];\n\n        last_marker_message_ = ros::Time::now();\n    }\n\n    inline void computeNormalMean(const ::pcl::PointCloud< ::pcl::Normal>& normals, const ::pcl::PointIndices& indices, Eigen::Vector3f& mean_normal)\n    {\n        mean_normal.setZero();\n        for (size_t i = 0; i < indices.indices.size(); ++i)\n            mean_normal += normals.at(indices.indices[i]).getNormalVector3fMap();\n\n        mean_normal.normalize();\n    }\n\n    template<typename Point>\n    inline float pointToLineDistance(const Point p, ::pcl::ModelCoefficientsConstPtr& line)\n    {\n        //    ::Eigen::Vector4f point(p.x, p.y, p.z, 0.0f);\n        //    ::Eigen::Vector4f line_point(line->values[0], line->values[1], line->values[2], 0.0f);\n        //    ::Eigen::Vector4f line_direction(line->values[3], line->values[4], line->values[5], 0.0f);\n        //    return ::pcl::sqrPointToLineDistance(point, line_point, line_direction);\n        return (p.x-line->values[0]) * (p.x-line->values[0]) + (p.y-line->values[1]) * (p.y-line->values[1]) + (p.z-line->values[2]) * (p.z-line->values[2]);\n    }\n\n    template<typename Point>\n    int process(const tendrils& inputs, const tendrils& outputs,\n                boost::shared_ptr<const ::pcl::PointCloud<Point> >& input,\n                boost::shared_ptr<const ::pcl::PointCloud< ::pcl::Normal> >& normals)\n    {\n        pregrasp_msgs::GraspStrategyArrayPtr push_messages(new ::pregrasp_msgs::GraspStrategyArray());\n        ::posesets::PoseSetArrayPtr pushing_manifolds(new ::posesets::PoseSetArray());\n\n        push_messages->header = pcl_conversions::fromPCL(input->header);\n\n        for (std::vector< ::pcl::PointIndices >::iterator it = clusters_->begin(); it != clusters_->end(); ++it)\n        {\n            size_t index = std::distance(clusters_->begin(), it);\n\n            if (clusters_->at(index).indices.empty() || cluster_seeds_->at(index).indices.empty() || cluster_borders_->at(index).indices.empty())\n                continue;\n\n//            ROS_INFO(\"Generating Push No. %zu.: %zu (cluster size), %zu (seed size), %zu (border size)\", index, clusters_->at(index).indices.size(), cluster_seeds_->at(index).indices.size(), cluster_borders_->at(index).indices.size());\n\n            ::pregrasp_msgs::GraspStrategy msg;\n            msg.pregrasp_configuration = pregrasp_msgs::GraspStrategy::PREGRASP_HOOK;\n            msg.strategy = pregrasp_msgs::GraspStrategy::STRATEGY_PUSH;\n\n            // start of slide\n            Eigen::Vector4f seed_centroid, border_centroid;\n            Eigen::Vector3f mean_normal(0, 0, 0);\n            ::pcl::compute3DCentroid(*input, cluster_seeds_->at(index), seed_centroid);\n            ::pcl::compute3DCentroid(*input, cluster_borders_->at(index), border_centroid);\n            computeNormalMean(*normals, cluster_seeds_->at(index), mean_normal);\n            msg.pregrasp_pose.center.pose.position.x = seed_centroid(0);\n            msg.pregrasp_pose.center.pose.position.y = seed_centroid(1);\n            msg.pregrasp_pose.center.pose.position.z = seed_centroid(2);\n            /*\n            tf::Vector3 z_axis(0, 0, -1);\n            tf::Vector3 avg_normal(mean_normal(0), mean_normal(1), mean_normal(2));\n            tf::quaternionTFToMsg(tf::shortestArcQuat(z_axis, avg_normal), msg.pregrasp_pose.center.pose.orientation);\n            */\n            Eigen::Vector3f push_direction = (border_centroid.topRows(3) - seed_centroid.topRows(3)).normalized();\n            Eigen::Vector3f approach_z = -mean_normal;\n            Eigen::Vector3f approach_x = push_direction.cross(approach_z);\n            Eigen::Matrix3f rotation;\n            rotation << approach_x, approach_z.cross(approach_x), approach_z;\n            Eigen::Quaterniond q_eigen(rotation.cast<double>());\n            tf::Quaternion q_tf;\n            tf::quaternionEigenToTF(q_eigen, q_tf);\n            tf::quaternionTFToMsg(q_tf, msg.pregrasp_pose.center.pose.orientation);\n\n            ::pcl::PointCloud<Point> tmp_cloud;\n            ::Eigen::Affine3f seed_transform(::Eigen::Translation3f(seed_centroid.topRows(3)));\n            seed_transform.rotate(::Eigen::AngleAxisf(q_eigen.cast<float>()));\n            ::pcl::transformPointCloud(*input, cluster_seeds_->at(index), tmp_cloud, seed_transform.inverse());\n            ::Eigen::Vector4f max_point, min_point;\n            ::pcl::getMinMax3D(tmp_cloud, min_point, max_point);\n            ::Eigen::Vector4f difference = max_point - min_point;\n\n            msg.pregrasp_pose.size.resize(4);\n            msg.pregrasp_pose.size[0] = difference[0];\n            msg.pregrasp_pose.size[1] = difference[1];\n            msg.pregrasp_pose.size[2] = difference[2];\n            msg.pregrasp_pose.size[3] = 0.1;\n\n            // end of slide\n            // HINT: could also be the mean of the seeds region\n            computeNormalMean(*normals, cluster_borders_->at(index), mean_normal);\n            msg.pregrasp_pose.pose.pose.position.x = border_centroid(0);\n            msg.pregrasp_pose.pose.pose.position.y = border_centroid(1);\n            msg.pregrasp_pose.pose.pose.position.z = border_centroid(2);\n\n            /*\n            avg_normal.setValue(mean_normal(0), mean_normal(1), mean_normal(2));\n            tf::quaternionTFToMsg(tf::shortestArcQuat(z_axis, avg_normal), msg.pregrasp_pose.pose.pose.orientation);\n            */\n            approach_z = -mean_normal;\n            approach_x = push_direction.cross(approach_z);\n            rotation << approach_x, approach_z.cross(approach_x), approach_z;\n            q_eigen = rotation.cast<double>();\n            tf::quaternionEigenToTF(q_eigen, q_tf);\n            tf::quaternionTFToMsg(q_tf, msg.pregrasp_pose.pose.pose.orientation);\n\n            tmp_cloud.clear();\n            ::Eigen::Affine3f border_transform(::Eigen::Translation3f(border_centroid.topRows(3)));\n            border_transform.rotate(::Eigen::AngleAxisf(q_eigen.cast<float>()));\n            ::pcl::transformPointCloud(*input, cluster_borders_->at(index), tmp_cloud, border_transform.inverse());\n            ::pcl::getMinMax3D(tmp_cloud, min_point, max_point);\n            difference = max_point - min_point;\n\n//            sensor_msgs::PointCloud2 color_msg;\n//            ::pcl::toROSMsg(tmp_cloud, color_msg);\n//            color_msg.header.frame_id = input->header.frame_id;\n//            color_msg.header.stamp = ::ros::Time::now();\n//            static ::ros::NodeHandle nh;\n//            static ::ros::Publisher debug_publisher = nh.advertise< sensor_msgs::PointCloud2 > (\"/debug_shit\", 1);\n//            debug_publisher.publish(color_msg);\n\n            msg.pregrasp_pose.image_size.resize(4);\n            msg.pregrasp_pose.image_size[0] = difference[0];\n            msg.pregrasp_pose.image_size[1] = difference[1];\n            msg.pregrasp_pose.image_size[2] = difference[2];\n            msg.pregrasp_pose.image_size[3] = 0.1;\n\n            // set object pose relative to hand\n            msg.object.center.pose = msg.object.pose.pose = msg.pregrasp_pose.center.pose;\n            msg.object.size.push_back(0.1);\n            msg.object.size.push_back(0.1);\n            msg.object.size.push_back(0.07);\n            msg.object.size.push_back(4.0);\n            msg.object.image_size.push_back(0.01);\n            msg.object.image_size.push_back(0.1);\n            msg.object.image_size.push_back(0.1);\n            msg.object.image_size.push_back(4.0);\n\n            push_messages->strategies.push_back(msg);\n\n            // add corresponding manifold\n            ::posesets::PoseSet ps(tf::Transform(q_tf, tf::Vector3(seed_centroid(0), seed_centroid(1), seed_centroid(2))));\n            ps.setPositions(tf::Vector3(difference[0], difference[1], difference[2]));\n            ps.getOrientations().add(q_tf, tf::Vector3(approach_z(0), approach_z(1), approach_z(2)));\n            pushing_manifolds->push_back(ps);\n\n            ROS_INFO(\"Push pointing from: %f, %f, %f\", msg.pregrasp_pose.center.pose.position.x, msg.pregrasp_pose.center.pose.position.y, msg.pregrasp_pose.center.pose.position.z);\n            ROS_INFO(\"                to: %f, %f, %f\", msg.pregrasp_pose.pose.pose.position.x, msg.pregrasp_pose.pose.pose.position.y, msg.pregrasp_pose.pose.pose.position.z);\n        }\n\n        (*pushing_pregrasp_messages_) = push_messages;\n        (*pushing_manifolds_) = pushing_manifolds;\n\n        return OK;\n    }\n};\n\n}\n\nECTO_CELL(ecto_rbo_grasping, ecto::pcl::PclCellWithNormals<ecto_rbo_grasping::PushingMotions>, \"PushingMotions\", \"Finding pushing motions.\");\n", "meta": {"hexsha": "fbc2a4e2c10774cab306a7c39802b0402c6eb63e", "size": 13262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ecto_rbo_grasping/src/ecto_rbo_grasping/PushingMotions.cpp", "max_stars_repo_name": "SoMa-Project/vision", "max_stars_repo_head_hexsha": "ea8199d98edc363b2be79baa7c691da3a5a6cc86", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-24T23:40:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-24T23:40:01.000Z", "max_issues_repo_path": "ecto_rbo_grasping/src/ecto_rbo_grasping/PushingMotions.cpp", "max_issues_repo_name": "SoMa-Project/vision", "max_issues_repo_head_hexsha": "ea8199d98edc363b2be79baa7c691da3a5a6cc86", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T18:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-19T15:53:43.000Z", "max_forks_repo_path": "ecto_rbo_grasping/src/ecto_rbo_grasping/PushingMotions.cpp", "max_forks_repo_name": "SoMa-Project/vision", "max_forks_repo_head_hexsha": "ea8199d98edc363b2be79baa7c691da3a5a6cc86", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.2125984252, "max_line_length": 736, "alphanum_fraction": 0.6729754185, "num_tokens": 3231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16262376119593347}}
{"text": "#include \"PCE.h\"\n#include \"GeomCommonFunctions.h\"\n#include <Gui/Application.h>\n#include <BRepBuilderAPI_GTransform.hxx>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <tchar.h>\n#include <iostream>\n#include <CompilerConfig.h>\n\nusing namespace PartDesignGui;\n\nPCETransform::PCETransform(\n\tVector3d2 surfs_,\n\tVector3d1 surf_normals_,\n\tVector3d center_,\n\tVector3d rotation_,\n\tglm::dmat4 PM_,\n\tglm::dmat4 RM_,\n\tVector3d tranform_corner_) :\n\tsurfs(surfs_),\n\tsurf_normals(surf_normals_),\n\tcenter(center_),\n\trotation(rotation_),\n\tPM(PM_),\n\tRM(RM_),\n\ttranform_corner(tranform_corner_) {\n\n};\n\nPCETransform::PCETransform()\n{\n\tindex = -1;\n}\n\nbool PCETransform::CheckWL(const int& wl_index_) const\n{\n\tfor (auto wl_rate : wl_rates)\n\t{\n\t\tif (wl_rate.wl->index == wl_index_)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid PCETransform::Clear()\n{\n\tstd::vector<WLRATE>().swap(wl_rates);\n\tcut_ends.Clear();\n\tVector3d2().swap(surfs);\n\tVector3d1().swap(surf_normals);\n}\n\nvoid PCETransform::AddNewEdges(std::vector<PCEEdge>& edges_, std::vector<int>& edge_indexes)\n{\n\tedge_indexes.clear();\n\tif (cut_ends.valid)\n\t{\n\t\tfor (const auto& end : cut_ends.ends)\n\t\t{\n\t\t\tedges_.emplace_back(PCEEdge(edges_.size(), pce_shape->index, end.cut));\n\t\t\tedge_indexes.emplace_back(edges_.back().index);\n\t\t}\n\t}\n\telse\n\t\tAddBoundingEdges(edges_, edge_indexes);\n}\n\nvoid PCETransform::AddBoundingEdges(std::vector<PCEEdge>& edges_, std::vector<int>& edge_indexes)\n{\n\tedge_indexes.clear();\n\n\tauto& offset_points = bounding_box.offset_2d;\n\tauto& origin_points = bounding_box.origin_2d;\n\n\tdouble height = wl_rates[0].wl->size[2];\n\tfor (int i = 0; i < offset_points.size(); i++)\n\t{\n\t\tconst int index_0 = i;\n\t\tconst int index_1 = (i + 1) % offset_points.size();\n\n\t\tconst Vector2d origin_s = origin_points[index_0];\n\t\tconst Vector2d origin_e = origin_points[index_1];\n\t\tconst Vector2d offset_s = offset_points[index_0];\n\t\tconst Vector2d offset_e = offset_points[index_1];\n\n\t\tPCECUT cut;\n\t\tcut.origin_s = origin_s;\n\t\tcut.origin_e = origin_e;\n\t\tcut.offset_s = offset_s;\n\t\tcut.offset_e = offset_e;\n\t\tcut.cutting_surface_normal = bounding_box.normals[i];\n\t\tcut.u_cutting_line_s = Vector3d(offset_s[0], offset_s[1], height);\n\t\tcut.u_cutting_line_e = Vector3d(offset_e[0], offset_e[1], height);\n\t\tcut.l_cutting_line_s = Vector3d(offset_s[0], offset_s[1], 0.0);\n\t\tcut.l_cutting_line_e = Vector3d(offset_e[0], offset_e[1], 0.0);\n\n\t\tcut.l_u_vector = Vector3d(0.0, 0.0, height);\n\n\t\tedges_.emplace_back(PCEEdge(edges_.size(), pce_shape->index, cut));\n\t\tedge_indexes.emplace_back(edges_.back().index);\n\t}\n}\n\n//only for collision detection\nVector2d1 PCETransform::UOffset(const Vector2d t) const\n{\n\tauto points = cut_ends.valid ? cut_ends.u_offset_2d : bounding_box.offset_2d;\n\tfor (auto& p : points)p += t;\n\treturn points;\n}\n\n//only for collision detection\nVector2d1 PCETransform::LOffset(const Vector2d t) const\n{\n\tauto points = cut_ends.valid ? cut_ends.l_offset_2d : bounding_box.offset_2d;\n\tfor (auto& p : points)p += t;\n\treturn points;\n}\n\n//only for collision detection\nVector2d1 PCETransform::UOrigin(const Vector2d t) const\n{\n\tauto points = cut_ends.valid ? cut_ends.u_origin_2d : bounding_box.origin_2d;\n\tfor (auto& p : points) p += t;\n\treturn points;\n}\n\n//only for collision detection\nVector2d1 PCETransform::LOrigin(const Vector2d t) const\n{\n\tauto points = cut_ends.valid ? cut_ends.l_origin_2d : bounding_box.origin_2d;\n\tfor (auto& p : points) p += t;\n\treturn points;\n}\n\nVector2d1 PCETransform::ULOffset(const Vector2d t) const\n{\n\tauto points = cut_ends.valid ? cut_ends.ul_offset_2d : bounding_box.offset_2d;\n\tfor (auto& p : points)p += t;\n\treturn points;\n}\n\nVector2d1 PCETransform::ULOrigin(const Vector2d t) const\n{\n\tauto points = cut_ends.valid ? cut_ends.ul_origin_2d : bounding_box.origin_2d;\n\tfor (auto& p : points)p += t;\n\treturn points;\n}\n\nPCETransform::CutEnds PCETransform::BuildEnd(const double& kerf, const HMODULE& hModule,\n\tconst Vector3d2& surfs_, Vector3d upper_normal, Vector3d lower_normal)\n{\n\t//build data structure\n\tstruct Node\n\t{\n\tpublic:\n\t\tenum { EdgeNode, SurfNode };\n\t\tenum { UpperEdge, LowerEdge };\n\n\t\tint index, style;\n\t\tstd::vector<int> neighbors;\n\t\tstd::vector<int> ends;\n\n\t\tint surface_index;\n\n\t\tbool used;\n\n\t\t//edge\n\t\tVector3d edge_s, edge_e;\n\t\tint edge_style;\n\t\tint friend_node;\n\t\tint edge_index;\n\n\t\t//surface\n\t\tVector3d1 surf_points;\n\t\tVector3d surf_normal;\n\n\t\t//EdgeNode\n\t\tNode(int index_, Vector3d s_, Vector3d e_, int edge_style_, int edge_index_, int surface_index_) :\n\t\t\tindex(index_), style(EdgeNode), edge_s(s_), edge_e(e_), edge_style(edge_style_), edge_index(edge_index_), surface_index(surface_index_)\n\t\t{\n\t\t\tfriend_node = -1;\n\t\t\tused = false;\n\t\t};\n\n\t\t//SurfNode\n\t\tNode(int index_, const Vector3d1& points_, const Vector3d& surf_normal_, int surface_index_) :\n\t\t\tindex(index_), style(SurfNode), surf_points(points_), surf_normal(surf_normal_), surface_index(surface_index_)\n\t\t{\n\t\t\tedge_style = -1;\n\t\t\tfriend_node = -1;\n\t\t\tused = false;\n\t\t};\n\n\t\tvoid PushEnd(int end)\n\t\t{\n\t\t\tif (Math::Functs::VectorIndex(ends, end) == -1) ends.emplace_back(end);\n\t\t}\n\n\t\tvoid PushEnd(std::vector<int> ints)\n\t\t{\n\t\t\tfor (auto i : ints) PushEnd(i);\n\t\t}\n\t};\n\tstruct Edge\n\t{\n\tpublic:\n\t\tint index;\n\t\tint node_0, node_1;\n\n\t\tEdge(int index_, int n_0, int n_1) : index(index_), node_0(n_0), node_1(n_1)\n\t\t{\n\t\t};\n\t};\n\tauto CheckConnecting0 = [&](const Vector3d& s, const Vector3d& e, const Vector3d1& contour)\n\t{\n\t\tfor (int i = 0; i < contour.size(); i++)\n\t\t{\n\t\t\tVector3d s_ = contour[i];\n\t\t\tVector3d e_ = contour[(i + 1) % contour.size()];\n\t\t\tbool ss = Math::Functs::IsAlmostZero(Math::Functs::GetDistance(s, s_));\n\t\t\tbool se = Math::Functs::IsAlmostZero(Math::Functs::GetDistance(s, e_));\n\t\t\tbool es = Math::Functs::IsAlmostZero(Math::Functs::GetDistance(e, s_));\n\t\t\tbool ee = Math::Functs::IsAlmostZero(Math::Functs::GetDistance(e, e_));\n\t\t\tif ((ss && ee) || (se && es)) return true;\n\t\t}\n\t\treturn false;\n\t};\n\tauto CheckConnecting1 = [&](Vector3d1& contour0, Vector3d1& contour1)\n\t{\n\t\tfor (int i = 0; i < contour0.size(); i++)\n\t\t{\n\t\t\tVector3d s = contour0[i];\n\t\t\tVector3d e = contour0[(i + 1) % contour0.size()];\n\n\t\t\tfor (int j = 0; j < contour1.size(); j++)\n\t\t\t{\n\t\t\t\tVector3d s_ = contour1[j];\n\t\t\t\tVector3d e_ = contour1[(j + 1) % contour1.size()];\n\t\t\t\tbool ss = Math::Functs::IsAlmostZero(Math::Functs::GetDistance(s, s_));\n\t\t\t\tbool se = Math::Functs::IsAlmostZero(Math::Functs::GetDistance(s, e_));\n\t\t\t\tbool es = Math::Functs::IsAlmostZero(Math::Functs::GetDistance(e, s_));\n\t\t\t\tbool ee = Math::Functs::IsAlmostZero(Math::Functs::GetDistance(e, e_));\n\t\t\t\tif ((ss && ee) || (se && es)) return true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t};\n\n\t//searching for the upper surface and the lower surface\n\tauto BuildNodes = [&](std::vector<Node>& nodes, Vector3d1& surf_normals_, PCETransform::CutEnds& cut_ends_) {\n\n\t\tbool ub(false), lb(false);\n\t\tfor (int i = 0; i < surf_normals_.size(); i++)\n\t\t{\n\t\t\tif (Math::Functs::IsAlmostZero(Math::Functs::GetAngleBetween(upper_normal, surf_normals_[i])))\n\t\t\t{\n\t\t\t\tif (ub)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Find not single surfaces which are upper surfaces...\" << std::endl;\n\t\t\t\t\tsystem(\"pause\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tcut_ends_.u_surf = surfs_[i];\n\t\t\t\tcut_ends_.u_surf_index = i;\n\n\t\t\t\tub = true;\n\t\t\t\tfor (int j = 0; j < cut_ends_.u_surf.size(); j++)\n\t\t\t\t\tnodes.emplace_back(Node(nodes.size(), cut_ends_.u_surf[j], cut_ends_.u_surf[(j + 1) % cut_ends_.u_surf.size()], Node::UpperEdge, j, i));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (Math::Functs::IsAlmostZero(Math::Functs::GetAngleBetween(lower_normal, surf_normals_[i])))\n\t\t\t\t{\n\t\t\t\t\tif (lb)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cerr << \"Find not single surfaces which are lower surfaces...\" << std::endl;\n\t\t\t\t\t\tsystem(\"pause\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t\tcut_ends_.l_surf = surfs_[i];\n\t\t\t\t\tcut_ends_.l_surf_index = i;\n\n\t\t\t\t\tlb = true;\n\t\t\t\t\tfor (int j = 0; j < cut_ends_.l_surf.size(); j++)\n\t\t\t\t\t\tnodes.emplace_back(Node(nodes.size(), cut_ends_.l_surf[j], cut_ends_.l_surf[(j + 1) % cut_ends_.l_surf.size()], Node::LowerEdge, j, i));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tnodes.emplace_back(Node(nodes.size(), surfs_[i], surf_normals_[i], i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!ub || !lb) return false;\n\t\treturn true;\n\t};\n\n\t//build edges\n\tauto BuildEdges = [&](std::vector<Node>& nodes)\n\t{\n\t\tstd::vector<Edge> edges;\n\t\tfor (auto& n : nodes)\n\t\t{\n\t\t\tfor (auto& nn : nodes)\n\t\t\t{\n\t\t\t\tif (n.index < nn.index && n.style == Node::EdgeNode && nn.style == Node::SurfNode)\n\t\t\t\t{\n\t\t\t\t\tif (CheckConnecting0(n.edge_s, n.edge_e, nn.surf_points))\n\t\t\t\t\t{\n\t\t\t\t\t\tedges.emplace_back(edges.size(), n.index, nn.index);\n\t\t\t\t\t\tn.neighbors.emplace_back(nn.index);\n\t\t\t\t\t\tnn.neighbors.emplace_back(n.index);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (n.index < nn.index && n.style == Node::SurfNode && nn.style == Node::EdgeNode)\n\t\t\t\t{\n\t\t\t\t\tif (CheckConnecting0(nn.edge_s, nn.edge_e, n.surf_points))\n\t\t\t\t\t{\n\t\t\t\t\t\tedges.emplace_back(edges.size(), n.index, nn.index);\n\t\t\t\t\t\tn.neighbors.emplace_back(nn.index);\n\t\t\t\t\t\tnn.neighbors.emplace_back(n.index);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (n.index < nn.index && n.style == Node::SurfNode && nn.style == Node::SurfNode)\n\t\t\t\t{\n\t\t\t\t\tif (CheckConnecting1(n.surf_points, nn.surf_points))\n\t\t\t\t\t{\n\t\t\t\t\t\tedges.emplace_back(edges.size(), n.index, nn.index);\n\t\t\t\t\t\tn.neighbors.emplace_back(nn.index);\n\t\t\t\t\t\tnn.neighbors.emplace_back(n.index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn edges;\n\t};\n\n\t//Note: there are challenged case I can not handle\n\t//This algorithm cannot guarantee to decompose all of surface into valid ends\n\t//multi merge\n\tauto RegionGrow = [&](std::vector<Node>& nodes, PCETransform::CutEnds& cut_ends_)\n\t{\n\t\tfor (auto& n : nodes)\n\t\t{\n\t\t\tif (n.style == Node::EdgeNode)\n\t\t\t{\n\t\t\t\tnodes[n.neighbors[0]].PushEnd(n.index);\n\t\t\t\tn.used = true;\n\t\t\t}\n\t\t}\n\n\t\twhile (true)\n\t\t{\n\t\t\tfor (auto& n : nodes)\n\t\t\t{\n\t\t\t\tif (n.style == Node::SurfNode)\n\t\t\t\t{\n\t\t\t\t\tif (n.ends.size() > 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cerr << \"Nodes' ends > 2...\" << std::endl;\n\t\t\t\t\t\tsystem(\"pause\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (n.ends.size() == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tNode& n0 = nodes[n.ends[0]];\n\t\t\t\t\t\tNode& n1 = nodes[n.ends[1]];\n\t\t\t\t\t\tif (n0.friend_node < 0)n0.friend_node = n1.index;\n\t\t\t\t\t\tif (n1.friend_node < 0)n1.friend_node = n0.index;\n\t\t\t\t\t\tn0.PushEnd(n.index);\n\t\t\t\t\t\tn1.PushEnd(n.index);\n\t\t\t\t\t\tn.used = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (n.ends.size() == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tNode& n_ = nodes[n.ends[0]];\n\t\t\t\t\t\tn_.PushEnd(n.index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool goon = false;\n\t\t\tfor (auto& n : nodes)\n\t\t\t{\n\t\t\t\tif (n.style == Node::SurfNode && n.ends.size() == 0)\n\t\t\t\t{\n\t\t\t\t\tgoon = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (n.style == Node::EdgeNode && n.friend_node < 0)\n\t\t\t\t{\n\t\t\t\t\tgoon = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!goon) break;\n\n\t\t\tfor (auto& n : nodes)\n\t\t\t{\n\t\t\t\tif (n.style == Node::SurfNode && !n.used && n.ends.size() > 0)\n\t\t\t\t{\n\t\t\t\t\tfor (auto i : n.neighbors)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!nodes[i].used && nodes[i].ends.size() < 2)\n\t\t\t\t\t\t\tnodes[i].PushEnd(n.ends);\n\t\t\t\t\t}\n\t\t\t\t\tn.used = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//valid detection\n\t\tfor (auto& n : nodes)\n\t\t{\n\t\t\tif (n.style == Node::EdgeNode && n.friend_node == -1)\n\t\t\t{\n\t\t\t\tstd::cerr << \"End computing error...: n.friend_node==-1\" << std::endl;\n\t\t\t\tsystem(\"pause\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (n.style == Node::SurfNode && n.ends.size() == 0)\n\t\t\t{\n\t\t\t\tstd::cerr << \"End computing error...:  n.ends.size()==0\" << std::endl;\n\t\t\t\tsystem(\"pause\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t//build ends\n\t\tfor (auto& n : nodes)\n\t\t{\n\t\t\tif (n.style == Node::EdgeNode && n.edge_style == Node::UpperEdge)\n\t\t\t{\n\t\t\t\tVector3d2 con_surfs;\n\t\t\t\tstd::vector<int> con_surf_indexes;\n\t\t\t\tVector3d1 con_surf_normals;\n\t\t\t\tn.PushEnd(nodes[n.friend_node].ends);\n\t\t\t\tfor (auto i : n.ends)\n\t\t\t\t{\n\t\t\t\t\tcon_surfs.emplace_back(nodes[i].surf_points);\n\t\t\t\t\tcon_surf_normals.emplace_back(nodes[i].surf_normal);\n\t\t\t\t\tcon_surf_indexes.emplace_back(nodes[i].surface_index);\n\t\t\t\t}\n\n\t\t\t\tif (con_surfs.size() != 1)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Two ends cutting....\" << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tcut_ends_.ends.emplace_back(PCEEnd(kerf, n.edge_index, n.edge_s, n.edge_e,\n\t\t\t\t\tnodes[n.friend_node].edge_s, nodes[n.friend_node].edge_e, con_surfs, con_surf_normals, con_surf_indexes));\n\t\t\t}\n\t\t}\n\t};\n\n\t//Note: this function can only handle very simple case\n\tauto ConnectContours = [](const HMODULE& hModule_, const std::vector<std::pair<Vector2d, Vector2d>>& contours)\n\t{\n\t\tVector2d1 results;\n\t\tauto line_itersection = (CGAL_2D_Intersection_Line_Line)GetProcAddress(hModule_, \"CGAL_2D_Intersection_Line_Line\");\n\t\tfor (int i = 0; i < contours.size(); i++)\n\t\t{\n\t\t\tint index_0 = i;\n\t\t\tint index_1 = (i + 1) % contours.size();\n\t\t\tVector2d inter;\n\t\t\tline_itersection(contours[index_0].first, contours[index_0].second, contours[index_1].first, contours[index_1].second, inter);\n\t\t\tresults.emplace_back(inter);\n\t\t}\n\t\treturn results;\n\t};\n\n\tPCETransform::CutEnds cut_ends_;\n\n\tcut_ends_.valid = false;\n\tVector3d1 surf_normals_;\n\tfor (const auto& surf_ : surfs_)\n\t{\n\t\tauto n = Math::Functs::ComputeNormalFromPolyline(surf_);\n\t\tMath::Functs::SetVectorLength(n, 1.0);\n\t\tsurf_normals_.emplace_back(-n[0], -n[1], -n[2]);\n\t}\n\n\t//input valid detection\n\tfor (auto& s : surfs_)\n\t\tif (s.size() < 3)\n\t\t{\n\t\t\tstd::cerr << \"Input surface is not valid...\" << std::endl;\n\t\t\tsystem(\"pause\");\n\t\t\treturn cut_ends_;\n\t\t}\n\n\tif (surfs_.size() != surf_normals_.size())\n\t{\n\t\tstd::cerr << \"Input surface and normals are not valid...\" << std::endl;\n\t\tsystem(\"pause\");\n\t\treturn cut_ends_;\n\t}\n\n\t//build nodes and edges\n\tstd::vector<Node> nodes;\n\tif (!BuildNodes(nodes, surf_normals_, cut_ends_)) return cut_ends_;\n\tstd::vector<Edge> edges = BuildEdges(nodes);\n\n\t//valid detection\n\tfor (auto& n : nodes)\n\t{\n\t\tif (n.style == Node::EdgeNode && n.neighbors.size() != 1)\n\t\t{\n\t\t\tstd::cerr << \"Edge computing error...\" << std::endl;\n\t\t\tsystem(\"pause\");\n\t\t\treturn cut_ends_;\n\t\t}\n\t\tif (n.style == Node::SurfNode && n.neighbors.size() != n.surf_points.size())\n\t\t{\n\t\t\tstd::cerr << \"Edge computing error...\" << std::endl;\n\t\t\tsystem(\"pause\");\n\t\t\treturn cut_ends_;\n\t\t}\n\t}\n\n\t//Note: there are challenged case I can not handle\n\t//This algorithm cannot guarantee to decompose all of surface into valid ends\n\t//multi merge\n\tRegionGrow(nodes, cut_ends_);\n\n\t//sort ends\n\tauto SortEnd = [](PCEEnd& end0, PCEEnd& end1) { return  end0.index < end1.index; };\n\tstd::sort(cut_ends_.ends.begin(), cut_ends_.ends.end(), SortEnd);\n\n\t//kerf offset\n\tauto check_orientation = (CGAL_2D_Polygon_Is_Clockwise_Oriented)GetProcAddress(hModule, \"CGAL_2D_Polygon_Is_Clockwise_Oriented\");\n\tauto PolyOffset = (CGAL_2D_Polygon_One_Offsets)GetProcAddress(hModule, \"CGAL_2D_Polygon_One_Offsets\");\n\tauto PolyUnion = (CGAL_2D_Two_Polygons_Union)GetProcAddress(hModule, \"CGAL_2D_Two_Polygons_Union\");\n\n\t//u_origin_2d  l_origin_2d\n\tfor (auto p : cut_ends_.u_surf) cut_ends_.u_origin_2d.emplace_back(p.x, p.y);\n\tfor (auto p : cut_ends_.l_surf) cut_ends_.l_origin_2d.emplace_back(p.x, p.y);\n\n\t//ul_origin_2d\n\tVector2d2 polygons;\n\tpolygons.clear();\n\tPolyUnion(cut_ends_.u_origin_2d, cut_ends_.l_origin_2d, polygons);\n\tcut_ends_.ul_origin_2d = polygons[0];\n\n\t//u_offset_2d\n\tstd::vector<std::pair<Vector2d, Vector2d>> contours;\n\tfor (auto& end : cut_ends_.ends)\n\t{\n\t\tcontours.emplace_back(Vector2d(end.cut.u_cutting_line_s[0], end.cut.u_cutting_line_s[1]),\n\t\t\tVector2d(end.cut.u_cutting_line_e[0], end.cut.u_cutting_line_e[1]));\n\t}\n\tcut_ends_.u_offset_2d = ConnectContours(hModule, contours);\n\n\t//l_offset_2d\n\tcontours.clear();\n\tfor (auto& end : cut_ends_.ends)\n\t{\n\t\tcontours.emplace_back(Vector2d(end.cut.l_cutting_line_s[0], end.cut.l_cutting_line_s[1]),\n\t\t\tVector2d(end.cut.l_cutting_line_e[0], end.cut.l_cutting_line_e[1]));\n\t}\n\tcut_ends_.l_offset_2d = ConnectContours(hModule, contours);\n\n\t//valid detection\n\tif (cut_ends_.u_offset_2d.size() != cut_ends_.l_offset_2d.size())\n\t{\n\t\tstd::cerr << \"if (u_offset_2d.size() != l_offset_2d.size())\" << std::endl;\n\t\tsystem(\"pause\");\n\t\treturn cut_ends_;\n\t}\n\n\t//ul_offset_2d\n\tpolygons.clear();\n\tPolyUnion(cut_ends_.u_offset_2d, cut_ends_.l_offset_2d, polygons);\n\tcut_ends_.ul_offset_2d = polygons[0];\n\n\tcut_ends_.ul_origin_2d=Math::Functs::Polygon_Clear(cut_ends_.ul_origin_2d, CompilerConfig::Instance().GetAngleMatchError(), CompilerConfig::Instance().GetPartMatchError());\n\tcut_ends_.ul_offset_2d=Math::Functs::Polygon_Clear(cut_ends_.ul_offset_2d, CompilerConfig::Instance().GetAngleMatchError(), CompilerConfig::Instance().GetPartMatchError());\n\n\tcut_ends_.valid = true;\n\treturn cut_ends_;\n}\n\n\nbool PCETransform::BuildEnd(const double& kerf, const HMODULE& hModule, Vector3d upper_normal, Vector3d lower_normal)\n{\n\tcut_ends = BuildEnd(kerf, hModule, surfs, upper_normal, lower_normal);\n\treturn cut_ends.valid;\n}\n\n\nbool PCETransform::BuildBoundingBox(const double& kerf, const HMODULE& hModule)\n{\n\tauto GetBoundingBox_2D = [](const Vector2d2& points, double kerf_ = 0.0)\n\t{\n\t\tVector2d corner_0, corner_2;\n\t\tMath::Functs::GetBoundingBox(points, corner_0, corner_2);\n\t\tVector2d1 box;\n\t\tbox.emplace_back(Vector2d(corner_0[0] - kerf_ / 2.0, corner_0[1] - kerf_ / 2.0));\n\t\tbox.emplace_back(Vector2d(corner_2[0] + kerf_ / 2.0, corner_0[1] - kerf_ / 2.0));\n\t\tbox.emplace_back(Vector2d(corner_2[0] + kerf_ / 2.0, corner_2[1] + kerf_ / 2.0));\n\t\tbox.emplace_back(Vector2d(corner_0[0] - kerf_ / 2.0, corner_2[1] + kerf_ / 2.0));\n\t\treturn box;\n\t};\n\n\tVector2d2 surfs_2d = Math::Functs::Vector3d2d(surfs);\n\n\tbounding_box.origin_2d = GetBoundingBox_2D(surfs_2d);\n\tbounding_box.offset_2d = GetBoundingBox_2D(surfs_2d, kerf);\n\tbounding_box.center_2d = (bounding_box.origin_2d[0] + bounding_box.origin_2d[2]) / 2.0;\n\n\tbounding_box.normals.emplace_back(Vector3d(0.0, -1.0, 0.0));\n\tbounding_box.normals.emplace_back(Vector3d(1.0, 0.0, 0.0));\n\tbounding_box.normals.emplace_back(Vector3d(0.0, 1.0, 0.0));\n\tbounding_box.normals.emplace_back(Vector3d(-1.0, 0.0, 0.0));\n\n\treturn true;\n}\n\n", "meta": {"hexsha": "edae174b59d191842ef152879ab9d87239a0f944", "size": 17635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gui/PCE_transform.cpp", "max_stars_repo_name": "haisenzhao/CarpentryCompiler", "max_stars_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-06T09:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T12:58:09.000Z", "max_issues_repo_path": "Gui/PCE_transform.cpp", "max_issues_repo_name": "haisenzhao/CarpentryCompiler", "max_issues_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "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": "Gui/PCE_transform.cpp", "max_forks_repo_name": "haisenzhao/CarpentryCompiler", "max_forks_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-18T00:09:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T04:40:47.000Z", "avg_line_length": 28.216, "max_line_length": 173, "alphanum_fraction": 0.6700878934, "num_tokens": 5569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1626237591339528}}
{"text": "#ifndef _RYSQ_ERI_IMPL_HPP_\n#define _RYSQ_ERI_IMPL_HPP_\n\n#include <boost/mpl/int.hpp>\n#include <boost/utility/enable_if.hpp>\n\n#include <rysq/eri.hpp>\n\n#include \"quartet.hpp\"\n#include \"quadrature.h\"\n#include \"normalize.h\"\n#include \"util.h\"\n#include \"kernels/functor.hpp\"\n#include \"eri-eval.hpp\"\n\n#include \"cxx/utility/permute.hpp\"\n\nnamespace mpl = boost::mpl;\nnamespace meta = rysq::meta;\n\n\nstruct rysq::Eri::Impl {\n    virtual ~Impl() {}\n    virtual void operator()(const Quartet<Center> &centers,\n\t\t\t    double *I, const Parameters &parameters) = 0;\n    template<type A, type B, type C, type D>\n    static Impl* instance(const Quartet<Shell> &shells);\n};\n\nnamespace rysq {\n    namespace eri {\n\n\n\ttemplate<class T, class Enable = void>\n\tstruct Kernel;\n\n\t// template <type A_, type B_, type C_, type D_>\n\t// struct Kernel<meta::braket<A_,B_,C_,D_>,\n\t// \t      typename boost::disable_if<kernels::braket<A_,B_,C_,D_> >::type>\n\t// {\n\t//     static const bool value = false;\n\t// };\n\n\ttemplate<class  braket, class enable = void>\n\tstruct enable_if_specialized {};\n\n\ttemplate <type A_, type B_, type C_, type D_>\n\tstruct enable_if_specialized<meta::braket<A_,B_,C_,D_>,\n\t\t\t\t     typename \n\t\t\t\t     boost::enable_if<kernels::braket<A_,B_,C_,D_>\n\t\t\t\t\t\t      >::type> {\n\t    typedef void type;\n\t};\n\n\ttemplate <type A_, type B_, type C_, type D_>\n\tstruct Kernel<meta::braket<A_,B_,C_,D_>, /*void*/\n\t\t      typename enable_if_specialized<\n\t\t\t  typename meta::sorted<A_,B_,C_,D_>::braket>:: type>\n\t: Eri::Impl {\n\t    static const bool value = true;\n\t    // typedef meta::braket<A_,B_,C_,D_>::braket braket;\n\t    typedef typename meta::sorted<A_,B_,C_,D_>::braket braket;\n\t    static const int transpose = meta::sorted<A_,B_,C_,D_>::value;\n\n\t    const Quartet<Shell> quartet;\n\n\t    Kernel(const Quartet<Shell> &quartet)\n\t\t: quartet(quartet.transposed(transpose)) { }\n\n\t    \n\t    static Impl* instance(const Quartet<Shell> &quartet) {\n\t\treturn new Kernel(quartet);\n\t    }\n\n\n\t//     static void eval(const Quartet<Shell> &quartet,\n\t// \t\t     const Quartet<Center> &centers,\n\t// \t\t     const density_set &D6,\n\t// \t\t     const fock_set &F6,\n\t// \t\t     const Parameters &parameters) {\n\t// \tdouble I[braket::size] __attribute__ ((aligned(16))) = { 0.0 };\n\t// \tdouble scale = 1.0;\n\t// \tdouble cutoff = parameters.cutoff/(5e1*SQRT_4PI5);\n\t// \teri::eval(quartet, centers, I, scale, cutoff);\n\t// \tParameters p = parameters;\n\t// \tp.scale *= SQRT_4PI5;\n\t// \tfock::eval<braket>(D6, F6, I, p);\n\t//     }\n\t// };\n\n\t    void operator()(const Quartet<Center> &centers,\n\t\t\t    double *I, const Parameters &p) {\n\t\tdouble scale = SQRT_4PI5*p.scale;\n\t\tdouble cutoff = p.cutoff/(5e1*scale);\n\t\teval(quartet, centers, I, scale, cutoff);\n\t    }\n\n\t    static void eval(const Quartet<Shell> &quartet,\n\t\t\t     const Quartet<Center> &centers,\n\t\t\t     double *I, double scale, double cutoff) {\n\t\tconst double *ri, *rj, *rk, *rl;\n\t\tutil::unpack(centers, ri, rj, rk, rl);\n\t\tcxx::utility::permute(ri, rj, rk, rl, quartet.shuffle_mask);\n\t\teri::eval<braket>(quartet, ri, rj, rk, rl, I, scale, cutoff);\n\t    }\n\n\t};\n\n\ttemplate<class braket, class Enable>\n\tstruct Kernel {\n\t    static const bool value = false;\n\t    static Eri::Impl* instance(const Quartet<Shell> &quartet) {\n\t\ttypedef typename braket::A A;\n\t\ttypedef typename braket::B B;\n\t\ttypedef typename braket::C C;\n\t\ttypedef typename braket::D D;\n\n\t\ttypedef typename braket::bra bra;\n\t\ttypedef typename braket::ket ket;\n\t\ttypedef mpl::int_<(braket::L)/2+1> N;\n\n\t\ttypedef mpl::bool_<A::L == 0 && B::L != 0> t0;\n\t\ttypedef mpl::bool_<C::L == 0 && D::L != 0> t1;\n\t\ttypedef mpl::bool_<bra::L < ket::L && bra::L == 0> t01;\n\n\t\t// typedef mpl::bool_<A::value < B::value> t0;\n\t\t// typedef mpl::bool_<C::value < D::value> t1;\n\t\t// typedef mpl::bool_<((A::value == C::value && B::value < D::value) ||\n\t\t// \t\t    (A::value < C::value))> t01;\n\n\t\ttypedef meta::state<B::type, A::type> BA_;\n\t\ttypedef meta::state<A::type, B::type> AB_;\n\t\ttypedef typename mpl::if_<t0, BA_, AB_>::type bra_;\n\n\t\ttypedef meta::state<D::type, C::type> DC_;\n\t\ttypedef meta::state<C::type, D::type> CD_;\n\t\ttypedef typename mpl::if_<t1, DC_, CD_>::type ket_;\n\n\t\ttypedef typename mpl::if_<t01, ket_, bra_>::type kBra;\n\n\t\tint transpose = Transpose::mask(t0::value, t1::value, t01::value);\n\t\t//if (braket::L < 5)std::cout << A::type << B::type << C::type  << D::type << \"\\n\";\n\t\treturn Kernel<kBra,N>::instance(quartet.transposed(transpose));\n\t    }\n\t};\n\n    \n\ttemplate<type A, type B, int N>\n\tstruct Kernel<meta::state<A,B>, mpl::int_<N> >\n\t    : Eri::Impl, Quadrature::Transform {\n\n\t    typedef meta::state<A,B> bra;\n\n\t    const Quartet<Shell> quartet;\n\t    Quadrature::Primitives primitives;\t    \n\t    Parameters parameters;\n\t    double scale, *eri;\n\n\t    Kernel(const Quartet<Shell> &quartet)\n\t\t: quartet(quartet),\n\t\t  primitives(this->quartet) {\n\t    }\n\n\t    static Eri::Impl* instance(const Quartet<Shell> &quartet) {\n\t\treturn new Kernel(quartet);\n\t    }\n\n\t    void operator()(const Quartet<Center> &centers,\n\t\t\t    double *eri, const Parameters &parameters) {\n\t\tthis->eri = eri;\n\t\tthis->scale = parameters.scale*SQRT_4PI5;\n\t\t double scale_ = 1;\n\t\tdouble cutoff_ = parameters.cutoff/(5e1*scale);\n\t\tQuadrature::eval<bra,N>(quartet, centers, scale_, cutoff_,\n\t\t\t\t\tprimitives, *this);\n\t    }\n\n\t    struct Transform {\n\t\tstatic const int size = bra::size;\n\t\tdouble  scale, *eri;\n\t\tTransform(double scale,double *eri) : scale(scale), eri(eri) {}\n\t\tvoid operator()(int k, int l, int kl, const double *eri) {\n\t\t    // std::cout << kl << std::endl;\n\t\t    double *eri_ = this->eri + kl*size;\n\t\t    for (int i = 0; i < size; ++i) {\n\t\t        eri_[i] = scale*eri[i];\n\t\t\t// std::cout << eri[i] << std::endl;\n\t\t    }\n\t\t}\n\t    };\n\n\t    void operator()(const Quadrature::Primitives &primitives) {\n\t\tint K = primitives.K;\n \t\tif (K == 0) return;\n\t\tconst Shell &c = quartet[2];\n\t\tconst Shell &d = quartet[3];\n\t\tTransform transform( scale,this->eri);\n\t\t// throw;\n\t\tQuadrature::apply<bra,N>(c, d, primitives, transform);\n\t    }\n\t    \n\n\t};\n\n\t// template <type A, type B, int N>\n\t// struct Kernel<meta::state<A,B>,  mpl::int_< N> >\n\t// : rysq::Eri::Impl, Quadrature::Transform {\n\n\t// };\n\n    }\n}\n\n\nnamespace rysq {\n\n    template<type A, type B, type C, type D>\n    inline Eri::Impl* Eri::Impl::instance(const Quartet<Shell> &quartet) {\n\ttypedef meta::braket<A,B,C,D> braket;\n\treturn eri::Kernel<braket>::instance(quartet);\n    }\n\n}\n\n\n#endif /* _RYSQ_ERI_HPP_ */\n\n", "meta": {"hexsha": "26746024d584b1d1098dce0b4f25b487f78117bf", "size": 6408, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/rysq/src/eri-impl.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/eri-impl.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/eri-impl.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": 28.1052631579, "max_line_length": 85, "alphanum_fraction": 0.6276529338, "num_tokens": 2015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16262375785516855}}
{"text": "/*\n * Copyright (c) 2021 Elastos Foundation\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 \"Mnemonic.h\"\n#include <utf8proc.h>\n\n#include <Common/hash.h>\n#include <Common/ErrorChecker.h>\n#include <Common/uint256.h>\n#include <Common/Utils.h>\n\n#include <sstream>\n#include <boost/algorithm/string.hpp>\n\nnamespace fs = boost::filesystem;\n\nnamespace Elastos {\n    namespace ElaWallet {\n\n        Mnemonic::Mnemonic() {\n        }\n\n        WordList Mnemonic::Create(const bytes_t &entropy, const Dictionary &lexicon) {\n            if ((entropy.size() % MnemonicSeedMultiple) != 0)\n                return {};\n\n            const size_t entropyBits = (entropy.size() * ByteBits);\n            const size_t checkBits = (entropyBits / EntropyBitDivisor);\n            const size_t totalBits = (entropyBits + checkBits);\n            const size_t wordCount = (totalBits / BitsPerWord);\n\n            if ((totalBits % BitsPerWord) != 0 || (wordCount % MnemonicWordMultiple) != 0)\n                return {};\n\n            bytes_t data = entropy + sha256(entropy);\n\n            size_t bit = 0;\n            WordList words;\n\n            for (size_t word = 0; word < wordCount; word++) {\n                size_t position = 0;\n                for (size_t loop = 0; loop < BitsPerWord; loop++) {\n                    bit = (word * BitsPerWord + loop);\n                    position <<= 1;\n\n                    const auto byte = bit / ByteBits;\n\n                    if ((data[byte] & Bip39Shift(bit)) > 0)\n                        position++;\n                }\n\n                if (position >= DictionarySize)\n                    return {};\n                words.push_back(lexicon[position]);\n            }\n\n            if (words.size() != ((bit + 1) / BitsPerWord))\n                return {};\n\n            return words;\n        }\n\n        bytes_t Mnemonic::Entropy(const WordList &words, const Dictionary &lexicon) {\n            const auto wordCount = words.size();\n            if ((wordCount % MnemonicWordMultiple) != 0)\n                return {};\n\n            const auto totalBits = BitsPerWord * wordCount;\n            const auto checkBits = totalBits / (EntropyBitDivisor + 1);\n            const auto entropyBits = totalBits - checkBits;\n\n            if ((entropyBits % ByteBits) != 0)\n                return {};\n\n            size_t bit = 0;\n            bytes_t data((totalBits + ByteBits - 1) / ByteBits, 0);\n\n            for (const auto& word: words) {\n                const auto position = FindPosition(lexicon, word);\n                if (position == -1)\n                    return {};\n\n                for (size_t loop = 0; loop < BitsPerWord; loop++, bit++)\n                {\n                    if (position & (1 << (BitsPerWord - loop - 1)))\n                    {\n                        const auto byte = bit / ByteBits;\n                        data[byte] |= Bip39Shift(bit);\n                    }\n                }\n            }\n\n            data.resize(entropyBits / ByteBits);\n            return data;\n        }\n\n        bool Mnemonic::Validate(const WordList &words, const Dictionary &lexicon) {\n            bytes_t entropy = Entropy(words, lexicon);\n            if (entropy.empty())\n                return false;\n\n            const auto mnemonic = Create(entropy, lexicon);\n            return std::equal(mnemonic.begin(), mnemonic.end(), words.begin());\n        }\n\n        bool Mnemonic::Validate(const WordList &words, const DictionaryMap &lexicons) {\n            for (const auto &lexicon : lexicons) {\n                if (Validate(words, *lexicon.second))\n                    return true;\n            }\n\n            return false;\n        }\n\n        std::string Mnemonic::Create(const std::string &language, WordCount wordCount) {\n            std::string languageLowerCase = language;\n            size_t entropyBits = 0;\n\n            switch (wordCount) {\n                case WORDS_12: entropyBits = 128; break;\n                case WORDS_15: entropyBits = 160; break;\n                case WORDS_18: entropyBits = 192; break;\n                case WORDS_21: entropyBits = 224; break;\n                case WORDS_24: entropyBits = 256; break;\n                default:\n                    ErrorChecker::ThrowParamException(Error::InvalidMnemonicWordCount, \"invalid mnemonic word count\");\n            }\n\n            std::transform(languageLowerCase.begin(), languageLowerCase.end(), languageLowerCase.begin(), ::tolower);\n            bytes_t entropy = Utils::GetRandom(entropyBits / 8);\n\n            auto it = Language::All.find(languageLowerCase);\n            if (it == Language::All.end())\n                ErrorChecker::ThrowParamException(Error::InvalidArgument, \"invalid mnemonic language\");\n\n            WordList words = Create(entropy, *it->second);\n            return boost::algorithm::join(words, \" \");\n        }\n\n        bytes_t Mnemonic::Entropy(const std::string &mnemonic, const Dictionary &lexicon) {\n            utf8proc_uint8_t *mnemonicTmp = utf8proc_NFKD((const utf8proc_uint8_t *)mnemonic.c_str());\n            std::string mnemonicFixed((char *)mnemonicTmp);\n            free(mnemonicTmp);\n\n            WordList words;\n            boost::algorithm::split(words, mnemonicFixed, boost::is_any_of(\" \\n\\r\\t\"), boost::token_compress_on);\n            words.erase(std::remove(words.begin(), words.end(), \"\"), words.end());\n\n            return Entropy(words, lexicon);\n        }\n\n        bool Mnemonic::Validate(const std::string &mnemonic) {\n            utf8proc_uint8_t *mnemonicTmp = utf8proc_NFKD((const utf8proc_uint8_t *)mnemonic.c_str());\n            std::string mnemonicFixed((char *)mnemonicTmp);\n            free(mnemonicTmp);\n\n            WordList words;\n            boost::algorithm::split(words, mnemonicFixed, boost::is_any_of(\" \\n\\r\\t\"), boost::token_compress_on);\n            words.erase(std::remove(words.begin(), words.end(), \"\"), words.end());\n\n            return Validate(words);\n        }\n\n        uint512 Mnemonic::DeriveSeed(const std::string &mnemonic, const std::string &passphrase) {\n            utf8proc_uint8_t *mnemonicTmp = utf8proc_NFKD((const utf8proc_uint8_t *)mnemonic.c_str());\n            std::string mnemonicFixed((char *)mnemonicTmp);\n            free(mnemonicTmp);\n\n            utf8proc_uint8_t *passphraseTmp = utf8proc_NFKD((const utf8proc_uint8_t *)passphrase.c_str());\n            std::string passphraseFixed((char *)passphraseTmp);\n            free(passphraseTmp);\n\n            WordList words;\n            boost::algorithm::split(words, mnemonicFixed, boost::is_any_of(\" \\n\\r\\t\"), boost::token_compress_on);\n            words.erase(std::remove(words.begin(), words.end(), \"\"), words.end());\n\n            ErrorChecker::CheckLogic(!Validate(words), Error::Mnemonic, \"invalid mnemonic\");\n\n            std::string sentence = boost::algorithm::join(words, \" \");\n            std::string salt = \"mnemonic\" + passphraseFixed;\n\n            return PBKDF2(bytes_t(sentence.data(), sentence.size()), bytes_t(salt.data(), salt.size()), 2048);\n        }\n\n        uint512 Mnemonic::PBKDF2(const bytes_t &pw, const bytes_t &salt, unsigned int rounds) {\n            bytes_t s(salt.size() + sizeof(uint32_t));\n            uint32_t i, j;\n            uint512 key;\n            size_t length, keyLen = key.size();\n            bytes_t U, T, k;\n\n            assert(rounds > 0);\n\n            memcpy(s.data(), salt.data(), salt.size());\n\n            for (i = 0; keyLen > 0; i++) {\n                s[salt.size() + 0] = (uint8_t)(((i + 1) >> 24) & 0xff);\n                s[salt.size() + 1] = (uint8_t)(((i + 1) >> 16) & 0xff);\n                s[salt.size() + 2] = (uint8_t)(((i + 1) >> 8) & 0xff);\n                s[salt.size() + 3] = (uint8_t)((i + 1) & 0xff);\n\n                U = hmac_sha512(pw, s); // U1 = hmac_hash(pw, salt || be32(i))\n                T = U;\n\n                for (unsigned int r = 1; r < rounds; r++) {\n                    U = hmac_sha512(pw, U); // Urounds = hmac_hash(pw, Urounds-1)\n                    for (j = 0; j < T.size(); j++) T[j] ^= U[j]; // Ti = U1 ^ U2 ^ ... ^ Urounds\n                }\n\n                // dk = T1 || T2 || ... || Tdklen/hlen\n                length = keyLen < T.size() ? keyLen : T.size();\n                k += T;\n                keyLen -= length;\n            }\n\n            key = uint512(k);\n\n            s.clean();\n            U.clean();\n            T.clean();\n            k.clean();\n\n            return key;\n        }\n\n    }\n}", "meta": {"hexsha": "286fbb0f5e788e0db5a524abf6a885c06b1b54ad", "size": 9431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SDK/WalletCore/Mnemonic.cpp", "max_stars_repo_name": "heropan/Elastos.ELA.SPV.Cpp", "max_stars_repo_head_hexsha": "9b7fe0de47d3213ed175e28e20905120bfb80a23", "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": "SDK/WalletCore/Mnemonic.cpp", "max_issues_repo_name": "heropan/Elastos.ELA.SPV.Cpp", "max_issues_repo_head_hexsha": "9b7fe0de47d3213ed175e28e20905120bfb80a23", "max_issues_repo_licenses": ["MIT"], "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/WalletCore/Mnemonic.cpp", "max_forks_repo_name": "heropan/Elastos.ELA.SPV.Cpp", "max_forks_repo_head_hexsha": "9b7fe0de47d3213ed175e28e20905120bfb80a23", "max_forks_repo_licenses": ["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.337398374, "max_line_length": 118, "alphanum_fraction": 0.5530696639, "num_tokens": 2169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.16251044160045575}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2019, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, 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#include \"common.hpp\"\n\n#include <boost/geometry/algorithms/distance.hpp>\n\nint test_main(int, char*[])\n{\n    geom g;\n\n    bg::distance(g.pt, g.pt, bg::strategy::distance::pythagoras<>());\n    bg::distance(g.pt, g.pt, bg::strategy::distance::haversine<>());\n    bg::distance(g.pt, g.pt, bg::strategy::distance::geographic<>());\n    bg::distance(g.pt, g.mpt, bg::strategy::distance::pythagoras<>());\n    bg::distance(g.pt, g.mpt, bg::strategy::distance::haversine<>());\n    bg::distance(g.pt, g.mpt, bg::strategy::distance::geographic<>());\n    bg::distance(g.mpt, g.mpt, bg::strategy::distance::pythagoras<>());\n    bg::distance(g.mpt, g.mpt, bg::strategy::distance::haversine<>());\n    bg::distance(g.mpt, g.mpt, bg::strategy::distance::geographic<>());\n    bg::distance(g.pt, g.ls, bg::strategy::distance::projected_point<>());\n    bg::distance(g.pt, g.ls, bg::strategy::distance::cross_track<>());\n    bg::distance(g.pt, g.ls, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.pt, g.mls, bg::strategy::distance::projected_point<>());\n    bg::distance(g.pt, g.mls, bg::strategy::distance::cross_track<>());\n    bg::distance(g.pt, g.mls, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mpt, g.ls, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mpt, g.ls, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mpt, g.ls, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mpt, g.mls, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mpt, g.mls, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mpt, g.mls, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.ls, g.ls, bg::strategy::distance::projected_point<>());\n    bg::distance(g.ls, g.ls, bg::strategy::distance::cross_track<>());\n    bg::distance(g.ls, g.ls, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.ls, g.mls, bg::strategy::distance::projected_point<>());\n    bg::distance(g.ls, g.mls, bg::strategy::distance::cross_track<>());\n    bg::distance(g.ls, g.mls, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mls, g.mls, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mls, g.mls, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mls, g.mls, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.pt, g.r, bg::strategy::distance::projected_point<>());\n    bg::distance(g.pt, g.r, bg::strategy::distance::cross_track<>());\n    bg::distance(g.pt, g.r, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.pt, g.po, bg::strategy::distance::projected_point<>());\n    bg::distance(g.pt, g.po, bg::strategy::distance::cross_track<>());\n    bg::distance(g.pt, g.po, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.pt, g.mpo, bg::strategy::distance::projected_point<>());\n    bg::distance(g.pt, g.mpo, bg::strategy::distance::cross_track<>());\n    bg::distance(g.pt, g.mpo, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mpt, g.r, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mpt, g.r, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mpt, g.r, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mpt, g.po, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mpt, g.po, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mpt, g.po, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mpt, g.mpo, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mpt, g.mpo, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mpt, g.mpo, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.ls, g.r, bg::strategy::distance::projected_point<>());\n    bg::distance(g.ls, g.r, bg::strategy::distance::cross_track<>());\n    bg::distance(g.ls, g.r, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.ls, g.po, bg::strategy::distance::projected_point<>());\n    bg::distance(g.ls, g.po, bg::strategy::distance::cross_track<>());\n    bg::distance(g.ls, g.po, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.ls, g.mpo, bg::strategy::distance::projected_point<>());\n    bg::distance(g.ls, g.mpo, bg::strategy::distance::cross_track<>());\n    bg::distance(g.ls, g.mpo, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mls, g.r, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mls, g.r, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mls, g.r, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mls, g.po, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mls, g.po, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mls, g.po, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mls, g.mpo, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mls, g.mpo, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mls, g.mpo, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.r, g.r, bg::strategy::distance::projected_point<>());\n    bg::distance(g.r, g.r, bg::strategy::distance::cross_track<>());\n    bg::distance(g.r, g.r, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.r, g.po, bg::strategy::distance::projected_point<>());\n    bg::distance(g.r, g.po, bg::strategy::distance::cross_track<>());\n    bg::distance(g.r, g.po, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.r, g.mpo, bg::strategy::distance::projected_point<>());\n    bg::distance(g.r, g.mpo, bg::strategy::distance::cross_track<>());\n    bg::distance(g.r, g.mpo, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.po, g.r, bg::strategy::distance::projected_point<>());\n    bg::distance(g.po, g.r, bg::strategy::distance::cross_track<>());\n    bg::distance(g.po, g.r, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.po, g.po, bg::strategy::distance::projected_point<>());\n    bg::distance(g.po, g.po, bg::strategy::distance::cross_track<>());\n    bg::distance(g.po, g.po, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.po, g.mpo, bg::strategy::distance::projected_point<>());\n    bg::distance(g.po, g.mpo, bg::strategy::distance::cross_track<>());\n    bg::distance(g.po, g.mpo, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mpo, g.r, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mpo, g.r, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mpo, g.r, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mpo, g.po, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mpo, g.po, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mpo, g.po, bg::strategy::distance::geographic_cross_track<>());\n    bg::distance(g.mpo, g.mpo, bg::strategy::distance::projected_point<>());\n    bg::distance(g.mpo, g.mpo, bg::strategy::distance::cross_track<>());\n    bg::distance(g.mpo, g.mpo, bg::strategy::distance::geographic_cross_track<>());\n\n    return 0;\n}\n", "meta": {"hexsha": "8bd03a44ceec3b87592081a18355ba4327fe9b5e", "size": 7440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/geometry/test/cs_undefined/distance.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/geometry/test/cs_undefined/distance.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/geometry/test/cs_undefined/distance.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": 65.2631578947, "max_line_length": 83, "alphanum_fraction": 0.6602150538, "num_tokens": 2123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16246246900997285}}
{"text": "#pragma once\n\n#include <memory>\n#include <utility>\n\n#include <boost/operators.hpp>\n\n#include <elle/attribute.hh>\n#include <elle/operator.hh>\n#include <elle/serialization.hh>\n\n#include <elle/cryptography/fwd.hh>\n#include <elle/cryptography/types.hh>\n#include <elle/cryptography/Oneway.hh>\n#include <elle/cryptography/Cipher.hh>\n#if defined(ELLE_CRYPTOGRAPHY_ROTATION)\n# include <elle/cryptography/rsa/Seed.hh>\n#endif\n#include <elle/cryptography/rsa/Padding.hh>\n#include <elle/cryptography/rsa/defaults.hh>\n\nnamespace elle\n{\n  namespace cryptography\n  {\n    namespace rsa\n    {\n      /// Represent a public key in the RSA asymmetric cryptosystem.\n      class PublicKey\n        : public elle::Printable\n        , public std::enable_shared_from_this<PublicKey>\n        , private boost::totally_ordered<PublicKey>\n      {\n      /*-------------.\n      | Construction |\n      `-------------*/\n      public:\n        /// Construct a public key out of its private counterpart.\n        explicit\n        PublicKey(PrivateKey const& k);\n        /// Construct a public key based on the given EVP_PKEY key whose\n        /// ownership is transferred.\n        explicit\n        PublicKey(::EVP_PKEY* key);\n        /// Construct a public key based on the given RSA key whose\n        /// ownership is transferred to the public key.\n        explicit\n        PublicKey(::RSA* rsa);\n        PublicKey(PublicKey const& other);\n        PublicKey(PublicKey&& other);\n        virtual\n        ~PublicKey() = default;\n\n        /*--------.\n        | Methods |\n        `--------*/\n      private:\n        /// Check that the key is valid.\n        void\n        _check() const;\n      public:\n        /// Encrypt the plain text and return the ciphered text in an envelope.\n        virtual\n        elle::Buffer\n        seal(elle::ConstWeakBuffer const& plain,\n             Cipher const cipher = defaults::envelope_cipher,\n             Mode const mode = defaults::envelope_mode) const;\n        /// Encrypt the stream-based plain text and seal it in an envelope.\n        void\n        seal(std::istream& plain,\n             std::ostream& code,\n             Cipher const cipher = defaults::envelope_cipher,\n             Mode const mode = defaults::envelope_mode) const;\n        /// Encrypt a plain text using the raw public key.\n        ///\n        /// WARNING: This method cannot be used to encrypt large amount of\n        ///          data as constrained by the key's modulus. Please refer\n        ///          to the seal()/open() methods.\n        virtual\n        elle::Buffer\n        encrypt(elle::ConstWeakBuffer const& plain,\n                Padding const padding = defaults::encryption_padding) const;\n        /// Verify the given signature against the original plain text.\n        bool\n        verify(elle::ConstWeakBuffer const& signature,\n               elle::ConstWeakBuffer const& plain,\n               Padding const padding = defaults::signature_padding,\n               Oneway const oneway = defaults::oneway) const;\n        /// Verify the given signature against the object\n        template <typename T>\n        bool\n        verify(elle::ConstWeakBuffer const& signature, T const& o) const;\n        template <typename T>\n        std::function<bool ()>\n        verify_async(elle::ConstWeakBuffer const& signature, T const& o) const;\n      private:\n        virtual\n        bool\n        _verify(elle::ConstWeakBuffer const& signature,\n                elle::ConstWeakBuffer const& plain,\n                Padding const padding = defaults::signature_padding,\n                Oneway const oneway = defaults::oneway) const;\n        template <typename T>\n        std::pair<elle::Buffer, elle::Buffer>\n        _verify_data(elle::ConstWeakBuffer const& signature,\n                     T const& o) const;\n      public:\n        /// Whether the given signature matches the stream-based plain.\n        bool\n        verify(elle::ConstWeakBuffer const& signature,\n               std::istream& plain,\n               Padding const padding = defaults::signature_padding,\n               Oneway const oneway = defaults::oneway) const;\n        /// Return the public key's size in bytes.\n        uint32_t\n        size() const;\n        /// Return the public key's length in bits.\n        uint32_t\n        length() const;\n      private:\n        bool\n        _verify(elle::ConstWeakBuffer const& signature,\n                std::istream& plain,\n                Padding const padding = defaults::signature_padding,\n                Oneway const oneway = defaults::oneway) const;\n\n# if defined(ELLE_CRYPTOGRAPHY_ROTATION)\n        /*---------.\n        | Rotation |\n        `---------*/\n      public:\n        /// Construct a public key based on a given seed i.e in a deterministic\n        /// way.\n        explicit\n        PublicKey(Seed const& seed);\n        /// Return the seed once unrotated by the public key.\n        Seed\n        unrotate(Seed const& seed) const;\n# endif\n\n        /*----------.\n        | Operators |\n        `----------*/\n      public:\n        bool\n        operator ==(PublicKey const& other) const;\n        bool\n        operator <(PublicKey const& other) const;\n        PublicKey&\n        operator =(PublicKey&& other) = default;\n\n        /*----------.\n        | Printable |\n        `----------*/\n      public:\n        void\n        print(std::ostream& stream) const override;\n\n        /*--------------.\n        | Serialization |\n        `--------------*/\n      public:\n        PublicKey(elle::serialization::SerializerIn& serializer);\n        void\n        serialize(elle::serialization::Serializer& serializer);\n        using serialization_tag = elle::serialization_tag;\n\n        /*-----------.\n        | Attributes |\n        `-----------*/\n      public:\n        ELLE_ATTRIBUTE_R(types::EVP_PKEY, key);\n      };\n\n      namespace _details\n      {\n        void\n        raise(std::string const& message);\n        types::EVP_PKEY\n        build_evp(::RSA* rsa);\n      }\n    }\n  }\n}\n\n//\n// ---------- DER -------------------------------------------------------------\n//\n\nnamespace elle\n{\n  namespace cryptography\n  {\n    namespace rsa\n    {\n      namespace publickey\n      {\n        namespace der\n        {\n          /*----------.\n          | Functions |\n          `----------*/\n\n          /// Encode the public key in DER.\n          elle::Buffer\n          encode(PublicKey const& K);\n          /// Decode the public key from a DER representation.\n          PublicKey\n          decode(elle::ConstWeakBuffer const& buffer);\n        }\n      }\n    }\n  }\n}\n\nnamespace std\n{\n  template <>\n  struct hash<elle::cryptography::rsa::PublicKey>\n  {\n    size_t\n    operator ()(elle::cryptography::rsa::PublicKey const& value) const;\n  };\n}\n\n#include <elle/cryptography/rsa/PublicKey.hxx>\n", "meta": {"hexsha": "8e777ad36928468b5e01dd7b8b43bda1f7478f39", "size": 6733, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/elle/cryptography/rsa/PublicKey.hh", "max_stars_repo_name": "infinitio/elle", "max_stars_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 521.0, "max_stars_repo_stars_event_min_datetime": "2016-02-14T00:39:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T22:39:25.000Z", "max_issues_repo_path": "src/elle/cryptography/rsa/PublicKey.hh", "max_issues_repo_name": "infinitio/elle", "max_issues_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-02-21T11:47:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-01T09:37:14.000Z", "max_forks_repo_path": "src/elle/cryptography/rsa/PublicKey.hh", "max_forks_repo_name": "infinitio/elle", "max_forks_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2017-02-21T10:18:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:35:20.000Z", "avg_line_length": 29.6607929515, "max_line_length": 79, "alphanum_fraction": 0.5634932422, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16246246900997283}}
{"text": "#include \"Common/Common.h\"\n#include \"Demos/Visualization/MiniGL.h\"\n#include \"Demos/Visualization/Selection.h\"\n#include \"GL/glut.h\"\n#include \"Simulation/TimeManager.h\"\n#include <Eigen/Dense>\n#include \"Simulation/SimulationModel.h\"\n#include \"Simulation/TimeStepController.h\"\n#include <iostream>\n#include \"Utils/OBJLoader.h\"\n#include \"Demos/Visualization/Visualization.h\"\n#include \"Utils/Logger.h\"\n#include \"Utils/Timing.h\"\n#include \"Utils/FileSystem.h\"\n#include \"Demos/Common/DemoBase.h\"\n#include \"Demos/Common/TweakBarParameters.h\"\n#include \"Simulation/Simulation.h\"\n\n#define _USE_MATH_DEFINES\n\n#include \"math.h\"\n\n\n// Enable memory leak detection\n#if defined(_DEBUG) && !defined(EIGEN_ALIGN)\n#define new DEBUG_NEW\n#endif\n\nusing namespace PBD;\nusing namespace Eigen;\nusing namespace std;\nusing namespace Utilities;\n\nvoid initParameters();\nvoid timeStep();\nvoid buildModel();\nvoid createBodyModel();\nvoid render();\nvoid reset();\n\nDemoBase *base;\n\nconst int numberOfBodies = 10;\nconst Real width = static_cast<Real>(1.0);\nconst Real height = static_cast<Real>(0.1);\nconst Real depth = static_cast<Real>(0.1);\n\n// main \nint main(int argc, char **argv)\n{\n    REPORT_MEMORY_LEAKS\n\n    base = new DemoBase();\n    base->init(argc, argv, \"Rigid body demo\");\n\n    SimulationModel *model = new SimulationModel();\n    model->init();\n    Simulation::getCurrent()->setModel(model);\n\n    buildModel();\n\n    initParameters();\n\n    Simulation::getCurrent()->setSimulationMethodChangedCallback([&]()\n                                                                 {\n                                                                     reset();\n                                                                     initParameters();\n                                                                     base->getSceneLoader()->readParameterObject(Simulation::getCurrent()->getTimeStep());\n                                                                 });\n\n    // OpenGL\n    MiniGL::setClientIdleFunc(50, timeStep);\n    MiniGL::setKeyFunc(0, 'r', reset);\n    MiniGL::setClientSceneFunc(render);\n    MiniGL::setViewport(40.0, 0.1f, 500.0, Vector3r(5.0, 10.0, 30.0), Vector3r(5.0, 0.0, 0.0));\n\n    glutMainLoop();\n\n    Utilities::Timing::printAverageTimes();\n    Utilities::Timing::printTimeSums();\n\n    delete Simulation::getCurrent();\n    delete base;\n    delete model;\n\n    return 0;\n}\n\nvoid initParameters()\n{\n    TwRemoveAllVars(MiniGL::getTweakBar());\n    TweakBarParameters::cleanup();\n\n    MiniGL::initTweakBarParameters();\n\n    TweakBarParameters::createParameterGUI();\n    TweakBarParameters::createParameterObjectGUI(base);\n    TweakBarParameters::createParameterObjectGUI(Simulation::getCurrent());\n    TweakBarParameters::createParameterObjectGUI(Simulation::getCurrent()->getModel());\n    TweakBarParameters::createParameterObjectGUI(Simulation::getCurrent()->getTimeStep());\n}\n\nvoid reset()\n{\n    Utilities::Timing::printAverageTimes();\n    Utilities::Timing::reset();\n\n    Simulation::getCurrent()->reset();\n    base->getSelectedParticles().clear();\n}\n\nvoid timeStep()\n{\n    const Real pauseAt = base->getValue<Real>(DemoBase::PAUSE_AT);\n    if ((pauseAt > 0.0) && (pauseAt < TimeManager::getCurrent()->getTime()))\n        base->setValue(DemoBase::PAUSE, true);\n\n    if (base->getValue<bool>(DemoBase::PAUSE))\n        return;\n\n    // Simulation code\n    SimulationModel *model = Simulation::getCurrent()->getModel();\n    const unsigned int numSteps = base->getValue<unsigned int>(DemoBase::NUM_STEPS_PER_RENDER);\n    for (unsigned int i = 0; i < numSteps; i++)\n    {\n        START_TIMING(\"SimStep\");\n        Simulation::getCurrent()->getTimeStep()->step(*model);\n        STOP_TIMING_AVG;\n    }\n}\n\nvoid buildModel()\n{\n    TimeManager::getCurrent()->setTimeStepSize(static_cast<Real>(0.005));\n\n    createBodyModel();\n}\n\nvoid render()\n{\n    base->render();\n}\n\nvoid loadObj(const std::string &filename, VertexData &vd, IndexedFaceMesh &mesh, const Vector3r &scale)\n{\n    std::vector<OBJLoader::Vec3f> x;\n    std::vector<OBJLoader::Vec3f> normals;\n    std::vector<OBJLoader::Vec2f> texCoords;\n    std::vector<MeshFaceIndices> faces;\n    OBJLoader::Vec3f s = {(float) scale[0], (float) scale[1], (float) scale[2]};\n    OBJLoader::loadObj(filename, &x, &faces, &normals, &texCoords, s);\n\n    mesh.release();\n    const unsigned int nPoints = (unsigned int) x.size();\n    const unsigned int nFaces = (unsigned int) faces.size();\n    const unsigned int nTexCoords = (unsigned int) texCoords.size();\n    mesh.initMesh(nPoints, nFaces * 2, nFaces);\n    vd.reserve(nPoints);\n    for (unsigned int i = 0; i < nPoints; i++)\n    {\n        vd.addVertex(Vector3r(x[i][0], x[i][1], x[i][2]));\n    }\n    for (unsigned int i = 0; i < nTexCoords; i++)\n    {\n        mesh.addUV(texCoords[i][0], texCoords[i][1]);\n    }\n    for (unsigned int i = 0; i < nFaces; i++)\n    {\n        // Reduce the indices by one\n        int posIndices[3];\n        int texIndices[3];\n        for (int j = 0; j < 3; j++)\n        {\n            posIndices[j] = faces[i].posIndices[j] - 1;\n            if (nTexCoords > 0)\n            {\n                texIndices[j] = faces[i].texIndices[j] - 1;\n                mesh.addUVIndex(texIndices[j]);\n            }\n        }\n\n        mesh.addFace(&posIndices[0]);\n    }\n    mesh.buildNeighbors();\n\n    mesh.updateNormals(vd, 0);\n    mesh.updateVertexNormals(vd);\n\n    LOG_INFO << \"Number of triangles: \" << nFaces;\n    LOG_INFO << \"Number of vertices: \" << nPoints;\n}\n\n/** Create the rigid body model\n*/\nvoid createBodyModel()\n{\n    SimulationModel *model = Simulation::getCurrent()->getModel();\n    SimulationModel::RigidBodyVector &rb = model->getRigidBodies();\n    SimulationModel::ConstraintVector &constraints = model->getConstraints();\n\n    string fileName = FileSystem::normalizePath(base->getDataPath() + \"/models/cube.obj\");\n    IndexedFaceMesh mesh;\n    VertexData vd;\n    loadObj(fileName, vd, mesh, Vector3r(width, height, depth));\n\n    string fileName2 = FileSystem::normalizePath(base->getDataPath() + \"/models/bunny_10k.obj\");\n    IndexedFaceMesh mesh2;\n    VertexData vd2;\n    loadObj(fileName2, vd2, mesh2, Vector3r(2.0, 2.0, 2.0));\n\n    rb.resize(numberOfBodies);\n    const Real density = 1.0;\n    for (unsigned int i = 0; i < numberOfBodies - 1; i++)\n    {\n        rb[i] = new RigidBody();\n        rb[i]->initBody(density, Vector3r((Real) i * width, 0.0, 0.0), Quaternionr(1.0, 0.0, 0.0, 0.0), vd, mesh);\n    }\n    // Make first body static\n    rb[0]->setMass(0.0);\n\n    // bunny\n    const Quaternionr q(AngleAxisr(static_cast<Real>(1.0 / 6.0 * M_PI), Vector3r(0.0, 0.0, 1.0)));\n    const Vector3r t(static_cast<Real>(0.411) + (static_cast<Real>(numberOfBodies) - static_cast<Real>(1.0)) * width, static_cast<Real>(-1.776),\n                     static_cast<Real>(0.356));\n    rb[numberOfBodies - 1] = new RigidBody();\n    rb[numberOfBodies - 1]->initBody(density, t, q, vd2, mesh2);\n\n    constraints.reserve(numberOfBodies - 1);\n    for (unsigned int i = 0; i < numberOfBodies - 1; i++)\n    {\n        model->addBallJoint(i, i + 1, Vector3r((Real) i * width + static_cast<Real>(0.5) * width, 0.0, 0.0));\n    }\n}\n", "meta": {"hexsha": "816cb7ee8dd1e7cea00d1337f8f762bc24287e9b", "size": 7119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Demos/RigidBodyDemos/ChainDemo.cpp", "max_stars_repo_name": "Xayahp/branchfrac", "max_stars_repo_head_hexsha": "50e0ccb970caf5f1510ed19d2393a7a440e3100d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-28T09:04:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T05:15:06.000Z", "max_issues_repo_path": "Demos/RigidBodyDemos/ChainDemo.cpp", "max_issues_repo_name": "Xayahp/branchfrac", "max_issues_repo_head_hexsha": "50e0ccb970caf5f1510ed19d2393a7a440e3100d", "max_issues_repo_licenses": ["MIT"], "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/RigidBodyDemos/ChainDemo.cpp", "max_forks_repo_name": "Xayahp/branchfrac", "max_forks_repo_head_hexsha": "50e0ccb970caf5f1510ed19d2393a7a440e3100d", "max_forks_repo_licenses": ["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.4230769231, "max_line_length": 154, "alphanum_fraction": 0.6262115466, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16243229417469168}}
{"text": "// Copyright Louis Dionne 2013-2016\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/mpl/integral_c.hpp>\n#include <boost/mpl/partition.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/vector.hpp>\nnamespace mpl = boost::mpl;\n\n\nstruct is_even {\n    template <typename N>\n    using apply = mpl::integral_c<bool, N::type::value % 2 == 0>;\n};\n\nusing vector = <%= mpl_vector((1..input_size).to_a.map { |n|\n    \"mpl::integral_c<int, #{n}>\"\n}) %>;\n\nusing result = mpl::partition<vector, is_even>::type;\n\n\nint main() { }\n", "meta": {"hexsha": "81cd76f761c324091c3cf46323c366e90741f884", "size": 635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.61.0/libs/hana/benchmark/partition/compile.mpl.vector.erb.cpp", "max_stars_repo_name": "mikestaub/arangodb", "max_stars_repo_head_hexsha": "1bdf414de29b31bcaf80769a095933f66f8256ce", "max_stars_repo_licenses": ["ICU", "BSL-1.0", "Zlib", "Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-01-19T09:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T07:31:38.000Z", "max_issues_repo_path": "libs/hana/benchmark/partition/compile.mpl.vector.erb.cpp", "max_issues_repo_name": "crystax/android-vendor-boost-1-61-0", "max_issues_repo_head_hexsha": "a1f467d25d815dc7613fbee06c632cae423f52ca", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T15:38:28.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-12T11:14:58.000Z", "max_forks_repo_path": "libs/hana/benchmark/partition/compile.mpl.vector.erb.cpp", "max_forks_repo_name": "crystax/android-vendor-boost-1-61-0", "max_forks_repo_head_hexsha": "a1f467d25d815dc7613fbee06c632cae423f52ca", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-11-02T09:37:09.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-05T06:38:49.000Z", "avg_line_length": 25.4, "max_line_length": 81, "alphanum_fraction": 0.6881889764, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.1624322927515125}}
{"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 <ros/ros.h>\n#include <moveit_msgs/GetPlanningScene.h>\n#include <urdf_model/model.h>\n#include <moveit/robot_model_loader/robot_model_loader.h>\n#include <moveit/planning_scene/planning_scene.h>\n#include \"sdf_tools/sdf.hpp\"\n#include \"sdf_tools/SDF.h\"\n\n#ifndef SDF_BUILDER_HPP\n#define SDF_BUILDER_HPP\n\nnamespace sdf_tools\n{\n    static const uint8_t USE_CACHED = 0x00;\n    static const uint8_t USE_ONLY_OCTOMAP = 0x01;\n    static const uint8_t USE_ONLY_COLLISION_OBJECTS = 0x02;\n    static const uint8_t USE_FULL_PLANNING_SCENE = 0x03;\n\n    typedef struct\n    {\n        uint32_t location[3];\n        uint32_t closest_point[3];\n        double distance_square;\n        int32_t update_direction;\n    } bucket_cell;\n\n    typedef VoxelGrid::VoxelGrid<bucket_cell> DistanceField;\n\n    inline double ComputeDistanceSquared(int32_t x1, int32_t y1, int32_t z1, int32_t x2, int32_t y2, 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    class SDF_Builder\n    {\n    protected:\n\n        bool initialized_;\n        bool has_cached_sdf_;\n        bool has_cached_collmap_;\n        bool has_planning_scene_;\n        Eigen::Affine3d origin_transform_;\n        std::string frame_;\n        double x_size_;\n        double y_size_;\n        double z_size_;\n        double resolution_;\n        float OOB_value_;\n        SignedDistanceField cached_sdf_;\n        VoxelGrid::VoxelGrid<uint8_t> cached_collmap_;\n        std::shared_ptr<planning_scene::PlanningScene> planning_scene_ptr_;\n        ros::NodeHandle nh_;\n        ros::ServiceClient planning_scene_client_;\n\n        SignedDistanceField UpdateSDFFromPlanningScene();\n\n        VoxelGrid::VoxelGrid<uint8_t> UpdateCollisionMapFromPlanningScene();\n\n        bool BuildInternalPlanningScene();\n\n        DistanceField BuildDistanceField(std::vector<Eigen::Vector3i>& points);\n\n        std::vector<std::vector<std::vector<std::vector<int>>>> MakeNeighborhoods();\n\n        inline int GetDirectionNumber(int dx, int dy, int dz)\n        {\n            return ((dx + 1) * 9) + ((dy + 1) * 3) + (dz + 1);\n        }\n\n        std::string GenerateSDFComputeBotURDFString();\n\n        std::string GenerateSDFComputeBotSRDFString();\n\n    public:\n\n        SDF_Builder(ros::NodeHandle& nh, Eigen::Affine3d origin_transform, std::string frame, double x_size, double y_size, double z_size, double resolution, float OOB_value, std::string planning_scene_service);\n\n        SDF_Builder(ros::NodeHandle& nh, std::string frame, double x_size, double y_size, double z_size, double resolution, float OOB_value, std::string planning_scene_service);\n\n        SDF_Builder()\n        {\n            initialized_ = false;\n            has_cached_sdf_ = false;\n            has_cached_collmap_ = false;\n            has_planning_scene_ = false;\n        }\n\n        void UpdatePlanningSceneFromMessage(moveit_msgs::PlanningScene& planning_scene);\n\n        SignedDistanceField UpdateSDF(uint8_t update_mode);\n\n        SignedDistanceField GetCachedSDF();\n\n        VoxelGrid::VoxelGrid<uint8_t> UpdateCollisionMap(uint8_t update_mode);\n\n        VoxelGrid::VoxelGrid<uint8_t> GetCachedCollisionMap();\n\n    };\n\n\n}\n\n#endif // SDF_BUILDER_HPP\n", "meta": {"hexsha": "5c05d2f84daf114c5e12ad34b1ab0f312b6eb42a", "size": 3418, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Btraj/third_party/sdf_tools/include/sdf_tools/sdf_builder.hpp", "max_stars_repo_name": "JCrime/Park_Inspection", "max_stars_repo_head_hexsha": "524d8286424e363a4bd3d77cf10df8f7eb3c3c6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-08-24T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T05:23:42.000Z", "max_issues_repo_path": "fm_Btraj/src/Btraj/third_party/sdf_tools/include/sdf_tools/sdf_builder.hpp", "max_issues_repo_name": "lvhualong/motion_Planning", "max_issues_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fm_Btraj/src/Btraj/third_party/sdf_tools/include/sdf_tools/sdf_builder.hpp", "max_forks_repo_name": "lvhualong/motion_Planning", "max_forks_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-24T08:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T12:47:20.000Z", "avg_line_length": 29.7217391304, "max_line_length": 211, "alphanum_fraction": 0.6813926273, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.16243228756620462}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2015.\n//\n// This software is released under a three-clause BSD license:\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 any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS 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 PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Chris Bielow $\n// $Authors: Chris Bielow $\n// --------------------------------------------------------------------------\n//\n\n#include <OpenMS/ANALYSIS/QUANTITATION/ItraqQuantifier.h>\n\n// default isotope correction (via A^-1)\n// NNLS isotope correction\n#include <OpenMS/MATH/MISC/NonNegativeLeastSquaresSolver.h>\n\n#include <OpenMS/DATASTRUCTURES/StringListUtils.h>\n#include <OpenMS/DATASTRUCTURES/Utils/MatrixUtils.h>\n#include <OpenMS/ANALYSIS/QUANTITATION/ProteinInference.h>\n#include <OpenMS/ANALYSIS/ID/IDMapper.h>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include <limits>\n\n\n\n//#define ITRAQ_DEBUG 1\n\nnamespace OpenMS\n{\n  ItraqQuantifier::ItraqQuantifier() :\n    DefaultParamHandler(\"ItraqQuantifier\"),\n    itraq_type_(FOURPLEX),\n    isotope_corrections_()\n  {\n    initIsotopeCorrections_();\n    setDefaultParams_();\n  }\n\n  ItraqQuantifier::ItraqQuantifier(Int itraq_type) :\n    DefaultParamHandler(\"ItraqQuantifier\"),\n    itraq_type_(itraq_type),\n    isotope_corrections_()\n  {\n    initIsotopeCorrections_();\n    setDefaultParams_();\n  }\n\n  ItraqQuantifier::ItraqQuantifier(Int itraq_type, const Param& param) :\n    DefaultParamHandler(\"ItraqQuantifier\"),\n    itraq_type_(itraq_type),\n    isotope_corrections_()\n  {\n    initIsotopeCorrections_();\n    setDefaultParams_();\n    setParameters(param);\n    updateMembers_();\n  }\n\n  ItraqQuantifier::ItraqQuantifier(const ItraqQuantifier& cp) :\n    DefaultParamHandler(cp),\n    ItraqConstants(cp),\n    itraq_type_(cp.itraq_type_),\n    channel_map_(cp.channel_map_),\n    isotope_corrections_(cp.isotope_corrections_)\n  {\n  }\n\n  ItraqQuantifier& ItraqQuantifier::operator=(const ItraqQuantifier& rhs)\n  {\n    if (this == &rhs)\n      return *this;\n\n    DefaultParamHandler::operator=(rhs);\n    ItraqConstants::operator=(rhs);\n    itraq_type_ = rhs.itraq_type_;\n    channel_map_ = rhs.channel_map_;\n    isotope_corrections_ = rhs.isotope_corrections_;\n\n    return *this;\n  }\n\n  bool ItraqQuantifier::isIdentityCorrectionMatrix_(const Matrix<double>& channel_frequency) const\n  {\n    // check if we have an identity matrix\n    bool isIdentity = true;\n    for (Size i = 0; i < channel_frequency.cols(); ++i)\n    {\n      if (channel_frequency.getValue(i, i) != 1.0)\n      {\n        isIdentity = false;\n        break;\n      }\n    }\n    return isIdentity;\n  }\n\n  void ItraqQuantifier::run(const ConsensusMap& consensus_map_in, ConsensusMap& consensus_map_out)\n  {\n    // new stats\n    stats_ = ItraqQuantifierStats();\n    stats_.channel_count = CHANNEL_COUNT[itraq_type_];\n    if (consensus_map_in.empty())\n    {\n      LOG_WARN << \"Warning: Empty iTRAQ container. No quantitative information available!\" << std::endl;\n      return;\n    }\n\n    reconstructChannelInfo_(consensus_map_in);\n    consensus_map_out = consensus_map_in;\n\n    // first do isotope correction\n    if (String(param_.getValue(\"isotope_correction\")) == \"true\")\n    {\n      // translate isotope_corrections_ to a channel_frequency matrix\n      Matrix<double> channel_frequency = ItraqConstants::translateIsotopeMatrix(itraq_type_, isotope_corrections_);\n\n      // if it is an identity matrix, performing isotope correction makes no sense\n      if (isIdentityCorrectionMatrix_(channel_frequency))\n      {\n        throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier: The given isotope correction matrix is an identity matrix leading to no correction. Please provide a valid isotope_correction matrix as it was provided with the iTRAQ/TMT kit!\");\n      }\n\n#ifdef ITRAQ_DEBUG\n      std::cout << \"channel_frequency matrix: \\n\" << channel_frequency << \"\\n\" << std::endl;\n#endif\n\n      // ISOTOPE CORRECTION: this solves the system naively via matrix inversion\n      EigenMatrixXdPtr m(convertOpenMSMatrix2EigenMatrixXd(channel_frequency));\n      Eigen::FullPivLU<Eigen::MatrixXd> ludecomp(*m);\n      Eigen::VectorXd b;\n      b.resize(CHANNEL_COUNT[itraq_type_]);\n      b.setZero();\n      std::vector<double> vec_x(CHANNEL_COUNT[itraq_type_], 0);\n\n\n      if (!ludecomp.isInvertible())\n      {\n        throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier: Invalid entry in Param 'isotope_correction_values'; the Matrix is not invertible!\");\n      }\n\n      LOG_INFO << \"SOLVING isotope correction via NNLS\\n\";\n\n      Matrix<double> m_b(CHANNEL_COUNT[itraq_type_], 1);\n      Matrix<double> m_x(CHANNEL_COUNT[itraq_type_], 1);\n\n      // correct all consensus elements\n      for (size_t i = 0; i < consensus_map_out.size(); ++i)\n      {\n#ifdef ITRAQ_DEBUG\n        std::cout << \"\\nMAP element  #### \" << i << \" #### \\n\" << std::endl;\n#endif\n\n        consensus_map_out[i].clear(); // delete only the consensus handles\n        // fill b vector\n        for (ConsensusFeature::HandleSetType::const_iterator it_elements = consensus_map_in[i].getFeatures().begin();\n             it_elements != consensus_map_in[i].getFeatures().end();\n             ++it_elements)\n        {\n\n\n          //find channel_id of current element\n          Int index = Int(consensus_map_in.getFileDescriptions().find(it_elements->getMapIndex())->second.getMetaValue(\"channel_id\"));\n#ifdef ITRAQ_DEBUG\n          std::cout << \"  map_index \" << it_elements->getMapIndex() << \"-> id \" << index << \" with intensity \" << it_elements->getIntensity() << \"\\n\" << std::endl;\n#endif\n\n          // this is deprecated, but serves as quality measurement\n          b(index) = it_elements->getIntensity();\n          m_b(index, 0) = it_elements->getIntensity();\n        }\n\n        // solve\n        Eigen::MatrixXd matrix_x = ludecomp.solve(b);\n        // check if a solution exists\n        if (!((*m) * matrix_x).isApprox(b))\n        {\n          throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier: Invalid entry in Param 'isotope_correction_values'; Cannot multiply!\");\n        }\n        Int status = NonNegativeLeastSquaresSolver::solve(channel_frequency, m_b, m_x);\n        if (status != NonNegativeLeastSquaresSolver::SOLVED)\n        {\n          throw Exception::FailedAPICall(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier: Failed to find least-squares fit!\");\n        }\n\n        Size s_negative(0);\n        Size s_different_count(0); // happens when naive solution is negative in other channels\n        double s_different_intensity(0);\n        // ISOTOPE CORRECTION: compare solutions of Matrix inversion vs. NNLS\n        for (Size index = 0; index < (Size)CHANNEL_COUNT[itraq_type_]; ++index)\n        {\n          if (matrix_x(index) < 0.0)\n          {\n            ++s_negative;\n          }\n          else if (std::fabs(m_x(index, 0) - matrix_x(index)) > 0.000001)\n          {\n            ++s_different_count;\n            s_different_intensity += std::fabs(m_x(index, 0) - matrix_x(index));\n          }\n        }\n\n        if (s_negative == 0 && s_different_count > 0) // solutions are inconsistent, despite being positive! This should not happen!\n        {\n          throw Exception::Postcondition(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"Isotope correction values of alternative method differ!\");\n        }\n\n        // update global stats\n        stats_.iso_number_reporter_negative += s_negative;\n        stats_.iso_number_reporter_different += s_different_count;\n        stats_.iso_solution_different_intensity += s_different_intensity;\n\n        // write back the values to the map\n        Peak2D::IntensityType cf_intensity(0);\n        for (ConsensusFeature::HandleSetType::const_iterator it_elements = consensus_map_in[i].begin();\n             it_elements != consensus_map_in[i].end();\n             ++it_elements)\n        {\n          FeatureHandle handle = *it_elements;\n          //find channel_id of current element\n          Int index = Int(consensus_map_out.getFileDescriptions()[it_elements->getMapIndex()].getMetaValue(\"channel_id\"));\n\n          handle.setIntensity(Peak2D::IntensityType(m_x(index, 0)));\n\n          consensus_map_out[i].insert(handle);\n\n          cf_intensity += handle.getIntensity(); // sum up all channels for CF\n\n#ifdef ITRAQ_DEBUG\n          std::cout <<  it_elements->getIntensity() << \" -> \" << handle.getIntensity() << std::endl;\n#endif\n        }\n        consensus_map_out[i].setIntensity(cf_intensity); // set overall intensity of CF (sum of all channels)\n\n        if (s_negative > 0)\n        {\n          ++stats_.iso_number_ms2_negative;\n          stats_.iso_total_intensity_negative += cf_intensity;\n        }\n      }\n\n    } // ! isotope_correction\n    else\n    {\n      LOG_WARN << \"Warning: Due to deactivated isotope-correction labeling statistics will be based on raw intensities, which might give too optimistic results.\" << std::endl;\n    }\n\n    stats_.number_ms2_total = consensus_map_out.size();\n    // ------------------------------\n    // Labeling efficiency statistics\n    // ------------------------------\n    std::map<Size, Size> empty_channel;\n\n    for (size_t i = 0; i < consensus_map_out.size(); ++i)\n    {\n      // is whole scan empty?!\n      if (consensus_map_out[i].getIntensity() == 0)\n        ++stats_.number_ms2_empty;\n\n      // look at single reporters\n      for (ConsensusFeature::HandleSetType::const_iterator it_elements = consensus_map_out[i].begin();\n           it_elements != consensus_map_out[i].end();\n           ++it_elements)\n      {\n        if (it_elements->getIntensity() == 0)\n        {\n          Int ch_index = consensus_map_out.getFileDescriptions()[it_elements->getMapIndex()].getMetaValue(\"channel_name\");\n          ++empty_channel[ch_index];\n        }\n      }\n    }\n    LOG_INFO << \"iTRAQ: skipped \" << stats_.number_ms2_empty << \" of \" << consensus_map_out.size() << \" selected scans due to lack of iTRAQ information:\\n\";\n    consensus_map_out.setMetaValue(\"itraq:scans_noquant\", stats_.number_ms2_empty);\n    consensus_map_out.setMetaValue(\"itraq:scans_total\", consensus_map_out.size());\n\n    stats_.empty_channels = empty_channel;\n\n    LOG_INFO << \"iTRAQ: channels with signal\\n\";\n    for (std::map<Size, Size>::const_iterator it_m = empty_channel.begin(); it_m != empty_channel.end(); ++it_m)\n    {\n      LOG_INFO << \"      channel \" << it_m->first << \": \" << (consensus_map_out.size() - it_m->second) << \" / \" <<  consensus_map_out.size() << \" (\" << ((consensus_map_out.size() - it_m->second) * 100 / consensus_map_out.size()) << \"%)\\n\";\n      consensus_map_out.setMetaValue(String(\"itraq:quantifyable_ch\") + it_m->first, (consensus_map_out.size() - it_m->second));\n    }\n\n    // ****************************\n    // ** find reference channel **\n    // ****************************\n    Int reference_channel = Int(param_.getValue(\"channel_reference\"));\n    if (itraq_type_ == ItraqConstants::FOURPLEX && (reference_channel < 114 || reference_channel > 117))\n    {\n      throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier:Invalid entry in Param 'channel_reference'; Valid channels for 4plex are 114-117!\");\n    }\n    else if (itraq_type_ == ItraqConstants::EIGHTPLEX && (reference_channel < 113 || reference_channel > 121))\n    {\n      throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier:Invalid entry in Param 'channel_reference'; Valid channels for 8plex are 113-121!\");\n    }\n    else if (itraq_type_ == ItraqConstants::TMT_SIXPLEX && (reference_channel < 126 || reference_channel > 131))\n    {\n      throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier:Invalid entry in Param 'channel_reference'; Valid channels for TMT-6plex are 126-131!\");\n    }\n\n#ifdef ITRAQ_DEBUG\n    std::cout << \"reference_channel is: \" << reference_channel  << std::endl;\n#endif\n\n    // determine reference channel as vector index\n    Map<Size, Size> map_to_vectorindex;\n    Size ref_mapid = 0;\n    Size index = 0;\n    for (ConsensusMap::FileDescriptions::const_iterator file_it = consensus_map_out.getFileDescriptions().begin();\n         file_it != consensus_map_out.getFileDescriptions().end();\n         ++file_it)\n    {\n      if ((Int) file_it->second.getMetaValue(\"channel_name\") == reference_channel)\n      {\n        ref_mapid = file_it->first;\n#ifdef ITRAQ_DEBUG\n        std::cout << \"reference_map_id is: \" << ref_mapid <<  std::endl;\n#endif\n      }\n      map_to_vectorindex[file_it->first] = index;\n      ++index;\n    }\n\n    // ** NORMALIZATION ** //\n\n    // normalize median of channel-to-reference ratio to 1\n    if (String(param_.getValue(\"do_normalization\")) == \"true\")\n    {\n      if (channel_map_.has(reference_channel))\n      {\n        std::vector<std::vector<double> > peptide_ratios;\n        // this is a control (the normalization factors should be about the same)\n        std::vector<std::vector<double> > peptide_intensities;\n\n        // build mapping of map_index to ratio_array_index\n        peptide_ratios.resize(channel_map_.size());\n        peptide_intensities.resize(channel_map_.size());\n\n        //build up ratios for each peptide of non-reference channels\n        ConsensusFeature::HandleSetType::iterator ref_it;\n        Peak2D::IntensityType ref_intensity;\n        for (size_t i = 0; i < consensus_map_out.size(); ++i)\n        {\n          // find reference index (this is inefficient to do every time,\n          // but the most robust against anyone who tries to change the internals of ConsensusFeature):\n          ref_it = consensus_map_out[i].end();\n          for (ConsensusFeature::HandleSetType::iterator it_elements = consensus_map_out[i].begin();\n               it_elements != consensus_map_out[i].end();\n               ++it_elements)\n          {\n            if ((Int) consensus_map_out.getFileDescriptions()[it_elements->getMapIndex()].getMetaValue(\"channel_name\") == reference_channel)\n            {\n              ref_it = it_elements;\n              break;\n            }\n          }\n\n          // reference channel not found in this ConsensusFeature\n          if (ref_it == consensus_map_out[i].end())\n          {\n            LOG_ERROR << \"ItraqQuantifier::run() WARNING: ConsensusFeature \" << i << \" does not have a reference channel! Skipping\" << std::endl;\n            continue;\n          }\n\n          ref_intensity = ref_it->getIntensity();\n\n          // now collect the ratios and intensities\n          for (ConsensusFeature::HandleSetType::iterator it_elements = consensus_map_out[i].begin();\n               it_elements != consensus_map_out[i].end();\n               ++it_elements)\n          {\n            if (ref_intensity == 0) //avoid nan's and inf's\n            {\n              if (it_elements->getIntensity() == 0) // 0/0 will give 'nan'\n              {\n                //so leave it out completely (there is no information to be gained)\n              }\n              else // x/0 is 'inf' but std::sort() has problems with that\n              {\n                peptide_ratios[map_to_vectorindex[it_elements->getMapIndex()]].push_back(std::numeric_limits<double>::max());\n              }\n            }\n            else // everything seems fine\n            {\n              peptide_ratios[map_to_vectorindex[it_elements->getMapIndex()]].push_back(it_elements->getIntensity() / ref_intensity);\n            }\n\n            // control\n            peptide_intensities[map_to_vectorindex[it_elements->getMapIndex()]].push_back(it_elements->getIntensity());\n          }\n        } // ! collect ratios\n\n        double max_deviation_from_control = 0;\n        // find MEDIAN of ratios for each channel (store as 0th element in sorted vector)\n        for (Map<Size, Size>::const_iterator it_map = map_to_vectorindex.begin(); it_map != map_to_vectorindex.end(); ++it_map)\n        {\n          // sort vector (partial_sort might improve performance here)\n          std::sort(peptide_ratios[it_map->second].begin(), peptide_ratios[it_map->second].end());\n          // save median as first element\n          peptide_ratios[it_map->second][0] = peptide_ratios[it_map->second][peptide_ratios[it_map->second].size() / 2];\n\n          // sort control (intensities)\n          std::sort(peptide_intensities[it_map->second].begin(), peptide_intensities[it_map->second].end());\n          // find MEDIAN of control-method (intensities) for each channel\n          peptide_intensities[it_map->second][0] = peptide_intensities[it_map->second][peptide_intensities[it_map->second].size() / 2] /\n                                                   peptide_intensities[ref_mapid][peptide_intensities[ref_mapid].size() / 2];\n          //#ifdef ITRAQ_DEBUG\n          LOG_INFO << \"iTRAQ-normalize:  map-id \" << (it_map->first) << \" has factor \" << (peptide_ratios[it_map->second][0]) << \" (control: \" << (peptide_intensities[it_map->second][0]) << \")\" << std::endl;\n          //#endif\n          double dev = (peptide_ratios[it_map->second][0] - peptide_intensities[it_map->second][0]) / peptide_ratios[it_map->second][0];\n          if (fabs(max_deviation_from_control) < fabs(dev))\n          {\n            max_deviation_from_control = dev;\n          }\n        }\n\n        LOG_INFO << \"iTRAQ-normalization: max ratio deviation of alternative method is \" << (max_deviation_from_control * 100) << \"%\\n\";\n\n#ifdef ITRAQ_DEBUG\n        std::cout << \"debug OUTPUT\\n\";\n        for (Size i = 1; i < peptide_ratios[0].size(); ++i)\n        {\n          if (i == peptide_intensities[0].size() / 2)\n          {\n            std::cout << \"++++++++++ median: \\n\";\n          }\n          for (Size j = 0; j < peptide_ratios.size(); ++j)\n          {\n            std::cout << peptide_ratios[j][i] << \" \";\n          }\n          std::cout << \" -- int -- \";\n          for (Size j = 0; j < peptide_intensities.size(); ++j)\n          {\n            std::cout << peptide_intensities[j][i] << \" \";\n          }\n          if (i == peptide_intensities[0].size() / 2)\n          {\n            std::cout << \"\\n----------- median: \";\n          }\n          std::cout << \"\\n\";\n        }\n#endif\n\n        // adjust intensity ratios\n        for (size_t i = 0; i < consensus_map_out.size(); ++i)\n        {\n          // find reference index (this is inefficient to do every time,\n          // but the most robust against anyone who tries to change the internals of ConsensusFeature):\n          ref_it = consensus_map_out[i].end();\n          for (ConsensusFeature::HandleSetType::iterator it_elements = consensus_map_out[i].begin();\n               it_elements != consensus_map_out[i].end();\n               ++it_elements)\n          {\n            if ((Int) consensus_map_out.getFileDescriptions()[it_elements->getMapIndex()].getMetaValue(\"channel_name\") == reference_channel)\n            {\n              ref_it = it_elements;\n              break;\n            }\n          }\n\n          // reference channel not found in this ConsensusFeature\n          if (ref_it == consensus_map_out[i].end())\n          {\n            continue;\n          }\n\n          ref_intensity = ref_it->getIntensity();\n\n          // now adjust the ratios\n          ConsensusFeature cf = consensus_map_out[i];\n          cf.clear(); // delete its handles\n          for (ConsensusFeature::HandleSetType::iterator it_elements = consensus_map_out[i].begin();\n               it_elements != consensus_map_out[i].end();\n               ++it_elements)\n          {\n            FeatureHandle hd = *it_elements;\n            if (it_elements == ref_it)\n            {\n              hd.setIntensity(1);\n            }\n            else // divide current intensity by normalization factor (which was stored at position 0)\n            {\n              hd.setIntensity(hd.getIntensity() / peptide_ratios[map_to_vectorindex[it_elements->getMapIndex()]][0]);\n            }\n            cf.insert(hd);\n          }\n          // replace consensusFeature with updated intensity\n          consensus_map_out[i] = cf;\n        } // ! adjust ratios\n\n      } // ! ref_channel valid\n      else\n      {\n        throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier::run() Parameter 'channel_reference' does not name a valid channel!\");\n      }\n    } // !do_normalization\n\n\n    // ** PEPTIDE PROTEIN MAPPING ** //\n\n    consensus_map_out.setExperimentType(\"itraq\");\n\n    return;\n  }\n\n  ItraqQuantifier::ItraqQuantifierStats ItraqQuantifier::getStats() const\n  {\n    return stats_;\n  }\n\n  void ItraqQuantifier::setDefaultParams_()\n  {\n    // choose default and documentation depending on itraq/tmt, since we can provide no stable default for TMT\n    defaults_.setValue(\"isotope_correction\",\n                       (itraq_type_ == TMT_SIXPLEX\n                        ? \"false\"\n                        : \"true\"),\n                       (itraq_type_ == TMT_SIXPLEX\n                        ? \"Enable isotope correction (highly recommended). Note that you need to provide a correction matrix (see isotope_correction:tmt-6plex otherwise the tool will fail.\"\n                        : \"Enable isotope correction (highly recommended).\"),\n                       ListUtils::create<String>(\"advanced\"));\n    defaults_.setValidStrings(\"isotope_correction\", ListUtils::create<String>(\"true,false\"));\n\n    defaults_.setValue(\"do_normalization\", \"false\", \"Normalize channels? Done by using the Median of Ratios (every channel / Reference). Also the ratio of medians (from any channel and reference) is provided as control measure!\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValidStrings(\"do_normalization\", ListUtils::create<String>(\"true,false\"));\n\n    if (itraq_type_ == TMT_SIXPLEX)\n    {\n      defaults_.setValue(\"isotope_correction:tmt-6plex\",\n                         ItraqConstants::getIsotopeMatrixAsStringList(ItraqConstants::TMT_SIXPLEX, isotope_corrections_),\n                         \"Override default values (see Documentation); use the following format: <channel>:<-2Da>/<-1Da>/<+1Da>/<+2Da> ; e.g. '126:0/0.3/4/0' , '128:0.1/0.3/3/0.2'.\",\n                         ListUtils::create<String>(\"advanced\"));\n    }\n    else\n    {\n      defaults_.setValue(\"isotope_correction:4plex\",\n                         ItraqConstants::getIsotopeMatrixAsStringList(ItraqConstants::FOURPLEX, isotope_corrections_),\n                         \"Override default values (see Documentation); use the following format: <channel>:<-2Da>/<-1Da>/<+1Da>/<+2Da> ; e.g. '114:0/0.3/4/0' , '116:0.1/0.3/3/0.2'.\",\n                         ListUtils::create<String>(\"advanced\"));\n      defaults_.setValue(\"isotope_correction:8plex\",\n                         ItraqConstants::getIsotopeMatrixAsStringList(ItraqConstants::EIGHTPLEX, isotope_corrections_),\n                         \"Override default values (see Documentation); use the following format: <channel>:<-2Da>/<-1Da>/<+1Da>/<+2Da> ; e.g. '114:0/0.3/4/0' , '116:0.1/0.3/3/0.2'.\",\n                         ListUtils::create<String>(\"advanced\"));\n    }\n\n    defaults_.setSectionDescription(\"isotope_correction\",\n                                    (itraq_type_ == TMT_SIXPLEX\n                                     ? \"Isotope correction matrices for tmt-6plex.\"\n                                     : \"Isotope correction matrices for 4plex and 8plex. Only one of them will be used (depending on iTRAQ mode).\"));\n\n\n    // for 4 & 8 plex. Max value is again checked during runtime\n    defaults_.setValue(\"channel_reference\",\n                       (itraq_type_ != TMT_SIXPLEX\n                        ? 114\n                        : 126),\n                       (itraq_type_ != TMT_SIXPLEX\n                        ? \"Number of the reference channel (114-117 for 4plex).\"\n                        : \"Number of the reference channel (126-131).\"));\n    if (itraq_type_ == TMT_SIXPLEX)\n    {\n      defaults_.setMinInt(\"channel_reference\", 126);\n      defaults_.setMaxInt(\"channel_reference\", 131);\n    }\n    else if (itraq_type_ == FOURPLEX)\n    {\n      defaults_.setMinInt(\"channel_reference\", 114);\n      defaults_.setMaxInt(\"channel_reference\", 117);\n    }\n    else // EIGHTPLEX\n    {\n      defaults_.setMinInt(\"channel_reference\", 113);\n      defaults_.setMaxInt(\"channel_reference\", 121);\n    }\n\n    defaultsToParam_();\n  }\n\n  void ItraqQuantifier::updateMembers_()\n  {\n    StringList channels;\n    // update isotope_corrections_ Matrix with custom values\n    if (itraq_type_ == ItraqConstants::FOURPLEX)\n    {\n      channels = param_.getValue(\"isotope_correction:4plex\");\n    }\n    else if (itraq_type_ == ItraqConstants::EIGHTPLEX)\n    {\n      channels = param_.getValue(\"isotope_correction:8plex\");\n    }\n    else if (itraq_type_ == ItraqConstants::TMT_SIXPLEX)\n    {\n      channels = param_.getValue(\"isotope_correction:tmt-6plex\");\n    }\n\n    if (channels.size() > 0)\n    {\n      ItraqConstants::updateIsotopeMatrixFromStringList(itraq_type_, channels, isotope_corrections_);\n    }\n  }\n\n  /// initialize\n  void ItraqQuantifier::initIsotopeCorrections_()\n  {\n    isotope_corrections_.resize(3);\n    isotope_corrections_[0].setMatrix<4, 4>(ItraqConstants::ISOTOPECORRECTIONS_FOURPLEX);\n    isotope_corrections_[1].setMatrix<8, 4>(ItraqConstants::ISOTOPECORRECTIONS_EIGHTPLEX);\n    isotope_corrections_[2].setMatrix<6, 4>(ItraqConstants::ISOTOPECORRECTIONS_TMT_SIXPLEX);\n  }\n\n  /// extract channel information (active channels, names, etc) from ConsensusMap\n  void ItraqQuantifier::reconstructChannelInfo_(const ConsensusMap& consensus_map)\n  {\n    channel_map_.clear();\n\n    for (ConsensusMap::FileDescriptions::const_iterator file_it = consensus_map.getFileDescriptions().begin();\n         file_it != consensus_map.getFileDescriptions().end();\n         ++file_it)\n    {\n      if (file_it->second.metaValueExists(\"channel_name\"))\n      {\n        ChannelInfo info;\n        // fill info\n        info.name = file_it->second.getMetaValue(\"channel_name\");\n        info.id = file_it->second.getMetaValue(\"channel_id\");\n        info.description = file_it->second.getMetaValue(\"channel_description\");\n        info.center = file_it->second.getMetaValue(\"channel_center\");\n        info.active = (String(file_it->second.getMetaValue(\"channel_active\")) == \"true\" ? true : false);\n        channel_map_[info.name] = info;\n#ifdef ITRAQ_DEBUG\n        std::cout << \" setting info.name \" << (info.name) << \" and id \" << (info.id) << std::endl;\n#endif\n      }\n      else\n      {\n        throw Exception::MissingInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"ItraqQuantifier::reconstructChannelInfo_ The ConsensusMap provided is missing MetaInfo from ItraqChannelExtractor!\");\n      }\n    }\n  }\n\n  std::ostream& operator<<(std::ostream& os, const ItraqQuantifier::ItraqQuantifierStats& stats)\n  {\n    os << \"name\\tvalue\\t(value in %)\\n\";\n    os << \"# channels\\t\" << stats.channel_count << \"\\tNA\\n\";\n    os << \"# spectra total\\t\" << stats.number_ms2_total << \"\\tNA\\n\";\n    os << \"# spectra negative\\t\" << stats.iso_number_reporter_negative << \"\\tNA\\n\";\n    os << \"# negative reporter intensity\\t\" << stats.iso_number_reporter_negative << \"\\tNA\\n\";\n    os << \"# alternative positive reporter intensity\\t\" << stats.iso_number_reporter_different << \"\\tNA\\n\";\n    os << \"total intensity (affected spectra)\\t\" << stats.iso_total_intensity_negative << \"\\tNA\\n\";\n    os << \"total intensity difference (affected spectra)\\t\" << stats.iso_solution_different_intensity << \"\\t\" << (stats.iso_solution_different_intensity * 100 / stats.iso_total_intensity_negative) << \"\\n\";\n\n    for (std::map<Size, Size>::const_iterator it_m = stats.empty_channels.begin(); it_m != stats.empty_channels.end(); ++it_m)\n    {\n      os << \"labeling_efficiency_channel_\" << it_m->first << \"\\t\" << (stats.number_ms2_total - it_m->second) << \"\\t\" << ((stats.number_ms2_total - it_m->second) * 100 / stats.number_ms2_total) << \"\\n\";\n    }\n\n    return os;\n  }\n\n}\n", "meta": {"hexsha": "82e0262fcd8b83d37f4c37736de43eac46862d0a", "size": 29535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/ANALYSIS/QUANTITATION/ItraqQuantifier.cpp", "max_stars_repo_name": "tomas-pluskal/openms", "max_stars_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_stars_repo_licenses": ["Zlib", "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/openms/source/ANALYSIS/QUANTITATION/ItraqQuantifier.cpp", "max_issues_repo_name": "tomas-pluskal/openms", "max_issues_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_issues_repo_licenses": ["Zlib", "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/openms/source/ANALYSIS/QUANTITATION/ItraqQuantifier.cpp", "max_forks_repo_name": "tomas-pluskal/openms", "max_forks_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_forks_repo_licenses": ["Zlib", "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.8664731495, "max_line_length": 279, "alphanum_fraction": 0.6316912138, "num_tokens": 6997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1624322875662046}}
{"text": "#ifndef DART_NEURAL_CONSTRAINT_MATRICES_HPP_\n#define DART_NEURAL_CONSTRAINT_MATRICES_HPP_\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"dart/neural/DifferentiableContactConstraint.hpp\"\n#include \"dart/neural/NeuralConstants.hpp\"\n#include \"dart/neural/NeuralUtils.hpp\"\n#include \"dart/performance/PerformanceLog.hpp\"\n#include \"dart/simulation/World.hpp\"\n\nnamespace dart {\n\nnamespace constraint {\nclass ConstrainedGroup;\nclass ConstraintBase;\n} // namespace constraint\n\nnamespace dynamics {\nclass Skeleton;\n} // namespace dynamics\n\nusing namespace performance;\n\nnamespace neural {\n\nenum ConstraintMapping\n{\n  CLAMPING = -1,\n  NOT_CLAMPING = -2,\n  ILLEGAL = -3,\n  IRRELEVANT = -4\n};\n\n/// This class pairs with a ConstrainedGroup, to save all the constraint\n/// matrices and related info for that ConstrainedGroup, so that we can\n/// construct full Jacobian matrices or run backprop later.\nclass ConstrainedGroupGradientMatrices\n{\npublic:\n  ConstrainedGroupGradientMatrices(\n      constraint::ConstrainedGroup& group, s_t timeStep);\n\n  /// This is a constructor for test mocks\n  ConstrainedGroupGradientMatrices(\n      int numDofs, int numConstraintDim, s_t timeStep);\n\n  /// This gets called during the setup of the ConstrainedGroupGradientMatrices\n  /// at each constraint. This must be called before constructMatrices(), and\n  /// must be called exactly once for each constraint.\n  void registerConstraint(\n      const std::shared_ptr<constraint::ConstraintBase>& constraint);\n\n  /// This mocks registering a constaint. Useful for testing.\n  void mockRegisterConstraint(\n      s_t restitutionCoeff, s_t penetrationHackVel);\n\n  /// This gets called during the setup of the ConstrainedGroupGradientMatrices\n  /// at each constraint's dimension. It gets called _after_ the system has\n  /// already applied a measurement impulse to that constraint dimension, and\n  /// measured some velocity changes. This must be called before\n  /// constructMatrices(), and must be called exactly once for each constraint's\n  /// dimension.\n  void measureConstraintImpulse(\n      const std::shared_ptr<constraint::ConstraintBase>& constraint,\n      std::size_t constraintIndex);\n\n  /// This will attempt to quickly solve an LCP by exploiting locality in the\n  /// solution. Assuming we were initialized at the last solution, there's\n  /// actually a good chance that we're still in all the same force categories.\n  /// This gets called before constructMatrices(), so it assumes no matrices\n  /// exist yet. Returns true if successful, false otherwise.\n  bool attemptFastSolveLCP(\n      simulation::World* world,\n      Eigen::VectorXs& mX,\n      const Eigen::VectorXs& A,\n      const Eigen::VectorXs& mHi,\n      const Eigen::VectorXs& mLo,\n      const Eigen::VectorXs& mB,\n      const Eigen::VectorXs& mFIndex);\n\n  /// This mocks measuring a constraint impulse. Useful for testing.\n  void mockMeasureConstraintImpulse(Eigen::VectorXs massedImpulseTest);\n\n  /// This gets called during the setup of the ConstrainedGroupGradientMatrices\n  /// after the LCP has run, with the result from the LCP solver.\n  void registerLCPResults(\n      Eigen::VectorXs mX,\n      Eigen::VectorXs hi,\n      Eigen::VectorXs lo,\n      Eigen::VectorXi fIndex,\n      Eigen::VectorXs b,\n      Eigen::VectorXs aColNorms,\n      Eigen::MatrixXs A,\n      s_t constraintForceMixingConstant,\n      bool deliberatelyIgnoreFriction);\n\n  /// If possible (because A is rank-deficient), this changes mX to be the\n  /// least-squares minimal solution. This makes mX unique for a given set of\n  /// inputs, rather than leaving the exact solution undefined. This can also be\n  /// used to short-circuit an LCP solve before it even needs to start, by using\n  /// the previous LCP solution as a \"close enough\" guess that can then be\n  /// cleaned up by this method and made exact. To faccilitate that use case,\n  /// this method returns true if it's found a valid solution, whether it\n  /// changed anything or not, and false if the solution is invalid.\n  bool opportunisticallyStandardizeResults(\n      simulation::World* world, Eigen::VectorXs& mX);\n\n  /// This returns true if the proposed mX is consistent with our recorded LCP\n  /// construction\n  bool isSolutionValid(const Eigen::VectorXs& mX);\n\n  /// This gets called by constructMatrices()\n  void deduplicateConstraints();\n\n  /// This gets called during the setup of the ConstrainedGroupGradientMatrices\n  /// after registerLCPResults(). This can only\n  /// be called once, and after this is called you cannot call\n  /// measureConstraintImpulse() again!\n  void constructMatrices(\n      simulation::World* world,\n      Eigen::VectorXi overrideClasses = Eigen::VectorXi::Zero(0));\n\n  /// This computes and returns the whole vel-vel jacobian for this group. For\n  /// backprop, you don't actually need this matrix, you can compute backprop\n  /// directly. This is here if you want access to the full Jacobian for some\n  /// reason.\n  Eigen::MatrixXs getVelVelJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole pos-vel jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  Eigen::MatrixXs getPosVelJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole force-vel jacobian for this group. For\n  /// backprop, you don't actually need this matrix, you can compute backprop\n  /// directly. This is here if you want access to the full Jacobian for some\n  /// reason.\n  Eigen::MatrixXs getControlForceVelJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole pos-pos jacobian for this group. For\n  /// backprop, you don't actually need this matrix, you can compute backprop\n  /// directly. This is here if you want access to the full Jacobian for some\n  /// reason.\n  Eigen::MatrixXs getPosPosJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole vel-pos jacobian for this group. For\n  /// backprop, you don't actually need this matrix, you can compute backprop\n  /// directly. This is here if you want access to the full Jacobian for some\n  /// reason.\n  Eigen::MatrixXs getVelPosJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This returns the [dC(pos,vel)/dpos] for the group, a block diagonal\n  /// concatenation of the skeleton [dC(pos,vel)/dpos] matrices.\n  Eigen::MatrixXs getPosCJacobian(simulation::WorldPtr world);\n\n  /// This returns the [dC(pos,vel)/dvel] for the group, a block diagonal\n  /// concatenation of the skeleton [dC(pos,vel)/dvel] matrices.\n  Eigen::MatrixXs getVelCJacobian(simulation::WorldPtr world);\n\n  /// This returns the mass matrix for the group, a block diagonal\n  /// concatenation of the skeleton mass matrices.\n  Eigen::MatrixXs getMassMatrix(simulation::WorldPtr world);\n\n  /// This returns the inverse mass matrix for the group, a block diagonal\n  /// concatenation of the skeleton inverse mass matrices.\n  Eigen::MatrixXs getInvMassMatrix(simulation::WorldPtr world);\n\n  /// This returns the block diagonal matrix where each skeleton's joints\n  /// integration scheme is reflected.\n  Eigen::MatrixXs getJointsPosPosJacobian(simulation::WorldPtr world);\n\n  /// This returns the block diagonal matrix where each skeleton's joints\n  /// integration scheme is reflected.\n  Eigen::MatrixXs getJointsVelPosJacobian(simulation::WorldPtr world);\n\n  /// This computes and returns the component of the pos-pos and pos-vel\n  /// jacobians due to bounce approximation. For backprop, you don't actually\n  /// need this matrix, you can compute backprop directly. This is here if you\n  /// want access to the full Jacobian for some reason.\n  Eigen::MatrixXs getBounceApproximationJacobian(PerformanceLog* perfLog);\n\n  /// This computes and returns the whole pos-vel jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  Eigen::MatrixXs getVelJacobianWrt(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the jacobian of constraint force, holding everyhing constant\n  /// except the value of WithRespectTo\n  Eigen::MatrixXs getJacobianOfConstraintForce(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the analytical expression for the Jacobian of Q*b, holding b\n  /// constant, if there are some upper-bound indices\n  Eigen::MatrixXs dQ_WithUB(\n      simulation::WorldPtr world,\n      const Eigen::MatrixXs& Minv,\n      const Eigen::MatrixXs& A_c,\n      const Eigen::MatrixXs& E,\n      const Eigen::MatrixXs& A_c_ub_E,\n      Eigen::VectorXs rhs,\n      WithRespectTo* wrt);\n\n  /// This returns the analytical expression for the Jacobian of Q^T*b, holding\n  /// b constant, if there are some upper-bound indices\n  Eigen::MatrixXs dQT_WithUB(\n      simulation::WorldPtr world,\n      const Eigen::MatrixXs& Minv,\n      const Eigen::MatrixXs& A_c,\n      const Eigen::MatrixXs& E,\n      const Eigen::MatrixXs& A_ub,\n      Eigen::VectorXs rhs,\n      WithRespectTo* wrt);\n\n  /// This returns the analytical expression for the Jacobian of Q*b, holding b\n  /// constant, if there are no upper-bound indices\n  Eigen::MatrixXs dQ_WithoutUB(\n      simulation::WorldPtr world,\n      const Eigen::MatrixXs& Minv,\n      const Eigen::MatrixXs& A_c,\n      Eigen::VectorXs rhs,\n      WithRespectTo* wrt);\n\n  /// This returns the vector of constants that get added to the diagonal of Q\n  /// to guarantee that Q is full-rank\n  Eigen::VectorXs& getConstraintForceMixingDiagonal();\n\n  /// This returns the jacobian of Q^{-1}b, holding b constant, with respect to\n  /// wrt\n  Eigen::MatrixXs getJacobianOfLCPConstraintMatrixClampingSubset(\n      simulation::WorldPtr world, Eigen::VectorXs b, WithRespectTo* wrt);\n\n  /// This returns the jacobian of b (from Q^{-1}b) with respect to wrt\n  Eigen::MatrixXs getJacobianOfLCPOffsetClampingSubset(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the subset of the A matrix used by the original LCP for just\n  /// the clamping constraints. It relates constraint force to constraint\n  /// acceleration. It's a mass matrix, just in a weird frame.\n  void computeLCPConstraintMatrixClampingSubset(\n      simulation::WorldPtr world,\n      Eigen::MatrixXs& Q,\n      const Eigen::MatrixXs& A_c);\n\n  /// This returns the subset of the b vector used by the original LCP for just\n  /// the clamping constraints. It's just the relative velocity at the clamping\n  /// contact points.\n  void computeLCPOffsetClampingSubset(\n      simulation::WorldPtr world,\n      Eigen::VectorXs& b,\n      const Eigen::MatrixXs& A_c);\n\n  /// This computes and returns an estimate of the constraint impulses for the\n  /// clamping constraints. This is based on a linear approximation of the\n  /// constraint impulses.\n  Eigen::VectorXs estimateClampingConstraintImpulses(\n      simulation::WorldPtr world, const Eigen::MatrixXs& A_c);\n\n  /// This returns the jacobian of M^{-1}(pos, inertia) * tau, holding\n  /// everything constant except the value of WithRespectTo\n  Eigen::MatrixXs getJacobianOfMinv(\n      simulation::WorldPtr world, Eigen::VectorXs tau, WithRespectTo* wrt);\n\n  /// This returns the jacobian of C(pos, inertia, vel), holding everything\n  /// constant except the value of WithRespectTo\n  Eigen::MatrixXs getJacobianOfC(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This computes the Jacobian of A_c*f0 with respect to position using\n  /// impulse tests.\n  Eigen::MatrixXs getJacobianOfClampingConstraints(\n      simulation::WorldPtr world, Eigen::VectorXs f0);\n\n  /// This computes the Jacobian of A_c^T*v0 with respect to position using\n  /// impulse tests.\n  Eigen::MatrixXs getJacobianOfClampingConstraintsTranspose(\n      simulation::WorldPtr world, Eigen::VectorXs v0);\n\n  /// This computes the Jacobian of A_ub*E*f0 with respect to position using\n  /// impulse tests.\n  Eigen::MatrixXs getJacobianOfUpperBoundConstraints(\n      simulation::WorldPtr world, Eigen::VectorXs f0);\n\n  /// This computes the Jacobian of A_ub^T*E*v0 with respect to position using\n  /// impulse tests.\n  Eigen::MatrixXs getJacobianOfUpperBoundConstraintsTranspose(\n      simulation::WorldPtr world, Eigen::VectorXs v0);\n\n  /// This computes the implicit backprop without forming intermediate\n  /// Jacobians. It takes a LossGradient with the position and velocity vectors\n  /// filled it, though the loss with respect to torque is ignored and can be\n  /// null. It returns a LossGradient with all three values filled in, position,\n  /// velocity, and torque.\n  void backprop(\n      simulation::WorldPtr world,\n      LossGradient& thisTimestepLoss,\n      const LossGradient& nextTimestepLoss,\n      bool exploreAlternateStrategies = false);\n\n  /// This zeros out any components of the gradient that would want to push us\n  /// out of the box-bounds encoded in the world for pos, vel, or force.\n  void clipLossGradientsToBounds(\n      simulation::WorldPtr world,\n      Eigen::VectorXs& lossWrtPos,\n      Eigen::VectorXs& lossWrtVel,\n      Eigen::VectorXs& lossWrtForce);\n\n  /// This replaces x with the result of M*x in place, without explicitly\n  /// forming M\n  Eigen::VectorXs implicitMultiplyByMassMatrix(\n      simulation::WorldPtr world, const Eigen::VectorXs& x);\n\n  /// This replaces x with the result of Minv*x in place, without explicitly\n  /// forming Minv\n  Eigen::VectorXs implicitMultiplyByInvMassMatrix(\n      simulation::WorldPtr world, const Eigen::VectorXs& x);\n\n  const Eigen::MatrixXs& getAllConstraintMatrix() const;\n\n  const Eigen::MatrixXs& getClampingConstraintMatrix() const;\n\n  const Eigen::MatrixXs& getMassedClampingConstraintMatrix() const;\n\n  const Eigen::MatrixXs& getUpperBoundConstraintMatrix() const;\n\n  const Eigen::MatrixXs& getMassedUpperBoundConstraintMatrix() const;\n\n  const Eigen::MatrixXs& getUpperBoundMappingMatrix() const;\n\n  const Eigen::MatrixXs& getBouncingConstraintMatrix() const;\n\n  /// These was the mX() vector used to construct this. Pretty much only here\n  /// for testing.\n  const Eigen::VectorXs& getContactConstraintImpulses() const;\n\n  /// These was the fIndex() vector used to construct this. Pretty much only\n  /// here for testing.\n  const Eigen::VectorXi& getContactConstraintMappings() const;\n\n  /// Returns the restitution coefficiennts at each clamping contact point.\n  const Eigen::VectorXs& getBounceDiagonals() const;\n\n  /// Returns the contact distances at each clamping contact point.\n  const Eigen::VectorXs& getRestitutionDiagonals() const;\n\n  /// Returns the penetration correction hack \"bounce\" (or 0 if the contact is\n  /// not inter-penetrating or is actively bouncing) at each contact point.\n  const Eigen::VectorXs& getPenetrationCorrectionVelocities() const;\n\n  /// This is the subset of the A matrix from the original LCP that corresponds\n  /// to clamping indices.\n  const Eigen::MatrixXs& getClampingAMatrix() const;\n\n  /// Returns the constraint impulses along the clamping constraints\n  const Eigen::VectorXs& getClampingConstraintImpulses() const;\n\n  /// Returns the relative velocities along the clamping constraints\n  const Eigen::VectorXs& getClampingConstraintRelativeVels() const;\n\n  /// Returns the velocity change caused by the illegal impulses from the LCP\n  const Eigen::VectorXs& getVelocityDueToIllegalImpulses() const;\n\n  /// Returns the torques applied pre-step\n  const Eigen::VectorXs& getPreStepTorques() const;\n\n  /// Returns the velocity pre-step\n  const Eigen::VectorXs& getPreStepVelocity() const;\n\n  /// Returns the velocity pre-LCP\n  const Eigen::VectorXs& getPreLCPVelocity() const;\n\n  /// Returns the M^{-1} matrix from pre-step\n  const Eigen::MatrixXs& getMinv() const;\n\n  /// Get the coriolis and gravity forces\n  const Eigen::VectorXs getCoriolisAndGravityAndExternalForces(\n      simulation::WorldPtr world) const;\n\n  /// This is like `getClampingConstraintMatrix()` or\n  /// `getUpperBoundConstraintMatrix()`, except that it returns all the columns\n  /// instead of just a subset.\n  Eigen::MatrixXs getFullConstraintMatrix(simulation::World* world) const;\n\n  std::size_t getNumDOFs() const;\n\n  std::size_t getNumConstraintDim() const;\n\n  const std::vector<std::string>& getSkeletons() const;\n\n  const std::vector<std::shared_ptr<DifferentiableContactConstraint>>&\n  getDifferentiableConstraints() const;\n\n  const std::vector<std::shared_ptr<DifferentiableContactConstraint>>&\n  getClampingConstraints() const;\n\n  const std::vector<std::shared_ptr<DifferentiableContactConstraint>>&\n  getUpperBoundConstraints() const;\n\n  /// Returns true if we were able to standardize our LCP results, false if we\n  /// weren't\n  bool areResultsStandardized() const;\n\n  /// This computes and returns the jacobian of M^{-1}(pos, inertia) * tau by\n  /// finite differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceJacobianOfMinv(\n      simulation::WorldPtr world,\n      Eigen::VectorXs tau,\n      WithRespectTo* wrt,\n      bool useRidders = false);\n\n  /// This computes and returns the jacobian of M^{-1}(pos, inertia) * tau by\n  /// finite differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfMinv(\n      simulation::WorldPtr world, Eigen::VectorXs tau, WithRespectTo* wrt);\n\n  /// This computes and returns the jacobian of C(pos, inertia, vel) by finite\n  /// differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceJacobianOfC(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// This computes and returns the jacobian of C(pos, inertia, vel) by finite\n  /// differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfC(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\nprivate:\n  std::size_t getWrtDim(simulation::WorldPtr world, WithRespectTo* wrt);\n\n  Eigen::VectorXs getWrt(simulation::WorldPtr world, WithRespectTo* wrt);\n\n  void setWrt(\n      simulation::WorldPtr world, WithRespectTo* wrt, Eigen::VectorXs v);\n\n  /// Gets the skeletons associated with this constrained group in vector form\n  std::vector<std::shared_ptr<dynamics::Skeleton>> getSkeletons(\n      simulation::WorldPtr world);\n\npublic:\n  /// This is only true after we've called constructMatrices(). It's a useful\n  /// flag to ensure we don't call it twice.\n  bool mFinalized;\n\n  /// This is a constant value we added to the diagonal entries of the A matrix,\n  /// which we only do if we were having problems because A is low rank.\n  /// Applying CFM amounts to softening the contact constraints on this\n  /// timestep.\n  s_t mConstraintForceMixingConstant;\n\n  bool mConstraintForceMixingDiagonalDirty;\n  Eigen::VectorXs mConstraintForceMixingDiagonal;\n\n  /// This flag gets set if we needed to ignore the friction indices in order to\n  /// solve the LCP. This can happen because boxed LCPs that we use to solve\n  /// friction aren't guaranteed to be solvable.\n  bool mDeliberatelyIgnoreFriction;\n\n  /// Impulse test matrix for all the constraints (only initialized in debug\n  /// mode)\n  Eigen::MatrixXs mAllConstraintMatrix;\n\n  /// Impulse test matrix for the clamping constraints\n  Eigen::MatrixXs mClampingConstraintMatrix;\n\n  /// Massed impulse test matrix for the clamping constraints\n  Eigen::MatrixXs mMassedClampingConstraintMatrix;\n\n  /// Impulse test matrix for the upper bound constraints\n  Eigen::MatrixXs mUpperBoundConstraintMatrix;\n\n  /// Massed impulse test matrix for the upper bound constraints\n  Eigen::MatrixXs mMassedUpperBoundConstraintMatrix;\n\n  /// Mapping matrix for upper bound constraints\n  Eigen::MatrixXs mUpperBoundMappingMatrix;\n\n  /// Impulse test matrix for the bouncing constraints\n  Eigen::MatrixXs mBouncingConstraintMatrix;\n\n  /// This is the vector of the coefficients on the diagonal of the bounce\n  /// matrix. These are 1+restitutionCoeff[i]\n  Eigen::VectorXs mBounceDiagonals;\n\n  /// This is the vector of the coefficients sized for just the bounces.\n  Eigen::VectorXs mRestitutionDiagonals;\n\n  /// This is the vector of velocity changes due to any impulses from the LCP\n  /// solver that are illegal (out of their legal bounds).\n  Eigen::VectorXs mVelocityDueToIllegalImpulses;\n\n  /// This is the vector of constraint impulses for all the clamping\n  /// constraints. It's key for computing Jacobians through quantities that\n  /// change the mass matrix.\n  Eigen::VectorXs mClampingConstraintImpulses;\n\n  /// This is just useful for testing the gradient computations\n  Eigen::VectorXs mClampingConstraintRelativeVels;\n\n  /// This is just useful for testing the gradient computations\n  Eigen::VectorXi mContactConstraintMappings;\n\n  /// This is just useful for testing the gradient computations\n  Eigen::VectorXs mPenetrationCorrectionVelocitiesVec;\n\n  /// This is the subset of the A matrix from the original LCP that corresponds\n  /// to clamping indices.\n  Eigen::MatrixXs mClampingAMatrix;\n\n  /// This is the inverse mass matrix computed in the constuctor\n  Eigen::MatrixXs mMinv;\n\n  /// These are the torques being applied, computed in the constuctor\n  Eigen::VectorXs mPreStepTorques;\n\n  /// These are the pre-step velocities, computed in the constuctor\n  Eigen::VectorXs mPreStepVelocities;\n\n  /// These are the pre-LCP velocities, computed in the constuctor\n  Eigen::VectorXs mPreLCPVelocities;\n\n  /// These are the names of skeletons that are covered by this constraint group\n  std::vector<std::string> mSkeletons;\n\n  /// For each index in the original force vector, this either points to an\n  /// index in the clamping vector, or it contains -1 to indicate the index was\n  /// not clamping.\n  std::vector<int> mClampingIndex;\n\n  /// For each index in the original force vector, this either points to an\n  /// index in the upper bound vector, or it contains -1 to indicate the index\n  /// was not clamping.\n  std::vector<int> mUpperBoundIndex;\n\n  /// This is the global timestep length. This is included here because it shows\n  /// up as a constant in some of the matrices.\n  s_t mTimeStep;\n\n  /// This is the total DOFs for this ConstrainedGroup\n  std::size_t mNumDOFs;\n\n  /// This is the number of total dimensions on all the constraints\n  std::size_t mNumConstraintDim;\n\n  /// These are the offsets into the total degrees of freedom for each skeleton\n  std::unordered_map<std::string, std::size_t> mSkeletonOffset;\n\n  /// This is all the constraints, in order that they were registered\n  std::vector<std::shared_ptr<constraint::ConstraintBase>> mConstraints;\n\n  /// This gives the index into the constraint at mConstraints[i] that\n  /// constraint i represents\n  std::vector<int> mConstraintIndices;\n\n  /// These are all the constraints\n  std::vector<std::shared_ptr<DifferentiableContactConstraint>>\n      mDifferentiableConstraints;\n\n  /// These are just the clamping constraints\n  std::vector<std::shared_ptr<DifferentiableContactConstraint>>\n      mClampingConstraints;\n\n  /// These are just the upper bound constraints\n  std::vector<std::shared_ptr<DifferentiableContactConstraint>>\n      mUpperBoundConstraints;\n\n  /// This is set to true when we were able to standardize the LCP output. It's\n  /// false if we were invalid for some reason.\n  bool mStandardizedResults;\n\n  /// These are public to enable unit testing\npublic:\n  /// This holds the coefficient of restitution for each constraint on this\n  /// group.\n  std::vector<s_t> mRestitutionCoeffs;\n\n  /// This holds the penetration correction velocities for each constraint in\n  /// this group.\n  std::vector<s_t> mPenetrationCorrectionVelocities;\n\n  /// These are all the values from the original LCP\n  Eigen::VectorXs mX;\n  Eigen::VectorXs mHi;\n  Eigen::VectorXs mLo;\n  Eigen::VectorXi mFIndex;\n  Eigen::VectorXs mB;\n  Eigen::VectorXs mAColNorms;\n  Eigen::MatrixXs mA;\n\n  /// These are values from our stabilization, for debugging\n  // TODO: <remove>\n  Eigen::VectorXs mStabilizationPos;\n  Eigen::VectorXs mStabilizationVel;\n  // TODO: </remove>\n  Eigen::MatrixXs mStabilizationQ;\n  Eigen::VectorXs mStabilizationB;\n\n  /// This holds the outputs of the impulse tests we run to create the\n  /// constraint matrices. We shuffle these vectors into the columns of\n  /// mClampingConstraintMatrix and mUpperBoundConstraintMatrix depending on the\n  /// values of the LCP solution. We also discard many of these vectors.\n  ///\n  /// mImpulseTests[k] holds the k'th constraint's impulse test, which is\n  /// a concatenated vector of the results for each skeleton in the group.\n  std::vector<Eigen::VectorXs> mMassedImpulseTests;\n};\n\n} // namespace neural\n} // namespace dart\n\n#endif", "meta": {"hexsha": "4887493298dd1d8a041e4743ed703013aa58d6c6", "size": 24937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/neural/ConstrainedGroupGradientMatrices.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/neural/ConstrainedGroupGradientMatrices.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/neural/ConstrainedGroupGradientMatrices.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": 40.2209677419, "max_line_length": 80, "alphanum_fraction": 0.7434735534, "num_tokens": 6175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.1620968251995491}}
{"text": "#pragma once\n\n#include <ostream>\n#include <boost/graph/adjacency_list.hpp>\n#include \"periodic.hpp\"\n#include \"ctab.hpp\" // MOL file format (aka CTable)\n\nstruct AtomVertex{\n    Code code;\n// temporaries for DFS that is used to find linear descriptors\n    boost::default_color_type color;\n    int path;\n// deduced as part of FCSP algorithm\n    int valence; // effective valence\n    int piE; // number of PI-electrons\n    bool inAromaCycle; // is part of aromatic cycle?\n    AtomVertex(){}\n    AtomVertex(Code code_):\n        code(code_), path(0), valence(0), piE(0), inAromaCycle(false){}\n};\n\n\nstruct Bound{\n    int type; //\n    Bound(){}\n    Bound(int type_) :type(type_){}\n};\n\ntemplate<typename V, typename E>\nusing Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, V, E>;\n\nusing ChemGraph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, AtomVertex, Bound>;\nusing vd = ChemGraph::vertex_descriptor;\nusing ed = ChemGraph::edge_descriptor;\n\nChemGraph toGraph(CTab& tab);\nChemGraph& addHydrogen(ChemGraph& graph);\nint getValence(ChemGraph& graph, ChemGraph::vertex_descriptor vertex);\nvoid dumpGraph(ChemGraph& graph, std::ostream& out);\n\ntemplate<class T, class EdgeMap>\nstd::vector<vd> cycleToChain(std::vector<T>& ic, EdgeMap&& mapper)\n{\n    typename std::vector<vd> vc;\n    auto seed = mapper(ic.front());\n    vc.push_back(seed.first);\n    vc.push_back(seed.second);\n    while (vc.front() != vc.back())\n    {\n        bool found = false;\n        for (auto e : ic)\n        {\n            auto p = mapper(e);\n            //has common vertex with back of chain and not == second one\n            if (p.first == vc.back() && p.second != vc[vc.size() - 2])\n                vc.push_back(p.second);\n            else if (p.second == vc.back() && p.first != vc[vc.size() - 2])\n                vc.push_back(p.first);\n            //has common vertex with front of chain and not == second one\n            else if (p.first == vc[0] && p.second != vc[1])\n                vc.insert(vc.begin(), p.second);\n            else if (p.second == vc[0] && p.first != vc[1])\n                vc.insert(vc.begin(), p.first);\n            else\n                continue;\n            found = true;\n            break;\n        }\n        assert(found);\n    }\n    vc.pop_back();\n    return vc;\n}\n\n\ntemplate<class T>\ninline bool operator<(const std::pair<T,T>& a, std::pair<T,T>& b){\n    return a.first < b.first || (a.first == b.first && a.second < b.second);\n}\n\nstruct Cycle{\npublic:\n    std::vector<vd> chain;\n    std::vector<std::pair<vd, vd>> edges; // ordered vertices (first<second)\n    bool aromatic_;\npublic:\n    // From set of edges\n    Cycle(std::vector<std::pair<vd, vd>> edges_);\n    // From chain of vertices\n    Cycle(std::vector<vd> chain);\n    // True if there is intersection of this and that cycle\n    bool intersects(const Cycle& that)const;\n    // Get set of edges of the intersection of this and that\n    std::vector<std::pair<vd,vd>> intersection(const Cycle& c)const;\n    // True if this cylce is aromatic\n    bool aromatic()const{ return aromatic_; }\n    // Chemical notion of size - number of edges\n    size_t size()const{ return edges.size(); }\n    // sets aromatic flags on atoms and cycle itself iff aromatic\n    Cycle& markAromatic(ChemGraph& graph);\n    // output as chain\n    friend std::ostream& operator<<(std::ostream& stream, const Cycle& cycle);\n};\n\nstd::ostream& operator<<(std::ostream& stream, const Cycle& cycle);\n\n// Obtain minimal cycle basis\nstd::vector<Cycle> minimalCycleBasis(ChemGraph& graph);\n\n// Impl class\ntemplate<class Vertex, class Edge>\nstruct ConnectedComponents{\n    using G = Graph<Vertex,Edge>;\n    ConnectedComponents(G& graph):\n    components(), g(graph),labels(boost::num_vertices(graph)), label(0){\n        findComponents();\n    }\n    std::vector<G> components;\nprivate:\n    void findComponents(){\n            using namespace boost;\n            auto const V = num_vertices(g);\n        for(size_t v=0; v<V; v++){\n            if(!labels[v]){\n                ++label; //start new component\n                dfs(v);\n            }\n        }\n        if(label == 1){\n            components.push_back(g);\n            return;\n        }\n        components.resize(label);\n        // for each component map global --> component\n        std::vector<std::vector<size_t>> g2c(label);\n        for(auto & vec : g2c)\n            vec.resize(V);\n\n        // map vertices to components and record positions\n        for(size_t v=0; v<V; v++){\n            int lbl = labels[v] - 1;\n            g2c[lbl][v] = add_vertex(g[v], components[lbl]);\n        }\n        // use map to copy over edges\n        for(size_t v=0; v<V; v++){\n                auto adj = adjacent_vertices(v, g);\n            for(auto p=adj.first; p!=adj.second; p++){\n                    auto w = *p;\n                if (w < v){ //deduplicate\n                    continue;\n                }\n                int lbl = labels[v] - 1;\n                auto e = edge(v, w, g).first;\n                add_edge(g2c[lbl][v], g2c[lbl][w], g[e], components[lbl]);\n            }\n        }\n    }\n\n    void dfs(size_t v){\n        labels[v] = label;\n        auto adj = adjacent_vertices(v, g);\n        for(auto p = adj.first; p != adj.second; p++){\n                auto w = *p;\n            if(!labels[w]){\n                dfs(w);\n            }\n        }\n    }\n    G& g;\n    std::vector<int> labels;\n    int label;\n};\n\n\n// Will copy g if it's the only component\ntemplate<class V, class E>\nstd::vector<Graph<V,E>> connectedComponents(Graph<V,E> &g)\n{\n    return ConnectedComponents<V,E>(g).components;\n}\n\n", "meta": {"hexsha": "43e16d49b0d3a0acd1f95a454b70493dbc66b541", "size": 5600, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/chemgraph.hpp", "max_stars_repo_name": "DmitryOlshansky/fcsp", "max_stars_repo_head_hexsha": "27301f475947c961501aa24a9537ca583a7d65c0", "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/chemgraph.hpp", "max_issues_repo_name": "DmitryOlshansky/fcsp", "max_issues_repo_head_hexsha": "27301f475947c961501aa24a9537ca583a7d65c0", "max_issues_repo_licenses": ["MIT"], "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/chemgraph.hpp", "max_forks_repo_name": "DmitryOlshansky/fcsp", "max_forks_repo_head_hexsha": "27301f475947c961501aa24a9537ca583a7d65c0", "max_forks_repo_licenses": ["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.7692307692, "max_line_length": 105, "alphanum_fraction": 0.5771428571, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.30735802955444114, "lm_q1q2_score": 0.1620749675774422}}
{"text": "// Copyright 2015-2020 Tier IV, 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#include <lanelet2_core/utility/Units.h>\n#include <lanelet2_io/Io.h>\n#include <lanelet2_io/io_handlers/Serialize.h>\n#include <lanelet2_projection/UTM.h>\n#include <quaternion_operation/quaternion_operation.h>\n\n#include <algorithm>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <deque>\n#include <lanelet2_extension_psim/io/autoware_osm_parser.hpp>\n#include <lanelet2_extension_psim/projection/mgrs_projector.hpp>\n#include <lanelet2_extension_psim/utility/message_conversion.hpp>\n#include <lanelet2_extension_psim/utility/query.hpp>\n#include <lanelet2_extension_psim/utility/utilities.hpp>\n#include <lanelet2_extension_psim/visualization/visualization.hpp>\n#include <memory>\n#include <scenario_simulator_exception/exception.hpp>\n#include <set>\n#include <string>\n#include <traffic_simulator/color_utils/color_utils.hpp>\n#include <traffic_simulator/hdmap_utils/hdmap_utils.hpp>\n#include <traffic_simulator/math/catmull_rom_spline.hpp>\n#include <traffic_simulator/math/hermite_curve.hpp>\n#include <traffic_simulator/math/linear_algebra.hpp>\n#include <traffic_simulator/math/transfrom.hpp>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace hdmap_utils\n{\nHdMapUtils::HdMapUtils(\n  const boost::filesystem::path & lanelet2_map_path, const geographic_msgs::msg::GeoPoint & origin)\n{\n  (void)origin;\n\n  lanelet::projection::MGRSProjector projector;\n\n  lanelet::ErrorMessages errors;\n\n  lanelet_map_ptr_ = lanelet::load(lanelet2_map_path.string(), projector, &errors);\n\n  if (not errors.empty()) {\n    std::stringstream ss;\n    const auto * separator = \"\";\n    for (const auto & error : errors) {\n      ss << separator << error;\n      separator = \"\\n\";\n    }\n    THROW_SIMULATION_ERROR(\"Failed to load lanelet map (\", ss.str(), \")\");\n  }\n  overwriteLaneletsCenterline();\n  traffic_rules_vehicle_ptr_ = lanelet::traffic_rules::TrafficRulesFactory::create(\n    lanelet::Locations::Germany, lanelet::Participants::Vehicle);\n  vehicle_routing_graph_ptr_ =\n    lanelet::routing::RoutingGraph::build(*lanelet_map_ptr_, *traffic_rules_vehicle_ptr_);\n  traffic_rules_pedestrian_ptr_ = lanelet::traffic_rules::TrafficRulesFactory::create(\n    lanelet::Locations::Germany, lanelet::Participants::Pedestrian);\n  pedestrian_routing_graph_ptr_ =\n    lanelet::routing::RoutingGraph::build(*lanelet_map_ptr_, *traffic_rules_pedestrian_ptr_);\n  std::vector<lanelet::routing::RoutingGraphConstPtr> all_graphs;\n  all_graphs.push_back(vehicle_routing_graph_ptr_);\n  all_graphs.push_back(pedestrian_routing_graph_ptr_);\n}\n\nconst std::vector<std::int64_t> HdMapUtils::getLaneletIds()\n{\n  std::vector<std::int64_t> ret;\n  for (const auto & lanelet : lanelet_map_ptr_->laneletLayer) {\n    ret.emplace_back(lanelet.id());\n  }\n  return ret;\n}\n\nconst std::vector<geometry_msgs::msg::Point> HdMapUtils::getLaneletPolygon(std::int64_t lanelet_id)\n{\n  std::vector<geometry_msgs::msg::Point> points;\n  lanelet::CompoundPolygon3d lanelet_polygon =\n    lanelet_map_ptr_->laneletLayer.get(lanelet_id).polygon3d();\n  for (const auto & lanelet_point : lanelet_polygon) {\n    geometry_msgs::msg::Point p;\n    p.x = lanelet_point.x();\n    p.y = lanelet_point.y();\n    p.z = lanelet_point.z();\n    points.emplace_back(p);\n  }\n  return points;\n}\n\nstd::vector<std::int64_t> HdMapUtils::filterLaneletIds(\n  const std::vector<std::int64_t> & lanelet_ids, const char subtype[]) const\n{\n  const auto lanelets = getLanelets(lanelet_ids);\n  std::vector<lanelet::Lanelet> filtered_lanelets;\n  for (const auto & ll : lanelets) {\n    if (ll.hasAttribute(lanelet::AttributeName::Subtype)) {\n      lanelet::Attribute attr = ll.attribute(lanelet::AttributeName::Subtype);\n      if (attr.value() == subtype) {\n        filtered_lanelets.emplace_back(ll);\n      }\n    }\n  }\n  return getLaneletIds(filtered_lanelets);\n}\n\nstd::vector<std::int64_t> HdMapUtils::getNearbyLaneletIds(\n  const geometry_msgs::msg::Point & position, double distance_threshold) const\n{\n  std::vector<std::int64_t> lanelet_ids;\n  lanelet::BasicPoint2d search_point(position.x, position.y);\n  std::vector<std::pair<double, lanelet::Lanelet>> nearest_lanelet =\n    lanelet::geometry::findNearest(lanelet_map_ptr_->laneletLayer, search_point, 5);\n  if (nearest_lanelet.empty()) {\n    return {};\n  }\n  for (const auto & lanelet : nearest_lanelet) {\n    if (lanelet.first <= distance_threshold) {\n      lanelet_ids.emplace_back(lanelet.second.id());\n    }\n  }\n  return lanelet_ids;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getNearbyLaneletIds(\n  const geometry_msgs::msg::Point & point, double distance_thresh, bool include_crosswalk) const\n{\n  std::vector<std::int64_t> lanelet_ids;\n  lanelet::BasicPoint2d search_point(point.x, point.y);\n  std::vector<std::pair<double, lanelet::Lanelet>> nearest_lanelet =\n    lanelet::geometry::findNearest(lanelet_map_ptr_->laneletLayer, search_point, 5);\n  if (include_crosswalk) {\n    if (nearest_lanelet.empty()) {\n      return {};\n    }\n    if (nearest_lanelet.front().first > distance_thresh) {\n      return {};\n    }\n    for (const auto & lanelet : nearest_lanelet) {\n      lanelet_ids.emplace_back(lanelet.second.id());\n    }\n  } else {\n    const auto nearest_road_lanelet =\n      excludeSubtypeLanelets(nearest_lanelet, lanelet::AttributeValueString::Crosswalk);\n    if (nearest_road_lanelet.empty()) {\n      return {};\n    }\n    if (nearest_road_lanelet.front().first > distance_thresh) {\n      return {};\n    }\n    for (const auto & lanelet : nearest_lanelet) {\n      lanelet_ids.emplace_back(lanelet.second.id());\n    }\n  }\n  return lanelet_ids;\n}\n\ndouble HdMapUtils::getHeight(const traffic_simulator_msgs::msg::LaneletPose & lanelet_pose)\n{\n  return toMapPose(lanelet_pose).pose.position.z;\n}\n\nboost::optional<double> HdMapUtils::getCollisionPointInLaneCoordinate(\n  std::int64_t lanelet_id, std::int64_t crossing_lanelet_id)\n{\n  namespace bg = boost::geometry;\n  using Point = bg::model::d2::point_xy<double>;\n  using Line = bg::model::linestring<Point>;\n  using Polygon = bg::model::polygon<Point, false>;\n  auto center_points = getCenterPoints(lanelet_id);\n  std::vector<Point> path_collision_points;\n  lanelet_map_ptr_->laneletLayer.get(crossing_lanelet_id);\n  lanelet::CompoundPolygon3d lanelet_polygon =\n    lanelet_map_ptr_->laneletLayer.get(crossing_lanelet_id).polygon3d();\n  Polygon crosswalk_polygon;\n  for (const auto & lanelet_point : lanelet_polygon) {\n    crosswalk_polygon.outer().push_back(bg::make<Point>(lanelet_point.x(), lanelet_point.y()));\n  }\n  crosswalk_polygon.outer().push_back(crosswalk_polygon.outer().front());\n  double s_in_lanelet = 0;\n  for (size_t i = 0; i < center_points.size() - 1; ++i) {\n    const auto p0 = center_points.at(i);\n    const auto p1 = center_points.at(i + 1);\n    const Line line{{p0.x, p0.y}, {p1.x, p1.y}};\n    double line_length =\n      std::sqrt(std::pow(p0.x - p1.x, 2) + std::pow(p0.y - p1.y, 2) + std::pow(p0.z - p1.z, 2));\n    std::vector<Point> line_collision_points;\n    bg::intersection(crosswalk_polygon, line, line_collision_points);\n    if (line_collision_points.empty()) {\n      continue;\n    }\n    std::vector<double> dist;\n    for (size_t j = 0; j < line_collision_points.size(); ++j) {\n      double s_in_line = 0;\n      if (std::fabs(p1.x - p0.x) < DBL_EPSILON) {\n        if (std::fabs(p1.y - p1.y < DBL_EPSILON)) {\n        } else {\n          s_in_line = (line_collision_points[j].y() - p0.y) / (p1.y - p0.y);\n          return s_in_lanelet + s_in_line * line_length;\n        }\n      } else {\n        s_in_line = (line_collision_points[j].x() - p0.x) / (p1.x - p0.x);\n        return s_in_lanelet + s_in_line * line_length;\n      }\n    }\n    s_in_lanelet = s_in_lanelet + line_length;\n  }\n  return boost::none;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getConflictingLaneIds(\n  const std::vector<std::int64_t> & lanelet_ids) const\n{\n  std::vector<std::int64_t> ret;\n  for (const auto & lanelet_id : lanelet_ids) {\n    const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n    const auto conflicting_lanelets =\n      lanelet::utils::getConflictingLanelets(vehicle_routing_graph_ptr_, lanelet);\n    for (const auto & conflicting_lanelet : conflicting_lanelets) {\n      ret.emplace_back(conflicting_lanelet.id());\n    }\n  }\n  return ret;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getConflictingCrosswalkIds(\n  const std::vector<std::int64_t> & lanelet_ids) const\n{\n  std::vector<std::int64_t> ret;\n  std::vector<lanelet::routing::RoutingGraphConstPtr> graphs;\n  graphs.emplace_back(vehicle_routing_graph_ptr_);\n  graphs.emplace_back(pedestrian_routing_graph_ptr_);\n  lanelet::routing::RoutingGraphContainer container(graphs);\n  for (const auto & lanelet_id : lanelet_ids) {\n    const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n    double height_clearance = 4;\n    size_t routing_graph_id = 1;\n    const auto conflicting_crosswalks =\n      container.conflictingInGraph(lanelet, routing_graph_id, height_clearance);\n    for (const auto & crosswalk : conflicting_crosswalks) {\n      ret.emplace_back(crosswalk.id());\n    }\n  }\n  return ret;\n}\n\nstd::vector<geometry_msgs::msg::Point> HdMapUtils::clipTrajectoryFromLaneletIds(\n  std::int64_t lanelet_id, double s, std::vector<std::int64_t> lanelet_ids, double forward_distance)\n{\n  std::vector<geometry_msgs::msg::Point> ret;\n  bool on_traj = false;\n  double rest_distance = forward_distance;\n  for (auto id_itr = lanelet_ids.begin(); id_itr != lanelet_ids.end(); id_itr++) {\n    double l = getLaneletLength(*id_itr);\n    if (on_traj) {\n      if (rest_distance < l) {\n        for (double s_val = 0; s_val < rest_distance; s_val = s_val + 1.0) {\n          auto map_pose = toMapPose(*id_itr, s_val, 0);\n          ret.emplace_back(map_pose.pose.position);\n        }\n        break;\n      } else {\n        rest_distance = rest_distance - l;\n        for (double s_val = 0; s_val < l; s_val = s_val + 1.0) {\n          auto map_pose = toMapPose(*id_itr, s_val, 0);\n          ret.emplace_back(map_pose.pose.position);\n        }\n        continue;\n      }\n    }\n    if (lanelet_id == *id_itr) {\n      on_traj = true;\n      if ((s + forward_distance) < l) {\n        for (double s_val = s; s_val < s + forward_distance; s_val = s_val + 1.0) {\n          auto map_pose = toMapPose(lanelet_id, s_val, 0);\n          ret.emplace_back(map_pose.pose.position);\n        }\n        break;\n      } else {\n        rest_distance = rest_distance - (l - s);\n        for (double s_val = s; s_val < l; s_val = s_val + 1.0) {\n          auto map_pose = toMapPose(lanelet_id, s_val, 0);\n          ret.emplace_back(map_pose.pose.position);\n        }\n        continue;\n      }\n    }\n  }\n  return ret;\n}\n\nstd::vector<lanelet::Lanelet> HdMapUtils::filterLanelets(\n  const std::vector<lanelet::Lanelet> & lanelets, const char subtype[]) const\n{\n  std::vector<lanelet::Lanelet> filtered_lanelets;\n  for (const auto & ll : lanelets) {\n    if (ll.hasAttribute(lanelet::AttributeName::Subtype)) {\n      lanelet::Attribute attr = ll.attribute(lanelet::AttributeName::Subtype);\n      if (attr.value() != subtype) {\n        filtered_lanelets.push_back(ll);\n      }\n    }\n  }\n  return filtered_lanelets;\n}\n\nstd::vector<std::pair<double, lanelet::Lanelet>> HdMapUtils::excludeSubtypeLanelets(\n  const std::vector<std::pair<double, lanelet::Lanelet>> & lls, const char subtype[]) const\n{\n  std::vector<std::pair<double, lanelet::Lanelet>> exclude_subtype_lanelets;\n  for (const auto & ll : lls) {\n    if (ll.second.hasAttribute(lanelet::AttributeName::Subtype)) {\n      lanelet::Attribute attr = ll.second.attribute(lanelet::AttributeName::Subtype);\n      if (attr.value() != subtype) {\n        exclude_subtype_lanelets.push_back(ll);\n      }\n    }\n  }\n  return exclude_subtype_lanelets;\n}\n\nlanelet::BasicPolygon2d HdMapUtils::absoluteHull(\n  const lanelet::BasicPolygon2d & relativeHull, const lanelet::matching::Pose2d & pose) const\n{\n  lanelet::BasicPolygon2d hullPoints;\n  hullPoints.reserve(relativeHull.size());\n  for (const auto & hullPt : relativeHull) {\n    hullPoints.push_back(pose * hullPt);\n  }\n  return hullPoints;\n}\n\nlanelet::BasicPoint2d HdMapUtils::toPoint2d(const geometry_msgs::msg::Point & point) const\n{\n  return lanelet::BasicPoint2d{point.x, point.y};\n}\n\nboost::optional<std::int64_t> HdMapUtils::matchToLane(\n  const geometry_msgs::msg::Pose & pose, const traffic_simulator_msgs::msg::BoundingBox & bbox,\n  bool include_crosswalk, double reduction_ratio) const\n{\n  boost::optional<std::int64_t> id;\n  lanelet::matching::Object2d obj;\n  obj.pose.translation() = toPoint2d(pose.position);\n  obj.pose.linear() = Eigen::Rotation2D<double>(\n                        quaternion_operation::convertQuaternionToEulerAngle(pose.orientation).z)\n                        .matrix();\n  obj.absoluteHull = absoluteHull(\n    lanelet::matching::Hull2d{\n      lanelet::BasicPoint2d{\n        bbox.center.x + bbox.dimensions.x * 0.5 * reduction_ratio,\n        bbox.center.y + bbox.dimensions.y * 0.5 * reduction_ratio},\n      lanelet::BasicPoint2d{\n        bbox.center.x - bbox.dimensions.x * 0.5 * reduction_ratio,\n        bbox.center.y - bbox.dimensions.y * 0.5 * reduction_ratio}},\n    obj.pose);\n  auto matches = lanelet::matching::getDeterministicMatches(*lanelet_map_ptr_, obj, 3.0);\n  if (!include_crosswalk) {\n    matches = lanelet::matching::removeNonRuleCompliantMatches(matches, traffic_rules_vehicle_ptr_);\n  }\n  if (matches.empty()) {\n    return boost::none;\n  }\n  std::sort(matches.begin(), matches.end(), [](auto const & lhs, auto const & rhs) {\n    return lhs.distance < rhs.distance;\n  });\n  return matches[0].lanelet.id();\n}\n\nboost::optional<traffic_simulator_msgs::msg::LaneletPose> HdMapUtils::toLaneletPose(\n  geometry_msgs::msg::Pose pose, bool include_crosswalk)\n{\n  const auto lanelet_ids = getNearbyLaneletIds(pose.position, 3.0, include_crosswalk);\n  if (lanelet_ids.empty()) {\n    return boost::none;\n  }\n  for (const auto & id : lanelet_ids) {\n    const auto lanelet_pose = toLaneletPose(pose, id);\n    if (lanelet_pose) {\n      return lanelet_pose;\n    }\n  }\n  return boost::none;\n}\n\nboost::optional<traffic_simulator_msgs::msg::LaneletPose> HdMapUtils::toLaneletPose(\n  geometry_msgs::msg::Pose pose, std::int64_t lanelet_id)\n{\n  const auto spline = getCenterPointsSpline(lanelet_id);\n  const auto s = spline->getSValue(pose);\n  if (!s) {\n    return boost::none;\n  }\n  auto pose_on_centerline = spline->getPose(s.get());\n  auto rpy = quaternion_operation::convertQuaternionToEulerAngle(\n    quaternion_operation::getRotation(pose_on_centerline.orientation, pose.orientation));\n  double offset = spline->getSquaredDistanceIn2D(pose.position, s.get());\n  traffic_simulator_msgs::msg::LaneletPose lanelet_pose;\n  lanelet_pose.lanelet_id = lanelet_id;\n  lanelet_pose.s = s.get();\n  lanelet_pose.offset = offset;\n  lanelet_pose.rpy = rpy;\n  return lanelet_pose;\n}\n\nboost::optional<traffic_simulator_msgs::msg::LaneletPose> HdMapUtils::toLaneletPose(\n  geometry_msgs::msg::Pose pose, const traffic_simulator_msgs::msg::BoundingBox & bbox,\n  bool include_crosswalk)\n{\n  const auto lanelet_id = matchToLane(pose, bbox, include_crosswalk);\n  if (!lanelet_id) {\n    return toLaneletPose(pose, include_crosswalk);\n  }\n  const auto pose_in_target_lanelet = toLaneletPose(pose, lanelet_id.get());\n  if (pose_in_target_lanelet) {\n    return pose_in_target_lanelet;\n  }\n  const auto previous = getPreviousLaneletIds(lanelet_id.get());\n  for (const auto id : previous) {\n    const auto pose_in_previous = toLaneletPose(pose, id);\n    if (pose_in_previous) {\n      return pose_in_previous;\n    }\n  }\n  const auto next = getNextLaneletIds(lanelet_id.get());\n  for (const auto id : previous) {\n    const auto pose_in_next = toLaneletPose(pose, id);\n    if (pose_in_next) {\n      return pose_in_next;\n    }\n  }\n  return toLaneletPose(pose, include_crosswalk);\n}\n\nboost::optional<std::int64_t> HdMapUtils::getClosestLaneletId(\n  geometry_msgs::msg::Pose pose, double distance_thresh, bool include_crosswalk)\n{\n  lanelet::BasicPoint2d search_point(pose.position.x, pose.position.y);\n  std::vector<std::pair<double, lanelet::Lanelet>> nearest_lanelet =\n    lanelet::geometry::findNearest(lanelet_map_ptr_->laneletLayer, search_point, 3);\n  if (include_crosswalk) {\n    if (nearest_lanelet.empty()) {\n      return boost::none;\n    }\n    if (nearest_lanelet.front().first > distance_thresh) {\n      return boost::none;\n    }\n    lanelet::Lanelet closest_lanelet;\n    closest_lanelet = nearest_lanelet.front().second;\n    return closest_lanelet.id();\n  } else {\n    const auto nearest_road_lanelet =\n      excludeSubtypeLanelets(nearest_lanelet, lanelet::AttributeValueString::Crosswalk);\n    if (nearest_road_lanelet.empty()) {\n      return boost::none;\n    }\n    if (nearest_road_lanelet.front().first > distance_thresh) {\n      return boost::none;\n    }\n    lanelet::Lanelet closest_lanelet;\n    closest_lanelet = nearest_road_lanelet.front().second;\n    return closest_lanelet.id();\n  }\n}\n\ndouble HdMapUtils::getSpeedLimit(std::vector<std::int64_t> lanelet_ids)\n{\n  std::vector<double> limits;\n  if (lanelet_ids.empty()) {\n    THROW_SEMANTIC_ERROR(\"size of the vector lanelet ids should be more than 1\");\n  }\n  for (auto itr = lanelet_ids.begin(); itr != lanelet_ids.end(); itr++) {\n    const auto lanelet = lanelet_map_ptr_->laneletLayer.get(*itr);\n    const auto limit = traffic_rules_vehicle_ptr_->speedLimit(lanelet);\n    limits.push_back(lanelet::units::KmHQuantity(limit.speedLimit).value() / 3.6);\n  }\n  return *std::min_element(limits.begin(), limits.end());\n}\n\nboost::optional<int64_t> HdMapUtils::getLaneChangeableLaneletId(\n  std::int64_t lanelet_id, traffic_simulator::lane_change::Direction direction, uint8_t shift)\n{\n  if (shift == 0) {\n    return getLaneChangeableLaneletId(\n      lanelet_id, traffic_simulator::lane_change::Direction::STRAIGHT);\n  } else {\n    std::int64_t reference_id = lanelet_id;\n    for (uint8_t i = 0; i < shift; i++) {\n      auto id = getLaneChangeableLaneletId(reference_id, direction);\n      if (!id) {\n        return boost::none;\n      } else {\n        reference_id = id.get();\n      }\n      if (i == (shift - 1)) {\n        return reference_id;\n      }\n    }\n  }\n  return boost::none;\n}\n\nboost::optional<std::int64_t> HdMapUtils::getLaneChangeableLaneletId(\n  std::int64_t lanelet_id, traffic_simulator::lane_change::Direction direction)\n{\n  const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n  boost::optional<std::int64_t> target = boost::none;\n  switch (direction) {\n    case traffic_simulator::lane_change::Direction::STRAIGHT:\n      target = lanelet.id();\n      break;\n    case traffic_simulator::lane_change::Direction::LEFT:\n      if (vehicle_routing_graph_ptr_->left(lanelet)) {\n        target = vehicle_routing_graph_ptr_->left(lanelet)->id();\n      }\n      break;\n    case traffic_simulator::lane_change::Direction::RIGHT:\n      if (vehicle_routing_graph_ptr_->right(lanelet)) {\n        target = vehicle_routing_graph_ptr_->right(lanelet)->id();\n      }\n      break;\n  }\n  return target;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getPreviousLanelets(std::int64_t lanelet_id, double distance)\n{\n  std::vector<std::int64_t> ret;\n  double total_distance = 0.0;\n  ret.push_back(lanelet_id);\n  while (total_distance < distance) {\n    auto ids = getPreviousLaneletIds(lanelet_id, \"straight\");\n    if (ids.size() != 0) {\n      lanelet_id = ids[0];\n      total_distance = total_distance + getLaneletLength(lanelet_id);\n      ret.push_back(lanelet_id);\n      continue;\n    } else {\n      auto else_ids = getPreviousLaneletIds(lanelet_id);\n      if (else_ids.size() != 0) {\n        lanelet_id = else_ids[0];\n        total_distance = total_distance + getLaneletLength(lanelet_id);\n        ret.push_back(lanelet_id);\n        continue;\n      } else {\n        break;\n      }\n    }\n  }\n  return ret;\n}\n\nbool HdMapUtils::isInRoute(std::int64_t lanelet_id, std::vector<std::int64_t> route) const\n{\n  for (const auto id : route) {\n    if (id == lanelet_id) {\n      return true;\n    }\n  }\n  return false;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getFollowingLanelets(\n  std::int64_t lanelet_id, std::vector<std::int64_t> candidate_lanelet_ids, double distance,\n  bool include_self)\n{\n  if (candidate_lanelet_ids.empty()) {\n    return {};\n  }\n  std::vector<std::int64_t> ret;\n  double total_distance = 0.0;\n  bool found = false;\n  for (const auto id : candidate_lanelet_ids) {\n    if (found) {\n      ret.emplace_back(id);\n      total_distance = total_distance + getLaneletLength(id);\n      if (total_distance > distance) {\n        return ret;\n      }\n    }\n    if (id == lanelet_id) {\n      found = true;\n      if (include_self) {\n        ret.emplace_back(id);\n      }\n    }\n  }\n  if (!found) {\n    THROW_SEMANTIC_ERROR(\"lanelet id does not match\");\n  }\n  if (total_distance > distance) {\n    return ret;\n  }\n  std::int64_t end_lanelet = candidate_lanelet_ids[candidate_lanelet_ids.size() - 1];\n  const auto followings = getFollowingLanelets(end_lanelet, distance - total_distance, false);\n  std::copy(followings.begin(), followings.end(), std::back_inserter(ret));\n  return ret;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getFollowingLanelets(\n  std::int64_t lanelet_id, double distance, bool include_self)\n{\n  std::vector<std::int64_t> ret;\n  double total_distance = 0.0;\n  if (include_self) {\n    ret.push_back(lanelet_id);\n  }\n  while (total_distance < distance) {\n    const auto straight_ids = getNextLaneletIds(lanelet_id, \"straight\");\n    if (straight_ids.size() != 0) {\n      lanelet_id = straight_ids[0];\n      total_distance = total_distance + getLaneletLength(lanelet_id);\n      ret.push_back(lanelet_id);\n      continue;\n    }\n    const auto ids = getNextLaneletIds(lanelet_id);\n    if (ids.size() != 0) {\n      lanelet_id = ids[0];\n      total_distance = total_distance + getLaneletLength(lanelet_id);\n      ret.push_back(lanelet_id);\n      continue;\n    } else {\n      break;\n    }\n  }\n  return ret;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getRoute(\n  std::int64_t from_lanelet_id, std::int64_t to_lanelet_id)\n{\n  if (route_cache_.exists(from_lanelet_id, to_lanelet_id)) {\n    return route_cache_.getRoute(from_lanelet_id, to_lanelet_id);\n  }\n  std::vector<std::int64_t> ret;\n  const auto lanelet = lanelet_map_ptr_->laneletLayer.get(from_lanelet_id);\n  const auto to_lanelet = lanelet_map_ptr_->laneletLayer.get(to_lanelet_id);\n  lanelet::Optional<lanelet::routing::Route> route =\n    vehicle_routing_graph_ptr_->getRoute(lanelet, to_lanelet, 0, false);\n  if (!route) {\n    route_cache_.appendData(from_lanelet_id, to_lanelet_id, ret);\n    return ret;\n  }\n  lanelet::routing::LaneletPath shortest_path = route->shortestPath();\n  if (shortest_path.empty()) {\n    route_cache_.appendData(from_lanelet_id, to_lanelet_id, ret);\n    return ret;\n  }\n  for (auto lane_itr = shortest_path.begin(); lane_itr != shortest_path.end(); lane_itr++) {\n    ret.push_back(lane_itr->id());\n  }\n  route_cache_.appendData(from_lanelet_id, to_lanelet_id, ret);\n  return ret;\n}\n\nstd::shared_ptr<traffic_simulator::math::CatmullRomSpline> HdMapUtils::getCenterPointsSpline(\n  std::int64_t lanelet_id)\n{\n  getCenterPoints(lanelet_id);\n  return center_points_cache_.getCenterPointsSpline(lanelet_id);\n}\n\nstd::vector<geometry_msgs::msg::Point> HdMapUtils::getCenterPoints(\n  std::vector<std::int64_t> lanelet_ids)\n{\n  std::vector<geometry_msgs::msg::Point> ret;\n  if (lanelet_ids.empty()) {\n    return ret;\n  }\n  for (const auto lanelet_id : lanelet_ids) {\n    std::vector<geometry_msgs::msg::Point> center_points = getCenterPoints(lanelet_id);\n    std::copy(center_points.begin(), center_points.end(), std::back_inserter(ret));\n  }\n  return ret;\n}\n\nstd::vector<geometry_msgs::msg::Point> HdMapUtils::getCenterPoints(std::int64_t lanelet_id)\n{\n  std::vector<geometry_msgs::msg::Point> ret;\n  if (!lanelet_map_ptr_) {\n    THROW_SIMULATION_ERROR(\"lanelet map is null pointer\");\n  }\n  if (lanelet_map_ptr_->laneletLayer.empty()) {\n    THROW_SIMULATION_ERROR(\"lanelet layer is empty\");\n  }\n  if (center_points_cache_.exists(lanelet_id)) {\n    return center_points_cache_.getCenterPoints(lanelet_id);\n  }\n\n  const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n  const auto centerline = lanelet.centerline();\n  for (const auto & point : centerline) {\n    geometry_msgs::msg::Point p;\n    p.x = point.x();\n    p.y = point.y();\n    p.z = point.z();\n    ret.push_back(p);\n  }\n  if (static_cast<int>(ret.size()) == 2) {\n    const auto p0 = ret[0];\n    const auto p2 = ret[1];\n    geometry_msgs::msg::Point p1;\n    p1.x = (p0.x + p2.x) * 0.5;\n    p1.y = (p0.y + p2.y) * 0.5;\n    p1.z = (p0.z + p2.z) * 0.5;\n    ret.clear();\n    ret.push_back(p0);\n    ret.push_back(p1);\n    ret.push_back(p2);\n  }\n  center_points_cache_.appendData(lanelet_id, ret);\n  return ret;\n}\n\ndouble HdMapUtils::getLaneletLength(std::int64_t lanelet_id)\n{\n  if (lanelet_length_cache_.exists(lanelet_id)) {\n    return lanelet_length_cache_.getLength(lanelet_id);\n  }\n  double ret = lanelet::utils::getLaneletLength2d(lanelet_map_ptr_->laneletLayer.get(lanelet_id));\n  lanelet_length_cache_.appendData(lanelet_id, ret);\n  return ret;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getPreviousLaneletIds(std::int64_t lanelet_id) const\n{\n  std::vector<std::int64_t> ret;\n  const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n  const auto previous_lanelets = vehicle_routing_graph_ptr_->previous(lanelet);\n  for (const auto & llt : previous_lanelets) {\n    ret.push_back(llt.id());\n  }\n  return ret;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getPreviousLaneletIds(\n  std::int64_t lanelet_id, std::string turn_direction)\n{\n  std::vector<std::int64_t> ret;\n  const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n  const auto previous_lanelets = vehicle_routing_graph_ptr_->previous(lanelet);\n  for (const auto & llt : previous_lanelets) {\n    const std::string turn_direction_llt = llt.attributeOr(\"turn_direction\", \"else\");\n    if (turn_direction_llt == turn_direction) {\n      ret.push_back(llt.id());\n    }\n  }\n  return ret;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getNextLaneletIds(std::int64_t lanelet_id) const\n{\n  std::vector<std::int64_t> ret;\n  const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n  const auto following_lanelets = vehicle_routing_graph_ptr_->following(lanelet);\n  for (const auto & llt : following_lanelets) {\n    ret.push_back(llt.id());\n  }\n  return ret;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getNextLaneletIds(\n  std::int64_t lanelet_id, std::string turn_direction)\n{\n  std::vector<std::int64_t> ret;\n  const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n  const auto following_lanelets = vehicle_routing_graph_ptr_->following(lanelet);\n  for (const auto & llt : following_lanelets) {\n    const std::string turn_direction_llt = llt.attributeOr(\"turn_direction\", \"else\");\n    if (turn_direction_llt == turn_direction) {\n      ret.push_back(llt.id());\n    }\n  }\n  return ret;\n}\n\nconst std::vector<std::int64_t> HdMapUtils::getTrafficLightIds() const\n{\n  std::vector<std::int64_t> ret;\n  lanelet::ConstLanelets all_lanelets = lanelet::utils::query::laneletLayer(lanelet_map_ptr_);\n  auto autoware_traffic_lights = lanelet::utils::query::autowareTrafficLights(all_lanelets);\n  for (const auto light : autoware_traffic_lights) {\n    for (auto light_string : light->lightBulbs()) {\n      if (light_string.hasAttribute(\"traffic_light_id\")) {\n        auto id = light_string.attribute(\"traffic_light_id\").asId();\n        if (id) {\n          ret.emplace_back(id.get());\n        }\n      }\n    }\n  }\n  return ret;\n}\n\nconst boost::optional<geometry_msgs::msg::Point> HdMapUtils::getTrafficLightBulbPosition(\n  std::int64_t traffic_light_id, traffic_simulator::TrafficLightColor color) const\n{\n  if (color == traffic_simulator::TrafficLightColor::NONE) {\n    return boost::none;\n  }\n  lanelet::ConstLanelets all_lanelets = lanelet::utils::query::laneletLayer(lanelet_map_ptr_);\n  auto autoware_traffic_lights = lanelet::utils::query::autowareTrafficLights(all_lanelets);\n  for (const auto light : autoware_traffic_lights) {\n    for (auto light_string : light->lightBulbs()) {\n      if (light_string.hasAttribute(\"traffic_light_id\")) {\n        auto id = light_string.attribute(\"traffic_light_id\").asId();\n        if (id) {\n          if (id.get() == traffic_light_id) {\n            const auto light_bulbs = light->lightBulbs();\n            for (auto ls : light_bulbs) {\n              lanelet::ConstLineString3d l = static_cast<lanelet::ConstLineString3d>(ls);\n              for (auto pt : l) {\n                if (pt.hasAttribute(\"color\")) {\n                  std::string color_string;\n                  switch (color) {\n                    case traffic_simulator::TrafficLightColor::GREEN:\n                      color_string = \"green\";\n                      break;\n                    case traffic_simulator::TrafficLightColor::YELLOW:\n                      color_string = \"yellow\";\n                      break;\n                    case traffic_simulator::TrafficLightColor::RED:\n                      color_string = \"red\";\n                      break;\n                    case traffic_simulator::TrafficLightColor::NONE:\n                      return boost::none;\n                  }\n                  lanelet::Attribute attr = pt.attribute(\"color\");\n                  if (attr.value().compare(color_string) == 0) {\n                    geometry_msgs::msg::Point point;\n                    point.x = pt.x();\n                    point.y = pt.y();\n                    point.z = pt.z();\n                    return point;\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  return boost::none;\n}\n\nboost::optional<std::pair<traffic_simulator::math::HermiteCurve, double>>\nHdMapUtils::getLaneChangeTrajectory(\n  const geometry_msgs::msg::Pose & from_pose,\n  const traffic_simulator::lane_change::Parameter & lane_change_parameter,\n  double maximum_curvature_threshold, double target_trajectory_length,\n  double forward_distance_threshold)\n{\n  double to_length = getLaneletLength(lane_change_parameter.target.lanelet_id);\n  std::vector<double> evaluation, target_s;\n  std::vector<traffic_simulator::math::HermiteCurve> curves;\n\n  for (double to_s = 0; to_s < to_length; to_s = to_s + 1.0) {\n    auto goal_pose = toMapPose(lane_change_parameter.target.lanelet_id, to_s, 0);\n    if (\n      traffic_simulator::math::getRelativePose(from_pose, goal_pose.pose).position.x <=\n      forward_distance_threshold) {\n      continue;\n    }\n    double start_to_goal_distance = std::sqrt(\n      std::pow(from_pose.position.x - goal_pose.pose.position.x, 2) +\n      std::pow(from_pose.position.y - goal_pose.pose.position.y, 2) +\n      std::pow(from_pose.position.z - goal_pose.pose.position.z, 2));\n    traffic_simulator_msgs::msg::LaneletPose to_pose;\n    to_pose.lanelet_id = lane_change_parameter.target.lanelet_id;\n    to_pose.s = to_s;\n    auto traj = getLaneChangeTrajectory(\n      from_pose, to_pose, lane_change_parameter.trajectory_shape, start_to_goal_distance * 0.5);\n    if (traj.getMaximum2DCurvature() < maximum_curvature_threshold) {\n      double eval = std::fabs(target_trajectory_length - traj.getLength());\n      evaluation.push_back(eval);\n      curves.push_back(traj);\n      target_s.push_back(to_s);\n    }\n  }\n  if (evaluation.empty()) {\n    return boost::none;\n  }\n  std::vector<double>::iterator min_itr = std::min_element(evaluation.begin(), evaluation.end());\n  size_t min_index = std::distance(evaluation.begin(), min_itr);\n  return std::make_pair(curves[min_index], target_s[min_index]);\n}\n\ntraffic_simulator::math::HermiteCurve HdMapUtils::getLaneChangeTrajectory(\n  const geometry_msgs::msg::Pose & from_pose,\n  const traffic_simulator_msgs::msg::LaneletPose & to_pose,\n  const traffic_simulator::lane_change::TrajectoryShape trajectory_shape,\n  double tangent_vector_size)\n{\n  geometry_msgs::msg::Vector3 start_vec;\n  geometry_msgs::msg::Vector3 to_vec;\n  geometry_msgs::msg::Pose goal_pose =\n    toMapPose(to_pose.lanelet_id, to_pose.s, to_pose.offset).pose;\n  switch (trajectory_shape) {\n    case traffic_simulator::lane_change::TrajectoryShape::CUBIC:\n      start_vec = getVectorFromPose(from_pose, tangent_vector_size);\n      if (getTangentVector(to_pose.lanelet_id, to_pose.s)) {\n        to_vec = getTangentVector(to_pose.lanelet_id, to_pose.s).get();\n      } else {\n        THROW_SIMULATION_ERROR(\n          \"Failed to calculate tangent vector at lanelet_id : \", to_pose.lanelet_id,\n          \" s : \", to_pose.s);\n      }\n      break;\n    case traffic_simulator::lane_change::TrajectoryShape::LINEAR:\n      start_vec.x = (goal_pose.position.x - from_pose.position.x);\n      start_vec.y = (goal_pose.position.y - from_pose.position.y);\n      start_vec.z = (goal_pose.position.z - from_pose.position.z);\n      to_vec = start_vec;\n      tangent_vector_size = 1;\n      break;\n  }\n  geometry_msgs::msg::Vector3 goal_vec = to_vec;\n  goal_vec.x = goal_vec.x * tangent_vector_size;\n  goal_vec.y = goal_vec.y * tangent_vector_size;\n  goal_vec.z = goal_vec.z * tangent_vector_size;\n  traffic_simulator::math::HermiteCurve curve(from_pose, goal_pose, start_vec, goal_vec);\n  return curve;\n}\n\ngeometry_msgs::msg::Vector3 HdMapUtils::getVectorFromPose(\n  geometry_msgs::msg::Pose pose, double magnitude)\n{\n  geometry_msgs::msg::Vector3 dir =\n    quaternion_operation::convertQuaternionToEulerAngle(pose.orientation);\n  geometry_msgs::msg::Vector3 vector;\n  vector.x = magnitude * std::cos(dir.z);\n  vector.y = magnitude * std::sin(dir.z);\n  vector.z = 0;\n  return vector;\n}\n\nbool HdMapUtils::isInLanelet(std::int64_t lanelet_id, double s)\n{\n  const auto spline = getCenterPointsSpline(lanelet_id);\n  double l = spline->getLength();\n  if (s > l) {\n    return false;\n  } else if (s < 0) {\n    return false;\n  }\n  return true;\n}\n\nstd::vector<geometry_msgs::msg::Point> HdMapUtils::toMapPoints(\n  std::int64_t lanelet_id, std::vector<double> s)\n{\n  std::vector<geometry_msgs::msg::Point> ret;\n  const auto spline = getCenterPointsSpline(lanelet_id);\n  for (const auto & s_value : s) {\n    ret.push_back(spline->getPoint(s_value));\n  }\n  return ret;\n}\n\ngeometry_msgs::msg::PoseStamped HdMapUtils::toMapPose(\n  std::int64_t lanelet_id, double s, double offset, geometry_msgs::msg::Quaternion quat)\n{\n  geometry_msgs::msg::PoseStamped ret;\n  ret.header.frame_id = \"map\";\n  const auto spline = getCenterPointsSpline(lanelet_id);\n  ret.pose = spline->getPose(s);\n  const auto normal_vec = spline->getNormalVector(s);\n  const auto diff = traffic_simulator::math::normalize(normal_vec) * offset;\n  ret.pose.position = ret.pose.position + diff;\n  const auto tangent_vec = spline->getTangentVector(s);\n  geometry_msgs::msg::Vector3 rpy;\n  rpy.x = 0.0;\n  rpy.y = 0.0;\n  rpy.z = std::atan2(tangent_vec.y, tangent_vec.x);\n  ret.pose.orientation = quaternion_operation::convertEulerAngleToQuaternion(rpy) * quat;\n  return ret;\n}\n\ngeometry_msgs::msg::PoseStamped HdMapUtils::toMapPose(\n  traffic_simulator_msgs::msg::LaneletPose lanelet_pose)\n{\n  return toMapPose(\n    lanelet_pose.lanelet_id, lanelet_pose.s, lanelet_pose.offset,\n    quaternion_operation::convertEulerAngleToQuaternion(lanelet_pose.rpy));\n}\n\ngeometry_msgs::msg::PoseStamped HdMapUtils::toMapPose(\n  std::int64_t lanelet_id, double s, double offset)\n{\n  traffic_simulator_msgs::msg::LaneletPose lanelet_pose;\n  lanelet_pose.lanelet_id = lanelet_id;\n  lanelet_pose.s = s;\n  lanelet_pose.offset = offset;\n  return toMapPose(lanelet_pose);\n}\n\nboost::optional<geometry_msgs::msg::Vector3> HdMapUtils::getTangentVector(\n  std::int64_t lanelet_id, double s)\n{\n  return getCenterPointsSpline(lanelet_id)->getTangentVector(s);\n}\n\nbool HdMapUtils::canChangeLane(std::int64_t from_lanelet_id, std::int64_t to_lanelet_id)\n{\n  const auto from_lanelet = lanelet_map_ptr_->laneletLayer.get(from_lanelet_id);\n  const auto to_lanelet = lanelet_map_ptr_->laneletLayer.get(to_lanelet_id);\n  return traffic_rules_vehicle_ptr_->canChangeLane(from_lanelet, to_lanelet);\n}\n\nboost::optional<double> HdMapUtils::getLongitudinalDistance(\n  traffic_simulator_msgs::msg::LaneletPose from, traffic_simulator_msgs::msg::LaneletPose to)\n{\n  return getLongitudinalDistance(from.lanelet_id, from.s, to.lanelet_id, to.s);\n}\n\nboost::optional<double> HdMapUtils::getLongitudinalDistance(\n  std::int64_t from_lanelet_id, double from_s, std::int64_t to_lanelet_id, double to_s)\n{\n  if (from_lanelet_id == to_lanelet_id) {\n    if (from_s > to_s) {\n      return boost::none;\n    } else {\n      return to_s - from_s;\n    }\n  }\n  const auto route = getRoute(from_lanelet_id, to_lanelet_id);\n  if (route.empty()) {\n    return boost::none;\n  }\n  double distance = 0;\n  for (const auto lanelet_id : route) {\n    if (lanelet_id == from_lanelet_id) {\n      distance = getLaneletLength(from_lanelet_id) - from_s;\n    } else if (lanelet_id == to_lanelet_id) {\n      distance = distance + to_s;\n    } else {\n      distance = distance + getLaneletLength(lanelet_id);\n    }\n  }\n  return distance;\n}\n\nconst autoware_auto_mapping_msgs::msg::HADMapBin HdMapUtils::toMapBin()\n{\n  std::stringstream ss;\n  boost::archive::binary_oarchive oa(ss);\n  oa << *lanelet_map_ptr_;\n  auto id_counter = lanelet::utils::getId();\n  oa << id_counter;\n  std::string tmp_str = ss.str();\n  autoware_auto_mapping_msgs::msg::HADMapBin msg;\n  msg.data.clear();\n  msg.data.resize(tmp_str.size());\n  msg.data.assign(tmp_str.begin(), tmp_str.end());\n  msg.header.frame_id = \"map\";\n  return msg;\n}\n\nvoid HdMapUtils::insertMarkerArray(\n  visualization_msgs::msg::MarkerArray & a1, const visualization_msgs::msg::MarkerArray & a2) const\n{\n  a1.markers.insert(a1.markers.end(), a2.markers.begin(), a2.markers.end());\n}\n\nconst visualization_msgs::msg::MarkerArray HdMapUtils::generateMarker() const\n{\n  visualization_msgs::msg::MarkerArray markers;\n  lanelet::ConstLanelets all_lanelets = lanelet::utils::query::laneletLayer(lanelet_map_ptr_);\n  lanelet::ConstLanelets road_lanelets = lanelet::utils::query::roadLanelets(all_lanelets);\n  lanelet::ConstLanelets crosswalk_lanelets =\n    lanelet::utils::query::crosswalkLanelets(all_lanelets);\n  lanelet::ConstLanelets walkway_lanelets = lanelet::utils::query::walkwayLanelets(all_lanelets);\n  std::vector<lanelet::ConstLineString3d> stop_lines =\n    lanelet::utils::query::stopLinesLanelets(road_lanelets);\n  std::vector<lanelet::AutowareTrafficLightConstPtr> aw_tl_reg_elems =\n    lanelet::utils::query::autowareTrafficLights(all_lanelets);\n  std::vector<lanelet::DetectionAreaConstPtr> da_reg_elems =\n    lanelet::utils::query::detectionAreas(all_lanelets);\n  lanelet::ConstLineStrings3d parking_spaces =\n    lanelet::utils::query::getAllParkingSpaces(lanelet_map_ptr_);\n  lanelet::ConstPolygons3d parking_lots =\n    lanelet::utils::query::getAllParkingLots(lanelet_map_ptr_);\n\n  auto cl_ll_borders = color_utils::fromRgba(1.0, 1.0, 1.0, 0.999);\n  auto cl_road = color_utils::fromRgba(0.2, 0.7, 0.7, 0.3);\n  auto cl_cross = color_utils::fromRgba(0.2, 0.7, 0.2, 0.3);\n  auto cl_stoplines = color_utils::fromRgba(1.0, 0.0, 0.0, 0.5);\n  auto cl_trafficlights = color_utils::fromRgba(0.7, 0.7, 0.7, 0.8);\n  auto cl_detection_areas = color_utils::fromRgba(0.7, 0.7, 0.7, 0.3);\n  auto cl_parking_lots = color_utils::fromRgba(0.7, 0.7, 0.0, 0.3);\n  auto cl_parking_spaces = color_utils::fromRgba(1.0, 0.647, 0.0, 0.6);\n  auto cl_lanelet_id = color_utils::fromRgba(0.8, 0.2, 0.2, 0.999);\n\n  insertMarkerArray(\n    markers,\n    lanelet::visualization::laneletsBoundaryAsMarkerArray(road_lanelets, cl_ll_borders, true));\n  insertMarkerArray(\n    markers,\n    lanelet::visualization::laneletsAsTriangleMarkerArray(\"road_lanelets\", road_lanelets, cl_road));\n  insertMarkerArray(\n    markers, lanelet::visualization::laneletsAsTriangleMarkerArray(\n               \"crosswalk_lanelets\", crosswalk_lanelets, cl_cross));\n  insertMarkerArray(\n    markers, lanelet::visualization::laneletsAsTriangleMarkerArray(\n               \"walkway_lanelets\", walkway_lanelets, cl_cross));\n  insertMarkerArray(markers, lanelet::visualization::laneletDirectionAsMarkerArray(road_lanelets));\n  insertMarkerArray(\n    markers,\n    lanelet::visualization::lineStringsAsMarkerArray(stop_lines, \"stop_lines\", cl_stoplines));\n  insertMarkerArray(\n    markers,\n    lanelet::visualization::autowareTrafficLightsAsMarkerArray(aw_tl_reg_elems, cl_trafficlights));\n  insertMarkerArray(\n    markers, lanelet::visualization::detectionAreasAsMarkerArray(da_reg_elems, cl_detection_areas));\n  insertMarkerArray(\n    markers, lanelet::visualization::parkingLotsAsMarkerArray(parking_lots, cl_parking_lots));\n  insertMarkerArray(\n    markers, lanelet::visualization::parkingSpacesAsMarkerArray(parking_spaces, cl_parking_spaces));\n  insertMarkerArray(\n    markers, lanelet::visualization::generateLaneletIdMarker(road_lanelets, cl_lanelet_id));\n  insertMarkerArray(\n    markers, lanelet::visualization::generateLaneletIdMarker(crosswalk_lanelets, cl_lanelet_id));\n  return markers;\n}\n\nvoid HdMapUtils::overwriteLaneletsCenterline()\n{\n  for (auto & lanelet_obj : lanelet_map_ptr_->laneletLayer) {\n    if (!lanelet_obj.hasCustomCenterline()) {\n      const auto fine_center_line = generateFineCenterline(lanelet_obj, 2.0);\n      lanelet_obj.setCenterline(fine_center_line);\n    }\n  }\n}\n\nstd::pair<size_t, size_t> HdMapUtils::findNearestIndexPair(\n  const std::vector<double> & accumulated_lengths, const double target_length)\n{\n  // List size\n  const auto N = accumulated_lengths.size();\n  // Front\n  if (target_length < accumulated_lengths.at(1)) {\n    return std::make_pair(0, 1);\n  }\n  // Back\n  if (target_length > accumulated_lengths.at(N - 2)) {\n    return std::make_pair(N - 2, N - 1);\n  }\n\n  // Middle\n  for (size_t i = 1; i < N; ++i) {\n    if (\n      accumulated_lengths.at(i - 1) <= target_length &&\n      target_length <= accumulated_lengths.at(i)) {\n      return std::make_pair(i - 1, i);\n    }\n  }\n\n  // Throw an exception because this never happens\n  THROW_SEMANTIC_ERROR(\"findNearestIndexPair(): No nearest point found.\");\n}\n\nconst std::unordered_map<std::int64_t, std::vector<std::int64_t>>\nHdMapUtils::getRightOfWayLaneletIds(std::vector<std::int64_t> lanelet_ids) const\n{\n  std::unordered_map<std::int64_t, std::vector<std::int64_t>> ret;\n  for (const auto & lanelet_id : lanelet_ids) {\n    ret.emplace(lanelet_id, getRightOfWayLaneletIds(lanelet_id));\n  }\n  return ret;\n}\n\nconst std::vector<std::int64_t> HdMapUtils::getRightOfWayLaneletIds(std::int64_t lanelet_id) const\n{\n  std::vector<std::int64_t> ret;\n  const auto & assigned_lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n  const auto right_of_ways = assigned_lanelet.regulatoryElementsAs<lanelet::RightOfWay>();\n  for (const auto & right_of_way : right_of_ways) {\n    const auto right_of_Way_lanelets = right_of_way->rightOfWayLanelets();\n    for (const auto & ll : right_of_Way_lanelets) {\n      ret.emplace_back(ll.id());\n    }\n  }\n  return ret;\n}\n\nstd::vector<std::shared_ptr<const lanelet::TrafficSign>>\nHdMapUtils::getTrafficSignRegElementsOnPath(std::vector<std::int64_t> lanelet_ids) const\n{\n  std::vector<std::shared_ptr<const lanelet::TrafficSign>> ret;\n  for (const auto & lanelet_id : lanelet_ids) {\n    const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n    const auto traffic_signs = lanelet.regulatoryElementsAs<const lanelet::TrafficSign>();\n    for (const auto traffic_sign : traffic_signs) {\n      ret.push_back(traffic_sign);\n    }\n  }\n  return ret;\n}\n\nstd::vector<std::shared_ptr<const lanelet::autoware::AutowareTrafficLight>>\nHdMapUtils::getTrafficLightRegElementsOnPath(const std::vector<std::int64_t> & lanelet_ids) const\n{\n  std::vector<std::shared_ptr<const lanelet::autoware::AutowareTrafficLight>> ret;\n  for (const auto & lanelet_id : lanelet_ids) {\n    const auto lanelet = lanelet_map_ptr_->laneletLayer.get(lanelet_id);\n    const auto traffic_lights =\n      lanelet.regulatoryElementsAs<const lanelet::autoware::AutowareTrafficLight>();\n    for (const auto traffic_light : traffic_lights) {\n      ret.push_back(traffic_light);\n    }\n  }\n  return ret;\n}\n\nstd::vector<lanelet::ConstLineString3d> HdMapUtils::getStopLinesOnPath(\n  std::vector<std::int64_t> lanelet_ids)\n{\n  std::vector<lanelet::ConstLineString3d> ret;\n  const auto traffic_signs = getTrafficSignRegElementsOnPath(lanelet_ids);\n  for (const auto & traffic_sign : traffic_signs) {\n    if (traffic_sign->type() != \"stop_sign\") {\n      continue;\n    }\n    for (const auto & stop_line : traffic_sign->refLines()) {\n      ret.emplace_back(stop_line);\n    }\n  }\n  return ret;\n}\n\nstd::vector<lanelet::AutowareTrafficLightConstPtr> HdMapUtils::getTrafficLights(\n  const std::int64_t traffic_light_id) const\n{\n  std::vector<lanelet::AutowareTrafficLightConstPtr> ret;\n  lanelet::ConstLanelets all_lanelets = lanelet::utils::query::laneletLayer(lanelet_map_ptr_);\n  auto autoware_traffic_lights = lanelet::utils::query::autowareTrafficLights(all_lanelets);\n  for (const auto light : autoware_traffic_lights) {\n    for (auto light_string : light->lightBulbs()) {\n      if (light_string.hasAttribute(\"traffic_light_id\")) {\n        auto id = light_string.attribute(\"traffic_light_id\").asId();\n        if (id == traffic_light_id) {\n          ret.emplace_back(light);\n        }\n      }\n    }\n  }\n  if (ret.empty()) {\n    THROW_SEMANTIC_ERROR(\"traffic_light_id does not match. ID : \", traffic_light_id);\n  }\n  return ret;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getTrafficLightStopLineIds(\n  const std::int64_t & traffic_light_id) const\n{\n  std::vector<std::int64_t> ret;\n  const auto traffic_lights = getTrafficLights(traffic_light_id);\n  for (const auto & traffic_light : traffic_lights) {\n    if (traffic_light->stopLine()) {\n      ret.emplace_back(traffic_light->stopLine()->id());\n    }\n  }\n  return ret;\n}\n\nstd::vector<std::vector<geometry_msgs::msg::Point>> HdMapUtils::getTrafficLightStopLinesPoints(\n  std::int64_t traffic_light_id) const\n{\n  std::vector<std::vector<geometry_msgs::msg::Point>> ret;\n  const auto traffic_lights = getTrafficLights(traffic_light_id);\n  for (const auto & traffic_light : traffic_lights) {\n    ret.emplace_back(std::vector<geometry_msgs::msg::Point>{});\n    const auto stop_line = traffic_light->stopLine();\n    if (stop_line) {\n      auto & current_stop_line = ret.back();\n      for (const auto point : stop_line.get()) {\n        geometry_msgs::msg::Point p;\n        p.x = point.x();\n        p.y = point.y();\n        p.z = point.z();\n        current_stop_line.emplace_back(p);\n      }\n    }\n  }\n  return ret;\n}\n\nconst std::vector<geometry_msgs::msg::Point> HdMapUtils::getStopLinePolygon(std::int64_t lanelet_id)\n{\n  std::vector<geometry_msgs::msg::Point> points;\n  const auto stop_line = lanelet_map_ptr_->lineStringLayer.get(lanelet_id);\n  for (const auto point : stop_line) {\n    geometry_msgs::msg::Point p;\n    p.x = point.x();\n    p.y = point.y();\n    p.z = point.z();\n    points.emplace_back(p);\n  }\n  return points;\n}\n\nconst std::vector<std::int64_t> HdMapUtils::getTrafficLightIdsOnPath(\n  const std::vector<std::int64_t> & route_lanelets) const\n{\n  std::vector<std::int64_t> ret;\n  auto traffic_lights = getTrafficLightRegElementsOnPath(route_lanelets);\n  for (const auto traffic_light : traffic_lights) {\n    for (auto light_string : traffic_light->lightBulbs()) {\n      if (light_string.hasAttribute(\"traffic_light_id\")) {\n        auto id = light_string.attribute(\"traffic_light_id\").asId();\n        if (id) {\n          ret.emplace_back(id.get());\n        }\n      }\n    }\n  }\n  return ret;\n}\n\nconst boost::optional<double> HdMapUtils::getDistanceToTrafficLightStopLine(\n  const std::vector<std::int64_t> & route_lanelets,\n  const std::vector<geometry_msgs::msg::Point> & waypoints) const\n{\n  auto traffic_light_ids = getTrafficLightIdsOnPath(route_lanelets);\n  if (traffic_light_ids.size() == 0) {\n    return boost::none;\n  }\n  std::set<double> collision_points;\n  for (const auto id : traffic_light_ids) {\n    const auto collision_point = getDistanceToTrafficLightStopLine(waypoints, id);\n    if (collision_point) {\n      collision_points.insert(collision_point.get());\n    }\n  }\n  if (collision_points.empty()) {\n    return boost::none;\n  }\n  return *collision_points.begin();\n}\n\nconst boost::optional<double> HdMapUtils::getDistanceToTrafficLightStopLine(\n  const std::vector<geometry_msgs::msg::Point> & waypoints,\n  const std::int64_t & traffic_light_id) const\n{\n  if (waypoints.empty()) {\n    return boost::none;\n  }\n  traffic_simulator::math::CatmullRomSpline spline(waypoints);\n  const auto stop_lines = getTrafficLightStopLinesPoints(traffic_light_id);\n  for (const auto & stop_line : stop_lines) {\n    const auto collision_point = spline.getCollisionPointIn2D(stop_line);\n    if (collision_point) {\n      return collision_point;\n    }\n  }\n  return boost::none;\n}\n\nboost::optional<double> HdMapUtils::getDistanceToStopLine(\n  const std::vector<std::int64_t> & route_lanelets,\n  const std::vector<geometry_msgs::msg::Point> & waypoints)\n{\n  if (waypoints.empty()) {\n    return boost::none;\n  }\n  std::set<double> collision_points;\n  if (waypoints.empty()) {\n    return boost::none;\n  }\n  traffic_simulator::math::CatmullRomSpline spline(waypoints);\n  const auto stop_lines = getStopLinesOnPath({route_lanelets});\n  for (const auto & stop_line : stop_lines) {\n    std::vector<geometry_msgs::msg::Point> stop_line_points;\n    for (const auto & point : stop_line) {\n      geometry_msgs::msg::Point p;\n      p.x = point.x();\n      p.y = point.y();\n      p.z = point.z();\n      stop_line_points.emplace_back(p);\n    }\n    const auto collision_point = spline.getCollisionPointIn2D(stop_line_points);\n    if (collision_point) {\n      collision_points.insert(collision_point.get());\n    }\n  }\n  if (collision_points.empty()) {\n    return boost::none;\n  }\n  return *collision_points.begin();\n}\n\nstd::vector<double> HdMapUtils::calculateSegmentDistances(\n  const lanelet::ConstLineString3d & line_string)\n{\n  std::vector<double> segment_distances;\n  segment_distances.reserve(line_string.size() - 1);\n  for (size_t i = 1; i < line_string.size(); ++i) {\n    const auto distance = lanelet::geometry::distance(line_string[i], line_string[i - 1]);\n    segment_distances.push_back(distance);\n  }\n  return segment_distances;\n}\n\nstd::vector<double> HdMapUtils::calculateAccumulatedLengths(\n  const lanelet::ConstLineString3d & line_string)\n{\n  const auto segment_distances = calculateSegmentDistances(line_string);\n\n  std::vector<double> accumulated_lengths{0};\n  accumulated_lengths.reserve(segment_distances.size() + 1);\n  std::partial_sum(\n    std::begin(segment_distances), std::end(segment_distances),\n    std::back_inserter(accumulated_lengths));\n  return accumulated_lengths;\n}\n\nstd::vector<lanelet::BasicPoint3d> HdMapUtils::resamplePoints(\n  const lanelet::ConstLineString3d & line_string, const int32_t num_segments)\n{\n  // Calculate length\n  const auto line_length = lanelet::geometry::length(line_string);\n\n  // Calculate accumulated lengths\n  const auto accumulated_lengths = calculateAccumulatedLengths(line_string);\n\n  // Create each segment\n  std::vector<lanelet::BasicPoint3d> resampled_points;\n  for (auto i = 0; i <= num_segments; ++i) {\n    // Find two nearest points\n    const double target_length =\n      (static_cast<double>(i) / num_segments) * static_cast<double>(line_length);\n    const auto index_pair = findNearestIndexPair(accumulated_lengths, target_length);\n\n    // Apply linear interpolation\n    const lanelet::BasicPoint3d back_point = line_string[index_pair.first];\n    const lanelet::BasicPoint3d front_point = line_string[index_pair.second];\n    const auto direction_vector = (front_point - back_point);\n\n    const auto back_length = accumulated_lengths.at(index_pair.first);\n    const auto front_length = accumulated_lengths.at(index_pair.second);\n    const auto segment_length = front_length - back_length;\n    const auto target_point =\n      back_point + (direction_vector * (target_length - back_length) / segment_length);\n\n    // Add to list\n    resampled_points.push_back(target_point);\n  }\n  return resampled_points;\n}\n\nlanelet::LineString3d HdMapUtils::generateFineCenterline(\n  const lanelet::ConstLanelet & lanelet_obj, const double resolution)\n{\n  // Get length of longer border\n  const double left_length =\n    static_cast<double>(lanelet::geometry::length(lanelet_obj.leftBound()));\n  const double right_length =\n    static_cast<double>(lanelet::geometry::length(lanelet_obj.rightBound()));\n  const double longer_distance = (left_length > right_length) ? left_length : right_length;\n  const int32_t num_segments =\n    std::max(static_cast<int32_t>(ceil(longer_distance / resolution)), 1);\n\n  // Resample points\n  const auto left_points = resamplePoints(lanelet_obj.leftBound(), num_segments);\n  const auto right_points = resamplePoints(lanelet_obj.rightBound(), num_segments);\n\n  // Create centerline\n  lanelet::LineString3d centerline(lanelet::utils::getId());\n  for (size_t i = 0; i < static_cast<size_t>(num_segments + 1); i++) {\n    // Add ID for the average point of left and right\n    const auto center_basic_point = (right_points.at(i) + left_points.at(i)) / 2.0;\n    const lanelet::Point3d center_point(\n      lanelet::utils::getId(), center_basic_point.x(), center_basic_point.y(),\n      center_basic_point.z());\n    centerline.push_back(center_point);\n  }\n  return centerline;\n}\n\nstd::vector<double> HdMapUtils::calcEuclidDist(\n  const std::vector<double> & x, const std::vector<double> & y, const std::vector<double> & z)\n{\n  std::vector<double> dist_v;\n  dist_v.push_back(0.0);\n  for (size_t i = 0; i < x.size() - 1; ++i) {\n    const double dx = x.at(i + 1) - x.at(i);\n    const double dy = y.at(i + 1) - y.at(i);\n    const double dz = z.at(i + 1) - z.at(i);\n    const double d = std::sqrt(dx * dx + dy * dy + dz * dz);\n    dist_v.push_back(dist_v.at(i) + d);\n  }\n  return dist_v;\n}\n\nstd::vector<lanelet::Lanelet> HdMapUtils::getLanelets(\n  const std::vector<std::int64_t> & lanelet_ids) const\n{\n  std::vector<lanelet::Lanelet> lanelets;\n  for (const auto & id : lanelet_ids) {\n    lanelets.emplace_back(lanelet_map_ptr_->laneletLayer.get(id));\n  }\n  return lanelets;\n}\n\nstd::vector<std::int64_t> HdMapUtils::getLaneletIds(\n  const std::vector<lanelet::Lanelet> & lanelets) const\n{\n  std::vector<std::int64_t> ids;\n  for (const auto & lanelet : lanelets) {\n    ids.emplace_back(lanelet.id());\n  }\n  return ids;\n}\n}  // namespace hdmap_utils\n", "meta": {"hexsha": "c63780f2b6309dd43a99e30179343d0cce31b3c5", "size": 55200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation/traffic_simulator/src/hdmap_utils/hdmap_utils.cpp", "max_stars_repo_name": "Utaro-M/scenario_simulator_v2", "max_stars_repo_head_hexsha": "d029534b3cea0cdb3b3d69a8dc63753ad00f52e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T22:43:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T23:57:53.000Z", "max_issues_repo_path": "simulation/traffic_simulator/src/hdmap_utils/hdmap_utils.cpp", "max_issues_repo_name": "Utaro-M/scenario_simulator_v2", "max_issues_repo_head_hexsha": "d029534b3cea0cdb3b3d69a8dc63753ad00f52e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 140.0, "max_issues_repo_issues_event_min_datetime": "2021-04-13T04:28:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:44:32.000Z", "max_forks_repo_path": "simulation/traffic_simulator/src/hdmap_utils/hdmap_utils.cpp", "max_forks_repo_name": "Utaro-M/scenario_simulator_v2", "max_forks_repo_head_hexsha": "d029534b3cea0cdb3b3d69a8dc63753ad00f52e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T02:24:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T05:16:31.000Z", "avg_line_length": 35.9375, "max_line_length": 100, "alphanum_fraction": 0.7079891304, "num_tokens": 14932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.16207495419501658}}
{"text": "#ifndef STAN_MCMC_HMC_UNIFORM_BASE_STATIC_UNIFORM_HPP\n#define STAN_MCMC_HMC_UNIFORM_BASE_STATIC_UNIFORM_HPP\n\n#include <stan/services/callbacks/logger.hpp>\n#include \"stan/algorithms/hmc/base_hmc.hpp\"\n#include \"stan/algorithms/hmc/hamiltonians/ps_point.hpp\"\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <cmath>\n#include <limits>\n#include <string>\n#include <vector>\n\nnamespace stan {\n\n  namespace mcmc {\n    /**\n     * Hamiltonian Monte Carlo implementation that uniformly samples\n     * from trajectories with a static integration time\n     */\n    template <class Model,\n              template<class, class> class Hamiltonian,\n              template<class> class Integrator,\n              class BaseRNG>\n    class base_static_uniform:\n      public base_hmc<Model, Hamiltonian, Integrator, BaseRNG> {\n    public:\n      base_static_uniform(const Model& model, BaseRNG& rng)\n        : base_hmc<Model, Hamiltonian, Integrator, BaseRNG>(model, rng),\n          T_(1), energy_(0) {\n        update_L_();\n      }\n\n      ~base_static_uniform() {}\n\n      sample\n      transition(sample& init_sample, callbacks::logger& logger) {\n        this->sample_stepsize();\n\n        this->seed(init_sample.cont_params());\n\n        this->hamiltonian_.sample_p(this->z_, this->rand_int_);\n        this->hamiltonian_.init(this->z_, logger);\n\n        ps_point z_init(this->z_);\n        double H0 = this->hamiltonian_.H(this->z_);\n\n        ps_point z_sample(this->z_);\n        double sum_prob = 1;\n        double sum_metro_prob = 1;\n\n        boost::random::uniform_int_distribution<> uniform(0, L_ - 1);\n        int Lp = uniform(this->rand_int_);\n\n        for (int l = 0; l < Lp; ++l) {\n          this->integrator_.evolve(this->z_, this->hamiltonian_,\n                                   -this->epsilon_,\n                                   logger);\n\n          double h = this->hamiltonian_.H(this->z_);\n          if (boost::math::isnan(h))\n            h = std::numeric_limits<double>::infinity();\n\n          double prob = std::exp(H0 - h);\n          sum_prob += prob;\n          sum_metro_prob += prob > 1 ? 1 : prob;\n\n          if (this->rand_uniform_() < prob / sum_prob)\n            z_sample = this->z_;\n        }\n\n        this->z_.ps_point::operator=(z_init);\n\n        for (int l = 0; l < L_ - 1 - Lp; ++l) {\n          this->integrator_.evolve(this->z_, this->hamiltonian_,\n                                   this->epsilon_,\n                                   logger);\n\n          double h = this->hamiltonian_.H(this->z_);\n          if (boost::math::isnan(h))\n            h = std::numeric_limits<double>::infinity();\n\n          double prob = std::exp(H0 - h);\n          sum_prob += prob;\n          sum_metro_prob += prob > 1 ? 1 : prob;\n\n          if (this->rand_uniform_() < prob / sum_prob)\n            z_sample = this->z_;\n        }\n\n        double accept_prob = sum_metro_prob / static_cast<double>(L_);\n\n        this->z_.ps_point::operator=(z_sample);\n        this->energy_ = this->hamiltonian_.H(this->z_);\n        return sample(this->z_.q,\n                      - this->hamiltonian_.V(this->z_),\n                      accept_prob);\n      }\n\n      void get_sampler_param_names(std::vector<std::string>& names) {\n        names.push_back(\"stepsize__\");\n        names.push_back(\"int_time__\");\n        names.push_back(\"energy__\");\n      }\n\n      void get_sampler_params(std::vector<double>& values) {\n        values.push_back(this->epsilon_);\n        values.push_back(this->T_);\n        values.push_back(this->energy_);\n      }\n\n      void set_nominal_stepsize_and_T(const double e, const double t) {\n        if (e > 0 && t > 0) {\n          this->nom_epsilon_ = e;\n          T_ = t;\n          update_L_();\n        }\n      }\n\n      void set_nominal_stepsize_and_L(const double e, const int l) {\n        if (e > 0 && l > 0) {\n          this->nom_epsilon_ = e;\n          L_ = l;\n          T_ = this->nom_epsilon_ * L_; }\n      }\n\n      void set_T(const double t) {\n        if (t > 0) {\n          T_ = t;\n          update_L_();\n        }\n      }\n\n      void set_nominal_stepsize(const double e) {\n        if (e > 0) {\n          this->nom_epsilon_ = e;\n          update_L_();\n        }\n      }\n\n      double get_T() {\n        return this->T_;\n      }\n\n      int get_L() {\n        return this->L_;\n      }\n\n    protected:\n      double T_;\n      int L_;\n      double energy_;\n\n      void update_L_() {\n        L_ = static_cast<int>(T_ / this->nom_epsilon_);\n        L_ = L_ < 1 ? 1 : L_;\n      }\n    };\n  }  // mcmc\n}  // stan\n#endif\n", "meta": {"hexsha": "287889802efe8cc0d61f4a66201c2f8ec56d350f", "size": 4573, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/algorithms/hmc/static_uniform/base_static_uniform.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/algorithms/hmc/static_uniform/base_static_uniform.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/algorithms/hmc/static_uniform/base_static_uniform.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": 28.2283950617, "max_line_length": 72, "alphanum_fraction": 0.5508418981, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1619307188517742}}
{"text": "#ifdef __cplusplus\n#include <memory>\n#include <vector>\n#include <deque>\n#include <algorithm>\n#include <boost/cstdint.hpp>\n\n#include <opencv2/opencv.hpp>     // C++\n#include \"opencv2/highgui/highgui_c.h\"  // C\n#include \"opencv2/imgproc/imgproc_c.h\"  // C\n\n// Tracker\n#include <opencv2/cudaoptflow.hpp>\n#include <opencv2/cudaimgproc.hpp>\n#include <opencv2/cudaarithm.hpp>\n#include <opencv2/core/cuda.hpp>\n\nclass Tracker_optflow {\npublic:\n  const int gpu_count;\n  const int gpu_id;\n  const int flow_error;\n\n\n  Tracker_optflow(int _gpu_id = 0, int win_size = 9, int max_level = 3, int iterations = 8000, int _flow_error = -1) :\n    gpu_count(cv::cuda::getCudaEnabledDeviceCount()), gpu_id(std::min(_gpu_id, gpu_count-1)),\n    flow_error((_flow_error > 0)? _flow_error:(win_size*4))\n  {\n    int const old_gpu_id = cv::cuda::getDevice();\n    cv::cuda::setDevice(gpu_id);\n\n    stream = cv::cuda::Stream();\n\n    sync_PyrLKOpticalFlow_gpu = cv::cuda::SparsePyrLKOpticalFlow::create();\n    sync_PyrLKOpticalFlow_gpu->setWinSize(cv::Size(win_size, win_size));  // 9, 15, 21, 31\n    sync_PyrLKOpticalFlow_gpu->setMaxLevel(max_level);    // +- 3 pt\n    sync_PyrLKOpticalFlow_gpu->setNumIters(iterations); // 2000, def: 30\n\n    cv::cuda::setDevice(old_gpu_id);\n  }\n\n  // just to avoid extra allocations\n  cv::cuda::GpuMat src_mat_gpu;\n  cv::cuda::GpuMat dst_mat_gpu, dst_grey_gpu;\n  cv::cuda::GpuMat prev_pts_flow_gpu, cur_pts_flow_gpu;\n  cv::cuda::GpuMat status_gpu, err_gpu;\n\n  cv::cuda::GpuMat src_grey_gpu;  // used in both functions\n  cv::Ptr<cv::cuda::SparsePyrLKOpticalFlow> sync_PyrLKOpticalFlow_gpu;\n  cv::cuda::Stream stream;\n\n  std::vector<bbox_t> cur_bbox_vec;\n  std::vector<bool> good_bbox_vec_flags;\n  cv::Mat prev_pts_flow_cpu;\n\n  void update_cur_bbox_vec(std::vector<bbox_t> _cur_bbox_vec)\n  {\n    cur_bbox_vec = _cur_bbox_vec;\n    good_bbox_vec_flags = std::vector<bool>(cur_bbox_vec.size(), true);\n    cv::Mat prev_pts, cur_pts_flow_cpu;\n\n    for (auto &i : cur_bbox_vec) {\n      float x_center = (i.x + i.w / 2.0F);\n      float y_center = (i.y + i.h / 2.0F);\n      prev_pts.push_back(cv::Point2f(x_center, y_center));\n    }\n\n    if (prev_pts.rows == 0)\n      prev_pts_flow_cpu = cv::Mat();\n    else\n      cv::transpose(prev_pts, prev_pts_flow_cpu);\n\n    if (prev_pts_flow_gpu.cols < prev_pts_flow_cpu.cols) {\n      prev_pts_flow_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), prev_pts_flow_cpu.type());\n      cur_pts_flow_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), prev_pts_flow_cpu.type());\n\n      status_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), CV_8UC1);\n      err_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), CV_32FC1);\n    }\n\n    prev_pts_flow_gpu.upload(cv::Mat(prev_pts_flow_cpu), stream);\n  }\n\n\n  void update_tracking_flow(cv::Mat src_mat, std::vector<bbox_t> _cur_bbox_vec)\n  {\n    int const old_gpu_id = cv::cuda::getDevice();\n    if (old_gpu_id != gpu_id)\n      cv::cuda::setDevice(gpu_id);\n\n    if (src_mat.channels() == 3) {\n      if (src_mat_gpu.cols == 0) {\n        src_mat_gpu = cv::cuda::GpuMat(src_mat.size(), src_mat.type());\n        src_grey_gpu = cv::cuda::GpuMat(src_mat.size(), CV_8UC1);\n      }\n\n      update_cur_bbox_vec(_cur_bbox_vec);\n\n      //src_grey_gpu.upload(src_mat, stream); // use BGR\n      src_mat_gpu.upload(src_mat, stream);\n      cv::cuda::cvtColor(src_mat_gpu, src_grey_gpu, CV_BGR2GRAY, 1, stream);\n    }\n    if (old_gpu_id != gpu_id)\n      cv::cuda::setDevice(old_gpu_id);\n  }\n\n\n  std::vector<bbox_t> tracking_flow(cv::Mat dst_mat, bool check_error = true)\n  {\n    if (sync_PyrLKOpticalFlow_gpu.empty()) {\n      std::cout << \"sync_PyrLKOpticalFlow_gpu isn't initialized \\n\";\n      return cur_bbox_vec;\n    }\n\n    int const old_gpu_id = cv::cuda::getDevice();\n    if(old_gpu_id != gpu_id)\n      cv::cuda::setDevice(gpu_id);\n\n    if (dst_mat_gpu.cols == 0) {\n      dst_mat_gpu = cv::cuda::GpuMat(dst_mat.size(), dst_mat.type());\n      dst_grey_gpu = cv::cuda::GpuMat(dst_mat.size(), CV_8UC1);\n    }\n\n    //dst_grey_gpu.upload(dst_mat, stream); // use BGR\n    dst_mat_gpu.upload(dst_mat, stream);\n    cv::cuda::cvtColor(dst_mat_gpu, dst_grey_gpu, CV_BGR2GRAY, 1, stream);\n\n    if (src_grey_gpu.rows != dst_grey_gpu.rows || src_grey_gpu.cols != dst_grey_gpu.cols) {\n      stream.waitForCompletion();\n      src_grey_gpu = dst_grey_gpu.clone();\n      cv::cuda::setDevice(old_gpu_id);\n      return cur_bbox_vec;\n    }\n\n    ////sync_PyrLKOpticalFlow_gpu.sparse(src_grey_gpu, dst_grey_gpu, prev_pts_flow_gpu, cur_pts_flow_gpu, status_gpu, &err_gpu);  // OpenCV 2.4.x\n    sync_PyrLKOpticalFlow_gpu->calc(src_grey_gpu, dst_grey_gpu, prev_pts_flow_gpu, cur_pts_flow_gpu, status_gpu, err_gpu, stream);  // OpenCV 3.x\n\n    cv::Mat cur_pts_flow_cpu;\n    cur_pts_flow_gpu.download(cur_pts_flow_cpu, stream);\n\n    dst_grey_gpu.copyTo(src_grey_gpu, stream);\n\n    cv::Mat err_cpu, status_cpu;\n    err_gpu.download(err_cpu, stream);\n    status_gpu.download(status_cpu, stream);\n\n    stream.waitForCompletion();\n\n    std::vector<bbox_t> result_bbox_vec;\n\n    if (err_cpu.cols == cur_bbox_vec.size() && status_cpu.cols == cur_bbox_vec.size()) \n    {\n      for (size_t i = 0; i < cur_bbox_vec.size(); ++i)\n      {\n        cv::Point2f cur_key_pt = cur_pts_flow_cpu.at<cv::Point2f>(0, i);\n        cv::Point2f prev_key_pt = prev_pts_flow_cpu.at<cv::Point2f>(0, i);\n\n        float moved_x = cur_key_pt.x - prev_key_pt.x;\n        float moved_y = cur_key_pt.y - prev_key_pt.y;\n\n        if (abs(moved_x) < 100 && abs(moved_y) < 100 && good_bbox_vec_flags[i])\n          if (err_cpu.at<float>(0, i) < flow_error && status_cpu.at<unsigned char>(0, i) != 0 &&\n            ((float)cur_bbox_vec[i].x + moved_x) > 0 && ((float)cur_bbox_vec[i].y + moved_y) > 0)\n          {\n            cur_bbox_vec[i].x += moved_x + 0.5;\n            cur_bbox_vec[i].y += moved_y + 0.5;\n            result_bbox_vec.push_back(cur_bbox_vec[i]);\n          }\n          else good_bbox_vec_flags[i] = false;\n        else good_bbox_vec_flags[i] = false;\n\n        //if(!check_error && !good_bbox_vec_flags[i]) result_bbox_vec.push_back(cur_bbox_vec[i]);\n      }\n    }\n\n    cur_pts_flow_gpu.swap(prev_pts_flow_gpu);\n    cur_pts_flow_cpu.copyTo(prev_pts_flow_cpu);\n\n    if (old_gpu_id != gpu_id)\n      cv::cuda::setDevice(old_gpu_id);\n\n    return result_bbox_vec;\n  }\n\n};\n#endif  // __cplusplus", "meta": {"hexsha": "2321245863ea9fee1a3ccfa4865b826c12d2a9d8", "size": 6295, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tracker.hpp", "max_stars_repo_name": "ddavid/kafvio", "max_stars_repo_head_hexsha": "33f36140e392ef5b421d3a323d785749d2aa9a17", "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/tracker.hpp", "max_issues_repo_name": "ddavid/kafvio", "max_issues_repo_head_hexsha": "33f36140e392ef5b421d3a323d785749d2aa9a17", "max_issues_repo_licenses": ["MIT"], "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/tracker.hpp", "max_forks_repo_name": "ddavid/kafvio", "max_forks_repo_head_hexsha": "33f36140e392ef5b421d3a323d785749d2aa9a17", "max_forks_repo_licenses": ["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.8440860215, "max_line_length": 145, "alphanum_fraction": 0.6735504369, "num_tokens": 1870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.16193071223111163}}
{"text": "// Copyright (c) 2010 Satoshi Nakamoto\n// Copyright (c) 2009-2016 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"base58.h\"\n#include \"blind.h\"\n#include \"chain.h\"\n#include \"coins.h\"\n#include \"consensus/validation.h\"\n#include \"core_io.h\"\n#include \"init.h\"\n#include \"issuance.h\"\n#include \"keystore.h\"\n#include \"validation.h\"\n#include \"merkleblock.h\"\n#include \"net.h\"\n#include \"policy/policy.h\"\n#include \"primitives/transaction.h\"\n#include \"rpc/server.h\"\n#include \"script/script.h\"\n#include \"script/script_error.h\"\n#include \"script/sign.h\"\n#include \"script/standard.h\"\n#include \"txmempool.h\"\n#include \"uint256.h\"\n#include \"utilstrencodings.h\"\n#include \"util.h\"\n#ifdef ENABLE_WALLET\n#include \"wallet/wallet.h\"\n#endif\n\n#include <stdint.h>\n\n#include <boost/assign/list_of.hpp>\n#include <secp256k1_rangeproof.h>\n\n#include <univalue.h>\n\nusing namespace std;\n\nstatic secp256k1_context* secp256k1_blind_context = NULL;\n\nclass RPCRawTransaction_ECC_Init {\npublic:\n    RPCRawTransaction_ECC_Init() {\n        assert(secp256k1_blind_context == NULL);\n\n        secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);\n        assert(ctx != NULL);\n\n        secp256k1_blind_context = ctx;\n    }\n\n    ~RPCRawTransaction_ECC_Init() {\n        secp256k1_context *ctx = secp256k1_blind_context;\n        secp256k1_blind_context = NULL;\n\n        if (ctx) {\n            secp256k1_context_destroy(ctx);\n        }\n    }\n};\nstatic RPCRawTransaction_ECC_Init ecc_init_on_load;\n\nvoid ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)\n{\n    txnouttype type;\n    vector<CTxDestination> addresses;\n    int nRequired;\n\n    out.push_back(Pair(\"asm\", ScriptToAsmStr(scriptPubKey)));\n    if (fIncludeHex)\n        out.push_back(Pair(\"hex\", HexStr(scriptPubKey.begin(), scriptPubKey.end())));\n\n    if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {\n        out.push_back(Pair(\"type\", GetTxnOutputType(type)));\n        return;\n    }\n\n    out.push_back(Pair(\"reqSigs\", nRequired));\n    out.push_back(Pair(\"type\", GetTxnOutputType(type)));\n\n    UniValue a(UniValue::VARR);\n    BOOST_FOREACH(const CTxDestination& addr, addresses)\n        a.push_back(CBitcoinAddress(addr).ToString());\n    out.push_back(Pair(\"addresses\", a));\n}\n\nvoid TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)\n{\n    entry.push_back(Pair(\"txid\", tx.GetHash().GetHex()));\n    entry.push_back(Pair(\"hash\", tx.GetHashWithWitness().GetHex()));\n    entry.push_back(Pair(\"withash\", tx.ComputeWitnessHash().GetHex()));\n    entry.push_back(Pair(\"size\", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)));\n    entry.push_back(Pair(\"vsize\", (int)::GetVirtualTransactionSize(tx)));\n    entry.push_back(Pair(\"version\", tx.nVersion));\n    entry.push_back(Pair(\"locktime\", (int64_t)tx.nLockTime));\n    \n    UniValue vin(UniValue::VARR);\n    for (unsigned int i = 0; i < tx.vin.size(); i++) {\n        const CTxIn& txin = tx.vin[i];\n        UniValue in(UniValue::VOBJ);\n        if (tx.IsCoinBase())\n            in.push_back(Pair(\"coinbase\", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));\n        else {\n            in.push_back(Pair(\"txid\", txin.prevout.hash.GetHex()));\n            in.push_back(Pair(\"vout\", (int64_t)txin.prevout.n));\n            UniValue o(UniValue::VOBJ);\n            o.push_back(Pair(\"asm\", ScriptToAsmStr(txin.scriptSig, true)));\n            o.push_back(Pair(\"hex\", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));\n            in.push_back(Pair(\"scriptSig\", o));\n            in.push_back(Pair(\"is_pegin\", txin.m_is_pegin));\n        }\n        if (tx.HasWitness()) {\n            UniValue scriptWitness(UniValue::VARR);\n            UniValue pegin_witness(UniValue::VARR);\n            if (tx.wit.vtxinwit.size() > i) {\n                for (unsigned int j = 0; j < tx.wit.vtxinwit[i].scriptWitness.stack.size(); j++) {\n                    std::vector<unsigned char> item = tx.wit.vtxinwit[i].scriptWitness.stack[j];\n                    scriptWitness.push_back(HexStr(item.begin(), item.end()));\n                }\n                for (unsigned int j = 0; j < tx.wit.vtxinwit[i].m_pegin_witness.stack.size(); j++) {\n                    std::vector<unsigned char> item = tx.wit.vtxinwit[i].m_pegin_witness.stack[j];\n                    pegin_witness.push_back(HexStr(item.begin(), item.end()));\n                }\n            }\n            in.push_back(Pair(\"scriptWitness\", scriptWitness));\n            in.push_back(Pair(\"pegin_witness\", pegin_witness));\n        }\n        const CAssetIssuance& issuance = txin.assetIssuance;\n        if (!issuance.IsNull()) {\n            UniValue issue(UniValue::VOBJ);\n            issue.push_back(Pair(\"assetBlindingNonce\", issuance.assetBlindingNonce.GetHex()));\n            CAsset asset;\n            CAsset token;\n            uint256 entropy;\n            if (issuance.assetBlindingNonce.IsNull()) {\n                GenerateAssetEntropy(entropy, txin.prevout, issuance.assetEntropy);\n                issue.push_back(Pair(\"assetEntropy\", HexStr(entropy)));\n                CalculateAsset(asset, entropy);\n                CalculateReissuanceToken(token, entropy, issuance.nAmount.IsCommitment());\n                issue.push_back(Pair(\"isreissuance\", false));\n                issue.push_back(Pair(\"token\", token.GetHex()));\n            }\n            else {\n                issue.push_back(Pair(\"assetEntropy\", issuance.assetEntropy.GetHex()));\n                issue.push_back(Pair(\"isreissuance\", true));\n                CalculateAsset(asset, issuance.assetEntropy);\n            }\n            issue.push_back(Pair(\"asset\", asset.GetHex()));\n\n            if (issuance.nAmount.IsExplicit()) {\n                issue.push_back(Pair(\"assetamount\", ValueFromAmount(issuance.nAmount.GetAmount())));\n            } else if (issuance.nAmount.IsCommitment()) {\n                issue.push_back(Pair(\"assetamountcommitment\", HexStr(issuance.nAmount.vchCommitment)));\n            }\n            if (issuance.nInflationKeys.IsExplicit()) {\n                issue.push_back(Pair(\"tokenamount\", ValueFromAmount(issuance.nInflationKeys.GetAmount())));\n            } else if (issuance.nInflationKeys.IsCommitment()) {\n                issue.push_back(Pair(\"tokenamountcommitment\", HexStr(issuance.nInflationKeys.vchCommitment)));\n            }\n            in.push_back(Pair(\"issuance\", issue));\n        }\n        in.push_back(Pair(\"sequence\", (int64_t)txin.nSequence));\n        vin.push_back(in);\n    }\n    entry.push_back(Pair(\"vin\", vin));\n    UniValue vout(UniValue::VARR);\n    for (unsigned int i = 0; i < tx.vout.size(); i++) {\n        const CTxOut& txout = tx.vout[i];\n        UniValue out(UniValue::VOBJ);\n        if (txout.nValue.IsExplicit()) {\n            out.push_back(Pair(\"value\", ValueFromAmount(txout.nValue.GetAmount())));\n        } else {\n            int exp;\n            int mantissa;\n            uint64_t minv;\n            uint64_t maxv;\n            const CTxOutWitness* ptxoutwit = tx.wit.vtxoutwit.size() <= i? NULL: &tx.wit.vtxoutwit[i];\n            if (ptxoutwit && secp256k1_rangeproof_info(secp256k1_blind_context, &exp, &mantissa, &minv, &maxv, &ptxoutwit->vchRangeproof[0], ptxoutwit->vchRangeproof.size())) {\n                if (exp == -1) {\n                    out.push_back(Pair(\"value\", ValueFromAmount((CAmount)minv)));\n                } else {\n                    out.push_back(Pair(\"value-minimum\", ValueFromAmount((CAmount)minv)));\n                    out.push_back(Pair(\"value-maximum\", ValueFromAmount((CAmount)maxv)));\n                }\n                out.push_back(Pair(\"ct-exponent\", exp));\n                out.push_back(Pair(\"ct-bits\", mantissa));\n            }\n            out.push_back(Pair(\"amountcommitment\", HexStr(txout.nValue.vchCommitment)));\n        }\n        const CConfidentialAsset& asset = txout.nAsset;\n        if (asset.IsExplicit()) {\n            out.push_back(Pair(\"asset\", asset.GetAsset().GetHex()));\n        } else if (asset.IsCommitment()) {\n            out.push_back(Pair(\"assetcommitment\", HexStr(asset.vchCommitment)));\n        }\n\n        out.push_back(Pair(\"n\", (int64_t)i));\n        UniValue o(UniValue::VOBJ);\n        ScriptPubKeyToJSON(txout.scriptPubKey, o, true);\n        out.push_back(Pair(\"scriptPubKey\", o));\n        vout.push_back(out);\n    }\n    entry.push_back(Pair(\"vout\", vout));\n\n    if (!hashBlock.IsNull()) {\n        entry.push_back(Pair(\"blockhash\", hashBlock.GetHex()));\n        BlockMap::iterator mi = mapBlockIndex.find(hashBlock);\n        if (mi != mapBlockIndex.end() && (*mi).second) {\n            CBlockIndex* pindex = (*mi).second;\n            if (chainActive.Contains(pindex)) {\n                entry.push_back(Pair(\"confirmations\", 1 + chainActive.Height() - pindex->nHeight));\n                entry.push_back(Pair(\"time\", pindex->GetBlockTime()));\n                entry.push_back(Pair(\"blocktime\", pindex->GetBlockTime()));\n            }\n            else\n                entry.push_back(Pair(\"confirmations\", 0));\n        }\n    }\n}\n\nUniValue getrawtransaction(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)\n        throw runtime_error(\n            \"getrawtransaction \\\"txid\\\" ( verbose )\\n\"\n\n            \"\\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\\n\"\n            \"enabled, it also works for blockchain transactions.\\n\"\n            \"DEPRECATED: for now, it also works for transactions with unspent outputs.\\n\"\n\n            \"\\nReturn the raw transaction data.\\n\"\n            \"\\nIf verbose is 'true', returns an Object with information about 'txid'.\\n\"\n            \"If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"txid\\\"      (string, required) The transaction id\\n\"\n            \"2. verbose       (bool, optional, default=false) If false, return a string, otherwise return a json object\\n\"\n\n            \"\\nResult (if verbose is not set or set to false):\\n\"\n            \"\\\"data\\\"      (string) The serialized, hex-encoded data for 'txid'\\n\"\n\n            \"\\nResult (if verbose is set to true):\\n\"\n            \"{\\n\"\n            \"  \\\"hex\\\" : \\\"data\\\",       (string) The serialized, hex-encoded data for 'txid'\\n\"\n            \"  \\\"txid\\\" : \\\"id\\\",        (string) The transaction id (same as provided)\\n\"\n            \"  \\\"hash\\\" : \\\"id\\\",        (string) The transaction hash (differs from txid for witness transactions)\\n\"\n            \"  \\\"size\\\" : n,             (numeric) The serialized transaction size\\n\"\n            \"  \\\"vsize\\\" : n,            (numeric) The virtual transaction size (differs from size for witness transactions)\\n\"\n            \"  \\\"version\\\" : n,          (numeric) The version\\n\"\n            \"  \\\"locktime\\\" : ttt,       (numeric) The lock time\\n\"\n            \"  \\\"vin\\\" : [               (array of json objects)\\n\"\n            \"     {\\n\"\n            \"       \\\"txid\\\": \\\"id\\\",    (string) The transaction id\\n\"\n            \"       \\\"vout\\\": n,         (numeric) \\n\"\n            \"       \\\"scriptSig\\\": {     (json object) The script\\n\"\n            \"         \\\"asm\\\": \\\"asm\\\",  (string) asm\\n\"\n            \"         \\\"hex\\\": \\\"hex\\\"   (string) hex\\n\"\n            \"       },\\n\"\n            \"       \\\"sequence\\\": n      (numeric) The script sequence number\\n\"\n            \"       \\\"txinwitness\\\": [\\\"hex\\\", ...] (array of string) hex-encoded witness data (if any)\\n\"\n            \"       \\\"issuance\\\"         (object) Info on issuance\\n\"\n            \"     }\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"vout\\\" : [              (array of json objects)\\n\"\n            \"     {\\n\"\n            \"       \\\"value\\\" : x.xxx,            (numeric) The value in \" + CURRENCY_UNIT + \"\\n\"\n            \"       \\\"amountcommitment\\\": \\\"hex\\\",     (string) the output's value commitment, if blinded\\n\"\n            \"       \\\"fee_value\\\" : x.xxx,        (numeric) The fee value in \" + CURRENCY_UNIT + \"\\n\"\n            \"       \\\"n\\\" : n,                    (numeric) index\\n\"\n            \"       \\\"asset\\\" : \\\"hex\\\"           (string) the asset id, if unblinded\\n\"\n            \"       \\\"assetcommitment\\\" : \\\"hex\\\" (string) the asset tag, if blinded\\n\"\n            \"       \\\"scriptPubKey\\\" : {          (json object)\\n\"\n            \"         \\\"asm\\\" : \\\"asm\\\",          (string) the asm\\n\"\n            \"         \\\"hex\\\" : \\\"hex\\\",          (string) the hex\\n\"\n            \"         \\\"reqSigs\\\" : n,            (numeric) The required sigs\\n\"\n            \"         \\\"type\\\" : \\\"pubkeyhash\\\",  (string) The type, eg 'pubkeyhash'\\n\"\n            \"         \\\"addresses\\\" : [           (json array of string)\\n\"\n            \"           \\\"address\\\"        (string) bitcoin address\\n\"\n            \"           ,...\\n\"\n            \"         ]\\n\"\n            \"       }\\n\"\n            \"     }\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"blockhash\\\" : \\\"hash\\\",   (string) the block hash\\n\"\n            \"  \\\"confirmations\\\" : n,      (numeric) The confirmations\\n\"\n            \"  \\\"time\\\" : ttt,             (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"blocktime\\\" : ttt         (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getrawtransaction\", \"\\\"mytxid\\\"\")\n            + HelpExampleCli(\"getrawtransaction\", \"\\\"mytxid\\\" true\")\n            + HelpExampleRpc(\"getrawtransaction\", \"\\\"mytxid\\\", true\")\n        );\n\n    LOCK(cs_main);\n\n    uint256 hash = ParseHashV(request.params[0], \"parameter 1\");\n\n    // Accept either a bool (true) or a num (>=1) to indicate verbose output.\n    bool fVerbose = false;\n    if (request.params.size() > 1) {\n        if (request.params[1].isNum()) {\n            if (request.params[1].get_int() != 0) {\n                fVerbose = true;\n            }\n        }\n        else if(request.params[1].isBool()) {\n            if(request.params[1].isTrue()) {\n                fVerbose = true;\n            }\n        }\n        else {\n            throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid type provided. Verbose parameter must be a boolean.\");\n        } \n    }\n\n    CTransactionRef tx;\n    uint256 hashBlock;\n    if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string(fTxIndex ? \"No such mempool or blockchain transaction\"\n            : \"No such mempool transaction. Use -txindex to enable blockchain transaction queries\") +\n            \". Use gettransaction for wallet transactions.\");\n\n    string strHex = EncodeHexTx(*tx, RPCSerializationFlags());\n\n    if (!fVerbose)\n        return strHex;\n\n    UniValue result(UniValue::VOBJ);\n    result.push_back(Pair(\"hex\", strHex));\n    TxToJSON(*tx, hashBlock, result);\n    return result;\n}\n\nUniValue gettxoutproof(const JSONRPCRequest& request)\n{\n    if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2))\n        throw runtime_error(\n            \"gettxoutproof [\\\"txid\\\",...] ( blockhash )\\n\"\n            \"\\nReturns a hex-encoded proof that \\\"txid\\\" was included in a block.\\n\"\n            \"\\nNOTE: By default this function only works sometimes. This is when there is an\\n\"\n            \"unspent output in the utxo for this transaction. To make it always work,\\n\"\n            \"you need to maintain a transaction index, using the -txindex command line option or\\n\"\n            \"specify the block in which the transaction is included manually (by blockhash).\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"txids\\\"       (string) A json array of txids to filter\\n\"\n            \"    [\\n\"\n            \"      \\\"txid\\\"     (string) A transaction hash\\n\"\n            \"      ,...\\n\"\n            \"    ]\\n\"\n            \"2. \\\"blockhash\\\"   (string, optional) If specified, looks for txid in the block with this hash\\n\"\n            \"\\nResult:\\n\"\n            \"\\\"data\\\"           (string) A string that is a serialized, hex-encoded data for the proof.\\n\"\n        );\n\n    set<uint256> setTxids;\n    uint256 oneTxid;\n    UniValue txids = request.params[0].get_array();\n    for (unsigned int idx = 0; idx < txids.size(); idx++) {\n        const UniValue& txid = txids[idx];\n        if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))\n            throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid txid \")+txid.get_str());\n        uint256 hash(uint256S(txid.get_str()));\n        if (setTxids.count(hash))\n            throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter, duplicated txid: \")+txid.get_str());\n       setTxids.insert(hash);\n       oneTxid = hash;\n    }\n\n    LOCK(cs_main);\n\n    CBlockIndex* pblockindex = NULL;\n\n    uint256 hashBlock;\n    if (request.params.size() > 1)\n    {\n        hashBlock = uint256S(request.params[1].get_str());\n        if (!mapBlockIndex.count(hashBlock))\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found\");\n        pblockindex = mapBlockIndex[hashBlock];\n    } else {\n        CCoins coins;\n        if (pcoinsTip->GetCoins(oneTxid, coins) && coins.nHeight > 0 && coins.nHeight <= chainActive.Height())\n            pblockindex = chainActive[coins.nHeight];\n    }\n\n    if (pblockindex == NULL)\n    {\n        CTransactionRef tx;\n        if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Transaction not yet in block\");\n        if (!mapBlockIndex.count(hashBlock))\n            throw JSONRPCError(RPC_INTERNAL_ERROR, \"Transaction index corrupt\");\n        pblockindex = mapBlockIndex[hashBlock];\n    }\n\n    CBlock block;\n    if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))\n        throw JSONRPCError(RPC_INTERNAL_ERROR, \"Can't read block from disk\");\n\n    unsigned int ntxFound = 0;\n    for (const auto& tx : block.vtx)\n        if (setTxids.count(tx->GetHash()))\n            ntxFound++;\n    if (ntxFound != setTxids.size())\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"(Not all) transactions not found in specified block\");\n\n    CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);\n    CMerkleBlock mb(block, setTxids);\n    ssMB << mb;\n    std::string strHex = HexStr(ssMB.begin(), ssMB.end());\n    return strHex;\n}\n\nUniValue verifytxoutproof(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw runtime_error(\n            \"verifytxoutproof \\\"proof\\\"\\n\"\n            \"\\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\\n\"\n            \"and throwing an RPC error if the block is not in our best chain\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"proof\\\"    (string, required) The hex-encoded proof generated by gettxoutproof\\n\"\n            \"\\nResult:\\n\"\n            \"[\\\"txid\\\"]      (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\\n\"\n        );\n\n    CDataStream ssMB(ParseHexV(request.params[0], \"proof\"), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);\n    CMerkleBlock merkleBlock;\n    ssMB >> merkleBlock;\n\n    UniValue res(UniValue::VARR);\n\n    vector<uint256> vMatch;\n    vector<unsigned int> vIndex;\n    if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)\n        return res;\n\n    LOCK(cs_main);\n\n    if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Block not found in chain\");\n\n    BOOST_FOREACH(const uint256& hash, vMatch)\n        res.push_back(hash.GetHex());\n    return res;\n}\n\nUniValue createrawtransaction(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)\n        throw runtime_error(\n            \"createrawtransaction [{\\\"txid\\\":\\\"id\\\",\\\"vout\\\":n},...] {\\\"address\\\":amount,\\\"data\\\":\\\"hex\\\",...} ( locktime {\\\"address\\\":asset} )\\n\"\n            \"\\nCreate a transaction spending the given inputs and creating new outputs.\\n\"\n            \"Outputs can be addresses or data.\\n\"\n            \"Returns hex-encoded raw transaction.\\n\"\n            \"Note that the transaction's inputs are not signed, and\\n\"\n            \"it is not stored in the wallet or transmitted to the network.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"inputs\\\"                (array, required) A json array of json objects\\n\"\n            \"     [\\n\"\n            \"       {\\n\"\n            \"         \\\"txid\\\":\\\"id\\\",    (string, required) The transaction id\\n\"\n            \"         \\\"vout\\\":n,         (numeric, required) The output number\\n\"\n            \"         \\\"asset\\\": \\\"string\\\"   (string, optional, default=bitcoin) The asset of the input, as a tag string or a hex value\\n\"\n            \"         \\\"sequence\\\":n      (numeric, optional) The sequence number\\n\"\n            \"       } \\n\"\n            \"       ,...\\n\"\n            \"     ]\\n\"\n            \"2. \\\"outputs\\\"               (object, required) a json object with outputs\\n\"\n            \"    {\\n\"\n            \"      \\\"address\\\": x.xxx,    (numeric or string, required) The key is the bitcoin address, the numeric value (can be string) is the \" + CURRENCY_UNIT + \" amount\\n\"\n            \"      \\\"data\\\": \\\"hex\\\"      (string, required) The key is \\\"data\\\", the value is hex encoded data\\n\"\n            \"      \\\"fee\\\": x.xxx           (numeric or string, required) The key is \\\"fee\\\", the value the fee output you want to add.\\n\"\n            \"      ,...\\n\"\n            \"    }\\n\"\n            \"3. locktime                  (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\\n\"\n            \"4. \\\"output_assets\\\"           (strings, optional, default=bitcoin) A json object of assets to addresses\\n\"\n            \"   {\\n\"\n            \"       \\\"address\\\": \\\"hex\\\" \\n\"\n            \"        \\\"fee\\\": \\\"hex\\\" \\n\"\n            \"       ...\\n\"\n            \"   }\\n\"\n            \"\\nResult:\\n\"\n            \"\\\"transaction\\\"              (string) hex string of the transaction\\n\"\n\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\":\\\\\\\"myid\\\\\\\",\\\\\\\"vout\\\\\\\":0}]\\\" \\\"{\\\\\\\"address\\\\\\\":2.41}\\\"\")\n            + HelpExampleCli(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\":\\\\\\\"myid\\\\\\\",\\\\\\\"vout\\\\\\\":0\\\\\\\"asset\\\\\\\":\\\\\\\"myasset\\\\\\\"}]\\\" \\\"{\\\\\\\"address\\\\\\\":2.41}\\\" 0 \\\"{\\\\\\\"address\\\\\\\":\\\\\\\"myasset\\\\\\\"}\\\"\")\n            + HelpExampleCli(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\":\\\\\\\"myid\\\\\\\",\\\\\\\"vout\\\\\\\":0}]\\\" \\\"{\\\\\\\"data\\\\\\\":\\\\\\\"00010203\\\\\\\"}\\\"\")\n            + HelpExampleRpc(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\":\\\\\\\"myid\\\\\\\",\\\\\\\"vout\\\\\\\":0}]\\\", \\\"{\\\\\\\"address\\\\\\\":2.41}\\\"\")\n            + HelpExampleRpc(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\":\\\\\\\"myid\\\\\\\",\\\\\\\"vout\\\\\\\":0\\\\\\\"asset\\\\\\\":\\\\\\\"myasset\\\\\\\"}]\\\", \\\"{\\\\\\\"address\\\\\\\":2.41}\\\", 0, \\\"{\\\\\\\"address\\\\\\\":\\\\\\\"myasset\\\\\\\"}\\\"\")\n            + HelpExampleRpc(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\":\\\\\\\"myid\\\\\\\",\\\\\\\"vout\\\\\\\":0}]\\\", \\\"{\\\\\\\"data\\\\\\\":\\\\\\\"00010203\\\\\\\"}\\\"\")\n        );\n\n    RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM)(UniValue::VOBJ), true);\n    if (request.params[0].isNull() || request.params[1].isNull())\n        throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, arguments 1 and 2 must be non-null\");\n\n    UniValue inputs = request.params[0].get_array();\n    UniValue sendTo = request.params[1].get_obj();\n\n    CMutableTransaction rawTx;\n\n    if (request.params.size() > 2 && !request.params[2].isNull()) {\n        int64_t nLockTime = request.params[2].get_int64();\n        if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, locktime out of range\");\n        rawTx.nLockTime = nLockTime;\n    }\n\n    UniValue assets;\n    if (request.params.size() > 3 && !request.params[3].isNull()) {\n        assets = request.params[3].get_obj();\n    }\n\n    for (unsigned int idx = 0; idx < inputs.size(); idx++) {\n        const UniValue& input = inputs[idx];\n        const UniValue& o = input.get_obj();\n\n        uint256 txid = ParseHashO(o, \"txid\");\n        const UniValue& vout_v = find_value(o, \"vout\");\n        if (!vout_v.isNum())\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, missing vout key\");\n        int nOutput = vout_v.get_int();\n        if (nOutput < 0)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, vout must be positive\");\n\n        uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());\n\n        // set the sequence number if passed in the parameters object\n        const UniValue& sequenceObj = find_value(o, \"sequence\");\n        if (sequenceObj.isNum()) {\n            int64_t seqNr64 = sequenceObj.get_int64();\n            if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max())\n                throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, sequence number is out of range\");\n            else\n                nSequence = (uint32_t)seqNr64;\n        }\n\n        CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);\n\n        CAsset asset(policyAsset);\n        const UniValue& asset_val = find_value(o, \"asset\");\n        if (asset_val.isStr()) {\n            asset = CAsset(ParseHashO(o, \"asset\"));\n        }\n\n        rawTx.vin.push_back(in);\n    }\n\n    set<CBitcoinAddress> setAddress;\n    vector<string> addrList = sendTo.getKeys();\n    BOOST_FOREACH(const string& name_, addrList) {\n        // Defaults to policyAsset\n        CAsset asset(policyAsset);\n        if (!assets.isNull()) {\n            if (!find_value(assets, name_).isNull()) {\n                asset = CAsset(ParseHashO(assets, name_));\n            }\n        }\n        if (name_ == \"data\") {\n            std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),\"Data\");\n\n            CTxOut out(asset, 0, CScript() << OP_RETURN << data);\n            rawTx.vout.push_back(out);\n        } else if (name_ == \"fee\") {\n            CAmount nAmount = AmountFromValue(sendTo[name_]);\n            CTxOut out(asset, nAmount, CScript());\n            rawTx.vout.push_back(out);\n        } else {\n            CBitcoinAddress address(name_);\n            if (!address.IsValid())\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string(\"Invalid Bitcoin address: \")+name_);\n\n            if (setAddress.count(address))\n                throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter, duplicated address: \")+name_);\n            setAddress.insert(address);\n\n            CScript scriptPubKey = GetScriptForDestination(address.Get());\n            CAmount nAmount = AmountFromValue(sendTo[name_]);\n\n            CTxOut out(asset, nAmount, scriptPubKey);\n            if (address.IsBlinded()) {\n                CPubKey confidentiality_pubkey = address.GetBlindingKey();\n                if (!confidentiality_pubkey.IsValid())\n                     throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter: invalid confidentiality public key given\"));\n                out.nNonce.vchCommitment = std::vector<unsigned char>(confidentiality_pubkey.begin(), confidentiality_pubkey.end());\n            }\n            rawTx.vout.push_back(out);\n        }\n    }\n\n    return EncodeHexTx(rawTx);\n}\n\n// Rewind the outputs to unblinded, and push placeholders for blinding info\nvoid FillBlinds(CMutableTransaction& tx, bool fUseWallet, std::vector<uint256>& output_value_blinds, std::vector<uint256>& output_asset_blinds, std::vector<CPubKey>& output_pubkeys, std::vector<CKey>& asset_keys, std::vector<CKey>& token_keys) {\n    for (size_t nOut = 0; nOut < tx.vout.size(); nOut++) {\n        if (!tx.vout[nOut].nValue.IsExplicit()) {\n#ifdef ENABLE_WALLET\n            CTxOutWitness* ptxoutwit = tx.wit.vtxoutwit.size() <= nOut? NULL: &tx.wit.vtxoutwit[nOut];\n            uint256 blinding_factor;\n            uint256 asset_blinding_factor;\n            CAsset asset;\n            CAmount amount;\n            // This can only be used to recover things like change addresses and self-sends.\n            if (fUseWallet && ptxoutwit && UnblindConfidentialPair(pwalletMain->GetBlindingKey(&tx.vout[nOut].scriptPubKey), tx.vout[nOut].nValue, tx.vout[nOut].nAsset, tx.vout[nOut].nNonce, tx.vout[nOut].scriptPubKey, ptxoutwit->vchRangeproof, amount, blinding_factor, asset, asset_blinding_factor) != 0) {\n                // Wipe out confidential info from output and output witness\n                CScript scriptPubKey = tx.vout[nOut].scriptPubKey;\n                CTxOut newOut(asset, amount, scriptPubKey);\n                tx.vout[nOut] = newOut;\n                ptxoutwit->SetNull();\n\n                // Mark for re-blinding with same key that deblinded it\n                CPubKey pubkey(pwalletMain->GetBlindingKey(&tx.vout[nOut].scriptPubKey).GetPubKey());\n                output_pubkeys.push_back(pubkey);\n                output_value_blinds.push_back(uint256());\n                output_asset_blinds.push_back(uint256());\n                continue;\n            }\n#endif\n            // If no wallet, or unable to unblind, leave it alone in next blinding step\n            output_pubkeys.push_back(CPubKey());\n            output_value_blinds.push_back(uint256());\n            output_asset_blinds.push_back(uint256());\n        } else if (tx.vout[nOut].nNonce.IsNull()) {\n            output_pubkeys.push_back(CPubKey());\n            output_value_blinds.push_back(uint256());\n            output_asset_blinds.push_back(uint256());\n        } else {\n            CPubKey pubkey(tx.vout[nOut].nNonce.vchCommitment);\n            if (!pubkey.IsValid()) {\n                 throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter: invalid confidentiality public key given\"));\n            }\n            output_pubkeys.push_back(pubkey);\n            output_value_blinds.push_back(uint256());\n            output_asset_blinds.push_back(uint256());\n        }\n    }\n\n    // Fill out issuance blinding keys to be used directly as nonce for rangeproof\n    for (size_t nIn = 0; nIn < tx.vin.size(); nIn++) {\n        CAssetIssuance& issuance = tx.vin[nIn].assetIssuance;\n        if (issuance.IsNull()) {\n            asset_keys.push_back(CKey());\n            token_keys.push_back(CKey());\n            continue;\n        }\n\n        // Calculate underlying asset for use as blinding key script\n        CAsset asset;\n        // New issuance, compute the asset ids\n        if (issuance.assetBlindingNonce.IsNull()) {\n            uint256 entropy;\n            GenerateAssetEntropy(entropy, tx.vin[nIn].prevout, issuance.assetEntropy);\n            CalculateAsset(asset, entropy);\n        }\n        // Re-issuance\n        else {\n            // TODO Give option to skip blinding when the reissuance token was derived without blinding ability. For now we assume blinded\n            // hashAssetIdentifier doubles as the entropy on reissuance\n            CalculateAsset(asset, issuance.assetEntropy);\n        }\n\n        // Special format for issuance blinding keys, unique for each transaction\n        CScript blindingScript = CScript() << OP_RETURN << std::vector<unsigned char>(tx.vin[nIn].prevout.hash.begin(), tx.vin[nIn].prevout.hash.end()) << tx.vin[nIn].prevout.n;\n\n        for (size_t nPseudo = 0; nPseudo < 2; nPseudo++) {\n            CConfidentialValue& confValue = (nPseudo == 0) ? issuance.nAmount : issuance.nInflationKeys;\n            if (confValue.IsCommitment()) {\n                // Rangeproof must exist\n                if (tx.wit.vtxinwit.size() <= nIn) {\n                    throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Transaction issuance is already blinded but has no attached rangeproof.\"));\n                }\n                CTxInWitness& txinwit = tx.wit.vtxinwit[nIn];\n                std::vector<unsigned char>& vchRangeproof = (nPseudo == 0) ? txinwit.vchIssuanceAmountRangeproof : txinwit.vchInflationKeysRangeproof;\n                uint256 blinding_factor;\n                uint256 asset_blinding_factor;\n                CAmount amount;\n#ifdef ENABLE_WALLET\n                if (fUseWallet && UnblindConfidentialPair(pwalletMain->GetBlindingKey(&blindingScript), confValue, CConfidentialAsset(asset), CConfidentialNonce(), CScript(), vchRangeproof, amount, blinding_factor, asset, asset_blinding_factor) != 0) {\n                    // Wipe out confidential info from issuance\n                    vchRangeproof.clear();\n                    confValue = CConfidentialValue(amount);\n                    // One key both blinded values, single key needed for issuance reveal\n                    asset_keys.push_back(pwalletMain->GetBlindingKey(&blindingScript));\n                    token_keys.push_back(pwalletMain->GetBlindingKey(&blindingScript));\n                    continue;\n                }\n#endif\n                // If no wallet, or unable to unblind, leave it alone in next blinding step\n                asset_keys.push_back(CKey());\n                token_keys.push_back(CKey());\n            } else {\n                // Without wallet, nothing to be done.\n                asset_keys.push_back(CKey());\n                token_keys.push_back(CKey());\n#ifdef ENABLE_WALLET\n                // Use wallet to generate blindingkey used directly as nonce\n                // as user is not \"sending\" to anyone.\n                // Always assumed we want to blind here.\n                // TODO Signal intent for all blinding via API including replacing nonce commitment\n                if (fUseWallet) {\n                    asset_keys[asset_keys.size()-1] = pwalletMain->GetBlindingKey(&blindingScript);\n                    token_keys[token_keys.size()-1] = pwalletMain->GetBlindingKey(&blindingScript);\n                }\n#endif\n            }\n        }\n    }\n}\n\nUniValue rawblindrawtransaction(const JSONRPCRequest& request)\n{\n    if (request.fHelp || (request.params.size() < 5 || request.params.size() > 7))\n        throw std::runtime_error(\n            \"rawblindrawtransaction \\\"hexstring\\\" [\\\"inputblinder\\\",...] [\\\"inputamount\\\",...] [\\\"inputasset\\\",...] [\\\"inputassetblinder\\\",...] ( totalblinder, ignoreblindfail )\\n\"\n            \"\\nConvert one or more outputs of a raw transaction into confidential ones.\\n\"\n            \"Returns the hex-encoded raw transaction.\\n\"\n            \"The input raw transaction cannot have already-blinded outputs.\\n\"\n            \"The output keys used can be specified by using a confidential address in createrawtransaction.\\n\"\n            \"If an additional blinded output is required to make a balanced blinding, a 0-value unspendable output will be added. Since there is no access to the wallet the blinding pubkey from the last output with blinding key will be repeated.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"hexstring\\\",          (string, required) A hex-encoded raw transaction.\\n\"\n            \"2. [                     (array, required) An array with one entry per transaction input.\\n\"\n            \"    \\\"inputblinder\\\"       (string, required) A hex-encoded blinding factor, one for each input.\\n\"\n            \"                         Blinding factors can be found in the \\\"blinder\\\" output of listunspent.\\n\"\n            \"   ],\\n\"\n            \"3. [                     (array, required) An array with one entry per transaction input.\\n\"\n            \"   \\\"inputamount\\\"       (numeric, required) An amount for each input.\\n\"\n            \"   ],\\n\"\n            \"4. [                     (array, required) An array with one entry per transaction input.\\n\"\n            \"   \\\"inputasset\\\"        (string, required) A hex-encoded asset id, one for each input.\\n\"\n            \"   ],\\n\"\n            \"5. [                     (array, required) An array with one entry per transaction input.\\n\"\n            \"   \\\"inputassetblinder\\\" (string, required) A hex-encoded asset blinding factor, one for each input.\\n\"\n            \"   ],\\n\"\n            \"6. \\\"totalblinder\\\"        (string, optional) Ignored for now.\\n\"\n            \"7. \\\"ignoreblindfail\\\"\\\"   (bool, optional, default=true) Return a transaction even when a blinding attempt fails due to number of blinded inputs/outputs.\\n\"\n\n            \"\\nResult:\\n\"\n            \"\\\"transaction\\\"              (string) hex string of the transaction\\n\"\n        );\n\n    if (request.params.size() == 5) {\n        RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VARR)(UniValue::VARR));\n    } else if (request.params.size() == 6) {\n        RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR));\n    } else {\n        RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR)(UniValue::VBOOL));\n    }\n\n    vector<unsigned char> txData(ParseHexV(request.params[0], \"argument 1\"));\n    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);\n    CMutableTransaction tx;\n    try {\n        ssData >> tx;\n    } catch (const std::exception &) {\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n    }\n\n    UniValue inputBlinds = request.params[1].get_array();\n    UniValue inputAmounts = request.params[2].get_array();\n    UniValue inputAssets = request.params[3].get_array();\n    UniValue inputAssetBlinds = request.params[4].get_array();\n\n    bool fIgnoreBlindFail = true;\n    if (request.params.size() > 6) {\n        fIgnoreBlindFail = request.params[6].get_bool();\n    }\n\n    int n_blinded_ins = 0;\n\n    if (inputBlinds.size() != tx.vin.size()) throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter: one (potentially empty) input blind for each input must be provided\"));\n    if (inputAmounts.size() != tx.vin.size()) throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter: one (potentially empty) input blind for each input must be provided\"));\n    if (inputAssets.size() != tx.vin.size()) throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter: one (potentially empty) input asset id for each input must be provided\"));\n    if (inputAssetBlinds.size() != tx.vin.size()) throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter: one (potentially empty) input asset blind for each input must be provided\"));\n\n    std::vector<CAmount> input_amounts;\n    std::vector<uint256> input_blinds;\n    std::vector<uint256> input_asset_blinds;\n    std::vector<CAsset> input_assets;\n    std::vector<uint256> output_value_blinds;\n    std::vector<uint256> output_asset_blinds;\n    std::vector<CAsset> output_assets;\n    std::vector<CPubKey> output_pubkeys;\n    for (size_t nIn = 0; nIn < tx.vin.size(); nIn++) {\n        if (!inputBlinds[nIn].isStr())\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"input blinds must be an array of hex strings\");\n        if (!inputAssetBlinds[nIn].isStr())\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"input asset blinds must be an array of hex strings\");\n        if (!inputAssets[nIn].isStr())\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"input asset ids must be an array of hex strings\");\n\n        std::string blind(inputBlinds[nIn].get_str());\n        std::string assetblind(inputAssetBlinds[nIn].get_str());\n        std::string asset(inputAssets[nIn].get_str());\n        if (!IsHex(blind) || blind.length() != 32*2)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"input blinds must be an array of 32-byte hex-encoded strings\");\n        if (!IsHex(assetblind) || assetblind.length() != 32*2)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"input asset blinds must be an array of 32-byte hex-encoded strings\");\n        if (!IsHex(asset) || asset.length() != 32*2)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"input asset blinds must be an array of 32-byte hex-encoded strings\");\n\n        input_blinds.push_back(uint256S(blind));\n        input_asset_blinds.push_back(uint256S(assetblind));\n        input_assets.push_back(CAsset(uint256S(asset)));\n        input_amounts.push_back(AmountFromValue(inputAmounts[nIn]));\n\n        if (!input_blinds.back().IsNull()) {\n            n_blinded_ins++;\n        }\n    }\n\n    std::vector<CKey> asset_keys;\n    std::vector<CKey> token_keys;\n    FillBlinds(tx, false, output_value_blinds, output_asset_blinds, output_pubkeys, asset_keys, token_keys);\n\n    // How many are we trying to blind?\n    int numPubKeys = 0;\n    unsigned int keyIndex = -1;\n    for (unsigned int i = 0; i < output_pubkeys.size(); i++) {\n        const CPubKey& key = output_pubkeys[i];\n        if (key.IsValid()) {\n            numPubKeys++;\n            keyIndex = i;\n        }\n    }\n\n    if (numPubKeys == 0 && n_blinded_ins == 0) {\n        // Vacuous, just return the transaction\n        return EncodeHexTx(tx);\n    } else if (n_blinded_ins > 0 && numPubKeys == 0) {\n        // No notion of wallet, cannot complete this blinding without passed-in pubkey\n        throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Unable to blind transaction: Add another output to blind in order to complete the blinding.\"));\n    } else if (n_blinded_ins == 0 && numPubKeys == 1) {\n        if (fIgnoreBlindFail) {\n            // Just get rid of the ECDH key in the nonce field and return\n            tx.vout[keyIndex].nNonce.SetNull();\n            return EncodeHexTx(tx);\n        } else {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Unable to blind transaction: Add another output to blind in order to complete the blinding.\"));\n        }\n    }\n\n    int ret = BlindTransaction(input_blinds, input_asset_blinds, input_assets, input_amounts, output_value_blinds, output_asset_blinds, output_pubkeys, std::vector<CKey>(), std::vector<CKey>(), tx);\n    if (ret != numPubKeys) {\n        // TODO Have more rich return values, communicating to user what has been blinded\n        // User may be ok not blinding something that for instance has no corresponding type on input\n        throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Unable to blind transaction: Are you sure each asset type to blind is represented in the inputs?\"));\n    }\n\n    return EncodeHexTx(tx);\n}\n\n#ifdef ENABLE_WALLET\nUniValue blindrawtransaction(const JSONRPCRequest& request)\n{\n    if (request.fHelp || (request.params.size() < 1 || request.params.size() > 4))\n        throw runtime_error(\n            \"blindrawtransaction \\\"hexstring\\\" ( ignoreblindfail [\\\"assetcommitment,...\\\"] totalblinder )\\n\"\n            \"\\nConvert one or more outputs of a raw transaction into confidential ones using only wallet inputs.\\n\"\n            \"Returns the hex-encoded raw transaction.\\n\"\n            \"The output keys used can be specified by using a confidential address in createrawtransaction.\\n\"\n            \"This call may add an additional 0-value unspendable output in order to balance the blinders.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"hexstring\\\",          (string, required) A hex-encoded raw transaction.\\n\"\n            \"2. \\\"ignoreblindfail\\\"\\\"   (bool, optional, default=true) Return a transaction even when a blinding attempt fails due to number of blinded inputs/outputs.\\n\"\n            \"3. [                       (array, optional) An array of input asset generators. If provided, this list must be empty, or match the final input commitment list, including ordering, to make a valid surjection proof. This list does not include generators for issuances, as these assets are inherently unblinded.\\n\"\n            \"    \\\"assetcommitment\\\"   (string, optional) A hex-encoded asset commitment, one for each input.\\n\"\n            \"                        Null commitments must be \\\"\\\".\\n\"\n            \"   ],\\n\"\n            \"4. \\\"totalblinder\\\"        (string, optional) Ignored for now.\\n\"\n\n            \"\\nResult:\\n\"\n            \"\\\"transaction\\\"              (string) hex string of the transaction\\n\"\n        );\n\n    if (request.params.size() == 1) {\n        RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR));\n    } else if (request.params.size() == 2){\n        RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));\n    } else if (request.params.size() == 3){\n        RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VARR));\n    } else {\n        RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VARR)(UniValue::VSTR));\n    }\n\n    vector<unsigned char> txData(ParseHexV(request.params[0], \"argument 1\"));\n    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);\n    CMutableTransaction tx;\n    try {\n        ssData >> tx;\n    } catch (const std::exception &) {\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n    }\n\n    bool fIgnoreBlindFail = true;\n    if (request.params.size() > 1) {\n        fIgnoreBlindFail = request.params[1].get_bool();\n    }\n\n    std::vector<std::vector<unsigned char> > auxiliary_generators;\n    if (request.params.size() > 2) {\n        UniValue assetCommitments = request.params[2].get_array();\n        if (assetCommitments.size() != 0 && assetCommitments.size() < tx.vin.size()) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Asset commitment array must have at least as many entries as transaction inputs.\");\n        }\n        for (size_t nIn = 0; nIn < assetCommitments.size(); nIn++) {\n            if (assetCommitments[nIn].isStr()) {\n                std::string assetcommitment = assetCommitments[nIn].get_str();\n                if (IsHex(assetcommitment) && assetcommitment.size() == 66) {\n                    auxiliary_generators.push_back(ParseHex(assetcommitment));\n                    continue;\n                }\n            }\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Asset commitments must be a hex encoded string of length 66.\");\n        }\n    }\n\n    LOCK(pwalletMain->cs_wallet);\n\n    std::vector<uint256> input_blinds;\n    std::vector<uint256> input_asset_blinds;\n    std::vector<CAsset> input_assets;\n    std::vector<CAmount> input_amounts;\n    std::vector<uint256> output_blinds;\n    std::vector<uint256> output_asset_blinds;\n    std::vector<CAsset> output_assets;\n    std::vector<CPubKey> output_pubkeys;\n    int n_blinded_ins = 0;\n    for (size_t nIn = 0; nIn < tx.vin.size(); nIn++) {\n\n        std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.find(tx.vin[nIn].prevout.hash);\n        if (it == pwalletMain->mapWallet.end()) {\n            // For inputs we don't own input assetcommitments for the surjection must be supplied\n            if (auxiliary_generators.size() > 0) {\n                input_blinds.push_back(uint256());\n                input_asset_blinds.push_back(uint256());\n                input_assets.push_back(CAsset());\n                input_amounts.push_back(-1);\n                continue;\n            }\n            throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter: transaction spends from non-wallet output and no assetcommitment list was given.\"));\n        }\n        if (tx.vin[nIn].prevout.n >= it->second.tx->vout.size()) {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter: transaction spends non-existing output\"));\n        }\n        input_blinds.push_back(it->second.GetOutputBlindingFactor(tx.vin[nIn].prevout.n));\n        input_asset_blinds.push_back(it->second.GetOutputAssetBlindingFactor(tx.vin[nIn].prevout.n));\n        // These cases unneeded? If value is explicit we can still get via GetOutputX calls.\n        if (it->second.tx->vout[tx.vin[nIn].prevout.n].nAsset.IsExplicit()) {\n            input_assets.push_back(it->second.tx->vout[tx.vin[nIn].prevout.n].nAsset.GetAsset());\n        }\n        else {\n            input_assets.push_back(it->second.GetOutputAsset(tx.vin[nIn].prevout.n));\n        }\n        if (it->second.tx->vout[tx.vin[nIn].prevout.n].nValue.IsExplicit()) {\n            input_amounts.push_back(it->second.tx->vout[tx.vin[nIn].prevout.n].nValue.GetAmount());\n        }\n        else {\n            input_amounts.push_back(it->second.GetOutputValueOut(tx.vin[nIn].prevout.n));\n            n_blinded_ins += 1;\n        }\n    }\n\n    std::vector<CKey> asset_keys;\n    std::vector<CKey> token_keys;\n    FillBlinds(tx, true, output_blinds, output_asset_blinds, output_pubkeys, asset_keys, token_keys);\n\n    // How many are we trying to blind?\n    int numPubKeys = 0;\n    unsigned int keyIndex = 0;\n    for (unsigned int i = 0; i < output_pubkeys.size(); i++) {\n        const CPubKey& key = output_pubkeys[i];\n        if (key.IsValid()) {\n            numPubKeys++;\n            keyIndex = i;\n        }\n    }\n\n    if (numPubKeys == 0 && n_blinded_ins == 0) {\n        // Vacuous, just return the transaction\n        return EncodeHexTx(tx);\n    } else if (n_blinded_ins > 0 && numPubKeys == 0) {\n        // Blinded inputs need to balanced with something to be valid, make a dummy.\n        CTxOut newTxOut(tx.vout.back().nAsset.GetAsset(), 0, CScript() << OP_RETURN);\n        tx.vout.push_back(newTxOut);\n        numPubKeys++;\n        output_pubkeys.push_back(pwalletMain->GetBlindingPubKey(newTxOut.scriptPubKey));\n    } else if (n_blinded_ins == 0 && numPubKeys == 1) {\n        if (fIgnoreBlindFail) {\n            // Just get rid of the ECDH key in the nonce field and return\n            tx.vout[keyIndex].nNonce.SetNull();\n            return EncodeHexTx(tx);\n        } else {\n            throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Unable to blind transaction: Add another output to blind in order to complete the blinding.\"));\n        }\n    }\n\n    if (BlindTransaction(input_blinds, input_asset_blinds, input_assets, input_amounts, output_blinds, output_asset_blinds, output_pubkeys, std::vector<CKey>(), std::vector<CKey>(), tx, (auxiliary_generators.size() ? &auxiliary_generators : NULL)) != numPubKeys) {\n        // TODO Have more rich return values, communicating to user what has been blinded\n        // User may be ok not blinding something that for instance has no corresponding type on input\n        throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Unable to blind transaction: Are you sure each asset type to blind is represented in the inputs?\"));\n    }\n\n    return EncodeHexTx(tx);\n}\n#endif\n\nUniValue decoderawtransaction(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw runtime_error(\n            \"decoderawtransaction \\\"hexstring\\\"\\n\"\n            \"\\nReturn a JSON object representing the serialized, hex-encoded transaction.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"hexstring\\\"      (string, required) The transaction hex string\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"txid\\\" : \\\"id\\\",        (string) The transaction id\\n\"\n            \"  \\\"hash\\\" : \\\"id\\\",        (string) The transaction hash (differs from txid for witness transactions)\\n\"\n            \"  \\\"size\\\" : n,             (numeric) The transaction size\\n\"\n            \"  \\\"vsize\\\" : n,            (numeric) The virtual transaction size (differs from size for witness transactions)\\n\"\n            \"  \\\"version\\\" : n,          (numeric) The version\\n\"\n            \"  \\\"locktime\\\" : ttt,       (numeric) The lock time\\n\"\n            \"  \\\"fee\\\" : x.xxx,          (numeric) The transaction fee in \" + CURRENCY_UNIT + \"\\n\"\n            \"  \\\"vin\\\" : [               (array of json objects)\\n\"\n            \"     {\\n\"\n            \"       \\\"txid\\\": \\\"id\\\",    (string) The transaction id\\n\"\n            \"       \\\"vout\\\": n,         (numeric) The output number\\n\"\n            \"       \\\"scriptSig\\\": {     (json object) The script\\n\"\n            \"         \\\"asm\\\": \\\"asm\\\",  (string) asm\\n\"\n            \"         \\\"hex\\\": \\\"hex\\\"   (string) hex\\n\"\n            \"       },\\n\"\n            \"       \\\"txinwitness\\\": [\\\"hex\\\", ...] (array of string) hex-encoded witness data (if any)\\n\"\n            \"       \\\"sequence\\\": n     (numeric) The script sequence number\\n\"\n            \"       \\\"issuance\\\"         (object) Info on issuance\\n\"\n            \"     }\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"vout\\\" : [             (array of json objects)\\n\"\n            \"     {\\n\"\n            \"       \\\"value\\\" : x.xxx,            (numeric) The value in \" + CURRENCY_UNIT + \"\\n\"\n            \"       \\\"n\\\" : n,                    (numeric) index\\n\"\n            \"       \\\"asset\\\" : \\\"hex\\\"           (string) the asset id, if unblinded\\n\"\n            \"       \\\"assetcommitment\\\" : \\\"hex\\\" (string) the asset tag, if blinded\\n\"\n            \"       \\\"scriptPubKey\\\" : {          (json object)\\n\"\n            \"         \\\"asm\\\" : \\\"asm\\\",          (string) the asm\\n\"\n            \"         \\\"hex\\\" : \\\"hex\\\",          (string) the hex\\n\"\n            \"         \\\"reqSigs\\\" : n,            (numeric) The required sigs\\n\"\n            \"         \\\"type\\\" : \\\"pubkeyhash\\\",  (string) The type, eg 'pubkeyhash'\\n\"\n            \"         \\\"addresses\\\" : [           (json array of string)\\n\"\n            \"           \\\"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\\\"   (string) bitcoin address\\n\"\n            \"           ,...\\n\"\n            \"         ]\\n\"\n            \"       }\\n\"\n            \"     }\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"decoderawtransaction\", \"\\\"hexstring\\\"\")\n            + HelpExampleRpc(\"decoderawtransaction\", \"\\\"hexstring\\\"\")\n        );\n\n    LOCK(cs_main);\n    RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR));\n\n    CMutableTransaction mtx;\n\n    if (!DecodeHexTx(mtx, request.params[0].get_str()))\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n\n    UniValue result(UniValue::VOBJ);\n    TxToJSON(CTransaction(std::move(mtx)), uint256(), result);\n\n    return result;\n}\n\nUniValue decodescript(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() != 1)\n        throw runtime_error(\n            \"decodescript \\\"hexstring\\\"\\n\"\n            \"\\nDecode a hex-encoded script.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"hexstring\\\"     (string) the hex encoded script\\n\"\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"asm\\\":\\\"asm\\\",   (string) Script public key\\n\"\n            \"  \\\"hex\\\":\\\"hex\\\",   (string) hex encoded public key\\n\"\n            \"  \\\"type\\\":\\\"type\\\", (string) The output type\\n\"\n            \"  \\\"reqSigs\\\": n,    (numeric) The required signatures\\n\"\n            \"  \\\"addresses\\\": [   (json array of string)\\n\"\n            \"     \\\"address\\\"     (string) bitcoin address\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"p2sh\\\",\\\"address\\\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"decodescript\", \"\\\"hexstring\\\"\")\n            + HelpExampleRpc(\"decodescript\", \"\\\"hexstring\\\"\")\n        );\n\n    RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR));\n\n    UniValue r(UniValue::VOBJ);\n    CScript script;\n    if (request.params[0].get_str().size() > 0){\n        vector<unsigned char> scriptData(ParseHexV(request.params[0], \"argument\"));\n        script = CScript(scriptData.begin(), scriptData.end());\n    } else {\n        // Empty scripts are valid\n    }\n    ScriptPubKeyToJSON(script, r, false);\n\n    UniValue type;\n    type = find_value(r, \"type\");\n\n    if (type.isStr() && type.get_str() != \"scripthash\") {\n        // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,\n        // don't return the address for a P2SH of the P2SH.\n        r.push_back(Pair(\"p2sh\", CBitcoinAddress(CScriptID(script)).ToString()));\n    }\n\n    return r;\n}\n\n/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */\nstatic void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)\n{\n    UniValue entry(UniValue::VOBJ);\n    entry.push_back(Pair(\"txid\", txin.prevout.hash.ToString()));\n    entry.push_back(Pair(\"vout\", (uint64_t)txin.prevout.n));\n    entry.push_back(Pair(\"scriptSig\", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));\n    entry.push_back(Pair(\"sequence\", (uint64_t)txin.nSequence));\n    entry.push_back(Pair(\"error\", strMessage));\n    vErrorsRet.push_back(entry);\n}\n\nUniValue signrawtransaction(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)\n        throw runtime_error(\n            \"signrawtransaction \\\"hexstring\\\" ( [{\\\"txid\\\":\\\"id\\\",\\\"vout\\\":n,\\\"scriptPubKey\\\":\\\"hex\\\",\\\"redeemScript\\\":\\\"hex\\\"},...] [\\\"privatekey1\\\",...] sighashtype )\\n\"\n            \"\\nSign inputs for raw transaction (serialized, hex-encoded).\\n\"\n            \"The second optional argument (may be null) is an array of previous transaction outputs that\\n\"\n            \"this transaction depends on but may not yet be in the block chain.\\n\"\n            \"The third optional argument (may be null) is an array of base58-encoded private\\n\"\n            \"keys that, if given, will be the only keys used to sign the transaction.\\n\"\n#ifdef ENABLE_WALLET\n            + HelpRequiringPassphrase() + \"\\n\"\n#endif\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"hexstring\\\"     (string, required) The transaction hex string\\n\"\n            \"2. \\\"prevtxs\\\"       (string, optional) An json array of previous dependent transaction outputs\\n\"\n            \"     [               (json array of json objects, or 'null' if none provided)\\n\"\n            \"       {\\n\"\n            \"         \\\"txid\\\":\\\"id\\\",             (string, required) The transaction id\\n\"\n            \"         \\\"vout\\\":n,                  (numeric, required) The output number\\n\"\n            \"         \\\"scriptPubKey\\\": \\\"hex\\\",   (string, required) script key\\n\"\n            \"         \\\"redeemScript\\\": \\\"hex\\\",   (string, required for P2SH or P2WSH) redeem script\\n\"\n            \"         \\\"amount\\\": value            (numeric, required) The amount spent\\n\"\n            \"       }\\n\"\n            \"       ,...\\n\"\n            \"    ]\\n\"\n            \"3. \\\"privkeys\\\"     (string, optional) A json array of base58-encoded private keys for signing\\n\"\n            \"    [                  (json array of strings, or 'null' if none provided)\\n\"\n            \"      \\\"privatekey\\\"   (string) private key in base58-encoding\\n\"\n            \"      ,...\\n\"\n            \"    ]\\n\"\n            \"4. \\\"sighashtype\\\"     (string, optional, default=ALL) The signature hash type. Must be one of\\n\"\n            \"       \\\"ALL\\\"\\n\"\n            \"       \\\"NONE\\\"\\n\"\n            \"       \\\"SINGLE\\\"\\n\"\n            \"       \\\"ALL|ANYONECANPAY\\\"\\n\"\n            \"       \\\"NONE|ANYONECANPAY\\\"\\n\"\n            \"       \\\"SINGLE|ANYONECANPAY\\\"\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"hex\\\" : \\\"value\\\",           (string) The hex-encoded raw transaction with signature(s)\\n\"\n            \"  \\\"complete\\\" : true|false,   (boolean) If the transaction has a complete set of signatures\\n\"\n            \"  \\\"errors\\\" : [                 (json array of objects) Script verification errors (if there are any)\\n\"\n            \"    {\\n\"\n            \"      \\\"txid\\\" : \\\"hash\\\",           (string) The hash of the referenced, previous transaction\\n\"\n            \"      \\\"vout\\\" : n,                (numeric) The index of the output to spent and used as input\\n\"\n            \"      \\\"scriptSig\\\" : \\\"hex\\\",       (string) The hex-encoded signature script\\n\"\n            \"      \\\"sequence\\\" : n,            (numeric) Script sequence number\\n\"\n            \"      \\\"error\\\" : \\\"text\\\"           (string) Verification or signing error related to the input\\n\"\n            \"    }\\n\"\n            \"    ,...\\n\"\n            \"  ]\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"signrawtransaction\", \"\\\"myhex\\\"\")\n            + HelpExampleRpc(\"signrawtransaction\", \"\\\"myhex\\\"\")\n        );\n\n#ifdef ENABLE_WALLET\n    LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);\n#else\n    LOCK(cs_main);\n#endif\n    RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);\n\n    vector<unsigned char> txData(ParseHexV(request.params[0], \"argument 1\"));\n    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);\n    vector<CMutableTransaction> txVariants;\n    while (!ssData.empty()) {\n        try {\n            CMutableTransaction tx;\n            ssData >> tx;\n            txVariants.push_back(tx);\n        }\n        catch (const std::exception&) {\n            throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n        }\n    }\n\n    if (txVariants.empty())\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"Missing transaction\");\n\n    // mergedTx will end up with all the signatures; it\n    // starts as a clone of the rawtx:\n    CMutableTransaction mergedTx(txVariants[0]);\n\n    // Fetch previous transactions (inputs):\n    CCoinsView viewDummy;\n    CCoinsViewCache view(&viewDummy);\n    {\n        LOCK(mempool.cs);\n        CCoinsViewCache &viewChain = *pcoinsTip;\n        CCoinsViewMemPool viewMempool(&viewChain, mempool);\n        view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view\n\n        BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {\n            const uint256& prevHash = txin.prevout.hash;\n            CCoins coins;\n            view.AccessCoins(prevHash); // this is certainly allowed to fail\n        }\n\n        view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long\n    }\n\n    bool fGivenKeys = false;\n    CBasicKeyStore tempKeystore;\n    if (request.params.size() > 2 && !request.params[2].isNull()) {\n        fGivenKeys = true;\n        UniValue keys = request.params[2].get_array();\n        for (unsigned int idx = 0; idx < keys.size(); idx++) {\n            UniValue k = keys[idx];\n            CBitcoinSecret vchSecret;\n            bool fGood = vchSecret.SetString(k.get_str());\n            if (!fGood)\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid private key\");\n            CKey key = vchSecret.GetKey();\n            if (!key.IsValid())\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Private key outside allowed range\");\n            tempKeystore.AddKey(key);\n        }\n    }\n#ifdef ENABLE_WALLET\n    else if (pwalletMain)\n        EnsureWalletIsUnlocked();\n#endif\n\n    // Add previous txouts given in the RPC call:\n    if (request.params.size() > 1 && !request.params[1].isNull()) {\n        UniValue prevTxs = request.params[1].get_array();\n        for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {\n            const UniValue& p = prevTxs[idx];\n            if (!p.isObject())\n                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"expected object with {\\\"txid'\\\",\\\"vout\\\",\\\"scriptPubKey\\\"}\");\n\n            UniValue prevOut = p.get_obj();\n\n            RPCTypeCheckObj(prevOut,\n                {\n                    {\"txid\", UniValueType(UniValue::VSTR)},\n                    {\"vout\", UniValueType(UniValue::VNUM)},\n                    {\"scriptPubKey\", UniValueType(UniValue::VSTR)},\n                });\n\n            uint256 txid = ParseHashO(prevOut, \"txid\");\n\n            int nOut = find_value(prevOut, \"vout\").get_int();\n            if (nOut < 0)\n                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"vout must be positive\");\n\n            vector<unsigned char> pkData(ParseHexO(prevOut, \"scriptPubKey\"));\n            CScript scriptPubKey(pkData.begin(), pkData.end());\n\n            {\n                CCoinsModifier coins = view.ModifyCoins(txid);\n                if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {\n                    string err(\"Previous output scriptPubKey mismatch:\\n\");\n                    err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + \"\\nvs:\\n\"+\n                        ScriptToAsmStr(scriptPubKey);\n                    throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n                }\n                if ((unsigned int)nOut >= coins->vout.size())\n                    coins->vout.resize(nOut+1);\n                coins->vout[nOut].scriptPubKey = scriptPubKey;\n                coins->vout[nOut].nValue = 0;\n                if (prevOut.exists(\"amount\")) {\n                    coins->vout[nOut].nValue = AmountFromValue(find_value(prevOut, \"amount\"));\n                }\n            }\n\n            // if redeemScript given and not using the local wallet (private keys\n            // given), add redeemScript to the tempKeystore so it can be signed:\n            if (fGivenKeys && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {\n                RPCTypeCheckObj(prevOut,\n                    {\n                        {\"txid\", UniValueType(UniValue::VSTR)},\n                        {\"vout\", UniValueType(UniValue::VNUM)},\n                        {\"scriptPubKey\", UniValueType(UniValue::VSTR)},\n                        {\"redeemScript\", UniValueType(UniValue::VSTR)},\n                    });\n                UniValue v = find_value(prevOut, \"redeemScript\");\n                if (!v.isNull()) {\n                    vector<unsigned char> rsData(ParseHexV(v, \"redeemScript\"));\n                    CScript redeemScript(rsData.begin(), rsData.end());\n                    tempKeystore.AddCScript(redeemScript);\n                }\n            }\n        }\n    }\n\n#ifdef ENABLE_WALLET\n    const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);\n#else\n    const CKeyStore& keystore = tempKeystore;\n#endif\n\n    int nHashType = SIGHASH_ALL;\n    if (request.params.size() > 3 && !request.params[3].isNull()) {\n        static map<string, int> mapSigHashValues =\n            boost::assign::map_list_of\n            (string(\"ALL\"), int(SIGHASH_ALL))\n            (string(\"ALL|ANYONECANPAY\"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))\n            (string(\"NONE\"), int(SIGHASH_NONE))\n            (string(\"NONE|ANYONECANPAY\"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))\n            (string(\"SINGLE\"), int(SIGHASH_SINGLE))\n            (string(\"SINGLE|ANYONECANPAY\"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))\n            ;\n        string strHashType = request.params[3].get_str();\n        if (mapSigHashValues.count(strHashType))\n            nHashType = mapSigHashValues[strHashType];\n        else\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid sighash param\");\n    }\n\n    bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);\n\n    // Script verification errors\n    UniValue vErrors(UniValue::VARR);\n\n    // Use CTransaction for the constant parts of the\n    // transaction to avoid rehashing.\n    const CTransaction txConst(mergedTx);\n    // Sign what we can, including peg-in inputs:\n    for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {\n        CTxIn& txin = mergedTx.vin[i];\n        const CCoins* coins = view.AccessCoins(txin.prevout.hash);\n        if (!txin.m_is_pegin && (coins == NULL || !coins->IsAvailable(txin.prevout.n))) {\n            TxInErrorToJSON(txin, vErrors, \"Input not found or already spent\");\n            continue;\n        } else if (txin.m_is_pegin && (txConst.wit.vtxinwit.size() <= i || !IsValidPeginWitness(txConst.wit.vtxinwit[i].m_pegin_witness, txin.prevout))) {\n            TxInErrorToJSON(txin, vErrors, \"Peg-in input has invalid proof.\");\n            continue;\n        }\n        const CScript& prevPubKey = txin.m_is_pegin ? GetPeginOutputFromWitness(txConst.wit.vtxinwit[i].m_pegin_witness).scriptPubKey : coins->vout[txin.prevout.n].scriptPubKey;\n        const CConfidentialValue& amount = txin.m_is_pegin ? GetPeginOutputFromWitness(txConst.wit.vtxinwit[i].m_pegin_witness).nValue : coins->vout[txin.prevout.n].nValue;\n\n        SignatureData sigdata;\n        // Only sign SIGHASH_SINGLE if there's a corresponding output:\n        if (!fHashSingle || (i < mergedTx.vout.size()))\n            ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);\n\n        // ... and merge in other signatures:\n        BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {\n            if (txv.vin.size() > i) {\n                sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));\n            }\n        }\n\n        UpdateTransaction(mergedTx, i, sigdata);\n\n        ScriptError serror = SCRIPT_ERR_OK;\n        if (!VerifyScript(txin.scriptSig, prevPubKey, (mergedTx.wit.vtxinwit.size() > i) ? &mergedTx.wit.vtxinwit[i].scriptWitness : NULL, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {\n            TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));\n        }\n    }\n    bool fComplete = vErrors.empty();\n\n    UniValue result(UniValue::VOBJ);\n    result.push_back(Pair(\"hex\", EncodeHexTx(mergedTx)));\n    result.push_back(Pair(\"complete\", fComplete));\n    if (!vErrors.empty()) {\n        result.push_back(Pair(\"errors\", vErrors));\n    }\n\n    AuditLogPrintf(\"%s : signrawtransaction %s\\n\", getUser(), EncodeHexTx(mergedTx));\n\n    return result;\n}\n\nUniValue sendrawtransaction(const JSONRPCRequest& request)\n{\n    if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)\n        throw runtime_error(\n            \"sendrawtransaction \\\"hexstring\\\" ( allowhighfees ) ( allowunblindfails )\\n\"\n            \"\\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\\n\"\n            \"\\nAlso see createrawtransaction and signrawtransaction calls.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"hexstring\\\"    (string, required) The hex string of the raw transaction)\\n\"\n            \"2. allowhighfees    (boolean, optional, default=false) Allow high fees\\n\"\n            \"3. allowblindfails  (boolean, optional, default=false) Allow outputs which have a pubkey attached (ie are blindable), which are unblinded\\n\"\n            \"\\nResult:\\n\"\n            \"\\\"hex\\\"             (string) The transaction hash in hex\\n\"\n            \"\\nExamples:\\n\"\n            \"\\nCreate a transaction\\n\"\n            + HelpExampleCli(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\" : \\\\\\\"mytxid\\\\\\\",\\\\\\\"vout\\\\\\\":0}]\\\" \\\"{\\\\\\\"myaddress\\\\\\\":0.01}\\\"\") +\n            \"Sign the transaction, and get back the hex\\n\"\n            + HelpExampleCli(\"signrawtransaction\", \"\\\"myhex\\\"\") +\n            \"\\nSend the transaction (signed hex)\\n\"\n            + HelpExampleCli(\"sendrawtransaction\", \"\\\"signedhex\\\"\") +\n            \"\\nAs a json rpc call\\n\"\n            + HelpExampleRpc(\"sendrawtransaction\", \"\\\"signedhex\\\"\")\n        );\n\n    LOCK(cs_main);\n    RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL));\n\n    // parse hex string from parameter\n    CMutableTransaction mtx;\n    if (!DecodeHexTx(mtx, request.params[0].get_str()))\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n    CTransactionRef tx(MakeTransactionRef(std::move(mtx)));\n    const uint256& hashTx = tx->GetHash();\n\n    bool fLimitFree = false;\n    CAmount nMaxRawTxFee = maxTxFee;\n    if (request.params.size() > 1 && request.params[1].get_bool())\n        nMaxRawTxFee = 0;\n\n    bool fOverrideBlindable = false;\n    if (request.params.size() > 2)\n        fOverrideBlindable = request.params[2].get_bool();\n\n    if (!fOverrideBlindable) {\n        for (unsigned i = 0; i < tx->vout.size(); i++) {\n            const CTxOut& txout = tx->vout[i];\n            if (txout.nValue.IsExplicit() && txout.nNonce.vchCommitment.size() != 0)\n                throw JSONRPCError(RPC_TRANSACTION_ERROR, strprintf(\"Output %u is unblinded, but has blinding pubkey attached, please use [raw]blindrawtransaction\", i));\n        }\n    }\n\n    CCoinsViewCache &view = *pcoinsTip;\n    const CCoins* existingCoins = view.AccessCoins(hashTx);\n    bool fHaveMempool = mempool.exists(hashTx);\n    bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;\n    if (!fHaveMempool && !fHaveChain) {\n        // push to local node and sync with wallets\n        CValidationState state;\n        bool fMissingInputs;\n        if (!AcceptToMemoryPool(mempool, state, std::move(tx), fLimitFree, &fMissingInputs, NULL, false, nMaxRawTxFee)) {\n            if (state.IsInvalid()) {\n                throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf(\"%i: %s\", state.GetRejectCode(), state.GetRejectReason()));\n            } else {\n                if (fMissingInputs) {\n                    throw JSONRPCError(RPC_TRANSACTION_ERROR, \"Missing inputs\");\n                }\n                throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());\n            }\n        }\n    } else if (fHaveChain) {\n        throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, \"transaction already in block chain\");\n    }\n    if(!g_connman)\n        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, \"Error: Peer-to-peer functionality missing or disabled\");\n    AuditLogPrintf(\"%s : sendrawtransaction %s\\n\", getUser(), hashTx.GetHex());\n\n    CInv inv(MSG_TX, hashTx);\n    g_connman->ForEachNode([&inv](CNode* pnode)\n    {\n        pnode->PushInventory(inv);\n    });\n    return hashTx.GetHex();\n}\n\nstatic const CRPCCommand commands[] =\n{ //  category              name                      actor (function)         okSafeMode\n  //  --------------------- ------------------------  -----------------------  ----------\n    { \"rawtransactions\",    \"getrawtransaction\",      &getrawtransaction,      true,  {\"txid\",\"verbose\"} },\n    { \"rawtransactions\",    \"createrawtransaction\",   &createrawtransaction,   true,  {\"inputs\",\"outputs\",\"locktime\",\"output_assets\"} },\n    { \"rawtransactions\",    \"decoderawtransaction\",   &decoderawtransaction,   true,  {\"hexstring\"} },\n    { \"rawtransactions\",    \"decodescript\",           &decodescript,           true,  {\"hexstring\"} },\n    { \"rawtransactions\",    \"sendrawtransaction\",     &sendrawtransaction,     false, {\"hexstring\",\"allowhighfees\"} },\n    { \"rawtransactions\",    \"signrawtransaction\",     &signrawtransaction,     false, {\"hexstring\",\"prevtxs\",\"privkeys\",\"sighashtype\"} }, /* uses wallet if enabled */\n    { \"rawtransactions\",    \"rawblindrawtransaction\", &rawblindrawtransaction, false, {}},\n#ifdef ENABLE_WALLET\n    { \"rawtransactions\",    \"blindrawtransaction\",    &blindrawtransaction,    true, {}},\n#endif\n    { \"blockchain\",         \"gettxoutproof\",          &gettxoutproof,          true,  {\"txids\", \"blockhash\"} },\n    { \"blockchain\",         \"verifytxoutproof\",       &verifytxoutproof,       true,  {\"proof\"} },\n};\n\nvoid RegisterRawTransactionRPCCommands(CRPCTable &t)\n{\n    for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)\n        t.appendCommand(commands[vcidx].name, &commands[vcidx]);\n}\n", "meta": {"hexsha": "4f96663c13dd9222271548364453b4eade166090", "size": 75067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rpc/rawtransaction.cpp", "max_stars_repo_name": "victorsintnicolaas/elements", "max_stars_repo_head_hexsha": "e7f04f35ba22ef9833fb2077eb8c2c9b246f4fd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-21T06:27:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-21T06:27:05.000Z", "max_issues_repo_path": "src/rpc/rawtransaction.cpp", "max_issues_repo_name": "goodluck2016/elements", "max_issues_repo_head_hexsha": "3912654e7d1b0d195040746ff412d88fd6883fa0", "max_issues_repo_licenses": ["MIT"], "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/rpc/rawtransaction.cpp", "max_forks_repo_name": "goodluck2016/elements", "max_forks_repo_head_hexsha": "3912654e7d1b0d195040746ff412d88fd6883fa0", "max_forks_repo_licenses": ["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.9993472585, "max_line_length": 325, "alphanum_fraction": 0.5911652257, "num_tokens": 18680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.1616638396671944}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018-2021 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/Dense>\n#include <iostream>\n#include <list>\n\n#include \"open3d/geometry/IntersectionTest.h\"\n#include \"open3d/geometry/KDTreeFlann.h\"\n#include \"open3d/geometry/PointCloud.h\"\n#include \"open3d/geometry/TriangleMesh.h\"\n#include \"open3d/utility/Logging.h\"\n\nnamespace open3d {\nnamespace geometry {\n\nclass BallPivotingVertex;\nclass BallPivotingEdge;\nclass BallPivotingTriangle;\n\ntypedef BallPivotingVertex* BallPivotingVertexPtr;\ntypedef std::shared_ptr<BallPivotingEdge> BallPivotingEdgePtr;\ntypedef std::shared_ptr<BallPivotingTriangle> BallPivotingTrianglePtr;\n\nclass BallPivotingVertex {\npublic:\n    enum Type { Orphan = 0, Front = 1, Inner = 2 };\n\n    BallPivotingVertex(int idx,\n                       const Eigen::Vector3d& point,\n                       const Eigen::Vector3d& normal)\n        : idx_(idx), point_(point), normal_(normal), type_(Orphan) {}\n\n    void UpdateType();\n\npublic:\n    int idx_;\n    const Eigen::Vector3d& point_;\n    const Eigen::Vector3d& normal_;\n    std::unordered_set<BallPivotingEdgePtr> edges_;\n    Type type_;\n};\n\nclass BallPivotingEdge {\npublic:\n    enum Type { Border = 0, Front = 1, Inner = 2 };\n\n    BallPivotingEdge(BallPivotingVertexPtr source, BallPivotingVertexPtr target)\n        : source_(source), target_(target), type_(Type::Front) {}\n\n    void AddAdjacentTriangle(BallPivotingTrianglePtr triangle);\n    BallPivotingVertexPtr GetOppositeVertex();\n\npublic:\n    BallPivotingVertexPtr source_;\n    BallPivotingVertexPtr target_;\n    BallPivotingTrianglePtr triangle0_;\n    BallPivotingTrianglePtr triangle1_;\n    Type type_;\n};\n\nclass BallPivotingTriangle {\npublic:\n    BallPivotingTriangle(BallPivotingVertexPtr vert0,\n                         BallPivotingVertexPtr vert1,\n                         BallPivotingVertexPtr vert2,\n                         Eigen::Vector3d ball_center)\n        : vert0_(vert0),\n          vert1_(vert1),\n          vert2_(vert2),\n          ball_center_(ball_center) {}\n\npublic:\n    BallPivotingVertexPtr vert0_;\n    BallPivotingVertexPtr vert1_;\n    BallPivotingVertexPtr vert2_;\n    Eigen::Vector3d ball_center_;\n};\n\nvoid BallPivotingVertex::UpdateType() {\n    if (edges_.empty()) {\n        type_ = Type::Orphan;\n    } else {\n        for (const BallPivotingEdgePtr& edge : edges_) {\n            if (edge->type_ != BallPivotingEdge::Type::Inner) {\n                type_ = Type::Front;\n                return;\n            }\n        }\n        type_ = Type::Inner;\n    }\n}\n\nvoid BallPivotingEdge::AddAdjacentTriangle(BallPivotingTrianglePtr triangle) {\n    if (triangle != triangle0_ && triangle != triangle1_) {\n        if (triangle0_ == nullptr) {\n            triangle0_ = triangle;\n            type_ = Type::Front;\n            // update orientation\n            if (BallPivotingVertexPtr opp = GetOppositeVertex()) {\n                Eigen::Vector3d tr_norm =\n                        (target_->point_ - source_->point_)\n                                .cross(opp->point_ - source_->point_);\n                tr_norm /= tr_norm.norm();\n                Eigen::Vector3d pt_norm =\n                        source_->normal_ + target_->normal_ + opp->normal_;\n                pt_norm /= pt_norm.norm();\n                if (pt_norm.dot(tr_norm) < 0) {\n                    std::swap(target_, source_);\n                }\n            } else {\n                utility::LogError(\"GetOppositeVertex() returns nullptr.\");\n            }\n        } else if (triangle1_ == nullptr) {\n            triangle1_ = triangle;\n            type_ = Type::Inner;\n        } else {\n            utility::LogDebug(\"!!! This case should not happen\");\n        }\n    }\n}\n\nBallPivotingVertexPtr BallPivotingEdge::GetOppositeVertex() {\n    if (triangle0_ != nullptr) {\n        if (triangle0_->vert0_->idx_ != source_->idx_ &&\n            triangle0_->vert0_->idx_ != target_->idx_) {\n            return triangle0_->vert0_;\n        } else if (triangle0_->vert1_->idx_ != source_->idx_ &&\n                   triangle0_->vert1_->idx_ != target_->idx_) {\n            return triangle0_->vert1_;\n        } else {\n            return triangle0_->vert2_;\n        }\n    } else {\n        return nullptr;\n    }\n}\n\nclass BallPivoting {\npublic:\n    BallPivoting(const PointCloud& pcd)\n        : has_normals_(pcd.HasNormals()), kdtree_(pcd) {\n        mesh_ = std::make_shared<TriangleMesh>();\n        mesh_->vertices_ = pcd.points_;\n        mesh_->vertex_normals_ = pcd.normals_;\n        mesh_->vertex_colors_ = pcd.colors_;\n        for (size_t vidx = 0; vidx < pcd.points_.size(); ++vidx) {\n            vertices.emplace_back(new BallPivotingVertex(static_cast<int>(vidx),\n                                                         pcd.points_[vidx],\n                                                         pcd.normals_[vidx]));\n        }\n    }\n\n    virtual ~BallPivoting() {\n        for (auto vert : vertices) {\n            delete vert;\n        }\n    }\n\n    bool ComputeBallCenter(int vidx1,\n                           int vidx2,\n                           int vidx3,\n                           double radius,\n                           Eigen::Vector3d& center) {\n        const Eigen::Vector3d& v1 = vertices[vidx1]->point_;\n        const Eigen::Vector3d& v2 = vertices[vidx2]->point_;\n        const Eigen::Vector3d& v3 = vertices[vidx3]->point_;\n        double c = (v2 - v1).squaredNorm();\n        double b = (v1 - v3).squaredNorm();\n        double a = (v3 - v2).squaredNorm();\n\n        double alpha = a * (b + c - a);\n        double beta = b * (a + c - b);\n        double gamma = c * (a + b - c);\n        double abg = alpha + beta + gamma;\n\n        if (abg < 1e-16) {\n            return false;\n        }\n\n        alpha = alpha / abg;\n        beta = beta / abg;\n        gamma = gamma / abg;\n\n        Eigen::Vector3d circ_center = alpha * v1 + beta * v2 + gamma * v3;\n        double circ_radius2 = a * b * c;\n\n        a = std::sqrt(a);\n        b = std::sqrt(b);\n        c = std::sqrt(c);\n        circ_radius2 = circ_radius2 /\n                       ((a + b + c) * (b + c - a) * (c + a - b) * (a + b - c));\n\n        double height = radius * radius - circ_radius2;\n        if (height >= 0.0) {\n            Eigen::Vector3d tr_norm = (v2 - v1).cross(v3 - v1);\n            tr_norm /= tr_norm.norm();\n            Eigen::Vector3d pt_norm = vertices[vidx1]->normal_ +\n                                      vertices[vidx2]->normal_ +\n                                      vertices[vidx3]->normal_;\n            pt_norm /= pt_norm.norm();\n            if (tr_norm.dot(pt_norm) < 0) {\n                tr_norm *= -1;\n            }\n\n            height = sqrt(height);\n            center = circ_center + height * tr_norm;\n            return true;\n        }\n        return false;\n    }\n\n    BallPivotingEdgePtr GetLinkingEdge(const BallPivotingVertexPtr& v0,\n                                       const BallPivotingVertexPtr& v1) {\n        for (BallPivotingEdgePtr edge0 : v0->edges_) {\n            for (BallPivotingEdgePtr edge1 : v1->edges_) {\n                if (edge0->source_->idx_ == edge1->source_->idx_ &&\n                    edge0->target_->idx_ == edge1->target_->idx_) {\n                    return edge0;\n                }\n            }\n        }\n        return nullptr;\n    }\n\n    void CreateTriangle(const BallPivotingVertexPtr& v0,\n                        const BallPivotingVertexPtr& v1,\n                        const BallPivotingVertexPtr& v2,\n                        const Eigen::Vector3d& center) {\n        utility::LogDebug(\n                \"[CreateTriangle] with v0.idx={}, v1.idx={}, v2.idx={}\",\n                v0->idx_, v1->idx_, v2->idx_);\n        BallPivotingTrianglePtr triangle =\n                std::make_shared<BallPivotingTriangle>(v0, v1, v2, center);\n\n        BallPivotingEdgePtr e0 = GetLinkingEdge(v0, v1);\n        if (e0 == nullptr) {\n            e0 = std::make_shared<BallPivotingEdge>(v0, v1);\n        }\n        e0->AddAdjacentTriangle(triangle);\n        v0->edges_.insert(e0);\n        v1->edges_.insert(e0);\n\n        BallPivotingEdgePtr e1 = GetLinkingEdge(v1, v2);\n        if (e1 == nullptr) {\n            e1 = std::make_shared<BallPivotingEdge>(v1, v2);\n        }\n        e1->AddAdjacentTriangle(triangle);\n        v1->edges_.insert(e1);\n        v2->edges_.insert(e1);\n\n        BallPivotingEdgePtr e2 = GetLinkingEdge(v2, v0);\n        if (e2 == nullptr) {\n            e2 = std::make_shared<BallPivotingEdge>(v2, v0);\n        }\n        e2->AddAdjacentTriangle(triangle);\n        v2->edges_.insert(e2);\n        v0->edges_.insert(e2);\n\n        v0->UpdateType();\n        v1->UpdateType();\n        v2->UpdateType();\n\n        Eigen::Vector3d face_normal =\n                ComputeFaceNormal(v0->point_, v1->point_, v2->point_);\n        if (face_normal.dot(v0->normal_) > -1e-16) {\n            mesh_->triangles_.emplace_back(\n                    Eigen::Vector3i(v0->idx_, v1->idx_, v2->idx_));\n        } else {\n            mesh_->triangles_.emplace_back(\n                    Eigen::Vector3i(v0->idx_, v2->idx_, v1->idx_));\n        }\n        mesh_->triangle_normals_.push_back(face_normal);\n    }\n\n    Eigen::Vector3d ComputeFaceNormal(const Eigen::Vector3d& v0,\n                                      const Eigen::Vector3d& v1,\n                                      const Eigen::Vector3d& v2) {\n        Eigen::Vector3d normal = (v1 - v0).cross(v2 - v0);\n        double norm = normal.norm();\n        if (norm > 0) {\n            normal /= norm;\n        }\n        return normal;\n    }\n\n    bool IsCompatible(const BallPivotingVertexPtr& v0,\n                      const BallPivotingVertexPtr& v1,\n                      const BallPivotingVertexPtr& v2) {\n        utility::LogDebug(\"[IsCompatible] v0.idx={}, v1.idx={}, v2.idx={}\",\n                          v0->idx_, v1->idx_, v2->idx_);\n        Eigen::Vector3d normal =\n                ComputeFaceNormal(v0->point_, v1->point_, v2->point_);\n        if (normal.dot(v0->normal_) < -1e-16) {\n            normal *= -1;\n        }\n        bool ret = normal.dot(v0->normal_) > -1e-16 &&\n                   normal.dot(v1->normal_) > -1e-16 &&\n                   normal.dot(v2->normal_) > -1e-16;\n        utility::LogDebug(\"[IsCompatible] returns = {}\", ret);\n        return ret;\n    }\n\n    BallPivotingVertexPtr FindCandidateVertex(\n            const BallPivotingEdgePtr& edge,\n            double radius,\n            Eigen::Vector3d& candidate_center) {\n        utility::LogDebug(\"[FindCandidateVertex] edge=({}, {}), radius={}\",\n                          edge->source_->idx_, edge->target_->idx_, radius);\n        BallPivotingVertexPtr src = edge->source_;\n        BallPivotingVertexPtr tgt = edge->target_;\n\n        const BallPivotingVertexPtr opp = edge->GetOppositeVertex();\n        if (opp == nullptr) {\n            utility::LogError(\"edge->GetOppositeVertex() returns nullptr.\");\n        }\n        utility::LogDebug(\"[FindCandidateVertex] edge=({}, {}), opp={}\",\n                          src->idx_, tgt->idx_, opp->idx_);\n        utility::LogDebug(\"[FindCandidateVertex] src={} => {}\", src->idx_,\n                          src->point_.transpose());\n        utility::LogDebug(\"[FindCandidateVertex] tgt={} => {}\", tgt->idx_,\n                          tgt->point_.transpose());\n        utility::LogDebug(\"[FindCandidateVertex] src={} => {}\", opp->idx_,\n                          opp->point_.transpose());\n\n        Eigen::Vector3d mp = 0.5 * (src->point_ + tgt->point_);\n        utility::LogDebug(\"[FindCandidateVertex] edge=({}, {}), mp={}\",\n                          edge->source_->idx_, edge->target_->idx_,\n                          mp.transpose());\n\n        BallPivotingTrianglePtr triangle = edge->triangle0_;\n        const Eigen::Vector3d& center = triangle->ball_center_;\n        utility::LogDebug(\"[FindCandidateVertex] edge=({}, {}), center={}\",\n                          edge->source_->idx_, edge->target_->idx_,\n                          center.transpose());\n\n        Eigen::Vector3d v = tgt->point_ - src->point_;\n        v /= v.norm();\n\n        Eigen::Vector3d a = center - mp;\n        a /= a.norm();\n\n        std::vector<int> indices;\n        std::vector<double> dists2;\n        kdtree_.SearchRadius(mp, 2 * radius, indices, dists2);\n        utility::LogDebug(\"[FindCandidateVertex] found {} potential candidates\",\n                          indices.size());\n\n        BallPivotingVertexPtr min_candidate = nullptr;\n        double min_angle = 2 * M_PI;\n        for (auto nbidx : indices) {\n            utility::LogDebug(\"[FindCandidateVertex] nbidx {:d}\", nbidx);\n            const BallPivotingVertexPtr& candidate = vertices[nbidx];\n            if (candidate->idx_ == src->idx_ || candidate->idx_ == tgt->idx_ ||\n                candidate->idx_ == opp->idx_) {\n                utility::LogDebug(\n                        \"[FindCandidateVertex] candidate {:d} is a triangle \"\n                        \"vertex of the edge\",\n                        candidate->idx_);\n                continue;\n            }\n            utility::LogDebug(\"[FindCandidateVertex] candidate={:d} => {}\",\n                              candidate->idx_, candidate->point_.transpose());\n\n            bool coplanar = IntersectionTest::PointsCoplanar(\n                    src->point_, tgt->point_, opp->point_, candidate->point_);\n            if (coplanar && (IntersectionTest::LineSegmentsMinimumDistance(\n                                     mp, candidate->point_, src->point_,\n                                     opp->point_) < 1e-12 ||\n                             IntersectionTest::LineSegmentsMinimumDistance(\n                                     mp, candidate->point_, tgt->point_,\n                                     opp->point_) < 1e-12)) {\n                utility::LogDebug(\n                        \"[FindCandidateVertex] candidate {:d} is intersecting \"\n                        \"the existing triangle\",\n                        candidate->idx_);\n                continue;\n            }\n\n            Eigen::Vector3d new_center;\n            if (!ComputeBallCenter(src->idx_, tgt->idx_, candidate->idx_,\n                                   radius, new_center)) {\n                utility::LogDebug(\n                        \"[FindCandidateVertex] candidate {:d} can not compute \"\n                        \"ball\",\n                        candidate->idx_);\n                continue;\n            }\n            utility::LogDebug(\"[FindCandidateVertex] candidate {:d} center={}\",\n                              candidate->idx_, new_center.transpose());\n\n            Eigen::Vector3d b = new_center - mp;\n            b /= b.norm();\n            utility::LogDebug(\n                    \"[FindCandidateVertex] candidate {:d} v={}, a={}, b={}\",\n                    candidate->idx_, v.transpose(), a.transpose(),\n                    b.transpose());\n\n            double cosinus = a.dot(b);\n            cosinus = std::min(cosinus, 1.0);\n            cosinus = std::max(cosinus, -1.0);\n            utility::LogDebug(\n                    \"[FindCandidateVertex] candidate {:d} cosinus={:f}\",\n                    candidate->idx_, cosinus);\n\n            double angle = std::acos(cosinus);\n\n            Eigen::Vector3d c = a.cross(b);\n            if (c.dot(v) < 0) {\n                angle = 2 * M_PI - angle;\n            }\n\n            if (angle >= min_angle) {\n                utility::LogDebug(\n                        \"[FindCandidateVertex] candidate {:d} angle {:f} > \"\n                        \"min_angle {:f}\",\n                        candidate->idx_, angle, min_angle);\n                continue;\n            }\n\n            bool empty_ball = true;\n            for (auto nbidx2 : indices) {\n                const BallPivotingVertexPtr& nb = vertices[nbidx2];\n                if (nb->idx_ == src->idx_ || nb->idx_ == tgt->idx_ ||\n                    nb->idx_ == candidate->idx_) {\n                    continue;\n                }\n                if ((new_center - nb->point_).norm() < radius - 1e-16) {\n                    utility::LogDebug(\n                            \"[FindCandidateVertex] candidate {:d} not an empty \"\n                            \"ball\",\n                            candidate->idx_);\n                    empty_ball = false;\n                    break;\n                }\n            }\n\n            if (empty_ball) {\n                utility::LogDebug(\"[FindCandidateVertex] candidate {:d} works\",\n                                  candidate->idx_);\n                min_angle = angle;\n                min_candidate = vertices[nbidx];\n                candidate_center = new_center;\n            }\n        }\n\n        if (min_candidate == nullptr) {\n            utility::LogDebug(\"[FindCandidateVertex] returns nullptr\");\n        } else {\n            utility::LogDebug(\"[FindCandidateVertex] returns {:d}\",\n                              min_candidate->idx_);\n        }\n        return min_candidate;\n    }\n\n    void ExpandTriangulation(double radius) {\n        utility::LogDebug(\"[ExpandTriangulation] radius={}\", radius);\n        while (!edge_front_.empty()) {\n            BallPivotingEdgePtr edge = edge_front_.front();\n            edge_front_.pop_front();\n            if (edge->type_ != BallPivotingEdge::Front) {\n                continue;\n            }\n\n            Eigen::Vector3d center;\n            BallPivotingVertexPtr candidate =\n                    FindCandidateVertex(edge, radius, center);\n            if (candidate == nullptr ||\n                candidate->type_ == BallPivotingVertex::Type::Inner ||\n                !IsCompatible(candidate, edge->source_, edge->target_)) {\n                edge->type_ = BallPivotingEdge::Type::Border;\n                border_edges_.push_back(edge);\n                continue;\n            }\n\n            BallPivotingEdgePtr e0 = GetLinkingEdge(candidate, edge->source_);\n            BallPivotingEdgePtr e1 = GetLinkingEdge(candidate, edge->target_);\n            if ((e0 != nullptr && e0->type_ != BallPivotingEdge::Type::Front) ||\n                (e1 != nullptr && e1->type_ != BallPivotingEdge::Type::Front)) {\n                edge->type_ = BallPivotingEdge::Type::Border;\n                border_edges_.push_back(edge);\n                continue;\n            }\n\n            CreateTriangle(edge->source_, edge->target_, candidate, center);\n\n            e0 = GetLinkingEdge(candidate, edge->source_);\n            e1 = GetLinkingEdge(candidate, edge->target_);\n            if (e0->type_ == BallPivotingEdge::Type::Front) {\n                edge_front_.push_front(e0);\n            }\n            if (e1->type_ == BallPivotingEdge::Type::Front) {\n                edge_front_.push_front(e1);\n            }\n        }\n    }\n\n    bool TryTriangleSeed(const BallPivotingVertexPtr& v0,\n                         const BallPivotingVertexPtr& v1,\n                         const BallPivotingVertexPtr& v2,\n                         const std::vector<int>& nb_indices,\n                         double radius,\n                         Eigen::Vector3d& center) {\n        utility::LogDebug(\n                \"[TryTriangleSeed] v0.idx={}, v1.idx={}, v2.idx={}, \"\n                \"radius={}\",\n                v0->idx_, v1->idx_, v2->idx_, radius);\n\n        if (!IsCompatible(v0, v1, v2)) {\n            return false;\n        }\n\n        BallPivotingEdgePtr e0 = GetLinkingEdge(v0, v2);\n        BallPivotingEdgePtr e1 = GetLinkingEdge(v1, v2);\n        if (e0 != nullptr && e0->type_ == BallPivotingEdge::Type::Inner) {\n            utility::LogDebug(\n                    \"[TryTriangleSeed] returns {} because e0 is inner edge\",\n                    false);\n            return false;\n        }\n        if (e1 != nullptr && e1->type_ == BallPivotingEdge::Type::Inner) {\n            utility::LogDebug(\n                    \"[TryTriangleSeed] returns {} because e1 is inner edge\",\n                    false);\n            return false;\n        }\n\n        if (!ComputeBallCenter(v0->idx_, v1->idx_, v2->idx_, radius, center)) {\n            utility::LogDebug(\n                    \"[TryTriangleSeed] returns {} could not compute ball \"\n                    \"center\",\n                    false);\n            return false;\n        }\n\n        // test if no other point is within the ball\n        for (const auto& nbidx : nb_indices) {\n            const BallPivotingVertexPtr& v = vertices[nbidx];\n            if (v->idx_ == v0->idx_ || v->idx_ == v1->idx_ ||\n                v->idx_ == v2->idx_) {\n                continue;\n            }\n            if ((center - v->point_).norm() < radius - 1e-16) {\n                utility::LogDebug(\n                        \"[TryTriangleSeed] returns {} computed ball is not \"\n                        \"empty\",\n                        false);\n                return false;\n            }\n        }\n\n        utility::LogDebug(\"[TryTriangleSeed] returns {}\", true);\n        return true;\n    }\n\n    bool TrySeed(BallPivotingVertexPtr& v, double radius) {\n        utility::LogDebug(\"[TrySeed] with v.idx={}, radius={}\", v->idx_,\n                          radius);\n        std::vector<int> indices;\n        std::vector<double> dists2;\n        kdtree_.SearchRadius(v->point_, 2 * radius, indices, dists2);\n        if (indices.size() < 3u) {\n            return false;\n        }\n\n        for (size_t nbidx0 = 0; nbidx0 < indices.size(); ++nbidx0) {\n            const BallPivotingVertexPtr& nb0 = vertices[indices[nbidx0]];\n            if (nb0->type_ != BallPivotingVertex::Type::Orphan) {\n                continue;\n            }\n            if (nb0->idx_ == v->idx_) {\n                continue;\n            }\n\n            int candidate_vidx2 = -1;\n            Eigen::Vector3d center;\n            for (size_t nbidx1 = nbidx0 + 1; nbidx1 < indices.size();\n                 ++nbidx1) {\n                const BallPivotingVertexPtr& nb1 = vertices[indices[nbidx1]];\n                if (nb1->type_ != BallPivotingVertex::Type::Orphan) {\n                    continue;\n                }\n                if (nb1->idx_ == v->idx_) {\n                    continue;\n                }\n                if (TryTriangleSeed(v, nb0, nb1, indices, radius, center)) {\n                    candidate_vidx2 = nb1->idx_;\n                    break;\n                }\n            }\n\n            if (candidate_vidx2 >= 0) {\n                const BallPivotingVertexPtr& nb1 = vertices[candidate_vidx2];\n\n                BallPivotingEdgePtr e0 = GetLinkingEdge(v, nb1);\n                if (e0 != nullptr &&\n                    e0->type_ != BallPivotingEdge::Type::Front) {\n                    continue;\n                }\n                BallPivotingEdgePtr e1 = GetLinkingEdge(nb0, nb1);\n                if (e1 != nullptr &&\n                    e1->type_ != BallPivotingEdge::Type::Front) {\n                    continue;\n                }\n                BallPivotingEdgePtr e2 = GetLinkingEdge(v, nb0);\n                if (e2 != nullptr &&\n                    e2->type_ != BallPivotingEdge::Type::Front) {\n                    continue;\n                }\n\n                CreateTriangle(v, nb0, nb1, center);\n\n                e0 = GetLinkingEdge(v, nb1);\n                e1 = GetLinkingEdge(nb0, nb1);\n                e2 = GetLinkingEdge(v, nb0);\n                if (e0->type_ == BallPivotingEdge::Type::Front) {\n                    edge_front_.push_front(e0);\n                }\n                if (e1->type_ == BallPivotingEdge::Type::Front) {\n                    edge_front_.push_front(e1);\n                }\n                if (e2->type_ == BallPivotingEdge::Type::Front) {\n                    edge_front_.push_front(e2);\n                }\n\n                if (edge_front_.size() > 0) {\n                    utility::LogDebug(\n                            \"[TrySeed] edge_front_.size() > 0 => return \"\n                            \"true\");\n                    return true;\n                }\n            }\n        }\n\n        utility::LogDebug(\"[TrySeed] return false\");\n        return false;\n    }\n\n    void FindSeedTriangle(double radius) {\n        for (size_t vidx = 0; vidx < vertices.size(); ++vidx) {\n            utility::LogDebug(\"[FindSeedTriangle] with radius={}, vidx={}\",\n                              radius, vidx);\n            if (vertices[vidx]->type_ == BallPivotingVertex::Type::Orphan) {\n                if (TrySeed(vertices[vidx], radius)) {\n                    ExpandTriangulation(radius);\n                }\n            }\n        }\n    }\n\n    std::shared_ptr<TriangleMesh> Run(const std::vector<double>& radii) {\n        if (!has_normals_) {\n            utility::LogError(\"ReconstructBallPivoting requires normals\");\n        }\n\n        mesh_->triangles_.clear();\n\n        for (double radius : radii) {\n            utility::LogDebug(\"[Run] ################################\");\n            utility::LogDebug(\"[Run] change to radius {:.4f}\", radius);\n            if (radius <= 0) {\n                utility::LogError(\n                        \"got an invalid, negative radius as parameter\");\n            }\n\n            // update radius => update border edges\n            for (auto it = border_edges_.begin(); it != border_edges_.end();) {\n                BallPivotingEdgePtr edge = *it;\n                BallPivotingTrianglePtr triangle = edge->triangle0_;\n                utility::LogDebug(\n                        \"[Run] try edge {:d}-{:d} of triangle {:d}-{:d}-{:d}\",\n                        edge->source_->idx_, edge->target_->idx_,\n                        triangle->vert0_->idx_, triangle->vert1_->idx_,\n                        triangle->vert2_->idx_);\n\n                Eigen::Vector3d center;\n                if (ComputeBallCenter(triangle->vert0_->idx_,\n                                      triangle->vert1_->idx_,\n                                      triangle->vert2_->idx_, radius, center)) {\n                    utility::LogDebug(\"[Run]   yes, we can work on this\");\n                    std::vector<int> indices;\n                    std::vector<double> dists2;\n                    kdtree_.SearchRadius(center, radius, indices, dists2);\n                    bool empty_ball = true;\n                    for (auto idx : indices) {\n                        if (idx != triangle->vert0_->idx_ &&\n                            idx != triangle->vert1_->idx_ &&\n                            idx != triangle->vert2_->idx_) {\n                            utility::LogDebug(\n                                    \"[Run]   but no, the ball is not empty\");\n                            empty_ball = false;\n                            break;\n                        }\n                    }\n\n                    if (empty_ball) {\n                        utility::LogDebug(\n                                \"[Run]   yeah, add edge to edge_front_: {:d}\",\n                                edge_front_.size());\n                        edge->type_ = BallPivotingEdge::Type::Front;\n                        edge_front_.push_back(edge);\n                        it = border_edges_.erase(it);\n                        continue;\n                    }\n                }\n                ++it;\n            }\n\n            // do the reconstruction\n            if (edge_front_.empty()) {\n                FindSeedTriangle(radius);\n            } else {\n                ExpandTriangulation(radius);\n            }\n\n            utility::LogDebug(\"[Run] mesh_ has {:d} triangles\",\n                              mesh_->triangles_.size());\n            utility::LogDebug(\"[Run] ################################\");\n        }\n        return mesh_;\n    }\n\nprivate:\n    bool has_normals_;\n    KDTreeFlann kdtree_;\n    std::list<BallPivotingEdgePtr> edge_front_;\n    std::list<BallPivotingEdgePtr> border_edges_;\n    std::vector<BallPivotingVertexPtr> vertices;\n    std::shared_ptr<TriangleMesh> mesh_;\n};\n\nstd::shared_ptr<TriangleMesh> TriangleMesh::CreateFromPointCloudBallPivoting(\n        const PointCloud& pcd, const std::vector<double>& radii) {\n    BallPivoting bp(pcd);\n    return bp.Run(radii);\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "d550cccc5330a6d437ebd6975402f4f2fda1b93f", "size": 29243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/open3d/geometry/SurfaceReconstructionBallPivoting.cpp", "max_stars_repo_name": "tiagomfmadeira/Open3D", "max_stars_repo_head_hexsha": "d63c6d2faff395cb474b6379d0a5f5f8e573811b", "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/open3d/geometry/SurfaceReconstructionBallPivoting.cpp", "max_issues_repo_name": "tiagomfmadeira/Open3D", "max_issues_repo_head_hexsha": "d63c6d2faff395cb474b6379d0a5f5f8e573811b", "max_issues_repo_licenses": ["MIT"], "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/SurfaceReconstructionBallPivoting.cpp", "max_forks_repo_name": "tiagomfmadeira/Open3D", "max_forks_repo_head_hexsha": "d63c6d2faff395cb474b6379d0a5f5f8e573811b", "max_forks_repo_licenses": ["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.3263433814, "max_line_length": 80, "alphanum_fraction": 0.501419143, "num_tokens": 6671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.16166383639494009}}
{"text": "#include \"Frame.h\"\n#include \"FeatureFrontEndCV.h\"\n#include \"FrameWiseGeometry.h\"\n\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/NavSatFix.h>\n#include <geometry_msgs/QuaternionStamped.h> //for DJI.\n\n\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/Quaternion.h> //for apm and pixhawk.\n\n#include <visualization_msgs/Marker.h> //for visualization.\n\n#include <cv_bridge/cv_bridge.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/time_synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <ros/duration.h>\n#include <math.h>\n\n#include <geometry_msgs/PoseStamped.h> //for px4's external pose estimate\n#include <sensor_msgs/Imu.h>\n\n#include <mavros_msgs/CommandBool.h>\n#include <mavros_msgs/SetMode.h>\n#include <mavros_msgs/State.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>  // linear algebra\n#include <Eigen/StdVector>\n\n\n\n\n#include <deque>\n#include <chrono>\n#include \"SLAM_simple.h\"\nusing namespace std;\n\n\n\nSLAM_simple* pSLAM;\nvoid FetchImageCallback(const sensor_msgs::ImageConstPtr& img1,const sensor_msgs::ImageConstPtr& img2,const sensor_msgs::ImageConstPtr& img3,const sensor_msgs::ImageConstPtr& img4)\n{\n    LOG(INFO)<<\"In Fetch Image Callback:\"<<endl;\n    cv_bridge::CvImageConstPtr p1,p2,p3,p4;\n    shared_ptr<cv::Mat> m1,m2,m3,m4;\n    try\n    {\n        p1 = cv_bridge::toCvShare(img1);\n        p2 = cv_bridge::toCvShare(img2);\n        p3 = cv_bridge::toCvShare(img3);\n        p4 = cv_bridge::toCvShare(img4);\n        m1 = shared_ptr<cv::Mat> (new cv::Mat(p1->image.clone()));\n        m2 = shared_ptr<cv::Mat> (new cv::Mat(p2->image.clone()));\n        m3 = shared_ptr<cv::Mat> (new cv::Mat(p3->image.clone()));\n        m4 = shared_ptr<cv::Mat> (new cv::Mat(p4->image.clone()));\n    }\n    catch (cv_bridge::Exception& e)\n    {\n        ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n        LOG(ERROR)<<\"cv_bridge exception: %s\"<<e.what()<<endl;\n        cout<<\"cv_bridge exception: %s\"<<e.what()<<endl;\n        return;\n    }\n    LOG(INFO)<<\"Images caught! Will call iterateWith4Imgs.\"<<endl;\n    pSLAM->iterateWith4Imgs(m1,m2,m3,m4);\n    LOG(INFO)<<\"iterateWith4Imgs() finished.\"<<endl;\n}\nvoid FetchIMUCallBack(const sensor_msgs::ImuConstPtr& imu)\n{\n    sensor_msgs::Imu imu_copy = *imu;\n    pSLAM->addIMUInfo(imu_copy);\n}\n\nint main(int argc,char** argv)\n{\n    google::InitGoogleLogging(argv[0]);\n    ros::init(argc,argv,\"test_VO_node\");\n    ros::NodeHandle nh;\n    std::string front_left_topic(\"/gi/forward/left/image_raw\"),front_right_topic(\"/gi/forward/right/image_raw\"),left_left_topic(\"/gi/leftward/left/image_raw\"),left_right_topic(\"/gi/leftward/right/image_raw\");\n\n    message_filters::Subscriber<sensor_msgs::Image> front_left_sub(nh, front_left_topic, 10);\n    message_filters::Subscriber<sensor_msgs::Image> front_right_sub(nh, front_right_topic, 10);\n    message_filters::Subscriber<sensor_msgs::Image> down_left_sub(nh, left_left_topic, 10);\n    message_filters::Subscriber<sensor_msgs::Image> down_right_sub(nh, left_right_topic, 10);\n\n    typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::Image,sensor_msgs::Image,sensor_msgs::Image> sync_pol;\n    message_filters::Synchronizer<sync_pol> sync(sync_pol(10), front_left_sub, front_right_sub,down_left_sub,down_right_sub);\n    sync.setMaxIntervalDuration(ros::Duration(0.01));\n    sync.registerCallback(boost::bind(FetchImageCallback, _1, _2,_3,_4));\n    ros::Subscriber sub = nh.subscribe(\"/mavros/imu/data_raw\",100,FetchIMUCallBack);\n    pSLAM = new SLAM_simple(argc,argv);\n    ros::spin();\n}\n\n", "meta": {"hexsha": "9dcb13f21a05d0b6f98c724b8833f78a48d652f2", "size": 3616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deprecated/algorithms/MultiCamSLAM/src/test/test_SLAM_simple.cpp", "max_stars_repo_name": "mfkiwl/GAAS", "max_stars_repo_head_hexsha": "29ab17d3e8a4ba18edef3a57c36d8db6329fac73", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "algorithms/MultiCamSLAM/src/test/test_SLAM_simple.cpp", "max_issues_repo_name": "Wayne-xixi/GAAS", "max_issues_repo_head_hexsha": "308ff4267ccc6fcad77eef07e21fa006cc2cdd5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "algorithms/MultiCamSLAM/src/test/test_SLAM_simple.cpp", "max_forks_repo_name": "Wayne-xixi/GAAS", "max_forks_repo_head_hexsha": "308ff4267ccc6fcad77eef07e21fa006cc2cdd5f", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 36.16, "max_line_length": 208, "alphanum_fraction": 0.7201327434, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16166383312268587}}
{"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_DETAIL_SHUFFLE_DEFAULT_MATCHER_HPP_INCLUDED\n#define BOOST_SIMD_DETAIL_SHUFFLE_DEFAULT_MATCHER_HPP_INCLUDED\n\n#include <boost/simd/config.hpp>\n#include <boost/simd/detail/brigand.hpp>\n#include <boost/simd/function/extract.hpp>\n#include <boost/simd/function/combine.hpp>\n#include <boost/simd/function/slice.hpp>\n#include <boost/simd/arch/common/simd/function/shuffle/identity.hpp>\n#include <boost/simd/arch/common/simd/function/shuffle/broadcast.hpp>\n\nnamespace boost { namespace simd { namespace detail\n{\n  // -----------------------------------------------------------------------------------------------\n  // Half-permutation snatcher\n  template<bool isUpper, int... Ps> struct half_\n  {\n    using perm = brigand::integral_list<int,Ps...>;\n    template<typename I, typename C>\n    struct apply : brigand::at_c < perm, isUpper ? I::value+C::value : I::value>\n    {};\n  };\n\n  // -----------------------------------------------------------------------------------------------\n  // Default matcher - don't do anything special but shuffle manually\n  struct  default_matcher\n        : identity_shuffle\n        , broadcast_shuffle\n  {\n    // please, trigger on identity & broadcast pattern to do the correct thing\n    using identity_shuffle::process;\n    using broadcast_shuffle::process;\n\n    // Unary helpers\n    template<typename T, int N> BOOST_FORCEINLINE static typename T::value_type\n    fill_( const T& a0, std::integral_constant<int,N> const& )\n    {\n      return boost::simd::extract<N>(a0);\n    }\n\n    template<typename T> BOOST_FORCEINLINE static typename T::value_type\n    fill_(const T&, std::integral_constant<int,-1> const&)\n    {\n      return typename T::value_type{0};\n    }\n\n    // Unary permutation handler\n    template<typename T, int... P>\n    static BOOST_FORCEINLINE T process(T const& a0, pattern_<P...> const& p)\n    {\n      return process(a0, p, typename T::storage_kind{});\n    }\n\n    template<typename T, int... P>\n    static BOOST_FORCEINLINE T process(T const& a0, pattern_<P...> const&, aggregate_storage const&)\n    {\n      // Aggregate storage has a chance to be the combination of two regular shuffles\n      auto s = slice(a0);\n      return combine( shuffle<half_<false,P...>>(s[0],s[1])\n                    , shuffle<half_<true ,P...>>(s[0],s[1])\n                    );\n    }\n\n    template<typename K, typename T, int... P>\n    static BOOST_FORCEINLINE T process(T const& a0, pattern_<P...> const&, K const&)\n    { return T( fill_ (a0 , std::integral_constant<int,P>{} )... );\n    }\n\n    // Binary permutation handler\n    template<typename T, int... P>\n    static BOOST_FORCEINLINE T process(T const& a0, T const& a1, pattern_<P...> const&)\n    {\n      return T( fill_ (a0 ,a1 , std::integral_constant<int,P>{}\n                              , brigand::bool_<(P<T::static_size)>{}\n                      )...\n              );\n    }\n\n    // Binary helpers\n    template<typename T, int N>\n    BOOST_FORCEINLINE static typename T::value_type\n    fill_ ( const T& a0, const T&\n          , std::integral_constant<int,N> const&, std::true_type const&\n          )\n    {\n      return  boost::simd::extract<N>(a0);\n    }\n\n    template<typename T>\n    BOOST_FORCEINLINE static typename T::value_type\n    fill_ ( const T&, const T&\n          , std::integral_constant<int,-1> const&, std::true_type const&\n          )\n    {\n      return 0;\n    }\n\n    template<typename T, int N>\n    BOOST_FORCEINLINE static typename T::value_type\n    fill_ (const T&, const T & a1\n          , std::integral_constant<int,N> const&, std::false_type const&\n          )\n    {\n      return  boost::simd::extract<N-T::static_size>(a1);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "2e37ef986946ab7e1ed4e8377c8d07f7d110d7e3", "size": 4056, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/detail/shuffle/default_matcher.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/detail/shuffle/default_matcher.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/detail/shuffle/default_matcher.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": 34.3728813559, "max_line_length": 100, "alphanum_fraction": 0.5796351085, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16166383312268587}}
{"text": "#include \"annotator.hpp\"\n#include \"extractor.hpp\"\n\n#include <cstddef>\n\n// For boost RTree\n#include <boost/geometry.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\n//#include <boost/log/trivial.hpp>\n\nRouteAnnotator::RouteAnnotator(const Database &db) : db(db) {}\n\nstd::vector<internal_nodeid_t>\nRouteAnnotator::coordinates_to_internal(const std::vector<point_t> &points)\n{\n\n    static const boost::geometry::strategy::distance::haversine<double> haversine(6372795.0);\n    static const double MAX_DISTANCE = 5;\n\n    if (!db.rtree)\n        throw RtreeError(\"RTree is null - call build_rtree() on database before use\");\n\n    std::vector<internal_nodeid_t> internal_nodeids;\n    for (const auto &point : points)\n    {\n        std::vector<value_t> rtree_results;\n\n        // Search for the nearest point to the one supplied\n        db.rtree->query(boost::geometry::index::nearest(point, 1),\n                        std::back_inserter(rtree_results));\n\n        // If we got exactly one hit (we should), append it to our nodeids list, if it\n        // was within 1m\n        /*\n        BOOST_LOG_TRIVIAL(debug) << \"Distance from \" << point.get<0>() << \",\" << point.get<1>()\n                                 << \" to  \" << rtree_results[0].first.get<0>() << \",\"\n                                 << rtree_results[0].first.get<1>() << \" is \"\n                                 << boost::geometry::distance(point, rtree_results[0].first,\n                                                              haversine)\n                                 << \"\\n\";\n        */\n        if (rtree_results.size() == 1 &&\n            boost::geometry::distance(point, rtree_results[0].first, haversine) < MAX_DISTANCE)\n        {\n            internal_nodeids.push_back(rtree_results[0].second);\n        }\n        // otherwise, insert a 0 value, this coordinate didn't match\n        else\n        {\n            internal_nodeids.push_back(INVALID_INTERNAL_NODEID);\n        }\n    }\n    return internal_nodeids;\n}\n\nstd::vector<internal_nodeid_t>\nRouteAnnotator::external_to_internal(const std::vector<external_nodeid_t> &external_nodeids)\n{\n    // Convert external node ids into internal ones\n    std::vector<internal_nodeid_t> results;\n    std::for_each(external_nodeids.begin(), external_nodeids.end(),\n                  [this, &results](const external_nodeid_t n) {\n                      const auto internal_node_id = db.external_internal_map.find(n);\n                      if (internal_node_id == db.external_internal_map.end())\n                      {\n                          // Push an invalid nodeid into the list if we didn't match\n                          results.push_back(INVALID_INTERNAL_NODEID);\n                      }\n                      else\n                      {\n                          results.push_back(internal_node_id->second);\n                      }\n                  });\n    return results;\n}\n\nannotated_route_t RouteAnnotator::annotateRoute(const std::vector<internal_nodeid_t> &route)\n{\n    annotated_route_t result;\n\n    for (std::size_t i = 0; i < route.size() - 1; i++)\n    {\n        const auto way_id = [&]() {\n            if (route[i] < route[i + 1])\n            {\n                return db.pair_way_map.find(std::make_pair(route[i], route[i + 1]));\n            }\n            else\n            {\n                return db.pair_way_map.find(std::make_pair(route[i + 1], route[i]));\n            }\n        }();\n        if (way_id != db.pair_way_map.end())\n        {\n            result.push_back(way_id->second.id);\n        }\n        else\n        {\n            result.push_back(INVALID_WAYID);\n        }\n    }\n    return result;\n}\n\nstd::string RouteAnnotator::get_tag_key(const std::size_t index)\n{\n    return db.getstring(db.key_value_pairs[index].first);\n}\n\nstd::string RouteAnnotator::get_tag_value(const std::size_t index)\n{\n    return db.getstring(db.key_value_pairs[index].second);\n}\n\ntagrange_t RouteAnnotator::get_tag_range(const wayid_t way_id) { return db.way_tag_ranges[way_id]; }\n\nwayid_t RouteAnnotator::get_external_way_id(const wayid_t way_id)\n{\n    return db.internal_to_external_way_id_map[way_id];\n}\n", "meta": {"hexsha": "6a346b713f59b209700169223511f1994634f297", "size": 4183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/annotator.cpp", "max_stars_repo_name": "ccebrand/route-annotator", "max_stars_repo_head_hexsha": "e139e93550ad60cd29b5e230a3146929dfeb29b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T09:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T12:34:42.000Z", "max_issues_repo_path": "src/annotator.cpp", "max_issues_repo_name": "ccebrand/route-annotator", "max_issues_repo_head_hexsha": "e139e93550ad60cd29b5e230a3146929dfeb29b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2016-05-18T23:12:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T15:07:55.000Z", "max_forks_repo_path": "src/annotator.cpp", "max_forks_repo_name": "ccebrand/route-annotator", "max_forks_repo_head_hexsha": "e139e93550ad60cd29b5e230a3146929dfeb29b6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2017-03-06T00:21:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T06:43:23.000Z", "avg_line_length": 34.0081300813, "max_line_length": 100, "alphanum_fraction": 0.5821180971, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.16150978428858426}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/Dense>\n#include <boost/hana.hpp>\nnamespace hana = boost::hana;\n\n#include <kontiki/types.h>\n#include <kontiki/measurements/newton_rscamera_measurement.h>\n#include <kontiki/sfm/landmark.h>\n#include <kontiki/sfm/observation.h>\n\n#include \"../camera_defs.h\"\n#include \"../trajectory_defs.h\"\n\n#include \"measurement_helper.h\"\n\n\nnamespace py = pybind11;\n\nPYBIND11_MODULE(_newton_rscamera_measurement, m) {\n  m.doc() = \"Newton rolling shutter projection\";\n\n  // Create one StaticRsMeasurement class for each camera type\n  hana::for_each(camera_types, [&](auto ct) {\n    using CameraModel = typename decltype(ct)::type;\n\n    using Class = kontiki::measurements::NewtonRsCameraMeasurement<CameraModel>;\n    std::string pyclass_name = \"NewtonRsCameraMeasurement_\" + std::string(CameraModel::CLASS_ID);\n    auto cls = py::class_<Class, std::shared_ptr<Class>>(m, pyclass_name.c_str());\n\n    cls.doc() = R\"pbdoc( Newton-based rolling shutter projection\n\n    Projects a landmark into a rolling shutter camera using the Newton method.\n    This method should produce measurements such that the projected image row\n    is consistent with the projection time.\n    However, this is not a guarantee, so if you really need to make sure that the\n    rolling shutter prjection time constraint is fulfilled, we recommend to at least\n    check the result before accepting it.\n    )pbdoc\";\n\n    declare_measurement_common<Class>(cls);\n    cls.def(py::init<std::shared_ptr<CameraModel>, std::shared_ptr<kontiki::sfm::Observation>, double, double>());\n    cls.def(py::init<std::shared_ptr<CameraModel>, std::shared_ptr<kontiki::sfm::Observation>, double>());\n    cls.def(py::init<std::shared_ptr<CameraModel>, std::shared_ptr<kontiki::sfm::Observation>>());\n\n    cls.def_readonly(\"camera\", &Class::camera);\n    cls.def_readonly(\"observation\", &Class::observation);\n    cls.def_readwrite(\"weight\", &Class::weight, \"Image residual weight (applied before loss)\");\n\n    // Declare the project() function for all trajectory types\n    hana::for_each(trajectory_types, [&](auto tt) {\n      using TrajectoryModel = typename decltype(tt)::type;\n\n      // Use temporary to extract TrajectoryModel from TrajectoryImpl\n      cls.def(\"project\", [](Class &self, const TrajectoryModel &trajectory) {\n        return self.template Project<TrajectoryModel>(trajectory);\n        });\n\n    }); // for_each(trajectory_types)\n  }); // for_each(camera_types)\n}", "meta": {"hexsha": "851c84c86a8298c69d2084f949c0a6b99e7ef6ac", "size": 2482, "ext": "cc", "lang": "C++", "max_stars_repo_path": "python/src/kontiki/measurements/py_newton_rscamera_measurement.cc", "max_stars_repo_name": "copark86/kontiki", "max_stars_repo_head_hexsha": "431349f9500c6ee954bc46c0643f49281163a7f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2018-06-19T05:59:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:25:29.000Z", "max_issues_repo_path": "python/src/kontiki/measurements/py_newton_rscamera_measurement.cc", "max_issues_repo_name": "copark86/kontiki", "max_issues_repo_head_hexsha": "431349f9500c6ee954bc46c0643f49281163a7f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T06:52:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T15:27:11.000Z", "max_forks_repo_path": "python/src/kontiki/measurements/py_newton_rscamera_measurement.cc", "max_forks_repo_name": "hovren/kontiki", "max_forks_repo_head_hexsha": "4c44edb7ef041c6abd549e1fe66fe3e9ca255399", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T12:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:34:13.000Z", "avg_line_length": 40.0322580645, "max_line_length": 114, "alphanum_fraction": 0.7280419017, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.16150978093868168}}
{"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 <ored/model/lgmdata.hpp>\n#include <ored/utilities/correlationmatrix.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ored/utilities/to_string.hpp>\n\n#include <qle/models/fxbsconstantparametrization.hpp>\n#include <qle/models/fxbspiecewiseconstantparametrization.hpp>\n#include <qle/models/fxeqoptionhelper.hpp>\n#include <qle/models/irlgm1fconstantparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiseconstanthullwhiteadaptor.hpp>\n#include <qle/models/irlgm1fpiecewiseconstantparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiselinearparametrization.hpp>\n#include <qle/pricingengines/analyticcclgmfxoptionengine.hpp>\n#include <qle/pricingengines/analyticlgmswaptionengine.hpp>\n\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/utilities/dataformatters.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/lexical_cast.hpp>\n\nnamespace ore {\nnamespace data {\n\nbool LgmData::operator==(const LgmData& rhs) {\n\n    if (qualifier_ != rhs.qualifier_ || calibrationType_ != rhs.calibrationType_ || revType_ != rhs.revType_ ||\n        volType_ != rhs.volType_ || calibrateH_ != rhs.calibrateH_ || hType_ != rhs.hType_ || hTimes_ != rhs.hTimes_ ||\n        hValues_ != rhs.hValues_ || calibrateA_ != rhs.calibrateA_ || aType_ != rhs.aType_ || aTimes_ != rhs.aTimes_ ||\n        aValues_ != rhs.aValues_ || shiftHorizon_ != rhs.shiftHorizon_ || scaling_ != rhs.scaling_ ||\n        optionExpiries_ != rhs.optionExpiries_ || optionTerms_ != rhs.optionTerms_ ||\n        optionStrikes_ != rhs.optionStrikes_) {\n        return false;\n    }\n    return true;\n}\n\nbool LgmData::operator!=(const LgmData& rhs) { return !(*this == rhs); }\n\nstd::ostream& operator<<(std::ostream& oss, const ParamType& type) {\n    if (type == ParamType::Constant)\n        oss << \"CONSTANT\";\n    else if (type == ParamType::Piecewise)\n        oss << \"PIECEWISE\";\n    else\n        QL_FAIL(\"Parameter type not covered by <<\");\n    return oss;\n}\n\nParamType parseParamType(const string& s) {\n    if (boost::algorithm::to_upper_copy(s) == \"CONSTANT\")\n        return ParamType::Constant;\n    else if (boost::algorithm::to_upper_copy(s) == \"PIECEWISE\")\n        return ParamType::Piecewise;\n    else\n        QL_FAIL(\"Parameter type \" << s << \" not recognized\");\n}\n\nCalibrationType parseCalibrationType(const string& s) {\n    if (boost::algorithm::to_upper_copy(s) == \"BOOTSTRAP\")\n        return CalibrationType::Bootstrap;\n    else if (boost::algorithm::to_upper_copy(s) == \"BESTFIT\")\n        return CalibrationType::BestFit;\n    else if (boost::algorithm::to_upper_copy(s) == \"NONE\")\n        return CalibrationType::None;\n    else\n        QL_FAIL(\"Calibration type \" << s << \" not recognized\");\n}\n\nstd::ostream& operator<<(std::ostream& oss, const CalibrationType& type) {\n    if (type == CalibrationType::Bootstrap)\n        oss << \"BOOTSTRAP\";\n    else if (type == CalibrationType::BestFit)\n        oss << \"BESTFIT\";\n    else if (type == CalibrationType::None)\n        oss << \"NONE\";\n    else\n        QL_FAIL(\"Calibration type not covered\");\n    return oss;\n}\n\nLgmData::ReversionType parseReversionType(const string& s) {\n    if (boost::algorithm::to_upper_copy(s) == \"HULLWHITE\")\n        return LgmData::ReversionType::HullWhite;\n    else if (boost::algorithm::to_upper_copy(s) == \"HAGAN\")\n        return LgmData::ReversionType::Hagan;\n    else\n        QL_FAIL(\"Reversion type \" << s << \" not recognized\");\n}\n\nstd::ostream& operator<<(std::ostream& oss, const LgmData::ReversionType& type) {\n    if (type == LgmData::ReversionType::HullWhite)\n        oss << \"HULLWHITE\";\n    else if (type == LgmData::ReversionType::Hagan)\n        oss << \"HAGAN\";\n    else\n        QL_FAIL(\"Reversion type not covered\");\n    return oss;\n}\n\nLgmData::VolatilityType parseVolatilityType(const string& s) {\n    if (boost::algorithm::to_upper_copy(s) == \"HULLWHITE\")\n        return LgmData::VolatilityType::HullWhite;\n    else if (boost::algorithm::to_upper_copy(s) == \"HAGAN\")\n        return LgmData::VolatilityType::Hagan;\n    else\n        QL_FAIL(\"Volatility type \" << s << \" not recognized\");\n}\n\nstd::ostream& operator<<(std::ostream& oss, const LgmData::VolatilityType& type) {\n    if (type == LgmData::VolatilityType::HullWhite)\n        oss << \"HULLWHITE\";\n    else if (type == LgmData::VolatilityType::Hagan)\n        oss << \"HAGAN\";\n    else\n        QL_FAIL(\"Volatility type not covered\");\n    return oss;\n}\n\nCalibrationStrategy parseCalibrationStrategy(const string& s) {\n    if (boost::algorithm::to_upper_copy(s) == \"COTERMINALATM\")\n        return CalibrationStrategy::CoterminalATM;\n    else if (boost::algorithm::to_upper_copy(s) == \"COTERMINALDEALSTRIKE\")\n        return CalibrationStrategy::CoterminalDealStrike;\n    else if (boost::algorithm::to_upper_copy(s) == \"UNDERLYINGATM\")\n        return CalibrationStrategy::UnderlyingATM;\n    else if (boost::algorithm::to_upper_copy(s) == \"UNDERLYINGDEALSTRIKE\")\n        return CalibrationStrategy::UnderlyingDealStrike;\n    else if (boost::algorithm::to_upper_copy(s) == \"NONE\")\n        return CalibrationStrategy::None;\n    else\n        QL_FAIL(\"Calibration strategy \" << s << \" not recognized\");\n}\n\nstd::ostream& operator<<(std::ostream& oss, const CalibrationStrategy& type) {\n    if (type == CalibrationStrategy::CoterminalATM)\n        oss << \"COTERMINALATM\";\n    else if (type == CalibrationStrategy::CoterminalDealStrike)\n        oss << \"COTERMINALDEALSTRIKE\";\n    else if (type == CalibrationStrategy::UnderlyingATM)\n        oss << \"UNDERLYINGATM\";\n    else if (type == CalibrationStrategy::UnderlyingDealStrike)\n        oss << \"UNDERLYINGDEALSTRIKE\";\n    else if (type == CalibrationStrategy::None)\n        oss << \"NONE\";\n    else\n        QL_FAIL(\"Calibration strategy not covered\");\n    return oss;\n}\n\n// TODO: use fromXML here, filtering is not done during parsing.\nvoid LgmData::fromFile(const std::string& fileName, const std::string& qualifier) {\n    LOG(\"load model configuration from \" << fileName);\n    clear();\n    XMLDocument doc(fileName);\n    XMLNode* root = doc.getFirstNode(\"Models\");\n    Size count = 0;\n    for (XMLNode* child = XMLUtils::getChildNode(root, \"LGM\"); child; child = XMLUtils::getNextSibling(child, \"LGM\")) {\n        std::string childCcy = XMLUtils::getAttribute(child, \"qualifier\");\n        if (qualifier == childCcy) {\n            fromXML(child);\n            count++;\n            break;\n        }\n    }\n    QL_REQUIRE(count == 1, \"LGM configuration not found for qualifier '\" << qualifier << \"'\");\n    LOG(\"load model configuration from \" << fileName << \" done.\");\n}\n\nvoid LgmData::clear() {\n\n    optionExpiries_.clear();\n    optionTerms_.clear();\n    optionStrikes_.clear();\n}\n\nvoid LgmData::reset() {\n    clear();\n\n    qualifier_ = \"\";\n    calibrationType_ = CalibrationType::Bootstrap;\n    revType_ = ReversionType::HullWhite;\n    volType_ = VolatilityType::HullWhite;\n    calibrateH_ = false;\n    hType_ = ParamType::Constant;\n    hTimes_ = {};\n    hValues_ = {0.03};\n    calibrateA_ = false;\n    aType_ = ParamType::Constant;\n    aTimes_ = {};\n    aValues_ = {0.01};\n    shiftHorizon_ = 0.0;\n    scaling_ = 1.0;\n}\n\nvoid LgmData::fromXML(XMLNode* node) {\n    // XMLUtils::checkNode(node, \"Models\");\n    // XMLNode* modelNode = XMLUtils::getChildNode(node, \"LGM\");\n\n    std::string calibTypeString = XMLUtils::getChildValue(node, \"CalibrationType\", true);\n    calibrationType_ = parseCalibrationType(calibTypeString);\n    LOG(\"LGM calibration type = \" << calibTypeString);\n\n    // Volatility config\n\n    XMLNode* volNode = XMLUtils::getChildNode(node, \"Volatility\");\n\n    calibrateA_ = XMLUtils::getChildValueAsBool(volNode, \"Calibrate\", true);\n    LOG(\"LGM Volatility calibrate = \" << calibrateA_);\n\n    std::string volTypeString = XMLUtils::getChildValue(volNode, \"VolatilityType\", true);\n    volType_ = parseVolatilityType(volTypeString);\n    LOG(\"LGM Volatility type = \" << volTypeString);\n\n    std::string alphaTypeString = XMLUtils::getChildValue(volNode, \"ParamType\", true);\n    aType_ = parseParamType(alphaTypeString);\n    LOG(\"LGM Volatility param type = \" << alphaTypeString);\n\n    aTimes_ = XMLUtils::getChildrenValuesAsDoublesCompact(volNode, \"TimeGrid\", true);\n    LOG(\"LGM Volatility time grid size = \" << aTimes_.size());\n\n    aValues_ = XMLUtils::getChildrenValuesAsDoublesCompact(volNode, \"InitialValue\", true);\n    LOG(\"LGM Volatility initial values size = \" << aValues_.size());\n\n    // Reversion config\n\n    XMLNode* revNode = XMLUtils::getChildNode(node, \"Reversion\");\n\n    calibrateH_ = XMLUtils::getChildValueAsBool(revNode, \"Calibrate\", true);\n    LOG(\"LGM Reversion calibrate = \" << calibrateH_);\n\n    std::string revTypeString = XMLUtils::getChildValue(revNode, \"ReversionType\", true);\n    revType_ = parseReversionType(revTypeString);\n    LOG(\"LGM Reversion type = \" << revTypeString);\n\n    std::string hTypeString = XMLUtils::getChildValue(revNode, \"ParamType\", true);\n    hType_ = parseParamType(hTypeString);\n    LOG(\"LGM Reversion parameter type = \" << hTypeString);\n\n    hTimes_ = XMLUtils::getChildrenValuesAsDoublesCompact(revNode, \"TimeGrid\", true);\n    LOG(\"LGM Reversion time grid size = \" << hTimes_.size());\n\n    hValues_ = XMLUtils::getChildrenValuesAsDoublesCompact(revNode, \"InitialValue\", true);\n    LOG(\"LGM Reversion initial values size = \" << hValues_.size());\n\n    // Parameter transformation config\n\n    XMLNode* tranformNode = XMLUtils::getChildNode(node, \"ParameterTransformation\");\n    shiftHorizon_ = XMLUtils::getChildValueAsDouble(tranformNode, \"ShiftHorizon\", true);\n    LOG(\"LGM shift horizon = \" << shiftHorizon_);\n\n    scaling_ = XMLUtils::getChildValueAsDouble(tranformNode, \"Scaling\", true);\n    LOG(\"LGM scaling = \" << scaling_);\n\n    LOG(\"LgmData done\");\n}\n\nXMLNode* LgmData::toXML(XMLDocument& doc) {\n\n    XMLNode* lgmNode = doc.allocNode(\"LGM\");\n\n    XMLUtils::addGenericChild(doc, lgmNode, \"CalibrationType\", calibrationType_);\n\n    // volatility\n    XMLNode* volatilityNode = XMLUtils::addChild(doc, lgmNode, \"Volatility\");\n    XMLUtils::addChild(doc, volatilityNode, \"Calibrate\", calibrateA_);\n\n    XMLNode* volatilityTypeNode = doc.allocNode(\"VolatilityType\", to_string(volType_));\n    XMLUtils::appendNode(volatilityNode, volatilityTypeNode);\n\n    XMLUtils::addGenericChild(doc, volatilityNode, \"ParamType\", aType_);\n    XMLUtils::addGenericChildAsList(doc, volatilityNode, \"TimeGrid\", aTimes_);\n    XMLUtils::addGenericChildAsList(doc, volatilityNode, \"InitialValue\", aValues_);\n\n    // reversion\n    XMLNode* reversionNode = XMLUtils::addChild(doc, lgmNode, \"Reversion\");\n    XMLUtils::addChild(doc, reversionNode, \"Calibrate\", calibrateH_);\n\n    XMLNode* reversionTypeNode = doc.allocNode(\"ReversionType\", to_string(revType_));\n    XMLUtils::appendNode(reversionNode, reversionTypeNode);\n\n    XMLUtils::addGenericChild(doc, reversionNode, \"ParamType\", hType_);\n    XMLUtils::addGenericChildAsList(doc, reversionNode, \"TimeGrid\", hTimes_);\n    XMLUtils::addGenericChildAsList(doc, reversionNode, \"InitialValue\", hValues_);\n\n    // parameter transformation\n    XMLNode* parameterTransformationNode = XMLUtils::addChild(doc, lgmNode, \"ParameterTransformation\");\n    XMLUtils::addChild(doc, parameterTransformationNode, \"ShiftHorizon\", shiftHorizon_);\n    XMLUtils::addChild(doc, parameterTransformationNode, \"Scaling\", scaling_);\n\n    return lgmNode;\n}\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "d33c57f8af6a69e2e0379972f99c85185c9bccb9", "size": 12239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/model/lgmdata.cpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "OREData/ored/model/lgmdata.cpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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": "OREData/ored/model/lgmdata.cpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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.7310126582, "max_line_length": 119, "alphanum_fraction": 0.6986681918, "num_tokens": 3239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.2974699550610674, "lm_q1q2_score": 0.16148552084970064}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"../Lstm.hpp\"\n\n#include <boost/test/data/test_case.hpp>\n\nBOOST_AUTO_TEST_SUITE(LstmTests)\n\nusing namespace armnn_driver;\n\nBOOST_DATA_TEST_CASE(LstmNoCifgNoPeepholeNoProjectionTest, COMPUTE_DEVICES)\n{\n    LstmNoCifgNoPeepholeNoProjection<hal_1_1::HalPolicy>(sample);\n}\n\nBOOST_DATA_TEST_CASE(LstmCifgPeepholeNoProjectionTest, COMPUTE_DEVICES)\n{\n    LstmCifgPeepholeNoProjection<hal_1_1::HalPolicy>(sample);\n}\n\nBOOST_DATA_TEST_CASE(LstmNoCifgPeepholeProjectionTest, COMPUTE_DEVICES)\n{\n    LstmNoCifgPeepholeProjection<hal_1_1::HalPolicy>(sample);\n}\n\nBOOST_DATA_TEST_CASE(LstmCifgPeepholeNoProjectionBatch2Test, COMPUTE_DEVICES)\n{\n    LstmCifgPeepholeNoProjectionBatch2<hal_1_1::HalPolicy>(sample);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "703597e5f1f2920aaf2193721d5c9def15945d29", "size": 824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/1.1/Lstm.cpp", "max_stars_repo_name": "flawedworld/platform_external_android-nn-driver", "max_stars_repo_head_hexsha": "f5ee7b83e375461ed3ca73e0d41f4397ac1bd711", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T15:14:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T15:14:02.000Z", "max_issues_repo_path": "test/1.1/Lstm.cpp", "max_issues_repo_name": "QPC-database/android-nn-driver", "max_issues_repo_head_hexsha": "42d0f1f5b17857259e4de60357a12464ef9e1752", "max_issues_repo_licenses": ["MIT"], "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/1.1/Lstm.cpp", "max_forks_repo_name": "QPC-database/android-nn-driver", "max_forks_repo_head_hexsha": "42d0f1f5b17857259e4de60357a12464ef9e1752", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-23T11:34:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T15:49:36.000Z", "avg_line_length": 23.5428571429, "max_line_length": 77, "alphanum_fraction": 0.8191747573, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.16148551070662076}}
{"text": "#include \"shift/rc/optimizer_mesh/filter.hpp\"\n#include <shift/resource_db/mesh.hpp>\n#include <shift/log/log.hpp>\n#include <shift/math/vector.hpp>\n#include <shift/core/hash_table.hpp>\n#include <boost/endian/conversion.hpp>\n#include <filesystem>\n#include <queue>\n#include <memory>\n\nnamespace std\n{\n/// Implementation of the 64bit Murmur hash algorithm to hash vertex data of\n/// arbitrary size.\ntemplate <>\nstruct hash<const void*>\n{\n  std::size_t operator()(const void* vertex) const\n  {\n    constexpr auto m = static_cast<std::size_t>(0xc6a4a7935bd1e995ULL);\n    constexpr int r = 47;\n\n    std::size_t remaining_size = vertex_size;\n    std::size_t h = vertex_size;\n\n    // Mix 4 bytes at a time into the hash\n    const auto* data = reinterpret_cast<const std::uint8_t*>(vertex);\n\n    while (remaining_size >= sizeof(std::size_t))\n    {\n      auto k = *reinterpret_cast<const std::size_t*>(data);\n\n      k *= m;\n      k ^= k >> r;\n      k *= m;\n\n      h *= m;\n      h ^= k;\n\n      data += sizeof(std::size_t);\n      remaining_size -= sizeof(std::size_t);\n    }\n\n    // Handle the last few bytes of the input array\n    switch (remaining_size)\n    {\n    case 7:\n      h ^= static_cast<std::size_t>(data[6]) << 48;\n      [[fallthrough]];\n    case 6:\n      h ^= static_cast<std::size_t>(data[5]) << 40;\n      [[fallthrough]];\n    case 5:\n      h ^= static_cast<std::size_t>(data[4]) << 32;\n      [[fallthrough]];\n    case 4:\n      h ^= *reinterpret_cast<const std::uint32_t*>(&data[0]);\n      break;\n    case 3:\n      h ^= static_cast<std::size_t>(data[2]) << 16;\n      [[fallthrough]];\n    case 2:\n      h ^= *reinterpret_cast<const std::uint16_t*>(&data[0]);\n      break;\n    case 1:\n      h ^= static_cast<std::size_t>(data[0]);\n    };\n    h *= m;\n\n    h ^= h >> 13;\n    h *= m;\n    h ^= h >> 15;\n\n    return h;\n  }\n\n  std::size_t vertex_size;\n};\n\n/// An overload of std::equal_to to compare arbitrary vertices.\ntemplate <>\nstruct equal_to<const void*>\n{\n  using first_argument_type = const void*;\n  using second_argument_type = const void*;\n  using result_type = bool;\n\n  bool operator()(const first_argument_type lhs, const second_argument_type rhs)\n  {\n    return std::memcmp(lhs, rhs, vertex_size) == 0;\n  }\n\n  std::size_t vertex_size;\n};\n}\n\nnamespace shift::rc\n{\nnamespace fs = std::filesystem;\n\nbool optimize_mesh(const job_description& /*job*/)\n{\n  // auto input_file_path = job.input_base_path / job.input_file_path;\n  // if (!fs::exists(input_file_path) ||\n  // !fs::is_regular_file(input_file_path))\n  //{\n  //  log::error() << \"Cannot find input file \" << input_file_path << \".\";\n  //  return false;\n  //}\n\n  // std::ifstream file;\n  // file.open(input_file_path.generic_string(),\n  //          std::ios_base::in | std::ios_base::binary);\n  // if (!file.is_open())\n  //{\n  //  /// ToDo: Throw exception.\n  //  return false;\n  //}\n\n  // std::vector<std::uint32_t> indices;\n  // indices.resize(1000);  // total_indices\n  // std::size_t unique_vertex_count;\n  // unique_vertex_count =\n  //  generate_index_buffer(indices, nullptr, sizeof(vertex));\n  // generate_vertex_buffer(indices, vertices.data(), indices.size(),\n  //                       sizeof(vertex));\n\n  //// Store resource into repository.\n  // resource_db::repository::singleton_instance().save(*mesh,\n\n  return true;\n}\n\ntemplate <typename Index>\nstd::vector<std::uint8_t> resolve_vertex_indices(resource_db::mesh& mesh,\n                                                 /* Index* indices, */\n                                                 std::size_t index_count)\n{\n  std::size_t vertex_size = 0;\n  for (auto& attribute : mesh.vertex_attributes)\n  {\n    vertex_size += resource_db::vertex_attribute_size(attribute.component_type,\n                                                      attribute.data_type);\n  }\n  const auto& index_buffer = mesh.index_buffer_view.buffer->storage;\n\n  std::vector<std::uint8_t> destination;\n  destination.resize(index_count * vertex_size);\n  for (std::size_t i = 0; i < index_count; ++i)\n  {\n    for (auto& attribute : mesh.vertex_attributes)\n    {\n      const auto& vertex_buffer = attribute.vertex_buffer_view.buffer->storage;\n      std::memcpy(\n        destination.data() + i * attribute.stride + attribute.offset,\n        vertex_buffer.data() +\n          *reinterpret_cast<const Index*>(&index_buffer[i * sizeof(Index)]) *\n            attribute.stride +\n          attribute.offset,\n        attribute.size);\n    }\n  }\n  return destination;\n}\n\nbool optimize_mesh(resource_db::mesh& mesh)\n{\n  if (mesh.sub_meshes.size() != 1)\n    return true;\n\n  for (auto& attribute : mesh.vertex_attributes)\n  {\n    if (!attribute.vertex_buffer_view.buffer)\n      return false;\n  }\n  std::vector<std::uint8_t> vertex_buffer;\n\n  if (!mesh.index_buffer_view.buffer)\n    return false;\n\n  std::size_t index_count = 0;\n  for (auto sub_mesh : mesh.sub_meshes)\n  {\n    switch (sub_mesh.topology)\n    {\n    case resource_db::primitive_topology::triangle_list:\n      index_count = sub_mesh.index_count / 3;\n      break;\n\n    case resource_db::primitive_topology::triangle_strip:\n      /// ToDo: Find and subtract empty triangles.\n      BOOST_ASSERT(false);  // Not yet implemented.\n      return false;\n\n    case resource_db::primitive_topology::triangle_fan:\n      BOOST_ASSERT(false);  // Not yet implemented.\n      return false;\n\n    default:\n      BOOST_ASSERT(false);  // Unsupported.\n      return false;\n    }\n  }\n\n  switch (mesh.index_data_type)\n  {\n  case resource_db::vertex_index_data_type::uint8:\n    resolve_vertex_indices<std::uint8_t>(\n      mesh, /*mesh.index_buffer_view.buffer->storage.data(),*/ index_count);\n    break;\n\n  default:\n    // Ignore other cases for now.\n    break;\n  }\n\n  // resolve_vertex_indices(mesh.\n  return true;\n}\n\nstd::pair<std::vector<std::uint32_t>, std::size_t> generate_index_buffer(\n  std::vector<std::uint8_t>& vertex_buffer, std::size_t vertex_size)\n{\n  std::size_t vertex_count = vertex_buffer.size() / vertex_size;\n  std::vector<std::uint32_t> indices;\n  indices.resize(vertex_count);\n\n  std::hash<const void*> hasher{vertex_size};\n  std::equal_to<const void*> compare{vertex_size};\n  core::hash_table<const void*, std::size_t> table(vertex_count, hasher,\n                                                   compare);\n\n  std::size_t next_vertex = 0;\n  for (std::size_t i = 0; i < vertex_count; ++i)\n  {\n    const void* vertex = vertex_buffer.data() + i * vertex_size;\n    bool unique;\n    std::size_t* value;\n    std::tie(unique, value) = table[vertex];\n    if (unique)\n      *value = next_vertex++;\n    indices[i] = *value;\n  }\n\n  return std::make_pair(std::move(indices), next_vertex);\n}\n\nvoid compress_vertex_buffer(std::vector<std::uint8_t>& vertex_buffer,\n                            std::size_t vertex_size,\n                            std::size_t unique_vertex_count,\n                            const std::vector<std::uint32_t>& indices)\n{\n  std::uint32_t next_vertex = 0;\n  for (std::size_t i = 0; i < unique_vertex_count; ++i)\n  {\n    BOOST_ASSERT(indices[i] <= next_vertex);\n    if (indices[i] == next_vertex)\n    {\n      if (next_vertex != i)\n      {\n        std::memcpy(vertex_buffer.data() + next_vertex * vertex_size,\n                    vertex_buffer.data() + i * vertex_size, vertex_size);\n      }\n      ++next_vertex;\n    }\n  }\n}\n}\n", "meta": {"hexsha": "b77c825d7bd3fc29169d7533e83d2572de2247bb", "size": 7274, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shift/rc/private/shift/rc/optimizer_mesh/filter.cpp", "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/rc/private/shift/rc/optimizer_mesh/filter.cpp", "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/rc/private/shift/rc/optimizer_mesh/filter.cpp", "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": 27.0408921933, "max_line_length": 80, "alphanum_fraction": 0.6230409678, "num_tokens": 1797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.297469948832931, "lm_q1q2_score": 0.16148550866853012}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SIMD_COSD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIMD_COSD_HPP_INCLUDED\n\n#include <boost/simd/function/scalar/cosd.hpp>\n#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>\n#include <boost/simd/arch/common/simd/function/cosd.hpp>\n\n#endif\n", "meta": {"hexsha": "6b72453f5101e7321763ae36f14c710be6f8e538", "size": 669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/simd/cosd.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/simd/cosd.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/simd/cosd.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.1666666667, "max_line_length": 100, "alphanum_fraction": 0.5605381166, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.16143631315865492}}
{"text": "/*\n\tThis file is part of solidity.\n\n\tsolidity is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tsolidity is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with solidity.  If not, see <http://www.gnu.org/licenses/>.\n*/\n/**\n * Component that can generate various useful Yul functions.\n */\n\n#include <libsolidity/codegen/YulUtilFunctions.h>\n\n#include <libsolidity/codegen/MultiUseYulFunctionCollector.h>\n#include <libsolidity/ast/AST.h>\n#include <libsolidity/codegen/CompilerUtils.h>\n\n#include <libsolutil/CommonData.h>\n#include <libsolutil/Whiskers.h>\n#include <libsolutil/StringUtils.h>\n\n#include <boost/algorithm/string/join.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n\nusing namespace std;\nusing namespace solidity;\nusing namespace solidity::util;\nusing namespace solidity::frontend;\n\nstring YulUtilFunctions::combineExternalFunctionIdFunction()\n{\n\tstring functionName = \"combine_external_function_id\";\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(addr, selector) -> combined {\n\t\t\t\tcombined := <shl64>(or(<shl32>(addr), and(selector, 0xffffffff)))\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"shl32\", shiftLeftFunction(32))\n\t\t(\"shl64\", shiftLeftFunction(64))\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::splitExternalFunctionIdFunction()\n{\n\tstring functionName = \"split_external_function_id\";\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(combined) -> addr, selector {\n\t\t\t\tcombined := <shr64>(combined)\n\t\t\t\tselector := and(combined, 0xffffffff)\n\t\t\t\taddr := <shr32>(combined)\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"shr32\", shiftRightFunction(32))\n\t\t(\"shr64\", shiftRightFunction(64))\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::copyToMemoryFunction(bool _fromCalldata)\n{\n\tstring functionName = \"copy_\" + string(_fromCalldata ? \"calldata\" : \"memory\") + \"_to_memory\";\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tif (_fromCalldata)\n\t\t{\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(src, dst, length) {\n\t\t\t\t\tcalldatacopy(dst, src, length)\n\t\t\t\t\t// clear end\n\t\t\t\t\tmstore(add(dst, length), 0)\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(src, dst, length) {\n\t\t\t\t\tlet i := 0\n\t\t\t\t\tfor { } lt(i, length) { i := add(i, 32) }\n\t\t\t\t\t{\n\t\t\t\t\t\tmstore(add(dst, i), mload(add(src, i)))\n\t\t\t\t\t}\n\t\t\t\t\tif gt(i, length)\n\t\t\t\t\t{\n\t\t\t\t\t\t// clear end\n\t\t\t\t\t\tmstore(add(dst, length), 0)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t\t}\n\t});\n}\n\nstring YulUtilFunctions::requireOrAssertFunction(bool _assert, Type const* _messageType)\n{\n\tstring functionName =\n\t\tstring(_assert ? \"assert_helper\" : \"require_helper\") +\n\t\t(_messageType ? (\"_\" + _messageType->identifier()) : \"\");\n\n\tsolAssert(!_assert || !_messageType, \"Asserts can't have messages!\");\n\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tif (!_messageType)\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(condition) {\n\t\t\t\t\tif iszero(condition) { <invalidOrRevert> }\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"invalidOrRevert\", _assert ? \"invalid()\" : \"revert(0, 0)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\n\t\tint const hashHeaderSize = 4;\n\t\tint const byteSize = 8;\n\t\tu256 const errorHash =\n\t\t\tu256(FixedHash<hashHeaderSize>::Arith(\n\t\t\t\tFixedHash<hashHeaderSize>(keccak256(\"Error(string)\"))\n\t\t\t)) << (256 - hashHeaderSize * byteSize);\n\n\t\tstring const encodeFunc = ABIFunctions(m_evmVersion, m_revertStrings, m_functionCollector)\n\t\t\t.tupleEncoder(\n\t\t\t\t{_messageType},\n\t\t\t\t{TypeProvider::stringMemory()}\n\t\t\t);\n\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(condition <messageVars>) {\n\t\t\t\tif iszero(condition) {\n\t\t\t\t\tlet fmp := mload(<freeMemPointer>)\n\t\t\t\t\tmstore(fmp, <errorHash>)\n\t\t\t\t\tlet end := <abiEncodeFunc>(add(fmp, <hashHeaderSize>) <messageVars>)\n\t\t\t\t\trevert(fmp, sub(end, fmp))\n\t\t\t\t}\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"freeMemPointer\", to_string(CompilerUtils::freeMemoryPointer))\n\t\t(\"errorHash\", formatNumber(errorHash))\n\t\t(\"abiEncodeFunc\", encodeFunc)\n\t\t(\"hashHeaderSize\", to_string(hashHeaderSize))\n\t\t(\"messageVars\",\n\t\t\t(_messageType->sizeOnStack() > 0 ? \", \" : \"\") +\n\t\t\tsuffixedVariableNameList(\"message_\", 1, 1 + _messageType->sizeOnStack())\n\t\t)\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::leftAlignFunction(Type const& _type)\n{\n\tstring functionName = string(\"leftAlign_\") + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers templ(R\"(\n\t\t\tfunction <functionName>(value) -> aligned {\n\t\t\t\t<body>\n\t\t\t}\n\t\t)\");\n\t\ttempl(\"functionName\", functionName);\n\t\tswitch (_type.category())\n\t\t{\n\t\tcase Type::Category::Address:\n\t\t\ttempl(\"body\", \"aligned := \" + leftAlignFunction(IntegerType(160)) + \"(value)\");\n\t\t\tbreak;\n\t\tcase Type::Category::Integer:\n\t\t{\n\t\t\tIntegerType const& type = dynamic_cast<IntegerType const&>(_type);\n\t\t\tif (type.numBits() == 256)\n\t\t\t\ttempl(\"body\", \"aligned := value\");\n\t\t\telse\n\t\t\t\ttempl(\"body\", \"aligned := \" + shiftLeftFunction(256 - type.numBits()) + \"(value)\");\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::RationalNumber:\n\t\t\tsolAssert(false, \"Left align requested for rational number.\");\n\t\t\tbreak;\n\t\tcase Type::Category::Bool:\n\t\t\ttempl(\"body\", \"aligned := \" + leftAlignFunction(IntegerType(8)) + \"(value)\");\n\t\t\tbreak;\n\t\tcase Type::Category::FixedPoint:\n\t\t\tsolUnimplemented(\"Fixed point types not implemented.\");\n\t\t\tbreak;\n\t\tcase Type::Category::Array:\n\t\tcase Type::Category::Struct:\n\t\t\tsolAssert(false, \"Left align requested for non-value type.\");\n\t\t\tbreak;\n\t\tcase Type::Category::FixedBytes:\n\t\t\ttempl(\"body\", \"aligned := value\");\n\t\t\tbreak;\n\t\tcase Type::Category::Contract:\n\t\t\ttempl(\"body\", \"aligned := \" + leftAlignFunction(*TypeProvider::address()) + \"(value)\");\n\t\t\tbreak;\n\t\tcase Type::Category::Enum:\n\t\t{\n\t\t\tunsigned storageBytes = dynamic_cast<EnumType const&>(_type).storageBytes();\n\t\t\ttempl(\"body\", \"aligned := \" + leftAlignFunction(IntegerType(8 * storageBytes)) + \"(value)\");\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::InaccessibleDynamic:\n\t\t\tsolAssert(false, \"Left align requested for inaccessible dynamic type.\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsolAssert(false, \"Left align of type \" + _type.identifier() + \" requested.\");\n\t\t}\n\n\t\treturn templ.render();\n\t});\n}\n\nstring YulUtilFunctions::shiftLeftFunction(size_t _numBits)\n{\n\tsolAssert(_numBits < 256, \"\");\n\n\tstring functionName = \"shift_left_\" + to_string(_numBits);\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(value) -> newValue {\n\t\t\t\tnewValue :=\n\t\t\t\t<?hasShifts>\n\t\t\t\t\tshl(<numBits>, value)\n\t\t\t\t<!hasShifts>\n\t\t\t\t\tmul(value, <multiplier>)\n\t\t\t\t</hasShifts>\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"numBits\", to_string(_numBits))\n\t\t\t(\"hasShifts\", m_evmVersion.hasBitwiseShifting())\n\t\t\t(\"multiplier\", toCompactHexWithPrefix(u256(1) << _numBits))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::shiftLeftFunctionDynamic()\n{\n\tstring functionName = \"shift_left_dynamic\";\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(bits, value) -> newValue {\n\t\t\t\tnewValue :=\n\t\t\t\t<?hasShifts>\n\t\t\t\t\tshl(bits, value)\n\t\t\t\t<!hasShifts>\n\t\t\t\t\tmul(value, exp(2, bits))\n\t\t\t\t</hasShifts>\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"hasShifts\", m_evmVersion.hasBitwiseShifting())\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::shiftRightFunction(size_t _numBits)\n{\n\tsolAssert(_numBits < 256, \"\");\n\n\t// Note that if this is extended with signed shifts,\n\t// the opcodes SAR and SDIV behave differently with regards to rounding!\n\n\tstring functionName = \"shift_right_\" + to_string(_numBits) + \"_unsigned\";\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(value) -> newValue {\n\t\t\t\tnewValue :=\n\t\t\t\t<?hasShifts>\n\t\t\t\t\tshr(<numBits>, value)\n\t\t\t\t<!hasShifts>\n\t\t\t\t\tdiv(value, <multiplier>)\n\t\t\t\t</hasShifts>\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"hasShifts\", m_evmVersion.hasBitwiseShifting())\n\t\t\t(\"numBits\", to_string(_numBits))\n\t\t\t(\"multiplier\", toCompactHexWithPrefix(u256(1) << _numBits))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::shiftRightFunctionDynamic()\n{\n\t// Note that if this is extended with signed shifts,\n\t// the opcodes SAR and SDIV behave differently with regards to rounding!\n\n\tstring const functionName = \"shift_right_unsigned_dynamic\";\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(bits, value) -> newValue {\n\t\t\t\tnewValue :=\n\t\t\t\t<?hasShifts>\n\t\t\t\t\tshr(bits, value)\n\t\t\t\t<!hasShifts>\n\t\t\t\t\tdiv(value, exp(2, bits))\n\t\t\t\t</hasShifts>\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"hasShifts\", m_evmVersion.hasBitwiseShifting())\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::updateByteSliceFunction(size_t _numBytes, size_t _shiftBytes)\n{\n\tsolAssert(_numBytes <= 32, \"\");\n\tsolAssert(_shiftBytes <= 32, \"\");\n\tsize_t numBits = _numBytes * 8;\n\tsize_t shiftBits = _shiftBytes * 8;\n\tstring functionName = \"update_byte_slice_\" + to_string(_numBytes) + \"_shift_\" + to_string(_shiftBytes);\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(value, toInsert) -> result {\n\t\t\t\tlet mask := <mask>\n\t\t\t\ttoInsert := <shl>(toInsert)\n\t\t\t\tvalue := and(value, not(mask))\n\t\t\t\tresult := or(value, and(toInsert, mask))\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"mask\", formatNumber(((bigint(1) << numBits) - 1) << shiftBits))\n\t\t\t(\"shl\", shiftLeftFunction(shiftBits))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::updateByteSliceFunctionDynamic(size_t _numBytes)\n{\n\tsolAssert(_numBytes <= 32, \"\");\n\tsize_t numBits = _numBytes * 8;\n\tstring functionName = \"update_byte_slice_dynamic\" + to_string(_numBytes);\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(value, shiftBytes, toInsert) -> result {\n\t\t\t\tlet shiftBits := mul(shiftBytes, 8)\n\t\t\t\tlet mask := <shl>(shiftBits, <mask>)\n\t\t\t\ttoInsert := <shl>(shiftBits, toInsert)\n\t\t\t\tvalue := and(value, not(mask))\n\t\t\t\tresult := or(value, and(toInsert, mask))\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"mask\", formatNumber((bigint(1) << numBits) - 1))\n\t\t\t(\"shl\", shiftLeftFunctionDynamic())\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::roundUpFunction()\n{\n\tstring functionName = \"round_up_to_mul_of_32\";\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(value) -> result {\n\t\t\t\tresult := and(add(value, 31), not(31))\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::overflowCheckedIntAddFunction(IntegerType const& _type)\n{\n\tstring functionName = \"checked_add_\" + _type.identifier();\n\t// TODO: Consider to add a special case for unsigned 256-bit integers\n\t//       and use the following instead:\n\t//       sum := add(x, y) if lt(sum, x) { revert(0, 0) }\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(x, y) -> sum {\n\t\t\t\t<?signed>\n\t\t\t\t\t// overflow, if x >= 0 and y > (maxValue - x)\n\t\t\t\t\tif and(iszero(slt(x, 0)), sgt(y, sub(<maxValue>, x))) { revert(0, 0) }\n\t\t\t\t\t// underflow, if x < 0 and y < (minValue - x)\n\t\t\t\t\tif and(slt(x, 0), slt(y, sub(<minValue>, x))) { revert(0, 0) }\n\t\t\t\t<!signed>\n\t\t\t\t\t// overflow, if x > (maxValue - y)\n\t\t\t\t\tif gt(x, sub(<maxValue>, y)) { revert(0, 0) }\n\t\t\t\t</signed>\n\t\t\t\tsum := add(x, y)\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"signed\", _type.isSigned())\n\t\t\t(\"maxValue\", toCompactHexWithPrefix(u256(_type.maxValue())))\n\t\t\t(\"minValue\", toCompactHexWithPrefix(u256(_type.minValue())))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::overflowCheckedIntMulFunction(IntegerType const& _type)\n{\n\tstring functionName = \"checked_mul_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\t// Multiplication by zero could be treated separately and directly return zero.\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(x, y) -> product {\n\t\t\t\t<?signed>\n\t\t\t\t\t// overflow, if x > 0, y > 0 and x > (maxValue / y)\n\t\t\t\t\tif and(and(sgt(x, 0), sgt(y, 0)), gt(x, div(<maxValue>, y))) { revert(0, 0) }\n\t\t\t\t\t// underflow, if x > 0, y < 0 and y < (minValue / x)\n\t\t\t\t\tif and(and(sgt(x, 0), slt(y, 0)), slt(y, sdiv(<minValue>, x))) { revert(0, 0) }\n\t\t\t\t\t// underflow, if x < 0, y > 0 and x < (minValue / y)\n\t\t\t\t\tif and(and(slt(x, 0), sgt(y, 0)), slt(x, sdiv(<minValue>, y))) { revert(0, 0) }\n\t\t\t\t\t// overflow, if x < 0, y < 0 and x < (maxValue / y)\n\t\t\t\t\tif and(and(slt(x, 0), slt(y, 0)), slt(x, sdiv(<maxValue>, y))) { revert(0, 0) }\n\t\t\t\t<!signed>\n\t\t\t\t\t// overflow, if x != 0 and y > (maxValue / x)\n\t\t\t\t\tif and(iszero(iszero(x)), gt(y, div(<maxValue>, x))) { revert(0, 0) }\n\t\t\t\t</signed>\n\t\t\t\tproduct := mul(x, y)\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"signed\", _type.isSigned())\n\t\t\t(\"maxValue\", toCompactHexWithPrefix(u256(_type.maxValue())))\n\t\t\t(\"minValue\", toCompactHexWithPrefix(u256(_type.minValue())))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::overflowCheckedIntDivFunction(IntegerType const& _type)\n{\n\tstring functionName = \"checked_div_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(x, y) -> r {\n\t\t\t\tif iszero(y) { revert(0, 0) }\n\t\t\t\t<?signed>\n\t\t\t\t// overflow for minVal / -1\n\t\t\t\tif and(\n\t\t\t\t\teq(x, <minVal>),\n\t\t\t\t\teq(y, sub(0, 1))\n\t\t\t\t) { revert(0, 0) }\n\t\t\t\t</signed>\n\t\t\t\tr := <?signed>s</signed>div(x, y)\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"signed\", _type.isSigned())\n\t\t\t(\"minVal\", toCompactHexWithPrefix(u256(_type.minValue())))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::checkedIntModFunction(IntegerType const& _type)\n{\n\tstring functionName = \"checked_mod_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(x, y) -> r {\n\t\t\t\tif iszero(y) { revert(0, 0) }\n\t\t\t\tr := <?signed>s</signed>mod(x, y)\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"signed\", _type.isSigned())\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::overflowCheckedIntSubFunction(IntegerType const& _type)\n{\n\tstring functionName = \"checked_sub_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\treturn\n\t\t\tWhiskers(R\"(\n\t\t\tfunction <functionName>(x, y) -> diff {\n\t\t\t\t<?signed>\n\t\t\t\t\t// underflow, if y >= 0 and x < (minValue + y)\n\t\t\t\t\tif and(iszero(slt(y, 0)), slt(x, add(<minValue>, y))) { revert(0, 0) }\n\t\t\t\t\t// overflow, if y < 0 and x > (maxValue + y)\n\t\t\t\t\tif and(slt(y, 0), sgt(x, add(<maxValue>, y))) { revert(0, 0) }\n\t\t\t\t<!signed>\n\t\t\t\t\tif lt(x, y) { revert(0, 0) }\n\t\t\t\t</signed>\n\t\t\t\tdiff := sub(x, y)\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"signed\", _type.isSigned())\n\t\t\t(\"maxValue\", toCompactHexWithPrefix(u256(_type.maxValue())))\n\t\t\t(\"minValue\", toCompactHexWithPrefix(u256(_type.minValue())))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::arrayLengthFunction(ArrayType const& _type)\n{\n\tstring functionName = \"array_length_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers w(R\"(\n\t\t\tfunction <functionName>(value) -> length {\n\t\t\t\t<?dynamic>\n\t\t\t\t\t<?memory>\n\t\t\t\t\t\tlength := mload(value)\n\t\t\t\t\t</memory>\n\t\t\t\t\t<?storage>\n\t\t\t\t\t\tlength := sload(value)\n\t\t\t\t\t\t<?byteArray>\n\t\t\t\t\t\t\t// Retrieve length both for in-place strings and off-place strings:\n\t\t\t\t\t\t\t// Computes (x & (0x100 * (ISZERO (x & 1)) - 1)) / 2\n\t\t\t\t\t\t\t// i.e. for short strings (x & 1 == 0) it does (x & 0xff) / 2 and for long strings it\n\t\t\t\t\t\t\t// computes (x & (-1)) / 2, which is equivalent to just x / 2.\n\t\t\t\t\t\t\tlet mask := sub(mul(0x100, iszero(and(length, 1))), 1)\n\t\t\t\t\t\t\tlength := div(and(length, mask), 2)\n\t\t\t\t\t\t</byteArray>\n\t\t\t\t\t</storage>\n\t\t\t\t<!dynamic>\n\t\t\t\t\tlength := <length>\n\t\t\t\t</dynamic>\n\t\t\t}\n\t\t)\");\n\t\tw(\"functionName\", functionName);\n\t\tw(\"dynamic\", _type.isDynamicallySized());\n\t\tif (!_type.isDynamicallySized())\n\t\t\tw(\"length\", toCompactHexWithPrefix(_type.length()));\n\t\tw(\"memory\", _type.location() == DataLocation::Memory);\n\t\tw(\"storage\", _type.location() == DataLocation::Storage);\n\t\tw(\"byteArray\", _type.isByteArray());\n\t\tif (_type.isDynamicallySized())\n\t\t\tsolAssert(\n\t\t\t\t_type.location() != DataLocation::CallData,\n\t\t\t\t\"called regular array length function on calldata array\"\n\t\t\t);\n\t\treturn w.render();\n\t});\n}\n\nstd::string YulUtilFunctions::resizeDynamicArrayFunction(ArrayType const& _type)\n{\n\tsolAssert(_type.location() == DataLocation::Storage, \"\");\n\tsolAssert(_type.isDynamicallySized(), \"\");\n\tsolUnimplementedAssert(!_type.isByteArray(), \"Byte Arrays not yet implemented!\");\n\tsolUnimplementedAssert(_type.baseType()->storageBytes() <= 32, \"...\");\n\tsolUnimplementedAssert(_type.baseType()->storageSize() == 1, \"\");\n\n\tstring functionName = \"resize_array_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(array, newLen) {\n\t\t\t\tif gt(newLen, <maxArrayLength>) {\n\t\t\t\t\tinvalid()\n\t\t\t\t}\n\n\t\t\t\tlet oldLen := <fetchLength>(array)\n\n\t\t\t\t// Store new length\n\t\t\t\tsstore(array, newLen)\n\n\t\t\t\t// Size was reduced, clear end of array\n\t\t\t\tif lt(newLen, oldLen) {\n\t\t\t\t\tlet oldSlotCount := <convertToSize>(oldLen)\n\t\t\t\t\tlet newSlotCount := <convertToSize>(newLen)\n\t\t\t\t\tlet arrayDataStart := <dataPosition>(array)\n\t\t\t\t\tlet deleteStart := add(arrayDataStart, newSlotCount)\n\t\t\t\t\tlet deleteEnd := add(arrayDataStart, oldSlotCount)\n\t\t\t\t\t<clearStorageRange>(deleteStart, deleteEnd)\n\t\t\t\t}\n\t\t\t})\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"fetchLength\", arrayLengthFunction(_type))\n\t\t\t(\"convertToSize\", arrayConvertLengthToSize(_type))\n\t\t\t(\"dataPosition\", arrayDataAreaFunction(_type))\n\t\t\t(\"clearStorageRange\", clearStorageRangeFunction(*_type.baseType()))\n\t\t\t(\"maxArrayLength\", (u256(1) << 64).str())\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::storageArrayPopFunction(ArrayType const& _type)\n{\n\tsolAssert(_type.location() == DataLocation::Storage, \"\");\n\tsolAssert(_type.isDynamicallySized(), \"\");\n\tsolUnimplementedAssert(!_type.isByteArray(), \"Byte Arrays not yet implemented!\");\n\tsolUnimplementedAssert(_type.baseType()->storageBytes() <= 32, \"Base type is not yet implemented.\");\n\n\tstring functionName = \"array_pop_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(array) {\n\t\t\t\tlet oldLen := <fetchLength>(array)\n\t\t\t\tif iszero(oldLen) { invalid() }\n\t\t\t\tlet newLen := sub(oldLen, 1)\n\n\t\t\t\tlet slot, offset := <indexAccess>(array, newLen)\n\t\t\t\t<setToZero>(slot, offset)\n\n\t\t\t\tsstore(array, newLen)\n\t\t\t})\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"fetchLength\", arrayLengthFunction(_type))\n\t\t\t(\"indexAccess\", storageArrayIndexAccessFunction(_type))\n\t\t\t(\"setToZero\", storageSetToZeroFunction(*_type.baseType()))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::storageArrayPushFunction(ArrayType const& _type)\n{\n\tsolAssert(_type.location() == DataLocation::Storage, \"\");\n\tsolAssert(_type.isDynamicallySized(), \"\");\n\tsolUnimplementedAssert(!_type.isByteArray(), \"Byte Arrays not yet implemented!\");\n\tsolUnimplementedAssert(_type.baseType()->storageBytes() <= 32, \"Base type is not yet implemented.\");\n\n\tstring functionName = \"array_push_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(array, value) {\n\t\t\t\tlet oldLen := <fetchLength>(array)\n\t\t\t\tif iszero(lt(oldLen, <maxArrayLength>)) { invalid() }\n\t\t\t\tsstore(array, add(oldLen, 1))\n\n\t\t\t\tlet slot, offset := <indexAccess>(array, oldLen)\n\t\t\t\t<storeValue>(slot, offset, value)\n\t\t\t})\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"fetchLength\", arrayLengthFunction(_type))\n\t\t\t(\"indexAccess\", storageArrayIndexAccessFunction(_type))\n\t\t\t(\"storeValue\", updateStorageValueFunction(*_type.baseType()))\n\t\t\t(\"maxArrayLength\", (u256(1) << 64).str())\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::storageArrayPushZeroFunction(ArrayType const& _type)\n{\n\tsolAssert(_type.location() == DataLocation::Storage, \"\");\n\tsolAssert(_type.isDynamicallySized(), \"\");\n\tsolUnimplementedAssert(!_type.isByteArray(), \"Byte Arrays not yet implemented!\");\n\tsolUnimplementedAssert(_type.baseType()->storageBytes() <= 32, \"Base type is not yet implemented.\");\n\n\tstring functionName = \"array_push_zero_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(array) -> slot, offset {\n\t\t\t\tlet oldLen := <fetchLength>(array)\n\t\t\t\tif iszero(lt(oldLen, <maxArrayLength>)) { invalid() }\n\t\t\t\tsstore(array, add(oldLen, 1))\n\t\t\t\tslot, offset := <indexAccess>(array, oldLen)\n\t\t\t\t<storeValue>(slot, offset, <zeroValueFunction>())\n\t\t\t})\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"fetchLength\", arrayLengthFunction(_type))\n\t\t\t(\"indexAccess\", storageArrayIndexAccessFunction(_type))\n\t\t\t(\"storeValue\", updateStorageValueFunction(*_type.baseType()))\n\t\t\t(\"maxArrayLength\", (u256(1) << 64).str())\n\t\t\t(\"zeroValueFunction\", zeroValueFunction(*_type.baseType()))\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::clearStorageRangeFunction(Type const& _type)\n{\n\tstring functionName = \"clear_storage_range_\" + _type.identifier();\n\n\tsolAssert(_type.storageBytes() >= 32, \"Expected smaller value for storage bytes\");\n\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(start, end) {\n\t\t\t\tfor {} lt(start, end) { start := add(start, <increment>) }\n\t\t\t\t{\n\t\t\t\t\t<setToZero>(start, 0)\n\t\t\t\t}\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"setToZero\", storageSetToZeroFunction(_type))\n\t\t(\"increment\", _type.storageSize().str())\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::clearStorageArrayFunction(ArrayType const& _type)\n{\n\tsolAssert(_type.location() == DataLocation::Storage, \"\");\n\n\tif (_type.baseType()->storageBytes() < 32)\n\t{\n\t\tsolAssert(_type.baseType()->isValueType(), \"Invalid storage size for non-value type.\");\n\t\tsolAssert(_type.baseType()->storageSize() <= 1, \"Invalid storage size for type.\");\n\t}\n\n\tif (_type.baseType()->isValueType())\n\t\tsolAssert(_type.baseType()->storageSize() <= 1, \"Invalid size for value type.\");\n\n\tstring functionName = \"clear_storage_array_\" + _type.identifier();\n\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(slot) {\n\t\t\t\t<?dynamic>\n\t\t\t\t\t<resizeArray>(slot, 0)\n\t\t\t\t<!dynamic>\n\t\t\t\t\t<clearRange>(slot, add(slot, <lenToSize>(<len>)))\n\t\t\t\t</dynamic>\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"dynamic\", _type.isDynamicallySized())\n\t\t(\"resizeArray\", _type.isDynamicallySized() ? resizeDynamicArrayFunction(_type) : \"\")\n\t\t(\n\t\t\t\"clearRange\",\n\t\t\tclearStorageRangeFunction(\n\t\t\t\t(_type.baseType()->storageBytes() < 32) ?\n\t\t\t\t*TypeProvider::uint256() :\n\t\t\t\t*_type.baseType()\n\t\t\t)\n\t\t)\n\t\t(\"lenToSize\", arrayConvertLengthToSize(_type))\n\t\t(\"len\", _type.length().str())\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::arrayConvertLengthToSize(ArrayType const& _type)\n{\n\tstring functionName = \"array_convert_length_to_size_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tType const& baseType = *_type.baseType();\n\n\t\tswitch (_type.location())\n\t\t{\n\t\t\tcase DataLocation::Storage:\n\t\t\t{\n\t\t\t\tunsigned const baseStorageBytes = baseType.storageBytes();\n\t\t\t\tsolAssert(baseStorageBytes > 0, \"\");\n\t\t\t\tsolAssert(32 / baseStorageBytes > 0, \"\");\n\n\t\t\t\treturn Whiskers(R\"(\n\t\t\t\t\tfunction <functionName>(length) -> size {\n\t\t\t\t\t\tsize := length\n\t\t\t\t\t\t<?multiSlot>\n\t\t\t\t\t\t\tsize := <mul>(<storageSize>, length)\n\t\t\t\t\t\t<!multiSlot>\n\t\t\t\t\t\t\t// Number of slots rounded up\n\t\t\t\t\t\t\tsize := div(add(length, sub(<itemsPerSlot>, 1)), <itemsPerSlot>)\n\t\t\t\t\t\t</multiSlot>\n\t\t\t\t\t})\")\n\t\t\t\t\t(\"functionName\", functionName)\n\t\t\t\t\t(\"multiSlot\", baseType.storageSize() > 1)\n\t\t\t\t\t(\"itemsPerSlot\", to_string(32 / baseStorageBytes))\n\t\t\t\t\t(\"storageSize\", baseType.storageSize().str())\n\t\t\t\t\t(\"mul\", overflowCheckedIntMulFunction(*TypeProvider::uint256()))\n\t\t\t\t\t.render();\n\t\t\t}\n\t\t\tcase DataLocation::CallData: // fallthrough\n\t\t\tcase DataLocation::Memory:\n\t\t\t\treturn Whiskers(R\"(\n\t\t\t\t\tfunction <functionName>(length) -> size {\n\t\t\t\t\t\t<?byteArray>\n\t\t\t\t\t\t\tsize := length\n\t\t\t\t\t\t<!byteArray>\n\t\t\t\t\t\t\tsize := <mul>(length, <stride>)\n\t\t\t\t\t\t</byteArray>\n\t\t\t\t\t})\")\n\t\t\t\t\t(\"functionName\", functionName)\n\t\t\t\t\t(\"stride\", to_string(_type.location() == DataLocation::Memory ? _type.memoryStride() : _type.calldataStride()))\n\t\t\t\t\t(\"byteArray\", _type.isByteArray())\n\t\t\t\t\t(\"mul\", overflowCheckedIntMulFunction(*TypeProvider::uint256()))\n\t\t\t\t\t.render();\n\t\t\tdefault:\n\t\t\t\tsolAssert(false, \"\");\n\t\t}\n\n\t});\n}\nstring YulUtilFunctions::arrayAllocationSizeFunction(ArrayType const& _type)\n{\n\tsolAssert(_type.dataStoredIn(DataLocation::Memory), \"\");\n\tstring functionName = \"array_allocation_size_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers w(R\"(\n\t\t\tfunction <functionName>(length) -> size {\n\t\t\t\t// Make sure we can allocate memory without overflow\n\t\t\t\tif gt(length, 0xffffffffffffffff) { revert(0, 0) }\n\t\t\t\t<?byteArray>\n\t\t\t\t\t// round up\n\t\t\t\t\tsize := and(add(length, 0x1f), not(0x1f))\n\t\t\t\t<!byteArray>\n\t\t\t\t\tsize := mul(length, 0x20)\n\t\t\t\t</byteArray>\n\t\t\t\t<?dynamic>\n\t\t\t\t\t// add length slot\n\t\t\t\t\tsize := add(size, 0x20)\n\t\t\t\t</dynamic>\n\t\t\t}\n\t\t)\");\n\t\tw(\"functionName\", functionName);\n\t\tw(\"byteArray\", _type.isByteArray());\n\t\tw(\"dynamic\", _type.isDynamicallySized());\n\t\treturn w.render();\n\t});\n}\n\nstring YulUtilFunctions::arrayDataAreaFunction(ArrayType const& _type)\n{\n\tstring functionName = \"array_dataslot_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\t// No special processing for calldata arrays, because they are stored as\n\t\t// offset of the data area and length on the stack, so the offset already\n\t\t// points to the data area.\n\t\t// This might change, if calldata arrays are stored in a single\n\t\t// stack slot at some point.\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(ptr) -> data {\n\t\t\t\tdata := ptr\n\t\t\t\t<?dynamic>\n\t\t\t\t\t<?memory>\n\t\t\t\t\t\tdata := add(ptr, 0x20)\n\t\t\t\t\t</memory>\n\t\t\t\t\t<?storage>\n\t\t\t\t\t\tmstore(0, ptr)\n\t\t\t\t\t\tdata := keccak256(0, 0x20)\n\t\t\t\t\t</storage>\n\t\t\t\t</dynamic>\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"dynamic\", _type.isDynamicallySized())\n\t\t(\"memory\", _type.location() == DataLocation::Memory)\n\t\t(\"storage\", _type.location() == DataLocation::Storage)\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::storageArrayIndexAccessFunction(ArrayType const& _type)\n{\n\tsolUnimplementedAssert(_type.baseType()->storageBytes() > 16, \"\");\n\n\tstring functionName = \"storage_array_index_access_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(array, index) -> slot, offset {\n\t\t\t\tif iszero(lt(index, <arrayLen>(array))) {\n\t\t\t\t\tinvalid()\n\t\t\t\t}\n\n\t\t\t\tlet data := <dataAreaFunc>(array)\n\t\t\t\t<?multipleItemsPerSlot>\n\n\t\t\t\t<!multipleItemsPerSlot>\n\t\t\t\t\tslot := add(data, mul(index, <storageSize>))\n\t\t\t\t\toffset := 0\n\t\t\t\t</multipleItemsPerSlot>\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"arrayLen\", arrayLengthFunction(_type))\n\t\t(\"dataAreaFunc\", arrayDataAreaFunction(_type))\n\t\t(\"multipleItemsPerSlot\", _type.baseType()->storageBytes() <= 16)\n\t\t(\"storageSize\", _type.baseType()->storageSize().str())\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::memoryArrayIndexAccessFunction(ArrayType const& _type)\n{\n\tstring functionName = \"memory_array_index_access_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(baseRef, index) -> addr {\n\t\t\t\tif iszero(lt(index, <arrayLen>(baseRef))) {\n\t\t\t\t\tinvalid()\n\t\t\t\t}\n\n\t\t\t\tlet offset := mul(index, <stride>)\n\t\t\t\t<?dynamicallySized>\n\t\t\t\t\toffset := add(offset, 32)\n\t\t\t\t</dynamicallySized>\n\t\t\t\taddr := add(baseRef, offset)\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"arrayLen\", arrayLengthFunction(_type))\n\t\t(\"stride\", to_string(_type.memoryStride()))\n\t\t(\"dynamicallySized\", _type.isDynamicallySized())\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::calldataArrayIndexAccessFunction(ArrayType const& _type)\n{\n\tsolAssert(_type.dataStoredIn(DataLocation::CallData), \"\");\n\tstring functionName = \"calldata_array_index_access_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(base_ref<?dynamicallySized>, length</dynamicallySized>, index) -> addr<?dynamicallySizedBase>, len</dynamicallySizedBase> {\n\t\t\t\tif iszero(lt(index, <?dynamicallySized>length<!dynamicallySized><arrayLen></dynamicallySized>)) { invalid() }\n\t\t\t\taddr := add(base_ref, mul(index, <stride>))\n\t\t\t\t<?dynamicallyEncodedBase>\n\t\t\t\t\taddr<?dynamicallySizedBase>, len</dynamicallySizedBase> := <accessCalldataTail>(base_ref, addr)\n\t\t\t\t</dynamicallyEncodedBase>\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"stride\", to_string(_type.calldataStride()))\n\t\t(\"dynamicallySized\", _type.isDynamicallySized())\n\t\t(\"dynamicallyEncodedBase\", _type.baseType()->isDynamicallyEncoded())\n\t\t(\"dynamicallySizedBase\", _type.baseType()->isDynamicallySized())\n\t\t(\"arrayLen\",  toCompactHexWithPrefix(_type.length()))\n\t\t(\"accessCalldataTail\", _type.baseType()->isDynamicallyEncoded() ? accessCalldataTailFunction(*_type.baseType()): \"\")\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::calldataArrayIndexRangeAccess(ArrayType const& _type)\n{\n\tsolAssert(_type.dataStoredIn(DataLocation::CallData), \"\");\n\tsolAssert(_type.isDynamicallySized(), \"\");\n\tstring functionName = \"calldata_array_index_range_access_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(offset, length, startIndex, endIndex) -> offsetOut, lengthOut {\n\t\t\t\tif gt(startIndex, endIndex) { <revertSliceStartAfterEnd> }\n\t\t\t\tif gt(endIndex, length) { <revertSliceGreaterThanLength> }\n\t\t\t\toffsetOut := add(offset, mul(startIndex, <stride>))\n\t\t\t\tlengthOut := sub(endIndex, startIndex)\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"stride\", to_string(_type.calldataStride()))\n\t\t(\"revertSliceStartAfterEnd\", revertReasonIfDebug(\"Slice starts after end\"))\n\t\t(\"revertSliceGreaterThanLength\", revertReasonIfDebug(\"Slice is greater than length\"))\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::accessCalldataTailFunction(Type const& _type)\n{\n\tsolAssert(_type.isDynamicallyEncoded(), \"\");\n\tsolAssert(_type.dataStoredIn(DataLocation::CallData), \"\");\n\tstring functionName = \"access_calldata_tail_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(base_ref, ptr_to_tail) -> addr<?dynamicallySized>, length</dynamicallySized> {\n\t\t\t\tlet rel_offset_of_tail := calldataload(ptr_to_tail)\n\t\t\t\tif iszero(slt(rel_offset_of_tail, sub(sub(calldatasize(), base_ref), sub(<neededLength>, 1)))) { <invalidCalldataTailOffset> }\n\t\t\t\taddr := add(base_ref, rel_offset_of_tail)\n\t\t\t\t<?dynamicallySized>\n\t\t\t\t\tlength := calldataload(addr)\n\t\t\t\t\tif gt(length, 0xffffffffffffffff) { <invalidCalldataTailLength> }\n\t\t\t\t\taddr := add(addr, 32)\n\t\t\t\t\tif sgt(addr, sub(calldatasize(), mul(length, <calldataStride>))) { <shortCalldataTail> }\n\t\t\t\t</dynamicallySized>\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"dynamicallySized\", _type.isDynamicallySized())\n\t\t(\"neededLength\", toCompactHexWithPrefix(_type.calldataEncodedTailSize()))\n\t\t(\"calldataStride\", toCompactHexWithPrefix(_type.isDynamicallySized() ? dynamic_cast<ArrayType const&>(_type).calldataStride() : 0))\n\t\t(\"invalidCalldataTailOffset\", revertReasonIfDebug(\"Invalid calldata tail offset\"))\n\t\t(\"invalidCalldataTailLength\", revertReasonIfDebug(\"Invalid calldata tail length\"))\n\t\t(\"shortCalldataTail\", revertReasonIfDebug(\"Calldata tail too short\"))\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::nextArrayElementFunction(ArrayType const& _type)\n{\n\tsolAssert(!_type.isByteArray(), \"\");\n\tif (_type.dataStoredIn(DataLocation::Storage))\n\t\tsolAssert(_type.baseType()->storageBytes() > 16, \"\");\n\tstring functionName = \"array_nextElement_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers templ(R\"(\n\t\t\tfunction <functionName>(ptr) -> next {\n\t\t\t\tnext := add(ptr, <advance>)\n\t\t\t}\n\t\t)\");\n\t\ttempl(\"functionName\", functionName);\n\t\tswitch (_type.location())\n\t\t{\n\t\tcase DataLocation::Memory:\n\t\t\ttempl(\"advance\", \"0x20\");\n\t\t\tbreak;\n\t\tcase DataLocation::Storage:\n\t\t{\n\t\t\tu256 size = _type.baseType()->storageSize();\n\t\t\tsolAssert(size >= 1, \"\");\n\t\t\ttempl(\"advance\", toCompactHexWithPrefix(size));\n\t\t\tbreak;\n\t\t}\n\t\tcase DataLocation::CallData:\n\t\t{\n\t\t\tu256 size = _type.calldataStride();\n\t\t\tsolAssert(size >= 32 && size % 32 == 0, \"\");\n\t\t\ttempl(\"advance\", toCompactHexWithPrefix(size));\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t\treturn templ.render();\n\t});\n}\n\nstring YulUtilFunctions::mappingIndexAccessFunction(MappingType const& _mappingType, Type const& _keyType)\n{\n\tsolAssert(_keyType.sizeOnStack() <= 1, \"\");\n\n\tstring functionName = \"mapping_index_access_\" + _mappingType.identifier() + \"_of_\" + _keyType.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tif (_mappingType.keyType()->isDynamicallySized())\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(slot <comma> <key>) -> dataSlot {\n\t\t\t\t\tdataSlot := <hash>(slot <comma> <key>)\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"key\", _keyType.sizeOnStack() > 0 ? \"key\" : \"\")\n\t\t\t(\"comma\", _keyType.sizeOnStack() > 0 ? \",\" : \"\")\n\t\t\t(\"hash\", packedHashFunction(\n\t\t\t\t{&_keyType, TypeProvider::uint256()},\n\t\t\t\t{_mappingType.keyType(), TypeProvider::uint256()}\n\t\t\t))\n\t\t\t.render();\n\t\telse\n\t\t{\n\t\t\tsolAssert(CompilerUtils::freeMemoryPointer >= 0x40, \"\");\n\t\t\tsolAssert(!_mappingType.keyType()->isDynamicallyEncoded(), \"\");\n\t\t\tsolAssert(_mappingType.keyType()->calldataEncodedSize(false) <= 0x20, \"\");\n\t\t\tWhiskers templ(R\"(\n\t\t\t\tfunction <functionName>(slot <key>) -> dataSlot {\n\t\t\t\t\tmstore(0, <convertedKey>)\n\t\t\t\t\tmstore(0x20, slot)\n\t\t\t\t\tdataSlot := keccak256(0, 0x40)\n\t\t\t\t}\n\t\t\t)\");\n\t\t\ttempl(\"functionName\", functionName);\n\t\t\ttempl(\"key\", _keyType.sizeOnStack() == 1 ? \", key\" : \"\");\n\t\t\tif (_keyType.sizeOnStack() == 0)\n\t\t\t\ttempl(\"convertedKey\", conversionFunction(_keyType, *_mappingType.keyType()) + \"()\");\n\t\t\telse\n\t\t\t\ttempl(\"convertedKey\", conversionFunction(_keyType, *_mappingType.keyType()) + \"(key)\");\n\t\t\treturn templ.render();\n\t\t}\n\t});\n}\n\nstring YulUtilFunctions::readFromStorage(Type const& _type, size_t _offset, bool _splitFunctionTypes)\n{\n\tsolUnimplementedAssert(!_splitFunctionTypes, \"\");\n\tstring functionName =\n\t\t\"read_from_storage_\" +\n\t\tstring(_splitFunctionTypes ? \"split_\" : \"\") +\n\t\t\"offset_\" +\n\t\tto_string(_offset) +\n\t\t\"_\" +\n\t\t_type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\tsolAssert(_type.sizeOnStack() == 1, \"\");\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(slot) -> value {\n\t\t\t\tvalue := <extract>(sload(slot))\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"extract\", extractFromStorageValue(_type, _offset, false))\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::readFromStorageDynamic(Type const& _type, bool _splitFunctionTypes)\n{\n\tsolUnimplementedAssert(!_splitFunctionTypes, \"\");\n\tstring functionName =\n\t\t\"read_from_storage_dynamic\" +\n\t\tstring(_splitFunctionTypes ? \"split_\" : \"\") +\n\t\t\"_\" +\n\t\t_type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\tsolAssert(_type.sizeOnStack() == 1, \"\");\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(slot, offset) -> value {\n\t\t\t\tvalue := <extract>(sload(slot), offset)\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"extract\", extractFromStorageValueDynamic(_type, _splitFunctionTypes))\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::readFromMemory(Type const& _type)\n{\n\treturn readFromMemoryOrCalldata(_type, false);\n}\n\nstring YulUtilFunctions::readFromCalldata(Type const& _type)\n{\n\treturn readFromMemoryOrCalldata(_type, true);\n}\n\nstring YulUtilFunctions::updateStorageValueFunction(Type const& _type, std::optional<unsigned> const& _offset)\n{\n\tstring const functionName =\n\t\t\"update_storage_value_\" +\n\t\t(_offset.has_value() ? (\"offset_\" + to_string(*_offset)) : \"\") +\n\t\t_type.identifier();\n\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\tif (_type.isValueType())\n\t\t{\n\t\t\tsolAssert(_type.storageBytes() <= 32, \"Invalid storage bytes size.\");\n\t\t\tsolAssert(_type.storageBytes() > 0, \"Invalid storage bytes size.\");\n\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(slot, <offset>value) {\n\t\t\t\t\tsstore(slot, <update>(sload(slot), <offset><prepare>(value)))\n\t\t\t\t}\n\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"update\",\n\t\t\t\t_offset.has_value() ?\n\t\t\t\t\tupdateByteSliceFunction(_type.storageBytes(), *_offset) :\n\t\t\t\t\tupdateByteSliceFunctionDynamic(_type.storageBytes())\n\t\t\t)\n\t\t\t(\"offset\", _offset.has_value() ? \"\" : \"offset, \")\n\t\t\t(\"prepare\", prepareStoreFunction(_type))\n\t\t\t.render();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (_type.category() == Type::Category::Array)\n\t\t\t\tsolUnimplementedAssert(false, \"\");\n\t\t\telse if (_type.category() == Type::Category::Struct)\n\t\t\t\tsolUnimplementedAssert(false, \"\");\n\t\t\telse\n\t\t\t\tsolAssert(false, \"Invalid non-value type for assignment.\");\n\t\t}\n\t});\n}\n\nstring YulUtilFunctions::writeToMemoryFunction(Type const& _type)\n{\n\tstring const functionName =\n\t\tstring(\"write_to_memory_\") +\n\t\t_type.identifier();\n\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\tsolAssert(!dynamic_cast<StringLiteralType const*>(&_type), \"\");\n\t\tif (auto ref = dynamic_cast<ReferenceType const*>(&_type))\n\t\t{\n\t\t\tsolAssert(\n\t\t\t\tref->location() == DataLocation::Memory,\n\t\t\t\t\"Can only update types with location memory.\"\n\t\t\t);\n\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(memPtr, value) {\n\t\t\t\t\tmstore(memPtr, value)\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t\t}\n\t\telse if (\n\t\t\t_type.category() == Type::Category::Function &&\n\t\t\tdynamic_cast<FunctionType const&>(_type).kind() == FunctionType::Kind::External\n\t\t)\n\t\t{\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(memPtr, addr, selector) {\n\t\t\t\t\tmstore(memPtr, <combine>(addr, selector))\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"combine\", combineExternalFunctionIdFunction())\n\t\t\t.render();\n\t\t}\n\t\telse if (_type.isValueType())\n\t\t{\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(memPtr, value) {\n\t\t\t\t\tmstore(memPtr, <cleanup>(value))\n\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"cleanup\", cleanupFunction(_type))\n\t\t\t.render();\n\t\t}\n\t\telse // Should never happen\n\t\t{\n\t\t\tsolAssert(\n\t\t\t\tfalse,\n\t\t\t\t\"Memory store of type \" + _type.toString(true) + \" not allowed.\"\n\t\t\t);\n\t\t}\n\t});\n}\n\nstring YulUtilFunctions::extractFromStorageValueDynamic(Type const& _type, bool _splitFunctionTypes)\n{\n\tsolUnimplementedAssert(!_splitFunctionTypes, \"\");\n\n\tstring functionName =\n\t\t\"extract_from_storage_value_dynamic\" +\n\t\tstring(_splitFunctionTypes ? \"split_\" : \"\") +\n\t\t_type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(slot_value, offset) -> value {\n\t\t\t\tvalue := <cleanupStorage>(<shr>(mul(offset, 8), slot_value))\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"shr\", shiftRightFunctionDynamic())\n\t\t(\"cleanupStorage\", cleanupFromStorageFunction(_type, _splitFunctionTypes))\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::extractFromStorageValue(Type const& _type, size_t _offset, bool _splitFunctionTypes)\n{\n\tsolUnimplementedAssert(!_splitFunctionTypes, \"\");\n\n\tstring functionName =\n\t\t\"extract_from_storage_value_\" +\n\t\tstring(_splitFunctionTypes ? \"split_\" : \"\") +\n\t\t\"offset_\" +\n\t\tto_string(_offset) +\n\t\t_type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(slot_value) -> value {\n\t\t\t\tvalue := <cleanupStorage>(<shr>(slot_value))\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"shr\", shiftRightFunction(_offset * 8))\n\t\t(\"cleanupStorage\", cleanupFromStorageFunction(_type, _splitFunctionTypes))\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::cleanupFromStorageFunction(Type const& _type, bool _splitFunctionTypes)\n{\n\tsolAssert(_type.isValueType(), \"\");\n\tsolUnimplementedAssert(!_splitFunctionTypes, \"\");\n\n\tstring functionName = string(\"cleanup_from_storage_\") + (_splitFunctionTypes ? \"split_\" : \"\") + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\tWhiskers templ(R\"(\n\t\t\tfunction <functionName>(value) -> cleaned {\n\t\t\t\tcleaned := <cleaned>\n\t\t\t}\n\t\t)\");\n\t\ttempl(\"functionName\", functionName);\n\n\t\tunsigned storageBytes = _type.storageBytes();\n\t\tif (IntegerType const* type = dynamic_cast<IntegerType const*>(&_type))\n\t\t\tif (type->isSigned() && storageBytes != 32)\n\t\t\t{\n\t\t\t\ttempl(\"cleaned\", \"signextend(\" + to_string(storageBytes - 1) + \", value)\");\n\t\t\t\treturn templ.render();\n\t\t\t}\n\n\t\tif (storageBytes == 32)\n\t\t\ttempl(\"cleaned\", \"value\");\n\t\telse if (_type.leftAligned())\n\t\t\ttempl(\"cleaned\", shiftLeftFunction(256 - 8 * storageBytes) + \"(value)\");\n\t\telse\n\t\t\ttempl(\"cleaned\", \"and(value, \" + toCompactHexWithPrefix((u256(1) << (8 * storageBytes)) - 1) + \")\");\n\n\t\treturn templ.render();\n\t});\n}\n\nstring YulUtilFunctions::prepareStoreFunction(Type const& _type)\n{\n\tsolUnimplementedAssert(_type.category() != Type::Category::Function, \"\");\n\n\tstring functionName = \"prepare_store_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers templ(R\"(\n\t\t\tfunction <functionName>(value) -> ret {\n\t\t\t\tret := <actualPrepare>\n\t\t\t}\n\t\t)\");\n\t\ttempl(\"functionName\", functionName);\n\t\tif (_type.category() == Type::Category::FixedBytes)\n\t\t\ttempl(\"actualPrepare\", shiftRightFunction(256 - 8 * _type.storageBytes()) + \"(value)\");\n\t\telse\n\t\t\ttempl(\"actualPrepare\", \"value\");\n\t\treturn templ.render();\n\t});\n}\n\nstring YulUtilFunctions::allocationFunction()\n{\n\tstring functionName = \"allocateMemory\";\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(size) -> memPtr {\n\t\t\t\tmemPtr := mload(<freeMemoryPointer>)\n\t\t\t\tlet newFreePtr := add(memPtr, size)\n\t\t\t\t// protect against overflow\n\t\t\t\tif or(gt(newFreePtr, 0xffffffffffffffff), lt(newFreePtr, memPtr)) { revert(0, 0) }\n\t\t\t\tmstore(<freeMemoryPointer>, newFreePtr)\n\t\t\t}\n\t\t)\")\n\t\t(\"freeMemoryPointer\", to_string(CompilerUtils::freeMemoryPointer))\n\t\t(\"functionName\", functionName)\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::allocateMemoryArrayFunction(ArrayType const& _type)\n{\n\tsolUnimplementedAssert(!_type.isByteArray(), \"\");\n\n\tstring functionName = \"allocate_memory_array_\" + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(length) -> memPtr {\n\t\t\t\tmemPtr := <alloc>(<allocSize>(length))\n\t\t\t\t<?dynamic>\n\t\t\t\tmstore(memPtr, length)\n\t\t\t\t</dynamic>\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"alloc\", allocationFunction())\n\t\t(\"allocSize\", arrayAllocationSizeFunction(_type))\n\t\t(\"dynamic\", _type.isDynamicallySized())\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::conversionFunction(Type const& _from, Type const& _to)\n{\n\tif (_from.category() == Type::Category::Function)\n\t{\n\t\tsolAssert(_to.category() == Type::Category::Function, \"\");\n\t\tFunctionType const& fromType = dynamic_cast<FunctionType const&>(_from);\n\t\tFunctionType const& targetType = dynamic_cast<FunctionType const&>(_to);\n\t\tsolAssert(\n\t\t\tfromType.isImplicitlyConvertibleTo(targetType) &&\n\t\t\tfromType.sizeOnStack() == targetType.sizeOnStack() &&\n\t\t\t(fromType.kind() == FunctionType::Kind::Internal || fromType.kind() == FunctionType::Kind::External) &&\n\t\t\tfromType.kind() == targetType.kind(),\n\t\t\t\"Invalid function type conversion requested.\"\n\t\t);\n\t\tstring const functionName =\n\t\t\t\"convert_\" +\n\t\t\t_from.identifier() +\n\t\t\t\"_to_\" +\n\t\t\t_to.identifier();\n\t\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(addr, functionId) -> outAddr, outFunctionId {\n\t\t\t\t\toutAddr := addr\n\t\t\t\t\toutFunctionId := functionId\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t\t});\n\t}\n\n\tif (_from.category() == Type::Category::ArraySlice)\n\t{\n\t\tsolAssert(_from.isDynamicallySized(), \"\");\n\t\tsolAssert(_from.dataStoredIn(DataLocation::CallData), \"\");\n\t\tsolAssert(_to.category() == Type::Category::Array, \"\");\n\n\t\tArraySliceType const& fromType = dynamic_cast<ArraySliceType const&>(_from);\n\t\tArrayType const& targetType = dynamic_cast<ArrayType const&>(_to);\n\n\t\tsolAssert(\n\t\t\t*fromType.arrayType().baseType() == *targetType.baseType(),\n\t\t\t\"Converting arrays of different type is not possible\"\n\t\t);\n\n\t\tstring const functionName =\n\t\t\t\"convert_\" +\n\t\t\t_from.identifier() +\n\t\t\t\"_to_\" +\n\t\t\t_to.identifier();\n\t\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(offset, length) -> outOffset, outLength {\n\t\t\t\t\toutOffset := offset\n\t\t\t\t\toutLength := length\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t\t});\n\t}\n\n\tif (_from.sizeOnStack() != 1 || _to.sizeOnStack() != 1)\n\t\treturn conversionFunctionSpecial(_from, _to);\n\n\tstring functionName =\n\t\t\"convert_\" +\n\t\t_from.identifier() +\n\t\t\"_to_\" +\n\t\t_to.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers templ(R\"(\n\t\t\tfunction <functionName>(value) -> converted {\n\t\t\t\t<body>\n\t\t\t}\n\t\t)\");\n\t\ttempl(\"functionName\", functionName);\n\t\tstring body;\n\t\tauto toCategory = _to.category();\n\t\tauto fromCategory = _from.category();\n\t\tswitch (fromCategory)\n\t\t{\n\t\tcase Type::Category::Address:\n\t\t\tbody =\n\t\t\t\tWhiskers(\"converted := <convert>(value)\")\n\t\t\t\t\t(\"convert\", conversionFunction(IntegerType(160), _to))\n\t\t\t\t\t.render();\n\t\t\tbreak;\n\t\tcase Type::Category::Integer:\n\t\tcase Type::Category::RationalNumber:\n\t\tcase Type::Category::Contract:\n\t\t{\n\t\t\tif (RationalNumberType const* rational = dynamic_cast<RationalNumberType const*>(&_from))\n\t\t\t\tsolUnimplementedAssert(!rational->isFractional(), \"Not yet implemented - FixedPointType.\");\n\t\t\tif (toCategory == Type::Category::FixedBytes)\n\t\t\t{\n\t\t\t\tsolAssert(\n\t\t\t\t\tfromCategory == Type::Category::Integer || fromCategory == Type::Category::RationalNumber,\n\t\t\t\t\t\"Invalid conversion to FixedBytesType requested.\"\n\t\t\t\t);\n\t\t\t\tFixedBytesType const& toBytesType = dynamic_cast<FixedBytesType const&>(_to);\n\t\t\t\tbody =\n\t\t\t\t\tWhiskers(\"converted := <shiftLeft>(<clean>(value))\")\n\t\t\t\t\t\t(\"shiftLeft\", shiftLeftFunction(256 - toBytesType.numBytes() * 8))\n\t\t\t\t\t\t(\"clean\", cleanupFunction(_from))\n\t\t\t\t\t\t.render();\n\t\t\t}\n\t\t\telse if (toCategory == Type::Category::Enum)\n\t\t\t{\n\t\t\t\tsolAssert(_from.mobileType(), \"\");\n\t\t\t\tbody =\n\t\t\t\t\tWhiskers(\"converted := <cleanEnum>(<cleanInt>(value))\")\n\t\t\t\t\t(\"cleanEnum\", cleanupFunction(_to))\n\t\t\t\t\t// \"mobileType()\" returns integer type for rational\n\t\t\t\t\t(\"cleanInt\", cleanupFunction(*_from.mobileType()))\n\t\t\t\t\t.render();\n\t\t\t}\n\t\t\telse if (toCategory == Type::Category::FixedPoint)\n\t\t\t\tsolUnimplemented(\"Not yet implemented - FixedPointType.\");\n\t\t\telse if (toCategory == Type::Category::Address)\n\t\t\t\tbody =\n\t\t\t\t\tWhiskers(\"converted := <convert>(value)\")\n\t\t\t\t\t\t(\"convert\", conversionFunction(_from, IntegerType(160)))\n\t\t\t\t\t\t.render();\n\t\t\telse\n\t\t\t{\n\t\t\t\tsolAssert(\n\t\t\t\t\ttoCategory == Type::Category::Integer ||\n\t\t\t\t\ttoCategory == Type::Category::Contract,\n\t\t\t\t\"\");\n\t\t\t\tIntegerType const addressType(160);\n\t\t\t\tIntegerType const& to =\n\t\t\t\t\ttoCategory == Type::Category::Integer ?\n\t\t\t\t\tdynamic_cast<IntegerType const&>(_to) :\n\t\t\t\t\taddressType;\n\n\t\t\t\t// Clean according to the \"to\" type, except if this is\n\t\t\t\t// a widening conversion.\n\t\t\t\tIntegerType const* cleanupType = &to;\n\t\t\t\tif (fromCategory != Type::Category::RationalNumber)\n\t\t\t\t{\n\t\t\t\t\tIntegerType const& from =\n\t\t\t\t\t\tfromCategory == Type::Category::Integer ?\n\t\t\t\t\t\tdynamic_cast<IntegerType const&>(_from) :\n\t\t\t\t\t\taddressType;\n\t\t\t\t\tif (to.numBits() > from.numBits())\n\t\t\t\t\t\tcleanupType = &from;\n\t\t\t\t}\n\t\t\t\tbody =\n\t\t\t\t\tWhiskers(\"converted := <cleanInt>(value)\")\n\t\t\t\t\t(\"cleanInt\", cleanupFunction(*cleanupType))\n\t\t\t\t\t.render();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::Bool:\n\t\t{\n\t\t\tsolAssert(_from == _to, \"Invalid conversion for bool.\");\n\t\t\tbody =\n\t\t\t\tWhiskers(\"converted := <clean>(value)\")\n\t\t\t\t(\"clean\", cleanupFunction(_from))\n\t\t\t\t.render();\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::FixedPoint:\n\t\t\tsolUnimplemented(\"Fixed point types not implemented.\");\n\t\t\tbreak;\n\t\tcase Type::Category::Array:\n\t\t{\n\t\t\tif (_from == _to)\n\t\t\t\tbody = \"converted := value\";\n\t\t\telse\n\t\t\t{\n\t\t\t\tArrayType const& from = dynamic_cast<decltype(from)>(_from);\n\t\t\t\tArrayType const& to = dynamic_cast<decltype(to)>(_to);\n\n\t\t\t\tswitch (to.location())\n\t\t\t\t{\n\t\t\t\tcase DataLocation::Storage:\n\t\t\t\t\t// Other cases are done explicitly in LValue::storeValue, and only possible by assignment.\n\t\t\t\t\tsolAssert(\n\t\t\t\t\t\t(to.isPointer() || (from.isByteArray() && to.isByteArray())) &&\n\t\t\t\t\t\tfrom.location() == DataLocation::Storage,\n\t\t\t\t\t\t\"Invalid conversion to storage type.\"\n\t\t\t\t\t);\n\t\t\t\t\tbody = \"converted := value\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataLocation::Memory:\n\t\t\t\t\t// Copy the array to a free position in memory, unless it is already in memory.\n\t\t\t\t\tsolUnimplementedAssert(from.location() == DataLocation::Memory, \"Not implemented yet.\");\n\t\t\t\t\tbody = \"converted := value\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataLocation::CallData:\n\t\t\t\t\tsolUnimplemented(\"Conversion of calldata types not yet implemented.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::Struct:\n\t\t\tsolUnimplementedAssert(false, \"Struct conversion not implemented.\");\n\t\t\tbreak;\n\t\tcase Type::Category::FixedBytes:\n\t\t{\n\t\t\tFixedBytesType const& from = dynamic_cast<FixedBytesType const&>(_from);\n\t\t\tif (toCategory == Type::Category::Integer)\n\t\t\t\tbody =\n\t\t\t\t\tWhiskers(\"converted := <convert>(<shift>(value))\")\n\t\t\t\t\t(\"shift\", shiftRightFunction(256 - from.numBytes() * 8))\n\t\t\t\t\t(\"convert\", conversionFunction(IntegerType(from.numBytes() * 8), _to))\n\t\t\t\t\t.render();\n\t\t\telse if (toCategory == Type::Category::Address)\n\t\t\t\tbody =\n\t\t\t\t\tWhiskers(\"converted := <convert>(value)\")\n\t\t\t\t\t\t(\"convert\", conversionFunction(_from, IntegerType(160)))\n\t\t\t\t\t\t.render();\n\t\t\telse\n\t\t\t{\n\t\t\t\t// clear for conversion to longer bytes\n\t\t\t\tsolAssert(toCategory == Type::Category::FixedBytes, \"Invalid type conversion requested.\");\n\t\t\t\tbody =\n\t\t\t\t\tWhiskers(\"converted := <clean>(value)\")\n\t\t\t\t\t(\"clean\", cleanupFunction(from))\n\t\t\t\t\t.render();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::Function:\n\t\t{\n\t\t\tsolAssert(false, \"Conversion should not be called for function types.\");\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::Enum:\n\t\t{\n\t\t\tsolAssert(toCategory == Type::Category::Integer || _from == _to, \"\");\n\t\t\tEnumType const& enumType = dynamic_cast<decltype(enumType)>(_from);\n\t\t\tbody =\n\t\t\t\tWhiskers(\"converted := <clean>(value)\")\n\t\t\t\t(\"clean\", cleanupFunction(enumType))\n\t\t\t\t.render();\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::Tuple:\n\t\t{\n\t\t\tsolUnimplementedAssert(false, \"Tuple conversion not implemented.\");\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tsolAssert(false, \"\");\n\t\t}\n\n\t\tsolAssert(!body.empty(), _from.canonicalName() + \" to \" + _to.canonicalName());\n\t\ttempl(\"body\", body);\n\t\treturn templ.render();\n\t});\n}\n\nstring YulUtilFunctions::cleanupFunction(Type const& _type)\n{\n\tstring functionName = string(\"cleanup_\") + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers templ(R\"(\n\t\t\tfunction <functionName>(value) -> cleaned {\n\t\t\t\t<body>\n\t\t\t}\n\t\t)\");\n\t\ttempl(\"functionName\", functionName);\n\t\tswitch (_type.category())\n\t\t{\n\t\tcase Type::Category::Address:\n\t\t\ttempl(\"body\", \"cleaned := \" + cleanupFunction(IntegerType(160)) + \"(value)\");\n\t\t\tbreak;\n\t\tcase Type::Category::Integer:\n\t\t{\n\t\t\tIntegerType const& type = dynamic_cast<IntegerType const&>(_type);\n\t\t\tif (type.numBits() == 256)\n\t\t\t\ttempl(\"body\", \"cleaned := value\");\n\t\t\telse if (type.isSigned())\n\t\t\t\ttempl(\"body\", \"cleaned := signextend(\" + to_string(type.numBits() / 8 - 1) + \", value)\");\n\t\t\telse\n\t\t\t\ttempl(\"body\", \"cleaned := and(value, \" + toCompactHexWithPrefix((u256(1) << type.numBits()) - 1) + \")\");\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::RationalNumber:\n\t\t\ttempl(\"body\", \"cleaned := value\");\n\t\t\tbreak;\n\t\tcase Type::Category::Bool:\n\t\t\ttempl(\"body\", \"cleaned := iszero(iszero(value))\");\n\t\t\tbreak;\n\t\tcase Type::Category::FixedPoint:\n\t\t\tsolUnimplemented(\"Fixed point types not implemented.\");\n\t\t\tbreak;\n\t\tcase Type::Category::Function:\n\t\t\tsolAssert(dynamic_cast<FunctionType const&>(_type).kind() == FunctionType::Kind::External, \"\");\n\t\t\ttempl(\"body\", \"cleaned := \" + cleanupFunction(FixedBytesType(24)) + \"(value)\");\n\t\t\tbreak;\n\t\tcase Type::Category::Array:\n\t\tcase Type::Category::Struct:\n\t\tcase Type::Category::Mapping:\n\t\t\tsolAssert(_type.dataStoredIn(DataLocation::Storage), \"Cleanup requested for non-storage reference type.\");\n\t\t\ttempl(\"body\", \"cleaned := value\");\n\t\t\tbreak;\n\t\tcase Type::Category::FixedBytes:\n\t\t{\n\t\t\tFixedBytesType const& type = dynamic_cast<FixedBytesType const&>(_type);\n\t\t\tif (type.numBytes() == 32)\n\t\t\t\ttempl(\"body\", \"cleaned := value\");\n\t\t\telse if (type.numBytes() == 0)\n\t\t\t\t// This is disallowed in the type system.\n\t\t\t\tsolAssert(false, \"\");\n\t\t\telse\n\t\t\t{\n\t\t\t\tsize_t numBits = type.numBytes() * 8;\n\t\t\t\tu256 mask = ((u256(1) << numBits) - 1) << (256 - numBits);\n\t\t\t\ttempl(\"body\", \"cleaned := and(value, \" + toCompactHexWithPrefix(mask) + \")\");\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::Contract:\n\t\t{\n\t\t\tAddressType addressType(dynamic_cast<ContractType const&>(_type).isPayable() ?\n\t\t\t\tStateMutability::Payable :\n\t\t\t\tStateMutability::NonPayable\n\t\t\t);\n\t\t\ttempl(\"body\", \"cleaned := \" + cleanupFunction(addressType) + \"(value)\");\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::Enum:\n\t\t{\n\t\t\t// Out of range enums cannot be truncated unambigiously and therefore it should be an error.\n\t\t\ttempl(\"body\", \"cleaned := value \" + validatorFunction(_type) + \"(value)\");\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::InaccessibleDynamic:\n\t\t\ttempl(\"body\", \"cleaned := 0\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsolAssert(false, \"Cleanup of type \" + _type.identifier() + \" requested.\");\n\t\t}\n\n\t\treturn templ.render();\n\t});\n}\n\nstring YulUtilFunctions::validatorFunction(Type const& _type, bool _revertOnFailure)\n{\n\tstring functionName = string(\"validator_\") + (_revertOnFailure ? \"revert_\" : \"assert_\") + _type.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers templ(R\"(\n\t\t\tfunction <functionName>(value) {\n\t\t\t\tif iszero(<condition>) { <failure> }\n\t\t\t}\n\t\t)\");\n\t\ttempl(\"functionName\", functionName);\n\t\tif (_revertOnFailure)\n\t\t\ttempl(\"failure\", \"revert(0, 0)\");\n\t\telse\n\t\t\ttempl(\"failure\", \"invalid()\");\n\n\t\tswitch (_type.category())\n\t\t{\n\t\tcase Type::Category::Address:\n\t\tcase Type::Category::Integer:\n\t\tcase Type::Category::RationalNumber:\n\t\tcase Type::Category::Bool:\n\t\tcase Type::Category::FixedPoint:\n\t\tcase Type::Category::Function:\n\t\tcase Type::Category::Array:\n\t\tcase Type::Category::Struct:\n\t\tcase Type::Category::Mapping:\n\t\tcase Type::Category::FixedBytes:\n\t\tcase Type::Category::Contract:\n\t\t{\n\t\t\ttempl(\"condition\", \"eq(value, \" + cleanupFunction(_type) + \"(value))\");\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::Enum:\n\t\t{\n\t\t\tsize_t members = dynamic_cast<EnumType const&>(_type).numberOfMembers();\n\t\t\tsolAssert(members > 0, \"empty enum should have caused a parser error.\");\n\t\t\ttempl(\"condition\", \"lt(value, \" + to_string(members) + \")\");\n\t\t\tbreak;\n\t\t}\n\t\tcase Type::Category::InaccessibleDynamic:\n\t\t\ttempl(\"condition\", \"1\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsolAssert(false, \"Validation of type \" + _type.identifier() + \" requested.\");\n\t\t}\n\n\t\treturn templ.render();\n\t});\n}\n\nstring YulUtilFunctions::packedHashFunction(\n\tvector<Type const*> const& _givenTypes,\n\tvector<Type const*> const& _targetTypes\n)\n{\n\tstring functionName = string(\"packed_hashed_\");\n\tfor (auto const& t: _givenTypes)\n\t\tfunctionName += t->identifier() + \"_\";\n\tfunctionName += \"_to_\";\n\tfor (auto const& t: _targetTypes)\n\t\tfunctionName += t->identifier() + \"_\";\n\tsize_t sizeOnStack = 0;\n\tfor (Type const* t: _givenTypes)\n\t\tsizeOnStack += t->sizeOnStack();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tWhiskers templ(R\"(\n\t\t\tfunction <functionName>(<variables>) -> hash {\n\t\t\t\tlet pos := mload(<freeMemoryPointer>)\n\t\t\t\tlet end := <packedEncode>(pos <comma> <variables>)\n\t\t\t\thash := keccak256(pos, sub(end, pos))\n\t\t\t}\n\t\t)\");\n\t\ttempl(\"functionName\", functionName);\n\t\ttempl(\"variables\", suffixedVariableNameList(\"var_\", 1, 1 + sizeOnStack));\n\t\ttempl(\"comma\", sizeOnStack > 0 ? \",\" : \"\");\n\t\ttempl(\"freeMemoryPointer\", to_string(CompilerUtils::freeMemoryPointer));\n\t\ttempl(\"packedEncode\", ABIFunctions(m_evmVersion, m_revertStrings, m_functionCollector).tupleEncoderPacked(_givenTypes, _targetTypes));\n\t\treturn templ.render();\n\t});\n}\n\nstring YulUtilFunctions::forwardingRevertFunction()\n{\n\tbool forward = m_evmVersion.supportsReturndata();\n\tstring functionName = \"revert_forward_\" + to_string(forward);\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tif (forward)\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>() {\n\t\t\t\t\treturndatacopy(0, 0, returndatasize())\n\t\t\t\t\trevert(0, returndatasize())\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t\telse\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>() {\n\t\t\t\t\trevert(0, 0)\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t});\n}\n\nstd::string YulUtilFunctions::decrementCheckedFunction(Type const& _type)\n{\n\tIntegerType const& type = dynamic_cast<IntegerType const&>(_type);\n\n\tstring const functionName = \"decrement_\" + _type.identifier();\n\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tu256 minintval;\n\n\t\t// Smallest admissible value to decrement\n\t\tif (type.isSigned())\n\t\t\tminintval = 0 - (u256(1) << (type.numBits() - 1)) + 1;\n\t\telse\n\t\t\tminintval = 1;\n\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(value) -> ret {\n\t\t\t\tif <lt>(value, <minval>) { revert(0,0) }\n\t\t\t\tret := sub(value, 1)\n\t\t\t}\n\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"minval\", toCompactHexWithPrefix(minintval))\n\t\t\t(\"lt\", type.isSigned() ? \"slt\" : \"lt\")\n\t\t\t.render();\n\t});\n}\n\nstd::string YulUtilFunctions::incrementCheckedFunction(Type const& _type)\n{\n\tIntegerType const& type = dynamic_cast<IntegerType const&>(_type);\n\n\tstring const functionName = \"increment_\" + _type.identifier();\n\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tu256 maxintval;\n\n\t\t// Biggest admissible value to increment\n\t\tif (type.isSigned())\n\t\t\tmaxintval = (u256(1) << (type.numBits() - 1)) - 2;\n\t\telse\n\t\t\tmaxintval = (u256(1) << type.numBits()) - 2;\n\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(value) -> ret {\n\t\t\t\tif <gt>(value, <maxval>) { revert(0,0) }\n\t\t\t\tret := add(value, 1)\n\t\t\t}\n\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"maxval\", toCompactHexWithPrefix(maxintval))\n\t\t\t(\"gt\", type.isSigned() ? \"sgt\" : \"gt\")\n\t\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::negateNumberCheckedFunction(Type const& _type)\n{\n\tIntegerType const& type = dynamic_cast<IntegerType const&>(_type);\n\tsolAssert(type.isSigned(), \"Expected signed type!\");\n\n\tstring const functionName = \"negate_\" + _type.identifier();\n\n\tu256 const minintval = 0 - (u256(1) << (type.numBits() - 1)) + 1;\n\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(_value) -> ret {\n\t\t\t\tif slt(_value, <minval>) { revert(0,0) }\n\t\t\t\tret := sub(0, _value)\n\t\t\t}\n\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"minval\", toCompactHexWithPrefix(minintval))\n\t\t\t.render();\n\t\t});\n}\n\nstring YulUtilFunctions::zeroValueFunction(Type const& _type)\n{\n\tsolUnimplementedAssert(_type.sizeOnStack() == 1, \"Stacksize not yet implemented!\");\n\tsolUnimplementedAssert(_type.isValueType(), \"Zero value for non-value types not yet implemented\");\n\n\tstring const functionName = \"zero_value_for_\" + _type.identifier();\n\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>() -> ret {\n\t\t\t\t<body>\n\t\t\t}\n\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"body\", \"ret := 0x0\")\n\t\t\t.render();\n\t\t});\n}\n\nstring YulUtilFunctions::storageSetToZeroFunction(Type const& _type)\n{\n\tstring const functionName = \"storage_set_to_zero_\" + _type.identifier();\n\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tif (_type.isValueType())\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(slot, offset) {\n\t\t\t\t\t<store>(slot, offset, <zeroValue>())\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"store\", updateStorageValueFunction(_type))\n\t\t\t(\"zeroValue\", zeroValueFunction(_type))\n\t\t\t.render();\n\t\telse if (_type.category() == Type::Category::Array)\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(slot, offset) {\n\t\t\t\t\t<clearArray>(slot)\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"clearArray\", clearStorageArrayFunction(dynamic_cast<ArrayType const&>(_type)))\n\t\t\t.render();\n\t\telse\n\t\t\tsolUnimplemented(\"setToZero for type \" + _type.identifier() + \" not yet implemented!\");\n\t});\n}\n\nstring YulUtilFunctions::conversionFunctionSpecial(Type const& _from, Type const& _to)\n{\n\tstring functionName =\n\t\t\"convert_\" +\n\t\t_from.identifier() +\n\t\t\"_to_\" +\n\t\t_to.identifier();\n\treturn m_functionCollector.createFunction(functionName, [&]() {\n\t\tif (\n\t\t\tauto fromTuple = dynamic_cast<TupleType const*>(&_from), toTuple = dynamic_cast<TupleType const*>(&_to);\n\t\t\tfromTuple && toTuple && fromTuple->components().size() == toTuple->components().size()\n\t\t)\n\t\t{\n\t\t\tsize_t sourceStackSize = 0;\n\t\t\tsize_t destStackSize = 0;\n\t\t\tstd::string conversions;\n\t\t\tfor (size_t i = 0; i < fromTuple->components().size(); ++i)\n\t\t\t{\n\t\t\t\tauto fromComponent = fromTuple->components()[i];\n\t\t\t\tauto toComponent = toTuple->components()[i];\n\t\t\t\tsolAssert(fromComponent, \"\");\n\t\t\t\tif (toComponent)\n\t\t\t\t{\n\t\t\t\t\tconversions +=\n\t\t\t\t\t\tsuffixedVariableNameList(\"converted\", destStackSize, destStackSize + toComponent->sizeOnStack()) +\n\t\t\t\t\t\t\" := \" +\n\t\t\t\t\t\tconversionFunction(*fromComponent, *toComponent) +\n\t\t\t\t\t\t\"(\" +\n\t\t\t\t\t\tsuffixedVariableNameList(\"value\", sourceStackSize, sourceStackSize + fromComponent->sizeOnStack()) +\n\t\t\t\t\t\t\")\\n\";\n\t\t\t\t\tdestStackSize += toComponent->sizeOnStack();\n\t\t\t\t}\n\t\t\t\tsourceStackSize += fromComponent->sizeOnStack();\n\t\t\t}\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(<values>) -> <converted> {\n\t\t\t\t\t<conversions>\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t(\"values\", suffixedVariableNameList(\"value\", 0, sourceStackSize))\n\t\t\t(\"converted\", suffixedVariableNameList(\"converted\", 0, destStackSize))\n\t\t\t(\"conversions\", conversions)\n\t\t\t.render();\n\t\t}\n\n\t\tsolUnimplementedAssert(\n\t\t\t_from.category() == Type::Category::StringLiteral,\n\t\t\t\"Type conversion \" + _from.toString() + \" -> \" + _to.toString() + \" not yet implemented.\"\n\t\t);\n\t\tstring const& data = dynamic_cast<StringLiteralType const&>(_from).value();\n\t\tif (_to.category() == Type::Category::FixedBytes)\n\t\t{\n\t\t\tunsigned const numBytes = dynamic_cast<FixedBytesType const&>(_to).numBytes();\n\t\t\tsolAssert(data.size() <= 32, \"\");\n\t\t\tWhiskers templ(R\"(\n\t\t\t\tfunction <functionName>() -> converted {\n\t\t\t\t\tconverted := <data>\n\t\t\t\t}\n\t\t\t)\");\n\t\t\ttempl(\"functionName\", functionName);\n\t\t\ttempl(\"data\", formatNumber(\n\t\t\t\th256::Arith(h256(data, h256::AlignLeft)) &\n\t\t\t\t(~(u256(-1) >> (8 * numBytes)))\n\t\t\t));\n\t\t\treturn templ.render();\n\t\t}\n\t\telse if (_to.category() == Type::Category::Array)\n\t\t{\n\t\t\tauto const& arrayType = dynamic_cast<ArrayType const&>(_to);\n\t\t\tsolAssert(arrayType.isByteArray(), \"\");\n\t\t\tsize_t words = (data.size() + 31) / 32;\n\t\t\tsize_t storageSize = 32 + words * 32;\n\n\t\t\tWhiskers templ(R\"(\n\t\t\t\tfunction <functionName>() -> converted {\n\t\t\t\t\tconverted := <allocate>(<storageSize>)\n\t\t\t\t\tmstore(converted, <size>)\n\t\t\t\t\t<#word>\n\t\t\t\t\t\tmstore(add(converted, <offset>), <wordValue>)\n\t\t\t\t\t</word>\n\t\t\t\t}\n\t\t\t)\");\n\t\t\ttempl(\"functionName\", functionName);\n\t\t\ttempl(\"allocate\", allocationFunction());\n\t\t\ttempl(\"storageSize\", to_string(storageSize));\n\t\t\ttempl(\"size\", to_string(data.size()));\n\t\t\tvector<map<string, string>> wordParams(words);\n\t\t\tfor (size_t i = 0; i < words; ++i)\n\t\t\t{\n\t\t\t\twordParams[i][\"offset\"] = to_string(32 + i * 32);\n\t\t\t\twordParams[i][\"wordValue\"] = formatAsStringOrNumber(data.substr(32 * i, 32));\n\t\t\t}\n\t\t\ttempl(\"word\", wordParams);\n\t\t\treturn templ.render();\n\t\t}\n\t\telse\n\t\t\tsolAssert(\n\t\t\t\tfalse,\n\t\t\t\t\"Invalid conversion from string literal to \" + _to.toString() + \" requested.\"\n\t\t\t);\n\t});\n}\n\nstring YulUtilFunctions::readFromMemoryOrCalldata(Type const& _type, bool _fromCalldata)\n{\n\tstring functionName =\n\t\tstring(\"read_from_\") +\n\t\t(_fromCalldata ? \"calldata\" : \"memory\") +\n\t\t_type.identifier();\n\n\t// TODO use ABI functions for handling calldata\n\tif (_fromCalldata)\n\t\tsolAssert(!_type.isDynamicallyEncoded(), \"\");\n\n\treturn m_functionCollector.createFunction(functionName, [&] {\n\t\tif (auto refType = dynamic_cast<ReferenceType const*>(&_type))\n\t\t{\n\t\t\tsolAssert(refType->sizeOnStack() == 1, \"\");\n\t\t\tsolAssert(!_fromCalldata, \"\");\n\n\t\t\treturn Whiskers(R\"(\n\t\t\t\tfunction <functionName>(memPtr) -> value {\n\t\t\t\t\tvalue := mload(memPtr)\n\t\t\t\t}\n\t\t\t)\")\n\t\t\t(\"functionName\", functionName)\n\t\t\t.render();\n\t\t}\n\n\t\tsolAssert(_type.isValueType(), \"\");\n\n\t\tif (auto const* funType = dynamic_cast<FunctionType const*>(&_type))\n\t\t\tif (funType->kind() == FunctionType::Kind::External)\n\t\t\t\treturn Whiskers(R\"(\n\t\t\t\t\tfunction <functionName>(memPtr) -> addr, selector {\n\t\t\t\t\t\tlet combined := <load>(memPtr)\n\t\t\t\t\t\taddr, selector := <splitFunction>(combined)\n\t\t\t\t\t}\n\t\t\t\t)\")\n\t\t\t\t(\"functionName\", functionName)\n\t\t\t\t(\"load\", _fromCalldata ? \"calldataload\" : \"mload\")\n\t\t\t\t(\"splitFunction\", splitExternalFunctionIdFunction())\n\t\t\t\t.render();\n\n\t\treturn Whiskers(R\"(\n\t\t\tfunction <functionName>(memPtr) -> value {\n\t\t\t\tvalue := <load>(memPtr)\n\t\t\t\t<?needsValidation>\n\t\t\t\t\t<validate>(value)\n\t\t\t\t</needsValidation>\n\t\t\t}\n\t\t)\")\n\t\t(\"functionName\", functionName)\n\t\t(\"load\", _fromCalldata ? \"calldataload\" : \"mload\")\n\t\t(\"needsValidation\", _fromCalldata)\n\t\t(\"validate\", _fromCalldata ? validatorFunction(_type) : \"\")\n\t\t.render();\n\t});\n}\n\nstring YulUtilFunctions::revertReasonIfDebug(RevertStrings revertStrings, string const& _message)\n{\n\tif (revertStrings >= RevertStrings::Debug && !_message.empty())\n\t{\n\t\tWhiskers templ(R\"({\n\t\t\tmstore(0, <sig>)\n\t\t\tmstore(4, 0x20)\n\t\t\tmstore(add(4, 0x20), <length>)\n\t\t\tlet reasonPos := add(4, 0x40)\n\t\t\t<#word>\n\t\t\t\tmstore(add(reasonPos, <offset>), <wordValue>)\n\t\t\t</word>\n\t\t\trevert(0, add(reasonPos, <end>))\n\t\t})\");\n\t\ttempl(\"sig\", (u256(util::FixedHash<4>::Arith(util::FixedHash<4>(util::keccak256(\"Error(string)\")))) << (256 - 32)).str());\n\t\ttempl(\"length\", to_string(_message.length()));\n\n\t\tsize_t words = (_message.length() + 31) / 32;\n\t\tvector<map<string, string>> wordParams(words);\n\t\tfor (size_t i = 0; i < words; ++i)\n\t\t{\n\t\t\twordParams[i][\"offset\"] = to_string(i * 32);\n\t\t\twordParams[i][\"wordValue\"] = formatAsStringOrNumber(_message.substr(32 * i, 32));\n\t\t}\n\t\ttempl(\"word\", wordParams);\n\t\ttempl(\"end\", to_string(words * 32));\n\n\t\treturn templ.render();\n\t}\n\telse\n\t\treturn \"revert(0, 0)\";\n}\n\nstring YulUtilFunctions::revertReasonIfDebug(string const& _message)\n{\n\treturn revertReasonIfDebug(m_revertStrings, _message);\n}\n", "meta": {"hexsha": "ba664dbb641f95acf04f421d844a6c22e6f1d786", "size": 67051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libsolidity/codegen/YulUtilFunctions.cpp", "max_stars_repo_name": "MrChico/solidity", "max_stars_repo_head_hexsha": "5b4ea1eb895d5edc9a24ee5c6f96d8580eceec08", "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": "libsolidity/codegen/YulUtilFunctions.cpp", "max_issues_repo_name": "MrChico/solidity", "max_issues_repo_head_hexsha": "5b4ea1eb895d5edc9a24ee5c6f96d8580eceec08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libsolidity/codegen/YulUtilFunctions.cpp", "max_forks_repo_name": "MrChico/solidity", "max_forks_repo_head_hexsha": "5b4ea1eb895d5edc9a24ee5c6f96d8580eceec08", "max_forks_repo_licenses": ["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.4350679794, "max_line_length": 150, "alphanum_fraction": 0.6711607582, "num_tokens": 18574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.1614123600065945}}
{"text": "#include \"Controller.h\"\n#include \"Character.h\"\n#include \"MultilevelSpline.h\"\n#include <boost/filesystem.hpp>\n#include <Eigen/QR>\n#include <fstream>\n#include <numeric>\n#include <algorithm>\nnamespace DPhy\n{\t\n\nController::Controller(ReferenceManager* ref, bool adaptive, bool parametric, bool record, int id)\n\t:mControlHz(30),mSimulationHz(150),mCurrentFrame(0),\n\tw_p(0.35),w_v(0.1),w_ee(0.3),w_com(0.25),\n\tterminationReason(-1),mIsNanAtTerminal(false), mIsTerminal(false)\n{\n\tthis->mRescaleParameter = std::make_tuple(1.0, 1.0, 1.0);\n\tthis->isAdaptive = adaptive;\n\tthis->isParametric = parametric;\n\tthis->mRecord = record;\n\tthis->mReferenceManager = ref;\n\tthis->id = id;\n\tthis->mParamGoal = mReferenceManager->GetParamGoal();\n\tthis->mCurrentFrameOnPhase = 0;\n\n\tthis->mSimPerCon = mSimulationHz / mControlHz;\n\tthis->mWorld = std::make_shared<dart::simulation::World>();\n\n\tthis->mBaseGravity = Eigen::Vector3d(0,-9.81, 0);\n\tthis->mWorld->setGravity(this->mBaseGravity);\n\n\tthis->mWorld->setTimeStep(1.0/(double)mSimulationHz);\n\tthis->mWorld->getConstraintSolver()->setCollisionDetector(dart::collision::DARTCollisionDetector::create());\n\tdynamic_cast<dart::constraint::BoxedLcpConstraintSolver*>(mWorld->getConstraintSolver())->setBoxedLcpSolver(std::make_shared<dart::constraint::PgsBoxedLcpSolver>());\n\t\n\tthis->mGround = DPhy::SkeletonBuilder::BuildFromFile(std::string(CAR_DIR)+std::string(\"/character/ground.xml\")).first;\n\tthis->mGround->getBodyNode(0)->setFrictionCoeff(1.0);\n\tthis->mWorld->addSkeleton(this->mGround);\n\t\n\tstd::string path = std::string(CAR_DIR)+std::string(\"/character/\") + std::string(CHARACTER_TYPE) + std::string(\".xml\");\n\tthis->mCharacter = new DPhy::Character(path);\n\tthis->mWorld->addSkeleton(this->mCharacter->GetSkeleton());\n\n\tthis->mBaseMass = mCharacter->GetSkeleton()->getMass();\n\tthis->mMass = mBaseMass;\n\n\tEigen::VectorXd kp(this->mCharacter->GetSkeleton()->getNumDofs()), kv(this->mCharacter->GetSkeleton()->getNumDofs());\n\n\tkp.setZero();\n\tkv.setZero();\n\tthis->mCharacter->SetPDParameters(kp,kv);\n\tmContacts.clear();\n\tmContacts.push_back(\"RightToe\");\n\tmContacts.push_back(\"RightFoot\");\n\tmContacts.push_back(\"LeftToe\");\n\tmContacts.push_back(\"LeftFoot\");\n\n\tmInterestedDof = mCharacter->GetSkeleton()->getNumDofs() - 6;\n\tmRewardDof = mCharacter->GetSkeleton()->getNumDofs();\n\n\tauto collisionEngine = mWorld->getConstraintSolver()->getCollisionDetector();\n\tthis->mCGL = collisionEngine->createCollisionGroup(this->mCharacter->GetSkeleton()->getBodyNode(\"LeftFoot\"));\n\tthis->mCGR = collisionEngine->createCollisionGroup(this->mCharacter->GetSkeleton()->getBodyNode(\"RightFoot\"));\n\tthis->mCGEL = collisionEngine->createCollisionGroup(this->mCharacter->GetSkeleton()->getBodyNode(\"LeftToe\"));\n\tthis->mCGER = collisionEngine->createCollisionGroup(this->mCharacter->GetSkeleton()->getBodyNode(\"RightToe\"));\n\tthis->mCGHL = collisionEngine->createCollisionGroup(this->mCharacter->GetSkeleton()->getBodyNode(\"LeftHand\"));\n\tthis->mCGHR = collisionEngine->createCollisionGroup(this->mCharacter->GetSkeleton()->getBodyNode(\"RightHand\"));\n\tthis->mCGG = collisionEngine->createCollisionGroup(this->mGround.get());\n\n\tint num_body_nodes = mInterestedDof / 3;\n\tint dof = this->mCharacter->GetSkeleton()->getNumDofs(); \n\t\n\tmActions = Eigen::VectorXd::Zero(mInterestedDof + 1);\n\tmActions.setZero();\n\n\tmEndEffectors.clear();\n\tmEndEffectors.push_back(\"RightFoot\");\n\tmEndEffectors.push_back(\"LeftFoot\");\n\tmEndEffectors.push_back(\"LeftHand\");\n\tmEndEffectors.push_back(\"RightHand\");\n\tmEndEffectors.push_back(\"Head\");\n\n\n\tthis->mTargetPositions = Eigen::VectorXd::Zero(dof);\n\tthis->mTargetVelocities = Eigen::VectorXd::Zero(dof);\n\n\tthis->mPDTargetPositions = Eigen::VectorXd::Zero(dof);\n\tthis->mPDTargetVelocities = Eigen::VectorXd::Zero(dof);\n\n\t//temp\n\tthis->mRewardParts.resize(7, 0.0);\n\tmParamCur.resize(mReferenceManager->GetParamGoal().rows());\n\tthis->mNumState = this->GetState().rows();\n\n\tthis->mNumAction = mActions.size();\n\n\tClearRecord();\n\t\n\tmRewardLabels.clear();\n\tif(isAdaptive) {\n\t\tmRewardLabels.push_back(\"total_d\");\n\t\tmRewardLabels.push_back(\"total_s\");\n\t\tmRewardLabels.push_back(\"tracking\");\n\t\tmRewardLabels.push_back(\"time\");\n\t\tmRewardLabels.push_back(\"similarity\");\n\t} else {\n\t\tmRewardLabels.push_back(\"total\");\n\t\tmRewardLabels.push_back(\"p\");\n\t\tmRewardLabels.push_back(\"com\");\n\t\tmRewardLabels.push_back(\"ee\");\n\t\tmRewardLabels.push_back(\"v\");\n\t\tmRewardLabels.push_back(\"time\");\n\t}\n\n}\nconst dart::dynamics::SkeletonPtr& \nController::GetSkeleton() { \n\treturn this->mCharacter->GetSkeleton(); \n}\nvoid \nController::\nStep()\n{\t\t\t\n\tif(IsTerminalState())\n\t\treturn;\n\n\tEigen::VectorXd s = this->GetState();\n\n\tEigen::VectorXd a = mActions;\n\n\t// set action target pos\n\tint num_body_nodes = mInterestedDof / 3;\n\tint dof = this->mCharacter->GetSkeleton()->getNumDofs(); \n\n\tfor(int i = 0; i < mInterestedDof; i++){\n\t\tmActions[i] = dart::math::clip(mActions[i]*0.2, -0.7*M_PI, 0.7*M_PI);\n\t}\n\tint sign = 1;\n\tif(mActions[mInterestedDof] < 0)\n\t\tsign = -1;\n\n\tmActions[mInterestedDof] = dart::math::clip(mActions[mInterestedDof]*1.5, -3.0, 1.0);\n\tmActions[mInterestedDof] = exp(mActions[mInterestedDof]);\n\tmAdaptiveStep = mActions[mInterestedDof];\n\t// /////BASELINE\n\t// mAdaptiveStep = 1;\n\t// if(!isAdaptive)\n\t// \tmAdaptiveStep = 1;\n\n\tmPrevFrameOnPhase = this->mCurrentFrameOnPhase;\n\tthis->mCurrentFrame += mAdaptiveStep;\n\tthis->mCurrentFrameOnPhase += mAdaptiveStep;\n\tnTotalSteps += 1;\n\tint n_bnodes = mCharacter->GetSkeleton()->getNumBodyNodes();\n\t// if(mRecord)\n\t// \tstd::cout << mCurrentFrameOnPhase << \" \"<< mAdaptiveStep << \" \"<< mReferenceManager->GetTimeStep(mPrevFrameOnPhase, true) << std::endl;\n\t\n\tMotion* p_v_target = mReferenceManager->GetMotion(mCurrentFrame, isAdaptive);\n\tthis->mTargetPositions = p_v_target->GetPosition();\n\tthis->mTargetVelocities = mCharacter->GetSkeleton()->getPositionDifferences(mTargetPositions, mPrevTargetPositions) / 0.033 * (mCurrentFrame - mPrevFrame);\n\tdelete p_v_target;\n\n\tp_v_target = mReferenceManager->GetMotion(mCurrentFrame, false);\n\tthis->mPDTargetPositions = p_v_target->GetPosition();\n\tthis->mPDTargetVelocities = p_v_target->GetVelocity();\n\tdelete p_v_target;\n\n\tint count_dof = 0;\n\n\tfor(int i = 1; i <= num_body_nodes; i++){\n\t\tint idx = mCharacter->GetSkeleton()->getBodyNode(i)->getParentJoint()->getIndexInSkeleton(0);\n\t\tint dof = mCharacter->GetSkeleton()->getBodyNode(i)->getParentJoint()->getNumDofs();\n\t\tmPDTargetPositions.block(idx, 0, dof, 1) += mActions.block(count_dof, 0, dof, 1);\n\t\tcount_dof += dof;\n\n\t}\n\n\tmSumTorque.resize(dof);\n\tmSumTorque.setZero();\n\tEigen::VectorXd torque;\n\tEigen::Vector3d d = Eigen::Vector3d(0, 0, 1);\n\tdouble end_f_sum = 0;\t\n\t\n\tfor(int i = 0; i < this->mSimPerCon; i += 2){\n\n\t\tfor(int j = 0; j < 2; j++) {\n\t\t\tmCharacter->GetSkeleton()->setSPDTarget(mPDTargetPositions, 600, 49);\n\t\t\t//Eigen::VectorXd torque = mCharacter->GetSkeleton()->getSPDForces(mPDTargetPositions, 600, 49, mWorld->getConstraintSolver());\n\t\t\t// for(int j = 0; j < num_body_nodes; j++) {\n\t\t\t// \tint idx = mCharacter->GetSkeleton()->getBodyNode(j)->getParentJoint()->getIndexInSkeleton(0);\n\t\t\t// \tint dof = mCharacter->GetSkeleton()->getBodyNode(j)->getParentJoint()->getNumDofs();\n\t\t\t// \tstd::string name = mCharacter->GetSkeleton()->getBodyNode(j)->getName();\n\t\t\t// \tdouble torquelim = mCharacter->GetTorqueLimit(name) * 1.5;\n\t\t\t// \tdouble torque_norm = torque.block(idx, 0, dof, 1).norm();\n\t\t\t\n\t\t\t// \ttorque.block(idx, 0, dof, 1) = std::max(-torquelim, std::min(torquelim, torque_norm)) * torque.block(idx, 0, dof, 1).normalized();\n\t\t\t// }\n\n\t\t\t//mCharacter->GetSkeleton()->setForces(torque);\n\t\t\tmWorld->step(false);\n\t\t\t//mSumTorque += torque.cwiseAbs();\n\n\t\t}\n\t\tif(mCurrentFrameOnPhase >= 18 && mControlFlag[0] == 0) {\n\t\t\tEigen::Vector3d c_vel = mCharacter->GetSkeleton()->getCOMLinearVelocity();\n\t\t\tdouble rf = mCharacter->GetSkeleton()->getBodyNode(\"LeftFoot\")->getWorldTransform().translation()(1);\n\t\t\tdouble lf = mCharacter->GetSkeleton()->getBodyNode(\"RightFoot\")->getWorldTransform().translation()(1);\n\t\t\tif(mVelocity < c_vel(1)) {\n\t\t\t\tmVelocity = c_vel(1);\n\t\t\t\tmMomentum = mCharacter->GetSkeleton()->getMass() * c_vel;\n\t\t\t}\n\t\t}\n\t\tmTimeElapsed += 2 * mAdaptiveStep;\n\t}\n\tif(this->mCurrentFrameOnPhase > mReferenceManager->GetPhaseLength()){\n\t\tthis->mCurrentFrameOnPhase -= mReferenceManager->GetPhaseLength();\n\t\tmRootZero = mCharacter->GetSkeleton()->getPositions().segment<6>(0);\n\n\t\tif(isAdaptive) {\n\t\t\tmTrackingRewardTrajectory /= mCountTracking;\n\t\t\tmFitness.sum_pos /= mCountTracking;\n\t\t\tmFitness.sum_vel /= mCountTracking;\n\t\t\tmFitness.sum_pos_threshold /= mCountTracking;\n\t\t\tmFitness.sum_vel_threshold /= mCountTracking;\n\t\t\tmFitness.sum_slide /= mCountSlide;\n\n\t\t\tmReferenceManager->SaveTrajectories(data_raw, std::tuple<double, double, Fitness>(mTrackingRewardTrajectory, mParamRewardTrajectory, mFitness), mParamCur);\n\t\t\tdata_raw.clear();\n\n\t\t\tmFitness.sum_contact = 0;\n\t\t\tmFitness.sum_pos = 0;\n\t\t\tmFitness.sum_vel = 0;\n\t\t\tmFitness.sum_pos_threshold = 0;\n\t\t\tmFitness.sum_vel_threshold = 0;\n\t\t\tmFitness.sum_slide = 0;\n\t\t\tmFitness.sum_reward = 0;\n\n\t\t\tmTrackingRewardTrajectory = 0;\n\t\t\tmParamRewardTrajectory = 0;\n\t\t\t\n\t\t\tmControlFlag.setZero();\n\t\t\tmCountParam = 0;\n\t\t\tmCountTracking = 0;\n\t\t\tmCondiff = 0;\n\t\t\tmCountContact = 0;\n\t\t\tmCountSlide = 0;\n\n\t\t\tmVelocity = 0;\n\t\t\tmMomentum.setZero();\n\t\t\tmMaxCOM.setZero();\t\t\n\t\t\tmPrevHeight = 0;\n\n\t\t\t////BASELINE\n\t\t\tmParamRewardMax = 0;\n\t\t}\n\t}\n\tif(isAdaptive) {\n\t\tthis->UpdateAdaptiveReward();\n\t}\n\telse\n\t\tthis->UpdateReward();\n\n\tthis->UpdateTerminalInfo();\n\n\tif(mRecord) {\n\t\tSaveStepInfo();\n\t}\n\n\tif(isAdaptive)\n\t{\n\t\tdata_raw.push_back(std::pair<Eigen::VectorXd,double>(mCharacter->GetSkeleton()->getPositions(), mCurrentFrameOnPhase));\n\t}\n\n\tmPrevTargetPositions = mTargetPositions;\n\tmPrevFrame = mCurrentFrame;\n\n\tif(mPosQueue.size() >= 3)\n\t\tmPosQueue.pop();\n\tif(mTimeQueue.size() >= 3)\n\t\tmTimeQueue.pop();\n\tmPosQueue.push(mCharacter->GetSkeleton()->getPositions());\n\tmTimeQueue.push(mCurrentFrame);\n\n\n\tif(isAdaptive && mIsTerminal)\n\t\tdata_raw.clear();\n\n}\nvoid\nController::\nSaveStepInfo() \n{\n\tmRecordBVHPosition.push_back(mReferenceManager->GetPosition(mCurrentFrame, false));\n\tmRecordTargetPosition.push_back(mTargetPositions);\n\tmRecordPosition.push_back(mCharacter->GetSkeleton()->getPositions());\n\tmRecordVelocity.push_back(mCharacter->GetSkeleton()->getVelocities());\n\tmRecordCOM.push_back(mCharacter->GetSkeleton()->getCOM());\n\tmRecordPhase.push_back(mCurrentFrame);\n\n\tbool rightContact = CheckCollisionWithGround(\"RightFoot\") || CheckCollisionWithGround(\"RightToe\");\n\tbool leftContact = CheckCollisionWithGround(\"LeftFoot\") || CheckCollisionWithGround(\"LeftToe\");\n\n\tmRecordFootContact.push_back(std::make_pair(rightContact, leftContact));\n}\nvoid \nController::\nClearRecord() \n{\n\tthis->mRecordVelocity.clear();\n\tthis->mRecordPosition.clear();\n\tthis->mRecordCOM.clear();\n\tthis->mRecordTargetPosition.clear();\n\tthis->mRecordBVHPosition.clear();\n\tthis->mRecordObjPosition.clear();\n\tthis->mRecordPhase.clear();\n\tthis->mRecordFootContact.clear();\n\n\tthis->mControlFlag.resize(4);\n\tthis->mControlFlag.setZero();\n\n\tmCountParam = 0;\n\tmCountTracking = 0;\n\n\twhile(!mPosQueue.empty())\n\t\tmPosQueue.pop();\n\twhile(!mTimeQueue.empty())\n\t\tmTimeQueue.pop();\n\n\tdata_raw.clear();\n\tmVelocity = 0;\n\tmMomentum.setZero();\n\tmMaxCOM.setZero();\n\tmCondiff = 0;\n\tmCountContact = 0;\n\n\t////BASELINE\n\tmParamRewardMax = 0;\n\tmPrevHeight = 0;\n}\n\nstd::vector<double> \nController::\nGetTrackingReward(Eigen::VectorXd position, Eigen::VectorXd position2, \n\tEigen::VectorXd velocity, Eigen::VectorXd velocity2, std::vector<std::string> list, bool useVelocity)\n{\n\tauto& skel = this->mCharacter->GetSkeleton();\n\tint dof = skel->getNumDofs();\n\tint num_body_nodes = skel->getNumBodyNodes();\n\n\tEigen::VectorXd p_save = skel->getPositions();\n\tEigen::VectorXd v_save = skel->getVelocities();\n\n\tEigen::VectorXd p_diff = skel->getPositionDifferences(position, position2);\n\tEigen::VectorXd p_diff_reward;\n\t\n\tp_diff_reward = p_diff;\n\t//OURS\n\t// if(isAdaptive) {\n\t// \tp_diff_reward.segment<6>(0) *= 3;\n\n\t// }\n\tEigen::VectorXd v_diff, v_diff_reward;\n\n\tif(useVelocity) {\n\t\tv_diff = skel->getVelocityDifferences(velocity, velocity2);\n\t\tv_diff_reward = v_diff;\n\t}\n\n\tskel->setPositions(position);\n\tskel->computeForwardKinematics(true,false,false);\n\n\tstd::vector<Eigen::Isometry3d> ee_transforms;\n\tEigen::VectorXd ee_diff(mEndEffectors.size()*3);\n\tee_diff.setZero();\t\n\tfor(int i=0;i<mEndEffectors.size(); i++){\n\t\tee_transforms.push_back(skel->getBodyNode(mEndEffectors[i])->getWorldTransform());\n\t}\n\t\n\tEigen::Vector3d com_diff = skel->getCOM();\n\t\n\tskel->setPositions(position2);\n\tskel->computeForwardKinematics(true,false,false);\n\n\tfor(int i=0;i<mEndEffectors.size();i++){\n\t\tEigen::Isometry3d diff = ee_transforms[i].inverse() * skel->getBodyNode(mEndEffectors[i])->getWorldTransform();\n\t\tee_diff.segment<3>(3*i) = diff.translation();\n\t}\n\tcom_diff -= skel->getCOM();\n\n\n\tdouble scale = 1.0;\n\n\tdouble sig_p = 0.4 * scale; \n\tdouble sig_v = 3 * scale;\t\n\tdouble sig_com = 0.2 * scale;\t\t\n\tdouble sig_ee = 0.2 * scale;\t\t\n\n\tdouble r_p = exp_of_squared(p_diff_reward,sig_p);\n\tdouble r_v;\n\tif(useVelocity)\n\t{\n\t\tr_v = exp_of_squared(v_diff_reward,sig_v);\n\t}\n\tdouble r_ee = exp_of_squared(ee_diff,sig_ee);\n\tdouble r_com = exp_of_squared(com_diff,sig_com);\n\n\tstd::vector<double> rewards;\n\trewards.clear();\n\n\trewards.push_back(r_p);\n\trewards.push_back(r_com);\n\trewards.push_back(r_ee);\n\n\tif(useVelocity) {\n\t\trewards.push_back(r_v);\n\t}\n\n\tskel->setPositions(p_save);\n\tskel->setVelocities(v_save);\n\tskel->computeForwardKinematics(true,true,false);\n\n\treturn rewards;\n\n}\nstd::vector<std::pair<bool, Eigen::Vector3d>> \nController::\nGetContactInfo(Eigen::VectorXd pos) \n{\n\tauto& skel = this->mCharacter->GetSkeleton();\n\tEigen::VectorXd p_save = skel->getPositions();\n\tEigen::VectorXd v_save = skel->getVelocities();\n\t\n\tskel->setPositions(pos);\n\tskel->computeForwardKinematics(true,false,false);\n\n\tstd::vector<std::string> contact;\n\tcontact.push_back(\"RightFoot\");\n\tcontact.push_back(\"RightToe\");\n\tcontact.push_back(\"LeftFoot\");\n\tcontact.push_back(\"LeftToe\");\n\n\tstd::vector<std::pair<bool, Eigen::Vector3d>> result;\n\tresult.clear();\n\tfor(int i = 0; i < contact.size(); i++) {\n\t\tEigen::Vector3d p = skel->getBodyNode(contact[i])->getWorldTransform().translation();\n\t\tif(p[1] < 0.07) {\n\t\t\tresult.push_back(std::pair<bool, Eigen::Vector3d>(true, p));\n\t\t} else {\n\t\t\tresult.push_back(std::pair<bool, Eigen::Vector3d>(false, p));\n\t\t}\n\t}\n\n\tskel->setPositions(p_save);\n\tskel->setVelocities(v_save);\n\tskel->computeForwardKinematics(true,true,false);\n\n\treturn result;\n}\ndouble\nController::\nGetSimilarityReward()\n{\n\n\tauto& skel = this->mCharacter->GetSkeleton();\n\tEigen::VectorXd p_save = skel->getPositions();\n\tEigen::VectorXd v_save = skel->getVelocities();\n\n\tauto p_v_target = mReferenceManager->GetMotion(mCurrentFrameOnPhase, false);\n\tEigen::VectorXd pos = p_v_target->GetPosition();\n\tEigen::VectorXd vel = p_v_target->GetVelocity();\n\tdelete p_v_target;\n\n\tstd::vector<std::pair<bool, Eigen::Vector3d>> contacts_ref = GetContactInfo(pos);\n\tstd::vector<std::pair<bool, Eigen::Vector3d>> contacts_cur = GetContactInfo(skel->getPositions());\n\n\tdouble con_diff = 0;\n\n\tfor(int i = 0; i < contacts_cur.size(); i++) {\n\t\tif(contacts_ref[i].first && !contacts_cur[i].first) {\n\t\t\tcon_diff += abs(std::max(0.0, (contacts_cur[i].second)(1) - 0.07));\n\t\t} else if(!contacts_ref[i].first && contacts_cur[i].first) {\n\t\t\tcon_diff += abs(std::max(0.0, (contacts_ref[i].second)(1) - 0.07));\n\t\t}\n\t}\n\n\t//double r_con = exp(-con_diff);\n\tEigen::VectorXd p_aligned = skel->getPositions();\n\tstd::vector<Eigen::VectorXd> p_with_zero;\n\tp_with_zero.push_back(mRootZero);\n\tp_with_zero.push_back(p_aligned.segment<6>(0));\n\tp_with_zero = Align(p_with_zero, mReferenceManager->GetPosition(0, false));\n\tp_aligned.segment<6>(0) = p_with_zero[1];\n\n\tEigen::VectorXd v = skel->getPositionDifferences(skel->getPositions(), mPosQueue.front()) / (mCurrentFrame - mTimeQueue.front() + 1e-10) / 0.033;\n\n\tfor(auto& jn : skel->getJoints()){\n\t\tif(dynamic_cast<dart::dynamics::RevoluteJoint*>(jn)!=nullptr){\n\t\t\tdouble v_ = v[jn->getIndexInSkeleton(0)];\n\t\t\tif(v_ > M_PI){\n\t\t\t\tv_ -= 2*M_PI;\n\t\t\t}\n\t\t\telse if(v_ < -M_PI){\n\t\t\t\tv_ += 2*M_PI;\n\t\t\t}\n\t\t\tv[jn->getIndexInSkeleton(0)] = v_;\n\t\t}\n\t}\n\n\tEigen::VectorXd p_diff = skel->getPositionDifferences(pos, p_aligned);\n\tEigen::VectorXd p_diff_th = p_diff;\n\n\tEigen::VectorXd v_diff = skel->getVelocityDifferences(vel, v);\n\n\tint num_body_nodes = skel->getNumBodyNodes();\n\tfor(int i =0 ; i < vel.rows(); i++) {\n\t\tv_diff(i) = v_diff(i) / std::max(0.5, vel(i));\n\t}\n\tEigen::VectorXd v_diff_th = v_diff;\n\n\tfor(int i = 0; i < num_body_nodes; i++) {\n\t\tstd::string name = mCharacter->GetSkeleton()->getBodyNode(i)->getName();\n\t\tint idx = mCharacter->GetSkeleton()->getBodyNode(i)->getParentJoint()->getIndexInSkeleton(0);\n\n\t\tif(name.compare(\"Hips\") == 0 ) {\n\t\t\tp_diff.segment<3>(idx) *= 3;\n\t\t\tp_diff.segment<3>(idx + 3) *= 5;\n\n\t\t\tp_diff_th.segment<3>(idx) *= 3;\n\t\t\tp_diff_th.segment<3>(idx + 3) *= 5;\n\n\t\t\tv_diff.segment<3>(idx + 3) *= 5;\n\t\t\tv_diff_th.segment<3>(idx + 3) *= 5;\n\t\t}\n\t}\n\n\tdouble footSlide = 0;\n\tif(mCurrentFrameOnPhase >= 41){\n\t\tEigen::Vector3d lf = skel->getBodyNode(\"LeftFoot\")->getWorldTransform().translation();\n\t\tlf += skel->getBodyNode(\"LeftToe\")->getWorldTransform().translation();\n\t\tlf /= 2.0;\n\n\t\tEigen::Vector3d rf = skel->getBodyNode(\"RightFoot\")->getWorldTransform().translation();\n\t\trf += skel->getBodyNode(\"RightToe\")->getWorldTransform().translation();\n\t\trf /= 2.0;\n\t\t\n\t\tEigen::VectorXd foot_diff (6);\n\t\tfoot_diff << (lf-stickLeftFoot), (rf- stickRightFoot);\n\t\tfoot_diff(1) = 0;\n\t\tfoot_diff(4) = 0;\n\n\t\tfootSlide += foot_diff.segment<3>(0).norm() + foot_diff.segment<3>(3).norm();\n\t\tmCountSlide += 1;\n\t\n\t} else if(mCurrentFrameOnPhase >= 35) {\n\t\tEigen::Vector3d lf = skel->getBodyNode(\"LeftFoot\")->getWorldTransform().translation();\n\t\tlf += skel->getBodyNode(\"LeftToe\")->getWorldTransform().translation();\n\t\tlf /= 2.0;\n\n\t\tEigen::Vector3d rf = skel->getBodyNode(\"RightFoot\")->getWorldTransform().translation();\n\t\trf += skel->getBodyNode(\"RightToe\")->getWorldTransform().translation();\n\t\trf /= 2.0;\n\n\t\tstickRightFoot = rf;\n\t\tstickLeftFoot = lf;\n\t}\n\n\n\tdouble r_con = exp(-con_diff);\n\tdouble r_ee = exp_of_squared(v_diff, 3);\n\tdouble r_p = exp_of_squared(p_diff, 0.3);\n\n\tmPrevFrame = mCurrentFrame;\n\n\tmFitness.sum_contact += con_diff;\n\tmFitness.sum_pos += p_diff.dot(p_diff) / p_diff.rows();\n\tmFitness.sum_vel += v_diff.dot(v_diff) / v_diff.rows();\n\n\tmFitness.sum_pos_threshold += p_diff_th.dot(p_diff_th) / p_diff_th.rows();\n\tmFitness.sum_vel_threshold += v_diff_th.dot(v_diff_th) / v_diff_th.rows();\n\n\tmFitness.sum_slide += footSlide;\n\treturn exp(-r_con)  * r_p * r_ee;\n}\ndouble \nController::\nGetParamReward()\n{\n\tdouble r_param = 0;\n\tauto& skel = this->mCharacter->GetSkeleton();\n\tif(mCurrentFrameOnPhase >= 26 && mControlFlag[0] == 0) {\n\t\tEigen::Vector3d momentumGoal = Eigen::Vector3d(0, 165, 0);\n\t\tEigen::Vector3d m_diff = momentumGoal - mMomentum;\n\t\tm_diff *= 0.1;\n\t\tm_diff(1) *= 4;\n\n\t\tdouble r_m = exp_of_squared(m_diff, 1.5); \n\t\tif(r_m < 0.4) {\n\t\t\tmParamCur(0) = -5;\n\t\t} else {\n\t\t\tmParamCur(0) = mParamGoal(0);\n\t\t}\n\t\tmFitness.sum_reward = (0.5 + 0.5 * r_m);\n\t\tr_param = 0.6 * r_m;\n\n\t\tmControlFlag[0] = 1;\n\t\tif(mRecord) {\n\t\t\tstd::cout << \"momentum: \" << mMomentum.transpose() << \" / \" << m_diff.transpose() << \" / \" << r_m << std::endl;\n\t\t}\n\t} if(mCurrentFrameOnPhase >= 30 && mControlFlag[0] == 1) {\n\t\tstd::vector<std::pair<bool, Eigen::Vector3d>> contacts_ref = GetContactInfo(mReferenceManager->GetPosition(mCurrentFrameOnPhase, false));\n\t\tstd::vector<std::pair<bool, Eigen::Vector3d>> contacts_cur = GetContactInfo(skel->getPositions());\n\n\t\tfor(int i = 0; i < contacts_cur.size(); i++) {\n\t\t\tif(contacts_ref[i].first && !contacts_cur[i].first) {\n\t\t\t\tmCondiff += pow(std::max(0.0, (contacts_cur[i].second)(1) - 0.07), 2);\n\t\t\t} else if(!contacts_ref[i].first && contacts_cur[i].first) {\n\t\t\t\tmCondiff += pow(std::max(0.0, (contacts_ref[i].second)(1) - 0.07), 2);\n\t\t\t}\n\t\t}\n\t\tmCountContact += 1;\n\n\t\tif(mCurrentFrameOnPhase >= 44) {\n\n\t\t\t// // /////BASELINE\n\t\t\t// // Eigen::Vector3d momentumGoal = Eigen::Vector3d(0, 165, 0);\n\t\t\t// // Eigen::Vector3d m_diff = momentumGoal - mMomentum;\n\t\t\t// // m_diff *= 0.1;\n\t\t\t// // m_diff(1) *= 4;\n\n\t\t\t// // double r_m = exp_of_squared(m_diff, 1.5); \n\t\t\t// // if(r_m < 0.4) {\n\t\t\t// // \tmParamCur(0) = -5;\n\t\t\t// // } else {\n\t\t\t// // \tmParamCur(0) = mParamGoal(0);\n\t\t\t// // }\n\t\t\t// // r_param = r_m;\n\t\t\t// // mParamRewardMax = r_param;\n\n\t\t\tdouble r_c = exp(-mCondiff * 7.5);\n\t\t\tif(r_c < 0.5) {\n\t\t\t\tmParamCur(0) = -5;\n\t\t\t} \n\t\t\t// else {\n\t\t\t// \tmParamCur(0) = mParamGoal(0);\n\t\t\t// }\n\t\t\tr_param = 0.6 * r_c;\n\t\t\tmFitness.sum_reward *= r_c;\n\n\t\t\tmControlFlag[0] = 2;\n\n\t\t\tif(mRecord) {\n\t\t\t\tstd::cout << \"contact: \" << mCondiff << \" / \" << r_c << std::endl;\n\t\t\t\tstd::cout << \"final parameter: \" <<  mParamCur.transpose() << std::endl;\n\t\t\t}\n\t\t}\n\t} \n\treturn r_param;\n\t\n}\nvoid\nController::\nUpdateAdaptiveReward()\n{\n\n\tauto& skel = this->mCharacter->GetSkeleton();\n\t\n\tstd::vector<double> tracking_rewards_bvh = this->GetTrackingReward(skel->getPositions(), mTargetPositions,\n\t\t\t\t\t\t\t\t skel->getVelocities(), mTargetVelocities, mRewardBodies, true);\n\tdouble accum_bvh = std::accumulate(tracking_rewards_bvh.begin(), tracking_rewards_bvh.end(), 0.0) / tracking_rewards_bvh.size();\t\n\tdouble time_diff = mAdaptiveStep  - mReferenceManager->GetTimeStep(mPrevFrameOnPhase, true);\n\tdouble r_time = exp(-pow(time_diff, 2)*75);\n\n\tdouble r_tracking = 0.85 * accum_bvh + 0.15 * r_time;\n\n\tdouble r_similarity = this->GetSimilarityReward();\n\tdouble r_param = this->GetParamReward();\n\n\tdouble r_tot = r_tracking;\n\n\tmRewardParts.clear();\n\n\tif(dart::math::isNan(r_tot)){\n\t\tmRewardParts.resize(mRewardLabels.size(), 0.0);\n\t}\n\telse {\n\t\tmRewardParts.push_back(r_tot);\n\t\tmRewardParts.push_back(20 * r_param);\n\t\tmRewardParts.push_back(accum_bvh);\n\t\tmRewardParts.push_back(r_time);\n\t\tmRewardParts.push_back(r_similarity);\n\t}\n\tif(r_param != 0) {\n\t\tif(mParamRewardTrajectory == 0) {\n\t\t\tmParamRewardTrajectory = r_param;\n\t\t}\n\t\telse {\n\t\t\tmParamRewardTrajectory *= r_param;\n\t\t}\n\t}\n\tmTrackingRewardTrajectory += accum_bvh;\n\tmCountTracking += 1;\n}\nvoid\nController::\nUpdateReward()\n{\n\tauto& skel = this->mCharacter->GetSkeleton();\n\tstd::vector<double> tracking_rewards_bvh = this->GetTrackingReward(skel->getPositions(), mTargetPositions,\n\t\t\t\t\t\t\t\t skel->getVelocities(), mTargetVelocities, mRewardBodies, true);\n\tdouble accum_bvh = std::accumulate(tracking_rewards_bvh.begin(), tracking_rewards_bvh.end(), 0.0) / tracking_rewards_bvh.size();\n\n\tdouble r_time = exp(-pow((mActions[mInterestedDof] - 1),2)*40);\n\n\tmSumTorque /= mSimPerCon;\n\tdouble r_torque = exp_of_squared(mSumTorque, 50);\n\n\tmRewardParts.clear();\n\tdouble r_tot = 0.9 * (0.5 * tracking_rewards_bvh[0] + 0.1 * tracking_rewards_bvh[1] + 0.3 * tracking_rewards_bvh[2] + 0.1 * tracking_rewards_bvh[3] ) + 0.1 * r_time;\n\t// r_tot = 0.99 * r_tot + 0.01 * r_torque;\n\tif(dart::math::isNan(r_tot)){\n\t\tmRewardParts.resize(mRewardLabels.size(), 0.0);\n\t}\n\telse {\n\t\tmRewardParts.push_back(r_tot);\n\t\tmRewardParts.push_back(tracking_rewards_bvh[0]);\n\t\tmRewardParts.push_back(tracking_rewards_bvh[1]);\n\t\tmRewardParts.push_back(tracking_rewards_bvh[2]);\n\t\tmRewardParts.push_back(tracking_rewards_bvh[3]);\n\t\tmRewardParts.push_back(r_torque);\n\t}\n}\nvoid\nController::\nUpdateTerminalInfo()\n{\t\n\tEigen::VectorXd p_ideal = mTargetPositions;\n\tauto& skel = this->mCharacter->GetSkeleton();\n\n\tEigen::VectorXd p = skel->getPositions();\n\tEigen::VectorXd v = skel->getVelocities();\n\tEigen::Vector3d root_pos = skel->getPositions().segment<3>(3);\n\tEigen::Isometry3d cur_root_inv = skel->getRootBodyNode()->getWorldTransform().inverse();\n\tdouble root_y = skel->getBodyNode(0)->getTransform().translation()[1];\n\n\tEigen::VectorXd p_save = skel->getPositions();\n\tEigen::VectorXd v_save = skel->getVelocities();\n\n\tskel->setPositions(mTargetPositions);\n\tskel->computeForwardKinematics(true,false,false);\n\n\tEigen::Isometry3d root_diff = cur_root_inv * skel->getRootBodyNode()->getWorldTransform();\n\t\n\tEigen::AngleAxisd root_diff_aa(root_diff.linear());\n\tdouble angle = RadianClamp(root_diff_aa.angle());\n\tEigen::Vector3d root_pos_diff = root_diff.translation();\n\n\n\t// check nan\n\tif(dart::math::isNan(p)){\n\t\tmIsNanAtTerminal = true;\n\t\tmIsTerminal = true;\n\t\tterminationReason = 3;\n\t} else if(dart::math::isNan(v)){\n\t\tmIsNanAtTerminal = true;\n\t\tmIsTerminal = true;\n\t\tterminationReason = 4;\n\t}\n\t//characterConfigration\n\telse if(!mRecord && root_pos_diff.norm() > TERMINAL_ROOT_DIFF_THRESHOLD){\n\t\tmIsTerminal = true;\n\t\tterminationReason = 2;\n\t} else if(!mRecord && root_y<TERMINAL_ROOT_HEIGHT_LOWER_LIMIT || root_y > TERMINAL_ROOT_HEIGHT_UPPER_LIMIT){\n\t\tmIsTerminal = true;\n\t\tterminationReason = 1;\n\t} else if(!mRecord && std::abs(angle) > TERMINAL_ROOT_DIFF_ANGLE_THRESHOLD){\n\t\tmIsTerminal = true;\n\t\tterminationReason = 5;\n\t} else if(isAdaptive && mCurrentFrame > mReferenceManager->GetPhaseLength()* 3 + 10) { // this->mBVH->GetMaxFrame() - 1.0){\n\t\tmIsTerminal = true;\n\t\tterminationReason =  8;\n\t} else if(!isAdaptive && mCurrentFrame > mReferenceManager->GetPhaseLength()* 5 + 10) { // this->mBVH->GetMaxFrame() - 1.0){\n\t\tmIsTerminal = true;\n\t\tterminationReason =  8;\n\t}\n\tif(mRecord) {\n\t\tif(mIsTerminal) std::cout << terminationReason << std::endl;\n\t}\n\n\tskel->setPositions(p_save);\n\tskel->setVelocities(v_save);\n\tskel->computeForwardKinematics(true,true,false);\n\n}\nbool\nController::\nFollowBvh()\n{\t\n\tif(IsTerminalState())\n\t\treturn false;\n\tauto& skel = mCharacter->GetSkeleton();\n\n\tMotion* p_v_target = mReferenceManager->GetMotion(mCurrentFrame);\n\tmTargetPositions = p_v_target->GetPosition();\n\tmTargetVelocities = p_v_target->GetVelocity();\n\tdelete p_v_target;\n\n\tfor(int i=0;i<this->mSimPerCon;i++)\n\t{\n\t\tskel->setPositions(mTargetPositions);\n\t\tskel->setVelocities(mTargetVelocities);\n\t\tskel->computeForwardKinematics(true, true, false);\n\t}\n\tthis->mCurrentFrame += 1;\n\tthis->nTotalSteps += 1;\n\treturn true;\n}\nvoid \nController::\nSetGoalParameters(Eigen::VectorXd tp)\n{\n\tmParamGoal = tp;\n\tthis->mWorld->setGravity(exp(mParamGoal(0))*mBaseGravity);\n\t// this->SetSkeletonWeight(mParamGoal(1)*mBaseMass);\n}\n\nvoid\nController::\nSetSkeletonWeight(double mass)\n{\n\n\tdouble m_new = mass / mMass;\n\n\tstd::vector<std::tuple<std::string, Eigen::Vector3d, double>> deform;\n\tint n_bnodes = mCharacter->GetSkeleton()->getNumBodyNodes();\n\n\tfor(int i = 0; i < n_bnodes; i++){\n\t\tstd::string name = mCharacter->GetSkeleton()->getBodyNode(i)->getName();\n\t\tdeform.push_back(std::make_tuple(name, Eigen::Vector3d(1, 1, 1), m_new));\n\t}\n\tDPhy::SkeletonBuilder::DeformSkeleton(mCharacter->GetSkeleton(), deform);\n\tmMass = mCharacter->GetSkeleton()->getMass();\n}\nvoid \nController::\nReset(bool RSI)\n{\n\tthis->mWorld->reset();\n\tauto& skel = mCharacter->GetSkeleton();\n\tskel->clearConstraintImpulses();\n\tskel->clearInternalForces();\n\tskel->clearExternalForces();\n\n\t//RSI\n\tif(RSI && !isAdaptive) {\n\t\tthis->mCurrentFrame = (int) dart::math::Random::uniform(0.0, mReferenceManager->GetPhaseLength()-5.0);\n\t}\n\telse {\n\t\tthis->mCurrentFrame = 0; // 0;\n\t\tthis->mParamRewardTrajectory = 0;\n\t\tthis->mTrackingRewardTrajectory = 0;\n\n\t\tmFitness.sum_contact = 0;\n\t\tmFitness.sum_pos = 0;\n\t\tmFitness.sum_vel = 0;\n\t\tmFitness.sum_pos_threshold = 0;\n\t\tmFitness.sum_pos_threshold = 0;\n\t\tmFitness.sum_reward = 0;\n\n\t}\n\n\tthis->mCurrentFrameOnPhase = this->mCurrentFrame;\n\tthis->mStartFrame = this->mCurrentFrame;\n\tthis->nTotalSteps = 0;\n\tthis->mTimeElapsed = 0;\n\n\tMotion* p_v_target;\n\tp_v_target = mReferenceManager->GetMotion(mCurrentFrame, isAdaptive);\n\tthis->mTargetPositions = p_v_target->GetPosition();\n\tthis->mTargetVelocities = p_v_target->GetVelocity();\n\tdelete p_v_target;\n\n\tthis->mPDTargetPositions = mTargetPositions;\n\tthis->mPDTargetVelocities = mTargetVelocities;\n\tint num_body_nodes = skel->getNumBodyNodes();\n\n\tskel->setPositions(mTargetPositions);\n\tskel->setVelocities(mTargetVelocities);\n\tskel->computeForwardKinematics(true,true,false);\n\n\tthis->mIsNanAtTerminal = false;\n\tthis->mIsTerminal = false;\n\t\n\tClearRecord();\n\tSaveStepInfo();\n\n\tmRootZero = mCharacter->GetSkeleton()->getPositions().segment<6>(0);\n\t\n\tmPrevPositions = mCharacter->GetSkeleton()->getPositions();\n\tmPrevTargetPositions = mTargetPositions;\n\t\n\tmPrevFrame = mCurrentFrame;\n\tmPrevFrame2 = mPrevFrame;\n\t\n\tmPosQueue.push(mCharacter->GetSkeleton()->getPositions());\n\tmTimeQueue.push(0);\n\tmAdaptiveStep = 1;\n\tif(isAdaptive)\n\t{\n\t\tdata_raw.push_back(std::pair<Eigen::VectorXd,double>(mCharacter->GetSkeleton()->getPositions(), mCurrentFrame));\n\t}\n\n}\nint\nController::\nGetNumState()\n{\n\treturn this->mNumState;\n}\nint\nController::\nGetNumAction()\n{\n\treturn this->mNumAction;\n}\nvoid \nController::\nSetAction(const Eigen::VectorXd& action)\n{\n\tthis->mActions = action;\n}\nEigen::VectorXd \nController::\nGetEndEffectorStatePosAndVel(const Eigen::VectorXd pos, const Eigen::VectorXd vel) {\n\tEigen::VectorXd ret;\n\tauto& skel = mCharacter->GetSkeleton();\n\tdart::dynamics::BodyNode* root = skel->getRootBodyNode();\n\tEigen::Isometry3d cur_root_inv = root->getWorldTransform().inverse();\n\n\tint num_ee = mEndEffectors.size();\n\tEigen::VectorXd p_save = skel->getPositions();\n\tEigen::VectorXd v_save = skel->getVelocities();\n\n\tskel->setPositions(pos);\n\tskel->setVelocities(vel);\n\tskel->computeForwardKinematics(true, true, false);\n\n\tret.resize((num_ee)*12+15);\n//\tret.resize((num_ee)*9+12);\n\n\tfor(int i=0;i<num_ee;i++)\n\t{\t\t\n\t\tEigen::Isometry3d transform = cur_root_inv * skel->getBodyNode(mEndEffectors[i])->getWorldTransform();\n\t\t//Eigen::Quaterniond q(transform.linear());\n\t\t// Eigen::Vector3d rot = QuaternionToDARTPosition(Eigen::Quaterniond(transform.linear()));\n\t\tret.segment<9>(9*i) << transform.linear()(0,0), transform.linear()(0,1), transform.linear()(0,2),\n\t\t\t\t\t\t\t   transform.linear()(1,0), transform.linear()(1,1), transform.linear()(1,2), \n\t\t\t\t\t\t\t   transform.translation();\n//\t\tret.segment<6>(6*i) << rot, transform.translation();\n\t}\n\n\n\tfor(int i=0;i<num_ee;i++)\n\t{\n\t    int idx = skel->getBodyNode(mEndEffectors[i])->getParentJoint()->getIndexInSkeleton(0);\n\t\tret.segment<3>(9*num_ee + 3*i) << vel.segment<3>(idx);\n//\t    ret.segment<3>(6*num_ee + 3*i) << vel.segment<3>(idx);\n\n\t}\n\n\t// root diff with target com\n\tEigen::Isometry3d transform = cur_root_inv * skel->getRootBodyNode()->getWorldTransform();\n\t//Eigen::Quaterniond q(transform.linear());\n\n\tEigen::Vector3d rot = QuaternionToDARTPosition(Eigen::Quaterniond(transform.linear()));\n\tEigen::Vector3d root_angular_vel_relative = cur_root_inv.linear() * skel->getRootBodyNode()->getAngularVelocity();\n\tEigen::Vector3d root_linear_vel_relative = cur_root_inv.linear() * skel->getRootBodyNode()->getCOMLinearVelocity();\n\n\tret.tail<15>() << transform.linear()(0,0), transform.linear()(0,1), transform.linear()(0,2),\n\t\t\t\t\t  transform.linear()(1,0), transform.linear()(1,1), transform.linear()(1,2),\n\t\t\t\t\t  transform.translation(), root_angular_vel_relative, root_linear_vel_relative;\n//\tret.tail<12>() << rot, transform.translation(), root_angular_vel_relative, root_linear_vel_relative;\n\n\t// restore\n\tskel->setPositions(p_save);\n\tskel->setVelocities(v_save);\n\tskel->computeForwardKinematics(true, true, false);\n\n\treturn ret;\n}\nbool\nController::\nCheckCollisionWithGround(std::string bodyName){\n\tauto collisionEngine = mWorld->getConstraintSolver()->getCollisionDetector();\n\tdart::collision::CollisionOption option;\n\tdart::collision::CollisionResult result;\n\tif(bodyName == \"RightFoot\"){\n\t\tbool isCollide = collisionEngine->collide(this->mCGR.get(), this->mCGG.get(), option, &result);\n\t\treturn isCollide;\n\t}\n\telse if(bodyName == \"LeftFoot\"){\n\t\tbool isCollide = collisionEngine->collide(this->mCGL.get(), this->mCGG.get(), option, &result);\n\t\treturn isCollide;\n\t}\n\telse if(bodyName == \"RightToe\"){\n\t\tbool isCollide = collisionEngine->collide(this->mCGER.get(), this->mCGG.get(), option, &result);\n\t\treturn isCollide;\n\t}\n\telse if(bodyName == \"LeftToe\"){\n\t\tbool isCollide = collisionEngine->collide(this->mCGEL.get(), this->mCGG.get(), option, &result);\n\t\treturn isCollide;\n\t}\n\telse if(bodyName == \"RightHand\"){\n\t\tbool isCollide = collisionEngine->collide(this->mCGHR.get(), this->mCGG.get(), option, &result);\n\t\treturn isCollide;\n\t}\n\telse if(bodyName == \"LeftHand\"){\n\t\tbool isCollide = collisionEngine->collide(this->mCGHL.get(), this->mCGG.get(), option, &result);\n\t\treturn isCollide;\n\t}\n\telse{ // error case\n\t\tstd::cout << \"check collision : bad body name\" << std::endl;\n\t\treturn false;\n\t}\n}\nEigen::VectorXd \nController::\nGetState()\n{\n\tif(mIsTerminal && terminationReason != 8){\n\t\treturn Eigen::VectorXd::Zero(mNumState);\n\t}\n\tauto& skel = mCharacter->GetSkeleton();\n\t\n\tdouble root_height = skel->getRootBodyNode()->getCOM()[1];\n\n\tEigen::VectorXd p_save = skel->getPositions();\n\tEigen::VectorXd v_save = skel->getVelocities();\n\tEigen::VectorXd p,v;\n\t// p.resize(p_save.rows()-6);\n\t// p = p_save.tail(p_save.rows()-6);\n\n\tint n_bnodes = mCharacter->GetSkeleton()->getNumBodyNodes();\n\tint num_p = (n_bnodes - 1) * 6;\n\tp.resize(num_p);\n\n\tfor(int i = 1; i < n_bnodes; i++){\n\t\tEigen::Isometry3d transform = skel->getBodyNode(i)->getRelativeTransform();\n\t\t// Eigen::Quaterniond q(transform.linear());\n\t\tp.segment<6>(6*(i-1)) << transform.linear()(0,0), transform.linear()(0,1), transform.linear()(0,2),\n\t\t\t\t\t\t\t\t transform.linear()(1,0), transform.linear()(1,1), transform.linear()(1,2);\n\t}\n\n\tv = v_save;\n\n\tdart::dynamics::BodyNode* root = skel->getRootBodyNode();\n\tEigen::Isometry3d cur_root_inv = root->getWorldTransform().inverse();\n\tEigen::VectorXd ee;\n\tee.resize(mEndEffectors.size()*3);\n\tfor(int i=0;i<mEndEffectors.size();i++)\n\t{\n\t\tEigen::Isometry3d transform = cur_root_inv * skel->getBodyNode(mEndEffectors[i])->getWorldTransform();\n\t\tee.segment<3>(3*i) << transform.translation();\n\t}\n\tdouble t = mReferenceManager->GetTimeStep(mCurrentFrameOnPhase, isAdaptive);\n\n\tMotion* p_v_target = mReferenceManager->GetMotion(mCurrentFrame+t, isAdaptive);\n\tEigen::VectorXd p_next = GetEndEffectorStatePosAndVel(p_v_target->GetPosition(), p_v_target->GetVelocity()*t);\n\n\tdelete p_v_target;\n\n\tEigen::Vector3d up_vec = root->getTransform().linear()*Eigen::Vector3d::UnitY();\n\tdouble up_vec_angle = atan2(std::sqrt(up_vec[0]*up_vec[0]+up_vec[2]*up_vec[2]),up_vec[1]);\n\tdouble phase = ((int) mCurrentFrame % mReferenceManager->GetPhaseLength()) / (double) mReferenceManager->GetPhaseLength();\n\tEigen::VectorXd state;\n\n\tdouble com_diff = 0;\n\n\tstd::vector<std::string> contact;\n\tcontact.push_back(\"RightFoot\");\n\tcontact.push_back(\"RightToe\");\n\tcontact.push_back(\"LeftFoot\");\n\tcontact.push_back(\"LeftToe\");\n\n\tEigen::Vector4d foot_height;\n\tfor(int i = 0; i < contact.size(); i++) {\n\t\tEigen::Vector3d p = skel->getBodyNode(contact[i])->getWorldTransform().translation();\n\t\tfoot_height[i] = p[1];\n\t}\n\n\tif(isParametric) {\n\t\tstate.resize(p.rows()+v.rows()+1+1+p_next.rows()+ee.rows()+2+mParamGoal.rows()+4);\n\t\tstate<< p, v, up_vec_angle, root_height, p_next, mAdaptiveStep, ee, mCurrentFrameOnPhase, mParamGoal, foot_height;\n\t}\n\telse {\n\t\tstate.resize(p.rows()+v.rows()+1+1+p_next.rows()+ee.rows()+2);\n\t\tstate<< p, v, up_vec_angle, root_height, p_next, mAdaptiveStep, ee, mCurrentFrameOnPhase;\n\t}\n\n\treturn state;\n}\nvoid\nController::SaveTimeData(std::string directory) {\n\tstd::string path = std::string(CAR_DIR) + std::string(\"/\") +  directory;\n\tstd::cout << \"save results to\" << path << std::endl;\n\t\n\tstd::ofstream ofs(path);\n\tofs << mReferenceManager->GetPhaseLength() << std::endl;\n\n\tfor(int i = 0; i < mRecordPhase.size() - 1; i++) {\n\t\tofs << i << \" \" << mRecordPhase[i] << \" \" << mRecordPhase[i+1] - mRecordPhase[i] << std::endl;\n\t}\n\tofs.close();\n\n}\nvoid\nController::SaveDisplayedData(std::string directory, bool normalized) {\n\tstd::string path = directory;\n\tstd::cout << \"save results to\" << path << std::endl;\n\tstd::vector<std::string> HIERARCHY = mReferenceManager->GetHierarchyStr();\n\n\tstd::ofstream ofs(path);\n\tstd::vector<std::string> bvh_order;\n\tbvh_order.push_back(\"Hips\");\n\tbvh_order.push_back(\"Spine\");\n\tbvh_order.push_back(\"Spine1\");\n\tbvh_order.push_back(\"Spine2\");\n\tbvh_order.push_back(\"Neck\");\n\tbvh_order.push_back(\"Head\");\n\tbvh_order.push_back(\"LeftShoulder\");\n\tbvh_order.push_back(\"LeftArm\");\n\tbvh_order.push_back(\"LeftForeArm\");\n\tbvh_order.push_back(\"LeftHand\");\n\tbvh_order.push_back(\"RightShoulder\");\n\tbvh_order.push_back(\"RightArm\");\n\tbvh_order.push_back(\"RightForeArm\");\n\tbvh_order.push_back(\"RightHand\");\n\tbvh_order.push_back(\"LeftUpLeg\");\n\tbvh_order.push_back(\"LeftLeg\");\n\tbvh_order.push_back(\"LeftFoot\");\n\tbvh_order.push_back(\"LeftToe\");\n\tbvh_order.push_back(\"RightUpLeg\");\n\tbvh_order.push_back(\"RightLeg\");\n\tbvh_order.push_back(\"RightFoot\");\n\tbvh_order.push_back(\"RightToe\");\n\n\tstd::vector<Eigen::VectorXd> normalizedPosition;\n\tstd::vector<double> normalizedDPhase;\n\n\tif(normalized){\n\t\tint count = 0;\n\t\tfor(int i = 0; i < mReferenceManager->GetPhaseLength(); i++) {\n\t\t\twhile(count + 1 < mRecordPosition.size() && i >= mRecordPhase[count+1])\n\t\t\t\tcount += 1;\n\t\t\tEigen::VectorXd p(mCharacter->GetSkeleton()->getNumDofs());\n\t\t\tdouble dp = 0;\n\t\t\tif(i < mRecordPhase[count]) {\n\t\t\t\tp = mRecordPosition[count];\n\t\t\t\tdp = mRecordPhase[count + 1] - mRecordPhase[count - 1];\n\t\t\t} else if(count == data_raw.size() - 1 && i > mRecordPhase[count]) {\n\t\t\t\tp = mRecordPosition[count];\n\t\t\t\tdp = mRecordPhase[count] - mRecordPhase[count - 1];\n\t\t\t} else if(i == mRecordPhase[count]) {\n\t\t\t\tp = mRecordPosition[count];\n\t\t\t\tdp = mRecordPhase[count+1] - mRecordPhase[count];\n\t\t\t} else {\n\t\t\t\tdouble weight = 1.0 - (mRecordPhase[count+1] - i) / (mRecordPhase[count+1] - mRecordPhase[count]);\n\t\t\t\tdouble dp0 = mRecordPhase[count+1] - mRecordPhase[count];\n\t\t\t\tdouble dp1 = mRecordPhase[count+2] - mRecordPhase[count+1];\n\t\t\t\tp = DPhy::BlendPosition(mRecordPosition[count], mRecordPosition[count+1], weight);\n\t\t\t\tdp = (1 - weight) * dp0 + weight * dp1;\n\t\t\t}\n\t\t\tnormalizedPosition.push_back(p);\n\t\t\tnormalizedDPhase.push_back(dp);\n\t\t}\n\t}\n\n\tofs << \"HIERARCHY\" << std::endl;\n\tofs << \"ROOT Hips\" << std::endl;\n\tfor(int i = 0; i < HIERARCHY.size(); i++) {\n\t\tofs << HIERARCHY[i] << std::endl;\n\t}\n\tofs << \"MOTION\" << std::endl;\n\tif(normalized) {\n\t\tofs << \"Frames: \" << std::to_string(normalizedPosition.size()) << std::endl;\n\t} else {\n\t\tofs << \"Frames: \" << std::to_string(mRecordPosition.size()) << std::endl;\n\t}\n\tofs << \"Frame Time:\t0.0333333\" << std::endl;\n\tif(normalized) {\n\t\tfor(auto t: normalizedPosition) {\n\n\t\t\tofs << t.segment<3>(3).transpose() * 100 << \" \";\n\n\t\t\tfor(int i = 0; i < bvh_order.size(); i++) {\n\t\t\t\tint idx = mCharacter->GetSkeleton()->getBodyNode(bvh_order[i])->getParentJoint()->getIndexInSkeleton(0);\n\t\t\t\tEigen::AngleAxisd aa(t.segment<3>(idx).norm(), t.segment<3>(idx).normalized());\n\t\t\t\tEigen::Matrix3d m;\n\t\t\t\tm = aa;\n\t\t\t\tEigen::Vector3d v = dart::math::matrixToEulerZXY(m);\n\t\t\t\tofs << v.transpose() * 180 / M_PI << \" \";\t\t\t\n\t\t\t}\n\t\t\tofs << std::endl;\n\t\t}\n\t} else {\n\t\tfor(auto t: mRecordPosition) {\n\t\t\tofs << t.segment<3>(3).transpose() * 100 << \" \";\n\n\t\t\tfor(int i = 0; i < bvh_order.size(); i++) {\n\t\t\t\tint idx = mCharacter->GetSkeleton()->getBodyNode(bvh_order[i])->getParentJoint()->getIndexInSkeleton(0);\n\t\t\t\tEigen::AngleAxisd aa(t.segment<3>(idx).norm(), t.segment<3>(idx).normalized());\n\t\t\t\tEigen::Matrix3d m;\n\t\t\t\tm = aa;\n\t\t\t\tEigen::Vector3d v = dart::math::matrixToEulerZXY(m);\n\t\t\t\tofs << v.transpose() * 180 / M_PI << \" \";\t\t\t\n\t\t\t}\n\t\t\tofs << std::endl;\t\t\n\t\t}\n\t\t\n\t}\n\tstd::cout << \"saved position: \" << mRecordPosition.size() << \", \"<< mReferenceManager->GetPhaseLength() << \", \" << mRecordPosition[0].rows() << std::endl;\n\tofs.close();\n\n\tofs.open(path+\"time\");\n\tfor(auto t: normalizedDPhase) {\n\t\tofs << t << std::endl;\t\n\t}\n\tofs.close();\n\n}\n}\n", "meta": {"hexsha": "9b218c4b5624fa6cb1b843350eceb16a824f079d", "size": 39444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sim/Controller.cpp", "max_stars_repo_name": "snumrl/CAR", "max_stars_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T08:47:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:56:21.000Z", "max_issues_repo_path": "sim/Controller.cpp", "max_issues_repo_name": "snumrl/CAR", "max_issues_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "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": "sim/Controller.cpp", "max_forks_repo_name": "snumrl/CAR", "max_forks_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "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.0422420796, "max_line_length": 166, "alphanum_fraction": 0.7012726904, "num_tokens": 11609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16141235669071524}}
{"text": "#include <gflags/gflags.h>\n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <random>\n#include <memory>\n#include <chrono>\n#include <vector>\n#include <string>\n#include <utility>\n#include <algorithm>\n#include <iterator>\n#include <map>\n#include <thread>\n#include <mutex>\n#include <math.h>\n\n#include <inference_engine.hpp>\n\n#include <samples/slog.hpp>\n\n#include \"customflags.hpp\"\n#include \"detectors.hpp\"\n#include \"cnn.hpp\"\n#include \"face_reid.hpp\"\n#include \"tracker.hpp\"\n#include \"classes.hpp\"\n\n#include <ie_iextension.h>\n#include <ext_list.hpp>\n\n#include <opencv2/opencv.hpp>\n\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/opencv.h>\n\n#include <boost/circular_buffer.hpp>\n\n#ifdef SIMULATOR\n#include \"rclcpp/rclcpp.hpp\"\n#include \"ets_msgs/msg/truck.hpp\"\n\nvoid ros_client(Truck *truck)\n{\n    auto node = rclcpp::Node::make_shared(\"ets_client\");\n\n    auto sub = node->create_subscription<ets_msgs::msg::Truck>(\n        \"truck\", std::bind(&Truck::ros_callback, truck, std::placeholders::_1), rmw_qos_profile_default);\n\n    rclcpp::spin(node);\n}\n#endif\n\nusing namespace InferenceEngine;\n\nstatic dlib::rectangle openCVRectToDlib(cv::Rect r)\n{\n    return dlib::rectangle((long)r.tl().x, (long)r.tl().y, (long)r.br().x - 1, (long)r.br().y - 1);\n}\n\nfloat distanceAtoB(cv::Point2f A, cv::Point2f B)\n{\n    float distance_l = sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y));\n    return distance_l;\n}\n\nbool ParseAndCheckCommandLine(int argc, char *argv[])\n{\n    // ---------------------------Parsing and validation of input args--------------------------------------\n    gflags::ParseCommandLineNonHelpFlags(&argc, &argv, true);\n    if (FLAGS_h)\n    {\n        showUsage();\n        return false;\n    }\n    slog::info << \"Parsing input parameters\" << slog::endl;\n\n    if (FLAGS_i.empty())\n    {\n        throw std::logic_error(\"Parameter -i is not set\");\n    }\n\n    if (FLAGS_m.empty())\n    {\n        throw std::logic_error(\"Parameter -m is not set\");\n    }\n\n    if (FLAGS_n_ag < 1)\n    {\n        throw std::logic_error(\"Parameter -n_ag cannot be 0\");\n    }\n\n    if (FLAGS_n_hp < 1)\n    {\n        throw std::logic_error(\"Parameter -n_hp cannot be 0\");\n    }\n\n    // no need to wait for a key press from a user if an output image/video file is not shown.\n    FLAGS_no_wait |= FLAGS_no_show;\n\n    return true;\n}\n\nenum distractionLevel\n{\n    NOT_DISTRACTED = 0,\n    DISTRACTED,\n    PHONE,\n};\n\nint isDistracted(float y, float p, float r)\n{\n    int result = 0;\n    if (abs(y) > 30 || abs(p) > 30)\n    {\n        if (abs(y) > 20 && p > 10 && r < 0)\n            result = PHONE;\n        else\n            result = DISTRACTED;\n    }\n    return result;\n}\n\nbool identify_driver(cv::Mat frame, std::vector<FaceDetection::Result> *results, VectorCNN *landmarks_detector,\n                     VectorCNN *face_reid, EmbeddingsGallery *face_gallery, std::string *driver_name)\n{\n    bool ret = false;\n    std::vector<cv::Mat> face_rois, landmarks, embeddings;\n\n    if (results->empty())\n        return ret;\n\n    for (const auto &face : *results)\n    {\n        cv::Rect rect = face.location;\n        float scale_factor_x = 0.15;\n        float scale_factor_y = 0.20;\n        double aux_x = (rect.x > 3 ? rect.x : 3);\n        double aux_y = (rect.y > 3 ? rect.y : 3);\n        double aux_width = (rect.width + aux_x < frame.cols ? rect.width : frame.cols - aux_x);\n        double aux_height = (rect.height + aux_y < frame.rows ? rect.height : frame.rows - aux_y);\n        aux_x += scale_factor_x * aux_width;\n        aux_y += scale_factor_y * aux_height;\n        aux_width = aux_width * (1 - 2 * scale_factor_x);\n        aux_height = aux_height * (1 - scale_factor_y);\n        cv::Rect aux_rect = cv::Rect(aux_x, aux_y, aux_width, aux_height);\n        face_rois.push_back(frame(aux_rect));\n    }\n\n    if (!face_rois.empty())\n    {\n        landmarks_detector->Compute(face_rois, &landmarks, cv::Size(2, 5));\n        AlignFaces(&face_rois, &landmarks);\n        face_reid->Compute(face_rois, &embeddings);\n        auto ids = face_gallery->GetIDsByEmbeddings(embeddings);\n\n        if (!ids.empty() && ids[0] != EmbeddingsGallery::unknown_id)\n        {\n            ret = true;\n            *driver_name = face_gallery->GetLabelByID(ids[0]);\n        }\n        else\n            *driver_name = \"Unknown\";\n    }\n\n    return ret;\n}\n\n// Global variables declaration\nint timer_danger = 150; // N frames for DANGER sign\nint timer_off = 0;      // N frames for Welcome sign\nbool face_identified = false;\nbool first_stage_completed = (FLAGS_d_recognition ? false : true);\nint biggest_head = 0;\nbool alarmDistraction = false;\nstd::string driver_name = \"\";\nTimer timer;\nint firstTime = 0;\nTruck truck;\nbool fSim = false;\n\n// Alarm Logic Function\nstd::string labelAlarm = \"\";\n\nstd::string alarmDetection(int is_dist, int yawn_total, int blinl_total)\n{\n    if (is_dist)\n    {\n        switch (is_dist)\n        {\n        case DISTRACTED:\n            if (truck.getSpeed() * 3.6 >= 5 || !fSim)\n            {\n                labelAlarm = \"EYES OUT OF ROAD\";\n                alarmDistraction = true;\n            }\n            break;\n        case PHONE:\n            if (truck.getSpeed() * 3.6 >= 2 || !fSim)\n            {\n                labelAlarm = \"LOOKING AT THE PHONE\";\n                alarmDistraction = true;\n            }\n            break;\n        default:\n            alarmDistraction = false;\n            break;\n        }\n    }\n    else\n    {\n        labelAlarm = \"\";\n        alarmDistraction = false;\n    }\n\n    return labelAlarm;\n}\n\nint maxNormal = 3;\nint maxWarning = 7;\nint maxCritical = 10;\nint x_vum = 5;\nint y_vum = 10;\nint tDrowsiness = 0 ;\n\nvoid alarmDrowsiness(cv::Mat prev_frame, int yawn_total, int blinl_total,int width, int height, int x_alarm, int y_alarm)\n{\n\n    tDrowsiness = (yawn_total + blinl_total);\n\n    if (tDrowsiness <= maxNormal)\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195, height - y_alarm + 15, tDrowsiness * x_vum, y_vum), cv::Scalar(0, 255, 0), -1);\n\n    else if (tDrowsiness > maxNormal && tDrowsiness <= maxWarning)\n    {\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195, height - y_alarm + 15, maxNormal * x_vum, y_vum), cv::Scalar(0, 255, 0), -1);\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195 + (maxNormal * x_vum), height - y_alarm + 15, (tDrowsiness - maxNormal) * x_vum, y_vum), cv::Scalar(0, 255, 255), -1);\n    }\n\n    else if (tDrowsiness > maxWarning && tDrowsiness <= maxCritical)\n    {\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195, height - y_alarm + 15, maxNormal * x_vum, y_vum), cv::Scalar(0, 255, 0), -1);\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195 + (maxNormal * x_vum), height - y_alarm + 15, (maxWarning - maxNormal) * x_vum, y_vum), cv::Scalar(0, 255, 255), -1);\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195 + (maxWarning * x_vum), height - y_alarm + 15, (tDrowsiness - maxWarning) * x_vum, y_vum), cv::Scalar(0, 0, 255), -1);\n    }\n    else\n    {\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195, height - y_alarm + 15, maxNormal * x_vum, y_vum), cv::Scalar(0, 255, 0), -1);\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195 + (maxNormal * x_vum), height - y_alarm + 15, (maxWarning - maxNormal) * x_vum, y_vum), cv::Scalar(0, 255, 255), -1);\n        cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195 + (maxWarning * x_vum), height - y_alarm + 15, (maxCritical - maxWarning) * x_vum, y_vum), cv::Scalar(0, 0, 255), -1);\n    }\n    \n    // VUmeter - White Rectangle\n    cv::rectangle(prev_frame, cv::Rect(width - x_alarm + 195, height - y_alarm + 15, maxCritical * x_vum, y_vum), cv::Scalar(255, 255, 255), 1);\n                        \n}\n\n// Thread 1: Driver Recognition\nvoid driver_recognition(cv::Mat prev_frame, std::vector<FaceDetection::Result> prev_detection_results, VectorCNN landmarks_detector, VectorCNN face_reid, EmbeddingsGallery face_gallery, std::string *driver_name)\n{\n    if (timer[\"face_identified\"].getSmoothedDuration() > 60000.0 && face_identified && firstTime == 1 ||\n        timer[\"face_identified\"].getSmoothedDuration() > 1000.0 && !face_identified && firstTime == 1 ||\n        firstTime == 0)\n    {\n        cv::Mat aux_prev_frame = prev_frame.clone();\n        face_identified = identify_driver(aux_prev_frame, &prev_detection_results, &landmarks_detector, &face_reid, &face_gallery, driver_name);\n        if (!prev_detection_results.empty())\n            cv::rectangle(prev_frame, prev_detection_results[0].location, cv::Scalar(255, 255, 255), 1);\n        firstTime = 1;\n        timer.start(\"face_identified\");\n    }\n}\n\n// Thread 2: Driver Behavior\nvoid driver_behavior(cv::Mat frame, cv::Mat prev_frame, std::vector<FaceDetection::Result> prev_detection_results, std::ostringstream out, dlib::shape_predictor sp, HeadPoseDetection headPoseDetector, size_t width, size_t height)\n{\n    float EYE_AR_THRESH = 0.195;\n    float MOUTH_EAR_THRESH = 0.65;\n    float EYE_AR_CONSEC_FRAMES = 3;\n    float MOUTH_EAR_CONSEC_FRAMES = 5;\n\n    bool eye_closed = false;\n\n    int blink_counter = 0;\n    int yawn_counter = 0;\n    int last_blink_counter = 0;\n    int last_yawn_counter = 0;\n    int blinl_total = 0;\n    int yawn_total = 0;\n    boost::circular_buffer<float> ear_5(5);\n    boost::circular_buffer<float> ear_5_mouth(5);\n\n    int i = 0;\n    std::vector<cv::Point2f> left_eye, right_eye, mouth;\n    for (auto &result : prev_detection_results)\n    {\n        // Complete this thread.\n    }\n}\n\nvoid beeping (Player* beep, bool* finished) {\n\n    while (!(*finished)) {\n        if (tDrowsiness <= 10)\n            beep->setGain(exp((float)(tDrowsiness-10)));\n        if(tDrowsiness > 3) {\n            if (!beep->isPlaying())\n                beep->play();\n        }\n    }\n}\n\nint headbuttDetection(boost::circular_buffer<double>* angle_p)\n{\n\tboost::circular_buffer<double>& pitch = *angle_p;\n\tbool ret = false;\n\tconst int full = 5;\n\tdouble delta = 0;\n\n\tint lim = std::min(full,(int)pitch.size()-1); // Wait for one frame to calculate speed\n\tif (lim > 1) {\n\t\tfor (int i = 0; i < lim; i++)\n\t\t\tdelta = delta + (pitch[i] - pitch[i+1]);\n\t\tdelta = delta / lim;\n\t\tif (delta > 6) // magic threshold (adjust)\n\t\t\tret=true;\n\t}\n\treturn ret;\n}\n\nint main(int argc, char *argv[])\n{\n\n#ifdef SIMULATOR\n    rclcpp::init(argc, argv);\n    std::thread truck_data(ros_client, &truck);\n    fSim = true;\n#endif\n\n    try\n    {\n        timer.start(\"face_identified\");\n        dlib::shape_predictor sp;\n        dlib::deserialize(\"../data/shape_predictor_68_face_landmarks.dat\") >> sp;\n        std::vector<dlib::full_object_detection> shapes;\n\n        std::chrono::high_resolution_clock::time_point slp1, slp2;\n\n        float EYE_AR_THRESH = 0.195;\n        float MOUTH_EAR_THRESH = 0.65;\n        float EYE_AR_CONSEC_FRAMES = 3;\n        float MOUTH_EAR_CONSEC_FRAMES = 5;\n\n        bool eye_closed = false;\n\n        int blink_counter = 0;\n        int yawn_counter = 0;\n        int last_blink_counter = 0;\n        int last_yawn_counter = 0;\n        int blinl_total = 0;\n        int yawn_total = 0;\n        boost::circular_buffer<float> ear_5(5);\n        boost::circular_buffer<float> ear_5_mouth(5);\n\n        std::cout << \"InferenceEngine: \" << GetInferenceEngineVersion() << std::endl;\n\n        // ------------------------------ Parsing and validation of input args ---------------------------------\n        if (!ParseAndCheckCommandLine(argc, argv))\n        {\n            return 0;\n        }\n\n        slog::info << \"Reading input\" << slog::endl;\n        cv::VideoCapture cap;\n        const bool isCamera = FLAGS_i == \"cam\";\n        if (FLAGS_i == \"cam\")\n        {\n            if (!cap.open(0))\n                throw std::logic_error(\"Cannot open input file or camera: \" + FLAGS_i);\n        }\n        else if (FLAGS_i == \"cam1\")\n        {\n            if (!cap.open(1))\n                throw std::logic_error(\"Cannot open input file or camera: \" + FLAGS_i);\n            cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'));\n            //cap.set(cv::CAP_PROP_FRAME_HEIGHT, 480);\n            //cap.set(cv::CAP_PROP_FRAME_WIDTH, 640);\n            //cap.set(cv::CAP_PROP_FPS, 30);\n        }\n        else if (!cap.open(FLAGS_i))\n        {\n            throw std::logic_error(\"Cannot open input file or camera: \" + FLAGS_i);\n        }\n\n        // Size force\n        cap.set(cv::CAP_PROP_FRAME_HEIGHT, 720);\n        cap.set(cv::CAP_PROP_FRAME_WIDTH, 1280);\n        // cap.set(cv::CAP_PROP_FPS, 30);\n\n        const size_t width = (size_t)cap.get(cv::CAP_PROP_FRAME_WIDTH);\n        const size_t height = (size_t)cap.get(cv::CAP_PROP_FRAME_HEIGHT);\n\n        int x = 200;\n        int y = 140;\n        int x_truck_i = width - (x + 10);\n        int y_driver_i = y + 30;\n\n        // read input (video) frame\n        cv::Mat frame;\n        if (!cap.read(frame))\n        {\n            throw std::logic_error(\"Failed to get frame from cv::VideoCapture\");\n        }\n        // -----------------------------------------------------------------------------------------------------\n        // --------------------------- 1. Load Plugin for inference engine -------------------------------------\n        std::map<std::string, InferencePlugin> pluginsForDevices;\n        std::vector<std::pair<std::string, std::string>> cmdOptions = {\n            {FLAGS_d, FLAGS_m}, {FLAGS_d_ag, FLAGS_m_ag}, {FLAGS_d_hp, FLAGS_m_hp}, {FLAGS_d_em, FLAGS_m_em}};\n        FaceDetection faceDetector(FLAGS_m, FLAGS_d, 1, false, FLAGS_async, FLAGS_t, FLAGS_r);\n        HeadPoseDetection headPoseDetector(FLAGS_m_hp, FLAGS_d_hp, FLAGS_n_hp, FLAGS_dyn_hp, FLAGS_async);\n        //\tFacialLandmarksDetection facialLandmarksDetector(FLAGS_m_lm, FLAGS_d_lm, FLAGS_n_lm, FLAGS_dyn_lm, FLAGS_async);\n\n        auto fr_model_path = FLAGS_m_reid;\n        std::cout << fr_model_path << std::endl;\n        auto fr_weights_path = fileNameNoExt(FLAGS_m_reid) + \".bin\";\n        auto lm_model_path = FLAGS_m_lm;\n        auto lm_weights_path = fileNameNoExt(FLAGS_m_lm) + \".bin\";\n\n        std::map<std::string, InferencePlugin> plugins_for_devices;\n        std::vector<std::string> devices = {FLAGS_d_lm, FLAGS_d_reid};\n\n        for (const auto &device : devices)\n        {\n            if (plugins_for_devices.find(device) != plugins_for_devices.end())\n            {\n                continue;\n            }\n            slog::info << \"Loading plugin \" << device << slog::endl;\n            InferencePlugin plugin = PluginDispatcher({\"../../../lib/intel64\", \"\"}).getPluginByDevice(device);\n            printPluginVersion(plugin, std::cout);\n            /** Load extensions for the CPU plugin **/\n            if ((device.find(\"CPU\") != std::string::npos))\n            {\n                plugin.AddExtension(std::make_shared<Extensions::Cpu::CpuExtensions>());\n                if (!FLAGS_l.empty())\n                {\n                    // CPU(MKLDNN) extensions are loaded as a shared library and passed as a pointer to base extension\n                    auto extension_ptr = make_so_pointer<IExtension>(FLAGS_l);\n                    plugin.AddExtension(extension_ptr);\n                    slog::info << \"CPU Extension loaded: \" << FLAGS_l << slog::endl;\n                }\n            }\n            else if (!FLAGS_c.empty())\n            {\n                // Load Extensions for other plugins not CPU\n                plugin.SetConfig({{PluginConfigParams::KEY_CONFIG_FILE, FLAGS_c}});\n            }\n            plugin.SetConfig({{PluginConfigParams::KEY_DYN_BATCH_ENABLED, PluginConfigParams::YES}});\n            if (FLAGS_pc)\n                plugin.SetConfig({{PluginConfigParams::KEY_PERF_COUNT, PluginConfigParams::YES}});\n            plugins_for_devices[device] = plugin;\n        }\n\n        CnnConfig reid_config(fr_model_path, fr_weights_path);\n        reid_config.max_batch_size = 16;\n        reid_config.enabled = /*face_config.enabled*/ true && !fr_model_path.empty() && !lm_model_path.empty();\n        reid_config.plugin = plugins_for_devices[FLAGS_d_reid];\n        VectorCNN face_reid(reid_config);\n\n        // Load landmarks detector\n        CnnConfig landmarks_config(lm_model_path, lm_weights_path);\n        landmarks_config.max_batch_size = 16;\n        landmarks_config.enabled = /*face_config.enabled*/ true && reid_config.enabled && !lm_model_path.empty();\n        landmarks_config.plugin = plugins_for_devices[FLAGS_d_lm];\n        VectorCNN landmarks_detector(landmarks_config);\n\n        double t_reid = 0.4; // Cosine distance threshold between two vectors for face reidentification.\n        EmbeddingsGallery face_gallery(FLAGS_fg, t_reid, landmarks_detector, face_reid);\n\n        for (auto &&option : cmdOptions)\n        {\n            auto deviceName = option.first;\n            auto networkName = option.second;\n\n            if (deviceName == \"\" || networkName == \"\")\n            {\n                continue;\n            }\n\n            if (pluginsForDevices.find(deviceName) != pluginsForDevices.end())\n            {\n                continue;\n            }\n            slog::info << \"Loading plugin \" << deviceName << slog::endl;\n            InferencePlugin plugin = PluginDispatcher({\"../../../lib/intel64\", \"\"}).getPluginByDevice(deviceName);\n\n            /** Printing plugin version **/\n            printPluginVersion(plugin, std::cout);\n\n            /** Load extensions for the CPU plugin **/\n            if ((deviceName.find(\"CPU\") != std::string::npos))\n            {\n                plugin.AddExtension(std::make_shared<Extensions::Cpu::CpuExtensions>());\n\n                if (!FLAGS_l.empty())\n                {\n                    // CPU(MKLDNN) extensions are loaded as a shared library and passed as a pointer to base extension\n                    auto extension_ptr = make_so_pointer<IExtension>(FLAGS_l);\n                    plugin.AddExtension(extension_ptr);\n                    slog::info << \"CPU Extension loaded: \" << FLAGS_l << slog::endl;\n                }\n            }\n            else if (!FLAGS_c.empty())\n            {\n                // Load Extensions for other plugins not CPU\n                plugin.SetConfig({{PluginConfigParams::KEY_CONFIG_FILE, FLAGS_c}});\n            }\n            pluginsForDevices[deviceName] = plugin;\n        }\n\n        /** Per layer metrics **/\n        if (FLAGS_pc)\n        {\n            for (auto &&plugin : pluginsForDevices)\n            {\n                plugin.second.SetConfig({{PluginConfigParams::KEY_PERF_COUNT, PluginConfigParams::YES}});\n            }\n        }\n        // -----------------------------------------------------------------------------------------------------\n\n        // --------------------------- 2. Read IR models and load them to plugins ------------------------------\n        // Disable dynamic batching for face detector as long it processes one image at a time.\n        Load(faceDetector).into(pluginsForDevices[FLAGS_d], false);\n        Load(headPoseDetector).into(pluginsForDevices[FLAGS_d_hp], FLAGS_dyn_hp);\n        // -----------------------------------------------------------------------------------------------------\n\n        // --------------------------- 3. Do inference ---------------------------------------------------------\n        // Start inference & calc performance.\n        slog::info << \"Start inference \" << slog::endl;\n        if (!FLAGS_no_show)\n        {\n            std::cout << \"Press any key to stop\" << std::endl;\n        }\n\n        bool isFaceAnalyticsEnabled = headPoseDetector.enabled();\n\n        //Timer timer;\n        timer.start(\"total\");\n\n        std::ostringstream out;\n        size_t framesCounter = 0;\n        bool frameReadStatus;\n        bool isLastFrame;\n        cv::Mat prev_frame, next_frame;\n\n        // Detect all faces on the first frame and read the next one.\n        timer.start(\"detection\");\n        faceDetector.enqueue(frame);\n        faceDetector.submitRequest();\n        timer.finish(\"detection\");\n\n        prev_frame = frame.clone();\n\n        // Read next frame.\n        timer.start(\"video frame decoding\");\n        frameReadStatus = cap.read(frame);\n        timer.finish(\"video frame decoding\");\n\n        //dlib\n        //dlib::image_window win, win_faces;\n\n        FaceDetection::Result big_head;\n        big_head.label = 0;\n        big_head.confidence = 0;\n        big_head.location = cv::Rect(0, 0, 0, 0);\n\n        boost::circular_buffer<double> pitch = boost::circular_buffer<double>(5);\n        bool headbutt = false;\n\n        bool processing_finished = false;\n        Player beep(\"../data/beep.ogg\");\n        std::thread beep_thread(beeping, &beep, &processing_finished);\n\n        while (true)\n        {\n            framesCounter++;\n            isLastFrame = !frameReadStatus;\n\n            timer.start(\"detection\");\n            // Retrieve face detection results for previous frame.\n            faceDetector.wait();\n            faceDetector.fetchResults();\n            auto prev_detection_results = faceDetector.results;\n            if (!prev_detection_results.empty())\n            {\n                for (int i = 0; i < prev_detection_results.size(); i++)\n                {\n                    if (big_head.location.area() < prev_detection_results[i].location.area())\n                    {\n                        big_head = prev_detection_results[i];\n                        biggest_head = i;\n                    }\n                }\n                prev_detection_results.clear();\n                prev_detection_results.push_back(big_head);\n                big_head.label = 0;\n                big_head.confidence = 0;\n                big_head.location = cv::Rect(0, 0, 0, 0);\n            }\n            // No valid frame to infer if previous frame is last.\n            if (!isLastFrame)\n            {\n                faceDetector.enqueue(frame);\n                faceDetector.submitRequest();\n            }\n            timer.finish(\"detection\");\n\n            timer.start(\"data preprocessing\");\n            // Fill inputs of face analytics networks.\n            for (auto &&face : prev_detection_results)\n            {\n                if (isFaceAnalyticsEnabled)\n                {\n                    auto clippedRect = face.location & cv::Rect(0, 0, width, height);\n                    cv::Mat face = prev_frame(clippedRect);\n                    headPoseDetector.enqueue(face);\n                }\n            }\n            timer.finish(\"data preprocessing\");\n\n            // Run age-gender recognition, head pose estimation and emotions recognition simultaneously.\n            timer.start(\"face analytics call\");\n            if (isFaceAnalyticsEnabled)\n            {\n                headPoseDetector.submitRequest();\n            }\n            timer.finish(\"face analytics call\");\n\n            // Read next frame if current one is not last.\n            if (!isLastFrame)\n            {\n                timer.start(\"video frame decoding\");\n                frameReadStatus = cap.read(next_frame);\n                timer.finish(\"video frame decoding\");\n            }\n\n            timer.start(\"face analytics wait\");\n            if (isFaceAnalyticsEnabled)\n            {\n                headPoseDetector.wait();\n            }\n            timer.finish(\"face analytics wait\");\n\n            // Visualize results.\n            if (!FLAGS_no_show)\n            {\n                TrackedObjects tracked_face_objects;\n                timer.start(\"visualization\");\n                out.str(\"\");\n                out << \"OpenCV cap/render time: \" << std::fixed << std::setprecision(2)\n                    << (timer[\"video frame decoding\"].getSmoothedDuration() +\n                        timer[\"visualization\"].getSmoothedDuration())\n                    << \" ms\";\n                cv::putText(prev_frame, out.str(), cv::Point2f(10, 25), cv::FONT_HERSHEY_TRIPLEX, 0.4,\n                            cv::Scalar(255, 0, 0));\n\n                out.str(\"\");\n                out << \"Face detection time: \" << std::fixed << std::setprecision(2)\n                    << timer[\"detection\"].getSmoothedDuration()\n                    << \" ms (\"\n                    << 1000.f / (timer[\"detection\"].getSmoothedDuration())\n                    << \" fps)\";\n                cv::putText(prev_frame, out.str(), cv::Point2f(10, 45), cv::FONT_HERSHEY_TRIPLEX, 0.4,\n                            cv::Scalar(255, 0, 0));\n\n                if (isFaceAnalyticsEnabled)\n                {\n                    out.str(\"\");\n                    out << \"Face Analysics Networks \"\n                        << \"time: \" << std::fixed << std::setprecision(2)\n                        << timer[\"face analytics call\"].getSmoothedDuration() +\n                               timer[\"face analytics wait\"].getSmoothedDuration()\n                        << \" ms \";\n                    if (!prev_detection_results.empty())\n                    {\n                        out << \"(\"\n                            << 1000.f / (timer[\"face analytics call\"].getSmoothedDuration() +\n                                         timer[\"face analytics wait\"].getSmoothedDuration())\n                            << \" fps)\";\n                    }\n                    cv::putText(prev_frame, out.str(), cv::Point2f(10, 65), cv::FONT_HERSHEY_TRIPLEX, 0.4,\n                                cv::Scalar(255, 0, 0));\n                }\n\n                if ((truck.getEngine() && fSim) || !fSim)\n                { // Detect if Engine = ON and Simulator Flag\n                    // Thread 1: Driver Recognition\n                    std::thread thread_recognition(driver_recognition, prev_frame, prev_detection_results, landmarks_detector, face_reid, face_gallery, &driver_name);\n\n                    // Tread 2: Diver Behavior\n                    // std::thread thread_behavior(driver_behavior, frame, prev_frame, prev_detection_results, out, sp, headPoseDetector, width, height);\n\n                    // Driver Label (CHECK! -> Not here)\n                    cv::rectangle(prev_frame, cv::Rect(width - (x + 20), y_driver_i, x, y), cv::Scalar(0, 0, 0), -1);\n                    cv::rectangle(prev_frame, cv::Rect(width - (x + 20), y_driver_i, x, y), cv::Scalar(255, 255, 255), 2);\n\n                    // For every detected face.\n                    int i = 0;\n                    std::vector<cv::Point2f> left_eye, right_eye, mouth;\n                    for (auto &result : prev_detection_results)\n                    {\n                        cv::Rect rect = result.location;\n\n                        out.str(\"\");\n                        cv::rectangle(prev_frame, rect, cv::Scalar(255, 255, 255), 1);\n                        if (FLAGS_dlib_lm)\n                        {\n                            float scale_factor_x = 0.15;\n                            float scale_factor_y = 0.20;\n                            cv::Rect aux_rect = cv::Rect(rect.x + scale_factor_x * rect.width, rect.y + scale_factor_y * rect.height, rect.width * (1 - 2 * scale_factor_x), rect.height * (1 - scale_factor_y));\n                            //dlib facial landmarks\n                            dlib::array2d<dlib::rgb_pixel> img;\n                            dlib::assign_image(img, dlib::cv_image<dlib::bgr_pixel>(prev_frame));\n                            dlib::rectangle det = openCVRectToDlib(aux_rect);\n                            dlib::full_object_detection shape = sp(img, det);\n                            for (int i = 0; i < shape.num_parts(); i++)\n                            {\n                                if (i >= 36 && i <= 41)\n                                {\n                                    left_eye.push_back(cv::Point2l(shape.part(i).x(), shape.part(i).y()));\n                                    cv::circle(prev_frame, cv::Point2l(shape.part(i).x(), shape.part(i).y()), 1 + static_cast<int>(0.0012 * rect.width), cv::Scalar(0, 255, 255), -1);\n                                }\n                                if (i >= 42 && i <= 47)\n                                {\n                                    right_eye.push_back(cv::Point2l(shape.part(i).x(), shape.part(i).y()));\n                                    cv::circle(prev_frame, cv::Point2l(shape.part(i).x(), shape.part(i).y()), 1 + static_cast<int>(0.0012 * rect.width), cv::Scalar(0, 255, 255), -1);\n                                }\n                                //48 - 54. 50 - 58. 52 - 56.\n\n                                if (i == 48 || i == 54 || i == 50 || i == 58 || i == 52 || i == 56)\n                                {\n                                    mouth.push_back(cv::Point2l(shape.part(i).x(), shape.part(i).y()));\n                                    cv::circle(prev_frame, cv::Point2l(shape.part(i).x(), shape.part(i).y()), 1 + static_cast<int>(0.0012 * rect.width), cv::Scalar(0, 255, 255), -1);\n                                }\n                            }\n                            float ear_left = 0;\n                            float ear_right = 0;\n                            float ear = 0;\n                            ear_left = (distanceAtoB(left_eye[1], left_eye[5]) + distanceAtoB(left_eye[2], left_eye[4])) / (2 * distanceAtoB(left_eye[0], left_eye[3]));\n                            ear_right = (distanceAtoB(right_eye[1], right_eye[5]) + distanceAtoB(right_eye[2], right_eye[4])) / (2 * distanceAtoB(right_eye[0], right_eye[3]));\n                            ear = (ear_left + ear_right) / 2;\n                            ear_5.push_front(ear);\n                            float ear_avg = 0;\n                            for (auto &&i : ear_5)\n                            {\n                                ear_avg = ear_avg + i;\n                            }\n                            ear_avg = ear_avg / ear_5.size();\n                            if (ear_avg < EYE_AR_THRESH)\n                            {\n                                blink_counter += 1;\n                                if (blink_counter >= 90)\n                                    eye_closed = true;\n                            }\n                            else\n                            {\n                                if (blink_counter >= EYE_AR_CONSEC_FRAMES)\n                                {\n                                    blinl_total += 1;\n                                    last_blink_counter = blink_counter;\n                                }\n                                blink_counter = 0;\n                            }\n                            if (eye_closed && timer_danger > 0)\n                            {\n                                cv::putText(frame, \"DANGER\", cv::Point2f(50, 250), cv::FONT_HERSHEY_SIMPLEX, 5, cv::Scalar(0, 0, 255), 5);\n                                cv::putText(frame, \"Blink time: \" + std::to_string(last_blink_counter) + \" frames\", cv::Point2f(250, 100), cv::FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2);\n                                timer_danger--;\n                            }\n                            if (timer_danger == 0)\n                            {\n                                eye_closed = false;\n                                timer_danger = 150;\n                            }\n\n                            cv::putText(prev_frame, \"Blinks: \" + std::to_string(blinl_total), cv::Point2f(x_truck_i, y_driver_i + 60), cv::FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1);\n                            //cv::putText(frame, \"EAR: \" + std::to_string(ear_avg), cv::Point2f(300, 100), cv::FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2);\n\n                            //Yawn detection\n                            float ear_mouth = (distanceAtoB(mouth[1], mouth[5]) + distanceAtoB(mouth[2], mouth[4])) / (2 * distanceAtoB(mouth[0], mouth[3]));\n                            ear_5_mouth.push_front(ear_mouth);\n                            float ear_avg_mouth = 0;\n                            for (auto &&i : ear_5_mouth)\n                            {\n                                ear_avg_mouth = ear_avg_mouth + i;\n                            }\n                            ear_avg_mouth = ear_avg_mouth / ear_5_mouth.size();\n                            if (ear_avg_mouth > MOUTH_EAR_THRESH)\n                            {\n                                yawn_counter += 1;\n                            }\n                            else\n                            {\n                                if (yawn_counter >= MOUTH_EAR_CONSEC_FRAMES)\n                                {\n                                    yawn_total += 1;\n                                    last_yawn_counter = yawn_counter;\n                                }\n                                yawn_counter = 0;\n                            }\n                            cv::putText(prev_frame, \"Yawn time: \" + std::to_string(last_yawn_counter) + \" frames\", cv::Point2f(x_truck_i, y_driver_i + 100), cv::FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1);\n                            cv::putText(prev_frame, \"Yawns: \" + std::to_string(yawn_total), cv::Point2f(x_truck_i, y_driver_i + 80), cv::FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1);\n                            // cv::putText(frame, \"EAR: \" + std::to_string(ear_avg_mouth), cv::Point2f(10, 160), cv::FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2);\n                        }\n\n                        cv::putText(prev_frame,\n                                    out.str(),\n                                    cv::Point2f(result.location.x, result.location.y - 15),\n                                    cv::FONT_HERSHEY_COMPLEX_SMALL,\n                                    0.8,\n                                    cv::Scalar(0, 0, 255));\n\n                        if (headPoseDetector.enabled() && i < headPoseDetector.maxBatch)\n                        {\n                            if (FLAGS_r)\n                            {\n                                std::cout << \"Head pose results: yaw, pitch, roll = \"\n                                          << headPoseDetector[i].angle_y << \";\"\n                                          << headPoseDetector[i].angle_p << \";\"\n                                          << headPoseDetector[i].angle_r << std::endl;\n                            }\n                            cv::Point3f center(rect.x + rect.width / 2, rect.y + rect.height / 2, 0);\n                            headPoseDetector.drawAxes(prev_frame, center, headPoseDetector[i], 50);\n                            pitch.push_front(headPoseDetector[i].angle_p);\n                            headbutt = headbuttDetection(&pitch);\n                            int is_dist = isDistracted(headPoseDetector[i].angle_y, headPoseDetector[i].angle_p, headPoseDetector[i].angle_r);\n\n                            // Alarm Label\n                            int x_alarm = 300;\n                            int y_alarm = 100;\n                            cv::Rect rect(width - (x_alarm + 20), height - (y_alarm + 20), x_alarm, y_alarm);\n                            cv::rectangle(prev_frame, rect, cv::Scalar(0, 0, 0), -1);\n                            cv::rectangle(prev_frame, rect, cv::Scalar(255, 255, 255), 2);\n\n                            cv::putText(prev_frame, \"Alarms\", cv::Point2f(width - x_alarm, height - y_alarm + 4), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 2);\n                            cv::putText(prev_frame, \"Distraction\", cv::Point2f(width - x_alarm + 100, height - y_alarm + 4), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 1);\n                            cv::putText(prev_frame, \"Drowsiness\", cv::Point2f(width - x_alarm + 100, height - y_alarm + 24), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 1);\n                            cv::putText(prev_frame, \"Description\", cv::Point2f(width - x_alarm, height - y_alarm + 44), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 2);\n\n                            // Call alarmDetection Function\n                            cv::putText(prev_frame, alarmDetection(is_dist, yawn_total, blinl_total), cv::Point2f(width - x_alarm, height - y_alarm + 64), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255), 2);\n\n                            if (alarmDistraction)\n                                cv::circle(prev_frame, cv::Point2f(width - x_alarm + 200, height - y_alarm), 7, cv::Scalar(0, 0, 255), -1);\n                            else\n                                cv::circle(prev_frame, cv::Point2f(width - x_alarm + 200, height - y_alarm), 7, cv::Scalar(255, 255, 255), 1);\n\n                            // Thread: Drowsiness Alarm\n                            std::thread thread_drowsiness(alarmDrowsiness,prev_frame, yawn_total, blinl_total, width, height, x_alarm, y_alarm);\n\n                            // Thread: Drowsiness Alarm\n                            thread_drowsiness.join();\n\n                            }\n                        i++;\n                    }\n\n                    // End Thread 1: Driver Recognition\n                    thread_recognition.join();\n\n                    // End Thread 2: Driver Behavior\n                    //thread_behavior.join();\n\n                    // Truck Label\n                    cv::rectangle(prev_frame, cv::Rect(width - (x + 20), 20, x, y), cv::Scalar(0, 0, 0), -1);\n                    cv::rectangle(prev_frame, cv::Rect(width - (x + 20), 20, x, y), cv::Scalar(255, 255, 255), 2);\n\n                    cv::putText(prev_frame, \"Truck Information\", cv::Point2f(x_truck_i, 40), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 2);\n                    if (truck.getEngine())\n                        cv::putText(prev_frame, \"Engine: ON\", cv::Point2f(x_truck_i, 60), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1.8);\n                    else\n                        cv::putText(prev_frame, \"Engine: OFF\", cv::Point2f(x_truck_i, 60), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255), 1.8);\n                    cv::putText(prev_frame, cv::format(\"Speed (Km/h): %3.2f\", truck.getSpeed() * 3.6), cv::Point2f(x_truck_i, 80), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 1.2);\n                    cv::putText(prev_frame, \"RPM: \" + std::to_string(truck.getRpm()), cv::Point2f(x_truck_i, 100), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 1.2);\n                    cv::putText(prev_frame, \"Gear: \" + std::to_string(truck.getGear()), cv::Point2f(x_truck_i, 120), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 1.2);\n                    if (truck.getTrailer())\n                        cv::putText(prev_frame, \"Trailer: ON\", cv::Point2f(x_truck_i, 140), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1.2);\n                    else\n                        cv::putText(prev_frame, \"Trailer: OFF\", cv::Point2f(x_truck_i, 140), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255), 1.2);\n\n                    // Driver Label\n                    cv::putText(prev_frame, \"Driver Information\", cv::Point2f(x_truck_i, y_driver_i + 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 2);\n\n                    if (face_identified)\n                    {\n                        cv::putText(prev_frame, \"Driver: \" + driver_name, cv::Point2f(x_truck_i, y_driver_i + 40), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1);\n                    }\n                    else if (!face_identified && driver_name == \"Unknown\")\n                    {\n                        cv::putText(prev_frame, \"Driver: \" + driver_name, cv::Point2f(x_truck_i, y_driver_i + 40), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255), 1);\n                    }\n                }\n\n                // Sample of Results\n                cv::imshow(\"Detection results\", prev_frame);\n                timer.finish(\"visualization\");\n            }\n\n            // End of file (or a single frame file like an image). We just keep last frame displayed to let user check what was shown\n            if (isLastFrame)\n            {\n                timer.finish(\"total\");\n                if (!FLAGS_no_wait)\n                {\n                    std::cout << \"No more frames to process. Press any key to exit\" << std::endl;\n                    cv::waitKey(0);\n                }\n                break;\n            }\n            else if (!FLAGS_no_show && -1 != cv::waitKey(1))\n            {\n                timer.finish(\"total\");\n                break;\n            }\n\n            prev_frame = frame;\n            frame = next_frame;\n            next_frame = cv::Mat();\n        }\n\n        processing_finished = true;\n        beep_thread.join();\n        slog::info << \"Number of processed frames: \" << framesCounter << slog::endl;\n        slog::info << \"Total image throughput: \" << framesCounter * (1000.f / timer[\"total\"].getTotalDuration()) << \" fps\" << slog::endl;\n\n        // Show performace results.\n        if (FLAGS_pc)\n        {\n            faceDetector.printPerformanceCounts();\n            headPoseDetector.printPerformanceCounts();\n        }\n        // -----------------------------------------------------------------------------------------------------\n    }\n    catch (const std::exception &error)\n    {\n        slog::err << error.what() << slog::endl;\n        return 1;\n    }\n    catch (...)\n    {\n        slog::err << \"Unknown/internal exception happened.\" << slog::endl;\n        return 1;\n    }\n\n#ifdef SIMULATOR\n    truck_data.join();\n#endif\n\n    slog::info << \"Execution successful\" << slog::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "0e8de1778d9212e7bd62fd9b82dce121ef4fc451", "size": 41390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "dinara92/OpenVino-Driver-Behaviour", "max_stars_repo_head_hexsha": "ebee22a9bc434a57cd73f1f0bb96ad529cbc1f1f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-10T07:11:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-10T07:11:26.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "dinara92/OpenVino-Driver-Behaviour", "max_issues_repo_head_hexsha": "ebee22a9bc434a57cd73f1f0bb96ad529cbc1f1f", "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": "dinara92/OpenVino-Driver-Behaviour", "max_forks_repo_head_hexsha": "ebee22a9bc434a57cd73f1f0bb96ad529cbc1f1f", "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.8024819028, "max_line_length": 229, "alphanum_fraction": 0.5165740517, "num_tokens": 9814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.29098086006635976, "lm_q1q2_score": 0.16134029706007258}}
{"text": "#pragma once\n#include \"rendering_randomwalk_impl.hxx\"\n#include \"renderingalgorithms_simplebase.hxx\"\n\n#include <unordered_map>\n#include <boost/functional/hash.hpp>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic warning \"-Wunused-parameter\" \n#pragma GCC diagnostic warning \"-Wunused-variable\"\n\nnamespace RandomWalk\n{\nusing namespace SimplePixelByPixelRenderingDetails;\n  \n// Ref: Veach's Thesis. Chpt. 10.\nnamespace BdptDetail\n{\n  \nusing NodeContainer = ToyVector<RW::PathNode>;\nusing PdfContainer  = ToyVector<Pdf>;\nusing SegmentContainer = ToyVector<RaySegment>;\nusing PathDensityContainer = ToyVector<double>;\nusing ConversionFactorContainer = ToyVector<double>;\nusing SpecularFlagContainer = ToyVector<bool>;\nusing WeightContainer = ToyVector<Spectral3>;\n\n\nclass SubpathHistory\n{\npublic:\n  SubpathHistory(RadianceEstimatorBase& _randomwalk_functions)\n    : randomwalk_functions(_randomwalk_functions)\n  {\n  }\n  \n  void Reset()\n  {\n    // Note: Allocation only on first use. clear() keeps the capacity up. However, incurs dtor calls.\n    fwd_conversion_factors.clear();\n    bwd_conversion_factors.clear();\n    pdfs.clear();\n    pdfs_rev.clear();\n    nodes.clear();\n    betas.clear();\n    segments.clear();\n    is_parallel_beam = true;\n  }\n  \n  void Start(const RW::PathNode &start, const Spectral3 &_weight, Pdf _start_pdf)\n  {\n    // Bah ... copying :-(\n    nodes.push_back(start);\n    betas.push_back(_weight);\n    pdfs.push_back(_start_pdf);  // The probability density of the starting location.\n    pdfs_rev.push_back(1.);\n    segments.push_back(RaySegment{}); // For convenience\n    fwd_conversion_factors.push_back(1.);\n    bwd_conversion_factors.push_back(1.);\n    assert(_start_pdf > 0 && std::isfinite(_start_pdf)); // Because it is the sample. So the probability to generate it must be positive!\n  }\n  \n  void AddSegment(const RW::PathNode &end_node, const Spectral3 &_weight, Pdf pdf_prev_scatter, Pdf pdf_prev_rev_scatter, const VolumePdfCoefficients &volume_pdf_coeff, const RaySegment &segment)\n  {\n    nodes.push_back(end_node);\n    const int idx = isize(nodes)-1;\n    Spectral3  beta_at_node = betas.back()*_weight;\n    betas.push_back(beta_at_node);\n    pdfs.push_back(pdf_prev_scatter);\n    pdfs_rev.push_back(pdf_prev_rev_scatter);\n    segments.push_back(segment);\n    is_parallel_beam &= pdf_prev_scatter.IsFromDelta();\n    double geom_coeff = randomwalk_functions.PdfConversionFactor(nodes[idx-1], nodes[idx], segments[idx], FwdCoeffs(volume_pdf_coeff), is_parallel_beam);\n    fwd_conversion_factors.push_back(geom_coeff);\n    geom_coeff = randomwalk_functions.PdfConversionFactor(nodes[idx], nodes[idx-1], segments[idx].Reversed(), BwdCoeffs(volume_pdf_coeff), false);\n    bwd_conversion_factors.push_back(geom_coeff);      \n    assert(pdf_prev_scatter > 0 && std::isfinite(pdf_prev_scatter)); // Because it is the sample. So the probability to generate it must be positive!\n    assert(geom_coeff > 0);\n  }\n  \n  void Finish()\n  {\n    fwd_conversion_factors.push_back(NaN); // Space for data of connection segment.\n    pdfs.push_back(Pdf{});  // Dito.\n    pdfs_rev.push_back(Pdf{});\n    assert (fwd_conversion_factors.size() == nodes.size() + 1);\n    assert (bwd_conversion_factors.size() == nodes.size());\n    assert (pdfs.size() == nodes.size() + 1);\n    assert (pdfs_rev.size() == pdfs.size());\n  }\n  \n  void Pop()\n  {\n    assert (!nodes.empty());\n    nodes.pop_back();\n    pdfs.pop_back();\n    pdfs_rev.pop_back();\n    betas.pop_back();\n    fwd_conversion_factors.pop_back();\n    bwd_conversion_factors.pop_back();\n    segments.pop_back();\n  }\n  \n  int NumNodes() const\n  {\n    return isize(nodes);\n  }\n\n  const RW::PathNode& Node(int i) const\n  {\n    return nodes[i];\n  }\n\n  RW::PathNode& Node(int i)\n  {\n    return nodes[i];\n  }\n  \n  const RW::PathNode& NodeFromBack(int i) const\n  {\n    return nodes[isize(nodes)-i-1];\n  }\n  \n  const Spectral3& Beta(int i) const\n  {\n    return betas[i];\n  }\n\n  friend class BdptMis;\n  friend class BackupAndReplace;\nprivate:\n  RadianceEstimatorBase& randomwalk_functions;\n  ConversionFactorContainer fwd_conversion_factors;\n  ConversionFactorContainer bwd_conversion_factors;\n  ToyVector<RaySegment> segments; // TODO: Might be able to get rid of this.\n  PdfContainer pdfs; // Initial node probability, then scatter pdf at *previous* node.\n  PdfContainer pdfs_rev; // First 1, then scatter pdf with swapped arguments at *previous* node.\n  NodeContainer nodes;\n  WeightContainer betas;\n  bool is_parallel_beam;\n};\n\n\nstruct Connection\n{\n  Pdf eye_pdf;\n  Pdf eye_pdf_rev;\n  Pdf light_pdf;\n  Pdf light_pdf_rev;\n  VolumePdfCoefficients volume_pdf_coeff;\n  int eye_index;\n  int light_index;\n  RaySegment segment;\n};\n\n\nusing DebugBuffers = std::unordered_map<std::pair<int,int>, Spectral3ImageBuffer, util::pair_hash<int,int>>;\n\n\nclass BackupAndReplace\n{\n  SubpathHistory &h;\n  int node_index; \n  Pdf pdf;\n  Pdf pdf_rev;\n  double fwd_conversion_factor;\n  \n  void InitBothPathsNonEmpty(const RW::PathNode &other_end_node, Pdf pdf_node_scatter, Pdf pdf_node_scatter_rev, const RaySegment &segment, const VolumePdfCoefficients &vol_pdf_coeff)\n  {\n    assert (node_index >= 0 && other_end_node.node_type != RW::NodeType::ZERO_CONTRIBUTION_ABORT_WALK);\n    // The pdf arrays contain the pdf at the previous node. So bump the index by one.\n    pdf = h.pdfs[node_index+1];\n    pdf_rev = h.pdfs_rev[node_index+1];\n    // The conversion factor \"pointing\" to the next node.\n    fwd_conversion_factor = h.fwd_conversion_factors[node_index+1];\n    h.pdfs[node_index+1] = pdf_node_scatter; \n    h.pdfs_rev[node_index+1] = pdf_node_scatter_rev;\n    // Replace by conversion factor for going from solid angle at this node to position at the opposite node.\n    h.fwd_conversion_factors[node_index+1] = h.randomwalk_functions.PdfConversionFactor(\n      h.Node(node_index), other_end_node, segment, FwdCoeffs(vol_pdf_coeff), pdf_node_scatter.IsFromDelta());\n  }\n  \n  void InitEitherSideEmpty(double one_or_start_position_pdf, double one_or_angular_emission_pdf)\n  {\n    // If this side has zero vertices, then it is a light (or not-implemented sensor), which was randomly hit, \n    // and the pdf should have the node position density in the forward pdf and 1 in the reverse pdf.\n    // On the other hand,\n    // If the other side has zero vertices, then this is the path that did the random walk to hit the light.\n    // It's forward pdf should be set to 1, and the reverse pdf to the angular emission density.\n    //assert ((one_or_angular_emission_pdf==1.) ^ (one_or_start_position_pdf==1.));\n    pdf = h.pdfs[node_index+1];\n    pdf_rev = h.pdfs[node_index+1];\n    fwd_conversion_factor = h.fwd_conversion_factors[node_index+1];\n    h.pdfs[node_index+1] = one_or_start_position_pdf;\n    h.pdfs_rev[node_index+1] = one_or_angular_emission_pdf;\n    h.fwd_conversion_factors[node_index+1] = 1.;\n  }\n   \npublic:\n  BackupAndReplace(const BackupAndReplace &) = delete;\n  BackupAndReplace& operator=(const BackupAndReplace &) = delete;\n  \n  BackupAndReplace(SubpathHistory &_h, int _node_index, SubpathHistory &other_h, int other_node_index, Pdf pdf, Pdf pdf_rev, const RaySegment &segment, const VolumePdfCoefficients &vol_pdf_coeff)\n    : h{_h}, node_index{_node_index} \n  {\n    if (_node_index >= 0 && other_node_index >= 0)\n      InitBothPathsNonEmpty(other_h.Node(other_node_index), pdf, pdf_rev, segment, vol_pdf_coeff);\n    else\n      InitEitherSideEmpty(pdf, pdf_rev);\n  }\n  \n  ~BackupAndReplace() \n  {\n    h.pdfs[node_index+1] = pdf;\n    h.fwd_conversion_factors[node_index+1] = fwd_conversion_factor;\n  }\n};\n\n  \nclass BdptMis\n{\npublic:\n  BdptMis(const Scene& scene)\n  {\n    one_over_number_of_splat_attempts_per_pixel = 1./(scene.GetCamera().xres*scene.GetCamera().yres);\n  }\n  \n  double Compute(const SubpathHistory &eye, const SubpathHistory &light, const Connection &connection)\n  {\n    Reset(connection);\n    ComputeSpecularFlags(eye, light, connection);\n    ComputeForwardSubpathDensities(eye, light, connection.eye_index, connection.light_index, eye_densities);\n    ComputeForwardSubpathDensities(light, eye, connection.light_index, connection.eye_index, light_densities);\n    FactorInNumberWeight();\n    double result = ComputePowerHeuristicWeight(connection);\n    //double result = WeightByNumberOfAdmissibleTechniques(); // For debugging!\n    return result;\n  }\nprivate:\n  SpecularFlagContainer specular_flags;\n  PathDensityContainer eye_densities;\n  PathDensityContainer light_densities;\n  int total_node_count;\n  double one_over_number_of_splat_attempts_per_pixel;\n    \n  void Reset(const Connection &connection)\n  {\n    total_node_count = connection.eye_index+1+connection.light_index+1;\n    specular_flags.clear();\n    eye_densities.clear();\n    light_densities.clear();\n  }\n\n  void ComputeSpecularFlags(const SubpathHistory &eye, const SubpathHistory &light, const Connection &connection)\n  {   \n    for (int i=0; i<=connection.eye_index+1; ++i)\n      specular_flags.push_back(eye.pdfs[i].IsFromDelta());\n    for (int i=connection.light_index+1; i>=0; --i)\n      specular_flags.push_back(light.pdfs[i].IsFromDelta());\n    assert(specular_flags.size() == total_node_count + 2);\n  }\n  \n  void ComputeForwardSubpathDensities(const SubpathHistory &fwd_path, const SubpathHistory &reverse_path, \n                                      int idx_fwd, int idx_rev, PathDensityContainer &destination)\n  {\n    assert (fwd_path.fwd_conversion_factors[0] == 1.);\n    destination.push_back(Pdf{1.}); // When there are zero nodes on this subpath.\n    for (int i=0; i<=idx_fwd; ++i)\n    {\n      destination.push_back(destination.back()*\n        fwd_path.fwd_conversion_factors[i] * fwd_path.pdfs[i]);\n    }\n    if (idx_rev >= 0) // Handling the connection segment.\n    {\n      destination.push_back(destination.back()*\n        fwd_path.fwd_conversion_factors[idx_fwd+1] * fwd_path.pdfs[idx_fwd+1]);\n    }\n    for (int i=idx_rev; i>=1; --i)\n    {\n      // Multiplying the scatter density at the node i with the conversion factor\n      // leading in the reverse direction from node i.\n      destination.push_back(destination.back()*\n        reverse_path.bwd_conversion_factors[i] * reverse_path.pdfs_rev[i+1]);\n    }\n    assert(destination.size() == total_node_count + 1);\n  }\n\n  double ComputePowerHeuristicWeight(const Connection &connection) const\n  {\n    /* Simple way to understand the number of admissible techniques in Veach's sense:\n     * Imagine there is a very glossy vertex. Sampling via bsdf is low variance because the bsdf and the pdf cancel each other in the nominator/denominator.\n     * Now, sampling something else and connecting to the vertex has high variance because only very few time we get a contribution, and if so, the bsdf has very large value because it is strongly peaked.\n     * Now make the bsdf sharper, narrower, take limit to Dirac-Delta function. \n     * Variance goes to infinity. We cannot do this. And in fact, my 'Evaluate' & 'Pdf' functions return 0 for specular components, no matter what coordinates.\n     * What is left are the sampling techniques where only non-specular vertices are connected. \n     * So I simply take the segments that have no adjacent specular vertices.\n     */\n    double nominator = eye_densities[connection.eye_index+1]*\n                       light_densities[connection.light_index+1];\n    nominator = Sqr(nominator);\n    assert (std::isfinite(nominator));\n    double denom = 0.;\n    for (int s = 0; s <= total_node_count; ++s)\n    {\n      bool flag = !(specular_flags[s] || specular_flags[s+1]);\n      double summand = flag ? (eye_densities[s]*light_densities[total_node_count-s]) : 0.;\n      denom += Sqr(summand);\n      assert (std::isfinite(denom));\n    }\n    assert(denom > 0.);\n    return nominator/denom;\n  }\n  \n  void FactorInNumberWeight()\n  {\n    for (int i=2; i<=total_node_count; ++i)\n    {\n      eye_densities[i] *= one_over_number_of_splat_attempts_per_pixel;\n    }\n  }\n  \n  double WeightByNumberOfAdmissibleTechniques() const\n  {\n    int num_tech = 0;\n    for (int i = 0; i <= total_node_count; ++i)\n    {\n      num_tech += !(specular_flags[i] || specular_flags[i+1]);\n    }\n    assert (num_tech >= 1); // Actually there can be purely specular paths that cannot be sampled.\n    return 1./(num_tech + Epsilon);\n  }\n};\n\n\n} // namespace BdptDetail\n\n\nclass BdptWorker;\n\n\nclass BdptAlgo : public SimplePixelByPixelRenderingDetails::SimplePixelByPixelRenderingAlgo\n{\n  friend class BdptWorker;\n  bool enable_debug_buffers = false;\n  BdptDetail::DebugBuffers debug_buffers;\n  BdptDetail::DebugBuffers debug_buffers_mis;\n  tbb::spin_mutex debug_buffer_mutex;\npublic:\n  BdptAlgo(const Scene &scene_,const RenderingParameters &render_params_)\n    : SimplePixelByPixelRenderingAlgo{render_params_,scene_}\n  {}\nprotected:\n  std::unique_ptr<SimplePixelByPixelRenderingDetails::Worker> AllocateWorker(int i) override;\n  void PassCompleted() override;\n};\n\n\nclass BdptWorker : public RadianceEstimatorBase, public Worker\n{\n  LambdaSelectionStrategy lambda_selection_factory;\n  ToyVector<SensorResponse> rgb_responses;\n\n  struct Splat : public ROI::PointEmitterArray::Response\n  {\n    Splat(int unit_index, const Spectral3 &weight, int _path_length) :\n      ROI::PointEmitterArray::Response{unit_index, weight}, path_length{_path_length} {}\n    int path_length = {};\n  };\n  \n  BdptDetail::SubpathHistory eye_history;\n  BdptDetail::SubpathHistory direct_light_history; // The alternate history ;-) .Where a random light is sampled for s=*,t=1 paths, instead of the original one. Contains only a single node.\n  BdptDetail::SubpathHistory light_history;\n  BdptDetail::BdptMis bdptmis;\n  ToyVector<MediumTracker> eye_medium_tracker_before_node;\n  Spectral3 total_eye_measurement_contributions;\n  ToyVector<Splat> splats;\n  Index3 lambda_idx;\n  int pixel_index;\n  PathContext eye_context;\n  PathContext light_context;\n  BdptAlgo* master;\n  \npublic:\n  BdptWorker(const Scene &_scene, const AlgorithmParameters &algo_params, BdptAlgo* master) \n  : RadianceEstimatorBase{_scene, algo_params},\n    lambda_selection_factory{},\n    eye_history{*this},\n    direct_light_history{*this},\n    light_history{*this},\n    bdptmis{_scene},\n    eye_medium_tracker_before_node{},\n    master{master}\n  {\n    rgb_responses.reserve(1024);\n    eye_medium_tracker_before_node.reserve(32);\n  }\n\n  \n  RGB RenderPixel(int _pixel_index) override\n  {\n    eye_history.Reset();\n    light_history.Reset();\n    total_eye_measurement_contributions = Spectral3{0.};\n    splats.clear();\n    eye_medium_tracker_before_node.clear();\n    \n    pixel_index = _pixel_index;\n    auto lambda_selection = lambda_selection_factory.WithWeights(sampler);\n    this->lambda_idx = lambda_selection.indices;\n    const auto &lambda_weights = lambda_selection.weights;\n\n    eye_context = PathContext{lambda_selection, TransportType::RADIANCE};\n    light_context = PathContext{lambda_selection, TransportType::IMPORTANCE};\n\n    {\n      Pdf eye_node_pdf;\n      RW::PathNode eye_node = SampleSensorEnd(pixel_index, eye_context, eye_node_pdf);   \n      MediumTracker eye_medium_tracker{scene};\n      InitializeMediumTracker(eye_node, eye_medium_tracker);    \n      eye_history.Start(eye_node, lambda_weights/eye_node_pdf, eye_node_pdf);\n      BdptForwardTrace(\n        eye_history, eye_medium_tracker,                \n        [&eye_medium_tracker, this](int ) { this->eye_medium_tracker_before_node.emplace_back(eye_medium_tracker); }, \n        eye_context);\n      eye_history.Finish();\n    }\n    \n    {\n      Pdf light_node_pdf;\n      RW::PathNode light_node = SampleEmissiveEnd(light_context, light_node_pdf);    \n      MediumTracker light_medium_tracker{scene};\n      InitializeMediumTracker(light_node, light_medium_tracker);\n      light_history.Start(light_node, Spectral3{1./light_node_pdf}, light_node_pdf);\n      BdptForwardTrace(\n        light_history, light_medium_tracker, \n        [](int ) {}, \n        light_context);\n      light_history.Finish();\n    }\n   \n    \n    assert (light_history.NumNodes() <= max_path_node_count);\n    assert (eye_history.NumNodes() <= max_path_node_count);\n\n    for (int eye_idx=0; eye_idx<eye_history.NumNodes(); ++eye_idx)\n    {\n      if (eye_idx==0 || eye_history.Node(eye_idx).IsScatterNode())\n      {\n        // Only camera and scatter nodes are allowed to connect to the light path. Sensor nodes only if they are the first node.\n        // In particular we must not connect light sources on the eye path to the light path. \n        // Surface or volume nodes default to being scatter nodes, so I don't have to consider these explicitly in the above conditional.\n        if (eye_idx+1 < max_path_node_count)\n          DirectLighting(eye_idx, eye_medium_tracker_before_node[eye_idx]);\n        for (int light_idx=1; light_idx<std::min(light_history.NumNodes(), max_path_node_count-eye_idx-1); ++light_idx)\n        {\n          ConnectWithLightPath(eye_idx, light_idx,  eye_medium_tracker_before_node[eye_idx]);\n        }\n      }\n      if (eye_idx>0) // Would cause error on starting node\n        HandleLightHit(eye_idx);\n    }\n \n    for (const auto &splat : splats)\n    {\n      assert(splat.path_length>=2);\n      rgb_responses.push_back(SensorResponse{\n        splat.unit_index,\n        Color::SpectralSelectionToRGB(splat.weight, lambda_idx)\n      });\n    }\n    \n    return Color::SpectralSelectionToRGB(total_eye_measurement_contributions, lambda_idx);\n  }\n  \n  void DirectLighting(int eye_idx, const MediumTracker &eye_medium_tracker)\n  {\n    Pdf pdf_sample_light;\n    RW::PathNode light_node = SampleEmissiveEnd(light_context, pdf_sample_light); \n    direct_light_history.Reset();\n    direct_light_history.Start(light_node, Spectral3{1./pdf_sample_light}, pdf_sample_light);\n    direct_light_history.Finish();\n    \n    ConnectEyeWithOtherPath(eye_idx, 0, direct_light_history, eye_medium_tracker);\n  }\n  \n  \n  void ConnectWithLightPath(int eye_idx, int light_idx, const MediumTracker &eye_medium_tracker)\n  {\n    ConnectEyeWithOtherPath(eye_idx, light_idx, light_history, eye_medium_tracker);\n  }\n  \n  \n  void ConnectEyeWithOtherPath(int eye_idx, int other_idx, BdptDetail::SubpathHistory &other, const MediumTracker &eye_medium_tracker)\n  {\n    VolumePdfCoefficients volume_pdf_coeff{};\n    double eye_pdf, light_pdf;\n    ConnectionSegment to_light = CalculateConnection(\n      eye_history.Node(eye_idx), eye_medium_tracker, other.Node(other_idx),\n      eye_context, light_context, &eye_pdf, &light_pdf, &volume_pdf_coeff);\n    \n    if (to_light.weight.isZero())\n      return;\n\n    double eye_rev_pdf = ReverseScatterPdf(eye_history.Node(eye_idx), eye_pdf, to_light.segment.ray.dir, this->eye_context);\n    double light_rev_pdf = ReverseScatterPdf(light_history.Node(other_idx), light_pdf, -to_light.segment.ray.dir, this->light_context);\n    \n    double mis_weight = MisWeight(eye_history, other, \n      BdptDetail::Connection{\n        Pdf{eye_pdf},\n        Pdf{eye_rev_pdf},\n        Pdf{light_pdf},\n        Pdf{light_rev_pdf},\n        volume_pdf_coeff,\n        eye_idx,\n        other_idx,\n        to_light.segment\n      }\n    );\n    \n    Spectral3 path_weight = eye_history.Beta(eye_idx)*other.Beta(other_idx)*to_light.weight;\n    AddPathContribution(eye_idx, other_idx, mis_weight, path_weight);\n  }\n  \n  \n  // Eye node lies on a light source. Compute path contribution.\n  void HandleLightHit(int eye_idx)\n  {\n    assert(eye_history.NumNodes()>=2);\n    auto &end_node = eye_history.Node(eye_idx);\n    \n    if (!end_node.TryEnableOperationsOnEmitter(scene))\n      return;\n    \n    double reverse_scatter_pdf = 0.;\n    Spectral3 end_weight = Evaluate(\n      end_node, -end_node.incident_dir, light_context, &reverse_scatter_pdf);\n    \n    VolumePdfCoefficients volume_pdf_coeff{}; // Already covered by the random walk. The SubpathHistory has the coefficients for the last segment.\n    \n    double mis_weight = MisWeight(eye_history, light_history, \n      BdptDetail::Connection{\n        Pdf{1.},\n        Pdf{reverse_scatter_pdf},\n        GetPdfOfGeneratingSampleOnEmitter(end_node, light_context),\n        Pdf{1.},\n        volume_pdf_coeff,\n        eye_idx,\n        -1,\n        RaySegment{}\n      }\n    );\n    \n    Spectral3 path_weight = end_weight*eye_history.Beta(eye_idx);\n    AddPathContribution(eye_idx, -1, mis_weight, path_weight);\n    \n    end_node.EnableOperationOnScattererIfFeasible();\n  }\n  \n  \n  double MisWeight(BdptDetail::SubpathHistory &eye, BdptDetail::SubpathHistory &light, BdptDetail::Connection &&connection)\n  {\n    using B = BdptDetail::BackupAndReplace;\n    B eye_backup{eye, connection.eye_index, light, connection.light_index, connection.eye_pdf, connection.eye_pdf_rev, connection.segment, connection.volume_pdf_coeff};\n    std::swap(connection.volume_pdf_coeff.pdf_scatter_bwd, connection.volume_pdf_coeff.pdf_scatter_fwd);\n    B light_backup{light, connection.light_index, eye, connection.eye_index, connection.light_pdf, connection.light_pdf_rev, connection.segment, connection.volume_pdf_coeff};\n    return bdptmis.Compute(eye, light, connection);\n  }\n  \n  \n  void AddPathContribution(int s, int t, double mis_weight, const Spectral3 &path_weight)\n  {\n    assert(path_weight.allFinite() && std::isfinite(mis_weight));\n    int path_length = s+t+2; // +2 Because s and t are 0-based indices.\n    assert(path_length >= 2);\n    if (s == 0) // Initial eye vertex.\n    {\n      if (sensor_connection_unit >= 0)\n      {\n        int num_attempted_paths_per_unit = scene.GetCamera().xres*scene.GetCamera().yres;\n        Spectral3 new_weight = path_weight/num_attempted_paths_per_unit;\n        splats.emplace_back(\n          sensor_connection_unit,\n          mis_weight*new_weight,\n          path_length\n        );\n        AddToDebugBuffer(sensor_connection_unit, s, t, mis_weight, new_weight);\n        sensor_connection_unit = -1;\n      }\n    }\n    else\n    {\n      total_eye_measurement_contributions += mis_weight*path_weight;\n      AddToDebugBuffer(pixel_index, s, t, mis_weight, path_weight);\n    }\n  }\n   \n  \n  template<class StepCallback>\n  void BdptForwardTrace(BdptDetail::SubpathHistory &path, MediumTracker &medium_tracker, StepCallback step_callback, const PathContext &context)\n  {\n    step_callback(0);\n    \n    if (this->max_path_node_count <= 1)\n      return;\n    \n    int path_node_count = 1;    \n    while (true)\n    { \n      VolumePdfCoefficients volume_pdf_coeff;\n      auto &current_node = path.NodeFromBack(0);\n      \n      StepResult step = TakeRandomWalkStep(\n        current_node, medium_tracker, context, &volume_pdf_coeff);\n      \n      if (step.node.node_type == RW::NodeType::ZERO_CONTRIBUTION_ABORT_WALK) // Hit a light or particle escaped the scene or aborting.\n        break;\n\n      // If this is a light path we must not generate paths with light sources in between the ends.\n      if (context.transport==IMPORTANCE && !step.node.IsScatterNode())\n        break;\n      \n      Pdf reverse_pdf = ReverseScatterPdf(current_node, step.scatter_pdf, step.segment.ray.dir, context);\n      \n      // Determine survival of russian roulette early because it modifies beta_factor!\n      bool survive = SurvivalAtNthScatterNode(step.beta_factor, path_node_count+1); \n      \n      path.AddSegment(step.node, step.beta_factor, step.scatter_pdf, reverse_pdf, volume_pdf_coeff, step.segment);\n      \n      step_callback(path_node_count);\n            \n      // The new node is used definitely. However now the walk can terminate.\n      // It would make more sense maybe to do RR right after evaluating the \n      // scatter function. On the other hand, it should not matter how and where \n      // I compute the termination (or survival) probability.\n      if (!survive)\n        break;\n      \n      if (step.node.node_type == RW::NodeType::ZERO_CONTRIBUTION_ABORT_WALK ||\n          step.node.node_type == RW::NodeType::ENV)\n        break;\n      \n      ++path_node_count;\n    }\n  }\n  \n  \n  Pdf ReverseScatterPdf(const PathNode &node, Pdf forward_pdf, const Double3 &reverse_incident_dir, const PathContext &context) const\n  {\n    // Only surface (BSDF) sampling pdf's are allowed to be unsymmetric. There is no need for phase functions to be asymmetric.\n    // And emission directions of light sources and sensors don't have a reverse path at all.\n    if (node.node_type != NodeType::SURFACE_SCATTER)\n      return forward_pdf;\n    // Components proportional to Dirac-Delta should be symmetrical because it importance samples the symmetrical bsdf!\n    // And then there is really no other place to put the peak other than the symmetrical directions.\n    // In that case, the \"pdf\" value here represents the probability to select the Dirac-Delta component of the material.\n    if (forward_pdf.IsFromDelta()) \n      return forward_pdf;\n\n    const SurfaceInteraction &intersection = node.interaction.surface;\n    return GetShaderOf(intersection, scene).Pdf(reverse_incident_dir, intersection, -node.incident_dir, context);\n  }\n\n\n  ToyVector<SensorResponse>& GetSensorResponses() override\n  {\n    return rgb_responses;\n  }\n  \n  \n  void AddToDebugBuffer(int unit_index, int s, int t, double mis_weight, const Spectral3 &path_weight)\n  {\n    if (!master->enable_debug_buffers)\n      return;\n\n    tbb::spin_mutex::scoped_lock lock(master->debug_buffer_mutex);\n    auto key = std::make_pair(s, t);\n    auto it = master->debug_buffers.find(key);\n    if (it == master->debug_buffers.end())\n    {\n      bool _;\n      std::tie(it, _) = master->debug_buffers.insert(std::make_pair(\n        key, Spectral3ImageBuffer(scene.GetCamera().xres, scene.GetCamera().yres)));\n\n    }\n    it->second.Insert(unit_index, Color::SpectralSelectionToRGB(path_weight, lambda_idx));\n    \n    if (!path_weight.isZero())\n    {\n      it = master->debug_buffers_mis.find(key);\n      if (it == master->debug_buffers_mis.end())\n      {\n        bool _;\n        std::tie(it, _) = master->debug_buffers_mis.insert(std::make_pair(\n          key, Spectral3ImageBuffer(scene.GetCamera().xres, scene.GetCamera().yres)));\n\n      }\n      it->second.Insert(unit_index, RGB{Color::RGBScalar{mis_weight}});\n    }\n  }\n};\n\n\n\nclass PathTracingWorker : public Worker, public RandomWalk::RadianceEstimatorBase\n{ \n  LambdaSelectionStrategy lambda_selection_factory;\n  bool do_sample_brdf;\n  bool do_sample_lights;\n  ToyVector<SensorResponse> rgb_responses;\npublic:\n  PathTracingWorker(const Scene &_scene, const AlgorithmParameters &algo_params) \n  : RadianceEstimatorBase{_scene, algo_params},\n    lambda_selection_factory{},\n    do_sample_brdf{true},\n    do_sample_lights{true}\n  {\n    // Which style of sampling for the last vertex of the path. \n    // Defaults to both light and brdf sampling.\n    if (algo_params.pt_sample_mode == \"bsdf\")\n    {\n      do_sample_lights = false;\n    }\n    else if (algo_params.pt_sample_mode == \"lights\")\n    {\n      do_sample_brdf = false;\n    }\n    rgb_responses.reserve(1024);\n  }\n\n  \n  RGB RenderPixel(int pixel_index) override\n  {\n    sensor_connection_unit = -1;\n    \n    auto lambda_selection = lambda_selection_factory.WithWeights(sampler);\n    PathContext context{lambda_selection, TransportType::RADIANCE};\n    context.pixel_index = pixel_index;\n    PathContext light_context{context}; light_context.transport = IMPORTANCE;\n    MediumTracker medium_tracker{scene};\n    VolumePdfCoefficients volume_pdf_coeff;\n    Spectral3 path_sample_values{0.};\n\n    RW::PathNode prev_node;\n    \n    StepResult step;\n    step.node = SampleSensorEnd(pixel_index, context, step.scatter_pdf); // Note: abuse of scatter_pdf. This is not about scattering but picking the initial location.\n    \n    Spectral3 beta{lambda_selection.weights/step.scatter_pdf};\n    \n    InitializeMediumTracker(step.node, medium_tracker);\n\n    int path_node_count = 1;\n    while (true)\n    {\n      if (this->do_sample_lights) \n      {\n        // Next vertex. Sample a point on a light source. Compute geometry term. Add path weight to total weights.\n        Pdf pdf_light;\n        RW::PathNode light_node = SampleEmissiveEnd(context, pdf_light);\n        double pdf_scatter = NaN;\n        volume_pdf_coeff = VolumePdfCoefficients{};\n        ConnectionSegment to_light = CalculateConnection(step.node, medium_tracker, light_node, context, light_context, &pdf_scatter, nullptr, &volume_pdf_coeff);\n        double pdf_of_light_due_to_scatter = pdf_scatter*PdfConversionFactor(step.node, light_node, to_light.segment, FwdCoeffs(volume_pdf_coeff), false);\n        double mis_weight = MisWeight(\n          pdf_light, // Maybe this needs multiplication with pmf to select the unit_index.\n          pdf_of_light_due_to_scatter);\n        Spectral3 path_weight = (mis_weight/pdf_light)*to_light.weight*beta;\n        if (step.node.node_type == NodeType::CAMERA)\n        {\n          if (sensor_connection_unit >= 0)\n          {\n            int num_attempted_paths = scene.GetCamera().xres*scene.GetCamera().yres;\n            path_weight /= num_attempted_paths;\n            rgb_responses.push_back({\n              sensor_connection_unit,\n              Color::SpectralSelectionToRGB(path_weight, lambda_selection.indices)\n            }); // This part works via the auto-generated initializer list ctor.\n          }\n        }\n        else\n        {\n          path_sample_values += path_weight;\n        }\n      }\n\n      prev_node = step.node;\n      volume_pdf_coeff = VolumePdfCoefficients{};\n      step = TakeRandomWalkStep(prev_node, medium_tracker, context, &volume_pdf_coeff);\n      \n      beta *= step.beta_factor;\n      \n      ++path_node_count;\n      \n      if (this->do_sample_brdf && step.node.TryEnableOperationsOnEmitter(scene))\n      {\n        Spectral3 end_weight = Evaluate(step.node, -step.segment.ray.dir, context, nullptr);\n        double pdf_direct_sample = GetPdfOfGeneratingSampleOnEmitter(step.node, context);\n        Pdf pdf_due_to_scatter = PdfConversionFactor(prev_node, step.node, step.segment, FwdCoeffs(volume_pdf_coeff), step.scatter_pdf.IsFromDelta())*step.scatter_pdf;\n        double mis_weight = MisWeight(pdf_due_to_scatter, pdf_direct_sample);\n        path_sample_values += mis_weight*end_weight*beta;\n        step.node.EnableOperationOnScattererIfFeasible();\n      }\n      \n      if (step.node.node_type == RW::NodeType::ZERO_CONTRIBUTION_ABORT_WALK ||\n          step.node.node_type == RW::NodeType::ENV)\n        break;\n      \n      bool survive = SurvivalAtNthScatterNode(beta, path_node_count); \n      if (!survive)\n        break;\n      \n      assert(beta.allFinite());\n    }\n\n \n    return Color::SpectralSelectionToRGB(path_sample_values, lambda_selection.indices);\n  }\n  \n  \n  ToyVector<SensorResponse>& GetSensorResponses() override\n  {\n    return rgb_responses;\n  }\n  \n\n  double MisWeight(Pdf pdf_or_pmf_taken, double pdf_other) const\n  {\n    double mis_weight = 1.;\n    if (!pdf_or_pmf_taken.IsFromDelta() && this->do_sample_brdf && this->do_sample_lights)\n    {\n      mis_weight = PowerHeuristic(pdf_or_pmf_taken, {pdf_other});\n    }\n    return mis_weight;\n  }\n};\n\n\n\n\n} // namespace\n\n\nusing RadianceEstimatorBase = RandomWalk::RadianceEstimatorBase;\n\n#pragma GCC diagnostic pop // Restore command line options\n", "meta": {"hexsha": "776f296b7d57198193a15d251cc118e61994583f", "size": 31022, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/renderingalgorithms_pathtracing.hxx", "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/renderingalgorithms_pathtracing.hxx", "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/renderingalgorithms_pathtracing.hxx", "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": 36.6690307329, "max_line_length": 204, "alphanum_fraction": 0.7122364773, "num_tokens": 7474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16134029277557957}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"test_utils.hpp\"\n\n#include <owlapi/Vocabulary.hpp>\n#include <moreorg/vocabularies/OM.hpp>\n#include <moreorg/reasoning/ResourceMatch.hpp>\n#include <moreorg/algebra/Connectivity.hpp>\n#include <moreorg/OrganizationModel.hpp>\n#include <moreorg/OrganizationModelAsk.hpp>\n#include <graph_analysis/GraphAnalysis.hpp>\n#include <graph_analysis/GraphIO.hpp>\n\nusing namespace owlapi;\nusing namespace owlapi::model;\nusing namespace moreorg;\nusing namespace moreorg::reasoning;\nusing namespace graph_analysis;\n\nBOOST_AUTO_TEST_SUITE(lego)\n\nBOOST_AUTO_TEST_CASE(list)\n{\n    OrganizationModel::Ptr om(new OrganizationModel(getRootDir() + \"/test/data/om-lego-v0.1.owl\"));\n    OrganizationModelAsk ask(om);\n\n    owlapi::vocabulary::Custom lego(\"http://www.rock-robotics.org/2017/10/om-lego#\");\n\n    // report\n    // Statistics:\n    // # graph completeness evaluations: 145\n    // time in s: 119.324\n    // stopped: 0\n    // # propagator executions: 3032041\n    // # failed nodes: 0\n    // # expanded nodes: 7540\n    // depth of search stack: 51\n    // # restarts: 144\n    // # nogoods: 144\n    ModelPool modelPool;\n    modelPool[ lego.resolve(\"YellowBlock\") ] = 10;\n    modelPool[ lego.resolve(\"GreenBlock\") ] = 10;\n    modelPool[ lego.resolve(\"RedBlock\") ] = 10;\n    modelPool[ lego.resolve(\"BlueBlock\") ] = 10;\n    modelPool[ lego.resolve(\"AdapterBlock\") ] = 10;\n    modelPool[ lego.resolve(\"Flag\") ] = 1;\n\n\n    BOOST_TEST_MESSAGE(\"Please remain patient -- this test can take up to 2-3 min\");\n    size_t epochs = 1;\n    size_t minFeasible = 1;\n    for(size_t i = 0; i < epochs; ++i)\n    {\n        BaseGraph::Ptr baseGraph;\n        bool feasible = algebra::Connectivity::isFeasible(modelPool, ask, baseGraph, 0, minFeasible, moreorg::vocabulary::OM::resolve(\"MechanicalInterface\") );\n        BOOST_REQUIRE_MESSAGE(feasible, \"Connectivity check should validate feasibility\");\n        if(baseGraph)\n        {\n            std::stringstream ss;\n            ss << \"/tmp/organization-model-lego-\";\n            ss << i;\n            ss << \".dot\";\n\n            graph_analysis::io::GraphIO::write(ss.str(), baseGraph);\n        }\n        BOOST_TEST_MESSAGE(algebra::Connectivity::getStatistics().toString());\n        usleep(200);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(icaps)\n{\n    OrganizationModel::Ptr om(new OrganizationModel(getRootDir() + \"/test/data/om-icaps-v0.1.owl\"));\n    OrganizationModelAsk ask(om);\n\n    owlapi::vocabulary::Custom lego(\"http://www.rock-robotics.org/2017/10/om-icaps#\");\n\n    ModelPool modelPool;\n    modelPool[ lego.resolve(\"YellowAgent\") ] = 4;\n    modelPool[ lego.resolve(\"GreenAgent\") ] = 3;\n    modelPool[ lego.resolve(\"RedAgent\") ] = 2;\n    modelPool[ lego.resolve(\"BlueAgent\") ] = 1;\n    modelPool[ lego.resolve(\"Adapter\") ] = 1;\n    modelPool[ lego.resolve(\"Manipulator\") ] = 1;\n\n\n    size_t epochs = 1;\n    size_t minFeasible = 1;\n    for(size_t i = 0; i < epochs; ++i)\n    {\n        BaseGraph::Ptr baseGraph;\n        bool feasible = algebra::Connectivity::isFeasible(modelPool, ask, baseGraph, 0, minFeasible, moreorg::vocabulary::OM::resolve(\"MechanicalInterface\") );\n        BOOST_REQUIRE_MESSAGE(feasible, \"Connectivity check should validate feasibility\");\n        if(baseGraph)\n        {\n            std::stringstream ss;\n            ss << \"/tmp/organization-model-icaps-\";\n            ss << i;\n            ss << \".dot\";\n\n            graph_analysis::io::GraphIO::write(ss.str(), baseGraph);\n        }\n        BOOST_TEST_MESSAGE(algebra::Connectivity::getStatistics().toString());\n        usleep(200);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "dc66414c6a2c9ac2fbfcf03d421595e82924863e", "size": 3592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_Lego.cpp", "max_stars_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_stars_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "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": "test/test_Lego.cpp", "max_issues_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_issues_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-26T11:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T19:16:10.000Z", "max_forks_repo_path": "test/test_Lego.cpp", "max_forks_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_forks_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T13:02:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T13:02:49.000Z", "avg_line_length": 32.9541284404, "max_line_length": 159, "alphanum_fraction": 0.6547884187, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16119282697829349}}
{"text": "//----------------------------------------------------------------------------\n// Copyright (C) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the Server Side Public License, version 1,\n// as published by the author.\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// Server Side Public License for more details.\n//\n// You should have received a copy of the Server Side Public License\n// along with this program. If not, see\n// <https://github.com/NilFoundation/plugin/blob/master/LICENSE_1_0.txt>.\n//----------------------------------------------------------------------------\n\n#define BOOST_TEST_MODULE post_rational_vanilla_test\n\n#include <boost/test/data/monomorphic.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <nil/filecoin/storage/proofs/core/sector.hpp>\n\n#include <nil/filecoin/storage/proofs/post/rational/vanilla.hpp>\n\n#include \"../../core/merkle/generate_tree.hpp\"\n\nusing namespace nil::filecoin;\n\nBOOST_AUTO_TEST_SUITE(post_rational_vanilla_test_suite)\n\ntemplate<typename MerkleTreeType>\nvoid test_rational_post() {\n    const auto rng = XorShiftRng::from_seed(crate::TEST_SEED);\n\n    const std::uint64_t leaves = 64 * get_base_tree_count::<Tree>();\n    const std::uint64_t sector_size = leaves * 32;\n    const std::size_t challenges_count = 8;\n\n    const auto pub_params = PublicParams {\n        sector_size,\n        challenges_count,\n    };\n\n    // Construct and store an MT using a named store.\n    const auto temp_dir = tempfile::tempdir();\n    const auto temp_path = temp_dir.path();\n\n    auto data1, data2, tree1, tree2;\n    const std::tie(data1, tree1) = merkletree::generate_tree<Tree>(rng, leaves, Some(temp_path.to_path_buf()));\n    const std::tie(data2, tree2) = merkletree::generate_tree<Tree>(rng, leaves, Some(temp_path.to_path_buf()));\n\n    const auto seed = (0..leaves).map(| _ | rng.gen()).collect::<Vec<u8>>();\n    auto faults = OrderedSectorSet();\n    faults.insert(139.into());\n    faults.insert(1.into());\n    faults.insert(32.into());\n\n    auto sectors = OrderedSectorSet();\n    sectors.insert(891.into());\n    sectors.insert(139.into());\n    sectors.insert(32.into());\n    sectors.insert(1.into());\n\n    auto trees = BTreeMap();\n    trees.insert(139.into(), &tree1);    // faulty with tree\n    trees.insert(891.into(), &tree2);\n    // other two faults don't have a tree available\n\n    const auto challenges = derive_challenges(challenges_count, sector_size, &sectors, &seed, &faults);\n\n    // the only valid sector to challenge is 891\n    BOOST_ASSERT_MSG(challenges.iter().all(| c | c.sector == 891.into()), \"invalid challenge generated\");\n\n    const auto comm_r_lasts = challenges.iter().map(| c | trees.get(&c.sector).root()).collect::<Vec<_>>();\n\n    std::vector<typename MerkleTreeType::hash_type::digest_type > comm_cs\n        = challenges.iter().map(| _c | typename MerkleTreeType::hash_type::digest_type::random(rng)).collect();\n\n    std::vector<typename MerkleTreeType::hash_type::digest_type > comm_rs\n        = comm_cs.iter()\n              .zip(comm_r_lasts.iter())\n              .map(| (comm_c, comm_r_last) | {<typename MerkleTreeType::hash_type>::Function::hash2(comm_c, comm_r_last)})\n              .collect();\n\n    const auto pub_inputs = PublicInputs {\n        challenges : &challenges,\n        comm_rs : &comm_rs,\n        faults : &faults,\n    };\n\n    const auto priv_inputs = PrivateInputs::<Tree> {\n        trees : &trees,\n        comm_cs : &comm_cs,\n        comm_r_lasts : &comm_r_lasts,\n    };\n\n    const auto proof = RationalPoSt::<Tree>::prove(&pub_params, &pub_inputs, &priv_inputs).expect(\"proving failed\");\n\n    const auto is_valid = RationalPoSt::<Tree>::verify(&pub_params, &pub_inputs, &proof).expect(\"verification failed\");\n\n    BOOST_ASSERT (is_valid);\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_pedersen) {\n    test_rational_post::<LCTree<PedersenHasher, U8, U0, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_sha256) {\n    test_rational_post::<LCTree<Sha256Hasher, U8, U0, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_blake2s) {\n    test_rational_post<LCTree<Blake2sHasher, U8, U0, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_poseidon) {\n    test_rational_post<LCTree<PoseidonHasher, U8, U0, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_poseidon_8_8) {\n    test_rational_post<LCTree<PoseidonHasher, U8, U8, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_poseidon_8_8_2) {\n    test_rational_post<LCTree<PoseidonHasher, U8, U8, U2>>();\n}\n\ntemplate<typename MerkleTreeType>\nvoid test_rational_post_validates_challenge_identity() {\n    const auto rng = XorShiftRng::from_seed(crate::TEST_SEED);\n\n    const std::uint64_t leaves = 64 * get_base_tree_count::<Tree>();\n    const std::uint64_t sector_size = leaves * 32;\n    const std::size_t challenges_count = 2;\n\n    const auto pub_params = PublicParams {\n        sector_size,\n        challenges_count,\n    };\n\n    // Construct and store an MT using a named store.\n    const auto temp_dir = tempfile::tempdir();\n    const auto temp_path = temp_dir.path();\n\n    auto data, tree;\n    const std::tie(data, tree) = merkletree::generate_tree<Tree>(rng, leaves, Some(temp_path.to_path_buf()));\n    const auto seed = (0..leaves).map(| _ | rng.gen()).collect::<Vec<u8>>();\n    auto faults = OrderedSectorSet();\n    faults.insert(1.into());\n    auto sectors = OrderedSectorSet();\n    sectors.insert(0.into());\n    sectors.insert(1.into());\n\n    auto trees = BTreeMap();\n    trees.insert(0.into(), &tree);\n\n    const auto challenges = derive_challenges(challenges_count, sector_size, &sectors, &seed, &faults);\n    const auto comm_r_lasts = challenges.iter().map(| c | trees.get(&c.sector).root()).collect::<Vec<_>>();\n\n    const std::vector<typename MerkleTreeType::hash_type::digest_type > comm_cs\n        = challenges.iter().map(| _c | typename MerkleTreeType::hash_type::digest_type::random(rng)).collect();\n\n    const std::vector<typename MerkleTreeType::hash_type::digest_type > comm_rs\n        = comm_cs.iter()\n              .zip(comm_r_lasts.iter())\n              .map(| (comm_c, comm_r_last) | {<typename MerkleTreeType::hash_type>::Function::hash2(comm_c, comm_r_last)})\n              .collect();\n\n    const auto pub_inputs = PublicInputs {\n        challenges : &challenges,\n        faults : &faults,\n        comm_rs : &comm_rs,\n    };\n\n    const auto priv_inputs = PrivateInputs::<Tree> {\n        trees : &trees,\n        comm_cs : &comm_cs,\n        comm_r_lasts : &comm_r_lasts,\n    };\n\n    const auto proof = RationalPoSt::<Tree>::prove(&pub_params, &pub_inputs, &priv_inputs).expect(\"proving failed\");\n\n    const auto seed = (0..leaves).map(| _ | rng.gen()).collect::<Vec<u8>>();\n    const auto challenges = derive_challenges(challenges_count, sector_size, &sectors, &seed, &faults);\n    const auto comm_r_lasts = challenges.iter().map(| _c | tree.root()).collect::<Vec<_>>();\n\n    const std::vector <typename MerkleTreeType::hash_type::digest_type > comm_cs\n        = challenges.iter().map(| _c | typename MerkleTreeType::hash_type::digest_type::random(rng)).collect();\n\n    const std::vector <typename MerkleTreeType::hash_type::digest_type > comm_rs\n        = comm_cs.iter()\n              .zip(comm_r_lasts.iter())\n              .map(| (comm_c, comm_r_last) | {<typename MerkleTreeType::hash_type>::Function::hash2(comm_c, comm_r_last)})\n              .collect();\n\n    const auto different_pub_inputs = PublicInputs {\n        challenges : &challenges,\n        faults : &faults,\n        comm_rs : &comm_rs,\n    };\n\n    const auto verified = RationalPoSt::<Tree>::verify(&pub_params, &different_pub_inputs, &proof);\n\n    // A proof created with a the wrong challenge not be verified!\n    BOOST_CHECK(!verified);\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_actually_validates_challenge_identity_sha256) {\n    test_rational_post_validates_challenge_identity<LCTree<Sha256Hasher, U8, U0, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_actually_validates_challenge_identity_blake2s) {\n    test_rational_post_validates_challenge_identity<LCTree<Blake2sHasher, U8, U0, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_actually_validates_challenge_identity_pedersen) {\n    test_rational_post_validates_challenge_identity<LCTree<PedersenHasher, U8, U0, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_actually_validates_challenge_identity_poseidon) {\n    test_rational_post_validates_challenge_identity<LCTree<PoseidonHasher, U8, U0, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_actually_validates_challenge_identity_poseidon_8_8) {\n    test_rational_post_validates_challenge_identity<LCTree<PoseidonHasher, U8, U8, U0>>();\n}\n\nBOOST_AUTO_TEST_CASE(rational_post_actually_validates_challenge_identity_poseidon_8_8_2) {\n    test_rational_post_validates_challenge_identity<LCTree<PoseidonHasher, U8, U8, U2>>();\n}\n\nBOOST_AUTO_TEST_CASE(test_derive_challenges_fails_on_all_faulty) {\n    use std::collections::BTreeSet;\n\n    auto sectors = BTreeSet();\n    sectors.insert(SectorId::from(1));\n    sectors.insert(SectorId::from(2));\n\n    auto faults = BTreeSet();\n    faults.insert(SectorId::from(1));\n    faults.insert(SectorId::from(2));\n\n    const std::vector<auto> seed = {0u8};\n\n    BOOST_ASSERT (derive_challenges(10, 1024, &sectors, &seed, &faults).is_err());\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "b0ba45a407282b25253962542f33fea96e561515", "size": 9484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/storage/test/post/rational/vanilla.cpp", "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/test/post/rational/vanilla.cpp", "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/test/post/rational/vanilla.cpp", "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": 37.7848605578, "max_line_length": 122, "alphanum_fraction": 0.6927456769, "num_tokens": 2409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3174262526733264, "lm_q1q2_score": 0.16119281714120368}}
{"text": "// Copyright \u00a9 2017-2021 Trust Wallet\n//\n// This file is part of Trust. The full Trust copyright notice, including\n// terms governing use, modification, and redistribution, is contained in the\n// file LICENSE at the root of the source code distribution tree.\n\n#include \"Address.h\"\n#include \"../Base32.h\"\n#include \"../HexCoding.h\"\n#include \"../Crc.h\"\n\n#include <boost/algorithm/string.hpp>\n#include <array>\n\nusing namespace TW::Stacks;\nusing namespace boost::algorithm;\n\nconst char* Address::BASE32_ALPHABET_CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nTW::Data Address::deconstruct(const std::string& string) {\n    if ((string.length() < (checksumSize + 2)) || (string.length() > size)) {\n        return {};\n    }\n\n    // Check that it decodes correctly\n    Data data;\n    auto normalise = to_upper_copy(string);\n    auto pad = size - normalise.length();\n    if (pad) {\n        normalise.insert(2, std::string(pad, '0'));\n    }\n    replace_all(normalise, \"O\", \"0\");\n    replace_all(normalise, \"L\", \"1\");\n    replace_all(normalise, \"I\", \"1\");\n    if ((normalise[0] != 'S') || !Base32::decode(normalise.substr(1), data, BASE32_ALPHABET_CROCKFORD)) {\n        return {};\n    }\n\n    // Verify that checksums match\n    data[0] >>= 3;\n    auto checksum = Hash::sha256(Hash::sha256(&data[0], bytesSize));\n    if (!std::equal(data.end() - checksumSize, data.end(), checksum.begin())) {\n\treturn {};\n    }\n    return Data(data.begin(), data.begin() + bytesSize);\n}\n\nbool Address::isValid(const std::string& string, const std::vector<TW::byte>& validPrefixes) {\n    auto data = deconstruct(string);\n    return data.size() && (!validPrefixes.size() || std::find(validPrefixes.begin(), validPrefixes.end(), data[0]) != validPrefixes.end()); \n}\n\nAddress::Address(const std::string& string) {\n    // Ensure address is valid\n    auto data = deconstruct(string);\n    if (!data.size()) {\n        throw std::invalid_argument(\"Invalid address data\");\n    }\n    std::copy(data.begin(), data.end(), bytes.begin());\n}\n\nAddress::Address(const PublicKey& publicKey, TW::byte prefix) {\n    if ((publicKey.type != TWPublicKeyTypeSECP256k1) && (publicKey.type != TWPublicKeyTypeSECP256k1Extended)) {\n        throw std::invalid_argument(\"Invalid public key type\");\n    }\n    auto data = publicKey.hash({}, Hash::sha256ripemd);\n    std::copy(data.begin(), data.end(), bytes.begin() + 1);\n    bytes[0] = prefix;\n}\n\nstd::string Address::string() const {\n    static_assert((8 * (bytesSize + checksumSize)) % 5 == 0);\n    auto data = Data(bytes.begin(), bytes.end());\n    auto checksum = Hash::sha256(Hash::sha256(data));\n    data.insert(data.end(), checksum.begin(), checksum.begin() + checksumSize);\n    TW::byte prefix = data[0] << 3;\n    data[0] = 0;\n    auto encoded = Base32::encode(data, BASE32_ALPHABET_CROCKFORD);\n    encoded.erase(0, encoded.find_first_not_of('0'));\n    for (int i = 1; i < data.size() && !data[i]; i++) {\n       encoded.insert(0, \"0\");\n    }\n    return std::string(\"S\") + Base32::encode({prefix}, BASE32_ALPHABET_CROCKFORD)[0] + encoded;\n}\n", "meta": {"hexsha": "e8b2cd54a85369c70d0521ac93761fb75e418e68", "size": 3037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Stacks/Address.cpp", "max_stars_repo_name": "dltxio/trustwallet-stacks", "max_stars_repo_head_hexsha": "46e81a03d81c4d067ca93684c75b51e337f4d1e0", "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/Stacks/Address.cpp", "max_issues_repo_name": "dltxio/trustwallet-stacks", "max_issues_repo_head_hexsha": "46e81a03d81c4d067ca93684c75b51e337f4d1e0", "max_issues_repo_licenses": ["MIT"], "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/Stacks/Address.cpp", "max_forks_repo_name": "dltxio/trustwallet-stacks", "max_forks_repo_head_hexsha": "46e81a03d81c4d067ca93684c75b51e337f4d1e0", "max_forks_repo_licenses": ["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.7294117647, "max_line_length": 140, "alphanum_fraction": 0.6476786302, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1609284900615129}}
{"text": "// experiment with posterior regularization on a simple, artificial clustering problem.\n#include \"Generic/common/leak_detection.h\"\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <map>\n#include <fstream>\n#include <iostream>\n#include <cstring>\n#include <iomanip>\n#include <errno.h>\n#include <time.h>\n#include <math.h>\n#include <boost/foreach.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include \"Generic/common/foreach_pair.hpp\"\n\n#include \"PosteriorRegularization.h\"\n#include \"constraints/ClassRequiresFeatureConstraint.h\"\n#include \"constraints/AtMostNOfClassConstraint.h\"\n#include \"constraints/AtLeastNOfClassIfFeatureConstraint.h\"\n#include \"../GraphicalModels/VectorUtils.h\"\n#include \"../GraphicalModels/DataSet.h\"\n#include \"../GraphicalModels/Graph.h\"\n#include \"../GraphicalModels/Factor.h\"\n#include \"../GraphicalModels/Variable.h\"\n#include \"../GraphicalModels/Message.h\"\n#include \"../GraphicalModels/learning/EM.h\"\n#include \"../GraphicalModels/learning/PREM.h\"\n#include \"../GraphicalModels/io/Reporter.h\"\n#include \"../GraphicalModels/pr/FeatureImpliesClassConstraint.h\"\n\nwchar_t* CLASS_NAMES[] = { L\"AIR\", L\"FN\", L\"MOD\", L\"LOC\", L\"CO\", L\"GAR\", L\"GAR_LOC\" };\nconst double BMMFeatureFactor::SMOOTHING = 0.1;\nconst double ArgTypePriorFactor::SMOOTHING = 0.5;\n\nusing namespace std;\nusing boost::make_shared;\nusing boost::static_pointer_cast;\nusing boost::shared_ptr;\nusing std::vector;\nusing GraphicalModel::DataSet;\nusing GraphicalModel::Constraint;\nusing GraphicalModel::Message_ptr;\nusing GraphicalModel::SymmetricDirichlet;\nusing GraphicalModel::FeatureImpliesClassConstraint;\n\ntypedef boost::shared_ptr<GraphicalModel::DataSet<Document> > DataSet_ptr;\n\nvoid Document::finalize(const std::vector<FV_ptr>& featureVectors) {\n\tassert(slots.size() == featureVectors.size());\n\n\tfor (size_t i=0; i<slots.size(); ++i) {\n\t\tconst SlotVariable_ptr& slot = slots[i];\n\n\t\tBMMFeatureFactor_ptr ff = make_shared<BMMFeatureFactor>(slot);\n\t\tBOOST_FOREACH(const std::wstring& feature, *featureVectors[i]) {\n\t\t\tff->addFeature(feature);\n\t\t}\n\t\tconnect(*ff, *slot);\n\t\tfeatureFactors.push_back(ff);\n\n\t\tArgTypePriorFactor_ptr apf = make_shared<ArgTypePriorFactor>();\n\t\tconnect(*apf, *slot);\n\t\tpriorFactors.push_back(apf);\n\t}\n}\n\nvoid BMMFeatureFactor::finishedLoading(unsigned int n_classes) {\n\tBMMFeatureFactorParent::finishedLoading(n_classes, false,\n\t\t\tmake_shared<SymmetricDirichlet>(SMOOTHING));\n}\n\nvoid ArgTypePriorFactor::finishedLoading(unsigned int n_classes) {\n\tATPFParent::finishedLoading(n_classes,\n\t\t\tmake_shared<SymmetricDirichlet>(ArgTypePriorFactor::SMOOTHING));\n}\n\nvoid Document::finishedLoading() {\n\tBMMFeatureFactor::finishedLoading(NUM_CLASSES);\n\tArgTypePriorFactor::finishedLoading(NUM_CLASSES);\n}\n\nvoid Document::clearFactorModificationsImpl() {\n\tBOOST_FOREACH(const BMMFeatureFactor_ptr& featureFactor, featureFactors) {\n\t\tfeatureFactor->clearModifiers();\n\t}\n\tBOOST_FOREACH(const ArgTypePriorFactor_ptr& priorFactor, priorFactors) {\n\t\tpriorFactor->clearModifiers();\n\t}\n}\n\n\nvoid Document::numberFactorsImpl(unsigned int& next_id) {\n\tBOOST_FOREACH(const BMMFeatureFactor_ptr& featureFactor, featureFactors) {\n\t\tfeatureFactor->setID(next_id++);\n\t}\n\tBOOST_FOREACH(const ArgTypePriorFactor_ptr& priorFactor, priorFactors) {\n\t\tpriorFactor->setID(next_id++);\n\t}\n}\n\nunsigned int Document::nFactorsImpl() const {\n\treturn featureFactors.size() + priorFactors.size();\n}\n\nunsigned int Document::nVariablesImpl() const {\n\treturn slots.size();\n}\n\n/*unsigned int Document::nRootFactors() const {\n\treturn featureFactors.size() + priorFactors.size();\n\t}\n\nSlotVariable& Document::variable(unsigned int i) const {\n\treturn *slots[i];\n}\n\nGraphicalModel::ModifiableUnaryFactor& Document::factor(unsigned int i) const {\n\tif (i<featureFactors.size()) {\n\t\treturn *featureFactors[i];\n\t} else {\n\t\treturn *priorFactors[i - featureFactors.size()];\n\t}\n}\n\nGraphicalModel::ModifiableUnaryFactor& Document::rootFactor(unsigned int i) const {\n\treturn factor(i);\n}\n*/\n\n/*\nvoid Document::clearFactorModifications() {\n\tBOOST_FOREACH(const BMMFeatureFactor_ptr& featureFactor, featureFactors) {\n\t\tfeatureFactor->clearModifiers();\n\t}\n\tBOOST_FOREACH(const ArgTypePriorFactor_ptr& priorFactor, priorFactors) {\n\t\tpriorFactor->clearModifiers();\n\t}\n}*/\n\n\ndouble Document::inferenceImpl() {\n\tdouble LL = 0.0;\n\t// first reset everything\n\tBOOST_FOREACH(const SlotVariable_ptr& slot, slots) {\n\t\tslot->clearMessages();\n\t}\n\tBOOST_FOREACH(const BMMFeatureFactor_ptr& featureFactor, featureFactors) {\n\t\tfeatureFactor->clearMessages();\n\t}\n\tBOOST_FOREACH(const ArgTypePriorFactor_ptr& priorFactor, priorFactors) {\n\t\tpriorFactor->clearMessages();\n\t}\n\n\t// all factors are roots and all roots are factors, so simply send messages\n\t// from all factors and we are done.\n\tBOOST_FOREACH(const BMMFeatureFactor_ptr& featureFactor, featureFactors) {\n\t\tfeatureFactor->sendMessages();\n\t}\n\tBOOST_FOREACH(const ArgTypePriorFactor_ptr& priorFactor, priorFactors) {\n\t\tpriorFactor->sendMessages();\n\t}\n\tstd::vector<double> messageProducts(NUM_CLASSES);\n\tBOOST_FOREACH(const SlotVariable_ptr& slot, slots) {\n\t\tslot->receiveMessage();\n\n\t\tslot->productOfIncomingMessages(messageProducts);\n\t\tLL += logSumExp(messageProducts);\n\t}\n\treturn LL;\n}\n\nvoid SlotVariable::dump() const {\n\twcout << L\"Incoming msgs: \" << endl;\n\tBOOST_FOREACH(const Message_ptr& msg, incomingMessages()) {\n\t\twcout << L\"\\t\";\n\t\tfor (unsigned int i =0; i<msg->size(); ++i) {\n\t\t\twcout << (*msg)[i] << L\"\\t\";\n\t\t}\n\t\twcout << endl;\n\t}\n\twcout << L\"Marginals: \";\n\tBOOST_FOREACH(double p, marginals()) {\n\t\twcout << p << L\"\\t\";\n\t}\n\twcout << endl;\n}\n\nvoid Document::initializeRandomlyImpl() {\n\tstd::vector<double> tmp(NUM_CLASSES);\n\n\tBOOST_FOREACH(const SlotVariable_ptr& slot, slots) {\n\t\tdouble sum = 0;\n\t\tBOOST_FOREACH(double& x, tmp) {\n\t\t\tx = rand() % 25 + 5;\n\t\t\tsum += x;\n\t\t}\n\t\tBOOST_FOREACH(double& x, tmp) {\n\t\t\tx/=sum;\n\t\t}\n\t\tslot->setMarginals(tmp);\n\t}\n}\n\nvoid Document::observeImpl() {\n\tfor (size_t i=0; i<slots.size(); ++i) {\n\t\tfeatureFactors[i]->observe(*slots[i]);\n\t\tpriorFactors[i]->observe(*slots[i]);\n\t}\n}\n\nvoid Document::clearCountsImpl() {\n\tArgTypePriorFactor::clearCounts();\n\tBMMFeatureFactor::clearCounts();\n}\n\ntemplate <typename Dumper>\nvoid Document::updateParametersFromCounts(const Dumper& dumper) {\n\tArgTypePriorFactor::updateParametersFromCounts(dumper);\n\tBMMFeatureFactor::updateParametersFromCounts(dumper);\n}\n\nFV_ptr fv(unsigned int slotNum, unsigned int slotIdx, const wstring& slotEntityType,\n\t\tconst vector<wstring>& words)\n{\n\tFV_ptr vec = make_shared<FV>();\n\twstring token = words[slotIdx];\n\tvec->push_back(token);\n\tstd::vector<wstring> tokParts;\n\tboost::split(tokParts, token, boost::is_any_of(L\" \"));\n\n\tif (slotEntityType != L\"O\") {\n\t\tvec->push_back(slotEntityType + L\"_entity_type\");\n\t}\n\n\tif (tokParts.size() > 0) {\n\t\tBOOST_FOREACH(const wstring& part, tokParts) {\n\t\t\tvec->push_back(part + L\"_part\");\n\t\t}\n\t}\n\n\tswitch(tokParts.size()) {\n\t\tcase 1:\n\t\t\tvec->push_back(L\"single_word\");\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvec->push_back(L\"two_words\");\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvec->push_back(L\"three_words\");\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tvec->push_back(L\"four_words\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tvec->push_back(L\"more_than_four_words\");\n\t\t\tbreak;\n\t}\n\t\n\tif (slotNum == 0) {\n\t\tvec->push_back(L\"first_slot\");\n\t} else if (slotNum == 1) {\n\t\tvec->push_back(L\"second_slot\");\n\t} else if (slotNum == 2) {\n\t\tvec->push_back(L\"third_slot\");\n\t} else if (slotNum == 3) {\n\t\tvec->push_back(L\"fourth_or_later_slot\");\n\t}\n\n\tif (slotIdx > 0) {\n\t\tvec->push_back(words[slotIdx-1] + L\"_prev_unigram\");\n\t\tif (slotIdx > 1) {\n\t\t\tvec->push_back(words[slotIdx-2] \n\t\t\t\t\t\t+ L\"_\" + words[slotIdx-1] + L\"_prev_bigram\");\n\t\t}\n\t}\n\n\tif (slotIdx < words.size() - 1) {\n\t\tvec->push_back(words[slotIdx+1] + L\"_next_unigram\");\n\t\tif (slotIdx < words.size() -2) {\n\t\t\tvec->push_back(words[slotIdx+1] + L\"_\" \n\t\t\t\t\t\t+ words[slotIdx+2] + L\"_next_bigram\");\n\t\t}\n\t}\n\n\treturn vec;\n} \n\nclass Label {\n\tpublic: \n\t\tLabel(const wstring& str) {\n\t\t\tbco = str[0];\n\t\t\tif (str == L\"O\") {\n\t\t\t\tgs = L\"null\";\n\t\t\t} else {\n\t\t\t\tif (str.length() < 3 || str[1] != L'-') {\n\t\t\t\t\twcerr << str << endl;\n\t\t\t\t\tthrow BadLineException(L\"Cannot parse label\");\n\t\t\t\t}\n\t\t\t\tgs = str.substr(2);\n\t\t\t}\n\t\t}\n\t\twchar_t bco;\n\t\twstring gs;\n};\n\nstruct SlotEntry {\n\tSlotEntry(unsigned int index, const wstring& type, const wstring& entityType)\n\t\t: index(index), type(type), entityType(entityType) {}\n\tunsigned int index;\n\twstring type;\n\twstring entityType;\n};\n\nvoid finishDocument(bool& in_slot, vector<SlotEntry>& slotIndicesAndTypes,\n\t\tvector<wstring>& words, wstring& accum, wstring& slotLabel, \n\t\twstring& slotEntityType, bool annotated, \n\t\tconst DataSet_ptr& data)\n{\n\tif (in_slot) {\n\t\tslotIndicesAndTypes.push_back(\n\t\t\t\tSlotEntry(words.size(), slotLabel, slotEntityType));\n\t\twords.push_back(accum);\n\t\taccum = L\"\";\n\t}\n\tDocument_ptr docInstances = make_shared<Document>();\n\tunsigned int slot_num = 0;\n\tvector<FV_ptr> fvs;\n\n\tBOOST_FOREACH(SlotEntry indexAndType, slotIndicesAndTypes) {\n\t\tSlotVariable_ptr slotInstance = make_shared<SlotVariable>();\n\t\tslotInstance->annotated = annotated;\n\t\tslotInstance->gold_label = SlotVariable::classIndex(indexAndType.type);\n\t\tslotInstance->tok_idx = indexAndType.index;\n\t\tdocInstances->slots.push_back(slotInstance);\n\t\tfvs.push_back(fv(slot_num, indexAndType.index, indexAndType.entityType,\n\t\t\t\twords));\n\t\t++slot_num;\n\t}\n\n\tif (!docInstances->slots.empty()) {\n\t\tdocInstances->words = words;\n\t\tdocInstances->finalize(fvs);\n\t\t//data->documents.push_back(docInstances);\n\t\tdata->addGraph(docInstances);\n\t} \n\twords.clear();\n\taccum = L\"\";\n\tslotLabel = L\"\";\n\tslotEntityType = L\"\";\n\tslotIndicesAndTypes.clear();\n\tin_slot = false;\n}\n\nvoid loadData(const string& filename, const DataSet_ptr& data) \n{\n\twifstream inp(filename.c_str());\n\n\twstring line;\n\tbool first_line = true;\n\tbool annotated = false;\n\tbool in_slot = false;\n\tvector<wstring> words;\n\twstring accum = L\"\";\n\tvector<SlotEntry> slotIndicesAndTypes;\n\twstring slotLabel = L\"\";\n\twstring slotEntityType = L\"\";\n\twstring entityType = L\"\";\n\n\ttry {\n\t\twhile (getline(inp, line)) {\n\t\t\tif (!line.empty()) {\n\t\t\t\tif (line.find(L\"Biography of\") == 0) {\n\t\t\t\t\tif (first_line) {\n\t\t\t\t\t\tfirst_line = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfinishDocument(in_slot, slotIndicesAndTypes, words, accum,\n\t\t\t\t\t\t\t\tslotLabel, slotEntityType, annotated, data);\n\t\t\t\t\t}\n\n\t\t\t\t\twstring year = line.substr(13,4);\n\t\t\t\t\tif (year ==  L\"2006\" || year == L\"2007\" || year == L\"2008\"\n\t\t\t\t\t\t\t|| year == L\"2009\")\n\t\t\t\t\t{\n\t\t\t\t\t\tannotated = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tannotated = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvector<wstring> lineParts;\n\t\t\t\t\tboost::split(lineParts, line, boost::is_any_of(L\" \"));\n\t\t\t\t\tif (lineParts.size() != 4 || lineParts[1].empty()) {\n\t\t\t\t\t\tthrow BadLineException(L\"Wrong number or empty parts\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\twstring token = lineParts[0];\n\t\t\t\t\t\ttransform(token.begin(), token.end(), token.begin(), ::tolower);\n\t\t\t\t\t\tfor(unsigned int i = 0; i < token.size(); ++i) {\n\t\t\t\t\t\t\tif (iswdigit(token[i])) {\n\t\t\t\t\t\t\t\ttoken[i] = L'$';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tLabel label = Label(lineParts[1]);\n\t\t\t\t\t\twstring entityType = lineParts[2];\n\n\t\t\t\t\t\tif (in_slot) {\n\t\t\t\t\t\t\tif (label.bco == L'B') {\n\t\t\t\t\t\t\t\tslotIndicesAndTypes.push_back(\n\t\t\t\t\t\t\t\t\t\tSlotEntry(words.size(), slotLabel,\n\t\t\t\t\t\t\t\t\t\t\tslotEntityType));\n\t\t\t\t\t\t\t\twords.push_back(accum);\n\t\t\t\t\t\t\t\taccum = token;\n\t\t\t\t\t\t\t\tslotLabel = label.gs;\n\t\t\t\t\t\t\t\tslotEntityType = entityType;\n\t\t\t\t\t\t\t} else if (label.bco == L'O') {\n\t\t\t\t\t\t\t\tslotIndicesAndTypes.push_back(\n\t\t\t\t\t\t\t\t\t\tSlotEntry(words.size(), slotLabel,\n\t\t\t\t\t\t\t\t\t\t\tslotEntityType));\n\t\t\t\t\t\t\t\twords.push_back(accum);\n\t\t\t\t\t\t\t\taccum = L\"\";\n\t\t\t\t\t\t\t\tin_slot = false;\n\t\t\t\t\t\t\t\twords.push_back(token);\n\t\t\t\t\t\t\t} else if (label.bco == L'C') {\n\t\t\t\t\t\t\t\taccum += L\" \" + token;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthrow BadLineException(L\"Unknown label, in slot\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (label.bco == L'O') {\n\t\t\t\t\t\t\t\twords.push_back(token);\n\t\t\t\t\t\t\t} else if (label.bco == 'B') {\n\t\t\t\t\t\t\t\taccum = token;\n\t\t\t\t\t\t\t\tin_slot = true;\n\t\t\t\t\t\t\t\tslotLabel = label.gs;\n\t\t\t\t\t\t\t\tslotEntityType = entityType;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthrow BadLineException(L\"Unknown label, out slot\");\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\t\tfinishDocument(in_slot, slotIndicesAndTypes, words, accum,\n\t\t\t\tslotLabel, slotEntityType, annotated, data);\n\t} catch (BadLineException& e) {\n\t\twcerr << L\"Failed to parse line: \" << line << endl;\n\t\twcerr << e.msg << endl;\n\t\tthrow;\n\t}\n\twcout << L\"Loaded \" << data->graphs.size() << L\" documents.\" << endl;\n}\n\ndouble score(const GraphicalModel::DataSet<Document>& data, int cls, int cluster) {\n\tint true_positives = 0;\n\tint false_positives = 0;\n\tint false_negatives = 0;\n\n\tBOOST_FOREACH(Document_ptr doc, data.graphs) {\n\t\tBOOST_FOREACH(SlotVariable_ptr slot, doc->slots) {\n\t\t\tif (slot->annotated) {\n\t\t\t\tunsigned int best_label = (unsigned int)slot->bestLabel();\n\t\t\t\tif (best_label == cluster) {\n\t\t\t\t\tif (slot->gold_label == cls) {\n\t\t\t\t\t\t++true_positives;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t++false_positives;\n\t\t\t\t\t}\n\t\t\t\t} else if (slot->gold_label == cls) {\n\t\t\t\t\t++false_negatives;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (true_positives == 0) {\n\t\treturn 0.0;\n\t} else {\n\t\tdouble precision = ((double)true_positives) / (true_positives + false_positives);\n\t\tdouble recall = ((double)true_positives) / (true_positives + false_negatives);\n\t\treturn 2.0*precision*recall/(precision+recall);\n\t}\n}\n\nvector<unsigned int> score(const GraphicalModel::DataSet<Document>& data) {\n\tvector<unsigned int> bestAlignment(NUM_CLASSES);\n\n\tfor (int cls=0; cls<NUM_CLASSES; ++cls) {\n\t\tint best = -1;\n\t\tdouble best_score = -1.0;\n\t\tfor (int cluster = 0; cluster<NUM_CLASSES; ++cluster) {\n\t\t\tdouble x = score(data, cls, cluster);\n\t\t\twcout << L\"align class \" << cls << L\" to cluster \" << cluster \n\t\t\t\t<< L\" results in F \" << x << endl;\n\t\t\tif (x > best_score) {\n\t\t\t\tbest = cluster;\n\t\t\t\tbest_score = x;\n\t\t\t}\n\t\t}\n\t\twcout << L\"Best alignment for class \" << CLASS_NAMES[cls] \n\t\t\t<< L\" is to cluster \" << best << L\" with an f-measure of \"\n\t\t\t<< best_score << endl;\n\t\tbestAlignment[cls] = best;\n\t}\n\treturn bestAlignment;\n}\n\nwchar_t * COLOR_CSS = L\".cluster0 { background-color: #FF0033; }\\n\"\nL\".cluster1 { background-color: #99FF00; }\\n\"\nL\".cluster2 { background-color: #99CCFF; }\\n\"\nL\".cluster3 { background-color: #FFFFCC; }\\n\"\nL\".cluster4 { background-color: #9966FF; }\\n\"\nL\".cluster5 { background-color: #FFCC33; }\\n\"\nL\".cluster6 { background-color: #00FF7F; }\\n\";\n\nvoid dumpFeatureVector(int cnt, Document_ptr doc) {\n\twcout << \"Document \" << cnt << endl;\n\tfor (unsigned int slot_count = 0; slot_count < doc->slots.size(); ++slot_count) {\n\t\twcout << L\"Slot \" << slot_count << L\": \";\n\t\tBOOST_FOREACH(unsigned int feat, doc->featureFactors[slot_count]->features()) {\n\t\t\twcout << BMMFeatureFactor::featureName(feat) << L\" \";\n\t\t}\n\t\twcout << endl;\n\t\twcout << L\"\\t\";\n\t\tfor (int i=0; i<NUM_CLASSES; ++i) {\n\t\t\twcout << CLASS_NAMES[i] << L\"=\" << setprecision(2) \n\t\t\t\t<< doc->slots[slot_count]->marginals()[i] << L\"\\t\";\n\t\t}\n\t\twcout << endl;\n\t}\n}\n\ntemplate <typename Model>\nvoid applyModel(const string& modelName, Model& model, \n\t\tGraphicalModel::DataSet<Document>& data) {\n\tmodel.e(data);\n\tunsigned int cnt = 0;\n\tvector<unsigned int> bestAlignments = score(data);\n\twofstream out((string(\"debug_\") + modelName + \".html\").c_str());\n\tout << L\"<html><head><title>foo</title><style>\" << COLOR_CSS << L\"</style></head><body>\";\n\tout << \"L<b>Key:</b> \";\n\tfor (int i = 0; i < NUM_CLASSES; ++i) {\n\t\tout << L\"<div class='cluster\" << bestAlignments[i] << L\"'><b>\" << CLASS_NAMES[i]\n\t\t\t<< L\"</b></div>\";\n\t}\n\tBOOST_FOREACH(const Document_ptr& doc, data.graphs) {\n\t\t++cnt;\n\t\tvector<SlotVariable_ptr>::const_iterator slotIt = doc->slots.begin();\n\t\t/*dumpFeatureVector(cnt, doc, alphabet); */\n\t\tout << L\"<p>\";\n\t\tfor (int i=0; i<doc->words.size(); ++i) {\n\t\t\tif (slotIt != doc->slots.end()) {\n\t\t\t\tif (i == (*slotIt)->tok_idx) {\n\t\t\t\t\tout << L\"<span class='cluster\" << (*slotIt)->bestLabel()\n\t\t\t\t\t\t<< L\"'><b>\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tout << doc->words[i] << L\" \";\n\t\t\tif (slotIt != doc->slots.end()) {\n\t\t\t\tif (i == (*slotIt)->tok_idx) {\n\t\t\t\t\tout << L\"</b></span>\";\n\t\t\t\t\t++slotIt;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tout << L\"</p>\";\n\t}\n}\n\n\nvoid createConstraints(const GraphicalModel::DataSet<Document>& dataset, \n\t\tvector<shared_ptr<GraphicalModel::Constraint<Document> > >& constraints)\n{\n\tvector<unsigned int> flightClasses, airlineClasses, modelClasses,\n\t\tgarbageClasses, locationClasses, countryClasses, locOrCoClasses,\n\t\tcountryOrGarbageLocClasses, locLikeClasses, locOrGarLocClasses,\n\t\tlocationOnlyClasses, atMostOneCountryClasses, atMostTwoLocationsClasses,\n\t\tatLeastOneLocationIfLocClasses;\n\tvector<wstring> flightFeatures, airlineFeatures, modelFeatures,\n\t\tgarbageFeatures, locationFeatures, countryFeatures, locOrCoFeatures,\n\t\tcountryOrGarbageLocFeatures, locLikeFeatures, locOrGarLocFeatures,\n\t\tlocationOnlyFeatures, atLeastOneLocationIfLocFeatures;\n\n\tflightClasses.push_back(FLIGHT_NUMBER);\n\tairlineClasses.push_back(AIRLINE);\n\tmodelClasses.push_back(AIRCRAFT_MODEL);\n\tgarbageClasses.push_back(GARBAGE);\n\tlocationClasses.push_back(LOCATION);\n\tlocOrCoClasses.push_back(LOCATION);\n\tlocOrCoClasses.push_back(COUNTRY);\n\tcountryClasses.push_back(COUNTRY);\n\tcountryOrGarbageLocClasses.push_back(COUNTRY);\n\tcountryOrGarbageLocClasses.push_back(GAR_LOC);\n\tlocLikeClasses.push_back(LOCATION);\n\tlocLikeClasses.push_back(COUNTRY);\n\tlocLikeClasses.push_back(GAR_LOC);\n\tlocOrGarLocClasses.push_back(LOCATION);\n\tlocOrGarLocClasses.push_back(GAR_LOC);\n\tlocationOnlyClasses.push_back(LOCATION);\n\tlocationOnlyClasses.push_back(COUNTRY);\n\tlocationOnlyClasses.push_back(GAR_LOC);\n\n\tatMostOneCountryClasses.push_back(COUNTRY);\n\tatMostTwoLocationsClasses.push_back(LOCATION);\n\tatLeastOneLocationIfLocClasses.push_back(LOCATION);\n\n\tflightFeatures.push_back(L\"flight_part\");\n\n\tairlineFeatures.push_back(L\"airlines_part\");\n\tairlineFeatures.push_back(L\"airways_part\");\n\n\tmodelFeatures.push_back(L\"boeing_part\");\n\tmodelFeatures.push_back(L\"airbus_part\");\n\tmodelFeatures.push_back(L\"vickers_part\");\n\tmodelFeatures.push_back(L\"dc-$$_part\");\n\tmodelFeatures.push_back(L\"dc-$_part\");\n\tmodelFeatures.push_back(L\"f-$$_part\");\n\t\n\tgarbageFeatures.push_back(L\"decompression_part\");\n\tgarbageFeatures.push_back(L\"collision_part\");\n\tgarbageFeatures.push_back(L\"crash_part\");\n\tgarbageFeatures.push_back(L\"crashed_part\");\n\tgarbageFeatures.push_back(L\"crashes_part\");\n\tgarbageFeatures.push_back(L\"explodes_part\");\n\tgarbageFeatures.push_back(L\"collides_part\");\n\tgarbageFeatures.push_back(L\"bird strike\");\n\tgarbageFeatures.push_back(L\"hijacked_part\");\n\tgarbageFeatures.push_back(L\"including_prev_unigram\");\n\tgarbageFeatures.push_back(L\"including_the_prev_bigram\");\n\tgarbageFeatures.push_back(L\"PERSON_entity_type\");\n\n\tlocationFeatures.push_back(L\"into_prev_unigram\");\n\tlocationFeatures.push_back(L\"near_prev_unigram\");\n\tlocationFeatures.push_back(L\"over_the_prev_bigram\");\n\tlocationFeatures.push_back(L\"north_of_prev_bigram\");\n\tlocationFeatures.push_back(L\"mountains_part\");\n\tlocationFeatures.push_back(L\"mount_part\");\n\tlocationFeatures.push_back(L\"at_prev_unigram\");\n\tlocationFeatures.push_back(L\"takeoff_from_prev_bigram\");\n\tlocationFeatures.push_back(L\"landing_at_prev_bigram\");\n\tlocationFeatures.push_back(L\"river_part\");\n\n\tcountryOrGarbageLocFeatures.push_back(L\"belgium\");\n\tcountryOrGarbageLocFeatures.push_back(L\"finland\");\n\tcountryOrGarbageLocFeatures.push_back(L\"norway\");\n\tcountryOrGarbageLocFeatures.push_back(L\"scotland\");\n\tcountryOrGarbageLocFeatures.push_back(L\"egypt\");\n\tcountryOrGarbageLocFeatures.push_back(L\"ireland\");\n\tcountryOrGarbageLocFeatures.push_back(L\"canada\");\n\tcountryOrGarbageLocFeatures.push_back(L\"france\");\n\n\tlocLikeFeatures.push_back(L\"LOCATION_entity_type\");\n\n\tlocOrCoFeatures.push_back(L\"over_prev_unigram\");\n\tlocOrCoFeatures.push_back(L\"in_prev_unigram\");\n\n\tlocOrGarLocFeatures.push_back(L\"indiana\");\n\tlocOrGarLocFeatures.push_back(L\"california\");\n\tlocOrGarLocFeatures.push_back(L\"to_the_prev_bigram\");\n\n\tlocationOnlyFeatures.push_back(L\"LOCATION_entity_type\");\n\n\tatLeastOneLocationIfLocFeatures.push_back(L\"LOCATION_entity_type\");\n\n\ttypedef FeatureImpliesClassConstraint<BMMFactorConstraintView> FICC;\n\tconstraints.push_back(make_shared<FICC>(dataset, flightFeatures, \n\t\t\t\tflightClasses, 0.8, BMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<FICC>(dataset, airlineFeatures, \n\t\t\t\tairlineClasses, 0.9, BMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<FICC>(dataset,\n\t\t\t\tmodelFeatures, modelClasses, 0.9, BMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<FICC>(dataset,\n\t\t\t\tgarbageFeatures, garbageClasses, 0.8, BMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<FICC>(dataset,\n\t\t\t\tlocationFeatures, locationClasses, 0.7, BMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<FICC>(dataset,\n\t\t\t\tlocOrCoFeatures, locOrCoClasses, 0.8, BMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<FICC>(dataset,\n\t\t\t\tcountryOrGarbageLocFeatures, countryOrGarbageLocClasses, 0.9, \n\t\t\t\tBMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<FICC>(dataset,\n\t\t\t\tlocLikeFeatures, locLikeClasses, 0.9, BMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<FICC>(dataset,\n\t\t\t\tlocOrGarLocFeatures, locOrGarLocClasses, 0.9, BMMFactorConstraintView()));\n\tconstraints.push_back(make_shared<ClassRequiresFeatureConstraint>(dataset,\n\t locationOnlyFeatures, locationOnlyClasses, 0.1));\n\tconstraints.push_back(make_shared<AtMostNOfClassConstraint>(\n\t\t\t\tatMostOneCountryClasses, 1.0));\n\tconstraints.push_back(make_shared<AtMostNOfClassConstraint>(\n\t\t\t\tatMostTwoLocationsClasses, 2.0));\n\tconstraints.push_back(make_shared<AtLeastNOfClassIfFeatureConstraint>(\n\t\t\t\tdataset, atLeastOneLocationIfLocClasses, \n\t\t\t\tatLeastOneLocationIfLocFeatures, 1.0));\n}\n\nstruct DataDumper {\n\tvoid postE(unsigned int i, double ll, const DataSet<Document>& data) const {\n\t\twcout << L\"Iteration \" << i << L\", LL=\" << ll << endl;\n\t}\n\tvoid postE(const DataSet<Document>& data) const {\n\n\t}\n\tvoid postM(unsigned int i, const DataSet<Document>& data) const {}\n};\n\nclass FixMe {};\n\nint main(int argc, char** argv) {\n\tsrand((unsigned int)time(NULL));\n\tif (argc < 2 ) {\n\t\tcerr << \"Must provide data file\" << endl;\n\t} else {\n\t\tDataSet_ptr data = make_shared<GraphicalModel::DataSet<Document> >();\n\t\tloadData(argv[1], data);\n\t\tDocument::finishedLoading();\n\t\twcout << \"\\n\\n\\nTrying PR...\" << endl;\n\t\tvector<shared_ptr<Constraint<Document> > > constraints;\n\t\tcreateConstraints(*data, constraints);\n\t\t//GraphicalModel::PREM<Document> prModel(*data, NUM_CLASSES, constraints);\n\t\t//prModel.em(*data, 15, Reporter());\n\t\tconst char* source = \"posterior regularization main\";\n\t\tconst char* msg = \"Change to logging broke this. Fix it if you plan to use it.\";\n\t\tthrow FixMe();\n\t\t//applyModel(\"PR\", prModel, *data);\n\t}\n}\n\n", "meta": {"hexsha": "e25f3c0c60522b113de4af0b8bac1b39160fc71e", "size": 22702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PosteriorRegularization/PosteriorRegularization.cpp", "max_stars_repo_name": "BBN-E/serif", "max_stars_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T19:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:57:00.000Z", "max_issues_repo_path": "src/PosteriorRegularization/PosteriorRegularization.cpp", "max_issues_repo_name": "BBN-E/serif", "max_issues_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "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/PosteriorRegularization/PosteriorRegularization.cpp", "max_forks_repo_name": "BBN-E/serif", "max_forks_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "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.0136612022, "max_line_length": 90, "alphanum_fraction": 0.7097172055, "num_tokens": 6109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.1609284833542049}}
{"text": "#include <ros/ros.h>\n#include <humanoid_catching/PredictFall.h>\n#include <humanoid_catching/CreateMeshCache.h>\n#include <humanoid_catching/FallPoint.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <ode/ode.h>\n#include <iostream>\n#include <tf/transform_listener.h>\n#include <geometry_msgs/WrenchStamped.h>\n#include <boost/math/constants/constants.hpp>\n#include <tf/tf.h>\n#include <geometric_shapes/shape_operations.h>\n#include <map>\n#include <iterator>\n#include <algorithm>\n\n#define PROFILE 0\n\n#if(PROFILE)\n#include <google/profiler.h>\n#endif\n\nnamespace\n{\nusing namespace std;\nusing namespace humanoid_catching;\n\n\n//! Default weight in kg\nstatic const double MASS_DEFAULT = 0.896;\nstatic const double HEIGHT_DEFAULT = 1.757;\nstatic const double RADIUS_DEFAULT = 0.03175;\n\nstatic const int MAX_CONTACTS = 20;\n\nstatic const double PI = boost::math::constants::pi<double>();\n\nstruct MeshCacheEntry {\n    dTriMeshDataID mesh;\n    double* vertices;\n    dTriIndex* triangles;\n};\n\ntypedef typename std::map<string, MeshCacheEntry> MeshCache;\n\n\nstruct Model\n{\n    dBodyID body;  // the dynamics body\n    dGeomID geom;  // geometries representing this body\n    string name; // name of the body\n    string meshResource; // path to the mesh\n    geometry_msgs::Vector3 meshScale; // scale of the mesh\n};\n\nstruct SimulationState {\n    //! Simulation time\n    double t;\n\n    //! Steps\n    unsigned int steps;\n\n    //! Is in contact\n    bool isInContact;\n\n    //! Is in contact with end effector\n    bool isInContactWithEndEffector;\n\n    //! Ground plane\n    dGeomID ground;\n\n    //! Simulation space\n    dSpaceID space;\n\n    //! Ground link for joint\n    dBodyID groundLink;\n\n    //! World\n    dWorldID world;\n\n    //! Joint group for collisions\n    dJointGroupID contactgroup;\n\n    //! Joint group for joint between ground and humanoid\n    dJointGroupID groundToBodyJG;\n\n    //! Joint between ground and humanoid\n    dJointID groundJoint;\n\n    //! Humanoid\n    Model humanoid;\n\n    //! End effectors\n    vector<Model> endEffectors;\n\n    //! Links (non end-effectors)\n    vector<Model> links;\n\n    //! Contacts with end effectors\n    vector<boost::optional<dContactGeom> > eeContacts;\n\n    //! Number of contacts with end effector\n    vector<unsigned int> eeContactCount;\n\n    SimulationState() {\n        isInContact = false;\n        isInContactWithEndEffector = false;\n        t = 0.0;\n        steps = 0;\n    }\n\n    int whichEndEffector(const dBodyID b1, const dBodyID b2) const\n    {\n        for (unsigned int i = 0; i < endEffectors.size(); ++i)\n        {\n            if (endEffectors[i].body == b1 || endEffectors[i].body == b2)\n            {\n                return i;\n            }\n        }\n        return -1;\n    }\n\n    int whichLink(const dBodyID b1, const dBodyID b2) const\n    {\n        for (unsigned int i = 0; i < links.size(); ++i)\n        {\n            if (links[i].body == b1 || links[i].body == b2)\n            {\n                return i;\n            }\n        }\n        return -1;\n    }\n\n    void destroyWorld() {\n\n        for (unsigned int i = 0; i < links.size(); ++i) {\n            if(dGeomGetClass(links[i].geom) == dTriMeshClass) {\n                // Get the trimesh id.\n                dTriMeshDataID trimesh = dGeomTriMeshGetTriMeshDataID(links[i].geom);\n\n                // Destroy the temporal coherence cache\n                dGeomTriMeshClearTCCache(links[i].geom);\n            }\n\n            // Destroy geometries.\n            dGeomDestroy(links[i].geom);\n        }\n\n        for (unsigned int i = 0; i < endEffectors.size(); ++i) {\n            if(dGeomGetClass(endEffectors[i].geom) == dTriMeshClass) {\n                // Get the trimesh id.\n                dTriMeshDataID trimesh = dGeomTriMeshGetTriMeshDataID(endEffectors[i].geom);\n\n                // Destroy the temporal coherence cache\n                dGeomTriMeshClearTCCache(endEffectors[i].geom);\n            }\n\n            // Destroy geometries.\n            dGeomDestroy(endEffectors[i].geom);\n        }\n\n        dJointGroupDestroy(contactgroup);\n        dJointGroupDestroy(groundToBodyJG);\n        dSpaceDestroy(space);\n        dWorldDestroy(world);\n    }\n\n    void initWorld()\n    {\n        world = dWorldCreate();\n        space = dSimpleSpaceCreate(0);\n        // TODO: Assess this parameter\n        // space = dHashSpaceCreate(0);\n        contactgroup = dJointGroupCreate(0);\n        ground = dCreatePlane(space, 0, 0, 1, 0);\n        dWorldSetGravity(world, 0, 0, -9.81);\n        dWorldSetERP(world, 0.2);\n        // TODO: Assess this parameter\n        dWorldSetCFM(world, 1e-5);\n        // TODO: Assess this parameter\n        dWorldSetContactSurfaceLayer(world, 0.001);\n    }\n\n    void initHumanoid(const geometry_msgs::Pose& pose, const geometry_msgs::Twist& velocity,\n                      double humanoidMass, double humanoidRadius, double humanoidHeight)\n    {\n\n        // Create the object\n        humanoid.body = dBodyCreate(world);\n\n        dBodySetPosition(humanoid.body, pose.position.x, pose.position.y, pose.position.z);\n        dBodySetLinearVel(humanoid.body, velocity.linear.x, velocity.linear.y, velocity.linear.z);\n        dBodySetAngularVel(humanoid.body, velocity.angular.x, velocity.angular.y, velocity.angular.z);\n\n        const dReal q[] = {pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w};\n        dBodySetQuaternion(humanoid.body, q);\n\n        dMass m;\n\n        // Use the inertia matrix for a point mass rotating about the ground.\n        // Use a very small sphere to mimic a point mass, which was not working properly.\n        dMassSetSphereTotal(&m, humanoidMass, 0.01);\n        dBodySetMass(humanoid.body, &m);\n        humanoid.geom = dCreateCylinder(space, humanoidRadius, humanoidHeight);\n        dGeomSetBody(humanoid.geom, humanoid.body);\n    }\n\n    void initGroundJoint(const geometry_msgs::Point& base)\n    {\n        ROS_DEBUG(\"Creating ground joint at [%f, %f %f]\", base.x, base.y, base.z);\n\n        // Create the ground object\n        groundLink = dBodyCreate(world);\n        groundToBodyJG = dJointGroupCreate(0);\n\n        dBodySetPosition(groundLink, base.x, base.y, base.z);\n\n        // Set it as unresponsive to forces\n        dBodySetKinematic(groundLink);\n\n        groundJoint = dJointCreateBall(world, groundToBodyJG);\n        dJointAttach(groundJoint, humanoid.body, groundLink);\n\n        dJointSetBallAnchor(groundJoint, base.x, base.y, base.z);\n    }\n\n    Model initLink(const string& name, const geometry_msgs::Pose& link, const geometry_msgs::Twist& velocity, const Shape& shape, const MeshCache& meshCache) const\n    {\n        // Create the object\n        Model object;\n        object.name = name;\n        object.body = dBodyCreate(world);\n\n        if (shape.type == Shape::BOX) {\n            ROS_DEBUG(\"Adding box @ %f %f %f (%f %f %f %f) with dimensions [%f %f %f]\",\n                    link.position.x, link.position.y, link.position.z,\n                    link.orientation.x, link.orientation.y, link.orientation.z, link.orientation.w,\n                    shape.dimensions[0], shape.dimensions[1], shape.dimensions[2]);\n\n            object.geom = dCreateBox(space, shape.dimensions[0],\n                                     shape.dimensions[1],\n                                     shape.dimensions[2]);\n        }\n        else if (shape.type == Shape::CYLINDER) {\n            ROS_DEBUG(\"Adding cylinder @ %f %f %f (%f %f %f %f) with dimensions [%f %f]\",\n                    link.position.x, link.position.y, link.position.z,\n                    link.orientation.x, link.orientation.y, link.orientation.z, link.orientation.w,\n                    shape.dimensions[0], shape.dimensions[1]);\n\n            object.geom = dCreateCylinder(space, shape.dimensions[0], shape.dimensions[1]);\n        }\n        else if (shape.type == Shape::SPHERE) {\n            ROS_DEBUG(\"Adding sphere @ %f %f %f (%f %f %f %f) with dimensions [%f]\",\n                    link.position.x, link.position.y, link.position.z,\n                    link.orientation.x, link.orientation.y, link.orientation.z, link.orientation.w,\n                    shape.dimensions[0]);\n\n            object.geom = dCreateSphere(space, shape.dimensions[0]);\n        }\n        else if (shape.type == Shape::MESH) {\n            ROS_DEBUG(\"Adding mesh @ %f %f %f (%f %f %f %f) with vertices [%lu] and indices [%lu]\",\n                    link.position.x, link.position.y, link.position.z,\n                    link.orientation.x, link.orientation.y, link.orientation.z, link.orientation.w,\n                    shape.vertices.size(), shape.triangles.size());\n\n            dTriMeshDataID data = NULL;\n            if (meshCache.at(name).mesh) {\n                data = meshCache.at(name).mesh;\n            }\n            else {\n                ROS_ERROR(\"Mesh for link [%s] could not be found in cache\", name.c_str());\n            }\n\n            object.geom = dCreateTriMesh(space, data, NULL, NULL, NULL);\n            object.meshResource = shape.meshResource;\n            object.meshScale = shape.meshScale;\n        }\n        else {\n            ROS_ERROR(\"Unsupported shape type\");\n        }\n\n        dGeomSetBody(object.geom, object.body);\n\n        dBodySetPosition(object.body, link.position.x, link.position.y, link.position.z);\n        dBodySetLinearVel(object.body, velocity.linear.x, velocity.linear.y, velocity.linear.z);\n        dBodySetAngularVel(object.body, velocity.angular.x, velocity.angular.y, velocity.angular.z);\n\n        const dReal q[] = {link.orientation.x, link.orientation.y, link.orientation.z, link.orientation.w};\n        dBodySetQuaternion(object.body, q);\n\n        // Set it as unresponsive to forces\n        dBodySetKinematic(object.body);\n\n        return object;\n    }\n\n    void nearCollisionCallback(dGeomID o1, dGeomID o2)\n    {\n        // Ignore ground contacts\n        if (o1 == ground || o2 == ground)\n        {\n            ROS_DEBUG(\"Ignoring ground contact\");\n            return;\n        }\n\n        dBodyID b1 = dGeomGetBody(o1);\n        dBodyID b2 = dGeomGetBody(o2);\n\n        // Check if either contact is the humanoid\n        if (b1 != humanoid.body && b2 != humanoid.body) {\n            ROS_DEBUG(\"Skipping non-humanoid contact\");\n            return;\n        }\n\n        ROS_DEBUG(\"Possible contact detected at time [%f]\", t);\n        isInContact = true;\n\n        dContact contact[MAX_CONTACTS];\n        for (int i = 0; i < MAX_CONTACTS; i++)\n        {\n            contact[i].surface.mode = dContactSoftCFM;\n            contact[i].surface.mu = dInfinity;\n            // TODO: Assess this parameter\n            contact[i].surface.mu2 = 0;\n            // TODO: Assess this parameter\n            contact[i].surface.soft_cfm = 0.01;\n        }\n\n        // Always compute contact with the humanoid as object 1, such that the contact normal\n        // is towards the humanoid\n        dGeomID firstObj = o1 == humanoid.geom ? o1 : o2;\n        dGeomID secondObj = o1 == humanoid.geom ? o2 : o1;\n\n        ROS_DEBUG(\"Computing contact between human and link at time [%f]\", t);\n        if (int numc = dCollide(firstObj, secondObj, MAX_CONTACTS, &contact[0].geom, sizeof(dContact)))\n        {\n            for (int i = 0; i < numc; i++)\n            {\n                dJointID c = dJointCreateContact(world, contactgroup, &contact[i]);\n                dJointAttach(c, b1, b2);\n\n                // Set that the human is in contact\n                int whichEE = whichEndEffector(b1, b2);\n                int link = whichLink(b1, b2);\n\n                isInContact = true;\n\n                // Determine if this contact should be saved\n                if (whichEE != -1) {\n                    ROS_DEBUG(\"Contact between human and end-effector [%s] at time [%f]. Previous contact count was %u. Contact position [%f, %f, %f] and normal [%f, %f, %f] at depth [%f]\",\n                             endEffectors[whichEE].name.c_str(), t, eeContactCount[whichEE], contact[i].geom.pos[0], contact[i].geom.pos[1], contact[i].geom.pos[2],\n                             contact[i].geom.normal[0], contact[i].geom.normal[1], contact[i].geom.normal[2],\n                             contact[i].geom.depth);\n\n                    assert(firstObj == humanoid.geom && secondObj == endEffectors[whichEE].geom\n                           && firstObj == contact[i].geom.g1 && secondObj == contact[i].geom.g2);\n\n                    // Average all the contacts for the end effector\n                    if (eeContactCount[whichEE] == 0) {\n                        eeContacts[whichEE] = contact[i].geom;\n                    }\n                    else {\n                        for (unsigned int j = 0; j < 3; ++j) {\n                            eeContacts[whichEE]->pos[j] = (contact[i].geom.pos[j] + (eeContactCount[whichEE] * eeContacts[whichEE]->pos[j])) / double(eeContactCount[whichEE] + 1);\n                        }\n                        for (unsigned int j = 0; j < 3; ++j) {\n                            eeContacts[whichEE]->normal[j] = (contact[i].geom.normal[j] + (eeContactCount[whichEE] * eeContacts[whichEE]->normal[j])) / double(eeContactCount[whichEE] + 1);\n                        }\n                    }\n                    ++eeContactCount[whichEE];\n                    isInContactWithEndEffector = true;\n                } else if (link != -1) {\n                    ROS_DEBUG(\"Contact between human and link [%s] at time [%f]\", links[link].name.c_str(), t);\n                }\n                else {\n                    ROS_WARN(\"Contact with unknown link at time [%f]\", t);\n                }\n            }\n        }\n        else {\n            ROS_DEBUG(\"Collided contacts but received zero contacts\");\n        }\n    }\n\n    static void staticNearCallback(void* data, dGeomID o1, dGeomID o2)\n    {\n        SimulationState* self = static_cast<SimulationState*>(data);\n        self->nearCollisionCallback(o1, o2);\n    }\n\n    void simLoop(double stepSize)\n    {\n        dSpaceCollide(space, this, &SimulationState::staticNearCallback);\n        dWorldStep(world, stepSize);\n        dJointGroupEmpty(contactgroup);\n    }\n};\n\nclass FallPredictor\n{\nprivate:\n    //! Publisher for the fall visualization\n    ros::Publisher fallVizPub;\n\n    //! Publisher for the contact visualization\n    ros::Publisher contactVizPub;\n\n    //! Publisher for the initial position\n    ros::Publisher initialPoseVizPub;\n\n    //! Publisher for the initial velocity\n    ros::Publisher initialVelocityVizPub;\n\n    //! Node handle\n    ros::NodeHandle nh;\n\n    //! Private nh\n    ros::NodeHandle pnh;\n\n    //! Fall prediction Service\n    ros::ServiceServer fallPredictionService;\n\n    //! Cache init Service\n    ros::ServiceServer initCacheService;\n\n    //! Height of object\n    double humanoidHeight;\n\n    //! Radius of object\n    double humanoidRadius;\n\n    //! Mass of the humanoid\n    double humanoidMass;\n\n    //! Position of base\n    geometry_msgs::Point base;\n\n    //! Mesh cache\n    MeshCache meshCache;\n\n    //! Previous path size. Used for clearing visualization markers\n    unsigned int lastPathSize;\n\n    #if(PROFILE)\n    //! Gprofile name\n    string profileName;\n    #endif\n\npublic:\n    FallPredictor(const string& name) :\n        pnh(\"~\")\n    {\n        pnh.param(\"humanoid_height\", humanoidHeight, HEIGHT_DEFAULT);\n        pnh.param(\"humanoid_radius\", humanoidRadius, RADIUS_DEFAULT);\n        pnh.param(\"humanoid_mass\", humanoidMass, MASS_DEFAULT);\n\n        fallVizPub = nh.advertise<visualization_msgs::MarkerArray>(\n                         \"/\" + name + \"/projected_path\", 1);\n\n        contactVizPub = nh.advertise<visualization_msgs::MarkerArray>(\n                            \"/\" + name + \"/contacts\", 1);\n\n        initialPoseVizPub = nh.advertise<geometry_msgs::PoseStamped>(\n                                \"/\" + name + \"/initial_pose\", 1);\n\n        initialVelocityVizPub = nh.advertise<geometry_msgs::WrenchStamped>(\n                                    \"/\" + name + \"/initial_velocity\", 1);\n\n        fallPredictionService = nh.advertiseService(\"/\" + name + \"/predict_fall\",\n                                &FallPredictor::predict, this);\n\n        initCacheService = nh.advertiseService(\"/\" + name + \"/create_mesh_cache\",\n                                &FallPredictor::initCache, this);\n\n        initODE();\n\n        #if(PROFILE)\n        profileName = \"/tmp/\" + ros::this_node::getName() + \".prof\";\n        ProfilerStart(profileName.c_str());\n        #endif\n\n        lastPathSize = 0;\n    }\n\n    ~FallPredictor() {\n        #if(PROFILE)\n        ProfilerStop();\n        #endif\n\n        // Clear out the mesh caches\n        for (MeshCache::iterator entry = meshCache.begin(); entry != meshCache.end(); ++entry) {\n            // Destroy the mesh.\n            dGeomTriMeshDataDestroy(entry->second.mesh);\n            delete[] entry->second.triangles;\n            delete[] entry->second.vertices;\n        }\n\n        // Clean up\n        destroyODE();\n    }\n\nprivate:\n\n    void initODE()\n    {\n        dInitODE();\n    }\n\n    void destroyODE()\n    {\n        dCloseODE();\n    }\n\n    void publishContacts(const vector<humanoid_catching::Contact>& contacts, const std_msgs::Header& header) const\n    {\n        visualization_msgs::MarkerArray arrows;\n        for (unsigned int i = 0; i < contacts.size(); ++i)\n        {\n            if (!contacts[i].is_in_contact)\n            {\n                visualization_msgs::Marker deleteContact;\n                deleteContact.ns = \"contacts\";\n                deleteContact.id = i;\n                deleteContact.header = header;\n                deleteContact.action = visualization_msgs::Marker::DELETE;\n                arrows.markers.push_back(deleteContact);\n            }\n            else\n            {\n                visualization_msgs::Marker arrow;\n                arrow.header = header;\n                arrow.ns = \"contacts\";\n                arrow.id = i;\n                arrow.type = visualization_msgs::Marker::ARROW;\n                arrow.points.resize(2);\n                arrow.points[0] = contacts[i].position;\n                arrow.points[1].x = contacts[i].normal.x;\n                arrow.points[1].y = contacts[i].normal.y;\n                arrow.points[1].z = contacts[i].normal.z;\n\n                arrow.scale.x = 0.025;\n                arrow.scale.y = 0.050;\n\n                arrow.color.r = 1.0;\n                arrow.color.a = 1.0;\n                arrows.markers.push_back(arrow);\n            }\n        }\n        contactVizPub.publish(arrows);\n    }\n\n    visualization_msgs::Marker textMarker(const string& ns, const std_msgs::Header& header, const unsigned int i, const string& name,\n                                          const geometry_msgs::Pose& pose) const {\n        visualization_msgs::Marker text;\n        text.header = header;\n        text.ns = ns + \"_text\";\n        text.id = i;\n\n        text.scale.x = 1.0;\n        text.scale.y = 1.0;\n        text.scale.z = 0.05;\n        text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n        text.pose = pose;\n        text.text = name;\n\n        // Text is black\n        text.color.r = text.color.b = text.color.g = 1.0f;\n        text.color.a = 1.0;\n        return text;\n    }\n\n    visualization_msgs::Marker objectMarker(const string& ns, const std_msgs::Header& header, unsigned int i, const Model& model, std_msgs::ColorRGBA color) const {\n        visualization_msgs::Marker marker;\n        marker.header = header;\n        marker.ns = ns;\n        marker.id = i;\n        marker.pose = getBodyPose(model.body);\n\n        if(dGeomGetClass(model.geom) == dBoxClass) {\n            marker.type = visualization_msgs::Marker::CUBE;\n            vector<double> objectSize = getGeomBoxSize(model.geom);\n\n            if (objectSize[0] <= 0.0 || objectSize[1] <= 0.0 || objectSize[2] <= 0.0) {\n                ROS_DEBUG(\"Cannot publish zero scale marker\");\n                objectSize[0] = objectSize[1] = objectSize[2] = 0.1;\n            }\n\n            marker.scale.x = objectSize[0];\n            marker.scale.y = objectSize[1];\n            marker.scale.z = objectSize[2];\n        }\n        else if(dGeomGetClass(model.geom) == dCylinderClass) {\n            marker.type = visualization_msgs::Marker::CYLINDER;\n            vector<double> objectSize = getGeomCylinderSize(model.geom);\n\n            if (objectSize[0] <= 0.0 || objectSize[1] <= 0.0) {\n                ROS_DEBUG(\"Cannot publish zero scale marker\");\n                objectSize[0] = objectSize[1] = 0.1;\n            }\n\n            marker.scale.x = 2 * objectSize[0]; // x diameter\n            marker.scale.y = 2 * objectSize[0]; // y diameter\n            marker.scale.z = objectSize[1]; // height\n        }\n        else if(dGeomGetClass(model.geom) == dSphereClass) {\n            marker.type = visualization_msgs::Marker::SPHERE;\n            double radius = getGeomSphereSize(model.geom);\n\n            if (radius <= 0.0) {\n                ROS_DEBUG(\"Cannot publish zero scale marker\");\n                radius = 0.1;\n            }\n\n            marker.scale.x = 2 * radius; // diameter\n        }\n        else if(dGeomGetClass(model.geom) == dTriMeshClass) {\n            marker.type = visualization_msgs::Marker::MESH_RESOURCE;\n            marker.mesh_resource = model.meshResource;\n            marker.scale = model.meshScale;\n            marker.mesh_use_embedded_materials = true;\n        }\n        else {\n            ROS_ERROR(\"Unsupported type\");\n        }\n\n        marker.color = color;\n        return marker;\n    }\n\n    void publishEeViz(const vector<Model>& endEffectors, const vector<Model>& links, const std_msgs::Header& header) const\n    {\n        visualization_msgs::MarkerArray markers;\n        for (unsigned int i = 0; i < endEffectors.size(); ++i){\n            // Object is yellow\n            std_msgs::ColorRGBA c;\n            c.r = 1.0f;\n            c.g = 1.0f;\n            c.a = 0.5;\n            markers.markers.push_back(objectMarker(\"end_effectors\", header, i, endEffectors[i], c));\n            markers.markers.push_back(textMarker(\"end_effectors\", header, i, endEffectors[i].name, getBodyPose(endEffectors[i].body)));\n        }\n\n        for (unsigned int i = 0; i < links.size(); ++i){\n            // Object is blue\n            std_msgs::ColorRGBA c;\n            c.b = 1.0f;\n            c.a = 0.5;\n            markers.markers.push_back(objectMarker(\"links\", header, i, links[i], c));\n            markers.markers.push_back(textMarker(\"links\", header, i, links[i].name, getBodyPose(links[i].body)));\n        }\n        fallVizPub.publish(markers);\n    }\n\n    visualization_msgs::Marker poseMarker(unsigned int i, const geometry_msgs::Pose& pose, const std_msgs::Header& header) const {\n        visualization_msgs::Marker cyl;\n        cyl.header = header;\n        cyl.ns = \"pole\";\n        cyl.id = i;\n        cyl.type = visualization_msgs::Marker::CYLINDER;\n        cyl.pose.orientation = orientPose(pose.orientation, false);\n        cyl.pose.position = pose.position;\n        cyl.scale.x = humanoidRadius;\n        cyl.scale.y = humanoidRadius;\n        cyl.scale.z = humanoidHeight;\n\n        // Cylinder is green unless it is the initial pose and then it is yellow\n        if (i == 0) {\n            cyl.color.r = 1.0f;\n            cyl.color.g = 1.0f;\n            cyl.color.a = 0.5;\n        }\n        else {\n            cyl.color.g = 1.0f;\n            cyl.color.a = 0.5;\n        }\n        return cyl;\n    }\n\n    visualization_msgs::Marker comMarker(unsigned int i, const geometry_msgs::Pose& pose, const std_msgs::Header& header) const {\n\n        visualization_msgs::Marker point;\n        point.header = header;\n        point.ns = \"com\";\n        point.id = i;\n        point.type = visualization_msgs::Marker::SPHERE;\n        point.pose.position = pose.position;\n        point.color.r = 1.0f;\n        point.color.a = 1.0f;\n        point.scale.x = point.scale.y = point.scale.z = 0.05;\n        return point;\n    }\n\n    void publishPathViz(const vector<geometry_msgs::Pose>& path, const std_msgs::Header& header) const\n    {\n        visualization_msgs::MarkerArray markers;\n        unsigned int i;\n        for (i = 0; i < path.size(); ++i)\n        {\n            markers.markers.push_back(poseMarker(i + 1, path[i], header));\n            markers.markers.push_back(comMarker(i + 1, path[i], header));\n        }\n\n        for (; i < lastPathSize; ++i) {\n            visualization_msgs::Marker cyl;\n            cyl.header = header;\n            cyl.ns = \"pole\";\n            cyl.id = i + 1;\n            cyl.action = visualization_msgs::Marker::DELETE;\n            markers.markers.push_back(cyl);\n\n            visualization_msgs::Marker point;\n            point.header = header;\n            point.ns = \"com\";\n            point.id = i + 1;\n            point.action = visualization_msgs::Marker::DELETE;\n            markers.markers.push_back(point);\n        }\n        fallVizPub.publish(markers);\n    }\n\n    void publishPoseAndVelocity(std_msgs::Header& header, geometry_msgs::Pose& pose, geometry_msgs::Twist& velocity)\n    {\n        if (initialPoseVizPub.getNumSubscribers() > 0)\n        {\n            geometry_msgs::PoseStamped ps;\n            ps.header = header;\n            ps.pose = pose;\n            initialPoseVizPub.publish(ps);\n        }\n        if (initialVelocityVizPub.getNumSubscribers() > 0)\n        {\n            geometry_msgs::WrenchStamped ws;\n            ws.header = header;\n            ws.wrench.force = velocity.linear;\n            ws.wrench.torque = velocity.angular;\n            initialVelocityVizPub.publish(ws);\n        }\n    }\n\n    static geometry_msgs::Quaternion quaternionFromVector(const geometry_msgs::Vector3& input)\n    {\n        tf::Vector3 axisVector(input.x, input.y, input.z);\n        tf::Vector3 upVector(0.0, 0.0, 1.0);\n        tf::Vector3 rightVector = axisVector.cross(upVector);\n        rightVector.normalized();\n        tf::Quaternion q(rightVector, -1.0 * acos(axisVector.dot(upVector)));\n        q.normalize();\n        geometry_msgs::Quaternion orientation;\n        tf::quaternionTFToMsg(q, orientation);\n        return orientation;\n    }\n\n    static geometry_msgs::Vector3 arrayToVector(const dReal* aArray)\n    {\n        geometry_msgs::Vector3 result;\n        result.x = aArray[0];\n        result.y = aArray[1];\n        result.z = aArray[2];\n        return result;\n    }\n\n    static geometry_msgs::Point arrayToPoint(const dReal* aArray)\n    {\n        geometry_msgs::Point result;\n        result.x = aArray[0];\n        result.y = aArray[1];\n        result.z = aArray[2];\n        return result;\n    }\n\n    static geometry_msgs::Quaternion arrayToQuat(const dReal* aArray)\n    {\n        geometry_msgs::Quaternion result;\n        result.x = aArray[0];\n        result.y = aArray[1];\n        result.z = aArray[2];\n        result.w = aArray[3];\n        return result;\n    }\n\n    static geometry_msgs::Pose getBodyPose(dBodyID body)\n    {\n        const dReal* position = dBodyGetPosition(body);\n        const dReal* orientation = dBodyGetQuaternion(body);\n        geometry_msgs::Pose pose;\n        pose.position = arrayToPoint(position);\n        pose.orientation = arrayToQuat(orientation);\n        return pose;\n    }\n\n    static geometry_msgs::Twist getBodyTwist(dBodyID body)\n    {\n        const dReal* linearVelocity = dBodyGetLinearVel(body);\n        const dReal* angularVelocity = dBodyGetAngularVel(body);\n        geometry_msgs::Twist twist;\n        twist.linear = arrayToVector(linearVelocity);\n        twist.angular = arrayToVector(angularVelocity);\n        return twist;\n    }\n\n    static tf::Vector3 quatToVector(const geometry_msgs::Quaternion& orientationMsg)\n    {\n        tf::Quaternion orientation;\n        tf::quaternionMsgToTF(orientationMsg, orientation);\n        tf::Transform rotation(orientation);\n        tf::Vector3 xAxis(1, 0, 0);\n        tf::Vector3 r = rotation.getBasis() * xAxis;\n        return r;\n    }\n\n    vector<double> getPoleInertiaMatrix() const\n    {\n        vector<double> I(9);\n        I[0] = I[4] = 1 / 12.0 * humanoidMass * pow(humanoidHeight, 2) + 0.25 * humanoidMass * pow(humanoidRadius, 2);\n        I[8] = 0.5 * humanoidMass * pow(humanoidRadius, 2);\n        return I;\n    }\n\n    /**\n     * Given a base position, pole length, and an orientation, compute the COM position\n     */\n    geometry_msgs::Point computeCOMPosition(const geometry_msgs::Quaternion& orientation) const\n    {\n        ROS_DEBUG(\"Computing COM position using base position: [%f %f %f]\", base.x, base.y, base.z);\n\n        // Rotate the up vector\n        tf::Quaternion rotation(orientation.x, orientation.y, orientation.z, orientation.w);\n\n        tf::Vector3 initialVector(1, 0, 0);\n        tf::Vector3 rotatedVector = tf::quatRotate(rotation, initialVector);\n\n        // Now set the height\n        rotatedVector *= humanoidHeight / 2.0;\n\n        // Now offset by the base\n        tf::Vector3 offset(base.x, base.y, base.z);\n        rotatedVector += offset;\n\n        geometry_msgs::Point result;\n        result.x = rotatedVector.x();\n        result.y = rotatedVector.y();\n        result.z = rotatedVector.z();\n        return result;\n    }\n\n    geometry_msgs::Vector3 computeLinearVelocity(const geometry_msgs::Quaternion& orientationMsg,\n            const geometry_msgs::Vector3& angular) const\n    {\n\n        tf::Vector3 r = quatToVector(orientationMsg);\n\n        // Now set the height\n        r *= humanoidHeight / 2.0;\n        tf::Vector3 w(angular.x, angular.y, angular.z);\n        tf::Vector3 linear = -r.cross(w);\n\n        geometry_msgs::Vector3 linearVelocityMsg;\n        tf::vector3TFToMsg(linear, linearVelocityMsg);\n        return linearVelocityMsg;\n    }\n\n    // Compensate for the model being initial aligned to the x axis and oriented\n    // up\n    static geometry_msgs::Quaternion orientPose(const geometry_msgs::Quaternion& orientationMsg, bool negate)\n    {\n        tf::Quaternion rotation = tf::createQuaternionFromRPY(0, (negate ? -1.0 : 1.0) * PI / 2.0, 0);\n\n        tf::Quaternion orientation;\n        tf::quaternionMsgToTF(orientationMsg, orientation);\n        orientation *= rotation;\n        geometry_msgs::Quaternion result;\n        tf::quaternionTFToMsg(orientation, result);\n        return result;\n    }\n\n    static vector<double> getGeomBoxSize(const dGeomID geom) {\n        dVector3 boxSize;\n        dGeomBoxGetLengths(geom, boxSize);\n        vector<double> vecBoxSize(3);\n        vecBoxSize[0] = boxSize[0];\n        vecBoxSize[1] = boxSize[1];\n        vecBoxSize[2] = boxSize[2];\n        return vecBoxSize;\n    }\n\n    static vector<double> getGeomCylinderSize(const dGeomID geom) {\n        dReal radius, length;\n        dGeomCylinderGetParams(geom, &radius, &length);\n        vector<double> vecCylinderSize(2);\n        vecCylinderSize[0] = radius;\n        vecCylinderSize[1] = length;\n        return vecCylinderSize;\n    }\n\n    static double getGeomSphereSize(const dGeomID geom) {\n        return dGeomSphereGetRadius(geom);\n    }\n\n    bool initCache(humanoid_catching::CreateMeshCache::Request& req,\n                   humanoid_catching::CreateMeshCache::Response& res) {\n\n        for (unsigned int i = 0; i < req.shapes.size(); ++i) {\n            if (req.shapes[i].type == Shape::MESH) {\n                ROS_DEBUG(\"Adding mesh for shape [%s] with vertices [%lu] and indices [%lu] to cache\",\n                        req.names[i].c_str(), req.shapes[i].vertices.size(), req.shapes[i].triangles.size());\n\n                MeshCacheEntry entry;\n                entry.mesh = dGeomTriMeshDataCreate();\n\n                // Clone the arrays\n                entry.vertices = new double[req.shapes[i].vertices.size()];\n                std::copy(req.shapes[i].vertices.begin(), req.shapes[i].vertices.end(), entry.vertices);\n\n                entry.triangles = new dTriIndex[req.shapes[i].triangles.size()];\n                std::copy(req.shapes[i].triangles.begin(), req.shapes[i].triangles.end(), entry.triangles);\n\n                dGeomTriMeshDataBuildDouble(entry.mesh, entry.vertices, 3 * sizeof(dReal), int(req.shapes[i].vertices.size() / 3),\n                                            entry.triangles, int(req.shapes[i].triangles.size()), 3 * sizeof(dTriIndex));\n                meshCache[req.names[i]] = entry;\n            }\n            else {\n                ROS_WARN(\"Unsupported shape type for cache: [%u]\", req.shapes[i].type);\n            }\n        }\n        return true;\n    }\n\n    static double floatEquals(double first, double second) {\n        return fabs(first - second) < 0.001;\n    }\n\n    /**\n     * Check that the COM remains the correct distance from the base\n     */\n    void checkCOM(const geometry_msgs::Point& position) const {\n        double dSquared = pow((position.x - base.x), 2) + pow((position.y - base.y), 2) + pow((position.z - base.z), 2);\n        if (!floatEquals(dSquared, pow(humanoidHeight / 2.0, 2))) {\n            ROS_WARN(\"COM distance is [%f] which is not correct distance from ground joint [%f]\",\n                     sqrt(dSquared), humanoidHeight / 2.0);\n        }\n    }\n\n    bool predict(humanoid_catching::PredictFall::Request& req,\n                 humanoid_catching::PredictFall::Response& res)\n    {\n        ROS_DEBUG(\"Predicting fall in frame %s for %lu end effector links and %lu collision links. Max time [%i], Contact time [%i], Step size [%i], Result Step size [%i]\",\n                 req.header.frame_id.c_str(), req.end_effectors.size(), req.links.size(), req.max_time.nsec, req.contact_time.nsec, req.step_size.nsec, req.result_step_size.nsec);\n\n        nh.param(\"base_x\", base.x, 0.5);\n        nh.param(\"base_y\", base.y, 0.0);\n        nh.param(\"base_z\", base.z, 0.0);\n\n        ROS_DEBUG(\"base x: %f, base y: %f, base z: %f\", base.x, base.y, base.z);\n\n        res.header = req.header;\n\n        SimulationState state;\n        state.initWorld();\n\n        ROS_INFO(\"Initializing humanoid with orientation: (%f %f %f %f) and velocity: (%f %f %f)\",\n                 req.orientation.x, req.orientation.y, req.orientation.z, req.orientation.w,\n                 req.velocity.angular.x, req.velocity.angular.y, req.velocity.angular.z);\n\n        geometry_msgs::Pose humanoidPose;\n        humanoidPose.position = computeCOMPosition(req.orientation);\n        checkCOM(humanoidPose.position);\n\n        ROS_DEBUG(\"Computed CoM position of (%f %f %f)\", humanoidPose.position.x, humanoidPose.position.y, humanoidPose.position.z);\n\n        // TODO: Replace this with linear/angular fusing\n        // TODO: Investigate this further\n        req.velocity.linear = computeLinearVelocity(req.orientation, req.velocity.angular);\n\n        humanoidPose.orientation = orientPose(req.orientation, false);\n\n        state.initHumanoid(humanoidPose, req.velocity, humanoidMass, humanoidRadius, humanoidHeight);\n        publishPoseAndVelocity(req.header, humanoidPose, req.velocity);\n\n        ROS_DEBUG(\"Recalculated humanoid linear velocity: (%f %f %f)\",\n                 req.velocity.linear.x, req.velocity.linear.y, req.velocity.linear.z);\n\n        state.initGroundJoint(base);\n\n        ROS_DEBUG(\"Creating links\");\n        state.endEffectors.resize(req.end_effectors.size());\n        for (unsigned int i = 0; i < req.end_effectors.size(); ++i)\n        {\n            state.endEffectors[i] = state.initLink(req.end_effectors[i].name, req.end_effectors[i].pose.pose, req.end_effectors[i].velocity, req.end_effectors[i].shape, meshCache);\n        }\n\n        state.links.resize(req.links.size());\n        for (unsigned int i = 0; i < req.links.size(); ++i)\n        {\n            state.links[i] = state.initLink(req.links[i].name, req.links[i].pose.pose, req.links[i].velocity, req.links[i].shape, meshCache);\n        }\n        ROS_DEBUG(\"Completed creating links\");\n\n        state.eeContacts.resize(req.end_effectors.size());\n        state.eeContactCount.resize(req.end_effectors.size());\n        res.ground_contact = arrayToPoint(dBodyGetPosition(state.groundLink));\n\n        // Preallocate space for the results\n        res.points.reserve(req.max_time.toSec() / req.step_size.toSec());\n\n        // Execute the simulation loop up to MAX_DURATION seconds\n        bool isOnGround = false;\n        ros::Duration lastTime = ros::Duration(0);\n        for (state.t = req.step_size.toSec(); state.t <= req.max_time.toSec() && (!state.isInContact || state.t <= req.contact_time.toSec()) && !isOnGround; state.t += req.step_size.toSec())\n        {\n            // Clear end effector contacts\n            for (unsigned int i = 0; i < state.eeContacts.size(); ++i) {\n                state.eeContacts[i] = boost::optional<dContactGeom>();\n                state.eeContactCount[i] = 0;\n            }\n\n            // Step forward\n            state.simLoop(req.step_size.toSec());\n            state.steps++;\n\n            geometry_msgs::Pose bodyPose = getBodyPose(state.humanoid.body);\n\n            checkCOM(bodyPose.position);\n\n            ROS_DEBUG(\"Computed CoM position of (%f %f %f)\", bodyPose.position.x, bodyPose.position.y, bodyPose.position.z);\n\n            // Determine if the pole is on the ground and end the simulation\n            // Check if COM is at a position with height approximately equal to the radius\n            if (bodyPose.position.z <= humanoidRadius * (1 + 0.05))\n            {\n                ROS_INFO(\"Humanoid is on the ground. Ending simulation @ [%f]s.\", state.t);\n                isOnGround = true;\n            }\n\n            // Only record results for requested steps\n            if (!isOnGround && !state.isInContact && lastTime != ros::Duration(0) && ros::Duration(state.t) - lastTime < req.result_step_size)\n            {\n                continue;\n            }\n            lastTime = ros::Duration(state.t);\n\n            FallPoint curr;\n\n            // Get the location of the body for the current iteration\n            curr.pose.position = bodyPose.position;\n            curr.pose.orientation = orientPose(bodyPose.orientation, true);\n            curr.velocity = getBodyTwist(state.humanoid.body);\n            curr.time = ros::Duration(state.t);\n\n            ROS_DEBUG(\"Recording pose @ time %f position (%f %f %f) orientation (%f %f %f %f)\",\n                      curr.time.toSec(), curr.pose.position.x, curr.pose.position.y, curr.pose.position.z,\n                      curr.pose.orientation.x, curr.pose.orientation.y, curr.pose.orientation.z, curr.pose.orientation.w);\n\n            curr.contacts.resize(state.eeContacts.size());\n            for (unsigned int i = 0; i < state.eeContacts.size(); ++i)\n            {\n                curr.contacts[i].is_in_contact = !!state.eeContacts[i];\n                if (state.eeContacts[i])\n                {\n                    curr.contacts[i].position = arrayToPoint(state.eeContacts[i]->pos);\n                    curr.contacts[i].normal = arrayToVector(state.eeContacts[i]->normal);\n                    curr.contacts[i].link = req.end_effectors[i];\n                    ROS_DEBUG(\"Setting contact link to %s\", req.end_effectors[i].name.c_str());\n                }\n            }\n\n            res.points.push_back(curr);\n        }\n\n        // Set the mass and inertia matrix\n        res.body_mass = humanoidMass;\n        res.height = humanoidHeight;\n        res.radius = humanoidRadius;\n        res.inertia_matrix = getPoleInertiaMatrix();\n\n        // Publish the path\n        if (fallVizPub.getNumSubscribers() > 0)\n        {\n            ROS_DEBUG(\"Publishing path visualization\");\n            vector<geometry_msgs::Pose> points;\n            for (vector<FallPoint>::const_iterator i = res.points.begin(); i != res.points.end(); ++i)\n            {\n                points.push_back(i->pose);\n            }\n            publishPathViz(points, res.header);\n            lastPathSize = points.size();\n        }\n\n        if (contactVizPub.getNumSubscribers() > 0)\n        {\n            ROS_DEBUG(\"Publishing contact visualization\");\n            for (vector<FallPoint>::const_iterator i = res.points.begin(); i != res.points.end(); ++i)\n            {\n                // Ignore contacts past the contact threshold\n                if (i->time > req.contact_time) {\n                    // This will clear contacts\n                    vector<humanoid_catching::Contact> emptyContacts(i->contacts.size());\n                    publishContacts(emptyContacts, res.header);\n                    break;\n                }\n\n                // Publish contacts from the first set of contacts. This will match what the catching controller\n                // uses\n                bool isInContact = false;\n                for (unsigned int j = 0; j < i->contacts.size(); ++j) {\n                    if (i->contacts[j].is_in_contact) {\n                        isInContact = true;\n                    }\n                }\n\n                if (isInContact) {\n                    publishContacts(i->contacts, res.header);\n                    break;\n                }\n            }\n        }\n\n        if (fallVizPub.getNumSubscribers() > 0){\n            ROS_DEBUG(\"Publishing link visualization\");\n            publishEeViz(state.endEffectors, state.links, res.header);\n        }\n\n        state.destroyWorld();\n        ROS_INFO(\"Completed fall prediction after [%u] steps. Predicted for [%f]s. Recorded [%lu] events. Ended in contact [%u]. Ended in contact with end-effector [%u]\", state.steps, state.t - req.step_size.toSec(), res.points.size(), state.isInContact, state.isInContactWithEndEffector);\n        return true;\n    }\n};\n}\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"fall_predictor\");\n    FallPredictor fp(ros::this_node::getName());\n    ros::spin();\n}\n", "meta": {"hexsha": "59a76185394ad8c1c7707a824ea38c64c874db48", "size": 41407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fall_predictor.cpp", "max_stars_repo_name": "PositronicsLab/humanoid_catching", "max_stars_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "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/fall_predictor.cpp", "max_issues_repo_name": "PositronicsLab/humanoid_catching", "max_issues_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "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/fall_predictor.cpp", "max_forks_repo_name": "PositronicsLab/humanoid_catching", "max_forks_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "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.3857644991, "max_line_length": 289, "alphanum_fraction": 0.5829690632, "num_tokens": 9605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.160877440435993}}
{"text": "#include \"stdafx.h\"\n#include \"searchoptions.h\"\n#include \"utility_funcs.h\"\n#include <boost/filesystem/operations.hpp> \n#include <iostream>  \n#include <regex>\nusing std::cout;\nusing std::endl;\n \n \n  SearchOptions::SearchOptions()\n  {\n    opt::options_description desc(\"All options: (search and listingfiles required)\");\n  }\n\n\n  SearchOptions::~SearchOptions()\n  {\n  }\n\n\n  void SearchOptions::getSizeOperands(){\n\n    std::regex greaterSmallerReg1(\"^([><gs]\\\\d+[kmgtKMGT]?)\");\n    string greaterSmaller1 = get_match(sizeFilter, greaterSmallerReg1);\n\n    std::regex greaterSmallerReg2(\"^[><gs]\\\\d+[kmgtKMGT]?\\\\s*([><gs]\\\\d+[kmgtKMGT]?)\");\n    string greaterSmaller2 = get_match(sizeFilter, greaterSmallerReg2);\n\n    std::regex numvalueReg(\"(\\\\d+)\");\n    std::regex metricPrfixReg(\"([kmgtKMGT]?)$\");\n\n    string numValueStr1 = get_match(greaterSmaller1, numvalueReg);\n    int sizeValue1 = boost::lexical_cast<int>(numValueStr1);\n    string metricPrefix1 = get_match(greaterSmaller1, metricPrfixReg);\n    metricPrefix1 = tolower(metricPrefix1[0]);\n    int metricMult1 = metricPrefix2Integer(metricPrefix1[0]);\n\n    int sizeValue2;\n    int metricMult2;\n    if (greaterSmaller2 != \"\") {\n      string numValueStr2 = get_match(greaterSmaller2, numvalueReg);\n      sizeValue2 = boost::lexical_cast<int>(numValueStr2);\n      string metricPrefix2 = get_match(greaterSmaller2, metricPrfixReg);\n      metricPrefix2 = tolower(metricPrefix2[0]);\n      metricMult2 = metricPrefix2Integer(metricPrefix2[0]);\n    }\n\n    if (greaterSmaller1[0] == '>' || greaterSmaller1[0] == 'g'){\n      sizeOperand.greaterThan = metricMult1 * sizeValue1;\n      sizeOperand.greaterThanActive = true;\n      if (greaterSmaller2 != \"\" && (greaterSmaller2[0] == '<' && greaterSmaller2[0] == 's')){\n        sizeOperand.smallerThan = metricMult2 * sizeValue2;\n        sizeOperand.smallerThanActive = true;\n      }\n    }\n    else {\n      sizeOperand.smallerThan = metricMult1 * sizeValue1;\n      sizeOperand.smallerThanActive = true;\n      bool greater = greaterSmaller2[0] == 'g';\n      bool greater1 = greaterSmaller2[0] == '>';\n      if (greaterSmaller2 != \"\" && (greater1 || greater))\n        sizeOperand.greaterThan = metricMult2 * sizeValue2;\n      sizeOperand.greaterThanActive = true;\n    }\n  }\n\n\n\n\n  bool SearchOptions::getParameters(int argc, char *argv[]){\n\n    //opt::options_description desc(\"All options: (search and listingfiles required)\");\n    //desc = desc.c;\n    //_crtBreakAlloc = 894;\n    desc.add_options()\n      (\"search,s\", opt::value<std::string>(), \"search string\")\n      (\"listingfiles,l\", opt::value<std::vector<std::string> >()->multitoken(),\n      \"file listings\")\n      (\"casesensitive,c\", opt::value<bool>()->default_value(false), \"casesensitive search true/false\")\n      (\"filetype,f\", opt::value<std::string>()->default_value(\"file\"), \"file type to search (file, directory or both)\")\n      (\"resultfile,r\",\n      opt::value<std::string>()->default_value(\"auto\"),\n      \"results output file name (auto means automatically generated file name with format: results_for_searchTerm_searchterm.txt )\")\n      (\"year,y\", opt::value<std::string>()->default_value(\"\"), \"filter by year: yyyy\")\n      (\"monthyear,m\", opt::value<std::string>()->default_value(\"\"), \"filter by monthyear with format mm.yyyy\")\n      (\"date,d\", opt::value<std::string>()->default_value(\"\"), \"filter by date with format dd.mm.yyyy\")\n      (\"size,z\", opt::value<std::string>()->default_value(\"\"),\n      \"filter by size. Example: -z\\\">1M\\\", -z\\\"<100k\\\" or -z\\\"g1M\\\" -z\\\"s100k\\\". \\\n           You can also make a range like this -z\\\">100k <2M\\\" (use allways double quotes!)\")\n           (\"fullpath,u\", opt::value<bool>()->default_value(false), \"fullpath included in results\")\n           (\"searchby,b\", opt::value<std::string>()->default_value(\"filename\"),\n           \"searchtype (filename, by_directory_name, duplicate or cdtree)\\n \\\n               filename = regular file name search,\\n \\\n                   by_directory_name = list all files in directories that match search term,\\n \\\n                       duplicate = search for file duplicates (date, size, filename match)\\n \\\n                           cdtree = search cdtree format csv file\")\n                           (\"fileextension,x\", opt::value<std::string>()->default_value(\"*\"), \"file extension filter for search default to any\")\n                           (\"fileextensioncase,n\", opt::value<bool>()->default_value(false), \"file extension filter casesensitive defaults to false (= case insensitive)\")\n                           (\"timestamp,e\", opt::value<bool>()->default_value(false), \"include timestamp in auto generated result file name\")\n                           (\"overwrite,o\", opt::value<bool>()->default_value(false), \"overwrite results file by default in case it exists\")\n                           (\"cdtreefilenameflag,t\", opt::value<std::string>()->default_value(\"cdtree\"), \"if this string found in the file name switch to cdtree search function\")\n                           (\"exposeoptions,i\", opt::value<bool>()->default_value(false), \"list all option values to terminal\")\n\n                           (\"help\", \"produce help message\");\n\n    opt::variables_map vm;\n    try {\n      opt::store(opt::parse_command_line(argc, argv, desc), vm);\n    }\n    catch (std::exception& e)\n    {\n      //  \n      std::cerr << \"\\n\\nERROR in options!!!  check your options: \" << e.what() << \"\\n\\n\";\n      std::cout << desc << \"\\n\";\n      return false;\n    }\n    opt::notify(vm);\n\n    if (vm.count(\"help\")) {\n      std::cout << \"Usage: FileListSearch options\\n\";\n      std::cout << \"--search and --listingfiles options required\\n\";\n      std::cout << desc << \"\\n\";\n      success = false;\n      return false;\n    }\n\n    opt::notify(vm);\n\n    // extracting search word from command line options\n    if (!vm[\"search\"].empty()) {\n      searchString = vm[\"search\"].as<std::string>();\n    }\n    else {\n      std::cout << \"Search option required:\" << \"\\n\";\n      std::cout << desc << \"\\n\";\n      success = false;\n      return false;\n    }\n\n    casesensitive = vm[\"casesensitive\"].as<bool>();\n    overwrite = vm[\"overwrite\"].as<bool>();\n    fullpath = vm[\"fullpath\"].as<bool>();\n    filetype = vm[\"filetype\"].as<std::string>();\n    cdtreefilenameflag = vm[\"cdtreefilenameflag\"].as<std::string>();\n    fileExtension = vm[\"fileextension\"].as<std::string>();\n    fileExtensionCheckCaseSensitive = vm[\"fileextensioncase\"].as<bool>();\n    exposeOptions = vm[\"exposeoptions\"].as<bool>();\n\n    if (!casesensitive){\n \n      std::transform(searchString.begin(), searchString.end(), searchString.begin(), ::tolower);\n    }\n\n    year = vm[\"year\"].as<std::string>();\n    date = vm[\"date\"].as<std::string>();\n    monthYear = vm[\"monthyear\"].as<std::string>();\n    sizeFilter = vm[\"size\"].as<std::string>();\n\n    std::regex  sizereg1(\"^[<>gs]\\\\d+[MmKkGgTt]?(\\\\s*[<>sg]\\\\d+[MmKkGgTt]?)?\\\\s*$\");\n\n    if (sizeFilter != \"\" && !std::regex_match(sizeFilter, sizereg1)) {\n      std::cout << \"\\n\\nAttention!!!\\n\\nSizeFilter option needs to be in this format: < or > number and optional metric prefix (k,M,G or T)\" << std::endl;\n      std::cout << \"Please try again like this example: -z\\\">100\\\" or -z\\\"<20M\\\" \" << std::endl;\n      std::cout << \"Or for a range like this example: -z\\\">100k <20M\\\"\" << std::endl;\n      success = false;\n      return false;\n    }\n\n    if (sizeFilter != \"\") {\n      getSizeOperands();\n    }\n\n    std::regex  datereg1(\"^\\\\d\\\\d\\\\.\\\\d\\\\d\\\\.\\\\d\\\\d\\\\d\\\\d$\");\n\n    if (date != \"\" && !std::regex_match(date, datereg1)) {\n      std::cout << \"\\n\\nAttention!!!\\n\\nDate option needs to be in this format: dd.mm.yyyy\" << std::endl;\n      std::cout << \"Please try again like this example: -d17.08.2014\" << std::endl;\n      success = false;\n      return false;\n    }\n\n    std::regex  monthYearreg1(\"^\\\\d\\\\d\\\\.\\\\d\\\\d\\\\d\\\\d$\");\n\n    if (monthYear != \"\" && !std::regex_match(monthYear, monthYearreg1)) {\n      std::cout << \"\\n\\nAttention!!!\\n\\nMonthYear filter option needs to be in this format: mm.yyyy\" << std::endl;\n      std::cout << \"Please try again like this example: -m08.2014\" << std::endl;\n      success = false;\n      return false;\n    }\n\n    std::regex  yearreg1(\"^\\\\d\\\\d\\\\d\\\\d$\");\n\n    if (year != \"\" && !std::regex_match(year, yearreg1)) {\n      std::cout << \"\\n\\nAttention!!!\\n\\nYear filter option needs to be in this format: yyyy\" << std::endl;\n      std::cout << \"Please try again like this example: -y2014\" << std::endl;\n      success = false;\n      return false;\n    }\n\n    searchby = vm[\"searchby\"].as<std::string>();\n\n    if (searchby == \"dup\")\n      searchby = \"duplicate\";\n\n    if (searchby == \"dir\")\n      searchby = \"by_directory_name\";\n    \n\n\n    if (searchby == \"by_directory_name\" && searchString == \"*\")\n    {\n      std::cout << \"\\n\\nAttention!!!\\n\\nby_directory_name search mode has to have a search string other than *\" << std::endl;\n      std::cout << \"Please try again with a valid search string for folder name\" << std::endl;\n      success = false;\n      return false;\n    }\n    timestampInAutoName = vm[\"timestamp\"].as<bool>();\n\n    // extracting search results file file name from command line options\n    resultsFilename = vm[\"resultfile\"].as<std::string>();\n    //timestampInAutoName = true;\n\n    if (resultsFilename == \"auto\")\n    {\n      string resultfileTermString = searchString;\n      if (resultfileTermString == \"*\")\n        resultfileTermString = \"any\";\n      if (fileExtension != \"*\")\n        resultfileTermString += \"_with_fileExt_\" + fileExtension;\n      string timeString = \"\";\n      if (timestampInAutoName) {\n        //boost::posix_time::ptime nowTime = boost::posix_time::second_clock::local_time();\n\n        boost::posix_time::ptime my_ptime = boost::posix_time::second_clock::universal_time();\n        boost::local_time::local_date_time ldt(my_ptime, s_timezone);\n\n        timeString = mydateformat(ldt);\n        //to_simple_string(nowTime);\n        resultsFilename = \"results_for_searchTerm_\" + resultfileTermString + \"_\" + timeString + \".txt\";\n      }\n      else\n      {\n        resultsFilename = \"results_for_searchTerm_\" + resultfileTermString + \".txt\";\n      }\n\n    }\n    // extracting file listing path names from command line options\n\n    if (!vm[\"listingfiles\"].empty() &&\n      (listFiles = vm[\"listingfiles\"].as<std::vector<string> >()).size() > 0) {\n      // good to go\n    }\n    else {\n      std::cout << desc << \"\\n\";\n      success = false;\n      return false;\n    }\n    success = true;\n    //bool fullexposureOfSearchOptions = true;\n    if (exposeOptions)\n    {\n\n      cout << \"exposeOptions: \" << exposeOptions << endl;\n      cout << \"searchString: \" << searchString << endl;\n      cout << \"casesensitive: \" << casesensitive << endl;\n      cout << \"overwrite: \" << overwrite << endl;\n      cout << \"fullpath: \" << fullpath << endl;\n      cout << \"filetype: \" << filetype << endl;\n      cout << \"cdtreefilenameflag: \" << cdtreefilenameflag << endl;\n      cout << \"fileExtension : \" << fileExtension << endl;\n      cout << \"fileExtensionCheckCaseSensitive : \" << fileExtensionCheckCaseSensitive << endl;\n      cout << \"year : \" << year << endl;\n      cout << \"date : \" << date << endl;\n      cout << \"monthYear : \" << monthYear << endl;\n      cout << \"sizeFilter: \" << sizeFilter << endl;\n      cout << \"searchby: \" << searchby << endl;\n      cout << \"timestampInAutoName: \" << timestampInAutoName << endl;\n      cout << \"resultsFilename: \" << resultsFilename << endl;\n      cout << \"listFiles: \" << endl;\n      for (string filelistfileName : listFiles)\n        cout << \"    \" << filelistfileName << endl;\n      if (sizeOperand.greaterThanActive)\n        cout << \"size filter greaterThan: \" << sizeOperand.greaterThan << endl;\n      if (sizeOperand.smallerThanActive)\n        cout << \"size filter smallerThan: \" << sizeOperand.smallerThan << endl;\n      cout <<   endl;\n    }\n\n    checkWildCardInFileListings();\n    return true;\n  }\n\n\n  void SearchOptions::checkWildCardInFileListings() {\n    std::size_t wildcardPos = listFiles.at(0).find(\"*\");\n\n    // if wild card in the first parameter list all files on the dir\n    if (listFiles.size() == 1 && wildcardPos != std::string::npos){\n\n      string listingDir = listFiles.at(0).substr(0, wildcardPos);\n      listFiles.clear();\n      boost::filesystem::directory_iterator begin(listingDir);\n      boost::filesystem::directory_iterator end;\n\n      for (; begin != end; ++begin) {\n\n        boost::filesystem::file_status fs =\n          begin->status();\n\n        switch (fs.type()) {\n        case boost::filesystem::regular_file:\n          std::cout << \"listing file:  \";\n          std::cout << begin->path() << '\\n';\n\n          listFiles.push_back(begin->path().string());\n          break;\n\n        default:\n          //std::cout << \"OTHER      \";\n          break;\n        }\n      }\n    }\n  }\n\n  void SearchOptions::initExtensionChar(){\n    fileExtLen = fileExtension.size();\n    fileExt = reinterpret_cast<char *>(malloc(fileExtension.size() + 1));\n    memcpy(fileExt, fileExtension.c_str(), fileExtLen + 1);\n  }\n\n  void SearchOptions::initializeVariables(){\n\n    searchChar1 = searchString[0];\n    searchStringLen = searchString.size();\n    searchCharArray = reinterpret_cast<char *>(malloc(searchString.size() + 1));\n    memcpy(searchCharArray, searchString.c_str(), searchStringLen + 1);\n\n    filterFileExt = false;\n    if (fileExtension.size() > 0 && fileExtension != \"*\") {\n\n      filterFileExt = true;\n      if (fileExtension.at(0) != '.')\n        fileExtension = \".\" + fileExtension;\n\n    }\n    initExtensionChar();\n\n    // do the file extension filtering\n    fileExtensionCheck = false; // actual test variable initial value\n\n    \n\n    sizeFilterActive = sizeOperand.greaterThanActive || sizeOperand.smallerThanActive;\n\n    dateFilter = reinterpret_cast<char *>(malloc(date.size() + 1));\n    memcpy(dateFilter, date.c_str(), date.size() + 1);\n\n    yearFilter = reinterpret_cast<char *>(malloc(year.size() + 1));\n    memcpy(yearFilter, year.c_str(), year.size() + 1);\n\n    monthYearFilter = reinterpret_cast<char *>(malloc(monthYear.size() + 1));\n    memcpy(monthYearFilter, monthYear.c_str(), monthYear.size() + 1);\n\n    // if empty no filtering\n    dateFilterActive = date.size() > 0;\n    // if empty no filtering and if dateFilterActive allready true override monthYearFilterActive\n    monthYearFilterActive = monthYear.size() > 0 && !dateFilterActive;\n    yearFilterActive = year.size() > 0 && (!monthYearFilterActive && !dateFilterActive);\n\n  }\n\n", "meta": {"hexsha": "faf778820e35f0b73d0298a822208ff5c70cf9c1", "size": 14466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FileListSearch/searchoptions.cpp", "max_stars_repo_name": "juyshy/FileListSearch", "max_stars_repo_head_hexsha": "5fbb181686b51fd4a515e0e2c284df8e9d5ad0c7", "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": "FileListSearch/searchoptions.cpp", "max_issues_repo_name": "juyshy/FileListSearch", "max_issues_repo_head_hexsha": "5fbb181686b51fd4a515e0e2c284df8e9d5ad0c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FileListSearch/searchoptions.cpp", "max_forks_repo_name": "juyshy/FileListSearch", "max_forks_repo_head_hexsha": "5fbb181686b51fd4a515e0e2c284df8e9d5ad0c7", "max_forks_repo_licenses": ["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.679144385, "max_line_length": 177, "alphanum_fraction": 0.6143370662, "num_tokens": 3673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.16087743711510621}}
{"text": "#include <gtest/gtest.h>\n\n#include \"converter/fixml2fix_converter.hxx\"\n#include \"converter/xml_element_helper.hxx\"\n#include \"converter/fix_helper.hxx\"\n#include \"util/fix_env.hxx\"\n#include \"tools/test_util.hxx\"\n\n#include <boost/log/trivial.hpp>\n\n#include <quickfix/fix50sp2/Quote.h>\n\n#include <list>\n#include <set>\n#include <string>\n#include <utility>\n\nusing namespace std;\nusing namespace fix2xml;\n\nTEST ( Quote, set_fields)\n{\n\n  fixml2fix_converter converter {\"../spec/fix/FIX50SP2.xml\", \"../spec/xsd/fixml-main-5-0-SP2.xsd\"};\n  auto& fixml_dict = converter.fixml_dico();\n  ASSERT_TRUE(converter.init());\n  ASSERT_TRUE(converter.parse_fixt_dico(\"../spec/fix/FIXT11.xml\"));\n  FIX50SP2::Quote msg;\n\n  list<multiset<string>> all_values;\n  multiset<string> all_compo_names;\n  multiset<string> Quote_0;\n  set_field(msg, FIX::Account{\"STRING_35938836\"}, Quote_0);\n  set_field(msg, FIX::AccountType{6}, Quote_0);\n  set_field(msg, FIX::AcctIDSource{99}, Quote_0);\n  FIX::BidForwardPoints BidForwardPoints_12;\n  BidForwardPoints_12.setString(\"14511736\");\nset_field(msg, BidForwardPoints_12, Quote_0);\n  FIX::BidForwardPoints2 BidForwardPoints2_12;\n  BidForwardPoints2_12.setString(\"20679105\");\nset_field(msg, BidForwardPoints2_12, Quote_0);\n  FIX::BidPx BidPx_12;\n  BidPx_12.setString(\"11857658\");\nset_field(msg, BidPx_12, Quote_0);\n  FIX::BidSize BidSize_12;\n  BidSize_12.setString(\"11440940\");\nset_field(msg, BidSize_12, Quote_0);\n  FIX::BidSpotRate BidSpotRate_12;\n  BidSpotRate_12.setString(\"14615302\");\nset_field(msg, BidSpotRate_12, Quote_0);\n  FIX::BidSwapPoints BidSwapPoints_0;\n  BidSwapPoints_0.setString(\"1440345\");\nset_field(msg, BidSwapPoints_0, Quote_0);\n  FIX::BidYield BidYield_12;\n  BidYield_12.setString(\"93.050000\");\nset_field(msg, BidYield_12, Quote_0);\n  set_field(msg, FIX::BookingType{0}, Quote_0);\n  set_field(msg, FIX::CommType{'6'}, Quote_0);\n  FIX::Commission Commission_24;\n  Commission_24.setString(\"12932233\");\nset_field(msg, Commission_24, Quote_0);\n  set_field(msg, FIX::Currency{\"USD\"}, Quote_0);\n  set_field(msg, FIX::CustOrderCapacity{4}, Quote_0);\n  set_field(msg, FIX::EncodedText{\"DATA_765090435\"}, Quote_0);\n  set_field(msg, FIX::EncodedTextLen{1711990359}, Quote_0);\n  set_field(msg, FIX::ExDestination{\"EXCHANGE_1511339453\"}, Quote_0);\n  set_field(msg, FIX::ExDestinationIDSource{'B'}, Quote_0);\n  FIX::MidPx MidPx_12;\n  MidPx_12.setString(\"868538\");\nset_field(msg, MidPx_12, Quote_0);\n  FIX::MidYield MidYield_12;\n  MidYield_12.setString(\"96.150000\");\nset_field(msg, MidYield_12, Quote_0);\n  FIX::MinBidSize MinBidSize_0;\n  MinBidSize_0.setString(\"6149259\");\nset_field(msg, MinBidSize_0, Quote_0);\n  FIX::MinOfferSize MinOfferSize_0;\n  MinOfferSize_0.setString(\"4877035\");\nset_field(msg, MinOfferSize_0, Quote_0);\n  FIX::MinQty MinQty_15;\n  MinQty_15.setString(\"20807427\");\nset_field(msg, MinQty_15, Quote_0);\n  FIX::MktBidPx MktBidPx_0;\n  MktBidPx_0.setString(\"470279\");\nset_field(msg, MktBidPx_0, Quote_0);\n  FIX::MktOfferPx MktOfferPx_0;\n  MktOfferPx_0.setString(\"12201325\");\nset_field(msg, MktOfferPx_0, Quote_0);\n  FIX::OfferForwardPoints OfferForwardPoints_12;\n  OfferForwardPoints_12.setString(\"1787129\");\nset_field(msg, OfferForwardPoints_12, Quote_0);\n  FIX::OfferForwardPoints2 OfferForwardPoints2_12;\n  OfferForwardPoints2_12.setString(\"13803525\");\nset_field(msg, OfferForwardPoints2_12, Quote_0);\n  FIX::OfferPx OfferPx_12;\n  OfferPx_12.setString(\"15780930\");\nset_field(msg, OfferPx_12, Quote_0);\n  FIX::OfferSize OfferSize_12;\n  OfferSize_12.setString(\"20532108\");\nset_field(msg, OfferSize_12, Quote_0);\n  FIX::OfferSpotRate OfferSpotRate_12;\n  OfferSpotRate_12.setString(\"14162913\");\nset_field(msg, OfferSpotRate_12, Quote_0);\n  FIX::OfferSwapPoints OfferSwapPoints_0;\n  OfferSwapPoints_0.setString(\"1893812\");\nset_field(msg, OfferSwapPoints_0, Quote_0);\n  FIX::OfferYield OfferYield_12;\n  OfferYield_12.setString(\"15.820000\");\nset_field(msg, OfferYield_12, Quote_0);\n  set_field(msg, FIX::OrdType{'6'}, Quote_0);\n  set_field(msg, FIX::OrderCapacity{'I'}, Quote_0);\n  FIX::OrderQty2 OrderQty2_17;\n  OrderQty2_17.setString(\"16592174\");\nset_field(msg, OrderQty2_17, Quote_0);\n  set_field(msg, FIX::OrderRestrictions{\"MULTIPLECHARVALUE_1\"}, Quote_0);\n  set_field(msg, FIX::PriceType{1}, Quote_0);\n  set_field(msg, FIX::PrivateQuote{false}, Quote_0);\n  set_field(msg, FIX::QuoteID{\"STRING_698171127\"}, Quote_0);\n  set_field(msg, FIX::QuoteMsgID{\"STRING_712259399\"}, Quote_0);\n  set_field(msg, FIX::QuoteReqID{\"STRING_276971640\"}, Quote_0);\n  set_field(msg, FIX::QuoteRespID{\"STRING_1991394462\"}, Quote_0);\n  set_field(msg, FIX::QuoteResponseLevel{3}, Quote_0);\n  set_field(msg, FIX::QuoteType{3}, Quote_0);\n  FIX::SettlCurrBidFxRate SettlCurrBidFxRate_0;\n  SettlCurrBidFxRate_0.setString(\"14205649\");\nset_field(msg, SettlCurrBidFxRate_0, Quote_0);\n  set_field(msg, FIX::SettlCurrFxRateCalc{'D'}, Quote_0);\n  FIX::SettlCurrOfferFxRate SettlCurrOfferFxRate_0;\n  SettlCurrOfferFxRate_0.setString(\"4075564\");\nset_field(msg, SettlCurrOfferFxRate_0, Quote_0);\n  set_field(msg, FIX::SettlCurrency{\"JPY\"}, Quote_0);\n  set_field(msg, FIX::SettlDate{\"LOCALMKTDATE_494410288\"}, Quote_0);\n  set_field(msg, FIX::SettlDate2{\"LOCALMKTDATE_1369490322\"}, Quote_0);\n  set_field(msg, FIX::SettlType{\"STRING_6\"}, Quote_0);\n  set_field(msg, FIX::Side{'B'}, Quote_0);\n  set_field(msg, FIX::Text{\"STRING_1302749413\"}, Quote_0);\n  set_field(msg, FIX::TradingSessionID{\"STRING_6\"}, Quote_0);\n  set_field(msg, FIX::TradingSessionSubID{\"STRING_1\"}, Quote_0);\n  set_field(msg, FIX::TransactTime{FIX::UTCTIMESTAMP(2, 31, 25, 12, 9, 2013)}, Quote_0);\n  set_field(msg, FIX::ValidUntilTime{FIX::UTCTIMESTAMP(22, 42, 43, 11, 3, 2004)}, Quote_0);\n  all_values.push_back(Quote_0);\n\n  all_compo_names.insert(\"Quote\");\n\n  // FinancingDetails\n  multiset<string> FinancingDetails_16;\n  set_field(msg, FIX::AgreementCurrency{\"GBP\"}, FinancingDetails_16);\n  set_field(msg, FIX::AgreementDate{\"LOCALMKTDATE_1666126724\"}, FinancingDetails_16);\n  set_field(msg, FIX::AgreementDesc{\"STRING_2016330761\"}, FinancingDetails_16);\n  set_field(msg, FIX::AgreementID{\"STRING_681013\"}, FinancingDetails_16);\n  set_field(msg, FIX::DeliveryType{2}, FinancingDetails_16);\n  set_field(msg, FIX::EndDate{\"LOCALMKTDATE_582108928\"}, FinancingDetails_16);\n  FIX::MarginRatio MarginRatio_16;\n  MarginRatio_16.setString(\"74.830000\");\nset_field(msg, MarginRatio_16, FinancingDetails_16);\n  set_field(msg, FIX::StartDate{\"LOCALMKTDATE_1723628684\"}, FinancingDetails_16);\n  set_field(msg, FIX::TerminationType{2}, FinancingDetails_16);\n  all_values.push_back(FinancingDetails_16);\n  all_compo_names.insert(\".\");\n\n  // Instrument\n  multiset<string> Instrument_66;\n  FIX::AttachmentPoint AttachmentPoint_66;\n  AttachmentPoint_66.setString(\"77.710000\");\nset_field(msg, AttachmentPoint_66, Instrument_66);\n  set_field(msg, FIX::CFICode{\"STRING_945635358\"}, Instrument_66);\n  set_field(msg, FIX::CPProgram{2}, Instrument_66);\n  set_field(msg, FIX::CPRegType{\"STRING_1884761573\"}, Instrument_66);\n  FIX::CapPrice CapPrice_66;\n  CapPrice_66.setString(\"1009011\");\nset_field(msg, CapPrice_66, Instrument_66);\n  FIX::ContractMultiplier ContractMultiplier_66;\n  ContractMultiplier_66.setString(\"21355447\");\nset_field(msg, ContractMultiplier_66, Instrument_66);\n  set_field(msg, FIX::ContractMultiplierUnit{2}, Instrument_66);\n  set_field(msg, FIX::ContractSettlMonth{\"MONTHYEAR_1582363476\"}, Instrument_66);\n  set_field(msg, FIX::CountryOfIssue{\"COUNTRY_1406725027\"}, Instrument_66);\n  set_field(msg, FIX::CouponPaymentDate{\"LOCALMKTDATE_1424896304\"}, Instrument_66);\n  FIX::CouponRate CouponRate_66;\n  CouponRate_66.setString(\"94.140000\");\nset_field(msg, CouponRate_66, Instrument_66);\n  set_field(msg, FIX::CreditRating{\"STRING_2094196607\"}, Instrument_66);\n  set_field(msg, FIX::DatedDate{\"LOCALMKTDATE_1099649624\"}, Instrument_66);\n  FIX::DetachmentPoint DetachmentPoint_66;\n  DetachmentPoint_66.setString(\"69.330000\");\nset_field(msg, DetachmentPoint_66, Instrument_66);\n  set_field(msg, FIX::EncodedIssuer{\"DATA_1354165921\"}, Instrument_66);\n  set_field(msg, FIX::EncodedIssuerLen{884211166}, Instrument_66);\n  set_field(msg, FIX::EncodedSecurityDesc{\"DATA_1907601876\"}, Instrument_66);\n  set_field(msg, FIX::EncodedSecurityDescLen{330727056}, Instrument_66);\n  set_field(msg, FIX::ExerciseStyle{2}, Instrument_66);\n  FIX::Factor Factor_66;\n  Factor_66.setString(\"7882614\");\nset_field(msg, Factor_66, Instrument_66);\n  set_field(msg, FIX::FlexProductEligibilityIndicator{false}, Instrument_66);\n  set_field(msg, FIX::FlexibleIndicator{false}, Instrument_66);\n  FIX::FloorPrice FloorPrice_66;\n  FloorPrice_66.setString(\"20933763\");\nset_field(msg, FloorPrice_66, Instrument_66);\n  set_field(msg, FIX::FlowScheduleType{3}, Instrument_66);\n  set_field(msg, FIX::InstrRegistry{\"STRING_2029633997\"}, Instrument_66);\n  set_field(msg, FIX::InstrmtAssignmentMethod{'2'}, Instrument_66);\n  set_field(msg, FIX::InterestAccrualDate{\"LOCALMKTDATE_463310373\"}, Instrument_66);\n  set_field(msg, FIX::IssueDate{\"LOCALMKTDATE_464259277\"}, Instrument_66);\n  set_field(msg, FIX::Issuer{\"STRING_354811241\"}, Instrument_66);\n  set_field(msg, FIX::ListMethod{0}, Instrument_66);\n  set_field(msg, FIX::LocaleOfIssue{\"STRING_422725658\"}, Instrument_66);\n  set_field(msg, FIX::MaturityDate{\"LOCALMKTDATE_1257459013\"}, Instrument_66);\n  set_field(msg, FIX::MaturityMonthYear{\"MONTHYEAR_985090768\"}, Instrument_66);\n  set_field(msg, FIX::MaturityTime{\"TZTIMEONLY_372475430\"}, Instrument_66);\n  FIX::MinPriceIncrement MinPriceIncrement_66;\n  MinPriceIncrement_66.setString(\"9947369\");\nset_field(msg, MinPriceIncrement_66, Instrument_66);\n  FIX::MinPriceIncrementAmount MinPriceIncrementAmount_66;\n  MinPriceIncrementAmount_66.setString(\"10859918\");\nset_field(msg, MinPriceIncrementAmount_66, Instrument_66);\n  set_field(msg, FIX::NTPositionLimit{360536574}, Instrument_66);\n  FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_66;\n  NotionalPercentageOutstanding_66.setString(\"75.510000\");\nset_field(msg, NotionalPercentageOutstanding_66, Instrument_66);\n  set_field(msg, FIX::OptAttribute{'5'}, Instrument_66);\n  FIX::OptPayoutAmount OptPayoutAmount_66;\n  OptPayoutAmount_66.setString(\"17672616\");\nset_field(msg, OptPayoutAmount_66, Instrument_66);\n  set_field(msg, FIX::OptPayoutType{3}, Instrument_66);\n  FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_66;\n  OriginalNotionalPercentageOutstanding_66.setString(\"11.350000\");\nset_field(msg, OriginalNotionalPercentageOutstanding_66, Instrument_66);\n  set_field(msg, FIX::Pool{\"STRING_1713974561\"}, Instrument_66);\n  set_field(msg, FIX::PositionLimit{1163839831}, Instrument_66);\n  set_field(msg, FIX::PriceQuoteMethod{\"STRING_STD\"}, Instrument_66);\n  set_field(msg, FIX::PriceUnitOfMeasure{\"STRING_920656834\"}, Instrument_66);\n  FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_66;\n  PriceUnitOfMeasureQty_66.setString(\"20480509\");\nset_field(msg, PriceUnitOfMeasureQty_66, Instrument_66);\n  set_field(msg, FIX::Product{11}, Instrument_66);\n  set_field(msg, FIX::ProductComplex{\"STRING_1251383890\"}, Instrument_66);\n  set_field(msg, FIX::PutOrCall{1}, Instrument_66);\n  set_field(msg, FIX::RedemptionDate{\"LOCALMKTDATE_279064138\"}, Instrument_66);\n  set_field(msg, FIX::RepoCollateralSecurityType{\"STRING_1256843209\"}, Instrument_66);\n  FIX::RepurchaseRate RepurchaseRate_66;\n  RepurchaseRate_66.setString(\"80.860000\");\nset_field(msg, RepurchaseRate_66, Instrument_66);\n  set_field(msg, FIX::RepurchaseTerm{224956883}, Instrument_66);\n  set_field(msg, FIX::RestructuringType{\"STRING_MR\"}, Instrument_66);\n  set_field(msg, FIX::SecurityDesc{\"STRING_2036132083\"}, Instrument_66);\n  set_field(msg, FIX::SecurityExchange{\"EXCHANGE_171530641\"}, Instrument_66);\n  set_field(msg, FIX::SecurityGroup{\"STRING_1244255978\"}, Instrument_66);\n  set_field(msg, FIX::SecurityID{\"STRING_352907713\"}, Instrument_66);\n  set_field(msg, FIX::SecurityIDSource{\"STRING_1\"}, Instrument_66);\n  set_field(msg, FIX::SecurityStatus{\"STRING_1\"}, Instrument_66);\n  set_field(msg, FIX::SecuritySubType{\"STRING_775633371\"}, Instrument_66);\n  set_field(msg, FIX::SecurityType{\"STRING_MPO\"}, Instrument_66);\n  set_field(msg, FIX::Seniority{\"STRING_SD\"}, Instrument_66);\n  set_field(msg, FIX::SettlMethod{'P'}, Instrument_66);\n  set_field(msg, FIX::SettleOnOpenFlag{\"STRING_631054186\"}, Instrument_66);\n  set_field(msg, FIX::StateOrProvinceOfIssue{\"STRING_1207310401\"}, Instrument_66);\n  set_field(msg, FIX::StrikeCurrency{\"CHF\"}, Instrument_66);\n  FIX::StrikeMultiplier StrikeMultiplier_66;\n  StrikeMultiplier_66.setString(\"17281821\");\nset_field(msg, StrikeMultiplier_66, Instrument_66);\n  FIX::StrikePrice StrikePrice_66;\n  StrikePrice_66.setString(\"11284233\");\nset_field(msg, StrikePrice_66, Instrument_66);\n  set_field(msg, FIX::StrikePriceBoundaryMethod{5}, Instrument_66);\n  FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_66;\n  StrikePriceBoundaryPrecision_66.setString(\"96.090000\");\nset_field(msg, StrikePriceBoundaryPrecision_66, Instrument_66);\n  set_field(msg, FIX::StrikePriceDeterminationMethod{3}, Instrument_66);\n  FIX::StrikeValue StrikeValue_66;\n  StrikeValue_66.setString(\"4983781\");\nset_field(msg, StrikeValue_66, Instrument_66);\n  set_field(msg, FIX::Symbol{\"STRING_654324030\"}, Instrument_66);\n  set_field(msg, FIX::SymbolSfx{\"STRING_CD\"}, Instrument_66);\n  set_field(msg, FIX::TimeUnit{\"STRING_Yr\"}, Instrument_66);\n  set_field(msg, FIX::UnderlyingPriceDeterminationMethod{3}, Instrument_66);\n  set_field(msg, FIX::UnitOfMeasure{\"STRING_oz_tr\"}, Instrument_66);\n  FIX::UnitOfMeasureQty UnitOfMeasureQty_66;\n  UnitOfMeasureQty_66.setString(\"3921403\");\nset_field(msg, UnitOfMeasureQty_66, Instrument_66);\n  set_field(msg, FIX::ValuationMethod{\"STRING_FUTDA\"}, Instrument_66);\n  all_values.push_back(Instrument_66);\n  all_compo_names.insert(\".\");\n\n  // ComplexEvents\n  // Group ComplexEvents.NoComplexEvents\n  {\n    FIX50SP2::Quote::NoComplexEvents noComplexEvents_0_0;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_132;\n    set_field(noComplexEvents_0_0, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_132);\n    FIX::ComplexEventPrice ComplexEventPrice_132;\n    ComplexEventPrice_132.setString(\"6491477\");\nset_field(noComplexEvents_0_0, ComplexEventPrice_132, ComplexEvents_NoComplexEvents_132);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceBoundaryMethod{1}, ComplexEvents_NoComplexEvents_132);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_132;\n    ComplexEventPriceBoundaryPrecision_132.setString(\"68.490000\");\nset_field(noComplexEvents_0_0, ComplexEventPriceBoundaryPrecision_132, ComplexEvents_NoComplexEvents_132);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceTimeType{1}, ComplexEvents_NoComplexEvents_132);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventType{2}, ComplexEvents_NoComplexEvents_132);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_132;\n    ComplexOptPayoutAmount_132.setString(\"6401945\");\nset_field(noComplexEvents_0_0, ComplexOptPayoutAmount_132, ComplexEvents_NoComplexEvents_132);\n    all_values.push_back(ComplexEvents_NoComplexEvents_132);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_258;\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(14, 51, 53, 15, 2, 2017)}, ComplexEventDates_NoComplexEventDates_258);\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(2, 9, 45, 18, 8, 2005)}, ComplexEventDates_NoComplexEventDates_258);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_258);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_532;\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(16, 25, 59)}, ComplexEventTimes_NoComplexEventTimes_532);\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(21, 56, 15)}, ComplexEventTimes_NoComplexEventTimes_532);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_532);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_0);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_0);\n    }\n    msg.addGroup(noComplexEvents_0_0);\n  }\n  {\n    FIX50SP2::Quote::NoComplexEvents noComplexEvents_0_1;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_133;\n    set_field(noComplexEvents_0_1, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_133);\n    FIX::ComplexEventPrice ComplexEventPrice_133;\n    ComplexEventPrice_133.setString(\"4010491\");\nset_field(noComplexEvents_0_1, ComplexEventPrice_133, ComplexEvents_NoComplexEvents_133);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceBoundaryMethod{4}, ComplexEvents_NoComplexEvents_133);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_133;\n    ComplexEventPriceBoundaryPrecision_133.setString(\"35.880000\");\nset_field(noComplexEvents_0_1, ComplexEventPriceBoundaryPrecision_133, ComplexEvents_NoComplexEvents_133);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceTimeType{3}, ComplexEvents_NoComplexEvents_133);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventType{2}, ComplexEvents_NoComplexEvents_133);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_133;\n    ComplexOptPayoutAmount_133.setString(\"6873781\");\nset_field(noComplexEvents_0_1, ComplexOptPayoutAmount_133, ComplexEvents_NoComplexEvents_133);\n    all_values.push_back(ComplexEvents_NoComplexEvents_133);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_259;\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(21, 16, 7, 0, 10, 2012)}, ComplexEventDates_NoComplexEventDates_259);\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(23, 55, 25, 25, 7, 2004)}, ComplexEventDates_NoComplexEventDates_259);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_259);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_533;\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(8, 39, 11)}, ComplexEventTimes_NoComplexEventTimes_533);\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(4, 59, 15)}, ComplexEventTimes_NoComplexEventTimes_533);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_533);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_0);\n      }\n      {\n        FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_534;\n        set_field(noComplexEventTimes_1_0_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(8, 48, 12)}, ComplexEventTimes_NoComplexEventTimes_534);\n        set_field(noComplexEventTimes_1_0_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(17, 43, 54)}, ComplexEventTimes_NoComplexEventTimes_534);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_534);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_1);\n      }\n      {\n        FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_535;\n        set_field(noComplexEventTimes_1_0_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(8, 10, 29)}, ComplexEventTimes_NoComplexEventTimes_535);\n        set_field(noComplexEventTimes_1_0_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(11, 15, 24)}, ComplexEventTimes_NoComplexEventTimes_535);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_535);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_2);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_260;\n      set_field(noComplexEventDates_1_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(15, 41, 55, 17, 11, 2015)}, ComplexEventDates_NoComplexEventDates_260);\n      set_field(noComplexEventDates_1_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(22, 41, 44, 26, 10, 2005)}, ComplexEventDates_NoComplexEventDates_260);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_260);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_536;\n        set_field(noComplexEventTimes_1_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(19, 1, 53)}, ComplexEventTimes_NoComplexEventTimes_536);\n        set_field(noComplexEventTimes_1_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(18, 28, 7)}, ComplexEventTimes_NoComplexEventTimes_536);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_536);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_0);\n      }\n      {\n        FIX50SP2::Quote::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_537;\n        set_field(noComplexEventTimes_1_1_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(0, 10, 2)}, ComplexEventTimes_NoComplexEventTimes_537);\n        set_field(noComplexEventTimes_1_1_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(13, 17, 41)}, ComplexEventTimes_NoComplexEventTimes_537);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_537);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_1);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_1);\n    }\n    msg.addGroup(noComplexEvents_0_1);\n  }\n  // EvntGrp\n  // Group EvntGrp.NoEvents\n  {\n    FIX50SP2::Quote::NoEvents noEvents_0_0;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_137;\n    set_field(noEvents_0_0, FIX::EventDate{\"LOCALMKTDATE_1669732820\"}, EvntGrp_NoEvents_137);\n    FIX::EventPx EventPx_137;\n    EventPx_137.setString(\"20571380\");\nset_field(noEvents_0_0, EventPx_137, EvntGrp_NoEvents_137);\n    set_field(noEvents_0_0, FIX::EventText{\"STRING_1256261675\"}, EvntGrp_NoEvents_137);\n    set_field(noEvents_0_0, FIX::EventTime{FIX::UTCTIMESTAMP(0, 45, 7, 11, 7, 2007)}, EvntGrp_NoEvents_137);\n    set_field(noEvents_0_0, FIX::EventType{18}, EvntGrp_NoEvents_137);\n    all_values.push_back(EvntGrp_NoEvents_137);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_0);\n  }\n  {\n    FIX50SP2::Quote::NoEvents noEvents_0_1;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_138;\n    set_field(noEvents_0_1, FIX::EventDate{\"LOCALMKTDATE_1433468583\"}, EvntGrp_NoEvents_138);\n    FIX::EventPx EventPx_138;\n    EventPx_138.setString(\"4902565\");\nset_field(noEvents_0_1, EventPx_138, EvntGrp_NoEvents_138);\n    set_field(noEvents_0_1, FIX::EventText{\"STRING_541110122\"}, EvntGrp_NoEvents_138);\n    set_field(noEvents_0_1, FIX::EventTime{FIX::UTCTIMESTAMP(2, 3, 37, 27, 2, 2003)}, EvntGrp_NoEvents_138);\n    set_field(noEvents_0_1, FIX::EventType{7}, EvntGrp_NoEvents_138);\n    all_values.push_back(EvntGrp_NoEvents_138);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_1);\n  }\n  // InstrumentParties\n  // Group InstrumentParties.NoInstrumentParties\n  {\n    FIX50SP2::Quote::NoInstrumentParties noInstrumentParties_0_0;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_125;\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyID{\"STRING_1718777565\"}, InstrumentParties_NoInstrumentParties_125);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyIDSource{'9'}, InstrumentParties_NoInstrumentParties_125);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyRole{700465187}, InstrumentParties_NoInstrumentParties_125);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_125);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::Quote::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_256;\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubID{\"STRING_1619730718\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_256);\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubIDType{1722181025}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_256);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_256);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_257;\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubID{\"STRING_2029244143\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_257);\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubIDType{517043550}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_257);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_257);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_1);\n    }\n    {\n      FIX50SP2::Quote::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_2;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_258;\n      set_field(noInstrumentPartySubIDs_0_1_2, FIX::InstrumentPartySubID{\"STRING_1244430197\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_258);\n      set_field(noInstrumentPartySubIDs_0_1_2, FIX::InstrumentPartySubIDType{1938898497}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_258);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_258);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_2);\n    }\n    msg.addGroup(noInstrumentParties_0_0);\n  }\n  // SecAltIDGrp\n  // Group SecAltIDGrp.NoSecurityAltID\n  {\n    FIX50SP2::Quote::NoSecurityAltID noSecurityAltID_0_0;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_138;\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltID{\"STRING_1754488251\"}, SecAltIDGrp_NoSecurityAltID_138);\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltIDSource{\"STRING_1114417850\"}, SecAltIDGrp_NoSecurityAltID_138);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_138);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_0);\n  }\n  {\n    FIX50SP2::Quote::NoSecurityAltID noSecurityAltID_0_1;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_139;\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltID{\"STRING_1639248282\"}, SecAltIDGrp_NoSecurityAltID_139);\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltIDSource{\"STRING_627247370\"}, SecAltIDGrp_NoSecurityAltID_139);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_139);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_1);\n  }\n  {\n    FIX50SP2::Quote::NoSecurityAltID noSecurityAltID_0_2;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_140;\n    set_field(noSecurityAltID_0_2, FIX::SecurityAltID{\"STRING_1134139241\"}, SecAltIDGrp_NoSecurityAltID_140);\n    set_field(noSecurityAltID_0_2, FIX::SecurityAltIDSource{\"STRING_1777174200\"}, SecAltIDGrp_NoSecurityAltID_140);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_140);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_2);\n  }\n  // SecurityXML\n  multiset<string> SecurityXML_132;\n  set_field(msg, FIX::SecurityXML{\"XMLDATA_1007761293\"}, SecurityXML_132);\n  set_field(msg, FIX::SecurityXMLLen{1069943550}, SecurityXML_132);\n  set_field(msg, FIX::SecurityXMLSchema{\"STRING_1063159136\"}, SecurityXML_132);\n  all_values.push_back(SecurityXML_132);\n  all_compo_names.insert(\"..\");\n\n  // LegQuotGrp\n  // Group LegQuotGrp.NoLegs\n  {\n    FIX50SP2::Quote::NoLegs noLegs_0_0;\n    // LegQuotGrp.NoLegs\n    multiset<string> LegQuotGrp_NoLegs_0;\n    FIX::LegBidForwardPoints LegBidForwardPoints_0;\n    LegBidForwardPoints_0.setString(\"16110536\");\nset_field(noLegs_0_0, LegBidForwardPoints_0, LegQuotGrp_NoLegs_0);\n    FIX::LegBidPx LegBidPx_0;\n    LegBidPx_0.setString(\"2806596\");\nset_field(noLegs_0_0, LegBidPx_0, LegQuotGrp_NoLegs_0);\n    FIX::LegOfferForwardPoints LegOfferForwardPoints_0;\n    LegOfferForwardPoints_0.setString(\"11010541\");\nset_field(noLegs_0_0, LegOfferForwardPoints_0, LegQuotGrp_NoLegs_0);\n    FIX::LegOfferPx LegOfferPx_0;\n    LegOfferPx_0.setString(\"13788437\");\nset_field(noLegs_0_0, LegOfferPx_0, LegQuotGrp_NoLegs_0);\n    FIX::LegOrderQty LegOrderQty_6;\n    LegOrderQty_6.setString(\"2603158\");\nset_field(noLegs_0_0, LegOrderQty_6, LegQuotGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegPriceType{41634585}, LegQuotGrp_NoLegs_0);\n    FIX::LegQty LegQty_6;\n    LegQty_6.setString(\"9283550\");\nset_field(noLegs_0_0, LegQty_6, LegQuotGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegRefID{\"STRING_372662339\"}, LegQuotGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegSettlDate{\"LOCALMKTDATE_1113271311\"}, LegQuotGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegSettlType{'1'}, LegQuotGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegSwapType{2}, LegQuotGrp_NoLegs_0);\n    all_values.push_back(LegQuotGrp_NoLegs_0);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_91;\n    set_field(noLegs_0_0, FIX::EncodedLegIssuer{\"DATA_2071627080\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::EncodedLegIssuerLen{144054597}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDesc{\"DATA_820113819\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDescLen{1543874150}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegCFICode{\"STRING_1866235622\"}, InstrumentLeg_91);\n    FIX::LegContractMultiplier LegContractMultiplier_91;\n    LegContractMultiplier_91.setString(\"7018743\");\nset_field(noLegs_0_0, LegContractMultiplier_91, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegContractMultiplierUnit{2060917700}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegContractSettlMonth{\"MONTHYEAR_963182171\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegCountryOfIssue{\"COUNTRY_493289163\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_1686739277\"}, InstrumentLeg_91);\n    FIX::LegCouponRate LegCouponRate_91;\n    LegCouponRate_91.setString(\"67.750000\");\nset_field(noLegs_0_0, LegCouponRate_91, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegCreditRating{\"STRING_1607707013\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegCurrency{\"CHF\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegDatedDate{\"LOCALMKTDATE_594362606\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegExerciseStyle{808194464}, InstrumentLeg_91);\n    FIX::LegFactor LegFactor_91;\n    LegFactor_91.setString(\"577117\");\nset_field(noLegs_0_0, LegFactor_91, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegFlowScheduleType{1664306156}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegInstrRegistry{\"STRING_1871353600\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_1555729683\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegIssueDate{\"LOCALMKTDATE_1127876180\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegIssuer{\"STRING_4529585\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegLocaleOfIssue{\"STRING_509300201\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegMaturityDate{\"LOCALMKTDATE_359236239\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegMaturityMonthYear{\"MONTHYEAR_264845407\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegMaturityTime{\"TZTIMEONLY_550934786\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegOptAttribute{'1'}, InstrumentLeg_91);\n    FIX::LegOptionRatio LegOptionRatio_91;\n    LegOptionRatio_91.setString(\"6375077\");\nset_field(noLegs_0_0, LegOptionRatio_91, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegPool{\"STRING_1664206097\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegPriceUnitOfMeasure{\"STRING_731180721\"}, InstrumentLeg_91);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_91;\n    LegPriceUnitOfMeasureQty_91.setString(\"5814640\");\nset_field(noLegs_0_0, LegPriceUnitOfMeasureQty_91, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegProduct{1588349529}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegPutOrCall{875235318}, InstrumentLeg_91);\n    FIX::LegRatioQty LegRatioQty_91;\n    LegRatioQty_91.setString(\"14015778\");\nset_field(noLegs_0_0, LegRatioQty_91, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegRedemptionDate{\"LOCALMKTDATE_984740031\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegRepoCollateralSecurityType{\"STRING_593987292\"}, InstrumentLeg_91);\n    FIX::LegRepurchaseRate LegRepurchaseRate_91;\n    LegRepurchaseRate_91.setString(\"21.360000\");\nset_field(noLegs_0_0, LegRepurchaseRate_91, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegRepurchaseTerm{898174083}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSecurityDesc{\"STRING_1557169463\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSecurityExchange{\"EXCHANGE_449257652\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSecurityID{\"STRING_437429713\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSecurityIDSource{\"STRING_2127356238\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSecuritySubType{\"STRING_2056964665\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSecurityType{\"STRING_1615933625\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSide{'1'}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegStateOrProvinceOfIssue{\"STRING_503843624\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegStrikeCurrency{\"EUR\"}, InstrumentLeg_91);\n    FIX::LegStrikePrice LegStrikePrice_91;\n    LegStrikePrice_91.setString(\"206661\");\nset_field(noLegs_0_0, LegStrikePrice_91, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSymbol{\"STRING_514394\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegSymbolSfx{\"STRING_643264562\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegTimeUnit{\"STRING_1148542313\"}, InstrumentLeg_91);\n    set_field(noLegs_0_0, FIX::LegUnitOfMeasure{\"STRING_5043979\"}, InstrumentLeg_91);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_91;\n    LegUnitOfMeasureQty_91.setString(\"11525647\");\nset_field(noLegs_0_0, LegUnitOfMeasureQty_91, InstrumentLeg_91);\n    all_values.push_back(InstrumentLeg_91);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::Quote::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_184;\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltID{\"STRING_269889386\"}, LegSecAltIDGrp_NoLegSecurityAltID_184);\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltIDSource{\"STRING_1703499549\"}, LegSecAltIDGrp_NoLegSecurityAltID_184);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_184);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_185;\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltID{\"STRING_647886216\"}, LegSecAltIDGrp_NoLegSecurityAltID_185);\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltIDSource{\"STRING_907397132\"}, LegSecAltIDGrp_NoLegSecurityAltID_185);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_185);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_1);\n    }\n    {\n      FIX50SP2::Quote::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_2;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_186;\n      set_field(noLegSecurityAltID_0_1_2, FIX::LegSecurityAltID{\"STRING_1220221998\"}, LegSecAltIDGrp_NoLegSecurityAltID_186);\n      set_field(noLegSecurityAltID_0_1_2, FIX::LegSecurityAltIDSource{\"STRING_1379066937\"}, LegSecAltIDGrp_NoLegSecurityAltID_186);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_186);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_2);\n    }\n    // LegBenchmarkCurveData\n    multiset<string> LegBenchmarkCurveData_0;\n    set_field(noLegs_0_0, FIX::LegBenchmarkCurveCurrency{\"GBP\"}, LegBenchmarkCurveData_0);\n    set_field(noLegs_0_0, FIX::LegBenchmarkCurveName{\"STRING_106818607\"}, LegBenchmarkCurveData_0);\n    set_field(noLegs_0_0, FIX::LegBenchmarkCurvePoint{\"STRING_742955310\"}, LegBenchmarkCurveData_0);\n    FIX::LegBenchmarkPrice LegBenchmarkPrice_0;\n    LegBenchmarkPrice_0.setString(\"16458279\");\nset_field(noLegs_0_0, LegBenchmarkPrice_0, LegBenchmarkCurveData_0);\n    set_field(noLegs_0_0, FIX::LegBenchmarkPriceType{700805899}, LegBenchmarkCurveData_0);\n    all_values.push_back(LegBenchmarkCurveData_0);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::Quote::NoLegs::NoLegStipulations noLegStipulations_0_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_15;\n      set_field(noLegStipulations_0_1_0, FIX::LegStipulationType{\"STRING_396518347\"}, LegStipulations_NoLegStipulations_15);\n      set_field(noLegStipulations_0_1_0, FIX::LegStipulationValue{\"STRING_110491714\"}, LegStipulations_NoLegStipulations_15);\n      all_values.push_back(LegStipulations_NoLegStipulations_15);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoLegs::NoLegStipulations noLegStipulations_0_1_1;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_16;\n      set_field(noLegStipulations_0_1_1, FIX::LegStipulationType{\"STRING_1148181451\"}, LegStipulations_NoLegStipulations_16);\n      set_field(noLegStipulations_0_1_1, FIX::LegStipulationValue{\"STRING_833948060\"}, LegStipulations_NoLegStipulations_16);\n      all_values.push_back(LegStipulations_NoLegStipulations_16);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_1);\n    }\n    {\n      FIX50SP2::Quote::NoLegs::NoLegStipulations noLegStipulations_0_1_2;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_17;\n      set_field(noLegStipulations_0_1_2, FIX::LegStipulationType{\"STRING_90364305\"}, LegStipulations_NoLegStipulations_17);\n      set_field(noLegStipulations_0_1_2, FIX::LegStipulationValue{\"STRING_1057662468\"}, LegStipulations_NoLegStipulations_17);\n      all_values.push_back(LegStipulations_NoLegStipulations_17);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_2);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::Quote::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_109;\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyID{\"STRING_1267671041\"}, NestedParties_NoNestedPartyIDs_109);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_109);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyRole{579042478}, NestedParties_NoNestedPartyIDs_109);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_109);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_224;\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubID{\"STRING_1582172225\"}, NstdPtysSubGrp_NoNestedPartySubIDs_224);\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubIDType{579556872}, NstdPtysSubGrp_NoNestedPartySubIDs_224);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_224);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_225;\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubID{\"STRING_998470482\"}, NstdPtysSubGrp_NoNestedPartySubIDs_225);\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubIDType{583230890}, NstdPtysSubGrp_NoNestedPartySubIDs_225);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_225);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_1);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_1;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_110;\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyID{\"STRING_584600851\"}, NestedParties_NoNestedPartyIDs_110);\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyIDSource{'3'}, NestedParties_NoNestedPartyIDs_110);\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyRole{2091009442}, NestedParties_NoNestedPartyIDs_110);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_110);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_226;\n        set_field(noNestedPartySubIDs_0_1_2_0, FIX::NestedPartySubID{\"STRING_1707051146\"}, NstdPtysSubGrp_NoNestedPartySubIDs_226);\n        set_field(noNestedPartySubIDs_0_1_2_0, FIX::NestedPartySubIDType{591412010}, NstdPtysSubGrp_NoNestedPartySubIDs_226);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_226);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_0);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_1);\n    }\n    {\n      FIX50SP2::Quote::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_2;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_111;\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyID{\"STRING_1761887370\"}, NestedParties_NoNestedPartyIDs_111);\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyIDSource{'7'}, NestedParties_NoNestedPartyIDs_111);\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyRole{1970478947}, NestedParties_NoNestedPartyIDs_111);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_111);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_2_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_227;\n        set_field(noNestedPartySubIDs_0_2_2_0, FIX::NestedPartySubID{\"STRING_1440877376\"}, NstdPtysSubGrp_NoNestedPartySubIDs_227);\n        set_field(noNestedPartySubIDs_0_2_2_0, FIX::NestedPartySubIDType{2077297554}, NstdPtysSubGrp_NoNestedPartySubIDs_227);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_227);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_2.addGroup(noNestedPartySubIDs_0_2_2_0);\n      }\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_2_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_228;\n        set_field(noNestedPartySubIDs_0_2_2_1, FIX::NestedPartySubID{\"STRING_1846220168\"}, NstdPtysSubGrp_NoNestedPartySubIDs_228);\n        set_field(noNestedPartySubIDs_0_2_2_1, FIX::NestedPartySubIDType{939221640}, NstdPtysSubGrp_NoNestedPartySubIDs_228);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_228);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_2.addGroup(noNestedPartySubIDs_0_2_2_1);\n      }\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_2_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_229;\n        set_field(noNestedPartySubIDs_0_2_2_2, FIX::NestedPartySubID{\"STRING_630619805\"}, NstdPtysSubGrp_NoNestedPartySubIDs_229);\n        set_field(noNestedPartySubIDs_0_2_2_2, FIX::NestedPartySubIDType{397660319}, NstdPtysSubGrp_NoNestedPartySubIDs_229);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_229);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_2.addGroup(noNestedPartySubIDs_0_2_2_2);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_2);\n    }\n    msg.addGroup(noLegs_0_0);\n  }\n  {\n    FIX50SP2::Quote::NoLegs noLegs_0_1;\n    // LegQuotGrp.NoLegs\n    multiset<string> LegQuotGrp_NoLegs_1;\n    FIX::LegBidForwardPoints LegBidForwardPoints_1;\n    LegBidForwardPoints_1.setString(\"13357399\");\nset_field(noLegs_0_1, LegBidForwardPoints_1, LegQuotGrp_NoLegs_1);\n    FIX::LegBidPx LegBidPx_1;\n    LegBidPx_1.setString(\"7411115\");\nset_field(noLegs_0_1, LegBidPx_1, LegQuotGrp_NoLegs_1);\n    FIX::LegOfferForwardPoints LegOfferForwardPoints_1;\n    LegOfferForwardPoints_1.setString(\"15458417\");\nset_field(noLegs_0_1, LegOfferForwardPoints_1, LegQuotGrp_NoLegs_1);\n    FIX::LegOfferPx LegOfferPx_1;\n    LegOfferPx_1.setString(\"222043\");\nset_field(noLegs_0_1, LegOfferPx_1, LegQuotGrp_NoLegs_1);\n    FIX::LegOrderQty LegOrderQty_7;\n    LegOrderQty_7.setString(\"8314758\");\nset_field(noLegs_0_1, LegOrderQty_7, LegQuotGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegPriceType{456020591}, LegQuotGrp_NoLegs_1);\n    FIX::LegQty LegQty_7;\n    LegQty_7.setString(\"3246024\");\nset_field(noLegs_0_1, LegQty_7, LegQuotGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegRefID{\"STRING_2099146866\"}, LegQuotGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegSettlDate{\"LOCALMKTDATE_2017526683\"}, LegQuotGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegSettlType{'9'}, LegQuotGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegSwapType{4}, LegQuotGrp_NoLegs_1);\n    all_values.push_back(LegQuotGrp_NoLegs_1);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_92;\n    set_field(noLegs_0_1, FIX::EncodedLegIssuer{\"DATA_1452215260\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::EncodedLegIssuerLen{1483201787}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::EncodedLegSecurityDesc{\"DATA_1305339620\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::EncodedLegSecurityDescLen{2035446150}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegCFICode{\"STRING_2067802638\"}, InstrumentLeg_92);\n    FIX::LegContractMultiplier LegContractMultiplier_92;\n    LegContractMultiplier_92.setString(\"13088912\");\nset_field(noLegs_0_1, LegContractMultiplier_92, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegContractMultiplierUnit{1978971945}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegContractSettlMonth{\"MONTHYEAR_774809228\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegCountryOfIssue{\"COUNTRY_868458715\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_422900307\"}, InstrumentLeg_92);\n    FIX::LegCouponRate LegCouponRate_92;\n    LegCouponRate_92.setString(\"29.500000\");\nset_field(noLegs_0_1, LegCouponRate_92, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegCreditRating{\"STRING_1648248211\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegCurrency{\"GBP\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegDatedDate{\"LOCALMKTDATE_941641940\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegExerciseStyle{175709513}, InstrumentLeg_92);\n    FIX::LegFactor LegFactor_92;\n    LegFactor_92.setString(\"11912143\");\nset_field(noLegs_0_1, LegFactor_92, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegFlowScheduleType{1880863580}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegInstrRegistry{\"STRING_806329319\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_1588874648\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegIssueDate{\"LOCALMKTDATE_1069119919\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegIssuer{\"STRING_1547440839\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegLocaleOfIssue{\"STRING_987232770\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegMaturityDate{\"LOCALMKTDATE_1091324318\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegMaturityMonthYear{\"MONTHYEAR_231433016\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegMaturityTime{\"TZTIMEONLY_1443253361\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegOptAttribute{'1'}, InstrumentLeg_92);\n    FIX::LegOptionRatio LegOptionRatio_92;\n    LegOptionRatio_92.setString(\"1830962\");\nset_field(noLegs_0_1, LegOptionRatio_92, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegPool{\"STRING_1313296397\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegPriceUnitOfMeasure{\"STRING_172088020\"}, InstrumentLeg_92);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_92;\n    LegPriceUnitOfMeasureQty_92.setString(\"4899653\");\nset_field(noLegs_0_1, LegPriceUnitOfMeasureQty_92, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegProduct{618028009}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegPutOrCall{1655289807}, InstrumentLeg_92);\n    FIX::LegRatioQty LegRatioQty_92;\n    LegRatioQty_92.setString(\"17953049\");\nset_field(noLegs_0_1, LegRatioQty_92, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegRedemptionDate{\"LOCALMKTDATE_505990512\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegRepoCollateralSecurityType{\"STRING_1575608798\"}, InstrumentLeg_92);\n    FIX::LegRepurchaseRate LegRepurchaseRate_92;\n    LegRepurchaseRate_92.setString(\"25.610000\");\nset_field(noLegs_0_1, LegRepurchaseRate_92, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegRepurchaseTerm{337478809}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSecurityDesc{\"STRING_202934378\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSecurityExchange{\"EXCHANGE_1825171276\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSecurityID{\"STRING_760379116\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSecurityIDSource{\"STRING_592147328\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSecuritySubType{\"STRING_1325935839\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSecurityType{\"STRING_1006274723\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSide{'2'}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegStateOrProvinceOfIssue{\"STRING_120094131\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegStrikeCurrency{\"JPY\"}, InstrumentLeg_92);\n    FIX::LegStrikePrice LegStrikePrice_92;\n    LegStrikePrice_92.setString(\"20009577\");\nset_field(noLegs_0_1, LegStrikePrice_92, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSymbol{\"STRING_1988313556\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegSymbolSfx{\"STRING_569746816\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegTimeUnit{\"STRING_922593982\"}, InstrumentLeg_92);\n    set_field(noLegs_0_1, FIX::LegUnitOfMeasure{\"STRING_1388270747\"}, InstrumentLeg_92);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_92;\n    LegUnitOfMeasureQty_92.setString(\"15569795\");\nset_field(noLegs_0_1, LegUnitOfMeasureQty_92, InstrumentLeg_92);\n    all_values.push_back(InstrumentLeg_92);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::Quote::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_187;\n      set_field(noLegSecurityAltID_1_1_0, FIX::LegSecurityAltID{\"STRING_1619703763\"}, LegSecAltIDGrp_NoLegSecurityAltID_187);\n      set_field(noLegSecurityAltID_1_1_0, FIX::LegSecurityAltIDSource{\"STRING_852749300\"}, LegSecAltIDGrp_NoLegSecurityAltID_187);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_187);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_0);\n    }\n    // LegBenchmarkCurveData\n    multiset<string> LegBenchmarkCurveData_1;\n    set_field(noLegs_0_1, FIX::LegBenchmarkCurveCurrency{\"EUR\"}, LegBenchmarkCurveData_1);\n    set_field(noLegs_0_1, FIX::LegBenchmarkCurveName{\"STRING_18562049\"}, LegBenchmarkCurveData_1);\n    set_field(noLegs_0_1, FIX::LegBenchmarkCurvePoint{\"STRING_1454449427\"}, LegBenchmarkCurveData_1);\n    FIX::LegBenchmarkPrice LegBenchmarkPrice_1;\n    LegBenchmarkPrice_1.setString(\"1452817\");\nset_field(noLegs_0_1, LegBenchmarkPrice_1, LegBenchmarkCurveData_1);\n    set_field(noLegs_0_1, FIX::LegBenchmarkPriceType{636590059}, LegBenchmarkCurveData_1);\n    all_values.push_back(LegBenchmarkCurveData_1);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::Quote::NoLegs::NoLegStipulations noLegStipulations_1_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_18;\n      set_field(noLegStipulations_1_1_0, FIX::LegStipulationType{\"STRING_1940586713\"}, LegStipulations_NoLegStipulations_18);\n      set_field(noLegStipulations_1_1_0, FIX::LegStipulationValue{\"STRING_1142580571\"}, LegStipulations_NoLegStipulations_18);\n      all_values.push_back(LegStipulations_NoLegStipulations_18);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_1.addGroup(noLegStipulations_1_1_0);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::Quote::NoLegs::NoNestedPartyIDs noNestedPartyIDs_1_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_112;\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyID{\"STRING_749815626\"}, NestedParties_NoNestedPartyIDs_112);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_112);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyRole{593315114}, NestedParties_NoNestedPartyIDs_112);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_112);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_230;\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubID{\"STRING_92954848\"}, NstdPtysSubGrp_NoNestedPartySubIDs_230);\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubIDType{1185462442}, NstdPtysSubGrp_NoNestedPartySubIDs_230);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_230);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_231;\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubID{\"STRING_1753439093\"}, NstdPtysSubGrp_NoNestedPartySubIDs_231);\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubIDType{1099229572}, NstdPtysSubGrp_NoNestedPartySubIDs_231);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_231);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::Quote::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_232;\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubID{\"STRING_1122603930\"}, NstdPtysSubGrp_NoNestedPartySubIDs_232);\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubIDType{1873533225}, NstdPtysSubGrp_NoNestedPartySubIDs_232);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_232);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_2);\n      }\n      noLegs_0_1.addGroup(noNestedPartyIDs_1_1_0);\n    }\n    msg.addGroup(noLegs_0_1);\n  }\n  // OrderQtyData\n  multiset<string> OrderQtyData_20;\n  FIX::CashOrderQty CashOrderQty_20;\n  CashOrderQty_20.setString(\"1337301\");\nset_field(msg, CashOrderQty_20, OrderQtyData_20);\n  FIX::OrderPercent OrderPercent_20;\n  OrderPercent_20.setString(\"60.990000\");\nset_field(msg, OrderPercent_20, OrderQtyData_20);\n  FIX::OrderQty OrderQty_29;\n  OrderQty_29.setString(\"17270072\");\nset_field(msg, OrderQty_29, OrderQtyData_20);\n  set_field(msg, FIX::RoundingDirection{'2'}, OrderQtyData_20);\n  FIX::RoundingModulus RoundingModulus_20;\n  RoundingModulus_20.setString(\"6732229\");\nset_field(msg, RoundingModulus_20, OrderQtyData_20);\n  all_values.push_back(OrderQtyData_20);\n  all_compo_names.insert(\".\");\n\n  // Parties\n  // Group Parties.NoPartyIDs\n  {\n    FIX50SP2::Quote::NoPartyIDs noPartyIDs_0_0;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_111;\n    set_field(noPartyIDs_0_0, FIX::PartyID{\"STRING_1362830816\"}, Parties_NoPartyIDs_111);\n    set_field(noPartyIDs_0_0, FIX::PartyIDSource{'G'}, Parties_NoPartyIDs_111);\n    set_field(noPartyIDs_0_0, FIX::PartyRole{8}, Parties_NoPartyIDs_111);\n    all_values.push_back(Parties_NoPartyIDs_111);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::Quote::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_222;\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubID{\"STRING_935468155\"}, PtysSubGrp_NoPartySubIDs_222);\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubIDType{12}, PtysSubGrp_NoPartySubIDs_222);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_222);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_1;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_223;\n      set_field(noPartySubIDs_0_1_1, FIX::PartySubID{\"STRING_490367280\"}, PtysSubGrp_NoPartySubIDs_223);\n      set_field(noPartySubIDs_0_1_1, FIX::PartySubIDType{7}, PtysSubGrp_NoPartySubIDs_223);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_223);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_1);\n    }\n    msg.addGroup(noPartyIDs_0_0);\n  }\n  // QuotQualGrp\n  // Group QuotQualGrp.NoQuoteQualifiers\n  {\n    FIX50SP2::Quote::NoQuoteQualifiers noQuoteQualifiers_0_0;\n    // QuotQualGrp.NoQuoteQualifiers\n    multiset<string> QuotQualGrp_NoQuoteQualifiers_0;\n    set_field(noQuoteQualifiers_0_0, FIX::QuoteQualifier{'6'}, QuotQualGrp_NoQuoteQualifiers_0);\n    all_values.push_back(QuotQualGrp_NoQuoteQualifiers_0);\n    all_compo_names.insert(\"...NoQuoteQualifiers\");\n\n    msg.addGroup(noQuoteQualifiers_0_0);\n  }\n  {\n    FIX50SP2::Quote::NoQuoteQualifiers noQuoteQualifiers_0_1;\n    // QuotQualGrp.NoQuoteQualifiers\n    multiset<string> QuotQualGrp_NoQuoteQualifiers_1;\n    set_field(noQuoteQualifiers_0_1, FIX::QuoteQualifier{'1'}, QuotQualGrp_NoQuoteQualifiers_1);\n    all_values.push_back(QuotQualGrp_NoQuoteQualifiers_1);\n    all_compo_names.insert(\"...NoQuoteQualifiers\");\n\n    msg.addGroup(noQuoteQualifiers_0_1);\n  }\n  {\n    FIX50SP2::Quote::NoQuoteQualifiers noQuoteQualifiers_0_2;\n    // QuotQualGrp.NoQuoteQualifiers\n    multiset<string> QuotQualGrp_NoQuoteQualifiers_2;\n    set_field(noQuoteQualifiers_0_2, FIX::QuoteQualifier{'1'}, QuotQualGrp_NoQuoteQualifiers_2);\n    all_values.push_back(QuotQualGrp_NoQuoteQualifiers_2);\n    all_compo_names.insert(\"...NoQuoteQualifiers\");\n\n    msg.addGroup(noQuoteQualifiers_0_2);\n  }\n  // RateSource\n  // Group RateSource.NoRateSources\n  {\n    FIX50SP2::Quote::NoRateSources noRateSources_0_0;\n    // RateSource.NoRateSources\n    multiset<string> RateSource_NoRateSources_19;\n    set_field(noRateSources_0_0, FIX::RateSource{2}, RateSource_NoRateSources_19);\n    set_field(noRateSources_0_0, FIX::RateSourceType{0}, RateSource_NoRateSources_19);\n    set_field(noRateSources_0_0, FIX::ReferencePage{\"STRING_1178567692\"}, RateSource_NoRateSources_19);\n    all_values.push_back(RateSource_NoRateSources_19);\n    all_compo_names.insert(\"...NoRateSources\");\n\n    msg.addGroup(noRateSources_0_0);\n  }\n  {\n    FIX50SP2::Quote::NoRateSources noRateSources_0_1;\n    // RateSource.NoRateSources\n    multiset<string> RateSource_NoRateSources_20;\n    set_field(noRateSources_0_1, FIX::RateSource{2}, RateSource_NoRateSources_20);\n    set_field(noRateSources_0_1, FIX::RateSourceType{0}, RateSource_NoRateSources_20);\n    set_field(noRateSources_0_1, FIX::ReferencePage{\"STRING_1606070946\"}, RateSource_NoRateSources_20);\n    all_values.push_back(RateSource_NoRateSources_20);\n    all_compo_names.insert(\"...NoRateSources\");\n\n    msg.addGroup(noRateSources_0_1);\n  }\n  // SpreadOrBenchmarkCurveData\n  multiset<string> SpreadOrBenchmarkCurveData_23;\n  set_field(msg, FIX::BenchmarkCurveCurrency{\"CAN\"}, SpreadOrBenchmarkCurveData_23);\n  set_field(msg, FIX::BenchmarkCurveName{\"STRING_FutureSWAP\"}, SpreadOrBenchmarkCurveData_23);\n  set_field(msg, FIX::BenchmarkCurvePoint{\"STRING_1110477339\"}, SpreadOrBenchmarkCurveData_23);\n  FIX::BenchmarkPrice BenchmarkPrice_23;\n  BenchmarkPrice_23.setString(\"9169299\");\nset_field(msg, BenchmarkPrice_23, SpreadOrBenchmarkCurveData_23);\n  set_field(msg, FIX::BenchmarkPriceType{938075968}, SpreadOrBenchmarkCurveData_23);\n  set_field(msg, FIX::BenchmarkSecurityID{\"STRING_1244207500\"}, SpreadOrBenchmarkCurveData_23);\n  set_field(msg, FIX::BenchmarkSecurityIDSource{\"STRING_1020406074\"}, SpreadOrBenchmarkCurveData_23);\n  FIX::Spread Spread_23;\n  Spread_23.setString(\"5175996\");\nset_field(msg, Spread_23, SpreadOrBenchmarkCurveData_23);\n  all_values.push_back(SpreadOrBenchmarkCurveData_23);\n  all_compo_names.insert(\".\");\n\n  // Stipulations\n  // Group Stipulations.NoStipulations\n  {\n    FIX50SP2::Quote::NoStipulations noStipulations_0_0;\n    // Stipulations.NoStipulations\n    multiset<string> Stipulations_NoStipulations_37;\n    set_field(noStipulations_0_0, FIX::StipulationType{\"STRING_PROD\"}, Stipulations_NoStipulations_37);\n    set_field(noStipulations_0_0, FIX::StipulationValue{\"STRING_1019717232\"}, Stipulations_NoStipulations_37);\n    all_values.push_back(Stipulations_NoStipulations_37);\n    all_compo_names.insert(\"...NoStipulations\");\n\n    msg.addGroup(noStipulations_0_0);\n  }\n  {\n    FIX50SP2::Quote::NoStipulations noStipulations_0_1;\n    // Stipulations.NoStipulations\n    multiset<string> Stipulations_NoStipulations_38;\n    set_field(noStipulations_0_1, FIX::StipulationType{\"STRING_MATURITY\"}, Stipulations_NoStipulations_38);\n    set_field(noStipulations_0_1, FIX::StipulationValue{\"STRING_1776347844\"}, Stipulations_NoStipulations_38);\n    all_values.push_back(Stipulations_NoStipulations_38);\n    all_compo_names.insert(\"...NoStipulations\");\n\n    msg.addGroup(noStipulations_0_1);\n  }\n  // UndInstrmtGrp\n  // Group UndInstrmtGrp.NoUnderlyings\n  {\n    FIX50SP2::Quote::NoUnderlyings noUnderlyings_0_0;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_91;\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuer{\"DATA_1269165668\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuerLen{564332351}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDesc{\"DATA_891699541\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDescLen{1759532948}, UnderlyingInstrument_91);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_91;\n    UnderlyingAdjustedQuantity_91.setString(\"15183625\");\nset_field(noUnderlyings_0_0, UnderlyingAdjustedQuantity_91, UnderlyingInstrument_91);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_91;\n    UnderlyingAllocationPercent_91.setString(\"90.020000\");\nset_field(noUnderlyings_0_0, UnderlyingAllocationPercent_91, UnderlyingInstrument_91);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_91;\n    UnderlyingAttachmentPoint_91.setString(\"83.010000\");\nset_field(noUnderlyings_0_0, UnderlyingAttachmentPoint_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCFICode{\"STRING_961499171\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPProgram{\"STRING_1622230402\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPRegType{\"STRING_676450367\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingCapValue UnderlyingCapValue_91;\n    UnderlyingCapValue_91.setString(\"15472163\");\nset_field(noUnderlyings_0_0, UnderlyingCapValue_91, UnderlyingInstrument_91);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_91;\n    UnderlyingCashAmount_91.setString(\"17852625\");\nset_field(noUnderlyings_0_0, UnderlyingCashAmount_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCashType{\"STRING_DIFF\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_91;\n    UnderlyingContractMultiplier_91.setString(\"14655092\");\nset_field(noUnderlyings_0_0, UnderlyingContractMultiplier_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingContractMultiplierUnit{394126140}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCountryOfIssue{\"COUNTRY_1313605357\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_1476757043\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_91;\n    UnderlyingCouponRate_91.setString(\"21.850000\");\nset_field(noUnderlyings_0_0, UnderlyingCouponRate_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCreditRating{\"STRING_378148100\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCurrency{\"EUR\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_91;\n    UnderlyingCurrentValue_91.setString(\"13162240\");\nset_field(noUnderlyings_0_0, UnderlyingCurrentValue_91, UnderlyingInstrument_91);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_91;\n    UnderlyingDetachmentPoint_91.setString(\"82.340000\");\nset_field(noUnderlyings_0_0, UnderlyingDetachmentPoint_91, UnderlyingInstrument_91);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_91;\n    UnderlyingDirtyPrice_91.setString(\"21257882\");\nset_field(noUnderlyings_0_0, UnderlyingDirtyPrice_91, UnderlyingInstrument_91);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_91;\n    UnderlyingEndPrice_91.setString(\"18338236\");\nset_field(noUnderlyings_0_0, UnderlyingEndPrice_91, UnderlyingInstrument_91);\n    FIX::UnderlyingEndValue UnderlyingEndValue_91;\n    UnderlyingEndValue_91.setString(\"7552421\");\nset_field(noUnderlyings_0_0, UnderlyingEndValue_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingExerciseStyle{1671933577}, UnderlyingInstrument_91);\n    FIX::UnderlyingFXRate UnderlyingFXRate_91;\n    UnderlyingFXRate_91.setString(\"7060572\");\nset_field(noUnderlyings_0_0, UnderlyingFXRate_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFXRateCalc{'D'}, UnderlyingInstrument_91);\n    FIX::UnderlyingFactor UnderlyingFactor_91;\n    UnderlyingFactor_91.setString(\"13007977\");\nset_field(noUnderlyings_0_0, UnderlyingFactor_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFlowScheduleType{2094326769}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingInstrRegistry{\"STRING_311038912\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_1865130125\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssuer{\"STRING_838542663\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingLocaleOfIssue{\"STRING_2070571860\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_1236009033\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_540638017\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_170786513\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_91;\n    UnderlyingNotionalPercentageOutstanding_91.setString(\"45.570000\");\nset_field(noUnderlyings_0_0, UnderlyingNotionalPercentageOutstanding_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_91);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_91;\n    UnderlyingOriginalNotionalPercentageOutstanding_91.setString(\"68.800000\");\nset_field(noUnderlyings_0_0, UnderlyingOriginalNotionalPercentageOutstanding_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_1597240915\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_91;\n    UnderlyingPriceUnitOfMeasureQty_91.setString(\"18006473\");\nset_field(noUnderlyings_0_0, UnderlyingPriceUnitOfMeasureQty_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingProduct{554771291}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPutOrCall{915266543}, UnderlyingInstrument_91);\n    FIX::UnderlyingPx UnderlyingPx_91;\n    UnderlyingPx_91.setString(\"472898\");\nset_field(noUnderlyings_0_0, UnderlyingPx_91, UnderlyingInstrument_91);\n    FIX::UnderlyingQty UnderlyingQty_91;\n    UnderlyingQty_91.setString(\"18683766\");\nset_field(noUnderlyings_0_0, UnderlyingQty_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_244539939\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_235741987\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_91;\n    UnderlyingRepurchaseRate_91.setString(\"11.010000\");\nset_field(noUnderlyings_0_0, UnderlyingRepurchaseRate_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepurchaseTerm{684290673}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRestructuringType{\"STRING_1341124148\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityDesc{\"STRING_1415265170\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityExchange{\"EXCHANGE_220765260\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityID{\"STRING_1319428736\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityIDSource{\"STRING_1101605200\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecuritySubType{\"STRING_976007415\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityType{\"STRING_843878665\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSeniority{\"STRING_1807662462\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlMethod{\"STRING_17880660\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlementType{4}, UnderlyingInstrument_91);\n    FIX::UnderlyingStartValue UnderlyingStartValue_91;\n    UnderlyingStartValue_91.setString(\"17545055\");\nset_field(noUnderlyings_0_0, UnderlyingStartValue_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_328919572\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStrikeCurrency{\"GBP\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_91;\n    UnderlyingStrikePrice_91.setString(\"2520077\");\nset_field(noUnderlyings_0_0, UnderlyingStrikePrice_91, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbol{\"STRING_950848302\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbolSfx{\"STRING_986202616\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingTimeUnit{\"STRING_422794298\"}, UnderlyingInstrument_91);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingUnitOfMeasure{\"STRING_1000872859\"}, UnderlyingInstrument_91);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_91;\n    UnderlyingUnitOfMeasureQty_91.setString(\"10015873\");\nset_field(noUnderlyings_0_0, UnderlyingUnitOfMeasureQty_91, UnderlyingInstrument_91);\n    all_values.push_back(UnderlyingInstrument_91);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_189;\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltID{\"STRING_450630126\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_189);\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_654751049\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_189);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_189);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_1;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_190;\n      set_field(noUnderlyingSecurityAltID_0_1_1, FIX::UnderlyingSecurityAltID{\"STRING_1824802470\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_190);\n      set_field(noUnderlyingSecurityAltID_0_1_1, FIX::UnderlyingSecurityAltIDSource{\"STRING_1365896670\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_190);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_190);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_1);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_182;\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipType{\"STRING_1545695471\"}, UnderlyingStipulations_NoUnderlyingStips_182);\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipValue{\"STRING_1610436609\"}, UnderlyingStipulations_NoUnderlyingStips_182);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_182);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_0);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_201;\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_1644736572\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_201);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_201);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyRole{131423339}, UndlyInstrumentParties_NoUndlyInstrumentParties_201);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_201);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_405;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_368008894\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_405);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{1450852075}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_405);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_405);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_0);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_202;\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_2014123294\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_202);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_202);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyRole{147247092}, UndlyInstrumentParties_NoUndlyInstrumentParties_202);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_202);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_406;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1361896970\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_406);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{144439884}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_406);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_406);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_407;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1281324043\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_407);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_1, FIX::UnderlyingInstrumentPartySubIDType{1690816542}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_407);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_407);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_1);\n      }\n      {\n        FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_408;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_2006762801\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_408);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_2, FIX::UnderlyingInstrumentPartySubIDType{1726888642}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_408);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_408);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_2);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_1);\n    }\n    msg.addGroup(noUnderlyings_0_0);\n  }\n  {\n    FIX50SP2::Quote::NoUnderlyings noUnderlyings_0_1;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_92;\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuer{\"DATA_1942824327\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuerLen{810127455}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDesc{\"DATA_565607610\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDescLen{218134978}, UnderlyingInstrument_92);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_92;\n    UnderlyingAdjustedQuantity_92.setString(\"18110003\");\nset_field(noUnderlyings_0_1, UnderlyingAdjustedQuantity_92, UnderlyingInstrument_92);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_92;\n    UnderlyingAllocationPercent_92.setString(\"49.970000\");\nset_field(noUnderlyings_0_1, UnderlyingAllocationPercent_92, UnderlyingInstrument_92);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_92;\n    UnderlyingAttachmentPoint_92.setString(\"61.570000\");\nset_field(noUnderlyings_0_1, UnderlyingAttachmentPoint_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCFICode{\"STRING_114146793\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPProgram{\"STRING_74462398\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPRegType{\"STRING_1165484979\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingCapValue UnderlyingCapValue_92;\n    UnderlyingCapValue_92.setString(\"14800434\");\nset_field(noUnderlyings_0_1, UnderlyingCapValue_92, UnderlyingInstrument_92);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_92;\n    UnderlyingCashAmount_92.setString(\"7765032\");\nset_field(noUnderlyings_0_1, UnderlyingCashAmount_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCashType{\"STRING_FIXED\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_92;\n    UnderlyingContractMultiplier_92.setString(\"9429964\");\nset_field(noUnderlyings_0_1, UnderlyingContractMultiplier_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingContractMultiplierUnit{1714286088}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCountryOfIssue{\"COUNTRY_60949726\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_1090240059\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_92;\n    UnderlyingCouponRate_92.setString(\"94.270000\");\nset_field(noUnderlyings_0_1, UnderlyingCouponRate_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCreditRating{\"STRING_973467820\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCurrency{\"JPY\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_92;\n    UnderlyingCurrentValue_92.setString(\"8401074\");\nset_field(noUnderlyings_0_1, UnderlyingCurrentValue_92, UnderlyingInstrument_92);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_92;\n    UnderlyingDetachmentPoint_92.setString(\"16.150000\");\nset_field(noUnderlyings_0_1, UnderlyingDetachmentPoint_92, UnderlyingInstrument_92);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_92;\n    UnderlyingDirtyPrice_92.setString(\"12963249\");\nset_field(noUnderlyings_0_1, UnderlyingDirtyPrice_92, UnderlyingInstrument_92);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_92;\n    UnderlyingEndPrice_92.setString(\"3669259\");\nset_field(noUnderlyings_0_1, UnderlyingEndPrice_92, UnderlyingInstrument_92);\n    FIX::UnderlyingEndValue UnderlyingEndValue_92;\n    UnderlyingEndValue_92.setString(\"20166785\");\nset_field(noUnderlyings_0_1, UnderlyingEndValue_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingExerciseStyle{1440764830}, UnderlyingInstrument_92);\n    FIX::UnderlyingFXRate UnderlyingFXRate_92;\n    UnderlyingFXRate_92.setString(\"16482499\");\nset_field(noUnderlyings_0_1, UnderlyingFXRate_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFXRateCalc{'D'}, UnderlyingInstrument_92);\n    FIX::UnderlyingFactor UnderlyingFactor_92;\n    UnderlyingFactor_92.setString(\"13000439\");\nset_field(noUnderlyings_0_1, UnderlyingFactor_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFlowScheduleType{1227654964}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingInstrRegistry{\"STRING_1355352159\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_2110171439\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssuer{\"STRING_1793262574\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingLocaleOfIssue{\"STRING_1573487137\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_1773688106\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_1212973923\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_914169646\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_92;\n    UnderlyingNotionalPercentageOutstanding_92.setString(\"48.990000\");\nset_field(noUnderlyings_0_1, UnderlyingNotionalPercentageOutstanding_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_92);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_92;\n    UnderlyingOriginalNotionalPercentageOutstanding_92.setString(\"46.260000\");\nset_field(noUnderlyings_0_1, UnderlyingOriginalNotionalPercentageOutstanding_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_1220394715\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_92;\n    UnderlyingPriceUnitOfMeasureQty_92.setString(\"20639395\");\nset_field(noUnderlyings_0_1, UnderlyingPriceUnitOfMeasureQty_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingProduct{495867780}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPutOrCall{15907491}, UnderlyingInstrument_92);\n    FIX::UnderlyingPx UnderlyingPx_92;\n    UnderlyingPx_92.setString(\"16307420\");\nset_field(noUnderlyings_0_1, UnderlyingPx_92, UnderlyingInstrument_92);\n    FIX::UnderlyingQty UnderlyingQty_92;\n    UnderlyingQty_92.setString(\"5568175\");\nset_field(noUnderlyings_0_1, UnderlyingQty_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_1106147550\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_1328967790\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_92;\n    UnderlyingRepurchaseRate_92.setString(\"53.270000\");\nset_field(noUnderlyings_0_1, UnderlyingRepurchaseRate_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepurchaseTerm{416912856}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRestructuringType{\"STRING_330561996\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityDesc{\"STRING_222909146\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityExchange{\"EXCHANGE_1071694471\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityID{\"STRING_1626886943\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityIDSource{\"STRING_589835072\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecuritySubType{\"STRING_940889409\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityType{\"STRING_920168125\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSeniority{\"STRING_90601394\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlMethod{\"STRING_353417241\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlementType{4}, UnderlyingInstrument_92);\n    FIX::UnderlyingStartValue UnderlyingStartValue_92;\n    UnderlyingStartValue_92.setString(\"13182563\");\nset_field(noUnderlyings_0_1, UnderlyingStartValue_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_1708769400\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStrikeCurrency{\"GBP\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_92;\n    UnderlyingStrikePrice_92.setString(\"11347728\");\nset_field(noUnderlyings_0_1, UnderlyingStrikePrice_92, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbol{\"STRING_1809104358\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbolSfx{\"STRING_29525560\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingTimeUnit{\"STRING_2048942536\"}, UnderlyingInstrument_92);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingUnitOfMeasure{\"STRING_1549455609\"}, UnderlyingInstrument_92);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_92;\n    UnderlyingUnitOfMeasureQty_92.setString(\"13169618\");\nset_field(noUnderlyings_0_1, UnderlyingUnitOfMeasureQty_92, UnderlyingInstrument_92);\n    all_values.push_back(UnderlyingInstrument_92);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_1_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_191;\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltID{\"STRING_622366676\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_191);\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_1233417805\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_191);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_191);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingSecurityAltID_1_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_1_1_1;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_192;\n      set_field(noUnderlyingSecurityAltID_1_1_1, FIX::UnderlyingSecurityAltID{\"STRING_329497647\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_192);\n      set_field(noUnderlyingSecurityAltID_1_1_1, FIX::UnderlyingSecurityAltIDSource{\"STRING_638274168\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_192);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_192);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingSecurityAltID_1_1_1);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_1_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_183;\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipType{\"STRING_886315154\"}, UnderlyingStipulations_NoUnderlyingStips_183);\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipValue{\"STRING_1744421718\"}, UnderlyingStipulations_NoUnderlyingStips_183);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_183);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingStips_1_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_1_1_1;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_184;\n      set_field(noUnderlyingStips_1_1_1, FIX::UnderlyingStipType{\"STRING_2045643959\"}, UnderlyingStipulations_NoUnderlyingStips_184);\n      set_field(noUnderlyingStips_1_1_1, FIX::UnderlyingStipValue{\"STRING_269116833\"}, UnderlyingStipulations_NoUnderlyingStips_184);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_184);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingStips_1_1_1);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_203;\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_228722308\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_203);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyIDSource{'4'}, UndlyInstrumentParties_NoUndlyInstrumentParties_203);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyRole{1085545398}, UndlyInstrumentParties_NoUndlyInstrumentParties_203);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_203);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_409;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1081861052\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_409);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{2026434807}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_409);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_409);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_0);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_0);\n    }\n    {\n      FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_204;\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_628293728\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_204);\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_204);\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyRole{232368400}, UndlyInstrumentParties_NoUndlyInstrumentParties_204);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_204);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::Quote::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_410;\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_343235157\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_410);\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{1941137800}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_410);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_410);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_1.addGroup(noUndlyInstrumentPartySubIDs_1_1_2_0);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_1);\n    }\n    msg.addGroup(noUnderlyings_0_1);\n  }\n  // YieldData\n  multiset<string> YieldData_18;\n  FIX::Yield Yield_18;\n  Yield_18.setString(\"84.410000\");\nset_field(msg, Yield_18, YieldData_18);\n  set_field(msg, FIX::YieldCalcDate{\"LOCALMKTDATE_1307270441\"}, YieldData_18);\n  set_field(msg, FIX::YieldRedemptionDate{\"LOCALMKTDATE_928427042\"}, YieldData_18);\n  FIX::YieldRedemptionPrice YieldRedemptionPrice_18;\n  YieldRedemptionPrice_18.setString(\"3980591\");\nset_field(msg, YieldRedemptionPrice_18, YieldData_18);\n  set_field(msg, FIX::YieldRedemptionPriceType{1336796001}, YieldData_18);\n  set_field(msg, FIX::YieldType{\"STRING_PUT\"}, YieldData_18);\n  all_values.push_back(YieldData_18);\n  all_compo_names.insert(\".\");\n\n  // header\n  multiset<string> header_68;\n  set_header_field(msg.getHeader(), FIX::ApplVerID{\"STRING_1\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::BeginString{\"STRING_506274235\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::BodyLength{663515797}, header_68);\n  set_header_field(msg.getHeader(), FIX::CstmApplVerID{\"STRING_422397789\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::DeliverToCompID{\"STRING_1739692041\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{\"STRING_993013444\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::DeliverToSubID{\"STRING_1060671957\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{308884562}, header_68);\n  set_header_field(msg.getHeader(), FIX::MessageEncoding{\"STRING_SHIFT_JIS\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::MsgSeqNum{657610028}, header_68);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{\"STRING_207044873\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{\"STRING_961784\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{\"STRING_671460954\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(19, 12, 4, 15, 8, 2013)}, header_68);\n  set_header_field(msg.getHeader(), FIX::PossDupFlag{true}, header_68);\n  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_68);\n  set_header_field(msg.getHeader(), FIX::SecureData{\"DATA_1473208702\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::SecureDataLen{943062771}, header_68);\n  set_header_field(msg.getHeader(), FIX::SenderCompID{\"STRING_1661980064\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::SenderLocationID{\"STRING_62163496\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::SenderSubID{\"STRING_102849564\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(15, 46, 49, 4, 6, 2009)}, header_68);\n  set_header_field(msg.getHeader(), FIX::TargetCompID{\"STRING_682651550\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::TargetLocationID{\"STRING_1538128194\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::TargetSubID{\"STRING_781854983\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::XmlData{\"DATA_1743323507\"}, header_68);\n  set_header_field(msg.getHeader(), FIX::XmlDataLen{1847012756}, header_68);\n  all_values.push_back(header_68);\n  all_compo_names.insert(\".header\");\n\n\n  xml_element elt;\n  converter.fix2fixml(msg, elt);\n  BOOST_LOG_TRIVIAL(debug) << \"The resulting XML is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << elt.to_string() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n\n  BOOST_LOG_TRIVIAL(debug) << \"Quickfix XML representation is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << msg.toXML() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n  list<multiset<string>> elt_lists;\n  elt.to_list(elt_lists);\n  EXPECT_EQ(elt_lists.size(), all_values.size());\n\n  if (elt_lists.size() != all_values.size())  {\n    multiset<string> elt_compo_name;\n    elt.all_components(elt_compo_name);\n    BOOST_LOG_TRIVIAL(debug) << \"XML Elements are:\";\n    cout << \"\t[\";\n    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n    BOOST_LOG_TRIVIAL(debug) << \"FIX Components are:\"; \n    cout << \"\t[\";\n    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All FIX components\";\n  for (const auto& l : all_values) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All XML components\";\n  for (const auto& l : elt_lists) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n\n  }\n\n  for (const auto& xml_l : elt_lists) {\n    bool found = false;\n    for (const auto& l : all_values) {\n      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {\n        found = true;\n        break;\n      } // end if includes\n    } // end for all_values\n    EXPECT_TRUE(found);\n    if ( ! found) {\n      BOOST_LOG_TRIVIAL(debug) << \"[TO CHECK] This XML component was not found in FIX message\";\n      cout << \"\t ---> [\";\n      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, \" \"));      cout << \"]\" << endl << endl;\n    } // end if ! found\n  } // end for elt_lists\n}\n", "meta": {"hexsha": "5a1c6de16bc7a09b0ad4ddffeccd59afa8798633", "size": 107567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/generated/fix2xml/test_fix2xml_Quote.cpp", "max_stars_repo_name": "abdelkaderamar/fix2xml", "max_stars_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T12:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T12:08:19.000Z", "max_issues_repo_path": "tools/generated/fix2xml/test_fix2xml_Quote.cpp", "max_issues_repo_name": "abdelkaderamar/fix2xml", "max_issues_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_issues_repo_licenses": ["MIT"], "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/generated/fix2xml/test_fix2xml_Quote.cpp", "max_forks_repo_name": "abdelkaderamar/fix2xml", "max_forks_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T04:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T04:11:44.000Z", "avg_line_length": 60.2954035874, "max_line_length": 174, "alphanum_fraction": 0.7996132643, "num_tokens": 32447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.29421497835151617, "lm_q1q2_score": 0.16085855355010115}}
{"text": "//\n//  fpt.hpp\n//  indigox\n//\n//  Created by Welsh, Ivan on 4/12/17.\n//  Copyright \u00a9 2017 Allison Group. All rights reserved.\n//\n\n#ifndef INDIGOX_FORMALBONDS_FPT_ALGO_HPP\n#define INDIGOX_FORMALBONDS_FPT_ALGO_HPP\n\n#include <map>\n#include <vector>\n\n#include <boost/dynamic_bitset.hpp>\n#include \"../../api.hpp\"\n#include \"../../classes/molecular_graph.hpp\"\n#include \"../../classes/nicetreedecomp.hpp\"\n\n#include \"electron_optimisation_algorithm.hpp\"\n\nnamespace indigox {\n  namespace algorithm {\n    struct TDVertScore;\n    \n    typedef boost::dynamic_bitset<> VertMask;\n    typedef VertMask ForgetMask;\n    typedef VertMask BagMask;\n    typedef std::multimap<Score, ForgetMask> MaskScores;\n    typedef std::map<BagMask, MaskScores> BagScores;\n    typedef std::map<uint32_t, BagScores> ProperScoreMatrix;\n    \n    class FPTOptimisation : public ElectronOptimisationAlgorithm {\n      friend struct TDVertScore;\n    private:\n      FPTOptimisation() = default;\n      \n    public:\n      FPTOptimisation(ElectronOpt* parent);\n      \n    public:\n      void Run() override;\n      \n    private:\n      void Initalise();\n      void DetermineMinMax();\n      void PopulateReferenceVectors();\n      Score ScoreVertex(MolVertPair v, VertMask mask);\n      ElnDist VertMaskToElnDist(const VertMask& m);\n      \n    private:\n      NTDecomp_p td_;\n      std::map<NTDVertex, std::shared_ptr<TDVertScore>> scorematrices_;\n      std::vector<MolVertPair> possibleStates_;\n      std::map<MolVertPair, VertMask> pairMasks_;\n      VertMask placedMask_;\n    };\n    \n    struct TDVertScore {\n      FPTOptimisation* parent;\n      NTDVertProp* tdProperties;\n      ProperScoreMatrix score;\n      uint32_t min_e, max_e;\n      VertMask fMask;\n      \n      TDVertScore(FPTOptimisation* p, NTDVertProp* prop)\n      : parent(p), tdProperties(prop) {}\n      \n      void PopulateScoreMatrix();\n      VertMask IntroduceCountToMask(MolVertPair, size_t);\n      void LeafPropagate();\n      void ForgetPropagate(std::shared_ptr<TDVertScore> a);\n      void IntroducePropagate(std::shared_ptr<TDVertScore> a);\n      void JoinPropagate(std::shared_ptr<TDVertScore> a, std::shared_ptr<TDVertScore> b);\n      \n      String VertMaskToNiceString(VertMask);\n      String ToString();\n      String KindToString();\n    };\n    \n  }\n}\n\n#endif /* INDIGOX_FORMALBONDS_FPT_ALGO_HPP */\n", "meta": {"hexsha": "6a8631bc6318d532386417a83f3ffe2da50a8a05", "size": 2320, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/indigox/algorithm/formalbonds/fpt.hpp", "max_stars_repo_name": "allison-group/indigo-bondorder", "max_stars_repo_head_hexsha": "9d1c434274ab478cfc274f059daace939b355fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-03-07T10:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T13:14:47.000Z", "max_issues_repo_path": "include/indigox/algorithm/formalbonds/fpt.hpp", "max_issues_repo_name": "allison-group/indigo-bondorder", "max_issues_repo_head_hexsha": "9d1c434274ab478cfc274f059daace939b355fbd", "max_issues_repo_licenses": ["MIT"], "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/indigox/algorithm/formalbonds/fpt.hpp", "max_forks_repo_name": "allison-group/indigo-bondorder", "max_forks_repo_head_hexsha": "9d1c434274ab478cfc274f059daace939b355fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-07T09:12:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-01T23:52:06.000Z", "avg_line_length": 27.2941176471, "max_line_length": 89, "alphanum_fraction": 0.6827586207, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1607048818739721}}
{"text": "// Copyright (c) 2017-2018 The PIVX developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"test_veil.h\"\n#include \"libzerocoin/Denominations.h\"\n#include \"amount.h\"\n#include \"chainparams.h\"\n#include \"consensus/params.h\"\n#include \"wallet/coincontrol.h\"\n//nclude \"libzerocoin/ZerocoinDefines.h\"\n//#include \"main.h\"\n#include \"wallet/wallet.h\"\n#include \"wallet/walletdb.h\"\n#include \"txdb.h\"\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include \"libzerocoin/ParamGeneration.h\"\n#include \"libzerocoin/Denominations.h\"\n#include \"libzerocoin/Coin.h\"\n\nusing namespace libzerocoin;\n/*\nCBigNum GetTestModulus()\n{\n    static CBigNum testModulus(0);\n\n    // TODO: should use a hard-coded RSA modulus for testing\n    if (!testModulus) {\n        CBigNum p, q;\n\n        // Note: we are NOT using safe primes for testing because\n        // they take too long to generate. Don't do this in real\n        // usage. See the paramgen utility for better code.\n        p = CBigNum::generatePrime(1024, false);\n        q = CBigNum::generatePrime(1024, false);\n        testModulus = p * q;\n    }\n\n    return testModulus;\n}*/\nBOOST_FIXTURE_TEST_SUITE(zerocoin_transaction, BasicTestingSetup)\n\n//static CWallet cWallet(\"unlocked.dat\");\n\nBOOST_AUTO_TEST_CASE(spend_nsequence)\n{\n    CTxIn in;\n    in.nSequence = libzerocoin::CoinDenomination::ZQ_TEN;\n    in.nSequence |= CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG;\n\n    CAmount nAmount = (in.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK);\n    BOOST_CHECK_MESSAGE(nAmount == 10, \"nSequence did not properly decode for 10\");\n\n    in.nSequence = libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED;\n    in.nSequence |= CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG;\n    nAmount = (in.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK);\n    BOOST_CHECK_MESSAGE(nAmount == 100, \"nSequence did not properly decode for 100\");\n\n    in.nSequence = libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND;\n    in.nSequence |= CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG;\n    nAmount = (in.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK);\n    BOOST_CHECK_MESSAGE(nAmount == 1000, \"nSequence did not properly decode for 1000\");\n\n    in.nSequence = libzerocoin::CoinDenomination::ZQ_TEN_THOUSAND;\n    in.nSequence |= CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG;\n    nAmount = (in.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK);\n    BOOST_CHECK_MESSAGE(nAmount == 10000, \"nSequence did not properly decode for 10000\");\n}\n\nBOOST_AUTO_TEST_CASE(zerocoin_spend_test)\n{\n\n/*\n    SelectParams(CBaseChainParams::MAIN);\n    ZerocoinParams *ZCParams = new ZerocoinParams(GetTestModulus());\n    (void)ZCParams;\n\n    //cWallet.zpivTracker = unique_ptr<CzPIVTracker>(new CzPIVTracker(cWallet.strWalletFile));\n    CMutableTransaction tx;\n    CWalletTx* wtx = new CWalletTx(&cWallet, tx);\n    bool fMintChange=true;\n    bool fMinimizeChange=true;\n    std::vector<CZerocoinSpend> vSpends;\n    std::vector<CZerocoinMint> vMints;\n    CAmount nAmount = COIN;\n    int nSecurityLevel = 100;\n\n    CZerocoinSpendReceipt receipt;\n    cWallet.SpendZerocoin(nAmount, nSecurityLevel, *wtx, receipt, vMints, fMintChange, fMinimizeChange);\n\n    BOOST_CHECK_MESSAGE(receipt.GetStatus() == ZPIV_TRX_FUNDS_PROBLEMS, \"Failed Invalid Amount Check\");\n\n    nAmount = 1;\n    CZerocoinSpendReceipt receipt2;\n    cWallet.SpendZerocoin(nAmount, nSecurityLevel, *wtx, receipt2, vMints, fMintChange, fMinimizeChange);\n\n    // if using \"wallet.dat\", instead of \"unlocked.dat\" need this\n    /// BOOST_CHECK_MESSAGE(vString == \"Error: Wallet locked, unable to create transaction!\",\" Locked Wallet Check Failed\");\n\n    BOOST_CHECK_MESSAGE(receipt2.GetStatus() == ZPIV_TRX_FUNDS_PROBLEMS, \"Failed Invalid Amount Check\");\n*/\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fac791fef388e62b70a423310f63d0ff4416466e", "size": 3770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/zerocoin_transactions_tests.cpp", "max_stars_repo_name": "Oilplik/veil-1", "max_stars_repo_head_hexsha": "852b05b255b464201de53fe7afdf7c696ed50724", "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/test/zerocoin_transactions_tests.cpp", "max_issues_repo_name": "Oilplik/veil-1", "max_issues_repo_head_hexsha": "852b05b255b464201de53fe7afdf7c696ed50724", "max_issues_repo_licenses": ["MIT"], "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/zerocoin_transactions_tests.cpp", "max_forks_repo_name": "Oilplik/veil-1", "max_forks_repo_head_hexsha": "852b05b255b464201de53fe7afdf7c696ed50724", "max_forks_repo_licenses": ["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.5660377358, "max_line_length": 124, "alphanum_fraction": 0.7379310345, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.1603313144366348}}
{"text": "#ifndef STAN_MCMC_HMC_NUTS_BASE_XHMC_HPP\n#define STAN_MCMC_HMC_NUTS_BASE_XHMC_HPP\n\n#include <stan/callbacks/logger.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <stan/mcmc/hmc/base_hmc.hpp>\n#include <stan/mcmc/hmc/hamiltonians/ps_point.hpp>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <string>\n#include <vector>\n#include <utility>\n\nnamespace stan {\nnamespace mcmc {\n\n/**\n * Exhaustive Hamiltonian Monte Carlo (XHMC) with multinomial sampling.\n * See http://arxiv.org/abs/1601.00225.\n */\ntemplate <class Model, template <class, class> class Hamiltonian,\n          template <class> class Integrator, class BaseRNG>\nclass base_xhmc : public base_hmc<Model, Hamiltonian, Integrator, BaseRNG> {\n public:\n  base_xhmc(const Model& model, BaseRNG& rng)\n      : base_hmc<Model, Hamiltonian, Integrator, BaseRNG>(model, rng),\n        depth_(0),\n        max_depth_(5),\n        max_deltaH_(1000),\n        x_delta_(0.1),\n        n_leapfrog_(0),\n        divergent_(0),\n        energy_(0) {}\n\n  ~base_xhmc() {}\n\n  void set_max_depth(int d) {\n    if (d > 0)\n      max_depth_ = d;\n  }\n\n  void set_max_deltaH(double d) { max_deltaH_ = d; }\n\n  void set_x_delta(double d) {\n    if (d > 0)\n      x_delta_ = d;\n  }\n\n  int get_max_depth() { return this->max_depth_; }\n  double get_max_deltaH() { return this->max_deltaH_; }\n  double get_x_delta() { return this->x_delta_; }\n\n  sample transition(sample& init_sample, callbacks::logger& logger) {\n    // Initialize the algorithm\n    this->sample_stepsize();\n\n    this->seed(init_sample.cont_params());\n\n    this->hamiltonian_.sample_p(this->z_, this->rand_int_);\n    this->hamiltonian_.init(this->z_, logger);\n\n    ps_point z_plus(this->z_);\n    ps_point z_minus(z_plus);\n\n    ps_point z_sample(z_plus);\n    ps_point z_propose(z_plus);\n\n    double ave = this->hamiltonian_.dG_dt(this->z_, logger);\n    double log_sum_weight = 0;  // log(exp(H0 - H0))\n\n    double H0 = this->hamiltonian_.H(this->z_);\n    int n_leapfrog = 0;\n    double sum_metro_prob = 1;  // exp(H0 - H0)\n\n    // Build a trajectory until the NUTS criterion is no longer satisfied\n    this->depth_ = 0;\n    this->divergent_ = 0;\n\n    while (this->depth_ < this->max_depth_) {\n      // Build a new subtree in a random direction\n      bool valid_subtree = false;\n      double ave_subtree = 0;\n      double log_sum_weight_subtree = -std::numeric_limits<double>::infinity();\n\n      if (this->rand_uniform_() > 0.5) {\n        this->z_.ps_point::operator=(z_plus);\n        valid_subtree = build_tree(this->depth_, z_propose, ave_subtree,\n                                   log_sum_weight_subtree, H0, 1, n_leapfrog,\n                                   sum_metro_prob, logger);\n        z_plus.ps_point::operator=(this->z_);\n      } else {\n        this->z_.ps_point::operator=(z_minus);\n        valid_subtree = build_tree(this->depth_, z_propose, ave_subtree,\n                                   log_sum_weight_subtree, H0, -1, n_leapfrog,\n                                   sum_metro_prob, logger);\n        z_minus.ps_point::operator=(this->z_);\n      }\n\n      if (!valid_subtree)\n        break;\n      std::tie(ave, log_sum_weight) = stable_sum(\n          ave, log_sum_weight, ave_subtree, log_sum_weight_subtree);\n\n      // Sample from an accepted subtree\n      ++(this->depth_);\n\n      double accept_prob = std::exp(log_sum_weight_subtree - log_sum_weight);\n      if (this->rand_uniform_() < accept_prob)\n        z_sample = z_propose;\n\n      // Break if exhaustion criterion is satisfied\n      if (std::fabs(ave) < x_delta_)\n        break;\n    }\n\n    this->n_leapfrog_ = n_leapfrog;\n\n    // Compute average acceptance probabilty across entire trajectory,\n    // even over subtrees that may have been rejected\n    double accept_prob = sum_metro_prob / static_cast<double>(n_leapfrog + 1);\n\n    this->z_.ps_point::operator=(z_sample);\n    this->energy_ = this->hamiltonian_.H(this->z_);\n    return sample(this->z_.q, -this->z_.V, accept_prob);\n  }\n\n  void get_sampler_param_names(std::vector<std::string>& names) {\n    names.push_back(\"stepsize__\");\n    names.push_back(\"treedepth__\");\n    names.push_back(\"n_leapfrog__\");\n    names.push_back(\"divergent__\");\n    names.push_back(\"energy__\");\n  }\n\n  void get_sampler_params(std::vector<double>& values) {\n    values.push_back(this->epsilon_);\n    values.push_back(this->depth_);\n    values.push_back(this->n_leapfrog_);\n    values.push_back(this->divergent_);\n    values.push_back(this->energy_);\n  }\n\n  /**\n   * Recursively build a new subtree to completion or until\n   * the subtree becomes invalid.  Returns validity of the\n   * resulting subtree.\n   *\n   * @param depth Depth of the desired subtree\n   * @param z_propose State proposed from subtree\n   * @param ave Weighted average of dG/dt across trajectory\n   * @param log_sum_weight Log of summed weights across trajectory\n   * @param H0 Hamiltonian of initial state\n   * @param sign Direction in time to built subtree\n   * @param n_leapfrog Summed number of leapfrog evaluations\n   * @param sum_metro_prob Summed Metropolis probabilities across trajectory\n   * @param logger Logger for messages\n   * @return whether built tree is valid\n   */\n  bool build_tree(int depth, ps_point& z_propose, double& ave,\n                  double& log_sum_weight, double H0, double sign,\n                  int& n_leapfrog, double& sum_metro_prob,\n                  callbacks::logger& logger) {\n    // Base case\n    if (depth == 0) {\n      this->integrator_.evolve(this->z_, this->hamiltonian_,\n                               sign * this->epsilon_, logger);\n      ++n_leapfrog;\n\n      double h = this->hamiltonian_.H(this->z_);\n      if (boost::math::isnan(h))\n        h = std::numeric_limits<double>::infinity();\n\n      if ((h - H0) > this->max_deltaH_)\n        this->divergent_ = true;\n\n      double dG_dt = this->hamiltonian_.dG_dt(this->z_, logger);\n\n      std::tie(ave, log_sum_weight)\n          = stable_sum(ave, log_sum_weight, dG_dt, H0 - h);\n\n      if (H0 - h > 0)\n        sum_metro_prob += 1;\n      else\n        sum_metro_prob += std::exp(H0 - h);\n\n      z_propose = this->z_;\n\n      return !this->divergent_;\n    }\n    // General recursion\n\n    // Build the left subtree\n    double ave_left = 0;\n    double log_sum_weight_left = -std::numeric_limits<double>::infinity();\n\n    bool valid_left\n        = build_tree(depth - 1, z_propose, ave_left, log_sum_weight_left, H0,\n                     sign, n_leapfrog, sum_metro_prob, logger);\n\n    if (!valid_left)\n      return false;\n    std::tie(ave, log_sum_weight)\n        = stable_sum(ave, log_sum_weight, ave_left, log_sum_weight_left);\n\n    // Build the right subtree\n    ps_point z_propose_right(this->z_);\n    double ave_right = 0;\n    double log_sum_weight_right = -std::numeric_limits<double>::infinity();\n\n    bool valid_right = build_tree(depth - 1, z_propose_right, ave_right,\n                                  log_sum_weight_right, H0, sign, n_leapfrog,\n                                  sum_metro_prob, logger);\n\n    if (!valid_right)\n      return false;\n    std::tie(ave, log_sum_weight)\n        = stable_sum(ave, log_sum_weight, ave_right, log_sum_weight_right);\n\n    // Multinomial sample from right subtree\n    double ave_subtree;\n    double log_sum_weight_subtree;\n    std::tie(ave_subtree, log_sum_weight_subtree) = stable_sum(\n        ave_left, log_sum_weight_left, ave_right, log_sum_weight_right);\n\n    double accept_prob\n        = std::exp(log_sum_weight_right - log_sum_weight_subtree);\n    if (this->rand_uniform_() < accept_prob)\n      z_propose = z_propose_right;\n\n    return std::abs(ave_subtree) >= x_delta_;\n  }\n\n  /**\n   * a1 and a2 are running averages of the form\n   *   \\f$ a1 =   ( \\sum_{n \\in N1} w_{n} f_{n} )\n   *            / ( \\sum_{n \\in N1}  w_{n} ) \\f$\n   *   \\f$ a2 =   ( \\sum_{n \\in N2} w_{n} f_{n} )\n   *            / ( \\sum_{n \\in N2}  w_{n} ) \\f$\n   * and the weights are the respective normalizing constants\n   *   \\f$ w1 = \\sum_{n \\in N1} w_{n} \\f$\n   *   \\f$ w2 = \\sum_{n \\in N2} w_{n}. \\f$\n   *\n   * This function returns the pooled average\n   *   \\f$ sum_a =   ( \\sum_{n \\in N1 \\cup N2} w_{n} f_{n} )\n   *               / ( \\sum_{n \\in N1 \\cup N2}  w_{n} ) \\f$\n   * and the pooled weights\n   *   \\f$ log_sum_w = log(w1 + w2). \\f$\n   *\n   * @param[in] a1 First running average, f1 / w1\n   * @param[in] log_w1 Log of first summed weight\n   * @param[in] a2 Second running average\n   * @param[in] log_w2 Log of second summed weight\n   * @return Pair of average of input running averages and log of summed input\n   * weights\n   */\n  static std::pair<double, double> stable_sum(double a1, double log_w1,\n                                              double a2, double log_w2) {\n    if (log_w2 > log_w1) {\n      const double e = std::exp(log_w1 - log_w2);\n      return std::make_pair((e * a1 + a2) / (1 + e), log_w2 + std::log1p(e));\n    } else {\n      const double e = std::exp(log_w2 - log_w1);\n      return std::make_pair((a1 + e * a2) / (1 + e), log_w1 + std::log1p(e));\n    }\n  }\n\n  int depth_;\n  int max_depth_;\n  double max_deltaH_;\n  double x_delta_;\n\n  int n_leapfrog_;\n  bool divergent_;\n  double energy_;\n};\n\n}  // namespace mcmc\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "90a9ac2ac2d62cb28b0c557e0c38480edc100bcc", "size": 9185, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/mcmc/hmc/xhmc/base_xhmc.hpp", "max_stars_repo_name": "Dr-G/stan", "max_stars_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "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/mcmc/hmc/xhmc/base_xhmc.hpp", "max_issues_repo_name": "Dr-G/stan", "max_issues_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "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/mcmc/hmc/xhmc/base_xhmc.hpp", "max_forks_repo_name": "Dr-G/stan", "max_forks_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "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.6868327402, "max_line_length": 79, "alphanum_fraction": 0.6318998367, "num_tokens": 2579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.1602162124592855}}
{"text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html.\n#include \"opencv2/slideio/imagetools.hpp\"\n#include \"opencv2/slideio.hpp\"\n#include \"opencv2/imgproc.hpp\"\n#include \"opencv2/slideio/memory_stream.hpp\"\n\n#include <openjpeg.h>\n\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <fstream>\n\nusing namespace cv;\n\nvoid slideio::ImageTools::readJp2KFile(const std::string& filePath, cv::OutputArray output)\n{\n    auto fileSize = boost::filesystem::file_size(filePath);\n    if(fileSize<=0)\n        throw std::runtime_error(\n            (boost::format(\"Invalid file: %1%\") % filePath).str());\n    \n    std::ifstream file(filePath, std::ios::binary);\n    // Stop eating new lines in binary mode!!!\n    file.unsetf(std::ios::skipws);\n    // reserve capacity\n    std::vector<uint8_t> vec;\n    vec.reserve(fileSize);\n    // read the data:\n    vec.insert(vec.begin(),\n        std::istream_iterator<uint8_t>(file),\n        std::istream_iterator<uint8_t>());\n    decodeJp2KStream(vec, output);\n}\n\nstatic int getComponentDataType(const opj_image_comp_t* comp)\n{\n    switch(comp->prec)\n    {\n    case 8:\n        return ((comp->sgnd)?CV_8S:CV_8U);\n    case 16:\n        return ((comp->sgnd)?CV_16S:CV_16U);\n    case 32:\n        return CV_32S;\n    }\n    throw std::runtime_error(\n        (boost::format(\"Unknown data type of data: %1%\") % (int)comp->bpp).str());\n}\n\nstatic OPJ_CODEC_FORMAT getJP2KCodec(const std::vector<uint8_t>& data)\n{\n    static const unsigned char jpc_header[] = {0xff, 0x4f};\n    static const unsigned char jp2_box_jp[] = {0x6a, 0x50, 0x20, 0x20}; /* 'jP  ' */\n\n    const uint8_t *buf = data.data();\n    size_t len = data.size();\n\n    OPJ_CODEC_FORMAT eCodecFormat;\n    if (len >= sizeof(jpc_header) &&\n            memcmp(buf, jpc_header, sizeof(jpc_header)) == 0) {\n        eCodecFormat = OPJ_CODEC_J2K;\n    }\n    else if (len >= 4 + sizeof(jp2_box_jp) &&\n               memcmp(buf + 4, jp2_box_jp, sizeof(jp2_box_jp)) == 0) {\n        eCodecFormat = OPJ_CODEC_JP2;\n    }\n    else\n    {\n        throw std::runtime_error(\"Unknown file format\");\n    }\n    return eCodecFormat;\n}\n\nvoid slideio::ImageTools::decodeJp2KStream(\n    const std::vector<uint8_t>& data,\n    cv::OutputArray output,\n    const std::vector<int>& channelIndices,\n    bool forceYUV)\n{\n    opj_codec_t* codec(nullptr);\n    opj_image_t* image(nullptr);\n    opj_stream_t* stream(nullptr);\n    try\n    {\n        OPJ_CODEC_FORMAT codecId = getJP2KCodec(data);\n        OPJStreamUserData userData((uint8_t*)data.data(), data.size());\n        stream = createOPJMemoryStream(&userData, data.size(), true);\n        codec = opj_create_decompress(codecId);\n        if(!codec)\n            throw std::runtime_error(\"Cannot get required codec\");\n        opj_dparameters_t jp2dParams;\n        opj_set_default_decoder_parameters(&jp2dParams);\n        if (!opj_setup_decoder(codec, &jp2dParams)){\n            throw std::runtime_error(\"Cannot setup codec\");\n        }\n        if(!opj_read_header(stream, codec, &image) || (image->numcomps == 0)){\n            throw std::runtime_error(\"Error reading image header\");\n        }\n        if(forceYUV)\n            image->color_space = OPJ_CLRSPC_SYCC;\n        // decode the image\n        OPJ_BOOL ret = opj_decode(codec, stream, image);\n        if(!ret)\n            throw std::runtime_error(\"Error by decoding of Jp2K stream\");\n\n        opj_end_decompress(codec,stream);\n        opj_destroy_codec(codec);\n        codec=nullptr;\n        opj_stream_destroy(stream);\n        stream = nullptr;\n\n        const OPJ_UINT32 imageWidth = image->x1 - image->x0;\n        const OPJ_UINT32 imageHeight = image->y1 - image->y0;\n        const OPJ_UINT32 numComps = image->numcomps;\n        const int dt = getComponentDataType(image->comps);\n\n        output.create(imageHeight, imageWidth,CV_MAKETYPE(dt, image->numcomps));\n        const cv::Size imageSize(imageWidth, imageHeight); \n\n        std::vector<cv::Mat> imagePlanes;\n        std::vector<int> channels(channelIndices);\n\n        for(OPJ_UINT32 channel=0; channel<numComps; channel++)\n        {\n            const opj_image_comp& component = image->comps[channel];\n            // create a cv::Mat object with the buffer \n            cv::Mat compRaster32S(component.h, component.w, CV_MAKETYPE(CV_32S, 1), component.data);\n            // convert raster from 32 bit integer to the original type\n            cv::Mat compRaster;\n            compRaster32S.convertTo(compRaster, CV_MAKETYPE(dt,1));\n            // check if we need to resize the component\n            if(component.w!=imageWidth || component.h!=imageHeight)\n            {\n                // resize the component so it fits to the image size\n                cv::Mat resized(imageSize.height, imageSize.width, CV_MAKETYPE(dt, 1));\n                cv::resize(compRaster, resized, imageSize);\n                imagePlanes.push_back(resized);\n            }\n            else\n            {\n                imagePlanes.push_back(compRaster);\n            }\n        }\n        cv::Mat targetImage;\n        if(forceYUV)\n        {\n            cv::Mat cvImage;\n            cv::merge(imagePlanes, cvImage);\n            cv::cvtColor(cvImage, targetImage, cv::COLOR_YUV2RGB);\n        }\n        else\n        {\n            cv::merge(imagePlanes, targetImage);\n        }\n        if(channels.empty())\n        {\n            // if no channel is defined - return all channels\n            targetImage.copyTo(output);\n        }\n        else\n        {\n            std::vector<cv::Mat> targetChannels;\n            for(const int& channel : channels)\n            {\n                cv::Mat channelRaster;\n                cv::extractChannel(targetImage,channelRaster, channel);\n                targetChannels.push_back(channelRaster);\n            }\n            if(targetChannels.size()==1)\n            {\n                targetChannels[0].copyTo(output);\n            }\n            else\n            {\n                cv::merge(targetChannels, output);\n            }\n        }\n        opj_image_destroy(image);\n    }\n    catch(std::exception& ex)\n    {\n        if(codec)\n            opj_destroy_codec(codec);\n        if(image)\n            opj_image_destroy(image);\n        if(stream)\n            opj_stream_destroy(stream);\n        throw ex;\n    }\n}\n", "meta": {"hexsha": "87e65556b3a9d21f2590ea018a9bf93450982c92", "size": 6368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/slideio/src/imagetools/jp2kcodec.cpp", "max_stars_repo_name": "Booritas/opencv_slideio", "max_stars_repo_head_hexsha": "86789b833cb5411c71757e7a1d49d481b1b905cd", "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/slideio/src/imagetools/jp2kcodec.cpp", "max_issues_repo_name": "Booritas/opencv_slideio", "max_issues_repo_head_hexsha": "86789b833cb5411c71757e7a1d49d481b1b905cd", "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/slideio/src/imagetools/jp2kcodec.cpp", "max_forks_repo_name": "Booritas/opencv_slideio", "max_forks_repo_head_hexsha": "86789b833cb5411c71757e7a1d49d481b1b905cd", "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.9948186528, "max_line_length": 100, "alphanum_fraction": 0.5984610553, "num_tokens": 1574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16020021497968093}}
{"text": "#include \"storm/abstraction/jani/EdgeAbstractor.h\"\n\n#include <chrono>\n\n#include <boost/iterator/transform_iterator.hpp>\n\n#include \"storm/abstraction/BottomStateResult.h\"\n#include \"storm/abstraction/AbstractionInformation.h\"\n\n#include \"storm/storage/dd/DdManager.h\"\n#include \"storm/storage/dd/Add.h\"\n\n#include \"storm/storage/jani/Edge.h\"\n#include \"storm/storage/jani/EdgeDestination.h\"\n\n#include \"storm/utility/solver.h\"\n#include \"storm/utility/macros.h\"\n\n#include \"storm-config.h\"\n#include \"storm/adapters/RationalFunctionAdapter.h\"\n\nnamespace storm {\n    namespace abstraction {\n        namespace jani {\n            template <storm::dd::DdType DdType, typename ValueType>\n            EdgeAbstractor<DdType, ValueType>::EdgeAbstractor(uint64_t edgeId, storm::jani::Edge const& edge, AbstractionInformation<DdType>& abstractionInformation, std::shared_ptr<storm::utility::solver::SmtSolverFactory> const& smtSolverFactory, bool useDecomposition, bool addPredicatesForValidBlocks, bool debug) : smtSolver(smtSolverFactory->create(abstractionInformation.getExpressionManager())), abstractionInformation(abstractionInformation), edgeId(edgeId), edge(edge), localExpressionInformation(abstractionInformation), evaluator(abstractionInformation.getExpressionManager()), relevantPredicatesAndVariables(), cachedDd(abstractionInformation.getDdManager().getBddZero(), 0), decisionVariables(), useDecomposition(useDecomposition), addPredicatesForValidBlocks(addPredicatesForValidBlocks), skipBottomStates(false), forceRecomputation(true), abstractGuard(abstractionInformation.getDdManager().getBddZero()), bottomStateAbstractor(abstractionInformation, {!edge.getGuard()}, smtSolverFactory), debug(debug) {\n                \n                // Make the second component of relevant predicates have the right size.\n                relevantPredicatesAndVariables.second.resize(edge.getNumberOfDestinations());\n                \n                // Assert all constraints to enforce legal variable values.\n                for (auto const& constraint : abstractionInformation.getConstraints()) {\n                    smtSolver->add(constraint);\n                    bottomStateAbstractor.constrain(constraint);\n                }\n                \n                // Assert the guard of the command.\n                smtSolver->add(edge.getGuard());\n                \n                // Construct assigned variables.\n                for (auto const& destination : edge.getDestinations()) {\n                    for (auto const& assignment : destination.getOrderedAssignments()) {\n                        assignedVariables.insert(assignment.getExpressionVariable());\n                    }\n                }\n                \n                // Log whether or not predicates are added to ensure valid blocks.\n                if (this->addPredicatesForValidBlocks) {\n                    STORM_LOG_DEBUG(\"Adding more predicates to ensure valid blocks.\");\n                }\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            void EdgeAbstractor<DdType, ValueType>::refine(std::vector<uint_fast64_t> const& predicates) {\n                // Add all predicates to the variable partition.\n                for (auto predicateIndex : predicates) {\n                    localExpressionInformation.addExpression(predicateIndex);\n                }\n                \n                // Next, we check whether there is work to be done by recomputing the relevant predicates and checking\n                // whether they changed.\n                std::pair<std::set<uint_fast64_t>, std::vector<std::set<uint_fast64_t>>> newRelevantPredicates = this->computeRelevantPredicates();\n                \n                // Check whether we need to recompute the abstraction.\n                bool relevantPredicatesChanged = this->relevantPredicatesChanged(newRelevantPredicates);\n                if (relevantPredicatesChanged) {\n                    addMissingPredicates(newRelevantPredicates);\n                }\n                forceRecomputation |= relevantPredicatesChanged;\n                \n                // Refine bottom state abstractor. Note that this does not trigger a recomputation yet.\n                bottomStateAbstractor.refine(predicates);\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            storm::expressions::Expression const& EdgeAbstractor<DdType, ValueType>::getGuard() const {\n                return edge.get().getGuard();\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            uint64_t EdgeAbstractor<DdType, ValueType>::getNumberOfUpdates(uint64_t player1Choice) const {\n                return edge.get().getNumberOfDestinations();\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            std::map<storm::expressions::Variable, storm::expressions::Expression> EdgeAbstractor<DdType, ValueType>::getVariableUpdates(uint64_t auxiliaryChoice) const {\n                return edge.get().getDestination(auxiliaryChoice).getAsVariableToExpressionMap();\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            std::set<storm::expressions::Variable> const& EdgeAbstractor<DdType, ValueType>::getAssignedVariables() const {\n                return assignedVariables;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            void EdgeAbstractor<DdType, ValueType>::recomputeCachedBdd() {\n                if (useDecomposition) {\n                    recomputeCachedBddWithDecomposition();\n                } else {\n                    recomputeCachedBddWithoutDecomposition();\n                }\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            void EdgeAbstractor<DdType, ValueType>::recomputeCachedBddWithDecomposition() {\n                STORM_LOG_TRACE(\"Recomputing BDD for edge with id \" << edgeId << \" and guard \" << edge.get().getGuard() << \" using the decomposition.\");\n                auto start = std::chrono::high_resolution_clock::now();\n                \n                // compute a decomposition of the command\n                //  * start with all relevant blocks: blocks of assignment variables and variables in the rhs of assignments\n                //  * go through all assignments of all updates and merge relevant blocks that are related via an assignment\n                //  * repeat this until nothing changes anymore\n                //  * the resulting blocks are the decomposition\n                \n                // Start by constructing the relevant blocks.\n                std::set<uint64_t> allRelevantBlocks;\n                std::map<storm::expressions::Variable, uint64_t> variableToBlockIndex;\n                for (auto const& destination : edge.get().getDestinations()) {\n                    for (auto const& assignment : destination.getOrderedAssignments().getAllAssignments()) {\n                        allRelevantBlocks.insert(localExpressionInformation.getBlockIndexOfVariable(assignment.getExpressionVariable()));\n                        \n                        auto rhsVariableBlocks = localExpressionInformation.getBlockIndicesOfVariables(assignment.getAssignedExpression().getVariables());\n                        allRelevantBlocks.insert(rhsVariableBlocks.begin(), rhsVariableBlocks.end());\n                    }\n                }\n                STORM_LOG_TRACE(\"Found \" << allRelevantBlocks.size() << \" relevant block(s).\");\n                \n                // Create a block partition.\n                std::vector<std::set<uint64_t>> relevantBlockPartition;\n                std::map<storm::expressions::Variable, uint64_t> variableToLocalBlockIndex;\n                uint64_t index = 0;\n                for (auto const& blockIndex : allRelevantBlocks) {\n                    relevantBlockPartition.emplace_back(std::set<uint64_t>({blockIndex}));\n                    for (auto const& variable : localExpressionInformation.getVariableBlockWithIndex(blockIndex)) {\n                        variableToLocalBlockIndex[variable] = index;\n                    }\n                    ++index;\n                }\n                \n                // Merge all blocks that are related via the right-hand side of assignments.\n                for (auto const& destination : edge.get().getDestinations()) {\n                    for (auto const& assignment : destination.getOrderedAssignments().getAllAssignments()) {\n                        std::set<storm::expressions::Variable> rhsVariables = assignment.getAssignedExpression().getVariables();\n                        \n                        if (!rhsVariables.empty()) {\n                            uint64_t blockToKeep = variableToLocalBlockIndex.at(*rhsVariables.begin());\n                            for (auto const& variable : rhsVariables) {\n                                uint64_t block = variableToLocalBlockIndex.at(variable);\n                                if (block != blockToKeep) {\n                                    for (auto const& blockIndex : relevantBlockPartition[block]) {\n                                        for (auto const& variable : localExpressionInformation.getVariableBlockWithIndex(blockIndex)) {\n                                            variableToLocalBlockIndex[variable] = blockToKeep;\n                                        }\n                                    }\n                                    relevantBlockPartition[blockToKeep].insert(relevantBlockPartition[block].begin(), relevantBlockPartition[block].end());\n                                    relevantBlockPartition[block].clear();\n                                }\n                            }\n                        }\n                    }\n                }\n                \n                // Proceed by relating the blocks via assignment-variables and the expressions of their assigned expressions.\n                bool changed = false;\n                do {\n                    changed = false;\n                    for (auto const& destination : edge.get().getDestinations()) {\n                        for (auto const& assignment : destination.getOrderedAssignments().getAllAssignments()) {\n                            std::set<storm::expressions::Variable> rhsVariables = assignment.getAssignedExpression().getVariables();\n                            \n                            if (!rhsVariables.empty()) {\n                                storm::expressions::Variable const& representativeVariable = *rhsVariables.begin();\n                                uint64_t representativeBlock = variableToLocalBlockIndex.at(representativeVariable);\n                                uint64_t assignmentVariableBlock = variableToLocalBlockIndex.at(assignment.getExpressionVariable());\n                                \n                                // If the blocks are different, we merge them now\n                                if (assignmentVariableBlock != representativeBlock) {\n                                    changed = true;\n                                    \n                                    for (auto const& blockIndex : relevantBlockPartition[assignmentVariableBlock]) {\n                                        for (auto const& variable : localExpressionInformation.getVariableBlockWithIndex(blockIndex)) {\n                                            variableToLocalBlockIndex[variable] = representativeBlock;\n                                        }\n                                    }\n                                    relevantBlockPartition[representativeBlock].insert(relevantBlockPartition[assignmentVariableBlock].begin(), relevantBlockPartition[assignmentVariableBlock].end());\n                                    relevantBlockPartition[assignmentVariableBlock].clear();\n                                }\n                            }\n                        }\n                    }\n                } while (changed);\n                \n                // Now remove all blocks that are empty and obtain the partition.\n                std::vector<std::set<uint64_t>> cleanedRelevantBlockPartition;\n                for (auto& outerBlock : relevantBlockPartition) {\n                    if (!outerBlock.empty()) {\n                        cleanedRelevantBlockPartition.emplace_back();\n                        \n                        for (auto const& innerBlock : outerBlock) {\n                            if (!localExpressionInformation.getExpressionBlock(innerBlock).empty()) {\n                                cleanedRelevantBlockPartition.back().insert(innerBlock);\n                            }\n                        }\n                        \n                        if (cleanedRelevantBlockPartition.back().empty()) {\n                            cleanedRelevantBlockPartition.pop_back();\n                        }\n                    }\n                }\n                relevantBlockPartition = std::move(cleanedRelevantBlockPartition);\n                \n                STORM_LOG_TRACE(\"Decomposition into \" << relevantBlockPartition.size() << \" blocks.\");\n                if (this->debug) {\n                    uint64_t blockIndex = 0;\n                    for (auto const& block : relevantBlockPartition) {\n                        STORM_LOG_TRACE(\"Predicates of block \" << blockIndex << \":\");\n                        std::set<uint64_t> blockPredicateIndices;\n                        for (auto const& innerBlock : block) {\n                            blockPredicateIndices.insert(localExpressionInformation.getExpressionBlock(innerBlock).begin(), localExpressionInformation.getExpressionBlock(innerBlock).end());\n                        }\n                        \n                        for (auto const& predicateIndex : blockPredicateIndices) {\n                            STORM_LOG_TRACE(abstractionInformation.get().getPredicateByIndex(predicateIndex));\n                        }\n                        \n                        ++blockIndex;\n                    }\n                }\n                \n                std::set<storm::expressions::Variable> variablesContainedInGuard = edge.get().getGuard().getVariables();\n                \n                // Check whether we need to enumerate the guard. This is the case if the blocks related by the guard\n                // are not contained within a single block of our decomposition.\n                bool enumerateAbstractGuard = true;\n                std::set<uint64_t> guardBlocks = localExpressionInformation.getBlockIndicesOfVariables(variablesContainedInGuard);\n                for (auto const& block : relevantBlockPartition) {\n                    bool allContained = true;\n                    for (auto const& guardBlock : guardBlocks) {\n                        if (block.find(guardBlock) == block.end()) {\n                            allContained = false;\n                            break;\n                        }\n                    }\n                    if (allContained) {\n                        enumerateAbstractGuard = false;\n                    }\n                }\n                \n                uint64_t numberOfSolutions = 0;\n                uint64_t numberOfTotalSolutions = 0;\n                \n                // If we need to enumerate the guard, do it only once now.\n                if (enumerateAbstractGuard) {\n                    std::set<uint64_t> relatedGuardPredicates = localExpressionInformation.getRelatedExpressions(variablesContainedInGuard);\n                    std::vector<storm::expressions::Variable> guardDecisionVariables;\n                    std::vector<std::pair<storm::expressions::Variable, uint_fast64_t>> guardVariablesAndPredicates;\n                    for (auto const& element : relevantPredicatesAndVariables.first) {\n                        if (relatedGuardPredicates.find(element.second) != relatedGuardPredicates.end()) {\n                            guardDecisionVariables.push_back(element.first);\n                            guardVariablesAndPredicates.push_back(element);\n                        }\n                    }\n                    abstractGuard = this->getAbstractionInformation().getDdManager().getBddZero();\n                    smtSolver->allSat(guardDecisionVariables, [this,&guardVariablesAndPredicates,&numberOfSolutions] (storm::solver::SmtSolver::ModelReference const& model) {\n                        abstractGuard |= getSourceStateBdd(model, guardVariablesAndPredicates);\n                        ++numberOfSolutions;\n                        return true;\n                    });\n                    STORM_LOG_TRACE(\"Enumerated \" << numberOfSolutions << \" solutions for abstract guard.\");\n                    \n                    // Now that we have the abstract guard, we can add it as an assertion to the solver before enumerating\n                    // the other solutions.\n                    \n                    // Create a new backtracking point before adding the guard.\n                    smtSolver->push();\n                    \n                    // Create the guard constraint.\n                    std::pair<std::vector<storm::expressions::Expression>, std::unordered_map<uint_fast64_t, storm::expressions::Variable>> result = abstractGuard.toExpression(this->getAbstractionInformation().getExpressionManager());\n                    \n                    // Then add it to the solver.\n                    for (auto const& expression : result.first) {\n                        smtSolver->add(expression);\n                    }\n                    \n                    // Finally associate the level variables with the predicates.\n                    for (auto const& indexVariablePair : result.second) {\n                        smtSolver->add(storm::expressions::iff(indexVariablePair.second, this->getAbstractionInformation().getPredicateForDdVariableIndex(indexVariablePair.first)));\n                    }\n                }\n                \n                // Then enumerate the solutions for each of the blocks of the decomposition\n                uint64_t usedNondeterminismVariables = 0;\n                uint64_t blockCounter = 0;\n                std::vector<storm::dd::Bdd<DdType>> blockBdds;\n                for (auto const& block : relevantBlockPartition) {\n                    std::set<uint64_t> relevantPredicates;\n                    for (auto const& innerBlock : block) {\n                        relevantPredicates.insert(localExpressionInformation.getExpressionBlock(innerBlock).begin(), localExpressionInformation.getExpressionBlock(innerBlock).end());\n                    }\n                    \n                    if (relevantPredicates.empty()) {\n                        STORM_LOG_TRACE(\"Block does not contain relevant predicates, skipping it.\");\n                        continue;\n                    }\n                    \n                    std::vector<storm::expressions::Variable> transitionDecisionVariables;\n                    std::vector<std::pair<storm::expressions::Variable, uint_fast64_t>> sourceVariablesAndPredicates;\n                    for (auto const& element : relevantPredicatesAndVariables.first) {\n                        if (relevantPredicates.find(element.second) != relevantPredicates.end()) {\n                            transitionDecisionVariables.push_back(element.first);\n                            sourceVariablesAndPredicates.push_back(element);\n                        }\n                    }\n                    \n                    std::vector<std::vector<std::pair<storm::expressions::Variable, uint_fast64_t>>> destinationVariablesAndPredicates;\n                    for (uint64_t destinationIndex = 0; destinationIndex < edge.get().getNumberOfDestinations(); ++destinationIndex) {\n                        destinationVariablesAndPredicates.emplace_back();\n                        for (auto const& assignment : edge.get().getDestination(destinationIndex).getOrderedAssignments().getAllAssignments()) {\n                            uint64_t assignmentVariableBlockIndex = localExpressionInformation.getBlockIndexOfVariable(assignment.getVariable().getExpressionVariable());\n                            \n                            if (block.find(assignmentVariableBlockIndex) != block.end()) {\n                                std::set<uint64_t> const& assignmentVariableBlock = localExpressionInformation.getExpressionBlock(assignmentVariableBlockIndex);\n                                for (auto const& element : relevantPredicatesAndVariables.second[destinationIndex]) {\n                                    if (assignmentVariableBlock.find(element.second) != assignmentVariableBlock.end()) {\n                                        destinationVariablesAndPredicates.back().push_back(element);\n                                        transitionDecisionVariables.push_back(element.first);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                    \n                    std::unordered_map<storm::dd::Bdd<DdType>, std::vector<storm::dd::Bdd<DdType>>> sourceToDistributionsMap;\n                    numberOfSolutions = 0;\n                    smtSolver->allSat(transitionDecisionVariables, [&sourceToDistributionsMap,this,&numberOfSolutions,&sourceVariablesAndPredicates,&destinationVariablesAndPredicates] (storm::solver::SmtSolver::ModelReference const& model) {\n                        sourceToDistributionsMap[getSourceStateBdd(model, sourceVariablesAndPredicates)].push_back(getDistributionBdd(model, destinationVariablesAndPredicates));\n                        ++numberOfSolutions;\n                        return true;\n                    });\n                    STORM_LOG_TRACE(\"Enumerated \" << numberOfSolutions << \" solutions for block \" << blockCounter << \".\");\n                    numberOfTotalSolutions += numberOfSolutions;\n                    \n                    // Now we search for the maximal number of choices of player 2 to determine how many DD variables we\n                    // need to encode the nondeterminism.\n                    uint_fast64_t maximalNumberOfChoices = 0;\n                    for (auto const& sourceDistributionsPair : sourceToDistributionsMap) {\n                        maximalNumberOfChoices = std::max(maximalNumberOfChoices, static_cast<uint_fast64_t>(sourceDistributionsPair.second.size()));\n                    }\n                    \n                    // We now compute how many variables we need to encode the choices. We add one to the maximal number of\n                    // choices to account for a possible transition to a bottom state.\n                    uint_fast64_t numberOfVariablesNeeded = (maximalNumberOfChoices > 1) ? (static_cast<uint_fast64_t>(std::ceil(std::log2(maximalNumberOfChoices + (blockCounter == 0 ? 1 : 0))))) : (blockCounter == 0 ? 1 : 0);\n\n                    // Finally, build overall result.\n                    storm::dd::Bdd<DdType> resultBdd = this->getAbstractionInformation().getDdManager().getBddZero();\n                    \n                    for (auto const& sourceDistributionsPair : sourceToDistributionsMap) {\n                        STORM_LOG_ASSERT(!sourceDistributionsPair.first.isZero(), \"The source BDD must not be empty.\");\n                        STORM_LOG_ASSERT(!sourceDistributionsPair.second.empty(), \"The distributions must not be empty.\");\n                        \n                        // We start with the distribution index of 1, because 0 is reserved for a potential bottom choice.\n                        uint_fast64_t distributionIndex = blockCounter == 0 ? 1 : 0;\n                        storm::dd::Bdd<DdType> allDistributions = this->getAbstractionInformation().getDdManager().getBddZero();\n                        for (auto const& distribution : sourceDistributionsPair.second) {\n                            allDistributions |= distribution && this->getAbstractionInformation().encodePlayer2Choice(distributionIndex, usedNondeterminismVariables, usedNondeterminismVariables + numberOfVariablesNeeded);\n                            ++distributionIndex;\n                            STORM_LOG_ASSERT(!allDistributions.isZero(), \"The BDD must not be empty.\");\n                        }\n                        resultBdd |= sourceDistributionsPair.first && allDistributions;\n                        STORM_LOG_ASSERT(!resultBdd.isZero(), \"The BDD must not be empty.\");\n                    }\n                    usedNondeterminismVariables += numberOfVariablesNeeded;\n                    \n                    blockBdds.push_back(resultBdd);\n                    ++blockCounter;\n                }\n                \n                if (enumerateAbstractGuard) {\n                    smtSolver->pop();\n                }\n                \n                // multiply the results\n                storm::dd::Bdd<DdType> resultBdd = getAbstractionInformation().getDdManager().getBddOne();\n                uint64_t blockIndex = 0;\n                for (auto const& blockBdd : blockBdds) {\n                    resultBdd &= blockBdd;\n                    ++blockIndex;\n                }\n                \n                // If we did not explicitly enumerate the guard, we can construct it from the result BDD.\n                if (!enumerateAbstractGuard) {\n                    std::set<storm::expressions::Variable> allVariables(getAbstractionInformation().getSuccessorVariables());\n                    auto player2Variables = getAbstractionInformation().getPlayer2VariableSet(usedNondeterminismVariables);\n                    allVariables.insert(player2Variables.begin(), player2Variables.end());\n                    auto auxVariables = getAbstractionInformation().getAuxVariableSet(0, getAbstractionInformation().getAuxVariableCount());\n                    allVariables.insert(auxVariables.begin(), auxVariables.end());\n                    \n                    std::set<storm::expressions::Variable> variablesToAbstract;\n                    std::set_intersection(allVariables.begin(), allVariables.end(), resultBdd.getContainedMetaVariables().begin(), resultBdd.getContainedMetaVariables().end(), std::inserter(variablesToAbstract, variablesToAbstract.begin()));\n                    \n                    abstractGuard = resultBdd.existsAbstract(variablesToAbstract);\n                } else {\n                    // Multiply the abstract guard as it can contain predicates that are not mentioned in the blocks.\n                    resultBdd &= abstractGuard;\n                }\n                \n                // multiply with missing identities\n                resultBdd &= computeMissingDestinationIdentities();\n\n                // cache and return result\n                resultBdd &= this->getAbstractionInformation().encodePlayer1Choice(edgeId, this->getAbstractionInformation().getPlayer1VariableCount());\n                \n                // Cache the result.\n                cachedDd = GameBddResult<DdType>(resultBdd, usedNondeterminismVariables);\n                \n                auto end = std::chrono::high_resolution_clock::now();\n                \n                STORM_LOG_TRACE(\"Enumerated \" << numberOfTotalSolutions << \" solutions in \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << \"ms.\");\n                forceRecomputation = false;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            void EdgeAbstractor<DdType, ValueType>::recomputeCachedBddWithoutDecomposition() {\n                STORM_LOG_TRACE(\"Recomputing BDD for edge with id \" << edgeId << \" and guard \" << edge.get().getGuard());\n                auto start = std::chrono::high_resolution_clock::now();\n                \n                // Create a mapping from source state DDs to their distributions.\n                std::unordered_map<storm::dd::Bdd<DdType>, std::vector<storm::dd::Bdd<DdType>>> sourceToDistributionsMap;\n                uint64_t numberOfSolutions = 0;\n                smtSolver->allSat(decisionVariables, [&sourceToDistributionsMap,this,&numberOfSolutions] (storm::solver::SmtSolver::ModelReference const& model) {\n                    sourceToDistributionsMap[getSourceStateBdd(model, relevantPredicatesAndVariables.first)].push_back(getDistributionBdd(model, relevantPredicatesAndVariables.second));\n                    ++numberOfSolutions;\n                    return true;\n                });\n                \n                // Now we search for the maximal number of choices of player 2 to determine how many DD variables we\n                // need to encode the nondeterminism.\n                uint_fast64_t maximalNumberOfChoices = 0;\n                for (auto const& sourceDistributionsPair : sourceToDistributionsMap) {\n                    maximalNumberOfChoices = std::max(maximalNumberOfChoices, static_cast<uint_fast64_t>(sourceDistributionsPair.second.size()));\n                }\n                \n                // We now compute how many variables we need to encode the choices. We add one to the maximal number of\n                // choices to account for a possible transition to a bottom state.\n                uint_fast64_t numberOfVariablesNeeded = static_cast<uint_fast64_t>(std::ceil(std::log2(maximalNumberOfChoices + 1)));\n                \n                // Finally, build overall result.\n                storm::dd::Bdd<DdType> resultBdd = this->getAbstractionInformation().getDdManager().getBddZero();\n                if (!skipBottomStates) {\n                    abstractGuard = this->getAbstractionInformation().getDdManager().getBddZero();\n                }\n                for (auto const& sourceDistributionsPair : sourceToDistributionsMap) {\n                    if (!skipBottomStates) {\n                        abstractGuard |= sourceDistributionsPair.first;\n                    }\n                    \n                    STORM_LOG_ASSERT(!sourceDistributionsPair.first.isZero(), \"The source BDD must not be empty.\");\n                    STORM_LOG_ASSERT(!sourceDistributionsPair.second.empty(), \"The distributions must not be empty.\");\n                    // We start with the distribution index of 1, becase 0 is reserved for a potential bottom choice.\n                    uint_fast64_t distributionIndex = 1;\n                    storm::dd::Bdd<DdType> allDistributions = this->getAbstractionInformation().getDdManager().getBddZero();\n                    for (auto const& distribution : sourceDistributionsPair.second) {\n                        allDistributions |= distribution && this->getAbstractionInformation().encodePlayer2Choice(distributionIndex, 0, numberOfVariablesNeeded);\n                        ++distributionIndex;\n                        STORM_LOG_ASSERT(!allDistributions.isZero(), \"The BDD must not be empty.\");\n                    }\n                    resultBdd |= sourceDistributionsPair.first && allDistributions;\n                    STORM_LOG_ASSERT(!resultBdd.isZero(), \"The BDD must not be empty.\");\n                }\n                \n                resultBdd &= computeMissingDestinationIdentities();\n                resultBdd &= this->getAbstractionInformation().encodePlayer1Choice(edgeId, this->getAbstractionInformation().getPlayer1VariableCount());\n                STORM_LOG_ASSERT(sourceToDistributionsMap.empty() || !resultBdd.isZero(), \"The BDD must not be empty, if there were distributions.\");\n                \n                // Cache the result.\n                cachedDd = GameBddResult<DdType>(resultBdd, numberOfVariablesNeeded);\n                auto end = std::chrono::high_resolution_clock::now();\n                \n                STORM_LOG_TRACE(\"Enumerated \" << numberOfSolutions << \" solutions in \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << \"ms.\");\n                forceRecomputation = false;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            std::pair<std::set<uint_fast64_t>, std::set<uint_fast64_t>> EdgeAbstractor<DdType, ValueType>::computeRelevantPredicates(storm::jani::OrderedAssignments const& assignments) const {\n                std::pair<std::set<uint_fast64_t>, std::set<uint_fast64_t>> result;\n                \n                std::set<storm::expressions::Variable> assignedVariables;\n                for (auto const& assignment : assignments.getAllAssignments()) {\n                    // Also, variables appearing on the right-hand side of an assignment are relevant for source state.\n                    auto const& rightHandSidePredicates = localExpressionInformation.getExpressionsUsingVariables(assignment.getAssignedExpression().getVariables());\n                    result.first.insert(rightHandSidePredicates.begin(), rightHandSidePredicates.end());\n                    \n                    // Variables that are being assigned are relevant for the successor state.\n                    storm::expressions::Variable const& assignedVariable = assignment.getExpressionVariable();\n                    auto const& leftHandSidePredicates = localExpressionInformation.getExpressionsUsingVariable(assignedVariable);\n                    result.second.insert(leftHandSidePredicates.begin(), leftHandSidePredicates.end());\n                    \n                    // Predicates that are indirectly related to the assigned variables are relevant for the source state (if requested).\n                    if (this->addPredicatesForValidBlocks) {\n                        auto const& assignedVariableBlock = localExpressionInformation.getRelatedExpressions(assignedVariable);\n                        result.first.insert(assignedVariableBlock.begin(), assignedVariableBlock.end());\n                    }\n                }\n                \n                return result;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            std::pair<std::set<uint_fast64_t>, std::vector<std::set<uint_fast64_t>>> EdgeAbstractor<DdType, ValueType>::computeRelevantPredicates() const {\n                std::pair<std::set<uint_fast64_t>, std::vector<std::set<uint_fast64_t>>> result;\n                \n                // To start with, all predicates related to the guard are relevant source predicates.\n                result.first = localExpressionInformation.getExpressionsUsingVariables(edge.get().getGuard().getVariables());\n                \n                // Then, we add the predicates that become relevant, because of some update.\n                for (auto const& destination : edge.get().getDestinations()) {\n                    std::pair<std::set<uint_fast64_t>, std::set<uint_fast64_t>> relevantUpdatePredicates = computeRelevantPredicates(destination.getOrderedAssignments());\n                    result.first.insert(relevantUpdatePredicates.first.begin(), relevantUpdatePredicates.first.end());\n                    result.second.push_back(relevantUpdatePredicates.second);\n                }\n                \n                return result;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            bool EdgeAbstractor<DdType, ValueType>::relevantPredicatesChanged(std::pair<std::set<uint_fast64_t>, std::vector<std::set<uint_fast64_t>>> const& newRelevantPredicates) const {\n                if (newRelevantPredicates.first.size() > relevantPredicatesAndVariables.first.size()) {\n                    return true;\n                }\n                \n                for (uint_fast64_t index = 0; index < edge.get().getNumberOfDestinations(); ++index) {\n                    if (newRelevantPredicates.second[index].size() > relevantPredicatesAndVariables.second[index].size()) {\n                        return true;\n                    }\n                }\n                \n                return false;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            void EdgeAbstractor<DdType, ValueType>::addMissingPredicates(std::pair<std::set<uint_fast64_t>, std::vector<std::set<uint_fast64_t>>> const& newRelevantPredicates) {\n                // Determine and add new relevant source predicates.\n                std::vector<std::pair<storm::expressions::Variable, uint_fast64_t>> newSourceVariables = this->getAbstractionInformation().declareNewVariables(relevantPredicatesAndVariables.first, newRelevantPredicates.first);\n                for (auto const& element : newSourceVariables) {\n                    allRelevantPredicates.insert(element.second);\n                    smtSolver->add(storm::expressions::iff(element.first, this->getAbstractionInformation().getPredicateByIndex(element.second)));\n                    decisionVariables.push_back(element.first);\n                }\n                \n                // Insert the new variables into the record of relevant source variables.\n                relevantPredicatesAndVariables.first.insert(relevantPredicatesAndVariables.first.end(), newSourceVariables.begin(), newSourceVariables.end());\n                std::sort(relevantPredicatesAndVariables.first.begin(), relevantPredicatesAndVariables.first.end(), [] (std::pair<storm::expressions::Variable, uint_fast64_t> const& first, std::pair<storm::expressions::Variable, uint_fast64_t> const& second) { return first.second < second.second; } );\n                \n                // Do the same for every update.\n                for (uint_fast64_t index = 0; index < edge.get().getNumberOfDestinations(); ++index) {\n                    std::vector<std::pair<storm::expressions::Variable, uint_fast64_t>> newSuccessorVariables = this->getAbstractionInformation().declareNewVariables(relevantPredicatesAndVariables.second[index], newRelevantPredicates.second[index]);\n                    for (auto const& element : newSuccessorVariables) {\n                        allRelevantPredicates.insert(element.second);\n                        smtSolver->add(storm::expressions::iff(element.first, this->getAbstractionInformation().getPredicateByIndex(element.second).substitute(edge.get().getDestination(index).getAsVariableToExpressionMap())));\n                        decisionVariables.push_back(element.first);\n                    }\n                    \n                    relevantPredicatesAndVariables.second[index].insert(relevantPredicatesAndVariables.second[index].end(), newSuccessorVariables.begin(), newSuccessorVariables.end());\n                    std::sort(relevantPredicatesAndVariables.second[index].begin(), relevantPredicatesAndVariables.second[index].end(), [] (std::pair<storm::expressions::Variable, uint_fast64_t> const& first, std::pair<storm::expressions::Variable, uint_fast64_t> const& second) { return first.second < second.second; } );\n                }\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            storm::dd::Bdd<DdType> EdgeAbstractor<DdType, ValueType>::getSourceStateBdd(storm::solver::SmtSolver::ModelReference const& model, std::vector<std::pair<storm::expressions::Variable, uint_fast64_t>> const& variablePredicates) const {\n                storm::dd::Bdd<DdType> result = this->getAbstractionInformation().getDdManager().getBddOne();\n                for (auto variableIndexPairIt = variablePredicates.rbegin(), variableIndexPairIte = variablePredicates.rend(); variableIndexPairIt != variableIndexPairIte; ++variableIndexPairIt) {\n                    auto const& variableIndexPair = *variableIndexPairIt;\n                    if (model.getBooleanValue(variableIndexPair.first)) {\n                        result &= this->getAbstractionInformation().encodePredicateAsSource(variableIndexPair.second);\n                    } else {\n                        result &= !this->getAbstractionInformation().encodePredicateAsSource(variableIndexPair.second);\n                    }\n                }\n                \n                STORM_LOG_ASSERT(!result.isZero(), \"Source must not be empty.\");\n                return result;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            storm::dd::Bdd<DdType> EdgeAbstractor<DdType, ValueType>::getDistributionBdd(storm::solver::SmtSolver::ModelReference const& model, std::vector<std::vector<std::pair<storm::expressions::Variable, uint_fast64_t>>> const& variablePredicates) const {\n                storm::dd::Bdd<DdType> result = this->getAbstractionInformation().getDdManager().getBddZero();\n                \n                for (uint_fast64_t destinationIndex = 0; destinationIndex < edge.get().getNumberOfDestinations(); ++destinationIndex) {\n                    storm::dd::Bdd<DdType> updateBdd = this->getAbstractionInformation().getDdManager().getBddOne();\n                    \n                    // Translate block variables for this update into a successor block.\n                    for (auto variableIndexPairIt = variablePredicates[destinationIndex].rbegin(), variableIndexPairIte = variablePredicates[destinationIndex].rend(); variableIndexPairIt != variableIndexPairIte; ++variableIndexPairIt) {\n                        auto const& variableIndexPair = *variableIndexPairIt;\n                        if (model.getBooleanValue(variableIndexPair.first)) {\n                            updateBdd &= this->getAbstractionInformation().encodePredicateAsSuccessor(variableIndexPair.second);\n                        } else {\n                            updateBdd &= !this->getAbstractionInformation().encodePredicateAsSuccessor(variableIndexPair.second);\n                        }\n                    }\n                    \n                    updateBdd &= this->getAbstractionInformation().encodeAux(destinationIndex, 0, this->getAbstractionInformation().getAuxVariableCount());\n                    result |= updateBdd;\n                }\n                \n                STORM_LOG_ASSERT(!result.isZero(), \"Distribution must not be empty.\");\n                return result;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            storm::dd::Bdd<DdType> EdgeAbstractor<DdType, ValueType>::computeMissingDestinationIdentities() const {\n                storm::dd::Bdd<DdType> result = this->getAbstractionInformation().getDdManager().getBddZero();\n                \n                for (uint_fast64_t destinationIndex = 0; destinationIndex < edge.get().getNumberOfDestinations(); ++destinationIndex) {\n                    // Compute the identities that are missing for this update.\n                    auto updateRelevantIt = relevantPredicatesAndVariables.second[destinationIndex].rbegin();\n                    auto updateRelevantIte = relevantPredicatesAndVariables.second[destinationIndex].rend();\n                    \n                    storm::dd::Bdd<DdType> updateIdentity = this->getAbstractionInformation().getDdManager().getBddOne();\n                    for (uint_fast64_t predicateIndex = this->getAbstractionInformation().getNumberOfPredicates() - 1;; --predicateIndex) {\n                        if (updateRelevantIt == updateRelevantIte || updateRelevantIt->second != predicateIndex) {\n                            updateIdentity &= this->getAbstractionInformation().getPredicateIdentity(predicateIndex);\n                        } else {\n                            ++updateRelevantIt;\n                        }\n                        \n                        if (predicateIndex == 0) {\n                            break;\n                        }\n                    }\n                    \n                    result |= updateIdentity && this->getAbstractionInformation().encodeAux(destinationIndex, 0, this->getAbstractionInformation().getAuxVariableCount());\n                }\n                return result;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            GameBddResult<DdType> EdgeAbstractor<DdType, ValueType>::abstract() {\n                if (forceRecomputation) {\n                    this->recomputeCachedBdd();\n                } else {\n                    cachedDd.bdd &= computeMissingDestinationIdentities();\n                }\n                \n                STORM_LOG_TRACE(\"Edge produces \" << cachedDd.bdd.getNonZeroCount() << \" transitions.\");\n                \n                return cachedDd;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            BottomStateResult<DdType> EdgeAbstractor<DdType, ValueType>::getBottomStateTransitions(storm::dd::Bdd<DdType> const& reachableStates, uint_fast64_t numberOfPlayer2Variables, boost::optional<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& locationVariables) {\n                \n                STORM_LOG_TRACE(\"Computing bottom state transitions of edge with index \" << edgeId << \".\");\n                BottomStateResult<DdType> result(this->getAbstractionInformation().getDdManager().getBddZero(), this->getAbstractionInformation().getDdManager().getBddZero());\n                \n                // If the guard of this command is a predicate, there are not bottom states/transitions.\n                if (skipBottomStates) {\n                    STORM_LOG_TRACE(\"Skipping bottom state computation for this edge.\");\n                    return result;\n                }\n                \n                storm::dd::Bdd<DdType> reachableStatesWithEdge = reachableStates && abstractGuard;\n                // needed?\n//                if (locationVariables) {\n//                    reachableStatesWithEdge = (reachableStates && abstractGuard && this->getAbstractionInformation().encodeLocation(locationVariables.get().first, edge.get().getSourceLocationIndex())).existsAbstract(this->getAbstractionInformation().getSourceLocationVariables());\n//                } else {\n//                    reachableStatesWithEdge = (reachableStates && abstractGuard).existsAbstract(this->getAbstractionInformation().getSourceLocationVariables());\n//                }\n\n                \n                // Use the state abstractor to compute the set of abstract states that has this command enabled but\n                // still has a transition to a bottom state.\n                bottomStateAbstractor.constrain(reachableStatesWithEdge);\n                if (locationVariables) {\n                    result.states = bottomStateAbstractor.getAbstractStates() && reachableStatesWithEdge && this->getAbstractionInformation().encodeLocation(locationVariables.get().first, edge.get().getSourceLocationIndex());\n                } else {\n                    result.states = bottomStateAbstractor.getAbstractStates() && reachableStatesWithEdge;\n                }\n\n                // If the result is empty one time, we can skip the bottom state computation from now on.\n                if (result.states.isZero()) {\n                    skipBottomStates = true;\n                }\n                \n                // Now equip all these states with an actual transition to a bottom state.\n                result.transitions = result.states && this->getAbstractionInformation().getAllPredicateIdentities() && this->getAbstractionInformation().getBottomStateBdd(false, false);\n                \n                // Mark the states as bottom states.\n                result.states &= this->getAbstractionInformation().getBottomStateBdd(true, false);\n                \n                // Add the command encoding and the next free player 2 encoding.\n                result.transitions &= this->getAbstractionInformation().encodePlayer1Choice(edgeId, this->getAbstractionInformation().getPlayer1VariableCount()) && this->getAbstractionInformation().encodePlayer2Choice(0, 0, numberOfPlayer2Variables) && this->getAbstractionInformation().encodeAux(0, 0, this->getAbstractionInformation().getAuxVariableCount());\n                \n                return result;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            storm::dd::Add<DdType, ValueType> EdgeAbstractor<DdType, ValueType>::getEdgeDecoratorAdd(boost::optional<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& locationVariables) const {\n                storm::dd::Add<DdType, ValueType> result = this->getAbstractionInformation().getDdManager().template getAddZero<ValueType>();\n                for (uint_fast64_t destinationIndex = 0; destinationIndex < edge.get().getNumberOfDestinations(); ++destinationIndex) {\n                    storm::dd::Add<DdType, ValueType> tmp = this->getAbstractionInformation().encodeAux(destinationIndex, 0, this->getAbstractionInformation().getAuxVariableCount()).template toAdd<ValueType>() * this->getAbstractionInformation().getDdManager().getConstant(evaluator.asRational(edge.get().getDestination(destinationIndex).getProbability()));\n                    if (locationVariables) {\n                        tmp *= this->getAbstractionInformation().encodeLocation(locationVariables.get().second, edge.get().getDestination(destinationIndex).getLocationIndex()).template toAdd<ValueType>();\n                    }\n                    result += tmp;\n                }\n                \n                storm::dd::Add<DdType, ValueType> tmp = this->getAbstractionInformation().getDdManager().template getAddOne<ValueType>();\n                if (locationVariables) {\n                    tmp *= this->getAbstractionInformation().encodeLocation(locationVariables.get().first, edge.get().getSourceLocationIndex()).template toAdd<ValueType>();\n                }\n                tmp *= this->getAbstractionInformation().encodePlayer1Choice(edgeId, this->getAbstractionInformation().getPlayer1VariableCount()).template toAdd<ValueType>();\n                \n                result *= tmp;\n                \n                return result;\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            storm::jani::Edge const& EdgeAbstractor<DdType, ValueType>::getConcreteEdge() const {\n                return edge.get();\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            AbstractionInformation<DdType> const& EdgeAbstractor<DdType, ValueType>::getAbstractionInformation() const {\n                return abstractionInformation.get();\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            AbstractionInformation<DdType>& EdgeAbstractor<DdType, ValueType>::getAbstractionInformation() {\n                return abstractionInformation.get();\n            }\n            \n            template <storm::dd::DdType DdType, typename ValueType>\n            void EdgeAbstractor<DdType, ValueType>::notifyGuardIsPredicate() {\n                skipBottomStates = true;\n            }\n            \n            template class EdgeAbstractor<storm::dd::DdType::CUDD, double>;\n            template class EdgeAbstractor<storm::dd::DdType::Sylvan, double>;\n#ifdef STORM_HAVE_CARL\n            template class EdgeAbstractor<storm::dd::DdType::Sylvan, storm::RationalNumber>;\n#endif\n        }\n    }\n}\n", "meta": {"hexsha": "ee52cae71d41596e8c22fe0b830e4a24022a388c", "size": 51123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "artifact/storm/src/storm/abstraction/jani/EdgeAbstractor.cpp", "max_stars_repo_name": "glatteis/tacas21-artifact", "max_stars_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "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": "artifact/storm/src/storm/abstraction/jani/EdgeAbstractor.cpp", "max_issues_repo_name": "glatteis/tacas21-artifact", "max_issues_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "artifact/storm/src/storm/abstraction/jani/EdgeAbstractor.cpp", "max_forks_repo_name": "glatteis/tacas21-artifact", "max_forks_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-05T12:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T12:39:53.000Z", "avg_line_length": 68.5294906166, "max_line_length": 1021, "alphanum_fraction": 0.5879154197, "num_tokens": 9386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1602002116887026}}
{"text": "#include \"visual_utility/VisualUtilityEstimator.h\"\n\n#include <ros/ros.h>\n#include <rosbag/view.h>\n#include <limits>\n#include <math.h>\n#include <boost/scoped_ptr.hpp>\n#include <boost/foreach.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/unordered_map.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <algorithm>\n#include \"visual_utility/cvutils-inl.h\"\n#include \"cv_utils/DisplayImages.h\"\n#include \"cv_utils/IntegralHistogram-Inl.h\"\n#include \"visual_utility/Parameter.h\"\n#include \"visual_utility/VisualUtilityEstimation.h\"\n#include \"base/StringHash.h\"\n#include \"visual_utility/VisualUtilityROSParams.h\"\n#include \"hog_detector/integral_hog_detector_inl.h\"\n\nusing namespace cv;\nusing namespace boost;\nusing namespace std;\n\nnamespace cv {\ninline std::size_t hash_value(const cv::Rect& key) {\n  size_t seed = 7823;\n  hash_combine(seed, key.x);\n  hash_combine(seed, key.y);\n  hash_combine(seed, key.height);\n  hash_combine(seed, key.width);\n  return seed;\n}\n\ninline std::size_t hash_value(const cv::Size& key) {\n  size_t seed = 54326;\n  hash_combine(seed, key.height);\n  hash_combine(seed, key.width);\n  return seed;\n}\n} // end namespace\n\nnamespace visual_utility {\n\n// ---------- Start VisualUtilityEstimator -----------\n\nVisualUtilityEstimator::~VisualUtilityEstimator() {}\n\nconst Mat* VisualUtilityEstimator::GetLastTransform() const {\n  return NULL;\n}\n\nvoid VisualUtilityEstimator::CalculateVisualUtility(\n  const string& filename,\n  const vector<Rect>& rois,\n  double time,\n  std::vector<ROIScore>* vuOut) {\n  // Open up the file\n  Mat cvImage = imread(filename);\n\n  // Calculate the visual utility\n  CalculateVisualUtility(cvImage, rois, time, vuOut);\n}\n\nvoid VisualUtilityEstimator::CalculateVisualUtility(\n  const cv::Mat& image,\n  const vector<Rect>& rois,\n  double time,\n  std::vector<ROIScore>* vuOut) {\n\n  ROS_ASSERT(vuOut);\n  lastRuntime_.reset(NULL);\n\n  // Start by initializing anything that's needed with the image\n  ros::WallTime startTime = ros::WallTime::now();\n  InitBoxCalculator(image, time);\n  ros::WallDuration initTime = ros::WallTime::now() - startTime;\n\n  ROS_INFO_STREAM(\"Processing time for initialization: \" << initTime.toSec());\n\n  // Now collect all the rois of interest for each box size\n  unordered_map<Size, shared_ptr<PointScores> > pointLists;\n  vuOut->resize(rois.size());\n  int i = 0;\n  for(vector<Rect>::const_iterator regionI = rois.begin();\n      regionI != rois.end(); ++regionI, ++i) {\n    Size winSize(regionI->width, regionI->height);\n    unordered_map<Size, shared_ptr<PointScores> >::iterator pointsPtr =\n      pointLists.find(winSize);\n    if (pointsPtr == pointLists.end()) {\n      pointsPtr = pointLists.insert(pair<Size, shared_ptr<PointScores> >(\n        winSize,\n        shared_ptr<PointScores>(new PointScores()))).first;\n    }\n    (*vuOut)[i].second = *regionI;\n    pointsPtr->second->push_back(pair<double*, Point>(&((*vuOut)[i].first),\n                                                      Point(regionI->x,\n                                                            regionI->y)));\n  }\n\n  // Now for each box size, calculate the visual utility scores across\n  // the image.\n  startTime = ros::WallTime::now();\n  for(unordered_map<Size, shared_ptr<PointScores> >::const_iterator\n        pointsI = pointLists.begin();\n      pointsI != pointLists.end(); ++pointsI) {\n    CalculateVisualUtilityBoxAcrossImage(pointsI->first.width,\n                                         pointsI->first.height,\n                                         *pointsI->second);\n  }\n\n  ros::WallDuration calculationTime = ros::WallTime::now() - startTime;\n  ROS_INFO_STREAM(\"Processing time for calculation: \" << calculationTime);\n  if (lastRuntime_.get() == NULL) {\n    lastRuntime_.reset(new double((initTime + calculationTime).toSec()));\n  }\n}\n\n// Helper function for the following CalculateVisualUtility that\n// creates a list of points to evaluate at based on a grid and a mask.\nvoid VisualUtilityEstimator::GetLocationsForEvaluation(\n  const Mat& image,\n  int minX, int minY,\n  int strideX, int strideY,\n  double width, double height,\n  const Mat& mask,\n  Mat& scores,\n  PointScores* locations) {\n  ROS_ASSERT(mask.empty() || mask.type() == CV_8U);\n  ROS_ASSERT(scores.type() == CV_64F);\n  ROS_ASSERT(locations);\n  locations->clear();\n\n  for (int i = 0, curX = minX; curX < image.cols-width; ++i) {\n    for (int j = 0, curY = minY; curY < image.rows-height; ++j) {\n      if (mask.empty() || mask.at<uint8_t>(i,j)) {\n        locations->push_back(pair<double*, Point>(scores.ptr<double>(i,j),\n                                                  Point(curX,curY)));\n      }\n      curY += strideY;\n    }\n    curX += strideX;\n  }\n}\n\nvoid VisualUtilityEstimator::GetGridHeightsAndWidths(const Mat& image,\n                                                     int minX, int minY,\n                                                     int minW, int minH,\n                                                     double strideW,\n                                                     double strideH,\n                                                     bool fixAspect,\n                                                     vector<double>* widths,\n                                                     vector<double>* heights){\n  ROS_ASSERT(widths);\n  ROS_ASSERT(heights);\n\n  if (fixAspect) {\n    strideH = strideW;\n  }\n\n  for (double curW = minW; curW < image.cols-minX; curW *= strideW) {\n    widths->push_back(cvRound(curW));\n  }\n\n  for (double curH = minH; curH < image.rows-minY; curH *= strideH) {\n    heights->push_back(cvRound(curH));\n  }\n\n  // If the aspect ratio is fixed, truncate the list of sizes to the\n  // smaller one.\n  if (fixAspect) {\n    if (heights->size() > widths->size()) {\n      heights->resize(widths->size());\n    } else {\n      widths->resize(heights->size());\n    }\n  }\n  \n}\n\nvoid VisualUtilityEstimator::InitializeScoreGrid(\n  const Mat& image,\n  int minX, int minY,\n  int strideX, int strideY,\n  bool fixAspect,\n  const vector<double>& widths,\n  const vector<double>& heights,\n  Mat* scoreGrid) {\n  ROS_ASSERT(scoreGrid);\n\n  vector<int> scoreSize;\n  scoreSize.push_back(widths.size());\n  if (!fixAspect) scoreSize.push_back(heights.size());\n  scoreSize.push_back(\n    std::max<int>(1, (image.cols - minX - widths[0]) / strideX));\n  scoreSize.push_back(\n    std::max<int>(1, (image.rows - minY - heights[0]) / strideY));\n  *scoreGrid = cv::Mat(scoreSize.size(), &scoreSize[0], CV_64F, \n                   -numeric_limits<double>::infinity());\n}\n\ncv::Mat VisualUtilityEstimator::CalculateVisualUtility(\n  const cv::Mat& image,\n  int minX, int minY,\n  int minW, int minH,\n  int strideX, int strideY,\n  double strideW, double strideH,\n  bool fixAspect,\n  double time,\n  const cv::Mat& mask) {\n  Mat scores;\n\n  lastRuntime_.reset(NULL);\n\n  // Start by initializing anything that's needed with the image\n  ros::WallTime startTime = ros::WallTime::now();\n  InitBoxCalculator(image, time);\n  ros::WallDuration initTime = ros::WallTime::now() - startTime;\n\n  vector<double> widths;\n  vector<double> heights;\n  GetGridHeightsAndWidths(image, minX, minY, minW, minH, strideW, strideH,\n                          fixAspect, &widths, &heights);\n\n  // Build the output score matrix\n  InitializeScoreGrid(image, minX, minY, strideX, strideY, fixAspect,\n                      widths, heights,\n                      &scores);\n  ROS_ASSERT(mask.empty() ||\n             (mask.dims == scores.dims &&\n              mask.size == scores.size));\n\n  \n  // Now walk through the different size of boxes\n  PointScores locations;\n  ros::WallDuration calculationTime(0);\n  for (unsigned int widthI = 0u; widthI < widths.size(); ++widthI) {\n    if (fixAspect) {\n      Mat scorePlane(2, &scores.size[1], CV_64F, \n                     scores.ptr(widthI), &scores.step[1]);\n      GetLocationsForEvaluation(image,\n                                minX, minY, strideX, strideY,\n                                widths[widthI],\n                                heights[widthI],\n                                (mask.empty() ? mask :\n                                 Mat(2, &mask.size[1], mask.type(),\n                                     const_cast<uchar*>(mask.ptr(widthI)),\n                                     &mask.step[1])),\n                                scorePlane,\n                                &locations);\n\n      startTime = ros::WallTime::now();\n      CalculateVisualUtilityBoxAcrossImage(widths[widthI],\n                                           heights[widthI],\n                                           locations);\n      calculationTime += ros::WallTime::now() - startTime;\n      \n    } else {\n      for (unsigned int heightI = 0u; heightI < heights.size(); ++heightI) {\n        Mat scorePlane(2, &scores.size[2], CV_64F, \n                       scores.ptr(widthI, heightI),\n                       &scores.step[2]);\n        GetLocationsForEvaluation(image, \n                                  minX, minY, strideX, strideY,\n                                  widths[widthI],\n                                  heights[heightI],\n                                  (mask.empty() ? mask :\n                                   Mat(2, &mask.size[2], mask.type(),\n                                       const_cast<uchar*>(mask.ptr(widthI,\n                                                                  heightI)),\n                                       &mask.step[2])),\n                                  scorePlane,\n                                  &locations);\n        \n        startTime = ros::WallTime::now();\n        CalculateVisualUtilityBoxAcrossImage(widths[widthI],\n                                             heights[heightI],\n                                             locations);\n        calculationTime += ros::WallTime::now() - startTime;\n      }\n    }\n  }\n\n  if (lastRuntime_.get() == NULL) {\n    lastRuntime_.reset(new double((initTime + calculationTime).toSec()));\n  }\n\n  return scores;\n}\n\nbool VisualUtilityEstimator::InitBoxCalculator(const cv::Mat& image,\n                                               double time) {\n  ROS_FATAL(\"InitBoxCalculator is not implemented\");\n  ROS_ASSERT(false);\n  return false;\n}\n\nvoid VisualUtilityEstimator::CalculateVisualUtilityBoxAcrossImage(\n    double width, double height,\n    const PointScores& locations) {\n\n  for (PointScores::const_iterator pointI = locations.begin();\n       pointI != locations.end();\n       ++pointI) {\n    *pointI->first = CalculateVisualUtilityOfBox(pointI->second.x,\n                                                 pointI->second.y,\n                                                 cvRound(height),\n                                                 cvRound(width));\n  }\n  \n}\n\n\ndouble VisualUtilityEstimator::CalculateVisualUtilityOfBox(int x, int y,\n                                                           int h, int w) {\n  ROS_FATAL(\"Calculating the visual utility of a box is not implemented. \"\n            \"Try wrapping it in one of the wrapper visual \"\n            \"utility estimators like RelativeEntropyVUWrapper\");\n  ROS_ASSERT(false);\n  return 0; // To make compiler happy\n}\n\n//-------- Start LABMotionVUEstimator --------------\n\nLABMotionVUEstimator::~LABMotionVUEstimator() {}\n\nconst Mat* LABMotionVUEstimator::GetLastTransform() const {\n  if (lastTransform_.empty()) {\n    return NULL;\n  }\n  return &lastTransform_;\n}\n\n//#define GREY_OVERRIDE 0\n\ncv::Mat_<double> LABMotionVUEstimator::CalculateVisualUtility(\n  const Mat& image, double time) {\n  \n  if (image.channels() != 3) {\n    ROS_ERROR(\"Image is not in color. We need a BGR image\");\n    return cv::Mat_<double>();\n  }\n\n  if (image.depth() != CV_8U) {\n    ROS_FATAL(\"For speed reasons, the image must be still in its natural \"\n              \"8-bit format\");\n    return cv::Mat_<double>();\n  }\n\n  // Get the LAB and greyscale images\n  Mat_<uchar> tmpGreyImage;\n  Mat_<double> curGreyImage;\n  cvtColor(image, tmpGreyImage, CV_BGR2GRAY);\n  tmpGreyImage.convertTo(curGreyImage, CV_64FC1, 1.0/255);\n\n  // The L value in the image is scaled to be 0-255 instead of 0-100,\n  // so we need to rescale it\n  Mat_<Vec3b> tmpLabImage;\n  Mat_<Vec3d> curLabImage;\n  cvtColor(image, tmpLabImage, CV_BGR2Lab);\n  tmpLabImage.assignTo(curLabImage, CV_64FC3);\n  vector<Mat> channels;\n  split(curLabImage, channels);\n  channels[0] *= 100./255.;\n  merge(channels, curLabImage);\n\n  if (lastLabImage_.empty()) {\n    // This is the first image added\n    lastLabImage_ = curLabImage;\n    lastGreyImage_ = curGreyImage;\n    return cv::Mat_<double>();\n  }\n\n  // Calculate the affine transform to convert the last image to the\n  // current one\n  Mat lastTransform_ = transformEstimator_.EstimateTransform(lastGreyImage_,\n                                                             curGreyImage);\n\n  // Now warp the old image to the current one\n#ifdef GREY_OVERRIDE\n  Mat_<double> warpedImage;\n  if (!lastTransform_.empty()) {\n    warpedImage =  transformEstimator_.ApplyTransform(\n      lastGreyImage_,\n      lastTransform_,\n      geo::BORDER_TRANSPARENT,\n      0.0,\n      curGreyImage);\n  } else {\n    warpedImage = lastGreyImage_;\n  }\n#else\n  Mat_<Vec3d> warpedImage ;\n  if (!lastTransform_.empty()) {\n    warpedImage = transformEstimator_.ApplyTransform(\n      lastLabImage_,\n      lastTransform_,\n      geo::BORDER_TRANSPARENT,\n      Vec3d(0,0,0),\n      curLabImage);\n  } else {\n    warpedImage = lastLabImage_;\n  }\n#endif\n\n  // Next calculate the distance between the two images\n  Mat_<float> dist(image.rows, image.cols, 0.0);\n\n#ifdef GREY_OVERRIDE\n  dist = abs(curGreyImage - warpedImage);\n#else\n  Mat_<Vec3d> diff = curLabImage - warpedImage;\n  diff = diff.mul(diff);\n\n  vector<Mat> diffChannels;\n  split(diff, diffChannels);\n  for (unsigned int i = 0u; i < diffChannels.size(); i++) {\n    add(dist, diffChannels[i], dist, noArray(), CV_32F);\n    //dist += diffChannels[i];\n  }\n  sqrt(dist, dist);\n#endif\n\n  lastLabImage_ = curLabImage;\n  lastGreyImage_ = curGreyImage;\n\n  // Do erode and dilate (aka openeing)\n  morphologyEx(dist, dist, MORPH_OPEN,\n               Mat_<int>::ones(openingSize_, openingSize_));\n\n  return dist;\n}\n\n// Functor for calculating the sums needed for the alpha calculation\nstruct SumForAlphaFunctor {\n  SumForAlphaFunctor(int& _nValidPixels,\n                     double& _paretoSum,\n                     double _logMode)\n    : nValidPixels(_nValidPixels), paretoSum(_paretoSum), logMode(_logMode){}\n\n  inline void operator()(const double val) {\n    const double lVal = log(val);\n    if (lVal >= logMode) {\n      nValidPixels++;\n      paretoSum += lVal - logMode;\n    }\n  }\n\n  int& nValidPixels;\n  double& paretoSum;\n  const double logMode;\n  \n};\n\n// Functor for building up the histogram\nstruct FillHistogramFunctor {\n  FillHistogramFunctor(vector<double>& hist, double minVal, double maxVal)\n    : hist_(hist), minVal_(minVal), maxVal_(maxVal),\n      histFactor((hist.size()-1)/(maxVal-minVal)) {}\n\n  inline void operator()(double val) {\n    if (val >= minVal_ && val <= maxVal_) {\n      hist_[static_cast<int>(histFactor*(val-minVal_))] += val;\n    }\n  }\n    \n    \n  vector<double>& hist_;\n  const double minVal_;\n  const double maxVal_;\n  const double histFactor;\n};\n\ndouble LABMotionVUEstimator::CalculateParetoThreshold(\n  const Mat_<double>& dist) {\n  // Fist find the range of distance values\n  double maxVal;\n  double minVal;\n  minMaxLoc(dist, &minVal, &maxVal);\n\n  if (minVal == maxVal) {\n    return std::numeric_limits<double>::infinity();\n  }\n\n  // Calculate the histogram\n  const int HIST_SIZE = 256;\n  vector<double> hist(HIST_SIZE+1, 0.0);\n  double histFactor = ((double)HIST_SIZE)/(maxVal - minVal);\n  double bucketSize = 1./histFactor;\n  cvutils::ApplyToEachElement<FillHistogramFunctor, double>(dist,\n    FillHistogramFunctor(hist, minVal, maxVal));\n\n  // Calculate the mode since we'll ignore points below that\n  int modeBucket=0;\n  double modeVal = 0;\n  for (unsigned int i = 0u; i < hist.size(); ++i) {\n    if (hist[i] > modeVal) {\n      modeVal = hist[i];\n      modeBucket = i;\n    }\n  }\n  double mode = ((double)modeBucket)/histFactor + minVal + bucketSize/2;\n  double logMode = log(mode);\n\n  // Now calculate the alpha parameter\n  int nValidPixels = 0;\n  double paretoSum = 0;\n  cvutils::ApplyToEachElement<SumForAlphaFunctor, double>(dist,\n    SumForAlphaFunctor(nValidPixels, paretoSum, logMode));\n  double alpha = nValidPixels / paretoSum;\n\n  // Alternate way to calcuate alpha using the buckets\n  /*int nValidPixels2 = 0;\n  double paretoSum2 = 0;\n  for (int i = 0; i < HIST_SIZE; ++i) {\n    const double bucketCenter = ((double)i)/histFactor + minVal +\n      bucketSize/2;\n    if (bucketCenter >= mode) {\n      nValidPixels2 += hist[i];\n      paretoSum2 += hist[i]*(log(bucketCenter) - logMode);\n    }\n  }\n  double alpha2 = nValidPixels2 / paretoSum2;\n\n  ROS_WARN_STREAM(\"Alpha1: \" << alpha << \" Alpha2: \" << alpha2);*/\n\n  // Finally calculate the threshold to where we have paretoThresh_\n  // fraction of the pixels\n  return exp((alpha*logMode-log(paretoThreshold_)) / alpha);\n}\n\n// ------------ Start SpectralSaliency ------------\nSpectralSaliency::~SpectralSaliency() {}\n\nMat_<double> SpectralSaliency::CalculateVisualUtility(\n  const Mat& image, double time) {\n  Mat_<double> retval;\n\n  // Get a floating point grey version of the image\n  /*Mat tmpGreyImage;\n  if (image.channels() != 1) {\n    cvtColor(image, tmpGreyImage, CV_BGR2GRAY);\n  } else {\n    tmpGreyImage = image;\n  }\n  Mat_<double> greyImage;\n  tmpGreyImage.convertTo(greyImage, CV_64FC1, 1.0/255);\n  Mat_<Vec<double, 2> > greyComplex;\n  vector<Mat> greyGroup;\n  greyGroup.push_back(greyImage);\n  greyGroup.push_back(Mat_<double>::zeros(image.rows, image.cols));\n  merge(greyGroup, greyComplex);\n\n  Mat_<Vec<double, 2> > fftMat(image.rows, image.cols);\n  dft(greyComplex, fftMat, DFT_COMPLEX_OUTPUT);\n\n  vector<Mat> splitFftMat;\n  split(fftMat, splitFftMat);\n\n  Mat_<double> phaseMat;\n  Mat_<double> logAmplitude;\n  cartToPolar(splitFftMat[0], splitFftMat[1], logAmplitude, phaseMat);\n  log(logAmplitude, logAmplitude);\n\n  Mat_<double> spectralResidual;\n  boxFilter(logAmplitude, spectralResidual, spectralResidual.depth(),\n            Size(3, 3));\n  spectralResidual = logAmplitude - spectralResidual;\n\n  polarToCart(spectralResidual, phaseMat, splitFftMat[0], splitFftMat[1]);\n  merge(splitFftMat, fftMat);\n\n  Mat_<Vec<double, 2> > complexSaliency;\n  dft(fftMat, complexSaliency, DFT_COMPLEX_OUTPUT | DFT_INVERSE);\n  vector<Mat> splitSaliency;\n  split(complexSaliency, splitSaliency);\n\n  retval = splitSaliency[0].mul(splitSaliency[0]) +\n    splitSaliency[1].mul(splitSaliency[1]);*/\n\n  // The 32-bit floating point version to speed things up\n  Mat tmpGreyImage;\n  if (image.channels() != 1) {\n    cvtColor(image, tmpGreyImage, CV_BGR2GRAY);\n  } else {\n    tmpGreyImage = image;\n  }\n  Mat_<float> greyImage;\n  tmpGreyImage.convertTo(greyImage, CV_32FC1, 1.0/255);\n  Mat_<Vec<float, 2> > greyComplex;\n  vector<Mat> greyGroup;\n  greyGroup.push_back(greyImage);\n  greyGroup.push_back(Mat_<float>::zeros(image.rows, image.cols));\n  merge(greyGroup, greyComplex);\n\n  Mat_<Vec<float, 2> > fftMat(image.rows, image.cols);\n  dft(greyComplex, fftMat, DFT_COMPLEX_OUTPUT);\n\n  vector<Mat> splitFftMat;\n  split(fftMat, splitFftMat);\n\n  Mat_<float> phaseMat;\n  Mat_<float> logAmplitude;\n  cartToPolar(splitFftMat[0], splitFftMat[1], logAmplitude, phaseMat);\n  log(logAmplitude, logAmplitude);\n\n  Mat_<float> spectralResidual;\n  boxFilter(logAmplitude, spectralResidual, spectralResidual.depth(),\n            Size(3, 3));\n  spectralResidual = logAmplitude - spectralResidual;\n\n  polarToCart(spectralResidual, phaseMat, splitFftMat[0], splitFftMat[1]);\n  merge(splitFftMat, fftMat);\n\n  Mat_<Vec<float, 2> > complexSaliency;\n  dft(fftMat, complexSaliency, DFT_COMPLEX_OUTPUT | DFT_INVERSE);\n  vector<Mat> splitSaliency;\n  split(complexSaliency, splitSaliency);\n\n  retval = splitSaliency[0].mul(splitSaliency[0]) +\n    splitSaliency[1].mul(splitSaliency[1]);\n  \n  return retval;\n}\n\n// ------- Start RelativeEntropyVUWrapper\n\nRelativeEntropyVUWrapper::~RelativeEntropyVUWrapper() {}\n\nbool RelativeEntropyVUWrapper::InitBoxCalculator(const cv::Mat& image,\n                                                 double time) {\n  // First get the visual utility of the entire image\n  Mat_<double> baseVu = baseEstimator_->CalculateVisualUtility(image, time);\n  \n  // Now get the integral image so we can compute more quickly\n  integralVu_.reset(new Mat_<double>());\n  integral(baseVu, *integralVu_, CV_64F);\n\n  \n  return true;\n}\n\ndouble RelativeEntropyVUWrapper::CalculateVisualUtilityOfBox(int x, int y,\n                                                             int h, int w) {\n  const Mat_<double>& intImage = *integralVu_;\n\n  double imArea = (intImage.rows-1)*(intImage.cols-1);\n  double imSum = intImage[intImage.rows-1][intImage.cols-1];\n  double pB = w*h / imArea;\n  double rB = intImage[y][x] + intImage[y+h][x+w] -\n    intImage[y][x+w] - intImage[y+h][x];\n  double entropy = 0;\n  if (imSum < 1e-10 || rB < 1e-10 || pB < 1e-10) {\n    // We basically have a zero value, so force the entropy to be zero\n  } else {\n    rB /= imSum;\n    if (rB > pB) {\n      entropy = rB * log(rB/pB) + (1-rB) * log((1-rB)/(1-pB));\n    } else {\n      entropy = - pB * log(pB/rB) - (1-pB) * log((1-pB)/(1-rB));\n    }\n  }\n\n  if (isnan(entropy)) {\n    ROS_WARN_STREAM(\"Somehow we have the entropy being a NaN.\"\n                    << \" pB = \" << pB\n                    << \" rB = \" << rB\n                    << \" imSum = \" << imSum);\n  }\n\n  return entropy;\n}\n\n// --------- Start LaplacianVU -------------\nLaplacianVU::~LaplacianVU() {}\n\nMat_<double> LaplacianVU::CalculateVisualUtility(const cv::Mat& image,\n                                                 double time) {\n  Mat_<double> retval;\n\n  Mat tmpGreyImage;\n  if (image.channels() != 1) {\n    cvtColor(image, tmpGreyImage, CV_BGR2GRAY);\n  } else {\n    tmpGreyImage = image;\n  }\n  Mat_<double> greyImage;\n  tmpGreyImage.convertTo(greyImage, CV_64FC1, 1.0/255);\n\n  \n  Laplacian(greyImage, retval, CV_64FC1, ksize_);\n  retval = abs(retval);\n\n  return retval;\n}\n\n// --------- Start AverageCenterSurround ---------\nCenterSurroundHistogram::~CenterSurroundHistogram() {}\n\nCenterSurroundHistogram::CenterSurroundHistogram(\n  const std::vector<double>& surroundScales,\n  const std::string& distType)\n  : surroundScales_(surroundScales) {\n  if (distType == \"chisq\") {\n    distType_ = CV_COMP_CHISQR;\n  } else if (distType == \"correl\") {\n    distType_ = CV_COMP_CORREL;\n  } else if (distType == \"intersect\") {\n    distType_ = CV_COMP_INTERSECT;\n  } else if (distType == \"bhattacharyya\") {\n    distType_ = CV_COMP_BHATTACHARYYA;\n  } else {\n    ROS_ERROR_STREAM(\"Invalid distance type: \" << distType\n                     << \" defaulting to Chi Squared\");\n    distType_ = CV_COMP_CHISQR;\n  }\n}\n\nMat_<double> CenterSurroundHistogram::CalculateVisualUtility(const Mat& image,\n                                                             double time) {\n  ROS_FATAL(\"The visual utility for every pixel is not defined for this \"\n            \"estimator.\");\n  return Mat_<double>();\n}\n\nbool CenterSurroundHistogram::InitBoxCalculator(const cv::Mat& image,\n                                                double time) {\n  // Get the image intensity since that's the feature we're going to use\n  Mat tmpGreyImage;\n  if (image.channels() != 1) {\n    cvtColor(image, tmpGreyImage, CV_BGR2GRAY);\n  } else {\n    tmpGreyImage = image;\n  }\n  Mat_<uint8_t> greyImage(tmpGreyImage);\n\n  // Calculate the integral histogram for the image\n  integralHist_.reset(cv_utils::IntegralHistogram<int>::Calculate<uint8_t>(\n    greyImage, 64, &std::pair<uint8_t, uint8_t>(0, 255)));\n\n  return true;\n}\n\ndouble CenterSurroundHistogram::CalculateVisualUtilityOfBox(int x, int y,\n                                                            int h, int w) {\n  double bestScore = 0;\n  for (vector<double>::const_iterator scaleI = surroundScales_.begin();\n       scaleI != surroundScales_.end(); ++scaleI) {\n    const double centerW = w * (*scaleI);\n    const double centerH = h * (*scaleI);\n    const int centerX1 = cvRound(x + (w - centerW) / 2.0);\n    const int centerY1 = cvRound(y + (h - centerH) / 2.0);\n    Mat_<float> centerHist = \n      integralHist_->GetHistInRegion(Rect(centerX1, centerY1,\n                                          cvRound(centerW), cvRound(centerH)));\n      \n    const double surW = centerW * M_SQRT2;\n    const double surH = centerH * M_SQRT2;\n    const int surX1 = cvRound(x + (w - surW) / 2.0);\n    const int surY1 = cvRound(y + (h - surH) / 2.0);\n    Mat_<float> surHist =\n      integralHist_->GetHistInRegion(Rect(surX1, surY1,\n                                          cvRound(surW), cvRound(surH)));\n    surHist -= centerHist;\n\n    // Normalize the histograms\n    const int centerArea = cvRound(centerH) * cvRound(centerW);\n    centerHist /= centerArea;\n    surHist /= (cvRound(surW) * cvRound(surH) - centerArea);\n    \n    double score = compareHist(centerHist, surHist, distType_);\n    if (score > bestScore) {\n      bestScore = score;\n    }\n  }\n  return bestScore;\n}\n\n// --------- Start Objectness ------------\nObjectness::~Objectness() {}\n\nObjectness::Objectness() : impl_(true) {\n  if (!impl_.Init()) {\n    ROS_FATAL_STREAM(\"Couldn't not initialize the objectness wrapper\");\n  }\n}\n\nvoid Objectness::CalculateVisualUtility(const cv::Mat& image,\n                                        const std::vector<cv::Rect>& rois,\n                                        double time,\n                                        std::vector<ROIScore>* vuOut) {\n  lastRuntime_.reset(new double(0));\n  impl_.CalculateObjectness(image, rois, vuOut, lastRuntime_.get());\n}\n\ncv::Mat Objectness::CalculateVisualUtility(const cv::Mat& image,\n                                           int minX, int minY,\n                                           int minW, int minH,\n                                           int strideX, int strideY,\n                                           double strideW, double strideH,\n                                           bool fixAspect,\n                                           double time,\n                                           const cv::Mat& mask) {\n  Mat scores;\n\n  vector<double> widths;\n  vector<double> heights;\n  GetGridHeightsAndWidths(image, minX, minY, minW, minH, strideW, strideH,\n                          fixAspect, &widths, &heights);\n\n  // Build the output score matrix\n  InitializeScoreGrid(image, minX, minY, strideX, strideY, fixAspect,\n                      widths, heights, &scores);\n  ROS_ASSERT(mask.empty() ||\n             (mask.dims == scores.dims &&\n              mask.size == scores.size));\n\n  // Build up the list of boxes to evaluate\n  vector<Rect> rois;\n  for (unsigned int widthI = 0u; widthI < widths.size(); ++widthI) {\n    for (int curX = minX; curX < image.cols-widths[widthI];) {\n      for (int curY = minY; curY < image.rows;) {\n        if (fixAspect) {\n          if (curY + heights[widthI] <= image.rows) {\n            rois.push_back(Rect(curX, curY, widths[widthI], heights[widthI]));\n          }\n        } else {\n          for (unsigned int heightI = 0u;\n               heightI < heights.size() && \n                 curY + heights[heightI] <= image.rows;\n               ++heightI) {\n            rois.push_back(Rect(curX, curY, widths[widthI],\n                                heights[heightI]));\n          }\n        }\n        curY += strideY;\n      }\n      curX += strideX;\n    }\n  }\n\n  // Do the evaluation\n  vector<ROIScore> scoreList;\n  CalculateVisualUtility(image, rois, time, &scoreList);\n\n  // Now load the results into the output grid\n  int gridIdx[4]; // (s, x, y) or (w, h, x, y)\n  for (vector<ROIScore>::const_iterator scoreI = scoreList.begin();\n       scoreI != scoreList.end(); ++scoreI) {\n    gridIdx[0] = (log(scoreI->second.width) - log(minW)) / log(strideW);\n    gridIdx[scores.dims-2] = (scoreI->second.x - minX) / strideX;\n    gridIdx[scores.dims-1] = (scoreI->second.y - minY) / strideY;\n    if (!fixAspect) {\n      gridIdx[1] = (log(scoreI->second.height) - log(minH)) / log(strideH);\n    }\n    ROS_ASSERT(gridIdx[0] >= 0 && gridIdx[1] >= 0 && gridIdx[2] >= 0 &&\n               gridIdx[0] < scores.size[0] &&\n               gridIdx[1] < scores.size[1] &&\n               gridIdx[2] < scores.size[2]);\n    scores.at<double>(gridIdx) = scoreI->first;\n  }\n\n  return scores;\n}\n\n\nMat_<double> Objectness::CalculateVisualUtility(const Mat& image,\n                                                double time) {\n  ROS_FATAL(\"Visual utility for a pixel is not defined\");\n  return Mat_<double>::zeros(image.rows, image.cols);\n}\n\n// ---------- Start ROSBag ---------------\nROSBag::ResultKey::ResultKey(const std::string& _filename,\n                             const cv::Rect _rect)\n  : filenameHash(hash<string>()(_filename)), rect(_rect) {}\nsize_t ROSBag::ResultKeyHash::operator()(const ResultKey& s) const {\n  size_t result = s.filenameHash;\n  hash_combine(result, hash_value(s.rect));\n  return result;\n}\n\nROSBag::ROSBag(const string& filename) {\n  rosbag::Bag bag;\n  bag.open(filename, rosbag::bagmode::Read);\n\n  CreateBaseEstimator(bag);\n\n  LoadBagResults(bag);\n\n  bag.close();\n}\n\nROSBag::~ROSBag() {}\n\nvoid ROSBag::CreateBaseEstimator(const rosbag::Bag& bag) {\n\n  // Load all the parameters into ros params\n  ros::NodeHandle handle(\"~ROSBag\");\n  rosbag::View view(bag, rosbag::TopicQuery(\"parameters\"));\n  BOOST_FOREACH(rosbag::MessageInstance const msg, view) {\n    Parameter::ConstPtr param = msg.instantiate<Parameter>();\n    if (param != NULL) {\n      handle.setParam(param->name.data, param->value.data);\n    }\n  }\n\n  // Create the visual utility estimator\n  transformEstimator_.reset(CreateTransformEstimator(handle));\n  baseEstimator_.reset(CreateVisualUtilityEstimator(handle,\n                                                    *transformEstimator_));\n  \n  // Delete all the parameters\n  rosbag::View view2(bag, rosbag::TopicQuery(\"parameters\"));\n  BOOST_FOREACH(rosbag::MessageInstance const msg, view2) {\n    Parameter::ConstPtr param = msg.instantiate<Parameter>();\n    if (param != NULL) {\n      handle.deleteParam(param->name.data);\n    }\n  }\n}\n\nvoid ROSBag::LoadBagResults(const rosbag::Bag& bag) {\n  rosbag::View view(bag, rosbag::TopicQuery(\"results\"));\n  BOOST_FOREACH(rosbag::MessageInstance const msg, view) {\n    VisualUtilityEstimation::ConstPtr result =\n      msg.instantiate<VisualUtilityEstimation>();\n    if (result != NULL) {\n      if (result->regions.size() != result->scores.size()) {\n        ROS_ERROR_STREAM(\"The number of regions and scores don't match. \"\n                         \"Aborting\");\n        continue;\n      }\n      for (unsigned int i = 0u; i < result->regions.size(); ++i) {\n        const sensor_msgs::RegionOfInterest& region = result->regions[i];\n        lut_[ResultKey(result->image, Rect(region.x_offset, region.y_offset,\n                                           region.width, region.height))] = \n          result->scores[i];\n      }\n    }\n  }\n}\n\nvoid ROSBag::CalculateVisualUtility(const cv::Mat& image,\n                                    const std::vector<cv::Rect>& rois,\n                                    double time,\n                                    std::vector<ROIScore>* vuOut) {\n  if (baseEstimator_.get()) {\n    baseEstimator_->CalculateVisualUtility(image, rois, time, vuOut);\n  }\n}\n\ncv::Mat_<double> ROSBag::CalculateVisualUtility(const cv::Mat& image,\n                                                double time) {\n  if (baseEstimator_.get()) {\n    return baseEstimator_->CalculateVisualUtility(image, time);\n  }\n  return Mat_<double>::zeros(image.rows, image.cols);\n}\n\nvoid ROSBag::CalculateVisualUtility(const std::string& filename,\n                                    const std::vector<cv::Rect>& rois,\n                                    double time,\n                                    std::vector<ROIScore>* vuOut) {\n  ROS_ASSERT(vuOut);\n\n  // Go through all the rois and look them up in the lookup table.\n  for (vector<Rect>::const_iterator roi = rois.begin(); roi != rois.end();\n       ++roi) {\n    hash_map<ResultKey, float, ResultKeyHash>::const_iterator entry = \n      lut_.find(ResultKey(filename, *roi));\n    if (entry != lut_.end()) {\n      vuOut->push_back(ROIScore(entry->second, *roi));\n    } else {\n      vuOut->push_back(ROIScore(0.0, *roi));\n    }\n  }\n\n  if (vuOut->size() != rois.size()) {\n    ROS_ERROR_STREAM(\"We could not find entries in the LUT for all of the \"\n                     \"rois. \"\n                     << rois.size() - vuOut->size()\n                     << \" entries were missing for file: \"\n                     << filename);\n  }\n}\n\n// ---------- Start HOGDetector ---------------\nHOGDetector::~HOGDetector() {}\n\nHOGDetector::HOGDetector(const std::string& modelFile,\n                         bool useDefaultPeopleDetector,\n                         Size winStride,\n                         bool doCache) {\n  if (!impl_.InitModel(modelFile, useDefaultPeopleDetector,\n                       -numeric_limits<double>::infinity(), // threshold\n                       false, // doNMS\n                       winStride,\n                       doCache)) {\n    ROS_FATAL_STREAM(\"Could not initialize HOG detector\");\n  }\n}\n\nvoid HOGDetector::CalculateVisualUtility(const cv::Mat& image,\n                                         const std::vector<cv::Rect>& rois,\n                                         double time,\n                                         std::vector<ROIScore>* vuOut) {\n  ROS_ASSERT(vuOut);\n\n  vector<double> scores;\n  vector<Rect> foundLocations;\n  lastRuntime_.reset(new double(0));\n  impl_.DetectObjects(image, rois, &foundLocations, &scores,\n                       lastRuntime_.get());\n\n  ROS_ASSERT(scores.size() == foundLocations.size());\n\n  for (unsigned int i = 0u; i < foundLocations.size(); ++i) {\n    vuOut->push_back(ROIScore(scores[i], foundLocations[i]));\n  }\n}\n\nMat_<double> HOGDetector::CalculateVisualUtility(const Mat& image,\n                                                 double time) {\n  ROS_FATAL(\"The visual utility for every pixel is not defined for this \"\n            \"estimator.\");\n  return Mat_<double>();\n}\n\n\n// ---------- Start CascadeDetector ---------------\nCascadeDetector::~CascadeDetector() {}\nCascadeDetector::CascadeDetector(const std::string& modelFile){\n  if (!impl_.Init(modelFile)) {\n    ROS_FATAL_STREAM(\"Could not load the classifier defined in \" << modelFile);\n  }\n}\n\nMat_<double> CascadeDetector::CalculateVisualUtility(const Mat& image,\n                                                 double time) {\n  ROS_FATAL(\"The visual utility for every pixel is not defined for this \"\n            \"estimator.\");\n  return Mat_<double>();\n}\n\nvoid CascadeDetector::CalculateVisualUtility(\n  const cv::Mat& image,\n  const std::vector<cv::Rect>& rois,\n  double time,\n  std::vector<ROIScore>* vuOut) {\n\n  ROS_ASSERT(vuOut);\n\n  if (image.empty()) {\n    return;\n  }\n\n  vector<int> scores;\n  vector<Rect> foundLocations;\n  lastRuntime_.reset(new double(0));\n  impl_.DetectObjects(image, rois, &foundLocations, &scores,\n                      lastRuntime_.get());\n\n  ROS_ASSERT(scores.size() == rois.size());\n  for (unsigned int i = 0u; i < scores.size(); ++i) {\n    vuOut->push_back(ROIScore(scores[i], rois[i]));\n  }\n}\n\n// ----------- Start ScaledDetectorWrapper -----------\nScaledDetectorWrapper::~ScaledDetectorWrapper() {}\n\nbool ScaledDetectorWrapper::InitBoxCalculator(const cv::Mat& image,\n                                              double time) {\n  ros::WallTime startTime = ros::WallTime::now();\n\n  // Resize the image and send it to the base estimator\n  Mat scaledImage;\n  cv::resize(image, scaledImage, cv::Size(), scaleFactor_, scaleFactor_);\n\n  resizeTime_ = ros::WallTime::now() - startTime;\n\n  return baseEstimator_->InitBoxCalculator(scaledImage, time);\n}\n\ndouble ScaledDetectorWrapper::CalculateVisualUtilityOfBox(int x, int y,\n                                                          int h, int w) {\n  // Scale the coordinates of the box and send to the base estimaor\n  return baseEstimator_->CalculateVisualUtilityOfBox(\n    cvRound(x * scaleFactor_),\n    cvRound(y * scaleFactor_),\n    cvRound(h * scaleFactor_),\n    cvRound(w * scaleFactor_));\n}\n\nvoid ScaledDetectorWrapper::CalculateVisualUtility(\n  const cv::Mat& image,\n  const std::vector<cv::Rect>& rois,\n  double time,\n  std::vector<ROIScore>* vuOut) {\n  ROS_ASSERT(vuOut);\n\n  // Scale the input rois\n  vector<Rect> scaledRois;\n  unordered_map<Rect, const Rect*> roiMap;\n  for (vector<Rect>::const_iterator roiI = rois.begin();\n       roiI != rois.end();\n       ++roiI) {\n    scaledRois.push_back(Rect(cvRound(roiI->x * scaleFactor_),\n                              cvRound(roiI->y * scaleFactor_),\n                              cvRound(roiI->width * scaleFactor_),\n                              cvRound(roiI->height * scaleFactor_)));\n    roiMap[scaledRois.back()] = &(*roiI);\n  }\n\n  ros::WallTime startTime = ros::WallTime::now();\n\n  // Resize the image\n  Mat scaledImage;\n  cv::resize(image, scaledImage, cv::Size(), scaleFactor_, scaleFactor_);\n  resizeTime_ = ros::WallTime::now() - startTime;\n  \n  // Calculate the visual utility\n  vector<ROIScore> scaledScores;\n  startTime = ros::WallTime::now();\n  baseEstimator_->CalculateVisualUtility(scaledImage,\n                                         scaledRois,\n                                         time,\n                                         &scaledScores);\n  ros::WallDuration baseTime = ros::WallTime::now() - startTime;\n\n  // Scale the output rois\n  for (vector<ROIScore>::const_iterator scoreI = scaledScores.begin();\n       scoreI != scaledScores.end();\n       ++scoreI) {\n    vuOut->push_back(ROIScore(scoreI->first,\n                              *roiMap[scoreI->second]));\n  }\n\n  // Do the timing properly\n  lastRuntime_.reset(new double(0));\n  *lastRuntime_ += resizeTime_.toSec();\n  if (baseEstimator_->GetLastRuntime()) {\n    *lastRuntime_ += *baseEstimator_->GetLastRuntime();\n  } else {\n    *lastRuntime_ += baseTime.toSec();\n  }\n  \n}\n\ncv::Mat_<double> ScaledDetectorWrapper::CalculateVisualUtility(\n  const cv::Mat& image,\n  double time) {\n  ros::WallTime startTime = ros::WallTime::now();\n\n  // Rescale the image\n  Mat scaledImage;\n  cv::resize(image, scaledImage, cv::Size(), scaleFactor_, scaleFactor_);\n\n  ros::WallDuration resizeTime = ros::WallTime::now() - startTime;\n  startTime = ros::WallTime::now();\n\n  // Calculate the visual utility on the scaled image\n  Mat_<double> scaledVU = baseEstimator_->CalculateVisualUtility(\n    scaledImage, time);\n\n  Mat_<double> retval;\n  cv::resize(scaledVU, retval, image.size());\n\n  ros::WallDuration baseTime = ros::WallTime::now() - startTime;\n\n  // Store the timing data properly\n  lastRuntime_.reset(new double(0));\n  *lastRuntime_ += resizeTime.toSec();\n  if (baseEstimator_->GetLastRuntime()) {\n    *lastRuntime_ += *baseEstimator_->GetLastRuntime();\n  } else {\n    *lastRuntime_ += baseTime.toSec();\n  }\n  return retval;\n}\n\n\n// ----------- Start IntegralHOGDetector -----------\nIntegralHOGDetector::IntegralHOGDetector(const std::string& modelFile,\n                                         const cv::Size& winStride)\n  : impl_(modelFile, winStride), hist_(), histSum_() {}\n\nIntegralHOGDetector::~IntegralHOGDetector() {}\n\nbool IntegralHOGDetector::InitBoxCalculator(const cv::Mat& image,\n                                            double time) {\n  hist_.reset(impl_.ComputeGradientIntegralHistograms(image, &histSum_));\n\n  return true;\n}\n\ndouble IntegralHOGDetector::CalculateVisualUtilityOfBox(int x, int y, int h,\n                                                        int w) {\n  return impl_.ComputeScore(*hist_, histSum_, Rect(x, y, w, h));\n}\n\n\ncv::Mat_<double> IntegralHOGDetector::CalculateVisualUtility(\n  const cv::Mat& image,\n  double time) {\n  ROS_FATAL(\"Per pixel evaluation is not implemented for this estimator\");\n  ROS_ASSERT(false);\n  return cv::Mat_<double>();\n}\n\n// ----------- Start IntegralHOGCascade -----------\nIntegralHOGCascade::IntegralHOGCascade(const std::string& modelFile,\n                                        const cv::Size& winStride)\n  : impl_(modelFile, winStride), hist_(), histSum_() {}\n\nIntegralHOGCascade::~IntegralHOGCascade() {}\n\nbool IntegralHOGCascade::InitBoxCalculator(const cv::Mat& image,\n                                           double time) {\n  hist_.reset(impl_.ComputeGradientIntegralHistograms(image, &histSum_));\n\n  return true;\n}\n\ndouble IntegralHOGCascade::CalculateVisualUtilityOfBox(int x, int y, int h,\n                                                       int w) {\n  return impl_.ComputeScore(*hist_, histSum_, Rect(x, y, w, h));\n}\n\n\ncv::Mat_<double> IntegralHOGCascade::CalculateVisualUtility(\n  const cv::Mat& image,\n  double time) {\n  ROS_FATAL(\"Per pixel evaluation is not implemented for this estimator\");\n  ROS_ASSERT(false);\n  return cv::Mat_<double>();\n}\n\n} // namespace\n", "meta": {"hexsha": "724885886c7770028f3f38e3c17ddd64735aea6b", "size": 40885, "ext": "cc", "lang": "C++", "max_stars_repo_path": "visual_utility/src/VisualUtilityEstimator.cc", "max_stars_repo_name": "MRSD2018/reefbot-1", "max_stars_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "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": "visual_utility/src/VisualUtilityEstimator.cc", "max_issues_repo_name": "MRSD2018/reefbot-1", "max_issues_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "visual_utility/src/VisualUtilityEstimator.cc", "max_forks_repo_name": "MRSD2018/reefbot-1", "max_forks_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_forks_repo_licenses": ["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.8921962993, "max_line_length": 79, "alphanum_fraction": 0.6075822429, "num_tokens": 10196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.28457599208146817, "lm_q1q2_score": 0.15998193546446435}}
{"text": "//\n//  Copyright (C) 2018 Boran Adas, Google Summer of Code\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\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/Fingerprints/FingerprintUtil.h>\n#include <GraphMol/Subgraphs/Subgraphs.h>\n#include <RDGeneral/hash/hash.hpp>\n#include <boost/dynamic_bitset.hpp>\n\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/SmilesParse/SmilesParse.h>\n#include <GraphMol/Substruct/SubstructMatch.h>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <algorithm>\n#include <RDGeneral/BoostStartInclude.h>\n#include <boost/flyweight.hpp>\n#include <boost/flyweight/key_value.hpp>\n#include <boost/flyweight/no_tracking.hpp>\n#include <RDGeneral/BoostEndInclude.h>\n\n#include <GraphMol/QueryOps.h>\n#include <DataStructs/ExplicitBitVect.h>\n#include <DataStructs/BitOps.h>\n#include <GraphMol/Subgraphs/SubgraphUtils.h>\n#include <RDGeneral/Invariant.h>\n#include <RDGeneral/BoostStartInclude.h>\n#include <boost/random.hpp>\n#include <cstdint>\n#include <RDGeneral/BoostEndInclude.h>\n#include <climits>\n#include <RDGeneral/types.h>\n\nnamespace RDKit {\nnamespace AtomPairs {\nunsigned int numPiElectrons(const Atom *atom) {\n  PRECONDITION(atom, \"no atom\");\n  unsigned int res = 0;\n  if (atom->getIsAromatic()) {\n    res = 1;\n  } else if (atom->getHybridization() != Atom::SP3) {\n    auto val = static_cast<unsigned int>(atom->getExplicitValence());\n    unsigned int physical_bonds = atom->getNumExplicitHs();\n    const auto &mol = atom->getOwningMol();\n    for (const auto &bndi :\n         boost::make_iterator_range(mol.getAtomBonds(atom))) {\n      if (mol[bndi]->getValenceContrib(atom) != 0.0) {\n        ++physical_bonds;\n      }\n    }\n    CHECK_INVARIANT(val >= physical_bonds,\n                    \"explicit valence exceeds atom degree\");\n    res = val - physical_bonds;\n  }\n  return res;\n}\n\nstd::uint32_t getAtomCode(const Atom *atom, unsigned int branchSubtract,\n                          bool includeChirality) {\n  PRECONDITION(atom, \"no atom\");\n  std::uint32_t code;\n\n  unsigned int numBranches = 0;\n  if (atom->getDegree() > branchSubtract) {\n    numBranches = atom->getDegree() - branchSubtract;\n  }\n\n  code = numBranches % maxNumBranches;\n  unsigned int nPi = numPiElectrons(atom) % maxNumPi;\n  code |= nPi << numBranchBits;\n\n  unsigned int typeIdx = 0;\n  unsigned int nTypes = 1 << numTypeBits;\n  while (typeIdx < nTypes) {\n    if (atomNumberTypes[typeIdx] ==\n        static_cast<unsigned int>(atom->getAtomicNum())) {\n      break;\n    } else if (atomNumberTypes[typeIdx] >\n               static_cast<unsigned int>(atom->getAtomicNum())) {\n      typeIdx = nTypes;\n      break;\n    }\n    ++typeIdx;\n  }\n  if (typeIdx == nTypes) {\n    --typeIdx;\n  }\n  code |= typeIdx << (numBranchBits + numPiBits);\n  if (includeChirality) {\n    std::string cipCode;\n    if (atom->getPropIfPresent(common_properties::_CIPCode, cipCode)) {\n      std::uint32_t offset = numBranchBits + numPiBits + numTypeBits;\n      if (cipCode == \"R\") {\n        code |= 1 << offset;\n      } else if (cipCode == \"S\") {\n        code |= 2 << offset;\n      }\n    }\n  }\n  POSTCONDITION(code < static_cast<std::uint32_t>(\n                           1 << (codeSize + (includeChirality ? 2 : 0))),\n                \"code exceeds number of bits\");\n  return code;\n};\n\nstd::uint32_t getAtomPairCode(std::uint32_t codeI, std::uint32_t codeJ,\n                              unsigned int dist, bool includeChirality) {\n  PRECONDITION(dist < maxPathLen, \"dist too long\");\n  std::uint32_t res = dist;\n  res |= std::min(codeI, codeJ) << numPathBits;\n  res |= std::max(codeI, codeJ)\n         << (numPathBits + codeSize + (includeChirality ? numChiralBits : 0));\n  return res;\n}\n\nstd::uint64_t getTopologicalTorsionCode(\n    const std::vector<std::uint32_t> &pathCodes, bool includeChirality) {\n  bool reverseIt = false;\n  unsigned int i = 0;\n  unsigned int j = pathCodes.size() - 1;\n  while (i < j) {\n    if (pathCodes[i] > pathCodes[j]) {\n      reverseIt = true;\n      break;\n    } else if (pathCodes[i] < pathCodes[j]) {\n      break;\n    }\n    ++i;\n    --j;\n  }\n\n  int shiftSize = codeSize + (includeChirality ? numChiralBits : 0);\n  std::uint64_t res = 0;\n  if (reverseIt) {\n    for (unsigned int i = 0; i < pathCodes.size(); ++i) {\n      res |= static_cast<std::uint64_t>(pathCodes[pathCodes.size() - i - 1])\n             << (shiftSize * i);\n    }\n  } else {\n    for (unsigned int i = 0; i < pathCodes.size(); ++i) {\n      res |= static_cast<std::uint64_t>(pathCodes[i]) << (shiftSize * i);\n    }\n  }\n  return res;\n}\n\nstd::uint32_t getTopologicalTorsionHash(\n    const std::vector<std::uint32_t> &pathCodes) {\n  bool reverseIt = false;\n  unsigned int i = 0;\n  unsigned int j = pathCodes.size() - 1;\n  while (i < j) {\n    if (pathCodes[i] > pathCodes[j]) {\n      reverseIt = true;\n      break;\n    } else if (pathCodes[i] < pathCodes[j]) {\n      break;\n    }\n    ++i;\n    --j;\n  }\n\n  std::uint32_t res = 0;\n  if (reverseIt) {\n    for (unsigned int i = 0; i < pathCodes.size(); ++i) {\n      gboost::hash_combine(res, pathCodes[pathCodes.size() - i - 1]);\n    }\n  } else {\n    for (unsigned int pathCode : pathCodes) {\n      gboost::hash_combine(res, pathCode);\n    }\n  }\n  return res;\n}\n}  // namespace AtomPairs\n\nnamespace MorganFingerprints {\n\n// Definitions for feature points adapted from:\n// Gobbi and Poppinger, Biotech. Bioeng. _61_ 47-54 (1998)\nconst char *smartsPatterns[6] = {\n    \"[$([N;!H0;v3,v4&+1]),\\\n$([O,S;H1;+0]),\\\nn&H1&+0]\",                                                  // Donor\n    \"[$([O,S;H1;v2;!$(*-*=[O,N,P,S])]),\\\n$([O,S;H0;v2]),\\\n$([O,S;-]),\\\n$([N;v3;!$(N-*=[O,N,P,S])]),\\\nn&H0&+0,\\\n$([o,s;+0;!$([o,s]:n);!$([o,s]:c:n)])]\",                    // Acceptor\n    \"[a]\",                                                  // Aromatic\n    \"[F,Cl,Br,I]\",                                          // Halogen\n    \"[#7;+,\\\n$([N;H2&+0][$([C,a]);!$([C,a](=O))]),\\\n$([N;H1&+0]([$([C,a]);!$([C,a](=O))])[$([C,a]);!$([C,a](=O))]),\\\n$([N;H0&+0]([C;!$(C(=O))])([C;!$(C(=O))])[C;!$(C(=O))])]\",  // Basic\n    \"[$([C,S](=[O,S,P])-[O;H1,-1])]\"                        // Acidic\n};\n\nconst RDKit::ROMol *ss_matcher::getMatcher() const { return m_matcher.get(); }\n\nss_matcher::ss_matcher(){};\nss_matcher::ss_matcher(const std::string &pattern) {\n  RDKit::RWMol *p = RDKit::SmartsToMol(pattern);\n  TEST_ASSERT(p);\n  m_matcher.reset(p);\n};\n\ntypedef boost::flyweight<boost::flyweights::key_value<std::string, ss_matcher>,\n                         boost::flyweights::no_tracking>\n    pattern_flyweight;\n\nstd::vector<std::string> defaultFeatureSmarts(smartsPatterns,\n                                              smartsPatterns + 6);\ntypedef boost::flyweight<boost::flyweights::key_value<std::string, ss_matcher>,\n                         boost::flyweights::no_tracking>\n    pattern_flyweight;\nvoid getFeatureInvariants(const ROMol &mol, std::vector<uint32_t> &invars,\n                          std::vector<const ROMol *> *patterns) {\n  unsigned int nAtoms = mol.getNumAtoms();\n  PRECONDITION(invars.size() >= nAtoms, \"vector too small\");\n\n  std::vector<const ROMol *> featureMatchers;\n  if (!patterns) {\n    featureMatchers.reserve(defaultFeatureSmarts.size());\n    for (std::vector<std::string>::const_iterator smaIt =\n             defaultFeatureSmarts.begin();\n         smaIt != defaultFeatureSmarts.end(); ++smaIt) {\n      const ROMol *matcher = pattern_flyweight(*smaIt).get().getMatcher();\n      CHECK_INVARIANT(matcher, \"bad smarts\");\n      featureMatchers.push_back(matcher);\n    }\n    patterns = &featureMatchers;\n  }\n  std::fill(invars.begin(), invars.end(), 0);\n  for (unsigned int i = 0; i < patterns->size(); ++i) {\n    unsigned int mask = 1 << i;\n    std::vector<MatchVectType> matchVect;\n    // to maintain thread safety, we have to copy the pattern\n    // molecules:\n    SubstructMatch(mol, ROMol(*(*patterns)[i], true), matchVect);\n    for (std::vector<MatchVectType>::const_iterator mvIt = matchVect.begin();\n         mvIt != matchVect.end(); ++mvIt) {\n      for (const auto &mIt : *mvIt) {\n        invars[mIt.second] |= mask;\n      }\n    }\n  }\n}  // end of getFeatureInvariants()\n\nvoid getConnectivityInvariants(const ROMol &mol, std::vector<uint32_t> &invars,\n                               bool includeRingMembership) {\n  unsigned int nAtoms = mol.getNumAtoms();\n  PRECONDITION(invars.size() >= nAtoms, \"vector too small\");\n  gboost::hash<std::vector<uint32_t>> vectHasher;\n  for (unsigned int i = 0; i < nAtoms; ++i) {\n    Atom const *atom = mol.getAtomWithIdx(i);\n    std::vector<uint32_t> components;\n    components.push_back(atom->getAtomicNum());\n    components.push_back(atom->getTotalDegree());\n    components.push_back(atom->getTotalNumHs());\n    components.push_back(atom->getFormalCharge());\n    int deltaMass = static_cast<int>(\n        atom->getMass() -\n        PeriodicTable::getTable()->getAtomicWeight(atom->getAtomicNum()));\n    components.push_back(deltaMass);\n\n    if (includeRingMembership &&\n        atom->getOwningMol().getRingInfo()->numAtomRings(atom->getIdx())) {\n      components.push_back(1);\n    }\n    invars[i] = vectHasher(components);\n  }\n}  // end of getConnectivityInvariants()\n\n}  // namespace MorganFingerprints\n\nnamespace RDKitFPUtils {\n\nvoid buildDefaultRDKitFingerprintAtomInvariants(\n    const ROMol &mol, std::vector<std::uint32_t> &lAtomInvariants) {\n  lAtomInvariants.clear();\n  lAtomInvariants.reserve(mol.getNumAtoms());\n  for (ROMol::ConstAtomIterator atomIt = mol.beginAtoms();\n       atomIt != mol.endAtoms(); ++atomIt) {\n    unsigned int aHash = ((*atomIt)->getAtomicNum() % 128) << 1 |\n                         static_cast<unsigned int>((*atomIt)->getIsAromatic());\n    lAtomInvariants.push_back(aHash);\n  }\n}\n\nvoid enumerateAllPaths(const ROMol &mol, INT_PATH_LIST_MAP &allPaths,\n                       const std::vector<std::uint32_t> *fromAtoms,\n                       bool branchedPaths, bool useHs, unsigned int minPath,\n                       unsigned int maxPath) {\n  if (!fromAtoms) {\n    if (branchedPaths) {\n      allPaths = findAllSubgraphsOfLengthsMtoN(mol, minPath, maxPath, useHs);\n    } else {\n      allPaths = findAllPathsOfLengthsMtoN(mol, minPath, maxPath, true, useHs);\n    }\n  } else {\n    for (auto aidx : *fromAtoms) {\n      INT_PATH_LIST_MAP tPaths;\n      if (branchedPaths) {\n        tPaths =\n            findAllSubgraphsOfLengthsMtoN(mol, minPath, maxPath, useHs, aidx);\n      } else {\n        tPaths =\n            findAllPathsOfLengthsMtoN(mol, minPath, maxPath, true, useHs, aidx);\n      }\n      for (INT_PATH_LIST_MAP::const_iterator tpit = tPaths.begin();\n           tpit != tPaths.end(); ++tpit) {\n#ifdef VERBOSE_FINGERPRINTING\n        std::cerr << \"paths from \" << aidx << \" size: \" << tpit->first\n                  << std::endl;\n        for (auto path : tpit->second) {\n          std::cerr << \" path: \";\n          std::copy(path.begin(), path.end(),\n                    std::ostream_iterator<int>(std::cerr, \", \"));\n          std::cerr << std::endl;\n        }\n#endif\n\n        allPaths[tpit->first].insert(allPaths[tpit->first].begin(),\n                                     tpit->second.begin(), tpit->second.end());\n      }\n    }\n  }\n}\n\nvoid identifyQueryBonds(const ROMol &mol, std::vector<const Bond *> &bondCache,\n                        std::vector<short> &isQueryBond) {\n  bondCache.resize(mol.getNumBonds());\n  ROMol::EDGE_ITER firstB, lastB;\n  boost::tie(firstB, lastB) = mol.getEdges();\n  while (firstB != lastB) {\n    const Bond *bond = mol[*firstB];\n    isQueryBond[bond->getIdx()] = 0x0;\n    bondCache[bond->getIdx()] = bond;\n    if (isComplexQuery(bond)) {\n      isQueryBond[bond->getIdx()] = 0x1;\n    }\n    if (isComplexQuery(bond->getBeginAtom())) {\n      isQueryBond[bond->getIdx()] |= 0x2;\n    }\n    if (isComplexQuery(bond->getEndAtom())) {\n      isQueryBond[bond->getIdx()] |= 0x4;\n    }\n    ++firstB;\n  }\n}\n\nstd::vector<unsigned int> generateBondHashes(\n    const ROMol &mol, boost::dynamic_bitset<> &atomsInPath,\n    const std::vector<const Bond *> &bondCache,\n    const std::vector<short> &isQueryBond, const PATH_TYPE &path,\n    bool useBondOrder, const std::vector<std::uint32_t> *atomInvariants) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n\n  std::vector<unsigned int> bondHashes;\n  atomsInPath.reset();\n  bool queryInPath = false;\n  std::vector<unsigned int> atomDegrees(mol.getNumAtoms(), 0);\n  for (unsigned int i = 0; i < path.size() && !queryInPath; ++i) {\n    const Bond *bi = bondCache[path[i]];\n    CHECK_INVARIANT(bi, \"bond not in cache\");\n    atomDegrees[bi->getBeginAtomIdx()]++;\n    atomDegrees[bi->getEndAtomIdx()]++;\n    atomsInPath.set(bi->getBeginAtomIdx());\n    atomsInPath.set(bi->getEndAtomIdx());\n    if (isQueryBond[path[i]]) {\n      queryInPath = true;\n    }\n  }\n  if (queryInPath) {\n    return bondHashes;\n  }\n\n  // -----------------\n  // calculate the bond hashes:\n  std::vector<unsigned int> bondNbrs(path.size(), 0);\n  bondHashes.reserve(path.size() + 1);\n\n  for (unsigned int i = 0; i < path.size(); ++i) {\n    const Bond *bi = bondCache[path[i]];\n#ifdef REPORT_FP_STATS\n    if (std::find(atomsToUse.begin(), atomsToUse.end(),\n                  bi->getBeginAtomIdx()) == atomsToUse.end()) {\n      atomsToUse.push_back(bi->getBeginAtomIdx());\n    }\n    if (std::find(atomsToUse.begin(), atomsToUse.end(), bi->getEndAtomIdx()) ==\n        atomsToUse.end()) {\n      atomsToUse.push_back(bi->getEndAtomIdx());\n    }\n#endif\n    for (unsigned int j = i + 1; j < path.size(); ++j) {\n      const Bond *bj = bondCache[path[j]];\n      if (bi->getBeginAtomIdx() == bj->getBeginAtomIdx() ||\n          bi->getBeginAtomIdx() == bj->getEndAtomIdx() ||\n          bi->getEndAtomIdx() == bj->getBeginAtomIdx() ||\n          bi->getEndAtomIdx() == bj->getEndAtomIdx()) {\n        ++bondNbrs[i];\n        ++bondNbrs[j];\n      }\n    }\n#ifdef VERBOSE_FINGERPRINTING\n    std::cerr << \"   bond(\" << i << \"):\" << bondNbrs[i] << std::endl;\n#endif\n    // we have the count of neighbors for bond bi, compute its hash:\n    unsigned int a1Hash = (*atomInvariants)[bi->getBeginAtomIdx()];\n    unsigned int a2Hash = (*atomInvariants)[bi->getEndAtomIdx()];\n    unsigned int deg1 = atomDegrees[bi->getBeginAtomIdx()];\n    unsigned int deg2 = atomDegrees[bi->getEndAtomIdx()];\n    if (a1Hash < a2Hash) {\n      std::swap(a1Hash, a2Hash);\n      std::swap(deg1, deg2);\n    } else if (a1Hash == a2Hash && deg1 < deg2) {\n      std::swap(deg1, deg2);\n    }\n    unsigned int bondHash = 1;\n    if (useBondOrder) {\n      if (bi->getIsAromatic() || bi->getBondType() == Bond::AROMATIC) {\n        // makes sure aromatic bonds always hash as aromatic\n        bondHash = Bond::AROMATIC;\n      } else {\n        bondHash = bi->getBondType();\n      }\n    }\n    std::uint32_t ourHash = bondNbrs[i];\n    gboost::hash_combine(ourHash, bondHash);\n    gboost::hash_combine(ourHash, a1Hash);\n    gboost::hash_combine(ourHash, deg1);\n    gboost::hash_combine(ourHash, a2Hash);\n    gboost::hash_combine(ourHash, deg2);\n    bondHashes.push_back(ourHash);\n    // std::cerr<<\"    \"<<bi->getIdx()<<\"\n    // \"<<a1Hash<<\"(\"<<deg1<<\")\"<<\"-\"<<a2Hash<<\"(\"<<deg2<<\")\"<<\" \"<<bondHash<<\"\n    // -> \"<<ourHash<<std::endl;\n  }\n  return bondHashes;\n}\n\n}  // namespace RDKitFPUtils\n\n}  // namespace RDKit\n", "meta": {"hexsha": "f65f44c456c439d633fd48f6d8c638c0af266031", "size": 15479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Fingerprints/FingerprintUtil.cpp", "max_stars_repo_name": "kazuyaujihara/rdkit", "max_stars_repo_head_hexsha": "06027dcd05674787b61f27ba46ec0d42a6037540", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1609.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T02:41:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:57:24.000Z", "max_issues_repo_path": "Code/GraphMol/Fingerprints/FingerprintUtil.cpp", "max_issues_repo_name": "kazuyaujihara/rdkit", "max_issues_repo_head_hexsha": "06027dcd05674787b61f27ba46ec0d42a6037540", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3412.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T12:13:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:25:41.000Z", "max_forks_repo_path": "Code/GraphMol/Fingerprints/FingerprintUtil.cpp", "max_forks_repo_name": "kazuyaujihara/rdkit", "max_forks_repo_head_hexsha": "06027dcd05674787b61f27ba46ec0d42a6037540", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 811.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T03:33:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:57:49.000Z", "avg_line_length": 33.9451754386, "max_line_length": 80, "alphanum_fraction": 0.6090186705, "num_tokens": 4492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.15995306042525306}}
{"text": "#include \"baldr/tilehierarchy.h\"\n#include \"baldr/graphid.h\"\n#include \"midgard/pointll.h\"\n\n#include \"test.h\"\n\n#include <boost/property_tree/ptree.hpp>\n\nusing namespace std;\nusing namespace valhalla::baldr;\nusing namespace valhalla::midgard;\n\nnamespace {\n\nTEST(TileHierarchy, Parse) {\n  EXPECT_EQ(TileHierarchy::levels().size(), 3) << \"Incorrect number of hierarchy levels\";\n  EXPECT_EQ((++TileHierarchy::levels().begin())->second.name, \"arterial\")\n      << \"Middle hierarchy should be named arterial\";\n  EXPECT_EQ(TileHierarchy::levels().begin()->second.level, 0) << \"Top hierarchy should have level 0\";\n  EXPECT_EQ(TileHierarchy::levels().rbegin()->second.tiles.TileSize(), .25f)\n      << \"Bottom hierarchy should have tile size of .25f\";\n  EXPECT_EQ(TileHierarchy::levels().find(5), TileHierarchy::levels().end())\n      << \"There should only be levels 0, 1, 2\";\n  EXPECT_NE(TileHierarchy::levels().find(2), TileHierarchy::levels().end())\n      << \"There should be a level 2\";\n  GraphId id = TileHierarchy::GetGraphId(PointLL(0, 0), 34);\n\n  EXPECT_FALSE(id.Is_Valid()) << \"GraphId should be invalid as the level doesn't exist\";\n\n  // there are 1440 cols and 720 rows, this spot lands on col 414 and row 522\n  id = TileHierarchy::GetGraphId(PointLL(-76.5, 40.5), 2);\n  EXPECT_EQ(id.level(), 2);\n  EXPECT_EQ(id.tileid(), (522 * 1440) + 414);\n  EXPECT_EQ(id.id(), 0);\n\n  EXPECT_EQ(TileHierarchy::levels().begin()->second.importance, RoadClass::kPrimary)\n      << \"Importance should be set to primary\";\n  EXPECT_EQ((++TileHierarchy::levels().begin())->second.importance, RoadClass::kTertiary)\n      << \"Importance should be set to tertiary\";\n  EXPECT_EQ(TileHierarchy::levels().rbegin()->second.importance, RoadClass::kServiceOther)\n      << \"Importance should be set to service/other\";\n}\n\nTEST(TileHierarchy, Tiles) {\n\n  // there are 1440 cols and 720 rows, this spot lands on col 414 and row 522\n  AABB2<PointLL> bbox{{-76.49, 40.51}, {-76.48, 40.52}};\n  auto ids = TileHierarchy::GetGraphIds(bbox, 2);\n  EXPECT_EQ(ids.size(), 1) << \"Should have only found one result.\";\n\n  auto id = ids[0];\n  EXPECT_EQ(id.level(), 2);\n  EXPECT_EQ(id.tileid(), (522 * 1440) + 414);\n  EXPECT_EQ(id.id(), 0);\n\n  bbox = AABB2<PointLL>{{-76.51, 40.49}, {-76.49, 40.51}};\n  ids = TileHierarchy::GetGraphIds(bbox, 2);\n  EXPECT_EQ(ids.size(), 4) << \"Should have found 4 results.\";\n}\n\n} // namespace\n\nint main(int argc, char* argv[]) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "2867583e3d8f011f912d86b0eb8bd76e7b64120d", "size": 2478, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/tilehierarchy.cc", "max_stars_repo_name": "mixvit/valhalla", "max_stars_repo_head_hexsha": "65d56caf85103f267452e7b79e49ec66a9bf480e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-11T13:45:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T13:45:27.000Z", "max_issues_repo_path": "test/tilehierarchy.cc", "max_issues_repo_name": "Bolaxax/valhalla", "max_issues_repo_head_hexsha": "f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-11T16:08:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T16:08:57.000Z", "max_forks_repo_path": "test/tilehierarchy.cc", "max_forks_repo_name": "Bolaxax/valhalla", "max_forks_repo_head_hexsha": "f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-01T14:49:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-01T14:49:36.000Z", "avg_line_length": 36.9850746269, "max_line_length": 101, "alphanum_fraction": 0.6844229217, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.1599530539176326}}
{"text": "/*\n * Copyright (C) 2019-2020 LEIDOS.\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\n#include <ros/ros.h>\n#include <string>\n#include <algorithm>\n#include <memory>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <lanelet2_core/geometry/Point.h>\n#include <trajectory_utils/trajectory_utils.h>\n#include <trajectory_utils/conversions/conversions.h>\n#include <sstream>\n#include <carma_utils/containers/containers.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <unordered_set>\n#include \"stop_and_wait_plugin.h\"\n#include <vector>\n#include <cav_msgs/Trajectory.h>\n#include <cav_msgs/StopAndWaitManeuver.h>\n#include <lanelet2_core/primitives/Lanelet.h>\n#include <lanelet2_core/geometry/LineString.h>\n#include <carma_wm/CARMAWorldModel.h>\n#include <carma_utils/containers/containers.h>\n#include <carma_wm/Geometry.h>\n#include <cav_msgs/TrajectoryPlanPoint.h>\n#include <cav_msgs/TrajectoryPlan.h>\n#include <math.h>\n#include <std_msgs/Float64.h>\n\n\n\nusing oss = std::ostringstream;\n\nnamespace stop_and_wait_plugin\n{\n    void StopandWait::initialize()\n    {\n        nh_.reset(new ros::CARMANodeHandle());\n        pnh_.reset(new ros::CARMANodeHandle(\"~\"));\n        pnh2_.reset(new ros::CARMANodeHandle(\"/\"));\n\n        trajectory_srv_ = nh_->advertiseService(\"plan_trajectory\",&StopandWait::plan_trajectory_cb, this);\n        \n        plugin_discovery_pub_ = nh_->advertise<cav_msgs::Plugin>(\"plugin_discovery\",1);\n        jerk_pub_ = nh_->advertise<std_msgs::Float64>(\"jerk\",1);\n        plugin_discovery_msg_.name = \"StopandWaitPlugin\";\n        plugin_discovery_msg_.versionId = \"v1.0\";\n        plugin_discovery_msg_.available = true;\n        plugin_discovery_msg_.activated = false;\n        plugin_discovery_msg_.type = cav_msgs::Plugin::TACTICAL;\n        plugin_discovery_msg_.capability = \"tactical_plan/plan_trajectory\";\n        \n        pose_sub_ = nh_->subscribe(\"current_pose\",1, &StopandWait::pose_cb, this);\n        twist_sub_ = nh_->subscribe(\"current_velocity\", 1, &StopandWait::twist_cb, this);\n\n        wml_.reset(new carma_wm::WMListener());\n        wm_ = wml_->getWorldModel();\n        \n        pnh_->param<double>(\"minimal_trajectory_duration\", minimal_trajectory_duration_);\n        pnh_->param<double>(\"max_jerk_limit\", max_jerk_limit_);\n        pnh_->param<double>(\"min_timestep\",min_timestep_);\n        pnh_->param<double>(\"min_jerk\", min_jerk_limit_);\n        pnh_->param<double>(\"/guidance/destination_downtrack_range\",destination_downtrack_range_);\n\n        discovery_pub_timer_ = pnh_->createTimer(\n            ros::Duration(ros::Rate(10.0)),\n            [this](const auto&) { \n                plugin_discovery_pub_.publish(plugin_discovery_msg_);\n                std_msgs::Float64 jerk_msg;\n                jerk_msg.data = jerk_;\n                jerk_pub_.publish(jerk_msg);\n             });\n    }\n\n    void StopandWait::run()\n    {\n        initialize();\n        ros::CARMANodeHandle::spin();\n    }\n\n    void StopandWait::pose_cb(const geometry_msgs::PoseStampedConstPtr& msg)\n    {\n        pose_msg_ = geometry_msgs::PoseStamped(*msg.get());\n    }\n    \n    void StopandWait::twist_cb(const geometry_msgs::TwistStampedConstPtr& msg)\n    {\n        current_speed_ = msg->twist.linear.x;\n    }\n    \n    bool StopandWait::plan_trajectory_cb(cav_srvs::PlanTrajectoryRequest& req, cav_srvs::PlanTrajectoryResponse& resp)\n    {\n        lanelet::BasicPoint2d veh_pos(pose_msg_.pose.position.x,pose_msg_.pose.position.y);\n        ROS_DEBUG_STREAM(\"curr state x:\"<< pose_msg_.pose.position.x << \", y: \" << pose_msg_.pose.position.y);\n        ROS_DEBUG_STREAM(\"old state x:\"<<  req.vehicle_state.X_pos_global << \", y: \" << req.vehicle_state.Y_pos_global);\n        double current_downtrack = wm_->routeTrackPos(veh_pos).downtrack;\n        ROS_DEBUG_STREAM(\"Starting stop&wait planning\");\n        ROS_DEBUG_STREAM(\"Current_downtrack\"<<current_downtrack);\n\n        // Only plan the trajectory for the requested STOP_AND_WAIT maneuver\n        std::vector<cav_msgs::Maneuver> maneuver_plan;\n        if(req.maneuver_plan.maneuvers[req.maneuver_index_to_plan].type != cav_msgs::Maneuver::STOP_AND_WAIT)\n        {\n            throw std::invalid_argument (\"Stop and Wait Plugin doesn't support this maneuver type\");\n        }\n        maneuver_plan.push_back(req.maneuver_plan.maneuvers[req.maneuver_index_to_plan]);\n        resp.related_maneuvers.push_back(req.maneuver_index_to_plan);\n\n        if(current_downtrack < maneuver_plan[0].stop_and_wait_maneuver.start_dist){\n            //Do nothing\n            return true;\n        }\n\n\n        std::vector<PointSpeedPair> points_and_target_speeds = maneuvers_to_points(maneuver_plan, current_downtrack, wm_, req.vehicle_state);\n\n        auto downsampled_points = \n            carma_utils::containers::downsample_vector(points_and_target_speeds,downsample_ratio_);\n        ROS_DEBUG_STREAM(\"downsampled points size:\"<<downsampled_points.size());\n        //Trajectory plan\n        cav_msgs::TrajectoryPlan  trajectory;\n        trajectory.header.frame_id = \"map\";\n        trajectory.header.stamp = ros::Time::now();\n        trajectory.trajectory_id = boost::uuids::to_string(boost::uuids::random_generator()());\n      \n        trajectory.trajectory_points = compose_trajectory_from_centerline(downsampled_points,req.vehicle_state);\n        ROS_DEBUG_STREAM(\"Trajectory points size:\"<<trajectory.trajectory_points.size());\n        trajectory.initial_longitudinal_velocity = req.vehicle_state.longitudinal_vel;\n        resp.trajectory_plan = trajectory;\n        resp.maneuver_status.push_back(cav_srvs::PlanTrajectory::Response::MANEUVER_IN_PROGRESS);\n\n        return true;\n    }\n\n    std::vector<PointSpeedPair> StopandWait::maneuvers_to_points(const std::vector<cav_msgs::Maneuver>& maneuvers,\n                                                                      double max_starting_downtrack,\n                                                                      const carma_wm::WorldModelConstPtr& wm, const cav_msgs::VehicleState& state)\n    {\n        std::vector<PointSpeedPair> points_and_target_speeds;\n        std::unordered_set<lanelet::Id> visited_lanelets;\n\n        bool first = true;\n        for(const auto& maneuver : maneuvers)\n        {\n            if(maneuver.type != cav_msgs::Maneuver::STOP_AND_WAIT)\n            {\n                throw std::invalid_argument (\"Stop and Wait Maneuver Plugin doesn't support this maneuver type\");\n            }\n            cav_msgs::StopAndWaitManeuver stop_and_wait_maneuver= maneuver.stop_and_wait_maneuver;\n\n            double starting_downtrack = stop_and_wait_maneuver.start_dist;  //starting downtrack recorded in message\n            if(first)   //check for first maneuver in vector \n            {\n                if(starting_downtrack > max_starting_downtrack)\n                {\n                    starting_downtrack = max_starting_downtrack;\n                }\n                first = false;\n\n            }\n           \n            double ending_downtrack = stop_and_wait_maneuver.end_dist; \n            double start_speed = current_speed_;    //Get static value of current speed at start of planning\n            //maneuver_time_ = ros::Duration(stop_and_wait_maneuver.end_time - stop_and_wait_maneuver.start_time).toSec();\n            \n            maneuver_time_ = (3*(ending_downtrack - starting_downtrack))/(2*start_speed);\n\n            double delta_time, curr_time;\n            if(start_speed < epsilon_ )  //If at end_dist return zero speed trajectory\n            {\n                ///guidance/route/destination_downtrack_range\n                auto shortest_path = wm_->getRoute()->shortestPath();\n\n                delta_time = min_timestep_;\n                curr_time = 0.0;\n                //wait\n                lanelet::BasicPoint2d curr_pose (pose_msg_.pose.position.x,pose_msg_.pose.position.y);\n                while(curr_time < minimal_trajectory_duration_)\n                {\n                    PointSpeedPair pair;\n                    pair.point = curr_pose;\n                    pair.speed = 0.0;\n                    points_and_target_speeds.push_back(pair);\n                    curr_time += delta_time;\n\n                    points_and_target_speeds.push_back(pair);\n                }\n            }\n            else\n            {\n                double jerk_req = (2*start_speed)/pow(maneuver_time_,2);\n\n                if(jerk_req > max_jerk_limit_)\n                {\n                    //unsafe to stop at the required jerk - reset to max_jerk and go beyond the maneuver end_dist\n                    jerk_ = max_jerk_limit_;  \n                    double travel_dist_new = start_speed * maneuver_time_ - (0.167 * jerk_ * pow(maneuver_time_,3));\n                    ending_downtrack = travel_dist_new + starting_downtrack;\n\n                    auto shortest_path = wm_->getRoute()->shortestPath();\n                    if(ending_downtrack > wm_->getRouteEndTrackPos().downtrack)\n                    {\n                        ROS_ERROR(\"Ending distance is beyond known route\");\n                        throw std::invalid_argument(\"Ending distance is beyond known route\"); \n                    }\n                }\n                else {\n                    //find distance to the end\n                    lanelet::BasicPoint2d curr_pose (pose_msg_.pose.position.x,pose_msg_.pose.position.y);\n                    double current_downtrack = wm_->routeTrackPos(curr_pose).downtrack;\n                    //stay approximately at crawl speed until within destination downtrack range (defined in route)\n                    if(start_speed <= min_crawl_speed_ && current_downtrack < ending_downtrack - destination_downtrack_range_){\n                        jerk_ = 0.0;\n                    }\n                    else{\n                        jerk_ = jerk_req;\n                    }\n                }\n                //get all the lanelets in between starting and ending downtrack on shortest path\n                auto lanelets = wm_->getLaneletsBetween(starting_downtrack, ending_downtrack, true);\n                //record all the lanelets to be added to path\n                std::vector<lanelet::ConstLanelet> lanelets_to_add;\n                for (auto& l : lanelets)\n                {\n                    if(visited_lanelets.find(l.id()) == visited_lanelets.end())\n                    {\n                        lanelets_to_add.push_back(l);\n                        visited_lanelets.insert(l.id());\n                    }\n                }\n\n                lanelet::BasicLineString2d route_geometry = carma_wm::geometry::concatenate_lanelets(lanelets_to_add);\n                int nearest_pt_index = getNearestRouteIndex(route_geometry,state);\n                // route end point index\n                auto temp_state = state;\n                \n                // maneuver end dist index\n                int ending_downtrack_pt_index = (int)(route_geometry.size() * (ending_downtrack / wm_->getRoute()->length2d()));\n                ROS_DEBUG_STREAM(\"ending_downtrack: \" << ending_downtrack);\n                ROS_DEBUG_STREAM(\"ending_downtrack_pt_index\" << ending_downtrack_pt_index);\n                ROS_DEBUG_STREAM(\"nearest_pt_index\" << nearest_pt_index);\n\n                lanelet::BasicLineString2d future_route_geometry(route_geometry.begin() + nearest_pt_index, route_geometry.begin()+ ending_downtrack_pt_index);\n                \n                int points_count = future_route_geometry.size();\n                delta_time = maneuver_time_/(points_count-1);\n\n                first = true;\n                curr_time = 0.0;\n\n                for(auto p : future_route_geometry)\n                {\n                    if (first && points_and_target_speeds.empty())\n                    {\n                        first = false;\n\n                        continue; //Skip the first point to avoid duplicates from previous maneuver\n                    }\n                    PointSpeedPair pair;\n                    pair.point = p;\n                    pair.speed = start_speed - (0.5 * jerk_ * pow(curr_time,2));\n                    if(pair.speed < 0.01){\n                        pair.speed = 0.0;\n                    }\n\n                    if(p == future_route_geometry.back()) \n                    {\n                        pair.speed = 0.0;    //force speed to 0 at last point\n                    }\n                    curr_time +=delta_time;\n\n                    points_and_target_speeds.push_back(pair);\n                }\n                //Change timestep to 0.1s\n                PointSpeedPair last_point = points_and_target_speeds.back();\n                if(delta_time < min_timestep_){\n                    int downsample_ratio = min_timestep_/delta_time;\n                    points_and_target_speeds = carma_utils::containers::downsample_vector(points_and_target_speeds,downsample_ratio);\n                }\n                points_and_target_speeds.push_back(last_point);            }\n            //If planned time is less than min trajectory duration add zero speed points\n            while(curr_time < minimal_trajectory_duration_)\n            {\n                PointSpeedPair pair;\n                pair.point = points_and_target_speeds.back().point;\n                pair.speed = 0.0;\n                curr_time += delta_time;\n                points_and_target_speeds.push_back(pair);\n            }\n            \n        }\n        \n        return points_and_target_speeds;\n    }\n\n    std::vector<cav_msgs::TrajectoryPlanPoint> StopandWait::compose_trajectory_from_centerline(\n    const std::vector<PointSpeedPair>& points, const cav_msgs::VehicleState& state)\n    {\n        int nearest_pt_index = getNearestPointIndex(points,state);\n        std::vector<PointSpeedPair> future_points(points.begin() + nearest_pt_index, points.end()); // Points in front of current vehicle position\n        //Get yaw - geometrically\n        std::vector<double> yaw_values;\n        for(size_t i=0 ;i < future_points.size()-1 ;i++)\n        {\n            double yaw = atan((future_points[i+1].point.y() - future_points[i].point.y())/ (future_points[i+1].point.x() - future_points[i].point.x()));\n            yaw_values.push_back(yaw);\n        }\n        yaw_values.push_back(0.0); //No rotation from last point\n\n        //get target time from speed\n        std::vector<double> target_times;\n        std::vector<lanelet::BasicPoint2d> trajectory_locations;\n        std::vector<double> trajectory_speeds;\n        //split point speed pair\n        splitPointSpeedPairs(future_points,&trajectory_locations,&trajectory_speeds);\n        std::vector<double> downtracks = carma_wm::geometry::compute_arc_lengths(trajectory_locations);\n\n        //get trajectory time from distance and speed\n        speed_to_time(downtracks, trajectory_speeds,target_times, jerk_);\n        std::vector <cav_msgs::TrajectoryPlanPoint> traj;\n        ros::Time start_time = ros::Time::now();\n        cav_msgs::TrajectoryPlanPoint traj_prev;\n        traj_prev.x= future_points[0].point.x();\n        traj_prev.y = future_points[0].point.y();\n        traj_prev.yaw = yaw_values[0];\n        traj_prev.target_time = start_time;\n\n        for (size_t i=0; i < future_points.size(); i++)\n        {\n            cav_msgs::TrajectoryPlanPoint traj_point;\n            if(trajectory_speeds[i] > 0.0){\n                traj_point.x = future_points[i].point.x();\n                traj_point.y = future_points[i].point.y();\n                traj_point.yaw = yaw_values[i];\n                traj_point.target_time = start_time + ros::Duration(target_times[i]);\n            }\n            else    //speed_to_time doesn't work for 0.0 speed\n            {\n                traj_point.x = future_points[i].point.x();\n                traj_point.y = future_points[i].point.y();\n                traj_point.yaw=traj_prev.yaw;\n                traj_point.target_time = traj_prev.target_time + ros::Duration(min_timestep_);\n                \n            }\n            traj_point.controller_plugin_name = \"Pure Pursuit Jerk\";\n            traj_point.planner_plugin_name =plugin_discovery_msg_.name;\n            traj.push_back(traj_point);\n            traj_prev = traj_point;\n        }\n        //If trajectory only contains one 0.0 mph point, add another iteration(valid trajectory needs to have atleast 2 points)\n        if(traj.size() == 1 && trajectory_speeds[0] == 0){\n            cav_msgs::TrajectoryPlanPoint traj_point;\n            traj_point = traj_prev;\n            traj_point.target_time = traj_prev.target_time + ros::Duration(min_timestep_);\n            traj.push_back(traj_point);\n        }\n        \n        return traj;\n    }\n\n    void StopandWait::speed_to_time(const std::vector<double>& downtrack, const std::vector<double>& speeds,std::vector<double>& times, double jerk) const\n    {\n        if(downtrack.size() !=speeds.size())\n        {\n            throw std::invalid_argument(\"Input vector sizes do not match\");\n        }\n        if (downtrack.empty())\n        {\n            throw std::invalid_argument(\"Input vectors are empty\");\n        }\n\n        times.reserve(downtrack.size());  \n\n        //Uses equation \n        //d_t = sqrt(2(d_v)/j)\n        double prev_speed = speeds[0];\n        double prev_time = 0.0;\n        double prev_pos = downtrack[0];\n        times.push_back(prev_time);\n        for(int i=1; i <downtrack.size();i++)\n        {\n            double cur_speed = speeds[i];\n            double delta_v = std::abs(cur_speed - prev_speed);\n            double dt = sqrt(2*delta_v/jerk);\n            double inst_acc = jerk * dt;\n            if(jerk < min_jerk_limit_)    //Below minimum jerk slow down is ignored, treat as constant velocity\n            {\n                double cur_pos = downtrack[i];\n                double delta_x = cur_pos - prev_pos;\n                dt = delta_x/cur_speed;\n            }\n            double cur_time = dt + prev_time;\n            times.push_back(cur_time);\n\n            prev_speed = cur_speed;\n            prev_time = cur_time;\n            prev_pos = downtrack[i];\n        }\n    }\n\n\n    int StopandWait::getNearestPointIndex(const std::vector<PointSpeedPair>& points, const cav_msgs::VehicleState& state) const\n    {\n        lanelet::BasicPoint2d veh_point(state.X_pos_global, state.Y_pos_global);\n        double min_distance = std::numeric_limits<double>::max();\n        int i = 0;\n        int best_index = 0;\n        for (const auto& p : points)\n        {\n            double distance = lanelet::geometry::distance2d(p.point, veh_point);\n            if (distance < min_distance)\n            {\n            best_index = i;\n            min_distance = distance;\n            }\n            i++;\n        }\n\n        return best_index;\n\n    }\n\n\n    int StopandWait::getNearestRouteIndex(lanelet::BasicLineString2d& points, const cav_msgs::VehicleState& state)\n    {\n        lanelet::BasicPoint2d veh_point(state.X_pos_global, state.Y_pos_global);\n                double min_distance = std::numeric_limits<double>::max();\n        int i = 0;\n        int best_index = 0;\n        for (const auto& p : points)\n        {\n            double distance = lanelet::geometry::distance2d(p,veh_point);\n            if (distance < min_distance)\n            {\n            best_index = i;\n            min_distance = distance;\n            }\n            i++;\n        }\n        return best_index;\n\n    }\n\n    void StopandWait::splitPointSpeedPairs(const std::vector<PointSpeedPair>& points, std::vector<lanelet::BasicPoint2d>* basic_points,\n                        std::vector<double>* speeds) const\n    {\n        basic_points->reserve(points.size());\n        speeds->reserve(points.size());\n\n        for (const auto& p : points)\n        {\n            basic_points->push_back(p.point);\n            speeds->push_back(p.speed);\n        }\n    }\n\n}", "meta": {"hexsha": "d53ce830d0a4b62cb923aa5e1597de97df76f3ce", "size": 20287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stop_and_wait_plugin/src/stop_and_wait_plugin.cpp", "max_stars_repo_name": "pmusau17/carma-platform", "max_stars_repo_head_hexsha": "69df8cb2e8c704a96b25687a435cba5e0aeda83d", "max_stars_repo_licenses": ["Apache-2.0", "CC-BY-4.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": "stop_and_wait_plugin/src/stop_and_wait_plugin.cpp", "max_issues_repo_name": "pmusau17/carma-platform", "max_issues_repo_head_hexsha": "69df8cb2e8c704a96b25687a435cba5e0aeda83d", "max_issues_repo_licenses": ["Apache-2.0", "CC-BY-4.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": "stop_and_wait_plugin/src/stop_and_wait_plugin.cpp", "max_forks_repo_name": "pmusau17/carma-platform", "max_forks_repo_head_hexsha": "69df8cb2e8c704a96b25687a435cba5e0aeda83d", "max_forks_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T21:05:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T21:05:20.000Z", "avg_line_length": 42.7995780591, "max_line_length": 159, "alphanum_fraction": 0.6059545522, "num_tokens": 4385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1597588738635844}}
{"text": "/* Copyright (c) Members of the EGEE Collaboration. 2004.\nSee http://www.eu-egee.org/partners/ for details on the copyright\nholders.\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#include <unistd.h>\n\n#include <cmath>\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <climits> \n\n#include <boost/filesystem/path.hpp>\n\n#include \"common/src/utilities/streamdescriptor.h\"\n#include \"glite/wms/common/logger/logstream.h\"\n#include \"glite/wms/common/logger/manipulators.h\"\n#include \"jobcontrol_namespace.h\"\n\n#include \"SizeFile.h\"\n\nUSING_COMMON_NAMESPACE;\nusing namespace std;\nnamespace fs = boost::filesystem;\n\nRenameLogStreamNS( elog );\n\nJOBCONTROL_NAMESPACE_BEGIN {\n\nnamespace logmonitor {\n\nnamespace {\n\nint integer_size( size_t size, int basen = 10 )\n{\n  int         bitnumber = (int) (log((double)(UCHAR_MAX + 1)) / log(2.0)), answer;\n  double      partial = size / sizeof(unsigned char), total = (bitnumber * partial), largest, rapporto;\n\n  largest = pow( 2, total ) - 1;\n  rapporto = log( largest ) / log( (double) basen );\n  answer = (int) rapporto;\n\n  if( ((double) answer) != rapporto ) answer += 1;\n\n  return answer;\n}\n\n} // Anonymous namespace\n\nsize_t  SizeField::sf_s_long = integer_size( sizeof(long int) ), SizeField::sf_s_unsigned = integer_size( sizeof(unsigned int) );\nconst string SizeFile::sf_s_defaultHeader( \"Condor log size file, DAG enabled.\\n\"\n\t\t\t\t\t   \"This header is made to contain the dagId.\\n\"\n\t\t\t\t\t   \"In this moment the DAG Id is unknown.\" );\n\nostream &operator<<( ostream &os, const SizeField &sf )\n{\n  os << setfill('0') << setw(SizeField::sf_s_long) << sf.sf_position << ' '\n     << setfill('0') << setw(SizeField::sf_s_unsigned) << sf.sf_pending << ' '\n     << sf.sf_last << \" |\";\n\n  return os;\n}\n\nistream &operator>>( istream &is, SizeField &sf )\n{\n  bool            good, last;\n  char            c;\n  unsigned int    pending;\n  long int        position;\n\n  is >> position >> pending >> last >> c;\n  good = is.good() && !is.bad() && (c == '|');\n\n  if( good ) {\n    sf.sf_position = position;\n    sf.sf_pending = pending;\n    sf.sf_last = last;\n  }\n\n  sf.sf_good = good;\n\n  return is;\n}\n\nSizeField::SizeField( void ) : sf_good( false ), sf_last( false ), sf_pending( 0 ), sf_position( 0 )\n{}\n\nSizeField::SizeField( long int position, unsigned int pending, bool last ) : sf_good( true ), sf_last( last ),\n\t\t\t\t\t\t\t\t\t     sf_pending( pending ), sf_position( position )\n{}\n\nSizeField::~SizeField( void ) {}\n\nSizeField &SizeField::reset( long int position, unsigned int pending, bool last )\n{\n  this->sf_position = position;\n  this->sf_pending = pending;\n  this->sf_last = last;\n  this->sf_good = true;\n\n  return *this;\n}\n\nostream &operator<<( ostream &os, const SizeHeader &sh )\n{\n  os << sh.sh_header << \"\\n...\";\n\n  return os;\n}\n\nistream &operator>>( istream &is, SizeHeader &sh )\n{\n  bool            last;\n  string          buffer, header;\n\n  do {\n    getline( is, buffer );\n\n    last = (buffer == \"...\");\n    if( is.good() && !last ) {\n      header.append( buffer );\n      header.append( 1, '\\n' );\n    }\n    else if( last )\n      header.erase( header.end() - 1 );\n\n  } while( is.good() && !last );\n\n  if( (sh.sh_good = last) )\n    sh.sh_header.assign( header );\n  else\n    sh.sh_header.clear();\n\n  return is;\n}\n\nSizeHeader::SizeHeader( const char *header ) : sh_good( header != NULL ), sh_header( header ? header : \"\" )\n{}\n\nSizeHeader::SizeHeader( const string &header ) : sh_good( header.size() != 0 ), sh_header( header )\n{}\n\nSizeHeader::~SizeHeader( void ) {}\n\nSizeHeader &SizeHeader::reset( const string &header )\n{\n  this->sh_good = (header.size() != 0);\n  this->sh_header.assign( header );\n\n  return *this;\n}\n\nvoid SizeFile::createDotFile( void )\n{\n  fs::path      condorfile( this->sf_filename, fs::native );\n  string        name( condorfile.leaf() );\n\n  if( !condorfile.empty() ) {\n  \n    name.insert( name.begin(), '.' );\n    name.append( \".size\" );\n\n    fs::path dotfile(condorfile.branch_path() / fs::path(name, fs::native));\n\t\t\n    this->sf_filename.assign( dotfile.native_file_string() );\n  }\n  else this->sf_filename.clear();\n\n  return;\n}\n\nvoid SizeFile::newSizeFile( void )\n{\n  if (! this->sf_stashed) {\n    this->sf_stream.clear(); this->sf_stream.close();\n  } else {\n    this->sf_stashed = false;\n  }\n  this->sf_stream.open( this->sf_filename.c_str(), ios::out );\n\n  if( !this->sf_header.good() )\n    this->sf_header.reset( sf_s_defaultHeader );\n\n  this->sf_stream << this->sf_header << endl << this->sf_current << endl;\n\n  this->sf_stream.close();\n  this->sf_stream.open( this->sf_filename.c_str(), ios::out | ios::in );\n  this->sf_stream.seekp( 0, ios::end );\n\n  return;\n}\n\nSizeField SizeFile::readField( streamoff position )\n{\n  SizeField     field;\n\n  // For extra safety - private method\n  if (this->sf_stashed) this->reopenFile();\n\n  this->sf_stream.seekg( position );\n  this->sf_stream >> field;\n\n  return field;\n}\n\nSizeField SizeFile::readLastField( void )\n{\n  streamoff       position = (SizeField::dimension() + 1);\n  SizeField       field;\n\n  // For extra safety - private method\n  if (this->sf_stashed) this->reopenFile();\n\n  this->sf_stream.seekg( -position, ios::end );\n  this->sf_stream >> field;\n\n  return field;\n}\n\nbool SizeFile::checkOldFormat( void )\n{\n  bool               last, good = false;\n  long int           position;\n  unsigned int       pending;\n  string             dagid, buffer;\n  SizeField          field;\n\n  // For extra safety - private method\n  if (this->sf_stashed) this->reopenFile();\n\n  this->sf_stream.clear(); this->sf_stream.seekg( 0 );\n  this->sf_stream >> position >> pending >> last;\n\n  if( this->sf_stream.good() ) this->sf_stream >> dagid;\n\n  if( this->sf_stream.good() || this->sf_stream.eof() ) {\n    this->sf_stream.clear();\n    field.reset( position, pending, last );\n\n    if( (good = field.good()) && (dagid.length() != 0) ) {\n      buffer.assign( \"Restored from old file\\nDagId = \" );\n      buffer.append( dagid );\n      buffer.append( \"\\n###########\" );\n\n      this->sf_header.reset( buffer );\n    }\n\n    if( good ) this->sf_current = field;\n  }\n\n  return good;\n}\n\nvoid SizeFile::openFile( bool create )\n{\n  int                   field_number;\n  streamoff             position, filesize, field_storage_size;\n  logger::StatePusher   pusher( elog::cedglog, \"SizeFile::openFile()\" );\n\n  if( this->sf_filename.size() != 0 ) {\n    utilities::create_file( this->sf_filename.c_str() );\n\n    if( create ) {\n      this->sf_header.reset( sf_s_defaultHeader );\n      this->sf_current.reset( 0, 0, 0 );\n\n      this->newSizeFile();\n\n      if( !this->sf_stream.good() || this->sf_stream.bad() ) {\n\telog::cedglog << logger::setlevel( logger::severe ) << \"Cannot open size file \\\"\" << this->sf_filename << \"\\\".\" << endl;\n\n\tthis->sf_good = false;\n      }\n    }\n    else {\n      this->sf_stream.open( this->sf_filename.c_str(), ios::in | ios::out );\n\n      if( this->sf_stream.good() ) {\n\tthis->sf_stream.seekg( 0, ios::end );\n\tfilesize = this->sf_stream.tellg();\n\n\tif( filesize != 0 ) { // File contains something\n\t  elog::cedglog << logger::setlevel( logger::info ) << \"Size file is not empty. Checking header.\" << endl;\n\n\t  this->sf_stream.seekg( 0 ); // Rewind the file !!!\n\t  this->sf_stream >> this->sf_header;\n\n\t  if( this->sf_header.good() && !this->sf_stream.eof() ) { // Good header\n\t    elog::cedglog << logger::setlevel( logger::debug ) << \"The header of the size file seems to be good...\" << endl\n\t\t\t  << \"Trying to read the last status...\" << endl;\n\n\t    this->sf_current = this->readLastField();\n\t    if( this->sf_current.good() && this->sf_stream.good() ) { // Last field successfully read\n\t      elog::cedglog << logger::setlevel( logger::info ) << \"Last field successfully read, winding size file.\" << endl\n\t\t\t    << logger::setlevel( logger::debug ) << \"Position = \" << this->sf_current.position() << endl\n\t\t\t    << \"Pending jobs = \" << this->sf_current.pending() << endl\n\t\t\t    << \"Last job submitted = \" << this->sf_current.last() << endl;\n\n\t      this->sf_stream.seekp( 0, ios::end );\n\t    }\n\t    else { // Try to read the last but one field\n\t      if( !this->sf_stream.good() || this->sf_stream.bad() ) this->sf_stream.clear();\n\n\t      field_storage_size = filesize - this->sf_header.size();\n\t      field_number = field_storage_size / (SizeField::dimension() + 1);\n\n\t      if( field_number != 0 ) { // There seems to be enough space to store some fields\n\t\twhile( field_number > 0 ) { // Try to find the \"first\" good field\n\t\t  this->sf_current = this->readField( this->sf_header.size() + (field_number * (SizeField::dimension() + 1)) );\n\n\t\t  if( this->sf_current.good() && this->sf_stream.good() ) {\n\t\t    elog::cedglog << logger::setlevel( logger::info ) << \"Badly closed file successfully recovered, winding it.\" << endl\n\t\t\t\t  << logger::setlevel( logger::debug ) << \"Position = \" << this->sf_current.position() << endl\n\t\t\t\t  << \"Pending jobs = \" << this->sf_current.pending() << endl\n\t\t\t\t  << \"Last job submitted = \" << this->sf_current.last() << endl;\n\n\t\t    position = this->sf_stream.tellg();\n\t\t    this->sf_stream.seekp( position ); // Put the write pointer at the last good known field.\n\n\t\t    break;\n\t\t  }\n\t\t  else if( !this->sf_stream.good() || this->sf_stream.bad() )\n\t\t    this->sf_stream.clear();\n\n\t\t  field_number -= 1;\n\t\t}\n\n\t\tif( field_number == 0 ) {\n\t\t  elog::cedglog << logger::setlevel( logger::error ) << \"Cannot find any good size field inside the file.\" << endl\n\t\t\t\t<< logger::setlevel( logger::warning ) << \"(Re)Starting with a zero sized file.\" << endl;\n\n\t\t  this->sf_current.reset( 0, 0, 0 );\n\t\t  this->newSizeFile();\n\t\t}\n\t      }\n\t      else { // File seems to be too short\n\t\telog::cedglog << logger::setlevel( logger::error ) << \"Size file is too short (\" \n\t\t\t      << filesize << \"/\" << (this->sf_header.size() + SizeField::dimension() + 1) << \")\" << endl\n\t\t\t      << logger::setlevel( logger::warning ) << \"(Re)Starting with a zero sized file.\" << endl;\n\n\t\tthis->sf_current.reset( 0, 0, 0 );\n\t\tthis->newSizeFile();\n\t      }\n\t    }\n\t  }\n\t  else if( this->sf_stream.eof() ) { // Header corrupted or old file...\n\t    elog::cedglog << logger::setlevel( logger::error ) << \"Size file header is not good.\"\n\t\t\t  << logger::setlevel( logger::info ) << \"Trying to understand if the file is in the old format.\" << endl;\n\n\t    if( this->checkOldFormat() ) { // File in the old format !!! Good...\n\t      elog::cedglog << logger::setlevel( logger::info ) << \"The file was in the old format... Well !!!\" << endl\n\t\t\t    << logger::setlevel( logger::debug ) << \"Position = \" << this->sf_current.position() << endl\n\t\t\t    << \"Pending jobs = \" << this->sf_current.pending() << endl\n\t\t\t    << \"Last job submitted = \" << this->sf_current.last() << endl\n\t\t\t    << logger::setlevel( logger::info ) << \"Reverting to the new format...\" << endl;\n\n\t      this->newSizeFile();\n\t    }\n\t    else {\n\t      elog::cedglog << logger::setlevel( logger::error ) << \"The file wasn't even in the old format.\" << endl\n\t\t\t    << logger::setlevel( logger::warning ) << \"(Re)Starting with a zero sized file.\" << endl;\n\n\t      this->sf_current.reset( 0, 0, 0 );\n\t      this->newSizeFile();\n\t    }\n\t  }\n\t  else { // Yuck !!! I/O errors...\n\t    elog::cedglog << logger::setlevel( logger::severe ) << \"Input/Output errors while reading size file.\" << endl;\n\n\t    this->sf_good = false;\n\t  }\n\t}\n\telse { // File is empty\n\t  elog::cedglog << logger::setlevel( logger::info ) << \"Size file is empty. Writing new one.\" << endl;\n\n\t  this->sf_header.reset( sf_s_defaultHeader );\n\t  this->sf_current.reset( 0, 0, 0 );\n\t  this->sf_stream.seekp( 0 );\n\t  this->sf_stream << this->sf_header << endl << this->sf_current << endl;\n\t}\n      }\n      else { // Yuck !!! I/O errors...\n\telog::cedglog << logger::setlevel( logger::severe ) << \"Input/Output errors while reading size file.\" << endl;\n\n\tthis->sf_good = false;\n      }\n    }\n  }\n  else { // Empty file name ???\n    elog::cedglog << logger::setlevel( logger::severe ) << \"Filename is empty: what I have to do ???\" << endl;\n\n    this->sf_good = false;\n  }\n\n  this->sf_stashed = false;\n  return;\n}\n\nvoid SizeFile::stashFile( void )\n{\n  // Stash file to save the file descriptor.\n  if ( this->sf_stashed ) return;\n  sf_stash_pos = this->sf_stream.tellg();\n  this->sf_stream.close();\n  // SizeFile::good() can continue to be happy.\n  this->sf_stashed = true;\n}\n\nvoid SizeFile::reopenFile( void )\n{\n  if ( ! this->sf_stashed ) return;\n  this->sf_stream.open(this->sf_filename.c_str(), ios::in | ios::out);\n  if (this->sf_stream.good()) this->sf_stream.seekg(sf_stash_pos);\n  this->sf_good = this->sf_stream.good();\n  this->sf_stashed = false;\n}\n\nvoid SizeFile::dumpField( void )\n{\n  // For extra safety - private method\n  if (this->sf_stashed) this->reopenFile();\n\n  if( this->sf_stream.good() )\n    this->sf_stream << this->sf_current << endl;\n\n  this->sf_good = this->sf_stream.good();\n\n  return;\n}\n\nSizeFile::SizeFile( const char *filename, bool create ) : sf_good( true ), sf_stashed( false ), sf_filename( filename ? filename : \"\" ), sf_stream(),\n\t\t\t\t\t\t\t  sf_header(), sf_current()\n{\n  this->createDotFile();\n  this->openFile( create );\n  // Try to save an open FD\n  this->stashFile();\n}\n\nvoid SizeFile::open( const char *filename, bool create )\n{\n  this->sf_good = true;\n  this->sf_filename.assign( filename ? filename : \"\" );\n  this->sf_stream.clear(); this->sf_stream.close();\n\n  this->createDotFile();\n  this->openFile( create );\n  // Try to save an open FD\n  this->stashFile();\n}\n\nSizeFile &SizeFile::update_position( long int new_position )\n{\n  if (this->sf_stashed) this->reopenFile();\n\n  if( this->sf_good ) {\n    this->sf_current.position( new_position );\n    this->dumpField();\n  }\n\n  // Try to save an open FD\n  this->stashFile();\n\n  return *this;\n}\n\nSizeFile &SizeFile::update_pending( unsigned int new_pending )\n{\n  if (this->sf_stashed) this->reopenFile();\n\n  if( this->sf_good ) {\n    this->sf_current.pending( new_pending );\n    this->dumpField();\n  }\n\n  // Try to save an open FD\n  this->stashFile();\n\n  return *this;\n}\n\nSizeFile &SizeFile::update_last( bool new_last )\n{\n  if (this->sf_stashed) this->reopenFile();\n\n  if( this->sf_good ) {\n    this->sf_current.last( new_last );\n    this->dumpField();\n  }\n\n  // Try to save an open FD\n  this->stashFile();\n\n  return *this;\n}\n\nSizeFile &SizeFile::update( long int new_position, unsigned int new_pending, bool new_last )\n{\n  if (this->sf_stashed) this->reopenFile();\n\n  if( this->sf_good ) {\n    this->sf_current.reset( new_position, new_pending, new_last );\n    this->dumpField();\n  }\n\n  // Try to save an open FD\n  this->stashFile();\n\n  return *this;\n}\n\nSizeFile &SizeFile::set_last( bool new_last )\n{\n  if( this->sf_good ) this->sf_current.last( new_last );\n\n  return *this;\n}\n\nSizeFile &SizeFile::set_completed( void )\n{\n  if( this->sf_good ) this->sf_current.pending( 0 ).last( true );\n\n  return *this;\n}\n\nSizeFile &SizeFile::increment_pending( void )\n{\n  unsigned int    old;\n\n  if( this->sf_good ) {\n    old = this->sf_current.pending() + 1;\n    this->sf_current.pending( old );\n  }\n\n  return *this;\n}\n\nSizeFile &SizeFile::decrement_pending( void )\n{\n  unsigned int    old;\n\n  if( this->sf_good ) {\n    old = this->sf_current.pending();\n\n    if( old > 0 ) {\n      old -= 1;\n      this->sf_current.pending( old );\n    }\n    // Something goes wrong but this is not a good reason for stopping\n    //else this->sf_good = false;\n  }\n\n  return *this;\n}\n\nSizeFile &SizeFile::update_header( const std::string &newheader )\n{\n  int                  fd;\n  string::size_type    space;\n  string               buffer;\n\n  if (this->sf_stashed) this->reopenFile();\n\n  if( this->sf_good ) {\n    if( this->sf_header.header().length() <= newheader.length() ) {\n      space = newheader.length() - this->sf_header.header().length();\n\n      buffer.assign( newheader );\n      if( space > 1 ) {\n\tbuffer.append( 1, '\\n' );\n\tbuffer.append( space - 1, '#' );\n      }\n      else if( space == 1 ) buffer.append( 1, ' ' );\n\n      this->sf_header.reset( buffer );\n\n      /*\n\tThis is dangerous, too...\n\tBut it should be faster than the next one...\n      */\n\n      if( this->sf_stream.good() ) {\n\tthis->sf_stream.seekp( 0 );\n\tthis->sf_stream << this->sf_header;\n\n\tthis->sf_stream.seekp( 0, ios::end );\n\n\tthis->sf_good = this->sf_stream.good();\n      }\n      else this->sf_good = false;\n    }\n    else {\n      /*\n\tDangerous operation, must rewind all the file and truncate it...\n\tBrrrrr...\n\tThis restores back an old problem with I/O interrupted operations.\n      */\n\n      this->sf_header.reset( newheader );\n      this->sf_stream.seekg( 0 ); this->sf_stream.seekp( 0 );\n\n      fd = utilities::streamdescriptor( this->sf_stream );\n      if( ftruncate(fd, 0) ) this->sf_good = false;\n      else {\n\tthis->sf_stream << this->sf_header << endl << this->sf_current << endl;\n\n\tthis->sf_good = this->sf_stream.good();\n      }\n    }\n  }\n\n  // Try to save an open FD\n  this->stashFile();\n\n  return *this;\n}\n\n} // Namespace logmonitor\n\n} JOBCONTROL_NAMESPACE_END\n", "meta": {"hexsha": "f3f4e50791ffdb3f6b2ddd9f034dc97eedebad0e", "size": 17416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jobsubmission/src/logmonitor/SizeFile.cpp", "max_stars_repo_name": "italiangrid/wms", "max_stars_repo_head_hexsha": "5b2adda72ba13cf2a85ec488894c2024e155a4b5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T02:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-18T02:19:18.000Z", "max_issues_repo_path": "jobsubmission/src/logmonitor/SizeFile.cpp", "max_issues_repo_name": "italiangrid/wms", "max_issues_repo_head_hexsha": "5b2adda72ba13cf2a85ec488894c2024e155a4b5", "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": "jobsubmission/src/logmonitor/SizeFile.cpp", "max_forks_repo_name": "italiangrid/wms", "max_forks_repo_head_hexsha": "5b2adda72ba13cf2a85ec488894c2024e155a4b5", "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.5134281201, "max_line_length": 149, "alphanum_fraction": 0.6238516307, "num_tokens": 4769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15975886720502452}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2011, 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// Author: Stuart Glaser\n\n#include <robot_mechanism_controllers/jt_cartesian_controller.h>\n\n#include <Eigen/LU>\n\n#include <ros/ros.h>\n\n#include <angles/angles.h>\n\n#include <pluginlib/class_list_macros.h>\nPLUGINLIB_EXPORT_CLASS(controller::JTCartesianController, pr2_controller_interface::Controller)\n\n\nnamespace controller {\n\nJTCartesianController::JTCartesianController()\n  : robot_state_(NULL), use_posture_(false)\n{}\n\nJTCartesianController::~JTCartesianController()\n{\n  sub_gains_.shutdown();\n  sub_posture_.shutdown();\n  sub_pose_.shutdown();\n}\n\n\nbool JTCartesianController::init(pr2_mechanism_model::RobotState *robot_state, ros::NodeHandle &n)\n{\n  node_ = n;\n\n  // get name of root and tip from the parameter server\n  std::string tip_name;\n  if (!node_.getParam(\"root_name\", root_name_)){\n    ROS_ERROR(\"JTCartesianController: No root name found on parameter server (namespace: %s)\",\n              node_.getNamespace().c_str());\n    return false;\n  }\n  if (!node_.getParam(\"tip_name\", tip_name)){\n    ROS_ERROR(\"JTCartesianController: No tip name found on parameter server (namespace: %s)\",\n              node_.getNamespace().c_str());\n    return false;\n  }\n\n  // test if we got robot pointer\n  assert(robot_state);\n  robot_state_ = robot_state;\n\n  // Chain of joints\n  if (!chain_.init(robot_state_, root_name_, tip_name))\n    return false;\n  if (!chain_.allCalibrated())\n  {\n    ROS_ERROR(\"Not all joints in the chain are calibrated (namespace: %s)\", node_.getNamespace().c_str());\n    return false;\n  }\n  if (chain_.size() != Joints)\n  {\n    ROS_ERROR(\"The JTCartesianController works with %d joints, but the chain from %s to %s has %d joints.\",\n              Joints, root_name_.c_str(), tip_name.c_str(), chain_.size());\n    return false;\n  }\n\n  // Kinematics\n  KDL::Chain kdl_chain;\n  chain_.toKDL(kdl_chain);\n  kin_.reset(new Kin<Joints>(kdl_chain));\n\n  // Cartesian gains\n  double kp_trans, kd_trans, kp_rot, kd_rot;\n  if (!node_.getParam(\"cart_gains/trans/p\", kp_trans) ||\n      !node_.getParam(\"cart_gains/trans/d\", kd_trans))\n  {\n    ROS_ERROR(\"P and D translational gains not specified (namespace: %s)\", node_.getNamespace().c_str());\n    return false;\n  }\n  if (!node_.getParam(\"cart_gains/rot/p\", kp_rot) ||\n      !node_.getParam(\"cart_gains/rot/d\", kd_rot))\n  {\n    ROS_ERROR(\"P and D rotational gains not specified (namespace: %s)\", node_.getNamespace().c_str());\n    return false;\n  }\n  Kp << kp_trans, kp_trans, kp_trans,  kp_rot, kp_rot, kp_rot;\n  Kd << kd_trans, kd_trans, kd_trans,  kd_rot, kd_rot, kd_rot;\n\n  node_.param(\"pose_command_filter\", pose_command_filter_, 1.0);\n\n  // Velocity saturation\n  node_.param(\"vel_saturation_trans\", vel_saturation_trans_, 0.0);\n  node_.param(\"vel_saturation_rot\", vel_saturation_rot_, 0.0);\n\n  node_.param(\"jacobian_inverse_damping\", jacobian_inverse_damping_, 0.0);\n  node_.param(\"joint_vel_filter\", joint_vel_filter_, 1.0);\n\n  // Joint gains\n  for (int i = 0; i < Joints; ++i)\n    node_.param(\"joint_feedforward/\" + chain_.getJoint(i)->joint_->name, joint_dd_ff_[i], 0.0);\n  for (int i = 0; i < Joints; ++i)\n    node_.param(\"saturation/\" + chain_.getJoint(i)->joint_->name, saturation_[i], 0.0);\n\n  // Posture gains\n  node_.param(\"k_posture\", k_posture_, 1.0);\n\n  node_.param(\"resolution/force\", res_force_, 0.01);\n  node_.param(\"resolution/position\", res_position_, 0.001);\n  node_.param(\"resolution/torque\", res_torque_, 0.01);\n  node_.param(\"resolution/orientation\", res_orientation_, 0.001);\n\n\n  sub_gains_ = node_.subscribe(\"gains\", 5, &JTCartesianController::setGains, this);\n  sub_posture_ = node_.subscribe(\"command_posture\", 5, &JTCartesianController::commandPosture, this);\n  sub_pose_ = node_.subscribe(\"command_pose\", 1, &JTCartesianController::commandPose, this);\n\n  StateMsg state_template;\n  state_template.header.frame_id = root_name_;\n  state_template.x.header.frame_id = root_name_;\n  state_template.x_desi.header.frame_id = root_name_;\n  state_template.x_desi_filtered.header.frame_id = root_name_;\n  state_template.tau_pose.resize(Joints);\n  state_template.tau_posture.resize(Joints);\n  state_template.tau.resize(Joints);\n  state_template.J.layout.dim.resize(2);\n  state_template.J.data.resize(6*Joints);\n  state_template.N.layout.dim.resize(2);\n  state_template.N.data.resize(Joints*Joints);\n  pub_state_.init(node_, \"state\", 10);\n  pub_state_.lock();\n  pub_state_.msg_ = state_template;\n  pub_state_.unlock();\n\n  pub_x_desi_.init(node_, \"state/x_desi\", 10);\n  pub_x_desi_.lock();\n  pub_x_desi_.msg_.header.frame_id = root_name_;\n  pub_x_desi_.unlock();\n\n  return true;\n}\n\nvoid JTCartesianController::starting()\n{\n  //Kp << 800.0, 800.0, 800.0,   80.0, 80.0, 80.0;\n  //Kd << 12.0, 12.0, 12.0,   0.0, 0.0, 0.0;\n\n  JointVec q;\n  chain_.getPositions(q);\n  kin_->fk(q, x_desi_);\n  x_desi_filtered_ = x_desi_;\n  last_pose_ = x_desi_;\n  q_posture_ = q;\n  qdot_filtered_.setZero();\n  last_wrench_.setZero();\n\n  loop_count_ = 0;\n}\n\n\nstatic void computePoseError(const Eigen::Affine3d &xact, const Eigen::Affine3d &xdes, Eigen::Matrix<double,6,1> &err)\n{\n  err.head<3>() = xact.translation() - xdes.translation();\n  err.tail<3>()   = 0.5 * (xdes.linear().col(0).cross(xact.linear().col(0)) +\n                          xdes.linear().col(1).cross(xact.linear().col(1)) +\n                          xdes.linear().col(2).cross(xact.linear().col(2)));\n}\n\nvoid JTCartesianController::update()\n{\n  // get time\n  ros::Time time = robot_state_->getTime();\n  ros::Duration dt = time - last_time_;\n  last_time_ = time;\n  ++loop_count_;\n\n  // ======== Measures current arm state\n\n  JointVec q;\n  chain_.getPositions(q);\n\n  Eigen::Affine3d x;\n  kin_->fk(q, x);\n\n  Jacobian J;\n  kin_->jac(q, J);\n\n\n  JointVec qdot_raw;\n  chain_.getVelocities(qdot_raw);\n  for (int i = 0; i < Joints; ++i)\n    qdot_filtered_[i] += joint_vel_filter_ * (qdot_raw[i] - qdot_filtered_[i]);\n  JointVec qdot = qdot_filtered_;\n  CartVec xdot = J * qdot;\n\n  // ======== Controls to the current pose setpoint\n\n  {\n    Eigen::Vector3d p0(x_desi_filtered_.translation());\n    Eigen::Vector3d p1(x_desi_.translation());\n    Eigen::Quaterniond q0(x_desi_filtered_.linear());\n    Eigen::Quaterniond q1(x_desi_.linear());\n    q0.normalize();\n    q1.normalize();\n\n    tf::Quaternion tf_q0(q0.x(), q0.y(), q0.z(), q0.w());\n    tf::Quaternion tf_q1(q1.x(), q1.y(), q1.z(), q1.w());\n    tf::Quaternion tf_q = tf_q0.slerp(tf_q1, pose_command_filter_);\n\n    Eigen::Vector3d p = p0 + pose_command_filter_ * (p1 - p0);\n    //Eigen::Quaterniond q = q0.slerp(pose_command_filter_, q1);\n    Eigen::Quaterniond q(tf_q.w(), tf_q.x(), tf_q.y(), tf_q.z());\n    //x_desi_filtered_ = q * Eigen::Translation3d(p);\n    x_desi_filtered_ = Eigen::Translation3d(p) * q;\n  }\n  CartVec x_err;\n  //computePoseError(x, x_desi_, x_err);\n  computePoseError(x, x_desi_filtered_, x_err);\n\n  CartVec xdot_desi = (Kp.array() / Kd.array()) * x_err.array() * -1.0;\n\n  // Caps the cartesian velocity\n  if (vel_saturation_trans_ > 0.0)\n  {\n    if (fabs(xdot_desi.head<3>().norm()) > vel_saturation_trans_)\n      xdot_desi.head<3>() *= (vel_saturation_trans_ / xdot_desi.head<3>().norm());\n  }\n  if (vel_saturation_rot_ > 0.0)\n  {\n    if (fabs(xdot_desi.tail<3>().norm()) > vel_saturation_rot_)\n      xdot_desi.tail<3>() *= (vel_saturation_rot_ / xdot_desi.tail<3>().norm());\n  }\n\n  CartVec F = Kd.array() * (xdot_desi - xdot).array();\n\n  JointVec tau_pose = J.transpose() * F;\n\n  // ======== J psuedo-inverse and Nullspace computation\n\n  // Computes pseudo-inverse of J\n  Eigen::Matrix<double,6,6> I6; I6.setIdentity();\n  //Eigen::Matrix<double,6,6> JJt = J * J.transpose();\n  //Eigen::Matrix<double,6,6> JJt_inv = JJt.inverse();\n  Eigen::Matrix<double,6,6> JJt_damped = J * J.transpose() + jacobian_inverse_damping_ * I6;\n  Eigen::Matrix<double,6,6> JJt_inv_damped = JJt_damped.inverse();\n  Eigen::Matrix<double,Joints,6> J_pinv = J.transpose() * JJt_inv_damped;\n\n  // Computes the nullspace of J\n  Eigen::Matrix<double,Joints,Joints> I;\n  I.setIdentity();\n  Eigen::Matrix<double,Joints,Joints> N = I - J_pinv * J;\n\n  // ======== Posture control\n\n  // Computes the desired joint torques for achieving the posture\n  JointVec tau_posture;\n  tau_posture.setZero();\n  if (use_posture_)\n  {\n    JointVec posture_err = q_posture_ - q;\n    for (size_t j = 0; j < Joints; ++j)\n    {\n      if (chain_.getJoint(j)->joint_->type == urdf::Joint::CONTINUOUS)\n        posture_err[j] = angles::normalize_angle(posture_err[j]);\n    }\n\n    for (size_t j = 0; j < Joints; ++j) {\n      if (fabs(q_posture_[j] - 9999) < 1e-5)\n        posture_err[j] = 0.0;\n    }\n\n    JointVec qdd_posture = k_posture_ * posture_err;\n    tau_posture = joint_dd_ff_.array() * (N * qdd_posture).array();\n  }\n\n  JointVec tau = tau_pose + tau_posture;\n\n  // ======== Torque Saturation\n  double sat_scaling = 1.0;\n  for (int i = 0; i < Joints; ++i) {\n    if (saturation_[i] > 0.0)\n      sat_scaling = std::min(sat_scaling, fabs(saturation_[i] / tau[i]));\n  }\n  JointVec tau_sat = sat_scaling * tau;\n\n  chain_.addEfforts(tau_sat);\n\n  if (loop_count_ % 10 == 0)\n  {\n    if (pub_x_desi_.trylock()) {\n      pub_x_desi_.msg_.header.stamp = time;\n      tf::poseEigenToMsg(x_desi_, pub_x_desi_.msg_.pose);\n      pub_x_desi_.unlockAndPublish();\n    }\n\n    if (pub_state_.trylock()) {\n      pub_state_.msg_.header.stamp = time;\n      pub_state_.msg_.x.header.stamp = time;\n      tf::poseEigenToMsg(x, pub_state_.msg_.x.pose);\n      pub_state_.msg_.x_desi.header.stamp = time;\n      tf::poseEigenToMsg(x_desi_, pub_state_.msg_.x_desi.pose);\n      pub_state_.msg_.x_desi_filtered.header.stamp = time;\n      tf::poseEigenToMsg(x_desi_filtered_, pub_state_.msg_.x_desi_filtered.pose);\n      tf::twistEigenToMsg(x_err, pub_state_.msg_.x_err);\n      tf::twistEigenToMsg(xdot, pub_state_.msg_.xd);\n      tf::twistEigenToMsg(xdot_desi, pub_state_.msg_.xd_desi);\n      tf::wrenchEigenToMsg(F, pub_state_.msg_.F);\n      tf::matrixEigenToMsg(J, pub_state_.msg_.J);\n      tf::matrixEigenToMsg(N, pub_state_.msg_.N);\n      for (size_t j = 0; j < Joints; ++j) {\n        pub_state_.msg_.tau_pose[j] = tau_pose[j];\n        pub_state_.msg_.tau_posture[j] = tau_posture[j];\n        pub_state_.msg_.tau[j] = tau[j];\n      }\n      pub_state_.unlockAndPublish();\n    }\n  }\n}\n\n} //namespace\n", "meta": {"hexsha": "b621406aa0edd06396f33b40506927ae6d987f93", "size": 12015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/pr2_controllers/robot_mechanism_controllers/src/jt_cartesian_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/jt_cartesian_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/jt_cartesian_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": 34.1335227273, "max_line_length": 118, "alphanum_fraction": 0.6774864752, "num_tokens": 3485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.29421497835151617, "lm_q1q2_score": 0.15971850910643157}}
{"text": "#include \"MapSystem.h\"\n\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\n#include \"../utility/Logging.h\"\n#include \"../constants/MapConstants.h\"\n#include \"../constants/RenderConstants.h\"\n\nusing namespace std;\n\nMapSystem::MapSystem(Input& input, Camera& camera, Map& map, Log& log)\n  : input_{input}\n  , camera_{camera}\n  , map_{map}\n  , log_{log}\n{\n}\n\n\nvoid \nMapSystem::init()\n{\n  cout << \"MapSystem initializing\" << endl;\n\n  srand(MAP_SEED);\n\n  generate_map();\n}\n\n\nvoid \nMapSystem::update()\n{\n  if (map_.floor_changed) {\n    map_.floor_changed = false;\n  }\n\n  if (input_.lclick) {\n    input_.lclick = false;\n    calculate_selected_tile();\n  }\n\n  update_floor();\n}\n\n\nvoid \nMapSystem::generate_map()\n{\n  for (auto floor{1}; floor <= NUM_FLOORS; floor++) {\n    define_blocks(floor);\n    layout_main_floor(floor);\n    seed_rooms(floor);\n    expand_rooms(floor);\n    build_rooms(floor);\n    place_doors(floor);\n    integrate_walls(floor);\n  }\n}\n\n\nvoid \nMapSystem::update_floor()\n{\n  if (input_.descend) {\n    input_.descend = false;\n\n    if (map_.cur_floor > 1) {\n      map_.floor_changed = true;\n      map_.cur_floor--;\n    }\n  }\n\n  if (input_.ascend) {\n    input_.ascend = false;\n\n    if (map_.cur_floor < NUM_FLOORS) {\n      map_.floor_changed = true;\n      map_.cur_floor++; \n    }\n  } \n}\n\n\nvoid \nMapSystem::define_blocks(i32 floor)\n{\n  // left edge\n  map_.blocks[floor].push_back({\n    0, 0, OUTER_PATH, TILES_PER_LAYER - 1\n  });\n  // right edge\n  map_.blocks[floor].push_back({\n    TILES_PER_LAYER - OUTER_PATH - 1, 0, OUTER_PATH, TILES_PER_LAYER - 1\n  });  \n  // top edge \n  map_.blocks[floor].push_back({\n    0, 0, TILES_PER_LAYER - 1, OUTER_PATH\n  });\n  // bottom edge\n  map_.blocks[floor].push_back({\n    0, TILES_PER_LAYER - OUTER_PATH - 1, TILES_PER_LAYER - 1, OUTER_PATH\n  });\n  // middle horizontal\n  map_.blocks[floor].push_back({\n    0, TILES_PER_LAYER / 2 - CENTRAL_PATH / 2 - 1, \n    TILES_PER_LAYER - 1, CENTRAL_PATH + 1\n  });\n  // middle vertical\n  map_.blocks[floor].push_back({\n    TILES_PER_LAYER / 2 - CENTRAL_PATH / 2 - 1, 0, \n    CENTRAL_PATH + 1, TILES_PER_LAYER - 1\n  });\n}\n\n\nvoid \nMapSystem::layout_main_floor(i32 floor)\n{\n  string floor_type;\n\n  switch (get_section(floor)) {\n  case 1: floor_type = \"dark_concrete\"; break;\n  case 2: floor_type = \"smooth_dark_concrete\"; break;\n  case 3: floor_type = \"bright_dark_concrete\"; break;\n  }\n\n  for (auto x{0}; x < TILES_PER_LAYER; x++) {\n    for (auto y{0}; y < TILES_PER_LAYER; y++) {\n      set_tile(\"flr\", x, y, floor, floor_type);\n    }\n  }\n}\n\n\nvoid \nMapSystem::seed_rooms(i32 floor)\n{\n  for (auto i{0}; i < NUM_ROOMS; i++) {\n    Room test_room;\n    bool collision{true};\n\n    switch (get_section(floor)) {\n    case 1:\n      test_room.wall_type = \"wall1\"; \n      test_room.floor_type = \"light_concrete\"; \n      break;\n    case 2:\n      test_room.wall_type = \"wall2\"; \n      test_room.floor_type = \"smooth_light_concrete\"; \n      break;\n    case 3:\n      test_room.wall_type = \"wall3\"; \n      test_room.floor_type = \"bright_light_concrete\"; \n      break;\n    }\n\n    do {\n      test_room.rect.x = rand() % (TILES_PER_LAYER - 1);\n      test_room.rect.y = rand() % (TILES_PER_LAYER - 1);\n      test_room.rect.w = 2;\n      test_room.rect.h = 2;\n    } \n    while (room_collision(floor, test_room));\n\n    map_.rooms[floor].push_back(test_room);\n  }\n}\n\n\nvoid \nMapSystem::expand_rooms(i32 floor)\n{\n  if (RANDOM_ROOMS) srand(time(nullptr));\n\n  for (auto i{0}; i < EXPANSION_ITERATIONS; i++) {\n    bool found{false};\n    vector<Dir> dirs{Dir::UP, Dir::DOWN, Dir::LEFT, Dir::RIGHT}; \n\n    u64 random_room_index{rand() % map_.rooms[floor].size()};\n\n    Room& room{map_.rooms[floor][random_room_index]}; \n\n    while (!found && !dirs.empty()) {\n      const Dir dir{rand_dir()};\n      dirs.erase(remove(dirs.begin(), dirs.end(), dir), dirs.end());\n\n      switch (dir) {\n      case Dir::UP:    room.rect.y--; break;\n      case Dir::DOWN:  room.rect.h++; break;\n      case Dir::LEFT:  room.rect.x--; break;\n      case Dir::RIGHT: room.rect.w++; break;\n      }\n\n      if (room_collision(floor, room)) {\n        switch (dir) {\n        case Dir::UP:    room.rect.y++; break;\n        case Dir::DOWN:  room.rect.h--; break;\n        case Dir::LEFT:  room.rect.x++; break;\n        case Dir::RIGHT: room.rect.w--; break;\n        }\n      } else {\n        found = true;\n      }\n    }\n  }  \n}\n\n\nvoid \nMapSystem::build_rooms(i32 floor)\n{\n  for (const auto& room : map_.rooms[floor]) {\n    for (auto x{room.l()}; x <= room.r(); x++) {\n      for (auto y{room.t()}; y <= room.b(); y++) {\n        set_tile(\"flr\", x, y, floor, room.floor_type);\n      }\n    }\n\n    for (auto x{room.l()}; x <= room.r(); x++) {\n      set_solid(x, room.t(), floor);\n      set_solid(x, room.b(), floor);\n      set_tile(\"wal\", x, room.t(), floor, room.wall_type + \"-str\"); \n      set_tile(\"wal\", x, room.b(), floor, room.wall_type + \"-str\");\n    }\n\n    for (auto y{room.t() + 1}; y <= room.b(); y++) {\n      set_solid(room.l(), y, floor);\n      set_solid(room.r(), y, floor);\n      set_tile(\"wal\", room.l(), y, floor, room.wall_type + \"-str\", 90); \n      set_tile(\"wal\", room.r(), y, floor, room.wall_type + \"-str\", 90);\n    }\n  }\n\n  cout << \" Floor \" << floor << \" rooms built\" << endl;\n}\n\n\nvoid \nMapSystem::integrate_walls(i32 floor)\n{\n  const auto& tiles{map_.floors[floor].layers[\"wal\"].tiles};\n\n  for (auto x{OUTER_PATH}; x < TILES_PER_LAYER - OUTER_PATH; x++) {\n    for (auto y{OUTER_PATH}; y < TILES_PER_LAYER - OUTER_PATH; y++) {\n      const Tile& tile{tiles[x][y]};\n\n      if (tile.category == \"walls\") {\n        const Tile& utile{tiles[x + 0][y - 1]};\n        const Tile& dtile{tiles[x + 0][y + 1]};\n        const Tile& ltile{tiles[x - 1][y + 0]};\n        const Tile& rtile{tiles[x + 1][y + 0]};\n\n        const bool umatch{tile.type == utile.type};\n        const bool rmatch{tile.type == rtile.type};\n        const bool dmatch{tile.type == dtile.type};\n        const bool lmatch{tile.type == ltile.type};\n\n        if (umatch && lmatch && dmatch && rmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-int\");\n        } else if (umatch && rmatch && dmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-tee\");\n        } else if (rmatch && dmatch && lmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-tee\", 90);\n        } else if (dmatch && lmatch && umatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-tee\", 180);\n        } else if (lmatch && umatch && rmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-tee\", 270);\n        } else if (umatch && rmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-cor\");\n        } else if (rmatch && dmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-cor\", 90);\n        } else if (dmatch && lmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-cor\", 180);\n        } else if (lmatch && umatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-cor\", 270);\n        } else if (lmatch && rmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-str\");\n        } else if (umatch && dmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-str\", 90);\n        } else if (umatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-end\");\n        } else if (rmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-end\", 90);\n        } else if (dmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-end\", 180);\n        } else if (lmatch) {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-end\", 270);\n        } else {\n          set_tile(\"wal\", x, y, floor, tile.type + \"-one\");\n        }\n      }\n    }\n  }\n\n  cout << \" Floor \" << floor << \" rooms integrated\" << endl;\n}\n\n\nvoid \nMapSystem::place_doors(i32 floor)\n{\n  for (auto& room : map_.rooms[floor]) {\n    u8 count{0};\n    bool found{false};\n\n    while (!found && count++ < 40) {\n      const auto horz_range{room.w() - 1};\n      const auto horz_start{room.l() + 1};\n      const auto vert_range{room.h() - 1};\n      const auto vert_start{room.t() + 1};\n\n      i32 rot, x, y;\n      const Dir dir{rand_dir()}; \n\n      if (dir == Dir::UP) {\n        rot = 0;\n        x = horz_start + rand() % horz_range;\n        y = room.t(); \n      } else if (dir == Dir::DOWN) {\n        rot = 90;\n        x = room.r();\n        y = vert_start + rand() % vert_range;\n      } else if (dir == Dir::RIGHT) {\n        rot = 180;\n        x = horz_start + rand() % horz_range;\n        y = room.b();\n      } else if (dir == Dir::LEFT) {\n        rot = 270;\n        x = room.l();\n        y = vert_start + rand() % vert_range;\n      }\n\n      if (has_clearance(\"door\", x, y, floor, dir)) {\n        found = true;\n        \n        if (rand() % 2 == 0) {\n          set_solid(x, y, floor);\n          set_tile(\"wal\", x, y, floor, \"door1-cls\", rot);\n        } else {\n          set_solid(x, y, floor, false);\n          set_tile(\"wal\", x, y, floor, \"door1-opn\", rot);\n        }\n      }\n    }\n  }\n\n  cout << \" Floor \" << floor << \" doors placed\" << endl;\n}\n\n\nvoid \nMapSystem::calculate_selected_tile()\n{\n  f32 screenx{(input_.mx - HALF_SCREEN_SIZE_X) / (f32)TILE_SIZE / camera_.zoom};\n  f32 screeny{(input_.my - HALF_SCREEN_SIZE_Y) / (f32)TILE_SIZE / camera_.zoom};\n\n  i32 targetx{static_cast<i32>(floor(screenx + camera_.pos.x))};\n  i32 targety{static_cast<i32>(floor(screeny + camera_.pos.y))};\n\n  if (select_tile(targetx, targety)) {\n    string msg{\"Selected: [\"};\n    msg += to_string(input_.selectx) + \",\" + to_string(input_.selecty) + \",\";\n    msg += to_string(input_.selectfloor) + \"]\"; \n\n    ::msg(log_, msg);\n  } else {\n    ::msg(log_, \"Selected: [invalid]\");\n  }\n}\n\n\nconst bool \nMapSystem::select_tile(i32 x, i32 y)\n{\n  const auto x_in_bounds{x >= 0 && x <= TILES_PER_LAYER - 1};\n  const auto y_in_bounds{y >= 0 && y <= TILES_PER_LAYER - 1}; \n\n  if (x_in_bounds && y_in_bounds) {\n    clear_selection();\n\n    input_.selectx = x;\n    input_.selecty = y;\n    input_.selectfloor = map_.cur_floor;\n\n    set_tile(\"ovr\", x, y, map_.cur_floor, \"select\");\n\n    return true;\n  } else {\n    return false;\n  }\n}\n\n\nvoid \nMapSystem::clear_selection() \n{\n  if (input_.selectx == -1 && input_.selecty == -1) {\n    return;\n  }\n\n  set_active(\n    \"ovr\", input_.selectx, input_.selecty, input_.selectfloor, false\n  );\n}\n\n\nconst bool \nMapSystem::room_collision(i32 floor, const Room& test_room) \nconst \n{\n  for (const auto& room : map_.blocks[floor]) {\n    if (SDL_HasIntersection(&room.rect, &test_room.rect)) {\n      return true;\n    }\n  }\n\n  for (const auto& room : map_.rooms[floor]) {\n    const auto intersection{SDL_HasIntersection(&room.rect, &test_room.rect)};\n\n    if (&room.rect != &test_room.rect && intersection) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n\nconst bool \nMapSystem::has_clearance(\n  const string& category, i32 x, i32 y, i32 floor, Dir dir\n) \nconst \n{\n  i8 dx1, dy1;\n  i8 dx2, dy2;\n  i8 dx3, dy3;\n\n  if (dir == Dir::UP) {\n    dx1 =  0; dy1 = -1;\n    dx2 = -1; dy2 =  0;\n    dx3 =  1; dy3 =  0;\n  } else if (dir == Dir::RIGHT) {\n    dx1 =  1; dy1 =  0;\n    dx2 =  0; dy2 = -1;\n    dx3 =  0; dy3 =  1;\n  } else if (dir == Dir::DOWN) {\n    dx1 =  0; dy1 =  1;\n    dx2 =  1; dy2 =  0;\n    dx3 = -1; dy3 =  0;\n  } else if (dir == Dir::LEFT) {\n    dx1 = -1; dy1 =  0;\n    dx2 =  0; dy2 =  1;\n    dx3 =  0; dy3 = -1;\n  }\n\n  const auto& tiles{map_.floors[floor].layers[\"wal\"].tiles};\n\n  const auto front_clear{tiles[x + dx1][y + dy1].type == \"\"};\n  const auto left_clear{tiles[x + dx2][y + dy2].category != \"door\"};\n  const auto right_clear{tiles[x + dx3][y + dy3].category != \"door\"};\n\n  return front_clear && left_clear && right_clear;\n}\n\n\nvoid \nMapSystem::set_tile(\n  const string& layer, i32 x, i32 y, i32 floor, const string& type, \n  f32 rot, SDL_RendererFlip flip\n) {\n  Tile& tile{map_.floors[floor].layers[layer].tiles[x][y]};\n\n  tile.active = true;\n  tile.rot = rot;\n  tile.flip = flip;\n\n  if (map_.tile_data.find(type) != map_.tile_data.end()) {\n    vector<string> type_vector; \n    boost::split(type_vector, type, boost::is_any_of(\"-\"));\n\n    tile.type = type_vector[0];\n    tile.subtype = type_vector.size() <= 1 ? \"\" : type_vector[1];\n    tile.category = map_.tile_data[type].category;\n    tile.src.x = map_.tile_data[type].uv.x * TILE_SIZE;\n    tile.src.y = map_.tile_data[type].uv.y * TILE_SIZE;\n  } else {\n    tile.src.x = 0;\n    tile.src.y = 0;\n\n    cerr << \"Tile(\" << x << \",\" << y << \") has invalid type: \";\n    cerr << tile.type << endl;\n  }\n}\n\n\nvoid \nMapSystem::set_solid(i32 x, i32 y, i32 floor, bool solid)\n{\n  Tile& tile{map_.floors[floor].layers[\"wal\"].tiles[x][y]};\n  tile.solid = solid;\n}\n\n\nvoid \nMapSystem::set_active(\n  const std::string& layer, i32 x, i32 y, i32 floor, bool active\n) {\n  Tile& tile{map_.floors[floor].layers[layer].tiles[x][y]};\n  tile.active = active;\n}\n\n\nconst i32 \nMapSystem::get_section(i32 floor) \nconst\n{\n  if (floor > 2 * NUM_FLOORS / 3 && floor <= NUM_FLOORS) {\n    return 3;\n  } else if (floor > 1 * NUM_FLOORS / 3) {\n    return 2;\n  } else if (floor > 0 * NUM_FLOORS / 3) {\n    return 1;\n  } else {\n    return -1;\n  }\n}\n\n", "meta": {"hexsha": "974e8597caf62b0cdc280d46c46b42046e4a0c1b", "size": 12989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/map/MapSystem.cpp", "max_stars_repo_name": "ecssiah/last-ditch", "max_stars_repo_head_hexsha": "af8ebe9a448f7f42c984a3f1d7d73ea811e1100f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-23T22:41:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-23T22:41:07.000Z", "max_issues_repo_path": "src/map/MapSystem.cpp", "max_issues_repo_name": "ecssiah/last-ditch", "max_issues_repo_head_hexsha": "af8ebe9a448f7f42c984a3f1d7d73ea811e1100f", "max_issues_repo_licenses": ["MIT"], "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/MapSystem.cpp", "max_forks_repo_name": "ecssiah/last-ditch", "max_forks_repo_head_hexsha": "af8ebe9a448f7f42c984a3f1d7d73ea811e1100f", "max_forks_repo_licenses": ["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.461393597, "max_line_length": 80, "alphanum_fraction": 0.567634152, "num_tokens": 4087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.1596790432344156}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef cancer_caller_hpp\n#define cancer_caller_hpp\n\n#include <vector>\n#include <unordered_map>\n#include <memory>\n#include <functional>\n#include <typeindex>\n\n#include <boost/optional.hpp>\n\n#include \"config/common.hpp\"\n#include \"core/types/haplotype.hpp\"\n#include \"core/types/cancer_genotype.hpp\"\n#include \"core/models/genotype/cancer_genotype_prior_model.hpp\"\n#include \"core/models/genotype/genotype_prior_model.hpp\"\n#include \"core/models/mutation/coalescent_model.hpp\"\n#include \"core/models/mutation/somatic_mutation_model.hpp\"\n#include \"core/models/genotype/individual_model.hpp\"\n#include \"core/models/genotype/cnv_model.hpp\"\n#include \"core/models/genotype/tumour_model.hpp\"\n#include \"basics/phred.hpp\"\n#include \"caller.hpp\"\n\nnamespace octopus {\n\nclass GenomicRegion;\nclass ReadPipe;\nclass Variant;\nclass VariantCall;\n\nclass CancerCaller : public Caller\n{\npublic:\n    using Caller::CallTypeSet;\n    \n    struct Parameters\n    {\n        enum class NormalContaminationRisk { high, low };\n        Phred<double> min_variant_posterior, min_somatic_posterior, min_refcall_posterior;\n        unsigned ploidy;\n        boost::optional<SampleName> normal_sample;\n        boost::optional<CoalescentModel::Parameters> germline_prior_model_params;\n        SomaticMutationModel::Parameters somatic_mutation_model_params;\n        double min_expected_somatic_frequency, credible_mass, min_credible_somatic_frequency;\n        std::size_t max_genotypes = 20000;\n        NormalContaminationRisk normal_contamination_risk = NormalContaminationRisk::low;\n        double cnv_normal_alpha = 50.0, cnv_tumour_alpha = 0.5;\n        double somatic_normal_germline_alpha = 50.0, somatic_normal_somatic_alpha = 0.05;\n        double somatic_tumour_germline_alpha = 1.5, somatic_tumour_somatic_alpha = 1.0;\n    };\n    \n    CancerCaller() = delete;\n    \n    CancerCaller(Caller::Components&& components,\n                 Caller::Parameters general_parameters,\n                 Parameters specific_parameters);\n    \n    CancerCaller(const CancerCaller&)            = delete;\n    CancerCaller& operator=(const CancerCaller&) = delete;\n    CancerCaller(CancerCaller&&)                 = delete;\n    CancerCaller& operator=(CancerCaller&&)      = delete;\n    \n    ~CancerCaller() = default;\n    \nprivate:\n    using GermlineModel = model::IndividualModel;\n    using CNVModel      = model::CNVModel;\n    using TumourModel   = model::TumourModel;\n    \n    class Latents;\n    friend Latents;\n    \n    struct ModelProbabilities\n    {\n        double germline, cnv, somatic;\n    };\n    \n    using ModelPriors     = ModelProbabilities;\n    using ModelPosteriors = ModelProbabilities;\n    \n    Parameters parameters_;\n    \n    // overrides\n    \n    std::string do_name() const override;\n    CallTypeSet do_call_types() const override;\n    \n    std::unique_ptr<Caller::Latents>\n    infer_latents(const std::vector<Haplotype>& haplotypes,\n                  const HaplotypeLikelihoodCache& haplotype_likelihoods) const override;\n    \n    boost::optional<double>\n    calculate_model_posterior(const std::vector<Haplotype>& haplotypes,\n                              const HaplotypeLikelihoodCache& haplotype_likelihoods,\n                              const Caller::Latents& latents) const override;\n    \n    boost::optional<double>\n    calculate_model_posterior(const std::vector<Haplotype>& haplotypes,\n                              const HaplotypeLikelihoodCache& haplotype_likelihoods,\n                              const Latents& latents) const;\n    \n    std::vector<std::unique_ptr<VariantCall>>\n    call_variants(const std::vector<Variant>& candidates, const Caller::Latents& latents) const override;\n    \n    std::vector<std::unique_ptr<VariantCall>>\n    call_variants(const std::vector<Variant>& candidates, const Latents& latents) const;\n    \n    std::vector<std::unique_ptr<ReferenceCall>>\n    call_reference(const std::vector<Allele>& alleles, const Caller::Latents& latents,\n                   const ReadMap& reads) const override;\n    \n    bool has_normal_sample() const noexcept;\n    const SampleName& normal_sample() const;\n    \n    using GenotypeVector                 = std::vector<Genotype<Haplotype>>;\n    using CancerGenotypeVector           = std::vector<CancerGenotype<Haplotype>>;\n    using GermlineGenotypeReference      = Genotype<Haplotype>;\n    using GermlineGenotypeProbabilityMap = std::unordered_map<GermlineGenotypeReference, double>;\n    using ProbabilityVector              = std::vector<double>;\n    \n    void generate_germline_genotypes(Latents& latents, const std::vector<Haplotype>& haplotypes) const;\n    void generate_cancer_genotypes(Latents& latents, const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    void generate_cancer_genotypes_with_clean_normal(Latents& latents, const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    void generate_cancer_genotypes_with_contaminated_normal(Latents& latents, const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    void generate_cancer_genotypes_with_no_normal(Latents& latents, const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    void generate_cancer_genotypes(Latents& latents, const std::vector<Genotype<Haplotype>>& germline_genotypes) const;\n    bool has_high_normal_contamination_risk(const Latents& latents) const;\n    \n    void evaluate_germline_model(Latents& latents, const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    void evaluate_cnv_model(Latents& latents, const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    void evaluate_tumour_model(Latents& latents, const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    void evaluate_noise_model(Latents& latents, const HaplotypeLikelihoodCache& haplotype_likelihoods) const;\n    void set_model_priors(Latents& latents) const;\n    void set_model_posteriors(Latents& latents) const;\n    \n    std::unique_ptr<GenotypePriorModel> make_germline_prior_model(const std::vector<Haplotype>& haplotypes) const;\n    CNVModel::Priors get_cnv_model_priors(const GenotypePriorModel& prior_model) const;\n    TumourModel::Priors get_somatic_model_priors(const CancerGenotypePriorModel& prior_model) const;\n    TumourModel::Priors get_noise_model_priors(const CancerGenotypePriorModel& prior_model) const;\n    CNVModel::Priors get_normal_noise_model_priors(const GenotypePriorModel& prior_model) const;\n    \n    GermlineGenotypeProbabilityMap\n    calculate_germline_genotype_posteriors(const Latents& latents, const ModelPosteriors& model_posteriors) const;\n    ProbabilityVector calculate_probability_samples_not_somatic(const Latents& inferences) const;\n    Phred<double> calculate_somatic_probability(const ProbabilityVector& sample_somatic_posteriors,\n                                                const ModelPosteriors& model_posteriors) const;\n};\n\nclass CancerCaller::Latents : public Caller::Latents\n{\npublic:\n    using Caller::Latents::HaplotypeProbabilityMap;\n    using Caller::Latents::GenotypeProbabilityMap;\n    \n    Latents() = delete;\n    \n    Latents(const std::vector<Haplotype>& haplotypes,\n            const std::vector<SampleName>& samples);\n    \n    std::shared_ptr<HaplotypeProbabilityMap> haplotype_posteriors() const override;\n    std::shared_ptr<GenotypeProbabilityMap> genotype_posteriors() const override;\n    \nprivate:\n    std::reference_wrapper<const std::vector<Haplotype>> haplotypes_;\n    std::vector<Genotype<Haplotype>> germline_genotypes_;\n    std::vector<CancerGenotype<Haplotype>> cancer_genotypes_;\n    boost::optional<std::vector<std::vector<unsigned>>> germline_genotype_indices_ = boost::none;\n    boost::optional<std::vector<std::pair<std::vector<unsigned>, unsigned>>> cancer_genotype_indices_ = boost::none;\n    \n    std::reference_wrapper<const std::vector<SampleName>> samples_;\n    boost::optional<std::reference_wrapper<const SampleName>> normal_sample_ = boost::none;\n    \n    CancerCaller::ModelPriors model_priors_;\n    std::unique_ptr<GenotypePriorModel> germline_prior_model_ = nullptr;\n    boost::optional<CancerGenotypePriorModel> cancer_genotype_prior_model_ = boost::none;\n    std::unique_ptr<GermlineModel> germline_model_ = nullptr;\n    GermlineModel::InferredLatents germline_model_inferences_;\n    CNVModel::InferredLatents cnv_model_inferences_;\n    TumourModel::InferredLatents tumour_model_inferences_;\n    boost::optional<TumourModel::InferredLatents> noise_model_inferences_ = boost::none;\n    boost::optional<GermlineModel::InferredLatents> normal_germline_inferences_ = boost::none;\n    CancerCaller::ModelPosteriors model_posteriors_;\n    \n    mutable std::shared_ptr<HaplotypeProbabilityMap> haplotype_posteriors_ = nullptr;\n    mutable std::shared_ptr<GenotypeProbabilityMap> genotype_posteriors_ = nullptr;\n    \n    friend CancerCaller;\n    \n    void compute_genotype_posteriors() const;\n    void compute_haplotype_posteriors() const;\n};\n\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "e0d17b5e856c41f3c85eed9cbc1cf0389de98077", "size": 9040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/callers/cancer_caller.hpp", "max_stars_repo_name": "alimanfoo/octopus", "max_stars_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-21T23:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T23:34:28.000Z", "max_issues_repo_path": "src/core/callers/cancer_caller.hpp", "max_issues_repo_name": "alimanfoo/octopus", "max_issues_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_issues_repo_licenses": ["MIT"], "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/callers/cancer_caller.hpp", "max_forks_repo_name": "alimanfoo/octopus", "max_forks_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_forks_repo_licenses": ["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.2, "max_line_length": 139, "alphanum_fraction": 0.7467920354, "num_tokens": 2170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.15957836141777623}}
{"text": "//receive ros msg:1.image_l,image_r   2.position.\n//output:scene struct.\n#include <memory>\n#include <glog/logging.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <opencv2/opencv.hpp>\n#include \"scene_retrieve.h\"\n#include <iostream>\n#include <thread>\n#include <ros/ros.h>\n#include <std_msgs/String.h>\n#include <roseus/StringStamped.h>\n#include <sensor_msgs/Image.h>\n#include <cv_bridge/cv_bridge.h>\n#include <opencv2/core/persistence.hpp>\n#include <message_filters/subscriber.h>\n#include <message_filters/time_synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <ros/duration.h>\n\n#include <image_process.h>\n#include \"global_frame_synchronizer.h\" //\u540c\u6b65\u4fe1\u606f\u7528.\n\n\n\nusing namespace std;\n\nros::Publisher Pub;\ncv::Mat* pQ_mat;\nLoopClosingManager* plcm;\n\ntemplate<typename Out>\nvoid split(const std::string &s, char delim, Out result) {\n    std::stringstream ss(s);\n    std::string item;\n    while (std::getline(ss, item, delim)) {\n        *(result++) = item;\n    }\n}\nstd::vector<std::string> __split(const std::string &s, char delim) {\n    std::vector<std::string> elems;\n    split(s, delim, std::back_inserter(elems));\n    return elems;\n}\n\nstd::vector<double> __split_comma_(const std::string input_str)\n{\n    std::vector<double> elems;\n    std::vector<string> str_d_ = __split(input_str,',');\n    LOG(INFO)<<\"in __split_comma_,input:\"<<input_str<<endl;\n    for(int i = 0;i<str_d_.size();i++)\n    {\n        elems.push_back(stod(str_d_[i]) );\n    }\n    return elems;\n}\n\nGlobalFrameSyncManager* pGlobalFrameSync;\nSceneRetriever* pSceneRetriever;\n\n\nvoid StereoImageCallback(const sensor_msgs::ImageConstPtr& msgLeft,const sensor_msgs::ImageConstPtr& msgRight);\n\nvoid GOG_INFO_CALLBACK(const roseus::StringStamped msg_gog) // here we use roseus::StringStamped.\n{\n    //auto msg_gog = *pmsg_gog;\n    cout<<\"in GOG_INFO_CALLBACK():\"<<endl;\n    LOG(INFO)<<\"in GOG_INFO_CALLBACK():\"<<endl;\n    auto timestamp = msg_gog.header.stamp;\n    string content(msg_gog.data);\n    LOG(INFO)<<\"in GOG_INFO_CALLBACK():original content:\"<<content<<endl;\n    // content contains:\n    // 1.\u5bf9\u5e94stamp\u7684\u56fe\u50cf\u5728gog_frame\u4e2d\u7684id.\n    \n    // 2.\u5bf9\u5e94stamp\u7684\u56fe\u50cf\u5728gog\u4e2d\u7684R,t.//\u53ef\u9009.\n   \n\n    //step<1> split content and do syntax analysis.\n    std::vector<std::string> parts = __split(content,'|');\n    std::string id_ = parts[0];\n    LOG(INFO)<<\"    id:\"<<id_<<endl;\n    std::string quat_ = parts[1];\n    LOG(INFO)<<\"    quat:\"<<quat_<<endl;\n    std::string translation_ = parts[2];\n    LOG(INFO)<<\"    translation:\"<<translation_<<endl;\n    LOG(INFO)<<\"Received GOG msg,id:\"<<id_<<\",quat:\"<<quat_<<\",translation:\"<<translation_<<endl;\n    int id = stoi(id_);\n    auto q_temp = __split_comma_(quat_);\n    Quaterniond quat(q_temp[0],q_temp[1],q_temp[2],q_temp[3]);\n    auto t_temp = __split_comma_(translation_);\n    Vector3d translation(t_temp[0],t_temp[1],t_temp[2]);\n    LOG(INFO)<<\"in GOG_INFO_CALLBACK():Calling GOG_msg_callback():\"<<endl;\n    pGlobalFrameSync->GOG_msg_callback(msg_gog,id,pSceneRetriever->getScene().getCurrentIndex());\n}\n\n/*void whole_callback(const sensor_msgs::ImageConstPtr& l, const sensor_msgs::ImageConstPtr& r, const roseus::StringStampedPtr& m)\n{\n    StereoImageCallback(l,r);\n    GOG_INFO_CALLBACK(m);\n}*/\n\nvoid StereoImageCallback(const sensor_msgs::ImageConstPtr& msgLeft,const sensor_msgs::ImageConstPtr& msgRight)\n{\n    LOG(INFO)<<\"in StereoImageCallback()\"<<endl;\n    cout<<\"in StereoImageCallback():\"<<endl;\n    std::shared_ptr<cv::Mat> pCurLeftImage(new cv::Mat), pCurRightImage(new cv::Mat);\n    try\n    {\n        //curLeftImage = cv_bridge::toCvShare(msgLeft)->image;\n        //curRightImage = cv_bridge::toCvShare(msgRight)->image;\n        //auto l_im& = cv_bridge::toCvShare(msgLeft)->image;\n        \n        cv::cvtColor(cv_bridge::toCvShare(msgLeft)->image, *pCurLeftImage, CV_BGR2GRAY);\n        cv::cvtColor(cv_bridge::toCvShare(msgRight)->image, *pCurRightImage, CV_BGR2GRAY);\n    }\n    catch(cv_bridge::Exception &e)\n    {\n        LOG(ERROR)<<\"in StereoImageCallback:cv_bridge exception caught!\"<<endl;\n        ROS_ERROR(\"in StereoImageCallback():cv_bridge exception: %s\", e.what());\n        return;\n    }\n\n    if (pCurLeftImage->empty() && pCurRightImage->empty())\n    {\n        LOG(WARNING)<<\"Empty image got in ros_global_optimization StereoImageCallback().\"<<endl;\n        return;\n    }\n    pGlobalFrameSync->Image_msg_callback(msgLeft->header.stamp,pCurLeftImage,pCurRightImage);//do loop closing check inside this callback;\n    /*\n    LOG(INFO)<<\"Forming empty rt mat.\"<<endl;\n    cv::Mat r_mat = cv::Mat::eye(3,3,CV_32F);\n    cv::Mat t_mat = cv::Mat::zeros(3,1,CV_32F);\n    LOG(INFO)<<\"Generating frame...\"<<endl;\n    bool success_gen = false;\n    auto current_scene_frame = generateSceneFrameFromStereoImage(curLeftImage,curRightImage,r_mat,t_mat,*pQ_mat,*plcm,success_gen);\n    if(!success_gen)\n    {\n        LOG(INFO)<<\"    after generateSceneFrameFromStereoImage():generate failed!\"<<endl;\n        return;\n    }\n    LOG(INFO)<<\"adding frame into scene...\"<<endl;\n    pSceneRetriever->addFrameToScene(std::get<0>(current_scene_frame),std::get<1>(current_scene_frame),std::get<2>(current_scene_frame),std::get<3>(current_scene_frame),std::get<4>(current_scene_frame));\n    int scene_frame_count = pSceneRetriever->getScene().getImageCount();\n    LOG(INFO)<<\"In ImageCallback():adding frame to scene by stereo...\"<<endl;\n    bool match_success;\n    cv::Mat RT_mat;\n    //int inliers = pSceneRetriever->retrieveSceneFromStereoImage(curLeftImage, curRightImage, *pQ_mat, RT_mat, match_success);\n    cv::Mat cam_matrix = (cv::Mat_<float >(3,3) << 376, 0, 376, \n            0, 376, 240, \n            0, 0, 1);\n    int loop_id;\n    int inliers = pSceneRetriever->retrieveSceneWithScaleFromMonoImage(curLeftImage,cam_matrix,RT_mat,match_success,&loop_id);\n\n    if(match_success)\n    {\n        LOG(INFO)<<\"In scene_retrieving_ros ImageCallback():Match success! RT mat is: \\n\"<<RT_mat<<endl;\n        //TODO:publish RT mat!\n        std_msgs::String str;\n        stringstream ss;\n        std::string str_content;\n        ss<<\"Frame id:\"<<loop_id<<\",\"<<scene_frame_count<<\";RT:\"<<RT_mat;\n        //ss>>str_content;\n        str_content = ss.str();\n        str.data = str_content.c_str();\n        Pub.publish(str);\n    }\n    else\n    {\n        LOG(INFO)<<\"Match failed.\"<<endl;\n        return;\n    }\n\n*/\n\n\n/*\n    cv::Mat RT_mat, Q_mat;\n    bool match_success;\n    int inliers = pSceneRetriever->retrieveSceneFromStereoImage(curLeftImage, curRightImage, Q_mat, RT_mat, match_success);\n    //step<3> form loop msg and publish to GOG.\n    if(match_success)\n    {\n        cout<<\" Match success! RT mat is: \\n\"<<RT_mat<<endl;\n        std_msgs::String str;\n        stringstream ss;\n        std::string str_content;\n        ss<<\"Frame id:\"<<0<<\",\"<<1<<\";RT:\"<<RT_mat;\n        ss>>str_content;\n        str.data = str_content.c_str();\n        Pub.publish(str);\n    }\n    else\n    {\n        return;\n    }\n*/\n}\n\n\nint main_of_backend_thread()\n{\n    LOG(INFO) << \"Starting backend thread.\"<<endl;\n    /*try\n    {\n        int *p = (int*)0;\n        cout<<\"create nullpoint deref error.\"<<endl;\n        cout<<\"*p = \"<<*p<<endl;\n    }\n    catch(...)\n    {\n        cout<<\"error caught!\"<<endl;\n        return -1;\n    }*/\n\n    //try\n    {\n        while(true)\n        {\n            LOG(INFO) << \"In backend thread:loop running.\"<<endl;\n            bool match_success_out = false;\n            cv::Mat camera_Q_mat;\n            cv::Mat RT_mat_out;\n            auto ret_val = pGlobalFrameSync->checkLoopTaskQueue(match_success_out,camera_Q_mat,RT_mat_out);\n            if(match_success_out)\n            {\n                LOG(INFO)<<\"in main_of_backend_thread():match success!\"<<endl;\n                LOG(INFO)<<\"Match success in backend thread,id:\"<<std::get<0>(ret_val)<<\",\"<<std::get<1>(ret_val)<<\".RT_mat:\"<<RT_mat_out<<endl;\n                //cout<<\" Match success! RT mat is: \\n\"<<RT_mat<<endl;\n                std_msgs::String str;\n                stringstream ss;\n                std::string str_content;\n                ss<<\"Frame id:\"<<0<<\",\"<<1<<\";RT:\"<<RT_mat_out;\n                ss>>str_content;\n                str.data = str_content.c_str();\n                Pub.publish(str);\n            }\n            {\n                LOG(INFO)<<\"Match failed sleep 0.1s.\"<<endl;\n                cout<<\"sleep 0.1s.\"<<endl;\n            }\n            std::this_thread::sleep_for(std::chrono::milliseconds(100));\n        }\n    }\n    //catch(...)\n    //{\n    //    LOG(ERROR) << \"Exiting concurrent thread.\"<<endl;\n    //}\n}\n\n\n\nint main(int argc,char** argv)\n{\n\n    google::InitGoogleLogging(argv[0]);\n    if (argc!=3)\n    {\n        //cout<<\"Usage: demo [scene_file_path] [voc_file_path] [l_image_path] [r_image_path] [Q_mat_file_path]\"<<endl;\n        LOG(INFO)<<\"Usage: demo [voc_file_path] [Q_mat_file_path]\"<<endl;\n    }\n    std::string voc_file_path(argv[1]) ,Q_mat_path(argv[2]);\n    LoopClosingManager lcm(voc_file_path);\n    plcm = &lcm;\n    LOG(INFO)<<\"voc_file_path: \"<<voc_file_path<<endl;\n    LOG(INFO)<<\"Q_mat_path: \"<<Q_mat_path<<endl;\n\n    cv::FileStorage fsSettings(Q_mat_path, cv::FileStorage::READ);\n    cv::Mat Q_mat;\n    fsSettings[\"Q_mat\"] >> Q_mat;\n\n    if (Q_mat.empty())\n    {\n        LOG(INFO)<<\"Q mat empty, exit.\"<<endl;\n        return -1;\n    }\n\n\n    LOG(INFO)<<\"Q_mat: \"<<endl<<Q_mat<<endl;\n    pQ_mat = &Q_mat;\n\n    cv::Mat RT_mat = (cv::Mat_<float >(4,4) << 1, 0, 0, 0,\n            0, 1, 0, 1,\n            0, 0, 1, 0,\n            0, 0, 0, 1);\n\n\n    /*cout<<\"Usage: ros_global_optimization [CONFIG_FILE_PATH]\"<<endl;\n    if (argc!=2)\n    {\n        cout <<\"Please check input format.\"<<endl;\n        exit(-1);\n    }\n    std::string config_file_path(argv[1]);\n    cv::FileStorage fSettings(config_file_path,cv::FileStorage::READ);\n    cv::Mat Q_mat;\n    fSettings[\"Q_mat\"] >> Q_mat;\n    if (Q_mat.empty())\n    {\n        cout<<\"Q mat empty, exit.\"<<endl;\n        return -1;\n    }\n    std::string voc_file_path(fSettings[\"VOC_FILE_PATH\"]);\n    std::string scene_path;\n    //std::string scene_path(argv[1]), voc_file_path(argv[2]) , l_img_path(argv[3]), r_img_path(argv[4]), Q_mat_path(argv[5]);\n\n    cv::Mat RT_mat = (cv::Mat_<float >(4,4) << 1, 0, 0, 0,\n            0, 1, 0, 1,\n            0, 0, 1, 0,\n            0, 0, 0, 1);*/\n\n    //ros init\n    ros::init(argc, argv, \"scene_retrieve\");\n    ros::NodeHandle nh;\n\n    Pub = nh.advertise<std_msgs::String>(\"/gaas/ros_gog_scene_retrieving\",10);\n    //std::shared_ptr<SceneRetriever> pSceneRetrieve(new SceneRetriever(voc_file_path));//, scene_path));\n    //std::shared_ptr<SceneRetriever> pSceneRetrieve(new DynamicalSceneRetriever(voc_file_path));//\u5148\u8bd5\u8bd5\u4fee\u6539\u539f\u6765\u7684\u7c7b,\u4e0d\u52a0\u5165\u65b0\u7684.\n    //pSceneRetriever = pSceneRetrieve;\n    pSceneRetriever = new SceneRetriever(voc_file_path);\n    pGlobalFrameSync = new GlobalFrameSyncManager(pSceneRetriever,pQ_mat,plcm);\n\n    ros::Subscriber gog_subscriber = nh.subscribe(\"/gaas/global_optimization_graph/state\", 30,GOG_INFO_CALLBACK);\n    message_filters::Subscriber<sensor_msgs::Image> left_sub(nh, \"/gi/simulation/left/image_raw\", 10);\n    message_filters::Subscriber<sensor_msgs::Image> right_sub(nh, \"/gi/simulation/right/image_raw\", 10);\n    //message_filters::Subscriber<roseus::StringStamped> global_optimization_graph_sub(nh,\"/gi/global_optimization/optimization_result\",30);\n\n    typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::Image> sync_pol;\n    message_filters::Synchronizer<sync_pol> sync(sync_pol(10), left_sub, right_sub);//,global_optimization_graph_sub);\n    sync.setMaxIntervalDuration(ros::Duration(0.01));\n    sync.registerCallback(boost::bind(StereoImageCallback, _1, _2));\n    //sync.registerCallback(boost::bind(whole_callback,_1,_2,_3));\n    //sync.registerCallback(whole_callback);\n    std::thread backend_thread(main_of_backend_thread);\n    ros::spin();\n    return 0;\n}\n\n\n\n\n", "meta": {"hexsha": "ca2aff7558205bb704145d5136819eb8baf5b5fb", "size": 11840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deprecated/software/scene_retrieving/src/ros_global_optimization.cpp", "max_stars_repo_name": "mfkiwl/GAAS", "max_stars_repo_head_hexsha": "29ab17d3e8a4ba18edef3a57c36d8db6329fac73", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "software/scene_retrieving/src/ros_global_optimization.cpp", "max_issues_repo_name": "Wayne-xixi/GAAS", "max_issues_repo_head_hexsha": "308ff4267ccc6fcad77eef07e21fa006cc2cdd5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "software/scene_retrieving/src/ros_global_optimization.cpp", "max_forks_repo_name": "Wayne-xixi/GAAS", "max_forks_repo_head_hexsha": "308ff4267ccc6fcad77eef07e21fa006cc2cdd5f", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 34.5189504373, "max_line_length": 203, "alphanum_fraction": 0.6423141892, "num_tokens": 3295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.15947859599039277}}
{"text": "/**\n * Copyright (c) 2017 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 <new>\n#include <algorithm>\n#include <cstring>\n\n#include <boost/iostreams/stream_buffer.hpp>\n#include <boost/iostreams/device/array.hpp>\n\n#include <opencv2/highgui/highgui.hpp>\n\n#include <sqlite3.h>\n\n#include <ogrsf_frmts.h>\n\n#include \"imgproc/rastermask/cvmat.hpp\"\n\n#include \"geo/verticaladjuster.hpp\"\n#include \"geo/csconvertor.hpp\"\n#include \"geo/srs.hpp\"\n\n#include \"../error.hpp\"\n#include \"../support/geo.hpp\"\n#include \"./operations.hpp\"\n\nnamespace bio = boost::iostreams;\nnamespace vr = vtslibs::registry;\n\nnamespace {\n\ncv::Mat* allocateMat(ManagedBuffer &mb\n                     , const math::Size2 &size, int type)\n{\n    // calculate sizes\n    const auto dataSize(math::area(size) * CV_ELEM_SIZE(type));\n    const auto matSize(sizeof(cv::Mat) + dataSize);\n\n    // create raw memory to hold matrix and data\n    char *raw(static_cast<char*>(mb.allocate(matSize)));\n\n    // allocate matrix in raw data block\n    return new (raw) cv::Mat(size.height, size.width, type\n                             , raw + sizeof(cv::Mat));\n}\n\ncv::Mat* warpImage(DatasetCache &cache, ManagedBuffer &mb\n                   , const std::string &dataset\n                   , const geo::SrsDefinition &srs\n                   , const math::Extents2 &extents\n                   , const math::Size2 &size\n                   , geo::GeoDataset::Resampling resampling\n                   , const boost::optional<std::string> &maskDataset\n                   , bool optimize)\n{\n    auto &src(cache(dataset));\n    auto dst(geo::GeoDataset::deriveInMemory(src, srs, size, extents));\n    src.warpInto(dst, resampling);\n\n    if (optimize && dst.cmask().empty()) {\n        throw EmptyImage(\"No valid data.\");\n    }\n\n    // apply mask set if defined\n    if (maskDataset) {\n        auto &srcMask(cache(*maskDataset));\n        auto dstMask(geo::GeoDataset::deriveInMemory\n                     (srcMask, srs, size, extents));\n        srcMask.warpInto(dstMask, resampling);\n        dst.applyMask(dstMask.cmask());\n\n        if (optimize && dst.cmask().empty()) {\n            throw EmptyImage(\"No valid data.\");\n        }\n    }\n\n    // grab destination\n    auto dstMat(dst.cdata());\n    auto type(CV_MAKETYPE(CV_8U, dstMat.channels()));\n\n    auto *tile(allocateMat(mb, size, type));\n    dstMat.convertTo(*tile, type);\n    return tile;\n}\n\ncv::Mat* warpMask(DatasetCache &cache, ManagedBuffer &mb\n                  , const std::string &dataset\n                  , const geo::SrsDefinition &srs\n                  , const math::Extents2 &extents\n                  , const math::Size2 &size\n                  , geo::GeoDataset::Resampling resampling\n                  , bool optimize)\n{\n    auto &src(cache(dataset));\n    auto dst(geo::GeoDataset::deriveInMemory(src, srs, size, extents));\n    src.warpInto(dst, resampling);\n\n    // fetch mask from dataset (optimized, all valid -> invalid matrix)\n    auto m(dst.fetchMask(optimize));\n    if (!m.data) {\n        // all pixels valid\n        throw FullImage(\"All data valid.\");\n    }\n\n    if (optimize) {\n        auto nonzero(cv::countNonZero(m));\n        if (!nonzero) {\n            // empty mask -> no valid data\n            throw EmptyImage(\"No valid data.\");\n        } else if (nonzero == area(size)) {\n            // all pixels valid\n            throw FullImage(\"All data valid.\");\n        }\n    }\n\n    auto *mask(allocateMat(mb, size, m.type()));\n    m.copyTo(*mask);\n    return mask;\n}\n\ncv::Mat* warpDetailMask(DatasetCache &cache, ManagedBuffer &mb\n                        , const std::string &dataset\n                        , const geo::SrsDefinition &srs\n                        , const math::Extents2 &extents\n                        , const math::Size2 &size)\n{\n    // generate metatile from mask dataset\n    auto &srcMask(cache(dataset));\n    auto dstMask(geo::GeoDataset::deriveInMemory\n                 (srcMask, srs, size, extents, boost::none\n                  , geo::GeoDataset::NodataValue()));\n\n    geo::GeoDataset::WarpOptions wo;\n    wo.srcNodataValue = geo::GeoDataset::NodataValue();\n    wo.dstNodataValue = geo::GeoDataset::NodataValue();\n    srcMask.warpInto(dstMask, geo::GeoDataset::Resampling::average, wo);\n\n    // mask is guaranteed to have single (double) channel\n    auto &dstMat(dstMask.cdata());\n    auto *tile(allocateMat(mb, size, dstMat.type()));\n    dstMat.copyTo(*tile);\n    return tile;\n}\n\nconst auto ForcedNodata(geo::GeoDataset::NodataValue(-1e10f));\n\ncv::Mat* warpValueMinMax(DatasetCache &cache, ManagedBuffer &mb\n                         , const std::string &dataset\n                         , const geo::SrsDefinition &srs\n                         , const math::Extents2 &extents\n                         , const math::Size2 &size\n                         , geo::GeoDataset::Resampling resampling)\n{\n    // combined result of warped dataset and result of warpMinMax\n    auto &src(cache(dataset));\n    auto &minSrc(cache(dataset + \".min\"));\n    auto &maxSrc(cache(dataset + \".max\"));\n\n    auto dst(geo::GeoDataset::deriveInMemory\n             (src, srs, size, extents, GDT_Float32, ForcedNodata));\n    auto minDst(geo::GeoDataset::deriveInMemory\n                (minSrc, srs, size, extents, GDT_Float32, ForcedNodata));\n    auto maxDst(geo::GeoDataset::deriveInMemory\n                (maxSrc, srs, size, extents, GDT_Float32, ForcedNodata));\n\n    geo::GeoDataset::WarpOptions warpOptions;\n#if GDAL_VERSION_NUM >= 2020000\n    // choose finer overview on GDAL>=2.2, since there is something rotten there\n    warpOptions.overviewBias = -1;\n#endif\n\n    auto wri(src.warpInto(dst, resampling, warpOptions));\n    minSrc.warpInto(minDst, geo::GeoDataset::Resampling::minimum\n                    , warpOptions);\n    maxSrc.warpInto(maxDst, geo::GeoDataset::Resampling::maximum\n                    , warpOptions);\n\n    // combine data\n    auto *tile(allocateMat(mb, size, CV_64FC3));\n    *tile = cv::Scalar(*ForcedNodata, *ForcedNodata, *ForcedNodata);\n\n    {\n        // TODO: use masks (get them as a byte matrices)\n        const auto &d(dst.cdata());\n        const auto &dmin(minDst.cdata());\n        const auto &dmax(maxDst.cdata());\n\n        auto id(d.begin<double>());\n        auto idmin(dmin.begin<double>());\n        auto idmax(dmax.begin<double>());\n\n        for (auto itile(tile->begin<cv::Vec3d>())\n                 , etile(tile->end<cv::Vec3d>());\n             itile != etile; ++itile, ++id, ++idmin, ++idmax)\n        {\n            // skip invalid value\n            auto value(*id);\n            if (value == ForcedNodata) { continue; }\n\n            auto &sample(*itile);\n            sample[0] = value;\n\n            if ((*idmin == ForcedNodata) || (*idmin > value)) {\n                // clone value into minimum if minimum is invalid or above value\n                sample[1] = value;\n            } else {\n                // copy min\n                sample[1] = *idmin;\n            }\n\n            if ((*idmax == ForcedNodata) || (*idmax < value)) {\n                // clone value into maximum if maximum is invalid or below value\n                sample[2] = value;\n            } else {\n                // copy max\n                sample[2] = *idmax;\n            }\n        }\n    }\n\n    return tile;\n}\n\ncv::Mat* warpDem(DatasetCache &cache, ManagedBuffer &mb\n                 , const std::string &dataset\n                 , const geo::SrsDefinition &srs\n                 , const math::Extents2 &extents\n                 , const math::Size2 &requestedSize\n                 , bool optimize)\n{\n    auto &src(cache(dataset));\n\n    // calculate size of dataset\n    auto size([&]() -> math::Size2\n    {\n        if (!optimize) { return requestedSize; }\n\n        auto pxc(tileCircumference(extents, srs, src));\n        // 1) divide circumference by 4 to get (average) length of one side\n        // 2) use 12 samples per one souce pixel\n        // 4) clip result to requesed size and 2\n        int samples(std::round(12.0 * pxc / 4.0));\n        return math::Size2\n            (std::max(std::min(samples, requestedSize.width), 2)\n             , std::max(std::min(samples, requestedSize.height), 2));\n    }());\n\n    // simulate grid registration\n    math::Size2 gridSize(size.width + 1, size.height + 1);\n    auto gridExtents(extentsPlusHalfPixel(extents, size));\n\n    // warp in floats\n    auto dst(geo::GeoDataset::deriveInMemory\n             (src, srs, gridSize, gridExtents, ::GDT_Float32\n              , ForcedNodata));\n\n    auto wri(src.warpInto(dst, geo::GeoDataset::Resampling::dem));\n    LOG(info1) << \"Warp result: scale=\" << wri.scale\n               << \", resampling=\" << wri.resampling << \".\";\n\n    // mask is guaranteed to have single (double) channel\n    auto &dstMat(dst.cdata());\n    auto *tile(allocateMat(mb, gridSize, dstMat.type()));\n    dstMat.copyTo(*tile);\n    return tile;\n}\n\n} // namespace\n\ncv::Mat* warp(DatasetCache &cache, ManagedBuffer &mb\n              , const GdalWarper::RasterRequest &req)\n{\n    typedef GdalWarper::RasterRequest::Operation Operation;\n\n    switch (req.operation) {\n    case Operation::image:\n    case Operation::imageNoOpt:\n        return warpImage\n            (cache, mb, req.dataset, req.srs, req.extents, req.size\n             , req.resampling, req.mask\n             , (req.operation == Operation::image));\n\n    case Operation::mask:\n    case Operation::maskNoOpt:\n        return warpMask\n            (cache, mb, req.dataset, req.srs, req.extents, req.size\n             , req.resampling, (req.operation == Operation::mask));\n\n    case Operation::detailMask:\n        return warpDetailMask\n            (cache, mb, req.dataset, req.srs, req.extents, req.size);\n\n    case Operation::dem:\n    case Operation::demOptimal:\n        return warpDem\n            (cache, mb, req.dataset, req.srs, req.extents, req.size\n             , (req.operation == Operation::demOptimal));\n\n    case Operation::valueMinMax:\n        return warpValueMinMax\n            (cache, mb, req.dataset, req.srs, req.extents, req.size\n             , req.resampling);\n    }\n    throw;\n}\n\nnamespace {\n\ntypedef std::shared_ptr< ::GDALDataset> VectorDataset;\n\nclass OptionsWrapper {\npublic:\n    OptionsWrapper() : opts_() {}\n\n    ~OptionsWrapper() { ::CSLDestroy(opts_); }\n\n    operator char**() const { return opts_; }\n\n    OptionsWrapper& operator()(const char *name, const char *value) {\n        opts_ = ::CSLSetNameValue(opts_, name, value);\n        return *this;\n    }\n\n    template <typename T>\n    OptionsWrapper& operator()(const char *name, const T &value) {\n        return operator()\n            (name, boost::lexical_cast<std::string>(value).c_str());\n    }\n\n    OptionsWrapper& operator()(const char *name, bool value) {\n        return operator()(name, value ? \"YES\" : \"NO\");\n    }\n\n    OptionsWrapper& operator()(const std::string &pair) {\n        opts_ = ::CSLAddString(opts_, pair.c_str());\n        return *this;\n    }\n\nprivate:\n    char **opts_;\n};\n\nVectorDataset openVectorDataset(const std::string &dataset\n                                , const OptionsWrapper &openOptions)\n{\n    auto ds(::GDALOpenEx(dataset.c_str(), (GDAL_OF_VECTOR | GDAL_OF_READONLY)\n                         , nullptr, openOptions, nullptr));\n\n    if (!ds) {\n        const auto code(::CPLGetLastErrorNo());\n        if (code == CPLE_OpenFailed) {\n            LOGTHROW(err2, EmptyGeoData)\n                << \"No file found for \" << dataset << \".\";\n        }\n\n        LOGTHROW(err2, std::runtime_error)\n            << \"Failed to open dataset \" << dataset << \" (\"\n            << ::CPLGetLastErrorNo() << \").\";\n    }\n\n    return VectorDataset(static_cast< ::GDALDataset*>(ds)\n                         , [](::GDALDataset *ds) { delete ds; });\n}\n\nVectorDataset openVectorDataset(const std::string &dataset\n                                , const geo::heightcoding::Config&\n                                , const GdalWarper::OpenOptions &openOptions)\n{\n    OptionsWrapper ow;\n    for (const auto &option : openOptions) { ow(option); }\n    return openVectorDataset(dataset, ow);\n}\n\nGdalWarper::Heightcoded*\nallocateHc(ManagedBuffer &mb\n           , const std::string &data\n           , const geo::heightcoding::Metadata &metadata)\n{\n    // create raw memory to hold block and data\n    char *raw(static_cast<char*>\n              (mb.allocate(sizeof(GdalWarper::Heightcoded) + data.size())));\n\n    // poiter to output data\n    auto *dataPtr(raw + sizeof(GdalWarper::Heightcoded));\n\n    // copy data into block\n    std::copy(data.begin(), data.end(), dataPtr);\n\n    // allocate block in raw data block\n    return new (raw) GdalWarper::Heightcoded\n        (dataPtr, data.size(), metadata);\n}\n\nstruct DbError : public std::runtime_error {\n    DbError(const std::string &msg) : std::runtime_error(msg) {}\n};\n\nclass SQLStatement {\npublic:\n    SQLStatement() : stmt_() {}\n    ~SQLStatement() { if (stmt_) { ::sqlite3_finalize(stmt_); } }\n    operator ::sqlite3_stmt*() { return stmt_; }\n    operator ::sqlite3_stmt**() { return &stmt_; }\n\nprivate:\n    ::sqlite3_stmt *stmt_;\n};\n\ntypedef geo::FeatureLayers::Features::Properties FeatureProperties;\n\nclass EnhanceDatabase {\npublic:\n    EnhanceDatabase(const std::string &path\n                    , const std::string &table)\n        : path_(path), table_(table), db_()\n    {\n        check(::sqlite3_open_v2\n              (path.c_str(), &db_, SQLITE_OPEN_READONLY, nullptr)\n              , \"sqlite3_open_v2\");\n\n        std::ostringstream os;\n        os << \"SELECT * FROM `\" << table << \"` WHERE `id`=?\";\n\n        const auto &str(os.str());\n        check(::sqlite3_prepare_v2(db_, str.data(), str.size()\n                                , select_, nullptr)\n              , \"sqlite3_prepare\");\n    }\n\n    ~EnhanceDatabase() { if (db_) { ::sqlite3_close(db_); } }\n\n    void enhance(FeatureProperties &properties, const std::string &id) {\n        check(::sqlite3_reset(select_), \"sqlite3_reset\");\n        check(::sqlite3_bind_text(select_, 1, id.data(), id.size(), nullptr)\n              , \"sqlite3_bind_text\");\n\n        switch (auto res = ::sqlite3_step(select_)) {\n        case SQLITE_ROW: break;\n\n        case SQLITE_DONE:\n            // nothing found\n            return;\n\n        default:\n            check(res, \"sqlite3_step\");\n        }\n\n        // process all columns\n        const int columns(::sqlite3_column_count(select_));\n        for (int column(0); column < columns; ++column) {\n            const auto name(::sqlite3_column_name(select_, column));\n            // skip id itself\n            if (!std::strcmp(name, \"id\")) { continue; }\n            const auto *text(reinterpret_cast<const char*>\n                             (::sqlite3_column_text(select_, column)));\n            const auto size(::sqlite3_column_bytes(select_, column));\n            properties.insert(FeatureProperties::value_type\n                              (name, std::string(text, size)));\n        }\n    }\n\nprivate:\n    void check(int status, const char *what) const {\n        if (status) {\n            const char *msg(::sqlite3_errmsg(db_));\n            LOGTHROW(err1, DbError)\n                << \"Sqlite3 operation \" << what << \" failed: <\"\n                << msg << \"> (file \\\"\" << path_ << \"\\\").\";\n        }\n    }\n\n    const std::string path_;\n    const std::string table_;\n    ::sqlite3 *db_;\n    SQLStatement select_;\n};\n\nvoid enhanceLayer(const LayerEnhancer &enhancer\n                   , geo::FeatureLayers::Layer &layer)\n{\n    EnhanceDatabase db(enhancer.databasePath, enhancer.table);\n\n    (void) db;\n\n    const auto manipulator([&](FeatureProperties &properties)\n    {\n        const auto fkey(properties.find(enhancer.key));\n        if (fkey == properties.end()) { return; }\n        db.enhance(properties, fkey->second);\n    });\n\n    layer.features.updateProperties(manipulator);\n}\n\nvoid enhanceLayers(const LayerEnhancer::map &layerEnancers\n                   , geo::FeatureLayers &layers)\n{\n    for (auto &layer : layers.layers) {\n        auto flayerEnancers(layerEnancers.find(layer.name));\n        if (flayerEnancers == layerEnancers.end()) { continue; }\n\n        const auto &enhancer(flayerEnancers->second);\n        enhanceLayer(enhancer, layer);\n    }\n}\n\nGdalWarper::Heightcoded*\nheightcode(ManagedBuffer &mb, const VectorDataset &vds\n           , std::vector<const geo::GeoDataset*> rds\n           , geo::heightcoding::Config config\n           , const boost::optional<std::string> &geoidGrid\n           , const boost::optional<std::string> &vectorGeoidGrid\n           , const LayerEnhancer::map &layerEnancers)\n{\n    if (geoidGrid) {\n        // apply geoid grid to SRS of rasterDs and set to rasterDsSrs\n        config.rasterDsSrs = geo::setGeoid(rds.back()->srs(), *geoidGrid);\n    }\n\n    if (vectorGeoidGrid && vds->GetLayerCount()) {\n        if (auto ref = vds->GetLayer(0)->GetSpatialRef()) {\n            // set vertical srs\n            config.vectorDsSrs\n                = geo::SrsDefinition::fromReference\n                (geo::setGeoid(*ref, *vectorGeoidGrid));\n        }\n    }\n\n    if (!layerEnancers.empty()) {\n        config.postprocess = [&](geo::FeatureLayers &layers) -> void {\n            enhanceLayers(layerEnancers, layers);\n        };\n    }\n\n    std::ostringstream os;\n    auto metadata(geo::heightcoding::heightCode(*vds, rds, os, config));\n\n    return allocateHc(mb, os.str(), metadata);\n}\n\n} // namespace\n\nGdalWarper::Heightcoded*\nheightcode(DatasetCache &cache, ManagedBuffer &mb\n           , const std::string &vectorDs\n           , const DemDataset::list &rasterDs\n           , geo::heightcoding::Config config\n           , const boost::optional<std::string> &vectorGeoidGrid\n           , const GdalWarper::OpenOptions &openOptions\n           , const LayerEnhancer::map &layerEnancers)\n{\n    std::vector<const geo::GeoDataset*> rasterDsStack;\n    for (const auto &ds : rasterDs) {\n        rasterDsStack.push_back(&cache(ds.dataset));\n    }\n\n    return heightcode(mb, openVectorDataset(vectorDs, config, openOptions)\n                      , rasterDsStack\n                      , config, rasterDs.back().geoidGrid\n                      , vectorGeoidGrid, layerEnancers);\n}\n", "meta": {"hexsha": "122c1773dc3dc5cb506cb88dcd3160bc8ea64375", "size": 19330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mapproxy/src/mapproxy/gdalsupport/operations.cpp", "max_stars_repo_name": "maka-io/vts-mapproxy", "max_stars_repo_head_hexsha": "13c70b1bd2013d76b387900fae839e3948e741c3", "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": "mapproxy/src/mapproxy/gdalsupport/operations.cpp", "max_issues_repo_name": "maka-io/vts-mapproxy", "max_issues_repo_head_hexsha": "13c70b1bd2013d76b387900fae839e3948e741c3", "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": "mapproxy/src/mapproxy/gdalsupport/operations.cpp", "max_forks_repo_name": "maka-io/vts-mapproxy", "max_forks_repo_head_hexsha": "13c70b1bd2013d76b387900fae839e3948e741c3", "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.0427350427, "max_line_length": 80, "alphanum_fraction": 0.5967925504, "num_tokens": 4659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.1593926086055076}}
{"text": "#pragma once\n\n#include \"generator/feature_builder.hpp\"\n#include \"generator/place_node.hpp\"\n\n#include \"geometry/point2d.hpp\"\n#include \"geometry/tree4d.hpp\"\n\n#include \"base/geo_object_id.hpp\"\n\n#include <cstddef>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/optional.hpp>\n\nnamespace generator_tests\n{\nclass TestPopularityBuilder;\n}  // namespace generator_tests\n\nnamespace generator\n{\nnamespace popularity\n{\n// These are functions for generating a csv file for popularity.\n// dataFilename - A path to data file\n// dataDir - A path to the directory where the data files are located\n// dataFilenames - Paths to data files\n// cpuCount - A number of processes\n// outFilename - A path where the csv file will be saved\n\n// Csv format:\n// Id;Parent id;Lat;Lon;Main type;Name\n// 9223372036936022489;;42.996411;41.004747;leisure-park;\u0421\u043a\u0432\u0435\u0440 \u0438\u043c. \u0418. \u0410. \u041a\u043e\u0433\u043e\u043d\u0438\u044f\n// 9223372037297546235;;43.325002;40.224941;leisure-park;\u041f\u0440\u0438\u043c\u043e\u0440\u0441\u043a\u0438\u0439 \u043f\u0430\u0440\u043a\n// 9223372036933918763;;43.005177;41.022295;leisure-park;\u0421\u0443\u0445\u0443\u043c\u0441\u043a\u0438\u0439 \u0431\u043e\u0442\u0430\u043d\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u0441\u0430\u0434\nvoid BuildPopularitySrcFromData(std::string const & dataFilename, std::string const & outFilename);\n\nvoid BuildPopularitySrcFromAllData(std::string const & dataDir, std::string const & outFilename,\n                                   size_t cpuCount = 1);\n\nvoid BuildPopularitySrcFromAllData(std::vector<std::string> const & dataFilenames, std::string const & outFilename,\n                                   size_t cpuCount = 1);\n\nclass PopularityGeomPlace\n{\npublic:\n  explicit PopularityGeomPlace(feature::FeatureBuilder const & feature);\n\n  bool Contains(PopularityGeomPlace const & smaller) const;\n  bool Contains(m2::PointD const & point) const;\n  feature::FeatureBuilder const & GetFeature() const { return m_feature; }\n  double GetArea() const { return m_area; }\n  base::GeoObjectId GetId() const { return m_id; }\n\nprivate:\n  using BoostPoint = boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>;\n  using BoostPolygon = boost::geometry::model::polygon<BoostPoint>;\n\n  base::GeoObjectId m_id;\n  std::reference_wrapper<feature::FeatureBuilder const> m_feature;\n  std::unique_ptr<BoostPolygon> m_polygon;\n  double m_area;\n};\n\nstruct PopularityLine\n{\n  base::GeoObjectId m_id;\n  boost::optional<base::GeoObjectId> m_parent;\n  m2::PointD m_center;\n  std::string m_type;\n  std::string m_name;\n};\n\nclass PopularityBuilder\n{\npublic:\n  friend class generator_tests::TestPopularityBuilder;\n\n  explicit PopularityBuilder(std::string const & dataFilename);\n\n  std::vector<PopularityLine> Build() const;\n\nprivate:\n  using Node = PlaceNode<PopularityGeomPlace>;\n  using Tree4d = m4::Tree<base::GeoObjectId>;\n  using MapIdToNode = std::unordered_map<base::GeoObjectId, Node::Ptr>;\n\n  static std::string GetType(feature::FeatureBuilder const & feature);\n  static std::string GetFeatureName(feature::FeatureBuilder const & feature);\n  static void FillLinesFromPointObjects(std::vector<feature::FeatureBuilder> const & pointObjs, MapIdToNode const & m,\n                                        Tree4d const & tree, std::vector<PopularityLine> & lines);\n  static boost::optional<base::GeoObjectId>\n  FindPointParent(m2::PointD const & point, MapIdToNode const & m, Tree4d const & tree);\n  static boost::optional<Node::Ptr>\n  FindPopularityGeomPlaceParent(PopularityGeomPlace const & place, MapIdToNode const & m,\n                                Tree4d const & tree);\n  static MapIdToNode GetAreaMap(Node::PtrList const & nodes);\n  static Tree4d MakeTree4d(Node::PtrList const & nodes);\n  static void FillLineFromGeomObjectPtr(PopularityLine & line, Node::Ptr const & node);\n  static void FillLinesFromGeomObjectPtrs(Node::PtrList const & nodes,\n                                          std::vector<PopularityLine> & lines);\n  static void LinkGeomPlaces(MapIdToNode const & m, Tree4d const & tree, Node::PtrList & nodes);\n  static Node::PtrList MakeNodes(std::vector<feature::FeatureBuilder> const & features);\n\n  std::string m_dataFilename;\n};\n}  // namespace popularity\n}  // namespace generator\n", "meta": {"hexsha": "33ecfbfa5ed03e926ee823bde7317da53f0732be", "size": 4071, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "generator/popularity.hpp", "max_stars_repo_name": "vmihaylenko/omim", "max_stars_repo_head_hexsha": "00087f340e723fc611cbc82e0ae898b9053b620a", "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": "generator/popularity.hpp", "max_issues_repo_name": "vmihaylenko/omim", "max_issues_repo_head_hexsha": "00087f340e723fc611cbc82e0ae898b9053b620a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-14T15:26:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-16T11:00:33.000Z", "max_forks_repo_path": "generator/popularity.hpp", "max_forks_repo_name": "vmihaylenko/omim", "max_forks_repo_head_hexsha": "00087f340e723fc611cbc82e0ae898b9053b620a", "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.0265486726, "max_line_length": 118, "alphanum_fraction": 0.7312699582, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.29746994260479465, "lm_q1q2_score": 0.15917569885147392}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// as_quantifier.hpp\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#ifndef BOOST_XPRESSIVE_DETAIL_STATIC_TRANSFORMS_AS_QUANTIFIER_HPP_EAN_04_01_2007\n#define BOOST_XPRESSIVE_DETAIL_STATIC_TRANSFORMS_AS_QUANTIFIER_HPP_EAN_04_01_2007\n\n// MS compatible compilers support #pragma once\n#if defined(_MSC_VER)\n#pragma once\n#endif\n\n#include <boost/mpl/assert.hpp>\n#include <boost/proto/core.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/xpressive/detail/detail_fwd.hpp>\n#include <boost/xpressive/detail/static/static.hpp>\n\nnamespace boost\n{\nnamespace xpressive\n{\nnamespace detail\n{\n///////////////////////////////////////////////////////////////////////////////\n// generic_quant_tag\ntemplate <uint_t Min, uint_t Max>\nstruct generic_quant_tag\n{\n    typedef mpl::integral_c<uint_t, Min> min_type;\n    typedef mpl::integral_c<uint_t, Max> max_type;\n};\n} // namespace detail\n} // namespace xpressive\n} // namespace boost\n\nnamespace boost\n{\nnamespace xpressive\n{\nnamespace grammar_detail\n{\nusing detail::uint_t;\n\n///////////////////////////////////////////////////////////////////////////////\n// min_type / max_type\ntemplate <typename Tag>\nstruct min_type : Tag::min_type\n{\n};\n\ntemplate <>\nstruct min_type<proto::tag::unary_plus> : mpl::integral_c<uint_t, 1>\n{\n};\n\ntemplate <>\nstruct min_type<proto::tag::dereference> : mpl::integral_c<uint_t, 0>\n{\n};\n\ntemplate <>\nstruct min_type<proto::tag::logical_not> : mpl::integral_c<uint_t, 0>\n{\n};\n\ntemplate <typename Tag>\nstruct max_type : Tag::max_type\n{\n};\n\ntemplate <>\nstruct max_type<proto::tag::unary_plus> : mpl::integral_c<uint_t, UINT_MAX - 1>\n{\n};\n\ntemplate <>\nstruct max_type<proto::tag::dereference> : mpl::integral_c<uint_t, UINT_MAX - 1>\n{\n};\n\ntemplate <>\nstruct max_type<proto::tag::logical_not> : mpl::integral_c<uint_t, 1>\n{\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// as_simple_quantifier\ntemplate <typename Grammar, typename Greedy,\n          typename Callable = proto::callable>\nstruct as_simple_quantifier\n    : proto::transform<as_simple_quantifier<Grammar, Greedy, Callable>>\n{\n    template <typename Expr, typename State, typename Data>\n    struct impl : proto::transform_impl<Expr, State, Data>\n    {\n        typedef typename proto::result_of::child<Expr>::type arg_type;\n\n        typedef\n            typename Grammar::template impl<arg_type, detail::true_xpression,\n                                            Data>::result_type xpr_type;\n\n        typedef detail::simple_repeat_matcher<xpr_type, Greedy> matcher_type;\n\n        typedef typename proto::terminal<matcher_type>::type result_type;\n\n        result_type operator()(typename impl::expr_param expr,\n                               typename impl::state_param,\n                               typename impl::data_param data) const\n        {\n            xpr_type xpr =\n                typename Grammar::template impl<arg_type,\n                                                detail::true_xpression, Data>()(\n                    proto::child(expr), detail::true_xpression(), data);\n\n            typedef typename impl::expr expr_type;\n            matcher_type matcher(\n                xpr, (uint_t)min_type<typename expr_type::proto_tag>::value,\n                (uint_t)max_type<typename expr_type::proto_tag>::value,\n                xpr.get_width().value());\n\n            return result_type::make(matcher);\n        }\n    };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// add_hidden_mark\nstruct add_hidden_mark : proto::transform<add_hidden_mark>\n{\n    template <typename Expr, typename State, typename Data>\n    struct impl : proto::transform_impl<Expr, State, Data>\n    {\n        typedef typename impl::expr expr_type;\n        typedef typename shift_right<\n            terminal<detail::mark_begin_matcher>::type,\n            typename shift_right<\n                Expr, terminal<detail::mark_end_matcher>::type>::type>::type\n            result_type;\n\n        result_type operator()(typename impl::expr_param expr,\n                               typename impl::state_param,\n                               typename impl::data_param data) const\n        {\n            // we're inserting a hidden mark ... so grab the next hidden mark\n            // number.\n            int mark_nbr = data.get_hidden_mark();\n            detail::mark_begin_matcher begin(mark_nbr);\n            detail::mark_end_matcher end(mark_nbr);\n\n            result_type that = {{begin}, {expr, {end}}};\n            return that;\n        }\n    };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// InsertMark\nstruct InsertMark : or_<when<proto::assign<detail::basic_mark_tag, _>, _>,\n                        otherwise<add_hidden_mark>>\n{\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// as_default_quantifier_impl\ntemplate <typename Greedy, uint_t Min, uint_t Max>\nstruct as_default_quantifier_impl\n    : proto::transform<as_default_quantifier_impl<Greedy, Min, Max>>\n{\n    template <typename Expr, typename State, typename Data>\n    struct impl : proto::transform_impl<Expr, State, Data>\n    {\n        typedef typename proto::result_of::child<Expr>::type xpr_type;\n\n        typedef typename InsertMark::impl<xpr_type, State, Data>::result_type\n            marked_sub_type;\n\n        typedef typename shift_right<\n            terminal<detail::repeat_begin_matcher>::type,\n            typename shift_right<marked_sub_type,\n                                 typename terminal<detail::repeat_end_matcher<\n                                     Greedy>>::type>::type>::type result_type;\n\n        result_type operator()(typename impl::expr_param expr,\n                               typename impl::state_param state,\n                               typename impl::data_param data) const\n        {\n            // Ensure this sub-expression is book-ended with mark matchers\n            marked_sub_type marked_sub =\n                InsertMark::impl<xpr_type, State, Data>()(proto::child(expr),\n                                                          state, data);\n\n            // Get the mark_number from the begin_mark_matcher\n            int mark_number =\n                proto::value(proto::left(marked_sub)).mark_number_;\n            BOOST_ASSERT(0 != mark_number);\n\n            typedef typename impl::expr expr_type;\n            uint_t min_ = (uint_t)min_type<typename expr_type::proto_tag>();\n            uint_t max_ = (uint_t)max_type<typename expr_type::proto_tag>();\n\n            detail::repeat_begin_matcher begin(mark_number);\n            detail::repeat_end_matcher<Greedy> end(mark_number, min_, max_);\n\n            result_type that = {{begin}, {marked_sub, {end}}};\n            return that;\n        }\n    };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// optional_tag\ntemplate <typename Greedy>\nstruct optional_tag\n{\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// as_default_optional\ntemplate <typename Grammar, typename Greedy,\n          typename Callable = proto::callable>\nstruct as_default_optional\n    : proto::transform<as_default_optional<Grammar, Greedy, Callable>>\n{\n    template <typename Expr, typename State, typename Data>\n    struct impl : proto::transform_impl<Expr, State, Data>\n    {\n        typedef detail::alternate_end_xpression end_xpr;\n\n        typedef detail::optional_matcher<\n            typename Grammar::template impl<Expr, end_xpr, Data>::result_type,\n            Greedy>\n            result_type;\n\n        result_type operator()(typename impl::expr_param expr,\n                               typename impl::state_param,\n                               typename impl::data_param data) const\n        {\n            return result_type(\n                typename Grammar::template impl<Expr, end_xpr, Data>()(\n                    expr, end_xpr(), data));\n        }\n    };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// as_mark_optional\ntemplate <typename Grammar, typename Greedy,\n          typename Callable = proto::callable>\nstruct as_mark_optional\n    : proto::transform<as_mark_optional<Grammar, Greedy, Callable>>\n{\n    template <typename Expr, typename State, typename Data>\n    struct impl : proto::transform_impl<Expr, State, Data>\n    {\n        typedef detail::alternate_end_xpression end_xpr;\n\n        typedef detail::optional_mark_matcher<\n            typename Grammar::template impl<Expr, end_xpr, Data>::result_type,\n            Greedy>\n            result_type;\n\n        result_type operator()(typename impl::expr_param expr,\n                               typename impl::state_param,\n                               typename impl::data_param data) const\n        {\n            int mark_number = proto::value(proto::left(expr)).mark_number_;\n\n            return result_type(\n                typename Grammar::template impl<Expr, end_xpr, Data>()(\n                    expr, end_xpr(), data),\n                mark_number);\n        }\n    };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// IsMarkerOrRepeater\nstruct IsMarkerOrRepeater\n    : or_<shift_right<terminal<detail::repeat_begin_matcher>, _>,\n          assign<terminal<detail::mark_placeholder>, _>>\n{\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// as_optional\ntemplate <typename Grammar, typename Greedy>\nstruct as_optional\n    : or_<when<IsMarkerOrRepeater, as_mark_optional<Grammar, Greedy>>,\n          otherwise<as_default_optional<Grammar, Greedy>>>\n{\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// make_optional_\ntemplate <typename Greedy, typename Callable = proto::callable>\nstruct make_optional_ : proto::transform<make_optional_<Greedy, Callable>>\n{\n    template <typename Expr, typename State, typename Data>\n    struct impl : proto::transform_impl<Expr, State, Data>\n    {\n        typedef typename impl::expr expr_type;\n        typedef\n            typename unary_expr<optional_tag<Greedy>, Expr>::type result_type;\n\n        result_type operator()(typename impl::expr_param expr,\n                               typename impl::state_param,\n                               typename impl::data_param) const\n        {\n            result_type that = {expr};\n            return that;\n        }\n    };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// as_default_quantifier_impl\ntemplate <typename Greedy, uint_t Max>\nstruct as_default_quantifier_impl<Greedy, 0, Max>\n    : call<make_optional_<Greedy>(as_default_quantifier_impl<Greedy, 1, Max>)>\n{\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// as_default_quantifier_impl\ntemplate <typename Greedy>\nstruct as_default_quantifier_impl<Greedy, 0, 1>\n    : call<make_optional_<Greedy>(_child)>\n{\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// as_default_quantifier\ntemplate <typename Greedy, typename Callable = proto::callable>\nstruct as_default_quantifier\n    : proto::transform<as_default_quantifier<Greedy, Callable>>\n{\n    template <typename Expr, typename State, typename Data>\n    struct impl : proto::transform_impl<Expr, State, Data>\n    {\n        typedef typename impl::expr expr_type;\n        typedef as_default_quantifier_impl<\n            Greedy, min_type<typename expr_type::proto_tag>::value,\n            max_type<typename expr_type::proto_tag>::value>\n            other;\n\n        typedef typename other::template impl<Expr, State, Data>::result_type\n            result_type;\n\n        result_type operator()(typename impl::expr_param expr,\n                               typename impl::state_param state,\n                               typename impl::data_param data) const\n        {\n            return typename other::template impl<Expr, State, Data>()(\n                expr, state, data);\n        }\n    };\n};\n\n} // namespace grammar_detail\n} // namespace xpressive\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "e9a4316552cafebdfe3b3023371520415b27ca37", "size": 12276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/xpressive/detail/static/transforms/as_quantifier.hpp", "max_stars_repo_name": "sotaoverride/backup", "max_stars_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/xpressive/detail/static/transforms/as_quantifier.hpp", "max_issues_repo_name": "sotaoverride/backup", "max_issues_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/xpressive/detail/static/transforms/as_quantifier.hpp", "max_forks_repo_name": "sotaoverride/backup", "max_forks_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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.3586956522, "max_line_length": 81, "alphanum_fraction": 0.5704626914, "num_tokens": 2390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3040416749665475, "lm_q1q2_score": 0.15914159960217472}}
{"text": "#include \"framework/builder/framework_builder.hpp\"\n\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/mpi.h>\n#include <sstream>\n#include <fstream>\n#include <quadrature/calculators/angular_flux_integrator.hpp>\n#include <quadrature/calculators/quadrature_calculators_factories.hpp>\n#include <calculator/drift_diffusion/drift_diffusion_vector_calculator.hpp>\n#include <calculator/drift_diffusion/factory.hpp>\n#include <formulation/scalar/scalar_formulation_factory.hpp>\n#include <formulation/updater/formulation_updater_factories.hpp>\n#include <iteration/subroutine/get_scalar_flux_from_framework.hpp>\n\n// Builders & factories\n#include \"solver/builder/solver_builder.hpp\"\n\n// Convergence classes\n#include \"convergence/iteration_completion_checker.hpp\"\n#include \"convergence/moments/convergence_checker_l1_norm.hpp\"\n#include \"convergence/moments/convergence_checker_l_infinity_norm.hpp\"\n#include \"convergence/moments/multi_moment_checker_max.hpp\"\n#include \"convergence/parameters/single_parameter_checker.hpp\"\n\n// Domain classes\n#include \"domain/domain.hpp\"\n#include \"domain/finite_element/finite_element_gaussian.hpp\"\n#include \"domain/mesh/mesh_cartesian.hpp\"\n\n// Formulation classes\n#include \"formulation/angular/self_adjoint_angular_flux.h\"\n#include \"formulation/scalar/diffusion.hpp\"\n#include \"formulation/scalar/drift_diffusion.hpp\"\n#include \"formulation/stamper.hpp\"\n#include \"formulation/updater/saaf_updater.h\"\n#include \"formulation/updater/diffusion_updater.hpp\"\n#include \"formulation/updater/drift_diffusion_updater.hpp\"\n\n// Framework class\n#include \"framework/framework.hpp\"\n\n// KEffective Updater Classes\n#include \"calculator/cell/total_aggregated_fission_source.hpp\"\n#include \"calculator/cell/integrated_fission_source.hpp\"\n#include \"eigenvalue/k_eigenvalue/calculator_via_fission_source.hpp\"\n#include \"eigenvalue/k_eigenvalue/calculator_via_rayleigh_quotient.hpp\"\n\n// Material classes\n#include \"data/material/material_protobuf.hpp\"\n\n// Iteration classes\n#include \"iteration/initializer/initialize_fixed_terms_once.h\"\n#include \"iteration/initializer/initialize_fixed_terms_reset_moments.hpp\"\n#include \"iteration/group/group_solve_iteration.hpp\"\n#include \"iteration/group/group_source_iteration.hpp\"\n#include \"iteration/outer/outer_power_iteration.hpp\"\n#include \"iteration/outer/outer_fixed_source_iteration.hpp\"\n\n// Quadrature classes & factories\n#include \"quadrature/quadrature_generator_i.h\"\n#include \"quadrature/factory/quadrature_factories.h\"\n#include \"quadrature/utility/quadrature_utilities.h\"\n\n// Results class\n#include \"results/output_dealii_vtu.h\"\n\n// System classes\n#include \"system/system.hpp\"\n#include \"system/solution/mpi_group_angular_solution.h\"\n#include \"system/solution/solution_types.h\"\n\n// Instrumentation\n#include \"instrumentation/builder/instrument_builder.hpp\"\n\nnamespace bart::framework::builder {\n\nnamespace  {\n\nusing InstrumentBuilder = instrumentation::builder::InstrumentBuilder;\nusing InstrumentName = instrumentation::builder::InstrumentName;\nusing StringColorPair = std::pair<std::string, utility::Color>;\n\n} // namespace\n\ntemplate<int dim>\nFrameworkBuilder<dim>::FrameworkBuilder(std::unique_ptr<Validator> validator_ptr)\n    : validator_ptr_(std::move(validator_ptr)) {}\n\n// =============================================================================\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildAngularFluxIntegrator(const std::shared_ptr<QuadratureSet> quadrature_set_ptr)\n-> std::unique_ptr<AngularFluxIntegrator> {\n  return quadrature::calculators::AngularFluxIntegrator<dim>::Factory::get()\n      .GetConstructor(quadrature::calculators::AngularFluxIntegratorName::kDefaultImplementation)(quadrature_set_ptr);\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildDiffusionFormulation(const std::shared_ptr<FiniteElement>& finite_element_ptr,\n                                                      const std::shared_ptr<data::cross_sections::CrossSectionsI>& cross_sections_ptr,\n                                                      const DiffusionFormulationImpl implementation)\n-> std::unique_ptr<DiffusionFormulation> {\n  ReportBuildingComponant(\"Diffusion formulation\");\n  std::unique_ptr<DiffusionFormulation> return_ptr = nullptr;\n\n  if (implementation == DiffusionFormulationImpl::kDefault) {\n    using ReturnType = formulation::scalar::Diffusion<dim>;\n    return_ptr = std::move(std::make_unique<ReturnType>(finite_element_ptr, cross_sections_ptr));\n  }\n  ReportBuildSuccess(return_ptr->description());\n\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildDriftDiffusionFormulation(\n    const std::shared_ptr<AngularFluxIntegrator>& angular_flux_integrator_ptr,\n    const std::shared_ptr<FiniteElement>& finite_element_ptr,\n    const std::shared_ptr<data::cross_sections::CrossSectionsI>& cross_sections_ptr) -> std::unique_ptr<DriftDiffusionFormulation> {\n  auto drift_diffusion_vector_calculator_ptr = Shared(calculator::drift_diffusion::DriftDiffusionVectorCalculatorIFactory<dim>::get()\n      .GetConstructor(calculator::drift_diffusion::DriftDiffusionVectorCalculatorName::kDefaultImplementation)());\n  return formulation::scalar::DriftDiffusion<dim>::Factory::get()\n      .GetConstructor(formulation::scalar::DriftDiffusionFormulationName::kDefaultImplementation)(\n          finite_element_ptr, cross_sections_ptr, drift_diffusion_vector_calculator_ptr, angular_flux_integrator_ptr);\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildDomain(FrameworkParameters::DomainSize domain_size,\n                                        FrameworkParameters::NumberOfCells number_of_cells,\n                                        const std::shared_ptr<FiniteElement>& finite_element_ptr,\n                                        std::string material_mapping) -> std::unique_ptr<Domain> {\n  std::unique_ptr<Domain> return_ptr = nullptr;\n  try {\n    ReportBuildingComponant(\"Mesh\");\n    auto mesh_ptr = std::make_unique<domain::mesh::MeshCartesian<dim>>(\n        domain_size.get(), number_of_cells.get(), material_mapping);\n    ReportBuildSuccess(mesh_ptr->description());\n\n    ReportBuildingComponant(\"Domain\");\n    return_ptr = std::move(std::make_unique<domain::Domain<dim>>(std::move(mesh_ptr), finite_element_ptr));\n    ReportBuildSuccess(return_ptr->description());\n  } catch (...) {\n    ReportBuildError();\n    throw;\n  }\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildFiniteElement(problem::CellFiniteElementType finite_element_type,\n                                               problem::DiscretizationType discretization_type,\n                                               FrameworkParameters::PolynomialDegree polynomial_degree)\n-> std::unique_ptr<FiniteElement> {\n  ReportBuildingComponant(\"Cell finite element basis\");\n  std::unique_ptr<FiniteElement> return_ptr{ nullptr };\n\n  try {\n    AssertThrow(polynomial_degree.get() > 0, dealii::ExcMessage(\"Bad polynomial degree\"))\n    switch (finite_element_type) {\n      case problem::CellFiniteElementType::kGaussian: {\n        using ReturnType = domain::finite_element::FiniteElementGaussian<dim>;\n        return_ptr = std::move(std::make_unique<ReturnType>(discretization_type, polynomial_degree.get()));\n      }\n    }\n  } catch (...) {\n    ReportBuildError();\n    throw;\n  }\n  ReportBuildSuccess(return_ptr->description());\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildUpdaterPointers(\n    std::unique_ptr<DiffusionFormulation> diffusion_formulation_ptr,\n    std::unique_ptr<DriftDiffusionFormulation> drift_diffusion_formulation_ptr,\n    std::shared_ptr<Stamper> stamper_ptr,\n    std::shared_ptr<AngularFluxIntegrator> angular_flux_integrator_ptr,\n    std::shared_ptr<SphericalHarmonicMoments> higher_order_moments_ptr,\n    AngularFluxStorage& angular_flux_storage,\n    const std::map<problem::Boundary, bool>& reflective_boundaries) -> UpdaterPointers {\n  ReportBuildingComponant(\"Building Drift-Diffusion Formulation updater\");\n  UpdaterPointers return_struct;\n\n  std::unordered_set<problem::Boundary> reflective_boundary_set;\n\n  for (const auto boundary_pair : reflective_boundaries) {\n    if (boundary_pair.second)\n      reflective_boundary_set.insert(boundary_pair.first);\n  }\n\n  using ReturnType = formulation::updater::DriftDiffusionUpdater<dim>;\n  auto implementation_name{ formulation::updater::DriftDiffusionUpdaterName::kDefaultImplementation };\n  auto drift_diffusion_updater_ptr = Shared(ReturnType::Factory::get().GetConstructor(implementation_name)(\n      std::move(diffusion_formulation_ptr),\n      std::move(drift_diffusion_formulation_ptr),\n      stamper_ptr,\n      angular_flux_integrator_ptr,\n      higher_order_moments_ptr,\n      angular_flux_storage,\n      reflective_boundary_set));\n\n  return_struct.fixed_updater_ptr = drift_diffusion_updater_ptr;\n  return_struct.fission_source_updater_ptr = drift_diffusion_updater_ptr;\n  return_struct.scattering_source_updater_ptr = drift_diffusion_updater_ptr;\n\n  return return_struct;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildUpdaterPointers(\n    std::unique_ptr<DiffusionFormulation> formulation_ptr,\n    std::unique_ptr<Stamper> stamper_ptr,\n    const std::map<problem::Boundary, bool>& reflective_boundaries) -> UpdaterPointers {\n  ReportBuildingComponant(\"Building Diffusion Formulation updater\");\n  UpdaterPointers return_struct;\n\n  std::unordered_set<problem::Boundary> reflective_boundary_set;\n\n  for (const auto boundary_pair : reflective_boundaries) {\n    if (boundary_pair.second)\n      reflective_boundary_set.insert(boundary_pair.first);\n  }\n\n  using ReturnType = formulation::updater::DiffusionUpdater<dim>;\n\n  auto diffusion_updater_ptr = std::make_shared<ReturnType>(std::move(formulation_ptr),\n                                                            std::move(stamper_ptr),\n                                                            reflective_boundary_set);\n  ReportBuildSuccess(diffusion_updater_ptr->description());\n  return_struct.fixed_updater_ptr = diffusion_updater_ptr;\n  return_struct.scattering_source_updater_ptr = diffusion_updater_ptr;\n  return_struct.fission_source_updater_ptr = diffusion_updater_ptr;\n\n  return return_struct;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildUpdaterPointers(\n    std::unique_ptr<SAAFFormulation> formulation_ptr,\n    std::unique_ptr<Stamper> stamper_ptr,\n    const std::shared_ptr<QuadratureSet>& quadrature_set_ptr) -> UpdaterPointers {\n  ReportBuildingComponant(\"Building SAAF Formulation updater\");\n  UpdaterPointers return_struct;\n\n  using ReturnType = formulation::updater::SAAFUpdater<dim>;\n  auto saaf_updater_ptr = std::make_shared<ReturnType>(std::move(formulation_ptr),\n                                                       std::move(stamper_ptr),\n                                                       quadrature_set_ptr);\n  ReportBuildSuccess(saaf_updater_ptr->description());\n  return_struct.fixed_updater_ptr = saaf_updater_ptr;\n  return_struct.scattering_source_updater_ptr = saaf_updater_ptr;\n  return_struct.fission_source_updater_ptr = saaf_updater_ptr;\n\n  return return_struct;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildUpdaterPointers(\n    std::unique_ptr<SAAFFormulation> formulation_ptr,\n    std::unique_ptr<Stamper> stamper_ptr,\n    const std::shared_ptr<QuadratureSet>& quadrature_set_ptr,\n    const std::map<problem::Boundary, bool>& reflective_boundaries,\n    const AngularFluxStorage& angular_flux_storage) -> UpdaterPointers {\n  ReportBuildingComponant(\"Building SAAF Formulation updater (with boundary conditions update)\");\n  UpdaterPointers return_struct;\n\n  // Transform map into set\n\n  std::unordered_set<problem::Boundary> reflective_boundary_set;\n\n  for (const auto boundary_pair : reflective_boundaries) {\n    if (boundary_pair.second)\n      reflective_boundary_set.insert(boundary_pair.first);\n  }\n\n  using ReturnType = formulation::updater::SAAFUpdater<dim>;\n  auto saaf_updater_ptr = std::make_shared<ReturnType>(std::move(formulation_ptr),\n                                                       std::move(stamper_ptr),\n                                                       quadrature_set_ptr,\n                                                       angular_flux_storage,\n                                                       reflective_boundary_set);\n  ReportBuildSuccess(saaf_updater_ptr->description());\n\n  return_struct.fixed_updater_ptr = saaf_updater_ptr;\n  return_struct.scattering_source_updater_ptr = saaf_updater_ptr;\n  return_struct.fission_source_updater_ptr = saaf_updater_ptr;\n  return_struct.boundary_conditions_updater_ptr = saaf_updater_ptr;\n\n  return return_struct;\n}\n\ntemplate <int dim>\nauto FrameworkBuilder<dim>::BuildGroupSolveIteration(\n    std::unique_ptr<SingleGroupSolver> single_group_solver_ptr,\n    std::unique_ptr<MomentConvergenceChecker> moment_convergence_checker_ptr,\n    std::unique_ptr<MomentCalculator> moment_calculator_ptr,\n    const std::shared_ptr<GroupSolution>& group_solution_ptr,\n    const UpdaterPointers& updater_ptrs,\n    std::unique_ptr<MomentMapConvergenceChecker> moment_map_convergence_checker_ptr)\n    -> std::unique_ptr<GroupSolveIteration> {\n  std::unique_ptr<GroupSolveIteration> return_ptr = nullptr;\n\n  ReportBuildingComponant(\"Iterative group solver\");\n\n  if (updater_ptrs.boundary_conditions_updater_ptr == nullptr) {\n    return_ptr = std::move(\n        std::make_unique<iteration::group::GroupSourceIteration<dim>>(\n            std::move(single_group_solver_ptr),\n            std::move(moment_convergence_checker_ptr),\n            std::move(moment_calculator_ptr),\n            group_solution_ptr,\n            updater_ptrs.scattering_source_updater_ptr,\n            std::move(moment_map_convergence_checker_ptr))\n    );\n  } else {\n    return_ptr = std::move(\n        std::make_unique<iteration::group::GroupSourceIteration<dim>>(\n            std::move(single_group_solver_ptr),\n            std::move(moment_convergence_checker_ptr),\n            std::move(moment_calculator_ptr),\n            group_solution_ptr,\n            updater_ptrs.scattering_source_updater_ptr,\n            updater_ptrs.boundary_conditions_updater_ptr,\n            std::move(moment_map_convergence_checker_ptr))\n    );\n  }\n\n  using ConvergenceStatusPort = iteration::group::data_ports::ConvergenceStatusPort;\n  using StatusPort = iteration::group::data_ports::StatusPort;\n\n  instrumentation::GetPort<ConvergenceStatusPort>(*return_ptr)\n      .AddInstrument(convergence_status_instrument_ptr_);\n  instrumentation::GetPort<StatusPort>(*return_ptr)\n      .AddInstrument(status_instrument_ptr_);\n\n  validator_ptr_->AddPart(FrameworkPart::ScatteringSourceUpdate);\n  ReportBuildSuccess(return_ptr->description());\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildGroupSolution(const int n_angles) -> std::unique_ptr<GroupSolution> {\n  std::unique_ptr<GroupSolution> return_ptr = nullptr;\n  ReportBuildingComponant(\"Group solution\");\n\n  return_ptr = std::move(std::make_unique<system::solution::MPIGroupAngularSolution>(n_angles));\n  ReportBuildSuccess(return_ptr->description());\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildInitializer(const std::shared_ptr<FixedTermUpdater>& updater_ptr,\n                                             const int total_groups,\n                                             const int total_angles,\n                                             const InitializerName implementation) -> std::unique_ptr<Initializer> {\n  ReportBuildingComponant(\"Initializer\");\n\n  std::unique_ptr<Initializer> return_ptr = nullptr;\n\n  if (implementation == InitializerName::kInitializeFixedTermsOnce) {\n    using InitializeOnceType = iteration::initializer::InitializeFixedTermsOnce;\n    return_ptr = std::move(std::make_unique<InitializeOnceType>(updater_ptr, total_groups, total_angles));\n  } else if (implementation == InitializerName::kInitializeFixedTermsAndResetMoments) {\n    using InitializeAndResetMoments = iteration::initializer::InitializeFixedTermsResetMoments;\n    return_ptr = std::move(std::make_unique<InitializeAndResetMoments>(updater_ptr, total_groups, total_angles));\n  }\n\n  ReportBuildSuccess(return_ptr->description());\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildInitializer(const std::shared_ptr<FixedTermUpdater>& updater_ptr,\n                                             const int total_groups,\n                                             const int total_angles) -> std::unique_ptr<Initializer> {\n  return BuildInitializer(updater_ptr, total_groups, total_angles, InitializerName::kInitializeFixedTermsOnce);\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildKEffectiveUpdater() -> std::unique_ptr<KEffectiveUpdater> {\n  using ReturnType = eigenvalue::k_eigenvalue::CalculatorViaRayleighQuotient;\n  ReportBuildingComponant(\"K_Effective updater\");\n  std::unique_ptr<KEffectiveUpdater> return_ptr{ nullptr };\n  return_ptr = std::move(std::make_unique<ReturnType>());\n  ReportBuildSuccess(return_ptr->description());\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildKEffectiveUpdater(\n    const std::shared_ptr<FiniteElement>& finite_element_ptr,\n    const std::shared_ptr<CrossSections>& cross_sections_ptr,\n    const std::shared_ptr<Domain>& domain_ptr)\n-> std::unique_ptr<KEffectiveUpdater> {\n  using AggregatedFissionSource = calculator::cell::TotalAggregatedFissionSource<dim>;\n  using IntegratedFissionSource = calculator::cell::IntegratedFissionSource<dim>;\n  using ReturnType = eigenvalue::k_eigenvalue::CalculatorViaFissionSource;\n\n  ReportBuildingComponant(\"K_Effective updater\");\n  std::unique_ptr<KEffectiveUpdater> return_ptr = nullptr;\n\n  return_ptr = std::move(\n      std::make_unique<ReturnType>(\n          std::make_unique<AggregatedFissionSource>(\n              std::make_unique<IntegratedFissionSource>(finite_element_ptr,\n                                                        cross_sections_ptr),\n              domain_ptr),\n          2.0,\n          10));\n\n  ReportBuildSuccess(return_ptr->description());\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildMomentCalculator(MomentCalculatorImpl implementation)\n-> std::unique_ptr<MomentCalculator> {\n  return BuildMomentCalculator(nullptr, implementation);\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildMomentCalculator(std::shared_ptr<QuadratureSet> quadrature_set_ptr,\n                                                  FrameworkBuilder::MomentCalculatorImpl implementation)\n-> std::unique_ptr<MomentCalculator> {\n  ReportBuildingComponant(\"Moment calculator\");\n  std::unique_ptr<MomentCalculator> return_ptr = nullptr;\n\n  try {\n    return_ptr = std::move(quadrature::factory::MakeMomentCalculator<dim>(implementation, quadrature_set_ptr));\n\n    if (implementation == MomentCalculatorImpl::kScalarMoment) {\n      ReportBuildSuccess(\"(default) calculator for scalar solve\");\n    } else if (implementation == MomentCalculatorImpl::kZerothMomentOnly) {\n      ReportBuildSuccess(\"(default) calculator for 0th moment only\");\n    } else {\n      AssertThrow(false,\n                  dealii::ExcMessage(\"Unsupported implementation of moment calculator specified in call to \"\n                                     \"BuildMomentCalculator\"))\n    }\n  } catch (...) {\n    ReportBuildError();\n    throw;\n  }\n\n  return return_ptr;\n}\n\n\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildMomentConvergenceChecker(\n    double max_delta,\n    int max_iterations) -> std::unique_ptr<MomentConvergenceChecker>{\n  //TODO(Josh): Add option for using other than L1Norm\n  ReportBuildingComponant(\"Moment convergence checker\");\n\n  using CheckerType = convergence::moments::ConvergenceCheckerLInfinityNorm;\n  using FinalCheckerType = convergence::IterationCompletionChecker<system::moments::MomentVector>;\n\n  auto return_ptr = std::make_unique<FinalCheckerType>(std::make_unique<CheckerType>(max_delta));\n  return_ptr->SetMaxIterations(max_iterations);\n  return return_ptr;\n}\n\ntemplate <int dim>\nauto FrameworkBuilder<dim>::BuildMomentMapConvergenceChecker(\n    double max_delta, int max_iterations)\n-> std::unique_ptr<MomentMapConvergenceChecker> {\n  ReportBuildingComponant(\"Moment map convergence checker\");\n\n  using SingleCheckerType = convergence::moments::ConvergenceCheckerLInfinityNorm;\n  using CheckerType = convergence::moments::MultiMomentCheckerMax;\n  using FinalCheckerType = convergence::IterationCompletionChecker<system::moments::MomentsMap>;\n\n  auto return_ptr = std::make_unique<FinalCheckerType>(\n      std::make_unique<CheckerType>(std::make_unique<SingleCheckerType>(max_delta)));\n  return_ptr->SetMaxIterations(max_iterations);\n  return return_ptr;\n}\ntemplate <int dim>\nauto FrameworkBuilder<dim>::BuildOuterIteration(\n    std::unique_ptr<GroupSolveIteration> group_iteration_ptr,\n    std::unique_ptr<ParameterConvergenceChecker> convergence_checker_ptr,\n    const std::string&)\n    -> std::unique_ptr<OuterIteration> {\n  ReportBuildingComponant(\"Outer iteration\");\n  std::unique_ptr<OuterIteration> return_ptr = nullptr;\n  using ReturnType = iteration::outer::OuterFixedSourceIteration;\n\n  return_ptr = std::move(std::make_unique<ReturnType>(\n      std::move(group_iteration_ptr),\n      std::move(convergence_checker_ptr)));\n\n  using ConvergenceDataPort = iteration::outer::data_names::ConvergenceStatusPort;\n  using StatusPort =  iteration::outer::data_names::StatusPort;\n\n  instrumentation::GetPort<ConvergenceDataPort>(*return_ptr)\n      .AddInstrument(convergence_status_instrument_ptr_);\n\n  instrumentation::GetPort<StatusPort>(*return_ptr)\n      .AddInstrument(status_instrument_ptr_);\n\n  ReportBuildSuccess(return_ptr->description());\n\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildOuterIteration(\n    std::unique_ptr<GroupSolveIteration> group_solve_iteration_ptr,\n    std::unique_ptr<ParameterConvergenceChecker> parameter_convergence_checker_ptr,\n    std::unique_ptr<KEffectiveUpdater> k_effective_updater_ptr,\n    const std::shared_ptr<FissionSourceUpdater>& fission_source_updater_ptr,\n    const std::string& output_filename_base)\n-> std::unique_ptr<OuterIteration> {\n  std::unique_ptr<OuterIteration> return_ptr = nullptr;\n  ReportBuildingComponant(\"Outer Iteration\");\n\n  using DefaultOuterPowerIteration = iteration::outer::OuterPowerIteration;\n\n  return_ptr = std::move(\n      std::make_unique<DefaultOuterPowerIteration>(\n          std::move(group_solve_iteration_ptr),\n          std::move(parameter_convergence_checker_ptr),\n          std::move(k_effective_updater_ptr),\n          fission_source_updater_ptr));\n\n  using ConvergenceDataPort = iteration::outer::data_names::ConvergenceStatusPort;\n  using StatusPort =  iteration::outer::data_names::StatusPort;\n  using IterationErrorPort = iteration::outer::data_names::IterationErrorPort;\n\n  using InstrumentBuilder = instrumentation::builder::InstrumentBuilder;\n  instrumentation::GetPort<ConvergenceDataPort>(*return_ptr)\n      .AddInstrument(convergence_status_instrument_ptr_);\n  instrumentation::GetPort<StatusPort>(*return_ptr)\n      .AddInstrument(status_instrument_ptr_);\n  instrumentation::GetPort<IterationErrorPort>(*return_ptr)\n      .AddInstrument(Shared(InstrumentBuilder::BuildInstrument<std::pair<int,double>>(\n          instrumentation::builder::InstrumentName::kIntDoublePairToFile,\n          output_filename_base + \"_iteration_error.csv\")));\n\n  validator_ptr_->AddPart(FrameworkPart::FissionSourceUpdate);\n  ReportBuildSuccess(return_ptr->description());\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildParameterConvergenceChecker(\n    double max_delta, int max_iterations)\n-> std::unique_ptr<ParameterConvergenceChecker>{\n  ReportBuildingComponant(\"Parameter (double) convergence checker\");\n  using CheckerType = convergence::parameters::SingleParameterChecker;\n  using FinalCheckerType = convergence::IterationCompletionChecker<double>;\n\n  auto return_ptr = std::make_unique<FinalCheckerType>(std::make_unique<CheckerType>(max_delta));\n  return_ptr->SetMaxIterations(max_iterations);\n\n  return return_ptr;\n}\n\ntemplate <int dim>\nauto FrameworkBuilder<dim>::BuildQuadratureSet(\n    const problem::AngularQuadType quadrature_type,\n    const FrameworkParameters::AngularQuadratureOrder order) -> std::shared_ptr<QuadratureSet> {\n  ReportBuildingComponant(\"quadrature set\");\n  using QuadratureGenerator = quadrature::QuadratureGeneratorI<dim>;\n\n  std::shared_ptr<QuadratureSet> return_ptr{ nullptr };\n  std::shared_ptr<QuadratureGenerator> quadrature_generator_ptr{ nullptr };\n\n  try {\n\n    switch (quadrature_type) {\n      case problem::AngularQuadType::kLevelSymmetricGaussian: {\n        AssertThrow(dim == 3, dealii::ExcMessage(\"Error in BuildQuadratureSet LSGC only available for 3D\"))\n        quadrature_generator_ptr = quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(\n            order, quadrature::AngularQuadratureSetType::kLevelSymmetricGaussian);\n        break;\n      }\n      case problem::AngularQuadType::kGaussLegendre: {\n        AssertThrow(dim == 1, dealii::ExcMessage(\"Error in BuildQuadratureSet GaussLegendre only available for 1D\"))\n        quadrature_generator_ptr =\n            quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(\n                order, quadrature::AngularQuadratureSetType::kGaussLegendre);\n        break;\n      }\n      default: {\n        AssertThrow(false, dealii::ExcMessage(\"No supported quadratures for this dimension and transport model\"))\n        break;\n      }\n    }\n    ReportBuildSuccess(quadrature_generator_ptr->description());\n\n    return_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>();\n\n    auto quadrature_points = quadrature::utility::GenerateAllPositiveX<dim>(quadrature_generator_ptr->GenerateSet());\n\n    quadrature::factory::FillQuadratureSet<dim>(return_ptr.get(), quadrature_points);\n\n    return return_ptr;\n  } catch (...) {\n    ReportBuildError();\n    throw;\n  }\n}\n\ntemplate <int dim>\nauto FrameworkBuilder<dim>::BuildSAAFFormulation(\n    const std::shared_ptr<FiniteElement>& finite_element_ptr,\n    const std::shared_ptr<data::cross_sections::CrossSectionsI>& cross_sections_ptr,\n    const std::shared_ptr<QuadratureSet>& quadrature_set_ptr,\n    const formulation::SAAFFormulationImpl implementation) -> std::unique_ptr<SAAFFormulation> {\n  ReportBuildingComponant(\"Building SAAF Formulation\");\n  std::unique_ptr<SAAFFormulation> return_ptr;\n\n  if (implementation == formulation::SAAFFormulationImpl::kDefault) {\n    using ReturnType = formulation::angular::SelfAdjointAngularFlux<dim>;\n    return_ptr = std::move(std::make_unique<ReturnType>(finite_element_ptr, cross_sections_ptr, quadrature_set_ptr));\n  }\n\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildSingleGroupSolver(const int max_iterations, const double convergence_tolerance)\n-> std::unique_ptr<SingleGroupSolver> {\n  using SolverName = solver::builder::SolverName;\n  using SolverBuilder = solver::builder::SolverBuilder;\n\n  ReportBuildingComponant(\"Single group solver\");\n  std::unique_ptr<SingleGroupSolver> return_ptr = nullptr;\n\n  return_ptr = std::move(SolverBuilder::BuildSolver(SolverName::kDefaultGMRESGroupSolver, max_iterations,\n                                                    convergence_tolerance));\n\n  ReportBuildSuccess(\"Default implementation with GMRES\");\n\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildSystem(\n    const int total_groups,\n    const int total_angles,\n    const Domain& domain,\n    const std::size_t solution_size,\n    bool is_eigenvalue_problem,\n    bool need_rhs_boundary_condition) -> std::unique_ptr<System> {\n  std::unique_ptr<System> return_ptr;\n\n  ReportBuildingComponant(\"system\");\n  try {\n    return_ptr = std::move(std::make_unique<System>());\n    system_helper_.InitializeSystem(*return_ptr, total_groups, total_angles,\n                             is_eigenvalue_problem, need_rhs_boundary_condition);\n    system_helper_.SetUpSystemTerms(*return_ptr, domain);\n    system_helper_.SetUpSystemMoments(*return_ptr, solution_size);\n    ReportBuildSuccess(\"system\");\n  } catch (...) {\n    ReportBuildError(\"system initialization error.\");\n    throw;\n  }\n\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildStamper(const std::shared_ptr<Domain>& domain_ptr) -> std::unique_ptr<Stamper> {\n  ReportBuildingComponant(\"Stamper\");\n  std::unique_ptr<Stamper> return_ptr = nullptr;\n\n  return_ptr = std::move(std::make_unique<formulation::Stamper<dim>>(domain_ptr));\n  ReportBuildSuccess(return_ptr->description());\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto FrameworkBuilder<dim>::BuildSubroutine(std::unique_ptr<FrameworkI> framework_ptr,\n                                            const SubroutineName subroutine_name) -> std::unique_ptr<Subroutine> {\n  std::unique_ptr<Subroutine> return_ptr{ nullptr };\n  if (subroutine_name == SubroutineName::kGetScalarFluxFromFramework) {\n    using ReturnType = iteration::subroutine::GetScalarFluxFromFramework;\n    return_ptr = std::move(std::make_unique<ReturnType>(std::move(framework_ptr)));\n  }\n  return return_ptr;\n}\n\ntemplate<int dim>\nvoid FrameworkBuilder<dim>::Validate() const {\n  validator_ptr_->ReportValidation();\n}\n\ntemplate class FrameworkBuilder<1>;\ntemplate class FrameworkBuilder<2>;\ntemplate class FrameworkBuilder<3>;\n\n} // namespace bart::framework::builder", "meta": {"hexsha": "7ebab2ba91b2794106d58d1afa12042736d24bcb", "size": 29329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/framework/builder/framework_builder.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/framework/builder/framework_builder.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/framework/builder/framework_builder.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 42.0186246418, "max_line_length": 134, "alphanum_fraction": 0.749394797, "num_tokens": 6315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.15914159630139105}}
{"text": "//\n// Created by yale on 8/14/18.\n//\n\n#include <random>\n#include <cmath>\n#include <boost/algorithm/hex.hpp>\n#include <eosio/chain/forest_bank.hpp>\n#include <celesos/miner_plugin/miner.hpp>\n\nusing namespace std;\nusing namespace eosio;\nusing namespace celesos;\n\nusing celesos::miner::worker;\nusing celesos::miner::worker_ctx;\n\nusing boost::multiprecision::uint256_t;\nusing boost::signals2::connection;\n\ncelesos::miner::miner::miner(const fc::logger &logger,\n                             boost::asio::io_service &main_io_service,\n                             unsigned int worker_count,\n                             uint32_t sleep_interval_sec,\n                             float sleep_probability) :\n        _logger{logger},\n        _alive_worker_ptrs{0, vector<shared_ptr<worker>>::allocator_type()},\n        _signal_ptr{make_shared<celesos::miner::mine_signal_type>()},\n        _main_io_service_ref{main_io_service},\n        _io_thread{&celesos::miner::miner::run, this},\n        _state{state::initialized},\n        _worker_count{worker_count},\n        _failure_retry_interval_us{fc::milliseconds(5000)},\n        _sleep_interval_sec{sleep_interval_sec},\n        _sleep_probability{sleep_probability},\n        _last_job_id{0} {\n}\n\ncelesos::miner::miner::~miner() {\n    fc_dlog(_logger, \"begin miner::~miner()\");\n    if (this->_signal_ptr) {\n        this->_signal_ptr->disconnect_all_slots();\n        this->_signal_ptr.reset();\n    }\n    this->stop(true);\n    if (this->_sub_io_service_ptr) {\n        this->_sub_io_service_ptr->stop();\n        this->_sub_io_service_ptr.reset();\n    }\n    fc_dlog(_logger, \"alive_worker_count: ${1}\", (\"1\", this->_alive_worker_ptrs.size()));\n    if (this->_io_thread.joinable()) {\n        this->_io_thread.detach();\n    }\n    fc_dlog(_logger, \"end miner::~miner()\");\n}\n\nvoid celesos::miner::miner::start(const chain::account_name &relative_account, chain::controller &cc) {\n    fc_dlog(_logger, \"attempt miner::start()\");\n    if (this->_state == state::started) {\n        return;\n    }\n    fc_dlog(_logger, \"begin miner::start()\");\n    this->_state = state::started;\n\n    auto slot = [this, &relative_account, &cc](const chain::block_state_ptr block_ptr) {\n        if (this->_last_failure_time_us) {\n            auto &&passed_time_us = fc::time_point::now().time_since_epoch() - this->_last_failure_time_us.get();\n            if (passed_time_us < this->_failure_retry_interval_us) {\n                return;\n            }\n        }\n\n        if (this->_last_forest_info_opt && (\n                this->_last_forest_info_opt->next_block_num == 0 ||\n                block_ptr->block_num < this->_last_forest_info_opt->next_block_num\n        )) {\n            return;\n        }\n\n        bool exception_occurred = true;\n        try {\n\n            auto &bank = *forest::forest_bank::getInstance(cc);\n\n            forest::forest_struct new_forest_info{};\n            if (!bank.get_forest(new_forest_info, relative_account)) {\n                FC_THROW_EXCEPTION(fc::unhandled_exception,\n                                   \"Fail to get forest with account: ${account}\",\n                                   (\"account\", relative_account));\n            }\n\n            bool no_old_forest = !this->_last_forest_info_opt;\n\n            bool is_forest_updated = false;\n            if (!no_old_forest) {\n                auto lhs = *this->_last_forest_info_opt;\n                auto &rhs = new_forest_info;\n                if (lhs.seed != rhs.seed || lhs.forest != rhs.forest || lhs.target != rhs.target) {\n                    is_forest_updated = true;\n                }\n            }\n\n            if (no_old_forest || is_forest_updated) {\n                fc_ilog(_logger, \"\\n\\tsuccess to get latest forest_info with \"\n                                 \"\\n\\t\\tseed: ${seed} \"\n                                 \"\\n\\t\\tforest: ${forest} \"\n                                 \"\\n\\t\\tblock_num: ${block_num}\"\n                                 \"\\n\\t\\tnext_block_num: ${next_block_num}\"\n                                 \"\\n\\t\\ttarget: ${target}\",\n                        (\"seed\", new_forest_info.seed.str())\n                                (\"forest\", new_forest_info.forest.str())\n                                (\"block_num\", new_forest_info.block_number)\n                                (\"next_block_num\", new_forest_info.next_block_num)\n                                (\"target\", new_forest_info.target.str(0, std::ios_base::hex)));\n\n\n                this->_last_job_id += 1;\n                auto old_forest_info = no_old_forest ? new_forest_info : *this->_last_forest_info_opt;\n\n                auto handler = std::bind(&miner::on_forest_updated, this,\n                                         old_forest_info, new_forest_info,\n                                         relative_account, no_old_forest);\n                this->_sub_io_service_ptr->post(handler);\n            }\n\n            this->_last_forest_info_opt = new_forest_info;\n\n            exception_occurred = false;\n        } catch (fc::exception &er) {\n            wlog(\"${details}\", (\"details\", er.to_detail_string()));\n        } catch (const std::exception &e) {\n            fc::exception fce{FC_LOG_MESSAGE(warn, \"rethrow ${what}: \", (\"what\", e.what())),\n                              fc::std_exception_code, BOOST_CORE_TYPEID(e).name(), e.what()};\n            wlog(\"${details}\", (\"details\", fce.to_detail_string()));\n        } catch (...) {\n            fc::unhandled_exception e{FC_LOG_MESSAGE(warn, \"rethrow\"), std::current_exception()};\n            wlog(\"${details}\", (\"details\", e.to_detail_string()));\n        }\n\n        if (exception_occurred) {\n            this->_last_failure_time_us = fc::time_point::now().time_since_epoch();\n            fc_elog(_logger, \"Fail to handle \\\"on_forest_update\\\"\");\n            return;\n        }\n\n        // clear last_failure_time_us for performance\n        this->_last_failure_time_us.reset();\n    };\n    auto a_connection = cc.accepted_block_header.connect(slot);\n    this->_connections.push_back(std::move(a_connection));\n    fc_dlog(_logger, \"end miner::start()\");\n}\n\nvoid celesos::miner::miner::stop_workers(bool wait) {\n    fc_dlog(_logger, \"begin miner::stop_workers(wait = ${wait})\", (\"wait\", wait));\n    for (auto &x : this->_alive_worker_ptrs) {\n        if (x) {\n            x->stop(wait);\n            x.reset();\n        }\n    }\n    this->_alive_worker_ptrs.clear();\n    fc_dlog(_logger, \"end miner::stop_workers(wait = ${wait})\", (\"wait\", wait));\n}\n\nvoid celesos::miner::miner::stop(bool wait) {\n    fc_dlog(_logger, \"begin miner::stop(wait = ${wait})\", (\"wait\", wait));\n    if (this->_state == state::stopped) {\n        fc_dlog(_logger, \"connection_count: ${1} worker_count: ${2}\",\n                (\"1\", this->_connections.size())(\"2\", this->_alive_worker_ptrs.size()));\n        fc_dlog(_logger, \"end miner::stop(wait = ${wait})\", (\"wait\", wait));\n        return;\n    }\n    this->_state = state::stopped;\n\n    for (auto &x : this->_connections) {\n        x.disconnect();\n    }\n    this->_connections.clear();\n\n    this->stop_workers(wait);\n\n    fc_dlog(_logger, \"end miner::stop(wait = ${wait})\", (\"wait\", wait));\n}\n\nconnection celesos::miner::miner::connect(const celesos::miner::mine_slot_type &slot) {\n    return _signal_ptr->connect(slot);\n}\n\nvoid celesos::miner::miner::on_forest_updated(const forest::forest_struct &old_forest_info,\n                                              const forest::forest_struct &new_forest_info,\n                                              const chain::account_name &relative_account, bool force) {\n    fc_ilog(_logger, \"on forest updated\");\n\n    auto current_job_id = this->_last_job_id;\n//    const auto target_ptr = make_shared<uint256_t>(\n//            \"0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n    const auto target_ptr = make_shared<uint256_t>(new_forest_info.target);\n\n    const auto seed_ptr = make_shared<string>(new_forest_info.seed.str());\n    const auto forest_ptr = make_shared<string>(new_forest_info.forest.str());\n\n    auto is_miner_quit_func = [this, current_job_id]() {\n        auto &logger = this->_logger;\n        if (this->_state == state::stopped) {\n            fc_ilog(logger, \"miner has been stop, quit\");\n            return true;\n        } else if (current_job_id != this->_last_job_id) {\n            fc_ilog(logger, \"forest has changed, quit\");\n            return true;\n        }\n        return false;\n    };\n\n    // prepare cache and dataset_ptr\n    const static auto is_cache_changed_func = [](const forest::forest_struct &old_forest,\n                                                 const forest::forest_struct &new_forest,\n                                                 const boost::optional<uint32_t> old_cache_count_opt,\n                                                 uint32_t new_cache_count) {\n        return !old_cache_count_opt ||\n               old_forest.forest != new_forest.forest ||\n               *old_cache_count_opt != new_cache_count;\n    };\n//    const uint32_t new_cache_count{512};\n\n    if (is_miner_quit_func()) {\n        return;\n    }\n\n    const auto new_cache_count = forest::cache_count();\n    const auto is_cache_changed = is_cache_changed_func(old_forest_info, new_forest_info,\n                                                        this->_target_cache_count_opt, new_cache_count);\n\n    shared_ptr<vector<ethash::node>> cache_ptr{};\n    if (force || is_cache_changed) {\n        fc_ilog(_logger, \"begin prepare cache with count: ${1}\", (\"1\", new_cache_count));\n        cache_ptr = make_shared<vector<ethash::node>>(new_cache_count, vector<ethash::node>::allocator_type());\n        ethash::calc_cache(*cache_ptr, new_cache_count, *seed_ptr);\n        fc_ilog(_logger, \"end prepare cache with count: ${1}\", (\"1\", new_cache_count));\n    } else {\n        fc_dlog(_logger, \"use cache generated\");\n        cache_ptr = *this->_target_cache_ptr_opt;\n    }\n\n    const static auto is_dataset_changed_func = [](bool is_cache_changed,\n                                                   const boost::optional<uint32_t> &old_dataset_count_opt,\n                                                   uint32_t new_dataset_count) {\n        return is_cache_changed ||\n               !old_dataset_count_opt ||\n               old_dataset_count_opt != new_dataset_count;\n    };\n\n    if (is_miner_quit_func()) {\n        return;\n    }\n\n//    const uint32_t new_dataset_count{512 * 16};\n    const auto new_dataset_count = forest::dataset_count();\n\n    const auto is_dataset_changed = is_dataset_changed_func(is_cache_changed,\n                                                            this->_target_dataset_count_opt, new_dataset_count);\n    shared_ptr<vector<ethash::node>> dataset_ptr{};\n    if (force || is_dataset_changed) {\n        fc_ilog(_logger, \"begin prepare dataset with count: ${1}\", (\"1\", new_dataset_count));\n        dataset_ptr = make_shared<vector<ethash::node>>(new_dataset_count,\n                                                        vector<ethash::node>::allocator_type());\n\n        auto &dataset = *dataset_ptr;\n        auto &cache = *cache_ptr;\n        dataset.resize(new_dataset_count);\n        for (uint32_t i = 0; i < new_dataset_count; ++i) {\n            if (i % 1000 == 0 && is_miner_quit_func()) {\n                return;\n            }\n            dataset[i] = calc_dataset_item(cache, i);\n        }\n\n//        ethash::calc_dataset(*dataset_ptr, new_dataset_count, *cache_ptr);\n        fc_ilog(_logger, \"end prepare dataset with count: ${1}\", (\"1\", new_dataset_count));\n    } else {\n        fc_dlog(_logger, \"use dataset generated\");\n        dataset_ptr = *this->_target_dataset_ptr_opt;\n    }\n\n    const static auto is_work_changed_func = [](bool is_dataset_changed,\n                                                const forest::forest_struct &old_forest,\n                                                const forest::forest_struct &new_forest) {\n        return is_dataset_changed || old_forest.forest != new_forest.forest;\n    };\n\n    if(is_miner_quit_func()) {\n        return;\n    }\n\n    const auto is_work_changed = is_work_changed_func(is_dataset_changed, old_forest_info, new_forest_info);\n    if (!force && !is_work_changed) {\n        fc_dlog(_logger, \"work not changed,no need to restart workers\");\n    } else {\n        fc_dlog(_logger, \"restart workers to logging\");\n        this->stop_workers(true);\n\n        auto retry_count_ptr = make_shared<uint256_t>(-1);\n        *retry_count_ptr /= _worker_count;\n\n        uint256_t nonce_init{0};\n        gen_random_uint256(nonce_init);\n\n        this->_alive_worker_ptrs.resize(_worker_count);\n        for (int i = 0; i < _worker_count; ++i) {\n            auto nonce_start_ptr = make_shared<uint256_t>(nonce_init + (*retry_count_ptr) * i);\n            worker_ctx ctx{\n                    .logger = _logger,\n                    .dataset_ptr = dataset_ptr,\n                    .seed_ptr = seed_ptr,\n                    .forest_ptr = forest_ptr,\n                    .nonce_start_ptr = std::move(nonce_start_ptr),\n                    .retry_count_ptr = retry_count_ptr,\n                    .target_ptr = target_ptr,\n                    .block_num = new_forest_info.block_number,\n                    .io_service_ref = this->_main_io_service_ref,\n                    .signal_ptr = this->_signal_ptr,\n                    .sleep_interval_sec = this->_sleep_interval_sec,\n                    .sleep_probability = this->_sleep_probability,\n            };\n            this->_alive_worker_ptrs[i] = make_shared<worker>(std::move(ctx));\n        }\n\n        if(is_miner_quit_func()) {\n            return;\n        }\n\n        for (auto &x : this->_alive_worker_ptrs) {\n            x->start();\n        }\n        fc_dlog(_logger, \"start worker with count: ${1}\", (\"1\", this->_alive_worker_ptrs.size()));\n    }\n\n    // update target fields\n    this->_target_cache_ptr_opt = cache_ptr;\n    this->_target_dataset_ptr_opt = dataset_ptr;\n    this->_target_cache_count_opt = new_cache_count;\n    this->_target_dataset_count_opt = new_dataset_count;\n\n    fc_dlog(_logger, \"end on_forested_updated()\");\n}\n\nvoid celesos::miner::miner::run() {\n    this->_sub_io_service_ptr = make_shared<boost::asio::io_service>();\n\n    auto sub_io_service_ptr = this->_sub_io_service_ptr;\n    boost::asio::io_service::work a_work{std::ref(*sub_io_service_ptr)};\n    sub_io_service_ptr->run();\n}\n\nvoid celesos::miner::miner::gen_random_uint256(uint256_t &dst) {\n    random_device rd{};\n    mt19937_64 gen{rd()};\n    uniform_int_distribution<uint64_t> dis{};\n    dst = 0;\n    for (int i = 0; i < 4; ++i) {\n        dst <<= 64;\n        dst |= dis(gen);\n    }\n}\n", "meta": {"hexsha": "1f1f224522f9ad6e4b2fad5c4b60a03eec3d497f", "size": 14603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugins/miner_plugin/miner.cpp", "max_stars_repo_name": "celes-dev/celesos", "max_stars_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "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": "plugins/miner_plugin/miner.cpp", "max_issues_repo_name": "celes-dev/celesos", "max_issues_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "max_issues_repo_licenses": ["MIT"], "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/miner_plugin/miner.cpp", "max_forks_repo_name": "celes-dev/celesos", "max_forks_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "max_forks_repo_licenses": ["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.0082191781, "max_line_length": 113, "alphanum_fraction": 0.5802917209, "num_tokens": 3270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.15898748603850169}}
{"text": "/**************************************************************\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 *************************************************************/\n\n\n\n// MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_cppcanvas.hxx\"\n\n#include <rtl/logfile.hxx>\n\n#include <com/sun/star/rendering/XCanvas.hpp>\n#include <com/sun/star/rendering/TexturingMode.hpp>\n\n#include <tools/gen.hxx>\n#include <vcl/canvastools.hxx>\n\n#include <basegfx/range/b2drectangle.hxx>\n#include <basegfx/tools/canvastools.hxx>\n#include <basegfx/polygon/b2dpolypolygon.hxx>\n#include <basegfx/polygon/b2dpolypolygontools.hxx>\n#include <basegfx/matrix/b2dhommatrix.hxx>\n#include <canvas/canvastools.hxx>\n\n#include <boost/utility.hpp>\n\n#include \"cachedprimitivebase.hxx\"\n#include \"polypolyaction.hxx\"\n#include \"outdevstate.hxx\"\n#include \"mtftools.hxx\"\n\n\nusing namespace ::com::sun::star;\n\nnamespace cppcanvas \n{ \n    namespace internal\n    {\n        namespace\n        {\n            class PolyPolyAction : public CachedPrimitiveBase\n            { \n            public: \n                PolyPolyAction( const ::basegfx::B2DPolyPolygon&,  \n                                const CanvasSharedPtr&, \n                                const OutDevState&,\n                                bool bFill,\n                                bool bStroke ); \n                PolyPolyAction( const ::basegfx::B2DPolyPolygon&,  \n                                const CanvasSharedPtr&, \n                                const OutDevState&,\n                                bool bFill,\n                                bool bStroke,\n                                int nTransparency ); \n\n                virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation,\n                                     const Subset&\t\t\t\t\trSubset ) const;\n\n                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const;\n                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                                       const Subset&\t\t\t\t\trSubset ) const;\n\n                virtual sal_Int32 getActionCount() const;\n\n            private:\n                using Action::render;\n                virtual bool render( uno::Reference< rendering::XCachedPrimitive >& rCachedPrimitive,\n                                     const ::basegfx::B2DHomMatrix&                 rTransformation ) const;\n\n                const uno::Reference< rendering::XPolyPolygon2D > \tmxPolyPoly;\n                const ::basegfx::B2DRange\t\t\t\t\t\t\tmaBounds;\n                const CanvasSharedPtr\t\t\t\t\t\t\t\tmpCanvas;\n\n            \t// stroke color is now implicit: the maState.DeviceColor member\n                rendering::RenderState\t\t\t\t\t\t\t\tmaState;\n                        \n                uno::Sequence< double >\t\t\t\t\t\t\t\tmaFillColor;\n            };\n\n            PolyPolyAction::PolyPolyAction( const ::basegfx::B2DPolyPolygon&\trPolyPoly, \n                                            const CanvasSharedPtr&              rCanvas,\n                                            const OutDevState&                  rState,\n                                            bool                                bFill,\n                                            bool                                bStroke ) :\n                CachedPrimitiveBase( rCanvas, false ),\n                mxPolyPoly( ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon( rCanvas->getUNOCanvas()->getDevice(), rPolyPoly) ),\n                maBounds( ::basegfx::tools::getRange(rPolyPoly) ),\n                mpCanvas( rCanvas ),\n                maState(),\n                maFillColor()\n            {\n                tools::initRenderState(maState,rState);\n\n                if( bFill )\n                    maFillColor = rState.fillColor;\n        \n                if( bStroke )\n                    maState.DeviceColor = rState.lineColor;\n            }\n\n            PolyPolyAction::PolyPolyAction( const ::basegfx::B2DPolyPolygon&\trPolyPoly, \n                                            const CanvasSharedPtr&              rCanvas,\n                                            const OutDevState&                  rState,\n                                            bool                                bFill,\n                                            bool                                bStroke,\n                                            int                                 nTransparency ) :\n                CachedPrimitiveBase( rCanvas, false ),\n                mxPolyPoly( ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon( rCanvas->getUNOCanvas()->getDevice(), rPolyPoly) ),\n                maBounds( ::basegfx::tools::getRange(rPolyPoly) ),\n                mpCanvas( rCanvas ),\n                maState(),\n                maFillColor()\n            {\n                tools::initRenderState(maState,rState);\n\n                if( bFill )\n                {\n                    maFillColor = rState.fillColor;\n\n                    if( maFillColor.getLength() < 4 )\n                        maFillColor.realloc( 4 );\n\n                    // TODO(F1): Color management\n                    // adapt fill color transparency\n                    maFillColor[3] = 1.0 - nTransparency / 100.0;\n                }\n        \n                if( bStroke )\n                {\n                    maState.DeviceColor = rState.lineColor;\n\n                    if( maState.DeviceColor.getLength() < 4 )\n                        maState.DeviceColor.realloc( 4 );\n\n                    // TODO(F1): Color management\n                    // adapt fill color transparency\n                    maState.DeviceColor[3] = 1.0 - nTransparency / 100.0;\n                }\n            }\n\n            bool PolyPolyAction::render( uno::Reference< rendering::XCachedPrimitive >& rCachedPrimitive,\n                                         const ::basegfx::B2DHomMatrix&                 rTransformation ) const\n            {\n                RTL_LOGFILE_CONTEXT( aLog, \"::cppcanvas::internal::PolyPolyAction::render()\" );\n                RTL_LOGFILE_CONTEXT_TRACE1( aLog, \"::cppcanvas::internal::PolyPolyAction: 0x%X\", this );\n\n                rendering::RenderState aLocalState( maState );\n                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);\n\n#ifdef SPECIAL_DEBUG\n                aLocalState.Clip.clear();\n                aLocalState.DeviceColor = \n                    ::vcl::unotools::colorToDoubleSequence( mpCanvas->getUNOCanvas()->getDevice(),\n                                                            ::Color( 0x80FF0000 ) );\n\n                if( maState.Clip.is() )\n                    mpCanvas->getUNOCanvas()->fillPolyPolygon( maState.Clip, \n                                                               mpCanvas->getViewState(), \n                                                               aLocalState );\n\n                aLocalState.DeviceColor = maState.DeviceColor;\n#endif\n\n                if( maFillColor.getLength() )\n                {\n                    // TODO(E3): Use DBO's finalizer here,\n                    // fillPolyPolygon() might throw\n                    const uno::Sequence< double > aTmpColor( aLocalState.DeviceColor );\n                    aLocalState.DeviceColor = maFillColor;\n                    \n                    rCachedPrimitive = mpCanvas->getUNOCanvas()->fillPolyPolygon( mxPolyPoly, \n                                                                                  mpCanvas->getViewState(),\n                                                                                  aLocalState );\n                    \n                    aLocalState.DeviceColor = aTmpColor;\n                }\n                \n                if( aLocalState.DeviceColor.getLength() )\n                {\n                    rCachedPrimitive = mpCanvas->getUNOCanvas()->drawPolyPolygon( mxPolyPoly, \n                                                                                  mpCanvas->getViewState(),\n                                                                                  aLocalState );\n                }\n\n                return true;\n            }\n\n            bool PolyPolyAction::render( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                         const Subset&\t\t\t\t\trSubset ) const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n\n                // polygon only contains a single action, fail if subset\n                // requests different range\n                if( rSubset.mnSubsetBegin != 0 ||\n                    rSubset.mnSubsetEnd != 1 )\n                    return false;\n\n                return CachedPrimitiveBase::render( rTransformation );\n            }\n\n            ::basegfx::B2DRange PolyPolyAction::getBounds( const ::basegfx::B2DHomMatrix&\trTransformation ) const\n            {\n                rendering::RenderState aLocalState( maState );\n                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);\n                \n                return tools::calcDevicePixelBounds( \n                    maBounds,\n                    mpCanvas->getViewState(),\n                    aLocalState );\n            }\n\n            ::basegfx::B2DRange PolyPolyAction::getBounds( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                                           const Subset&\t\t\t\t\trSubset ) const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n\n                // polygon only contains a single action, empty bounds\n                // if subset requests different range\n                if( rSubset.mnSubsetBegin != 0 ||\n                    rSubset.mnSubsetEnd != 1 )\n                    return ::basegfx::B2DRange();\n\n                return getBounds( rTransformation );\n            }\n\n            sal_Int32 PolyPolyAction::getActionCount() const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n                return 1;\n            }\n\n\n            // -------------------------------------------------------------------------------\n\n            class TexturedPolyPolyAction : public CachedPrimitiveBase\n            { \n            public: \n                TexturedPolyPolyAction( const ::basegfx::B2DPolyPolygon& rPoly,\n                                        const CanvasSharedPtr&\t\t     rCanvas, \n                                        const OutDevState&\t\t\t     rState,\n                                        const rendering::Texture& \t     rTexture ); \n\n                virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation,\n                                     const Subset&\t\t\t\t\trSubset ) const;\n\n                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const;\n                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                                       const Subset&\t\t\t\t\trSubset ) const;\n\n                virtual sal_Int32 getActionCount() const;\n\n            private:\n                using Action::render;\n                virtual bool render( uno::Reference< rendering::XCachedPrimitive >& rCachedPrimitive,\n                                     const ::basegfx::B2DHomMatrix&                 rTransformation ) const;\n\n                const uno::Reference< rendering::XPolyPolygon2D >\tmxPolyPoly;\n                const ::basegfx::B2DRectangle\t\t\t\t\t\tmaBounds;\n                const CanvasSharedPtr\t\t\t\t\t\t\t\tmpCanvas;\n\n            \t// stroke color is now implicit: the maState.DeviceColor member\n                rendering::RenderState\t\t\t\t\t\t\t\tmaState;\n                const rendering::Texture\t\t\t\t\t\t\tmaTexture;\n            };\n\n            TexturedPolyPolyAction::TexturedPolyPolyAction( const ::basegfx::B2DPolyPolygon& rPolyPoly, \n                                                            const CanvasSharedPtr&\t\t     rCanvas,\n                                                            const OutDevState& \t\t\t     rState,\n                                                            const rendering::Texture& \t     rTexture ) :\n                CachedPrimitiveBase( rCanvas, true ),\n                mxPolyPoly( ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon( rCanvas->getUNOCanvas()->getDevice(), rPolyPoly) ),\n                maBounds( ::basegfx::tools::getRange(rPolyPoly) ),\n                mpCanvas( rCanvas ),\n                maState(),\n                maTexture( rTexture )\n            {\n                tools::initRenderState(maState,rState);\n            }\n\n            bool TexturedPolyPolyAction::render( uno::Reference< rendering::XCachedPrimitive >& rCachedPrimitive,\n                                                 const ::basegfx::B2DHomMatrix&                 rTransformation ) const\n            {\n                RTL_LOGFILE_CONTEXT( aLog, \"::cppcanvas::internal::PolyPolyAction::render()\" );\n                RTL_LOGFILE_CONTEXT_TRACE1( aLog, \"::cppcanvas::internal::PolyPolyAction: 0x%X\", this );\n\n                rendering::RenderState aLocalState( maState );\n                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);\n\n                uno::Sequence< rendering::Texture > aSeq(1);\n                aSeq[0] = maTexture;\n                \n                rCachedPrimitive = mpCanvas->getUNOCanvas()->fillTexturedPolyPolygon( mxPolyPoly, \n                                                                                      mpCanvas->getViewState(),\n                                                                                      aLocalState,\n                                                                                      aSeq );\n                return true;\n            }\n\n            bool TexturedPolyPolyAction::render( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                                 const Subset&\t\t\t\t\trSubset ) const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n\n                // polygon only contains a single action, fail if subset\n                // requests different range\n                if( rSubset.mnSubsetBegin != 0 ||\n                    rSubset.mnSubsetEnd != 1 )\n                    return false;\n\n                return CachedPrimitiveBase::render( rTransformation );\n            }\n\n            ::basegfx::B2DRange TexturedPolyPolyAction::getBounds( const ::basegfx::B2DHomMatrix&\trTransformation ) const\n            {\n                rendering::RenderState aLocalState( maState );\n                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);\n                \n                return tools::calcDevicePixelBounds( \n                    maBounds,\n                    mpCanvas->getViewState(),\n                    aLocalState );\n            }\n\n            ::basegfx::B2DRange TexturedPolyPolyAction::getBounds( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                                                   const Subset&\t\t\t\t\trSubset ) const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n\n                // polygon only contains a single action, empty bounds\n                // if subset requests different range\n                if( rSubset.mnSubsetBegin != 0 ||\n                    rSubset.mnSubsetEnd != 1 )\n                    return ::basegfx::B2DRange();\n\n                return getBounds( rTransformation );\n            }\n\n            sal_Int32 TexturedPolyPolyAction::getActionCount() const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n                return 1;\n            }\n\n            // -------------------------------------------------------------------------------\n\n            class StrokedPolyPolyAction : public CachedPrimitiveBase\n            { \n            public: \n                StrokedPolyPolyAction( const ::basegfx::B2DPolyPolygon&     rPoly,\n                                       const CanvasSharedPtr&\t\t\t\trCanvas, \n                                       const OutDevState&\t\t\t\t\trState,\n                                       const rendering::StrokeAttributes&\trStrokeAttributes ); \n\n                virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation,\n                                     const Subset&\t\t\t\t\trSubset ) const;\n\n                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const;\n                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                                       const Subset&\t\t\t\t\trSubset ) const;\n\n                virtual sal_Int32 getActionCount() const;\n\n            private:\n                using Action::render;\n                virtual bool render( uno::Reference< rendering::XCachedPrimitive >& rCachedPrimitive,\n                                     const ::basegfx::B2DHomMatrix&                 rTransformation ) const;\n\n                const uno::Reference< rendering::XPolyPolygon2D >\tmxPolyPoly;\n                const ::basegfx::B2DRectangle\t\t\t\t\t\tmaBounds;\n                const CanvasSharedPtr\t\t\t\t\t\t\t\tmpCanvas;\n                rendering::RenderState\t\t\t\t\t\t\t\tmaState;\n                const rendering::StrokeAttributes\t\t\t\t\tmaStrokeAttributes;\n            };\n\n            StrokedPolyPolyAction::StrokedPolyPolyAction( const ::basegfx::B2DPolyPolygon&      rPolyPoly, \n                                                          const CanvasSharedPtr&\t\t\t\trCanvas,\n                                                          const OutDevState& \t\t\t\t\trState,\n                                                          const rendering::StrokeAttributes&\trStrokeAttributes ) :\n                CachedPrimitiveBase( rCanvas, false ),\n                mxPolyPoly( ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon( rCanvas->getUNOCanvas()->getDevice(), rPolyPoly) ),\n                maBounds( ::basegfx::tools::getRange(rPolyPoly) ),\n                mpCanvas( rCanvas ),\n                maState(),\n                maStrokeAttributes( rStrokeAttributes )\n            {\n                tools::initRenderState(maState,rState);\n                maState.DeviceColor = rState.lineColor;\n            }\n\n            bool StrokedPolyPolyAction::render( uno::Reference< rendering::XCachedPrimitive >& rCachedPrimitive,\n                                                const ::basegfx::B2DHomMatrix&                 rTransformation ) const\n            {\n                RTL_LOGFILE_CONTEXT( aLog, \"::cppcanvas::internal::PolyPolyAction::render()\" );\n                RTL_LOGFILE_CONTEXT_TRACE1( aLog, \"::cppcanvas::internal::PolyPolyAction: 0x%X\", this );\n\n                rendering::RenderState aLocalState( maState );\n                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);\n\n                rCachedPrimitive = mpCanvas->getUNOCanvas()->strokePolyPolygon( mxPolyPoly, \n                                                                                mpCanvas->getViewState(),\n                                                                                aLocalState,\n                                                                                maStrokeAttributes );\n                return true;\n            }\n\n            bool StrokedPolyPolyAction::render( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                                const Subset&\t\t\t\t\trSubset ) const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n\n                // polygon only contains a single action, fail if subset\n                // requests different range\n                if( rSubset.mnSubsetBegin != 0 ||\n                    rSubset.mnSubsetEnd != 1 )\n                    return false;\n\n                return CachedPrimitiveBase::render( rTransformation );\n            }\n\n            ::basegfx::B2DRange StrokedPolyPolyAction::getBounds( const ::basegfx::B2DHomMatrix&\trTransformation ) const\n            {\n                rendering::RenderState aLocalState( maState );\n                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);\n                \n                return tools::calcDevicePixelBounds( \n                    maBounds,\n                    mpCanvas->getViewState(),\n                    aLocalState );\n            }\n\n            ::basegfx::B2DRange StrokedPolyPolyAction::getBounds( const ::basegfx::B2DHomMatrix&\trTransformation,\n                                                                  const Subset&\t\t\t\t\trSubset ) const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n\n                // polygon only contains a single action, empty bounds\n                // if subset requests different range\n                if( rSubset.mnSubsetBegin != 0 ||\n                    rSubset.mnSubsetEnd != 1 )\n                    return ::basegfx::B2DRange();\n\n                return getBounds( rTransformation );\n            }\n\n            sal_Int32 StrokedPolyPolyAction::getActionCount() const\n            {\n                // TODO(F1): Split up poly-polygon into polygons, or even\n                // line segments, when subsets are requested.\n                return 1;\n            }\n        }\n\n        ActionSharedPtr PolyPolyActionFactory::createPolyPolyAction( const ::basegfx::B2DPolyPolygon& rPoly,  \n                                                                     const CanvasSharedPtr&           rCanvas, \n                                                                     const OutDevState&               rState\t)\n        {\n            OSL_ENSURE( rState.isLineColorSet || rState.isFillColorSet,\n                        \"PolyPolyActionFactory::createPolyPolyAction() with empty line and fill color\" );\n            return ActionSharedPtr( new PolyPolyAction( rPoly, rCanvas, rState, \n                                                        rState.isFillColorSet, \n                                                        rState.isLineColorSet ) );\n        }\n\n        ActionSharedPtr PolyPolyActionFactory::createPolyPolyAction( const ::basegfx::B2DPolyPolygon&   rPoly,  \n                                                                     const CanvasSharedPtr&             rCanvas, \n                                                                     const OutDevState&                 rState,\n                                                                     const rendering::Texture&          rTexture )\n        {\n            return ActionSharedPtr( new TexturedPolyPolyAction( rPoly, rCanvas, rState, rTexture ) );\n        }\n\n        ActionSharedPtr PolyPolyActionFactory::createLinePolyPolyAction( const ::basegfx::B2DPolyPolygon& rPoly,  \n                                                                         const CanvasSharedPtr&           rCanvas, \n                                                                         const OutDevState&               rState )\n        {\n            OSL_ENSURE( rState.isLineColorSet,\n                        \"PolyPolyActionFactory::createLinePolyPolyAction() called with empty line color\" );\n\n            return ActionSharedPtr( new PolyPolyAction( rPoly, rCanvas, rState, \n                                                        false, \n                                                        rState.isLineColorSet ) );\n        }\n        \n        ActionSharedPtr PolyPolyActionFactory::createPolyPolyAction( const ::basegfx::B2DPolyPolygon&   rPoly,\t  \n                                                                     const CanvasSharedPtr&\t\t\t\trCanvas, \n                                                                     const OutDevState&\t\t\t\t\trState,\n                                                                     const rendering::StrokeAttributes& rStrokeAttributes )\n        {\n            OSL_ENSURE( rState.isLineColorSet,\n                        \"PolyPolyActionFactory::createPolyPolyAction() for strokes called with empty line color\" );\n            return ActionSharedPtr( new StrokedPolyPolyAction( rPoly, rCanvas, rState, rStrokeAttributes ) );\n        }\n\n        ActionSharedPtr PolyPolyActionFactory::createPolyPolyAction( const ::basegfx::B2DPolyPolygon& rPoly,  \n                                                                     const CanvasSharedPtr&           rCanvas, \n                                                                     const OutDevState&               rState,\n                                                                     int                              nTransparency \t)\n        {\n            OSL_ENSURE( rState.isLineColorSet || rState.isFillColorSet,\n                        \"PolyPolyActionFactory::createPolyPolyAction() with empty line and fill color\" );\n            return ActionSharedPtr( new PolyPolyAction( rPoly, rCanvas, rState, \n                                                        rState.isFillColorSet, \n                                                        rState.isLineColorSet,\n                                                        nTransparency ) );\n        }\n\n    }\n}\n", "meta": {"hexsha": "1485586a1ce1c239313b6cc3d283d85fa30fdcc7", "size": 26415, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "main/cppcanvas/source/mtfrenderer/polypolyaction.cxx", "max_stars_repo_name": "Grosskopf/openoffice", "max_stars_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 679.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T06:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:06:03.000Z", "max_issues_repo_path": "main/cppcanvas/source/mtfrenderer/polypolyaction.cxx", "max_issues_repo_name": "Grosskopf/openoffice", "max_issues_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 102.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T08:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T12:13:49.000Z", "max_forks_repo_path": "main/cppcanvas/source/mtfrenderer/polypolyaction.cxx", "max_forks_repo_name": "Grosskopf/openoffice", "max_forks_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 331.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T11:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T04:07:51.000Z", "avg_line_length": 49.3738317757, "max_line_length": 132, "alphanum_fraction": 0.4771531327, "num_tokens": 4772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31069437683198786, "lm_q1q2_score": 0.15898747161314133}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <optional>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"DataStructures/DataBox/PrefixHelpers.hpp\"\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"DataStructures/VariablesTag.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Domain/TagsTimeDependent.hpp\"\n#include \"Evolution/BoundaryCorrectionTags.hpp\"\n#include \"Evolution/DgSubcell/Projection.hpp\"\n#include \"Evolution/DgSubcell/Reconstruction.hpp\"\n#include \"Evolution/DgSubcell/ReconstructionMethod.hpp\"\n#include \"Evolution/DgSubcell/SubcellOptions.hpp\"\n#include \"Evolution/DgSubcell/Tags/Mesh.hpp\"\n#include \"Evolution/DgSubcell/Tags/NeighborData.hpp\"\n#include \"Evolution/DgSubcell/Tags/SubcellOptions.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Actions/NormalCovectorAndMagnitude.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Actions/PackageDataImpl.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/BoundaryCorrections/BoundaryCorrection.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/BoundaryCorrections/Factory.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/FiniteDifference/Reconstructor.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/FiniteDifference/Tag.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Subcell/ComputeFluxes.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/System.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Tags.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Parallel/Tags/Metavariables.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"\n#include \"PointwiseFunctions/Hydro/Tags.hpp\"\n#include \"Utilities/CallWithDynamicType.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace NewtonianEuler::subcell {\n/*!\n * \\brief On elements using DG, reconstructs the interface data from a\n * neighboring element doing subcell.\n *\n * The neighbor's packaged data needed by the boundary correction is computed\n * and returned so that it can be used for solving the Riemann problem on the\n * interfaces.\n *\n * Note that for strict conservation the Riemann solve should be done on the\n * subcells, with the correction being projected back to the DG interface.\n * However, in practice such strict conservation doesn't seem to be necessary\n * and can be explained by that we only need strict conservation at shocks, and\n * if one element is doing DG, then we aren't at a shock.\n */\nstruct NeighborPackagedData {\n  template <size_t Dim, typename DbTagsList>\n  static FixedHashMap<maximum_number_of_neighbors(Dim),\n                      std::pair<Direction<Dim>, ElementId<Dim>>,\n                      std::vector<double>,\n                      boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>\n  apply(const db::DataBox<DbTagsList>& box,\n        const std::vector<std::pair<Direction<Dim>, ElementId<Dim>>>&\n            mortars_to_reconstruct_to) {\n    using system =\n        typename std::decay_t<decltype(db::get<Parallel::Tags::Metavariables>(\n            box))>::system;\n    using evolved_vars_tag = typename system::variables_tag;\n    using evolved_vars_tags = typename evolved_vars_tag::tags_list;\n    using prim_tags = typename system::primitive_variables_tag::tags_list;\n    using fluxes_tags = db::wrap_tags_in<::Tags::Flux, evolved_vars_tags,\n                                         tmpl::size_t<Dim>, Frame::Inertial>;\n\n    ASSERT(not db::get<domain::Tags::MeshVelocity<Dim>>(box).has_value(),\n           \"Haven't yet added support for moving mesh to DG-subcell. This \"\n           \"should be easy to generalize, but we will want to consider \"\n           \"storing the mesh velocity on the faces instead of \"\n           \"re-slicing/projecting.\");\n\n    FixedHashMap<maximum_number_of_neighbors(Dim),\n                 std::pair<Direction<Dim>, ElementId<Dim>>, std::vector<double>,\n                 boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>\n        neighbor_package_data{};\n\n    const auto& neighbor_subcell_data = db::get<\n        evolution::dg::subcell::Tags::NeighborDataForReconstruction<Dim>>(box);\n    const Mesh<Dim>& subcell_mesh =\n        db::get<evolution::dg::subcell::Tags::Mesh<Dim>>(box);\n    const Mesh<Dim>& dg_mesh = db::get<domain::Tags::Mesh<Dim>>(box);\n    const auto& subcell_options =\n        db::get<evolution::dg::subcell::Tags::SubcellOptions>(box);\n\n    const auto volume_prims = evolution::dg::subcell::fd::project(\n        db::get<typename system::primitive_variables_tag>(box), dg_mesh,\n        subcell_mesh.extents());\n\n    const auto& recons =\n        db::get<NewtonianEuler::fd::Tags::Reconstructor<Dim>>(box);\n    const auto& boundary_correction =\n        db::get<evolution::Tags::BoundaryCorrection<system>>(box);\n    using derived_boundary_corrections =\n        typename std::decay_t<decltype(boundary_correction)>::creatable_classes;\n    tmpl::for_each<\n        derived_boundary_corrections>([&box, &boundary_correction, &dg_mesh,\n                                       &mortars_to_reconstruct_to,\n                                       &neighbor_package_data,\n                                       &neighbor_subcell_data, &recons,\n                                       &subcell_mesh, &subcell_options,\n                                       &volume_prims](\n                                          auto derived_correction_v) {\n      using DerivedCorrection = tmpl::type_from<decltype(derived_correction_v)>;\n      if (typeid(boundary_correction) == typeid(DerivedCorrection)) {\n        using dg_package_data_temporary_tags =\n            typename DerivedCorrection::dg_package_data_temporary_tags;\n        using dg_package_data_argument_tags =\n            tmpl::append<evolved_vars_tags, prim_tags, fluxes_tags,\n                         dg_package_data_temporary_tags>;\n\n        const auto& element = db::get<domain::Tags::Element<Dim>>(box);\n        const auto& eos = get<hydro::Tags::EquationOfStateBase>(box);\n\n        using dg_package_field_tags =\n            typename DerivedCorrection::dg_package_field_tags;\n        Variables<dg_package_data_argument_tags> vars_on_face;\n        Variables<dg_package_field_tags> packaged_data;\n        for (const auto& mortar_id : mortars_to_reconstruct_to) {\n          const Direction<Dim>& direction = mortar_id.first;\n\n          Index<Dim> extents = subcell_mesh.extents();\n          // Switch to face-centered instead of cell-centered points on the FD.\n          // There are num_cell_centered+1 face-centered points.\n          ++extents[direction.dimension()];\n\n          // Computed prims and cons on face via reconstruction\n          const size_t num_face_pts = subcell_mesh.extents()\n                                          .slice_away(direction.dimension())\n                                          .product();\n          vars_on_face.initialize(num_face_pts);\n\n          call_with_dynamic_type<void,\n                                 typename NewtonianEuler::fd::Reconstructor<\n                                     Dim>::creatable_classes>(\n              &recons, [&element, &eos, &mortar_id, &neighbor_subcell_data,\n                        &subcell_mesh, &vars_on_face,\n                        &volume_prims](const auto& reconstructor) {\n                reconstructor->reconstruct_fd_neighbor(\n                    make_not_null(&vars_on_face), volume_prims, eos, element,\n                    neighbor_subcell_data, subcell_mesh, mortar_id.first);\n              });\n\n          NewtonianEuler::subcell::compute_fluxes<Dim>(\n              make_not_null(&vars_on_face));\n\n          tnsr::i<DataVector, Dim, Frame::Inertial> normal_covector = get<\n              evolution::dg::Tags::NormalCovector<Dim>>(\n              *db::get<evolution::dg::Tags::NormalCovectorAndMagnitude<Dim>>(\n                   box)\n                   .at(mortar_id.first));\n          for (auto& t : normal_covector) {\n            t *= -1.0;\n          }\n          if constexpr (Dim > 1) {\n            const auto dg_normal_covector = normal_covector;\n            for (size_t i = 0; i < Dim; ++i) {\n              normal_covector.get(i) = evolution::dg::subcell::fd::project(\n                  dg_normal_covector.get(i),\n                  dg_mesh.slice_away(mortar_id.first.dimension()),\n                  subcell_mesh.extents().slice_away(\n                      mortar_id.first.dimension()));\n            }\n          }\n\n          // Compute the packaged data\n          packaged_data.initialize(num_face_pts);\n          using dg_package_data_projected_tags = tmpl::append<\n              evolved_vars_tags, fluxes_tags, dg_package_data_temporary_tags,\n              typename DerivedCorrection::dg_package_data_primitive_tags>;\n          evolution::dg::Actions::detail::dg_package_data<system>(\n              make_not_null(&packaged_data),\n              dynamic_cast<const DerivedCorrection&>(boundary_correction),\n              vars_on_face, normal_covector, {std::nullopt}, box,\n              typename DerivedCorrection::dg_package_data_volume_tags{},\n              dg_package_data_projected_tags{});\n\n          if constexpr (Dim == 1) {\n            (void)dg_mesh;\n            (void)subcell_options;\n            neighbor_package_data[mortar_id] = std::vector<double>{\n                packaged_data.data(),\n                packaged_data.data() + packaged_data.size()};\n          } else {\n            // Reconstruct the DG solution.\n            // Really we should be solving the boundary correction and\n            // then reconstructing, but away from a shock this doesn't\n            // matter.\n            auto dg_packaged_data = evolution::dg::subcell::fd::reconstruct(\n                packaged_data, dg_mesh.slice_away(mortar_id.first.dimension()),\n                subcell_mesh.extents().slice_away(mortar_id.first.dimension()),\n                subcell_options.reconstruction_method());\n            neighbor_package_data[mortar_id] = std::vector<double>{\n                dg_packaged_data.data(),\n                dg_packaged_data.data() + dg_packaged_data.size()};\n          }\n        }\n      }\n    });\n\n    return neighbor_package_data;\n  }\n};\n}  // namespace NewtonianEuler::subcell\n", "meta": {"hexsha": "bf647e05efb9fd98ce299fcbf01ad622135ef618", "size": 10606, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/NewtonianEuler/Subcell/NeighborPackagedData.hpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-11T00:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T00:17:33.000Z", "max_issues_repo_path": "src/Evolution/Systems/NewtonianEuler/Subcell/NeighborPackagedData.hpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "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/Evolution/Systems/NewtonianEuler/Subcell/NeighborPackagedData.hpp", "max_forks_repo_name": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["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.3482142857, "max_line_length": 86, "alphanum_fraction": 0.6598151989, "num_tokens": 2326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1589874716131413}}
{"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#ifndef QCTOOL_CROSS_DATA_SET_HAPLOTYPE_COMPARISON_COMPUTATION_HPP\n#define QCTOOL_CROSS_DATA_SET_HAPLOTYPE_COMPARISON_COMPUTATION_HPP\n\n#include <deque>\n#include <vector>\n#include <Eigen/Core>\n#include \"genfile/CohortIndividualSource.hpp\"\n#include \"genfile/SNPDataSource.hpp\"\n#include \"components/SNPSummaryComponent/SNPSummaryComputation.hpp\"\n#include \"components/SNPSummaryComponent/CrossDataSetConcordanceComputation.hpp\"\n\nnamespace snp_stats {\n\tstruct CrossDataSetHaplotypeComparisonComputation: public CrossDataSetComparison\n\t{\n\tpublic:\n\t\tCrossDataSetHaplotypeComparisonComputation(\n\t\t\tgenfile::CohortIndividualSource const& m_samples,\n\t\t\tstd::string const& main_dataset_sample_id_column\n\t\t) ;\n\n\t\tvoid set_alternate_dataset(\n\t\t\tgenfile::CohortIndividualSource::UniquePtr samples,\n\t\t\tstd::string const& comparison_dataset_sample_id_column,\n\t\t\tgenfile::SNPDataSource::UniquePtr snps\n\t\t) ;\n\t\n\t\tvoid set_comparer( genfile::VariantIdentifyingData::CompareFields const& comparer ) ;\n\t\tvoid set_match_alleles() ;\n\t\n\t\tvoid operator()( VariantIdentifyingData const&, Genotypes const&, Ploidy const&, genfile::VariantDataReader&, ResultCallback ) ;\n\t\tstd::string get_summary( std::string const& prefix = \"\", std::size_t column_width = 20 ) const ;\n\n\tprivate:\n\t\tCrossDataSetSampleMapper m_sample_mapper ;\n\n\t\tgenfile::VariantIdentifyingData::CompareFields m_comparer ;\n\t\tbool m_match_alleles ;\n\t\tgenfile::SNPDataSource::UniquePtr m_alt_dataset_snps ;\n\n\t\tdouble const m_call_threshhold ;\n\t\tEigen::MatrixXd m_haplotypes1 ;\n\t\tEigen::MatrixXd m_haplotypes2 ;\n\t\tEigen::MatrixXd m_nonmissingness1 ;\n\t\tEigen::MatrixXd m_nonmissingness2 ;\n\t\n\t\tEigen::VectorXd m_relative_phase ;\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "9c0841e61d0b6725de246f607d59dfa9c64fad14", "size": 1893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/include/components/SNPSummaryComponent/CrossDataSetHaplotypeComparisonComputation.hpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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": "components/SNPSummaryComponent/include/components/SNPSummaryComponent/CrossDataSetHaplotypeComparisonComputation.hpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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": "components/SNPSummaryComponent/include/components/SNPSummaryComponent/CrossDataSetHaplotypeComparisonComputation.hpp", "max_forks_repo_name": "CreRecombinase/qctool", "max_forks_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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.2105263158, "max_line_length": 130, "alphanum_fraction": 0.7897517169, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.15858811641395268}}
{"text": "// Copyright (c) 2015-2019 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 \"error_rate.hpp\"\n\n#include <numeric>\n#include <algorithm>\n#include <iterator>\n#include <map>\n#include <cstddef>\n\n#include <boost/variant.hpp>\n\n#include \"basics/cigar_string.hpp\"\n#include \"basics/aligned_read.hpp\"\n#include \"core/types/haplotype.hpp\"\n#include \"io/variant/vcf_record.hpp\"\n#include \"../facets/samples.hpp\"\n#include \"../facets/read_assignments.hpp\"\n\nnamespace octopus { namespace csr {\n\nconst std::string ErrorRate::name_ = \"ER\";\n\nstd::unique_ptr<Measure> ErrorRate::do_clone() const\n{\n    return std::make_unique<ErrorRate>(*this);\n}\n\nMeasure::ResultType ErrorRate::get_default_result() const\n{\n    return std::vector<boost::optional<double>> {};\n}\n\nnamespace {\n\nboost::optional<double> \ncompute_error_rate(const Facet::SupportMaps::HaplotypeSupportMaps& assignments, const GenomicRegion& region) noexcept\n{\n    std::size_t error_bases {0}, total_bases {0};\n    for (const auto& p : assignments.assigned_wrt_haplotype) {\n        for (const auto& read : overlap_range(p.second, region)) {\n            error_bases += sum_non_matches(read.cigar());\n            total_bases += sequence_size(read);\n        }\n    }\n    for (const auto& read : overlap_range(assignments.ambiguous_wrt_haplotype, region)) {\n        error_bases += sum_non_matches(read.read.cigar());\n        total_bases += sequence_size(read.read);\n    }\n    if (total_bases > 0) {\n        return static_cast<double>(error_bases) / total_bases;\n    } else {\n        return boost::none;\n    }\n}\n\n} // namespace\n\nMeasure::ResultType ErrorRate::do_evaluate(const VcfRecord& call, const FacetMap& facets) const\n{\n    const auto& samples = get_value<Samples>(facets.at(\"Samples\"));\n    const auto& assignments = get_value<ReadAssignments>(facets.at(\"ReadAssignments\")).haplotypes;\n    std::vector<boost::optional<double>> result {};\n    result.reserve(samples.size());\n    for (const auto& sample : samples) {\n        result.push_back(compute_error_rate(assignments.at(sample), mapped_region(call)));\n    }\n    return result;\n}\n\nMeasure::ResultCardinality ErrorRate::do_cardinality() const noexcept\n{\n    return ResultCardinality::samples;\n}\n\nconst std::string& ErrorRate::do_name() const\n{\n    return name_;\n}\n\nstd::string ErrorRate::do_describe() const\n{\n    return \"Error rate in reads overlapping the site\";\n}\n\nstd::vector<std::string> ErrorRate::do_requirements() const\n{\n    return {\"Samples\", \"ReadAssignments\"};\n}\n    \n} // namespace csr\n} // namespace octopus\n", "meta": {"hexsha": "0663f4c59301a55f6d74372907a8b1fbe1081504", "size": 2583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/csr/measures/error_rate.cpp", "max_stars_repo_name": "gunjanbaid/octopus", "max_stars_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "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/csr/measures/error_rate.cpp", "max_issues_repo_name": "gunjanbaid/octopus", "max_issues_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_issues_repo_licenses": ["MIT"], "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/csr/measures/error_rate.cpp", "max_forks_repo_name": "gunjanbaid/octopus", "max_forks_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_forks_repo_licenses": ["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.4787234043, "max_line_length": 117, "alphanum_fraction": 0.7042198993, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.15858811310907062}}
{"text": "/// @file\n///\n/// @copyright (c) 2008 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// 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, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Matthew Whiting <matthew.whiting@csiro.au>\n///\n\n#include <askap_analysis.h>\n\n#include <askap/AskapLogging.h>\n#include <askap/AskapError.h>\n\n#include <sourcefitting/RadioSource.h>\n#include <sourcefitting/Fitter.h>\n#include <sourcefitting/FittingParameters.h>\n#include <sourcefitting/FitResults.h>\n#include <sourcefitting/SubComponent.h>\n#include <sourcefitting/SubThresholder.h>\n#include <analysisparallel/SubimageDef.h>\n#include <casainterface/CasaInterface.h>\n#include <mathsutils/MathsUtils.h>\n#include <outputs/CataloguePreparation.h>\n\n#include <duchamp/fitsHeader.hh>\n#include <duchamp/PixelMap/Voxel.hh>\n#include <duchamp/PixelMap/Object2D.hh>\n#include <duchamp/PixelMap/Object3D.hh>\n#include <duchamp/Cubes/cubes.hh>\n#include <duchamp/Detection/detection.hh>\n#include <duchamp/Outputs/columns.hh>\n#include <duchamp/Outputs/CatalogueSpecification.hh>\n#include <duchamp/Outputs/AnnotationWriter.hh>\n#include <duchamp/Outputs/KarmaAnnotationWriter.hh>\n#include <duchamp/Utils/Section.hh>\n#include <duchamp/Utils/utils.hh>\n#include <duchamp/Detection/finders.hh>\n\n#include <casacore/scimath/Fitting/FitGaussian.h>\n#include <casacore/scimath/Functionals/Gaussian1D.h>\n#include <casacore/scimath/Functionals/Gaussian2D.h>\n#include <casacore/scimath/Functionals/Gaussian3D.h>\n#include <casacore/casa/namespace.h>\n#include <casacore/casa/Arrays/IPosition.h>\n#include <casacore/casa/Arrays/MaskedArray.h>\n#include <casacore/casa/Arrays/Slicer.h>\n#include <casacore/casa/Arrays/ArrayMath.h>\n#include <casacore/casa/Quanta/Quantum.h>\n#include <boost/scoped_ptr.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <Common/LofarTypedefs.h>\nusing namespace LOFAR::TYPES;\n#include <Blob/BlobString.h>\n#include <Blob/BlobIBufString.h>\n#include <Blob/BlobOBufString.h>\n#include <Blob/BlobIStream.h>\n#include <Blob/BlobOStream.h>\n#include <Common/Exceptions.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <string>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <utility>\n#include <math.h>\n\n///@brief Where the log messages go.\nASKAP_LOGGER(logger, \".radioSource\");\n\nusing namespace duchamp;\nusing namespace askap::analysisutilities;\n\nnamespace askap {\n\nnamespace analysis {\n\nnamespace sourcefitting {\n\nRadioSource::RadioSource():\n    duchamp::Detection()\n{\n    itsFlagHasFit = false;\n    itsFlagAtEdge = false;\n    itsHeader = duchamp::FitsHeader();\n    itsFitParams = FittingParameters();\n    itsNoiseLevel = itsFitParams.noiseLevel();\n\n    initialiseAlphaBetaMaps();\n}\n\n//**************************************************************//\n\nRadioSource::RadioSource(duchamp::Detection obj):\n    duchamp::Detection(obj)\n{\n    itsFlagHasFit = false;\n    itsFlagAtEdge = false;\n    itsHeader = duchamp::FitsHeader();\n    itsFitParams = FittingParameters();\n    itsNoiseLevel = itsFitParams.noiseLevel();\n\n    initialiseAlphaBetaMaps();\n\n}\n\n//**************************************************************//\n\nRadioSource::RadioSource(const RadioSource& src):\n    duchamp::Detection(src)\n{\n    operator=(src);\n}\n\n//**************************************************************//\n\nRadioSource& RadioSource::operator= (const duchamp::Detection& det)\n{\n    ((duchamp::Detection &) *this) = det;\n    itsFlagHasFit = false;\n    itsFlagAtEdge = false;\n    itsFitParams = FittingParameters();\n    itsHeader = duchamp::FitsHeader();\n    itsNoiseLevel = itsFitParams.noiseLevel();\n\n    initialiseAlphaBetaMaps();\n\n    return *this;\n}\n\n//**************************************************************//\n\nRadioSource& RadioSource::operator= (const RadioSource& src)\n{\n    ((duchamp::Detection &) *this) = src;\n    itsFlagAtEdge = src.itsFlagAtEdge;\n    itsFlagHasFit = src.itsFlagHasFit;\n    itsNoiseLevel = src.itsNoiseLevel;\n    itsDetectionThreshold = src.itsDetectionThreshold;\n    itsHeader = src.itsHeader;\n    itsBox = src.itsBox;\n    itsFitParams = src.itsFitParams;\n    itsBestFitMap = src.itsBestFitMap;\n    itsBestFitType = src.itsBestFitType;\n    itsAlphaMap = src.itsAlphaMap;\n    itsBetaMap = src.itsBetaMap;\n    itsAlphaError = src.itsAlphaError;\n    itsBetaError = src.itsBetaError;\n    return *this;\n}\n\n//**************************************************************//\n\nvoid RadioSource::initialiseAlphaBetaMaps()\n{\n\n    std::vector<std::string>::iterator type;\n    std::vector<std::string> typelist = availableFitTypes;\n\n    for (type = typelist.begin(); type < typelist.end(); type++) {\n        itsAlphaMap[*type] = std::vector<double>(1, defaultAlpha);\n        itsAlphaError[*type] = std::vector<double>(1, 0.);\n        itsBetaMap[*type] = std::vector<double>(1, defaultBeta);\n        itsBetaError[*type] = std::vector<double>(1, 0.);\n    }\n\n    itsAlphaMap[\"best\"] = std::vector<double>(1, defaultAlpha);\n    itsAlphaError[\"best\"] = std::vector<double>(1, 0.);\n    itsBetaMap[\"best\"] = std::vector<double>(1, defaultBeta);\n    itsBetaError[\"best\"] = std::vector<double>(1, 0.);\n\n}\n\n//**************************************************************//\n\nvoid RadioSource::addOffsets(long xoff, long yoff, long zoff)\n{\n    this->Detection::addOffsets(xoff, yoff, zoff);\n\n    std::map<std::string, FitResults>::iterator fit;\n    for (fit = itsBestFitMap.begin(); fit != itsBestFitMap.end(); fit++) {\n        std::vector<casa::Gaussian2D<Double> >::iterator gauss;\n        for (gauss = fit->second.fits().begin();\n                gauss != fit->second.fits().end();\n                gauss++) {\n            gauss->setXcenter(gauss->xCenter() + xoff);\n            gauss->setYcenter(gauss->yCenter() + yoff);\n        }\n    }\n\n}\n\n//**************************************************************//\n\nvoid RadioSource::defineBox(duchamp::Section &sec,\n                            int spectralAxis)\n{\n\n    int ndim = (spectralAxis >= 0) ? 3 : 2;\n    casa::IPosition start(ndim, 0), end(ndim, 0), stride(ndim, 1);\n    start(0) = std::max(long(sec.getStart(0) - this->xSubOffset),\n                        this->getXmin() - itsFitParams.boxPadSize());\n    end(0)   = std::min(long(sec.getEnd(0) - this->xSubOffset),\n                        this->getXmax() + itsFitParams.boxPadSize());\n    start(1) = std::max(long(sec.getStart(1) - this->ySubOffset),\n                        this->getYmin() - itsFitParams.boxPadSize());\n    end(1)   = std::min(long(sec.getEnd(1) - this->ySubOffset),\n                        this->getYmax() + itsFitParams.boxPadSize());\n    if (spectralAxis >= 0) {\n        start(2) = std::max(long(sec.getStart(spectralAxis) - this->zSubOffset),\n                            this->getZmin() - itsFitParams.boxPadSize());\n        end(2)   = std::min(long(sec.getEnd(spectralAxis) - this->zSubOffset),\n                            this->getZmax() + itsFitParams.boxPadSize());\n    }\n\n    if (start >= end) {\n        ASKAPLOG_DEBUG_STR(logger,\n                           \"RadioSource::defineBox failing : sec=\" << sec.getSection() <<\n                           \", offsets: \" << this->xSubOffset << \" \" << this->ySubOffset <<\n                           \" \" << this->zSubOffset <<\n                           \", mins: \" << this->getXmin() << \" \" << this->getYmin() <<\n                           \" \" << this->getZmin() <<\n                           \", maxs: \" << this->getXmax() << \" \" << this->getYmax() <<\n                           \" \" << this->getZmax() <<\n                           \", boxpadsize: \" << itsFitParams.boxPadSize());\n        ASKAPTHROW(AskapError,\n                   \"RadioSource::defineBox bad slicer: end(\" <<\n                   end << \") < start (\" << start << \")\");\n    }\n    itsBox = casa::Slicer(start, end, stride, Slicer::endIsLast);\n}\n\n//**************************************************************//\n\nstd::string RadioSource::boundingSubsection(std::vector<size_t> dim,\n        bool fullSpectralRange)\n{\n\n    const int lng = itsHeader.getWCS()->lng;\n    const int lat = itsHeader.getWCS()->lat;\n    const int spec = itsHeader.getWCS()->spec;\n    std::vector<std::string> sectionlist(dim.size(), \"1:1\");\n    long first, last;\n    for (int ax = 0; ax < int(dim.size()); ax++) {\n        std::stringstream ss;\n        if (ax == spec) {\n            if (fullSpectralRange) {\n                first = 1;\n                last = dim[ax];\n            } else {\n                first = std::max(1L, this->zmin - itsFitParams.boxPadSize() + 1);\n                last = std::min(long(dim[ax]), this->zmax + itsFitParams.boxPadSize() + 1);\n            }\n        } else if (ax == lng) {\n            first = this->xmin - itsFitParams.boxPadSize() + 1;\n            last = this->xmax + itsFitParams.boxPadSize() + 1;\n            if (itsFitParams.useNoise()) {\n                first = std::min(first, this->xpeak - itsFitParams.noiseBoxSize() / 2 + 1);\n                last = std::max(last, this->xpeak + itsFitParams.noiseBoxSize() / 2 + 1);\n            }\n            first = std::max(first, 1L);\n            last = std::min(last, long(dim[ax]));\n\n        } else if (ax == lat) {\n            first = this->ymin - itsFitParams.boxPadSize() + 1;\n            last = this->ymax + itsFitParams.boxPadSize() + 1;\n            if (itsFitParams.useNoise()) {\n                first = std::min(first, this->ypeak - itsFitParams.noiseBoxSize() / 2 + 1);\n                last = std::max(last, this->ypeak + itsFitParams.noiseBoxSize() / 2 + 1);\n            }\n            first = std::max(first, 1L);\n            last = std::min(last, long(dim[ax]));\n\n        } else {\n            first = last = 1;\n        }\n        ss << first << \":\" << last;\n        sectionlist[ax] = ss.str();\n    }\n    std::stringstream secstr;\n    secstr << \"[ \" << sectionlist[0];\n    for (size_t i = 1; i < dim.size(); i++) {\n        secstr << \",\" << sectionlist[i];\n    }\n    secstr << \"]\";\n\n    return secstr.str();\n}\n\n\n//**************************************************************//\n\nvoid RadioSource::setAtEdge(duchamp::Cube &cube,\n                            analysisutilities::SubimageDef &subimage,\n                            int workerNum)\n{\n    bool flagBoundary = false;\n    bool flagAdj = cube.pars().getFlagAdjacent();\n    float threshS = cube.pars().getThreshS();\n    float threshV = cube.pars().getThreshV();\n\n    long xminEdge, xmaxEdge, yminEdge, ymaxEdge, zminEdge, zmaxEdge;\n\n    if (workerNum < 0) {  // if it is the Master node\n        xminEdge = yminEdge = zminEdge = 0;\n        xmaxEdge = cube.getDimX() - 1;\n        ymaxEdge = cube.getDimY() - 1;\n        zmaxEdge = cube.getDimZ() - 1;\n    } else {\n        std::vector<unsigned int> nsub = subimage.nsub();\n        std::vector<unsigned int> overlap = subimage.overlap();\n        unsigned int colnum = workerNum % nsub[0];\n        unsigned int rownum = workerNum / nsub[0];\n        unsigned int znum = workerNum / (nsub[0] * nsub[1]);\n        xminEdge = (colnum == 0) ? 0 : overlap[0];\n        xmaxEdge = (colnum == nsub[0] - 1) ?\n                   cube.getDimX() - 1 : cube.getDimX() - 1 - overlap[0];\n        yminEdge = (rownum == 0) ? 0 : overlap[1];\n        ymaxEdge = (rownum == nsub[1] - 1) ?\n                   cube.getDimY() - 1 : cube.getDimY() - 1 - overlap[1];\n        zminEdge = (znum == 0) ? 0 : overlap[2];\n        zmaxEdge = (znum == nsub[2] - 1) ?\n                   cube.getDimZ() - 1 : cube.getDimZ() - 1 - overlap[2];\n    }\n\n\n    if (flagAdj) {\n        flagBoundary = flagBoundary || (this->getXmin() <= xminEdge);\n        flagBoundary = flagBoundary || (this->getXmax() >= xmaxEdge);\n        flagBoundary = flagBoundary || (this->getYmin() <= yminEdge);\n        flagBoundary = flagBoundary || (this->getYmax() >= ymaxEdge);\n\n        if (cube.getDimZ() > 1) {\n            flagBoundary = flagBoundary || (this->getZmin() <= zminEdge);\n            flagBoundary = flagBoundary || (this->getZmax() >= zmaxEdge);\n        }\n    } else {\n        flagBoundary = flagBoundary || ((this->getXmin() - xminEdge) < threshS);\n        flagBoundary = flagBoundary || ((xmaxEdge - this->getXmax()) < threshS);\n        flagBoundary = flagBoundary || ((this->getYmin() - yminEdge) < threshS);\n        flagBoundary = flagBoundary || ((ymaxEdge - this->getYmax()) < threshS);\n\n        if (cube.getDimZ() > 1) {\n            flagBoundary = flagBoundary || ((this->getZmin() - zminEdge) < threshV);\n            flagBoundary = flagBoundary || ((zmaxEdge - this->getZmax()) < threshV);\n        }\n    }\n\n    itsFlagAtEdge = flagBoundary;\n}\n//**************************************************************//\n\nvoid RadioSource::setNoiseLevel(duchamp::Cube &cube)\n{\n    if (itsFitParams.useNoise() || !itsFitParams.doFit()) {\n        std::vector<float> array(cube.getArray(),\n                                 cube.getArray() + cube.getSize());\n        std::vector<size_t> dim(cube.getDimArray(),\n                                cube.getDimArray() + cube.getNumDim());\n        this->setNoiseLevel(array, dim, itsFitParams.noiseBoxSize());\n    } else {\n        itsNoiseLevel = itsFitParams.noiseLevel();\n    }\n}\n\n//**************************************************************//\n\nvoid RadioSource::setNoiseLevel(std::vector<float> &array,\n                                std::vector<size_t> &dim,\n                                unsigned int boxSize)\n{\n    if (boxSize % 2 == 0) boxSize += 1;\n    int hw = boxSize / 2;\n    std::vector<float> localArray;\n    long xmin = max(0, this->xpeak - hw);\n    long ymin = max(0, this->ypeak - hw);\n    int xsize = dim[0];\n    int ysize = dim[1];\n    long xmax = min(xsize - 1, this->xpeak + hw);\n    long ymax = min(ysize - 1, this->ypeak + hw);\n\n    unsigned int npix = (xmax - xmin + 1) * (ymax - ymin + 1);\n    ASKAPASSERT(npix <= boxSize * boxSize);\n\n    for (int x = xmin; x <= xmax; x++) {\n        for (int y = ymin; y <= ymax; y++) {\n            int pos = x + y * xsize;\n            localArray.push_back(array[pos]);\n        }\n    }\n\n    itsNoiseLevel = analysisutilities::findSpread(true, localArray);\n\n}\n\n\n//**************************************************************//\n\nvoid RadioSource::setDetectionThreshold(duchamp::Cube &cube,\n                                        bool flagVariableThreshold)\n{\n\n    if (flagVariableThreshold) {\n\n        // Use the fact that the SNR array has been stored in the\n        // Cube's recon array. So just need the max value from that\n        // array to get peakSNR, and the minimum flux value of all\n        // detected pixels to get the detection threshold.\n        \n        std::vector<PixelInfo::Voxel> voxSet = this->getPixelSet();\n\n        std::vector<PixelInfo::Voxel>::iterator vox = voxSet.begin();\n        itsDetectionThreshold = cube.getPixValue(vox->getX(), vox->getY(), vox->getZ());\n\n        for (; vox < voxSet.end(); vox++) {\n            float pixval = cube.getPixValue(vox->getX(), vox->getY(), vox->getZ());\n            itsDetectionThreshold = std::min(itsDetectionThreshold, pixval);\n        }\n\n    } else {\n\n        itsDetectionThreshold = cube.stats().getThreshold();\n\n        if (cube.pars().getFlagGrowth()) {\n            float growth;\n            if (cube.pars().getFlagUserGrowthThreshold()) {\n                growth = cube.pars().getGrowthThreshold();\n                itsDetectionThreshold = std::min(itsDetectionThreshold, growth);\n            } else {\n                growth = cube.stats().snrToValue(cube.pars().getGrowthCut());\n                itsDetectionThreshold = std::min(itsDetectionThreshold, growth);\n            }\n        }\n\n    }\n\n}\n\n//**************************************************************//\n\nvoid RadioSource::setDetectionThreshold(std::vector<PixelInfo::Voxel> &inVoxlist,\n                                        std::vector<PixelInfo::Voxel> &inSNRvoxlist,\n                                        bool flagMedianSearch)\n{\n\n    if (flagMedianSearch) {\n        std::vector<PixelInfo::Voxel> voxSet = this->getPixelSet();\n        std::vector<PixelInfo::Voxel>::iterator vox = voxSet.begin();\n        this->peakSNR = 0.;\n\n        for (; vox < voxSet.end(); vox++) {\n            std::vector<PixelInfo::Voxel>::iterator pixvox = inVoxlist.begin();\n\n            while (pixvox < inVoxlist.end() && !vox->match(*pixvox)) {\n                pixvox++;\n            }\n\n            if (pixvox == inVoxlist.end()) {\n                ASKAPLOG_ERROR_STR(logger,\n                                   \"Missing a voxel in the pixel list comparison: (\" <<\n                                   vox->getX() << \",\" << vox->getY() << \")\");\n            }\n\n            float flux = pixvox->getF();\n            if (vox == voxSet.begin()) {\n                itsDetectionThreshold = flux;\n            } else {\n                itsDetectionThreshold = std::min(itsDetectionThreshold, flux);\n            }\n\n            std::vector<PixelInfo::Voxel>::iterator snrvox = inSNRvoxlist.begin();\n\n            while (snrvox < inSNRvoxlist.end() && !vox->match(*snrvox)) {\n                snrvox++;\n            }\n\n            if (snrvox == inSNRvoxlist.end()) {\n                ASKAPLOG_ERROR_STR(logger,\n                                   \"Missing a voxel in the SNR list comparison: (\" <<\n                                   vox->getX() << \",\" << vox->getY() << \")\");\n            }\n\n            flux = snrvox->getF();\n            if (vox == voxSet.begin()) {\n                this->peakSNR = flux;\n            } else {\n                this->peakSNR = std::max(this->peakSNR, flux);\n            }\n        }\n\n    }\n\n}\n//**************************************************************//\n\nvoid RadioSource::getFWHMestimate(std::vector<float> fluxarray,\n                                  double & angle,\n                                  double & maj,\n                                  double & min)\n{\n\n    size_t dim[2];\n    dim[0] = this->boxXsize();\n    dim[1] = this->boxYsize();\n    boost::scoped_ptr<duchamp::Image> smlIm(new duchamp::Image(dim));\n    smlIm->saveArray(fluxarray.data(), this->boxSize());\n    smlIm->setMinSize(1);\n    float thresh = (itsDetectionThreshold + this->peakFlux) / 2.;\n    smlIm->stats().setThreshold(thresh);\n    std::vector<PixelInfo::Object2D> objlist = smlIm->findSources2D();\n    std::vector<PixelInfo::Object2D>::iterator o;\n\n    for (o = objlist.begin(); o < objlist.end(); o++) {\n        duchamp::Detection tempobj;\n        tempobj.addChannel(0, *o);\n        tempobj.calcFluxes(fluxarray.data(), dim); // we need to know where the peak is.\n\n        if ((tempobj.getXPeak() + this->boxXmin()) == this->getXPeak()  &&\n                (tempobj.getYPeak() + this->boxYmin()) == this->getYPeak()) {\n            // measure parameters only for source at peak\n            angle = o->getPositionAngle();\n            std::pair<double, double> axes = o->getPrincipalAxes();\n            maj = std::max(axes.first, axes.second);\n            min = std::min(axes.first, axes.second);\n        }\n\n    }\n\n}\n\n//**************************************************************//\n\nstd::vector<SubComponent>\nRadioSource::getSubComponentList(casa::Matrix<casa::Double> pos,\n                                 casa::Vector<casa::Double> &f)\n{\n    std::vector<SubComponent> cmpntlist;\n    if (itsFitParams.useCurvature()) {\n\n        // 1. get array of curvature from curvature map\n        // 2. define bool array of correct size\n        // 3. value of this is = (isInObject) && (curvature < -sigmaCurv)\n        // 4. run lutz_detect to get list of objects\n        // 5. for each object, define a subcomponent of zero size with correct peak & position\n\n        casa::IPosition globalOffset(itsBox.start().size(), 0);\n        globalOffset[0] = this->xSubOffset;\n        globalOffset[1] = this->ySubOffset;\n\n        casa::Slicer fullImageBox(itsBox.start() + globalOffset,\n                                  itsBox.length(), Slicer::endIsLength);\n\n\n        // casa::Array<float> curvArray =\n        //     analysisutilities::getPixelsInBox(itsFitParams.curvatureImage(),\n        //                                       fullImageBox, false);\n        casa::MaskedArray<float> curvArray =\n            analysisutilities::getPixelsInBox(itsFitParams.curvatureImage(),\n                                              fullImageBox, false);\n\n        PixelInfo::Object2D spatMap = this->getSpatialMap();\n        size_t dim[2];\n        dim[0] = fullImageBox.length()[0];\n        dim[1] = fullImageBox.length()[1];\n\n        std::vector<float> fluxArray(fullImageBox.length().product(), 0.);\n        std::vector<bool> summitMap(fullImageBox.length().product(), false);\n\n        for (size_t i = 0; i < f.size(); i++) {\n            int x = int(pos(i, 0));\n            int y = int(pos(i, 1));\n            if (spatMap.isInObject(x, y)) {\n                int loc = (x - this->boxXmin()) + this->boxXsize() * (y - this->boxYmin());\n                fluxArray[loc] = float(f(i));\n                summitMap[loc] = (curvArray.getArray().data()[loc] < -1.*itsFitParams.sigmaCurv());\n            }\n        }\n\n        std::vector<Object2D> summitList = duchamp::lutz_detect(summitMap,\n                                           this->boxXsize(),\n                                           this->boxYsize(),\n                                           1);\n        ASKAPLOG_DEBUG_STR(logger, \"Found \" << summitList.size() << \" summits\");\n\n        duchamp::Param par;\n        par.setXOffset(fullImageBox.start()[0]);\n        par.setYOffset(fullImageBox.start()[1]);\n        for (std::vector<Object2D>::iterator obj = summitList.begin();\n                obj < summitList.end();\n                obj++) {\n            duchamp::Detection det;\n            det.addChannel(0, *obj);\n            det.calcFluxes(fluxArray.data(), dim);\n            det.setOffsets(par);\n            det.addOffsets();\n            SubComponent cmpnt;\n            cmpnt.setPeak(det.getPeakFlux());\n            // Need to correct the positions to put them in the current worker frame\n            cmpnt.setX(det.getXPeak() - globalOffset[0]);\n            cmpnt.setY(det.getYPeak() - globalOffset[1]);\n            cmpnt.setPA(0.);\n            cmpnt.setMajor(0.);\n            cmpnt.setMinor(0.);\n            cmpntlist.push_back(cmpnt);\n            ASKAPLOG_DEBUG_STR(logger, \"Found subcomponent \" << cmpnt);\n        }\n\n    } else {\n        SubThresholder subThresh;\n        subThresh.define(*this, pos, f);\n        cmpntlist = subThresh.find();\n    }\n\n    return cmpntlist;\n}\n\n//**************************************************************//\n\nstd::vector<SubComponent>\nRadioSource::getThresholdedSubComponentList(std::vector<float> fluxarray)\n{\n\n    std::vector<SubComponent> fullList;\n    size_t dim[2];\n    dim[0] = this->boxXsize();\n    dim[1] = this->boxYsize();\n    boost::scoped_ptr<duchamp::Image> smlIm(new duchamp::Image(dim));\n    smlIm->saveArray(fluxarray.data(), this->boxSize());\n    smlIm->setMinSize(1);\n    SubComponent base;\n    base.setPeak(this->peakFlux);\n    base.setX(this->xpeak);\n    base.setY(this->ypeak);\n    double a = 0., b = 0., c = 0.;\n\n    if (this->getSize() < 3) {\n        base.setPA(0);\n        base.setMajor(1.);\n        base.setMinor(1.);\n        fullList.push_back(base);\n        return fullList;\n    }\n\n    this->getFWHMestimate(fluxarray, a, b, c);\n    base.setPA(a);\n    base.setMajor(b);\n    base.setMinor(c);\n    const int numThresh = itsFitParams.numSubThresholds();\n    float baseThresh = itsDetectionThreshold > 0 ?\n                       log10(itsDetectionThreshold) : -6.;\n    float threshIncrement = (log10(this->peakFlux) - baseThresh) / float(numThresh + 1);\n    float thresh;\n    int threshCtr = 0;\n    std::vector<PixelInfo::Object2D> objlist;\n    std::vector<PixelInfo::Object2D>::iterator obj;\n    bool keepGoing;\n\n    do {\n        threshCtr++;\n        thresh = pow(10., baseThresh + threshCtr * threshIncrement);\n        smlIm->stats().setThreshold(thresh);\n        objlist = smlIm->findSources2D();\n        keepGoing = (objlist.size() == 1);\n    } while (keepGoing && (threshCtr < numThresh));\n\n    if (!keepGoing) {\n        for (obj = objlist.begin(); obj < objlist.end(); obj++) {\n            RadioSource newsrc;\n            newsrc.setFitParams(itsFitParams);\n            newsrc.setDetectionThreshold(thresh);\n            newsrc.addChannel(0, *obj);\n            newsrc.calcFluxes(fluxarray.data(), dim);\n            newsrc.setBox(this->box());\n            newsrc.addOffsets(this->boxXmin(), this->boxYmin(), 0);\n            newsrc.xpeak += this->boxXmin();\n            newsrc.ypeak += this->boxYmin();\n            // now change the flux array so that we only see the current object\n            std::vector<float> newfluxarray(this->boxSize(), 0.);\n\n            for (size_t i = 0; i < this->boxSize(); i++) {\n                size_t xbox = i % this->boxXsize();\n                size_t ybox = i / this->boxXsize();\n                PixelInfo::Object2D spatMap = newsrc.getSpatialMap();\n\n                if (spatMap.isInObject(xbox + this->boxXmin(), ybox + this->boxYmin())) {\n                    newfluxarray[i] = fluxarray[i];\n                }\n            }\n\n            std::vector<SubComponent>\n            newlist = newsrc.getThresholdedSubComponentList(newfluxarray);\n\n            for (uInt i = 0; i < newlist.size(); i++) {\n                fullList.push_back(newlist[i]);\n            }\n        }\n    } else {\n        fullList.push_back(base);\n    }\n\n    if (fullList.size() > 1) {\n        std::sort(fullList.begin(), fullList.end());\n        std::reverse(fullList.begin(), fullList.end());\n    }\n\n    return fullList;\n}\n\n\n//**************************************************************//\n\nstd::multimap<int, PixelInfo::Voxel>\nRadioSource::findDistinctPeaks(casa::Vector<casa::Double> f)\n{\n\n    const int numThresh = itsFitParams.numSubThresholds();\n    std::multimap<int, PixelInfo::Voxel> peakMap;\n    std::multimap<int, PixelInfo::Voxel>::iterator pk;\n    size_t dim[2];\n    dim[0] = this->boxXsize();\n    dim[1] = this->boxYsize();\n    duchamp::Image smlIm(dim);\n    std::vector<float> fluxarray(this->boxSize());\n\n    for (size_t i = 0; i < this->boxSize(); i++) {\n        fluxarray[i] = f(i);\n    }\n\n    smlIm.saveArray(fluxarray.data(), this->boxSize());\n    smlIm.setMinSize(1);\n    float baseThresh = log10(itsDetectionThreshold);\n    float threshIncrement = (log10(this->peakFlux) - baseThresh) / float(numThresh);\n    PixelInfo::Object2D spatMap = this->getSpatialMap();\n\n    for (int i = 1; i <= numThresh; i++) {\n        float thresh = pow(10., baseThresh + i * threshIncrement);\n        smlIm.stats().setThreshold(thresh);\n        std::vector<PixelInfo::Object2D> objlist = smlIm.findSources2D();\n        std::vector<PixelInfo::Object2D>::iterator o;\n\n        for (o = objlist.begin(); o < objlist.end(); o++) {\n            duchamp::Detection tempobj;\n            tempobj.addChannel(0, *o);\n            tempobj.calcFluxes(fluxarray.data(), dim);\n            bool pkInObj = spatMap.isInObject(tempobj.getXPeak() + this->boxXmin(),\n                                              tempobj.getYPeak() + this->boxYmin());\n\n            if (pkInObj) {\n                PixelInfo::Voxel peakLoc(tempobj.getXPeak() + this->boxXmin(),\n                                         tempobj.getYPeak() + this->boxYmin(),\n                                         tempobj.getZPeak(),\n                                         tempobj.getPeakFlux());\n                int freq = 1;\n                bool finished = false;\n\n                if (peakMap.size() > 0) {\n                    pk = peakMap.begin();\n\n                    while (!finished && pk != peakMap.end()) {\n                        if (!(pk->second == peakLoc)) {\n                            pk++;\n                        } else {\n                            freq = pk->first + 1;\n                            peakMap.erase(pk);\n                            finished = true;\n                        }\n                    }\n                }\n\n                peakMap.insert(std::pair<int, PixelInfo::Voxel>(freq, peakLoc));\n            }\n        }\n    }\n\n    return peakMap;\n}\n\n\n//**************************************************************//\n\nvoid RadioSource::prepareForFit(duchamp::Cube & cube, bool useArray)\n{\n\n    if (useArray) {\n        this->setNoiseLevel(cube);\n    } else {\n        // if need to use the surrounding noise, we have to go extract\n        // it from the image\n        if (itsFitParams.useNoise()) {\n            float noise = findSurroundingNoise(cube.pars().getImageFile(),\n                                               this->xpeak + this->xSubOffset,\n                                               this->ypeak + this->ySubOffset,\n                                               itsFitParams.noiseBoxSize());\n            this->setNoiseLevel(noise);\n        } else {\n            this->setNoiseLevel(1);\n        }\n    }\n\n    this->setHeader(cube.header());\n    this->setOffsets(cube.pars());\n    if (!itsFitParams.doFit()) {\n        itsFitParams.setBoxPadSize(1);\n    }\n    this->defineBox(cube.pars().section(), cube.header().getWCS()->spec);\n\n}\n\n//**************************************************************//\n\nbool RadioSource::fitGauss(duchamp::Cube &cube)\n{\n    std::vector<float> array(cube.getArray(),\n                             cube.getArray() + cube.getSize());\n    std::vector<size_t> dim(cube.getDimArray(),\n                            cube.getDimArray() + cube.getNumDim());\n\n    if (itsFitParams.fitJustDetection()) {\n        ASKAPLOG_DEBUG_STR(logger, \"Fitting to detected pixels\");\n        std::vector<PixelInfo::Voxel> voxlist = this->getPixelSet(array.data(), dim.data());\n        return fitGauss(voxlist);\n    } else {\n        return fitGauss(array, dim);\n    }\n\n}\n\n//**************************************************************//\n\nbool RadioSource::fitGauss(std::vector<PixelInfo::Voxel> &voxelList)\n{\n    int size = this->getSize();\n    casa::Matrix<casa::Double> pos;\n    casa::Vector<casa::Double> f;\n    casa::Vector<casa::Double> sigma;\n    pos.resize(size, 2);\n    f.resize(size);\n    sigma.resize(size);\n    casa::Vector<casa::Double> curpos(2);\n    curpos = 0;\n\n    if (this->getZmin() != this->getZmax()) {\n        ASKAPLOG_ERROR_STR(logger,\n                           \"Can only do fitting for two-dimensional objects!: \" <<\n                           \"z-locations show a spread: \" <<\n                           \" zmin=\" << this->getZmin() <<\n                           \", zmax=\" << this->getZmax());\n        return false;\n    }\n\n    int i = 0;\n    std::vector<PixelInfo::Voxel>::iterator vox = voxelList.begin();\n\n    for (; vox < voxelList.end(); vox++) {\n        if (this->isInObject(*vox)) { // just to make sure it is a source pixel\n            sigma(i) = itsNoiseLevel;\n            curpos(0) = vox->getX();\n            curpos(1) = vox->getY();\n            pos.row(i) = curpos;\n            f(i) = vox->getF();\n            i++;\n        }\n    }\n\n    return fitGauss(pos, f, sigma);\n}\n\n//**************************************************************//\n\nbool RadioSource::fitGauss(std::vector<float> &fluxArray,\n                           std::vector<size_t> &dimArray)\n{\n\n    if (this->getZcentre() != this->getZmin() || this->getZcentre() != this->getZmax()) {\n        ASKAPLOG_ERROR(logger, \"Can only do fitting for two-dimensional objects!\");\n        return false;\n    }\n\n    casa::Matrix<casa::Double> pos;\n    casa::Vector<casa::Double> f;\n    casa::Vector<casa::Double> sigma;\n    pos.resize(this->boxSize(), 2);\n    f.resize(this->boxSize());\n    sigma.resize(this->boxSize());\n    casa::Vector<casa::Double> curpos(2);\n    curpos = 0;\n\n    for (long x = this->boxXmin(); x <= this->boxXmax(); x++) {\n        for (long y = this->boxYmin(); y <= this->boxYmax(); y++) {\n            size_t i = (x - this->boxXmin()) +\n                       (y - this->boxYmin()) * this->boxXsize();\n            size_t j = x + y * dimArray[0];\n\n            if (j < dimArray[0]*dimArray[1]) {\n                f(i) = fluxArray[j];\n            } else {\n                f(i) = 0.;\n            }\n\n            sigma(i) = itsNoiseLevel;\n            curpos(0) = x;\n            curpos(1) = y;\n            pos.row(i) = curpos;\n        }\n    }\n\n    return fitGauss(pos, f, sigma);\n}\n\n//**************************************************************//\n\nFitter RadioSource::fitGauss(int nGauss,\n                             std::vector<SubComponent> &estimateList,\n                             casa::Matrix<casa::Double> &pos,\n                             casa::Vector<casa::Double> &f,\n                             casa::Vector<casa::Double> &sigma)\n{\n    Fitter newfit(itsFitParams);\n    newfit.setNumGauss(nGauss);\n    newfit.setEstimates(estimateList);\n    newfit.setRetries();\n    newfit.setMasks();\n    newfit.fit(pos, f, sigma);\n    return newfit;\n}\n\n\nbool RadioSource::fitGauss(casa::Matrix<casa::Double> &pos,\n                           casa::Vector<casa::Double> &f,\n                           casa::Vector<casa::Double> &sigma)\n{\n\n    ASKAPLOG_INFO_STR(logger, \"Fitting source \" << this->name <<\n                      \" at RA=\" << this->raS << \", Dec=\" << this->decS <<\n                      \", or global position (x,y)=(\" <<\n                      this->getXcentre() + this->getXOffset() << \",\" <<\n                      this->getYcentre() + this->getYOffset() << \")\");\n\n    if (this->getSpatialSize() < itsFitParams.minFitSize()) {\n        ASKAPLOG_INFO_STR(logger, \"Not fitting- source is too small - \" <<\n                          \"spatial size = \" << this->getSpatialSize() <<\n                          \" cf. minFitSize = \" << itsFitParams.minFitSize());\n        return false;\n    }\n\n    itsFitParams.saveBox(itsBox);\n    itsFitParams.setPeakFlux(this->peakFlux);\n    itsFitParams.setDetectThresh(itsDetectionThreshold);\n    if (itsHeader.beam().min() > 0) {\n        itsFitParams.setBeamSize(itsHeader.beam().min());\n    } else {\n        itsFitParams.setBeamSize(1.);\n    }\n\n    ASKAPLOG_DEBUG_STR(logger, \"numSubThresh=\" << itsFitParams.numSubThresholds());\n\n    ASKAPLOG_INFO_STR(logger, \"detect threshold = \" << itsDetectionThreshold <<\n                      \",  peak flux = \" << this->peakFlux <<\n                      \",  noise level = \" << itsNoiseLevel);\n\n    // Get the list of subcomponents\n    std::vector<SubComponent> cmpntList = this->getSubComponentList(pos, f);\n    ASKAPLOG_DEBUG_STR(logger, \"Found \" << cmpntList.size() << \" subcomponents\");\n\n    for (uInt i = 0; i < cmpntList.size(); i++) {\n        ASKAPLOG_DEBUG_STR(logger, \"SubComponent: \" << cmpntList[i]);\n    }\n\n    std::map<float, std::string> bestChisqMap; // map reduced-chisq to fitType\n\n    std::vector<std::string>::iterator type;\n    std::vector<std::string> typelist = availableFitTypes;\n\n    for (type = typelist.begin(); type < typelist.end(); type++) {\n        if (itsFitParams.hasType(*type)) {\n            ASKAPLOG_INFO_STR(logger, \"Commencing fits of type \\\"\" << *type << \"\\\"\");\n            itsFitParams.setFlagFitThisParam(*type);\n\n            std::vector<SubComponent> cmpntListCopy(cmpntList);\n\n            // For any subcomponent that is smaller than the beam\n            // (when comparing major axes), set its size to the beam\n            // size. Always do this when fitting \"psf\" type.\n            for (size_t i = 0; i < cmpntList.size(); i++) {\n                cmpntListCopy[i].fixSize(*type, itsHeader);\n            }\n\n            int ctr = 0;\n            std::vector<Fitter> fit;\n            bool fitIsGood = false;\n            int bestFit = 0;\n            float bestRChisq = 9999.;\n\n            unsigned int minGauss, maxGauss;\n            if (itsFitParams.numGaussFromGuess()) {\n                minGauss = maxGauss = cmpntListCopy.size();\n            } else {\n                minGauss = 1;\n                maxGauss = std::min(size_t(itsFitParams.maxNumGauss()), f.size());\n            }\n\n            bool fitPossible = true;\n            bool stopNow = false;\n            for (unsigned int g = minGauss; g <= maxGauss && fitPossible && !stopNow; g++) {\n                ASKAPLOG_DEBUG_STR(logger, \"Number of Gaussian components = \" << g);\n\n                fit.push_back(fitGauss(g, cmpntListCopy, pos, f, sigma));\n                fitPossible = fit[ctr].fitExists();\n                bool acceptable = fit[ctr].acceptable();\n\n                if (fitPossible && acceptable) {\n                    if ((ctr == 0) || (fit[ctr].redChisq() < bestRChisq)) {\n                        fitIsGood = true;\n                        bestFit = ctr;\n                        bestRChisq = fit[ctr].redChisq();\n                    }\n                } else {\n\n                    if (itsFitParams.numGaussFromGuess() &&\n                            (fit[ctr].ndof() > 0) && (fit[ctr].passConverged())) {\n                        // If we are just going on the number of\n                        // Gaussians from the initial estimate, and\n                        // the fit failed, we subtract the fit result\n                        // and search again for an estimate, adding\n                        // the brightest component to the list and\n                        // re-doing. But only if that brightest\n                        // component is brighter than the noise.\n\n                        ASKAPLOG_DEBUG_STR(logger, \"Removing fitted Gaussian from array\");\n                        casa::Vector<casa::Double> newf = fit[ctr].subtractFit(pos, f);\n                        ASKAPLOG_DEBUG_STR(logger, \"Finding new subcomponents\");\n                        std::vector<SubComponent> newGuessList =\n                            this->getSubComponentList(pos, newf);\n\n                        if (newGuessList[0].peak() > itsDetectionThreshold) {\n                            newGuessList[0].fixSize(*type, itsHeader);\n                            cmpntListCopy.push_back(newGuessList[0]);\n                            ASKAPLOG_DEBUG_STR(logger, \"Adding new subcomponent \" <<\n                                               newGuessList[0]);\n                            maxGauss++;\n                        }\n                    }\n\n                }\n\n                stopNow = itsFitParams.stopAfterFirstGoodFit() && acceptable;\n                ctr++;\n\n            } // end of 'g' for-loop\n            ASKAPLOG_DEBUG_STR(logger, \"Finished loop over Gaussians\");\n\n            if (fitIsGood) {\n                itsFlagHasFit = true;\n\n                itsBestFitMap[*type].saveResults(fit[bestFit]);\n\n                bestChisqMap.insert(std::pair<float,\n                                    std::string>(fit[bestFit].redChisq(), *type));\n            }\n        }\n    } // end of type for-loop\n\n    if (itsFlagHasFit) {\n\n        itsBestFitType = bestChisqMap.begin()->second;\n        itsBestFitMap[\"best\"] = itsBestFitMap[itsBestFitType];\n\n        ASKAPLOG_INFO_STR(logger, \"BEST FIT: \" <<\n                          itsBestFitMap[\"best\"].numGauss() << \" Gaussians\" <<\n                          \" with fit type \\\"\" << bestChisqMap.begin()->second <<\n                          \"\\\", chisq = \" << itsBestFitMap[\"best\"].chisq() <<\n                          \", chisq/nu =  \"  << itsBestFitMap[\"best\"].redchisq() <<\n                          \", RMS = \" << itsBestFitMap[\"best\"].RMS());\n        itsBestFitMap[\"best\"].logIt(\"INFO\");\n\n    } else {\n        itsFlagHasFit = false;\n        if (itsFitParams.useGuessIfBad()) {\n            ASKAPLOG_INFO_STR(logger, \"Fits failed, so saving initial estimate (\" << cmpntList.size() << \" components) as solution\"); \n            itsBestFitType = \"guess\";\n            // set the components to be at least as big as the beam\n            for (size_t i = 0; i < cmpntList.size(); i++) {\n                casa::Gaussian2D<casa::Double> gauss = cmpntList[i].asGauss();\n                if (cmpntList[i].maj() < itsHeader.beam().maj()) {\n                    cmpntList[i].setMajor(itsHeader.beam().maj());\n                    cmpntList[i].setMinor(itsHeader.beam().min());\n                    cmpntList[i].setPA(itsHeader.beam().pa()*M_PI / 180.);\n                } else {\n                    cmpntList[i].setMinor(std::max(cmpntList[i].min(),\n                                                   double(itsHeader.beam().min())));\n                }\n            }\n            FitResults guess;\n            guess.saveGuess(cmpntList);\n            itsBestFitMap[\"guess\"] = guess;\n            itsBestFitMap[\"best\"] = guess;\n            for (type = typelist.begin(); type < typelist.end(); type++) {\n                if (itsFitParams.hasType(*type)) {\n                    itsBestFitMap[*type] = guess;\n                }\n            }\n            ASKAPLOG_INFO_STR(logger,\n                              \"No good fit found, so saving initial guess as the fit result\");\n            itsBestFitMap[\"best\"].logIt(\"INFO\");\n        } else {\n            ASKAPLOG_INFO_STR(logger, \"No good fit found.\");\n        }\n    }\n\n    ASKAPLOG_INFO_STR(logger, \"-----------------------\");\n    return itsFlagHasFit;\n}\n\n//**************************************************************//\n\nvoid RadioSource::findSpectralTerm(std::string imageName, int term, bool doCalc)\n{\n\n    std::string termtype[3] = {\"\", \"spectral index\", \"spectral curvature\"};\n\n    ASKAPCHECK(term == 1 || term == 2,\n               \"Term number (\" << term <<\n               \") must be either 1 (for spectral index) or 2 (for spectral curvature)\");\n\n\n    if (!doCalc) {\n\n        std::vector<std::string>::iterator type;\n        std::vector<std::string> typelist = availableFitTypes;\n        typelist.push_back(\"best\");\n\n        for (type = typelist.begin(); type < typelist.end(); type++) {\n            int nfits = itsBestFitMap[*type].numFits();\n            if (term == 1) {\n                itsAlphaMap[*type] = std::vector<double>(nfits, defaultAlpha);\n                itsAlphaError[*type] = std::vector<double>(nfits, 0.);\n            } else if (term == 2) {\n                itsBetaMap[*type] = std::vector<double>(nfits, defaultBeta);\n                itsBetaError[*type] = std::vector<double>(nfits, 0.);\n            }\n        }\n\n\n\n    }\n    else {\n        ASKAPLOG_DEBUG_STR(logger,\n                           \"About to find the \" << termtype[term] <<\n                           \", for image \" << imageName);\n\n        // Get taylor1 values for box, and define positions\n        Slice xrange = casa::Slice(this->boxXmin() + this->getXOffset(),\n                                   this->boxXmax() - this->boxXmin() + 1, 1);\n        Slice yrange = casa::Slice(this->boxYmin() + this->getYOffset(),\n                                   this->boxYmax() - this->boxYmin() + 1, 1);\n        Slicer theBox = casa::Slicer(xrange, yrange);\n\n        // casa::Array<casa::Float> flux_all = getPixelsInBox(imageName, theBox);\n        casa::MaskedArray<casa::Float> flux_all = getPixelsInBox(imageName, theBox);\n\n        std::vector<double> fluxvec;\n        for (size_t i = 0; i < flux_all.size(); i++) {\n            if (!isnan(flux_all.getArray().data()[i])) {\n                fluxvec.push_back(flux_all.getArray().data()[i]);\n            }\n        }\n        casa::Matrix<casa::Double> pos;\n        casa::Vector<casa::Double> sigma;\n        pos.resize(fluxvec.size(), 2);\n        sigma.resize(fluxvec.size());\n        casa::Vector<casa::Double> curpos(2);\n        curpos = 0;\n\n        // The following checks for pixels that have been blanked, and\n        // ignores them\n        int counter = 0;\n        for (size_t i = 0; i < flux_all.size(); i++) {\n            if (flux_all.getMask().data()[i]) {\n                sigma(counter) = 1;\n                curpos(0) = i % this->boxXsize() + this->boxXmin();\n                curpos(1) = i / this->boxXsize() + this->boxYmin();\n                pos.row(counter) = curpos;\n                counter++;\n            }\n        }\n        casa::Vector<casa::Double> f(fluxvec);\n\n        // Set up fit with same parameters and do the fit\n        std::vector<std::string>::iterator type;\n        std::vector<std::string> typelist = availableFitTypes;\n\n        for (type = typelist.begin(); type < typelist.end(); type++) {\n            std::vector<double> termValues(itsBestFitMap[*type].numGauss(), 0.);\n            std::vector<double> termErrors(itsBestFitMap[*type].numGauss(), 0.);\n\n            if (itsBestFitMap[*type].isGood() || itsBestFitMap[*type].fitIsGuess()) {\n\n                ASKAPLOG_DEBUG_STR(logger, \"Finding \" << termtype[term] <<\n                                   \" values for fit type \\\"\" << *type <<\n                                   \"\\\", with \" << itsBestFitMap[*type].numGauss() <<\n                                   \" components \");\n\n                std::vector<SubComponent> cmpnts = itsBestFitMap[*type].getCmpntList();\n                itsFitParams.setFlagFitThisParam(\"height\");\n                itsFitParams.setNegativeFluxPossible(true);\n                Fitter fit = fitGauss(itsBestFitMap[*type].numGauss(),\n                                      cmpnts, pos, f, sigma);\n\n                // Calculate taylor term value\n\n                if (fit.fitExists() && fit.passConverged() && fit.passChisq()) {\n                    // the fit is OK\n                    ASKAPLOG_DEBUG_STR(logger,\n                                       \"Values for \" << termtype[term] << \" follow \" <<\n                                       \"(\" << itsBestFitMap[*type].numGauss() << \" of them):\");\n\n                    for (unsigned int i = 0; i < itsBestFitMap[*type].numGauss(); i++) {\n                        double Iref = itsBestFitMap[*type].gaussian(i).flux();\n                        double Iref_err = itsBestFitMap[*type].errors(i)[0];\n                        if (term == 1) {\n                            termValues[i] = fit.gaussian(i).flux() / Iref;\n                            termErrors[i] = abs(termValues[i]) *\n                                sqrt(Iref_err*Iref_err/(Iref*Iref) +\n                                     fit.error(i)[0]*fit.error(i)[0]/(fit.gaussian(i).flux()*fit.gaussian(i).flux()));\n                        } else if (term == 2) {\n                            double alpha = itsAlphaMap[*type][i];\n                            double alpha_err = itsAlphaError[*type][i];\n                            termValues[i] = fit.gaussian(i).flux() / Iref -\n                                            0.5 * alpha * (alpha - 1.);\n                            termErrors[i] = sqrt(fit.error(i)[0]*fit.error(i)[0]/(Iref*Iref) +\n                                                 fit.error(i)[0]*fit.error(i)[0]*fit.gaussian(i).flux()*fit.gaussian(i).flux()/(Iref*Iref*Iref*Iref) +\n                                                 (0.5-alpha)*(0.5-alpha)*alpha_err*alpha_err);\n                        }\n                        ASKAPLOG_DEBUG_STR(logger,\n                                           \"   Component \" << i << \": \" << termValues[i] <<\n                                           \" +- \" << termErrors[i] <<\n                                           \", calculated with fitted flux of \" <<\n                                           fit.gaussian(i).flux() <<\n                                           \", peaking at \" << fit.gaussian(i).height() <<\n                                           \", best fit taylor0 flux of \" << Iref);\n                    }\n                }\n\n            }\n\n            if (term == 1) {\n                itsAlphaMap[*type] = termValues;\n                itsAlphaError[*type] = termErrors;\n            } else if (term == 2) {\n                itsBetaMap[*type] = termValues;\n                itsBetaError[*type] = termErrors;\n            }\n        }\n\n        ASKAPLOG_DEBUG_STR(logger, \"Finished finding the \" << termtype[term] << \" values\");\n\n    }\n\n    if (term == 1) {\n        itsAlphaMap[\"best\"] = itsAlphaMap[itsBestFitType];\n        itsAlphaError[\"best\"] = itsAlphaError[itsBestFitType];\n    } else if (term == 2) {\n        itsBetaMap[\"best\"] = itsBetaMap[itsBestFitType];\n        itsBetaError[\"best\"] = itsBetaError[itsBestFitType];\n    }\n\n}\n\n\n//**************************************************************//\n\nvoid RadioSource::printTableRow(std::ostream &stream,\n                                duchamp::Catalogues::CatalogueSpecification columns,\n                                size_t fitNum,\n                                std::string fitType)\n{\n\n    stream.setf(std::ios::fixed);\n    for (size_t i = 0; i < columns.size(); i++) {\n        this->printTableEntry(stream, columns.column(i), fitNum, fitType);\n    }\n    stream << \"\\n\";\n\n}\n\n//**************************************************************//\n\ncasa::Unit getUnit(duchamp::Catalogues::Column &column)\n{\n    std::string desiredUnitsStr = column.getUnits();\n    if (desiredUnitsStr[0] == '[') {\n        // may have units in square brackets, eg. Jy/beam\n        desiredUnitsStr = desiredUnitsStr.substr(1, desiredUnitsStr.size() - 2);\n    }\n    casa::Unit desiredUnits(desiredUnitsStr);\n    return desiredUnits;\n\n}\n\nvoid RadioSource::printTableEntry(std::ostream &stream,\n                                  duchamp::Catalogues::Column column,\n                                  size_t fitNum,\n                                  std::string fitType)\n{\n\n    // check that we are requesting a valid fit number\n    ASKAPCHECK(fitNum < itsBestFitMap[fitType].numFits(),\n               \"fitNum=\" << fitNum << \", but source \" << this->getID() <<\n               \" only has \" << itsBestFitMap[fitType].numFits() <<\n               \" fits for type \" << fitType);\n\n    // Define local variables that will get printed\n    FitResults results = itsBestFitMap[fitType];\n    casa::Gaussian2D<Double> gauss = itsBestFitMap[fitType].gaussian(fitNum);\n    std::stringstream id;\n    id << this->getID() << getSuffix(fitNum);\n    std::vector<Double> deconv = deconvolveGaussian(gauss, itsHeader.getBeam());\n\n    double thisRA, thisDec, zworld;\n    itsHeader.pixToWCS(gauss.xCenter(), gauss.yCenter(), this->getZcentre(),\n                       thisRA, thisDec, zworld);\n\n    int lng = itsHeader.WCS().lng;\n    int precision = -int(log10(fabs(itsHeader.WCS().cdelt[lng] * 3600. / 10.)));\n    float pixscale = itsHeader.getAvPixScale() * 3600.; // convert from pixels to arcsec\n    std::string raS  = decToDMS(thisRA, itsHeader.lngtype(), precision);\n    std::string decS = decToDMS(thisDec, itsHeader.lattype(), precision);\n    std::string name = itsHeader.getIAUName(thisRA, thisDec);\n    float intfluxfit = gauss.flux();\n    if (itsHeader.needBeamSize()) {\n        intfluxfit /= itsHeader.beam().area(); // Convert from Jy/beam to Jy\n    }\n    double alpha = itsAlphaMap[fitType][fitNum];\n    double beta = itsBetaMap[fitType][fitNum];\n    std::string blankComment = \"--\";\n    int flagGuess = results.fitIsGuess() ? 1 : 0;\n    int flagSiblings = itsBestFitMap[fitType].numFits() > 1 ? 1 : 0;\n\n    casa::Unit fluxUnits(itsHeader.getFluxUnits());\n    casa::Unit intFluxUnits(itsHeader.getIntFluxUnits());\n\n    std::string type = column.type();\n    if (type == \"ISLAND\") {\n        column.printEntry(stream, this->getID());\n    } else if (type == \"NUM\") {\n        column.printEntry(stream, id.str());\n    } else if (type == \"NAME\") {\n        column.printEntry(stream, name);\n    } else if (type == \"RA\") {\n        column.printEntry(stream, raS);\n    } else if (type == \"DEC\") {\n        column.printEntry(stream, decS);\n    } else if (type == \"RAJD\") {\n        column.printEntry(stream, thisRA);\n    } else if (type == \"DECJD\") {\n        column.printEntry(stream, thisDec);\n    } else if (type == \"RAERR\") {\n        column.printEntry(stream, 0.);\n    } else if (type == \"DECERR\") {\n        column.printEntry(stream, 0.);\n    } else if (type == \"X\") {\n        column.printEntry(stream, gauss.xCenter());\n    } else if (type == \"Y\") {\n        column.printEntry(stream, gauss.yCenter());\n    } else if (type == \"FINT\") {\n        double fluxscale = casa::Quantity(1., intFluxUnits).getValue(getUnit(column));\n        column.printEntry(stream, this->getIntegFlux()*fluxscale);\n    } else if (type == \"FPEAK\") {\n        double fluxscale = casa::Quantity(1., fluxUnits).getValue(getUnit(column));\n        column.printEntry(stream, this->getPeakFlux()*fluxscale);\n    } else if (type == \"FINTFIT\") {\n        double fluxscale = casa::Quantity(1., intFluxUnits).getValue(getUnit(column));\n        column.printEntry(stream, intfluxfit * fluxscale);\n    } else if (type == \"FINTFITERR\") {\n        double fluxscale = casa::Quantity(1., intFluxUnits).getValue(getUnit(column));\n        column.printEntry(stream, 0.*fluxscale);\n    } else if (type == \"FPEAKFIT\") {\n        double fluxscale = casa::Quantity(1., fluxUnits).getValue(getUnit(column));\n        column.printEntry(stream, gauss.height()*fluxscale);\n    } else if (type == \"FPEAKFITERR\") {\n        double fluxscale = casa::Quantity(1., fluxUnits).getValue(getUnit(column));\n        column.printEntry(stream, 0.*fluxscale);\n    } else if (type == \"MAJFIT\") {\n        column.printEntry(stream, gauss.majorAxis()*pixscale);\n    } else if (type == \"MINFIT\") {\n        column.printEntry(stream, gauss.minorAxis()*pixscale);\n    } else if (type == \"PAFIT\") {\n        column.printEntry(stream, gauss.PA() * 180. / M_PI);\n    } else if (type == \"MAJERR\") {\n        column.printEntry(stream, 0.);\n    } else if (type == \"MINERR\") {\n        column.printEntry(stream, 0.);\n    } else if (type == \"PAERR\") {\n        column.printEntry(stream, 0.);\n    } else if (type == \"MAJDECONV\") {\n        column.printEntry(stream, deconv[0]*pixscale);\n    } else if (type == \"MINDECONV\") {\n        column.printEntry(stream, deconv[1]*pixscale);\n    } else if (type == \"PADECONV\") {\n        column.printEntry(stream, deconv[2] * 180. / M_PI);\n    } else if (type == \"ALPHA\") {\n        column.printEntry(stream, alpha);\n    } else if (type == \"BETA\") {\n        column.printEntry(stream, beta);\n    } else if (type == \"CHISQFIT\") {\n        column.printEntry(stream, results.chisq());\n    } else if (type == \"RMSIMAGE\") {\n        double fluxscale = casa::Quantity(1., fluxUnits).getValue(getUnit(column));\n        column.printEntry(stream, itsNoiseLevel * fluxscale);\n    } else if (type == \"RMSFIT\") {\n        double fluxscale = casa::Quantity(1., fluxUnits).getValue(getUnit(column));\n        column.printEntry(stream, results.RMS()*fluxscale);\n    } else if (type == \"NFREEFIT\") {\n        column.printEntry(stream, results.numFreeParam());\n    } else if (type == \"NDOFFIT\") {\n        column.printEntry(stream, results.ndof());\n    } else if (type == \"NPIXFIT\") {\n        column.printEntry(stream, results.numPix());\n    } else if (type == \"NPIXOBJ\") {\n        column.printEntry(stream, this->getSize());\n    } else if (type == \"GUESS\") {\n        column.printEntry(stream, flagGuess);\n    } else if (type == \"FLAG1\") {\n        column.printEntry(stream, flagSiblings);\n    } else if (type == \"FLAG2\") {\n        column.printEntry(stream, flagGuess);\n    } else if (type == \"FLAG3\") {\n        column.printEntry(stream, 0);\n    } else if (type == \"FLAG4\") {\n        column.printEntry(stream, 0);\n    } else if (type == \"COMMENT\") {\n        column.printEntry(stream, blankComment);\n    } else {\n        // handles anything covered by duchamp code. If different column,\n        // use the following.\n        this->duchamp::Detection::printTableEntry(stream, column);\n    }\n}\n\n//**************************************************************//\n\nvoid\nRadioSource::writeFitToAnnotationFile(boost::shared_ptr<duchamp::AnnotationWriter> &writer,\n                                      int sourceNum,\n                                      bool doEllipse,\n                                      bool doBox)\n{\n\n    std::stringstream ss;\n    ss << \"# Source \" << sourceNum << \":\";\n    writer->writeCommentString(ss.str());\n\n    std::vector<double> pix(12);\n    std::vector<double> world(12);\n\n    for (int i = 0; i < 4; i++) {\n        // set z-pixel values to zero\n        pix[i * 3 + 2] = 0.;\n    }\n\n    std::vector<casa::Gaussian2D<Double> > fitSet = itsBestFitMap[\"best\"].fitSet();\n    std::vector<casa::Gaussian2D<Double> >::iterator fit;\n\n    float pixscale = itsHeader.getAvPixScale();\n    if (doEllipse) {\n        for (fit = fitSet.begin(); fit < fitSet.end(); fit++) {\n            pix[0] = fit->xCenter();\n            pix[1] = fit->yCenter();\n            itsHeader.pixToWCS(pix.data(), world.data());\n\n            writer->ellipse(world[0],\n                            world[1],\n                            fit->majorAxis() * pixscale / 2.,\n                            fit->minorAxis() * pixscale / 2.,\n                            fit->PA() * 180. / M_PI);\n        }\n    }\n\n    if (doBox) {\n        pix[0] = pix[9] = this->getXmin() - itsFitParams.boxPadSize() - 0.5;\n        pix[1] = pix[4] = this->getYmin() - itsFitParams.boxPadSize() - 0.5;\n        pix[3] = pix[6] = this->getXmax() + itsFitParams.boxPadSize() + 0.5;\n        pix[7] = pix[10] = this->getYmax() + itsFitParams.boxPadSize() + 0.5;\n        itsHeader.pixToWCS(pix.data(), world.data(), 4);\n\n        std::vector<double> x, y;\n        for (int i = 0; i <= 4; i++) {\n            x.push_back(world[(i % 4) * 3]);\n            y.push_back(world[(i % 4) * 3 + 1]);\n        }\n        writer->joinTheDots(x, y);\n    }\n\n}\n\n//**************************************************************//\n\nLOFAR::BlobOStream& operator<<(LOFAR::BlobOStream& blob, RadioSource& src)\n{\n    int32 l;\n    int i;\n    float f;\n    double d;\n    std::string s;\n    bool b;\n    int size = src.getSize();\n    blob << size;\n    std::vector<PixelInfo::Voxel> pixelSet = src.getPixelSet();\n\n    for (i = 0; i < size; i++) {\n        l = pixelSet[i].getX(); blob << l;\n        l = pixelSet[i].getY(); blob << l;\n        l = pixelSet[i].getZ(); blob << l;\n    }\n\n    l = src.xSubOffset; blob << l;\n    l = src.ySubOffset; blob << l;\n    l = src.zSubOffset; blob << l;\n    b = src.haveParams; blob << b;\n    f = src.totalFlux;  blob << f;\n    f = src.intFlux;    blob << f;\n    f = src.peakFlux;   blob << f;\n    l = src.xpeak;      blob << l;\n    l = src.ypeak;      blob << l;\n    l = src.zpeak;      blob << l;\n    f = src.peakSNR;    blob << f;\n    f = src.xCentroid;  blob << f;\n    f = src.yCentroid;  blob << f;\n    f = src.zCentroid;  blob << f;\n    s = src.centreType; blob << s;\n    b = src.negSource;  blob << b;\n    s = src.flagText;   blob << s;\n    i = src.id;         blob << i;\n    s = src.name;       blob << s;\n    b = src.flagWCS;    blob << b;\n    s = src.raS;        blob << s;\n    s = src.decS;       blob << s;\n    d = src.ra;         blob << d;\n    d = src.dec;        blob << d;\n    d = src.raWidth;    blob << d;\n    d = src.decWidth;   blob << d;\n    d = src.majorAxis;  blob << d;\n    d = src.minorAxis;  blob << d;\n    d = src.posang;     blob << d;\n    b = src.specOK;     blob << b;\n    s = src.specUnits;  blob << s;\n    s = src.specType;   blob << s;\n    s = src.fluxUnits;  blob << s;\n    s = src.intFluxUnits; blob << s;\n    s = src.lngtype;    blob << s;\n    s = src.lattype;    blob << s;\n    d = src.vel;        blob << d;\n    d = src.velWidth;   blob << d;\n    d = src.velMin;     blob << d;\n    d = src.velMax;     blob << d;\n    d = src.v20min;     blob << d;\n    d = src.v20max;     blob << d;\n    d = src.w20;        blob << d;\n    d = src.v50min;     blob << d;\n    d = src.v50max;     blob << d;\n    d = src.w50;        blob << d;\n    i = src.posPrec;    blob << i;\n    i = src.xyzPrec;    blob << i;\n    i = src.fintPrec;   blob << i;\n    i = src.fpeakPrec;  blob << i;\n    i = src.velPrec;    blob << i;\n    i = src.snrPrec;    blob << i;\n    b = src.itsFlagHasFit;     blob << b;\n    b = src.itsFlagAtEdge;     blob << b;\n    f = src.itsDetectionThreshold; blob << f;\n    f = src.itsNoiseLevel; blob << f;\n    blob << src.itsFitParams;\n    size = src.itsBestFitMap.size();\n    blob << size;\n    std::map<std::string, FitResults>::iterator fit;\n\n    for (fit = src.itsBestFitMap.begin(); fit != src.itsBestFitMap.end(); fit++) {\n        blob << fit->first;\n        blob << fit->second;\n    }\n\n    std::map<std::string, std::vector<double> >::iterator val;\n    size = src.itsAlphaMap.size();\n    blob << size;\n    for (val = src.itsAlphaMap.begin(); val != src.itsAlphaMap.end(); val++) {\n        blob << val->first;\n        size = val->second.size();\n        blob << size;\n\n        for (int i = 0; i < size; i++) blob << val->second[i];\n    }\n\n    size = src.itsAlphaError.size();\n    blob << size;\n    for (val = src.itsAlphaError.begin(); val != src.itsAlphaError.end(); val++) {\n        blob << val->first;\n        size = val->second.size();\n        blob << size;\n\n        for (int i = 0; i < size; i++) blob << val->second[i];\n    }\n\n    size = src.itsBetaMap.size();\n    blob << size;\n    for (val = src.itsBetaMap.begin(); val != src.itsBetaMap.end(); val++) {\n        blob << val->first;\n        size = val->second.size();\n        blob << size;\n\n        for (int i = 0; i < size; i++) blob << val->second[i];\n    }\n\n    size = src.itsBetaError.size();\n    blob << size;\n    for (val = src.itsBetaError.begin(); val != src.itsBetaError.end(); val++) {\n        blob << val->first;\n        size = val->second.size();\n        blob << size;\n\n        for (int i = 0; i < size; i++) blob << val->second[i];\n    }\n\n    i = src.box().ndim(); blob << i;\n    i = src.box().start()[0]; blob << i;\n    i = src.box().start()[1]; blob << i;\n    if (src.box().ndim() > 2) {\n        i = src.box().start()[2]; blob << i;\n    }\n    i = src.box().end()[0]; blob << i;\n    i = src.box().end()[1]; blob << i;\n    if (src.box().ndim() > 2) {\n        i = src.box().end()[2]; blob << i;\n    }\n\n    return blob;\n}\n\n//**************************************************************//\n\nLOFAR::BlobIStream& operator>>(LOFAR::BlobIStream &blob, RadioSource& src)\n{\n    int i;\n    int32 l;\n    bool b;\n    float f;\n    double d;\n    std::string s;\n    int32 size;\n    blob >> size;\n\n    for (i = 0; i < size; i++) {\n        int32 x, y, z;\n        blob >> x;\n        blob >> y;\n        blob >> z;\n        src.addPixel(x, y, z);\n    }\n\n    blob >> l; src.xSubOffset = l;\n    blob >> l; src.ySubOffset = l;\n    blob >> l; src.zSubOffset = l;\n    blob >> b; src.haveParams = b;\n    blob >> f; src.totalFlux = f;\n    blob >> f; src.intFlux = f;\n    blob >> f; src.peakFlux = f;\n    blob >> l; src.xpeak = l;\n    blob >> l; src.ypeak = l;\n    blob >> l; src.zpeak = l;\n    blob >> f; src.peakSNR = f;\n    blob >> f; src.xCentroid = f;\n    blob >> f; src.yCentroid = f;\n    blob >> f; src.zCentroid = f;\n    blob >> s; src.centreType = s;\n    blob >> b; src.negSource = b;\n    blob >> s; src.flagText = s;\n    blob >> i; src.id = i;\n    blob >> s; src.name = s;\n    blob >> b; src.flagWCS = b;\n    blob >> s; src.raS = s;\n    blob >> s; src.decS = s;\n    blob >> d; src.ra = d;\n    blob >> d; src.dec = d;\n    blob >> d; src.raWidth = d;\n    blob >> d; src.decWidth = d;\n    blob >> d; src.majorAxis = d;\n    blob >> d; src.minorAxis = d;\n    blob >> d; src.posang = d;\n    blob >> b; src.specOK = b;\n    blob >> s; src.specUnits = s;\n    blob >> s; src.specType = s;\n    blob >> s; src.fluxUnits = s;\n    blob >> s; src.intFluxUnits = s;\n    blob >> s; src.lngtype = s;\n    blob >> s; src.lattype = s;\n    blob >> d; src.vel = d;\n    blob >> d; src.velWidth = d;\n    blob >> d; src.velMin = d;\n    blob >> d; src.velMax = d;\n    blob >> d; src.v20min = d;\n    blob >> d; src.v20max = d;\n    blob >> d; src.w20 = d;\n    blob >> d; src.v50min = d;\n    blob >> d; src.v50max = d;\n    blob >> d; src.w50 = d;\n    blob >> i; src.posPrec = i;\n    blob >> i; src.xyzPrec = i;\n    blob >> i; src.fintPrec = i;\n    blob >> i; src.fpeakPrec = i;\n    blob >> i; src.velPrec = i;\n    blob >> i; src.snrPrec = i;\n    blob >> b; src.itsFlagHasFit = b;\n    blob >> b; src.itsFlagAtEdge = b;\n    blob >> f; src.itsDetectionThreshold = f;\n    blob >> f; src.itsNoiseLevel = f;\n    blob >> src.itsFitParams;\n    blob >> size;\n\n    for (int i = 0; i < size; i++) {\n        FitResults res;\n        blob >> s >> res;\n        src.itsBestFitMap[s] = res;\n    }\n\n    blob >> size;\n\n    for (int i = 0; i < size; i++) {\n        int32 vecsize;\n        blob >> s >> vecsize;\n        std::vector<double> vec(vecsize);\n\n        for (int i = 0; i < vecsize; i++) blob >> vec[i];\n\n        src.itsAlphaMap[s] = vec;\n    }\n\n    blob >> size;\n\n    for (int i = 0; i < size; i++) {\n        int32 vecsize;\n        blob >> s >> vecsize;\n        std::vector<double> vec(vecsize);\n\n        for (int i = 0; i < vecsize; i++){\n            blob >> vec[i];\n            ASKAPLOG_DEBUG_STR(logger, \"alpha error \" << vec[i]);\n        }\n\n        src.itsAlphaError[s] = vec;\n    }\n\n    blob >> size;\n\n    for (int i = 0; i < size; i++) {\n        int32 vecsize;\n        blob >> s >> vecsize;\n        std::vector<double> vec(vecsize);\n\n        for (int i = 0; i < vecsize; i++) blob >> vec[i];\n\n        src.itsBetaMap[s] = vec;\n    }\n\n    blob >> size;\n\n    for (int i = 0; i < size; i++) {\n        int32 vecsize;\n        blob >> s >> vecsize;\n        std::vector<double> vec(vecsize);\n\n        for (int i = 0; i < vecsize; i++) blob >> vec[i];\n\n        src.itsBetaError[s] = vec;\n    }\n\n    int ndim, x1, y1, z1, x2, y2, z2;\n    blob >> ndim >> x1 >> y1;\n    if (ndim > 2) {\n        blob >> z1;\n    }\n    blob >> x2 >> y2;\n    if (ndim > 2) {\n        blob >> z2;\n    }\n    casa::IPosition start(ndim), end(ndim), stride(ndim, 1);\n    start(0) = x1; start(1) = y1;\n    end(0) = x2; end(1) = y2;\n    if (ndim > 2) {\n        start(2) = z1;\n        end(2) = z2;\n    }\n    ASKAPCHECK(end >= start,\n               \"Slicer in blob transfer of RadioSource - start \" << start << \" > end \" << end);\n    Slicer box(start, end, stride, Slicer::endIsLast);;\n    src.setBox(box);\n\n    return blob;\n}\n\n\n\n}\n\n}\n\n}\n", "meta": {"hexsha": "4f9633397ea8151d3c4150c55e1275e39b71a94a", "size": 66355, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Code/Components/Analysis/analysis/current/sourcefitting/RadioSource.cc", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "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/Components/Analysis/analysis/current/sourcefitting/RadioSource.cc", "max_issues_repo_name": "rtobar/askapsoft", "max_issues_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "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/Components/Analysis/analysis/current/sourcefitting/RadioSource.cc", "max_forks_repo_name": "rtobar/askapsoft", "max_forks_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2793876435, "max_line_length": 150, "alphanum_fraction": 0.5202923668, "num_tokens": 17193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.15858811310907062}}
{"text": "#define TINYOBJLOADER_IMPLEMENTATION\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n\n#include <array>\n#include <limits>\n#include <map>\n#include <memory>\n#include <optional>\n#include <regex>\n#include <unordered_map>\n#include <utility>\n\n#include \"scene.hh\"\n\n// clang-format off\n#include \"spdlog/spdlog.h\"\n#include \"spdlog/sinks/stdout_color_sinks.h\"\n// clang-format on\n\n#include <boost/filesystem.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"fplus/fplus.hpp\"\n\n#include \"tinyxml2.h\"\n\n#include \"tiny_obj_loader.h\"\n\n#include <urdf_model/model.h>\n#include <urdf_model/joint.h>\n#include <urdf_parser/urdf_parser.h>\n\nnamespace input::scene {\n// TODO(Wil): Should pose/surface/grasp info be bundled into Objects or contained separately for\n// faster searches?\nnamespace {\n  auto log = spdlog::stdout_color_st(\"scene\");\n  // NOTE: Taken from ImportURDFDemo in Bullet repo\n  constexpr float DEFAULT_COLLISION_MARGIN = 0.001;\n\n  template <int dim> auto parse_template(const Vec<Str>& elems);\n  template <> auto parse_template<3>(const Vec<Str>& elems) {\n    Eigen::Matrix<double, 3, 3> transform_mat(Eigen::Matrix<double, 3, 3>::Identity());\n    for (size_t i = 0; i < 3; ++i) {\n      for (size_t j = 0; j < 3; ++j) {\n        transform_mat(i, j) = std::stod(elems[3 * i + j]);\n      }\n    }\n\n    return transform_mat;\n  }\n\n  template <> auto parse_template<4>(const Vec<Str>& elems) {\n    Eigen::Matrix<double, 4, 4> transform_mat(Eigen::Matrix<double, 4, 4>::Identity());\n    for (size_t i = 0; i < 3; ++i) {\n      for (size_t j = 0; j < 4; ++j) {\n        transform_mat(i, j) = std::stod(elems[4 * i + j]);\n      }\n    }\n\n    return transform_mat;\n  }\n\n  auto transform_of_pose(const urdf::Pose& pose) {\n    Transform3r result;\n    result.translation() = Vector3r(pose.position.x, pose.position.y, pose.position.z);\n    result.linear() =\n    Eigen::Quaterniond(pose.rotation.w, pose.rotation.x, pose.rotation.y, pose.rotation.z)\n    .toRotationMatrix();\n    return result;\n  }\n\n  auto parse_point(const tinyxml2::XMLNode* point_node) {\n    auto x = point_node->FirstChildElement(\"x\")->Value();\n    auto y = point_node->FirstChildElement(\"y\")->Value();\n    auto z = point_node->FirstChildElement(\"z\")->Value();\n    return Vector3r(std::stod(x), std::stod(y), std::stod(z));\n  }\n\n  std::unique_ptr<btCollisionShape> load_bullet_mesh(const Vec<tinyobj::shape_t>& shapes,\n                                                     const tinyobj::attrib_t& mesh_attrib,\n                                                     const urdf::Vector3& scale,\n                                                     const bool maybe_concave) {\n    btVector3 geom_scale(scale.x, scale.y, scale.z);\n    std::unique_ptr<btCollisionShape> model;\n    if (maybe_concave) {\n      // NOTE: We assume that there is only ever one shape in an obj file for a concave shape\n      const auto& shape   = shapes[0];\n      size_t index_offset = 0;\n      auto* trimesh       = new btTriangleMesh();\n      std::array<btVector3, 3> verts;\n      for (size_t f = 0; f < shape.mesh.num_face_vertices.size(); ++f) {\n        for (size_t v = 0; v < 3; ++v) {\n          auto idx = shape.mesh.indices[index_offset + v];\n          auto vx  = mesh_attrib.vertices[3 * idx.vertex_index + 0];\n          auto vy  = mesh_attrib.vertices[3 * idx.vertex_index + 1];\n          auto vz  = mesh_attrib.vertices[3 * idx.vertex_index + 2];\n          btVector3 point(vx, vy, vz);\n          verts[v] = point * geom_scale;\n        }\n\n        trimesh->addTriangle(verts[0], verts[1], verts[2]);\n        index_offset += 3;\n      }\n\n      model = std::make_unique<btBvhTriangleMeshShape>(trimesh, true, true);\n      model->setMargin(DEFAULT_COLLISION_MARGIN);\n    } else {\n      // If we know something isn't possibly concave, it's because it's a convex decomposition\n      btTransform identity;\n      identity.setIdentity();\n      auto compound_model = std::make_unique<btCompoundShape>();\n      for (const auto& shape : shapes) {\n        auto hull_model = new btConvexHullShape();\n        for (const auto& idx : shape.mesh.indices) {\n          auto vx = mesh_attrib.vertices[3 * idx.vertex_index + 0];\n          auto vy = mesh_attrib.vertices[3 * idx.vertex_index + 1];\n          auto vz = mesh_attrib.vertices[3 * idx.vertex_index + 2];\n          btVector3 point(vx, vy, vz);\n          hull_model->addPoint(point * geom_scale, false);\n        }\n\n        hull_model->setMargin(DEFAULT_COLLISION_MARGIN);\n        hull_model->recalcLocalAabb();\n        hull_model->optimizeConvexHull();\n        compound_model->addChildShape(identity, hull_model);\n      }\n\n      compound_model->setMargin(DEFAULT_COLLISION_MARGIN);\n      compound_model->recalculateLocalAabb();\n      model = std::move(compound_model);\n    }\n\n    return model;\n  }\n\n  std::unique_ptr<CollisionShape> parse_obj_mesh(const Str& obj_mesh_path,\n                                                 const Str& obj_dir,\n                                                 const urdf::Vector3& scale,\n                                                 const bool maybe_concave) {\n    tinyobj::attrib_t mesh_attrib;\n    Vec<tinyobj::shape_t> shapes;\n    Vec<tinyobj::material_t> materials;\n    Str err;\n    Str warn;\n    if (!tinyobj::LoadObj(\n        &mesh_attrib, &shapes, &materials, &warn, &err, obj_mesh_path.c_str(), obj_dir.c_str())) {\n      log->error(\"Error loading mesh from {}: '{}'\", obj_mesh_path, err);\n      return nullptr;\n    }\n\n    return load_bullet_mesh(shapes, mesh_attrib, scale, maybe_concave);\n  }\n\n  std::unique_ptr<CollisionShape> geom_of_collision(const urdf::CollisionSharedPtr& collision,\n                                                    const boost::filesystem::path& model_dir) {\n    std::unique_ptr<CollisionShape> geom;\n    switch (collision->geometry->type) {\n      case urdf::Geometry::MESH: {\n        auto collision_geom          = dynamic_cast<const urdf::Mesh&>(*collision->geometry);\n        auto collision_geom_filename = collision_geom.filename;\n        log->debug(\"Loading from mesh: {}\", collision_geom_filename);\n        char const* ros_package_path = std::getenv(\"ROS_PACKAGE_PATH\");\n        if (ros_package_path == nullptr) {\n          log->warn(\"Environment variable ROS_PACKAGE_PATH is undefined! Assuming default value \"\n                    \"(/opt/ros/melodic/share)\");\n          ros_package_path = \"/opt/ros/melodic/share\";\n        }\n\n        // Resolve the path to mesh files\n        const std::regex package_re(\"^package:/\");\n        collision_geom_filename =\n        std::regex_replace(collision_geom_filename, package_re, ros_package_path);\n        auto collision_geom_path = boost::filesystem::path(collision_geom_filename);\n        bool is_obj              = collision_geom_path.extension() == \".obj\";\n        if (collision_geom_path.is_relative()) {\n          collision_geom_path = model_dir / collision_geom_path;\n        }\n\n        if (!is_obj) {\n          collision_geom_path.replace_extension(\".obj\");\n          collision_geom_path =\n          boost::filesystem::temp_directory_path() / collision_geom_path.filename();\n        }\n\n        // TODO(Wil): Find a better way of doing this. Right now (a) using std::system is bad and\n        // (b) this assumes that the right script is at the relative path scripts/mesh_to_obj,\n        // which is also bad.\n        if (!is_obj && !boost::filesystem::is_regular_file(collision_geom_path)) {\n          log->debug(\"Building .obj file for {}\", collision_geom_filename);\n          std::system(fmt::format(\"blender -b -P scripts/mesh_to_obj -- {} -o {}\",\n                                  collision_geom_filename,\n                                  collision_geom_path.string())\n                      .c_str());\n        } else {\n          // TODO(Wil): This could be a problem if there are multiple distinct meshes with the\n          // same name.\n          log->debug(\"Using cached .obj file for {}\", collision_geom_filename);\n        }\n        // Assume success...\n        geom = parse_obj_mesh(collision_geom_path.string(), \"\", collision_geom.scale, false);\n      } break;\n\n      case urdf::Geometry::BOX: {\n        const auto& collision_geom = dynamic_cast<const urdf::Box&>(*collision->geometry);\n        // Bullet expects half-extents here\n        const auto x = collision_geom.dim.x / 2.0;\n        const auto y = collision_geom.dim.y / 2.0;\n        const auto z = collision_geom.dim.z / 2.0;\n        geom         = std::make_unique<btBoxShape>(btVector3(x, y, z));\n      } break;\n\n      case urdf::Geometry::CYLINDER: {\n        const auto& collision_geom = dynamic_cast<const urdf::Cylinder&>(*collision->geometry);\n        // URDF cylinders are Z-aligned, and Bullet expects half-extents here\n        geom = std::make_unique<btCylinderShapeZ>(\n        btVector3(collision_geom.radius, collision_geom.radius, collision_geom.length / 2.0));\n      } break;\n\n      case urdf::Geometry::SPHERE: {\n        const auto& collision_geom = dynamic_cast<const urdf::Sphere&>(*collision->geometry);\n        geom                       = std::make_unique<btSphereShape>(collision_geom.radius);\n      } break;\n\n      default:\n        log->error(\"Got a mesh type I don't know how to deal with! Got: {}\",\n                   collision->geometry->type);\n        throw std::runtime_error(\"Unknown mesh type\");\n    }\n\n    geom->setMargin(DEFAULT_COLLISION_MARGIN);\n    return geom;\n  }\n\n\n  Map<Str, Str> scenegraph_from_model_helper(const urdf::LinkSharedPtr& node,\n                                             const boost::filesystem::path& model_dir,\n                                             std::shared_ptr<Graph>& sg,\n                                             int parent_idx) {\n    // Handle this node\n    std::unique_ptr<btCollisionShape> collision = nullptr;\n    urdf::Pose coll_pose;\n    // NOTE: We assume there's at most one collision/node, which might be wrong for some URDF\n    // models\n    if (node->collision_array.size() > 1) {\n      log->warn(\"More than one collision for {}\", node->name);\n    }\n\n    Transform3r coll_tf;\n    if (node->collision != nullptr) {\n      collision = geom_of_collision(node->collision, model_dir);\n      coll_pose = node->collision->origin;\n      coll_tf   = transform_of_pose(coll_pose);\n    } else {\n      coll_tf = Transform3r::Identity();\n    }\n\n    auto pose = node->parent_joint->parent_to_joint_origin_transform;\n    auto tf   = transform_of_pose(pose);\n    Vector3r axis;\n    auto node_axis = node->parent_joint->axis;\n    Node::Type type;\n    switch (node->parent_joint->type) {\n      case urdf::Joint::PRISMATIC:\n        axis = Vector3r(node_axis.x, node_axis.y, node_axis.z);\n        type = Node::Type::PRISMATIC;\n        break;\n\n      case urdf::Joint::REVOLUTE:\n        axis = Vector3r(node_axis.x, node_axis.y, node_axis.z);\n        type = Node::Type::REVOLUTE;\n        break;\n\n      case urdf::Joint::FIXED:\n        type = Node::Type::FIXED;\n        axis = Vector3r::Zero();\n        break;\n\n      case urdf::Joint::CONTINUOUS:\n        type = Node::Type::CONTINUOUS;\n        axis = Vector3r(node_axis.x, node_axis.y, node_axis.z);\n        break;\n\n      default:\n        log->warn(\"Unsupported joint type '{}'! Treating as fixed.\", node->parent_joint->type);\n        type = Node::Type::FIXED;\n        axis = Vector3r::Zero();\n    }\n\n    Node graph_node(node->name, type, tf, coll_tf, std::move(axis), std::move(collision));\n    auto& new_node     = sg->add_node(parent_idx, graph_node);\n    const auto new_idx = new_node.self_idx;\n\n    // Then the children, recursively\n    Map<Str, Str> name_puns;\n    for (const auto& child : node->child_links) {\n      auto child_name_puns = scenegraph_from_model_helper(child, model_dir, sg, new_idx);\n      name_puns.emplace(child->name, child->parent_joint->name);\n      name_puns.merge(child_name_puns);\n      // tree_nodes.insert({child->parent_joint->name, child_tree.get()});\n      // tree_nodes.insert({child->name, child_tree.get()});\n      // tree_nodes.merge(child_tree_nodes);\n    }\n\n    return name_puns;\n  }\n\n  /// Build a scenegraph from a URDF model\n  Map<Str, Str> scenegraph_from_model(const std::shared_ptr<urdf::ModelInterface>& model,\n                                      const boost::filesystem::path& model_dir,\n                                      std::shared_ptr<Graph>& sg) {\n    // First, extract the root\n    auto model_root       = model->getRoot();\n    auto root_collision   = geom_of_collision(model_root->collision, model_dir);\n    auto root_tf          = Transform3r::Identity();\n    const auto& coll_pose = model_root->collision->origin;\n    const auto coll_tf    = transform_of_pose(coll_pose);\n    Node root(model_root->name,\n              Node::Type::FIXED,\n              root_tf,\n              coll_tf,\n              Vector3r::Zero(),\n              std::move(root_collision));\n\n    // Then, recursively handle the children\n    auto& new_root      = sg->add_node(-1, root);\n    new_root.is_base    = true;\n    const auto root_idx = new_root.self_idx;\n    Map<Str, Str> name_puns;\n    for (const auto& child : model_root->child_links) {\n      auto child_name_puns = scenegraph_from_model_helper(child, model_dir, sg, root_idx);\n      name_puns.emplace(child->name, child->parent_joint->name);\n      name_puns.merge(child_name_puns);\n      // tree_nodes.emplace(child->parent_joint->name, child_tree.get());\n      // tree_nodes.emplace(child->name, child_tree.get());\n      // tree_nodes.merge(child_tree_nodes);\n      // sg->add_node(root.get(), std::move(child_tree));\n    }\n\n    return name_puns;\n  }\n\n  std::pair<Object, Transform3r> parse_object(const Str& obj_dir, tinyxml2::XMLNode* object) {\n    auto name = object->FirstChildElement(\"name\")->FirstChild()->Value();\n    // Check movability\n    auto movable =\n    strncmp(object->FirstChildElement(\"moveable\")->FirstChild()->Value(), \"true\", 4) == 0;\n    Object result(name, movable);\n\n    // Load mesh\n    auto geom_path =\n    fmt::format(\"{}/{}\", obj_dir, object->FirstChildElement(\"geom\")->FirstChild()->Value());\n\n    // Load transform matrix\n    auto pose_elems = fplus::split_by_token<Str>(\n    \" \", false, object->FirstChildElement(\"pose\")->FirstChild()->Value());\n    auto transform_mat = parse_template<4>(pose_elems);\n\n    // Get SSSP (only one is currently allowed)\n    auto sssp_node = object->FirstChildElement(\"sssp\");\n    auto pssp_node = object->FirstChildElement(\"pssp\");\n    if (sssp_node != nullptr) {\n      auto xmin = std::stod(sssp_node->FirstChildElement(\"xmin\")->FirstChild()->Value());\n      auto xmax = std::stod(sssp_node->FirstChildElement(\"xmax\")->FirstChild()->Value());\n\n      auto ymin = std::stod(sssp_node->FirstChildElement(\"ymin\")->FirstChild()->Value());\n      auto ymax = std::stod(sssp_node->FirstChildElement(\"ymax\")->FirstChild()->Value());\n\n      auto zmin = std::stod(sssp_node->FirstChildElement(\"zmin\")->FirstChild()->Value());\n      auto zmax = std::stod(sssp_node->FirstChildElement(\"zmax\")->FirstChild()->Value());\n\n      result.stable_face.emplace<structures::object::StableRegion>(\n      structures::object::StableRegion(xmin, xmax, ymin, ymax, zmin, zmax));\n    } else if (pssp_node != nullptr) {\n      auto point_node = pssp_node->FirstChildElement(\"point\");\n      structures::object::StablePlane plane;\n      while (point_node != nullptr) {\n        plane.emplace_back(parse_point(point_node));\n        point_node = point_node->NextSiblingElement(\"point\");\n      }\n\n      result.stable_face.emplace<structures::object::StablePlane>(\n      structures::object::StablePlane(plane));\n    } else {\n      log->debug(\"No SSSP for {}\", name);\n    }\n\n    // Get SOPs\n    auto sop_node = object->FirstChildElement(\"sop\");\n    while (sop_node != nullptr) {\n      auto template_elems = fplus::split_by_token<Str>(\n      \" \", false, sop_node->FirstChildElement(\"template\")->FirstChild()->Value());\n      Eigen::Quaterniond template_rot(parse_template<3>(template_elems));\n      auto axis_elems = fplus::split_by_token<Str>(\n      \" \", false, sop_node->FirstChildElement(\"axis\")->FirstChild()->Value());\n      auto axis =\n      Vector3r(std::stod(axis_elems[0]), std::stod(axis_elems[1]), std::stod(axis_elems[2]));\n      auto distance = std::stod(sop_node->FirstChildElement(\"distance\")->FirstChild()->Value());\n      result.stable_poses.emplace_back(template_rot, axis, distance);\n      sop_node = sop_node->NextSiblingElement(\"sop\");\n    }\n\n    // Get grasps - First discrete, then continuous\n    auto grasp_node = object->FirstChildElement(\"gf\");\n    while (grasp_node != nullptr) {\n      auto template_elems =\n      fplus::split_by_token<Str>(\" \", false, grasp_node->FirstChild()->Value());\n      auto frame = parse_template<4>(template_elems);\n      result.grasps.emplace_back(Transform3r(frame));\n      grasp_node = grasp_node->NextSiblingElement(\"gf\");\n    }\n\n    grasp_node = object->FirstChildElement(\"gc\");\n    while (grasp_node != nullptr) {\n      auto template_elems = fplus::split_by_token<Str>(\n      \" \", false, grasp_node->FirstChildElement(\"template\")->FirstChild()->Value());\n      auto frame      = parse_template<4>(template_elems);\n      auto axis_elems = fplus::split_by_token<Str>(\n      \" \", false, grasp_node->FirstChildElement(\"axis\")->FirstChild()->Value());\n      auto axis =\n      Vector3r(std::stod(axis_elems[0]), std::stod(axis_elems[1]), std::stod(axis_elems[2]));\n      result.grasps.emplace_back(std::in_place_type_t<structures::object::ContinuousGrasp>(),\n                                 Transform3r(frame),\n                                 axis);\n      grasp_node = grasp_node->NextSiblingElement(\"gc\");\n    }\n\n    result.geom = parse_obj_mesh(geom_path, obj_dir, urdf::Vector3(1.0, 1.0, 1.0), true);\n    const Transform3r eigen_transform(transform_mat);\n    btTransform pose_transform;\n    auto& pose_origin            = pose_transform.getOrigin();\n    const auto& pose_translation = eigen_transform.translation();\n    pose_origin.setX(pose_translation.x());\n    pose_origin.setY(pose_translation.y());\n    pose_origin.setZ(pose_translation.z());\n    const Eigen::Quaterniond eigen_rotation(eigen_transform.linear());\n    btQuaternion pose_rotation(\n    eigen_rotation.x(), eigen_rotation.y(), eigen_rotation.z(), eigen_rotation.w());\n    pose_transform.setRotation(pose_rotation);\n    result.initial_pose = pose_transform;\n    return std::make_pair(std::move(result), eigen_transform);\n  }\n\n  std::optional<Robot> parse_robot(tinyxml2::XMLNode* robot_node, std::shared_ptr<Graph>& sg) {\n    auto name = robot_node->FirstChildElement(\"name\")->FirstChild()->Value();\n\n    // Load kinematic tree\n    auto urdf_path = robot_node->FirstChildElement(\"urdf\")->FirstChild()->Value();\n    auto model     = urdf::parseURDFFile(urdf_path);\n    if (model == nullptr) {\n      log->error(\"Failed to load URDF for {}!\", name);\n      return std::nullopt;\n    }\n\n    // We need the path for handling relative paths to meshes in the URDF\n    auto model_dir = boost::filesystem::path(urdf_path).parent_path();\n    auto name_puns = scenegraph_from_model(model, model_dir, sg);\n    // Load base pose transform matrix\n    auto pose_elems = fplus::split_by_token<Str>(\n    \" \", false, robot_node->FirstChildElement(\"basepose\")->FirstChild()->Value());\n    auto transform_mat = parse_template<4>(pose_elems);\n\n    auto tf = std::make_unique<Transform3r>(transform_mat);\n\n    // Load torso configuration\n    auto torso_node = robot_node->FirstChildElement(\"torso\");\n    auto torso_cfg  = (torso_node != nullptr) ?\n                     std::optional<double>(std::stod(torso_node->FirstChild()->Value())) :\n                     std::nullopt;\n\n    // Setup info for controllable joints\n\n    auto controllable_joints_element    = robot_node->FirstChildElement(\"controllable_joints\");\n    tinyxml2::XMLElement* joint_element = nullptr;\n    if (controllable_joints_element == nullptr) {\n      log->critical(\"No controllable joints found! Good luck solving manipulation problems...\");\n    } else {\n      joint_element = controllable_joints_element->FirstChildElement(\"joint\");\n    }\n\n    std::map<Str, JointData> controllable_joints;\n    auto unbounded_limits   = std::make_shared<urdf::JointLimits>();\n    unbounded_limits->lower = -std::numeric_limits<double>::infinity();\n    unbounded_limits->upper = std::numeric_limits<double>::infinity();\n    while (joint_element != nullptr) {\n      auto joint_name       = joint_element->FindAttribute(\"name\")->Value();\n      auto joint_init_value = std::stod(joint_element->FirstChild()->Value());\n      auto& joint_bounds    = model->joints_[joint_name]->type == urdf::Joint::CONTINUOUS ?\n                           unbounded_limits :\n                           model->joints_[joint_name]->limits;\n\n      controllable_joints.emplace(\n      joint_name,\n      JointData{joint_name, joint_bounds->lower, joint_bounds->upper, joint_init_value});\n\n      joint_element = joint_element->NextSiblingElement();\n    }\n\n    // Now that everything is added into the scenegraph, we can make the tree_nodes map for the\n    // robot\n    const auto tree_nodes = sg->make_robot_nodes_map(name_puns);\n\n    // Check base movability\n    auto base_movable =\n    strncmp(robot_node->FirstChildElement(\"movebase\")->FirstChild()->Value(), \"true\", 4) == 0;\n    return std::make_optional<Robot>(\n    tree_nodes, controllable_joints, base_movable, std::move(tf), torso_cfg);\n  }\n}  // namespace\n\nstd::optional<\nstd::tuple<ObjectSet, ObjectSet, Robot, std::shared_ptr<Graph>, std::optional<std::array<Bounds, 3>>>>\nload(const Str& scene_path, const Str& obj_dir) {\n  log->info(\"Loading scene from: {}\", scene_path);\n  tinyxml2::XMLDocument scene_doc;\n  if (scene_doc.LoadFile(scene_path.c_str()) != tinyxml2::XML_SUCCESS) {\n    log->error(\"Failed to load scene! XML parsing error: {}\", scene_doc.ErrorStr());\n    return std::nullopt;\n  }\n\n  log->debug(\"Loaded scene XML! Starting parsing...\");\n\n  auto problem     = scene_doc.RootElement();\n  auto object_node = problem->FirstChildElement(\"objects\")->FirstChild();\n  ObjectSet objects;\n  ObjectSet obstacles;\n  auto scenegraph = std::make_shared<Graph>();\n  if (object_node != nullptr) {\n    while (object_node != nullptr) {\n      auto [obj, eigen_pose] = parse_object(obj_dir, object_node);\n      // To avoid use-after-move\n      auto name = obj.name;\n      Node node(\n      name, Node::Type::FIXED, eigen_pose, Transform3r::Identity(), Vector3r::Zero(), obj.geom);\n      auto& sg_node = scenegraph->add_node(-1, node);\n      obj.node_idx = sg_node.self_idx;\n      if (obj.movable) {\n        objects.emplace(name, std::make_shared<Object>(std::move(obj)));\n        sg_node.is_object = true;\n      } else {\n        obstacles.emplace(name, std::make_shared<Object>(std::move(obj)));\n        sg_node.is_obstacle = true;\n      }\n\n      object_node = object_node->NextSiblingElement(\"obj\");\n    }\n  } else {\n    log->warn(\"No objects!\");\n  }\n\n  log->debug(\"Loaded {} objects\", objects.size());\n\n  // Note: We assume there is only ever a single robot, for now\n  auto robot_node = problem->FirstChildElement(\"robots\")->FirstChild();\n  if (robot_node == nullptr) {\n    log->error(\"No robot found!\");\n    return std::nullopt;\n  }\n\n  auto robot_result = parse_robot(robot_node, scenegraph);\n  if (!robot_result) {\n    log->error(\"Failed to parse robot config!\");\n    return std::nullopt;\n  }\n\n  // scenegraph->add_node(nullptr, std::move(robot_result->second));\n\n  auto* bounds_node = problem->FirstChildElement(\"workspace_bounds\");\n  std::optional<std::array<Bounds, 3>> workspace_bounds = std::nullopt;\n  if (bounds_node != nullptr) {\n    auto* x_bounds_node = bounds_node->FirstChildElement(\"x\");\n    auto* y_bounds_node = bounds_node->FirstChildElement(\"y\");\n    auto* z_bounds_node = bounds_node->FirstChildElement(\"z\");\n    double x_low, x_high, y_low, y_high, z_low, z_high;\n    x_bounds_node->FirstChildElement(\"low\")->QueryDoubleText(&x_low);\n    x_bounds_node->FirstChildElement(\"high\")->QueryDoubleText(&x_high);\n    y_bounds_node->FirstChildElement(\"low\")->QueryDoubleText(&y_low);\n    y_bounds_node->FirstChildElement(\"high\")->QueryDoubleText(&y_high);\n    z_bounds_node->FirstChildElement(\"low\")->QueryDoubleText(&z_low);\n    z_bounds_node->FirstChildElement(\"high\")->QueryDoubleText(&z_high);\n\n    workspace_bounds.emplace(\n    std::array<Bounds, 3>{Bounds(x_low, x_high), Bounds(y_low, y_high), Bounds(z_low, z_high)});\n  }\n\n  return std::make_optional(std::make_tuple(std::move(objects),\n                                            std::move(obstacles),\n                                            std::move(*robot_result),\n                                            std::move(scenegraph),\n                                            std::move(workspace_bounds)));\n}\n}  // namespace input::scene\n", "meta": {"hexsha": "f42d7a42cfbf9eb9b6f357c8e2b6a5f8c8ff6364", "size": 24691, "ext": "cc", "lang": "C++", "max_stars_repo_path": "input/scene.cc", "max_stars_repo_name": "MiaoDragon/planet", "max_stars_repo_head_hexsha": "54238a892ddf78ac3327665f4c6859681c6d4142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-10-11T08:23:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T10:23:55.000Z", "max_issues_repo_path": "input/scene.cc", "max_issues_repo_name": "MiaoDragon/planet", "max_issues_repo_head_hexsha": "54238a892ddf78ac3327665f4c6859681c6d4142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "input/scene.cc", "max_forks_repo_name": "MiaoDragon/planet", "max_forks_repo_head_hexsha": "54238a892ddf78ac3327665f4c6859681c6d4142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-17T21:03:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-17T21:03:46.000Z", "avg_line_length": 41.427852349, "max_line_length": 102, "alphanum_fraction": 0.6386537605, "num_tokens": 5909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.15857693660645747}}
{"text": "#include <iostream>\n#include <sstream>\n\n#include <boost/archive/iterators/base64_from_binary.hpp>\n#include <boost/archive/iterators/binary_from_base64.hpp>\n#include <boost/archive/iterators/transform_width.hpp>\n#include <boost/archive/iterators/insert_linebreaks.hpp>\n#include <boost/archive/iterators/ostream_iterator.hpp>\n#include <boost/algorithm/string.hpp>\n//\n#include <boost/archive/iterators/base64_from_binary.hpp>\n#include <boost/uuid/name_generator_sha1.hpp>\n\n//\nnamespace my_base_encode\n{\n    //\n    // ref\n    //   - https://code-examples.net/en/q/6ba0e2\n    //   - https://stackoverflow.com/questions/7053538/how-do-i-encode-a-string-to-base64-using-only-boost\n    //\n    std::string decode_base64(const std::string &val)\n    {\n        using namespace boost::archive::iterators;\n        using base64_txt = boost::archive::iterators::transform_width<\n            binary_from_base64<std::string::const_iterator>, 8, 6>;\n        std::stringstream ss;\n\n        std::copy(\n            base64_txt(val.c_str()),\n            base64_txt(val.c_str() + val.size()),\n            ostream_iterator<char>(ss));\n\n        return ss.str();\n    }\n\n    std::string encode_base64(const std::string &val)\n    {\n        using base64_txt = boost::archive::iterators::base64_from_binary<\n            boost::archive::iterators::transform_width<\n                std::string::const_iterator, 6, 8>>;\n        auto tmp = std::string(base64_txt(std::begin(val)), base64_txt(std::end(val)));\n        return tmp.append((3 - val.size() % 3) % 3, '=');\n    }\n\n    std::string encode_hex(const std::string &val)\n    {\n        static char const _hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};\n        const char *v = val.c_str();\n        int size = val.size();\n        std::string ret(size * 2, ' ');\n        for (int i = 0; i < size; i++)\n        {\n            ret[i * 2] = _hex[(val[i] >> 4) & 0xf];\n            ret[i * 2 + 1] = _hex[(val[i]) & 0xf];\n        }\n        return ret;\n    }\n\n    std::string generate_sha1_string(std::string v)\n    {\n        boost::uuids::detail::sha1 sha1;\n        boost::uuids::detail::sha1::digest_type digest;\n        char sha1string[sizeof(digest) + 1];\n\n        sha1.process_bytes(v.c_str(), v.size());\n        sha1.get_digest(digest);\n\n        char hash[20];\n        for (int i = 0; i < 5; ++i)\n        {\n            const char *tmp = reinterpret_cast<char *>(digest);\n            hash[i * 4] = tmp[i * 4 + 3];\n            hash[i * 4 + 1] = tmp[i * 4 + 2];\n            hash[i * 4 + 2] = tmp[i * 4 + 1];\n            hash[i * 4 + 3] = tmp[i * 4];\n        }\n\n        return encode_hex(std::string(hash, 20));\n    }\n\n    void to_hexchar(unsigned char c, unsigned char &hex1, unsigned char &hex2)\n    {\n        // ref https://gist.github.com/litefeel/1197e5c24eb9ec93d771\n\n        hex1 = c / 16;\n        hex2 = c % 16;\n        hex1 += hex1 <= 9 ? '0' : 'a' - 10;\n        hex2 += hex2 <= 9 ? '0' : 'a' - 10;\n    }\n\n    void from_hexchar(unsigned char hex1, unsigned char hex2, unsigned char &c)\n    {\n        // ref https://gist.github.com/litefeel/1197e5c24eb9ec93d771\n        c = 0;\n        if ('0' <= hex1 <= '9')\n        {\n            c |= (hex1 - '0') << 4;\n        }\n        else\n        {\n            c |= (hex1 - 'a') << 4;\n        }\n        if ('0' <= hex2 <= '9')\n        {\n            c |= (hex2 - '0');\n        }\n        else\n        {\n            c |= (hex2 - 'a');\n        }\n    }\n\n    std::string encode_url(std::string s, bool handled_space, bool handled_2f)\n    {\n        // ref https://gist.github.com/litefeel/1197e5c24eb9ec93d771\n        std::stringstream ss;\n        const char *str = s.c_str();\n        int size = s.size();\n\n        for (size_t i = 0; i < size; i++)\n        {\n            char c = str[i];\n            if ((c >= '0' && c <= '9') ||\n                (c >= 'a' && c <= 'z') ||\n                (c >= 'A' && c <= 'Z') ||\n                c == '-' || c == '_' || c == '.' || c == '!' || c == '~' ||\n                c == '*' || c == '\\'' || c == '(' || c == ')')\n            {\n                ss << c;\n            }\n            else if (handled_space == true && c == ' ')\n            {\n                ss << '+';\n            }\n            else if (handled_2f == true && c == '/')\n            {\n                ss << '/';\n            }\n            else\n            {\n                ss << '%';\n                unsigned char d1, d2;\n                to_hexchar(c, d1, d2);\n                ss << d1;\n                ss << d2;\n            }\n        }\n\n        return ss.str();\n    }\n\n    std::string decode_url(std::string s)\n    {\n        std::stringstream ss;\n        const char *str = s.c_str();\n        int size = s.size();\n\n        for (size_t i = 0; i < size; i++)\n        {\n            char c = str[i];\n            if ((c >= '0' && c <= '9') ||\n                (c >= 'a' && c <= 'z') ||\n                (c >= 'A' && c <= 'Z') ||\n                c == '-' || c == '_' || c == '.' || c == '!' || c == '~' ||\n                c == '*' || c == '\\'' || c == '(' || c == ')')\n            {\n                ss << c;\n            }\n            else if (c == '+')\n            {\n                ss << ' ';\n            }\n            else if (c == '%')\n            {\n                i++;\n                if (!(i + 1 < size))\n                {\n                    break;\n                }\n                const char h1 = i;\n                i++;\n                const char h2 = i;\n                unsigned char out;\n                from_hexchar(h1, h2, out);\n                ss << out;\n            }\n        }\n\n        return ss.str();\n    }\n} // namespace my_base_encode", "meta": {"hexsha": "811d1b86c13e30fb3a2410fcbc0f54d3531777aa", "size": 5639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/my_base_encode.cpp", "max_stars_repo_name": "kyorohiro/torrent_chaser", "max_stars_repo_head_hexsha": "b212d51c96de893b3dd4f0f9ad41f66dced377f5", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-06T07:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T07:38:23.000Z", "max_issues_repo_path": "src/my_base_encode.cpp", "max_issues_repo_name": "kyorohiro/torrent_chaser", "max_issues_repo_head_hexsha": "b212d51c96de893b3dd4f0f9ad41f66dced377f5", "max_issues_repo_licenses": ["BSD-Source-Code"], "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/my_base_encode.cpp", "max_forks_repo_name": "kyorohiro/torrent_chaser", "max_forks_repo_head_hexsha": "b212d51c96de893b3dd4f0f9ad41f66dced377f5", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-03T08:21:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T08:21:39.000Z", "avg_line_length": 29.3697916667, "max_line_length": 118, "alphanum_fraction": 0.4248980316, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.1585769299354326}}
{"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// File generated at Sat 27 Aug 2016 12:50:19\n\n/**\n * @file MSSMNoFVatMGUT_mass_eigenstates.hpp\n *\n * @brief contains class for model with routines needed to solve boundary\n *        value problem using the two_scale solver by solving EWSB\n *        and determine the pole masses and mixings\n *\n * This file was generated at Sat 27 Aug 2016 12:50:19 with FlexibleSUSY\n * 1.5.1 (git commit: 8356bacd26e8aecc6635607a32835d534ea3cf01) and SARAH 4.9.0 .\n */\n\n#ifndef MSSMNoFVatMGUT_MASS_EIGENSTATES_H\n#define MSSMNoFVatMGUT_MASS_EIGENSTATES_H\n\n#include \"MSSMNoFVatMGUT_two_scale_soft_parameters.hpp\"\n#include \"MSSMNoFVatMGUT_physical.hpp\"\n#include \"MSSMNoFVatMGUT_info.hpp\"\n#include \"two_loop_corrections.hpp\"\n#include \"problems.hpp\"\n#include \"config.h\"\n\n#include <iosfwd>\n#include <string>\n\n#ifdef ENABLE_THREADS\n#include <mutex>\n#endif\n\n#include <gsl/gsl_vector.h>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\n/**\n * @class MSSMNoFVatMGUT_mass_eigenstates\n * @brief model class with routines for determing masses and mixinga and EWSB\n */\nclass MSSMNoFVatMGUT_mass_eigenstates : public MSSMNoFVatMGUT_soft_parameters {\npublic:\n   explicit MSSMNoFVatMGUT_mass_eigenstates(const MSSMNoFVatMGUT_input_parameters& input_ = MSSMNoFVatMGUT_input_parameters());\n   virtual ~MSSMNoFVatMGUT_mass_eigenstates();\n\n   /// number of EWSB equations\n   static const std::size_t number_of_ewsb_equations = 2;\n\n   void calculate_DRbar_masses();\n   void calculate_DRbar_parameters();\n   void calculate_pole_masses();\n   void check_pole_masses_for_tachyons();\n   virtual void clear();\n   void clear_DRbar_parameters();\n   Eigen::ArrayXd get_DRbar_masses() const;\n   void do_calculate_sm_pole_masses(bool);\n   bool do_calculate_sm_pole_masses() const;\n   void do_force_output(bool);\n   bool do_force_output() const;\n   void reorder_DRbar_masses();\n   void reorder_pole_masses();\n   void set_ewsb_iteration_precision(double);\n   void set_ewsb_loop_order(unsigned);\n   void set_two_loop_corrections(const Two_loop_corrections&);\n   const Two_loop_corrections& get_two_loop_corrections() const;\n   void set_DRbar_masses(const Eigen::ArrayXd&);\n   void set_number_of_ewsb_iterations(std::size_t);\n   void set_number_of_mass_iterations(std::size_t);\n   std::size_t get_number_of_ewsb_iterations() const;\n   std::size_t get_number_of_mass_iterations() const;\n   void set_pole_mass_loop_order(unsigned);\n   unsigned get_pole_mass_loop_order() const;\n   void set_physical(const MSSMNoFVatMGUT_physical&);\n   double get_ewsb_iteration_precision() const;\n   double get_ewsb_loop_order() const;\n   const MSSMNoFVatMGUT_physical& get_physical() const;\n   MSSMNoFVatMGUT_physical& get_physical();\n   const Problems<MSSMNoFVatMGUT_info::NUMBER_OF_PARTICLES>& get_problems() const;\n   Problems<MSSMNoFVatMGUT_info::NUMBER_OF_PARTICLES>& get_problems();\n   int solve_ewsb_tree_level();\n   int solve_ewsb_one_loop();\n   int solve_ewsb();            ///< solve EWSB at ewsb_loop_order level\n\n   void calculate_spectrum();\n   void clear_problems();\n   std::string name() const;\n   void run_to(double scale, double eps = -1.0);\n   void print(std::ostream& out = std::cout) const;\n   void set_precision(double);\n   double get_precision() const;\n\n\n   double get_MVG() const { return MVG; }\n   double get_MGlu() const { return MGlu; }\n   double get_MFd() const { return MFd; }\n   double get_MFs() const { return MFs; }\n   double get_MFb() const { return MFb; }\n   double get_MFu() const { return MFu; }\n   double get_MFc() const { return MFc; }\n   double get_MFt() const { return MFt; }\n   double get_MFve() const { return MFve; }\n   double get_MFvm() const { return MFvm; }\n   double get_MFvt() const { return MFvt; }\n   double get_MFe() const { return MFe; }\n   double get_MFm() const { return MFm; }\n   double get_MFtau() const { return MFtau; }\n   double get_MSveL() const { return MSveL; }\n   double get_MSvmL() const { return MSvmL; }\n   double get_MSvtL() const { return MSvtL; }\n   const Eigen::Array<double,2,1>& get_MSd() const { return MSd; }\n   double get_MSd(int i) const { return MSd(i); }\n   const Eigen::Array<double,2,1>& get_MSu() const { return MSu; }\n   double get_MSu(int i) const { return MSu(i); }\n   const Eigen::Array<double,2,1>& get_MSe() const { return MSe; }\n   double get_MSe(int i) const { return MSe(i); }\n   const Eigen::Array<double,2,1>& get_MSm() const { return MSm; }\n   double get_MSm(int i) const { return MSm(i); }\n   const Eigen::Array<double,2,1>& get_MStau() const { return MStau; }\n   double get_MStau(int i) const { return MStau(i); }\n   const Eigen::Array<double,2,1>& get_MSs() const { return MSs; }\n   double get_MSs(int i) const { return MSs(i); }\n   const Eigen::Array<double,2,1>& get_MSc() const { return MSc; }\n   double get_MSc(int i) const { return MSc(i); }\n   const Eigen::Array<double,2,1>& get_MSb() const { return MSb; }\n   double get_MSb(int i) const { return MSb(i); }\n   const Eigen::Array<double,2,1>& get_MSt() const { return MSt; }\n   double get_MSt(int i) const { return MSt(i); }\n   const Eigen::Array<double,2,1>& get_Mhh() const { return Mhh; }\n   double get_Mhh(int i) const { return Mhh(i); }\n   const Eigen::Array<double,2,1>& get_MAh() const { return MAh; }\n   double get_MAh(int i) const { return MAh(i); }\n   const Eigen::Array<double,2,1>& get_MHpm() const { return MHpm; }\n   double get_MHpm(int i) const { return MHpm(i); }\n   const Eigen::Array<double,4,1>& get_MChi() const { return MChi; }\n   double get_MChi(int i) const { return MChi(i); }\n   const Eigen::Array<double,2,1>& get_MCha() const { return MCha; }\n   double get_MCha(int i) const { return MCha(i); }\n   double get_MVWm() const { return MVWm; }\n   double get_MVP() const { return MVP; }\n   double get_MVZ() const { return MVZ; }\n\n   \n   Eigen::Array<double,1,1> get_MChargedHiggs() const;\n\n   Eigen::Array<double,1,1> get_MPseudoscalarHiggs() const;\n\n   const Eigen::Matrix<double,2,2>& get_ZD() const { return ZD; }\n   double get_ZD(int i, int k) const { return ZD(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZU() const { return ZU; }\n   double get_ZU(int i, int k) const { return ZU(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZE() const { return ZE; }\n   double get_ZE(int i, int k) const { return ZE(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZM() const { return ZM; }\n   double get_ZM(int i, int k) const { return ZM(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZTau() const { return ZTau; }\n   double get_ZTau(int i, int k) const { return ZTau(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZS() const { return ZS; }\n   double get_ZS(int i, int k) const { return ZS(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZC() const { return ZC; }\n   double get_ZC(int i, int k) const { return ZC(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZB() const { return ZB; }\n   double get_ZB(int i, int k) const { return ZB(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZT() const { return ZT; }\n   double get_ZT(int i, int k) const { return ZT(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZH() const { return ZH; }\n   double get_ZH(int i, int k) const { return ZH(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZA() const { return ZA; }\n   double get_ZA(int i, int k) const { return ZA(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZP() const { return ZP; }\n   double get_ZP(int i, int k) const { return ZP(i,k); }\n   const Eigen::Matrix<std::complex<double>,4,4>& get_ZN() const { return ZN; }\n   const std::complex<double>& get_ZN(int i, int k) const { return ZN(i,k); }\n   const Eigen::Matrix<std::complex<double>,2,2>& get_UM() const { return UM; }\n   const std::complex<double>& get_UM(int i, int k) const { return UM(i,k); }\n   const Eigen::Matrix<std::complex<double>,2,2>& get_UP() const { return UP; }\n   const std::complex<double>& get_UP(int i, int k) const { return UP(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZZ() const { return ZZ; }\n   double get_ZZ(int i, int k) const { return ZZ(i,k); }\n\n   void set_PhaseGlu(std::complex<double> PhaseGlu_) { PhaseGlu = PhaseGlu_; }\n   std::complex<double> get_PhaseGlu() const { return PhaseGlu; }\n\n   double get_mass_matrix_VG() const;\n   void calculate_MVG();\n   double get_mass_matrix_Glu() const;\n   void calculate_MGlu();\n   double get_mass_matrix_Fd() const;\n   void calculate_MFd();\n   double get_mass_matrix_Fs() const;\n   void calculate_MFs();\n   double get_mass_matrix_Fb() const;\n   void calculate_MFb();\n   double get_mass_matrix_Fu() const;\n   void calculate_MFu();\n   double get_mass_matrix_Fc() const;\n   void calculate_MFc();\n   double get_mass_matrix_Ft() const;\n   void calculate_MFt();\n   double get_mass_matrix_Fve() const;\n   void calculate_MFve();\n   double get_mass_matrix_Fvm() const;\n   void calculate_MFvm();\n   double get_mass_matrix_Fvt() const;\n   void calculate_MFvt();\n   double get_mass_matrix_Fe() const;\n   void calculate_MFe();\n   double get_mass_matrix_Fm() const;\n   void calculate_MFm();\n   double get_mass_matrix_Ftau() const;\n   void calculate_MFtau();\n   double get_mass_matrix_SveL() const;\n   void calculate_MSveL();\n   double get_mass_matrix_SvmL() const;\n   void calculate_MSvmL();\n   double get_mass_matrix_SvtL() const;\n   void calculate_MSvtL();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Sd() const;\n   void calculate_MSd();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Su() const;\n   void calculate_MSu();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Se() const;\n   void calculate_MSe();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Sm() const;\n   void calculate_MSm();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Stau() const;\n   void calculate_MStau();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Ss() const;\n   void calculate_MSs();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Sc() const;\n   void calculate_MSc();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Sb() const;\n   void calculate_MSb();\n   Eigen::Matrix<double,2,2> get_mass_matrix_St() const;\n   void calculate_MSt();\n   Eigen::Matrix<double,2,2> get_mass_matrix_hh() const;\n   void calculate_Mhh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Ah() const;\n   void calculate_MAh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Hpm() const;\n   void calculate_MHpm();\n   Eigen::Matrix<double,4,4> get_mass_matrix_Chi() const;\n   void calculate_MChi();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Cha() const;\n   void calculate_MCha();\n   double get_mass_matrix_VWm() const;\n   void calculate_MVWm();\n   Eigen::Matrix<double,2,2> get_mass_matrix_VPVZ() const;\n   void calculate_MVPVZ();\n\n   double get_ewsb_eq_hh_1() const;\n   double get_ewsb_eq_hh_2() const;\n\n   std::complex<double> CpUSdconjUSdVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSdconjUSdconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSdconjUSdconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSdconjUSdconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUSdconjUSdconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSdconjUSdAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSdconjUSdhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdSdAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdSdhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdSuHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSdVGSd(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSdVPSd(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSdVZSd(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSdVWmSu(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSdFuChaPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSdFuChaPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSdFdChiPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSdFdChiPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSdGluFdPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpconjUSdGluFdPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUSuconjUSuVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSuconjUSuconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSuconjUSuconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSuconjUSuconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUSuconjUSuconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSuconjUSuAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSuconjUSuhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuconjHpmSd(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuSuAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSuSuhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSubarChaFdPR(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpconjUSubarChaFdPL(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpconjUSuconjVWmSd(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSuVGSu(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSuVPSu(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSuVZSu(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSuFuChiPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSuFuChiPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSuGluFuPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpconjUSuGluFuPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUSeconjUSeVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSeconjUSeconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSeconjUSeconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSeconjUSeconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUSeconjUSeconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   double CpconjUSeVWmSveL(unsigned gO2) const;\n   std::complex<double> CpUSeconjUSeAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSeconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSeconjUSehhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeSeAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeSehh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSeSveLHpm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSeVPSe(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSeVZSe(unsigned gO2, unsigned gI2) const;\n   double CpconjUSeFveChaPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjUSeFveChaPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpconjUSeFeChiPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSeFeChiPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSmconjUSmconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSmconjUSmconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSmconjUSmconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUSmconjUSmconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   double CpconjUSmVWmSvmL(unsigned gO2) const;\n   std::complex<double> CpUSmconjUSmAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSmconjUSmhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSmSmAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSmSmhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSmSvmLHpm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSmVPSm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSmVZSm(unsigned gO2, unsigned gI2) const;\n   double CpconjUSmFvmChaPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjUSmFvmChaPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpconjUSmFmChiPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSmFmChiPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUStauconjUStauconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUStauconjUStauconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUStauconjUStauconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUStauconjUStauconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   double CpconjUStauVWmSvtL(unsigned gO2) const;\n   std::complex<double> CpUStauconjUStauAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStauconjUStauhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUStauStauAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUStauStauhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUStauSvtLHpm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUStauVPStau(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUStauVZStau(unsigned gO2, unsigned gI2) const;\n   double CpconjUStauFvtChaPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjUStauFvtChaPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpconjUStauFtauChiPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUStauFtauChiPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSsconjUSsconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSsconjUSsconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSsconjUSsconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUSsconjUSsconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSsconjUSsAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSsconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSsconjUSshhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSsScHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSsSsAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSsSshh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSsVWmSc(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSsVGSs(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSsVPSs(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSsVZSs(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSsFcChaPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSsFcChaPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSsFsChiPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSsFsChiPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSsGluFsPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpconjUSsGluFsPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUScconjUScVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUScconjUScconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUScconjUScconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUScconjUScconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUScconjUScconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUScconjUScAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUScconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUScconjUSchhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUScconjHpmSs(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUScScAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUScSchh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUScbarChaFsPR(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpconjUScbarChaFsPL(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpconjUScVGSc(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUScVPSc(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUScVZSc(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUScconjVWmSs(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUScFcChiPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUScFcChiPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUScGluFcPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpconjUScGluFcPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUSbconjUSbVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSbconjUSbconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSbconjUSbconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSbconjUSbconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUSbconjUSbconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUSbconjUSbAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUSbconjUSbhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSbSbAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSbSbhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSbStHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUSbVGSb(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSbVPSb(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSbVZSb(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSbVWmSt(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUSbFtChaPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSbFtChaPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSbFbChiPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSbFbChiPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUSbGluFbPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpconjUSbGluFbPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUStconjUStVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUStconjUStconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUStconjUStconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUStconjUStconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   double CpUStconjUStconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUStconjUStAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUStconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUStconjUSthhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUStconjHpmSb(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUStStAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUStSthh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUStbarChaFbPR(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpconjUStbarChaFbPL(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpconjUStconjVWmSb(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUStVGSt(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUStVPSt(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUStVZSt(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUStFtChiPR(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUStFtChiPL(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpconjUStGluFtPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpconjUStGluFtPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUhhVZVZ(unsigned gO2) const;\n   std::complex<double> CpUhhconjSveLSveL(unsigned gO2) const;\n   std::complex<double> CpUhhconjSvmLSvmL(unsigned gO2) const;\n   std::complex<double> CpUhhconjSvtLSvtL(unsigned gO2) const;\n   std::complex<double> CpUhhconjVWmVWm(unsigned gO2) const;\n   std::complex<double> CpUhhbargWmgWm(unsigned gO1) const;\n   std::complex<double> CpUhhbargWmCgWmC(unsigned gO1) const;\n   std::complex<double> CpUhhbargZgZ(unsigned gO1) const;\n   std::complex<double> CpUhhUhhVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUhhUhhAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhUhhhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhAhAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjHpmHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSbSb(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjScSc(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSdSd(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSeSe(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSmSm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSsSs(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjStSt(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjStauStau(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhconjSuSu(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhhhhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarChaChaPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhbarChaChaPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhChiChiPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhChiChiPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUhhVZAh(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUhhconjVWmHpm(unsigned gO2, unsigned gI2) const;\n   double CpUhhbarFeFePR(unsigned gO2) const;\n   double CpUhhbarFeFePL(unsigned gO1) const;\n   double CpUhhbarFmFmPR(unsigned gO2) const;\n   double CpUhhbarFmFmPL(unsigned gO1) const;\n   double CpUhhbarFtauFtauPR(unsigned gO2) const;\n   double CpUhhbarFtauFtauPL(unsigned gO1) const;\n   double CpUhhbarFbFbPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpUhhbarFbFbPL(unsigned gO1, unsigned , unsigned ) const;\n   double CpUhhbarFcFcPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpUhhbarFcFcPL(unsigned gO1, unsigned , unsigned ) const;\n   double CpUhhbarFdFdPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpUhhbarFdFdPL(unsigned gO1, unsigned , unsigned ) const;\n   double CpUhhbarFsFsPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpUhhbarFsFsPL(unsigned gO1, unsigned , unsigned ) const;\n   double CpUhhbarFtFtPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpUhhbarFtFtPL(unsigned gO1, unsigned , unsigned ) const;\n   double CpUhhbarFuFuPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpUhhbarFuFuPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbargWmgWm(unsigned gO1) const;\n   std::complex<double> CpUAhbargWmCgWmC(unsigned gO1) const;\n   std::complex<double> CpUAhUAhVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUAhUAhconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUAhUAhconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUAhUAhconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUAhUAhconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUAhUAhAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhUAhhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjHpmHpm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSbSb(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjScSc(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSdSd(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSeSe(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSmSm(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSsSs(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjStSt(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjStauStau(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhconjSuSu(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhhhAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarChaChaPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhbarChaChaPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhChiChiPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhChiChiPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUAhVZhh(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUAhconjVWmHpm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUAhbarFeFePR(unsigned gO2) const;\n   std::complex<double> CpUAhbarFeFePL(unsigned gO1) const;\n   std::complex<double> CpUAhbarFmFmPR(unsigned gO2) const;\n   std::complex<double> CpUAhbarFmFmPL(unsigned gO1) const;\n   std::complex<double> CpUAhbarFtauFtauPR(unsigned gO2) const;\n   std::complex<double> CpUAhbarFtauFtauPL(unsigned gO1) const;\n   std::complex<double> CpUAhbarFbFbPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFbFbPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFcFcPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFcFcPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFdFdPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFdFdPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFsFsPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFsFsPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFtFtPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFtFtPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFuFuPR(unsigned gO2, unsigned , unsigned ) const;\n   std::complex<double> CpUAhbarFuFuPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpconjUHpmVWmVP(unsigned gO2) const;\n   std::complex<double> CpconjUHpmVZVWm(unsigned gO2) const;\n   std::complex<double> CpconjUHpmbargWmCgZ(unsigned gO1) const;\n   std::complex<double> CpUHpmgWmCbargZ(unsigned gO2) const;\n   std::complex<double> CpconjUHpmbargZgWm(unsigned gO1) const;\n   std::complex<double> CpUHpmgZbargWm(unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmVZVZ(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmconjSveLSveL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmconjSvmLSvmL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmconjSvtLSvtL(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmconjVWmVWm(unsigned gO1, unsigned gO2) const;\n   std::complex<double> CpUHpmconjUHpmAhAh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjHpmHpm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSbSb(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjScSc(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSdSd(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSeSe(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSmSm(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSsSs(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjStSt(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjStauStau(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmconjSuSu(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUHpmconjUHpmhhhh(unsigned gO1, unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmconjScSs(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmconjStSb(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmconjSuSd(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmHpmAh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmHpmhh(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmChiChaPR(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmChiChaPL(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjUHpmconjSveLSe(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmconjSvmLSm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmconjSvtLStau(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVWmAh(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVWmhh(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVPHpm(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpconjUHpmVZHpm(unsigned gO2, unsigned gI2) const;\n   double CpconjUHpmbarFveFePR(unsigned gO2) const;\n   double CpconjUHpmbarFveFePL(unsigned ) const;\n   double CpconjUHpmbarFvmFmPR(unsigned gO2) const;\n   double CpconjUHpmbarFvmFmPL(unsigned ) const;\n   double CpconjUHpmbarFvtFtauPR(unsigned gO2) const;\n   double CpconjUHpmbarFvtFtauPL(unsigned ) const;\n   double CpconjUHpmbarFcFsPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpconjUHpmbarFcFsPL(unsigned gO1, unsigned , unsigned ) const;\n   double CpconjUHpmbarFtFbPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpconjUHpmbarFtFbPL(unsigned gO1, unsigned , unsigned ) const;\n   double CpconjUHpmbarFuFdPR(unsigned gO2, unsigned , unsigned ) const;\n   double CpconjUHpmbarFuFdPL(unsigned gO1, unsigned , unsigned ) const;\n   std::complex<double> CpSveLconjSveLVZVZ() const;\n   double CpSveLconjSveLconjSveLSveL() const;\n   double CpSveLconjSveLconjSvmLSvmL() const;\n   double CpSveLconjSveLconjSvtLSvtL() const;\n   double CpSveLconjSveLconjVWmVWm() const;\n   double CpconjSveLVZSveL() const;\n   std::complex<double> CpSveLconjSveLAhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjSbSb(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjScSc(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjSmSm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjSsSs(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjStSt(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjStauStau(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSveLconjSveLhhhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjSveLconjHpmSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjSveLbarChaFePR(unsigned gI1) const;\n   std::complex<double> CpconjSveLbarChaFePL(unsigned gI1) const;\n   std::complex<double> CpconjSveLSveLhh(unsigned gI2) const;\n   std::complex<double> CpconjSveLconjVWmSe(unsigned gI2) const;\n   double CpconjSveLFveChiPR(unsigned ) const;\n   std::complex<double> CpconjSveLFveChiPL(unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLVZVZ() const;\n   double CpSvmLconjSvmLconjSveLSveL() const;\n   double CpSvmLconjSvmLconjSvmLSvmL() const;\n   double CpSvmLconjSvmLconjSvtLSvtL() const;\n   double CpSvmLconjSvmLconjVWmVWm() const;\n   double CpconjSvmLVZSvmL() const;\n   std::complex<double> CpSvmLconjSvmLAhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjSbSb(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjScSc(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjSmSm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjSsSs(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjStSt(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjStauStau(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvmLconjSvmLhhhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjSvmLconjHpmSm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjSvmLbarChaFmPR(unsigned gI1) const;\n   std::complex<double> CpconjSvmLbarChaFmPL(unsigned gI1) const;\n   std::complex<double> CpconjSvmLSvmLhh(unsigned gI2) const;\n   std::complex<double> CpconjSvmLconjVWmSm(unsigned gI2) const;\n   double CpconjSvmLFvmChiPR(unsigned ) const;\n   std::complex<double> CpconjSvmLFvmChiPL(unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLVZVZ() const;\n   double CpSvtLconjSvtLconjSveLSveL() const;\n   double CpSvtLconjSvtLconjSvmLSvmL() const;\n   double CpSvtLconjSvtLconjSvtLSvtL() const;\n   double CpSvtLconjSvtLconjVWmVWm() const;\n   double CpconjSvtLVZSvtL() const;\n   std::complex<double> CpSvtLconjSvtLAhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjSbSb(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjScSc(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjSmSm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjSsSs(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjStSt(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjStauStau(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpSvtLconjSvtLhhhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjSvtLconjHpmStau(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjSvtLbarChaFtauPR(unsigned gI1) const;\n   std::complex<double> CpconjSvtLbarChaFtauPL(unsigned gI1) const;\n   std::complex<double> CpconjSvtLSvtLhh(unsigned gI2) const;\n   std::complex<double> CpconjSvtLconjVWmStau(unsigned gI2) const;\n   double CpconjSvtLFvtChiPR(unsigned ) const;\n   std::complex<double> CpconjSvtLFvtChiPL(unsigned gI2) const;\n   double CpVZbargWmgWm() const;\n   double CpVZbargWmCgWmC() const;\n   double CpVZconjSveLSveL() const;\n   double CpVZconjSvmLSvmL() const;\n   double CpVZconjSvtLSvtL() const;\n   std::complex<double> CpVZVZconjSveLSveL() const;\n   std::complex<double> CpVZVZconjSvmLSvmL() const;\n   std::complex<double> CpVZVZconjSvtLSvtL() const;\n   double CpVZconjVWmVWm() const;\n   double CpVZbarFeFePL() const;\n   double CpVZbarFeFePR() const;\n   double CpVZbarFmFmPL() const;\n   double CpVZbarFmFmPR() const;\n   double CpVZbarFtauFtauPL() const;\n   double CpVZbarFtauFtauPR() const;\n   double CpVZbarFveFvePL() const;\n   double CpVZbarFveFvePR() const;\n   double CpVZbarFvmFvmPL() const;\n   double CpVZbarFvmFvmPR() const;\n   double CpVZbarFvtFvtPL() const;\n   double CpVZbarFvtFvtPR() const;\n   std::complex<double> CpVZVZAhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSbSb(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjScSc(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSmSm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSsSs(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjStSt(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjStauStau(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZhhhh(unsigned gI1, unsigned gI2) const;\n   double CpVZconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSbSb(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjScSc(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSmSm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSsSs(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjStSt(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjStauStau(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZhhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZbarChaChaPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZbarChaChaPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZChiChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZChiChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZVZhh(unsigned gI2) const;\n   std::complex<double> CpVZconjVWmHpm(unsigned gI2) const;\n   double CpVZbarFbFbPL(unsigned , unsigned ) const;\n   double CpVZbarFbFbPR(unsigned , unsigned ) const;\n   double CpVZbarFcFcPL(unsigned , unsigned ) const;\n   double CpVZbarFcFcPR(unsigned , unsigned ) const;\n   double CpVZbarFdFdPL(unsigned , unsigned ) const;\n   double CpVZbarFdFdPR(unsigned , unsigned ) const;\n   double CpVZbarFsFsPL(unsigned , unsigned ) const;\n   double CpVZbarFsFsPR(unsigned , unsigned ) const;\n   double CpVZbarFtFtPL(unsigned , unsigned ) const;\n   double CpVZbarFtFtPR(unsigned , unsigned ) const;\n   double CpVZbarFuFuPL(unsigned , unsigned ) const;\n   double CpVZbarFuFuPR(unsigned , unsigned ) const;\n   double CpVZVZconjVWmVWm1() const;\n   double CpVZVZconjVWmVWm2() const;\n   double CpVZVZconjVWmVWm3() const;\n   double CpconjVWmbargPgWm() const;\n   double CpconjVWmbargWmCgP() const;\n   double CpconjVWmbargWmCgZ() const;\n   double CpconjVWmbargZgWm() const;\n   double CpVWmconjVWmconjSveLSveL() const;\n   double CpVWmconjVWmconjSvmLSvmL() const;\n   double CpVWmconjVWmconjSvtLSvtL() const;\n   double CpconjVWmVWmVP() const;\n   double CpconjVWmVZVWm() const;\n   double CpconjVWmbarFveFePL() const;\n   double CpconjVWmbarFveFePR() const;\n   double CpconjVWmbarFvmFmPL() const;\n   double CpconjVWmbarFvmFmPR() const;\n   double CpconjVWmbarFvtFtauPL() const;\n   double CpconjVWmbarFvtFtauPR() const;\n   std::complex<double> CpVWmconjVWmAhAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjHpmHpm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSbSb(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjScSc(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSdSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSeSe(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSmSm(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSsSs(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjStSt(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjStauStau(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmconjSuSu(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVWmconjVWmhhhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmconjScSs(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmconjStSb(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmconjSuSd(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmHpmAh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmHpmhh(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmChiChaPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmChiChaPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjVWmVPHpm(unsigned gI2) const;\n   std::complex<double> CpconjVWmVWmhh(unsigned gI2) const;\n   std::complex<double> CpconjVWmVZHpm(unsigned gI2) const;\n   std::complex<double> CpconjVWmconjSveLSe(unsigned gI2) const;\n   std::complex<double> CpconjVWmconjSvmLSm(unsigned gI2) const;\n   std::complex<double> CpconjVWmconjSvtLStau(unsigned gI2) const;\n   double CpconjVWmbarFcFsPL(unsigned , unsigned ) const;\n   double CpconjVWmbarFcFsPR(unsigned , unsigned ) const;\n   double CpconjVWmbarFtFbPL(unsigned , unsigned ) const;\n   double CpconjVWmbarFtFbPR(unsigned , unsigned ) const;\n   double CpconjVWmbarFuFdPL(unsigned , unsigned ) const;\n   double CpconjVWmbarFuFdPR(unsigned , unsigned ) const;\n   double CpVWmconjVWmVPVP1() const;\n   double CpVWmconjVWmVPVP2() const;\n   double CpVWmconjVWmVPVP3() const;\n   double CpVWmconjVWmVZVZ1() const;\n   double CpVWmconjVWmVZVZ2() const;\n   double CpVWmconjVWmVZVZ3() const;\n   double CpVWmconjVWmconjVWmVWm1() const;\n   double CpVWmconjVWmconjVWmVWm2() const;\n   double CpVWmconjVWmconjVWmVWm3() const;\n   std::complex<double> CpUChiconjHpmChaPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjHpmChaPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChihhChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChihhChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSbFbPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjSbFbPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjScFcPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjScFcPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjSdFdPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjSdFdPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjSeFePL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpUChiconjSeFePR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpUChiconjSmFmPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpUChiconjSmFmPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpUChiconjSsFsPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjSsFsPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjStFtPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjStFtPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjStauFtauPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpUChiconjStauFtauPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpUChiconjSuFuPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiconjSuFuPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpUChiChiAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiChiAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpUChiconjVWmChaPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUChiconjVWmChaPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpUChiVZChiPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpUChiVZChiPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpUChiconjSveLFvePL(unsigned gO2) const;\n   double CpUChiconjSveLFvePR(unsigned ) const;\n   std::complex<double> CpUChiconjSvmLFvmPL(unsigned gO2) const;\n   double CpUChiconjSvmLFvmPR(unsigned ) const;\n   std::complex<double> CpUChiconjSvtLFvtPL(unsigned gO2) const;\n   double CpUChiconjSvtLFvtPR(unsigned ) const;\n   std::complex<double> CpbarUChaChaAhPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaChaAhPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChahhChaPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChahhChaPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaHpmChiPL(unsigned gO2, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaHpmChiPR(unsigned gO1, unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarUChaconjScFsPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUChaconjScFsPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUChaconjStFbPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUChaconjStFbPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUChaconjSuFdPL(unsigned gO2, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUChaconjSuFdPR(unsigned gO1, unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarUChaVPChaPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUChaVPChaPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUChaVZChaPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUChaVZChaPL(unsigned gO1, unsigned gI2) const;\n   double CpbarUChabarFveSePL(unsigned , unsigned ) const;\n   std::complex<double> CpbarUChabarFveSePR(unsigned gO1, unsigned gI2) const;\n   double CpbarUChabarFvmSmPL(unsigned , unsigned ) const;\n   std::complex<double> CpbarUChabarFvmSmPR(unsigned gO1, unsigned gI2) const;\n   double CpbarUChabarFvtStauPL(unsigned , unsigned ) const;\n   std::complex<double> CpbarUChabarFvtStauPR(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUChabarFcSsPL(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpbarUChabarFcSsPR(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpbarUChabarFtSbPL(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpbarUChabarFtSbPR(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpbarUChabarFuSdPL(unsigned gO2, unsigned , unsigned gI2) const;\n   std::complex<double> CpbarUChabarFuSdPR(unsigned gO1, unsigned , unsigned gI2) const;\n   std::complex<double> CpbarUChaVWmChiPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUChaVWmChiPL(unsigned gO1, unsigned gI2) const;\n   double CpbarUChaconjSveLFePL(unsigned gO2) const;\n   double CpbarUChaconjSveLFePR(unsigned gO1) const;\n   double CpbarUChaconjSvmLFmPL(unsigned gO2) const;\n   double CpbarUChaconjSvmLFmPR(unsigned gO1) const;\n   double CpbarUChaconjSvtLFtauPL(unsigned gO2) const;\n   double CpbarUChaconjSvtLFtauPR(unsigned gO1) const;\n   std::complex<double> CpGluconjSbFbPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjSbFbPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjScFcPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjScFcPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjSdFdPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjSdFdPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjSsFsPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjSsFsPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjStFtPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjStFtPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjSuFuPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluconjSuFuPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpGluVGGluPR() const;\n   std::complex<double> CpGluVGGluPL() const;\n   std::complex<double> CpbarFdSuChaPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdSuChaPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdSdChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdSdChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFdhhFdPL(unsigned gI1) const;\n   std::complex<double> CpbarFdhhFdPR(unsigned gI1) const;\n   std::complex<double> CpbarFdHpmFuPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFdHpmFuPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFdSdGluPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFdSdGluPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFdFdAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFdFdAhPR(unsigned gI2) const;\n   double CpbarFdVGFdPR() const;\n   double CpbarFdVGFdPL() const;\n   double CpbarFdVPFdPR() const;\n   double CpbarFdVPFdPL() const;\n   double CpbarFdVWmFuPR(unsigned ) const;\n   double CpbarFdVWmFuPL(unsigned ) const;\n   double CpbarFdVZFdPR() const;\n   double CpbarFdVZFdPL() const;\n   std::complex<double> CpbarFsScChaPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFsScChaPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFsSsChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFsSsChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFshhFsPL(unsigned gI1) const;\n   std::complex<double> CpbarFshhFsPR(unsigned gI1) const;\n   std::complex<double> CpbarFsHpmFcPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFsHpmFcPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFsSsGluPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFsSsGluPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFsFsAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFsFsAhPR(unsigned gI2) const;\n   double CpbarFsVGFsPR() const;\n   double CpbarFsVGFsPL() const;\n   double CpbarFsVPFsPR() const;\n   double CpbarFsVPFsPL() const;\n   double CpbarFsVWmFcPR(unsigned ) const;\n   double CpbarFsVWmFcPL(unsigned ) const;\n   double CpbarFsVZFsPR() const;\n   double CpbarFsVZFsPL() const;\n   std::complex<double> CpbarFbStChaPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFbStChaPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFbSbChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFbSbChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFbhhFbPL(unsigned gI1) const;\n   std::complex<double> CpbarFbhhFbPR(unsigned gI1) const;\n   std::complex<double> CpbarFbHpmFtPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFbHpmFtPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFbSbGluPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFbSbGluPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFbFbAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFbFbAhPR(unsigned gI2) const;\n   double CpbarFbVGFbPR() const;\n   double CpbarFbVGFbPL() const;\n   double CpbarFbVPFbPR() const;\n   double CpbarFbVPFbPL() const;\n   double CpbarFbVWmFtPR(unsigned ) const;\n   double CpbarFbVWmFtPL(unsigned ) const;\n   double CpbarFbVZFbPR() const;\n   double CpbarFbVZFbPL() const;\n   std::complex<double> CpbarFubarChaSdPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFubarChaSdPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuSuChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuSuChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFuconjHpmFdPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFuconjHpmFdPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFuhhFuPL(unsigned gI1) const;\n   std::complex<double> CpbarFuhhFuPR(unsigned gI1) const;\n   std::complex<double> CpbarFuSuGluPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFuSuGluPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFuFuAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFuFuAhPR(unsigned gI2) const;\n   double CpbarFuVGFuPR() const;\n   double CpbarFuVGFuPL() const;\n   double CpbarFuVPFuPR() const;\n   double CpbarFuVPFuPL() const;\n   double CpbarFuVZFuPR() const;\n   double CpbarFuVZFuPL() const;\n   double CpbarFuconjVWmFdPR(unsigned ) const;\n   double CpbarFuconjVWmFdPL(unsigned ) const;\n   std::complex<double> CpbarFcbarChaSsPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFcbarChaSsPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFcScChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFcScChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFcconjHpmFsPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFcconjHpmFsPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFchhFcPL(unsigned gI1) const;\n   std::complex<double> CpbarFchhFcPR(unsigned gI1) const;\n   std::complex<double> CpbarFcScGluPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFcScGluPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFcFcAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFcFcAhPR(unsigned gI2) const;\n   double CpbarFcVGFcPR() const;\n   double CpbarFcVGFcPL() const;\n   double CpbarFcVPFcPR() const;\n   double CpbarFcVPFcPL() const;\n   double CpbarFcVZFcPR() const;\n   double CpbarFcVZFcPL() const;\n   double CpbarFcconjVWmFsPR(unsigned ) const;\n   double CpbarFcconjVWmFsPL(unsigned ) const;\n   std::complex<double> CpbarFtbarChaSbPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFtbarChaSbPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFtStChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFtStChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFtconjHpmFbPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFtconjHpmFbPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFthhFtPL(unsigned gI1) const;\n   std::complex<double> CpbarFthhFtPR(unsigned gI1) const;\n   std::complex<double> CpbarFtStGluPL(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFtStGluPR(unsigned gI1, unsigned ) const;\n   std::complex<double> CpbarFtFtAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFtFtAhPR(unsigned gI2) const;\n   double CpbarFtVGFtPR() const;\n   double CpbarFtVGFtPL() const;\n   double CpbarFtVPFtPR() const;\n   double CpbarFtVPFtPL() const;\n   double CpbarFtVZFtPR() const;\n   double CpbarFtVZFtPL() const;\n   double CpbarFtconjVWmFbPR(unsigned ) const;\n   double CpbarFtconjVWmFbPL(unsigned ) const;\n   double CpbarFvebarChaSePL(unsigned , unsigned ) const;\n   std::complex<double> CpbarFvebarChaSePR(unsigned gI1, unsigned gI2) const;\n   double CpbarFveconjHpmFePL(unsigned ) const;\n   std::complex<double> CpbarFveconjHpmFePR(unsigned gI1) const;\n   double CpbarFveSveLChiPL(unsigned ) const;\n   std::complex<double> CpbarFveSveLChiPR(unsigned gI2) const;\n   double CpbarFveVZFvePR() const;\n   double CpbarFveVZFvePL() const;\n   double CpbarFveconjVWmFePR() const;\n   double CpbarFveconjVWmFePL() const;\n   double CpbarFvmbarChaSmPL(unsigned , unsigned ) const;\n   std::complex<double> CpbarFvmbarChaSmPR(unsigned gI1, unsigned gI2) const;\n   double CpbarFvmconjHpmFmPL(unsigned ) const;\n   std::complex<double> CpbarFvmconjHpmFmPR(unsigned gI1) const;\n   double CpbarFvmSvmLChiPL(unsigned ) const;\n   std::complex<double> CpbarFvmSvmLChiPR(unsigned gI2) const;\n   double CpbarFvmVZFvmPR() const;\n   double CpbarFvmVZFvmPL() const;\n   double CpbarFvmconjVWmFmPR() const;\n   double CpbarFvmconjVWmFmPL() const;\n   double CpbarFvtbarChaStauPL(unsigned , unsigned ) const;\n   std::complex<double> CpbarFvtbarChaStauPR(unsigned gI1, unsigned gI2) const;\n   double CpbarFvtconjHpmFtauPL(unsigned ) const;\n   std::complex<double> CpbarFvtconjHpmFtauPR(unsigned gI1) const;\n   double CpbarFvtSvtLChiPL(unsigned ) const;\n   std::complex<double> CpbarFvtSvtLChiPR(unsigned gI2) const;\n   double CpbarFvtVZFvtPR() const;\n   double CpbarFvtVZFvtPL() const;\n   double CpbarFvtconjVWmFtauPR() const;\n   double CpbarFvtconjVWmFtauPL() const;\n   std::complex<double> CpbarFeSeChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFeSeChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFehhFePL(unsigned gI1) const;\n   std::complex<double> CpbarFehhFePR(unsigned gI1) const;\n   std::complex<double> CpbarFeHpmFvePL(unsigned gI1) const;\n   double CpbarFeHpmFvePR(unsigned ) const;\n   std::complex<double> CpbarFeFeAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFeFeAhPR(unsigned gI2) const;\n   std::complex<double> CpbarFeSveLChaPL(unsigned gI2) const;\n   std::complex<double> CpbarFeSveLChaPR(unsigned gI2) const;\n   double CpbarFeVPFePR() const;\n   double CpbarFeVPFePL() const;\n   double CpbarFeVWmFvePR() const;\n   double CpbarFeVWmFvePL() const;\n   double CpbarFeVZFePR() const;\n   double CpbarFeVZFePL() const;\n   std::complex<double> CpbarFmSmChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFmSmChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFmhhFmPL(unsigned gI1) const;\n   std::complex<double> CpbarFmhhFmPR(unsigned gI1) const;\n   std::complex<double> CpbarFmHpmFvmPL(unsigned gI1) const;\n   double CpbarFmHpmFvmPR(unsigned ) const;\n   std::complex<double> CpbarFmFmAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFmFmAhPR(unsigned gI2) const;\n   std::complex<double> CpbarFmSvmLChaPL(unsigned gI2) const;\n   std::complex<double> CpbarFmSvmLChaPR(unsigned gI2) const;\n   double CpbarFmVPFmPR() const;\n   double CpbarFmVPFmPL() const;\n   double CpbarFmVWmFvmPR() const;\n   double CpbarFmVWmFvmPL() const;\n   double CpbarFmVZFmPR() const;\n   double CpbarFmVZFmPL() const;\n   std::complex<double> CpbarFtauStauChiPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFtauStauChiPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpbarFtauhhFtauPL(unsigned gI1) const;\n   std::complex<double> CpbarFtauhhFtauPR(unsigned gI1) const;\n   std::complex<double> CpbarFtauHpmFvtPL(unsigned gI1) const;\n   double CpbarFtauHpmFvtPR(unsigned ) const;\n   std::complex<double> CpbarFtauFtauAhPL(unsigned gI2) const;\n   std::complex<double> CpbarFtauFtauAhPR(unsigned gI2) const;\n   std::complex<double> CpbarFtauSvtLChaPL(unsigned gI2) const;\n   std::complex<double> CpbarFtauSvtLChaPR(unsigned gI2) const;\n   double CpbarFtauVPFtauPR() const;\n   double CpbarFtauVPFtauPL() const;\n   double CpbarFtauVWmFvtPR() const;\n   double CpbarFtauVWmFvtPL() const;\n   double CpbarFtauVZFtauPR() const;\n   double CpbarFtauVZFtauPL() const;\n   std::complex<double> self_energy_Sd(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Su(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Se(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Sm(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Stau(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Ss(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Sc(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Sb(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_St(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_hh(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Ah(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Hpm(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_SveL(double p ) const;\n   std::complex<double> self_energy_SvmL(double p ) const;\n   std::complex<double> self_energy_SvtL(double p ) const;\n   std::complex<double> self_energy_VZ(double p ) const;\n   std::complex<double> self_energy_VWm(double p ) const;\n   std::complex<double> self_energy_Chi_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Chi_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Chi_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Cha_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Cha_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Cha_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Glu_1(double p ) const;\n   std::complex<double> self_energy_Glu_PR(double p ) const;\n   std::complex<double> self_energy_Glu_PL(double p ) const;\n   std::complex<double> self_energy_Fd_1(double p ) const;\n   std::complex<double> self_energy_Fd_PR(double p ) const;\n   std::complex<double> self_energy_Fd_PL(double p ) const;\n   std::complex<double> self_energy_Fs_1(double p ) const;\n   std::complex<double> self_energy_Fs_PR(double p ) const;\n   std::complex<double> self_energy_Fs_PL(double p ) const;\n   std::complex<double> self_energy_Fb_1(double p ) const;\n   std::complex<double> self_energy_Fb_PR(double p ) const;\n   std::complex<double> self_energy_Fb_PL(double p ) const;\n   std::complex<double> self_energy_Fu_1(double p ) const;\n   std::complex<double> self_energy_Fu_PR(double p ) const;\n   std::complex<double> self_energy_Fu_PL(double p ) const;\n   std::complex<double> self_energy_Fc_1(double p ) const;\n   std::complex<double> self_energy_Fc_PR(double p ) const;\n   std::complex<double> self_energy_Fc_PL(double p ) const;\n   std::complex<double> self_energy_Ft_1(double p ) const;\n   std::complex<double> self_energy_Ft_PR(double p ) const;\n   std::complex<double> self_energy_Ft_PL(double p ) const;\n   std::complex<double> self_energy_Fve_1(double p ) const;\n   std::complex<double> self_energy_Fve_PR(double p ) const;\n   std::complex<double> self_energy_Fve_PL(double p ) const;\n   std::complex<double> self_energy_Fvm_1(double p ) const;\n   std::complex<double> self_energy_Fvm_PR(double p ) const;\n   std::complex<double> self_energy_Fvm_PL(double p ) const;\n   std::complex<double> self_energy_Fvt_1(double p ) const;\n   std::complex<double> self_energy_Fvt_PR(double p ) const;\n   std::complex<double> self_energy_Fvt_PL(double p ) const;\n   std::complex<double> self_energy_Fe_1(double p ) const;\n   std::complex<double> self_energy_Fe_PR(double p ) const;\n   std::complex<double> self_energy_Fe_PL(double p ) const;\n   std::complex<double> self_energy_Fm_1(double p ) const;\n   std::complex<double> self_energy_Fm_PR(double p ) const;\n   std::complex<double> self_energy_Fm_PL(double p ) const;\n   std::complex<double> self_energy_Ftau_1(double p ) const;\n   std::complex<double> self_energy_Ftau_PR(double p ) const;\n   std::complex<double> self_energy_Ftau_PL(double p ) const;\n   std::complex<double> self_energy_VZ_heavy(double p ) const;\n   std::complex<double> self_energy_VWm_heavy(double p ) const;\n   std::complex<double> self_energy_Fb_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fb_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fb_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fe_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fe_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fe_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fm_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fm_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fm_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ftau_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ftau_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ftau_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ft_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ft_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ft_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ft_1_heavy(double p ) const;\n   std::complex<double> self_energy_Ft_PR_heavy(double p ) const;\n   std::complex<double> self_energy_Ft_PL_heavy(double p ) const;\n   std::complex<double> tadpole_hh(unsigned gO1) const;\n\n\n   /// calculates the tadpoles at current loop order\n   void tadpole_equations(double[number_of_ewsb_equations]) const;\n\n   void calculate_MTopSquark_3rd_generation(double&, double&, double&) const;\n   void calculate_MBottomSquark_3rd_generation(double&, double&, double&) const;\n   void calculate_MSneutrino_3rd_generation(double&, double&, double&) const;\n   void calculate_MSelectron_3rd_generation(double&, double&, double&) const;\n\n   void self_energy_hh_2loop(double result[3]) const;\n   void self_energy_Ah_2loop(double result[3]) const;\n\n   void tadpole_hh_2loop(double result[2]) const;\n\n\n   void calculate_MVG_pole();\n   void calculate_MGlu_pole();\n   void calculate_MVP_pole();\n   void calculate_MVZ_pole();\n   void calculate_MFd_pole();\n   void calculate_MFs_pole();\n   void calculate_MFb_pole();\n   void calculate_MFu_pole();\n   void calculate_MFc_pole();\n   void calculate_MFt_pole();\n   void calculate_MFve_pole();\n   void calculate_MFvm_pole();\n   void calculate_MFvt_pole();\n   void calculate_MFe_pole();\n   void calculate_MFm_pole();\n   void calculate_MFtau_pole();\n   void calculate_MSveL_pole();\n   void calculate_MSvmL_pole();\n   void calculate_MSvtL_pole();\n   void calculate_MSd_pole();\n   void calculate_MSu_pole();\n   void calculate_MSe_pole();\n   void calculate_MSm_pole();\n   void calculate_MStau_pole();\n   void calculate_MSs_pole();\n   void calculate_MSc_pole();\n   void calculate_MSb_pole();\n   void calculate_MSt_pole();\n   void calculate_Mhh_pole();\n   void calculate_MAh_pole();\n   void calculate_MHpm_pole();\n   void calculate_MChi_pole();\n   void calculate_MCha_pole();\n   void calculate_MVWm_pole();\n   double calculate_MVWm_pole(double);\n   double calculate_MVZ_pole(double);\n\n   double calculate_MFve_DRbar(double) const;\n   double calculate_MFvm_DRbar(double) const;\n   double calculate_MFvt_DRbar(double) const;\n   double calculate_MFe_DRbar(double) const;\n   double calculate_MFm_DRbar(double) const;\n   double calculate_MFtau_DRbar(double) const;\n   double calculate_MFu_DRbar(double) const;\n   double calculate_MFc_DRbar(double) const;\n   double calculate_MFt_DRbar(double) const;\n   double calculate_MFd_DRbar(double) const;\n   double calculate_MFs_DRbar(double) const;\n   double calculate_MFb_DRbar(double) const;\n   double calculate_MVP_DRbar(double);\n   double calculate_MVZ_DRbar(double);\n   double calculate_MVWm_DRbar(double);\n\n   double v() const;\n   double Betax() const;\n   double Alpha() const;\n   double ThetaW() const;\n\n\nprivate:\n   struct EWSB_args {\n      MSSMNoFVatMGUT_mass_eigenstates* model;\n      unsigned ewsb_loop_order;\n   };\n\n#ifdef ENABLE_THREADS\n   struct Thread {\n      typedef void(MSSMNoFVatMGUT_mass_eigenstates::*Memfun_t)();\n      MSSMNoFVatMGUT_mass_eigenstates* model;\n      Memfun_t fun;\n\n      Thread(MSSMNoFVatMGUT_mass_eigenstates* model_, Memfun_t fun_)\n         : model(model_), fun(fun_) {}\n      void operator()() {\n         try {\n            (model->*fun)();\n         } catch (...) {\n            model->thread_exception = std::current_exception();\n         }\n      }\n   };\n#endif\n\n   std::size_t number_of_ewsb_iterations;\n   std::size_t number_of_mass_iterations;\n   unsigned ewsb_loop_order;\n   unsigned pole_mass_loop_order;\n   bool calculate_sm_pole_masses; ///< switch to calculate the pole masses of the Standard Model particles\n   bool force_output;             ///< switch to force output of pole masses\n   double precision;              ///< RG running precision\n   double ewsb_iteration_precision;\n   MSSMNoFVatMGUT_physical physical; ///< contains the pole masses and mixings\n   Problems<MSSMNoFVatMGUT_info::NUMBER_OF_PARTICLES> problems;\n   Two_loop_corrections two_loop_corrections; ///< used 2-loop corrections\n#ifdef ENABLE_THREADS\n   std::exception_ptr thread_exception;\n   static std::mutex mtx_fortran; /// locks fortran functions\n#endif\n\n   int solve_ewsb_iteratively();\n   int solve_ewsb_iteratively(unsigned);\n   int solve_ewsb_iteratively_with(EWSB_solver*, const double[number_of_ewsb_equations]);\n   int solve_ewsb_tree_level_custom();\n   void ewsb_initial_guess(double[number_of_ewsb_equations]);\n   int ewsb_step(double[number_of_ewsb_equations]) const;\n   static int ewsb_step(const gsl_vector*, void*, gsl_vector*);\n   static int tadpole_equations(const gsl_vector*, void*, gsl_vector*);\n   void copy_DRbar_masses_to_pole_masses();\n\n   // Passarino-Veltman loop functions\n   double A0(double) const;\n   double B0(double, double, double) const;\n   double B1(double, double, double) const;\n   double B00(double, double, double) const;\n   double B22(double, double, double) const;\n   double H0(double, double, double) const;\n   double F0(double, double, double) const;\n   double G0(double, double, double) const;\n\n   // DR-bar masses\n   double MVG;\n   double MGlu;\n   double MFd;\n   double MFs;\n   double MFb;\n   double MFu;\n   double MFc;\n   double MFt;\n   double MFve;\n   double MFvm;\n   double MFvt;\n   double MFe;\n   double MFm;\n   double MFtau;\n   double MSveL;\n   double MSvmL;\n   double MSvtL;\n   Eigen::Array<double,2,1> MSd;\n   Eigen::Array<double,2,1> MSu;\n   Eigen::Array<double,2,1> MSe;\n   Eigen::Array<double,2,1> MSm;\n   Eigen::Array<double,2,1> MStau;\n   Eigen::Array<double,2,1> MSs;\n   Eigen::Array<double,2,1> MSc;\n   Eigen::Array<double,2,1> MSb;\n   Eigen::Array<double,2,1> MSt;\n   Eigen::Array<double,2,1> Mhh;\n   Eigen::Array<double,2,1> MAh;\n   Eigen::Array<double,2,1> MHpm;\n   Eigen::Array<double,4,1> MChi;\n   Eigen::Array<double,2,1> MCha;\n   double MVWm;\n   double MVP;\n   double MVZ;\n\n   // DR-bar mixing matrices\n   Eigen::Matrix<double,2,2> ZD;\n   Eigen::Matrix<double,2,2> ZU;\n   Eigen::Matrix<double,2,2> ZE;\n   Eigen::Matrix<double,2,2> ZM;\n   Eigen::Matrix<double,2,2> ZTau;\n   Eigen::Matrix<double,2,2> ZS;\n   Eigen::Matrix<double,2,2> ZC;\n   Eigen::Matrix<double,2,2> ZB;\n   Eigen::Matrix<double,2,2> ZT;\n   Eigen::Matrix<double,2,2> ZH;\n   Eigen::Matrix<double,2,2> ZA;\n   Eigen::Matrix<double,2,2> ZP;\n   Eigen::Matrix<std::complex<double>,4,4> ZN;\n   Eigen::Matrix<std::complex<double>,2,2> UM;\n   Eigen::Matrix<std::complex<double>,2,2> UP;\n   Eigen::Matrix<double,2,2> ZZ;\n\n   // phases\n   std::complex<double> PhaseGlu;\n\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMNoFVatMGUT_mass_eigenstates&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "6f06473c0ade54bdb3d254d9198bc7db59e41f64", "size": 89741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_mass_eigenstates.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/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_mass_eigenstates.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/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_mass_eigenstates.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": 61.6776632302, "max_line_length": 127, "alphanum_fraction": 0.7620819915, "num_tokens": 29758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.15857692659992023}}
{"text": "#pragma once\n#include <boost/type_traits/is_detected.hpp>\n#include <cstdint>\n#include <stdexcept>\n#include \"ft/core/Fields.hpp\"\n#include \"ft/core/Requests.hpp\"\n#include \"ft/sbe/SbeTypes.hpp\"\n#include \"toolbox/sys/Time.hpp\"\n\nnamespace ft::tbricks::v1 {\n\n#pragma pack(push, 1)\n\nenum class MessageType: uint8_t {\n    NotAMessage, \n    SubscriptionRequest, \n    SubscriptionCancelRequest, \n    ClosingEvent, \n    MarketData, \n    HeartBeat,\n    SubscriptionRequestBBO,\n    MarketDataBBO\n};\n\nenum  class Phase:  uint8_t {NotSet, Trading, Closed, Halted, Auction};\nenum  class MDStatus:  uint8_t {NotSet, Failed, Pending, Staled, OK};\n\nusing String = sbe::BasicVarString<std::size_t>;\nusing Sequence = std::uint64_t;\n\nstruct Price {\n    double value;\n    bool empty;\n};\n\nstruct Timestamp {\n    std::uint64_t value;\n    Timestamp(core::Timestamp ts)\n    : value(ts.time_since_epoch().count()/1000ul) {}\n    core::Timestamp to_core_timestamp() const {\n        return core::Timestamp{toolbox::Nanos{value*1000ul}};\n    }\n};\n\nstruct SubscriptionPayload {\n#define TB_PADVAL 0\n    TB_FIELD(String, symbol, symbol_);\n#undef  TB_PADVAL\n#define TB_PADVAL TB_PADSIZE(symbol_)\n    TB_FIELD(Sequence, seq, seq_);\n    TB_BYTESIZE(*this)\n#undef TB_PADVAL\n};\n\nstruct SequencePayload {\n#define TB_PADVAL 0\n    TB_FIELD(Sequence, seq, seq_);\n    TB_BYTESIZE(*this)\n#undef TB_PADVAL\n};\n\nstruct MarketDataPayload {\n#define TB_PADVAL 0\n    TB_FIELD(String, symbol, symbol_);\n#undef TB_PADVAL\n#define TB_PADVAL TB_PADSIZE(symbol_)\n    TB_FIELD(Price, bid, bid_);\n    TB_FIELD(Price, ask, ask_);\n    TB_FIELD(Phase, phase, phase_);\n    TB_FIELD(MDStatus, status, status_);\n    TB_FIELD(Timestamp, time, time_);\n    TB_FIELD(Sequence, seq, seq_);\n    TB_BYTESIZE(*this)\n#undef TB_PADVAL\n};\n\ntemplate<std::size_t PadSizeI=0>\nstruct Message {\n    MessageType msgtype_;\n    union {\n        SubscriptionPayload subscription_;\n        MarketDataPayload marketdata_;\n        SequencePayload sequence_;\n    };\n    char data_[PadSizeI];\n\n    auto& msgtype() { return msgtype_; }\n    const auto& msgtype() const { return msgtype_; }\n\n    Message(MessageType msgtype = MessageType::NotAMessage)\n    : msgtype_(msgtype)\n    {}\n\n    const MarketDataPayload& marketdata() const {\n        assert(msgtype_==MessageType::MarketData);\n        return marketdata_;\n    }\n    MarketDataPayload& marketdata() {\n        assert(msgtype_==MessageType::MarketData);\n        return marketdata_;\n    }\n\n    const SubscriptionPayload& subscription() const {\n        assert(msgtype_==MessageType::SubscriptionRequest || msgtype_==MessageType::SubscriptionCancelRequest);\n        return subscription_;\n    }\n    SubscriptionPayload& subscription() {\n        assert(msgtype_==MessageType::SubscriptionRequest || msgtype_==MessageType::SubscriptionCancelRequest);\n        return subscription_;\n    }\n\n    template<std::size_t NewSizeI>\n    Message<NewSizeI>& as_size() {\n        return *reinterpret_cast<Message<NewSizeI>*>(this);\n    }\n\n    std::size_t bytesize() const { \n        switch(msgtype()) {\n            case MessageType::SubscriptionRequest: \n            case MessageType::SubscriptionRequestBBO:\n            case MessageType::SubscriptionCancelRequest:\n                return sizeof(msgtype()) + subscription_.bytesize();\n            case MessageType::MarketData:\n            case MessageType::MarketDataBBO:\n                return sizeof(msgtype()) + marketdata_.bytesize();\n            case MessageType::HeartBeat:\n            case MessageType::ClosingEvent:            \n                return sizeof(msgtype()) + sequence_.bytesize();\n            default: \n                assert(false);\n                return sizeof(msgtype_);\n        }\n    }\n    bool is_valid() {\n        switch(msgtype_) {\n            case MessageType::SubscriptionRequest:\n            case MessageType::SubscriptionCancelRequest: \n            case MessageType::MarketData: \n            case MessageType::MarketDataBBO:            \n            case MessageType::ClosingEvent: \n            case MessageType::HeartBeat:\n                return true;\n            default: return false;\n        }\n    }\n\n    TB_FIELD_FN(Sequence, seq, {\n        switch(msgtype_) {\n            case MessageType::SubscriptionRequest: \n            case MessageType::SubscriptionCancelRequest: \n                return subscription_.seq();\n            case MessageType::MarketData:\n            case MessageType::MarketDataBBO:\n                return marketdata_.seq();\n            case MessageType::ClosingEvent: \n            case MessageType::HeartBeat:\n                return sequence_.seq();\n            default: throw std::runtime_error(\"bad_msgtype\");\n        }\n    });\n\n    TB_FIELD_FN(String, symbol, {\n        switch(msgtype_) {\n            case MessageType::SubscriptionRequest: \n            case MessageType::SubscriptionRequestBBO:\n            case MessageType::SubscriptionCancelRequest:\n                return subscription_.symbol();\n                break;\n            case MessageType::MarketData:\n            case MessageType::MarketDataBBO:\n                return marketdata_.symbol();\n            default:\n                throw std::runtime_error(\"bad_msgtype\");\n        }\n    }); \n};\n\n#pragma pack(pop)\n} // tbricks::schema::v1", "meta": {"hexsha": "bd732db3619c53cfafef552137cba922e75513d0", "size": 5243, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ft/tbricks/TbricksSchemaV1.hpp", "max_stars_repo_name": "mmitkevich/freeticks-cpp", "max_stars_repo_head_hexsha": "45c30f42856b47c3f2e8ebfd35441d658c6ba00d", "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": "ft/tbricks/TbricksSchemaV1.hpp", "max_issues_repo_name": "mmitkevich/freeticks-cpp", "max_issues_repo_head_hexsha": "45c30f42856b47c3f2e8ebfd35441d658c6ba00d", "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": "ft/tbricks/TbricksSchemaV1.hpp", "max_forks_repo_name": "mmitkevich/freeticks-cpp", "max_forks_repo_head_hexsha": "45c30f42856b47c3f2e8ebfd35441d658c6ba00d", "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.2905027933, "max_line_length": 111, "alphanum_fraction": 0.6387564372, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.15847991475286055}}
{"text": "//\n//  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)\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#define BOOST_LOCALE_SOURCE\n#include \"all_generator.hpp\"\n#include \"cdata.hpp\"\n#include \"time_zone.hpp\"\n#include \"uconv.hpp\"\n\n#include <math.h>\n#include <unicode/calendar.h>\n#include <unicode/gregocal.h>\n#include <unicode/utypes.h>\n\n#include <boost/locale/date_time.hpp>\n#include <boost/locale/date_time_facet.hpp>\n#include <boost/locale/formatting.hpp>\n#include <boost/locale/hold_ptr.hpp>\n#include <boost/thread.hpp>\n#include <iostream>\n#include <memory>\n\nnamespace boost\n{\nnamespace locale\n{\nnamespace impl_icu\n{\n\nstatic void check_and_throw_dt(UErrorCode& e)\n{\n    if (U_FAILURE(e))\n    {\n        throw date_time_error(u_errorName(e));\n    }\n}\nusing period::marks::period_mark;\n\nstatic UCalendarDateFields to_icu(period::marks::period_mark f)\n{\n    using namespace period::marks;\n\n    switch (f)\n    {\n        case era:\n            return UCAL_ERA;\n        case year:\n            return UCAL_YEAR;\n        case extended_year:\n            return UCAL_EXTENDED_YEAR;\n        case month:\n            return UCAL_MONTH;\n        case day:\n            return UCAL_DATE;\n        case day_of_year:\n            return UCAL_DAY_OF_YEAR;\n        case day_of_week:\n            return UCAL_DAY_OF_WEEK;\n        case day_of_week_in_month:\n            return UCAL_DAY_OF_WEEK_IN_MONTH;\n        case day_of_week_local:\n            return UCAL_DOW_LOCAL;\n        case hour:\n            return UCAL_HOUR_OF_DAY;\n        case hour_12:\n            return UCAL_HOUR;\n        case am_pm:\n            return UCAL_AM_PM;\n        case minute:\n            return UCAL_MINUTE;\n        case second:\n            return UCAL_SECOND;\n        case week_of_year:\n            return UCAL_WEEK_OF_YEAR;\n        case week_of_month:\n            return UCAL_WEEK_OF_MONTH;\n        default:\n            throw std::invalid_argument(\"Invalid date_time period type\");\n    }\n}\n\nclass calendar_impl : public abstract_calendar\n{\n  public:\n    calendar_impl(cdata const& dat)\n    {\n        UErrorCode err = U_ZERO_ERROR;\n        calendar_.reset(icu::Calendar::createInstance(dat.locale, err));\n        check_and_throw_dt(err);\n#if U_ICU_VERSION_MAJOR_NUM * 100 + U_ICU_VERSION_MINOR_NUM < 402\n        // workaround old/invalid data, it should be 4 in general\n        calendar_->setMinimalDaysInFirstWeek(4);\n#endif\n        encoding_ = dat.encoding;\n    }\n    calendar_impl(calendar_impl const& other)\n    {\n        calendar_.reset(other.calendar_->clone());\n        encoding_ = other.encoding_;\n    }\n\n    calendar_impl* clone() const\n    {\n        return new calendar_impl(*this);\n    }\n\n    void set_value(period::marks::period_mark p, int value)\n    {\n        calendar_->set(to_icu(p), int32_t(value));\n    }\n\n    int get_value(period::marks::period_mark p, value_type type) const\n    {\n        UErrorCode err = U_ZERO_ERROR;\n        int v = 0;\n        if (p == period::marks::first_day_of_week)\n        {\n            guard l(lock_);\n            v = calendar_->getFirstDayOfWeek(err);\n        }\n        else\n        {\n            UCalendarDateFields uper = to_icu(p);\n            guard l(lock_);\n            switch (type)\n            {\n                case absolute_minimum:\n                    v = calendar_->getMinimum(uper);\n                    break;\n                case actual_minimum:\n                    v = calendar_->getActualMinimum(uper, err);\n                    break;\n                case greatest_minimum:\n                    v = calendar_->getGreatestMinimum(uper);\n                    break;\n                case current:\n                    v = calendar_->get(uper, err);\n                    break;\n                case least_maximum:\n                    v = calendar_->getLeastMaximum(uper);\n                    break;\n                case actual_maximum:\n                    v = calendar_->getActualMaximum(uper, err);\n                    break;\n                case absolute_maximum:\n                    v = calendar_->getMaximum(uper);\n                    break;\n            }\n        }\n        check_and_throw_dt(err);\n        return v;\n    }\n\n    virtual void set_time(posix_time const& p)\n    {\n        double utime = p.seconds * 1000.0 + p.nanoseconds / 1000000.0;\n        UErrorCode code = U_ZERO_ERROR;\n        calendar_->setTime(utime, code);\n        check_and_throw_dt(code);\n    }\n    virtual void normalize()\n    {\n        // Can't call complete() explicitly (protected)\n        // calling get wich calls complete\n        UErrorCode code = U_ZERO_ERROR;\n        calendar_->get(UCAL_YEAR, code);\n        check_and_throw_dt(code);\n    }\n    virtual posix_time get_time() const\n    {\n\n        UErrorCode code = U_ZERO_ERROR;\n        double rtime = 0;\n        {\n            guard l(lock_);\n            rtime = calendar_->getTime(code);\n        }\n        check_and_throw_dt(code);\n        rtime /= 1000.0;\n        double secs = floor(rtime);\n        posix_time res;\n        res.seconds = static_cast<int64_t>(secs);\n        res.nanoseconds = static_cast<uint32_t>((rtime - secs) / 1e9);\n        if (res.nanoseconds > 999999999)\n            res.nanoseconds = 999999999;\n        return res;\n    }\n    virtual void set_option(calendar_option_type opt, int /*v*/)\n    {\n        switch (opt)\n        {\n            case is_gregorian:\n                throw date_time_error(\n                    \"is_gregorian is not settable options for calendar\");\n            case is_dst:\n                throw date_time_error(\n                    \"is_dst is not settable options for calendar\");\n            default:;\n        }\n    }\n    virtual int get_option(calendar_option_type opt) const\n    {\n        switch (opt)\n        {\n            case is_gregorian:\n                return dynamic_cast<icu::GregorianCalendar const*>(\n                           calendar_.get()) != 0;\n            case is_dst:\n            {\n                guard l(lock_);\n                UErrorCode err = U_ZERO_ERROR;\n                bool res = (calendar_->inDaylightTime(err) != 0);\n                check_and_throw_dt(err);\n                return res;\n            }\n            default:\n                return 0;\n        }\n    }\n    virtual void adjust_value(period::marks::period_mark p, update_type u,\n                              int difference)\n    {\n        UErrorCode err = U_ZERO_ERROR;\n        switch (u)\n        {\n            case move:\n                calendar_->add(to_icu(p), difference, err);\n                break;\n            case roll:\n                calendar_->roll(to_icu(p), difference, err);\n                break;\n        }\n        check_and_throw_dt(err);\n    }\n    virtual int difference(abstract_calendar const* other_ptr,\n                           period::marks::period_mark p) const\n    {\n        UErrorCode err = U_ZERO_ERROR;\n        double other_time = 0;\n        //\n        // fieldDifference has side effect of moving calendar (WTF?)\n        // So we clone it for performing this operation\n        //\n        hold_ptr<icu::Calendar> self(calendar_->clone());\n\n        calendar_impl const* other_cal =\n            dynamic_cast<calendar_impl const*>(other_ptr);\n        if (other_cal)\n        {\n            guard l(other_cal->lock_);\n            other_time = other_cal->calendar_->getTime(err);\n            check_and_throw_dt(err);\n        }\n        else\n        {\n            posix_time p = other_ptr->get_time();\n            other_time = p.seconds * 1000.0 + p.nanoseconds / 1000000.0;\n        }\n\n        int diff = self->fieldDifference(other_time, to_icu(p), err);\n\n        check_and_throw_dt(err);\n        return diff;\n    }\n    virtual void set_timezone(std::string const& tz)\n    {\n        calendar_->adoptTimeZone(get_time_zone(tz));\n    }\n    virtual std::string get_timezone() const\n    {\n        icu::UnicodeString tz;\n        calendar_->getTimeZone().getID(tz);\n        icu_std_converter<char> cvt(encoding_);\n        return cvt.std(tz);\n    }\n    virtual bool same(abstract_calendar const* other) const\n    {\n        calendar_impl const* oc = dynamic_cast<calendar_impl const*>(other);\n        if (!oc)\n            return false;\n        return calendar_->isEquivalentTo(*oc->calendar_) != 0;\n    }\n\n  private:\n    typedef boost::unique_lock<boost::mutex> guard;\n    mutable boost::mutex lock_;\n    std::string encoding_;\n    hold_ptr<icu::Calendar> calendar_;\n};\n\nclass icu_calendar_facet : public calendar_facet\n{\n  public:\n    icu_calendar_facet(cdata const& d, size_t refs = 0) :\n        calendar_facet(refs), data_(d)\n    {\n    }\n    virtual abstract_calendar* create_calendar() const\n    {\n        return new calendar_impl(data_);\n    }\n\n  private:\n    cdata data_;\n};\n\nstd::locale create_calendar(std::locale const& in, cdata const& d)\n{\n    return std::locale(in, new icu_calendar_facet(d));\n}\n\n} // namespace impl_icu\n} // namespace locale\n} // namespace boost\n\n// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4\n", "meta": {"hexsha": "42af9053eeb4ae922d46f7e3de89eed02875dedb", "size": 9035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/locale/src/icu/date_time.cpp", "max_stars_repo_name": "sotaoverride/backup", "max_stars_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/locale/src/icu/date_time.cpp", "max_issues_repo_name": "sotaoverride/backup", "max_issues_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/locale/src/icu/date_time.cpp", "max_forks_repo_name": "sotaoverride/backup", "max_forks_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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.1464174455, "max_line_length": 76, "alphanum_fraction": 0.5698948533, "num_tokens": 2018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.1584799082100682}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <memory>\n\n#include \"../motionmodule.hh\"\n#include \"../../Smoother/LinearSmoother/linearsmoother.hh\"\n#include \"../../WalkAttitude/walkattitude.hh\"\n\nnamespace bold\n{\n  class Balance;\n  class WalkEngine;\n  template<typename> class Setting;\n\n  enum class WalkStatus : uchar\n  {\n    Stopped = 0,\n    Starting = 1,\n    Walking = 2,\n    Stabilising = 3\n  };\n\n  std::string getWalkStatusName(WalkStatus status);\n\n  class WalkModule : public MotionModule\n  {\n  public:\n    WalkModule(std::shared_ptr<MotionTaskScheduler> scheduler);\n    ~WalkModule() override = default;\n\n    void step(std::shared_ptr<JointSelection> const& selectedJoints) override;\n\n    void applyHead(HeadSection* head) override;\n    void applyArms(ArmSection* arms) override;\n    void applyLegs(LegSection* legs) override;\n\n    /** Slow walking to a stop and stabilise.\n     */\n    void stop();\n\n    /** Stop walking abruptly. Likely unstable.\n     *\n     * Call stop instead to have walking stop smoothly.\n     */\n    void stopImmediately();\n\n    bool isRunning() const { return !d_immediateStopRequested && d_status != WalkStatus::Stopped; }\n\n    WalkStatus getStatus() const { return d_status; }\n\n    /**\n     * Set the direction of motion, where positive X is in the forwards\n     * direction, and positive Y is to the left. The length of the vector\n     * determines the velocity of motion (unspecified units).\n     *\n     * Note that the same value will result in different speeds in the X and Y\n     * axes.\n     */\n    void setMoveDir(double x, double y);\n\n    void setMoveDir(Eigen::Vector2d const& dir)\n    {\n      setMoveDir(dir.x(), dir.y());\n    }\n\n    /**\n     * Set the rate of turning, where positive values turn right (clockwise)\n     * and negative values turn left (counter-clockwise) (unspecified units).\n     */\n    void setTurnAngle(double turnSpeed);\n\n  private:\n    WalkModule(const WalkModule&) = delete;\n    WalkModule& operator=(const WalkModule&) = delete;\n\n    void start();\n\n    std::shared_ptr<WalkEngine> d_walkEngine;\n    std::shared_ptr<Balance> d_balance;\n\n    Setting<int>* d_stabilisationTimeMillis;\n    int d_stabilisationCycleCount;\n    int d_stabilisationCyclesRemaining;\n\n    LinearSmoother d_xAmpSmoother;\n    LinearSmoother d_yAmpSmoother;\n    LinearSmoother d_turnAmpSmoother;\n    LinearSmoother d_hipPitchSmoother;\n    WalkAttitude d_attitude;\n    Setting<bool>* d_isParalysed;\n\n    bool d_turnAngleSet;\n    bool d_moveDirSet;\n    bool d_immediateStopRequested;\n    WalkStatus d_status;\n  };\n}\n", "meta": {"hexsha": "654b25ec62da2d02eb45cef61f7ea1afa0847e27", "size": 2545, "ext": "hh", "lang": "C++", "max_stars_repo_path": "MotionModule/WalkModule/walkmodule.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": "MotionModule/WalkModule/walkmodule.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": "MotionModule/WalkModule/walkmodule.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": 25.7070707071, "max_line_length": 99, "alphanum_fraction": 0.6911591356, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.15847990821006816}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_STERE_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_STERE_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// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017-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// 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// 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/config.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_tsfn.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct stere {};\n    struct ups {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace stere\n    {\n            static const double EPS10 = 1.e-10;\n            static const double TOL = 1.e-8;\n            static const int NITER = 8;\n            static const double CONV = 1.e-10;\n            static const int S_POLE = 0;\n            static const int N_POLE = 1;\n            static const int OBLIQ = 2;\n            static const int EQUIT = 3;\n\n            template <typename T>\n            struct par_stere\n            {\n                T   phits;\n                T   sinX1;\n                T   cosX1;\n                T   akm1;\n                int mode;\n            };\n\n            template <typename T>\n            inline T ssfn_(T const& phit, T sinphi, T const& eccen)\n            {\n                sinphi *= eccen;\n                return (tan (.5 * (geometry::math::half_pi<T>() + phit)) *\n                   pow((1. - sinphi) / (1. + sinphi), .5 * eccen));\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_stere_ellipsoid : public base_t_fi<base_stere_ellipsoid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_stere<CalculationType> m_proj_parm;\n\n                inline base_stere_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_stere_ellipsoid<CalculationType, Parameters>,\n                     CalculationType, Parameters>(*this, par) {}\n\n                // FORWARD(e_forward)  ellipsoid\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                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n\n                    CalculationType coslam, sinlam, sinX=0.0, cosX=0.0, X, A, sinphi;\n\n                    coslam = cos(lp_lon);\n                    sinlam = sin(lp_lon);\n                    sinphi = sin(lp_lat);\n                    if (this->m_proj_parm.mode == OBLIQ || this->m_proj_parm.mode == EQUIT) {\n                        sinX = sin(X = 2. * atan(ssfn_(lp_lat, sinphi, this->m_par.e)) - HALFPI);\n                        cosX = cos(X);\n                    }\n                    switch (this->m_proj_parm.mode) {\n                    case OBLIQ:\n                        A = this->m_proj_parm.akm1 / (this->m_proj_parm.cosX1 * (1. + this->m_proj_parm.sinX1 * sinX +\n                           this->m_proj_parm.cosX1 * cosX * coslam));\n                        xy_y = A * (this->m_proj_parm.cosX1 * sinX - this->m_proj_parm.sinX1 * cosX * coslam);\n                        goto xmul;\n                    case EQUIT:\n                        A = this->m_proj_parm.akm1 / (1. + cosX * coslam);\n                        xy_y = A * sinX;\n                xmul:\n                        xy_x = A * cosX;\n                        break;\n                    case S_POLE:\n                        lp_lat = -lp_lat;\n                        coslam = - coslam;\n                        sinphi = -sinphi;\n                        BOOST_FALLTHROUGH;\n                    case N_POLE:\n                        xy_x = this->m_proj_parm.akm1 * pj_tsfn(lp_lat, sinphi, this->m_par.e);\n                        xy_y = - xy_x * coslam;\n                        break;\n                    }\n                    xy_x = xy_x * sinlam;\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\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                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n\n                    CalculationType cosphi, sinphi, tp=0.0, phi_l=0.0, rho, halfe=0.0, halfpi=0.0;\n                    int i;\n\n                    rho = boost::math::hypot(xy_x, xy_y);\n                    switch (this->m_proj_parm.mode) {\n                    case OBLIQ:\n                    case EQUIT:\n                        cosphi = cos( tp = 2. * atan2(rho * this->m_proj_parm.cosX1 , this->m_proj_parm.akm1) );\n                        sinphi = sin(tp);\n                                if( rho == 0.0 )\n                            phi_l = asin(cosphi * this->m_proj_parm.sinX1);\n                                else\n                            phi_l = asin(cosphi * this->m_proj_parm.sinX1 + (xy_y * sinphi * this->m_proj_parm.cosX1 / rho));\n\n                        tp = tan(.5 * (HALFPI + phi_l));\n                        xy_x *= sinphi;\n                        xy_y = rho * this->m_proj_parm.cosX1 * cosphi - xy_y * this->m_proj_parm.sinX1* sinphi;\n                        halfpi = HALFPI;\n                        halfe = .5 * this->m_par.e;\n                        break;\n                    case N_POLE:\n                        xy_y = -xy_y;\n                        BOOST_FALLTHROUGH;\n                    case S_POLE:\n                        phi_l = HALFPI - 2. * atan(tp = - rho / this->m_proj_parm.akm1);\n                        halfpi = -HALFPI;\n                        halfe = -.5 * this->m_par.e;\n                        break;\n                    }\n                    for (i = NITER; i--; phi_l = lp_lat) {\n                        sinphi = this->m_par.e * sin(phi_l);\n                        lp_lat = 2. * atan(tp * pow((1.+sinphi)/(1.-sinphi), halfe)) - halfpi;\n                        if (fabs(phi_l - lp_lat) < CONV) {\n                            if (this->m_proj_parm.mode == S_POLE)\n                                lp_lat = -lp_lat;\n                            lp_lon = (xy_x == 0. && xy_y == 0.) ? 0. : atan2(xy_x, xy_y);\n                            return;\n                        }\n                    }\n                    BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"stere_ellipsoid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_stere_spheroid : public base_t_fi<base_stere_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_stere<CalculationType> m_proj_parm;\n\n                inline base_stere_spheroid(const Parameters& par)\n                    : base_t_fi<base_stere_spheroid<CalculationType, Parameters>,\n                     CalculationType, 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                    static const CalculationType FORTPI = detail::FORTPI<CalculationType>();\n                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n\n                    CalculationType  sinphi, cosphi, coslam, sinlam;\n\n                    sinphi = sin(lp_lat);\n                    cosphi = cos(lp_lat);\n                    coslam = cos(lp_lon);\n                    sinlam = sin(lp_lon);\n                    switch (this->m_proj_parm.mode) {\n                    case EQUIT:\n                        xy_y = 1. + cosphi * coslam;\n                        goto oblcon;\n                    case OBLIQ:\n                        xy_y = 1. + this->m_proj_parm.sinX1 * sinphi + this->m_proj_parm.cosX1 * cosphi * coslam;\n                oblcon:\n                        if (xy_y <= EPS10)\n                            BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                        xy_x = (xy_y = this->m_proj_parm.akm1 / xy_y) * cosphi * sinlam;\n                        xy_y *= (this->m_proj_parm.mode == EQUIT) ? sinphi :\n                           this->m_proj_parm.cosX1 * sinphi - this->m_proj_parm.sinX1 * cosphi * coslam;\n                        break;\n                    case N_POLE:\n                        coslam = - coslam;\n                        lp_lat = - lp_lat;\n                        BOOST_FALLTHROUGH;\n                    case S_POLE:\n                        if (fabs(lp_lat - HALFPI) < TOL)\n                            BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                        xy_x = sinlam * ( xy_y = this->m_proj_parm.akm1 * tan(FORTPI + .5 * lp_lat) );\n                        xy_y *= coslam;\n                        break;\n                    }\n                }\n\n                // INVERSE(s_inverse)  spheroid\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                    CalculationType  c, rh, sinc, cosc;\n\n                    sinc = sin(c = 2. * atan((rh = boost::math::hypot(xy_x, xy_y)) / this->m_proj_parm.akm1));\n                    cosc = cos(c);\n                    lp_lon = 0.;\n                    switch (this->m_proj_parm.mode) {\n                    case EQUIT:\n                        if (fabs(rh) <= EPS10)\n                            lp_lat = 0.;\n                        else\n                            lp_lat = asin(xy_y * sinc / rh);\n                        if (cosc != 0. || xy_x != 0.)\n                            lp_lon = atan2(xy_x * sinc, cosc * rh);\n                        break;\n                    case OBLIQ:\n                        if (fabs(rh) <= EPS10)\n                            lp_lat = this->m_par.phi0;\n                        else\n                            lp_lat = asin(cosc * this->m_proj_parm.sinX1 + xy_y * sinc * this->m_proj_parm.cosX1 / rh);\n                        if ((c = cosc - this->m_proj_parm.sinX1 * sin(lp_lat)) != 0. || xy_x != 0.)\n                            lp_lon = atan2(xy_x * sinc * this->m_proj_parm.cosX1, c * rh);\n                        break;\n                    case N_POLE:\n                        xy_y = -xy_y;\n                        BOOST_FALLTHROUGH;\n                    case S_POLE:\n                        if (fabs(rh) <= EPS10)\n                            lp_lat = this->m_par.phi0;\n                        else\n                            lp_lat = asin(this->m_proj_parm.mode == S_POLE ? - cosc : cosc);\n                        lp_lon = (xy_x == 0. && xy_y == 0.) ? 0. : atan2(xy_x, xy_y);\n                        break;\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"stere_spheroid\";\n                }\n\n            };\n\n            template <typename Parameters, typename T>\n            inline void setup(Parameters& par, par_stere<T>& proj_parm)  /* general initialization */\n            {\n                static const T FORTPI = detail::FORTPI<T>();\n                static const T HALFPI = detail::HALFPI<T>();\n\n                T t;\n\n                if (fabs((t = fabs(par.phi0)) - HALFPI) < EPS10)\n                    proj_parm.mode = par.phi0 < 0. ? S_POLE : N_POLE;\n                else\n                    proj_parm.mode = t > EPS10 ? OBLIQ : EQUIT;\n                proj_parm.phits = fabs(proj_parm.phits);\n                if (par.es != 0.0) {\n                    T X;\n\n                    switch (proj_parm.mode) {\n                    case N_POLE:\n                    case S_POLE:\n                        if (fabs(proj_parm.phits - HALFPI) < EPS10)\n                            proj_parm.akm1 = 2. * par.k0 /\n                               sqrt(pow(1+par.e,1+par.e)*pow(1-par.e,1-par.e));\n                        else {\n                            proj_parm.akm1 = cos(proj_parm.phits) /\n                               pj_tsfn(proj_parm.phits, t = sin(proj_parm.phits), par.e);\n                            t *= par.e;\n                            proj_parm.akm1 /= sqrt(1. - t * t);\n                        }\n                        break;\n                    case EQUIT:\n                        //proj_parm.akm1 = 2. * par.k0;\n                        //break;\n                    case OBLIQ:\n                        t = sin(par.phi0);\n                        X = 2. * atan(ssfn_(par.phi0, t, par.e)) - HALFPI;\n                        t *= par.e;\n                        proj_parm.akm1 = 2. * par.k0 * cos(par.phi0) / sqrt(1. - t * t);\n                        proj_parm.sinX1 = sin(X);\n                        proj_parm.cosX1 = cos(X);\n                        break;\n                    }\n                } else {\n                    switch (proj_parm.mode) {\n                    case OBLIQ:\n                        proj_parm.sinX1 = sin(par.phi0);\n                        proj_parm.cosX1 = cos(par.phi0);\n                        BOOST_FALLTHROUGH;\n                    case EQUIT:\n                        proj_parm.akm1 = 2. * par.k0;\n                        break;\n                    case S_POLE:\n                    case N_POLE:\n                        proj_parm.akm1 = fabs(proj_parm.phits - HALFPI) >= EPS10 ?\n                           cos(proj_parm.phits) / tan(FORTPI - .5 * proj_parm.phits) :\n                           2. * par.k0 ;\n                        break;\n                    }\n                }\n            }\n\n\n            // Stereographic\n            template <typename Parameters, typename T>\n            inline void setup_stere(Parameters& par, par_stere<T>& proj_parm)\n            {\n                static const T HALFPI = detail::HALFPI<T>();\n\n                proj_parm.phits = pj_param(par.params, \"tlat_ts\").i ?\n                        pj_param(par.params, \"rlat_ts\").f : HALFPI;\n                setup(par, proj_parm);\n            }\n\n            // Universal Polar Stereographic\n            template <typename Parameters, typename T>\n            inline void setup_ups(Parameters& par, par_stere<T>& proj_parm)\n            {\n                static const T HALFPI = detail::HALFPI<T>();\n\n                /* International Ellipsoid */\n                par.phi0 = pj_param(par.params, \"bsouth\").i ? -HALFPI: HALFPI;\n                if (!par.es)\n                    BOOST_THROW_EXCEPTION( projection_exception(-34) );\n                par.k0 = .994;\n                par.x0 = 2000000.;\n                par.y0 = 2000000.;\n                proj_parm.phits = HALFPI;\n                par.lam0 = 0.;\n                setup(par, proj_parm);\n            }\n\n    }} // namespace detail::stere\n    #endif // doxygen\n\n    /*!\n        \\brief Stereographic 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         - Azimuthal\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - lat_ts: Latitude of true scale (degrees)\n        \\par Example\n        \\image html ex_stere.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct stere_ellipsoid : public detail::stere::base_stere_ellipsoid<CalculationType, Parameters>\n    {\n        inline stere_ellipsoid(const Parameters& par) : detail::stere::base_stere_ellipsoid<CalculationType, Parameters>(par)\n        {\n            detail::stere::setup_stere(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Stereographic 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         - Azimuthal\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - lat_ts: Latitude of true scale (degrees)\n        \\par Example\n        \\image html ex_stere.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct stere_spheroid : public detail::stere::base_stere_spheroid<CalculationType, Parameters>\n    {\n        inline stere_spheroid(const Parameters& par) : detail::stere::base_stere_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::stere::setup_stere(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Universal Polar Stereographic 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         - Azimuthal\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - south: Denotes southern hemisphere UTM zone (boolean)\n        \\par Example\n        \\image html ex_ups.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct ups_ellipsoid : public detail::stere::base_stere_ellipsoid<CalculationType, Parameters>\n    {\n        inline ups_ellipsoid(const Parameters& par) : detail::stere::base_stere_ellipsoid<CalculationType, Parameters>(par)\n        {\n            detail::stere::setup_ups(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Universal Polar Stereographic 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         - Azimuthal\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - south: Denotes southern hemisphere UTM zone (boolean)\n        \\par Example\n        \\image html ex_ups.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct ups_spheroid : public detail::stere::base_stere_spheroid<CalculationType, Parameters>\n    {\n        inline ups_spheroid(const Parameters& par) : detail::stere::base_stere_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::stere::setup_ups(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::stere, stere_spheroid, stere_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::ups, ups_spheroid, ups_ellipsoid)\n\n        // Factory entry(s)\n        template <typename CalculationType, typename Parameters>\n        class stere_entry : public detail::factory_entry<CalculationType, Parameters>\n        {\n            public :\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\n                {\n                    if (par.es)\n                        return new base_v_fi<stere_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                    else\n                        return new base_v_fi<stere_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        class ups_entry : public detail::factory_entry<CalculationType, Parameters>\n        {\n            public :\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\n                {\n                    if (par.es)\n                        return new base_v_fi<ups_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                    else\n                        return new base_v_fi<ups_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void stere_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"stere\", new stere_entry<CalculationType, Parameters>);\n            factory.add_to_factory(\"ups\", new ups_entry<CalculationType, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_STERE_HPP\n\n", "meta": {"hexsha": "9278902e34df4f3f62d79b0f9828b32dc9cb90e1", "size": 23142, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/stere.hpp", "max_stars_repo_name": "ramcn/gemmx", "max_stars_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2018-08-13T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:37:20.000Z", "max_issues_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/stere.hpp", "max_issues_repo_name": "ramcn/gemmx", "max_issues_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/stere.hpp", "max_forks_repo_name": "ramcn/gemmx", "max_forks_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T12:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:39.000Z", "avg_line_length": 42.3846153846, "max_line_length": 131, "alphanum_fraction": 0.5200501253, "num_tokens": 5105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.15844707555879875}}
{"text": "/*\n * Copyright (C) 2020 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#ifndef RMF_FLEET_ADAPTER__AGV__WAYPOINT_HPP\n#define RMF_FLEET_ADAPTER__AGV__WAYPOINT_HPP\n\n#include <rmf_traffic/Time.hpp>\n\n#include <rmf_utils/impl_ptr.hpp>\n\n#include <Eigen/Geometry>\n\nnamespace rmf_fleet_adapter {\nnamespace agv {\n\n//==============================================================================\nclass Waypoint\n{\npublic:\n\n  /// Constructor\n  ///\n  /// \\param[in] map_name\n  ///   The name of the reference map that the position is on.\n  ///\n  /// \\param[in] position\n  ///   A position along the robot's path where it will (or can) have zero\n  ///   instantaneous velocity. This will usually be a point where the robot\n  ///   needs to turn, or a point that comes before an intersection, so the\n  ///   robot can come to a stop and allow other vehicles to pass. This is a 2D\n  ///   heterogeneous vector. The first two elements refer to translational\n  ///   (x,y) position while the third element is a yaw value in radians.\n  ///\n  /// \\param[in] mandatory_delay\n  ///   A delay that the robot is expected to experience once it arrives at\n  ///   this waypoint. Usually this will be caused by the robots needing to\n  ///   wait for doors to open or lifts to arrive.\n  ///\n  /// \\param[in] yield\n  ///   Whether or not the robot can wait at this point. If yield is false, then\n  ///   the planner will assume that it cannot ask the robot to wait here. If\n  ///   yield is true, then the planner may request that the robot wait here to\n  ///   avoid conflicts with other traffic participants.\n  Waypoint(\n    std::string map_name,\n    Eigen::Vector3d position,\n    rmf_traffic::Duration mandatory_delay = std::chrono::nanoseconds(0),\n    bool yield = true);\n\n  /// Get the map of this Waypoint.\n  const std::string& map_name() const;\n\n  /// Set the map of this Waypoint.\n  Waypoint& map_name(std::string new_map_name);\n\n  /// Get the position of this Waypoint.\n  const Eigen::Vector3d& position() const;\n\n  /// Set the position of this Waypoint.\n  Waypoint& position(Eigen::Vector3d new_position);\n\n  /// Get the mandatory delay associated with this Waypoint.\n  rmf_traffic::Duration mandatory_delay() const;\n\n  /// Set the mandatory delay associated with this Waypoint.\n  Waypoint& mandatory_delay(rmf_traffic::Duration duration);\n\n  /// Get whether the robot can yield here.\n  bool yield() const;\n\n  /// Set whether the robot can yield here.\n  Waypoint& yield(bool on);\n\n  class Implementation;\nprivate:\n  rmf_utils::impl_ptr<Implementation> _pimpl;\n};\n\n} // namespace agv\n} // namespace rmf_fleet_adapter\n\n#endif // RMF_FLEET_ADAPTER__AGV__WAYPOINT_HPP\n", "meta": {"hexsha": "ffa92de74b8cf92af5779d8325b7714e1ee077fb", "size": 3195, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rmf_fleet_adapter/include/rmf_fleet_adapter/agv/Waypoint.hpp", "max_stars_repo_name": "Capstone-S13/rmf_ros2", "max_stars_repo_head_hexsha": "66721dd2ab5a458c050bad154c6a17d8e4b5c8f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T03:03:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:48:41.000Z", "max_issues_repo_path": "rmf_fleet_adapter/include/rmf_fleet_adapter/agv/Waypoint.hpp", "max_issues_repo_name": "Capstone-S13/rmf_ros2", "max_issues_repo_head_hexsha": "66721dd2ab5a458c050bad154c6a17d8e4b5c8f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 147.0, "max_issues_repo_issues_event_min_datetime": "2021-03-09T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T11:26:58.000Z", "max_forks_repo_path": "rmf_fleet_adapter/include/rmf_fleet_adapter/agv/Waypoint.hpp", "max_forks_repo_name": "Capstone-S13/rmf_ros2", "max_forks_repo_head_hexsha": "66721dd2ab5a458c050bad154c6a17d8e4b5c8f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2021-05-21T06:54:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T10:43:01.000Z", "avg_line_length": 32.9381443299, "max_line_length": 80, "alphanum_fraction": 0.6992175274, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1582520107145203}}
{"text": "#include \"UnlabeledDisagreementLoss.h\"\r\n#include <iostream>\r\n#include <boost/lexical_cast.hpp>\r\n#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\r\n#include \"LearnIt/Eigen/Sparse\"\r\n#include \"ActiveLearning/DataView.h\"\r\n#include \"ActiveLearning/ActiveLearningData.h\"\r\n#include \"ActiveLearning/SmoothedL1.h\"\r\n\r\nusing Eigen::VectorXd;\r\nusing Eigen::SparseVector;\r\n\r\nUnlabeledDisagreementLoss::UnlabeledDisagreementLoss(InferenceDataView_ptr view1, \r\n\t\tInferenceDataView_ptr view2, ActiveLearningData_ptr alData,\r\n\t\tdouble whenAnnotatedLossWeight, double whenUnannotatedLossWeight,\r\n\t\tLoss lossFunc) \r\n: _data1(view1), _data2(view2), _alData(alData), \r\n_whenAnnotatedLossWeight(whenAnnotatedLossWeight),\r\n_whenUnannotatedLossWeight(whenUnannotatedLossWeight),\r\n_lossFunc(lossFunc) {}\r\n\r\ndouble UnlabeledDisagreementLoss::operator()(VectorXd& gradient,\r\n\t\tsize_t thread_idx, size_t n_threads) const {\r\n\tdouble loss = 0.0;\r\n\tdouble dbg = 0.0;\r\n\tfor (unsigned int i=thread_idx; i<_data1->nInstances(); i+=n_threads) {\r\n\t\tif (!_alData->instanceAnnotation(i)) {\r\n\t\t\t\t// 1= slot\r\n\t\t\t\t// 2= sent\r\n\t\t\tSparseVector<double>::InnerIterator it1(_data1->features(i));\r\n\t\t\tSparseVector<double>::InnerIterator it2(_data2->features(i));\r\n\r\n\t\t\t// skip instances where one FV is empty\r\n\t\t\tif (it1 && it2) {\r\n\t\t\t\t// generally, we want to penalize disagreement more when\r\n\t\t\t\t// we have an annotation to make us more sure of one of\r\n\t\t\t\t// the models\r\n\t\t\t\tdouble lossWeight = _alData->instanceHasAnnotatedFeature(i)\r\n\t\t\t\t\t? _whenAnnotatedLossWeight : _whenUnannotatedLossWeight;\r\n\r\n\t\t\t\t// we dont take the prior into account when calculating disagreement,\r\n\t\t\t\t// since otherwise the default value for an instance we know nothing\r\n\t\t\t\t// about is rather extreme\r\n\t\t\t\t//double pos1 = _data1.predictionNoPrior(i);\r\n\t\t\t\tdouble pos1 = _data1->prediction(i);\r\n\t\t\t\tdouble neg1 = 1.0 - pos1;\r\n\t\t\t\t//double pos2= _data2.predictionNoPrior(i);\r\n\t\t\t\tdouble pos2= _data2->prediction(i);\r\n\t\t\t\tdouble neg2 = 1.0 - pos2;\r\n\r\n\t\t\t\tif (_lossFunc == SQUARED) {\r\n\t\t\t\t\tdouble diff = pos1 - pos2;\r\n\t\t\t\t\tloss -= lossWeight * (diff)*(diff);\r\n\t\t\t\t\tdouble both_mult = lossWeight * 2.0 * diff;\r\n\t\t\t\t\tdouble mult1 = both_mult*pos1*neg1;\r\n\t\t\t\t\tdouble mult2 = both_mult*pos2*neg2;\r\n\t\t\t\t\tfor (; it1; ++it1) {\r\n\t\t\t\t\t\tgradient(it1.index()) -= mult1*it1.value();\r\n\t\t\t\t\t\t/*if (_debug_gradient) {\r\n\t\t\t\t\t\t_local_gradient(it1.index()) -= mult1*it1.value();\r\n\t\t\t\t\t\t}*/\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfor (; it2; ++it2) {\r\n\t\t\t\t\t\tgradient(it2.index()) += mult2*it2.value();\r\n\t\t\t\t\t\t/*if (_debug_gradient) {\r\n\t\t\t\t\t\t_local_gradient(it2.index()) += mult2*it2.value();\r\n\t\t\t\t\t\t}*/\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (_lossFunc == KL) {\r\n\t\t\t\t\t//_loss -= _lossWeight * (pos1*log(pos1/pos2) + neg1*log(neg1/neg2));\r\n\t\t\t\t\tloss -= lossWeight * (pos1*(log(pos1)-log(pos2)) \r\n\t\t\t\t\t\t+ neg1*(log(neg1)-log(neg2)));\r\n\t\t\t\t\t//double factor1 = -_lossWeight * pos1*neg1*(log((pos1*neg2)/(neg1 * pos2)));\r\n\t\t\t\t\tdouble factor1 = -lossWeight * pos1*neg1*\r\n\t\t\t\t\t\t(log(pos1*neg2) -log(neg1 * pos2));\r\n\t\t\t\t\tdouble factor2 = -lossWeight * (neg1*pos2-pos1*neg2);\r\n\t\t\t\t\r\n\t\t\t\t\tfor (; it1; ++it1) {\r\n\t\t\t\t\t\tgradient(it1.index()) += factor1 * it1.value();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfor (; it2; ++it2) {\r\n\t\t\t\t\t\tgradient(it2.index()) += factor2 * it2.value();\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (_lossFunc == L1) {\r\n\t\t\t\t\tloss += SmoothedL1::SmoothedL1ProbProb(pos1, pos2, \r\n\t\t\t\t\t\t_data1->features(i), _data2->features(i),\r\n\t\t\t\t\t\tgradient, lossWeight);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t_debug_loss = loss;\r\n\treturn loss;\r\n}\r\n\r\nstd::wstring UnlabeledDisagreementLoss::status() const {\r\n\treturn L\"diss_loss = \" + boost::lexical_cast<std::wstring>(_debug_loss);\r\n}\r\n\r\nvoid UnlabeledDisagreementLoss::snapshot() {\r\n}\r\n\r\ndouble UnlabeledDisagreementLoss::forInstance(int inst, \r\n\t\t\t\t\t\t\t\tEigen::SparseVector<double>& gradient) const\r\n{\r\n\tdouble ret = 0.0;\r\n\r\n\tif (!_alData->instanceAnnotation(inst)) {\r\n\t\t// 1= slot\r\n\t\t// 2= sent\r\n\t\tSparseVector<double>::InnerIterator it1(_data1->features(inst));\r\n\t\tSparseVector<double>::InnerIterator it2(_data2->features(inst));\r\n\r\n\t\t// skip instances where one FV is empty\r\n\t\tif (it1 && it2) {\r\n\t\t\tdouble lossWeight = _alData->instanceHasAnnotatedFeature(inst)\r\n\t\t\t\t? _whenAnnotatedLossWeight : _whenUnannotatedLossWeight;\r\n\r\n\t\t\t// we dont take the prior into account when calculating disagreement,\r\n\t\t\t// since otherwise the default value for an instance we know nothing\r\n\t\t\t// about is rather extreme\r\n\t\t\t//double pos1 = _data1.predictionNoPrior(i);\r\n\t\t\tdouble pos1 = _data1->prediction(inst);\r\n\t\t\tdouble neg1 = 1.0 - pos1;\r\n\t\t\t//double pos2= _data2.predictionNoPrior(i);\r\n\t\t\tdouble pos2= _data2->prediction(inst);\r\n\t\t\tdouble neg2 = 1.0 - pos2;\r\n\r\n\t\t\tdouble diff = pos1 - pos2;\r\n\t\t\tret -= lossWeight * (diff)*(diff);\r\n\t\t\tdouble both_mult = lossWeight * 2.0 * diff;\r\n\t\t\tdouble mult1 = both_mult*pos1*neg1;\r\n\t\t\tdouble mult2 = both_mult*pos2*neg2;\r\n\t\t\tfor (; it1; ++it1) {\r\n\t\t\t\tgradient.coeffRef(it1.index()) -= mult1*it1.value();\r\n\t\t\t\t\r\n\t\t\t\t/*if (_debug_gradient) {\r\n\t\t\t\t_local_gradient(it1.index()) -= mult1*it1.value();\r\n\t\t\t\t}*/\r\n\t\t\t}\r\n\t\t\tfor (; it2; ++it2) {\r\n\t\t\t\tgradient.coeffRef(it2.index()) += mult2*it2.value();\r\n\t\t\t\t\r\n\t\t\t\t/*if (_debug_gradient) {\r\n\t\t\t\t_local_gradient(it2.index()) += mult2*it2.value();\r\n\t\t\t\t}*/\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n", "meta": {"hexsha": "fb0ba63e386cbd137ccb9fd3cbc16bfd4e10373f", "size": 5230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LearnIt2Trainer/objectives/UnlabeledDisagreementLoss.cpp", "max_stars_repo_name": "BBN-E/serif", "max_stars_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T19:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:57:00.000Z", "max_issues_repo_path": "src/LearnIt2Trainer/objectives/UnlabeledDisagreementLoss.cpp", "max_issues_repo_name": "BBN-E/serif", "max_issues_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "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/LearnIt2Trainer/objectives/UnlabeledDisagreementLoss.cpp", "max_forks_repo_name": "BBN-E/serif", "max_forks_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "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.1830065359, "max_line_length": 83, "alphanum_fraction": 0.6512428298, "num_tokens": 1552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.15825200747939241}}
{"text": "#include \"extractor/tarjan_scc.hpp\"\n#include \"util/coordinate_calculation.hpp\"\n#include \"util/dynamic_graph.hpp\"\n#include \"util/exception.hpp\"\n#include \"util/fingerprint.hpp\"\n#include \"util/graph_loader.hpp\"\n#include \"util/make_unique.hpp\"\n#include \"util/simple_logger.hpp\"\n#include \"util/static_graph.hpp\"\n#include \"util/typedefs.hpp\"\n\n#include <boost/filesystem.hpp>\n\n#if defined(__APPLE__) || defined(_WIN32)\n#include <gdal.h>\n#include <ogrsf_frmts.h>\n#else\n#include <gdal/gdal.h>\n#include <gdal/ogrsf_frmts.h>\n#endif\n\n#include \"osrm/coordinate.hpp\"\n\n#include <fstream>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace osrm\n{\nnamespace tools\n{\n\nstruct TarjanEdgeData\n{\n    TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {}\n    TarjanEdgeData(unsigned distance, unsigned name_id) : distance(distance), name_id(name_id) {}\n    unsigned distance;\n    unsigned name_id;\n};\n\nusing TarjanGraph = util::StaticGraph<TarjanEdgeData>;\nusing TarjanEdge = TarjanGraph::InputEdge;\n\nvoid deleteFileIfExists(const std::string &file_name)\n{\n    if (boost::filesystem::exists(file_name))\n    {\n        boost::filesystem::remove(file_name);\n    }\n}\n\nstd::size_t loadGraph(const char *path,\n                      std::vector<extractor::QueryNode> &coordinate_list,\n                      std::vector<TarjanEdge> &graph_edge_list)\n{\n    std::ifstream input_stream(path, std::ifstream::in | std::ifstream::binary);\n    if (!input_stream.is_open())\n    {\n        throw util::exception(\"Cannot open osrm file\");\n    }\n\n    // load graph data\n    std::vector<extractor::NodeBasedEdge> edge_list;\n    std::vector<NodeID> traffic_light_node_list;\n    std::vector<NodeID> barrier_node_list;\n\n    auto number_of_nodes = util::loadNodesFromFile(\n        input_stream, barrier_node_list, traffic_light_node_list, coordinate_list);\n\n    util::loadEdgesFromFile(input_stream, edge_list);\n\n    traffic_light_node_list.clear();\n    traffic_light_node_list.shrink_to_fit();\n\n    // Building an node-based graph\n    for (const auto &input_edge : edge_list)\n    {\n        if (input_edge.source == input_edge.target)\n        {\n            continue;\n        }\n\n        if (input_edge.forward)\n        {\n            graph_edge_list.emplace_back(input_edge.source,\n                                         input_edge.target,\n                                         (std::max)(input_edge.weight, 1),\n                                         input_edge.name_id);\n        }\n        if (input_edge.backward)\n        {\n            graph_edge_list.emplace_back(input_edge.target,\n                                         input_edge.source,\n                                         (std::max)(input_edge.weight, 1),\n                                         input_edge.name_id);\n        }\n    }\n\n    return number_of_nodes;\n}\n}\n}\n\nint main(int argc, char *argv[])\n{\n    std::vector<osrm::extractor::QueryNode> coordinate_list;\n    osrm::util::LogPolicy::GetInstance().Unmute();\n\n    // enable logging\n    if (argc < 2)\n    {\n        osrm::util::SimpleLogger().Write(logWARNING) << \"usage:\\n\" << argv[0] << \" <osrm>\";\n        return EXIT_FAILURE;\n    }\n\n    std::vector<osrm::tools::TarjanEdge> graph_edge_list;\n    auto number_of_nodes = osrm::tools::loadGraph(argv[1], coordinate_list, graph_edge_list);\n\n    tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end());\n    const auto graph = std::make_shared<osrm::tools::TarjanGraph>(number_of_nodes, graph_edge_list);\n    graph_edge_list.clear();\n    graph_edge_list.shrink_to_fit();\n\n    osrm::util::SimpleLogger().Write() << \"Starting SCC graph traversal\";\n\n    auto tarjan =\n        osrm::util::make_unique<osrm::extractor::TarjanSCC<osrm::tools::TarjanGraph>>(graph);\n    tarjan->Run();\n    osrm::util::SimpleLogger().Write() << \"identified: \" << tarjan->GetNumberOfComponents()\n                                       << \" many components\";\n    osrm::util::SimpleLogger().Write() << \"identified \" << tarjan->GetSizeOneCount()\n                                       << \" size 1 SCCs\";\n\n    // output\n    TIMER_START(SCC_RUN_SETUP);\n\n    // remove files from previous run if exist\n    osrm::tools::deleteFileIfExists(\"component.dbf\");\n    osrm::tools::deleteFileIfExists(\"component.shx\");\n    osrm::tools::deleteFileIfExists(\"component.shp\");\n\n    OGRRegisterAll();\n\n    const char *psz_driver_name = \"ESRI Shapefile\";\n    auto *po_driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(psz_driver_name);\n    if (nullptr == po_driver)\n    {\n        throw osrm::util::exception(\"ESRI Shapefile driver not available\");\n    }\n    auto *po_datasource = po_driver->CreateDataSource(\"component.shp\", nullptr);\n\n    if (nullptr == po_datasource)\n    {\n        throw osrm::util::exception(\"Creation of output file failed\");\n    }\n\n    auto *po_srs = new OGRSpatialReference();\n    po_srs->importFromEPSG(4326);\n\n    auto *po_layer = po_datasource->CreateLayer(\"component\", po_srs, wkbLineString, nullptr);\n\n    if (nullptr == po_layer)\n    {\n        throw osrm::util::exception(\"Layer creation failed.\");\n    }\n    TIMER_STOP(SCC_RUN_SETUP);\n    osrm::util::SimpleLogger().Write() << \"shapefile setup took \"\n                                       << TIMER_MSEC(SCC_RUN_SETUP) / 1000. << \"s\";\n\n    uint64_t total_network_length = 0;\n    osrm::util::Percent percentage(graph->GetNumberOfNodes());\n    TIMER_START(SCC_OUTPUT);\n    for (const NodeID source : osrm::util::irange(0u, graph->GetNumberOfNodes()))\n    {\n        percentage.PrintIncrement();\n        for (const auto current_edge : graph->GetAdjacentEdgeRange(source))\n        {\n            const auto target = graph->GetTarget(current_edge);\n\n            if (source < target || SPECIAL_EDGEID == graph->FindEdge(target, source))\n            {\n                total_network_length +=\n                    100 * osrm::util::coordinate_calculation::greatCircleDistance(\n                              coordinate_list[source], coordinate_list[target]);\n\n                BOOST_ASSERT(current_edge != SPECIAL_EDGEID);\n                BOOST_ASSERT(source != SPECIAL_NODEID);\n                BOOST_ASSERT(target != SPECIAL_NODEID);\n\n                const unsigned size_of_containing_component =\n                    std::min(tarjan->GetComponentSize(tarjan->GetComponentID(source)),\n                             tarjan->GetComponentSize(tarjan->GetComponentID(target)));\n\n                // edges that end on bollard nodes may actually be in two distinct components\n                if (size_of_containing_component < 1000)\n                {\n                    OGRLineString line_string;\n                    line_string.addPoint(\n                        static_cast<double>(osrm::util::toFloating(coordinate_list[source].lon)),\n                        static_cast<double>(osrm::util::toFloating(coordinate_list[source].lat)));\n                    line_string.addPoint(\n                        static_cast<double>(osrm::util::toFloating(coordinate_list[target].lon)),\n                        static_cast<double>(osrm::util::toFloating(coordinate_list[target].lat)));\n\n                    OGRFeature *po_feature = OGRFeature::CreateFeature(po_layer->GetLayerDefn());\n\n                    po_feature->SetGeometry(&line_string);\n                    if (OGRERR_NONE != po_layer->CreateFeature(po_feature))\n                    {\n                        throw osrm::util::exception(\"Failed to create feature in shapefile.\");\n                    }\n                    OGRFeature::DestroyFeature(po_feature);\n                }\n            }\n        }\n    }\n    OGRSpatialReference::DestroySpatialReference(po_srs);\n    OGRDataSource::DestroyDataSource(po_datasource);\n    TIMER_STOP(SCC_OUTPUT);\n    osrm::util::SimpleLogger().Write()\n        << \"generating output took: \" << TIMER_MSEC(SCC_OUTPUT) / 1000. << \"s\";\n\n    osrm::util::SimpleLogger().Write()\n        << \"total network distance: \" << static_cast<uint64_t>(total_network_length / 100 / 1000.)\n        << \" km\";\n\n    osrm::util::SimpleLogger().Write() << \"finished component analysis\";\n    return EXIT_SUCCESS;\n} catch(...) {\n\n}\n\n", "meta": {"hexsha": "3cf5c3dd6934a182ac217a40b56e8a45dde5b022", "size": 8087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools/components.cpp", "max_stars_repo_name": "beemogmbh/osrm-backend", "max_stars_repo_head_hexsha": "547f29384cb05dde1383d7d364fc7d87eb5d0d1b", "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/tools/components.cpp", "max_issues_repo_name": "beemogmbh/osrm-backend", "max_issues_repo_head_hexsha": "547f29384cb05dde1383d7d364fc7d87eb5d0d1b", "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/tools/components.cpp", "max_forks_repo_name": "beemogmbh/osrm-backend", "max_forks_repo_head_hexsha": "547f29384cb05dde1383d7d364fc7d87eb5d0d1b", "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": 34.5598290598, "max_line_length": 100, "alphanum_fraction": 0.6174106591, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.15825200424426458}}
{"text": "/*!\r\n@file\r\nDefines `boost::hana::Group`.\r\n\r\n@copyright Louis Dionne 2013-2016\r\nDistributed under the Boost Software License, Version 1.0.\r\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#ifndef BOOST_HANA_CONCEPT_GROUP_HPP\r\n#define BOOST_HANA_CONCEPT_GROUP_HPP\r\n\r\n#include <boost/hana/fwd/concept/group.hpp>\r\n\r\n#include <boost/hana/config.hpp>\r\n#include <boost/hana/core/default.hpp>\r\n#include <boost/hana/core/tag_of.hpp>\r\n#include <boost/hana/minus.hpp>\r\n#include <boost/hana/negate.hpp>\r\n\r\n\r\nBOOST_HANA_NAMESPACE_BEGIN\r\n    template <typename G>\r\n    struct Group {\r\n        using Tag = typename tag_of<G>::type;\r\n        static constexpr bool value = !is_default<negate_impl<Tag>>::value ||\r\n                                      !is_default<minus_impl<Tag, Tag>>::value;\r\n    };\r\nBOOST_HANA_NAMESPACE_END\r\n\r\n#endif // !BOOST_HANA_CONCEPT_GROUP_HPP\r\n", "meta": {"hexsha": "88402a17f2b3e9dffc811b5bb7e859a10c01bee7", "size": 895, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/test/lib/boost/boost/hana/concept/group.hpp", "max_stars_repo_name": "kodxana/lib-ledger-core", "max_stars_repo_head_hexsha": "96f04d378b7747e1b80b49da7ae637eb33b23678", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174.0, "max_stars_repo_stars_event_min_datetime": "2016-10-05T19:45:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T18:40:57.000Z", "max_issues_repo_path": "core/test/lib/boost/boost/hana/concept/group.hpp", "max_issues_repo_name": "kodxana/lib-ledger-core", "max_issues_repo_head_hexsha": "96f04d378b7747e1b80b49da7ae637eb33b23678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 91.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T19:32:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-13T09:00:23.000Z", "max_forks_repo_path": "core/test/lib/boost/boost/hana/concept/group.hpp", "max_forks_repo_name": "kodxana/lib-ledger-core", "max_forks_repo_head_hexsha": "96f04d378b7747e1b80b49da7ae637eb33b23678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 73.0, "max_forks_repo_forks_event_min_datetime": "2016-10-05T02:40:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T17:55:40.000Z", "avg_line_length": 27.96875, "max_line_length": 80, "alphanum_fraction": 0.6927374302, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.15825200424426453}}
{"text": "#include \"stdafx.h\"\n\n#include <boost\\test\\unit_test.hpp>\n\n#include <geometry\\geometry.hpp>\n\n\n#include <boost\\gil\\extension\\io_new\\png_all.hpp>\n\nusing namespace boost;\nusing namespace gil;\n//using namespace boost::gil::opencv;\n\ntemplate< typename Geometry, typename View >\nstruct draw {};\n\ntemplate< typename View, typename Point >\nstruct draw< geometry::box< Point >, View > { static void d() {} };\n\n\n\nBOOST_AUTO_TEST_CASE( test_geometry )\n{\n\ttypedef geometry::point_xy<double> P;\n\n\tgeometry::box< P > b( P( 10, 10 )\n\t                    , P( 35, 70 )\n\t                    );\n\n    rgb8_image_t img;\n    int i;\n    //draw( i, view( img ) );\n\n    draw< geometry::box< P >, double >::d();\n    \n\n\n    //write_view( \"..\\\\out\\\\geometry.png\", view( dst ), png_tag() );\n}\n", "meta": {"hexsha": "b40217bf0d6e5008bc53173090c62c973859c612", "size": 764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gil_2/libs/gil/opencv/unit_test/geometry_test.cpp", "max_stars_repo_name": "boost-gil/gil-contributions", "max_stars_repo_head_hexsha": "22c32e6221d0c52a4c4bd46d1395b00fdefbd061", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-19T00:50:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-19T00:50:12.000Z", "max_issues_repo_path": "gil_2/libs/gil/opencv/unit_test/geometry_test.cpp", "max_issues_repo_name": "boost-gil/gil-contributions-archive", "max_issues_repo_head_hexsha": "22c32e6221d0c52a4c4bd46d1395b00fdefbd061", "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": "gil_2/libs/gil/opencv/unit_test/geometry_test.cpp", "max_forks_repo_name": "boost-gil/gil-contributions-archive", "max_forks_repo_head_hexsha": "22c32e6221d0c52a4c4bd46d1395b00fdefbd061", "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": 19.1, "max_line_length": 68, "alphanum_fraction": 0.6151832461, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.15825200100913672}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <string>\n#include <vector>\n\n#include \"boost/filesystem.hpp\"\n#include \"boost/program_options.hpp\"\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/common/transforms.h>\n\n#include \"modules/common/log.h\"\n#include \"modules/localization/msf/common/io/pcl_point_types.h\"\n#include \"modules/localization/msf/common/io/velodyne_utility.h\"\n\nbool ParseCommandLine(int argc, char* argv[],\n                      boost::program_options::variables_map* vm) {\n  boost::program_options::options_description desc(\"Allowd options\");\n  desc.add_options()(\"help\", \"product help message\")\n      (\"pcd_folders\", boost::program_options::value<std::vector<std::string>>()\n                          ->multitoken()\n                          ->composing()\n                          ->required(),\n       \"pcd folders(repeated)\")(\n          \"pose_files\",\n          boost::program_options::value<std::vector<std::string>>()\n              ->multitoken()\n              ->composing()\n              ->required(),\n          \"pose files(repeated)\");\n  try {\n    boost::program_options::store(\n        boost::program_options::parse_command_line(argc, argv, desc), *vm);\n    if (vm->count(\"help\")) {\n      std::cerr << desc << std::endl;\n      return false;\n    }\n    boost::program_options::notify(*vm);\n  } catch (std::exception& e) {\n    std::cerr << \"Error\" << e.what() << std::endl;\n    std::cerr << desc << std::endl;\n    return false;\n  } catch (...) {\n    std::cerr << \"Unknown error!\" << std::endl;\n    return false;\n  }\n  return true;\n}\n\nint main(int argc, char** argv) {\n  boost::program_options::variables_map boost_args;\n  if (!ParseCommandLine(argc, argv, &boost_args)) {\n    std::cerr << \"Parse input command line failed.\" << std::endl;\n    return -1;\n  }\n\n  const std::vector<std::string> pcd_folder_pathes =\n      boost_args[\"pcd_folders\"].as<std::vector<std::string>>();\n  const std::vector<std::string> pose_files =\n      boost_args[\"pose_files\"].as<std::vector<std::string>>();\n  if (pcd_folder_pathes.size() != pose_files.size()) {\n    std::cerr << \"The count of pcd folders is not equal pose files\"\n              << std::endl;\n    return -1;\n  }\n\n  const unsigned int num_trials = pcd_folder_pathes.size();\n\n  // load all poses\n  std::cerr << \"Pcd folders are as follows:\" << std::endl;\n  for (std::size_t i = 0; i < num_trials; ++i) {\n    std::cerr << pcd_folder_pathes[i] << std::endl;\n  }\n  std::vector<std::vector<Eigen::Affine3d>> ieout_poses(num_trials);\n  std::vector<std::vector<double>> time_stamps(num_trials);\n  std::vector<std::vector<unsigned int>> pcd_indices(num_trials);\n  for (std::size_t i = 0; i < pose_files.size(); ++i) {\n    apollo::localization::msf::velodyne::LoadPcdPoses(\n        pose_files[i], &ieout_poses[i], &time_stamps[i], &pcd_indices[i]);\n  }\n\n  Eigen::Affine3d initial_pose_inv;\n\n  pcl::PointCloud<apollo::localization::msf::velodyne::PointXYZIT>::Ptr result_cloud(new pcl::PointCloud<apollo::localization::msf::velodyne::PointXYZIT>);\n\n  for (unsigned int trial = 0; trial < num_trials; ++trial) {\n    for (unsigned int frame_idx = 0; frame_idx < ieout_poses[trial].size();\n         ++frame_idx) {\n      unsigned int trial_frame_idx = frame_idx;\n      const std::vector<Eigen::Affine3d>& poses = ieout_poses[trial];\n\n      apollo::localization::msf::velodyne::VelodyneFrame velodyne_frame;\n      std::string pcd_file_path;\n      std::ostringstream ss;\n      ss << pcd_indices[trial][frame_idx];\n      pcd_file_path = pcd_folder_pathes[trial] + \"/\" + ss.str() + \".pcd\";\n      const Eigen::Affine3d& pcd_pose = poses[trial_frame_idx];\n\n      if (trial_frame_idx == 0) {\n          initial_pose_inv = pcd_pose.inverse();\n      }\n\n      pcl::PointCloud<apollo::localization::msf::velodyne::PointXYZIT>::Ptr cloud(new pcl::PointCloud<apollo::localization::msf::velodyne::PointXYZIT>);\n      if (pcl::io::loadPCDFile(pcd_file_path, *cloud) >= 0) {\n        pcl::transformPointCloud (*cloud, *cloud, pcd_pose);\n        pcl::transformPointCloud (*cloud, *cloud, initial_pose_inv);\n\n        *result_cloud+=*cloud;\n\n      } else {\n        AERROR << \"Failed to load PCD file: \" << pcd_file_path;\n      }\n\n      pcl::io::savePCDFile(\"result_pcd.pcd\", *result_cloud);\n      AERROR << \"File \" << frame_idx << \" out of \" << ieout_poses[trial].size();\n\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "e6f7d055921af7030ab29ad9e887e92fdc4b9223", "size": 4328, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/localization/msf/local_tool/map_creation/huge_point_cloud.cc", "max_stars_repo_name": "DavidSplit/apollo-3.0", "max_stars_repo_head_hexsha": "9f82838e857e4c9146952946cbc34b9f35098deb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-10-11T07:57:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T15:23:41.000Z", "max_issues_repo_path": "modules/localization/msf/local_tool/map_creation/huge_point_cloud.cc", "max_issues_repo_name": "DavidSplit/apollo-3.0", "max_issues_repo_head_hexsha": "9f82838e857e4c9146952946cbc34b9f35098deb", "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": "modules/localization/msf/local_tool/map_creation/huge_point_cloud.cc", "max_forks_repo_name": "DavidSplit/apollo-3.0", "max_forks_repo_head_hexsha": "9f82838e857e4c9146952946cbc34b9f35098deb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T07:57:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T05:13:00.000Z", "avg_line_length": 35.4754098361, "max_line_length": 155, "alphanum_fraction": 0.6312384473, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.15819961971415863}}
{"text": "// Copyright (c) 2011-2013, Pacific Biosciences of California, Inc.\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\n// disclaimer 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\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 Pacific Biosciences 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// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY PACIFIC\n// BIOSCIENCES AND ITS CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL PACIFIC BIOSCIENCES OR ITS\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 AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n// 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\n// SUCH DAMAGE.\n\n// Author: David Alexander\n\n#pragma once\n\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <ConsensusCore/Mutation.hpp>\n#include <ConsensusCore/Features.hpp>\n#include <ConsensusCore/Quiver/QvEvaluator.hpp>\n#include <ConsensusCore/Read.hpp>\n#include <ConsensusCore/Utils.hpp>\n\n#include \"ParameterSettings.hpp\"\n\nusing ConsensusCore::Mutation;\nusing ConsensusCore::MutationType;\nusing ConsensusCore::QvEvaluator;\nusing ConsensusCore::QvModelParams;\nusing ConsensusCore::QvSequenceFeatures;\nusing ConsensusCore::QvRead;\n\ntemplate<typename RNG>\nstd::string\nRandomSequence(RNG& rng, int length)\n{\n    const char* bases = \"ACGT\";\n    boost::random::uniform_int_distribution<> indexDist(0, 3);\n    std::stringstream ss;\n    for (int i = 0; i < length; ++i)\n    {\n        ss << bases[indexDist(rng)];\n    }\n    return ss.str();\n}\n\ntemplate<typename RNG>\nfloat*\nRandomQvArray(RNG& rng, int length)\n{\n    float* array = new float[length];\n    boost::random::uniform_int_distribution<> indexDist(0, 127);\n    for (int i = 0; i < length; ++i)\n    {\n        array[i] = static_cast<float>(indexDist(rng));\n    }\n    return array;\n}\n\ntemplate<typename RNG>\nfloat*\nRandomTagArray(RNG& rng, int length)\n{\n    std::string seq = RandomSequence(rng, length);\n    float* array = new float[length];\n    for (int i = 0; i < length; ++i)\n    {\n        array[i] = static_cast<float>(seq[i]);\n    }\n    return array;\n}\n\ntemplate<typename RNG>\nint\nRandomPoissonDraw(RNG& rng, int mean)\n{\n    boost::random::poisson_distribution<> dist(mean);\n    return dist(rng);\n}\n\ntemplate<typename RNG>\nbool\nRandomBernoulliDraw(RNG& rng, float p)\n{\n    boost::random::bernoulli_distribution<> dist(p);\n    return dist(rng);\n}\n\ntemplate<typename RNG>\nQvEvaluator\nRandomQvEvaluator(RNG& rng, int length)\n{\n    std::string tpl = RandomSequence(rng, length);\n\n    int readLength = RandomPoissonDraw(rng, length);\n    std::string seq = RandomSequence(rng, readLength);\n\n    float* insQv = RandomQvArray(rng, readLength);\n    float* subsQv = RandomQvArray(rng, readLength);\n    float* delQv = RandomQvArray(rng, readLength);\n    float* delTag = RandomTagArray(rng, readLength);\n    float* mergeQv = RandomQvArray(rng, readLength);\n\n    QvSequenceFeatures f(seq, insQv, subsQv, delQv, delTag, mergeQv);\n    QvRead read(f, \"anonymous\", \"unknown\");\n\n    delete[] insQv;\n    delete[] subsQv;\n    delete[] delQv;\n    delete[] delTag;\n    delete[] mergeQv;\n\n    bool pinStart = RandomBernoulliDraw(rng, 0.5);\n    bool pinEnd = RandomBernoulliDraw(rng, 0.5);\n    return QvEvaluator(read, tpl, TestingParams(), pinStart, pinEnd);\n}\n\ntemplate<typename RNG>\nstd::vector<int>\nRandomSampleWithoutReplacement(RNG& rng, int n, int k)\n{\n    // Random sample of k elements from [0..n) without replacement\n    std::vector<int> draws;\n    boost::random::uniform_int_distribution<> indexDist(0, n - 1);\n    while (draws.size() < k) {\n        int draw = indexDist(rng);\n        if (std::find(draws.begin(), draws.end(), draw) == draws.end())\n        {\n            draws.push_back(draw);\n        }\n    }\n}\n\ntypedef boost::mt19937 Rng;\n", "meta": {"hexsha": "14e4b2dd00ee8324094e21d01028b36fa6f73927", "size": 5059, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ConsensusCore/src/Tests/Random.hpp", "max_stars_repo_name": "pb-cdunn/pbccs", "max_stars_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ConsensusCore/src/Tests/Random.hpp", "max_issues_repo_name": "pb-cdunn/pbccs", "max_issues_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "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": "ConsensusCore/src/Tests/Random.hpp", "max_forks_repo_name": "pb-cdunn/pbccs", "max_forks_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "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.6606060606, "max_line_length": 71, "alphanum_fraction": 0.7139750939, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.15796283171162423}}
{"text": "#include <iostream>\n#include <fstream>\n#include <mutex>\n#include <condition_variable>\n#include <queue>\n#include <iostream>\n#include <zlib.h>\n#include <omp.h>\n#include <thread>\n#include <valarray>\n#include <vector>\n#include <iomanip>\n\n#include <boost/program_options.hpp>\n#include <boost/iostreams/device/mapped_file.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/asio.hpp>\n\n#include \"./include/seq.h\"\n#include \"./include/kmer.h\"\n\nusing namespace std;\n\nnamespace po = boost::program_options;\nnamespace bio = boost::iostreams;\nnamespace basio = boost::asio;\n\nmutex mux;\nqueue<string> reads_queue;\ncondition_variable condition;\nvolatile bool terminate_threads;\n\nclass ProgressDisplay\n{\nprivate:\n    int total = 0;\n    int progress = 0;\npublic:\n    ProgressDisplay(int total)\n    {\n        this->total = total;\n    }\n\n    void operator++(int)\n    {\n        this->operator++();\n    }\n\n    void operator++()\n    {\n        this->progress++;\n        this->print();\n    }\n\n    void end()\n    {\n        this->progress=this->total;\n        cout << \"Completed \" << fixed << setprecision(2) << 100.00 << \"%       \" << endl << flush;\n    }\n\n    void print()\n    {\n        float percentage = 100.0 * static_cast<float>(this->progress)/static_cast<float>(this->total);\n        cout << \"Completed \" << fixed << setprecision(2) << percentage << \"%             \\r\" << flush;\n    }\n};\n\nvoid off_load_process(string &output, KmerCounter &kc, int &threads)\n{\n    string seq;\n    vector<string> batch;\n    ofstream outfs(output, ios::out);\n    size_t batch_size;\n\n    while (true)\n    {\n        {\n            unique_lock<mutex> lock(mux);\n\n            while (reads_queue.size() > 0)\n            {\n                seq = reads_queue.front();\n                batch.push_back(seq);\n                reads_queue.pop();\n\n                if (batch.size() == 10000)\n                {\n                    break;\n                }\n            }\n        }\n\n        condition.notify_all();\n\n        if (batch.size() > 0)\n        {\n            batch_size = batch.size();\n            vector<valarray<double>> results(batch_size);\n            ostringstream outss;\n            outss.precision(6);\n            outss << fixed;\n\n#pragma omp parallel for num_threads(threads) schedule(dynamic, 1)\n            for (size_t i = 0; i < batch_size; i++)\n            {\n                results[i] = kc.count_kmers(batch[i]);\n            }\n\n            for (auto dvec : results)\n            {\n                for (size_t j = 0; j < dvec.size(); j++)\n                {\n                    outss << dvec[j];\n                    if (j < dvec.size() - 1)\n                    {\n                        outss << ' ';\n                    }\n                }\n                outss << '\\n';\n            }\n\n            outfs << outss.str();\n            outss.clear();\n\n            results.clear();\n            batch.clear();\n        }\n\n        {\n            unique_lock<mutex> lock(mux);\n            if (terminate_threads && reads_queue.size() == 0)\n            {\n                break;\n            }\n        }\n    }\n\n    outfs.close();\n}\n\nvoid io_thread(SeqReader &reader)\n{\n    Seq seq;\n    int count = 0;\n\n    while (reader.get_seq(seq))\n    {\n        {\n            unique_lock<mutex> lock(mux);\n            condition.wait(lock, [] { return reads_queue.size() < 10000; });\n            reads_queue.push(seq.seq_string);\n        }\n        count++;\n\n        cout << \"Loaded Reads \" << count << \"     \\r\" << flush;\n    }\n\n    cout << endl;\n\n    terminate_threads = true;\n}\n\nvoid run(string &input, string &output, int &ksize, int &threads)\n{\n    SeqReader reader(input);\n    KmerCounter kc(ksize);\n\n    cout << \"Counting sequences\" << endl;\n    size_t total_reads = reader.get_seq_count();\n    cout << total_reads <<  \" sequences found\" << endl;\n    size_t per_line_size = kc.kmer_counts_length * (8 + 1);\n    size_t estimated_file_size = total_reads * per_line_size; // space after each value + newline (9 ASCII chars per value)\n    \n    bio::mapped_file_params params;\n    params.path = output;\n    params.new_file_size = estimated_file_size;\n    params.flags = bio::mapped_file::mapmode::readwrite;\n    bio::mapped_file_sink mmout(params);\n\n    asio::thread_pool pool(threads);\n    ProgressDisplay pd(total_reads);\n    mutex reader_mux;\n\n    for (int _ = 0; _ < threads * 5; _++)\n    {\n        asio::post(pool, [&reader_mux, &estimated_file_size, &reader, &pd, &mmout, &kc, &per_line_size]() {\n            bool has_read = true;\n            Seq seq;\n            auto sptr = mmout.begin();\n\n            while (true)\n            {\n                {\n                    unique_lock<mutex> lock(reader_mux);\n                    has_read = reader.get_seq(seq);\n                    pd++;\n                }\n\n                if (has_read)\n                {\n                    // process the read\n                    valarray<double> dvec = kc.count_kmers(seq.seq_string);\n                    ostringstream outss;\n                    outss.precision(6);\n                    outss << fixed;\n\n                    for (size_t j = 0; j < dvec.size(); j++)\n                    {\n                        outss << dvec[j];\n                        if (j < dvec.size() - 1)\n                        {\n                            outss << ' ';\n                        }\n                    }\n                    outss << '\\n';\n\n                    memcpy(sptr + seq.seq_id * per_line_size, outss.str().c_str(), outss.str().size());\n                }\n                else\n                {\n                    break;\n                }\n            }\n        });\n    }\n    pool.join();\n    mmout.close();\n    pd.end();\n}\n\nint main(int ac, char **av)\n{\n    int ksize, threads;\n    string input, output;\n\n    po::options_description desc(\"Seq2Vec fast sequence vectorization\");\n\n    desc.add_options()(\"help,h\", \"show help message\");\n    desc.add_options()(\"file,f\", po::value<string>(&input)->required(), \"input file path\");\n    desc.add_options()(\"output,o\", po::value<string>(&output)->required(), \"output vectors path\");\n    desc.add_options()(\"k-size,k\", po::value<int>(&ksize)->default_value(3), \"set k-mer size\");\n    desc.add_options()(\"threads,t\", po::value<int>(&threads)->default_value(8), \"set thread count\");\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(ac, av, desc), vm);\n\n    if (vm.count(\"help\") || ac == 1)\n    {\n        cout << desc << \"\\n\";\n        return 1;\n    }\n\n    po::notify(vm);\n\n    cout << \"Starting Seq2Vec sequence vectorization\" << endl;\n    run(input, output, ksize, threads);\n\n    return 0;\n}\n", "meta": {"hexsha": "36b89f20726f898c11fe0ca27302894d50fa38fb", "size": 6573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "anuradhawick/seq2vec", "max_stars_repo_head_hexsha": "4ced909f4046a7aa8ec0562ea85e75d5702054b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-10T02:10:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T06:53:14.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "anuradhawick/seq2vec", "max_issues_repo_head_hexsha": "4ced909f4046a7aa8ec0562ea85e75d5702054b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-29T01:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T00:53:42.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "anuradhawick/seq2vec", "max_forks_repo_head_hexsha": "4ced909f4046a7aa8ec0562ea85e75d5702054b5", "max_forks_repo_licenses": ["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.2807692308, "max_line_length": 123, "alphanum_fraction": 0.5023581318, "num_tokens": 1502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.15777429072011737}}
{"text": "/*\n * beam.cc\n *\n *  Copyright (C) 2013 Diamond Light Source\n *\n *  Author: James Parkhurst\n *\n *  This code is distributed under the BSD license, a copy of which is\n *  included in the root directory of this package.\n */\n#include <boost/python.hpp>\n#include <boost/python/def.hpp>\n#include <string>\n#include <sstream>\n#include <scitbx/constants.h>\n#include <dxtbx/model/beam.h>\n#include <dxtbx/model/boost_python/to_from_dict.h>\n#include <scitbx/array_family/boost_python/flex_wrapper.h>\n\nnamespace dxtbx { namespace model { namespace boost_python {\n\n  using namespace boost::python;\n  using scitbx::deg_as_rad;\n  using scitbx::rad_as_deg;\n\n  std::string beam_to_string(const Beam &beam) {\n    std::stringstream ss;\n    ss << beam;\n    return ss.str();\n  }\n\n  struct BeamPickleSuite : boost::python::pickle_suite {\n    static boost::python::tuple getinitargs(const Beam &obj) {\n      return boost::python::make_tuple(obj.get_sample_to_source_direction(),\n                                       obj.get_wavelength(),\n                                       obj.get_divergence(),\n                                       obj.get_sigma_divergence(),\n                                       obj.get_polarization_normal(),\n                                       obj.get_polarization_fraction(),\n                                       obj.get_flux(),\n                                       obj.get_transmission());\n    }\n\n    static boost::python::tuple getstate(boost::python::object obj) {\n      const Beam &beam = boost::python::extract<const Beam &>(obj)();\n      return boost::python::make_tuple(obj.attr(\"__dict__\"),\n                                       beam.get_s0_at_scan_points());\n    }\n\n    static void setstate(boost::python::object obj, boost::python::tuple state) {\n      Beam &beam = boost::python::extract<Beam &>(obj)();\n      DXTBX_ASSERT(boost::python::len(state) == 2);\n\n      // restore the object's __dict__\n      boost::python::dict d =\n        boost::python::extract<boost::python::dict>(obj.attr(\"__dict__\"))();\n      d.update(state[0]);\n\n      // restore the internal state of the C++ object\n      scitbx::af::const_ref<vec3<double> > s0_list =\n        boost::python::extract<scitbx::af::const_ref<vec3<double> > >(state[1]);\n      beam.set_s0_at_scan_points(s0_list);\n    }\n\n    static bool getstate_manages_dict() {\n      return true;\n    }\n  };\n\n  static Beam *make_beam(vec3<double> sample_to_source,\n                         double wavelength,\n                         double divergence,\n                         double sigma_divergence,\n                         bool deg) {\n    Beam *beam = NULL;\n    if (deg) {\n      beam = new Beam(sample_to_source,\n                      wavelength,\n                      deg_as_rad(divergence),\n                      deg_as_rad(sigma_divergence));\n    } else {\n      beam = new Beam(sample_to_source, wavelength, divergence, sigma_divergence);\n    }\n    return beam;\n  }\n\n  static Beam *make_beam_w_s0(vec3<double> s0,\n                              double divergence,\n                              double sigma_divergence,\n                              bool deg) {\n    Beam *beam = NULL;\n    if (deg) {\n      beam = new Beam(s0, deg_as_rad(divergence), deg_as_rad(sigma_divergence));\n    } else {\n      beam = new Beam(s0, divergence, sigma_divergence);\n    }\n    return beam;\n  }\n\n  static Beam *make_beam_w_all(vec3<double> sample_to_source,\n                               double wavelength,\n                               double divergence,\n                               double sigma_divergence,\n                               vec3<double> polarization_normal,\n                               double polarization_fraction,\n                               double flux,\n                               double transmission,\n                               bool deg) {\n    Beam *beam = NULL;\n    if (deg) {\n      beam = new Beam(sample_to_source,\n                      wavelength,\n                      deg_as_rad(divergence),\n                      deg_as_rad(sigma_divergence),\n                      polarization_normal,\n                      polarization_fraction,\n                      flux,\n                      transmission);\n    } else {\n      beam = new Beam(sample_to_source,\n                      wavelength,\n                      divergence,\n                      sigma_divergence,\n                      polarization_normal,\n                      polarization_fraction,\n                      flux,\n                      transmission);\n    }\n    return beam;\n  }\n\n  static double get_divergence(const Beam &beam, bool deg) {\n    double divergence = beam.get_divergence();\n    return deg ? rad_as_deg(divergence) : divergence;\n  }\n\n  static double get_sigma_divergence(const Beam &beam, bool deg) {\n    double sigma_divergence = beam.get_sigma_divergence();\n    return deg ? rad_as_deg(sigma_divergence) : sigma_divergence;\n  }\n\n  static void set_divergence(Beam &beam, double divergence, bool deg) {\n    beam.set_divergence(deg ? deg_as_rad(divergence) : divergence);\n  }\n\n  static void set_sigma_divergence(Beam &beam, double sigma_divergence, bool deg) {\n    beam.set_sigma_divergence(deg ? deg_as_rad(sigma_divergence) : sigma_divergence);\n  }\n\n  static void rotate_around_origin(Beam &beam,\n                                   vec3<double> axis,\n                                   double angle,\n                                   bool deg) {\n    double angle_rad = deg ? deg_as_rad(angle) : angle;\n    beam.rotate_around_origin(axis, angle_rad);\n  }\n\n  static void Beam_set_s0_at_scan_points_from_tuple(Beam &beam,\n                                                    boost::python::tuple l) {\n    scitbx::af::shared<vec3<double> > s0_list;\n    for (std::size_t i = 0; i < boost::python::len(l); ++i) {\n      vec3<double> s0 = boost::python::extract<vec3<double> >(l[i]);\n      s0_list.push_back(s0);\n    }\n    beam.set_s0_at_scan_points(s0_list.const_ref());\n  }\n\n  static void Beam_set_s0_at_scan_points_from_list(Beam &beam, boost::python::list l) {\n    scitbx::af::shared<vec3<double> > s0_list;\n    for (std::size_t i = 0; i < boost::python::len(l); ++i) {\n      vec3<double> s0 = boost::python::extract<vec3<double> >(l[i]);\n      s0_list.push_back(s0);\n    }\n    beam.set_s0_at_scan_points(s0_list.const_ref());\n  }\n\n  template <>\n  boost::python::dict to_dict<Beam>(const Beam &obj) {\n    boost::python::dict result;\n    result[\"direction\"] = obj.get_sample_to_source_direction();\n    result[\"wavelength\"] = obj.get_wavelength();\n    result[\"divergence\"] = rad_as_deg(obj.get_divergence());\n    result[\"sigma_divergence\"] = rad_as_deg(obj.get_sigma_divergence());\n    result[\"polarization_normal\"] = obj.get_polarization_normal();\n    result[\"polarization_fraction\"] = obj.get_polarization_fraction();\n    result[\"flux\"] = obj.get_flux();\n    result[\"transmission\"] = obj.get_transmission();\n    if (obj.get_num_scan_points() > 0) {\n      boost::python::list l;\n      scitbx::af::shared<vec3<double> > s0_at_scan_points = obj.get_s0_at_scan_points();\n      for (scitbx::af::shared<vec3<double> >::iterator it = s0_at_scan_points.begin();\n           it != s0_at_scan_points.end();\n           ++it) {\n        l.append(boost::python::make_tuple((*it)[0], (*it)[1], (*it)[2]));\n      }\n      result[\"s0_at_scan_points\"] = l;\n    }\n    return result;\n  }\n\n  template <>\n  Beam *from_dict<Beam>(boost::python::dict obj) {\n    Beam *b = new Beam(\n      boost::python::extract<vec3<double> >(obj[\"direction\"]),\n      boost::python::extract<double>(obj[\"wavelength\"]),\n      deg_as_rad(boost::python::extract<double>(obj.get(\"divergence\", 0.0))),\n      deg_as_rad(boost::python::extract<double>(obj.get(\"sigma_divergence\", 0.0))),\n      boost::python::extract<vec3<double> >(\n        obj.get(\"polarization_normal\", vec3<double>(0.0, 1.0, 0.0))),\n      boost::python::extract<double>(obj.get(\"polarization_fraction\", 0.999)),\n      boost::python::extract<double>(obj.get(\"flux\", 0)),\n      boost::python::extract<double>(obj.get(\"transmission\", 1)));\n    if (obj.has_key(\"s0_at_scan_points\")) {\n      boost::python::list s0_at_scan_points =\n        boost::python::extract<boost::python::list>(obj[\"s0_at_scan_points\"]);\n      Beam_set_s0_at_scan_points_from_list(*b, s0_at_scan_points);\n    }\n    return b;\n  }\n\n  void export_beam() {\n    // Export BeamBase\n    class_<BeamBase, boost::noncopyable>(\"BeamBase\", no_init)\n      .def(\"get_sample_to_source_direction\", &BeamBase::get_sample_to_source_direction)\n      .def(\"set_direction\", &BeamBase::set_direction)\n      .def(\"get_wavelength\", &BeamBase::get_wavelength)\n      .def(\"set_wavelength\", &BeamBase::set_wavelength)\n      .def(\"get_s0\", &BeamBase::get_s0)\n      .def(\"set_s0\", &BeamBase::set_s0)\n      .def(\"get_unit_s0\", &BeamBase::get_unit_s0)\n      .def(\"set_unit_s0\", &BeamBase::set_unit_s0)\n      .def(\"get_divergence\", &get_divergence, (arg(\"deg\") = true))\n      .def(\"set_divergence\", &set_divergence, (arg(\"divergence\"), arg(\"deg\") = true))\n      .def(\"get_sigma_divergence\", &get_sigma_divergence, (arg(\"deg\") = true))\n      .def(\"set_sigma_divergence\",\n           &set_sigma_divergence,\n           (arg(\"sigma_divergence\"), arg(\"deg\") = true))\n      .def(\"get_polarization_normal\", &BeamBase::get_polarization_normal)\n      .def(\"set_polarization_normal\", &BeamBase::set_polarization_normal)\n      .def(\"get_polarization_fraction\", &BeamBase::get_polarization_fraction)\n      .def(\"set_polarization_fraction\", &BeamBase::set_polarization_fraction)\n      .def(\"get_flux\", &BeamBase::get_flux)\n      .def(\"set_flux\", &BeamBase::set_flux)\n      .def(\"get_transmission\", &BeamBase::get_transmission)\n      .def(\"set_transmission\", &BeamBase::set_transmission)\n      .add_property(\"num_scan_points\", &BeamBase::get_num_scan_points)\n      .def(\"get_num_scan_points\", &BeamBase::get_num_scan_points)\n      .def(\"set_s0_at_scan_points\", &BeamBase::set_s0_at_scan_points)\n      .def(\"set_s0_at_scan_points\", &Beam_set_s0_at_scan_points_from_tuple)\n      .def(\"set_s0_at_scan_points\", &Beam_set_s0_at_scan_points_from_list)\n      .def(\"get_s0_at_scan_points\", &BeamBase::get_s0_at_scan_points)\n      .def(\"get_s0_at_scan_point\", &BeamBase::get_s0_at_scan_point)\n      .def(\"reset_scan_points\", &BeamBase::reset_scan_points)\n      .def(\"rotate_around_origin\",\n           &rotate_around_origin,\n           (arg(\"axis\"), arg(\"angle\"), arg(\"deg\") = true))\n      .def(\"__eq__\", &BeamBase::operator==)\n      .def(\"__ne__\", &BeamBase::operator!=)\n      .def(\"is_similar_to\",\n           &BeamBase::is_similar_to,\n           (arg(\"other\"),\n            arg(\"wavelength_tolerance\") = 1e-6,\n            arg(\"direction_tolerance\") = 1e-6,\n            arg(\"polarization_normal_tolerance\") = 1e-6,\n            arg(\"polarization_fraction_tolerance\") = 1e-6));\n\n    // Export Beam : BeamBase\n    class_<Beam, boost::shared_ptr<Beam>, bases<BeamBase> >(\"Beam\")\n      .def(init<const Beam &>())\n      .def(init<vec3<double>, double>((arg(\"direction\"), arg(\"wavelength\"))))\n      .def(init<vec3<double> >((arg(\"s0\"))))\n      .def(\"__init__\",\n           make_constructor(&make_beam,\n                            default_call_policies(),\n                            (arg(\"direction\"),\n                             arg(\"wavelength\"),\n                             arg(\"divergence\"),\n                             arg(\"sigma_divergence\"),\n                             arg(\"deg\") = true)))\n      .def(\n        \"__init__\",\n        make_constructor(\n          &make_beam_w_s0,\n          default_call_policies(),\n          (arg(\"s0\"), arg(\"divergence\"), arg(\"sigma_divergence\"), arg(\"deg\") = true)))\n      .def(\"__init__\",\n           make_constructor(&make_beam_w_all,\n                            default_call_policies(),\n                            (arg(\"direction\"),\n                             arg(\"wavelength\"),\n                             arg(\"divergence\"),\n                             arg(\"sigma_divergence\"),\n                             arg(\"polarization_normal\"),\n                             arg(\"polarization_fraction\"),\n                             arg(\"flux\"),\n                             arg(\"transmission\"),\n                             arg(\"deg\") = true)))\n      .def(\"__str__\", &beam_to_string)\n      .def(\"to_dict\", &to_dict<Beam>)\n      .def(\"from_dict\", &from_dict<Beam>, return_value_policy<manage_new_object>())\n      .staticmethod(\"from_dict\")\n      .def_pickle(BeamPickleSuite());\n\n    scitbx::af::boost_python::flex_wrapper<Beam>::plain(\"flex_Beam\");\n  }\n\n}}}  // namespace dxtbx::model::boost_python\n", "meta": {"hexsha": "02b075424b3e8beb4a3355e656b880f14d52ca3d", "size": 12525, "ext": "cc", "lang": "C++", "max_stars_repo_path": "model/boost_python/beam.cc", "max_stars_repo_name": "ndevenish/dxtbx", "max_stars_repo_head_hexsha": "2e3fff616dd99e5e7557e9774e4357bacae59f1b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T05:46:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T08:38:37.000Z", "max_issues_repo_path": "model/boost_python/beam.cc", "max_issues_repo_name": "ndevenish/dxtbx", "max_issues_repo_head_hexsha": "2e3fff616dd99e5e7557e9774e4357bacae59f1b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 448.0, "max_issues_repo_issues_event_min_datetime": "2019-04-06T01:20:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:58:48.000Z", "max_forks_repo_path": "model/boost_python/beam.cc", "max_forks_repo_name": "ndevenish/dxtbx", "max_forks_repo_head_hexsha": "2e3fff616dd99e5e7557e9774e4357bacae59f1b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-04-08T13:30:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T14:48:50.000Z", "avg_line_length": 40.6655844156, "max_line_length": 88, "alphanum_fraction": 0.5828343313, "num_tokens": 3004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.15743396928283757}}
{"text": "#ifndef HERMIT_SPIRIT_QI_RFC1123_DATE_HPP\n#define HERMIT_SPIRIT_QI_RFC1123_DATE_HPP\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <boost/date_time/date_defs.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/date_time/gregorian_calendar.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n\nnamespace hermit {\n  namespace spirit {\n    namespace qi {\n      template <typename InputIterator>\n        class rfc1123_date :\n          public boost::spirit::qi::grammar< InputIterator, boost::posix_time::ptime() > {\n            public:\n              rfc1123_date() : rfc1123_date::base_type( root ) {\n                namespace qi = boost::spirit::qi;\n                namespace dt = boost::date_time;\n                namespace phx = boost::phoenix;\n                root = ( wkday >> ',' >> qi::omit[ +qi::standard::space ] >>\n                         date >> qi::omit[ +qi::standard::space ] >> time >> qi::omit[ +qi::standard::space ] >>\n                         zone )[\n                  qi::_pass = qi::_1 == phx::bind( &boost::gregorian::date::day_of_week, &qi::_2 ),\n                  qi::_val = phx::construct< boost::posix_time::ptime >( qi::_2,\n                    qi::_3 + qi::_4\n                  )\n                ];\n                date = ( dec2_p >> qi::omit[ +qi::standard::space ] >> month >> qi::omit[ +qi::standard::space ] >> dec4_p )[\n                  qi::_pass = qi::_1 <= phx::bind( boost::gregorian::gregorian_calendar::end_of_month_day, qi::_3, qi::_2 ),\n                  qi::_val = phx::construct< boost::gregorian::date >( qi::_3, qi::_2, qi::_1 )\n                ];\n                time = ( dec2_p >> ':' >> dec2_p >> ':' >> dec2_p )[\n                  qi::_pass = qi::_1 < 24u && qi::_2 < 60u && qi::_3 < 60u,\n                  qi::_val = phx::construct< boost::posix_time::time_duration >( qi::_1, qi::_2, qi::_3 )\n                ];\n                wkday.add( \"Mon\", dt::Monday )( \"Tue\", dt::Tuesday )( \"Wed\", dt::Wednesday )( \"Thu\", dt::Thursday )\n                         ( \"Fri\", dt::Friday )( \"Sat\", dt::Saturday )( \"Sun\", dt::Sunday );\n                month.add( \"Jan\", dt::Jan )( \"Feb\", dt::Feb )( \"Mar\", dt::Mar )( \"Apr\", dt::Apr )\n                         ( \"May\", dt::May )( \"Jun\", dt::Jun )( \"Jul\", dt::Jul )( \"Aug\", dt::Aug )\n                         ( \"Sep\", dt::Sep )( \"Oct\", dt::Oct )( \"Nov\", dt::Nov )( \"Dec\", dt::Dec );\n                zone_name.add( \"UT\", boost::posix_time::time_duration( 0, 0, 0 ) )\n                             ( \"GMT\", boost::posix_time::time_duration( 0, 0, 0 ) )\n                             ( \"EST\", boost::posix_time::time_duration( -5, 0, 0 ) )\n                             ( \"EDT\", boost::posix_time::time_duration( -4, 0, 0 ) )\n                             ( \"CST\", boost::posix_time::time_duration( -6, 0, 0 ) )\n                             ( \"CDT\", boost::posix_time::time_duration( -5, 0, 0 ) )\n                             ( \"MST\", boost::posix_time::time_duration( -7, 0, 0 ) )\n                             ( \"MDT\", boost::posix_time::time_duration( -6, 0, 0 ) )\n                             ( \"PST\", boost::posix_time::time_duration( -8, 0, 0 ) )\n                             ( \"PDT\", boost::posix_time::time_duration( -7, 0, 0 ) )\n                             ( \"Z\", boost::posix_time::time_duration( 0, 0, 0 ) )\n                             ( \"A\", boost::posix_time::time_duration( -1, 0, 0 ) )\n                             ( \"B\", boost::posix_time::time_duration( -2, 0, 0 ) )\n                             ( \"C\", boost::posix_time::time_duration( -3, 0, 0 ) )\n                             ( \"D\", boost::posix_time::time_duration( -4, 0, 0 ) )\n                             ( \"E\", boost::posix_time::time_duration( -5, 0, 0 ) )\n                             ( \"F\", boost::posix_time::time_duration( -6, 0, 0 ) )\n                             ( \"G\", boost::posix_time::time_duration( -7, 0, 0 ) )\n                             ( \"H\", boost::posix_time::time_duration( -8, 0, 0 ) )\n                             ( \"I\", boost::posix_time::time_duration( -9, 0, 0 ) )\n                             ( \"K\", boost::posix_time::time_duration( -10, 0, 0 ) )\n                             ( \"L\", boost::posix_time::time_duration( -11, 0, 0 ) )\n                             ( \"M\", boost::posix_time::time_duration( -12, 0, 0 ) )\n                             ( \"N\", boost::posix_time::time_duration( 1, 0, 0 ) )\n                             ( \"O\", boost::posix_time::time_duration( 2, 0, 0 ) )\n                             ( \"P\", boost::posix_time::time_duration( 3, 0, 0 ) )\n                             ( \"Q\", boost::posix_time::time_duration( 4, 0, 0 ) )\n                             ( \"R\", boost::posix_time::time_duration( 5, 0, 0 ) )\n                             ( \"S\", boost::posix_time::time_duration( 6, 0, 0 ) )\n                             ( \"T\", boost::posix_time::time_duration( 7, 0, 0 ) )\n                             ( \"U\", boost::posix_time::time_duration( 8, 0, 0 ) )\n                             ( \"V\", boost::posix_time::time_duration( 9, 0, 0 ) )\n                             ( \"W\", boost::posix_time::time_duration( 10, 0, 0 ) )\n                             ( \"X\", boost::posix_time::time_duration( 11, 0, 0 ) )\n                             ( \"Y\", boost::posix_time::time_duration( 12, 0, 0 ) );\n                zone_pos = ( '+' >> qi::omit[ *qi::standard::space ] >> dece2_p >> dece2_p )[\n                  qi::_pass = qi::_2 < 60u,\n                  qi::_val = phx::construct< boost::posix_time::time_duration >( qi::_1, qi::_2, 0 )\n                ];\n                zone_neg = ( '-' >> qi::omit[ *qi::standard::space ] >> dece2_p >> dece2_p )[\n                  qi::_pass = qi::_2 < 60u,\n                  qi::_val = -phx::construct< boost::posix_time::time_duration >( qi::_1, qi::_2, 0 )\n                ];\n                zone = zone_name|zone_pos|zone_neg;\n              }\n            private:\n              boost::spirit::qi::uint_parser<unsigned int, 10, 2, 2> dece2_p;\n              boost::spirit::qi::uint_parser<unsigned int, 10, 1, 2> dec2_p;\n              boost::spirit::qi::uint_parser<unsigned int, 10, 1, 4> dec4_p;\n              boost::spirit::qi::rule< InputIterator, boost::posix_time::ptime() > root;\n              boost::spirit::qi::rule< InputIterator, boost::gregorian::date() > date;\n              boost::spirit::qi::rule< InputIterator, boost::posix_time::time_duration() > time;\n              boost::spirit::qi::rule< InputIterator, boost::posix_time::time_duration() > zone;\n              boost::spirit::qi::rule< InputIterator, boost::posix_time::time_duration() > zone_pos;\n              boost::spirit::qi::rule< InputIterator, boost::posix_time::time_duration() > zone_neg;\n              boost::spirit::qi::symbols< char, boost::date_time::weekdays > wkday;\n              boost::spirit::qi::symbols< char, boost::posix_time::time_duration > zone_name; \n              boost::spirit::qi::symbols< char, boost::date_time::months_of_year > month;\n      };\n    }\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "0570de3ef3e4be3df04c6ec707d0ccde96115f94", "size": 7114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hermit/spirit/qi/rfc1123_date.hpp", "max_stars_repo_name": "Fadis/hermit", "max_stars_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T05:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-09T05:54:01.000Z", "max_issues_repo_path": "include/hermit/spirit/qi/rfc1123_date.hpp", "max_issues_repo_name": "Fadis/hermit", "max_issues_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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/hermit/spirit/qi/rfc1123_date.hpp", "max_forks_repo_name": "Fadis/hermit", "max_forks_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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": 64.0900900901, "max_line_length": 125, "alphanum_fraction": 0.4738543717, "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.15743396492029613}}
{"text": "#ifndef _RYSQ_CUDA_HPP_\n#define _RYSQ_CUDA_HPP_\n\n#include <vector>\n\n// #include <boost/numeric/ublas/matrix.hpp>\n#include \"rysq/core.hpp\"\n#include \"rysq/eri.hpp\"\n#include \"rysq/fock.hpp\"\n\n\n#include \"rysq/cuda-memory.hpp\"\n#include \"rysq/cuda-matrix.hpp\"\n\nnamespace rysq {\n    namespace cuda {\n\n\tstd::vector<int> get_devices();\n\tvoid set_device(size_t device = 0);\n\tvoid thread_exit();\n\n\tstruct thread {\n\t    thread(size_t device = 0) { set_device(device); }\n\t    ~thread() { thread_exit(); }\n\t};\n\n\tnamespace detail {\n\t    class Eri;\n\t    class Fock;\n\t}\n\n\ttypedef cuda::array<Center> Centers;\n\n\tstruct Quartets : cuda::array<Int4> {\n\t    Quartets() {\n\t\tmin.assign(1);\n\t\tmax.assign(0);\n\t    }\n\t    template<typename T>\n\t    explicit Quartets(T begin, T end)\n\t\t: vector_(begin, end) {\n\t\tinitialize();\n\t    }\n\t    explicit Quartets(const std::vector<Int4> &centers)\n\t\t: vector_(centers) {\n\t\tinitialize();\n\t    }\n\t    void assign(const std::vector<Int4> &centers) {\n\t\tvector_ = centers;\n\t\tinitialize();\n\t    }\n\t    typedef std::vector<Int4>::const_iterator const_iterator;\n\t    const_iterator begin() const { return vector_.begin(); }\n\t    const_iterator end() const { return vector_.end(); }\n\t    boost::array<int,4> max, min;\n\tprivate:\n\t    typedef cuda::array<Int4> base_type;\n\t    std::vector<Int4> vector_;\n\t    void initialize() {\n\t\tmax.assign(0);\n\t\tmin.assign(1);\n\t\tif (!vector_ . empty()) {\n\t\t    max = vector_.front();\n\t\t    min = max;\n\t\t}\n\t\ttypedef std::vector<Int4>::const_iterator iterator;\n\t\tfor (iterator it = vector_.begin(); it < vector_.end(); ++ it) {\n\t\t    // std:: cout << *it << std::endl;\n\t\t    for (int i = 0; i < 4; ++i) {\n\t\t\tmax[i] = std::max(max[i], (*it)[i]);\n\t\t\tmin[i] = std::min(min[i], (*it)[i]);\n\t\t    }\n\t\t}\n\t\tbase_type::assign(vector_);\n\t    }\n\t};\n\n\tstruct Eri {\n\t    Eri(const rysq::Quartet<rysq::Shell> &shells);\n\t    ~Eri();\n\t    operator bool() const { return kernel_ != NULL; }\n\t    void operator()(const cuda::Centers &centers,\n\t\t\t    const cuda::Quartets &quartets,\n\t\t\t    cuda::array <double> &Eri,\n\t\t\t    const Parameters &parameters);\n\tprivate:\n\t    detail::Eri *kernel_;\n\t};\n\n\ttypedef cuda::block_matrix<double> density_matrix;\n\ttypedef cuda::block_matrix<double> fock_matrix;\n\n\tstruct Fock {\n\t    typedef hf::matrix_ptr_set < fock_matrix> fock_matrix_set;\n\t    typedef hf::matrix_ptr_set < density_matrix> density_matrix_set;\n\t    Fock(const rysq::Quartet<rysq::Shell> &shells);\n\t    ~Fock();\n\t    operator bool() const { return kernel_ != NULL; }\n\t    // operator bool() const { return  kernel_ != NULL; }\n\t    void operator()(const cuda::Centers &centers,\n\t\t\t    const cuda::Quartets &quartets,\n\t\t\t    density_matrix_set D, fock_matrix_set F,\n\t\t\t    const Parameters &parameters);\n\tprivate:\n\t    detail::Fock *kernel_;\n\t    size_t block_[4];\n\t};\n\t    \n\n    }\n}\n\n#endif /* _RYSQ_CUDA_HPP_ */\n", "meta": {"hexsha": "956dfc2b7d53ef598bd88f6a83d87294d5c1d778", "size": 2831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/rysq/src/rysq/cuda.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/rysq/cuda.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/rysq/cuda.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.8333333333, "max_line_length": 69, "alphanum_fraction": 0.6273401625, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.1572802040655297}}
{"text": "#ifndef MAC_TIME_TRACKER_TIME_HPP\n#define MAC_TIME_TRACKER_TIME_HPP\n\n#include <chrono>\n#include <ctime>   // for std::localtime()\n#include <iomanip> // for std::put_time()\n#include <iostream>\n#include <string>\n\n#include <boost/lexical_cast.hpp>\n\n#include <mac_time_tracker/io.hpp>\n\nnamespace mac_time_tracker {\n\nclass Time : public std::chrono::system_clock::time_point, public Writable {\nprivate:\n  using Base = std::chrono::system_clock::time_point;\n\npublic:\n  // Constructors\n  using Base::Base;\n  Time(const Base &base) : Base(base) {}\n  Time(Base &&base) : Base(base) {}\n  template <class Duration>\n  Time(const std::chrono::time_point<clock, Duration> &t)\n      : Base(std::chrono::time_point_cast<Base>(t)) {}\n\n  // A shortcut to Time::clock::now()\n  static Time now() { return clock::now(); }\n\n  using Writable::toStr;\n  std::string toStr(const std::string &fmt) const {\n    const std::time_t t = clock::to_time_t(*this);\n    return boost::lexical_cast<std::string>(std::put_time(std::localtime(&t), fmt.c_str()));\n  }\n\n  static std::string defaultFormat() {\n    // a format like \"Y-M-D H:M:S\", which is based on ISO 8601\n    return \"%F %T\";\n  }\n\nprivate:\n  virtual void write(std::ostream &os) const override { os << toStr(defaultFormat()); }\n};\n\n} // namespace mac_time_tracker\n\n#endif", "meta": {"hexsha": "69bdaa66fd4ab8b6cb499c5eeecc3e7114a24254", "size": 1295, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mac_time_tracker/time.hpp", "max_stars_repo_name": "yoshito-n-students/mac_time_tracker", "max_stars_repo_head_hexsha": "0532b0c71635bad343ae06b09818156024ff39f5", "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/mac_time_tracker/time.hpp", "max_issues_repo_name": "yoshito-n-students/mac_time_tracker", "max_issues_repo_head_hexsha": "0532b0c71635bad343ae06b09818156024ff39f5", "max_issues_repo_licenses": ["MIT"], "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/mac_time_tracker/time.hpp", "max_forks_repo_name": "yoshito-n-students/mac_time_tracker", "max_forks_repo_head_hexsha": "0532b0c71635bad343ae06b09818156024ff39f5", "max_forks_repo_licenses": ["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.4285714286, "max_line_length": 92, "alphanum_fraction": 0.6872586873, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.1572801975722671}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/overloads.hpp>\n#include <mmtbx/building/loop_closure/ccd.h>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/copy_non_const_reference.hpp>\n#include <boost/python/copy_const_reference.hpp>\n\n\nnamespace mmtbx { namespace building { namespace loop_closure {\nnamespace {\n\n  void init_module()\n  {\n    using namespace boost::python;\n    typedef return_value_policy<return_by_value> rbv;\n    typedef return_value_policy<copy_const_reference> ccr;\n    typedef return_value_policy<copy_non_const_reference> cncr;\n    typedef default_call_policies dcp;\n\n    class_<ccd_cpp> (\"ccd_cpp\", no_init)\n      .def(init< scitbx::af::tiny<scitbx::vec3<double>, 3 >,\n        iotbx::pdb::hierarchy::root & ,\n        scitbx::af::tiny<size_t, 3>,\n        const int&,\n        const double&>(\n          (arg(\"fixed_ref_atoms\"),\n           arg(\"moving_h\"),\n           arg(\"moving_ref_atoms_iseqs\"),\n           arg(\"max_number_of_iterations\")=500,\n           arg(\"needed_rmsd\")=0.1)))\n      .def(\"_find_angle\", &ccd_cpp::_find_angle,\n          (arg(\"axis_point_1\"),\n           arg(\"axis_point_2\")))\n      .def(\"_modify_angle\", &ccd_cpp::_modify_angle,\n          (arg(\"angle\")))\n\n      .add_property(\"early_exit\",\n          make_getter(&ccd_cpp::early_exit, rbv()),\n          make_setter(&ccd_cpp::early_exit, dcp()))\n      .add_property(\"resulting_rmsd\",\n          make_getter(&ccd_cpp::resulting_rmsd, rbv()),\n          make_setter(&ccd_cpp::resulting_rmsd, dcp()))\n      .add_property(\"needed_rmsd\",\n          make_getter(&ccd_cpp::needed_rmsd, rbv()),\n          make_setter(&ccd_cpp::needed_rmsd, dcp()))\n      .add_property(\"max_number_of_iterations\",\n          make_getter(&ccd_cpp::max_number_of_iterations, rbv()),\n          make_setter(&ccd_cpp::max_number_of_iterations, dcp()))\n      .add_property(\"r\",\n          make_getter(&ccd_cpp::r, rbv()),\n          make_setter(&ccd_cpp::r, dcp()))\n      .add_property(\"convergence_diff\",\n          make_getter(&ccd_cpp::convergence_diff, rbv()),\n          make_setter(&ccd_cpp::convergence_diff, dcp()))\n      .add_property(\"fixed_ref_atoms\",\n          make_getter(&ccd_cpp::fixed_ref_atoms, rbv()))\n      .add_property(\"moving_ref_atoms_iseqs\",\n          make_getter(&ccd_cpp::moving_ref_atoms_iseqs, rbv()))\n      .add_property(\"moving_h\", make_getter(&ccd_cpp::moving_h, cncr()))\n    ;\n  }\n\n\n\n} // namespace <anonymous>\n}}} // namespace mmtbx::building::loop_closure\n\nBOOST_PYTHON_MODULE(mmtbx_building_loop_closure_ext)\n{\n  mmtbx::building::loop_closure::init_module();\n}\n", "meta": {"hexsha": "eb4fd3b3755e04d13b372c34f31011f78a98afc0", "size": 2678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mmtbx/building/loop_closure/ccd_bpl.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": "mmtbx/building/loop_closure/ccd_bpl.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": "mmtbx/building/loop_closure/ccd_bpl.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": 35.7066666667, "max_line_length": 72, "alphanum_fraction": 0.6650485437, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.297469948832931, "lm_q1q2_score": 0.1568608192284789}}
{"text": "/*\n * Representer.hxx\n *\n * Created by Remi Blanc, Marcel Luethi\n *\n * Copyright (c) 2011 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\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 __ConditionalModelBuilder_hxx\n#define __ConditionalModelBuilder_hxx\n\n#include \"CommonTypes.h\"\n#include \"Exceptions.h\"\n#include <iostream>\n\n#include <Eigen/SVD>\n#include \"PCAModelBuilder.h\"\n#include \"ConditionalModelBuilder.h\"\n\nnamespace statismo {\n\n//\n// ConditionalModelBuilder\n//\n//\n\n\ntemplate <typename T>\nunsigned\nConditionalModelBuilder<T>::PrepareData(const DataItemListType& sampleDataList,\n                                        const SurrogateTypeInfoType& surrogateTypesInfo,\n                                        const CondVariableValueVectorType& conditioningInfo,\n                                        DataItemListType *acceptedSamples,\n                                        MatrixType *surrogateMatrix,\n                                        VectorType *conditions) const {\n    bool acceptSample;\n    unsigned nbAcceptedSamples = 0;\n    unsigned nbContinuousSurrogatesInUse = 0, nbCategoricalSurrogatesInUse = 0;\n    std::vector<unsigned> indicesContinuousSurrogatesInUse;\n    std::vector<unsigned> indicesCategoricalSurrogatesInUse;\n\n    //first: identify the continuous and categorical variables, which are used for conditioning and which are not\n    for (unsigned i=0 ; i<conditioningInfo.size() ; i++) {\n        if (conditioningInfo[i].first) { //only variables that are used for conditioning are of interest here\n            if (surrogateTypesInfo.types[i] == DataItemWithSurrogatesType::Continuous) {\n                nbContinuousSurrogatesInUse++;\n                indicesContinuousSurrogatesInUse.push_back(i);\n            } else {\n                nbCategoricalSurrogatesInUse++;\n                indicesCategoricalSurrogatesInUse.push_back(i);\n            }\n        }\n    }\n    conditions->resize(nbContinuousSurrogatesInUse);\n    for (unsigned i=0 ; i<nbContinuousSurrogatesInUse ; i++) (*conditions)(i) = conditioningInfo[i].second;\n    surrogateMatrix->resize(nbContinuousSurrogatesInUse, sampleDataList.size()); //number of variables is now known: nbContinuousSurrogatesInUse ; the number of samples is yet unknown...\n\n    //now, browse all samples to select the ones which fall into the requested categories\n    for (typename DataItemListType::const_iterator it = sampleDataList.begin(); it != sampleDataList.end(); ++it) {\n        const DataItemWithSurrogatesType* sampleData = dynamic_cast<const DataItemWithSurrogatesType*>(*it);\n        if (sampleData == 0)  {\n            // this is a normal sample without surrogate information.\n            // we simply discard it\n            std::cout<<\"WARNING: ConditionalModelBuilder, sample data \"<< (*it)->GetDatasetURI()<<\" has no surrogate data associated, and is ignored\"<<std::endl;\n            continue;\n        }\n\n        VectorType surrogateData = sampleData->GetSurrogateVector();\n        acceptSample = true;\n        for (unsigned i=0 ; i<nbCategoricalSurrogatesInUse ; i++) { //check that this sample respect the requested categories\n            if ( conditioningInfo[indicesCategoricalSurrogatesInUse[i]].second !=\n                    surrogateData[indicesCategoricalSurrogatesInUse[i]] ) {\n                //if one of the categories does not fit the requested one, then the sample is discarded\n                acceptSample = false;\n                continue;\n            }\n        }\n\n        if (acceptSample) { //if the sample is of the right category\n            acceptedSamples->push_back(*it);\n            //and fill in the matrix of continuous variables\n            for (unsigned j=0 ; j<nbContinuousSurrogatesInUse ; j++) {\n                (*surrogateMatrix)(j,nbAcceptedSamples) = surrogateData[indicesContinuousSurrogatesInUse[j]];\n            }\n            nbAcceptedSamples++;\n        }\n    }\n    //resize the matrix of surrogate data to the effective number of accepted samples\n    surrogateMatrix->conservativeResize(Eigen::NoChange_t(), nbAcceptedSamples);\n\n    return nbAcceptedSamples;\n}\n\ntemplate <typename T>\ntypename ConditionalModelBuilder<T>::StatisticalModelType*\nConditionalModelBuilder<T>::BuildNewModel(const DataItemListType& sampleDataList,\n        const SurrogateTypeInfoType& surrogateTypesInfo,\n        const CondVariableValueVectorType& conditioningInfo,\n        float noiseVariance,\n        double modelVarianceRetained) const {\n    DataItemListType acceptedSamples;\n    MatrixType X;\n    VectorType x0;\n    unsigned nSamples = PrepareData(sampleDataList, surrogateTypesInfo, conditioningInfo, &acceptedSamples, &X, &x0);\n    assert(nSamples == acceptedSamples.size());\n\n    unsigned nCondVariables = X.rows();\n\n    // build a normal PCA model\n    typedef PCAModelBuilder<T> PCAModelBuilderType;\n    PCAModelBuilderType* modelBuilder = PCAModelBuilderType::Create();\n    StatisticalModelType* pcaModel = modelBuilder->BuildNewModel(acceptedSamples, noiseVariance);\n\n    unsigned nPCAComponents = pcaModel->GetNumberOfPrincipalComponents();\n\n    if ( X.cols() == 0 || X.rows() == 0) {\n        return pcaModel;\n    } else {\n        // the scores in the pca model correspond to the parameters of each sample in the model.\n        MatrixType B = pcaModel->GetModelInfo().GetScoresMatrix().transpose();\n        assert(B.rows() == nSamples);\n        assert(B.cols() == nPCAComponents);\n\n        // A is the joint data matrix B, X, where X contains the conditional information for each sample\n        // Thus the i-th row of A contains the PCA parameters b of the i-th sample,\n        // together with the conditional information for each sample\n        MatrixType A(nSamples, nPCAComponents+nCondVariables);\n        A << B,X.transpose();\n\n        // Compute the mean and the covariance of the joint data matrix\n        VectorType mu = A.colwise().mean().transpose(); // colwise returns a row vector\n        assert(mu.rows() == nPCAComponents + nCondVariables);\n\n        MatrixType A0 = A.rowwise() - mu.transpose(); //\n        MatrixType cov = 1.0 / (nSamples-1) * A0.transpose() *  A0;\n\n        assert(cov.rows() == cov.cols());\n        assert(cov.rows() == pcaModel->GetNumberOfPrincipalComponents() + nCondVariables);\n\n        // extract the submatrices involving the conditionals x\n        // note that since the matrix is symmetric, Sbx = Sxb.transpose(), hence we only store one\n        MatrixType Sbx = cov.topRightCorner(nPCAComponents, nCondVariables);\n        MatrixType Sxx = cov.bottomRightCorner(nCondVariables, nCondVariables);\n        MatrixType Sbb = cov.topLeftCorner(nPCAComponents, nPCAComponents);\n\n        // compute the conditional mean\n        VectorType condMean = mu.topRows(nPCAComponents) + Sbx * Sxx.inverse() * (x0 - mu.bottomRows(nCondVariables));\n\n        // compute the conditional covariance\n        MatrixType condCov = Sbb - Sbx * Sxx.inverse() * Sbx.transpose();\n\n        // get the sample mean corresponding the the conditional given mean of the parameter vectors\n        VectorType condMeanSample = pcaModel->GetRepresenter()->SampleToSampleVector(pcaModel->DrawSample(condMean));\n\n\n        // so far all the computation have been done in parameter (latent) space. Go back to sample space.\n        // (see PartiallyFixedModelBuilder for a detailed documentation)\n        // TODO we should factor this out into the base class, as it is the same code as it is used in\n        // the partially fixed model builder\n        const VectorType& pcaVariance = pcaModel->GetPCAVarianceVector();\n        VectorTypeDoublePrecision pcaSdev = pcaVariance.cast<double>().array().sqrt();\n\n        typedef Eigen::JacobiSVD<MatrixTypeDoublePrecision> SVDType;\n        MatrixTypeDoublePrecision innerMatrix = pcaSdev.asDiagonal() * condCov.cast<double>() * pcaSdev.asDiagonal();\n        SVDType svd(innerMatrix, Eigen::ComputeThinU);\n        VectorType singularValues = svd.singularValues().cast<ScalarType>();\n\n        // keep only the necessary number of modes, wrt modelVarianceRetained...\n        double totalRemainingVariance = singularValues.sum(); //\n        //and count the number of modes required for the model\n        double cumulatedVariance = singularValues(0);\n        unsigned numComponentsToReachPrescribedVariance = 1;\n        while ( cumulatedVariance/totalRemainingVariance < modelVarianceRetained ) {\n            numComponentsToReachPrescribedVariance++;\n            if (numComponentsToReachPrescribedVariance==singularValues.size()) break;\n            cumulatedVariance += singularValues(numComponentsToReachPrescribedVariance-1);\n        }\n\n        unsigned numComponentsToKeep = std::min<unsigned>( numComponentsToReachPrescribedVariance, singularValues.size() );\n\n        VectorType newPCAVariance = singularValues.topRows(numComponentsToKeep);\n        MatrixType newPCABasisMatrix = (pcaModel->GetOrthonormalPCABasisMatrix() * svd.matrixU().cast<ScalarType>()).topLeftCorner(X.cols(), numComponentsToKeep);\n\n        StatisticalModelType* model = StatisticalModelType::Create(pcaModel->GetRepresenter(),  condMeanSample, newPCABasisMatrix, newPCAVariance, noiseVariance);\n\n        // add builder info and data info to the info list\n        MatrixType scores(0,0);\n        BuilderInfo::ParameterInfoList bi;\n\n        bi.push_back(BuilderInfo::KeyValuePair(\"NoiseVariance \", Utils::toString(noiseVariance)));\n\n        //generate a matrix ; first column = boolean (yes/no, this variable is used) ; second: conditioning value.\n        MatrixType conditioningInfoMatrix(conditioningInfo.size(), 2);\n        for (unsigned i=0 ; i<conditioningInfo.size() ; i++) {\n            conditioningInfoMatrix(i,0) = conditioningInfo[i].first;\n            conditioningInfoMatrix(i,1) = conditioningInfo[i].second;\n        }\n        bi.push_back(BuilderInfo::KeyValuePair(\"ConditioningInfo \", Utils::toString(conditioningInfoMatrix)));\n\n        typename BuilderInfo::DataInfoList di;\n\n        unsigned i = 0;\n        for (typename DataItemListType::const_iterator it = sampleDataList.begin();\n                it != sampleDataList.end();\n                ++it, i++) {\n            const DataItemWithSurrogatesType* sampleData = dynamic_cast<const DataItemWithSurrogatesType*>(*it);\n            std::ostringstream os;\n            os << \"URI_\" << i;\n            di.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),sampleData->GetDatasetURI()));\n\n            os << \"_surrogates\";\n            di.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),sampleData->GetSurrogateFilename()));\n        }\n\n        std::ostringstream os;\n        os << \"surrogates_types\";\n        di.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),surrogateTypesInfo.typeFilename));\n\n\n        BuilderInfo builderInfo(\"ConditionalModelBuilder\", di, bi);\n\n        ModelInfo::BuilderInfoList biList;\n        biList.push_back(builderInfo);\n\n        ModelInfo info(scores, biList);\n        model->SetModelInfo(info);\n\n        delete pcaModel;\n\n        return model;\n    }\n\n}\n\n} // namespace statismo\n\n#endif\n", "meta": {"hexsha": "a44af02618e3bbe8c51341eec19e1b1f2bb0211f", "size": 12455, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "modules/core/include/ConditionalModelBuilder.hxx", "max_stars_repo_name": "tom-albrecht/statismo", "max_stars_repo_head_hexsha": "e7825afadb1accc4902d911d5f00a8c4bd383a31", "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/core/include/ConditionalModelBuilder.hxx", "max_issues_repo_name": "tom-albrecht/statismo", "max_issues_repo_head_hexsha": "e7825afadb1accc4902d911d5f00a8c4bd383a31", "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/core/include/ConditionalModelBuilder.hxx", "max_forks_repo_name": "tom-albrecht/statismo", "max_forks_repo_head_hexsha": "e7825afadb1accc4902d911d5f00a8c4bd383a31", "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": 46.6479400749, "max_line_length": 186, "alphanum_fraction": 0.6918506624, "num_tokens": 2711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.1568608126600806}}
{"text": "#include \"ElNullRangeEst.h\"\n\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Dense>\n\n#include <isce3/antenna/Frame.h>\n#include <isce3/core/Attitude.h>\n#include <isce3/core/DateTime.h>\n#include <isce3/core/EMatrix.h>\n#include <isce3/core/Ellipsoid.h>\n#include <isce3/core/Linspace.h>\n#include <isce3/core/Orbit.h>\n#include <isce3/core/Poly1d.h>\n#include <isce3/geometry/DEMInterpolator.h>\n\n// Alias\nnamespace py = pybind11;\nusing namespace isce3::core;\nusing namespace isce3::antenna;\nusing isce3::geometry::DEMInterpolator;\n\n// readonly struct or aggregate  datatypes\nvoid addbinding(py::class_<NullProduct>& pyNullProduct)\n{\n    pyNullProduct.def_readonly(\"slant_range\", &NullProduct::slant_range)\n            .def_readonly(\"el_angle\", &NullProduct::el_angle)\n            .def_readonly(\"doppler\", &NullProduct::doppler)\n            .def_readonly(\"magnitude\", &NullProduct::magnitude);\n    pyNullProduct.doc() = R\"(\nEL null product\n\nAttributes\n----------\nslant_range : float\n    Slant range of the null location in (m).\nel_angle : float\n    Elevation angle of the null location in (rad).\ndoppler : float\n    Doppler at the null location in (Hz).\nmagnitude : float\n    Relative magnitude of the null w.r.t left/right peaks in (linear).\n)\";\n}\n\nvoid addbinding(py::class_<NullConvergenceFlags>& pyNullConvergenceFlags)\n{\n    pyNullConvergenceFlags\n            .def_readonly(\"newton_solver\", &NullConvergenceFlags::newton_solver)\n            .def_readonly(\"geometry_echo\", &NullConvergenceFlags::geometry_echo)\n            .def_readonly(\"geometry_antenna\",\n                    &NullConvergenceFlags::geometry_antenna);\n    pyNullConvergenceFlags.doc() = R\"(\nA set of flags indicating convergence of iterative operations\nused in EL null product formation\n\nAttributes\n----------\nnewton_solver : bool\n    Indicates convergence of the 1-D Newton root solver.\ngeometry_echo : bool\n    Indicates geometry-related convergence for echo null estimation.\ngeometry_antenna : bool\n    Indicates geometry-related convergence for antenna null estimation.\n)\";\n}\n\n// class\nvoid addbinding(py::class_<ElNullRangeEst>& pyElNullRangeEst)\n{\n    pyElNullRangeEst\n            // constructors\n            .def(py::init([](double wavelength, double sr_spacing,\n                                  double chirp_rate, double chirp_dur,\n                                  const Orbit& orbit, const Attitude& attitude,\n                                  const DEMInterpolator& dem_interp = {},\n                                  const Frame& ant_frame = {},\n                                  const Ellipsoid& ellips = {},\n                                  double el_res = 8.726646259971648e-06,\n                                  double abs_tol_dem = 1.0,\n                                  int max_iter_dem = 20) {\n                return ElNullRangeEst(wavelength, sr_spacing, chirp_rate,\n                        chirp_dur, orbit, attitude, dem_interp, ant_frame,\n                        ellips, el_res, abs_tol_dem, max_iter_dem);\n            }),\n                    py::arg(\"wavelength\"), py::arg(\"sr_spacing\"),\n                    py::arg(\"chirp_rate\"), py::arg(\"chirp_dur\"),\n                    py::arg(\"orbit\"), py::arg(\"attitude\"),\n                    py::arg_v(\"dem_interp\", DEMInterpolator(), \"0.0\"),\n                    py::arg_v(\"ant_frame\", Frame(), \"EL_AND_AZ\"),\n                    py::arg_v(\"ellips\", Ellipsoid(), \"WGS84\"),\n                    py::arg(\"el_res\") = 8.726646259971648e-06,\n                    py::arg(\"abs_tol_dem\") = 1.0, py::arg(\"max_iter_dem\") = 20)\n\n            // methods\n            .def(\"genNullRangeDoppler\", &ElNullRangeEst::genNullRangeDoppler,\n                    py::arg(\"echo_left\"), py::arg(\"echo_right\"),\n                    py::arg(\"el_cut_left\"), py::arg(\"el_cut_right\"),\n                    py::arg(\"sr_start\"), py::arg(\"el_ang_start\"),\n                    py::arg(\"el_ang_step\"), py::arg(\"az_ang\"),\n                    py::arg(\"az_time\") = std::nullopt, R\"(\nGenerate null products from echo (measured) and antenna (nominal/expected).\nThe null product consists of azimuth time tag, null relative magnitude and its\nlocation in EL and slant range, plut its Doppler value given \nazimuth (antenna geometry)/squint(Radar geometry) angle.\n\nParameters\n----------\necho_left : np.ndarray(complex64) \n    complex 2-D array of raw echo samples (pulse by range) for\n    the left RX channel corresponding to the left beam.\necho_right : np.ndarray(complex64)\n    complex 2-D array of raw echo samples (pulse by range) for\n    the right RX channel corresponding to the right beam. \n    Must have the same shape as of that of left one!\nel_cut_left : np.ndarray(complex128) \n    complex array of uniformly-sampled relative or absolute \n    EL-cut antenna pattern on the left side.\nel_cut_right : np.ndarray(complex128)  \n    complex array of uniformly-sampled relative or absolute \n    EL-cut antenna pattern on the right side. \n    It must have the same size as left one!\nsr_start : float\n    start slant range (m) for both uniformly-sampled echoes in range.\nel_ang_start : float \n    start elevation angle for left/right EL patterns in (rad)\nel_ang_step : float \n    step elevation angle for left/right EL patterns in (rad) \naz_ang : float \n    azimuth angle (antenna geometry) or squint angle (Radar geometry) \n    in (rad). This angle determines the final Doppler centroid on \n    top of slant range value for both echo and antenna nulls.\naz_time : float, (optional) \n    azimuth time of echoes in (sec) w.r.t reference epoch of orbit. \n    If not specified, the mid azimuth time of orbit will be used instead.\n\nReturns\n-------\nisce3::core::DateTime\n    azimuth time tag of the null product\nisce3::antenna::NullProduct \n    echo null product\nisce3::antenna:NullProduct\n    antenna null product\nisce3::antenna::NullConvergenceFlags\n    all flags indicating convergence of iterative operations used \n    in forming both echo and antenna EL null products.\n\nRaises\n------\nValueError\n    for bad input arguments\nRuntimeError\n    for failure in null formation\n\n)\")\n\n            // properties\n            .def_property_readonly(\"wave_length\", &ElNullRangeEst::waveLength)\n            .def_property_readonly(\n                    \"slant_range_spacing\", &ElNullRangeEst::slantRangeSpacing)\n            .def_property_readonly(\n                    \"grid_type_name\", &ElNullRangeEst::gridTypeName)\n            .def_property_readonly(\n                    \"chirp_sample_ref\", &ElNullRangeEst::chirpSampleRef)\n            .def_property_readonly(\"ref_epoch\", &ElNullRangeEst::refEpoch)\n            .def_property_readonly(\n                    \"dem_ref_height\", &ElNullRangeEst::demRefHeight)\n            .def_property_readonly(\n                    \"mid_time_orbit\", &ElNullRangeEst::midTimeOrbit)\n            .def_property_readonly(\n                    \"max_el_spacing\", &ElNullRangeEst::maxElSpacing)\n            .def_property_readonly(\"atol_dem\", &ElNullRangeEst::atolDEM)\n            .def_property_readonly(\"max_iter_dem\", &ElNullRangeEst::maxIterDEM)\n            .def_property_readonly(\"atol_null\", &ElNullRangeEst::atolNull)\n            .def_property_readonly(\n                    \"max_iter_null\", &ElNullRangeEst::maxIterNull)\n            .def_property_readonly(\"polyfit_deg\", &ElNullRangeEst::polyfitDeg)\n\n            .doc() = R\"(\nA class for forming Null power patterns in EL direction from both\na pair of adjacent El-cut antenna patterns as well as the respective\nraw echoes of two adjacent RX channels.\nThe location of null in both antenna and echo domain will be estimated\nand their respective values in EL angle, slant range, and Doppler will\nbe reported at a specific azimuth time in orbit.\nSee the following link and its references for algorithm, simulation and analyses,\nhttps://github.jpl.nasa.gov/NISAR-POINTING/DOC/blob/master/Null_ELPointEst_REEsim_RevB.pdf\n)\";\n}\n", "meta": {"hexsha": "c21484eb965c970a8296fecb3925a8e74342577d", "size": 7911, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/extensions/pybind_isce3/antenna/ElNullRangeEst.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": "python/extensions/pybind_isce3/antenna/ElNullRangeEst.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": "python/extensions/pybind_isce3/antenna/ElNullRangeEst.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": 40.9896373057, "max_line_length": 90, "alphanum_fraction": 0.6570597902, "num_tokens": 1873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.15686081266008053}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n//#include <cctbx/miller/sym_equiv.h>\n//#include <cctbx/miller/union_of_indices.h>\n#include <cctbx/miller/math.h>\n#include <boost/python.hpp>\n#include <scitbx/boost_python/container_conversions.h>\n\nnamespace yamtbx { namespace dataproc { namespace crystfel { namespace boost_python {\n  void wrap_merge_equivalents();\n\nnamespace {\n  void init_module()\n  {\n    using namespace boost::python;\n\n    wrap_merge_equivalents();\n  }\n} // namespace <anonymous>\n}}}} // namespace yamtbx::dataproc::crystfel::boost_python\n\n\nBOOST_PYTHON_MODULE(yamtbx_dataproc_crystfel_ext)\n{\n  yamtbx::dataproc::crystfel::boost_python::init_module();\n}\n", "meta": {"hexsha": "7431128fcc22b7d97cf9d1d5f1e9e21710516387", "size": 668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "yamtbx/dataproc/crystfel/boost_python/crystfel_ext.cpp", "max_stars_repo_name": "7l2icj/kamo_clone", "max_stars_repo_head_hexsha": "5f4a5eed3cd9d91a021d805e46125c19cc2ed1b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T11:19:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-01T19:44:23.000Z", "max_issues_repo_path": "yamtbx/dataproc/crystfel/boost_python/crystfel_ext.cpp", "max_issues_repo_name": "7l2icj/kamo_clone", "max_issues_repo_head_hexsha": "5f4a5eed3cd9d91a021d805e46125c19cc2ed1b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-03-10T00:51:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-07T17:18:46.000Z", "max_forks_repo_path": "yamtbx/dataproc/crystfel/boost_python/crystfel_ext.cpp", "max_forks_repo_name": "7l2icj/kamo_clone", "max_forks_repo_head_hexsha": "5f4a5eed3cd9d91a021d805e46125c19cc2ed1b6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-12-15T16:00:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T08:34:14.000Z", "avg_line_length": 24.7407407407, "max_line_length": 85, "alphanum_fraction": 0.7589820359, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.15676994282253567}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <Data/Shape.h>\n\n#include <QFile>\n#include <QFileInfo>\n#include <QMessageBox>\n#include <QTextStream>\n\n#include <itkOrientImageFilter.h>\n\n#include <vtkCenterOfMass.h>\n\n#include <Data/MeshGenerator.h>\n#include <Data/StudioLog.h>\n#include <Visualization/Visualizer.h>\n#include <Libs/Project/ProjectUtils.h>\n\nusing ReaderType = itk::ImageFileReader<ImageType>;\n\nnamespace shapeworks {\n\n//---------------------------------------------------------------------------\nShape::Shape()\n{\n  this->id_ = 0;\n\n  this->corner_annotations_ << \"\";\n  this->corner_annotations_ << \"\";\n  this->corner_annotations_ << \"\";\n  this->corner_annotations_ << \"\";\n}\n\n//---------------------------------------------------------------------------\nShape::~Shape() = default;\n\n//---------------------------------------------------------------------------\nMeshGroup Shape::get_meshes(const string& display_mode)\n{\n  if (display_mode == Visualizer::MODE_ORIGINAL_C) {\n    return this->get_original_meshes();\n  }\n  else if (display_mode == Visualizer::MODE_GROOMED_C) {\n    return this->get_groomed_meshes();\n  }\n  return this->get_reconstructed_meshes();\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_annotations(QStringList annotations, bool only_overwrite_blank)\n{\n  if (only_overwrite_blank && !this->corner_annotations_.empty() &&\n      this->corner_annotations_[0] != \"\") {\n    return; // don't override\n  }\n  this->corner_annotations_ = annotations;\n}\n\n//---------------------------------------------------------------------------\nQStringList Shape::get_annotations()\n{\n  return this->corner_annotations_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_mesh_manager(QSharedPointer<MeshManager> mesh_manager)\n{\n  this->mesh_manager_ = mesh_manager;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_subject(std::shared_ptr<Subject> subject)\n{\n  this->subject_ = subject;\n  this->original_meshes_.set_number_of_meshes(subject->get_number_of_domains());\n  this->groomed_meshes_.set_number_of_meshes(subject->get_number_of_domains());\n  this->reconstructed_meshes_.set_number_of_meshes(subject->get_number_of_domains());\n\n  if (!this->subject_->get_segmentation_filenames().empty()) {\n\n    /// TODO: Show multiple lines of filenames for multiple domains?\n    std::string filename = this->subject_->get_segmentation_filenames()[0];\n    this->corner_annotations_[0] = QFileInfo(QString::fromStdString(filename)).fileName();\n  }\n\n  if (subject->get_display_name() != \"\") {\n    this->corner_annotations_[0] = QString::fromStdString(subject->get_display_name());\n  }\n}\n\n//---------------------------------------------------------------------------\nstd::shared_ptr<Subject> Shape::get_subject()\n{\n  return this->subject_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::import_original_image(const std::string& filename)\n{\n  this->subject_->set_segmentation_filenames(std::vector<std::string>{filename});\n  this->corner_annotations_[0] = QFileInfo(QString::fromStdString(filename)).fileName();\n}\n\n//---------------------------------------------------------------------------\nMeshGroup Shape::get_original_meshes(bool wait)\n{\n  if (!this->subject_) {\n    std::cerr << \"Error: asked for original mesh when none is present!\\n\";\n    assert(0);\n  }\n\n  if (!this->original_meshes_.valid()) {\n    this->generate_meshes(this->subject_->get_segmentation_filenames(), this->original_meshes_,\n                          true, wait);\n  }\n  return this->original_meshes_;\n}\n\n//---------------------------------------------------------------------------\nMeshGroup Shape::get_groomed_meshes(bool wait)\n{\n  if (!this->subject_) {\n    std::cerr << \"Error: asked for groomed meshes when none are present!\\n\";\n    assert(0);\n  }\n\n  if (!this->groomed_meshes_.valid()) {\n    this->generate_meshes(this->subject_->get_groomed_filenames(), this->groomed_meshes_,\n                          true, wait);\n  }\n  return this->groomed_meshes_;\n}\n\n//---------------------------------------------------------------------------\nMeshGroup Shape::get_reconstructed_meshes(bool wait)\n{\n  if (!this->reconstructed_meshes_.valid()) {\n    auto worlds = this->particles_.get_world_particles();\n    this->reconstructed_meshes_.set_number_of_meshes(worlds.size());\n    for (int i = 0; i < worlds.size(); i++) {\n      MeshHandle mesh = this->mesh_manager_->get_mesh(worlds[i], i);\n      if (mesh) {\n        this->reconstructed_meshes_.set_mesh(i, mesh);\n      }\n    }\n  }\n  return this->reconstructed_meshes_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::reset_groomed_mesh()\n{\n  this->groomed_meshes_ = MeshGroup(this->subject_->get_number_of_domains());\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::clear_reconstructed_mesh()\n{\n  this->reconstructed_meshes_ = MeshGroup(this->subject_->get_number_of_domains());\n}\n\n//---------------------------------------------------------------------------\nbool Shape::import_global_point_files(QStringList filenames)\n{\n  for (int i = 0; i < filenames.size(); i++) {\n    Eigen::VectorXd points;\n    if (!Shape::import_point_file(filenames[i], points)) {\n      return false;\n    }\n    this->global_point_filenames_.push_back(filenames[i].toStdString());\n    this->particles_.set_world_particles(i, points);\n  }\n  this->subject_->set_world_particle_filenames(this->global_point_filenames_);\n  return true;\n}\n\n//---------------------------------------------------------------------------\nbool Shape::import_local_point_files(QStringList filenames)\n{\n  for (int i = 0; i < filenames.size(); i++) {\n    Eigen::VectorXd points;\n    if (!Shape::import_point_file(filenames[i], points)) {\n      throw std::invalid_argument(\"Unable to load file: \" + filenames[i].toStdString());\n    }\n    this->local_point_filenames_.push_back(filenames[i].toStdString());\n    this->particles_.set_local_particles(i, points);\n  }\n  this->subject_->set_local_particle_filenames(this->local_point_filenames_);\n  return true;\n}\n\n//---------------------------------------------------------------------------\nEigen::VectorXd Shape::get_global_correspondence_points()\n{\n  return this->particles_.get_combined_global_particles();\n}\n\n//---------------------------------------------------------------------------\nEigen::VectorXd Shape::get_local_correspondence_points()\n{\n  return this->particles_.get_combined_local_particles();\n}\n\n//---------------------------------------------------------------------------\nint Shape::get_id()\n{\n  return this->id_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_id(int id)\n{\n  this->id_ = id;\n}\n\n//---------------------------------------------------------------------------\nQString Shape::get_original_filename()\n{\n  if (this->subject_->get_segmentation_filenames().size() < 1) {\n    return \"\";\n  }\n  auto string = QString::fromStdString(this->subject_->get_segmentation_filenames()[0]);\n  QFileInfo info(string);\n  return info.fileName();\n}\n\n//---------------------------------------------------------------------------\nQString Shape::get_original_filename_with_path()\n{\n  if (this->subject_->get_segmentation_filenames().size() < 1) {\n    return \"\";\n  }\n  return QString::fromStdString(this->subject_->get_segmentation_filenames()[0]);\n}\n\n//---------------------------------------------------------------------------\nstd::vector<QString> Shape::get_original_filenames()\n{\n  if (this->subject_->get_segmentation_filenames().size() < 1) {\n    return std::vector<QString>();\n  }\n\n  std::vector<QString> filenames;\n  for (auto&& name : this->subject_->get_segmentation_filenames()) {\n    filenames.push_back(QFileInfo(QString::fromStdString(name)).fileName());\n  }\n\n  return filenames;\n}\n\n//---------------------------------------------------------------------------\nstd::vector<QString> Shape::get_original_filenames_with_path()\n{\n  if (this->subject_->get_segmentation_filenames().size() < 1) {\n    return std::vector<QString>();\n  }\n\n  std::vector<QString> filenames;\n  for (auto&& name : this->subject_->get_segmentation_filenames()) {\n    filenames.push_back(QString::fromStdString(name));\n  }\n\n  return filenames;\n}\n\n//---------------------------------------------------------------------------\nQString Shape::get_groomed_filename()\n{\n  if (this->subject_->get_groomed_filenames().size() < 1) {\n    return \"\";\n  }\n  auto string = QString::fromStdString(this->subject_->get_groomed_filenames()[0]);\n  QFileInfo info(string);\n  return info.fileName();\n}\n\n//---------------------------------------------------------------------------\nQString Shape::get_groomed_filename_with_path(int domain)\n{\n  if (domain >= this->subject_->get_groomed_filenames().size()) {\n    return \"\";\n  }\n  return QString::fromStdString(this->subject_->get_groomed_filenames()[domain]);\n}\n\n//---------------------------------------------------------------------------\nQList<Shape::Point> Shape::get_exclusion_sphere_centers()\n{\n  return this->exclusion_sphere_centers_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_exclusion_sphere_centers(QList<Shape::Point> centers)\n{\n  this->exclusion_sphere_centers_ = centers;\n}\n\n//---------------------------------------------------------------------------\nQList<double> Shape::get_exclusion_sphere_radii()\n{\n  return this->exclusion_sphere_radii_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_exclusion_sphere_radii(QList<double> radii)\n{\n  this->exclusion_sphere_radii_ = radii;\n}\n\n//---------------------------------------------------------------------------\nint Shape::get_group_id()\n{\n  return this->group_id_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_group_id(int id)\n{\n  if (this->subject_) {\n    this->subject_->set_group_values({{\"group\", std::to_string(id)}});\n  }\n  this->group_id_ = id;\n}\n\n//---------------------------------------------------------------------------\nstd::vector<Shape::Point> Shape::get_vectors()\n{\n  return this->vectors_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_vectors(std::vector<Shape::Point> vectors)\n{\n  this->vectors_ = vectors;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_transform(vtkSmartPointer<vtkTransform> transform)\n{\n  this->transform_ = transform;\n}\n\n//---------------------------------------------------------------------------\nvtkSmartPointer<vtkTransform> Shape::get_transform(int domain)\n{\n  auto groom_transform = this->get_groomed_transform(domain);\n  if (!groom_transform) {\n    return this->transform_;\n  }\n  return groom_transform;\n}\n\n//---------------------------------------------------------------------------\nvtkSmartPointer<vtkTransform> Shape::get_alignment(int domain)\n{\n  auto groom_transform = this->get_groomed_transform(domain);\n  if (!groom_transform) {\n    vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n    transform->Identity();\n    return transform;\n  }\n  return groom_transform;\n}\n\n//---------------------------------------------------------------------------\nbool Shape::has_alignment()\n{\n  auto groom_transform = this->get_groomed_transform(0);\n  if (groom_transform) {\n    return true;\n  }\n\n  return false;\n}\n\n//---------------------------------------------------------------------------\nvtkSmartPointer<vtkTransform> Shape::get_original_transform(int domain)\n{\n  return this->transform_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::generate_meshes(std::vector<std::string> filenames, MeshGroup& mesh_group,\n                            bool save_transform, bool wait)\n{\n  if (filenames.empty()) {\n    return;\n  }\n\n  for (int i = 0; i < filenames.size(); i++) {\n    auto filename = filenames[i];\n    MeshWorkItem item;\n    item.filename = filename;\n    MeshHandle new_mesh = this->mesh_manager_->get_mesh(item, wait);\n    if (new_mesh) {\n      mesh_group.set_mesh(i, new_mesh);\n\n      // generate a basic centering transform\n      auto com = vtkSmartPointer<vtkCenterOfMass>::New();\n      com->SetInputData(new_mesh->get_poly_data());\n      com->Update();\n      double center[3];\n      com->GetCenter(center);\n\n      if (save_transform && i == 0) { // only store for first domain\n        this->transform_->Identity();\n        this->transform_->Translate(-center[0], -center[1], -center[2]);\n      }\n    }\n  }\n}\n\n//---------------------------------------------------------------------------\nbool Shape::import_point_file(QString filename, Eigen::VectorXd& points)\n{\n  std::ifstream in(filename.toStdString().c_str());\n  if (!in.good()) {\n    return false;\n  }\n  vtkSmartPointer<vtkPoints> vtk_points = vtkSmartPointer<vtkPoints>::New();\n  auto test = filename.toStdString();\n  int num_points = 0;\n  while (in.good()) {\n    double x, y, z;\n    in >> x >> y >> z;\n    if (!in.good()) { break; }\n    vtk_points->InsertNextPoint(x, y, z);\n    num_points++;\n  }\n  in.close();\n  points.setZero();\n  points.resize(num_points * 3);\n\n  int idx = 0;\n  for (int i = 0; i < num_points; i++) {\n    double* pos = vtk_points->GetPoint(i);\n    points[idx++] = pos[0];\n    points[idx++] = pos[1];\n    points[idx++] = pos[2];\n  }\n  return true;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::load_feature(std::string display_mode, std::string feature)\n{\n  auto group = this->get_meshes(display_mode);\n  if (!group.valid()) {\n    // not ready yet\n    return;\n  }\n\n  int num_domains = group.meshes().size();\n\n  for (int d = 0; d < num_domains; d++) {\n\n    vtkSmartPointer<vtkPolyData> poly_data = group.meshes()[d]->get_poly_data();\n\n    // first check if we already have this array\n    auto scalar_array = poly_data->GetPointData()->GetArray(feature.c_str());\n    if (!scalar_array) {\n\n      if (!this->subject_) {\n        return;\n      }\n\n      // first check if we have particle scalars for this feature\n      auto point_features = this->get_point_features(feature);\n      if (point_features.size() > 0 && display_mode == Visualizer::MODE_RECONSTRUCTION_C) { // already loaded as particle scalars\n        this->set_point_features(feature, point_features);\n      }\n      else {\n        // next check if there is a feature filename\n        auto filenames = this->subject_->get_feature_filenames();\n        if (filenames.find(feature) == filenames.end()) {\n          // no feature filename, so load it from the original mesh\n          auto original_meshes = this->get_original_meshes(true).meshes();\n\n          if (original_meshes.size() > d) {\n            // assign scalars at points\n            this->load_feature_from_mesh(feature, original_meshes[d]);\n          }\n        }\n        else {\n          // read the feature\n          QString filename = QString::fromStdString(filenames[feature]);\n          try {\n            ReaderType::Pointer reader = ReaderType::New();\n            reader->SetFileName(filename.toStdString());\n            reader->Update();\n            ImageType::Pointer image = reader->GetOutput();\n            group.meshes()[d]->apply_feature_map(feature, image);\n            this->apply_feature_to_points(feature, image);\n          } catch (itk::ExceptionObject& excep) {\n            QMessageBox::warning(0, \"Unable to open file\",\n                                 \"Error opening file: \\\"\" + filename + \"\\\"\");\n          }\n        }\n      }\n    }\n  }\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::apply_feature_to_points(std::string feature, ImageType::Pointer image)\n{\n  using LinearInterpolatorType = itk::LinearInterpolateImageFunction<ImageType, double>;\n\n  LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New();\n  interpolator->SetInputImage(image);\n\n  auto region = image->GetLargestPossibleRegion();\n\n  Eigen::VectorXd all_locals = this->get_local_correspondence_points();\n\n  int num_points = all_locals.size() / 3;\n\n  Eigen::VectorXf values(num_points);\n\n  int idx = 0;\n  for (int i = 0; i < num_points; ++i) {\n\n    double p[3];\n    p[0] = all_locals[idx++];\n    p[1] = all_locals[idx++];\n    p[2] = all_locals[idx++];\n\n    double* pt = p;\n\n    ImageType::PointType pitk;\n    pitk[0] = pt[0];\n    pitk[1] = pt[1];\n    pitk[2] = pt[2];\n\n    LinearInterpolatorType::ContinuousIndexType index;\n    image->TransformPhysicalPointToContinuousIndex(pitk, index);\n\n    auto pixel = 0;\n    if (region.IsInside(index)) {\n      pixel = interpolator->EvaluateAtContinuousIndex(index);\n    }\n\n    values[i] = pixel;\n  }\n\n  this->set_point_features(feature, values);\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::load_feature_from_mesh(std::string feature, MeshHandle mesh)\n{\n  vtkSmartPointer<vtkPolyData> from_mesh = mesh->get_poly_data();\n\n  // Create the tree\n  vtkSmartPointer<vtkKdTreePointLocator> kd_tree = vtkSmartPointer<vtkKdTreePointLocator>::New();\n  kd_tree->SetDataSet(from_mesh);\n  kd_tree->BuildLocator();\n\n  Eigen::VectorXd all_locals = this->get_local_correspondence_points();\n\n  int num_points = all_locals.size() / 3;\n\n  Eigen::VectorXf values(num_points);\n\n  vtkDataArray* from_array = from_mesh->GetPointData()->GetArray(feature.c_str());\n  if (!from_array) {\n    return;\n  }\n\n  int idx = 0;\n  for (int i = 0; i < num_points; ++i) {\n\n    double p[3];\n    p[0] = all_locals[idx++];\n    p[1] = all_locals[idx++];\n    p[2] = all_locals[idx++];\n\n    vtkIdType id = kd_tree->FindClosestPoint(p);\n    vtkVariant var = from_array->GetVariantValue(id);\n\n    values[i] = var.ToDouble();\n  }\n\n  this->set_point_features(feature, values);\n}\n\n//---------------------------------------------------------------------------\nEigen::VectorXf Shape::get_point_features(std::string feature)\n{\n  auto it = this->point_features_.find(feature);\n  if (it == this->point_features_.end()) {\n    return Eigen::VectorXf();\n  }\n\n  return it->second;\n}\n\n//---------------------------------------------------------------------------\nvtkSmartPointer<vtkTransform> Shape::get_groomed_transform(int domain)\n{\n  auto transforms = this->subject_->get_groomed_transforms();\n  if (domain < 0) { // global alignment is stored at the end\n    domain = transforms.size() - 1;\n  }\n  if (domain < transforms.size()) {\n    return ProjectUtils::convert_transform(transforms[domain]);\n  }\n  return nullptr;\n}\n\n//---------------------------------------------------------------------------\nvtkSmartPointer<vtkTransform> Shape::get_procrustest_transform(int domain)\n{\n  auto transforms = this->subject_->get_procrustes_transforms();\n  if (domain < transforms.size()) {\n    return ProjectUtils::convert_transform(transforms[domain]);\n  }\n  return nullptr;\n}\n\n//---------------------------------------------------------------------------\nstd::vector<vtkSmartPointer<vtkTransform>> Shape::get_procrustest_transforms()\n{\n  auto lists = this->subject_->get_procrustes_transforms();\n  std::vector<vtkSmartPointer<vtkTransform>> transforms;\n  for (size_t i = 0; i < lists.size(); i++) {\n    transforms.push_back(ProjectUtils::convert_transform(lists[i]));\n  }\n  return transforms;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_point_features(std::string feature, Eigen::VectorXf values)\n{\n  this->point_features_[feature] = values;\n\n  auto group = this->get_meshes(Visualizer::MODE_RECONSTRUCTION_C);\n\n  if (group.valid()) {\n    for (auto mesh : group.meshes()) {\n      mesh->interpolate_scalars_to_mesh(feature,\n                                        this->get_global_correspondence_points(), values);\n    }\n  }\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_particles(StudioParticles particles)\n{\n  this->particles_ = particles;\n}\n\n//---------------------------------------------------------------------------\nStudioParticles Shape::get_particles()\n{\n  return this->particles_;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_particle_transform(vtkSmartPointer<vtkTransform> transform)\n{\n  this->particles_.set_procrustes_transforms(this->get_procrustest_transforms());\n  this->particles_.set_transform(transform);\n}\n\n//---------------------------------------------------------------------------\nvtkSmartPointer<vtkTransform> Shape::get_reconstruction_transform(int domain)\n{\n  if (domain < this->reconstruction_transforms_.size()) {\n    return this->reconstruction_transforms_[domain];\n  }\n\n  // no transforms, just return identity\n  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n  transform->Identity();\n  return transform;\n}\n\n//---------------------------------------------------------------------------\nEigen::VectorXd Shape::get_global_correspondence_points_for_display()\n{\n  auto worlds = this->particles_.get_world_particles();\n  int size = 0;\n  for (int i = 0; i < worlds.size(); i++) {\n    size += worlds[i].size();\n  }\n  Eigen::VectorXd points;\n  points.resize(size);\n\n  int idx = 0;\n  for (int i = 0; i < worlds.size(); i++) {\n    for (int j = 0; j < worlds[i].size(); j += 3) {\n      double p[3];\n      p[0] = worlds[i][j + 0];\n      p[1] = worlds[i][j + 1];\n      p[2] = worlds[i][j + 2];\n      if (this->reconstruction_transforms_.size() > i) {\n        double* pt = this->reconstruction_transforms_[i]->TransformPoint(p);\n        points[idx++] = pt[0];\n        points[idx++] = pt[1];\n        points[idx++] = pt[2];\n      }\n      else {\n        points[idx++] = p[0];\n        points[idx++] = p[1];\n        points[idx++] = p[2];\n      }\n    }\n  }\n\n  return points;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_reconstruction_transforms(std::vector<vtkSmartPointer<vtkTransform>> transforms)\n{\n  this->reconstruction_transforms_ = transforms;\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::load_feature_from_scalar_file(std::string filename, std::string feature_name)\n{\n  QString qfilename = QString::fromStdString(filename);\n\n  if (!QFile(qfilename).exists()) {\n    return;\n  }\n\n  QFile file(qfilename);\n  if (!file.open(QIODevice::ReadOnly)) {\n    STUDIO_LOG_ERROR(\"Unable to open scalar file: \" + qfilename);\n    return;\n  }\n\n  auto data = QString(file.readAll()).trimmed();\n  auto lines = data.split('\\n');\n  file.close();\n\n  Eigen::VectorXf values(lines.size());\n  for (int i = 0; i < lines.size(); i++) {\n    float value = QString(lines[i]).toFloat();\n    values[i] = value;\n  }\n\n  this->set_point_features(feature_name, values);\n}\n\n//---------------------------------------------------------------------------\nvoid Shape::set_override_feature(string feature)\n{\n  this->override_feature_ = feature;\n}\n\n//---------------------------------------------------------------------------\nstring Shape::get_override_feature()\n{\n  return this->override_feature_;\n}\n}\n", "meta": {"hexsha": "16c15a0193e4d57e89447532618718c3eef5212d", "size": 23180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Studio/src/Data/Shape.cpp", "max_stars_repo_name": "ben2k/ShapeWorks", "max_stars_repo_head_hexsha": "a61d2710c5592db1dc00b4fe11990e512220161f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-14T19:04:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T19:04:58.000Z", "max_issues_repo_path": "Studio/src/Data/Shape.cpp", "max_issues_repo_name": "ben2k/ShapeWorks", "max_issues_repo_head_hexsha": "a61d2710c5592db1dc00b4fe11990e512220161f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Studio/src/Data/Shape.cpp", "max_forks_repo_name": "ben2k/ShapeWorks", "max_forks_repo_head_hexsha": "a61d2710c5592db1dc00b4fe11990e512220161f", "max_forks_repo_licenses": ["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.4599211564, "max_line_length": 129, "alphanum_fraction": 0.5496980155, "num_tokens": 4729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.156769939570943}}
{"text": "// Copyright (c) 2015-2018 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 \"cell_caller.hpp\"\n\n#include <typeinfo>\n#include <unordered_map>\n#include <deque>\n#include <algorithm>\n#include <numeric>\n#include <iterator>\n#include <utility>\n#include <stdexcept>\n#include <iostream>\n\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/tuple/tuple.hpp>\n\n#include \"basics/genomic_region.hpp\"\n#include \"containers/probability_matrix.hpp\"\n#include \"core/types/allele.hpp\"\n#include \"core/types/variant.hpp\"\n#include \"core/types/phylogeny.hpp\"\n#include \"core/types/calls/cell_variant_call.hpp\"\n#include \"core/types/calls/reference_call.hpp\"\n#include \"core/models/genotype/uniform_genotype_prior_model.hpp\"\n#include \"core/models/genotype/coalescent_genotype_prior_model.hpp\"\n#include \"core/models/mutation/denovo_model.hpp\"\n#include \"core/models/genotype/single_cell_prior_model.hpp\"\n#include \"utils/maths.hpp\"\n#include \"logging/logging.hpp\"\n\nnamespace octopus {\n\nCellCaller::CellCaller(Caller::Components&& components,\n                       Caller::Parameters general_parameters,\n                       Parameters specific_parameters)\n: Caller {std::move(components), std::move(general_parameters)}\n, parameters_{std::move(specific_parameters)}\n{}\n\nstd::string CellCaller::do_name() const\n{\n    return \"cell\";\n}\n\nCellCaller::CallTypeSet CellCaller::do_call_types() const\n{\n    return {std::type_index(typeid(CellVariantCall))};\n}\n\nunsigned CellCaller::do_min_callable_ploidy() const\n{\n    return parameters_.ploidy;\n}\n\nunsigned CellCaller::do_max_callable_ploidy() const\n{\n    return parameters_.ploidy;\n}\n\nstd::size_t CellCaller::do_remove_duplicates(std::vector<Haplotype>& haplotypes) const\n{\n    if (parameters_.deduplicate_haplotypes_with_prior_model) {\n        if (haplotypes.size() < 2) return 0;\n        CoalescentModel::Parameters model_params {};\n        if (parameters_.prior_model_params) model_params = *parameters_.prior_model_params;\n        Haplotype reference {mapped_region(haplotypes.front()), reference_.get()};\n        CoalescentModel model {std::move(reference), model_params, haplotypes.size(), CoalescentModel::CachingStrategy::none};\n        const CoalescentProbabilityGreater cmp {std::move(model)};\n        return octopus::remove_duplicates(haplotypes, cmp);\n    } else {\n        return Caller::do_remove_duplicates(haplotypes);\n    }\n}\n\n// CellCaller::Latents public methods\n\nCellCaller::Latents::Latents(const CellCaller& caller,\n                             std::vector<Haplotype> haplotypes,\n                             std::vector<Genotype<Haplotype>> genotypes,\n                             std::vector<model::SingleCellModel::Inferences> inferences)\n: caller_ {caller}\n, haplotypes_ {std::move(haplotypes)}\n, genotypes_ {std::move(genotypes)}\n, phylogeny_inferences_ {std::move(inferences)}\n{\n    phylogeny_posteriors_.resize(phylogeny_inferences_.size());\n    std::transform(std::cbegin(phylogeny_inferences_), std::cend(phylogeny_inferences_), std::begin(phylogeny_posteriors_),\n                   [] (const auto& inferences) { return inferences.log_evidence; });\n    maths::normalise_exp(phylogeny_posteriors_);\n}\n\nnamespace {\n\nusing InverseGenotypeTable = std::vector<std::vector<std::size_t>>;\n\nauto make_inverse_genotype_table(const std::vector<Haplotype>& haplotypes,\n                                 const std::vector<Genotype<Haplotype>>& genotypes)\n{\n    assert(!haplotypes.empty() && !genotypes.empty());\n    using HaplotypeReference = std::reference_wrapper<const Haplotype>;\n    std::unordered_map<HaplotypeReference, std::vector<std::size_t>> result_map {haplotypes.size()};\n    const auto cardinality = element_cardinality_in_genotypes(static_cast<unsigned>(haplotypes.size()),\n                                                              genotypes.front().ploidy());\n    for (const auto& haplotype : haplotypes) {\n        auto itr = result_map.emplace(std::piecewise_construct,\n                                      std::forward_as_tuple(std::cref(haplotype)),\n                                      std::forward_as_tuple());\n        itr.first->second.reserve(cardinality);\n    }\n    for (std::size_t i {0}; i < genotypes.size(); ++i) {\n        for (const auto& haplotype : genotypes[i]) {\n            result_map.at(haplotype).emplace_back(i);\n        }\n    }\n    InverseGenotypeTable result {};\n    result.reserve(haplotypes.size());\n    for (const auto& haplotype : haplotypes) {\n        auto& indices = result_map.at(haplotype);\n        std::sort(std::begin(indices), std::end(indices));\n        indices.erase(std::unique(std::begin(indices), std::end(indices)), std::end(indices));\n        result.emplace_back(std::move(indices));\n    }\n    return result;\n}\n\nusing GenotypeMarginalPosteriorVector = std::vector<double>;\nusing GenotypeMarginalPosteriorMatrix = std::vector<GenotypeMarginalPosteriorVector>;\n\nauto calculate_haplotype_posteriors(const std::vector<Haplotype>& haplotypes,\n                                    const std::vector<Genotype<Haplotype>>& genotypes,\n                                    const ProbabilityMatrix<Genotype<Haplotype>>& genotype_posteriors,\n                                    const InverseGenotypeTable& inverse_genotypes)\n{\n    std::unordered_map<std::reference_wrapper<const Haplotype>, double> result {haplotypes.size()};\n    auto itr = std::cbegin(inverse_genotypes);\n    std::vector<std::size_t> genotype_indices(genotypes.size());\n    std::iota(std::begin(genotype_indices), std::end(genotype_indices), 0);\n    // noncontaining genotypes are genotypes that do not contain a particular haplotype.\n    const auto num_noncontaining_genotypes = genotypes.size() - itr->size();\n    std::vector<std::size_t> noncontaining_genotype_indices(num_noncontaining_genotypes);\n    for (const auto& haplotype : haplotypes) {\n        std::set_difference(std::cbegin(genotype_indices), std::cend(genotype_indices),\n                            std::cbegin(*itr), std::cend(*itr),\n                            std::begin(noncontaining_genotype_indices));\n        double prob_not_observed {1};\n        for (const auto& p : genotype_posteriors) {\n            const auto slice = genotype_posteriors(p.first);\n            std::vector<double> sample_genotype_posteriors {std::cbegin(slice), std::cend(slice)};\n            prob_not_observed *= std::accumulate(std::cbegin(noncontaining_genotype_indices),\n                                                 std::cend(noncontaining_genotype_indices),\n                                                 0.0, [&sample_genotype_posteriors]\n                                                 (const auto curr, const auto i) {\n                return curr + sample_genotype_posteriors[i];\n            });\n        }\n        result.emplace(haplotype, 1.0 - prob_not_observed);\n        ++itr;\n    }\n    return result;\n}\n\nauto calculate_haplotype_posteriors(const std::vector<Haplotype>& haplotypes,\n                                    const std::vector<Genotype<Haplotype>>& genotypes,\n                                    const ProbabilityMatrix<Genotype<Haplotype>>& genotype_posteriors)\n{\n    const auto inverse_genotypes = make_inverse_genotype_table(haplotypes, genotypes);\n    return calculate_haplotype_posteriors(haplotypes, genotypes, genotype_posteriors, inverse_genotypes);\n}\n\n} // namespace\n\nstd::shared_ptr<CellCaller::Latents::HaplotypeProbabilityMap>\nCellCaller::Latents::haplotype_posteriors() const noexcept\n{\n    if (haplotype_posteriors_ == nullptr) {\n        const auto marginal_genotype_posteriors = this->genotype_posteriors();\n        haplotype_posteriors_ = std::make_unique<HaplotypeProbabilityMap>(calculate_haplotype_posteriors(haplotypes_, genotypes_, *marginal_genotype_posteriors));\n    }\n    return haplotype_posteriors_;\n}\n\nnamespace {\n\ntemplate <typename... T>\nauto zip(const T&... containers) -> boost::iterator_range<boost::zip_iterator<decltype(boost::make_tuple(std::begin(containers)...))>>\n{\n    auto zip_begin = boost::make_zip_iterator(boost::make_tuple(std::begin(containers)...));\n    auto zip_end   = boost::make_zip_iterator(boost::make_tuple(std::end(containers)...));\n    return boost::make_iterator_range(zip_begin, zip_end);\n}\n\n} // namespace\n\nstd::shared_ptr<CellCaller::Latents::GenotypeProbabilityMap>\nCellCaller::Latents::genotype_posteriors() const noexcept\n{\n    if (genotype_posteriors_ == nullptr) {\n        genotype_posteriors_ = std::make_unique<GenotypeProbabilityMap>(std::cbegin(genotypes_), std::cend(genotypes_));\n        for (std::size_t sample_idx {0}; sample_idx < caller_.samples_.size(); ++sample_idx) {\n            std::vector<double> marginal_genotype_posteriors(genotypes_.size());\n            for (const auto& p : zip(phylogeny_inferences_, phylogeny_posteriors_)) {\n                const auto& phylogeny = p.get<0>().phylogeny;\n                for (unsigned t {0}; t < phylogeny.size(); ++t) {\n                    const auto& group = phylogeny.group(t).value;\n                    for (std::size_t genotype_idx {0}; genotype_idx < group.genotype_posteriors.size(); ++genotype_idx) {\n                        marginal_genotype_posteriors[genotype_idx] += p.get<1>()\n                                * group.sample_attachment_posteriors[sample_idx]\n                                * group.genotype_posteriors[genotype_idx];\n                    }\n                }\n            }\n            insert_sample(caller_.samples_[sample_idx], std::move(marginal_genotype_posteriors), *genotype_posteriors_);\n        }\n    }\n    return genotype_posteriors_;\n}\n\n// CellCaller::Latents private methods\n\ntemplate <typename S>\nvoid log(const model::SingleCellModel::Inferences& inferences,\n         const std::vector<SampleName>& samples,\n         const std::vector<Genotype<Haplotype>>& genotypes,\n         S&& logger)\n{\n    std::vector<std::size_t> map_genotypes {};\n    map_genotypes.reserve(inferences.phylogeny.size());\n    std::vector<std::pair<std::size_t, double>> map_sample_assignments(samples.size());\n    for (std::size_t group_id {0}; group_id < inferences.phylogeny.size(); ++group_id) {\n        const auto& group = inferences.phylogeny.group(group_id).value;\n        auto map_itr = std::max_element(std::cbegin(group.genotype_posteriors), std::cend(group.genotype_posteriors));\n        auto map_idx = static_cast<std::size_t>(std::distance(std::cbegin(group.genotype_posteriors), map_itr));\n        map_genotypes.push_back(map_idx);\n        for (std::size_t sample_idx {0}; sample_idx < samples.size(); ++sample_idx) {\n            if (group.sample_attachment_posteriors[sample_idx] > map_sample_assignments[sample_idx].second) {\n                map_sample_assignments[sample_idx].first = group_id;\n                map_sample_assignments[sample_idx].second = group.sample_attachment_posteriors[sample_idx];\n            }\n        }\n    }\n    logger << \"MAP genotypes: \" << '\\n';\n    for (std::size_t group_id {0}; group_id < map_genotypes.size(); ++group_id) {\n        logger << group_id << \": \"; debug::print_variant_alleles(logger, genotypes[map_genotypes[group_id]]); logger << '\\n';\n    }\n    logger << \"Sample MAP assignments:\" << '\\n';\n    for (std::size_t sample_idx {0}; sample_idx < samples.size(); ++sample_idx) {\n        logger << samples[sample_idx] << \": \" << map_sample_assignments[sample_idx].first\n               << \" (\" << map_sample_assignments[sample_idx].second << \")\\n\";\n    }\n    logger << \"Evidence: \" << inferences.log_evidence << '\\n';\n}\n\nvoid log(const model::SingleCellModel::Inferences& inferences,\n         const std::vector<SampleName>& samples,\n         const std::vector<Genotype<Haplotype>>& genotypes,\n         boost::optional<logging::DebugLogger>& logger)\n{\n    if (logger) {\n        log(inferences, samples, genotypes, stream(*logger));\n    }\n}\n\nstd::unique_ptr<CellCaller::Caller::Latents>\nCellCaller::infer_latents(const std::vector<Haplotype>& haplotypes, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    std::vector<GenotypeIndex> genotype_indices {};\n    auto genotypes = generate_all_genotypes(haplotypes, parameters_.ploidy, genotype_indices);\n    if (debug_log_) stream(*debug_log_) << \"There are \" << genotypes.size() << \" candidate genotypes\";\n    const auto genotype_prior_model = make_prior_model(haplotypes);\n    DeNovoModel mutation_model {parameters_.mutation_model_parameters};\n    model::SingleCellPriorModel::Parameters cell_prior_params {};\n    cell_prior_params.copy_number_log_probability = std::log(1e-6);\n    model::SingleCellModel::Parameters model_parameters {};\n    model_parameters.dropout_concentration = parameters_.dropout_concentration;\n    model_parameters.group_concentration = 1.0;\n    model::SingleCellModel::AlgorithmParameters config {};\n    config.max_genotype_combinations = parameters_.max_joint_genotypes;\n    if (parameters_.max_vb_seeds) config.max_seeds = *parameters_.max_vb_seeds;\n    \n    using CellPhylogeny =  model::SingleCellPriorModel::CellPhylogeny;\n    CellPhylogeny single_group_phylogeny {CellPhylogeny::Group {0}};\n    model::SingleCellPriorModel single_group_prior_model {std::move(single_group_phylogeny), *genotype_prior_model, mutation_model, cell_prior_params};\n    model::SingleCellModel single_group_model {samples_, std::move(single_group_prior_model), model_parameters, config};\n    auto single_group_inferences = single_group_model.evaluate(genotypes, haplotype_likelihoods);\n    \n    CellPhylogeny two_group_phylogeny {CellPhylogeny::Group {0}};\n    two_group_phylogeny.add_descendant(CellPhylogeny::Group {1}, 0);\n    model::SingleCellPriorModel two_group_prior_model {std::move(two_group_phylogeny), *genotype_prior_model, mutation_model, cell_prior_params};\n    model::SingleCellModel two_group_model {samples_, std::move(two_group_prior_model), model_parameters, config};\n    auto two_group_inferences = two_group_model.evaluate(genotypes, haplotype_likelihoods);\n    \n    log(single_group_inferences, samples_, genotypes, debug_log_);\n    log(two_group_inferences, samples_, genotypes, debug_log_);\n    \n    std::vector<model::SingleCellModel::Inferences> inferences {std::move(single_group_inferences), std::move(two_group_inferences)};\n    return std::make_unique<Latents>(*this, haplotypes, std::move(genotypes), std::move(inferences));\n}\n\nboost::optional<double>\nCellCaller::calculate_model_posterior(const std::vector<Haplotype>& haplotypes,\n                                      const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                                      const Caller::Latents& latents) const\n{\n    return calculate_model_posterior(haplotypes, haplotype_likelihoods, dynamic_cast<const Latents&>(latents));\n}\n\nboost::optional<double>\nCellCaller::calculate_model_posterior(const std::vector<Haplotype>& haplotypes,\n                                      const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                                      const Latents& latents) const\n{\n    return boost::none;\n}\n\nstd::vector<std::unique_ptr<octopus::VariantCall>>\nCellCaller::call_variants(const std::vector<Variant>& candidates, const Caller::Latents& latents) const\n{\n    return call_variants(candidates, dynamic_cast<const Latents&>(latents));\n}\n\nnamespace {\n\nusing GenotypeProbabilityMap = ProbabilityMatrix<Genotype<Haplotype>>::InnerMap;\nusing PopulationGenotypeProbabilityMap = ProbabilityMatrix<Genotype<Haplotype>>;\n\nusing VariantReference = std::reference_wrapper<const Variant>;\nusing VariantPosteriorVector = std::vector<std::pair<VariantReference, std::vector<Phred<double>>>>;\n\nstruct VariantCall : Mappable<VariantCall>\n{\n    VariantCall() = delete;\n    VariantCall(const std::pair<VariantReference, std::vector<Phred<double>>>& p)\n    : variant {p.first}\n    , posteriors {p.second}\n    {}\n    VariantCall(const Variant& variant, std::vector<Phred<double>> posterior)\n    : variant {variant}\n    , posteriors {posterior}\n    {}\n    \n    const GenomicRegion& mapped_region() const noexcept\n    {\n        return octopus::mapped_region(variant.get());\n    }\n    \n    VariantReference variant;\n    std::vector<Phred<double>> posteriors;\n};\n\nusing VariantCalls = std::vector<VariantCall>;\n\nstruct GenotypeCall\n{\n    Genotype<Allele> genotype;\n    Phred<double> posterior;\n};\n\nusing GenotypeCalls = std::vector<std::vector<GenotypeCall>>;\n\n// allele posterior calculations\n\nusing AlleleBools           = std::deque<bool>; // using std::deque because std::vector<bool> is evil\nusing GenotypePropertyBools = std::vector<AlleleBools>;\n\nauto marginalise(const GenotypeProbabilityMap& genotype_posteriors,\n                 const AlleleBools& contained_alleles)\n{\n    auto p = std::inner_product(std::cbegin(genotype_posteriors), std::cend(genotype_posteriors),\n                                std::cbegin(contained_alleles), 0.0, std::plus<> {},\n                                [] (const auto& p, const bool is_contained) {\n                                    return is_contained ? 0.0 : p.second;\n                                });\n    return probability_to_phred(p);\n}\n\nauto compute_sample_allele_posteriors(const GenotypeProbabilityMap& genotype_posteriors,\n                                      const GenotypePropertyBools& contained_alleles)\n{\n    std::vector<Phred<double>> result {};\n    result.reserve(contained_alleles.size());\n    for (const auto& allele : contained_alleles) {\n        result.emplace_back(marginalise(genotype_posteriors, allele));\n    }\n    return result;\n}\n\nauto get_contained_alleles(const PopulationGenotypeProbabilityMap& genotype_posteriors,\n                           const std::vector<Allele>& alleles)\n{\n    const auto num_genotypes = genotype_posteriors.size2();\n    GenotypePropertyBools result {};\n    if (num_genotypes == 0 || genotype_posteriors.empty1() || alleles.empty()) {\n        return result;\n    }\n    result.reserve(alleles.size());\n    const auto& test_sample   = genotype_posteriors.begin()->first;\n    const auto genotype_begin = genotype_posteriors.begin(test_sample);\n    const auto genotype_end   = genotype_posteriors.end(test_sample);\n    for (const auto& allele : alleles) {\n        result.emplace_back(num_genotypes);\n        std::transform(genotype_begin, genotype_end, std::begin(result.back()),\n                       [&] (const auto& p) { return contains(p.first, allele); });\n    }\n    return result;\n}\n\nusing AllelePosteriorMatrix = std::vector<std::vector<Phred<double>>>;\n\nauto compute_posteriors(const std::vector<SampleName>& samples,\n                        const std::vector<Allele>& alleles,\n                        const PopulationGenotypeProbabilityMap& genotype_posteriors)\n{\n    const auto contained_alleles = get_contained_alleles(genotype_posteriors, alleles);\n    AllelePosteriorMatrix result {};\n    result.reserve(genotype_posteriors.size1());\n    for (const auto& sample : samples) {\n        result.emplace_back(compute_sample_allele_posteriors(genotype_posteriors[sample], contained_alleles));\n    }\n    return result;\n}\n\nauto extract_ref_alleles(const std::vector<Variant>& variants)\n{\n    std::vector<Allele> result {};\n    result.reserve(variants.size());\n    std::transform(std::cbegin(variants), std::cend(variants), std::back_inserter(result),\n                   [] (const auto& variant) { return variant.ref_allele(); });\n    return result;\n}\n\nauto extract_alt_alleles(const std::vector<Variant>& variants)\n{\n    std::vector<Allele> result {};\n    result.reserve(variants.size());\n    std::transform(std::cbegin(variants), std::cend(variants), std::back_inserter(result),\n                   [] (const auto& variant) { return variant.alt_allele(); });\n    return result;\n}\n\nauto compute_posteriors(const std::vector<SampleName>& samples,\n                        const std::vector<Variant>& variants,\n                        const PopulationGenotypeProbabilityMap& genotype_posteriors)\n{\n    const auto allele_posteriors = compute_posteriors(samples, extract_alt_alleles(variants), genotype_posteriors);\n    VariantPosteriorVector result {};\n    result.reserve(variants.size());\n    for (std::size_t i {0}; i < variants.size(); ++i) {\n        std::vector<Phred<double>> sample_posteriors(samples.size());\n        std::transform(std::cbegin(allele_posteriors), std::cend(allele_posteriors), std::begin(sample_posteriors),\n                       [i] (const auto& ps) { return ps[i]; });\n        result.emplace_back(variants[i], std::move(sample_posteriors));\n    }\n    return result;\n}\n\n// haplotype genotype calling\n\nauto call_genotype(const PopulationGenotypeProbabilityMap::InnerMap& genotype_posteriors)\n{\n    return std::max_element(std::cbegin(genotype_posteriors), std::cend(genotype_posteriors),\n                            [] (const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; })->first;\n}\n\nauto call_genotypes(const std::vector<SampleName>& samples, const PopulationGenotypeProbabilityMap& genotype_posteriors)\n{\n    std::vector<Genotype<Haplotype>> result {};\n    result.reserve(samples.size());\n    for (const auto& sample : samples) {\n        result.push_back(call_genotype(genotype_posteriors[sample]));\n    }\n    return result;\n}\n\n// variant calling\n\nbool has_above(const std::vector<Phred<double>>& posteriors, const Phred<double> min_posterior)\n{\n    return std::any_of(std::cbegin(posteriors), std::cend(posteriors), [=] (auto p) { return p >= min_posterior; });\n}\n\nbool contains_alt(const Genotype<Haplotype>& genotype_call, const VariantReference& candidate)\n{\n    return includes(genotype_call, candidate.get().alt_allele());\n}\n\nbool contains_alt(const std::vector<Genotype<Haplotype>>& genotype_calls, const VariantReference& candidate)\n{\n    return std::any_of(std::cbegin(genotype_calls), std::cend(genotype_calls),\n                       [&] (const auto& genotype) { return contains_alt(genotype, candidate); });\n}\n\nVariantCalls call_candidates(const VariantPosteriorVector& candidate_posteriors,\n                             const std::vector<Genotype<Haplotype>>& genotype_calls,\n                             const Phred<double> min_posterior)\n{\n    VariantCalls result {};\n    result.reserve(candidate_posteriors.size());\n    std::copy_if(std::cbegin(candidate_posteriors), std::cend(candidate_posteriors),\n                 std::back_inserter(result),\n                 [&genotype_calls, min_posterior] (const auto& p) {\n                     return has_above(p.second, min_posterior) && contains_alt(genotype_calls, p.first);\n                 });\n    return result;\n}\n\n// allele genotype calling\n\nauto marginalise(const Genotype<Allele>& genotype, const GenotypeProbabilityMap& genotype_posteriors)\n{\n    auto p = std::accumulate(std::cbegin(genotype_posteriors), std::cend(genotype_posteriors), 0.0,\n                             [&genotype] (const double curr, const auto& p) {\n                                 return curr + (contains(p.first, genotype) ? 0.0 : p.second);\n                             });\n    return probability_to_phred(p);\n}\n\nauto call_genotypes(const std::vector<SampleName>& samples,\n                    const std::vector<Genotype<Haplotype>>& genotype_calls,\n                    const PopulationGenotypeProbabilityMap& genotype_posteriors,\n                    const std::vector<GenomicRegion>& variant_regions)\n{\n    GenotypeCalls result {};\n    result.reserve(variant_regions.size());\n    for (const auto& region : variant_regions) {\n        std::vector<GenotypeCall> region_calls {};\n        region_calls.reserve(samples.size());\n        for (std::size_t s {0}; s < samples.size(); ++s) {\n            auto genotype_chunk = copy<Allele>(genotype_calls[s], region);\n            const auto posterior = marginalise(genotype_chunk, genotype_posteriors[samples[s]]);\n            region_calls.push_back({std::move(genotype_chunk), posterior});\n        }\n        result.push_back(std::move(region_calls));\n    }\n    return result;\n}\n\n// output\n\noctopus::VariantCall::GenotypeCall convert(GenotypeCall&& call)\n{\n    return octopus::VariantCall::GenotypeCall {std::move(call.genotype), call.posterior};\n}\n\nstd::unique_ptr<octopus::VariantCall>\ntransform_call(const std::vector<SampleName>& samples,\n               VariantCall&& variant_call,\n               std::vector<GenotypeCall>&& sample_genotype_calls)\n{\n    std::vector<std::pair<SampleName, Call::GenotypeCall>> tmp {};\n    tmp.reserve(samples.size());\n    std::transform(std::cbegin(samples), std::cend(samples),\n                   std::make_move_iterator(std::begin(sample_genotype_calls)),\n                   std::back_inserter(tmp),\n                   [] (const auto& sample, auto&& genotype) {\n                       return std::make_pair(sample, convert(std::move(genotype)));\n                   });\n    auto quality = *std::max_element(std::cbegin(variant_call.posteriors), std::cend(variant_call.posteriors));\n    return std::make_unique<CellVariantCall>(variant_call.variant.get(), std::move(tmp), quality);\n}\n\nauto transform_calls(const std::vector<SampleName>& samples,\n                     VariantCalls&& variant_calls,\n                     GenotypeCalls&& genotype_calls)\n{\n    std::vector<std::unique_ptr<octopus::VariantCall>> result {};\n    result.reserve(variant_calls.size());\n    std::transform(std::make_move_iterator(std::begin(variant_calls)), std::make_move_iterator(std::end(variant_calls)),\n                   std::make_move_iterator(std::begin(genotype_calls)), std::back_inserter(result),\n                   [&samples] (auto&& variant_call, auto&& genotype_call) {\n                       return transform_call(samples, std::move(variant_call), std::move(genotype_call));\n                   });\n    return result;\n}\n\n} // namespace\n\nstd::vector<std::unique_ptr<octopus::VariantCall>>\nCellCaller::call_variants(const std::vector<Variant>& candidates, const Latents& latents) const\n{\n    const auto& genotype_posteriors = *(latents.genotype_posteriors());\n    const auto sample_candidate_posteriors = compute_posteriors(samples_, candidates, genotype_posteriors);\n    const auto genotype_calls = call_genotypes(samples_, genotype_posteriors);\n    auto variant_calls = call_candidates(sample_candidate_posteriors, genotype_calls, parameters_.min_variant_posterior);\n    const auto called_regions = extract_regions(variant_calls);\n    auto allele_genotype_calls = call_genotypes(samples_, genotype_calls, genotype_posteriors, called_regions);\n    return transform_calls(samples_, std::move(variant_calls), std::move(allele_genotype_calls));\n}\n\nstd::vector<std::unique_ptr<ReferenceCall>>\nCellCaller::call_reference(const std::vector<Allele>& alleles, const Caller::Latents& latents, const ReadPileupMap& pileup) const\n{\n    return call_reference(alleles, dynamic_cast<const Latents&>(latents), pileup);\n}\n\nstd::vector<std::unique_ptr<ReferenceCall>>\nCellCaller::call_reference(const std::vector<Allele>& alleles, const Latents& latents, const ReadPileupMap& pileup) const\n{\n    return {};\n}\n\nstd::unique_ptr<GenotypePriorModel> CellCaller::make_prior_model(const std::vector<Haplotype>& haplotypes) const\n{\n    if (parameters_.prior_model_params) {\n        return std::make_unique<CoalescentGenotypePriorModel>(CoalescentModel {\n        Haplotype {mapped_region(haplotypes.front()), reference_},\n        *parameters_.prior_model_params, haplotypes.size(), CoalescentModel::CachingStrategy::address\n        });\n    } else {\n        return std::make_unique<UniformGenotypePriorModel>();\n    }\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "02a8a3b28071c63f9cc50e3d06d9c3b9d2106a13", "size": 27429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/callers/cell_caller.cpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "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/callers/cell_caller.cpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/callers/cell_caller.cpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.5275974026, "max_line_length": 162, "alphanum_fraction": 0.6853330417, "num_tokens": 6324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.1567699382963832}}
{"text": "// Author(s): Wieger Wesselink\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\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/// \\file process_test.cpp\n/// \\brief Add your file description here.\n\n#include \"mcrl2/process/find.h\"\n#include \"mcrl2/process/parse.h\"\n#include \"mcrl2/process/process_specification.h\"\n#include <boost/test/minimal.hpp>\n#include <iostream>\n#include <set>\n#include <string>\n\nusing namespace mcrl2;\nusing namespace mcrl2::process;\n\nconst std::string SPEC1 =\n  \"act a;                  \\n\"\n  \"proc X = a;             \\n\"\n  \"init X;                 \\n\"\n  ;\n\nconst std::string SPEC2 =\n  \"act a;                  \\n\"\n  \"proc X(i: Nat) = a.X(i);\\n\"\n  \"init X(2);              \\n\"\n  ;\n\nconst std::string ABS_SPEC_LINEARIZED =\n  \"sort D = struct d1 | d2;                                                                                                     \\n\"\n  \"     Error = struct e;                                                                                                       \\n\"\n  \"                                                                                                                             \\n\"\n  \"act  r1,s4: D;                                                                                                               \\n\"\n  \"     s2,r2,c2,s3,r3,c3: D # Bool;                                                                                            \\n\"\n  \"     s3,r3,c3: Error;                                                                                                        \\n\"\n  \"     s5,r5,c5,s6,r6,c6: Bool;                                                                                                \\n\"\n  \"     s6,r6,c6: Error;                                                                                                        \\n\"\n  \"     i;                                                                                                                      \\n\"\n  \"                                                                                                                             \\n\"\n  \"proc P(s31_S: Pos, d_S: D, b_S: Bool, s32_K: Pos, d_K: D, b_K: Bool, s33_L: Pos, b_L: Bool, s34_R: Pos, d_R: D, b_R: Bool) = \\n\"\n  \"       sum e1_S: Bool.                                                                                                       \\n\"\n  \"         ((s31_S == 3 && s33_L == 3) && if(e1_S, !b_S, b_S) == b_L) ->                                                       \\n\"\n  \"         c6(if(e1_S, !b_S, b_S)) .                                                                                           \\n\"\n  \"         P(if(e1_S, 2, 1), if(e1_S, d_S, d2), if(e1_S, b_S, !b_S), s32_K, d_K, b_K, 1, false, s34_R, d_R, b_R)               \\n\"\n  \"     + (s31_S == 3 && s33_L == 4) ->                                                                                         \\n\"\n  \"         c6(e) .                                                                                                             \\n\"\n  \"         P(2, d_S, b_S, s32_K, d_K, b_K, 1, false, s34_R, d_R, b_R)                                                          \\n\"\n  \"     + (s31_S == 2 && s32_K == 1) ->                                                                                         \\n\"\n  \"         c2(d_S, b_S) .                                                                                                      \\n\"\n  \"         P(3, d_S, b_S, 2, d_S, b_S, s33_L, b_L, s34_R, d_R, b_R)                                                            \\n\"\n  \"     + sum e2_K: Bool.                                                                                                       \\n\"\n  \"         (s32_K == 2) ->                                                                                                     \\n\"\n  \"         i .                                                                                                                 \\n\"\n  \"         P(s31_S, d_S, b_S, if(e2_K, 4, 3), if(e2_K, d2, d_K), if(e2_K, false, b_K), s33_L, b_L, s34_R, d_R, b_R)            \\n\"\n  \"     + sum e4_R: Bool.                                                                                                       \\n\"\n  \"         (s33_L == 1 && if(e4_R, s34_R == 4, s34_R == 3)) ->                                                                 \\n\"\n  \"         c5(if(e4_R, !b_R, b_R)) .                                                                                           \\n\"\n  \"         P(s31_S, d_S, b_S, s32_K, d_K, b_K, 2, if(e4_R, !b_R, b_R), 1, d2, if(e4_R, b_R, !b_R))                             \\n\"\n  \"     + (s34_R == 2) ->                                                                                                       \\n\"\n  \"         s4(d_R) .                                                                                                           \\n\"\n  \"         P(s31_S, d_S, b_S, s32_K, d_K, b_K, s33_L, b_L, 3, d2, b_R)                                                         \\n\"\n  \"     + sum e3_L: Bool.                                                                                                       \\n\"\n  \"         (s33_L == 2) ->                                                                                                     \\n\"\n  \"         i .                                                                                                                 \\n\"\n  \"         P(s31_S, d_S, b_S, s32_K, d_K, b_K, if(e3_L, 4, 3), if(e3_L, false, b_L), s34_R, d_R, b_R)                          \\n\"\n  \"     + (s32_K == 4 && s34_R == 1) ->                                                                                         \\n\"\n  \"         c3(e) .                                                                                                             \\n\"\n  \"         P(s31_S, d_S, b_S, 1, d2, false, s33_L, b_L, 4, d2, b_R)                                                            \\n\"\n  \"     + sum e5_R: Bool.                                                                                                       \\n\"\n  \"         ((s32_K == 3 && s34_R == 1) && if(e5_R, b_R, !b_R) == b_K) ->                                                       \\n\"\n  \"         c3(d_K, if(e5_R, b_R, !b_R)) .                                                                                      \\n\"\n  \"         P(s31_S, d_S, b_S, 1, d2, false, s33_L, b_L, if(e5_R, 2, 4), if(e5_R, d_K, d2), b_R)                                \\n\"\n  \"     + sum d3_S: D.                                                                                                          \\n\"\n  \"         (s31_S == 1) ->                                                                                                     \\n\"\n  \"         r1(d3_S) .                                                                                                          \\n\"\n  \"         P(2, d3_S, b_S, s32_K, d_K, b_K, s33_L, b_L, s34_R, d_R, b_R)                                                       \\n\"\n  \"     + true ->                                                                                                               \\n\"\n  \"         delta;                                                                                                              \\n\"\n  \"                                                                                                                             \\n\"\n  \"init P(1, d2, true, 1, d2, false, 1, false, 1, d2, true);                                                                    \\n\"\n  ;\n\n// CASE?? specifications were borrowed from sumelm_test.\n\nstd::string CASE1 =\n  \"sort S = struct s1 | s2;\\n\"\n  \"map f : S -> Bool;\\n\"\n  \"act a : S # Bool;\\n\"\n  \"proc P = sum c : S, b : Bool . (b == f(c) && c == s2) -> a(c, b) . P;\\n\"\n  \"init P;\\n\"\n  ;\n\nstd::string CASE2 =\n  \"act a,b;\\n\"\n  \"proc P(s3_P: Pos) = sum y_P: Int. (s3_P == 1) -> a . P(2)\\n\"\n  \"                  + (s3_P == 2) -> b . P(1);\\n\"\n  \"init P(1);\\n\"\n  ;\n\nstd::string CASE3 =\n  \"act a;\\n\"\n  \"proc P = sum y:Int . (4 == y) -> a . P;\\n\"\n  \"init P;\\n\"\n  ;\n\nstd::string CASE4 =\n  \"act a;\\n\"\n  \"proc P = sum y:Int . (y == 4) -> a . P;\\n\"\n  \"init P;\\n\"\n  ;\n\nstd::string CASE5 =\n  \"act a,b:Int;\\n\"\n  \"proc P = sum y:Int . (y == 4) -> a(y)@y . b(y*2)@(y+1) . P;\\n\"\n  \"init P;\\n\"\n  ;\n\nstd::string CASE6 =\n  \"act a;\\n\"\n  \"proc P = sum y:Int . (y == y + 1) -> a . P;\\n\"\n  \"init P;\\n\"\n  ;\n\nstd::string CASE7 =\n  \"sort D = struct d1 | d2 | d3;\\n\"\n  \"map g : D -> D;\\n\"\n  \"act a;\\n\"\n  \"proc P(c:D) = sum d:D . sum e:D . sum f:D . (d == e && e == g(e) && e == f) -> a . P(d);\\n\"\n  \"init P(d1);\\n\"\n  ;\n\nstd::string CASE8 =\n  \"sort D = struct d1 | d2 | d3;\\n\"\n  \"act a;\\n\"\n  \"proc P(c:D) = sum d:D . sum e:D . sum f:D . (d == e && d == f) -> a . P(d);\\n\"\n  \"init P(d1);\\n\"\n  ;\n\nstd::string CASE9 =\n  \"proc P = sum y:Bool . y -> delta;\\n\"\n  \"init P;\\n\"\n  ;\n\nstd::string CASE10 =\n  \"act a:Nat;\\n\"\n  \"proc P(n0: Nat) = sum n: Nat. (n == n0 && n == 1) -> a(n0) . P(n);\\n\"\n  \"init P(0);\\n\"\n  ;\n\nvoid test_process(const std::string& text)\n{\n  process_specification spec = parse_process_specification(text);\n  std::set<data::sort_expression> sorts;\n  process::find_sort_expressions(spec, std::inserter(sorts, sorts.end()));\n  std::cerr << \"sorts: \" << data::pp(data::sort_expression_list(sorts.begin(), sorts.end())) << std::endl;\n}\n\nint test_main(int argc, char* argv[])\n{\n  test_process(CASE1);\n  test_process(CASE2);\n  test_process(CASE3);\n  test_process(CASE4);\n  test_process(CASE5);\n  test_process(CASE6);\n  test_process(CASE7);\n  test_process(CASE8);\n  test_process(CASE9);\n  test_process(CASE10);\n  test_process(SPEC1);\n  test_process(SPEC2);\n  test_process(ABS_SPEC_LINEARIZED);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "b865499d6ac87a86d290a74f7f9cadcd3e8a052b", "size": 9814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/process/test/sort_traverser_test.cpp", "max_stars_repo_name": "wiegerw/mcrl3", "max_stars_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-22T09:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T09:16:39.000Z", "max_issues_repo_path": "libraries/process/test/sort_traverser_test.cpp", "max_issues_repo_name": "wiegerw/mcrl3", "max_issues_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "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": "libraries/process/test/sort_traverser_test.cpp", "max_forks_repo_name": "wiegerw/mcrl3", "max_forks_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "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": 53.6284153005, "max_line_length": 131, "alphanum_fraction": 0.2783778276, "num_tokens": 2422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.15656081363432608}}
{"text": "//\n// Copyright (c) 2014 CNRS\n// Authors: Steve Tonneau (steve.tonneau@laas.fr)\n//\n// This file is part of hpp-rbprm.\n// hpp-rbprm is free software: you can redistribute it\n// and/or modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation, either version\n// 3 of the License, or (at your option) any later version.\n//\n// hpp-rbprm 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 GNU\n// General Lesser Public License for more details.  You should have\n// received a copy of the GNU Lesser General Public License along with\n// hpp-core  If not, see\n// <http://www.gnu.org/licenses/>.\n\n#ifndef HPP_IK_DEFINITIONS_HH\n#define HPP_IK_DEFINITIONS_HH\n\n\n#include <hpp/ik/config.hh>\n\n#include <hpp/pinocchio/frame.hh>\n#include <hpp/pinocchio/device.hh>\n#include <hpp/core/config-projector.hh>\n\n#include <Eigen/Core>\n\nnamespace hpp {\n\nnamespace ik {\n\ntypedef Eigen::Matrix <double, Eigen::Dynamic, 1> vector_t;\ntypedef Eigen::Vector3d vector3_t;\ntypedef Eigen::Quaterniond quat_t;\n\n\nenum HPP_IK_DLLAPI MaintainConstraintType\n{\n    MAINTAIN_3D = 0,\n    MAINTAIN_6D\n};\n\nstruct HPP_IK_DLLAPI IkHelper{\n\n    IkHelper(hpp::pinocchio::DevicePtr_t device, const double tolerance = 1e-5)\n    : device_(device)\n    , proj_(core::ConfigProjector::create(device, \"proj\", tolerance, 40 ))\n    {\n        device_->controlComputation(pinocchio::Computation_t(device_->computationFlag()\n                                        | pinocchio::JOINT_POSITION | pinocchio::JACOBIAN | pinocchio::COM));\n    }\n\n     IkHelper(){}\n    ~IkHelper(){}\n\n    hpp::pinocchio::DevicePtr_t device_;\n    core::ConfigProjectorPtr_t proj_;\n};\n\n\nstruct HPP_IK_DLLAPI FrameMarker{\n\n    FrameMarker(pinocchio::Frame& frame):\n        frame_(frame),\n        offset_(vector3_t::Zero()),\n        normal_(vector3_t::Zero())\n    {}\n\n    FrameMarker(pinocchio::Frame& frame, const vector3_t& offset, const vector3_t& normal):\n        frame_(frame),\n        offset_(offset),\n        normal_(normal)\n    {}\n\n    ~FrameMarker(){}\n\n\n    pinocchio::Frame frame_;\n    vector3_t offset_;\n    vector3_t normal_;\n};\n\n} // namespace hpp\n} // namespace ik\n#endif // HPP_IK_DEFINITIONS_HH\n", "meta": {"hexsha": "f8f2bc1c2e1886bfb7be7cf86bcdf18715de4db3", "size": 2313, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/hpp/ik/definitions.hh", "max_stars_repo_name": "stonneau/hpp-ik", "max_stars_repo_head_hexsha": "f6d65de00b7aa2c6e98ec995ea932de8c064b765", "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/hpp/ik/definitions.hh", "max_issues_repo_name": "stonneau/hpp-ik", "max_issues_repo_head_hexsha": "f6d65de00b7aa2c6e98ec995ea932de8c064b765", "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/hpp/ik/definitions.hh", "max_forks_repo_name": "stonneau/hpp-ik", "max_forks_repo_head_hexsha": "f6d65de00b7aa2c6e98ec995ea932de8c064b765", "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.9887640449, "max_line_length": 109, "alphanum_fraction": 0.6969303934, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.15656081363432603}}
{"text": "#include <iostream>\n#include <thread>\n#include <tuple>\n#include <random>\n#include <chrono>\n#include <functional>\n\n#include \"Part.h\"\n#include \"Angle.h\"\n#include \"Quaternion.h\"\n#include \"World.h\"\n#include \"BoundingBox.h\"\n#include \"Vector.h\"\n#include \"WeightedVector.h\"\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/range/algorithm_ext/erase.hpp>\n\ntemplate <class Eng>\nConnection *selectRandomConnection(Part& part, Eng &engine)\n{\n\tif (part.connections.reachable() == 0)\n\t\treturn nullptr;\n\n\tstd::uniform_int_distribution<ptrdiff_t> dist(0, part.connections.totalWeight() - 1);\n\n\treturn &part.connections.getWeighted(dist(engine));\n}\n\nvoid movePart(Part& part, Connection* newc, const Connection* prevc)\n{\n\tQuaternion targetQuat(prevc->angles());\n\n\ttargetQuat = targetQuat * Quaternion{ 0, 0, 1, 0 };\n\n\tAngle newAngle = newc->angles();\n\n\tauto rotmat = newAngle.calcRotation(targetQuat);\n\n\tpart.rotate(rotmat);\n\tVector mov = Vector::diff(newc->origin(), prevc->origin());\n\tpart.move(mov);\n\n\tauto iter = boost::find_if(part.connections, [newc](auto &con) {return &con == newc; });\n\n\tpart.connections.setWeight(iter, 0);\n}\n\nvoid scaleToFit(Part& scaleable, Connection* scalec, const Connection* firstc, const Connection* secondc)\n{\n\tdouble dist = (firstc->originKV() - secondc->originKV()).length();\n\n\tscaleable.scaleTo(dist);\n\n\tmovePart(scaleable, scalec, firstc);\n}\n\nint main(int argc, char* argv[])\n{\n\t//Part p(R\"(f:\\test\\collisions\\collision 1.vmf)\");\n\n\t//std::vector<Solid> lhs, rhs;\n\n\t//const auto &worldspawn = *boost::find_if(p.entities, &Entity::entworldcmp);\n\n\t//for (auto &solid : worldspawn.solids)\n\t//{\n\t//\tauto &side = solid.sides[0];\n\n\t//\tif (side[\"material\"] == \"BRICK/BRICKFLOOR001A\")\n\t//\t\tlhs.push_back(solid);\n\t//\telse if (side[\"material\"] == \"BRICK/BRICKWALL001A\")\n\t//\t\trhs.push_back(solid);\n\t//}\n\n\t//std::cout << lhs.size() << \", \" << rhs.size() << \"\\n\";\n\n\t//for (auto &lhsSolid : lhs)\n\t//{\n\t//\tfor (auto &rhsSolid : rhs)\n\t//\t{\n\t//\t\tif (Solid::testCollision(lhsSolid, rhsSolid))\n\t//\t\t{\n\t//\t\t\tstd::cout << \"collision\\n\";\n\t//\t\t}\n\t//\t}\n\t//}\n\n\t//std::cin.get();\n\n\t//return 0;\n\n\tWorld randomWorld;\n\n\trandomWorld.addPart(Part(R\"(f:\\test\\rndmap\\room5.vmf)\"));\n\trandomWorld.addPart(Part(R\"(f:\\test\\testmap.vmf)\"));\n\trandomWorld.addPart(Part(R\"(f:\\test\\rndmap\\room6.vmf)\"));\n\trandomWorld.addPart(Part(R\"(f:\\test\\rndmap\\room1.vmf)\"));\n\trandomWorld.addPart(Part(R\"(f:\\test\\rndmap\\room2.vmf)\"));\n\trandomWorld.addPart(Part(R\"(f:\\test\\rndmap\\roomT.vmf)\"));\n\trandomWorld.addPart(Part(R\"(f:\\test\\rndmap\\roomX.vmf)\"));\n\n\trandomWorld.buildInitial(30);\n\n\trandomWorld.serialize().toFile(R\"(f:\\test\\randomworld.vmf)\");\n\n\tstd::cin.get();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9b48d0ee5df508490c5261720cfe1e96f8f5e633", "size": 2723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rndlevelsource CLI/main.cpp", "max_stars_repo_name": "Telefragged/rndlevelsource", "max_stars_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "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": "rndlevelsource CLI/main.cpp", "max_issues_repo_name": "Telefragged/rndlevelsource", "max_issues_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rndlevelsource CLI/main.cpp", "max_forks_repo_name": "Telefragged/rndlevelsource", "max_forks_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_forks_repo_licenses": ["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.0973451327, "max_line_length": 105, "alphanum_fraction": 0.6797649651, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2942149783515163, "lm_q1q2_score": 0.15628975428728223}}
{"text": "#ifndef OSRM_ENGINE_ROUTING_BASE_HPP\n#define OSRM_ENGINE_ROUTING_BASE_HPP\n\n#include \"guidance/turn_bearing.hpp\"\n#include \"guidance/turn_instruction.hpp\"\n\n#include \"engine/algorithm.hpp\"\n#include \"engine/datafacade.hpp\"\n#include \"engine/internal_route_result.hpp\"\n#include \"engine/phantom_node.hpp\"\n#include \"engine/search_engine_data.hpp\"\n\n#include \"util/coordinate_calculation.hpp\"\n#include \"util/typedefs.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <cstddef>\n#include <cstdint>\n\n#include <algorithm>\n#include <functional>\n#include <iterator>\n#include <memory>\n#include <numeric>\n#include <stack>\n#include <utility>\n#include <vector>\n\nnamespace osrm\n{\nnamespace engine\n{\n\nnamespace routing_algorithms\n{\n\nnamespace details\n{\ntemplate <typename Heap>\nvoid insertSourceInForwardHeap(Heap &forward_heap, const PhantomNode &source)\n{\n    if (source.IsValidForwardSource())\n    {\n        forward_heap.Insert(source.forward_segment_id.id,\n                            -source.GetForwardWeightPlusOffset(),\n                            source.forward_segment_id.id);\n    }\n\n    if (source.IsValidReverseSource())\n    {\n        forward_heap.Insert(source.reverse_segment_id.id,\n                            -source.GetReverseWeightPlusOffset(),\n                            source.reverse_segment_id.id);\n    }\n}\n\ntemplate <typename Heap>\nvoid insertTargetInReverseHeap(Heap &reverse_heap, const PhantomNode &target)\n{\n    if (target.IsValidForwardTarget())\n    {\n        reverse_heap.Insert(target.forward_segment_id.id,\n                            target.GetForwardWeightPlusOffset(),\n                            target.forward_segment_id.id);\n    }\n\n    if (target.IsValidReverseTarget())\n    {\n        reverse_heap.Insert(target.reverse_segment_id.id,\n                            target.GetReverseWeightPlusOffset(),\n                            target.reverse_segment_id.id);\n    }\n}\n} // namespace details\nstatic constexpr bool FORWARD_DIRECTION = true;\nstatic constexpr bool REVERSE_DIRECTION = false;\n\n// Identify nodes in the forward(reverse) search direction that will require loop forcing\n// e.g. if source and destination nodes are on the same segment.\nstd::vector<NodeID> getForwardLoopNodes(const PhantomEndpointCandidates &candidates);\nstd::vector<NodeID> getForwardLoopNodes(const PhantomCandidatesToTarget &candidates);\nstd::vector<NodeID> getBackwardLoopNodes(const PhantomEndpointCandidates &candidates);\nstd::vector<NodeID> getBackwardLoopNodes(const PhantomCandidatesToTarget &candidates);\n\n// Find the specific phantom node endpoints for a given path from a list of candidates.\nPhantomEndpoints endpointsFromCandidates(const PhantomEndpointCandidates &candidates,\n                                         const std::vector<NodeID> &path);\n\ntemplate <typename HeapNodeT>\ninline bool force_loop(const std::vector<NodeID> &force_nodes, const HeapNodeT &heap_node)\n{\n    // if loops are forced, they are so at the source\n    return !force_nodes.empty() &&\n           std::find(force_nodes.begin(), force_nodes.end(), heap_node.node) != force_nodes.end() &&\n           heap_node.data.parent == heap_node.node;\n}\n\ntemplate <typename Heap>\nvoid insertNodesInHeaps(Heap &forward_heap, Heap &reverse_heap, const PhantomEndpoints &endpoints)\n{\n    details::insertSourceInForwardHeap(forward_heap, endpoints.source_phantom);\n    details::insertTargetInReverseHeap(reverse_heap, endpoints.target_phantom);\n}\n\ntemplate <typename Heap>\nvoid insertNodesInHeaps(Heap &forward_heap,\n                        Heap &reverse_heap,\n                        const PhantomEndpointCandidates &endpoint_candidates)\n{\n    for (const auto &source : endpoint_candidates.source_phantoms)\n    {\n        details::insertSourceInForwardHeap(forward_heap, source);\n    }\n\n    for (const auto &target : endpoint_candidates.target_phantoms)\n    {\n        details::insertTargetInReverseHeap(reverse_heap, target);\n    }\n}\n\ntemplate <typename ManyToManyQueryHeap>\nvoid insertSourceInHeap(ManyToManyQueryHeap &heap, const PhantomNodeCandidates &source_candidates)\n{\n    for (const auto &phantom_node : source_candidates)\n    {\n        if (phantom_node.IsValidForwardSource())\n        {\n            heap.Insert(phantom_node.forward_segment_id.id,\n                        -phantom_node.GetForwardWeightPlusOffset(),\n                        {phantom_node.forward_segment_id.id,\n                         -phantom_node.GetForwardDuration(),\n                         -phantom_node.GetForwardDistance()});\n        }\n        if (phantom_node.IsValidReverseSource())\n        {\n            heap.Insert(phantom_node.reverse_segment_id.id,\n                        -phantom_node.GetReverseWeightPlusOffset(),\n                        {phantom_node.reverse_segment_id.id,\n                         -phantom_node.GetReverseDuration(),\n                         -phantom_node.GetReverseDistance()});\n        }\n    }\n}\n\ntemplate <typename ManyToManyQueryHeap>\nvoid insertTargetInHeap(ManyToManyQueryHeap &heap, const PhantomNodeCandidates &target_candidates)\n{\n    for (const auto &phantom_node : target_candidates)\n    {\n        if (phantom_node.IsValidForwardTarget())\n        {\n            heap.Insert(phantom_node.forward_segment_id.id,\n                        phantom_node.GetForwardWeightPlusOffset(),\n                        {phantom_node.forward_segment_id.id,\n                         phantom_node.GetForwardDuration(),\n                         phantom_node.GetForwardDistance()});\n        }\n        if (phantom_node.IsValidReverseTarget())\n        {\n            heap.Insert(phantom_node.reverse_segment_id.id,\n                        phantom_node.GetReverseWeightPlusOffset(),\n                        {phantom_node.reverse_segment_id.id,\n                         phantom_node.GetReverseDuration(),\n                         phantom_node.GetReverseDistance()});\n        }\n    }\n}\n\ntemplate <typename FacadeT>\nvoid annotatePath(const FacadeT &facade,\n                  const PhantomEndpoints &endpoints,\n                  const std::vector<NodeID> &unpacked_nodes,\n                  const std::vector<EdgeID> &unpacked_edges,\n                  std::vector<PathData> &unpacked_path)\n{\n    BOOST_ASSERT(!unpacked_nodes.empty());\n    BOOST_ASSERT(unpacked_nodes.size() == unpacked_edges.size() + 1);\n\n    const auto source_node_id = unpacked_nodes.front();\n    const auto target_node_id = unpacked_nodes.back();\n    const bool start_traversed_in_reverse =\n        endpoints.source_phantom.forward_segment_id.id != source_node_id;\n    const bool target_traversed_in_reverse =\n        endpoints.target_phantom.forward_segment_id.id != target_node_id;\n\n    BOOST_ASSERT(endpoints.source_phantom.forward_segment_id.id == source_node_id ||\n                 endpoints.source_phantom.reverse_segment_id.id == source_node_id);\n    BOOST_ASSERT(endpoints.target_phantom.forward_segment_id.id == target_node_id ||\n                 endpoints.target_phantom.reverse_segment_id.id == target_node_id);\n\n    // datastructures to hold extracted data from geometry\n    std::vector<NodeID> id_vector;\n    std::vector<SegmentWeight> weight_vector;\n    std::vector<SegmentDuration> duration_vector;\n    std::vector<DatasourceID> datasource_vector;\n\n    const auto get_segment_geometry = [&](const auto geometry_index) {\n        const auto copy = [](auto &vector, const auto range) {\n            vector.resize(range.size());\n            std::copy(range.begin(), range.end(), vector.begin());\n        };\n\n        if (geometry_index.forward)\n        {\n            copy(id_vector, facade.GetUncompressedForwardGeometry(geometry_index.id));\n            copy(weight_vector, facade.GetUncompressedForwardWeights(geometry_index.id));\n            copy(duration_vector, facade.GetUncompressedForwardDurations(geometry_index.id));\n            copy(datasource_vector, facade.GetUncompressedForwardDatasources(geometry_index.id));\n        }\n        else\n        {\n            copy(id_vector, facade.GetUncompressedReverseGeometry(geometry_index.id));\n            copy(weight_vector, facade.GetUncompressedReverseWeights(geometry_index.id));\n            copy(duration_vector, facade.GetUncompressedReverseDurations(geometry_index.id));\n            copy(datasource_vector, facade.GetUncompressedReverseDatasources(geometry_index.id));\n        }\n    };\n\n    auto node_from = unpacked_nodes.begin(), node_last = std::prev(unpacked_nodes.end());\n    for (auto edge = unpacked_edges.begin(); node_from != node_last; ++node_from, ++edge)\n    {\n        const auto &edge_data = facade.GetEdgeData(*edge);\n        const auto turn_id = edge_data.turn_id; // edge-based graph edge index\n        const auto node_id = *node_from;        // edge-based graph node index\n\n        const auto geometry_index = facade.GetGeometryIndex(node_id);\n        get_segment_geometry(geometry_index);\n\n        BOOST_ASSERT(!id_vector.empty());\n        BOOST_ASSERT(!datasource_vector.empty());\n        BOOST_ASSERT(weight_vector.size() + 1 == id_vector.size());\n        BOOST_ASSERT(duration_vector.size() + 1 == id_vector.size());\n\n        const bool is_first_segment = unpacked_path.empty();\n\n        std::size_t start_index = 0;\n        if (is_first_segment)\n        {\n            unsigned short segment_position = endpoints.source_phantom.fwd_segment_position;\n            if (start_traversed_in_reverse)\n            {\n                segment_position =\n                    weight_vector.size() - endpoints.source_phantom.fwd_segment_position - 1;\n            }\n            BOOST_ASSERT(segment_position >= 0);\n            start_index = static_cast<std::size_t>(segment_position);\n        }\n        const std::size_t end_index = weight_vector.size();\n\n        BOOST_ASSERT(start_index < end_index);\n        for (std::size_t segment_idx = start_index; segment_idx < end_index; ++segment_idx)\n        {\n            unpacked_path.push_back(\n                PathData{node_id,\n                         id_vector[segment_idx + 1],\n                         static_cast<EdgeWeight>(weight_vector[segment_idx]),\n                         0,\n                         static_cast<EdgeDuration>(duration_vector[segment_idx]),\n                         0,\n                         datasource_vector[segment_idx],\n                         boost::none});\n        }\n        BOOST_ASSERT(unpacked_path.size() > 0);\n\n        const auto turn_duration = facade.GetDurationPenaltyForEdgeID(turn_id);\n        const auto turn_weight = facade.GetWeightPenaltyForEdgeID(turn_id);\n\n        unpacked_path.back().duration_until_turn += turn_duration;\n        unpacked_path.back().duration_of_turn = turn_duration;\n        unpacked_path.back().weight_until_turn += turn_weight;\n        unpacked_path.back().weight_of_turn = turn_weight;\n        unpacked_path.back().turn_edge = turn_id;\n    }\n\n    std::size_t start_index = 0, end_index = 0;\n    const auto source_geometry_id = facade.GetGeometryIndex(source_node_id).id;\n    const auto target_geometry = facade.GetGeometryIndex(target_node_id);\n    const auto is_local_path = source_geometry_id == target_geometry.id && unpacked_path.empty();\n\n    get_segment_geometry(target_geometry);\n\n    if (target_traversed_in_reverse)\n    {\n        if (is_local_path)\n        {\n            start_index = weight_vector.size() - endpoints.source_phantom.fwd_segment_position - 1;\n        }\n        end_index = weight_vector.size() - endpoints.target_phantom.fwd_segment_position - 1;\n    }\n    else\n    {\n        if (is_local_path)\n        {\n            start_index = endpoints.source_phantom.fwd_segment_position;\n        }\n        end_index = endpoints.target_phantom.fwd_segment_position;\n    }\n\n    // Given the following compressed geometry:\n    // U---v---w---x---y---Z\n    //    s           t\n    // s: fwd_segment 0\n    // t: fwd_segment 3\n    // -> (U, v), (v, w), (w, x)\n    // note that (x, t) is _not_ included but needs to be added later.\n    for (std::size_t segment_idx = start_index; segment_idx != end_index;\n         (start_index < end_index ? ++segment_idx : --segment_idx))\n    {\n        BOOST_ASSERT(segment_idx < static_cast<std::size_t>(id_vector.size() - 1));\n        unpacked_path.push_back(\n            PathData{target_node_id,\n                     id_vector[start_index < end_index ? segment_idx + 1 : segment_idx - 1],\n                     static_cast<EdgeWeight>(weight_vector[segment_idx]),\n                     0,\n                     static_cast<EdgeDuration>(duration_vector[segment_idx]),\n                     0,\n                     datasource_vector[segment_idx],\n                     boost::none});\n    }\n\n    if (!unpacked_path.empty())\n    {\n        const auto source_weight = start_traversed_in_reverse\n                                       ? endpoints.source_phantom.reverse_weight\n                                       : endpoints.source_phantom.forward_weight;\n        const auto source_duration = start_traversed_in_reverse\n                                         ? endpoints.source_phantom.reverse_duration\n                                         : endpoints.source_phantom.forward_duration;\n        // The above code will create segments for (v, w), (w,x), (x, y) and (y, Z).\n        // However the first segment duration needs to be adjusted to the fact that the source\n        // phantom is in the middle of the segment. We do this by subtracting v--s from the\n        // duration.\n\n        // Since it's possible duration_until_turn can be less than source_weight here if\n        // a negative enough turn penalty is used to modify this edge weight during\n        // osrm-contract, we clamp to 0 here so as not to return a negative duration\n        // for this segment.\n\n        // TODO this creates a scenario where it's possible the duration from a phantom\n        // node to the first turn would be the same as from end to end of a segment,\n        // which is obviously incorrect and not ideal...\n        unpacked_path.front().weight_until_turn =\n            std::max(unpacked_path.front().weight_until_turn - source_weight, 0);\n        unpacked_path.front().duration_until_turn =\n            std::max(unpacked_path.front().duration_until_turn - source_duration, 0);\n    }\n}\n\ntemplate <typename Algorithm>\ndouble getPathDistance(const DataFacade<Algorithm> &facade,\n                       const std::vector<PathData> &unpacked_path,\n                       const PhantomNode &source_phantom,\n                       const PhantomNode &target_phantom)\n{\n    using util::coordinate_calculation::detail::DEGREE_TO_RAD;\n    using util::coordinate_calculation::detail::EARTH_RADIUS;\n\n    double distance = 0;\n    double prev_lat =\n        static_cast<double>(util::toFloating(source_phantom.location.lat)) * DEGREE_TO_RAD;\n    double prev_lon =\n        static_cast<double>(util::toFloating(source_phantom.location.lon)) * DEGREE_TO_RAD;\n    double prev_cos = std::cos(prev_lat);\n    for (const auto &p : unpacked_path)\n    {\n        const auto current_coordinate = facade.GetCoordinateOfNode(p.turn_via_node);\n\n        const double current_lat =\n            static_cast<double>(util::toFloating(current_coordinate.lat)) * DEGREE_TO_RAD;\n        const double current_lon =\n            static_cast<double>(util::toFloating(current_coordinate.lon)) * DEGREE_TO_RAD;\n        const double current_cos = std::cos(current_lat);\n\n        const double sin_dlon = std::sin((prev_lon - current_lon) / 2.0);\n        const double sin_dlat = std::sin((prev_lat - current_lat) / 2.0);\n\n        const double aharv = sin_dlat * sin_dlat + prev_cos * current_cos * sin_dlon * sin_dlon;\n        const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv));\n        distance += EARTH_RADIUS * charv;\n\n        prev_lat = current_lat;\n        prev_lon = current_lon;\n        prev_cos = current_cos;\n    }\n\n    const double current_lat =\n        static_cast<double>(util::toFloating(target_phantom.location.lat)) * DEGREE_TO_RAD;\n    const double current_lon =\n        static_cast<double>(util::toFloating(target_phantom.location.lon)) * DEGREE_TO_RAD;\n    const double current_cos = std::cos(current_lat);\n\n    const double sin_dlon = std::sin((prev_lon - current_lon) / 2.0);\n    const double sin_dlat = std::sin((prev_lat - current_lat) / 2.0);\n\n    const double aharv = sin_dlat * sin_dlat + prev_cos * current_cos * sin_dlon * sin_dlon;\n    const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv));\n    distance += EARTH_RADIUS * charv;\n\n    return distance;\n}\n\ntemplate <typename AlgorithmT>\nInternalRouteResult extractRoute(const DataFacade<AlgorithmT> &facade,\n                                 const EdgeWeight weight,\n                                 const PhantomEndpointCandidates &endpoint_candidates,\n                                 const std::vector<NodeID> &unpacked_nodes,\n                                 const std::vector<EdgeID> &unpacked_edges)\n{\n    InternalRouteResult raw_route_data;\n\n    // No path found for both target nodes?\n    if (INVALID_EDGE_WEIGHT == weight)\n    {\n        return raw_route_data;\n    }\n\n    auto phantom_endpoints = endpointsFromCandidates(endpoint_candidates, unpacked_nodes);\n    raw_route_data.leg_endpoints = {phantom_endpoints};\n\n    raw_route_data.shortest_path_weight = weight;\n    raw_route_data.unpacked_path_segments.resize(1);\n    raw_route_data.source_traversed_in_reverse.push_back(\n        (unpacked_nodes.front() != phantom_endpoints.source_phantom.forward_segment_id.id));\n    raw_route_data.target_traversed_in_reverse.push_back(\n        (unpacked_nodes.back() != phantom_endpoints.target_phantom.forward_segment_id.id));\n\n    annotatePath(facade,\n                 phantom_endpoints,\n                 unpacked_nodes,\n                 unpacked_edges,\n                 raw_route_data.unpacked_path_segments.front());\n\n    return raw_route_data;\n}\n\ntemplate <typename FacadeT> EdgeDistance computeEdgeDistance(const FacadeT &facade, NodeID node_id)\n{\n    const auto geometry_index = facade.GetGeometryIndex(node_id);\n\n    EdgeDistance total_distance = 0.0;\n\n    auto geometry_range = facade.GetUncompressedForwardGeometry(geometry_index.id);\n    for (auto current = geometry_range.begin(); current < geometry_range.end() - 1; ++current)\n    {\n        total_distance += util::coordinate_calculation::fccApproximateDistance(\n            facade.GetCoordinateOfNode(*current), facade.GetCoordinateOfNode(*std::next(current)));\n    }\n\n    return total_distance;\n}\n\n} // namespace routing_algorithms\n} // namespace engine\n} // namespace osrm\n\n#endif // OSRM_ENGINE_ROUTING_BASE_HPP\n", "meta": {"hexsha": "adcdd78305e80965916e499f3d921f91e403d9bc", "size": 18507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/engine/routing_algorithms/routing_base.hpp", "max_stars_repo_name": "fofanov/osrm-backend", "max_stars_repo_head_hexsha": "4a8b4052b20c40e6c8ae221185b9b5dd13b52577", "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/engine/routing_algorithms/routing_base.hpp", "max_issues_repo_name": "fofanov/osrm-backend", "max_issues_repo_head_hexsha": "4a8b4052b20c40e6c8ae221185b9b5dd13b52577", "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/engine/routing_algorithms/routing_base.hpp", "max_forks_repo_name": "fofanov/osrm-backend", "max_forks_repo_head_hexsha": "4a8b4052b20c40e6c8ae221185b9b5dd13b52577", "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.4082969432, "max_line_length": 100, "alphanum_fraction": 0.6603447344, "num_tokens": 3817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.15624374399882804}}
{"text": "#ifndef STREAM_LINE_HPP\n#define STREAM_LINE_HPP\n#include <ctime>\n#include <random>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/for_each.hpp>\n#include <deque>\n#include <vector>\n#include \"image/image.hpp\"\n#include \"interpolation_process.hpp\"\n#include \"basic_process.hpp\"\n#include \"roi.hpp\"\n#include \"fib_data.hpp\"\n\ntypedef boost::mpl::vector<\n            EstimateNextDirection,\n            SmoothDir,\n            MoveTrack\n> streamline_method_process;\n\ntypedef boost::mpl::vector<\n            LocateVoxel\n> voxel_tracking;\n\n\ntypedef boost::mpl::vector<\n            EstimateNextDirectionRungeKutta4,\n            MoveTrack\n> streamline_runge_kutta_4_method_process;\n\n\n\nstruct TrackingParam\n{\n    float threshold,otsu_threshold;\n    float cull_cos_angle;\n    float step_size;\n    float smooth_fraction;\n    float min_length;\n    float max_length;\n\n};\n\n\nclass TrackingMethod{\nprivate:\n    std::auto_ptr<basic_interpolation> interpolation;\npublic:// Parameters\n    image::vector<3,float> position;\n    image::vector<3,float> dir;\n    image::vector<3,float> next_dir;\n    bool terminated;\n    bool forward;\npublic:\n    const tracking_data& trk;\n    const TrackingParam& param;\n    float current_fa_threshold;\n    float current_tracking_angle;\n    float current_tracking_smoothing;\n    float current_step_size_in_voxel[3];\n    int current_min_steps3;\n    int current_max_steps3;\n    void scaling_in_voxel(image::vector<3,float>& dir) const\n    {\n        dir[0] *= current_step_size_in_voxel[0];\n        dir[1] *= current_step_size_in_voxel[1];\n        dir[2] *= current_step_size_in_voxel[2];\n    }\nprivate:\n    const RoiMgr& roi_mgr;\n\tstd::vector<float> track_buffer;\n\tmutable std::vector<float> reverse_buffer;\n    unsigned int buffer_front_pos;\n    unsigned int buffer_back_pos;\n\nprivate:\n    unsigned int init_fib_index;\npublic:\n    unsigned int get_buffer_size(void) const\n\t{\n\t\treturn buffer_back_pos-buffer_front_pos;\n\t}\n    unsigned int get_point_count(void) const\n\t{\n\t\treturn (buffer_back_pos-buffer_front_pos)/3;\n\t}\n    bool get_dir(const image::vector<3,float>& position,\n                      const image::vector<3,float>& ref_dir,\n                      image::vector<3,float>& result_dir)\n    {\n        return interpolation->evaluate(trk,position,ref_dir,result_dir,current_fa_threshold,current_tracking_angle);\n    }\npublic:\n    TrackingMethod(const tracking_data& trk_,basic_interpolation* interpolation_,\n                   const RoiMgr& roi_mgr_,const TrackingParam& param_):\n        trk(trk_),interpolation(interpolation_),roi_mgr(roi_mgr_),param(param_),init_fib_index(0)\n\t{\n\n\n\t}\npublic:\n\ttemplate<class Process>\n    void operator()(Process)\n    {\n        Process()(*this);\n    }\n\ttemplate<class ProcessList>\n    void tracking(ProcessList)\n    {\n        boost::mpl::for_each<ProcessList>(boost::ref(*this));\n    }\npublic:\n\n\n\tstd::vector<float>& get_track_buffer(void){return track_buffer;}\n\tstd::vector<float>& get_reverse_buffer(void){return reverse_buffer;}\n\n\ttemplate<class ProcessList>\n    bool start_tracking(bool smoothing)\n    {\n        image::vector<3,float> seed_pos(position);\n        image::vector<3,float> begin_dir(dir);\n        // floatd for full backward or full forward\n        track_buffer.resize(current_max_steps3 << 1);\n        reverse_buffer.resize(current_max_steps3 << 1);\n        buffer_front_pos = current_max_steps3;\n        buffer_back_pos = current_max_steps3;\n        image::vector<3,float> end_point1;\n        terminated = false;\n\t\tdo\n\t\t{\n            if(get_buffer_size() > current_max_steps3 || buffer_back_pos + 3 >= track_buffer.size())\n\t\t\t\treturn false;\n            if(roi_mgr.is_excluded_point(position))\n\t\t\t\treturn false;\n            track_buffer[buffer_back_pos] = position[0];\n            track_buffer[buffer_back_pos+1] = position[1];\n            track_buffer[buffer_back_pos+2] = position[2];\n            buffer_back_pos += 3;\n            if(roi_mgr.is_terminate_point(position))\n                break;\n            tracking(ProcessList());\n\t\t\t// make sure that the length won't overflow\n\t\t\t\n\t\t}\n        while(!terminated);\n\t\t\n        end_point1 = position;\n        terminated = false;\n        position = seed_pos;\n        dir = -begin_dir;\n        forward = false;\n\t\tdo\n\t\t{\n            tracking(ProcessList());\n\t\t\t// make sure that the length won't overflow\n            if(get_buffer_size() > current_max_steps3 || buffer_front_pos < 3)\n\t\t\t\treturn false;\t\t\t\n            if(terminated)\n\t\t\t\tbreak;\n\t\t\tbuffer_front_pos -= 3;\n            if(roi_mgr.is_excluded_point(position))\n\t\t\t\treturn false;\n            track_buffer[buffer_front_pos] = position[0];\n            track_buffer[buffer_front_pos+1] = position[1];\n            track_buffer[buffer_front_pos+2] = position[2];\n        }\n        while(!roi_mgr.is_terminate_point(position));\n\n        if(smoothing)\n        {\n            std::vector<float> smoothed(track_buffer.size());\n            float w[5] = {1.0,2.0,4.0,2.0,1.0};\n            int dis[5] = {-6, -3, 0, 3, 6};\n            for(int index = buffer_front_pos;index < buffer_back_pos;++index)\n            {\n                float sum_w = 0.0;\n                float sum = 0.0;\n                for(char i = 0;i < 5;++i)\n                {\n                    int cur_index = index + dis[i];\n                    if(cur_index < buffer_front_pos || cur_index >= buffer_back_pos)\n                        continue;\n                    sum += w[i]*track_buffer[cur_index];\n                    sum_w += w[i];\n                }\n                if(sum_w != 0.0)\n                    smoothed[index] = sum/sum_w;\n            }\n            smoothed.swap(track_buffer);\n        }\n\n        return get_buffer_size() > current_min_steps3 &&\n               roi_mgr.have_include(get_result(),get_buffer_size()) &&\n               roi_mgr.fulfill_end_point(position,end_point1);\n\n\n\t}\n        bool init(unsigned char initial_direction,\n                  const image::vector<3,float>& position_,\n                  std::mt19937& seed)\n        {\n            std::uniform_real_distribution<float> gen(0,1);\n            position = position_;\n            terminated = false;\n            forward = true;\n            image::pixel_index<3> pindex(std::round(position[0]),\n                                    std::round(position[1]),\n                                    std::round(position[2]),trk.dim);\n            if (!trk.dim.is_valid(pindex))\n                return false;\n\n            switch (initial_direction)\n            {\n            case 0:// main direction\n                {\n                    if(trk.fa[0][pindex.index()] < current_fa_threshold)\n                        return false;\n                    dir = trk.get_dir(pindex.index(),0);\n                }\n                return true;\n            case 1:// random direction\n                for (unsigned int index = 0;index < 10;++index)\n                {\n                    float txy = gen(seed);\n                    float tz = gen(seed)/2.0;\n                    float x = std::sin(txy)*std::sin(tz);\n                    float y = std::cos(txy)*std::sin(tz);\n                    float z = std::cos(tz);\n                    if (get_dir(position,image::vector<3,float>(x,y,z),dir))\n                        return true;\n                }\n                return false;\n            case 2:// all direction\n                {\n                    if (init_fib_index >= trk.fib_num ||\n                        trk.fa[init_fib_index][pindex.index()] < current_fa_threshold)\n                    {\n                        init_fib_index = 0;\n                        return false;\n                    }\n                    else\n                        dir = trk.get_dir(pindex.index(),init_fib_index);\n                    ++init_fib_index;\n                }\n                return true;\n            }\n            return false;\n        }\n\n        const float* tracking(unsigned char tracking_method,unsigned int& point_count)\n        {\n            point_count = 0;\n            switch (tracking_method)\n            {\n            case 0:\n                if (!start_tracking<streamline_method_process>(false))\n                    return 0;\n                break;\n            case 1:\n                if (!start_tracking<streamline_runge_kutta_4_method_process>(false))\n                    return 0;\n                break;\n            case 2:\n                position[0] = std::round(position[0]);\n                position[1] = std::round(position[1]);\n                position[2] = std::round(position[2]);\n                if (!start_tracking<voxel_tracking>(true))\n                    return 0;\n                break;\n            default:\n                return 0;\n            }\n            point_count = get_point_count();\n            return get_result();\n        }\n\n\tconst float* get_result(void) const\n\t{\n                image::vector<3,float> head(&*(track_buffer.begin() + buffer_front_pos));\n                image::vector<3,float> tail(&*(track_buffer.begin() + buffer_back_pos-3));\n\t\ttail -= head;\n                image::vector<3,float> abs_dis(std::abs(tail[0]),std::abs(tail[1]),std::abs(tail[2]));\n\t\t\n\t\tif((abs_dis[0] > abs_dis[1] && abs_dis[0] > abs_dis[2] && tail[0] < 0) ||\n\t\t   (abs_dis[1] > abs_dis[0] && abs_dis[1] > abs_dis[2] && tail[1] < 0) ||\n\t\t   (abs_dis[2] > abs_dis[1] && abs_dis[2] > abs_dis[0] && tail[2] < 0))\n\t\t{\n\t\t\tstd::vector<float>::const_iterator src = track_buffer.begin() + buffer_back_pos-3;\n\t\t\tstd::vector<float>::iterator iter = reverse_buffer.begin();\n\t\t\tstd::vector<float>::iterator end = reverse_buffer.begin()+buffer_back_pos-buffer_front_pos;\n\t\t\tfor(;iter < end;iter += 3,src -= 3)\n\t\t\t\tstd::copy(src,src+3,iter);\n\t\t\treturn &*reverse_buffer.begin();\n\t\t}\n\n\t\treturn &*(track_buffer.begin() + buffer_front_pos);\n\t}\n};\n\n\n\n\n\n\n#endif//STREAM_LINE_HPP\n", "meta": {"hexsha": "f9e189d77dab6645d9e529e2cfb2862c3d48cf9e", "size": 9764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/tracking/tracking_method.hpp", "max_stars_repo_name": "cbutakoff/DSI-Studio", "max_stars_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "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/tracking/tracking_method.hpp", "max_issues_repo_name": "cbutakoff/DSI-Studio", "max_issues_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "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/tracking/tracking_method.hpp", "max_forks_repo_name": "cbutakoff/DSI-Studio", "max_forks_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "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.8045602606, "max_line_length": 116, "alphanum_fraction": 0.5652396559, "num_tokens": 2228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15608005076736617}}
{"text": "#include <gtest/gtest.h>\n\n#include \"converter/fixml2fix_converter.hxx\"\n#include \"converter/xml_element_helper.hxx\"\n#include \"converter/fix_helper.hxx\"\n#include \"util/fix_env.hxx\"\n#include \"tools/test_util.hxx\"\n\n#include <boost/log/trivial.hpp>\n\n#include <quickfix/fix50sp2/AdjustedPositionReport.h>\n\n#include <list>\n#include <set>\n#include <string>\n#include <utility>\n\nusing namespace std;\nusing namespace fix2xml;\n\nTEST ( AdjustedPositionReport, set_fields)\n{\n\n  fixml2fix_converter converter {\"../spec/fix/FIX50SP2.xml\", \"../spec/xsd/fixml-main-5-0-SP2.xsd\"};\n  auto& fixml_dict = converter.fixml_dico();\n  ASSERT_TRUE(converter.init());\n  ASSERT_TRUE(converter.parse_fixt_dico(\"../spec/fix/FIXT11.xml\"));\n  FIX50SP2::AdjustedPositionReport msg;\n\n  list<multiset<string>> all_values;\n  multiset<string> all_compo_names;\n  multiset<string> AdjustedPositionReport_0;\n  set_field(msg, FIX::ClearingBusinessDate{\"LOCALMKTDATE_91349213\"}, AdjustedPositionReport_0);\n  set_field(msg, FIX::PosMaintRptID{\"STRING_879879046\"}, AdjustedPositionReport_0);\n  set_field(msg, FIX::PosMaintRptRefID{\"STRING_743400359\"}, AdjustedPositionReport_0);\n  set_field(msg, FIX::PosReqType{3}, AdjustedPositionReport_0);\n  FIX::PriorSettlPrice PriorSettlPrice_0;\n  PriorSettlPrice_0.setString(\"10892417\");\nset_field(msg, PriorSettlPrice_0, AdjustedPositionReport_0);\n  FIX::SettlPrice SettlPrice_0;\n  SettlPrice_0.setString(\"11484783\");\nset_field(msg, SettlPrice_0, AdjustedPositionReport_0);\n  set_field(msg, FIX::SettlSessID{\"STRING_EOD\"}, AdjustedPositionReport_0);\n  all_values.push_back(AdjustedPositionReport_0);\n\n  all_compo_names.insert(\"AdjustedPositionReport\");\n\n  // InstrmtGrp\n  // Group InstrmtGrp.NoRelatedSym\n  {\n    FIX50SP2::AdjustedPositionReport::NoRelatedSym noRelatedSym_0_0;\n    // InstrmtGrp.NoRelatedSym\n    // Instrument\n    multiset<string> Instrument_0;\n    FIX::AttachmentPoint AttachmentPoint_0;\n    AttachmentPoint_0.setString(\"32.640000\");\nset_field(noRelatedSym_0_0, AttachmentPoint_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::CFICode{\"STRING_2104574526\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::CPProgram{1}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::CPRegType{\"STRING_727533419\"}, Instrument_0);\n    FIX::CapPrice CapPrice_0;\n    CapPrice_0.setString(\"14477170\");\nset_field(noRelatedSym_0_0, CapPrice_0, Instrument_0);\n    FIX::ContractMultiplier ContractMultiplier_0;\n    ContractMultiplier_0.setString(\"10700682\");\nset_field(noRelatedSym_0_0, ContractMultiplier_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::ContractMultiplierUnit{2}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::ContractSettlMonth{\"MONTHYEAR_1306419442\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::CountryOfIssue{\"COUNTRY_1095952950\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::CouponPaymentDate{\"LOCALMKTDATE_721006617\"}, Instrument_0);\n    FIX::CouponRate CouponRate_0;\n    CouponRate_0.setString(\"57.760000\");\nset_field(noRelatedSym_0_0, CouponRate_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::CreditRating{\"STRING_933467467\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::DatedDate{\"LOCALMKTDATE_305301742\"}, Instrument_0);\n    FIX::DetachmentPoint DetachmentPoint_0;\n    DetachmentPoint_0.setString(\"54.440000\");\nset_field(noRelatedSym_0_0, DetachmentPoint_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::EncodedIssuer{\"DATA_505261502\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::EncodedIssuerLen{2146549818}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::EncodedSecurityDesc{\"DATA_1421553838\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::EncodedSecurityDescLen{379719443}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::ExerciseStyle{2}, Instrument_0);\n    FIX::Factor Factor_0;\n    Factor_0.setString(\"7973337\");\nset_field(noRelatedSym_0_0, Factor_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::FlexProductEligibilityIndicator{true}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::FlexibleIndicator{true}, Instrument_0);\n    FIX::FloorPrice FloorPrice_0;\n    FloorPrice_0.setString(\"17220019\");\nset_field(noRelatedSym_0_0, FloorPrice_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::FlowScheduleType{1}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::InstrRegistry{\"STRING_392707776\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::InstrmtAssignmentMethod{'3'}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::InterestAccrualDate{\"LOCALMKTDATE_892571277\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::IssueDate{\"LOCALMKTDATE_1481949560\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::Issuer{\"STRING_1466396930\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::ListMethod{1}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::LocaleOfIssue{\"STRING_1915344811\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::MaturityDate{\"LOCALMKTDATE_5606546\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::MaturityMonthYear{\"MONTHYEAR_1573618627\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::MaturityTime{\"TZTIMEONLY_2101622777\"}, Instrument_0);\n    FIX::MinPriceIncrement MinPriceIncrement_0;\n    MinPriceIncrement_0.setString(\"7331399\");\nset_field(noRelatedSym_0_0, MinPriceIncrement_0, Instrument_0);\n    FIX::MinPriceIncrementAmount MinPriceIncrementAmount_0;\n    MinPriceIncrementAmount_0.setString(\"8738520\");\nset_field(noRelatedSym_0_0, MinPriceIncrementAmount_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::NTPositionLimit{1024207348}, Instrument_0);\n    FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_0;\n    NotionalPercentageOutstanding_0.setString(\"2.560000\");\nset_field(noRelatedSym_0_0, NotionalPercentageOutstanding_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::OptAttribute{'3'}, Instrument_0);\n    FIX::OptPayoutAmount OptPayoutAmount_0;\n    OptPayoutAmount_0.setString(\"21201602\");\nset_field(noRelatedSym_0_0, OptPayoutAmount_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::OptPayoutType{2}, Instrument_0);\n    FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_0;\n    OriginalNotionalPercentageOutstanding_0.setString(\"35.720000\");\nset_field(noRelatedSym_0_0, OriginalNotionalPercentageOutstanding_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::Pool{\"STRING_906144117\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::PositionLimit{247244967}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::PriceQuoteMethod{\"STRING_STD\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::PriceUnitOfMeasure{\"STRING_1411405619\"}, Instrument_0);\n    FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_0;\n    PriceUnitOfMeasureQty_0.setString(\"2463111\");\nset_field(noRelatedSym_0_0, PriceUnitOfMeasureQty_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::Product{10}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::ProductComplex{\"STRING_1791125062\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::PutOrCall{1}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::RedemptionDate{\"LOCALMKTDATE_505199300\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::RepoCollateralSecurityType{\"STRING_1138607823\"}, Instrument_0);\n    FIX::RepurchaseRate RepurchaseRate_0;\n    RepurchaseRate_0.setString(\"82.610000\");\nset_field(noRelatedSym_0_0, RepurchaseRate_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::RepurchaseTerm{79717561}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::RestructuringType{\"STRING_FR\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityDesc{\"STRING_859496037\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityExchange{\"EXCHANGE_397636181\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityGroup{\"STRING_1470011074\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityID{\"STRING_193961950\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityIDSource{\"STRING_I\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityStatus{\"STRING_2\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SecuritySubType{\"STRING_2109306761\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityType{\"STRING_TAXA\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::Seniority{\"STRING_SR\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SettlMethod{'C'}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SettleOnOpenFlag{\"STRING_455295974\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::StateOrProvinceOfIssue{\"STRING_1239042156\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::StrikeCurrency{\"USD\"}, Instrument_0);\n    FIX::StrikeMultiplier StrikeMultiplier_0;\n    StrikeMultiplier_0.setString(\"12718299\");\nset_field(noRelatedSym_0_0, StrikeMultiplier_0, Instrument_0);\n    FIX::StrikePrice StrikePrice_0;\n    StrikePrice_0.setString(\"9128462\");\nset_field(noRelatedSym_0_0, StrikePrice_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::StrikePriceBoundaryMethod{2}, Instrument_0);\n    FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_0;\n    StrikePriceBoundaryPrecision_0.setString(\"98.760000\");\nset_field(noRelatedSym_0_0, StrikePriceBoundaryPrecision_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::StrikePriceDeterminationMethod{2}, Instrument_0);\n    FIX::StrikeValue StrikeValue_0;\n    StrikeValue_0.setString(\"20129044\");\nset_field(noRelatedSym_0_0, StrikeValue_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::Symbol{\"STRING_764775245\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::SymbolSfx{\"STRING_WI\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::TimeUnit{\"STRING_Yr\"}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::UnderlyingPriceDeterminationMethod{4}, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::UnitOfMeasure{\"STRING_lbs\"}, Instrument_0);\n    FIX::UnitOfMeasureQty UnitOfMeasureQty_0;\n    UnitOfMeasureQty_0.setString(\"10656914\");\nset_field(noRelatedSym_0_0, UnitOfMeasureQty_0, Instrument_0);\n    set_field(noRelatedSym_0_0, FIX::ValuationMethod{\"STRING_CDSD\"}, Instrument_0);\n    all_values.push_back(Instrument_0);\n    all_compo_names.insert(\"...NoRelatedSym.\");\n\n    // ComplexEvents\n    // Group ComplexEvents.NoComplexEvents\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents noComplexEvents_0_1_0;\n      // ComplexEvents.NoComplexEvents\n      multiset<string> ComplexEvents_NoComplexEvents_0;\n      set_field(noComplexEvents_0_1_0, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_0);\n      FIX::ComplexEventPrice ComplexEventPrice_0;\n      ComplexEventPrice_0.setString(\"10575576\");\nset_field(noComplexEvents_0_1_0, ComplexEventPrice_0, ComplexEvents_NoComplexEvents_0);\n      set_field(noComplexEvents_0_1_0, FIX::ComplexEventPriceBoundaryMethod{1}, ComplexEvents_NoComplexEvents_0);\n      FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_0;\n      ComplexEventPriceBoundaryPrecision_0.setString(\"20.960000\");\nset_field(noComplexEvents_0_1_0, ComplexEventPriceBoundaryPrecision_0, ComplexEvents_NoComplexEvents_0);\n      set_field(noComplexEvents_0_1_0, FIX::ComplexEventPriceTimeType{2}, ComplexEvents_NoComplexEvents_0);\n      set_field(noComplexEvents_0_1_0, FIX::ComplexEventType{1}, ComplexEvents_NoComplexEvents_0);\n      FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_0;\n      ComplexOptPayoutAmount_0.setString(\"4384540\");\nset_field(noComplexEvents_0_1_0, ComplexOptPayoutAmount_0, ComplexEvents_NoComplexEvents_0);\n      all_values.push_back(ComplexEvents_NoComplexEvents_0);\n      all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents\");\n\n      // ComplexEventDates\n      // Group ComplexEventDates.NoComplexEventDates\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_0_2_0;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_0;\n        set_field(noComplexEventDates_0_0_2_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(23, 58, 10, 10, 1, 2009)}, ComplexEventDates_NoComplexEventDates_0);\n        set_field(noComplexEventDates_0_0_2_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(11, 31, 45, 23, 1, 2006)}, ComplexEventDates_NoComplexEventDates_0);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_0);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_0_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_0;\n          set_field(noComplexEventTimes_0_0_0_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(23, 32, 28)}, ComplexEventTimes_NoComplexEventTimes_0);\n          set_field(noComplexEventTimes_0_0_0_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(1, 32, 25)}, ComplexEventTimes_NoComplexEventTimes_0);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_0);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_0_0_2_0.addGroup(noComplexEventTimes_0_0_0_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_0_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_1;\n          set_field(noComplexEventTimes_0_0_0_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(17, 0, 11)}, ComplexEventTimes_NoComplexEventTimes_1);\n          set_field(noComplexEventTimes_0_0_0_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(13, 37, 16)}, ComplexEventTimes_NoComplexEventTimes_1);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_1);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_0_0_2_0.addGroup(noComplexEventTimes_0_0_0_3_1);\n        }\n        noComplexEvents_0_1_0.addGroup(noComplexEventDates_0_0_2_0);\n      }\n      noRelatedSym_0_0.addGroup(noComplexEvents_0_1_0);\n    }\n    // EvntGrp\n    // Group EvntGrp.NoEvents\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoEvents noEvents_0_1_0;\n      // EvntGrp.NoEvents\n      multiset<string> EvntGrp_NoEvents_0;\n      set_field(noEvents_0_1_0, FIX::EventDate{\"LOCALMKTDATE_7183529\"}, EvntGrp_NoEvents_0);\n      FIX::EventPx EventPx_0;\n      EventPx_0.setString(\"19674581\");\nset_field(noEvents_0_1_0, EventPx_0, EvntGrp_NoEvents_0);\n      set_field(noEvents_0_1_0, FIX::EventText{\"STRING_464292280\"}, EvntGrp_NoEvents_0);\n      set_field(noEvents_0_1_0, FIX::EventTime{FIX::UTCTIMESTAMP(7, 19, 3, 22, 3, 2012)}, EvntGrp_NoEvents_0);\n      set_field(noEvents_0_1_0, FIX::EventType{10}, EvntGrp_NoEvents_0);\n      all_values.push_back(EvntGrp_NoEvents_0);\n      all_compo_names.insert(\"...NoRelatedSym....NoEvents\");\n\n      noRelatedSym_0_0.addGroup(noEvents_0_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoEvents noEvents_0_1_1;\n      // EvntGrp.NoEvents\n      multiset<string> EvntGrp_NoEvents_1;\n      set_field(noEvents_0_1_1, FIX::EventDate{\"LOCALMKTDATE_1231795350\"}, EvntGrp_NoEvents_1);\n      FIX::EventPx EventPx_1;\n      EventPx_1.setString(\"12948818\");\nset_field(noEvents_0_1_1, EventPx_1, EvntGrp_NoEvents_1);\n      set_field(noEvents_0_1_1, FIX::EventText{\"STRING_1199742167\"}, EvntGrp_NoEvents_1);\n      set_field(noEvents_0_1_1, FIX::EventTime{FIX::UTCTIMESTAMP(10, 19, 36, 13, 1, 2008)}, EvntGrp_NoEvents_1);\n      set_field(noEvents_0_1_1, FIX::EventType{4}, EvntGrp_NoEvents_1);\n      all_values.push_back(EvntGrp_NoEvents_1);\n      all_compo_names.insert(\"...NoRelatedSym....NoEvents\");\n\n      noRelatedSym_0_0.addGroup(noEvents_0_1_1);\n    }\n    // InstrumentParties\n    // Group InstrumentParties.NoInstrumentParties\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties noInstrumentParties_0_1_0;\n      // InstrumentParties.NoInstrumentParties\n      multiset<string> InstrumentParties_NoInstrumentParties_0;\n      set_field(noInstrumentParties_0_1_0, FIX::InstrumentPartyID{\"STRING_154706310\"}, InstrumentParties_NoInstrumentParties_0);\n      set_field(noInstrumentParties_0_1_0, FIX::InstrumentPartyIDSource{'2'}, InstrumentParties_NoInstrumentParties_0);\n      set_field(noInstrumentParties_0_1_0, FIX::InstrumentPartyRole{1599358907}, InstrumentParties_NoInstrumentParties_0);\n      all_values.push_back(InstrumentParties_NoInstrumentParties_0);\n      all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties\");\n\n      // InstrumentPtysSubGrp\n      // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_0_2_0;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_0;\n        set_field(noInstrumentPartySubIDs_0_0_2_0, FIX::InstrumentPartySubID{\"STRING_1000513277\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_0);\n        set_field(noInstrumentPartySubIDs_0_0_2_0, FIX::InstrumentPartySubIDType{1206265277}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_0);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_0);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_0_1_0.addGroup(noInstrumentPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_0_2_1;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_1;\n        set_field(noInstrumentPartySubIDs_0_0_2_1, FIX::InstrumentPartySubID{\"STRING_1130080674\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_1);\n        set_field(noInstrumentPartySubIDs_0_0_2_1, FIX::InstrumentPartySubIDType{542915086}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_1);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_1);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_0_1_0.addGroup(noInstrumentPartySubIDs_0_0_2_1);\n      }\n      noRelatedSym_0_0.addGroup(noInstrumentParties_0_1_0);\n    }\n    // SecAltIDGrp\n    // Group SecAltIDGrp.NoSecurityAltID\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoSecurityAltID noSecurityAltID_0_1_0;\n      // SecAltIDGrp.NoSecurityAltID\n      multiset<string> SecAltIDGrp_NoSecurityAltID_0;\n      set_field(noSecurityAltID_0_1_0, FIX::SecurityAltID{\"STRING_950055180\"}, SecAltIDGrp_NoSecurityAltID_0);\n      set_field(noSecurityAltID_0_1_0, FIX::SecurityAltIDSource{\"STRING_1007207366\"}, SecAltIDGrp_NoSecurityAltID_0);\n      all_values.push_back(SecAltIDGrp_NoSecurityAltID_0);\n      all_compo_names.insert(\"...NoRelatedSym....NoSecurityAltID\");\n\n      noRelatedSym_0_0.addGroup(noSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoSecurityAltID noSecurityAltID_0_1_1;\n      // SecAltIDGrp.NoSecurityAltID\n      multiset<string> SecAltIDGrp_NoSecurityAltID_1;\n      set_field(noSecurityAltID_0_1_1, FIX::SecurityAltID{\"STRING_1536871737\"}, SecAltIDGrp_NoSecurityAltID_1);\n      set_field(noSecurityAltID_0_1_1, FIX::SecurityAltIDSource{\"STRING_2119224979\"}, SecAltIDGrp_NoSecurityAltID_1);\n      all_values.push_back(SecAltIDGrp_NoSecurityAltID_1);\n      all_compo_names.insert(\"...NoRelatedSym....NoSecurityAltID\");\n\n      noRelatedSym_0_0.addGroup(noSecurityAltID_0_1_1);\n    }\n    // SecurityXML\n    multiset<string> SecurityXML_0;\n    set_field(noRelatedSym_0_0, FIX::SecurityXML{\"XMLDATA_1484948625\"}, SecurityXML_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityXMLLen{969220012}, SecurityXML_0);\n    set_field(noRelatedSym_0_0, FIX::SecurityXMLSchema{\"STRING_18855357\"}, SecurityXML_0);\n    all_values.push_back(SecurityXML_0);\n    all_compo_names.insert(\"...NoRelatedSym..\");\n\n    msg.addGroup(noRelatedSym_0_0);\n  }\n  {\n    FIX50SP2::AdjustedPositionReport::NoRelatedSym noRelatedSym_0_1;\n    // InstrmtGrp.NoRelatedSym\n    // Instrument\n    multiset<string> Instrument_1;\n    FIX::AttachmentPoint AttachmentPoint_1;\n    AttachmentPoint_1.setString(\"51.680000\");\nset_field(noRelatedSym_0_1, AttachmentPoint_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::CFICode{\"STRING_423339873\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::CPProgram{2}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::CPRegType{\"STRING_184796870\"}, Instrument_1);\n    FIX::CapPrice CapPrice_1;\n    CapPrice_1.setString(\"17182216\");\nset_field(noRelatedSym_0_1, CapPrice_1, Instrument_1);\n    FIX::ContractMultiplier ContractMultiplier_1;\n    ContractMultiplier_1.setString(\"19093152\");\nset_field(noRelatedSym_0_1, ContractMultiplier_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::ContractMultiplierUnit{0}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::ContractSettlMonth{\"MONTHYEAR_1641810454\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::CountryOfIssue{\"COUNTRY_1582330125\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::CouponPaymentDate{\"LOCALMKTDATE_1674195942\"}, Instrument_1);\n    FIX::CouponRate CouponRate_1;\n    CouponRate_1.setString(\"99.520000\");\nset_field(noRelatedSym_0_1, CouponRate_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::CreditRating{\"STRING_794309186\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::DatedDate{\"LOCALMKTDATE_1234796922\"}, Instrument_1);\n    FIX::DetachmentPoint DetachmentPoint_1;\n    DetachmentPoint_1.setString(\"17.350000\");\nset_field(noRelatedSym_0_1, DetachmentPoint_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::EncodedIssuer{\"DATA_1077732122\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::EncodedIssuerLen{1389503232}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::EncodedSecurityDesc{\"DATA_1287259870\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::EncodedSecurityDescLen{529607381}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::ExerciseStyle{2}, Instrument_1);\n    FIX::Factor Factor_1;\n    Factor_1.setString(\"1402894\");\nset_field(noRelatedSym_0_1, Factor_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::FlexProductEligibilityIndicator{true}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::FlexibleIndicator{true}, Instrument_1);\n    FIX::FloorPrice FloorPrice_1;\n    FloorPrice_1.setString(\"6832045\");\nset_field(noRelatedSym_0_1, FloorPrice_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::FlowScheduleType{1}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::InstrRegistry{\"STRING_1378677276\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::InstrmtAssignmentMethod{'1'}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::InterestAccrualDate{\"LOCALMKTDATE_191225905\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::IssueDate{\"LOCALMKTDATE_1350418608\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::Issuer{\"STRING_1027876930\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::ListMethod{0}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::LocaleOfIssue{\"STRING_1369273965\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::MaturityDate{\"LOCALMKTDATE_2128362098\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::MaturityMonthYear{\"MONTHYEAR_1583785791\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::MaturityTime{\"TZTIMEONLY_2078847032\"}, Instrument_1);\n    FIX::MinPriceIncrement MinPriceIncrement_1;\n    MinPriceIncrement_1.setString(\"1656753\");\nset_field(noRelatedSym_0_1, MinPriceIncrement_1, Instrument_1);\n    FIX::MinPriceIncrementAmount MinPriceIncrementAmount_1;\n    MinPriceIncrementAmount_1.setString(\"11545238\");\nset_field(noRelatedSym_0_1, MinPriceIncrementAmount_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::NTPositionLimit{1840678618}, Instrument_1);\n    FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_1;\n    NotionalPercentageOutstanding_1.setString(\"79.460000\");\nset_field(noRelatedSym_0_1, NotionalPercentageOutstanding_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::OptAttribute{'6'}, Instrument_1);\n    FIX::OptPayoutAmount OptPayoutAmount_1;\n    OptPayoutAmount_1.setString(\"12755250\");\nset_field(noRelatedSym_0_1, OptPayoutAmount_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::OptPayoutType{1}, Instrument_1);\n    FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_1;\n    OriginalNotionalPercentageOutstanding_1.setString(\"5.770000\");\nset_field(noRelatedSym_0_1, OriginalNotionalPercentageOutstanding_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::Pool{\"STRING_2069834281\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::PositionLimit{429843515}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::PriceQuoteMethod{\"STRING_STD\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::PriceUnitOfMeasure{\"STRING_1000082755\"}, Instrument_1);\n    FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_1;\n    PriceUnitOfMeasureQty_1.setString(\"18193467\");\nset_field(noRelatedSym_0_1, PriceUnitOfMeasureQty_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::Product{3}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::ProductComplex{\"STRING_1529690137\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::PutOrCall{1}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::RedemptionDate{\"LOCALMKTDATE_122024386\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::RepoCollateralSecurityType{\"STRING_1118079147\"}, Instrument_1);\n    FIX::RepurchaseRate RepurchaseRate_1;\n    RepurchaseRate_1.setString(\"2.650000\");\nset_field(noRelatedSym_0_1, RepurchaseRate_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::RepurchaseTerm{805228972}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::RestructuringType{\"STRING_FR\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SecurityDesc{\"STRING_777703894\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SecurityExchange{\"EXCHANGE_348157277\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SecurityGroup{\"STRING_2111142869\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SecurityID{\"STRING_2128122502\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SecurityIDSource{\"STRING_A\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SecurityStatus{\"STRING_2\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SecuritySubType{\"STRING_1349912819\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SecurityType{\"STRING_GO\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::Seniority{\"STRING_SR\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SettlMethod{'P'}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SettleOnOpenFlag{\"STRING_1522587977\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::StateOrProvinceOfIssue{\"STRING_1714931101\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::StrikeCurrency{\"USD\"}, Instrument_1);\n    FIX::StrikeMultiplier StrikeMultiplier_1;\n    StrikeMultiplier_1.setString(\"2162980\");\nset_field(noRelatedSym_0_1, StrikeMultiplier_1, Instrument_1);\n    FIX::StrikePrice StrikePrice_1;\n    StrikePrice_1.setString(\"1025126\");\nset_field(noRelatedSym_0_1, StrikePrice_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::StrikePriceBoundaryMethod{4}, Instrument_1);\n    FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_1;\n    StrikePriceBoundaryPrecision_1.setString(\"86.560000\");\nset_field(noRelatedSym_0_1, StrikePriceBoundaryPrecision_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::StrikePriceDeterminationMethod{3}, Instrument_1);\n    FIX::StrikeValue StrikeValue_1;\n    StrikeValue_1.setString(\"8158123\");\nset_field(noRelatedSym_0_1, StrikeValue_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::Symbol{\"STRING_480283673\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::SymbolSfx{\"STRING_CD\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::TimeUnit{\"STRING_Min\"}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::UnderlyingPriceDeterminationMethod{1}, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::UnitOfMeasure{\"STRING_Bcf\"}, Instrument_1);\n    FIX::UnitOfMeasureQty UnitOfMeasureQty_1;\n    UnitOfMeasureQty_1.setString(\"16055636\");\nset_field(noRelatedSym_0_1, UnitOfMeasureQty_1, Instrument_1);\n    set_field(noRelatedSym_0_1, FIX::ValuationMethod{\"STRING_FUT\"}, Instrument_1);\n    all_values.push_back(Instrument_1);\n    all_compo_names.insert(\"...NoRelatedSym.\");\n\n    // ComplexEvents\n    // Group ComplexEvents.NoComplexEvents\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents noComplexEvents_1_1_0;\n      // ComplexEvents.NoComplexEvents\n      multiset<string> ComplexEvents_NoComplexEvents_1;\n      set_field(noComplexEvents_1_1_0, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_1);\n      FIX::ComplexEventPrice ComplexEventPrice_1;\n      ComplexEventPrice_1.setString(\"13892719\");\nset_field(noComplexEvents_1_1_0, ComplexEventPrice_1, ComplexEvents_NoComplexEvents_1);\n      set_field(noComplexEvents_1_1_0, FIX::ComplexEventPriceBoundaryMethod{3}, ComplexEvents_NoComplexEvents_1);\n      FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_1;\n      ComplexEventPriceBoundaryPrecision_1.setString(\"41.640000\");\nset_field(noComplexEvents_1_1_0, ComplexEventPriceBoundaryPrecision_1, ComplexEvents_NoComplexEvents_1);\n      set_field(noComplexEvents_1_1_0, FIX::ComplexEventPriceTimeType{2}, ComplexEvents_NoComplexEvents_1);\n      set_field(noComplexEvents_1_1_0, FIX::ComplexEventType{6}, ComplexEvents_NoComplexEvents_1);\n      FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_1;\n      ComplexOptPayoutAmount_1.setString(\"17629330\");\nset_field(noComplexEvents_1_1_0, ComplexOptPayoutAmount_1, ComplexEvents_NoComplexEvents_1);\n      all_values.push_back(ComplexEvents_NoComplexEvents_1);\n      all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents\");\n\n      // ComplexEventDates\n      // Group ComplexEventDates.NoComplexEventDates\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_0_2_0;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_1;\n        set_field(noComplexEventDates_1_0_2_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(13, 24, 38, 25, 6, 2001)}, ComplexEventDates_NoComplexEventDates_1);\n        set_field(noComplexEventDates_1_0_2_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(9, 30, 59, 2, 12, 2016)}, ComplexEventDates_NoComplexEventDates_1);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_1);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_0_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_2;\n          set_field(noComplexEventTimes_1_0_0_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(20, 16, 12)}, ComplexEventTimes_NoComplexEventTimes_2);\n          set_field(noComplexEventTimes_1_0_0_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(5, 18, 21)}, ComplexEventTimes_NoComplexEventTimes_2);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_2);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_0_2_0.addGroup(noComplexEventTimes_1_0_0_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_0_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_3;\n          set_field(noComplexEventTimes_1_0_0_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(21, 36, 7)}, ComplexEventTimes_NoComplexEventTimes_3);\n          set_field(noComplexEventTimes_1_0_0_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(0, 5, 52)}, ComplexEventTimes_NoComplexEventTimes_3);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_3);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_0_2_0.addGroup(noComplexEventTimes_1_0_0_3_1);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_0_3_2;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_4;\n          set_field(noComplexEventTimes_1_0_0_3_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(22, 16, 5)}, ComplexEventTimes_NoComplexEventTimes_4);\n          set_field(noComplexEventTimes_1_0_0_3_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(14, 37, 10)}, ComplexEventTimes_NoComplexEventTimes_4);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_4);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_0_2_0.addGroup(noComplexEventTimes_1_0_0_3_2);\n        }\n        noComplexEvents_1_1_0.addGroup(noComplexEventDates_1_0_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_0_2_1;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_2;\n        set_field(noComplexEventDates_1_0_2_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(23, 1, 29, 2, 4, 2009)}, ComplexEventDates_NoComplexEventDates_2);\n        set_field(noComplexEventDates_1_0_2_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(23, 19, 54, 6, 5, 2013)}, ComplexEventDates_NoComplexEventDates_2);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_2);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_1_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_5;\n          set_field(noComplexEventTimes_1_0_1_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(14, 8, 18)}, ComplexEventTimes_NoComplexEventTimes_5);\n          set_field(noComplexEventTimes_1_0_1_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(20, 15, 16)}, ComplexEventTimes_NoComplexEventTimes_5);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_5);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_0_2_1.addGroup(noComplexEventTimes_1_0_1_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_1_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_6;\n          set_field(noComplexEventTimes_1_0_1_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(18, 25, 45)}, ComplexEventTimes_NoComplexEventTimes_6);\n          set_field(noComplexEventTimes_1_0_1_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(3, 14, 47)}, ComplexEventTimes_NoComplexEventTimes_6);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_6);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_0_2_1.addGroup(noComplexEventTimes_1_0_1_3_1);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_1_3_2;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_7;\n          set_field(noComplexEventTimes_1_0_1_3_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(13, 41, 28)}, ComplexEventTimes_NoComplexEventTimes_7);\n          set_field(noComplexEventTimes_1_0_1_3_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(20, 31, 54)}, ComplexEventTimes_NoComplexEventTimes_7);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_7);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_0_2_1.addGroup(noComplexEventTimes_1_0_1_3_2);\n        }\n        noComplexEvents_1_1_0.addGroup(noComplexEventDates_1_0_2_1);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_0_2_2;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_3;\n        set_field(noComplexEventDates_1_0_2_2, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(14, 49, 50, 27, 7, 2014)}, ComplexEventDates_NoComplexEventDates_3);\n        set_field(noComplexEventDates_1_0_2_2, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(8, 14, 45, 0, 3, 2004)}, ComplexEventDates_NoComplexEventDates_3);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_3);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_8;\n          set_field(noComplexEventTimes_1_0_2_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(2, 14, 43)}, ComplexEventTimes_NoComplexEventTimes_8);\n          set_field(noComplexEventTimes_1_0_2_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(21, 57, 3)}, ComplexEventTimes_NoComplexEventTimes_8);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_8);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_0_2_2.addGroup(noComplexEventTimes_1_0_2_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_9;\n          set_field(noComplexEventTimes_1_0_2_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(2, 36, 55)}, ComplexEventTimes_NoComplexEventTimes_9);\n          set_field(noComplexEventTimes_1_0_2_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(9, 18, 1)}, ComplexEventTimes_NoComplexEventTimes_9);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_9);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_0_2_2.addGroup(noComplexEventTimes_1_0_2_3_1);\n        }\n        noComplexEvents_1_1_0.addGroup(noComplexEventDates_1_0_2_2);\n      }\n      noRelatedSym_0_1.addGroup(noComplexEvents_1_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents noComplexEvents_1_1_1;\n      // ComplexEvents.NoComplexEvents\n      multiset<string> ComplexEvents_NoComplexEvents_2;\n      set_field(noComplexEvents_1_1_1, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_2);\n      FIX::ComplexEventPrice ComplexEventPrice_2;\n      ComplexEventPrice_2.setString(\"2718770\");\nset_field(noComplexEvents_1_1_1, ComplexEventPrice_2, ComplexEvents_NoComplexEvents_2);\n      set_field(noComplexEvents_1_1_1, FIX::ComplexEventPriceBoundaryMethod{1}, ComplexEvents_NoComplexEvents_2);\n      FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_2;\n      ComplexEventPriceBoundaryPrecision_2.setString(\"75.510000\");\nset_field(noComplexEvents_1_1_1, ComplexEventPriceBoundaryPrecision_2, ComplexEvents_NoComplexEvents_2);\n      set_field(noComplexEvents_1_1_1, FIX::ComplexEventPriceTimeType{1}, ComplexEvents_NoComplexEvents_2);\n      set_field(noComplexEvents_1_1_1, FIX::ComplexEventType{6}, ComplexEvents_NoComplexEvents_2);\n      FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_2;\n      ComplexOptPayoutAmount_2.setString(\"13227921\");\nset_field(noComplexEvents_1_1_1, ComplexOptPayoutAmount_2, ComplexEvents_NoComplexEvents_2);\n      all_values.push_back(ComplexEvents_NoComplexEvents_2);\n      all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents\");\n\n      // ComplexEventDates\n      // Group ComplexEventDates.NoComplexEventDates\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_2_0;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_4;\n        set_field(noComplexEventDates_1_1_2_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(8, 27, 17, 11, 1, 2012)}, ComplexEventDates_NoComplexEventDates_4);\n        set_field(noComplexEventDates_1_1_2_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(2, 12, 28, 2, 10, 2013)}, ComplexEventDates_NoComplexEventDates_4);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_4);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_0_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_10;\n          set_field(noComplexEventTimes_1_1_0_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(19, 38, 48)}, ComplexEventTimes_NoComplexEventTimes_10);\n          set_field(noComplexEventTimes_1_1_0_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(15, 6, 27)}, ComplexEventTimes_NoComplexEventTimes_10);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_10);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_0.addGroup(noComplexEventTimes_1_1_0_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_0_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_11;\n          set_field(noComplexEventTimes_1_1_0_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(19, 9, 8)}, ComplexEventTimes_NoComplexEventTimes_11);\n          set_field(noComplexEventTimes_1_1_0_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(21, 14, 14)}, ComplexEventTimes_NoComplexEventTimes_11);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_11);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_0.addGroup(noComplexEventTimes_1_1_0_3_1);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_0_3_2;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_12;\n          set_field(noComplexEventTimes_1_1_0_3_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(2, 33, 38)}, ComplexEventTimes_NoComplexEventTimes_12);\n          set_field(noComplexEventTimes_1_1_0_3_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(21, 44, 50)}, ComplexEventTimes_NoComplexEventTimes_12);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_12);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_0.addGroup(noComplexEventTimes_1_1_0_3_2);\n        }\n        noComplexEvents_1_1_1.addGroup(noComplexEventDates_1_1_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_2_1;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_5;\n        set_field(noComplexEventDates_1_1_2_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(20, 18, 34, 21, 12, 2000)}, ComplexEventDates_NoComplexEventDates_5);\n        set_field(noComplexEventDates_1_1_2_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(7, 7, 2, 13, 11, 2002)}, ComplexEventDates_NoComplexEventDates_5);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_5);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_1_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_13;\n          set_field(noComplexEventTimes_1_1_1_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(20, 33, 47)}, ComplexEventTimes_NoComplexEventTimes_13);\n          set_field(noComplexEventTimes_1_1_1_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(18, 53, 37)}, ComplexEventTimes_NoComplexEventTimes_13);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_13);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_1.addGroup(noComplexEventTimes_1_1_1_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_1_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_14;\n          set_field(noComplexEventTimes_1_1_1_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(19, 11, 18)}, ComplexEventTimes_NoComplexEventTimes_14);\n          set_field(noComplexEventTimes_1_1_1_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(0, 54, 7)}, ComplexEventTimes_NoComplexEventTimes_14);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_14);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_1.addGroup(noComplexEventTimes_1_1_1_3_1);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_1_3_2;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_15;\n          set_field(noComplexEventTimes_1_1_1_3_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(7, 18, 51)}, ComplexEventTimes_NoComplexEventTimes_15);\n          set_field(noComplexEventTimes_1_1_1_3_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(17, 19, 18)}, ComplexEventTimes_NoComplexEventTimes_15);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_15);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_1.addGroup(noComplexEventTimes_1_1_1_3_2);\n        }\n        noComplexEvents_1_1_1.addGroup(noComplexEventDates_1_1_2_1);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_2_2;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_6;\n        set_field(noComplexEventDates_1_1_2_2, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(6, 12, 45, 13, 2, 2005)}, ComplexEventDates_NoComplexEventDates_6);\n        set_field(noComplexEventDates_1_1_2_2, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(21, 50, 51, 8, 1, 2000)}, ComplexEventDates_NoComplexEventDates_6);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_6);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_16;\n          set_field(noComplexEventTimes_1_1_2_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(11, 17, 50)}, ComplexEventTimes_NoComplexEventTimes_16);\n          set_field(noComplexEventTimes_1_1_2_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(5, 36, 4)}, ComplexEventTimes_NoComplexEventTimes_16);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_16);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_2.addGroup(noComplexEventTimes_1_1_2_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_17;\n          set_field(noComplexEventTimes_1_1_2_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(23, 22, 57)}, ComplexEventTimes_NoComplexEventTimes_17);\n          set_field(noComplexEventTimes_1_1_2_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(19, 16, 18)}, ComplexEventTimes_NoComplexEventTimes_17);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_17);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_2.addGroup(noComplexEventTimes_1_1_2_3_1);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_3_2;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_18;\n          set_field(noComplexEventTimes_1_1_2_3_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(11, 31, 25)}, ComplexEventTimes_NoComplexEventTimes_18);\n          set_field(noComplexEventTimes_1_1_2_3_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(8, 43, 4)}, ComplexEventTimes_NoComplexEventTimes_18);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_18);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_1_2_2.addGroup(noComplexEventTimes_1_1_2_3_2);\n        }\n        noComplexEvents_1_1_1.addGroup(noComplexEventDates_1_1_2_2);\n      }\n      noRelatedSym_0_1.addGroup(noComplexEvents_1_1_1);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents noComplexEvents_1_1_2;\n      // ComplexEvents.NoComplexEvents\n      multiset<string> ComplexEvents_NoComplexEvents_3;\n      set_field(noComplexEvents_1_1_2, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_3);\n      FIX::ComplexEventPrice ComplexEventPrice_3;\n      ComplexEventPrice_3.setString(\"8976075\");\nset_field(noComplexEvents_1_1_2, ComplexEventPrice_3, ComplexEvents_NoComplexEvents_3);\n      set_field(noComplexEvents_1_1_2, FIX::ComplexEventPriceBoundaryMethod{1}, ComplexEvents_NoComplexEvents_3);\n      FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_3;\n      ComplexEventPriceBoundaryPrecision_3.setString(\"86.330000\");\nset_field(noComplexEvents_1_1_2, ComplexEventPriceBoundaryPrecision_3, ComplexEvents_NoComplexEvents_3);\n      set_field(noComplexEvents_1_1_2, FIX::ComplexEventPriceTimeType{3}, ComplexEvents_NoComplexEvents_3);\n      set_field(noComplexEvents_1_1_2, FIX::ComplexEventType{9}, ComplexEvents_NoComplexEvents_3);\n      FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_3;\n      ComplexOptPayoutAmount_3.setString(\"18783298\");\nset_field(noComplexEvents_1_1_2, ComplexOptPayoutAmount_3, ComplexEvents_NoComplexEvents_3);\n      all_values.push_back(ComplexEvents_NoComplexEvents_3);\n      all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents\");\n\n      // ComplexEventDates\n      // Group ComplexEventDates.NoComplexEventDates\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_2_2_0;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_7;\n        set_field(noComplexEventDates_1_2_2_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(8, 40, 7, 10, 9, 2017)}, ComplexEventDates_NoComplexEventDates_7);\n        set_field(noComplexEventDates_1_2_2_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(20, 33, 5, 4, 9, 2013)}, ComplexEventDates_NoComplexEventDates_7);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_7);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_2_0_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_19;\n          set_field(noComplexEventTimes_1_2_0_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(16, 1, 38)}, ComplexEventTimes_NoComplexEventTimes_19);\n          set_field(noComplexEventTimes_1_2_0_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(13, 13, 44)}, ComplexEventTimes_NoComplexEventTimes_19);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_19);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_2_2_0.addGroup(noComplexEventTimes_1_2_0_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_2_0_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_20;\n          set_field(noComplexEventTimes_1_2_0_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(14, 31, 8)}, ComplexEventTimes_NoComplexEventTimes_20);\n          set_field(noComplexEventTimes_1_2_0_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(6, 47, 54)}, ComplexEventTimes_NoComplexEventTimes_20);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_20);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_2_2_0.addGroup(noComplexEventTimes_1_2_0_3_1);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_2_0_3_2;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_21;\n          set_field(noComplexEventTimes_1_2_0_3_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(0, 26, 4)}, ComplexEventTimes_NoComplexEventTimes_21);\n          set_field(noComplexEventTimes_1_2_0_3_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(23, 15, 38)}, ComplexEventTimes_NoComplexEventTimes_21);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_21);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_2_2_0.addGroup(noComplexEventTimes_1_2_0_3_2);\n        }\n        noComplexEvents_1_1_2.addGroup(noComplexEventDates_1_2_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_2_2_1;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_8;\n        set_field(noComplexEventDates_1_2_2_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(4, 35, 7, 0, 1, 2007)}, ComplexEventDates_NoComplexEventDates_8);\n        set_field(noComplexEventDates_1_2_2_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(17, 31, 3, 5, 9, 2008)}, ComplexEventDates_NoComplexEventDates_8);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_8);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_2_1_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_22;\n          set_field(noComplexEventTimes_1_2_1_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(22, 9, 35)}, ComplexEventTimes_NoComplexEventTimes_22);\n          set_field(noComplexEventTimes_1_2_1_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(8, 22, 21)}, ComplexEventTimes_NoComplexEventTimes_22);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_22);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_2_2_1.addGroup(noComplexEventTimes_1_2_1_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_2_1_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_23;\n          set_field(noComplexEventTimes_1_2_1_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(2, 48, 57)}, ComplexEventTimes_NoComplexEventTimes_23);\n          set_field(noComplexEventTimes_1_2_1_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(15, 4, 50)}, ComplexEventTimes_NoComplexEventTimes_23);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_23);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_1_2_2_1.addGroup(noComplexEventTimes_1_2_1_3_1);\n        }\n        noComplexEvents_1_1_2.addGroup(noComplexEventDates_1_2_2_1);\n      }\n      noRelatedSym_0_1.addGroup(noComplexEvents_1_1_2);\n    }\n    // EvntGrp\n    // Group EvntGrp.NoEvents\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoEvents noEvents_1_1_0;\n      // EvntGrp.NoEvents\n      multiset<string> EvntGrp_NoEvents_2;\n      set_field(noEvents_1_1_0, FIX::EventDate{\"LOCALMKTDATE_1078040084\"}, EvntGrp_NoEvents_2);\n      FIX::EventPx EventPx_2;\n      EventPx_2.setString(\"16830815\");\nset_field(noEvents_1_1_0, EventPx_2, EvntGrp_NoEvents_2);\n      set_field(noEvents_1_1_0, FIX::EventText{\"STRING_150574621\"}, EvntGrp_NoEvents_2);\n      set_field(noEvents_1_1_0, FIX::EventTime{FIX::UTCTIMESTAMP(6, 38, 13, 19, 2, 2014)}, EvntGrp_NoEvents_2);\n      set_field(noEvents_1_1_0, FIX::EventType{9}, EvntGrp_NoEvents_2);\n      all_values.push_back(EvntGrp_NoEvents_2);\n      all_compo_names.insert(\"...NoRelatedSym....NoEvents\");\n\n      noRelatedSym_0_1.addGroup(noEvents_1_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoEvents noEvents_1_1_1;\n      // EvntGrp.NoEvents\n      multiset<string> EvntGrp_NoEvents_3;\n      set_field(noEvents_1_1_1, FIX::EventDate{\"LOCALMKTDATE_1327340170\"}, EvntGrp_NoEvents_3);\n      FIX::EventPx EventPx_3;\n      EventPx_3.setString(\"4133576\");\nset_field(noEvents_1_1_1, EventPx_3, EvntGrp_NoEvents_3);\n      set_field(noEvents_1_1_1, FIX::EventText{\"STRING_512864586\"}, EvntGrp_NoEvents_3);\n      set_field(noEvents_1_1_1, FIX::EventTime{FIX::UTCTIMESTAMP(7, 16, 20, 2, 1, 2010)}, EvntGrp_NoEvents_3);\n      set_field(noEvents_1_1_1, FIX::EventType{12}, EvntGrp_NoEvents_3);\n      all_values.push_back(EvntGrp_NoEvents_3);\n      all_compo_names.insert(\"...NoRelatedSym....NoEvents\");\n\n      noRelatedSym_0_1.addGroup(noEvents_1_1_1);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoEvents noEvents_1_1_2;\n      // EvntGrp.NoEvents\n      multiset<string> EvntGrp_NoEvents_4;\n      set_field(noEvents_1_1_2, FIX::EventDate{\"LOCALMKTDATE_426802197\"}, EvntGrp_NoEvents_4);\n      FIX::EventPx EventPx_4;\n      EventPx_4.setString(\"17097555\");\nset_field(noEvents_1_1_2, EventPx_4, EvntGrp_NoEvents_4);\n      set_field(noEvents_1_1_2, FIX::EventText{\"STRING_629611171\"}, EvntGrp_NoEvents_4);\n      set_field(noEvents_1_1_2, FIX::EventTime{FIX::UTCTIMESTAMP(1, 46, 50, 16, 1, 2004)}, EvntGrp_NoEvents_4);\n      set_field(noEvents_1_1_2, FIX::EventType{6}, EvntGrp_NoEvents_4);\n      all_values.push_back(EvntGrp_NoEvents_4);\n      all_compo_names.insert(\"...NoRelatedSym....NoEvents\");\n\n      noRelatedSym_0_1.addGroup(noEvents_1_1_2);\n    }\n    // InstrumentParties\n    // Group InstrumentParties.NoInstrumentParties\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties noInstrumentParties_1_1_0;\n      // InstrumentParties.NoInstrumentParties\n      multiset<string> InstrumentParties_NoInstrumentParties_1;\n      set_field(noInstrumentParties_1_1_0, FIX::InstrumentPartyID{\"STRING_1044003562\"}, InstrumentParties_NoInstrumentParties_1);\n      set_field(noInstrumentParties_1_1_0, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_1);\n      set_field(noInstrumentParties_1_1_0, FIX::InstrumentPartyRole{1080675560}, InstrumentParties_NoInstrumentParties_1);\n      all_values.push_back(InstrumentParties_NoInstrumentParties_1);\n      all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties\");\n\n      // InstrumentPtysSubGrp\n      // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_0_2_0;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_2;\n        set_field(noInstrumentPartySubIDs_1_0_2_0, FIX::InstrumentPartySubID{\"STRING_107754670\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_2);\n        set_field(noInstrumentPartySubIDs_1_0_2_0, FIX::InstrumentPartySubIDType{1358292261}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_2);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_2);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_1_1_0.addGroup(noInstrumentPartySubIDs_1_0_2_0);\n      }\n      noRelatedSym_0_1.addGroup(noInstrumentParties_1_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties noInstrumentParties_1_1_1;\n      // InstrumentParties.NoInstrumentParties\n      multiset<string> InstrumentParties_NoInstrumentParties_2;\n      set_field(noInstrumentParties_1_1_1, FIX::InstrumentPartyID{\"STRING_1324506704\"}, InstrumentParties_NoInstrumentParties_2);\n      set_field(noInstrumentParties_1_1_1, FIX::InstrumentPartyIDSource{'9'}, InstrumentParties_NoInstrumentParties_2);\n      set_field(noInstrumentParties_1_1_1, FIX::InstrumentPartyRole{538148783}, InstrumentParties_NoInstrumentParties_2);\n      all_values.push_back(InstrumentParties_NoInstrumentParties_2);\n      all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties\");\n\n      // InstrumentPtysSubGrp\n      // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_2_0;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_3;\n        set_field(noInstrumentPartySubIDs_1_1_2_0, FIX::InstrumentPartySubID{\"STRING_1493190225\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_3);\n        set_field(noInstrumentPartySubIDs_1_1_2_0, FIX::InstrumentPartySubIDType{5549640}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_3);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_3);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_1_1_1.addGroup(noInstrumentPartySubIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_2_1;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_4;\n        set_field(noInstrumentPartySubIDs_1_1_2_1, FIX::InstrumentPartySubID{\"STRING_2003618456\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_4);\n        set_field(noInstrumentPartySubIDs_1_1_2_1, FIX::InstrumentPartySubIDType{660540533}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_4);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_4);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_1_1_1.addGroup(noInstrumentPartySubIDs_1_1_2_1);\n      }\n      noRelatedSym_0_1.addGroup(noInstrumentParties_1_1_1);\n    }\n    // SecAltIDGrp\n    // Group SecAltIDGrp.NoSecurityAltID\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoSecurityAltID noSecurityAltID_1_1_0;\n      // SecAltIDGrp.NoSecurityAltID\n      multiset<string> SecAltIDGrp_NoSecurityAltID_2;\n      set_field(noSecurityAltID_1_1_0, FIX::SecurityAltID{\"STRING_830755758\"}, SecAltIDGrp_NoSecurityAltID_2);\n      set_field(noSecurityAltID_1_1_0, FIX::SecurityAltIDSource{\"STRING_150366537\"}, SecAltIDGrp_NoSecurityAltID_2);\n      all_values.push_back(SecAltIDGrp_NoSecurityAltID_2);\n      all_compo_names.insert(\"...NoRelatedSym....NoSecurityAltID\");\n\n      noRelatedSym_0_1.addGroup(noSecurityAltID_1_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoSecurityAltID noSecurityAltID_1_1_1;\n      // SecAltIDGrp.NoSecurityAltID\n      multiset<string> SecAltIDGrp_NoSecurityAltID_3;\n      set_field(noSecurityAltID_1_1_1, FIX::SecurityAltID{\"STRING_1176912227\"}, SecAltIDGrp_NoSecurityAltID_3);\n      set_field(noSecurityAltID_1_1_1, FIX::SecurityAltIDSource{\"STRING_227994481\"}, SecAltIDGrp_NoSecurityAltID_3);\n      all_values.push_back(SecAltIDGrp_NoSecurityAltID_3);\n      all_compo_names.insert(\"...NoRelatedSym....NoSecurityAltID\");\n\n      noRelatedSym_0_1.addGroup(noSecurityAltID_1_1_1);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoSecurityAltID noSecurityAltID_1_1_2;\n      // SecAltIDGrp.NoSecurityAltID\n      multiset<string> SecAltIDGrp_NoSecurityAltID_4;\n      set_field(noSecurityAltID_1_1_2, FIX::SecurityAltID{\"STRING_577168734\"}, SecAltIDGrp_NoSecurityAltID_4);\n      set_field(noSecurityAltID_1_1_2, FIX::SecurityAltIDSource{\"STRING_739184164\"}, SecAltIDGrp_NoSecurityAltID_4);\n      all_values.push_back(SecAltIDGrp_NoSecurityAltID_4);\n      all_compo_names.insert(\"...NoRelatedSym....NoSecurityAltID\");\n\n      noRelatedSym_0_1.addGroup(noSecurityAltID_1_1_2);\n    }\n    // SecurityXML\n    multiset<string> SecurityXML_2;\n    set_field(noRelatedSym_0_1, FIX::SecurityXML{\"XMLDATA_857605653\"}, SecurityXML_2);\n    set_field(noRelatedSym_0_1, FIX::SecurityXMLLen{483464920}, SecurityXML_2);\n    set_field(noRelatedSym_0_1, FIX::SecurityXMLSchema{\"STRING_1402846061\"}, SecurityXML_2);\n    all_values.push_back(SecurityXML_2);\n    all_compo_names.insert(\"...NoRelatedSym..\");\n\n    msg.addGroup(noRelatedSym_0_1);\n  }\n  {\n    FIX50SP2::AdjustedPositionReport::NoRelatedSym noRelatedSym_0_2;\n    // InstrmtGrp.NoRelatedSym\n    // Instrument\n    multiset<string> Instrument_2;\n    FIX::AttachmentPoint AttachmentPoint_2;\n    AttachmentPoint_2.setString(\"1.990000\");\nset_field(noRelatedSym_0_2, AttachmentPoint_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::CFICode{\"STRING_1014429450\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::CPProgram{2}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::CPRegType{\"STRING_691683060\"}, Instrument_2);\n    FIX::CapPrice CapPrice_2;\n    CapPrice_2.setString(\"4759504\");\nset_field(noRelatedSym_0_2, CapPrice_2, Instrument_2);\n    FIX::ContractMultiplier ContractMultiplier_2;\n    ContractMultiplier_2.setString(\"18641563\");\nset_field(noRelatedSym_0_2, ContractMultiplier_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::ContractMultiplierUnit{2}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::ContractSettlMonth{\"MONTHYEAR_1519953979\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::CountryOfIssue{\"COUNTRY_1594775850\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::CouponPaymentDate{\"LOCALMKTDATE_1082216101\"}, Instrument_2);\n    FIX::CouponRate CouponRate_2;\n    CouponRate_2.setString(\"5.470000\");\nset_field(noRelatedSym_0_2, CouponRate_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::CreditRating{\"STRING_1702530521\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::DatedDate{\"LOCALMKTDATE_293024715\"}, Instrument_2);\n    FIX::DetachmentPoint DetachmentPoint_2;\n    DetachmentPoint_2.setString(\"72.510000\");\nset_field(noRelatedSym_0_2, DetachmentPoint_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::EncodedIssuer{\"DATA_535372512\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::EncodedIssuerLen{831173498}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::EncodedSecurityDesc{\"DATA_1610627964\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::EncodedSecurityDescLen{2028562737}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::ExerciseStyle{0}, Instrument_2);\n    FIX::Factor Factor_2;\n    Factor_2.setString(\"14667627\");\nset_field(noRelatedSym_0_2, Factor_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::FlexProductEligibilityIndicator{false}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::FlexibleIndicator{false}, Instrument_2);\n    FIX::FloorPrice FloorPrice_2;\n    FloorPrice_2.setString(\"1500348\");\nset_field(noRelatedSym_0_2, FloorPrice_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::FlowScheduleType{0}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::InstrRegistry{\"STRING_1648029698\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::InstrmtAssignmentMethod{'3'}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::InterestAccrualDate{\"LOCALMKTDATE_1269154895\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::IssueDate{\"LOCALMKTDATE_239730214\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::Issuer{\"STRING_1235635017\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::ListMethod{1}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::LocaleOfIssue{\"STRING_1642576276\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::MaturityDate{\"LOCALMKTDATE_620551568\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::MaturityMonthYear{\"MONTHYEAR_619565618\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::MaturityTime{\"TZTIMEONLY_287053029\"}, Instrument_2);\n    FIX::MinPriceIncrement MinPriceIncrement_2;\n    MinPriceIncrement_2.setString(\"13122346\");\nset_field(noRelatedSym_0_2, MinPriceIncrement_2, Instrument_2);\n    FIX::MinPriceIncrementAmount MinPriceIncrementAmount_2;\n    MinPriceIncrementAmount_2.setString(\"10955160\");\nset_field(noRelatedSym_0_2, MinPriceIncrementAmount_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::NTPositionLimit{3725688}, Instrument_2);\n    FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_2;\n    NotionalPercentageOutstanding_2.setString(\"51.700000\");\nset_field(noRelatedSym_0_2, NotionalPercentageOutstanding_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::OptAttribute{'4'}, Instrument_2);\n    FIX::OptPayoutAmount OptPayoutAmount_2;\n    OptPayoutAmount_2.setString(\"15985015\");\nset_field(noRelatedSym_0_2, OptPayoutAmount_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::OptPayoutType{2}, Instrument_2);\n    FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_2;\n    OriginalNotionalPercentageOutstanding_2.setString(\"69.120000\");\nset_field(noRelatedSym_0_2, OriginalNotionalPercentageOutstanding_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::Pool{\"STRING_1153548412\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::PositionLimit{541532338}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::PriceQuoteMethod{\"STRING_STD\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::PriceUnitOfMeasure{\"STRING_1688920924\"}, Instrument_2);\n    FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_2;\n    PriceUnitOfMeasureQty_2.setString(\"13727058\");\nset_field(noRelatedSym_0_2, PriceUnitOfMeasureQty_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::Product{9}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::ProductComplex{\"STRING_1570000013\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::PutOrCall{0}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::RedemptionDate{\"LOCALMKTDATE_1966397605\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::RepoCollateralSecurityType{\"STRING_2111619636\"}, Instrument_2);\n    FIX::RepurchaseRate RepurchaseRate_2;\n    RepurchaseRate_2.setString(\"27.990000\");\nset_field(noRelatedSym_0_2, RepurchaseRate_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::RepurchaseTerm{2116432487}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::RestructuringType{\"STRING_MR\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SecurityDesc{\"STRING_33608850\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SecurityExchange{\"EXCHANGE_346978203\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SecurityGroup{\"STRING_1925277044\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SecurityID{\"STRING_273339064\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SecurityIDSource{\"STRING_D\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SecurityStatus{\"STRING_2\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SecuritySubType{\"STRING_1915915340\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SecurityType{\"STRING_CB\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::Seniority{\"STRING_SD\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SettlMethod{'C'}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SettleOnOpenFlag{\"STRING_1367915769\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::StateOrProvinceOfIssue{\"STRING_1098011216\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::StrikeCurrency{\"CHF\"}, Instrument_2);\n    FIX::StrikeMultiplier StrikeMultiplier_2;\n    StrikeMultiplier_2.setString(\"15659975\");\nset_field(noRelatedSym_0_2, StrikeMultiplier_2, Instrument_2);\n    FIX::StrikePrice StrikePrice_2;\n    StrikePrice_2.setString(\"16577119\");\nset_field(noRelatedSym_0_2, StrikePrice_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::StrikePriceBoundaryMethod{1}, Instrument_2);\n    FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_2;\n    StrikePriceBoundaryPrecision_2.setString(\"8.460000\");\nset_field(noRelatedSym_0_2, StrikePriceBoundaryPrecision_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::StrikePriceDeterminationMethod{2}, Instrument_2);\n    FIX::StrikeValue StrikeValue_2;\n    StrikeValue_2.setString(\"13242472\");\nset_field(noRelatedSym_0_2, StrikeValue_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::Symbol{\"STRING_1618731362\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::SymbolSfx{\"STRING_WI\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::TimeUnit{\"STRING_Wk\"}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::UnderlyingPriceDeterminationMethod{3}, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::UnitOfMeasure{\"STRING_Bbl\"}, Instrument_2);\n    FIX::UnitOfMeasureQty UnitOfMeasureQty_2;\n    UnitOfMeasureQty_2.setString(\"6114147\");\nset_field(noRelatedSym_0_2, UnitOfMeasureQty_2, Instrument_2);\n    set_field(noRelatedSym_0_2, FIX::ValuationMethod{\"STRING_FUT\"}, Instrument_2);\n    all_values.push_back(Instrument_2);\n    all_compo_names.insert(\"...NoRelatedSym.\");\n\n    // ComplexEvents\n    // Group ComplexEvents.NoComplexEvents\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents noComplexEvents_2_1_0;\n      // ComplexEvents.NoComplexEvents\n      multiset<string> ComplexEvents_NoComplexEvents_4;\n      set_field(noComplexEvents_2_1_0, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_4);\n      FIX::ComplexEventPrice ComplexEventPrice_4;\n      ComplexEventPrice_4.setString(\"19062289\");\nset_field(noComplexEvents_2_1_0, ComplexEventPrice_4, ComplexEvents_NoComplexEvents_4);\n      set_field(noComplexEvents_2_1_0, FIX::ComplexEventPriceBoundaryMethod{3}, ComplexEvents_NoComplexEvents_4);\n      FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_4;\n      ComplexEventPriceBoundaryPrecision_4.setString(\"64.200000\");\nset_field(noComplexEvents_2_1_0, ComplexEventPriceBoundaryPrecision_4, ComplexEvents_NoComplexEvents_4);\n      set_field(noComplexEvents_2_1_0, FIX::ComplexEventPriceTimeType{1}, ComplexEvents_NoComplexEvents_4);\n      set_field(noComplexEvents_2_1_0, FIX::ComplexEventType{3}, ComplexEvents_NoComplexEvents_4);\n      FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_4;\n      ComplexOptPayoutAmount_4.setString(\"14514254\");\nset_field(noComplexEvents_2_1_0, ComplexOptPayoutAmount_4, ComplexEvents_NoComplexEvents_4);\n      all_values.push_back(ComplexEvents_NoComplexEvents_4);\n      all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents\");\n\n      // ComplexEventDates\n      // Group ComplexEventDates.NoComplexEventDates\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_2_0_2_0;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_9;\n        set_field(noComplexEventDates_2_0_2_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(9, 8, 21, 27, 10, 2009)}, ComplexEventDates_NoComplexEventDates_9);\n        set_field(noComplexEventDates_2_0_2_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(1, 51, 51, 8, 2, 2004)}, ComplexEventDates_NoComplexEventDates_9);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_9);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_0_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_24;\n          set_field(noComplexEventTimes_2_0_0_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(2, 4, 57)}, ComplexEventTimes_NoComplexEventTimes_24);\n          set_field(noComplexEventTimes_2_0_0_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(6, 21, 32)}, ComplexEventTimes_NoComplexEventTimes_24);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_24);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_2_0_2_0.addGroup(noComplexEventTimes_2_0_0_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_0_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_25;\n          set_field(noComplexEventTimes_2_0_0_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(0, 5, 48)}, ComplexEventTimes_NoComplexEventTimes_25);\n          set_field(noComplexEventTimes_2_0_0_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(1, 33, 29)}, ComplexEventTimes_NoComplexEventTimes_25);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_25);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_2_0_2_0.addGroup(noComplexEventTimes_2_0_0_3_1);\n        }\n        noComplexEvents_2_1_0.addGroup(noComplexEventDates_2_0_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_2_0_2_1;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_10;\n        set_field(noComplexEventDates_2_0_2_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(10, 29, 19, 9, 4, 2004)}, ComplexEventDates_NoComplexEventDates_10);\n        set_field(noComplexEventDates_2_0_2_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(20, 11, 45, 20, 1, 2014)}, ComplexEventDates_NoComplexEventDates_10);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_10);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_1_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_26;\n          set_field(noComplexEventTimes_2_0_1_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(20, 49, 33)}, ComplexEventTimes_NoComplexEventTimes_26);\n          set_field(noComplexEventTimes_2_0_1_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(20, 46, 29)}, ComplexEventTimes_NoComplexEventTimes_26);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_26);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_2_0_2_1.addGroup(noComplexEventTimes_2_0_1_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_1_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_27;\n          set_field(noComplexEventTimes_2_0_1_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(14, 26, 53)}, ComplexEventTimes_NoComplexEventTimes_27);\n          set_field(noComplexEventTimes_2_0_1_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(16, 18, 54)}, ComplexEventTimes_NoComplexEventTimes_27);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_27);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_2_0_2_1.addGroup(noComplexEventTimes_2_0_1_3_1);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_1_3_2;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_28;\n          set_field(noComplexEventTimes_2_0_1_3_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(20, 23, 56)}, ComplexEventTimes_NoComplexEventTimes_28);\n          set_field(noComplexEventTimes_2_0_1_3_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(18, 25, 7)}, ComplexEventTimes_NoComplexEventTimes_28);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_28);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_2_0_2_1.addGroup(noComplexEventTimes_2_0_1_3_2);\n        }\n        noComplexEvents_2_1_0.addGroup(noComplexEventDates_2_0_2_1);\n      }\n      noRelatedSym_0_2.addGroup(noComplexEvents_2_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents noComplexEvents_2_1_1;\n      // ComplexEvents.NoComplexEvents\n      multiset<string> ComplexEvents_NoComplexEvents_5;\n      set_field(noComplexEvents_2_1_1, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_5);\n      FIX::ComplexEventPrice ComplexEventPrice_5;\n      ComplexEventPrice_5.setString(\"12690686\");\nset_field(noComplexEvents_2_1_1, ComplexEventPrice_5, ComplexEvents_NoComplexEvents_5);\n      set_field(noComplexEvents_2_1_1, FIX::ComplexEventPriceBoundaryMethod{1}, ComplexEvents_NoComplexEvents_5);\n      FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_5;\n      ComplexEventPriceBoundaryPrecision_5.setString(\"53.980000\");\nset_field(noComplexEvents_2_1_1, ComplexEventPriceBoundaryPrecision_5, ComplexEvents_NoComplexEvents_5);\n      set_field(noComplexEvents_2_1_1, FIX::ComplexEventPriceTimeType{3}, ComplexEvents_NoComplexEvents_5);\n      set_field(noComplexEvents_2_1_1, FIX::ComplexEventType{9}, ComplexEvents_NoComplexEvents_5);\n      FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_5;\n      ComplexOptPayoutAmount_5.setString(\"5544155\");\nset_field(noComplexEvents_2_1_1, ComplexOptPayoutAmount_5, ComplexEvents_NoComplexEvents_5);\n      all_values.push_back(ComplexEvents_NoComplexEvents_5);\n      all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents\");\n\n      // ComplexEventDates\n      // Group ComplexEventDates.NoComplexEventDates\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates noComplexEventDates_2_1_2_0;\n        // ComplexEventDates.NoComplexEventDates\n        multiset<string> ComplexEventDates_NoComplexEventDates_11;\n        set_field(noComplexEventDates_2_1_2_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(5, 45, 20, 21, 12, 2005)}, ComplexEventDates_NoComplexEventDates_11);\n        set_field(noComplexEventDates_2_1_2_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(13, 8, 39, 14, 5, 2001)}, ComplexEventDates_NoComplexEventDates_11);\n        all_values.push_back(ComplexEventDates_NoComplexEventDates_11);\n        all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates\");\n\n        // ComplexEventTimes\n        // Group ComplexEventTimes.NoComplexEventTimes\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_1_0_3_0;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_29;\n          set_field(noComplexEventTimes_2_1_0_3_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(21, 59, 14)}, ComplexEventTimes_NoComplexEventTimes_29);\n          set_field(noComplexEventTimes_2_1_0_3_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(10, 31, 25)}, ComplexEventTimes_NoComplexEventTimes_29);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_29);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_2_1_2_0.addGroup(noComplexEventTimes_2_1_0_3_0);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_1_0_3_1;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_30;\n          set_field(noComplexEventTimes_2_1_0_3_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(7, 10, 15)}, ComplexEventTimes_NoComplexEventTimes_30);\n          set_field(noComplexEventTimes_2_1_0_3_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(13, 19, 41)}, ComplexEventTimes_NoComplexEventTimes_30);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_30);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_2_1_2_0.addGroup(noComplexEventTimes_2_1_0_3_1);\n        }\n        {\n          FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_1_0_3_2;\n          // ComplexEventTimes.NoComplexEventTimes\n          multiset<string> ComplexEventTimes_NoComplexEventTimes_31;\n          set_field(noComplexEventTimes_2_1_0_3_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(4, 18, 12)}, ComplexEventTimes_NoComplexEventTimes_31);\n          set_field(noComplexEventTimes_2_1_0_3_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(6, 46, 32)}, ComplexEventTimes_NoComplexEventTimes_31);\n          all_values.push_back(ComplexEventTimes_NoComplexEventTimes_31);\n          all_compo_names.insert(\"...NoRelatedSym....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n          noComplexEventDates_2_1_2_0.addGroup(noComplexEventTimes_2_1_0_3_2);\n        }\n        noComplexEvents_2_1_1.addGroup(noComplexEventDates_2_1_2_0);\n      }\n      noRelatedSym_0_2.addGroup(noComplexEvents_2_1_1);\n    }\n    // EvntGrp\n    // Group EvntGrp.NoEvents\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoEvents noEvents_2_1_0;\n      // EvntGrp.NoEvents\n      multiset<string> EvntGrp_NoEvents_5;\n      set_field(noEvents_2_1_0, FIX::EventDate{\"LOCALMKTDATE_528565486\"}, EvntGrp_NoEvents_5);\n      FIX::EventPx EventPx_5;\n      EventPx_5.setString(\"3584138\");\nset_field(noEvents_2_1_0, EventPx_5, EvntGrp_NoEvents_5);\n      set_field(noEvents_2_1_0, FIX::EventText{\"STRING_2139416817\"}, EvntGrp_NoEvents_5);\n      set_field(noEvents_2_1_0, FIX::EventTime{FIX::UTCTIMESTAMP(4, 33, 35, 5, 2, 2011)}, EvntGrp_NoEvents_5);\n      set_field(noEvents_2_1_0, FIX::EventType{99}, EvntGrp_NoEvents_5);\n      all_values.push_back(EvntGrp_NoEvents_5);\n      all_compo_names.insert(\"...NoRelatedSym....NoEvents\");\n\n      noRelatedSym_0_2.addGroup(noEvents_2_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoEvents noEvents_2_1_1;\n      // EvntGrp.NoEvents\n      multiset<string> EvntGrp_NoEvents_6;\n      set_field(noEvents_2_1_1, FIX::EventDate{\"LOCALMKTDATE_1186967891\"}, EvntGrp_NoEvents_6);\n      FIX::EventPx EventPx_6;\n      EventPx_6.setString(\"19842322\");\nset_field(noEvents_2_1_1, EventPx_6, EvntGrp_NoEvents_6);\n      set_field(noEvents_2_1_1, FIX::EventText{\"STRING_431708936\"}, EvntGrp_NoEvents_6);\n      set_field(noEvents_2_1_1, FIX::EventTime{FIX::UTCTIMESTAMP(12, 7, 22, 4, 9, 2009)}, EvntGrp_NoEvents_6);\n      set_field(noEvents_2_1_1, FIX::EventType{14}, EvntGrp_NoEvents_6);\n      all_values.push_back(EvntGrp_NoEvents_6);\n      all_compo_names.insert(\"...NoRelatedSym....NoEvents\");\n\n      noRelatedSym_0_2.addGroup(noEvents_2_1_1);\n    }\n    // InstrumentParties\n    // Group InstrumentParties.NoInstrumentParties\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties noInstrumentParties_2_1_0;\n      // InstrumentParties.NoInstrumentParties\n      multiset<string> InstrumentParties_NoInstrumentParties_3;\n      set_field(noInstrumentParties_2_1_0, FIX::InstrumentPartyID{\"STRING_177089190\"}, InstrumentParties_NoInstrumentParties_3);\n      set_field(noInstrumentParties_2_1_0, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_3);\n      set_field(noInstrumentParties_2_1_0, FIX::InstrumentPartyRole{1403101241}, InstrumentParties_NoInstrumentParties_3);\n      all_values.push_back(InstrumentParties_NoInstrumentParties_3);\n      all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties\");\n\n      // InstrumentPtysSubGrp\n      // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_0_2_0;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_5;\n        set_field(noInstrumentPartySubIDs_2_0_2_0, FIX::InstrumentPartySubID{\"STRING_41027526\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_5);\n        set_field(noInstrumentPartySubIDs_2_0_2_0, FIX::InstrumentPartySubIDType{99977779}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_5);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_5);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_2_1_0.addGroup(noInstrumentPartySubIDs_2_0_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_0_2_1;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_6;\n        set_field(noInstrumentPartySubIDs_2_0_2_1, FIX::InstrumentPartySubID{\"STRING_1933132368\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_6);\n        set_field(noInstrumentPartySubIDs_2_0_2_1, FIX::InstrumentPartySubIDType{1814601313}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_6);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_6);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_2_1_0.addGroup(noInstrumentPartySubIDs_2_0_2_1);\n      }\n      noRelatedSym_0_2.addGroup(noInstrumentParties_2_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties noInstrumentParties_2_1_1;\n      // InstrumentParties.NoInstrumentParties\n      multiset<string> InstrumentParties_NoInstrumentParties_4;\n      set_field(noInstrumentParties_2_1_1, FIX::InstrumentPartyID{\"STRING_628543265\"}, InstrumentParties_NoInstrumentParties_4);\n      set_field(noInstrumentParties_2_1_1, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_4);\n      set_field(noInstrumentParties_2_1_1, FIX::InstrumentPartyRole{1806534483}, InstrumentParties_NoInstrumentParties_4);\n      all_values.push_back(InstrumentParties_NoInstrumentParties_4);\n      all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties\");\n\n      // InstrumentPtysSubGrp\n      // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_2_0;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_7;\n        set_field(noInstrumentPartySubIDs_2_1_2_0, FIX::InstrumentPartySubID{\"STRING_855080495\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_7);\n        set_field(noInstrumentPartySubIDs_2_1_2_0, FIX::InstrumentPartySubIDType{1067746468}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_7);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_7);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_2_1_1.addGroup(noInstrumentPartySubIDs_2_1_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_2_1;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_8;\n        set_field(noInstrumentPartySubIDs_2_1_2_1, FIX::InstrumentPartySubID{\"STRING_2005151279\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_8);\n        set_field(noInstrumentPartySubIDs_2_1_2_1, FIX::InstrumentPartySubIDType{1990402128}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_8);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_8);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_2_1_1.addGroup(noInstrumentPartySubIDs_2_1_2_1);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_2_2;\n        // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n        multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_9;\n        set_field(noInstrumentPartySubIDs_2_1_2_2, FIX::InstrumentPartySubID{\"STRING_1540396013\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_9);\n        set_field(noInstrumentPartySubIDs_2_1_2_2, FIX::InstrumentPartySubIDType{1216230152}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_9);\n        all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_9);\n        all_compo_names.insert(\"...NoRelatedSym....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n        noInstrumentParties_2_1_1.addGroup(noInstrumentPartySubIDs_2_1_2_2);\n      }\n      noRelatedSym_0_2.addGroup(noInstrumentParties_2_1_1);\n    }\n    // SecAltIDGrp\n    // Group SecAltIDGrp.NoSecurityAltID\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoSecurityAltID noSecurityAltID_2_1_0;\n      // SecAltIDGrp.NoSecurityAltID\n      multiset<string> SecAltIDGrp_NoSecurityAltID_5;\n      set_field(noSecurityAltID_2_1_0, FIX::SecurityAltID{\"STRING_579880256\"}, SecAltIDGrp_NoSecurityAltID_5);\n      set_field(noSecurityAltID_2_1_0, FIX::SecurityAltIDSource{\"STRING_1052978797\"}, SecAltIDGrp_NoSecurityAltID_5);\n      all_values.push_back(SecAltIDGrp_NoSecurityAltID_5);\n      all_compo_names.insert(\"...NoRelatedSym....NoSecurityAltID\");\n\n      noRelatedSym_0_2.addGroup(noSecurityAltID_2_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoRelatedSym::NoSecurityAltID noSecurityAltID_2_1_1;\n      // SecAltIDGrp.NoSecurityAltID\n      multiset<string> SecAltIDGrp_NoSecurityAltID_6;\n      set_field(noSecurityAltID_2_1_1, FIX::SecurityAltID{\"STRING_56742727\"}, SecAltIDGrp_NoSecurityAltID_6);\n      set_field(noSecurityAltID_2_1_1, FIX::SecurityAltIDSource{\"STRING_1043426644\"}, SecAltIDGrp_NoSecurityAltID_6);\n      all_values.push_back(SecAltIDGrp_NoSecurityAltID_6);\n      all_compo_names.insert(\"...NoRelatedSym....NoSecurityAltID\");\n\n      noRelatedSym_0_2.addGroup(noSecurityAltID_2_1_1);\n    }\n    // SecurityXML\n    multiset<string> SecurityXML_4;\n    set_field(noRelatedSym_0_2, FIX::SecurityXML{\"XMLDATA_636982241\"}, SecurityXML_4);\n    set_field(noRelatedSym_0_2, FIX::SecurityXMLLen{1323484874}, SecurityXML_4);\n    set_field(noRelatedSym_0_2, FIX::SecurityXMLSchema{\"STRING_686563278\"}, SecurityXML_4);\n    all_values.push_back(SecurityXML_4);\n    all_compo_names.insert(\"...NoRelatedSym..\");\n\n    msg.addGroup(noRelatedSym_0_2);\n  }\n  // Parties\n  // Group Parties.NoPartyIDs\n  {\n    FIX50SP2::AdjustedPositionReport::NoPartyIDs noPartyIDs_0_0;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_0;\n    set_field(noPartyIDs_0_0, FIX::PartyID{\"STRING_1154413131\"}, Parties_NoPartyIDs_0);\n    set_field(noPartyIDs_0_0, FIX::PartyIDSource{'E'}, Parties_NoPartyIDs_0);\n    set_field(noPartyIDs_0_0, FIX::PartyRole{4}, Parties_NoPartyIDs_0);\n    all_values.push_back(Parties_NoPartyIDs_0);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::AdjustedPositionReport::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_0;\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubID{\"STRING_240794894\"}, PtysSubGrp_NoPartySubIDs_0);\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubIDType{24}, PtysSubGrp_NoPartySubIDs_0);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_0);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_1;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_1;\n      set_field(noPartySubIDs_0_1_1, FIX::PartySubID{\"STRING_86749913\"}, PtysSubGrp_NoPartySubIDs_1);\n      set_field(noPartySubIDs_0_1_1, FIX::PartySubIDType{10}, PtysSubGrp_NoPartySubIDs_1);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_1);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_1);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_2;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_2;\n      set_field(noPartySubIDs_0_1_2, FIX::PartySubID{\"STRING_1449801245\"}, PtysSubGrp_NoPartySubIDs_2);\n      set_field(noPartySubIDs_0_1_2, FIX::PartySubIDType{32}, PtysSubGrp_NoPartySubIDs_2);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_2);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_2);\n    }\n    msg.addGroup(noPartyIDs_0_0);\n  }\n  {\n    FIX50SP2::AdjustedPositionReport::NoPartyIDs noPartyIDs_0_1;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_1;\n    set_field(noPartyIDs_0_1, FIX::PartyID{\"STRING_904998730\"}, Parties_NoPartyIDs_1);\n    set_field(noPartyIDs_0_1, FIX::PartyIDSource{'I'}, Parties_NoPartyIDs_1);\n    set_field(noPartyIDs_0_1, FIX::PartyRole{56}, Parties_NoPartyIDs_1);\n    all_values.push_back(Parties_NoPartyIDs_1);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::AdjustedPositionReport::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_3;\n      set_field(noPartySubIDs_1_1_0, FIX::PartySubID{\"STRING_775969745\"}, PtysSubGrp_NoPartySubIDs_3);\n      set_field(noPartySubIDs_1_1_0, FIX::PartySubIDType{1}, PtysSubGrp_NoPartySubIDs_3);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_3);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_0);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_1;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_4;\n      set_field(noPartySubIDs_1_1_1, FIX::PartySubID{\"STRING_1904141788\"}, PtysSubGrp_NoPartySubIDs_4);\n      set_field(noPartySubIDs_1_1_1, FIX::PartySubIDType{11}, PtysSubGrp_NoPartySubIDs_4);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_4);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_1);\n    }\n    {\n      FIX50SP2::AdjustedPositionReport::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_2;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_5;\n      set_field(noPartySubIDs_1_1_2, FIX::PartySubID{\"STRING_1140134553\"}, PtysSubGrp_NoPartySubIDs_5);\n      set_field(noPartySubIDs_1_1_2, FIX::PartySubIDType{9}, PtysSubGrp_NoPartySubIDs_5);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_5);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_2);\n    }\n    msg.addGroup(noPartyIDs_0_1);\n  }\n  // PositionQty\n  // Group PositionQty.NoPositions\n  {\n    FIX50SP2::AdjustedPositionReport::NoPositions noPositions_0_0;\n    // PositionQty.NoPositions\n    multiset<string> PositionQty_NoPositions_0;\n    FIX::LongQty LongQty_0;\n    LongQty_0.setString(\"2088810\");\nset_field(noPositions_0_0, LongQty_0, PositionQty_NoPositions_0);\n    set_field(noPositions_0_0, FIX::PosQtyStatus{1}, PositionQty_NoPositions_0);\n    set_field(noPositions_0_0, FIX::PosType{\"STRING_AS\"}, PositionQty_NoPositions_0);\n    set_field(noPositions_0_0, FIX::QuantityDate{\"LOCALMKTDATE_1261859854\"}, PositionQty_NoPositions_0);\n    FIX::ShortQty ShortQty_0;\n    ShortQty_0.setString(\"14288367\");\nset_field(noPositions_0_0, ShortQty_0, PositionQty_NoPositions_0);\n    all_values.push_back(PositionQty_NoPositions_0);\n    all_compo_names.insert(\"...NoPositions\");\n\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::AdjustedPositionReport::NoPositions::NoNestedPartyIDs noNestedPartyIDs_0_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_0;\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyID{\"STRING_1898842095\"}, NestedParties_NoNestedPartyIDs_0);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyIDSource{'6'}, NestedParties_NoNestedPartyIDs_0);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyRole{1399015110}, NestedParties_NoNestedPartyIDs_0);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_0);\n      all_compo_names.insert(\"...NoPositions...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::AdjustedPositionReport::NoPositions::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_0;\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubID{\"STRING_1759251144\"}, NstdPtysSubGrp_NoNestedPartySubIDs_0);\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubIDType{1462720814}, NstdPtysSubGrp_NoNestedPartySubIDs_0);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_0);\n        all_compo_names.insert(\"...NoPositions...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoPositions::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_1;\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubID{\"STRING_199370388\"}, NstdPtysSubGrp_NoNestedPartySubIDs_1);\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubIDType{442899816}, NstdPtysSubGrp_NoNestedPartySubIDs_1);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_1);\n        all_compo_names.insert(\"...NoPositions...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoPositions::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_2;\n        set_field(noNestedPartySubIDs_0_0_2_2, FIX::NestedPartySubID{\"STRING_1703515708\"}, NstdPtysSubGrp_NoNestedPartySubIDs_2);\n        set_field(noNestedPartySubIDs_0_0_2_2, FIX::NestedPartySubIDType{1608144107}, NstdPtysSubGrp_NoNestedPartySubIDs_2);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_2);\n        all_compo_names.insert(\"...NoPositions...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_2);\n      }\n      noPositions_0_0.addGroup(noNestedPartyIDs_0_1_0);\n    }\n    msg.addGroup(noPositions_0_0);\n  }\n  {\n    FIX50SP2::AdjustedPositionReport::NoPositions noPositions_0_1;\n    // PositionQty.NoPositions\n    multiset<string> PositionQty_NoPositions_1;\n    FIX::LongQty LongQty_1;\n    LongQty_1.setString(\"5296497\");\nset_field(noPositions_0_1, LongQty_1, PositionQty_NoPositions_1);\n    set_field(noPositions_0_1, FIX::PosQtyStatus{2}, PositionQty_NoPositions_1);\n    set_field(noPositions_0_1, FIX::PosType{\"STRING_PNTN\"}, PositionQty_NoPositions_1);\n    set_field(noPositions_0_1, FIX::QuantityDate{\"LOCALMKTDATE_716377422\"}, PositionQty_NoPositions_1);\n    FIX::ShortQty ShortQty_1;\n    ShortQty_1.setString(\"15803808\");\nset_field(noPositions_0_1, ShortQty_1, PositionQty_NoPositions_1);\n    all_values.push_back(PositionQty_NoPositions_1);\n    all_compo_names.insert(\"...NoPositions\");\n\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::AdjustedPositionReport::NoPositions::NoNestedPartyIDs noNestedPartyIDs_1_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_1;\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyID{\"STRING_1531648381\"}, NestedParties_NoNestedPartyIDs_1);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyIDSource{'4'}, NestedParties_NoNestedPartyIDs_1);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyRole{655866712}, NestedParties_NoNestedPartyIDs_1);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_1);\n      all_compo_names.insert(\"...NoPositions...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::AdjustedPositionReport::NoPositions::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_3;\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubID{\"STRING_238616585\"}, NstdPtysSubGrp_NoNestedPartySubIDs_3);\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubIDType{352099278}, NstdPtysSubGrp_NoNestedPartySubIDs_3);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_3);\n        all_compo_names.insert(\"...NoPositions...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoPositions::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_4;\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubID{\"STRING_1806766208\"}, NstdPtysSubGrp_NoNestedPartySubIDs_4);\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubIDType{1985676853}, NstdPtysSubGrp_NoNestedPartySubIDs_4);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_4);\n        all_compo_names.insert(\"...NoPositions...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::AdjustedPositionReport::NoPositions::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_5;\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubID{\"STRING_1588727857\"}, NstdPtysSubGrp_NoNestedPartySubIDs_5);\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubIDType{2015647265}, NstdPtysSubGrp_NoNestedPartySubIDs_5);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_5);\n        all_compo_names.insert(\"...NoPositions...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_2);\n      }\n      noPositions_0_1.addGroup(noNestedPartyIDs_1_1_0);\n    }\n    msg.addGroup(noPositions_0_1);\n  }\n  // header\n  multiset<string> header_0;\n  set_header_field(msg.getHeader(), FIX::ApplVerID{\"STRING_4\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::BeginString{\"STRING_1257753045\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::BodyLength{1130023472}, header_0);\n  set_header_field(msg.getHeader(), FIX::CstmApplVerID{\"STRING_491640403\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::DeliverToCompID{\"STRING_1970204877\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{\"STRING_881381919\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::DeliverToSubID{\"STRING_1096478416\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{1221736340}, header_0);\n  set_header_field(msg.getHeader(), FIX::MessageEncoding{\"STRING_ISO-2022-JP\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::MsgSeqNum{708245912}, header_0);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{\"STRING_536973506\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{\"STRING_895915008\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{\"STRING_1151145728\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(3, 37, 37, 15, 1, 2006)}, header_0);\n  set_header_field(msg.getHeader(), FIX::PossDupFlag{true}, header_0);\n  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_0);\n  set_header_field(msg.getHeader(), FIX::SecureData{\"DATA_683243235\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::SecureDataLen{1802800850}, header_0);\n  set_header_field(msg.getHeader(), FIX::SenderCompID{\"STRING_300485620\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::SenderLocationID{\"STRING_921859821\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::SenderSubID{\"STRING_7416480\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(2, 37, 45, 3, 4, 2003)}, header_0);\n  set_header_field(msg.getHeader(), FIX::TargetCompID{\"STRING_314497046\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::TargetLocationID{\"STRING_529134964\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::TargetSubID{\"STRING_1839337189\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::XmlData{\"DATA_1410975462\"}, header_0);\n  set_header_field(msg.getHeader(), FIX::XmlDataLen{1750871304}, header_0);\n  all_values.push_back(header_0);\n  all_compo_names.insert(\".header\");\n\n\n  xml_element elt;\n  converter.fix2fixml(msg, elt);\n  BOOST_LOG_TRIVIAL(debug) << \"The resulting XML is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << elt.to_string() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n\n  BOOST_LOG_TRIVIAL(debug) << \"Quickfix XML representation is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << msg.toXML() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n  list<multiset<string>> elt_lists;\n  elt.to_list(elt_lists);\n  EXPECT_EQ(elt_lists.size(), all_values.size());\n\n  if (elt_lists.size() != all_values.size())  {\n    multiset<string> elt_compo_name;\n    elt.all_components(elt_compo_name);\n    BOOST_LOG_TRIVIAL(debug) << \"XML Elements are:\";\n    cout << \"\t[\";\n    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n    BOOST_LOG_TRIVIAL(debug) << \"FIX Components are:\"; \n    cout << \"\t[\";\n    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All FIX components\";\n  for (const auto& l : all_values) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All XML components\";\n  for (const auto& l : elt_lists) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n\n  }\n\n  for (const auto& xml_l : elt_lists) {\n    bool found = false;\n    for (const auto& l : all_values) {\n      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {\n        found = true;\n        break;\n      } // end if includes\n    } // end for all_values\n    EXPECT_TRUE(found);\n    if ( ! found) {\n      BOOST_LOG_TRIVIAL(debug) << \"[TO CHECK] This XML component was not found in FIX message\";\n      cout << \"\t ---> [\";\n      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, \" \"));      cout << \"]\" << endl << endl;\n    } // end if ! found\n  } // end for elt_lists\n}\n", "meta": {"hexsha": "69433a90a766052107d4a6a17459313a5502629e", "size": 115891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/generated/fix2xml/test_fix2xml_AdjustedPositionReport.cpp", "max_stars_repo_name": "abdelkaderamar/fix2xml", "max_stars_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T12:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T12:08:19.000Z", "max_issues_repo_path": "tools/generated/fix2xml/test_fix2xml_AdjustedPositionReport.cpp", "max_issues_repo_name": "abdelkaderamar/fix2xml", "max_issues_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_issues_repo_licenses": ["MIT"], "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/generated/fix2xml/test_fix2xml_AdjustedPositionReport.cpp", "max_forks_repo_name": "abdelkaderamar/fix2xml", "max_forks_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T04:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T04:11:44.000Z", "avg_line_length": 63.397702407, "max_line_length": 161, "alphanum_fraction": 0.7802935517, "num_tokens": 34069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.15605461522506692}}
{"text": "/*\n * LYPineappleAlgorithmDelegate.cpp\n *\n *  Created on: 2013-7-31\n *      Author: caiqingfeng\n */\n\n#include <boost/random.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/regex.hpp>\n\n#include \"poker/src/LYCardHelpers.h\"\n#include \"poker/src/LYDeck.h\"\n\n#include \"LYPineappleAlgorithmDelegate.h\"\n#include \"libmrock/common/src/my_log.h\"\n\nconst char* OpenEndedStraightFlushDraw =\n\"(Kc.*Qc.*Jc.*Tc)|\\\n(Qc.*Jc.*Tc.*9c)|\\\n(Jc.*Tc.*9c.*8c)|\\\n(Tc.*9c.*8c.*7c)|\\\n(9c.*8c.*7c.*6c)|\\\n(8c.*7c.*6c.*5c)|\\\n(7c.*6c.*5c.*4c)|\\\n(6c.*5c.*4c.*3c)|\\\n(5c.*4c.*3c.*2c)|\\\n(Kd.*Qd.*Jd.*Td)|\\\n(Qd.*Jd.*Td.*9d)|\\\n(Jd.*Td.*9d.*8d)|\\\n(Td.*9d.*8d.*7d)|\\\n(9d.*8d.*7d.*6d)|\\\n(8d.*7d.*6d.*5d)|\\\n(7d.*6d.*5d.*4d)|\\\n(6d.*5d.*4d.*3d)|\\\n(5d.*4d.*3d.*2d)|\\\n(Kh.*Qh.*Jh.*Th)|\\\n(Qh.*Jh.*Th.*9h)|\\\n(Jh.*Th.*9h.*8h)|\\\n(Th.*9h.*8h.*7h)|\\\n(9h.*8h.*7h.*6h)|\\\n(8h.*7h.*6h.*5h)|\\\n(7h.*6h.*5h.*4h)|\\\n(6h.*5h.*4h.*3h)|\\\n(5h.*4h.*3h.*2h)|\\\n(Ks.*Qs.*Js.*Ts)|\\\n(Qs.*Js.*Ts.*9s)|\\\n(Js.*Ts.*9s.*8s)|\\\n(Ts.*9s.*8s.*7s)|\\\n(9s.*8s.*7s.*6s)|\\\n(8s.*7s.*6s.*5s)|\\\n(7s.*6s.*5s.*4s)|\\\n(6s.*5s.*4s.*3s)|\\\n(5s.*4s.*3s.*2s)\" ;\n\nconst char* GushotStraightFlushDraw =\n\"(Ac.*Kc.*Qc.*Jc)|\\\n(Ac.*Kc.*Qc.*Tc)|\\\n(Ac.*Kc.*Jc.*Tc)|\\\n(Ac.*Qc.*Jc.*Tc)|\\\n(Kc.*Qc.*Jc.*9c)|\\\n(Kc.*Qc.*Tc.*9c)|\\\n(Kc.*Jc.*Tc.*9c)|\\\n(Qc.*Jc.*Tc.*8c)|\\\n(Qc.*Jc.*9c.*8c)|\\\n(Qc.*Tc.*9c.*8c)|\\\n(Jc.*Tc.*9c.*7c)|\\\n(Jc.*Tc.*8c.*7c)|\\\n(Jc.*9c.*8c.*7c)|\\\n(Tc.*9c.*8c.*6c)|\\\n(Tc.*9c.*7c.*6c)|\\\n(Tc.*8c.*7c.*6c)|\\\n(9c.*8c.*7c.*5c)|\\\n(9c.*8c.*6c.*5c)|\\\n(9c.*7c.*6c.*5c)|\\\n(8c.*7c.*6c.*4c)|\\\n(8c.*7c.*5c.*4c)|\\\n(8c.*6c.*5c.*4c)|\\\n(7c.*6c.*5c.*3c)|\\\n(7c.*6c.*4c.*3c)|\\\n(7c.*5c.*4c.*3c)|\\\n(6c.*5c.*4c.*2c)|\\\n(6c.*5c.*3c.*2c)|\\\n(6c.*4c.*3c.*2c)|\\\n(Ac.*5c.*4c.*3c)|\\\n(Ac.*5c.*4c.*2c)|\\\n(Ac.*5c.*3c.*2c)|\\\n(Ac.*4c.*3c.*2c)|\\\n(Ad.*Kd.*Qd.*Jd)|\\\n(Ad.*Kd.*Qd.*Td)|\\\n(Ad.*Kd.*Jd.*Td)|\\\n(Ad.*Qd.*Jd.*Td)|\\\n(Kd.*Qd.*Jd.*9d)|\\\n(Kd.*Qd.*Td.*9d)|\\\n(Kd.*Jd.*Td.*9d)|\\\n(Qd.*Jd.*Td.*8d)|\\\n(Qd.*Jd.*9d.*8d)|\\\n(Qd.*Td.*9d.*8d)|\\\n(Jd.*Td.*9d.*7d)|\\\n(Jd.*Td.*8d.*7d)|\\\n(Jd.*9d.*8d.*7d)|\\\n(Td.*9d.*8d.*6d)|\\\n(Td.*9d.*7d.*6d)|\\\n(Td.*8d.*7d.*6d)|\\\n(9d.*8d.*7d.*5d)|\\\n(9d.*8d.*6d.*5d)|\\\n(9d.*7d.*6d.*5d)|\\\n(8d.*7d.*6d.*4d)|\\\n(8d.*7d.*5d.*4d)|\\\n(8d.*6d.*5d.*4d)|\\\n(7d.*6d.*5d.*3d)|\\\n(7d.*6d.*4d.*3d)|\\\n(7d.*5d.*4d.*3d)|\\\n(6d.*5d.*4d.*2d)|\\\n(6d.*5d.*3d.*2d)|\\\n(6d.*4d.*3d.*2d)|\\\n(Ad.*5d.*4d.*3d)|\\\n(Ad.*5d.*4d.*2d)|\\\n(Ad.*5d.*3d.*2d)|\\\n(Ad.*4d.*3d.*2d)|\\\n(Ah.*Kh.*Qh.*Jh)|\\\n(Ah.*Kh.*Qh.*Th)|\\\n(Ah.*Kh.*Jh.*Th)|\\\n(Ah.*Qh.*Jh.*Th)|\\\n(Kh.*Qh.*Jh.*9h)|\\\n(Kh.*Qh.*Th.*9h)|\\\n(Kh.*Jh.*Th.*9h)|\\\n(Qh.*Jh.*Th.*8h)|\\\n(Qh.*Jh.*9h.*8h)|\\\n(Qh.*Th.*9h.*8h)|\\\n(Jh.*Th.*9h.*7h)|\\\n(Jh.*Th.*8h.*7h)|\\\n(Jh.*9h.*8h.*7h)|\\\n(Th.*9h.*8h.*6h)|\\\n(Th.*9h.*7h.*6h)|\\\n(Th.*8h.*7h.*6h)|\\\n(9h.*8h.*7h.*5h)|\\\n(9h.*8h.*6h.*5h)|\\\n(9h.*7h.*6h.*5h)|\\\n(8h.*7h.*6h.*4h)|\\\n(8h.*7h.*5h.*4h)|\\\n(8h.*6h.*5h.*4h)|\\\n(7h.*6h.*5h.*3h)|\\\n(7h.*6h.*4h.*3h)|\\\n(7h.*5h.*4h.*3h)|\\\n(6h.*5h.*4h.*2h)|\\\n(6h.*5h.*3h.*2h)|\\\n(6h.*4h.*3h.*2h)|\\\n(Ah.*5h.*4h.*3h)|\\\n(Ah.*5h.*4h.*2h)|\\\n(Ah.*5h.*3h.*2h)|\\\n(Ah.*4h.*3h.*2h)|\\\n(As.*Ks.*Qs.*Js)|\\\n(As.*Ks.*Qs.*Ts)|\\\n(As.*Ks.*Js.*Ts)|\\\n(As.*Qs.*Js.*Ts)|\\\n(Ks.*Qs.*Js.*9s)|\\\n(Ks.*Qs.*Ts.*9s)|\\\n(Ks.*Js.*Ts.*9s)|\\\n(Qs.*Js.*Ts.*8s)|\\\n(Qs.*Js.*9s.*8s)|\\\n(Qs.*Ts.*9s.*8s)|\\\n(Js.*Ts.*9s.*7s)|\\\n(Js.*Ts.*8s.*7s)|\\\n(Js.*9s.*8s.*7s)|\\\n(Ts.*9s.*8s.*6s)|\\\n(Ts.*9s.*7s.*6s)|\\\n(Ts.*8s.*7s.*6s)|\\\n(9s.*8s.*7s.*5s)|\\\n(9s.*8s.*6s.*5s)|\\\n(9s.*7s.*6s.*5s)|\\\n(8s.*7s.*6s.*4s)|\\\n(8s.*7s.*5s.*4s)|\\\n(8s.*6s.*5s.*4s)|\\\n(7s.*6s.*5s.*3s)|\\\n(7s.*6s.*4s.*3s)|\\\n(7s.*5s.*4s.*3s)|\\\n(6s.*5s.*4s.*2s)|\\\n(6s.*5s.*3s.*2s)|\\\n(6s.*4s.*3s.*2s)|\\\n(As.*5s.*4s.*3s)|\\\n(As.*5s.*4s.*2s)|\\\n(As.*5s.*3s.*2s)|\\\n(As.*4s.*3s.*2s)\";\n\nconst char* GushotAceToFiveStraightFlush =\n\"(Ac.*5c.*4c.*3c)|\\\n(Ac.*5c.*4c.*2c)|\\\n(Ac.*5c.*3c.*2c)|\\\n(Ac.*4c.*3c.*2c)|\\\n(Ad.*5d.*4d.*3d)|\\\n(Ad.*5d.*4d.*2d)|\\\n(Ad.*5d.*3d.*2d)|\\\n(Ad.*4d.*3d.*2d)|\\\n(Ah.*5h.*4h.*3h)|\\\n(Ah.*5h.*4h.*2h)|\\\n(Ah.*5h.*3h.*2h)|\\\n(Ah.*4h.*3h.*2h)|\\\n(As.*5s.*4s.*3s)|\\\n(As.*5s.*4s.*2s)|\\\n(As.*5s.*3s.*2s)|\\\n(As.*4s.*3s.*2s)\";\n\nconst char *ThreeOfAKindPtn =\n\"(A.{1}A.{1}A.{1})|\\\n(K.{1}K.{1}K.{1})|\\\n(Q.{1}Q.{1}Q.{1})|\\\n(J.{1}J.{1}J.{1})|\\\n(T.{1}T.{1}T.{1})|\\\n(9.{1}9.{1}9.{1})|\\\n(8.{1}8.{1}8.{1})|\\\n(7.{1}7.{1}7.{1})|\\\n(6.{1}6.{1}6.{1})|\\\n(5.{1}5.{1}5.{1})|\\\n(4.{1}4.{1}4.{1})|\\\n(3.{1}3.{1}3.{1})|\\\n(2.{1}2.{1}2.{1})\";\n\nconst char *OnePairPtn =\n\"(A.{1}A.{1})|\\\n(K.{1}K.{1})|\\\n(Q.{1}Q.{1})|\\\n(J.{1}J.{1})|\\\n(T.{1}T.{1})|\\\n(9.{1}9.{1})|\\\n(8.{1}8.{1})|\\\n(7.{1}7.{1})|\\\n(6.{1}6.{1})|\\\n(5.{1}5.{1})|\\\n(4.{1}4.{1})|\\\n(3.{1}3.{1})|\\\n(2.{1}2.{1})\";\n\nconst char* FlushDrawPtn =\n\"(.{1}c.*.{1}c.*.{1}c.*.{1}c)|\\\n(.{1}d.*.{1}d.*.{1}d.*.{1}d)|\\\n(.{1}h.*.{1}h.*.{1}h.*.{1}h)|\\\n(.{1}s.*.{1}s.*.{1}s.*.{1}s)\";\n\nconst char* OpenEndedStraightDrawPtn =\n\"(K.{1}.*Q.{1}.*J.{1}.*T.{1})|\\\n(Q.{1}.*J.{1}.*T.{1}.*9.{1})|\\\n(J.{1}.*T.{1}.*9.{1}.*8.{1})|\\\n(T.{1}.*9.{1}.*8.{1}.*7.{1})|\\\n(9.{1}.*8.{1}.*7.{1}.*6.{1})|\\\n(8.{1}.*7.{1}.*6.{1}.*5.{1})|\\\n(7.{1}.*6.{1}.*5.{1}.*4.{1})|\\\n(6.{1}.*5.{1}.*4.{1}.*3.{1})|\\\n(5.{1}.*4.{1}.*3.{1}.*2.{1})\"\n;\n\nconst char* GushotStraightDrawPtn =\n\"(A.{1}.*K.{1}.*Q.{1}.*J.{1})|\\\n(A.{1}.*K.{1}.*Q.{1}.*T.{1})|\\\n(A.{1}.*K.{1}.*J.{1}.*T.{1})|\\\n(A.{1}.*Q.{1}.*J.{1}.*T.{1})|\\\n(K.{1}.*Q.{1}.*J.{1}.*9.{1})|\\\n(K.{1}.*Q.{1}.*T.{1}.*9.{1})|\\\n(K.{1}.*J.{1}.*T.{1}.*9.{1})|\\\n(Q.{1}.*J.{1}.*T.{1}.*8.{1})|\\\n(Q.{1}.*J.{1}.*9.{1}.*8.{1})|\\\n(Q.{1}.*T.{1}.*9.{1}.*8.{1})|\\\n(J.{1}.*T.{1}.*9.{1}.*7.{1})|\\\n(J.{1}.*T.{1}.*8.{1}.*7.{1})|\\\n(J.{1}.*9.{1}.*8.{1}.*7.{1})|\\\n(T.{1}.*9.{1}.*8.{1}.*6.{1})|\\\n(T.{1}.*9.{1}.*7.{1}.*6.{1})|\\\n(T.{1}.*8.{1}.*7.{1}.*6.{1})|\\\n(9.{1}.*8.{1}.*7.{1}.*5.{1})|\\\n(9.{1}.*8.{1}.*6.{1}.*5.{1})|\\\n(9.{1}.*7.{1}.*6.{1}.*5.{1})|\\\n(8.{1}.*7.{1}.*6.{1}.*4.{1})|\\\n(8.{1}.*7.{1}.*5.{1}.*4.{1})|\\\n(8.{1}.*6.{1}.*5.{1}.*4.{1})|\\\n(7.{1}.*6.{1}.*5.{1}.*3.{1})|\\\n(7.{1}.*6.{1}.*4.{1}.*3.{1})|\\\n(7.{1}.*5.{1}.*4.{1}.*3.{1})|\\\n(6.{1}.*5.{1}.*4.{1}.*2.{1})|\\\n(6.{1}.*5.{1}.*3.{1}.*2.{1})|\\\n(6.{1}.*4.{1}.*3.{1}.*2.{1})|\\\n(A.{1}.*5.{1}.*4.{1}.*3.{1})|\\\n(A.{1}.*5.{1}.*4.{1}.*2.{1})|\\\n(A.{1}.*5.{1}.*3.{1}.*2.{1})|\\\n(A.{1}.*4.{1}.*3.{1}.*2.{1})\"\n;\n\nconst char* GushotAceToFiveStraightDrawPtn =\n\"(A.{1}.*5.{1}.*4.{1}.*3.{1})|\\\n(A.{1}.*5.{1}.*4.{1}.*2.{1})|\\\n(A.{1}.*5.{1}.*3.{1}.*2.{1})|\\\n(A.{1}.*4.{1}.*3.{1}.*2.{1})\"\n;\n\nLYPineappleAlgorithmDelegate::LYPineappleAlgorithmDelegate() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nLYPineappleAlgorithmDelegate::~LYPineappleAlgorithmDelegate() {\n\t// TODO Auto-generated destructor stub\n}\n\nstd::vector<LYCard> LYPineappleAlgorithmDelegate::initDeck()\n{\n\tstd::vector<LYCard> deck;\n\tdeck.push_back(smallGhost);\n\tdeck.push_back(cA);\n\tdeck.push_back(cK);\n\tdeck.push_back(cQ);\n\tdeck.push_back(cJ);\n\tdeck.push_back(cT);\n\tdeck.push_back(c9);\n\tdeck.push_back(c8);\n\tdeck.push_back(c7);\n\tdeck.push_back(c6);\n\tdeck.push_back(c5);\n\tdeck.push_back(c4);\n\tdeck.push_back(c3);\n\tdeck.push_back(c2);\n\tdeck.push_back(dA);\n\tdeck.push_back(dK);\n\tdeck.push_back(dQ);\n\tdeck.push_back(dJ);\n\tdeck.push_back(dT);\n\tdeck.push_back(d9);\n\tdeck.push_back(d8);\n\tdeck.push_back(d7);\n\tdeck.push_back(d6);\n\tdeck.push_back(d5);\n\tdeck.push_back(d4);\n\tdeck.push_back(d3);\n\tdeck.push_back(d2);\n\tdeck.push_back(hA);\n\tdeck.push_back(hK);\n\tdeck.push_back(hQ);\n\tdeck.push_back(hJ);\n\tdeck.push_back(hT);\n\tdeck.push_back(h9);\n\tdeck.push_back(h8);\n\tdeck.push_back(h7);\n\tdeck.push_back(h6);\n\tdeck.push_back(h5);\n\tdeck.push_back(h4);\n\tdeck.push_back(h3);\n\tdeck.push_back(h2);\n\tdeck.push_back(sA);\n\tdeck.push_back(sK);\n\tdeck.push_back(sQ);\n\tdeck.push_back(sJ);\n\tdeck.push_back(sT);\n\tdeck.push_back(s9);\n\tdeck.push_back(s8);\n\tdeck.push_back(s7);\n\tdeck.push_back(s6);\n\tdeck.push_back(s5);\n\tdeck.push_back(s4);\n\tdeck.push_back(s3);\n\tdeck.push_back(s2);\n\n\treturn deck;\n}\n\n/*\n * capHs: \u4e0d\u80fd\u8d85\u8fc7\u8fd9\u4e2a\u5f3a\u5ea6\uff0c\u4f8b\u5982\u5f53\u5e95\u9053\u662f\u4e24\u5bf9\u65f6\uff0c\u4e2d\u9053\u5c31\u4e0d\u80fd\u662f\u4e09\u6761\n */\nLYHandStrength * LYPineappleAlgorithmDelegate::isStraightFlush(LYHandStrength *hs, LYHandStrength* capHs)\n{\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isStraightFlush(hs);\n\n\tif (capHs && capHs->ranking != StraightFlush) return NULL;\n\tLYCard capTopRankCard = flipCard;\n\tif (capHs) capTopRankCard = capHs->topRankCard;\n\n\tstd::string cs = hs->genCardStringWithoutGhost();\n\n\t//\u9996\u5148\u5224\u65adOpenEndedStraightFlush\uff0c\u6bd4\u8f83\u590d\u6742\uff0c\u738b\u53ef\u4ee5\u5f53\u4e24\u5f20\u724c\n//\tstd::cout << OpenEndedStraightFlushDraw << std::endl;\n    boost::regex reg(OpenEndedStraightFlushDraw);\n    boost::sregex_token_iterator it(cs.begin(), cs.end(), reg, 0);\n    boost::sregex_token_iterator end;\n\n    for (; it != end; ++it) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n    \tstd::string strMatched = *it;\n        for (unsigned int i=0; i<strMatched.size()/2; i++) {\n            char f = strMatched[i*2];\n            char s = strMatched[i*2+1];\n            LYCard card(f, s);\n            hs->rank.push_back(card);\n            if (i == 0) {\n            \tLYCard ghostCard((enum LYFace)(card.face+1), card.suit);\n            \ths->rank.push_back(ghostCard);\n            }\n        }\n    \ths->ranking = StraightFlush;\n        hs->rankingString = StringifiedStraightFlush;\n        hs->topRankCard = hs->rank[0];\n    \tif (!capHs || hs->topRankCard > capTopRankCard) {\n        \tif (capHs && hs->rank[1].face > capTopRankCard.face) {\n        \t\ths->reset();\n        \t\treturn NULL;\n        \t}\n        \ths->topRankCard = hs->rank[1];\n        \tif (hs->rank[1].face > FIVE) {\n        \t\tLYCard ghostCard(hs->rank[1].face-4, hs->rank[1].suit);\n        \t\ths->rank[0] = ghostCard;\n        \t} else {\n        \t\tLYCard ghostCard(ACE, hs->rank[1].suit);\n        \t\ths->rank[0] = ghostCard;\n        \t}\n        \tLYCardHelpers::sortCardsByFace(hs->rank);\n        }\n    \treturn hs;\n    }\n\n    //\u5176\u6b21\u5224\u65adA\uff0d5\u7684Gushot\n//\tstd::cout << GushotAceToFiveStraightFlush << std::endl;\n    boost::regex reg2(GushotAceToFiveStraightFlush);\n    boost::sregex_token_iterator it2(cs.begin(), cs.end(), reg2, 0);\n\n    for (; it2 != end; ++it2) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n        std::string strMatched = *it2;\n//        std::cout << \"matched:\" << strMatched << std::endl;\n        char s = strMatched[1];\n        for (unsigned int i=0; i<4; i++) {\n        \tLYCard cd(strMatched[0], s);\n        \tcd.face = (enum LYFace)(TWO + i);\n        \ths->rank.push_back(cd);\n        }\n        LYCard aceCard(ACE, hs->rank[0].suit);\n        LYCard fiveCard(FIVE, hs->rank[0].suit);\n        hs->rank.push_back(aceCard);\n        LYCardHelpers::sortCardsByFace(hs->rank);\n        hs->rankingString = StringifiedStraightFlush;\n        hs->ranking = StraightFlush;\n        hs->topRankCard = fiveCard;\n        return hs;\n    }\n\n    //\u6700\u540e\u5224\u65ad\u5176\u5b83\u7684Gushot\n    boost::regex reg3(GushotStraightFlushDraw);\n    boost::sregex_token_iterator it3(cs.begin(), cs.end(), reg3, 0);\n\n    for (; it3 != end; ++it3) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n        std::string strMatched = *it3;\n//        std::cout << \"matched:\" << strMatched << std::endl;\n        char s = strMatched[1];\n        char f = strMatched[0];\n    \tLYCard topCard(f, s);\n//    \tstd::cout << \"topCard:\" << topCard.toString() << std::endl;\n        if (capHs && capTopRankCard.face < topCard.face) return NULL;\n        hs->rank.push_back(topCard);\n        for (unsigned int i=0; i<4; i++) {\n        \tLYCard cd(f, s);\n        \tcd.face = (enum LYFace)(topCard.face - i - 1);\n        \ths->rank.push_back(cd);\n//        \tstd::cout << cd.toString() << std::endl;\n        }\n        LYCardHelpers::sortCardsByFace(hs->rank);\n        hs->rankingString = StringifiedStraightFlush;\n        hs->ranking = StraightFlush;\n        hs->topRankCard = topCard;\n        return hs;\n    }\n\n    hs->reset();\n    return NULL;\n}\n\nLYHandStrength * LYPineappleAlgorithmDelegate::isFourOfAKind(LYHandStrength *hs, LYHandStrength* capHs)\n{\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isFourOfAKind(hs);\n\t//\u5176\u6b21\u5224\u65ad\u662f\u5426\u5df2\u7ecf\u5177\u5907\u56db\u6761\uff0c\u65e0\u8bba\u6709\u65e0Ghost\u90fd\u5df2\u7ecf\u662f\u56db\u6761\n\tLYHandStrength* orgHs = LYHoldemAlgorithmDelegate::isFourOfAKind(hs);\n\tif (orgHs != NULL) {\n\t\t//\u53ea\u9700\u8981\u8bbe\u7f6eKicker\n\t\tLYCard kicker = hs->topRankCard;\n\t\tif (kicker.face != ACE) {\n\t\t\tkicker.face = ACE;\n\t\t} else {\n\t\t\tkicker.face = KING;\n\t\t}\n\t\ths->kicker.push_back(kicker);\n\t\treturn orgHs;\n\t}\n\t//\u6b64\u5904\u4e0d\u80fd\u8c03!!!! 20141104\n//\ths->reset();\n\n    if (NULL != this->isStraightFlush(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fStraightFlush\n        return NULL;\n    }\n\n    if (hs->rank.size() > 0) { //have done checking it once.\n        if (hs->ranking == FourOfAKind) return hs;\n        return NULL;\n    }\n\n\tif (capHs && capHs->ranking != StraightFlush && capHs->ranking != FourOfAKind) return NULL;\n\tLYCard capTopRankCard = flipCard;\n\tif (capHs) capTopRankCard = capHs->topRankCard;\n\n    boost::regex reg(ThreeOfAKindPtn);\n    boost::cmatch matched;\n    boost::sregex_token_iterator it(hs->cardString.begin(), hs->cardString.end(), reg, 0);\n    boost::sregex_token_iterator end;\n\n    for (; it != end; ++it) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n        std::string strMatched = *it;\n//        std::cout << \"matched:\" << strMatched << std::endl;\n        LYCard topRankCard(strMatched[0], strMatched[1]);\n        if (capHs && capHs->ranking == FourOfAKind && topRankCard.face > capTopRankCard.face) return NULL;\n//        std::cout << \"hahaah:\" << strMatched << std::endl;\n        topRankCard.suit = Spades;\n        hs->rank.push_back(topRankCard);\n        hs->topRankCard = topRankCard;\n        topRankCard.suit = Hearts;\n        hs->rank.push_back(topRankCard);\n        topRankCard.suit = Diamonds;\n        hs->rank.push_back(topRankCard);\n        topRankCard.suit = Clubs;\n        hs->rank.push_back(topRankCard);\n\n        hs->ranking = FourOfAKind;\n        hs->rankingString = StringifiedFourOfAKind;\n\n        //\u627e\u51faKicker\n        std::vector<LYCard>::iterator it = hs->cards.begin();\n        for (; it!=hs->cards.end(); it++) {\n        \tLYCard cd = *it;\n        \tif (!cd.isGhost() && !hs->rankHasThisCard(cd)) {\n        \t\ths->kicker.push_back(cd);\n        \t\tbreak; //\u56e0\u4e3akicker\u53ea\u53ef\u80fd\u6709\u4e00\u4e2a\uff0c\u6240\u4ee5\u53d6\u6700\u5927\u7684\u4e00\u4e2a\u5373\u53ef\uff01\n        \t}\n        }\n        return hs;\n    }\n\n    return NULL;\n}\n\nLYHandStrength * LYPineappleAlgorithmDelegate::isFullHouse(LYHandStrength *hs, LYHandStrength* capHs)\n{\n//LY_LOG_DBG(\"enter fullhouse\");\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isFullHouse(hs);\n\n\tif (this->isFourOfAKind(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fFourOfAKind\n        return NULL;\n    }\n\n    if (hs->rank.size() > 0) { //have done checking it once.\n        if (hs->ranking == FullHouse) return hs;\n        return NULL;\n    }\n\n\tif (capHs && capHs->ranking != StraightFlush && capHs->ranking != FourOfAKind &&\n\t\t\tcapHs->ranking != FullHouse) return NULL;\n\tLYCard capTopRankCard = flipCard;\n\tif (capHs) capTopRankCard = capHs->topRankCard;\n\n    //\u9996\u5148\u6765\u5224\u65ad\u662f\u5426\u6709\u4e09\u6761\n\tboost::regex reg(ThreeOfAKindPtn);\n    boost::sregex_token_iterator it(hs->cardString.begin(), hs->cardString.end(), reg, 0);\n    boost::sregex_token_iterator end;\n\n    for (; it != end; ++it) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n    \t//\u8bf4\u660e\u6709\u4e09\u6761\uff0c\u4f46\u5df2\u7ecf\u6392\u9664\u662f\u56db\u6761\n        std::string strMatched = *it;\n        LYCard topRankCard(strMatched[0], strMatched[1]);\n        if (capHs && capHs->ranking == FullHouse && topRankCard.face > capTopRankCard.face) return NULL;\n\n        for (unsigned int i=0; i<hs->cardString.size()/2; i++) {\n            char f = hs->cardString[i*2];\n            char s = hs->cardString[i*2+1];\n            LYCard card(f, s);\n            if (!card.isGhost() && !hs->rankHasThisCard(card) && hs->rank.size() < 5) {\n            \ths->rank.push_back(card);\n            \tif (card.face != topRankCard.face) {\n            \t\tLYCard ghostCard(card.face, Spades);\n            \t\ths->rank.push_back(ghostCard);\n            \t}\n            }\n        }\n        hs->ranking = FullHouse;\n        hs->rankingString = StringifiedFullHouse;\n        hs->topRankCard = topRankCard;\n        return hs;\n    }\n\n    //\u5176\u6b21\u5224\u65ad\u662f\u5426\u6709\u4e24\u5bf9\n    if (!LYHoldemAlgorithmDelegate::isTwoPair(hs)) return NULL;\n//    LY_LOG_DBG(\"two pairs:\" << hs->cardString);\n    //\u6b64\u65f6hs\u5df2\u7ecf\u8bbe\u7f6e\u6210two pairs\n    LYCard topPairCard = hs->rank[0];\n    LYCard secondPairCard = hs->rank[2];\n    if (capHs && capHs->ranking == FullHouse && secondPairCard.face > capTopRankCard.face) return NULL; //\u6700\u5c0f\u7684\u5bf9\u4e5f\u6bd4Cap\u7684\u4e09\u6761\u5927\uff0c\u81ea\u7136\u4e0d\u53ef\u80fd\u662fFullHouse\n\ths->kicker.clear();\n\ths->ranking = FullHouse;\n    hs->rankingString = StringifiedFullHouse;\n    if (!capHs || //\u5728\u5e95\u9053\n    \t\tcapHs->ranking != FullHouse || //\u5982\u679c\u4e0d\u662fFullHouse\uff0c\u80af\u5b9a\u6bd4FullHouse\u5927\n    \t\ttopPairCard.face < capTopRankCard.face) {\n    \ths->rank.push_back(topPairCard);\n    } else {\n    \ths->rank.push_back(secondPairCard);\n    }\n    LYCardHelpers::sortCardsByFace(hs->rank);\n    return hs;\n}\n\nLYHandStrength * LYPineappleAlgorithmDelegate::isFlush(LYHandStrength *hs, LYHandStrength* capHs)\n{\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isFlush(hs);\n\n\tif (this->isStraightFlush(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fStraightFlush\n        return NULL;\n    }\n\n    if (hs->rank.size() > 0) { //have done checking it once.\n        if (hs->ranking == Flush) return hs;\n        hs->reset();\n        return NULL;\n    }\n\n\tif (capHs && capHs->ranking != StraightFlush && capHs->ranking != FourOfAKind &&\n\t\t\tcapHs->ranking != FullHouse && capHs->ranking != Flush) return NULL;\n\tLYCard capTopRankCard = flipCard;\n\tif (capHs) capTopRankCard = capHs->topRankCard;\n\n    boost::regex reg(FlushDrawPtn);\n    boost::sregex_token_iterator it(hs->cardString.begin(), hs->cardString.end(), reg, 0);\n    boost::sregex_token_iterator end;\n\n    for (; it != end; ++it) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n        std::string strMatched = *it;\n        char suitSymbol = strMatched[1];\n//        std::cout << strMatched << std::endl;\n        for (unsigned int i=0; i<strMatched.size()/2; i++) {\n            char f = strMatched[i*2];\n            char s = strMatched[i*2+1];\n            LYCard card(f, s);\n            if (!hs->rankHasThisCard(card) && s == suitSymbol && hs->rank.size()<4) {\n            \ths->rank.push_back(card);\n            }\n        }\n    \tLYHoldemAlgorithmDelegate had;\n        if (!capHs || capHs->ranking != Flush) {\n        \t//\u6b64\u65f6\u8981\u4e48capHs\u4e3aNull\uff0c\u8981\u4e48capHs\u5927\u4e8eFlush\n        \t//\u4e0d\u80fd\u7b80\u5355\u7684\u8ba9Ghost\uff1dA\uff0c\u56e0\u4e3a\u9700\u8981\u6392\u9664\u4e00\u79cd\u53ef\u80fd\u6027\uff0c\u672c\u9053\uff1dA Hight Flush\uff0c\u53ef\u80fd\u5df2\u7ecf\u6709\u4e00\u4e2aA\u4e86\uff0c\u6b64\u65f6\u6709\u4e24\u4e2aA\uff0c\u5bfc\u81f4\u8ddf\u5bf9\u624b\u7684AK Flush\u76f8\u6bd4\u65f6\u6bd4\u522b\u4eba\u5927\n            for (int face=ACE; face>=TWO; face--) {\n            \tLYCard ghostCard((enum LYFace)face, LYCard::char2suit(suitSymbol));\n            \tif (hs->rankHasThisCard(ghostCard)) continue;\n            \tstd::vector<LYCard> cds = hs->rank;\n            \tcds.push_back(ghostCard);\n            \tLYHandStrength tmpHs(cds, &had);\n            \tif (tmpHs.ranking != Flush) continue; //\u9700\u8981\u6392\u9664\u662fStraightFlush\n\n            \ths->rank.push_back(ghostCard);\n            \ths->ranking = Flush;\n            \ths->rankingString = StringifiedFlush;\n            \tLYCardHelpers::sortCardsByFace(hs->rank);\n            \ths->topRankCard = hs->rank[0];\n            \treturn hs;\n            }\n        }\n        for (int face=ACE; face>=TWO; face--) {\n        \tLYCard ghostCard((enum LYFace)face, LYCard::char2suit(suitSymbol));\n        \tif (hs->rankHasThisCard(ghostCard)) continue;\n        \tstd::vector<LYCard> cds = hs->rank;\n//        \tstd::cout << \"ghost:\" << ghostCard.toString() << std::endl;\n        \tcds.push_back(ghostCard);\n        \tLYHandStrength tmpHs(cds, &had);\n        \tif (tmpHs.ranking != Flush) continue;\n        \tif ((capHs && !(tmpHs > *capHs)) ||\n        \t\t\t!capHs) {\n            \ths->rank.push_back(ghostCard);\n            \ths->ranking = Flush;\n            \ths->rankingString = StringifiedFlush;\n            \ths->topRankCard = tmpHs.topRankCard;\n            \treturn hs;\n        \t}\n        }\n        hs->reset();\n        return NULL;\n    }\n    hs->reset();\n    return NULL;\n}\n\nLYHandStrength * LYPineappleAlgorithmDelegate::isStraight(LYHandStrength *hs, LYHandStrength* capHs)\n{\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isStraight(hs);\n\n    if (NULL != this->isStraightFlush(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fStraightFlush\n        return NULL;\n    }\n\n    if (NULL != this->isFlush(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fFlush\n        return NULL;\n    }\n\n    if (hs->rank.size() > 0) {\n//    \tstd::cout << \"kkkkk\" << std::endl;\n        if (hs->ranking == Straight) return hs;\n        return NULL;\n    }\n\n    if (capHs && capHs->ranking != StraightFlush && capHs->ranking != FourOfAKind &&\n\t\t\tcapHs->ranking != FullHouse && capHs->ranking != Flush && capHs->ranking != Straight) return NULL;\n\tLYCard capTopRankCard = flipCard;\n\tif (capHs) capTopRankCard = capHs->topRankCard;\n\n\tstd::string gushot_ptn(GushotStraightDrawPtn);\n\tstd::string ptn(OpenEndedStraightDrawPtn);\n\tptn = ptn + \"|\" + gushot_ptn;\n    boost::regex reg(ptn.c_str());\n    boost::sregex_token_iterator it(hs->cardString.begin(), hs->cardString.end(), reg, 0);\n    boost::sregex_token_iterator end;\n\n    for (; it != end; ++it) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n        std::string strMatched = *it;\n//    \tstd::cout << strMatched << std::endl;\n        for (unsigned int i=0; i<strMatched.size()/2; i++) {\n            char f = strMatched[i*2];\n            char s = strMatched[i*2+1];\n            LYCard card(f, s);\n            if (!hs->rankHasThisFace(card) && hs->rank.size()<4) {\n            \ths->rank.push_back(card);\n            }\n        }\n    }\n\n    //\u7136\u540e\u5224\u65ad\u662f\u5426A\uff0d5\u7684GushotStraight\uff0c\u6b64\u65f6A\u548c5\u80af\u5b9a\u5df2\u7ecf\u5728hs->rank\u4e2d\n    boost::regex reg2(GushotAceToFiveStraightDrawPtn);\n    boost::sregex_token_iterator it2(hs->cardString.begin(), hs->cardString.end(), reg2, 0);\n\n    for (; it2 != end; ++it2) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n        std::string strMatched = *it2;\n//        std::cout << strMatched << std::endl;\n    \t//\u56e0\u4e3a\u662f\u6700\u5c0f\u7684\u987a\u5b50\uff0c\u6240\u4ee5\u80af\u5b9a\u6210\u7acb\n    \tfor (unsigned int s=Spades; s>=Clubs; s--) {\n    \t\tif (s == hs->rank[0].suit) continue;\n    \t\t//\u4efb\u610f\u53d6\u4e00\u4e2a\u975e\u540c\u82b1\u8272\u76842\uff0d4\u5373\u53ef\uff0c\u4fdd\u8bc1\u4e0d\u662f\u540c\u82b1\n    \t\tfor (unsigned int f=FIVE; f>=TWO; f--) {\n    \t\t\tLYCard cd((enum LYFace)f, (enum LYSuit)s);\n    \t\t\tif (hs->rankHasThisFace(cd)) continue;\n    \t\t\ths->rank.push_back(cd);\n    \t\t\ths->ranking = Straight;\n            \ths->rankingString = StringifiedStraight;\n            \tLYCardHelpers::sortCardsByFace(hs->rank);\n            \ths->topRankCard = hs->rank[1];\n            \treturn hs;\n    \t\t}\n    \t}\n    }\n\n    //\u5176\u6b21\u5224\u65ad\u662f\u5426\u5176\u5b83\u7684GushotStraight\uff0c\u6b64\u65f6\u5934\u548c\u5c3e\u80af\u5b9a\u5df2\u7ecf\u5728hs->rank\u4e2d\n    boost::regex reg3(GushotStraightDrawPtn);\n    boost::sregex_token_iterator it3(hs->cardString.begin(), hs->cardString.end(), reg3, 0);\n\n    for (; it3 != end; ++it3) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n    \t//\u9700\u8981\u5224\u65ad\u6b64\u65f6\u7684\u987a\u5b50\u662f\u5426\u6bd4capHs\u5927\n        std::string strMatched = *it3;\n//    \tstd::cout << strMatched << std::endl;\n    \tif (capHs && capHs->ranking == Straight && hs->rank[0].face > capTopRankCard.face) {\n    \t\treturn NULL;\n    \t}\n\n    \tfor (unsigned int s=Spades; s>=Clubs; s--) {\n    \t\tif (s == hs->rank[0].suit) continue;\n    \t\t//\u4efb\u610f\u53d6\u4e00\u4e2a\u975e\u540c\u82b1\u8272\u7684\u724c\u5373\u53ef\uff0c\u4fdd\u8bc1\u4e0d\u662f\u540c\u82b1\n    \t\tfor (unsigned int f=(unsigned int)(hs->rank[0].face)-1; f>=hs->rank[3].face; f--) {\n    \t\t\tLYCard cd((LYFace)f, (LYSuit)s);\n    \t\t\tif (hs->rankHasThisFace(cd)) continue;\n    \t\t\ths->rank.push_back(cd);\n    \t\t\ths->ranking = Straight;\n            \ths->rankingString = StringifiedStraight;\n            \tLYCardHelpers::sortCardsByFace(hs->rank);\n            \ths->topRankCard = hs->rank[0];\n            \treturn hs;\n    \t\t}\n    \t}\n    }\n\n    //\u6700\u540e\u5224\u65ad\u662f\u5426OpenEndedStraight\n    boost::regex reg4(OpenEndedStraightDrawPtn);\n    boost::sregex_token_iterator it4(hs->cardString.begin(), hs->cardString.end(), reg4, 0);\n\n    for (; it4 != end; ++it4) { //\u53ea\u53d6\u7b2c\u4e00\u4e2a\n//    \tstd::cout << \"here!\" << capTopRankCard.face << std::endl;\n    \t//\u9700\u8981\u5224\u65ad\u6b64\u65f6\u7684\u987a\u5b50\u662f\u5426\u6bd4capHs\u5927\n    \tLYFace f = (LYFace)(hs->rank[0].face+1);\n    \tif (capHs && capHs->ranking == Straight && f >= capTopRankCard.face) {\n    \t\tf = (LYFace)(hs->rank[3].face - 1);\n    \t}\n    \tfor (unsigned int s=Spades; s>=Clubs; s--) {\n    \t\tif (s == hs->rank[0].suit) continue;\n    \t\tLYCard cd((LYFace)f, (LYSuit)s);\n    \t\ths->rank.push_back(cd);\n    \t\ths->ranking = Straight;\n    \t\ths->rankingString = StringifiedStraight;\n    \t\tLYCardHelpers::sortCardsByFace(hs->rank);\n    \t\ths->topRankCard = hs->rank[0];\n    \t\tif (hs->topRankCard.face == ACE && hs->rank[1].face == FIVE) hs->topRankCard = hs->rank[1];\n        \tif (!capHs ||\n        \t\t\t(capHs->ranking != Straight ||\n        \t\t\t\t\ths->topRankCard.face <= capTopRankCard.face)) {\n            \treturn hs;\n        \t}\n        \ths->reset();\n        \treturn NULL;\n    \t}\n    }\n    return NULL;\n}\n\n/*\n * \u4ee5\u4e0a\u9664\u4e86FourOfAKind\uff0c\u5176\u5b83\u7684\u90fd\u662f\u9700\u8981\u4e94\u5f20\u724c\u624d\u80fd\u6210\n * \u4ee5\u4e0b\u4e09\u5f20\u3001\u4e8c\u5f20\u3001\u62161\u5f20\u90fd\u53ef\u4ee5\u6210\u724c\n */\nLYHandStrength * LYPineappleAlgorithmDelegate::isThreeOfAKind(LYHandStrength *hs, LYHandStrength* capHs)\n{\n//\tstd::cout << \"3t\" << std::endl;\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isThreeOfAKind(hs);\n    if (NULL != this->isStraightFlush(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fStraightFlush\n        return NULL;\n    }\n    if (NULL != this->isFourOfAKind(hs, capHs)) { //not four of a kind\n    \treturn NULL;\n    }\n    if (NULL != this->isFlush(hs, capHs)) { //\u6392\u9664\u662fFlush\n        return NULL;\n    }\n    if (NULL != this->isStraight(hs, capHs)) { //\u6392\u9664\u662fStraight\n        return NULL;\n    }\n\n\t//\u5982\u679c\u5df2\u7ecf\u662f\u4e09\u6761\u4e86\u81ea\u7136\u5fc5\u987b\u5f97\u8fd4\u56de\u4e09\u6761\u4e86\n\tif (LYHoldemAlgorithmDelegate::isThreeOfAKind(hs)) {\n//\t\tstd::cout << \"kkkk\" << std::endl;\n\t\t//\u8bbe\u7f6e\u4e00\u4e0bGhost\u5373\u53ef\n\t\tunsigned int kicker_face = 0;\n\t\tunsigned int kicker_suit = 0;\n\t\tfor (unsigned int i=0; i<2; i++) {\n\t\t\tif (!hs->kicker[i].isGhost()) {\n\t\t\t\tkicker_face = hs->kicker[i].face;\n\t\t\t\tkicker_suit = hs->kicker[i].suit;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tLYCard k((LYFace)kicker_face, (LYSuit)kicker_suit);\n\t\tunsigned int f = ACE;\n\t\tfor (; f>=TWO; f--) {\n\t\t\tif (!LYCardHelpers::hasThisFace(hs->cards, (LYFace)f)) break;\n\t\t}\n\t\ths->kicker.clear();\n\t\ths->kicker.push_back(k);\n\t\tLYCard ghostCard((LYFace)f, Spades);\n//\t\tstd::cout << ghostCard.toString() << std::endl;\n\t\ths->kicker.push_back(ghostCard);\n//\t\tLYCardHelpers::sortCardsByFace(hs->rank);\n\t\tLYCardHelpers::sortCardsByFace(hs->kicker);\n\t\treturn hs;\n\t}\n\ths->reset();\n\t//\u5982\u679c\u662f\u4e24\u5bf9\uff0c\u5c31\u4e0d\u53ef\u80fd\u662f\u4e09\u6761\n\tif (LYHoldemAlgorithmDelegate::isTwoPair(hs)) return NULL;\n\ths->reset();\n\t//\u5982\u679c\u4e00\u5bf9\u90fd\u6ca1\u6709\uff0c\u5f53\u7136\u4e0d\u53ef\u80fd\u662f\u4e09\u6761\n\tif (!LYHoldemAlgorithmDelegate::isOnePair(hs)) return NULL;\n\n\tif (capHs && capHs->ranking != StraightFlush && capHs->ranking != FourOfAKind &&\n\t\t\tcapHs->ranking != FullHouse && capHs->ranking != Flush && capHs->ranking != Straight\n\t\t\t&& capHs->ranking != ThreeOfAKind) return NULL;\n\n\tif (capHs && capHs->ranking == ThreeOfAKind && capHs->topRankCard.face < hs->topRankCard.face) {\n\t\ths->reset();\n\t\treturn NULL;\n\t}\n\n\tfor (unsigned int s=Spades; s>=Clubs; s--) {\n\t\tLYCard ghostCard(hs->topRankCard.face, (LYSuit)s);\n\t\tif (!hs->rankHasThisCard(ghostCard)) {\n\t\t\ths->rank.push_back(ghostCard);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::vector<LYCard>::iterator cit = hs->kicker.begin();\n\tfor (; cit!=hs->kicker.end(); cit++) {\n\t\tif ((*cit).isGhost()) {\n\t\t\ths->kicker.erase(cit);\n\t\t\tbreak;\n\t\t}\n\t}\n\ths->ranking = ThreeOfAKind;\n\ths->rankingString = StringifiedThreeOfAKind;\n\tLYCardHelpers::sortCardsByFace(hs->rank);\n\tLYCardHelpers::sortCardsByFace(hs->kicker);\n\treturn hs;\n}\n\nLYHandStrength * LYPineappleAlgorithmDelegate::isTwoPair(LYHandStrength *hs, LYHandStrength* capHs)\n{\n//\tstd::cout << \"2p\" << std::endl;\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isTwoPair(hs);\n\n    if (NULL != this->isStraightFlush(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fStraightFlush\n        return NULL;\n    }\n    if (NULL != this->isFourOfAKind(hs, capHs)) { //not four of a kind\n    \treturn NULL;\n    }\n    if (NULL != this->isFlush(hs, capHs)) { //\u6392\u9664\u662fFlush\n        return NULL;\n    }\n    if (NULL != this->isStraight(hs, capHs)) { //\u6392\u9664\u662fStraight\n        return NULL;\n    }\n    if (NULL != this->isThreeOfAKind(hs, capHs)) { //\u6392\u9664\u662fThreeOfAKind\n        return NULL;\n    }\n\n\t//\u5982\u679c\u5df2\u7ecf\u662f2P\u4e86\u81ea\u7136\u5fc5\u987b\u5f97\u8fd4\u56de2P\u4e86\n\tif (LYHoldemAlgorithmDelegate::isTwoPair(hs)) {\n\t\t//\u8bbe\u7f6e\u4e00\u4e0bGhost\u5373\u53ef\n\t\t//\u6709\u975e\u5e38\u5c0f\u7684\u6982\u7387\u662f\u5e95\u4e0b\u4e24\u5bf9\u548c\u4e2d\u95f4\u4e24\u5bf9\u5b8c\u5168\u4e00\u6837\uff0c\u53ea\u662fKicker\u4e0d\u540c\uff0c\u57fa\u672c\u65e0\u9700\u8003\u8651\u8fd9\u79cd\u60c5\u51b5\uff01\uff01\uff01\uff01\n\t\t//\u53cd\u4eba\u7c7b\u7684\u6446\u6cd5\u624d\u53ef\u80fd\u51fa\u73b0\n\t\tfor (unsigned int f=ACE; f>=TWO; f--) {\n\t\t\tLYCard ghostCard((LYFace)f, Spades);\n\t\t\tif (!hs->rankHasThisFace(ghostCard)) {\n\t\t\t\ths->kicker.clear();\n\t\t\t\ths->kicker.push_back(ghostCard);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn hs;\n\t}\n\ths->reset();\n\t//\u5982\u679c\u4e00\u5bf9\u90fd\u6ca1\u6709\uff0c\u5f53\u7136\u4e0d\u53ef\u80fd\u662f\u4e24\u5bf9\n\tif (!LYHoldemAlgorithmDelegate::isOnePair(hs)) return NULL;\n\n\tLYHoldemAlgorithmDelegate had;\n\tstd::vector<LYCard> newCards = hs->rank;\n    for (unsigned int i=0; i<hs->kicker.size(); i++) {\n    \tif (hs->kicker[i].isGhost()) continue;\n    \tnewCards.push_back(hs->kicker[i]);\n    }\n//\tstd::cout << newCards.size() << std::endl;\n\n    for (unsigned int i=0; i<hs->kicker.size(); i++) {\n    \tif (hs->kicker[i].isGhost()) continue;\n    \tunsigned int s = hs->kicker[i].suit;\n    \tif (s == Spades) {\n    \t\ts = Hearts;\n    \t} else {\n    \t\ts = Spades;\n    \t}\n    \tLYCard ghostCard(hs->kicker[i].face, (LYSuit)s);\n//    \tstd::cout << \"ghost=\" << ghostCard.toString() << std::endl;\n    \tnewCards.push_back(ghostCard);\n    \tLYHandStrength tmpHs(newCards, &had);\n    \tif (tmpHs.ranking != TwoPair) {\n    \t\ths->reset();\n    \t\treturn NULL;\n    \t}\n    \tif (!capHs ||\n    \t\t\t!(tmpHs > *capHs)) {\n        \ths->rank = tmpHs.rank;\n        \ths->kicker = tmpHs.kicker;\n        \ths->ranking = TwoPair;\n        \ths->rankingString = StringifiedTwoPairs;\n        \ths->topRankCard = tmpHs.topRankCard;\n        \treturn hs;\n    \t}\n    \tnewCards.pop_back();\n    }\n\n    hs->reset();\n    return NULL;\n}\n\nLYHandStrength * LYPineappleAlgorithmDelegate::isOnePair(LYHandStrength *hs, LYHandStrength* capHs)\n{\n//\tstd::cout << \"onep\" << std::endl;\n\tLYHoldemAlgorithmDelegate had;\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isOnePair(hs);\n    if (NULL != this->isStraight(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fTwoPair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n\n    if (NULL != this->isTwoPair(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fTwoPair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n\n\tstd::vector<LYCard> cards = hs->cards;\n\tstd::vector<LYCard>::iterator it = cards.begin();\n\tfor (; it!=cards.end(); it++) {\n\t\tif ((*it).isGhost()) {\n\t\t\tcards.erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n\t//\u5982\u679c\u5df2\u7ecf\u662f1P\u4e86\u81ea\u7136\u5fc5\u987b\u5f97\u8fd4\u56de1P\u4e86\n\tif (LYHoldemAlgorithmDelegate::isOnePair(hs)) {\n\t\t//\u8bbe\u7f6e\u4e00\u4e0bGhost\u5373\u53ef\n\t\tfor (unsigned int f=ACE; f>=TWO; f--) {\n\t\t\tLYCard ghostCard((LYFace)f, Spades);\n\t\t\tif (!hs->rankHasThisFace(ghostCard)) {\n\t\t\t\tcards.push_back(ghostCard);\n\t\t    \tLYHandStrength tmpHs(cards, &had);\n\t\t    \tif (tmpHs.ranking != OnePair) {\n\t\t    \t\tcards.pop_back();\n\t\t    \t\ths->reset();\n\t\t    \t\tcontinue;\n\t\t    \t}\n\t\t    \tif (!capHs ||\n\t\t    \t\t\t!(tmpHs > *capHs)) {\n\t\t        \ths->rank = tmpHs.rank;\n\t\t        \ths->kicker = tmpHs.kicker;\n\t\t        \ths->ranking = OnePair;\n\t\t        \ths->rankingString = StringifiedOnePair;\n\t\t        \ths->topRankCard = tmpHs.topRankCard;\n\t\t        \treturn hs;\n\t\t    \t}\n\n\t\t    \tcards.pop_back();\n\t\t    \ths->reset();\n\t\t\t}\n\t\t}\n\t\treturn hs;\n\t}\n\ths->reset();\n//\tstd::cout << \"kkkk\" << std::endl;\n\n    for (unsigned int i=0; i<hs->cards.size(); i++) {\n    \tif (hs->cards[i].isGhost()) continue;\n    \tunsigned int s = hs->cards[i].suit;\n    \tif (s == Spades) {\n    \t\ts = Hearts;\n    \t} else {\n    \t\ts = Spades;\n    \t}\n    \tLYCard ghostCard(hs->cards[i].face, (LYSuit)s);\n    \tcards.push_back(ghostCard);\n//    \tstd::cout << \"ghost:\" << ghostCard.toString() << std::endl;\n    \tLYHandStrength tmpHs(cards, &had);\n    \tif (tmpHs.ranking != OnePair) return NULL;\n    \tif (!capHs ||\n    \t\t\t!(tmpHs > *capHs)){\n        \ths->rank = tmpHs.rank;\n        \ths->kicker = tmpHs.kicker;\n        \ths->ranking = OnePair;\n        \ths->rankingString = StringifiedOnePair;\n        \ths->topRankCard = tmpHs.topRankCard;\n        \treturn hs;\n    \t}\n    \tcards.pop_back();\n    }\n\n    return NULL;\n}\n\nLYHandStrength * LYPineappleAlgorithmDelegate::isHighCard(LYHandStrength *hs, LYHandStrength* capHs)\n{\n//LY_LOG_DBG(\"isHighCard?\" << hs->cardString);\n\tif (!hs->hasGhost()) return LYHoldemAlgorithmDelegate::isHighCard(hs);\n    if (NULL != this->isStraightFlush(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fTwoPair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n\n    if (NULL != this->isFourOfAKind(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fTwoPair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n\n    if (NULL != this->isFullHouse(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fTwoPair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n\n    if (NULL != this->isFlush(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fTwoPair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n\n    if (NULL != this->isStraight(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fTwoPair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n\n    if (NULL != this->isThreeOfAKind(hs, capHs)) { //\u6392\u9664\u662fThreeOfAKind\n        return NULL;\n    }\n\n    if (NULL != this->isTwoPair(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fOnePair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n\n    if (NULL != this->isOnePair(hs, capHs)) { //\u9996\u5148\u6392\u9664\u662fOnePair\u4ee5\u4e0a\u724c\u529b\n        return NULL;\n    }\n//std::cout << \"high card!!!\" << std::endl;\n\tstd::vector<LYCard> cards = hs->cards;\n\tstd::vector<LYCard>::iterator it = cards.begin();\n\tfor (; it!=cards.end(); it++) {\n\t\tif ((*it).isGhost()) {\n\t\t\tcards.erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tLYCardHelpers::sortCardsByFace(cards);\n    enum LYFace f = cards[0].face;\n    enum LYSuit s = cards[0].suit;\n    if (s == Spades) {\n    \ts = Hearts;\n    } else {\n    \ts = Spades;\n    }\n\tLYHoldemAlgorithmDelegate had;\n\tenum LYFace min_face = ACE;\n    for (unsigned int i=ACE; i>=TWO; i--) {\n    \tLYCard cd((LYFace)i, s);\n//    \tstd::cout << cd.toString() << std::endl;\n    \tif (LYCardHelpers::hasThisFace(cards, cd)) continue;\n    \tmin_face = (LYFace)i;\n    \tcards.push_back(cd);\n    \tLYHandStrength tmpHs(cards, &had);\n    \tif (tmpHs.ranking != HighCard) return NULL;\n    \tif ((capHs && !(tmpHs > *capHs)) ||\n    \t\t\t!capHs) {\n        \ths->rank = tmpHs.rank;\n        \ths->kicker = tmpHs.kicker;\n        \ths->ranking = HighCard;\n        \ths->rankingString = StringifiedOnePair;\n        \ths->topRankCard = tmpHs.topRankCard;\n        \treturn hs;\n    \t}\n    \tcards.pop_back();\n    }\n    //\u6700\u540e\u5373\u4f7f\u4e0d\u6bd4Cap\u5927\uff0c\u4e5f\u5f97\u662f\u4e00\u4e2aHighCard\uff0c\u6700\u5c0f\u7684\u4e00\u4e2aHighCard\n    hs->reset();\n    LYCard cd(min_face, s);\n\tcards.push_back(cd);\n\tLYHandStrength tmpHs(cards, &had);\n\n\ths->rank = tmpHs.rank;\n\ths->kicker = tmpHs.kicker;\n\ths->ranking = HighCard;\n\ths->rankingString = StringifiedOnePair;\n\ths->topRankCard = tmpHs.topRankCard;\n    return hs;\n}\n\n", "meta": {"hexsha": "c1eb4a5544183f8906b3f319ced4595aa2bbbe7f", "size": 32954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pineapple/src/LYPineappleAlgorithmDelegate.cpp", "max_stars_repo_name": "caiqingfeng/libpoker", "max_stars_repo_head_hexsha": "a2c60884fc5c8e31455fb39e432c49e0df55956b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-20T06:22:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T06:22:30.000Z", "max_issues_repo_path": "pineapple/src/LYPineappleAlgorithmDelegate.cpp", "max_issues_repo_name": "caiqingfeng/libpoker", "max_issues_repo_head_hexsha": "a2c60884fc5c8e31455fb39e432c49e0df55956b", "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": "pineapple/src/LYPineappleAlgorithmDelegate.cpp", "max_forks_repo_name": "caiqingfeng/libpoker", "max_forks_repo_head_hexsha": "a2c60884fc5c8e31455fb39e432c49e0df55956b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-29T08:21:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T06:40:18.000Z", "avg_line_length": 28.6556521739, "max_line_length": 135, "alphanum_fraction": 0.5682163015, "num_tokens": 12658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.2720245628973633, "lm_q1q2_score": 0.15605461406546}}
{"text": "//  Copyright John Maddock 2012.\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#include <cstddef> // See https://gcc.gnu.org/gcc-4.9/porting_to.html\n#include <mpfr.h>\n#include <boost/config.hpp>\n\n#ifdef __GNUC__\n#pragma message \"MPFR_VERSION_STRING=\" MPFR_VERSION_STRING\n#endif\n\n#if (__GNU_MP_VERSION < 4) || ((__GNU_MP_VERSION == 4) && (__GNU_MP_VERSION_MINOR < 2))\n#error \"Incompatible GMP version\"\n#endif\n\n#if (MPFR_VERSION < 3)\n#error \"Incompatible MPFR version\"\n#endif\n\n#ifdef __GNUC__\n#pragma message \"__GNU_MP_VERSION=\" BOOST_STRINGIZE(__GNU_MP_VERSION)\n#pragma message \"__GNU_MP_VERSION_MINOR=\" BOOST_STRINGIZE(__GNU_MP_VERSION_MINOR)\n#endif\n\n#if (__GNU_MP_VERSION < 4) || ((__GNU_MP_VERSION == 4) && (__GNU_MP_VERSION_MINOR < 2))\n#error \"Incompatible GMP version\"\n#endif\n\nint main()\n{\n   void* (*alloc_func_ptr)(size_t);\n   void* (*realloc_func_ptr)(void*, size_t, size_t);\n   void (*free_func_ptr)(void*, size_t);\n\n   mp_get_memory_functions(&alloc_func_ptr, &realloc_func_ptr, &free_func_ptr);\n\n   mpfr_buildopt_tls_p();\n\n   mpfr_t t;\n   mpfr_init2(t, 128);\n   if (t[0]._mpfr_d)\n      mpfr_clear(t);\n\n   return 0;\n}\n", "meta": {"hexsha": "c82f28d7d521d0e7ae96390237dfec0af3d2da52", "size": 1273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/config/has_mpfr.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "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": "libs/multiprecision/config/has_mpfr.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "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": "libs/multiprecision/config/has_mpfr.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "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": 26.5208333333, "max_line_length": 87, "alphanum_fraction": 0.7297721917, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.15603110133523684}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SCALAR_ASIN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SCALAR_ASIN_HPP_INCLUDED\n\n#include <boost/simd/function/definition/asin.hpp>\n#include <boost/simd/arch/common/scalar/function/asin.hpp>\n\n#endif\n", "meta": {"hexsha": "ee2982e194d1a4732af8ea633c18b3ddc5eff44d", "size": 609, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/scalar/asin.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/scalar/asin.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/scalar/asin.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.8235294118, "max_line_length": 100, "alphanum_fraction": 0.5369458128, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.297469948832931, "lm_q1q2_score": 0.1557018244162032}}
{"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_FUNCTION_DETAIL_SLIDE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DETAIL_SLIDE_HPP_INCLUDED\n\n#include <boost/simd/config.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/detail/nsm.hpp>\n\nnamespace boost { namespace simd { namespace detail\n{\n  namespace tt = nsm::type_traits;\n\n  template<typename T,int N, int Card, bool isFwd> struct slider;\n\n  // We add a small trampoline so MSVC is happy with the cardinal_of call\n  template<typename T,int N, typename Card, bool isFwd>\n  struct slider_ : slider<T,N,Card::value,isFwd>\n  {};\n\n  // General case dispatch to arch-specific implementation\n  template<typename T,int N, int Card, bool isFwd> struct slider\n  {\n    static BOOST_FORCEINLINE auto call(T const& a0, T const& a1)\n    BOOST_NOEXCEPT_DECLTYPE_BODY(detail::slide(a0,a1,tt::integral_constant<int, N>{}));\n\n    static BOOST_FORCEINLINE auto call(T const& a0)\n    BOOST_NOEXCEPT_DECLTYPE_BODY(detail::slide(a0,tt::integral_constant<int, N>{}));\n  };\n\n  // Backward slide slides the swapped inputs by the complement of the offset except for\n  // unary case which may be optimized by the architecture except for slide<-Card>\n  template<typename T,int N, int Card> struct slider<T,N,Card,false>\n  {\n    //static BOOST_FORCEINLINE auto call(T const& a0, T const& a1)\n    //BOOST_NOEXCEPT_DECLTYPE_BODY(detail::slide(a1,a0,tt::integral_constant<int, Card+N>{}));\n\n    static BOOST_FORCEINLINE auto call(T const& a0, tt::false_type const&)\n    BOOST_NOEXCEPT_DECLTYPE_BODY(detail::slide(a0,tt::integral_constant<int, N>{}));\n\n    static BOOST_FORCEINLINE T call(T const&, tt::true_type const&)\n    { return Zero<T>(); }\n\n    static BOOST_FORCEINLINE auto call(T const& a0)\n    BOOST_NOEXCEPT_DECLTYPE_BODY( call(a0, nsm::bool_<(N==-Card)>{}) );\n\n    static BOOST_FORCEINLINE auto call(T const& a0, T const& a1, tt::false_type const&)\n    BOOST_NOEXCEPT_DECLTYPE_BODY(detail::slide(a1, a0, tt::integral_constant<int, Card+N>{}));\n\n    static BOOST_FORCEINLINE T call(T const&, T const& a1, tt::true_type const&)\n    { return a1; }\n\n    static BOOST_FORCEINLINE auto call(T const& a0, T const& a1)\n    BOOST_NOEXCEPT_DECLTYPE_BODY(call(a0, a1, nsm::bool_<(N == -Card)>{}));\n  };\n\n  // Scalar-like value returns a0 in backward mode\n  template<typename T,int N> struct slider<T,N,1,false>\n  {\n    static BOOST_FORCEINLINE T call(T const&, T const& a1)  BOOST_NOEXCEPT { return a1;        }\n    static BOOST_FORCEINLINE T call(T const&)               BOOST_NOEXCEPT { return Zero<T>(); }\n  };\n\n  // Sliding by 0 is identity\n  template<typename T, int Card> struct slider<T,0,Card,true>\n  {\n    static BOOST_FORCEINLINE T call(T const& a0, T const&)  BOOST_NOEXCEPT  { return a0; }\n    static BOOST_FORCEINLINE T call(T const& a0)            BOOST_NOEXCEPT  { return a0; }\n  };\n\n  // Sliding by cardinal is the 2nd parameter (or zero if lack thereof)\n  template<int N,typename T> struct slider<T, N, N, true>\n  {\n    static BOOST_FORCEINLINE T call(T const&, T const& a1)  BOOST_NOEXCEPT  { return a1;        }\n    static BOOST_FORCEINLINE T call(T const& )              BOOST_NOEXCEPT  { return Zero<T>(); }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "6353167353ee36f5e6ae1362d98d5d802c58d731", "size": 3536, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/detail/slide.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/detail/slide.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/detail/slide.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": 41.1162790698, "max_line_length": 100, "alphanum_fraction": 0.6662895928, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.15558317360244908}}
{"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#ifndef SNPTEST_REGRESSION_LOG_POSTERIOR_DENSITY_HPP\n#define SNPTEST_REGRESSION_LOG_POSTERIOR_DENSITY_HPP\n\n#include <vector>\n#include <memory>\n#include <boost/noncopyable.hpp>\n#include \"Eigen/Core\"\n#include \"metro/regression/Design.hpp\"\n\n#include \"metro/regression/LogLikelihood.hpp\"\n\nnamespace metro {\n\tnamespace regression {\n\t\t/*\n\t\t*\n\t\t* DEPRECATED: use LogUnnormalisedPosterior instead\n\t\t*\n\t\t* Base class for classes implementing regression log posterior densities\n\t\t* These are prior / log-likelihood combinations that can unpack the contribution from likelihood and prior\n\t\t*/\n\t\tstruct LogPosteriorDensity: public LogLikelihood\n\t\t{\n\t\t\ttypedef std::auto_ptr< LogPosteriorDensity > UniquePtr ;\n\t\t\tvirtual Vector get_prior_mode() const = 0 ;\n\t\t\tvirtual Matrix get_loglikelihood_second_derivative() const = 0 ;\n\t\t} ;\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "55fe68ae59bc6aa0a6cee8c9b3e35e5da7bff2c4", "size": 1047, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/regression/LogPosteriorDensity.hpp", "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/include/metro/regression/LogPosteriorDensity.hpp", "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/include/metro/regression/LogPosteriorDensity.hpp", "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": 28.2972972973, "max_line_length": 108, "alphanum_fraction": 0.7545367717, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.2658804672827599, "lm_q1q2_score": 0.15556696828723723}}
{"text": "/*! \\file demo_2d_values.cpp\n    \\brief Demonstration of marking data-point values and uncertainty information in 2D plots.\n    \\details Contains Quickbook Markup to be included in documentation.\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A Bristow 2008, 2021\n\n// demo_2d_values.cpp\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// An example to demonstrate marking data-point values with uncertainty information\n// like uncertainty (nominally standard deviation),\n// degrees of freedom (nominally observations - 1),\n// and/or computed confidence limits (confidence intervals).\n\n// See also demo_2d_plot.cpp for a wider range of use.\n// See demo_2d_uncertainty.cpp to show confidence intervals as ellipse around the data_points.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_2d_values_1\n\n/*`As always, we need a few includes to use Boost.Plot\n*/\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n  //using namespace boost::svg;\n  //using boost::svg::svg_2d_plot;\n\n#include <iostream>\n  //using std::cout;\n  //using std::endl;\n  //using std::dec;\n  //using std::hex;\n\n#include <map>\n//  using std::map;\n\n//] [demo_2d_values_1]\n\nint main()\n{\n\n  using namespace boost::svg;\n\n//[demo_2d_values_2\n/*`Some fictional data is pushed into an STL container, here std::map:*/\n\n  try\n  { // try'n'catch blocks are needed to ensure error messages from any exceptions are shown.\n\n/*`This example uses a single map to demonstrate autoscaling. We create a map to hold our first data-series using type double.\n*/\n    std::map<double, double> my_data;\n    /*`\n    Inserting some fictional values also sorts the data.\n    The index value in [ ] is the x value.\n    */\n    my_data[1.1] = 3.2;  // X = 1.1 and Y = 3.2.\n    my_data[7.3] = 8.1; // \n    my_data[-2.12] = -2.4394;\n    my_data[5.47] = 5.3861;\n\n    using boost::svg::svg_2d_plot;  // This is needed to construct, setup and output the 2D plot in SVG format.\n\n    svg_2d_plot my_2d_plot; // Construct a plot with all the default constructor values.\n\n    my_2d_plot.title(\"Demo 2d Values\") // Add a string title of the plot.\n      .x_range(-5, 10) // Add a range for the X-axis.\n      .x_label(\"length (m)\"); // Add a label for the X-axis.\n\n/*`Add the one data-point series, `my_data` and a description, and how the data-points are to be marked,\nhere a circle with a diameter of 5 pixels.\n*/\n    my_2d_plot.plot(my_data, \"2d Values\").shape(circlet).size(5).line_on(false);\n\n/*`To put a value-label against each data_point, switch on the option:\n*/\n    //my_2d_plot.x_values_on(true); // Add a label for the X-axis.\n    //my_2d_plot.y_values_on(true); // Add a label for the X-axis.\n    my_2d_plot.xy_values_on(true); // Add a label for both the X and Y-axis.\n\n/*`If the default size and color are not to your taste, set more options, like:\n*/\n    my_2d_plot.x_values_font_size(16) // Change font size for the X-axis value-labels.\n      .x_values_font_family(\"Times New Roman\") // Change font for the X-axis value-labels.\n      .x_values_color(red); // Change X values color from default black to red.\n\n    my_2d_plot.y_values_font_size(14) // Change font size for the Y-axis value-labels.\n      .y_values_font_family(\"Arial\") // Change font for the Y-axis value-labels.\n      .y_values_color(blue); // Change Y color from default black to blue.\n\n/*`The format of the values may also not be ideal,\nso we can use the normal `iostream precision` and `ioflags` to change,\nhere to reduce the number of digits used from default precision 6 down to a more readable 2,\nreducing the risk of collisions between adjacent values.\n(Obviously the most suitable precision depends on the range of the data_points.\nIf values are very close to each other, a higher precision will be needed to differentiate them).\nFor measurement of typical precision, 2 or 3 decimal places will suffice.\n*/\n    my_2d_plot.x_values_precision(3); // Typical precision (3) for the X-axis value-label.\n    my_2d_plot.y_values_precision(5); // Higher precision (5) for the Y-axis value-label.\n\n/*`We can also prescribe the use of scientific, fixed format and/or force a positive sign:\n*/\n   //my_2d_plot.x_values_ioflags(std::ios::scientific | std::ios::showpos);\n   //my_2d_plot.x_values_ioflags(std::ios::scientific);\n   //my_2d_plot.y_values_ioflags(std::ios::fixed);\n\n/*`By default, any unnecessary spacing-wasting zeros in the exponent field are removed.\nStripping \"e+000\" may appear to mean that the normal effect of `scientific` is not working.\n(If, probably perversely, the full 1.123456e+012 format is required,\nthe stripping can be switched off with:\n  `my_2d_plot.x_labels_strip_e0s(false);` )\n\nIn general, sticking to the default `ioflags` usually produces the neatest presentation of values.\n\nThe uncertainty information about the values can also be shown, \nbut none is available for our demonstration values, so would show just implicit zero degrees of freedom.\n\n*/\n    //my_2d_plot.x_plusminus_on(true); // Uncertainty label for the X-axis value-label.\n    //my_2d_plot.x_df_on(true); // Degrees of freedom label for the X-axis value-label.\n\n    //my_2d_plot.y_plusminus_on(true); // Uncertainty label for the Y-axis value-label.\n    //my_2d_plot.y_df_on(true); // Degrees of freedom label for the Y-axis value-label.  \n\n/*`The default value-label is horizontal, centered above the data_point marker,\nbut, depending on the type and density of data_points, and the length of the values\n(controlled in turn by choice of options, the `precision` and `ioflags` in use),\nit is often clearer to use a different orientation.\nThis can be controlled in steps using an 'enum rotate_style` for convenience (or in degrees).\n\n* `leftward` - writing level with the data_point but to its left.\n* `rightward` - writing level with the data-point but to its right.\n* `uphill` - writing up at 45 degree slope is often a good choice,\n* `upward` - writing vertically up and\n* `backup` - writing to the left are also useful.\n\n(For 1-D plots other directions are less attractive,\nplacing the values below the horizontal Y-axis line,\nbut for 2-D plots all writing orientations can be useful).\n*/\n    //my_2d_plot.x_values_rotation(rightward); // Orientation for the Y-axis value-labels.\n    //my_2d_plot.x_values_rotation(horizontal); // Orientation for the X-axis value-labels.\n    //my_2d_plot.x_values_rotation(uphill); // Orientation for the X-axis value-labels.\n    my_2d_plot.y_values_rotation(downhill); // Orientation for the Y-axis value-labels.\n    //my_2d_plot.x_values_rotation(leftward); // Orientation for the X-axis value-labels.\n    //my_2d_plot.y_values_rotation(rightward); // Orientation for the Y-axis value-labels.\n\n   // my_2d_plot.x_plusminus_on(true); // Show Uncertainty for X-axis value-labels.\n   // my_2d_plot.x_df_on(true); // Show Degrees of freedom (n-1) for X-axis value-labels.\n    //my_2d_plot.y_plusminus_on(true); // Uncertainty for X-axis value-labels.\n\n/*`To use all these settings, finally write the SVG plot to file.\n*/\n    my_2d_plot.write(\"demo_2d_values.svg\");\n\n/*`If chosen settings do not have the expected effect, is may be helpful to display them.\n\n(All settings can be displayed with `show_2d_plot_settings(my_2d_plot)`.)\n*/\n    //std::cout << \"my_2d_plot.x_values_font_size() \" << my_2d_plot.x_values_font_size() << std::endl;\n    //std::cout << \"my_2d_plot.x_values_font_family() \" << my_2d_plot.x_values_font_family() << std::endl;\n    //std::cout << \"my_2d_plot.x_values_color() \" << my_2d_plot.x_values_color() << std::endl;\n    //std::cout << \"my_2d_plot.x_values_precision() \" << my_2d_plot.x_values_precision() << std::endl;\n    //std::cout << \"my_2d_plot.x_values_ioflags() \" << std::hex << my_2d_plot.x_values_ioflags() << std::dec << std::endl;\n\n    //std::cout << \"my_2d_plot.y_values_font_size() \" << my_2d_plot.y_values_font_size() << std::endl;\n    //std::cout << \"my_2d_plot.y_values_font_family() \" << my_2d_plot.y_values_font_family() << std::endl;\n    //std::cout << \"my_2d_plot.y_values_color() \" << my_2d_plot.y_values_color() << std::endl;\n    //std::cout << \"my_2d_plot.y_values_precision() \" << my_2d_plot.y_values_precision() << std::endl;\n    //std::cout << \" my_2d_plot.y_values_ioflags() \" << std::hex << my_2d_plot.y_values_ioflags() << std::dec << std::endl;\n//] [demo_2d_values_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\n//[demo_2d_values_output\n\nOutput:\n\ndemo_2d_values.cpp\nLinking...\nEmbedding manifest...\nAutorun \"j:\\Cpp\\SVG\\debug\\demo_2d_values.exe\"\nmy_2d_plot.x_values_font_size() 16\nmy_2d_plot.x_values_font_family() Times New Roman\nmy_2d_plot.x_values_color() RGB(255,0,0)\nmy_2d_plot.x_values_precision() 3\nmy_2d_plot.x_values_ioflags() 200\nmy_2d_plot.y_values_font_size() 14\nmy_2d_plot.y_values_font_family() Arial\nmy_2d_plot.y_values_color() RGB(0,0,255)\nmy_2d_plot.y_values_precision() 5\n my_2d_plot.y_values_ioflags() 200\n\n//] [demo_2d_values_output]\n\n\n*/\n\n", "meta": {"hexsha": "79675efebf7c9ed8fca28bc3d07506018e2b1542", "size": 9420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_values.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_values.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_values.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 43.0136986301, "max_line_length": 126, "alphanum_fraction": 0.7268577495, "num_tokens": 2586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.31069437044942166, "lm_q1q2_score": 0.15534718522471083}}
{"text": "#include <boost/rational.hpp>   /// For calculations related to sampling coefficients.\n#include <base/scope_guard_safe.h>\n#include <optional>\n#include <unordered_set>\n\n#include <Storages/MergeTree/MergeTreeDataSelectExecutor.h>\n#include <Storages/MergeTree/MergeTreeReadPool.h>\n#include <Storages/MergeTree/MergeTreeIndices.h>\n#include <Storages/MergeTree/MergeTreeIndexReader.h>\n#include <Storages/MergeTree/KeyCondition.h>\n#include <Storages/MergeTree/MergeTreeDataPartUUID.h>\n#include <Storages/ReadInOrderOptimizer.h>\n#include <Parsers/ASTIdentifier.h>\n#include <Parsers/ASTLiteral.h>\n#include <Parsers/ASTFunction.h>\n#include <Parsers/ASTSampleRatio.h>\n#include <Parsers/parseIdentifierOrStringLiteral.h>\n#include <Interpreters/ExpressionAnalyzer.h>\n#include <Interpreters/Context.h>\n#include <Processors/ConcatProcessor.h>\n#include <Processors/QueryPlan/QueryPlan.h>\n#include <Processors/QueryPlan/CreatingSetsStep.h>\n#include <Processors/QueryPlan/FilterStep.h>\n#include <Processors/QueryPlan/ExpressionStep.h>\n#include <Processors/QueryPlan/ReadFromPreparedSource.h>\n#include <Processors/QueryPlan/ReadFromMergeTree.h>\n#include <Processors/QueryPlan/UnionStep.h>\n#include <Processors/Sources/SourceFromSingleChunk.h>\n\n#include <Core/UUID.h>\n#include <DataTypes/DataTypeDate.h>\n#include <DataTypes/DataTypeEnum.h>\n#include <DataTypes/DataTypeUUID.h>\n#include <DataTypes/DataTypeTuple.h>\n#include <DataTypes/DataTypesNumber.h>\n#include <DataTypes/DataTypeArray.h>\n#include <Storages/VirtualColumnUtils.h>\n\n#include <Interpreters/InterpreterSelectQuery.h>\n\n#include <Processors/Transforms/AggregatingTransform.h>\n#include <Storages/MergeTree/StorageFromMergeTreeDataPart.h>\n#include <IO/WriteBufferFromOStream.h>\n\nnamespace ProfileEvents\n{\n    extern const Event SelectedParts;\n    extern const Event SelectedRanges;\n    extern const Event SelectedMarks;\n}\n\n\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int LOGICAL_ERROR;\n    extern const int INDEX_NOT_USED;\n    extern const int ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER;\n    extern const int ILLEGAL_COLUMN;\n    extern const int ARGUMENT_OUT_OF_BOUND;\n    extern const int TOO_MANY_ROWS;\n    extern const int CANNOT_PARSE_TEXT;\n    extern const int TOO_MANY_PARTITIONS;\n    extern const int DUPLICATED_PART_UUIDS;\n    extern const int NO_SUCH_COLUMN_IN_TABLE;\n    extern const int PROJECTION_NOT_USED;\n}\n\n\nMergeTreeDataSelectExecutor::MergeTreeDataSelectExecutor(const MergeTreeData & data_)\n    : data(data_), log(&Poco::Logger::get(data.getLogName() + \" (SelectExecutor)\"))\n{\n}\n\nsize_t MergeTreeDataSelectExecutor::getApproximateTotalRowsToRead(\n    const MergeTreeData::DataPartsVector & parts,\n    const StorageMetadataPtr & metadata_snapshot,\n    const KeyCondition & key_condition,\n    const Settings & settings,\n    Poco::Logger * log)\n{\n    size_t rows_count = 0;\n\n    /// We will find out how many rows we would have read without sampling.\n    LOG_DEBUG(log, \"Preliminary index scan with condition: {}\", key_condition.toString());\n\n    for (const auto & part : parts)\n    {\n        MarkRanges ranges = markRangesFromPKRange(part, metadata_snapshot, key_condition, settings, log);\n\n        /** In order to get a lower bound on the number of rows that match the condition on PK,\n          *  consider only guaranteed full marks.\n          * That is, do not take into account the first and last marks, which may be incomplete.\n          */\n        for (const auto & range : ranges)\n            if (range.end - range.begin > 2)\n                rows_count += part->index_granularity.getRowsCountInRange({range.begin + 1, range.end - 1});\n\n    }\n\n    return rows_count;\n}\n\n\nusing RelativeSize = boost::rational<ASTSampleRatio::BigNum>;\n\nstatic std::string toString(const RelativeSize & x)\n{\n    return ASTSampleRatio::toString(x.numerator()) + \"/\" + ASTSampleRatio::toString(x.denominator());\n}\n\n/// Converts sample size to an approximate number of rows (ex. `SAMPLE 1000000`) to relative value (ex. `SAMPLE 0.1`).\nstatic RelativeSize convertAbsoluteSampleSizeToRelative(const ASTPtr & node, size_t approx_total_rows)\n{\n    if (approx_total_rows == 0)\n        return 1;\n\n    const auto & node_sample = node->as<ASTSampleRatio &>();\n\n    auto absolute_sample_size = node_sample.ratio.numerator / node_sample.ratio.denominator;\n    return std::min(RelativeSize(1), RelativeSize(absolute_sample_size) / RelativeSize(approx_total_rows));\n}\n\n\nQueryPlanPtr MergeTreeDataSelectExecutor::read(\n    const Names & column_names_to_return,\n    const StorageMetadataPtr & metadata_snapshot,\n    const SelectQueryInfo & query_info,\n    ContextPtr context,\n    const UInt64 max_block_size,\n    const unsigned num_streams,\n    QueryProcessingStage::Enum processed_stage,\n    std::shared_ptr<PartitionIdToMaxBlock> max_block_numbers_to_read) const\n{\n    if (query_info.merge_tree_empty_result)\n        return std::make_unique<QueryPlan>();\n\n    const auto & settings = context->getSettingsRef();\n    if (!query_info.projection)\n    {\n        auto plan = readFromParts(\n            query_info.merge_tree_select_result_ptr ? MergeTreeData::DataPartsVector{} : data.getDataPartsVector(),\n            column_names_to_return,\n            metadata_snapshot,\n            metadata_snapshot,\n            query_info,\n            context,\n            max_block_size,\n            num_streams,\n            max_block_numbers_to_read,\n            query_info.merge_tree_select_result_ptr);\n\n        if (plan->isInitialized() && settings.allow_experimental_projection_optimization && settings.force_optimize_projection\n            && !metadata_snapshot->projections.empty())\n            throw Exception(\n                \"No projection is used when allow_experimental_projection_optimization = 1 and force_optimize_projection = 1\",\n                ErrorCodes::PROJECTION_NOT_USED);\n\n        return plan;\n    }\n\n    LOG_DEBUG(\n        log,\n        \"Choose {} {} projection {}\",\n        query_info.projection->complete ? \"complete\" : \"incomplete\",\n        query_info.projection->desc->type,\n        query_info.projection->desc->name);\n\n    Pipes pipes;\n    Pipe projection_pipe;\n    Pipe ordinary_pipe;\n\n    auto projection_plan = std::make_unique<QueryPlan>();\n    if (query_info.projection->desc->is_minmax_count_projection)\n    {\n        Pipe pipe(std::make_shared<SourceFromSingleChunk>(query_info.minmax_count_projection_block));\n        auto read_from_pipe = std::make_unique<ReadFromPreparedSource>(std::move(pipe));\n        projection_plan->addStep(std::move(read_from_pipe));\n    }\n    else if (query_info.projection->merge_tree_projection_select_result_ptr)\n    {\n        LOG_DEBUG(log, \"projection required columns: {}\", fmt::join(query_info.projection->required_columns, \", \"));\n        projection_plan = readFromParts(\n            {},\n            query_info.projection->required_columns,\n            metadata_snapshot,\n            query_info.projection->desc->metadata,\n            query_info,\n            context,\n            max_block_size,\n            num_streams,\n            max_block_numbers_to_read,\n            query_info.projection->merge_tree_projection_select_result_ptr);\n    }\n\n    if (projection_plan->isInitialized())\n    {\n        if (query_info.projection->before_where)\n        {\n            auto where_step = std::make_unique<FilterStep>(\n                projection_plan->getCurrentDataStream(),\n                query_info.projection->before_where,\n                query_info.projection->where_column_name,\n                query_info.projection->remove_where_filter);\n\n            where_step->setStepDescription(\"WHERE\");\n            projection_plan->addStep(std::move(where_step));\n        }\n\n        if (query_info.projection->before_aggregation)\n        {\n            auto expression_before_aggregation\n                = std::make_unique<ExpressionStep>(projection_plan->getCurrentDataStream(), query_info.projection->before_aggregation);\n            expression_before_aggregation->setStepDescription(\"Before GROUP BY\");\n            projection_plan->addStep(std::move(expression_before_aggregation));\n        }\n\n        projection_pipe = projection_plan->convertToPipe(\n            QueryPlanOptimizationSettings::fromContext(context), BuildQueryPipelineSettings::fromContext(context));\n    }\n\n    if (query_info.projection->merge_tree_normal_select_result_ptr)\n    {\n        auto storage_from_base_parts_of_projection\n            = StorageFromMergeTreeDataPart::create(data, query_info.projection->merge_tree_normal_select_result_ptr);\n        auto interpreter = InterpreterSelectQuery(\n            query_info.query,\n            context,\n            storage_from_base_parts_of_projection,\n            nullptr,\n            SelectQueryOptions{processed_stage}.projectionQuery());\n\n        QueryPlan ordinary_query_plan;\n        interpreter.buildQueryPlan(ordinary_query_plan);\n\n        const auto & expressions = interpreter.getAnalysisResult();\n        if (processed_stage == QueryProcessingStage::Enum::FetchColumns && expressions.before_where)\n        {\n            auto where_step = std::make_unique<FilterStep>(\n                ordinary_query_plan.getCurrentDataStream(),\n                expressions.before_where,\n                expressions.where_column_name,\n                expressions.remove_where_filter);\n            where_step->setStepDescription(\"WHERE\");\n            ordinary_query_plan.addStep(std::move(where_step));\n        }\n\n        ordinary_pipe = ordinary_query_plan.convertToPipe(\n            QueryPlanOptimizationSettings::fromContext(context), BuildQueryPipelineSettings::fromContext(context));\n    }\n\n    if (query_info.projection->desc->type == ProjectionDescription::Type::Aggregate)\n    {\n        /// Here we create shared ManyAggregatedData for both projection and ordinary data.\n        /// For ordinary data, AggregatedData is filled in a usual way.\n        /// For projection data, AggregatedData is filled by merging aggregation states.\n        /// When all AggregatedData is filled, we merge aggregation states together in a usual way.\n        /// Pipeline will look like:\n        /// ReadFromProjection   -> Aggregating (only merge states) ->\n        /// ReadFromProjection   -> Aggregating (only merge states) ->\n        /// ...                                                     -> Resize -> ConvertingAggregatedToChunks\n        /// ReadFromOrdinaryPart -> Aggregating (usual)             ->           (added by last Aggregating)\n        /// ReadFromOrdinaryPart -> Aggregating (usual)             ->\n        /// ...\n        auto many_data = std::make_shared<ManyAggregatedData>(projection_pipe.numOutputPorts() + ordinary_pipe.numOutputPorts());\n        size_t counter = 0;\n\n        AggregatorListPtr aggregator_list_ptr = std::make_shared<AggregatorList>();\n\n        // TODO apply in_order_optimization here\n        auto build_aggregate_pipe = [&](Pipe & pipe, bool projection)\n        {\n            const auto & header_before_aggregation = pipe.getHeader();\n\n            ColumnNumbers keys;\n            for (const auto & key : query_info.projection->aggregation_keys)\n                keys.push_back(header_before_aggregation.getPositionByName(key.name));\n\n            AggregateDescriptions aggregates = query_info.projection->aggregate_descriptions;\n            if (!projection)\n            {\n                for (auto & descr : aggregates)\n                    if (descr.arguments.empty())\n                        for (const auto & name : descr.argument_names)\n                            descr.arguments.push_back(header_before_aggregation.getPositionByName(name));\n            }\n\n            AggregatingTransformParamsPtr transform_params;\n            if (projection)\n            {\n                Aggregator::Params params(\n                    header_before_aggregation,\n                    keys,\n                    aggregates,\n                    query_info.projection->aggregate_overflow_row,\n                    settings.max_rows_to_group_by,\n                    settings.group_by_overflow_mode,\n                    settings.group_by_two_level_threshold,\n                    settings.group_by_two_level_threshold_bytes,\n                    settings.max_bytes_before_external_group_by,\n                    settings.empty_result_for_aggregation_by_empty_set,\n                    context->getTemporaryVolume(),\n                    settings.max_threads,\n                    settings.min_free_disk_space_for_temporary_data,\n                    settings.compile_expressions,\n                    settings.min_count_to_compile_aggregate_expression,\n                    header_before_aggregation); // The source header is also an intermediate header\n\n                transform_params = std::make_shared<AggregatingTransformParams>(\n                    std::move(params), aggregator_list_ptr, query_info.projection->aggregate_final);\n\n                /// This part is hacky.\n                /// We want AggregatingTransform to work with aggregate states instead of normal columns.\n                /// It is almost the same, just instead of adding new data to aggregation state we merge it with existing.\n                ///\n                /// It is needed because data in projection:\n                /// * is not merged completely (we may have states with the same key in different parts)\n                /// * is not split into buckets (so if we just use MergingAggregated, it will use single thread)\n                transform_params->only_merge = true;\n            }\n            else\n            {\n                Aggregator::Params params(\n                    header_before_aggregation,\n                    keys,\n                    aggregates,\n                    query_info.projection->aggregate_overflow_row,\n                    settings.max_rows_to_group_by,\n                    settings.group_by_overflow_mode,\n                    settings.group_by_two_level_threshold,\n                    settings.group_by_two_level_threshold_bytes,\n                    settings.max_bytes_before_external_group_by,\n                    settings.empty_result_for_aggregation_by_empty_set,\n                    context->getTemporaryVolume(),\n                    settings.max_threads,\n                    settings.min_free_disk_space_for_temporary_data,\n                    settings.compile_aggregate_expressions,\n                    settings.min_count_to_compile_aggregate_expression);\n\n                transform_params = std::make_shared<AggregatingTransformParams>(\n                    std::move(params), aggregator_list_ptr, query_info.projection->aggregate_final);\n            }\n\n            pipe.resize(pipe.numOutputPorts(), true, true);\n\n            auto merge_threads = num_streams;\n            auto temporary_data_merge_threads = settings.aggregation_memory_efficient_merge_threads\n                ? static_cast<size_t>(settings.aggregation_memory_efficient_merge_threads)\n                : static_cast<size_t>(settings.max_threads);\n\n            pipe.addSimpleTransform([&](const Block & header)\n            {\n                return std::make_shared<AggregatingTransform>(\n                    header, transform_params, many_data, counter++, merge_threads, temporary_data_merge_threads);\n            });\n        };\n\n        if (!projection_pipe.empty())\n            build_aggregate_pipe(projection_pipe, true);\n        if (!ordinary_pipe.empty())\n            build_aggregate_pipe(ordinary_pipe, false);\n    }\n\n    pipes.emplace_back(std::move(projection_pipe));\n    pipes.emplace_back(std::move(ordinary_pipe));\n    auto pipe = Pipe::unitePipes(std::move(pipes));\n    auto plan = std::make_unique<QueryPlan>();\n    if (pipe.empty())\n        return plan;\n\n    pipe.resize(1);\n    auto step = std::make_unique<ReadFromStorageStep>(\n        std::move(pipe),\n        fmt::format(\"MergeTree(with {} projection {})\", query_info.projection->desc->type, query_info.projection->desc->name));\n    plan->addStep(std::move(step));\n\n    if (query_info.projection->subqueries_for_sets && !query_info.projection->subqueries_for_sets->empty())\n    {\n        SizeLimits limits(settings.max_rows_to_transfer, settings.max_bytes_to_transfer, settings.transfer_overflow_mode);\n        addCreatingSetsStep(*plan, std::move(*query_info.projection->subqueries_for_sets), limits, context);\n    }\n    return plan;\n}\n\nMergeTreeDataSelectSamplingData MergeTreeDataSelectExecutor::getSampling(\n    const ASTSelectQuery & select,\n    NamesAndTypesList available_real_columns,\n    const MergeTreeData::DataPartsVector & parts,\n    KeyCondition & key_condition,\n    const MergeTreeData & data,\n    const StorageMetadataPtr & metadata_snapshot,\n    ContextPtr context,\n    bool sample_factor_column_queried,\n    Poco::Logger * log)\n{\n    const Settings & settings = context->getSettingsRef();\n    /// Sampling.\n    MergeTreeDataSelectSamplingData sampling;\n\n    RelativeSize relative_sample_size = 0;\n    RelativeSize relative_sample_offset = 0;\n\n    auto select_sample_size = select.sampleSize();\n    auto select_sample_offset = select.sampleOffset();\n\n    if (select_sample_size)\n    {\n        relative_sample_size.assign(\n            select_sample_size->as<ASTSampleRatio &>().ratio.numerator,\n            select_sample_size->as<ASTSampleRatio &>().ratio.denominator);\n\n        if (relative_sample_size < 0)\n            throw Exception(\"Negative sample size\", ErrorCodes::ARGUMENT_OUT_OF_BOUND);\n\n        relative_sample_offset = 0;\n        if (select_sample_offset)\n            relative_sample_offset.assign(\n                select_sample_offset->as<ASTSampleRatio &>().ratio.numerator,\n                select_sample_offset->as<ASTSampleRatio &>().ratio.denominator);\n\n        if (relative_sample_offset < 0)\n            throw Exception(\"Negative sample offset\", ErrorCodes::ARGUMENT_OUT_OF_BOUND);\n\n        /// Convert absolute value of the sampling (in form `SAMPLE 1000000` - how many rows to\n        /// read) into the relative `SAMPLE 0.1` (how much data to read).\n        size_t approx_total_rows = 0;\n        if (relative_sample_size > 1 || relative_sample_offset > 1)\n            approx_total_rows = getApproximateTotalRowsToRead(parts, metadata_snapshot, key_condition, settings, log);\n\n        if (relative_sample_size > 1)\n        {\n            relative_sample_size = convertAbsoluteSampleSizeToRelative(select_sample_size, approx_total_rows);\n            LOG_DEBUG(log, \"Selected relative sample size: {}\", toString(relative_sample_size));\n        }\n\n        /// SAMPLE 1 is the same as the absence of SAMPLE.\n        if (relative_sample_size == RelativeSize(1))\n            relative_sample_size = 0;\n\n        if (relative_sample_offset > 0 && RelativeSize(0) == relative_sample_size)\n            throw Exception(\"Sampling offset is incorrect because no sampling\", ErrorCodes::ARGUMENT_OUT_OF_BOUND);\n\n        if (relative_sample_offset > 1)\n        {\n            relative_sample_offset = convertAbsoluteSampleSizeToRelative(select_sample_offset, approx_total_rows);\n            LOG_DEBUG(log, \"Selected relative sample offset: {}\", toString(relative_sample_offset));\n        }\n    }\n\n    /** Which range of sampling key values do I need to read?\n        * First, in the whole range (\"universe\") we select the interval\n        *  of relative `relative_sample_size` size, offset from the beginning by `relative_sample_offset`.\n        *\n        * Example: SAMPLE 0.4 OFFSET 0.3\n        *\n        * [------********------]\n        *        ^ - offset\n        *        <------> - size\n        *\n        * If the interval passes through the end of the universe, then cut its right side.\n        *\n        * Example: SAMPLE 0.4 OFFSET 0.8\n        *\n        * [----------------****]\n        *                  ^ - offset\n        *                  <------> - size\n        *\n        * Next, if the `parallel_replicas_count`, `parallel_replica_offset` settings are set,\n        *  then it is necessary to break the received interval into pieces of the number `parallel_replicas_count`,\n        *  and select a piece with the number `parallel_replica_offset` (from zero).\n        *\n        * Example: SAMPLE 0.4 OFFSET 0.3, parallel_replicas_count = 2, parallel_replica_offset = 1\n        *\n        * [----------****------]\n        *        ^ - offset\n        *        <------> - size\n        *        <--><--> - pieces for different `parallel_replica_offset`, select the second one.\n        *\n        * It is very important that the intervals for different `parallel_replica_offset` cover the entire range without gaps and overlaps.\n        * It is also important that the entire universe can be covered using SAMPLE 0.1 OFFSET 0, ... OFFSET 0.9 and similar decimals.\n        */\n\n    /// Parallel replicas has been requested but there is no way to sample data.\n    /// Select all data from first replica and no data from other replicas.\n    if (settings.parallel_replicas_count > 1 && !data.supportsSampling() && settings.parallel_replica_offset > 0)\n    {\n        LOG_DEBUG(log, \"Will use no data on this replica because parallel replicas processing has been requested\"\n            \" (the setting 'max_parallel_replicas') but the table does not support sampling and this replica is not the first.\");\n        sampling.read_nothing = true;\n        return sampling;\n    }\n\n    sampling.use_sampling = relative_sample_size > 0 || (settings.parallel_replicas_count > 1 && data.supportsSampling());\n    bool no_data = false;   /// There is nothing left after sampling.\n\n    if (sampling.use_sampling)\n    {\n        if (sample_factor_column_queried && relative_sample_size != RelativeSize(0))\n            sampling.used_sample_factor = 1.0 / boost::rational_cast<Float64>(relative_sample_size);\n\n        RelativeSize size_of_universum = 0;\n        const auto & sampling_key = metadata_snapshot->getSamplingKey();\n        DataTypePtr sampling_column_type = sampling_key.data_types[0];\n\n        if (sampling_key.data_types.size() == 1)\n        {\n            if (typeid_cast<const DataTypeUInt64 *>(sampling_column_type.get()))\n                size_of_universum = RelativeSize(std::numeric_limits<UInt64>::max()) + RelativeSize(1);\n            else if (typeid_cast<const DataTypeUInt32 *>(sampling_column_type.get()))\n                size_of_universum = RelativeSize(std::numeric_limits<UInt32>::max()) + RelativeSize(1);\n            else if (typeid_cast<const DataTypeUInt16 *>(sampling_column_type.get()))\n                size_of_universum = RelativeSize(std::numeric_limits<UInt16>::max()) + RelativeSize(1);\n            else if (typeid_cast<const DataTypeUInt8 *>(sampling_column_type.get()))\n                size_of_universum = RelativeSize(std::numeric_limits<UInt8>::max()) + RelativeSize(1);\n        }\n\n        if (size_of_universum == RelativeSize(0))\n            throw Exception(\n                \"Invalid sampling column type in storage parameters: \" + sampling_column_type->getName()\n                    + \". Must be one unsigned integer type\",\n                ErrorCodes::ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER);\n\n        if (settings.parallel_replicas_count > 1)\n        {\n            if (relative_sample_size == RelativeSize(0))\n                relative_sample_size = 1;\n\n            relative_sample_size /= settings.parallel_replicas_count.value;\n            relative_sample_offset += relative_sample_size * RelativeSize(settings.parallel_replica_offset.value);\n        }\n\n        if (relative_sample_offset >= RelativeSize(1))\n            no_data = true;\n\n        /// Calculate the half-interval of `[lower, upper)` column values.\n        bool has_lower_limit = false;\n        bool has_upper_limit = false;\n\n        RelativeSize lower_limit_rational = relative_sample_offset * size_of_universum;\n        RelativeSize upper_limit_rational = (relative_sample_offset + relative_sample_size) * size_of_universum;\n\n        UInt64 lower = boost::rational_cast<ASTSampleRatio::BigNum>(lower_limit_rational);\n        UInt64 upper = boost::rational_cast<ASTSampleRatio::BigNum>(upper_limit_rational);\n\n        if (lower > 0)\n            has_lower_limit = true;\n\n        if (upper_limit_rational < size_of_universum)\n            has_upper_limit = true;\n\n        /*std::cerr << std::fixed << std::setprecision(100)\n            << \"relative_sample_size: \" << relative_sample_size << \"\\n\"\n            << \"relative_sample_offset: \" << relative_sample_offset << \"\\n\"\n            << \"lower_limit_float: \" << lower_limit_rational << \"\\n\"\n            << \"upper_limit_float: \" << upper_limit_rational << \"\\n\"\n            << \"lower: \" << lower << \"\\n\"\n            << \"upper: \" << upper << \"\\n\";*/\n\n        if ((has_upper_limit && upper == 0)\n            || (has_lower_limit && has_upper_limit && lower == upper))\n            no_data = true;\n\n        if (no_data || (!has_lower_limit && !has_upper_limit))\n        {\n            sampling.use_sampling = false;\n        }\n        else\n        {\n            /// Let's add the conditions to cut off something else when the index is scanned again and when the request is processed.\n\n            std::shared_ptr<ASTFunction> lower_function;\n            std::shared_ptr<ASTFunction> upper_function;\n\n            /// If sample and final are used together no need to calculate sampling expression twice.\n            /// The first time it was calculated for final, because sample key is a part of the PK.\n            /// So, assume that we already have calculated column.\n            ASTPtr sampling_key_ast = metadata_snapshot->getSamplingKeyAST();\n\n            if (select.final())\n            {\n                sampling_key_ast = std::make_shared<ASTIdentifier>(sampling_key.column_names[0]);\n                /// We do spoil available_real_columns here, but it is not used later.\n                available_real_columns.emplace_back(sampling_key.column_names[0], std::move(sampling_column_type));\n            }\n\n            if (has_lower_limit)\n            {\n                if (!key_condition.addCondition(sampling_key.column_names[0], Range::createLeftBounded(lower, true)))\n                    throw Exception(\"Sampling column not in primary key\", ErrorCodes::ILLEGAL_COLUMN);\n\n                ASTPtr args = std::make_shared<ASTExpressionList>();\n                args->children.push_back(sampling_key_ast);\n                args->children.push_back(std::make_shared<ASTLiteral>(lower));\n\n                lower_function = std::make_shared<ASTFunction>();\n                lower_function->name = \"greaterOrEquals\";\n                lower_function->arguments = args;\n                lower_function->children.push_back(lower_function->arguments);\n\n                sampling.filter_function = lower_function;\n            }\n\n            if (has_upper_limit)\n            {\n                if (!key_condition.addCondition(sampling_key.column_names[0], Range::createRightBounded(upper, false)))\n                    throw Exception(\"Sampling column not in primary key\", ErrorCodes::ILLEGAL_COLUMN);\n\n                ASTPtr args = std::make_shared<ASTExpressionList>();\n                args->children.push_back(sampling_key_ast);\n                args->children.push_back(std::make_shared<ASTLiteral>(upper));\n\n                upper_function = std::make_shared<ASTFunction>();\n                upper_function->name = \"less\";\n                upper_function->arguments = args;\n                upper_function->children.push_back(upper_function->arguments);\n\n                sampling.filter_function = upper_function;\n            }\n\n            if (has_lower_limit && has_upper_limit)\n            {\n                ASTPtr args = std::make_shared<ASTExpressionList>();\n                args->children.push_back(lower_function);\n                args->children.push_back(upper_function);\n\n                sampling.filter_function = std::make_shared<ASTFunction>();\n                sampling.filter_function->name = \"and\";\n                sampling.filter_function->arguments = args;\n                sampling.filter_function->children.push_back(sampling.filter_function->arguments);\n            }\n\n            ASTPtr query = sampling.filter_function;\n            auto syntax_result = TreeRewriter(context).analyze(query, available_real_columns);\n            sampling.filter_expression = ExpressionAnalyzer(sampling.filter_function, syntax_result, context).getActionsDAG(false);\n        }\n    }\n\n    if (no_data)\n    {\n        LOG_DEBUG(log, \"Sampling yields no data.\");\n        sampling.read_nothing = true;\n    }\n\n    return sampling;\n}\n\nstd::optional<std::unordered_set<String>> MergeTreeDataSelectExecutor::filterPartsByVirtualColumns(\n    const MergeTreeData & data,\n    const MergeTreeData::DataPartsVector & parts,\n    const ASTPtr & query,\n    ContextPtr context)\n{\n    std::unordered_set<String> part_values;\n    ASTPtr expression_ast;\n    auto virtual_columns_block = data.getBlockWithVirtualPartColumns(parts, true /* one_part */);\n\n    // Generate valid expressions for filtering\n    VirtualColumnUtils::prepareFilterBlockWithQuery(query, context, virtual_columns_block, expression_ast);\n\n    // If there is still something left, fill the virtual block and do the filtering.\n    if (expression_ast)\n    {\n        virtual_columns_block = data.getBlockWithVirtualPartColumns(parts, false /* one_part */);\n        VirtualColumnUtils::filterBlockWithQuery(query, virtual_columns_block, context, expression_ast);\n        return VirtualColumnUtils::extractSingleValueFromBlock<String>(virtual_columns_block, \"_part\");\n    }\n\n    return {};\n}\n\nvoid MergeTreeDataSelectExecutor::filterPartsByPartition(\n    MergeTreeData::DataPartsVector & parts,\n    const std::optional<std::unordered_set<String>> & part_values,\n    const StorageMetadataPtr & metadata_snapshot,\n    const MergeTreeData & data,\n    const SelectQueryInfo & query_info,\n    const ContextPtr & context,\n    const PartitionIdToMaxBlock * max_block_numbers_to_read,\n    Poco::Logger * log,\n    ReadFromMergeTree::IndexStats & index_stats)\n{\n    const Settings & settings = context->getSettingsRef();\n    std::optional<PartitionPruner> partition_pruner;\n    std::optional<KeyCondition> minmax_idx_condition;\n    DataTypes minmax_columns_types;\n    if (metadata_snapshot->hasPartitionKey())\n    {\n        const auto & partition_key = metadata_snapshot->getPartitionKey();\n        auto minmax_columns_names = data.getMinMaxColumnsNames(partition_key);\n        minmax_columns_types = data.getMinMaxColumnsTypes(partition_key);\n\n        minmax_idx_condition.emplace(\n            query_info, context, minmax_columns_names, data.getMinMaxExpr(partition_key, ExpressionActionsSettings::fromContext(context)));\n        partition_pruner.emplace(metadata_snapshot, query_info, context, false /* strict */);\n\n        if (settings.force_index_by_date && (minmax_idx_condition->alwaysUnknownOrTrue() && partition_pruner->isUseless()))\n        {\n            String msg = \"Neither MinMax index by columns (\";\n            bool first = true;\n            for (const String & col : minmax_columns_names)\n            {\n                if (first)\n                    first = false;\n                else\n                    msg += \", \";\n                msg += col;\n            }\n            msg += \") nor partition expr is used and setting 'force_index_by_date' is set\";\n\n            throw Exception(msg, ErrorCodes::INDEX_NOT_USED);\n        }\n    }\n\n    auto query_context = context->hasQueryContext() ? context->getQueryContext() : context;\n    PartFilterCounters part_filter_counters;\n    if (query_context->getSettingsRef().allow_experimental_query_deduplication)\n        selectPartsToReadWithUUIDFilter(\n            parts,\n            part_values,\n            data.getPinnedPartUUIDs(),\n            minmax_idx_condition,\n            minmax_columns_types,\n            partition_pruner,\n            max_block_numbers_to_read,\n            query_context,\n            part_filter_counters,\n            log);\n    else\n        selectPartsToRead(\n            parts,\n            part_values,\n            minmax_idx_condition,\n            minmax_columns_types,\n            partition_pruner,\n            max_block_numbers_to_read,\n            part_filter_counters);\n\n    index_stats.emplace_back(ReadFromMergeTree::IndexStat{\n        .type = ReadFromMergeTree::IndexType::None,\n        .num_parts_after = part_filter_counters.num_initial_selected_parts,\n        .num_granules_after = part_filter_counters.num_initial_selected_granules});\n\n    if (minmax_idx_condition)\n    {\n        auto description = minmax_idx_condition->getDescription();\n        index_stats.emplace_back(ReadFromMergeTree::IndexStat{\n            .type = ReadFromMergeTree::IndexType::MinMax,\n            .condition = std::move(description.condition),\n            .used_keys = std::move(description.used_keys),\n            .num_parts_after = part_filter_counters.num_parts_after_minmax,\n            .num_granules_after = part_filter_counters.num_granules_after_minmax});\n        LOG_DEBUG(log, \"MinMax index condition: {}\", minmax_idx_condition->toString());\n    }\n\n    if (partition_pruner)\n    {\n        auto description = partition_pruner->getKeyCondition().getDescription();\n        index_stats.emplace_back(ReadFromMergeTree::IndexStat{\n            .type = ReadFromMergeTree::IndexType::Partition,\n            .condition = std::move(description.condition),\n            .used_keys = std::move(description.used_keys),\n            .num_parts_after = part_filter_counters.num_parts_after_partition_pruner,\n            .num_granules_after = part_filter_counters.num_granules_after_partition_pruner});\n    }\n}\n\nRangesInDataParts MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexes(\n    MergeTreeData::DataPartsVector && parts,\n    StorageMetadataPtr metadata_snapshot,\n    const SelectQueryInfo & query_info,\n    const ContextPtr & context,\n    const KeyCondition & key_condition,\n    const MergeTreeReaderSettings & reader_settings,\n    Poco::Logger * log,\n    size_t num_streams,\n    ReadFromMergeTree::IndexStats & index_stats,\n    bool use_skip_indexes)\n{\n    RangesInDataParts parts_with_ranges(parts.size());\n    const Settings & settings = context->getSettingsRef();\n\n    /// Let's start analyzing all useful indices\n\n    struct DataSkippingIndexAndCondition\n    {\n        MergeTreeIndexPtr index;\n        MergeTreeIndexConditionPtr condition;\n        std::atomic<size_t> total_granules{0};\n        std::atomic<size_t> granules_dropped{0};\n        std::atomic<size_t> total_parts{0};\n        std::atomic<size_t> parts_dropped{0};\n\n        DataSkippingIndexAndCondition(MergeTreeIndexPtr index_, MergeTreeIndexConditionPtr condition_)\n            : index(index_), condition(condition_)\n        {\n        }\n    };\n    std::list<DataSkippingIndexAndCondition> useful_indices;\n\n    if (use_skip_indexes)\n    {\n        for (const auto & index : metadata_snapshot->getSecondaryIndices())\n        {\n            auto index_helper = MergeTreeIndexFactory::instance().get(index);\n            auto condition = index_helper->createIndexCondition(query_info, context);\n            if (!condition->alwaysUnknownOrTrue())\n                useful_indices.emplace_back(index_helper, condition);\n        }\n    }\n\n    if (use_skip_indexes && settings.force_data_skipping_indices.changed)\n    {\n        const auto & indices = settings.force_data_skipping_indices.toString();\n\n        Strings forced_indices;\n        {\n            Tokens tokens(&indices[0], &indices[indices.size()], settings.max_query_size);\n            IParser::Pos pos(tokens, settings.max_parser_depth);\n            Expected expected;\n            if (!parseIdentifiersOrStringLiterals(pos, expected, forced_indices))\n                throw Exception(ErrorCodes::CANNOT_PARSE_TEXT, \"Cannot parse force_data_skipping_indices ('{}')\", indices);\n        }\n\n        if (forced_indices.empty())\n            throw Exception(ErrorCodes::CANNOT_PARSE_TEXT, \"No indices parsed from force_data_skipping_indices ('{}')\", indices);\n\n        std::unordered_set<std::string> useful_indices_names;\n        for (const auto & useful_index : useful_indices)\n            useful_indices_names.insert(useful_index.index->index.name);\n\n        for (const auto & index_name : forced_indices)\n        {\n            if (!useful_indices_names.count(index_name))\n            {\n                throw Exception(\n                    ErrorCodes::INDEX_NOT_USED,\n                    \"Index {} is not used and setting 'force_data_skipping_indices' contains it\",\n                    backQuote(index_name));\n            }\n        }\n    }\n\n    std::atomic<size_t> sum_marks_pk = 0;\n    std::atomic<size_t> sum_parts_pk = 0;\n\n    /// Let's find what range to read from each part.\n    {\n        std::atomic<size_t> total_rows{0};\n\n        SizeLimits limits;\n        if (settings.read_overflow_mode == OverflowMode::THROW && settings.max_rows_to_read)\n            limits = SizeLimits(settings.max_rows_to_read, 0, settings.read_overflow_mode);\n\n        SizeLimits leaf_limits;\n        if (settings.read_overflow_mode_leaf == OverflowMode::THROW && settings.max_rows_to_read_leaf)\n            leaf_limits = SizeLimits(settings.max_rows_to_read_leaf, 0, settings.read_overflow_mode_leaf);\n\n        auto mark_cache = context->getIndexMarkCache();\n        auto uncompressed_cache = context->getIndexUncompressedCache();\n\n        auto process_part = [&](size_t part_index)\n        {\n            auto & part = parts[part_index];\n\n            RangesInDataPart ranges(part, part_index);\n\n            size_t total_marks_count = part->index_granularity.getMarksCountWithoutFinal();\n\n            if (metadata_snapshot->hasPrimaryKey())\n                ranges.ranges = markRangesFromPKRange(part, metadata_snapshot, key_condition, settings, log);\n            else if (total_marks_count)\n                ranges.ranges = MarkRanges{MarkRange{0, total_marks_count}};\n\n            sum_marks_pk.fetch_add(ranges.getMarksCount(), std::memory_order_relaxed);\n\n            if (!ranges.ranges.empty())\n                sum_parts_pk.fetch_add(1, std::memory_order_relaxed);\n\n            for (auto & index_and_condition : useful_indices)\n            {\n                if (ranges.ranges.empty())\n                    break;\n\n                index_and_condition.total_parts.fetch_add(1, std::memory_order_relaxed);\n\n                size_t total_granules = 0;\n                size_t granules_dropped = 0;\n                ranges.ranges = filterMarksUsingIndex(\n                    index_and_condition.index,\n                    index_and_condition.condition,\n                    part,\n                    ranges.ranges,\n                    settings,\n                    reader_settings,\n                    total_granules,\n                    granules_dropped,\n                    mark_cache.get(),\n                    uncompressed_cache.get(),\n                    log);\n\n                index_and_condition.total_granules.fetch_add(total_granules, std::memory_order_relaxed);\n                index_and_condition.granules_dropped.fetch_add(granules_dropped, std::memory_order_relaxed);\n\n                if (ranges.ranges.empty())\n                    index_and_condition.parts_dropped.fetch_add(1, std::memory_order_relaxed);\n            }\n\n            if (!ranges.ranges.empty())\n            {\n                if (limits.max_rows || leaf_limits.max_rows)\n                {\n                    /// Fail fast if estimated number of rows to read exceeds the limit\n                    auto current_rows_estimate = ranges.getRowsCount();\n                    size_t prev_total_rows_estimate = total_rows.fetch_add(current_rows_estimate);\n                    size_t total_rows_estimate = current_rows_estimate + prev_total_rows_estimate;\n                    limits.check(total_rows_estimate, 0, \"rows (controlled by 'max_rows_to_read' setting)\", ErrorCodes::TOO_MANY_ROWS);\n                    leaf_limits.check(\n                        total_rows_estimate, 0, \"rows (controlled by 'max_rows_to_read_leaf' setting)\", ErrorCodes::TOO_MANY_ROWS);\n                }\n\n                parts_with_ranges[part_index] = std::move(ranges);\n            }\n        };\n\n        size_t num_threads = std::min(size_t(num_streams), parts.size());\n\n        if (num_threads <= 1)\n        {\n            for (size_t part_index = 0; part_index < parts.size(); ++part_index)\n                process_part(part_index);\n        }\n        else\n        {\n            /// Parallel loading of data parts.\n            ThreadPool pool(num_threads);\n\n            for (size_t part_index = 0; part_index < parts.size(); ++part_index)\n                pool.scheduleOrThrowOnError([&, part_index, thread_group = CurrentThread::getGroup()]\n                {\n                    SCOPE_EXIT_SAFE(if (thread_group) CurrentThread::detachQueryIfNotDetached(););\n                    if (thread_group)\n                        CurrentThread::attachTo(thread_group);\n\n                    process_part(part_index);\n                });\n\n            pool.wait();\n        }\n\n        /// Skip empty ranges.\n        size_t next_part = 0;\n        for (size_t part_index = 0; part_index < parts.size(); ++part_index)\n        {\n            auto & part = parts_with_ranges[part_index];\n            if (!part.data_part)\n                continue;\n\n            if (next_part != part_index)\n                std::swap(parts_with_ranges[next_part], part);\n\n            ++next_part;\n        }\n\n        parts_with_ranges.resize(next_part);\n    }\n\n    if (metadata_snapshot->hasPrimaryKey())\n    {\n        auto description = key_condition.getDescription();\n\n        index_stats.emplace_back(ReadFromMergeTree::IndexStat{\n            .type = ReadFromMergeTree::IndexType::PrimaryKey,\n            .condition = std::move(description.condition),\n            .used_keys = std::move(description.used_keys),\n            .num_parts_after = sum_parts_pk.load(std::memory_order_relaxed),\n            .num_granules_after = sum_marks_pk.load(std::memory_order_relaxed)});\n    }\n\n    for (const auto & index_and_condition : useful_indices)\n    {\n        const auto & index_name = index_and_condition.index->index.name;\n        LOG_DEBUG(\n            log,\n            \"Index {} has dropped {}/{} granules.\",\n            backQuote(index_name),\n            index_and_condition.granules_dropped,\n            index_and_condition.total_granules);\n\n        std::string description\n            = index_and_condition.index->index.type + \" GRANULARITY \" + std::to_string(index_and_condition.index->index.granularity);\n\n        index_stats.emplace_back(ReadFromMergeTree::IndexStat{\n            .type = ReadFromMergeTree::IndexType::Skip,\n            .name = index_name,\n            .description = std::move(description), //-V1030\n            .num_parts_after = index_and_condition.total_parts - index_and_condition.parts_dropped,\n            .num_granules_after = index_and_condition.total_granules - index_and_condition.granules_dropped});\n    }\n\n    return parts_with_ranges;\n}\n\nstd::shared_ptr<QueryIdHolder> MergeTreeDataSelectExecutor::checkLimits(\n    const MergeTreeData & data,\n    const ReadFromMergeTree::AnalysisResult & result,\n    const ContextPtr & context)\n{\n    const auto & settings = context->getSettingsRef();\n    const auto data_settings = data.getSettings();\n    auto max_partitions_to_read\n        = settings.max_partitions_to_read.changed ? settings.max_partitions_to_read : data_settings->max_partitions_to_read;\n    if (max_partitions_to_read > 0)\n    {\n        std::set<String> partitions;\n        for (const auto & part_with_ranges : result.parts_with_ranges)\n            partitions.insert(part_with_ranges.data_part->info.partition_id);\n        if (partitions.size() > size_t(max_partitions_to_read))\n            throw Exception(\n                ErrorCodes::TOO_MANY_PARTITIONS,\n                \"Too many partitions to read. Current {}, max {}\",\n                partitions.size(),\n                max_partitions_to_read);\n    }\n\n    if (data_settings->max_concurrent_queries > 0 && data_settings->min_marks_to_honor_max_concurrent_queries > 0\n        && result.selected_marks >= data_settings->min_marks_to_honor_max_concurrent_queries)\n    {\n        auto query_id = context->getCurrentQueryId();\n        if (!query_id.empty())\n        {\n            auto lock = data.getQueryIdSetLock();\n            if (data.insertQueryIdOrThrowNoLock(query_id, data_settings->max_concurrent_queries, lock))\n            {\n                try\n                {\n                    return std::make_shared<QueryIdHolder>(query_id, data);\n                }\n                catch (...)\n                {\n                    /// If we fail to construct the holder, remove query_id explicitly to avoid leak.\n                    data.removeQueryIdNoLock(query_id, lock);\n                    throw;\n                }\n            }\n        }\n    }\n    return nullptr;\n}\n\nstatic void selectColumnNames(\n    const Names & column_names_to_return,\n    const MergeTreeData & data,\n    Names & real_column_names,\n    Names & virt_column_names,\n    bool & sample_factor_column_queried)\n{\n    sample_factor_column_queried = false;\n\n    for (const String & name : column_names_to_return)\n    {\n        if (name == \"_part\")\n        {\n            virt_column_names.push_back(name);\n        }\n        else if (name == \"_part_index\")\n        {\n            virt_column_names.push_back(name);\n        }\n        else if (name == \"_partition_id\")\n        {\n            virt_column_names.push_back(name);\n        }\n        else if (name == \"_part_uuid\")\n        {\n            virt_column_names.push_back(name);\n        }\n        else if (name == \"_partition_value\")\n        {\n            if (!typeid_cast<const DataTypeTuple *>(data.getPartitionValueType().get()))\n            {\n                throw Exception(\n                    ErrorCodes::NO_SUCH_COLUMN_IN_TABLE,\n                    \"Missing column `_partition_value` because there is no partition column in table {}\",\n                    data.getStorageID().getTableName());\n            }\n\n            virt_column_names.push_back(name);\n        }\n        else if (name == \"_sample_factor\")\n        {\n            sample_factor_column_queried = true;\n            virt_column_names.push_back(name);\n        }\n        else\n        {\n            real_column_names.push_back(name);\n        }\n    }\n}\n\nMergeTreeDataSelectAnalysisResultPtr MergeTreeDataSelectExecutor::estimateNumMarksToRead(\n    MergeTreeData::DataPartsVector parts,\n    const Names & column_names_to_return,\n    const StorageMetadataPtr & metadata_snapshot_base,\n    const StorageMetadataPtr & metadata_snapshot,\n    const SelectQueryInfo & query_info,\n    ContextPtr context,\n    unsigned num_streams,\n    std::shared_ptr<PartitionIdToMaxBlock> max_block_numbers_to_read) const\n{\n    size_t total_parts = parts.size();\n    if (total_parts == 0)\n        return std::make_shared<MergeTreeDataSelectAnalysisResult>(\n            MergeTreeDataSelectAnalysisResult{.result = ReadFromMergeTree::AnalysisResult()});\n\n    Names real_column_names;\n    Names virt_column_names;\n    /// If query contains restrictions on the virtual column `_part` or `_part_index`, select only parts suitable for it.\n    /// The virtual column `_sample_factor` (which is equal to 1 / used sample rate) can be requested in the query.\n    bool sample_factor_column_queried = false;\n\n    selectColumnNames(column_names_to_return, data, real_column_names, virt_column_names, sample_factor_column_queried);\n\n    return ReadFromMergeTree::selectRangesToRead(\n        std::move(parts),\n        metadata_snapshot_base,\n        metadata_snapshot,\n        query_info,\n        context,\n        num_streams,\n        max_block_numbers_to_read,\n        data,\n        real_column_names,\n        sample_factor_column_queried,\n        log);\n}\n\nQueryPlanPtr MergeTreeDataSelectExecutor::readFromParts(\n    MergeTreeData::DataPartsVector parts,\n    const Names & column_names_to_return,\n    const StorageMetadataPtr & metadata_snapshot_base,\n    const StorageMetadataPtr & metadata_snapshot,\n    const SelectQueryInfo & query_info,\n    ContextPtr context,\n    const UInt64 max_block_size,\n    const unsigned num_streams,\n    std::shared_ptr<PartitionIdToMaxBlock> max_block_numbers_to_read,\n    MergeTreeDataSelectAnalysisResultPtr merge_tree_select_result_ptr) const\n{\n    /// If merge_tree_select_result_ptr != nullptr, we use analyzed result so parts will always be empty.\n    if (merge_tree_select_result_ptr)\n    {\n        if (merge_tree_select_result_ptr->marks() == 0)\n            return std::make_unique<QueryPlan>();\n    }\n    else if (parts.empty())\n        return std::make_unique<QueryPlan>();\n\n    Names real_column_names;\n    Names virt_column_names;\n    /// If query contains restrictions on the virtual column `_part` or `_part_index`, select only parts suitable for it.\n    /// The virtual column `_sample_factor` (which is equal to 1 / used sample rate) can be requested in the query.\n    bool sample_factor_column_queried = false;\n\n    selectColumnNames(column_names_to_return, data, real_column_names, virt_column_names, sample_factor_column_queried);\n\n    auto read_from_merge_tree = std::make_unique<ReadFromMergeTree>(\n        std::move(parts),\n        real_column_names,\n        virt_column_names,\n        data,\n        query_info,\n        metadata_snapshot,\n        metadata_snapshot_base,\n        context,\n        max_block_size,\n        num_streams,\n        sample_factor_column_queried,\n        max_block_numbers_to_read,\n        log,\n        merge_tree_select_result_ptr\n    );\n\n    QueryPlanPtr plan = std::make_unique<QueryPlan>();\n    plan->addStep(std::move(read_from_merge_tree));\n    return plan;\n}\n\n\n/// Marks are placed whenever threshold on rows or bytes is met.\n/// So we have to return the number of marks on whatever estimate is higher - by rows or by bytes.\nsize_t MergeTreeDataSelectExecutor::roundRowsOrBytesToMarks(\n    size_t rows_setting,\n    size_t bytes_setting,\n    size_t rows_granularity,\n    size_t bytes_granularity)\n{\n    size_t res = (rows_setting + rows_granularity - 1) / rows_granularity;\n\n    if (bytes_granularity == 0)\n        return res;\n    else\n        return std::max(res, (bytes_setting + bytes_granularity - 1) / bytes_granularity);\n}\n\n/// Same as roundRowsOrBytesToMarks() but do not return more then max_marks\nsize_t MergeTreeDataSelectExecutor::minMarksForConcurrentRead(\n    size_t rows_setting,\n    size_t bytes_setting,\n    size_t rows_granularity,\n    size_t bytes_granularity,\n    size_t max_marks)\n{\n    size_t marks = 1;\n\n    if (rows_setting + rows_granularity <= rows_setting) /// overflow\n        marks = max_marks;\n    else if (rows_setting)\n        marks = (rows_setting + rows_granularity - 1) / rows_granularity;\n\n    if (bytes_granularity == 0)\n        return marks;\n    else\n    {\n        /// Overflow\n        if (bytes_setting + bytes_granularity <= bytes_setting) /// overflow\n            return max_marks;\n        if (bytes_setting)\n            return std::max(marks, (bytes_setting + bytes_granularity - 1) / bytes_granularity);\n        else\n            return marks;\n    }\n}\n\n\n/// Calculates a set of mark ranges, that could possibly contain keys, required by condition.\n/// In other words, it removes subranges from whole range, that definitely could not contain required keys.\nMarkRanges MergeTreeDataSelectExecutor::markRangesFromPKRange(\n    const MergeTreeData::DataPartPtr & part,\n    const StorageMetadataPtr & metadata_snapshot,\n    const KeyCondition & key_condition,\n    const Settings & settings,\n    Poco::Logger * log)\n{\n    MarkRanges res;\n\n    size_t marks_count = part->index_granularity.getMarksCount();\n    const auto & index = part->index;\n    if (marks_count == 0)\n        return res;\n\n    bool has_final_mark = part->index_granularity.hasFinalMark();\n\n    /// If index is not used.\n    if (key_condition.alwaysUnknownOrTrue())\n    {\n        if (has_final_mark)\n            res.push_back(MarkRange(0, marks_count - 1));\n        else\n            res.push_back(MarkRange(0, marks_count));\n\n        return res;\n    }\n\n    size_t used_key_size = key_condition.getMaxKeyColumn() + 1;\n\n    std::function<void(size_t, size_t, FieldRef &)> create_field_ref;\n    /// If there are no monotonic functions, there is no need to save block reference.\n    /// Passing explicit field to FieldRef allows to optimize ranges and shows better performance.\n    const auto & primary_key = metadata_snapshot->getPrimaryKey();\n    if (key_condition.hasMonotonicFunctionsChain())\n    {\n        auto index_columns = std::make_shared<ColumnsWithTypeAndName>();\n        for (size_t i = 0; i < used_key_size; ++i)\n            index_columns->emplace_back(ColumnWithTypeAndName{index[i], primary_key.data_types[i], primary_key.column_names[i]});\n\n        create_field_ref = [index_columns](size_t row, size_t column, FieldRef & field)\n        {\n            field = {index_columns.get(), row, column};\n            // NULL_LAST\n            if (field.isNull())\n                field = POSITIVE_INFINITY;\n        };\n    }\n    else\n    {\n        create_field_ref = [&index](size_t row, size_t column, FieldRef & field)\n        {\n            index[column]->get(row, field);\n            // NULL_LAST\n            if (field.isNull())\n                field = POSITIVE_INFINITY;\n        };\n    }\n\n    /// NOTE Creating temporary Field objects to pass to KeyCondition.\n    std::vector<FieldRef> index_left(used_key_size);\n    std::vector<FieldRef> index_right(used_key_size);\n\n    auto may_be_true_in_range = [&](MarkRange & range)\n    {\n        if (range.end == marks_count && !has_final_mark)\n        {\n            for (size_t i = 0; i < used_key_size; ++i)\n            {\n                create_field_ref(range.begin, i, index_left[i]);\n                index_right[i] = POSITIVE_INFINITY;\n            }\n        }\n        else\n        {\n            if (has_final_mark && range.end == marks_count)\n                range.end -= 1; /// Remove final empty mark. It's useful only for primary key condition.\n\n            for (size_t i = 0; i < used_key_size; ++i)\n            {\n                create_field_ref(range.begin, i, index_left[i]);\n                create_field_ref(range.end, i, index_right[i]);\n            }\n        }\n        return key_condition.mayBeTrueInRange(\n            used_key_size, index_left.data(), index_right.data(), primary_key.data_types);\n    };\n\n    if (!key_condition.matchesExactContinuousRange())\n    {\n        // Do exclusion search, where we drop ranges that do not match\n\n        size_t min_marks_for_seek = roundRowsOrBytesToMarks(\n            settings.merge_tree_min_rows_for_seek,\n            settings.merge_tree_min_bytes_for_seek,\n            part->index_granularity_info.fixed_index_granularity,\n            part->index_granularity_info.index_granularity_bytes);\n\n        /** There will always be disjoint suspicious segments on the stack, the leftmost one at the top (back).\n        * At each step, take the left segment and check if it fits.\n        * If fits, split it into smaller ones and put them on the stack. If not, discard it.\n        * If the segment is already of one mark length, add it to response and discard it.\n        */\n        std::vector<MarkRange> ranges_stack = { {0, marks_count} };\n\n        size_t steps = 0;\n\n        while (!ranges_stack.empty())\n        {\n            MarkRange range = ranges_stack.back();\n            ranges_stack.pop_back();\n\n            steps++;\n\n            if (!may_be_true_in_range(range))\n                continue;\n\n            if (range.end == range.begin + 1)\n            {\n                /// We saw a useful gap between neighboring marks. Either add it to the last range, or start a new range.\n                if (res.empty() || range.begin - res.back().end > min_marks_for_seek)\n                    res.push_back(range);\n                else\n                    res.back().end = range.end;\n            }\n            else\n            {\n                /// Break the segment and put the result on the stack from right to left.\n                size_t step = (range.end - range.begin - 1) / settings.merge_tree_coarse_index_granularity + 1;\n                size_t end;\n\n                for (end = range.end; end > range.begin + step; end -= step)\n                    ranges_stack.emplace_back(end - step, end);\n\n                ranges_stack.emplace_back(range.begin, end);\n            }\n        }\n\n        LOG_TRACE(log, \"Used generic exclusion search over index for part {} with {} steps\", part->name, steps);\n    }\n    else\n    {\n        /// In case when SELECT's predicate defines a single continuous interval of keys,\n        /// we can use binary search algorithm to find the left and right endpoint key marks of such interval.\n        /// The returned value is the minimum range of marks, containing all keys for which KeyCondition holds\n\n        LOG_TRACE(log, \"Running binary search on index range for part {} ({} marks)\", part->name, marks_count);\n\n        size_t steps = 0;\n\n        MarkRange result_range;\n\n        size_t searched_left = 0;\n        size_t searched_right = marks_count;\n\n        while (searched_left + 1 < searched_right)\n        {\n            const size_t middle = (searched_left + searched_right) / 2;\n            MarkRange range(0, middle);\n            if (may_be_true_in_range(range))\n                searched_right = middle;\n            else\n                searched_left = middle;\n            ++steps;\n        }\n        result_range.begin = searched_left;\n        LOG_TRACE(log, \"Found (LEFT) boundary mark: {}\", searched_left);\n\n        searched_right = marks_count;\n        while (searched_left + 1 < searched_right)\n        {\n            const size_t middle = (searched_left + searched_right) / 2;\n            MarkRange range(middle, marks_count);\n            if (may_be_true_in_range(range))\n                searched_left = middle;\n            else\n                searched_right = middle;\n            ++steps;\n        }\n        result_range.end = searched_right;\n        LOG_TRACE(log, \"Found (RIGHT) boundary mark: {}\", searched_right);\n\n        if (result_range.begin < result_range.end && may_be_true_in_range(result_range))\n            res.emplace_back(std::move(result_range));\n\n        LOG_TRACE(log, \"Found {} range in {} steps\", res.empty() ? \"empty\" : \"continuous\", steps);\n    }\n\n    return res;\n}\n\n\nMarkRanges MergeTreeDataSelectExecutor::filterMarksUsingIndex(\n    MergeTreeIndexPtr index_helper,\n    MergeTreeIndexConditionPtr condition,\n    MergeTreeData::DataPartPtr part,\n    const MarkRanges & ranges,\n    const Settings & settings,\n    const MergeTreeReaderSettings & reader_settings,\n    size_t & total_granules,\n    size_t & granules_dropped,\n    MarkCache * mark_cache,\n    UncompressedCache * uncompressed_cache,\n    Poco::Logger * log)\n{\n    const std::string & path_prefix = part->getFullRelativePath() + index_helper->getFileName();\n    if (!index_helper->getDeserializedFormat(part->volume->getDisk(), path_prefix))\n    {\n        LOG_DEBUG(log, \"File for index {} does not exist ({}.*). Skipping it.\", backQuote(index_helper->index.name), path_prefix);\n        return ranges;\n    }\n\n    auto index_granularity = index_helper->index.granularity;\n\n    const size_t min_marks_for_seek = roundRowsOrBytesToMarks(\n        settings.merge_tree_min_rows_for_seek,\n        settings.merge_tree_min_bytes_for_seek,\n        part->index_granularity_info.fixed_index_granularity,\n        part->index_granularity_info.index_granularity_bytes);\n\n    size_t marks_count = part->getMarksCount();\n    size_t final_mark = part->index_granularity.hasFinalMark();\n    size_t index_marks_count = (marks_count - final_mark + index_granularity - 1) / index_granularity;\n\n    MergeTreeIndexReader reader(\n        index_helper, part,\n        index_marks_count,\n        ranges,\n        mark_cache,\n        uncompressed_cache,\n        reader_settings);\n\n    MarkRanges res;\n\n    /// Some granules can cover two or more ranges,\n    /// this variable is stored to avoid reading the same granule twice.\n    MergeTreeIndexGranulePtr granule = nullptr;\n    size_t last_index_mark = 0;\n    for (const auto & range : ranges)\n    {\n        MarkRange index_range(\n                range.begin / index_granularity,\n                (range.end + index_granularity - 1) / index_granularity);\n\n        if (last_index_mark != index_range.begin || !granule)\n            reader.seek(index_range.begin);\n\n        total_granules += index_range.end - index_range.begin;\n\n        for (size_t index_mark = index_range.begin; index_mark < index_range.end; ++index_mark)\n        {\n            if (index_mark != index_range.begin || !granule || last_index_mark != index_range.begin)\n                granule = reader.read();\n\n            MarkRange data_range(\n                    std::max(range.begin, index_mark * index_granularity),\n                    std::min(range.end, (index_mark + 1) * index_granularity));\n\n            if (!condition->mayBeTrueOnGranule(granule))\n            {\n                ++granules_dropped;\n                continue;\n            }\n\n            if (res.empty() || res.back().end - data_range.begin > min_marks_for_seek)\n                res.push_back(data_range);\n            else\n                res.back().end = data_range.end;\n        }\n\n        last_index_mark = index_range.end - 1;\n    }\n\n    return res;\n}\n\nvoid MergeTreeDataSelectExecutor::selectPartsToRead(\n    MergeTreeData::DataPartsVector & parts,\n    const std::optional<std::unordered_set<String>> & part_values,\n    const std::optional<KeyCondition> & minmax_idx_condition,\n    const DataTypes & minmax_columns_types,\n    std::optional<PartitionPruner> & partition_pruner,\n    const PartitionIdToMaxBlock * max_block_numbers_to_read,\n    PartFilterCounters & counters)\n{\n    MergeTreeData::DataPartsVector prev_parts;\n    std::swap(prev_parts, parts);\n    for (const auto & part_or_projection : prev_parts)\n    {\n        const auto * part = part_or_projection->isProjectionPart() ? part_or_projection->getParentPart() : part_or_projection.get();\n        if (part_values && part_values->find(part->name) == part_values->end())\n            continue;\n\n        if (part->isEmpty())\n            continue;\n\n        if (max_block_numbers_to_read)\n        {\n            auto blocks_iterator = max_block_numbers_to_read->find(part->info.partition_id);\n            if (blocks_iterator == max_block_numbers_to_read->end() || part->info.max_block > blocks_iterator->second)\n                continue;\n        }\n\n        size_t num_granules = part->getMarksCount();\n        if (num_granules && part->index_granularity.hasFinalMark())\n            --num_granules;\n\n        counters.num_initial_selected_parts += 1;\n        counters.num_initial_selected_granules += num_granules;\n\n        if (minmax_idx_condition && !minmax_idx_condition->checkInHyperrectangle(\n                part->minmax_idx->hyperrectangle, minmax_columns_types).can_be_true)\n            continue;\n\n        counters.num_parts_after_minmax += 1;\n        counters.num_granules_after_minmax += num_granules;\n\n        if (partition_pruner)\n        {\n            if (partition_pruner->canBePruned(*part))\n                continue;\n        }\n\n        counters.num_parts_after_partition_pruner += 1;\n        counters.num_granules_after_partition_pruner += num_granules;\n\n        parts.push_back(part_or_projection);\n    }\n}\n\nvoid MergeTreeDataSelectExecutor::selectPartsToReadWithUUIDFilter(\n    MergeTreeData::DataPartsVector & parts,\n    const std::optional<std::unordered_set<String>> & part_values,\n    MergeTreeData::PinnedPartUUIDsPtr pinned_part_uuids,\n    const std::optional<KeyCondition> & minmax_idx_condition,\n    const DataTypes & minmax_columns_types,\n    std::optional<PartitionPruner> & partition_pruner,\n    const PartitionIdToMaxBlock * max_block_numbers_to_read,\n    ContextPtr query_context,\n    PartFilterCounters & counters,\n    Poco::Logger * log)\n{\n    const Settings & settings = query_context->getSettings();\n\n    /// process_parts prepare parts that have to be read for the query,\n    /// returns false if duplicated parts' UUID have been met\n    auto select_parts = [&] (MergeTreeData::DataPartsVector & selected_parts) -> bool\n    {\n        auto ignored_part_uuids = query_context->getIgnoredPartUUIDs();\n        std::unordered_set<UUID> temp_part_uuids;\n\n        MergeTreeData::DataPartsVector prev_parts;\n        std::swap(prev_parts, selected_parts);\n        for (const auto & part_or_projection : prev_parts)\n        {\n            const auto * part = part_or_projection->isProjectionPart() ? part_or_projection->getParentPart() : part_or_projection.get();\n            if (part_values && part_values->find(part->name) == part_values->end())\n                continue;\n\n            if (part->isEmpty())\n                continue;\n\n            if (max_block_numbers_to_read)\n            {\n                auto blocks_iterator = max_block_numbers_to_read->find(part->info.partition_id);\n                if (blocks_iterator == max_block_numbers_to_read->end() || part->info.max_block > blocks_iterator->second)\n                    continue;\n            }\n\n            /// Skip the part if its uuid is meant to be excluded\n            if (part->uuid != UUIDHelpers::Nil && ignored_part_uuids->has(part->uuid))\n                continue;\n\n            size_t num_granules = part->getMarksCount();\n            if (num_granules && part->index_granularity.hasFinalMark())\n                --num_granules;\n\n            counters.num_initial_selected_parts += 1;\n            counters.num_initial_selected_granules += num_granules;\n\n            if (minmax_idx_condition\n                && !minmax_idx_condition->checkInHyperrectangle(part->minmax_idx->hyperrectangle, minmax_columns_types)\n                        .can_be_true)\n                continue;\n\n            counters.num_parts_after_minmax += 1;\n            counters.num_granules_after_minmax += num_granules;\n\n            if (partition_pruner)\n            {\n                if (partition_pruner->canBePruned(*part))\n                    continue;\n            }\n\n            counters.num_parts_after_partition_pruner += 1;\n            counters.num_granules_after_partition_pruner += num_granules;\n\n            /// populate UUIDs and exclude ignored parts if enabled\n            if (part->uuid != UUIDHelpers::Nil)\n            {\n                if (settings.experimental_query_deduplication_send_all_part_uuids || pinned_part_uuids->contains(part->uuid))\n                {\n                    auto result = temp_part_uuids.insert(part->uuid);\n                    if (!result.second)\n                        throw Exception(\"Found a part with the same UUID on the same replica.\", ErrorCodes::LOGICAL_ERROR);\n                }\n            }\n\n            selected_parts.push_back(part_or_projection);\n        }\n\n        if (!temp_part_uuids.empty())\n        {\n            auto duplicates = query_context->getPartUUIDs()->add(std::vector<UUID>{temp_part_uuids.begin(), temp_part_uuids.end()});\n            if (!duplicates.empty())\n            {\n                /// on a local replica with prefer_localhost_replica=1 if any duplicates appeared during the first pass,\n                /// adding them to the exclusion, so they will be skipped on second pass\n                query_context->getIgnoredPartUUIDs()->add(duplicates);\n                return false;\n            }\n        }\n\n        return true;\n    };\n\n    /// Process parts that have to be read for a query.\n    auto needs_retry = !select_parts(parts);\n\n    /// If any duplicated part UUIDs met during the first step, try to ignore them in second pass.\n    /// This may happen when `prefer_localhost_replica` is set and \"distributed\" stage runs in the same process with \"remote\" stage.\n    if (needs_retry)\n    {\n        LOG_DEBUG(log, \"Found duplicate uuids locally, will retry part selection without them\");\n\n        counters = PartFilterCounters();\n\n        /// Second attempt didn't help, throw an exception\n        if (!select_parts(parts))\n            throw Exception(\"Found duplicate UUIDs while processing query.\", ErrorCodes::DUPLICATED_PART_UUIDS);\n    }\n}\n\n}\n", "meta": {"hexsha": "106bca97a3850e0a1ef2a00cd1f50eac8155eda9", "size": 68041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp", "max_stars_repo_name": "540522905/ClickHouse", "max_stars_repo_head_hexsha": "299445ec7da10bd2ef62d8e333a95b7ab12bf5f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-15T16:35:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T12:39:52.000Z", "max_issues_repo_path": "src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp", "max_issues_repo_name": "540522905/ClickHouse", "max_issues_repo_head_hexsha": "299445ec7da10bd2ef62d8e333a95b7ab12bf5f2", "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/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp", "max_forks_repo_name": "540522905/ClickHouse", "max_forks_repo_head_hexsha": "299445ec7da10bd2ef62d8e333a95b7ab12bf5f2", "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.4284016637, "max_line_length": 139, "alphanum_fraction": 0.6462574036, "num_tokens": 14152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.1551020284111609}}
{"text": "/*\n\tgr-scan - A GNU Radio signal scanner\n\tCopyright (C) 2015 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.\n\tCopyright (C) 2012  Nicholas Tomlinson\n\n\tThis program is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <ctime>\n#include <set>\n#include <utility>\n\n#include <boost/shared_ptr.hpp>\n\n#include <gnuradio/block.h>\n#include <gnuradio/io_signature.h>\n#include <osmosdr/source.h>\n\n#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n#include <sys/ipc.h>\n#include <sys/shm.h>\n\n#define SHM_SIZE 1000000\n\nclass scanner_sink : public gr::block\n{\npublic:\n\tscanner_sink(osmosdr::source::sptr source, unsigned int vector_length, double start_freq,\n\t\t     double end_freq, double samples_per_second, double step, \n\t\tunsigned int avg_size, double def_gain, int use_AGC) :\n\t\tgr::block(\"scanner_sink\",\n\t\t\t  gr::io_signature::make(1, 1, sizeof (float) * vector_length),\n\t\t\t  gr::io_signature::make(0, 0, 0)),\n\t\tm_source(source), //We need the source in order to be able to control it\n\t\tm_buffer(new float[vector_length]), //buffer into which we accumulate the total for averaging\n\t\tm_vector_length(vector_length), //size of the FFT\n\t\tm_count(0), //number of FFTs totalled in the buffer\n\t\tm_wait_count(0), //number of times we've listenned on this frequency\n\t\tm_avg_size(avg_size), //the number of FFTs we should average over\n\t\tm_step(step), //the amount by which the frequency shold be incremented\n\t\tm_start_freq(start_freq), //start frequency\n\t\tm_end_freq(end_freq), //end frequency\n\t\tm_sps(samples_per_second), //samples per second\n\t\tm_start_time(time(0)), //the start time of the scan (useful for logging/reporting/monitoring)\n\t\tm_default_gain(def_gain)\n\t{\n\t\tcurrent_gain_RF = 0;\n\t\tcurrent_gain_IF = 0;\n\t\trf_gain_mod = 0; //compensation for RF gain not equal to 14dB in hardware\n\t\tagc_threshold_low = 0.01;\n\t\tagc_threshold_high = 2.0;\n\t\tagc_power_level = 0.5*(agc_threshold_high + agc_threshold_low); //init at value that won't force gain change at the beginning\n\n\t\tgain_change_timeout = 0;\n\t\tm_current_freq = start_freq;\n\t\tm_use_AGC = use_AGC;\n\n\t\tlast_log_out = 0;\n\t\tZeroBuffer();\n\t\tkey_t key = 47192032; //some random number that must be the same in monitor shared mem module\n\t\tint shmid;\n\n\t\tif ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) < 0) {\n\t\tprintf(\"shmget error!\\n\");\n\t\t}\n\n\t\tif ((shared_memory = (uint8_t*)shmat(shmid, NULL, 0)) == (uint8_t *) -1) {\n\t\tprintf(\"shmat error!\\n\");\n\t\t}\n\t}\n\n\tvirtual ~scanner_sink()\n\t{\n\t\tdelete []m_buffer; //delete the buffer\n\t}\n\nprivate:\n\tvirtual int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items)\n\t{\n\t\tfor (int i = 0; i < ninput_items[0]; ++i)\n\t\t\tProcessVector(static_cast<const float *>(input_items[0]) + i * m_vector_length);\n\n\t\tconsume_each(ninput_items[0]);\n\t\treturn 0;\n\t}\n\n\tvoid ProcessVector(const float *input)\n\t{\n\t\tfloat sample_max = -100;\n\t\tfloat sample_average = 0;\n\t\tfloat sample_top_average = 0;\n\t\tfloat avg_z = 0;\n\t\tfloat avg_top_z = 0;\n\t\tfloat signal_mult = 1.0;//pow(10, -(m_default_gain + current_gain) * 0.1);\n\t\tfor (unsigned int i = 0; i < m_vector_length; ++i)\n\t\t{\n\t\t\tif(i > 10 && i < m_vector_length - 10)\n\t\t\t{\n\t\t\t\tsample_average += input[i];\n\t\t\t\tavg_z++;\n\t\t\t\tif(sample_max < input[i]) sample_max = input[i];\n\t\t\t}\n\t\t\tm_buffer[i] += input[i]*signal_mult; //if gain is turned on, adjust signal to fit\n\t\t}\n\t\tsample_average /= avg_z;\n\t\t++m_count; //increment the total\n\n\t\tif(current_gain_RF > 1) rf_gain_mod = -7;\n\t\telse rf_gain_mod = 0;\n\t\tif(m_use_AGC)\n\t\t{\n\t\t\tfor (unsigned int i = 0; i < m_vector_length; ++i)\n\t\t\t{\n\t\t\t\tif(i > 10 && i < m_vector_length - 10)\n\t\t\t\t\tif(input[i] > sample_average)\n\t\t\t\t\t{\n\t\t\t\t\t\tsample_top_average += input[i];\n\t\t\t\t\t\tavg_top_z++;\n\t\t\t\t\t}\n\t\t\t}\n\t\t\tsample_top_average /= avg_top_z;\n\n\t\t\tagc_power_level *= 0.9;\n\t\t\tagc_power_level += 0.1 * sample_top_average;\n\n\t\t\tif(gain_change_timeout > 0) gain_change_timeout--;\n\n\t\t\tif(agc_power_level < agc_threshold_low && gain_change_timeout < 1) //increase gain\n\t\t\t{\n\t\t\t\tif(current_gain_RF < 1)\n\t\t\t\t\tcurrent_gain_RF = 14;\n\t\t\t\telse\n\t\t\t\t\tcurrent_gain_IF += 8;\n\t\t\t\tif(current_gain_IF > 40) current_gain_IF = 40;\n\t\t\t\tm_source->set_gain(current_gain_RF, \"RF\");\n\t\t\t\tm_source->set_gain(current_gain_IF, \"IF\");\n\t\t\t\tgain_change_timeout = 200;\n\t\t\t}\n\n\t\t\tif(agc_power_level > agc_threshold_high && gain_change_timeout < 1) //decrease gain\n\t\t\t{\n\t\t\t\tif(current_gain_IF > 0)\n\t\t\t\t\tcurrent_gain_IF -= 8;\n\t\t\t\telse\n\t\t\t\t\tcurrent_gain_RF = 0;\n\t\t\t\tif(current_gain_IF < 0) current_gain_IF = 0;\n\t\t\t\tm_source->set_gain(current_gain_RF, \"RF\");\n\t\t\t\tm_source->set_gain(current_gain_IF, \"IF\");\n\t\t\t\tgain_change_timeout = 200;\n\t\t\t}\n\t\t}\n\n\t\tif (m_count < m_avg_size) //we haven't yet averaged over the number we intended to\n\t\t\treturn;\n\n\n\t\tdouble freqs[m_vector_length]; //for convenience\n\t\tfloat bands0[m_vector_length]; //bands in order of frequency\n\n\t\tRearrange(bands0, freqs, m_current_freq, m_sps); //organise the buffer into a convenient order (saves to bands0)\n\t\tfor(unsigned int n = 0; n < m_vector_length; n++)\n\t\t{\n\t\t\tbands0[n] = 10*log10(bands0[n]) - 38.0 - (m_default_gain + current_gain_IF + current_gain_RF + rf_gain_mod);\n\t\t}\n\t\tPrintSignals(freqs, bands0);\n\n//\t\tm_source->set_gain(m_default_gain); //by default, set gain to match 1dBm\n//\t\tm_gain_mode = 1;\n\n\t\tm_count = 0; //next time, we're starting from scratch - so note this\n\t\tZeroBuffer(); //get ready to start again\n\n\t\t++m_wait_count; //we've just done another listen\n\t\tif(1){\n\t\t\tfor (;;) { //keep moving to the next frequency until we get to one we can listen on (copes with holes in the tunable range)\n\t\t\t\tif (m_current_freq >= m_end_freq) { //we reached the end!\n//\t\t\t\t\tm_step = -m_step;\n\t\t\t\t\t//do something to end the scan\n\t\t\t\t\tfprintf(stderr, \"[*] Finished range, starting again\\n\"); //say we're exiting\n\t\t\t\t\tm_current_freq = m_start_freq;\n//\t\t\t\t\texit(0); //TODO: This probably isn't the right thing, but it'll do for now\n\t\t\t\t}\n\n\t\t\t\tm_current_freq += m_step; //calculate the frequency we should change to\n\t\t\t\tdouble actual = m_source->set_center_freq(m_current_freq); //change frequency\n\t\t\t\tif (fabs(m_current_freq - actual) < 100.0) //success\n\t\t\t\t\tbreak; //so stop changing frequency\n\t\t\t}\n\t\t\tm_wait_count = 0; //new frequency - we've listened 0 times on it\n\t\t}\n\t}\n\n\tvoid PrintSignals(double *freqs, float *bands0)\n\t{\n\t\t/* Calculate the current time after start */\n\t\tunsigned int t = time(NULL) - m_start_time;\n\t\tunsigned int hours = t / 3600;\n\t\tunsigned int minutes = (t % 3600) / 60;\n\t\tunsigned int seconds = t % 60;\n\n\t\t//Print that we finished scanning something\n\t\tfprintf(stderr, \"%02u:%02u:%02u: Finished scanning %f MHz - %f MHz\\n\",\n\t\t\thours, minutes, seconds, (m_current_freq - m_sps/2.0)/1000000.0, (m_current_freq + m_sps/2.0)/1000000.0);\n\n\t\tif(fabs(m_current_freq - last_log_out) >= 1000000.0)\n\t\t{\n\t\t\tlast_log_out = m_current_freq;\n\t\t\tchar logfn[512];\n\t\t\tsprintf(logfn, \"logs/signal_%02u_%02u_%02u_%f_%f.txt\", hours, minutes, seconds, (m_current_freq - m_sps/2.0)/1000000.0, (m_current_freq + m_sps/2.0)/1000000.0);\n\t\t\tint log_file = open(logfn, O_WRONLY | O_CREAT, 0b110110110);\n\t\t\tif(log_file > 0)\n\t\t\t{\n\t\t\t\tchar line[1024];\n\t\t\t\tfor (unsigned int i = 0; i < m_vector_length; i++){\n\t\t\t\t\tint lng = sprintf(line, \"%g %g\\n\", freqs[i], bands0[i]);\n\t\t\t\t\tint sz = write(log_file, line, lng);\n\t\t\t\t\tif(sz < 0) printf(\"log file write failed\\n\");\n\t\t\t\t}\n\t\t\t\tclose(log_file);\n\t\t\t}\n\t\t}\n\t\tfloat *f_shm = (float*)shared_memory;\n\t\tint *i_shm = (int*)shared_memory;\n\t\ti_shm[4] = m_vector_length;\n\t\tf_shm[1] = current_gain_IF + current_gain_RF + rf_gain_mod + m_default_gain;\n\t\n\t\tint rpos = 0;\n\t\tfor(unsigned int r = 0; r < m_vector_length; r++)\n\t\t{\n\t\t\tf_shm[5 + rpos*2] = freqs[r];\n\t\t\tf_shm[6 + rpos*2] = bands0[r];\n\t\t\trpos++;\n\t\t}\n\n\t\ti_shm[0]++;\n\t}\n\n\tvoid Rearrange(float *bands, double *freqs, double centre, double bandwidth)\n\t{\n\t\tdouble samplewidth = bandwidth/(double)m_vector_length;\n\t\tfor (unsigned int i = 0; i < m_vector_length; ++i) {\n\t\t\t/* FFT is arranged starting at 0 Hz at the start, rather than in the middle */\n\t\t\tif (i < m_vector_length / 2) //lower half of the fft\n\t\t\t\tbands[i + m_vector_length / 2] = m_buffer[i] / static_cast<float>(m_avg_size);\n\t\t\telse //upper half of the fft\n\t\t\t\tbands[i - m_vector_length / 2] = m_buffer[i] / static_cast<float>(m_avg_size);\n\n\t\t\tfreqs[i] = centre + i * samplewidth - bandwidth / 2.0; //calculate the frequency of this sample\n\t\t}\n\t}\n\n\tvoid ZeroBuffer()\n\t{\n\t\t/* writes zeros to m_buffer */\n\t\tfor (unsigned int i = 0; i < m_vector_length; ++i)\n\t\t\tm_buffer[i] = 0.0;\n\t}\n\n\tstd::set<double> m_signals;\n\tosmosdr::source::sptr m_source;\n\tfloat *m_buffer;\n\tunsigned int m_vector_length;\n\tunsigned int m_count;\n\tunsigned int m_wait_count;\n\tunsigned int m_avg_size;\n\tdouble m_step;\n\tdouble m_start_freq;\n\tdouble m_current_freq;\n\tdouble m_end_freq;\n\tdouble m_sps;\n\ttime_t m_start_time;\n\tint m_gain_mode; //check whether gain was turned off already\n\tint m_use_AGC;\n\tdouble m_default_gain; //BB gain in dBm\n\tdouble agc_power_level;\n\tdouble agc_threshold_low;\n\tdouble agc_threshold_high;\n\tdouble current_gain_RF;\n\tdouble current_gain_IF;\n\tdouble rf_gain_mod;\n\t\n\tuint8_t *shared_memory; //memory shared with external monitor\n\tdouble last_log_out;\n\tint gain_change_timeout;\n};\n\n/* Shared pointer thing gnuradio is fond of */\ntypedef boost::shared_ptr<scanner_sink> scanner_sink_sptr;\nscanner_sink_sptr make_scanner_sink(osmosdr::source::sptr source, unsigned int vector_length, double start_freq, double end_freq, double samples_per_second,double step, unsigned int avg_size, double def_gain, int use_AGC)\n{\n\treturn boost::shared_ptr<scanner_sink>(new scanner_sink(source, vector_length, start_freq, end_freq, samples_per_second, step, avg_size, def_gain, use_AGC));\n}\n", "meta": {"hexsha": "b8a7ad26a7a6181b6a7115f76f98a529da951d63", "size": 10276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gr-scan-v/scanner_sink.hpp", "max_stars_repo_name": "ultimaterobotics/radio-scan-monitor", "max_stars_repo_head_hexsha": "f286789acab6cc1abcc133bc03c470801b73e52e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T07:22:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-10T07:22:46.000Z", "max_issues_repo_path": "gr-scan-v/scanner_sink.hpp", "max_issues_repo_name": "ultimaterobotics/radio-scan-monitor", "max_issues_repo_head_hexsha": "f286789acab6cc1abcc133bc03c470801b73e52e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gr-scan-v/scanner_sink.hpp", "max_forks_repo_name": "ultimaterobotics/radio-scan-monitor", "max_forks_repo_head_hexsha": "f286789acab6cc1abcc133bc03c470801b73e52e", "max_forks_repo_licenses": ["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.2556634304, "max_line_length": 221, "alphanum_fraction": 0.7015375633, "num_tokens": 3027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.15510201756470773}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <boost/program_options.hpp>\n\n#include <koinos/exception.hpp>\n#include <koinos/log.hpp>\n#include <koinos/crypto/elliptic.hpp>\n#include <koinos/crypto/multihash.hpp>\n#include <koinos/pack/classes.hpp>\n\n// Command line option definitions\n#define HELP_OPTION        \"help\"\n#define HELP_FLAG          \"h\"\n\n#define PRIVATE_KEY_OPTION \"private-key\"\n#define PRIVATE_KEY_FLAG   \"p\"\n\n#define WRAP_OPTION        \"wrap\"\n#define WRAP_FLAG          \"w\"\n\n// Sign the given transaction\nvoid sign_transaction( koinos::protocol::transaction& transaction, koinos::crypto::private_key& transaction_signing_key )\n{\n   // Signature is on the hash of the active data\n   koinos::multihash digest = koinos::crypto::hash( CRYPTO_SHA2_256_ID, transaction.active_data );\n   auto signature = transaction_signing_key.sign_compact( digest );\n   koinos::pack::to_variable_blob( transaction.signature_data, signature );\n}\n\n// Wrap the given transaction in a request\nkoinos::rpc::chain::chain_rpc_request wrap_transaction( koinos::protocol::transaction& transaction )\n{\n   // Construct a submit_transaction_request from the transaction\n   koinos::rpc::chain::submit_transaction_request transaction_request;\n   transaction_request.transaction = transaction;\n   transaction_request.verify_passive_data = true;\n   transaction_request.verify_transaction_signatures = true;\n\n   // Put the request in a chain_request\n   koinos::rpc::chain::chain_rpc_request chain_request;\n   chain_request = transaction_request;\n\n   return chain_request;\n}\n\n// Read a base58 WIF private key from the given file\nkoinos::crypto::private_key read_keyfile( std::string key_filename )\n{\n   // Read base58 wif string from given file\n   std::string key_string;\n   std::ifstream instream;\n   instream.open( key_filename );\n   std::getline( instream, key_string );\n   instream.close();\n\n   // Create and return the key from the wif\n   auto key = koinos::crypto::private_key::from_wif( key_string );\n   return key;\n}\n\nint main( int argc, char** argv )\n{\n   try\n   {\n      // Setup command line options\n      boost::program_options::options_description options( \"Options\" );\n      options.add_options()\n      ( HELP_OPTION \",\" HELP_FLAG,               \"print usage message\" )\n      ( PRIVATE_KEY_OPTION \",\" PRIVATE_KEY_FLAG, boost::program_options::value< std::string >()->default_value( \"private.key\" ), \"private key file\" )\n      ( WRAP_OPTION \",\" WRAP_FLAG,               \"wrap signed transaction in a request\" )\n      ;\n\n      // Parse command-line options\n      boost::program_options::variables_map vm;\n      boost::program_options::store( boost::program_options::parse_command_line( argc, argv, options ), vm );\n\n      // Handle help message\n      if ( vm.count( HELP_OPTION ) )\n      {\n         std::cout << \"Koinos Transaction Signing Tool\" << std::endl;\n         std::cout << \"Accepts a json transaction to sign via STDIN\" << std::endl;\n         std::cout << \"Returns the signed transaction via STDOUT\" << std::endl << std::endl;\n         std::cout << options << std::endl;\n         return EXIT_SUCCESS;\n      }\n\n      // Read options into variables\n      std::string key_filename = vm[ PRIVATE_KEY_OPTION ].as< std::string >();\n      bool wrap                = vm.count( WRAP_OPTION );\n      \n      // Read the keyfile\n      auto private_key = read_keyfile( key_filename );\n\n      // Read STDIN to a string\n      std::string transaction_json;\n      std::getline( std::cin, transaction_json );\n\n      // Parse and deserialize the json to a transaction\n      auto j = koinos::pack::json::parse( transaction_json );\n      koinos::protocol::transaction transaction;\n      koinos::pack::from_json( j, transaction );\n\n      // Sign the transaction\n      sign_transaction( transaction, private_key );\n\n      // Set the transaction id\n      transaction.id = koinos::crypto::hash( CRYPTO_SHA2_256_ID, transaction.active_data );\n\n      if (wrap) // Wrap the transaction if requested\n      {\n         auto request = wrap_transaction( transaction );\n         std::cout << request << std::endl;\n      }\n      else // Else simply output the signed transaction\n      {\n         std::cout << transaction << std::endl;\n      }\n\n      return EXIT_SUCCESS;\n   }\n   catch ( const boost::exception& e )\n   {\n      LOG(fatal) << boost::diagnostic_information( e ) << std::endl;\n   }\n   catch ( const std::exception& e )\n   {\n      LOG(fatal) << e.what() << std::endl;\n   }\n   catch ( ... )\n   {\n      LOG(fatal) << \"unknown exception\" << std::endl;\n   }\n\n   return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "5c0aa15aa3969234e2e9780ecb2d200726d49c5a", "size": 4552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/koinos_transaction_signer/main.cpp", "max_stars_repo_name": "arafat877/koinos-chain", "max_stars_repo_head_hexsha": "3773eaf326be5fcab271b1a411a8eb5282ed2b28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-27T19:48:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:48:51.000Z", "max_issues_repo_path": "programs/koinos_transaction_signer/main.cpp", "max_issues_repo_name": "arafat877/koinos-chain", "max_issues_repo_head_hexsha": "3773eaf326be5fcab271b1a411a8eb5282ed2b28", "max_issues_repo_licenses": ["MIT"], "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/koinos_transaction_signer/main.cpp", "max_forks_repo_name": "arafat877/koinos-chain", "max_forks_repo_head_hexsha": "3773eaf326be5fcab271b1a411a8eb5282ed2b28", "max_forks_repo_licenses": ["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.2262773723, "max_line_length": 149, "alphanum_fraction": 0.6693760984, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15507040683617732}}
{"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 2013-2020.\n// Modifications copyright (c) 2013-2020 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_ALGORITHMS_DETAIL_COVERED_BY_IMPLEMENTATION_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_COVERED_BY_IMPLEMENTATION_HPP\n\n#include <cstddef>\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/algorithms/detail/covered_by/interface.hpp>\n#include <boost/geometry/algorithms/detail/within/implementation.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace covered_by {\n\nstruct use_point_in_geometry\n{\n    template <typename Geometry1, typename Geometry2, typename Strategy>\n    static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& strategy)\n    {\n        return detail::within::covered_by_point_geometry(geometry1, geometry2, strategy);\n    }\n};\n\nstruct use_relate\n{\n    template <typename Geometry1, typename Geometry2, typename Strategy>\n    static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& strategy)\n    {\n        typedef typename detail::de9im::static_mask_covered_by_type\n            <\n                Geometry1, Geometry2\n            >::type covered_by_mask;\n        return geometry::relate(geometry1, geometry2, covered_by_mask(), strategy);\n    }\n};\n\n}} // namespace detail::covered_by\n#endif // DOXYGEN_NO_DETAIL\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate <typename Point, typename Box>\nstruct covered_by<Point, Box, point_tag, box_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(Point const& point, Box const& box, Strategy const& strategy)\n    {\n        return strategy.covered_by(point, box).apply(point, box);\n    }\n};\n\ntemplate <typename Box1, typename Box2>\nstruct covered_by<Box1, Box2, box_tag, box_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(Box1 const& box1, Box2 const& box2, Strategy const& strategy)\n    {\n        assert_dimension_equal<Box1, Box2>();\n        return strategy.covered_by(box1, box2).apply(box1, box2);\n    }\n};\n\n\n// P/P\n\ntemplate <typename Point1, typename Point2>\nstruct covered_by<Point1, Point2, point_tag, point_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename MultiPoint>\nstruct covered_by<Point, MultiPoint, point_tag, multi_point_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename MultiPoint, typename Point>\nstruct covered_by<MultiPoint, Point, multi_point_tag, point_tag>\n    : public detail::within::multi_point_point\n{};\n\ntemplate <typename MultiPoint1, typename MultiPoint2>\nstruct covered_by<MultiPoint1, MultiPoint2, multi_point_tag, multi_point_tag>\n    : public detail::within::multi_point_multi_point\n{};\n\n// P/L\n\ntemplate <typename Point, typename Segment>\nstruct covered_by<Point, Segment, point_tag, segment_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename Linestring>\nstruct covered_by<Point, Linestring, point_tag, linestring_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename MultiLinestring>\nstruct covered_by<Point, MultiLinestring, point_tag, multi_linestring_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename MultiPoint, typename Segment>\nstruct covered_by<MultiPoint, Segment, multi_point_tag, segment_tag>\n    : public detail::within::multi_point_single_geometry<false>\n{};\n\ntemplate <typename MultiPoint, typename Linestring>\nstruct covered_by<MultiPoint, Linestring, multi_point_tag, linestring_tag>\n    : public detail::within::multi_point_single_geometry<false>\n{};\n\ntemplate <typename MultiPoint, typename MultiLinestring>\nstruct covered_by<MultiPoint, MultiLinestring, multi_point_tag, multi_linestring_tag>\n    : public detail::within::multi_point_multi_geometry<false>\n{};\n\n// P/A\n\ntemplate <typename Point, typename Ring>\nstruct covered_by<Point, Ring, point_tag, ring_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename Polygon>\nstruct covered_by<Point, Polygon, point_tag, polygon_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename Point, typename MultiPolygon>\nstruct covered_by<Point, MultiPolygon, point_tag, multi_polygon_tag>\n    : public detail::covered_by::use_point_in_geometry\n{};\n\ntemplate <typename MultiPoint, typename Ring>\nstruct covered_by<MultiPoint, Ring, multi_point_tag, ring_tag>\n    : public detail::within::multi_point_single_geometry<false>\n{};\n\ntemplate <typename MultiPoint, typename Polygon>\nstruct covered_by<MultiPoint, Polygon, multi_point_tag, polygon_tag>\n    : public detail::within::multi_point_single_geometry<false>\n{};\n\ntemplate <typename MultiPoint, typename MultiPolygon>\nstruct covered_by<MultiPoint, MultiPolygon, multi_point_tag, multi_polygon_tag>\n    : public detail::within::multi_point_multi_geometry<false>\n{};\n\n// L/L\n\ntemplate <typename Linestring1, typename Linestring2>\nstruct covered_by<Linestring1, Linestring2, linestring_tag, linestring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Linestring, typename MultiLinestring>\nstruct covered_by<Linestring, MultiLinestring, linestring_tag, multi_linestring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring, typename Linestring>\nstruct covered_by<MultiLinestring, Linestring, multi_linestring_tag, linestring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring1, typename MultiLinestring2>\nstruct covered_by<MultiLinestring1, MultiLinestring2, multi_linestring_tag, multi_linestring_tag>\n    : public detail::covered_by::use_relate\n{};\n\n// L/A\n\ntemplate <typename Linestring, typename Ring>\nstruct covered_by<Linestring, Ring, linestring_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring, typename Ring>\nstruct covered_by<MultiLinestring, Ring, multi_linestring_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Linestring, typename Polygon>\nstruct covered_by<Linestring, Polygon, linestring_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring, typename Polygon>\nstruct covered_by<MultiLinestring, Polygon, multi_linestring_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Linestring, typename MultiPolygon>\nstruct covered_by<Linestring, MultiPolygon, linestring_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiLinestring, typename MultiPolygon>\nstruct covered_by<MultiLinestring, MultiPolygon, multi_linestring_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\n// A/A\n\ntemplate <typename Ring1, typename Ring2>\nstruct covered_by<Ring1, Ring2, ring_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Ring, typename Polygon>\nstruct covered_by<Ring, Polygon, ring_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Polygon, typename Ring>\nstruct covered_by<Polygon, Ring, polygon_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Polygon1, typename Polygon2>\nstruct covered_by<Polygon1, Polygon2, polygon_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Ring, typename MultiPolygon>\nstruct covered_by<Ring, MultiPolygon, ring_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiPolygon, typename Ring>\nstruct covered_by<MultiPolygon, Ring, multi_polygon_tag, ring_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename Polygon, typename MultiPolygon>\nstruct covered_by<Polygon, MultiPolygon, polygon_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiPolygon, typename Polygon>\nstruct covered_by<MultiPolygon, Polygon, multi_polygon_tag, polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\ntemplate <typename MultiPolygon1, typename MultiPolygon2>\nstruct covered_by<MultiPolygon1, MultiPolygon2, multi_polygon_tag, multi_polygon_tag>\n    : public detail::covered_by::use_relate\n{};\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_COVERED_BY_IMPLEMENTATION_HPP\n", "meta": {"hexsha": "80cdd539f9ba87f86c01a5c4dd57acdcee21eb3b", "size": 9128, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/covered_by/implementation.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/geometry/algorithms/detail/covered_by/implementation.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/geometry/algorithms/detail/covered_by/implementation.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": 32.8345323741, "max_line_length": 110, "alphanum_fraction": 0.7802366345, "num_tokens": 2166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.15487960125998765}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2019-2020, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, 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_STRATEGIES_IO_GEOGRAPHIC_HPP\n#define BOOST_GEOMETRY_STRATEGIES_IO_GEOGRAPHIC_HPP\n\n\n#include <boost/geometry/strategies/detail.hpp>\n#include <boost/geometry/strategies/io/services.hpp>\n\n#include <boost/geometry/strategies/geographic/point_order.hpp>\n#include <boost/geometry/strategies/geographic/point_in_poly_winding.hpp>\n#include <boost/geometry/strategies/spherical/point_in_point.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace io\n{\n\ntemplate\n    <\n        typename FormulaPolicy = strategy::andoyer,\n        typename Spheroid = srs::spheroid<double>,\n        typename CalculationType = void\n    >\nclass geographic\n    : public strategies::detail::geographic_base<Spheroid>\n{\n    using base_t = strategies::detail::geographic_base<Spheroid>;\n\npublic:\n    geographic()\n        : base_t()\n    {}\n\n    explicit geographic(Spheroid const& spheroid)\n        : base_t(spheroid)\n    {}\n\n    auto point_order() const\n    {\n        return strategy::point_order::geographic\n                <\n                    FormulaPolicy, Spheroid, CalculationType\n                >(base_t::m_spheroid);\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    static auto relate(Geometry1 const&, Geometry2 const&,\n                       std::enable_if_t\n                            <\n                                util::is_pointlike<Geometry1>::value\n                             && util::is_pointlike<Geometry2>::value\n                            > * = nullptr)\n    {\n        return strategy::within::spherical_point_point();\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    auto relate(Geometry1 const&, Geometry2 const&,\n                std::enable_if_t\n                    <\n                        util::is_pointlike<Geometry1>::value\n                        && ( util::is_linear<Geometry2>::value\n                        || util::is_polygonal<Geometry2>::value )\n                    > * = nullptr) const\n    {\n        return strategy::within::geographic_winding\n            <\n                void, void,\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n};\n\nnamespace services\n{\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, geographic_tag>\n{\n    typedef geographic<> type;\n};\n\n} // namespace services\n\n}} // namespace strategies::io\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_IO_GEOGRAPHIC_HPP\n", "meta": {"hexsha": "ed17c9d4a2b0e40de83256df1677184c43719d21", "size": 2711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/io/geographic.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/geometry/strategies/io/geographic.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/geometry/strategies/io/geographic.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.11, "max_line_length": 73, "alphanum_fraction": 0.6311324235, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3073580041760868, "lm_q1q2_score": 0.15487959486583305}}
{"text": "/**\n * Copyright (c) 2017 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 <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/replace.hpp>\n\n#include \"utility/premain.hpp\"\n#include \"utility/raise.hpp\"\n#include \"utility/format.hpp\"\n#include \"utility/path.hpp\"\n\n#include \"geo/heightcoding.hpp\"\n#include \"geo/srsfactors.hpp\"\n\n#include \"jsoncpp/json.hpp\"\n#include \"jsoncpp/as.hpp\"\n\n#include \"../support/python.hpp\"\n#include \"../support/serialization.hpp\"\n\n#include \"vts-libs/vts/opencv/navtile.hpp\"\n\n#include \"../support/python.hpp\"\n#include \"../support/tileindex.hpp\"\n#include \"../support/srs.hpp\"\n#include \"../support/revision.hpp\"\n\n#include \"./geodata-vector-tiled.hpp\"\n#include \"./factory.hpp\"\n#include \"./metatile.hpp\"\n\nnamespace ba = boost::algorithm;\n\nnamespace vr = vtslibs::registry;\nnamespace fs = boost::filesystem;\n\nnamespace generator {\n\nnamespace {\n\nstruct Factory : Generator::Factory {\n    virtual Generator::pointer create(const Generator::Params &params)\n    {\n        return std::make_shared<GeodataVectorTiled>(params);\n    }\n\nprivate:\n    static utility::PreMain register_;\n};\n\nutility::PreMain Factory::register_([]()\n{\n    Generator::registerType<GeodataVectorTiled>(std::make_shared<Factory>());\n});\n\n/** NOTICE: increment each time some data-related bug is fixed.\n */\nint GeneratorRevision(0);\n\n} // namespace\n\nGeodataVectorTiled::GeodataVectorTiled(const Params &params)\n    : GeodataVectorBase(params, true)\n    , definition_(this->resource().definition<Definition>())\n    , dem_(absoluteDataset(definition_.dem.dataset + \"/dem\")\n           , definition_.dem.geoidGrid)\n    , effectiveGsdArea_(), effectiveGsdAreaComputed_(false)\n    , tileFile_(definition_.dataset)\n    , physicalSrs_\n      (vr::system.srs(resource().referenceFrame->model.physicalSrs))\n{\n    {\n        // open dataset and get descriptor + metadata\n        auto ds(geo::GeoDataset::open(dem_.dataset));\n        demDescriptor_ = ds.descriptor();\n\n        auto md(ds.getMetadata(\"vts\"));\n\n        if (auto effectiveGSD = md.get<double>(\"effectiveGSD\")) {\n            effectiveGsdArea_ = (*effectiveGSD * *effectiveGSD);\n\n            LOG(info2)\n                << \"<\" << id() << \">: using configured effective GSD area of \"\n                << definition_.dem.dataset << \": \"\n                << effectiveGsdArea_ << \" m2.\";\n        } else {\n            auto esize(math::size(demDescriptor_.extents));\n            auto srs(demDescriptor_.srs.reference());\n            if (srs.IsGeographic()) {\n                // geographic coordinates system -> convert degrees to meters\n                double a(srs.GetSemiMajor());\n                // double b(srs.GetSemiMinor());\n\n                esize.width *= (a * M_PI / 180.0);\n\n                // TODO: compute length of arc between extents.ll(1) nad\n                // extents.ur(1) on the ellipsoid\n                // for now, use same calculation as on the equator\n                esize.height *= (a * M_PI / 180.0);\n            }\n\n            math::Size2f px(esize.width / demDescriptor_.size.width\n                            , esize.height / demDescriptor_.size.height);\n\n            effectiveGsdArea_ = math::area(px);\n            effectiveGsdAreaComputed_ = true;\n\n            LOG(info2)\n                << id() << \": using computed effective GSD area \"\n                << definition_.dem.dataset << \": \"\n                << effectiveGsdArea_ << \" m2.\";\n        }\n    }\n\n    if (changeEnforced()) {\n        LOG(info1) << \"Generator for <\" << id() << \"> not ready.\";\n        return;\n    }\n\n    try {\n        auto indexPath(root() / \"tileset.index\");\n        auto deliveryIndexPath(root() / \"delivery.index\");\n\n        if (fs::exists(indexPath)) {\n            if (!fs::exists(deliveryIndexPath)) {\n                // no delivery index -> create\n                vts::tileset::Index index(referenceFrame().metaBinaryOrder);\n                vts::tileset::loadTileSetIndex(index, indexPath);\n\n                // convert it to delivery index (using a temporary file)\n                const auto tmpPath(utility::addExtension\n                                   (deliveryIndexPath, \".tmp\"));\n                mmapped::TileIndex::write(tmpPath, index.tileIndex);\n                fs::rename(tmpPath, deliveryIndexPath);\n            }\n\n            // load delivery index\n            index_ = boost::in_place(referenceFrame().metaBinaryOrder\n                                     , deliveryIndexPath);\n            makeReady();\n            return;\n        }\n    } catch (const std::exception &e) {\n        // not ready\n    }\n\n    LOG(info1) << \"Generator for <\" << id() << \"> not ready.\";\n}\n\nvoid GeodataVectorTiled::prepare_impl(Arsenal&)\n{\n    LOG(info2) << \"Preparing <\" << id() << \">.\";\n\n    const auto &r(resource());\n\n    // try to open datasets\n    geo::GeoDataset::open(dem_.dataset);\n    geo::GeoDataset::open(dem_.dataset + \".min\");\n    geo::GeoDataset::open(dem_.dataset + \".max\");\n\n    // prepare tile index\n    {\n        vts::tileset::Index index(referenceFrame().metaBinaryOrder);\n        prepareTileIndex(index\n                         , (absoluteDataset(definition_.dem.dataset)\n                            + \"/tiling.\" + r.id.referenceFrame)\n                         , r);\n\n        // save it all\n        vts::tileset::saveTileSetIndex(index, root() / \"tileset.index\");\n\n        const auto deliveryIndexPath(root() / \"delivery.index\");\n        // convert it to delivery index (using a temporary file)\n        const auto tmpPath(utility::addExtension\n                           (deliveryIndexPath, \".tmp\"));\n        mmapped::TileIndex::write(tmpPath, index.tileIndex);\n        fs::rename(tmpPath, deliveryIndexPath);\n\n        index_ = boost::in_place(referenceFrame().metaBinaryOrder\n                                 , deliveryIndexPath);\n    }\n}\n\nvr::FreeLayer GeodataVectorTiled::freeLayer_impl(ResourceRoot root) const\n{\n    const auto &res(resource());\n\n    vr::FreeLayer fl;\n    fl.id = res.id.fullId();\n    fl.type = vr::FreeLayer::Type::geodataTiles;\n\n    auto &def(fl.createDefinition<vr::FreeLayer::GeodataTiles>());\n    def.metaUrl = prependRoot\n        (utility::format(\"{lod}-{x}-{y}.meta?gr=%d-%d%s\", GeneratorRevision\n                         , vts::MetaTile::currentVersion()\n                         , RevisionWrapper(res.revision, \"&\"))\n         , resource(), root);\n    def.geodataUrl = prependRoot\n        (utility::format(\"{lod}-{x}-{y}.geo?gr=%d%s&viewspec={viewspec}\"\n                         , GeneratorRevision\n                         , RevisionWrapper(res.revision, \"&\"))\n         , resource(), root);\n    def.style = styleUrl();\n\n    def.lodRange = res.lodRange;\n    def.tileRange = res.tileRange;\n    fl.credits = asInlineCredits(res);\n\n    // done\n    return fl;\n}\n\nvts::MapConfig GeodataVectorTiled::mapConfig_impl(ResourceRoot root)\n    const\n{\n    const auto &res(resource());\n\n    vts::MapConfig mapConfig;\n    mapConfig.referenceFrame = *res.referenceFrame;\n    mapConfig.srs = vr::listSrs(*res.referenceFrame);\n\n    // add free layer into list of free layers\n    mapConfig.freeLayers.add\n        (vr::FreeLayer\n         (res.id.fullId()\n          , prependRoot(std::string(\"freelayer.json\"), resource(), root)));\n\n    // add free layer into view\n    mapConfig.view.freeLayers[res.id.fullId()];\n\n    if (definition_.introspection.surface) {\n        LOG(info1) << \"trying to find surface\";\n        if (auto other = otherGenerator\n            (Resource::Generator::Type::surface\n             , addReferenceFrame(*definition_.introspection.surface\n                                 , referenceFrameId())))\n        {\n            mapConfig.merge(other->mapConfig\n                            (resolveRoot(resource(), other->resource())));\n        }\n    }\n\n    // browser options (must be Json::Value!); overrides browser options from\n    // surface's introspection\n    if (!definition_.introspection.browserOptions.empty()) {\n        mapConfig.browserOptions = definition_.introspection.browserOptions;\n    }\n\n    // done\n    return mapConfig;\n}\n\nvoid GeodataVectorTiled::generateMetatile(Sink &sink\n                                          , const GeodataFileInfo &fi\n                                          , Arsenal &arsenal) const\n{\n    sink.checkAborted();\n\n    if (!index_->meta(fi.tileId)) {\n        sink.error(utility::makeError<NotFound>(\"Metatile not found.\"));\n        return;\n    }\n\n    auto metatile(metatileFromDem\n                  (fi.tileId, sink, arsenal, resource()\n                   , index_->tileIndex, dem_.dataset\n                   , dem_.geoidGrid\n                   , MaskTree(), definition_.displaySize));\n\n    // write metatile to stream\n    std::ostringstream os;\n    metatile.save(os);\n    sink.content(os.str(), fi.sinkFileInfo());\n}\n\nvoid GeodataVectorTiled::generateGeodata(Sink &sink\n                                         , const GeodataFileInfo &fi\n                                         , Arsenal &arsenal) const\n{\n    const auto &tileId(fi.tileId);\n    auto flags(index_->tileIndex.get(tileId));\n    if (!vts::TileIndex::Flag::isReal(flags)) {\n        sink.error(utility::makeError<NotFound>(\"No geodata for this tile.\"));\n        return;\n    }\n\n    vts::NodeInfo nodeInfo(referenceFrame(), tileId);\n    if (!nodeInfo.productive()) {\n        sink.error(utility::makeError<NotFound>\n                   (\"TileId outside of valid reference frame tree.\"));\n        return;\n    }\n\n    auto sourceTileId(tileId);\n    auto sourceLocalId(vts::local(nodeInfo.rootLod(), sourceTileId));\n    auto tileExtents(nodeInfo.extents());\n\n    bool cutting(false);\n\n    if (definition_.maxSourceLod && (sourceLocalId.lod\n                                     > *definition_.maxSourceLod))\n    {\n        // shift source to proper layer\n        auto lodDiff(sourceLocalId.lod - *definition_.maxSourceLod);\n        sourceTileId = vts::parent(sourceTileId, lodDiff);\n        sourceLocalId = vts::parent(sourceLocalId, lodDiff);\n        tileExtents = vts::NodeInfo(referenceFrame(), sourceTileId).extents();\n        cutting = true;\n    }\n\n    const auto tileFile\n        (absoluteDataset\n         (tileFile_(vts::UrlTemplate::Vars(sourceTileId, sourceLocalId))));\n\n    LOG(info1) << \"Using geo file: <\" << tileFile << \">.\";\n\n    // combine all dem datasets and default/fallback dem dataset\n    auto datasets(viewspec2datasets(fi.fileInfo.query, dem_));\n\n    geo::heightcoding::Config config;\n    config.workingSrs = sds(nodeInfo, dem_.geoidGrid);\n    config.outputSrs = boost::in_place\n        (physicalSrs_.srsDef, physicalSrs_.adjustVertical());\n    config.layers = definition_.layers;\n    config.format = definition_.format;\n    config.formatConfig = definition_.formatConfig;\n    config.mode = definition_.mode;\n\n    if (cutting) {\n        // clip whole tile to node extents\n        config.clipWorkingExtents = nodeInfo.extents();\n    } else if (definition_.clipLayers) {\n        // clip only given layers\n        config.clipWorkingExtents = nodeInfo.extents();\n        config.clipLayers = definition_.clipLayers;\n    }\n\n    // build open options for MVT driver\n    GdalWarper::OpenOptions openOptions;\n    {\n        std::ostringstream os;\n        os << \"@MVT_EXTENTS=\" << std::fixed << tileExtents;\n        openOptions.push_back(os.str());\n\n        os.str(\"\");\n        os << \"@MVT_SRS=\" << *config.workingSrs;\n        openOptions.push_back(os.str());\n    }\n\n    // heightcode data using warper's machinery\n    auto hc(arsenal.warper.heightcode\n            (tileFile, datasets.first, config, dem_.geoidGrid\n             , openOptions, layerEnhancers(), sink));\n\n    // force 1 hour max age if not all views from viewspec have been found\n    boost::optional<long> maxAge;\n    if (!datasets.second) { maxAge = 3600; }\n\n    sink.content(hc->data, hc->size\n                 , fi.sinkFileInfo().setMaxAge(maxAge), true);\n}\n\n} // namespace generator\n", "meta": {"hexsha": "faf0f0dfa4703b96ddaedfbbbbba3175c9fa71b1", "size": 13142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mapproxy/src/mapproxy/generator/geodata-vector-tiled.cpp", "max_stars_repo_name": "maka-io/vts-mapproxy", "max_stars_repo_head_hexsha": "13c70b1bd2013d76b387900fae839e3948e741c3", "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": "mapproxy/src/mapproxy/generator/geodata-vector-tiled.cpp", "max_issues_repo_name": "maka-io/vts-mapproxy", "max_issues_repo_head_hexsha": "13c70b1bd2013d76b387900fae839e3948e741c3", "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": "mapproxy/src/mapproxy/generator/geodata-vector-tiled.cpp", "max_forks_repo_name": "maka-io/vts-mapproxy", "max_forks_repo_head_hexsha": "13c70b1bd2013d76b387900fae839e3948e741c3", "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.9586563307, "max_line_length": 78, "alphanum_fraction": 0.6133769594, "num_tokens": 2965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.27512972976675254, "lm_q1q2_score": 0.15467147280628338}}
{"text": "#include \"TTree.h\"\n#include \"TStyle.h\"\n#include \"TMath.h\"\n#include \"TFile.h\"\n#include \"TH1F.h\"\n#include \"TH2F.h\"\n#include \"TF1.h\"\n#include \"TCut.h\"\n#include \"TLegend.h\"\n#include \"TCanvas.h\"\n#include \"TProfile.h\"\n#include \"TMath.h\"\n#include \"TPaveText.h\"\n#include \"TLeaf.h\"\n#include \"TLine.h\"\n#include \"TArrow.h\"\n#include \"TRandom2.h\"\n#include \"TRandom3.h\"\n#include \"TRolke.h\"\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <cmath>\n#include <algorithm>\n#include \"TRandom3.h\"\n#include \"TFrame.h\"\n//#include <boost/lexical_cast.hpp>\n//#include <boost/timer.hpp>\n\n#include <TChain.h>\n#include <string>\n#include <fstream>\n\n#include <TLimit.h>\n#include <TConfidenceLevel.h>\n#include <TLimitDataSource.h>\n#include \"Riostream.h\"\n#include \"TMath.h\"\n#include \"TNtuple.h\"\n   \n#include \"TObject.h\"\n#include \"TString.h\"\n#include \"TGraph.h\"\n\n#include \"TFile.h\"\n#include <cstdio>\n#include \"TAxis.h\"\n\n\n#include <iostream>\n#include <iomanip>\n#include \"TSystem.h\"\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TH2.h\"\n#include \"TTree.h\"\n#include \"TF1.h\"\n#include \"TMath.h\"\n#include \"TFitResult.h\"\n#include \"TChain.h\"\n#include \"TLegend.h\"\n#include \"TCanvas.h\"\n#include \"TLine.h\"\n#include \"TLatex.h\"\n#include \"TVector.h\"\n#include \"TLorentzVector.h\"\n\n#include \"TGraphErrors.h\"\n#include \"TFitResultPtr.h\"\n#include \"TBox.h\"\n#include \"TAxis.h\"\nusing namespace std;\n\nDouble_t getMedian(TH1F* histo,Double_t x, Double_t q){\n  histo->ComputeIntegral();\n  histo->GetQuantiles(1,&x,&q);\n  return x;\n}\n\nvoid rhbDictRankMedian()\n\n{\n\n  std::ofstream analysisOut;\n  std::ofstream bothOut;\n  \n  analysisOut.open(\"analysisRHB.txt\");\n   bothOut.open(\"bothRHB.txt\");\n   //  std::ifstream inputFiles(\"TestOneSpreadsheet.txt\");\n  std::ifstream inputFiles(\"annotated_v5_ALL.txt\");\n  \n  std::vector<std::string> letterFileList;\n  std::string letterLine;\n\n\n  while(std::getline(inputFiles,letterLine))\n    {\n      letterFileList.push_back(letterLine);\n      //     std::cout << \"checking \" << letterLine << std::endl;\n      //     std::cout << physicscMrMLine << std::endl;\n    }\n\n  analysisOut << \" past initial while loop\" << std::endl;\n  Int_t letterLength = letterFileList.size();\n  analysisOut << \"length of letter list = \" << letterLength << std::endl;\n \n  \n  /*********analyze**************/\n  Int_t cat;\n\n  Bool_t useBoth;\n  useBoth = false;\n  Int_t wc; Int_t disp;\n  string rowHash;\n  string rowNo,bobHash;\n\n  Float_t Analytic,Clout,Authentic,Tone,WPS, Dic, function, pronoun, ppron, i, we, you , shehe, they, ipron, article, prep, auxverb, adverb, conj, negate, verb, adj, compare, interrog, number, quant,\n    affect, posemo, negemo, anx, anger, sad ,\n    social , family, friends, female, male, cogproc, insight, cause, discrep, tentat, certain, differ, percept, see, hear, feel, bio, body, health, sexual, ingest, drives, affiliation,\n    achiev,power,reward,risk,focuspast,focuspresent,focusfuture ,\n    relativ,motion,space,time,work,leisure,home,money,relig,death,informal,swear,netspeak,assent,nonflu,filler,AllPunc,Period,Comma,Colon,SemiC,QMark,Exclam,Dash,Quote,\n    Apostro,Parent,OtherP;\n\n  Int_t canGender, writerGender,both,candId,writerId,discipline;\n  string candidateName;\n  Int_t wcCut;\n\n  \n  Int_t Ref_is_advisor, Ref_nonresearch,both_gender_non_advisor_refs;\n\n  Float_t standout, ability, grindstone , teaching , research , agentic, communal, comparisonMale , comparisonFemale, signalPhysics, signalSociology , ranking, negative;\n  \n  Int_t nlines = 0;\n  TFile* f = new TFile(\"lexicalAnalysisRHBGt1000.root\", \"RECREATE\");\n  TH1F* wordCountPhysicscMrM = new TH1F(\"wordCountWilsoncMrM\", \" number of words in Wilson letter, cMrM \",100,0.,5000.);\n  TH1F* wordCountPhysicscFrM = new TH1F(\"wordCountWilsoncFrM\", \" number of words in Wilson letter, cFrM \",100,0.,5000.);\n  TH1F* wordCountPhysicscFrF = new TH1F(\"wordCountWilsoncFrF\", \" number of words in Wilson letter, cFrF \",100,0.,5000.);\n  TH1F* wordCountPhysicscMrF = new TH1F(\"wordCountWilsoncMrF\", \" number of words in Wilson letter, cMrF \",100,0.,5000.);\n\n  TH1F* wordCountSocScicMrM = new TH1F(\"wordCountSocScicMrM\", \" number of words in Cornell letter, cMrM \",100,0.,5000.);\n  TH1F* wordCountSocScicFrM = new TH1F(\"wordCountSocScicFrM\", \" number of words in Cornell letter, cFrM \",100,0.,5000.);\n  TH1F* wordCountSocScicFrF = new TH1F(\"wordCountSocScicFrF\", \" number of words in Cornell letter, cFrF \",100,0.,5000.);\n  TH1F* wordCountSocScicMrF = new TH1F(\"wordCountSocScicMrF\", \" number of words in Cornell letter, cMrF \",100,0.,5000.);\n\n\n  TH1F* agenticPhysicscMrM = new TH1F(\"agenticWilsoncMrM\", \" rate of agentic words in Wilson letter, cMrM \",50,0.,5.);\n  TH1F* agenticPhysicscFrM = new TH1F(\"agenticWilsoncFrM\", \" rate of agentic words in Wilson letter, cFrM \",50,0.,5.);\n  TH1F* agenticPhysicscFrF = new TH1F(\"agenticWilsoncFrF\", \" rate of agentic words in Wilson letter, cFrF \",50,0.,5.);\n  TH1F* agenticPhysicscMrF = new TH1F(\"agenticWilsoncMrF\", \" rate of agentic words in Wilson letter, cMrF \",50,0.,5.);\n\n  TH1F* agenticSocScicMrM = new TH1F(\"agenticSocScicMrM\", \" rate of agentic words in Cornell letter, cMrM \",50,0.,5.);\n  TH1F* agenticSocScicFrM = new TH1F(\"agenticSocScicFrM\", \" rate of agentic words in Cornell letter, cFrM \",50,0.,5.);\n  TH1F* agenticSocScicFrF = new TH1F(\"agenticSocScicFrF\", \" rate of agentic words in Cornell letter, cFrF \",50,0.,5.);\n  TH1F* agenticSocScicMrF = new TH1F(\"agenticSocScicMrF\", \" rate of agentic words in Cornell letter, cMrF \",50,0.,5.);\n\n  TH1F* communalPhysicscMrM = new TH1F(\"communalWilsoncMrM\", \" rate of communal words in Wilson letter, cMrM \",50,0.,5.);\n  TH1F* communalPhysicscFrM = new TH1F(\"communalWilsoncFrM\", \" rate of communal words in Wilson letter, cFrM \",50,0.,5.);\n  TH1F* communalPhysicscFrF = new TH1F(\"communalWilsoncFrF\", \" rate of communal words in Wilson letter, cFrF \",50,0.,5.);\n  TH1F* communalPhysicscMrF = new TH1F(\"communalWilsoncMrF\", \" rate of communal words in Wilson letter, cMrF \",50,0.,5.);\n\n  TH1F* communalSocScicMrM = new TH1F(\"communalSocScicMrM\", \" rate of communal words in Cornell letter, cMrM \",50,0.,5.);\n  TH1F* communalSocScicFrM = new TH1F(\"communalSocScicFrM\", \" rate of communal words in Cornell letter, cFrM \",50,0.,5.);\n  TH1F* communalSocScicFrF = new TH1F(\"communalSocScicFrF\", \" rate of communal words in Cornell letter, cFrF \",50,0.,5.);\n  TH1F* communalSocScicMrF= new TH1F(\"communalSocScicMrF\", \" rate of communal words in Cornell letter, cMrF \",50,0.,5.);\n\n  TH1F* standoutPhysicscMrM = new TH1F(\"standoutWilsoncMrM\", \" rate of standout words in Wilson letter, cMrM \",50,0.,5.);\n  TH1F* standoutPhysicscFrM = new TH1F(\"standoutWilsoncFrM\", \" rate of standout words in Wilson letter, cFrM \",50,0.,5.);\n  TH1F* standoutPhysicscFrF = new TH1F(\"standoutWilsoncFrF\", \" rate of standout words in Wilson letter, cFrF \",50,0.,5.);\n  TH1F* standoutPhysicscMrF = new TH1F(\"standoutWilsoncMrF\", \" rate of standout words in Wilson letter, cMrF \",50,0.,5.);\n\n  TH1F* standoutSocScicMrM = new TH1F(\"standoutSocScicMrM\", \" rate of standout words in Cornell letter, cMrM \",50,0.,5.);\n  TH1F* standoutSocScicFrM = new TH1F(\"standoutSocScicFrM\", \" rate of standout words in Cornell letter, cFrM \",50,0.,5.);\n  TH1F* standoutSocScicFrF = new TH1F(\"standoutSocScicFrF\", \" rate of standout words in Cornell letter, cFrF \",50,0.,5.);\n  TH1F* standoutSocScicMrF = new TH1F(\"standoutSocScicMrF\", \" rate of standout words in Cornell letter, cMrF \",50,0.,5.);\n\n  TH1F* abilityPhysicscMrM = new TH1F(\"abilityWilsoncMrM\", \" rate of ability words in Wilson letter, cMrM \",50,0.,5.);\n  TH1F* abilityPhysicscFrM = new TH1F(\"abilityWilsoncFrM\", \" rate of ability words in Wilson letter, cFrM \",50,0.,5.);\n  TH1F* abilityPhysicscFrF = new TH1F(\"abilityWilsoncFrF\", \" rate of ability words in Wilson letter, cFrF \",50,0.,5.);\n  TH1F* abilityPhysicscMrF = new TH1F(\"abilityWilsoncMrF\", \" rate of ability words in Wilson letter, cMrF \",50,0.,5.);\n\n  TH1F* comparisonFemalePhysicscMrM = new TH1F(\"comparisonFemaleWilsoncMrM\", \" rate of comparisonFemale words in Wilson letter, cMrM \",50,0.,5.);\n  TH1F* comparisonFemalePhysicscFrM = new TH1F(\"comparisonFemaleWilsoncFrM\", \" rate of comparisonFemale words in Wilson letter, cFrM \",50,0.,5.);\n  TH1F* comparisonFemalePhysicscFrF = new TH1F(\"comparisonFemaleWilsoncFrF\", \" rate of comparisonFemale words in Wilson letter, cFrF \",50,0.,5.);\n  TH1F* comparisonFemalePhysicscMrF = new TH1F(\"comparisonFemaleWilsoncMrF\", \" rate of comparisonFemale words in Wilson letter, cMrF \",50,0.,5.);\n\n  TH1F* comparisonMalePhysicscMrM = new TH1F(\"comparisonMaleWilsoncMrM\", \" rate of comparisonMale words in Wilson letter, cMrM \",50,0.,5.);\n  TH1F* comparisonMalePhysicscFrM = new TH1F(\"comparisonMaleWilsoncFrM\", \" rate of comparisonMale words in Wilson letter, cFrM \",50,0.,5.);\n  TH1F* comparisonMalePhysicscFrF = new TH1F(\"comparisonMaleWilsoncFrF\", \" rate of comparisonMale words in Wilson letter, cFrF \",50,0.,5.);\n  TH1F* comparisonMalePhysicscMrF = new TH1F(\"comparisonMaleWilsoncMrF\", \" rate of comparisonMale words in Wilson letter, cMrF \",50,0.,5.);\n\n  TH1F* abilitySocScicMrM = new TH1F(\"abilitySocScicMrM\", \" rate of ability words in Cornell letter, cMrM \",50,0.,5.);\n  TH1F* abilitySocScicFrM = new TH1F(\"abilitySocScicFrM\", \" rate of ability words in Cornell letter, cFrM \",50,0.,5.);\n  TH1F* abilitySocScicFrF = new TH1F(\"abilitySocScicFrF\", \" rate of ability words in Cornell letter, cFrF \",50,0.,5.);\n  TH1F* abilitySocScicMrF = new TH1F(\"abilitySocScicMrF\", \" rate of ability words in Cornell letter, cMrF \",50,0.,5.);\n\n  TH1F* grindstonePhysicscMrM = new TH1F(\"grindstoneWilsoncMrM\", \" rate of grindstone words in Wilson letter, cMrM \",50,0.,5.);\n  TH1F* grindstonePhysicscFrM = new TH1F(\"grindstoneWilsoncFrM\", \" rate of grindstone words in Wilson letter, cFrM \",50,0.,5.);\n  TH1F* grindstonePhysicscFrF = new TH1F(\"grindstoneWilsoncFrF\", \" rate of grindstone words in Wilson letter, cFrF \",50,0.,5.);\n  TH1F* grindstonePhysicscMrF = new TH1F(\"grindstoneWilsoncMrF\", \" rate of grindstone words in Wilson letter, cMrF \",50,0.,5.);\n\n  TH1F* grindstoneSocScicMrM = new TH1F(\"grindstoneSocScicMrM\", \" rate of grindstone words in Cornell letter, cMrM \",50,0.,5.);\n  TH1F* grindstoneSocScicFrM = new TH1F(\"grindstoneSocScicFrM\", \" rate of grindstone words in Cornell letter, cFrM \",50,0.,5.);\n  TH1F* grindstoneSocScicFrF = new TH1F(\"grindstoneSocScicFrF\", \" rate of grindstone words in Cornell letter, cFrF \",50,0.,5.);\n  TH1F* grindstoneSocScicMrF = new TH1F(\"grindstoneSocScicMrF\", \" rate of grindstone words in Cornell letter, cMrF \",50,0.,5.);\n\n  TH1F* signalPhysicscMrM = new TH1F(\"signalWilsoncMrM\", \" rate of signal words in Wilson letter, cMrM \",50,0.,5.);\n  TH1F* signalPhysicscFrM = new TH1F(\"signalWilsoncFrM\", \" rate of signal words in Wilson letter, cFrM \",50,0.,5.);\n  TH1F* signalPhysicscFrF = new TH1F(\"signalWilsoncFrF\", \" rate of signal words in Wilson letter, cFrF \",50,0.,5.);\n  TH1F* signalPhysicscMrF = new TH1F(\"signalWilsoncMrF\", \" rate of signal words in Wilson letter, cMrF \",50,0.,5.);\n\n  TH1F* signalSocScicMrM = new TH1F(\"signalSocScicMrM\", \" rate of signal words in Cornell letter, cMrM \",50,0.,5.);\n  TH1F* signalSocScicFrM = new TH1F(\"signalSocScicFrM\", \" rate of signal words in Cornell letter, cFrM \",50,0.,5.);\n  TH1F* signalSocScicFrF = new TH1F(\"signalSocScicFrF\", \" rate of signal words in Cornell letter, cFrF \",50,0.,5.);\n  TH1F* signalSocScicMrF = new TH1F(\"signalSocScicMrF\", \" rate of signal words in Cornell letter, cMrF \",50,0.,5.);\n\n  //\n  // some correlation plots\n  TH2F* agenticVsCommunalPhysics = new TH2F(\"agenticVsCommunalPhysics\", \" agentic vs communal rates, Physics\", 25, 0., 2.5, 25, 0., 2.5);\n  TH2F* standoutVsGrindstonePhysics = new TH2F(\"standoutVsGrindstonePhysics\",\n\t\t\t\t\t       \" standout vs grindstone rates, Physics\", 25, 0., 2.5, 25, 0., 2.5);\n  TH2F* agenticVsCommunalSocSci = new TH2F(\"agenticVsCommunalSocSci\", \" agentic vs communal rates, SocSci\", 25, 0., 2.5, 25, 0., 2.5);\n  TH2F* standoutVsGrindstoneSocSci = new TH2F(\"standoutVsGrindstoneSocSci\",\n\t\t\t\t\t      \" standout vs grindstone rates, SocSci\", 25, 0., 2.5, 25, 0., 2.5);\n\n  \n  TH2F* agenticVsCommunalPhysicsMaleCand = new TH2F(\"agenticVsCommunalPhysicsMaleCand\", \" agentic vs communal rates, PhysicsMaleCand\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* standoutVsGrindstonePhysicsMaleCand = new TH2F(\"standoutVsGrindstonePhysicsMaleCand\",\n\t\t\t\t\t\t       \" standout vs grindstone rates, PhysicsMaleCand\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* agenticVsCommunalSocSciMaleCand = new TH2F(\"agenticVsCommunalSocSciMaleCand\", \" agentic vs communal rates, SocSciMaleCand\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* standoutVsGrindstoneSocSciMaleCand = new TH2F(\"standoutVsGrindstoneSocSciMaleCand\",\n\t\t\t\t\t\t      \" standout vs grindstone rates, SocSciMaleCand\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* agenticVsCommunalPhysicsFemaleCand = new TH2F(\"agenticVsCommunalPhysicsFemaleCand\", \" agentic vs communal rates, PhysicsFemaleCand\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* standoutVsGrindstonePhysicsFemaleCand = new TH2F(\"standoutVsGrindstonePhysicsFemaleCand\",\n\t\t\t\t\t\t\t \" standout vs grindstone rates, PhysicsFemaleCand\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* agenticVsCommunalSocSciFemaleCand = new TH2F(\"agenticVsCommunalSocSciFemaleCand\", \" agentic vs communal rates, SocSciFemaleCand\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* standoutVsGrindstoneSocSciFemaleCand = new TH2F(\"standoutVsGrindstoneSocSciFemaleCand\",\n\t\t\t\t\t\t\t\" standout vs grindstone rates, SocSciFemaleCand\", 10, 0., 2.5, 10, 0., 2.5);\n\n  TH2F* agenticVsCommunalPhysicsMaleWriter = new TH2F(\"agenticVsCommunalPhysicsMaleWriter\", \" agentic vs communal rates, PhysicsMaleWriter\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* standoutVsGrindstonePhysicsMaleWriter = new TH2F(\"standoutVsGrindstonePhysicsMaleWriter\",\n\t\t\t\t\t\t\t \" standout vs grindstone rates, PhysicsMaleWriter\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* agenticVsCommunalSocSciMaleWriter = new TH2F(\"agenticVsCommunalSocSciMaleWriter\", \" agentic vs communal rates, SocSciMaleWriter\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* standoutVsGrindstoneSocSciMaleWriter = new TH2F(\"standoutVsGrindstoneSocSciMaleWriter\",\n\t\t\t\t\t\t\t\" standout vs grindstone rates, SocSciMaleWriter\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* agenticVsCommunalPhysicsFemaleWriter = new TH2F(\"agenticVsCommunalPhysicsFemaleWriter\", \" agentic vs communal rates, PhysicsFemaleWriter\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* standoutVsGrindstonePhysicsFemaleWriter = new TH2F(\"standoutVsGrindstonePhysicsFemaleWriter\",\n\t\t\t\t\t\t\t   \" standout vs grindstone rates, PhysicsFemaleWriter\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* agenticVsCommunalSocSciFemaleWriter = new TH2F(\"agenticVsCommunalSocSciFemaleWriter\", \" agentic vs communal rates, SocSciFemaleWriter\", 10, 0., 2.5, 10, 0., 2.5);\n  TH2F* standoutVsGrindstoneSocSciFemaleWriter = new TH2F(\"standoutVsGrindstoneSocSciFemaleWriter\",\n\t\t\t\t\t\t\t  \" standout vs grindstone rates, SocSciFemaleWriter\", 10, 0., 2.5, 10, 0., 2.5);\n\n  \n  // make some summed histos\n\n  TH1F* sumOverMenAppPhysicsWordCount = new TH1F(\"sumOverMenAppPhysicsWordCount\",\" for all male applicants, physics, wordCount\", 100,0.,5000.);\n  TH1F* sumOverMenAppPhysicsAgentic = new TH1F(\"sumOverMenAppPhysicsAgentic\",\" for all male applicants, physics, agentic\", 50,0.,5.);\n  TH1F* sumOverMenAppPhysicsCommunal = new TH1F(\"sumOverMenAppPhysicsCommunal\",\" for all male applicants, physics, communal\", 50,0.,5.);\n  TH1F* sumOverMenAppPhysicsAbility = new TH1F(\"sumOverMenAppPhysicsAbility\",\" for all male applicants, physics, ability\", 50,0.,5.);\n  TH1F* sumOverMenAppPhysicsGrindstone = new TH1F(\"sumOverMenAppPhysicsGrindstone\",\" for all male applicants, physics, grindstone\", 50,0.,5.);\n  TH1F* sumOverMenAppPhysicsStandout = new TH1F(\"sumOverMenAppPhysicsStandout\",\" for all male applicants, physics, standout\", 50,0.,5.);\n \n  TH1F* sumOverWomenAppPhysicsWordCount = new TH1F(\"sumOverWomenAppPhysicsWordCount\",\" for all female applicants, physics, wordCount\", 100,0.,5000.);\n  TH1F* sumOverWomenAppPhysicsAgentic = new TH1F(\"sumOverWomenAppPhysicsAgentic\",\" for all female applicants, physics, agentic\", 50,0.,5.);\n  TH1F* sumOverWomenAppPhysicsCommunal = new TH1F(\"sumOverWomenAppPhysicsCommunal\",\" for all female applicants, physics, communal\", 50,0.,5.);\n  TH1F* sumOverWomenAppPhysicsAbility = new TH1F(\"sumOverWomenAppPhysicsAbilty\",\" for all female applicants, physics, ability\", 50,0.,5.);\n  TH1F* sumOverWomenAppPhysicsGrindstone = new TH1F(\"sumOverWomenAppPhysicsGrindstone\",\" for all female applicants, physics, grindstone\", 50,0.,5.);\n  TH1F* sumOverWomenAppPhysicsStandout = new TH1F(\"sumOverWomenAppPhysicsStandout\",\" for all female applicants, physics, standout\", 50,0.,5.);\n\n\n  TH1F* sumOverMenWritersPhysicsWordCount = new TH1F(\"sumOverMenWritersPhysicsWordCount\",\" for all male writers, physics, wordCount\", 100,0.,5000.);\n  TH1F* sumOverMenWritersPhysicsAgentic = new TH1F(\"sumOverMenWritersPhysicsAgentic\",\" for all male writers, physics, agentic\", 50,0.,5.);\n  TH1F* sumOverMenWritersPhysicsCommunal = new TH1F(\"sumOverMenWritersPhysicsCommunal\",\" for all male writers, physics, communal\", 50,0.,5.);\n  TH1F* sumOverMenWritersPhysicsAbility = new TH1F(\"sumOverMenWritersPhysicsAbility\",\" for all male writers, physics, ability\", 50,0.,5.);\n  TH1F* sumOverMenWritersPhysicsGrindstone = new TH1F(\"sumOverMenWritersPhysicsGrindstone\",\" for all male writers, physics, grindstone\", 50,0.,5.);\n  TH1F* sumOverMenWritersPhysicsStandout = new TH1F(\"sumOverMenWritersPhysicsStandout\",\" for all male writers, physics, standout\", 50,0.,5.);\n \n  TH1F* sumOverWomenWritersPhysicsWordCount = new TH1F(\"sumOverWomenWritersPhysicsWordCount\",\" for all female writers, physics, wordCount\", 100,0.,5000.);\n  TH1F* sumOverWomenWritersPhysicsAgentic = new TH1F(\"sumOverWomenWritersPhysicsAgentic\",\" for all female writers, physics, agentic\", 50,0.,5.);\n  TH1F* sumOverWomenWritersPhysicsCommunal = new TH1F(\"sumOverWomenWritersPhysicsCommunal\",\" for all female writers, physics, communal\", 50,0.,5.);\n  TH1F* sumOverWomenWritersPhysicsAbility = new TH1F(\"sumOverWomenWritersPhysicsAbilty\",\" for all female writers, physics, ability\", 50,0.,5.);\n  TH1F* sumOverWomenWritersPhysicsGrindstone = new TH1F(\"sumOverWomenWritersPhysicsGrindstone\",\" for all female writers, physics, grindstone\", 50,0.,5.);\n  TH1F* sumOverWomenWritersPhysicsStandout = new TH1F(\"sumOverWomenWritersPhysicsStandout\",\" for all female writers, physics, standout\", 50,0.,5.);\n\n\n  /**********socsci*********/\n  TH1F* sumOverMenAppSocSciWordCount = new TH1F(\"sumOverMenAppSocSciWordCount\",\" for all male applicants, social science, wordCount\", 100,0.,5000.);\n  TH1F* sumOverMenAppSocSciAgentic = new TH1F(\"sumOverMenAppSocSciAgentic\",\" for all male applicants, social science, agentic\", 50,0.,5.);\n  TH1F* sumOverMenAppSocSciCommunal = new TH1F(\"sumOverMenAppSocSciWordCommunal\",\" for all male applicants, social science, communal\", 50,0.,5.);\n  TH1F* sumOverMenAppSocSciAbility = new TH1F(\"sumOverMenAppSocSciAbility\",\" for all male applicants, social science, ability\", 50,0.,5.);\n  TH1F* sumOverMenAppSocSciGrindstone = new TH1F(\"sumOverMenAppSocSciGrindstone\",\" for all male applicants, social science, grindstone\", 50,0.,5.);\n  TH1F* sumOverMenAppSocSciStandout = new TH1F(\"sumOverMenAppSocSciStandout\",\" for all male applicants, social science, standout\", 50,0.,5.);\n \n  TH1F* sumOverWomenAppSocSciWordCount = new TH1F(\"sumOverWomenAppSocSciWordCount\",\" for all female applicants, social science, wordCount\", 100,0.,5000.);\n  TH1F* sumOverWomenAppSocSciAgentic = new TH1F(\"sumOverWomenAppSocSciAgentic\",\" for all female applicants, social science, agentic\", 50,0.,5.);\n  TH1F* sumOverWomenAppSocSciCommunal = new TH1F(\"sumOverWomenAppSocSciCommunal\",\" for all female applicants, social science, communal\", 50,0.,5.);\n  TH1F* sumOverWomenAppSocSciAbility = new TH1F(\"sumOverWomenAppSocSciAbilty\",\" for all female applicants, social science, ability\", 50,0.,5.);\n  TH1F* sumOverWomenAppSocSciGrindstone = new TH1F(\"sumOverWomenAppSocSciGrindstone\",\" for all female applicants, social science, grindstone\", 50,0.,5.);\n  TH1F* sumOverWomenAppSocSciStandout = new TH1F(\"sumOverWomenAppSocSciStandout\",\" for all female applicants, social science, standout\", 50,0.,5.);\n\n\n  TH1F* sumOverMenWritersSocSciWordCount = new TH1F(\"sumOverMenWritersSocSciWordCount\",\" for all male writers, social science, wordCount\", 100,0.,5000.);\n  TH1F* sumOverMenWritersSocSciAgentic = new TH1F(\"sumOverMenWritersSocSciAgentic\",\" for all male writers, social science, agentic\", 50,0.,5.);\n  TH1F* sumOverMenWritersSocSciCommunal = new TH1F(\"sumOverMenWritersSocSciCommunal\",\" for all male writers, social science, communal\", 50,0.,5.);\n  TH1F* sumOverMenWritersSocSciAbility = new TH1F(\"sumOverMenWritersSocSciAbility\",\" for all male writers, social science, ability\", 50,0.,5.);\n  TH1F* sumOverMenWritersSocSciGrindstone = new TH1F(\"sumOverMenWritersSocSciGrindstone\",\" for all male writers, social science, grindstone\", 50,0.,5.);\n  TH1F* sumOverMenWritersSocSciWStandout = new TH1F(\"sumOverMenWritersSocSciStandout\",\" for all male writers, social science, standout\", 50,0.,5.);\n \n  TH1F* sumOverWomenWritersSocSciWordCount = new TH1F(\"sumOverWomenWritersSocSciWordCount\",\" for all female writers, social science, wordCount\", 100,0.,5000.);\n  TH1F* sumOverWomenWritersSocSciAgentic = new TH1F(\"sumOverWomenWritersSocSciAgentic\",\" for all female writers, social science, agentic\", 50,0.,5.);\n  TH1F* sumOverWomenWritersSocSciCommunal = new TH1F(\"sumOverWomenWritersSocSciCommunal\",\" for all female writers, social science, communal\", 50,0.,5.);\n  TH1F* sumOverWomenWritersSocSciAbility = new TH1F(\"sumOverWomenWritersSocSciAbilty\",\" for all female writers, social science, ability\", 50,0.,5.);\n  TH1F* sumOverWomenWritersSocSciGrindstone = new TH1F(\"sumOverWomenWritersSocSciGrindstone\",\" for all female writers, social science, grindstone\", 50,0.,5.);\n  TH1F* sumOverWomenWritersSocSciStandout = new TH1F(\"sumOverWomenWritersSocSciStandout\",\" for all female writers, social science, standout\", 50,0.,5.);\n \n\n  Float_t nt[17];\n  TNtuple* physics = new TNtuple(\"physics\",\"Physics Ntuple\",\n\t\t\t\t \"cat:wc:WPS:Dic:standout:ability:grindstone:teaching:research:agentic:communal:comparisonMale:comparisonFemale:signalPhysics:signalSociology:ranking:negative\");\n\n  TNtuple* socsci = new TNtuple(\"socsci\",\"SocSci Ntuple\",\n\t\t\t\t\"cat:wc:WPS:Dic:standout:ability:grindstone:teaching:research:agentic:communal:comparisonMale:comparisonFemale:signalPhysics:signalSociology:ranking:negative\");\n\n\n  const char* labels[4] = {\"cMwM\", \"cMwF\", \"cFwF\",\"cFwM\"};\n  analysisOut << \"made ntuples\" << std::endl;\n  inputFiles.clear();\n  inputFiles.seekg(0);\n \n\n  Int_t comparisonMin = 0.0;\n  wcCut = 0;\n  //    physicsLength = 10;\n  string headerInfo;\n  Int_t oldCandId = -1;\n  Int_t bothNum;\n  Bool_t femaleWriter;\n  Bool_t maleWriter;\n  femaleWriter = false;\n  maleWriter = false;\n  std::getline(inputFiles,headerInfo);\n  Int_t nWriters;\n  nWriters = 0;\n  std::cout << \"letter Length = \" << letterLength << std::endl;\n  for (Int_t ithLetter = 0 ; ithLetter< letterLength; ++ithLetter)\n    {\n      std::cout << \"rowNo = \" << rowNo << std::endl;\n           inputFiles >> rowNo >> rowHash >> bobHash >> candId >> writerId >> canGender >> writerGender >> both >> discipline\n\t       >> Ref_is_advisor >> Ref_nonresearch >> both_gender_non_advisor_refs >>  wc >> Analytic >> Clout >> Authentic >> Tone >>  WPS>> Dic>> function>> pronoun>> ppron>> i>> we>> you >> shehe>> they>> ipron>> article>> prep>> auxverb>> adverb>> conj>> negate>> verb>> adj>> compare>> interrog>> number>> quant>>\n      affect>> posemo>> negemo>> anx>> anger>> sad >>      social >> family>> friends>> female>> male>> cogproc>> insight>> cause>> discrep>> tentat>> certain>> differ>> percept>> see>> hear>> feel>> bio>> body>> health>> sexual>> ingest>> drives>> affiliation>>\n      achiev>>power>>reward>>risk>>focuspast>>focuspresent>>focusfuture >>\n      relativ>>motion>>space>>time>>work>>leisure>>home>>money>>relig>>death>>informal>>swear>>netspeak>>assent>>nonflu>>filler>>AllPunc>>Period>>Comma>>Colon>>SemiC>>QMark>>Exclam>>Dash>>Quote>>\n      Apostro>>Parent>>OtherP >> standout >> ability >> grindstone >> teaching >> research >> agentic >> communal >> comparisonMale >> comparisonFemale >> signalPhysics >> signalSociology >> ranking >> negative;\n      if (ithLetter == 0){oldCandId = candId; nWriters = 0;}\n      //      bothOut << \"candidate ID \" << candId << std::endl;\n      // this doesn't do last person, just check externally.\n\n\tif (ithLetter > -10000){\n\t  analysisOut   << candidateName << \" \"  <<   wc <<  \" \"  <<  WPS <<  \" \"  <<  Dic <<  \" \"  <<  function <<  \" \"  <<  pronoun <<  \" \"  <<  ppron <<  \" \"  <<  i <<  \" \"  <<  we <<  \" \"  <<  you  <<  \" \"  <<  shehe <<  \" \"  <<  they <<  \" \"  <<  ipron  <<  \" \"  <<  article <<  \" \"\n\t\t\t<<  prep  <<  \" \"  <<  auxverb <<  \" \"  <<  adverb <<  \" \"  <<  conj <<  \" \"  <<  negate <<  \" \"  <<  verb <<  \" \"  <<  adj <<  \" \"  <<  compare <<  \" \"  <<  interrog <<  \" \"  <<  number <<  \" \"  <<  quant <<  \"\\n \"\n\t\t\t<<  affect <<  \" \"  <<  posemo <<  \" \"  <<  negemo <<  \" \"  <<  anx <<  \" \"  <<  anger <<  \" \"  <<  sad  <<  \" \"\n\t\t\t<<  social  <<  \" \"  <<  family <<  \" \"  <<  friends <<  \" \"  <<  female <<  \" \"  <<  male <<  \"\\n \"  <<  cogproc <<  \" \"  <<  insight <<  \" \"  <<  cause <<  \" \"  <<  discrep <<  \" \"  <<  tentat <<  \" \"  <<  certain <<  \" \"  <<  differ <<  \" \"\n\t\t\t<<  percept <<  \" \"  <<  see <<  \" \"  <<  hear  <<  \" \"  <<  feel  <<  \" \"  <<  bio  <<  \" \"  <<  body  <<  \" \"  <<  health <<  \" \"  <<  sexual <<  \" \"  <<  ingest  <<  \" \"  <<  drives  <<  \" \"  <<  affiliation  <<  \" \" \n\t\t\t<<  achiev <<  \" \"  << power <<  \" \"  << reward <<  \" \"  << risk <<  \" \"  <<  focuspast <<  \" \"  <<  focuspresent <<  \" \"  <<  focusfuture  <<  \"\\n \"  << \n\t    relativ <<  \" \"  << motion <<  \" \"  << space <<  \" \"  << time <<  \" \"  << work <<  \" \"  << leisure <<  \" \"  << home <<  \" \"  << money <<  \" \"  << relig <<  \" \"\n\t\t\t<< death <<  \"\\n \"  << informal <<  \" \"  << swear <<  \" \"  << netspeak <<  \" \"  << assent <<  \" \"  << nonflu <<  \" \"  << filler <<  \" \"  << AllPunc <<  \" \"  << Period <<  \" \"  << Comma <<  \" \"\n\t\t\t<< Colon <<  \" \"  << SemiC <<  \" \"  << QMark <<  \" \"  << Exclam <<  \" \"  << Dash <<  \" \"  << Quote <<  \" \"  << \n\t    Apostro <<  \" \"  << Parent <<  \" \"  << OtherP  <<  \"\\n \\n \" <<  std::endl;\n\t}\n\n      if (candId != oldCandId ){\n\tbothNum = 0;\n\tif (femaleWriter && maleWriter) bothNum = 1;\n\tfor (Int_t iWrite = 0; iWrite< nWriters;++iWrite){\n\tbothOut << oldCandId << \" \" << bothNum << std::endl;\n\t}\n\toldCandId = candId;\n\tfemaleWriter = false;\n\tmaleWriter = false;\n\tnWriters = 0;\n      }\n      if (writerGender > 0.5){\n\tfemaleWriter= true;\n\t//bothOut << \"female writer\" << std::endl;\n      }\n      if (writerGender < 0.5){\n\tmaleWriter=true;\n\t//\tbothOut << \"maleWriter\" << std::endl;\n      }\n      ++nWriters;\n \n            if (useBoth && both < 0.5) continue;\n      if (discipline > 0.5) {\n\tanalysisOut << \"finished\" << std::endl;\n\tanalysisOut << \" candidate and writer \" << canGender << \" \" << writerGender << \" \" << candId << std::endl;\n\tif (writerGender < 0.5){analysisOut << \"male writer \" << std::endl;}\n\tif (wc < wcCut ) continue;\n    \n\tif (canGender < 0.5 && writerGender < 0.5){\n\t  cat = 1;\n\t  wordCountPhysicscMrM->Fill(wc);\n\t  agenticPhysicscMrM->Fill(agentic);\n\t  communalPhysicscMrM->Fill(communal);\n\t  standoutPhysicscMrM->Fill(standout);\n\t  abilityPhysicscMrM->Fill(ability);\n\t  grindstonePhysicscMrM->Fill(grindstone);\n\t  if ( (comparisonMale+comparisonFemale) > comparisonMin){\n\t    comparisonMalePhysicscMrM->Fill(comparisonMale);\n\t    comparisonFemalePhysicscMrM->Fill(comparisonFemale);\n\t  }\n\t  sumOverMenAppPhysicsWordCount->Fill(wc);\n\t  sumOverMenWritersPhysicsWordCount->Fill(wc);\n\n\t  agenticVsCommunalPhysics->Fill(communal,agentic);\n\t  agenticVsCommunalPhysicsMaleCand->Fill(communal,agentic);\n\t  agenticVsCommunalPhysicsMaleWriter->Fill(communal,agentic);\n\n\n\t  standoutVsGrindstonePhysics->Fill(grindstone,standout);\n\t  standoutVsGrindstonePhysicsMaleCand->Fill(grindstone,standout);\n\t  standoutVsGrindstonePhysicsMaleWriter->Fill(grindstone,standout);\n\t  cat = 1;\n\t  analysisOut << \"in cat 1\" << std::endl;\n\t  nt[0] = cat;\n\t  nt[1] = wc;\n\t  nt[2] = WPS;\n\t  nt[3] = Dic;\n\t  nt[4] = standout;\n\t  nt[5] = ability;\n\t  nt[6] = grindstone;\n\t  nt[7] = teaching;\n\t  nt[8] = research;\n\t  nt[9] = agentic;\n\t  nt[10] = communal;\n\t  nt[11] = comparisonMale;\n\t  nt[12] = comparisonFemale;\n\t  nt[13] = signalPhysics;\n\t  nt[14] = signalSociology;\n\t  nt[15] = ranking;\n\t  nt[16] = negative;\n\t  physics->Fill(nt);\n   \n\t  ++nlines;\n\t}\n\n    \n\tif ( canGender > 0.5 && writerGender < 0.5){\n\t  cat = 2;\n\t  analysisOut << \"in cat 2\" << std::endl;\n\t  wordCountPhysicscFrM->Fill(wc);\n\t  agenticPhysicscFrM->Fill(agentic);\n\t  communalPhysicscFrM->Fill(communal);\n\t  standoutPhysicscFrM->Fill(standout);\n\t  abilityPhysicscFrM->Fill(ability);\n\t  grindstonePhysicscFrM->Fill(grindstone);\n\t  if ( (comparisonMale+comparisonFemale) > comparisonMin){\n\t    comparisonMalePhysicscFrM->Fill(comparisonMale);\n\t    comparisonFemalePhysicscFrM->Fill(comparisonFemale);\n\t  }\n\t  sumOverWomenAppPhysicsWordCount->Fill(wc);\n\t  sumOverMenWritersPhysicsWordCount->Fill(wc);\n\n\t  agenticVsCommunalPhysics->Fill(communal,agentic);\n\t  agenticVsCommunalPhysicsFemaleCand->Fill(communal,agentic);\n\t  agenticVsCommunalPhysicsMaleWriter->Fill(communal,agentic);\n\n\t  standoutVsGrindstonePhysics->Fill(grindstone,standout);\n\t  standoutVsGrindstonePhysicsFemaleCand->Fill(grindstone,standout);\n\t  standoutVsGrindstonePhysicsMaleWriter->Fill(grindstone,standout);\n\n\n\t  nt[0] = cat;\n\t  nt[1] = wc;\n\t  nt[2] = WPS;\n\t  nt[3] = Dic;\n\t  nt[4] = standout;\n\t  nt[5] = ability;\n\t  nt[6] = grindstone;\n\t  nt[7] = teaching;\n\t  nt[8] = research;\n\t  nt[9] = agentic;\n\t  nt[10] = communal;\n\t  nt[11] = comparisonMale;\n\t  nt[12] = comparisonFemale;\n\t  nt[13] = signalPhysics;\n\t  nt[14] = signalSociology;\n\t  nt[15] = ranking;\n\t  nt[16] = negative;\n\t  physics->Fill(nt);\n\t  ++nlines;\n\t}\n\n\tif (canGender > 0.5 && (writerGender > 0.5)){\n\t  cat = 3;\n\t  analysisOut << \"in cat 3\" << std::endl;\n\t  wordCountPhysicscFrF->Fill(wc);\n\t  agenticPhysicscFrF->Fill(agentic);\n\t  communalPhysicscFrF->Fill(communal);\n\t  standoutPhysicscFrF->Fill(standout);\n\t  abilityPhysicscFrF->Fill(ability);\n\t  grindstonePhysicscFrF->Fill(grindstone);\n\t  sumOverWomenAppPhysicsWordCount->Fill(wc);\n\t  sumOverWomenWritersPhysicsWordCount->Fill(wc);\n\t  if ( (comparisonMale+comparisonFemale) > comparisonMin){\n\t    comparisonMalePhysicscFrF->Fill(comparisonMale);\n\t    comparisonFemalePhysicscFrF->Fill(comparisonFemale);\n\t  }\n\n\t  agenticVsCommunalPhysics->Fill(communal,agentic);\n\t  agenticVsCommunalPhysicsFemaleCand->Fill(communal,agentic);\n\t  agenticVsCommunalPhysicsFemaleWriter->Fill(communal,agentic);\n\n\t  standoutVsGrindstonePhysics->Fill(grindstone,standout);\n\t  standoutVsGrindstonePhysicsFemaleCand->Fill(grindstone,standout);\n\t  standoutVsGrindstonePhysicsFemaleWriter->Fill(grindstone,standout);\n\n\t  nt[0] = cat;\n\t  nt[1] = wc;\n\t  nt[2] = WPS;\n\t  nt[3] = Dic;\n\t  nt[4] = standout;\n\t  nt[5] = ability;\n\t  nt[6] = grindstone;\n\t  nt[7] = teaching;\n\t  nt[8] = research;\n\t  nt[9] = agentic;\n\t  nt[10] = communal;\n\t  nt[11] = comparisonMale; \n\t  nt[12] = comparisonFemale;\n\t  nt[13] = signalPhysics;\n\t  nt[14] = signalSociology;\n\t  nt[15] = ranking;\n\t  nt[16] = negative;\n\t  physics->Fill(nt);\n\t  ++nlines;\n\t}\n\n\tif (canGender < 0.5 && writerGender > 0.5){\n\t  cat = 4;\n\t  analysisOut << \"in cat 4\" << std::endl;\n\t  wordCountPhysicscMrF->Fill(wc);\n\t  agenticPhysicscMrF->Fill(agentic);\n\t  communalPhysicscMrF->Fill(communal);\n\t  standoutPhysicscMrF->Fill(standout);\n\t  abilityPhysicscMrF->Fill(ability);\n\t  grindstonePhysicscMrF->Fill(grindstone);\n\t  sumOverMenAppPhysicsWordCount->Fill(wc);\n\t  sumOverWomenWritersPhysicsWordCount->Fill(wc);\n\t  if ( (comparisonMale + comparisonFemale) > comparisonMin){\n\t    comparisonMalePhysicscMrF->Fill(comparisonMale);\n\t    comparisonFemalePhysicscMrF->Fill(comparisonFemale);\n\t  }\n\n\t  agenticVsCommunalPhysics->Fill(communal,agentic);\n\t  agenticVsCommunalPhysicsMaleCand->Fill(communal,agentic);\n\t  agenticVsCommunalPhysicsFemaleWriter->Fill(communal,agentic);\n\n\t  standoutVsGrindstonePhysics->Fill(grindstone,standout);\n\t  standoutVsGrindstonePhysicsMaleCand->Fill(grindstone,standout);\n\t  standoutVsGrindstonePhysicsFemaleWriter->Fill(grindstone,standout);\n\n\t  nt[0] = cat;\n\t  nt[1] = wc;\n\t  nt[2] = WPS;\n\t  nt[3] = Dic;\n\t  nt[4] = standout;\n\t  nt[5] = ability;\n\t  nt[6] = grindstone;\n\t  nt[7] = teaching;\n\t  nt[8] = research;\n\t  nt[9] = agentic;\n\t  nt[10] = communal;\n\t  nt[11] = comparisonMale;\n\t  nt[12] = comparisonFemale;\n\t  nt[13] = signalPhysics;\n\t  nt[14] = signalSociology;\n\t  nt[15] = ranking;\n\t  nt[16] = negative;\n\t  physics->Fill(nt);\n\t  ++nlines;\n\t}\n\n      \n      }\n      analysisOut << \"discipline and genders = \" << discipline << \" \" << canGender << \" \" << writerGender << std::endl;\n      if (discipline < 0.5){\n\t\n\tif (canGender < 0.5 && writerGender < 0.5){\n\t  cat = 5;\n\t  wordCountSocScicMrM->Fill(wc);\n\t  agenticSocScicMrM->Fill(agentic);\n\t  communalSocScicMrM->Fill(communal);\n\t  standoutSocScicMrM->Fill(standout);\n\t  abilitySocScicMrM->Fill(ability);\n\t  grindstoneSocScicMrM->Fill(grindstone);\n\t  sumOverMenAppSocSciWordCount->Fill(wc);\n\t  sumOverMenWritersSocSciWordCount->Fill(wc);\n\n\t  agenticVsCommunalSocSci->Fill(communal,agentic);\n\t  agenticVsCommunalSocSciMaleCand->Fill(communal,agentic);\n\t  agenticVsCommunalSocSciMaleWriter->Fill(communal,agentic);\n\n\t  standoutVsGrindstoneSocSci->Fill(grindstone,standout);\n\t  standoutVsGrindstoneSocSciMaleCand->Fill(grindstone,standout);\n\t  standoutVsGrindstoneSocSciMaleWriter->Fill(grindstone,standout);\n\n\t  nt[0] = cat;\n\t  nt[1] = wc;\n\t  nt[2] = WPS;\n\t  nt[3] = Dic;\n\t  nt[4] = standout;\n\t  nt[5] = ability;\n\t  nt[6] = grindstone;\n\t  nt[7] = teaching;\n\t  nt[8] = research;\n\t  nt[9] = agentic;\n\t  nt[10] = communal;\n\t  nt[11] = comparisonMale;\n\t  nt[12] = comparisonFemale;\n\t  nt[13] = signalPhysics;\n\t  nt[14] = signalSociology;\n\t  nt[15] = ranking;\n\t  nt[16] = negative;\n\t  socsci->Fill(nt);\n\t  ++nlines;\n\t}\n\t\n\tif ( canGender > 0.5 && writerGender < 0.5){\n\t  cat = 6;\n\t  wordCountSocScicFrM->Fill(wc);\n\t  agenticSocScicFrM->Fill(agentic);\n\t  communalSocScicFrM->Fill(communal);\n\t  standoutSocScicFrM->Fill(standout);\n\t  abilitySocScicFrM->Fill(ability);\n\t  grindstoneSocScicFrM->Fill(grindstone);\n\t  sumOverWomenAppSocSciWordCount->Fill(wc);\n\t  sumOverMenWritersSocSciWordCount->Fill(wc);\n\n\t  agenticVsCommunalSocSci->Fill(communal,agentic);\n\t  agenticVsCommunalSocSciFemaleCand->Fill(communal,agentic);\n\t  agenticVsCommunalSocSciMaleWriter->Fill(communal,agentic);\n\n\t  standoutVsGrindstoneSocSci->Fill(grindstone,standout);\n\t  standoutVsGrindstoneSocSciFemaleCand->Fill(grindstone,standout);\n\t  standoutVsGrindstoneSocSciMaleWriter->Fill(grindstone,standout);\n\n\t  nt[0] = cat;\n\t  nt[1] = wc;\n\t  nt[2] = WPS;\n\t  nt[3] = Dic;\n\t  nt[4] = standout;\n\t  nt[5] = ability;\n\t  nt[6] = grindstone;\n\t  nt[7] = teaching;\n\t  nt[8] = research;\n\t  nt[9] = agentic;\n\t  nt[10] = communal;\n\t  nt[11] = comparisonMale;\n\t  nt[12] = comparisonFemale;\n\t  nt[13] = signalPhysics;\n\t  nt[14] = signalSociology;\n\t  nt[15] = ranking;\n\t  nt[16] = negative;\n\t  socsci->Fill(nt);\n\t  ++nlines;\n\t}\n\n\n\tif (canGender > 0.5 && (writerGender > 0.5)){\n\t  cat = 7;\n\t  wordCountSocScicFrF->Fill(wc);\n\t  agenticSocScicFrF->Fill(agentic);\n\t  communalSocScicFrF->Fill(communal);\n\t  standoutSocScicFrF->Fill(standout);\n\t  abilitySocScicFrF->Fill(ability);\n\t  grindstoneSocScicFrF->Fill(grindstone);\n\t  sumOverWomenAppSocSciWordCount->Fill(wc);\n\t  sumOverWomenWritersSocSciWordCount->Fill(wc);\n\n\t  agenticVsCommunalSocSci->Fill(communal,agentic);\n\t  agenticVsCommunalSocSciFemaleCand->Fill(communal,agentic);\n\t  agenticVsCommunalSocSciFemaleWriter->Fill(communal,agentic);\n\n\t  standoutVsGrindstoneSocSci->Fill(grindstone,standout);\n\t  standoutVsGrindstoneSocSciFemaleCand->Fill(grindstone,standout);\n\t  standoutVsGrindstoneSocSciFemaleWriter->Fill(grindstone,standout);\n\n\t  nt[0] = cat;\n\t  nt[1] = wc;\n\t  nt[2] = WPS;\n\t  nt[3] = Dic;\n\t  nt[4] = standout;\n\t  nt[5] = ability;\n\t  nt[6] = grindstone;\n\t  nt[7] = teaching;\n\t  nt[8] = research;\n\t  nt[9] = agentic;\n\t  nt[10] = communal;\n\t  nt[11] = comparisonMale;\n\t  nt[12] = comparisonFemale;\n\t  nt[13] = signalPhysics;\n\t  nt[14] = signalSociology;\n\t  nt[15] = ranking;\n\t  nt[16] = negative;\n\t  socsci->Fill(nt);\n\t  ++nlines;\n\t}\n\n\n\tif (canGender < 0.5 && writerGender > 0.5){\n\t  cat = 8;\n\t  wordCountSocScicMrF->Fill(wc);\n\t  agenticSocScicMrF->Fill(agentic);\n\t  communalSocScicMrF->Fill(communal);\n\t  standoutSocScicMrF->Fill(standout);\n\t  abilitySocScicMrF->Fill(ability);\n\t  grindstoneSocScicMrF->Fill(grindstone);\n\t  sumOverMenAppSocSciWordCount->Fill(wc);\n\t  sumOverWomenWritersSocSciWordCount->Fill(wc);\n\n\t  agenticVsCommunalSocSci->Fill(communal,agentic);\n\t  agenticVsCommunalSocSciMaleCand->Fill(communal,agentic);\n\t  agenticVsCommunalSocSciFemaleWriter->Fill(communal,agentic);\n\n\t  standoutVsGrindstoneSocSci->Fill(grindstone,standout);\n\t  standoutVsGrindstoneSocSciMaleCand->Fill(grindstone,standout);\n\t  standoutVsGrindstoneSocSciFemaleWriter->Fill(grindstone,standout);\n\n\t  nt[0] = cat;\n\t  nt[1] = wc;\n\t  nt[2] = WPS;\n\t  nt[3] = Dic;\n\t  nt[4] = standout;\n\t  nt[5] = ability;\n\t  nt[6] = grindstone;\n\t  nt[7] = teaching;\n\t  nt[8] = research;\n\t  nt[9] = agentic;\n\t  nt[10] = communal;\n\t  nt[11] = comparisonMale;\n\t  nt[12] = comparisonFemale;\n\t  nt[13] = signalPhysics;\n\t  nt[14] = signalSociology;\n\t  nt[15] = ranking;\n\t  nt[16] = negative;\n\t  socsci->Fill(nt);\n\t  ++nlines;\n\t}\n\n\n      }\n    }\n  std::cout << \"about to write physics ntuple\" << std::endl;\n  \n  physics->Write();\n\n  wordCountPhysicscMrM->Write();\n  wordCountPhysicscFrM->Write();\n  wordCountPhysicscFrF->Write();\n  wordCountPhysicscFrM->Write();\n\n\n  agenticPhysicscMrM->Write();\n  agenticPhysicscFrM->Write();\n  agenticPhysicscFrF->Write();\n  agenticPhysicscFrM->Write();\n \n  communalPhysicscMrM->Write();\n  communalPhysicscFrM->Write();\n  communalPhysicscFrF->Write();\n  communalPhysicscFrM->Write();\n\n  abilityPhysicscMrM->Write();\n  abilityPhysicscFrM->Write();\n  abilityPhysicscFrF->Write();\n  abilityPhysicscFrM->Write();\n\n  grindstonePhysicscMrM->Write();\n  grindstonePhysicscFrM->Write();\n  grindstonePhysicscFrF->Write();\n  grindstonePhysicscFrM->Write();\n\n  standoutPhysicscMrM->Write();\n  standoutPhysicscFrM->Write();\n  standoutPhysicscFrF->Write();\n  standoutPhysicscFrM->Write();\n  analysisOut << \"everything in physics written\" << std::endl;\n \n  \n  sumOverMenWritersPhysicsWordCount->Write();\n  sumOverMenAppPhysicsWordCount->Write();\n  sumOverWomenWritersPhysicsWordCount->Write();\n  sumOverWomenAppPhysicsWordCount->Write();\n  sumOverMenWritersSocSciWordCount->Write();\n  sumOverMenAppSocSciWordCount->Write();\n  sumOverWomenWritersSocSciWordCount->Write();\n  sumOverWomenAppSocSciWordCount->Write();\n\n\n  socsci->Write();\n \n  agenticSocScicMrM->Write();\n  agenticSocScicFrM->Write();\n  agenticSocScicFrF->Write();\n  agenticSocScicMrF->Write();\n \n  communalSocScicMrM->Write();\n  communalSocScicFrM->Write();\n  communalSocScicFrF->Write();\n  communalSocScicMrF->Write();\n\n  abilitySocScicMrM->Write();\n  abilitySocScicFrM->Write();\n  abilitySocScicFrF->Write();\n  abilitySocScicMrF->Write();\n\n  grindstoneSocScicMrM->Write();\n  grindstoneSocScicFrM->Write();\n  grindstoneSocScicFrF->Write();\n  grindstoneSocScicMrF->Write();\n\n  standoutSocScicMrM->Write();\n  standoutSocScicFrM->Write();\n  standoutSocScicFrF->Write();\n  standoutSocScicMrF->Write();\n  \n\n\n  \n  wordCountSocScicMrM->Write();\n  wordCountSocScicFrM->Write();\n  wordCountSocScicFrF->Write();\n  wordCountSocScicMrF->Write();\n\n  agenticSocScicMrM->Write();\n  agenticSocScicFrM->Write();\n  agenticSocScicFrF->Write();\n  agenticSocScicMrF->Write();\n \n  communalSocScicMrM->Write();\n  communalSocScicFrM->Write();\n  communalSocScicFrF->Write();\n  communalSocScicMrF->Write();\n \n \n  analysisOut << \"finished socsci\" << std::endl;\n      \n\n\n\n  gStyle->SetOptFit(1);\n  //\n  // get means and errors.  Look at ratio M/F and make a big TGraphErrors\n\n\n Double_t par0;\n  Double_t err0;\n  TF1* fitRaw = new TF1(\"fits\",\"[0]\",0.,10.);\n  fitRaw->SetParNames(\"average\");\n\n  \n  Double_t quantileVal;\n  Double_t quantile = 0.5;\n\n  TCanvas* c1 = new TCanvas();\n  c1->Divide(2,1);\n  c1->cd(2);\n\n  \n  Float_t x2[4] = {1.,2.,3.,4.};\n  Float_t y2[4] = {\n    static_cast<Float_t>(getMedian(wordCountPhysicscMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(wordCountPhysicscFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(wordCountPhysicscMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(wordCountPhysicscFrF,quantileVal,quantile))\n  };\n  Float_t ex2[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey2[4] = {\n    static_cast<Float_t>(wordCountPhysicscMrM->GetMeanError()),\n    static_cast<Float_t>(wordCountPhysicscFrM->GetMeanError()),\n    static_cast<Float_t>(wordCountPhysicscMrF->GetMeanError()),\n    static_cast<Float_t>(wordCountPhysicscFrF->GetMeanError())\n  };\n\n  TGraphErrors* wordCountsPhysics = new TGraphErrors(4,x2,y2,ex2,ey2);\n  wordCountsPhysics->SetTitle(\"             EPP Median Word Count          \");\n\n  TFitResultPtr fitWordCountsPhysics = wordCountsPhysics->Fit(\"fits\",\"S\");\n  Double_t parWordCountsPhysics = fitWordCountsPhysics->Value(0);\n  Double_t errWordCountsPhysics = fitWordCountsPhysics->ParError(0);\n\n  TAxis* yAxisWordCountsPhysics = wordCountsPhysics->GetYaxis();\n   yAxisWordCountsPhysics->SetTitle(\"Number of Words\");\n   yAxisWordCountsPhysics->SetTickLength(0.);\n  TAxis* xaxisWordCountsPhysics= wordCountsPhysics->GetXaxis();\n  xaxisWordCountsPhysics->SetTickLength(0.);\n  xaxisWordCountsPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisWordCountsPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisWordCountsPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisWordCountsPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisWordCountsPhysics->ChangeLabel(2,-1.,0.);\n  xaxisWordCountsPhysics->ChangeLabel(4,-1.,0.);\n  xaxisWordCountsPhysics->ChangeLabel(6,-1.,0.);\n  xaxisWordCountsPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisWordCountsPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisWordCountsPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisWordCountsPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisWordCountsPhysics->ChangeLabel(2,-1.,0.);\n  xaxisWordCountsPhysics->ChangeLabel(4,-1.,0.);\n  xaxisWordCountsPhysics->ChangeLabel(6,-1.,0.);\n \n  wordCountsPhysics->SetFillColor(38);\n  wordCountsPhysics->Draw(\"AB\");\n  TBox* boxWordCountsPhysics = new TBox(0.6,parWordCountsPhysics-errWordCountsPhysics,4.4,parWordCountsPhysics+errWordCountsPhysics);\n  boxWordCountsPhysics->SetFillColor(kBlue);\n  boxWordCountsPhysics->SetFillStyle(3004);\n  wordCountsPhysics->SetMaximum(parWordCountsPhysics+5.*wordCountPhysicscFrF->GetMeanError());\n  wordCountsPhysics->SetMinimum(TMath::Max(parWordCountsPhysics-5.*wordCountPhysicscFrF->GetMeanError(),0.));\n  boxWordCountsPhysics->Draw();\n\n\n  wordCountsPhysics->Write();\n\n\n  if (useBoth){\n  c1->SaveAs(\"pdfPlotsBoth/physicsWC.pdf\");\n  }else { c1->SaveAs(\"pdfPlots/physicsWC.pdf\");}\n\n  c1->cd(1);\n  Float_t x1[4] = {1.,2.,3.,4.};\n  Float_t y1[4] = {\n    static_cast<Float_t>(getMedian(wordCountSocScicMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(wordCountSocScicFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(wordCountSocScicMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(wordCountSocScicFrF,quantileVal,quantile))\n  };\n  Float_t ex1[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey1[4] = {\n    static_cast<Float_t>(wordCountSocScicMrM->GetMeanError()),\n    static_cast<Float_t>(wordCountSocScicFrM->GetMeanError()),\n    static_cast<Float_t>(wordCountSocScicMrF->GetMeanError()),\n    static_cast<Float_t>(wordCountSocScicFrF->GetMeanError())\n  };\n\n  \n  TGraphErrors* wordCountsSocSci = new TGraphErrors(4,x1,y1,ex1,ey1);\n  wordCountsSocSci->SetMaximum(1250.);\n  wordCountsSocSci->SetMinimum(750.);\n  wordCountsSocSci->SetTitle(\"         Social Science Median Word Count        \");\n  TFitResultPtr fit = wordCountsSocSci->Fit(\"fits\",\"S\");\n  par0 = fit->Value(0);\n  err0 = fit->ParError(0);\n  TAxis* yAxisWordCountsSocSci = wordCountsSocSci->GetYaxis();\n  yAxisWordCountsSocSci->SetTitle(\"Number of Words\");\n  yAxisWordCountsSocSci->SetTickLength(0.);\n  TAxis* xaxisWordCountsSocSci = wordCountsSocSci->GetXaxis();\n  xaxisWordCountsSocSci->SetTickLength(0.);\n   xaxisWordCountsSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisWordCountsSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisWordCountsSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisWordCountsSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisWordCountsSocSci->ChangeLabel(2,-1.,0.);\n  xaxisWordCountsSocSci->ChangeLabel(4,-1.,0.);\n  xaxisWordCountsSocSci->ChangeLabel(6,-1.,0.);\n  xaxisWordCountsSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisWordCountsSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisWordCountsSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisWordCountsSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisWordCountsSocSci->ChangeLabel(2,-1.,0.);\n  xaxisWordCountsSocSci->ChangeLabel(4,-1.,0.);\n  xaxisWordCountsSocSci->ChangeLabel(6,-1.,0.);\n  wordCountsSocSci->SetFillColor(38);\n  wordCountsSocSci->SetMaximum(par0 + 5.*wordCountSocScicFrF->GetMeanError());\n  wordCountsSocSci->SetMinimum(TMath::Max(par0 - 5.*wordCountSocScicFrF->GetMeanError(),0.));\n   wordCountsSocSci->Draw(\"AB\");\n  //wordCountsSocSci->SetMinimum(0.);\n\n  TBox* boxWordCountsSocSci = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxWordCountsSocSci->SetFillColor(kBlue);\n  boxWordCountsSocSci->SetFillStyle(3004);\n  boxWordCountsSocSci->Draw();\n\n  if (useBoth){\n    c1->SaveAs(\"pdfPlotsBoth/SocSciWC.pdf\");\n  }else\n    {\n      c1->SaveAs(\"pdfPlots/SocSciWC.pdf\");\n    }\n\n \n\n  analysisOut  << \"summary word count \" << std::endl;\n\t\t\t\t\t    \n  analysisOut <<  static_cast<Float_t>(getMedian(wordCountPhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(wordCountPhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(wordCountPhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(wordCountPhysicscFrM,quantileVal,quantile)) << \" \" << std::endl;\n    \n  analysisOut <<    static_cast<Float_t>(wordCountPhysicscMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(wordCountPhysicscFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(wordCountPhysicscFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(wordCountPhysicscFrM->GetMeanError()) << \" \" << std::endl;\n\n\n  analysisOut <<    static_cast<Float_t>(getMedian(wordCountSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(wordCountSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(wordCountSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(wordCountSocScicFrM,quantileVal,quantile)) << \" \" << std::endl;\n    \n  analysisOut <<    static_cast<Float_t>(wordCountSocScicMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(wordCountSocScicFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(wordCountSocScicFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(wordCountSocScicFrM->GetMeanError()) << \" \" << std::endl;\n\n   analysisOut << \"summary standout\" << std::endl;\n\n  analysisOut <<  static_cast<Float_t>(getMedian(standoutPhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(standoutPhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(standoutPhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(standoutPhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n\n    \n    analysisOut <<    static_cast<Float_t>(standoutPhysicscMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(standoutPhysicscFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(standoutPhysicscFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(standoutPhysicscMrF->GetMeanError()) << \" \" << std::endl;\n\n  analysisOut <<    static_cast<Float_t>(getMedian(standoutSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(standoutSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(standoutSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(standoutSocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n\n   \n  analysisOut <<    static_cast<Float_t>(standoutSocScicMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(standoutSocScicFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(standoutSocScicFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(standoutSocScicMrF->GetMeanError()) << \" \" << std::endl;\n  \n  analysisOut << \" summary grindstone\" << std::endl;\n  analysisOut <<    static_cast<Float_t>(getMedian(grindstonePhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(grindstonePhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(grindstonePhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(grindstonePhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n\n    \n  analysisOut <<    static_cast<Float_t>(grindstonePhysicscMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(grindstonePhysicscFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(grindstonePhysicscFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(grindstonePhysicscMrF->GetMeanError()) << \" \" << std::endl;\n\n\n\n  analysisOut <<    static_cast<Float_t>(getMedian(grindstoneSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(grindstoneSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(grindstoneSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(grindstoneSocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n\n   \n  analysisOut <<    static_cast<Float_t>(grindstoneSocScicMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(grindstoneSocScicFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(grindstoneSocScicFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(grindstoneSocScicMrF->GetMeanError()) << \" \" << std::endl;\n\n\n  /* agentic and communal*/\n  analysisOut << \"summary agentic\" << std::endl;\n  analysisOut <<    static_cast<Float_t>(getMedian(agenticPhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(agenticPhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(agenticPhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(agenticPhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n\n\n\t\t\t\t      \n  analysisOut <<    static_cast<Float_t>(agenticPhysicscMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(agenticPhysicscFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(agenticPhysicscFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(agenticPhysicscMrF->GetMeanError()) << \" \" << std::endl;\n\n\n\n  analysisOut <<    static_cast<Float_t>(getMedian(agenticSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(agenticSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(agenticSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(agenticSocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n\n   \n  analysisOut <<    static_cast<Float_t>(agenticSocScicMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(agenticSocScicFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(agenticSocScicFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(agenticSocScicMrF->GetMeanError()) << \" \" << std::endl;\n\n  analysisOut << \"summary communal\" << std::endl;\n  analysisOut <<    static_cast<Float_t>(getMedian(communalPhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(communalPhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(communalPhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(communalPhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n\n\n\t\t\t\t      \n  analysisOut <<    static_cast<Float_t>(communalPhysicscMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(communalPhysicscFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(communalPhysicscFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(communalPhysicscMrF->GetMeanError()) << \" \" << std::endl;\n\n\n\n  analysisOut <<    static_cast<Float_t>(getMedian(communalSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(communalSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(communalSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(communalSocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n\n   \n  analysisOut <<    static_cast<Float_t>(communalSocScicMrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(communalSocScicFrM->GetMeanError()) << \" \" << \n    static_cast<Float_t>(communalSocScicFrF->GetMeanError()) << \" \" <<\n    static_cast<Float_t>(communalSocScicMrF->GetMeanError()) << \" \" << std::endl;\n\n\t\t\t\t\t\t\t\t       analysisOut << \"all done\" << std::endl;\n TCanvas* c2 = new TCanvas();\n c2->Divide(2);\n c2->cd(2);\n  Float_t xStandoutPhysics[4] = {1.,2.,3.,4.};\n  Float_t yStandoutPhysics[4] = {\n    static_cast<Float_t>(getMedian(standoutPhysicscMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(standoutPhysicscFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(standoutPhysicscMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(standoutPhysicscFrF,quantileVal,quantile))\n  };\n  Float_t exStandoutPhysics[4] = {0.1,0.1,0.1,0.1};\n  Float_t eyStandoutPhysics[4] = {\n    static_cast<Float_t>(standoutPhysicscMrM->GetMeanError()),\n    static_cast<Float_t>(standoutPhysicscFrM->GetMeanError()),\n    static_cast<Float_t>(standoutPhysicscMrF->GetMeanError()),\n    static_cast<Float_t>(standoutPhysicscFrF->GetMeanError())\n  };\n\n  TGraphErrors* standoutPhysics = new TGraphErrors(4,xStandoutPhysics,yStandoutPhysics,exStandoutPhysics,eyStandoutPhysics);\n  standoutPhysics->SetMaximum(1.7);\n  standoutPhysics->SetMinimum(0.7);\n  standoutPhysics->SetTitle(\"EPP Median Standout\");\n  TFitResultPtr fitStandoutPhysics = standoutPhysics->Fit(\"fits\",\"S\");\n  par0 = fitStandoutPhysics->Value(0);\n  err0 = fitStandoutPhysics->ParError(0);\n  TAxis* yAxisStandoutPhysics = standoutPhysics->GetYaxis();\n  yAxisStandoutPhysics->SetTitle(\"% of Words\");\n  yAxisStandoutPhysics->SetTickLength(0.);\n \n  TAxis* xaxisStandoutPhysics = standoutPhysics->GetXaxis();\n   xaxisStandoutPhysics->SetTickLength(0.);\n   xaxisStandoutPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisStandoutPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisStandoutPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisStandoutPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisStandoutPhysics->ChangeLabel(2,-1.,0.);\n  xaxisStandoutPhysics->ChangeLabel(4,-1.,0.);\n  xaxisStandoutPhysics->ChangeLabel(6,-1.,0.);\n  xaxisStandoutPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisStandoutPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisStandoutPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisStandoutPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisStandoutPhysics->ChangeLabel(2,-1.,0.);\n  xaxisStandoutPhysics->ChangeLabel(4,-1.,0.);\n  xaxisStandoutPhysics->ChangeLabel(6,-1.,0.);\n  standoutPhysics->SetFillColor(38);\n  standoutPhysics->SetMaximum(par0 + 5.*standoutPhysicscFrF->GetMeanError());\n  standoutPhysics->SetMinimum(TMath::Max(par0 - 5.*standoutPhysicscFrF->GetMeanError(),0.));\n\n  standoutPhysics->Draw(\"AB\");\n  TBox* boxStandoutPhysics = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxStandoutPhysics->SetFillColor(kBlue);\n  boxStandoutPhysics->SetFillStyle(3004);\n  boxStandoutPhysics->Draw();\n\n  standoutPhysics->Write();\n  if (useBoth)\n    {c2->SaveAs(\"pdfPlotsBoth/physicsStandout.pdf\");}\n  else{c2->SaveAs(\"pdfPlots/physicsStandout.pdf\");}\n\n  c2->cd(1);\n  //  TCanvas* c4 = new TCanvas();\n\n  analysisOut <<    static_cast<Float_t>(getMedian(standoutSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(standoutSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(standoutSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(standoutSocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t xStandoutSocSci[4] = {1.,2.,3.,4.};\n  Float_t yStandoutSocSci[4] = {\n    static_cast<Float_t>(getMedian(standoutSocScicMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(standoutSocScicFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(standoutSocScicMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(standoutSocScicFrF,quantileVal,quantile))\n  };\n  Float_t exStandoutSocSci[4] = {0.1,0.1,0.1,0.1};\n  Float_t eyStandoutSocSci[4] = {\n    static_cast<Float_t>(standoutSocScicMrM->GetMeanError()),\n    static_cast<Float_t>(standoutSocScicFrM->GetMeanError()),\n    static_cast<Float_t>(standoutSocScicMrF->GetMeanError()),\n    static_cast<Float_t>(standoutSocScicFrF->GetMeanError())\n  };\n\n  TGraphErrors* standoutSocSci = new TGraphErrors(4,xStandoutSocSci,yStandoutSocSci,exStandoutSocSci,eyStandoutSocSci);\n  standoutSocSci->SetTitle(\"Social Science Median Standout\");\n  TFitResultPtr fit4 = standoutSocSci->Fit(\"fits\",\"S\");\n  par0 = fit4->Value(0);\n  err0 = fit4->ParError(0);\n   TAxis* yAxisStandoutSocSci = standoutSocSci->GetYaxis();\n   yAxisStandoutSocSci->SetTitle(\"% of Words\");\n  yAxisStandoutSocSci->SetTickLength(0.);\n\n  TAxis* xaxisStandoutSocSci = standoutSocSci->GetXaxis();\n   xaxisStandoutSocSci->SetTickLength(0.);\n   xaxisStandoutSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisStandoutSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisStandoutSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisStandoutSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisStandoutSocSci->ChangeLabel(2,-1.,0.);\n  xaxisStandoutSocSci->ChangeLabel(4,-1.,0.);\n  xaxisStandoutSocSci->ChangeLabel(6,-1.,0.);\n  xaxisStandoutSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisStandoutSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisStandoutSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisStandoutSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisStandoutSocSci->ChangeLabel(2,-1.,0.);\n  xaxisStandoutSocSci->ChangeLabel(4,-1.,0.);\n  xaxisStandoutSocSci->ChangeLabel(6,-1.,0.);\n  standoutSocSci->SetFillColor(38);\n\n\n  standoutSocSci->SetMaximum(par0 + 5.*standoutSocScicFrF->GetMeanError());\n  standoutSocSci->SetMinimum(TMath::Max(par0 - 5.*standoutSocScicFrF->GetMeanError(),0.));\n\n  standoutSocSci->Draw(\"AB\");\n  TBox* boxStandoutSocSci = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxStandoutSocSci->SetFillColor(kBlue);\n  boxStandoutSocSci->SetFillStyle(3004);\n  boxStandoutSocSci->Draw();\n\n  standoutSocSci->Write();\n  if (useBoth){\n    c2->SaveAs(\"pdfPlotsBoth/SocSciStandout.pdf\");\n  }else {c2->SaveAs(\"pdfPlots/SocSciStandout.pdf\");}\n\n\n    TCanvas* c3 = new TCanvas();\n   c3->Divide(2);\n  c3->cd(2);\n\n    Float_t xGrindstonePhysics[4] = {1.,2.,3.,4.};\n  Float_t yGrindstonePhysics[4] = {\n    static_cast<Float_t>(getMedian(grindstonePhysicscMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(grindstonePhysicscFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(grindstonePhysicscMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(grindstonePhysicscFrF,quantileVal,quantile))\n  };\n  Float_t exGrindstonePhysics[4] = {0.1,0.1,0.1,0.1};\n  Float_t eyGrindstonePhysics[4] = {\n    static_cast<Float_t>(grindstonePhysicscMrM->GetMeanError()),\n    static_cast<Float_t>(grindstonePhysicscFrM->GetMeanError()),\n    static_cast<Float_t>(grindstonePhysicscMrF->GetMeanError()),\n    static_cast<Float_t>(grindstonePhysicscFrF->GetMeanError())\n  };\n\n  TGraphErrors* grindstonePhysics = new TGraphErrors(4,xGrindstonePhysics,yGrindstonePhysics,exGrindstonePhysics,eyGrindstonePhysics);\n  grindstonePhysics->SetTitle(\"EPP Grindstone\");\n  TFitResultPtr fitGrindstonePhysics = grindstonePhysics->Fit(\"fits\",\"S\");\n  par0 = fitGrindstonePhysics->Value(0);\n  err0 = fitGrindstonePhysics->ParError(0);\n    TAxis* yAxisGrindstonePhysics = grindstonePhysics->GetYaxis();\n  yAxisGrindstonePhysics->SetTitle(\"% of Words\");\n  yAxisGrindstonePhysics->SetTickLength(0.);\n\n  TAxis* xaxisGrindstonePhysics = grindstonePhysics->GetXaxis();\n  xaxisGrindstonePhysics->SetTickLength(0.);\n   xaxisGrindstonePhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisGrindstonePhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisGrindstonePhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisGrindstonePhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisGrindstonePhysics->ChangeLabel(2,-1.,0.);\n  xaxisGrindstonePhysics->ChangeLabel(4,-1.,0.);\n  xaxisGrindstonePhysics->ChangeLabel(6,-1.,0.);\n  xaxisGrindstonePhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisGrindstonePhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisGrindstonePhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisGrindstonePhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisGrindstonePhysics->ChangeLabel(2,-1.,0.);\n  xaxisGrindstonePhysics->ChangeLabel(4,-1.,0.);\n  xaxisGrindstonePhysics->ChangeLabel(6,-1.,0.);\n  grindstonePhysics->SetFillColor(38);\n\n  grindstonePhysics->SetMaximum(par0 + 5.*grindstonePhysicscFrF->GetMeanError());\n  grindstonePhysics->SetMinimum(TMath::Max(par0 - 5.*grindstonePhysicscFrF->GetMeanError(),0.));\n\n  grindstonePhysics->Draw(\"AB\");\n  TBox* boxGrindstonePhysics = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxGrindstonePhysics->SetFillColor(kBlue);\n  boxGrindstonePhysics->SetFillStyle(3004);\n  boxGrindstonePhysics->Draw();\n\n  grindstonePhysics->Write();\n  if (useBoth)\n    {c2->SaveAs(\"pdfPlotsBoth/physicsGrindstone.pdf\");}\n  else{c2->SaveAs(\"pdfPlots/physicsGrindstone.pdf\");}\n  \n     // TCanvas* c4 = new TCanvas();\n  c3->cd(1);\n\n  analysisOut <<    static_cast<Float_t>(getMedian(grindstoneSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(grindstoneSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(grindstoneSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(grindstoneSocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x4[4] = {1.,2.,3.,4.};\n  Float_t y4[4] = {\n    static_cast<Float_t>(getMedian(grindstoneSocScicMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(grindstoneSocScicFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(grindstoneSocScicMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(grindstoneSocScicFrF,quantileVal,quantile))\n  };\n  Float_t ex4[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey4[4] = {\n    static_cast<Float_t>(grindstoneSocScicMrM->GetMeanError()),\n    static_cast<Float_t>(grindstoneSocScicFrM->GetMeanError()),\n    static_cast<Float_t>(grindstoneSocScicMrF->GetMeanError()),\n    static_cast<Float_t>(grindstoneSocScicFrF->GetMeanError())\n  };\n\n  TGraphErrors* grindstoneSocSci = new TGraphErrors(4,x4,y4,ex4,ey4);\n  grindstoneSocSci->SetMaximum(2.0);\n  grindstoneSocSci->SetMinimum(1.0);\n  grindstoneSocSci->SetTitle(\"Social Science Median Grindstone\");\n  TFitResultPtr fitGrindstoneSocSci = grindstoneSocSci->Fit(\"fits\",\"S\");\n  par0 = fitGrindstoneSocSci->Value(0);\n  err0 = fitGrindstoneSocSci->ParError(0);\n    TAxis* yAxisGrindstoneSocSci = grindstoneSocSci->GetYaxis();\n  yAxisGrindstoneSocSci->SetTitle(\"% of Words\");\n  yAxisGrindstoneSocSci->SetTickLength(0.);\n  TAxis* xaxisGrindstoneSocSci = grindstoneSocSci->GetXaxis();\n  xaxisGrindstoneSocSci->SetTickLength(0.);\n  xaxisGrindstoneSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisGrindstoneSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisGrindstoneSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisGrindstoneSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisGrindstoneSocSci->ChangeLabel(2,-1.,0.);\n  xaxisGrindstoneSocSci->ChangeLabel(4,-1.,0.);\n  xaxisGrindstoneSocSci->ChangeLabel(6,-1.,0.);\n  xaxisGrindstoneSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisGrindstoneSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisGrindstoneSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisGrindstoneSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisGrindstoneSocSci->ChangeLabel(2,-1.,0.);\n  xaxisGrindstoneSocSci->ChangeLabel(4,-1.,0.);\n  xaxisGrindstoneSocSci->ChangeLabel(6,-1.,0.);\n  grindstoneSocSci->SetFillColor(38);\n\n  grindstoneSocSci->SetMaximum(par0 + 5.*grindstoneSocScicFrF->GetMeanError());\n  grindstoneSocSci->SetMinimum(TMath::Max(par0 - 5.*grindstoneSocScicFrF->GetMeanError(),0.));\n\n  grindstoneSocSci->Draw(\"AB\");\n  TBox* boxGrindstoneSocSci = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxGrindstoneSocSci->SetFillColor(kBlue);\n  boxGrindstoneSocSci->SetFillStyle(3004);\n  boxGrindstoneSocSci->Draw();\n\n  grindstoneSocSci->Write();\n  if (useBoth){\n    c2->SaveAs(\"pdfPlotsBoth/SocSciGrindstone.pdf\");\n  }else {c2->SaveAs(\"pdfPlots/SocSciGrindstone.pdf\");}\n\n  TCanvas* c5 = new TCanvas();\n  c5->Divide(2);\n  c5->cd(2);\n  analysisOut <<    static_cast<Float_t>(getMedian(agenticPhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(agenticPhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(agenticPhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(agenticPhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x5[4] = {1.,2.,3.,4.};\n  Float_t y5[4] = {\n    static_cast<Float_t>(getMedian(agenticPhysicscMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(agenticPhysicscFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(agenticPhysicscMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(agenticPhysicscFrF,quantileVal,quantile))\n  };\n  Float_t ex5[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey5[4] = {\n    static_cast<Float_t>(agenticPhysicscMrM->GetMeanError()),\n    static_cast<Float_t>(agenticPhysicscFrM->GetMeanError()),\n    static_cast<Float_t>(agenticPhysicscMrF->GetMeanError()),\n    static_cast<Float_t>(agenticPhysicscFrF->GetMeanError())\n  };\n\n  TGraphErrors* agenticPhysics = new TGraphErrors(4,x5,y5,ex5,ey5);\n  agenticPhysics->SetMaximum(1.5);\n  agenticPhysics->SetMinimum(0.5);\n  agenticPhysics->SetTitle(\"EPP Median Agentic\");\n  TFitResultPtr fit5 = agenticPhysics->Fit(\"fits\",\"S\");\n  par0 = fit5->Value(0);\n  err0 = fit5->ParError(0);\n    TAxis* yAxisAgenticPhysics = agenticPhysics->GetYaxis();\n  yAxisAgenticPhysics->SetTitle(\"% of Words\");\n  yAxisAgenticPhysics->SetTickLength(0.);\n \n\n  TAxis* xaxisAgenticPhysics= agenticPhysics->GetXaxis();\n  xaxisAgenticPhysics->SetTickLength(0.);\n   xaxisAgenticPhysics->SetTickLength(0.);\n   xaxisAgenticPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisAgenticPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisAgenticPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisAgenticPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisAgenticPhysics->ChangeLabel(2,-1.,0.);\n  xaxisAgenticPhysics->ChangeLabel(4,-1.,0.);\n  xaxisAgenticPhysics->ChangeLabel(6,-1.,0.);\n  xaxisAgenticPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisAgenticPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisAgenticPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisAgenticPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisAgenticPhysics->ChangeLabel(2,-1.,0.);\n  xaxisAgenticPhysics->ChangeLabel(4,-1.,0.);\n  xaxisAgenticPhysics->ChangeLabel(6,-1.,0.);\n  agenticPhysics->SetFillColor(38);\n  agenticPhysics->SetMaximum(par0 + 5.*agenticPhysicscFrF->GetMeanError());\n  agenticPhysics->SetMinimum(TMath::Max(par0 - 5.*agenticPhysicscFrF->GetMeanError(),0.));\n   agenticPhysics->Draw(\"AB\");\n\n  TBox* box5 = new TBox(0.6,par0-err0,4.4,par0+err0);\n  box5->SetFillColor(kBlue);\n  box5->SetFillStyle(3004);\n  box5->Draw();\n\n  agenticPhysics->Write();\n  if (useBoth){\n    c5->SaveAs(\"pdfPlotsBoth/physicsAgentic.pdf\");}\n  else{ c5->SaveAs(\"pdfPlots/physicsAgentic.pdf\");}\n  \n  //    TCanvas* c6 = new TCanvas();\n  c5->cd(1);\n  analysisOut <<    static_cast<Float_t>(getMedian(agenticSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(agenticSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(agenticSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(agenticSocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x6[4] = {1.,2.,3.,4.};\n  Float_t y6[4] = {\n    static_cast<Float_t>(getMedian(agenticSocScicMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(agenticSocScicFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(agenticSocScicMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(agenticSocScicFrF,quantileVal,quantile))\n  };\n  Float_t ex6[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey6[4] = {\n    static_cast<Float_t>(agenticSocScicMrM->GetMeanError()),\n    static_cast<Float_t>(agenticSocScicFrM->GetMeanError()),\n    static_cast<Float_t>(agenticSocScicMrF->GetMeanError()),\n    static_cast<Float_t>(agenticSocScicFrF->GetMeanError())\n  };\n\n  TGraphErrors* agenticSocSci = new TGraphErrors(4,x6,y6,ex6,ey6);\n  agenticSocSci->SetMaximum(1.5);\n  agenticSocSci->SetMinimum(0.5);\n  agenticSocSci->SetTitle(\"Social Science Median Agentic\");\n  TFitResultPtr fit6 = agenticSocSci->Fit(\"fits\",\"S\");\n  par0 = fit6->Value(0);\n  err0 = fit6->ParError(0);\n   TAxis* yAxisAgenticSocSci = agenticSocSci->GetYaxis();\n  yAxisAgenticSocSci->SetTitle(\"% of Words\");\n  yAxisAgenticSocSci->SetTickLength(0.);\n \n  TAxis* xaxisAgenticSocSci = agenticSocSci->GetXaxis();\n   xaxisAgenticSocSci->SetTickLength(0.);\n   xaxisAgenticSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisAgenticSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisAgenticSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisAgenticSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisAgenticSocSci->ChangeLabel(2,-1.,0.);\n  xaxisAgenticSocSci->ChangeLabel(4,-1.,0.);\n  xaxisAgenticSocSci->ChangeLabel(6,-1.,0.);\n  xaxisAgenticSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\" \");\n  xaxisAgenticSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\" \");\n  xaxisAgenticSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\" \");\n  xaxisAgenticSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\" \");\n  xaxisAgenticSocSci->ChangeLabel(2,-1.,0.);\n  xaxisAgenticSocSci->ChangeLabel(4,-1.,0.);\n  xaxisAgenticSocSci->ChangeLabel(6,-1.,0.);\n  agenticSocSci->SetFillColor(38);\n  agenticSocSci->SetMaximum(par0 + 5.*agenticSocScicFrF->GetMeanError());\n  agenticSocSci->SetMinimum(TMath::Max(par0 - 5.*agenticSocScicFrF->GetMeanError(),0.));\n   agenticSocSci->Draw(\"AB\");\n\n \n  TBox* box6 = new TBox(0.6,par0-err0,4.4,par0+err0);\n  box6->SetFillColor(kBlue);\n  box6->SetFillStyle(3004);\n  box6->Draw();\n\n  agenticSocSci->Write();\n\n  if (useBoth){\n    c5->SaveAs(\"pdfPlotsBoth/SocSciAgentic.pdf\");\n  } else {c5->SaveAs(\"pdfPlots/SocSciAgentic.pdf\");}\n\n  TCanvas* c7 = new TCanvas();\n  c7->Divide(2);\n  c7->cd(2);\n  analysisOut <<    static_cast<Float_t>(getMedian(communalPhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(communalPhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(communalPhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(communalPhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x7[4] = {1.,2.,3.,4.};\n  Float_t y7[4] = {\n    static_cast<Float_t>(getMedian(communalPhysicscMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(communalPhysicscFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(communalPhysicscMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(communalPhysicscFrF,quantileVal,quantile))\n  };\n  Float_t ex7[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey7[4] = {\n    static_cast<Float_t>(communalPhysicscMrM->GetMeanError()),\n    static_cast<Float_t>(communalPhysicscFrM->GetMeanError()),\n    static_cast<Float_t>(communalPhysicscMrF->GetMeanError()),\n    static_cast<Float_t>(communalPhysicscFrF->GetMeanError())\n  };\n\n  TGraphErrors* communalPhysics = new TGraphErrors(4,x7,y7,ex7,ey7);\n  communalPhysics->SetMaximum(1.6);\n  communalPhysics->SetMinimum(0.5);\n  communalPhysics->SetTitle(\"EPP Median Communal\");\n  TFitResultPtr fit7 = communalPhysics->Fit(\"fits\",\"S\");\n  par0 = fit7->Value(0);\n  err0 = fit7->ParError(0);\n     TAxis* yAxisCommunalPhysics = communalPhysics->GetYaxis();\n  yAxisCommunalPhysics->SetTitle(\"% of Words\");\n  yAxisCommunalPhysics->SetTickLength(0.);\n \n\n  TAxis* xaxisCommunalPhysics= communalPhysics->GetXaxis();\n  xaxisCommunalPhysics->SetTickLength(0.);\n   xaxisCommunalPhysics->SetTickLength(0.);\n   xaxisCommunalPhysics->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisCommunalPhysics->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisCommunalPhysics->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisCommunalPhysics->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisCommunalPhysics->ChangeLabel(2,-1.,0.);\n  xaxisCommunalPhysics->ChangeLabel(4,-1.,0.);\n  xaxisCommunalPhysics->ChangeLabel(6,-1.,0.);\n  communalPhysics->SetFillColor(38);\n  communalPhysics->SetMaximum(par0 + 5.*communalPhysicscFrF->GetMeanError());\n  communalPhysics->SetMinimum(TMath::Max(par0 - 5.*communalPhysicscFrF->GetMeanError(),0.));\n   communalPhysics->Draw(\"AB\");\n\n  TBox* boxCommunalPhysics = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxCommunalPhysics->SetFillColor(kBlue);\n  boxCommunalPhysics->SetFillStyle(3004);\n  boxCommunalPhysics->Draw();\n\n  communalPhysics->Write();\n  if (useBoth){\n    c5->SaveAs(\"pdfPlotsBoth/physicsCommunal.pdf\");}\n  else{ c5->SaveAs(\"pdfPlots/physicsCommunal.pdf\");}\n \n  if (useBoth)\n    {\n      c7->SaveAs(\"pdfPlotsBoth/physicsCommunal.pdf\");\n    }else{c7->SaveAs(\"pdfPlots/physicsCommunal.pdf\");}\n\n  //\n  c7->cd(1); //TCanvas* c8 = new TCanvas();\n\n  analysisOut <<    static_cast<Float_t>(getMedian(communalSocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(communalSocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(communalSocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(communalSocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x8[4] = {1.,2.,3.,4.};\n  Float_t y8[4] = {\n    static_cast<Float_t>(getMedian(communalSocScicMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(communalSocScicFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(communalSocScicMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(communalSocScicFrF,quantileVal,quantile))\n  };\n  Float_t ex8[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey8[4] = {\n    static_cast<Float_t>(communalSocScicMrM->GetMeanError()),\n    static_cast<Float_t>(communalSocScicFrM->GetMeanError()),\n    static_cast<Float_t>(communalSocScicMrF->GetMeanError()),\n    static_cast<Float_t>(communalSocScicFrF->GetMeanError())\n    //static_cast<Float_t>(100000.),\n    //static_cast<Float_t>(100000.),\n    //    static_cast<Float_t>(100000.),\n    //static_cast<Float_t>(100000.)\n  };\n\n  TGraphErrors* communalSocSci = new TGraphErrors(4,x8,y8,ex8,ey8);\n  communalSocSci->SetTitle(\"Social Science Median Communal\");\n  TFitResultPtr fit8 = communalSocSci->Fit(\"fits\",\"S\");\n  par0 = fit8->Value(0);\n  err0 = fit8->ParError(0);\n     TAxis* yAxisCommunalSocSci = communalSocSci->GetYaxis();\n  yAxisCommunalSocSci->SetTitle(\"% of Words\");\n  yAxisCommunalSocSci->SetTickLength(0.);\n \n\n  TAxis* xaxisCommunalSocSci= communalSocSci->GetXaxis();\n  xaxisCommunalSocSci->SetTickLength(0.);\n   xaxisCommunalSocSci->SetTickLength(0.);\n   xaxisCommunalSocSci->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxisCommunalSocSci->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxisCommunalSocSci->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxisCommunalSocSci->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxisCommunalSocSci->ChangeLabel(2,-1.,0.);\n  xaxisCommunalSocSci->ChangeLabel(4,-1.,0.);\n  xaxisCommunalSocSci->ChangeLabel(6,-1.,0.);\n  communalSocSci->SetFillColor(38);\n  communalSocSci->SetMaximum(par0 + 5.*communalSocScicFrF->GetMeanError());\n  communalSocSci->SetMinimum(TMath::Max(par0 - 5.*communalSocScicFrF->GetMeanError(),0.));\n   communalSocSci->Draw(\"AB\");\n\n  TBox* boxCommunalSocSci = new TBox(0.6,par0-err0,4.4,par0+err0);\n  boxCommunalSocSci->SetFillColor(kBlue);\n  boxCommunalSocSci->SetFillStyle(3004);\n  boxCommunalSocSci->Draw();\n \n \n  communalSocSci->Write();\n  if (useBoth)\n    {\n      c7->SaveAs(\"pdfPlotsBoth/SocSciCommunal.pdf\");\n    }else{ c7->SaveAs(\"pdfPlots/SocSciCommunal.pdf\");}\n\n\n  \n  TCanvas* c9 = new TCanvas();\n\n  analysisOut <<    static_cast<Float_t>(getMedian(comparisonMalePhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(comparisonMalePhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(comparisonMalePhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(comparisonMalePhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x9[4] = {1.,2.,3.,4.};\n  Float_t y9[4] = {\n    static_cast<Float_t>(getMedian(comparisonMalePhysicscMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(comparisonMalePhysicscFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(comparisonMalePhysicscMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(comparisonMalePhysicscFrF,quantileVal,quantile))\n  };\n  Float_t ex9[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey9[4] = {\n    static_cast<Float_t>(comparisonMalePhysicscMrM->GetMeanError()),\n    static_cast<Float_t>(comparisonMalePhysicscFrM->GetMeanError()),\n    static_cast<Float_t>(comparisonMalePhysicscMrF->GetMeanError()),\n    static_cast<Float_t>(comparisonMalePhysicscFrF->GetMeanError())\n  };\n\n  TGraphErrors* comparisonMalePhysics = new TGraphErrors(4,x9,y9,ex9,ey9);\n  comparisonMalePhysics->SetMaximum(0.3);\n  comparisonMalePhysics->SetMinimum(0.0);\n\n  comparisonMalePhysics->SetTitle(\"Physics Comparison to a Male\");\n  TFitResultPtr fit9 = comparisonMalePhysics->Fit(\"fits\",\"S\");\n  par0 = fit9->Value(0);\n  err0 = fit9->ParError(0);\n  TAxis* xaxis9= comparisonMalePhysics->GetXaxis();\n  xaxis9->SetTickLength(0.);\n  xaxis9->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxis9->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxis9->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxis9->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxis9->ChangeLabel(2,-1.,0.);\n  xaxis9->ChangeLabel(4,-1.,0.);\n  xaxis9->ChangeLabel(6,-1.,0.);\n    comparisonMalePhysics->SetMaximum(par0 + 5.*comparisonMalePhysicscFrF->GetMeanError());\n  comparisonMalePhysics->SetMinimum(TMath::Max(par0 - 5.*comparisonMalePhysicscFrF->GetMeanError(),0.));\n\n  comparisonMalePhysics->Draw(\"A*\");\n  TBox* box9 = new TBox(0.6,par0-err0,4.4,par0+err0);\n  box9->SetFillColor(kBlue);\n  box9->SetFillStyle(3004);\n  box9->Draw();\n\n  comparisonMalePhysics->Write();\n  if (useBoth){\n    c9->SaveAs(\"pdfPlotsBoth/physicsComparisonMale.pdf\");\n  }else {c9->SaveAs(\"pdfPlots/physicsComparisonMale.pdf\");}\n\n  TCanvas* c10 = new TCanvas();\n  analysisOut <<    static_cast<Float_t>(getMedian(comparisonFemalePhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(comparisonFemalePhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(comparisonFemalePhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(comparisonFemalePhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x10[4] = {1.,2.,3.,4.};\n  Float_t y10[4] = {\n    static_cast<Float_t>(getMedian(comparisonFemalePhysicscMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(comparisonFemalePhysicscFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(comparisonFemalePhysicscMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(comparisonFemalePhysicscFrF,quantileVal,quantile))\n  };\n  Float_t ex10[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey10[4] = {\n    static_cast<Float_t>(comparisonFemalePhysicscMrM->GetMeanError()),\n    static_cast<Float_t>(comparisonFemalePhysicscFrM->GetMeanError()),\n    static_cast<Float_t>(comparisonFemalePhysicscFrF->GetMeanError()),\n    static_cast<Float_t>(comparisonFemalePhysicscMrF->GetMeanError())\n  };\n\n  TGraphErrors* comparisonFemalePhysics = new TGraphErrors(4,x10,y10,ex10,ey10);\n  comparisonFemalePhysics->SetMaximum(0.3);\n  comparisonFemalePhysics->SetMinimum(0.0);\n\n  comparisonFemalePhysics->SetTitle(\"Physics Comparison to a Female\");\n \n  TFitResultPtr fit10 = comparisonFemalePhysics->Fit(\"fits\",\"S\");\n  par0 = fit10->Value(0);\n  err0 = fit10->ParError(0);\n  TAxis* xaxis10= comparisonFemalePhysics->GetXaxis();\n  xaxis10->SetTickLength(0.);\n  xaxis10->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"cMrM\");\n  xaxis10->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"cFrM\");\n  xaxis10->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"cFrF\");\n  xaxis10->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"cMrF\");\n  xaxis10->ChangeLabel(2,-1.,0.);\n  xaxis10->ChangeLabel(4,-1.,0.);\n  xaxis10->ChangeLabel(6,-1.,0.);\n  comparisonFemalePhysics->SetMaximum(par0 + 5.*comparisonFemalePhysicscFrF->GetMeanError());\n  comparisonFemalePhysics->SetMinimum(TMath::Max(par0 - 5.*comparisonFemalePhysicscFrF->GetMeanError(),0.));\n\n  comparisonFemalePhysics->Draw(\"A*\");\n  TBox* box10 = new TBox(0.6,par0-err0,4.4,par0+err0);\n  box10->SetFillColor(kBlue);\n  box10->SetFillStyle(3004);\n  box10->Draw();\n  if (useBoth)\n    {\n      c10->SaveAs(\"pdfPlotsBoth/physicsComparisonFemale.pdf\");\n    }else{ c10->SaveAs(\"pdfPlots/physicsComparisonFemale.pdf\");}\n\n\n  TCanvas* c11 = new TCanvas();\n  c11->Divide(2);\n  c11->cd(2);\n    analysisOut <<    static_cast<Float_t>(getMedian(abilityPhysicscMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(abilityPhysicscFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(abilityPhysicscFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(abilityPhysicscMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x11[4] = {1.,2.,3.,4.};\n  Float_t y11[4] = {\n    static_cast<Float_t>(getMedian(abilityPhysicscMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(abilityPhysicscFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(abilityPhysicscMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(abilityPhysicscFrF,quantileVal,quantile))\n  };\n  Float_t ex11[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey11[4] = {\n    static_cast<Float_t>(abilityPhysicscMrM->GetMeanError()),\n    static_cast<Float_t>(abilityPhysicscFrM->GetMeanError()),\n    static_cast<Float_t>(abilityPhysicscMrF->GetMeanError()),\n    static_cast<Float_t>(abilityPhysicscFrF->GetMeanError())\n  };\n\n  TGraphErrors* abilityPhysics = new TGraphErrors(4,x11,y11,ex11,ey11);\n  abilityPhysics->SetMaximum(0.3);\n  abilityPhysics->SetMinimum(0.0);\n\n  abilityPhysics->SetTitle(\"EPP Median Ability\");\n \n  TFitResultPtr fit11 = abilityPhysics->Fit(\"fits\",\"S\");\n  par0 = fit11->Value(0);\n  err0 = fit11->ParError(0);\n  TAxis* xaxis11= abilityPhysics->GetXaxis();\n  xaxis11->SetTickLength(0.);\n  xaxis11->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxis11->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxis11->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxis11->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxis11->ChangeLabel(2,-1.,0.);\n  xaxis11->ChangeLabel(4,-1.,0.);\n  xaxis11->ChangeLabel(6,-1.,0.);\n  abilityPhysics->SetMaximum(par0 + 5.*abilityPhysicscFrF->GetMeanError());\n  abilityPhysics->SetMinimum(TMath::Max(par0 - 5.*abilityPhysicscFrF->GetMeanError(),0.));\n  abilityPhysics->SetFillColor(38);\n  abilityPhysics->Draw(\"AB\");\n  TBox* box11 = new TBox(0.6,par0-err0,4.4,par0+err0);\n  box11->SetFillColor(kBlue);\n  box11->SetFillStyle(3004);\n  box11->Draw();\n\n  c11->cd(1);\n  \n   analysisOut <<    static_cast<Float_t>(getMedian(abilitySocScicMrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(abilitySocScicFrM,quantileVal,quantile)) << \" \" << \n    static_cast<Float_t>(getMedian(abilitySocScicFrF,quantileVal,quantile)) << \" \" <<\n    static_cast<Float_t>(getMedian(abilitySocScicMrF,quantileVal,quantile)) << \" \" << std::endl;\n \n  Float_t x12[4] = {1.,2.,3.,4.};\n  Float_t y12[4] = {\n    static_cast<Float_t>(getMedian(abilitySocScicMrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(abilitySocScicFrM,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(abilitySocScicMrF,quantileVal,quantile)),\n    static_cast<Float_t>(getMedian(abilitySocScicFrF,quantileVal,quantile))\n  };\n  Float_t ex12[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey12[4] = {\n    static_cast<Float_t>(abilitySocScicMrM->GetMeanError()),\n    static_cast<Float_t>(abilitySocScicFrM->GetMeanError()),\n    static_cast<Float_t>(abilitySocScicMrF->GetMeanError()),\n    static_cast<Float_t>(abilitySocScicFrF->GetMeanError())\n  };\n\n  TGraphErrors* abilitySocSci = new TGraphErrors(4,x12,y12,ex12,ey12);\n  abilitySocSci->SetMaximum(0.3);\n  abilitySocSci->SetMinimum(0.0);\n\n  abilitySocSci->SetTitle(\"Social Science Median Ability\");\n \n  TFitResultPtr fit12 = abilitySocSci->Fit(\"fits\",\"S\");\n  par0 = fit12->Value(0);\n  err0 = fit12->ParError(0);\n  TAxis* xaxis12= abilitySocSci->GetXaxis();\n  xaxis12->SetTickLength(0.);\n  xaxis12->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer M}\");\n  xaxis12->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer M}\");\n  xaxis12->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{cand. M}{writer F}\");\n  xaxis12->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{cand. F}{writer F}\");\n  xaxis12->ChangeLabel(2,-1.,0.);\n  xaxis12->ChangeLabel(4,-1.,0.);\n  xaxis12->ChangeLabel(6,-1.,0.);\n  abilitySocSci->SetMaximum(par0 + 5.*abilitySocScicFrF->GetMeanError());\n  abilitySocSci->SetMinimum(TMath::Max(par0 - 5.*abilitySocScicFrF->GetMeanError(),0.));\n  abilitySocSci->SetFillColor(38);\n  abilitySocSci->Draw(\"AB\");\n  TBox* box12 = new TBox(0.6,par0-err0,4.4,par0+err0);\n  box12->SetFillColor(kBlue);\n  box12->SetFillStyle(3004);\n  box12->Draw();\n\n\n      TCanvas* c20 = new TCanvas();\n\n \n    Float_t x20[8] = {1.,2.,3.,4.,5.,6.,7.,8.};\n  Float_t y20[8] = {\n    static_cast<Float_t>(0.139),\n    static_cast<Float_t>(0.096),\n    static_cast<Float_t>(0.173),\n    static_cast<Float_t>(0.240),\n    static_cast<Float_t>(0.459),\n    static_cast<Float_t>(0.455),\n    static_cast<Float_t>(0.230),\n    static_cast<Float_t>(0.210)\n  };\n  Float_t ex20[8] = {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1};\n  Float_t ey20[8] = {0.018*1.96,0.013*1.96,0.020*1.96,0.020*1.96,0.032*1.96,0.027*1.96,0.023*1.96,0.019*1.96};\n\n  TGraphErrors* rankSocSci = new TGraphErrors(8,x20,y20,ex20,ey20);\n  TAxis* rankSocSciAxis = rankSocSci->GetXaxis();\n    rankSocSciAxis->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{rank 0-2}{writer M}\");\n  rankSocSciAxis->ChangeLabel(2,-1.,-1.,-1,-1,-1,\"#splitline{rank 0-2}{writer F}\");\n  rankSocSciAxis->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{rank 3}{writer M}\");\n  rankSocSciAxis->ChangeLabel(4,-1.,-1.,-1,-1,-1,\"#splitline{rank 3}{writer F}\");\n    rankSocSciAxis->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{rank 4}{writer M}\");\n  rankSocSciAxis->ChangeLabel(6,-1.,-1.,-1,-1,-1,\"#splitline{rank 4}{writer F}\");\n  rankSocSciAxis->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{rank 5}{writer M}\");\n  rankSocSciAxis->ChangeLabel(8,-1.,-1.,-1,-1,-1,\"#splitline{rank 5}{writer F}\");\n  TAxis* rankSocSciY = rankSocSci->GetYaxis();\n   rankSocSciY->SetTitle(\"Fraction of Letters (M/F)\");\n   //   rankSocSciY->SetTickLength(0.);\n\n   rankSocSci->SetMaximum(1.0);\n  rankSocSci->SetMinimum(0.0);\n\n  rankSocSci->SetFillColor(38);\n  rankSocSci->SetTitle(\"SocSci Rank\");\n  rankSocSci->Draw(\"AB\");\n  //\n  //physics\n       TCanvas* c21 = new TCanvas();\n\n \n    Float_t x21[8] = {1.,2.,3.,4.,5.,6.,7.,8.};\n  Float_t y21[8] = {\n    static_cast<Float_t>(0.039),\n    static_cast<Float_t>(0.020),\n    static_cast<Float_t>(0.104),\n    static_cast<Float_t>(0.086),\n    static_cast<Float_t>(0.669),\n    static_cast<Float_t>(0.712),\n    static_cast<Float_t>(0.188),\n    static_cast<Float_t>(0.182)\n  };\n  Float_t ex21[8] = {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1};\n  Float_t ey21[8] = {0.006*1.96,.010*1.96,.010*1.96,.021*1.96,.026*1.96,.060*1.96,.014*1.96,.030*1.96};\n\n  TGraphErrors* rankPhysics = new TGraphErrors(8,x21,y21,ex21,ey21);\n  TAxis* rankPhysicsAxis = rankPhysics->GetXaxis();\n    rankPhysicsAxis->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{rank 0-2}{writer M}\");\n  rankPhysicsAxis->ChangeLabel(2,-1.,-1.,-1,-1,-1,\"#splitline{rank 0-2}{writer F}\");\n  rankPhysicsAxis->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{rank 3}{writer M}\");\n  rankPhysicsAxis->ChangeLabel(4,-1.,-1.,-1,-1,-1,\"#splitline{rank 3}{writer F}\");\n    rankPhysicsAxis->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{rank 4}{writer M}\");\n  rankPhysicsAxis->ChangeLabel(6,-1.,-1.,-1,-1,-1,\"#splitline{rank 4}{writer F}\");\n  rankPhysicsAxis->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{rank 5}{writer M}\");\n  rankPhysicsAxis->ChangeLabel(8,-1.,-1.,-1,-1,-1,\"#splitline{rank 5}{writer F}\");\n  TAxis* rankPhysicsY = rankPhysics->GetYaxis();\n   rankPhysicsY->SetTitle(\"Fraction of Letters (M/F)\");\n   //   rankPhysicsY->SetTickLength(0.);\n\n  rankPhysics->SetMaximum(1.0);\n  rankPhysics->SetMinimum(0.0);\n\n  rankPhysics->SetFillColor(38);\n  rankPhysics->SetTitle(\"F/\");\n  rankPhysics->Draw(\"AB\");\n\n  /*********************/\n        TCanvas* c30 = new TCanvas();\n\n \n    Float_t x30[4] = {1.,2.,3.,4.};\n  Float_t y30[4] = {\n    static_cast<Float_t>(0.46),\n    static_cast<Float_t>(1.03),\n     static_cast<Float_t>(0.14),\n    static_cast<Float_t>(0.13)\n };\n  Float_t ex30[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey30[4] ={.047,.084,.014,.028};\n\n  TGraphErrors* fOverMSocSci = new TGraphErrors(4,x30,y30,ex30,ey30);\n  TAxis* fOverMSocSciAxis = fOverMSocSci->GetXaxis();\n    fOverMSocSciAxis->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{     EPP}{male candidate}\");\n  fOverMSocSciAxis->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{       EPP}{female candidate}\");\n  fOverMSocSciAxis->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{social science}{male candidate}\");\n  fOverMSocSciAxis->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{social science}{female candidate}\");\n  TAxis* fOverMSocSciY = fOverMSocSci->GetYaxis();\n   fOverMSocSciY->SetTitle(\"Fraction of Letters (F/M)\");\n   //   fOverMSocSciY->SetTickLength(0.);\n\n\n \n   fOverMSocSci->SetMaximum(1.5);\n  fOverMSocSci->SetMinimum(0.0);\n\n  fOverMSocSci->SetFillColor(38);\n  fOverMSocSci->SetTitle(\"F/M Ratio of Writers\");\n  fOverMSocSci->Draw(\"AB\");\n\n TBox* boxFOverMP = new TBox(2.65,.13,4.4,.19);\n  boxFOverMP->SetFillColor(kBlue);\n  boxFOverMP->SetFillStyle(3004);\n  boxFOverMP->Draw();\n\n   TBox* boxFOverMS = new TBox(0.6,.63,2.35,.71);\n  boxFOverMS->SetFillColor(kBlue);\n  boxFOverMS->SetFillStyle(3004);\n  boxFOverMS->Draw();\n  /******95%CL*****/\n         TCanvas* c31 = new TCanvas();\n\n \n    Float_t x31[4] = {1.,2.,3.,4.};\n  Float_t y31[4] = {\n    static_cast<Float_t>(0.46),\n    static_cast<Float_t>(1.03),\n    static_cast<Float_t>(0.14),\n    static_cast<Float_t>(0.13),\n  };\n  Float_t ex31[4] = {0.1,0.1,0.1,0.1};\n  Float_t ey31[4] = {.047*1.96,.084*1.96,.014*1.96,.028*1.96};\n\n  TGraphErrors* fOverMSocSci95 = new TGraphErrors(4,x31,y31,ex31,ey31);\n  TAxis* fOverMSocSciAxis95 = fOverMSocSci95->GetXaxis();\n    fOverMSocSciAxis95->ChangeLabel(5,-1.,-1.,-1,-1,-1,\"#splitline{     EPP}{male candidate}\");\n  fOverMSocSciAxis95->ChangeLabel(7,-1.,-1.,-1,-1,-1,\"#splitline{       EPP}{female candidate}\");\n  fOverMSocSciAxis95->ChangeLabel(1,-1.,-1.,-1,-1,-1,\"#splitline{social science}{male candidate}\");\n  fOverMSocSciAxis95->ChangeLabel(3,-1.,-1.,-1,-1,-1,\"#splitline{social science}{female candidate}\");\n  TAxis* fOverMSocSciY95 = fOverMSocSci->GetYaxis();\n   fOverMSocSciY95->SetTitle(\"Fraction of Letters (F/M)\");\n   //   fOverMSocSciY->SetTickLength(0.);\n\n\n \n   fOverMSocSci95->SetMaximum(1.5);\n  fOverMSocSci95->SetMinimum(0.0);\n\n  fOverMSocSci95->SetFillColor(38);\n  fOverMSocSci95->SetTitle(\"F/M Ratio of Writers\");\n  fOverMSocSci95->Draw(\"AB\");\n\n TBox* boxFOverMP95 = new TBox(2.65,0.16-1.96*.03,4.4,.16+1.96*.03);\n  boxFOverMP95->SetFillColor(kBlue);\n  boxFOverMP95->SetFillStyle(3004);\n  boxFOverMP95->Draw();\n\n   TBox* boxFOverMS95 = new TBox(0.6,.67-.04*1.96,2.35,.67+.04*1.96);\n  boxFOverMS95->SetFillColor(kBlue);\n  boxFOverMS95->SetFillStyle(3004);\n  boxFOverMS95->Draw();\n  /****/\n  abilityPhysics->Write();\n  abilitySocSci->Write();\n\n  agenticVsCommunalPhysics->Write();\n  agenticVsCommunalPhysicsMaleCand->Write();\n  agenticVsCommunalPhysicsMaleWriter->Write();\n\n  standoutVsGrindstonePhysics->Write();\n  standoutVsGrindstonePhysicsMaleCand->Write();\n  standoutVsGrindstonePhysicsMaleWriter->Write();\n  standoutVsGrindstonePhysicsFemaleCand->Write();\n  standoutVsGrindstonePhysicsFemaleWriter->Write();\n\n  agenticVsCommunalSocSci->Write();\n  agenticVsCommunalSocSciMaleCand->Write();\n  agenticVsCommunalSocSciMaleWriter->Write();\n\n  standoutVsGrindstoneSocSci->Write();\n  standoutVsGrindstoneSocSciMaleCand->Write();\n  standoutVsGrindstoneSocSciMaleWriter->Write();\n  standoutVsGrindstoneSocSciFemaleCand->Write();\n  standoutVsGrindstoneSocSciFemaleWriter->Write();\n\n  f->Close();\n  \n}\n\n\n", "meta": {"hexsha": "efcb0c089db2016873f9f10824a3d81ce7ac64a7", "size": 94173, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "rhbDictRankMedian.cxx", "max_stars_repo_name": "rhbob/genderDifferences", "max_stars_repo_head_hexsha": "4c464151cb2de42a9c649b5ad1e08648281cfe6b", "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": "rhbDictRankMedian.cxx", "max_issues_repo_name": "rhbob/genderDifferences", "max_issues_repo_head_hexsha": "4c464151cb2de42a9c649b5ad1e08648281cfe6b", "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": "rhbDictRankMedian.cxx", "max_forks_repo_name": "rhbob/genderDifferences", "max_forks_repo_head_hexsha": "4c464151cb2de42a9c649b5ad1e08648281cfe6b", "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": 46.4135041893, "max_line_length": 312, "alphanum_fraction": 0.7034075584, "num_tokens": 32334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.15467146542858862}}
{"text": "// Copyright (c) 2015-2021 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 \"assembler.hpp\"\n\n#include <iterator>\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <numeric>\n#include <limits>\n#include <cassert>\n#include <iostream>\n\n#include <boost/functional/hash.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/dag_shortest_paths.hpp>\n#include <boost/graph/dominator_tree.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/exception.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/copy.hpp>\n\n#include \"ksp/yen_ksp.hpp\"\n\n#include \"utils/sequence_utils.hpp\"\n#include \"utils/append.hpp\"\n#include \"utils/maths.hpp\"\n\n#define _unused(x) ((void)(x))\n\nnamespace octopus { namespace coretools {\n\nnamespace {\n\ntemplate <typename I>\nauto sequence_length(const I num_kmers, const unsigned kmer_size) noexcept\n{\n    return num_kmers > 0 ? num_kmers + kmer_size - 1 : 0;\n}\n\ntemplate <typename T>\nstd::size_t count_kmers(const T& sequence, const unsigned kmer_size) noexcept\n{\n    return sequence.size() >= kmer_size ? sequence.size() - kmer_size + 1 : 0;\n}\n\n} // namespace\n\n// public methods\n\nAssembler::NonCanonicalReferenceSequence::NonCanonicalReferenceSequence(NucleotideSequence reference_sequence)\n: std::invalid_argument {\"bad reference sequence\"}\n, reference_sequence_ {std::move(reference_sequence)}\n{}\n\nconst char* Assembler::NonCanonicalReferenceSequence::what() const noexcept\n{\n    return std::invalid_argument::what();\n}\n\nAssembler::Assembler(const Parameters params)\n: params_ {params}\n, reference_kmers_ {}\n, reference_head_position_ {0}\n, reference_vertices_ {}\n{}\n\nAssembler::Assembler(const Parameters params, const NucleotideSequence& reference)\n: params_ {params}\n, reference_kmers_ {}\n, reference_head_position_ {0}\n, reference_vertices_ {}\n{\n    insert_reference_into_empty_graph(reference);\n}\n\nAssembler::Assembler(const Assembler& other)\n: params_ {other.params_}\n, reference_kmers_ {other.reference_kmers_}\n, reference_head_position_ {other.reference_head_position_}\n{\n    std::unordered_map<Vertex, std::size_t> index_map {};\n    index_map.reserve(boost::num_vertices(other.graph_));\n    const auto p = boost::vertices(other.graph_);\n    std::size_t i {0};\n    std::for_each(p.first, p.second, [&i, &index_map] (const Vertex& v) { index_map.emplace(v, i++); });\n    std::unordered_map<Vertex, Vertex> vertex_copy_map {};\n    vertex_copy_map.reserve(boost::num_vertices(other.graph_));\n    boost::copy_graph(other.graph_, this->graph_,\n                      boost::vertex_index_map(boost::make_assoc_property_map(index_map))\n                      .orig_to_copy(boost::make_assoc_property_map(vertex_copy_map)));\n    vertex_cache_ = other.vertex_cache_;\n    for (auto& p : vertex_cache_) {\n        p.second = vertex_copy_map.at(p.second);\n    }\n    reference_vertices_ = other.reference_vertices_;\n    for (auto& v : reference_vertices_) {\n        v = vertex_copy_map.at(v);\n    }\n    for (const auto& other_edge : other.reference_edges_) {\n        Edge e; bool e_in_graph;\n        const auto u = vertex_copy_map.at(boost::source(other_edge, other.graph_));\n        const auto v = vertex_copy_map.at(boost::target(other_edge, other.graph_));\n        std::tie(e, e_in_graph) = boost::edge(u, v, graph_);\n        assert(e_in_graph);\n        reference_edges_.push_back(e);\n    }\n}\n\nunsigned Assembler::kmer_size() const noexcept\n{\n    return params_.kmer_size;\n}\n\nAssembler::Parameters Assembler::params() const\n{\n    return params_;\n}\n\nvoid Assembler::insert_reference(const NucleotideSequence& sequence)\n{\n    if (sequence.size() >= kmer_size()) {\n        if (is_empty()) {\n            insert_reference_into_empty_graph(sequence);\n        } else if (reference_kmers_.empty()) {\n            insert_reference_into_populated_graph(sequence);\n        } else {\n            throw std::runtime_error {\"Assembler: only one reference sequence can be inserted into the graph\"};\n        }\n    } else {\n        throw std::runtime_error {\"Assembler:: reference length must >= kmer_size\"};\n    }\n}\n\nvoid Assembler::insert_read(const NucleotideSequence& sequence,\n                            const BaseQualityVector& base_qualities,\n                            const Direction strand,\n                            const SampleID sample)\n{\n    if (sequence.size() >= kmer_size()) {\n        const bool is_forward_strand {strand == Direction::forward};\n        auto kmer_begin = std::cbegin(sequence);\n        auto kmer_end   = std::next(kmer_begin, kmer_size());\n        auto base_quality_itr = std::next(std::cbegin(base_qualities), kmer_size());\n        Kmer prev_kmer {kmer_begin, kmer_end};\n        bool prev_kmer_good {true};\n        auto vertex_itr = vertex_cache_.find(prev_kmer);\n        auto ref_kmer_itr = std::cbegin(reference_kmers_);\n        if (vertex_itr == std::cend(vertex_cache_)) {\n            const auto u = add_vertex(prev_kmer);\n            if (!u) prev_kmer_good = false;\n        } else if (is_reference(vertex_itr->second)) {\n            ref_kmer_itr = std::find(std::cbegin(reference_kmers_), std::cend(reference_kmers_), prev_kmer);\n            assert(ref_kmer_itr != std::cend(reference_kmers_));\n            auto next_kmer_begin = std::next(kmer_begin);\n            auto next_kmer_end   = std::next(kmer_end);\n            const auto ref_offset = std::distance(std::cbegin(reference_kmers_), ref_kmer_itr);\n            auto ref_vertex_itr = std::next(std::cbegin(reference_vertices_), ref_offset);\n            auto ref_edge_itr = std::next(std::cbegin(reference_edges_), ref_offset);\n            ++ref_kmer_itr;\n            for (; next_kmer_end <= std::cend(sequence) && ref_kmer_itr < std::cend(reference_kmers_);\n                   ++next_kmer_begin, ++next_kmer_end, ++ref_kmer_itr, ++ref_vertex_itr, ++ref_edge_itr, ++base_quality_itr) {\n                if (std::equal(next_kmer_begin, next_kmer_end, std::cbegin(*ref_kmer_itr))) {\n                    assert(ref_edge_itr != std::cend(reference_edges_));\n                    increment_weight(*ref_edge_itr, is_forward_strand, *base_quality_itr, sample);\n                } else {\n                    break;\n                }\n            }\n            if (next_kmer_end > std::cend(sequence)) {\n                return;\n            }\n            kmer_begin = std::prev(next_kmer_begin);\n            kmer_end   = std::prev(next_kmer_end);\n            assert(kmer_end <= std::cend(sequence));\n            prev_kmer = Kmer {kmer_begin, kmer_end};\n        }\n        ++kmer_begin;\n        ++kmer_end;\n        for (; kmer_end <= std::cend(sequence); ++kmer_begin, ++kmer_end, ++base_quality_itr) {\n            Kmer kmer {kmer_begin, kmer_end};\n            const auto kmer_itr = vertex_cache_.find(kmer);\n            if (kmer_itr == std::cend(vertex_cache_)) {\n                const auto v = add_vertex(kmer);\n                if (v) {\n                    if (prev_kmer_good) {\n                        assert(vertex_cache_.count(prev_kmer) == 1);\n                        const auto u = vertex_cache_.at(prev_kmer);\n                        add_edge(u, *v, 1, is_forward_strand, *base_quality_itr, false, sample);\n                    }\n                    prev_kmer_good = true;\n                } else {\n                    prev_kmer_good = false;\n                }\n            } else {\n                if (prev_kmer_good) {\n                    const auto u = vertex_cache_.at(prev_kmer);\n                    const auto v = kmer_itr->second;\n                    Edge e; bool e_in_graph;\n                    std::tie(e, e_in_graph) = boost::edge(u, v, graph_);\n                    if (e_in_graph) {\n                        increment_weight(e, is_forward_strand, *base_quality_itr, sample);\n                    } else {\n                        add_edge(u, v, 1, is_forward_strand, *base_quality_itr, false, sample);\n                    }\n                }\n                if (is_reference(kmer_itr->second)) {\n                    ref_kmer_itr = std::find(ref_kmer_itr, std::cend(reference_kmers_), kmer);\n                    if (ref_kmer_itr != std::cend(reference_kmers_)) {\n                        auto next_kmer_begin = std::next(kmer_begin);\n                        auto next_kmer_end   = std::next(kmer_end);\n                        const auto ref_offset = std::distance(std::cbegin(reference_kmers_), ref_kmer_itr);\n                        auto ref_vertex_itr = std::next(std::cbegin(reference_vertices_), ref_offset);\n                        auto ref_edge_itr = std::next(std::cbegin(reference_edges_), ref_offset);\n                        ++ref_kmer_itr;\n                        for (; next_kmer_end <= std::cend(sequence) && ref_kmer_itr < std::cend(reference_kmers_);\n                               ++next_kmer_begin, ++next_kmer_end, ++ref_kmer_itr, ++ref_vertex_itr, ++ref_edge_itr) {\n                            if (std::equal(next_kmer_begin, next_kmer_end, std::cbegin(*ref_kmer_itr))) {\n                                assert(ref_edge_itr != std::cend(reference_edges_));\n                                increment_weight(*ref_edge_itr, is_forward_strand, *base_quality_itr, sample);\n                            } else {\n                                break;\n                            }\n                        }\n                        if (next_kmer_end > std::cend(sequence)) {\n                            return;\n                        }\n                        kmer_begin = std::prev(next_kmer_begin);\n                        kmer_end   = std::prev(next_kmer_end);\n                        assert(kmer_end <= std::cend(sequence));\n                        kmer = Kmer {kmer_begin, kmer_end};\n                    }\n                }\n                prev_kmer_good = true;\n            }\n            prev_kmer = kmer;\n        }\n    }\n}\n\nstd::size_t Assembler::num_kmers() const noexcept\n{\n    return vertex_cache_.size();\n}\n\nbool Assembler::is_empty() const noexcept\n{\n    return vertex_cache_.empty();\n}\n\nbool Assembler::is_acyclic() const\n{\n    return !(graph_has_trivial_cycle() || graph_has_nontrivial_cycle());\n}\n\nvoid Assembler::remove_nonreference_cycles(bool break_chains)\n{\n    remove_all_nonreference_cycles(break_chains);\n}\n\nnamespace {\n\nstruct CycleDetector : public boost::default_dfs_visitor\n{\n    struct CycleDetectedException {};\n    explicit CycleDetector(bool allow_self_edges = true) : allow_self_edges_ {allow_self_edges} {}\n    \n    template <typename Graph>\n    void back_edge(typename boost::graph_traits<Graph>::edge_descriptor e, const Graph& g)\n    {\n        if (boost::source(e, g) != boost::target(e, g) || !allow_self_edges_) {\n            throw CycleDetectedException {};\n        }\n    }\nprotected:\n    const bool allow_self_edges_;\n};\n\ntemplate <typename Container>\nstruct CyclicEdgeDetector : public boost::default_dfs_visitor\n{\n    CyclicEdgeDetector(Container& result, bool include_self_edges = true)\n    : include_self_edges_ {include_self_edges}, result_ {result} {}\n    \n    template <typename Graph>\n    void back_edge(typename boost::graph_traits<Graph>::edge_descriptor e, const Graph& g)\n    {\n        if (boost::source(e, g) != boost::target(e, g) || include_self_edges_) {\n            result_.push_back(e);\n        }\n    }\nprotected:\n    const bool include_self_edges_;\n    Container& result_;\n};\n\n} // namespace\n\nstd::vector<Assembler::SampleID> Assembler::find_cyclic_samples(const unsigned min_weight) const\n{\n    const auto index_map = boost::get(&GraphNode::index, graph_);\n    std::deque<Edge> cyclic_edges {};\n    CyclicEdgeDetector<decltype(cyclic_edges)> vis {cyclic_edges};\n    boost::depth_first_search(graph_, boost::visitor(vis).root_vertex(reference_head()).vertex_index_map(index_map));\n    std::set<SampleID> cyclic_samples {};\n    for (const Edge& e : cyclic_edges) {\n        if (!is_reference(e)) {\n            for (const auto& p : graph_[e].samples) {\n                if (p.second.weight >= min_weight) {\n                    cyclic_samples.insert(p.first);\n                }\n            } \n        }\n    }\n    return {std::begin(cyclic_samples), std::end(cyclic_samples)};\n}\n\nbool Assembler::is_all_reference() const\n{\n    const auto p = boost::edges(graph_);\n    return std::all_of(p.first, p.second, [this] (const Edge& e) { return is_reference(e); });\n}\n\nbool Assembler::is_unique_reference() const\n{\n    return is_reference_unique_path();\n}\n\nvoid Assembler::try_recover_dangling_branches()\n{\n    const auto p = boost::vertices(graph_);\n    std::for_each(p.first, p.second, [this] (const Vertex& v) {\n        if (is_dangling_branch(v)) {\n            const auto joining_kmer = find_joining_kmer(v);\n            if (joining_kmer) {\n                add_edge(v, *joining_kmer, 1, 0, false);\n            }\n        }\n    });\n}\n\nvoid Assembler::prune(const unsigned min_weight)\n{\n    remove_low_weight_edges(min_weight);\n}\n\nvoid Assembler::cleanup()\n{\n    if (!is_reference_unique_path()) {\n        throw NonUniqueReferenceSequence {};\n    }\n    auto old_size = boost::num_vertices(graph_);\n    if (old_size < 2) return;\n    assert(is_reference_unique_path());\n    remove_disconnected_vertices();\n    auto new_size = boost::num_vertices(graph_);\n    if (new_size != old_size) {\n        regenerate_vertex_indices();\n        if (new_size < 2) return;\n        old_size = new_size;\n    }\n    assert(is_reference_unique_path());\n    remove_vertices_that_cant_be_reached_from(reference_head());\n    new_size = boost::num_vertices(graph_);\n    if (new_size != old_size) {\n        regenerate_vertex_indices();\n        if (new_size < 2) return;\n        old_size = new_size;\n    }\n    assert(is_reference_unique_path());\n    remove_vertices_past(reference_tail());\n    new_size = boost::num_vertices(graph_);\n    if (new_size != old_size) {\n        regenerate_vertex_indices();\n        if (new_size < 2) return;\n        old_size = new_size;\n    }\n    assert(is_reference_unique_path());\n    remove_vertices_that_cant_reach(reference_tail());\n    new_size = boost::num_vertices(graph_);\n    if (new_size != old_size) {\n        regenerate_vertex_indices();\n        if (new_size < 2) return;\n        old_size = new_size;\n    }\n    assert(is_reference_unique_path());\n    prune_reference_flanks();\n    assert(is_reference_unique_path());\n    if (is_reference_empty()) {\n        clear();\n        return;\n    }\n    new_size = boost::num_vertices(graph_);\n    assert(new_size != 0);\n    assert(!(boost::num_edges(graph_) == 0 && new_size > 1));\n    assert(is_reference_unique_path());\n    if (new_size != old_size) {\n        regenerate_vertex_indices();\n    }\n}\n\nvoid Assembler::clear(const std::vector<SampleID>& samples)\n{\n    const auto can_remove_edge = [&] (const Edge& e) {\n        if (is_reference(e)) return false;\n        if (is_artificial(e)) return false;\n        if (graph_[e].samples.size() > samples.size()) return false;\n        const auto includes_sample = [&] (const auto& p) {\n            return std::find(std::cbegin(samples), std::cend(samples), p.first) != std::cend(samples);\n        };\n        return std::all_of(std::cbegin(graph_[e].samples), std::cend(graph_[e].samples), includes_sample);\n    };\n    boost::remove_edge_if(can_remove_edge, graph_);\n    const auto p = boost::edges(graph_);\n    std::for_each(p.first, p.second, [&] (const Edge& e) {\n        auto& edge = graph_[e];\n        for (const auto& sample : samples) {\n            const auto sample_itr = edge.samples.find(sample);\n            if (sample_itr != std::cend(edge.samples)) {\n                edge.weight -= sample_itr->second.weight;\n                edge.forward_strand_weight -= sample_itr->second.forward_strand_weight;\n                edge.base_quality_sum -= sample_itr->second.base_quality_sum;\n                edge.samples.erase(sample_itr);\n            }\n        }\n    });\n}\n\nvoid Assembler::clear()\n{\n    graph_.clear();\n    vertex_cache_.clear();\n    reference_kmers_.clear();\n    reference_kmers_.shrink_to_fit();\n    reference_vertices_.clear();\n    reference_vertices_.shrink_to_fit();\n    reference_edges_.clear();\n    reference_edges_.shrink_to_fit();\n}\n\nbool operator<(const Assembler::Variant& lhs, const Assembler::Variant& rhs) noexcept\n{\n    if (lhs.begin_pos == rhs.begin_pos) {\n        if (lhs.ref.size() == rhs.ref.size()) {\n            return lhs.alt < rhs.alt;\n        }\n        return lhs.ref.size() < rhs.ref.size();\n    }\n    return lhs.begin_pos < rhs.begin_pos;\n}\n\nstd::deque<Assembler::Variant>\nAssembler::extract_variants(const unsigned max_bubbles, const BubbleScoreSetter min_bubble_scorer)\n{\n    if (is_empty() || is_all_reference()) return {};\n    set_all_edge_transition_scores_from(reference_head());\n    auto result = extract_bubble_paths(max_bubbles, min_bubble_scorer);\n    std::sort(std::begin(result), std::end(result));\n    result.erase(std::unique(std::begin(result), std::end(result)), std::end(result));\n    return result;\n}\n\nvoid Assembler::write_dot(std::ostream& out) const\n{\n    const auto vertex_writer = [this] (std::ostream& out, Vertex v) {\n        if (is_reference(v)) {\n            out << \" [shape=box,color=blue]\" << std::endl;\n        } else {\n            out << \" [shape=box,color=red]\" << std::endl;\n        }\n        out << \" [label=\\\"\" << kmer_of(v) << \"\\\"]\" << std::endl;\n    };\n    const auto edge_writer = [this] (std::ostream& out, Edge e) {\n        if (is_reference(e)) {\n            out << \" [color=blue]\" << std::endl;\n        } else if (is_artificial(e)) {\n            out << \" [style=dotted,color=grey]\" << std::endl;\n        } else {\n            out << \" [color=red]\" << std::endl;\n        }\n        out << \" [label=\\\"\" << graph_[e].weight << \"\\\"]\" << std::endl;\n    };\n    const auto graph_writer = [] (std::ostream& out) {\n        out << \"rankdir=LR\" << std::endl;\n    };\n    boost::write_graphviz(out, graph_, vertex_writer, edge_writer, graph_writer);\n}\n\n// Kmer\nAssembler::Kmer::Kmer(SequenceIterator first, SequenceIterator last) noexcept\n: first_ {first}\n, last_ {last}\n, hash_ {boost::hash_range(first_, last_)}\n{}\n\nchar Assembler::Kmer::front() const noexcept\n{\n    return *first_;\n}\n\nchar Assembler::Kmer::back() const noexcept\n{\n    return *std::prev(last_);\n}\n\nAssembler::Kmer::SequenceIterator Assembler::Kmer::begin() const noexcept\n{\n    return first_;\n}\n\nAssembler::Kmer::SequenceIterator Assembler::Kmer::end() const noexcept\n{\n    return last_;\n}\n\nAssembler::Kmer::operator NucleotideSequence() const\n{\n    return NucleotideSequence {first_, last_};\n}\n\nstd::size_t Assembler::Kmer::hash() const noexcept\n{\n    return hash_;\n}\n\nbool operator==(const Assembler::Kmer& lhs, const Assembler::Kmer& rhs) noexcept\n{\n    return std::equal(lhs.first_, lhs.last_, rhs.first_);\n}\n\nbool operator<(const Assembler::Kmer& lhs, const Assembler::Kmer& rhs) noexcept\n{\n    return std::lexicographical_compare(lhs.first_, lhs.last_, rhs.first_, rhs.last_);\n}\n//\n// Assembler private methods\n//\nvoid Assembler::insert_reference_into_empty_graph(const NucleotideSequence& sequence)\n{\n    assert(sequence.size() >= kmer_size());\n    vertex_cache_.reserve(sequence.size() + std::pow(4, 5));\n    auto kmer_begin = std::cbegin(sequence);\n    auto kmer_end   = std::next(kmer_begin, kmer_size());\n    reference_kmers_.emplace_back(kmer_begin, kmer_end);\n    if (!contains_kmer(reference_kmers_.back())) {\n        const auto u = add_vertex(reference_kmers_.back(), true);\n        if (!u) {\n            throw NonCanonicalReferenceSequence {sequence};\n        }\n        reference_vertices_.push_back(*u);\n    } else {\n        reference_vertices_.push_back(vertex_cache_.at(reference_kmers_.back()));\n    }\n    ++kmer_begin;\n    ++kmer_end;\n    for (; kmer_end <= std::cend(sequence); ++kmer_begin, ++kmer_end) {\n        reference_kmers_.emplace_back(kmer_begin, kmer_end);\n        const auto& kmer = reference_kmers_.back();\n        if (!contains_kmer(kmer)) {\n            const auto v = add_vertex(kmer, true);\n            if (v) {\n                reference_vertices_.push_back(*v);\n                const auto u = vertex_cache_.at(std::crbegin(reference_kmers_)[1]);\n                const auto e = add_reference_edge(u, *v);\n                reference_edges_.push_back(e);\n            } else {\n                throw NonCanonicalReferenceSequence {sequence};\n            }\n        } else {\n            const auto u = vertex_cache_.at(std::crbegin(reference_kmers_)[1]);\n            const auto v = vertex_cache_.at(kmer);\n            reference_vertices_.push_back(v);\n            const auto e = add_reference_edge(u, v);\n            reference_edges_.push_back(e);\n        }\n    }\n    assert(reference_vertices_.size() == reference_kmers_.size());\n    assert(reference_edges_.size() == reference_vertices_.size() - 1);\n    reference_kmers_.shrink_to_fit();\n    reference_vertices_.shrink_to_fit();\n    reference_edges_.shrink_to_fit();\n}\n\nvoid Assembler::insert_reference_into_populated_graph(const NucleotideSequence& sequence)\n{\n    assert(sequence.size() >= kmer_size());\n    assert(reference_kmers_.empty());\n    vertex_cache_.reserve(vertex_cache_.size() + sequence.size() + std::pow(4, 5));\n    auto kmer_begin = std::cbegin(sequence);\n    auto kmer_end   = std::next(kmer_begin, kmer_size());\n    reference_kmers_.emplace_back(kmer_begin, kmer_end);\n    if (!contains_kmer(reference_kmers_.back())) {\n        const auto u = add_vertex(reference_kmers_.back(), true);\n        if (!u) {\n            throw NonCanonicalReferenceSequence {sequence};\n        }\n        reference_vertices_.push_back(*u);\n    } else {\n        set_vertex_reference(reference_kmers_.back());\n        reference_vertices_.push_back(vertex_cache_.at(reference_kmers_.back()));\n    }\n    ++kmer_begin;\n    ++kmer_end;\n    for (; kmer_end <= std::cend(sequence); ++kmer_begin, ++kmer_end) {\n        reference_kmers_.emplace_back(kmer_begin, kmer_end);\n        if (!contains_kmer(reference_kmers_.back())) {\n            const auto v = add_vertex(reference_kmers_.back(), true);\n            if (v) {\n                reference_vertices_.push_back(*v);\n                const auto u = vertex_cache_.at(std::crbegin(reference_kmers_)[1]);\n                const auto e = add_reference_edge(u, *v);\n                reference_edges_.push_back(e);\n            } else {\n                throw NonCanonicalReferenceSequence {sequence};\n            }\n        } else {\n            const auto u = vertex_cache_.at(std::crbegin(reference_kmers_)[1]);\n            const auto v = vertex_cache_.at(reference_kmers_.back());\n            reference_vertices_.push_back(v);\n            set_vertex_reference(v);\n            Edge e; bool e_in_graph;\n            std::tie(e, e_in_graph) = boost::edge(u, v, graph_);\n            if (e_in_graph) {\n                set_edge_reference(e);\n            } else {\n                e = add_reference_edge(u, v);\n            }\n            reference_edges_.push_back(e);\n        }\n    }\n    vertex_cache_.rehash(vertex_cache_.size());\n    reference_kmers_.shrink_to_fit();\n    reference_vertices_.shrink_to_fit();\n    reference_edges_.shrink_to_fit();\n    regenerate_vertex_indices();\n    reference_head_position_ = 0;\n}\n\nbool Assembler::contains_kmer(const Kmer& kmer) const noexcept\n{\n    return vertex_cache_.count(kmer) == 1;\n}\n\nstd::size_t Assembler::count_kmer(const Kmer& kmer) const noexcept\n{\n    return vertex_cache_.count(kmer);\n}\n\nstd::size_t Assembler::reference_size() const noexcept\n{\n    return sequence_length(reference_kmers_.size(), kmer_size());\n}\n\nvoid Assembler::regenerate_vertex_indices()\n{\n    const auto p = boost::vertices(graph_);\n    unsigned idx {0};\n    std::for_each(p.first, p.second, [this, &idx] (Vertex v) { graph_[v].index = idx++; });\n}\n\nbool Assembler::is_reference_unique_path() const\n{\n    if (is_reference_empty()) {\n        return true;\n    } else {\n        auto u = reference_head();\n        const auto tail = reference_tail();\n        const auto is_reference_edge = [this] (const Edge e) { return is_reference(e); };\n        while (u != tail) {\n            const auto p = boost::out_edges(u, graph_);\n            const auto itr = std::find_if(p.first, p.second, is_reference_edge);\n            assert(itr != p.second);\n            if (std::any_of(boost::next(itr), p.second, is_reference_edge)) {\n                return false;\n            }\n            u = boost::target(*itr, graph_);\n        }\n        const auto p = boost::out_edges(tail, graph_);\n        return std::none_of(p.first, p.second, is_reference_edge);\n    }\n}\n\nAssembler::Vertex Assembler::null_vertex() const\n{\n    return boost::graph_traits<KmerGraph>::null_vertex();\n}\n\nboost::optional<Assembler::Vertex> Assembler::add_vertex(const Kmer& kmer, const bool is_reference)\n{\n    if (!utils::is_canonical_dna(kmer)) return boost::none;\n    const auto u = boost::add_vertex({boost::num_vertices(graph_), kmer, is_reference}, graph_);\n    vertex_cache_.emplace(kmer, u);\n    return u;\n}\n\nvoid Assembler::remove_vertex(const Vertex v)\n{\n    const auto c = vertex_cache_.erase(kmer_of(v));\n    assert(c == 1);\n    _unused(c); // make production build happy\n    boost::remove_vertex(v, graph_);\n}\n\nvoid Assembler::clear_and_remove_vertex(const Vertex v)\n{\n    const auto c = vertex_cache_.erase(kmer_of(v));\n    assert(c == 1);\n    _unused(c); // make production build happy\n    boost::clear_vertex(v, graph_);\n    boost::remove_vertex(v, graph_);\n}\n\nvoid Assembler::clear_and_remove_all(const std::unordered_set<Vertex>& vertices)\n{\n    for (const Vertex v : vertices) {\n        clear_and_remove_vertex(v);\n    }\n}\n\nAssembler::Edge \nAssembler::add_edge(const Vertex u, const Vertex v,\n                    const GraphEdge::WeightType weight, \n                    GraphEdge::WeightType forward_weight,\n                    const int base_quality_sum,\n                    const bool is_reference,\n                    const boost::optional<Assembler::SampleID> sample)\n{\n    decltype(GraphEdge::samples) samples {};\n    if (sample) {\n        samples[*sample] = {weight, forward_weight, base_quality_sum};\n    }\n    return boost::add_edge(u, v, {std::move(samples), weight, forward_weight, base_quality_sum, is_reference}, graph_).first;\n}\n\nAssembler::Edge Assembler::add_reference_edge(const Vertex u, const Vertex v)\n{\n    return add_edge(u, v, 0, 0, 0, true);\n}\n\nvoid Assembler::remove_edge(const Vertex u, const Vertex v)\n{\n    boost::remove_edge(u, v, graph_);\n}\n\nvoid Assembler::remove_edge(const Edge e)\n{\n    boost::remove_edge(e, graph_);\n}\n\nvoid Assembler::increment_weight(const Edge e, const bool is_forward, const int base_quality, const SampleID sample)\n{\n    auto& edge = graph_[e];\n    auto sample_itr = edge.samples.find(sample);\n    if (sample_itr != std::cend(edge.samples)) {\n        ++sample_itr->second.weight;\n        sample_itr->second.base_quality_sum += base_quality;\n        if (is_forward) ++sample_itr->second.base_quality_sum;\n    } else {\n        edge.samples[sample] = {1, is_forward, base_quality};\n    }\n    ++edge.weight;\n    edge.base_quality_sum += base_quality;\n    if (is_forward) ++edge.forward_strand_weight;\n}\n\nvoid Assembler::set_vertex_reference(const Vertex v)\n{\n    graph_[v].is_reference = true;\n}\n\nvoid Assembler::set_vertex_reference(const Kmer& kmer)\n{\n    set_vertex_reference(vertex_cache_.at(kmer));\n}\n\nvoid Assembler::set_edge_reference(const Edge e)\n{\n    graph_[e].is_reference = true;\n}\n\nconst Assembler::Kmer& Assembler::kmer_of(const Vertex v) const\n{\n    return graph_[v].kmer;\n}\n\nchar Assembler::front_base_of(const Vertex v) const\n{\n    return kmer_of(v).front();\n}\n\nchar Assembler::back_base_of(const Vertex v) const\n{\n    return kmer_of(v).back();\n}\n\nconst Assembler::Kmer& Assembler::source_kmer_of(const Edge e) const\n{\n    return kmer_of(boost::source(e, graph_));\n}\n\nconst Assembler::Kmer& Assembler::target_kmer_of(const Edge e) const\n{\n    return kmer_of(boost::target(e, graph_));\n}\n\nbool Assembler::is_reference(const Vertex v) const\n{\n    return graph_[v].is_reference;\n}\n\nbool Assembler::is_source_reference(const Edge e) const\n{\n    return is_reference(boost::source(e, graph_));\n}\n\nbool Assembler::is_target_reference(const Edge e) const\n{\n    return is_reference(boost::target(e, graph_));\n}\n\nbool Assembler::is_reference(const Edge e) const\n{\n    return graph_[e].is_reference;\n}\n\nbool Assembler::is_artificial(const Edge e) const\n{\n    return graph_[e].samples.empty();\n}\n\nbool Assembler::is_reference_empty() const noexcept\n{\n    return reference_vertices_.empty();\n}\n\nAssembler::Vertex Assembler::reference_head() const\n{\n    return reference_vertices_.front();\n}\n\nAssembler::Vertex Assembler::reference_tail() const\n{\n    return reference_vertices_.back();\n}\n\nAssembler::Vertex Assembler::next_reference(const Vertex u) const\n{\n    const auto p = boost::out_edges(u, graph_);\n    const auto itr = std::find_if(p.first, p.second, [this] (const Edge e) { return is_reference(e); });\n    assert(itr != p.second);\n    return boost::target(*itr, graph_);\n}\n\nAssembler::Vertex Assembler::prev_reference(const Vertex v) const\n{\n    const auto p = boost::in_edges(v, graph_);\n    const auto itr = std::find_if(p.first, p.second, [this] (const Edge e) { return is_reference(e); });\n    assert(itr != p.second);\n    return boost::source(*itr, graph_);\n}\n\nstd::size_t Assembler::num_reference_kmers() const\n{\n    const auto p = boost::vertices(graph_);\n    return std::count_if(p.first, p.second, [this] (const Vertex& v) { return is_reference(v); });\n}\n\nbool Assembler::is_dangling_branch(const Vertex v) const\n{\n    return !is_reference(v) && boost::in_degree(v, graph_) > 0 && boost::out_degree(v, graph_) == 0;\n}\n\nboost::optional<Assembler::Vertex> Assembler::find_joining_kmer(const Vertex v) const\n{\n    const auto& kmer = kmer_of(v);\n    NucleotideSequence adjacent_kmer {std::next(std::cbegin(kmer)), std::cend(kmer)};\n    adjacent_kmer.resize(kmer_size());\n    constexpr std::array<NucleotideSequence::value_type, 4> bases {'A', 'C', 'G', 'T'};\n    for (const auto base : bases) {\n        adjacent_kmer.back() = base;\n        const Kmer k {std::cbegin(adjacent_kmer), std::cend(adjacent_kmer)};\n        const auto itr = vertex_cache_.find(k);\n        if (itr != std::cend(vertex_cache_)) {\n            return itr->second;\n        }\n    }\n    return boost::none;\n}\n\nAssembler::NucleotideSequence Assembler::make_sequence(const Path& path) const\n{\n    assert(!path.empty());\n    NucleotideSequence result(kmer_size() + path.size() - 1, 'N');\n    const auto& first_kmer = kmer_of(path.front());\n    auto itr = std::copy(std::cbegin(first_kmer), std::cend(first_kmer), std::begin(result));\n    std::transform(std::next(std::cbegin(path)), std::cend(path), itr,\n                  [this] (const Vertex v) { return back_base_of(v); });\n    return result;\n}\n\nAssembler::NucleotideSequence Assembler::make_reference(Vertex from, const Vertex to) const\n{\n    const auto null = null_vertex();\n    \n    NucleotideSequence result {};\n    if (from == to || from == null) {\n        return result;\n    }\n    auto last = to;\n    if (last == null) {\n        if (from == reference_tail()) {\n            return static_cast<NucleotideSequence>(kmer_of(from));\n        }\n        last = reference_tail();\n    }\n    result.reserve(2 * kmer_size());\n    const auto& first_kmer = kmer_of(from);\n    result.assign(std::cbegin(first_kmer), std::cend(first_kmer));\n    from = next_reference(from);\n    while (from != last) {\n        result.push_back(back_base_of(from));\n        from = next_reference(from);\n    }\n    if (to == null) {\n        result.push_back(back_base_of(last));\n    }\n    \n    result.shrink_to_fit();\n    \n    return result;\n}\n\nvoid Assembler::remove_path(const std::deque<Vertex>& path)\n{\n    assert(!path.empty());\n    if (path.size() == 1) {\n        clear_and_remove_vertex(path.front());\n    } else {\n        remove_edge(*boost::in_edges(path.front(), graph_).first);\n        auto prev = path.front();\n        std::for_each(std::next(std::cbegin(path)), std::cend(path),\n                      [this, &prev] (const Vertex v) {\n                          remove_edge(prev, v);\n                          remove_vertex(prev);\n                          prev = v;\n                      });\n        remove_edge(*boost::out_edges(path.back(), graph_).first);\n        remove_vertex(path.back());\n    }\n}\n\nbool Assembler::is_bridge(const Vertex v) const\n{\n    return boost::in_degree(v, graph_) == 1 && boost::out_degree(v, graph_) == 1;\n}\n\nbool Assembler::is_reference_bridge(const Vertex v) const\n{\n    return is_reference(v) && is_bridge(v);\n}\n\nAssembler::Path::const_iterator\nAssembler::is_bridge_until(const Path::const_iterator first, const Path::const_iterator last) const\n{\n    return std::find_if_not(first, last, [this] (const Vertex v) { return is_bridge(v); });\n}\n\nAssembler::Path::const_iterator Assembler::is_bridge_until(const Path& path) const\n{\n    return is_bridge_until(std::cbegin(path), std::cend(path));\n}\n\nbool Assembler::is_bridge(Path::const_iterator first, Path::const_iterator last) const\n{\n    return std::all_of(first, last, [this] (const Vertex v) { return is_bridge(v); });\n}\n\nbool Assembler::is_bridge(const Path& path) const\n{\n    return is_bridge(std::cbegin(path), std::cend(path));\n}\n\nstd::pair<bool, Assembler::Vertex> Assembler::is_bridge_to_reference(Vertex from) const\n{\n    while (is_bridge(from)) {\n        from = *boost::adjacent_vertices(from, graph_).first;\n        if (is_reference(from)) {\n            return std::make_pair(true, from);\n        }\n    }\n    return std::make_pair(false, null_vertex());\n}\n\nbool Assembler::joins_reference_only(const Vertex v) const\n{\n    return boost::out_degree(v, graph_) == 1 && is_reference(*boost::out_edges(v, graph_).first);\n}\n\nbool Assembler::joins_reference_only(Path::const_iterator first, Path::const_iterator last) const\n{\n    const auto itr = std::find_if(first, last, [this] (Vertex v) { return is_reference(v) || boost::out_degree(v, graph_) != 1; });\n    return itr == last || is_reference(*itr);\n}\n\nbool Assembler::is_trivial_cycle(const Edge e) const\n{\n    return boost::source(e, graph_) == boost::target(e, graph_);\n}\n\nbool Assembler::graph_has_trivial_cycle() const\n{\n    const auto p = boost::edges(graph_);\n    return std::any_of(p.first, p.second, [this] (const Edge& e) { return is_trivial_cycle(e); });\n}\n\nbool Assembler::graph_has_nontrivial_cycle() const\n{\n    const auto index_map = boost::get(&GraphNode::index, graph_);\n    try {\n        boost::depth_first_search(graph_, boost::visitor(CycleDetector {}).root_vertex(reference_head()).vertex_index_map(index_map));\n        return false;\n    } catch (const CycleDetector::CycleDetectedException&) {\n        return true;\n    }\n}\n\nvoid Assembler::remove_trivial_nonreference_cycles()\n{\n    boost::remove_edge_if([this] (const Edge e) { return !is_reference(e) && is_trivial_cycle(e); }, graph_);\n}\n\nvoid Assembler::remove_nontrivial_nonreference_cycles()\n{\n    const auto index_map = boost::get(&GraphNode::index, graph_);\n    std::deque<Edge> cyclic_edges {};\n    CyclicEdgeDetector<decltype(cyclic_edges)> vis {cyclic_edges, false};\n    boost::depth_first_search(graph_, boost::visitor(vis).root_vertex(reference_head()).vertex_index_map(index_map));\n    for (const Edge& e : cyclic_edges) {\n        if (!(is_reference(e) || is_simple_deletion(e))) {\n            remove_edge(e);\n        }\n    }\n}\n\nvoid Assembler::remove_all_nonreference_cycles(const bool break_chains)\n{\n    const auto index_map = boost::get(&GraphNode::index, graph_);\n    std::deque<Edge> cyclic_edges {};\n    CyclicEdgeDetector<decltype(cyclic_edges)> vis {cyclic_edges};\n    boost::depth_first_search(graph_, boost::visitor(vis).root_vertex(reference_head()).vertex_index_map(index_map));\n    if (cyclic_edges.empty()) return;\n    std::unordered_set<Vertex> bad_kmers {}, reference_origins {}, reference_sinks {};\n    std::deque<std::pair<Vertex, Vertex>> cyclic_reference_segments {};\n    if (break_chains) {\n        bad_kmers.reserve(std::min(2 * cyclic_edges.size(), num_kmers()));\n        reference_origins.reserve(num_reference_kmers());\n    }\n    for (const Edge& back_edge : cyclic_edges) {\n        if (!is_reference(back_edge)) {\n            if (break_chains) {\n                Vertex cycle_origin {boost::source(back_edge, graph_)};\n                while (!is_reference(cycle_origin) && is_bridge(cycle_origin) && bad_kmers.count(cycle_origin) == 0) {\n                    bad_kmers.insert(cycle_origin);\n                    cycle_origin = *boost::inv_adjacent_vertices(cycle_origin, graph_).first;\n                }\n                bool is_reference_origin {false};\n                if (is_reference(cycle_origin)) {\n                    reference_origins.insert(cycle_origin);\n                    is_reference_origin = true;\n                } else {\n                    bad_kmers.insert(cycle_origin);\n                }\n                Vertex cycle_sink {boost::target(back_edge, graph_)};\n                while (!is_reference(cycle_sink) && is_bridge(cycle_sink) && bad_kmers.count(cycle_sink) == 0) {\n                    bad_kmers.insert(cycle_origin);\n                    cycle_sink = *boost::adjacent_vertices(cycle_sink, graph_).first;\n                }\n                if (is_reference(cycle_sink)) {\n                    reference_sinks.insert(cycle_sink);\n                    if (is_reference_origin) {\n                        cyclic_reference_segments.emplace_back(cycle_sink, cycle_origin);\n                    } else if (boost::out_degree(cycle_origin, graph_) > 1) {\n                        const auto p = boost::out_edges(cycle_origin, graph_);\n                        std::vector<Vertex> reference_tails {};\n                        reference_tails.reserve(std::distance(p.first, p.second));\n                        std::for_each(p.first, p.second, [&] (Edge tail_edge) {\n                            if (tail_edge != back_edge) {\n                                auto tail = boost::target(tail_edge, graph_);\n                                while (!is_reference(tail) && boost::out_degree(tail, graph_) == 1\n                                       && bad_kmers.count(tail) == 0) {\n                                    bad_kmers.insert(tail);\n                                    tail = *boost::adjacent_vertices(tail, graph_).first;\n                                }\n                                if (is_reference(tail)) {\n                                    reference_tails.push_back(tail);\n                                }\n                            }\n                        });\n                        if (!reference_tails.empty()) {\n                            Vertex cycle_tail;\n                            if (reference_tails.size() == 1) {\n                                cycle_tail = reference_tails.front();\n                            } else {\n                                // Just add the rightmost reference vertex\n                                auto itr = std::find_first_of(std::crbegin(reference_vertices_), std::crend(reference_vertices_),\n                                                              std::cbegin(reference_tails), std::cend(reference_tails));\n                                assert(itr != std::crend(reference_vertices_));\n                                cycle_tail = *itr;\n                            }\n                            const std::array<Vertex, 2> cycle_vertices {cycle_sink, cycle_tail};\n                            auto itr = std::find_first_of(std::cbegin(reference_vertices_), std::cend(reference_vertices_),\n                                                          std::cbegin(cycle_vertices), std::cend(cycle_vertices));\n                            assert(itr != std::cend(reference_vertices_));\n                            if (*itr == cycle_vertices.front()) {\n                                cyclic_reference_segments.emplace_back(cycle_sink, cycle_tail);\n                            } else {\n                                cyclic_reference_segments.emplace_back(cycle_tail, cycle_sink);\n                            }\n                        }\n                    }\n                } else {\n                    bad_kmers.insert(cycle_sink);\n                }\n            }\n            remove_edge(back_edge);\n        }\n    }\n    bool regenerate_indices {false};\n    for (Vertex v : reference_origins) {\n        boost::remove_in_edge_if(v, [this] (Edge e) { return !is_reference(e); }, graph_);\n        regenerate_indices = true;\n    }\n    for (Vertex v : reference_sinks) {\n        boost::remove_out_edge_if(v, [this] (Edge e) { return !is_reference(e); }, graph_);\n        regenerate_indices = true;\n    }\n    if (!bad_kmers.empty()) {\n        clear_and_remove_all(bad_kmers);\n        regenerate_indices = true;\n    }\n    if (!cyclic_reference_segments.empty()) {\n        for (const auto& p : cyclic_reference_segments) {\n            const auto first_vertex_itr = std::find(std::cbegin(reference_vertices_), std::cend(reference_vertices_), p.first);\n            assert(first_vertex_itr != std::cend(reference_vertices_));\n            const auto last_vertex_itr  = std::find(first_vertex_itr, std::cend(reference_vertices_), p.second);\n            assert(last_vertex_itr != std::cend(reference_vertices_));\n            std::for_each(first_vertex_itr, last_vertex_itr, [this] (Vertex v) {\n                boost::remove_in_edge_if(v, [this] (Edge e) { return !is_reference(e); }, graph_);\n                boost::remove_out_edge_if(v, [this] (Edge e) { return !is_reference(e); }, graph_);\n            });\n        }\n        regenerate_indices = true;\n    }\n    if (regenerate_indices) {\n        regenerate_vertex_indices();\n    }\n}\n\nbool Assembler::is_simple_deletion(Edge e) const\n{\n    return !is_reference(e) && is_source_reference(e) && is_target_reference(e);\n}\n\nbool Assembler::is_on_path(const Edge e, const Path& path) const\n{\n    if (path.size() < 2) return false;\n    auto first_vertex = std::cbegin(path);\n    auto next_vertex = std::next(first_vertex);\n    const auto last_vertex = std::cend(path);\n    Edge path_edge; bool good;\n    for (; next_vertex != last_vertex; ++first_vertex, ++next_vertex) {\n        std::tie(path_edge, good) = boost::edge(*first_vertex, *next_vertex, graph_);\n        assert(good);\n        if (path_edge == e) return true;\n    }\n    return false;\n}\n\nbool Assembler::connects_to_path(Edge e, const Path& path) const\n{\n    return e == *boost::in_edges(path.front(), graph_).first || e == *boost::out_edges(path.back(), graph_).first;\n}\n\nbool Assembler::is_dependent_on_path(Edge e, const Path& path) const\n{\n    return connects_to_path(e, path) || is_on_path(e, path);\n}\n\nAssembler::GraphEdge::WeightType Assembler::weight(const Path& path) const\n{\n    if (path.size() < 2) return 0;\n    return std::inner_product(std::cbegin(path), std::prev(std::cend(path)),\n                              std::next(std::cbegin(path)), GraphEdge::WeightType {0},\n                              std::plus<> {},\n                              [this] (const auto& u, const auto& v) {\n                                  Edge e; bool good;\n                                  std::tie(e, good) = boost::edge(u, v, graph_);\n                                  assert(good);\n                                  return graph_[e].weight;\n                              });\n}\n\nAssembler::GraphEdge::WeightType Assembler::max_weight(const Path& path) const\n{\n    GraphEdge::WeightType result {0};\n    for (std::size_t u {0}, v {1}; v < path.size(); ++u, ++v) {\n        Edge e; bool good;\n        std::tie(e, good) = boost::edge(path[u], path[v], graph_);\n        assert(good);\n        result = std::max(result, graph_[e].weight);\n    }\n    return result;\n}\n\nunsigned Assembler::count_low_weights(const Path& path, const unsigned low_weight) const\n{\n    if (path.size() < 2) return 0;\n    return std::inner_product(std::cbegin(path), std::prev(std::cend(path)), std::next(std::cbegin(path)), 0u, std::plus<> {},\n                              [this, low_weight] (const auto& u, const auto& v) {\n                                  Edge e; bool good;\n                                  std::tie(e, good) = boost::edge(u, v, graph_);\n                                  assert(good);\n                                  return graph_[e].weight <= low_weight ? 1 : 0;\n                              });\n}\n\nbool Assembler::has_low_weight_flanks(const Path& path, const unsigned low_weight) const\n{\n    if (path.size() < 2) return false;\n    Edge e; bool good;\n    std::tie(e, good) = boost::edge(path[0], path[1], graph_);\n    assert(good);\n    if (graph_[e].weight <= low_weight) return true;\n    std::tie(e, good) = boost::edge(std::crbegin(path)[1], std::crbegin(path)[0], graph_);\n    assert(good);\n    return graph_[e].weight <= low_weight;\n}\n\nunsigned Assembler::count_low_weight_flanks(const Path& path, unsigned low_weight) const\n{\n    if (path.size() < 2) return 0;\n    const auto is_low_weight = [this, low_weight] (const auto& u, const auto& v) {\n        Edge e; bool good;\n        std::tie(e, good) = boost::edge(u, v, graph_);\n        assert(good);\n        return graph_[e].weight > low_weight ? 1 : 0;\n    };\n    const auto first_head_high_weight = std::adjacent_find(std::cbegin(path), std::cend(path), is_low_weight);\n    const auto first_tail_high_weight = std::adjacent_find(std::crbegin(path), std::make_reverse_iterator(first_head_high_weight),\n                                                           [&] (const auto& u, const auto& v) {\n                                                               return is_low_weight(v, u);\n                                                           });\n    const auto num_head_low_weight = std::distance(std::cbegin(path), first_head_high_weight);\n    const auto num_tail_low_weight = std::distance(std::crbegin(path), first_tail_high_weight);\n    return static_cast<unsigned>(num_head_low_weight + num_tail_low_weight);\n}\n\nAssembler::PathWeightStats Assembler::compute_weight_stats(const Path& path) const\n{\n    PathWeightStats result {};\n    if (path.size() > 1) {\n        result.max = max_weight(path);\n        result.min = result.max;\n        result.distribution.resize(result.max + 1);\n        std::vector<GraphEdge::WeightType> weights(path.size() - 1);\n        for (std::size_t u {0}, v {1}; v < path.size(); ++u, ++v) {\n            Edge e; bool good;\n            std::tie(e, good) = boost::edge(path[u], path[v], graph_);\n            assert(good);\n            const auto weight = graph_[e].weight;\n            ++result.distribution[weight];\n            result.total += weight;\n            result.min = std::min(result.min, weight);\n            if (!is_artificial(e)) {\n                const auto forward_weight = graph_[e].forward_strand_weight;\n                result.total_forward += forward_weight;\n                result.total_reverse += weight - forward_weight;\n            }\n            weights[u] = weight;\n        }\n        for (auto& w : result.distribution) w /= weights.size();\n        result.mean = static_cast<double>(result.total) / weights.size();\n        result.median = maths::median(weights);\n        result.stdev = maths::stdev(weights);\n    }\n    return result;\n}\n\nAssembler::GraphEdge::WeightType Assembler::sum_source_in_edge_weight(const Edge e) const\n{\n    const auto p = boost::in_edges(boost::source(e, graph_), graph_);\n    using Weight = GraphEdge::WeightType;\n    return std::accumulate(p.first, p.second, Weight {0},\n                           [this] (const Weight curr, const Edge& e) {\n                               return curr + graph_[e].weight;\n                           });\n}\n\nAssembler::GraphEdge::WeightType Assembler::sum_target_out_edge_weight(const Edge e) const\n{\n    const auto p = boost::out_edges(boost::target(e, graph_), graph_);\n    using Weight = GraphEdge::WeightType;\n    return std::accumulate(p.first, p.second, Weight {0},\n                           [this] (const Weight curr, const Edge& e) {\n                               return curr + graph_[e].weight;\n                           });\n}\n\nbool Assembler::all_in_edges_low_weight(Vertex v, unsigned min_weight) const\n{\n    const auto p = boost::in_edges(v, graph_);\n    return std::all_of(p.first, p.second, [this, min_weight] (Edge e) { return graph_[e].weight < min_weight; });\n}\n\nbool Assembler::all_out_edges_low_weight(Vertex v, unsigned min_weight) const\n{\n    const auto p = boost::out_edges(v, graph_);\n    return std::all_of(p.first, p.second, [this, min_weight] (Edge e) { return graph_[e].weight < min_weight; });\n}\n\nbool Assembler::is_low_weight(const Vertex v, const unsigned min_weight) const\n{\n    return !is_reference(v) && all_in_edges_low_weight(v, min_weight) && all_out_edges_low_weight(v, min_weight);\n}\n\nstd::size_t Assembler::low_weight_out_degree(Vertex v, unsigned min_weight) const\n{\n    const auto p = boost::out_edges(v, graph_);\n    const auto d = std::count_if(p.first, p.second, [this, min_weight] (Edge e) { return graph_[e].weight < min_weight; });\n    return static_cast<std::size_t>(d);\n}\n\nstd::size_t Assembler::low_weight_in_degree(Vertex v, unsigned min_weight) const\n{\n    const auto p = boost::in_edges(v, graph_);\n    const auto d = std::count_if(p.first, p.second, [this, min_weight] (Edge e) { return graph_[e].weight < min_weight; });\n    return static_cast<std::size_t>(d);\n}\n\nbool Assembler::is_low_weight_source(Vertex v, unsigned min_weight) const\n{\n    const auto num_low_weight = low_weight_out_degree(v, min_weight);\n    return num_low_weight > 0 && num_low_weight < boost::out_degree(v, graph_);\n}\n\nbool Assembler::is_low_weight_sink(Vertex v, unsigned min_weight) const\n{\n    const auto num_low_weight = low_weight_in_degree(v, min_weight);\n    return num_low_weight > 0 && num_low_weight < boost::in_degree(v, graph_);\n}\n\nnamespace {\n\ntemplate <typename Iterator, typename Set>\nbool all_in(Iterator first, Iterator last, const Set& values)\n{\n    return std::all_of(first, last, [&] (const auto& value) { return values.count(value) == 1; });\n}\n\n} // namespace\n\nvoid Assembler::remove_low_weight_edges(const unsigned min_weight)\n{\n    boost::remove_edge_if([this, min_weight] (const Edge& e) {\n        return !is_reference(e) && graph_[e].weight < min_weight\n               && sum_source_in_edge_weight(e) < min_weight\n               && sum_target_out_edge_weight(e) < min_weight;\n    }, graph_);\n}\n\nvoid Assembler::remove_disconnected_vertices()\n{\n    VertexIterator vi, vi_end, vi_next;\n    std::tie(vi, vi_end) = boost::vertices(graph_);\n    for (vi_next = vi; vi != vi_end; vi = vi_next) {\n        ++vi_next;\n        if (boost::degree(*vi, graph_) == 0) {\n            remove_vertex(*vi);\n        }\n    }\n}\n\nstd::unordered_set<Assembler::Vertex> Assembler::find_reachable_kmers(const Vertex from) const\n{\n    std::unordered_set<Vertex> result {};\n    result.reserve(boost::num_vertices(graph_));\n    auto vis = boost::make_bfs_visitor(boost::write_property(boost::typed_identity_property_map<Vertex>(),\n                                                             std::inserter(result, std::begin(result)),\n                                                             boost::on_discover_vertex()));\n    boost::breadth_first_search(graph_, from,\n                                boost::visitor(vis).vertex_index_map(boost::get(&GraphNode::index, graph_)));\n    return result;\n}\n\nstd::deque<Assembler::Vertex> Assembler::remove_vertices_that_cant_be_reached_from(const Vertex v)\n{\n    const auto reachables = find_reachable_kmers(v);\n    VertexIterator vi, vi_end, vi_next;\n    std::tie(vi, vi_end) = boost::vertices(graph_);\n    std::deque<Vertex> result {};\n    for (vi_next = vi; vi != vi_end; vi = vi_next) {\n        ++vi_next;\n        if (reachables.count(*vi) == 0) {\n            result.push_back(*vi);\n            clear_and_remove_vertex(*vi);\n        }\n    }\n    return result;\n}\n\nvoid Assembler::remove_vertices_that_cant_reach(const Vertex v)\n{\n    if (!is_reference_empty()) {\n        const auto transpose = boost::make_reverse_graph(graph_);\n        const auto index_map = boost::get(&GraphNode::index, transpose);\n        std::unordered_set<Vertex> reachables {};\n        auto vis = boost::make_bfs_visitor(boost::write_property(boost::typed_identity_property_map<Vertex>(),\n                                                                 std::inserter(reachables, std::begin(reachables)),\n                                                                 boost::on_discover_vertex()));\n        boost::breadth_first_search(transpose, v, boost::visitor(vis).vertex_index_map(index_map));\n        VertexIterator vi, vi_end, vi_next;\n        std::tie(vi, vi_end) = boost::vertices(graph_);\n        for (vi_next = vi; vi != vi_end; vi = vi_next) {\n            ++vi_next;\n            if (reachables.count(*vi) == 0) {\n                clear_and_remove_vertex(*vi);\n            }\n        }\n    }\n}\n\nvoid Assembler::remove_vertices_past(const Vertex v)\n{\n    auto reachables = find_reachable_kmers(v);\n    reachables.erase(v);\n    boost::clear_out_edges(v, graph_);\n    std::deque<Vertex> cycle_tails {};\n    // Must check for cycles that lead back to v\n    for (auto u : reachables) {\n        Edge e; bool present;\n        std::tie(e, present) = boost::edge(u, v, graph_);\n        if (present) cycle_tails.push_back(u);\n    }\n    if (!cycle_tails.empty()) {\n        // We can check reachable back edges as the links from v were cut previously\n        const auto transpose = boost::make_reverse_graph(graph_);\n        const auto index_map = boost::get(&GraphNode::index, transpose);\n        std::unordered_set<Vertex> back_reachables {};\n        auto vis = boost::make_bfs_visitor(boost::write_property(boost::typed_identity_property_map<Vertex>(),\n                                                                 std::inserter(back_reachables, std::begin(back_reachables)),\n                                                                 boost::on_discover_vertex()));\n        for (auto u : cycle_tails) {\n            boost::breadth_first_search(transpose, u, boost::visitor(vis).vertex_index_map(index_map));\n            reachables.erase(u);\n        }\n        // The intersection of reachables & back_reachables are vertices part\n        // of a cycle past v. The remaining vertices in reachables are safe to\n        // remove.\n        bool has_intersects {false};\n        for (auto u : back_reachables) {\n            const auto iter = reachables.find(u);\n            if (iter != std::cend(reachables)) {\n                reachables.erase(iter);\n                has_intersects = true;\n            }\n        }\n        if (has_intersects) {\n            const auto removed = remove_vertices_that_cant_be_reached_from(reference_head());\n            for (auto u : removed) reachables.erase(u);\n        }\n    }\n    clear_and_remove_all(reachables);\n}\n\nbool Assembler::can_prune_reference_flanks() const\n{\n    return boost::out_degree(reference_head(), graph_) == 1 || boost::in_degree(reference_tail(), graph_) == 1;\n}\n\nvoid Assembler::pop_reference_head()\n{\n    reference_kmers_.pop_front();\n    reference_vertices_.pop_front();\n    if (!reference_edges_.empty()) {\n        reference_edges_.pop_front();\n    }\n    ++reference_head_position_;\n}\n\nvoid Assembler::pop_reference_tail()\n{\n    reference_kmers_.pop_back();\n    reference_vertices_.pop_back();\n    if (!reference_edges_.empty()) {\n        reference_edges_.pop_back();\n    }\n}\n\nvoid Assembler::prune_reference_flanks()\n{\n    if (!is_reference_empty()) {\n        auto new_head_itr = std::cbegin(reference_vertices_);\n        const auto is_bridge_vertex = [this] (const Vertex v) { return is_bridge(v); };\n        if (boost::in_degree(reference_head(), graph_) == 0 && boost::out_degree(reference_head(), graph_) == 1) {\n            new_head_itr = std::find_if_not(std::next(new_head_itr), std::cend(reference_vertices_), is_bridge_vertex);\n            std::for_each(std::cbegin(reference_vertices_), new_head_itr, [this] (const Vertex u) {\n                remove_edge(u, *boost::adjacent_vertices(u, graph_).first);\n                remove_vertex(u);\n                pop_reference_head();\n            });\n        }\n        if (new_head_itr != std::cend(reference_vertices_) && boost::in_degree(reference_tail(), graph_) == 1\n            && boost::out_degree(reference_tail(), graph_) == 0) {\n            const auto new_tail_itr = std::find_if_not(std::next(std::crbegin(reference_vertices_)),\n                                                       std::make_reverse_iterator(new_head_itr),\n                                                       is_bridge_vertex);\n            std::for_each(std::crbegin(reference_vertices_), new_tail_itr, [this] (const Vertex u) {\n                remove_edge(*boost::inv_adjacent_vertices(u, graph_).first, u);\n                remove_vertex(u);\n                pop_reference_tail();\n            });\n        }\n    }\n}\n\nAssembler::DominatorMap\nAssembler::build_dominator_tree(const Vertex from) const\n{\n    DominatorMap result;\n    result.reserve(boost::num_vertices(graph_));\n    boost::lengauer_tarjan_dominator_tree(graph_, from,  boost::make_assoc_property_map(result));\n    auto it = std::cbegin(result);\n    for (; it != std::cend(result);) {\n        if (it->second == null_vertex()) {\n            it = result.erase(it);\n        } else {\n            ++it;\n        }\n    }\n    result.rehash(result.size());\n    return result;\n}\n\nstd::unordered_set<Assembler::Vertex> Assembler::extract_nondominants(const Vertex from) const\n{\n    const auto dom_tree = build_dominator_tree(from);\n    std::unordered_set<Vertex> dominators {};\n    dominators.reserve(dom_tree.size());\n    for (const auto& p : dom_tree) {\n        dominators.emplace(p.second);\n    }\n    std::unordered_set<Vertex> result {};\n    result.reserve(dom_tree.size());\n    for (const auto& p : dom_tree) {\n        if (dominators.count(p.first) == 0) {\n            result.emplace(p.first);\n        }\n    }\n    return result;\n}\n\nstd::deque<Assembler::Vertex> Assembler::extract_nondominant_reference(const DominatorMap& dominator_tree) const\n{\n    std::unordered_set<Vertex> dominators {};\n    dominators.reserve(dominator_tree.size());\n    for (const auto& p : dominator_tree) {\n        dominators.emplace(p.second);\n    }\n    std::deque<Vertex> result {};\n    for (const auto& p : dominator_tree) {\n        if (is_reference(p.first) && p.first != reference_tail() && dominators.count(p.first) == 0) {\n            result.push_back(p.first);\n        }\n    }\n    return result;\n}\n\nstd::pair<Assembler::Vertex, unsigned> Assembler::find_bifurcation(Vertex from, const Vertex to) const\n{\n    unsigned count {0};\n    while (from != to) {\n        const auto d = boost::out_degree(from, graph_);\n        if (d == 0 || d > 1) {\n            return std::make_pair(from, count);\n        }\n        from = *boost::adjacent_vertices(from, graph_).first;\n        ++count;\n    }\n    return std::make_pair(from, count);\n}\n\ntemplate <typename V, typename G>\nauto count_out_weight(const V& v, const G& g)\n{\n    using T = decltype(g[typename boost::graph_traits<G>::edge_descriptor()].weight);\n    const auto p = boost::out_edges(v, g);\n    return std::accumulate(p.first, p.second, T {0},\n                           [&g] (const auto curr, const auto& e) {\n                               return curr + g[e].weight;\n                           });\n}\n\ntemplate <typename R, typename T>\nauto compute_transition_score(const T edge_weight, const T total_out_weight) noexcept\n{\n    if (total_out_weight == 0) {\n        return R {0};\n    } else if (edge_weight == 0) {\n        return -10 * std::log10(R {1} / total_out_weight);\n    } else if (edge_weight == total_out_weight) {\n        return R {1} / edge_weight;\n    } else {\n        return -10 * std::log10(static_cast<R>(edge_weight) / total_out_weight);\n    }\n}\n\nvoid Assembler::set_out_edge_transition_scores(const Vertex v)\n{\n    const auto total_out_weight = count_out_weight(v, graph_);\n    const auto p = boost::out_edges(v, graph_);\n    using R = GraphEdge::ScoreType;\n    std::for_each(p.first, p.second, [this, total_out_weight] (const Edge& e) {\n        graph_[e].transition_score = compute_transition_score<R>(graph_[e].weight, total_out_weight);\n    });\n}\n\ntemplate <typename R, typename G, typename PropertyMap>\nstruct TransitionScorer : public boost::default_dfs_visitor\n{\n    using Vertex = typename boost::graph_traits<G>::vertex_descriptor;\n    \n    PropertyMap map;\n    \n    TransitionScorer(PropertyMap m) : map {m} {}\n    \n    void discover_vertex(Vertex v, const G& g)\n    {\n        const auto total_out_weight = count_out_weight(v, g);\n        const auto p = boost::out_edges(v, g);\n        std::for_each(p.first, p.second, [this, &g, total_out_weight] (const auto& e) {\n            boost::put(map, e, compute_transition_score<R>(g[e].weight, total_out_weight));\n        });\n    }\n};\n\nvoid Assembler::set_all_edge_transition_scores_from(const Vertex src)\n{\n    auto score_map = boost::get(&GraphEdge::transition_score, graph_);\n    TransitionScorer<GraphEdge::ScoreType, KmerGraph, decltype(score_map)> vis {score_map};\n    boost::depth_first_search(graph_, boost::visitor(vis)\n                              .vertex_index_map(boost::get(&GraphNode::index, graph_)));\n    for (auto p = boost::edges(graph_); p.first != p.second; ++p.first) {\n        graph_[*p.first].transition_score = score_map[*p.first];\n    }\n}\n\nvoid Assembler::set_all_in_edge_transition_scores(const Vertex v, const GraphEdge::ScoreType score)\n{\n    const auto p = boost::in_edges(v, graph_);\n    std::for_each(p.first, p.second, [this, score] (const Edge e) {\n        graph_[e].transition_score = score;\n    });\n}\n\nvoid Assembler::block_all_in_edges(const Vertex v)\n{\n    const auto total_out_weight = count_out_weight(v, graph_);\n    set_all_in_edge_transition_scores(v, compute_transition_score<GraphEdge::ScoreType>(0u, total_out_weight));\n}\n\nAssembler::PredecessorMap Assembler::find_shortest_scoring_paths(const Vertex from, const bool use_weights) const\n{\n    assert(from != null_vertex());\n    std::unordered_map<Vertex, Vertex> result {};\n    result.reserve(boost::num_vertices(graph_));\n    if (use_weights) {\n        boost::dag_shortest_paths(graph_, from,\n                                  boost::weight_map(boost::get(&GraphEdge::weight, graph_))\n                                  .predecessor_map(boost::make_assoc_property_map(result))\n                                  .vertex_index_map(boost::get(&GraphNode::index, graph_)));\n    } else {\n        boost::dag_shortest_paths(graph_, from,\n                                  boost::weight_map(boost::get(&GraphEdge::transition_score, graph_))\n                                  .predecessor_map(boost::make_assoc_property_map(result))\n                                  .vertex_index_map(boost::get(&GraphNode::index, graph_)));\n    }\n    return result;\n}\n\nbool Assembler::is_on_path(const Vertex v, const PredecessorMap& predecessors, const Vertex from) const\n{\n    if (v == from) return true;\n    assert(predecessors.count(from) == 1);\n    auto itr = predecessors.find(from);\n    while (itr != std::end(predecessors) && itr->first != itr->second) {\n        if (itr->second == v) return true;\n        itr = predecessors.find(itr->second);\n    }\n    return false;\n}\n\nbool Assembler::is_on_path(const Edge e, const PredecessorMap& predecessors, const Vertex from) const\n{\n    assert(predecessors.count(from) == 1);\n    const auto last = std::cend(predecessors);\n    auto itr1 = predecessors.find(from);\n    assert(itr1 != last);\n    auto itr2 = predecessors.find(itr1->second);\n    Edge path_edge; bool good;\n    while (itr2 != last && itr1 != itr2) {\n        std::tie(path_edge, good) = boost::edge(itr2->second, itr1->second, graph_);\n        assert(good);\n        if (path_edge == e) {\n            return true;\n        }\n        itr1 = itr2;\n        itr2 = predecessors.find(itr1->second);\n    }\n    return false;\n}\n\nAssembler::Path Assembler::extract_full_path(const PredecessorMap& predecessors, const Vertex from) const\n{\n    assert(predecessors.count(from) == 1);\n    Path result {from};\n    auto itr = predecessors.find(from);\n    while (itr != std::end(predecessors) && itr->first != itr->second) {\n        result.push_front(itr->second);\n        itr = predecessors.find(itr->second);\n    }\n    return result;\n}\n\nstd::tuple<Assembler::Vertex, Assembler::Vertex, unsigned>\nAssembler::backtrack_until_nonreference(const PredecessorMap& predecessors, Vertex from) const\n{\n    assert(predecessors.count(from) == 1);\n    auto v = predecessors.at(from);\n    unsigned count {1};\n    const auto head = reference_head();\n    while (v != head) {\n        assert(from != v); // was not reachable from source\n        const auto p = boost::edge(v, from, graph_);\n        assert(p.second);\n        if (!is_reference(p.first)) break;\n        from = v;\n        assert(predecessors.count(from) == 1);\n        v = predecessors.at(from);\n        ++count;\n    }\n    return std::make_tuple(v, from, count);\n}\n\nAssembler::Path Assembler::extract_nonreference_path(const PredecessorMap& predecessors, Vertex from) const\n{\n    Path result {from};\n    from = predecessors.at(from);\n    while (!is_reference(from)) {\n        result.push_front(from);\n        from = predecessors.at(from);\n    }\n    return result;\n}\n\ntemplate <typename Map>\nauto count_unreachables(const Map& predecessors)\n{\n    return std::count_if(std::cbegin(predecessors), std::cend(predecessors),\n                         [] (const auto& p) { return p.first == p.second; });\n}\n\ntemplate <typename Path, typename Map>\nvoid erase_all(const Path& path, Map& dominator_tree)\n{\n    for (const auto& v : path) dominator_tree.erase(v);\n}\n\ntemplate <typename V, typename BidirectionalIt, typename Map>\nbool is_dominated_by_path(const V& vertex, const BidirectionalIt first, const BidirectionalIt last,\n                          const Map& dominator_tree)\n{\n    const auto& dominator = dominator_tree.at(vertex);\n    const auto rfirst = std::make_reverse_iterator(last);\n    const auto rlast  = std::make_reverse_iterator(first);\n    // reverse because more likely to be a closer vertex\n    return std::find(rfirst, rlast, dominator) != rlast;\n}\n\nAssembler::Edge Assembler::head_edge(const Path& path) const\n{\n    assert(path.size() > 1);\n    Edge e; bool good;\n    std::tie(e, good) = boost::edge(path[0], path[1], graph_);\n    assert(good);\n    return e;\n}\n\nint Assembler::head_mean_base_quality(const Path& path) const\n{\n    const auto& fork_edge = graph_[head_edge(path)];\n    return fork_edge.weight > 0 ? fork_edge.base_quality_sum / fork_edge.weight : 0;\n}\nint Assembler::tail_mean_base_quality(const Path& path) const\n{\n    if (path.size() < 3) return 0;\n    int base_quality_sum {0};\n    const auto add_edge = [&] (const auto& u, const auto& v) {\n        Edge e; bool good;\n        std::tie(e, good) = boost::edge(u, v, graph_);\n        assert(good);\n        base_quality_sum += graph_[e].base_quality_sum;\n        return graph_[e].weight;\n    };\n    auto total_weight = std::inner_product(std::next(std::cbegin(path)), std::prev(std::cend(path)),\n                       std::next(std::cbegin(path), 2), GraphEdge::WeightType {0},\n                       std::plus<> {}, add_edge);\n    return base_quality_sum / total_weight;\n}\n\ndouble Assembler::get_min_bubble_score(Vertex ref_head, Vertex ref_tail, BubbleScoreSetter min_bubble_scorer) const\n{\n    const auto ref_head_itr = std::find(std::cbegin(reference_vertices_), std::cend(reference_vertices_), ref_head);\n    assert(ref_head_itr != std::cend(reference_vertices_));\n    const auto ref_head_idx = static_cast<std::size_t>(std::distance(std::cbegin(reference_vertices_), ref_head_itr));\n    const auto ref_tail_itr = std::find(ref_head_itr, std::cend(reference_vertices_), ref_tail);\n    assert(ref_tail_itr != std::cend(reference_vertices_));\n    const auto ref_tail_idx = static_cast<std::size_t>(std::distance(std::cbegin(reference_vertices_), ref_tail_itr));\n    return min_bubble_scorer(ref_head_idx, ref_tail_idx);\n}\n\nnamespace {\n\ndouble base_quality_probability(const int base_quality)\n{\n    // If the given base quality is zero then there were no observations so just report 1\n    return base_quality > 0 ? maths::phred_to_probability<>(base_quality) : 1.0;\n}\n\n} // namespace\n\ndouble Assembler::bubble_score(const Path& path) const\n{\n    if (path.size() < 2) return 0;\n    const auto weight_stats = compute_weight_stats(path);\n    auto result = static_cast<double>(weight_stats.max);\n    if (params_.use_strand_bias) {\n        GraphEdge::WeightType context_forward_weight {0}, context_reverse_weight {0};\n        const auto add_strand_weights = [&] (const auto& p) {\n            std::for_each(p.first, p.second, [&] (const Edge e) {\n                const auto forward_weight = graph_[e].forward_strand_weight;\n                context_forward_weight += forward_weight;\n                context_reverse_weight += (graph_[e].weight - forward_weight);\n            });\n        };\n        add_strand_weights(boost::in_edges(path.front(), graph_));\n        // path.front() is reference, path.back() is not\n        const auto p = boost::adjacent_vertices(path.back(), graph_);\n        std::for_each(p.first, p.second, [&] (Vertex v) {\n            add_strand_weights(boost::out_edges(v, graph_));\n        });\n        auto pval = maths::fisher_exact_test(weight_stats.total_forward, context_forward_weight,\n                                            weight_stats.total_reverse, context_reverse_weight);\n        if (pval < 0.001) result *= pval;\n    }\n    if (params_.use_base_qualities) {\n        result *= base_quality_probability(head_mean_base_quality(path));\n        if (path.size() > 2) {\n            result *= base_quality_probability(tail_mean_base_quality(path));\n        }\n    }\n    return result;\n}\n\nstd::vector<Assembler::EdgePath> Assembler::extract_k_shortest_paths(Vertex src, Vertex dst, unsigned k) const\n{\n    auto weights = boost::get(&GraphEdge::transition_score, graph_);\n    auto indices = boost::get(&GraphNode::index, graph_);\n    const auto ksps = boost::yen_ksp(graph_, src, dst, std::move(weights), std::move(indices), k);\n    std::vector<EdgePath> result {};\n    result.reserve(k);\n    for (const auto& p : ksps) {\n        result.emplace_back(std::cbegin(p.second), std::cend(p.second));\n    }\n    return result;\n}\n\nstruct BfsSearcherSuccess {};\n\ntemplate <typename Vertex>\nstruct BfsSearcher : public boost::default_bfs_visitor\n{\n    BfsSearcher(Vertex v) : v_ {v} {}\n    \n    template <typename Graph>\n    void discover_vertex(Vertex v, const Graph& g) const\n    {\n        if (v == v_) throw BfsSearcherSuccess {};\n    }\nprivate:\n    Vertex v_;\n};\n\ntemplate <typename Vertex>\nauto make_bfs_searcher(Vertex v)\n{\n    return BfsSearcher<Vertex> {v};\n}\n\nstd::deque<Assembler::Variant>\nAssembler::extract_bubble_paths(unsigned k, const BubbleScoreSetter min_bubble_scorer)\n{\n    auto num_remaining_alt_kmers = num_kmers() - num_reference_kmers();\n    std::deque<Variant> result {};\n    boost::optional<DominatorMap> dominator_tree {};\n    bool use_weights {false};\n    while (k > 0 && num_remaining_alt_kmers > 0) {\n        auto predecessors = find_shortest_scoring_paths(reference_head(), use_weights);\n        assert(count_unreachables(predecessors) == 1);\n        Vertex ref, alt; unsigned rhs_kmer_count;\n        std::tie(alt, ref, rhs_kmer_count) = backtrack_until_nonreference(predecessors, reference_tail());\n        if (alt == reference_head()) {\n            // complete reference path is shortest path\n            if (dominator_tree) {\n                if (use_weights) {\n                    utils::append(extract_bubble_paths_with_ksp(k, min_bubble_scorer), result);\n                    return result;\n                } else {\n                    use_weights = true;\n                    continue;\n                }\n            } else {\n                dominator_tree = build_dominator_tree(reference_head());\n                const auto nondominant_reference = extract_nondominant_reference(*dominator_tree);\n                for (Vertex v : nondominant_reference) {\n                    block_all_in_edges(v);\n                }\n                continue;\n            }\n        }\n        bool removed_bubble {false};\n        while (alt != reference_head()) {\n            auto alt_path = extract_nonreference_path(predecessors, alt);\n            assert(!alt_path.empty());\n            assert(predecessors.count(alt_path.front()) == 1);\n            const auto ref_before_bubble = predecessors.at(alt_path.front());\n            auto ref_seq = make_reference(ref_before_bubble, ref);\n            alt_path.push_front(ref_before_bubble);\n            const auto min_bubble_score = get_min_bubble_score(ref_before_bubble, ref, min_bubble_scorer);\n            const auto score = bubble_score(alt_path);\n            const bool is_extractable {score >= min_bubble_score};\n            auto alt_seq = make_sequence(alt_path);\n            alt_path.pop_front();\n            rhs_kmer_count += count_kmers(ref_seq, kmer_size());\n            if (is_extractable) {\n                const auto pos = reference_head_position_ + reference_size() - sequence_length(rhs_kmer_count, kmer_size());\n                result.emplace_front(pos, std::move(ref_seq), std::move(alt_seq));\n            }\n            --rhs_kmer_count; // because we padded one reference kmer to make ref_seq\n            Edge edge_to_alt; bool good;\n            std::tie(edge_to_alt, good) = boost::edge(alt, ref, graph_);\n            assert(good);\n            if (alt_path.size() == 1 && is_simple_deletion(edge_to_alt)) {\n                remove_edge(alt_path.front(), ref);\n                set_out_edge_transition_scores(alt_path.front());\n            } else {\n                auto vertex_before_bridge = ref_before_bubble;\n                assert(is_reference(vertex_before_bridge));\n                const auto bifurication_point_itr = is_bridge_until(alt_path);\n                if (bifurication_point_itr == std::cend(alt_path)) {\n                    /*\n                           -> ref -> ref -> ->\n                          /                    \\\n                       ref                     ref*\n                          \\                    /\n                            -> alt -> alt -> alt\n                      \n                       The entire alt path can be removed as it never needs to be explored again;\n                       the reference path can always be taken.\n                    */\n                    remove_path(alt_path);\n                    regenerate_vertex_indices();\n                    set_out_edge_transition_scores(vertex_before_bridge);\n                    num_remaining_alt_kmers -= alt_path.size();\n                    alt_path.clear();\n                    removed_bubble = true;\n                } else if (joins_reference_only(bifurication_point_itr, std::cend(alt_path))) {\n                    /*\n                            -> ref -> ref -> ref -> ref ->\n                           /                              \\\n                        ref -> alt -> -> alt              ref\n                           \\                 \\            /\n                            -> alt -> alt -> alt* -> alt ->\n                      \n                       The alt path can be removed up until the bifurication point as one of the other\n                       alt paths can be taken in future paths.\n                    */\n                    if (bifurication_point_itr == std::cbegin(alt_path)) {\n                        remove_edge(ref_before_bubble, alt_path.front());\n                        alt_path.clear();\n                    } else {\n                        alt_path.erase(bifurication_point_itr, std::cend(alt_path));\n                        remove_path(alt_path);\n                    }\n                    regenerate_vertex_indices();\n                    set_out_edge_transition_scores(vertex_before_bridge);\n                    num_remaining_alt_kmers -= alt_path.size();\n                    removed_bubble = true;\n                } else if (boost::in_degree(*bifurication_point_itr, graph_) == 1) {\n                    const auto next_bifurication_point_itr = is_bridge_until(std::next(bifurication_point_itr), std::cend(alt_path));\n                    if (next_bifurication_point_itr != std::cend(alt_path)) {\n                        if (boost::out_degree(*next_bifurication_point_itr, graph_) == 1) {\n                            if (joins_reference_only(next_bifurication_point_itr, std::cend(alt_path))) {\n                                const auto p = boost::adjacent_vertices(*bifurication_point_itr, graph_);\n                                auto is_simple_bubble = std::all_of(p.first, p.second, [&] (Vertex v) {\n                                    if (v == *std::next(bifurication_point_itr)) {\n                                        return true;\n                                    } else {\n                                        try {\n                                            boost::breadth_first_search(graph_, v,\n                                                                        boost::visitor(make_bfs_searcher(*next_bifurication_point_itr)).\n                                                                        vertex_index_map(boost::get(&GraphNode::index, graph_)));\n                                        } catch (const BfsSearcherSuccess&) {\n                                            return true;\n                                        }\n                                        return false;\n                                    }\n                                });\n                                if (is_simple_bubble) {\n                                    /*\n                                            -> ref -> ref -> ref -> ref ->\n                                           /                               \\\n                                        ref         -> alt -> -> alt        ref\n                                           \\      /                  \\     /\n                                            -> alt* -> alt -> alt -> alt ->\n                                    */\n                                    const auto bifurication_point = *bifurication_point_itr;\n                                    if (std::next(bifurication_point_itr) == next_bifurication_point_itr) {\n                                        remove_edge(*bifurication_point_itr, *std::next(bifurication_point_itr));\n                                        alt_path.clear();\n                                    } else {\n                                        alt_path.erase(std::cbegin(alt_path), std::next(bifurication_point_itr));\n                                        alt_path.erase(next_bifurication_point_itr, std::cend(alt_path));\n                                        remove_path(alt_path);\n                                    }\n                                    regenerate_vertex_indices();\n                                    set_all_edge_transition_scores_from(bifurication_point);\n                                    num_remaining_alt_kmers -= alt_path.size();\n                                    removed_bubble = true;\n                                }\n                            }\n                        }\n                    } else {\n                        /*\n                                -> ref -> ref -> ref -> ref ->\n                               /                        /      \\\n                            ref         -> alt -> -> alt        ref\n                               \\      /                        /\n                                -> alt* -> alt -> alt -> alt ->\n                        */\n                        const auto bifurication_point = *bifurication_point_itr;\n                        alt_path.erase(std::cbegin(alt_path), std::next(bifurication_point_itr));\n                        if (alt_path.empty()) {\n                            remove_edge(bifurication_point, ref);\n                        } else {\n                            remove_path(alt_path);\n                        }\n                        regenerate_vertex_indices();\n                        set_all_edge_transition_scores_from(bifurication_point);\n                        num_remaining_alt_kmers -= alt_path.size();\n                        removed_bubble = true;\n                    }\n                }\n            }\n            unsigned kmer_count_to_alt;\n            std::tie(alt, ref, kmer_count_to_alt) = backtrack_until_nonreference(predecessors, ref_before_bubble);\n            rhs_kmer_count += kmer_count_to_alt;\n            if (!use_weights && k > 0) --k;\n        }\n        if (!removed_bubble && use_weights) {\n            if (can_prune_reference_flanks()) {\n                prune_reference_flanks();\n                regenerate_vertex_indices();\n            }\n            utils::append(extract_bubble_paths_with_ksp(k, min_bubble_scorer), result);\n            return result;\n        } else if (!removed_bubble) {\n            use_weights = true;\n        }\n        assert(boost::out_degree(reference_head(), graph_) > 0);\n        assert(boost::in_degree(reference_tail(), graph_) > 0);\n        if (can_prune_reference_flanks()) {\n            prune_reference_flanks();\n            regenerate_vertex_indices();\n        }\n    }\n    return result;\n}\n\nstd::deque<Assembler::SubGraph> Assembler::find_independent_subgraphs() const\n{\n    assert(!reference_vertices_.empty());\n    const auto diverges  = [this] (const Vertex& v) { return boost::out_degree(v, graph_) > 1; };\n    const auto coalesces = [this] (const Vertex& v) { return boost::in_degree(v, graph_) > 1; };\n    auto subgraph_head_itr = std::find_if(std::cbegin(reference_vertices_), std::cend(reference_vertices_), diverges);\n    if (subgraph_head_itr == std::cend(reference_vertices_)) {\n        return {{reference_head(), reference_tail(), 0}};\n    }\n    auto candidate_subgraph_tail_itr = std::find_if(subgraph_head_itr, std::cend(reference_vertices_), coalesces);\n    if (candidate_subgraph_tail_itr == std::cend(reference_vertices_)) {\n        return {{reference_head(), reference_tail(), 0}};\n    } else {\n        std::deque<Vertex> coalescent_points {*candidate_subgraph_tail_itr};\n        std::copy_if(std::next(candidate_subgraph_tail_itr), std::cend(reference_vertices_),\n                     std::front_inserter(coalescent_points), coalesces);\n        const auto dominator = build_dominator_tree(reference_head());\n        std::deque<SubGraph> result {};\n        while (subgraph_head_itr != std::cend(reference_vertices_)) {\n            auto subbgraph_end = std::find_if(std::cbegin(coalescent_points), std::cend(coalescent_points),\n                                              [&] (const Vertex& v) { return dominator.at(v) == *subgraph_head_itr; });\n            assert(subbgraph_end != std::cend(coalescent_points));\n            auto subgraph_offset = static_cast<std::size_t>(std::distance(std::cbegin(reference_vertices_), subgraph_head_itr));\n            result.push_back({*subgraph_head_itr, *subbgraph_end, subgraph_offset});\n            subgraph_head_itr = std::find_if(std::find(subgraph_head_itr, std::cend(reference_vertices_), *subbgraph_end),\n                                             std::cend(reference_vertices_), diverges);\n            coalescent_points.erase(subbgraph_end, std::cend(coalescent_points));\n        }\n        return result;\n    }\n}\n\nstd::deque<Assembler::Variant> Assembler::extract_bubble_paths_with_ksp(const unsigned k, const BubbleScoreSetter min_bubble_scorer)\n{\n    const auto subgraphs = find_independent_subgraphs();\n    std::deque<Variant> result {};\n    for (const auto& subgraph : subgraphs) {\n        auto shortest_paths = extract_k_shortest_paths(subgraph.head, subgraph.tail, k);\n        for (const auto& path : shortest_paths) {\n            assert(!path.empty());\n            const auto is_alt_edge = [this] (const Edge e) { return !is_reference(e); };\n            auto alt_head_itr = std::find_if(std::cbegin(path), std::cend(path), is_alt_edge);\n            auto lhs_kmer_count = std::distance(std::cbegin(path), alt_head_itr);\n            while (alt_head_itr != std::cend(path)) {\n                const auto ref_before_bubble = boost::source(*alt_head_itr, graph_);\n                assert(is_reference(ref_before_bubble));\n                const auto alt_tail_itr = std::find_if(alt_head_itr, std::cend(path), [this] (Edge e) { return is_target_reference(e); });\n                assert(alt_tail_itr != std::cend(path));\n                const auto ref_after_bubble = boost::target(*alt_tail_itr, graph_);\n                assert(!is_reference(*alt_tail_itr));\n                assert(is_reference(ref_after_bubble));\n                auto ref_seq = make_reference(ref_before_bubble, ref_after_bubble);\n                Path alt_path {};\n                std::transform(alt_head_itr, std::next(alt_tail_itr), std::back_inserter(alt_path),\n                               [this] (Edge e) { return boost::source(e, graph_); });\n                const auto num_ref_kmers = count_kmers(ref_seq, kmer_size());\n                const auto min_bubble_score = get_min_bubble_score(ref_before_bubble, ref_after_bubble, min_bubble_scorer);\n                const auto score = bubble_score(alt_path);\n                if (score >= min_bubble_score) {\n                    auto alt_seq = make_sequence(alt_path);\n                    const auto pos = reference_head_position_ + subgraph.reference_offset + lhs_kmer_count;\n                    result.emplace_front(pos, std::move(ref_seq), std::move(alt_seq));\n                }\n                alt_head_itr = std::find_if(std::next(alt_tail_itr), std::cend(path), is_alt_edge);\n                lhs_kmer_count += num_ref_kmers + std::distance(alt_tail_itr, alt_head_itr) - 1;\n            }\n        }\n    }\n    return result;\n}\n\n// debug\n\nstd::ostream& operator<<(std::ostream& os, const Assembler::Kmer& kmer)\n{\n    std::copy(std::cbegin(kmer), std::cend(kmer), std::ostreambuf_iterator<char> {os});\n    return os;\n}\n\nvoid Assembler::print_reference_head() const\n{\n    std::cout << \"reference head is \" << kmer_of(reference_head()) << std::endl;\n}\n\nvoid Assembler::print_reference_tail() const\n{\n    std::cout << \"reference tail is \" << kmer_of(reference_tail()) << std::endl;\n}\n\nvoid Assembler::print_reference_path() const\n{\n    print(reference_vertices_);\n}\n\nvoid Assembler::print(const Edge e) const\n{\n    std::cout << kmer_of(boost::source(e, graph_)) << \"->\" << kmer_of(boost::target(e, graph_));\n}\n\nvoid Assembler::print(const Path& path) const\n{\n    assert(!path.empty());\n    std::transform(std::cbegin(path), std::prev(std::cend(path)), std::ostream_iterator<Kmer> {std::cout, \"->\"},\n                   [this] (const Vertex v) { return kmer_of(v); });\n    std::cout << kmer_of(path.back());\n}\n\nvoid Assembler::print_verbose(const Path& path) const\n{\n    if (path.size() < 2) return;\n    std::transform(std::cbegin(path), std::prev(std::cend(path)), std::next(std::cbegin(path)),\n                   std::ostream_iterator<std::string> {std::cout, \"->\"},\n                   [this] (const auto& u, const auto& v) {\n                       Edge e; bool good;\n                       std::tie(e, good) = boost::edge(u, v, graph_);\n                       assert(good);\n                       auto result = static_cast<std::string>(this->kmer_of(v));\n                       result += \"(\";\n                       result += std::to_string(graph_[e].weight);\n                       result += \", \" + std::to_string(graph_[e].forward_strand_weight);\n                       result += \", \" + std::to_string(graph_[e].base_quality_sum);\n                       result += \")\";\n                       return result;\n                   });\n    std::cout << kmer_of(path.back());\n}\n\nvoid Assembler::print_dominator_tree() const\n{\n    const auto dom_tree = build_dominator_tree(reference_head());\n    for (const auto& p : dom_tree) {\n        std::cout << kmer_of(p.first) << \" dominated by \" << kmer_of(p.second) << std::endl;\n    }\n}\n\n// non-member methods\n\nbool operator==(const Assembler::Variant& lhs, const Assembler::Variant& rhs) noexcept\n{\n    return lhs.begin_pos == rhs.begin_pos && lhs.ref.size() == rhs.ref.size() && lhs.alt == rhs.alt;\n}\n\n} // namespace coretools\n} // namespace octopus\n", "meta": {"hexsha": "6d43b6f2613163a2bf25f0bbff73584fcfd6f96c", "size": 88441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/tools/vargen/utils/assembler.cpp", "max_stars_repo_name": "Schaudge/octopus", "max_stars_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "src/core/tools/vargen/utils/assembler.cpp", "max_issues_repo_name": "Schaudge/octopus", "max_issues_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "src/core/tools/vargen/utils/assembler.cpp", "max_forks_repo_name": "Schaudge/octopus", "max_forks_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 39.3245887061, "max_line_length": 138, "alphanum_fraction": 0.6009543085, "num_tokens": 20105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093882168609, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.1545717711909988}}
{"text": "#pragma once\n\n#include <sensor_msgs/point_cloud_conversion.h>\n#include <boost/foreach.hpp>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PoseWithCovariance.h>\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/Quaternion.h>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <octomap_msgs/Octomap.h>\n#include <octomap/octomap.h>\n#include <octomap/AbstractOcTree.h>\n#include <octomap/ColorOcTree.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <nav_msgs/Path.h>\n#include <nav_msgs/OccupancyGrid.h>\n#include <ros/package.h>\n#include <nav_msgs/Odometry.h>\n#include <visualization_msgs/Marker.h>\n\n#include <fcl/config.h>\n#include <fcl/geometry/octree/octree.h>\n#include <fcl/common/types.h>\n#include <fcl/octree.h>\n#include <fcl/data_types.h>\n#include <fcl/math/vec_3f.h>\n#include <fcl/math/math_details.h>\n\n#include <fcl/narrowphase/collision.h>\n#include <fcl/geometry/collision_geometry.h>\n#include <fcl/narrowphase/collision_request.h>\n#include <fcl/narrowphase/collision_result.h>\n#include <fcl/collision_func_matrix.h>\n#include <fcl/narrowphase/collision_object.h>\n#include <fcl/collision.h>\n#include <ccd/ccd.h>\n#include <ccd/quat.h>\n\n#include <fcl/common/unused.h>\n#include \"fcl/math/constants.h\"\n#include \"fcl/math/triangle.h\"\n\n#include \"fcl/geometry/shape/box.h\"\n#include \"fcl/geometry/shape/sphere.h\"\n#include \"fcl/geometry/shape/cylinder.h\"\n#include \"fcl/geometry/bvh/BVH_model.h\"\n#include \"fcl/geometry/octree/octree.h\"\n\n#include \"fcl/narrowphase/distance.h\"\n#include \"fcl/narrowphase/continuous_collision_object.h\"\n#include \"fcl/narrowphase/continuous_collision_request.h\"\n#include \"fcl/narrowphase/continuous_collision_result.h\"\n\n#include \"fcl/narrowphase/collision.h\"\n#include \"fcl/broadphase/broadphase_bruteforce.h\"\n#include \"fcl/broadphase/broadphase_spatialhash.h\"\n#include \"fcl/broadphase/broadphase_SaP.h\"\n#include \"fcl/broadphase/broadphase_SSaP.h\"\n#include \"fcl/broadphase/broadphase_interval_tree.h\"\n#include \"fcl/broadphase/broadphase_dynamic_AABB_tree.h\"\n#include \"fcl/broadphase/broadphase_dynamic_AABB_tree_array.h\"\n#include \"fcl/broadphase/default_broadphase_callbacks.h\"\n#include \"fcl/geometry/geometric_shape_to_BVH_model.h\"\n\n\n\n#include <cmath>\n#include <limits>\n#include <tf/transform_broadcaster.h>\n#include <octomap_ros/conversions.h>\n#include <grid_map_octomap/GridMapOctomapConverter.hpp>\n#include <grid_map_octomap/grid_map_octomap.hpp>\n#include <moveit/ompl_interface/ompl_interface.h>\n\n\n#include <ompl/geometric/planners/prm/LazyPRMstar.h>\n#include <ompl/geometric/planners/prm/LazyPRM.h>\n#include <ompl/geometric/planners/prm/PRMstar.h>\n#include <ompl/geometric/planners/prm/PRM.h>\n\n#include <ompl/geometric/planners/rrt/RRTstar.h>\n#include <ompl/geometric/planners/rrt/InformedRRTstar.h>\n#include <ompl/geometric/planners/rrt/RRTConnect.h>\n#include <ompl/base/Planner.h>\n\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n#include <ompl/base/spaces/RealVectorBounds.h>\n#include <ompl/base/spaces/SE3StateSpace.h>\n#include <moveit/ompl_interface/ompl_interface.h>\n\n// Eigen\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Geometry>\n#include <eigen3/Eigen/Eigen>\n#include <eigen3/Eigen/Dense>\n\n\n// Octomap conversions\n#include <drone_planning/conversions.h>\n\n// Boost\n#include <boost/thread.hpp>\n\n//standard\n#include <mutex>\n#include <iostream>\n#include <thread>\n#include <fstream>\n#include <iomanip>\n\n#include <string>\n\n#include <array>\n#include <random>\n\n\nnamespace drone_planning{\n\nclass Planner3D\n{\npublic:\n    /*!\n     * Constructor\n     * @param nodeHandle the ros node Handle.\n     */\n    Planner3D(ros::NodeHandle& _nodeHandle);\n\n    /*!\n    * Destructor\n    */\n    virtual ~Planner3D();\n\n    /*!\n     * plan path\n     * @param octomapMsg - Octomap message of enviroment\n     */\n    nav_msgs::Path planPath();\n\n    /// get current start Position - > Useful in visualization\n    void getStartPosition(float &xPos, float &yPos, float &zPos);\n    void getGoalPosition(float &xGoalPos, float &yGoalPos, float &zGoalPos);\n\n    /// configure\n    void configure(const octomap_msgs::Octomap& octomapMsg);\n\n\n\nprivate:\n\n    /// node handle\n    ros::NodeHandle& nodeHandle;\n\n    /// problem dimension\n    int dim;\n\n    /// bounds for all dimensions\n    std::shared_ptr<ompl::base::RealVectorBounds> bounds;\n\n    /// starting and goal position\n    std::shared_ptr<ompl::base::ScopedState<>> start;\n    std::shared_ptr<ompl::base::ScopedState<>> goal;\n\n    /// intersting points to visit on our octomoap\n    /// under pool table, in the little room, under table in biggest room, back room\n    float intrestingX[4] = {4.92, 0.96,-2.75, -6.37};\n    float intrestingY[4] = {2.80, 2.09, 2.42, -2.32};\n\n    unsigned int intrestingPositionsNumber = 4;\n    int curPosition = 0;\n\n    /// space of problem\n    std::shared_ptr<ompl::base::SE3StateSpace> space;\n    /// space information\n    std::shared_ptr<ompl::base::SpaceInformation> si;\n    /// problem definition\n    std::shared_ptr<ompl::base::ProblemDefinition> pdef;\n\n    /* **************************************************************************\n     * CHOOSE YOUR FIGHTER BELOW and in configure() method\n     * Remember to check if you use single query planner or multi-query planner.\n     * Remember to check if you imported library of used planner\n     * Look for usage of clearQuery() and clear() functions in planPath() method.\n     * *************************************************************************/\n    /// planner definition\n    std::shared_ptr<ompl::geometric::LazyPRMstar> planner;\n    /* **************************************************************************\n     * CHOOSE YOUR FIGHTER ABOVE\n     * **************************************************************************/\n\n\n    /// time which planner can use for searching and returning possible path\n    double SOLVING_TIME = 3.0;\n\n    /// get new random goal state\n    void randomizeNewGoalState(void);\n\n    /// save last start state to visualize movement of drone\n    void saveStartState(void);\n\n    /// extract path function\n    nav_msgs::Path extractPath(ompl::base::ProblemDefinition* pdef);\n\n    /// check approximate solution function\n    bool checkApproximateSolution(ompl::base::ProblemDefinition* pdef, double errorThreshold);\n\n    /// add intresting goal positions to vector\n    void addIntrestingGoalPositions(void);\n\n    /// initial move\n    bool initialMove = true;\n\n    /// Goal and start positions. Useful in visualization\n    float xStart, yStart, zStart;\n    float xGoal, yGoal, zGoal;\n\n};\n\n}\n", "meta": {"hexsha": "d59a3db8ba6ef82511883c60c848803a22f980d3", "size": 6523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/drone_planning/drone_planning.hpp", "max_stars_repo_name": "arekmula/drone_planning", "max_stars_repo_head_hexsha": "888769793ba657977abed8c62ac40bd80be453fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-04-23T19:25:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T23:58:26.000Z", "max_issues_repo_path": "include/drone_planning/drone_planning.hpp", "max_issues_repo_name": "arekmula/drone_planning", "max_issues_repo_head_hexsha": "888769793ba657977abed8c62ac40bd80be453fd", "max_issues_repo_licenses": ["MIT"], "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/drone_planning/drone_planning.hpp", "max_forks_repo_name": "arekmula/drone_planning", "max_forks_repo_head_hexsha": "888769793ba657977abed8c62ac40bd80be453fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-27T20:54:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T12:34:43.000Z", "avg_line_length": 29.65, "max_line_length": 94, "alphanum_fraction": 0.7042771731, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.1545717701381051}}
{"text": "// Copyright (c) 2015-2021 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 \"cancer_caller.hpp\"\n\n#include <typeinfo>\n#include <string>\n#include <utility>\n#include <algorithm>\n#include <numeric>\n#include <deque>\n#include <unordered_set>\n#include <stdexcept>\n#include <iostream>\n#include <limits>\n\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\n#include \"basics/genomic_region.hpp\"\n#include \"containers/probability_matrix.hpp\"\n#include \"readpipe/read_pipe.hpp\"\n#include \"core/types/allele.hpp\"\n#include \"core/types/variant.hpp\"\n#include \"core/types/genotype.hpp\"\n#include \"core/models/genotype/uniform_genotype_prior_model.hpp\"\n#include \"core/models/genotype/coalescent_genotype_prior_model.hpp\"\n#include \"core/models/genotype/constant_mixture_genotype_likelihood_model.hpp\"\n#include \"utils/read_stats.hpp\"\n#include \"utils/sequence_utils.hpp\"\n#include \"utils/merge_transform.hpp\"\n#include \"utils/mappable_algorithms.hpp\"\n#include \"utils/maths.hpp\"\n#include \"utils/map_utils.hpp\"\n#include \"logging/logging.hpp\"\n#include \"core/types/calls/germline_variant_call.hpp\"\n#include \"core/types/calls/reference_call.hpp\"\n#include \"core/types/calls/somatic_call.hpp\"\n#include \"core/types/calls/cnv_call.hpp\"\n\nnamespace octopus {\n\n// public methods\n\nCancerCaller::CancerCaller(Caller::Components&& components,\n                           Caller::Parameters general_parameters,\n                           Parameters specific_parameters)\n: Caller {std::move(components), std::move(general_parameters)}\n, parameters_ {std::move(specific_parameters)}\n{\n    if (parameters_.ploidy == 0) {\n        throw std::logic_error {\"CancerCaller: ploidy must be > 0\"};\n    }\n    if (parameters_.max_genotypes && *parameters_.max_genotypes == 0) {\n        throw std::logic_error {\"CancerCaller: max genotypes must be > 0\"};\n    }\n    if (has_normal_sample()) {\n        if (std::find(std::cbegin(samples_), std::cend(samples_), normal_sample()) == std::cend(samples_)) {\n            throw std::invalid_argument {\"CancerCaller: normal sample is not a valid sample\"};\n        }\n    }\n    if (parameters_.concentrations.cnv.normal <= 0.0\n        || parameters_.concentrations.cnv.tumour <= 0.0\n        || parameters_.concentrations.somatic.normal_germline <= 0.0\n        || parameters_.concentrations.somatic.normal_somatic <= 0.0\n        || parameters_.concentrations.somatic.tumour_germline <= 0.0\n        || parameters_.concentrations.somatic.tumour_somatic <= 0.0) {\n        throw std::invalid_argument {\"CancerCaller: concentration parameters must be positive\"};\n    }\n    if (parameters_.min_variant_posterior == Phred<double> {0}) {\n        logging::WarningLogger wlog {};\n        wlog << \"Having no germline variant posterior threshold means no somatic variants will be called\";\n    }\n    if (debug_log_) {\n        if (has_normal_sample()) {\n            stream(*debug_log_) << \"Normal sample is \" << *parameters_.normal_sample;\n        } else {\n            *debug_log_ << \"There is no normal sample\";\n        }\n    }\n    if (!has_normal_sample()) {\n        parameters_.concentrations.cnv.tumour = parameters_.concentrations.somatic.tumour_germline;\n    }\n}\n\n// private methods\n\nstd::string CancerCaller::do_name() const\n{\n    return \"cancer\";\n}\n\nCancerCaller::CallTypeSet CancerCaller::do_call_types() const\n{\n    return {\n        std::type_index(typeid(GermlineVariantCall)),\n        std::type_index(typeid(SomaticCall)),\n        std::type_index(typeid(CNVCall))\n    };\n}\n\nunsigned CancerCaller::do_min_callable_ploidy() const\n{\n    return parameters_.ploidy;\n}\n\nunsigned CancerCaller::do_max_callable_ploidy() const\n{\n    return parameters_.ploidy + parameters_.max_somatic_haplotypes;\n}\n\nbool CancerCaller::has_normal_sample() const noexcept\n{\n    return static_cast<bool>(parameters_.normal_sample);\n}\n\nconst SampleName& CancerCaller::normal_sample() const\n{\n    return *parameters_.normal_sample;\n}\n\nstd::size_t CancerCaller::do_remove_duplicates(HaplotypeBlock& haplotypes) const\n{\n    if (parameters_.deduplicate_haplotypes_with_germline_model) {\n        if (haplotypes.size() < 2) return 0;\n        CoalescentModel::Parameters model_params {};\n        if (parameters_.germline_prior_model_params) model_params = *parameters_.germline_prior_model_params;\n        Haplotype reference {mapped_region(haplotypes), reference_.get()};\n        CoalescentModel model {std::move(reference), model_params, haplotypes.size(), CoalescentModel::CachingStrategy::none};\n        const CoalescentProbabilityGreater cmp {std::move(model)};\n        return octopus::remove_duplicates(haplotypes, cmp);\n    } else {\n        return Caller::do_remove_duplicates(haplotypes);\n    }\n}\n\nstd::unique_ptr<CancerCaller::Caller::Latents>\nCancerCaller::infer_latents(const HaplotypeBlock& haplotypes,\n                            const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    // Store any intermediate results in Latents for reuse, so the order of model evaluation matters!\n    auto result = std::make_unique<Latents>(haplotypes, samples_, parameters_);\n    set_model_priors(*result);\n    generate_germline_genotypes(*result, result->indexed_haplotypes_);\n    if (debug_log_) stream(*debug_log_) << \"There are \" << result->germline_genotypes_.size() << \" candidate germline genotypes\";\n    evaluate_germline_model(*result, haplotype_likelihoods);\n    evaluate_cnv_model(*result, haplotype_likelihoods);\n    if (haplotypes.size() > 1) {\n        fit_somatic_model(*result, haplotype_likelihoods);\n        evaluate_noise_model(*result, haplotype_likelihoods);\n        set_model_posteriors(*result);\n    }\n    return result;\n}\n\nboost::optional<double>\nCancerCaller::calculate_model_posterior(const HaplotypeBlock& haplotypes,\n                                        const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                                        const Caller::Latents& latents) const\n{\n    return calculate_model_posterior(haplotypes, haplotype_likelihoods,\n                                     dynamic_cast<const Latents&>(latents));\n}\n\nvoid CancerCaller::set_cancer_genotype_prior_model(Latents& latents) const\n{\n    SomaticMutationModel mutation_model {parameters_.somatic_mutation_model_params};\n    latents.cancer_genotype_prior_model_ = CancerGenotypePriorModel {*latents.germline_prior_model_, std::move(mutation_model)};\n}\n\nvoid CancerCaller::fit_somatic_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    set_cancer_genotype_prior_model(latents);\n    latents.max_evidence_somatic_model_index_ = 0;\n    latents.cancer_genotypes_.reserve(parameters_.max_somatic_haplotypes);\n    latents.somatic_model_inferences_.reserve(parameters_.max_somatic_haplotypes);\n    latents.somatic_model_posteriors_.reserve(latents.somatic_model_inferences_.size());\n    for (unsigned somatic_ploidy {1}; somatic_ploidy <= parameters_.max_somatic_haplotypes; ++somatic_ploidy) {\n        if (debug_log_) stream(*debug_log_) << \"Fitting somatic model with somatic ploidy \" << somatic_ploidy;\n        latents.inferred_somatic_ploidy_ = somatic_ploidy;\n        generate_cancer_genotypes(latents, haplotype_likelihoods);\n        if (debug_log_) stream(*debug_log_) << \"There are \" << latents.cancer_genotypes_.back().size() << \" candidate cancer genotypes\";\n        evaluate_somatic_model(latents, haplotype_likelihoods);\n        latents.somatic_model_posteriors_.push_back(latents.somatic_model_inferences_.back().approx_log_evidence);\n        if (debug_log_) stream(*debug_log_) << \"Evidence for somatic model with somatic ploidy \"\n                             << somatic_ploidy << \" is \" << latents.somatic_model_posteriors_.back();\n        \n        if (somatic_ploidy > 1) {\n            if (latents.somatic_model_inferences_.back().approx_log_evidence\n              < latents.somatic_model_inferences_[somatic_ploidy - 2].approx_log_evidence) {\n                  latents.inferred_somatic_ploidy_ = somatic_ploidy - 1;\n                break;\n            }\n        } else {\n            set_model_posteriors(latents);\n            if (latents.model_posteriors_.somatic < std::max(latents.model_posteriors_.germline, latents.model_posteriors_.cnv)) {\n                break;\n            }\n        }\n        if (latents.haplotypes_.get().size() <= somatic_ploidy + 1) break;\n    }\n    maths::normalise_exp(latents.somatic_model_posteriors_);\n    if (debug_log_) stream(*debug_log_) << \"Best somatic model has somatic ploidy \" << latents.inferred_somatic_ploidy_;\n    latents.max_evidence_somatic_model_index_ = latents.inferred_somatic_ploidy_ - 1;\n}\n\nstatic double calculate_model_posterior(const double normal_germline_model_log_evidence,\n                                        const double normal_dummy_model_log_evidence)\n{\n    constexpr double normalModelPrior {0.99};\n    constexpr double dummyModelPrior {1.0 - normalModelPrior};\n    const auto normal_model_ljp = std::log(normalModelPrior) + normal_germline_model_log_evidence;\n    const auto dummy_model_ljp  = std::log(dummyModelPrior) + normal_dummy_model_log_evidence;\n    const auto norm = maths::log_sum_exp(normal_model_ljp, dummy_model_ljp);\n    return std::exp(normal_model_ljp - norm);\n}\n\nstatic double calculate_model_posterior(const double germline_model_log_evidence,\n                                        const double dummy_model_log_evidence,\n                                        const double noise_model_log_evidence)\n{\n    constexpr double normalModelPrior {0.99};\n    constexpr double dummyModelPrior {1.0 - normalModelPrior};\n    const auto normal_model_ljp = std::log(normalModelPrior) + germline_model_log_evidence;\n    const auto dummy_model_ljp  = std::log(dummyModelPrior) + dummy_model_log_evidence;\n    const auto noise_model_ljp  = std::log(dummyModelPrior) + noise_model_log_evidence;\n    const auto norm = maths::log_sum_exp(normal_model_ljp, std::max(dummy_model_ljp, noise_model_ljp));\n    return std::exp(normal_model_ljp - norm);\n}\n\nnamespace {\n\nauto demote_each(const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& genotypes)\n{\n    MappableBlock<Genotype<IndexedHaplotype<>>> result {};\n    result.reserve(genotypes.size());\n    std::transform(std::cbegin(genotypes), std::cend(genotypes), std::back_inserter(result),\n                   [] (const auto& genotype) { return demote(genotype); });\n    return result;\n}\n\n} // namespace\n\nboost::optional<double>\nCancerCaller::calculate_model_posterior(const HaplotypeBlock& haplotypes,\n                                        const HaplotypeLikelihoodArray& haplotype_likelihoods,\n                                        const Latents& latents) const\n{\n    if (has_normal_sample()) {\n        assert(latents.germline_model_);\n        const auto& germline_model = *latents.germline_model_;\n        haplotype_likelihoods.prime(normal_sample());\n        GermlineModel::InferredLatents normal_inferences;\n        if (latents.normal_germline_inferences_) {\n            normal_inferences = *latents.normal_germline_inferences_;\n        } else {\n            normal_inferences = germline_model.evaluate(latents.germline_genotypes_, haplotype_likelihoods);\n        }\n        const auto dummy_genotypes = demote_each(latents.cancer_genotypes_[latents.max_evidence_somatic_model_index_]);\n        const auto dummy_inferences = germline_model.evaluate(dummy_genotypes, haplotype_likelihoods);\n        if (latents.noise_model_inferences_) {\n            return octopus::calculate_model_posterior(normal_inferences.log_evidence,\n                                                      dummy_inferences.log_evidence,\n                                                      latents.noise_model_inferences_->approx_log_evidence);\n        } else {\n            return octopus::calculate_model_posterior(normal_inferences.log_evidence,\n                                                      dummy_inferences.log_evidence);\n        }\n    } else {\n        // TODO\n        return boost::none;\n    }\n}\n\nvoid CancerCaller::generate_germline_genotypes(Latents& latents, const IndexedHaplotypeBlock& haplotypes) const\n{\n    latents.germline_genotypes_ = generate_all_genotypes(haplotypes, parameters_.ploidy);\n}\n\nnamespace {\n\ntemplate <typename... T>\nauto zip(const T&... containers) -> boost::iterator_range<boost::zip_iterator<decltype(boost::make_tuple(std::begin(containers)...))>>\n{\n    auto zip_begin = boost::make_zip_iterator(boost::make_tuple(std::begin(containers)...));\n    auto zip_end   = boost::make_zip_iterator(boost::make_tuple(std::end(containers)...));\n    return boost::make_iterator_range(zip_begin, zip_end);\n}\n\ntemplate <typename Range>\nauto zip_cref(const Range& values, const std::vector<double>& probabilities)\n{\n    using ValueReference = std::reference_wrapper<const typename Range::value_type>;\n    std::vector<std::pair<ValueReference, double>> result {};\n    result.reserve(values.size());\n    std::transform(std::cbegin(values), std::cend(values), std::cbegin(probabilities), std::back_inserter(result),\n                   [] (const auto& v, const auto& p) noexcept { return std::make_pair(std::cref(v), p); });\n    return result;\n}\n\ntemplate <typename G>\nMappableBlock<G>\ncopy_greatest_probability_values(const MappableBlock<G>& values,\n                                 const std::vector<double>& probabilities,\n                                 const std::size_t n,\n                                 const boost::optional<double> min_include_probability = boost::none,\n                                 const boost::optional<double> max_exclude_probability = boost::none)\n{\n    assert(values.size() == probabilities.size());\n    if (values.size() <= n) return values;\n    auto value_probabilities = zip_cref(values, probabilities);\n    auto last_include_itr = std::next(std::begin(value_probabilities), n);\n    const auto probability_greater = [] (const auto& lhs, const auto& rhs) noexcept { return lhs.second > rhs.second; };\n    std::partial_sort(std::begin(value_probabilities), last_include_itr, std::end(value_probabilities), probability_greater);\n    if (min_include_probability) {\n        last_include_itr = std::upper_bound(std::begin(value_probabilities), last_include_itr, *min_include_probability,\n                                            [] (auto lhs, const auto& rhs) noexcept { return lhs > rhs.second; });\n        if (last_include_itr == std::begin(value_probabilities)) ++last_include_itr;\n    }\n    if (max_exclude_probability) {\n        last_include_itr = std::partition(last_include_itr, std::end(value_probabilities),\n                                          [&] (const auto& p) noexcept { return p.second > *max_exclude_probability; });\n    }\n    MappableBlock<G> result {mapped_region(values)};\n    result.reserve(std::distance(std::begin(value_probabilities), last_include_itr));\n    std::transform(std::begin(value_probabilities), last_include_itr, std::back_inserter(result),\n                   [] (const auto& p) { return p.first.get(); });\n    return result;\n}\n\ntemplate <typename G>\nauto copy_greatest_probability_genotypes(const MappableBlock<G>& genotypes,\n                                         const std::vector<double>& probabilities,\n                                         const std::size_t n,\n                                         const boost::optional<double> min_include_probability = boost::none,\n                                         const boost::optional<double> max_exclude_probability = boost::none)\n{\n    assert(genotypes.size() == probabilities.size());\n    return copy_greatest_probability_values(genotypes, probabilities, n, min_include_probability, max_exclude_probability);\n}\n\nauto calculate_posteriors_with_germline_likelihood_model(const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& genotypes,\n                                                         const CancerGenotypePriorModel& prior_model,\n                                                         const model::ConstantMixtureGenotypeLikelihoodModel likelihood_model,\n                                                         const std::vector<SampleName>& samples)\n{\n    auto result = evaluate(genotypes, prior_model);\n    for (const auto& sample : samples) {\n        likelihood_model.cache().prime(sample);\n        std::transform(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(result), std::begin(result),\n                       [&] (const auto& genotype, auto curr) {\n                           return curr + likelihood_model.evaluate(demote(genotype));\n                       });\n    }\n    maths::normalise_exp(result);\n    return result;\n}\n\nvoid filter_with_germline_model(MappableBlock<CancerGenotype<IndexedHaplotype<>>>& genotypes,\n                                const CancerGenotypePriorModel& prior_model,\n                                const model::ConstantMixtureGenotypeLikelihoodModel likelihood_model,\n                                const std::vector<SampleName>& samples,\n                                const std::size_t n)\n{\n    const auto germline_model_posteriors = calculate_posteriors_with_germline_likelihood_model(genotypes, prior_model, likelihood_model, samples);\n    genotypes = copy_greatest_probability_genotypes(genotypes, germline_model_posteriors, n);\n}\n\n} // namespace\n\nvoid CancerCaller::generate_cancer_genotypes(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    const auto num_haplotypes = latents.indexed_haplotypes_.size();\n    if (num_haplotypes == 1) return;\n    const auto& germline_genotypes = latents.germline_genotypes_;\n    const auto num_germline_genotypes = germline_genotypes.size();\n    const auto max_possible_cancer_genotypes = num_haplotypes * num_germline_genotypes;\n    if (!parameters_.max_genotypes || max_possible_cancer_genotypes <= *parameters_.max_genotypes) {\n        generate_cancer_genotypes(latents, latents.germline_genotypes_);\n    } else if (has_normal_sample()) {\n        if (has_high_normal_contamination_risk(latents)) {\n            generate_cancer_genotypes_with_contaminated_normal(latents, haplotype_likelihoods);\n        } else {\n            generate_cancer_genotypes_with_clean_normal(latents, haplotype_likelihoods);\n        }\n    } else {\n        generate_cancer_genotypes_with_no_normal(latents, haplotype_likelihoods);\n    }\n}\n\nauto calculate_max_germline_genotype_bases(const unsigned max_genotypes, const unsigned num_haplotypes,\n                                           const unsigned somatic_ploidy)\n{\n    const auto num_somatic_genotypes = num_genotypes(num_haplotypes, somatic_ploidy);\n    return std::max(max_genotypes / num_somatic_genotypes, decltype(num_somatic_genotypes) {1});\n}\n\nnamespace {\n\nstruct CancerGenotypeLess\n{\n    template <typename T>\n    bool operator()(const CancerGenotype<T>& lhs, const CancerGenotype<T>& rhs) const\n    {\n        return lhs.germline() == rhs.germline() ? GenotypeLess()(lhs.somatic(), rhs.somatic()) : GenotypeLess()(lhs.germline(), rhs.germline());\n    }\n};\n\ntemplate <typename IndexType>\nvoid erase_duplicates(MappableBlock<CancerGenotype<IndexedHaplotype<IndexType>>>& genotypes)\n{\n    using std::begin; using std::end;\n    std::sort(begin(genotypes), end(genotypes), CancerGenotypeLess {});\n    genotypes.erase(std::unique(begin(genotypes), end(genotypes)), end(genotypes));\n}\n\n} // namespace\n\nvoid CancerCaller::generate_cancer_genotypes_with_clean_normal(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(parameters_.max_genotypes);\n    const auto num_haplotypes = latents.indexed_haplotypes_.size();\n    const auto& germline_genotypes = latents.germline_genotypes_;\n    const auto max_allowed_cancer_genotypes = *parameters_.max_genotypes;\n    if (!latents.cancer_genotypes_.empty()) {\n        const auto max_old_cancer_genotype_bases = std::max(max_allowed_cancer_genotypes / num_haplotypes, std::size_t {1});\n        const auto& cancer_genotype_posteriors = latents.somatic_model_inferences_.back().weighted_genotype_posteriors;\n        const auto old_cancer_genotype_bases = copy_greatest_probability_values(latents.cancer_genotypes_.back(), cancer_genotype_posteriors, max_old_cancer_genotype_bases);\n        latents.cancer_genotypes_.push_back(extend_somatic(old_cancer_genotype_bases, latents.indexed_haplotypes_));\n        erase_duplicates(latents.cancer_genotypes_.back());\n    } else {\n        assert(latents.germline_model_);\n        haplotype_likelihoods.prime(normal_sample());\n        latents.normal_germline_inferences_ = latents.germline_model_->evaluate(germline_genotypes, haplotype_likelihoods);\n        const auto& germline_normal_posteriors = latents.normal_germline_inferences_->posteriors.genotype_probabilities;\n        const auto max_germline_genotype_bases = calculate_max_germline_genotype_bases(max_allowed_cancer_genotypes, num_haplotypes, 1);\n        MappableBlock<Genotype<IndexedHaplotype<>>> germline_bases;\n        germline_bases = copy_greatest_probability_genotypes(germline_genotypes, germline_normal_posteriors, max_germline_genotype_bases, 1e-100, 1e-2);\n        latents.cancer_genotypes_.push_back(generate_all_cancer_genotypes(germline_bases, latents.indexed_haplotypes_, 1));\n        if (latents.cancer_genotypes_.size() > 2 * max_allowed_cancer_genotypes) {\n            if (!latents.cancer_genotype_prior_model_->mutation_model().is_primed()) {\n                latents.cancer_genotype_prior_model_->mutation_model().prime(latents.haplotypes_.get());\n            }\n            const model::ConstantMixtureGenotypeLikelihoodModel likelihood_model {haplotype_likelihoods};\n            filter_with_germline_model(latents.cancer_genotypes_.back(), *latents.cancer_genotype_prior_model_,\n                                       likelihood_model, samples_, max_allowed_cancer_genotypes);\n        }\n    }\n}\n\nvoid CancerCaller::generate_cancer_genotypes_with_contaminated_normal(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    // TODO\n    generate_cancer_genotypes_with_clean_normal(latents, haplotype_likelihoods);\n}\n\nnamespace {\n\nstruct GenotypeReferenceEqual\n{\n    using GenotypeReference = std::reference_wrapper<const Genotype<IndexedHaplotype<>>>;\n    std::size_t operator()(const GenotypeReference& lhs, const GenotypeReference& rhs) const\n    {\n        return lhs.get() == rhs.get();\n    }\n};\n\ntemplate <typename BidirIt, typename T, typename Compare>\nBidirIt binary_find(BidirIt first, BidirIt last, const T& value, Compare cmp)\n{\n    const auto itr = std::lower_bound(first, last, value, std::move(cmp));\n    return (itr != last && *itr == value) ? itr : last;\n}\n\n} // namespace\n\nvoid CancerCaller::generate_cancer_genotypes_with_no_normal(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(parameters_.max_genotypes);\n    const auto num_haplotypes = latents.indexed_haplotypes_.size();\n    const auto& germline_genotypes = latents.germline_genotypes_;\n    const auto max_allowed_cancer_genotypes = *parameters_.max_genotypes;\n    if (!latents.cancer_genotypes_.empty()) {\n        const auto max_old_cancer_genotype_bases = std::max(max_allowed_cancer_genotypes / num_haplotypes, std::size_t {1});\n        const auto& cancer_genotype_posteriors = latents.somatic_model_inferences_.back().max_evidence_params.genotype_probabilities;\n        const auto old_cancer_genotype_bases = copy_greatest_probability_values(latents.cancer_genotypes_.back(), cancer_genotype_posteriors, max_old_cancer_genotype_bases);\n        latents.cancer_genotypes_.push_back(extend_somatic(old_cancer_genotype_bases, latents.indexed_haplotypes_));\n    } else {\n        const auto max_germline_genotype_bases = calculate_max_germline_genotype_bases(max_allowed_cancer_genotypes, num_haplotypes, 1);\n        const auto& germline_genotype_posteriors = latents.germline_model_inferences_.posteriors.genotype_probabilities;\n        std::vector<double> germline_model_haplotype_posteriors(num_haplotypes);\n        for (std::size_t g {0}; g < germline_genotypes.size(); ++g) {\n            for (const auto& haplotype : collapse(germline_genotypes[g])) {\n                germline_model_haplotype_posteriors[index_of(haplotype)] += germline_genotype_posteriors[g];\n            }\n        }\n        const auto max_germline_haplotype_bases = max_num_elements(max_germline_genotype_bases, parameters_.ploidy);\n        const auto top_haplotypes = copy_greatest_probability_values(latents.indexed_haplotypes_, germline_model_haplotype_posteriors,\n                                                                     max_germline_haplotype_bases);\n        auto germline_bases = generate_all_genotypes(top_haplotypes, parameters_.ploidy);\n        latents.cancer_genotypes_.push_back(generate_all_cancer_genotypes(germline_bases, latents.indexed_haplotypes_, 1));\n        if (latents.cancer_genotypes_.size() > 2 * max_allowed_cancer_genotypes) {\n            if (!latents.cancer_genotype_prior_model_->mutation_model().is_primed()) {\n                latents.cancer_genotype_prior_model_->mutation_model().prime(latents.haplotypes_);\n            }\n            const model::ConstantMixtureGenotypeLikelihoodModel likelihood_model {haplotype_likelihoods};\n            filter_with_germline_model(latents.cancer_genotypes_.back(), *latents.cancer_genotype_prior_model_,\n                                       likelihood_model, samples_, max_allowed_cancer_genotypes);\n        }\n    }\n}\n\nvoid CancerCaller::generate_cancer_genotypes(Latents& latents, const MappableBlock<Genotype<IndexedHaplotype<>>>& germline_genotypes) const\n{\n    latents.cancer_genotypes_.push_back(generate_all_cancer_genotypes(germline_genotypes, latents.indexed_haplotypes_, latents.inferred_somatic_ploidy_));\n}\n\nbool CancerCaller::has_high_normal_contamination_risk(const Latents& latents) const\n{\n    return parameters_.normal_contamination_risk == Parameters::NormalContaminationRisk::high;\n}\n\nvoid CancerCaller::evaluate_germline_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(!(latents.indexed_haplotypes_.empty() || latents.germline_genotypes_.empty()));\n    latents.germline_prior_model_ = make_germline_prior_model(latents.haplotypes_);\n    latents.germline_model_ = std::make_unique<GermlineModel>(*latents.germline_prior_model_);\n    const auto pooled_likelihoods = haplotype_likelihoods.merge_samples();\n    latents.germline_prior_model_->prime(latents.haplotypes_);\n    latents.germline_model_->prime(latents.haplotypes_);\n    latents.germline_model_inferences_ = latents.germline_model_->evaluate(latents.germline_genotypes_, pooled_likelihoods);\n}\n\nvoid CancerCaller::evaluate_cnv_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(!latents.germline_genotypes_.empty() && latents.germline_prior_model_);\n    auto cnv_model_priors = get_cnv_model_priors(*latents.germline_prior_model_);\n    CNVModel::AlgorithmParameters params {};\n    if (parameters_.max_vb_seeds) params.max_seeds = *parameters_.max_vb_seeds;\n    params.target_max_memory = this->target_max_memory();\n    params.execution_policy = this->exucution_policy();\n    CNVModel cnv_model {samples_, cnv_model_priors, params};\n    cnv_model.prime(latents.haplotypes_);\n    latents.cnv_model_inferences_ = cnv_model.evaluate(latents.germline_genotypes_,  haplotype_likelihoods);\n}\n\nvoid CancerCaller::evaluate_somatic_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    assert(latents.germline_prior_model_ && !latents.cancer_genotypes_.empty() && !latents.cancer_genotypes_.back().empty());\n    assert(latents.cancer_genotype_prior_model_);\n    auto somatic_model_priors = get_somatic_model_priors(*latents.cancer_genotype_prior_model_, latents.inferred_somatic_ploidy_);\n    SomaticModel::AlgorithmParameters params {};\n    if (parameters_.max_vb_seeds) params.max_seeds = *parameters_.max_vb_seeds;\n    params.target_max_memory = this->target_max_memory();\n    params.execution_policy = this->exucution_policy();\n    SomaticModel model {samples_, somatic_model_priors, params};\n    assert(latents.cancer_genotype_prior_model_->germline_model().is_primed());\n    if (!latents.cancer_genotype_prior_model_->mutation_model().is_primed()) {\n        latents.cancer_genotype_prior_model_->mutation_model().prime(latents.haplotypes_);\n    }\n    model.prime(latents.haplotypes_);\n    latents.somatic_model_inferences_.push_back(model.evaluate(latents.cancer_genotypes_.back(), haplotype_likelihoods));\n}\n\nauto get_high_posterior_genotypes(const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& genotypes,\n                                  const model::SomaticSubcloneModel::InferredLatents& latents)\n{\n    return copy_greatest_probability_values(genotypes, latents.max_evidence_params.genotype_probabilities, 10, 1e-3);\n}\n\nvoid CancerCaller::evaluate_noise_model(Latents& latents, const HaplotypeLikelihoodArray& haplotype_likelihoods) const\n{\n    if (has_normal_sample() && !has_high_normal_contamination_risk(latents)) {\n        if (!latents.normal_germline_inferences_) {\n            assert(latents.germline_model_);\n            haplotype_likelihoods.prime(normal_sample());\n            latents.normal_germline_inferences_ = latents.germline_model_->evaluate(latents.germline_genotypes_, haplotype_likelihoods);\n        }\n        assert(latents.cancer_genotype_prior_model_);\n        auto noise_model_priors = get_noise_model_priors(*latents.cancer_genotype_prior_model_, latents.inferred_somatic_ploidy_);\n        const SomaticModel noise_model {{*parameters_.normal_sample}, noise_model_priors};\n        const auto& best_cancer_genotypes = latents.cancer_genotypes_[latents.max_evidence_somatic_model_index_];\n        const auto& best_somatic_inferences = latents.somatic_model_inferences_[latents.max_evidence_somatic_model_index_];\n        auto noise_genotypes = get_high_posterior_genotypes(best_cancer_genotypes, best_somatic_inferences);\n        latents.noise_model_inferences_ = noise_model.evaluate(noise_genotypes, haplotype_likelihoods);\n    }\n}\n\nvoid CancerCaller::set_model_priors(Latents& latents) const\n{\n    if (has_normal_sample()) {\n        latents.model_priors_ = {.09, 0.01, 0.9};\n    } else {\n        latents.model_priors_ = {.09, 0.001, 0.909};\n    }\n}\n\nvoid CancerCaller::set_model_posteriors(Latents& latents) const\n{\n    const auto& germline_inferences = latents.germline_model_inferences_;\n    const auto& cnv_inferences      = latents.cnv_model_inferences_;\n    const auto& somatic_inferences  = latents.somatic_model_inferences_[latents.max_evidence_somatic_model_index_];\n    const auto& model_priors        = latents.model_priors_;\n    if (debug_log_) {\n        stream(*debug_log_) << \"Germline model evidence: \" << germline_inferences.log_evidence;\n        stream(*debug_log_) << \"CNV model evidence:      \" << cnv_inferences.approx_log_evidence;\n        stream(*debug_log_) << \"Somatic model evidence:  \" << somatic_inferences.approx_log_evidence;\n    }\n    const auto germline_model_jlp = std::log(model_priors.germline) + germline_inferences.log_evidence;\n    const auto cnv_model_jlp      = std::log(model_priors.cnv) + cnv_inferences.approx_log_evidence;\n    const auto somatic_model_jlp  = std::log(model_priors.somatic) + somatic_inferences.approx_log_evidence;\n    const auto norm = maths::log_sum_exp(germline_model_jlp, cnv_model_jlp, somatic_model_jlp);\n    latents.model_posteriors_.germline = std::exp(germline_model_jlp - norm);\n    latents.model_posteriors_.cnv      = std::exp(cnv_model_jlp - norm);\n    latents.model_posteriors_.somatic  = std::exp(somatic_model_jlp - norm);\n    const auto check_sum = latents.model_posteriors_.germline + latents.model_posteriors_.cnv + latents.model_posteriors_.somatic;\n    if (check_sum > 1.0) {\n        latents.model_posteriors_.germline /= check_sum;\n        latents.model_posteriors_.cnv /= check_sum;\n        latents.model_posteriors_.somatic /= check_sum;\n    }\n}\n\nCancerCaller::CNVModel::Priors\nCancerCaller::get_cnv_model_priors(const GenotypePriorModel& prior_model) const\n{\n    using Priors = CNVModel::Priors;\n    Priors::GenotypeMixturesDirichletAlphaMap cnv_alphas {};\n    cnv_alphas.reserve(samples_.size());\n    for (const auto& sample : samples_) {\n        if (has_normal_sample() && sample == normal_sample()) {\n            Priors::GenotypeMixturesDirichletAlphas sample_alphas(parameters_.ploidy, parameters_.concentrations.cnv.normal);\n            cnv_alphas.emplace(sample, std::move(sample_alphas));\n        } else {\n            Priors::GenotypeMixturesDirichletAlphas sample_alphas(parameters_.ploidy, parameters_.concentrations.cnv.tumour);\n            cnv_alphas.emplace(sample, std::move(sample_alphas));\n        }\n    }\n    return Priors {prior_model, std::move(cnv_alphas)};\n}\n\nauto make_dirichlet_alphas(unsigned n_germline, double germline, unsigned n_somatic, double somatic)\n{\n    model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas result(n_germline + n_somatic);\n    std::fill_n(std::begin(result), n_germline, germline);\n    std::fill_n(std::rbegin(result), n_somatic, somatic);\n    return result;\n}\n\nCancerCaller::SomaticModel::Priors\nCancerCaller::get_somatic_model_priors(const CancerGenotypePriorModel& prior_model, const unsigned somatic_ploidy) const\n{\n    using Priors = SomaticModel::Priors;\n    Priors::GenotypeMixturesDirichletAlphaMap alphas {};\n    alphas.reserve(samples_.size());\n    for (const auto& sample : samples_) {\n        if (has_normal_sample() && sample == normal_sample()) {\n            alphas.emplace(sample, make_dirichlet_alphas(parameters_.ploidy, parameters_.concentrations.somatic.normal_germline,\n                                                         somatic_ploidy, parameters_.concentrations.somatic.normal_somatic));\n        } else {\n            alphas.emplace(sample, make_dirichlet_alphas(parameters_.ploidy, parameters_.concentrations.somatic.tumour_germline,\n                                                         somatic_ploidy, parameters_.concentrations.somatic.tumour_somatic));\n        }\n    }\n    return Priors {prior_model, std::move(alphas)};\n}\n\nCancerCaller::SomaticModel::Priors\nCancerCaller::get_noise_model_priors(const CancerGenotypePriorModel& prior_model, const unsigned somatic_ploidy) const\n{\n    // The noise model is intended to capture noise that may also be present in the normal sample,\n    // hence all samples have the same prior alphas.\n    using Priors = SomaticModel::Priors;\n    auto noise_alphas = make_dirichlet_alphas(parameters_.ploidy, parameters_.concentrations.somatic.normal_germline,\n                                              somatic_ploidy, parameters_.concentrations.somatic.tumour_somatic);\n    Priors::GenotypeMixturesDirichletAlphaMap alphas {};\n    alphas.reserve(samples_.size());\n    for (const auto& sample : samples_) {\n        alphas.emplace(sample, noise_alphas);\n    }\n    return Priors {prior_model, std::move(alphas)};\n}\n\nCancerCaller::CNVModel::Priors\nCancerCaller::get_normal_noise_model_priors(const GenotypePriorModel& prior_model) const\n{\n    using Priors = CNVModel::Priors;\n    Priors::GenotypeMixturesDirichletAlphaMap cnv_alphas {};\n    if (has_normal_sample()) {\n        Priors::GenotypeMixturesDirichletAlphas sample_alphas(parameters_.ploidy, 0.5);\n        cnv_alphas.emplace(normal_sample(), std::move(sample_alphas));\n    }\n    return Priors {prior_model, std::move(cnv_alphas)};\n}\n\nstd::vector<std::unique_ptr<VariantCall>>\nCancerCaller::call_variants(const std::vector<Variant>& candidates,\n                                   const Caller::Latents& latents) const\n{\n    return call_variants(candidates, dynamic_cast<const Latents&>(latents));\n}\n\nnamespace {\n\nusing VariantReference  = std::reference_wrapper<const Variant>;\nusing VariantPosteriorVector = std::vector<std::pair<VariantReference, Phred<double>>>;\n\nauto compute_marginal_credible_interval(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas& alphas,\n                                        const std::size_t k, const double mass)\n{\n    const auto a0 = std::accumulate(std::cbegin(alphas), std::cend(alphas), 0.0);\n    return maths::beta_hdi(alphas[k], a0 - alphas[k], mass);\n}\n\nstruct VAFStats\n{\n    using CredibleRegion = std::pair<double, double>;\n    CredibleRegion credible_region;\n    double map, count;\n};\n\nauto compute_vaf_stats(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas& alphas,\n                       const double credible_mass)\n{\n    const auto a0 = std::accumulate(std::cbegin(alphas), std::cend(alphas), 0.0);\n    std::vector<VAFStats> result {};\n    result.reserve(alphas.size());\n    for (std::size_t i {0}; i < alphas.size(); ++i) {\n        auto map_vaf = maths::dirichlet_expectation(i, alphas);\n        auto vaf_cr = maths::beta_hdi(alphas[i], a0 - alphas[i], credible_mass);\n        result.push_back({vaf_cr, map_vaf, alphas[i]});\n    }\n    return result;\n}\n\nusing VAFStatsVector = std::vector<VAFStats>;\nusing VAFStatsMap = std::unordered_map<SampleName, VAFStatsVector>;\n\nauto compute_vaf_stats(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphaMap& alphas,\n                       const double credible_mass)\n{\n    VAFStatsMap result {};\n    result.reserve(alphas.size());\n    for (const auto& p : alphas) {\n        result.emplace(p.first, compute_vaf_stats(p.second, credible_mass));\n    }\n    return result;\n}\n\nauto compute_credible_somatic_mass(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphas& alphas,\n                                   const unsigned somatic_ploidy, const double min_credible_somatic_frequency)\n{\n    if (somatic_ploidy == 1) {\n        return maths::dirichlet_marginal_sf(alphas, alphas.size() - 1, min_credible_somatic_frequency);\n    } else {\n        double inv_result {1.0};\n        for (unsigned i {1}; i <= somatic_ploidy; ++i) {\n            inv_result *= maths::dirichlet_marginal_cdf(alphas, alphas.size() - i, min_credible_somatic_frequency);\n        }\n        return 1.0 - inv_result;\n    }\n}\n\nauto compute_credible_somatic_mass(const model::SomaticSubcloneModel::Priors::GenotypeMixturesDirichletAlphaMap& alphas,\n                                   const unsigned somatic_ploidy, const double min_credible_somatic_frequency)\n{\n    double inv_result {1.0};\n    for (const auto& p : alphas) {\n        if (somatic_ploidy == 1) {\n            inv_result *= maths::dirichlet_marginal_cdf(p.second, p.second.size() - 1, min_credible_somatic_frequency);\n        } else {\n            inv_result *= 1.0 - compute_credible_somatic_mass(p.second, somatic_ploidy, min_credible_somatic_frequency);\n        }\n    }\n    return 1.0 - inv_result;\n}\n\nstruct GermlineVariantCall : Mappable<GermlineVariantCall>\n{\n    GermlineVariantCall() = delete;\n    GermlineVariantCall(const std::pair<VariantReference, Phred<double>>& p)\n    : variant {p.first}\n    , posterior {p.second}\n    {}\n    GermlineVariantCall(const Variant& variant, Phred<double> posterior)\n    : variant {variant}\n    , posterior {posterior}\n    {}\n    \n    const GenomicRegion& mapped_region() const noexcept { return octopus::mapped_region(variant.get()); }\n    \n    VariantReference variant;\n    Phred<double> posterior, segregation_quality;\n};\n\nusing GermlineVariantCalls = std::vector<GermlineVariantCall>;\n\nstruct SomaticVariantCall : Mappable<SomaticVariantCall>\n{\n    SomaticVariantCall() = delete;\n    SomaticVariantCall(const std::pair<VariantReference, Phred<double>>& p)\n    : variant {p.first}, posterior {p.second} {}\n    SomaticVariantCall(const Variant& variant, Phred<double> posterior)\n    : variant {variant}, posterior {posterior} {}\n    \n    const GenomicRegion& mapped_region() const noexcept { return octopus::mapped_region(variant.get()); }\n    \n    VariantReference variant;\n    Phred<double> posterior, segregation_quality;\n};\n\nusing SomaticVariantCalls = std::vector<SomaticVariantCall>;\n\nstruct GermlineGenotypeCall\n{\n    template <typename T>\n    GermlineGenotypeCall(T&& genotype, Phred<double> posterior)\n    : genotype {std::forward<T>(genotype)}\n    , somatic {}\n    , posterior {posterior}\n    {}\n    template <typename T, typename A>\n    GermlineGenotypeCall(T&& genotype, A&& somatic, Phred<double> posterior)\n    : genotype {std::forward<T>(genotype)}\n    , somatic {std::forward<A>(somatic)}\n    , posterior {posterior}\n    {}\n    \n    Genotype<Allele> genotype, somatic;\n    Phred<double> posterior;\n};\n\nusing GermlineGenotypeCalls = std::vector<GermlineGenotypeCall>;\n\nstruct CancerGenotypeCall\n{\n    template <typename T>\n    CancerGenotypeCall(T&& genotype, Phred<double> posterior)\n    : genotype {std::forward<T>(genotype)}, posterior {posterior} {}\n    \n    CancerGenotype<Allele> genotype;\n    Phred<double> posterior;\n    VAFStatsMap vaf_stats;\n};\n\nusing CancerGenotypeCalls = std::vector<CancerGenotypeCall>;\n\ntemplate <typename L>\nauto find_map_genotype(const L& posteriors)\n{\n    return std::max_element(std::cbegin(posteriors), std::cend(posteriors),\n                            [] (const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; });\n}\n\n// germline variant posterior calculations\n\ntemplate <typename M>\nPhred<double> marginalise(const Allele& allele, const M& genotype_posteriors)\n{\n    auto p = std::accumulate(std::cbegin(genotype_posteriors), std::cend(genotype_posteriors),\n                             0.0, [&allele] (const auto curr, const auto& p) {\n                                 return curr + (contains(p.first, allele) ? 0.0 : p.second);\n                             });\n    return probability_false_to_phred(p);\n}\n\ntemplate <typename M>\nVariantPosteriorVector compute_candidate_posteriors(const std::vector<Variant>& candidates, const M& genotype_posteriors)\n{\n    VariantPosteriorVector result {};\n    result.reserve(candidates.size());\n    for (const auto& candidate : candidates) {\n        result.emplace_back(candidate, marginalise(candidate.alt_allele(), genotype_posteriors));\n    }\n    return result;\n}\n\n// segregation probability\n\nusing BigFloat = boost::multiprecision::mpf_float_1000;\n\nBigFloat marginalise(const Allele& allele, const MappableBlock<Genotype<IndexedHaplotype<>>>& genotypes, const std::vector<double>& probabilities)\n{\n    assert(genotypes.size() == probabilities.size());\n    auto inv_result = std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities),\n                                         0.0, std::plus<> {}, [&allele] (const auto& genotype, const auto probability) {\n        return contains(genotype, allele) ? 0.0 : probability; });\n    return BigFloat {1.0} - BigFloat {inv_result};\n}\n\nbool is_somatic(const Allele& allele, const CancerGenotype<IndexedHaplotype<>>& genotype)\n{\n    return contains(genotype.somatic(), allele) && !contains(genotype.germline(), allele);\n}\n\nBigFloat marginalise(const Allele& allele, const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& genotypes, const std::vector<double>& probabilities,\n                     const BigFloat somatic_mass_complement)\n{\n    assert(genotypes.size() == probabilities.size());\n    const BigFloat contained_complement {std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities),\n                                                  0.0, std::plus<> {}, [&] (const auto& genotype, const auto probability) {\n        return contains(genotype, allele) ? 0.0 : probability; })};\n    BigFloat somatic_complement {std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities),\n                                                 0.0, std::plus<> {}, [&] (const auto& genotype, const auto probability) {\n        return is_somatic(allele, genotype) ? probability : 0.0; })};\n    somatic_complement *= somatic_mass_complement;\n    const BigFloat result_complement {contained_complement + somatic_complement};\n    assert(result_complement >= 0.0 && result_complement <= 1.0);\n    return BigFloat {1.0} - result_complement;\n}\n\nPhred<double>\ncalculate_segregation_probability(const Allele& allele,\n                                  const MappableBlock<Genotype<IndexedHaplotype<>>>& germline_genotypes,\n                                  const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& cancer_genotypes,\n                                  const std::vector<double>& germline_genotype_probabilities,\n                                  const std::vector<double>& cnv_genotype_probabilities,\n                                  const std::vector<double>& cancer_genotype_probabilities,\n                                  const BigFloat germline_probability,\n                                  const BigFloat cnv_probability,\n                                  const BigFloat somatic_probability,\n                                  const BigFloat somatic_mass)\n{\n    auto prob_germline_segregates = marginalise(allele, germline_genotypes, germline_genotype_probabilities);\n    prob_germline_segregates *= germline_probability;\n    auto prob_cnv_segregates = marginalise(allele, germline_genotypes, cnv_genotype_probabilities);\n    prob_cnv_segregates *= cnv_probability;\n    auto prob_somatic_segregates = marginalise(allele, cancer_genotypes, cancer_genotype_probabilities, BigFloat {1.0} - somatic_mass);\n    prob_somatic_segregates *= somatic_probability;\n    const BigFloat prob_segregates {prob_germline_segregates + prob_cnv_segregates + prob_somatic_segregates};\n    return probability_true_to_phred<double>(prob_segregates);\n}\n\nPhred<double>\ncalculate_segregation_probability(const Allele& allele,\n                                  const MappableBlock<Genotype<IndexedHaplotype<>>>& germline_genotypes,\n                                  const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& cancer_genotypes,\n                                  const std::vector<double>& germline_genotype_probabilities,\n                                  const std::vector<double>& cnv_genotype_probabilities,\n                                  const std::vector<double>& cancer_genotype_probabilities,\n                                  const double germline_probability,\n                                  const double cnv_probability,\n                                  const double somatic_probability,\n                                  const double somatic_mass)\n{\n    BigFloat germline_bf {germline_probability}, cnv_bf {cnv_probability}, somatic_bf {somatic_probability};\n    const BigFloat norm {germline_bf + cnv_bf + somatic_bf};\n    germline_bf /= norm; cnv_bf /= norm; somatic_bf /= norm;\n    return calculate_segregation_probability(allele, germline_genotypes, cancer_genotypes,\n                                             germline_genotype_probabilities, cnv_genotype_probabilities, cancer_genotype_probabilities,\n                                             germline_bf, cnv_bf, somatic_bf, BigFloat {somatic_mass});\n}\n\nPhred<double> calculate_somatic_posterior(const double somatic_model_posterior, const double somatic_mass)\n{\n    BigFloat somatic_posterior {somatic_model_posterior};\n    somatic_posterior *= somatic_mass;\n    return probability_true_to_phred<double>(somatic_posterior);\n}\n\n// germline variant calling\n\nbool contains_alt(const Genotype<IndexedHaplotype<>>& genotype_call, const VariantReference& candidate)\n{\n    return includes(genotype_call, candidate.get().alt_allele());\n}\n\nauto call_candidates(const VariantPosteriorVector& candidate_posteriors,\n                     const Genotype<IndexedHaplotype<>>& genotype_call,\n                     const Phred<double> min_posterior)\n{\n    GermlineVariantCalls calls {};\n    calls.reserve(candidate_posteriors.size());\n    std::vector<VariantReference> uncalled {};\n    for (const auto& p : candidate_posteriors) {\n        if (p.second >= min_posterior && contains_alt(genotype_call, p.first)) {\n            calls.emplace_back(p.first, p.second);\n        } else {\n            uncalled.emplace_back(p.first);\n        }\n    }\n    return std::make_pair(std::move(calls), std::move(uncalled));\n}\n\n// somatic variant posterior\n\nBigFloat marginalise_somatic(const Allele& allele, const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& genotypes,\n                             const std::vector<double>& probabilities)\n{\n    BigFloat result_complement {std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(probabilities),\n                                                   0.0, std::plus<> {}, [&allele] (const auto& genotype, auto probability) {\n        return is_somatic(allele, genotype) ? 0.0 : probability; })};\n    return BigFloat {1.0} - result_complement;\n}\n\nauto compute_somatic_variant_posteriors(const std::vector<VariantReference>& candidates,\n                                        const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& cancer_genotypes,\n                                        const std::vector<double>& cancer_genotype_posteriors,\n                                        const BigFloat somatic_posterior)\n{\n    VariantPosteriorVector result {};\n    result.reserve(candidates.size());\n    for (const auto& candidate : candidates) {\n        auto p = marginalise_somatic(candidate.get().alt_allele(), cancer_genotypes, cancer_genotype_posteriors);\n        p *= somatic_posterior;\n        result.emplace_back(candidate, probability_true_to_phred<double>(p));\n    }\n    return result;\n}\n\nauto compute_somatic_variant_posteriors(const std::vector<VariantReference>& candidates,\n                                        const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& cancer_genotypes,\n                                        const std::vector<double>& cancer_genotype_posteriors,\n                                        const Phred<double> somatic_posterior)\n{\n    return compute_somatic_variant_posteriors(candidates, cancer_genotypes, cancer_genotype_posteriors,\n                                              BigFloat {somatic_posterior.probability_true().value});\n}\n\nauto call_somatic_variants(const VariantPosteriorVector& somatic_variant_posteriors,\n                           const CancerGenotype<IndexedHaplotype<>>& called_genotype,\n                           const Phred<double> min_posterior)\n{\n    SomaticVariantCalls result {};\n    result.reserve(somatic_variant_posteriors.size());\n    std::copy_if(std::begin(somatic_variant_posteriors), std::end(somatic_variant_posteriors), std::back_inserter(result),\n                 [min_posterior, &called_genotype] (const auto& p) {\n                     return p.second >= min_posterior && includes(called_genotype, p.first.get().alt_allele());\n                 });\n    return result;\n}\n\nPhred<double>\nmarginalise(const CancerGenotype<Allele>& genotype, const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& genotypes,\n            const std::vector<double>& genotype_posteriors)\n{\n    auto p = std::inner_product(std::cbegin(genotypes), std::cend(genotypes), std::cbegin(genotype_posteriors),\n                                0.0, std::plus<> {},  [&genotype] (const auto& g, auto probability) {\n                                    return contains(g, genotype) ? 0.0 : probability; });\n    return probability_false_to_phred(p);\n}\n\nauto call_somatic_genotypes(const CancerGenotype<IndexedHaplotype<>>& called_genotype,\n                            const std::vector<GenomicRegion>& called_somatic_regions,\n                            const MappableBlock<CancerGenotype<IndexedHaplotype<>>>& genotypes,\n                            const std::vector<double>& genotype_posteriors,\n                            const VAFStatsMap& vaf_stats)\n{\n    CancerGenotypeCalls result {};\n    result.reserve(called_somatic_regions.size());\n    for (const auto& region : called_somatic_regions) {\n        auto genotype_chunk = copy<Allele>(called_genotype, region);\n        auto posterior = marginalise(genotype_chunk, genotypes, genotype_posteriors);\n        result.emplace_back(std::move(genotype_chunk), posterior);\n        result.back().vaf_stats = vaf_stats;\n    }\n    return result;\n}\n\n// output\n\noctopus::VariantCall::GenotypeCall demote(GermlineGenotypeCall call)\n{\n    return octopus::VariantCall::GenotypeCall {std::move(call.genotype), call.posterior};\n}\n\nstd::unique_ptr<octopus::VariantCall>\ntransform_germline_cnv_call(GermlineVariantCall&& variant_call, GermlineGenotypeCall&& genotype_call,\n                            const std::vector<SampleName>& samples, const std::vector<SampleName>& somatic_samples)\n{\n    std::vector<std::pair<SampleName, Call::GenotypeCall>> genotypes {};\n    CNVCall::SomaticHaplotypeMap somatic_haplotypes {};\n    somatic_haplotypes.reserve(samples.size());\n    const auto germline_ploidy = genotype_call.genotype.ploidy();\n    const auto somatic_ploidy = genotype_call.somatic.ploidy();\n    for (const auto& sample : samples) {\n        if (std::find(std::cbegin(somatic_samples), std::cend(somatic_samples), sample) == std::cend(somatic_samples)) {\n            genotypes.emplace_back(sample, demote(genotype_call));\n            somatic_haplotypes.emplace(sample, CNVCall::SomaticHaplotypeVector(germline_ploidy));\n        } else {\n            auto copy = genotype_call;\n            for (auto allele : genotype_call.somatic) copy.genotype.emplace(allele);\n            genotypes.emplace_back(sample, demote(std::move(copy)));\n            CNVCall::SomaticHaplotypeVector sample_somatic_haplotypes(germline_ploidy + somatic_ploidy);\n            std::fill_n(std::rbegin(sample_somatic_haplotypes), somatic_ploidy, true);\n            somatic_haplotypes.emplace(sample, std::move(sample_somatic_haplotypes));\n        }\n    }\n    return std::make_unique<CNVCall>(variant_call.variant.get(), std::move(genotypes),\n                                     variant_call.segregation_quality, variant_call.posterior,\n                                     std::move(somatic_haplotypes));\n}\n\nstd::unique_ptr<octopus::VariantCall>\ntransform_germline_call(GermlineVariantCall&& variant_call, GermlineGenotypeCall&& genotype_call,\n                        const std::vector<SampleName>& samples)\n{\n    std::vector<std::pair<SampleName, Call::GenotypeCall>> genotypes {};\n    for (const auto& sample : samples) {\n        genotypes.emplace_back(sample, demote(genotype_call));\n    }\n    return std::make_unique<octopus::GermlineVariantCall>(variant_call.variant.get(), std::move(genotypes),\n                                                          variant_call.segregation_quality, variant_call.posterior);\n}\n\ntemplate <typename Container, typename T>\nauto find_index(const Container& values, const T& value)\n{\n    const auto itr = std::find(std::cbegin(values), std::cend(values), value);\n    return itr != std::cend(values) ? std::distance(std::cbegin(values), itr) : -1;\n}\n\nauto transform_somatic_calls(SomaticVariantCalls&& somatic_calls, CancerGenotypeCalls&& genotype_calls,\n                             const std::vector<SampleName>& somatic_samples)\n{\n    std::vector<std::unique_ptr<octopus::VariantCall>> result {};\n    result.reserve(somatic_calls.size());\n    std::transform(std::make_move_iterator(std::begin(somatic_calls)), std::make_move_iterator(std::end(somatic_calls)),\n                   std::make_move_iterator(std::begin(genotype_calls)), std::back_inserter(result),\n                   [&somatic_samples] (auto&& variant_call, auto&& genotype_call) -> std::unique_ptr<octopus::VariantCall> {\n                       SomaticCall::GenotypeStatsMap genotype_stats {};\n                       genotype_stats.reserve(genotype_call.vaf_stats.size()); // num samples\n                       for (const auto& p : genotype_call.vaf_stats) {\n                           const VAFStatsVector& stats {p.second};\n                           SomaticCall::GenotypeAlleleStats sample_stats {};\n                           sample_stats.germline.reserve(genotype_call.genotype.germline_ploidy());\n                           const auto convert_stats = [] (const VAFStats& stats) -> SomaticCall::AlleleStats {\n                               return {stats.credible_region, stats.map, stats.count};\n                           };\n                           std::transform(std::cbegin(stats), std::next(std::cbegin(stats), genotype_call.genotype.germline_ploidy()),\n                                          std::back_inserter(sample_stats.germline), convert_stats);\n                           if (std::find(std::cbegin(somatic_samples), std::cend(somatic_samples), p.first) != std::cend(somatic_samples)) {\n                               sample_stats.somatic.reserve(genotype_call.genotype.somatic_ploidy());\n                               std::transform(std::next(std::cbegin(stats), genotype_call.genotype.germline_ploidy()), std::cend(stats),\n                                              std::back_inserter(sample_stats.somatic), convert_stats);\n                           }\n                           genotype_stats.emplace(p.first, std::move(sample_stats));\n                       }\n                       return std::make_unique<SomaticCall>(variant_call.variant.get(), std::move(genotype_call.genotype),\n                                                            variant_call.segregation_quality, genotype_call.posterior,\n                                                            std::move(genotype_stats), variant_call.posterior);\n                   });\n    return result;\n}\n\ntemplate <typename Map>\nauto compute_posterior(const Genotype<Allele>& genotype, const Map& genotype_posteriors)\n{\n    auto p = std::accumulate(std::cbegin(genotype_posteriors), std::cend(genotype_posteriors), 0.0,\n                             [&genotype] (const double curr, const auto& p) {\n                                 return curr + (contains(p.first, genotype) ? 0.0 : p.second);\n                             });\n    return probability_false_to_phred(p);\n}\n\n} // namespace\n\nPhred<double>\nCancerCaller::calculate_segregation_probability(const Variant& variant, const Latents& latents, double somatic_mass) const\n{\n    return octopus::calculate_segregation_probability(variant.alt_allele(),\n                                                      latents.germline_genotypes_,\n                                                      latents.cancer_genotypes_[latents.max_evidence_somatic_model_index_],\n                                                      latents.germline_model_inferences_.posteriors.genotype_probabilities,\n                                                      latents.cnv_model_inferences_.max_evidence_params.genotype_probabilities,\n                                                      latents.somatic_model_inferences_[latents.max_evidence_somatic_model_index_].max_evidence_params.genotype_probabilities,\n                                                      latents.model_posteriors_.germline, latents.model_posteriors_.cnv,\n                                                      latents.model_posteriors_.somatic, somatic_mass);\n}\n\nnamespace debug {\n\ntemplate <typename S, typename T>\nvoid print_variants(S&& stream, const std::vector<T>& variants)\n{\n    for (const auto& v : variants) stream << v.variant << \" \" << v.posterior << '\\n';\n}\n\n} // namespace debug\n\nstd::vector<std::unique_ptr<VariantCall>>\nCancerCaller::call_variants(const std::vector<Variant>& candidates, const Latents& latents) const\n{\n    // TODO: refactor this into smaller methods!\n    const auto conditional_somatic_mass = calculate_somatic_mass(latents);\n    const auto& model_posteriors = latents.model_posteriors_;\n    log(model_posteriors);\n    const auto somatic_posterior = calculate_somatic_posterior(latents.model_posteriors_.somatic, conditional_somatic_mass);\n    const auto germline_genotype_posteriors = calculate_germline_genotype_posteriors(latents);\n    const auto& best_somatic_model_inferences = latents.somatic_model_inferences_[latents.max_evidence_somatic_model_index_];\n    const auto& cancer_genotype_posteriors = best_somatic_model_inferences.max_evidence_params.genotype_probabilities;\n    const auto& best_cancer_genotypes_set = latents.cancer_genotypes_[latents.max_evidence_somatic_model_index_];\n    log(latents.germline_genotypes_, germline_genotype_posteriors, latents.germline_model_inferences_, latents.cnv_model_inferences_,\n        best_cancer_genotypes_set, best_somatic_model_inferences);\n    const auto germline_candidate_posteriors = compute_candidate_posteriors(candidates, germline_genotype_posteriors);\n    boost::optional<Genotype<IndexedHaplotype<>>> called_germline_genotype {};\n    boost::optional<CancerGenotype<IndexedHaplotype<>>> called_cancer_genotype {};\n    if (model_posteriors.somatic > model_posteriors.germline && somatic_posterior >= parameters_.min_somatic_posterior) {\n        if (debug_log_) *debug_log_ << \"Using cancer genotype for germline genotype call\";\n        if (!called_cancer_genotype) {\n            auto cancer_posteriors = zip_cref(best_cancer_genotypes_set, cancer_genotype_posteriors);\n            called_cancer_genotype = find_map_genotype(cancer_posteriors)->first;\n        }\n        called_germline_genotype = called_cancer_genotype->germline();\n    } else {\n        called_germline_genotype = find_map_genotype(germline_genotype_posteriors)->first;\n    }\n    GermlineVariantCalls germline_variant_calls;\n    std::vector<VariantReference> uncalled_germline_candidates;\n    std::tie(germline_variant_calls, uncalled_germline_candidates) = call_candidates(germline_candidate_posteriors,\n                                                                                     *called_germline_genotype,\n                                                                                     parameters_.min_variant_posterior);\n    \n    for (auto& v : germline_variant_calls) {\n        v.segregation_quality = calculate_segregation_probability(v.variant, latents, conditional_somatic_mass);\n        if (v.posterior > v.segregation_quality) v.posterior = v.segregation_quality;\n    }\n    \n    std::vector<std::unique_ptr<octopus::VariantCall>> result {};\n    Genotype<IndexedHaplotype<>> called_somatic_genotype {};\n    std::vector<SampleName> somatic_samples {};\n    if (somatic_posterior >= parameters_.min_somatic_posterior) {\n        auto somatic_allele_posteriors = compute_somatic_variant_posteriors(uncalled_germline_candidates, best_cancer_genotypes_set,\n                                                                            cancer_genotype_posteriors, somatic_posterior);\n        if (!called_cancer_genotype) {\n            auto cancer_posteriors = zip_cref(best_cancer_genotypes_set, cancer_genotype_posteriors);\n            called_cancer_genotype = find_map_genotype(cancer_posteriors)->first.get();\n        }\n        if (called_cancer_genotype->germline() == called_germline_genotype) {\n            auto somatic_variant_calls = call_somatic_variants(somatic_allele_posteriors, *called_cancer_genotype,\n                                                               parameters_.min_somatic_posterior);\n            const auto& somatic_alphas = best_somatic_model_inferences.max_evidence_params.alphas;\n            const auto vaf_stats = compute_vaf_stats(somatic_alphas, parameters_.credible_mass);\n            if (!somatic_variant_calls.empty()) {\n                for (const auto& p : vaf_stats) {\n                    const auto& sample = p.first;\n                    const auto& sample_vaf_stats = p.second;\n                    if (debug_log_) {\n                        auto ss = stream(*debug_log_);\n                        ss << sample << \" somatic credible regions: \";\n                        for (auto stats : sample_vaf_stats) ss << '(' << stats.credible_region.first << ' ' << stats.credible_region.second << \") \";\n                    }\n                    if (std::any_of(std::next(std::cbegin(sample_vaf_stats), parameters_.ploidy), std::cend(sample_vaf_stats),\n                        [this] (const auto& stats) { return stats.credible_region.first >= parameters_.min_credible_somatic_frequency; })) {\n                        if (has_normal_sample() && sample == normal_sample()) {\n                            somatic_samples.clear();\n                            break;\n                        }\n                        somatic_samples.push_back(sample);\n                    }\n                }\n                if (latents.noise_model_inferences_ && latents.normal_germline_inferences_) {\n                    const auto noise_model_evidence = latents.noise_model_inferences_->approx_log_evidence;\n                    const auto germline_model_evidence = latents.normal_germline_inferences_->log_evidence;\n                    if (noise_model_evidence > germline_model_evidence) {\n                        // Does the normal sample contain the called somatic variant?\n                        const auto& noisy_alphas = latents.noise_model_inferences_->max_evidence_params.alphas.at(normal_sample());\n                        const auto noise_mass = compute_credible_somatic_mass(noisy_alphas, latents.inferred_somatic_ploidy_, parameters_.min_expected_somatic_frequency);\n                        if (noise_mass > 2 * parameters_.min_credible_somatic_frequency) {\n                            somatic_samples.clear();\n                        }\n                    }\n                }\n                if (somatic_samples.empty()) {\n                    somatic_variant_calls.clear();\n                    somatic_variant_calls.shrink_to_fit();\n                } else {\n                    called_somatic_genotype = called_cancer_genotype->somatic();\n                }\n                for (auto& v : somatic_variant_calls) {\n                    v.segregation_quality = calculate_segregation_probability(v.variant, latents, conditional_somatic_mass);\n                    if (v.posterior > v.segregation_quality) v.posterior = v.segregation_quality;\n                }\n            }\n            if (debug_log_) {\n                *debug_log_ << \"Called somatic variants:\";\n                debug::print_variants(stream(*debug_log_), somatic_variant_calls);\n            }\n            const auto called_somatic_regions = extract_regions(somatic_variant_calls);\n            auto cancer_genotype_calls = call_somatic_genotypes(*called_cancer_genotype, called_somatic_regions,\n                                                                best_cancer_genotypes_set, cancer_genotype_posteriors,\n                                                                vaf_stats);\n            result = transform_somatic_calls(std::move(somatic_variant_calls), std::move(cancer_genotype_calls), somatic_samples);\n        } else if (debug_log_) {\n            stream(*debug_log_) << \"Conflict between called germline genotype and called cancer genotype. Not calling somatics\";\n        }\n    }\n    const auto called_germline_regions = extract_regions(germline_variant_calls);\n    GermlineGenotypeCalls germline_genotype_calls {};\n    germline_genotype_calls.reserve(called_germline_regions.size());\n    for (const auto& region : called_germline_regions) {\n        auto genotype_chunk = copy<Allele>(*called_germline_genotype, region);\n        const auto posterior = compute_posterior(genotype_chunk, germline_genotype_posteriors);\n        if (called_somatic_genotype.ploidy() > 0) {\n            germline_genotype_calls.emplace_back(std::move(genotype_chunk),\n                                                 copy<Allele>(called_somatic_genotype, region),\n                                                 posterior);\n        } else {\n            germline_genotype_calls.emplace_back(std::move(genotype_chunk), posterior);\n        }\n    }\n    if (debug_log_) {\n        *debug_log_ << \"Called germline variants:\";\n        debug::print_variants(stream(*debug_log_), germline_variant_calls);\n    }\n    result.reserve(result.size() + germline_variant_calls.size());\n    const auto itr = std::end(result);\n    std::transform(std::make_move_iterator(std::begin(germline_variant_calls)),\n                   std::make_move_iterator(std::end(germline_variant_calls)),\n                   std::make_move_iterator(std::begin(germline_genotype_calls)),\n                   std::back_inserter(result),\n                   [this, &somatic_samples] (auto&& variant_call, auto&& genotype_call) {\n                       if (somatic_samples.empty()) {\n                           return transform_germline_call(std::move(variant_call), std::move(genotype_call), samples_);\n                       } else {\n                           return transform_germline_cnv_call(std::move(variant_call), std::move(genotype_call),\n                                                              samples_, somatic_samples);\n                       }\n                       \n                   });\n    std::inplace_merge(std::begin(result), itr, std::end(result),\n                       [] (const auto& lhs, const auto& rhs) { return *lhs < *rhs; });\n    return result;\n}\n\nCancerCaller::GermlineGenotypeProbabilityMap\nCancerCaller::calculate_germline_genotype_posteriors(const Latents& latents) const\n{\n    const auto& model_posteriors = latents.model_posteriors_;\n    const auto& germline_genotypes = latents.germline_genotypes_;\n    GermlineGenotypeProbabilityMap result {germline_genotypes.size()};\n    std::transform(std::cbegin(germline_genotypes), std::cend(germline_genotypes),\n                   std::cbegin(latents.germline_model_inferences_.posteriors.genotype_probabilities),\n                   std::inserter(result, std::begin(result)),\n                   [&model_posteriors] (const auto& genotype, const auto& posterior) {\n                       return std::make_pair(genotype, model_posteriors.germline * posterior);\n                   });\n    const auto& cnv_posteriors = latents.cnv_model_inferences_.max_evidence_params.genotype_probabilities;\n    for (std::size_t i {0}; i < latents.germline_genotypes_.size(); ++i) {\n        result[germline_genotypes[i]] += model_posteriors.cnv * cnv_posteriors[i];\n    }\n    const auto& cancer_genotypes = latents.cancer_genotypes_[latents.max_evidence_somatic_model_index_];\n    const auto& somatic_posteriors = latents.somatic_model_inferences_[latents.max_evidence_somatic_model_index_].max_evidence_params.genotype_probabilities;\n    for (std::size_t i {0}; i < cancer_genotypes.size(); ++i) {\n        result[cancer_genotypes[i].germline()] += model_posteriors.somatic * somatic_posteriors[i];\n    }\n    return result;\n}\n\ndouble CancerCaller::calculate_somatic_mass(const CancerCaller::Latents& latents) const\n{\n    return compute_credible_somatic_mass(latents.somatic_model_inferences_[latents.max_evidence_somatic_model_index_].max_evidence_params.alphas,\n                                         latents.inferred_somatic_ploidy_,\n                                         parameters_.min_expected_somatic_frequency);\n}\n\nstd::vector<std::unique_ptr<ReferenceCall>>\nCancerCaller::call_reference(const std::vector<Allele>& alleles, const Caller::Latents& latents, const ReadPileupMap& pileups) const\n{\n    return {};\n}\n\nstd::unique_ptr<GenotypePriorModel> CancerCaller::make_germline_prior_model(const HaplotypeBlock& haplotypes) const\n{\n    if (parameters_.germline_prior_model_params) {\n        return std::make_unique<CoalescentGenotypePriorModel>(CoalescentModel {\n        Haplotype {octopus::mapped_region(haplotypes), reference_},\n        *parameters_.germline_prior_model_params\n        });\n    } else {\n        return std::make_unique<UniformGenotypePriorModel>();\n    }\n}\n\n// CancerCaller::Latents\n\nCancerCaller::Latents::Latents(const HaplotypeBlock& haplotypes,\n                               const std::vector<SampleName>& samples,\n                               const CancerCaller::Parameters& parameters)\n: haplotypes_ {haplotypes}\n, indexed_haplotypes_ {index(haplotypes)}\n, samples_ {samples}\n, parameters_ {parameters}\n{}\n\nstd::shared_ptr<CancerCaller::Latents::HaplotypeProbabilityMap>\nCancerCaller::Latents::haplotype_posteriors() const\n{\n    if (haplotype_posteriors_ == nullptr) {\n        compute_haplotype_posteriors();\n    }\n    return haplotype_posteriors_;\n}\n\nstd::shared_ptr<CancerCaller::Latents::GenotypeProbabilityMap>\nCancerCaller::Latents::genotype_posteriors() const\n{\n    if (genotype_posteriors_ == nullptr) {\n        compute_genotype_posteriors();\n    }\n    return genotype_posteriors_;\n}\n\nvoid CancerCaller::Latents::compute_genotype_posteriors() const\n{\n    if (model_posteriors_.somatic < std::max(model_posteriors_.germline, model_posteriors_.cnv)) {\n        // If no somatic variants likely then only consider the germline component\n        GenotypeProbabilityMap genotype_posteriors {std::begin(germline_genotypes_), std::end(germline_genotypes_)};\n        for (const auto& sample : samples_.get()) {\n            insert_sample(sample, germline_model_inferences_.posteriors.genotype_probabilities, genotype_posteriors);\n        }\n        genotype_posteriors_ = std::make_shared<Latents::GenotypeProbabilityMap>(std::move(genotype_posteriors));\n    } else {\n        // If somatic variant(s) likely then consider all components\n        auto total_num_genotypes = 2 * germline_genotypes_.size();\n        for (const auto& genotypes : cancer_genotypes_) total_num_genotypes += genotypes.size();\n        std::unordered_map<Genotype<IndexedHaplotype<>>, double> posteriors {};\n        posteriors.reserve(total_num_genotypes);\n        for (std::size_t g {0}; g < germline_genotypes_.size(); ++g) {\n            posteriors[germline_genotypes_[g]]\n                 += model_posteriors_.germline * germline_model_inferences_.posteriors.genotype_probabilities[g]\n                  + model_posteriors_.cnv * cnv_model_inferences_.weighted_genotype_posteriors[g];\n        }\n        for (std::size_t somatic_model_idx {0}; somatic_model_idx < somatic_model_inferences_.size(); ++somatic_model_idx) {\n            auto genotypes = demote_each(cancer_genotypes_[somatic_model_idx]);\n            const auto& genotype_posteriors = somatic_model_inferences_[somatic_model_idx].weighted_genotype_posteriors;\n            const auto somatic_model_posterior = model_posteriors_.somatic * somatic_model_posteriors_[somatic_model_idx];\n            for (std::size_t g {0}; g < genotypes.size(); ++g) {\n                posteriors[genotypes[g]] += somatic_model_posterior * genotype_posteriors[g];\n            }\n        }\n        auto unique_genotypes = extract_keys(posteriors);\n        auto unique_posteriors = extract_values(posteriors);\n        GenotypeProbabilityMap genotype_posteriors {std::make_move_iterator(std::begin(unique_genotypes)),\n                                                    std::make_move_iterator(std::end(unique_genotypes))};\n        for (const auto& sample : samples_.get()) {\n            insert_sample(sample, unique_posteriors, genotype_posteriors);\n        }\n        genotype_posteriors_ = std::make_shared<Latents::GenotypeProbabilityMap>(std::move(genotype_posteriors));\n    }\n}\n\nvoid CancerCaller::Latents::compute_haplotype_posteriors() const\n{\n    Latents::HaplotypeProbabilityMap result {indexed_haplotypes_.size()};\n    for (const auto& haplotype : indexed_haplotypes_) {\n        result.emplace(haplotype, 0.0);\n    }\n    // Contribution from germline model\n    for (const auto& p : zip(germline_genotypes_, germline_model_inferences_.posteriors.genotype_probabilities)) {\n        for (const auto& haplotype : collapse(p.get<0>())) {\n            result.at(haplotype) += model_posteriors_.germline * p.get<1>();\n        }\n    }\n    // Contribution from CNV model\n    for (const auto& p : zip(germline_genotypes_, cnv_model_inferences_.max_evidence_params.genotype_probabilities)) {\n        for (const auto& haplotype : collapse(p.get<0>())) {\n            result.at(haplotype) += model_posteriors_.cnv * p.get<1>();\n        }\n    }\n    // Contribution from somatic model\n    for (std::size_t somatic_model_idx {0}; somatic_model_idx < somatic_model_inferences_.size(); ++somatic_model_idx) {\n        const auto& genotypes = cancer_genotypes_[somatic_model_idx];\n        const auto& map_params = somatic_model_inferences_[somatic_model_idx].max_evidence_params;\n        const auto conditional_somatic_prob = compute_credible_somatic_mass(map_params.alphas, somatic_model_idx + 1, parameters_.get().min_expected_somatic_frequency);\n        const auto somatic_model_posterior = model_posteriors_.somatic * somatic_model_posteriors_[somatic_model_idx];\n        const auto& genotype_posteriors = somatic_model_inferences_[somatic_model_idx].weighted_genotype_posteriors;\n        for (const auto& p : zip(genotypes, genotype_posteriors)) {\n            const auto unique_genotype = collapse(p.get<0>());\n            for (const auto& haplotype : unique_genotype.germline()) {\n                result.at(haplotype) += somatic_model_posterior * p.get<1>();\n            }\n            for (const auto& haplotype : unique_genotype.somatic()) {\n                result.at(haplotype) += somatic_model_posterior * conditional_somatic_prob * p.get<1>();\n            }\n        }\n    }\n    haplotype_posteriors_ = std::make_shared<Latents::HaplotypeProbabilityMap>(std::move(result));\n}\n\n// logging\n\nvoid CancerCaller::log(const ModelPosteriors& model_posteriors) const\n{\n    if (debug_log_) {\n        stream(*debug_log_) << \"Germline model posterior: \" << model_posteriors.germline;\n        stream(*debug_log_) << \"CNV model posterior:      \" << model_posteriors.cnv;\n        stream(*debug_log_) << \"Somatic model posterior:  \" << model_posteriors.somatic;\n    }\n}\n\nnamespace debug {\n\ntemplate <typename S, typename GenotypeReference>\nvoid print_genotype_posteriors(S&& stream,\n                               std::vector<std::pair<GenotypeReference, double>> genotype_posteriors,\n                               const std::size_t n = std::numeric_limits<std::size_t>::max())\n{\n    const auto m = std::min(n, genotype_posteriors.size());\n    if (m == genotype_posteriors.size()) {\n        stream << \"Printing all genotype posteriors \" << '\\n';\n    } else {\n        stream << \"Printing top \" << m << \" genotype posteriors \" << '\\n';\n    }\n    const auto mth = std::next(std::begin(genotype_posteriors), m);\n    std::partial_sort(std::begin(genotype_posteriors), mth, std::end(genotype_posteriors),\n                      [] (const auto& lhs, const auto& rhs) { return lhs.second > rhs.second; });\n    std::for_each(std::begin(genotype_posteriors), mth,\n                  [&] (const auto& p) {\n                      print_variant_alleles(stream, p.first.get());\n                      stream << \" \" << p.second << '\\n';\n                  });\n}\n\n} // namespace debug\n\nvoid CancerCaller::log(const GenotypeVector& germline_genotypes,\n                       const GermlineGenotypeProbabilityMap& germline_genotype_posteriors,\n                       const GermlineModel::InferredLatents& germline_inferences,\n                       const CNVModel::InferredLatents& cnv_inferences,\n                       const CancerGenotypeVector& cancer_genotypes,\n                       const SomaticModel::InferredLatents& somatic_inferences) const\n{\n    if (debug_log_) {\n        auto germline_posteriors = zip_cref(germline_genotypes, germline_inferences.posteriors.genotype_probabilities);\n        auto map_germline = find_map_genotype(germline_posteriors);\n        auto germline_log = stream(*debug_log_);\n        germline_log << \"MAP germline genotype: \";\n        debug::print_variant_alleles(germline_log, map_germline->first.get());\n        germline_log << ' ' << map_germline->second;\n        auto cnv_posteriors = zip_cref(germline_genotypes, cnv_inferences.max_evidence_params.genotype_probabilities);\n        auto map_cnv = find_map_genotype(cnv_posteriors);\n        auto cnv_log = stream(*debug_log_);\n        cnv_log << \"MAP CNV genotype: \";\n        debug::print_variant_alleles(cnv_log, map_cnv->first.get());\n        cnv_log << ' ' << map_cnv->second;\n        auto somatic_log = stream(*debug_log_);\n        auto cancer_posteriors = zip_cref(cancer_genotypes, somatic_inferences.max_evidence_params.genotype_probabilities);\n        auto map_somatic = find_map_genotype(cancer_posteriors);\n        auto map_cancer_genotype = map_somatic->first.get();\n        somatic_log << \"MAP cancer genotype: \";\n        auto weighted_cancer_posteriors = zip_cref(cancer_genotypes, somatic_inferences.weighted_genotype_posteriors);\n        auto weighted_somatic_log = stream(*debug_log_);\n        weighted_somatic_log << \"Weighted cancer genotypes... \";\n        debug::print_genotype_posteriors(weighted_somatic_log, weighted_cancer_posteriors, 10);\n        debug::print_variant_alleles(somatic_log, map_cancer_genotype);\n        somatic_log << ' ' << map_somatic->second;\n        auto map_marginal_germline = find_map_genotype(germline_genotype_posteriors);\n        auto marginal_germline_log = stream(*debug_log_);\n        marginal_germline_log << \"MAP marginal germline genotype: \";\n        debug::print_variant_alleles(marginal_germline_log, map_marginal_germline->first);\n        marginal_germline_log << ' ' << map_marginal_germline->second;\n    }\n    if (trace_log_) {\n        auto weighted_cancer_posteriors = zip_cref(cancer_genotypes, somatic_inferences.weighted_genotype_posteriors);\n        auto weighted_somatic_log = stream(*trace_log_);\n        weighted_somatic_log << \"Weighted cancer genotypes... \";\n        debug::print_genotype_posteriors(weighted_somatic_log, weighted_cancer_posteriors);\n    }\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "040d7855c11c2f8d44e119ce175e1a62fe870632", "size": 81447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/callers/cancer_caller.cpp", "max_stars_repo_name": "iamh2o/octopus", "max_stars_repo_head_hexsha": "09ebd28945026556e77d73f1dcd8f0212265183c", "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/callers/cancer_caller.cpp", "max_issues_repo_name": "iamh2o/octopus", "max_issues_repo_head_hexsha": "09ebd28945026556e77d73f1dcd8f0212265183c", "max_issues_repo_licenses": ["MIT"], "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/callers/cancer_caller.cpp", "max_forks_repo_name": "iamh2o/octopus", "max_forks_repo_head_hexsha": "09ebd28945026556e77d73f1dcd8f0212265183c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.0760869565, "max_line_length": 174, "alphanum_fraction": 0.6866305696, "num_tokens": 18996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.15457176360577343}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <list>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n#include <boost/algorithm/clamp.hpp>\n#include <random>\n#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"unsupported/Eigen/CXX11/src/Tensor/TensorDeviceCuda.h\"\n//#include \"unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include \"tensorflow/core/util/work_sharder.h\"\n#include \"bboxes.h\"\n#include \"wtoolkit.h\"\n#include \"open_pose_decode_imp.h\"\n#include <future>\n\nusing namespace tensorflow;\nusing namespace std;\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;\n/*\n * gaussian_delta: \u4e00\u822c\u4e3a2\n * keypoints: [B,N,num_points_nr,2] \u76f8\u5bf9\u5750\u6807,x,y\n * glength: \u6709\u6548\u7684groundtruth instance\u6570\u91cf\n * output_size: \u8f93\u51fa\u56fe\u7684\u5927\u5c0f[2]=(OH,OW) \n *\n * output:\n * output_conf_map: top left heatmaps [B,OH,OW,num_points_nr]\n * output_paf_map: bottom right heatmaps [B,OH,OW,num_points_nr*2]\n */\nREGISTER_OP(\"OpenPoseEncode\")\n    .Attr(\"T: {float,double,int32,int64}\")\n\t.Attr(\"l_delta:float=8.0\")\n\t.Attr(\"gaussian_delta:float=8.0\")\n\t.Attr(\"keypoints_pair:list(int)\")\n    .Input(\"keypoints: T\")\n    .Input(\"output_size: int32\")\n    .Input(\"glength: int32\")\n\t.Output(\"output_conf_map:T\")\n\t.Output(\"output_paf_map:T\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n            const auto input_shape0 = c->input(0);\n            const auto points_nr = c->Value(c->Dim(input_shape0,2));\n            const auto batch_size = c->Dim(input_shape0,0);\n            vector<int> keypoints_pair;\n\t\t\tc->GetAttr(\"keypoints_pair\", &keypoints_pair);\n            auto shape0 = c->MakeShape({batch_size,-1,-1,points_nr});\n            auto shape1 = c->MakeShape({batch_size,-1,-1,keypoints_pair.size()});\n\n\t\t\tc->set_output(0, shape0);\n\t\t\tc->set_output(1, shape1);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device,typename T>\nclass OpenPoseEncodeOp: public OpKernel {\n\tpublic:\n\t\texplicit OpenPoseEncodeOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"l_delta\", &l_delta_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"gaussian_delta\", &gaussian_delta_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"keypoints_pair\", &keypoints_pair_));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n        {\n            TIME_THISV1(\"OpenPoseEncode\");\n            const Tensor &_keypoints = context->input(0);\n            const Tensor &_gsize      = context->input(2);\n            auto          output_size = context->input(1).template flat<int>().data();\n            const auto    batch_size  = _keypoints.dim_size(0);\n            const auto num_keypoints = _keypoints.dim_size(2);\n\n            OP_REQUIRES(context, _keypoints.dims() == 4, errors::InvalidArgument(\"keypoints data must be 4-dimension\"));\n            OP_REQUIRES(context, _gsize.dims() == 1, errors::InvalidArgument(\"gsize data must be 1-dimension\"));\n\n            auto         keypoints       = _keypoints.template tensor<T,4>();\n            auto         gsize           = _gsize.template tensor<int,1>();\n            int          dims_4d0[4]     = {int(batch_size),output_size[0],output_size[1],num_keypoints};\n            int          dims_4d1[4]     = {int(batch_size),output_size[0],output_size[1],keypoints_pair_.size()};\n            TensorShape  outshape0;\n            TensorShape  outshape1;\n            Tensor      *output_conf_map = NULL;\n            Tensor      *output_paf_map  = NULL;\n            const auto   max_data_nr     = _keypoints.dim_size(1);\n\n            TensorShapeUtils::MakeShape(dims_4d0, 4, &outshape0);\n            TensorShapeUtils::MakeShape(dims_4d1, 4, &outshape1);\n\n\n            OP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_conf_map));\n            OP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_paf_map));\n\n            auto heatmaps_conf = output_conf_map->template tensor<T,4>();\n            auto heatmaps_paf = output_paf_map->template tensor<T,4>();\n\n            heatmaps_conf.setZero();\n            heatmaps_paf.setZero();\n\n            for(auto i=0; i<batch_size; ++i) {\n                for(auto j=0; j<gsize(i); ++j) {\n                    for(auto k=0; k<num_keypoints; ++k) {\n                        const auto x0 = keypoints(i,j,k,0)*(output_size[1]-1);\n                        const auto y0 = keypoints(i,j,k,1)*(output_size[0]-1);\n\n\t\t\t\t\t\tif((x0>=0) && (y0>=0))\n                        \tdraw_gaussian(heatmaps_conf,i,x0,y0,k,gaussian_delta_);\n                    }\n                }\n            }\n            if(keypoints_pair_.size()%2 != 0) {\n                cout<<\"ERROR keypoints pair size, \"<<keypoints_pair_.size()<<endl;\n            }\n            const auto kpoints_pair_nr = keypoints_pair_.size()/2;\n            Eigen::Tensor<float,4,Eigen::RowMajor> data_ct(batch_size,output_size[0],output_size[1],num_keypoints);\n            for(auto i=0; i<batch_size; ++i) {\n                const auto nr = min<int>(max_data_nr,gsize(i));\n                for(auto j=0; j<nr; ++j) {\n                    for(auto k=0; k<kpoints_pair_nr; ++k) {\n                        const auto index0 = keypoints_pair_[k*2];\n                        const auto index1 = keypoints_pair_[k*2+1];\n                        const auto x0 = keypoints(i,j,index0,0)*(output_size[1]-1);\n                        const auto y0 = keypoints(i,j,index0,1)*(output_size[0]-1);\n                        const auto x1 = keypoints(i,j,index1,0)*(output_size[1]-1);\n                        const auto y1 = keypoints(i,j,index1,1)*(output_size[0]-1);\n\t\t\t\t\t\tif((index0>num_keypoints) || (index1>num_keypoints)) {\n\t\t\t\t\t\t\tcout<<\"ERROR: OpenPoseEncode: error keypoints pair index \"<<index0<<\" and \"<<index1<<\", Keypoints num is \"<<num_keypoints<<endl;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif((x0>=0) && (y0>=0) && (x1>=0) && (y1>=0))\n                        \tdraw_paf(heatmaps_paf,data_ct,i,x0,y0,x1,y1,k);\n                    }\n                }\n            }\n        }\n\n        template<typename DT>\n        static void draw_gaussian(DT& data,int batch_index,float cx,float cy,int k,float radius)\n        {\n            const auto th           = 4.6052;\n            const auto spread_range = radius *sqrt(2*th);\n            const auto width        = data.dimension(2);\n            const auto height       = data.dimension(1);\n            const auto xtl          = max(0,int(cx-spread_range));\n            const auto ytl          = max(0,int(cy-spread_range));\n            const auto xbr          = min<int>(width,int(cx+spread_range+1));\n            const auto ybr          = min<int>(height,int(cy+spread_range+1));\n            const auto sigma_p      = 2 *radius*radius;\n\n            for(auto x=xtl; x<xbr; ++x) {\n                for(auto y=ytl; y<ybr; ++y) {\n                    auto dx = x-cx;\n                    auto dy = y-cy;\n                    const auto d = (dx*dx+dy*dy);\n                    const auto expv = d/sigma_p;\n                    if (expv>th)\n                        continue;\n                    auto v = exp(-expv);\n                    data(batch_index,y,x,k) = max(data(batch_index,y,x,k),v);\n                }\n            }\n        }\n        template<typename DT,typename CT>\n        void draw_paf(DT& data,CT& ct,int batch_index,float x0,float y0,float x1,float y1,int k)\n        {\n            const auto dis     = distance(x0,y0,x1,y1);\n            const auto l_delta = max<float>(dis *0.125,l_delta_);\n            const auto width   = data.dimension(2);\n            const auto height  = data.dimension(1);\n            const auto xtl     = max<int>(min(x0,x1)-l_delta,0);\n            const auto ytl     = max<int>(min(y0,y1)-l_delta,0);\n            const auto xbr     = min<int>(max<int>(x0,x1)+l_delta+1,width);\n            const auto ybr     = min<int>(max<int>(y0,y1)+l_delta+1,height);\n            const auto vx      = (x1-x0)/dis;\n            const auto vy      = (y1-y0)/dis;\n            const auto A       = y1-y0;\n            const auto B       = x0-x1;\n            const auto C       = y0 *x1-x0 *y1;\n            const auto D       = sqrt(A *A+B *B+1e-8);\n            bool       set_any = false;\n\n            for(auto x=xtl; x<xbr; ++x) {\n                for(auto y=ytl; y<ybr; ++y) {\n                    auto dx = x-x0;\n                    auto dy = y-y0;\n                    auto j0 = dx*vx+dy*vy;\n\n                    if((j0<0) || (j0>dis))\n                        continue;\n\n                    if(fabs((x*A+y*B+C)/D)>l_delta)\n                        continue;\n\n                    set_any = true;\n\n                    ct(batch_index,y,x,k) = ct(batch_index,y,x,k)+1;\n\n                    const auto nr = ct(batch_index,y,x,k);\n\n                    if(nr>1) {\n                        auto old_vx = data(batch_index,y,x,k*2);\n                        auto old_vy = data(batch_index,y,x,k*2+1);\n                        auto new_vx = (old_vx*(nr-1)+vx)/nr;\n                        auto new_vy = (old_vy*(nr-1)+vy)/nr;\n\n                        data(batch_index,y,x,k*2) = new_vx;\n                        data(batch_index,y,x,k*2+1) = new_vy;\n                    } else {\n                        data(batch_index,y,x,k*2) = vx;\n                        data(batch_index,y,x,k*2+1) = vy;\n                    }\n                }\n            }\n            if(!set_any) {\n                auto x = int((x0+x1)/2+0.5);\n                auto y = int((y0+y1)/2+0.5);\n\n                ct(batch_index,y,x,k) = ct(batch_index,y,x,k)+1;\n\n                const auto nr = ct(batch_index,y,x,k);\n\n                if(nr>1) {\n                    auto old_vx = data(batch_index,y,x,k*2);\n                    auto old_vy = data(batch_index,y,x,k*2+1);\n                    auto new_vx = (old_vx*(nr-1)+vx)/nr;\n                    auto new_vy = (old_vy*(nr-1)+vy)/nr;\n\n                    data(batch_index,y,x,k*2) = new_vx;\n                    data(batch_index,y,x,k*2+1) = new_vy;\n                } else {\n                    data(batch_index,y,x,k*2) = vx;\n                    data(batch_index,y,x,k*2+1) = vy;\n                }\n            }\n        }\n        inline float distance(float x0,float y0,float x1,float y1) {\n            const auto dx = x1-x0;\n            const auto dy = y1-y0;\n\n            return sqrt(dx*dx+dy*dy+1e-8);\n        }\n\tprivate:\n       float       l_delta_        = 2;\n       float       gaussian_delta_ = 2;\n       vector<int> keypoints_pair_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"OpenPoseEncode\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), OpenPoseEncodeOp<CPUDevice, float>);\n\n/*\n * keypoints_th: threshold for detection keypoints on conf_maps\n * interp_samples: interp samples in paf map line test\n * paf_score_th: threshold for detection points on paf map\n * conf_th: percent of valid point on paf map line\n * max detection: max persion in one image\n * keypoints_pair: [limb0_begin_id,limb0_end_id,limb1_begin_id,....]\n * conf_maps: typical: [B,H,W,points_nr]\n * paf_maps: typical: [B,H,W,len(keypoints_pair)]\n * return:\n * output_keypoints:[B,max_detection,points_nr,2]\n * output_lengths:[B]\n */\nREGISTER_OP(\"OpenPoseDecode\")\n    .Attr(\"T: {float,double,int32,int64}\")\n    .Attr(\"keypoints_th:float=0.1\")\n    .Attr(\"interp_samples:int=10\")\n    .Attr(\"paf_score_th:float=0.1\")\n    .Attr(\"conf_th:float=0.7\")\n    .Attr(\"max_detection:int=100\")\n\t.Attr(\"keypoints_pair:list(int)\")\n    .Input(\"conf_maps: T\")\n    .Input(\"paf_maps: T\")\n\t.Output(\"output_keypoints:T\")\n\t.Output(\"output_lengths:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n            const auto input_shape0 = c->input(0);\n            const auto batch_size = c->Dim(input_shape0,0);\n            const auto points_nr = c->Dim(input_shape0,3);\n            int max_detection;\n\n            c->GetAttr(\"max_detection\",&max_detection);\n\n            auto shape0 = c->MakeShape({batch_size,max_detection,points_nr,2});\n            auto shape1 = c->MakeShape({batch_size});\n\n\t\t\tc->set_output(0, shape0);\n\t\t\tc->set_output(1, shape1);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device,typename T>\nclass OpenPoseDecodeOp: public OpKernel {\n    public:\n        explicit OpenPoseDecodeOp(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"keypoints_th\", &keypoints_th_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"interp_samples\", &interp_samples_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"paf_score_th\", &paf_score_th_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"conf_th\", &conf_th_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"max_detection\", &max_detection_));\n            vector<int> _keypoints_pair;\n            OP_REQUIRES_OK(context, context->GetAttr(\"keypoints_pair\", &_keypoints_pair));\n\n            if(_keypoints_pair.size()%2 != 0) {\n                cout<<\"ERROR keypoints pair size: \"<<_keypoints_pair.size()<<endl;\n            }\n\n            for(auto i=0; i<_keypoints_pair.size()/2; ++i) {\n                keypoints_pair_.emplace_back(_keypoints_pair[i*2],_keypoints_pair[i*2+1]);\n                map_idx_.emplace_back(i*2,i*2+1);\n            }\n        }\n        void Compute(OpKernelContext* context) override\n        {\n            TIME_THISV1(\"OpenPoseDecode\");\n            const Tensor &_conf_map = context->input(0);\n            const Tensor &_paf_map  = context->input(1);\n\n            OP_REQUIRES(context, _conf_map.dims() == 4, errors::InvalidArgument(\"conf map data must be 4-dimension\"));\n            OP_REQUIRES(context, _paf_map.dims() == 4, errors::InvalidArgument(\"paf map data must be 4-dimension\"));\n\n            auto       conf_map   = _conf_map.template tensor<T,4>();\n            auto       paf_map    = _paf_map.template tensor<T,4>();\n            const auto batch_size = _conf_map.dim_size(0);\n            const auto points_nr  = _conf_map.dim_size(3);\n            const auto H          = conf_map.dimension(1);\n            const auto W          = conf_map.dimension(2);\n\n            int           dims_4d[4]            = {int(batch_size),max_detection_,points_nr,2};\n            int           dims_1d[1]           = {int(batch_size)};\n            TensorShape  outshape0;\n            TensorShape  outshape1;\n            Tensor      *output_keypoints = NULL;\n            Tensor      *output_lens = NULL;\n\n            TensorShapeUtils::MakeShape(dims_4d, 4, &outshape0);\n            TensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n\n            OP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_keypoints));\n            OP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_lens));\n\n            auto o_keypoints = output_keypoints->template tensor<T,4>();\n            auto o_lens = output_lens->template tensor<int,1>();\n\n            o_keypoints.setZero();\n            o_lens.setZero();\n            int size_conf_map[] = {points_nr,H,W};\n            int size_paf_map[] = {paf_map.dimension(3),H,W};\n            Eigen::array<int, 3> shuffling({2, 0,1});\n\n            for(auto i=0; i<batch_size; ++i) {\n                Eigen::Tensor<float,3,Eigen::RowMajor> l_conf_map = conf_map.chip(i,0);\n                Eigen::Tensor<float,3,Eigen::RowMajor> l_paf_map = paf_map.chip(i,0);\n                Eigen::Tensor<float,3,Eigen::RowMajor> l_conf_map_t = l_conf_map.shuffle(shuffling);\n                Eigen::Tensor<float,3,Eigen::RowMajor> l_paf_map_t = l_paf_map.shuffle(shuffling);\n                cv::Mat paf_map_mat = cv::Mat(3,size_paf_map,CV_32FC1,l_paf_map_t.data());\n                cv::Mat conf_map_mat = cv::Mat(3,size_conf_map,CV_32FC1,l_conf_map_t.data());\n                auto persion_wise_keypoints = openpose_decode_imp(conf_map_mat,paf_map_mat,\n                        map_idx_,keypoints_pair_,\n                        keypoints_th_,\n                        interp_samples_,\n                        paf_score_th_,\n                        conf_th_);\n                auto data_nr = min<int>(persion_wise_keypoints.size(),max_detection_);\n                for(auto j=0; j<data_nr; ++j) {\n                    auto& keypoints = persion_wise_keypoints[j];\n                    for(auto k=0; k<keypoints.size(); ++k) {\n                        auto x = keypoints[k].first;\n                        auto y = keypoints[k].second;\n                        if(x>0)\n                            x = x/(W-1);\n                        if(y>0)\n                            y = y/(H-1);\n                        o_keypoints(i,j,k,0) = x;\n                        o_keypoints(i,j,k,1) = y;\n                    }\n                }\n                o_lens(i) = data_nr;\n            }\n        }\n    private:\n        float keypoints_th_   = 0.1;\n        int interp_samples_ = 10;\n        float paf_score_th_   = 0.1;\n        float conf_th_        = 0.7;\n        int   max_detection_  = 100;\n        vector<pair<int,int>> keypoints_pair_;\n        vector<pair<int,int>> map_idx_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"OpenPoseDecode\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), OpenPoseDecodeOp<CPUDevice, float>);\n", "meta": {"hexsha": "24a9a315006c570542f752b18e7fe903d98497c1", "size": 17180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tfop/open_pose.cpp", "max_stars_repo_name": "vghost2008/wml", "max_stars_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-10T17:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T01:00:35.000Z", "max_issues_repo_path": "tfop/open_pose.cpp", "max_issues_repo_name": "vghost2008/wml", "max_issues_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T16:16:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T05:21:19.000Z", "max_forks_repo_path": "tfop/open_pose.cpp", "max_forks_repo_name": "vghost2008/wml", "max_forks_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-07T09:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T04:58:10.000Z", "avg_line_length": 43.1658291457, "max_line_length": 135, "alphanum_fraction": 0.554540163, "num_tokens": 4429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.15455714461206713}}
{"text": "/*\n    Magnum::Math\n        \u2014 a graphics-focused vector math library\n\n    https://doc.magnum.graphics/magnum/namespaceMagnum_1_1Math.html\n    https://doc.magnum.graphics/magnum/namespaceMagnum_1_1EigenIntegration.html\n    https://doc.magnum.graphics/magnum/namespaceMagnum_1_1GlmIntegration.html\n\n    This is a single-header library generated from the Magnum project. With the\n    goal being easy integration, it's deliberately free of all comments to keep\n    the file size small. More info, changelogs and full docs here:\n\n    -   Project homepage \u2014 https://magnum.graphics/magnum/\n    -   Documentation \u2014 https://doc.magnum.graphics/\n    -   GitHub project page \u2014 https://github.com/mosra/magnum\n    -   GitHub Singles repository \u2014 https://github.com/mosra/magnum-singles\n\n    v2019.10-0-g8412e8f99 (2019-10-24)\n    -   New IsScalar, IsVector, IsIntegral, IsFloatingPoint type traits,\n        correct handling of Deg and Rad types in all APIs\n    -   Guaranteed NaN handling semantic in min()/max()/minmax() APIs\n    -   Using a GCC compiler builtin in sincos()\n    -   swizzle() is replaced with gather() and scatter()\n    -   Added Matrix::{cofactor,comatrix,adjugate}(), Matrix4::normalMatrix()\n    -   New Matrix4::perspectiveProjection() overload taking corner positions\n    -   Handling also Eigen::Ref types; EigenIntegration::eigenCast() is now\n        just EigenIntegration::cast()\n    v2019.01-241-g93686746a (2019-04-03)\n    -   Initial release\n\n    Generated from Corrade v2019.10-0-g162d6a7d (2019-10-24),\n        Magnum v2019.10-0-g8412e8f99 (2019-10-24) and\n        Magnum Integration v2019.10 (2019-10-24), 7499 / 9608 LoC\n*/\n\n/*\n    This file is part of Magnum.\n\n    Copyright \u00a9 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,\n                2017, 2018, 2019 Vladim\u00edr Vondru\u0161 <mosra@centrum.cz>\n    Copyright \u00a9 2016 Ashwin Ravichandran <ashwinravichandran24@gmail.com>\n    Copyright \u00a9 2016, 2018 Jonathan Hale <squareys@googlemail.com>\n    Copyright \u00a9 2017 sigman78 <sigman78@gmail.com>\n    Copyright \u00a9 2018 Borislav Stanimirov <b.stanimirov@abv.bg>\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 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\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n*/\n\n#include <ciso646>\n#ifdef _GLIBCXX_USE_STD_SPEC_FUNCS\n#undef _GLIBCXX_USE_STD_SPEC_FUNCS\n#define _GLIBCXX_USE_STD_SPEC_FUNCS 0\n#endif\n#include <cmath>\n#include <cstddef>\n#include <cstdint>\n#include <cstdlib>\n#include <type_traits>\n#include <utility>\n#if (!defined(CORRADE_ASSERT) || !defined(CORRADE_CONSTEXPR_ASSERT) || !defined(CORRADE_INTERNAL_ASSERT_OUTPUT) || !defined(CORRADE_ASSERT_UNREACHABLE)) && !defined(NDEBUG)\n#include <cassert>\n#endif\n\n#if defined(_MSC_VER) && _MSC_VER <= 1920\n#define CORRADE_MSVC2017_COMPATIBILITY\n#endif\n#if defined(_MSC_VER) && _MSC_VER <= 1910\n#define CORRADE_MSVC2015_COMPATIBILITY\n#endif\n#ifdef _WIN32\n#define CORRADE_TARGET_WINDOWS\n#endif\n#ifdef __EMSCRIPTEN__\n#define CORRADE_TARGET_EMSCRIPTEN\n#endif\n#ifdef __ANDROID__\n#define CORRADE_TARGET_ANDROID\n#endif\n\n#ifndef MAGNUM_EXPORT\n#define MAGNUM_EXPORT\n#endif\n\n#ifndef Magnum_Types_h\n#define Magnum_Types_h\n\nnamespace Magnum {\n\ntypedef std::uint8_t UnsignedByte;\ntypedef std::int8_t Byte;\ntypedef std::uint16_t UnsignedShort;\ntypedef std::int16_t Short;\ntypedef std::uint32_t UnsignedInt;\ntypedef std::int32_t Int;\ntypedef std::uint64_t UnsignedLong;\ntypedef std::int64_t Long;\n\ntypedef float Float;\ntypedef double Double;\n\n}\n\n#endif\n#ifndef Magnum_Math_Math_h\n#define Magnum_Math_Math_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<std::size_t> class BoolVector;\n\ntemplate<class> struct Constants;\n\ntemplate<class> class Complex;\ntemplate<class> class Dual;\ntemplate<class> class DualComplex;\ntemplate<class> class DualQuaternion;\n\ntemplate<class> class Frustum;\n\ntemplate<std::size_t, class> class Matrix;\ntemplate<class T> using Matrix2x2 = Matrix<2, T>;\ntemplate<class T> using Matrix3x3 = Matrix<3, T>;\ntemplate<class T> using Matrix4x4 = Matrix<4, T>;\n\ntemplate<class> class Matrix3;\ntemplate<class> class Matrix4;\n\ntemplate<class> class Quaternion;\n\ntemplate<std::size_t, std::size_t, class> class RectangularMatrix;\ntemplate<class T> using Matrix2x3 = RectangularMatrix<2, 3, T>;\ntemplate<class T> using Matrix3x2 = RectangularMatrix<3, 2, T>;\ntemplate<class T> using Matrix2x4 = RectangularMatrix<2, 4, T>;\ntemplate<class T> using Matrix4x2 = RectangularMatrix<4, 2, T>;\ntemplate<class T> using Matrix3x4 = RectangularMatrix<3, 4, T>;\ntemplate<class T> using Matrix4x3 = RectangularMatrix<4, 3, T>;\n\ntemplate<template<class> class, class> class Unit;\ntemplate<class> class Deg;\ntemplate<class> class Rad;\n\nclass Half;\n\ntemplate<std::size_t, class> class Vector;\ntemplate<class> class Vector2;\ntemplate<class> class Vector3;\ntemplate<class> class Vector4;\n\ntemplate<class> struct ColorHsv;\ntemplate<class> class Color3;\ntemplate<class> class Color4;\n\ntemplate<UnsignedInt, UnsignedInt, class> class Bezier;\ntemplate<UnsignedInt dimensions, class T> using QuadraticBezier = Bezier<2, dimensions, T>;\ntemplate<UnsignedInt dimensions, class T> using CubicBezier = Bezier<3, dimensions, T>;\ntemplate<class T> using QuadraticBezier2D = QuadraticBezier<2, T>;\ntemplate<class T> using QuadraticBezier3D = QuadraticBezier<3, T>;\ntemplate<class T> using CubicBezier2D = CubicBezier<2, T>;\ntemplate<class T> using CubicBezier3D = CubicBezier<3, T>;\n\ntemplate<class> class CubicHermite;\ntemplate<class T> using CubicHermite1D = CubicHermite<T>;\ntemplate<class T> using CubicHermite2D = CubicHermite<Vector2<T>>;\ntemplate<class T> using CubicHermite3D = CubicHermite<Vector3<T>>;\ntemplate<class T> using CubicHermiteComplex = CubicHermite<Complex<T>>;\ntemplate<class T> using CubicHermiteQuaternion = CubicHermite<Quaternion<T>>;\n\ntemplate<UnsignedInt, class> class Range;\ntemplate<class T> using Range1D = Range<1, T>;\ntemplate<class> class Range2D;\ntemplate<class> class Range3D;\n\nnamespace Implementation {\n    template<class> struct StrictWeakOrdering;\n}\n\n}}\n\n#endif\n#ifndef MagnumMath_hpp\n#define MagnumMath_hpp\n\nnamespace Magnum {\n\ntypedef Math::Half Half;\ntypedef Math::Vector2<Float> Vector2;\ntypedef Math::Vector3<Float> Vector3;\ntypedef Math::Vector4<Float> Vector4;\ntypedef Math::Vector2<UnsignedInt> Vector2ui;\ntypedef Math::Vector3<UnsignedInt> Vector3ui;\ntypedef Math::Vector4<UnsignedInt> Vector4ui;\ntypedef Math::Vector2<Int> Vector2i;\ntypedef Math::Vector3<Int> Vector3i;\ntypedef Math::Vector4<Int> Vector4i;\ntypedef Math::Color3<Float> Color3;\ntypedef Math::Color4<Float> Color4;\ntypedef Math::Color3<UnsignedByte> Color3ub;\ntypedef Math::Color4<UnsignedByte> Color4ub;\ntypedef Math::Matrix3<Float> Matrix3;\ntypedef Math::Matrix4<Float> Matrix4;\ntypedef Math::Matrix2x2<Float> Matrix2x2;\ntypedef Math::Matrix3x3<Float> Matrix3x3;\ntypedef Math::Matrix4x4<Float> Matrix4x4;\ntypedef Math::Matrix2x3<Float> Matrix2x3;\ntypedef Math::Matrix3x2<Float> Matrix3x2;\ntypedef Math::Matrix2x4<Float> Matrix2x4;\ntypedef Math::Matrix4x2<Float> Matrix4x2;\ntypedef Math::Matrix3x4<Float> Matrix3x4;\ntypedef Math::Matrix4x3<Float> Matrix4x3;\ntypedef Math::QuadraticBezier2D<Float> QuadraticBezier2D;\ntypedef Math::QuadraticBezier3D<Float> QuadraticBezier3D;\ntypedef Math::CubicBezier2D<Float> CubicBezier2D;\ntypedef Math::CubicBezier3D<Float> CubicBezier3D;\ntypedef Math::CubicHermite1D<Float> CubicHermite1D;\ntypedef Math::CubicHermite2D<Float> CubicHermite2D;\ntypedef Math::CubicHermite3D<Float> CubicHermite3D;\ntypedef Math::CubicHermiteComplex<Float> CubicHermiteComplex;\ntypedef Math::CubicHermiteQuaternion<Float> CubicHermiteQuaternion;\ntypedef Math::Complex<Float> Complex;\ntypedef Math::DualComplex<Float> DualComplex;\ntypedef Math::Quaternion<Float> Quaternion;\ntypedef Math::DualQuaternion<Float> DualQuaternion;\ntypedef Math::Constants<Float> Constants;\ntypedef Math::Deg<Float> Deg;\ntypedef Math::Rad<Float> Rad;\ntypedef Math::Range1D<Float> Range1D;\ntypedef Math::Range2D<Float> Range2D;\ntypedef Math::Range3D<Float> Range3D;\ntypedef Math::Range1D<Int> Range1Di;\ntypedef Math::Range2D<Int> Range2Di;\ntypedef Math::Range3D<Int> Range3Di;\ntypedef Math::Frustum<Float> Frustum;\ntypedef Math::Vector2<Double> Vector2d;\ntypedef Math::Vector3<Double> Vector3d;\ntypedef Math::Vector4<Double> Vector4d;\ntypedef Math::Matrix3<Double> Matrix3d;\ntypedef Math::Matrix4<Double> Matrix4d;\ntypedef Math::Matrix2x2<Double> Matrix2x2d;\ntypedef Math::Matrix3x3<Double> Matrix3x3d;\ntypedef Math::Matrix4x4<Double> Matrix4x4d;\ntypedef Math::Matrix2x3<Double> Matrix2x3d;\ntypedef Math::Matrix3x2<Double> Matrix3x2d;\ntypedef Math::Matrix2x4<Double> Matrix2x4d;\ntypedef Math::Matrix4x2<Double> Matrix4x2d;\ntypedef Math::Matrix3x4<Double> Matrix3x4d;\ntypedef Math::Matrix4x3<Double> Matrix4x3d;\ntypedef Math::QuadraticBezier2D<Float> QuadraticBezier2Dd;\ntypedef Math::QuadraticBezier3D<Float> QuadraticBezier3Dd;\ntypedef Math::CubicBezier2D<Float> CubicBezier2Dd;\ntypedef Math::CubicBezier3D<Float> CubicBezier3Dd;\ntypedef Math::CubicHermite1D<Double> CubicHermite1Dd;\ntypedef Math::CubicHermite2D<Double> CubicHermite2Dd;\ntypedef Math::CubicHermite3D<Double> CubicHermite3Dd;\ntypedef Math::CubicHermiteComplex<Double> CubicHermiteComplexd;\ntypedef Math::CubicHermiteQuaternion<Double> CubicHermiteQuaterniond;\ntypedef Math::Complex<Double> Complexd;\ntypedef Math::DualComplex<Double> DualComplexd;\ntypedef Math::Quaternion<Double> Quaterniond;\ntypedef Math::DualQuaternion<Double> DualQuaterniond;\ntypedef Math::Constants<Double> Constantsd;\ntypedef Math::Deg<Double> Degd;\ntypedef Math::Rad<Double> Radd;\ntypedef Math::Range1D<Double> Range1Dd;\ntypedef Math::Range2D<Double> Range2Dd;\ntypedef Math::Range3D<Double> Range3Dd;\ntypedef Math::Frustum<Double> Frustumd;\n\n}\n\n#endif\n#ifndef Magnum_Math_Constants_h\n#define Magnum_Math_Constants_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<class> struct Constants;\n\n#ifndef CORRADE_TARGET_EMSCRIPTEN\ntemplate<> struct Constants<long double> {\n    static constexpr long double pi()   { return 3.14159265358979323846l; }\n};\n#endif\n\ntemplate<> struct Constants<Double> {\n    Constants() = delete;\n\n    static constexpr Double pi()        { return 3.1415926535897932; }\n    static constexpr Double piHalf()    { return 1.5707963267948966; }\n    static constexpr Double piQuarter() { return 0.7853981633974483; }\n    static constexpr Double tau()       { return 6.2831853071795864; }\n    static constexpr Double e()         { return 2.7182818284590452; }\n    static constexpr Double sqrt2()     { return 1.4142135623730950; }\n    static constexpr Double sqrt3()     { return 1.7320508075688773; }\n    static constexpr Double sqrtHalf()  { return 0.7071067811865475; }\n\n    static constexpr Double nan()   { return Double(NAN); }\n    static constexpr Double inf()   { return HUGE_VAL; }\n};\ntemplate<> struct Constants<Float> {\n    Constants() = delete;\n\n    static constexpr Float pi()         { return 3.141592654f; }\n    static constexpr Float piHalf()     { return 1.570796327f; }\n    static constexpr Float piQuarter()  { return 0.785398163f; }\n    static constexpr Float tau()        { return 6.283185307f; }\n    static constexpr Float e()          { return 2.718281828f; }\n    static constexpr Float sqrt2()      { return 1.414213562f; }\n    static constexpr Float sqrt3()      { return 1.732050808f; }\n    static constexpr Float sqrtHalf()   { return 0.707106781f; }\n\n    static constexpr Float nan()    { return NAN; }\n    static constexpr Float inf()    { return HUGE_VALF; }\n};\n\n}}\n\n#endif\n#ifndef Magnum_Math_TypeTraits_h\n#define Magnum_Math_TypeTraits_h\n\n#ifndef FLOAT_EQUALITY_PRECISION\n#define FLOAT_EQUALITY_PRECISION 1.0e-5f\n#endif\n\n#ifndef DOUBLE_EQUALITY_PRECISION\n#define DOUBLE_EQUALITY_PRECISION 1.0e-14\n#endif\n\n#ifndef CORRADE_TARGET_EMSCRIPTEN\n#ifndef LONG_DOUBLE_EQUALITY_PRECISION\n#if !defined(_MSC_VER) && (!defined(CORRADE_TARGET_ANDROID) || __LP64__)\n#define LONG_DOUBLE_EQUALITY_PRECISION 1.0e-17l\n#else\n#define LONG_DOUBLE_EQUALITY_PRECISION 1.0e-14\n#endif\n#endif\n#endif\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> struct IsScalar\n    : std::false_type\n    {};\n\ntemplate<> struct IsScalar<char>: std::true_type {};\ntemplate<> struct IsScalar<signed char>: std::true_type {};\ntemplate<> struct IsScalar<unsigned char>: std::true_type {};\ntemplate<> struct IsScalar<short>: std::true_type {};\ntemplate<> struct IsScalar<unsigned short>: std::true_type {};\ntemplate<> struct IsScalar<int>: std::true_type {};\ntemplate<> struct IsScalar<unsigned int>: std::true_type {};\ntemplate<> struct IsScalar<long>: std::true_type {};\ntemplate<> struct IsScalar<unsigned long>: std::true_type {};\ntemplate<> struct IsScalar<long long>: std::true_type {};\ntemplate<> struct IsScalar<unsigned long long>: std::true_type {};\ntemplate<> struct IsScalar<float>: std::true_type {};\ntemplate<> struct IsScalar<double>: std::true_type {};\n#ifndef CORRADE_TARGET_EMSCRIPTEN\ntemplate<> struct IsScalar<long double>: std::true_type {};\n#endif\ntemplate<template<class> class Derived, class T> struct IsScalar<Unit<Derived, T>>: std::true_type {};\ntemplate<class T> struct IsScalar<Deg<T>>: std::true_type {};\ntemplate<class T> struct IsScalar<Rad<T>>: std::true_type {};\n\ntemplate<class T> struct IsVector\n    : std::false_type\n    {};\n\ntemplate<std::size_t size, class T> struct IsVector<Vector<size, T>>: std::true_type {};\ntemplate<class T> struct IsVector<Vector2<T>>: std::true_type {};\ntemplate<class T> struct IsVector<Vector3<T>>: std::true_type {};\ntemplate<class T> struct IsVector<Vector4<T>>: std::true_type {};\ntemplate<class T> struct IsVector<Color3<T>>: std::true_type {};\ntemplate<class T> struct IsVector<Color4<T>>: std::true_type {};\n\ntemplate<class T> struct IsIntegral\n    : std::false_type\n    {};\n\ntemplate<> struct IsIntegral<char>: std::true_type {};\ntemplate<> struct IsIntegral<signed char>: std::true_type {};\ntemplate<> struct IsIntegral<unsigned char>: std::true_type {};\ntemplate<> struct IsIntegral<short>: std::true_type {};\ntemplate<> struct IsIntegral<unsigned short>: std::true_type {};\ntemplate<> struct IsIntegral<int>: std::true_type {};\ntemplate<> struct IsIntegral<unsigned int>: std::true_type {};\ntemplate<> struct IsIntegral<long>: std::true_type {};\ntemplate<> struct IsIntegral<unsigned long>: std::true_type {};\ntemplate<> struct IsIntegral<long long>: std::true_type {};\ntemplate<> struct IsIntegral<unsigned long long>: std::true_type {};\ntemplate<std::size_t size, class T> struct IsIntegral<Vector<size, T>>: IsIntegral<T> {};\ntemplate<class T> struct IsIntegral<Vector2<T>>: IsIntegral<T> {};\ntemplate<class T> struct IsIntegral<Vector3<T>>: IsIntegral<T> {};\ntemplate<class T> struct IsIntegral<Vector4<T>>: IsIntegral<T> {};\ntemplate<class T> struct IsIntegral<Color3<T>>: IsIntegral<T> {};\ntemplate<class T> struct IsIntegral<Color4<T>>: IsIntegral<T> {};\n\ntemplate<class T> struct IsFloatingPoint\n    : std::false_type\n    {};\n\ntemplate<> struct IsFloatingPoint<Float>: std::true_type {};\ntemplate<> struct IsFloatingPoint<Double>: std::true_type {};\n#ifndef CORRADE_TARGET_EMSCRIPTEN\ntemplate<> struct IsFloatingPoint<long double>: std::true_type {};\n#endif\ntemplate<std::size_t size, class T> struct IsFloatingPoint<Vector<size, T>>: IsFloatingPoint<T> {};\ntemplate<class T> struct IsFloatingPoint<Vector2<T>>: IsFloatingPoint<T> {};\ntemplate<class T> struct IsFloatingPoint<Vector3<T>>: IsFloatingPoint<T> {};\ntemplate<class T> struct IsFloatingPoint<Vector4<T>>: IsFloatingPoint<T> {};\ntemplate<class T> struct IsFloatingPoint<Color3<T>>: IsFloatingPoint<T> {};\ntemplate<class T> struct IsFloatingPoint<Color4<T>>: IsFloatingPoint<T> {};\ntemplate<template<class> class Derived, class T> struct IsFloatingPoint<Unit<Derived, T>>: IsFloatingPoint<T> {};\ntemplate<class T> struct IsFloatingPoint<Deg<T>>: IsFloatingPoint<T> {};\ntemplate<class T> struct IsFloatingPoint<Rad<T>>: IsFloatingPoint<T> {};\n\ntemplate<class T> struct IsUnitless\n    : std::integral_constant<bool, IsScalar<T>::value || IsVector<T>::value>\n    {};\ntemplate<template<class> class Derived, class T> struct IsUnitless<Unit<Derived, T>>: std::false_type {};\ntemplate<class T> struct IsUnitless<Deg<T>>: std::false_type {};\ntemplate<class T> struct IsUnitless<Rad<T>>: std::false_type {};\n\nnamespace Implementation {\n    template<class T> struct UnderlyingType {\n        static_assert(IsScalar<T>::value, \"type is not scalar\");\n        typedef T Type;\n    };\n    template<template<class> class Derived, class T> struct UnderlyingType<Unit<Derived, T>> {\n        typedef T Type;\n    };\n    template<class T> struct UnderlyingType<Deg<T>> { typedef T Type; };\n    template<class T> struct UnderlyingType<Rad<T>> { typedef T Type; };\n    template<std::size_t size, class T> struct UnderlyingType<Vector<size, T>> {\n        typedef T Type;\n    };\n    template<class T> struct UnderlyingType<Vector2<T>> { typedef T Type; };\n    template<class T> struct UnderlyingType<Vector3<T>> { typedef T Type; };\n    template<class T> struct UnderlyingType<Vector4<T>> { typedef T Type; };\n    template<class T> struct UnderlyingType<Color3<T>> { typedef T Type; };\n    template<class T> struct UnderlyingType<Color4<T>> { typedef T Type; };\n    template<std::size_t cols, std::size_t rows, class T> struct UnderlyingType<RectangularMatrix<cols, rows, T>> {\n        typedef T Type;\n    };\n    template<std::size_t size, class T> struct UnderlyingType<Matrix<size, T>> {\n        typedef T Type;\n    };\n    template<class T> struct UnderlyingType<Matrix3<T>> { typedef T Type; };\n    template<class T> struct UnderlyingType<Matrix4<T>> { typedef T Type; };\n}\n\ntemplate<class T> using UnderlyingTypeOf = typename Implementation::UnderlyingType<T>::Type;\n\nnamespace Implementation {\n    template<class T> struct TypeTraitsDefault {\n        TypeTraitsDefault() = delete;\n\n        constexpr static bool equals(T a, T b) {\n            return a == b;\n        }\n\n        constexpr static bool equalsZero(T a, T) {\n            return !a;\n        }\n    };\n}\n\ntemplate<class T> struct TypeTraits: Implementation::TypeTraitsDefault<T> {\n\n};\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, bool>::type equal(T a, T b) {\n    return TypeTraits<T>::equals(a, b);\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, bool>::type notEqual(T a, T b) {\n    return !TypeTraits<T>::equals(a, b);\n}\n\nnamespace Implementation {\n    template<class> struct TypeTraitsName;\n    #define _c(type) template<> struct TypeTraitsName<type> { \\\n        constexpr static const char* name() { return #type; } \\\n    };\n    _c(UnsignedByte)\n    _c(Byte)\n    _c(UnsignedShort)\n    _c(Short)\n    _c(UnsignedInt)\n    _c(Int)\n    #ifndef CORRADE_TARGET_EMSCRIPTEN\n    _c(UnsignedLong)\n    _c(Long)\n    #endif\n    _c(Float)\n    _c(Double)\n    #ifndef CORRADE_TARGET_EMSCRIPTEN\n    _c(long double)\n    #endif\n    #undef _c\n\n    template<class T> struct TypeTraitsIntegral: TypeTraitsDefault<T>, TypeTraitsName<T> {\n        constexpr static T epsilon() { return T(1); }\n    };\n}\n\ntemplate<> struct TypeTraits<UnsignedByte>: Implementation::TypeTraitsIntegral<UnsignedByte> {\n    typedef Float FloatingPointType;\n};\ntemplate<> struct TypeTraits<Byte>: Implementation::TypeTraitsIntegral<Byte> {\n    typedef Float FloatingPointType;\n};\ntemplate<> struct TypeTraits<UnsignedShort>: Implementation::TypeTraitsIntegral<UnsignedShort> {\n    typedef Float FloatingPointType;\n};\ntemplate<> struct TypeTraits<Short>: Implementation::TypeTraitsIntegral<Short> {\n    typedef Float FloatingPointType;\n};\ntemplate<> struct TypeTraits<UnsignedInt>: Implementation::TypeTraitsIntegral<UnsignedInt> {\n    typedef Double FloatingPointType;\n};\ntemplate<> struct TypeTraits<Int>: Implementation::TypeTraitsIntegral<Int> {\n    typedef Double FloatingPointType;\n};\n#ifndef CORRADE_TARGET_EMSCRIPTEN\ntemplate<> struct TypeTraits<UnsignedLong>: Implementation::TypeTraitsIntegral<UnsignedLong> {\n    typedef long double FloatingPointType;\n};\ntemplate<> struct TypeTraits<Long>: Implementation::TypeTraitsIntegral<Long> {\n    typedef long double FloatingPointType;\n};\n#endif\n\nnamespace Implementation {\n\ntemplate<class T> struct TypeTraitsFloatingPoint: TypeTraitsName<T> {\n    TypeTraitsFloatingPoint() = delete;\n\n    static bool equals(T a, T b);\n    static bool equalsZero(T a, T epsilon);\n};\n\ntemplate<class T> bool TypeTraitsFloatingPoint<T>::equals(const T a, const T b) {\n    if(a == b) return true;\n\n    const T absA = std::abs(a);\n    const T absB = std::abs(b);\n    const T difference = std::abs(a - b);\n\n    if(a == T{} || b == T{} || difference < TypeTraits<T>::epsilon())\n        return difference < TypeTraits<T>::epsilon();\n\n    return difference/(absA + absB) < TypeTraits<T>::epsilon();\n}\n\ntemplate<class T> bool TypeTraitsFloatingPoint<T>::equalsZero(const T a, const T magnitude) {\n    if(a == T(0.0)) return true;\n\n    const T absA = std::abs(a);\n\n    if(absA < TypeTraits<T>::epsilon())\n        return absA < TypeTraits<T>::epsilon();\n\n    return absA*T(0.5)/magnitude < TypeTraits<T>::epsilon();\n}\n\n}\n\ntemplate<> struct TypeTraits<Float>: Implementation::TypeTraitsFloatingPoint<Float> {\n    typedef Float FloatingPointType;\n\n    constexpr static Float epsilon() { return FLOAT_EQUALITY_PRECISION; }\n};\ntemplate<> struct TypeTraits<Double>: Implementation::TypeTraitsFloatingPoint<Double> {\n    typedef Double FloatingPointType;\n\n    constexpr static Double epsilon() { return DOUBLE_EQUALITY_PRECISION; }\n};\n#ifndef CORRADE_TARGET_EMSCRIPTEN\ntemplate<> struct TypeTraits<long double>: Implementation::TypeTraitsFloatingPoint<long double> {\n    typedef long double FloatingPointType;\n\n    constexpr static long double epsilon() { return LONG_DOUBLE_EQUALITY_PRECISION; }\n};\n#endif\n\nnamespace Implementation {\n\ntemplate<class T> inline bool isNormalizedSquared(T lengthSquared) {\n    return std::abs(lengthSquared - T(1)) < T(2)*TypeTraits<T>::epsilon();\n}\n\n}\n\n}}\n\n#endif\n#ifndef Corrade_Containers_Tags_h\n#define Corrade_Containers_Tags_h\n\nnamespace Corrade { namespace Containers {\n\nstruct DefaultInitT {\n    struct Init{};\n    constexpr explicit DefaultInitT(Init) {}\n};\n\nstruct ValueInitT {\n    struct Init{};\n    constexpr explicit ValueInitT(Init) {}\n};\n\nstruct NoInitT {\n    struct Init{};\n    constexpr explicit NoInitT(Init) {}\n};\n\nstruct NoCreateT {\n    struct Init{};\n    constexpr explicit NoCreateT(Init) {}\n};\n\nstruct DirectInitT {\n    struct Init{};\n    constexpr explicit DirectInitT(Init) {}\n};\n\nstruct InPlaceInitT {\n    struct Init{};\n    constexpr explicit InPlaceInitT(Init) {}\n};\n\nconstexpr DefaultInitT DefaultInit{DefaultInitT::Init{}};\n\nconstexpr ValueInitT ValueInit{ValueInitT::Init{}};\n\nconstexpr NoInitT NoInit{NoInitT::Init{}};\n\nconstexpr NoCreateT NoCreate{NoCreateT::Init{}};\n\nconstexpr DirectInitT DirectInit{DirectInitT::Init{}};\n\nconstexpr InPlaceInitT InPlaceInit{InPlaceInitT::Init{}};\n\n}}\n\n#endif\n#ifndef Magnum_Math_Tags_h\n#define Magnum_Math_Tags_h\n\nnamespace Magnum { namespace Math {\n\ntypedef Corrade::Containers::NoInitT NoInitT;\n\nstruct ZeroInitT {\n    struct Init{};\n    constexpr explicit ZeroInitT(Init) {}\n};\n\nstruct IdentityInitT {\n    struct Init{};\n    constexpr explicit IdentityInitT(Init) {}\n};\n\nusing Corrade::Containers::NoInit;\n\nconstexpr ZeroInitT ZeroInit{ZeroInitT::Init{}};\n\nconstexpr IdentityInitT IdentityInit{IdentityInitT::Init{}};\n\n}}\n\n#endif\n#ifndef Magnum_Math_Unit_h\n#define Magnum_Math_Unit_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<template<class> class Derived, class T> class Unit {\n    template<template<class> class, class> friend class Unit;\n\n    public:\n        typedef T Type;\n\n        constexpr /*implicit*/ Unit() noexcept: _value(T(0)) {}\n\n        constexpr explicit Unit(ZeroInitT) noexcept: _value(T(0)) {}\n\n        explicit Unit(NoInitT) noexcept {}\n\n        constexpr explicit Unit(T value) noexcept: _value(value) {}\n\n        template<class U> constexpr explicit Unit(Unit<Derived, U> value) noexcept: _value(T(value._value)) {}\n\n        constexpr /*implicit*/ Unit(const Unit<Derived, T>& other) noexcept = default;\n\n        constexpr explicit operator T() const { return _value; }\n\n        constexpr bool operator==(Unit<Derived, T> other) const {\n            return TypeTraits<T>::equals(_value, other._value);\n        }\n\n        constexpr bool operator!=(Unit<Derived, T> other) const {\n            return !operator==(other);\n        }\n\n        constexpr bool operator<(Unit<Derived, T> other) const {\n            return _value < other._value;\n        }\n\n        constexpr bool operator>(Unit<Derived, T> other) const {\n            return _value > other._value;\n        }\n\n        constexpr bool operator<=(Unit<Derived, T> other) const {\n            return !operator>(other);\n        }\n\n        constexpr bool operator>=(Unit<Derived, T> other) const {\n            return !operator<(other);\n        }\n\n        constexpr Unit<Derived, T> operator-() const {\n            return Unit<Derived, T>(-_value);\n        }\n\n        Unit<Derived, T>& operator+=(Unit<Derived, T> other) {\n            _value += other._value;\n            return *this;\n        }\n\n        constexpr Unit<Derived, T> operator+(Unit<Derived, T> other) const {\n            return Unit<Derived, T>(_value + other._value);\n        }\n\n        Unit<Derived, T>& operator-=(Unit<Derived, T> other) {\n            _value -= other._value;\n            return *this;\n        }\n\n        constexpr Unit<Derived, T> operator-(Unit<Derived, T> other) const {\n            return Unit<Derived, T>(_value - other._value);\n        }\n\n        Unit<Derived, T>& operator*=(T number) {\n            _value *= number;\n            return *this;\n        }\n\n        constexpr Unit<Derived, T> operator*(T number) const {\n            return Unit<Derived, T>(_value*number);\n        }\n\n        Unit<Derived, T>& operator/=(T number) {\n            _value /= number;\n            return *this;\n        }\n\n        constexpr Unit<Derived, T> operator/(T number) const {\n            return Unit<Derived, T>(_value/number);\n        }\n\n        constexpr T operator/(Unit<Derived, T> other) const {\n            return _value/other._value;\n        }\n\n    private:\n        T _value;\n};\n\ntemplate<template<class> class Derived, class T> constexpr Unit<Derived, T> operator*(typename std::common_type<T>::type number, const Unit<Derived, T>& value) {\n    return value*number;\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Angle_h\n#define Magnum_Math_Angle_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> class Deg: public Unit<Deg, T> {\n    public:\n        constexpr /*implicit*/ Deg() noexcept: Unit<Math::Deg, T>{ZeroInit} {}\n\n        constexpr explicit Deg(ZeroInitT) noexcept: Unit<Math::Deg, T>{ZeroInit} {}\n\n        explicit Deg(NoInitT) noexcept: Unit<Math::Deg, T>{NoInit} {}\n\n        constexpr explicit Deg(T value) noexcept: Unit<Math::Deg, T>(value) {}\n\n        template<class U> constexpr explicit Deg(Unit<Math::Deg, U> value) noexcept: Unit<Math::Deg, T>(value) {}\n\n        constexpr /*implicit*/ Deg(Unit<Math::Deg, T> other) noexcept: Unit<Math::Deg, T>(other) {}\n\n        constexpr /*implicit*/ Deg(Unit<Rad, T> value);\n};\n\nnamespace Literals {\n\nconstexpr Deg<Double> operator \"\" _deg(long double value) { return Deg<Double>(Double(value)); }\n\nconstexpr Deg<Float> operator \"\" _degf(long double value) { return Deg<Float>(Float(value)); }\n\n}\n\ntemplate<class T> class Rad: public Unit<Rad, T> {\n    public:\n        constexpr /*implicit*/ Rad() noexcept: Unit<Math::Rad, T>{ZeroInit} {}\n\n        constexpr explicit Rad(ZeroInitT) noexcept: Unit<Math::Rad, T>{ZeroInit} {}\n\n        explicit Rad(NoInitT) noexcept: Unit<Math::Rad, T>{NoInit} {}\n\n        constexpr explicit Rad(T value) noexcept: Unit<Math::Rad, T>(value) {}\n\n        template<class U> constexpr explicit Rad(Unit<Math::Rad, U> value) noexcept: Unit<Math::Rad, T>(value) {}\n\n        constexpr /*implicit*/ Rad(Unit<Math::Rad, T> value) noexcept: Unit<Math::Rad, T>(value) {}\n\n        constexpr /*implicit*/ Rad(Unit<Deg, T> value);\n};\n\nnamespace Literals {\n\nconstexpr Rad<Double> operator \"\" _rad(long double value) { return Rad<Double>(Double(value)); }\n\nconstexpr Rad<Float> operator \"\" _radf(long double value) { return Rad<Float>(Float(value)); }\n\n}\n\ntemplate<class T> constexpr Deg<T>::Deg(Unit<Rad, T> value): Unit<Math::Deg, T>(T(180)*T(value)/Math::Constants<T>::pi()) {}\ntemplate<class T> constexpr Rad<T>::Rad(Unit<Deg, T> value): Unit<Math::Rad, T>(T(value)*Math::Constants<T>::pi()/T(180)) {}\n\n}}\n\nnamespace Corrade { namespace Utility {\n\n}}\n\n#endif\n#ifndef CORRADE_ASSERT\n#ifdef NDEBUG\n#define CORRADE_ASSERT(condition, message, returnValue) do {} while(0)\n#else\n#define CORRADE_ASSERT(condition, message, returnValue) assert(condition)\n#endif\n#endif\n\n#ifndef CORRADE_CONSTEXPR_ASSERT\n#ifdef NDEBUG\n#define CORRADE_CONSTEXPR_ASSERT(condition, message) static_cast<void>(0)\n#else\n#define CORRADE_CONSTEXPR_ASSERT(condition, message)                        \\\n    static_cast<void>((condition) ? 0 : ([&]() {                            \\\n        assert(!#condition);                                                \\\n    }(), 0))\n#endif\n#endif\n\n#ifndef CORRADE_INTERNAL_ASSERT_OUTPUT\n#ifdef NDEBUG\n#define CORRADE_INTERNAL_ASSERT_OUTPUT(call)                                \\\n    static_cast<void>(call)\n#else\n#define CORRADE_INTERNAL_ASSERT_OUTPUT(call) assert(call)\n#endif\n#endif\n\n#ifndef CORRADE_ASSERT_UNREACHABLE\n#ifdef NDEBUG\n#ifdef __GNUC__\n#define CORRADE_ASSERT_UNREACHABLE() __builtin_unreachable()\n#elif defined(_MSC_VER)\n#define CORRADE_ASSERT_UNREACHABLE() __assume(0)\n#else\n#define CORRADE_ASSERT_UNREACHABLE() std::abort()\n#endif\n#else\n#define CORRADE_ASSERT_UNREACHABLE() assert(!\"unreachable code\")\n#endif\n#endif\n#ifndef Magnum_Math_BoolVector_h\n#define Magnum_Math_BoolVector_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<std::size_t, class> struct BoolVectorConverter;\n\n    template<std::size_t ...> struct Sequence {};\n\n    template<std::size_t N, std::size_t ...sequence> struct GenerateSequence:\n        GenerateSequence<N-1, N-1, sequence...> {};\n\n    template<std::size_t ...sequence> struct GenerateSequence<0, sequence...> {\n        typedef Sequence<sequence...> Type;\n    };\n\n    template<class T> constexpr T repeat(T value, std::size_t) { return value; }\n}\n\ntemplate<std::size_t size> class BoolVector {\n    static_assert(size != 0, \"BoolVector cannot have zero elements\");\n\n    public:\n        enum: std::size_t {\n            Size = size,\n            DataSize = (size-1)/8+1\n        };\n\n        constexpr /*implicit*/ BoolVector() noexcept: _data{} {}\n\n        constexpr explicit BoolVector(ZeroInitT) noexcept: _data{} {}\n\n        explicit BoolVector(NoInitT) noexcept {}\n\n        template<class ...T, class U = typename std::enable_if<sizeof...(T)+1 == DataSize, bool>::type> constexpr /*implicit*/ BoolVector(UnsignedByte first, T... next) noexcept: _data{first, UnsignedByte(next)...} {}\n\n        template<class T, class U = typename std::enable_if<std::is_same<bool, T>::value && size != 1, bool>::type> constexpr explicit BoolVector(T value) noexcept: BoolVector(typename Implementation::GenerateSequence<DataSize>::Type(), value ? FullSegmentMask : 0) {}\n\n        template<class U, class V = decltype(Implementation::BoolVectorConverter<size, U>::from(std::declval<U>()))> constexpr explicit BoolVector(const U& other) noexcept: BoolVector{Implementation::BoolVectorConverter<size, U>::from(other)} {}\n\n        constexpr /*implicit*/ BoolVector(const BoolVector<size>&) noexcept = default;\n\n        template<class U, class V = decltype(Implementation::BoolVectorConverter<size, U>::to(std::declval<BoolVector<size>>()))> constexpr explicit operator U() const {\n            return Implementation::BoolVectorConverter<size, U>::to(*this);\n        }\n\n        UnsignedByte* data() { return _data; }\n        constexpr const UnsignedByte* data() const { return _data; }\n\n        constexpr bool operator[](std::size_t i) const {\n            return (_data[i/8] >> i%8) & 0x01;\n        }\n\n        BoolVector<size>& set(std::size_t i, bool value) {\n            value ? _data[i/8] |=  (1 << i%8) :\n                    _data[i/8] &= ~(1 << i%8);\n            return *this;\n        }\n\n        bool operator==(const BoolVector<size>& other) const;\n\n        bool operator!=(const BoolVector<size>& other) const {\n            return !operator==(other);\n        }\n\n        explicit operator bool() const { return all(); }\n\n        bool all() const;\n\n        bool none() const;\n\n        bool any() const { return !none(); }\n\n        BoolVector<size> operator~() const;\n\n        BoolVector<size> operator!() const { return operator~(); }\n\n        BoolVector<size>& operator&=(const BoolVector<size>& other) {\n            for(std::size_t i = 0; i != DataSize; ++i)\n                _data[i] &= other._data[i];\n\n            return *this;\n        }\n\n        BoolVector<size> operator&(const BoolVector<size>& other) const {\n            return BoolVector<size>(*this) &= other;\n        }\n\n        BoolVector<size> operator&&(const BoolVector<size>& other) const {\n            return BoolVector<size>(*this) &= other;\n        }\n\n        BoolVector<size>& operator|=(const BoolVector<size>& other) {\n            for(std::size_t i = 0; i != DataSize; ++i)\n                _data[i] |= other._data[i];\n\n            return *this;\n        }\n\n        BoolVector<size> operator|(const BoolVector<size>& other) const {\n            return BoolVector<size>(*this) |= other;\n        }\n\n        BoolVector<size> operator||(const BoolVector<size>& other) const {\n            return BoolVector<size>(*this) |= other;\n        }\n\n        BoolVector<size>& operator^=(const BoolVector<size>& other) {\n            for(std::size_t i = 0; i != DataSize; ++i)\n                _data[i] ^= other._data[i];\n\n            return *this;\n        }\n\n        BoolVector<size> operator^(const BoolVector<size>& other) const {\n            return BoolVector<size>(*this) ^= other;\n        }\n\n    private:\n        enum: UnsignedByte {\n            FullSegmentMask = 0xFF,\n            LastSegmentMask = (1 << size%8) - 1\n        };\n\n        template<std::size_t ...sequence> constexpr explicit BoolVector(Implementation::Sequence<sequence...>, UnsignedByte value): _data{Implementation::repeat(value, sequence)...} {}\n\n        UnsignedByte _data[(size-1)/8+1];\n};\n\ntemplate<std::size_t size> inline bool BoolVector<size>::operator==(const BoolVector<size>& other) const {\n    for(std::size_t i = 0; i != size/8; ++i)\n        if(_data[i] != other._data[i]) return false;\n\n    if(size%8 && (_data[DataSize-1] & LastSegmentMask) != (other._data[DataSize-1] & LastSegmentMask))\n        return false;\n\n    return true;\n}\n\ntemplate<std::size_t size> inline bool BoolVector<size>::all() const {\n    for(std::size_t i = 0; i != size/8; ++i)\n        if(_data[i] != FullSegmentMask) return false;\n\n    if(size%8 && (_data[DataSize-1] & LastSegmentMask) != LastSegmentMask)\n        return false;\n\n    return true;\n}\n\ntemplate<std::size_t size> inline bool BoolVector<size>::none() const {\n    for(std::size_t i = 0; i != size/8; ++i)\n        if(_data[i]) return false;\n\n    if(size%8 && (_data[DataSize-1] & LastSegmentMask))\n        return false;\n\n    return true;\n}\n\ntemplate<std::size_t size> inline BoolVector<size> BoolVector<size>::operator~() const {\n    BoolVector<size> out{NoInit};\n\n    for(std::size_t i = 0; i != DataSize; ++i)\n        out._data[i] = ~_data[i];\n\n    return out;\n}\n\nnamespace Implementation {\n\ntemplate<std::size_t size> struct StrictWeakOrdering<BoolVector<size>> {\n    bool operator()(const BoolVector<size>& a, const BoolVector<size>& b) const {\n        auto ad = a.data();\n        auto bd = b.data();\n        for(std::size_t i = 0; i < BoolVector<size>::DataSize - 1; ++i) {\n            if(ad[i] < bd[i])\n                return true;\n            if(ad[i] > bd[i])\n                return false;\n        }\n\n        constexpr UnsignedByte mask = UnsignedByte(0xFF) >> (BoolVector<size>::DataSize * 8 - size);\n        constexpr std::size_t i = BoolVector<size>::DataSize - 1;\n        return (ad[i] & mask) < (bd[i] & mask);\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Vector_h\n#define Magnum_Math_Vector_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, bool>::type isNan(T value) {\n    return std::isnan(UnderlyingTypeOf<T>(value));\n}\ntemplate<class T> constexpr typename std::enable_if<IsScalar<T>::value, T>::type min(T value, T min) {\n    return min < value ? min : value;\n}\ntemplate<class T> constexpr typename std::enable_if<IsScalar<T>::value, T>::type max(T value, T max) {\n    return value < max ? max : value;\n}\n\nnamespace Implementation {\n    template<std::size_t, class, class> struct VectorConverter;\n    template<class T, class U> T lerp(const T& a, const T& b, U t) {\n        return T((U(1) - t)*a + t*b);\n    }\n\n    template<bool integral> struct IsZero;\n    template<> struct IsZero<false> {\n        template<std::size_t size, class T> bool operator()(const Vector<size, T>& vec) const {\n            return std::abs(vec.dot()) < TypeTraits<T>::epsilon();\n        }\n    };\n    template<> struct IsZero<true> {\n        template<std::size_t size, class T> bool operator()(const Vector<size, T>& vec) const {\n            return vec == Vector<size, T>{};\n        }\n    };\n\n    template<std::size_t, class> struct MatrixDeterminant;\n    template<std::size_t, std::size_t> struct GatherComponentAt;\n    template<std::size_t, std::size_t, bool> struct ScatterComponentOr;\n    template<class T, std::size_t valueSize, char, char...> constexpr T scatterRecursive(const T&, const Vector<valueSize, typename T::Type>&, std::size_t);\n}\n\ntemplate<std::size_t size, class T> inline T dot(const Vector<size, T>& a, const Vector<size, T>& b) {\n    return (a*b).sum();\n}\n\ntemplate<std::size_t size, class FloatingPoint> inline\ntypename std::enable_if<std::is_floating_point<FloatingPoint>::value, Rad<FloatingPoint>>::type\nangle(const Vector<size, FloatingPoint>& normalizedA, const Vector<size, FloatingPoint>& normalizedB) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::angle(): vectors\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    return Rad<FloatingPoint>(std::acos(dot(normalizedA, normalizedB)));\n}\n\ntemplate<std::size_t size, class T> class Vector {\n    static_assert(size != 0, \"Vector cannot have zero elements\");\n\n    public:\n        typedef T Type;\n\n        enum: std::size_t {\n            Size = size\n        };\n\n        static Vector<size, T>& from(T* data) {\n            return *reinterpret_cast<Vector<size, T>*>(data);\n        }\n        static const Vector<size, T>& from(const T* data) {\n            return *reinterpret_cast<const Vector<size, T>*>(data);\n        }\n\n        template<std::size_t otherSize> constexpr static Vector<size, T> pad(const Vector<otherSize, T>& a, T value = T(0)) {\n            return padInternal<otherSize>(typename Implementation::GenerateSequence<size>::Type(), a, value);\n        }\n\n        constexpr /*implicit*/ Vector() noexcept: _data{} {}\n\n        constexpr explicit Vector(ZeroInitT) noexcept: _data{} {}\n\n        explicit Vector(NoInitT) noexcept {}\n\n        template<class ...U, class V = typename std::enable_if<sizeof...(U)+1 == size, T>::type> constexpr /*implicit*/ Vector(T first, U... next) noexcept: _data{first, next...} {}\n\n        template<class U, class V = typename std::enable_if<std::is_same<T, U>::value && size != 1, T>::type> constexpr explicit Vector(U value) noexcept: Vector(typename Implementation::GenerateSequence<size>::Type(), value) {}\n\n        template<class U> constexpr explicit Vector(const Vector<size, U>& other) noexcept: Vector(typename Implementation::GenerateSequence<size>::Type(), other) {}\n\n        template<class U, class V = decltype(Implementation::VectorConverter<size, T, U>::from(std::declval<U>()))> constexpr explicit Vector(const U& other) noexcept: Vector(Implementation::VectorConverter<size, T, U>::from(other)) {}\n\n        constexpr /*implicit*/ Vector(const Vector<size, T>&) noexcept = default;\n\n        template<class U, class V = decltype(Implementation::VectorConverter<size, T, U>::to(std::declval<Vector<size, T>>()))> constexpr explicit operator U() const {\n            return Implementation::VectorConverter<size, T, U>::to(*this);\n        }\n\n        T* data() { return _data; }\n        constexpr const T* data() const { return _data; }\n\n        T& operator[](std::size_t pos) { return _data[pos]; }\n        constexpr T operator[](std::size_t pos) const { return _data[pos]; }\n\n        bool operator==(const Vector<size, T>& other) const {\n            for(std::size_t i = 0; i != size; ++i)\n                if(!TypeTraits<T>::equals(_data[i], other._data[i])) return false;\n\n            return true;\n        }\n\n        bool operator!=(const Vector<size, T>& other) const {\n            return !operator==(other);\n        }\n\n        BoolVector<size> operator<(const Vector<size, T>& other) const;\n\n        BoolVector<size> operator<=(const Vector<size, T>& other) const;\n\n        BoolVector<size> operator>=(const Vector<size, T>& other) const;\n\n        BoolVector<size> operator>(const Vector<size, T>& other) const;\n\n        bool isZero() const {\n            return Implementation::IsZero<std::is_integral<T>::value>{}(*this);\n        }\n\n        bool isNormalized() const {\n            return Implementation::isNormalizedSquared(dot());\n        }\n\n        template<class U = T> typename std::enable_if<std::is_signed<U>::value, Vector<size, T>>::type\n        operator-() const;\n\n        Vector<size, T>& operator+=(const Vector<size, T>& other) {\n            for(std::size_t i = 0; i != size; ++i)\n                _data[i] += other._data[i];\n\n            return *this;\n        }\n\n        Vector<size, T> operator+(const Vector<size, T>& other) const {\n            return Vector<size, T>(*this) += other;\n        }\n\n        Vector<size, T>& operator-=(const Vector<size, T>& other) {\n            for(std::size_t i = 0; i != size; ++i)\n                _data[i] -= other._data[i];\n\n            return *this;\n        }\n\n        Vector<size, T> operator-(const Vector<size, T>& other) const {\n            return Vector<size, T>(*this) -= other;\n        }\n\n        Vector<size, T>& operator*=(T scalar) {\n            for(std::size_t i = 0; i != size; ++i)\n                _data[i] *= scalar;\n\n            return *this;\n        }\n\n        Vector<size, T> operator*(T scalar) const {\n            return Vector<size, T>(*this) *= scalar;\n        }\n\n        Vector<size, T>& operator/=(T scalar) {\n            for(std::size_t i = 0; i != size; ++i)\n                _data[i] /= scalar;\n\n            return *this;\n        }\n\n        Vector<size, T> operator/(T scalar) const {\n            return Vector<size, T>(*this) /= scalar;\n        }\n\n        Vector<size, T>& operator*=(const Vector<size, T>& other) {\n            for(std::size_t i = 0; i != size; ++i)\n                _data[i] *= other._data[i];\n\n            return *this;\n        }\n\n        Vector<size, T> operator*(const Vector<size, T>& other) const {\n            return Vector<size, T>(*this) *= other;\n        }\n\n        Vector<size, T>& operator/=(const Vector<size, T>& other) {\n            for(std::size_t i = 0; i != size; ++i)\n                _data[i] /= other._data[i];\n\n            return *this;\n        }\n\n        Vector<size, T> operator/(const Vector<size, T>& other) const {\n            return Vector<size, T>(*this) /= other;\n        }\n\n        T dot() const { return Math::dot(*this, *this); }\n\n        T length() const { return std::sqrt(dot()); }\n\n        template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, T>::type\n        lengthInverted() const { return T(1)/length(); }\n\n        template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, Vector<size, T>>::type\n        normalized() const { return *this*lengthInverted(); }\n\n        template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, Vector<size, T>>::type\n        resized(T length) const {\n            return *this*(lengthInverted()*length);\n        }\n\n        template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, Vector<size, T>>::type\n        projected(const Vector<size, T>& line) const {\n            return line*Math::dot(*this, line)/line.dot();\n        }\n\n        template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, Vector<size, T>>::type\n        projectedOntoNormalized(const Vector<size, T>& line) const;\n\n        constexpr Vector<size, T> flipped() const {\n            return flippedInternal(typename Implementation::GenerateSequence<size>::Type{});\n        }\n\n        T sum() const;\n\n        T product() const;\n\n        T min() const;\n\n        T max() const;\n\n        std::pair<T, T> minmax() const;\n\n    protected:\n        T _data[size];\n\n    private:\n        template<std::size_t, class> friend class Vector;\n        template<std::size_t, std::size_t, class> friend class RectangularMatrix;\n        template<std::size_t, class> friend class Matrix;\n        template<std::size_t, class> friend struct Implementation::MatrixDeterminant;\n        template<std::size_t, std::size_t> friend struct Implementation::GatherComponentAt;\n        template<std::size_t, std::size_t, bool> friend struct Implementation::ScatterComponentOr;\n        template<class T_, std::size_t valueSize, char, char...> friend constexpr T_ Implementation::scatterRecursive(const T_&, const Vector<valueSize, typename T_::Type>&, std::size_t);\n\n        template<std::size_t size_, class T_> friend BoolVector<size_> equal(const Vector<size_, T_>&, const Vector<size_, T_>&);\n        template<std::size_t size_, class T_> friend BoolVector<size_> notEqual(const Vector<size_, T_>&, const Vector<size_, T_>&);\n\n        template<class U, std::size_t ...sequence> constexpr explicit Vector(Implementation::Sequence<sequence...>, const Vector<size, U>& vector) noexcept: _data{T(vector._data[sequence])...} {}\n\n        template<std::size_t ...sequence> constexpr explicit Vector(Implementation::Sequence<sequence...>, T value) noexcept: _data{Implementation::repeat(value, sequence)...} {}\n\n        template<std::size_t otherSize, std::size_t ...sequence> constexpr static Vector<size, T> padInternal(Implementation::Sequence<sequence...>, const Vector<otherSize, T>& a, T value) {\n            return {sequence < otherSize ? a[sequence] : value...};\n        }\n\n        template<std::size_t ...sequence> constexpr Vector<size, T> flippedInternal(Implementation::Sequence<sequence...>) const {\n            return {_data[size - 1 - sequence]...};\n        }\n};\n\ntemplate<std::size_t size, class T> inline BoolVector<size> equal(const Vector<size, T>& a, const Vector<size, T>& b) {\n    BoolVector<size> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, TypeTraits<T>::equals(a._data[i], b._data[i]));\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline BoolVector<size> notEqual(const Vector<size, T>& a, const Vector<size, T>& b) {\n    BoolVector<size> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, !TypeTraits<T>::equals(a._data[i], b._data[i]));\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> operator*(\n    typename std::common_type<T>::type\n    scalar, const Vector<size, T>& vector)\n{\n    return vector*scalar;\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> operator/(\n    typename std::common_type<T>::type\n    scalar, const Vector<size, T>& vector)\n{\n    Vector<size, T> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = scalar/vector[i];\n\n    return out;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>&>::type\noperator%=(Vector<size, Integral>& a, Integral b) {\n    for(std::size_t i = 0; i != size; ++i)\n        a[i] %= b;\n\n    return a;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>>::type\noperator%(const Vector<size, Integral>& a, Integral b) {\n    Vector<size, Integral> copy(a);\n    return copy %= b;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>&>::type\noperator%=(Vector<size, Integral>& a, const Vector<size, Integral>& b) {\n    for(std::size_t i = 0; i != size; ++i)\n        a[i] %= b[i];\n\n    return a;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>>::type\noperator%(const Vector<size, Integral>& a, const Vector<size, Integral>& b) {\n    Vector<size, Integral> copy(a);\n    return copy %= b;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>>::type\noperator~(const Vector<size, Integral>& vector) {\n    Vector<size, Integral> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = ~vector[i];\n\n    return out;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>&>::type\noperator&=(Vector<size, Integral>& a, const Vector<size, Integral>& b) {\n    for(std::size_t i = 0; i != size; ++i)\n        a[i] &= b[i];\n\n    return a;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>>::type\noperator&(const Vector<size, Integral>& a, const Vector<size, Integral>& b) {\n    Vector<size, Integral> copy(a);\n    return copy &= b;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>&>::type\noperator|=(Vector<size, Integral>& a, const Vector<size, Integral>& b) {\n    for(std::size_t i = 0; i != size; ++i)\n        a[i] |= b[i];\n\n    return a;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>>::type\noperator|(const Vector<size, Integral>& a, const Vector<size, Integral>& b) {\n    Vector<size, Integral> copy(a);\n    return copy |= b;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>&>::type\noperator^=(Vector<size, Integral>& a, const Vector<size, Integral>& b) {\n    for(std::size_t i = 0; i != size; ++i)\n        a[i] ^= b[i];\n\n    return a;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>>::type\noperator^(const Vector<size, Integral>& a, const Vector<size, Integral>& b) {\n    Vector<size, Integral> copy(a);\n    return copy ^= b;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>&>::type\noperator<<=(Vector<size, Integral>& vector,\n    typename std::common_type<Integral>::type\n    shift)\n{\n    for(std::size_t i = 0; i != size; ++i)\n        vector[i] <<= shift;\n\n    return vector;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>>::type\noperator<<(const Vector<size, Integral>& vector,\n    typename std::common_type<Integral>::type\n    shift)\n{\n    Vector<size, Integral> copy(vector);\n    return copy <<= shift;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>&>::type\noperator>>=(Vector<size, Integral>& vector,\n    typename std::common_type<Integral>::type\n    shift) {\n    for(std::size_t i = 0; i != size; ++i)\n        vector[i] >>= shift;\n\n    return vector;\n}\n\ntemplate<std::size_t size, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value, Vector<size, Integral>>::type\noperator>>(const Vector<size, Integral>& vector,\n    typename std::common_type<Integral>::type\n    shift) {\n    Vector<size, Integral> copy(vector);\n    return copy >>= shift;\n}\n\ntemplate<std::size_t size, class Integral, class FloatingPoint> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>&>::type\noperator*=(Vector<size, Integral>& vector, FloatingPoint scalar) {\n    for(std::size_t i = 0; i != size; ++i)\n        vector[i] = Integral(vector[i]*scalar);\n\n    return vector;\n}\n\ntemplate<std::size_t size, class Integral, class FloatingPoint> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>>::type\noperator*(const Vector<size, Integral>& vector, FloatingPoint scalar) {\n    Vector<size, Integral> copy(vector);\n    return copy *= scalar;\n}\n\ntemplate<std::size_t size, class FloatingPoint, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>>::type\noperator*(FloatingPoint scalar, const Vector<size, Integral>& vector) {\n    return vector*scalar;\n}\n\ntemplate<std::size_t size, class Integral, class FloatingPoint> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>&>::type\noperator/=(Vector<size, Integral>& vector, FloatingPoint scalar) {\n    for(std::size_t i = 0; i != size; ++i)\n        vector[i] = Integral(vector[i]/scalar);\n\n    return vector;\n}\n\ntemplate<std::size_t size, class Integral, class FloatingPoint> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>>::type\noperator/(const Vector<size, Integral>& vector, FloatingPoint scalar) {\n    Vector<size, Integral> copy(vector);\n    return copy /= scalar;\n}\n\ntemplate<std::size_t size, class Integral, class FloatingPoint> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>&>::type\noperator*=(Vector<size, Integral>& a, const Vector<size, FloatingPoint>& b) {\n    for(std::size_t i = 0; i != size; ++i)\n        a[i] = Integral(a[i]*b[i]);\n\n    return a;\n}\n\ntemplate<std::size_t size, class Integral, class FloatingPoint> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>>::type\noperator*(const Vector<size, Integral>& a, const Vector<size, FloatingPoint>& b) {\n    Vector<size, Integral> copy(a);\n    return copy *= b;\n}\n\ntemplate<std::size_t size, class FloatingPoint, class Integral> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>>::type\noperator*(const Vector<size, FloatingPoint>& a, const Vector<size, Integral>& b) {\n    return b*a;\n}\n\ntemplate<std::size_t size, class Integral, class FloatingPoint> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>&>::type\noperator/=(Vector<size, Integral>& a, const Vector<size, FloatingPoint>& b) {\n    for(std::size_t i = 0; i != size; ++i)\n        a[i] = Integral(a[i]/b[i]);\n\n    return a;\n}\n\ntemplate<std::size_t size, class Integral, class FloatingPoint> inline\ntypename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Vector<size, Integral>>::type\noperator/(const Vector<size, Integral>& a, const Vector<size, FloatingPoint>& b) {\n    Vector<size, Integral> copy(a);\n    return copy /= b;\n}\n\n#define MAGNUM_VECTOR_SUBCLASS_IMPLEMENTATION(size, Type)                   \\\n    static Type<T>& from(T* data) {                                         \\\n        return *reinterpret_cast<Type<T>*>(data);                           \\\n    }                                                                       \\\n    static const Type<T>& from(const T* data) {                             \\\n        return *reinterpret_cast<const Type<T>*>(data);                     \\\n    }                                                                       \\\n    template<std::size_t otherSize> constexpr static Type<T> pad(const Math::Vector<otherSize, T>& a, T value = T(0)) { \\\n        return Math::Vector<size, T>::pad(a, value);                        \\\n    }                                                                       \\\n                                                                            \\\n    template<class U = T> typename std::enable_if<std::is_signed<U>::value, Type<T>>::type \\\n    operator-() const {                                                     \\\n        return Math::Vector<size, T>::operator-();                          \\\n    }                                                                       \\\n    Type<T>& operator+=(const Math::Vector<size, T>& other) {               \\\n        Math::Vector<size, T>::operator+=(other);                           \\\n        return *this;                                                       \\\n    }                                                                       \\\n    Type<T> operator+(const Math::Vector<size, T>& other) const {           \\\n        return Math::Vector<size, T>::operator+(other);                     \\\n    }                                                                       \\\n    Type<T>& operator-=(const Math::Vector<size, T>& other) {               \\\n        Math::Vector<size, T>::operator-=(other);                           \\\n        return *this;                                                       \\\n    }                                                                       \\\n    Type<T> operator-(const Math::Vector<size, T>& other) const {           \\\n        return Math::Vector<size, T>::operator-(other);                     \\\n    }                                                                       \\\n    Type<T>& operator*=(T number) {                                         \\\n        Math::Vector<size, T>::operator*=(number);                          \\\n        return *this;                                                       \\\n    }                                                                       \\\n    Type<T> operator*(T number) const {                                     \\\n        return Math::Vector<size, T>::operator*(number);                    \\\n    }                                                                       \\\n    Type<T>& operator/=(T number) {                                         \\\n        Math::Vector<size, T>::operator/=(number);                          \\\n        return *this;                                                       \\\n    }                                                                       \\\n    Type<T> operator/(T number) const {                                     \\\n        return Math::Vector<size, T>::operator/(number);                    \\\n    }                                                                       \\\n    Type<T>& operator*=(const Math::Vector<size, T>& other) {               \\\n        Math::Vector<size, T>::operator*=(other);                           \\\n        return *this;                                                       \\\n    }                                                                       \\\n    Type<T> operator*(const Math::Vector<size, T>& other) const {           \\\n        return Math::Vector<size, T>::operator*(other);                     \\\n    }                                                                       \\\n    Type<T>& operator/=(const Math::Vector<size, T>& other) {               \\\n        Math::Vector<size, T>::operator/=(other);                           \\\n        return *this;                                                       \\\n    }                                                                       \\\n    Type<T> operator/(const Math::Vector<size, T>& other) const {           \\\n        return Math::Vector<size, T>::operator/(other);                     \\\n    }                                                                       \\\n                                                                            \\\n    template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, Type<T>>::type normalized() const { \\\n        return Math::Vector<size, T>::normalized();                         \\\n    }                                                                       \\\n    template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, Type<T>>::type resized(T length) const { \\\n        return Math::Vector<size, T>::resized(length);                      \\\n    }                                                                       \\\n    template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, Type<T>>::type projected(const Math::Vector<size, T>& other) const {           \\\n        return Math::Vector<size, T>::projected(other);                     \\\n    }                                                                       \\\n    template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, Type<T>>::type projectedOntoNormalized(const Math::Vector<size, T>& other) const { \\\n        return Math::Vector<size, T>::projectedOntoNormalized(other);       \\\n    }                                                                       \\\n    constexpr Type<T> flipped() const {                                     \\\n        return Math::Vector<size, T>::flipped();                            \\\n    }\n\n#define MAGNUM_VECTORn_OPERATOR_IMPLEMENTATION(size, Type)                  \\\n    template<class T> inline Type<T> operator*(typename std::common_type<T>::type number, const Type<T>& vector) { \\\n        return number*static_cast<const Math::Vector<size, T>&>(vector);    \\\n    }                                                                       \\\n    template<class T> inline Type<T> operator/(typename std::common_type<T>::type number, const Type<T>& vector) { \\\n        return number/static_cast<const Math::Vector<size, T>&>(vector);    \\\n    }                                                                       \\\n                                                                            \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>&>::type operator%=(Type<Integral>& a, Integral b) { \\\n        static_cast<Math::Vector<size, Integral>&>(a) %= b;                 \\\n        return a;                                                           \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>>::type operator%(const Type<Integral>& a, Integral b) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(a) % b;     \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>&>::type operator%=(Type<Integral>& a, const Math::Vector<size, Integral>& b) { \\\n        static_cast<Math::Vector<size, Integral>&>(a) %= b;                 \\\n        return a;                                                           \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>>::type operator%(const Type<Integral>& a, const Math::Vector<size, Integral>& b) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(a) % b;     \\\n    }                                                                       \\\n                                                                            \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>>::type operator~(const Type<Integral>& vector) { \\\n        return ~static_cast<const Math::Vector<size, Integral>&>(vector);   \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>&>::type operator&=(Type<Integral>& a, const Math::Vector<size, Integral>& b) { \\\n        static_cast<Math::Vector<size, Integral>&>(a) &= b;                 \\\n        return a;                                                           \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>>::type operator&(const Type<Integral>& a, const Math::Vector<size, Integral>& b) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(a) & b;     \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>&>::type operator|=(Type<Integral>& a, const Math::Vector<size, Integral>& b) { \\\n        static_cast<Math::Vector<size, Integral>&>(a) |= b;                 \\\n        return a;                                                           \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>>::type operator|(const Type<Integral>& a, const Math::Vector<size, Integral>& b) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(a) | b;     \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>&>::type operator^=(Type<Integral>& a, const Math::Vector<size, Integral>& b) { \\\n        static_cast<Math::Vector<size, Integral>&>(a) ^= b;                 \\\n        return a;                                                           \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>>::type operator^(const Type<Integral>& a, const Math::Vector<size, Integral>& b) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(a) ^ b;     \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>&>::type operator<<=(Type<Integral>& vector, typename std::common_type<Integral>::type shift) { \\\n        static_cast<Math::Vector<size, Integral>&>(vector) <<= shift;       \\\n        return vector;                                                      \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>>::type operator<<(const Type<Integral>& vector, typename std::common_type<Integral>::type shift) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(vector) << shift; \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>&>::type operator>>=(Type<Integral>& vector, typename std::common_type<Integral>::type shift) { \\\n        static_cast<Math::Vector<size, Integral>&>(vector) >>= shift;       \\\n        return vector;                                                      \\\n    }                                                                       \\\n    template<class Integral> inline typename std::enable_if<std::is_integral<Integral>::value, Type<Integral>>::type operator>>(const Type<Integral>& vector, typename std::common_type<Integral>::type shift) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(vector) >> shift; \\\n    }                                                                       \\\n    template<class Integral, class FloatingPoint> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>&>::type operator*=(Type<Integral>& vector, FloatingPoint number) { \\\n        static_cast<Math::Vector<size, Integral>&>(vector) *= number;       \\\n        return vector;                                                      \\\n    }                                                                       \\\n    template<class Integral, class FloatingPoint> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>>::type operator*(const Type<Integral>& vector, FloatingPoint number) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(vector)*number; \\\n    }                                                                       \\\n    template<class FloatingPoint, class Integral> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>>::type operator*(FloatingPoint number, const Type<Integral>& vector) { \\\n        return number*static_cast<const Math::Vector<size, Integral>&>(vector); \\\n    }                                                                       \\\n    template<class Integral, class FloatingPoint> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>&>::type operator/=(Type<Integral>& vector, FloatingPoint number) { \\\n        static_cast<Math::Vector<size, Integral>&>(vector) /= number;       \\\n        return vector;                                                      \\\n    }                                                                       \\\n    template<class Integral, class FloatingPoint> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>>::type operator/(const Type<Integral>& vector, FloatingPoint number) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(vector)/number; \\\n    }                                                                       \\\n                                                                            \\\n    template<class Integral, class FloatingPoint> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>&>::type operator*=(Type<Integral>& a, const Math::Vector<size, FloatingPoint>& b) { \\\n        static_cast<Math::Vector<size, Integral>&>(a) *= b;                 \\\n        return a;                                                           \\\n    }                                                                       \\\n    template<class Integral, class FloatingPoint> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>>::type operator*(const Type<Integral>& a, const Math::Vector<size, FloatingPoint>& b) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(a)*b;       \\\n    }                                                                       \\\n    template<class FloatingPoint, class Integral> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>>::type operator*(const Math::Vector<size, FloatingPoint>& a, const Type<Integral>& b) { \\\n        return a*static_cast<const Math::Vector<size, Integral>&>(b);       \\\n    }                                                                       \\\n    template<class Integral, class FloatingPoint> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>&>::type operator/=(Type<Integral>& a, const Math::Vector<size, FloatingPoint>& b) { \\\n        static_cast<Math::Vector<size, Integral>&>(a) /= b;                 \\\n        return a;                                                           \\\n    }                                                                       \\\n    template<class Integral, class FloatingPoint> inline typename std::enable_if<std::is_integral<Integral>::value && std::is_floating_point<FloatingPoint>::value, Type<Integral>>::type operator/(const Type<Integral>& a, const Math::Vector<size, FloatingPoint>& b) { \\\n        return static_cast<const Math::Vector<size, Integral>&>(a)/b;       \\\n    }\n\ntemplate<std::size_t size, class T> inline BoolVector<size> Vector<size, T>::operator<(const Vector<size, T>& other) const {\n    BoolVector<size> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, _data[i] < other._data[i]);\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline BoolVector<size> Vector<size, T>::operator<=(const Vector<size, T>& other) const {\n    BoolVector<size> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, _data[i] <= other._data[i]);\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline BoolVector<size> Vector<size, T>::operator>=(const Vector<size, T>& other) const {\n    BoolVector<size> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, _data[i] >= other._data[i]);\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline BoolVector<size> Vector<size, T>::operator>(const Vector<size, T>& other) const {\n    BoolVector<size> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, _data[i] > other._data[i]);\n\n    return out;\n}\n\ntemplate<std::size_t size, class T>\ntemplate<class U> inline typename std::enable_if<std::is_signed<U>::value, Vector<size, T>>::type\nVector<size, T>::operator-() const {\n    Vector<size, T> out;\n\n    for(std::size_t i = 0; i != size; ++i)\n        out._data[i] = -_data[i];\n\n    return out;\n}\n\ntemplate<std::size_t size, class T>\ntemplate<class U> inline typename std::enable_if<std::is_floating_point<U>::value, Vector<size, T>>::type\nVector<size, T>::projectedOntoNormalized(const Vector<size, T>& line) const {\n    CORRADE_ASSERT(line.isNormalized(),\n        \"Math::Vector::projectedOntoNormalized(): line\" << line << \"is not normalized\", {});\n    return line*Math::dot(*this, line);\n}\n\ntemplate<std::size_t size, class T> inline T Vector<size, T>::sum() const {\n    T out(_data[0]);\n\n    for(std::size_t i = 1; i != size; ++i)\n        out += _data[i];\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline T Vector<size, T>::product() const {\n    T out(_data[0]);\n\n    for(std::size_t i = 1; i != size; ++i)\n        out *= _data[i];\n\n    return out;\n}\n\nnamespace Implementation {\n    template<std::size_t size, class T> constexpr std::size_t firstNonNan(const T(&)[size], std::false_type) {\n        return 0;\n    }\n    template<std::size_t size, class T> inline std::size_t firstNonNan(const T(&data)[size], std::true_type) {\n        for(std::size_t i = 0; i != size; ++i)\n            if(!isNan(data[i])) return i;\n        return size - 1;\n    }\n}\n\ntemplate<std::size_t size, class T> inline T Vector<size, T>::min() const {\n    std::size_t i = Implementation::firstNonNan(_data, IsFloatingPoint<T>{});\n    T out(_data[i]);\n\n    for(++i; i != size; ++i)\n        out = Math::min(out, _data[i]);\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline T Vector<size, T>::max() const {\n    std::size_t i = Implementation::firstNonNan(_data, IsFloatingPoint<T>{});\n    T out(_data[i]);\n\n    for(++i; i != size; ++i)\n        out = Math::max(out, _data[i]);\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline std::pair<T, T> Vector<size, T>::minmax() const {\n    std::size_t i = Implementation::firstNonNan(_data, IsFloatingPoint<T>{});\n    T min{_data[i]}, max{_data[i]};\n\n    for(++i; i != size; ++i) {\n        if(_data[i] < min)\n            min = _data[i];\n        else if(_data[i] > max)\n            max = _data[i];\n    }\n\n    return {min, max};\n}\n\nnamespace Implementation {\n\ntemplate<std::size_t size, class T> struct StrictWeakOrdering<Vector<size, T>> {\n    bool operator()(const Vector<size, T>& a, const Vector<size, T>& b) const {\n        for(std::size_t i = 0; i < size; ++i) {\n            if(a[i] < b[i])\n                return true;\n            if(a[i] > b[i])\n                return false;\n        }\n\n        return false;\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Bezier_h\n#define Magnum_Math_Bezier_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<UnsignedInt, UnsignedInt, class, class> struct BezierConverter;\n}\n\ntemplate<UnsignedInt order, UnsignedInt dimensions, class T> class Bezier {\n    static_assert(order != 0, \"Bezier cannot have zero order\");\n\n    template<UnsignedInt, UnsignedInt, class> friend class Bezier;\n\n    public:\n        typedef T Type;\n\n        enum: UnsignedInt {\n            Order = order,\n            Dimensions = dimensions\n        };\n\n        template<class VectorType> static\n        typename std::enable_if<std::is_base_of<Vector<dimensions, T>, VectorType>::value && order == 3, Bezier<order, dimensions, T>>::type\n        fromCubicHermite(const CubicHermite<VectorType>& a, const CubicHermite<VectorType>& b) {\n            return {a.point(), a.outTangent()/T(3) - a.point(), b.point() - b.inTangent()/T(3), b.point()};\n        }\n\n        constexpr /*implicit*/ Bezier() noexcept: Bezier<order, dimensions, T>{typename Implementation::GenerateSequence<order + 1>::Type{}, ZeroInit} {}\n\n        constexpr explicit Bezier(ZeroInitT) noexcept: Bezier<order, dimensions, T>{typename Implementation::GenerateSequence<order + 1>::Type{}, ZeroInit} {}\n\n        explicit Bezier(NoInitT) noexcept: Bezier<order, dimensions, T>{typename Implementation::GenerateSequence<order + 1>::Type{}, NoInit} {}\n\n        template<typename... U> constexpr /*implicit*/ Bezier(const Vector<dimensions, T>& first, U... next) noexcept: _data{first, next...} {\n            static_assert(sizeof...(U) + 1 == order + 1, \"Wrong number of arguments\");\n        }\n\n        template<class U> constexpr explicit Bezier(const Bezier<order, dimensions, U>& other) noexcept: Bezier{typename Implementation::GenerateSequence<order + 1>::Type(), other} {}\n\n        template<class U, class V = decltype(Implementation::BezierConverter<order, dimensions, T, U>::from(std::declval<U>()))> constexpr explicit Bezier(const U& other) noexcept: Bezier<order, dimensions, T>{Implementation::BezierConverter<order, dimensions, T, U>::from(other)} {}\n\n        template<class U, class V = decltype(Implementation::BezierConverter<order, dimensions, T, U>::to(std::declval<Bezier<order, dimensions, T>>()))> constexpr explicit operator U() const {\n            return Implementation::BezierConverter<order, dimensions, T, U>::to(*this);\n        }\n\n        Vector<dimensions, T>* data() { return _data; }\n        constexpr const Vector<dimensions, T>* data() const { return _data; }\n\n        bool operator==(const Bezier<order, dimensions, T>& other) const {\n            for(std::size_t i = 0; i != order + 1; ++i)\n                if(_data[i] != other._data[i]) return false;\n            return true;\n        }\n\n        bool operator!=(const Bezier<order, dimensions, T>& other) const {\n            return !operator==(other);\n        }\n\n        Vector<dimensions, T>& operator[](std::size_t i) { return _data[i]; }\n        constexpr const Vector<dimensions, T>& operator[](std::size_t i) const { return _data[i]; }\n\n        Vector<dimensions, T> value(Float t) const {\n            Bezier<order, dimensions, T> iPoints[order + 1];\n            calculateIntermediatePoints(iPoints, t);\n            return iPoints[0][order];\n        }\n\n        std::pair<Bezier<order, dimensions, T>, Bezier<order, dimensions, T>> subdivide(Float t) const {\n            Bezier<order, dimensions, T> iPoints[order + 1];\n            calculateIntermediatePoints(iPoints, t);\n            Bezier<order, dimensions, T> left, right;\n            for(std::size_t i = 0; i <= order; ++i)\n                left[i] = iPoints[0][i];\n            for(std::size_t i = 0, j = order; i <= order; --j, ++i)\n                right[i] = iPoints[i][j];\n            return {left, right};\n        }\n\n    private:\n        template<class U, std::size_t ...sequence> constexpr explicit Bezier(Implementation::Sequence<sequence...>, const Bezier<order, dimensions, U>& other) noexcept: _data{Vector<dimensions, T>(other._data[sequence])...} {}\n\n        template<class U, std::size_t ...sequence> constexpr explicit Bezier(Implementation::Sequence<sequence...>, U): _data{Vector<dimensions, T>((static_cast<void>(sequence), U{typename U::Init{}}))...} {}\n\n        void calculateIntermediatePoints(Bezier<order, dimensions, T>(&iPoints)[order + 1], Float t) const {\n            for(std::size_t i = 0; i <= order; ++i) {\n                iPoints[i][0] = _data[i];\n            }\n            for(std::size_t r = 1; r <= order; ++r) {\n                for(std::size_t i = 0; i <= order - r; ++i) {\n                    iPoints[i][r] = (1 - t)*iPoints[i][r - 1] + t*iPoints[i + 1][r - 1];\n                }\n            }\n        }\n\n        Vector<dimensions, T> _data[order + 1];\n};\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<UnsignedInt dimensions, class T> using QuadraticBezier = Bezier<2, dimensions, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using QuadraticBezier2D = QuadraticBezier<2, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using QuadraticBezier3D = QuadraticBezier<3, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<UnsignedInt dimensions, class T> using CubicBezier = Bezier<3, dimensions, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using CubicBezier2D = CubicBezier<2, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using CubicBezier3D = CubicBezier<3, T>;\n#endif\n\nnamespace Implementation {\n\ntemplate<UnsignedInt order, UnsignedInt dimensions, class T> struct StrictWeakOrdering<Bezier<order, dimensions, T>> {\n    bool operator()(const Bezier<order, dimensions, T>& a, const Bezier<order, dimensions, T>& b) const {\n        StrictWeakOrdering<Vector<dimensions, T>> o;\n        for(std::size_t i = 0; i < order + 1; ++i) {\n            if(o(a[i], b[i]))\n                return true;\n            if(o(b[i], a[i]))\n                return false;\n        }\n\n        return false;\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_RectangularMatrix_h\n#define Magnum_Math_RectangularMatrix_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<std::size_t, std::size_t, class, class> struct RectangularMatrixConverter;\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> class RectangularMatrix {\n    static_assert(cols != 0 && rows != 0, \"RectangularMatrix cannot have zero elements\");\n\n    template<std::size_t, std::size_t, class> friend class RectangularMatrix;\n\n    public:\n        typedef T Type;\n\n        enum: std::size_t {\n            Cols = cols,\n            Rows = rows,\n\n            DiagonalSize = (cols < rows ? cols : rows)\n        };\n\n        static RectangularMatrix<cols, rows, T>& from(T* data) {\n            return *reinterpret_cast<RectangularMatrix<cols, rows, T>*>(data);\n        }\n        static const RectangularMatrix<cols, rows, T>& from(const T* data) {\n            return *reinterpret_cast<const RectangularMatrix<cols, rows, T>*>(data);\n        }\n\n        static RectangularMatrix<cols, rows, T> fromVector(const Vector<cols*rows, T>& vector) {\n            return *reinterpret_cast<const RectangularMatrix<cols, rows, T>*>(vector.data());\n        }\n\n        constexpr static RectangularMatrix<cols, rows, T> fromDiagonal(const Vector<DiagonalSize, T>& diagonal) noexcept {\n            return RectangularMatrix(typename Implementation::GenerateSequence<cols>::Type(), diagonal);\n        }\n\n        constexpr /*implicit*/ RectangularMatrix() noexcept: RectangularMatrix<cols, rows, T>{typename Implementation::GenerateSequence<cols>::Type{}, ZeroInit} {}\n\n        constexpr explicit RectangularMatrix(ZeroInitT) noexcept: RectangularMatrix<cols, rows, T>{typename Implementation::GenerateSequence<cols>::Type{}, ZeroInit} {}\n\n        explicit RectangularMatrix(NoInitT) noexcept: RectangularMatrix<cols, rows, T>{typename Implementation::GenerateSequence<cols>::Type{}, NoInit} {}\n\n        template<class ...U> constexpr /*implicit*/ RectangularMatrix(const Vector<rows, T>& first, const U&... next) noexcept: _data{first, next...} {\n            static_assert(sizeof...(next)+1 == cols, \"Improper number of arguments passed to RectangularMatrix constructor\");\n        }\n\n        constexpr explicit RectangularMatrix(T value) noexcept: RectangularMatrix{typename Implementation::GenerateSequence<cols>::Type(), value} {}\n\n        template<class U> constexpr explicit RectangularMatrix(const RectangularMatrix<cols, rows, U>& other) noexcept: RectangularMatrix(typename Implementation::GenerateSequence<cols>::Type(), other) {}\n\n        template<class U, class V = decltype(Implementation::RectangularMatrixConverter<cols, rows, T, U>::from(std::declval<U>()))> constexpr explicit RectangularMatrix(const U& other): RectangularMatrix(Implementation::RectangularMatrixConverter<cols, rows, T, U>::from(other)) {}\n\n        constexpr /*implicit*/ RectangularMatrix(const RectangularMatrix<cols, rows, T>&) noexcept = default;\n\n        template<class U, class V = decltype(Implementation::RectangularMatrixConverter<cols, rows, T, U>::to(std::declval<RectangularMatrix<cols, rows, T>>()))> constexpr explicit operator U() const {\n            return Implementation::RectangularMatrixConverter<cols, rows, T, U>::to(*this);\n        }\n\n        T* data() { return _data[0].data(); }\n        constexpr const T* data() const { return _data[0].data(); }\n\n        Vector<rows, T>& operator[](std::size_t col) { return _data[col]; }\n        constexpr const Vector<rows, T>& operator[](std::size_t col) const { return _data[col]; }\n\n        Vector<cols, T> row(std::size_t row) const;\n\n        void setRow(std::size_t row, const Vector<cols, T>& data);\n\n        bool operator==(const RectangularMatrix<cols, rows, T>& other) const {\n            for(std::size_t i = 0; i != cols; ++i)\n                if(_data[i] != other._data[i]) return false;\n\n            return true;\n        }\n\n        bool operator!=(const RectangularMatrix<cols, rows, T>& other) const {\n            return !operator==(other);\n        }\n\n        BoolVector<cols*rows> operator<(const RectangularMatrix<cols, rows, T>& other) const {\n            return toVector() < other.toVector();\n        }\n\n        BoolVector<cols*rows> operator<=(const RectangularMatrix<cols, rows, T>& other) const {\n            return toVector() <= other.toVector();\n        }\n\n        BoolVector<cols*rows> operator>=(const RectangularMatrix<cols, rows, T>& other) const {\n            return toVector() >= other.toVector();\n        }\n\n        BoolVector<cols*rows> operator>(const RectangularMatrix<cols, rows, T>& other) const {\n            return toVector() > other.toVector();\n        }\n\n        RectangularMatrix<cols, rows, T> operator-() const;\n\n        RectangularMatrix<cols, rows, T>& operator+=(const RectangularMatrix<cols, rows, T>& other) {\n            for(std::size_t i = 0; i != cols; ++i)\n                _data[i] += other._data[i];\n\n            return *this;\n        }\n\n        RectangularMatrix<cols, rows, T> operator+(const RectangularMatrix<cols, rows, T>& other) const {\n            return RectangularMatrix<cols, rows, T>(*this)+=other;\n        }\n\n        RectangularMatrix<cols, rows, T>& operator-=(const RectangularMatrix<cols, rows, T>& other) {\n            for(std::size_t i = 0; i != cols; ++i)\n                _data[i] -= other._data[i];\n\n            return *this;\n        }\n\n        RectangularMatrix<cols, rows, T> operator-(const RectangularMatrix<cols, rows, T>& other) const {\n            return RectangularMatrix<cols, rows, T>(*this)-=other;\n        }\n\n        RectangularMatrix<cols, rows, T>& operator*=(T scalar) {\n            for(std::size_t i = 0; i != cols; ++i)\n                _data[i] *= scalar;\n\n            return *this;\n        }\n\n        RectangularMatrix<cols, rows, T> operator*(T scalar) const {\n            return RectangularMatrix<cols, rows, T>(*this) *= scalar;\n        }\n\n        RectangularMatrix<cols, rows, T>& operator/=(T scalar) {\n            for(std::size_t i = 0; i != cols; ++i)\n                _data[i] /= scalar;\n\n            return *this;\n        }\n\n        RectangularMatrix<cols, rows, T> operator/(T scalar) const {\n            return RectangularMatrix<cols, rows, T>(*this) /= scalar;\n        }\n\n        template<std::size_t size> RectangularMatrix<size, rows, T> operator*(const RectangularMatrix<size, cols, T>& other) const;\n\n        Vector<rows, T> operator*(const Vector<cols, T>& other) const {\n            return operator*(RectangularMatrix<1, cols, T>(other))[0];\n        }\n\n        RectangularMatrix<rows, cols, T> transposed() const;\n\n        constexpr RectangularMatrix<cols, rows, T> flippedCols() const {\n            return flippedColsInternal(typename Implementation::GenerateSequence<cols>::Type{});\n        }\n\n        constexpr RectangularMatrix<cols, rows, T> flippedRows() const {\n            return flippedRowsInternal(typename Implementation::GenerateSequence<cols>::Type{});\n        }\n\n        constexpr Vector<DiagonalSize, T> diagonal() const {\n            return diagonalInternal(typename Implementation::GenerateSequence<DiagonalSize>::Type());\n        }\n\n        Vector<rows*cols, T> toVector() const {\n            return *reinterpret_cast<const Vector<rows*cols, T>*>(data());\n        }\n\n    protected:\n        template<std::size_t ...sequence> constexpr explicit RectangularMatrix(Implementation::Sequence<sequence...>, const Vector<DiagonalSize, T>& diagonal);\n\n        template<std::size_t ...sequence> constexpr explicit RectangularMatrix(Implementation::Sequence<sequence...>, T value) noexcept: _data{Vector<rows, T>((static_cast<void>(sequence), value))...} {}\n\n    private:\n        template<std::size_t, class> friend class Matrix;\n        template<std::size_t, class> friend struct Implementation::MatrixDeterminant;\n\n        template<class U, std::size_t ...sequence> constexpr explicit RectangularMatrix(Implementation::Sequence<sequence...>, const RectangularMatrix<cols, rows, U>& matrix) noexcept: _data{Vector<rows, T>(matrix[sequence])...} {}\n\n        template<class U, std::size_t ...sequence> constexpr explicit RectangularMatrix(Implementation::Sequence<sequence...>, U) noexcept: _data{Vector<rows, T>((static_cast<void>(sequence), U{typename U::Init{}}))...} {}\n\n        template<std::size_t ...sequence> constexpr RectangularMatrix<cols, rows, T> flippedColsInternal(Implementation::Sequence<sequence...>) const {\n            return {_data[cols - 1 - sequence]...};\n        }\n\n        template<std::size_t ...sequence> constexpr RectangularMatrix<cols, rows, T> flippedRowsInternal(Implementation::Sequence<sequence...>) const {\n            return {_data[sequence].flipped()...};\n        }\n\n        template<std::size_t ...sequence> constexpr Vector<DiagonalSize, T> diagonalInternal(Implementation::Sequence<sequence...>) const;\n\n        Vector<rows, T> _data[cols];\n};\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix2x3 = RectangularMatrix<2, 3, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix3x2 = RectangularMatrix<3, 2, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix2x4 = RectangularMatrix<2, 4, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix4x2 = RectangularMatrix<4, 2, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix3x4 = RectangularMatrix<3, 4, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix4x3 = RectangularMatrix<4, 3, T>;\n#endif\n\ntemplate<std::size_t cols, std::size_t rows, class T> inline RectangularMatrix<cols, rows, T> operator*(\n    typename std::common_type<T>::type\n    scalar, const RectangularMatrix<cols, rows, T>& matrix)\n{\n    return matrix*scalar;\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> inline RectangularMatrix<cols, rows, T> operator/(\n    typename std::common_type<T>::type\n    scalar, const RectangularMatrix<cols, rows, T>& matrix)\n{\n    RectangularMatrix<cols, rows, T> out{NoInit};\n\n    for(std::size_t i = 0; i != cols; ++i)\n        out[i] = scalar/matrix[i];\n\n    return out;\n}\n\ntemplate<std::size_t size, std::size_t cols, class T> inline RectangularMatrix<cols, size, T> operator*(const Vector<size, T>& vector, const RectangularMatrix<cols, 1, T>& matrix) {\n    return RectangularMatrix<1, size, T>(vector)*matrix;\n}\n\n#define MAGNUM_RECTANGULARMATRIX_SUBCLASS_IMPLEMENTATION(cols, rows, ...)   \\\n    static __VA_ARGS__& from(T* data) {                                     \\\n        return *reinterpret_cast<__VA_ARGS__*>(data);                       \\\n    }                                                                       \\\n    static const __VA_ARGS__& from(const T* data) {                         \\\n        return *reinterpret_cast<const __VA_ARGS__*>(data);                 \\\n    }                                                                       \\\n    constexpr static __VA_ARGS__ fromDiagonal(const Vector<Math::RectangularMatrix<cols, rows, T>::DiagonalSize, T>& diagonal) { \\\n        return Math::RectangularMatrix<cols, rows, T>::fromDiagonal(diagonal); \\\n    }                                                                       \\\n                                                                            \\\n    __VA_ARGS__ operator-() const {                                         \\\n        return Math::RectangularMatrix<cols, rows, T>::operator-();         \\\n    }                                                                       \\\n    __VA_ARGS__& operator+=(const Math::RectangularMatrix<cols, rows, T>& other) { \\\n        Math::RectangularMatrix<cols, rows, T>::operator+=(other);          \\\n        return *this;                                                       \\\n    }                                                                       \\\n    __VA_ARGS__ operator+(const Math::RectangularMatrix<cols, rows, T>& other) const { \\\n        return Math::RectangularMatrix<cols, rows, T>::operator+(other);    \\\n    }                                                                       \\\n    __VA_ARGS__& operator-=(const Math::RectangularMatrix<cols, rows, T>& other) { \\\n        Math::RectangularMatrix<cols, rows, T>::operator-=(other);          \\\n        return *this;                                                       \\\n    }                                                                       \\\n    __VA_ARGS__ operator-(const Math::RectangularMatrix<cols, rows, T>& other) const { \\\n        return Math::RectangularMatrix<cols, rows, T>::operator-(other);    \\\n    }                                                                       \\\n    __VA_ARGS__& operator*=(T number) {                                     \\\n        Math::RectangularMatrix<cols, rows, T>::operator*=(number);         \\\n        return *this;                                                       \\\n    }                                                                       \\\n    __VA_ARGS__ operator*(T number) const {                                 \\\n        return Math::RectangularMatrix<cols, rows, T>::operator*(number);   \\\n    }                                                                       \\\n    __VA_ARGS__& operator/=(T number) {                                     \\\n        Math::RectangularMatrix<cols, rows, T>::operator/=(number);         \\\n        return *this;                                                       \\\n    }                                                                       \\\n    __VA_ARGS__ operator/(T number) const {                                 \\\n        return Math::RectangularMatrix<cols, rows, T>::operator/(number);   \\\n    }                                                                       \\\n    constexpr __VA_ARGS__ flippedCols() const {                             \\\n        return Math::RectangularMatrix<cols, rows, T>::flippedCols();       \\\n    }                                                                       \\\n    constexpr __VA_ARGS__ flippedRows() const {                             \\\n        return Math::RectangularMatrix<cols, rows, T>::flippedRows();       \\\n    }                                                                       \\\n\n#define MAGNUM_MATRIX_OPERATOR_IMPLEMENTATION(...)                          \\\n    template<std::size_t size, class T> inline __VA_ARGS__ operator*(typename std::common_type<T>::type number, const __VA_ARGS__& matrix) { \\\n        return number*static_cast<const Math::RectangularMatrix<size, size, T>&>(matrix); \\\n    }                                                                       \\\n    template<std::size_t size, class T> inline __VA_ARGS__ operator/(typename std::common_type<T>::type number, const __VA_ARGS__& matrix) { \\\n        return number/static_cast<const Math::RectangularMatrix<size, size, T>&>(matrix); \\\n    }                                                                       \\\n    template<std::size_t size, class T> inline __VA_ARGS__ operator*(const Vector<size, T>& vector, const RectangularMatrix<size, 1, T>& matrix) { \\\n        return Math::RectangularMatrix<1, size, T>(vector)*matrix;          \\\n    }\n\n#define MAGNUM_MATRIXn_OPERATOR_IMPLEMENTATION(size, Type)                  \\\n    template<class T> inline Type<T> operator*(typename std::common_type<T>::type number, const Type<T>& matrix) { \\\n        return number*static_cast<const Math::RectangularMatrix<size, size, T>&>(matrix); \\\n    }                                                                       \\\n    template<class T> inline Type<T> operator/(typename std::common_type<T>::type number, const Type<T>& matrix) { \\\n        return number/static_cast<const Math::RectangularMatrix<size, size, T>&>(matrix); \\\n    }                                                                       \\\n    template<class T> inline Type<T> operator*(const Vector<size, T>& vector, const RectangularMatrix<size, 1, T>& matrix) { \\\n        return Math::RectangularMatrix<1, size, T>(vector)*matrix;          \\\n    }\n\nnamespace Implementation {\n    template<std::size_t rows, std::size_t i, class T, std::size_t ...sequence> constexpr Vector<rows, T> diagonalMatrixColumn2(Implementation::Sequence<sequence...>, const T& number) {\n        return {(sequence == i ? number : T(0))...};\n    }\n    template<std::size_t rows, std::size_t i, class T> constexpr Vector<rows, T> diagonalMatrixColumn(const T& number) {\n        return diagonalMatrixColumn2<rows, i, T>(typename Implementation::GenerateSequence<rows>::Type(), number);\n    }\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> template<std::size_t ...sequence> constexpr RectangularMatrix<cols, rows, T>::RectangularMatrix(Implementation::Sequence<sequence...>, const Vector<DiagonalSize, T>& diagonal): _data{Implementation::diagonalMatrixColumn<rows, sequence>(sequence < DiagonalSize ? diagonal[sequence] : T{})...} {}\n\ntemplate<std::size_t cols, std::size_t rows, class T> inline Vector<cols, T> RectangularMatrix<cols, rows, T>::row(std::size_t row) const {\n    Vector<cols, T> out;\n\n    for(std::size_t i = 0; i != cols; ++i)\n        out[i] = _data[i]._data[row];\n\n    return out;\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> inline void RectangularMatrix<cols, rows, T>::setRow(std::size_t row, const Vector<cols, T>& data) {\n    for(std::size_t i = 0; i != cols; ++i)\n        _data[i]._data[row] = data._data[i];\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> inline RectangularMatrix<cols, rows, T> RectangularMatrix<cols, rows, T>::operator-() const {\n    RectangularMatrix<cols, rows, T> out;\n\n    for(std::size_t i = 0; i != cols; ++i)\n        out._data[i] = -_data[i];\n\n    return out;\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> template<std::size_t size> inline RectangularMatrix<size, rows, T> RectangularMatrix<cols, rows, T>::operator*(const RectangularMatrix<size, cols, T>& other) const {\n    RectangularMatrix<size, rows, T> out{ZeroInit};\n\n    for(std::size_t col = 0; col != size; ++col)\n        for(std::size_t row = 0; row != rows; ++row)\n            for(std::size_t pos = 0; pos != cols; ++pos)\n                out._data[col]._data[row] += _data[pos]._data[row]*other._data[col]._data[pos];\n\n    return out;\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> inline RectangularMatrix<rows, cols, T> RectangularMatrix<cols, rows, T>::transposed() const {\n    RectangularMatrix<rows, cols, T> out{NoInit};\n\n    for(std::size_t col = 0; col != cols; ++col)\n        for(std::size_t row = 0; row != rows; ++row)\n            out._data[row]._data[col] = _data[col]._data[row];\n\n    return out;\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> template<std::size_t ...sequence> constexpr auto RectangularMatrix<cols, rows, T>::diagonalInternal(Implementation::Sequence<sequence...>) const -> Vector<DiagonalSize, T> {\n    return {_data[sequence][sequence]...};\n}\n\nnamespace Implementation {\n\ntemplate<std::size_t cols, std::size_t rows, class T> struct StrictWeakOrdering<RectangularMatrix<cols, rows, T>> {\n    bool operator()(const RectangularMatrix<cols, rows, T>& a, const RectangularMatrix<cols, rows, T>& b) const {\n        StrictWeakOrdering<Vector<rows, T>> o;\n        for(std::size_t i = 0; i < cols; ++i) {\n            if(o(a[i], b[i]))\n                return true;\n            if(o(b[i], a[i]))\n                return false;\n        }\n\n        return false;\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Matrix_h\n#define Magnum_Math_Matrix_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<std::size_t, class> struct MatrixDeterminant;\n\n    template<std::size_t size, std::size_t col, std::size_t otherSize, class T, std::size_t ...row> constexpr Vector<size, T> valueOrIdentityVector(Sequence<row...>, const RectangularMatrix<otherSize, otherSize, T>& other) {\n        return {(col < otherSize && row < otherSize ? other[col][row] :\n            col == row ? T{1} : T{0})...};\n    }\n\n    template<std::size_t size, std::size_t col, std::size_t otherSize, class T> constexpr Vector<size, T> valueOrIdentityVector(const RectangularMatrix<otherSize, otherSize, T>& other) {\n        return valueOrIdentityVector<size, col>(typename Implementation::GenerateSequence<size>::Type(), other);\n    }\n}\n\ntemplate<std::size_t size, class T> class Matrix: public RectangularMatrix<size, size, T> {\n    public:\n        enum: std::size_t {\n            Size = size\n        };\n\n        constexpr /*implicit*/ Matrix() noexcept: RectangularMatrix<size, size, T>{typename Implementation::GenerateSequence<size>::Type(), Vector<size, T>(T(1))} {}\n\n        constexpr explicit Matrix(IdentityInitT, T value = T(1)) noexcept: RectangularMatrix<size, size, T>{typename Implementation::GenerateSequence<size>::Type(), Vector<size, T>(value)} {}\n\n        constexpr explicit Matrix(ZeroInitT) noexcept: RectangularMatrix<size, size, T>{ZeroInit} {}\n\n        constexpr explicit Matrix(NoInitT) noexcept: RectangularMatrix<size, size, T>{NoInit} {}\n\n        template<class ...U> constexpr /*implicit*/ Matrix(const Vector<size, T>& first, const U&... next) noexcept: RectangularMatrix<size, size, T>(first, next...) {}\n\n        constexpr explicit Matrix(T value) noexcept: RectangularMatrix<size, size, T>{typename Implementation::GenerateSequence<size>::Type(), value} {}\n\n        template<class U> constexpr explicit Matrix(const RectangularMatrix<size, size, U>& other) noexcept: RectangularMatrix<size, size, T>(other) {}\n\n        template<class U, class V = decltype(Implementation::RectangularMatrixConverter<size, size, T, U>::from(std::declval<U>()))> constexpr explicit Matrix(const U& other): RectangularMatrix<size, size, T>(Implementation::RectangularMatrixConverter<size, size, T, U>::from(other)) {}\n\n        template<std::size_t otherSize> constexpr explicit Matrix(const RectangularMatrix<otherSize, otherSize, T>& other) noexcept: Matrix<size, T>{typename Implementation::GenerateSequence<size>::Type(), other} {}\n\n        constexpr /*implicit*/ Matrix(const RectangularMatrix<size, size, T>& other) noexcept: RectangularMatrix<size, size, T>(other) {}\n\n        bool isOrthogonal() const;\n\n        T trace() const { return RectangularMatrix<size, size, T>::diagonal().sum(); }\n\n        Matrix<size-1, T> ij(std::size_t skipCol, std::size_t skipRow) const;\n\n        T cofactor(std::size_t col, std::size_t row) const;\n\n        Matrix<size, T> comatrix() const;\n\n        Matrix<size, T> adjugate() const;\n\n        T determinant() const { return Implementation::MatrixDeterminant<size, T>()(*this); }\n\n        Matrix<size, T> inverted() const;\n\n        Matrix<size, T> invertedOrthogonal() const {\n            CORRADE_ASSERT(isOrthogonal(),\n                \"Math::Matrix::invertedOrthogonal(): the matrix is not orthogonal:\" << Corrade::Utility::Debug::Debug::newline << *this, {});\n            return RectangularMatrix<size, size, T>::transposed();\n        }\n\n        Matrix<size, T> operator*(const Matrix<size, T>& other) const {\n            return RectangularMatrix<size, size, T>::operator*(other);\n        }\n        template<std::size_t otherCols> RectangularMatrix<otherCols, size, T> operator*(const RectangularMatrix<otherCols, size, T>& other) const {\n            return RectangularMatrix<size, size, T>::operator*(other);\n        }\n        Vector<size, T> operator*(const Vector<size, T>& other) const {\n            return RectangularMatrix<size, size, T>::operator*(other);\n        }\n        Matrix<size, T> transposed() const {\n            return RectangularMatrix<size, size, T>::transposed();\n        }\n        MAGNUM_RECTANGULARMATRIX_SUBCLASS_IMPLEMENTATION(size, size, Matrix<size, T>)\n\n    private:\n        friend struct Implementation::MatrixDeterminant<size, T>;\n\n        template<std::size_t otherSize, std::size_t ...col> constexpr explicit Matrix(Implementation::Sequence<col...>, const RectangularMatrix<otherSize, otherSize, T>& other) noexcept: RectangularMatrix<size, size, T>{Implementation::valueOrIdentityVector<size, col>(other)...} {}\n};\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix2x2 = Matrix<2, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix3x3 = Matrix<3, T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Matrix4x4 = Matrix<4, T>;\n#endif\n\nMAGNUM_MATRIX_OPERATOR_IMPLEMENTATION(Matrix<size, T>)\n\n#define MAGNUM_MATRIX_SUBCLASS_IMPLEMENTATION(size, Type, VectorType)       \\\n    VectorType<T>& operator[](std::size_t col) {                            \\\n        return static_cast<VectorType<T>&>(Matrix<size, T>::operator[](col)); \\\n    }                                                                       \\\n    constexpr const VectorType<T> operator[](std::size_t col) const {       \\\n        return VectorType<T>(Matrix<size, T>::operator[](col));             \\\n    }                                                                       \\\n    VectorType<T> row(std::size_t row) const {                              \\\n        return VectorType<T>(Matrix<size, T>::row(row));                    \\\n    }                                                                       \\\n                                                                            \\\n    Type<T> operator*(const Matrix<size, T>& other) const {                 \\\n        return Matrix<size, T>::operator*(other);                           \\\n    }                                                                       \\\n    template<std::size_t otherCols> RectangularMatrix<otherCols, size, T> operator*(const RectangularMatrix<otherCols, size, T>& other) const { \\\n        return Matrix<size, T>::operator*(other);                           \\\n    }                                                                       \\\n    VectorType<T> operator*(const Vector<size, T>& other) const {           \\\n        return Matrix<size, T>::operator*(other);                           \\\n    }                                                                       \\\n                                                                            \\\n    Type<T> transposed() const { return Matrix<size, T>::transposed(); }    \\\n    constexpr VectorType<T> diagonal() const { return Matrix<size, T>::diagonal(); } \\\n    Type<T> inverted() const { return Matrix<size, T>::inverted(); }        \\\n    Type<T> invertedOrthogonal() const {                                    \\\n        return Matrix<size, T>::invertedOrthogonal();                       \\\n    }\n\nnamespace Implementation {\n\ntemplate<std::size_t size, class T> struct MatrixDeterminant {\n    T operator()(const Matrix<size, T>& m) {\n        T out(0);\n\n        for(std::size_t col = 0; col != size; ++col)\n            out += m._data[col]._data[0]*m.cofactor(col, 0);\n\n        return out;\n    }\n\n    T operator()(const Matrix<size + 1, T>& m, const std::size_t skipCol, const std::size_t skipRow) {\n        return m.ij(skipCol, skipRow).determinant();\n    }\n};\n\ntemplate<class T> struct MatrixDeterminant<3, T> {\n    constexpr T operator()(const Matrix<3, T>& m) const {\n        return m._data[0]._data[0]*((m._data[1]._data[1]*m._data[2]._data[2]) - (m._data[2]._data[1]*m._data[1]._data[2])) -\n            m._data[0]._data[1]*(m._data[1]._data[0]*m._data[2]._data[2] - m._data[2]._data[0]*m._data[1]._data[2]) +\n            m._data[0]._data[2]*(m._data[1]._data[0]*m._data[2]._data[1] - m._data[2]._data[0]*m._data[1]._data[1]);\n    }\n\n    constexpr T operator()(const Matrix<4, T>& m, const std::size_t skipCol, const std::size_t skipRow) const {\n        #define _col(i) _data[i + (i >= skipCol)]\n        #define _row(i) _data[i + (i >= skipRow)]\n        return\n            m._col(0)._row(0)*((m._col(1)._row(1)*m._col(2)._row(2)) - (m._col(2)._row(1)*m._col(1)._row(2))) -\n            m._col(0)._row(1)*(m._col(1)._row(0)*m._col(2)._row(2) - m._col(2)._row(0)*m._col(1)._row(2)) +\n            m._col(0)._row(2)*(m._col(1)._row(0)*m._col(2)._row(1) - m._col(2)._row(0)*m._col(1)._row(1));\n        #undef _col\n        #undef _row\n    }\n};\n\ntemplate<class T> struct MatrixDeterminant<2, T> {\n    constexpr T operator()(const Matrix<2, T>& m) const {\n        return m._data[0]._data[0]*m._data[1]._data[1] - m._data[1]._data[0]*m._data[0]._data[1];\n    }\n\n    constexpr T operator()(const Matrix<3, T>& m, const std::size_t skipCol, const std::size_t skipRow) const {\n        #define _col(i) _data[i + (i >= skipCol)]\n        #define _row(i) _data[i + (i >= skipRow)]\n        return m._col(0)._row(0)*m._col(1)._row(1) - m._col(1)._row(0)*m._col(0)._row(1);\n        #undef _col\n        #undef _row\n    }\n};\n\ntemplate<class T> struct MatrixDeterminant<1, T> {\n    constexpr T operator()(const Matrix<1, T>& m) const {\n        return m._data[0]._data[0];\n    }\n\n    constexpr T operator()(const Matrix<2, T>& m, const std::size_t skipCol, const std::size_t skipRow) const {\n        return m._data[0 + (0 >= skipCol)]._data[0 + (0 >= skipRow)];\n    }\n};\n\ntemplate<std::size_t size, class T> struct StrictWeakOrdering<Matrix<size, T>>: StrictWeakOrdering<RectangularMatrix<size, size, T>> {};\n\n}\n\ntemplate<std::size_t size, class T> bool Matrix<size, T>::isOrthogonal() const {\n\n    for(std::size_t i = 0; i != size; ++i)\n        if(!RectangularMatrix<size, size, T>::_data[i].isNormalized()) return false;\n\n    for(std::size_t i = 0; i != size-1; ++i)\n        for(std::size_t j = i+1; j != size; ++j)\n            if(dot(RectangularMatrix<size, size, T>::_data[i], RectangularMatrix<size, size, T>::_data[j]) > TypeTraits<T>::epsilon())\n                return false;\n\n    return true;\n}\n\ntemplate<std::size_t size, class T> Matrix<size-1, T> Matrix<size, T>::ij(const std::size_t skipCol, const std::size_t skipRow) const {\n    Matrix<size-1, T> out{NoInit};\n\n    for(std::size_t col = 0; col != size-1; ++col)\n        for(std::size_t row = 0; row != size-1; ++row)\n            out._data[col]._data[row] = RectangularMatrix<size, size, T>::\n                _data[col + (col >= skipCol)]\n               ._data[row + (row >= skipRow)];\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> T Matrix<size, T>::cofactor(std::size_t col, std::size_t row) const {\n    return (((row+col) & 1) ? -1 : 1)*Implementation::MatrixDeterminant<size - 1, T>()(*this, col, row);\n}\n\ntemplate<std::size_t size, class T> Matrix<size, T> Matrix<size, T>::comatrix() const {\n    Matrix<size, T> out{NoInit};\n\n    for(std::size_t col = 0; col != size; ++col)\n        for(std::size_t row = 0; row != size; ++row)\n            out._data[col]._data[row] = cofactor(col, row);\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> Matrix<size, T> Matrix<size, T>::adjugate() const {\n    Matrix<size, T> out{NoInit};\n\n    for(std::size_t col = 0; col != size; ++col)\n        for(std::size_t row = 0; row != size; ++row)\n            out._data[col]._data[row] = cofactor(row, col);\n\n    return out;\n}\n\ntemplate<std::size_t size, class T> Matrix<size, T> Matrix<size, T>::inverted() const {\n    return adjugate()/determinant();\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Functions_h\n#define Magnum_Math_Functions_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<UnsignedInt exponent> struct Pow {\n        Pow() = delete;\n\n        template<class T> constexpr static T pow(T base) {\n            return base*Pow<exponent-1>::pow(base);\n        }\n    };\n    template<> struct Pow<0> {\n        Pow() = delete;\n\n        template<class T> constexpr static T pow(T) { return T(1); }\n    };\n\n    template<class> struct IsBoolVectorOrScalar: std::false_type {};\n    template<> struct IsBoolVectorOrScalar<bool>: std::true_type {};\n    template<std::size_t size> struct IsBoolVectorOrScalar<BoolVector<size>>: std::true_type {};\n}\n\ntemplate<class Integral> inline std::pair<Integral, Integral> div(Integral x, Integral y) {\n    static_assert(IsIntegral<Integral>::value && IsScalar<Integral>::value,\n        \"scalar integral type expected\");\n    const auto result = std::div(x, y);\n    return {result.quot, result.rem};\n}\n\ntemplate<class T> inline T sin(Unit<Rad, T> angle) { return std::sin(T(angle)); }\ntemplate<class T> inline T sin(Unit<Deg, T> angle) { return sin(Rad<T>(angle)); }\n\ntemplate<class T> inline T cos(Unit<Rad, T> angle) { return std::cos(T(angle)); }\ntemplate<class T> inline T cos(Unit<Deg, T> angle) { return cos(Rad<T>(angle)); }\n\n#if defined(__GNUC__) && !defined(__clang__)\nnamespace Implementation {\n    inline void sincos(Float rad, Float& sin, Float& cos) {\n        __builtin_sincosf(rad, &sin, &cos);\n    }\n    inline void sincos(Double rad, Double& sin, Double& cos) {\n        __builtin_sincos(rad, &sin, &cos);\n    }\n    inline void sincos(long double rad, long double& sin, long double& cos) {\n        __builtin_sincosl(rad, &sin, &cos);\n    }\n}\n#endif\n\ntemplate<class T> inline std::pair<T, T> sincos(Unit<Rad, T> angle) {\n    #if defined(__GNUC__) && !defined(__clang__)\n    std::pair<T, T> out;\n    Implementation::sincos(T(angle), out.first, out.second);\n    return out;\n    #else\n    return {std::sin(T(angle)), std::cos(T(angle))};\n    #endif\n}\ntemplate<class T> inline std::pair<T, T> sincos(Unit<Deg, T> angle) { return sincos(Rad<T>(angle)); }\n\ntemplate<class T> inline T tan(Unit<Rad, T> angle) { return std::tan(T(angle)); }\ntemplate<class T> inline T tan(Unit<Deg, T> angle) { return tan(Rad<T>(angle)); }\n\ntemplate<class T> inline Rad<T> asin(T value) { return Rad<T>(std::asin(value)); }\n\ntemplate<class T> inline Rad<T> acos(T value) { return Rad<T>(std::acos(value)); }\n\ntemplate<class T> inline Rad<T> atan(T value) { return Rad<T>(std::atan(value)); }\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, bool>::type isInf(T value) {\n    return std::isinf(UnderlyingTypeOf<T>(value));\n}\n\ntemplate<std::size_t size, class T> inline BoolVector<size> isInf(const Vector<size, T>& value) {\n    BoolVector<size> out;\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, Math::isInf(value[i]));\n    return out;\n}\n\ntemplate<class T> typename std::enable_if<IsScalar<T>::value, bool>::type isNan(T value);\n\ntemplate<std::size_t size, class T> inline BoolVector<size> isNan(const Vector<size, T>& value) {\n    BoolVector<size> out;\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, Math::isNan(value[i]));\n    return out;\n}\n\ntemplate<class T> constexpr typename std::enable_if<IsScalar<T>::value, T>::type min(T value, T min);\n\ntemplate<std::size_t size, class T> inline Vector<size, T> min(const Vector<size, T>& value, const Vector<size, T>& min) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::min(value[i], min[i]);\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> min(const Vector<size, T>& value, T min) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::min(value[i], min);\n    return out;\n}\n\ntemplate<class T> constexpr typename std::enable_if<IsScalar<T>::value, T>::type max(T a, T b);\n\ntemplate<std::size_t size, class T> Vector<size, T> max(const Vector<size, T>& value, const Vector<size, T>& max) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::max(value[i], max[i]);\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> max(const Vector<size, T>& value, T max) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::max(value[i], max);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, std::pair<T, T>>::type minmax(T a, T b) {\n    return a < b ? std::make_pair(a, b) : std::make_pair(b, a);\n}\n\ntemplate<std::size_t size, class T> inline std::pair<Vector<size, T>, Vector<size, T>> minmax(const Vector<size, T>& a, const Vector<size, T>& b) {\n    using std::swap;\n    std::pair<Vector<size, T>, Vector<size, T>> out{a, b};\n    for(std::size_t i = 0; i != size; ++i)\n        if(out.first[i] > out.second[i]) swap(out.first[i], out.second[i]);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type clamp(T value, T min, T max) {\n    return Math::min(Math::max(value, min), max);\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> clamp(const Vector<size, T>& value, const Vector<size, T>& min, const Vector<size, T>& max) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::clamp(value[i], min[i], max[i]);\n    return out;\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> clamp(const Vector<size, T>& value, T min, T max) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::clamp(value[i], min, max);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type sign(const T& scalar) {\n    if(scalar > T(0)) return T(1);\n    if(scalar < T(0)) return T(-1);\n    return T(0);\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> sign(const Vector<size, T>& a) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::sign(a[i]);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type abs(T a) {\n    return T(std::abs(UnderlyingTypeOf<T>(a)));\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> abs(const Vector<size, T>& a) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::abs(a[i]);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type floor(T a) {\n    return T(std::floor(UnderlyingTypeOf<T>(a)));\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> floor(const Vector<size, T>& a) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::floor(a[i]);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type round(T a) {\n    return T(std::round(UnderlyingTypeOf<T>(a)));\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> round(const Vector<size, T>& a) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::round(a[i]);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type ceil(T a) {\n    return T(std::ceil(UnderlyingTypeOf<T>(a)));\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> ceil(const Vector<size, T>& a) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::ceil(a[i]);\n    return out;\n}\n\ntemplate<class T, class U> inline\n    typename std::enable_if<(IsVector<T>::value || IsScalar<T>::value) && !Implementation::IsBoolVectorOrScalar<U>::value, T>::type\nlerp(const T& a, const T& b, U t) {\n    return Implementation::lerp(a, b, t);\n}\n\ntemplate<class T> inline T lerp(const T& a, const T& b, bool t) {\n    return t ? b : a;\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> lerp(const Vector<size, T>& a, const Vector<size, T>& b, const BoolVector<size>& t) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = t[i] ? b[i] : a[i];\n    return out;\n}\n\ntemplate<std::size_t size> inline BoolVector<size> lerp(const BoolVector<size>& a, const BoolVector<size>& b, const BoolVector<size>& t) {\n    BoolVector<size> out;\n    for(std::size_t i = 0; i != size; ++i)\n        out.set(i, t[i] ? b[i] : a[i]);\n    return out;\n}\n\ntemplate<class T> inline UnderlyingTypeOf<typename std::enable_if<IsScalar<T>::value, T>::type> lerpInverted(T a, T b, T lerp) {\n    return (lerp - a)/(b - a);\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, UnderlyingTypeOf<T>> lerpInverted(const Vector<size, T>& a, const Vector<size, T>& b, const Vector<size, T>& lerp) {\n    return (lerp - a)/(b - a);\n}\n\ntemplate<class T, class U> constexpr T select(const T& a, const T& b, U t) {\n    return lerp(a, b, t >= U(1));\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type fma(T a, T b, T c) {\n    static_assert(IsUnitless<T>::value, \"expecting an unitless type\");\n    #ifndef CORRADE_TARGET_EMSCRIPTEN\n    return std::fma(a, b, c);\n    #else\n    return a*b + c;\n    #endif\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> fma(const Vector<size, T>& a, const Vector<size, T>& b, const Vector<size, T>& c) {\n    static_assert(IsUnitless<T>::value, \"expecting an unitless type\");\n    return a*b + c;\n}\n\nUnsignedInt MAGNUM_EXPORT log(UnsignedInt base, UnsignedInt number);\n\nUnsignedInt MAGNUM_EXPORT log2(UnsignedInt number);\n\ntemplate<class T> inline T log(T number) { return std::log(number); }\n\ntemplate<class T> inline T exp(T exponent) { return std::exp(exponent); }\n\ntemplate<UnsignedInt exponent, class T> constexpr typename std::enable_if<IsScalar<T>::value, T>::type pow(T base) {\n    static_assert(IsUnitless<T>::value, \"expected an unitless type\");\n    return Implementation::Pow<exponent>::pow(base);\n}\n\ntemplate<UnsignedInt exponent, std::size_t size, class T> inline Vector<size, T> pow(const Vector<size, T>& base) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::pow<exponent>(base[i]);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type pow(T base, T exponent) {\n    static_assert(IsUnitless<T>::value, \"expected an unitless type\");\n    return std::pow(base, exponent);\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> pow(const Vector<size, T>& base, T exponent) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::pow(base[i], exponent);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type sqrt(T a) {\n    static_assert(IsUnitless<T>::value, \"expecting an unitless type\");\n    return std::sqrt(a);\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> sqrt(const Vector<size, T>& a) {\n    Vector<size, T> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = Math::sqrt(a[i]);\n    return out;\n}\n\ntemplate<class T> inline typename std::enable_if<IsScalar<T>::value, T>::type sqrtInverted(T a) {\n    static_assert(IsUnitless<T>::value, \"expecting an unitless type\");\n    return T(1)/std::sqrt(a);\n}\n\ntemplate<std::size_t size, class T> inline Vector<size, T> sqrtInverted(const Vector<size, T>& a) {\n    return Vector<size, T>(T(1))/Math::sqrt(a);\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Packing_h\n#define Magnum_Math_Packing_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n\ntemplate<class T, UnsignedInt bits = sizeof(T)*8> inline constexpr T bitMax() {\n    return T(typename std::make_unsigned<T>::type(~T{}) >> (sizeof(T)*8 - (std::is_signed<T>::value ? bits - 1 : bits)));\n}\n\n}\n\ntemplate<class FloatingPoint, class Integral, UnsignedInt bits = sizeof(Integral)*8> inline typename std::enable_if<IsScalar<Integral>::value && std::is_unsigned<Integral>::value, FloatingPoint>::type unpack(const Integral& value) {\n    static_assert(IsFloatingPoint<FloatingPoint>::value && IsIntegral<Integral>::value,\n        \"unpacking must be done from integral to floating-point type\");\n    static_assert(bits <= sizeof(Integral)*8,\n        \"bit count larger than size of the integral type\");\n    return FloatingPoint(value/UnderlyingTypeOf<FloatingPoint>(Implementation::bitMax<Integral, bits>()));\n}\ntemplate<class FloatingPoint, class Integral, UnsignedInt bits = sizeof(Integral)*8> inline typename std::enable_if<IsScalar<Integral>::value && std::is_signed<Integral>::value, FloatingPoint>::type unpack(const Integral& value) {\n    static_assert(IsFloatingPoint<FloatingPoint>::value && IsIntegral<Integral>::value,\n        \"unpacking must be done from integral to floating-point type\");\n    static_assert(bits <= sizeof(Integral)*8,\n        \"bit count larger than size of the integral type\");\n    return FloatingPoint(Math::max(value/UnderlyingTypeOf<FloatingPoint>(Implementation::bitMax<Integral, bits>()), UnderlyingTypeOf<FloatingPoint>(-1.0)));\n}\ntemplate<class FloatingPoint, std::size_t size, class Integral, UnsignedInt bits = sizeof(Integral)*8> FloatingPoint unpack(const Vector<size, Integral>& value) {\n    static_assert(FloatingPoint::Size == size,\n        \"return vector type should have the same size as input vector type\");\n    FloatingPoint out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = unpack<typename FloatingPoint::Type, Integral, bits>(value[i]);\n    return out;\n}\n\ntemplate<class FloatingPoint, UnsignedInt bits, class Integral> inline typename std::enable_if<IsScalar<Integral>::value, FloatingPoint>::type unpack(const Integral& value) {\n    return unpack<FloatingPoint, Integral, bits>(value);\n}\ntemplate<class FloatingPoint, UnsignedInt bits, std::size_t size, class Integral> inline FloatingPoint unpack(const Vector<size, Integral>& value) {\n    return unpack<FloatingPoint, size, Integral, bits>(value);\n}\n\ntemplate<class Integral, class FloatingPoint, UnsignedInt bits = sizeof(Integral)*8> inline typename std::enable_if<IsScalar<FloatingPoint>::value, Integral>::type pack(FloatingPoint value) {\n    static_assert(IsFloatingPoint<FloatingPoint>::value && IsIntegral<Integral>::value,\n        \"packing must be done from floating-point to integral type\");\n    static_assert(bits <= sizeof(Integral)*8,\n        \"bit count larger than size of the integral type\");\n    return Integral(round(UnderlyingTypeOf<FloatingPoint>(value)*Implementation::bitMax<Integral, bits>()));\n}\ntemplate<class Integral, std::size_t size, class FloatingPoint, UnsignedInt bits = sizeof(typename Integral::Type)*8> Integral pack(const Vector<size, FloatingPoint>& value) {\n    static_assert(Integral::Size == size,\n        \"return vector type should have the same size as input vector type\");\n    Integral out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = pack<typename Integral::Type, FloatingPoint, bits>(value[i]);\n    return out;\n}\n\ntemplate<class Integral, UnsignedInt bits, class FloatingPoint> inline typename std::enable_if<IsScalar<FloatingPoint>::value, Integral>::type pack(FloatingPoint value) {\n    return pack<Integral, FloatingPoint, bits>(value);\n}\ntemplate<class Integral, UnsignedInt bits, std::size_t size, class FloatingPoint> inline Integral pack(const Vector<size, FloatingPoint>& value) {\n    return pack<Integral, size, FloatingPoint, bits>(value);\n}\n\nMAGNUM_EXPORT UnsignedShort packHalf(Float value);\n\ntemplate<std::size_t size> Vector<size, UnsignedShort> packHalf(const Vector<size, Float>& value) {\n    Vector<size, UnsignedShort> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = packHalf(value[i]);\n    return out;\n}\n\nMAGNUM_EXPORT Float unpackHalf(UnsignedShort value);\n\ntemplate<std::size_t size> Vector<size, Float> unpackHalf(const Vector<size, UnsignedShort>& value) {\n    Vector<size, Float> out{NoInit};\n    for(std::size_t i = 0; i != size; ++i)\n        out[i] = unpackHalf(value[i]);\n    return out;\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Vector2_h\n#define Magnum_Math_Vector2_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> inline T cross(const Vector2<T>& a, const Vector2<T>& b) {\n    return dot(a.perpendicular(), b);\n}\n\ntemplate<class T> class Vector2: public Vector<2, T> {\n    public:\n        constexpr static Vector2<T> xAxis(T length = T(1)) { return {length, T(0)}; }\n\n        constexpr static Vector2<T> yAxis(T length = T(1)) { return {T(0), length}; }\n\n        constexpr static Vector2<T> xScale(T scale) { return {scale, T(1)}; }\n\n        constexpr static Vector2<T> yScale(T scale) { return {T(1), scale}; }\n\n        constexpr /*implicit*/ Vector2() noexcept: Vector<2, T>{ZeroInit} {}\n\n        constexpr explicit Vector2(ZeroInitT) noexcept: Vector<2, T>{ZeroInit} {}\n\n        explicit Vector2(NoInitT) noexcept: Vector<2, T>{NoInit} {}\n\n        constexpr explicit Vector2(T value) noexcept: Vector<2, T>(value) {}\n\n        constexpr /*implicit*/ Vector2(T x, T y) noexcept: Vector<2, T>(x, y) {}\n\n        template<class U> constexpr explicit Vector2(const Vector<2, U>& other) noexcept: Vector<2, T>(other) {}\n\n        template<class U, class V =\n            #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Causes ICE */\n            decltype(Implementation::VectorConverter<2, T, U>::from(std::declval<U>()))\n            #else\n            decltype(Implementation::VectorConverter<2, T, U>())\n            #endif\n            >\n        constexpr explicit Vector2(const U& other): Vector<2, T>(Implementation::VectorConverter<2, T, U>::from(other)) {}\n\n        constexpr /*implicit*/ Vector2(const Vector<2, T>& other) noexcept: Vector<2, T>(other) {}\n\n        T& x() { return Vector<2, T>::_data[0]; }\n        constexpr T x() const { return Vector<2, T>::_data[0]; }\n        T& y() { return Vector<2, T>::_data[1]; }\n        constexpr T y() const { return Vector<2, T>::_data[1]; }\n\n        template<class U = T> typename std::enable_if<std::is_signed<U>::value, Vector2<T>>::type\n        perpendicular() const { return {-y(), x()}; }\n\n        template<class U = T> typename std::enable_if<std::is_floating_point<U>::value, T>::type\n        aspectRatio() const { return x()/y(); }\n\n        MAGNUM_VECTOR_SUBCLASS_IMPLEMENTATION(2, Vector2)\n};\n\nMAGNUM_VECTORn_OPERATOR_IMPLEMENTATION(2, Vector2)\n\nnamespace Implementation {\n    template<std::size_t, class> struct TypeForSize;\n    template<class T> struct TypeForSize<2, T> { typedef Math::Vector2<typename T::Type> Type; };\n\n    template<class T> struct StrictWeakOrdering<Vector2<T>>: StrictWeakOrdering<Vector<2, T>> {};\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Swizzle_h\n#define Magnum_Math_Swizzle_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<std::size_t size, std::size_t position> struct GatherComponentAt {\n        static_assert(size > position, \"numeric swizzle parameter out of range of gather vector, use either xyzw/rgba/0/1 letters or small enough numbers\");\n\n        template<class T> constexpr static T value(const Math::Vector<size, T>& vector) {\n            return vector._data[position];\n        }\n    };\n\n    template<std::size_t size, char component> struct GatherComponent: GatherComponentAt<size, component> {};\n    template<std::size_t size> struct GatherComponent<size, 'x'>: public GatherComponentAt<size, 0> {};\n    template<std::size_t size> struct GatherComponent<size, 'y'>: public GatherComponentAt<size, 1> {};\n    template<std::size_t size> struct GatherComponent<size, 'z'>: public GatherComponentAt<size, 2> {};\n    template<std::size_t size> struct GatherComponent<size, 'w'>: public GatherComponentAt<size, 3> {};\n    template<std::size_t size> struct GatherComponent<size, 'r'>: public GatherComponentAt<size, 0> {};\n    template<std::size_t size> struct GatherComponent<size, 'g'>: public GatherComponentAt<size, 1> {};\n    template<std::size_t size> struct GatherComponent<size, 'b'>: public GatherComponentAt<size, 2> {};\n    template<std::size_t size> struct GatherComponent<size, 'a'>: public GatherComponentAt<size, 3> {};\n    template<std::size_t size> struct GatherComponent<size, '0'> {\n        template<class T> constexpr static T value(const Math::Vector<size, T>&) { return T(0); }\n    };\n    template<std::size_t size> struct GatherComponent<size, '1'> {\n        template<class T> constexpr static T value(const Math::Vector<size, T>&) { return T(1); }\n    };\n\n    template<std::size_t size, class T> struct TypeForSize {\n        typedef Math::Vector<size, typename T::Type> Type;\n    };\n\n    template<std::size_t size, std::size_t i, bool = true> struct ScatterComponentOr {\n        template<class T> constexpr static T value(const Math::Vector<size, T>&, const T& value) {\n            return value;\n        }\n    };\n    template<std::size_t size, std::size_t i> struct ScatterComponentOr<size, i, false> {\n        template<class T> constexpr static T value(const Math::Vector<size, T>& vector, const T&) {\n            return vector._data[i];\n        }\n    };\n    template<std::size_t size, char component, std::size_t i> struct ScatterComponent: ScatterComponentOr<size, i, component == i> {\n        static_assert(component == 'x' || component == 'r' ||\n                    ((component == 'y' || component == 'g') && size > 1) ||\n                    ((component == 'z' || component == 'b') && size > 2) ||\n                    ((component == 'w' || component == 'a') && size > 3) ||\n                     std::size_t(component) < size,\n            \"swizzle parameter out of range of scatter vector, use either xyzw/rgba letters or small enough numbers\");\n    };\n    template<std::size_t size> struct ScatterComponent<size, 'x', 0>: ScatterComponentOr<size, 0> {};\n    template<std::size_t size> struct ScatterComponent<size, 'y', 1>: ScatterComponentOr<size, 1> {};\n    template<std::size_t size> struct ScatterComponent<size, 'z', 2>: ScatterComponentOr<size, 2> {};\n    template<std::size_t size> struct ScatterComponent<size, 'w', 3>: ScatterComponentOr<size, 3> {};\n    template<std::size_t size> struct ScatterComponent<size, 'r', 0>: ScatterComponentOr<size, 0> {};\n    template<std::size_t size> struct ScatterComponent<size, 'g', 1>: ScatterComponentOr<size, 1> {};\n    template<std::size_t size> struct ScatterComponent<size, 'b', 2>: ScatterComponentOr<size, 2> {};\n    template<std::size_t size> struct ScatterComponent<size, 'a', 3>: ScatterComponentOr<size, 3> {};\n\n    template<class T, char component, std::size_t ...sequence> constexpr T scatterComponentOr(const T& vector, const typename T::Type& value, Sequence<sequence...>) {\n        return {ScatterComponent<T::Size, component, sequence>::value(vector, value)...};\n    }\n    template<class T, std::size_t valueSize> constexpr T scatterRecursive(const T& vector, const Vector<valueSize, typename T::Type>&, std::size_t) {\n        return vector;\n    }\n    template<class T, std::size_t valueSize, char component, char ...next> constexpr T scatterRecursive(const T& vector, const Vector<valueSize, typename T::Type>& values, std::size_t valueIndex) {\n        return scatterRecursive<T, valueSize, next...>(\n            scatterComponentOr<T, component>(vector, values._data[valueIndex], typename GenerateSequence<T::Size>::Type{}),\n            values, valueIndex + 1);\n    }\n}\n\ntemplate<char ...components, class T> constexpr typename Implementation::TypeForSize<sizeof...(components), T>::Type gather(const T& vector) {\n    return {Implementation::GatherComponent<T::Size, components>::value(vector)...};\n}\n\ntemplate<char ...components, class T> constexpr T scatter(const T& vector, const typename std::common_type<Vector<sizeof...(components), typename T::Type>>::type& values)\n{\n    return Implementation::scatterRecursive<T, sizeof...(components), components...>(vector, values, 0);\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Vector3_h\n#define Magnum_Math_Vector3_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> inline Vector3<T> cross(const Vector3<T>& a, const Vector3<T>& b) {\n    return gather<'y', 'z', 'x'>(a*gather<'y', 'z', 'x'>(b) -\n                                 b*gather<'y', 'z', 'x'>(a));\n}\n\ntemplate<class T> class Vector3: public Vector<3, T> {\n    public:\n        constexpr static Vector3<T> xAxis(T length = T(1)) { return {length, T(0), T(0)}; }\n\n        constexpr static Vector3<T> yAxis(T length = T(1)) { return {T(0), length, T(0)}; }\n\n        constexpr static Vector3<T> zAxis(T length = T(1)) { return {T(0), T(0), length}; }\n\n        constexpr static Vector3<T> xScale(T scale) { return {scale, T(1), T(1)}; }\n\n        constexpr static Vector3<T> yScale(T scale) { return {T(1), scale, T(1)}; }\n\n        constexpr static Vector3<T> zScale(T scale) { return {T(1), T(1), scale}; }\n\n        constexpr /*implicit*/ Vector3() noexcept: Vector<3, T>{ZeroInit} {}\n\n        constexpr explicit Vector3(ZeroInitT) noexcept: Vector<3, T>{ZeroInit} {}\n\n        explicit Vector3(NoInitT) noexcept: Vector<3, T>{NoInit} {}\n\n        constexpr explicit Vector3(T value) noexcept: Vector<3, T>(value) {}\n\n        constexpr /*implicit*/ Vector3(T x, T y, T z) noexcept: Vector<3, T>(x, y, z) {}\n\n        constexpr /*implicit*/ Vector3(const Vector2<T>& xy, T z) noexcept: Vector<3, T>(xy[0], xy[1], z) {}\n\n        template<class U> constexpr explicit Vector3(const Vector<3, U>& other) noexcept: Vector<3, T>(other) {}\n\n        template<class U, class V =\n            #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Causes ICE */\n            decltype(Implementation::VectorConverter<3, T, U>::from(std::declval<U>()))\n            #else\n            decltype(Implementation::VectorConverter<3, T, U>())\n            #endif\n            >\n        constexpr explicit Vector3(const U& other): Vector<3, T>(Implementation::VectorConverter<3, T, U>::from(other)) {}\n\n        constexpr /*implicit*/ Vector3(const Vector<3, T>& other) noexcept: Vector<3, T>(other) {}\n\n        T& x() { return Vector<3, T>::_data[0]; }\n        constexpr T x() const { return Vector<3, T>::_data[0]; }\n\n        T& y() { return Vector<3, T>::_data[1]; }\n        constexpr T y() const { return Vector<3, T>::_data[1]; }\n\n        T& z() { return Vector<3, T>::_data[2]; }\n        constexpr T z() const { return Vector<3, T>::_data[2]; }\n\n        T& r() { return Vector<3, T>::_data[0]; }\n        constexpr T r() const { return Vector<3, T>::_data[0]; }\n\n        T& g() { return Vector<3, T>::_data[1]; }\n        constexpr T g() const { return Vector<3, T>::_data[1]; }\n\n        T& b() { return Vector<3, T>::_data[2]; }\n        constexpr T b() const { return Vector<3, T>::_data[2]; }\n\n        Vector2<T>& xy() { return Vector2<T>::from(Vector<3, T>::data()); }\n        constexpr const Vector2<T> xy() const {\n            return {Vector<3, T>::_data[0], Vector<3, T>::_data[1]};\n        }\n\n        constexpr const Vector2<T> xz() const {\n            return { Vector<3, T>::_data[0], Vector<3, T>::_data[2] };\n        }\n\n        MAGNUM_VECTOR_SUBCLASS_IMPLEMENTATION(3, Vector3)\n};\n\nMAGNUM_VECTORn_OPERATOR_IMPLEMENTATION(3, Vector3)\n\nnamespace Implementation {\n    template<class T> struct TypeForSize<3, T> { typedef Math::Vector3<typename T::Type> Type; };\n\n    template<class T> struct StrictWeakOrdering<Vector3<T>>: StrictWeakOrdering<Vector<3, T>> {};\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Vector4_h\n#define Magnum_Math_Vector4_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> class Vector4: public Vector<4, T> {\n    public:\n        template<std::size_t otherSize> constexpr static Vector4<T> pad(const Vector<otherSize, T>& a, T xyz, T w) {\n            return {0 < otherSize ? a[0] : xyz,\n                    1 < otherSize ? a[1] : xyz,\n                    2 < otherSize ? a[2] : xyz,\n                    3 < otherSize ? a[3] : w};\n        }\n\n        constexpr /*implicit*/ Vector4() noexcept: Vector<4, T>{ZeroInit} {}\n\n        constexpr explicit Vector4(ZeroInitT) noexcept: Vector<4, T>{ZeroInit} {}\n\n        explicit Vector4(NoInitT) noexcept: Vector<4, T>{NoInit} {}\n\n        constexpr explicit Vector4(T value) noexcept: Vector<4, T>(value) {}\n\n        constexpr /*implicit*/ Vector4(T x, T y, T z, T w) noexcept: Vector<4, T>(x, y, z, w) {}\n\n        constexpr /*implicit*/ Vector4(const Vector3<T>& xyz, T w) noexcept: Vector<4, T>(xyz[0], xyz[1], xyz[2], w) {}\n\n        template<class U> constexpr explicit Vector4(const Vector<4, U>& other) noexcept: Vector<4, T>(other) {}\n\n        template<class U, class V = decltype(Implementation::VectorConverter<4, T, U>::from(std::declval<U>()))> constexpr explicit Vector4(const U& other): Vector<4, T>(Implementation::VectorConverter<4, T, U>::from(other)) {}\n\n        constexpr /*implicit*/ Vector4(const Vector<4, T>& other) noexcept: Vector<4, T>(other) {}\n\n        T& x() { return Vector<4, T>::_data[0]; }\n        constexpr T x() const { return Vector<4, T>::_data[0]; }\n\n        T& y() { return Vector<4, T>::_data[1]; }\n        constexpr T y() const { return Vector<4, T>::_data[1]; }\n\n        T& z() { return Vector<4, T>::_data[2]; }\n        constexpr T z() const { return Vector<4, T>::_data[2]; }\n\n        T& w() { return Vector<4, T>::_data[3]; }\n        constexpr T w() const { return Vector<4, T>::_data[3]; }\n\n        T& r() { return Vector<4, T>::_data[0]; }\n        constexpr T r() const { return Vector<4, T>::_data[0]; }\n\n        T& g() { return Vector<4, T>::_data[1]; }\n        constexpr T g() const { return Vector<4, T>::_data[1]; }\n\n        T& b() { return Vector<4, T>::_data[2]; }\n        constexpr T b() const { return Vector<4, T>::_data[2]; }\n\n        T& a() { return Vector<4, T>::_data[3]; }\n        constexpr T a() const { return Vector<4, T>::_data[3]; }\n\n        Vector3<T>& xyz() { return Vector3<T>::from(Vector<4, T>::data()); }\n        constexpr const Vector3<T> xyz() const {\n            return {Vector<4, T>::_data[0], Vector<4, T>::_data[1], Vector<4, T>::_data[2]};\n        }\n\n        Vector3<T>& rgb() { return Vector3<T>::from(Vector<4, T>::data()); }\n        constexpr const Vector3<T> rgb() const {\n            return {Vector<4, T>::_data[0], Vector<4, T>::_data[1], Vector<4, T>::_data[2]};\n        }\n\n        Vector2<T>& xy() { return Vector2<T>::from(Vector<4, T>::data()); }\n        constexpr const Vector2<T> xy() const {\n            return {Vector<4, T>::_data[0], Vector<4, T>::_data[1]};\n        }\n\n        MAGNUM_VECTOR_SUBCLASS_IMPLEMENTATION(4, Vector4)\n};\n\ntemplate<class T> Vector4<T> planeEquation(const Vector3<T>& p0, const Vector3<T>& p1, const Vector3<T>& p2) {\n    const Vector3<T> normal = Math::cross(p1 - p0, p2 - p0).normalized();\n    return {normal, -Math::dot(normal, p0)};\n}\n\ntemplate<class T> Vector4<T> planeEquation(const Vector3<T>& normal, const Vector3<T>& point) {\n    return {normal, -Math::dot(normal, point)};\n}\n\nMAGNUM_VECTORn_OPERATOR_IMPLEMENTATION(4, Vector4)\n\nnamespace Implementation {\n    template<class T> struct TypeForSize<4, T> { typedef Math::Vector4<typename T::Type> Type; };\n\n    template<class T> struct StrictWeakOrdering<Vector4<T>>: StrictWeakOrdering<Vector<4, T>> {};\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Color_h\n#define Magnum_Math_Color_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n\ntemplate<class T> typename std::enable_if<std::is_floating_point<T>::value, Color3<T>>::type fromHsv(ColorHsv<T> hsv) {\n    hsv.hue -= floor(T(hsv.hue)/T(360))*Deg<T>(360);\n    if(hsv.hue < Deg<T>(0)) hsv.hue += Deg<T>(360);\n\n    int h = int(T(hsv.hue)/T(60)) % 6;\n    T f = T(hsv.hue)/T(60) - h;\n\n    T p = hsv.value * (T(1) - hsv.saturation);\n    T q = hsv.value * (T(1) - f*hsv.saturation);\n    T t = hsv.value * (T(1) - (T(1) - f)*hsv.saturation);\n\n    switch(h) {\n        case 0: return {hsv.value, t, p};\n        case 1: return {q, hsv.value, p};\n        case 2: return {p, hsv.value, t};\n        case 3: return {p, q, hsv.value};\n        case 4: return {t, p, hsv.value};\n        case 5: return {hsv.value, p, q};\n        default: CORRADE_ASSERT_UNREACHABLE();\n    }\n}\ntemplate<class T> inline typename std::enable_if<std::is_integral<T>::value, Color3<T>>::type fromHsv(const ColorHsv<typename TypeTraits<T>::FloatingPointType>& hsv) {\n    return pack<Color3<T>>(fromHsv<typename TypeTraits<T>::FloatingPointType>(hsv));\n}\n\ntemplate<class T> Deg<T> hue(const Color3<T>& color, T max, T delta) {\n    T deltaInv60 = T(60)/delta;\n\n    T hue(0);\n    if(delta != T(0)) {\n        if(max == color.r())\n            hue = (color.g()-color.b())*deltaInv60 + (color.g() < color.b() ? T(360) : T(0));\n        else if(max == color.g())\n            hue = (color.b()-color.r())*deltaInv60 + T(120);\n        else\n            hue = (color.r()-color.g())*deltaInv60 + T(240);\n    }\n\n    return Deg<T>(hue);\n}\n\ntemplate<class T> inline Deg<T> hue(typename std::enable_if<std::is_floating_point<T>::value, const Color3<T>&>::type color) {\n    T max = color.max();\n    T delta = max - color.min();\n    return hue(color, max, delta);\n}\ntemplate<class T> inline T saturation(typename std::enable_if<std::is_floating_point<T>::value, const Color3<T>&>::type color) {\n    T max = color.max();\n    T delta = max - color.min();\n    return max != T(0) ? delta/max : T(0);\n}\ntemplate<class T> inline T value(typename std::enable_if<std::is_floating_point<T>::value, const Color3<T>&>::type color) {\n    return color.max();\n}\n\ntemplate<class T> inline Deg<typename Color3<T>::FloatingPointType> hue(typename std::enable_if<std::is_integral<T>::value, const Color3<T>&>::type color) {\n    return hue<typename Color3<T>::FloatingPointType>(unpack<Color3<typename Color3<T>::FloatingPointType>>(color));\n}\ntemplate<class T> inline typename Color3<T>::FloatingPointType saturation(typename std::enable_if<std::is_integral<T>::value, const Color3<T>&>::type& color) {\n    return saturation<typename Color3<T>::FloatingPointType>(unpack<Color3<typename Color3<T>::FloatingPointType>>(color));\n}\ntemplate<class T> inline typename Color3<T>::FloatingPointType value(typename std::enable_if<std::is_integral<T>::value, const Color3<T>&>::type color) {\n    return unpack<typename Color3<T>::FloatingPointType>(color.max());\n}\n\ntemplate<class T> inline ColorHsv<T> toHsv(typename std::enable_if<std::is_floating_point<T>::value, const Color3<T>&>::type color) {\n    T max = color.max();\n    T delta = max - color.min();\n\n    return ColorHsv<T>{hue<typename Color3<T>::FloatingPointType>(color, max, delta), max != T(0) ? delta/max : T(0), max};\n}\ntemplate<class T> inline ColorHsv<typename TypeTraits<T>::FloatingPointType> toHsv(typename std::enable_if<std::is_integral<T>::value, const Color3<T>&>::type color) {\n    return toHsv<typename TypeTraits<T>::FloatingPointType>(unpack<Color3<typename TypeTraits<T>::FloatingPointType>>(color));\n}\n\ntemplate<class T> typename std::enable_if<std::is_floating_point<T>::value, Color3<T>>::type fromSrgb(const Vector3<T>& srgb) {\n    constexpr const T a(T(0.055));\n    return lerp(srgb/T(12.92), pow((srgb + Vector3<T>{a})/(T(1.0) + a), T(2.4)), srgb > Vector3<T>(T(0.04045)));\n}\ntemplate<class T> typename std::enable_if<std::is_floating_point<T>::value, Color4<T>>::type fromSrgbAlpha(const Vector4<T>& srgbAlpha) {\n    return {fromSrgb<T>(srgbAlpha.rgb()), srgbAlpha.a()};\n}\ntemplate<class T> inline typename std::enable_if<std::is_integral<T>::value, Color3<T>>::type fromSrgb(const Vector3<typename Color3<T>::FloatingPointType>& srgb) {\n    return pack<Color3<T>>(fromSrgb<typename Color3<T>::FloatingPointType>(srgb));\n}\ntemplate<class T> inline typename std::enable_if<std::is_integral<T>::value, Color4<T>>::type fromSrgbAlpha(const Vector4<typename Color4<T>::FloatingPointType>& srgbAlpha) {\n    return {fromSrgb<T>(srgbAlpha.rgb()), pack<T>(srgbAlpha.a())};\n}\ntemplate<class T, class Integral> inline Color3<T> fromSrgbIntegral(const Vector3<Integral>& srgb) {\n    static_assert(std::is_integral<Integral>::value, \"only conversion from different integral type is supported\");\n    return fromSrgb<T>(unpack<Vector3<typename Color3<T>::FloatingPointType>>(srgb));\n}\ntemplate<class T, class Integral> inline Color4<T> fromSrgbAlphaIntegral(const Vector4<Integral>& srgbAlpha) {\n    static_assert(std::is_integral<Integral>::value, \"only conversion from different integral type is supported\");\n    return fromSrgbAlpha<T>(unpack<Vector4<typename Color4<T>::FloatingPointType>>(srgbAlpha));\n}\n\ntemplate<class T> Vector3<typename Color3<T>::FloatingPointType> toSrgb(typename std::enable_if<std::is_floating_point<T>::value, const Color3<T>&>::type rgb) {\n    constexpr const T a = T(0.055);\n    return lerp(rgb*T(12.92), (T(1.0) + a)*pow(rgb, T(1.0)/T(2.4)) - Vector3<T>{a}, rgb > Vector3<T>(T(0.0031308)));\n}\ntemplate<class T> Vector4<typename Color4<T>::FloatingPointType> toSrgbAlpha(typename std::enable_if<std::is_floating_point<T>::value, const Color4<T>&>::type rgba) {\n    return {toSrgb<T>(rgba.rgb()), rgba.a()};\n}\ntemplate<class T> inline Vector3<typename Color3<T>::FloatingPointType> toSrgb(typename std::enable_if<std::is_integral<T>::value, const Color3<T>&>::type rgb) {\n    return toSrgb<typename Color3<T>::FloatingPointType>(unpack<Color3<typename Color3<T>::FloatingPointType>>(rgb));\n}\ntemplate<class T> inline Vector4<typename Color4<T>::FloatingPointType> toSrgbAlpha(typename std::enable_if<std::is_integral<T>::value, const Color4<T>&>::type rgba) {\n    return {toSrgb<T>(rgba.rgb()), unpack<typename Color3<T>::FloatingPointType>(rgba.a())};\n}\ntemplate<class T, class Integral> inline Vector3<Integral> toSrgbIntegral(const Color3<T>& rgb) {\n    static_assert(std::is_integral<Integral>::value, \"only conversion from different integral type is supported\");\n    return pack<Vector3<Integral>>(toSrgb<T>(rgb));\n}\ntemplate<class T, class Integral> inline Vector4<Integral> toSrgbAlphaIntegral(const Color4<T>& rgba) {\n    static_assert(std::is_integral<Integral>::value, \"only conversion from different integral type is supported\");\n    return pack<Vector4<Integral>>(toSrgbAlpha<T>(rgba));\n}\n\ntemplate<class T> typename std::enable_if<std::is_floating_point<T>::value, Color3<T>>::type fromXyz(const Vector3<T>& xyz) {\n    return Matrix3x3<T>{\n        Vector3<T>{T(12831)/T(3959), T(-851781)/T(878810), T(705)/T(12673)},\n        Vector3<T>{T(-329)/T(214), T(1648619)/T(878810), T(-2585)/T(12673)},\n        Vector3<T>{T(-1974)/T(3959), T(36519)/T(878810), T(705)/T(667)}}*xyz;\n}\ntemplate<class T> inline typename std::enable_if<std::is_integral<T>::value, Color3<T>>::type fromXyz(const Vector3<typename Color3<T>::FloatingPointType>& xyz) {\n    return pack<Color3<T>>(fromXyz<typename Color3<T>::FloatingPointType>(xyz));\n}\n\ntemplate<class T> Vector3<typename Color3<T>::FloatingPointType> toXyz(typename std::enable_if<std::is_floating_point<T>::value, const Color3<T>&>::type rgb) {\n    return (Matrix3x3<T>{\n        Vector3<T>{T(506752)/T(1228815), T(87098)/T(409605), T(7918)/T(409605)},\n        Vector3<T>{T(87881)/T(245763), T(175762)/T(245763), T(87881)/T(737289)},\n        Vector3<T>{T(12673)/T(70218), T(12673)/T(175545), T(1001167)/T(1053270)}})*rgb;\n}\ntemplate<class T> inline Vector3<typename Color3<T>::FloatingPointType> toXyz(typename std::enable_if<std::is_integral<T>::value, const Color3<T>&>::type rgb) {\n    return toXyz<typename Color3<T>::FloatingPointType>(unpack<Color3<typename Color3<T>::FloatingPointType>>(rgb));\n}\n\n#if !defined(CORRADE_MSVC2017_COMPATIBILITY) || defined(CORRADE_MSVC2015_COMPATIBILITY)\ntemplate<class T> constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type fullChannel() {\n    return T(1);\n}\ntemplate<class T> constexpr typename std::enable_if<std::is_integral<T>::value, T>::type fullChannel() {\n    return Implementation::bitMax<T>();\n}\n#else\ntemplate<class T> constexpr T fullChannel() { return bitMax<T>(); }\ntemplate<> constexpr float fullChannel<float>() { return 1.0f; }\ntemplate<> constexpr double fullChannel<double>() { return 1.0; }\ntemplate<> constexpr long double fullChannel<long double>() { return 1.0l; }\n#endif\n\n}\n\ntemplate<class T> class Color3: public Vector3<T> {\n    public:\n        typedef typename TypeTraits<T>::FloatingPointType FloatingPointType;\n\n        constexpr static Color3<T> red(T red = Implementation::fullChannel<T>()) {\n            return Vector3<T>::xAxis(red);\n        }\n\n        constexpr static Color3<T> green(T green = Implementation::fullChannel<T>()) {\n            return Vector3<T>::yAxis(green);\n        }\n\n        constexpr static Color3<T> blue(T blue = Implementation::fullChannel<T>()) {\n            return Vector3<T>::zAxis(blue);\n        }\n\n        constexpr static Color3<T> cyan(T red = T(0)) {\n            return {red, Implementation::fullChannel<T>(), Implementation::fullChannel<T>()};\n        }\n\n        constexpr static Color3<T> magenta(T green = T(0)) {\n            return {Implementation::fullChannel<T>(), green, Implementation::fullChannel<T>()};\n        }\n\n        constexpr static Color3<T> yellow(T blue = T(0)) {\n            return {Implementation::fullChannel<T>(), Implementation::fullChannel<T>(), blue};\n        }\n\n        static Color3<T> fromHsv(const ColorHsv<FloatingPointType>& hsv) {\n            return Implementation::fromHsv<T>(hsv);\n        }\n\n        static Color3<T> fromSrgb(const Vector3<FloatingPointType>& srgb) {\n            return Implementation::fromSrgb<T>(srgb);\n        }\n\n        template<class Integral> static Color3<T> fromSrgb(const Vector3<Integral>& srgb) {\n            return Implementation::fromSrgbIntegral<T, Integral>(srgb);\n        }\n\n        static Color3<T> fromSrgb(UnsignedInt srgb) {\n            return fromSrgb<UnsignedByte>({UnsignedByte(srgb >> 16),\n                                           UnsignedByte(srgb >> 8),\n                                           UnsignedByte(srgb)});\n        }\n\n        static Color3<T> fromXyz(const Vector3<FloatingPointType>& xyz) {\n            return Implementation::fromXyz<T>(xyz);\n        }\n\n        constexpr /*implicit*/ Color3() noexcept: Vector3<T>{ZeroInit} {}\n\n        constexpr explicit Color3(ZeroInitT) noexcept: Vector3<T>{ZeroInit} {}\n\n        explicit Color3(NoInitT) noexcept: Vector3<T>{NoInit} {}\n\n        constexpr explicit Color3(T rgb) noexcept: Vector3<T>(rgb) {}\n\n        constexpr /*implicit*/ Color3(T r, T g, T b) noexcept: Vector3<T>(r, g, b) {}\n\n        template<class U> constexpr explicit Color3(const Vector<3, U>& other) noexcept: Vector3<T>(other) {}\n\n        template<class U, class V =\n            #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Causes ICE */\n            decltype(Implementation::VectorConverter<3, T, U>::from(std::declval<U>()))\n            #else\n            decltype(Implementation::VectorConverter<3, T, U>())\n            #endif\n            >\n        constexpr explicit Color3(const U& other): Vector3<T>(Implementation::VectorConverter<3, T, U>::from(other)) {}\n\n        constexpr /*implicit*/ Color3(const Vector<3, T>& other) noexcept: Vector3<T>(other) {}\n\n        ColorHsv<FloatingPointType> toHsv() const {\n            return Implementation::toHsv<T>(*this);\n        }\n\n        Deg<FloatingPointType> hue() const {\n            return Deg<FloatingPointType>(Implementation::hue<T>(*this));\n        }\n\n        FloatingPointType saturation() const {\n            return Implementation::saturation<T>(*this);\n        }\n\n        FloatingPointType value() const {\n            return Implementation::value<T>(*this);\n        }\n\n        Vector3<FloatingPointType> toSrgb() const {\n            return Implementation::toSrgb<T>(*this);\n        }\n\n        template<class Integral> Vector3<Integral> toSrgb() const {\n            return Implementation::toSrgbIntegral<T, Integral>(*this);\n        }\n\n        UnsignedInt toSrgbInt() const {\n            const auto srgb = toSrgb<UnsignedByte>();\n            return (srgb[0] << 16) | (srgb[1] << 8) | srgb[2];\n        }\n\n        Vector3<FloatingPointType> toXyz() const {\n            return Implementation::toXyz<T>(*this);\n        }\n\n        MAGNUM_VECTOR_SUBCLASS_IMPLEMENTATION(3, Color3)\n};\n\nMAGNUM_VECTORn_OPERATOR_IMPLEMENTATION(3, Color3)\n\ntemplate<class T>\nclass Color4: public Vector4<T> {\n    public:\n        typedef typename Color3<T>::FloatingPointType FloatingPointType;\n\n        constexpr static Color4<T> red(T red = Implementation::fullChannel<T>(), T alpha = Implementation::fullChannel<T>()) {\n            return {red, T(0), T(0), alpha};\n        }\n\n        constexpr static Color4<T> green(T green = Implementation::fullChannel<T>(), T alpha = Implementation::fullChannel<T>()) {\n            return {T(0), green, T(0), alpha};\n        }\n\n        constexpr static Color4<T> blue(T blue = Implementation::fullChannel<T>(), T alpha = Implementation::fullChannel<T>()) {\n            return {T(0), T(0), blue, alpha};\n        }\n\n        constexpr static Color4<T> cyan(T red = T(0), T alpha = Implementation::fullChannel<T>()) {\n            return {red, Implementation::fullChannel<T>(), Implementation::fullChannel<T>(), alpha};\n        }\n\n        constexpr static Color4<T> magenta(T green = T(0), T alpha = Implementation::fullChannel<T>()) {\n            return {Implementation::fullChannel<T>(), green, Implementation::fullChannel<T>(), alpha};\n        }\n\n        constexpr static Color4<T> yellow(T blue = T(0), T alpha = Implementation::fullChannel<T>()) {\n            return {Implementation::fullChannel<T>(), Implementation::fullChannel<T>(), blue, alpha};\n        }\n\n        static Color4<T> fromHsv(const ColorHsv<FloatingPointType>& hsv, T a = Implementation::fullChannel<T>()) {\n            return Color4<T>(Implementation::fromHsv<T>(hsv), a);\n        }\n\n        static Color4<T> fromSrgbAlpha(const Vector4<FloatingPointType>& srgbAlpha) {\n            return {Implementation::fromSrgbAlpha<T>(srgbAlpha)};\n        }\n\n        static Color4<T> fromSrgb(const Vector3<FloatingPointType>& srgb, T a = Implementation::fullChannel<T>()) {\n            return {Implementation::fromSrgb<T>(srgb), a};\n        }\n\n        template<class Integral> static Color4<T> fromSrgbAlpha(const Vector4<Integral>& srgbAlpha) {\n            return {Implementation::fromSrgbAlphaIntegral<T, Integral>(srgbAlpha)};\n        }\n\n        template<class Integral> static Color4<T> fromSrgb(const Vector3<Integral>& srgb, T a = Implementation::fullChannel<T>()) {\n            return {Implementation::fromSrgbIntegral<T, Integral>(srgb), a};\n        }\n\n        static Color4<T> fromSrgbAlpha(UnsignedInt srgbAlpha) {\n            return fromSrgbAlpha<UnsignedByte>({UnsignedByte(srgbAlpha >> 24),\n                                                UnsignedByte(srgbAlpha >> 16),\n                                                UnsignedByte(srgbAlpha >> 8),\n                                                UnsignedByte(srgbAlpha)});\n        }\n\n        static Color4<T> fromSrgb(UnsignedInt srgb, T a = Implementation::fullChannel<T>()) {\n            return fromSrgb<UnsignedByte>({UnsignedByte(srgb >> 16),\n                                           UnsignedByte(srgb >> 8),\n                                           UnsignedByte(srgb)}, a);\n        }\n\n        static Color4<T> fromXyz(const Vector3<FloatingPointType> xyz, T a = Implementation::fullChannel<T>()) {\n            return {Implementation::fromXyz<T>(xyz), a};\n        }\n\n        constexpr /*implicit*/ Color4() noexcept: Vector4<T>{ZeroInit} {}\n\n        constexpr explicit Color4(ZeroInitT) noexcept: Vector4<T>{ZeroInit} {}\n\n        explicit Color4(NoInitT) noexcept: Vector4<T>{NoInit} {}\n\n        constexpr explicit Color4(T rgb, T alpha = Implementation::fullChannel<T>()) noexcept: Vector4<T>(rgb, rgb, rgb, alpha) {}\n\n        constexpr /*implicit*/ Color4(T r, T g, T b, T a = Implementation::fullChannel<T>()) noexcept: Vector4<T>(r, g, b, a) {}\n\n        constexpr /*implicit*/ Color4(const Vector3<T>& rgb, T a = Implementation::fullChannel<T>()) noexcept: Vector4<T>(rgb[0], rgb[1], rgb[2], a) {}\n\n        template<class U> constexpr explicit Color4(const Vector<4, U>& other) noexcept: Vector4<T>(other) {}\n\n        template<class U, class V =\n            #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Causes ICE */\n            decltype(Implementation::VectorConverter<4, T, U>::from(std::declval<U>()))\n            #else\n            decltype(Implementation::VectorConverter<4, T, U>())\n            #endif\n            >\n        constexpr explicit Color4(const U& other): Vector4<T>(Implementation::VectorConverter<4, T, U>::from(other)) {}\n\n        constexpr /*implicit*/ Color4(const Vector<4, T>& other) noexcept: Vector4<T>(other) {}\n\n        ColorHsv<FloatingPointType> toHsv() const {\n            return Implementation::toHsv<T>(Vector4<T>::rgb());\n        }\n\n        Deg<FloatingPointType> hue() const {\n            return Implementation::hue<T>(Vector4<T>::rgb());\n        }\n\n        FloatingPointType saturation() const {\n            return Implementation::saturation<T>(Vector4<T>::rgb());\n        }\n\n        FloatingPointType value() const {\n            return Implementation::value<T>(Vector4<T>::rgb());\n        }\n\n        Vector4<FloatingPointType> toSrgbAlpha() const {\n            return Implementation::toSrgbAlpha<T>(*this);\n        }\n\n        template<class Integral> Vector4<Integral> toSrgbAlpha() const {\n            return Implementation::toSrgbAlphaIntegral<T, Integral>(*this);\n        }\n\n        UnsignedInt toSrgbAlphaInt() const {\n            const auto srgbAlpha = toSrgbAlpha<UnsignedByte>();\n            return (srgbAlpha[0] << 24) | (srgbAlpha[1] << 16) | (srgbAlpha[2] << 8) | srgbAlpha[3];\n        }\n\n        Vector3<FloatingPointType> toXyz() const {\n            return Implementation::toXyz<T>(rgb());\n        }\n\n        Color3<T>& xyz() { return Color3<T>::from(Vector4<T>::data()); }\n        constexpr const Color3<T> xyz() const { return Vector4<T>::xyz(); }\n\n        Color3<T>& rgb() { return xyz(); }\n        constexpr const Color3<T> rgb() const { return xyz(); }\n\n        MAGNUM_VECTOR_SUBCLASS_IMPLEMENTATION(4, Color4)\n};\n\ntemplate<class T> inline Vector3<T> xyYToXyz(const Vector3<T>& xyY) {\n    return {xyY[0]*xyY[2]/xyY[1], xyY[2], (T(1) - xyY[0] - xyY[1])*xyY[2]/xyY[1]};\n}\n\ntemplate<class T> inline Vector3<T> xyzToXyY(const Vector3<T>& xyz) {\n    return {xyz.xy()/xyz.sum(), xyz.y()};\n}\n\ntemplate<class T> struct ColorHsv {\n    constexpr /*implicit*/ ColorHsv() noexcept: hue{}, saturation{}, value{} {}\n\n    constexpr explicit ColorHsv(ZeroInitT) noexcept: hue{}, saturation{}, value{} {}\n\n    explicit ColorHsv(NoInitT) noexcept: hue{NoInit} /* and the others not */ {}\n\n    constexpr /*implicit*/ ColorHsv(Deg<T> hue, T saturation, T value) noexcept: hue{hue}, saturation{saturation}, value{value} {}\n\n    template<class U> constexpr explicit ColorHsv(const ColorHsv<U>& other) noexcept: hue{other.hue}, saturation{T(other.saturation)}, value{T(other.value)} {}\n\n    bool operator==(const ColorHsv<T>& other) const {\n        return hue == other.hue &&\n            TypeTraits<T>::equals(saturation, other.saturation) &&\n            TypeTraits<T>::equals(value, other.value);\n    }\n\n    bool operator!=(const ColorHsv<T>& other) const {\n        return !operator==(other);\n    }\n\n    Deg<T> hue;\n\n    T saturation;\n\n    T value;\n};\n\nMAGNUM_VECTORn_OPERATOR_IMPLEMENTATION(4, Color4)\n\nnamespace Literals {\n\nconstexpr Color3<UnsignedByte> operator \"\" _rgb(unsigned long long value) {\n    return {UnsignedByte(value >> 16), UnsignedByte(value >> 8), UnsignedByte(value)};\n}\n\nconstexpr Vector3<UnsignedByte> operator \"\" _srgb(unsigned long long value) {\n    return {UnsignedByte(value >> 16), UnsignedByte(value >> 8), UnsignedByte(value)};\n}\n\nconstexpr Color4<UnsignedByte> operator \"\" _rgba(unsigned long long value) {\n    return {UnsignedByte(value >> 24), UnsignedByte(value >> 16), UnsignedByte(value >> 8), UnsignedByte(value)};\n}\n\nconstexpr Vector4<UnsignedByte> operator \"\" _srgba(unsigned long long value) {\n    return {UnsignedByte(value >> 24), UnsignedByte(value >> 16), UnsignedByte(value >> 8), UnsignedByte(value)};\n}\n\ninline Color3<Float> operator \"\" _rgbf(unsigned long long value) {\n    return Math::unpack<Color3<Float>>(Color3<UnsignedByte>{UnsignedByte(value >> 16), UnsignedByte(value >> 8), UnsignedByte(value)});\n}\n\ninline Color3<Float> operator \"\" _srgbf(unsigned long long value) {\n    return Color3<Float>::fromSrgb(UnsignedInt(value));\n}\n\ninline Color4<Float> operator \"\" _rgbaf(unsigned long long value) {\n    return Math::unpack<Color4<Float>>(Color4<UnsignedByte>{UnsignedByte(value >> 24), UnsignedByte(value >> 16), UnsignedByte(value >> 8), UnsignedByte(value)});\n}\n\ninline Color4<Float> operator \"\" _srgbaf(unsigned long long value) {\n    return Color4<Float>::fromSrgbAlpha(UnsignedInt(value));\n}\n\n}\n\nnamespace Implementation {\n    template<class T> struct TypeForSize<3, Color3<T>> { typedef Color3<T> Type; };\n    template<class T> struct TypeForSize<3, Color4<T>> { typedef Color3<T> Type; };\n    template<class T> struct TypeForSize<4, Color3<T>> { typedef Color4<T> Type; };\n    template<class T> struct TypeForSize<4, Color4<T>> { typedef Color4<T> Type; };\n\n    template<class T> struct StrictWeakOrdering<Color3<T>>: StrictWeakOrdering<Vector<3, T>> {};\n    template<class T> struct StrictWeakOrdering<Color4<T>>: StrictWeakOrdering<Vector<4, T>> {};\n}\n\n}}\n\nnamespace Corrade { namespace Utility {\n\n}}\n\n#endif\n#ifndef Magnum_Math_Complex_h\n#define Magnum_Math_Complex_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<class T> constexpr static Complex<T> complexFromMatrix(const Matrix2x2<T>& matrix) {\n        return {matrix[0][0], matrix[0][1]};\n    }\n\n    template<class, class> struct ComplexConverter;\n}\n\ntemplate<class T> inline T dot(const Complex<T>& a, const Complex<T>& b) {\n    return a.real()*b.real() + a.imaginary()*b.imaginary();\n}\n\ntemplate<class T> inline Rad<T> angle(const Complex<T>& normalizedA, const Complex<T>& normalizedB) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::angle(): complex numbers\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    return Rad<T>(std::acos(dot(normalizedA, normalizedB)));\n}\n\ntemplate<class T> class Complex {\n    public:\n        typedef T Type;\n\n        static Complex<T> rotation(Rad<T> angle) {\n            return {std::cos(T(angle)), std::sin(T(angle))};\n        }\n\n        static Complex<T> fromMatrix(const Matrix2x2<T>& matrix) {\n            CORRADE_ASSERT(matrix.isOrthogonal(),\n                \"Math::Complex::fromMatrix(): the matrix is not orthogonal:\" << Corrade::Utility::Debug::newline << matrix, {});\n            return Implementation::complexFromMatrix(matrix);\n        }\n\n        constexpr /*implicit*/ Complex() noexcept: _real(T(1)), _imaginary(T(0)) {}\n\n        constexpr explicit Complex(IdentityInitT) noexcept: _real(T(1)), _imaginary(T(0)) {}\n\n        constexpr explicit Complex(ZeroInitT) noexcept: _real{}, _imaginary{} {}\n\n        explicit Complex(NoInitT) noexcept {}\n\n        constexpr /*implicit*/ Complex(T real, T imaginary) noexcept: _real(real), _imaginary(imaginary) {}\n\n        constexpr explicit Complex(const Vector2<T>& vector) noexcept: _real(vector.x()), _imaginary(vector.y()) {}\n\n        template<class U> constexpr explicit Complex(const Complex<U>& other) noexcept: _real{T(other._real)}, _imaginary{T(other._imaginary)} {}\n\n        template<class U, class V = decltype(Implementation::ComplexConverter<T, U>::from(std::declval<U>()))> constexpr explicit Complex(const U& other): Complex{Implementation::ComplexConverter<T, U>::from(other)} {}\n\n        constexpr /*implicit*/ Complex(const Complex<T>&) noexcept = default;\n\n        template<class U, class V = decltype(Implementation::ComplexConverter<T, U>::to(std::declval<Complex<T>>()))> constexpr explicit operator U() const {\n            return Implementation::ComplexConverter<T, U>::to(*this);\n        }\n\n        T* data() { return &_real; }\n        constexpr const T* data() const { return &_real; }\n\n        bool operator==(const Complex<T>& other) const {\n            return TypeTraits<T>::equals(_real, other._real) &&\n                   TypeTraits<T>::equals(_imaginary, other._imaginary);\n        }\n\n        bool operator!=(const Complex<T>& other) const {\n            return !operator==(other);\n        }\n\n        bool isNormalized() const {\n            return Implementation::isNormalizedSquared(dot());\n        }\n\n        T& real() { return _real; }\n        constexpr T real() const { return _real; }\n\n        T& imaginary() { return _imaginary; }\n        constexpr T imaginary() const { return _imaginary; }\n\n        constexpr explicit operator Vector2<T>() const {\n            return {_real, _imaginary};\n        }\n\n        Rad<T> angle() const {\n            return Rad<T>(std::atan2(_imaginary, _real));\n        }\n\n        Matrix2x2<T> toMatrix() const {\n            return {Vector<2, T>(_real, _imaginary),\n                    Vector<2, T>(-_imaginary, _real)};\n        }\n\n        Complex<T>& operator+=(const Complex<T>& other) {\n            _real += other._real;\n            _imaginary += other._imaginary;\n            return *this;\n        }\n\n        Complex<T> operator+(const Complex<T>& other) const {\n            return Complex<T>(*this) += other;\n        }\n\n        Complex<T> operator-() const {\n            return {-_real, -_imaginary};\n        }\n\n        Complex<T>& operator-=(const Complex<T>& other) {\n            _real -= other._real;\n            _imaginary -= other._imaginary;\n            return *this;\n        }\n\n        Complex<T> operator-(const Complex<T>& other) const {\n            return Complex<T>(*this) -= other;\n        }\n\n        Complex<T>& operator*=(T scalar) {\n            _real *= scalar;\n            _imaginary *= scalar;\n            return *this;\n        }\n\n        Complex<T>& operator*=(const Vector2<T>& vector) {\n             _real *= vector.x();\n             _imaginary *= vector.y();\n             return *this;\n        }\n\n        Complex<T> operator*(T scalar) const {\n            return Complex<T>(*this) *= scalar;\n        }\n\n        Complex<T> operator*(const Vector2<T>& vector) const {\n            return Complex<T>(*this) *= vector;\n        }\n\n        Complex<T>& operator/=(T scalar) {\n            _real /= scalar;\n            _imaginary /= scalar;\n            return *this;\n        }\n\n        Complex<T>& operator/=(const Vector2<T>& vector) {\n             _real /= vector.x();\n             _imaginary /= vector.y();\n             return *this;\n        }\n\n        Complex<T> operator/(T scalar) const {\n            return Complex<T>(*this) /= scalar;\n        }\n\n        Complex<T> operator/(const Vector2<T>& vector) const {\n            return Complex<T>(*this) /= vector;\n        }\n\n        Complex<T> operator*(const Complex<T>& other) const {\n            return {_real*other._real - _imaginary*other._imaginary,\n                    _imaginary*other._real + _real*other._imaginary};\n        }\n\n        T dot() const { return Math::dot(*this, *this); }\n\n        T length() const { return std::hypot(_real, _imaginary); }\n\n        Complex<T> normalized() const {\n            return (*this)/length();\n        }\n\n        Complex<T> conjugated() const {\n            return {_real, -_imaginary};\n        }\n\n        Complex<T> inverted() const {\n            return conjugated()/dot();\n        }\n\n        Complex<T> invertedNormalized() const {\n            CORRADE_ASSERT(isNormalized(),\n                \"Math::Complex::invertedNormalized():\" << *this << \"is not normalized\", {});\n            return conjugated();\n        }\n\n        Vector2<T> transformVector(const Vector2<T>& vector) const {\n            return Vector2<T>((*this)*Complex<T>(vector));\n        }\n\n    private:\n        template<class> friend class Complex;\n\n        T _real, _imaginary;\n};\n\ntemplate<class T> inline Complex<T> operator*(T scalar, const Complex<T>& complex) {\n    return complex*scalar;\n}\n\ntemplate<class T> inline Complex<T> operator*(const Vector2<T>& vector, const Complex<T>& complex) {\n    return complex*vector;\n}\n\ntemplate<class T> inline Complex<T> operator/(T scalar, const Complex<T>& complex) {\n    return {scalar/complex.real(), scalar/complex.imaginary()};\n}\n\ntemplate<class T> inline Complex<T> operator/(const Vector2<T>& vector, const Complex<T>& complex) {\n    return {vector.x()/complex.real(), vector.y()/complex.imaginary()};\n}\n\ntemplate<class T> inline Complex<T> lerp(const Complex<T>& normalizedA, const Complex<T>& normalizedB, T t) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::lerp(): complex numbers\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    return ((T(1) - t)*normalizedA + t*normalizedB).normalized();\n}\n\ntemplate<class T> inline Complex<T> slerp(const Complex<T>& normalizedA, const Complex<T>& normalizedB, T t) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::slerp(): complex numbers\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    const T cosAngle = dot(normalizedA, normalizedB);\n\n    if(std::abs(cosAngle) >= T(1)) return Complex<T>{normalizedA};\n\n    const T a = std::acos(cosAngle);\n    return (std::sin((T(1) - t)*a)*normalizedA + std::sin(t*a)*normalizedB)/std::sin(a);\n}\n\nnamespace Implementation {\n\ntemplate<class T> struct StrictWeakOrdering<Complex<T>> {\n    bool operator()(const Complex<T>& a, const Complex<T>& b) const {\n        if(a.real() < b.real())\n            return true;\n        if(a.real() > b.real())\n            return false;\n\n        return a.imaginary() < b.imaginary();\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Quaternion_h\n#define Magnum_Math_Quaternion_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<class, class> struct QuaternionConverter;\n}\n\ntemplate<class T> inline T dot(const Quaternion<T>& a, const Quaternion<T>& b) {\n    return dot(a.vector(), b.vector()) + a.scalar()*b.scalar();\n}\n\nnamespace Implementation {\n    template<class T> inline T angle(const Quaternion<T>& normalizedA, const Quaternion<T>& normalizedB) {\n        return std::acos(dot(normalizedA, normalizedB));\n    }\n}\n\ntemplate<class T> inline Rad<T> angle(const Quaternion<T>& normalizedA, const Quaternion<T>& normalizedB) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::angle(): quaternions\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    return Rad<T>{Implementation::angle(normalizedA, normalizedB)};\n}\n\ntemplate<class T> inline Quaternion<T> lerp(const Quaternion<T>& normalizedA, const Quaternion<T>& normalizedB, T t) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::lerp(): quaternions\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    return ((T(1) - t)*normalizedA + t*normalizedB).normalized();\n}\n\ntemplate<class T> inline Quaternion<T> lerpShortestPath(const Quaternion<T>& normalizedA, const Quaternion<T>& normalizedB, T t) {\n    return lerp(dot(normalizedA, normalizedB) < T(0) ? -normalizedA : normalizedA, normalizedB, t);\n}\n\ntemplate<class T> inline Quaternion<T> slerp(const Quaternion<T>& normalizedA, const Quaternion<T>& normalizedB, T t) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::slerp(): quaternions\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    const T cosHalfAngle = dot(normalizedA, normalizedB);\n\n    if(std::abs(cosHalfAngle) >= T(1) - TypeTraits<T>::epsilon())\n        return normalizedA;\n\n    const T a = std::acos(cosHalfAngle);\n    return (std::sin((T(1) - t)*a)*normalizedA + std::sin(t*a)*normalizedB)/std::sin(a);\n}\n\ntemplate<class T> inline Quaternion<T> slerpShortestPath(const Quaternion<T>& normalizedA, const Quaternion<T>& normalizedB, T t) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::slerpShortestPath(): quaternions\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    const T cosHalfAngle = dot(normalizedA, normalizedB);\n\n    if(std::abs(cosHalfAngle) >= T(1) - TypeTraits<T>::epsilon())\n        return normalizedA;\n\n    const Quaternion<T> shortestNormalizedA = cosHalfAngle < 0 ? -normalizedA : normalizedA;\n\n    const T a = std::acos(std::abs(cosHalfAngle));\n    return (std::sin((T(1) - t)*a)*shortestNormalizedA + std::sin(t*a)*normalizedB)/std::sin(a);\n}\n\ntemplate<class T> class Quaternion {\n    public:\n        typedef T Type;\n\n        static Quaternion<T> rotation(Rad<T> angle, const Vector3<T>& normalizedAxis);\n\n        static Quaternion<T> fromMatrix(const Matrix3x3<T>& matrix);\n\n        constexpr /*implicit*/ Quaternion() noexcept: _scalar{T(1)} {}\n\n        constexpr explicit Quaternion(IdentityInitT) noexcept: _scalar{T(1)} {}\n\n        constexpr explicit Quaternion(ZeroInitT) noexcept: _vector{ZeroInit}, _scalar{T{0}} {}\n\n        explicit Quaternion(NoInitT) noexcept: _vector{NoInit} {}\n\n        constexpr /*implicit*/ Quaternion(const Vector3<T>& vector, T scalar) noexcept: _vector(vector), _scalar(scalar) {}\n\n        constexpr explicit Quaternion(const Vector3<T>& vector) noexcept: _vector(vector), _scalar(T(0)) {}\n\n        template<class U> constexpr explicit Quaternion(const Quaternion<U>& other) noexcept: _vector{other._vector}, _scalar{T(other._scalar)} {}\n\n        template<class U, class V = decltype(Implementation::QuaternionConverter<T, U>::from(std::declval<U>()))> constexpr explicit Quaternion(const U& other): Quaternion{Implementation::QuaternionConverter<T, U>::from(other)} {}\n\n        constexpr /*implicit*/ Quaternion(const Quaternion<T>&) noexcept = default;\n\n        template<class U, class V = decltype(Implementation::QuaternionConverter<T, U>::to(std::declval<Quaternion<T>>()))> constexpr explicit operator U() const {\n            return Implementation::QuaternionConverter<T, U>::to(*this);\n        }\n\n        T* data() { return _vector.data(); }\n        constexpr const T* data() const { return _vector.data(); }\n\n        bool operator==(const Quaternion<T>& other) const {\n            return _vector == other._vector && TypeTraits<T>::equals(_scalar, other._scalar);\n        }\n\n        bool operator!=(const Quaternion<T>& other) const {\n            return !operator==(other);\n        }\n\n        bool isNormalized() const {\n            return Implementation::isNormalizedSquared(dot());\n        }\n\n        Vector3<T>& vector() { return _vector; }\n        constexpr const Vector3<T> vector() const { return _vector; }\n\n        T& scalar() { return _scalar; }\n        constexpr T scalar() const { return _scalar; }\n\n        Rad<T> angle() const;\n\n        Vector3<T> axis() const;\n\n        Matrix3x3<T> toMatrix() const;\n\n        Quaternion<T> operator-() const { return {-_vector, -_scalar}; }\n\n        Quaternion<T>& operator+=(const Quaternion<T>& other) {\n            _vector += other._vector;\n            _scalar += other._scalar;\n            return *this;\n        }\n\n        Quaternion<T> operator+(const Quaternion<T>& other) const {\n            return Quaternion<T>(*this) += other;\n        }\n\n        Quaternion<T>& operator-=(const Quaternion<T>& other) {\n            _vector -= other._vector;\n            _scalar -= other._scalar;\n            return *this;\n        }\n\n        Quaternion<T> operator-(const Quaternion<T>& other) const {\n            return Quaternion<T>(*this) -= other;\n        }\n\n        Quaternion<T>& operator*=(T scalar) {\n            _vector *= scalar;\n            _scalar *= scalar;\n            return *this;\n        }\n\n        Quaternion<T> operator*(T scalar) const {\n            return Quaternion<T>(*this) *= scalar;\n        }\n\n        Quaternion<T>& operator/=(T scalar) {\n            _vector /= scalar;\n            _scalar /= scalar;\n            return *this;\n        }\n\n        Quaternion<T> operator/(T scalar) const {\n            return Quaternion<T>(*this) /= scalar;\n        }\n\n        Quaternion<T> operator*(const Quaternion<T>& other) const;\n\n        T dot() const { return Math::dot(*this, *this); }\n\n        T length() const { return std::sqrt(dot()); }\n\n        Quaternion<T> normalized() const { return (*this)/length(); }\n\n        Quaternion<T> conjugated() const { return {-_vector, _scalar}; }\n\n        Quaternion<T> inverted() const { return conjugated()/dot(); }\n\n        Quaternion<T> invertedNormalized() const;\n\n        Vector3<T> transformVector(const Vector3<T>& vector) const {\n            return ((*this)*Quaternion<T>(vector)*inverted()).vector();\n        }\n\n        Vector3<T> transformVectorNormalized(const Vector3<T>& vector) const;\n\n    private:\n        template<class> friend class Quaternion;\n\n        constexpr static T pow2(T value) {\n            return value*value;\n        }\n\n        Vector3<T> _vector;\n        T _scalar;\n};\n\ntemplate<class T> inline Quaternion<T> operator*(T scalar, const Quaternion<T>& quaternion) {\n    return quaternion*scalar;\n}\n\ntemplate<class T> inline Quaternion<T> operator/(T scalar, const Quaternion<T>& quaternion) {\n    return {scalar/quaternion.vector(), scalar/quaternion.scalar()};\n}\n\nnamespace Implementation {\n\ntemplate<class T> Quaternion<T> quaternionFromMatrix(const Matrix3x3<T>& m) {\n    const Vector<3, T> diagonal = m.diagonal();\n    const T trace = diagonal.sum();\n\n    if(trace > T(0)) {\n        const T s = std::sqrt(trace + T(1));\n        const T t = T(0.5)/s;\n        return {Vector3<T>(m[1][2] - m[2][1],\n                           m[2][0] - m[0][2],\n                           m[0][1] - m[1][0])*t, s*T(0.5)};\n    }\n\n    std::size_t i = 0;\n    if(diagonal[1] > diagonal[0]) i = 1;\n    if(diagonal[2] > diagonal[i]) i = 2;\n\n    const std::size_t j = (i + 1) % 3;\n    const std::size_t k = (i + 2) % 3;\n\n    const T s = std::sqrt(diagonal[i] - diagonal[j] - diagonal[k] + T(1));\n    const T t = (s == T(0) ? T(0) : T(0.5)/s);\n\n    Vector3<T> vec;\n    vec[i] = s*T(0.5);\n    vec[j] = (m[i][j] + m[j][i])*t;\n    vec[k] = (m[i][k] + m[k][i])*t;\n\n    return {vec, (m[j][k] - m[k][j])*t};\n}\n\n}\n\ntemplate<class T> inline Quaternion<T> Quaternion<T>::rotation(const Rad<T> angle, const Vector3<T>& normalizedAxis) {\n    CORRADE_ASSERT(normalizedAxis.isNormalized(),\n        \"Math::Quaternion::rotation(): axis\" << normalizedAxis << \"is not normalized\", {});\n    return {normalizedAxis*std::sin(T(angle)/2), std::cos(T(angle)/2)};\n}\n\ntemplate<class T> inline Quaternion<T> Quaternion<T>::fromMatrix(const Matrix3x3<T>& matrix) {\n    CORRADE_ASSERT(matrix.isOrthogonal(),\n        \"Math::Quaternion::fromMatrix(): the matrix is not orthogonal:\" << Corrade::Utility::Debug::newline << matrix, {});\n    return Implementation::quaternionFromMatrix(matrix);\n}\n\ntemplate<class T> inline Rad<T> Quaternion<T>::angle() const {\n    CORRADE_ASSERT(isNormalized(),\n        \"Math::Quaternion::angle():\" << *this << \"is not normalized\", {});\n    return Rad<T>(T(2)*std::acos(_scalar));\n}\n\ntemplate<class T> inline Vector3<T> Quaternion<T>::axis() const {\n    CORRADE_ASSERT(isNormalized(),\n        \"Math::Quaternion::axis():\" << *this << \"is not normalized\", {});\n    return _vector/std::sqrt(1-pow2(_scalar));\n}\n\ntemplate<class T> Matrix3x3<T> Quaternion<T>::toMatrix() const {\n    return {\n        Vector<3, T>(T(1) - 2*pow2(_vector.y()) - 2*pow2(_vector.z()),\n            2*_vector.x()*_vector.y() + 2*_vector.z()*_scalar,\n                2*_vector.x()*_vector.z() - 2*_vector.y()*_scalar),\n        Vector<3, T>(2*_vector.x()*_vector.y() - 2*_vector.z()*_scalar,\n            T(1) - 2*pow2(_vector.x()) - 2*pow2(_vector.z()),\n                2*_vector.y()*_vector.z() + 2*_vector.x()*_scalar),\n        Vector<3, T>(2*_vector.x()*_vector.z() + 2*_vector.y()*_scalar,\n            2*_vector.y()*_vector.z() - 2*_vector.x()*_scalar,\n                T(1) - 2*pow2(_vector.x()) - 2*pow2(_vector.y()))\n    };\n}\n\ntemplate<class T> inline Quaternion<T> Quaternion<T>::operator*(const Quaternion<T>& other) const {\n    return {_scalar*other._vector + other._scalar*_vector + Math::cross(_vector, other._vector),\n            _scalar*other._scalar - Math::dot(_vector, other._vector)};\n}\n\ntemplate<class T> inline Quaternion<T> Quaternion<T>::invertedNormalized() const {\n    CORRADE_ASSERT(isNormalized(),\n        \"Math::Quaternion::invertedNormalized():\" << *this << \"is not normalized\", {});\n    return conjugated();\n}\n\ntemplate<class T> inline Vector3<T> Quaternion<T>::transformVectorNormalized(const Vector3<T>& vector) const {\n    CORRADE_ASSERT(isNormalized(),\n        \"Math::Quaternion::transformVectorNormalized():\" << *this << \"is not normalized\", {});\n    const Vector3<T> t = T(2)*Math::cross(_vector, vector);\n    return vector + _scalar*t + Math::cross(_vector, t);\n}\n\nnamespace Implementation {\n\ntemplate<class T> struct StrictWeakOrdering<Quaternion<T>> {\n    bool operator()(const Quaternion<T>& a, const Quaternion<T>& b) const {\n        StrictWeakOrdering<Vector3<T>> o;\n        if(o(a.vector(), b.vector()))\n            return true;\n        if(o(b.vector(), a.vector()))\n            return false;\n\n        return a.scalar() < b.scalar();\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_CubicHermiteSpline_h\n#define Magnum_Math_CubicHermiteSpline_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> class CubicHermite {\n    public:\n        typedef T Type;\n\n        template<UnsignedInt dimensions, class U> static\n        typename std::enable_if<std::is_base_of<Vector<dimensions, U>, T>::value, CubicHermite<T>>::type\n        fromBezier(const CubicBezier<dimensions, U>& a, const CubicBezier<dimensions, U>& b) {\n            return CORRADE_CONSTEXPR_ASSERT(a[3] == b[0],\n                \"Math::CubicHermite::fromBezier(): segments are not adjacent\"),\n                CubicHermite<T>{3*(a[3] - a[2]), a[3], 3*(b[1] - a[3])};\n        }\n\n        constexpr /*implicit*/ CubicHermite() noexcept: CubicHermite{typename std::conditional<std::is_constructible<T, IdentityInitT>::value, IdentityInitT, ZeroInitT>::type{typename std::conditional<std::is_constructible<T, IdentityInitT>::value, IdentityInitT, ZeroInitT>::type::Init{}}} {}\n\n        constexpr explicit CubicHermite(ZeroInitT) noexcept: CubicHermite{ZeroInit, typename std::conditional<std::is_constructible<T, ZeroInitT>::value, ZeroInitT*, void*>::type{}} {}\n\n        template<class U = T, class = typename std::enable_if<std::is_constructible<U, IdentityInitT>::value>::type> constexpr explicit CubicHermite(IdentityInitT) noexcept: _inTangent{ZeroInit}, _point{IdentityInit}, _outTangent{ZeroInit} {}\n\n        explicit CubicHermite(NoInitT) noexcept: CubicHermite{NoInit, typename std::conditional<std::is_constructible<T, NoInitT>::value, NoInitT*, void*>::type{}} {}\n\n        constexpr /*implicit*/ CubicHermite(const T& inTangent, const T& point, const T& outTangent) noexcept: _inTangent{inTangent}, _point{point}, _outTangent{outTangent} {}\n\n        template<class U> constexpr explicit CubicHermite(const CubicHermite<U>& other) noexcept: _inTangent{T(other._inTangent)}, _point{T(other._point)}, _outTangent{T(other._outTangent)} {}\n\n        T* data() { return &_inTangent; }\n        constexpr const T* data() const { return &_inTangent; }\n\n        bool operator==(const CubicHermite<T>& other) const;\n\n        bool operator!=(const CubicHermite<T>& other) const {\n            return !operator==(other);\n        }\n\n        T& inTangent() { return _inTangent; }\n        constexpr const T& inTangent() const { return _inTangent; }\n\n        T& point() { return _point; }\n        constexpr const T& point() const { return _point; }\n\n        T& outTangent() { return _outTangent; }\n        constexpr const T& outTangent() const { return _outTangent; }\n\n    private:\n        template<class> friend class CubicHermite;\n\n        constexpr explicit CubicHermite(ZeroInitT, ZeroInitT*) noexcept: _inTangent{ZeroInit}, _point{ZeroInit}, _outTangent{ZeroInit} {}\n        constexpr explicit CubicHermite(ZeroInitT, void*) noexcept: _inTangent{T(0)}, _point{T(0)}, _outTangent{T(0)} {}\n\n        explicit CubicHermite(NoInitT, NoInitT*) noexcept: _inTangent{NoInit}, _point{NoInit}, _outTangent{NoInit} {}\n        explicit CubicHermite(NoInitT, void*) noexcept {}\n\n        T _inTangent;\n        T _point;\n        T _outTangent;\n};\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using CubicHermite1D = CubicHermite<T>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using CubicHermite2D = CubicHermite<Vector2<T>>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using CubicHermite3D = CubicHermite<Vector3<T>>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using CubicHermiteComplex = CubicHermite<Complex<T>>;\n#endif\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using CubicHermiteQuaternion = CubicHermite<Quaternion<T>>;\n#endif\n\ntemplate<class T, class U> T select(const CubicHermite<T>& a, const CubicHermite<T>& b, U t) {\n    return t < U(1) ? a.point() : b.point();\n}\n\ntemplate<class T, class U> T lerp(const CubicHermite<T>& a, const CubicHermite<T>& b, U t) {\n    return Implementation::lerp(a.point(), b.point(), t);\n}\n\ntemplate<class T> Complex<T> lerp(const CubicHermiteComplex<T>& a, const CubicHermiteComplex<T>& b, T t) {\n    return lerp(a.point(), b.point(), t);\n}\n\ntemplate<class T> Quaternion<T> lerp(const CubicHermiteQuaternion<T>& a, const CubicHermiteQuaternion<T>& b, T t) {\n    return lerp(a.point(), b.point(), t);\n}\n\ntemplate<class T> Quaternion<T> lerpShortestPath(const CubicHermiteQuaternion<T>& a, const CubicHermiteQuaternion<T>& b, T t) {\n    return lerpShortestPath(a.point(), b.point(), t);\n}\n\ntemplate<class T> inline Complex<T> slerp(const CubicHermiteComplex<T>& a, const CubicHermiteComplex<T>& b, T t) {\n    return slerp(a.point(), b.point(), t);\n}\n\ntemplate<class T> inline Quaternion<T> slerp(const CubicHermiteQuaternion<T>& a, const CubicHermiteQuaternion<T>& b, T t) {\n    return slerp(a.point(), b.point(), t);\n}\n\ntemplate<class T> Quaternion<T> slerpShortestPath(const CubicHermiteQuaternion<T>& a, const CubicHermiteQuaternion<T>& b, T t) {\n    return slerpShortestPath(a.point(), b.point(), t);\n}\n\ntemplate<class T, class U> T splerp(const CubicHermite<T>& a, const CubicHermite<T>& b, U t) {\n    return (U(2)*t*t*t - U(3)*t*t + U(1))*a.point() +\n        (t*t*t - U(2)*t*t + t)*a.outTangent() +\n        (U(-2)*t*t*t + U(3)*t*t)*b.point() +\n        (t*t*t - t*t)*b.inTangent();\n}\n\ntemplate<class T> Complex<T> splerp(const CubicHermiteComplex<T>& a, const CubicHermiteComplex<T>& b, T t) {\n    CORRADE_ASSERT(a.point().isNormalized() && b.point().isNormalized(),\n        \"Math::splerp(): complex spline points\" << a.point() << \"and\" << b.point() << \"are not normalized\", {});\n    return ((T(2)*t*t*t - T(3)*t*t + T(1))*a.point() +\n        (t*t*t - T(2)*t*t + t)*a.outTangent() +\n        (T(-2)*t*t*t + T(3)*t*t)*b.point() +\n        (t*t*t - t*t)*b.inTangent()).normalized();\n}\n\ntemplate<class T> Quaternion<T> splerp(const CubicHermiteQuaternion<T>& a, const CubicHermiteQuaternion<T>& b, T t) {\n    CORRADE_ASSERT(a.point().isNormalized() && b.point().isNormalized(),\n        \"Math::splerp(): quaternion spline points\" << a.point() << \"and\" << b.point() << \"are not normalized\", {});\n    return ((T(2)*t*t*t - T(3)*t*t + T(1))*a.point() +\n        (t*t*t - T(2)*t*t + t)*a.outTangent() +\n        (T(-2)*t*t*t + T(3)*t*t)*b.point() +\n        (t*t*t - t*t)*b.inTangent()).normalized();\n}\n\ntemplate<class T> inline bool CubicHermite<T>::operator==(const CubicHermite<T>& other) const {\n    return TypeTraits<T>::equals(_inTangent, other._inTangent) &&\n        TypeTraits<T>::equals(_point, other._point) &&\n        TypeTraits<T>::equals(_outTangent, other._outTangent);\n}\n\nnamespace Implementation {\n\ntemplate<class T> struct StrictWeakOrdering<CubicHermite<T>> {\n    bool operator()(const CubicHermite<T>& a, const CubicHermite<T>& b) const {\n        StrictWeakOrdering<T> o;\n        if(o(a.inTangent(), b.inTangent()))\n            return true;\n        if(o(b.inTangent(), a.inTangent()))\n            return false;\n        if(o(a.point(), b.point()))\n            return true;\n        if(o(b.point(), a.point()))\n            return false;\n        return o(a.outTangent(), b.outTangent());\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Distance_h\n#define Magnum_Math_Distance_h\n\nnamespace Magnum { namespace Math { namespace Distance {\n\ntemplate<class T> inline T linePointSquared(const Vector2<T>& a, const Vector2<T>& b, const Vector2<T>& point) {\n    const Vector2<T> bMinusA = b - a;\n    return Math::pow<2>(cross(bMinusA, a - point))/bMinusA.dot();\n}\n\ntemplate<class T> inline T linePoint(const Vector2<T>& a, const Vector2<T>& b, const Vector2<T>& point) {\n    const Vector2<T> bMinusA = b - a;\n    return std::abs(cross(bMinusA, a - point))/bMinusA.length();\n}\n\ntemplate<class T> inline T linePointSquared(const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& point) {\n    return cross(point - a, point - b).dot()/(b - a).dot();\n}\n\ntemplate<class T> inline T linePoint(const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& point) {\n    return std::sqrt(linePointSquared(a, b, point));\n}\n\ntemplate<class T> T lineSegmentPointSquared(const Vector2<T>& a, const Vector2<T>& b, const Vector2<T>& point);\n\ntemplate<class T> T lineSegmentPoint(const Vector2<T>& a, const Vector2<T>& b, const Vector2<T>& point);\n\ntemplate<class T> T lineSegmentPointSquared(const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& point);\n\ntemplate<class T> inline T lineSegmentPoint(const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& point) {\n    return std::sqrt(lineSegmentPointSquared(a, b, point));\n}\n\ntemplate<class T> inline T pointPlaneScaled(const Vector3<T>& point, const Vector4<T>& plane) {\n    return dot(plane.xyz(), point) + plane.w();\n}\n\ntemplate<class T> inline T pointPlane(const Vector3<T>& point, const Vector4<T>& plane) {\n    return pointPlaneScaled<T>(point, plane)/plane.xyz().length();\n}\n\ntemplate<class T> inline T pointPlaneNormalized(const Vector3<T>& point, const Vector4<T>& plane) {\n    CORRADE_ASSERT(plane.xyz().isNormalized(),\n        \"Math::Distance::pointPlaneNormalized(): plane normal\" << plane.xyz() << \"is not normalized\", {});\n    return pointPlaneScaled<T>(point, plane);\n}\n\ntemplate<class T> T lineSegmentPoint(const Vector2<T>& a, const Vector2<T>& b, const Vector2<T>& point) {\n    const Vector2<T> pointMinusA = point - a;\n    const Vector2<T> pointMinusB = point - b;\n    const Vector2<T> bMinusA = b - a;\n    const T pointDistanceA = pointMinusA.dot();\n    const T pointDistanceB = pointMinusB.dot();\n    const T bDistanceA = bMinusA.dot();\n\n    if(pointDistanceB > bDistanceA + pointDistanceA)\n        return std::sqrt(pointDistanceA);\n\n    if(pointDistanceA > bDistanceA + pointDistanceB)\n        return std::sqrt(pointDistanceB);\n\n    return std::abs(cross(bMinusA, -pointMinusA))/std::sqrt(bDistanceA);\n}\n\ntemplate<class T> T lineSegmentPointSquared(const Vector2<T>& a, const Vector2<T>& b, const Vector2<T>& point) {\n    const Vector2<T> pointMinusA = point - a;\n    const Vector2<T> pointMinusB = point - b;\n    const Vector2<T> bMinusA = b - a;\n    const T pointDistanceA = pointMinusA.dot();\n    const T pointDistanceB = pointMinusB.dot();\n    const T bDistanceA = bMinusA.dot();\n\n    if(pointDistanceB > bDistanceA + pointDistanceA)\n        return pointDistanceA;\n\n    if(pointDistanceA > bDistanceA + pointDistanceB)\n        return pointDistanceB;\n\n    return Math::pow<2>(cross(bMinusA, -pointMinusA))/bDistanceA;\n}\n\ntemplate<class T> T lineSegmentPointSquared(const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& point) {\n    const Vector3<T> pointMinusA = point - a;\n    const Vector3<T> pointMinusB = point - b;\n    const T pointDistanceA = pointMinusA.dot();\n    const T pointDistanceB = pointMinusB.dot();\n    const T bDistanceA = (b - a).dot();\n\n    if(pointDistanceB > bDistanceA + pointDistanceA)\n        return pointDistanceA;\n\n    if(pointDistanceA > bDistanceA + pointDistanceB)\n        return pointDistanceB;\n\n    return cross(pointMinusA, pointMinusB).dot()/bDistanceA;\n}\n\n}}}\n\n#endif\n#ifndef Corrade_Utility_TypeTraits_h\n#define Corrade_Utility_TypeTraits_h\n\nnamespace Corrade { namespace Utility {\n\n#define CORRADE_HAS_TYPE(className, typeExpression)                         \\\ntemplate<class U> class className {                                         \\\n    template<class T> static char get(T&&, typeExpression* = nullptr);      \\\n    static short get(...);                                                  \\\n    public:                                                                 \\\n        enum: bool { value = sizeof(get(std::declval<U>())) == sizeof(char) }; \\\n}\n\nnamespace Implementation {\n    CORRADE_HAS_TYPE(HasMemberBegin, decltype(std::declval<T>().begin()));\n    CORRADE_HAS_TYPE(HasMemberEnd, decltype(std::declval<T>().end()));\n    CORRADE_HAS_TYPE(HasBegin, decltype(begin(std::declval<T>())));\n    CORRADE_HAS_TYPE(HasEnd, decltype(end(std::declval<T>())));\n    CORRADE_HAS_TYPE(HasMemberCStr, decltype(std::declval<T>().c_str()));\n}\n\ntemplate<class T> using IsIterable = std::integral_constant<bool,\n    (Implementation::HasMemberBegin<T>::value || Implementation::HasBegin<T>::value) &&\n    (Implementation::HasMemberEnd<T>::value || Implementation::HasEnd<T>::value)\n    >;\n\ntemplate<class T> using IsStringLike = std::integral_constant<bool,\n    Implementation::HasMemberCStr<T>::value\n    >;\n\n}}\n\n#endif\n#ifndef Magnum_Math_Dual_h\n#define Magnum_Math_Dual_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    CORRADE_HAS_TYPE(IsDual, decltype(std::declval<const T>().dual()));\n}\n\ntemplate<class T> class Dual {\n    template<class> friend class Dual;\n\n    public:\n        typedef T Type;\n\n        constexpr /*implicit*/ Dual() noexcept: _real{}, _dual{} {}\n\n        template<class U = T, class = typename std::enable_if<std::is_pod<U>::value>::type> constexpr explicit Dual(ZeroInitT) noexcept: _real{}, _dual{} {}\n        template<class U = T, class V = T, class = typename std::enable_if<std::is_constructible<U, ZeroInitT>::value>::type> constexpr explicit Dual(ZeroInitT) noexcept: _real{ZeroInit}, _dual{ZeroInit} {}\n\n        template<class U = T, class = typename std::enable_if<std::is_pod<U>::value>::type> explicit Dual(NoInitT) noexcept {}\n        template<class U = T, class V = T, class = typename std::enable_if<std::is_constructible<U, NoInitT>::value>::type> explicit Dual(NoInitT) noexcept: _real{NoInit}, _dual{NoInit} {}\n\n        #if !defined(CORRADE_MSVC2017_COMPATIBILITY) || defined(CORRADE_MSVC2015_COMPATIBILITY)\n        constexpr /*implicit*/ Dual(const T& real, const T& dual = T()) noexcept: _real(real), _dual(dual) {}\n        #else\n        constexpr /*implicit*/ Dual(const T& real, const T& dual) noexcept: _real(real), _dual(dual) {}\n        constexpr /*implicit*/ Dual(const T& real) noexcept: _real(real), _dual() {}\n        #endif\n\n        template<class U> constexpr explicit Dual(const Dual<U>& other) noexcept: _real{T(other._real)}, _dual{T(other._dual)} {}\n\n        constexpr /*implicit*/ Dual(const Dual<T>&) noexcept = default;\n\n        T* data() { return &_real; }\n        constexpr const T* data() const { return &_real; }\n\n        bool operator==(const Dual<T>& other) const {\n            return TypeTraits<T>::equals(_real, other._real) &&\n                   TypeTraits<T>::equals(_dual, other._dual);\n        }\n\n        bool operator!=(const Dual<T>& other) const {\n            return !operator==(other);\n        }\n\n        T& real() { return _real; }\n        constexpr const T real() const { return _real; }\n\n        T& dual() { return _dual; }\n        constexpr const T dual() const { return _dual; }\n\n        Dual<T>& operator+=(const Dual<T>& other) {\n            _real += other._real;\n            _dual += other._dual;\n            return *this;\n        }\n\n        Dual<T> operator+(const Dual<T>& other) const {\n            return Dual<T>(*this)+=other;\n        }\n\n        Dual<T> operator-() const {\n            return {-_real, -_dual};\n        }\n\n        Dual<T>& operator-=(const Dual<T>& other) {\n            _real -= other._real;\n            _dual -= other._dual;\n            return *this;\n        }\n\n        Dual<T> operator-(const Dual<T>& other) const {\n            return Dual<T>(*this)-=other;\n        }\n\n        template<class U> auto operator*(const Dual<U>& other) const -> Dual<decltype(std::declval<T>()*std::declval<U>())> {\n            return {_real*other._real, _real*other._dual + _dual*other._real};\n        }\n\n        template<class U, class V = typename std::enable_if<!Implementation::IsDual<U>::value, void>::type> Dual<decltype(std::declval<T>()*std::declval<U>())> operator*(const U& other) const {\n            return {_real*other, _dual*other};\n        }\n\n        template<class U> auto operator/(const Dual<U>& other) const -> Dual<decltype(std::declval<T>()/std::declval<U>())> {\n            return {_real/other._real, (_dual*other._real - _real*other._dual)/(other._real*other._real)};\n        }\n\n        template<class U, class V = typename std::enable_if<!Implementation::IsDual<U>::value, Dual<decltype(std::declval<T>()/std::declval<U>())>>::type> V operator/(const U& other) const {\n            return {_real/other, _dual/other};\n        }\n\n        Dual<T> conjugated() const {\n            return {_real, -_dual};\n        }\n\n    private:\n        T _real, _dual;\n};\n\ntemplate<class T, class U, class V = typename std::enable_if<!Implementation::IsDual<T>::value, Dual<decltype(std::declval<T>()*std::declval<U>())>>::type> inline V operator*(const T& a, const Dual<U>& b) {\n    return {a*b.real(), a*b.dual()};\n}\n\n#define MAGNUM_DUAL_SUBCLASS_IMPLEMENTATION(Type, Underlying, Multiplicable) \\\n    Type<T> operator-() const {                                             \\\n        return Math::Dual<Underlying<T>>::operator-();                      \\\n    }                                                                       \\\n    Type<T>& operator+=(const Math::Dual<Underlying<T>>& other) {           \\\n        Math::Dual<Underlying<T>>::operator+=(other);                       \\\n        return *this;                                                       \\\n    }                                                                       \\\n    Type<T> operator+(const Math::Dual<Underlying<T>>& other) const {       \\\n        return Math::Dual<Underlying<T>>::operator+(other);                 \\\n    }                                                                       \\\n    Type<T>& operator-=(const Math::Dual<Underlying<T>>& other) {           \\\n        Math::Dual<Underlying<T>>::operator-=(other);                       \\\n        return *this;                                                       \\\n    }                                                                       \\\n    Type<T> operator-(const Math::Dual<Underlying<T>>& other) const {       \\\n        return Math::Dual<Underlying<T>>::operator-(other);                 \\\n    }                                                                       \\\n    Type<T> operator*(const Math::Dual<Multiplicable>& other) const {       \\\n        return Math::Dual<Underlying<T>>::operator*(other);                 \\\n    }                                                                       \\\n    Type<T> operator*(const Multiplicable& other) const {                   \\\n        return Math::Dual<Underlying<T>>::operator*(other);                 \\\n    }                                                                       \\\n    Type<T> operator/(const Math::Dual<Multiplicable>& other) const {       \\\n        return Math::Dual<Underlying<T>>::operator/(other);                 \\\n    }                                                                       \\\n    Type<T> operator/(const Multiplicable& other) const {                   \\\n        return Math::Dual<Underlying<T>>::operator/(other);                 \\\n    }\n\n#define MAGNUM_DUAL_SUBCLASS_MULTIPLICATION_IMPLEMENTATION(Type, Underlying) \\\n    template<class U> Type<T> operator*(const Math::Dual<U>& other) const { \\\n        return Math::Dual<Underlying<T>>::operator*(other);                 \\\n    }                                                                       \\\n    template<class U> Type<T> operator/(const Math::Dual<U>& other) const { \\\n        return Math::Dual<Underlying<T>>::operator/(other);                 \\\n    }                                                                       \\\n    Type<T> operator*(const Math::Dual<Underlying<T>>& other) const {       \\\n        return Math::Dual<Underlying<T>>::operator*(other);                 \\\n    }                                                                       \\\n    Type<T> operator/(const Math::Dual<Underlying<T>>& other) const {       \\\n        return Math::Dual<Underlying<T>>::operator/(other);                 \\\n    }\n\n#define MAGNUM_DUAL_OPERATOR_IMPLEMENTATION(Type, Underlying, Multiplicable) \\\n    template<class T> inline Type<T> operator*(const Math::Dual<Multiplicable>& a, const Type<T>& b) { \\\n        return a*static_cast<const Math::Dual<Underlying<T>>&>(b);          \\\n    }                                                                       \\\n    template<class T> inline Type<T> operator*(const Multiplicable& a, const Type<T>& b) { \\\n        return a*static_cast<const Math::Dual<Underlying<T>>&>(b);          \\\n    }                                                                       \\\n    template<class T> inline Type<T> operator/(const Math::Dual<Multiplicable>& a, const Type<T>& b) { \\\n        return a/static_cast<const Math::Dual<Underlying<T>>&>(b);          \\\n    }\n\ntemplate<class T> Dual<T> sqrt(const Dual<T>& dual) {\n    T sqrt0 = std::sqrt(dual.real());\n    return {sqrt0, dual.dual()/(2*sqrt0)};\n}\n\ntemplate<class T> std::pair<Dual<T>, Dual<T>> sincos(const Dual<Rad<T>>& angle)\n{\n    const T sin = std::sin(T(angle.real()));\n    const T cos = std::cos(T(angle.real()));\n    return {{sin, T(angle.dual())*cos}, {cos, -T(angle.dual())*sin}};\n}\ntemplate<class T> std::pair<Dual<T>, Dual<T>> sincos(const Dual<Deg<T>>& angle) { return sincos(Dual<Rad<T>>(angle)); }\ntemplate<class T> std::pair<Dual<T>, Dual<T>> sincos(const Dual<Unit<Rad, T>>& angle) { return sincos(Dual<Rad<T>>(angle)); }\ntemplate<class T> std::pair<Dual<T>, Dual<T>> sincos(const Dual<Unit<Deg, T>>& angle) { return sincos(Dual<Rad<T>>(angle)); }\n\nnamespace Implementation {\n\ntemplate<class T> struct StrictWeakOrdering<Dual<T>> {\n    bool operator()(const Dual<T>& a, const Dual<T>& b) const {\n        StrictWeakOrdering<T> o;\n        if(o(a.real(), b.real()))\n            return true;\n        if(o(b.real(), a.real()))\n            return false;\n\n        return o(a.dual(), b.dual());\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Matrix3_h\n#define Magnum_Math_Matrix3_h\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> class Matrix3: public Matrix3x3<T> {\n    public:\n        constexpr static Matrix3<T> translation(const Vector2<T>& vector) {\n            return {{      T(1),       T(0), T(0)},\n                    {      T(0),       T(1), T(0)},\n                    {vector.x(), vector.y(), T(1)}};\n        }\n\n        constexpr static Matrix3<T> scaling(const Vector2<T>& vector) {\n            return {{vector.x(),       T(0), T(0)},\n                    {      T(0), vector.y(), T(0)},\n                    {      T(0),       T(0), T(1)}};\n        }\n\n        static Matrix3<T> rotation(Rad<T> angle);\n\n        static Matrix3<T> reflection(const Vector2<T>& normal) {\n            CORRADE_ASSERT(normal.isNormalized(),\n                \"Math::Matrix3::reflection(): normal\" << normal << \"is not normalized\", {});\n            return from(Matrix2x2<T>() - T(2)*normal*RectangularMatrix<1, 2, T>(normal).transposed(), {});\n        }\n\n        constexpr static Matrix3<T> shearingX(T amount) {\n            return {{  T(1), T(0), T(0)},\n                    {amount, T(1), T(0)},\n                    {  T(0), T(0), T(1)}};\n        }\n\n        constexpr static Matrix3<T> shearingY(T amount) {\n            return {{T(1), amount, T(0)},\n                    {T(0),   T(1), T(0)},\n                    {T(0),   T(0), T(1)}};\n        }\n\n        static Matrix3<T> projection(const Vector2<T>& size) {\n            return scaling(2.0f/size);\n        }\n\n        constexpr static Matrix3<T> from(const Matrix2x2<T>& rotationScaling, const Vector2<T>& translation) {\n            return {{rotationScaling[0], T(0)},\n                    {rotationScaling[1], T(0)},\n                    {       translation, T(1)}};\n        }\n\n        constexpr /*implicit*/ Matrix3() noexcept: Matrix3x3<T>{IdentityInit, T(1)} {}\n\n        constexpr explicit Matrix3(IdentityInitT, T value = T{1}) noexcept: Matrix3x3<T>{IdentityInit, value} {}\n\n        constexpr explicit Matrix3(ZeroInitT) noexcept: Matrix3x3<T>{ZeroInit} {}\n\n        constexpr explicit Matrix3(NoInitT) noexcept: Matrix3x3<T>{NoInit} {}\n\n        constexpr /*implicit*/ Matrix3(const Vector3<T>& first, const Vector3<T>& second, const Vector3<T>& third) noexcept: Matrix3x3<T>(first, second, third) {}\n\n        constexpr explicit Matrix3(T value) noexcept: Matrix3x3<T>{value} {}\n\n        template<class U> constexpr explicit Matrix3(const RectangularMatrix<3, 3, U>& other) noexcept: Matrix3x3<T>(other) {}\n\n        template<class U, class V = decltype(Implementation::RectangularMatrixConverter<3, 3, T, U>::from(std::declval<U>()))> constexpr explicit Matrix3(const U& other) noexcept: Matrix3x3<T>(Implementation::RectangularMatrixConverter<3, 3, T, U>::from(other)) {}\n\n        template<std::size_t otherSize> constexpr explicit Matrix3(const RectangularMatrix<otherSize, otherSize, T>& other) noexcept: Matrix3x3<T>{other} {}\n\n        constexpr /*implicit*/ Matrix3(const RectangularMatrix<3, 3, T>& other) noexcept: Matrix3x3<T>(other) {}\n\n        bool isRigidTransformation() const {\n            return rotationScaling().isOrthogonal() && row(2) == Vector3<T>(T(0), T(0), T(1));\n        }\n\n        constexpr Matrix2x2<T> rotationScaling() const {\n            return {(*this)[0].xy(),\n                    (*this)[1].xy()};\n        }\n\n        Matrix2x2<T> rotationShear() const {\n            return {(*this)[0].xy().normalized(),\n                    (*this)[1].xy().normalized()};\n        }\n\n        Matrix2x2<T> rotation() const;\n\n        Matrix2x2<T> rotationNormalized() const;\n\n        Vector2<T> scalingSquared() const {\n            return {(*this)[0].xy().dot(),\n                    (*this)[1].xy().dot()};\n        }\n\n        Vector2<T> scaling() const {\n            return {(*this)[0].xy().length(),\n                    (*this)[1].xy().length()};\n        }\n\n        T uniformScalingSquared() const;\n\n        T uniformScaling() const { return std::sqrt(uniformScalingSquared()); }\n\n        Vector2<T>& right() { return (*this)[0].xy(); }\n        constexpr Vector2<T> right() const { return (*this)[0].xy(); }\n\n        Vector2<T>& up() { return (*this)[1].xy(); }\n        constexpr Vector2<T> up() const { return (*this)[1].xy(); }\n\n        Vector2<T>& translation() { return (*this)[2].xy(); }\n        constexpr Vector2<T> translation() const { return (*this)[2].xy(); }\n\n        Matrix3<T> invertedRigid() const;\n\n        Vector2<T> transformVector(const Vector2<T>& vector) const {\n            return ((*this)*Vector3<T>(vector, T(0))).xy();\n        }\n\n        Vector2<T> transformPoint(const Vector2<T>& vector) const {\n            return ((*this)*Vector3<T>(vector, T(1))).xy();\n        }\n\n        MAGNUM_RECTANGULARMATRIX_SUBCLASS_IMPLEMENTATION(3, 3, Matrix3<T>)\n        MAGNUM_MATRIX_SUBCLASS_IMPLEMENTATION(3, Matrix3, Vector3)\n};\n\nMAGNUM_MATRIXn_OPERATOR_IMPLEMENTATION(3, Matrix3)\n\ntemplate<class T> Matrix3<T> Matrix3<T>::rotation(const Rad<T> angle) {\n    const T sine = std::sin(T(angle));\n    const T cosine = std::cos(T(angle));\n\n    return {{ cosine,   sine, T(0)},\n            {  -sine, cosine, T(0)},\n            {   T(0),   T(0), T(1)}};\n}\n\ntemplate<class T> Matrix2x2<T> Matrix3<T>::rotation() const {\n    Matrix2x2<T> rotation{(*this)[0].xy().normalized(),\n                          (*this)[1].xy().normalized()};\n    CORRADE_ASSERT(rotation.isOrthogonal(),\n        \"Math::Matrix3::rotation(): the normalized rotation part is not orthogonal:\" << Corrade::Utility::Debug::newline << rotation, {});\n    return rotation;\n}\n\ntemplate<class T> Matrix2x2<T> Matrix3<T>::rotationNormalized() const {\n    Matrix2x2<T> rotation{(*this)[0].xy(),\n                          (*this)[1].xy()};\n    CORRADE_ASSERT(rotation.isOrthogonal(),\n        \"Math::Matrix3::rotationNormalized(): the rotation part is not orthogonal:\" << Corrade::Utility::Debug::newline << rotation, {});\n    return rotation;\n}\n\ntemplate<class T> T Matrix3<T>::uniformScalingSquared() const {\n    const T scalingSquared = (*this)[0].xy().dot();\n    CORRADE_ASSERT(TypeTraits<T>::equals((*this)[1].xy().dot(), scalingSquared),\n        \"Math::Matrix3::uniformScaling(): the matrix doesn't have uniform scaling:\" << Corrade::Utility::Debug::newline << rotationScaling(), {});\n    return scalingSquared;\n}\n\ntemplate<class T> inline Matrix3<T> Matrix3<T>::invertedRigid() const {\n    CORRADE_ASSERT(isRigidTransformation(),\n        \"Math::Matrix3::invertedRigid(): the matrix doesn't represent a rigid transformation:\" << Corrade::Utility::Debug::newline << *this, {});\n\n    Matrix2x2<T> inverseRotation = rotationScaling().transposed();\n    return from(inverseRotation, inverseRotation*-translation());\n}\n\nnamespace Implementation {\n    template<class T> struct StrictWeakOrdering<Matrix3<T>>: StrictWeakOrdering<RectangularMatrix<3, 3, T>> {};\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_DualComplex_h\n#define Magnum_Math_DualComplex_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<class, class> struct DualComplexConverter;\n}\n\ntemplate<class T> class DualComplex: public Dual<Complex<T>> {\n    public:\n        typedef T Type;\n\n        static DualComplex<T> rotation(Rad<T> angle) {\n            return {Complex<T>::rotation(angle), {{}, {}}};\n        }\n\n        static DualComplex<T> translation(const Vector2<T>& vector) {\n            return {{}, {vector.x(), vector.y()}};\n        }\n\n        static DualComplex<T> fromMatrix(const Matrix3<T>& matrix) {\n            CORRADE_ASSERT(matrix.isRigidTransformation(),\n                \"Math::DualComplex::fromMatrix(): the matrix doesn't represent rigid transformation:\" << Corrade::Utility::Debug::newline << matrix, {});\n            return {Implementation::complexFromMatrix(matrix.rotationScaling()), Complex<T>(matrix.translation())};\n        }\n\n        constexpr /*implicit*/ DualComplex() noexcept: Dual<Complex<T>>({}, {T(0), T(0)}) {}\n\n        constexpr explicit DualComplex(IdentityInitT) noexcept: Dual<Complex<T>>({}, {T(0), T(0)}) {}\n\n        constexpr explicit DualComplex(ZeroInitT) noexcept: Dual<Complex<T>>{Complex<T>{ZeroInit}, Complex<T>{ZeroInit}} {}\n\n        explicit DualComplex(NoInitT) noexcept: Dual<Complex<T>>{NoInit} {}\n\n        constexpr /*implicit*/ DualComplex(const Complex<T>& real, const Complex<T>& dual = Complex<T>(T(0), T(0))) noexcept: Dual<Complex<T>>(real, dual) {}\n\n        constexpr explicit DualComplex(const Vector2<T>& vector) noexcept: Dual<Complex<T>>({}, Complex<T>(vector)) {}\n\n        template<class U> constexpr explicit DualComplex(const DualComplex<U>& other) noexcept: Dual<Complex<T>>{other} {}\n\n        template<class U, class V = decltype(Implementation::DualComplexConverter<T, U>::from(std::declval<U>()))> constexpr explicit DualComplex(const U& other): DualComplex{Implementation::DualComplexConverter<T, U>::from(other)} {}\n\n        constexpr /*implicit*/ DualComplex(const Dual<Complex<T>>& other) noexcept: Dual<Complex<T>>(other) {}\n\n        template<class U, class V = decltype(Implementation::DualComplexConverter<T, U>::to(std::declval<DualComplex<T>>()))> constexpr explicit operator U() const {\n            return Implementation::DualComplexConverter<T, U>::to(*this);\n        }\n\n        T* data() { return Dual<Complex<T>>::data()->data(); }\n        constexpr const T* data() const { return Dual<Complex<T>>::data()->data(); }\n\n        bool isNormalized() const {\n            return Implementation::isNormalizedSquared(lengthSquared());\n        }\n\n        constexpr Complex<T> rotation() const {\n            return Dual<Complex<T>>::real();\n        }\n\n        Vector2<T> translation() const {\n            return Vector2<T>(Dual<Complex<T>>::dual());\n        }\n\n        Matrix3<T> toMatrix() const {\n            return Matrix3<T>::from(Dual<Complex<T>>::real().toMatrix(), translation());\n        }\n\n        DualComplex<T> operator*(const DualComplex<T>& other) const {\n            return {Dual<Complex<T>>::real()*other.real(), Dual<Complex<T>>::real()*other.dual() + Dual<Complex<T>>::dual()};\n        }\n\n        DualComplex<T> complexConjugated() const {\n            return {Dual<Complex<T>>::real().conjugated(), Dual<Complex<T>>::dual().conjugated()};\n        }\n\n        DualComplex<T> dualConjugated() const {\n            return Dual<Complex<T>>::conjugated();\n        }\n\n        DualComplex<T> conjugated() const {\n            return {Dual<Complex<T>>::real().conjugated(), {-Dual<Complex<T>>::dual().real(), Dual<Complex<T>>::dual().imaginary()}};\n        }\n\n        T lengthSquared() const {\n            return Dual<Complex<T>>::real().dot();\n        }\n\n        T length() const {\n            return Dual<Complex<T>>::real().length();\n        }\n\n        DualComplex<T> normalized() const {\n            return {Dual<Complex<T>>::real()/length(), Dual<Complex<T>>::dual()};\n        }\n\n        DualComplex<T> inverted() const {\n            return DualComplex<T>(Dual<Complex<T>>::real().inverted(), {{}, {}})*DualComplex<T>({}, -Dual<Complex<T>>::dual());\n        }\n\n        DualComplex<T> invertedNormalized() const {\n            return DualComplex<T>(Dual<Complex<T>>::real().invertedNormalized(), {{}, {}})*DualComplex<T>({}, -Dual<Complex<T>>::dual());\n        }\n\n        Vector2<T> transformPoint(const Vector2<T>& vector) const {\n            return Vector2<T>(((*this)*DualComplex<T>(vector)).dual());\n        }\n\n        MAGNUM_DUAL_SUBCLASS_IMPLEMENTATION(DualComplex, Vector2, T)\n};\n\nMAGNUM_DUAL_OPERATOR_IMPLEMENTATION(DualComplex, Vector2, T)\n\nnamespace Implementation {\n    template<class T> struct StrictWeakOrdering<DualComplex<T>>: StrictWeakOrdering<Dual<Complex<T>>> {};\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Matrix4_h\n#define Magnum_Math_Matrix4_h\n\n#ifdef CORRADE_TARGET_WINDOWS /* I so HATE windef.h */\n#undef near\n#undef far\n#endif\n\nnamespace Magnum { namespace Math {\n\ntemplate<class T> class Matrix4: public Matrix4x4<T> {\n    public:\n        constexpr static Matrix4<T> translation(const Vector3<T>& vector) {\n            return {{      T(1),       T(0),       T(0), T(0)},\n                    {      T(0),       T(1),       T(0), T(0)},\n                    {      T(0),       T(0),       T(1), T(0)},\n                    {vector.x(), vector.y(), vector.z(), T(1)}};\n        }\n\n        constexpr static Matrix4<T> scaling(const Vector3<T>& vector) {\n            return {{vector.x(),       T(0),       T(0), T(0)},\n                    {      T(0), vector.y(),       T(0), T(0)},\n                    {      T(0),       T(0), vector.z(), T(0)},\n                    {      T(0),       T(0),       T(0), T(1)}};\n        }\n\n        static Matrix4<T> rotation(Rad<T> angle, const Vector3<T>& normalizedAxis);\n\n        static Matrix4<T> rotationX(Rad<T> angle);\n\n        static Matrix4<T> rotationY(Rad<T> angle);\n\n        static Matrix4<T> rotationZ(Rad<T> angle);\n\n        static Matrix4<T> reflection(const Vector3<T>& normal);\n\n        constexpr static Matrix4<T> shearingXY(T amountX, T amountY) {\n            return {{    (1),    T(0), T(0), T(0)},\n                    {    (0),    T(1), T(0), T(0)},\n                    {amountX, amountY, T(1), T(0)},\n                    {    (0),    T(0), T(0), T(1)}};\n        }\n\n        constexpr static Matrix4<T> shearingXZ(T amountX, T amountZ) {\n            return {{   T(1), T(0),    T(0), T(0)},\n                    {amountX, T(1), amountZ, T(0)},\n                    {   T(0), T(0),    T(1), T(0)},\n                    {   T(0), T(0),    T(0), T(1)}};\n        }\n\n        constexpr static Matrix4<T> shearingYZ(T amountY, T amountZ) {\n            return {{T(1), amountY, amountZ, T(0)},\n                    {T(0),    T(1),    T(0), T(0)},\n                    {T(0),    T(0),    T(1), T(0)},\n                    {T(0),    T(0),    T(0), T(1)}};\n        }\n\n        static Matrix4<T> orthographicProjection(const Vector2<T>& size, T near, T far);\n\n        static Matrix4<T> perspectiveProjection(const Vector2<T>& size, T near, T far);\n\n        static Matrix4<T> perspectiveProjection(Rad<T> fov, T aspectRatio, T near, T far) {\n            return perspectiveProjection(T(2)*near*std::tan(T(fov)*T(0.5))*Vector2<T>::yScale(T(1)/aspectRatio), near, far);\n        }\n\n        static Matrix4<T> perspectiveProjection(const Vector2<T>& bottomLeft, const Vector2<T>& topRight, T near, T far);\n\n        static Matrix4<T> lookAt(const Vector3<T>& eye, const Vector3<T>& target, const Vector3<T>& up);\n\n        constexpr static Matrix4<T> from(const Matrix3x3<T>& rotationScaling, const Vector3<T>& translation) {\n            return {{rotationScaling[0], T(0)},\n                    {rotationScaling[1], T(0)},\n                    {rotationScaling[2], T(0)},\n                    {       translation, T(1)}};\n        }\n\n        constexpr /*implicit*/ Matrix4() noexcept: Matrix4x4<T>{IdentityInit, T(1)} {}\n\n        constexpr explicit Matrix4(IdentityInitT, T value = T{1}) noexcept: Matrix4x4<T>{IdentityInit, value} {}\n\n        constexpr explicit Matrix4(ZeroInitT) noexcept: Matrix4x4<T>{ZeroInit} {}\n\n        constexpr explicit Matrix4(NoInitT) noexcept: Matrix4x4<T>{NoInit} {}\n\n        constexpr /*implicit*/ Matrix4(const Vector4<T>& first, const Vector4<T>& second, const Vector4<T>& third, const Vector4<T>& fourth) noexcept: Matrix4x4<T>(first, second, third, fourth) {}\n\n        constexpr explicit Matrix4(T value) noexcept: Matrix4x4<T>{value} {}\n\n        template<class U> constexpr explicit Matrix4(const RectangularMatrix<4, 4, U>& other) noexcept: Matrix4x4<T>(other) {}\n\n        template<class U, class V = decltype(Implementation::RectangularMatrixConverter<4, 4, T, U>::from(std::declval<U>()))> constexpr explicit Matrix4(const U& other): Matrix4x4<T>(Implementation::RectangularMatrixConverter<4, 4, T, U>::from(other)) {}\n\n        template<std::size_t otherSize> constexpr explicit Matrix4(const RectangularMatrix<otherSize, otherSize, T>& other) noexcept: Matrix4x4<T>{other} {}\n\n        constexpr /*implicit*/ Matrix4(const RectangularMatrix<4, 4, T>& other) noexcept: Matrix4x4<T>(other) {}\n\n        bool isRigidTransformation() const {\n            return rotationScaling().isOrthogonal() && row(3) == Vector4<T>(T(0), T(0), T(0), T(1));\n        }\n\n        constexpr Matrix3x3<T> rotationScaling() const {\n            return {(*this)[0].xyz(),\n                    (*this)[1].xyz(),\n                    (*this)[2].xyz()};\n        }\n\n        Matrix3x3<T> rotationShear() const {\n            return {(*this)[0].xyz().normalized(),\n                    (*this)[1].xyz().normalized(),\n                    (*this)[2].xyz().normalized()};\n        }\n\n        Matrix3x3<T> rotation() const;\n\n        Matrix3x3<T> rotationNormalized() const;\n\n        Vector3<T> scalingSquared() const {\n            return {(*this)[0].xyz().dot(),\n                    (*this)[1].xyz().dot(),\n                    (*this)[2].xyz().dot()};\n        }\n\n        Vector3<T> scaling() const {\n            return {(*this)[0].xyz().length(),\n                    (*this)[1].xyz().length(),\n                    (*this)[2].xyz().length()};\n        }\n\n        T uniformScalingSquared() const;\n\n        T uniformScaling() const { return std::sqrt(uniformScalingSquared()); }\n\n        Matrix3x3<T> normalMatrix() const {\n            return Matrix3x3<T>{(*this)[0].xyz(),\n                                (*this)[1].xyz(),\n                                (*this)[2].xyz()}.comatrix();\n        }\n\n        Vector3<T>& right() { return (*this)[0].xyz(); }\n        constexpr Vector3<T> right() const { return (*this)[0].xyz(); }\n\n        Vector3<T>& up() { return (*this)[1].xyz(); }\n        constexpr Vector3<T> up() const { return (*this)[1].xyz(); }\n\n        Vector3<T>& backward() { return (*this)[2].xyz(); }\n        constexpr Vector3<T> backward() const { return (*this)[2].xyz(); }\n\n        Vector3<T>& translation() { return (*this)[3].xyz(); }\n        constexpr Vector3<T> translation() const { return (*this)[3].xyz(); }\n\n        Matrix4<T> invertedRigid() const;\n\n        Vector3<T> transformVector(const Vector3<T>& vector) const {\n            return ((*this)*Vector4<T>(vector, T(0))).xyz();\n        }\n\n        Vector3<T> transformPoint(const Vector3<T>& vector) const {\n            const Vector4<T> transformed{(*this)*Vector4<T>(vector, T(1))};\n            return transformed.xyz()/transformed.w();\n        }\n\n        MAGNUM_RECTANGULARMATRIX_SUBCLASS_IMPLEMENTATION(4, 4, Matrix4<T>)\n        MAGNUM_MATRIX_SUBCLASS_IMPLEMENTATION(4, Matrix4, Vector4)\n};\n\nMAGNUM_MATRIXn_OPERATOR_IMPLEMENTATION(4, Matrix4)\n\ntemplate<class T> Matrix4<T> Matrix4<T>::rotation(const Rad<T> angle, const Vector3<T>& normalizedAxis) {\n    CORRADE_ASSERT(normalizedAxis.isNormalized(),\n        \"Math::Matrix4::rotation(): axis\" << normalizedAxis << \"is not normalized\", {});\n\n    const T sine = std::sin(T(angle));\n    const T cosine = std::cos(T(angle));\n    const T oneMinusCosine = T(1) - cosine;\n\n    const T xx = normalizedAxis.x()*normalizedAxis.x();\n    const T xy = normalizedAxis.x()*normalizedAxis.y();\n    const T xz = normalizedAxis.x()*normalizedAxis.z();\n    const T yy = normalizedAxis.y()*normalizedAxis.y();\n    const T yz = normalizedAxis.y()*normalizedAxis.z();\n    const T zz = normalizedAxis.z()*normalizedAxis.z();\n\n    return {\n        {cosine + xx*oneMinusCosine,\n            xy*oneMinusCosine + normalizedAxis.z()*sine,\n                xz*oneMinusCosine - normalizedAxis.y()*sine,\n                   T(0)},\n        {xy*oneMinusCosine - normalizedAxis.z()*sine,\n            cosine + yy*oneMinusCosine,\n                yz*oneMinusCosine + normalizedAxis.x()*sine,\n                   T(0)},\n        {xz*oneMinusCosine + normalizedAxis.y()*sine,\n            yz*oneMinusCosine - normalizedAxis.x()*sine,\n                cosine + zz*oneMinusCosine,\n                   T(0)},\n        {T(0), T(0), T(0), T(1)}\n    };\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::rotationX(const Rad<T> angle) {\n    const T sine = std::sin(T(angle));\n    const T cosine = std::cos(T(angle));\n\n    return {{T(1),   T(0),   T(0), T(0)},\n            {T(0), cosine,   sine, T(0)},\n            {T(0),  -sine, cosine, T(0)},\n            {T(0),   T(0),   T(0), T(1)}};\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::rotationY(const Rad<T> angle) {\n    const T sine = std::sin(T(angle));\n    const T cosine = std::cos(T(angle));\n\n    return {{cosine, T(0),  -sine, T(0)},\n            {  T(0), T(1),   T(0), T(0)},\n            {  sine, T(0), cosine, T(0)},\n            {  T(0), T(0),   T(0), T(1)}};\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::rotationZ(const Rad<T> angle) {\n    const T sine = std::sin(T(angle));\n    const T cosine = std::cos(T(angle));\n\n    return {{cosine,   sine, T(0), T(0)},\n            { -sine, cosine, T(0), T(0)},\n            {  T(0),   T(0), T(1), T(0)},\n            {  T(0),   T(0), T(0), T(1)}};\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::reflection(const Vector3<T>& normal) {\n    CORRADE_ASSERT(normal.isNormalized(),\n        \"Math::Matrix4::reflection(): normal\" << normal << \"is not normalized\", {});\n    return from(Matrix3x3<T>() - T(2)*normal*RectangularMatrix<1, 3, T>(normal).transposed(), {});\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::orthographicProjection(const Vector2<T>& size, const T near, const T far) {\n    const Vector2<T> xyScale = T(2.0)/size;\n    const T zScale = T(2.0)/(near-far);\n\n    return {{xyScale.x(),        T(0),             T(0), T(0)},\n            {       T(0), xyScale.y(),             T(0), T(0)},\n            {       T(0),        T(0),           zScale, T(0)},\n            {       T(0),        T(0), near*zScale-T(1), T(1)}};\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::perspectiveProjection(const Vector2<T>& size, const T near, const T far) {\n    const Vector2<T> xyScale = 2*near/size;\n\n    T m22, m32;\n    if(far == Constants<T>::inf()) {\n        m22 = T(-1);\n        m32 = T(-2)*near;\n    } else {\n        const T zScale = T(1.0)/(near-far);\n        m22 = (far+near)*zScale;\n        m32 = T(2)*far*near*zScale;\n    }\n\n    return {{xyScale.x(),        T(0), T(0),  T(0)},\n            {       T(0), xyScale.y(), T(0),  T(0)},\n            {       T(0),        T(0), m22,  T(-1)},\n            {       T(0),        T(0), m32,  T(0)}};\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::perspectiveProjection(const Vector2<T>& bottomLeft, const Vector2<T>& topRight, const T near, const T far) {\n    const Vector2<T> xyDifference = topRight - bottomLeft;\n    const Vector2<T> xyScale = 2*near/xyDifference;\n    const Vector2<T> xyOffset = (topRight + bottomLeft)/xyDifference;\n\n    T m22, m32;\n    if(far == Constants<T>::inf()) {\n        m22 = T(-1);\n        m32 = T(-2)*near;\n    } else {\n        const T zScale = T(1.0)/(near-far);\n        m22 = (far+near)*zScale;\n        m32 = T(2)*far*near*zScale;\n    }\n\n    return {{ xyScale.x(),         T(0), T(0),  T(0)},\n            {        T(0),  xyScale.y(), T(0),  T(0)},\n            {xyOffset.x(), xyOffset.y(), m22,  T(-1)},\n            {        T(0),         T(0), m32,  T(0)}};\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::lookAt(const Vector3<T>& eye, const Vector3<T>& target, const Vector3<T>& up) {\n    const Vector3<T> backward = (eye - target).normalized();\n    const Vector3<T> right = cross(up, backward).normalized();\n    const Vector3<T> realUp = cross(backward, right);\n    return from({right, realUp, backward}, eye);\n}\n\ntemplate<class T> Matrix3x3<T> Matrix4<T>::rotation() const {\n    Matrix3x3<T> rotation{(*this)[0].xyz().normalized(),\n                          (*this)[1].xyz().normalized(),\n                          (*this)[2].xyz().normalized()};\n    CORRADE_ASSERT(rotation.isOrthogonal(),\n        \"Math::Matrix4::rotation(): the normalized rotation part is not orthogonal:\" << Corrade::Utility::Debug::newline << rotation, {});\n    return rotation;\n}\n\ntemplate<class T> Matrix3x3<T> Matrix4<T>::rotationNormalized() const {\n    Matrix3x3<T> rotation{(*this)[0].xyz(),\n                          (*this)[1].xyz(),\n                          (*this)[2].xyz()};\n    CORRADE_ASSERT(rotation.isOrthogonal(),\n        \"Math::Matrix4::rotationNormalized(): the rotation part is not orthogonal:\" << Corrade::Utility::Debug::newline << rotation, {});\n    return rotation;\n}\n\ntemplate<class T> T Matrix4<T>::uniformScalingSquared() const {\n    const T scalingSquared = (*this)[0].xyz().dot();\n    CORRADE_ASSERT(TypeTraits<T>::equals((*this)[1].xyz().dot(), scalingSquared) &&\n                   TypeTraits<T>::equals((*this)[2].xyz().dot(), scalingSquared),\n        \"Math::Matrix4::uniformScaling(): the matrix doesn't have uniform scaling:\" << Corrade::Utility::Debug::newline << rotationScaling(), {});\n    return scalingSquared;\n}\n\ntemplate<class T> Matrix4<T> Matrix4<T>::invertedRigid() const {\n    CORRADE_ASSERT(isRigidTransformation(),\n        \"Math::Matrix4::invertedRigid(): the matrix doesn't represent a rigid transformation:\" << Corrade::Utility::Debug::newline << *this, {});\n\n    Matrix3x3<T> inverseRotation = rotationScaling().transposed();\n    return from(inverseRotation, inverseRotation*-translation());\n}\n\nnamespace Implementation {\n    template<class T> struct StrictWeakOrdering<Matrix4<T>>: StrictWeakOrdering<RectangularMatrix<4, 4, T>> {};\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_DualQuaternion_h\n#define Magnum_Math_DualQuaternion_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<class, class> struct DualQuaternionConverter;\n}\n\ntemplate<class T> inline DualQuaternion<T> sclerp(const DualQuaternion<T>& normalizedA, const DualQuaternion<T>& normalizedB, const T t) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::sclerp(): dual quaternions\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    const T cosHalfAngle = dot(normalizedA.real(), normalizedB.real());\n\n    if(std::abs(cosHalfAngle) >= T(1) - TypeTraits<T>::epsilon())\n        return DualQuaternion<T>::translation(Implementation::lerp(normalizedA.translation(), normalizedB.translation(), t))*DualQuaternion<T>{normalizedA.real()};\n\n    const DualQuaternion<T> diff = normalizedA.quaternionConjugated()*normalizedB;\n    const Quaternion<T>& l = diff.real();\n    const Quaternion<T>& m = diff.dual();\n\n    const T invr = l.vector().lengthInverted();\n    const Dual<T> aHalf{std::acos(l.scalar()), -m.scalar()*invr};\n\n    const Vector3<T> direction = l.vector()*invr;\n    const Vector3<T> moment = (m.vector() - direction*(aHalf.dual()*l.scalar()))*invr;\n    const Dual<Vector3<T>> n{direction, moment};\n\n    const std::pair<Dual<T>, Dual<T>> sincos = Math::sincos(t*Dual<Rad<T>>(aHalf));\n    return normalizedA*DualQuaternion<T>{n*sincos.first, sincos.second};\n}\n\ntemplate<class T> inline DualQuaternion<T> sclerpShortestPath(const DualQuaternion<T>& normalizedA, const DualQuaternion<T>& normalizedB, const T t) {\n    CORRADE_ASSERT(normalizedA.isNormalized() && normalizedB.isNormalized(),\n        \"Math::sclerp(): dual quaternions\" << normalizedA << \"and\" << normalizedB << \"are not normalized\", {});\n    const T cosHalfAngle = dot(normalizedA.real(), normalizedB.real());\n\n    if(std::abs(cosHalfAngle) >= T(1) - TypeTraits<T>::epsilon())\n        return DualQuaternion<T>::translation(Implementation::lerp(normalizedA.translation(), normalizedB.translation(), t))*DualQuaternion<T>{normalizedA.real()};\n\n    const DualQuaternion<T> diff = normalizedA.quaternionConjugated()*(cosHalfAngle < T(0) ? -normalizedB : normalizedB);\n    const Quaternion<T>& l = diff.real();\n    const Quaternion<T>& m = diff.dual();\n\n    const T invr = l.vector().lengthInverted();\n    const Dual<T> aHalf{std::acos(l.scalar()), -m.scalar()*invr};\n\n    const Vector3<T> direction = l.vector()*invr;\n    const Vector3<T> moment = (m.vector() - direction*(aHalf.dual()*l.scalar()))*invr;\n    const Dual<Vector3<T>> n{direction, moment};\n\n    const std::pair<Dual<T>, Dual<T>> sincos = Math::sincos(t*Dual<Rad<T>>(aHalf));\n    return normalizedA*DualQuaternion<T>{n*sincos.first, sincos.second};\n}\n\ntemplate<class T> class DualQuaternion: public Dual<Quaternion<T>> {\n    public:\n        typedef T Type;\n\n        static DualQuaternion<T> rotation(Rad<T> angle, const Vector3<T>& normalizedAxis) {\n            return {Quaternion<T>::rotation(angle, normalizedAxis), {{}, T(0)}};\n        }\n\n        static DualQuaternion<T> translation(const Vector3<T>& vector) {\n            return {{}, {vector/T(2), T(0)}};\n        }\n\n        static DualQuaternion<T> fromMatrix(const Matrix4<T>& matrix) {\n            CORRADE_ASSERT(matrix.isRigidTransformation(),\n                \"Math::DualQuaternion::fromMatrix(): the matrix doesn't represent a rigid transformation:\" << Corrade::Utility::Debug::newline << matrix, {});\n\n            Quaternion<T> q = Implementation::quaternionFromMatrix(matrix.rotationScaling());\n            return {q, Quaternion<T>(matrix.translation()/2)*q};\n        }\n\n        constexpr /*implicit*/ DualQuaternion() noexcept: Dual<Quaternion<T>>{{}, {{}, T(0)}} {}\n\n        constexpr explicit DualQuaternion(IdentityInitT) noexcept: Dual<Quaternion<T>>{{}, {{}, T(0)}} {}\n\n        constexpr explicit DualQuaternion(ZeroInitT) noexcept: Dual<Quaternion<T>>{Quaternion<T>{ZeroInit}, Quaternion<T>{ZeroInit}} {}\n\n        explicit DualQuaternion(NoInitT) noexcept: Dual<Quaternion<T>>{NoInit} {}\n\n        constexpr /*implicit*/ DualQuaternion(const Quaternion<T>& real, const Quaternion<T>& dual = Quaternion<T>({}, T(0))) noexcept: Dual<Quaternion<T>>(real, dual) {}\n\n        constexpr /*implicit*/ DualQuaternion(const Dual<Vector3<T>>& vector, const Dual<T>& scalar) noexcept: Dual<Quaternion<T>>{{vector.real(), scalar.real()}, {vector.dual(), scalar.dual()}} {}\n\n        constexpr explicit DualQuaternion(const Vector3<T>& vector) noexcept: Dual<Quaternion<T>>({}, {vector, T(0)}) {}\n\n        template<class U> constexpr explicit DualQuaternion(const DualQuaternion<U>& other) noexcept: Dual<Quaternion<T>>(other) {}\n\n        template<class U, class V = decltype(Implementation::DualQuaternionConverter<T, U>::from(std::declval<U>()))> constexpr explicit DualQuaternion(const U& other): DualQuaternion{Implementation::DualQuaternionConverter<T, U>::from(other)} {}\n\n        constexpr /*implicit*/ DualQuaternion(const Dual<Quaternion<T>>& other) noexcept: Dual<Quaternion<T>>(other) {}\n\n        template<class U, class V = decltype(Implementation::DualQuaternionConverter<T, U>::to(std::declval<DualQuaternion<T>>()))> constexpr explicit operator U() const {\n            return Implementation::DualQuaternionConverter<T, U>::to(*this);\n        }\n\n        T* data() { return Dual<Quaternion<T>>::data()->data(); }\n        constexpr const T* data() const { return Dual<Quaternion<T>>::data()->data(); }\n\n        bool isNormalized() const {\n            Dual<T> a = lengthSquared();\n            return Implementation::isNormalizedSquared(a.real()) &&\n                   TypeTraits<T>::equalsZero(a.dual(), Math::max(Math::abs(Math::Dual<Quaternion<T>>::dual().vector()).max(), Math::abs(Math::Dual<Quaternion<T>>::dual().scalar())));\n        }\n\n        constexpr Quaternion<T> rotation() const {\n            return Dual<Quaternion<T>>::real();\n        }\n\n        Vector3<T> translation() const {\n            return (Dual<Quaternion<T>>::dual()*Dual<Quaternion<T>>::real().conjugated()).vector()*T(2);\n        }\n\n        Matrix4<T> toMatrix() const {\n            return Matrix4<T>::from(Dual<Quaternion<T>>::real().toMatrix(), translation());\n        }\n\n        DualQuaternion<T> quaternionConjugated() const {\n            return {Dual<Quaternion<T>>::real().conjugated(), Dual<Quaternion<T>>::dual().conjugated()};\n        }\n\n        DualQuaternion<T> dualConjugated() const {\n            return Dual<Quaternion<T>>::conjugated();\n        }\n\n        DualQuaternion<T> conjugated() const {\n            return {Dual<Quaternion<T>>::real().conjugated(), {Dual<Quaternion<T>>::dual().vector(), -Dual<Quaternion<T>>::dual().scalar()}};\n        }\n\n        Dual<T> lengthSquared() const {\n            return {Dual<Quaternion<T>>::real().dot(), T(2)*dot(Dual<Quaternion<T>>::real(), Dual<Quaternion<T>>::dual())};\n        }\n\n        Dual<T> length() const {\n            return Math::sqrt(lengthSquared());\n        }\n\n        DualQuaternion<T> normalized() const {\n            return (*this)/length();\n        }\n\n        DualQuaternion<T> inverted() const {\n            return quaternionConjugated()/lengthSquared();\n        }\n\n        DualQuaternion<T> invertedNormalized() const {\n            CORRADE_ASSERT(isNormalized(),\n                \"Math::DualQuaternion::invertedNormalized():\" << *this << \"is not normalized\", {});\n            return quaternionConjugated();\n        }\n\n        Vector3<T> transformPoint(const Vector3<T>& vector) const {\n            return ((*this)*DualQuaternion<T>(vector)*inverted().dualConjugated()).dual().vector();\n        }\n\n        Vector3<T> transformPointNormalized(const Vector3<T>& vector) const {\n            CORRADE_ASSERT(isNormalized(),\n                \"Math::DualQuaternion::transformPointNormalized():\" << *this << \"is not normalized\", {});\n            return ((*this)*DualQuaternion<T>(vector)*conjugated()).dual().vector();\n        }\n\n        MAGNUM_DUAL_SUBCLASS_IMPLEMENTATION(DualQuaternion, Quaternion, T)\n        MAGNUM_DUAL_SUBCLASS_MULTIPLICATION_IMPLEMENTATION(DualQuaternion, Quaternion)\n};\n\nMAGNUM_DUAL_OPERATOR_IMPLEMENTATION(DualQuaternion, Quaternion, T)\n\nnamespace Implementation {\n    template<class T> struct StrictWeakOrdering<DualQuaternion<T>>: StrictWeakOrdering<Dual<Quaternion<T>>> {};\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Frustum_h\n#define Magnum_Math_Frustum_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<class, class> struct FrustumConverter;\n}\n\ntemplate<class T> class Frustum {\n    public:\n        static Frustum<T> fromMatrix(const Matrix4<T>& m) {\n            return {m.row(3) + m.row(0),\n                    m.row(3) - m.row(0),\n                    m.row(3) + m.row(1),\n                    m.row(3) - m.row(1),\n                    m.row(3) + m.row(2),\n                    m.row(3) - m.row(2)};\n        }\n\n        constexpr /*implicit*/ Frustum() noexcept: Frustum<T>{IdentityInit} {}\n\n        constexpr explicit Frustum(IdentityInitT) noexcept;\n\n        explicit Frustum(NoInitT) noexcept: _data{Vector4<T>{NoInit}, Vector4<T>{NoInit}, Vector4<T>{NoInit}, Vector4<T>{NoInit}, Vector4<T>{NoInit}, Vector4<T>{NoInit}} {}\n\n        constexpr /*implicit*/ Frustum(const Vector4<T>& left, const Vector4<T>& right, const Vector4<T>& bottom, const Vector4<T>& top, const Vector4<T>& near, const Vector4<T>& far) noexcept: _data{left, right, bottom, top, near, far} {}\n\n        template<class U> constexpr explicit Frustum(const Frustum<U>& other) noexcept;\n\n        template<class U, class V = decltype(Implementation::FrustumConverter<T, U>::from(std::declval<U>()))> constexpr explicit Frustum(const U& other) noexcept: Frustum<T>{Implementation::FrustumConverter<T, U>::from(other)} {}\n\n        template<class U, class V = decltype(Implementation::FrustumConverter<T, U>::to(std::declval<Frustum<T>>()))> constexpr explicit operator U() const {\n            return Implementation::FrustumConverter<T, U>::to(*this);\n        }\n\n        bool operator==(const Frustum<T>& other) const {\n            for(std::size_t i = 0; i != 6; ++i)\n                if(_data[i] != other._data[i]) return false;\n\n            return true;\n        }\n\n        bool operator!=(const Frustum<T>& other) const {\n            return !operator==(other);\n        }\n\n        T* data() { return _data[0].data(); }\n        constexpr const T* data() const { return _data[0].data(); }\n\n        constexpr const Vector4<T>& operator[](std::size_t i) const {\n            return CORRADE_CONSTEXPR_ASSERT(i < 6, \"Math::Frustum::operator[](): index\" << i << \"out of range\"), _data[i];\n        }\n\n        Vector4<T>* begin() { return _data; }\n        constexpr const Vector4<T>* begin() const { return _data; }\n        constexpr const Vector4<T>* cbegin() const { return _data; }\n\n        Vector4<T>* end() { return _data + 6; }\n        constexpr const Vector4<T>* end() const { return _data + 6; }\n        constexpr const Vector4<T>* cend() const { return _data + 6; }\n\n        constexpr Vector4<T> left() const { return _data[0]; }\n\n        constexpr Vector4<T> right() const { return _data[1]; }\n\n        constexpr Vector4<T> bottom() const { return _data[2]; }\n\n        constexpr Vector4<T> top() const { return _data[3]; }\n\n        constexpr Vector4<T> near() const { return _data[4]; }\n\n        constexpr Vector4<T> far() const { return _data[5]; }\n\n    private:\n        Vector4<T> _data[6];\n};\n\ntemplate<class T> constexpr Frustum<T>::Frustum(IdentityInitT) noexcept: _data{\n    { 1.0f,  0.0f,  0.0f, 1.0f},\n    {-1.0f,  0.0f,  0.0f, 1.0f},\n    { 0.0f,  1.0f,  0.0f, 1.0f},\n    { 0.0f, -1.0f,  0.0f, 1.0f},\n    { 0.0f,  0.0f,  1.0f, 1.0f},\n    { 0.0f,  0.0f, -1.0f, 1.0f}} {}\n\ntemplate<class T> template<class U> constexpr Frustum<T>::Frustum(const Frustum<U>& other) noexcept: _data{\n    Vector4<T>{other[0]},\n    Vector4<T>{other[1]},\n    Vector4<T>{other[2]},\n    Vector4<T>{other[3]},\n    Vector4<T>{other[4]},\n    Vector4<T>{other[5]}} {}\n\nnamespace Implementation {\n\ntemplate<class T> struct StrictWeakOrdering<Frustum<T>> {\n    bool operator()(const Frustum<T>& a, const Frustum<T>& b) const {\n        StrictWeakOrdering<Vector<4, T>> o;\n        for(std::size_t i = 0; i < 6; ++i) {\n            if(o(a[i], b[i]))\n                return true;\n            if(o(b[i], a[i]))\n                return false;\n        }\n\n        return false;\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Half_h\n#define Magnum_Math_Half_h\n\nnamespace Magnum { namespace Math {\n\nclass Half {\n    public:\n        constexpr /*implicit*/ Half() noexcept: _data{} {}\n\n        constexpr explicit Half(ZeroInitT) noexcept: _data{} {}\n\n        constexpr explicit Half(UnsignedShort data) noexcept: _data{data} {}\n\n        explicit Half(Float value) noexcept: _data{packHalf(value)} {}\n\n        explicit Half(NoInitT) noexcept {}\n\n        constexpr bool operator==(Half other) const {\n            return (((      _data & 0x7c00) == 0x7c00 && (      _data & 0x03ff)) ||\n                    ((other._data & 0x7c00) == 0x7c00 && (other._data & 0x03ff))) ?\n                false : _data == other._data;\n        }\n\n        constexpr bool operator!=(Half other) const {\n            return !operator==(other);\n        }\n\n        constexpr Half operator+() const { return *this; }\n\n        constexpr Half operator-() const {\n            return Half{UnsignedShort(_data ^ (1 << 15))};\n        }\n\n        constexpr explicit operator UnsignedShort() const { return _data; }\n\n        explicit operator Float() const { return unpackHalf(_data); }\n\n        constexpr UnsignedShort data() const { return _data; }\n\n    private:\n        UnsignedShort _data;\n};\n\nnamespace Literals {\n\ninline Half operator \"\" _h(long double value) { return Half(Float(value)); }\n\n}\n\nnamespace Implementation {\n\ntemplate<> struct StrictWeakOrdering<Half> {\n    bool operator()(Half a, Half b) const {\n        return a.data() < b.data();\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Range_h\n#define Magnum_Math_Range_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n    template<UnsignedInt, class> struct RangeTraits;\n\n    template<class T> struct RangeTraits<1, T> { typedef T Type; };\n    template<class T> struct RangeTraits<2, T> { typedef Vector2<T> Type; };\n    template<class T> struct RangeTraits<3, T> { typedef Vector3<T> Type; };\n\n    template<UnsignedInt, class, class> struct RangeConverter;\n}\n\ntemplate<UnsignedInt dimensions, class T> class Range {\n    template<UnsignedInt, class> friend class Range;\n\n    public:\n        typedef typename Implementation::RangeTraits<dimensions, T>::Type VectorType;\n\n        static Range<dimensions, T> fromSize(const VectorType& min, const VectorType& size) {\n            return {min, min+size};\n        }\n\n        static Range<dimensions, T> fromCenter(const VectorType& center, const VectorType& halfSize) {\n            return {center - halfSize, center + halfSize};\n        }\n\n        constexpr /*implicit*/ Range() noexcept: Range<dimensions, T>{ZeroInit, typename std::conditional<dimensions == 1, void*, ZeroInitT*>::type{}} {}\n\n        constexpr explicit Range(ZeroInitT) noexcept: Range<dimensions, T>{ZeroInit, typename std::conditional<dimensions == 1, void*, ZeroInitT*>::type{}} {}\n\n        explicit Range(NoInitT) noexcept: Range<dimensions, T>{NoInit, typename std::conditional<dimensions == 1, void*, NoInitT*>::type{}} {}\n\n        constexpr /*implicit*/ Range(const VectorType& min, const VectorType& max) noexcept: _min{min}, _max{max} {}\n\n        /*implicit*/ Range(const std::pair<VectorType, VectorType>& minmax) noexcept:\n            _min{minmax.first}, _max{minmax.second} {}\n\n        template<UnsignedInt d = dimensions, class = typename std::enable_if<d != 1>::type>\n        /*implicit*/ Range(const std::pair<Vector<dimensions, T>, Vector<dimensions, T>>& minmax) noexcept: _min{minmax.first}, _max{minmax.second} {}\n\n        template<class U> constexpr explicit Range(const Range<dimensions, U>& other) noexcept: _min(other._min), _max(other._max) {}\n\n        template<class U, class V = decltype(Implementation::RangeConverter<dimensions, T, U>::from(std::declval<U>()))> constexpr explicit Range(const U& other): Range{Implementation::RangeConverter<dimensions, T, U>::from(other)} {}\n\n        constexpr /*implicit*/ Range(const Range<dimensions, T>&) noexcept = default;\n\n        template<class U, class V = decltype(Implementation::RangeConverter<dimensions, T, U>::to(std::declval<Range<dimensions, T>>()))> constexpr explicit operator U() const {\n            return Implementation::RangeConverter<dimensions, T, U>::to(*this);\n        }\n\n        bool operator==(const Range<dimensions, T>& other) const;\n\n        bool operator!=(const Range<dimensions, T>& other) const {\n            return !operator==(other);\n        }\n\n        T* data() {\n            return dataInternal(typename std::conditional<dimensions == 1, void*, T*>::type{});\n        }\n        constexpr const T* data() const {\n            return dataInternal(typename std::conditional<dimensions == 1, void*, T*>::type{});\n        }\n\n        VectorType& min() { return _min; }\n        constexpr const VectorType min() const { return _min; }\n\n        VectorType& max() { return _max; }\n        constexpr const VectorType max() const { return _max; }\n\n        VectorType size() const { return _max - _min; }\n\n        VectorType center() const { return (_min + _max)/T(2); }\n\n        Range<dimensions, T> translated(const VectorType& vector) const {\n            return {_min + vector, _max + vector};\n        }\n\n        Range<dimensions, T> padded(const VectorType& padding) const {\n            return {_min - padding, _max + padding};\n        }\n\n        Range<dimensions, T> scaled(const VectorType& scaling) const {\n            return {_min*scaling, _max*scaling};\n        }\n\n        Range<dimensions, T> scaledFromCenter(const VectorType& scaling) const {\n            return fromCenter(center(), size()*scaling/T(2));\n        }\n\n        bool contains(const VectorType& b) const {\n            return (Vector<dimensions, T>{b} >= _min).all() &&\n                   (Vector<dimensions, T>{b} < _max).all();\n        }\n\n        bool contains(const Range<dimensions, T>& b) const {\n            return (Vector<dimensions, T>{b._min} >= _min).all() &&\n                   (Vector<dimensions, T>{b._max} <= _max).all();\n        }\n\n    private:\n        constexpr explicit Range(ZeroInitT, ZeroInitT*) noexcept: _min{ZeroInit}, _max{ZeroInit} {}\n        constexpr explicit Range(ZeroInitT, void*) noexcept: _min{T(0)}, _max{T(0)} {}\n\n        explicit Range(NoInitT, NoInitT*) noexcept: _min{NoInit}, _max{NoInit} {}\n        explicit Range(NoInitT, void*) noexcept {}\n\n        constexpr const VectorType* dataInternal(void*) const { return &_min; }\n        VectorType* dataInternal(void*) { return &_min; }\n        constexpr const T* dataInternal(T*) const { return _min.data(); }\n        T* dataInternal(T*) { return _min.data(); }\n\n        VectorType _min, _max;\n};\n\n#define MAGNUM_RANGE_SUBCLASS_IMPLEMENTATION(dimensions, Type, VectorType)  \\\n    static Type<T> fromSize(const VectorType<T>& min, const VectorType<T>& size) { \\\n        return Range<dimensions, T>::fromSize(min, size);                   \\\n    }                                                                       \\\n    static Type<T> fromCenter(const VectorType<T>& center, const VectorType<T>& halfSize) { \\\n        return Range<dimensions, T>::fromCenter(center, halfSize);          \\\n    }                                                                       \\\n                                                                            \\\n    Type<T> translated(const VectorType<T>& vector) const {                 \\\n        return Range<dimensions, T>::translated(vector);                    \\\n    }                                                                       \\\n    Type<T> padded(const VectorType<T>& padding) const {                    \\\n        return Range<dimensions, T>::padded(padding);                       \\\n    }                                                                       \\\n    Type<T> scaled(const VectorType<T>& scaling) const {                    \\\n        return Range<dimensions, T>::scaled(scaling);                       \\\n    }                                                                       \\\n    Type<T> scaledFromCenter(const VectorType<T>& scaling) const {          \\\n        return Range<dimensions, T>::scaledFromCenter(scaling);             \\\n    }\n\n#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */\ntemplate<class T> using Range1D = Range<1, T>;\n#endif\n\ntemplate<class T> class Range2D: public Range<2, T> {\n    public:\n        constexpr /*implicit*/ Range2D() noexcept: Range<2, T>{ZeroInit} {}\n\n        constexpr explicit Range2D(ZeroInitT) noexcept: Range<2, T>{ZeroInit} {}\n\n        explicit Range2D(NoInitT) noexcept: Range<2, T>{NoInit} {}\n\n        constexpr /*implicit*/ Range2D(const Vector2<T>& min, const Vector2<T>& max) noexcept: Range<2, T>(min, max) {}\n\n        template<class U> constexpr explicit Range2D(const Range2D<U>& other) noexcept: Range<2, T>(other) {}\n\n        template<class U, class V =\n            #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Causes ICE */\n            decltype(Implementation::RangeConverter<2, T, U>::from(std::declval<U>()))\n            #else\n            decltype(Implementation::RangeConverter<2, T, U>())\n            #endif\n            >\n        constexpr explicit Range2D(const U& other): Range<2, T>{Implementation::RangeConverter<2, T, U>::from(other)} {}\n\n        constexpr /*implicit*/ Range2D(const Range<2, T>& other) noexcept: Range<2, T>(other) {}\n\n        Vector2<T>& bottomLeft() { return Range<2, T>::min(); }\n        constexpr Vector2<T> bottomLeft() const { return Range<2, T>::min(); }\n\n        constexpr Vector2<T> bottomRight() const {\n            return {Range<2, T>::max().x(), Range<2, T>::min().y()};\n        }\n\n        constexpr Vector2<T> topLeft() const {\n            return {Range<2, T>::min().x(), Range<2, T>::max().y()};\n        }\n\n        Vector2<T>& topRight() { return Range<2, T>::max(); }\n        constexpr Vector2<T> topRight() const { return Range<2, T>::max(); }\n\n        T& left() { return Range<2, T>::min().x(); }\n        constexpr T left() const { return Range<2, T>::min().x(); }\n\n        T& right() { return Range<2, T>::max().x(); }\n        constexpr T right() const { return Range<2, T>::max().x(); }\n\n        T& bottom() { return Range<2, T>::min().y(); }\n        constexpr T bottom() const { return Range<2, T>::min().y(); }\n\n        T& top() { return Range<2, T>::max().y(); }\n        constexpr T top() const { return Range<2, T>::max().y(); }\n\n        constexpr Range<1, T> x() const {\n            return {Range<2, T>::min().x(), Range<2, T>::max().x()};\n        }\n\n        constexpr Range<1, T> y() const {\n            return {Range<2, T>::min().y(), Range<2, T>::max().y()};\n        }\n\n        T sizeX() const {\n            return Range<2, T>::max().x() - Range<2, T>::min().x();\n        }\n\n        T sizeY() const {\n            return Range<2, T>::max().y() - Range<2, T>::min().y();\n        }\n\n        T centerX() const {\n            return (Range<2, T>::min().x() + Range<2, T>::max().x())/T(2);\n        }\n\n        T centerY() const {\n            return (Range<2, T>::min().y() + Range<2, T>::max().y())/T(2);\n        }\n\n        MAGNUM_RANGE_SUBCLASS_IMPLEMENTATION(2, Range2D, Vector2)\n};\n\ntemplate<class T> class Range3D: public Range<3, T> {\n    public:\n        constexpr /*implicit*/ Range3D() noexcept: Range<3, T>{ZeroInit} {}\n\n        constexpr explicit Range3D(ZeroInitT) noexcept: Range<3, T>{ZeroInit} {}\n\n        explicit Range3D(NoInitT) noexcept: Range<3, T>{NoInit} {}\n\n        constexpr /*implicit*/ Range3D(const Vector3<T>& min, const Vector3<T>& max) noexcept: Range<3, T>(min, max) {}\n\n        template<class U> constexpr explicit Range3D(const Range3D<U>& other) noexcept: Range<3, T>(other) {}\n\n        template<class U, class V = decltype(Implementation::RangeConverter<3, T, U>::from(std::declval<U>()))> constexpr explicit Range3D(const U& other) noexcept: Range<3, T>{Implementation::RangeConverter<3, T, U>::from(other)} {}\n\n        constexpr /*implicit*/ Range3D(const Range<3, T>& other) noexcept: Range<3, T>(other) {}\n\n        Vector3<T>& backBottomLeft() { return Range<3, T>::min(); }\n        constexpr Vector3<T> backBottomLeft() const { return Range<3, T>::min(); }\n\n        constexpr Vector3<T> backBottomRight() const {\n            return {Range<3, T>::max().x(), Range<3, T>::min().y(), Range<3, T>::min().z()};\n        }\n\n        constexpr Vector3<T> backTopLeft() const {\n            return {Range<3, T>::min().x(), Range<3, T>::max().y(), Range<3, T>::min().z()};\n        }\n\n        constexpr Vector3<T> backTopRight() const {\n            return {Range<3, T>::max().x(), Range<3, T>::max().y(), Range<3, T>::min().z()};\n        }\n\n        Vector3<T>& frontTopRight() { return Range<3, T>::max(); }\n        constexpr Vector3<T> frontTopRight() const { return Range<3, T>::max(); }\n\n        constexpr Vector3<T> frontTopLeft() const {\n            return {Range<3, T>::min().x(), Range<3, T>::max().y(), Range<3, T>::max().z()};\n        }\n\n        constexpr Vector3<T> frontBottomRight() const {\n            return {Range<3, T>::max().x(), Range<3, T>::min().y(), Range<3, T>::max().z()};\n        }\n\n        constexpr Vector3<T> frontBottomLeft() const {\n            return {Range<3, T>::min().x(), Range<3, T>::min().y(), Range<3, T>::max().z()};\n        }\n\n        T& left() { return Range<3, T>::min().x(); }\n        constexpr T left() const { return Range<3, T>::min().x(); }\n\n        T& right() { return Range<3, T>::max().x(); }\n        constexpr T right() const { return Range<3, T>::max().x(); }\n\n        T& bottom() { return Range<3, T>::min().y(); }\n        constexpr T bottom() const { return Range<3, T>::min().y(); }\n\n        T& top() { return Range<3, T>::max().y(); }\n        constexpr T top() const { return Range<3, T>::max().y(); }\n\n        T& back() { return Range<3, T>::min().z(); }\n        constexpr T back() const { return Range<3, T>::min().z(); }\n\n        T& front() { return Range<3, T>::max().z(); }\n        constexpr T front() const { return Range<3, T>::max().z(); }\n\n        constexpr Range<1, T> x() const {\n            return {Range<3, T>::min().x(), Range<3, T>::max().x()};\n        }\n\n        constexpr Range<1, T> y() const {\n            return {Range<3, T>::min().y(), Range<3, T>::max().y()};\n        }\n\n        constexpr Range<1, T> z() const {\n            return {Range<3, T>::min().z(), Range<3, T>::max().z()};\n        }\n\n        constexpr Range2D<T> xy() const {\n            return {Range<3, T>::min().xy(), Range<3, T>::max().xy()};\n        }\n\n        T sizeX() const {\n            return Range<3, T>::max().x() - Range<3, T>::min().x();\n        }\n\n        T sizeY() const {\n            return Range<3, T>::max().y() - Range<3, T>::min().y();\n        }\n\n        T sizeZ() const {\n            return Range<3, T>::max().z() - Range<3, T>::min().z();\n        }\n\n        T centerX() const {\n            return (Range<3, T>::min().x() + Range<3, T>::max().x())/T(2);\n        }\n\n        T centerY() const {\n            return (Range<3, T>::min().y() + Range<3, T>::max().y())/T(2);\n        }\n\n        T centerZ() const {\n            return (Range<3, T>::min().z() + Range<3, T>::max().z())/T(2);\n        }\n\n        MAGNUM_RANGE_SUBCLASS_IMPLEMENTATION(3, Range3D, Vector3)\n};\n\ntemplate<UnsignedInt dimensions, class T> inline Range<dimensions, T> join(const Range<dimensions, T>& a, const Range<dimensions, T>& b) {\n    if(a.min() == a.max()) return b;\n    if(b.min() == b.max()) return a;\n    return {min(a.min(), b.min()), max(a.max(), b.max())};\n}\n\ntemplate<UnsignedInt dimensions, class T> inline Range<dimensions, T> intersect(const Range<dimensions, T>& a, const Range<dimensions, T>& b) {\n    if(!intersects(a, b)) return {};\n    return {max(a.min(), b.min()), min(a.max(), b.max())};\n}\n\ntemplate<UnsignedInt dimensions, class T> inline bool intersects(const Range<dimensions, T>& a, const Range<dimensions, T>& b) {\n    return (Vector<dimensions, T>{a.max()} > b.min()).all() &&\n           (Vector<dimensions, T>{a.min()} < b.max()).all();\n}\n\ntemplate<UnsignedInt dimensions, class T> inline bool Range<dimensions, T>::operator==(const Range<dimensions, T>& other) const {\n    return TypeTraits<VectorType>::equals(_min, other._min) &&\n        TypeTraits<VectorType>::equals(_max, other._max);\n}\n\nnamespace Implementation {\n\ntemplate<UnsignedInt dimensions, class T> struct StrictWeakOrdering<Range<dimensions, T>> {\n    bool operator()(const Range<dimensions, T>& a, const Range<dimensions, T>& b) const {\n        StrictWeakOrdering<typename Range<dimensions, T>::VectorType> o;\n        if(o(a.min(), b.min()))\n            return true;\n        if(o(b.min(), a.min()))\n            return false;\n        return o(a.max(), b.max());\n    }\n};\n\n}\n\n}}\n\n#endif\n#ifndef Magnum_Math_Intersection_h\n#define Magnum_Math_Intersection_h\n\nnamespace Magnum { namespace Math { namespace Intersection {\n\ntemplate<class T> inline std::pair<T, T> lineSegmentLineSegment(const Vector2<T>& p, const Vector2<T>& r, const Vector2<T>& q, const Vector2<T>& s) {\n    const Vector2<T> qp = q - p;\n    const T rs = cross(r, s);\n    return {cross(qp, s)/rs, cross(qp, r)/rs};\n}\n\ntemplate<class T> inline T lineSegmentLine(const Vector2<T>& p, const Vector2<T>& r, const Vector2<T>& q, const Vector2<T>& s) {\n    return cross(q - p, s)/cross(r, s);\n}\n\ntemplate<class T> inline T planeLine(const Vector4<T>& plane, const Vector3<T>& p, const Vector3<T>& r) {\n    return (-plane.w() - dot(plane.xyz(), p))/dot(plane.xyz(), r);\n}\n\ntemplate<class T> bool pointFrustum(const Vector3<T>& point, const Frustum<T>& frustum);\n\ntemplate<class T> bool rangeFrustum(const Range3D<T>& range, const Frustum<T>& frustum);\n\ntemplate<class T> bool aabbFrustum(const Vector3<T>& aabbCenter, const Vector3<T>& aabbExtents, const Frustum<T>& frustum);\n\ntemplate<class T> bool sphereFrustum(const Vector3<T>& sphereCenter, T sphereRadius, const Frustum<T>& frustum);\n\ntemplate<class T> bool pointCone(const Vector3<T>& point, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, Rad<T> coneAngle);\n\ntemplate<class T> bool pointCone(const Vector3<T>& point, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, T tanAngleSqPlusOne);\n\ntemplate<class T> bool pointDoubleCone(const Vector3<T>& point, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, Rad<T> coneAngle);\n\ntemplate<class T> bool pointDoubleCone(const Vector3<T>& point, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, T tanAngleSqPlusOne);\n\ntemplate<class T> bool sphereConeView(const Vector3<T>& sphereCenter, T sphereRadius, const Matrix4<T>& coneView, Rad<T> coneAngle);\n\ntemplate<class T> bool sphereConeView(const Vector3<T>& sphereCenter, T sphereRadius, const Matrix4<T>& coneView, T sinAngle, T tanAngle);\n\ntemplate<class T> bool sphereCone(const Vector3<T>& sphereCenter, T sphereRadius, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, Rad<T> coneAngle);\n\ntemplate<class T> bool sphereCone(const Vector3<T>& sphereCenter, T sphereRadius, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, T sinAngle, T tanAngleSqPlusOne);\n\ntemplate<class T> bool aabbCone(const Vector3<T>& aabbCenter, const Vector3<T>& aabbExtents, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, Rad<T> coneAngle);\n\ntemplate<class T> bool aabbCone(const Vector3<T>& aabbCenter, const Vector3<T>& aabbExtents, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, T tanAngleSqPlusOne);\n\ntemplate<class T> bool rangeCone(const Range3D<T>& range, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const Rad<T> coneAngle);\n\ntemplate<class T> bool rangeCone(const Range3D<T>& range, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const T tanAngleSqPlusOne);\n\ntemplate<class T> bool pointFrustum(const Vector3<T>& point, const Frustum<T>& frustum) {\n    for(const Vector4<T>& plane: frustum) {\n        if(Distance::pointPlaneScaled<T>(point, plane) < T(0))\n            return false;\n    }\n\n    return true;\n}\n\ntemplate<class T> bool rangeFrustum(const Range3D<T>& range, const Frustum<T>& frustum) {\n    const Vector3<T> center = range.min() + range.max();\n    const Vector3<T> extent = range.max() - range.min();\n\n    for(const Vector4<T>& plane: frustum) {\n        const Vector3<T> absPlaneNormal = Math::abs(plane.xyz());\n\n        const Float d = Math::dot(center, plane.xyz());\n        const Float r = Math::dot(extent, absPlaneNormal);\n        if(d + r < -T(2)*plane.w()) return false;\n    }\n\n    return true;\n}\n\ntemplate<class T> bool aabbFrustum(const Vector3<T>& aabbCenter, const Vector3<T>& aabbExtents, const Frustum<T>& frustum) {\n    for(const Vector4<T>& plane: frustum) {\n        const Vector3<T> absPlaneNormal = Math::abs(plane.xyz());\n\n        const Float d = Math::dot(aabbCenter, plane.xyz());\n        const Float r = Math::dot(aabbExtents, absPlaneNormal);\n        if(d + r < -plane.w()) return false;\n    }\n\n    return true;\n}\n\ntemplate<class T> bool sphereFrustum(const Vector3<T>& sphereCenter, const T sphereRadius, const Frustum<T>& frustum) {\n    const T radiusSq = sphereRadius*sphereRadius;\n\n    for(const Vector4<T>& plane: frustum) {\n        if(Distance::pointPlaneScaled<T>(sphereCenter, plane) < -radiusSq)\n            return false;\n    }\n\n    return true;\n}\n\ntemplate<class T> bool pointCone(const Vector3<T>& point, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const Rad<T> coneAngle) {\n    const T tanAngleSqPlusOne = Math::pow<2>(Math::tan(coneAngle*T(0.5))) + T(1);\n    return pointCone(point, coneOrigin, coneNormal, tanAngleSqPlusOne);\n}\n\ntemplate<class T> bool pointCone(const Vector3<T>& point, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const T tanAngleSqPlusOne) {\n    const Vector3<T> c = point - coneOrigin;\n    const T lenA = dot(c, coneNormal);\n\n    return lenA >= 0 && c.dot() <= lenA*lenA*tanAngleSqPlusOne;\n}\n\ntemplate<class T> bool pointDoubleCone(const Vector3<T>& point, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const Rad<T> coneAngle) {\n    const T tanAngleSqPlusOne = Math::pow<2>(Math::tan(coneAngle*T(0.5))) + T(1);\n    return pointDoubleCone(point, coneOrigin, coneNormal, tanAngleSqPlusOne);\n}\n\ntemplate<class T> bool pointDoubleCone(const Vector3<T>& point, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const T tanAngleSqPlusOne) {\n    const Vector3<T> c = point - coneOrigin;\n    const T lenA = dot(c, coneNormal);\n\n    return c.dot() <= lenA*lenA*tanAngleSqPlusOne;\n}\n\ntemplate<class T> bool sphereConeView(const Vector3<T>& sphereCenter, const T sphereRadius, const Matrix4<T>& coneView, const Rad<T> coneAngle) {\n    const Rad<T> halfAngle = coneAngle*T(0.5);\n    const T sinAngle = Math::sin(halfAngle);\n    const T tanAngle = Math::tan(halfAngle);\n\n    return sphereConeView(sphereCenter, sphereRadius, coneView, sinAngle, tanAngle);\n}\n\ntemplate<class T> bool sphereConeView(const Vector3<T>& sphereCenter, const T sphereRadius, const Matrix4<T>& coneView, const T sinAngle, const T tanAngle) {\n    CORRADE_ASSERT(coneView.isRigidTransformation(),\n        \"Math::Intersection::sphereConeView(): coneView does not represent a rigid transformation:\" << Corrade::Utility::Debug::newline << coneView, false);\n\n    const Vector3<T> center = coneView.transformPoint(sphereCenter);\n\n    if (-center.z() > -sphereRadius*sinAngle) {\n        const T coneRadius = tanAngle*(center.z() - sphereRadius/sinAngle);\n        return center.xy().dot() <= coneRadius*coneRadius;\n    } else {\n        return center.dot() <= sphereRadius*sphereRadius;\n    }\n\n    return false;\n}\n\ntemplate<class T> bool sphereCone(\n    const Vector3<T>& sphereCenter, const T sphereRadius,\n    const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const Rad<T> coneAngle)\n{\n    const Rad<T> halfAngle = coneAngle*T(0.5);\n    const T sinAngle = Math::sin(halfAngle);\n    const T tanAngleSqPlusOne = T(1) + Math::pow<T>(Math::tan<T>(halfAngle), T(2));\n\n    return sphereCone(sphereCenter, sphereRadius, coneOrigin, coneNormal, sinAngle, tanAngleSqPlusOne);\n}\n\ntemplate<class T> bool sphereCone(\n    const Vector3<T>& sphereCenter, const T sphereRadius,\n    const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal,\n    const T sinAngle, const T tanAngleSqPlusOne)\n{\n    const Vector3<T> diff = sphereCenter - coneOrigin;\n\n    if(Math::dot(diff - sphereRadius*sinAngle*coneNormal, coneNormal) > T(0)) {\n        const Vector3<T> c = sinAngle*diff + coneNormal*sphereRadius;\n        const T lenA = Math::dot(c, coneNormal);\n\n        return c.dot() <= lenA*lenA*tanAngleSqPlusOne;\n\n    } else return diff.dot() <= sphereRadius*sphereRadius;\n}\n\ntemplate<class T> bool aabbCone(\n    const Vector3<T>& aabbCenter, const Vector3<T>& aabbExtents,\n    const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const Rad<T> coneAngle)\n{\n    const T tanAngleSqPlusOne = Math::pow<T>(Math::tan<T>(coneAngle*T(0.5)), T(2)) + T(1);\n    return aabbCone(aabbCenter, aabbExtents, coneOrigin, coneNormal, tanAngleSqPlusOne);\n}\n\ntemplate<class T> bool aabbCone(\n    const Vector3<T>& aabbCenter, const Vector3<T>& aabbExtents,\n    const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const T tanAngleSqPlusOne)\n{\n    const Vector3<T> c = aabbCenter - coneOrigin;\n\n    for(const Int axis: {0, 1, 2}) {\n        const Int z = axis;\n        const Int x = (axis + 1) % 3;\n        const Int y = (axis + 2) % 3;\n        if(coneNormal[z] != T(0)) {\n            const Float t0 = ((c[z] - aabbExtents[z])/coneNormal[z]);\n            const Float t1 = ((c[z] + aabbExtents[z])/coneNormal[z]);\n\n            const Vector3<T> i0 = coneNormal*t0;\n            const Vector3<T> i1 = coneNormal*t1;\n\n            for(const auto& i : {i0, i1}) {\n                Vector3<T> closestPoint = i;\n\n                if(i[x] - c[x] > aabbExtents[x]) {\n                    closestPoint[x] = c[x] + aabbExtents[x];\n                } else if(i[x] - c[x] < -aabbExtents[x]) {\n                    closestPoint[x] = c[x] - aabbExtents[x];\n                }\n\n                if(i[y] - c[y] > aabbExtents[y]) {\n                    closestPoint[y] = c[y] + aabbExtents[y];\n                } else if(i[y] - c[y] < -aabbExtents[y]) {\n                    closestPoint[y] = c[y] - aabbExtents[y];\n                }\n\n                if(pointCone<T>(closestPoint, {}, coneNormal, tanAngleSqPlusOne))\n                    return true;\n            }\n        }\n    }\n\n    return false;\n}\n\ntemplate<class T> bool rangeCone(const Range3D<T>& range, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const Rad<T> coneAngle) {\n    const T tanAngleSqPlusOne = Math::pow<2>(Math::tan(coneAngle*T(0.5))) + T(1);\n    return rangeCone(range, coneOrigin, coneNormal, tanAngleSqPlusOne);\n}\n\ntemplate<class T> bool rangeCone(const Range3D<T>& range, const Vector3<T>& coneOrigin, const Vector3<T>& coneNormal, const T tanAngleSqPlusOne) {\n    const Vector3<T> center = (range.min() + range.max())*T(0.5);\n    const Vector3<T> extents = (range.max() - range.min())*T(0.5);\n    return aabbCone(center, extents, coneOrigin, coneNormal, tanAngleSqPlusOne);\n}\n\n}}}\n\n#endif\n#ifndef Magnum_Math_StrictWeakOrdering_h\n#define Magnum_Math_StrictWeakOrdering_h\n\nnamespace Magnum { namespace Math {\n\nnamespace Implementation {\n\ntemplate<class T> struct StrictWeakOrdering {\n    bool operator()(const T& a, const T& b) const {\n        return a < b;\n    }\n};\n\n}\n\nstruct StrictWeakOrdering {\n    template<class T> bool operator()(const T& a, const T& b) const {\n        Implementation::StrictWeakOrdering<T> o;\n        return o(a, b);\n    }\n};\n\n}}\n\n#endif\n#ifndef Magnum_Math_Algorithms_GaussJordan_h\n#define Magnum_Math_Algorithms_GaussJordan_h\n\nnamespace Magnum { namespace Math { namespace Algorithms {\n\ntemplate<std::size_t size, std::size_t rows, class T> bool gaussJordanInPlaceTransposed(RectangularMatrix<size, size, T>& a, RectangularMatrix<size, rows, T>& t) {\n    for(std::size_t row = 0; row != size; ++row) {\n        std::size_t rowMax = row;\n        for(std::size_t row2 = row+1; row2 != size; ++row2)\n            if(std::abs(a[row2][row]) > std::abs(a[rowMax][row]))\n                rowMax = row2;\n\n        using std::swap;\n        swap(a[row], a[rowMax]);\n        swap(t[row], t[rowMax]);\n\n        if(TypeTraits<T>::equals(a[row][row], T(0)))\n            return false;\n\n        for(std::size_t row2 = row+1; row2 != size; ++row2) {\n            T c = a[row2][row]/a[row][row];\n\n            a[row2] -= a[row]*c;\n            t[row2] -= t[row]*c;\n        }\n    }\n\n    for(std::size_t row = size; row != 0; --row) {\n        T c = T(1)/a[row-1][row-1];\n\n        for(std::size_t row2 = 0; row2 != row-1; ++row2)\n            t[row2] -= t[row-1]*a[row2][row-1]*c;\n\n        t[row-1] *= c;\n    }\n\n    return true;\n}\n\ntemplate<std::size_t size, std::size_t cols, class T> bool gaussJordanInPlace(RectangularMatrix<size, size, T>& a, RectangularMatrix<cols, size, T>& t) {\n    a = a.transposed();\n    RectangularMatrix<size, cols, T> tTransposed = t.transposed();\n\n    bool ret = gaussJordanInPlaceTransposed(a, tTransposed);\n\n    a = a.transposed();\n    t = tTransposed.transposed();\n\n    return ret;\n}\n\ntemplate<std::size_t size, class T> Matrix<size, T> gaussJordanInverted(Matrix<size, T> matrix) {\n    Matrix<size, T> inverted{Math::IdentityInit};\n    CORRADE_INTERNAL_ASSERT_OUTPUT(gaussJordanInPlaceTransposed(matrix, inverted));\n    return inverted;\n}\n\n}}}\n\n#endif\n#ifndef Magnum_Math_Algorithms_GramSchmidt_h\n#define Magnum_Math_Algorithms_GramSchmidt_h\n\nnamespace Magnum { namespace Math { namespace Algorithms {\n\ntemplate<std::size_t cols, std::size_t rows, class T> void gramSchmidtOrthogonalizeInPlace(RectangularMatrix<cols, rows, T>& matrix) {\n    static_assert(cols <= rows, \"Unsupported matrix aspect ratio\");\n    for(std::size_t i = 0; i != cols; ++i) {\n        for(std::size_t j = i+1; j != cols; ++j)\n            matrix[j] -= matrix[j].projected(matrix[i]);\n    }\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> RectangularMatrix<cols, rows, T> gramSchmidtOrthogonalize(RectangularMatrix<cols, rows, T> matrix) {\n    gramSchmidtOrthogonalizeInPlace(matrix);\n    return matrix;\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> void gramSchmidtOrthonormalizeInPlace(RectangularMatrix<cols, rows, T>& matrix) {\n    static_assert(cols <= rows, \"Unsupported matrix aspect ratio\");\n    for(std::size_t i = 0; i != cols; ++i) {\n        matrix[i] = matrix[i].normalized();\n        for(std::size_t j = i+1; j != cols; ++j)\n            matrix[j] -= matrix[j].projectedOntoNormalized(matrix[i]);\n    }\n}\n\ntemplate<std::size_t cols, std::size_t rows, class T> RectangularMatrix<cols, rows, T> gramSchmidtOrthonormalize(RectangularMatrix<cols, rows, T> matrix) {\n    gramSchmidtOrthonormalizeInPlace(matrix);\n    return matrix;\n}\n\n}}}\n\n#endif\n#ifndef Magnum_Math_Algorithms_KahanSum_h\n#define Magnum_Math_Algorithms_KahanSum_h\n\nnamespace Magnum { namespace Math { namespace Algorithms {\n\ntemplate<class Iterator, class T = typename std::decay<decltype(*std::declval<Iterator>())>::type> T kahanSum(Iterator begin, Iterator end, T sum = T(0), T* compensation = nullptr) {\n    T c = compensation ? *compensation : T(0);\n    for(Iterator it = begin; it != end; ++it) {\n        const T y = *it - c;\n        const T t = sum + y;\n        c = (t - sum) - y;\n        sum = t;\n    }\n\n    if(compensation) *compensation = c;\n    return sum;\n}\n\n}}}\n\n#endif\n#ifndef Magnum_Math_Algorithms_Qr_h\n#define Magnum_Math_Algorithms_Qr_h\n\nnamespace Magnum { namespace Math { namespace Algorithms {\n\ntemplate<std::size_t size, class T> std::pair<Matrix<size, T>, Matrix<size, T>> qr(const Matrix<size, T>& matrix) {\n    const Matrix<size, T> q = gramSchmidtOrthonormalize(matrix);\n    Matrix<size, T> r{ZeroInit};\n    for(std::size_t k = 0; k != size; ++k) {\n        for(std::size_t j = 0; j <= k; ++j) {\n            r[k][j] = Math::dot(q[j], matrix[k]);\n        }\n    }\n\n    return {q, r};\n}\n\n}}}\n\n#endif\n#ifdef MAGNUM_MATH_GLM_INTEGRATION\n#include <glm/gtc/quaternion.hpp>\n#include <glm/gtx/dual_quaternion.hpp>\n#include <glm/matrix.hpp>\n#ifndef Magnum_GlmIntegration_Integration_h\n#define Magnum_GlmIntegration_Integration_h\n\n#if GLM_VERSION < 96 /* Was just two decimals in the old days, now it's 3 */\nnamespace glm {\n    template<class T, glm::precision q> using tvec2 = detail::tvec2<T, q>;\n    template<class T, glm::precision q> using tvec3 = detail::tvec3<T, q>;\n    template<class T, glm::precision q> using tvec4 = detail::tvec4<T, q>;\n\n    template<class T, glm::precision q> using tmat2x2 = detail::tmat2x2<T, q>;\n    template<class T, glm::precision q> using tmat2x3 = detail::tmat2x3<T, q>;\n    template<class T, glm::precision q> using tmat2x4 = detail::tmat2x4<T, q>;\n\n    template<class T, glm::precision q> using tmat3x2 = detail::tmat3x2<T, q>;\n    template<class T, glm::precision q> using tmat3x3 = detail::tmat3x3<T, q>;\n    template<class T, glm::precision q> using tmat3x4 = detail::tmat3x4<T, q>;\n\n    template<class T, glm::precision q> using tmat4x2 = detail::tmat4x2<T, q>;\n    template<class T, glm::precision q> using tmat4x3 = detail::tmat4x3<T, q>;\n    template<class T, glm::precision q> using tmat4x4 = detail::tmat4x4<T, q>;\n}\n#endif\n\nnamespace Magnum { namespace Math { namespace Implementation {\n\ntemplate<\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct BoolVectorConverter<2, glm::tvec2<bool, q>> {\n    static BoolVector<2> from(const glm::tvec2<bool, q>& other) {\n        return (other.x << 0)|(other.y << 1);\n    }\n\n    static glm::tvec2<bool, q> to(const BoolVector<2>& other) {\n        return {other[0], other[1]};\n    }\n};\n\ntemplate<\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct BoolVectorConverter<3, glm::tvec3<bool, q>> {\n    static BoolVector<3> from(const glm::tvec3<bool, q>& other) {\n        return (other.x << 0)|(other.y << 1)|(other.z << 2);\n    }\n\n    static glm::tvec3<bool, q> to(const BoolVector<3>& other) {\n        return {other[0], other[1], other[2]};\n    }\n};\n\ntemplate<\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct BoolVectorConverter<4, glm::tvec4<bool, q>> {\n    static BoolVector<4> from(const glm::tvec4<bool, q>& other) {\n        return (other.x << 0)|(other.y << 1)|(other.z << 2)|(other.w << 3);\n    }\n\n    static glm::tvec4<bool, q> to(const BoolVector<4>& other) {\n        return {other[0], other[1], other[2], other[3]};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct VectorConverter<2, T, glm::tvec2<T, q>> {\n    static Vector<2, T> from(const glm::tvec2<T, q>& other) {\n        return {other.x, other.y};\n    }\n\n    static glm::tvec2<T, q> to(const Vector<2, T>& other) {\n        return {other[0], other[1]};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct VectorConverter<3, T, glm::tvec3<T, q>> {\n    static Vector<3, T> from(const glm::tvec3<T, q>& other) {\n        return {other.x, other.y, other.z};\n    }\n\n    static glm::tvec3<T, q> to(const Vector<3, T>& other) {\n        return {other[0], other[1],  other[2]};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct VectorConverter<4, T, glm::tvec4<T, q>> {\n    static Vector<4, T> from(const glm::tvec4<T, q>& other) {\n        return {other.x, other.y, other.z, other.w};\n    }\n\n    static glm::tvec4<T, q> to(const Vector<4, T>& other) {\n        return {other[0], other[1],  other[2], other[3]};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<2, 2, T, glm::tmat2x2<T, q>> {\n    static RectangularMatrix<2, 2, T> from(const glm::tmat2x2<T, q>& other) {\n        return {Vector<2, T>(other[0]),\n                Vector<2, T>(other[1])};\n    }\n\n    static glm::tmat2x2<T, q> to(const RectangularMatrix<2, 2, T>& other) {\n        return {glm::tvec2<T, q>(other[0]),\n                glm::tvec2<T, q>(other[1])};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<2, 3, T, glm::tmat2x3<T, q>> {\n    static RectangularMatrix<2, 3, T> from(const glm::tmat2x3<T, q>& other) {\n        return {Vector<3, T>(other[0]),\n                Vector<3, T>(other[1])};\n    }\n\n    static glm::tmat2x3<T, q> to(const RectangularMatrix<2, 3, T>& other) {\n        return {glm::tvec3<T, q>(other[0]),\n                glm::tvec3<T, q>(other[1])};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<2, 4, T, glm::tmat2x4<T, q>> {\n    static RectangularMatrix<2, 4, T> from(const glm::tmat2x4<T, q>& other) {\n        return {Vector<4, T>(other[0]),\n                Vector<4, T>(other[1])};\n    }\n\n    static glm::tmat2x4<T, q> to(const RectangularMatrix<2, 4, T>& other) {\n        return {glm::tvec4<T, q>(other[0]),\n                glm::tvec4<T, q>(other[1])};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<3, 2, T, glm::tmat3x2<T, q>> {\n    static RectangularMatrix<3, 2, T> from(const glm::tmat3x2<T, q>& other) {\n        return {Vector<2, T>(other[0]),\n                Vector<2, T>(other[1]),\n                Vector<2, T>(other[2])};\n    }\n\n    static glm::tmat3x2<T, q> to(const RectangularMatrix<3, 2, T>& other) {\n        return {glm::tvec2<T, q>(other[0]),\n                glm::tvec2<T, q>(other[1]),\n                glm::tvec2<T, q>(other[2])};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<3, 3, T, glm::tmat3x3<T, q>> {\n    static RectangularMatrix<3, 3, T> from(const glm::tmat3x3<T, q>& other) {\n        return {Vector<3, T>(other[0]),\n                Vector<3, T>(other[1]),\n                Vector<3, T>(other[2])};\n    }\n\n    static glm::tmat3x3<T, q> to(const RectangularMatrix<3, 3, T>& other) {\n        return {glm::tvec3<T, q>(other[0]),\n                glm::tvec3<T, q>(other[1]),\n                glm::tvec3<T, q>(other[2])};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<3, 4, T, glm::tmat3x4<T, q>> {\n    static RectangularMatrix<3, 4, T> from(const glm::tmat3x4<T, q>& other) {\n        return {Vector<4, T>(other[0]),\n                Vector<4, T>(other[1]),\n                Vector<4, T>(other[2])};\n    }\n\n    static glm::tmat3x4<T, q> to(const RectangularMatrix<3, 4, T>& other) {\n        return {glm::tvec4<T, q>(other[0]),\n                glm::tvec4<T, q>(other[1]),\n                glm::tvec4<T, q>(other[2])};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<4, 2, T, glm::tmat4x2<T, q>> {\n    static RectangularMatrix<4, 2, T> from(const glm::tmat4x2<T, q>& other) {\n        return {Vector<2, T>(other[0]),\n                Vector<2, T>(other[1]),\n                Vector<2, T>(other[2]),\n                Vector<2, T>(other[3])};\n    }\n\n    static glm::tmat4x2<T, q> to(const RectangularMatrix<4, 2, T>& other) {\n        return {glm::tvec2<T, q>(other[0]),\n                glm::tvec2<T, q>(other[1]),\n                glm::tvec2<T, q>(other[2]),\n                glm::tvec2<T, q>(other[3])};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<4, 3, T, glm::tmat4x3<T, q>> {\n    static RectangularMatrix<4, 3, T> from(const glm::tmat4x3<T, q>& other) {\n        return {Vector<3, T>(other[0]),\n                Vector<3, T>(other[1]),\n                Vector<3, T>(other[2]),\n                Vector<3, T>(other[3])};\n    }\n\n    static glm::tmat4x3<T, q> to(const RectangularMatrix<4, 3, T>& other) {\n        return {glm::tvec3<T, q>(other[0]),\n                glm::tvec3<T, q>(other[1]),\n                glm::tvec3<T, q>(other[2]),\n                glm::tvec3<T, q>(other[3])};\n    }\n};\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct RectangularMatrixConverter<4, 4, T, glm::tmat4x4<T, q>> {\n    static RectangularMatrix<4, 4, T> from(const glm::tmat4x4<T, q>& other) {\n        return {Vector<4, T>(other[0]),\n                Vector<4, T>(other[1]),\n                Vector<4, T>(other[2]),\n                Vector<4, T>(other[3])};\n    }\n\n    static glm::tmat4x4<T, q> to(const RectangularMatrix<4, 4, T>& other) {\n        return {glm::tvec4<T, q>(other[0]),\n                glm::tvec4<T, q>(other[1]),\n                glm::tvec4<T, q>(other[2]),\n                glm::tvec4<T, q>(other[3])};\n    }\n};\n\n}}}\n\n#endif\n#ifndef Magnum_GlmIntegration_GtcIntegration_h\n#define Magnum_GlmIntegration_GtcIntegration_h\n\n#if GLM_VERSION < 96 /* Was just two decimals in the old days, now it's 3 */\nnamespace glm {\n    template<class T, glm::precision q> using tquat = detail::tquat<T, q>;\n}\n#endif\n\nnamespace Magnum { namespace Math { namespace Implementation {\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct QuaternionConverter<T, glm::tquat<T, q>> {\n    static Quaternion<T> from(const glm::tquat<T, q>& other) {\n        return {{other.x, other.y, other.z}, other.w};\n    }\n\n    static glm::tquat<T, q> to(const Quaternion<T>& other) {\n        #if GLM_VERSION*10 + GLM_VERSION_REVISION < 952\n        return glm::tquat<T, q>(other.scalar(), other.vector().x(), other.vector().y(), other.vector().z());\n        #else\n        return {other.scalar(), other.vector().x(), other.vector().y(), other.vector().z()};\n        #endif\n    }\n};\n\n}}}\n\n#endif\n#ifndef Magnum_GlmIntegration_GtxIntegration_h\n#define Magnum_GlmIntegration_GtxIntegration_h\n\n#if GLM_VERSION < 96 /* Was just two decimals in the old days, now it's 3 */\nnamespace glm {\n    template<class T, glm::precision q> using tdualquat = detail::tdualquat<T, q>;\n}\n#endif\n\nnamespace Magnum { namespace Math { namespace Implementation {\n\ntemplate<class T,\n    #if GLM_VERSION < 990\n    glm::precision\n    #else\n    glm::qualifier\n    #endif\nq> struct DualQuaternionConverter<T, glm::tdualquat<T, q>> {\n    static DualQuaternion<T> from(const glm::tdualquat<T, q>& other) {\n        return {Quaternion<T>(other.real), Quaternion<T>(other.dual)};\n    }\n\n    static glm::tdualquat<T, q> to(const DualQuaternion<T>& other) {\n        return {glm::tquat<T, q>(other.real()), glm::tquat<T, q>(other.dual())};\n    }\n};\n\n}}}\n\n#endif\n#endif\n#ifdef MAGNUM_MATH_EIGEN_INTEGRATION\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#ifndef Magnum_EigenIntegration_Integration_h\n#define Magnum_EigenIntegration_Integration_h\n\nnamespace Magnum {\n\nnamespace Math { namespace Implementation {\n\ntemplate<std::size_t size> struct BoolVectorConverter<size, Eigen::Ref<const Eigen::Array<bool, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>> {\n    static BoolVector<size> from(const Eigen::Ref<const Eigen::Array<bool, size, 1>>& other) {\n        BoolVector<size> out;\n        for(std::size_t i = 0; i != size; ++i)\n            out.set(i, other(i, 0));\n        return out;\n    }\n};\ntemplate<std::size_t size> struct BoolVectorConverter<size, Eigen::Ref<Eigen::Array<bool, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>>: BoolVectorConverter<size, Eigen::Ref<const Eigen::Array<bool, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>> {};\ntemplate<std::size_t size> struct BoolVectorConverter<size, Eigen::Array<bool, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>> {\n    static BoolVector<size> from(const Eigen::Array<bool, size, 1>& other) {\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic push\n        #pragma GCC diagnostic ignored \"-Wzero-as-null-pointer-constant\"\n        #endif\n        return BoolVectorConverter<size, Eigen::Ref<const Eigen::Array<bool, int(size), 1>>>::from(other);\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic pop\n        #endif\n    }\n\n    static Eigen::Array<bool, size, 1> to(const BoolVector<size>& other) {\n        Eigen::Array<bool, size, 1> out;\n        for(std::size_t i = 0; i != size; ++i)\n            out(i, 0) = other[i];\n        return out;\n    }\n};\n\ntemplate<std::size_t size, class T> struct VectorConverter<size, T, Eigen::Ref<const Eigen::Array<T, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>> {\n    static Vector<size, T> from(const Eigen::Ref<const Eigen::Array<T, size, 1>>& other) {\n        Vector<size, T> out{NoInit};\n        for(std::size_t i = 0; i != size; ++i)\n            out[i] = other(i, 0);\n        return out;\n    }\n};\ntemplate<std::size_t size, class T> struct VectorConverter<size, T, Eigen::Ref<Eigen::Array<T, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>>: VectorConverter<size, T, Eigen::Ref<const Eigen::Array<T, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>> {};\ntemplate<std::size_t size, class T> struct VectorConverter<size, T, Eigen::Array<T, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>> {\n    static Vector<size, T> from(const Eigen::Array<T, size, 1>& other) {\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic push\n        #pragma GCC diagnostic ignored \"-Wzero-as-null-pointer-constant\"\n        #endif\n        return VectorConverter<size, T, Eigen::Ref<const Eigen::Array<T, int(size), 1>>>::from(other);\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic pop\n        #endif\n    }\n\n    static Eigen::Array<T, size, 1> to(const Vector<size, T>& other) {\n        Eigen::Array<T, size, 1> out;\n        for(std::size_t i = 0; i != size; ++i)\n            out(i, 0) = other[i];\n        return out;\n    }\n};\n\ntemplate<std::size_t size, class T> struct VectorConverter<size, T, Eigen::Ref<const Eigen::Matrix<T, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>> {\n    static Vector<size, T> from(const Eigen::Ref<const Eigen::Matrix<T, size, 1>>& other) {\n        Vector<size, T> out{NoInit};\n        for(std::size_t i = 0; i != size; ++i)\n            out[i] = other(i, 0);\n        return out;\n    }\n};\ntemplate<std::size_t size, class T> struct VectorConverter<size, T, Eigen::Ref<Eigen::Matrix<T, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>>: VectorConverter<size, T, Eigen::Ref<const Eigen::Matrix<T, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>>> {};\ntemplate<std::size_t size, class T> struct VectorConverter<size, T, Eigen::Matrix<T, int(size), 1\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(size), 1\n    #endif\n>> {\n    static Vector<size, T> from(const Eigen::Matrix<T, size, 1>& other) {\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic push\n        #pragma GCC diagnostic ignored \"-Wzero-as-null-pointer-constant\"\n        #endif\n        return VectorConverter<size, T, Eigen::Ref<const Eigen::Matrix<T, int(size), 1>>>::from(other);\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic pop\n        #endif\n    }\n\n    static Eigen::Matrix<T, size, 1> to(const Vector<size, T>& other) {\n        Eigen::Matrix<T, size, 1> out;\n        for(std::size_t i = 0; i != size; ++i)\n            out(i, 0) = other[i];\n        return out;\n    }\n};\n\ntemplate<std::size_t cols, std::size_t rows, class T> struct RectangularMatrixConverter<cols, rows, T, Eigen::Ref<const Eigen::Array<T, int(rows), int(cols)\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(rows), int(cols)\n    #endif\n>>> {\n    static RectangularMatrix<cols, rows, T> from(const Eigen::Ref<const Eigen::Array<T, rows, cols>>& other) {\n        RectangularMatrix<cols, rows, T> out{NoInit};\n        for(std::size_t col = 0; col != cols; ++col)\n            for(std::size_t row = 0; row != rows; ++row)\n                out[col][row] = other(row, col);\n        return out;\n    }\n};\ntemplate<std::size_t cols, std::size_t rows, class T> struct RectangularMatrixConverter<cols, rows, T, Eigen::Ref<Eigen::Array<T, int(rows), int(cols)\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(rows), int(cols)\n    #endif\n>>>: RectangularMatrixConverter<cols, rows, T, Eigen::Ref<const Eigen::Array<T, int(rows), int(cols)\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(rows), int(cols)\n    #endif\n>>> {};\ntemplate<std::size_t cols, std::size_t rows, class T> struct RectangularMatrixConverter<cols, rows, T, Eigen::Array<T, int(rows), int(cols)\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(rows), int(cols)\n    #endif\n>> {\n    static RectangularMatrix<cols, rows, T> from(const Eigen::Array<T, rows, cols>& other) {\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic push\n        #pragma GCC diagnostic ignored \"-Wzero-as-null-pointer-constant\"\n        #endif\n        return RectangularMatrixConverter<cols, rows, T, Eigen::Ref<const Eigen::Array<T, int(rows), int(cols)>>>::from(other);\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic pop\n        #endif\n    }\n\n    static Eigen::Array<T, rows, cols> to(const RectangularMatrix<cols, rows, T>& other) {\n        Eigen::Array<T, rows, cols> out;\n        for(std::size_t col = 0; col != cols; ++col)\n            for(std::size_t row = 0; row != rows; ++row)\n                out(row, col) = other[col][row];\n        return out;\n    }\n};\n\ntemplate<std::size_t cols, std::size_t rows, class T> struct RectangularMatrixConverter<cols, rows, T, Eigen::Ref<const Eigen::Matrix<T, int(rows), int(cols)\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(rows), int(cols)\n    #endif\n>>> {\n    static RectangularMatrix<cols, rows, T> from(const Eigen::Ref<const Eigen::Matrix<T, rows, cols>>& other) {\n        RectangularMatrix<cols, rows, T> out{NoInit};\n        for(std::size_t col = 0; col != cols; ++col)\n            for(std::size_t row = 0; row != rows; ++row)\n                out[col][row] = other(row, col);\n        return out;\n    }\n};\ntemplate<std::size_t cols, std::size_t rows, class T> struct RectangularMatrixConverter<cols, rows, T, Eigen::Ref<Eigen::Matrix<T, int(rows), int(cols)\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(rows), int(cols)\n    #endif\n>>>: RectangularMatrixConverter<cols, rows, T, Eigen::Ref<const Eigen::Matrix<T, int(rows), int(cols)\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(rows), int(cols)\n    #endif\n>>> {};\ntemplate<std::size_t cols, std::size_t rows, class T> struct RectangularMatrixConverter<cols, rows, T, Eigen::Matrix<T, int(rows), int(cols)\n    #ifdef CORRADE_MSVC2019_COMPATIBILITY\n    , 0, int(rows), int(cols)\n    #endif\n>> {\n    static RectangularMatrix<cols, rows, T> from(const Eigen::Matrix<T, rows, cols>& other) {\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic push\n        #pragma GCC diagnostic ignored \"-Wzero-as-null-pointer-constant\"\n        #endif\n        return RectangularMatrixConverter<cols, rows, T, Eigen::Ref<const Eigen::Matrix<T, int(rows), int(cols)>>>::from(other);\n        #if defined(__GNUC__) && !defined(__clang__)\n        #pragma GCC diagnostic pop\n        #endif\n    }\n\n    static Eigen::Matrix<T, rows, cols> to(const RectangularMatrix<cols, rows, T>& other) {\n        Eigen::Matrix<T, rows, cols> out;\n        for(std::size_t col = 0; col != cols; ++col)\n            for(std::size_t row = 0; row != rows; ++row)\n                out(row, col) = other[col][row];\n        return out;\n    }\n};\n\n}}\n\nnamespace EigenIntegration {\n\ntemplate<class To, std::size_t cols, std::size_t rows, class T> inline To cast(const Math::RectangularMatrix<cols, rows, T>& from) {\n    return Math::Implementation::RectangularMatrixConverter<cols, rows, T, To>::to(from);\n}\n\ntemplate<class To, std::size_t size> inline To cast(const Math::BoolVector<size>& from) {\n    return Math::Implementation::BoolVectorConverter<size, To>::to(from);\n}\n\ntemplate<class To, std::size_t size, class T> inline To cast(const Math::Vector<size, T>& from) {\n    return Math::Implementation::VectorConverter<size, T, To>::to(from);\n}\n\n}\n\n}\n\n#endif\n#ifndef Magnum_EigenIntegration_GeometryIntegration_h\n#define Magnum_EigenIntegration_GeometryIntegration_h\n\nnamespace Magnum { namespace Math { namespace Implementation {\n\ntemplate<std::size_t size, class T> struct VectorConverter<size, T, Eigen::Translation<T, int(size)>> {\n    static Vector<size, T> from(const Eigen::Translation<T, size>& other) {\n        return Vector<size, T>(other.vector());\n    }\n\n    static Eigen::Translation<T, size> to(const Vector<size, T>& other) {\n        return Eigen::Translation<T, size>(VectorConverter<size, T, Eigen::Matrix<T, size, 1>>::to(other));\n    }\n};\n\ntemplate<std::size_t size, class T, int mode> struct RectangularMatrixConverter<size, size, T, Eigen::Transform<T, int(size - 1), mode>> {\n    static_assert(mode == Eigen::Affine || mode == Eigen::Projective || mode == Eigen::Isometry,\n        \"only Affine, Projective and Isometry transform supported\");\n\n    static RectangularMatrix<size, size, T> from(const Eigen::Transform<T, int(size - 1), mode>& other) {\n        return RectangularMatrix<size, size, T>(other.matrix());\n    }\n\n    static Eigen::Transform<T, int(size - 1), mode> to(const RectangularMatrix<size, size, T>& other) {\n        return Eigen::Transform<T, int(size - 1), mode>(RectangularMatrixConverter<size, size, T, Eigen::Matrix<T, size, size>>::to(other));\n    }\n};\n\ntemplate<class T> struct RectangularMatrixConverter<3, 2, T, Eigen::Transform<T, 2, Eigen::AffineCompact>> {\n    static RectangularMatrix<3, 2, T> from(const Eigen::Transform<T, 2, Eigen::AffineCompact>& other) {\n        return RectangularMatrix<3, 2, T>(other.matrix());\n    }\n\n    static Eigen::Transform<T, 2, Eigen::AffineCompact> to(const RectangularMatrix<3, 2, T>& other) {\n        return Eigen::Transform<T, 2, Eigen::AffineCompact>(RectangularMatrixConverter<3, 2, T, Eigen::Matrix<T, 2, 3>>::to(other));\n    }\n};\ntemplate<class T> struct RectangularMatrixConverter<4, 3, T, Eigen::Transform<T, 3, Eigen::AffineCompact>> {\n    static RectangularMatrix<4, 3, T> from(const Eigen::Transform<T, 3, Eigen::AffineCompact>& other) {\n        return RectangularMatrix<4, 3, T>(other.matrix());\n    }\n\n    static Eigen::Transform<T, 3, Eigen::AffineCompact> to(const RectangularMatrix<4, 3, T>& other) {\n        return Eigen::Transform<T, 3, Eigen::AffineCompact>(RectangularMatrixConverter<4, 3, T, Eigen::Matrix<T, 3, 4>>::to(other));\n    }\n};\n\ntemplate<class T> struct QuaternionConverter<T, Eigen::Quaternion<T>> {\n    static Quaternion<T> from(const Eigen::Quaternion<T>& other) {\n        return {{other.x(), other.y(), other.z()}, other.w()};\n    }\n\n    static Eigen::Quaternion<T> to(const Quaternion<T>& other) {\n        return {other.scalar(), other.vector().x(), other.vector().y(), other.vector().z()};\n    }\n};\n\n}}\n\nnamespace EigenIntegration {\n\ntemplate<class To, class T> inline To cast(const Math::Quaternion<T>& from) {\n    return To(from);\n}\n\n}\n\n}\n\n#endif\n#endif\n#ifdef MAGNUM_MATH_IMPLEMENTATION\nnamespace Magnum { namespace Math {\n\nUnsignedInt log(UnsignedInt base, UnsignedInt number) {\n    UnsignedInt log = 0;\n    while(number /= base)\n        ++log;\n    return log;\n}\n\nUnsignedInt log2(UnsignedInt number) {\n    UnsignedInt log = 0;\n    while(number >>= 1)\n        ++log;\n    return log;\n}\n\n}}\nnamespace Magnum { namespace Math {\n\nnamespace {\n\nunion FloatBits {\n    UnsignedInt u;\n    Float f;\n};\n\n}\n\nFloat unpackHalf(const UnsignedShort value) {\n    constexpr const FloatBits Magic{113 << 23};\n    constexpr const UnsignedInt ShiftedExp = 0x7c00 << 13;\n\n    const UnsignedShort h{value};\n    FloatBits o;\n\n    o.u = (h & 0x7fff) << 13;\n    const UnsignedInt exp = ShiftedExp & o.u;\n    o.u += (127 - 15) << 23;\n\n    if(exp == ShiftedExp) {\n        o.u += (128 - 16) << 23;\n    } else if(exp == 0) {\n        o.u += 1 << 23;\n        o.f -= Magic.f;\n    }\n\n    o.u |= (h & 0x8000) << 16;\n    return o.f;\n}\n\nUnsignedShort packHalf(const Float value) {\n    constexpr const FloatBits FloatInfinity{255 << 23};\n    constexpr const FloatBits HalfInfinity{31 << 23};\n    constexpr const FloatBits Magic{15 << 23};\n    constexpr const UnsignedInt SignMask = 0x80000000u;\n    constexpr const UnsignedInt RoundMask = ~0xfffu;\n\n    FloatBits f;\n    f.f = value;\n    UnsignedShort h;\n\n    const UnsignedInt sign = f.u & SignMask;\n    f.u ^= sign;\n\n    if(f.u >= FloatInfinity.u) {\n        h = (f.u > FloatInfinity.u) ? 0x7e00 : 0x7c00;\n\n    } else {\n        f.u &= RoundMask;\n        f.f *= Magic.f;\n        f.u -= RoundMask;\n\n        if (f.u > HalfInfinity.u) f.u = HalfInfinity.u;\n\n        h = f.u >> 13;\n    }\n\n    h |= sign >> 16;\n    return h;\n}\n\n}}\n#endif\n", "meta": {"hexsha": "0e96e8d1a93f0ee246b3c9e7dd804f011eb8ec39", "size": 304755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/magnum/MagnumMath.hpp", "max_stars_repo_name": "jakubtyrcha/playground", "max_stars_repo_head_hexsha": "d6be4387ffb2d9a2106f01b4c1b1a46ce78c1cef", "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": "external/magnum/MagnumMath.hpp", "max_issues_repo_name": "jakubtyrcha/playground", "max_issues_repo_head_hexsha": "d6be4387ffb2d9a2106f01b4c1b1a46ce78c1cef", "max_issues_repo_licenses": ["MIT"], "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/magnum/MagnumMath.hpp", "max_forks_repo_name": "jakubtyrcha/playground", "max_forks_repo_head_hexsha": "d6be4387ffb2d9a2106f01b4c1b1a46ce78c1cef", "max_forks_repo_licenses": ["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.6123400853, "max_line_length": 348, "alphanum_fraction": 0.6160030188, "num_tokens": 78169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.297469948832931, "lm_q1q2_score": 0.15454198105870573}}
{"text": "#include \"biggles/model.hpp\"\n#include \"biggles/partition.hpp\"\n#include \"biggles/tracker.hpp\"\n#include \"biggles/simulate.hpp\"\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/tuple/tuple_io.hpp>\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include \"biggles/tools/sundries.hpp\"\n\n// include this last to stop pre-processor macros breaking things\nextern \"C\" {\n#include <ccan/tap/tap.h>\n}\n\nusing namespace biggles;\n\nstd::vector<std::string> move_names(mh_moves::MOVE_COUNT);\n\nstruct part_para {\n    float b, c, o, s;\n    part_para (float bb, float cc, float oo, float ss) : b(bb), c(cc), o(oo), s(ss) {}\n};\n\nint test1(int n_it, model::parameters &params)\n{\n    float image_size(32.f);\n    time_stamp time_extent(128);\n\n    // simulate full data\n    partition_ptr_t partition_ptr;\n    simulate::generate_partition(partition_ptr, params, 0, (time_extent>>1) + time_extent, image_size * 1.5f, image_size * 1.5f);\n\n    diag(\"Generated %zu new tracks.\", partition_ptr->tracks().size());\n    diag(\"Generated %zu clutter observations.\", partition_ptr->clutter().size());\n\n    // crop partition to a specific region\n    simulate::crop_partition(partition_ptr, partition_ptr,\n                             image_size * 0.25f, image_size * 1.25f,\n                             image_size * 0.25f, image_size * 1.25f,\n                             time_extent >> 2, (time_extent >> 2) + time_extent);\n\n    partition_ptr_t ground_truth(new partition(*partition_ptr));\n\n    diag(\"Cropped to %zu tracks.\", partition_ptr->tracks().size());\n    diag(\"Cropped to %zu clutter observations.\", partition_ptr->clutter().size());\n    diag(\"Ground truth log pdf: %f\", model::log_partition_given_parameters_and_data_density(*partition_ptr, params));\n\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, partition_ptr->tracks())\n    {\n        diag(\"P(t|theta): %f\", model::log_track_given_parameters_density(t_ptr, params));\n    }\n\n    diag(\"P(clutter|theta): %f\", model::log_clutter_given_parameters_density(*partition_ptr, params));\n    diag(\"P(T|theta): %f\", model::log_partition_given_parameters_density(*partition_ptr, params));\n    diag(\"Priors: %f\", model::log_parameters_prior_density(params));\n\n\n    // create a synthetic dataset from the partition\n    simulate::demote_all_tracks_from_partition(partition_ptr, partition_ptr);\n\n    // check we have some data and no tracks\n    ok1(partition_ptr->clutter().size() > 0);\n    ok1(partition_ptr->tracks().size() == 0);\n\n    diag(\"P(T|theta): %f\", model::log_partition_given_parameters_density(*partition_ptr, params));\n\n    diag(\"Final data set consists of %zu observations.\", partition_ptr->clutter().size());\n\n    // create tracker\n    tracker tracking(params, partition_ptr);\n    //tracker tracking(params, ground_truth);\n    for(int i=0; i<n_it; ++i)\n    {\n        tracking();\n\n        if(0 == (i&0xff))\n        {\n            diag(\"i: %i, track count: %zu, log PDF: %f, last PDF: %f\",\n                 i,\n                 tracking.best_partition()->tracks().size(),\n                 tracking.best_log_pdf(),\n                 tracking.last_log_pdf());\n\n            model::parameters theta(tracking.best_parameters());\n            diag(\"parameters: lambda_b = %f, lambda_f = %f, p_s = %f, p_d = %f\",\n                model::birth_rate(theta),\n                model::clutter_rate(theta),\n                model::observation_probability(theta),\n                model::survival_probability(theta));\n        }\n\n        if(0 == (i&0x1ff))\n            write_partition(\"tracker\", *tracking.best_partition(), \"estimate\");\n    }\n\n    write_partition(\"tracker\", *tracking.best_partition(), \"estimate\");\n    return 0;\n}\n\nint test2(int n_it, model::parameters &params)\n{\n    observation_collection track1_obs;\n    track1_obs.insert(new_obs(0, 0, 0));\n    track1_obs.insert(new_obs(0, 0, 2));\n    track1_obs.insert(new_obs(0, 0, 4));\n    track1_obs.insert(new_obs(0, 0, 6));\n    track1_obs.insert(new_obs(0, 0, 8));\n\n    observation_collection track2_obs;\n    track2_obs.insert(new_obs(0, 0, 1));\n    track2_obs.insert(new_obs(0, 0, 3));\n    track2_obs.insert(new_obs(0, 0, 5));\n    track2_obs.insert(new_obs(0, 0, 7));\n    track2_obs.insert(new_obs(0, 0, 9));\n\n    observation_collection clutter_obs;\n    clutter_obs.insert(new_obs(9, 9, 1));\n\n    boost::shared_ptr<track_collection> tracks2(new track_collection());\n    clutter_ptr clutter(new clutter_t(clutter_obs.begin(), clutter_obs.end()));\n\n    track track1(0, 10, track1_obs.begin(), track1_obs.end(), 1.0);\n    track track2(0, 10, track2_obs.begin(), track2_obs.end(), 1.0);\n\n    tracks2->insert(track1);\n    tracks2->insert(track2);\n\n    partition_ptr_t partition_ptr(new partition(tracks2, clutter));\n\n    model::mean_new_tracks_per_frame(params)           = 0.2f;\n    model::mean_false_observations_per_frame(params)   = 0.1f;\n    model::frame_to_frame_survival_probability(params) = 0.95f;\n    model::generate_observation_probability(params)    = 0.5f;\n\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, partition_ptr->tracks())\n    {\n        diag(\"P(t|theta): %f\", model::log_track_given_parameters_density(t_ptr, params));\n    }\n\n    diag(\"P(clutter|theta): %f\", model::log_clutter_given_parameters_density(*partition_ptr, params));\n    diag(\"P(T|theta): %f\", model::log_partition_given_parameters_density(*partition_ptr, params));\n    diag(\"Priors: %f\", model::log_parameters_prior_density(params));\n\n    diag(\"Original partition log pdf: %f\", model::log_partition_given_parameters_and_data_density(*partition_ptr, params));\n\n    diag(\"** starting tracking **\");\n\n    tracker trackit(params, partition_ptr);\n\n    std::deque<mh_moves::move_type> move_seq;\n    std::deque<mh_moves::move_type> prop_seq;\n    std::deque<int> num_tr_seq;\n    std::deque<int> longest_dur_seq;\n    std::deque<int> longest_obs_seq;\n    std::deque<int> sample_id_seq;\n    std::deque<int> clutter_size_seq;\n    std::deque<float> log_pdf_seq;\n    std::deque<part_para> para_seq;\n\n    for(int i=0; i<n_it; ++i)\n    {\n        try {\n            trackit();\n        }\n        catch (const std::exception& e) {\n            for (size_t k = 0; k < move_seq.size(); ++k ) {\n                std::cerr\n                    << \"  \"\n                    << mh_moves::move_sign(prop_seq[k])\n                    << \"  \"\n                    << mh_moves::move_sign(move_seq[k])\n                    << std::endl\n                ;\n            }\n            std::cerr << \"iteration i=\" << i << std::endl;\n            throw;\n        }\n        prop_seq.push_back(trackit.last_proposal_move());\n        if (trackit.last_proposal_accepted()) {\n            //diag(\"%s\", mh_moves::move_name(trackit.last_move_type()).c_str());\n            sample_id_seq.push_back(i+1);\n            move_seq.push_back(trackit.last_move_type());\n            track_collection tracks = trackit.last_partition()->tracks();\n            clutter_size_seq.push_back(trackit.last_partition()->clutter().size());\n            num_tr_seq.push_back(tracks.size());\n            track_collection::const_iterator iter = tracks.begin();\n            int maxdur = 0;\n            int maxobs = 0;\n            for (; iter != tracks.end(); ++iter) {\n                if ((*iter)->duration() > maxdur) {\n                    maxdur = (*iter)->duration();\n                    maxobs = (*iter)->size();\n                }\n            }\n            longest_dur_seq.push_back(maxdur);\n            longest_obs_seq.push_back(maxobs);\n            log_pdf_seq.push_back(trackit.last_log_pdf());\n            model::parameters params(trackit.last_parameters());\n            para_seq.push_back(part_para(model::birth_rate(params), model::clutter_rate(params),\n                model::observation_probability(params), model::survival_probability(params)));\n        } else {\n            move_seq.push_back(mh_moves::NONE);\n        }\n\n    }\n    partition_ptr_t last_partition = trackit.last_partition();\n    track_collection::const_iterator iter = last_partition->tracks().begin();\n    for (; iter != last_partition->tracks().end(); ++iter) {\n        diag(\"duration %zu, observations %zu\", (*iter)->duration(), (*iter)->size());\n    }\n    const std::deque< uint64_t >& move_histogram = trackit.move_histogram();\n    for (size_t i = 0; i < move_histogram.size(); ++i)\n        diag(\"move: %s, count: %zu\", move_names[i].c_str(), move_histogram[i]);\n\n    /*\n    for (int i = 0; i < move_seq.size(); ++i) {\n        std::stringstream sstr;\n        sstr << boost::format(\"%4d #%1d/%1d (%2d, %2d) log PDF %.2f ; b=%.2f, c=%.2f, o=%.2f, s=%.2f\")\n            % sample_id_seq[i]\n            % num_tr_seq[i]\n            % clutter_size_seq[i]\n            % longest_dur_seq[i]\n            % longest_obs_seq[i]\n            % log_pdf_seq[i]\n            % para_seq[i].b % para_seq[i].c % para_seq[i].o % para_seq[i].s\n        ;\n        diag(\"%s\", sstr.str().c_str());\n    }\n    */\n    return 0;\n}\n\nint main(int argc, char** argv)\n{\n    plan_tests(1);\n\n    const float sigma_R = 0.1f;\n\n    //biggles::detail::seed_prng(0xfacedead);\n\n    // initialise model parameters\n    model::parameters params;\n    model::mean_new_tracks_per_frame(params)           = 1.f;\n    model::mean_false_observations_per_frame(params)   = 1.f;\n    model::frame_to_frame_survival_probability(params) = 0.95f;\n    model::generate_observation_probability(params)    = 0.9f;\n    model::observation_error_covariance(params)       << sigma_R * sigma_R, 0, 0, sigma_R * sigma_R;\n    model::constraint_radius(params) = 100.0f;\n    model::process_noise_covariance(params) = detail::initQ();\n\n\n    int n_it(4000);\n    if(argc > 1)\n        n_it = atoi(argv[1]);\n\n    //test1(n_it, params);\n    test2(n_it, params);\n    ok1(true);\n\n    return exit_status();\n}\n", "meta": {"hexsha": "88926892afd0a823d1ff313d7b0836220b7ea2f0", "size": 9750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/biggles_tracker.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": "test/biggles_tracker.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": "test/biggles_tracker.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": 36.5168539326, "max_line_length": 129, "alphanum_fraction": 0.6207179487, "num_tokens": 2468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.1545419757776476}}
{"text": "/*\n    Copyright 2013 Adobe\n    Distributed under the Boost Software License, Version 1.0.\n    (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n/**************************************************************************************************/\n\n#include <adobe/eve.hpp>\n\n#include <iterator>\n#include <utility>\n\n#include <boost/bind/bind.hpp>\n#include <boost/iterator/filter_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/variant/static_visitor.hpp>\n\n#include <adobe/algorithm/for_each.hpp>\n#include <adobe/algorithm/for_each_position.hpp>\n#include <adobe/algorithm/transform.hpp>\n#include <adobe/cmath.hpp>\n#include <adobe/forest.hpp>\n#include <adobe/functional.hpp>\n#include <adobe/iterator.hpp>\n#include <adobe/numeric.hpp>\n\n#ifndef NDEBUG\n#include <iostream>\n#endif\n\n/**************************************************************************************************/\n\nusing namespace boost::placeholders;\n\n/**************************************************************************************************/\n\nnamespace {\n\nusing adobe::eve_t;\n\nstruct filter_visible {\n    bool operator()(const adobe::implementation::view_proxy_t& x);\n};\n\ntypedef adobe::filter_fullorder_iterator<adobe::eve_t::proxy_tree_t::iterator, filter_visible>\n    cursor;\ntypedef boost::filter_iterator<filter_visible, adobe::child_iterator<cursor>> child_iterator;\ntypedef std::reverse_iterator<child_iterator> reverse_child_iterator;\n\ninline child_iterator child_begin(cursor c) {\n    return child_iterator(filter_visible(), adobe::child_begin(c), adobe::child_end(c));\n}\n\ninline child_iterator child_end(cursor c) {\n    return child_iterator(filter_visible(), adobe::child_end(c), adobe::child_end(c));\n}\n\n\n/**************************************************************************************************/\n\n} // namespace\n\n/**************************************************************************************************/\n\n\n#ifdef ADOBE_HAS_CPLUS0X_CONCEPTS\n#include <concepts>\nnamespace std {\nconcept_map\n    RandomAccessIterator<boost::filter_iterator<filter_visible, adobe::child_iterator<cursor>>>{};\n}\n#endif\n\n/*\n    REVISIT (sparent) : namespace adobe::implementation used instead of unnamed to support friend\n    in eve_t.\n*/\n\nnamespace adobe {\nnamespace implementation {\n\n/**************************************************************************************************/\n\nstruct view_proxy_t : adobe::extents_slices_t {\n    view_proxy_t(const layout_attributes_t&, poly_placeable_t&);\n\n    poly_placeable_t& placeable_m;\n\n    bool visible_m;\n\n    typedef boost::array<guide_set_t, 2> fr_guide_set_t;\n\n    layout_attributes_t geometry_m; // REVISIT (sparent) : make const\n    place_data_t place_m;\n\n    int space_before_m;                      // populated from spacing_m of parent\n    boost::array<int, 2> container_length_m; // calculated length of container\n    boost::array<int, 2> measured_length_m;  // length of container children only\n\n    boost::array<fr_guide_set_t, 2> container_guide_set_m; // forward/reverse guide set for\n    // container\n\n    void calculate();\n    void calculate_vertical();\n    void place();\n\n    void adjust(::child_iterator, ::child_iterator, slice_select_t);\n    void solve_up(::child_iterator, ::child_iterator, slice_select_t slice);\n    bool solve_down(::child_iterator, ::child_iterator, slice_select_t slice);\n    void layout(::child_iterator, ::child_iterator, slice_select_t slice);\n    void flatten(::child_iterator, ::child_iterator, slice_select_t slice,\n                 adobe::eve_t::evaluate_options_t);\n\n    void adjust_outsets(::child_iterator, ::child_iterator, slice_select_t);\n    void adjust_outsets_with(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    void adjust_outsets_cross(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    void adjust_with(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    void adjust_cross(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    void solve_up_with(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    void solve_up_cross(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    bool solve_down_with(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    bool solve_down_cross(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    void layout_with(::child_iterator first, ::child_iterator last, slice_select_t slice);\n    void layout_cross(::child_iterator first, ::child_iterator last, slice_select_t slice);\n};\n\n/**************************************************************************************************/\n\n} // namespace implementation\n} // namespace adobe\n\n/**************************************************************************************************/\n#if !defined(ADOBE_NO_DOCUMENTATION)\nnamespace {\n\ninline bool filter_visible::operator()(const adobe::implementation::view_proxy_t& x) {\n    return x.visible_m;\n}\n\n/**************************************************************************************************/\n\ntypedef adobe::implementation::view_proxy_t::slice_select_t slice_select_t;\ntypedef void (adobe::implementation::view_proxy_t::*apply_member_t)(::child_iterator,\n                                                                    ::child_iterator,\n                                                                    ::slice_select_t);\n\n/*\n    REVISIT (sparent) : VC 7.1 cannot handle the apply_member_t as a template parameter.\n    Unfortunate, as this form would be more efficient.\n*/\n#if 0\ntemplate<typename BeadIterator, ::apply_member_t Apply>\nstruct apply_to_children\n{\n    typedef void result_type;\n    \n    explicit apply_to_children(::slice_select_t select) : select_m(select) { }\n\n    void operator()(BeadIterator iter)const\n    {\n        ((*iter).*Apply)(::child_begin(iter.base()), ::child_end(iter.base()), select_m);\n    }\n\nprivate:\n    ::slice_select_t select_m;\n};\n#endif\n#if 1\ntemplate <typename BeadIterator>\nstruct apply_to_children {\n    typedef void result_type;\n    explicit apply_to_children(::apply_member_t apply, ::slice_select_t select)\n        : apply_m(apply), select_m(select) {}\n\n    void operator()(BeadIterator iter) {\n        ((*iter).*apply_m)(::child_begin(iter.base()), ::child_end(iter.base()), select_m);\n    }\n\nprivate:\n    ::apply_member_t apply_m;\n    ::slice_select_t select_m;\n};\n#endif\n\n/*\n    REVISIT (sparent) : This is a quick fix for flatten - I think we could do much of what is\n    here more efficiently.\n*/\n\nstruct apply_flatten_t {\n    typedef void result_type;\n\n    explicit apply_flatten_t(slice_select_t select, adobe::eve_t::evaluate_options_t options)\n        : options_m(options), select_m(select) {}\n\n    template <typename BeadIterator>\n    void operator()(BeadIterator iter) {\n        iter->flatten(::child_begin(iter.base()), ::child_end(iter.base()), select_m, options_m);\n    }\n\nprivate:\n    adobe::eve_t::evaluate_options_t options_m;\n    slice_select_t select_m;\n};\n\n/**************************************************************************************************/\n\nbool is_with(adobe::eve_t::placement_t placement, adobe::eve_t::slice_select_t select) {\n    return ((placement == adobe::eve_t::place_column) && (select == adobe::eve_t::vertical)) ||\n           ((placement == adobe::eve_t::place_row) && (select == adobe::eve_t::horizontal));\n}\n\n/**************************************************************************************************/\n\n} // namespace\n#endif\n/**************************************************************************************************/\n\n#if 0\n#pragma mark -\n#endif\n\n/**************************************************************************************************/\n\nnamespace adobe {\n\n/**************************************************************************************************/\n\nvoid set_margin(layout_attributes_t& container, int x) {\n    container.slice_m[eve_t::horizontal].margin_m.first = x;\n    container.slice_m[eve_t::horizontal].margin_m.second = x;\n    container.slice_m[eve_t::vertical].margin_m.first = x;\n    container.slice_m[eve_t::vertical].margin_m.second = x;\n}\n\n/**************************************************************************************************/\n\n#if 0\n#pragma mark -\n#endif\n\n/**************************************************************************************************/\n\nclass eve_t::implementation_t : private extents_slices_t {\npublic:\n    implementation_t();\n\n    ~implementation_t();\n\n    std::pair<int, int> evaluate(evaluate_options_t, int width, int height);\n    std::pair<int, int> adjust(evaluate_options_t options, int width, int height);\n    iterator add_placeable(iterator parent, const layout_attributes_t& initial,\n                           bool is_container_type, poly_placeable_t& placeable, bool reverse);\n    void set_visible(iterator, bool);\n\nprivate:\n    void solve(slice_select_t select);\n    void layout(slice_select_t select, int optional_length);\n\n\n    typedef edge_iterator<cursor, adobe::forest_trailing_edge> postorder_iterator;\n    typedef edge_iterator<cursor, adobe::forest_leading_edge> preorder_iterator;\n\n    boost::iterator_range<postorder_iterator> postorder_range() {\n        return adobe::postorder_range(filter_fullorder_range(proxies_m, filter_visible()));\n    }\n\n    boost::iterator_range<preorder_iterator> preorder_range() {\n        return adobe::preorder_range(filter_fullorder_range(proxies_m, filter_visible()));\n    }\n\n    proxy_tree_t proxies_m;\n};\n\n/**************************************************************************************************/\n\n#if !defined(ADOBE_NO_DOCUMENTATION)\neve_t::eve_t() : object_m(new implementation_t()) {}\n\neve_t::~eve_t() { delete object_m; }\n#endif\n\nstd::pair<int, int> eve_t::evaluate(evaluate_options_t options, int width, int height) {\n    return object_m->evaluate(options, width, height);\n}\n\nstd::pair<int, int> eve_t::adjust(evaluate_options_t options, int width, int height) {\n    return object_m->adjust(options, width, height);\n}\n\neve_t::iterator eve_t::add_placeable(iterator parent, const layout_attributes_t& initial,\n                                     bool is_container_type,      // is the element a container?\n                                     poly_placeable_t& placeable, // signals to call for the element\n                                     bool reverse) {\n    return object_m->add_placeable(parent, initial, is_container_type, placeable, reverse);\n}\n\nvoid eve_t::set_visible(iterator c, bool visible) { return object_m->set_visible(c, visible); }\n\n/**************************************************************************************************/\n\n#if 0\n#pragma mark -\n#endif\n\n/**************************************************************************************************/\n\neve_t::implementation_t::implementation_t() {}\n\n/**************************************************************************************************/\n\neve_t::implementation_t::~implementation_t() {}\n\n/**************************************************************************************************/\n\n/*\n    REVISIT (sparent) : This logic would be simplified with a root() function wich could be passed\n    as the initial parent.\n*/\n\neve_t::iterator eve_t::implementation_t::add_placeable(iterator parent,\n                                                       const layout_attributes_t& initial,\n                                                       bool is_container_type,\n                                                       poly_placeable_t& placeable, bool reverse) {\n    if (parent == iterator())\n        parent = proxies_m.end();\n\n    parent = proxies_m.insert(reverse ? boost::next(adobe::leading_of(parent))\n                                      : adobe::trailing_of(parent),\n                              implementation::view_proxy_t(initial, placeable));\n\n    if (!is_container_type)\n        parent->geometry_m.placement_m = place_leaf;\n\n    return parent;\n}\n\n/**************************************************************************************************/\n\nvoid eve_t::implementation_t::set_visible(iterator c, bool visible) { c->visible_m = visible; }\n\n/**************************************************************************************************/\n\nvoid eve_t::implementation_t::solve(slice_select_t select) {\n    adobe::for_each_position(\n        postorder_range(),\n        apply_to_children<postorder_iterator>(&implementation::view_proxy_t::solve_up, select));\n\n    // REVISIT (sparent) : HUGE opportunities to optimize this.\n\n    // solve until things settle down.\n\n    bool progress(false);\n\n    /*\n        REVISIT (sparent) : This loop should solve it in rougly log N passes\n        We know that we are guaranteed to solve one guide completely per iteration\n        and most often it should be several. But, I've been known to make a mistake or two\n        (which could cause this loop to solve forever!). So we put a limiter on it and\n        an assert.\n\n    */\n    proxy_tree_t::size_type limiter(proxies_m.size() + 1); // + 1 to account for the empty case\n\n    do {\n        --limiter;\n        progress = false;\n\n        for (preorder_iterator first(boost::begin(preorder_range())),\n             last(boost::end(preorder_range()));\n             first != last; ++first) {\n            progress |=\n                first->solve_down(::child_begin(first.base()), ::child_end(first.base()), select);\n        }\n\n        adobe::for_each_position(postorder_range(),\n                                 ::apply_to_children<postorder_iterator>(\n                                     &implementation::view_proxy_t::solve_up, select));\n\n    } while (progress && limiter);\n\n    assert(limiter); // Failing to make forward progress - aborting.\n}\n\n/**************************************************************************************************/\n\nvoid eve_t::implementation_t::layout(slice_select_t select, int optional_length) {\n    // FILTER VISIBLE - this assumes a visible root\n\n    if (!proxies_m.empty()) {\n        place_data_t::slice_t& pslice(proxies_m.front().place_m.slice_m[select]);\n\n        /*\n            REVISIT (sparent) : This allows us to go sub-minimum. May revisit for wrapped\n            containers.\n        */\n\n        pslice.length_m =\n            optional_length ? optional_length : proxies_m.front().container_length_m[select];\n    }\n\n    adobe::for_each_position(preorder_range(), apply_to_children<preorder_iterator>(\n                                                   &implementation::view_proxy_t::layout, select));\n}\n\n/**************************************************************************************************/\n\nstd::pair<int, int> eve_t::implementation_t::evaluate(evaluate_options_t options, int width,\n                                                      int height) {\n    // Calculate\n\n    adobe::for_each(postorder_range(), &proxy_tree_t::value_type::calculate);\n\n    // adjust\n\n    return adjust(options, width, height);\n}\n\n/**************************************************************************************************/\n\nstd::pair<int, int> eve_t::implementation_t::adjust(evaluate_options_t options, int width,\n                                                    int height) {\n    // adjust\n\n    adobe::for_each_position(\n        postorder_range(),\n        apply_to_children<postorder_iterator>(&implementation::view_proxy_t::adjust, horizontal));\n\n    // solve\n\n    solve(horizontal); // Not necessary\n    layout(horizontal, width);\n\n    // adjust outsets\n\n    adobe::for_each_position(postorder_range(),\n                             apply_to_children<postorder_iterator>(\n                                 &implementation::view_proxy_t::adjust_outsets, horizontal));\n\n    // flatten\n\n    adobe::for_each_position(preorder_range(), apply_flatten_t(horizontal, options));\n\n    // give the client a crack at adjusting vertical\n\n    adobe::for_each(postorder_range(), &proxy_tree_t::value_type::calculate_vertical);\n\n    // adjust\n\n    adobe::for_each_position(\n        postorder_range(),\n        apply_to_children<postorder_iterator>(&implementation::view_proxy_t::adjust, vertical));\n\n    // solve\n\n    solve(vertical);\n    layout(vertical, height);\n\n    // adjust outsets\n\n    adobe::for_each_position(postorder_range(),\n                             apply_to_children<postorder_iterator>(\n                                 &implementation::view_proxy_t::adjust_outsets, vertical));\n\n    // flatten\n\n    adobe::for_each_position(preorder_range(), apply_flatten_t(vertical, options));\n\n    // place\n\n    adobe::for_each(preorder_range(), &proxy_tree_t::value_type::place);\n\n    return std::make_pair(proxies_m.front().place_m.horizontal().length_m,\n                          proxies_m.front().place_m.vertical().length_m);\n}\n\n/**************************************************************************************************/\n\n#if 0\n#pragma mark -\n#endif\n\n/**************************************************************************************************/\n\nnamespace implementation {\n\n/**************************************************************************************************/\n\nstruct calculate : public boost::static_visitor<> {\n    template <typename T>\n    void operator()(T& operand) const {\n        operand += operand;\n    }\n};\n\n/**************************************************************************************************/\n\nview_proxy_t::view_proxy_t(const adobe::layout_attributes_t& d, poly_placeable_t& p)\n    : placeable_m(p), visible_m(true), geometry_m(d) {}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::calculate() {\n    /*\n        REVISIT (sparent) : What we want is for the data from placeable widgets to be preserved\n        unless they are explicity dirtied - rather than calling measure for every update.\n        For now, there are several bugs caused by the measuring code in widgets assuming that\n       the\n        initial extents it is handed is a defaulted extents. Without that - some code\n       accumulates\n        metrics into the extents giving ever increasing growth when a window is resized (as an\n        example). This fix is a hack - to just always clear the extents before measuring.\n    */\n    geometry_m.extents_m = extents_t();\n\n    placeable_m.measure(geometry_m.extents_m);\n\n    extents_t::slice_t& eslice = geometry_m.extents_m.horizontal();\n\n    place_m.horizontal().length_m = eslice.length_m;\n    place_m.horizontal().outset_m = eslice.outset_m;\n\n    // Copy the guides over. Only non-surpressed guides will be updated.\n    place_m.horizontal().guide_set_m = eslice.guide_set_m;\n\n    /*\n        REVISIT (sparent) : It becomes apparent here that we have a number of limitation which\n        we should address:\n\n        1. Containers cannot have their own guides to align items in their frame.\n        2. Leaf nodes effectively have thier guides surpressed if they are aligned by anything\n       other\n            than forward or reverse. Should probably allow for fill, but that would make fill\n            orthoganal to alignment.\n    */\n\n    /*\n        REVISIT (sparent) : The vertical data should also be handled here to avoid the\n       peformance\n        hit in calculate_vertical() during a resize. I'll factor this code later.\n    */\n\n    container_length_m[horizontal] = eslice.length_m;\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::calculate_vertical() {\n    extents_t::slice_t& eslice = geometry_m.extents_m.vertical();\n\n    if (poly_placeable_twopass_t* p = poly_cast<poly_placeable_twopass_t*>(&placeable_m)) {\n        // We pass a copy of the geometry so client can't modify horizontal properties.\n        extents_t vertical_stuff(geometry_m.extents_m);\n        p->measure_vertical(vertical_stuff, place_m);\n        eslice = vertical_stuff.vertical();\n    }\n\n    place_m.vertical().length_m = eslice.length_m;\n    place_m.vertical().outset_m = eslice.outset_m;\n\n    // Copy the guides over. Only non-surpressed guides will be updated.\n    place_m.vertical().guide_set_m = eslice.guide_set_m;\n\n    container_length_m[vertical] = eslice.length_m;\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::place() { placeable_m.place(place_m); }\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::adjust(::child_iterator first, ::child_iterator last, slice_select_t select) {\n    if (geometry_m.placement_m == eve_t::place_leaf)\n        return;\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        layout_attributes_t::alignment_t& child_alignment(\n            iter->geometry_m.slice_m[select].alignment_m);\n\n        if (child_alignment == layout_attributes_t::align_default) {\n            child_alignment = geometry_m.slice_m[select].child_alignment_m;\n        }\n\n        /*\n            Now that we know the final alignment - we can copy the guides to the container\n           guides.\n            This is only done on leaf nodes because the guides will be propogated to the\n           containers\n            through either adjust_with or _cross.\n        */\n        if (iter->geometry_m.placement_m == eve_t::place_leaf) {\n            switch (child_alignment) {\n            case layout_attributes_t::align_forward:\n            case layout_attributes_t::align_forward_fill: {\n                iter->container_guide_set_m[select][layout_attributes_t::align_forward] =\n                    iter->geometry_m.extents_m.slice_m[select].guide_set_m;\n            } break;\n            case layout_attributes_t::align_reverse:\n            case layout_attributes_t::align_reverse_fill: {\n                guide_set_t& guide_set(\n                    iter->container_guide_set_m[select][layout_attributes_t::align_reverse]);\n\n                guide_set = iter->geometry_m.extents_m.slice_m[select].guide_set_m;\n\n                adobe::transform(guide_set, boost::begin(guide_set),\n                                 boost::bind(std::minus<int>(),\n                                             iter->geometry_m.extents_m.slice_m[select].length_m,\n                                             _1));\n                adobe::reverse(guide_set);\n            } break;\n            default:\n                break;\n            }\n        }\n    }\n\n    if (is_with(geometry_m.placement_m, select))\n        adjust_with(first, last, select);\n    else\n        adjust_cross(first, last, select);\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::solve_up(::child_iterator first, ::child_iterator last, slice_select_t select) {\n    if (geometry_m.placement_m == adobe::eve_t::place_leaf)\n        return;\n\n    if (select == vertical) {\n        if (geometry_m.placement_m == adobe::eve_t::place_column)\n            solve_up_with(first, last, vertical);\n        else\n            solve_up_cross(first, last, vertical);\n    } else {\n        if (geometry_m.placement_m == adobe::eve_t::place_row)\n            solve_up_with(first, last, horizontal);\n        else\n            solve_up_cross(first, last, horizontal);\n    }\n}\n\n/**************************************************************************************************/\n\nbool view_proxy_t::solve_down(::child_iterator first, ::child_iterator last,\n                              slice_select_t select) {\n    bool result(false);\n\n    if (geometry_m.placement_m == adobe::eve_t::place_leaf)\n        return result;\n\n    if (select == vertical) {\n        if (geometry_m.placement_m == adobe::eve_t::place_column)\n            result |= solve_down_with(first, last, vertical);\n        else\n            result |= solve_down_cross(first, last, vertical);\n    } else {\n        if (geometry_m.placement_m == adobe::eve_t::place_row)\n            result |= solve_down_with(first, last, horizontal);\n        else\n            result |= solve_down_cross(first, last, horizontal);\n    }\n\n    return result;\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::layout(::child_iterator first, ::child_iterator last, slice_select_t select) {\n    if (geometry_m.placement_m == adobe::eve_t::place_leaf)\n        return;\n\n    if (select == vertical) {\n        if (geometry_m.placement_m == adobe::eve_t::place_column)\n            layout_with(first, last, vertical);\n        else\n            layout_cross(first, last, vertical);\n    } else {\n        if (geometry_m.placement_m == adobe::eve_t::place_row)\n            layout_with(first, last, horizontal);\n        else\n            layout_cross(first, last, horizontal);\n    }\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::flatten(::child_iterator first, ::child_iterator last, slice_select_t select,\n                           adobe::eve_t::evaluate_options_t options) {\n    // Push the guides into the element being placed.\n\n    guide_set_t& guide_set(place_m.slice_m[select].guide_set_m);\n\n    switch (geometry_m.slice_m[select].alignment_m) {\n    case layout_attributes_t::align_forward:\n    case layout_attributes_t::align_forward_fill: {\n        guide_set = container_guide_set_m[select][layout_attributes_t::align_forward];\n    } break;\n    case layout_attributes_t::align_reverse:\n    case layout_attributes_t::align_reverse_fill: {\n        guide_set = container_guide_set_m[select][layout_attributes_t::align_reverse];\n        adobe::transform(guide_set, boost::begin(guide_set),\n                         boost::bind(std::minus<int>(), place_m.slice_m[select].length_m, _1));\n        adobe::reverse(guide_set);\n    } break;\n    default:\n        break;\n    }\n\n    // Flatten the coordinate system if needed for the children.\n\n    if (options == adobe::eve_t::evaluate_nested && geometry_m.create_m)\n        return;\n\n    int position(place_m.slice_m[select].position_m);\n\n    for (; first != last; ++first) {\n        first->place_m.slice_m[select].position_m += position;\n    }\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::adjust_outsets(::child_iterator first, ::child_iterator last,\n                                  slice_select_t select) {\n    if (select == vertical) {\n        if (geometry_m.placement_m == adobe::eve_t::place_column)\n            adjust_outsets_with(first, last, vertical);\n        else\n            adjust_outsets_cross(first, last, vertical);\n    } else {\n        if (geometry_m.placement_m == adobe::eve_t::place_row)\n            adjust_outsets_with(first, last, horizontal);\n        else\n            adjust_outsets_cross(first, last, horizontal);\n    }\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::adjust_outsets_with(::child_iterator first, ::child_iterator last,\n                                       slice_select_t select) {\n    const extents_t::slice_t& eslice(geometry_m.extents_m.slice_m[select]);\n    place_data_t::slice_t& pslice(place_m.slice_m[select]);\n\n    if (first == last) {\n        pslice.outset_m = eslice.outset_m;\n        return;\n    }\n\n    --last;\n\n    adobe::place_data_t::slice_t& leading_pslice(first->place_m.slice_m[select]);\n    adobe::place_data_t::slice_t& trailing_pslice(last->place_m.slice_m[select]);\n\n    int leading_outset_position = leading_pslice.position_m - leading_pslice.outset_m.first;\n\n    // trailing_outset_position is measured as distance from edge to inside (like frame)\n    int trailing_outset_position =\n        pslice.length_m -\n        (trailing_pslice.position_m + trailing_pslice.length_m + trailing_pslice.outset_m.second);\n\n// REVISIT (sparent) : We need a warning mechanism to report this issue!\n#ifndef NDEBUG\n    if (!(!eslice.frame_m.first || (leading_outset_position >= eslice.frame_m.first))) {\n        std::cerr << \"WARNING (sparent) : outset collision.\" << std::endl;\n    }\n#endif\n\n    pslice.outset_m.first = std::max(pslice.outset_m.first, -leading_outset_position);\n\n#ifndef NDEBUG\n    if (!(!eslice.frame_m.second || (trailing_outset_position >= eslice.frame_m.second))) {\n        std::cerr << \"WARNING (sparent) : outset collision.\" << std::endl;\n    }\n#endif\n\n    pslice.outset_m.second = std::max(pslice.outset_m.second, -trailing_outset_position);\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::adjust_outsets_cross(::child_iterator first, ::child_iterator last,\n                                        slice_select_t select) {\n    const extents_t::slice_t& eslice(geometry_m.extents_m.slice_m[select]);\n    place_data_t::slice_t& pslice(place_m.slice_m[select]);\n\n    if (first == last) {\n        pslice.outset_m = eslice.outset_m;\n        return;\n    }\n\n    // start by assuming enough space for the frame.\n    int leading_outset_position = eslice.frame_m.first;\n    int trailing_outset_position = eslice.frame_m.second;\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        place_data_t::slice_t& iter_pslice(iter->place_m.slice_m[select]);\n\n        leading_outset_position =\n            std::min(leading_outset_position, iter_pslice.position_m - iter_pslice.outset_m.first);\n\n        // trailing_outset_position is measured as distance from edge to inside (like frame)\n        trailing_outset_position =\n            std::min(trailing_outset_position,\n                     pslice.length_m - (iter_pslice.position_m + iter_pslice.length_m +\n                                        iter_pslice.outset_m.second));\n    }\n\n// REVISIT (sparent) : We need a warning mechanism to report this issue!\n#ifndef NDEBUG\n    if (!(!eslice.frame_m.first || (leading_outset_position >= eslice.frame_m.first))) {\n        std::cerr << \"WARNING (sparent) : outset collision.\" << std::endl;\n    }\n#endif\n\n    pslice.outset_m.first = std::max(pslice.outset_m.first, -leading_outset_position);\n\n#ifndef NDEBUG\n    if (!(!eslice.frame_m.second || (trailing_outset_position >= eslice.frame_m.second))) {\n        std::cerr << \"WARNING (sparent) : outset collision.\" << std::endl;\n    }\n#endif\n\n    pslice.outset_m.second = std::max(pslice.outset_m.second, -trailing_outset_position);\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::layout_with(::child_iterator first, ::child_iterator last,\n                               slice_select_t select) {\n    if (first == last)\n        return;\n\n    const layout_attributes_t::slice_t& gslice(geometry_m.slice_m[select]);\n    const extents_t::slice_t& eslice(geometry_m.extents_m.slice_m[select]);\n    place_data_t::slice_t& pslice(place_m.slice_m[select]);\n\n    /*\n    REVISIT (sparent) : Something to think about. Counting the number of children could be\n    expressed as count_if that takes a \"within set\" as a predicate.\n    */\n\n    /*\n    REVISIT (sparent) : The extra space should be destributed to the items in blocks - up to the\n    first guide, then to the next.\n    */\n\n    // count the number of children to distribute any additional space\n\n    int padded_count(0);\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n\n        switch (iter->geometry_m.slice_m[select].alignment_m) {\n        case adobe::layout_attributes_t::align_center:\n        case adobe::layout_attributes_t::align_proportional:\n        case adobe::layout_attributes_t::align_forward_fill:\n        case adobe::layout_attributes_t::align_reverse_fill:\n            ++padded_count;\n            break;\n        default:\n            break;\n        }\n    }\n\n    // calculate the additional per/item space\n\n    int remaining_additional_length(pslice.length_m - measured_length_m[select]);\n\n    int available_length(pslice.length_m - gslice.margin_m.first - gslice.margin_m.second -\n                         eslice.frame_m.first - eslice.frame_m.second);\n\n    // place any reverse align items\n    int rlength = pslice.length_m - (gslice.margin_m.second + eslice.frame_m.second);\n\n    ::reverse_child_iterator riter(last);\n    ::reverse_child_iterator rlast(first);\n\n    guide_set_t::iterator reverse_guide_iter(\n        container_guide_set_m[select][layout_attributes_t::align_reverse].begin());\n\n    for (; riter != rlast; ++riter) {\n        const layout_attributes_t::slice_t& iter_gslice(riter->geometry_m.slice_m[select]);\n\n        if (iter_gslice.alignment_m != layout_attributes_t::align_reverse &&\n            iter_gslice.alignment_m != layout_attributes_t::align_reverse_fill)\n            break;\n\n        place_data_t::slice_t& iter_pslice(riter->place_m.slice_m[select]);\n        guide_set_t& reverse_child_guide_set(\n            riter->container_guide_set_m[select][layout_attributes_t::align_reverse]);\n\n        iter_pslice.length_m = riter->container_length_m[select];\n\n        // These items are offset by their guides\n\n        if (!iter_gslice.suppress_m && reverse_child_guide_set.size()) {\n            if (riter->geometry_m.placement_m == eve_t::place_leaf) {\n                rlength -= *reverse_guide_iter - reverse_child_guide_set.front();\n            }\n            std::advance(reverse_guide_iter,\n                         guide_set_t::difference_type(reverse_child_guide_set.size()));\n        }\n\n        /*\n            REVISIT (sparent) : Filled items fill forward. The space to behind is going to\n            be dead space... It would be good to allow it to be filled.\n        */\n\n        if (iter_gslice.alignment_m == adobe::layout_attributes_t::align_reverse_fill) {\n\n            int additional_length(remaining_additional_length / padded_count);\n\n            --padded_count;\n            remaining_additional_length -= additional_length;\n\n            iter_pslice.length_m = riter->container_length_m[select] + additional_length;\n        }\n\n        iter_pslice.position_m = rlength - iter_pslice.length_m;\n\n        rlength -= iter_pslice.length_m + riter->space_before_m;\n    }\n\n    // place any forward items\n\n    int zero_length = gslice.margin_m.first + eslice.frame_m.first;\n    int length = zero_length;\n\n    guide_set_t::iterator guide_iter(\n        container_guide_set_m[select][layout_attributes_t::align_forward].begin());\n\n    for (::child_iterator iter(first); iter != riter.base(); ++iter) {\n        const layout_attributes_t::slice_t& iter_gslice(iter->geometry_m.slice_m[select]);\n        place_data_t::slice_t& iter_pslice(iter->place_m.slice_m[select]);\n\n        guide_set_t& forward_child_guide_set(\n            iter->container_guide_set_m[select][layout_attributes_t::align_forward]);\n\n        length += iter->space_before_m;\n\n        if (iter_gslice.alignment_m != adobe::layout_attributes_t::align_fill) {\n            iter_pslice.length_m = iter->container_length_m[select];\n        }\n\n        int additional_length(0);\n\n        switch (iter_gslice.alignment_m) {\n        case adobe::layout_attributes_t::align_forward_fill:\n        case adobe::layout_attributes_t::align_center:\n        case adobe::layout_attributes_t::align_proportional: {\n            additional_length = remaining_additional_length / padded_count;\n            --padded_count;\n            remaining_additional_length -= additional_length;\n        } break;\n        default:\n            break;\n        }\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_forward:\n        case layout_attributes_t::align_forward_fill: {\n            // These items are offset by their guides\n\n            if (!iter_gslice.suppress_m && forward_child_guide_set.size()) {\n                if (iter->geometry_m.placement_m == eve_t::place_leaf) {\n                    length = *guide_iter - forward_child_guide_set.front();\n                }\n                std::advance(guide_iter,\n                             guide_set_t::difference_type(forward_child_guide_set.size()));\n            }\n\n            /*\n                REVISIT (sparent) : Filled items fill forward. The space to behind is going to\n                be dead space... It would be good to allow it to be filled.\n            */\n\n            if (iter_gslice.alignment_m == adobe::layout_attributes_t::align_forward_fill) {\n                iter_pslice.length_m = iter->container_length_m[select] + additional_length;\n            }\n\n            iter_pslice.position_m = length;\n        } break;\n        case adobe::layout_attributes_t::align_center: {\n            int block_length(iter->container_length_m[select] + additional_length);\n            iter_pslice.position_m = length + (block_length - iter->container_length_m[select]) / 2;\n            length += additional_length;\n        } break;\n        case adobe::layout_attributes_t::align_proportional: {\n            int block_length(iter->container_length_m[select] + additional_length);\n            double proportion(double(length - zero_length) /\n                              double(available_length - block_length));\n            iter_pslice.position_m = length + adobe::lround_half_up(proportion * additional_length);\n            length += additional_length;\n        } break;\n        case adobe::layout_attributes_t::align_reverse:\n        case adobe::layout_attributes_t::align_reverse_fill:\n            /*\n                REVISIT (sparent) : This is a runtime error and needs to go through the stream\n                error reporting mechanism.\n            */\n            throw std::logic_error(\"Right align item before other item.\");\n        default:\n            break;\n        }\n\n        length += iter_pslice.length_m;\n    }\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::layout_cross(::child_iterator first, ::child_iterator last,\n                                slice_select_t select) {\n    const layout_attributes_t::slice_t& gslice(geometry_m.slice_m[select]);\n    const extents_t::slice_t& eslice(geometry_m.extents_m.slice_m[select]);\n    place_data_t::slice_t& pslice(place_m.slice_m[select]);\n\n    // calculate a base for the child position.\n\n    int length = gslice.margin_m.first + eslice.frame_m.first;\n    int rlength = pslice.length_m - (gslice.margin_m.second + eslice.frame_m.second);\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        const layout_attributes_t::slice_t& iter_gslice(iter->geometry_m.slice_m[select]);\n        place_data_t::slice_t& iter_pslice(iter->place_m.slice_m[select]);\n\n        guide_set_t& forward_child_guide_set(\n            iter->container_guide_set_m[select][layout_attributes_t::align_forward]);\n        guide_set_t& reverse_child_guide_set(\n            iter->container_guide_set_m[select][layout_attributes_t::align_reverse]);\n\n        if (iter_gslice.alignment_m != adobe::layout_attributes_t::align_fill) {\n            iter_pslice.length_m = iter->container_length_m[select];\n        }\n\n        int iter_length(length);\n        int iter_rlength(rlength);\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_forward:\n        case layout_attributes_t::align_forward_fill:\n            iter_length += iter->geometry_m.indent_m;\n            break;\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill:\n            iter_rlength -= iter->geometry_m.indent_m;\n            break;\n        default:\n            break;\n        }\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_forward:\n        case layout_attributes_t::align_forward_fill: {\n            if ((iter->geometry_m.placement_m == eve_t::place_leaf) && !iter_gslice.suppress_m &&\n                forward_child_guide_set.size()) {\n                iter_length =\n                    container_guide_set_m[select][layout_attributes_t::align_forward].front() -\n                    forward_child_guide_set.front();\n            }\n\n            if (iter_gslice.alignment_m == layout_attributes_t::align_forward_fill) {\n                iter_pslice.length_m = iter_rlength - iter_length;\n            }\n\n            iter_pslice.position_m = iter_length;\n        } break;\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill: {\n            if ((iter->geometry_m.placement_m == eve_t::place_leaf) && !iter_gslice.suppress_m &&\n                reverse_child_guide_set.size()) {\n                iter_rlength =\n                    pslice.length_m -\n                    (container_guide_set_m[select][layout_attributes_t::align_reverse].front() -\n                     reverse_child_guide_set.front());\n            }\n\n            if (iter_gslice.alignment_m == layout_attributes_t::align_reverse_fill) {\n                iter_pslice.length_m = iter_rlength - iter_length;\n            }\n\n            iter_pslice.position_m = iter_rlength - iter->container_length_m[select];\n        } break;\n        case layout_attributes_t::align_center:\n        case layout_attributes_t::align_proportional:\n            iter_pslice.position_m =\n                (iter_rlength + iter_length - iter->container_length_m[select]) / 2;\n            break;\n        default:\n            break;\n        }\n    }\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::adjust_with(::child_iterator first, ::child_iterator last,\n                               slice_select_t select) {\n    // set the spacing for each of our children.\n\n    /*\n    REVISIT (sparent) : I'm still struggling to write a concise version of this section.\n\n    Things to note:\n        1. we need a make_tranform_range().\n        2. This function should be passed _range_ instead of first, last.\n        3. complain to boost again about bind/mem_fn not dealing with non-const member\n    references.\n\n    ----\n\n    typedef adobe::mem_data_t<view_proxy_t, int>            transform_function;\n    typedef boost::transform_iterator<transform_function>   tranform_iterator;\n    typedef boost::tranform_range<tranform_iterator>        tranform_range;\n\n    tranform_range child_spacing_range(\n            adobe::make_tranform_range(range, adobe::mem_data(&view_proxy_t::space_before_m));\n\n    assert(!geometry_m.spacing_m.empty());\n\n    std::fill(\n        adobe::copy_bound(geometry.spacing_m, child_spacing_range).second,\n        boost::end(child_spacing_range), geometry_m.spacing_m.back());\n    */\n\n    typedef layout_attributes_t::spacing_t::difference_type difference_type;\n\n    const difference_type copy_count(std::min(difference_type(geometry_m.spacing_m.size()),\n                                              difference_type(std::distance(first, last))));\n\n    assert(!geometry_m.spacing_m.empty());\n\n    std::fill(std::copy(geometry_m.spacing_m.begin(), geometry_m.spacing_m.begin() + copy_count,\n                        boost::make_transform_iterator(\n                            first, adobe::mem_data(&view_proxy_t::space_before_m))),\n              boost::make_transform_iterator(last, adobe::mem_data(&view_proxy_t::space_before_m)),\n              geometry_m.spacing_m.back());\n\n    // size the container guide set based on the number of guides our children have.\n\n    /*\n    REVISIT (sparent) : I'm sure there is oportunity to do less work here but we clear the\n    guides\n    so we can re-adjust on a size adjust.\n    */\n\n    container_guide_set_m[select][layout_attributes_t::align_forward].clear();\n    container_guide_set_m[select][layout_attributes_t::align_reverse].clear();\n\n    /*\n    REVISIT (sparent) : This is a good candidate for using boost::lambda and accumlate.\n    There may also be the notion of an iterator adaptor that adapts iterator to pointer\n    to behave as a simple iterator.\n    */\n\n    std::size_t forward_guide_count(0);\n    std::size_t reverse_guide_count(0);\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        layout_attributes_t::slice_t& gslice(iter->geometry_m.slice_m[select]);\n        if (!gslice.suppress_m) {\n            switch (gslice.alignment_m) {\n            case layout_attributes_t::align_forward: {\n                forward_guide_count +=\n                    iter->container_guide_set_m[select][layout_attributes_t::align_forward].size();\n            } break;\n            case layout_attributes_t::align_reverse: {\n                reverse_guide_count +=\n                    iter->container_guide_set_m[select][layout_attributes_t::align_reverse].size();\n            } break;\n            case layout_attributes_t::align_forward_fill:\n            case layout_attributes_t::align_reverse_fill: {\n                forward_guide_count +=\n                    iter->container_guide_set_m[select][layout_attributes_t::align_forward].size();\n                reverse_guide_count +=\n                    iter->container_guide_set_m[select][layout_attributes_t::align_reverse].size();\n            } break;\n            default:\n                gslice.suppress_m = true;\n                break;\n            }\n        }\n    }\n\n    container_guide_set_m[select][layout_attributes_t::align_forward].resize(forward_guide_count);\n    container_guide_set_m[select][layout_attributes_t::align_reverse].resize(reverse_guide_count);\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::adjust_cross(::child_iterator first, ::child_iterator last,\n                                slice_select_t select) {\n    // size the container guide set based on the number of guides our children have.\n\n    /*\n    REVISIT (sparent) : I'm sure there is oportunity to do less work here but we clear the\n    guides\n    so we can re-adjust on a size adjust.\n    */\n\n    container_guide_set_m[select][layout_attributes_t::align_forward].clear();\n    container_guide_set_m[select][layout_attributes_t::align_reverse].clear();\n\n    /*\n    REVISIT (sparent) : This is a good candidate for using boost::lambda and accumlate.\n    There may also be the notion of an iterator adaptor that adapts iterator to pointer\n    to behave as a simple iterator.\n    */\n\n    std::size_t forward_guide_count(0);\n    std::size_t reverse_guide_count(0);\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        layout_attributes_t::slice_t& gslice(iter->geometry_m.slice_m[select]);\n\n        if (gslice.suppress_m)\n            continue;\n\n        switch (gslice.alignment_m) {\n        case layout_attributes_t::align_forward: {\n            forward_guide_count = std::max(\n                forward_guide_count,\n                iter->container_guide_set_m[select][layout_attributes_t::align_forward].size());\n        } break;\n        case layout_attributes_t::align_reverse: {\n            reverse_guide_count = std::max(\n                reverse_guide_count,\n                iter->container_guide_set_m[select][layout_attributes_t::align_reverse].size());\n        } break;\n        case layout_attributes_t::align_forward_fill:\n        case layout_attributes_t::align_reverse_fill: {\n            forward_guide_count = std::max(\n                forward_guide_count,\n                iter->container_guide_set_m[select][layout_attributes_t::align_forward].size());\n            reverse_guide_count = std::max(\n                reverse_guide_count,\n                iter->container_guide_set_m[select][layout_attributes_t::align_reverse].size());\n        } break;\n        default:\n            gslice.suppress_m = true;\n            break;\n        }\n    }\n\n    container_guide_set_m[select][layout_attributes_t::align_forward].resize(forward_guide_count);\n    container_guide_set_m[select][layout_attributes_t::align_reverse].resize(reverse_guide_count);\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::solve_up_with(::child_iterator first, ::child_iterator last,\n                                 slice_select_t select) {\n    const layout_attributes_t::slice_t& gslice(geometry_m.slice_m[select]);\n    const extents_t::slice_t& eslice(geometry_m.extents_m.slice_m[select]);\n    int length(eslice.frame_m.first + gslice.margin_m.first);\n    int rlength(eslice.frame_m.second + gslice.margin_m.second);\n\n    guide_set_t& forward_guide_set(\n        container_guide_set_m[select][layout_attributes_t::align_forward]);\n    guide_set_t& reverse_guide_set(\n        container_guide_set_m[select][layout_attributes_t::align_reverse]);\n    guide_set_t::iterator forward_guide_iter(forward_guide_set.begin());\n    guide_set_t::iterator reverse_guide_iter(reverse_guide_set.begin());\n\n    int additional_rlength(rlength);\n\n    // accumulate the length and update the position.\n\n    for (::reverse_child_iterator rfirst(last), rlast(first); rfirst != rlast; ++rfirst) {\n        switch (rfirst->geometry_m.slice_m[select].alignment_m) {\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill:\n        case layout_attributes_t::align_forward_fill: {\n            if (rfirst->geometry_m.slice_m[select].suppress_m)\n                break;\n\n            guide_set_t::iterator reverse_first_guide(reverse_guide_iter);\n            guide_set_t& reverse_child_guide_set(\n                rfirst->container_guide_set_m[select][layout_attributes_t::align_reverse]);\n\n            for (guide_set_t::iterator guide(reverse_child_guide_set.begin());\n                 guide != reverse_child_guide_set.end(); ++guide, ++reverse_guide_iter) {\n                assert(reverse_guide_iter != reverse_guide_set.end());\n                *reverse_guide_iter = std::max(*reverse_guide_iter, *guide + rlength);\n            }\n\n            if ((rfirst->geometry_m.placement_m == adobe::eve_t::place_leaf) &&\n                reverse_child_guide_set.size()) {\n                assert(reverse_first_guide != reverse_guide_set.end());\n                int current_rlength(rlength);\n                rlength = *reverse_first_guide - reverse_child_guide_set.front();\n                additional_rlength += rlength - current_rlength;\n            }\n        } break;\n        default:\n            break;\n        }\n\n        rlength += rfirst->container_length_m[select] + rfirst->space_before_m;\n    }\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        length += iter->space_before_m;\n\n        switch (iter->geometry_m.slice_m[select].alignment_m) {\n        case layout_attributes_t::align_forward:\n        case layout_attributes_t::align_forward_fill:\n        case layout_attributes_t::align_reverse_fill: {\n            if (iter->geometry_m.slice_m[select].suppress_m)\n                break;\n\n            guide_set_t::iterator forward_first_guide(forward_guide_iter);\n            guide_set_t& forward_child_guide_set(\n                iter->container_guide_set_m[select][layout_attributes_t::align_forward]);\n\n            for (guide_set_t::iterator guide(forward_child_guide_set.begin());\n                 guide != forward_child_guide_set.end(); ++guide, ++forward_guide_iter) {\n                assert(forward_guide_iter != forward_guide_set.end());\n                *forward_guide_iter = std::max(*forward_guide_iter, *guide + length);\n            }\n\n            if ((iter->geometry_m.placement_m == adobe::eve_t::place_leaf) &&\n                forward_child_guide_set.size()) {\n                assert(forward_first_guide != forward_guide_set.end());\n                length = *forward_first_guide - forward_child_guide_set.front();\n            }\n        } break;\n        default:\n            break;\n        }\n\n        length += iter->container_length_m[select];\n    }\n\n    // balance the guides\n\n    if (gslice.balance_m && forward_guide_set.size() > 2) {\n        guide_set_t::iterator iter(adobe::max_adjacent_difference(forward_guide_set));\n        guide_set_t::value_type difference(*boost::next(iter) - *iter);\n\n        guide_set_t::value_type accumulate(forward_guide_set.front());\n\n        /*\n        REVISIT (sparent) : This should be a call to generate - but I need a simple to create\n        accumulate function object.\n        */\n\n        for (guide_set_t::iterator first(boost::next(forward_guide_set.begin())),\n             last(forward_guide_set.end());\n             first != last; ++first) {\n            accumulate += difference;\n            *first = accumulate;\n        }\n    }\n\n    length += additional_rlength;\n\n    // update properties on this container.\n\n    measured_length_m[select] = length;\n    container_length_m[select] = std::max(length, container_length_m[select]);\n}\n\n/**************************************************************************************************/\n\nbool view_proxy_t::solve_down_with(::child_iterator first, ::child_iterator last,\n                                   slice_select_t select) {\n    bool result(false);\n    const layout_attributes_t::slice_t& gslice(geometry_m.slice_m[select]);\n    const extents_t::slice_t& eslice(geometry_m.extents_m.slice_m[select]);\n    int length(eslice.frame_m.first + gslice.margin_m.first);\n    int rlength(eslice.frame_m.second + gslice.margin_m.second);\n    guide_set_t::iterator guide_iter(\n        container_guide_set_m[select][layout_attributes_t::align_forward].begin());\n    guide_set_t::iterator reverse_guide_iter(\n        container_guide_set_m[select][layout_attributes_t::align_reverse].begin());\n\n    // accumulate the length and update the position.\n\n    /*\n        REVISIT (sparent) : After we move the guides on a container we don't know if we need to\n        move the guides on subsequent children because the container may (or may not) grow in\n        response. If it grows, it will shift the sibling over, which may resolve the guide for\n       us.\n\n        Becuase of this, we break out of this loop once we've adjusted one guide on one\n       container.\n        ... I suspect there is a pathelogical case here that's tending towards N^2. I need to\n        revist how we are solving but the actual case where this happens is complex enough\n        (requiring 4 levels of nesting with two guides) that I don't think it is a huge problem.\n    */\n\n    for (::reverse_child_iterator rfirst(last), rlast(first); rfirst != rlast && !result;\n         ++rfirst) {\n        switch (rfirst->geometry_m.slice_m[select].alignment_m) {\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill:\n        case layout_attributes_t::align_forward_fill: {\n            if (rfirst->geometry_m.slice_m[select].suppress_m)\n                break;\n\n            guide_set_t& child_guide_set(\n                rfirst->container_guide_set_m[select][layout_attributes_t::align_reverse]);\n\n            guide_set_t::iterator guide(child_guide_set.begin());\n            guide_set_t::iterator guide_last(child_guide_set.end());\n\n            if ((rfirst->geometry_m.placement_m == eve_t::place_leaf) && guide != guide_last) {\n                // Snap the current postion to the guide.\n                assert(reverse_guide_iter !=\n                       container_guide_set_m[select][layout_attributes_t::align_reverse].end());\n                rlength = *reverse_guide_iter++ - *guide++;\n            }\n\n            for (; guide != guide_last; ++guide, ++reverse_guide_iter) {\n                assert(reverse_guide_iter !=\n                       container_guide_set_m[select][layout_attributes_t::align_reverse].end());\n                int new_guide(*reverse_guide_iter - rlength);\n\n                if (new_guide != *guide) {\n                    result = true;\n                    *guide = new_guide;\n                }\n            }\n        } break;\n        default:\n            break;\n        }\n\n        rlength += rfirst->container_length_m[select] + rfirst->space_before_m;\n    }\n\n    if (result)\n        return result;\n\n    for (::child_iterator iter(first); (iter != last) && !result; ++iter) {\n        length += iter->space_before_m;\n\n        switch (iter->geometry_m.slice_m[select].alignment_m) {\n        case layout_attributes_t::align_forward:\n        case layout_attributes_t::align_forward_fill:\n        case layout_attributes_t::align_reverse_fill: {\n            if (iter->geometry_m.slice_m[select].suppress_m)\n                break;\n\n            guide_set_t& child_guide_set(\n                iter->container_guide_set_m[select][layout_attributes_t::align_forward]);\n\n            guide_set_t::iterator guide(child_guide_set.begin());\n            guide_set_t::iterator guide_last(child_guide_set.end());\n\n            if ((iter->geometry_m.placement_m == adobe::eve_t::place_leaf) && guide != guide_last) {\n                // Snap the current postion to the guide.\n                assert(guide_iter !=\n                       container_guide_set_m[select][layout_attributes_t::align_forward].end());\n                length = *guide_iter++ - *guide++;\n            }\n\n            for (; guide != guide_last; ++guide, ++guide_iter) {\n                assert(guide_iter !=\n                       container_guide_set_m[select][layout_attributes_t::align_forward].end());\n                int new_guide(*guide_iter - length);\n\n                if (new_guide != *guide) {\n                    result = true;\n                    *guide = new_guide;\n                }\n            }\n        } break;\n        default:\n            break;\n        }\n\n        length += iter->container_length_m[select];\n    }\n\n    return result;\n}\n\n/**************************************************************************************************/\n\nvoid view_proxy_t::solve_up_cross(::child_iterator first, ::child_iterator last,\n                                  slice_select_t select) {\n    const layout_attributes_t::slice_t& gslice(geometry_m.slice_m[select]);\n    const extents_t::slice_t& eslice(geometry_m.extents_m.slice_m[select]);\n    int near_additional(eslice.frame_m.first + gslice.margin_m.first);\n    int far_additional(eslice.frame_m.second + gslice.margin_m.second);\n    guide_set_t& forward_guide_set(\n        container_guide_set_m[select][layout_attributes_t::align_forward]);\n    guide_set_t& reverse_guide_set(\n        container_guide_set_m[select][layout_attributes_t::align_reverse]);\n\n    // Solve for guides\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        const layout_attributes_t::slice_t& iter_gslice(iter->geometry_m.slice_m[select]);\n\n        if (iter_gslice.suppress_m)\n            continue;\n\n        int forward_iter_length(near_additional);\n        int reverse_iter_length(far_additional);\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_forward:\n        case layout_attributes_t::align_forward_fill:\n            forward_iter_length += iter->geometry_m.indent_m;\n            break;\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill:\n            reverse_iter_length += iter->geometry_m.indent_m;\n            break;\n        default:\n            break;\n        }\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_forward:\n        case layout_attributes_t::align_forward_fill:\n        case layout_attributes_t::align_reverse_fill: {\n            guide_set_t& forward_child_guide_set(\n                iter->container_guide_set_m[select][layout_attributes_t::align_forward]);\n\n            for (guide_set_t::iterator guide_first(forward_child_guide_set.begin()),\n                 guide_last(forward_child_guide_set.end()), base_guide(forward_guide_set.begin());\n                 guide_first != guide_last; ++guide_first, ++base_guide) {\n                assert(base_guide != forward_guide_set.end());\n                *base_guide = std::max(*base_guide, *guide_first + forward_iter_length);\n            }\n        } break;\n        default:\n            break;\n        }\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill:\n        case layout_attributes_t::align_forward_fill: {\n            guide_set_t& reverse_child_guide_set(\n                iter->container_guide_set_m[select][layout_attributes_t::align_reverse]);\n\n            for (guide_set_t::iterator guide_first(reverse_child_guide_set.begin()),\n                 guide_last(reverse_child_guide_set.end()), base_guide(reverse_guide_set.begin());\n                 guide_first != guide_last; ++guide_first, ++base_guide) {\n                assert(base_guide != reverse_guide_set.end());\n                *base_guide = std::max(*base_guide, *guide_first + reverse_iter_length);\n            }\n        } break;\n        default:\n            break;\n        }\n    }\n\n    int length(near_additional + far_additional);\n\n    /*\n    Solve for length. For containers the effects of guides needs to be solved down then back up.\n    For leaf-nodes we offset them directly.\n    */\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        const layout_attributes_t::slice_t& iter_gslice(iter->geometry_m.slice_m[select]);\n\n        int forward_iter_length(near_additional);\n        int reverse_iter_length(far_additional);\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_fill:\n        case layout_attributes_t::align_forward:\n            forward_iter_length += iter->geometry_m.indent_m;\n            break;\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill:\n            reverse_iter_length += iter->geometry_m.indent_m;\n            break;\n        default:\n            break;\n        }\n\n        if (iter->geometry_m.placement_m == eve_t::place_leaf && !iter_gslice.suppress_m) {\n            switch (iter_gslice.alignment_m) {\n            case layout_attributes_t::align_forward:\n            case layout_attributes_t::align_forward_fill:\n            case layout_attributes_t::align_reverse_fill: {\n                guide_set_t& forward_child_guide_set(\n                    iter->container_guide_set_m[select][layout_attributes_t::align_forward]);\n\n                if (forward_child_guide_set.size()) {\n                    forward_iter_length += forward_guide_set.front() -\n                                           (forward_child_guide_set.front() + forward_iter_length);\n                }\n            } break;\n            default:\n                break;\n            }\n            switch (iter_gslice.alignment_m) {\n            case layout_attributes_t::align_reverse:\n            case layout_attributes_t::align_reverse_fill:\n            case layout_attributes_t::align_forward_fill: {\n                guide_set_t& reverse_child_guide_set(\n                    iter->container_guide_set_m[select][layout_attributes_t::align_reverse]);\n                if (reverse_child_guide_set.size()) {\n                    reverse_iter_length += reverse_guide_set.front() -\n                                           (reverse_child_guide_set.front() + reverse_iter_length);\n                }\n            } break;\n            default:\n                break;\n            }\n        }\n\n        length = std::max(length, iter->container_length_m[select] + forward_iter_length +\n                                      reverse_iter_length);\n    }\n\n    // update properties on this container.\n\n    measured_length_m[select] = length;\n    container_length_m[select] = std::max(length, container_length_m[select]);\n}\n\n/**************************************************************************************************/\n\nbool view_proxy_t::solve_down_cross(::child_iterator first, ::child_iterator last,\n                                    slice_select_t select) {\n    bool result(false);\n    const layout_attributes_t::slice_t& gslice(geometry_m.slice_m[select]);\n    const extents_t::slice_t& eslice(geometry_m.extents_m.slice_m[select]);\n    int near_additional(eslice.frame_m.first + gslice.margin_m.first);\n    int far_additional(eslice.frame_m.second + gslice.margin_m.second);\n\n    // Impose guide positions on containers.\n\n    for (::child_iterator iter(first); iter != last; ++iter) {\n        const layout_attributes_t::slice_t& iter_gslice(iter->geometry_m.slice_m[select]);\n\n        if (iter_gslice.suppress_m)\n            continue;\n\n        guide_set_t::iterator forward_guide_iter(\n            container_guide_set_m[select][layout_attributes_t::align_forward].begin());\n        guide_set_t::iterator reverse_guide_iter(\n            container_guide_set_m[select][layout_attributes_t::align_reverse].begin());\n\n        // Leaf nodes are offset to the first guide.\n\n        int length(near_additional);\n        int rlength(far_additional);\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_fill:\n        case layout_attributes_t::align_forward:\n            length += iter->geometry_m.indent_m;\n            break;\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill:\n            rlength += iter->geometry_m.indent_m;\n            break;\n        default:\n            break;\n        }\n\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_forward:\n        case layout_attributes_t::align_forward_fill:\n        case layout_attributes_t::align_reverse_fill: {\n            guide_set_t& forward_child_guide_set(\n                iter->container_guide_set_m[select][layout_attributes_t::align_forward]);\n\n            guide_set_t::iterator forward_guide_first(forward_child_guide_set.begin());\n            guide_set_t::iterator forward_guide_last(forward_child_guide_set.end());\n\n            if (iter->geometry_m.placement_m == adobe::eve_t::place_leaf) {\n                if (forward_guide_first != forward_guide_last)\n                    length = *forward_guide_iter++ - *forward_guide_first++;\n            }\n\n            for (; forward_guide_first != forward_guide_last;\n                 ++forward_guide_first, ++forward_guide_iter) {\n                int new_guide(*forward_guide_iter - length);\n                if (new_guide != *forward_guide_first) {\n                    result = true;\n                    *forward_guide_first = new_guide;\n                }\n            }\n        } break;\n        default:\n            break;\n        }\n        switch (iter_gslice.alignment_m) {\n        case layout_attributes_t::align_reverse:\n        case layout_attributes_t::align_reverse_fill:\n        case layout_attributes_t::align_forward_fill: {\n            guide_set_t& reverse_child_guide_set(\n                iter->container_guide_set_m[select][layout_attributes_t::align_reverse]);\n\n            guide_set_t::iterator reverse_guide_first(reverse_child_guide_set.begin());\n            guide_set_t::iterator reverse_guide_last(reverse_child_guide_set.end());\n\n            if (iter->geometry_m.placement_m == adobe::eve_t::place_leaf) {\n                if (reverse_guide_first != reverse_guide_last)\n                    rlength = *reverse_guide_iter++ - *reverse_guide_first++;\n            }\n\n            for (; reverse_guide_first != reverse_guide_last;\n                 ++reverse_guide_first, ++reverse_guide_iter) {\n                int new_guide(*reverse_guide_iter - rlength);\n                if (new_guide != *reverse_guide_first) {\n                    result = true;\n                    *reverse_guide_first = new_guide;\n                }\n            }\n        } break;\n        default:\n            break;\n        }\n    }\n    return result;\n}\n\n/**************************************************************************************************/\n\n} // namespace implementation\n\n/**************************************************************************************************/\n\n#if 0\n#pragma mark -\n#endif\n\n/**************************************************************************************************/\n\n#if !defined(ADOBE_NO_DOCUMENTATION)\n\nplace_data_t::slice_t::slice_t() : length_m(0), position_m(0) {}\n\n#endif\n\n/**************************************************************************************************/\n\n} // namespace adobe\n\n/**************************************************************************************************/\n", "meta": {"hexsha": "822b0b454a98e80fa7473db73834cb5c6a7ba263", "size": 68274, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/eve.cpp", "max_stars_repo_name": "jaredwy/adobe_source_libraries", "max_stars_repo_head_hexsha": "b71f5d08ab10396e9d2ba5e73861ca018f899a2d", "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": "source/eve.cpp", "max_issues_repo_name": "jaredwy/adobe_source_libraries", "max_issues_repo_head_hexsha": "b71f5d08ab10396e9d2ba5e73861ca018f899a2d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-04T12:42:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T12:42:52.000Z", "max_forks_repo_path": "source/eve.cpp", "max_forks_repo_name": "jaredwy/adobe_source_libraries", "max_forks_repo_head_hexsha": "b71f5d08ab10396e9d2ba5e73861ca018f899a2d", "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.0807097882, "max_line_length": 100, "alphanum_fraction": 0.5981193426, "num_tokens": 13505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.15454197458740657}}
{"text": "#include <booster/booster.h>\n#include <booster/sgeconv.h>\n#include <immintrin.h>\n#include <string.h>\n\nint align_ceil(int num, int align)\n{\n    return num + (align - (num % align)) % align;\n}\n\nvoid (*inner_kernel_Nx16)(int K, float *packA, float *packB, float *c, int ldc);\n\n#include <stdio.h>\ntemplate<int N>\nvoid inner_kernel_Nx16_template(int K, float *packA, float *packB, float *c, int ldc)\n{\n    float *aptr = packA;\n    float *bptr = packB;\n    float *cptr = c;\n    __m256 va, va1, va2, va3, va4, va5;\n    __m256 vb0, vb1, vb2, vB0, vB1, vB2;\n    __m256 vc0, vc1, vc2, vc3, vc4, vc5, vc6, vc7, vc8, vc9, vcA, vcB;\n\n    //N is 1, 2, 3, 4, 5, 6\n    vc0 = _mm256_load_ps(cptr);\n    vc6 = _mm256_load_ps(cptr + 8);\n    cptr += ldc;\n    if (N > 1) //N is 2, 3, 4, 5, 6\n    {\n        vc1 = _mm256_load_ps(cptr);\n        vc7 = _mm256_load_ps(cptr + 8);\n        cptr += ldc;\n    }\n    if (N > 2) //N is 3, 4, 5, 6\n    {\n        vc2 = _mm256_load_ps(cptr);\n        vc8 = _mm256_load_ps(cptr + 8);\n        cptr += ldc;\n    }\n    if (N > 3) //N is 4, 5, 6\n    {\n        vc3 = _mm256_load_ps(cptr);\n        vc9 = _mm256_load_ps(cptr + 8);\n        cptr += ldc;\n    }\n    if (N > 4) //N is 5, 6\n    {\n        vc4 = _mm256_load_ps(cptr);\n        vcA = _mm256_load_ps(cptr + 8);\n        cptr += ldc;\n    }\n    if (N > 5) //N is 6\n    {\n        vc5 = _mm256_load_ps(cptr);\n        vcB = _mm256_load_ps(cptr + 8);\n    }\n    vb0 = _mm256_load_ps(bptr);\n    vb1 = _mm256_load_ps(bptr + 8);\n    for (int p = 0; p < (K - 1); ++p)\n    {\n        va = _mm256_broadcast_ss(aptr);\n        vc0 = _mm256_fmadd_ps(vb0, va, vc0);\n        vc6 = _mm256_fmadd_ps(vb1, va, vc6);\n\n        if (N > 1)\n        {\n            va = _mm256_broadcast_ss(aptr + 1);\n            vc1 = _mm256_fmadd_ps(vb0, va, vc1);\n            vc7 = _mm256_fmadd_ps(vb1, va, vc7);\n        }\n\n        if (N > 2)\n        {\n            va = _mm256_broadcast_ss(aptr + 2);\n            vc2 = _mm256_fmadd_ps(vb0, va, vc2);\n            vc8 = _mm256_fmadd_ps(vb1, va, vc8);\n        }\n\n        if (N > 3)\n        {\n            va = _mm256_broadcast_ss(aptr + 3);\n            vc3 = _mm256_fmadd_ps(vb0, va, vc3);\n            vc9 = _mm256_fmadd_ps(vb1, va, vc9);\n        }\n\n        if (N > 4)\n        {\n            va = _mm256_broadcast_ss(aptr + 4);\n            vc4 = _mm256_fmadd_ps(vb0, va, vc4);\n            vcA = _mm256_fmadd_ps(vb1, va, vcA);\n        }\n\n\n        if (N > 5)\n        {\n            va = _mm256_broadcast_ss(aptr + 5);\n            vc5 = _mm256_fmadd_ps(vb0, va, vc5);\n            vcB = _mm256_fmadd_ps(vb1, va, vcB);\n        }\n\n        vb0 = _mm256_load_ps(bptr + 16);\n        vb1 = _mm256_load_ps(bptr + 24);\n        bptr += 16;\n        aptr += N;\n    }\n    cptr = c;\n    va = _mm256_broadcast_ss(aptr);\n    vc0 = _mm256_fmadd_ps(vb0, va, vc0);\n    vc6 = _mm256_fmadd_ps(vb1, va, vc6);\n    _mm256_store_ps(cptr, vc0);\n    _mm256_store_ps(cptr + 8, vc6);\n    if (N > 1)\n    {\n        va = _mm256_broadcast_ss(aptr + 1);\n        vc1 = _mm256_fmadd_ps(vb0, va, vc1);\n        vc7 = _mm256_fmadd_ps(vb1, va, vc7);\n        cptr += ldc;\n        _mm256_store_ps(cptr, vc1);\n        _mm256_store_ps(cptr + 8, vc7);\n    }\n    if (N > 2)\n    {\n        va = _mm256_broadcast_ss(aptr + 2);\n        vc2 = _mm256_fmadd_ps(vb0, va, vc2);\n        vc8 = _mm256_fmadd_ps(vb1, va, vc8);\n        cptr += ldc;\n        _mm256_store_ps(cptr, vc2);\n        _mm256_store_ps(cptr + 8, vc8);\n    }\n    if (N > 3)\n    {\n        va = _mm256_broadcast_ss(aptr + 3);\n        vc3 = _mm256_fmadd_ps(vb0, va, vc3);\n        vc9 = _mm256_fmadd_ps(vb1, va, vc9);\n        cptr += ldc;\n        _mm256_store_ps(cptr, vc3);\n        _mm256_store_ps(cptr + 8, vc9);\n    }\n    if (N > 4)\n    {\n        va = _mm256_broadcast_ss(aptr + 4);\n        vc4 = _mm256_fmadd_ps(vb0, va, vc4);\n        vcA = _mm256_fmadd_ps(vb1, va, vcA);\n        cptr += ldc;\n        _mm256_store_ps(cptr, vc4);\n        _mm256_store_ps(cptr + 8, vcA);\n    }\n    if (N > 5)\n    {\n        va = _mm256_broadcast_ss(aptr + 5);\n        vc5 = _mm256_fmadd_ps(vb0, va, vc5);\n        vcB = _mm256_fmadd_ps(vb1, va, vcB);\n        cptr += ldc;\n        _mm256_store_ps(cptr, vc5);\n        _mm256_store_ps(cptr + 8, vcB);\n    }\n}\n\nvoid set_kernel(int k)\n{\n    switch (k)\n    {\n        case 1:\n            inner_kernel_Nx16 = inner_kernel_Nx16_template<1>;\n            break;\n        case 2:\n            inner_kernel_Nx16 = inner_kernel_Nx16_template<2>;\n            break;\n        case 3:\n            inner_kernel_Nx16 = inner_kernel_Nx16_template<3>;\n            break;\n        case 4:\n            inner_kernel_Nx16 = inner_kernel_Nx16_template<4>;\n            break;\n        case 5:\n            inner_kernel_Nx16 = inner_kernel_Nx16_template<5>;\n            break;\n        case 0:\n            inner_kernel_Nx16 = inner_kernel_Nx16_template<6>;\n            break;\n    }\n}\n\n\ntemplate<bool fuseBias, bool fuseRelu>\ninline void compute_block_activation(int M, int nc, int kc, float* packA, float* packB, float* loadC, float *C, int ldc, float* bias, int bias_len)\n{\n    //M is already aligned.\n    int nc_ceil = align_ceil(nc, 16);\n    int nc_floor = nc - nc % 8;\n    for (int i = 0; i < M - M % 6; i += 6)\n    {\n        //Load C into cache\n        float* rC = C + i * ldc;\n        for (int m = 0; m < 6; ++m)\n        {\n            float* pC = rC + m * ldc;\n            float* pL = loadC + m * nc_ceil;\n            for (int n = 0; n < nc_floor; n += 8)\n            {\n                _mm256_store_ps(pL + n, _mm256_load_ps(pC + n));\n            }\n            for (int n = nc - nc % 8; n < nc; ++n)\n            {\n                pL[n] = pC[n];\n            }\n        }\n        for (int j = 0; j < nc_ceil; j += 16)\n        {\n            float* pC = loadC + j;\n            float* pA = packA + i * kc;\n            float* pB = packB + j * kc;\n            inner_kernel_Nx16_template<6>(kc, pA, pB, pC, nc_ceil);\n        }\n        //Write Results\n        for (int m = 0; m < 6; ++m)\n        {\n            float* pC = rC + m * ldc;\n            float* pL = loadC + m * nc_ceil;\n            __m256 vZero = _mm256_set1_ps(0.f);\n            __m256 vBias = vZero;\n            if (m + i < bias_len)\n            {\n                if (fuseBias)\n                    vBias = _mm256_broadcast_ss(bias + i + m);\n            }\n            for (int n = 0; n < nc_floor; n += 8)\n            {\n                __m256 vec = _mm256_load_ps(pL + n);\n                if (fuseBias)\n                    vec = _mm256_add_ps(vec, vBias);\n                if (fuseRelu)\n                    vec = _mm256_max_ps(vec, vZero);\n\n                _mm256_storeu_ps(pC + n, vec);\n            }\n            //Last column batch.\n            for (int n = nc - nc % 8; n < nc; ++n)\n            {\n                float l = pL[n];\n                if (fuseBias && ((i + m) < bias_len))\n                    l += bias[i + m];\n                if (fuseRelu)\n                    l = (l > 0) ? l : 0;\n                pC[n] = l;\n            }\n        }\n    }\n    int m_len = M % 6;\n    if (m_len)\n    {\n        int i = M - M % 6;\n        //Load C into cache\n        float* rC = C + i * ldc;\n        for (int m = 0; m < m_len; ++m)\n        {\n            float* pC = rC + m * ldc;\n            float* pL = loadC + m * nc_ceil;\n            for (int n = 0; n < nc_floor; n += 8)\n            {\n                _mm256_store_ps(pL + n, _mm256_load_ps(pC + n));\n            }\n            for (int n = nc - nc % 8; n < nc; ++n)\n            {\n                pL[n] = pC[n];\n            }\n        }\n        for (int j = 0; j < nc_ceil; j += 16)\n        {\n            float* pC = loadC + j;\n            float* pA = packA + i * kc;\n            float* pB = packB + j * kc;\n            inner_kernel_Nx16(kc, pA, pB, pC, nc_ceil);\n        }\n        //Write Results\n        for (int m = 0; m < m_len; ++m)\n        {\n            float* pC = rC + m * ldc;\n            float* pL = loadC + m * nc_ceil;\n            __m256 vZero = _mm256_set1_ps(0.f);\n            __m256 vBias = vZero;\n            if (m + i < bias_len)\n            {\n                if (fuseBias)\n                    vBias = _mm256_broadcast_ss(bias + i + m);\n            }\n            for (int n = 0; n < nc_floor; n += 8)\n            {\n                __m256 vec = _mm256_load_ps(pL + n);\n                if (fuseBias)\n                    vec = _mm256_add_ps(vec, vBias);\n                if (fuseRelu)\n                    vec = _mm256_max_ps(vec, vZero);\n\n                _mm256_storeu_ps(pC + n, vec);\n            }\n            //Last column batch.\n            for (int n = nc - nc % 8; n < nc; ++n)\n            {\n                float l = pL[n];\n                if (fuseBias && ((i + m) < bias_len))\n                    l += bias[i + m];\n                if (fuseRelu)\n                    l = (l > 0) ? l : 0;\n                pC[n] = l;\n            }\n        }\n    }\n}\n\n//Decide how many rows should be packed together.\ntemplate<int ROW_BATCH>\nvoid packed_sgeconv_init(int M, int K, int kc, float* packA, float* A, int lda)\n{\n    //int M_align = align_ceil(M, 6);\n    for (int p = 0; p < K; p += kc)\n    {\n\n        //The last row batch may not have sufficient rows\n        //Implicit padding so as to reduce code complexity for packed_sgemm\n        //float* pPack = packA + (p / kc) * M_align * kc;\n        float* pPack = packA + (p / kc) * M * kc;\n        for (int i = 0; i < M; i += ROW_BATCH)\n        {\n            int k_len = kc;\n            int j_len = ROW_BATCH;\n            if (M - i < ROW_BATCH)\n            {\n                j_len = M - i;\n            }\n            float* pA = A + i * lda + p;\n            if (K - p < kc)\n                k_len = K - p;\n            //Every ROW_BATCH rows are batched together.\n            for (int k = 0; k < k_len; ++k)\n            {\n                for (int j = 0; j < j_len; ++j)\n                {\n                    pPack[j] = pA[j * lda];\n                }\n                pPack += j_len;\n                pA++;\n            }\n        }\n    }\n}\n\ntemplate void packed_sgeconv_init<6>(int M, int K, int kc, float* packedA, float* A, int lda);\n\nvoid pack_B_avx(int kc, int nc, float* packB, float* B, int ldb)\n{\n    const int COL_BATCH = 16;\n    int nc_floor = nc - nc % COL_BATCH;\n    for (int k = 0; k < kc; ++k)\n    {\n        float* pB = B + k * ldb;\n        for (int j = 0; j < nc_floor; j += COL_BATCH)\n        {\n            float* pPack = packB + (j / COL_BATCH) * kc * COL_BATCH + k * COL_BATCH;\n            _mm256_store_ps(pPack, _mm256_loadu_ps(pB));\n            _mm256_store_ps(pPack + 8, _mm256_loadu_ps(pB + 8));\n            pB += 16;\n        }\n        if (nc_floor < nc)\n        {\n            int j = nc_floor;\n            int n_len = nc - nc_floor;\n            float* pPack = packB + (j / COL_BATCH) * kc * COL_BATCH + k * COL_BATCH;\n            for (int i = 0; i < n_len; ++i)\n            {\n                pPack[i] = pB[i];\n            }\n        }\n    }\n}\n\n\n\nvoid pack_B_im2col_stride_1_avx(booster::ConvParam *conv_param, int kc, int nc, int nt, float* packB, float* tB, float *B, int ldb)\n{\n    const int COL_BATCH = 16;\n    int nc_floor = nc - nc % COL_BATCH;\n    // int pad_left = 1;\n    // int pad_top = 1;\n    int img_pixels = conv_param->input_h * conv_param->input_w;\n    int img_ld = conv_param->input_w;\n    int base_col_index = nt % conv_param->input_w - conv_param->pad_left;\n    for (int k = 0; k < kc; ++k)\n    {\n        float *pChannel = tB + k * img_pixels;\n        for (int kh = 0; kh < conv_param->kernel_h; ++kh)\n        {\n            for (int kw = 0; kw < conv_param->kernel_w; ++kw)\n            {\n                // float *pB = tB + k * ldb + kw;\n                int row_idx = k + kh * conv_param->kernel_w + kw - conv_param->pad_top;\n                for (int j = 0; j < nc; j += COL_BATCH) //nc is the #(output pixels) to be computed\n                {\n                    int img_col_idx = (base_col_index + j + kw);\n                    float *pB = tB + img_col_idx + k * ldb;\n\n                    float *pPack = packB + (j / COL_BATCH) * kc * COL_BATCH + row_idx * COL_BATCH;\n                    // _mm256_store_ps(pPack, _mm256_loadu_ps(pB));\n                    // _mm256_store_ps(pPack + 8, _mm256_loadu_ps(pB + 8));\n                    for (int i = 0; i < COL_BATCH; ++i)\n                    {\n                        pPack[i] = (img_col_idx + i < 0 || img_col_idx + i > conv_param->input_w) ? 0.f : pB[i];\n                        ++pB;\n                    }\n                    // pB += COL_BATCH;\n                }\n                // if (nc_floor < nc)\n                // {\n                //  int j = nc_floor;\n                //  int n_len = nc - nc_floor;\n                //  float *pPack = packB + (j / COL_BATCH) * kc * COL_BATCH + row_idx * COL_BATCH;\n                //  for (int i = 0; i < n_len; ++i)\n                //  {\n                //      pPack[i] = pB[i];\n                //  }\n                // }\n            }\n        }\n    }\n}\n#include <assert.h>\ntemplate<bool fuseBias, bool fuseRelu>\nvoid packed_sgeconv_im2col_activation(booster::ConvParam *conv_param, float *packA, float *B, const int ldb, float *C, const int ldc, const int nc, const int kc, float* bias)\n{\n    //nc = nc - nc % (kernel_h * kernel_w);\n    int M = conv_param->output_channels;\n    int N = conv_param->input_h * conv_param->input_w;//pixel num\n    int K = conv_param->kernel_h * conv_param->kernel_w * conv_param->input_channels;\n    assert(nc % (conv_param->kernel_h * conv_param->kernel_w) == 0);\n    set_kernel(M % 6);\n    for (int i = 0; i < M; ++i)\n    {\n        memset(C + ldc * i, 0, sizeof(float) * N);\n    }\n\n    int M_align = align_ceil(M, 6);\n    int N_align = align_ceil(N, 16);\n\n    int NBlocks = (N_align + nc - 1) / nc;\n    int KBlocks = (K + kc - 1) / kc;\n\n    //float* packB = (float *) _mm_malloc(sizeof(float) * kc * nc, 32);\n    //float* loadC = (float *) _mm_malloc(sizeof(float) * 6 * nc, 32);\n    //printf(\"loadC %x %d\\n\", loadC, ((size_t) loadC) % 32);\n\n    //Our GEMM is implemented in GEPB fashion, as the operands are row-major\n    int k_len = kc;\n    int n_len = nc;\n\n    //kt is always the channel index.\n    for (int kt = 0; kt < KBlocks - 1; ++kt)\n    {\n        //k_len = (kt == KBlocks - 1) ? (K - kt * kc) : kc;\n//#pragma omp parallel for num_threads(2)\n        for (int nt = 0; nt < NBlocks; ++nt)\n        {\n            FEATHER_MEN_ALIGN(32) float loadC[6 * nc];\n            FEATHER_MEN_ALIGN(32) float packB[kc * nc];\n            //float* pA = packA + kt * kc * M_align;\n            float* pA = packA + kt * kc * M;\n            float* pB = B + kt * kc * ldb + nt * nc;\n            float* pC = C + nt * nc;\n            if (nt == NBlocks - 1)\n                n_len = N - nt * nc;\n            else\n                n_len = nc;\n            memset(packB, 0, sizeof(float) * kc * nc);\n            // pack_B_avx(k_len, n_len, packB, pB, N);\n            pack_B_im2col_stride_1_avx(conv_param, kc, nc, nt * nt, packB, pB, B, N);\n            compute_block_activation<false, false>(M, n_len, k_len, pA, packB, loadC, pC, ldc, bias, M);\n        }\n    }\n    {\n        int kt = KBlocks - 1;\n        k_len = (K - kt * kc);\n        FEATHER_MEN_ALIGN(32) float loadC[6 * nc];\n//#pragma omp parallel for num_threads(2)\n        for (int nt = 0; nt < NBlocks; ++nt)\n        {\n            //float loadC[6 * nc];\n            //float* pA = packA + kt * kc * M_align;\n            FEATHER_MEN_ALIGN(32) float loadC[6 * nc];\n            FEATHER_MEN_ALIGN(32) float packB[kc * nc];\n            float* pA = packA + kt * kc * M;\n            float* pB = B + kt * kc * ldb + nt * nc;\n            float* pC = C + nt * nc;\n            if (nt == NBlocks - 1)\n                n_len = N - nt * nc;\n            else\n                n_len = nc;\n            //I'm going to pack B in here.\n            memset(packB, 0, sizeof(float) * kc * nc);\n            pack_B_avx(k_len, n_len, packB, pB, N);\n            compute_block_activation<fuseBias, fuseRelu>(M, n_len, k_len, pA, packB, loadC, pC, ldc, bias, M);\n        }\n    }\n    //_mm_free(packB);\n    //_mm_free(loadC);\n}\n\ntemplate void packed_sgeconv_im2col_activation<false, false>(booster::ConvParam *conv_param, float *packA, float *B, const int ldb, float *C, const int ldc, const int nc, const int kc, float* bias);\n// template void packed_sgeconv_im2col_activation<false,  true>(int, int, int, int, int, int, float*, float*, int, float*, int, int, int, float*);\n// template void packed_sgeconv_im2col_activation<true,  false>(int, int, int, int, int, int, float*, float*, int, float*, int, int, int, float*);\n// template void packed_sgeconv_im2col_activation<true,   true>(int, int, int, int, int, int, float*, float*, int, float*, int, int, int, float*);\n", "meta": {"hexsha": "2c553bb99f76e9ac4382d91431af592741f00c20", "size": 16646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/booster/avx/sgeconv.cpp", "max_stars_repo_name": "nihui/FeatherCNN", "max_stars_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-14T09:00:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:11:54.000Z", "max_issues_repo_path": "src/booster/avx/sgeconv.cpp", "max_issues_repo_name": "nihui/FeatherCNN", "max_issues_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "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/booster/avx/sgeconv.cpp", "max_forks_repo_name": "nihui/FeatherCNN", "max_forks_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "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.6392156863, "max_line_length": 198, "alphanum_fraction": 0.4744683407, "num_tokens": 5332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.15428589303248158}}
{"text": "// ======================================================================\n/*!\n * \\file NFmiSaveBaseFactory.cpp\n * \\brief Implementation of a factory for newbase objects\n */\n// ======================================================================\n\n#include \"NFmiSaveBaseFactory.h\"\n#include \"NFmiEquidistArea.h\"\n#include \"NFmiGdalArea.h\"\n#include \"NFmiGnomonicArea.h\"\n#include \"NFmiGrid.h\"\n#include \"NFmiLambertEqualArea.h\"\n#include \"NFmiLatLonArea.h\"\n#include \"NFmiMercatorArea.h\"\n#include \"NFmiQueryData.h\"\n#include \"NFmiRotatedLatLonArea.h\"\n#include \"NFmiStationBag.h\"\n#include \"NFmiStereographicArea.h\"\n#include \"NFmiYKJArea.h\"\n\n#include \"NFmiVersion.h\"\n\n#include <boost/lexical_cast.hpp>\n\n// Having 'extern' and initializatin is no good (gcc gives a warning).\n//  -AKa 3-Jun-10\n//\n// Note that these are GLOBALLY WRITTEN TO in 'NFmiMetBox.cpp' (looks very suspicious...)\n//  -AKa 3-Jun-10\n//\nunsigned short FmiBoxVersion = 3;\nunsigned short FmiInfoVersion = 7;\n\n// ----------------------------------------------------------------------\n/*!\n * Returns a newbase object based on the given unique numeric ID.\n * The returned object is a void pointer, which makes this a rather\n * strange factory, but it will have to do until a complete redesign.\n *\n * \\param classId The ID of the object to be created\n * \\return Pointer to the new object\n * \\todo Should return an boost::shared_ptr\n */\n// ----------------------------------------------------------------------\n\nvoid *CreateSaveBase(unsigned int classId)\n{\n  switch (classId)\n  {\n    case kNFmiGrid:\n      return static_cast<void *>(new NFmiGrid);\n\n    case kNFmiLambertEqualArea:\n      return static_cast<void *>(new NFmiLambertEqualArea);\n    case kNFmiLatLonArea:\n      return static_cast<void *>(new NFmiLatLonArea);\n    case kNFmiRotatedLatLonArea:\n      return static_cast<void *>(new NFmiRotatedLatLonArea);\n    case kNFmiStereographicArea:\n      return static_cast<void *>(new NFmiStereographicArea);\n    case kNFmiYKJArea:\n      return static_cast<void *>(new NFmiYKJArea);\n    case kNFmiEquiDistArea:\n      return static_cast<void *>(new NFmiEquidistArea);\n    case kNFmiMercatorArea:\n      return static_cast<void *>(new NFmiMercatorArea);\n    case kNFmiGnomonicArea:\n      return static_cast<void *>(new NFmiGnomonicArea);\n\n    case kNFmiQueryData:\n      return static_cast<void *>(new NFmiQueryData);\n    case kNFmiQueryInfo:\n      return static_cast<void *>(new NFmiQueryInfo);\n\n    case kNFmiLocationBag:\n      return static_cast<void *>(new NFmiLocationBag);\n    case kNFmiStationBag:\n      return static_cast<void *>(new NFmiStationBag);\n#ifdef UNIX\n    case kNFmiGdalArea:\n      return static_cast<void *>(new NFmiGdalArea);\n#endif\n\n    default:\n      throw std::runtime_error(\"Newbase: unable to create unknown class \" +\n                               boost::lexical_cast<std::string>(classId));\n  }\n}\n\n// ======================================================================\n", "meta": {"hexsha": "629038cbbd176f827c8bcc5c63fd0b10585bb2ea", "size": 2948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/newbase/newbase/NFmiSaveBaseFactory.cpp", "max_stars_repo_name": "fmidev/smartmet-workstation-vtk", "max_stars_repo_head_hexsha": "ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99", "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": "modules/newbase/newbase/NFmiSaveBaseFactory.cpp", "max_issues_repo_name": "fmidev/smartmet-workstation-vtk", "max_issues_repo_head_hexsha": "ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99", "max_issues_repo_licenses": ["MIT"], "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/newbase/newbase/NFmiSaveBaseFactory.cpp", "max_forks_repo_name": "fmidev/smartmet-workstation-vtk", "max_forks_repo_head_hexsha": "ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99", "max_forks_repo_licenses": ["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.0434782609, "max_line_length": 89, "alphanum_fraction": 0.6285617368, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.15389650653560066}}
{"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_DETAILS_BLAS_RK_HPP_INCLUDED\n#define NT2_LINALG_DETAILS_BLAS_RK_HPP_INCLUDED\n\n#include <complex>\n#include <boost/preprocessor/cat.hpp>\n#include <nt2/linalg/details/blas/blas3.hpp>\n#include <nt2/linalg/details/utility/f77_wrapper.hpp>\n\nnamespace nt2 { namespace details\n{\n#define NT2_RK(T, PREFIX)                                           \\\ninline void syrk( const char *uplo, const long int *n               \\\n                , const T *al                                       \\\n                , const T *a, const long int *lda                   \\\n                , const T *be                                       \\\n                , T *c      , const long int *ldc                   \\\n                )                                                   \\\n{                                                                   \\\n  NT2_F77NAME(BOOST_PP_CAT(PREFIX,syrk))(uplo,n,al,a,lda,be,c,ldc); \\\n}                                                                   \\\n/**/\n\n  // INTERNAL ONLY\n  // tA is the transpose of A\n  // syrk  C <- al*A*tA+be*C or  C <- al*tA*A+be*C (trans N, T)\n  NT2_RK(double, d)\n  NT2_RK(float,  s)\n  NT2_RK(std::complex<double> , z )\n  NT2_RK(std::complex<float>  , c )\n#undef NT2_RK\n\n#define NT2_RK(T, PREFIX)                                           \\\ninline void herk( const char *uplo, const long int *n               \\\n                , const T *al                                       \\\n                , const T *a, const long int *lda                   \\\n                , const T *be                                       \\\n                , T *c      , const long int *ldc                   \\\n                )                                                   \\\n{                                                                   \\\n  NT2_F77NAME(BOOST_PP_CAT(PREFIX,herk))(uplo,n,al,a,lda,be,c,ldc); \\\n}                                                                   \\\n/**/\n\n  // INTERNAL ONLY\n  // hA is the transconjugate of A\n  // herk  C <- al*A*hA+be*C or  C <- al*A*hA+be*C (trans N, C)\n  NT2_RK(std::complex<double>, z)\n  NT2_RK(std::complex<float>, c)\n#undef NT2_RK\n\n} }\n\n#endif\n", "meta": {"hexsha": "c69abdf62170337c7a7363a18c83b8dee0811374", "size": 2662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/details/blas/rk.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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/details/blas/rk.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/linalg/include/nt2/linalg/details/blas/rk.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": 42.935483871, "max_line_length": 80, "alphanum_fraction": 0.3933132983, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.30074556640652345, "lm_q1q2_score": 0.15389650012137726}}
{"text": "#define BOOST_TEST_MODULE signer_validator_unittest\n#include <boost/test/included/unit_test.hpp>\n\n#include <iostream>\n\n#include <core/Message.h>\n#include <crypto/PrivateKey.h>\n#include <crypto/PublicKey.h>\n#include <crypto/Validator.h>\n#include <crypto/Signer.h>\n\nusing namespace ultrainio;\nusing namespace std;\n\n// Signer/Validator\nBOOST_AUTO_TEST_SUITE(signer_validator_test_suite)\n\n    BOOST_AUTO_TEST_CASE(normal) {\n        PrivateKey privateKey;\n        PublicKey publicKey;\n        PrivateKey::generate(publicKey, privateKey);\n        Block block;\n        block.version = 1;\n        block.proposer = N(\"ultr_genesis\");\n        block.signature = std::string(Signer::sign<BlockHeader>(block, privateKey));\n        BOOST_CHECK(Validator::verify<BlockHeader>(Signature(block.signature), block, publicKey));\n\n        EchoMsg echoMsg;\n        echoMsg.baxCount = 0;\n        echoMsg.account = N(\"ultr_test\");\n        echoMsg.signature = std::string(Signer::sign<UnsignedEchoMsg>(echoMsg, privateKey));\n        BOOST_CHECK(Validator::verify<UnsignedEchoMsg>(Signature(echoMsg.signature), echoMsg, publicKey));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "6f3726b86d2afdfbbe6c4bffa5f30f7449a5e92d", "size": 1141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/crypto/SignerValidatorTest.cpp", "max_stars_repo_name": "sighttviewliu/ultrain-core-production", "max_stars_repo_head_hexsha": "c2807d9310da8b5dc1408502866be59299a96c22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-19T05:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-19T05:25:28.000Z", "max_issues_repo_path": "unittests/crypto/SignerValidatorTest.cpp", "max_issues_repo_name": "sighttviewliu/ultrain-core-production", "max_issues_repo_head_hexsha": "c2807d9310da8b5dc1408502866be59299a96c22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/crypto/SignerValidatorTest.cpp", "max_forks_repo_name": "sighttviewliu/ultrain-core-production", "max_forks_repo_head_hexsha": "c2807d9310da8b5dc1408502866be59299a96c22", "max_forks_repo_licenses": ["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.6, "max_line_length": 106, "alphanum_fraction": 0.7204206836, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.15389650012137723}}
{"text": "#ifndef OSRM_GUIDANCE_TOOLKIT_HPP_\n#define OSRM_GUIDANCE_TOOLKIT_HPP_\n\n#include \"util/attributes.hpp\"\n#include \"util/bearing.hpp\"\n#include \"util/coordinate.hpp\"\n#include \"util/coordinate_calculation.hpp\"\n#include \"util/guidance/toolkit.hpp\"\n#include \"util/guidance/turn_lanes.hpp\"\n#include \"util/typedefs.hpp\"\n\n#include \"extractor/compressed_edge_container.hpp\"\n#include \"extractor/query_node.hpp\"\n\n#include \"extractor/guidance/discrete_angle.hpp\"\n#include \"extractor/guidance/intersection.hpp\"\n#include \"extractor/guidance/turn_instruction.hpp\"\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <map>\n#include <string>\n#include <unordered_map>\n#include <utility>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/tokenizer.hpp>\n\nnamespace osrm\n{\nnamespace extractor\n{\nnamespace guidance\n{\n\nusing util::guidance::LaneTupelIdPair;\nusing LaneDataIdMap = std::unordered_map<LaneTupelIdPair, LaneDataID, boost::hash<LaneTupelIdPair>>;\n\nusing util::guidance::angularDeviation;\nusing util::guidance::entersRoundabout;\nusing util::guidance::leavesRoundabout;\n\nnamespace detail\n{\nconst constexpr double DESIRED_SEGMENT_LENGTH = 10.0;\n\ntemplate <typename IteratorType>\nutil::Coordinate\ngetCoordinateFromCompressedRange(util::Coordinate current_coordinate,\n                                 const IteratorType compressed_geometry_begin,\n                                 const IteratorType compressed_geometry_end,\n                                 const util::Coordinate final_coordinate,\n                                 const std::vector<extractor::QueryNode> &query_nodes)\n{\n    const auto extractCoordinateFromNode =\n        [](const extractor::QueryNode &node) -> util::Coordinate {\n        return {node.lon, node.lat};\n    };\n    double distance_to_current_coordinate = 0;\n    double distance_to_next_coordinate = 0;\n\n    // get the length that is missing from the current segment to reach DESIRED_SEGMENT_LENGTH\n    const auto getFactor = [](const double first_distance, const double second_distance) {\n        BOOST_ASSERT(first_distance < detail::DESIRED_SEGMENT_LENGTH);\n        double segment_length = second_distance - first_distance;\n        BOOST_ASSERT(segment_length > 0);\n        BOOST_ASSERT(second_distance >= detail::DESIRED_SEGMENT_LENGTH);\n        double missing_distance = detail::DESIRED_SEGMENT_LENGTH - first_distance;\n        return std::max(0., std::min(missing_distance / segment_length, 1.0));\n    };\n\n    for (auto compressed_geometry_itr = compressed_geometry_begin;\n         compressed_geometry_itr != compressed_geometry_end;\n         ++compressed_geometry_itr)\n    {\n        const auto next_coordinate =\n            extractCoordinateFromNode(query_nodes[compressed_geometry_itr->node_id]);\n        distance_to_next_coordinate =\n            distance_to_current_coordinate +\n            util::coordinate_calculation::haversineDistance(current_coordinate, next_coordinate);\n\n        // reached point where coordinates switch between\n        if (distance_to_next_coordinate >= detail::DESIRED_SEGMENT_LENGTH)\n            return util::coordinate_calculation::interpolateLinear(\n                getFactor(distance_to_current_coordinate, distance_to_next_coordinate),\n                current_coordinate,\n                next_coordinate);\n\n        // prepare for next iteration\n        current_coordinate = next_coordinate;\n        distance_to_current_coordinate = distance_to_next_coordinate;\n    }\n\n    distance_to_next_coordinate =\n        distance_to_current_coordinate +\n        util::coordinate_calculation::haversineDistance(current_coordinate, final_coordinate);\n\n    // reached point where coordinates switch between\n    if (distance_to_current_coordinate < detail::DESIRED_SEGMENT_LENGTH &&\n        distance_to_next_coordinate >= detail::DESIRED_SEGMENT_LENGTH)\n        return util::coordinate_calculation::interpolateLinear(\n            getFactor(distance_to_current_coordinate, distance_to_next_coordinate),\n            current_coordinate,\n            final_coordinate);\n    else\n        return final_coordinate;\n}\n} // namespace detail\n\n// Finds a (potentially interpolated) coordinate that is DESIRED_SEGMENT_LENGTH away\n// from the start of an edge\ninline util::Coordinate\ngetRepresentativeCoordinate(const NodeID from_node,\n                            const NodeID to_node,\n                            const EdgeID via_edge_id,\n                            const bool traverse_in_reverse,\n                            const extractor::CompressedEdgeContainer &compressed_geometries,\n                            const std::vector<extractor::QueryNode> &query_nodes)\n{\n    const auto extractCoordinateFromNode =\n        [](const extractor::QueryNode &node) -> util::Coordinate {\n        return {node.lon, node.lat};\n    };\n\n    // Uncompressed roads are simple, return the coordinate at the end\n    if (!compressed_geometries.HasZippedEntryForForwardID(via_edge_id) && !compressed_geometries.HasZippedEntryForReverseID(via_edge_id))\n    {\n        return extractCoordinateFromNode(traverse_in_reverse ? query_nodes[from_node]\n                                                             : query_nodes[to_node]);\n    }\n    else\n    {\n        const auto &geometry = compressed_geometries.GetBucketReference(via_edge_id);\n\n        const auto base_node_id = (traverse_in_reverse) ? to_node : from_node;\n        const auto base_coordinate = extractCoordinateFromNode(query_nodes[base_node_id]);\n\n        const auto final_node = (traverse_in_reverse) ? from_node : to_node;\n        const auto final_coordinate = extractCoordinateFromNode(query_nodes[final_node]);\n\n        if (traverse_in_reverse)\n            return detail::getCoordinateFromCompressedRange(\n                base_coordinate, geometry.rbegin(), geometry.rend(), final_coordinate, query_nodes);\n        else\n            return detail::getCoordinateFromCompressedRange(\n                base_coordinate, geometry.begin(), geometry.end(), final_coordinate, query_nodes);\n    }\n}\n\n// To simplify handling of Left/Right hand turns, we can mirror turns and write an intersection\n// handler only for one side. The mirror function turns a left-hand turn in a equivalent right-hand\n// turn and vice versa.\nOSRM_ATTR_WARN_UNUSED\ninline ConnectedRoad mirror(ConnectedRoad road)\n{\n    const constexpr DirectionModifier::Enum mirrored_modifiers[] = {DirectionModifier::UTurn,\n                                                                    DirectionModifier::SharpLeft,\n                                                                    DirectionModifier::Left,\n                                                                    DirectionModifier::SlightLeft,\n                                                                    DirectionModifier::Straight,\n                                                                    DirectionModifier::SlightRight,\n                                                                    DirectionModifier::Right,\n                                                                    DirectionModifier::SharpRight};\n\n    if (angularDeviation(road.turn.angle, 0) > std::numeric_limits<double>::epsilon())\n    {\n        road.turn.angle = 360 - road.turn.angle;\n        road.turn.instruction.direction_modifier =\n            mirrored_modifiers[road.turn.instruction.direction_modifier];\n    }\n    return road;\n}\n\ninline bool hasRoundaboutType(const TurnInstruction instruction)\n{\n    using namespace extractor::guidance::TurnType;\n    const constexpr TurnType::Enum valid_types[] = {TurnType::EnterRoundabout,\n                                                    TurnType::EnterAndExitRoundabout,\n                                                    TurnType::EnterRotary,\n                                                    TurnType::EnterAndExitRotary,\n                                                    TurnType::EnterRoundaboutIntersection,\n                                                    TurnType::EnterAndExitRoundaboutIntersection,\n                                                    TurnType::EnterRoundaboutAtExit,\n                                                    TurnType::ExitRoundabout,\n                                                    TurnType::EnterRotaryAtExit,\n                                                    TurnType::ExitRotary,\n                                                    TurnType::EnterRoundaboutIntersectionAtExit,\n                                                    TurnType::ExitRoundaboutIntersection,\n                                                    TurnType::StayOnRoundabout};\n\n    const auto *first = valid_types;\n    const auto *last = first + sizeof(valid_types) / sizeof(valid_types[0]);\n\n    return std::find(first, last, instruction.type) != last;\n}\n\n// Public service vehicle lanes and similar can introduce additional lanes into the lane string that\n// are not specifically marked for left/right turns. This function can be used from the profile to\n// trim the lane string appropriately\n//\n// left|throught|\n// in combination with lanes:psv:forward=1\n// will be corrected to left|throught, since the final lane is not drivable.\n// This is in contrast to a situation with lanes:psv:forward=0 (or not set) where left|through|\n// represents left|through|through\nOSRM_ATTR_WARN_UNUSED\ninline std::string\ntrimLaneString(std::string lane_string, std::int32_t count_left, std::int32_t count_right)\n{\n    if (count_left)\n    {\n        bool sane = count_left < static_cast<std::int32_t>(lane_string.size());\n        for (std::int32_t i = 0; i < count_left; ++i)\n            // this is adjusted for our fake pipe. The moment cucumber can handle multiple escaped\n            // pipes, the '&' part can be removed\n            if (lane_string[i] != '|')\n            {\n                sane = false;\n                break;\n            }\n\n        if (sane)\n        {\n            lane_string.erase(lane_string.begin(), lane_string.begin() + count_left);\n        }\n    }\n    if (count_right)\n    {\n        bool sane = count_right < static_cast<std::int32_t>(lane_string.size());\n        for (auto itr = lane_string.rbegin();\n             itr != lane_string.rend() && itr != lane_string.rbegin() + count_right;\n             ++itr)\n        {\n            if (*itr != '|')\n            {\n                sane = false;\n                break;\n            }\n        }\n        if (sane)\n            lane_string.resize(lane_string.size() - count_right);\n    }\n    return lane_string;\n}\n\n// https://github.com/Project-OSRM/osrm-backend/issues/2638\n// It can happen that some lanes are not drivable by car. Here we handle this tagging scheme\n// (vehicle:lanes) to filter out not-allowed roads\n// lanes=3\n// turn:lanes=left|through|through|right\n// vehicle:lanes=yes|yes|no|yes\n// bicycle:lanes=yes|no|designated|yes\nOSRM_ATTR_WARN_UNUSED\ninline std::string applyAccessTokens(std::string lane_string, const std::string &access_tokens)\n{\n    typedef boost::tokenizer<boost::char_separator<char>> tokenizer;\n    boost::char_separator<char> sep(\"|\", \"\", boost::keep_empty_tokens);\n    tokenizer tokens(lane_string, sep);\n    tokenizer access(access_tokens, sep);\n\n    // strings don't match, don't do anything\n    if (std::distance(std::begin(tokens), std::end(tokens)) !=\n        std::distance(std::begin(access), std::end(access)))\n        return lane_string;\n\n    std::string result_string = \"\";\n    const static std::string yes = \"yes\";\n\n    for (auto token_itr = std::begin(tokens), access_itr = std::begin(access);\n         token_itr != std::end(tokens);\n         ++token_itr, ++access_itr)\n    {\n        if (*access_itr == yes)\n        {\n            // we have to add this in front, because the next token could be invalid. Doing this on\n            // non-empty strings makes sure that the token string will be valid in the end\n            if (!result_string.empty())\n                result_string += '|';\n\n            result_string += *token_itr;\n        }\n    }\n    return result_string;\n}\n\n} // namespace guidance\n} // namespace extractor\n} // namespace osrm\n\n#endif // OSRM_GUIDANCE_TOOLKIT_HPP_\n", "meta": {"hexsha": "1a87f116238fcf42e7a2fa12c6d0d21778345cdb", "size": 12102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/extractor/guidance/toolkit.hpp", "max_stars_repo_name": "beemogmbh/osrm-backend", "max_stars_repo_head_hexsha": "547f29384cb05dde1383d7d364fc7d87eb5d0d1b", "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/extractor/guidance/toolkit.hpp", "max_issues_repo_name": "beemogmbh/osrm-backend", "max_issues_repo_head_hexsha": "547f29384cb05dde1383d7d364fc7d87eb5d0d1b", "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/extractor/guidance/toolkit.hpp", "max_forks_repo_name": "beemogmbh/osrm-backend", "max_forks_repo_head_hexsha": "547f29384cb05dde1383d7d364fc7d87eb5d0d1b", "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.3037542662, "max_line_length": 137, "alphanum_fraction": 0.6319616592, "num_tokens": 2365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.26284183737131667, "lm_q1q2_score": 0.15378906622204325}}
{"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#ifndef QCTOOL_INTENSITY_SUMMARY_COMPUTATION_HPP\n#define QCTOOL_INTENSITY_SUMMARY_COMPUTATION_HPP\n\n#include <string>\n#include <memory>\n#include <vector>\n#include <map>\n#include <boost/noncopyable.hpp>\n#include <boost/function.hpp>\n#include <Eigen/Core>\n#include \"genfile/VariantIdentifyingData.hpp\"\n#include \"genfile/VariantEntry.hpp\"\n#include \"genfile/VariantDataReader.hpp\"\n#include \"components/SNPSummaryComponent/SNPSummaryComputation.hpp\"\n\nnamespace snp_summary_component {\n\tstruct IntensitySummaryComputation: public SNPSummaryComputation {\n\t\tIntensitySummaryComputation( double call_threshhold = 0.9 ) ;\n\t\tvoid operator()( VariantIdentifyingData const&, Genotypes const&, Ploidy const&, genfile::VariantDataReader&, ResultCallback ) ;\n\t\tstd::string get_summary( std::string const& prefix = \"\", std::size_t column_width = 20 ) const ;\n\tprivate:\n\t\tdouble const m_call_threshhold ;\n\t\ttypedef Eigen::MatrixXd IntensityMatrix ;\n\t\tIntensityMatrix m_intensities ;\n\t\tIntensityMatrix m_intensities_by_genotype ;\n\t\tIntensityMatrix m_nonmissingness ;\n\t\tIntensityMatrix m_nonmissingness_by_genotype ;\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "3ca7cf456357ce508b3e97c26bf841c9a1d696a6", "size": 1327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/include/components/SNPSummaryComponent/IntensitySummaryComputation.hpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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": "components/SNPSummaryComponent/include/components/SNPSummaryComponent/IntensitySummaryComputation.hpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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": "components/SNPSummaryComponent/include/components/SNPSummaryComponent/IntensitySummaryComputation.hpp", "max_forks_repo_name": "CreRecombinase/qctool", "max_forks_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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.9210526316, "max_line_length": 130, "alphanum_fraction": 0.7829691032, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.1534390252268805}}
{"text": "#include \"parse_opening_hours.hpp\"\n#include \"opening_hours_parsers.hpp\"\n\n#include <boost/phoenix/bind.hpp>\n#include <boost/phoenix/operator.hpp>  // operator,\n\nnamespace osmoh\n{\n  namespace parsing\n  {\n    month_selector_parser::month_selector_parser() : month_selector_parser::base_type(main)\n    {\n      using qi::_1;\n      using qi::_2;\n      using qi::_3;\n      using qi::_a;\n      using qi::_val;\n      using qi::uint_;\n      using qi::ushort_;\n      using qi::lit;\n      using qi::double_;\n      using qi::lexeme;\n      using osmoh::DateOffset;\n      using osmoh::MonthDay;\n      using osmoh::MonthdayRange;\n\n      static const qi::int_parser<unsigned, 10, 4, 4> year = {};\n\n      day_offset = ((lit('+')[_a = 1] | lit('-')[_a = -1]) >>\n                    ushort_ >> charset::no_case[(lit(\"days\") | lit(\"day\"))]) [_val = _a * _1];\n\n      date_offset = ((lit('+')[_a = true] | lit('-')[_a = false])\n                     >> charset::no_case[wdays] >> day_offset)\n      [bind(&DateOffset::SetWDayOffset, _val, _1),\n       bind(&DateOffset::SetOffset, _val, _2),\n       bind(&DateOffset::SetWDayOffsetPositive, _val, _a)]\n      | ((lit('+')[_a = true] | lit('-') [_a = false]) >> charset::no_case[wdays])\n      [bind(&DateOffset::SetWDayOffset, _val, _1),\n       bind(&DateOffset::SetWDayOffsetPositive, _val, _a)]\n      | day_offset [bind(&DateOffset::SetOffset, _val, _1)]\n      ;\n\n      date_left = (year >> charset::no_case[month]) [bind(&MonthDay::SetYear, _val, _1),\n                                                     bind(&MonthDay::SetMonth, _val, _2)]\n\n      | charset::no_case[month]                 [bind(&MonthDay::SetMonth, _val, _1)]\n      ;\n\n      date_right = charset::no_case[month]          [bind(&MonthDay::SetMonth, _val, _1)]\n      ;\n\n      date_from = (date_left >> (daynum >> !(lit(':') >> qi::digit)))\n      [_val = _1, bind(&MonthDay::SetDayNum, _val, _2)]\n      | (year >> charset::no_case[lit(\"easter\")]) [bind(&MonthDay::SetYear, _val, _1),\n                                                   bind(&MonthDay::SetVariableDate, _val,\n                                                        MonthDay::VariableDate::Easter)]\n      | charset::no_case[lit(\"easter\")]           [bind(&MonthDay::SetVariableDate, _val,\n                                                        MonthDay::VariableDate::Easter)]\n      ;\n\n      date_to = date_from                        [_val = _1]\n      | (daynum >> !(lit(':') >> qi::digit)) [bind(&MonthDay::SetDayNum, _val, _1)]\n      ;\n\n      date_from_with_offset = (date_from >> date_offset)\n      [_val = _1, bind(&MonthDay::SetOffset, _val, _2)]\n      | date_from         [_val = _1]\n      ;\n\n      date_to_with_offset = (date_to >> date_offset)\n      [_val = _1, bind(&MonthDay::SetOffset, _val, _2)]\n      | date_to         [_val = _1]\n      ;\n\n      monthday_range = (date_from_with_offset >> dash >> date_to_with_offset)\n      [bind(&MonthdayRange::SetStart, _val, _1),\n       bind(&MonthdayRange::SetEnd, _val, _2)]\n      | (date_from_with_offset >> '+') [bind(&MonthdayRange::SetStart, _val, _1),\n                                        bind(&MonthdayRange::SetPlus, _val, true)]\n      | (date_left >> dash >> date_right >> '/' >> uint_)\n      [bind(&MonthdayRange::SetStart, _val, _1),\n       bind(&MonthdayRange::SetEnd, _val, _2),\n       bind(&MonthdayRange::SetPeriod, _val, _3)]\n      | (date_left >> lit(\"-\") >> date_right) [bind(&MonthdayRange::SetStart, _val, _1),\n                                               bind(&MonthdayRange::SetEnd, _val, _2)]\n      | date_from [bind(&MonthdayRange::SetStart, _val, _1)]\n      | date_left [bind(&MonthdayRange::SetStart, _val, _1)]\n      ;\n\n      main %= (monthday_range % ',');\n\n      BOOST_SPIRIT_DEBUG_NODE(main);\n      BOOST_SPIRIT_DEBUG_NODE(monthday_range);\n      BOOST_SPIRIT_DEBUG_NODE(day_offset);\n      BOOST_SPIRIT_DEBUG_NODE(date_offset);\n      BOOST_SPIRIT_DEBUG_NODE(date_left);\n      BOOST_SPIRIT_DEBUG_NODE(date_right);\n      BOOST_SPIRIT_DEBUG_NODE(date_from);\n      BOOST_SPIRIT_DEBUG_NODE(date_to);\n      BOOST_SPIRIT_DEBUG_NODE(date_from_with_offset);\n      BOOST_SPIRIT_DEBUG_NODE(date_to_with_offset);\n    }\n  }\n\n  bool Parse(std::string const & str, TMonthdayRanges & context)\n  {\n    return osmoh::ParseImpl<parsing::month_selector_parser>(str, context);\n  }\n} // namespace osmoh\n", "meta": {"hexsha": "fc28d3b2bba36856053626a50e84f59c8d618924", "size": 4322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3party/opening_hours/parse_months.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": "3party/opening_hours/parse_months.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": "3party/opening_hours/parse_months.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": 39.2909090909, "max_line_length": 94, "alphanum_fraction": 0.5689495604, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.1533814299473657}}
{"text": "#include \"Q.h\"\n#include \"Model.h\"\n#include \"WGS84EnvelopeFactory.h\"\n#include <boost/date_time/local_time/local_time_io.hpp>\n#include <boost/date_time/posix_time/posix_time_types.hpp>\n#include <boost/date_time/time_facet.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/optional.hpp>\n#include <boost/range/algorithm/sort.hpp>\n#include <boost/range/algorithm/unique.hpp>\n#include <boost/range/algorithm_ext/erase.hpp>\n#include <boost/timer/timer.hpp>\n#include <gis/Box.h>\n#include <gis/CoordinateTransformation.h>\n#include <gis/DEM.h>\n#include <gis/LandCover.h>\n#include <gis/OGR.h>\n#include <gis/SpatialReference.h>\n#include <macgyver/Astronomy.h>\n#include <macgyver/CharsetTools.h>\n#include <macgyver/Exception.h>\n#include <macgyver/Hash.h>\n#include <macgyver/StringConversion.h>\n#include <macgyver/TimeFormatter.h>\n#include <macgyver/TimeZoneFactory.h>\n#include <newbase/NFmiMetMath.h>\n#include <newbase/NFmiMultiQueryInfo.h>\n#include <newbase/NFmiQueryData.h>\n#include <newbase/NFmiQueryDataUtil.h>\n#include <newbase/NFmiTimeList.h>\n#include <spine/ParameterFactory.h>\n#include <cassert>\n#include <ogr_spatialref.h>\n#include <stdexcept>\n\n#ifndef WGS84\n#include <newbase/NFmiGdalArea.h>\n#endif\n\nnamespace ts = SmartMet::Spine::TimeSeries;\n\nnamespace\n{\n// SmartSymbol / WeatherNumber calculation limits\n\nconst float thunder_limit1 = 30;\nconst float thunder_limit2 = 60;\n\nconst float rain_limit1 = 0.025;\nconst float rain_limit2 = 0.04;\nconst float rain_limit3 = 0.4;\nconst float rain_limit4 = 1.5;\nconst float rain_limit5 = 2;\nconst float rain_limit6 = 4;\nconst float rain_limit7 = 7;\n\nconst int cloud_limit1 = 7;\nconst int cloud_limit2 = 20;\nconst int cloud_limit3 = 33;\nconst int cloud_limit4 = 46;\nconst int cloud_limit5 = 59;\nconst int cloud_limit6 = 72;\nconst int cloud_limit7 = 85;\nconst int cloud_limit8 = 93;\n\nconst char *LevelName(FmiLevelType theLevel)\n{\n  try\n  {\n    switch (theLevel)\n    {\n      case kFmiGroundSurface:\n        return \"GroundSurface\";\n      case kFmiPressureLevel:\n        return \"PressureLevel\";\n      case kFmiMeanSeaLevel:\n        return \"MeanSeaLevel\";\n      case kFmiAltitude:\n        return \"Altitude\";\n      case kFmiHeight:\n        return \"Height\";\n      case kFmiHybridLevel:\n        return \"HybridLevel\";\n      case kFmi:\n        return \"?\";\n      case kFmiAnyLevelType:\n        return \"AnyLevelType\";\n      case kFmiRoadClass1:\n        return \"RoadClass1\";\n      case kFmiRoadClass2:\n        return \"RoadClass2\";\n      case kFmiRoadClass3:\n        return \"RoadClass3\";\n      case kFmiSoundingLevel:\n        return \"SoundingLevel\";\n      case kFmiAmdarLevel:\n        return \"AmdarLevel\";\n      case kFmiFlightLevel:\n        return \"FlightLevel\";\n      case kFmiDepth:\n        return \"Depth\";\n      case kFmiNoLevelType:\n        return \"NoLevel\";\n#ifndef UNREACHABLE\n      default:\n        throw Fmi::Exception(BCP, \"Internal error in deducing level names\");\n#endif\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n}  // namespace\n\nnamespace SmartMet\n{\nnamespace Engine\n{\nnamespace Querydata\n{\nvoid check_local_time_pool(const ParameterOptions& options)\n{\n  // LocalTimePool must be created by client plugin, because references to localtimes in the pool \n  // are used in the result set and they must be valid as log as result set is processed\n  if(options.localTimePool == nullptr)\n\tthrow Fmi::Exception::Trace(BCP, \"Querydata::ParameterOptions::localTimePool can not be null!!!\");\n}\n\n// Max interpolation gap\nconst int maxgap = 6 * 60;\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Is the location of water type?\n */\n// ----------------------------------------------------------------------\n\nbool iswater(const Spine::Location &theLocation)\n{\n  try\n  {\n    if (theLocation.dem == 0)\n      return true;\n\n    return Fmi::LandCover::isOpenWater(theLocation.covertype);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief The destructor releases the NFmiFastQueryInfo back into a pool\n */\n// ----------------------------------------------------------------------\n\nQImpl::~QImpl()\n{\n  for (std::size_t i = 0; i < itsInfos.size(); i++)\n    itsModels[i]->release(itsInfos[i]);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Construct from a single model\n */\n// ----------------------------------------------------------------------\n\nQImpl::QImpl(SharedModel theModel)\n{\n  try\n  {\n    itsModels.emplace_back(theModel);\n    itsInfos.push_back(theModel->info());\n    itsInfo = theModel->info();\n\n    itsValidTimes = theModel->validTimes();\n\n    itsHashValue = hash_value(theModel);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Construct from multiple models\n */\n// ----------------------------------------------------------------------\n\nQImpl::QImpl(const std::vector<SharedModel> &theModels)\n    : itsModels(theModels), itsValidTimes(new ValidTimeList)\n{\n  try\n  {\n    if (theModels.empty())\n      throw Fmi::Exception(BCP, \"Cannot initialize any empty view over multiple models\");\n\n    for (auto &model : itsModels)\n      itsInfos.push_back(model->info());\n\n    if (itsInfos.size() > 1)\n      itsInfo = boost::make_shared<NFmiMultiQueryInfo>(itsInfos);\n    else\n      itsInfo = itsInfos[0];\n\n    // Establish hash value\n    itsHashValue = 0;\n    for (const auto &model : itsModels)\n    {\n      Fmi::hash_combine(itsHashValue, Fmi::hash_value(model));\n    }\n\n    // Establish unique valid times\n    std::set<boost::posix_time::ptime> uniquetimes;\n    for (auto &model : itsModels)\n    {\n      const auto &validtimes = model->validTimes();\n      for (const auto &t : *validtimes)\n        uniquetimes.insert(t);\n    }\n    for (const auto &t : uniquetimes)\n      itsValidTimes->push_back(t);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Direct access to the data\n */\n// ----------------------------------------------------------------------\n\nboost::shared_ptr<NFmiFastQueryInfo> QImpl::info()\n{\n  return itsInfo;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return metadata on the querydata\n */\n// ----------------------------------------------------------------------\n\nMetaData QImpl::metaData()\n{\n  try\n  {\n    MetaData meta;\n\n    // TODO(mheiskan): should not access NFmiFastQueryInfo directly\n    NFmiFastQueryInfo &qi = *itsInfo;\n\n    meta.producer = itsModels[0]->producer();\n\n    // Get querydata origintime\n\n    meta.originTime = qi.OriginTime();\n\n    // Get querydata first time\n    if (qi.FirstTime())\n      meta.firstTime = qi.ValidTime();\n    else\n      meta.firstTime = boost::posix_time::not_a_date_time;\n\n    // Get querydata last time\n    if (qi.LastTime())\n      meta.lastTime = qi.ValidTime();\n    else\n      meta.lastTime = boost::posix_time::not_a_date_time;\n\n    // Get querydata timestep\n    if (qi.FirstTime() && qi.NextTime())\n    {\n      qi.FirstTime();\n      auto t1 = qi.ValidTime();\n      qi.NextTime();\n      auto t2 = qi.ValidTime();\n      meta.timeStep = t2.DifferenceInMinutes(t1);\n    }\n    else\n    {\n      meta.timeStep = 0;\n    }\n\n    // Get querydata timesteps size\n    meta.nTimeSteps = qi.SizeTimes();\n\n    // Get the parameter list from querydatainfo\n    std::list<ModelParameter> params;\n    for (qi.ResetParam(); qi.NextParam(false);)\n    {\n      const int paramID = boost::numeric_cast<int>(qi.Param().GetParamIdent());\n      const std::string paramName = Spine::ParameterFactory::instance().name(paramID);\n      const std::string paramDesc = qi.Param().GetParamName().CharPtr();\n      const std::string paramPrec = qi.Param().GetParam()->Precision().CharPtr();\n      // Find the numerical part of the precision string\n      auto dot = paramPrec.find('.');\n      auto fchar = paramPrec.find('f');\n      if ((dot != std::string::npos) && (fchar != std::string::npos))\n      {\n        auto theNumber = std::string(paramPrec.begin() + dot + 1, paramPrec.begin() + fchar);\n        params.emplace_back(paramName, paramDesc, std::strtol(theNumber.c_str(), nullptr, 10));\n      }\n      else\n      {\n        params.emplace_back(paramName, paramDesc, 0);  // 0 is the default\n      }\n    }\n\n    // Get the model level list from querydatainfo\n    std::list<ModelLevel> levels;\n    qi.ResetLevel();\n    while (qi.NextLevel())\n    {\n      const NFmiLevel &level = *qi.Level();\n\n      const auto *type = ::LevelName(level.LevelType());\n      const auto *name = level.GetName().CharPtr();\n      auto value = level.LevelValue();\n      levels.emplace_back(type, name, value);\n    }\n\n    meta.levels = levels;\n    meta.parameters = params;\n\n    // Get projection string\n    if (qi.Area() == nullptr)\n    {\n      meta.WKT = \"nan\";\n      return meta;\n    }\n\n    meta.WKT = qi.Area()->WKT();\n\n    // Get querydata area info\n\n    const NFmiArea *area = qi.Area();\n    const NFmiGrid *grid = qi.Grid();\n\n    meta.ullon = area->TopLeftLatLon().X();\n    meta.ullat = area->TopLeftLatLon().Y();\n    meta.urlon = area->TopRightLatLon().X();\n    meta.urlat = area->TopRightLatLon().Y();\n    meta.bllon = area->BottomLeftLatLon().X();\n    meta.bllat = area->BottomLeftLatLon().Y();\n    meta.brlon = area->BottomRightLatLon().X();\n    meta.brlat = area->BottomRightLatLon().Y();\n    meta.clon = area->CenterLatLon().X();\n    meta.clat = area->CenterLatLon().Y();\n\n    // Get querydata grid info\n\n    meta.xNumber = boost::numeric_cast<unsigned int>(grid->XNumber());\n    meta.yNumber = boost::numeric_cast<unsigned int>(grid->YNumber());\n\n    meta.xResolution = area->WorldXYWidth() / grid->XNumber() / 1000.0;\n    meta.yResolution = area->WorldXYHeight() / grid->YNumber() / 1000.0;\n\n    meta.areaWidth = area->WorldXYWidth() / 1000.0;\n    meta.areaHeight = area->WorldXYHeight() / 1000.0;\n\n    meta.aspectRatio = area->WorldXYAspectRatio();\n\n    meta.wgs84Envelope = *(WGS84EnvelopeFactory::Get(itsModels[0]->info()));\n\n    return meta;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return origin time of the model\n */\n// ----------------------------------------------------------------------\n\nconst NFmiMetTime &QImpl::originTime() const\n{\n  try\n  {\n    return itsInfo->OriginTime();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return modification time of the model\n */\n// ----------------------------------------------------------------------\n\nboost::posix_time::ptime QImpl::modificationTime() const\n{\n  try\n  {\n    auto t = itsModels[0]->modificationTime();\n\n    for (std::size_t i = 1; i < itsModels.size(); i++)\n      t = std::max(t, itsModels[i]->modificationTime());\n\n    return t;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return estimated expiration time of the model\n */\n// ----------------------------------------------------------------------\n\nboost::posix_time::ptime QImpl::expirationTime() const\n{\n  try\n  {\n    auto t = itsModels[0]->expirationTime();\n\n    for (std::size_t i = 1; i < itsModels.size(); i++)\n      t = std::max(t, itsModels[i]->expirationTime());\n\n    return t;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return valid times of the model\n */\n// ----------------------------------------------------------------------\n\nboost::shared_ptr<ValidTimeList> QImpl::validTimes() const\n{\n  return itsValidTimes;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the level type of the model\n */\n// ----------------------------------------------------------------------\n\nconst std::string &QImpl::levelName() const\n{\n  try\n  {\n    return itsModels[0]->levelName();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the level type of the model\n */\n// ----------------------------------------------------------------------\n\nFmiLevelType QImpl::levelType() const\n{\n  try\n  {\n    return itsInfo->LevelType();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return true if the data represents a climatology\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::isClimatology() const\n{\n  try\n  {\n    return itsModels[0]->isClimatology();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return true if the data covers the entire grid\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::isFullGrid() const\n{\n  try\n  {\n    return itsModels[0]->isFullGrid();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return true if the wind U/V components are relative to the grid\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::isRelativeUV() const\n{\n  try\n  {\n    return itsModels[0]->isRelativeUV();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the nearest grid point with valid data\n */\n// ----------------------------------------------------------------------\n\nNFmiPoint QImpl::validPoint(const NFmiPoint &theLatLon, double theMaxDist) const\n{\n  try\n  {\n    return itsModels[0]->validPoint(theLatLon, theMaxDist);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Reset the time iterator\n */\n// ----------------------------------------------------------------------\n\nvoid QImpl::resetTime()\n{\n  try\n  {\n    itsInfo->ResetTime();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the first time\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::firstTime()\n{\n  try\n  {\n    return itsInfo->FirstTime();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the last time\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::lastTime()\n{\n  try\n  {\n    return itsInfo->LastTime();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Advance the time iterator\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::nextTime()\n{\n  try\n  {\n    return itsInfo->NextTime();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Previous time position\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::previousTime()\n{\n  try\n  {\n    return itsInfo->PreviousTime();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return true if the time iterator is valid\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::isTimeUsable() const\n{\n  try\n  {\n    return itsInfo->IsTimeUsable();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the valid time\n */\n// ----------------------------------------------------------------------\n\nconst NFmiMetTime &QImpl::validTime() const\n{\n  try\n  {\n    return itsInfo->ValidTime();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the valid time\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::time(const NFmiMetTime &theTime)\n{\n  try\n  {\n    return itsInfo->Time(theTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*\n *! \\brief Set the given parameter\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::param(FmiParameterName theParam)\n{\n  try\n  {\n    return itsInfo->Param(theParam);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Reset the parameter iterator\n */\n// ----------------------------------------------------------------------\n\nvoid QImpl::resetParam()\n{\n  try\n  {\n    itsInfo->ResetParam();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Advance the parameter iterator\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::nextParam(bool ignoreSubParams)\n{\n  try\n  {\n    return itsInfo->NextParam(ignoreSubParams);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return true if the data is gridded\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::isArea() const\n{\n  try\n  {\n    return (itsInfo->Area() != nullptr);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Reset the location iterator\n */\n// ----------------------------------------------------------------------\n\nvoid QImpl::resetLocation()\n{\n  itsInfo->ResetLocation();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the first location\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::firstLocation()\n{\n  return itsInfo->FirstLocation();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Advance the location iterator\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::nextLocation()\n{\n  return itsInfo->NextLocation();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the current WorldXY coordinate\n */\n// ----------------------------------------------------------------------\nNFmiPoint QImpl::worldXY() const\n{\n  return itsInfo->WorldXY();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the current LatLon coordinate\n */\n// ----------------------------------------------------------------------\n\nNFmiPoint QImpl::latLon() const\n{\n  return itsInfo->LatLon();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the spatial reference\n */\n// ----------------------------------------------------------------------\n\nconst Fmi::SpatialReference &QImpl::SpatialReference() const\n{\n  return itsInfo->SpatialReference();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return data coordinates\n */\n// ----------------------------------------------------------------------\n\nFmi::CoordinateMatrix QImpl::CoordinateMatrix() const\n{\n  return itsInfo->CoordinateMatrix(false);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return data coordinates with possible wraparound column for global data\n */\n// ----------------------------------------------------------------------\n\nFmi::CoordinateMatrix QImpl::FullCoordinateMatrix() const\n{\n  return itsInfo->CoordinateMatrix(true);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return true if the data is gridded\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::isGrid() const\n{\n  try\n  {\n    return (itsInfo->Grid() != nullptr);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the area\n */\n// ----------------------------------------------------------------------\n\nconst NFmiArea &QImpl::area() const\n{\n  try\n  {\n    if (itsInfo->Area() == nullptr)\n      throw Fmi::Exception(BCP, \"Attempt to access unset area in querydata\");\n    return *itsInfo->Area();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the grid\n */\n// ----------------------------------------------------------------------\n\nconst NFmiGrid &QImpl::grid() const\n{\n  try\n  {\n    if (itsInfo->Grid() == nullptr)\n      throw Fmi::Exception(BCP, \"Attempt to access unset grid in querydata\");\n    return *itsInfo->Grid();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the param\n */\n// ----------------------------------------------------------------------\n\nconst NFmiDataIdent &QImpl::param() const\n{\n  try\n  {\n    return itsInfo->Param();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the level\n */\n// ----------------------------------------------------------------------\n\nconst NFmiLevel &QImpl::level() const\n{\n  try\n  {\n    return *itsInfo->Level();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return true if the given point is in the data\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::isInside(double theLon, double theLat, double theMaxDist)\n{\n  try\n  {\n    return itsInfo->IsInside(NFmiPoint(theLon, theLat), 1000 * theMaxDist);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return current parameter\n */\n// ----------------------------------------------------------------------\n\nFmiParameterName QImpl::parameterName() const\n{\n  try\n  {\n    return FmiParameterName(itsInfo->Param().GetParamIdent());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Interpolate the value\n */\n// ----------------------------------------------------------------------\n\nfloat QImpl::interpolate(const NFmiPoint &theLatLon,\n                         const NFmiMetTime &theTime,\n                         int theMaxMinuteGap)\n{\n  try\n  {\n    return itsInfo->InterpolatedValue(theLatLon, theTime, theMaxMinuteGap);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nfloat QImpl::interpolateAtPressure(const NFmiPoint &theLatLon,\n                                   const NFmiMetTime &theTime,\n                                   float thePressure,\n                                   int theMaxMinuteGap)\n{\n  try\n  {\n    return itsInfo->PressureLevelValue(thePressure, theLatLon, theTime, theMaxMinuteGap);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nfloat QImpl::interpolateAtHeight(const NFmiPoint &theLatLon,\n                                 const NFmiMetTime &theTime,\n                                 float theHeight,\n                                 int theMaxMinuteGap)\n{\n  try\n  {\n    return itsInfo->HeightValue(theHeight, theLatLon, theTime, theMaxMinuteGap);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Reset the level iterator\n */\n// ----------------------------------------------------------------------\n\nvoid QImpl::resetLevel()\n{\n  try\n  {\n    itsInfo->ResetLevel();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the first level\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::firstLevel()\n{\n  try\n  {\n    return itsInfo->FirstLevel();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * \\brief Advance the level iterator\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::nextLevel()\n{\n  try\n  {\n    return itsInfo->NextLevel();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the level value\n */\n// ----------------------------------------------------------------------\n\nfloat QImpl::levelValue() const\n{\n  try\n  {\n    return itsInfo->Level()->LevelValue();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the coordinates for the given location index\n */\n// ----------------------------------------------------------------------\n\nNFmiPoint QImpl::latLon(long theIndex) const\n{\n  try\n  {\n    return itsInfo->LatLon(theIndex);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the version number\n */\n// ----------------------------------------------------------------------\n\ndouble QImpl::infoVersion() const\n{\n  try\n  {\n    return itsInfo->InfoVersion();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the parameter index\n */\n// ----------------------------------------------------------------------\n\nunsigned long QImpl::paramIndex() const\n{\n  try\n  {\n    return itsInfo->ParamIndex();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the parameter index\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::paramIndex(unsigned long theIndex)\n{\n  try\n  {\n    return itsInfo->ParamIndex(theIndex);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the level index\n */\n// ----------------------------------------------------------------------\n\nunsigned long QImpl::levelIndex() const\n{\n  try\n  {\n    return itsInfo->LevelIndex();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the level index\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::levelIndex(unsigned long theIndex)\n{\n  try\n  {\n    return itsInfo->LevelIndex(theIndex);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the time index\n */\n// ----------------------------------------------------------------------\n\nunsigned long QImpl::timeIndex() const\n{\n  try\n  {\n    return itsInfo->TimeIndex();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the time index\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::timeIndex(unsigned long theIndex)\n{\n  try\n  {\n    return itsInfo->TimeIndex(theIndex);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the location index\n */\n// ----------------------------------------------------------------------\n\nunsigned long QImpl::locationIndex() const\n{\n  try\n  {\n    return itsInfo->LocationIndex();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Set the location index\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::locationIndex(unsigned long theIndex)\n{\n  try\n  {\n    return itsInfo->LocationIndex(theIndex);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * \\brief Prepare cache values for speeding up time interpolation\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::calcTimeCache(NFmiQueryInfo &theTargetInfo, std::vector<NFmiTimeCache> &theTimeCache)\n{\n  try\n  {\n    return itsInfo->CalcTimeCache(theTargetInfo, theTimeCache);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Prepare cache values for speeding up time interpolation\n */\n// ----------------------------------------------------------------------\n\nNFmiTimeCache QImpl::calcTimeCache(const NFmiMetTime &theTime)\n{\n  try\n  {\n    return itsInfo->CalcTimeCache(theTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Perform cached interpolation\n */\n// ----------------------------------------------------------------------\n\nfloat QImpl::cachedInterpolation(const NFmiTimeCache &theTimeCache)\n{\n  try\n  {\n    return itsInfo->CachedInterpolation(theTimeCache);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Perform cached interpolation\n */\n// ----------------------------------------------------------------------\n\nfloat QImpl::cachedInterpolation(const NFmiLocationCache &theLocationCache)\n{\n  try\n  {\n    return itsInfo->CachedInterpolation(theLocationCache);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Perform cached interpolation\n */\n// ----------------------------------------------------------------------\n\nfloat QImpl::cachedInterpolation(const NFmiLocationCache &theLocationCache,\n                                 const NFmiTimeCache &theTimeCache)\n{\n  try\n  {\n    return itsInfo->CachedInterpolation(theLocationCache, theTimeCache);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Perform landscaped cached interpolation\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::landscapeCachedInterpolation(\n    const NFmiDataMatrix<NFmiLocationCache> &theLocationCache,\n    const NFmiTimeCache &theTimeCache,\n    const NFmiDataMatrix<float> &theDEMValues,\n    const NFmiDataMatrix<bool> &theWaterFlags)\n{\n  try\n  {\n    return itsInfo->LandscapeCachedInterpolation(\n        theLocationCache, theTimeCache, theDEMValues, theWaterFlags);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Perform fast interpolation with cached location information\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::calcLatlonCachePoints(NFmiQueryInfo &theTargetInfo,\n                                  NFmiDataMatrix<NFmiLocationCache> &theLocationCache)\n{\n  try\n  {\n    return itsInfo->CalcLatlonCachePoints(theTargetInfo, theLocationCache);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Matrix calculation of derived values\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::calculatedValues(const Spine::Parameter &theParam,\n                                              const boost::posix_time::ptime &theInterpolatedTime)\n{\n  try\n  {\n    const auto *grid = itsInfo->Grid();\n    if (grid == nullptr)\n      throw Fmi::Exception(BCP, \"Cannot extract grid of values from point data\");\n    const auto nx = grid->XNumber();\n    const auto ny = grid->YNumber();\n\n    NFmiDataMatrix<float> ret(nx, ny, kFloatMissing);\n\n    // Note: Landscaping has no effect at grid points\n\n    switch (theParam.number())\n    {\n      case kFmiWindChill:\n      {\n        if (param(kFmiWindSpeedMS) && param(kFmiTemperature))\n        {\n          auto t2m = values(theInterpolatedTime);\n          param(kFmiWindSpeedMS);\n          auto wspd = values(theInterpolatedTime);\n          for (std::size_t j = 0; j < t2m.NY(); ++j)\n            for (std::size_t i = 0; i < t2m.NX(); ++i)\n              ret[i][j] = FmiWindChill(wspd[i][j], t2m[i][j]);\n        }\n        break;\n      }\n      case kFmiSummerSimmerIndex:\n      {\n        if (param(kFmiHumidity) && param(kFmiTemperature))\n        {\n          auto t2m = values(theInterpolatedTime);\n          param(kFmiHumidity);\n          auto rh = values(theInterpolatedTime);\n          for (std::size_t j = 0; j < t2m.NY(); ++j)\n            for (std::size_t i = 0; i < t2m.NX(); ++i)\n              ret[i][j] = FmiSummerSimmerIndex(rh[i][j], t2m[i][j]);\n        }\n        break;\n      }\n      case kFmiFeelsLike:\n      {\n        if (param(kFmiHumidity) && param(kFmiWindSpeedMS) && param(kFmiTemperature))\n        {\n          auto t2m = values(theInterpolatedTime);\n          param(kFmiHumidity);\n          auto rh = values(theInterpolatedTime);\n          param(kFmiWindSpeedMS);\n          auto wpsd = values(theInterpolatedTime);\n\n          bool has_radiation = param(kFmiRadiationGlobal);\n          if (has_radiation)\n            ret = values(theInterpolatedTime);  // Using ret as temporary storage for radiation\n          for (std::size_t j = 0; j < t2m.NY(); ++j)\n            for (std::size_t i = 0; i < t2m.NX(); ++i)\n              if (has_radiation)\n                ret[i][j] = FmiFeelsLikeTemperature(wpsd[i][j], rh[i][j], t2m[i][j], ret[i][j]);\n        }\n        break;\n      }\n      case kFmiApparentTemperature:\n      {\n        if (param(kFmiHumidity) && param(kFmiWindSpeedMS) && param(kFmiTemperature))\n        {\n          auto t2m = values(theInterpolatedTime);\n          param(kFmiHumidity);\n          auto rh = values(theInterpolatedTime);\n          param(kFmiWindSpeedMS);\n          auto wpsd = values(theInterpolatedTime);\n          for (std::size_t j = 0; j < t2m.NY(); ++j)\n            for (std::size_t i = 0; i < t2m.NX(); ++i)\n              ret[i][j] = FmiApparentTemperature(wpsd[i][j], rh[i][j], t2m[i][j]);\n        }\n        break;\n      }\n      default:\n      {\n        throw Fmi::Exception(BCP, \"Unable to fetch parameter as a value matrix\")\n            .addParameter(\"parameter\", theParam.name());\n      }\n    }\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Failed to extract calculated values from querydata\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract values at grid points\n * \\param theDemValues DEM values for landscaping (an empty matrix by default)\n * \\param theWaterFlags Water flags for landscaping (an empty matrix by default)\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::values(const NFmiDataMatrix<float> &theDEMValues,\n                                    const NFmiDataMatrix<bool> &theWaterFlags)\n{\n  try\n  {\n    if ((theDEMValues.NX() > 0) && (theWaterFlags.NX() > 0))\n      return itsInfo->LandscapeValues(theDEMValues, theWaterFlags);\n\n    return itsInfo->Values();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract time interpolated values at grid points\n * \\param theInterpolatedTime The desired time\n * \\param theDemValues DEM values for landscaping (an empty matrix by default)\n * \\param theWaterFlags Water flags for landscaping (an empty matrix by default)\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::values(const NFmiMetTime &theInterpolatedTime,\n                                    const NFmiDataMatrix<float> &theDEMValues,\n                                    const NFmiDataMatrix<bool> &theWaterFlags)\n{\n  try\n  {\n    if ((theDEMValues.NX() > 0) && (theWaterFlags.NX() > 0))\n      return itsInfo->LandscapeValues(theInterpolatedTime, theDEMValues, theWaterFlags);\n\n    return itsInfo->Values(theInterpolatedTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract time interpolated values at grid points\n * \\param theInterpolatedTime The desired time\n * \\param theDemValues DEM values for landscaping (an empty matrix by default)\n * \\param theWaterFlags Water flags for landscaping (an empty matrix by default)\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::values(const Spine::Parameter &theParam,\n                                    const boost::posix_time::ptime &theInterpolatedTime,\n                                    const NFmiDataMatrix<float> &theDEMValues,\n                                    const NFmiDataMatrix<bool> &theWaterFlags)\n{\n  try\n  {\n    switch (theParam.type())\n    {\n      case Spine::Parameter::Type::Data:\n      case Spine::Parameter::Type::Landscaped:\n      {\n        if (!param(theParam.number()))\n          throw Fmi::Exception(BCP,\n                               \"Parameter \" + theParam.name() + \" is not available in the data\");\n        return values(theInterpolatedTime, theDEMValues, theWaterFlags);\n      }\n      case Spine::Parameter::Type::DataDerived:\n      case Spine::Parameter::Type::DataIndependent:\n      default:\n      {\n        return calculatedValues(theParam, theInterpolatedTime);\n      }\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Interpolate values\n */\n// ----------------------------------------------------------------------\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Interpolate values\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::values(const Fmi::CoordinateMatrix &theLatlonMatrix,\n                                    const NFmiMetTime &theTime,\n                                    float P,\n                                    float H)\n{\n  try\n  {\n    return itsInfo->Values(theLatlonMatrix, theTime, P, H);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract subgrid values\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::croppedValues(\n    int x1,\n    int y1,\n    int x2,\n    int y2,\n    const NFmiDataMatrix<float> &theDEMValues,  // DEM values for landscaping\n                                                // (an empty matrix by\n                                                // default)\n    const NFmiDataMatrix<bool> &theWaterFlags   // Water flags for landscaping\n                                                // (an empty matrix by default)\n) const\n{\n  try\n  {\n    if ((theDEMValues.NX() > 0) && (theWaterFlags.NX() > 0))\n      return itsInfo->LandscapeCroppedValues(x1, y1, x2, y2, theDEMValues, theWaterFlags);\n\n    return itsInfo->CroppedValues(x1, y1, x2, y2);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract values for pressure level\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::pressureValues(const NFmiMetTime &theInterpolatedTime,\n                                            float wantedPressureLevel)\n{\n  try\n  {\n    return itsInfo->PressureValues(theInterpolatedTime, wantedPressureLevel);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract values for pressure level\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::pressureValues(const NFmiGrid &theWantedGrid,\n                                            const NFmiMetTime &theInterpolatedTime,\n                                            float wantedPressureLevel)\n{\n  try\n  {\n    return itsInfo->PressureValues(theWantedGrid, theInterpolatedTime, wantedPressureLevel);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nNFmiDataMatrix<float> QImpl::pressureValues(const NFmiGrid &theWantedGrid,\n                                            const NFmiMetTime &theInterpolatedTime,\n                                            float wantedPressureLevel,\n                                            bool relative_uv)\n{\n  try\n  {\n    return itsInfo->PressureValues(\n        theWantedGrid, theInterpolatedTime, wantedPressureLevel, relative_uv);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract values for grid\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::gridValues(const NFmiGrid &theWantedGrid,\n                                        const NFmiMetTime &theInterpolatedTime,\n                                        bool relative_uv)\n{\n  try\n  {\n    return itsInfo->GridValues(theWantedGrid, theInterpolatedTime, relative_uv);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract values for height level\n */\n// ----------------------------------------------------------------------\n\nNFmiDataMatrix<float> QImpl::heightValues(const NFmiGrid &theWantedGrid,\n                                          const NFmiMetTime &theInterpolatedTime,\n                                          float wantedHeightLevel,\n                                          bool relative_uv)\n{\n  try\n  {\n    return itsInfo->HeightValues(\n        theWantedGrid, theInterpolatedTime, wantedHeightLevel, relative_uv);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n//----------------------------------------------------------------------\n/*!\n * \\brief Return status on whether a sub parameter is active\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::isSubParamUsed() const\n{\n  try\n  {\n    return itsInfo->IsSubParamUsed();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n//----------------------------------------------------------------------\n/*!\n * \\brief Restore status on whether a sub parameter is active\n */\n// ----------------------------------------------------------------------\n\nvoid QImpl::setIsSubParamUsed(bool theState)\n{\n  try\n  {\n    itsInfo->SetIsSubParamUsed(theState);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Time formatter\n */\n// ----------------------------------------------------------------------\n\nstd::string format_date(const boost::local_time::local_date_time &ldt,\n                        const std::locale &llocale,\n                        const std::string &fmt)\n{\n  try\n  {\n    using tfacet = boost::date_time::time_facet<boost::local_time::local_date_time, char>;\n    std::ostringstream os;\n    os.imbue(std::locale(llocale, new tfacet(fmt.c_str())));\n    os << ldt;\n    return Fmi::latin1_to_utf8(os.str());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief WindUMS with true north orientation\n */\n// ----------------------------------------------------------------------\n\nts::Value WindUMS(QImpl &q,\n                  const Spine::Location &loc,\n                  const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    Fmi::CoordinateTransformation transformation(\"WGS84\", q.SpatialReference());\n    auto opt_angle = Fmi::OGR::gridNorth(transformation, loc.longitude, loc.latitude);\n\n    if (!opt_angle)\n      return Spine::TimeSeries::None();\n\n    auto angle = *opt_angle * boost::math::double_constants::degree;\n\n    NFmiPoint latlon(loc.longitude, loc.latitude);\n    // auto angle = q.area().TrueNorthAzimuth(latlon).ToRad();\n\n    if (!q.param(kFmiWindUMS))\n      return Spine::TimeSeries::None();\n\n    auto u = q.interpolate(latlon, ldt, maxgap);\n\n    if (angle == 0)\n      return u;\n\n    if (!q.param(kFmiWindVMS))\n      return Spine::TimeSeries::None();\n\n    auto v = q.interpolate(latlon, ldt, maxgap);\n\n    if (u == kFloatMissing || v == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    // Unrotate U by the given angle\n\n    return u * cos(-angle) + v * sin(-angle);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief WindVMS with true north orientation\n */\n// ----------------------------------------------------------------------\n\nts::Value WindVMS(QImpl &q,\n                  const Spine::Location &loc,\n                  const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    Fmi::CoordinateTransformation transformation(\"WGS84\", q.SpatialReference());\n    auto opt_angle = Fmi::OGR::gridNorth(transformation, loc.longitude, loc.latitude);\n\n    if (!opt_angle)\n      return Spine::TimeSeries::None();\n\n    auto angle = *opt_angle * boost::math::double_constants::degree;\n\n    NFmiPoint latlon(loc.longitude, loc.latitude);\n    // auto angle = q.area().TrueNorthAzimuth(latlon).ToRad();\n\n    if (!q.param(kFmiWindVMS))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    auto v = q.interpolate(latlon, t, maxgap);\n\n    if (angle == 0)\n      return v;\n\n    if (!q.param(kFmiWindUMS))\n      return Spine::TimeSeries::None();\n\n    auto u = q.interpolate(latlon, t, maxgap);\n\n    if (u == kFloatMissing || v == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    // Unrotate V by the given angle\n\n    return v * cos(-angle) - u * sin(-angle);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief WindCompass 8th\n */\n// ----------------------------------------------------------------------\n\nts::Value WindCompass8(QImpl &q,\n                       const Spine::Location &loc,\n                       const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    std::vector<std::string> names{\"N\", \"NE\", \"E\", \"SE\", \"S\", \"SW\", \"W\", \"NW\"};\n\n    if (!q.param(kFmiWindDirection))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n    float value = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (value == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    int i = static_cast<int>((value + 22.5) / 45) % 8;\n    return names.at(i);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief WindCompass 16th\n */\n// ----------------------------------------------------------------------\n\nts::Value WindCompass16(QImpl &q,\n                        const Spine::Location &loc,\n                        const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    std::vector<std::string> names{\"N\",\n                                   \"NNE\",\n                                   \"NE\",\n                                   \"ENE\",\n                                   \"E\",\n                                   \"ESE\",\n                                   \"SE\",\n                                   \"SSE\",\n                                   \"S\",\n                                   \"SSW\",\n                                   \"SW\",\n                                   \"WSW\",\n                                   \"W\",\n                                   \"WNW\",\n                                   \"NW\",\n                                   \"NNW\"};\n\n    if (!q.param(kFmiWindDirection))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n    float value = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (value == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    int i = static_cast<int>((value + 11.25) / 22.5) % 16;\n    return names.at(i);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief WindCompass 32th\n */\n// ----------------------------------------------------------------------\n\nts::Value WindCompass32(QImpl &q,\n                        const Spine::Location &loc,\n                        const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    std::vector<std::string> names{\"N\", \"NbE\", \"NNE\", \"NEbN\", \"NE\", \"NEbE\", \"ENE\", \"EbN\",\n                                   \"E\", \"EbS\", \"ESE\", \"SEbE\", \"SE\", \"SEbS\", \"SSE\", \"SbE\",\n                                   \"S\", \"SbW\", \"SSW\", \"SWbS\", \"SW\", \"SWbW\", \"WSW\", \"WbS\",\n                                   \"W\", \"WbN\", \"WNW\", \"NWbW\", \"NW\", \"NWbN\", \"NNW\", \"NbW\"};\n\n    if (!q.param(kFmiWindDirection))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n    float value = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (value == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    int i = static_cast<int>((value + 5.625) / 11.25) % 32;\n    return names.at(i);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Cloudiness8th\n */\n// ----------------------------------------------------------------------\n\nts::Value Cloudiness8th(QImpl &q,\n                        const Spine::Location &loc,\n                        const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    if (!q.param(kFmiTotalCloudCover))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n    float value = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (value == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    // This is the synoptic interpretation of 8s\n\n    int n = boost::numeric_cast<int>(ceil(value / 12.5));\n    return n;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief WindChill\n */\n// ----------------------------------------------------------------------\n\nts::Value WindChill(QImpl &q,\n                    const Spine::Location &loc,\n                    const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    if (!q.param(kFmiWindSpeedMS))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n    float wspd = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (!q.param(kFmiTemperature))\n      return Spine::TimeSeries::None();\n\n    float t2m = q.info()->LandscapeInterpolatedValue(\n        loc.dem, iswater(loc), NFmiPoint(loc.longitude, loc.latitude), t);\n\n    if (wspd == kFloatMissing || t2m == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    float chill = FmiWindChill(wspd, t2m);\n    return chill;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief SummerSimmerIndex\n */\n// ----------------------------------------------------------------------\n\nts::Value SummerSimmerIndex(QImpl &q,\n                            const Spine::Location &loc,\n                            const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    if (!q.param(kFmiHumidity))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    float rh = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (!q.param(kFmiTemperature))\n      return Spine::TimeSeries::None();\n\n    float t2m = q.info()->LandscapeInterpolatedValue(\n        loc.dem, iswater(loc), NFmiPoint(loc.longitude, loc.latitude), t);\n\n    if (rh == kFloatMissing || t2m == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    float ssi = FmiSummerSimmerIndex(rh, t2m);\n    return ssi;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief FeelsLike temperature\n */\n// ----------------------------------------------------------------------\n\nts::Value FeelsLike(QImpl &q,\n                    const Spine::Location &loc,\n                    const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    if (!q.param(kFmiHumidity))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    float rh = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (!q.param(kFmiWindSpeedMS))\n      return Spine::TimeSeries::None();\n\n    float wspd = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (!q.param(kFmiTemperature))\n      return Spine::TimeSeries::None();\n\n    float t2m = q.info()->LandscapeInterpolatedValue(\n        loc.dem, iswater(loc), NFmiPoint(loc.longitude, loc.latitude), t);\n\n    if (rh == kFloatMissing || t2m == kFloatMissing || wspd == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    // We permit radiation to be missing\n    float rad = kFloatMissing;\n    if (q.param(kFmiRadiationGlobal))\n      rad = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    float ret = FmiFeelsLikeTemperature(wspd, rh, t2m, rad);\n\n    if (ret == kFloatMissing)\n      return Spine::TimeSeries::None();\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Apparent Temperature\n */\n// ----------------------------------------------------------------------\n\nts::Value ApparentTemperature(QImpl &q,\n                              const Spine::Location &loc,\n                              const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    if (!q.param(kFmiHumidity))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    float rh = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (!q.param(kFmiWindSpeedMS))\n      return Spine::TimeSeries::None();\n\n    float wspd = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (!q.param(kFmiTemperature))\n      return Spine::TimeSeries::None();\n\n    float t2m = q.info()->LandscapeInterpolatedValue(\n        loc.dem, iswater(loc), NFmiPoint(loc.longitude, loc.latitude), t);\n\n    if (rh == kFloatMissing || t2m == kFloatMissing || wspd == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    float ret = FmiApparentTemperature(wspd, rh, t2m);\n\n    if (ret == kFloatMissing)\n      return Spine::TimeSeries::None();\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Lower limit of water to snow conversion\n */\n// ----------------------------------------------------------------------\nts::Value Snow1hLower(QImpl &q,\n                      const Spine::Location &loc,\n                      const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    if (!q.param(kFmiPrecipitation1h))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    float prec1h = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    // FmiSnowLowerLimit fails if input is 'nan', check here.\n\n    if (prec1h == kFloatMissing)\n    {\n      return Spine::TimeSeries::None();\n    }\n    float ret = FmiSnowLowerLimit(prec1h);\n    if (ret == kFloatMissing)\n      return Spine::TimeSeries::None();\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Upper limit of water to snow conversion\n */\n// ----------------------------------------------------------------------\nts::Value Snow1hUpper(QImpl &q,\n                      const Spine::Location &loc,\n                      const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    if (!q.param(kFmiPrecipitation1h))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    float prec1h = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    // FmiSnowUpperLimit fails if input is 'nan', check here.\n    if (prec1h == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    float ret = FmiSnowUpperLimit(prec1h);\n    if (ret == kFloatMissing)\n      return Spine::TimeSeries::None();\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Snow estimate if no Snow1h parameter present\n */\n// ----------------------------------------------------------------------\nts::Value Snow1h(QImpl &q,\n                 const Spine::Location &loc,\n                 const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    // Use the actual Snow1h if it is present\n    if (q.param(kFmiSnow1h))\n      return q.param(kFmiSnow1h);\n\n    if (!q.param(kFmiTemperature))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    float t2m = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (!q.param(kFmiWindSpeedMS))\n      return Spine::TimeSeries::None();\n\n    float wspd = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (!q.param(kFmiPrecipitation1h))\n      return Spine::TimeSeries::None();\n\n    float prec1h = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (t2m == kFloatMissing || wspd == kFloatMissing || prec1h == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    float snow1h = prec1h * FmiSnowWaterRatio(t2m, wspd);  // Can this be kFLoatMissing???\n    return snow1h;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief WeatherSymbol = WeatherSymbol3 + 100*Dark\n */\n// ----------------------------------------------------------------------\n\nts::Value WeatherSymbol(QImpl &q,\n                        const Spine::Location &loc,\n                        const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    if (!q.param(kFmiWeatherSymbol3))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    float symbol = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n    if (symbol == kFloatMissing)\n      return kFloatMissing;\n\n    Fmi::Astronomy::solar_position_t sp =\n        Fmi::Astronomy::solar_position(t, loc.longitude, loc.latitude);\n    if (sp.dark())\n      return 100 + symbol;\n    return symbol;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Weather text\n */\n// ----------------------------------------------------------------------\n\nts::Value WeatherText(QImpl &q,\n                      const Spine::Location &loc,\n                      const boost::local_time::local_date_time &ldt,\n                      const std::string &lang,\n                      const ParameterTranslations &translations)\n{\n  try\n  {\n    if (!q.param(kFmiWeatherSymbol3))\n      return Spine::TimeSeries::None();\n\n    NFmiMetTime t(ldt);\n\n    float w = q.interpolate(NFmiPoint(loc.longitude, loc.latitude), t, maxgap);\n\n    if (w == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    auto ret = translations.getTranslation(\"WeatherText\", static_cast<int>(w), lang);\n    if (!ret)\n      return Spine::TimeSeries::None();\n\n    return *ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, u8\"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Calculate the smart weather symbol if possible\n */\n// ----------------------------------------------------------------------\n\nboost::optional<int> calc_smart_symbol(QImpl &q,\n                                       const NFmiPoint &latlon,\n                                       const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    // Cloudiness is almost always needed\n\n    if (!q.param(kFmiTotalCloudCover))\n      return {};\n\n    NFmiMetTime t(ldt);\n\n    const auto n = q.interpolate(latlon, t, maxgap);\n\n    if (n == kFloatMissing)\n      return {};\n\n    // The first parameter we need always is POT. We allow it to be missing though.\n\n    if (q.param(kFmiProbabilityThunderstorm))\n    {\n      const auto thunder = q.interpolate(latlon, t, maxgap);\n\n      if (thunder >= thunder_limit1 && thunder != kFloatMissing)\n      {\n        int nclass = (n < cloud_limit6 ? 0 : (n < cloud_limit8 ? 1 : 2));\n        return 71 + 3 * nclass;  // 71,74,77\n      }\n    }\n\n    // No thunder (or not available). Then we always need precipitation rate\n\n    if (!q.param(kFmiPrecipitation1h))\n      return {};\n\n    const auto rain = q.interpolate(latlon, t, maxgap);\n\n    if (rain == kFloatMissing)\n      return {};\n\n    if (rain < rain_limit1)\n    {\n      // No precipitation. Now we need only fog/cloudiness\n\n      if (q.param(kFmiFogIntensity))\n      {\n        const auto fog = q.interpolate(latlon, t, maxgap);\n        if (fog > 0 && fog != kFloatMissing)\n          return 9;  // fog\n      }\n\n      // no rain, no fog (or not available), only cloudiness\n      if (n < cloud_limit2)\n        return 1;  // clear\n      if (n < cloud_limit3)\n        return 2;  // mostly clear\n      if (n < cloud_limit6)\n        return 4;  // partly cloudy\n      if (n < cloud_limit8)\n        return 6;  // mostly cloudy\n      return 7;    // overcast\n    }\n\n    // Since we have precipitation, we always need precipitation form\n    int rform = static_cast<int>(kFloatMissing);\n    if (q.param(kFmiPotentialPrecipitationForm) || q.param(kFmiPrecipitationForm))\n      rform = static_cast<int>(q.interpolate(latlon, t, maxgap));\n\n    if (rform == static_cast<int>(kFloatMissing))\n      return {};\n\n    if (rform == 0)  // drizzle\n      return 11;\n\n    if (rform == 4)  // freezing drizzle\n      return 14;\n\n    if (rform == 5)  // freezing rain\n      return 17;\n\n    if (rform == 7 || rform == 8)  // snow or ice particles\n      return 57;                   // convert to plain snowfall + cloudy\n\n    // only water, sleet and snow left. Cloudiness limits\n    // are the same for them, precipitation limits are not.\n\n    int nclass = (n < cloud_limit6 ? 0 : (n < cloud_limit8 ? 1 : 2));\n\n    if (rform == 6)  // hail\n      return 61 + 3 * nclass;\n\n    if (rform == 1)  // water\n    {\n      // Now we need precipitation type too\n      int rtype = 1;  // large scale by default\n      if (q.param(kFmiPotentialPrecipitationType) || q.param(kFmiPrecipitationType))\n        rtype = static_cast<int>(q.interpolate(latlon, t, maxgap));\n\n      if (rtype == 2)            // convective\n        return 21 + 3 * nclass;  // 21, 24, 27 for showers\n\n      // rtype=1:large scale precipitation (or rtype is missing)\n      int rclass = (rain < rain_limit3 ? 0 : (rain < rain_limit6 ? 1 : 2));\n      return 31 + 3 * nclass + rclass;  // 31-39 for precipitation\n    }\n\n    // rform=2:sleet and rform=3:snow map to 41-49 and 51-59 respectively\n\n    int rclass = (rain < rain_limit3 ? 0 : (rain < rain_limit4 ? 1 : 2));\n    return (10 * rform + 21 + 3 * nclass + rclass);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Calculate the weather number used as basis for SmartSymbol\n */\n// ----------------------------------------------------------------------\n\nboost::optional<int> calc_weather_number(QImpl &q,\n                                         const NFmiPoint &latlon,\n                                         const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    NFmiMetTime t(ldt);\n\n    // Cloudiness is optional\n    float n = kFloatMissing;\n    if (q.param(kFmiTotalCloudCover))\n      n = q.interpolate(latlon, t, maxgap);\n\n    int n_class = 9;  // missing\n    if (n == kFloatMissing)\n      n_class = 9;\n    else if (n < cloud_limit1)\n      n_class = 0;\n    else if (n < cloud_limit2)\n      n_class = 1;\n    else if (n < cloud_limit3)\n      n_class = 2;\n    else if (n < cloud_limit4)\n      n_class = 3;\n    else if (n < cloud_limit5)\n      n_class = 4;\n    else if (n < cloud_limit6)\n      n_class = 5;\n    else if (n < cloud_limit7)\n      n_class = 6;\n    else if (n < cloud_limit8)\n      n_class = 7;\n    else\n      n_class = 8;\n\n    // Precipitation is optional\n    float rain = kFloatMissing;\n    if (q.param(kFmiPrecipitation1h))\n      rain = q.interpolate(latlon, t, maxgap);\n\n    int rain_class = 9;  // missing\n    if (rain == kFloatMissing)\n      rain_class = 9;\n    else if (rain < rain_limit1)\n      rain_class = 0;\n    else if (rain < rain_limit2)\n      rain_class = 1;\n    else if (rain < rain_limit3)\n      rain_class = 2;\n    else if (rain < rain_limit4)\n      rain_class = 3;\n    else if (rain < rain_limit5)\n      rain_class = 4;\n    else if (rain < rain_limit6)\n      rain_class = 5;\n    else if (rain < rain_limit7)\n      rain_class = 6;\n    else\n      rain_class = 7;\n\n    // Precipitation form is optional\n    float rform = kFloatMissing;\n    if (q.param(kFmiPotentialPrecipitationForm))\n      rform = q.interpolate(latlon, t, maxgap);\n    else if (q.param(kFmiPrecipitationForm))\n      rform = q.interpolate(latlon, t, maxgap);\n\n    int rform_class = (rform == kFloatMissing ? 9 : static_cast<int>(rform));\n\n    // Precipitation type is optional\n    float rtype = kFloatMissing;\n    if (q.param(kFmiPotentialPrecipitationType) || q.param(kFmiPrecipitationType))\n      rtype = q.interpolate(latlon, t, maxgap);\n\n    int rtype_class = (rtype == kFloatMissing ? 9 : static_cast<int>(rtype));\n\n    // Thunder is optional\n    float thunder = kFloatMissing;\n    if (q.param(kFmiProbabilityThunderstorm))\n      thunder = q.interpolate(latlon, t, maxgap);\n\n    int thunder_class = 9;\n    if (thunder == kFloatMissing)\n      thunder_class = 9;\n    else if (thunder < thunder_limit1)\n      thunder_class = 0;\n    else if (thunder < thunder_limit2)\n      thunder_class = 1;\n    else\n      thunder_class = 2;\n\n    // Fog is optional\n    float fog = kFloatMissing;\n    if (q.param(kFmiFogIntensity))\n      fog = q.interpolate(latlon, t, maxgap);\n\n    int fog_class = (fog == kFloatMissing ? 9 : static_cast<int>(fog));\n\n    // Build the number\n    const int version = 1;\n    const int cloud_class = 0;  // not available yet\n\n    // clang-format off\n    return (10000000 * version +\n            1000000 * thunder_class +\n            100000 * rform_class +\n            10000 * rtype_class +\n            1000 * rain_class +\n            100 * fog_class +\n            10 * n_class +\n            cloud_class);\n    // clang-format on\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}  // namespace Querydata\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief SmartSymbol\n */\n// ----------------------------------------------------------------------\n\nts::Value SmartSymbolNumber(QImpl &q,\n                            const Spine::Location &loc,\n                            const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    NFmiPoint latlon(loc.longitude, loc.latitude);\n\n    auto symbol = calc_smart_symbol(q, latlon, ldt);\n\n    if (!symbol || *symbol == kFloatMissing)\n      return Spine::TimeSeries::None();\n\n    // Add day/night information\n    Fmi::Astronomy::solar_position_t sp =\n        Fmi::Astronomy::solar_position(ldt, loc.longitude, loc.latitude);\n\n    if (sp.dark())\n      return 100 + *symbol;\n    return *symbol;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief WeatherNumber\n */\n// ----------------------------------------------------------------------\n\nts::Value WeatherNumber(QImpl &q,\n                        const Spine::Location &loc,\n                        const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    NFmiPoint latlon(loc.longitude, loc.latitude);\n\n    auto number = calc_weather_number(q, latlon, ldt);\n\n    if (!number)\n      return Spine::TimeSeries::None();\n\n    return *number;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Symbol text\n */\n// ----------------------------------------------------------------------\n\nts::Value SmartSymbolText(QImpl &q,\n                          const Spine::Location &loc,\n                          const boost::local_time::local_date_time &ldt,\n                          const std::string &lang)\n{\n  try\n  {\n    NFmiPoint latlon(loc.longitude, loc.latitude);\n\n    auto symbol = calc_smart_symbol(q, latlon, ldt);\n\n    if (!symbol)\n      return Spine::TimeSeries::None();\n\n    if (lang == \"en\")\n    {\n      switch (*symbol)\n      {\n        case 1:\n          return \"clear\";\n        case 2:\n          return \"mostly clear\";\n        case 4:\n          return \"partly cloudy\";\n        case 6:\n          return \"mostly cloudy\";\n        case 7:\n          return \"overcast\";\n        case 9:\n          return \"fog\";\n        case 71:\n          return \"isolated thundershowers\";\n        case 74:\n          return \"scattered thundershowers\";\n        case 77:\n          return \"thundershowers\";\n        case 21:\n          return \"isolated showers\";\n        case 24:\n          return \"scattered showers\";\n        case 27:\n          return \"showers\";\n        case 11:\n          return \"drizzle\";\n        case 14:\n          return \"freezing drizzle\";\n        case 17:\n          return \"freezing rain\";\n        case 31:\n        case 34:\n          return \"periods of light rain\";\n        case 37:\n          return \"light rain\";\n        case 32:\n        case 35:\n          return \"periods of moderate rain\";\n        case 38:\n          return \"moderate rain\";\n        case 33:\n        case 36:\n          return \"periods of heavy rain\";\n        case 39:\n          return \"heavy rain\";\n        case 41:\n          return \"isolated light sleet showers\";\n        case 44:\n          return \"scattered light sleet showers\";\n        case 47:\n          return \"light sleet\";\n        case 42:\n          return \"isolated moderate sleet showers\";\n        case 45:\n          return \"scattered moderate sleet showers\";\n        case 48:\n          return \"moderate sleet\";\n        case 43:\n          return \"isolated heavy sleet showers\";\n        case 46:\n          return \"scattered heavy sleet showers\";\n        case 49:\n          return \"heavy sleet\";\n        case 51:\n          return \"isolated light snow showers\";\n        case 54:\n          return \"scattered light snow showers\";\n        case 57:\n          return \"light snowfall\";\n        case 52:\n          return \"isolated moderate snow showers\";\n        case 55:\n          return \"scattered moderate snow showers\";\n        case 58:\n          return \"moderate snowfall\";\n        case 53:\n          return \"isolated heavy snow showers\";\n        case 56:\n          return \"scattered heavy snow showers\";\n        case 59:\n          return \"heavy snowfall\";\n        case 61:\n          return \"isolated hail showers\";\n        case 64:\n          return \"scattered hail showers\";\n        case 67:\n          return \"hail showers\";\n      }\n    }\n    else if (lang == \"sv\")\n    {\n      // From http://sv.ilmatieteenlaitos.fi/vadersymbolerna\n      switch (*symbol)\n      {\n        case 1:\n          return u8\"klart\";\n        case 2:\n          return u8\"mest klart\";\n        case 4:\n          return u8\"halvklart\";\n        case 6:\n          return u8\"molnight\";\n        case 7:\n          return u8\"mulet\";\n        case 9:\n          return u8\"dimma\";\n        case 71:\n          return u8\"enstaka \\00e5skskurar\";\n        case 74:\n          return u8\"lokalt \\00e5skskurar\";\n        case 77:\n          return u8\"\\00e5skskurar\";\n        case 21:\n          return u8\"enstaka regnskurar\";\n        case 24:\n          return u8\"lokalt regnskurar\";\n        case 27:\n          return u8\"regnskurar\";\n        case 11:\n          return u8\"duggregn\";\n        case 14:\n          return u8\"underkylt duggregn\";\n        case 17:\n          return u8\"underkylt regn\";\n        case 31:\n        case 34:\n          return u8\"tidvis l\\u00e4tt regn\";\n        case 37:\n          return u8\"l\\u00e4tt regn\";\n        case 32:\n        case 35:\n          return u8\"tidvis m\\00e5ttligt regn\";\n        case 38:\n          return u8\"m\\00e5ttligt regn\";\n        case 33:\n        case 36:\n          return u8\"tidvis kraftigt regn\";\n        case 39:\n          return u8\"kraftigt regn\";\n        case 41:\n        case 44:\n          return u8\"tidvis l\\u00e4tta byar av sn\\u00f6blandat regn\";\n        case 47:\n          return u8\"l\\u00e4tt sn\\u00f6blandat regn\";\n        case 42:\n        case 45:\n          return u8\"tidvis m\\00e5ttliga byar av sn\\u00f6blandat regn\";\n        case 48:\n          return u8\"m\\00e5ttligt sn\\u00f6blandat regn\";\n        case 43:\n        case 46:\n          return u8\"tidvis kraftiga byar av sn\\u00f6blandat regn\";\n        case 49:\n          return u8\"kraftigt sn\\u00f6blandat regn\";\n        case 51:\n        case 54:\n          return u8\"tidvis l\\u00e4tta sn\\u00f6byar\";\n        case 57:\n          return u8\"tidvis l\\u00e4tt sn\\u00f6fall\";\n        case 52:\n        case 55:\n          return u8\"tidvis m\\00e5ttliga sn\\u00f6byar\";\n        case 58:\n          return u8\"m\\00e5ttligt sn\\u00f6fall\";\n        case 53:\n        case 56:\n          return u8\"tidvis ymniga sn\\u00f6byar\";\n        case 59:\n          return u8\"ymnigt sn\\u00f6fall\";\n        case 61:\n          return u8\"enstaka hagelskurar\";\n        case 64:\n          return u8\"lokalt hagelskurar\";\n        case 67:\n          return u8\"hagelskurar\";\n      }\n    }\n    else\n    {\n      switch (*symbol)\n      {\n        case 1:\n          return u8\"selke\\u00e4\\u00e4\";\n        case 2:\n          return u8\"enimm\\u00e4kseen selke\\u00e4\\u00e4\";\n        case 4:\n          return u8\"puolipilvist\\u00e4\";\n        case 6:\n          return u8\"enimm\\u00e4kseen pilvist\\u00e4\";\n        case 7:\n          return u8\"pilvist\\u00e4\";\n        case 9:\n          return u8\"sumua\";\n        case 71:\n          return u8\"yksitt\\u00e4isi\\u00e4 ukkoskuuroja\";\n        case 74:\n          return u8\"paikoin ukkoskuuroja\";\n        case 77:\n          return u8\"ukkoskuuroja\";\n        case 21:\n          return u8\"yksitt\\u00e4isi\\u00e4 sadekuuroja\";\n        case 24:\n          return u8\"paikoin sadekuuroja\";\n        case 27:\n          return u8\"sadekuuroja\";\n        case 11:\n          return u8\"tihkusadetta\";\n        case 14:\n          return u8\"j\\u00e4\\u00e4t\\u00e4v\\u00e4\\u00e4 tihkua\";\n        case 17:\n          return u8\"j\\u00e4\\u00e4t\\u00e4v\\u00e4\\u00e4 sadetta\";\n        case 31:\n        case 34:\n          return u8\"ajoittain heikkoa vesisadetta\";\n        case 37:\n          return u8\"heikkoa vesisadetta\";\n        case 32:\n        case 35:\n          return u8\"ajoittain kohtalaista vesisadetta\";\n        case 38:\n          return u8\"kohtalaista vesisadetta\";\n        case 33:\n        case 36:\n          return u8\"ajoittain voimakasta vesisadetta\";\n        case 39:\n          return u8\"voimakasta vesisadetta\";\n        case 41:\n        case 44:\n          return u8\"ajoittain heikkoja r\\u00e4nt\\u00e4kuuroja\";\n        case 47:\n          return u8\"heikkoa r\\u00e4nt\\u00e4sadetta\";\n        case 42:\n        case 45:\n          return u8\"ajoittain kohtalaisia r\\u00e4nt\\u00e4kuuroja\";\n        case 48:\n          return u8\"kohtalaista r\\u00e4nt\\u00e4sadetta\";\n        case 43:\n        case 46:\n          return u8\"ajoittain voimakkaita r\\u00e4nt\\u00e4kuuroja\";\n        case 49:\n          return u8\"voimakasta r\\u00e4nt\\u00e4sadetta\";\n        case 51:\n        case 54:\n          return u8\"ajoittain heikkoja lumikuuroja\";\n          return u8\"ajoittain heikkoja lumikuuroja\";\n        case 57:\n          return u8\"heikkoa lumisadetta\";\n        case 52:\n        case 55:\n          return u8\"ajoittain kohtalaisia lumikuuroja\";\n          return u8\"ajoittain kohtalaisia lumikuuroja\";\n        case 58:\n          return u8\"kohtalaista lumisadetta\";\n        case 53:\n        case 56:\n          return u8\"ajoittain sakeita lumikuuroja\";\n        case 59:\n          return u8\"runsasta lumisadetta\";\n        case 61:\n          return u8\"yksitt\\u00e4isi\\u00e4 raekuuroja\";\n        case 64:\n          return u8\"paikoin raekuuroja\";\n        case 67:\n          return u8\"raekuuroja\";\n      }\n    }\n    throw Fmi::Exception(BCP, \"Unknown symbol value : \" + Fmi::to_string(*symbol));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Grid north deviation\n */\n// ----------------------------------------------------------------------\n\nts::Value GridNorth(const QImpl &q, const Spine::Location &loc)\n{\n  try\n  {\n    Fmi::CoordinateTransformation transformation(\"WGS84\", q.SpatialReference());\n    auto opt_angle = Fmi::OGR::gridNorth(transformation, loc.longitude, loc.latitude);\n    if (!opt_angle)\n      return Spine::TimeSeries::None();\n    return *opt_angle;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract data value\n */\n// ----------------------------------------------------------------------\n\nts::Value QImpl::dataValue(const ParameterOptions &opt,\n                           const NFmiPoint &latlon,\n                           const boost::local_time::local_date_time &ldt)\n{\n  NFmiMetTime t = ldt;\n\n  // Change the year if the data contains climatology\n  if (isClimatology())\n  {\n    int year = originTime().PosixTime().date().year();\n    t.SetYear(boost::numeric_cast<short>(year));\n  }\n\n  float interpolatedValue = interpolate(latlon, t, maxgap);\n\n  // If we got no value and the proper flag is on,\n  // find the nearest point with valid values and use\n  // the values from that point\n\n  if (interpolatedValue == kFloatMissing && opt.findnearestvalidpoint)\n  {\n    interpolatedValue = interpolate(opt.nearestpoint, t, maxgap);\n    if (interpolatedValue != kFloatMissing)\n      opt.lastpoint = opt.nearestpoint;\n  }\n\n  if (interpolatedValue == kFloatMissing)\n    return Spine::TimeSeries::None();\n\n  return interpolatedValue;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract data independent parameter value\n */\n// ----------------------------------------------------------------------\n\nts::Value QImpl::dataIndependentValue(const ParameterOptions &opt,\n                                      const boost::local_time::local_date_time &ldt,\n                                      double levelResult)\n{\n  // Some shorthand variables\n  const std::string &pname = opt.par.name();\n  const Spine::Location &loc = opt.loc;\n\n  switch (opt.par.number())\n  {\n    case kFmiPlace:\n      return opt.place;\n    case kFmiName:\n      return loc.name;\n    case kFmiISO2:\n      return loc.iso2;\n    case kFmiGEOID:\n    {\n      if (loc.geoid == 0)  // not sure why this is still here\n        return Spine::TimeSeries::None();\n      return Fmi::to_string(loc.geoid);\n    }\n    case kFmiLatitude:\n      return loc.latitude;\n    case kFmiLongitude:\n      return loc.longitude;\n    case kFmiLatLon:\n    case kFmiLonLat:\n      return ts::LonLat(loc.longitude, loc.latitude);\n    case kFmiRegion:\n    {\n      // This reintroduces an older bug/feature where the name of the location is given as a\n      // region if it doesn't belong to any administrative region. (i.e. Helsinki doesn't have\n      // region, Kumpula has.) Also checking whether the loc.name has valid data, if it's empty as\n      // well - which shoudn't occur - we return nan\n\n      if (!loc.area.empty())\n        return loc.area;  // Administrative region known.\n\n      if (loc.name.empty())\n        // No area (administrative region) nor name known.\n        return Spine::TimeSeries::None();\n\n      // Place name known, administrative region unknown.\n      return loc.name;\n    }\n    case kFmiCountry:\n      return opt.country;\n    case kFmiFeature:\n      return loc.feature;\n    case kFmiTZ:\n    {\n      if (ldt.zone())\n        return ldt.zone()->std_zone_name();\n      return Spine::TimeSeries::None();\n    }\n    case kFmiLocalTZ:\n      return loc.timezone;\n    case kFmiLevel:\n      return levelResult;\n    case kFmiNearLatitude:\n      return opt.lastpoint.Y();\n    case kFmiNearLongitude:\n      return opt.lastpoint.X();\n    case kFmiNearLatLon:\n    case kFmiNearLonLat:\n      return ts::LonLat(opt.lastpoint.X(), opt.lastpoint.Y());\n    case kFmiPopulation:\n      return Fmi::to_string(loc.population);\n    case kFmiElevation:\n      return Fmi::to_string(loc.elevation);\n    case kFmiDEM:\n      return Fmi::to_string(loc.dem);\n    case kFmiCoverType:\n      return Fmi::to_string(static_cast<int>(loc.covertype));\n    case kFmiModel:\n      return opt.producer;\n    case kFmiTime:\n      return opt.timeformatter.format(ldt);\n    case kFmiISOTime:\n      return Fmi::to_iso_string(ldt.local_time());\n    case kFmiXMLTime:\n      return Fmi::to_iso_extended_string(ldt.local_time());\n    case kFmiLocalTime:\n    {\n      auto localtz = Fmi::TimeZoneFactory::instance().time_zone_from_string(loc.timezone);\n      boost::posix_time::ptime utc = ldt.utc_time();\n      boost::local_time::local_date_time localt(utc, localtz);\n      return opt.timeformatter.format(localt);\n    }\n    case kFmiUTCTime:\n      return opt.timeformatter.format(ldt.utc_time());\n    case kFmiEpochTime:\n    {\n      boost::posix_time::ptime time_t_epoch(boost::gregorian::date(1970, 1, 1));\n      boost::posix_time::time_duration diff = ldt.utc_time() - time_t_epoch;\n      return Fmi::to_string(diff.total_seconds());\n    }\n    case kFmiOriginTime:\n    {\n      if (!time(ldt.utc_time()))\n      {\n        // Search first valid time after the desired time, and choose that origintime\n        bool ok = false;\n        for (resetTime(); !ok && nextTime();)\n          ok = (validTime() > ldt.utc_time());\n        if (!ok)\n          return Spine::TimeSeries::None();\n      }\n      boost::posix_time::ptime utc = originTime();\n      boost::local_time::local_date_time localt(utc, ldt.zone());\n      return opt.timeformatter.format(localt);\n    }\n    case kFmiModTime:\n    {\n      boost::posix_time::ptime utc = modificationTime();\n      boost::local_time::local_date_time localt(utc, ldt.zone());\n      return opt.timeformatter.format(localt);\n    }\n    case kFmiDark:\n    {\n      auto pos = Fmi::Astronomy::solar_position(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(pos.dark()));\n    }\n    case kFmiMoonPhase:\n      return Fmi::Astronomy::moonphase(ldt.utc_time());\n    case kFmiMoonrise:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_iso_string(ltime.moonrise.local_time());\n    }\n    case kFmiMoonrise2:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n\n      if (ltime.moonrise2_today())\n        return Fmi::to_iso_string(ltime.moonrise2.local_time());\n\n      return std::string(\"\");\n    }\n    case kFmiMoonset:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_iso_string(ltime.moonset.local_time());\n    }\n    case kFmiMoonset2:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      if (ltime.moonset2_today())\n        return Fmi::to_iso_string(ltime.moonset2.local_time());\n      return std::string(\"\");\n    }\n    case kFmiMoonriseToday:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(ltime.moonrise_today()));\n    }\n    case kFmiMoonrise2Today:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(ltime.moonrise2_today()));\n    }\n    case kFmiMoonsetToday:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(ltime.moonset_today()));\n    }\n    case kFmiMoonset2Today:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(ltime.moonset2_today()));\n    }\n    case kFmiMoonUp24h:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(ltime.above_horizont_24h()));\n    }\n    case kFmiMoonDown24h:\n    {\n      auto ltime = Fmi::Astronomy::lunar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(!ltime.moonrise_today() && !ltime.moonset_today() &&\n                                             !ltime.above_horizont_24h()));\n    }\n    case kFmiSunrise:\n    {\n      auto stime = Fmi::Astronomy::solar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_iso_string(stime.sunrise.local_time());\n    }\n    case kFmiSunset:\n    {\n      auto stime = Fmi::Astronomy::solar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_iso_string(stime.sunset.local_time());\n    }\n    case kFmiNoon:\n    {\n      auto stime = Fmi::Astronomy::solar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_iso_string(stime.noon.local_time());\n    }\n    case kFmiSunriseToday:\n    {\n      auto stime = Fmi::Astronomy::solar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(stime.sunrise_today()));\n    }\n    case kFmiSunsetToday:\n    {\n      auto stime = Fmi::Astronomy::solar_time(ldt, loc.longitude, loc.latitude);\n      return Fmi::to_string(static_cast<int>(stime.sunset_today()));\n    }\n    case kFmiDayLength:\n    {\n      auto stime = Fmi::Astronomy::solar_time(ldt, loc.longitude, loc.latitude);\n      auto seconds = stime.daylength().total_seconds();\n      auto minutes = lround(seconds / 60.0);\n      return Fmi::to_string(minutes);\n    }\n    case kFmiTimeString:\n      return format_date(ldt, opt.outlocale, opt.timestring);\n    case kFmiWDay:\n      return format_date(ldt, opt.outlocale, \"%a\");\n    case kFmiWeekday:\n      return format_date(ldt, opt.outlocale, \"%A\");\n    case kFmiMon:\n      return format_date(ldt, opt.outlocale, \"%b\");\n    case kFmiMonth:\n      return format_date(ldt, opt.outlocale, \"%B\");\n    case kFmiSunElevation:\n    {\n      auto pos = Fmi::Astronomy::solar_position(ldt, loc.longitude, loc.latitude);\n      return pos.elevation;\n    }\n    case kFmiSunDeclination:\n    {\n      auto pos = Fmi::Astronomy::solar_position(ldt, loc.longitude, loc.latitude);\n      return pos.declination;\n    }\n    case kFmiSunAzimuth:\n    {\n      auto pos = Fmi::Astronomy::solar_position(ldt, loc.longitude, loc.latitude);\n      return pos.azimuth;\n    }\n    case kFmiGridNorth:\n      return GridNorth(*this, loc);\n    case kFmiHour:\n      return Fmi::to_string(ldt.local_time().time_of_day().hours());\n      // The following parameters are added for for obsengine compability reasons\n      // so that we can have e.g. fmisid identifier for observations in query which\n      // has both observations and forecasts\n    case kFmiFMISID:\n    case kFmiWmoStationNumber:\n    case kFmiLPNN:\n    case kFmiRWSID:\n    case kFmiStationary:\n    case kFmiDistance:\n    case kFmiDirection:\n    case kFmiSensorNo:\n    case kFmiStationName:\n      return Spine::TimeSeries::None();\n    default:\n      break;\n  }\n\n  if (pname.substr(0, 5) == \"date(\" && pname[pname.size() - 1] == ')')\n    return format_date(ldt, opt.outlocale, pname.substr(5, pname.size() - 6));\n\n  throw Fmi::Exception(BCP,\n                       \"Unknown DataIndependent special function '\" + pname + \"' with number \" +\n                           Fmi::to_string(opt.par.number()));\n}\n\n// ======================================================================\n\nts::Value QImpl::value(const ParameterOptions &opt, const boost::local_time::local_date_time &ldt)\n{\n  try\n  {\n    // Default return value\n    ts::Value retval = Spine::TimeSeries::None();\n\n    // Shorthand variables\n    const Spine::Location &loc = opt.loc;\n\n    // Update last accessed point.\n\n    NFmiPoint latlon(loc.longitude, loc.latitude);\n\n    switch (opt.par.type())\n    {\n      case Spine::Parameter::Type::Landscaped:\n      {\n        // We can landscape only surface data\n        if (itsModels[0]->levelName() == \"surface\")\n        {\n          if (param(opt.par.number()))\n          {\n            time(ldt);\n\n            bool iswater = Fmi::LandCover::isOpenWater(loc.covertype);\n            // DEM data is more accurate\n            if (loc.dem == 0)\n              iswater = true;\n\n            retval = itsInfo->LandscapeInterpolatedValue(loc.dem, iswater, latlon, ldt);\n          }\n          break;\n        }\n        // normal handling continues below\n      }\n      // fall through\n      case Spine::Parameter::Type::Data:\n      {\n        opt.lastpoint = latlon;\n        if (param(opt.par.number()))\n          retval = dataValue(opt, latlon, ldt);\n        break;\n      }\n      case Spine::Parameter::Type::DataDerived:\n      {\n        switch (opt.par.number())\n        {\n          case kFmiLatitude:\n          {\n            retval = loc.latitude;\n            break;\n          }\n          case kFmiLongitude:\n          {\n            retval = loc.longitude;\n            break;\n          }\n          case kFmiLatLon:\n          case kFmiLonLat:\n          {\n            retval = ts::LonLat(loc.longitude, loc.latitude);\n            break;\n          }\n          case kFmiWindCompass8:\n          {\n            retval = WindCompass8(*this, loc, ldt);\n            break;\n          }\n          case kFmiWindCompass16:\n          {\n            retval = WindCompass16(*this, loc, ldt);\n            break;\n          }\n          case kFmiWindCompass32:\n          {\n            retval = WindCompass32(*this, loc, ldt);\n            break;\n          }\n          case kFmiCloudiness8th:\n          {\n            retval = Cloudiness8th(*this, loc, ldt);\n            break;\n          }\n          case kFmiWindChill:\n          {\n            retval = WindChill(*this, loc, ldt);\n            break;\n          }\n          case kFmiSummerSimmerIndex:\n          {\n            retval = SummerSimmerIndex(*this, loc, ldt);\n            break;\n          }\n          case kFmiFeelsLike:\n          {\n            retval = FeelsLike(*this, loc, ldt);\n            break;\n          }\n          case kFmiApparentTemperature:\n          {\n            retval = ApparentTemperature(*this, loc, ldt);\n            break;\n          }\n          case kFmiWeather:\n          {\n            retval = WeatherText(*this, loc, ldt, opt.language, *itsParameterTranslations);\n            break;\n          }\n          case kFmiWeatherSymbol:\n          {\n            retval = WeatherSymbol(*this, loc, ldt);\n            break;\n          }\n          case kFmiSmartSymbol:\n          {\n            retval = SmartSymbolNumber(*this, loc, ldt);\n            break;\n          }\n          case kFmiSmartSymbolText:\n          {\n            retval = SmartSymbolText(*this, loc, ldt, opt.language);\n            break;\n          }\n          case kFmiWeatherNumber:\n          {\n            retval = WeatherNumber(*this, loc, ldt);\n            break;\n          }\n          case kFmiSnow1hLower:\n          {\n            retval = Snow1hLower(*this, loc, ldt);\n            break;\n          }\n          case kFmiSnow1hUpper:\n          {\n            retval = Snow1hUpper(*this, loc, ldt);\n            break;\n          }\n          case kFmiSnow1h:\n          {\n            retval = Snow1h(*this, loc, ldt);\n            break;\n          }\n          case kFmiWindUMS:\n          {\n            if (isRelativeUV())\n              retval = WindUMS(*this, loc, ldt);\n            else if (param(kFmiWindUMS))\n              retval = dataValue(opt, latlon, ldt);\n            break;\n          }\n          case kFmiWindVMS:\n          {\n            if (isRelativeUV())\n              retval = WindVMS(*this, loc, ldt);\n            else if (param(kFmiWindVMS))\n              retval = dataValue(opt, latlon, ldt);\n            break;\n          }\n          default:\n            throw Fmi::Exception(BCP, \"Unknown DataDerived parameter '\" + opt.par.name() + \"'!\");\n        }\n        break;\n      }\n      case Spine::Parameter::Type::DataIndependent:\n      {\n        retval = dataIndependentValue(opt, ldt, levelValue());\n        break;\n      }\n    }\n\n    if (boost::get<double>(&retval) != nullptr)\n    {\n      if (*(boost::get<double>(&retval)) == kFloatMissing)\n        retval = Spine::TimeSeries::None();\n    }\n\n    return retval;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nts::Value QImpl::valueAtPressure(const ParameterOptions &opt,\n                                 const boost::local_time::local_date_time &ldt,\n                                 float pressure)\n{\n  try\n  {\n    // Default return value\n    ts::Value retval = Spine::TimeSeries::None();\n\n    // Some shorthand variables\n    const Spine::Location &loc = opt.loc;\n\n    // Update last accessed point.\n\n    NFmiPoint latlon(loc.longitude, loc.latitude);\n\n    switch (opt.par.type())\n    {\n      case Spine::Parameter::Type::Landscaped:\n      case Spine::Parameter::Type::Data:\n      {\n        opt.lastpoint = latlon;\n\n        if (param(opt.par.number()) && (itsModels[0]->levelName() != \"surface\") && !isClimatology())\n        {\n          NFmiMetTime t = ldt;\n\n          float interpolatedValue = interpolateAtPressure(latlon, t, pressure, maxgap);\n\n          // If we got no value and the proper flag is on,\n          // find the nearest point with valid values and use\n          // the values from that point\n\n          if (interpolatedValue == kFloatMissing && opt.findnearestvalidpoint)\n          {\n            interpolatedValue = interpolateAtPressure(opt.nearestpoint, t, pressure, maxgap);\n            if (interpolatedValue != kFloatMissing)\n              opt.lastpoint = opt.nearestpoint;\n          }\n\n          if (interpolatedValue == kFloatMissing)\n            retval = Spine::TimeSeries::None();\n          else\n            retval = interpolatedValue;\n        }\n\n        break;\n      }\n      case Spine::Parameter::Type::DataDerived:\n      {\n        auto num = opt.par.number();\n        if (num == kFmiLatitude)\n          retval = loc.latitude;\n        else if (num == kFmiLongitude)\n          retval = loc.longitude;\n        else if (num == kFmiLatLon || num == kFmiLonLat)\n          retval = ts::LonLat(loc.longitude, loc.latitude);\n\n        break;\n      }\n      case Spine::Parameter::Type::DataIndependent:\n      {\n        retval = dataIndependentValue(opt, ldt, pressure);\n        break;\n      }\n    }\n\n    if (boost::get<double>(&retval) != nullptr)\n    {\n      if (*(boost::get<double>(&retval)) == kFloatMissing)\n        retval = Spine::TimeSeries::None();\n    }\n\n    return retval;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nts::Value QImpl::valueAtHeight(const ParameterOptions &opt,\n                               const boost::local_time::local_date_time &ldt,\n                               float height)\n{\n  try\n  {\n    // Default return value\n    ts::Value retval = Spine::TimeSeries::None();\n\n    // Some shorthand variables\n    const Spine::Location &loc = opt.loc;\n\n    // Update last accessed point.\n\n    NFmiPoint latlon(loc.longitude, loc.latitude);\n\n    switch (opt.par.type())\n    {\n      case Spine::Parameter::Type::Landscaped:\n      case Spine::Parameter::Type::Data:\n      {\n        opt.lastpoint = latlon;\n\n        if (param(opt.par.number()) && (itsModels[0]->levelName() != \"surface\") && !isClimatology())\n        {\n          NFmiMetTime t = ldt;\n\n          float interpolatedValue = interpolateAtHeight(latlon, t, height, maxgap);\n\n          // If we got no value and the proper flag is on,\n          // find the nearest point with valid values and use\n          // the values from that point\n\n          if (interpolatedValue == kFloatMissing && opt.findnearestvalidpoint)\n          {\n            interpolatedValue = interpolateAtHeight(opt.nearestpoint, t, height, maxgap);\n            if (interpolatedValue != kFloatMissing)\n              opt.lastpoint = opt.nearestpoint;\n          }\n\n          if (interpolatedValue == kFloatMissing)\n            retval = Spine::TimeSeries::None();\n          else\n            retval = interpolatedValue;\n        }\n\n        break;\n      }\n      case Spine::Parameter::Type::DataDerived:\n      {\n        auto num = opt.par.number();\n        if (num == kFmiLatitude)\n          retval = loc.latitude;\n        else if (num == kFmiLongitude)\n          retval = loc.longitude;\n        else if (num == kFmiLatLon || num == kFmiLonLat)\n          retval = ts::LonLat(loc.longitude, loc.latitude);\n\n        break;\n      }\n      case Spine::Parameter::Type::DataIndependent:\n      {\n        retval = dataIndependentValue(opt, ldt, height);\n        break;\n      }\n    }\n\n    if (boost::get<double>(&retval) != nullptr)\n    {\n      if (*(boost::get<double>(&retval)) == kFloatMissing)\n        retval = Spine::TimeSeries::None();\n    }\n\n    return retval;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// one location, many timesteps\nts::TimeSeriesPtr QImpl::values(const ParameterOptions &param,\n                                const Spine::TimeSeriesGenerator::LocalTimeList &tlist)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesPtr ret(new ts::TimeSeries(param.localTimePool));\n\n    for (const boost::local_time::local_date_time &ldt : tlist)\n    {\n      ret->emplace_back(ts::TimedValue(ldt, value(param, ldt)));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\nts::TimeSeriesPtr QImpl::valuesAtPressure(const ParameterOptions &param,\n                                          const Spine::TimeSeriesGenerator::LocalTimeList &tlist,\n                                          float pressure)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesPtr ret(new ts::TimeSeries(param.localTimePool));\n\n    for (const boost::local_time::local_date_time &ldt : tlist)\n    {\n      ret->emplace_back(ts::TimedValue(ldt, valueAtPressure(param, ldt, pressure)));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\nts::TimeSeriesPtr QImpl::valuesAtHeight(const ParameterOptions &param,\n                                        const Spine::TimeSeriesGenerator::LocalTimeList &tlist,\n                                        float height)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesPtr ret(new ts::TimeSeries(param.localTimePool));\n\n    for (const boost::local_time::local_date_time &ldt : tlist)\n    {\n      ret->emplace_back(ts::TimedValue(ldt, valueAtHeight(param, ldt, height)));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// many locations (indexmask), many timesteps\nts::TimeSeriesGroupPtr QImpl::values(const ParameterOptions &param,\n                                     const NFmiIndexMask &indexmask,\n                                     const Spine::TimeSeriesGenerator::LocalTimeList &tlist)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesGroupPtr ret(new ts::TimeSeriesGroup);\n\n    for (const auto &mask : indexmask)\n    {\n      // Indexed latlon\n      NFmiPoint latlon(latLon(mask));\n\n      Spine::Location location(param.loc.geoid,\n                               param.loc.name,\n                               param.loc.iso2,\n                               param.loc.municipality,\n                               param.loc.area,\n                               param.loc.feature,\n                               param.loc.country,\n                               latlon.X(),\n                               latlon.Y(),\n                               param.loc.timezone,\n                               param.loc.population,\n                               param.loc.elevation,\n                               param.loc.priority);\n\n      ParameterOptions paramOptions(param.par,\n                                    param.producer,\n                                    location,\n                                    param.country,\n                                    param.place,\n                                    param.timeformatter,\n                                    param.timestring,\n                                    param.language,\n                                    param.outlocale,\n                                    param.outzone,\n                                    param.findnearestvalidpoint,\n                                    param.nearestpoint,\n                                    param.lastpoint,\n\t\t\t\t\t\t\t\t\tparam.localTimePool);\n\n      ts::TimeSeriesPtr timeseries = values(paramOptions, tlist);\n      ts::LonLat lonlat(latlon.X(), latlon.Y());\n\n      ret->emplace_back(ts::LonLatTimeSeries(lonlat, *timeseries));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\nts::TimeSeriesGroupPtr QImpl::valuesAtPressure(\n    const ParameterOptions &param,\n    const NFmiIndexMask &indexmask,\n    const Spine::TimeSeriesGenerator::LocalTimeList &tlist,\n    float pressure)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesGroupPtr ret(new ts::TimeSeriesGroup);\n\n    for (const auto &mask : indexmask)\n    {\n      // Indexed latlon\n      NFmiPoint latlon(latLon(mask));\n\n      Spine::Location location(param.loc.geoid,\n                               param.loc.name,\n                               param.loc.iso2,\n                               param.loc.municipality,\n                               param.loc.area,\n                               param.loc.feature,\n                               param.loc.country,\n                               latlon.X(),\n                               latlon.Y(),\n                               param.loc.timezone,\n                               param.loc.population,\n                               param.loc.elevation,\n                               param.loc.priority);\n\n      ParameterOptions paramOptions(param.par,\n                                    param.producer,\n                                    location,\n                                    param.country,\n                                    param.place,\n                                    param.timeformatter,\n                                    param.timestring,\n                                    param.language,\n                                    param.outlocale,\n                                    param.outzone,\n                                    param.findnearestvalidpoint,\n                                    param.nearestpoint,\n                                    param.lastpoint,\n\t\t\t\t\t\t\t\t\tparam.localTimePool);\n\n      ts::TimeSeriesPtr timeseries = valuesAtPressure(paramOptions, tlist, pressure);\n      ts::LonLat lonlat(latlon.X(), latlon.Y());\n\n      ret->emplace_back(ts::LonLatTimeSeries(lonlat, *timeseries));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\nts::TimeSeriesGroupPtr QImpl::valuesAtHeight(const ParameterOptions &param,\n                                             const NFmiIndexMask &indexmask,\n                                             const Spine::TimeSeriesGenerator::LocalTimeList &tlist,\n                                             float height)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesGroupPtr ret(new ts::TimeSeriesGroup);\n\n    for (const auto &mask : indexmask)\n    {\n      // Indexed latlon\n      NFmiPoint latlon(latLon(mask));\n\n      Spine::Location location(param.loc.geoid,\n                               param.loc.name,\n                               param.loc.iso2,\n                               param.loc.municipality,\n                               param.loc.area,\n                               param.loc.feature,\n                               param.loc.country,\n                               latlon.X(),\n                               latlon.Y(),\n                               param.loc.timezone,\n                               param.loc.population,\n                               param.loc.elevation,\n                               param.loc.priority);\n\n      ParameterOptions paramOptions(param.par,\n                                    param.producer,\n                                    location,\n                                    param.country,\n                                    param.place,\n                                    param.timeformatter,\n                                    param.timestring,\n                                    param.language,\n                                    param.outlocale,\n                                    param.outzone,\n                                    param.findnearestvalidpoint,\n                                    param.nearestpoint,\n                                    param.lastpoint,\n\t\t\t\t\t\t\t\t\tparam.localTimePool);\n\n      ts::TimeSeriesPtr timeseries = valuesAtHeight(paramOptions, tlist, height);\n      ts::LonLat lonlat(latlon.X(), latlon.Y());\n\n      ret->emplace_back(ts::LonLatTimeSeries(lonlat, *timeseries));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// many locations (llist), many timesteps\n\n// BUG?? Why is maxdistance in the API?\n\nts::TimeSeriesGroupPtr QImpl::values(const ParameterOptions &param,\n                                     const Spine::LocationList &llist,\n                                     const Spine::TimeSeriesGenerator::LocalTimeList &tlist,\n                                     const double & /* maxdistance */)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesGroupPtr ret(new ts::TimeSeriesGroup);\n\n    for (const Spine::LocationPtr &loc : llist)\n    {\n      ParameterOptions paramOptions(param.par,\n                                    param.producer,\n                                    *loc,\n                                    param.country,\n                                    param.place,\n                                    param.timeformatter,\n                                    param.timestring,\n                                    param.language,\n                                    param.outlocale,\n                                    param.outzone,\n                                    param.findnearestvalidpoint,\n                                    param.nearestpoint,\n                                    param.lastpoint,\n\t\t\t\t\t\t\t\t\tparam.localTimePool);\n\n      ts::TimeSeriesPtr timeseries = values(paramOptions, tlist);\n      ts::LonLat lonlat(loc->longitude, loc->latitude);\n\n      ret->emplace_back(ts::LonLatTimeSeries(lonlat, *timeseries));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\nts::TimeSeriesGroupPtr QImpl::valuesAtPressure(\n    const ParameterOptions &param,\n    const Spine::LocationList &llist,\n    const Spine::TimeSeriesGenerator::LocalTimeList &tlist,\n    const double & /* maxdistance */,\n    float pressure)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesGroupPtr ret(new ts::TimeSeriesGroup);\n\n    for (const Spine::LocationPtr &loc : llist)\n    {\n      ParameterOptions paramOptions(param.par,\n                                    param.producer,\n                                    *loc,\n                                    param.country,\n                                    param.place,\n                                    param.timeformatter,\n                                    param.timestring,\n                                    param.language,\n                                    param.outlocale,\n                                    param.outzone,\n                                    param.findnearestvalidpoint,\n                                    param.nearestpoint,\n                                    param.lastpoint,\n\t\t\t\t\t\t\t\t\tparam.localTimePool);\n\n      ts::TimeSeriesPtr timeseries = valuesAtPressure(paramOptions, tlist, pressure);\n      ts::LonLat lonlat(loc->longitude, loc->latitude);\n\n      ret->emplace_back(ts::LonLatTimeSeries(lonlat, *timeseries));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\nts::TimeSeriesGroupPtr QImpl::valuesAtHeight(const ParameterOptions &param,\n                                             const Spine::LocationList &llist,\n                                             const Spine::TimeSeriesGenerator::LocalTimeList &tlist,\n                                             const double & /* maxdistance */,\n                                             float height)\n{\n  try\n  {\n\tcheck_local_time_pool(param);\n\n    ts::TimeSeriesGroupPtr ret(new ts::TimeSeriesGroup);\n\n    for (const Spine::LocationPtr &loc : llist)\n    {\n      ParameterOptions paramOptions(param.par,\n                                    param.producer,\n                                    *loc,\n                                    param.country,\n                                    param.place,\n                                    param.timeformatter,\n                                    param.timestring,\n                                    param.language,\n                                    param.outlocale,\n                                    param.outzone,\n                                    param.findnearestvalidpoint,\n                                    param.nearestpoint,\n                                    param.lastpoint,\n\t\t\t\t\t\t\t\t\tparam.localTimePool);\n\n      ts::TimeSeriesPtr timeseries = valuesAtHeight(paramOptions, tlist, height);\n      ts::LonLat lonlat(loc->longitude, loc->latitude);\n\n      ret->emplace_back(ts::LonLatTimeSeries(lonlat, *timeseries));\n    }\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Load dem values and water flags for native (sub)grid or for given locations.\n * \t\t  Returns false if there's no valid location (within the native grid)\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::loadDEMAndWaterFlags(const Fmi::DEM &theDem,\n                                 const Fmi::LandCover &theLandCover,\n                                 double theResolution,\n                                 const NFmiDataMatrix<NFmiLocationCache> &theLocationCache,\n                                 NFmiDataMatrix<float> &theDemMatrix,\n                                 NFmiDataMatrix<bool> &theWaterFlagMatrix,\n                                 int x1,\n                                 int y1,\n                                 int x2,\n                                 int y2) const\n{\n  try\n  {\n    if (!isGrid())\n      throw Fmi::Exception(BCP, \"Can only be used for gridded data!\");\n\n    // Resolution must be given with locations\n\n    if (theResolution < 0)\n      throw Fmi::Exception(BCP, \"Resolution must be nonnegative!\");\n\n    if (theResolution < 0.01)\n    {\n      if (theResolution > 0)\n        throw Fmi::Exception(BCP, \"Resolutions below 10 meters are not supported!\");\n\n      if (theLocationCache.NX() > 0)\n        throw Fmi::Exception(BCP, \"Nonzero resolution must be given with locations!\");\n    }\n\n    const NFmiGrid &nativeGrid = grid();\n\n    if (theLocationCache.NX() > 0)\n    {\n      // Load dem values and waterflags for given locations (target grid)\n      //\n      bool intersectsGrid = false;\n      int nx = theLocationCache.NX();\n      int ny = theLocationCache.NY();\n\n      theDemMatrix.Resize(nx, ny);\n      theWaterFlagMatrix.Resize(nx, ny);\n\n      for (int i = 0; (i < nx); i++)\n        for (int j = 0; (j < ny); j++)\n        {\n          auto const &loc = theLocationCache[i][j];\n\n          if (loc.itsLocationIndex != static_cast<unsigned long>(-1))\n          {\n            auto latLon = nativeGrid.GridToLatLon(loc.itsGridPoint);\n            auto dem = theDem.elevation(latLon.X(), latLon.Y(), theResolution);\n\n            theDemMatrix[i][j] = dem;\n            theWaterFlagMatrix[i][j] =\n                ((dem == 0) ||\n                 Fmi::LandCover::isOpenWater(theLandCover.coverType(latLon.X(), latLon.Y())));\n\n            intersectsGrid = true;\n          }\n          else\n          {\n            theDemMatrix[i][j] = kFloatMissing;\n            theWaterFlagMatrix[i][j] = false;\n          }\n        }\n\n      return intersectsGrid;\n    }\n\n    // Load dem values and waterflags for native grid points.\n    //\n    // When cropping, extend the subgrid dimensions by 1 if possible to be get values for the last\n    // column and row\n    // (landscaping requires neighbour gridpoints to be available)\n\n    int nativeGridSizeX = nativeGrid.XNumber();\n    int nativeGridSizeY = nativeGrid.YNumber();\n    int nx;\n    int ny;\n\n    if ((x1 != 0) || (y1 != 0) || (x2 != 0) || (y2 != 0))\n    {\n      if (!((x1 >= 0) && (x1 < x2) && (y1 >= 0) && (y1 < y2) && (x2 < nativeGridSizeX) &&\n            (y2 < nativeGridSizeY)))\n        throw Fmi::Exception(BCP, \"Cropping is invalid or outside the grid!\");\n\n      if (x2 < (nativeGridSizeX - 1))\n        x2++;\n      if (y2 < (nativeGridSizeY - 1))\n        y2++;\n\n      nx = x2 - x1 + 1;\n      ny = y2 - y1 + 1;\n    }\n    else\n    {\n      nx = nativeGridSizeX;\n      x1 = 0, x2 = nativeGridSizeX - 1;\n      ny = nativeGridSizeY;\n      y1 = 0;\n      y2 = nativeGridSizeY - 1;\n    }\n\n    // Default resolution is the grid resolution\n\n    if (theResolution == 0)\n      theResolution = (nativeGrid.Area()->WorldXYWidth() / nativeGridSizeX) / 1000;\n\n    theDemMatrix.Resize(nx, ny);\n    theWaterFlagMatrix.Resize(nx, ny);\n\n    for (int i = x1, i0 = 0; (i <= x2); i++, i0++)\n      for (int j = y1, j0 = 0; (j <= y2); j++, j0++)\n      {\n        auto latLon = nativeGrid.GridToLatLon(i, j);\n        auto dem = theDem.elevation(latLon.X(), latLon.Y(), theResolution);\n\n        theDemMatrix[i0][j0] = dem;\n        theWaterFlagMatrix[i0][j0] =\n            ((dem == 0) ||\n             Fmi::LandCover::isOpenWater(theLandCover.coverType(latLon.X(), latLon.Y())));\n      }\n\n    return true;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Sample the data to create a new Q object\n */\n// ----------------------------------------------------------------------\n\nQ QImpl::sample(const Spine::Parameter &theParameter,\n                const boost::posix_time::ptime &theTime,\n                const Fmi::SpatialReference &theCrs,\n                double theXmin,\n                double theYmin,\n                double theXmax,\n                double theYmax,\n                double theResolution,\n                const Fmi::DEM &theDem,\n                const Fmi::LandCover &theLandCover)\n{\n  try\n  {\n    if (!param(theParameter.number()))\n      throw Fmi::Exception(\n          BCP,\n          \"Parameter \" + theParameter.name() + \" is not available for sampling in the querydata\");\n\n    if (theResolution <= 0)\n      throw Fmi::Exception(BCP, \"The sampling resolution must be nonnegative\");\n\n    if (theResolution < 0.01)\n      throw Fmi::Exception(BCP, \"Sampling resolutions below 10 meters are not supported\");\n\n    if (!itsInfo->TimeDescriptor().IsInside(theTime))\n      throw Fmi::Exception(BCP, \"Cannot sample data to a time outside the querydata\");\n\n    if (!itsInfo->IsGrid())\n      throw Fmi::Exception(BCP, \"Cannot sample point data to new resolution\");\n\n    // Establish the new descriptors\n\n    NFmiVPlaceDescriptor vdesc(itsInfo->VPlaceDescriptor());\n\n    NFmiParamBag pbag;\n    pbag.Add(itsInfo->Param());\n    NFmiParamDescriptor pdesc(pbag);\n\n    NFmiTimeList tlist;\n    tlist.Add(new NFmiMetTime(theTime));  // NOLINT(cppcoreguidelines-owning-memory)\n    NFmiTimeDescriptor tdesc(itsInfo->OriginTime(), tlist);\n\n    // Establish new projection and the required grid size of the desired resolution\n\n#ifdef WGS84\n    std::shared_ptr<NFmiArea> newarea(\n        NFmiArea::CreateFromBBox(theCrs, NFmiPoint(theXmin, theYmin), NFmiPoint(theXmax, theYmax)));\n#else\n    auto newarea =\n        std::make_shared<NFmiGdalArea>(\"FMI\", theCrs, theXmin, theYmin, theXmax, theYmax);\n#endif\n\n    double datawidth = newarea->WorldXYWidth() / 1000.0;  // view extent in kilometers\n    double dataheight = newarea->WorldXYHeight() / 1000.0;\n    int width = static_cast<int>(datawidth / theResolution);\n    int height = static_cast<int>(dataheight / theResolution);\n\n    // Must use at least two grid points, value 1 would cause a segmentation fault in here\n    width = std::max(width, 2);\n    height = std::max(height, 2);\n\n    NFmiGrid grid(newarea.get(), width, height);\n    NFmiHPlaceDescriptor hdesc(grid);\n\n    // Then create the new querydata\n\n    NFmiFastQueryInfo info(pdesc, tdesc, hdesc, vdesc);\n    boost::shared_ptr<NFmiQueryData> data(NFmiQueryDataUtil::CreateEmptyData(info));\n    if (data.get() == nullptr)\n      throw Fmi::Exception(BCP, \"Failed to create querydata by sampling\");\n\n    NFmiFastQueryInfo dstinfo(data.get());\n    dstinfo.First();  // sets the only param and time active\n\n    if ((itsModels[0]->levelName() == \"surface\") &&\n        (theParameter.type() == Spine::Parameter::Type::Landscaped))\n    {\n      // Landscaping; temperature or dewpoint\n      //\n      NFmiDataMatrix<NFmiLocationCache> locCache;\n      NFmiTimeCache timeCache = itsInfo->CalcTimeCache(NFmiMetTime(theTime));\n      NFmiDataMatrix<float> valueMatrix;\n      NFmiDataMatrix<float> demMatrix;\n      NFmiDataMatrix<bool> waterFlagMatrix;\n\n      calcLatlonCachePoints(dstinfo, locCache);\n\n      if (loadDEMAndWaterFlags(\n              theDem, theLandCover, theResolution, locCache, demMatrix, waterFlagMatrix))\n        valueMatrix = landscapeCachedInterpolation(locCache, timeCache, demMatrix, waterFlagMatrix);\n      else\n        // Target grid does not intersect the native grid\n        //\n        valueMatrix.Resize(locCache.NX(), locCache.NY(), kFloatMissing);\n\n      int nx = valueMatrix.NX();\n      int n;\n\n      for (dstinfo.ResetLocation(), n = 0; dstinfo.NextLocation(); n++)\n      {\n        int i = n % nx;\n        int j = n / nx;\n\n        dstinfo.FloatValue(valueMatrix[i][j]);\n      }\n    }\n    else\n    {\n      // Now we need all kinds of extra variables because of the damned API\n\n      NFmiPoint dummy;\n      boost::shared_ptr<Fmi::TimeFormatter> timeformatter(Fmi::TimeFormatter::create(\"iso\"));\n      boost::local_time::time_zone_ptr utc(new boost::local_time::posix_time_zone(\"UTC\"));\n      boost::local_time::local_date_time localdatetime(theTime, utc);\n\t  SmartMet::Spine::TimeSeries::LocalTimePoolPtr localTimePool = nullptr;\n\n      auto mylocale = std::locale::classic();\n\n      for (dstinfo.ResetLevel(); dstinfo.NextLevel();)\n      {\n        itsInfo->Level(*dstinfo.Level());\n        for (dstinfo.ResetLocation(); dstinfo.NextLocation();)\n        {\n          auto latlon = dstinfo.LatLon();\n\n          if (theParameter.name() == \"dem\")\n            dstinfo.FloatValue(theDem.elevation(latlon.X(), latlon.Y(), theResolution));\n          else if (theParameter.name() == \"covertype\")\n            dstinfo.FloatValue(theLandCover.coverType(latlon.X(), latlon.Y()));\n          else\n          {\n            Spine::Location loc(latlon.X(), latlon.Y());\n\n            ParameterOptions options(theParameter,\n                                     Producer(),\n                                     loc,\n                                     \"\",\n                                     \"\",\n                                     *timeformatter,\n                                     \"\",\n                                     \"\",\n                                     mylocale,\n                                     \"\",\n                                     false,\n                                     NFmiPoint(),\n                                     dummy,\n\t\t\t\t\t\t\t\t\t localTimePool);\n\n            auto result = value(options, localdatetime);\n            if (boost::get<double>(&result) != nullptr)\n              dstinfo.FloatValue(*boost::get<double>(&result));\n          }\n        }\n      }\n    }\n\n    // Return the new Q but with a new hash value\n\n    std::size_t hash = itsHashValue;\n    Fmi::hash_combine(hash, Fmi::hash_value(theResolution));\n    Fmi::hash_combine(hash, Fmi::hash_value(theTime));\n    Fmi::hash_combine(hash, Fmi::hash_value(theXmin));\n    Fmi::hash_combine(hash, Fmi::hash_value(theYmin));\n    Fmi::hash_combine(hash, Fmi::hash_value(theXmax));\n    Fmi::hash_combine(hash, Fmi::hash_value(theYmax));\n    Fmi::hash_combine(hash, theCrs.hashValue());\n\n    auto model = boost::make_shared<Model>(*itsModels[0], data, hash);\n    return boost::make_shared<QImpl>(model);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nbool QImpl::selectLevel(double theLevel)\n{\n  try\n  {\n    this->resetLevel();\n    while (this->nextLevel())\n    {\n      if (this->levelValue() == theLevel)\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 Return the data hash value\n */\n// ----------------------------------------------------------------------\n\nstd::size_t QImpl::hashValue() const\n{\n  return itsHashValue;\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return the grid hash value\n *\n * Note: All models are required to have the same grid\n */\n// ----------------------------------------------------------------------\n\nstd::size_t QImpl::gridHashValue() const\n{\n  return itsModels.front()->gridHashValue();\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return true if the data looks global but lacks one grid cell column\n */\n// ----------------------------------------------------------------------\n\nbool QImpl::needsGlobeWrap() const\n{\n  return itsInfo->NeedsGlobeWrap();\n}\n\n}  // namespace Querydata\n}  // namespace Engine\n}  // namespace SmartMet\n", "meta": {"hexsha": "467dfa42a0b484014eb11386e603189ff1a9427e", "size": 125881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "querydata/Q.cpp", "max_stars_repo_name": "fmidev/smartmet-engine-querydata", "max_stars_repo_head_hexsha": "dc4731ea7cc8ad1e0f673030ad9fe77481cb4f51", "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": "querydata/Q.cpp", "max_issues_repo_name": "fmidev/smartmet-engine-querydata", "max_issues_repo_head_hexsha": "dc4731ea7cc8ad1e0f673030ad9fe77481cb4f51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "querydata/Q.cpp", "max_forks_repo_name": "fmidev/smartmet-engine-querydata", "max_forks_repo_head_hexsha": "dc4731ea7cc8ad1e0f673030ad9fe77481cb4f51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-15T09:06:45.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-15T09:06:45.000Z", "avg_line_length": 28.1675990154, "max_line_length": 100, "alphanum_fraction": 0.502959144, "num_tokens": 28835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.26894142136999516, "lm_q1q2_score": 0.15325697811346176}}
{"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#ifndef QCTOOL_Genotype_FREQUENCY_TEST_CALL_COMPARER_HPP\n#define QCTOOL_Genotype_FREQUENCY_TEST_CALL_COMPARER_HPP\n\n#include <string>\n#include <map>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/function.hpp>\n#include \"genfile/SingleSNPGenotypeProbabilities.hpp\"\n#include \"PairwiseCallComparer.hpp\"\n\nstruct GenotypeFrequencyTestCallComparer: public PairwiseCallComparer {\n\n\tGenotypeFrequencyTestCallComparer() ;\n\n\tvoid compare(\n\t\tEigen::MatrixXd const& left,\n\t\tEigen::MatrixXd const& right,\n\t\tCallback\n\t) const ;\n\t\nprivate:\n\tdouble m_threshhold ;\n\tboost::math::chi_squared_distribution< double > m_chi_squared ;\t\n} ;\n\n#endif\n", "meta": {"hexsha": "90c6001b8642199400292a9bc343f6e2dd0c754c", "size": 862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/include/components/SNPSummaryComponent/GenotypeFrequencyTestCallComparer.hpp", "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/SNPSummaryComponent/include/components/SNPSummaryComponent/GenotypeFrequencyTestCallComparer.hpp", "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/SNPSummaryComponent/include/components/SNPSummaryComponent/GenotypeFrequencyTestCallComparer.hpp", "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": 26.1212121212, "max_line_length": 71, "alphanum_fraction": 0.7737819026, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.15320848246908783}}
{"text": "/*\n* Copyright (C) 2017 Incognito (Edited by ProMetheus)\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 <streamer/config.hpp>\n#include \"../natives.h\"\n\n#include \"../core.h\"\n#include \"../utility.h\"\n\n#include <streamer/text-labels.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/intrusive_ptr.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/unordered_set.hpp>\n\n#include <Eigen/Core>\n\n#include <string>\n\nSTREAMER_BEGIN_NS\n\nint CreateDynamic3DTextLabel(std::string text, int color, float x, float y, float z, float drawDistance, int attachedPlayer, int attachedVehicle, bool testlos, int worldid, int interiorid, int playerid, float streamDistance, int areaid, int priority) {\n\tif (core->getData()->getGlobalMaxItems(STREAMER_TYPE_3D_TEXT_LABEL) == core->getData()->textLabels.size()) {\n\t\treturn 0;\n\t}\n\tint textLabelId = Item::TextLabel::identifier.get();\n\tItem::SharedTextLabel textLabel(new Item::TextLabel);\n\t//textLabel->amx = amx;\n\ttextLabel->textLabelId = textLabelId;\n\ttextLabel->inverseAreaChecking = false;\n\ttextLabel->originalComparableStreamDistance = -1.0f;\n\ttextLabel->positionOffset = Eigen::Vector3f::Zero();\n\ttextLabel->streamCallbacks = false;\n\ttextLabel->text = text;\n\ttextLabel->color = color;\n\ttextLabel->position = Eigen::Vector3f(x, y, z);\n\ttextLabel->drawDistance = drawDistance;\n\tif (attachedPlayer != INVALID_OBJECT_ID || attachedVehicle != INVALID_OBJECT_ID) {\n\t\ttextLabel->attach = boost::intrusive_ptr<Item::TextLabel::Attach>(new Item::TextLabel::Attach);\n\t\ttextLabel->attach->player = attachedPlayer;\n\t\ttextLabel->attach->vehicle = attachedVehicle;\n\t\tif (textLabel->position.cwiseAbs().maxCoeff() > 50.0f) {\n\t\t\ttextLabel->position.setZero();\n\t\t}\n\t\tcore->getStreamer()->attachedTextLabels.insert(textLabel);\n\t}\n\ttextLabel->testLOS = testlos;\n\tUtility::addToContainer(textLabel->worlds, worldid);\n\tUtility::addToContainer(textLabel->interiors, interiorid);\n\tUtility::addToContainer(textLabel->players, playerid);\n\ttextLabel->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;\n\ttextLabel->streamDistance = streamDistance;\n\tUtility::addToContainer(textLabel->areas, areaid);\n\ttextLabel->priority = priority;\n\tcore->getGrid()->addTextLabel(textLabel);\n\tcore->getData()->textLabels.insert(std::make_pair(textLabelId, textLabel));\n\treturn textLabelId;\n}\n\nint DestroyDynamic3DTextLabel(int id) {\n\tboost::unordered_map<int, Item::SharedTextLabel>::iterator t = core->getData()->textLabels.find(id);\n\tif (t != core->getData()->textLabels.end()) {\n\t\tUtility::destroyTextLabel(t);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint IsValidDynamic3DTextLabel(int id) {\n\tboost::unordered_map<int, Item::SharedTextLabel>::iterator t = core->getData()->textLabels.find(id);\n\tif (t != core->getData()->textLabels.end()) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstd::string GetDynamic3DTextLabelText(int id) {\n\tboost::unordered_map<int, Item::SharedTextLabel>::iterator t = core->getData()->textLabels.find(id);\n\tif (t != core->getData()->textLabels.end()) {\n\t\treturn t->second->text;\n\t}\n\treturn \"\";\n}\n\nint UpdateDynamic3DTextLabelText(int label, int color, std::string text) {\n\tboost::unordered_map<int, Item::SharedTextLabel>::iterator t = core->getData()->textLabels.find(label);\n\tif (t != core->getData()->textLabels.end()) {\n\t\tt->second->color = color;\n\t\tt->second->text = text;\n\t\tfor (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p)\n\t\t{\n\t\t\tboost::unordered_map<int, int>::iterator i = p->second.internalTextLabels.find(t->first);\n\t\t\tif (i != p->second.internalTextLabels.end())\n\t\t\t{\n\t\t\t\tsampgdk::UpdatePlayer3DTextLabelText(p->first, i->second, t->second->color, t->second->text.c_str());\n\t\t\t}\n\t\t}\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nSTREAMER_END_NS", "meta": {"hexsha": "256eaee36afa641fba820a2ab416ae9f0c9dcf46", "size": 4387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/implements/text-labels_impl.cpp", "max_stars_repo_name": "philip1337/samp-plugin-streamer", "max_stars_repo_head_hexsha": "54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T23:27:03.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-24T06:18:13.000Z", "max_issues_repo_path": "src/implements/text-labels_impl.cpp", "max_issues_repo_name": "Sphinxila/samp-plugin-streamer", "max_issues_repo_head_hexsha": "54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a", "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/implements/text-labels_impl.cpp", "max_forks_repo_name": "Sphinxila/samp-plugin-streamer", "max_forks_repo_head_hexsha": "54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a", "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.1779661017, "max_line_length": 252, "alphanum_fraction": 0.736038295, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.15320847611364036}}
{"text": "#include <k52/optimization/bounded_nelder_mead.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/common/constants.h>\n\nusing ::std::vector;\nusing ::k52::common::Constants;\n\nnamespace k52\n{\nnamespace optimization\n{\n\nBoundedNelderMead::BoundedNelderMead(double l, double precision, double lower_bound, double upper_bound)\n{\n    lower_bound_ = lower_bound;\n    upper_bound_ = upper_bound;\n    precision_ = precision;\n    l_ = l;\n}\n\nBoundedNelderMead* BoundedNelderMead::Clone() const\n{\n    return new BoundedNelderMead(l_, precision_, lower_bound_, upper_bound_);\n}\n\nstd::string BoundedNelderMead::get_name() const\n{\n    return \"Bounded Nelder Mead\";\n}\n\ndouble BoundedNelderMead::get_lower_bound() const\n{\n    return lower_bound_;\n}\n\ndouble BoundedNelderMead::get_upper_bound() const\n{\n    return upper_bound_;\n}\n\n#ifdef BUILD_WITH_MPI\nvoid BoundedNelderMead::Send(boost::mpi::communicator* communicator, int target) const\n{\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, l_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, precision_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, lower_bound_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, upper_bound_);\n}\n\nvoid BoundedNelderMead::Receive(boost::mpi::communicator* communicator, int source)\n{\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, l_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, precision_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, lower_bound_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, upper_bound_);\n}\n#endif\n\nstd::vector<double> BoundedNelderMead::FindOptimalParameters(const std::vector<double>& initial_parameters)\n{\n    //Iteration index\n    size_t r = 0;\n\n    //Build simplex based on initial_parameters\n    vector< vector<double> > polygon = GetRegularSimplex(initial_parameters, l_);\n\n    //count values\n    vector<double> function_values = CountObjectiveFunctionValues(polygon);\n\n    do\n    {\n        OutputPolygon(polygon);\n        r++;\n\n        size_t first_max_index = 0, second_max_index = 0, min_index = 0;\n        //determine maximums and minimum\n        GetIndexes(function_values, &first_max_index, &second_max_index, &min_index);\n\n        double highest_value = function_values[first_max_index];\n        double second_highest_value = function_values[second_max_index];\n        double lowest_value = function_values[min_index];\n\n        //determine center of mass\n        vector<double> center_of_mass = GetCenterOfMass(polygon, first_max_index);\n\n        //Reflect max point - we seek for minimum\n        vector<double> reflected_point = Reflexion(center_of_mass, polygon[first_max_index]);\n        CorrectByProjectingToBounds(&reflected_point);\n        double reflected_point_value = CountSingleObjectiveFunctionValue(reflected_point);\n\n        if (reflected_point_value < lowest_value)\n        {\n            vector<double> expanded_point = Expansion(center_of_mass, reflected_point);\n            CorrectByProjectingToBounds(&expanded_point);\n            double expanded_point_value = CountSingleObjectiveFunctionValue(expanded_point);\n\n            if (expanded_point_value < reflected_point_value)\n            {\n                //Replace max with expanded\n                polygon[first_max_index] = expanded_point;\n                function_values[first_max_index] = expanded_point_value;\n                continue;\n            }\n            else\n            {\n                //Replace max with reflected\n                polygon[first_max_index] = reflected_point;\n                function_values[first_max_index] = reflected_point_value;\n                continue;\n            }\n        }\n        else\n        {\n            if (reflected_point_value <= second_highest_value)\n            {\n                //Replace max with reflected\n                polygon[first_max_index] = reflected_point;\n                function_values[first_max_index] = reflected_point_value;\n                continue;\n            }\n            else\n            {\n                if (reflected_point_value < highest_value)\n                {\n                    //Replace max with reflected\n                    polygon[first_max_index] = reflected_point;\n                    function_values[first_max_index] = reflected_point_value;\n                    highest_value = reflected_point_value;\n                }\n\n                vector<double> contraction_point = Contraction(center_of_mass, polygon[first_max_index]);\n                double contraction_point_value = CountSingleObjectiveFunctionValue(contraction_point);\n\n                if (contraction_point_value > highest_value)\n                {\n                    Reduction(&polygon, min_index);\n                    continue;\n                }\n                else\n                {\n                    //Replace max with contracted\n                    polygon[first_max_index] = contraction_point;\n                    function_values[first_max_index] = contraction_point_value;\n                    continue;\n                }\n            }\n        }\n    } while (GetTerminationCriteria(r, function_values, polygon));\n\n\n    size_t best_index = std::distance(function_values.begin(), std::max_element(function_values.begin(), function_values.end()));\n    return polygon[best_index];\n}\n\nvoid BoundedNelderMead::CorrectByProjectingToBounds(vector<double>* point)\n{\n    for(size_t i = 0; i < point->size(); i++)\n    {\n        if( (*point)[i] > upper_bound_)\n        {\n            (*point)[i] = upper_bound_;\n        }\n        else if( (*point)[i] < lower_bound_)\n        {\n            (*point)[i] = lower_bound_;\n        }\n    }\n}\n\nvector<double> BoundedNelderMead::CountObjectiveFunctionValues(\n    const vector< vector<double> >& parameters_values)\n{\n    size_t N = parameters_values.size();\n    vector<double> counted_values(N);\n\n    for(size_t i = 0; i < N; i++)\n    {\n        //As Nelder-Mead tends to minimize function we need to reverse it to find max\n        counted_values[i] = CountObjectiveFunctionValueToMinimize(parameters_values[i]);\n    }\n\n    return counted_values;\n}\n\ndouble BoundedNelderMead::CountSingleObjectiveFunctionValue(\n    const vector<double>& parameters)\n{\n    vector< vector<double> > cover(1);\n    cover[0] = parameters;\n    return CountObjectiveFunctionValues(cover)[0];\n}\n\nbool BoundedNelderMead::GetTerminationCriteria(\n        size_t itreation_index,\n        const std::vector<double>& function_values,\n        const std::vector< std::vector<double> >& polygon)\n{\n    const size_t iterations_per_dimension = 1000;\n    if (itreation_index > iterations_per_dimension * polygon[0].size())\n    {\n        std::cout << \"WARNING: Exiting BDNM by iterations\"\n                \" criteria!\" << std::endl;\n        return false;\n    }\n\n    if (WasSamePolygonBefore(polygon))\n    {\n        std::cout << \"WARNING: Exiting BDNM because of a polygon loop,\"\n                \" you migth have a special function behaviour.\" << std::endl;\n        return false;\n    }\n\n    return CountDifferance(function_values) > precision_;\n}\n\nbool BoundedNelderMead::WasSamePolygonBefore(const std::vector< std::vector<double> >& polygon)\n{\n    bool was_same_before = false;\n\n    for (std::list< std::vector< std::vector<double> > >::const_iterator it = previous_polygons_.begin();\n         it != previous_polygons_.end();\n         ++it)\n    {\n        if (CountPolygonDifferance(polygon, *it) < Constants::Eps)\n        {\n            was_same_before = true;\n            break;\n        }\n    }\n\n    if (previous_polygons_.size() >= max_previous_polygons_count)\n    {\n        previous_polygons_.pop_front();\n    }\n    previous_polygons_.push_back(polygon);\n\n    return was_same_before;\n}\n\nvoid BoundedNelderMead::GetIndexes(const vector<double>& values, size_t* first_max_index, size_t* secound_max_index, size_t* min_index)\n{\n    if(values.size() < 2)\n    {\n        throw std::invalid_argument(\"values must have at least 2 elements\");\n    }\n\n    if( values[0] > values[1] )\n    {\n        *first_max_index = 0;\n        *secound_max_index = 1;\n        *min_index = 1;\n    }\n    else\n    {\n        *first_max_index = 1;\n        *secound_max_index = 0;\n        *min_index = 0;\n    }\n\n    for (size_t i = 2; i<values.size(); i++) \n    {\n        if (values[i] > values[*first_max_index]) \n        {\n            *secound_max_index = *first_max_index;\n            *first_max_index = i;\n        } \n        else if (values[i]  > values[*secound_max_index]) \n        {\n            *secound_max_index = i;\n        }\n\n        if( values[i] < values[*min_index])\n        {\n            *min_index = i;\n        }\n    }\n}\n\nvector< vector<double> > BoundedNelderMead::GetRegularSimplex(const vector<double>& base_point, double l)\n{\n    //Size of task\n    size_t n = base_point.size();\n\n    //For simplex points count\n    double square_root_from_2 = std::sqrt(2.);\n    double r1 = l * ( std::sqrt((double)(n+1)) + n - 1 ) / ( n * square_root_from_2 );\n    double r2 = l * ( std::sqrt((double)(n+1)) - 1 ) / ( n * square_root_from_2 );\n\n    vector< vector<double> > regular_simplex( n + 1 );\n    regular_simplex[0] = base_point;\n\n    for(size_t i = 1; i < n + 1; i++)\n    {\n        regular_simplex[i] = vector<double>(n);\n\n        for(size_t j = 0; j < n; j++)\n        {\n            if( j == i - 1 )\n            {\n                regular_simplex[i][j] = base_point[j] + r1;\n            }\n            else\n            {\n                regular_simplex[i][j] = base_point[j] + r2;\n            }\n        }\n    }\n    return regular_simplex;\n}\n\nvector<double> BoundedNelderMead::Reflexion(const vector<double>& center_of_mass, const vector<double>& target_point)\n{\n    double reflection_coefficient = 1;\n    vector<double> new_point (target_point.size());\n\n    //Reflect\n    for(size_t i = 0; i < target_point.size(); i++)\n    {\n        new_point[i] = center_of_mass[i] + reflection_coefficient * (center_of_mass[i] - target_point[i]);\n    }\n\n    return new_point;\n}\n\nvector<double> BoundedNelderMead::Expansion(const vector<double>& center_of_mass, const vector<double>& target_point)\n{\n    double expansion_coefficient = 2;\n    vector<double> new_point (target_point.size());\n\n    //Expand\n    for(size_t i = 0; i < target_point.size(); i++)\n    {\n        new_point[i] = center_of_mass[i] + expansion_coefficient * (target_point[i] - center_of_mass[i]);\n    }\n\n    return new_point;\n}\n\nvector<double> BoundedNelderMead::Contraction(const vector<double>& center_of_mass, const vector<double>& target_point)\n{\n    double contraction_coefficient = 0.5;\n    vector<double> new_point (target_point.size());\n\n    //Contract\n    for(size_t i = 0; i < target_point.size(); i++)\n    {\n        new_point[i] = center_of_mass[i] + contraction_coefficient * (target_point[i] - center_of_mass[i]);\n    }\n\n    return new_point;\n}\n\nvoid BoundedNelderMead::Reduction(vector< vector<double> >* polygon, size_t point_index)\n{\n    if(point_index >= polygon->size())\n    {\n        throw std::invalid_argument(\"Incorrect point_index\");\n    }\n\n    double reduction_coefficient = 0.5;\n    size_t n = (*polygon)[0].size();\n\n    for(size_t i = 0; i < n +1; i++)\n    {\n        if( i != point_index )\n        {\n            for(size_t j = 0; j < n; j++)\n            {\n                (*polygon)[i][j] = (*polygon)[point_index][j] + reduction_coefficient *\n                        ((*polygon)[i][j]  - (*polygon)[point_index][j]);\n            }\n        }\n    }\n}\n\ndouble BoundedNelderMead::CountDifferance(const vector<double>& values)\n{\n    double summ = 0;\n    for(size_t i = 0; i < values.size(); i++)\n    {\n        summ += values[i];\n    }\n    double averadge = summ / values.size();\n\n    double square_summ = 0;\n    for(size_t i = 0; i < values.size(); i++)\n    {\n        double diff = values[i] - averadge;\n        square_summ += diff*diff;\n    }\n    return sqrt( square_summ / values.size());\n}\n\ndouble BoundedNelderMead::CountPolygonDifferance(\n        const std::vector< std::vector<double> >& polygon,\n        const std::vector< std::vector<double> >& previous_polygon)\n{\n    double summ = 0;\n    for(size_t i = 0; i < polygon.size(); i++)\n    {\n        for(size_t j = 0; j < polygon[i].size(); j++)\n        {\n            summ += std::abs(polygon[i][j] - previous_polygon[i][j]);\n        }\n    }\n    return summ;\n}\n\nvector<double> BoundedNelderMead::GetCenterOfMass(const vector< vector<double> >& polygon, size_t point_index)\n{\n    if(point_index>= polygon.size())\n    {\n        throw std::invalid_argument(\"Incorrect point_index\");\n    }\n\n    size_t n = polygon[0].size();\n    vector<double> center_of_mass(n);\n\n    //TODO implement with valarray\n    for(size_t i = 0; i < n; i++)\n    {\n        center_of_mass[i] = 0;\n\n        for(size_t j = 0; j < n+1; j++)\n        {\n            if( j != point_index )\n            {\n                center_of_mass[i] += polygon[j][i];\n            }\n        }\n\n        center_of_mass[i] /= n;\n    }\n\n    return center_of_mass;\n}\n\nvoid BoundedNelderMead::OutputPolygon(const vector< vector<double> >& polygon)\n{\n    std::ofstream polygon_output(\"polygon.plot\", std::ofstream::app);\n    polygon_output.precision(16);\n    polygon_output<<std::endl;\n\n    for(size_t i = 0; i < polygon.size(); i++)\n    {\n        for(size_t j = 0; j < polygon[i].size(); j++)\n        {\n            polygon_output << polygon[i][j] << \" \";\n        }\n        polygon_output<<std::endl;\n    }\n}\n\n}/* namespace optimization */\n}/* namespace k52 */\n", "meta": {"hexsha": "b49c05bf76c2b5676b1bcbb72a06362a88f8fedf", "size": 13719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization/bounded_nelder_mead.cpp", "max_stars_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_stars_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "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/bounded_nelder_mead.cpp", "max_issues_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_issues_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "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/bounded_nelder_mead.cpp", "max_forks_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_forks_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "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": 29.2515991471, "max_line_length": 135, "alphanum_fraction": 0.6151322983, "num_tokens": 3290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.1532084761136403}}
{"text": "/**\n * Copyright 2004-present Facebook. All Rights Reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nconst char* kUsage = R\"(\n  - Reads a point cloud as an ASCII file with a single point per line and generates a disparity\n  image per camera.\n\n  Supports multiple point cloud formats, but only extracts the xyz coordinates.\n\n  The input file can have a single line header with a point count.\n\n  - Example:\n    ./ImportPointCloud \\\n    --output=/path/to/output \\\n    --rig=/path/to/rigs/rig.json \\\n    --point_cloud=/path/to/points.xyz\n\n    Where points.xyz may be of the form:\n\n    10000\n    -0.04503071680665016 -2.2521071434020996 4.965743541717529 1 90 104 136\n    -0.005194493103772402 -2.323836088180542 4.938142776489258 1 94 110 143\n    0.046292994171381 -2.2623345851898193 4.609960079193115 1 101 122 149\n    ...\n)\";\n\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <boost/format.hpp>\n#include \"source/conversion/PointCloudUtil.h\"\n#include \"source/util/Camera.h\"\n#include \"source/util/ImageUtil.h\"\n#include \"source/util/SystemUtil.h\"\n#include \"source/util/ThreadPool.h\"\n\nusing namespace fb360_dep;\nusing namespace fb360_dep::image_util;\nusing namespace fb360_dep::point_cloud_util;\n\nDEFINE_string(cameras, \"\", \"comma-separated cameras to render (empty for all)\");\nDEFINE_double(max_depth, INFINITY, \"ignore depths farther than this value (m)\");\nDEFINE_double(min_depth, 0, \"ignore depths closer than this value (m)\");\nDEFINE_string(output, \"\", \"output directory (required)\");\nDEFINE_string(point_cloud, \"\", \"input point cloud (required)\");\nDEFINE_string(rig, \"\", \"path to camera rig .json (required)\");\nDEFINE_int32(threads, -1, \"number of threads (-1 = auto, 0 = none)\");\nDEFINE_int32(width, 1024, \"width of output camera images (0 = size from rig file)\");\n\nvoid verifyInputs(const Camera::Rig& rig) {\n  CHECK_NE(FLAGS_point_cloud, \"\");\n  CHECK_NE(FLAGS_output, \"\");\n  CHECK_GE(FLAGS_width, 0);\n  CHECK_EQ(FLAGS_width % 2, 0) << \"width must be a multiple of 2\";\n  CHECK_GT(rig.size(), 0);\n}\n\nvoid rescaleCameras(Camera::Rig& rig) {\n  for (Camera& cam : rig) {\n    if (FLAGS_width > 0) {\n      int height = std::round(FLAGS_width * cam.resolution.y() / float(cam.resolution.x()));\n      height += height % 2; // force even number of rows\n      cam = cam.rescale({FLAGS_width, height});\n\t}\n\n    LOG(INFO) << boost::format(\n        \"%1% output resolution: %2%x%3%\") % cam.id % cam.resolution.x() % cam.resolution.y();\n  }\n}\n\nstd::vector<cv::Mat_<float>> projectPointsToCameras(\n    const PointCloud& points,\n    const Camera::Rig& rig) {\n  LOG(INFO) << \"Projecting points to cameras...\";\n\n  std::vector<cv::Mat_<float>> disparities;\n  for (const Camera& cam : rig) {\n    disparities.emplace_back(cam.resolution.y(), cam.resolution.x(), 0.0f);\n  }\n\n  ThreadPool threadPool(FLAGS_threads);\n  const int threads = threadPool.getMaxThreads();\n\n  // Evenly distribute lines across threads\n  const int pointCount = points.size();\n  const int pointsPerThread = float(pointCount) / threads;\n  const int remain = pointCount % threads;\n\n  for (int i = 0; i < threads; ++i) {\n    threadPool.spawn([&, i] {\n      const int begin =\n          i < remain ? i * (pointsPerThread + 1) : pointCount - (threads - i) * pointsPerThread;\n      const int end = begin + pointsPerThread + (i < remain);\n      for (int j = begin; j < end; ++j) {\n        // Project point to all cameras\n        for (ssize_t i = 0; i < ssize(rig); ++i) {\n          const Camera::Vector3& pWorld = points[j].coords;\n          Camera::Vector2 pSrc;\n          if (!rig[i].sees(pWorld, pSrc)) {\n            continue; // Outside src FOV, ignore\n          }\n          cv::Mat_<float>& disparity = disparities[i];\n          const int xSrc = math_util::clamp(int(std::round(pSrc.x())), 0, disparity.cols - 1);\n          const int ySrc = math_util::clamp(int(std::round(pSrc.y())), 0, disparity.rows - 1);\n          float depth = pWorld.norm();\n          if (depth < FLAGS_min_depth || depth > FLAGS_max_depth) {\n            depth = INFINITY;\n          }\n          disparity(ySrc, xSrc) =\n              std::max(disparity(ySrc, xSrc), 1.0f / depth); // get closest value\n        }\n      }\n    });\n  }\n  threadPool.join();\n\n  return disparities;\n}\n\nvoid saveImages(const std::vector<cv::Mat_<float>>& disparities, const Camera::Rig& rig) {\n  LOG(INFO) << \"Saving images...\";\n  const filesystem::path dirOut = filesystem::path(FLAGS_output);\n  for (ssize_t i = 0; i < ssize(rig); ++i) {\n    const filesystem::path fn = dirOut / rig[i].id / \"000000.png\";\n    filesystem::create_directories(fn.parent_path());\n    cv_util::imwriteExceptionOnFail(fn, cv_util::convertTo<uint16_t>(disparities[i]));\n  }\n}\n\nint main(int argc, char** argv) {\n  gflags::SetUsageMessage(kUsage);\n  system_util::initDep(argc, argv);\n\n  CHECK_NE(FLAGS_rig, \"\");\n  Camera::Rig rig = filterDestinations(Camera::loadRig(FLAGS_rig), FLAGS_cameras);\n\n  verifyInputs(rig);\n  rescaleCameras(rig);\n  const int pointCount = getPointCount(FLAGS_point_cloud);\n  const PointCloud points = extractPoints(FLAGS_point_cloud, pointCount, FLAGS_threads);\n  const std::vector<cv::Mat_<float>> disparities = projectPointsToCameras(points, rig);\n  saveImages(disparities, rig);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "104795fb29f76d138c8a4ae9ef92214ac02a8025", "size": 5321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/conversion/ImportPointCloud.cpp", "max_stars_repo_name": "sparsebase/facebook360_dep", "max_stars_repo_head_hexsha": "1f15adb097652ef460c37435c504eff1b571a25c", "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/conversion/ImportPointCloud.cpp", "max_issues_repo_name": "sparsebase/facebook360_dep", "max_issues_repo_head_hexsha": "1f15adb097652ef460c37435c504eff1b571a25c", "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/conversion/ImportPointCloud.cpp", "max_forks_repo_name": "sparsebase/facebook360_dep", "max_forks_repo_head_hexsha": "1f15adb097652ef460c37435c504eff1b571a25c", "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.711409396, "max_line_length": 96, "alphanum_fraction": 0.6711144522, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.28776781576105315, "lm_q1q2_score": 0.15286496108756356}}
{"text": "#include <StdInc.h>\n\n// TODOs:\n// - texture compression and repacking R/B channels\n// - draco compression enablement\n// - animations\n// - skeletons\n// - material improvements for PBR\n//   - spec conversion\n// - RAGE materials\n// - #map/#typ exporting (text at first)\n\n#ifdef GTA_FIVE\n#include <d3d9.h>\n\n#define RAGE_FORMATS_GAME five\n#define RAGE_FORMATS_GAME_FIVE\n#include <gtaDrawable.h>\n#include <phBound.h>\n#include <fragType.h>\n\n#include \"ToolComponentHelpers.h\"\n\n#include <json.hpp>\n#include <tiny_gltf.h>\n\n#include <boost/filesystem.hpp>\n#include <DirectXMath.h>\n\n#include <ShaderInfo.h>\n\nstatic DirectX::XMFLOAT3 ConvertTranslation(const std::vector<double>& pos)\n{\n\tif (pos.empty())\n\t{\n\t\treturn {\n\t\t\t0.0f, 0.0f, 0.0f\n\t\t};\n\t}\n\n\treturn {\n\t\t-static_cast<float>(pos[0]),\n\t\tstatic_cast<float>(pos[2]),\n\t\tstatic_cast<float>(pos[1])\n\t};\n}\n\nstatic DirectX::XMFLOAT4 ConvertQuaternion(const std::vector<double>& quat)\n{\n\tif (quat.empty())\n\t{\n\t\treturn {\n\t\t\t0.0f, 0.0f, 0.0f, 1.0f\n\t\t};\n\t}\n\n\treturn {\n\t\t-static_cast<float>(quat[0]),\n\t\tstatic_cast<float>(quat[2]), \n\t\tstatic_cast<float>(quat[1]), \n\t\tstatic_cast<float>(quat[3])\n\t};\n}\n\nstatic DirectX::XMFLOAT3 ConvertScale(const std::vector<double>& scale)\n{\n\tif (scale.empty())\n\t{\n\t\treturn {\n\t\t\t1.0f, 1.0f, 1.0f\n\t\t};\n\t}\n\n\treturn {\n\t\tstatic_cast<float>(scale[0]),\n\t\tstatic_cast<float>(scale[2]),\n\t\tstatic_cast<float>(scale[1])\n\t};\n}\n\nstatic DirectX::XMMATRIX ConvertNodeMatrix(const tinygltf::Node& node)\n{\n\tauto translation = ConvertTranslation(node.translation);\n\tauto rotation = ConvertQuaternion(node.rotation);\n\tauto scale = ConvertScale(node.scale);\n\n\tif (!node.matrix.empty())\n\t{\n\t\tDirectX::XMFLOAT4X4 mat;\n\t\tfor (int x = 0; x < 4; x++)\n\t\t{\n\t\t\tfor (int y = 0; y < 4; y++)\n\t\t\t{\n\t\t\t\tmat.m[x][y] = static_cast<float>(node.matrix[(x * 4) + y]);\n\t\t\t}\n\t\t}\n\n\t\t// decompose and run conversion ops\n\t\tDirectX::XMVECTOR scaleVec;\n\t\tDirectX::XMVECTOR rotationVec;\n\t\tDirectX::XMVECTOR translationVec;\n\t\tDirectX::XMMatrixDecompose(&scaleVec, &rotationVec, &translationVec, DirectX::XMLoadFloat4x4(&mat));\n\n\t\tstd::vector<double> scaleD(3);\n\t\tstd::vector<double> rotationD(4);\n\t\tstd::vector<double> translationD(3);\n\n\t\tscaleD[0] = DirectX::XMVectorGetX(scaleVec);\n\t\tscaleD[1] = DirectX::XMVectorGetY(scaleVec);\n\t\tscaleD[2] = DirectX::XMVectorGetZ(scaleVec);\n\n\t\trotationD[0] = DirectX::XMVectorGetX(rotationVec);\n\t\trotationD[1] = DirectX::XMVectorGetY(rotationVec);\n\t\trotationD[2] = DirectX::XMVectorGetZ(rotationVec);\n\t\trotationD[3] = DirectX::XMVectorGetW(rotationVec);\n\n\t\ttranslationD[0] = DirectX::XMVectorGetX(translationVec);\n\t\ttranslationD[1] = DirectX::XMVectorGetY(translationVec);\n\t\ttranslationD[2] = DirectX::XMVectorGetZ(translationVec);\n\n\t\ttranslation = ConvertTranslation(translationD);\n\t\trotation = ConvertQuaternion(rotationD);\n\t\tscale = ConvertScale(scaleD);\n\t}\n\n\treturn DirectX::XMMatrixAffineTransformation(DirectX::XMLoadFloat3(&scale), DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f), DirectX::XMLoadFloat4(&rotation), DirectX::XMLoadFloat3(&translation));\n}\n\ntemplate<typename T>\nstatic bool OutputFile(T&& callback, int fileVersion, const std::wstring& fileName)\n{\n\tauto bm = rage::five::pgStreamManager::BeginPacking();\n\n\tcallback();\n\n\trage::five::pgStreamManager::EndPacking();\n\n\tFILE* f = _wfopen(fileName.c_str(), L\"wb\");\n\n\tif (!f)\n\t{\n\t\tprintf(\"... couldn't open output file for writing.\\n\");\n\t\treturn false;\n\t}\n\n\tsize_t outputSize = 0;\n\n\tbm->Save(fileVersion, [&](const void* d, size_t s)\n\t{\n\t\tfwrite(d, 1, s, f);\n\n\t\toutputSize += s;\n\t});\n\n\twprintf(L\"written %s successfully - compressed size %d\\n\", boost::filesystem::path(fileName).filename().c_str(), outputSize);\n\n\tfclose(f);\n\n\treturn true;\n}\n\nenum class grcDataSize\n{\n\tNothing = 0,\n\tFloat16_2,\n\tFloat,\n\tFloat16_4,\n\tFloat_unk,\n\tFloat2,\n\tFloat3,\n\tFloat4,\n\tUByte4,\n\tColor,\n\tDec3N,\n\tUShort4 = 15\n};\n\nstatic rage::five::grmGeometryQB* ConvertGeometry(const tinygltf::Model& model, const tinygltf::Primitive& geometry, const DirectX::XMMATRIX& scaleMatrix, int boneIdx = -1)\n{\n\tDirectX::XMVECTOR scale;\n\tDirectX::XMVECTOR rotQuat;\n\tDirectX::XMVECTOR trans;\n\tDirectX::XMMatrixDecompose(&scale, &rotQuat, &trans, scaleMatrix);\n\tauto rotMatrix = DirectX::XMMatrixAffineTransformation(DirectX::XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f), DirectX::XMVectorZero(), rotQuat, DirectX::XMVectorZero());\n\n\trage::five::grmGeometryQB* gameGeom = new (false) rage::five::grmGeometryQB();\n\t\n\t// make index buffer\n\t{\n\t\tconst tinygltf::Accessor& accessor = model.accessors[geometry.indices];\n\t\tuint32_t numIndices = accessor.count;\n\n\t\tconst tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView];\n\t\tconst tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];\n\n\t\tstd::vector<uint16_t> indices(numIndices);\n\t\tif (accessor.componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT)\n\t\t{\n\t\t\tmemcpy(&indices[0], (uint16_t*)&buffer.data[bufferView.byteOffset], numIndices * 2);\n\t\t}\n\t\telse if (accessor.componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)\n\t\t{\n\t\t\tuint8_t* start = (uint8_t*)&buffer.data[bufferView.byteOffset];\n\n\t\t\tfor (int i = 0; i < numIndices; i++)\n\t\t\t{\n\t\t\t\tindices[i] = start[i];\n\t\t\t}\n\t\t}\n\t\t\n\t\t// flip?\n\t\t/*for (int i = 0; i < numIndices; i += 3)\n\t\t{\n\t\t\tstd::swap(indices[i + 1], indices[i + 2]);\n\t\t}*/\n\n\t\trage::five::grcIndexBufferD3D* indexBuffer = new (false) rage::five::grcIndexBufferD3D(numIndices, &indices[0]);\n\t\tgameGeom->SetIndexBuffer(indexBuffer);\n\t}\n\n\t{\n\t\trage::five::grcVertexBufferD3D* vertexBuffer = new (false) rage::five::grcVertexBufferD3D();\n\n\t\t// build a fitting (interleaved) FVF\n\t\tuint64_t dataSizes = 0;\n\t\tuint32_t bits = 0;\n\t\tuint32_t vertexSize = 0;\n\t\tuint8_t numFields = 0;\n\n\t\tsize_t count = 0;\n\n\t\tstatic const std::map<std::string, int> attributeRefs = {\n\t\t\t{ \"POSITION\", 0\t},\n\t\t\t{ \"WEIGHTS_0\", 1 },\n\t\t\t{ \"JOINTS_0\", 2 },\n\t\t\t{ \"NORMAL\", 3 },\n\t\t\t{ \"COLOR_0\", 4 },\n\t\t\t{ \"TEXCOORD_0\", 6 },\n\t\t\t{ \"TEXCOORD_1\", 7 },\n\t\t\t{ \"TANGENT\", 14 },\n\t\t};\n\n\t\tstatic const std::map<std::tuple<int, int>, grcDataSize> typeRefs = { \n\t\t\t{ { TINYGLTF_TYPE_VEC4, TINYGLTF_COMPONENT_TYPE_BYTE }, grcDataSize::UByte4 },\n\t\t\t{ { TINYGLTF_TYPE_VEC4, TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE }, grcDataSize::UByte4 },\n\t\t\t{ { TINYGLTF_TYPE_VEC4, TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT }, grcDataSize::UShort4 },\n\t\t\t{ { TINYGLTF_TYPE_SCALAR, TINYGLTF_COMPONENT_TYPE_FLOAT }, grcDataSize::Float },\n\t\t\t{ { TINYGLTF_TYPE_VEC2, TINYGLTF_COMPONENT_TYPE_FLOAT }, grcDataSize::Float2 },\n\t\t\t{ { TINYGLTF_TYPE_VEC3, TINYGLTF_COMPONENT_TYPE_FLOAT }, grcDataSize::Float3 },\n\t\t\t{ { TINYGLTF_TYPE_VEC4, TINYGLTF_COMPONENT_TYPE_FLOAT }, grcDataSize::Float4 },\n\t\t};\n\n\t\tauto increaseSize = [](grcDataSize dataSize, uint32_t& vertexSize)\n\t\t{\n\t\t\tswitch (dataSize)\n\t\t\t{\n\t\t\t\tcase grcDataSize::Float16_2:\n\t\t\t\t\tvertexSize += 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::Float:\n\t\t\t\t\tvertexSize += 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::Float16_4:\n\t\t\t\t\tvertexSize += 8;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::Float_unk:\n\t\t\t\t\tvertexSize += 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::Float2:\n\t\t\t\t\tvertexSize += 8;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::Float3:\n\t\t\t\t\tvertexSize += 12;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::Float4:\n\t\t\t\t\tvertexSize += 16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::UByte4:\n\t\t\t\t\tvertexSize += 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::Color:\n\t\t\t\t\tvertexSize += 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase grcDataSize::Dec3N:\n\t\t\t\t\tvertexSize += 4;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t};\n\n\t\tconst tinygltf::Accessor* accessors[16] = { 0 };\n\n\t\tfor (const auto& entry : geometry.attributes)\n\t\t{\n\t\t\tconst tinygltf::Accessor& accessor = model.accessors[entry.second];\n\t\t\t\n\t\t\tauto attrRefIt = attributeRefs.find(entry.first);\n\n\t\t\tif (attrRefIt == attributeRefs.end())\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tauto typeRefIt = typeRefs.find({ accessor.type, accessor.componentType });\n\n\t\t\tif (typeRefIt == typeRefs.end())\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint fvfIndex = attrRefIt->second;\n\t\t\taccessors[fvfIndex] = &accessor;\n\n\t\t\tgrcDataSize dataSize = typeRefIt->second;\n\t\t\tbits |= (1 << fvfIndex);\n\t\t\tdataSizes |= uint64_t(dataSize) << uint64_t(fvfIndex * 4);\n\n\t\t\tincreaseSize(dataSize, vertexSize);\n\n\t\t\tcount = accessor.count;\n\t\t\tnumFields++;\n\t\t}\n\n\t\t// no color?\n\t\tif (!(bits & (1 << 4)))\n\t\t{\n\t\t\tbits |= (1 << 4);\n\t\t\tdataSizes |= uint64_t(grcDataSize::Color) << uint64_t(4 * 4);\n\t\t\tvertexSize += 4;\n\t\t}\n\n\t\t// no texcoord0?\n\t\tif (!(bits & (1 << 6)))\n\t\t{\n\t\t\tbits |= (1 << 6);\n\t\t\tdataSizes |= uint64_t(grcDataSize::Float2) << uint64_t(6 * 4);\n\t\t\tvertexSize += 8;\n\t\t}\n\n\t\t// no blend weights (for complex hierarchy)?\n\t\tif (!bits & (1 << 1))\n\t\t{\n\t\t\tbits |= (1 << 1);\n\t\t\tdataSizes |= uint64_t(grcDataSize::UByte4) << uint64_t(1 * 4);\n\t\t\tvertexSize += 4;\n\t\t}\n\n\t\tif (!bits & (1 << 2))\n\t\t{\n\t\t\tbits |= (1 << 2);\n\t\t\tdataSizes |= uint64_t(grcDataSize::UByte4) << uint64_t(2 * 4);\n\t\t\tvertexSize += 4;\n\t\t}\n\n\t\t// build vertex buffer\n\t\tstd::vector<uint8_t> vertices(vertexSize * count);\n\t\tuint32_t outOffset = 0;\n\t\t\n\t\tfor (int fvfIndex = 0; fvfIndex < 16; fvfIndex++)\n\t\t{\n\t\t\tif (!(bits & (1 << fvfIndex)))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!accessors[fvfIndex])\n\t\t\t{\n\t\t\t\t// make up colors\n\t\t\t\tif (fvfIndex == 4)\n\t\t\t\t{\n\t\t\t\t\tauto outData = &vertices[outOffset];\n\n\t\t\t\t\tfor (uint32_t vert = 0; vert < count; vert++)\n\t\t\t\t\t{\n\t\t\t\t\t\t*(uint32_t*)outData = 0xffffffff;\n\t\t\t\t\t\toutData += vertexSize;\n\t\t\t\t\t}\n\n\t\t\t\t\toutOffset += 4;\n\t\t\t\t}\n\t\t\t\telse if (fvfIndex == 6)\n\t\t\t\t{\n\t\t\t\t\tauto outData = &vertices[outOffset];\n\n\t\t\t\t\tfor (uint32_t vert = 0; vert < count; vert++)\n\t\t\t\t\t{\n\t\t\t\t\t\t*(float*)outData = 0.0f;\n\t\t\t\t\t\t*((float*)outData + 1) = 0.0f;\n\t\t\t\t\t\toutData += vertexSize;\n\t\t\t\t\t}\n\n\t\t\t\t\toutOffset += 8;\n\t\t\t\t}\n\t\t\t\telse if (fvfIndex == 1)\n\t\t\t\t{\n\t\t\t\t\tauto outData = &vertices[outOffset];\n\n\t\t\t\t\tfor (uint32_t vert = 0; vert < count; vert++)\n\t\t\t\t\t{\n\t\t\t\t\t\t*(uint32_t*)outData = 0x000000FF;\n\t\t\t\t\t\toutData += vertexSize;\n\t\t\t\t\t}\n\n\t\t\t\t\toutOffset += 4;\n\t\t\t\t}\n\t\t\t\telse if (fvfIndex == 2)\n\t\t\t\t{\n\t\t\t\t\tauto outData = &vertices[outOffset];\n\n\t\t\t\t\tfor (uint32_t vert = 0; vert < count; vert++)\n\t\t\t\t\t{\n\t\t\t\t\t\t*(uint32_t*)outData = 0x00000000 | (uint8_t)boneIdx;\n\t\t\t\t\t\toutData += vertexSize;\n\t\t\t\t\t}\n\n\t\t\t\t\toutOffset += 4;\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst auto& accessor = *accessors[fvfIndex];\n\n\t\t\tgrcDataSize dataSize = (grcDataSize)((dataSizes >> uint64_t(fvfIndex * 4)) & 0xF);\n\n\t\t\tconst tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView];\n\t\t\tconst tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];\n\n\t\t\tauto inStride = accessor.ByteStride(bufferView);\n\t\t\tconst uint8_t* inData = &buffer.data[bufferView.byteOffset];\n\t\t\tuint8_t* outData = &vertices[outOffset];\n\n\t\t\tuint32_t compSize = 0;\n\t\t\tincreaseSize(dataSize, compSize);\n\n\t\t\tfor (uint32_t vert = 0; vert < accessor.count; vert++)\n\t\t\t{\n\t\t\t\tmemcpy(outData, inData, compSize);\n\n\t\t\t\tinData += inStride;\n\t\t\t\toutData += vertexSize;\n\t\t\t}\n\n\t\t\t// convert coordsys\n\t\t\tif (fvfIndex == 0 || fvfIndex == 3 || fvfIndex == 14)\n\t\t\t{\n\t\t\t\toutData = &vertices[outOffset];\n\n\t\t\t\tfor (uint32_t vert = 0; vert < accessor.count; vert++)\n\t\t\t\t{\n\t\t\t\t\tfloat* dataRef = (float*)outData;\n\t\t\t\t\tstd::swap(dataRef[1], dataRef[2]);\n\t\t\t\t\tdataRef[0] = -dataRef[0];\n\n\t\t\t\t\toutData += vertexSize;\n\t\t\t\t}\n\n\t\t\t\t// scale positions\n\t\t\t\tif (fvfIndex == 0)\n\t\t\t\t{\n\t\t\t\t\toutData = &vertices[outOffset];\n\n\t\t\t\t\tfor (uint32_t vert = 0; vert < accessor.count; vert++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat* dataRef = (float*)outData;\n\t\t\t\t\t\tDirectX::XMStoreFloat3((DirectX::XMFLOAT3*)dataRef, DirectX::XMVector3TransformCoord(DirectX::XMLoadFloat3((DirectX::XMFLOAT3*)dataRef), scaleMatrix));\n\t\t\t\t\t\t\n\t\t\t\t\t\toutData += vertexSize;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (fvfIndex == 3 || fvfIndex == 14)\n\t\t\t\t{\n\t\t\t\t\toutData = &vertices[outOffset];\n\n\t\t\t\t\tfor (uint32_t vert = 0; vert < accessor.count; vert++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat* dataRef = (float*)outData;\n\t\t\t\t\t\tDirectX::XMStoreFloat3((DirectX::XMFLOAT3*)dataRef, DirectX::XMVector3TransformNormal(DirectX::XMLoadFloat3((DirectX::XMFLOAT3*)dataRef), rotMatrix));\n\n\t\t\t\t\t\toutData += vertexSize;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutOffset += compSize;\n\t\t}\n\n\t\trage::five::grcVertexFormat* fvf = new (false) rage::five::grcVertexFormat(bits, vertexSize, numFields, dataSizes);\n\t\tvertexBuffer->SetVertices(count, vertexSize, &vertices[0]);\n\t\tvertexBuffer->SetVertexFormat(fvf);\n\n\t\tgameGeom->SetVertexBuffer(vertexBuffer);\n\t}\n\n\treturn gameGeom;\n}\n\nstatic rage::five::grcTexturePC* MakeTexture(const std::vector<double>& factor, rage::five::pgDictionary<rage::five::grcTexturePC>* txd)\n{\n\tuint8_t a, r, g, b;\n\tr = uint8_t(factor[0] * 255.0);\n\tg = uint8_t(factor[1] * 255.0);\n\tb = uint8_t(factor[2] * 255.0);\n\ta = uint8_t(factor[3] * 255.0);\n\n\tauto imageName = fmt::sprintf(\"c_%02X%02X%02X%02X\", r, g, b, a);\n\n\tif (txd->Get(imageName.c_str()))\n\t{\n\t\treturn txd->Get(imageName.c_str());\n\t}\n\n\tuint32_t color = (a << 24) | (r << 16) | (g << 8) | (b << 0);\n\n\tuint16_t width = 1;\n\tuint16_t height = 1;\n\n\tint format = D3DFMT_A8R8G8B8;\n\n\tauto tex = new (false) rage::five::grcTexturePC(\n\twidth,\n\theight,\n\tformat,\n\t4,\n\t1,\n\t&color);\n\n\ttex->SetName(imageName.c_str());\n\ttxd->Add(imageName.c_str(), tex);\n\n\treturn tex;\n}\n\nstatic rage::five::grcTexturePC* ConvertTexture(const tinygltf::Model& model, int textureIdx, rage::five::pgDictionary<rage::five::grcTexturePC>* txd)\n{\n\tconst tinygltf::Texture& texture = model.textures[textureIdx];\n\tconst tinygltf::Image& image = model.images[texture.source];\n\n\tauto imageName = image.name;\n\n\tif (imageName.empty())\n\t{\n\t\timageName = image.uri;\n\t}\n\n\tif (imageName.empty())\n\t{\n\t\timageName = fmt::sprintf(\"t%d\", rand());\n\t}\n\n\tif (txd->Get(imageName.c_str()))\n\t{\n\t\treturn txd->Get(imageName.c_str());\n\t}\n\n\tassert(!image.as_is);\n\n\tuint16_t width = image.width;\n\tuint16_t height = image.height;\n\n\tint format = D3DFMT_UNKNOWN;\n\n\tif (image.bits == 8)\n\t{\n\t\tif (image.component == 4)\n\t\t{\n\t\t\tformat = D3DFMT_A8B8G8R8;\n\t\t}\n\t\telse if (image.component == 3)\n\t\t{\n\t\t\tformat = D3DFMT_R8G8B8;\n\t\t}\n\t\telse if (image.component == 2)\n\t\t{\n\t\t\tformat = D3DFMT_A8L8;\n\t\t}\n\t\telse if (image.component == 1)\n\t\t{\n\t\t\tformat = D3DFMT_L8;\n\t\t}\n\t}\n\telse if (image.bits == 16)\n\t{\n\t\tif (image.component == 4)\n\t\t{\n\t\t\tformat = D3DFMT_A16B16G16R16;\n\t\t}\n\t\telse if (image.component == 3)\n\t\t{\n\t\t\t//??\n\t\t}\n\t\telse if (image.component == 2)\n\t\t{\n\t\t\tformat = D3DFMT_G16R16;\n\t\t}\n\t\telse if (image.component == 1)\n\t\t{\n\t\t\tformat = D3DFMT_L16;\n\t\t}\n\t}\n\n\tauto tex = new (false) rage::five::grcTexturePC(\n\twidth,\n\theight,\n\tformat,\n\t(image.bits * image.component * image.width) / 8,\n\t1, // TODO: gen mips!\n\t&image.image[0]);\n\n\ttex->SetName(imageName.c_str());\n\ttxd->Add(imageName.c_str(), tex);\n\t\n\treturn tex;\n}\n\nstatic rage::five::grmShaderFx* ConvertShader(const tinygltf::Model& model, int materialIdx, rage::five::pgDictionary<rage::five::grcTexturePC>* txd)\n{\n\tconst tinygltf::Material& material = model.materials[materialIdx];\n\t\n\tbool hasNormal = material.normalTexture.index >= 0;\n\tbool hasEmissive = material.emissiveTexture.index >= 0;\n\tbool hasAlbedo = material.pbrMetallicRoughness.baseColorTexture.index >= 0;\n\t// we don't do specular *yet*\n\n\tstd::string shaderPreset = \"default.sps\";\n\n\tif (hasNormal)\n\t{\n\t\tshaderPreset = \"normal.sps\";\n\t}\n\n\tif (hasEmissive)\n\t{\n\t\tshaderPreset = \"emissive.sps\";\n\t}\n\n\tauto spsFile = fxc::SpsFile::Load(MakeRelativeCitPath(fmt::sprintf(L\"citizen\\\\shaders\\\\db\\\\%s\", ToWide(shaderPreset))));\n\tstd::string shaderName;\n\n\tif (spsFile)\n\t{\n\t\tshaderName = spsFile->GetShader();\n\t}\n\n\trage::five::grmShaderFx* shader = new (false) rage::five::grmShaderFx();\n\tshader->DoPreset(shaderName.c_str(), shaderPreset.c_str());\n\n\t// emissive trumps all\n\tif (hasEmissive)\n\t{\n\t\tshader->SetParameter(\"DiffuseSampler\", ConvertTexture(model, material.emissiveTexture.index, txd));\n\n\t\tfloat emissiveMult = float(material.emissiveFactor[0] + material.emissiveFactor[1] + material.emissiveFactor[2]) / 3.0f;\n\t\tshader->SetParameter(\"emissiveMultiplier\", &emissiveMult, sizeof(emissiveMult));\n\t}\n\telse\n\t{\n\t\tif (hasNormal)\n\t\t{\n\t\t\tshader->SetParameter(\"BumpSampler\", ConvertTexture(model, material.normalTexture.index, txd));\n\n\t\t\tfloat bumpiness = (float)material.normalTexture.scale;\n\t\t\tshader->SetParameter(\"bumpiness\", &bumpiness, sizeof(bumpiness));\n\t\t}\n\n\t\tif (!hasAlbedo)\n\t\t{\n\t\t\tshader->SetParameter(\"DiffuseSampler\", MakeTexture(material.pbrMetallicRoughness.baseColorFactor, txd));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tshader->SetParameter(\"DiffuseSampler\", ConvertTexture(model, material.pbrMetallicRoughness.baseColorTexture.index, txd));\n\t\t}\n\t}\n\n\treturn shader;\n\n\t//shaders[0] = new (false) rage::five::grmShaderFx();\n\t//shaders[0]->DoPreset(\"default\", \"default.sps\");\n\t//shaders[0]->SetParameter(\"DiffuseSampler\", \"dreamy\");\n}\n\nstruct GeomSetupContext\n{\n\tbool hadSkin = false;\n\tint geomIndex = 0;\n\tint boneIndex = 0;\n\n\trage::five::grmGeometryQB* geometries[512];\n\tuint16_t shaderMappings[512];\n\trage::five::GeometryBound gbs[512];\n\n\trage::five::crBone bones[256];\n\tstd::map<int, int> boneMapping;\n};\n\n#if 0\nstatic void ProcessMesh(const tinygltf::Model& model, const std::string& nodeName, int meshIdx, const DirectX::XMMATRIX& matrix)\n{\n\tconst tinygltf::Mesh& mesh = model.meshes[meshIdx];\n\n\tstd::string meshName = mesh.name;\n\n\tif (!meshName.empty())\n\t{\n\t\tmeshName = nodeName;\n\t}\n\n\tOutputFile([&]()\n\t{\n\t\tauto out = new (false) rage::five::gtaDrawable;\n\t\tout->SetBlockMap();\n\n\t\tout->SetName(fmt::format(\"{}.#dr\", nodeName).c_str());\n\t\tauto& lodGroup = out->GetLodGroup();\n\n\t\trage::five::grmModel* gameModel = new (false) rage::five::grmModel;\n\n\t\tint i = 0;\n\n\t\tfor (auto& geom : mesh.primitives)\n\t\t{\n\t\t\tgeometries[i] = ConvertGeometry(model, geom, matrix);\n\t\t\tshaderMappings[i] = 0;\n\n\t\t\ti++;\n\t\t}\n\n\t\tgameModel->SetGeometries(i, geometries);\n\t\tgameModel->SetGeometryBounds(i, gbs);\n\t\t\n\t\tlodGroup.SetModel(0, gameModel);\n\t\tlodGroup.SetDrawBucketMask(0, 0xff01);\n\t\tlodGroup.SetMaxPoint({ 9999.0f, 9999.0f, 9999.0f, 9999.0f });\n\n\t\t// set up shaders\n\t\trage::five::pgPtr<rage::five::grmShaderFx> shaders[512];\n\t\t//shaders[0] = new (false) rage::five::grmShaderFx();\n\t\t//shaders[0]->DoPreset(\"default\", \"default.sps\");\n\t\t//shaders[0]->SetParameter(\"DiffuseSampler\", \"dreamy\");\n\n\t\ti = 0;\n\t\tint shaderIdx = 0;\n\n\t\tstd::map<int, int> materialsToShaders;\n\t\trage::five::pgDictionary<rage::five::grcTexturePC> txd;\n\n\t\tfor (auto& geom : mesh.primitives)\n\t\t{\n\t\t\tif (materialsToShaders.find(geom.material) != materialsToShaders.end())\n\t\t\t{\n\t\t\t\tshaderMappings[i] = materialsToShaders[geom.material];\n\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tauto materialIdx = geom.material;\n\t\t\tshaders[shaderIdx] = ConvertShader(model, geom.material, &txd);\n\n\t\t\tmaterialsToShaders[materialIdx] = shaderIdx;\n\t\t\tshaderMappings[i] = shaderIdx;\n\n\t\t\tshaderIdx++;\n\t\t\ti++;\n\t\t}\n\n\t\trage::five::grmShaderGroup* shaderGroup = new (false) rage::five::grmShaderGroup();\n\t\tshaderGroup->SetShaders(shaderIdx, shaders);\n\n\t\tif (txd.GetCount())\n\t\t{\n\t\t\trage::five::pgDictionary<rage::five::grcTexturePC>* rtxd = new (false) rage::five::pgDictionary<rage::five::grcTexturePC>();\n\t\t\trtxd->SetBlockMap();\n\n\t\t\trtxd->SetFrom(&txd);\n\n\t\t\tshaderGroup->SetTextures(rtxd);\n\t\t}\n\n\t\tgameModel->SetShaderMappings(i, shaderMappings);\n\n\t\tout->SetPrimaryModel();\n\t\tout->SetShaderGroup(shaderGroup);\n\t}, 165, ToWide(nodeName + \".ydr\"));\n}\n#endif\n\nstatic void AddMesh(GeomSetupContext& context, const tinygltf::Model& model, int meshIdx, const DirectX::XMMATRIX& matrix, int boneIdx = -1)\n{\n\tconst tinygltf::Mesh& mesh = model.meshes[meshIdx];\n\n\tfor (auto& geom : mesh.primitives)\n\t{\n\t\tcontext.geometries[context.geomIndex] = ConvertGeometry(model, geom, matrix, boneIdx);\n\t\tcontext.shaderMappings[context.geomIndex] = geom.material;\n\n\t\tcontext.geomIndex++;\n\t}\n}\n\nstatic int ProcessNodesForSkeleton(GeomSetupContext& ctx, const tinygltf::Model& model, int nodeIdx, int parentIdx = -1, DirectX::XMMATRIX parentMatrix = DirectX::XMMatrixIdentity())\n{\n\tusing namespace DirectX;\n\n\tconst tinygltf::Node& node = model.nodes[nodeIdx];\n\n\tstd::string nodeName = node.name;\n\n\tif (nodeName.empty())\n\t{\n\t\tnodeName = fmt::format(\"node_{}\", nodeIdx);\n\t}\n\t\n\tauto matrix = ConvertNodeMatrix(node);\n\tauto fullMatrix = parentMatrix * matrix;\n\n\tDirectX::XMVECTOR scale;\n\tDirectX::XMVECTOR rotQuat;\n\tDirectX::XMVECTOR trans;\n\tDirectX::XMMatrixDecompose(&scale, &rotQuat, &trans, matrix);\n\n\trage::Vector4 rotationV;\n\trage::Vector3 transV;\n\trage::Vector3 scaleV;\n\n\tscaleV.x = DirectX::XMVectorGetX(scale);\n\tscaleV.y = DirectX::XMVectorGetY(scale);\n\tscaleV.z = DirectX::XMVectorGetZ(scale);\n\n\trotationV.x = DirectX::XMVectorGetX(rotQuat);\n\trotationV.y = DirectX::XMVectorGetY(rotQuat);\n\trotationV.z = DirectX::XMVectorGetZ(rotQuat);\n\trotationV.w = DirectX::XMVectorGetW(rotQuat);\n\n\ttransV.x = DirectX::XMVectorGetX(trans);\n\ttransV.y = DirectX::XMVectorGetY(trans);\n\ttransV.z = DirectX::XMVectorGetZ(trans);\n\n\tusing rage::five::crBoneFlags;\n\n\tint siblingIdx = -1;\n\n\tint bi = ctx.boneIndex++;\n\tctx.bones[bi].Init(nodeName.c_str(), bi, (crBoneFlags)(crBoneFlags::RotX | crBoneFlags::RotY | crBoneFlags::RotZ | crBoneFlags::TransX | crBoneFlags::TransY | crBoneFlags::TransZ), rotationV, scaleV, transV, parentIdx, siblingIdx);\n\n\tctx.boneMapping[nodeIdx] = bi;\n\n\tint lastIdx = -1;\n\n\tfor (int c = 0; c < node.children.size(); c++)\n\t{\n\t\tint childIdx = node.children[c];\n\t\tint idx = ProcessNodesForSkeleton(ctx, model, childIdx, nodeIdx, fullMatrix);\n\t\t\n\t\tif (lastIdx >= 0)\n\t\t{\n\t\t\tctx.bones[lastIdx].SetSiblingIndex(idx);\n\t\t}\n\n\t\tlastIdx = idx;\n\t}\n\n\treturn bi;\n}\n\nstatic void ProcessNode(const tinygltf::Model& model, int nodeIdx, const std::string& sceneName, int depth = 0, DirectX::XMMATRIX parentMatrix = DirectX::XMMatrixIdentity(), DirectX::XMMATRIX invRootMatrix = DirectX::XMMatrixIdentity())\n{\n\tusing namespace DirectX;\n\n\tconst tinygltf::Node& node = model.nodes[nodeIdx];\n\n\tauto matrix = ConvertNodeMatrix(node);\n\tauto fullMatrix = parentMatrix * matrix;\n\n\tif (depth == 0)\n\t{\n\t\tDirectX::XMVECTOR scale;\n\t\tDirectX::XMVECTOR rotQuat;\n\t\tDirectX::XMVECTOR trans;\n\t\tDirectX::XMMatrixDecompose(&scale, &rotQuat, &trans, fullMatrix);\n\n\t\tauto noScaleMatrix = DirectX::XMMatrixAffineTransformation(DirectX::XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f), DirectX::XMVectorZero(), rotQuat, trans);\n\n\t\tinvRootMatrix = DirectX::XMMatrixInverse(NULL, noScaleMatrix);\n\t}\n\n\tstd::string nodeName = node.name;\n\n\tif (nodeName.empty())\n\t{\n\t\tnodeName = fmt::format(\"{}_{}\", sceneName, nodeIdx);\n\t}\n\n\tstatic thread_local GeomSetupContext* geomCtx;\n\n\tauto processEntry = [&]()\n\t{\n\t\tif (node.mesh >= 0)\n\t\t{\n\t\t\tAddMesh(*geomCtx, model, node.mesh, invRootMatrix * fullMatrix, geomCtx->boneMapping[nodeIdx]);\n\t\t}\n\n\t\tfor (int nodeIdx : node.children)\n\t\t{\n\t\t\tProcessNode(model, nodeIdx, sceneName, depth + 1, fullMatrix, invRootMatrix);\n\t\t}\n\t};\n\n\tif (depth == 0)\n\t{\n\t\tgeomCtx = new GeomSetupContext();\n\n\t\tOutputFile([&]()\n\t\t{\n\t\t\tauto out = new (false) rage::five::gtaDrawable;\n\t\t\tout->SetBlockMap();\n\n\t\t\tout->SetName(fmt::format(\"{}.#dr\", nodeName).c_str());\n\n\t\t\tProcessNodesForSkeleton(*geomCtx, model, nodeIdx);\n\n\t\t\tauto& lodGroup = out->GetLodGroup();\n\n\t\t\trage::five::grmModel* gameModel = new (false) rage::five::grmModel;\n\n\t\t\tprocessEntry();\n\n\t\t\tgameModel->SetGeometries(geomCtx->geomIndex, geomCtx->geometries);\n\t\t\tgameModel->SetGeometryBounds(geomCtx->geomIndex, geomCtx->gbs);\n\n\t\t\tlodGroup.SetModel(0, gameModel);\n\t\t\tlodGroup.SetDrawBucketMask(0, 0xff01);\n\t\t\tlodGroup.SetMaxPoint({ 9999.0f, 9999.0f, 9999.0f, 9999.0f });\n\n\t\t\t// set up shaders\n\t\t\trage::five::pgPtr<rage::five::grmShaderFx> shaders[512];\n\n\t\t\tint shaderIdx = 0;\n\n\t\t\tstd::map<int, int> materialsToShaders;\n\t\t\trage::five::pgDictionary<rage::five::grcTexturePC> txd;\n\n\t\t\tfor (int i = 0; i < geomCtx->geomIndex;)\n\t\t\t{\n\t\t\t\tif (materialsToShaders.find(geomCtx->shaderMappings[i]) != materialsToShaders.end())\n\t\t\t\t{\n\t\t\t\t\tgeomCtx->shaderMappings[i] = materialsToShaders[geomCtx->shaderMappings[i]];\n\n\t\t\t\t\ti++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tauto materialIdx = geomCtx->shaderMappings[i];\n\t\t\t\tshaders[shaderIdx] = ConvertShader(model, materialIdx, &txd);\n\n\t\t\t\tmaterialsToShaders[materialIdx] = shaderIdx;\n\t\t\t\tgeomCtx->shaderMappings[i] = shaderIdx;\n\n\t\t\t\tshaderIdx++;\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\trage::five::grmShaderGroup* shaderGroup = new (false) rage::five::grmShaderGroup();\n\t\t\tshaderGroup->SetShaders(shaderIdx, shaders);\n\n\t\t\tif (txd.GetCount())\n\t\t\t{\n\t\t\t\trage::five::pgDictionary<rage::five::grcTexturePC>* rtxd = new (false) rage::five::pgDictionary<rage::five::grcTexturePC>();\n\t\t\t\trtxd->SetBlockMap();\n\n\t\t\t\trtxd->SetFrom(&txd);\n\n\t\t\t\tshaderGroup->SetTextures(rtxd);\n\t\t\t}\n\n\t\t\tgameModel->SetShaderMappings(geomCtx->geomIndex, geomCtx->shaderMappings);\n\n\t\t\tauto skeleton = new (false) rage::five::crSkeletonData();\n\t\t\tskeleton->SetBones(geomCtx->boneIndex, geomCtx->bones);\n\t\t\t//out->SetSkeleton(skeleton);\n\n\t\t\tout->SetPrimaryModel();\n\t\t\tout->SetShaderGroup(shaderGroup);\n\n\t\t\tdelete geomCtx;\n\t\t},\n\t\t165, ToWide(nodeName + \".ydr\"));\n\t}\n\telse\n\t{\n\t\tprocessEntry();\n\t}\n}\n\nstatic void ConvertAsset(const boost::filesystem::path& path)\n{\n\ttinygltf::Model model;\n\tstd::string err, warn;\n\n\t// load the asset\n\ttinygltf::TinyGLTF loader;\n\n\tbool success = false;\n\tif (path.extension() == \".glb\")\n\t{\n\t\tsuccess = loader.LoadBinaryFromFile(&model, &err, &warn, ToNarrow(path.wstring()));\n\t}\n\telse\n\t{\n\t\tsuccess = loader.LoadASCIIFromFile(&model, &err, &warn, ToNarrow(path.wstring()));\n\t}\n\n\t// check for success\n\tif (!warn.empty())\n\t{\n\t\tfmt::printf(\"WARN: %s\\n\", warn);\n\t}\n\n\tif (!err.empty())\n\t{\n\t\tfmt::printf(\"ERR: %s\\n\", err);\n\t}\n\n\tif (!success)\n\t{\n\t\treturn;\n\t}\n\n\tif (model.defaultScene < 0)\n\t{\n\t\tfmt::printf(\"%s: Assets without default scene are not supported!\\n\", path.filename().string());\n\t\treturn;\n\t}\n\n\tconst tinygltf::Scene& scene = model.scenes[model.defaultScene];\n\tauto fn = path.filename();\n\tfn.replace_extension();\n\n\tstd::string sceneName = scene.name.empty() ? fn.string() : scene.name;\n\n\tfor (int nodeIdx : scene.nodes)\n\t{\n\t\tProcessNode(model, nodeIdx, sceneName);\n\t}\n}\n\nstatic void HandleArguments(boost::program_options::wcommand_line_parser& parser, std::function<void()> cb)\n{\n\tboost::program_options::options_description desc;\n\n\tdesc.add_options()(\"filename\", boost::program_options::value<std::vector<boost::filesystem::path>>()->required(), \"The path of the file to convert.\");\n\n\tboost::program_options::positional_options_description positional;\n\tpositional.add(\"filename\", -1);\n\n\tparser.options(desc).positional(positional);\n\n\tcb();\n}\n\nstatic void Run(const boost::program_options::variables_map& map)\n{\n\tif (map.count(\"filename\") == 0)\n\t{\n\t\tprintf(\"Usage:\\n\\n   fivem formats:gltfImport *.gltf/*.glb...\\n\");\n\t\treturn;\n\t}\n\n\tauto& entries = map[\"filename\"].as<std::vector<boost::filesystem::path>>();\n\n\tfor (auto& filePath : entries)\n\t{\n\t\tConvertAsset(filePath);\n\t}\n}\n\nstatic FxToolCommand command(\"formats:gltfImport\", HandleArguments, Run);\n#endif\n", "meta": {"hexsha": "0662a69b17dbea9e42ee7a625d8783787b009455", "size": 26433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/components/tool-formats/src/GLTFImport.cpp", "max_stars_repo_name": "thorium-cfx/fivem", "max_stars_repo_head_hexsha": "587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5411.0, "max_stars_repo_stars_event_min_datetime": "2017-04-14T08:57:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:35:15.000Z", "max_issues_repo_path": "code/components/tool-formats/src/GLTFImport.cpp", "max_issues_repo_name": "thorium-cfx/fivem", "max_issues_repo_head_hexsha": "587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 802.0, "max_issues_repo_issues_event_min_datetime": "2017-04-21T14:18:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:20:48.000Z", "max_forks_repo_path": "code/components/tool-formats/src/GLTFImport.cpp", "max_forks_repo_name": "thorium-cfx/fivem", "max_forks_repo_head_hexsha": "587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2011.0, "max_forks_repo_forks_event_min_datetime": "2017-04-14T09:44:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:40:39.000Z", "avg_line_length": 24.4976830399, "max_line_length": 236, "alphanum_fraction": 0.6706011425, "num_tokens": 8331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.15285095127621418}}
{"text": "#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <chratos/node/common.hpp>\n#include <chratos/node/stats.hpp>\n#include <chratos/secure/blockstore.hpp>\n#include <chratos/secure/ledger.hpp>\n\nnamespace\n{\n/**\n * Roll back the visited block\n */\nclass rollback_visitor : public chratos::block_visitor\n{\npublic:\n\trollback_visitor (chratos::transaction const & transaction_a, chratos::ledger & ledger_a) :\n\ttransaction (transaction_a),\n\tledger (ledger_a)\n\t{\n\t}\n\tvirtual ~rollback_visitor () = default;\n\n\tvoid state_block (chratos::state_block const & block_a) override\n\t{\n\t\tauto hash (block_a.hash ());\n\t\tchratos::block_hash representative (0);\n\t\tif (!block_a.hashables.previous.is_zero ())\n\t\t{\n\t\t\trepresentative = ledger.representative (transaction, block_a.hashables.previous);\n\t\t}\n\t\tauto balance (ledger.balance (transaction, block_a.hashables.previous));\n\t\tauto is_send (block_a.hashables.balance < balance);\n\t\t// Add in amount delta\n\t\tledger.store.representation_add (transaction, hash, 0 - block_a.hashables.balance.number ());\n\t\tif (!representative.is_zero ())\n\t\t{\n\t\t\t// Move existing representation\n\t\t\tledger.store.representation_add (transaction, representative, balance);\n\t\t}\n\n\t\tchratos::account_info info;\n\t\tauto error (ledger.store.account_get (transaction, block_a.hashables.account, info));\n\n\t\tif (is_send)\n\t\t{\n\t\t\tchratos::pending_key key (block_a.hashables.link, hash);\n\t\t\twhile (!ledger.store.pending_exists (transaction, key))\n\t\t\t{\n\t\t\t\tledger.rollback (transaction, ledger.latest (transaction, block_a.hashables.link));\n\t\t\t}\n\t\t\tledger.store.pending_del (transaction, key);\n\t\t\tledger.stats.inc (chratos::stat::type::rollback, chratos::stat::detail::send);\n\t\t}\n\t\telse if (!block_a.hashables.link.is_zero () && !ledger.is_epoch_link (block_a.hashables.link))\n\t\t{\n\t\t\tauto source_version (ledger.store.block_version (transaction, block_a.hashables.link));\n\t\t\tchratos::pending_info pending_info (ledger.account (transaction, block_a.hashables.link), block_a.hashables.balance.number () - balance, block_a.hashables.dividend, source_version);\n\t\t\tledger.store.pending_put (transaction, chratos::pending_key (block_a.hashables.account, block_a.hashables.link), pending_info);\n\t\t\tledger.stats.inc (chratos::stat::type::rollback, chratos::stat::detail::receive);\n\t\t}\n\n\t\tassert (!error);\n\t\tauto previous_version (ledger.store.block_version (transaction, block_a.hashables.previous));\n\t\tledger.change_latest (transaction, block_a.hashables.account, block_a.hashables.previous, representative, block_a.hashables.dividend, balance, info.block_count - 1, false, previous_version);\n\n\t\tauto previous (ledger.store.block_get (transaction, block_a.hashables.previous));\n\t\tif (previous != nullptr)\n\t\t{\n\t\t\tledger.store.block_successor_clear (transaction, block_a.hashables.previous);\n\t\t\tif (previous->type () < chratos::block_type::state)\n\t\t\t{\n\t\t\t\tledger.store.frontier_put (transaction, block_a.hashables.previous, block_a.hashables.account);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tledger.stats.inc (chratos::stat::type::rollback, chratos::stat::detail::open);\n\t\t}\n\t\tledger.store.block_del (transaction, hash);\n\t}\n\tvoid dividend_block (chratos::dividend_block const & block_a) override\n\t{\n\t\tauto hash (block_a.hash ());\n\t}\n\tvoid claim_block (chratos::claim_block const & block_a) override\n\t{\n\t\tauto hash (block_a.hash ());\n\t}\n\tchratos::transaction const & transaction;\n\tchratos::ledger & ledger;\n};\n\nclass ledger_processor : public chratos::block_visitor\n{\npublic:\n\tledger_processor (chratos::ledger &, chratos::transaction const &, bool = false);\n\tvirtual ~ledger_processor () = default;\n\n\tvoid state_block (chratos::state_block const &) override;\n\tvoid dividend_block (chratos::dividend_block const &) override;\n\tvoid claim_block (chratos::claim_block const &) override;\n\n\tvoid state_block_impl (chratos::state_block const &);\n\tvoid epoch_block_impl (chratos::state_block const &);\n\tchratos::ledger & ledger;\n\tchratos::transaction const & transaction;\n\tbool valid_signature;\n\tchratos::process_return result;\n};\n\nvoid ledger_processor::state_block (chratos::state_block const & block_a)\n{\n\tresult.code = chratos::process_result::progress;\n\tauto is_epoch_block (false);\n\t// Check if this is an epoch block\n\tif (!ledger.epoch_link.is_zero () && ledger.is_epoch_link (block_a.hashables.link))\n\t{\n\t\tchratos::amount prev_balance (0);\n\t\tif (!block_a.hashables.previous.is_zero ())\n\t\t{\n\t\t\tresult.code = ledger.store.block_exists (transaction, block_a.hashables.previous) ? chratos::process_result::progress : chratos::process_result::gap_previous;\n\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t{\n\t\t\t\tprev_balance = ledger.balance (transaction, block_a.hashables.previous);\n\t\t\t}\n\t\t}\n\t\tif (block_a.hashables.balance == prev_balance)\n\t\t{\n\t\t\tis_epoch_block = true;\n\t\t}\n\t}\n\tif (result.code == chratos::process_result::progress)\n\t{\n\t\tif (is_epoch_block)\n\t\t{\n\t\t\tepoch_block_impl (block_a);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstate_block_impl (block_a);\n\t\t}\n\t}\n}\n\nvoid ledger_processor::state_block_impl (chratos::state_block const & block_a)\n{\n\tauto hash (block_a.hash ());\n\tauto existing (ledger.store.block_exists (transaction, hash));\n\tresult.code = existing ? chratos::process_result::old : chratos::process_result::progress; // Have we seen this block before? (Unambiguous)\n\tif (result.code == chratos::process_result::progress)\n\t{\n\t\tresult.code = validate_message (block_a.hashables.account, hash, block_a.signature) ? chratos::process_result::bad_signature : chratos::process_result::progress; // Is this block signed correctly (Unambiguous)\n\t\tif (result.code == chratos::process_result::progress)\n\t\t{\n\t\t\tresult.code = block_a.hashables.account.is_zero () ? chratos::process_result::opened_burn_account : chratos::process_result::progress; // Is this for the burn account? (Unambiguous)\n\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t{\n\t\t\t\tchratos::epoch epoch (chratos::epoch::epoch_0);\n\t\t\t\tchratos::account_info info;\n\t\t\t\tresult.amount = block_a.hashables.balance;\n\t\t\t\tauto is_send (false);\n\t\t\t\tauto account_error (ledger.store.account_get (transaction, block_a.hashables.account, info));\n\t\t\t\tif (!account_error)\n\t\t\t\t{\n\t\t\t\t\tepoch = info.epoch;\n\t\t\t\t\tresult.code = block_a.hashables.previous.is_zero () ? chratos::process_result::fork : chratos::process_result::progress; // Has this account already been opened? (Ambigious)\n\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Account already exists\n\t\t\t\t\t\tresult.code = ledger.store.block_exists (transaction, block_a.hashables.previous) ? chratos::process_result::progress : chratos::process_result::gap_previous; // Does the previous block exist in the ledger? (Unambigious)\n\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tis_send = block_a.hashables.balance < info.balance;\n\n\t\t\t\t\t\t\tresult.amount = is_send ? (info.balance.number () - result.amount.number ()) : (result.amount.number () - info.balance.number ());\n\n\t\t\t\t\t\t\tresult.code = block_a.hashables.previous == info.head ? chratos::process_result::progress : chratos::process_result::fork; // Is the previous block the account's head block? (Ambigious)\n\t\t\t\t\t\t}\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\t// Account does not yet exists\n\t\t\t\t\tresult.code = block_a.previous ().is_zero () ? chratos::process_result::progress : chratos::process_result::gap_previous; // Does the first block in an account yield 0 for previous() ? (Unambigious)\n\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult.code = !block_a.hashables.link.is_zero () ? chratos::process_result::progress : chratos::process_result::gap_source; // Is the first block receiving from a send ? (Unambigious)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\tif (!is_send)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!block_a.hashables.link.is_zero ())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tresult.code = ledger.store.block_exists (transaction, block_a.hashables.link) ? chratos::process_result::progress : chratos::process_result::gap_source; // Have we seen the source block already? (Harmless)\n\n\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// Make sure the dividend is ordered with the most recent\n\t\t\t\t\t\t\t\tif (info.head != chratos::dividend_base)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tresult.code = ledger.dividends_are_ordered (transaction, block_a.hashables.dividend, info.dividend_block) ? chratos::process_result::progress : chratos::process_result::unreceivable;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tchratos::pending_key key (block_a.hashables.account, block_a.hashables.link);\n\t\t\t\t\t\t\t\t\tchratos::pending_info pending;\n\t\t\t\t\t\t\t\t\tresult.code = ledger.store.pending_get (transaction, key, pending) ? chratos::process_result::unreceivable : chratos::process_result::progress; // Has this source already been received (Malformed)\n\t\t\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tresult.code = result.amount == pending.amount ? chratos::process_result::progress : chratos::process_result::balance_mismatch;\n\t\t\t\t\t\t\t\t\t\tepoch = std::max (epoch, pending.epoch);\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}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// If there's no link, the balance must remain the same, only the representative can change\n\t\t\t\t\t\t\tresult.code = result.amount.is_zero () ? chratos::process_result::progress : chratos::process_result::balance_mismatch;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (is_send)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult.code = (info.dividend_block == block_a.hashables.dividend) ? chratos::process_result::progress : chratos::process_result::incorrect_dividend;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\tledger.stats.inc (chratos::stat::type::ledger, chratos::stat::detail::state_block);\n\t\t\t\t\tresult.state_is_send = is_send;\n\t\t\t\t\tledger.store.block_put (transaction, hash, block_a, 0, epoch);\n\n\t\t\t\t\tif (!info.rep_block.is_zero ())\n\t\t\t\t\t{\n\t\t\t\t\t\t// Move existing representation\n\t\t\t\t\t\tledger.store.representation_add (transaction, info.rep_block, 0 - info.balance.number ());\n\t\t\t\t\t}\n\t\t\t\t\t// Add in amount delta\n\t\t\t\t\tledger.store.representation_add (transaction, hash, block_a.hashables.balance.number ());\n\n\t\t\t\t\tif (is_send)\n\t\t\t\t\t{\n\t\t\t\t\t\tchratos::pending_key key (block_a.hashables.link, hash);\n\t\t\t\t\t\tchratos::pending_info info (block_a.hashables.account, result.amount.number (), block_a.hashables.dividend, epoch);\n\t\t\t\t\t\tledger.store.pending_put (transaction, key, info);\n\t\t\t\t\t}\n\t\t\t\t\telse if (!block_a.hashables.link.is_zero ())\n\t\t\t\t\t{\n\t\t\t\t\t\tledger.store.pending_del (transaction, chratos::pending_key (block_a.hashables.account, block_a.hashables.link));\n\t\t\t\t\t}\n\n\t\t\t\t\tledger.change_latest (transaction, block_a.hashables.account, hash, hash, block_a.hashables.dividend, block_a.hashables.balance, info.block_count + 1, true, epoch);\n\t\t\t\t\tif (!ledger.store.frontier_get (transaction, info.head).is_zero ())\n\t\t\t\t\t{\n\t\t\t\t\t\tledger.store.frontier_del (transaction, info.head);\n\t\t\t\t\t}\n\t\t\t\t\t// Frontier table is unnecessary for state blocks and this also prevents old blocks from being inserted on top of state blocks\n\t\t\t\t\tresult.account = block_a.hashables.account;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid ledger_processor::epoch_block_impl (chratos::state_block const & block_a)\n{\n\tauto hash (block_a.hash ());\n\tauto existing (ledger.store.block_exists (transaction, hash));\n\tresult.code = existing ? chratos::process_result::old : chratos::process_result::progress; // Have we seen this block before? (Unambiguous)\n\tif (result.code == chratos::process_result::progress)\n\t{\n\t\tresult.code = validate_message (ledger.epoch_signer, hash, block_a.signature) ? chratos::process_result::bad_signature : chratos::process_result::progress; // Is this block signed correctly (Unambiguous)\n\t\tif (result.code == chratos::process_result::progress)\n\t\t{\n\t\t\tresult.code = block_a.hashables.account.is_zero () ? chratos::process_result::opened_burn_account : chratos::process_result::progress; // Is this for the burn account? (Unambiguous)\n\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t{\n\t\t\t\tchratos::account_info info;\n\t\t\t\tauto account_error (ledger.store.account_get (transaction, block_a.hashables.account, info));\n\t\t\t\tif (!account_error)\n\t\t\t\t{\n\t\t\t\t\t// Account already exists\n\t\t\t\t\tresult.code = block_a.hashables.previous.is_zero () ? chratos::process_result::fork : chratos::process_result::progress; // Has this account already been opened? (Ambigious)\n\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult.code = ledger.store.block_exists (transaction, block_a.hashables.previous) ? chratos::process_result::progress : chratos::process_result::gap_previous; // Does the previous block exist in the ledger? (Unambigious)\n\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tresult.code = block_a.hashables.previous == info.head ? chratos::process_result::progress : chratos::process_result::fork; // Is the previous block the account's head block? (Ambigious)\n\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto last_rep_block (ledger.store.block_get (transaction, info.rep_block));\n\t\t\t\t\t\t\t\tassert (last_rep_block != nullptr);\n\t\t\t\t\t\t\t\tresult.code = block_a.hashables.representative == last_rep_block->representative () ? chratos::process_result::progress : chratos::process_result::representative_mismatch;\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\telse\n\t\t\t\t{\n\t\t\t\t\tresult.code = block_a.hashables.representative.is_zero () ? chratos::process_result::progress : chratos::process_result::representative_mismatch;\n\t\t\t\t}\n\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\tresult.code = info.epoch == chratos::epoch::epoch_0 ? chratos::process_result::progress : chratos::process_result::block_position;\n\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult.code = block_a.hashables.balance == info.balance ? chratos::process_result::progress : chratos::process_result::balance_mismatch;\n\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tledger.stats.inc (chratos::stat::type::ledger, chratos::stat::detail::epoch_block);\n\t\t\t\t\t\t\tresult.account = block_a.hashables.account;\n\t\t\t\t\t\t\tresult.amount = 0;\n\t\t\t\t\t\t\tledger.store.block_put (transaction, hash, block_a, 0, chratos::epoch::epoch_1);\n\t\t\t\t\t\t\tledger.change_latest (transaction, block_a.hashables.account, hash, hash, block_a.hashables.dividend, info.balance, info.block_count + 1, true, chratos::epoch::epoch_1);\n\t\t\t\t\t\t\tif (!ledger.store.frontier_get (transaction, info.head).is_zero ())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tledger.store.frontier_del (transaction, info.head);\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\t}\n}\n\nvoid ledger_processor::dividend_block (chratos::dividend_block const & block_a)\n{\n\tauto hash (block_a.hash ());\n\tauto existing (ledger.store.block_exists (transaction, hash));\n\tresult.code = existing ? chratos::process_result::old : chratos::process_result::progress; // Have we seen this block before? (Harmless)\n\tif (result.code == chratos::process_result::progress)\n\t{\n\t\tstd::shared_ptr<chratos::block> previous (ledger.store.block_get (transaction, block_a.hashables.previous));\n\t\tresult.code = previous != nullptr ? chratos::process_result::progress : chratos::process_result::gap_previous; // Have we seen the previous block already? (Harmless)\n\t\tif (result.code == chratos::process_result::progress)\n\t\t{\n\t\t\tauto account = block_a.hashables.account;\n\t\t\tresult.code = account.is_zero () ? chratos::process_result::fork : chratos::process_result::progress;\n\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t{\n\t\t\t\t// Here is the dividend account check.\n\t\t\t\tresult.code = account == chratos::dividend_account ? chratos::process_result::progress : chratos::process_result::invalid_dividend_account;\n\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\tresult.code = validate_message (account, hash, block_a.signature) ? chratos::process_result::bad_signature : chratos::process_result::progress; // Is this block signed correctly (Malformed)\n\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\tchratos::account_info info;\n\t\t\t\t\t\tauto latest_error (ledger.store.account_get (transaction, account, info));\n\t\t\t\t\t\tassert (!latest_error);\n\t\t\t\t\t\tassert (info.head == block_a.hashables.previous);\n\t\t\t\t\t\tresult.code = info.balance.number () >= block_a.hashables.balance.number () ? chratos::process_result::progress : chratos::process_result::negative_spend; // Is this trying to spend a negative amount (Malicious)\n\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto amount (info.balance.number () - block_a.hashables.balance.number ());\n\t\t\t\t\t\t\tresult.code = amount > chratos::minimum_dividend_amount ? chratos::process_result::progress : chratos::process_result::dividend_too_small;\n\n\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// Do dividend checks. Make sure that the previous dividend hasn't been used before.\n\t\t\t\t\t\t\t\tif (block_a.hashables.dividend != chratos::dividend_base)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t// check block exists\n\t\t\t\t\t\t\t\t\tresult.code = ledger.store.block_exists (transaction, block_a.hashables.dividend) ? chratos::process_result::progress : chratos::process_result::gap_source;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tauto dividend_info (ledger.store.dividend_get (transaction));\n\t\t\t\t\t\t\t\t\tresult.code = block_a.hashables.dividend == dividend_info.head ? chratos::process_result::progress : chratos::process_result::dividend_fork;\n\n\t\t\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tledger.store.block_put (transaction, hash, block_a);\n\n\t\t\t\t\t\t\t\t\t\tif (!info.rep_block.is_zero ())\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t// Move existing representation\n\t\t\t\t\t\t\t\t\t\t\tledger.store.representation_add (transaction, info.rep_block, 0 - info.balance.number ());\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t// Add in amount delta\n\t\t\t\t\t\t\t\t\t\tledger.store.representation_add (transaction, hash, block_a.hashables.balance.number ());\n\n\t\t\t\t\t\t\t\t\t\tledger.change_latest (transaction, account, hash, info.rep_block, block_a.hashables.dividend, block_a.hashables.balance, info.block_count + 1);\n\t\t\t\t\t\t\t\t\t\tif (!ledger.store.frontier_get (transaction, info.head).is_zero ())\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tledger.store.frontier_del (transaction, info.head);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t// Frontier table is unnecessary for state blocks and this also prevents old blocks from being inserted on top of state blocks.\n\t\t\t\t\t\t\t\t\t\tresult.account = account;\n\t\t\t\t\t\t\t\t\t\tresult.amount = amount;\n\t\t\t\t\t\t\t\t\t\tledger.stats.inc (chratos::stat::type::ledger, chratos::stat::detail::dividend_block);\n\t\t\t\t\t\t\t\t\t\tauto previous_info (ledger.store.dividend_get (transaction));\n\t\t\t\t\t\t\t\t\t\tconst auto balance = previous_info.balance.number () + result.amount.number ();\n\t\t\t\t\t\t\t\t\t\tconst auto count = previous_info.block_count + 1;\n\t\t\t\t\t\t\t\t\t\tconst auto time = chratos::seconds_since_epoch ();\n\t\t\t\t\t\t\t\t\t\tchratos::dividend_info info (hash, balance, time, count, chratos::epoch::epoch_0);\n\t\t\t\t\t\t\t\t\t\tledger.store.dividend_put (transaction, info);\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}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid ledger_processor::claim_block (chratos::claim_block const & block_a)\n{\n\tauto hash (block_a.hash ());\n\tauto existing (ledger.store.block_exists (transaction, hash));\n\tresult.code = existing ? chratos::process_result::old : chratos::process_result::progress; // Have we seen this block already?  (Harmless)\n\tif (result.code == chratos::process_result::progress)\n\t{\n\t\tauto previous (ledger.store.block_get (transaction, block_a.hashables.previous));\n\t\tresult.code = previous != nullptr ? chratos::process_result::progress : chratos::process_result::gap_previous;\n\t\tif (result.code == chratos::process_result::progress)\n\t\t{\n\t\t\tstd::shared_ptr<chratos::block> dividend = ledger.store.block_get (transaction, block_a.hashables.dividend);\n\t\t\tresult.code = dividend != nullptr ? chratos::process_result::progress : chratos::process_result::gap_source; // Have we seen the source block already? (Harmless)\n\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t{\n\t\t\t\tchratos::dividend_block const * div_block = dynamic_cast<chratos::dividend_block const *> (dividend.get ());\n\t\t\t\tresult.code = div_block != nullptr ? chratos::process_result::progress : chratos::process_result::incorrect_dividend;\n\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\tauto account = block_a.hashables.account;\n\t\t\t\t\tresult.code = account.is_zero () ? chratos::process_result::gap_previous : chratos::process_result::progress; //Have we seen the previous block? No entries for account at all (Harmless)\n\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult.code = chratos::validate_message (account, hash, block_a.signature) ? chratos::process_result::bad_signature : chratos::process_result::progress; // Is the signature valid (Malformed)\n\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tchratos::account_info info;\n\t\t\t\t\t\t\tledger.store.account_get (transaction, account, info);\n\t\t\t\t\t\t\tresult.code = info.head == block_a.hashables.previous ? chratos::process_result::progress : chratos::process_result::gap_previous; // Block doesn't immediately follow latest block (Harmless)\n\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tresult.code = ledger.has_outstanding_pendings_for_dividend (transaction, div_block->hashables.dividend, account) ? chratos::process_result::outstanding_pendings : chratos::process_result::progress;\n\t\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tresult.code = info.dividend_block == div_block->hashables.dividend ? chratos::process_result::progress : chratos::process_result::unreceivable; // Hash this dividend been claimed already.\n\t\t\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tresult.amount = block_a.hashables.balance.number () - info.balance.number ();\n\t\t\t\t\t\t\t\t\t\tconst auto expected (ledger.amount_for_dividend (transaction, block_a.hashables.dividend, account));\n\t\t\t\t\t\t\t\t\t\tresult.code = result.amount == expected ? chratos::process_result::progress : chratos::process_result::balance_mismatch;\n\t\t\t\t\t\t\t\t\t\tif (result.code == chratos::process_result::progress)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tledger.store.block_put (transaction, hash, block_a);\n\n\t\t\t\t\t\t\t\t\t\t\tif (!info.rep_block.is_zero ())\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t// Move existing representation\n\t\t\t\t\t\t\t\t\t\t\t\tledger.store.representation_add (transaction, info.rep_block, 0 - info.balance.number ());\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t// Add in amount delta\n\t\t\t\t\t\t\t\t\t\t\tledger.store.representation_add (transaction, hash, block_a.hashables.balance.number ());\n\n\t\t\t\t\t\t\t\t\t\t\tchratos::account account = block_a.hashables.account;\n\n\t\t\t\t\t\t\t\t\t\t\tif (ledger.dividends_are_ordered (transaction, info.dividend_block, block_a.hashables.dividend))\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tinfo.dividend_block = block_a.hashables.dividend;\n\t\t\t\t\t\t\t\t\t\t\t\tledger.store.account_put (transaction, account, info);\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tledger.change_latest (transaction, account, hash, info.rep_block, block_a.hashables.dividend, block_a.hashables.balance, info.block_count + 1);\n\t\t\t\t\t\t\t\t\t\t\tif (!ledger.store.frontier_get (transaction, info.head).is_zero ())\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tledger.store.frontier_del (transaction, info.head);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t// Frontier table is unnecessary for state blocks and this also prevents old blocks from being inserted on top of state blocks.\n\t\t\t\t\t\t\t\t\t\t\tresult.account = account;\n\t\t\t\t\t\t\t\t\t\t\tledger.stats.inc (chratos::stat::type::ledger, chratos::stat::detail::claim_block);\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\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tresult.code = ledger.store.block_exists (transaction, block_a.hashables.previous) ? chratos::process_result::fork : chratos::process_result::gap_previous; // If we have the block but it's not the latest we have a signed fork (Malicious)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nledger_processor::ledger_processor (chratos::ledger & ledger_a, chratos::transaction const & transaction_a, bool valid_signature_a) :\nledger (ledger_a),\ntransaction (transaction_a),\nvalid_signature (valid_signature_a)\n{\n}\n} // namespace\n\nsize_t chratos::shared_ptr_block_hash::operator() (std::shared_ptr<chratos::block> const & block_a) const\n{\n\tauto hash (block_a->hash ());\n\tauto result (static_cast<size_t> (hash.qwords[0]));\n\treturn result;\n}\n\nbool chratos::shared_ptr_block_hash::operator() (std::shared_ptr<chratos::block> const & lhs, std::shared_ptr<chratos::block> const & rhs) const\n{\n\treturn lhs->hash () == rhs->hash ();\n}\n\nchratos::ledger::ledger (chratos::block_store & store_a, chratos::stat & stat_a, chratos::uint256_union const & epoch_link_a, chratos::account const & epoch_signer_a) :\nstore (store_a),\nstats (stat_a),\ncheck_bootstrap_weights (true),\nepoch_link (epoch_link_a),\nepoch_signer (epoch_signer_a)\n{\n}\n\n// Balance for account containing hash\nchratos::uint128_t chratos::ledger::balance (chratos::transaction const & transaction_a, chratos::block_hash const & hash_a)\n{\n\tchratos::balance_visitor visitor (transaction_a, store);\n\tvisitor.compute (hash_a);\n\treturn visitor.balance;\n}\n\n// Balance for an account by account number\nchratos::uint128_t chratos::ledger::account_balance (chratos::transaction const & transaction_a, chratos::account const & account_a)\n{\n\tchratos::uint128_t result (0);\n\tchratos::account_info info;\n\tauto none (store.account_get (transaction_a, account_a, info));\n\tif (!none)\n\t{\n\t\tresult = info.balance.number ();\n\t}\n\treturn result;\n}\n\nchratos::uint128_t chratos::ledger::account_pending (chratos::transaction const & transaction_a, chratos::account const & account_a)\n{\n\tchratos::uint128_t result (0);\n\tchratos::account end (account_a.number () + 1);\n\tfor (auto i (store.pending_v0_begin (transaction_a, chratos::pending_key (account_a, 0))), n (store.pending_v0_begin (transaction_a, chratos::pending_key (end, 0))); i != n; ++i)\n\t{\n\t\tchratos::pending_info info (i->second);\n\t\tresult += info.amount.number ();\n\t}\n\tfor (auto i (store.pending_v1_begin (transaction_a, chratos::pending_key (account_a, 0))), n (store.pending_v1_begin (transaction_a, chratos::pending_key (end, 0))); i != n; ++i)\n\t{\n\t\tchratos::pending_info info (i->second);\n\t\tresult += info.amount.number ();\n\t}\n\treturn result;\n}\n\nchratos::process_return chratos::ledger::process (chratos::transaction const & transaction_a, chratos::block const & block_a, bool valid_signature)\n{\n\tledger_processor processor (*this, transaction_a, valid_signature);\n\tblock_a.visit (processor);\n\treturn processor.result;\n}\n\nchratos::block_hash chratos::ledger::representative (chratos::transaction const & transaction_a, chratos::block_hash const & hash_a)\n{\n\tauto result (representative_calculated (transaction_a, hash_a));\n\tassert (result.is_zero () || store.block_exists (transaction_a, result));\n\treturn result;\n}\n\nchratos::block_hash chratos::ledger::representative_calculated (chratos::transaction const & transaction_a, chratos::block_hash const & hash_a)\n{\n\trepresentative_visitor visitor (transaction_a, store);\n\tvisitor.compute (hash_a);\n\treturn visitor.result;\n}\n\nbool chratos::ledger::block_exists (chratos::block_hash const & hash_a)\n{\n\tauto transaction (store.tx_begin_read ());\n\tauto result (store.block_exists (transaction, hash_a));\n\treturn result;\n}\n\nstd::string chratos::ledger::block_text (char const * hash_a)\n{\n\treturn block_text (chratos::block_hash (hash_a));\n}\n\nstd::string chratos::ledger::block_text (chratos::block_hash const & hash_a)\n{\n\tstd::string result;\n\tauto transaction (store.tx_begin_read ());\n\tauto block (store.block_get (transaction, hash_a));\n\tif (block != nullptr)\n\t{\n\t\tblock->serialize_json (result);\n\t}\n\treturn result;\n}\n\nbool chratos::ledger::is_send (chratos::transaction const & transaction_a, chratos::state_block const & block_a)\n{\n\tbool result (false);\n\tchratos::block_hash previous (block_a.hashables.previous);\n\tif (!previous.is_zero ())\n\t{\n\t\tif (block_a.hashables.balance < balance (transaction_a, previous))\n\t\t{\n\t\t\tresult = true;\n\t\t}\n\t}\n\treturn result;\n}\n\nbool chratos::ledger::is_dividend (chratos::transaction const & transaction_a, chratos::state_block const & block_a)\n{\n\tbool result (false);\n\n\tchratos::block_hash dividend (block_a.hashables.dividend);\n\tchratos::block_hash link (block_a.hashables.link);\n\n\tif (link == dividend)\n\t{\n\t\tresult = !is_send (transaction_a, block_a);\n\t}\n\n\treturn result;\n}\n\nbool chratos::ledger::is_dividend_claim (chratos::transaction const & transaction_a, chratos::state_block const & block_a)\n{\n\tbool result (false);\n\n\tchratos::block_hash dividend (block_a.hashables.dividend);\n\tchratos::block_hash link (block_a.hashables.link);\n\n\tif (link == dividend)\n\t{\n\t\tresult = !is_send (transaction_a, block_a);\n\t}\n\n\treturn result;\n}\n\nbool chratos::ledger::has_outstanding_pendings_for_dividend (chratos::transaction const & transaction_a, chratos::block_hash const & dividend_a, chratos::account const & account_a)\n{\n\tbool result (false);\n\n\tchratos::account end (account_a.number () + 1);\n\n\tfor (auto i (store.pending_begin (transaction_a, chratos::pending_key (account_a, 0))), n (store.pending_begin (transaction_a, chratos::pending_key (end, 0))); i != n && !result; ++i)\n\t{\n\t\tchratos::pending_info info (i->second);\n\t\tauto block (store.block_get (transaction_a, i->first.hash));\n\t\tif (block->dividend () == dividend_a)\n\t\t{\n\t\t\tresult = true;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nbool chratos::ledger::dividends_are_ordered (chratos::transaction const & transaction_a, chratos::block_hash const & first_a, chratos::block_hash const & last_a)\n{\n\tbool result (false);\n\n\tif (first_a == last_a)\n\t{\n\t\treturn true;\n\t}\n\n\tstd::shared_ptr<chratos::block> block = store.block_get (transaction_a, last_a);\n\n\twhile (block != nullptr)\n\t{\n\t\tchratos::block_hash previous = block->dividend ();\n\t\tif (previous == first_a)\n\t\t{\n\t\t\tresult = true;\n\t\t}\n\t\tblock = store.block_get (transaction_a, previous);\n\t}\n\n\treturn result;\n}\n\nchratos::amount chratos::ledger::amount_for_dividend (chratos::transaction const & transaction_a, chratos::block_hash const & dividend_a, chratos::account const & account_a)\n{\n\tchratos::amount result (0);\n\tchratos::account_info account_info;\n\tstd::shared_ptr<chratos::block> block_l = store.block_get (transaction_a, dividend_a);\n\tauto dividend_hash (block_l->dividend ());\n\tauto previous (store.block_get (transaction_a, block_l->previous ()));\n\tchratos::dividend_block const * dividend_block (dynamic_cast<chratos::dividend_block const *> (block_l.get ()));\n\n\tassert (dividend_block != nullptr);\n\n  if (dividend_block != nullptr)\n  {\n    if (!store.account_get (transaction_a, account_a, account_info))\n    {\n      auto front (store.block_get (transaction_a, account_info.head));\n\n      while (front && (front->dividend () == dividend_a || dividends_are_ordered (transaction_a, dividend_a, front->dividend ())))\n      {\n        front = store.block_get (transaction_a, front->previous ());\n      }\n\n      if (front) {\n        chratos::amount genesis_supply (std::numeric_limits<chratos::uint128_t>::max ());\n        chratos::amount burned_amount (burn_account_balance (transaction_a, dividend_a));\n        chratos::amount balance_at_dividend (balance (transaction_a, front->hash ()));\n        chratos::amount dividend_amount (amount (transaction_a, block_l->hash ()));\n        chratos::amount total_supply (genesis_supply.number () - burned_amount.number ());\n        boost::multiprecision::cpp_bin_float_100 balance_f (balance_at_dividend.number ());\n        boost::multiprecision::cpp_bin_float_100 daf (dividend_amount.number ());\n        boost::multiprecision::cpp_bin_float_100 tsf (total_supply.number ());\n        boost::multiprecision::cpp_bin_float_100 total_f (tsf - daf);\n        boost::multiprecision::cpp_bin_float_100 proportion (balance_f / total_f);\n        boost::multiprecision::cpp_bin_float_100 reward (proportion * daf);\n\n        result = chratos::amount (static_cast<uint128_t> (reward));\n      }\n    }\n  }\n\n\treturn result;\n}\n\nstd::vector<chratos::block_hash> chratos::ledger::unclaimed_for_account (chratos::transaction const & transaction_a, chratos::account const & account_a)\n{\n\tstd::vector<chratos::block_hash> result;\n\n\tchratos::dividend_info div_info (store.dividend_get (transaction_a));\n\tchratos::account_info info;\n\tif (!store.account_get (transaction_a, account_a, info))\n\t{\n\t\tauto open_block = store.block_get (transaction_a, info.open_block);\n\t\tchratos::block_hash open_div = open_block->dividend ();\n\t\tchratos::block_hash current = div_info.head;\n\t\tboost::property_tree::ptree entry;\n\n\t\twhile (current != chratos::uint256_union (0) && current != open_div && current != info.dividend_block)\n\t\t{\n\t\t\tresult.push_back (current);\n\t\t\tauto block (store.block_get (transaction_a, current));\n\t\t\tcurrent = block->dividend ();\n\t\t}\n\t}\n\n\tstd::reverse (std::begin (result), std::end (result));\n\treturn result;\n}\n\nchratos::amount chratos::ledger::burn_account_balance (chratos::transaction const & transaction_a, chratos::block_hash const & dividend_a)\n{\n\tchratos::account burn = burn_account;\n\tchratos::amount result (0);\n\tchratos::account_info info;\n\n\tif (!store.account_get (transaction_a, burn, info))\n\t{\n\t\tresult = info.balance;\n\t}\n\n\tstd::shared_ptr<chratos::block> dividend = store.block_get (transaction_a, dividend_a);\n\n\tchratos::block_hash previous = dividend->dividend ();\n\n\tchratos::account end (burn.number () + 1);\n\tfor (auto i (store.pending_v0_begin (transaction_a, chratos::pending_key (burn, 0))), n (store.pending_v0_begin (transaction_a, chratos::pending_key (end, 0))); i != n; ++i)\n\t{\n\t\tauto pending_info = i->second;\n\t\tif (dividends_are_ordered (transaction_a, pending_info.dividend, previous))\n\t\t{\n\t\t\tresult = result.number () + pending_info.amount.number ();\n\t\t}\n\t}\n\n\treturn result;\n}\n\nstd::vector<std::shared_ptr<chratos::block>> chratos::ledger::dividend_claim_blocks (chratos::transaction const & transaction_a, chratos::account const & account_a)\n{\n\tchratos::account_info account_info;\n\tstd::vector<std::shared_ptr<chratos::block>> result;\n\n\tif (!store.account_get (transaction_a, account_a, account_info))\n\t{\n\t\tchratos::block_hash current = account_info.head;\n\n\t\twhile (current != account_a)\n\t\t{\n\t\t\tstd::shared_ptr<chratos::block> block = store.block_get (transaction_a, current);\n\t\t\tchratos::state_block const * state = dynamic_cast<chratos::state_block const *> (block.get ());\n\n\t\t\tif (!state)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (is_dividend_claim (transaction_a, *state))\n\t\t\t{\n\t\t\t\tresult.push_back (block);\n\t\t\t}\n\t\t\tcurrent = block->previous ();\n\t\t}\n\t}\n\n\treturn result;\n}\n\nstd::unordered_map<chratos::block_hash, int> chratos::ledger::get_dividend_indexes (chratos::transaction const & transaction_a)\n{\n\tstd::unordered_map<chratos::block_hash, int> results;\n\n\tauto dividend_info = store.dividend_get (transaction_a);\n\tauto current = dividend_info.head;\n\tint index (0);\n\n\twhile (current != chratos::dividend_base)\n\t{\n\t\tstd::shared_ptr<chratos::block> block = store.block_get (transaction_a, current);\n\t\tresults[current] = index++;\n\t\tcurrent = block->dividend ();\n\t}\n\n\tconst auto count = results.size ();\n\n\tfor (auto & it : results)\n\t{\n\t\tit.second = (count - 1) - it.second;\n\t}\n\n\treturn results;\n}\n\nchratos::block_hash chratos::ledger::block_destination (chratos::transaction const & transaction_a, chratos::block const & block_a)\n{\n\tchratos::block_hash result (0);\n\tchratos::state_block const * state_block (dynamic_cast<chratos::state_block const *> (&block_a));\n\tif (state_block != nullptr && is_send (transaction_a, *state_block))\n\t{\n\t\tresult = state_block->hashables.link;\n\t}\n\treturn result;\n}\n\nchratos::block_hash chratos::ledger::block_source (chratos::transaction const & transaction_a, chratos::block const & block_a)\n{\n\t/*\n\t * block_source() requires that the previous block of the block\n\t * passed in exist in the database.  This is because it will try\n\t * to check account balances to determine if it is a send block.\n\t */\n\tassert (block_a.previous ().is_zero () || store.block_exists (transaction_a, block_a.previous ()));\n\n\t// If block_a.source () is nonzero, then we have our source.\n\t// However, universal blocks will always return zero.\n\tchratos::block_hash result (block_a.source ());\n\tchratos::state_block const * state_block (dynamic_cast<chratos::state_block const *> (&block_a));\n\tif (state_block != nullptr && !is_send (transaction_a, *state_block))\n\t{\n\t\tresult = state_block->hashables.link;\n\t}\n\treturn result;\n}\n\n// Vote weight of an account\nchratos::uint128_t chratos::ledger::weight (chratos::transaction const & transaction_a, chratos::account const & account_a)\n{\n\tif (check_bootstrap_weights.load ())\n\t{\n\t\tauto blocks = store.block_count (transaction_a);\n\t\tif (blocks.sum () < bootstrap_weight_max_blocks)\n\t\t{\n\t\t\tauto weight = bootstrap_weights.find (account_a);\n\t\t\tif (weight != bootstrap_weights.end ())\n\t\t\t{\n\t\t\t\treturn weight->second;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcheck_bootstrap_weights = false;\n\t\t}\n\t}\n\treturn store.representation_get (transaction_a, account_a);\n}\n\n// Rollback blocks until `block_a' doesn't exist\nvoid chratos::ledger::rollback (chratos::transaction const & transaction_a, chratos::block_hash const & block_a)\n{\n\tassert (store.block_exists (transaction_a, block_a));\n\tauto account_l (account (transaction_a, block_a));\n\trollback_visitor rollback (transaction_a, *this);\n\tchratos::account_info info;\n\twhile (store.block_exists (transaction_a, block_a))\n\t{\n\t\tauto latest_error (store.account_get (transaction_a, account_l, info));\n\t\tassert (!latest_error);\n\t\tauto block (store.block_get (transaction_a, info.head));\n\t\tblock->visit (rollback);\n\t}\n}\n\n// Return account containing hash\nchratos::account chratos::ledger::account (chratos::transaction const & transaction_a, chratos::block_hash const & hash_a)\n{\n\tchratos::account result;\n\tauto hash (hash_a);\n\tchratos::block_hash successor (1);\n\tchratos::block_info block_info;\n\tstd::unique_ptr<chratos::block> block (store.block_get (transaction_a, hash));\n\twhile (!successor.is_zero () && (block->type () != chratos::block_type::state || block->type () != chratos::block_type::dividend || block->type () != chratos::block_type::claim) && store.block_info_get (transaction_a, successor, block_info))\n\t{\n\t\tsuccessor = store.block_successor (transaction_a, hash);\n\t\tif (!successor.is_zero ())\n\t\t{\n\t\t\thash = successor;\n\t\t\tblock = store.block_get (transaction_a, hash);\n\t\t}\n\t}\n\tif (block->type () == chratos::block_type::state)\n\t{\n\t\tauto state_block (dynamic_cast<chratos::state_block *> (block.get ()));\n\t\tresult = state_block->hashables.account;\n\t}\n\telse if (block->type () == chratos::block_type::dividend)\n\t{\n\t\tauto dividend_block (dynamic_cast<chratos::dividend_block *> (block.get ()));\n\t\tresult = dividend_block->hashables.account;\n\t}\n\telse if (block->type () == chratos::block_type::claim)\n\t{\n\t\tauto claim_block (dynamic_cast<chratos::claim_block *> (block.get ()));\n\t\tresult = claim_block->hashables.account;\n\t}\n\telse if (successor.is_zero ())\n\t{\n\t\tresult = store.frontier_get (transaction_a, hash);\n\t}\n\telse\n\t{\n\t\tresult = block_info.account;\n\t}\n\tassert (!result.is_zero ());\n\treturn result;\n}\n\n// Return amount decrease or increase for block\nchratos::uint128_t chratos::ledger::amount (chratos::transaction const & transaction_a, chratos::block_hash const & hash_a)\n{\n\tamount_visitor amount (transaction_a, store);\n\tamount.compute (hash_a);\n\treturn amount.amount;\n}\n\n// Return latest block for account\nchratos::block_hash chratos::ledger::latest (chratos::transaction const & transaction_a, chratos::account const & account_a)\n{\n\tchratos::account_info info;\n\tauto latest_error (store.account_get (transaction_a, account_a, info));\n\treturn latest_error ? 0 : info.head;\n}\n\n// Return latest root for account, account number of there are no blocks for this account.\nchratos::block_hash chratos::ledger::latest_root (chratos::transaction const & transaction_a, chratos::account const & account_a)\n{\n\tchratos::account_info info;\n\tauto latest_error (store.account_get (transaction_a, account_a, info));\n\tchratos::block_hash result;\n\tif (latest_error)\n\t{\n\t\tresult = account_a;\n\t}\n\telse\n\t{\n\t\tresult = info.head;\n\t}\n\treturn result;\n}\n\nchratos::block_hash chratos::ledger::latest_dividend (chratos::transaction const & transaction_a)\n{\n\tchratos::dividend_info info = store.dividend_get (transaction_a);\n\treturn info.head;\n}\n\nchratos::checksum chratos::ledger::checksum (chratos::transaction const & transaction_a, chratos::account const & begin_a, chratos::account const & end_a)\n{\n\tchratos::checksum result;\n\tauto error (store.checksum_get (transaction_a, 0, 0, result));\n\tassert (!error);\n\treturn result;\n}\n\nvoid chratos::ledger::dump_account_chain (chratos::account const & account_a)\n{\n\tauto transaction (store.tx_begin_read ());\n\tauto hash (latest (transaction, account_a));\n\twhile (!hash.is_zero ())\n\t{\n\t\tauto block (store.block_get (transaction, hash));\n\t\tassert (block != nullptr);\n\t\tstd::cerr << hash.to_string () << std::endl;\n\t\thash = block->previous ();\n\t}\n}\n\nclass block_fit_visitor : public chratos::block_visitor\n{\npublic:\n\tblock_fit_visitor (chratos::ledger & ledger_a, chratos::transaction const & transaction_a) :\n\tledger (ledger_a),\n\ttransaction (transaction_a),\n\tresult (false)\n\t{\n\t}\n\tvoid state_block (chratos::state_block const & block_a) override\n\t{\n\t\tresult = block_a.previous ().is_zero () || ledger.store.block_exists (transaction, block_a.previous ());\n\t\tif (result && !ledger.is_send (transaction, block_a))\n\t\t{\n\t\t\tresult &= ledger.store.block_exists (transaction, block_a.hashables.link);\n\t\t}\n\t}\n\tvoid dividend_block (chratos::dividend_block const & block_a) override\n\t{\n\t\tresult = ledger.store.block_exists (transaction, block_a.previous ());\n\t}\n\tvoid claim_block (chratos::claim_block const & block_a) override\n\t{\n\t\tresult = ledger.store.block_exists (transaction, block_a.previous ());\n\t\tresult &= ledger.store.block_exists (transaction, block_a.dividend ());\n\t}\n\tchratos::ledger & ledger;\n\tchratos::transaction const & transaction;\n\tbool result;\n};\n\nbool chratos::ledger::could_fit (chratos::transaction const & transaction_a, chratos::block const & block_a)\n{\n\tblock_fit_visitor visitor (*this, transaction_a);\n\tblock_a.visit (visitor);\n\treturn visitor.result;\n}\n\nbool chratos::ledger::is_epoch_link (chratos::uint256_union const & link_a)\n{\n\treturn link_a == epoch_link;\n}\n\nvoid chratos::ledger::checksum_update (chratos::transaction const & transaction_a, chratos::block_hash const & hash_a)\n{\n\tchratos::checksum value;\n\tauto error (store.checksum_get (transaction_a, 0, 0, value));\n\tassert (!error);\n\tvalue ^= hash_a;\n\tstore.checksum_put (transaction_a, 0, 0, value);\n}\n\nvoid chratos::ledger::change_latest (chratos::transaction const & transaction_a, chratos::account const & account_a, chratos::block_hash const & hash_a, chratos::block_hash const & rep_block_a, chratos::block_hash const & dividend_a, chratos::amount const & balance_a, uint64_t block_count_a, bool is_state, chratos::epoch epoch_a)\n{\n\tchratos::account_info info;\n\tauto exists (!store.account_get (transaction_a, account_a, info));\n\tif (exists)\n\t{\n\t\tchecksum_update (transaction_a, info.head);\n\t}\n\telse\n\t{\n\t\tassert (store.block_get (transaction_a, hash_a)->previous ().is_zero ());\n\t\tinfo.open_block = hash_a;\n\t\tinfo.dividend_block = dividend_a;\n\t}\n\tif (!hash_a.is_zero ())\n\t{\n\t\tinfo.head = hash_a;\n\t\tinfo.rep_block = rep_block_a;\n\t\tinfo.balance = balance_a;\n\t\tinfo.modified = chratos::seconds_since_epoch ();\n\t\tinfo.block_count = block_count_a;\n\t\tif (exists && info.epoch != epoch_a)\n\t\t{\n\t\t\t// otherwise we'd end up with a duplicate\n\t\t\tstore.account_del (transaction_a, account_a);\n\t\t}\n\t\tinfo.epoch = epoch_a;\n\t\tstore.account_put (transaction_a, account_a, info);\n\t\tif (!(block_count_a % store.block_info_max) && !is_state)\n\t\t{\n\t\t\tchratos::block_info block_info;\n\t\t\tblock_info.account = account_a;\n\t\t\tblock_info.balance = balance_a;\n\t\t\tstore.block_info_put (transaction_a, hash_a, block_info);\n\t\t}\n\t\tchecksum_update (transaction_a, hash_a);\n\t}\n\telse\n\t{\n\t\tstore.account_del (transaction_a, account_a);\n\t}\n}\n\nstd::unique_ptr<chratos::block> chratos::ledger::successor (chratos::transaction const & transaction_a, chratos::uint256_union const & root_a)\n{\n\tchratos::block_hash successor (0);\n\tif (store.account_exists (transaction_a, root_a))\n\t{\n\t\tchratos::account_info info;\n\t\tauto error (store.account_get (transaction_a, root_a, info));\n\t\tassert (!error);\n\t\tsuccessor = info.open_block;\n\t}\n\telse\n\t{\n\t\tsuccessor = store.block_successor (transaction_a, root_a);\n\t}\n\tstd::unique_ptr<chratos::block> result;\n\tif (!successor.is_zero ())\n\t{\n\t\tresult = store.block_get (transaction_a, successor);\n\t}\n\tassert (successor.is_zero () || result != nullptr);\n\treturn result;\n}\n\nstd::unique_ptr<chratos::block> chratos::ledger::forked_block (chratos::transaction const & transaction_a, chratos::block const & block_a)\n{\n\tassert (!store.block_exists (transaction_a, block_a.hash ()));\n\tauto root (block_a.root ());\n\tassert (store.block_exists (transaction_a, root) || store.account_exists (transaction_a, root));\n\tstd::unique_ptr<chratos::block> result (store.block_get (transaction_a, store.block_successor (transaction_a, root)));\n\tif (result == nullptr)\n\t{\n\t\tchratos::account_info info;\n\t\tauto error (store.account_get (transaction_a, root, info));\n\t\tassert (!error);\n\t\tresult = store.block_get (transaction_a, info.open_block);\n\t\tassert (result != nullptr);\n\t}\n\treturn result;\n}\n", "meta": {"hexsha": "79df915185da75c4f8edea3e1bd87813ec7294fb", "size": 45371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "chratos/secure/ledger.cpp", "max_stars_repo_name": "chratos-system/chratos", "max_stars_repo_head_hexsha": "caf1b608a21ccc7b13726a64497036ab53f837b3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-10T16:28:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T17:44:43.000Z", "max_issues_repo_path": "chratos/secure/ledger.cpp", "max_issues_repo_name": "chratos-system/chratos", "max_issues_repo_head_hexsha": "caf1b608a21ccc7b13726a64497036ab53f837b3", "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": "chratos/secure/ledger.cpp", "max_forks_repo_name": "chratos-system/chratos", "max_forks_repo_head_hexsha": "caf1b608a21ccc7b13726a64497036ab53f837b3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-27T13:00:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-16T21:54:13.000Z", "avg_line_length": 39.2822510823, "max_line_length": 331, "alphanum_fraction": 0.7156553746, "num_tokens": 11134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.15285095127621415}}
{"text": "// Copyright (C) 2011-2012 by the Bem++ 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 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#ifndef fiber_default_local_assembler_for_potential_operators_on_surfaces_hpp\n#define fiber_default_local_assembler_for_potential_operators_on_surfaces_hpp\n\n#include \"../common/common.hpp\"\n\n#include \"local_assembler_for_potential_operators.hpp\"\n\n#include \"_2d_array.hpp\"\n#include \"accuracy_options.hpp\"\n#include \"default_local_assembler_for_operators_on_surfaces_utilities.hpp\"\n#include \"element_pair_topology.hpp\"\n#include \"numerical_quadrature.hpp\"\n#include \"parallelization_options.hpp\"\n#include \"shared_ptr.hpp\"\n#include \"kernel_trial_integrator.hpp\"\n#include \"verbosity_level.hpp\"\n\n#include <boost/static_assert.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <tbb/concurrent_unordered_map.h>\n#include <cstring>\n#include <climits>\n#include <set>\n#include <utility>\n#include <vector>\n\nnamespace Fiber {\n\n/** \\cond FORWARD_DECL */\nclass OpenClHandler;\ntemplate <typename CoordinateType> class CollectionOfShapesetTransformations;\ntemplate <typename ValueType> class CollectionOfKernels;\ntemplate <typename BasisFunctionType, typename KernelType, typename ResultType>\nclass KernelTrialIntegral;\ntemplate <typename CoordinateType> class RawGridGeometry;\ntemplate <typename BasisFunctionType>\nclass QuadratureDescriptorSelectorForPotentialOperators;\ntemplate <typename CoordinateType> class SingleQuadratureRuleFamily;\n/** \\endcond */\n\ntemplate <typename BasisFunctionType, typename KernelType, typename ResultType,\n          typename GeometryFactory>\nclass DefaultLocalAssemblerForPotentialOperatorsOnSurfaces\n    : public LocalAssemblerForPotentialOperators<ResultType> {\npublic:\n  typedef typename ScalarTraits<ResultType>::RealType CoordinateType;\n\n  DefaultLocalAssemblerForPotentialOperatorsOnSurfaces(\n      const arma::Mat<CoordinateType> &points,\n      const shared_ptr<const GeometryFactory> &geometryFactory,\n      const shared_ptr<const RawGridGeometry<CoordinateType>> &rawGeometry,\n      const shared_ptr<const std::vector<const Shapeset<BasisFunctionType> *>> &\n          trialShapesets,\n      const shared_ptr<const CollectionOfKernels<KernelType>> &kernels,\n      const shared_ptr<const CollectionOfShapesetTransformations<\n          CoordinateType>> &trialTransformations,\n      const shared_ptr<const KernelTrialIntegral<BasisFunctionType, KernelType,\n                                                 ResultType>> &integral,\n      const ParallelizationOptions &parallelizationOptions,\n      VerbosityLevel::Level verbosityLevel,\n      const shared_ptr<const QuadratureDescriptorSelectorForPotentialOperators<\n          BasisFunctionType>> &quadDescSelector,\n      const shared_ptr<const SingleQuadratureRuleFamily<CoordinateType>> &\n          quadRuleFamily);\n  virtual ~DefaultLocalAssemblerForPotentialOperatorsOnSurfaces();\n\n  virtual void\n  evaluateLocalContributions(const std::vector<int> &pointIndices,\n                             int trialElementIndex,\n                             LocalDofIndex localTrialDofIndex,\n                             std::vector<arma::Mat<ResultType>> &result,\n                             CoordinateType nominalDistance = -1.);\n\n  virtual void\n  evaluateLocalContributions(int pointIndex, int componentIndex,\n                             const std::vector<int> &trialElementIndices,\n                             std::vector<arma::Mat<ResultType>> &result,\n                             CoordinateType nominalDistance = -1.);\n\n  virtual void\n  evaluateLocalContributions(const std::vector<int> &pointIndices,\n                             const std::vector<int> &trialElementIndices,\n                             Fiber::_2dArray<arma::Mat<ResultType>> &result,\n                             CoordinateType nominalDistance = -1.);\n\n  virtual int resultDimension() const;\n\n  virtual CoordinateType estimateRelativeScale(CoordinateType minDist) const;\n\nprivate:\n  /** \\cond PRIVATE */\n  typedef KernelTrialIntegrator<BasisFunctionType, KernelType, ResultType>\n  Integrator;\n  typedef DefaultLocalAssemblerForOperatorsOnSurfacesUtilities<\n      BasisFunctionType> Utilities;\n\n  const Integrator &selectIntegrator(int testElementIndex,\n                                     int trialElementIndex,\n                                     CoordinateType nominalDistance = -1.);\n\n  int order(int pointIndex, int trialElementIndex,\n            CoordinateType nominalDistance) const;\n\n  const Integrator &getIntegrator(const SingleQuadratureDescriptor &index);\n\n  CoordinateType pointElementDistanceSquared(int pointIndex,\n                                             int trialElementIndex) const;\n\n  void precalculateElementSizesAndCenters();\n\nprivate:\n  arma::Mat<CoordinateType> m_points;\n  shared_ptr<const GeometryFactory> m_geometryFactory;\n  shared_ptr<const RawGridGeometry<CoordinateType>> m_rawGeometry;\n  shared_ptr<const std::vector<const Shapeset<BasisFunctionType> *>>\n  m_trialShapesets;\n  shared_ptr<const CollectionOfKernels<KernelType>> m_kernels;\n  shared_ptr<const CollectionOfShapesetTransformations<CoordinateType>>\n  m_trialTransformations;\n  shared_ptr<const KernelTrialIntegral<BasisFunctionType, KernelType,\n                                       ResultType>> m_integral;\n  ParallelizationOptions m_parallelizationOptions;\n  VerbosityLevel::Level m_verbosityLevel;\n  shared_ptr<const QuadratureDescriptorSelectorForPotentialOperators<\n      BasisFunctionType>> m_quadDescSelector;\n  shared_ptr<const SingleQuadratureRuleFamily<CoordinateType>> m_quadRuleFamily;\n\n  typedef tbb::concurrent_unordered_map<SingleQuadratureDescriptor,\n                                        Integrator *> IntegratorMap;\n  IntegratorMap m_kernelTrialIntegrators;\n\n  enum {\n    INVALID_INDEX = INT_MAX\n  };\n  /** \\endcond */\n};\n\n} // namespace Fiber\n\n#include \"default_local_assembler_for_potential_operators_on_surfaces_imp.hpp\"\n\n#endif\n", "meta": {"hexsha": "b447d7507775f84ddc1af926b081c81a0eb1bf4f", "size": 6915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/fiber/default_local_assembler_for_potential_operators_on_surfaces.hpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/fiber/default_local_assembler_for_potential_operators_on_surfaces.hpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/fiber/default_local_assembler_for_potential_operators_on_surfaces.hpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": 42.4233128834, "max_line_length": 80, "alphanum_fraction": 0.7434562545, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.1527647719521381}}
{"text": "#ifndef __TVC_HH__\n#define __TVC_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Describe the TVC Module On Board)\nLIBRARY DEPENDENCY:\n      ((../src/Tvc.cpp))\n*******************************************************************************/\n#include <armadillo>\n#include <functional>\n#include <tuple>\n#include <vector>\n#include \"Component.hh\"\n#include \"Module.hh\"\n#include \"aux.hh\"\n#include \"global_constants.hh\"\n#include \"icf_trx_ctrl.h\"\n\nclass TVC : public Dynamics {\n  TRICK_INTERFACE(TVC);\n\n public:\n  TVC(Data_exchang &input);\n  TVC(const TVC &other);\n\n  TVC &operator=(const TVC &other);\n\n  virtual void init();\n\n  virtual void algorithm(double int_step);\n  void Allocate_ENG(int NumEng, std::vector<ENG *> &Eng_list);\n\n  enum TVC_TYPE {\n    NO_TVC = 0,\n    NO_DYNAMIC_TVC,\n    SECON_ORDER_TVC,          // TVC Second order dynamics with rate limiting\n    ONLINE_SECOND_ORDER_TVC,  // same as 2nd order but with on-line TVC gain\n    S2_TVC,\n    S3_TVC\n  };\n\n  enum TVC_TYPE get_mtvc();\n  void set_mtvc(enum TVC_TYPE);\n  void set_S2_TVC();\n  void set_S3_TVC();\n\n  std::function<double()> grab_theta_a_cmd;\n  std::function<double()> grab_theta_b_cmd;\n  std::function<double()> grab_theta_c_cmd;\n  std::function<double()> grab_theta_d_cmd;\n  std::vector<ENG *> S2_Eng_list;\n  std::vector<ENG *> S3_Eng_list;\n\n private:\n  /* Internal Initializers */\n  void default_data();\n\n  /* State */\n  enum TVC_TYPE mtvc; /* *o  (--)      see TVC_TYPE */\n\n  /* Constants */\n  double gtvc; /* *o  (--)    TVC nozzle deflection gain n*/\n\n  double theta_a_cmd;  /* *o (r)  Store first actuator command */\n  double theta_b_cmd;  /* *o (r)  Store second actuator command */\n  double theta_c_cmd;  /* *o (r)  Store third actuator command */\n  double theta_d_cmd;  /* *o (r)  Store fourth actuator command */\n  double ActOutput1;   /* *o (r)  Store first actuator output value for trick data record */\n  double ActOutput2;   /* *o (r)  Store second actuator output value for trick data record */\n  double ActOutput3;   /* *o (r)  Store third actuator output value for trick data record */\n  double ActOutput4;   /* *o (r)  Store fourth actuator output value for trick data record */\n\n  VECTOR(Q_TVC, 6);    /* *o (--) External force generated by the rocket engines */\n};\n\n#endif  // __TVC_HH__\n", "meta": {"hexsha": "0fcf80756ea1b7991e8f422b1efb84b52c5e5ca5", "size": 2330, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/dm/include/Tvc.hh", "max_stars_repo_name": "ultype/Next-simulation", "max_stars_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "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/dm/include/Tvc.hh", "max_issues_repo_name": "ultype/Next-simulation", "max_issues_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "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/dm/include/Tvc.hh", "max_forks_repo_name": "ultype/Next-simulation", "max_forks_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "avg_line_length": 30.2597402597, "max_line_length": 93, "alphanum_fraction": 0.6369098712, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.15272217311588052}}
{"text": "#include \"AssemblyOptions.hpp\"\nusing namespace ChanZuckerberg;\nusing namespace shasta;\n\n// Boost libraries.\n#include <boost/tokenizer.hpp>\n\n// Standard library.\n#include\"stdexcept.hpp\"\n\n\n\n// Add the AssemblyOptions to a Boost option description object.\nvoid AssemblyOptions::add(boost::program_options::options_description& options)\n{\n    using boost::program_options::value;\n\n    options.add_options()\n\n        (\"Reads.minReadLength\",\n        value<int>(&Reads.minReadLength)->\n        default_value(10000),\n        \"Read length cutoff.\")\n\n        (\"Reads.palindromicReads.maxSkip\",\n        value<int>(&Reads.palindromicReads.maxSkip)->\n        default_value(100),\n        \"Used for palindromic read detection.\")\n\n        (\"Reads.palindromicReads.maxMarkerFrequency\",\n        value<int>(&Reads.palindromicReads.maxMarkerFrequency)->\n        default_value(10),\n        \"Used for palindromic read detection.\")\n\n        (\"Reads.palindromicReads.alignedFractionThreshold\",\n        value<double>(&Reads.palindromicReads.alignedFractionThreshold)->\n        default_value(0.1, \"0.1\"),\n        \"Used for palindromic read detection.\")\n\n        (\"Reads.palindromicReads.nearDiagonalFractionThreshold\",\n        value<double>(&Reads.palindromicReads.nearDiagonalFractionThreshold)->\n        default_value(0.1, \"0.1\"),\n        \"Used for palindromic read detection.\")\n\n        (\"Reads.palindromicReads.deltaThreshold\",\n         value<int>(&Reads.palindromicReads.deltaThreshold)->\n         default_value(100),\n         \"Used for palindromic read detection.\")\n\n        (\"Kmers.k\",\n        value<int>(&Kmers.k)->\n        default_value(10),\n        \"Length of marker k-mers (in run-length space).\")\n\n        (\"Kmers.probability\",\n        value<double>(&Kmers.probability)->\n        default_value(0.1, \"0.1\"),\n        \"Probability that a k-mer is used as a marker.\")\n\n        (\"MinHash.m\",\n        value<int>(&MinHash.m)->\n        default_value(4),\n        \"The number of consecutive markers that define a MinHash/LowHash feature.\")\n\n        (\"MinHash.hashFraction\",\n        value<double>(&MinHash.hashFraction)->\n        default_value(0.01, \"0.01\"),\n        \"Defines how low a hash has to be to be used with the LowHash algorithm.\")\n\n        (\"MinHash.minHashIterationCount\",\n        value<int>(&MinHash.minHashIterationCount)->\n        default_value(10),\n        \"The number of MinHash/LowHash iterations.\")\n\n        (\"MinHash.maxBucketSize\",\n        value<int>(&MinHash.maxBucketSize)->\n        default_value(10),\n        \"The maximum bucket size to be used by the MinHash/LowHash algoritm.\")\n\n        (\"MinHash.minFrequency\",\n        value<int>(&MinHash.minFrequency)->\n        default_value(2),\n        \"The minimum number of times a pair of reads must be found by the MinHash/LowHash algorithm \"\n        \"in order to be considered a candidate alignment.\")\n\n        (\"Align.maxSkip\",\n        value<int>(&Align.maxSkip)->\n        default_value(30),\n        \"The maximum number of markers that an alignment is allowed to skip.\")\n\n        (\"Align.maxTrim\",\n        value<int>(&Align.maxTrim)->\n        default_value(30),\n        \"The maximum number of trim markers tolerated at the beginning and end of an alignment.\")\n\n        (\"Align.maxMarkerFrequency\",\n        value<int>(&Align.maxMarkerFrequency)->\n        default_value(10),\n        \"Marker frequency threshold.\")\n\n        (\"Align.minAlignedMarkerCount\",\n        value<int>(&Align.minAlignedMarkerCount)->\n        default_value(100),\n        \"The minimum number of aligned markers for an alignment to be used.\")\n\n        (\"ReadGraph.maxAlignmentCount\",\n        value<int>(&ReadGraph.maxAlignmentCount)->\n        default_value(6),\n        \"The maximum alignments to be kept for each read.\")\n\n        (\"ReadGraph.minComponentSize\",\n        value<int>(&ReadGraph.minComponentSize)->\n        default_value(100),\n        \"The minimum size (number of oriented reads) of a connected component \"\n        \"of the read graph to be kept.\")\n\n        (\"ReadGraph.maxChimericReadDistance\",\n        value<int>(&ReadGraph.maxChimericReadDistance)->\n        default_value(2),\n        \"Used for chimeric read detection.\")\n\n        (\"MarkerGraph.minCoverage\",\n        value<int>(&MarkerGraph.minCoverage)->\n        default_value(10),\n        \"Minimum number of markers for a marker graph vertex.\")\n\n        (\"MarkerGraph.maxCoverage\",\n        value<int>(&MarkerGraph.maxCoverage)->\n        default_value(100),\n        \"Maximum number of markers for a marker graph vertex.\")\n\n        (\"MarkerGraph.lowCoverageThreshold\",\n        value<int>(&MarkerGraph.lowCoverageThreshold)->\n        default_value(0),\n        \"Used during approximate transitive reduction.\")\n\n        (\"MarkerGraph.highCoverageThreshold\",\n        value<int>(&MarkerGraph.highCoverageThreshold)->\n        default_value(256),\n        \"Used during approximate transitive reduction.\")\n\n        (\"MarkerGraph.maxDistance\",\n        value<int>(&MarkerGraph.maxDistance)->\n        default_value(30),\n        \"Used during approximate transitive reduction.\")\n\n        (\"MarkerGraph.edgeMarkerSkipThreshold\",\n        value<int>(&MarkerGraph.edgeMarkerSkipThreshold)->\n        default_value(100),\n        \"Used during approximate transitive reduction.\")\n\n        (\"MarkerGraph.pruneIterationCount\",\n        value<int>(&MarkerGraph.pruneIterationCount)->\n        default_value(6),\n        \"Number of prune iterations.\")\n\n        (\"MarkerGraph.simplifyMaxLength\",\n        value<string>(&MarkerGraph.simplifyMaxLength)->\n        default_value(\"10,100,1000\"),\n        \"Maximum lengths (in markers) used at each iteration of simplifyMarkerGraph.\")\n\n        (\"Assembly.markerGraphEdgeLengthThresholdForConsensus\",\n        value<int>(&Assembly.markerGraphEdgeLengthThresholdForConsensus)->\n        default_value(1000),\n        \"Controls assembly of long marker graph edges.\")\n\n        (\"Assembly.consensusCaller\",\n        value<string>(&Assembly.consensusCaller)->\n        default_value(\"SimpleConsensusCaller\"),\n        \"Selects the consensus caller for repeat counts.\\n\"\n        \"SimpleConsensusCaller is the only choice currently\\n\"\n        \"supported by the Shasta executable.\\n\"\n        \"Other choices are available with the Shasta library.\")\n\n        (\"Assembly.useMarginPhase\",\n        value<string>(&Assembly.useMarginPhase)->\n        default_value(\"False\"),\n        \"Used to turn on margin phase.\")\n\n        (\"Assembly.storeCoverageData\",\n        value<string>(&Assembly.storeCoverageData)->\n        default_value(\"False\"),\n        \"Used to request storing coverage data.\")\n        ;\n}\n\n\n\nvoid AssemblyOptions::ReadsOptions::PalindromicReadOptions::write(ostream& s) const\n{\n    s << \"palindromicReads.maxSkip = \" << maxSkip << \"\\n\";\n    s << \"palindromicReads.maxMarkerFrequency = \" << maxMarkerFrequency << \"\\n\";\n    s << \"palindromicReads.alignedFractionThreshold = \" << alignedFractionThreshold << \"\\n\";\n    s << \"palindromicReads.nearDiagonalFractionThreshold = \" << nearDiagonalFractionThreshold << \"\\n\";\n    s << \"palindromicReads.deltaThreshold = \" << deltaThreshold << \"\\n\";\n}\n\n\n\nvoid AssemblyOptions::ReadsOptions::write(ostream& s) const\n{\n    s << \"[Reads]\\n\";\n    s << \"minReadLength = \" << minReadLength << \"\\n\";\n    palindromicReads.write(s);\n}\n\n\n\nvoid AssemblyOptions::KmersOptions::write(ostream& s) const\n{\n    s << \"[Kmers]\\n\";\n    s << \"k = \" << k << \"\\n\";\n    s << \"probability = \" << probability << \"\\n\";\n}\n\n\n\nvoid AssemblyOptions::MinHashOptions::write(ostream& s) const\n{\n    s << \"[MinHash]\\n\";\n    s << \"m = \" << m << \"\\n\";\n    s << \"hashFraction = \" << hashFraction << \"\\n\";\n    s << \"minHashIterationCount = \" << minHashIterationCount << \"\\n\";\n    s << \"maxBucketSize = \" << maxBucketSize << \"\\n\";\n    s << \"minFrequency = \" << minFrequency << \"\\n\";\n}\n\n\n\nvoid AssemblyOptions::AlignOptions::write(ostream& s) const\n{\n    s << \"[Align]\\n\";\n    s << \"maxSkip = \" << maxSkip << \"\\n\";\n    s << \"maxTrim = \" << maxTrim << \"\\n\";\n    s << \"maxMarkerFrequency = \" << maxMarkerFrequency << \"\\n\";\n    s << \"minAlignedMarkerCount = \" << minAlignedMarkerCount << \"\\n\";\n}\n\n\n\nvoid AssemblyOptions::ReadGraphOptions::write(ostream& s) const\n{\n    s << \"[ReadGraph]\\n\";\n    s << \"maxAlignmentCount = \" << maxAlignmentCount << \"\\n\";\n    s << \"minComponentSize = \" << minComponentSize << \"\\n\";\n    s << \"maxChimericReadDistance = \" << maxChimericReadDistance << \"\\n\";\n}\n\n\nvoid AssemblyOptions::MarkerGraphOptions::write(ostream& s) const\n{\n    s << \"[MarkerGraph]\\n\";\n    s << \"minCoverage = \" << minCoverage << \"\\n\";\n    s << \"maxCoverage = \" << maxCoverage << \"\\n\";\n    s << \"lowCoverageThreshold = \" << lowCoverageThreshold << \"\\n\";\n    s << \"highCoverageThreshold = \" << highCoverageThreshold << \"\\n\";\n    s << \"maxDistance = \" << maxDistance << \"\\n\";\n    s << \"edgeMarkerSkipThreshold = \" << edgeMarkerSkipThreshold << \"\\n\";\n    s << \"pruneIterationCount = \" << pruneIterationCount << \"\\n\";\n    s << \"simplifyMaxLength = \" << simplifyMaxLength << \"\\n\";\n}\n\n\n\nvoid AssemblyOptions::AssemblyOptionsInner::write(ostream& s) const\n{\n    s << \"[Assembly]\\n\";\n    s << \"markerGraphEdgeLengthThresholdForConsensus = \" <<\n        markerGraphEdgeLengthThresholdForConsensus << \"\\n\";\n    s << \"consensusCaller = \" <<\n        consensusCaller << \"\\n\";\n    s << \"useMarginPhase = \" <<\n        useMarginPhase << \"\\n\";\n    s << \"storeCoverageData = \" <<\n        storeCoverageData << \"\\n\";\n}\n\n\n\nvoid AssemblyOptions::write(ostream& s) const\n{\n    Reads.write(s);\n    s << \"\\n\";\n    Kmers.write(s);\n    s << \"\\n\";\n    MinHash.write(s);\n    s << \"\\n\";\n    Align.write(s);\n    s << \"\\n\";\n    ReadGraph.write(s);\n    s << \"\\n\";\n    MarkerGraph.write(s);\n    s << \"\\n\";\n    Assembly.write(s);\n    s << endl;\n}\n\n\n\nvoid AssemblyOptions::MarkerGraphOptions::parseSimplifyMaxLength()\n{\n    simplifyMaxLengthVector.clear();\n\n    boost::tokenizer< boost::char_separator<char> > tokenizer(\n        simplifyMaxLength, boost::char_separator<char>(\",\"));\n    for(const string token: tokenizer) {\n        try {\n            size_t numberEndsHere;\n            const size_t value = std::stoi(token, &numberEndsHere);\n            if(numberEndsHere != token.size()) {\n                throw runtime_error(\"Error parsing MarkerGraph.simplifyMaxLength \" +\n                    simplifyMaxLength);\n            }\n            simplifyMaxLengthVector.push_back(value);\n        } catch(std::invalid_argument e) {\n            throw runtime_error(\"Error parsing MarkerGraph,simplifyMaxLength \" +\n                simplifyMaxLength);\n        }\n    }\n\n}\n\n\n\n", "meta": {"hexsha": "bf19e0daaeb5b125ad7e210fa29cec9584fc81c5", "size": 10500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src-static-executable/AssemblyOptions.cpp", "max_stars_repo_name": "ekg/shasta", "max_stars_repo_head_hexsha": "e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01", "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-static-executable/AssemblyOptions.cpp", "max_issues_repo_name": "ekg/shasta", "max_issues_repo_head_hexsha": "e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01", "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-static-executable/AssemblyOptions.cpp", "max_forks_repo_name": "ekg/shasta", "max_forks_repo_head_hexsha": "e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01", "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.3076923077, "max_line_length": 102, "alphanum_fraction": 0.6285714286, "num_tokens": 2479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.15272217311588052}}
{"text": "/*! \\file demo_1d_containers.cpp\n  \\brief An example to demonstrate simple 1D plotting using a range of different STL containers.\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A Bristow 2008, 2012, 2021\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// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_1d_containers_1\n\n/*`First a few includes to use Boost.Plot and various STL containers:\n*/\n#include <boost/svg_plot/svg_1d_plot.hpp>\n  // using namespace boost::svg;\n#include <boost/array.hpp>\n  using boost::array;\n#include <vector>\n  using std::vector;\n#include <set>\n  using std::set; // Automatically sorted - though this is not useful to the plot process.\n  using std::multiset; // At present using std::multiset, allowing duplicates, plot does not indicate duplicates.\n  // With 2_D data in std::multimap, duplicate values are usefully displayed.\n#include <list>\n  using std::list;\n#include <deque>\n  using std::deque;\n\n//] [/demo_1d_containers_1]\n\nint main()\n{\n  {\n//[demo_1d_containers_2\n\n/*`STL vector is used as the container,\nand fictional values are inserted using push_back.\nSince this is a 1-D plot the order of data values is not important.\n*/\n  std::vector<float> values;\n  values.push_back(3.1f);\n  values.push_back(-5.5f);\n  values.push_back(8.7f);\n  values.push_back(0.5f);\n\n/*`The constructor initializes a new 1D plot, called `my_plot`, and also sets all the many default values.\n*/\n  \n  using namespace boost::svg;\n  boost::svg::svg_1d_plot my_plot;\n\n/*`Setting (member) functions are fairly self-explanatory:\nTitle provides a title at the top for the whole plot,\nand plot adds a (unnamed) data series (naming isn't very useful if there is only one data series).\n*/\n  my_plot.title(\"vector&lt;float&gt; example\");\n/*`\n[note One must insert the XML character entity equivalents of &lt; for < and &gt; for >).]\n*/\n  my_plot.plot(values);\n\n/*`Write the SVG to a file.\n*/\n  my_plot.write(\"./demo_1d_vector_float.svg\");\n//] [/demo_1d_containers_2]\n  }\n\n  {\n//[demo_1d_containers_3\n\n  static boost::array<const long double, 4> values {3.1L,-5.5L, 8.7L, 0.5L};\n  //! \\note Using @c long double provokes an expected warning about conversion from 'T' to 'const double', possible loss of data.\n  boost::svg::svg_1d_plot my_plot;\n  my_plot.title(\"array&lt;long double&gt; example\");\n  my_plot.plot(values);\n  my_plot.write(\"./demo_1d_array_long_double.svg\");\n//] [/demo_1d_containers_3]\n  }\n\n  {\n//[demo_1d_containers_4\n/*`If the container type is a set, then it can be filled with insert:*/\n  std::set<double> values;\n  values.insert(-8.4);\n  values.insert(-2.3);\n  values.insert(0.1);\n  values.insert(5.6);\n  values.insert(7.8);\n\n  boost::svg::svg_1d_plot my_plot;\n  my_plot.title(\"set&lt;double&gt; example\");\n  my_plot.plot(values);\n  my_plot.write(\"./demo_1d_set_double.svg\");\n//] [/demo_1d_containers_4]\n  }\n\n  {\n//[demo_1d_containers_5\n/*`If the container type is a list, then it can be filled with push_back or push_front:*/\n  std::list<double> values;\n  values.push_back(-8.4);\n  values.push_back(-2.3);\n  values.push_back(0.1);\n  values.push_back(5.6);\n  values.push_back(7.8);\n  boost::svg::svg_1d_plot my_plot;\n  my_plot.title(\"list&lt;double&gt; example\");\n  my_plot.plot(values);\n  my_plot.write(\"./demo_1d_list_double.svg\");\n//] [/demo_1d_containers_5]\n  }\n\n  {\n//[demo_1d_containers_6\n/*`If the container type is a deque, then it can be filled with push_back or push_front:*/\n  std::deque<double> values;\n  values.push_front(-8.4);\n  values.push_front(-2.3);\n  values.push_front(0.1);\n  values.push_front(5.6);\n  values.push_front(7.8);\n\n  boost::svg::svg_1d_plot my_plot;\n  my_plot.title(\"deque&lt;double&gt; example\");\n  my_plot.plot(values);\n  my_plot.x_label(\"X values as doubles\");\n\n  my_plot.write(\"./demo_1d_deque_double.svg\");\n//] [/demo_1d_containers_6]\n  }\n  return 0;\n} // int main()\n\n/*\nSample output:\n//[demo_1d_containers_output\n\ndemo_1d_containers.cpp\ndemo_1d_containers.vcxproj -> I:\\Cpp\\SVG_plot\\svg_plot\\x64\\Release\\demo_1d_containers.exe\nAutorun \"I:\\Cpp\\SVG_plot\\svg_plot\\x64\\Release\\demo_1d_containers.exe\"\nPlot written to file ./demo_1d_vector_float.svg.\nPlot written to file ./demo_1d_array_long_double.svg.\nPlot written to file ./demo_1d_set_double.svg.\nPlot written to file ./demo_1d_list_double.svg.\nPlot written to file ./demo_1d_deque_double.svg.\n//] [/demo_1d_containers_output]\n*/\n", "meta": {"hexsha": "786d4d2e574cdf0305bdf477792fa50657ab447a", "size": 4784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_1d_containers.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_1d_containers.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_1d_containers.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 30.4713375796, "max_line_length": 129, "alphanum_fraction": 0.7261705686, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.15264503525280454}}
{"text": "/*! \\file demo_2d_autoscaling_vector.cpp\n    \\brief Demonstration of autoscaling in 2D plots.\n    \\details  An example to demonstrate simplest 2d *default* settings.\n     See also auto_2d_plot.cpp for a wider range of use.\n\n    \\date 20 Mar 2009\n    \\author Paul A. Bristow\n*/\n// Copyright Paul A Bristow 2009, 2021\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// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_2d_autoscaling_vector_1\n\n/*`As always, we need a few includes to use Boost.Plot:\n*/\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n//using namespace boost::svg;\n//using boost::svg::svg_2d_plot;\n#include <boost/svg_plot/detail/pair.hpp>\n//  using boost::svg::detail::operator<<; // Output pair as, for example: 1.23, 4.56\n\n#include <iostream>\n  //using std::cout;\n  //using std::endl;\n  //using std::dec;\n  //using std::hex;\n\n#include <vector>\n//  using std::vector\n#include <tuple>\n// using std::pair;\n// \n//] [demo_2d_autoscaling_vector_1]\n\nint main()\n{\n\n  //[demo_2d_autoscaling_vector_2\n  /*`Some fictional data is pushed into an STL container, here `std::map`:\\n\n\n    This example uses a single map to demonstrate autoscaling.\n    We construct a `std::map` to hold our data-series, and insert some fictional values (that also sorts the data).\n    The 'index' value in [ ] is the X value.\n    */\n  std::vector< std::pair<double, double> > my_vector_data(4);\n//  my_vector_data.push_back(1.1, 3.2);\n  std::pair<double, double> p0 = std::make_pair(1.1, 3.2);\n  my_vector_data[0] = p0;\n  my_vector_data[1] = std::make_pair(7.3, 9.1);\n  my_vector_data[2] = std::make_pair(2.12, 2.4394);\n  my_vector_data[3] = std::make_pair(5.47, 5.3861);\n  my_vector_data.push_back(p0);\n\n  for (std::size_t i = 0; i < my_vector_data.size(); i++)\n  { \n    using boost::svg::detail::operator<<; // Output pairs as, for example: 1.23, 4.56\n    std::cout << my_vector_data[i] << std::endl; \n  }\n\n  try\n  {\n    // try'n'catch blocks are needed to ensure error messages from any exceptions are shown by the catch block below.\n    using boost::svg::svg_2d_plot;\n    svg_2d_plot my_2d_plot; // Construct a plot with all the default constructor values.\n    my_2d_plot.title(\"Autoscaling 2d Values in a vector.\"); // Add a string title of the plot.\n\n/*`We can show the ranges before  autoscaling;\n*/\n    std::cout << \"X-min \" << my_2d_plot.x_range().first << \", X-max \" << my_2d_plot.x_range().second << std::endl;\n    std::cout << \"Y-min \" << my_2d_plot.y_range().first << \", Y-max \"  << my_2d_plot.y_range().second << std::endl;\n\n/*` With the defaults ranges would be -10 to +10 for both X and Y axes.  We could chose our own ranges thus:\n    `.x_range(0, 6) // Add a range for the X-axis.\n    .y_range(0, 10) // Add a range for the Y-axis.`\n  Or we can use autoscaling.\n\n*/\n    my_2d_plot.xy_autoscale(my_vector_data); // Autoscale both X and Y axes.\n\n    std::cout << \"X-axis autoscaled minimum tick value = \" << my_2d_plot.x_auto_min_value() \n      << \" to max \" << my_2d_plot.x_auto_max_value() << \" with \" << my_2d_plot.x_auto_ticks() << \" ticks at \" \n      << my_2d_plot.x_auto_tick_interval() << \" tick intervals.\" << std::endl;\n    std::cout << \"Y-axis autoscaled minimum tick value = \" << my_2d_plot.y_auto_min_value_ \n        << \" to max \" << my_2d_plot.y_auto_max_value() << \" with \" << my_2d_plot.y_auto_ticks() << \" ticks at \" \n      << my_2d_plot.y_auto_tick_interval() << \" tick intervals.\"<< std::endl;\n    \n    my_2d_plot.x_autoscale(true); // Confirm that want to use default of using the autoscaling.\n  //  my_2d_plot.y_autoscale(false); // Revert to using any range selected, or the default range -10 to +10.\n\n    std::cout << \"Y-axis autoscaled minimum tick value = \" << my_2d_plot.y_auto_min_value_ \n        << \" to max \" << my_2d_plot.y_auto_max_value() << \" with \" << my_2d_plot.y_auto_ticks() << \" ticks at \" \n      << my_2d_plot.y_auto_tick_interval() << \" tick intervals.\"<< std::endl;\n\n    \n /*`This says use the entire STL `std::map` container `my_vector_data` to set both X and Y ranges.\n (The data used to autoscale the range(s) does not have to be the same as the data being plotted.\n For example, if we have analysed a product and know that an attribute like strength can only decline as the product ages,\n it would make sense to use the reference 'as new' data to scale the plot for the 'aged' product samples).\n */\n\n    std::cout << std::boolalpha \n      << \"X-autoscale \" << my_2d_plot.x_autoscale() << \", X-autoscale_check_limits \" << my_2d_plot.autoscale_check_limits() << std::endl;\n    std::cout << \"Y-min \" << my_2d_plot.y_range().first << \", Y-max \"  << my_2d_plot.y_range().second << std::endl;\n\n    // std::cout << \"X-min \" << my_2d_plot.\n\n    /*`Then add the (one but could be more) data-series, @c my_vector_data and a description, and how the data-points are to be marked,\n    here a circle with a diameter of 5 pixels, without a line joining the points (also the default).\n    */\n    my_2d_plot.plot(my_vector_data, \"2d Values\").size(8);\n\n    /*`To use all these settings, finally write the plot to file.\n    */\n    my_2d_plot.write(\"./demo_2d_autoscaling_vector.svg\");\n\n    std::cout << \"Wrote SVG XML to file \" << \"./demo_2d_autoscaling_vector.svg\" << std::endl;\n\n    //] [demo_2d_autoscaling_vector_2]\n\n  }\n  catch (const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\n//[demo_2d_autoscaling_vector_output\n\nOutput:\nChecked: x_min 1.1, x_max 7.3, y_min 2.4394, y_max 9.1, 5 'good' values, 0 values at limits.\nX-axis autoscaled minimum tick value = 1 to max 8\nY-axis autoscaled minimum value = 2 to max 2\nX min -10, X max 10\nY min -10, Y max 10\n\n  Xautoscale true, X-autoscale_check_limits true\n*/\n\n", "meta": {"hexsha": "5e3ee2d2f4ec7530ff544e96f403463341c0ae68", "size": 6182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_autoscaling_vector.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_autoscaling_vector.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_autoscaling_vector.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 40.1428571429, "max_line_length": 137, "alphanum_fraction": 0.6776124232, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.15233350794079803}}
{"text": "//  Copyright (c) 2007-2012 Hartmut Kaiser\n//  Copyright (c) 2014 Agustin Berge\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#if !defined(HPX_UTIL_DATE_TIME_CHRONO_APR_10_2012_0449PM)\n#define HPX_UTIL_DATE_TIME_CHRONO_APR_10_2012_0449PM\n\n#include <hpx/hpx_fwd.hpp>\n#include <boost/chrono/chrono.hpp>\n#include <boost/date_time/posix_time/posix_time_duration.hpp>\n#include <boost/date_time/posix_time/ptime.hpp>\n\n#if defined(HPX_WITH_CXX11_CHRONO)\n#include <chrono>\n#endif\n\nnamespace hpx { namespace util\n{\n    template <typename Clock, typename Duration>\n    boost::posix_time::ptime\n    to_ptime(boost::chrono::time_point<Clock, Duration> const& from)\n    {\n        typedef boost::chrono::nanoseconds duration_type;\n        typedef duration_type::rep rep_type;\n        rep_type d = boost::chrono::duration_cast<duration_type>(\n            from.time_since_epoch()).count();\n        rep_type sec = d / 1000000000;\n        rep_type nsec = d % 1000000000;\n        return boost::posix_time::from_time_t(0) +\n\n            boost::posix_time::seconds(static_cast<long>(sec)) +\n#ifdef BOOST_DATE_TIME_HAS_NANOSECONDS\n            boost::posix_time::nanoseconds(nsec);\n#else\n            boost::posix_time::microseconds((nsec+500)/1000);\n#endif\n    }\n\n    template <typename Clock, typename Duration>\n    boost::posix_time::time_duration\n    to_time_duration(boost::chrono::duration<Clock, Duration> const& from)\n    {\n        typedef boost::chrono::nanoseconds duration_type;\n        typedef duration_type::rep rep_type;\n        rep_type d = boost::chrono::duration_cast<duration_type>(from).count();\n        rep_type sec = d / 1000000000;\n        rep_type nsec = d % 1000000000;\n        return boost::posix_time::seconds(static_cast<long>(sec)) +\n#ifdef BOOST_DATE_TIME_HAS_NANOSECONDS\n            boost::posix_time::nanoseconds(nsec);\n#else\n            boost::posix_time::microseconds((nsec+500)/1000);\n#endif\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    struct posix_clock\n    {\n        typedef boost::int_least64_t rep;\n        typedef boost::nano period;\n        typedef boost::chrono::duration<rep, period> duration;\n        typedef boost::chrono::time_point<posix_clock, duration> time_point;\n        BOOST_STATIC_CONSTEXPR bool is_steady = false;\n\n        static BOOST_FORCEINLINE time_point now() BOOST_NOEXCEPT\n        {\n            return from_ptime(boost::get_system_time());\n        }\n\n        static boost::posix_time::ptime to_ptime(time_point const& t) BOOST_NOEXCEPT\n        {\n            return boost::posix_time::from_time_t(0) +\n#if defined(BOOST_DATE_TIME_HAS_NANOSECONDS)\n                boost::posix_time::nanoseconds(t.time_since_epoch().count());\n#else\n                boost::posix_time::microseconds(t.time_since_epoch().count() / 1000);\n#endif\n        }\n\n        static time_point from_ptime(boost::posix_time::ptime const& t) BOOST_NOEXCEPT\n        {\n            return time_point(duration(\n              (t - boost::posix_time::from_time_t(0)).total_nanoseconds()));\n        }\n    };\n\n    class steady_time_point\n    {\n        typedef boost::chrono::steady_clock::time_point value_type;\n\n    public:\n        steady_time_point(value_type const& abs_time)\n          : _abs_time(abs_time)\n        {}\n\n        template <typename Clock, typename Duration>\n        steady_time_point(boost::chrono::time_point<Clock, Duration> const& abs_time)\n          : _abs_time(boost::chrono::steady_clock::now()\n              + (abs_time - Clock::now()))\n        {}\n\n        steady_time_point(boost::posix_time::ptime const& abs_time)\n          : _abs_time(boost::chrono::steady_clock::now()\n              + (posix_clock::from_ptime(abs_time) - posix_clock::now()))\n        {}\n\n#if defined(HPX_WITH_CXX11_CHRONO)\n        template <typename Clock, typename Duration>\n        steady_time_point(std::chrono::time_point<Clock, Duration> const& std_abs_time)\n        {\n            boost::chrono::nanoseconds rel_time(\n                std::chrono::duration_cast<std::chrono::nanoseconds>(\n                    std_abs_time - Clock::now()).count());\n\n            _abs_time = boost::chrono::steady_clock::now() + rel_time;\n        }\n#endif\n\n        value_type const& value() const BOOST_NOEXCEPT\n        {\n            return _abs_time;\n        }\n\n    private:\n        value_type _abs_time;\n    };\n\n    class steady_duration\n    {\n        typedef boost::chrono::steady_clock::duration value_type;\n\n    public:\n        steady_duration(value_type const& rel_time)\n          : _rel_time(rel_time)\n        {}\n\n        template <typename Rep, typename Period>\n        steady_duration(boost::chrono::duration<Rep, Period> const& rel_time)\n          : _rel_time(boost::chrono::duration_cast<value_type>(rel_time))\n        {\n            if (_rel_time < rel_time)\n                ++_rel_time;\n        }\n\n        steady_duration(boost::posix_time::time_duration const& rel_time)\n          : _rel_time(rel_time.total_nanoseconds())\n        {}\n\n#if defined(HPX_WITH_CXX11_CHRONO)\n        template <typename Rep, typename Period>\n        steady_duration(std::chrono::duration<Rep, Period> const& std_rel_time)\n        {\n            boost::chrono::nanoseconds rel_time(\n                std::chrono::duration_cast<std::chrono::nanoseconds>(\n                    std_rel_time).count());\n            \n            _rel_time = boost::chrono::duration_cast<value_type>(rel_time);\n            if (_rel_time < rel_time)\n                ++_rel_time;\n        }\n#endif\n\n        value_type const& value() const BOOST_NOEXCEPT\n        {\n            return _rel_time;\n        }\n\n        boost::chrono::steady_clock::time_point from_now() const BOOST_NOEXCEPT\n        {\n            return boost::chrono::steady_clock::now() + _rel_time;\n        }\n\n    private:\n        value_type _rel_time;\n    };\n\n    ///////////////////////////////////////////////////////////////////////////\n    template <typename Clock>\n    struct chrono_traits\n    {\n        typedef typename Clock::duration duration_type;\n        typedef typename Clock::time_point time_type;\n\n        static time_type now() BOOST_NOEXCEPT\n        {\n            return Clock::now();\n        }\n\n        static time_type add(time_type t, duration_type d)\n        {\n            return t + d;\n        }\n\n        static duration_type subtract(time_type t1, time_type t2)\n        {\n            return t1 - t2;\n        }\n\n        static bool less_than(time_type t1, time_type t2)\n        {\n            return t1 < t2;\n        }\n\n        static boost::posix_time::time_duration to_posix_duration(duration_type d)\n        {\n#ifdef BOOST_DATE_TIME_HAS_NANOSECONDS\n            return boost::posix_time::nanoseconds(\n                boost::chrono::duration_cast<boost::chrono::nanoseconds>(d).count());\n#else\n            return boost::posix_time::microseconds(\n                boost::chrono::duration_cast<boost::chrono::microseconds>(d).count());\n#endif\n        }\n    };\n}}\n\n#endif\n", "meta": {"hexsha": "4f5711e5ddf07c4717ab6079814a20961decbb20", "size": 7048, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hpx/util/date_time_chrono.hpp", "max_stars_repo_name": "Titzi90/hpx", "max_stars_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "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": "hpx/util/date_time_chrono.hpp", "max_issues_repo_name": "Titzi90/hpx", "max_issues_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "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": "hpx/util/date_time_chrono.hpp", "max_forks_repo_name": "Titzi90/hpx", "max_forks_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "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.0363636364, "max_line_length": 87, "alphanum_fraction": 0.6169125993, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.15230530330972575}}
{"text": "//\n// Created by erik on 9/27/16.\n//\n\n#include \"PhysicsWorld.h\"\n#include \"HitTests.h\"\n#include \"Fixture.h\"\n#include <boost/optional.hpp>\n#include <boost/variant.hpp>\n#include <iostream>\n\nusing namespace spatacs::physics;\nusing spatacs::Vec;\n\n\nnamespace\n{\n    template<class Base>\n    struct GetUnderlyingContainer : public Base\n    {\n        using container_t = typename Base::container_type;\n        container_t& container() { return Base::c; }\n        const container_t& container() const  { return Base::c; }\n    };\n}\n\nvoid PhysicsWorld::pushEvent(Collision evt)\n{\n    mEventQueue.push( std::move(evt) );\n}\n\nconst Object& PhysicsWorld::getObject(ObjectID id) const\n{\n    return getObjectRec(id).object;\n}\n\nvoid PhysicsWorld::setCollisionCallback(PhysicsWorld::collision_callback_fn cb)\n{\n    mCollisionCallback = std::move(cb);\n}\n\nvoid PhysicsWorld::simulate(time_t time_step)\n{\n    mNow = 0.0_s;\n\n    // detect all collisions\n    for(auto& obj : mObjects)\n        detectCollisionsOf(obj.first, time_step);\n\n    // now handle all events\n    while( !mEventQueue.empty() )\n    {\n        auto ev = std::move(mEventQueue.top());\n        mEventQueue.pop();\n\n        ImpactInfo info;\n        info.time = ev.time;\n        info.fixture_A = ev.fA;\n        info.fixture_B = ev.fB;\n        mNow = ev.time;\n        if(ev.time <= time_step) {\n            /// \\todo maybe we should update A and B here to the ev.time state\n            mCollisionCallback(*this, getObject(ev.A), getObject(ev.B), info);\n        }\n    }\n\n    mNow = time_step;\n\n    // update positions\n    for(auto& obr : mObjects)\n    {\n        auto dt = mNow - obr.second.update;\n        obr.second.object.setPosition( obr.second.object.position() + dt * obr.second.object.velocity());\n        obr.second.object.setVelocity( obr.second.object.velocity() + obr.second.acceleration );\n        obr.second.acceleration = velocity_vec{Vec{0, 0, 0}};\n        obr.second.update = 0.0_s;\n    }\n}\n\nvoid PhysicsWorld::detectCollisionsOf(ObjectID id, time_t max_dt, bool all)\n{\n    auto& orec = getObjectRec(id);\n    auto& obj = orec.object;\n    for(auto& fixa : obj) {\n        length_vec original_position = obj.position() - orec.update * obj.velocity();\n        MovingSphere ppath = {original_position, obj.velocity(), fixa.radius(), speed_t(0)};\n        // check ship impact\n        for (auto& target : mObjects) {\n            // no self-intersection, check each pair only once\n            if (target.first == id || (id < target.first && !all))\n                continue;\n            /// \\todo disable projectile-projectile hit tests\n            Object& tobj = target.second.object;\n            for (auto& fix : tobj)\n            {\n                auto opos = tobj.position() - target.second.update * tobj.velocity();\n                MovingSphere tpath = {opos, tobj.velocity(), fix.radius(), speed_t(0)};\n                auto hit = intersect(tpath, ppath);\n                if (hit) {\n                    time_t time = hit.get();\n                    if (time >= mNow && time < max_dt) {\n                        pushEvent(Collision{id, target.first, fixa.userdata(), fix.userdata(), time});\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid PhysicsWorld::filterCollisions(ObjectID id)\n{\n    std::vector<Collision> container = std::move(((GetUnderlyingContainer<decltype(mEventQueue)>&)(mEventQueue)).container());\n    auto nend = std::remove_if(begin(container), end(container), [id](auto& e){ return e.A == id || e.B == id;});\n    container.resize( std::distance(begin(container), nend) );\n\n    // construct a new queue, because I don't know whether we might hav destroyed some invariants in\n    // the process above.\n    mEventQueue = queue_t(Compare(), std::move(container));\n}\n\n\nconst PhysicsWorld::ObjectRecord& PhysicsWorld::getObjectRec(ObjectID id) const\n{\n    return mObjects.at(id);\n}\n\nPhysicsWorld::ObjectRecord& PhysicsWorld::getObjectRec(ObjectID id)\n{\n    return mObjects.at(id);\n}\n\nObjectID PhysicsWorld::spawn(const Object& object)\n{\n    ObjectRecord new_rec;\n    new_rec.object = object;\n    ObjectID id{mFreeID};\n    new_rec.object.setID( id );\n    new_rec.acceleration = velocity_vec(Vec{0, 0, 0});\n    mObjects[id] = std::move(new_rec);\n    ++mFreeID;\n    return id;\n    /// \\todo trigger calculation of collision events.\n}\n\nbool PhysicsWorld::despawn(ObjectID id)\n{\n    auto e = mObjects.erase(id);\n    if( e != 1 )\n    {\n        return false;\n    }\n\n    filterCollisions(id);\n    return true;\n}\n\nvoid PhysicsWorld::applyForce(ObjectID id, force_vec force)\n{\n    /// \\todo this is a fixed end time! Change!\n    time_t application_time = 0.1_s;\n    auto& target = getObjectRec(id);\n    target.acceleration += force * application_time / target.object.mass();\n}\n\nvoid PhysicsWorld::setMass(ObjectID id, mass_t mass)\n{\n    auto& target = getObjectRec(id);\n    target.object.setMass( mass );\n}\n\nvoid PhysicsWorld::applyImpulse(ObjectID id, impulse_vec impulse)\n{\n    auto& target = getObjectRec(id);\n    auto vel_old = target.object.velocity();\n    target.object.setVelocity( vel_old + impulse / target.object.mass() );\n\n    // perform part of the integration now\n    auto dt = mNow - target.update;\n    target.object.setPosition( target.object.position() + dt * vel_old);\n    target.update = mNow;\n\n    // now we can update the collision tests\n    // remove old collisions of id\n    filterCollisions(id);\n    detectCollisionsOf( id, 1.0_s, true );\n}\n\nvoid PhysicsWorld::updateObject(ObjectID id, length_vec new_position, velocity_vec new_veloctiy, mass_t new_mass)\n{\n    auto& target = getObjectRec(id);\n    target.object.setMass( new_mass );\n    target.object.setPosition(new_position);\n    target.object.setVelocity(new_veloctiy);\n}\n\nbool PhysicsWorld::Compare::operator()(const Collision& a, const Collision& b) const\n{\n    return a.time > b.time;\n}\n", "meta": {"hexsha": "4900b1be550f391e95316feaeead2178cc3bbb03", "size": 5843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "physics/PhysicsWorld.cpp", "max_stars_repo_name": "ngc92/SpaTacS", "max_stars_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "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": "physics/PhysicsWorld.cpp", "max_issues_repo_name": "ngc92/SpaTacS", "max_issues_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_issues_repo_licenses": ["MIT"], "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/PhysicsWorld.cpp", "max_forks_repo_name": "ngc92/SpaTacS", "max_forks_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_forks_repo_licenses": ["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.215, "max_line_length": 126, "alphanum_fraction": 0.6385418449, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.28457599814899737, "lm_q1q2_score": 0.152276169434378}}
{"text": "// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-\n// vi: set ts=2 noet:\n\n#ifndef INCLUDED_riflib_HBondedPairGenerator_hh\n#define INCLUDED_riflib_HBondedPairGenerator_hh\n\n// headers\n\n\t// #include <core/pack/rotamer_set/RotamerSet.hh>\n\t// #include <core/pack/rotamer_set/RotamerSetFactory.hh>\n\t// #include <core/pack/dunbrack/RotamerLibrary.hh>\n\t#include <core/pack/dunbrack/RotamerLibraryScratchSpace.hh>\n\t// #include <core/pack/dunbrack/SingleResidueDunbrackLibrary.hh>\n\t// #include <core/pack/task/TaskFactory.hh>\n\t// #include <core/graph/Graph.hh>\n\t// #include <core/pack/packer_neighbors.hh>\n\n\t#include <ObjexxFCL/format.hh>\n\t#include <ObjexxFCL/string.functions.hh>\n\n\t#include <core/chemical/AtomType.hh>\n\t#include <core/chemical/orbitals/OrbitalType.hh>\n\t#include <core/chemical/ChemicalManager.hh>\n\t#include <core/chemical/ResidueTypeSet.hh>\n\t// #include <core/conformation/symmetry/util.hh>\n\t#include <core/conformation/ResidueFactory.hh>\n\t// #include <core/conformation/util.hh>\n\t// #include <core/import_pose/import_pose.hh>\n\t// #include <core/io/silent/SilentFileData.hh>\n\t// #include <core/pose/PDBInfo.hh>\n\t#include <core/pose/Pose.hh>\n\t// #include <core/pose/annotated_sequence.hh>\n\t#include <core/pose/motif/reference_frames.hh>\n\t// #include <core/pose/util.hh>\n\t// #include <core/pose/symmetry/util.hh>\n\t// #include <core/import_pose/import_pose\t.hh>\n\t// #include <core/kinematics/MoveMap.hh>\n\t#include <core/scoring/Energies.hh>\n\t// #include <core/scoring/EnergyGraph.hh>\n\t#include <core/scoring/ScoreFunction.hh>\n\t#include <core/scoring/ScoreFunctionFactory.hh>\n\t// #include <core/scoring/ScoreTypeManager.hh>\n\t// #include <core/scoring/dssp/Dssp.hh>\n\t// #include <core/scoring/etable/Etable.hh>\n\t#include <core/scoring/hbonds/HBondOptions.hh>\n\t// #include <core/scoring/hbonds/HBondSet.hh>\n\t// #include <core/scoring/hbonds/hbonds.hh>\n\t#include <core/scoring/motif/util.hh>\n\n\t#include <core/scoring/methods/EnergyMethodOptions.hh>\n\t// #include <core/scoring/packing/compute_holes_score.hh>\n\t// #include <core/scoring/rms_util.hh>\n\t// #include <core/scoring/sasa.hh>\n\t// #include <core/scoring/symmetry/SymmetricScoreFunction.hh>\n\t#include <numeric/conversions.hh>\n\t#include <numeric/model_quality/rms.hh>\n\t// #include <numeric/random/random.hh>\n\t#include <numeric/xyz.functions.hh>\n\t#include <numeric/xyz.io.hh>\n\t#include <numeric/xyzVector.hh>\n\t// #include <protocols/idealize/IdealizeMover.hh>\n\t// #include <protocols/sicdock/Assay.hh>\n\t// #include <protocols/sic_dock/SICFast.hh>\n\t// #include <protocols/sic_dock/util.hh>\n\t// #include <protocols/sic_dock/read_biounit.hh>\n\t// #include <protocols/simple_moves/MinMover.hh>\n\t// #include <protocols/simple_moves/AddConstraintsToCurrentConformationMover.hh>\n\t// #include <utility/io/izstream.hh>\n\t// #include <utility/io/ozstream.hh>\n\t#include <utility/tools/make_vector1.hh>\n\t// #include <utility/fixedsizearray1.hh>\n\t// #include <utility/file/file_sys_util.hh>\n\t// #include <numeric/geometry/hashing/SixDHasher.hh>\n\t// #include <numeric/HomogeneousTransform.hh>\n\n\t#include <riflib/RotamerGenerator.hh>\n\n\t// #include <apps/pilot/will/will_util.ihh>\n\n\t#include <boost/foreach.hpp>\n\t#include <boost/iterator/iterator_facade.hpp>\n\n\nnamespace devel {\nnamespace scheme {\n\ncore::Real\nget_rot_score(\n\tcore::pose::Pose & pose,\n\tcore::Size ir,\n\tcore::pack::dunbrack::RotamerLibraryScratchSpaceOP scratch\n);\n\nvoid dump_pdb_atom(\n\tstd::ostream & out,\n\tdouble x, double y, double z\n);\n\n\n///@brief generate BCC lattice \"hyper-ring\" to sample rotationr around\n/// the hbond axis as well as tilting the axis a up to short_tol\nutility::vector1<numeric::xyzMatrix<double> >\nget_rotation_samples( double short_tol, double long_tol, double reslang );\n\n\nclass HBondedPairGenerator\n    : public boost::iterator_facade< HBondedPairGenerator,\n                                     core::pose::Pose,\n                                     boost::forward_traversal_tag,\n                                     core::pose::Pose const &\n             \t\t\t\t\t\t>\n{\npublic:\n\tcore::pose::Pose pose_,pose0_;\n\tcore::pack::dunbrack::RotamerLibraryScratchSpaceOP scratch_;\n\t// core::pack::rotamer_set::RotamerSetOP rotset1_,rotset2_;\n\tutility::vector1< utility::vector1< float > > rotset1_, rotset2_;\n\tcore::Size irot1_,irot2_,idon_,iacc_,iorb_,ihbr_,irotindex_start1_,irotindex_start2_;\n\tcore::Size nrots1_,nrots2_;\n\tcore::Size clash_atom_start1_, clash_atom_start2_;\n\tutility::vector1<core::Size> donor_atoms_;\n\tutility::vector1<core::Size> donor_bases_;\n\tutility::vector1<core::Size> acceptor_atoms_;\n\tutility::vector1<utility::vector1<core::Size> > acceptor_orbitals_;\n\tutility::vector1<numeric::xyzMatrix<double> > rot_samples_;\n\tcore::scoring::ScoreFunctionOP score_func_;\n\tcore::id::AtomID align_atom1_, align_atom2_, align_atom3_;\n\tcore::Real score_;\n\tbool fix_donor_, fix_acceptor_;\n\tHBondedPairGenerator(){ irot1_=0; irot2_=0; idon_=0; iacc_=0; iorb_=0; ihbr_=0; }\n\tcore::chemical::ResidueTypeOP rtype1op_, rtype2op_;\n\tvirtual ~HBondedPairGenerator(){}\n\tvoid init(\n\t\tRotamerIndex const & rot_index,\n\t\tstd::string resn1,\n\t\tstd::string resn2,\n\t\tdouble tip_tol=20.0,\n\t\tdouble rot_resl=5.0,\n\t\tdouble rot_range=360.0,\n\t\tbool fix_donor=false,\n\t\tbool fix_acceptor=false,\n\t\tcore::id::AtomID align_atom1 = core::id::AtomID(1,1),\n\t\tcore::id::AtomID align_atom2 = core::id::AtomID(2,1),\n\t\tcore::id::AtomID align_atom3 = core::id::AtomID(3,1),\n\t\tstd::map<std::string,core::pose::Pose> const & exemplars = std::map<std::string,core::pose::Pose>()\n\t);\n\tbool has_more_samples() const { return irot1_!=0; }\n\tcore::Size raw_num_samples() const {\n\t\tcore::Size nacc_orbs = 0;\n\t\tfor(core::Size i = 1; i <= acceptor_orbitals_.size(); ++i)\n\t\t\tnacc_orbs += acceptor_orbitals_[i].size();\n\t\treturn rot_samples_.size()              *\n\t\t\t   nacc_orbs                        *\n\t\t       nrots2_                          *\n\t\t       donor_atoms_.size()              *\n\t\t       nrots1_                          ;\n\t}\n\tsize_t rot1_of_current() const { return irot1_ + irotindex_start1_ - 1 ; }\n\tsize_t rot2_of_current() const { return irot2_ + irotindex_start2_ - 1 ; }\n\tcore::Real score_of_current() const { return score_; }\nprivate:\n    friend class boost::iterator_core_access;\n    core::pose::Pose const & dereference() const {\n    \treturn pose_;\n    }\n    void update_chi(){\n    \tif( ! fix_donor_ )\n\t\t\tfor(core::Size ichi=1; ichi <= pose0_.residue(1).nchi(); ++ichi)\n\t\t\t\tpose0_.set_chi(ichi,1, rotset1_[irot1_][ichi] );\n\t\tif( ! fix_acceptor_ )\n\t\t\tfor(core::Size ichi=1; ichi <= pose0_.residue(2).nchi(); ++ichi)\n\t\t\t\tpose0_.set_chi(ichi,2, rotset2_[irot2_][ichi] );\n    }\n\n    virtual bool update_hb_and_score(bool=true) { utility_exit_with_message(\"Abstract base class\"); }\n\n    void increment(){\n    \tbool clash = true;\n    \twhile(clash){\n\t\t\t// std::cout << \"INCR \" << irot1_ << \" \" << idon_ << \" \" << irot2_ << \" \" << iacc_ << \" \" << iorb_ << \" \" << ihbr_ << std::endl;\n    \t\t++ihbr_;\n\t    \tif( ihbr_  > rot_samples_.size()              ){ ihbr_  = 1; ++iorb_ ; }\n    \t\tif( iorb_  > acceptor_orbitals_[iacc_].size() ){ iorb_  = 1; ++iacc_ ; }\n    \t\tif( iacc_  > acceptor_atoms_.size()           ){ iacc_  = 1; ++irot2_; }\n\t\t\tif( irot2_ > nrots2_                          ){ irot2_ = 1; ++idon_ ; }\n\t\t\tif( idon_  > donor_atoms_.size()              ){ idon_  = 1; ++irot1_;  }\n\t\t\tif( irot1_ > nrots1_                          ){ irot1_ = irot2_ = idon_ = iacc_ = iorb_ = ihbr_ = 0;  return; }\n\t\t\tthis->update_chi();\n\t\t\tclash = ! this->update_hb_and_score(ihbr_==1);\n\t\t}\n    }\n    bool equal(HBondedPairGenerator const& o) const {\n    \treturn o.irot1_==irot1_ && o.irot2_==irot2_ && o.iacc_==iacc_ && o.idon_==idon_ && iorb_==o.iorb_ && ihbr_==o.ihbr_;\n    }\n\n};\n\n// typedef utility::pointer::shared_ptr<HBondedPairGenerator> HBondedPairGeneratorOP;\n\nclass SingleHbondedPairGenerator : public HBondedPairGenerator {\n\n    virtual bool update_hb_and_score(bool realign=true);\n\n};\n\nclass BidentateHbondedPairGenerator : public HBondedPairGenerator {\n\n   virtual bool update_hb_and_score(bool realign=true);\n\n};\n\n}\n}\n\n#endif\n\n", "meta": {"hexsha": "5e62b77eeb14b314ebd68697fb2df059836b36ab", "size": 8075, "ext": "hh", "lang": "C++", "max_stars_repo_path": "apps/rosetta/riflib/HBondedPairGenerator.hh", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "apps/rosetta/riflib/HBondedPairGenerator.hh", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "apps/rosetta/riflib/HBondedPairGenerator.hh", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 37.2119815668, "max_line_length": 131, "alphanum_fraction": 0.6882972136, "num_tokens": 2459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.15222030903126849}}
{"text": "// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-\n// vi: set ts=2 noet:\n//\n// (c) Copyright Rosetta Commons Member Institutions.\n// (c) This file is part of the Rosetta software suite and is made available under license.\n// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.\n// (c) For more information, see http://wsic_dockosettacommons.org. Questions about this casic_dock\n// (c) addressed to University of Waprotocolsgton UW TechTransfer, email: license@u.washington.eprotocols\n\n#ifndef INCLUDED_riflib_CBTooCloseManager_hh\n#define INCLUDED_riflib_CBTooCloseManager_hh\n\n#include <riflib/types.hh>\n#include <riflib/rifdock_typedefs.hh>\n\n#include \"scheme/util/SimpleArray.hh\"\n#include <riflib/RotamerGenerator.hh>\n#include <riflib/ScoreRotamerVsTarget.hh>\n#include <scheme/objective/voxel/VoxelArray.hh>\n\n#include <core/pose/Pose.hh>\n\n#include <string>\n#include <vector>\n\n#include <boost/any.hpp>\n#include <boost/format.hpp>\n\n#include <riflib/util.hh>\n\n#include <ObjexxFCL/format.hh>\n\n\nnamespace devel {\nnamespace scheme {\n\n\n\nstruct CBTooCloseManager {\n\n    float resl_;\n\n    shared_ptr<::scheme::objective::voxel::VoxelArray<3>> voxel_array_;\n\n\n\n\n    CBTooCloseManager(\n        core::pose::Pose const & target,\n        float resl,\n        float too_close_dist,\n        float penalty,\n        size_t max_target_res_atom_idx\n    ) : resl_( resl )\n    {\n        std::cout << \"Creating CB too close grid\" << std::endl;\n        prepare_bounds( target, too_close_dist, max_target_res_atom_idx );\n        create_and_fill_voxel_map( target, too_close_dist, penalty, max_target_res_atom_idx );\n    \n\n        // voxel_array_->dump_pdb(\"CB_too_close.pdb\", 0.1, true, 0.1);\n    }\n\n\n    void\n    prepare_bounds( core::pose::Pose const & target, float too_close_dist, size_t max_target_res_atom_idx ) {\n\n        Eigen::Vector3f lbs( 9e9, 9e9, 9e9 );\n        Eigen::Vector3f ubs( -9e9, -9e9, -9e9 );\n\n        for ( core::Size seqpos = 1; seqpos <= target.size(); seqpos++ ) {\n            core::conformation::Residue const & res = target.residue(seqpos);\n            size_t loop_ub = std::min<size_t>( res.nheavyatoms(), max_target_res_atom_idx );\n            for ( core::Size atno = 1; atno <= loop_ub; atno++ ) { \n\n                numeric::xyzVector<core::Real> xyz = res.xyz(atno);\n                for ( int i = 0; i < 3; i++ ) {\n                    lbs[i] = std::min<float>( lbs[i], xyz[i] );\n                    ubs[i] = std::max<float>( ubs[i], xyz[i] );\n                }\n            }\n            \n        }\n\n        \n        for ( int i = 0; i < 3; i++ ) {\n            lbs[i] -= too_close_dist + resl_ * 2;\n            ubs[i] += too_close_dist + resl_ * 2;\n        }\n\n        // lb_ = lbs;\n        // ub_ = ubs;\n        // cs_ = Eigen::Vector3f( resl_, resl_, resl_ );\n\n        voxel_array_ = make_shared<::scheme::objective::voxel::VoxelArray<3>>( lbs, ubs, Eigen::Vector3f( resl_, resl_, resl_ ) );\n\n        // Indices extents = floats_to_index( ub_ );\n        // shape_ = extents + Indices(1);\n\n    }\n\n    void\n    create_and_fill_voxel_map(\n        core::pose::Pose const & target, \n        float too_close_dist,\n        float penalty,\n        size_t max_target_res_atom_idx\n        ) {\n\n        // size_t elements = shape_[0] * shape_[1] * shape_[2];\n        // std::cout << shape_ << std::endl;\n        // std::cout << floats_to_index( ub_ ) << std::endl;\n        // std::cout << elements << \" \" << index_to_map_index( floats_to_index( ub_ ) ) << std::endl;\n        // runtime_assert( elements - 1 == index_to_map_index( floats_to_index( ub_ ) ) );\n\n        // voxel_map_.resize( elements, 0 );\n\n\n        ::scheme::util::SimpleArray<3,float> lb = voxel_array_->lb_;\n        ::scheme::util::SimpleArray<3,float> ub = voxel_array_->ub_;\n\n        float const too_close_dist2 = too_close_dist * too_close_dist;\n\n\n        for ( size_t seqpos = 1; seqpos <= target.size(); seqpos ++  ) {\n            core::conformation::Residue const & res = target.residue(seqpos);\n\n            size_t loop_ub = std::min<size_t>( res.nheavyatoms(), max_target_res_atom_idx );\n            for ( core::Size atno = 1; atno <= loop_ub; atno++ ) {  \n\n                numeric::xyzVector<core::Real> _xyz = res.xyz( atno );\n                Eigen::Vector3f xyz; xyz[0] = _xyz[0]; xyz[1] = _xyz[1]; xyz[2] = _xyz[2];\n\n                Eigen::Vector3f lbs( xyz[0] - too_close_dist, xyz[1] - too_close_dist, xyz[2] - too_close_dist );\n                Eigen::Vector3f ubs( xyz[0] + too_close_dist, xyz[1] + too_close_dist, xyz[2] + too_close_dist );\n\n                const float step = resl_;\n\n                Eigen::Vector3f worker;\n\n                for ( float x = lbs[0] - step/2; x < ubs[0] + step; x += step ) {\n                    if ( x < lb[0] || x > ub[0] ) continue;\n                    worker[0] = x;\n\n                    for ( float y = lbs[1] - step/2; y < ubs[1] + step; y += step ) {\n                        if ( y < lb[1] || y > ub[1] ) continue;\n                        worker[1] = y;\n\n                        for ( float z = lbs[2] - step/2; z < ubs[2] + step; z += step ) {\n                            if ( z < lb[2] || z > ub[2] ) continue;\n                            worker[2] = z;\n\n                            const float squared_dist = ( xyz - worker ).squaredNorm();\n\n                            if ( squared_dist < too_close_dist2 ) {\n                                (*voxel_array_)[worker] = penalty;\n                                // size_t offset = index_to_map_index( floats_to_index( worker ) );\n                                // voxel_map_.at(offset) = penalty;\n                            } \n                        }\n                    }\n                }\n            }\n        }\n    }\n\n\n\n\n/////////////////////////////////////////////////////////////////////////\n    float\n    get_CB_penalty(\n        EigenXform const & bbpos\n    ) const {\n\n        Eigen::Matrix<float,3,1> CB = bbpos * Eigen::Matrix<float,3,1>( 1.0264273 ,  0.25245885, -0.308907 );\n\n        return voxel_array_->at( CB );\n\n    }\n\n\n\n\n    // template<class Floats> Indices floats_to_index(Floats const & f) const {\n    //     Indices ind;\n    //     for(int i = 0; i < 3; ++i){\n    //         float tmp = ((f[i]-lb_[i])/cs_[i]);\n    //         ind[i] = tmp;\n    //     }\n    //     return ind;\n    // }\n\n    // size_t index_to_map_index( Indices const & ind ) const {\n\n    //     size_t accum = ind[0];\n    //     accum = accum * shape_[1] + ind[1];\n    //     accum = accum * shape_[2] + ind[2];\n\n    //     return accum;\n\n    // }\n\n    // size_t index_to_offset( Indices const & ind ) const {\n\n    //     return index_to_map_index( ind );\n\n    // }\n\n\n\n    // float const &\n    // at( float f, float g, float h ) const {\n    //     Indices idx = floats_to_index( Bounds( f, g, h ) );\n    //     if( idx[0] < shape_[0] && idx[1] < shape_[1] && idx[2] < shape_[2] )\n    //         return voxel_map_.at( index_to_offset(idx) );\n    //     else return 0;\n    // }\n\n    // template<class V>\n    // float const &\n    // at( V const & v ) const {\n    //     Indices idx = floats_to_index( Bounds( v[0], v[1], v[2] ) );\n    //     if( idx[0] < shape_[0] && idx[1] < shape_[1] && idx[2] < shape_[2] )\n    //         return voxel_map_.at( index_to_offset(idx) );\n    //     else return 0;\n    // }\n\n\n};\n\n\n\n\n}}\n\n#endif\n", "meta": {"hexsha": "914a86edc487d1c34f58b7c21a857f4c9b5b7618", "size": 7368, "ext": "hh", "lang": "C++", "max_stars_repo_path": "apps/rosetta/riflib/CBTooCloseManager.hh", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "apps/rosetta/riflib/CBTooCloseManager.hh", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "apps/rosetta/riflib/CBTooCloseManager.hh", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 30.9579831933, "max_line_length": 130, "alphanum_fraction": 0.5347448426, "num_tokens": 2032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.15222030584422777}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  Aggregate SIMD numerical and type limits for X86 AVX\n\n  @copyright 2012 - 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_ARCH_X86_AVX_LIMITS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_AVX_LIMITS_HPP_INCLUDED\n\n#include <boost/simd/arch/x86/tags.hpp>\n#include <boost/simd/arch/common/limits.hpp>\n#include <boost/simd/detail/brigand.hpp>\n\nnamespace boost { namespace simd\n{\n  template<> struct limits<boost::simd::avx_>\n  {\n    struct largest_integer\n    {\n      template<typename Sign> struct apply { using type = brigand::no_such_type_; };\n    };\n\n    struct smallest_integer\n    {\n      template<typename Sign> struct apply { using type = brigand::no_such_type_; };\n    };\n\n    using parent = boost::simd::sse2_;\n\n    using smallest_real = float;\n    using largest_real  = double;\n\n    enum { bits = 256, bytes = 32 };\n  };\n} }\n\n#endif\n\n", "meta": {"hexsha": "9c26ebc59838a79c4f5319dfd6616136573eda89", "size": 1190, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/x86/avx/limits.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/x86/avx/limits.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/x86/avx/limits.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": 25.8695652174, "max_line_length": 100, "alphanum_fraction": 0.5865546218, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.15222030265718703}}
{"text": "/*\n * Copyright (C) 2019-2020 LEIDOS.\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\n#include <ros/ros.h>\n#include <string>\n#include <algorithm>\n#include <memory>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <lanelet2_core/geometry/Point.h>\n#include <trajectory_utils/trajectory_utils.h>\n#include <trajectory_utils/conversions/conversions.h>\n#include <sstream>\n#include <carma_utils/containers/containers.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <inlanecruising_plugin/smoothing/SplineI.h>\n#include <inlanecruising_plugin/smoothing/CubicSpline.h>\n#include <inlanecruising_plugin/inlanecruising_plugin.h>\n#include <inlanecruising_plugin/log/log.h>\n#include <carma_utils/containers/containers.h>\n#include <inlanecruising_plugin/smoothing/filters.h>\n#include <unordered_set>\n\nusing oss = std::ostringstream;\n\nnamespace inlanecruising_plugin\n{\nInLaneCruisingPlugin::InLaneCruisingPlugin(carma_wm::WorldModelConstPtr wm, InLaneCruisingPluginConfig config,\n                                           PublishPluginDiscoveryCB plugin_discovery_publisher)\n  : wm_(wm), config_(config), plugin_discovery_publisher_(plugin_discovery_publisher)\n{\n  plugin_discovery_msg_.name = \"InLaneCruisingPlugin\";\n  plugin_discovery_msg_.versionId = \"v1.0\";\n  plugin_discovery_msg_.available = true;\n  plugin_discovery_msg_.activated = false;\n  plugin_discovery_msg_.type = cav_msgs::Plugin::TACTICAL;\n  plugin_discovery_msg_.capability = \"tactical_plan/plan_trajectory\";\n}\n\nbool InLaneCruisingPlugin::onSpin()\n{\n  plugin_discovery_publisher_(plugin_discovery_msg_);\n  return true;\n}\n\nbool InLaneCruisingPlugin::plan_trajectory_cb(cav_srvs::PlanTrajectoryRequest& req,\n                                              cav_srvs::PlanTrajectoryResponse& resp)\n{\n  ros::WallTime start_time = ros::WallTime::now(); // Start timeing the execution time for planning so it can be logged\n\n  lanelet::BasicPoint2d veh_pos(req.vehicle_state.X_pos_global, req.vehicle_state.Y_pos_global);\n  double current_downtrack = wm_->routeTrackPos(veh_pos).downtrack;\n\n  auto points_and_target_speeds = maneuvers_to_points(req.maneuver_plan.maneuvers, current_downtrack, wm_); // Convert maneuvers to points\n\n  ROS_DEBUG_STREAM(\"points_and_target_speeds: \" << points_and_target_speeds.size());\n\n  auto downsampled_points =\n      carma_utils::containers::downsample_vector(points_and_target_speeds, config_.downsample_ratio);\n\n  ROS_DEBUG_STREAM(\"downsample_points: \" << downsampled_points.size());\n\n  ROS_DEBUG_STREAM(\"PlanTrajectory\");\n\n  cav_msgs::TrajectoryPlan trajectory;\n  trajectory.header.frame_id = \"map\";\n  trajectory.header.stamp = ros::Time::now();\n  trajectory.trajectory_id = boost::uuids::to_string(boost::uuids::random_generator()());\n\n  trajectory.trajectory_points = compose_trajectory_from_centerline(downsampled_points, req.vehicle_state); // Compute the trajectory\n  trajectory.initial_longitudinal_velocity = std::max(req.vehicle_state.longitudinal_vel, config_.minimum_speed);\n\n  resp.trajectory_plan = trajectory;\n  resp.related_maneuvers.push_back(cav_msgs::Maneuver::LANE_FOLLOWING);\n  resp.maneuver_status.push_back(cav_srvs::PlanTrajectory::Response::MANEUVER_IN_PROGRESS);\n\n  ros::WallTime end_time = ros::WallTime::now(); // Planning complete\n\n  ros::WallDuration duration = end_time - start_time;\n  ROS_DEBUG_STREAM(\"ExecutionTime: \" << duration.toSec());\n\n  return true;\n}\n\nstd::vector<double> InLaneCruisingPlugin::apply_speed_limits(const std::vector<double> speeds,\n                                                             const std::vector<double> speed_limits)\n{\n  ROS_DEBUG_STREAM(\"Speeds list size: \" << speeds.size());\n  ROS_DEBUG_STREAM(\"SpeedLimits list size: \" << speed_limits.size());\n\n  if (speeds.size() != speed_limits.size())\n  {\n    throw std::invalid_argument(\"Speeds and speed limit lists not same size\");\n  }\n  std::vector<double> out;\n  for (size_t i = 0; i < speeds.size(); i++)\n  {\n    out.push_back(std::min(speeds[i], speed_limits[i]));\n  }\n\n  return out;\n}\n\nEigen::Isometry2d InLaneCruisingPlugin::compute_heading_frame(const lanelet::BasicPoint2d& p1,\n                                                              const lanelet::BasicPoint2d& p2)\n{\n  Eigen::Rotation2Dd yaw(atan2(p2.y() - p1.y(), p2.x() - p1.x()));\n\n  return carma_wm::geometry::build2dEigenTransform(p1, yaw);\n}\n\nstd::vector<DiscreteCurve> InLaneCruisingPlugin::compute_sub_curves(const std::vector<PointSpeedPair>& map_points)\n{\n  if (map_points.size() < 2)\n  {\n    throw std::invalid_argument(\"Not enough points\");\n  }\n\n  std::vector<DiscreteCurve> curves;\n  DiscreteCurve curve;\n  curve.frame = compute_heading_frame(map_points[0].point, map_points[1].point);\n  Eigen::Isometry2d map_in_curve = curve.frame.inverse();\n\n  for (size_t i = 0; i < map_points.size() - 1; i++)\n  {\n    lanelet::BasicPoint2d p1 = map_in_curve * map_points[i].point;\n    lanelet::BasicPoint2d p2 = map_in_curve * map_points[i + 1].point;  // TODO Optimization to cache this value\n\n    PointSpeedPair initial_pair;\n    initial_pair.point = p1;\n    initial_pair.speed = map_points[i].speed;\n    curve.points.push_back(initial_pair);\n\n    bool x_dir = (p2.x() - p1.x()) > 0;\n    if (!x_dir)  // If x starts going backwards we need a new curve\n    {\n      // New Curve\n      curves.push_back(curve);\n\n      curve = DiscreteCurve();\n      curve.frame = compute_heading_frame(map_points[i].point, map_points[i + 1].point);\n      map_in_curve = curve.frame.inverse();\n\n      PointSpeedPair pair;\n      pair.point = map_in_curve * map_points[i].point;\n      pair.speed = map_points[i].speed;\n\n      curve.points.push_back(pair);  // Include first point in curve\n    }\n  }\n\n  curves.push_back(curve);\n\n  return curves;\n}\n\nstd::vector<PointSpeedPair> InLaneCruisingPlugin::constrain_to_time_boundary(const std::vector<PointSpeedPair>& points,\n                                                                             double time_span)\n{\n  std::vector<lanelet::BasicPoint2d> basic_points;\n  std::vector<double> speeds;\n  splitPointSpeedPairs(points, &basic_points, &speeds);\n\n  std::vector<double> downtracks = carma_wm::geometry::compute_arc_lengths(basic_points);\n\n  size_t time_boundary_exclusive_index =\n      trajectory_utils::time_boundary_index(downtracks, speeds, config_.trajectory_time_length);\n\n  if (time_boundary_exclusive_index == 0)\n  {\n    throw std::invalid_argument(\"No points to fit in timespan\"); \n  }\n\n  std::vector<PointSpeedPair> time_bound_points;\n  time_bound_points.reserve(time_boundary_exclusive_index);\n\n  if (time_boundary_exclusive_index == points.size())\n  {\n    time_bound_points.insert(time_bound_points.end(), points.begin(),\n                             points.end());  // All points fit within time boundary\n  }\n  else\n  {\n    time_bound_points.insert(time_bound_points.end(), points.begin(),\n                             points.begin() + time_boundary_exclusive_index - 1);  // Limit points by time boundary\n  }\n\n  return time_bound_points;\n}\n\nstd::vector<cav_msgs::TrajectoryPlanPoint> InLaneCruisingPlugin::compose_trajectory_from_centerline(\n    const std::vector<PointSpeedPair>& points, const cav_msgs::VehicleState& state)\n{\n  ROS_DEBUG_STREAM(\"VehicleState: \"\n                   << \" x: \" << state.X_pos_global << \" y: \" << state.Y_pos_global << \" yaw: \" << state.orientation\n                   << \" speed: \" << state.longitudinal_vel);\n\n  ROS_DEBUG_STREAM(\"points size: \" << points.size());\n  \n  log::printDebugPerLine(points, &log::pointSpeedPairToStream);\n\n  int nearest_pt_index = getNearestPointIndex(points, state);\n\n  ROS_DEBUG_STREAM(\"NearestPtIndex: \" << nearest_pt_index);\n\n  std::vector<PointSpeedPair> future_points(points.begin() + nearest_pt_index + 1, points.end()); // Points in front of current vehicle position\n\n  auto time_bound_points = constrain_to_time_boundary(future_points, config_.trajectory_time_length);\n\n  ROS_DEBUG_STREAM(\"time_bound_points: \" << time_bound_points.size());\n\n  log::printDebugPerLine(time_bound_points, &log::pointSpeedPairToStream);\n\n  ROS_DEBUG(\"Got basic points \");\n  std::vector<DiscreteCurve> sub_curves = compute_sub_curves(time_bound_points);\n\n  ROS_DEBUG_STREAM(\"Got sub_curves \" << sub_curves.size());\n\n  std::vector<double> final_yaw_values;\n  std::vector<double> final_actual_speeds;\n  std::vector<lanelet::BasicPoint2d> all_sampling_points;\n\n  for (const auto& discreet_curve : sub_curves)\n  {\n    ROS_DEBUG(\"SubCurve\");\n\n    std::vector<double> speed_limits;\n    std::vector<lanelet::BasicPoint2d> curve_points;\n    splitPointSpeedPairs(discreet_curve.points, &curve_points, &speed_limits);\n\n    std::unique_ptr<smoothing::SplineI> fit_curve = compute_fit(curve_points); // Compute splines based on curve points\n\n    if (!fit_curve)\n    {  // TODO how better to handle this case\n      for (size_t i = 0; i < discreet_curve.points.size() - 1; i++)\n      {\n        Eigen::Isometry2d point_in_map =\n            curvePointInMapTF(discreet_curve.frame, discreet_curve.points[i].point, final_yaw_values.back());\n        all_sampling_points.push_back(point_in_map.translation());\n        final_yaw_values.push_back(final_yaw_values.back());\n        final_actual_speeds.push_back(final_actual_speeds.back());\n      }\n      continue;\n    }\n\n    ROS_DEBUG(\"Got fit\");\n\n    ROS_DEBUG_STREAM(\"speed_limits.size() \" << speed_limits.size());\n\n    std::vector<lanelet::BasicPoint2d> sampling_points;\n    sampling_points.reserve(1 + discreet_curve.points.size() * 2);\n\n    std::vector<double> distributed_speed_limits;\n    distributed_speed_limits.reserve(1 + discreet_curve.points.size() * 2);\n\n    double max_x = curve_points.back().x();\n    double current_dist = 0;\n    double step_size = config_.curve_resample_step_size;\n    int current_speed_index = 0;\n\n    while (current_dist < max_x - step_size) // Resample curve at tighter resolution\n    {\n      double x = current_dist;\n      double y = (*fit_curve)(x);\n      lanelet::BasicPoint2d p(x, y);\n      sampling_points.push_back(p);\n\n      for (size_t i = current_speed_index; i < curve_points.size(); i++)\n      {\n        if (curve_points[i].x() >= current_dist)\n        {\n          current_speed_index = i;\n          break;\n        }\n      }\n\n      distributed_speed_limits.push_back(speed_limits[current_speed_index]); // Identify speed limits for resampled points\n      current_dist += step_size;\n    }\n\n    log::printDebugPerLine(sampling_points, &log::basicPointToStream);\n\n    std::vector<double> yaw_values = carma_wm::geometry::compute_tangent_orientations(sampling_points);\n\n    std::vector<double> curvatures = carma_wm::geometry::local_circular_arc_curvatures(\n        sampling_points, config_.curvature_calc_lookahead_count);  \n\n    curvatures = smoothing::moving_average_filter(curvatures, config_.moving_average_window_size);\n\n    log::printDoublesPerLineWithPrefix(\"curvatures[i]: \", curvatures);\n\n    std::vector<double> ideal_speeds =\n        trajectory_utils::constrained_speeds_for_curvatures(curvatures, config_.lateral_accel_limit);\n\n    log::printDoublesPerLineWithPrefix(\"ideal_speeds: \", ideal_speeds);\n\n    std::vector<double> actual_speeds = apply_speed_limits(ideal_speeds, distributed_speed_limits);\n\n    log::printDoublesPerLineWithPrefix(\"actual_speeds: \", actual_speeds);\n\n    log::printDoublesPerLineWithPrefix(\"yaw_values[i]: \", yaw_values);\n\n    for (int i = 0; i < yaw_values.size() - 1; i++)\n    {  // Drop last point\n\n      Eigen::Isometry2d point_in_map = curvePointInMapTF(discreet_curve.frame, sampling_points[i], yaw_values[i]);\n      Eigen::Rotation2Dd new_rot(point_in_map.rotation());\n      final_yaw_values.push_back(new_rot.smallestAngle());\n      all_sampling_points.push_back(point_in_map.translation());\n    }\n\n    final_actual_speeds.insert(final_actual_speeds.end(), actual_speeds.begin(), actual_speeds.end() - 1);\n\n    ROS_DEBUG(\"Appended to final\");\n  }\n\n\n  ROS_DEBUG(\"Processed all curves\");\n\n  if (all_sampling_points.size() == 0)\n  {\n    ROS_WARN_STREAM(\"No trajectory points could be generated\");\n    return {};\n  }\n\n  log::printDoublesPerLineWithPrefix(\"final_actual_speeds[i]: \", final_actual_speeds);\n\n  log::printDoublesPerLineWithPrefix(\"final_yaw_values[i]: \", final_yaw_values);\n\n  // Find Lookahead Distance based on Velocity\n  double lookahead_distance = get_adaptive_lookahead(state.longitudinal_vel);\n\n  ROS_DEBUG_STREAM(\"Lookahead distance at current speed: \" << lookahead_distance);\n\n  // Apply lookahead speeds\n  final_actual_speeds = get_lookahead_speed(all_sampling_points, final_actual_speeds, lookahead_distance);\n  \n  // Add current vehicle point to front of the trajectory\n  lanelet::BasicPoint2d cur_veh_point(state.X_pos_global, state.Y_pos_global);\n  all_sampling_points.insert(all_sampling_points.begin(),\n                             cur_veh_point);  // Add current vehicle position to front of sample points\n\n  final_actual_speeds.insert(final_actual_speeds.begin(), std::max(state.longitudinal_vel, config_.minimum_speed));\n\n  final_yaw_values.insert(final_yaw_values.begin(), state.orientation);\n\n  log::printDoublesPerLineWithPrefix(\"pre_smoot[i]: \", final_actual_speeds);\n  \n  // Compute points to local downtracks\n  std::vector<double> downtracks = carma_wm::geometry::compute_arc_lengths(all_sampling_points);\n\n  log::printDoublesPerLineWithPrefix(\"post_shift[i]: \", final_actual_speeds);\n  \n  // Apply accel limits\n  final_actual_speeds = trajectory_utils::apply_accel_limits_by_distance(downtracks, final_actual_speeds,\n                                                                         config_.max_accel, config_.max_accel);\n  log::printDoublesPerLineWithPrefix(\"postAccel[i]: \", final_actual_speeds);\n\n  \n  final_actual_speeds = smoothing::moving_average_filter(final_actual_speeds, config_.moving_average_window_size);\n  log::printDoublesPerLineWithPrefix(\"post_average[i]: \", final_actual_speeds);\n\n  for (auto& s : final_actual_speeds)  // Limit minimum speed. TODO how to handle stopping?\n  {\n    s = std::max(s, config_.minimum_speed);\n  }\n\n  log::printDoublesPerLineWithPrefix(\"post_min_speed[i]: \", final_actual_speeds);\n  // Convert speeds to times\n  std::vector<double> times;\n  trajectory_utils::conversions::speed_to_time(downtracks, final_actual_speeds, &times);\n\n  log::printDoublesPerLineWithPrefix(\"times[i]: \", times);\n  \n  // Build trajectory points\n  // TODO When more plugins are implemented that might share trajectory planning the start time will need to be based\n  // off the last point in the plan if an earlier plan was provided\n  std::vector<cav_msgs::TrajectoryPlanPoint> traj_points =\n      trajectory_from_points_times_orientations(all_sampling_points, times, final_yaw_values, ros::Time::now());\n\n  return traj_points;\n}\n\ndouble InLaneCruisingPlugin::get_adaptive_lookahead(double velocity){\n  \n  // lookahead:\n  // v<10kph:  5m\n  // 10kph<v<50kph:  0.5*v\n  // v>50kph:  25m\n\n  double lookahead = config_.minimum_lookahead_distance;\n\n  if (velocity < config_.minimum_lookahead_speed)\n  {\n    lookahead = config_.minimum_lookahead_distance;\n  } \n  else if (velocity >= config_.minimum_lookahead_speed && velocity < config_.maximum_lookahead_speed)\n  {\n    lookahead = config_.lookahead_ratio * velocity;\n  } \n  else lookahead = config_.maximum_lookahead_distance;\n\n  return lookahead;\n\n}\n\nstd::vector<double> InLaneCruisingPlugin::get_lookahead_speed(const std::vector<lanelet::BasicPoint2d>& points, const std::vector<double>& speeds, const double& lookahead){\n  \n  if (lookahead < config_.minimum_lookahead_distance)\n  {\n    throw std::invalid_argument(\"Invalid lookahead value\");\n  }\n\n  if (speeds.size() < 1)\n  {\n    throw std::invalid_argument(\"Invalid speeds vector\");\n  }\n\n  if (speeds.size() != points.size())\n  {\n    throw std::invalid_argument(\"Speeds and Points lists not same size\");\n  }\n\n  std::vector<double> out;\n  out.reserve(speeds.size());\n\n  for (int i = 0; i < points.size(); i++)\n  {\n    int idx = i;\n    double min_dist = std::numeric_limits<double>::max();\n    for (int j=i+1; j < points.size(); j++){\n      double dist = lanelet::geometry::distance2d(points[i],points[j]);\n      if (abs(lookahead - dist) <= min_dist){\n        idx = j;\n        min_dist = abs(lookahead - dist);\n      }\n    }\n    out.push_back(speeds[idx]);\n  }\n  \n  return out;\n}\n\nEigen::Isometry2d InLaneCruisingPlugin::curvePointInMapTF(const Eigen::Isometry2d& curve_in_map,\n                                                          const lanelet::BasicPoint2d& p, double yaw) const\n{\n  Eigen::Rotation2Dd yaw_rot(yaw);\n  Eigen::Isometry2d point_in_c = carma_wm::geometry::build2dEigenTransform(p, yaw_rot);\n  Eigen::Isometry2d point_in_map = curve_in_map * point_in_c;\n  return point_in_map;\n}\n\nstd::vector<cav_msgs::TrajectoryPlanPoint> InLaneCruisingPlugin::trajectory_from_points_times_orientations(\n    const std::vector<lanelet::BasicPoint2d>& points, const std::vector<double>& times, const std::vector<double>& yaws,\n    ros::Time startTime)\n{\n  if (points.size() != times.size() || points.size() != yaws.size())\n  {\n    throw std::invalid_argument(\"All input vectors must have the same size\");\n  }\n\n  std::vector<cav_msgs::TrajectoryPlanPoint> traj;\n  traj.reserve(points.size());\n\n  for (int i = 0; i < points.size(); i++)\n  {\n    cav_msgs::TrajectoryPlanPoint tpp;\n    ros::Duration relative_time(times[i]);\n    tpp.target_time = startTime + relative_time;\n    tpp.x = points[i].x();\n    tpp.y = points[i].y();\n    tpp.yaw = yaws[i];\n\n    tpp.controller_plugin_name = \"default\";\n    tpp.planner_plugin_name = plugin_discovery_msg_.name;\n\n    traj.push_back(tpp);\n  }\n\n  return traj;\n}\n\nstd::vector<PointSpeedPair> InLaneCruisingPlugin::maneuvers_to_points(const std::vector<cav_msgs::Maneuver>& maneuvers,\n                                                                      double max_starting_downtrack,\n                                                                      const carma_wm::WorldModelConstPtr& wm)\n{\n  std::vector<PointSpeedPair> points_and_target_speeds;\n  std::unordered_set<lanelet::Id> visited_lanelets;\n\n  bool first = true;\n  ROS_DEBUG_STREAM(\"VehDowntrack: \" << max_starting_downtrack);\n  for (const auto& manuever : maneuvers)\n  {\n    if (manuever.type != cav_msgs::Maneuver::LANE_FOLLOWING)\n    {\n      throw std::invalid_argument(\"In-Lane Cruising does not support this maneuver type\");\n    }\n\n    cav_msgs::LaneFollowingManeuver lane_following_maneuver = manuever.lane_following_maneuver;\n\n    double starting_downtrack = lane_following_maneuver.start_dist;\n    if (first)\n    {\n      if (starting_downtrack > max_starting_downtrack)\n      {\n        starting_downtrack = max_starting_downtrack;\n      }\n      first = false;\n    }\n\n    ROS_DEBUG_STREAM(\"Used downtrack: \" << starting_downtrack);\n\n    auto lanelets = wm->getLaneletsBetween(starting_downtrack, lane_following_maneuver.end_dist, true);\n\n    ROS_DEBUG_STREAM(\"Maneuver\");\n    std::vector<lanelet::ConstLanelet> lanelets_to_add;\n    for (auto l : lanelets)\n    {\n      ROS_DEBUG_STREAM(\"Lanelet ID: \" << l.id());\n      if (visited_lanelets.find(l.id()) == visited_lanelets.end())\n      {\n        lanelets_to_add.push_back(l);\n        visited_lanelets.insert(l.id());\n      }\n    }\n\n    lanelet::BasicLineString2d route_geometry = carma_wm::geometry::concatenate_lanelets(lanelets_to_add);\n\n    first = true;\n    for (auto p : route_geometry)\n    {\n      if (first && points_and_target_speeds.size() != 0)\n      {\n        first = false;\n        continue;  // Skip the first point if we have already added points from a previous maneuver to avoid duplicates\n      }\n      PointSpeedPair pair;\n      pair.point = p;\n      pair.speed = lane_following_maneuver.end_speed;\n      points_and_target_speeds.push_back(pair);\n    }\n  }\n\n  return points_and_target_speeds;\n}\n\nint InLaneCruisingPlugin::getNearestPointIndex(const std::vector<PointSpeedPair>& points,\n                                               const cav_msgs::VehicleState& state)\n{\n  lanelet::BasicPoint2d veh_point(state.X_pos_global, state.Y_pos_global);\n  ROS_DEBUG_STREAM(\"veh_point: \" << veh_point.x() << \", \" << veh_point.y());\n  double min_distance = std::numeric_limits<double>::max();\n  int i = 0;\n  int best_index = 0;\n  for (const auto& p : points)\n  {\n    double distance = lanelet::geometry::distance2d(p.point, veh_point);\n    ROS_DEBUG_STREAM(\"distance: \" << distance);\n    ROS_DEBUG_STREAM(\"p: \" << p.point.x() << \", \" << p.point.y());\n    if (distance < min_distance)\n    {\n      best_index = i;\n      min_distance = distance;\n    }\n    i++;\n  }\n\n  return best_index;\n}\n\n\nvoid InLaneCruisingPlugin::splitPointSpeedPairs(const std::vector<PointSpeedPair>& points,\n                                                std::vector<lanelet::BasicPoint2d>* basic_points,\n                                                std::vector<double>* speeds)\n{\n  basic_points->reserve(points.size());\n  speeds->reserve(points.size());\n\n  for (const auto& p : points)\n  {\n    basic_points->push_back(p.point);\n    speeds->push_back(p.speed);\n  }\n}\n\nstd::unique_ptr<smoothing::SplineI>\nInLaneCruisingPlugin::compute_fit(const std::vector<lanelet::BasicPoint2d>& basic_points)\n{\n  if (basic_points.size() < 3)\n  {\n    ROS_WARN_STREAM(\"Insufficient Spline Points\");\n    return nullptr;\n  }\n\n  std::unique_ptr<smoothing::SplineI> spl = std::make_unique<smoothing::CubicSpline>();\n  spl->setPoints(basic_points);\n\n  return spl;\n}\n}  // namespace inlanecruising_plugin\n", "meta": {"hexsha": "a8d21946347d9bd82b5faee13b5beacfe7438884", "size": 21951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "inlanecruising_plugin/src/inlanecruising_plugin.cpp", "max_stars_repo_name": "harderthan/carma-platform", "max_stars_repo_head_hexsha": "29921896a761a866db9cfee473f02a481d8bb9c9", "max_stars_repo_licenses": ["Apache-2.0", "CC-BY-4.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": "inlanecruising_plugin/src/inlanecruising_plugin.cpp", "max_issues_repo_name": "harderthan/carma-platform", "max_issues_repo_head_hexsha": "29921896a761a866db9cfee473f02a481d8bb9c9", "max_issues_repo_licenses": ["Apache-2.0", "CC-BY-4.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": "inlanecruising_plugin/src/inlanecruising_plugin.cpp", "max_forks_repo_name": "harderthan/carma-platform", "max_forks_repo_head_hexsha": "29921896a761a866db9cfee473f02a481d8bb9c9", "max_forks_repo_licenses": ["Apache-2.0", "CC-BY-4.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": 35.5769854133, "max_line_length": 172, "alphanum_fraction": 0.7052070521, "num_tokens": 5392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2877678279774722, "lm_q1q2_score": 0.15174473058956997}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef variational_bayes_mixture_model_hpp\n#define variational_bayes_mixture_model_hpp\n\n#include <array>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <iterator>\n#include <cstddef>\n#include <utility>\n#include <cassert>\n#include <limits>\n\n#include <boost/optional.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"utils/maths.hpp\"\n#include \"utils/memory_footprint.hpp\"\n#include \"core/models/haplotype_likelihood_array.hpp\"\n\n/**\n *\n * This file contains an implementation of the Variational Bayes mixture model\n * used by some genotype models. The notation follows the documentation.\n *\n */\n\nnamespace octopus { namespace model {\n\n// Types needed for Variational Bayes model\n\nstruct VariationalBayesParameters\n{\n    double epsilon = 0.05;\n    unsigned max_iterations = 1000;\n    double save_memory = false;\n};\n\nusing ProbabilityVector    = std::vector<double>;\nusing LogProbabilityVector = std::vector<double>;\n\ntemplate <std::size_t K>\nusing VBAlpha = std::array<double, K>;\ntemplate <std::size_t K>\nusing VBAlphaVector = std::vector<VBAlpha<K>>;\n\nclass VBReadLikelihoodArray\n{\npublic:\n    using BaseType = HaplotypeLikelihoodArray::LikelihoodVector;\n    \n    VBReadLikelihoodArray() = default;\n    \n    explicit VBReadLikelihoodArray(const BaseType&);\n    \n    VBReadLikelihoodArray(const VBReadLikelihoodArray&)            = default;\n    VBReadLikelihoodArray& operator=(const VBReadLikelihoodArray&) = default;\n    VBReadLikelihoodArray(VBReadLikelihoodArray&&)                 = default;\n    VBReadLikelihoodArray& operator=(VBReadLikelihoodArray&&)      = default;\n    \n    ~VBReadLikelihoodArray() = default;\n    \n    void operator=(const BaseType&);\n    void operator=(std::reference_wrapper<const BaseType>);\n    std::size_t size() const noexcept;\n    BaseType::const_iterator begin() const noexcept;\n    BaseType::const_iterator end() const noexcept;\n    double operator[](const std::size_t n) const noexcept;\n\nprivate:\n    const BaseType* likelihoods;\n};\n\ntemplate <std::size_t K>\nusing VBGenotype = std::array<VBReadLikelihoodArray, K>; // One element per haplotype in genotype (i.e. K)\ntemplate <std::size_t K>\nusing VBGenotypeVector = std::vector<VBGenotype<K>>; // Per element per genotype\ntemplate <std::size_t K>\nusing VBReadLikelihoodMatrix = std::vector<VBGenotypeVector<K>>; // One element per sample\n\nusing VBTau = std::vector<double>; // One element per read\ntemplate <std::size_t K>\nusing VBResponsabilityVector = std::array<VBTau, K>; // One element per haplotype in genotype (i.e. K)\ntemplate <std::size_t K>\nusing VBResponsabilityMatrix = std::vector<VBResponsabilityVector<K>>; // One element per sample\n\ntemplate <std::size_t K>\nstruct VBLatents\n{\n    ProbabilityVector genotype_posteriors;\n    LogProbabilityVector genotype_log_posteriors;\n    VBAlphaVector<K> alphas;\n    VBResponsabilityMatrix<K> responsabilities;\n};\n\n// Main VB method\n\nnamespace detail {\n\nusing VBExpandedLikelihood = std::vector<double>; // One element per genotype\nusing VBExpandedGenotype = std::vector<VBExpandedLikelihood>; // One element per read\ntemplate <std::size_t K>\nusing VBExpandedGenotypeVector = std::array<VBExpandedGenotype, K>; // One element per haplotype in genotype\ntemplate <std::size_t K>\nusing VBExpandedLikelihoodMatrix = std::vector<VBExpandedGenotypeVector<K>>; // One element per sample\n\ntemplate <std::size_t K>\nauto invert(const VBGenotypeVector<K>& likelihoods)\n{\n    static_assert(K > 0, \"K == 0\");\n    const auto num_genotypes = likelihoods.size();\n    assert(num_genotypes > 0);\n    const auto num_reads = likelihoods.front().front().size();\n    VBExpandedGenotypeVector<K> result {};\n    for (std::size_t k {0}; k < K; ++k) {\n        result[k] = VBExpandedGenotype(num_reads, VBExpandedLikelihood(num_genotypes));\n        for (std::size_t n {0}; n < num_reads; ++n) {\n            for (std::size_t g {0}; g < num_genotypes; ++g) {\n                result[k][n][g] = likelihoods[g][k][n];\n            }\n        }\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nauto invert(const VBReadLikelihoodMatrix<K>& matrix)\n{\n    VBExpandedLikelihoodMatrix<K> result {};\n    result.reserve(matrix.size());\n    std::transform(std::cbegin(matrix), std::cend(matrix), std::back_inserter(result),\n                   [] (const auto& v) { return invert(v); });\n    return result;\n}\n\ninline ProbabilityVector& exp(const LogProbabilityVector& log_probabilities, ProbabilityVector& result) noexcept\n{\n    std::transform(std::cbegin(log_probabilities), std::cend(log_probabilities), std::begin(result),\n                   [] (const auto lp) noexcept { return std::exp(lp); });\n    return result;\n}\n\ninline ProbabilityVector exp(const LogProbabilityVector& log_probabilities)\n{\n    ProbabilityVector result(log_probabilities.size());\n    return exp(log_probabilities, result);\n}\n\ninline auto sum(const VBAlpha<2>& alpha) noexcept\n{\n    return alpha[0] + alpha[1];\n}\n\ninline auto sum(const VBAlpha<3>& alpha) noexcept\n{\n    return alpha[0] + alpha[1] + alpha[2];\n}\n\ntemplate <std::size_t K>\nauto sum(const VBAlpha<K>& alpha) noexcept\n{\n    using T = typename VBAlpha<K>::value_type;\n    return std::accumulate(std::cbegin(alpha), std::cend(alpha), T {0});\n}\n\ntemplate <typename T>\ninline auto digamma_diff(const T a, const T b)\n{\n    using boost::math::digamma;\n    return digamma(a) - digamma(b);\n}\n\ntemplate <typename T>\ninline T log_sum_exp(const std::array<T, 1>& logs)\n{\n    return logs[0];\n}\n\ntemplate <typename T>\ninline T log_sum_exp(const std::array<T, 2>& logs)\n{\n    return maths::log_sum_exp(logs[0], logs[1]);\n}\n\ntemplate <typename T>\ninline T log_sum_exp(const std::array<T, 3>& logs)\n{\n    return maths::log_sum_exp(logs[0], logs[1], logs[2]);\n}\n\ntemplate <typename T, std::size_t K>\nT log_sum_exp(const std::array<T, K>& logs)\n{\n    return maths::log_sum_exp(logs);\n}\n\ntemplate <std::size_t K>\nauto count_reads(const VBGenotypeVector<K>& likelihoods) noexcept\n{\n    return likelihoods[0][0].size();\n}\n\ntemplate <std::size_t K>\nauto count_reads(const VBExpandedGenotypeVector<K>& likelihoods) noexcept\n{\n    return likelihoods[0].size();\n}\n\ntemplate <std::size_t K>\nauto marginalise(const ProbabilityVector& distribution, const VBGenotypeVector<K>& likelihoods,\n                 const unsigned k, const std::size_t n) noexcept\n{\n    using T = ProbabilityVector::value_type;\n    return std::inner_product(std::cbegin(distribution), std::cend(distribution),\n                              std::cbegin(likelihoods), T {0}, std::plus<> {},\n                              [k, n] (const auto p, const auto& haplotype_likelihoods) noexcept {\n                                  return p * haplotype_likelihoods[k][n];\n                              });\n}\n\ntemplate <typename T1, typename T2>\nauto inner_product(const T1& lhs, const T2& rhs) noexcept\n{\n    assert(std::distance(std::cbegin(lhs), std::cend(lhs)) == std::distance(std::cbegin(rhs), std::cend(rhs)));\n    using T = typename T1::value_type;\n    return std::inner_product(std::cbegin(lhs), std::cend(lhs), std::cbegin(rhs), T {0});\n}\n\ntemplate <std::size_t K>\nauto marginalise(const ProbabilityVector& distribution, const VBExpandedGenotypeVector<K>& likelihoods,\n                 const unsigned k, const std::size_t n) noexcept\n{\n    return inner_product(distribution, likelihoods[k][n]);\n}\n\ntemplate <std::size_t K, typename VBLikelihoodVector_>\nVBResponsabilityVector<K>\ninit_responsabilities(const VBAlpha<K>& prior_alphas,\n                      const ProbabilityVector& genotype_probabilities,\n                      const VBLikelihoodVector_& read_likelihoods)\n{\n    using T = typename VBAlpha<K>::value_type;\n    std::array<T, K> al; // no need to keep recomputing this\n    const auto a0 = sum(prior_alphas);\n    for (unsigned k {0}; k < K; ++k) {\n        al[k] = digamma_diff(prior_alphas[k], a0);\n    }\n    const auto N = count_reads(read_likelihoods);\n    VBResponsabilityVector<K> result {};\n    for (auto& tau : result) tau.resize(N);\n    std::array<T, K> ln_rho;\n    for (std::size_t n {0}; n < N; ++n) {\n        for (unsigned k {0}; k < K; ++k) {\n            ln_rho[k] = al[k] + marginalise(genotype_probabilities, read_likelihoods, k, n);\n        }\n        const auto ln_rho_norm = log_sum_exp(ln_rho);\n        for (unsigned k {0}; k < K; ++k) {\n            result[k][n] = std::exp(ln_rho[k] - ln_rho_norm);\n        }\n    }\n    return result;\n}\n\ntemplate <std::size_t K, typename VBLikelihoodMatrix>\nVBResponsabilityMatrix<K>\ninit_responsabilities(const VBAlphaVector<K>& prior_alphas,\n                      const ProbabilityVector& genotype_probabilities,\n                      const VBLikelihoodMatrix& read_likelihoods)\n{\n    const auto S = read_likelihoods.size(); // num samples\n    VBResponsabilityMatrix<K> result {};\n    result.reserve(S);\n    for (std::size_t s {0}; s < S; ++s) {\n        result.push_back(init_responsabilities(prior_alphas[s], genotype_probabilities, read_likelihoods[s]));\n    }\n    return result;\n}\n\ntemplate <std::size_t K, typename VBLikelihoodVector_>\nvoid update_responsabilities(VBResponsabilityVector<K>& result,\n                             const VBAlpha<K>& posterior_alphas,\n                             const ProbabilityVector& genotype_probabilities,\n                             const VBLikelihoodVector_& read_likelihoods)\n{\n    using T = typename VBAlpha<K>::value_type;\n    std::array<T, K> al;\n    const auto a0 = sum(posterior_alphas);\n    for (unsigned k {0}; k < K; ++k) {\n        al[k] = digamma_diff(posterior_alphas[k], a0);\n    }\n    const auto N = count_reads(read_likelihoods);\n    std::array<T, K> ln_rho;\n    for (std::size_t n {0}; n < N; ++n) {\n        for (unsigned k {0}; k < K; ++k) {\n            ln_rho[k] = al[k] + marginalise(genotype_probabilities, read_likelihoods, k, n);\n        }\n        const auto ln_rho_norm = log_sum_exp(ln_rho);\n        for (unsigned k {0}; k < K; ++k) {\n            result[k][n] = std::exp(ln_rho[k] - ln_rho_norm);\n        }\n    }\n}\n\n// same as init_responsabilities but in-place\ntemplate <std::size_t K, typename VBLikelihoodMatrix>\nvoid update_responsabilities(VBResponsabilityMatrix<K>& result,\n                             const VBAlphaVector<K>& posterior_alphas,\n                             const ProbabilityVector& genotype_probabilities,\n                             const VBLikelihoodMatrix& read_likelihoods)\n{\n    const auto S = read_likelihoods.size();\n    for (std::size_t s {0}; s < S; ++s) {\n        update_responsabilities(result[s], posterior_alphas[s], genotype_probabilities, read_likelihoods[s]);\n    }\n}\n\ntemplate <typename T>\ninline auto sum(const std::vector<T>& values) noexcept\n{\n    return std::accumulate(std::cbegin(values), std::cend(values), T {});\n}\n\ntemplate <std::size_t K>\nvoid update_alpha(VBAlpha<K>& alpha, const VBAlpha<K>& prior_alpha,\n                  const VBResponsabilityVector<K>& taus) noexcept\n{\n    for (unsigned k {0}; k < K; ++k) {\n        alpha[k] = prior_alpha[k] + sum(taus[k]);\n    }\n}\n\ntemplate <std::size_t K>\nvoid update_alphas(VBAlphaVector<K>& alphas, const VBAlphaVector<K>& prior_alphas,\n                   const VBResponsabilityMatrix<K>& responsabilities) noexcept\n{\n    const auto S = alphas.size();\n    assert(S == prior_alphas.size() && S == responsabilities.size());\n    for (std::size_t s {0}; s < S; ++s) {\n        update_alpha(alphas[s], prior_alphas[s], responsabilities[s]);\n    }\n}\n\ninline auto marginalise(const VBTau& responsabilities, const VBReadLikelihoodArray& likelihoods) noexcept\n{\n    assert(responsabilities.size() == likelihoods.size()); // num reads\n    return inner_product(responsabilities, likelihoods);\n}\n\ntemplate <std::size_t K>\nauto marginalise(const VBResponsabilityVector<K>& responsabilities,\n                 const VBGenotype<K>& read_likelihoods) noexcept\n{\n    double result {0};\n    for (unsigned k {0}; k < K; ++k) {\n        result += marginalise(responsabilities[k], read_likelihoods[k]);\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nauto marginalise(const VBResponsabilityMatrix<K>& responsabilities,\n                 const VBReadLikelihoodMatrix<K>& read_likelihoods,\n                 const std::size_t g) noexcept\n{\n    double result {0};\n    const auto S = read_likelihoods.size(); // num samples\n    assert(S == responsabilities.size());\n    for (std::size_t s {0}; s < S; ++s) {\n        result += marginalise(responsabilities[s], read_likelihoods[s][g]);\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nvoid update_genotype_log_posteriors(LogProbabilityVector& result,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const VBResponsabilityMatrix<K>& responsabilities,\n                                    const VBReadLikelihoodMatrix<K>& read_likelihoods)\n{\n    const auto G = result.size();\n    for (std::size_t g {0}; g < G; ++g) {\n        result[g] = genotype_log_priors[g] + marginalise(responsabilities, read_likelihoods, g);\n    }\n    maths::normalise_logs(result);\n}\n\ninline auto entropy(const VBTau& tau) noexcept\n{\n    using T = VBTau::value_type;\n    return -std::accumulate(std::cbegin(tau), std::cend(tau), T {0},\n                            [] (const auto curr, const auto t) noexcept { return curr + (t * std::log(t)); });\n}\n\n// E [ln q(Z_s)]\ntemplate <std::size_t K>\nauto sum_entropies(const VBResponsabilityVector<K>& taus) noexcept\n{\n    using T = VBTau::value_type;\n    return std::accumulate(std::cbegin(taus), std::cend(taus), T {0},\n                           [] (const auto curr, const auto& tau) noexcept { return curr + entropy(tau); });\n}\n\ntemplate <std::size_t K>\nauto calculate_evidence_lower_bound(const VBAlphaVector<K>& prior_alphas,\n                                    const VBAlphaVector<K>& posterior_alphas,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const ProbabilityVector& genotype_posteriors,\n                                    const LogProbabilityVector& genotype_log_posteriors,\n                                    const VBResponsabilityMatrix<K>& taus,\n                                    const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                    const boost::optional<double> max_posterior_skip = boost::none)\n{\n    const auto G = genotype_log_priors.size();\n    const auto S = log_likelihoods.size();\n    double result {0};\n    for (std::size_t g {0}; g < G; ++g) {\n        if (!max_posterior_skip || genotype_posteriors[g] >= *max_posterior_skip) {\n            auto w = genotype_log_priors[g] - genotype_log_posteriors[g];\n            for (std::size_t s {0}; s < S; ++s) {\n                w += marginalise(taus[s], log_likelihoods[s][g]);\n            }\n            result += genotype_posteriors[g] * w;\n        }\n    }\n    for (std::size_t s {0}; s < S; ++s) {\n        result += (maths::log_beta(posterior_alphas[s]) - maths::log_beta(prior_alphas[s]));\n        result += sum_entropies(taus[s]);\n    }\n    return result;\n}\n\n// Main algorithm - single seed\n\n// Starting iteration with given genotype_log_posteriors\ntemplate <std::size_t K, typename VBLikelihoodMatrix1, typename VBLikelihoodMatrix2>\nVBLatents<K>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBLikelihoodMatrix1& log_likelihoods1,\n                      const VBLikelihoodMatrix2& log_likelihoods2,\n                      LogProbabilityVector genotype_log_posteriors,\n                      const VariationalBayesParameters& params)\n{\n    assert(!prior_alphas.empty());\n    assert(!genotype_log_priors.empty());\n    assert(!log_likelihoods1.empty());\n    assert(log_likelihoods1.size() == log_likelihoods2.size());\n    assert(prior_alphas.size() == log_likelihoods1.size()); // num samples\n    assert(log_likelihoods1.front().size() == genotype_log_priors.size()); // num genotypes\n    assert(params.max_iterations > 0);\n    auto genotype_posteriors = exp(genotype_log_posteriors);\n    auto posterior_alphas = prior_alphas;\n    auto responsabilities = init_responsabilities<K>(posterior_alphas, genotype_posteriors, log_likelihoods2);\n    assert(responsabilities.size() == log_likelihoods1.size()); // num samples\n    auto prev_evidence = std::numeric_limits<double>::lowest();\n    for (unsigned i {0}; i < params.max_iterations; ++i) {\n        update_genotype_log_posteriors(genotype_log_posteriors, genotype_log_priors, responsabilities, log_likelihoods1);\n        exp(genotype_log_posteriors, genotype_posteriors);\n        update_alphas(posterior_alphas, prior_alphas, responsabilities);\n        auto curr_evidence = calculate_evidence_lower_bound(prior_alphas, posterior_alphas, genotype_log_priors,\n                                                            genotype_posteriors, genotype_log_posteriors, responsabilities,\n                                                            log_likelihoods1, 1e-10);\n        if (curr_evidence <= prev_evidence || (curr_evidence - prev_evidence) < params.epsilon) break;\n        prev_evidence = curr_evidence;\n        update_responsabilities(responsabilities, posterior_alphas, genotype_posteriors, log_likelihoods2);\n    }\n    return VBLatents<K> {\n        std::move(genotype_posteriors), std::move(genotype_log_posteriors),\n        std::move(posterior_alphas), std::move(responsabilities)\n    };\n}\n\n// Not using inverted log likelihoods\ntemplate <std::size_t K>\nVBLatents<K>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      LogProbabilityVector genotype_log_posteriors,\n                      const VariationalBayesParameters& params)\n{\n    return run_variational_bayes(prior_alphas, genotype_log_posteriors, log_likelihoods,\n                                 log_likelihoods, genotype_log_posteriors, params);\n}\n\n// Main algorithm - multiple seed\n\ntemplate <std::size_t K>\nbool run_vb_with_matrix_inversion(const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                  const VariationalBayesParameters& params,\n                                  const std::vector<LogProbabilityVector>& seeds) noexcept\n{\n    return !params.save_memory;\n}\n\ntemplate <std::size_t K>\nstd::vector<VBLatents<K>>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      const VariationalBayesParameters& params,\n                      std::vector<LogProbabilityVector>&& seeds)\n{\n    std::vector<VBLatents<K>> result {};\n    result.reserve(seeds.size());\n    if (run_vb_with_matrix_inversion(log_likelihoods, params, seeds)) {\n        const auto inverted_log_likelihoods = invert(log_likelihoods);\n        for (auto& seed : seeds) {\n            result.push_back(detail::run_variational_bayes(prior_alphas, genotype_log_priors,\n                                                           log_likelihoods, inverted_log_likelihoods,\n                                                           std::move(seed), params));\n        }\n    } else {\n        for (auto& seed : seeds) {\n            result.push_back(detail::run_variational_bayes(prior_alphas, genotype_log_priors,\n                                                           log_likelihoods,\n                                                           std::move(seed), params));\n        }\n    }\n    return result;\n}\n\n// lower-bound calculation\n\ntemplate <std::size_t K>\nauto calculate_evidence_lower_bound(const VBAlphaVector<K>& prior_alphas,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                    const VBLatents<K>& latents)\n{\n    return calculate_evidence_lower_bound(prior_alphas, latents.alphas, genotype_log_priors,\n                                          latents.genotype_posteriors, latents.genotype_log_posteriors,\n                                          latents.responsabilities, log_likelihoods);\n    \n}\n\ntemplate <std::size_t K>\nvoid check_normalisation(VBLatents<K>& latents)\n{\n    const auto total_posterior = std::accumulate(std::cbegin(latents.genotype_posteriors), std::cend(latents.genotype_posteriors), 0.0);\n    if (total_posterior > 1.0) {\n        for (auto& p : latents.genotype_posteriors) p /= total_posterior;\n    }\n}\n\ntemplate <std::size_t K>\nstd::pair<VBLatents<K>, double>\nget_max_evidence_latents(const VBAlphaVector<K>& prior_alphas,\n                         const LogProbabilityVector& genotype_log_priors,\n                         const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                         std::vector<VBLatents<K>>&& latents)\n{\n    std::vector<double> seed_evidences(latents.size());\n    std::transform(std::cbegin(latents), std::cend(latents), std::begin(seed_evidences),\n                   [&] (const auto& seed_latents) {\n                       return calculate_evidence_lower_bound(prior_alphas, genotype_log_priors, log_likelihoods, seed_latents);\n                   });\n    const auto max_itr = std::max_element(std::cbegin(seed_evidences), std::cend(seed_evidences));\n    const auto max_idx = std::distance(std::cbegin(seed_evidences), max_itr);\n    return std::make_pair(std::move(latents[max_idx]), *max_itr);\n}\n\n} // namespace detail\n\ntemplate <std::size_t K>\nstd::pair<VBLatents<K>, double>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      const VariationalBayesParameters& params,\n                      std::vector<LogProbabilityVector> seeds)\n{\n    assert(!seeds.empty());\n    auto latents = detail::run_variational_bayes(prior_alphas, genotype_log_priors, log_likelihoods, params, std::move(seeds));\n    auto result = detail::get_max_evidence_latents(prior_alphas, genotype_log_priors, log_likelihoods, std::move(latents));\n    detail::check_normalisation(result.first);\n    return result;\n}\n\ninline VBReadLikelihoodArray::VBReadLikelihoodArray(const BaseType& underlying_likelihoods)\n: likelihoods{std::addressof(underlying_likelihoods)} {}\n\ninline void VBReadLikelihoodArray::operator=(const BaseType& other)\n{\n    likelihoods = std::addressof(other);\n}\n\ninline void VBReadLikelihoodArray::operator=(std::reference_wrapper<const BaseType> other)\n{\n    likelihoods = std::addressof(other.get());\n}\n\ninline std::size_t VBReadLikelihoodArray::size() const noexcept\n{\n    return likelihoods->size();\n}\n\ninline VBReadLikelihoodArray::BaseType::const_iterator VBReadLikelihoodArray::begin() const noexcept\n{\n    return likelihoods->begin();\n}\n\ninline VBReadLikelihoodArray::BaseType::const_iterator VBReadLikelihoodArray::end() const noexcept\n{\n    return likelihoods->end();\n}\n\ninline double VBReadLikelihoodArray::operator[](const std::size_t n) const noexcept\n{\n    return likelihoods->operator[](n);\n}\n\ntemplate <std::size_t K>\nstd::pair<VBLatents<K>, double>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      const VariationalBayesParameters& params,\n                      std::vector<LogProbabilityVector> seeds);\n\ntemplate <std::size_t K>\nMemoryFootprint\nestimate_memory_requirement(const std::vector<SampleName>& samples,\n                            const HaplotypeLikelihoodArray& likelihoods,\n                            const std::size_t num_genotypes,\n                            VariationalBayesParameters params)\n{\n    std::size_t bytes {};\n    for (const auto& sample : samples) {\n        bytes += sizeof(VBReadLikelihoodMatrix<K>);\n        bytes += sizeof(VBGenotypeVector<K>) * num_genotypes;\n        bytes += sizeof(VBResponsabilityMatrix<K>);\n        const auto num_likelihoods = likelihoods.num_likelihoods(sample);\n        const auto tau_bytes = num_likelihoods * sizeof(VBTau::value_type);\n        bytes += tau_bytes * K + sizeof(VBResponsabilityVector<K>);\n        if (!params.save_memory) {\n            bytes += sizeof(detail::VBExpandedLikelihoodMatrix<K>);\n            auto inverse_bytes = sizeof(detail::VBExpandedLikelihood::value_type) * num_genotypes + sizeof(detail::VBExpandedLikelihood);\n            inverse_bytes *= num_likelihoods;\n            inverse_bytes += sizeof(detail::VBExpandedGenotype);\n            bytes += K * inverse_bytes + sizeof(detail::VBExpandedGenotypeVector<K>);\n        }\n    }\n    return MemoryFootprint {bytes};\n};\n\n} // namespace model\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "90aca4e37c57d29e7df449e7595daefa2ad5b4ac", "size": 25015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/genotype/variational_bayes_mixture_model.hpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "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/genotype/variational_bayes_mixture_model.hpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "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/genotype/variational_bayes_mixture_model.hpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.249235474, "max_line_length": 137, "alphanum_fraction": 0.6577253648, "num_tokens": 5921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.1517447177057308}}
{"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/base/cards.h\"\n#include \"ps/support/command.h\"\n#include \"ps/detail/print.h\"\n#include \"ps/eval/class_cache.h\"\n#include \"ps/eval/holdem_class_vector_cache.h\"\n#include \"app/pretty_printer.h\"\n#include \"app/serialization_util.h\"\n#include \"ps/detail/graph.h\"\n#include \"ps/detail/popcount.h\"\n\n#include \"ps/sim/computer.h\"\n#include \"ps/sim/game_tree.h\"\n#include \"ps/sim/computer_factory.h\"\n#include \"ps/sim/_extra.h\"\n#include \"ps/sim/solver.h\"\n\n#include <boost/any.hpp>\n#include <numeric>\n#include <boost/timer/timer.hpp>\n\nnamespace ps{\nnamespace sim{\n        struct PermutationSolverArguments{\n                double clamp_epsilon{1e-6};\n                size_t grid_size    {11};\n                size_t max_popcount {1};\n                size_t dbg_use_threads{true};\n                // this is stop wasting CPU time\n                size_t max_evaluations{1000};\n\n\n                void EmitDescriptions(SolverDecl::ArgumentVisitor& V)const{\n                        V.DeclArgument(\"clamp-epsilon\" , clamp_epsilon,\n                                       \"used for clamping close to mixed strategies to non-mixed, \"\n                                       \"too small slower convergence\");\n                        V.DeclArgument(\"grid-size\" , grid_size, \"the size of each grid\");\n                        V.DeclArgument(\"max-popcount\" , max_popcount, \"number of freedoms, O(n!)\");\n                        V.DeclArgument(\"dbg-use-threads\" , dbg_use_threads, \"development aid\");\n                        V.DeclArgument(\"max-evaluations\", max_evaluations, \"upper limit of where to fail\");\n                }\n                void Read(bpt::ptree const& args){\n                        grid_size       = args.get<double>(\"grid-size\");\n                        max_popcount    = args.get<size_t>(\"max-popcount\");\n                        clamp_epsilon   = args.get<double>(\"clamp-epsilon\");\n                        dbg_use_threads = args.get<size_t>(\"dbg-use-threads\");\n                        max_evaluations = args.get<size_t>(\"max-evaluations\");\n                }\n        };\n        /*\n         * This is a wrapper around StateType. This solves the problem\n         * of computing the counter strategy and EV in observer functions.\n         */\n        struct MixedSolutionDescription{\n                MixedSolutionDescription(size_t player_index_, std::vector<size_t> const& mixed_)\n                        :player_index(player_index_),\n                        mixed(mixed_)\n                {}\n                friend std::ostream& operator<<(std::ostream& ostr, MixedSolutionDescription const& self){\n                        ostr << \"player_index = \" << self.player_index;\n                        typedef std::vector<size_t>::const_iterator CI0;\n                        const char* comma = \"\";\n                        ostr << \"mixed\" << \" = {\";\n                        for(CI0 iter= self.mixed.begin(), end=self.mixed.end();iter!=end;++iter){\n                                ostr << comma << *iter;\n                                comma = \", \";\n                        }\n                        ostr << \"}\\n\";\n                        return ostr;\n                }\n                size_t player_index;\n                std::vector<size_t> mixed;\n        };\n\n        inline std::vector<MixedSolutionDescription> MakeMixedSolutionDescription(StateType const& S, StateType const& CS){\n                /*\n                        Here we want to construct a vector which indicate all the mixed strategis.\n                        For example if every was push/fold for hero/villian excep A2o for Hero, and \n                        67o and 79o for villian, we would have\n                                        ({A2o}, {67o, 79o}).\n                 */\n                std::vector<MixedSolutionDescription> mixed_info;\n                for(size_t idx=0;idx!=S.size();++idx){\n                        auto const& c = CS[idx][0];\n                        auto const& t = S[idx][0];\n                        std::vector<size_t> mixed;\n                        for(size_t cid=0;cid!=169;++cid){\n                                if( t[cid] == c[cid] )\n                                        continue;\n                                mixed.push_back(cid);\n                        }\n                        if( mixed.empty() )\n                                continue;\n                        mixed_info.emplace_back(idx, std::move(mixed));\n                }\n                return mixed_info;\n        }\n\n        struct PermutationSolver : Solver{\n\n\n                PermutationSolver( PermutationSolverArguments const& args)\n                        : args_{args}\n                {}\n                virtual boost::optional<StateType> Execute(SolverContext& ctx,\n                                                           std::shared_ptr<GameTree> const& gt,\n                                                           GraphColouring<AggregateComputer> const& AG,\n                                                           StateType const& S0)override\n                {\n\n                        PS_LOG(trace) << \"----------------- PermutationSolver ---------------\";\n\n                        assert( args_.grid_size != 1 );\n                        \n                        Solution Sol = Solution::MakeWithDeps(gt, AG, S0);\n                        auto const& S = Sol.S;\n\n                        auto const& Counter = Sol.Counter;\n\n                        \n                        std::vector<MixedSolutionDescription> mixed_info = MakeMixedSolutionDescription(S, Counter);\n                        #if 0\n                        /*\n                                Here we want to construct a vector which indicate all the mixed strategis.\n                                For example if every was push/fold for hero/villian excep A2o for Hero, and \n                                67o and 79o for villian, we would have\n                                                ({A2o}, {67o, 79o}).\n                         */\n                        for(size_t idx=0;idx!=S.size();++idx){\n                                auto const& c = Counter[idx][0];\n                                auto const& t = S[idx][0];\n                                std::vector<size_t> mixed;\n                                for(size_t cid=0;cid!=169;++cid){\n                                        if( t[cid] == c[cid] )\n                                                continue;\n                                        mixed.push_back(cid);\n                                }\n                                if( mixed.empty() )\n                                        continue;\n                                mixed_info.emplace_back(idx, std::move(mixed));\n                        }\n                        \n                        for(auto const& mi : mixed_info){\n                                std::cout << mi << \"\\n\";\n                        }\n                        #endif\n\n                        using factor_vector_type = std::vector<size_t>;\n                        using factor_set_type = std::vector<factor_vector_type>;\n                        using factor_family = std::vector<factor_set_type>;\n\n                        std::vector<factor_family> family_vec;\n\n                        for(auto const& mi : mixed_info){\n                                \n                                factor_vector_type proto(mi.mixed.size(),1);\n\n                                factor_family family;\n\n                                family.push_back(factor_set_type{proto});\n\n                                factor_set_type s;\n                                for(size_t idx=0;idx!=mi.mixed.size();++idx){\n                                        auto next = proto;\n                                        next[idx] = args_.grid_size;\n                                        s.push_back(next);\n                                }\n                                family.push_back(s);\n\n                                family_vec.push_back(std::move(family));\n\n                        }\n\n                        enum{ Debug = 1 };\n                        if( Debug ){\n                                std::stringstream sstr;\n                                for(size_t idx=0;idx!=family_vec.size();++idx){\n                                        if(idx != 0 )\n                                                sstr << \" x \";\n                                        sstr << \"{\";\n                                        for(size_t j=0;j!=family_vec[idx].size();++j){\n                                                if(j != 0 )\n                                                        sstr << \", \";\n                                                sstr << \"{\";\n                                                for(size_t k=0;k!=family_vec[idx][j].size();++k){\n                                                        if(k != 0 )\n                                                                sstr << \", \";\n                                                        sstr << detail::to_string(family_vec[idx][j][k]);\n                                                }\n                                                sstr << \"}\";\n\n                                        }\n                                        sstr << \"}\";\n                                }\n                                std::cout << \"sstr.str() => \" << sstr.str() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,sstr.str())\n                        }\n\n                        size_t upper_bound = ( static_cast<size_t>(1) << mixed_info.size() );\n\n                        std::vector<std::vector<factor_set_type> > cross_products;\n\n                        for(size_t level = 0; level <= args_.max_popcount; ++level ){\n                                for(size_t mask = 0; mask != upper_bound; ++mask ){\n                                        if( detail::popcount(mask) != level )\n                                                continue;\n                                        cross_products.emplace_back();\n                                        for(size_t idx=0;idx!=mixed_info.size();++idx){\n                                                size_t cond = !! ( mask & static_cast<size_t>(1) << idx );\n                                                cross_products.back().push_back( family_vec[idx][cond] );\n                                        }\n                                }\n                        }\n\n\n                        if( Debug ){\n                                std::cout << \"-------------------------------------\\n\";\n                                for(auto const& cp : cross_products ){\n                                        std::stringstream sstr;\n                                        for(size_t idx=0;idx!=cp.size();++idx){\n                                                if( idx != 0 ) sstr << \" x \";\n                                                sstr << \"{\";\n                                                for(size_t k=0;k!=cp[idx].size();++k){\n                                                        if(k != 0 )\n                                                                sstr << \", \";\n                                                        sstr << detail::to_string(cp[idx][k]);\n                                                }\n                                                sstr << \"}\";\n                                        }\n                                        std::cout << \"sstr.str() => \" << sstr.str() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,sstr.str())\n                                }\n                        }\n                        \n                        using realization_type = std::vector<factor_vector_type>;\n                        using realizations_type = std::vector<realization_type>;\n                        realizations_type realizations;\n                        auto print_realizations = [&](){\n                                std::cout << \"-------------------------------------\\n\";\n                                for(auto const& realization : realizations){\n                                        std::stringstream sstr;\n                                        for(size_t idx=0;idx!=realization.size();++idx){\n                                                if( idx != 0 ) sstr << \", \";\n                                                sstr << detail::to_string(realization[idx]);\n                                        }\n                                        std::cout << \"sstr.str() => \" << sstr.str() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,sstr.str())\n                                }\n                        };\n                        print_realizations();\n                        for(std::vector<factor_set_type> const& cp : cross_products){\n                                realizations_type sub;\n                                sub.emplace_back();\n                                for(std::vector<factor_vector_type> const & group : cp ){\n                                        auto proto = std::move(sub);\n                                        for(factor_vector_type const& item : group ){\n                                                auto next = proto;\n                                                for(auto p : next){\n                                                        p.push_back(item);\n                                                        sub.push_back(p);\n                                                }\n                                        }\n                                }\n                                std::copy(sub.begin(), sub.end(), std::back_inserter(realizations));\n                                print_realizations();\n                        }\n\n                        if( Debug ){\n                                print_realizations();\n                        }\n\n\n                        std::vector<StateType> SV_family; \n                        for(auto const& realization : boost::range::unique(boost::range::sort(realizations))){\n                                std::vector<StateType> SV;\n                                SV.push_back(S);\n                                // for each player\n                                for(size_t idx=0;idx!=mixed_info.size();++idx){\n                                        auto const& mi = mixed_info[idx];\n                                        size_t pid = mi.player_index;\n                                        // for each mixed card\n                                        for(size_t j=0;j!=mi.mixed.size();++j){\n\n\n                                                // now N states increase N * (num_steps+1) states\n\n                                                size_t cid = mi.mixed[j];\n                                                size_t num_steps = realization[idx][j];\n                                                auto proto = std::move(SV);\n                                                for(size_t k=0;k<=num_steps;++k){\n                                                        double pct = 1.0 / num_steps * k;\n                                                        for(auto Q : proto ){\n                                                                Q[pid][0][cid] =       pct;\n                                                                Q[pid][1][cid] = 1.0 - pct;\n                                                                SV.push_back(Q);\n                                                        }\n                                                }\n                                        }\n                                }\n                                std::copy(SV.begin(), SV.end(), std::back_inserter(SV_family));\n                        }\n\n\n                        std::vector<Solution> solution_candidates;\n\n                        PS_LOG(trace) << \"SV_family.size() => \" << SV_family.size();\n\n                        // do nothing rather than waste computation on something not tangible\n                        if( SV_family.size() > args_.max_evaluations ){\n                                PS_LOG(warning) << \"Failing as we have \" << SV_family.size() << \" evaluations to perfom\";\n                                return {};\n                        }\n\n                        #if 0\n                        for(size_t idx=0;idx!=SV_family.size();++idx){\n                                std::cout << \"idx => \" << idx << \" out of \" << SV_family.size() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,idx)\n                                auto Q = SV_family[idx];\n                                computation_kernel::InplaceClamp(Q, args_.clamp_epsilon);\n                                auto candidate = Solution::MakeWithDeps(gt, AG, Q);\n                                solution_candidates.push_back(candidate);\n                        }\n                        #else\n                        std::vector<std::function<Solution()> > tasks;\n                        for(size_t idx=0;idx!=SV_family.size();++idx){\n                                auto atom = [&,idx](){\n                                        auto Q = SV_family[idx];\n                                        computation_kernel::InplaceClamp(Q, args_.clamp_epsilon);\n                                        auto candidate = Solution::MakeWithDeps(gt, AG, Q);\n                                        return candidate;\n                                };\n                                tasks.push_back(atom);\n                        }\n                        if( args_.dbg_use_threads ){\n                                std::vector<std::future<Solution> > futs;\n                                for(auto& t : tasks ){\n                                        //futs.push_back( std::async(std::launch::async, t) );\n                                        futs.push_back( std::async(t) );\n                                }\n                                for(auto& f : futs){\n                                        solution_candidates.push_back(f.get());\n                                }\n                        } else {\n                                for(auto& t : tasks ){\n                                        solution_candidates.push_back(t());\n                                }\n                        }\n                        #endif\n\n                        std::vector<Pretty::LineItem> dbg;\n                        dbg.push_back(std::vector<std::string>{\"n\", \"|.|\", \"Gamma\", \"Mixed\"});\n                        dbg.push_back(Pretty::LineBreak);\n\n                        std::sort(solution_candidates.begin(), solution_candidates.end());\n\n                        for(auto const& sol : solution_candidates){\n\n                                std::vector<std::string> dbg_line;\n                                dbg_line.push_back(boost::lexical_cast<std::string>(sol.Level));\n                                dbg_line.push_back(boost::lexical_cast<std::string>(sol.Norm));\n                                dbg_line.push_back(detail::to_string(sol.Gamma));\n                                dbg_line.push_back(detail::to_string(sol.Mixed));\n                                dbg.push_back(std::move(dbg_line));\n                        }\n\n\n                        Pretty::RenderTablePretty(std::cout, dbg);\n\n                        if( solution_candidates.empty() )\n                               return {};\n                        return solution_candidates.front().S;\n                        #if 0\n                        if( solution_candidates.size() && solution_candidates.front().Level <= 1 ){\n                                auto const& best = solution_candidates.front();\n                                std::cout << \"detail::to_string(best.Gamma) => \" << detail::to_string(best.Gamma) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,detail::to_string(best.Gamma))\n                                return best.S;\n                        } else {\n                                ctx.Message(\"no best :(\");\n                        }\n                        return {};\n                        #endif\n                }\n                virtual std::string StringDescription()const override{\n                        std::stringstream sstr;\n                        sstr << \"PermutationSolver{}\";\n                        return sstr.str();\n                }\n        private:\n                PermutationSolverArguments args_;\n        };\n        \n        struct PermutationSolverDecl : SolverDecl{\n                virtual void Accept(ArgumentVisitor& V)const override{\n                        PermutationSolverArguments proto;\n                        proto.EmitDescriptions(V);\n                }\n                virtual std::shared_ptr<Solver> Make( bpt::ptree const& args)const override\n                {\n                        PermutationSolverArguments bargs;\n                        bargs.Read(args);\n                        return std::make_shared<PermutationSolver>(bargs);\n                }\n        };\n\n        static SolverRegister<PermutationSolverDecl> PermutationSolverReg(\"permutation\");\n        \n        \n        \n        struct SinglePermutationSolver : Solver{\n\n                virtual boost::optional<StateType> Execute(SolverContext& ctx,\n                                                           std::shared_ptr<GameTree> const& gt,\n                                                           GraphColouring<AggregateComputer> const& AG,\n                                                           StateType const& S0)override\n                {\n\n                        PS_LOG(trace) << \"----------------- SinglePermutationSolver ---------------\";\n\n                        SequenceConsumer seq;\n                        seq.Consume(Solution::MakeWithDeps(gt, AG, S0));\n                        for(size_t loop_count=0;;++loop_count){\n\n                                std::cout << \"loop_count => \" << loop_count << \"\\n\"; // __CandyPrint__(cxx-print-scalar,loop_count)\n\n                                auto opt_sol = seq.AsOptSolution();\n                                BOOST_ASSERT( opt_sol );\n                                Solution const& Sol = opt_sol.get();\n\n                                auto const& S  = Sol.S;\n                                auto const& CS = Sol.Counter;\n\n                                std::vector<MixedSolutionDescription> mixed_info = MakeMixedSolutionDescription(S, CS);\n\n                                std::vector<StateType> candidates;\n\n                                for(auto const& mi : mixed_info ){\n                                        for(auto const& cid : mi.mixed ){\n                                                auto next = S;\n                                                next[mi.player_index][0][cid] = 1.0;\n                                                next[mi.player_index][1][cid] = 0.0;\n                                                candidates.push_back(next);\n                                                next[mi.player_index][0][cid] = 0.0;\n                                                next[mi.player_index][1][cid] = 1.0;\n                                                candidates.push_back(next);\n                                        }\n                                }\n                                std::cout << \"mixed_info.size() => \" << mixed_info.size() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,mixed_info.size())\n                                std::vector<std::function<Solution()> > tasks;\n                                for(auto const& cand : candidates){\n                                        auto atom = [&]()->Solution{\n                                                auto solution = Solution::MakeWithDeps(gt, AG, cand);\n                                                return solution;\n                                        };\n                                        tasks.emplace_back(atom);\n                                }\n                                std::cout << \"tasks.size() => \" << tasks.size() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,tasks.size())\n                                std::vector<std::future<Solution> > futs;\n                                for(auto& t : tasks ){\n                                        futs.push_back( std::async(std::launch::async, t) );\n                                }\n                                std::vector<Solution> solution_candidates;\n                                for(auto& f : futs){\n                                        solution_candidates.push_back(f.get());\n                                }\n                                #if 0\n                                std::mutex mtx;\n                                auto child = [&]()mutable{\n                                        for(;;){\n                                                \n                                                mtx.lock();\n                                                if( tasks.empty() ){\n                                                        mtx.unlock();\n                                                        return;\n                                                }\n                                                auto fut = std::move(tasks.back());\n                                                tasks.pop_back();\n                                                mtx.unlock();\n                                                fut();\n                                        }\n                                };\n                                std::vector<std::thread> tg;\n                                for(size_t idx=0;idx!=std::thread::hardware_concurrency();++idx){\n                                        tg.emplace_back(child);\n                                }\n                                for(auto& _ : tg){\n                                        _.join();\n                                }\n                                #endif\n                                \n                                bool do_break = true;\n                                std::cout << \"HEAD \" << Sol.Total << \"\\n\"; // __CandyPrint__(cxx-print-scalar,Sol.Total)\n                                for(auto& _ : solution_candidates){\n                                        switch(seq.Consume(_)){\n                                        case SequenceConsumer::Ctrl_Rejected:\n                                                break;\n                                        case SequenceConsumer::Ctrl_Accepted:\n                                                std::cout << \"Accepted\\n\";\n                                                do_break = false;\n                                                break;\n                                        case SequenceConsumer::Ctrl_Perfect:\n                                                return seq.AsOptState();\n                                        }\n                                }\n\n                                if( do_break ){\n                                        break;\n                                }\n                        }\n                        return seq.AsOptState();\n                }\n                virtual std::string StringDescription()const override{\n                        std::stringstream sstr;\n                        sstr << \"SinglePermutationSolver{}\";\n                        return sstr.str();\n                }\n        };\n        \n        struct SinglePermutationSolverDecl : SolverDecl{\n                virtual void Accept(ArgumentVisitor& V)const override{\n                }\n                virtual std::shared_ptr<Solver> Make( bpt::ptree const& args)const override\n                {\n                        return std::make_shared<SinglePermutationSolver>();\n                }\n        };\n\n        static SolverRegister<SinglePermutationSolverDecl> SinglePermutationSolverReg(\"single-permutation\");\n\n} // end namespace sim\n} // end namespace ps\n", "meta": {"hexsha": "744e945070d06cec0fc3bb15166fa25c545408fe", "size": 28847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/sim/solver_permutation.cpp", "max_stars_repo_name": "mastermind88/CandyPoker", "max_stars_repo_head_hexsha": "37b502ce6ea8733ce0b70476fcf32930961923a8", "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": "lib/sim/solver_permutation.cpp", "max_issues_repo_name": "mastermind88/CandyPoker", "max_issues_repo_head_hexsha": "37b502ce6ea8733ce0b70476fcf32930961923a8", "max_issues_repo_licenses": ["MIT"], "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/sim/solver_permutation.cpp", "max_forks_repo_name": "mastermind88/CandyPoker", "max_forks_repo_head_hexsha": "37b502ce6ea8733ce0b70476fcf32930961923a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.0703971119, "max_line_length": 188, "alphanum_fraction": 0.3700558117, "num_tokens": 4476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2942149845400438, "lm_q1q2_score": 0.15170310553298572}}
{"text": "#include <fstream>\n#include <utility>\n#include <vector>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/log/trivial.hpp>\n#include <bitset>\n\n#include \"tensorflow/cc/ops/const_op.h\"\n#include \"tensorflow/cc/ops/image_ops.h\"\n#include \"tensorflow/cc/ops/standard_ops.h\"\n#include \"tensorflow/core/framework/graph.pb.h\"\n#include \"tensorflow/core/graph/default_device.h\"\n#include \"tensorflow/core/graph/graph_def_builder.h\"\n#include \"tensorflow/core/lib/core/threadpool.h\"\n#include \"tensorflow/core/lib/io/path.h\"\n#include \"tensorflow/core/lib/strings/stringprintf.h\"\n#include \"tensorflow/core/platform/init_main.h\"\n#include \"tensorflow/core/public/session.h\"\n#include \"tensorflow/core/util/command_line_flags.h\"\n\n\nusing tensorflow::Flag;\nusing tensorflow::Tensor;\nusing tensorflow::Status;\nusing tensorflow::string;\nusing tensorflow::int32;\n\n#include \"tensorflow.h\"\n\nusing namespace std;\nusing namespace boost;\n\nnamespace ml {\n    namespace images {\n\n        Inception::Inception(std::string graph_file_name, std::string labels_file_name) {\n            tensorflow::GraphDef graph_def;\n            Status status = ReadBinaryProto(tensorflow::Env::Default(), graph_file_name, &graph_def);\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"unable to load compute graph at %s, %s\") % graph_file_name % status.error_message();\n            }\n            status = tensorflow::NewSession(tensorflow::SessionOptions(), &session);\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"failure creating new session, %s\") % status.error_message();\n            }\n            status = session->Create(graph_def);\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"unable to create session for compute graph at %s, %s\") % graph_file_name % status.error_message();\n            }\n            ifstream file(labels_file_name);\n            if (!file) {\n                BOOST_LOG_TRIVIAL(error) << format(\"Labels file %s not found.\") % labels_file_name;\n            }\n            labels.clear();\n            string line;\n            while (getline(file, line)) {\n                labels.push_back(line);\n            }\n            found_label_count = labels.size();\n            const int padding = 16;\n            while (labels.size() % padding) {\n                labels.emplace_back();\n            }\n        }\n\n        Inception::~Inception() {\n            Status session_close = session->Close();\n            if (!session_close.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"could not close session, %s\") % session_close.error_message();\n            }\n        }\n\n        vector<inception_score> Inception::classify(memory_block *block, int width, int height) {\n            vector<inception_score> result;\n\n            auto root = tensorflow::Scope::NewRootScope();\n            using namespace ::tensorflow::ops;\n\n            tensorflow::StringPiece data(block->memory, block->size);\n            Tensor input(tensorflow::DT_STRING, tensorflow::TensorShape());\n            (&input)->scalar<string>()() = data.ToString();\n\n            auto reader = Placeholder(root.WithOpName(\"input\"), tensorflow::DataType::DT_STRING);\n            const int wanted_channels = 3;\n            tensorflow::Output image_reader;\n\n            switch(block->type) {\n                case png:\n                    image_reader = DecodePng(root.WithOpName(\"png_reader\"), reader, DecodePng::Channels(wanted_channels));\n                    break;\n                case gif:\n                    image_reader = Squeeze(root.WithOpName(\"squeeze_first_dim\"), DecodeGif(root.WithOpName(\"gif_reader\"), reader));\n                    break;\n                case bmp:\n                    image_reader = DecodeBmp(root.WithOpName(\"bmp_reader\"), reader);\n                    break;\n                case jpg:\n                    image_reader = DecodeJpeg(root.WithOpName(\"jpeg_reader\"), reader, DecodeJpeg::Channels(wanted_channels));\n                case unkown:\n                    BOOST_LOG_TRIVIAL(error) << \"could not determine image type to analyze, aborting...\";\n                    return result;\n            }\n\n            auto float_caster = Cast(root.WithOpName(\"float_caster\"), reader, tensorflow::DT_FLOAT);\n            auto dims_expander = ExpandDims(root, float_caster, 0);\n            auto resized = ResizeBilinear(root, dims_expander, Const(root.WithOpName(\"size\"), {height, width}));\n\n            Div(root.WithOpName(\"normalized\"), Sub(root, resized, {input_mean}), {input_std});\n\n            tensorflow::GraphDef image_graph;\n            Status status = root.ToGraphDef(&image_graph);\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"could not create image_graph definition, %s\") % status.error_message();\n                return result;\n            }\n\n            session.reset(tensorflow::NewSession(tensorflow::SessionOptions()));\n\n            status = session->Create(image_graph);\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"could not create image_graph, %s\") % status.error_message();\n                return result;\n            }\n\n            vector<Tensor> outputs;\n            vector<pair<string, tensorflow::Tensor>> inputs = { {\"input\", input}, };\n            status = session->Run({inputs}, {\"normalized\"}, {}, &outputs);\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"failure during analysis, %s\") % status.error_message();\n                return result;\n            }\n\n            string output_name = \"top_k\";\n            TopK(root.WithOpName(output_name), outputs[0], min(5, static_cast<int>(found_label_count)));\n\n            tensorflow::GraphDef label_graph;\n            status = root.ToGraphDef(&label_graph);\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"could not create label_graph definition, %s\") % status.error_message();\n                return result;\n            }\n\n            session.reset(tensorflow::NewSession(tensorflow::SessionOptions()));\n\n            status = session->Create(label_graph);\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"could not create label_graph, %s\") % status.error_message();\n                return result;\n            }\n\n            std::vector<Tensor> out_tensors;\n            status = session->Run({}, {output_name + \":0\", output_name + \":1\"}, {}, &out_tensors));\n\n            if (!status.ok()) {\n                BOOST_LOG_TRIVIAL(error) << format(\"could not create execute run, %s\") % status.error_message();\n                return result;\n            }\n\n            tensorflow::TTypes<float>::Flat scores_flat = out_tensors[0].flat<float>();\n            tensorflow::TTypes<int32>::Flat indices_flat = out_tensors[1].flat<int32>();\n\n            for (int pos = 0; pos < min(5, static_cast<int>(found_label_count)); ++pos) {\n                const int label_index = indices_flat(pos);\n                const float score = scores_flat(pos);\n                result.push_back(inception_score{labels[label_index], label_index, score});\n            }\n\n            return result;\n        }\n\n    }\n}", "meta": {"hexsha": "04d30d31fc2dccc0022c83bb829e7b20d31f0db6", "size": 7228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tensorflow.cpp", "max_stars_repo_name": "witlox/marvin", "max_stars_repo_head_hexsha": "1cfc4508e922205101fa49a838eba66df9f1c7f0", "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/tensorflow.cpp", "max_issues_repo_name": "witlox/marvin", "max_issues_repo_head_hexsha": "1cfc4508e922205101fa49a838eba66df9f1c7f0", "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/tensorflow.cpp", "max_forks_repo_name": "witlox/marvin", "max_forks_repo_head_hexsha": "1cfc4508e922205101fa49a838eba66df9f1c7f0", "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.5402298851, "max_line_length": 150, "alphanum_fraction": 0.5900664084, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.15170310234205764}}
{"text": "#include \"traffic/traffic_info.hpp\"\n#include \"traffic/speed_groups.hpp\"\n\n#include \"indexer/classificator_loader.hpp\"\n\n#include \"platform/platform.hpp\"\n\n#include \"base/assert.hpp\"\n#include \"base/logging.hpp\"\n#include \"base/math.hpp\"\n\n#include \"std/cstdint.hpp\"\n#include \"std/map.hpp\"\n#include \"std/sstream.hpp\"\n#include \"std/string.hpp\"\n#include \"std/vector.hpp\"\n\n#include \"pyhelpers/module_version.hpp\"\n#include \"pyhelpers/vector_list_conversion.hpp\"\n#include \"pyhelpers/vector_uint8.hpp\"\n\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/map_indexing_suite.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\nnamespace\n{\nusing namespace boost::python;\n\nstruct SegmentSpeeds\n{\n  SegmentSpeeds() = default;\n  SegmentSpeeds(double weightedSpeed, double weightedRefSpeed, double weight)\n    : m_weightedSpeed(weightedSpeed), m_weightedRefSpeed(weightedRefSpeed), m_weight(weight)\n  {\n  }\n\n  double m_weightedSpeed = 0;\n  double m_weightedRefSpeed = 0;\n  double m_weight = 0;\n};\n\nusing SegmentMapping = map<traffic::TrafficInfo::RoadSegmentId, SegmentSpeeds>;\n\nstring SegmentSpeedsRepr(SegmentSpeeds const & v)\n{\n  ostringstream ss;\n  ss << \"SegmentSpeeds(\"\n     << \" weighted_speed=\" << v.m_weightedSpeed << \" weighted_ref_speed=\" << v.m_weightedRefSpeed\n     << \" weight=\" << v.m_weight << \" )\";\n  return ss.str();\n}\n\ntraffic::TrafficInfo::Coloring TransformToSpeedGroups(SegmentMapping const & segmentMapping)\n{\n  double const kEps = 1e-9;\n  traffic::TrafficInfo::Coloring result;\n  for (auto const & kv : segmentMapping)\n  {\n    double const ws = kv.second.m_weightedSpeed;\n    double const wrs = kv.second.m_weightedRefSpeed;\n    double const w = kv.second.m_weight;\n    if (base::AlmostEqualAbs(w, 0.0, kEps))\n    {\n      LOG(LWARNING, (\"A traffic segment has zero weight.\"));\n      continue;\n    }\n    double const u = ws / w;\n    double const v = wrs / w;\n    bool const uz = base::AlmostEqualAbs(u, 0.0, kEps);\n    bool const vz = base::AlmostEqualAbs(v, 0.0, kEps);\n    if (uz && vz)\n    {\n      result[kv.first] = traffic::SpeedGroup::TempBlock;\n    }\n    else if (vz)\n    {\n      LOG(LWARNING, (\"A traffic segment has zero reference speed.\"));\n      continue;\n    }\n    else\n    {\n      double p = 100.0 * u / v;\n      p = base::clamp(p, 0.0, 100.0);\n      result[kv.first] = traffic::GetSpeedGroupByPercentage(p);\n    }\n  }\n  return result;\n}\n\nstring RoadSegmentIdRepr(traffic::TrafficInfo::RoadSegmentId const & v)\n{\n  ostringstream ss;\n  ss << \"RoadSegmentId(\" << v.m_fid << \", \" << v.m_idx << \", \" << int(v.m_dir) << \")\";\n  return ss.str();\n}\n\nboost::python::list GenerateTrafficKeys(string const & mwmPath)\n{\n  vector<traffic::TrafficInfo::RoadSegmentId> result;\n  traffic::TrafficInfo::ExtractTrafficKeys(mwmPath, result);\n  return std_vector_to_python_list(result);\n}\n\nvector<uint8_t> GenerateTrafficValues(vector<traffic::TrafficInfo::RoadSegmentId> const & keys,\n                                      boost::python::dict const & segmentMappingDict,\n                                      uint8_t useTempBlock)\n{\n  SegmentMapping segmentMapping;\n  boost::python::list mappingKeys = segmentMappingDict.keys();\n  for (size_t i = 0; i < len(mappingKeys); ++i)\n  {\n    object curArg = segmentMappingDict[mappingKeys[i]];\n    if (curArg)\n      segmentMapping[extract<traffic::TrafficInfo::RoadSegmentId>(mappingKeys[i])] =\n          extract<SegmentSpeeds>(segmentMappingDict[mappingKeys[i]]);\n  }\n\n  traffic::TrafficInfo::Coloring const knownColors = TransformToSpeedGroups(segmentMapping);\n  traffic::TrafficInfo::Coloring coloring;\n  traffic::TrafficInfo::CombineColorings(keys, knownColors, coloring);\n\n  vector<traffic::SpeedGroup> values(coloring.size());\n\n  size_t i = 0;\n  for (auto const & kv : coloring)\n  {\n    ASSERT_EQUAL(kv.first, keys[i], ());\n    if (useTempBlock == 0 && kv.second == traffic::SpeedGroup::TempBlock)\n      continue;\n\n    values[i] = kv.second;\n    ++i;\n  }\n  ASSERT_EQUAL(i, values.size(), ());\n\n  vector<uint8_t> buf;\n  traffic::TrafficInfo::SerializeTrafficValues(values, buf);\n  return buf;\n}\n\nvector<uint8_t> GenerateTrafficValuesFromList(boost::python::list const & keys,\n                                              boost::python::dict const & segmentMappingDict)\n{\n  vector<traffic::TrafficInfo::RoadSegmentId> keysVec =\n      python_list_to_std_vector<traffic::TrafficInfo::RoadSegmentId>(keys);\n\n  return GenerateTrafficValues(keysVec, segmentMappingDict, 1 /* useTempBlock */);\n}\n\nvector<uint8_t> GenerateTrafficValuesFromBinary(vector<uint8_t> const & keysBlob,\n                                                boost::python::dict const & segmentMappingDict,\n                                                uint8_t useTempBlock = 1)\n{\n  vector<traffic::TrafficInfo::RoadSegmentId> keys;\n  traffic::TrafficInfo::DeserializeTrafficKeys(keysBlob, keys);\n\n  return GenerateTrafficValues(keys, segmentMappingDict, useTempBlock);\n}\n\nvoid LoadClassificator(string const & classifPath)\n{\n  GetPlatform().SetResourceDir(classifPath);\n  classificator::Load();\n}\n}  // namespace\n\nBOOST_PYTHON_MODULE(pytraffic)\n{\n  using namespace boost::python;\n  scope().attr(\"__version__\") = PYBINDINGS_VERSION;\n\n  // Register the to-python converters.\n  to_python_converter<vector<uint8_t>, vector_uint8t_to_str>();\n  vector_uint8t_from_python_str();\n\n  class_<SegmentSpeeds>(\"SegmentSpeeds\", init<double, double, double>())\n      .def(\"__repr__\", &SegmentSpeedsRepr)\n      .def_readwrite(\"weighted_speed\", &SegmentSpeeds::m_weightedSpeed)\n      .def_readwrite(\"weighted_ref_speed\", &SegmentSpeeds::m_weightedRefSpeed)\n      .def_readwrite(\"weight\", &SegmentSpeeds::m_weight)\n  ;\n\n  class_<traffic::TrafficInfo::RoadSegmentId>(\"RoadSegmentId\", init<uint32_t, uint16_t, uint8_t>())\n      .def(\"__repr__\", &RoadSegmentIdRepr)\n      .add_property(\"fid\", &traffic::TrafficInfo::RoadSegmentId::GetFid)\n      .add_property(\"idx\", &traffic::TrafficInfo::RoadSegmentId::GetIdx)\n      .add_property(\"dir\", &traffic::TrafficInfo::RoadSegmentId::GetDir)\n  ;\n\n  class_<std::vector<traffic::TrafficInfo::RoadSegmentId>>(\"RoadSegmentIdVec\")\n      .def(vector_indexing_suite<std::vector<traffic::TrafficInfo::RoadSegmentId>>());\n\n  enum_<traffic::SpeedGroup>(\"SpeedGroup\")\n      .value(\"G0\", traffic::SpeedGroup::G0)\n      .value(\"G1\", traffic::SpeedGroup::G1)\n      .value(\"G2\", traffic::SpeedGroup::G2)\n      .value(\"G3\", traffic::SpeedGroup::G3)\n      .value(\"G4\", traffic::SpeedGroup::G4)\n      .value(\"G5\", traffic::SpeedGroup::G5)\n      .value(\"TempBlock\", traffic::SpeedGroup::TempBlock)\n      .value(\"Unknown\", traffic::SpeedGroup::Unknown)\n  ;\n\n  def(\"load_classificator\", LoadClassificator);\n  def(\"generate_traffic_keys\", GenerateTrafficKeys);\n  def(\"generate_traffic_values_from_list\", GenerateTrafficValuesFromList);\n  def(\"generate_traffic_values_from_binary\", GenerateTrafficValuesFromBinary,\n      (arg(\"keysBlob\"), arg(\"segmentMappingDict\"), arg(\"useTempBlock\") = 1));\n}\n", "meta": {"hexsha": "0b17d7b26a9c06d33d282bba6aaa7f6e467d423a", "size": 6938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "traffic/pytraffic/bindings.cpp", "max_stars_repo_name": "fossabot/omim", "max_stars_repo_head_hexsha": "a76f25d83726d1a8256ba5379c0d9d42d8ab134f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T02:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-27T02:45:22.000Z", "max_issues_repo_path": "traffic/pytraffic/bindings.cpp", "max_issues_repo_name": "MohammadMoeinfar/omim", "max_issues_repo_head_hexsha": "7b7d1990143bc3cbe218ea14b5428d0fc02d78fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-14T15:26:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-16T11:00:33.000Z", "max_forks_repo_path": "traffic/pytraffic/bindings.cpp", "max_forks_repo_name": "vmihaylenko/omim", "max_forks_repo_head_hexsha": "00087f340e723fc611cbc82e0ae898b9053b620a", "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.8815165877, "max_line_length": 99, "alphanum_fraction": 0.693283367, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.15170309915112967}}
{"text": "#include \"sif/pedestriancost.h\"\n#include \"sif/costconstants.h\"\n\n#include \"baldr/accessrestriction.h\"\n#include \"midgard/constants.h\"\n#include \"midgard/util.h\"\n\n#ifdef INLINE_TEST\n#include \"test/test.h\"\n#include <random>\n#include <boost/property_tree/json_parser.hpp>\n#endif\n\nusing namespace valhalla::baldr;\n\nnamespace valhalla {\nnamespace sif {\n\n// Default options/values\nnamespace {\n\n// Maximum route distances\nconstexpr uint32_t kMaxDistanceFoot        = 100000; // 100 km\nconstexpr uint32_t kMaxDistanceWheelchair  = 10000;  // 10 km\n\n// Default speeds\nconstexpr float kDefaultSpeedFoot          = 5.1f;   // 3.16 MPH\nconstexpr float kDefaultSpeedWheelchair    = 4.0f;   // 2.5  MPH  TODO\n\n// Penalty to take steps\nconstexpr float kDefaultStepPenaltyFoot       = 30.0f;   // 30 seconds\nconstexpr float kDefaultStepPenaltyWheelchair = 600.0f;  // 10 minutes\n\n// Maximum grade30\nconstexpr uint32_t kDefaultMaxGradeFoot = 90;\nconstexpr uint32_t kDefaultMaxGradeWheelchair = 12; // Conservative for now...\n\n// Other defaults (not dependent on type)\nconstexpr float kModeFactor             = 1.5f;   // Favor this mode?\nconstexpr float kDefaultManeuverPenalty = 5.0f;   // Seconds\nconstexpr float kDefaultGatePenalty     = 10.0f;  // Seconds\nconstexpr float kDefaultWalkwayFactor   = 0.9f;   // Slightly favor walkways\nconstexpr float kDefaultSideWalkFactor  = 0.95f;  // Slightly favor sidewalks\nconstexpr float kDefaultAlleyFactor     = 2.0f;   // Avoid alleys\nconstexpr float kDefaultDrivewayFactor  = 5.0f;   // Avoid driveways\nconstexpr float kDefaultFerryCost               = 300.0f; // Seconds\nconstexpr float kDefaultCountryCrossingCost     = 600.0f; // Seconds\nconstexpr float kDefaultCountryCrossingPenalty  = 0.0f;   // Seconds\nconstexpr float kDefaultUseFerry = 1.0f;\n\n// Maximum distance at the beginning or end of a multimodal route\n// that you are willing to travel for this mode.  In this case,\n// it is the max walking distance.\nconstexpr uint32_t kTransitStartEndMaxDistance    = 2415;   // 1.5 miles\n\n// Maximum transfer distance between stops that you are willing\n// to travel for this mode.  In this case, it is the max walking\n// distance you are willing to walk between transfers.\nconstexpr uint32_t kTransitTransferMaxDistance   = 805;   // 0.5 miles\n\n// Avoid roundabouts\nconstexpr float kRoundaboutFactor = 2.0f;\n\n// Maximum ferry penalty (when use_ferry == 0). Can't make this too large\n// since a ferry is sometimes required to complete a route.\nconstexpr float kMaxFerryPenalty = 8.0f * 3600.0f; // 8 hours\n\n// Minimum and maximum average pedestrian speed (to validate input).\nconstexpr float kMinPedestrianSpeed = 0.5f;\nconstexpr float kMaxPedestrianSpeed = 25.0f;\n\n// Crossing penalties. TODO - may want to lower stop impact when\n// 2 cycleways or walkways cross\nconstexpr uint32_t kCrossingCosts[] = { 0, 0, 1, 1, 2, 3, 5, 15 };\n}\n\n// Maximum amount of seconds that will be allowed to be passed in to influence paths\n// This can't be too high because sometimes a certain kind of path is required to be taken\nconstexpr float kMaxSeconds = 12.0f * kSecPerHour; // 12 hours\n\nconstexpr float kMinFactor = 0.1f;\nconstexpr float kMaxFactor = 100000.0f;\n\n// Valid ranges and defaults\nconstexpr ranged_default_t<uint32_t> kMaxDistanceWheelchairRange{0, kMaxDistanceWheelchair, kMaxDistanceFoot};\nconstexpr ranged_default_t<uint32_t> kMaxDistanceFootRange{0, kMaxDistanceFoot, kMaxDistanceFoot};\n\nconstexpr ranged_default_t<float> kSpeedWheelchairRange{kMinPedestrianSpeed, kDefaultSpeedWheelchair, kMaxPedestrianSpeed};\nconstexpr ranged_default_t<float> kSpeedFootRange{kMinPedestrianSpeed, kDefaultSpeedFoot, kMaxPedestrianSpeed};\n\nconstexpr ranged_default_t<float> kStepPenaltyWheelchairRange{0, kDefaultStepPenaltyWheelchair, kMaxSeconds};\nconstexpr ranged_default_t<float> kStepPenaltyFootRange{0, kDefaultStepPenaltyFoot, kMaxSeconds};  \n\nconstexpr ranged_default_t<uint32_t> kMaxGradeWheelchairRange{0, kDefaultMaxGradeWheelchair, kDefaultMaxGradeFoot};\nconstexpr ranged_default_t<uint32_t> kMaxGradeFootRange{0, kDefaultMaxGradeFoot, kDefaultMaxGradeFoot};\n\n// Other valid ranges and defaults (not dependent on type)\nconstexpr ranged_default_t<float> kModeFactorRange{kMinFactor, kModeFactor, kMaxFactor};\nconstexpr ranged_default_t<float> kManeuverPenaltyRange{kMinFactor, kDefaultManeuverPenalty, kMaxSeconds};\nconstexpr ranged_default_t<float> kGatePenaltyRange{kMinFactor, kDefaultGatePenalty, kMaxSeconds};\nconstexpr ranged_default_t<float> kWalkwayFactorRange{kMinFactor, kDefaultWalkwayFactor, kMaxFactor};\nconstexpr ranged_default_t<float> kSideWalkFactorRange{kMinFactor, kDefaultSideWalkFactor, kMaxFactor};\nconstexpr ranged_default_t<float> kAlleyFactorRange{kMinFactor, kDefaultAlleyFactor, kMaxFactor};\nconstexpr ranged_default_t<float> kDrivewayFactorRange{kMinFactor, kDefaultDrivewayFactor, kMaxFactor};\nconstexpr ranged_default_t<float> kFerryCostRange{0, kDefaultFerryCost, kMaxSeconds};\nconstexpr ranged_default_t<float> kCountryCrossingCostRange{0, kDefaultCountryCrossingCost, kMaxSeconds};\nconstexpr ranged_default_t<float> kCountryCrossingPenaltyRange{0, kDefaultCountryCrossingPenalty, kMaxSeconds};\nconstexpr ranged_default_t<uint32_t> kTransitStartEndMaxDistanceRange{0, kTransitStartEndMaxDistance,\n                                                                     100000}; // Max 100k\nconstexpr ranged_default_t<uint32_t> kTransitTransferMaxDistanceRange{0, kTransitTransferMaxDistance,\n                                                                      50000}; // Max 50k\nconstexpr ranged_default_t<float> kUseFerryRange{0, kDefaultUseFerry, 1.0f};\n\n/**\n * Derived class providing dynamic edge costing for pedestrian routes.\n */\nclass PedestrianCost : public DynamicCost {\n public:\n  /**\n   * Constructor. Configuration / options for pedestrian costing are provided\n   * via a property tree (JSON).\n   * @param  pt  Property tree with configuration/options.\n   */\n  //Armin H.\n  PedestrianCost(const boost::property_tree::ptree& pt, baldr::GraphReader& graphreader);\n  //Armin H.\n\n  virtual ~PedestrianCost();\n\n  /**\n   * Does the costing method allow multiple passes (with relaxed hierarchy\n   * limits).\n   * @return  Returns true if the costing model allows multiple passes.\n   */\n  virtual bool AllowMultiPass() const;\n\n  /**\n   * This method overrides the max_distance with the max_distance_mm per segment\n   * distance. An example is a pure walking route may have a max distance of\n   * 10000 meters (10km) but for a multi-modal route a lower limit of 5000\n   * meters per segment (e.g. from origin to a transit stop or from the last\n   * transit stop to the destination).\n   */\n  virtual void UseMaxMultiModalDistance();\n\n  /**\n   * Returns the maximum transfer distance between stops that you are willing\n   * to travel for this mode.  In this case, it is the max walking\n   * distance you are willing to walk between transfers.\n   */\n  virtual uint32_t GetMaxTransferDistanceMM();\n\n  /**\n   * This method overrides the factor for this mode.  The higher the value\n   * the more the mode is favored.\n   */\n  virtual float GetModeFactor();\n\n  /**\n   * Get the access mode used by this costing method.\n   * @return  Returns access mode.\n   */\n  uint32_t access_mode() const;\n\n  /**\n   * Checks if access is allowed for the provided directed edge.\n   * This is generally based on mode of travel and the access modes\n   * allowed on the edge. However, it can be extended to exclude access\n   * based on other parameters.\n   * @param  edge     Pointer to a directed edge.\n   * @param  pred     Predecessor edge information.\n   * @param  tile     current tile\n   * @param  edgeid   edgeid that we care about\n   * @return  Returns true if access is allowed, false if not.\n   */\n  virtual bool Allowed(const baldr::DirectedEdge* edge,\n                       const EdgeLabel& pred,\n                       const baldr::GraphTile*& tile,\n                       const baldr::GraphId& edgeid) const;\n\n  /**\n   * Checks if access is allowed for an edge on the reverse path\n   * (from destination towards origin). Both opposing edges are\n   * provided.\n   * @param  edge           Pointer to a directed edge.\n   * @param  pred           Predecessor edge information.\n   * @param  opp_edge       Pointer to the opposing directed edge.\n   * @param  tile           Tile for the opposing edge (for looking\n   *                        up restrictions).\n   * @param  opp_edgeid     Opposing edge Id\n   * @return  Returns true if access is allowed, false if not.\n   */\n  virtual bool AllowedReverse(const baldr::DirectedEdge* edge,\n                 const EdgeLabel& pred,\n                 const baldr::DirectedEdge* opp_edge,\n                 const baldr::GraphTile*& tile,\n                 const baldr::GraphId& opp_edgeid) const;\n\n  /**\n   * Checks if access is allowed for the provided node. Node access can\n   * be restricted if bollards or gates are present.\n   * @param  edge  Pointer to node information.\n   * @return  Returns true if access is allowed, false if not.\n   */\n  virtual bool Allowed(const baldr::NodeInfo* node) const;\n\n  /**\n   * Get the cost to traverse the specified directed edge. Cost includes\n   * the time (seconds) to traverse the edge.\n   * @param   edge  Pointer to a directed edge.\n   * @return  Returns the cost and time (seconds)\n   */\n  virtual Cost EdgeCost(const baldr::DirectedEdge* edge) const;\n\n  /**\n   * Returns the cost to make the transition from the predecessor edge.\n   * Defaults to 0. Costing models that wish to include edge transition\n   * costs (i.e., intersection/turn costs) must override this method.\n   * @param  edge  Directed edge (the to edge)\n   * @param  node  Node (intersection) where transition occurs.\n   * @param  pred  Predecessor edge information.\n   * @return  Returns the cost and time (seconds)\n   */\n  virtual Cost TransitionCost(const baldr::DirectedEdge* edge,\n                              const baldr::NodeInfo* node,\n                              const EdgeLabel& pred) const;\n\n  /**\n   * Returns the cost to make the transition from the predecessor edge\n   * when using a reverse search (from destination towards the origin).\n   * Defaults to 0. Costing models that wish to include edge transition\n   * costs (i.e., intersection/turn costs) must override this method.\n   * @param  idx   Directed edge local index\n   * @param  node  Node (intersection) where transition occurs.\n   * @param  pred  the opposing current edge in the reverse tree.\n   * @param  edge  the opposing predecessor in the reverse tree\n   * @return  Returns the cost and time (seconds)\n   */\n  virtual Cost TransitionCostReverse(const uint32_t idx,\n                                     const baldr::NodeInfo* node,\n                                     const baldr::DirectedEdge* pred,\n                                     const baldr::DirectedEdge* edge) const;\n\n  /**\n   * Get the cost factor for A* heuristics. This factor is multiplied\n   * with the distance to the destination to produce an estimate of the\n   * minimum cost to the destination. The A* heuristic must underestimate the\n   * cost to the destination. So a time based estimate based on speed should\n   * assume the maximum speed is used to the destination such that the time\n   * estimate is less than the least possible time along roads.\n   */\n  virtual float AStarCostFactor() const;\n\n  /**\n   * Get the current travel type.\n   * @return  Returns the current travel type.\n   */\n  virtual uint8_t travel_type() const;\n\n  /**\n   * Returns a function/functor to be used in location searching which will\n   * exclude and allow ranking results from the search by looking at each\n   * edges attribution and suitability for use as a location by the travel\n   * mode used by the costing method. Function/functor is also used to filter\n   * edges not usable / inaccessible by pedestrians.\n   */\n   virtual const EdgeFilter GetEdgeFilter() const {\n     // Throw back a lambda that checks the access for this type of costing\n     auto access_mask = access_mask_;\n     return [access_mask](const baldr::DirectedEdge* edge) {\n       return !(edge->IsTransition() || edge->is_shortcut() ||\n           edge->use() >= Use::kRail ||\n          !(edge->forwardaccess() & access_mask));\n     };\n   }\n\n   virtual const NodeFilter GetNodeFilter() const {\n     //throw back a lambda that checks the access for this type of costing\n     auto access_mask = access_mask_;\n     return [access_mask](const baldr::NodeInfo* node){\n       return !(node->access() & access_mask);\n     };\n   }\n\n  /**\n   * Returns a function/functor to be used in location searching which will\n   * exclude results from the search by looking at each node's attribution\n   * @return Function/functor to be used in filtering out nodes\n   */\n\n public:\n  // Type: foot (default), wheelchair, etc.\n  PedestrianType type_;\n\n  uint32_t access_mask_;\n\n  // Maximum pedestrian distance.\n  uint32_t max_distance_;\n\n  // This is the factor for this mode.  The higher the value the more the\n  // mode is favored.\n  float mode_factor_;\n\n  // Maximum pedestrian distance in meters for multimodal routes.\n  // Maximum distance at the beginning or end of a multimodal route\n  // that you are willing to travel for this mode.  In this case,\n  // it is the max walking distance.\n  uint32_t transit_start_end_max_distance_;\n\n  // Maximum transfer, distance in meters for multimodal routes.\n  // Maximum transfer distance between stops that you are willing\n  // to travel for this mode.  In this case, it is the max distance\n  // you are willing to walk between transfers.\n  uint32_t transit_transfer_max_distance_;\n\n  // Minimal surface type usable by the pedestrian type\n  Surface minimal_allowed_surface_;\n\n  uint32_t max_grade_;    // Maximum grade (percent).\n  float speed_;           // Pedestrian speed.\n  float speedfactor_;     // Speed factor for costing. Based on speed.\n  float walkway_factor_;  // Factor for favoring walkways and paths.\n  float sidewalk_factor_; // Factor for favoring sidewalks.\n  float alley_factor_;    // Avoid alleys factor.\n  float driveway_factor_; // Avoid driveways factor.\n  float step_penalty_;    // Penalty applied to steps/stairs (seconds).\n  float gate_penalty_;    // Penalty (seconds) to go through gate\n  float maneuver_penalty_;          // Penalty (seconds) when inconsistent names\n  float country_crossing_cost_;     // Cost (seconds) to go through toll booth\n  float country_crossing_penalty_;  // Penalty (seconds) to go across a country border\n  float ferry_cost_;                // Cost (seconds) to exit a ferry\n  float ferry_penalty_;             // Penalty (seconds) to enter a ferry\n  float ferry_factor_;              // Weighting to apply to ferry edges\n  float use_ferry_;\n};\n\n// Constructor. Parse pedestrian options from property tree. If option is\n// not present, set the default.\n//Armin H.\nPedestrianCost::PedestrianCost(const boost::property_tree::ptree& pt, baldr::GraphReader& graphreader)\n    : DynamicCost(pt, graphreader, TravelMode::kPedestrian) {\n  // Set hierarchy to allow unlimited transitions\n  for (auto& h : hierarchy_limits_) {\n    h.max_up_transitions = kUnlimitedTransitions;\n  }\n\n  allow_transit_connections_ = false;\n\n  // Get the pedestrian type - enter as string and convert to enum\n  std::string type = pt.get<std::string>(\"type\", \"foot\");\n  if (type == \"wheelchair\") {\n    type_ = PedestrianType::kWheelchair;\n  } else if (type == \"segway\") {\n    type_ = PedestrianType::kSegway;\n  } else {\n    type_ = PedestrianType::kFoot;\n  }\n\n  // Set type specific defaults, override with URL inputs\n  if (type == \"wheelchair\") {\n    access_mask_ = kWheelchairAccess;\n    max_distance_ = kMaxDistanceWheelchairRange(\n      pt.get<uint32_t>(\"max_distance\", kMaxDistanceWheelchair)\n    );\n    speed_ = kSpeedWheelchairRange(\n      pt.get<float>(\"walking_speed\", kDefaultSpeedWheelchair)\n    );\n    step_penalty_ = kStepPenaltyWheelchairRange(\n      pt.get<float>(\"step_penalty\", kDefaultStepPenaltyWheelchair)\n    );\n    max_grade_ = kMaxGradeWheelchairRange(\n      pt.get<uint32_t>(\"max_grade\", kDefaultMaxGradeWheelchair)\n    );\n    minimal_allowed_surface_ = Surface::kCompacted;\n  } else {\n    // Assume type = foot\n    access_mask_ = kPedestrianAccess;\n    max_distance_ = kMaxDistanceFootRange(\n      pt.get<uint32_t>(\"max_distance\", kMaxDistanceFoot)\n    );\n    speed_ = kSpeedFootRange(\n      pt.get<float>(\"walking_speed\", kDefaultSpeedFoot)\n    );\n    step_penalty_ = kStepPenaltyFootRange(\n      pt.get<float>(\"step_penalty\", kDefaultStepPenaltyFoot)\n    );\n    max_grade_ = kMaxGradeFootRange(\n      pt.get<uint32_t>(\"max_grade\", kDefaultMaxGradeFoot)\n    );\n    minimal_allowed_surface_ = Surface::kPath;\n  }\n\n\n  mode_factor_ = kModeFactorRange(\n    pt.get<float>(\"mode_factor\", kModeFactor)\n  );\n  maneuver_penalty_ = kManeuverPenaltyRange(\n    pt.get<float>(\"maneuver_penalty\", kDefaultManeuverPenalty)\n  );\n  gate_penalty_ = kGatePenaltyRange(\n    pt.get<float>(\"gate_penalty\", kDefaultGatePenalty)\n  );\n  walkway_factor_ = kWalkwayFactorRange(\n    pt.get<float>(\"walkway_factor\", kDefaultWalkwayFactor)\n  );\n  sidewalk_factor_ = kSideWalkFactorRange(\n    pt.get<float>(\"sidewalk_factor\", kDefaultSideWalkFactor)\n  );\n  alley_factor_ = kAlleyFactorRange(\n    pt.get<float>(\"alley_factor\", kDefaultAlleyFactor)\n  );\n  driveway_factor_ = kDrivewayFactorRange(\n    pt.get<float>(\"driveway_factor\", kDefaultDrivewayFactor)\n  );\n  ferry_cost_ = kFerryCostRange(\n    pt.get<float>(\"ferry_cost\", kDefaultFerryCost)\n  );\n  country_crossing_cost_ = kCountryCrossingCostRange(\n    pt.get<float>(\"country_crossing_cost\", kDefaultCountryCrossingCost)\n  );\n  country_crossing_penalty_ = kCountryCrossingPenaltyRange(\n    pt.get<float>(\"country_crossing_penalty\", kDefaultCountryCrossingPenalty)\n  );\n  transit_start_end_max_distance_ = kTransitStartEndMaxDistanceRange(\n    pt.get<uint32_t>(\"transit_start_end_max_distance\", kTransitStartEndMaxDistance)\n  );\n  transit_transfer_max_distance_  = kTransitTransferMaxDistanceRange(\n    pt.get<uint32_t>(\"transit_transfer_max_distance\", kTransitTransferMaxDistance)\n  );\n\n  // Modify ferry penalty and edge weighting based on use_ferry_ factor\n  use_ferry_ = kUseFerryRange(\n    pt.get<float>(\"use_ferry\", kDefaultUseFerry)\n  );\n  if (use_ferry_ < 0.5f) {\n    // Penalty goes from max at use_ferry_ = 0 to 0 at use_ferry_ = 0.5\n    ferry_penalty_ = static_cast<uint32_t>(kMaxFerryPenalty * (1.0f - use_ferry_ * 2.0f));\n\n    // Cost X10 at use_ferry_ == 0, slopes downwards towards 1.0 at use_ferry_ = 0.5\n    ferry_factor_ = 10.0f - use_ferry_ * 18.0f;\n  } else {\n    // Add a ferry weighting factor to influence cost along ferries to make\n    // them more favorable if desired rather than driving. No ferry penalty.\n    // Half the cost at use_ferry_ == 1, progress to 1.0 at use_ferry_ = 0.5\n    ferry_penalty_ = 0.0f;\n    ferry_factor_  = 1.5f - use_ferry_;\n  }\n\n  // Set the speed factor (to avoid division in costing)\n  speedfactor_ = (kSecPerHour * 0.001f) / speed_;\n}\n\n// Destructor\nPedestrianCost::~PedestrianCost() {\n}\n\n// Allow multiple passes when ferries are on initial path.\nbool PedestrianCost::AllowMultiPass() const {\n  return true;\n}\n\n// This method overrides the max_distance with the max_distance_mm per segment\n// distance. An example is a pure walking route may have a max distance of\n// 10000 meters (10km) but for a multi-modal route a lower limit of 5000\n// meters per segment (e.g. from origin to a transit stop or from the last\n// transit stop to the destination).\nvoid PedestrianCost::UseMaxMultiModalDistance() {\n  max_distance_ = transit_start_end_max_distance_;\n}\n\n// Returns the maximum transfer distance between stops that you are willing\n// to travel for this mode.  In this case, it is the max walking\n// distance you are willing to walk between transfers.\nuint32_t PedestrianCost::GetMaxTransferDistanceMM() {\n  return transit_transfer_max_distance_;\n}\n\n// This method overrides the factor for this mode.  The lower the value\n// the more the mode is favored.\nfloat PedestrianCost::GetModeFactor() {\n  return mode_factor_;\n}\n\n// Get the access mode used by this costing method.\nuint32_t PedestrianCost::access_mode() const {\n  return access_mask_;\n}\n\n// Check if access is allowed on the specified edge. Disallow if no\n// access for this pedestrian type, if surface type exceeds (worse than)\n// the minimum allowed surface type, or if max grade is exceeded.\n// Disallow edges where max. distance will be exceeded.\nbool PedestrianCost::Allowed(const baldr::DirectedEdge* edge,\n                             const EdgeLabel& pred,\n                             const baldr::GraphTile*& tile,\n                             const baldr::GraphId& edgeid) const {\n  // TODO - obtain and check the access restrictions.\n\n  if (!(edge->forwardaccess() & access_mask_) ||\n       (edge->surface() > minimal_allowed_surface_) ||\n        edge->is_shortcut() || IsUserAvoidEdge(edgeid) ||\n //      (edge->max_up_slope() > max_grade_ || edge->max_down_slope() > max_grade_) ||\n      ((pred.path_distance() + edge->length()) > max_distance_)) {\n    return false;\n  }\n\n  // Disallow transit connections (except when set for multi-modal routes)\n  if (!allow_transit_connections_ && (edge->use() == Use::kPlatformConnection ||\n      edge->use() == Use::kEgressConnection ||\n      edge->use() == Use::kTransitConnection)) {\n    return false;\n  }\n  return true;\n}\n\n// Checks if access is allowed for an edge on the reverse path (from\n// destination towards origin). Both opposing edges are provided.\nbool PedestrianCost::AllowedReverse(const baldr::DirectedEdge* edge,\n               const EdgeLabel& pred,\n               const baldr::DirectedEdge* opp_edge,\n               const baldr::GraphTile*& tile,\n               const baldr::GraphId& opp_edgeid) const {\n  // TODO - obtain and check the access restrictions.\n\n  // Do not check max walking distance and assume we are not allowing\n  // transit connections. Assume this method is never used in\n  // multimodal routes).\n  if (!(opp_edge->forwardaccess() & access_mask_) ||\n       (opp_edge->surface() > minimal_allowed_surface_) ||\n        opp_edge->is_shortcut() || IsUserAvoidEdge(opp_edgeid) ||\n //      (opp_edge->max_up_slope() > max_grade_ || opp_edge->max_down_slope() > max_grade_) ||\n        opp_edge->use() == Use::kTransitConnection || opp_edge->use() == Use::kEgressConnection ||\n        opp_edge->use() == Use::kPlatformConnection) {\n    return false;\n  }\n  return true;\n}\n\n// Check if access is allowed at the specified node.\nbool PedestrianCost::Allowed(const baldr::NodeInfo* node) const {\n  return (node->access() & access_mask_);\n}\n\n// Returns the cost to traverse the edge and an estimate of the actual time\n// (in seconds) to traverse the edge.\nCost PedestrianCost::EdgeCost(const baldr::DirectedEdge* edge) const {\n\n  // Ferries are a special case - they use the ferry speed (stored on the edge)\n  if (edge->use() == Use::kFerry) {\n    float sec = edge->length() * (kSecPerHour * 0.001f) /\n            static_cast<float>(edge->speed());\n    return { sec * ferry_factor_, sec };\n  }\n\n  // Slightly favor walkways/paths and penalize alleys and driveways.\n  float sec = edge->length() * speedfactor_;\n  if (edge->use() == Use::kFootway) {\n    return { sec * walkway_factor_, sec };\n  } else if (edge->use() == Use::kAlley) {\n    return { sec * alley_factor_, sec };\n  } else if (edge->use() == Use::kDriveway) {\n    return { sec * driveway_factor_, sec };\n  } else if (edge->use() == Use::kSidewalk) {\n    return { sec * sidewalk_factor_, sec };\n  } else if (edge->roundabout()) {\n    return { sec * kRoundaboutFactor, sec };\n  } else {\n    return { sec, sec };\n  }\n}\n\n// Returns the time (in seconds) to make the transition from the predecessor\nCost PedestrianCost::TransitionCost(const baldr::DirectedEdge* edge,\n                                    const baldr::NodeInfo* node,\n                                    const EdgeLabel& pred) const {\n  // Special cases: fixed penalty for steps/stairs\n  if (edge->use() == Use::kSteps) {\n    return { step_penalty_, 0.0f };\n  }\n\n  // Penalty through gates and border control.\n  float seconds = 0.0f;\n  float penalty = 0.0f;\n  if (node->type() == NodeType::kBorderControl) {\n    seconds += country_crossing_cost_;\n    penalty += country_crossing_penalty_;\n  } else if (node->type() == NodeType::kGate) {\n    penalty += gate_penalty_;\n  }\n\n  if ((pred.use() != Use::kFerry && edge->use() == Use::kFerry)) {\n    seconds += ferry_cost_;\n    penalty += ferry_penalty_;\n  }\n\n  uint32_t idx = pred.opp_local_idx();\n  // Ignore name inconsistency when entering a link to avoid double penalizing.\n  if (!edge->link() && edge->use() != Use::kEgressConnection &&\n      edge->use() != Use::kPlatformConnection &&\n      !node->name_consistency(idx, edge->localedgeidx())) {\n    // Slight maneuver penalty\n      penalty += maneuver_penalty_;\n  }\n\n  // Costs for crossing an intersection.\n  if (edge->edge_to_right(idx) && edge->edge_to_left(idx)) {\n    seconds += kCrossingCosts[edge->stopimpact(idx)];\n  }\n  return { seconds + penalty, seconds };\n}\n\n// Returns the cost to make the transition from the predecessor edge\n// when using a reverse search (from destination towards the origin).\n// Defaults to 0. Costing models that wish to include edge transition\n// costs (i.e., intersection/turn costs) must override this method.\nCost PedestrianCost::TransitionCostReverse(\n    const uint32_t idx, const baldr::NodeInfo* node,\n    const baldr::DirectedEdge* pred, const baldr::DirectedEdge* edge) const {\n  // Special cases: fixed penalty for steps/stairs\n  if (edge->use() == Use::kSteps) {\n    return { step_penalty_, 0.0f };\n  }\n\n  // Penalty through gates and border control.\n  float seconds = 0.0f;\n  float penalty = 0.0f;\n  if (node->type() == NodeType::kBorderControl) {\n    seconds += country_crossing_cost_;\n    penalty += country_crossing_penalty_;\n  } else if (node->type() == NodeType::kGate) {\n    penalty += gate_penalty_;\n  }\n\n  if (pred->use() != Use::kFerry && edge->use() == Use::kFerry) {\n    seconds += ferry_cost_;\n    penalty += ferry_penalty_;\n  }\n\n  // Ignore name inconsistency when entering a link to avoid double penalizing.\n  if (!edge->link() && edge->use() != Use::kEgressConnection &&\n      edge->use() != Use::kPlatformConnection &&\n      !node->name_consistency(idx, edge->localedgeidx())) {\n    // Slight maneuver penalty\n    penalty += maneuver_penalty_;\n  }\n\n  // Costs for crossing an intersection.\n  if (edge->edge_to_right(idx) && edge->edge_to_left(idx)) {\n    seconds += kCrossingCosts[edge->stopimpact(idx)];\n  }\n  return { seconds + penalty, seconds };\n}\n\n// Get the cost factor for A* heuristics. This factor is multiplied\n// with the distance to the destination to produce an estimate of the\n// minimum cost to the destination. The A* heuristic must underestimate the\n// cost to the destination. So a time based estimate based on speed should\n// assume the maximum speed is used to the destination such that the time\n// estimate is less than the least possible time along roads.\nfloat PedestrianCost::AStarCostFactor() const {\n  // On first pass use the walking speed plus a small factor to account for\n  // favoring walkways, on the second pass use the the maximum ferry speed.\n  if (pass_ == 0) {\n    float speed = kDefaultSpeedFoot * std::min(walkway_factor_, sidewalk_factor_);\n    return (kSecPerHour * 0.001f) / static_cast<float>(speed);\n  } else {\n    return (kSecPerHour * 0.001f) / static_cast<float>(kMaxFerrySpeedKph);\n  }\n}\n\n// Returns the current travel type.\nuint8_t PedestrianCost::travel_type() const {\n  return static_cast<uint8_t>(type_);\n}\n\n//Armin H.\ncost_ptr_t CreatePedestrianCost(const boost::property_tree::ptree& config, baldr::GraphReader& graphreader) {\n  return std::make_shared<PedestrianCost>(config, graphreader);\n}\n\n}\n}\n\n/**********************************************************************************************/\n\n#ifdef INLINE_TEST\n\nusing namespace valhalla;\nusing namespace sif;\n\nnamespace {\n\nPedestrianCost* make_pedestriancost_from_json(const std::string& property, float testVal, const std::string& type) {\n  std::stringstream ss;\n  ss << R\"({\")\" << property << R\"(\":)\" << testVal << R\"(,\"type\":\")\" << type << R\"(\")\" << \"}\";\n  boost::property_tree::ptree costing_ptree;\n  boost::property_tree::read_json(ss, costing_ptree);\n  //Armin H.\n  boost::property_tree::ptree pt;\n  pt.put(\"tile_dir\", \"test/gphrdr_test\");\n  GraphReader reader(pt);\n  return new PedestrianCost(costing_ptree, reader);\n}\n\nstd::uniform_real_distribution<float>* make_distributor_from_range (const ranged_default_t<float>& range) {\n  float rangeLength = range.max - range.min;\n  return new std::uniform_real_distribution<float>(range.min - rangeLength, range.max + rangeLength);\n}\n\nstd::uniform_int_distribution<uint32_t>* make_distributor_from_range (const ranged_default_t<uint32_t>& range) {\n  uint32_t rangeLength = range.max - range.min;\n  return new std::uniform_int_distribution<uint32_t>(range.min - rangeLength, range.max + rangeLength);\n}\n\nvoid testPedestrianCostParams() {\n  constexpr unsigned testIterations = 250;\n  constexpr unsigned seed = 0;\n  std::default_random_engine generator(seed);\n  std::shared_ptr<std::uniform_real_distribution<float>> real_distributor;\n  std::shared_ptr<std::uniform_int_distribution<uint32_t>> int_distributor;\n  std::shared_ptr<PedestrianCost> ctorTester;\n\n  // Wheelchair tests\n  // max_distance_\n  int_distributor.reset(make_distributor_from_range(kMaxDistanceWheelchairRange));\n  for (unsigned i = 0; i < 100; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"max_distance\", (*int_distributor)(generator), \"wheelchair\"));\n    if (ctorTester->max_distance_ < kMaxDistanceWheelchairRange.min ||\n        ctorTester->max_distance_ > kMaxDistanceWheelchairRange.max) {\n      throw std::runtime_error (\"max_distance_ with type wheelchair is not within it's range\");\n    }\n  }\n\n  // speed_\n  real_distributor.reset(make_distributor_from_range(kSpeedWheelchairRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"walking_speed\", (*real_distributor)(generator), \"wheelchair\"));\n    if (ctorTester->speed_ < kSpeedWheelchairRange.min ||\n        ctorTester->speed_ > kSpeedWheelchairRange.max) {\n      throw std::runtime_error (\"speed_ with type wheelchair is not within it's range\");\n    }\n  }\n\n  // step_penalty_\n  real_distributor.reset(make_distributor_from_range(kStepPenaltyWheelchairRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"step_penalty\", (*real_distributor)(generator), \"wheelchair\"));\n    if (ctorTester->step_penalty_ < kStepPenaltyWheelchairRange.min ||\n        ctorTester->step_penalty_ > kStepPenaltyWheelchairRange.max) {\n      throw std::runtime_error (\"step_penalty_ with type wheelchair is not within it's range\");\n    }\n  }\n\n  // max_grade_\n  int_distributor.reset(make_distributor_from_range(kMaxGradeWheelchairRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"max_grade\", (*int_distributor)(generator), \"wheelchair\"));\n    if (ctorTester->max_grade_ < kMaxGradeWheelchairRange.min ||\n        ctorTester->max_grade_ > kMaxGradeWheelchairRange.max) {\n      throw std::runtime_error (\"max_grade_ with type wheelchair is not within it's range\");\n    }\n  }\n\n\n  // Foot tests\n  // max_distance_\n  int_distributor.reset(make_distributor_from_range(kMaxDistanceFootRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"max_distance\", (*int_distributor)(generator), \"foot\"));\n    if (ctorTester->max_distance_ < kMaxDistanceFootRange.min ||\n        ctorTester->max_distance_ > kMaxDistanceFootRange.max) {\n      throw std::runtime_error (\"max_distance_ with type foot is not within it's range\");\n    }\n  }\n\n  // speed_\n  real_distributor.reset(make_distributor_from_range(kSpeedFootRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"walking_speed\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->speed_ < kSpeedFootRange.min ||\n        ctorTester->speed_ > kSpeedFootRange.max) {\n      throw std::runtime_error (\"speed_ with type foot is not within it's range\");\n    }\n  }\n\n  // step_penalty_\n  real_distributor.reset(make_distributor_from_range(kStepPenaltyFootRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"step_penalty\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->step_penalty_ < kStepPenaltyFootRange.min ||\n        ctorTester->step_penalty_ > kStepPenaltyFootRange.max) {\n      throw std::runtime_error (\"step_penalty_ with type foot is not within it's range\");\n    }\n  }\n\n  // max_grade_\n  int_distributor.reset(make_distributor_from_range(kMaxGradeFootRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"max_grade\", (*int_distributor)(generator), \"foot\"));\n    if (ctorTester->max_grade_ < kMaxGradeFootRange.min ||\n        ctorTester->max_grade_ > kMaxGradeFootRange.max) {\n      throw std::runtime_error (\"max_grade_ with type foot is not within it's range\");\n    }\n  }\n\n\n  // Non type dependent tests\n  // mode_factor_\n    real_distributor.reset(make_distributor_from_range(kModeFactorRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"mode_factor\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->mode_factor_ < kModeFactorRange.min ||\n        ctorTester->mode_factor_ > kModeFactorRange.max) {\n      throw std::runtime_error (\"mode_factor_ is not within it's range\");\n    }\n  }\n\n  // maneuver_penalty_\n  real_distributor.reset(make_distributor_from_range(kManeuverPenaltyRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"maneuver_penalty\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->maneuver_penalty_ < kManeuverPenaltyRange.min ||\n        ctorTester->maneuver_penalty_ > kManeuverPenaltyRange.max) {\n      throw std::runtime_error (\"maneuver_penalty_ is not within it's range\");\n    }\n  }\n\n  // gate_penalty_\n  real_distributor.reset(make_distributor_from_range(kGatePenaltyRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"gate_penalty\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->gate_penalty_ < kGatePenaltyRange.min ||\n        ctorTester->gate_penalty_ > kGatePenaltyRange.max) {\n      throw std::runtime_error (\"gate_penalty_ is not within it's range\");\n    }\n  }\n\n  // walkway_factor_\n  real_distributor.reset(make_distributor_from_range(kWalkwayFactorRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"walkway_factor\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->walkway_factor_ < kWalkwayFactorRange.min ||\n        ctorTester->walkway_factor_ > kWalkwayFactorRange.max) {\n      throw std::runtime_error (\"walkway_factor_ is not within it's range\");\n    }\n  }\n\n  // sidewalk_factor_\n  real_distributor.reset(make_distributor_from_range(kSideWalkFactorRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"sidewalk_factor\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->sidewalk_factor_ < kSideWalkFactorRange.min ||\n        ctorTester->sidewalk_factor_ > kSideWalkFactorRange.max) {\n      throw std::runtime_error (\"sidewalk_factor_ is not within it's range\");\n    }\n  }\n\n  // alley_factor_\n  real_distributor.reset(make_distributor_from_range(kAlleyFactorRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"alley_factor\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->alley_factor_ < kAlleyFactorRange.min ||\n        ctorTester->alley_factor_ > kAlleyFactorRange.max) {\n      throw std::runtime_error (\"alley_factor_ is not within it's range\");\n    }\n  }\n\n  // driveway_factor_\n  real_distributor.reset(make_distributor_from_range(kDrivewayFactorRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"driveway_factor\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->driveway_factor_ < kDrivewayFactorRange.min ||\n        ctorTester->driveway_factor_ > kDrivewayFactorRange.max) {\n      throw std::runtime_error (\"driveway_factor_ is not within it's range\");\n    }\n  }\n\n  // ferry_cost_\n  real_distributor.reset(make_distributor_from_range(kFerryCostRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"ferry_cost\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->ferry_cost_ < kFerryCostRange.min ||\n        ctorTester->ferry_cost_ > kFerryCostRange.max) {\n      throw std::runtime_error (\"ferry_cost_ is not within it's range\");\n    }\n  }\n\n  // country_crossing_cost_\n  real_distributor.reset(make_distributor_from_range(kCountryCrossingCostRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"country_crossing_cost\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->country_crossing_cost_ < kCountryCrossingCostRange.min ||\n        ctorTester->country_crossing_cost_ > kCountryCrossingCostRange.max) {\n      throw std::runtime_error (\"country_crossing_cost_ is not within it's range\");\n    }\n  }\n\n  // country_crossing_penalty_\n  real_distributor.reset(make_distributor_from_range(kCountryCrossingPenaltyRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"country_crossing_penalty\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->country_crossing_penalty_ < kCountryCrossingPenaltyRange.min ||\n        ctorTester->country_crossing_penalty_ > kCountryCrossingPenaltyRange.max) {\n      throw std::runtime_error (\"country_crossing_penalty_ is not within it's range\");\n    }\n  }\n\n  // transit_start_end_max_distance_\n  int_distributor.reset(make_distributor_from_range(kTransitStartEndMaxDistanceRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"transit_start_end_max_distance\",\n                                                  (*int_distributor)(generator), \"foot\"));\n    if (ctorTester->transit_start_end_max_distance_ < kTransitStartEndMaxDistanceRange.min ||\n        ctorTester->transit_start_end_max_distance_ > kTransitStartEndMaxDistanceRange.max) {\n      throw std::runtime_error (\"transit_start_end_max_distance_ is not within it's range\");\n    }\n  }\n\n  // transit_transfer_max_distance_\n  int_distributor.reset(make_distributor_from_range(kTransitTransferMaxDistanceRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"transit_transfer_max_distance\",\n                                                  (*int_distributor)(generator), \"foot\"));\n    if (ctorTester->transit_transfer_max_distance_ < kTransitTransferMaxDistanceRange.min ||\n        ctorTester->transit_transfer_max_distance_ > kTransitTransferMaxDistanceRange.max) {\n      throw std::runtime_error (\"transit_transfer_max_distance_ is not within it's range\");\n    }\n  }\n\n  // use_ferry_\n  real_distributor.reset(make_distributor_from_range(kUseFerryRange));\n  for (unsigned i = 0; i < testIterations; ++i) {\n    ctorTester.reset(make_pedestriancost_from_json(\"use_ferry\", (*real_distributor)(generator), \"foot\"));\n    if (ctorTester->use_ferry_ < kUseFerryRange.min ||\n        ctorTester->use_ferry_ > kUseFerryRange.max) {\n      throw std::runtime_error (\"use_ferry_ is not within it's range\");\n    }\n  }\n}\n}\n\nint main() {\n  test::suite suite(\"costing\");\n\n  suite.test(TEST_CASE(testPedestrianCostParams));\n\n  return suite.tear_down();\n}\n\n#endif\n", "meta": {"hexsha": "c96f1b25b6db6ea29a30060c23e9eec36619d1c5", "size": 40018, "ext": "cc", "lang": "C++", "max_stars_repo_path": "valhalla/src/sif/pedestriancost.cc", "max_stars_repo_name": "arminHadzic/Panorama_Valhalla", "max_stars_repo_head_hexsha": "e20e73b7b8256901d9e5065b7b9aa2c0988fea68", "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": "valhalla/src/sif/pedestriancost.cc", "max_issues_repo_name": "arminHadzic/Panorama_Valhalla", "max_issues_repo_head_hexsha": "e20e73b7b8256901d9e5065b7b9aa2c0988fea68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "valhalla/src/sif/pedestriancost.cc", "max_forks_repo_name": "arminHadzic/Panorama_Valhalla", "max_forks_repo_head_hexsha": "e20e73b7b8256901d9e5065b7b9aa2c0988fea68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-03T00:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-03T00:58:58.000Z", "avg_line_length": 42.079915878, "max_line_length": 123, "alphanum_fraction": 0.7136538558, "num_tokens": 10092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.15170309915112964}}
{"text": "#include <data/Geometry.hpp>\n#include <engine/Neighbours.hpp>\n#include <engine/Vectormath.hpp>\n#include <utility/Exception.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"Qhull.h\"\n#include \"QhullFacetList.h\"\n#include \"QhullVertexSet.h\"\n\n#include <fmt/ostream.h>\n\n#include <random>\n#include <array>\n\nnamespace Data\n{\n    Geometry::Geometry(std::vector<Vector3> bravais_vectors, intfield n_cells,\n                        std::vector<Vector3> cell_atoms,  Basis_Cell_Composition cell_composition,\n                        scalar lattice_constant, Pinning pinning, Defects defects) :\n        bravais_vectors(bravais_vectors), n_cells(n_cells), n_cell_atoms(cell_atoms.size()),\n        cell_atoms(cell_atoms), cell_composition(cell_composition), lattice_constant(lattice_constant),\n        nos(cell_atoms.size() * n_cells[0] * n_cells[1] * n_cells[2]),\n        nos_nonvacant(cell_atoms.size() * n_cells[0] * n_cells[1] * n_cells[2]),\n        n_cells_total(n_cells[0] * n_cells[1] * n_cells[2]),\n        pinning(pinning), defects(defects)\n    {\n        // Generate positions and atom types\n        this->positions = vectorfield(this->nos);\n        this->generatePositions();\n\n        // Calculate some useful info\n        this->calculateBounds();\n        this->calculateUnitCellBounds();\n        this->calculateDimensionality();\n\n        // Calculate center of the System\n        this->center = 0.5 * (this->bounds_min + this->bounds_max);\n\n        // Generate default atom_types, mu_s and pinning masks\n        this->atom_types        = intfield(this->nos, 0);\n        this->mu_s              = scalarfield(this->nos, 1);\n        this->mask_unpinned     = intfield(this->nos, 1);\n        this->mask_pinned_cells = vectorfield(this->nos, { 0,0,0 });\n\n        // Set atom types, mu_s\n        this->applyCellComposition();\n\n        // Apply additional pinned sites\n        for( int isite=0; isite < pinning.sites.size(); ++isite )\n        {\n            auto& site = pinning.sites[isite];\n            int ispin = site.i + Engine::Vectormath::idx_from_translations(\n                        this->n_cells, this->n_cell_atoms,\n                        {site.translations[0], site.translations[1], site.translations[2]} );\n            this->mask_unpinned[ispin] = 0;\n            this->mask_pinned_cells[ispin] = pinning.spins[isite];\n        }\n\n        // Apply additional defect sites\n        for (int i = 0; i < defects.sites.size(); ++i)\n        {\n            auto& defect = defects.sites[i];\n            int ispin = defects.sites[i].i + Engine::Vectormath::idx_from_translations(\n                        this->n_cells, this->n_cell_atoms,\n                        {defect.translations[0], defect.translations[1], defect.translations[2]} );\n            this->atom_types[ispin] = defects.types[i];\n            this->mu_s[ispin] = 0.0;\n        }\n\n        // Calculate the type of geometry\n        this->calculateGeometryType();\n\n        // For updates of triangulation and tetrahedra\n        this->last_update_n_cell_step = -1;\n        this->last_update_n_cells = intfield(3, -1);\n    }\n\n    void Geometry::generatePositions()\n    {\n        const scalar epsilon = 1e-6;\n\n        // Check for erronous input placing two spins on the same location\n        int max_a = std::min(10, n_cells[0]);\n        int max_b = std::min(10, n_cells[1]);\n        int max_c = std::min(10, n_cells[2]);\n        Vector3 diff;\n        for (int i = 0; i < n_cell_atoms; ++i)\n        {\n            for (int j = 0; j < n_cell_atoms; ++j)\n            {\n                for (int da = -max_a; da <= max_a; ++da)\n                {\n                    for (int db = -max_b; db <= max_b; ++db)\n                    {\n                        for (int dc = -max_c; dc <= max_c; ++dc)\n                        {\n                            // Norm is zero if translated basis atom is at position of another basis atom\n                            diff = cell_atoms[i] - ( cell_atoms[j] + Vector3{scalar(da), scalar(db), scalar(dc)} );\n\n                            if( (i != j || da != 0 || db != 0 || dc != 0) &&\n                                std::abs(diff[0]) < epsilon &&\n                                std::abs(diff[1]) < epsilon &&\n                                std::abs(diff[2]) < epsilon )\n                            {\n                                Vector3 position = lattice_constant * (\n                                      (da + cell_atoms[i][0]) * bravais_vectors[0]\n                                    + (db + cell_atoms[i][1]) * bravais_vectors[1]\n                                    + (dc + cell_atoms[i][2]) * bravais_vectors[2] );\n                                std::string message = fmt::format(\n                                    \"Unable to initialize Spin-System, since 2 spins occupy the same space\"\n                                    \"within a margin of {} at absolute position ({}).\\n\"\n                                    \"Index combination: i={} j={}, translations=({}, {}, {}).\\n\"\n                                    \"Please check the config file!\", epsilon, position.transpose(), i, j, da, db, dc);\n                                spirit_throw(Utility::Exception_Classifier::System_not_Initialized, Utility::Log_Level::Severe, message);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // Generate positions\n        for (int dc = 0; dc < n_cells[2]; ++dc)\n        {\n            for (int db = 0; db < n_cells[1]; ++db)\n            {\n                for (int da = 0; da < n_cells[0]; ++da)\n                {\n                    for (int iatom = 0; iatom < n_cell_atoms; ++iatom)\n                    {\n                        int ispin = iatom\n                            + dc * n_cell_atoms * n_cells[1] * n_cells[0]\n                            + db * n_cell_atoms * n_cells[0]\n                            + da * n_cell_atoms;\n\n                        positions[ispin] = lattice_constant * (\n                                  (da + cell_atoms[iatom][0]) * bravais_vectors[0]\n                                + (db + cell_atoms[iatom][1]) * bravais_vectors[1]\n                                + (dc + cell_atoms[iatom][2]) * bravais_vectors[2] );\n                    }\n                }\n            }\n        }\n    }\n\n\n\n    std::vector<tetrahedron_t> compute_delaunay_triangulation_3D(const std::vector<vector3_t> & points)\n    try\n    {\n        const int ndim = 3;\n        std::vector<tetrahedron_t> tetrahedra;\n        tetrahedron_t tmp_tetrahedron;\n        int *current_index;\n\n        orgQhull::Qhull qhull;\n        qhull.runQhull(\"\", ndim, points.size(), (coordT *) points.data(),  \"d Qt Qbb Qz\");\n        orgQhull::QhullFacetList facet_list = qhull.facetList();\n        for(const auto & facet : facet_list)\n        {\n            if(!facet.isUpperDelaunay())\n            {\n                current_index = &tmp_tetrahedron[0];\n                for(const auto & vertex : facet.vertices())\n                {\n                    *current_index++ = vertex.point().id();\n                }\n                tetrahedra.push_back(tmp_tetrahedron);\n            }\n        }\n        return tetrahedra;\n    }\n    catch( ... )\n    {\n        spirit_handle_exception_core( \"Could not compute 3D Delaunay triangulation of the Geometry. Probably Qhull threw an exception.\" );\n        return std::vector<tetrahedron_t>(0);\n    }\n\n    std::vector<triangle_t> compute_delaunay_triangulation_2D(const std::vector<vector2_t> & points)\n    try\n    {\n        const int ndim = 2;\n        std::vector<triangle_t> triangles;\n        triangle_t tmp_triangle;\n        int *current_index;\n\n        orgQhull::Qhull qhull;\n        qhull.runQhull(\"\", ndim, points.size(), (coordT *) points.data(),  \"d Qt Qbb Qz\");\n        for(const auto & facet : qhull.facetList())\n        {\n            if(!facet.isUpperDelaunay())\n            {\n                current_index = &tmp_triangle[0];\n                for(const auto & vertex : facet.vertices())\n                {\n                    *current_index++ = vertex.point().id();\n                }\n                triangles.push_back(tmp_triangle);\n            }\n        }\n        return triangles;\n    }\n    catch( ... )\n    {\n        spirit_handle_exception_core( \"Could not compute 2D Delaunay triangulation of the Geometry. Probably Qhull threw an exception.\" );\n        return std::vector<triangle_t>(0);\n    }\n\n    const std::vector<triangle_t>& Geometry::triangulation(int n_cell_step)\n    {\n        // Only every n_cell_step'th cell is used. So we check if there is still enough cells in all\n        //      directions. Note: when visualising, 'n_cell_step' can be used to e.g. olny visualise\n        //      every 2nd spin.\n        if ( (n_cells[0]/n_cell_step < 2 && n_cells[0] > 1) ||\n             (n_cells[1]/n_cell_step < 2 && n_cells[1] > 1) ||\n             (n_cells[2]/n_cell_step < 2 && n_cells[2] > 1) )\n        {\n            _triangulation.clear();\n            return _triangulation;\n        }\n\n        // 2D: triangulation\n        if (this->dimensionality == 2)\n        {\n            // Check if the tetrahedra for this combination of n_cells and n_cell_step has already been calculated\n            if (this->last_update_n_cell_step != n_cell_step ||\n                this->last_update_n_cells[0]  != n_cells[0]  ||\n                this->last_update_n_cells[1]  != n_cells[1]  ||\n                this->last_update_n_cells[2]  != n_cells[2]  )\n            {\n                this->last_update_n_cell_step = n_cell_step;\n                this->last_update_n_cells[0]  = n_cells[0];\n                this->last_update_n_cells[1]  = n_cells[1];\n                this->last_update_n_cells[2]  = n_cells[2];\n\n                _triangulation.clear();\n\n                std::vector<vector2_t> points;\n                points.resize(positions.size());\n\n                int icell = 0, idx;\n                for (int cell_c=0; cell_c<n_cells[2]; cell_c+=n_cell_step)\n                {\n                    for (int cell_b=0; cell_b<n_cells[1]; cell_b+=n_cell_step)\n                    {\n                        for (int cell_a=0; cell_a<n_cells[0]; cell_a+=n_cell_step)\n                        {\n                            for (int ibasis=0; ibasis < n_cell_atoms; ++ibasis)\n                            {\n                                idx = ibasis + n_cell_atoms*cell_a + n_cell_atoms*n_cells[0]*cell_b + n_cell_atoms*n_cells[0]*n_cells[1]*cell_c;\n                                points[icell].x = double(positions[idx][0]);\n                                points[icell].y = double(positions[idx][1]);\n                                ++icell;\n                            }\n                        }\n                    }\n                }\n                _triangulation = compute_delaunay_triangulation_2D(points);\n            }\n        }// endif 2D\n        // 0D, 1D and 3D give no triangulation\n        else\n        {\n            _triangulation.clear();\n        }\n        return _triangulation;\n    }\n\n    const std::vector<tetrahedron_t>& Geometry::tetrahedra(int n_cell_step)\n    {\n        // Only every n_cell_step'th cell is used. So we check if there is still enough cells in all\n        //      directions. Note: when visualising, 'n_cell_step' can be used to e.g. olny visualise\n        //      every 2nd spin.\n        if (n_cells[0]/n_cell_step < 2 || n_cells[1]/n_cell_step < 2 || n_cells[2]/n_cell_step < 2)\n        {\n            _tetrahedra.clear();\n            return _tetrahedra;\n        }\n\n        // 3D: Tetrahedra\n        if (this->dimensionality == 3)\n        {\n            // Check if the tetrahedra for this combination of n_cells and n_cell_step has already been calculated\n            if (this->last_update_n_cell_step != n_cell_step ||\n                this->last_update_n_cells[0]  != n_cells[0]  ||\n                this->last_update_n_cells[1]  != n_cells[1]  ||\n                this->last_update_n_cells[2]  != n_cells[2]  )\n            {\n                this->last_update_n_cell_step = n_cell_step;\n                this->last_update_n_cells[0]  = n_cells[0];\n                this->last_update_n_cells[1]  = n_cells[1];\n                this->last_update_n_cells[2]  = n_cells[2];\n\n                // If we have only one spin in the basis our lattice is a simple regular geometry\n                bool is_simple_regular_geometry = n_cell_atoms == 1;\n\n                // If we have a simple regular geometry everything can be calculated by hand\n                if (is_simple_regular_geometry)\n                {\n                    _tetrahedra.clear();\n                    int cell_indices[] = {\n                        0, 1, 5, 3,\n                        1, 3, 2, 5,\n                        3, 2, 5, 6,\n                        7, 6, 5, 3,\n                        4, 7, 5, 3,\n                        0, 4, 3, 5\n                        };\n                    int x_offset = 1;\n                    int y_offset = n_cells[0]/n_cell_step;\n                    int z_offset = n_cells[0]/n_cell_step*n_cells[1]/n_cell_step;\n                    int offsets[] = {\n                        0, x_offset, x_offset+y_offset, y_offset,\n                        z_offset, x_offset+z_offset, x_offset+y_offset+z_offset, y_offset+z_offset\n                        };\n\n                    for (int ix = 0; ix < (n_cells[0]-1)/n_cell_step; ix++)\n                    {\n                        for (int iy = 0; iy < (n_cells[1]-1)/n_cell_step; iy++)\n                        {\n                            for (int iz = 0; iz < (n_cells[2]-1)/n_cell_step; iz++)\n                            {\n                                int base_index = ix*x_offset+iy*y_offset+iz*z_offset;\n                                for (int j = 0; j < 6; j++)\n                                {\n                                    tetrahedron_t tetrahedron;\n                                    for (int k = 0; k < 4; k++)\n                                    {\n                                        int index = base_index + offsets[cell_indices[j*4+k]];\n                                        tetrahedron[k] = index;\n                                    }\n                                    _tetrahedra.push_back(tetrahedron);\n                                }\n                            }\n                        }\n                    }\n                }\n                // For general basis cells we calculate the Delaunay tetrahedra\n                else\n                {\n                    std::vector<vector3_t> points;\n                    points.resize(positions.size());\n\n                    int icell = 0, idx;\n                    for (int cell_c=0; cell_c<n_cells[2]; cell_c+=n_cell_step)\n                    {\n                        for (int cell_b=0; cell_b<n_cells[1]; cell_b+=n_cell_step)\n                        {\n                            for (int cell_a=0; cell_a<n_cells[0]; cell_a+=n_cell_step)\n                            {\n                                for (int ibasis=0; ibasis < n_cell_atoms; ++ibasis)\n                                {\n                                    idx = ibasis + n_cell_atoms*cell_a + n_cell_atoms*n_cells[0]*cell_b + n_cell_atoms*n_cells[0]*n_cells[1]*cell_c;\n                                    points[icell].x = double(positions[idx][0]);\n                                    points[icell].y = double(positions[idx][1]);\n                                    points[icell].z = double(positions[idx][2]);\n                                    ++icell;\n                                }\n                            }\n                        }\n                    }\n                    _tetrahedra = compute_delaunay_triangulation_3D(points);\n                }\n            }\n        } // endif 3D\n        // 0-2 D gives no tetrahedra\n        else\n        {\n            _tetrahedra.clear();\n        }\n        return _tetrahedra;\n    }\n\n\n    std::vector<Vector3> Geometry::BravaisVectorsSC()\n    {\n        return { { scalar(1), scalar(0), scalar(0) },\n                 { scalar(0), scalar(1), scalar(0) },\n                 { scalar(0), scalar(0), scalar(1) } };\n    }\n\n    std::vector<Vector3> Geometry::BravaisVectorsFCC()\n    {\n        return { { scalar(0.5), scalar(0.0), scalar(0.5) },\n                 { scalar(0.5), scalar(0.5), scalar(0.0) },\n                 { scalar(0.0), scalar(0.5), scalar(0.5) } };\n    }\n\n    std::vector<Vector3> Geometry::BravaisVectorsBCC()\n    {\n        return { { scalar( 0.5), scalar( 0.5), scalar(-0.5) },\n                 { scalar(-0.5), scalar( 0.5), scalar(-0.5) },\n                 { scalar( 0.5), scalar(-0.5), scalar(-0.5) } };\n    }\n\n    std::vector<Vector3> Geometry::BravaisVectorsHex2D60()\n    {\n        return { { scalar(0.5*std::sqrt(3)), scalar(-0.5), scalar(0) },\n                 { scalar(0.5*std::sqrt(3)), scalar( 0.5), scalar(0) },\n                 { scalar(0),                scalar( 0),   scalar(1) } };\n    }\n\n    std::vector<Vector3> Geometry::BravaisVectorsHex2D120()\n    {\n        return { { scalar(0.5), scalar(-0.5*std::sqrt(3)), scalar(0) },\n                 { scalar(0.5), scalar( 0.5*std::sqrt(3)), scalar(0) },\n                 { scalar(0),   scalar( 0),                scalar(1) } };\n    }\n\n    void Geometry::applyCellComposition()\n    {\n        int N  = this->n_cell_atoms;\n        int Na = this->n_cells[0];\n        int Nb = this->n_cells[1];\n        int Nc = this->n_cells[2];\n        int ispin, iatom, atom_type;\n        scalar concentration, rvalue;\n        std::vector<bool> visited(N);\n\n        std::mt19937 prng;\n        std::uniform_real_distribution<scalar> distribution;\n        if( this->cell_composition.disordered )\n        {\n            // TODO: the seed should be a parameter and the instance a member of this class\n            prng = std::mt19937(2006);\n            distribution = std::uniform_real_distribution<scalar>(0, 1);\n            // In the disordered case, unvisited atoms will be vacancies\n            this->atom_types = intfield(nos, -1);\n        }\n\n        for (int na = 0; na < Na; ++na)\n        {\n            for (int nb = 0; nb < Nb; ++nb)\n            {\n                for (int nc = 0; nc < Nc; ++nc)\n                {\n                    std::fill(visited.begin(), visited.end(), false);\n\n                    for (int icomposition = 0; icomposition < this->cell_composition.iatom.size(); ++icomposition)\n                    {\n                        iatom = this->cell_composition.iatom[icomposition];\n\n                        if( !visited[iatom] )\n                        {\n                            ispin = N*na + N*Na*nb + N*Na*Nb*nc + iatom;\n\n                            // In the disordered case, we only visit an atom if the dice will it\n                            if( this->cell_composition.disordered )\n                            {\n                                concentration = this->cell_composition.concentration[icomposition];\n                                rvalue = distribution(prng);\n                                if( rvalue <= concentration )\n                                {\n                                    this->atom_types[ispin] = this->cell_composition.atom_type[icomposition];\n                                    this->mu_s[ispin]       = this->cell_composition.mu_s[icomposition];\n                                    visited[iatom] = true;\n                                    if( this->atom_types[ispin] < 0 )\n                                        --this->nos_nonvacant;\n                                }\n                            }\n                            // In the ordered case, we visit every atom\n                            else\n                            {\n                                this->atom_types[ispin] = this->cell_composition.atom_type[icomposition];\n                                this->mu_s[ispin]       = this->cell_composition.mu_s[icomposition];\n                                visited[iatom] = true;\n                                if( this->atom_types[ispin] < 0 )\n                                    --this->nos_nonvacant;\n                            }\n\n                            // Pinning of boundary layers\n                            if( (na < pinning.na_left || na >= Na - pinning.na_right) ||\n                                (nb < pinning.nb_left || nb >= Nb - pinning.nb_right) ||\n                                (nc < pinning.nc_left || nc >= Nc - pinning.nc_right) )\n                            {\n                                // Pinned cells\n                                this->mask_unpinned[ispin] = 0;\n                                this->mask_pinned_cells[ispin] = pinning.pinned_cell[iatom];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n\n    void Geometry::calculateDimensionality()\n    {\n        int dims_basis = 0, dims_translations = 0;\n        Vector3 test_vec_basis, test_vec_translations;\n\n        const scalar epsilon = 1e-6;\n\n        // ----- Find dimensionality of the basis -----\n        if     ( n_cell_atoms == 1 )\n            dims_basis = 0;\n        else if( n_cell_atoms == 2 )\n        {\n            dims_basis = 1;\n            test_vec_basis = positions[0] - positions[1];\n        }\n        else\n        {\n            // Get basis atoms relative to the first atom\n            Vector3 v0 = positions[0];\n            std::vector<Vector3> b_vectors(n_cell_atoms-1);\n            for( int i = 1; i < n_cell_atoms; ++i )\n                b_vectors[i-1] = (positions[i] - v0).normalized();\n\n            // Calculate basis dimensionality\n            // test vec is along line\n            test_vec_basis = b_vectors[0];\n            //      is it 1D?\n            int n_parallel = 0;\n            for( unsigned int i = 1; i < b_vectors.size(); ++i )\n            {\n                if( std::abs(b_vectors[i].dot(test_vec_basis)) - 1 < epsilon )\n                    ++n_parallel;\n                // Else n_parallel will give us the last parallel vector\n                // Also the if-statement for dims_basis=1 wont be met\n                else\n                    break;\n            }\n            if( n_parallel == b_vectors.size() - 1 )\n            {\n                dims_basis = 1;\n            }\n            else\n            {\n                // test vec is normal to plane\n                test_vec_basis = b_vectors[0].cross(b_vectors[n_parallel+1]);\n                //      is it 2D?\n                int n_in_plane = 0;\n                for( unsigned int i = 2; i < b_vectors.size(); ++i )\n                {\n                    if (std::abs(b_vectors[i].dot(test_vec_basis)) < epsilon)\n                        ++n_in_plane;\n                }\n                if( n_in_plane == b_vectors.size() - 2 )\n                    dims_basis = 2;\n                else\n                {\n                    this->dimensionality = 3;\n                    return;\n                }\n            }\n        }\n\n        // ----- Find dimensionality of the translations -----\n        //      The following are zero if the corresponding pair is parallel or antiparallel\n        double t01, t02, t12;\n        t01 = std::abs(bravais_vectors[0].normalized().dot(bravais_vectors[1].normalized())) - 1.0;\n        t02 = std::abs(bravais_vectors[0].normalized().dot(bravais_vectors[2].normalized())) - 1.0;\n        t12 = std::abs(bravais_vectors[1].normalized().dot(bravais_vectors[2].normalized())) - 1.0;\n        //      Check if pairs are linearly independent\n        int n_independent_pairs = 0;\n        if( t01 < epsilon && n_cells[0] > 1 && n_cells[1] > 1 ) ++n_independent_pairs;\n        if( t02 < epsilon && n_cells[0] > 1 && n_cells[2] > 1 ) ++n_independent_pairs;\n        if( t12 < epsilon && n_cells[1] > 1 && n_cells[2] > 1 ) ++n_independent_pairs;\n        //      Calculate translations dimensionality\n        if( n_cells[0] == 1 && n_cells[1] == 1 && n_cells[2] == 1 )\n        {\n            dims_translations = 0;\n        }\n        else if( n_independent_pairs == 0 )\n        {\n            dims_translations = 1;\n            // Test if vec is along the line\n            for (int i=0; i<3; ++i) if (n_cells[i] > 1) test_vec_translations = bravais_vectors[i];\n        }\n        else if( n_independent_pairs < 3 )\n        {\n            dims_translations = 2;\n            // Test if vec is normal to plane\n            int n = 0;\n            std::vector<Vector3> plane(2);\n            for( int i = 0; i < 3; ++i )\n            {\n                if( n_cells[i] > 1 )\n                {\n                    plane[n] = bravais_vectors[i];\n                    ++n;\n                }\n            }\n            test_vec_translations = plane[0].cross(plane[1]);\n        }\n        else\n        {\n            this->dimensionality = 3;\n            return;\n        }\n\n\n        // ----- Calculate dimensionality of system -----\n        test_vec_basis.normalize();\n        test_vec_translations.normalize();\n        //      If one dimensionality is zero, only the other counts\n        if( dims_basis == 0 )\n        {\n            this->dimensionality = dims_translations;\n            return;\n        }\n        else if( dims_translations == 0 )\n        {\n            this->dimensionality = dims_basis;\n            return;\n        }\n        //      If both are linear or both are planar, the test vectors should be (anti)parallel if the geometry is 1D or 2D\n        else if (dims_basis == dims_translations)\n        {\n            if( std::abs(test_vec_basis.dot(test_vec_translations)) - 1 < epsilon )\n            {\n                this->dimensionality = dims_basis;\n                return;\n            }\n            else if( dims_basis == 1 )\n            {\n                this->dimensionality = 2;\n                return;\n            }\n            else if( dims_basis == 2 )\n            {\n                this->dimensionality = 3;\n                return;\n            }\n        }\n        //      If one is linear (1D), and the other planar (2D) then the test vectors should be orthogonal if the geometry is 2D\n        else if( (dims_basis == 1 && dims_translations == 2) || (dims_basis == 2 && dims_translations == 1) )\n        {\n            if( std::abs(test_vec_basis.dot(test_vec_translations)) < epsilon )\n            {\n                this->dimensionality = 2;\n                return;\n            }\n            else\n            {\n                this->dimensionality = 3;\n                return;\n            }\n        }\n    }\n\n    void Geometry::calculateBounds()\n    {\n        this->bounds_max.setZero();\n        this->bounds_min.setZero();\n        for (int iatom = 0; iatom < nos; ++iatom)\n        {\n            for (int dim = 0; dim < 3; ++dim)\n            {\n                if (this->positions[iatom][dim] < this->bounds_min[dim]) this->bounds_min[dim] = this->positions[iatom][dim];\n                if (this->positions[iatom][dim] > this->bounds_max[dim]) this->bounds_max[dim] = this->positions[iatom][dim];\n            }\n        }\n    }\n\n    void Geometry::calculateUnitCellBounds()\n    {\n        this->cell_bounds_max.setZero();\n        this->cell_bounds_min.setZero();\n        for (unsigned int ivec = 0; ivec < this->bravais_vectors.size(); ++ivec)\n        {\n            for (int iatom = 0; iatom < this->n_cell_atoms; ++iatom)\n            {\n                auto neighbour1 = this->positions[iatom] + this->lattice_constant * this->bravais_vectors[ivec];\n                auto neighbour2 = this->positions[iatom] - this->lattice_constant * this->bravais_vectors[ivec];\n                for (int dim = 0; dim < 3; ++dim)\n                {\n                    if (neighbour1[dim] < this->cell_bounds_min[dim]) this->cell_bounds_min[dim] = neighbour1[dim];\n                    if (neighbour1[dim] > this->cell_bounds_max[dim]) this->cell_bounds_max[dim] = neighbour1[dim];\n                    if (neighbour2[dim] < this->cell_bounds_min[dim]) this->cell_bounds_min[dim] = neighbour2[dim];\n                    if (neighbour2[dim] > this->cell_bounds_max[dim]) this->cell_bounds_max[dim] = neighbour2[dim];\n                }\n            }\n        }\n        this->cell_bounds_min *= 0.5;\n        this->cell_bounds_max *= 0.5;\n    }\n\n    void Geometry::calculateGeometryType()\n    {\n        const scalar epsilon = 1e-6;\n\n        // Automatically try to determine GeometryType\n        // Single-atom unit cell\n        if (cell_atoms.size() == 1)\n        {\n            // If the basis vectors are orthogonal, it is a rectilinear lattice\n            if (std::abs(bravais_vectors[0].normalized().dot(bravais_vectors[1].normalized())) < epsilon &&\n                std::abs(bravais_vectors[0].normalized().dot(bravais_vectors[2].normalized())) < epsilon)\n            {\n                // If equidistant it is simple cubic\n                if (bravais_vectors[0].norm() == bravais_vectors[1].norm() == bravais_vectors[2].norm())\n                    this->classifier = BravaisLatticeType::SC;\n                // Otherwise only rectilinear\n                else\n                    this->classifier = BravaisLatticeType::Rectilinear;\n            }\n        }\n        // Regular unit cell with multiple atoms (e.g. bcc, fcc, hex)\n        //else if (n_cell_atoms == 2)\n        // Irregular unit cells arranged on a lattice (e.g. B20 or custom)\n        /*else if (n_cells[0] > 1 || n_cells[1] > 1 || n_cells[2] > 1)\n        {\n            this->classifier = BravaisLatticeType::Lattice;\n        }*/\n        // A single irregular unit cell\n        else\n        {\n            this->classifier = BravaisLatticeType::Irregular;\n        }\n    }\n\n    void Geometry::Apply_Pinning(vectorfield & vf)\n    {\n        #if defined(SPIRIT_ENABLE_PINNING)\n        int N  = this->n_cell_atoms;\n        int Na = this->n_cells[0];\n        int Nb = this->n_cells[1];\n        int Nc = this->n_cells[2];\n        int ispin;\n\n        for (int iatom = 0; iatom < N; ++iatom)\n        {\n            for (int na = 0; na < Na; ++na)\n            {\n                for (int nb = 0; nb < Nb; ++nb)\n                {\n                    for (int nc = 0; nc < Nc; ++nc)\n                    {\n                        ispin = N*na + N*Na*nb + N*Na*Nb*nc + iatom;\n                        if (!this->mask_unpinned[ispin])\n                            vf[ispin] = this->mask_pinned_cells[ispin];\n                    }\n                }\n            }\n        }\n        #endif\n    }\n}\n\n", "meta": {"hexsha": "4da814f2835b37830919c7a55cca8fe9d937ecd7", "size": 30285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/data/Geometry.cpp", "max_stars_repo_name": "ddkn/spirit", "max_stars_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "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": "core/src/data/Geometry.cpp", "max_issues_repo_name": "ddkn/spirit", "max_issues_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_issues_repo_licenses": ["MIT"], "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/data/Geometry.cpp", "max_forks_repo_name": "ddkn/spirit", "max_forks_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_forks_repo_licenses": ["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.5965147453, "max_line_length": 148, "alphanum_fraction": 0.4719167905, "num_tokens": 7208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30074559147595986, "lm_q1q2_score": 0.1515475593041542}}
{"text": "\n#include \"CRagdollCollision.h\"\n//#include \"Water.h\"\n//#include \"physical/physics/water/Water.h\"\n\n#include \"core-ext/animation/AnimationControl.h\"\n#include \"core-ext/animation/Skeleton.h\"\n#include \"core-ext/types/sHitbox.h\"\n#include \"physical/skeleton/skeletonBone.h\"\n\n#include \"renderer/logic/model/RrCModel.h\"\n\n//#include \"renderer/logic/model/CSkinnedModel.h\"\n\n//#include \"physical/physics/motion/physRigidbody.h\"\n//#include \"physical/physics/shapes/physBoxShape.h\"\n\n#include <list>\nusing std::list;\n\nCRagdollCollision::CRagdollCollision ( const prRigidbodyCreateParams& params, RrCModel* sourceModel )\n\t: CMotion(params.owner, params.ownerType)\n{\n\thasJoints = false;\n\tm_model = sourceModel;\n\n\t// Set the layer\n\tlayer = physical::layer::Hitboxes;\n\n\thitboxEntry hb;\n\tstd::vector<sHitbox>* mdl_hitboxes = NULL;// &m_model->m_meshGroup->m_hitboxes; // Mesh system currently doesn't load hitboxes, making this class useless.\n\tanimation::Skeleton* skeleton = NULL; //m_model->pMyAnimation->GetSkeleton();\n\n\t// Create the model/world space of the reference pose\n\tstd::vector<core::TransformLite> pose_model;\n\tpose_model.resize( skeleton->parent.size() );\n\tcore::TransformUtility::LocalToWorld( &skeleton->parent[0], &skeleton->reference_xpose[0], &pose_model[0], (int)pose_model.size() );\n\n#if 0\n\t// Add root as first hitbox/bone\n\t{\n\t\t//glBone* targetBone = m_skinnedmodel->GetSkeletonList()->at(0);\n\n\t\tphysShape* tCollider;\n\t\t//tCollider = Physics::CreateBoxShape( Vector3f(0.17f,0.17f,0.17f) );\n\t\ttCollider = new physBoxShape( Vector3f(0.17f,0.17f,0.17f) );\n\n\t\tphysRigidBodyInfo tInfo;\n\t\ttInfo.m_mass = 3.0f;\n\t\ttInfo.m_shape = tCollider;\n\t\ttInfo.m_centerOfMass = physVector4( 0,0,0 );\n\t\ttInfo.m_friction = 0.5f;\n\t\ttInfo.m_motionType = physMotion::MOTION_DYNAMIC;\n\t\t//Vector3f targetPosition = targetBone->xRagdollPoseModel.position;//targetBone->transform.position;\n\t\tVector3f targetPosition = pose_model[0].world.position;\n\t\ttInfo.m_position = physVector4( targetPosition.x, targetPosition.y, targetPosition.z );\n\t\t//Quaternion targetRotation = targetBone->xRagdollPoseModel.rotation;//targetBone->transform.rotation.getQuaternion();\n\t\tQuaternion targetRotation = pose_model[0].world.rotation;\n\t\ttInfo.m_rotation = physQuaternion( targetRotation.x, targetRotation.y, targetRotation.z, targetRotation.w );\n\t\ttInfo.m_linearDamping = 0.1f;\n\t\ttInfo.m_angularDamping = 0.2f;\n\n\t\ttInfo.m_collisionFilterInfo = CPhysics::GetCollisionFilter( Layers::PhysicsTypes::PHYS_HITBOX );\n\t\t\t\n\t\thitboxEntry thb;\n\t\tthb.rigidbody = new physRigidBody( &tInfo );\n\t\tthb.rigidbody->setUserData( GetId() ); // Give the rigidbody this ragoll's ID.\n\n\t\tthb.impulse = Vector3f(0,0,0);\n\t\tthb.boneIndex = 0;//targetBone->index;\n\t\tthb.hitboxIndex = 0;\n\t\tthb.name = \"Root\";\n\t\tthb.constraint = NULL;\n\n\t\tm_hitboxList.push_back( thb );\n\t\tdelete_safe(tCollider);\n\t}\n\t// Loop through model hitboxes\n\tfor ( uint i = 0; i < mdl_hitboxes->size(); ++i ) \n\t{\n\t\t//glBone* targetBone = m_skinnedmodel->GetSkeletonList()->at(mdl_hitboxes->at(i).indexLink);\n\t\tint boneIndex = mdl_hitboxes->at(i).indexLink;\n\n\t\tphysShape* tCollider;\n\t\t//tCollider = Physics::CreateBoxShape( mdl_hitboxes->at(i).extents*1.3f, mdl_hitboxes->at(i).center );\n\t\ttCollider = new physBoxShape( mdl_hitboxes->at(i).extents*1.3f, mdl_hitboxes->at(i).center );\n\n\t\tphysRigidBodyInfo tInfo;\n\t\ttInfo.m_mass = 3.0f;\n\t\ttInfo.m_shape = tCollider;\n\t\ttInfo.m_centerOfMass = physVector4( 0,0,0 );\n\t\ttInfo.m_friction = 0.5f;\n\t\ttInfo.m_motionType = physMotion::MOTION_DYNAMIC;\n\t\t//Vector3f targetPosition = targetBone->xRagdollPoseModel.position;//targetBone->transform.position;\n\t\tVector3f targetPosition = pose_model[boneIndex].world.position;\n\t\ttInfo.m_position = physVector4( targetPosition.x, targetPosition.y, targetPosition.z );\n\t\t//Quaternion targetRotation = targetBone->xRagdollPoseModel.rotation;// targetBone->transform.rotation.getQuaternion();\n\t\tQuaternion targetRotation = pose_model[boneIndex].world.rotation;\n\t\ttInfo.m_rotation = physQuaternion( targetRotation.x, targetRotation.y, targetRotation.z, targetRotation.w );\n\t\ttInfo.m_linearDamping = 0.1f;\n\t\ttInfo.m_angularDamping = 0.3f;\n\n\t\ttInfo.m_collisionFilterInfo = CPhysics::GetCollisionFilter( Layers::PhysicsTypes::PHYS_HITBOX );\n\n\t\thitboxEntry thb;\n\t\tthb.rigidbody = new physRigidBody( &tInfo );\n\t\tthb.rigidbody->setUserData( GetId() ); // Give the rigidbody this ragoll's ID.\n\n\t\tthb.impulse = Vector3f(0,0,0);\n\t\tthb.boneIndex = boneIndex;\n\t\tthb.hitboxIndex = m_hitboxList.size();\n\t\tthb.name = mdl_hitboxes->at(i).name;\n\t\tthb.constraint = NULL;\n\n\t\tm_hitboxList.push_back( thb );\n\t\tdelete_safe(tCollider);\n\t}\n#endif\n\n\tCreateJoints(pose_model);\n\tCreateMapping(pose_model);\n\n\t// Now, change inertias so ragdolls stop exploding\n\t/*{\n\t\tstd::vector<hkpConstraintInstance*> constraints;\n\t\tfor ( auto hb = m_hitboxList.begin(); hb != m_hitboxList.end(); ++hb )\n\t\t{\n\t\t\tif ( hb->constraint_instance ) {\n\t\t\t\tconstraints.push_back( hb->constraint_instance );\n\t\t\t}\n\t\t}\n\t\thkpInertiaTensorComputer::optimizeInertiasOfConstraintTree( &(constraints[0]), constraints.size(), m_hitboxList[0].rigidbody, 4 );\n\t}*/\n}\n\nvoid CRagdollCollision::CreateJoints ( std::vector<core::TransformLite>& pose_model )\n{\n\tstd::vector<sHitbox>* mdl_hitboxes = NULL;//m_skinnedmodel->GetHitboxes();\n\tanimation::Skeleton* skeleton = NULL;//m_skinnedmodel->GetSkeleton();\n\n\t// Loop through model skeleton, child-first order, to create joints\n\t//Transform* tr_root = m_skinnedmodel->GetSkeletonRoot();\n\t//std::list<Transform*> tr_bonelist;\n\t//std::list<Transform*> tr_heirarchylist;\n\t//tr_bonelist.push_back( tr_root );\n\t//// First add all the children to the list in child-first order\n\t//while ( !tr_bonelist.empty() ) {\n\t//\tTransform* tr_current = tr_bonelist.front();\n\t//\ttr_bonelist.pop_front();\n\t//\ttr_heirarchylist.push_front( tr_current ); // Add in child-first order\n\t//\tfor ( uint i = 0; i < tr_current->children.size(); ++i )\n\t//\t{\n\t//\t\ttr_bonelist.push_back( tr_current->children[i] );\n\t//\t}\n\t//}\n\t//// Loop through the children and generate joints as needed\n\t///*while ( !tr_heirarchylist.empty() ) {\n\t//\tTransform* tr_current = tr_heirarchylist.front();\n\t//\ttr_heirarchylist.pop_front();\n\t//\t// Skip root\n\t//\tif ( tr_current == m_skinnedmodel->GetSkeletonRoot() ) {\n\t//\t\tcontinue;\n\t//\t}\n\t//\tglBone* targetBone = (glBone*)tr_current->pOwnerRenderer;\n\t//\t// Search the hitboxes for this bone\n\t//\tuint hitboxIndex = uint(-1);\n\t//\tfor ( uint i = 0; i < m_hitboxList.size(); ++i ) \n\t//\t{\n\t//\t\tif ( m_hitboxList[i].boneIndex == targetBone->index ) {\n\t//\t\t\thitboxIndex = i; // Save hitbox index\n\t//\t\t\t// Break out of loop\n\t//\t\t\ti = m_hitboxList.size() + 1;\n\t//\t\t}\n\t//\t}\n\t//\t// Skip if no hitbox\n\t//\tif ( hitboxIndex == uint(-1) ) {\n\t//\t\tcontinue;\n\t//\t}*/\n#if 0\n\tfor ( uint i = 0; i < m_hitboxList.size(); ++i )\n\t{\n\t\t//Transform* tr_current = &(m_skinnedmodel->GetSkeletonList()->at(mdl_hitboxes->at(i).indexLink)->transform);\n\t\t//Transform* tr_current = &(m_skinnedmodel->GetSkeletonList()->at(m_hitboxList[i].boneIndex)->transform);\n\t\tuint hitboxIndex = i;\n\t\t//glBone* targetBone = (glBone*)tr_current->owner;\n\t\tint boneIndex = m_hitboxList[i].boneIndex;\n\n\t\t// Has a hitbox, so find the next parent with a hitbox (search up the list)\n\t\tint parentHitboxIndex = -1;\n\t\t// Search up the parents\n\t\t//CTransform* tr_next = tr_current->GetParent();\n\t\tint tr_next = skeleton->parent[boneIndex];\n\t\t//glBone* parentBone;\n\t\tint parentBone;\n\t\t//while ( tr_next != &CTransform::root )\n\t\twhile ( tr_next >= 0 )\n\t\t{\n\t\t\t//parentBone = (glBone*)tr_next->owner;\n\t\t\tparentBone = tr_next;\n\t\t\tfor ( uint i = 0; i < m_hitboxList.size(); ++i ) \n\t\t\t{\n\t\t\t\tif ( m_hitboxList[i].boneIndex == tr_next )\n\t\t\t\t{\n\t\t\t\t\tparentHitboxIndex = i; // Save hitbox index\n\t\t\t\t\t// Break out of loop\n\t\t\t\t\ti = m_hitboxList.size() + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( parentHitboxIndex != -1 )\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//tr_next = tr_next->GetParent();\n\t\t\t tr_next = skeleton->parent[tr_next];\n\t\t}\n\t\t// Skip if no parent hitbox\n\t\tif ( parentHitboxIndex == -1 )\n\t\t{\n\t\t\tm_hitboxList[i].constraint = NULL;\n\t\t\tm_hitboxList[i].constraint_instance = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t//cout << \"PARENT HITBOX: \" << hitboxIndex << \" to \" << parentHitboxIndex << endl;\n\t\t// Have a parent, so make a joint between the two rigidbodies at the position of the current bone\n\t\t/*{\n\t\t\thkpConstraintData* t_cst_data;\n\t\t\thkpConstraintInstance* t_cst_inst;\n\t\t\tif ( (targetBone->name.find( \"Calf\" ) != string::npos) || (targetBone->name.find( \"Forearm\" ) != string::npos) )\n\t\t\t{\n\t\t\t\t//targetBone->transform.Up();\n\t\t\t\tVector3f axisUp = targetBone->xRagdollPoseModel.rotation * Vector3f::up;\n\n\t\t\t\thkpLimitedHingeConstraintData* hc;\n\t\t\t\thc = new hkpLimitedHingeConstraintData();\n\t\t\t\thc->setInWorldSpace(\n\t\t\t\t\tm_hitboxList[hitboxIndex].rigidbody->getTransform(),\n\t\t\t\t\tm_hitboxList[parentHitboxIndex].rigidbody->getTransform(),\n\t\t\t\t\tm_hitboxList[hitboxIndex].rigidbody->getPosition(),\n\t\t\t\t\thkVector4( axisUp.x, axisUp.y, axisUp.z ) );\n\t\t\t\thc->setMinAngularLimit( -HK_REAL_PI * 0.9f );\n\t\t\t\thc->setMaxAngularLimit( HK_REAL_PI * 0.1f );\n\n\t\t\t\tt_cst_data = hc;\n\t\t\t}\n\t\t\telse if ( (m_hitboxList[i].name.compare( \"Hips\" )) )\n\t\t\t{\n\t\t\t\thkpBallAndSocketConstraintData* bs;\n\t\t\t\tbs = new hkpBallAndSocketConstraintData(); \n\t\t\t\tbs->setInWorldSpace(\n\t\t\t\t\tm_hitboxList[hitboxIndex].rigidbody->getTransform(),\n\t\t\t\t\tm_hitboxList[parentHitboxIndex].rigidbody->getTransform(),\n\t\t\t\t\tm_hitboxList[hitboxIndex].rigidbody->getPosition() );\n\n\t\t\t\tt_cst_data = bs;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tVector3f axisUp = targetBone->xRagdollPoseModel.rotation * Vector3f::up;\n\t\t\t\tVector3f axisSide = targetBone->xRagdollPoseModel.rotation * Vector3f::left;\n\t\t\t\tVector3f axisForward = targetBone->xRagdollPoseModel.rotation * Vector3f::forward;\n\n\t\t\t\thkpRagdollConstraintData* rdc;\n\t\t\t\t\n\t\t\t\trdc = new hkpRagdollConstraintData();\n\n\t\t\t\thkVector4 twistAxisA( axisForward.x, axisForward.y, axisForward.z );\n\t\t\t\thkVector4 planeAxisA( axisUp.x, axisUp.y, axisUp.z );\n\n\t\t\t\trdc->setInWorldSpace(\n\t\t\t\t\tm_hitboxList[hitboxIndex].rigidbody->getTransform(),\n\t\t\t\t\tm_hitboxList[parentHitboxIndex].rigidbody->getTransform(),\n\t\t\t\t\tm_hitboxList[hitboxIndex].rigidbody->getPosition(),\n\t\t\t\t\ttwistAxisA, planeAxisA );\n\n\t\t\t\trdc->setTwistMinAngularLimit( -HK_REAL_PI * 0.45f );\n\t\t\t\trdc->setTwistMaxAngularLimit( +HK_REAL_PI * 0.45f );\n\t\t\t\trdc->setPlaneMinAngularLimit( -HK_REAL_PI * 0.45f );\n\t\t\t\trdc->setPlaneMaxAngularLimit( +HK_REAL_PI * 0.45f );\n\n\t\t\t\trdc->setAsymmetricConeAngle( -HK_REAL_PI * 0.45f, +HK_REAL_PI * 0.45f );\n\n\t\t\t\tt_cst_data = rdc;\n\t\t\t}\n\n\t\t\t// Wrap constraint in malleable constraint data\n\t\t\tm_hitboxList[i].constraint = new hkpMalleableConstraintData ( t_cst_data );\n\t\t\tm_hitboxList[i].constraint->m_strength = 1;\n\n\t\t\tt_cst_inst = new hkpConstraintInstance(\n\t\t\t\tm_hitboxList[hitboxIndex].rigidbody,\n\t\t\t\tm_hitboxList[parentHitboxIndex].rigidbody,\n\t\t\t\tm_hitboxList[i].constraint);\n\n\t\t\tCPhysics::AddConstraint( t_cst_inst );\n\n\t\t\tm_hitboxList[i].constraint_instance = t_cst_inst;\n\n\t\t\tt_cst_data->removeReference();  \n\t\t\tt_cst_inst->removeReference();\n\t\t}*/\n\t}\n#endif\n}\n\n//#include <boost/algorithm/string.hpp>\n#include \"core/utils/string.h\"\nint boneNameCompare ( const char * bone1, const char * bone2 )\n{\n\tstring sbone1 (bone1);\n\tstring sbone2 (bone2);\n\tsbone1 = core::utils::string::GetLower(sbone1);\n\tsbone2 = core::utils::string::GetLower(sbone2);\n\tif ( sbone1.find(sbone2) != string::npos ) {\n\t\treturn 0;\n\t}\n\telse if ( sbone2.find(sbone1) != string::npos ) {\n\t\treturn 0;\n\t}\n\telse {\n\t\treturn sbone1.compare(sbone2);\n\t}\n}\n\nvoid CRagdollCollision::CreateMapping ( std::vector<core::TransformLite>& pose_model )\n{\n\t// First, create the skeletons\n\t/*skeletonModel = new hkaSkeleton();\n\tskeletonRagdoll = new hkaSkeleton();\n\n\t// Loop through model bones and create the skeleton\n\tskeletonModel->m_referencePose.setSize( m_skinnedmodel->GetSkeletonList()->size() );\n\tskeletonModel->m_parentIndices.setSize( m_skinnedmodel->GetSkeletonList()->size() );\n\tskeletonModel->m_bones.setSize( m_skinnedmodel->GetSkeletonList()->size() );\n\tXTransform* temp;\n\tfor ( int i = 0; i < skeletonModel->m_bones.getSize(); ++i )\n\t{\n\t\tglBone* currentBone = m_skinnedmodel->GetSkeletonList()->at(i);\n\t\ttemp = &(currentBone->xBindPose);\n\t\tskeletonModel->m_referencePose[i] = hkQsTransform(\n\t\t\thkVector4( temp->position.x, temp->position.y, temp->position.z ),\n\t\t\thkQuaternion( temp->rotation.x, temp->rotation.y, temp->rotation.z, temp->rotation.w ),\n\t\t\thkVector4( temp->scale.x, temp->scale.y, temp->scale.z ) );\n\t\tskeletonModel->m_bones[i].m_name = currentBone->name.c_str();\n\t\tskeletonModel->m_bones[i].m_lockTranslation = false;\n\n\t\t// Search for the parent index\n\t\tskeletonModel->m_parentIndices[i] = -1;\n\t\tfor ( int j = 0; j < skeletonModel->m_bones.getSize(); ++j ) {\n\t\t\tglBone* parentBone = m_skinnedmodel->GetSkeletonList()->at(j);\n\t\t\tif ( currentBone->transform.GetParent() == (&(parentBone->transform)) ) {\n\t\t\t\tskeletonModel->m_parentIndices[i] = j;\n\t\t\t\tj = skeletonModel->m_bones.getSize();\n\t\t\t}\n\t\t}\n\t}\n\n\t// Loop through hitboxes and create another skeleton\n\tskeletonRagdoll->m_referencePose.setSize( m_hitboxList.size() );\n\tskeletonRagdoll->m_parentIndices.setSize( m_hitboxList.size() );\n\tskeletonRagdoll->m_bones.setSize( m_hitboxList.size() );\n\tfor ( int i = 0; i < m_hitboxList.size(); ++i )\n\t{\n\t\tglBone* currentBone = m_skinnedmodel->GetSkeletonList()->at(m_hitboxList[i].boneIndex);\n\t\ttemp = &(currentBone->xBindPose);\n\t\tskeletonRagdoll->m_referencePose[i] = hkQsTransform(\n\t\t\thkVector4( temp->position.x, temp->position.y, temp->position.z ),\n\t\t\thkQuaternion( temp->rotation.x, temp->rotation.y, temp->rotation.z, temp->rotation.w ),\n\t\t\thkVector4( temp->scale.x, temp->scale.y, temp->scale.z ) );\n\t\tskeletonRagdoll->m_bones[i].m_name = currentBone->name.c_str();\n\t\tskeletonRagdoll->m_bones[i].m_lockTranslation = false;\n\n\t\t// Search up the parents\n\t\tCTransform* tr_next = currentBone->transform.GetParent();\n\t\tskeletonRagdoll->m_parentIndices[i] = -1;\n\t\twhile ( tr_next != &CTransform::root ) {\n\t\t\tglBone* parentBone = (glBone*)tr_next->pOwnerRenderer;\n\t\t\tfor ( uint j = 0; j < m_hitboxList.size(); ++j ) \n\t\t\t{\n\t\t\t\tif ( m_hitboxList[j].boneIndex == parentBone->index ) {\n\t\t\t\t\tskeletonRagdoll->m_parentIndices[i] = j; // Save hitbox index\n\t\tcout << \"PARENT HITBOX: \" << i << \" to \" << j << endl;\n\t\t\t\t\t// Break out of loop\n\t\t\t\t\tj = m_hitboxList.size() + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( skeletonRagdoll->m_parentIndices[i] != -1 ) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttr_next = tr_next->GetParent();\n\t\t}\n\t}\n\n\t///\n\thkaSkeletonMapperUtils::Params param;\n\tparam.m_skeletonA = skeletonModel;\n\tparam.m_skeletonB = skeletonRagdoll;\n\tparam.m_autodetectChains = false;\n\tparam.m_compareNames = boneNameCompare;\n\thkaSkeletonMapperUtils::UserChain userchain;\n\tuserchain.m_start = \"Spine\";\n\tuserchain.m_end = \"Spine3\";\n\tparam.m_userChains.pushBack( userchain );\n\n\thkaSkeletonMapperData* mdRagdollToAnim = new hkaSkeletonMapperData();\n\thkaSkeletonMapperData* mdAnimToRagdoll = new hkaSkeletonMapperData();\n\thkaSkeletonMapperUtils::createMapping( param, *mdAnimToRagdoll, *mdRagdollToAnim );\n\n\tmMapperRagdollToAnim = new hkaSkeletonMapper( *mdRagdollToAnim );\n\tmMapperAnimToRagdoll = new hkaSkeletonMapper( *mdAnimToRagdoll );\n\t*/\n}\n\nCRagdollCollision::~CRagdollCollision ( void )\n{\n\t//for ( auto hb = m_hitboxList.begin(); hb != m_hitboxList.end(); ++hb ) {\n\t//\t//Physics::FreeRigidBody( hb->rigidbody );\n\t//\tdelete_safe( hb->rigidbody );\n\t//\tif ( hb->constraint ) {\n\t//\t\tPhysics::RemoveReference(hb->constraint);\n\t//\t\thb->constraint = NULL;\n\t//\t}\n\t//}\n\t//m_hitboxList.clear();\n}\n\nvoid CRagdollCollision::Update ( void )\n{\n\t//bool inWater = WaterTester::Get()->PositionInside( m_hitboxList[0].start.position );\n\t//auto skeleton = m_skinnedmodel->GetSkeleton();\n\t//for ( auto hb = m_hitboxList.begin(); hb != m_hitboxList.end(); ++hb )\n\t//{\n\t//\t//glBone* targetBone = m_skinnedmodel->GetSkeletonList()->at(hb->boneIndex);\n\t//\tif ( hb->constraint )\n\t//\t{\n\t//\t\t//glBone* parentBone = (glBone*)(targetBone->transform.owner);\n\t//\t\t//hb->constraint->m_strength = std::max<Real>(targetBone->ragdollStrength,parentBone->ragdollStrength); //* 0.7f;\n\t//\t\tif ( skeleton->parent[hb->boneIndex] >= 0 )\n\t//\t\t{\n\t//\t\t\thb->constraint->m_strength = std::max<Real>(\n\t//\t\t\t\tskeleton->ext_physics_strength[hb->boneIndex],\n\t//\t\t\t\tskeleton->ext_physics_strength[skeleton->parent[hb->boneIndex]]);\n\t//\t\t}\n\t//\t}\n\t//\tif ( hb->rigidbody )\n\t//\t{\n\t//\t\tif ( !inWater ) {\n\t//\t\t\t//hb->rigidbody->setGravityFactor( targetBone->ragdollStrength );\n\t//\t\t\thb->rigidbody->setGravityFactor( skeleton->ext_physics_strength[hb->boneIndex] );\n\t//\t\t\thb->rigidbody->setLinearDamping( 0.1f );\n\t//\t\t}\n\t//\t\telse {\n\t//\t\t\thb->rigidbody->setGravityFactor( 0.05f );\n\t//\t\t\thb->rigidbody->setLinearDamping( 0.6f );\n\t//\t\t}\n\t//\t}\n\t//}\n}\n\nvoid CRagdollCollision::LateUpdate ( void )\n{\n\t//// Set the current hitbox rigidbody position, so can create proper velocities later\n\t//for ( auto hb = m_hitboxList.begin(); hb != m_hitboxList.end(); ++hb )\n\t//{\n\t//\thb->start.position = hb->rigidbody->getPosition();\n\t//\thb->start.rotation = hb->rigidbody->getRotation();\n\t//}\n}\n\nvoid CRagdollCollision::PostUpdate ( void )\n{\n\t\n}\n\nvoid CRagdollCollision::PostFixedUpdate ( void )\n{\n\n}\n\nvoid CRagdollCollision::RigidbodyUpdate ( Real interpolation )\n{\n\tanimation::Skeleton* skeleton = NULL;//m_skinnedmodel->GetSkeleton();\n\t// Need a Ragdoll to Animation conversion here\n\tfor ( auto hb = m_hitboxList.begin(); hb != m_hitboxList.end(); ++hb )\n\t{\t// TODO: apply impulse and continue\n\t\thb->impulse = Vector3f(0,0,0);\n\n\t\t// If the ragdoll strength is high with this one, take the output from the physics\n\t\t/*glBone* targetBone = m_skinnedmodel->GetSkeletonList()->at(hb->boneIndex);\n\t\tif ( targetBone->ragdollStrength > FTYPE_PRECISION )\n\t\t{\n\t\t\tVector3f nextPosition = hb->rigidbody->getPosition();\n\t\t\tnextPosition -= m_skinnedmodel->transform.position;\n\t\t\tnextPosition = m_skinnedmodel->transform.rotation.inverse() * nextPosition;\n\t\t\ttargetBone->transform.position = targetBone->transform.position.lerp(nextPosition,targetBone->ragdollStrength);\n\n\t\t\tQuaternion nextRotation = hb->rigidbody->getRotation();\n\t\t\tRotator nextRotator = m_skinnedmodel->transform.rotation.inverse() * Rotator(nextRotation);\n\t\t\ttargetBone->transform.rotation = targetBone->transform.rotation.LerpTo(nextRotator,targetBone->ragdollStrength);\n\t\t}*/\n\t\tif ( skeleton->ext_physics_strength[hb->boneIndex] > FTYPE_PRECISION)\n\t\t{\n\t\t\tthrow core::NotYetImplementedException();\n\t\t}\n\t}\n}\n\n\nvoid CRagdollCollision::FixedUpdate ( void )\n{\n\tanimation::Skeleton* skeleton = NULL;//m_skinnedmodel->GetSkeleton();\n\t// TODO: Ensure lite transform is updated\n#if 0 \n\n\t// Need a Animation to Ragdoll conversion here\n\tfor ( auto hb = m_hitboxList.begin(); hb != m_hitboxList.end(); ++hb )\n\t{\n\t\t//glBone* targetBone = m_skinnedmodel->GetSkeletonList()->at(hb->boneIndex);\n\t\tcore::TransformLite* bone_transform = &skeleton->current_transform[hb->boneIndex]; \n\t\tReal bone_strength = skeleton->ext_physics_strength[hb->boneIndex];\n\n\t\tVector3f targetPosition = m_skinnedmodel->transform.rotation * bone_transform->world.position + m_skinnedmodel->transform.position;\n\t\tQuaternion targetRotation = ( m_skinnedmodel->transform.rotation * bone_transform->world.rotation ).getQuaternion();\n\n\t\tVector3f linearVelocity = hb->rigidbody->getLinearVelocity();\n\t\tVector4f angularVelocity = hb->rigidbody->getAngularVelocity();\n\t\tlinearVelocity *= bone_strength;\n\t\tangularVelocity *= bone_strength;\n\t\tVector3f currentPosition = hb->rigidbody->getPosition();\n\t\tVector3f deltaPosition = targetPosition - currentPosition;\n\t\t//currentPosition.setInterpolate( hkVector4(targetPosition.x,targetPosition.y,targetPosition.z), currentPosition, targetBone->ragdollStrength );\n\t\tcurrentPosition = targetPosition.lerp( currentPosition, bone_strength );\n\t\tQuaternion currentRotation = hb->rigidbody->getRotation();\n\t\tQuaternion deltaRotation = targetRotation;\n\t\tQuaternion invRotation = currentRotation;\n//\t\tinvRotation.setInverse( currentRotation );\n\t\tinvRotation.Invert();\n\t\t//deltaRotation.mul( invRotation );\n\t\tdeltaRotation = deltaRotation * invRotation;\n\t\t//currentRotation.setSlerp( hkQuaternion(targetRotation.x,targetRotation.y,targetRotation.z,targetRotation.w), currentRotation, targetBone->ragdollStrength );\n\t\tcurrentRotation = targetRotation.Slerp( currentRotation, bone_strength );\n\n\t\t// now, motorize the rigidbody\n\t\tdeltaPosition = targetPosition;//hkVector4( targetPosition.x, targetPosition.y, targetPosition.z );\n\t\t//deltaPosition.sub( hkVector4( hb->start.position.x,hb->start.position.y,hb->start.position.z ) );\n\t\tdeltaPosition -= hb->start.position;\n\n\t\t//deltaPosition.mul( (1 - targetBone->ragdollStrength)*30 );\n\t\tdeltaPosition *= (1.0F - bone_strength)*30.0F;\n\t\tlinearVelocity += deltaPosition;\n\t\t//deltaRotation.setSlerp( deltaRotation, hkQuaternion::getIdentity(), targetBone->ragdollStrength );\n\t\tdeltaRotation = deltaRotation.Slerp( Quaternion(), bone_strength );\n\t\tangularVelocity += Vector4f( &deltaRotation.x );\n\t\t\n\t\t// set velocities and position\n\t\thb->rigidbody->setLinearVelocity( linearVelocity );\n\t\thb->rigidbody->setAngularVelocity( angularVelocity );\n\t\thb->rigidbody->setPositionAndRotation( currentPosition, currentRotation );\n\n\t}\n#endif\n\t/*hkaPose modelPose ( skeletonModel );\n\thkaPose ragdollPose ( skeletonRagdoll );\n\n\t// Get current anim pose\n\thkArray<hkQsTransform>& tempTransforms = modelPose.accessUnsyncedPoseModelSpace();\n\tfor ( uint i = 0; i < skeletonModel->m_bones.getSize(); ++i )\n\t{\n\t\tglBone* bone = m_skinnedmodel->GetSkeletonList()->at(i);\n\t\tVector3f position = bone->transform.position;\n\t\ttempTransforms[i].m_translation = hkVector4( position.x, position.y, position.z );\n\t\tQuaternion rotation = bone->transform.rotation;\n\t\ttempTransforms[i].m_rotation = hkQuaternion( rotation.x, rotation.y, rotation.z, rotation.w );\n\t\tQuaternion scale = bone->transform.scale;\n\t\ttempTransforms[i].m_scale = hkVector4( scale.x, scale.y, scale.z );\n\t}\n\n\tragdollPose.setToReferencePose();\n\n\tmMapperAnimToRagdoll->mapPose( modelPose, ragdollPose, hkaSkeletonMapper::CURRENT_POSE );\n\tragdollPose.syncModelSpace();\n\n\t// Apply the animation to the ragdoll\n\tfor ( auto hb = m_hitboxList.begin(); hb != m_hitboxList.end(); ++hb )\n\t{\n\t\tglBone* targetBone = m_skinnedmodel->GetSkeletonList()->at(hb->boneIndex);\n\t\thkQsTransform targetTransform = ragdollPose.getBoneModelSpace(hb->hitboxIndex);\n\n\t\thkVector4 linearVelocity = hb->rigidbody->getLinearVelocity();\n\t\thkVector4 angularVelocity = hb->rigidbody->getAngularVelocity();\n\t\tlinearVelocity.mul( targetBone->ragdollStrength );\n\t\tangularVelocity.mul( targetBone->ragdollStrength );\n\n\t\thkVector4 currentPosition = hb->rigidbody->getPosition();\n\t\tcurrentPosition.setInterpolate( targetTransform.getTranslation(), currentPosition, targetBone->ragdollStrength );\n\t\thkQuaternion currentRotation = hb->rigidbody->getRotation();\n\t\tcurrentRotation.setSlerp( targetTransform.getRotation(), currentRotation, targetBone->ragdollStrength );\n\n\t\thb->rigidbody->setLinearVelocity( linearVelocity );\n\t\thb->rigidbody->setAngularVelocity( angularVelocity );\n\t\thb->rigidbody->setPositionAndRotation( currentPosition, currentRotation );\n\t}*/\n}\n\nvoid CRagdollCollision::SetActor ( CActor* n_actor )\n{\n\tm_owning_actor = n_actor;\n\towner = (CGameBehavior*)n_actor;\n}\n\nCActor* CRagdollCollision::GetActor ( void )\n{\n\treturn m_owning_actor;\n}\nReal\tCRagdollCollision::GetMultiplier ( btRigidBody* n_hitBody )\n{\n\t// Todo: give certain rigidbodies different damage boosters\n\treturn 1;\n}", "meta": {"hexsha": "b4168f8966cde1b04d6bc9a833f2bd0525534c42", "size": 23360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "oneEngine/oneGame/source/engine-common/physics/motion/CRagdollCollision.cpp", "max_stars_repo_name": "jonting/1Engine", "max_stars_repo_head_hexsha": "f22ba31f08fa96fe6405ebecec4f374138283803", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T02:59:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T04:30:03.000Z", "max_issues_repo_path": "oneEngine/oneGame/source/engine-common/physics/motion/CRagdollCollision.cpp", "max_issues_repo_name": "jonting/1Engine", "max_issues_repo_head_hexsha": "f22ba31f08fa96fe6405ebecec4f374138283803", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-16T03:44:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T06:48:44.000Z", "max_forks_repo_path": "oneEngine/oneGame/source/engine-common/physics/motion/CRagdollCollision.cpp", "max_forks_repo_name": "jonting/1Engine", "max_forks_repo_head_hexsha": "f22ba31f08fa96fe6405ebecec4f374138283803", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T02:09:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T02:09:54.000Z", "avg_line_length": 37.7993527508, "max_line_length": 160, "alphanum_fraction": 0.7182363014, "num_tokens": 6843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15154754982967136}}
{"text": "#include <iostream>\n#include <sstream>\n\n#include <armadillo>\n\n#include <cpp-argparse/OptionParser.h>\n#include <besiq/io/covariates.hpp>\n\n#include <plink/plink_file.hpp>\n\n#include \"gene_environment.hpp\"\n\nusing namespace arma;\nusing namespace optparse;\n\nconst std::string USAGE = \"besiq-predict [OPTIONS] plink_file beta_file\";\nconst std::string DESCRIPTION = \"Predicts phenotypes given a list of betas.\";\nconst std::string VERSION = \"besiq 0.0.1\";\nconst std::string EPILOG = \"\";\n\narma::vec\nparse_beta(std::istream &stream, std::vector<std::string> &labels)\n{\n    std::string line;\n    std::vector<double> beta_list;\n    while( std::getline( stream, line ) )\n    {\n        std::istringstream line_stream( line );\n        std::string rs_name;\n        double beta;\n\n        line_stream >> rs_name >> beta;\n            \n        labels.push_back( rs_name );\n        beta_list.push_back( beta );\n    }\n\n    arma::vec b = arma::zeros<arma::vec>( beta_list.size( ) );\n    for(int i = 0; i < beta_list.size( ); i++)\n    {\n        b[ i ] = beta_list[ i ];\n    }\n    \n    return b;\n}\n\narma::uvec get_causal_indices(const std::vector<std::string> variable_order, const std::vector<std::string> &labels)\n{\n    std::vector<size_t> indices;\n    std::map<std::string, int> variable_to_index;\n    for(int i = 0; i < variable_order.size( ); i++)\n    {\n        variable_to_index[ variable_order[ i ] ] = i;\n    }\n\n    for(int i = 0; i < labels.size( ); i++)\n    {\n        if( variable_to_index.count( labels[ i ] ) > 0 )\n        {\n            indices.push_back( variable_to_index[ labels[ i ] ] );\n        }\n    }\n\n    arma::uvec result = arma::zeros<arma::uvec>( indices.size( ) );\n    for(int i = 0; i < indices.size( ); i++)\n    {\n        result[ i ] = indices[ i ];\n    }\n\n    return result;\n}\n\nint\nmain(int argc, char *argv[])\n{\n    OptionParser parser = OptionParser( ).usage( USAGE )\n                                         .version( VERSION )\n                                         .description( DESCRIPTION )\n                                         .epilog( EPILOG ); \n \n    parser.add_option( \"-c\", \"--cov\" ).action( \"store\" ).type( \"string\" ).metavar( \"filename\" ).help( \"Performs the analysis by including the covariates in this file.\" );\n    parser.add_option( \"-o\", \"--out\" ).help( \"The output file that will contain the results (binary).\" );\n    parser.add_option( \"--standardize\" ).help( \"Use standardized genotypes and covariates.\" ).action( \"store_true\" );\n\n    Values options = parser.parse_args( argc, argv );\n    if( parser.args( ).size( ) != 2 )\n    {\n        parser.print_help( );\n        exit( 1 );\n    }\n\n    std::ios_base::sync_with_stdio( false );\n    \n    /* Read all genotypes */\n    plink_file_ptr genotype_file = open_plink_file( parser.args( )[ 0 ] );\n    genotype_matrix_ptr genotypes = create_genotype_matrix( genotype_file );\n    std::vector<std::string> order = genotype_file->get_sample_iids( );\n    std::vector< std::pair<std::string, std::string> > fid_iid = genotype_file->get_sample_fid_iid( );\n\n    std::vector<std::string> labels;\n    std::ifstream beta_file( parser.args( )[ 1 ].c_str( ) );\n    arma::vec beta = parse_beta( beta_file, labels );\n\n    /* Make error streams separate from stdout */\n    arma::set_stream_err1( std::cerr );\n    arma::set_stream_err2( std::cerr );\n\n    /* Parse phenotypes */\n    arma::uvec cov_missing = arma::zeros<arma::uvec>( genotype_file->get_samples( ).size( ) );\n    arma::mat cov;\n    std::vector<std::string> cov_names;\n    if( options.is_set( \"cov\" ) )\n    {\n        std::ifstream covariate_file( options[ \"cov\" ].c_str( ) );\n        cov = parse_covariate_matrix( covariate_file, cov_missing, order, &cov_names );\n    }\n\n    /* Open output stream */\n    std::ofstream output_file;\n    if( options.is_set( \"out\" ) )\n    {\n        output_file.open( options[ \"out\" ].c_str( ) );\n    }\n    std::ostream &out = options.is_set( \"out\" ) ? output_file : std::cout;\n\n    arma::vec phenotype = arma::zeros<arma::vec>( fid_iid.size( ) );\n    gene_environment ge( genotypes, cov, phenotype, cov_names, true );\n    ge.impute_missing( );\n\n    arma::uvec causal = get_causal_indices( ge.get_names( ), labels );\n    if( causal.n_elem != labels.size( ) )\n    {\n        std::cout << \"besiq-predict: Error could not find all genotype or covariate variables.\\n\";\n        return 1;\n    }\n\n    bool standardize = options.is_set( \"only_pvalues\" );\n    \n    arma::mat X;\n    if( standardize )\n    {\n        X = ge.get_active( causal );\n    }\n    else\n    {\n        X = ge.get_active_raw( causal );\n    }\n    arma::vec y = X * beta;\n    arma::vec y_std = ( y - arma::mean( y ) ) / arma::stddev( y );\n\n    out << \"FID\\tIID\\tPhenotype\\n\";\n    for(int i = 0; i < fid_iid.size( ); i++)\n    {\n        out << fid_iid[ i ].first << \"\\t\" << fid_iid[ i ].second << \"\\t\" << y_std[ i ] << \"\\n\";\n    } \n\n    return 0;\n}\n", "meta": {"hexsha": "68b5e6ceea4b6588e1522b80946f414b5ab5509e", "size": 4850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/besiq_predict.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "src/besiq_predict.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "src/besiq_predict.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 30.5031446541, "max_line_length": 170, "alphanum_fraction": 0.5901030928, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.26894142136999516, "lm_q1q2_score": 0.1511925472090369}}
{"text": "#include \"stdafx.h\"\r\n#include \"CryptoSaver.h\"\r\n\r\n\r\n#include <boost/random/random_device.hpp>\r\n#include <boost/random/uniform_int_distribution.hpp>\r\n#include <boost/endian/arithmetic.hpp>\r\n\r\n#include <boost/spirit/include/qi.hpp>\r\n#include <boost/spirit/include/phoenix.hpp>\r\n#include <boost/fusion/include/adapt_struct.hpp>\r\n#include <boost/fusion/include/std_pair.hpp> \r\n\r\n#include <boost/archive/iterators/binary_from_base64.hpp>\r\n#include <boost/archive/iterators/base64_from_binary.hpp>\r\n#include <boost/archive/iterators/remove_whitespace.hpp>\r\n#include <boost/archive/iterators/insert_linebreaks.hpp>\r\n#include <boost/archive/iterators/transform_width.hpp>\r\n#include <boost/archive/iterators/ostream_iterator.hpp>\r\n\r\n#include <boost/algorithm/string.hpp>\r\n\r\n#include <openssl/rsa.h>\r\n#include <openssl/rand.h>\r\n#include <openssl/err.h>\r\n#include <openssl/evp.h>\r\n\r\n\r\ntypedef boost::endian::big_uint64_at uint64be_t;\r\n\r\ntypedef\r\nBOOLEAN(*RtlGenRandom_t)(\r\n\t_Out_ PVOID RandomBuffer,\r\n\t_In_  ULONG RandomBufferLength\r\n\t);\r\n\r\nclass WinRandomGen : public RandomGen\r\n{\r\npublic:\r\n\tWinRandomGen()\r\n\t{\r\n\t\thLib = LoadLibrary(L\"advapi32.dll\");\r\n\t\tif (!hLib)\r\n\t\t\tthrow std::runtime_error(\"Could not load advapi32.dll\");\r\n\r\n\t\tgen_rand = (RtlGenRandom_t)GetProcAddress(hLib, \"SystemFunction036\");\r\n\t\tif (!gen_rand)\r\n\t\t\tthrow std::runtime_error(\"Could not load RtlGenRandom\");\r\n\r\n\t}\r\n\r\n\tvirtual ~WinRandomGen()\r\n\t{\r\n\t\tFreeLibrary(hLib);\r\n\t}\r\n\r\n\tvirtual void generate(uint8_t * buffer, size_t& len)\r\n\t{\r\n\t\tgen_rand(buffer, (ULONG)len);\r\n\t}\r\nprivate:\r\n\tHMODULE hLib;\r\n\tRtlGenRandom_t gen_rand;\r\n};\r\n\r\n\r\n\r\nRandomGen::Ptr RandomGen::create()\r\n{\r\n\treturn boost::make_shared<WinRandomGen>();\r\n}\r\n\r\n\r\nCryptoKey::CryptoKey()\r\n{\r\n\r\n}\r\n\r\nCryptoKey::~CryptoKey()\r\n{\r\n\r\n}\r\n\r\nconst uint8_t * CryptoKey::get()\r\n{\r\n\treturn m_public_key.get();\r\n}\r\n\r\nsize_t CryptoKey::size()\r\n{\r\n\treturn m_public_key_size;\r\n}\r\n\r\nCryptoKey CryptoKey::load(std::string const& filename)\r\n{\r\n\tnamespace bs = boost::spirit;\r\n\tnamespace qi = boost::spirit::qi;\r\n\tnamespace phx = boost::phoenix;\r\n\tusing namespace bs;\r\n\tusing namespace qi::standard;\r\n\r\n\r\n\tstd::string contents;\r\n\tfs::ifstream in(filename, std::ios::in | std::ios::binary);\r\n\tif (!in)\r\n\t\tthrow std::runtime_error((std::string(\"Cannot open file \") + filename).c_str());\r\n\r\n\tin.seekg(0, std::ios::end);\r\n\tcontents.resize(in.tellg());\r\n\tin.seekg(0, std::ios::beg);\r\n\tin.read(&contents[0], contents.size());\r\n\tin.close();\r\n\r\n\tauto first = std::begin(contents);\r\n\tauto last = std::end(contents);\r\n\r\n\tstd::string key;\r\n\r\n\tqi::rule<std::string::const_iterator, std::string()> key_rule =\r\n\t\tlit(\"-----BEGIN RSA PUBLIC KEY-----\\n\")\r\n\t\t\t> lexeme[*(char_(\"A-Za-z0-9/+=\\n\"))]\r\n\t\t\t> \"-----END RSA PUBLIC KEY-----\\n\";\r\n\r\n\tbool r = qi::phrase_parse(first, last, key_rule[phx::ref(key) = bs::_1], blank);\r\n\tif (!r )\r\n\t{\r\n\t\tstd::cerr << L\"Failed to read public key file\" << std::endl;\r\n\t\tthrow std::runtime_error(\"Failed to read public key file\");\r\n\t}\r\n\r\n\tstd::vector<uint8_t> result;\r\n\r\n\t{\r\n\t\tusing namespace boost::archive::iterators;\r\n\t\ttypedef transform_width< binary_from_base64<remove_whitespace<std::string::const_iterator> >, 8, 6 > it_binary_t;\r\n\r\n\t\tstd::string contents = b::trim_copy(key);\r\n\t\tsize_t paddChars = std::count(contents.begin(), contents.end(), '=');\r\n\t\tresult.assign(it_binary_t(contents.begin()), it_binary_t(contents.end())); // decode\r\n\t\tresult.erase(result.end() - paddChars, result.end());  // erase padding '\\0' characters\r\n\t}\r\n\r\n\tCryptoKey cryptokey;\r\n\r\n\tcryptokey.m_public_key_size = result.size();\r\n\tcryptokey.m_public_key = b::make_shared<uint8_t[] >(cryptokey.m_public_key_size);\r\n\tstd::copy(std::begin(result), std::end(result), cryptokey.m_public_key.get());\r\n\r\n\treturn cryptokey;\r\n}\r\n\r\n\r\n\r\nCryptoSaver::CryptoSaver(const CryptoKey& key, RandomGen * pRandom)\r\n\t: m_rsa(nullptr)\r\n\t, m_key(key)\r\n\t, m_pRandom(pRandom)\r\n{\r\n\tm_rsa = RSA_new();\r\n\tconst uint8_t * p_key = m_key.get();\r\n\td2i_RSAPublicKey(&m_rsa, &p_key, (long)m_key.size());\r\n\r\n}\r\n\r\nCryptoSaver::~CryptoSaver()\r\n{\r\n\tRSA_free(m_rsa);\r\n}\r\n\r\nbool CryptoSaver::save(const fs::path& filename, uint8_t const* txt, size_t txt_size)\r\n{\r\n\tif (!m_rsa)\r\n\t{\r\n\t\tstd::vector<char> err(1024);\r\n\t\tERR_error_string_n(ERR_get_error(), err.data(), err.size());\r\n\t\tstd::cerr << L\"Internal activation error: \" << err.data() << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t{\r\n\t\tuint8_t buffer[32];\r\n\t\tsize_t len = sizeof(buffer);\r\n\t\tm_pRandom->generate(buffer, len);\r\n\t\tRAND_seed(buffer, (int)len);\r\n\t\tmemset(buffer, 0, sizeof(buffer));\r\n\t}\r\n\r\n\tconst size_t key_size = RSA_size(m_rsa);\r\n\r\n\tstd::vector<uint8_t> aesPassword(key_size - 42, 0); //The Ultimate Question of Life, the Universe, and Everything\r\n\r\n\t{\r\n\t\tsize_t sz = aesPassword.size();\r\n\t\tm_pRandom->generate(aesPassword.data(), sz);\r\n\t\tif(sz < aesPassword.size())\r\n\t\t\taesPassword.erase(aesPassword.end() - sz, aesPassword.end());\r\n\t}\r\n\r\n\tstd::vector<uint8_t> encryptedPassword;\r\n\r\n\t{\r\n\t\tencryptedPassword.resize((aesPassword.size() / key_size + 1)*key_size + 10);\r\n\r\n\t\t{\r\n\t\t\tint step = RSA_public_encrypt((int)aesPassword.size(),\r\n\t\t\t\taesPassword.data(),\r\n\t\t\t\tencryptedPassword.data(),\r\n\t\t\t\tm_rsa,\r\n\t\t\t\tRSA_PKCS1_OAEP_PADDING);\r\n\t\t\tif (step < 0)\r\n\t\t\t{\r\n\t\t\t\tstd::vector<char> err(1024);\r\n\t\t\t\tERR_error_string_n(ERR_get_error(), err.data(), err.size());\r\n\t\t\t\tstd::cerr << L\"Failed to store activation data: \" << err.data() << std::endl;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif (step < encryptedPassword.size())\r\n\t\t\t\tencryptedPassword.erase(encryptedPassword.end() - (encryptedPassword.size() - step), encryptedPassword.end());\r\n\t\t}\r\n\t}\r\n\r\n\tstd::vector<uint8_t> ciphered_data;\r\n\r\n\t{\r\n\t\tEVP_CIPHER_CTX *ctx;\r\n\t\tconst EVP_CIPHER *cipher;\r\n\t\tconst EVP_MD *dgst = NULL;\r\n\t\tconst uint8_t *salt = NULL;\r\n\t\tuint8_t key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];\r\n\t\tstd::vector<uint8_t> block;\r\n\t\tint len = 0, written = 0;\r\n\r\n\t\tblock.resize(txt_size + sizeof(key) + 1);\r\n\r\n\t\tif (!(ctx = EVP_CIPHER_CTX_new()))\r\n\t\t{\r\n\t\t\tstd::cerr << (\"Failed to initialize cipher\") << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tcipher = EVP_get_cipherbyname(\"aes-256-cbc\");\r\n\t\tif (!cipher)\r\n\t\t{\r\n\t\t\tstd::cerr << (\"EVP_get_cipherbyname failed\") << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tdgst = EVP_get_digestbyname(\"md5\");\r\n\t\tif (!dgst)\r\n\t\t{\r\n\t\t\tstd::cerr << (\"EVP_get_digestbyname failed\") << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (!EVP_BytesToKey(cipher, dgst, salt, aesPassword.data(), (int)aesPassword.size(), 1, key, iv))\r\n\t\t{\r\n\t\t\tstd::cerr << (\"EVP_BytesToKey failed\") << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))\r\n\t\t{\r\n\t\t\tstd::cerr << (\"Failed to initialize AES\") << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (1 != EVP_EncryptUpdate(ctx, block.data(), &len, txt, (int)txt_size))\r\n\t\t{\r\n\t\t\tstd::cerr << (\"EVP_EncryptUpdate failed\") << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\twritten += len;\r\n\r\n\t\tif (1 != EVP_EncryptFinal_ex(ctx, block.data() + written, &len))\r\n\t\t{\r\n\t\t\tstd::cerr << (\"EVP_EncryptFinal_ex failed\") << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\twritten += len;\r\n\r\n\t\tciphered_data.insert(std::end(ciphered_data), block.begin(), block.begin() + written);\r\n\r\n\t\tEVP_CIPHER_CTX_free(ctx);\r\n\t}\r\n\r\n\r\n\t//write data to file\r\n\t{\r\n\t\tuint64be_t dataSize = (uint64_t)encryptedPassword.size();\r\n\t\tfs::ofstream os(filename, std::ios::out | std::ios::binary);\r\n\t\tif (!os)\r\n\t\t{\r\n\t\t\tstd::cerr << (\"Failed to open file: \") << filename << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tos.write((const char*)&dataSize, sizeof(dataSize));\r\n\t\tos.write((const char*)encryptedPassword.data(), encryptedPassword.size());\r\n\r\n\t\tdataSize = ciphered_data.size();\r\n\t\tos.write((const char*)&dataSize, sizeof(dataSize));\r\n\t\tos.write((const char*)ciphered_data.data(), ciphered_data.size());\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "9cbec13e0177af4915130b71acb73bdc596117f9", "size": 7750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CryptoSaver.cpp", "max_stars_repo_name": "Ghoort/GmailSaver", "max_stars_repo_head_hexsha": "4b2769b7b1c58f3b129183f5147c83deb5320f1a", "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": "CryptoSaver.cpp", "max_issues_repo_name": "Ghoort/GmailSaver", "max_issues_repo_head_hexsha": "4b2769b7b1c58f3b129183f5147c83deb5320f1a", "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": "CryptoSaver.cpp", "max_forks_repo_name": "Ghoort/GmailSaver", "max_forks_repo_head_hexsha": "4b2769b7b1c58f3b129183f5147c83deb5320f1a", "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.9196141479, "max_line_length": 116, "alphanum_fraction": 0.6576774194, "num_tokens": 2104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.1511707610844322}}
{"text": "#include \"gene/coding/dna.hpp\"\n#include \"gene/policies.hpp\"\n#include \"gene/algorithm.hpp\"\n\n#include <utility>\n#include <boost/noncopyable.hpp>\n\nusing namespace gene;\nusing namespace gene::coding::dna;\n\n///////////////////////////////////////////////////////////////////////////////\nstruct Neuron : boost::noncopyable\n{\n  uint8_t x;\n  uint8_t y;\n  uint8_t z;\n  uint8_t distanceThreshold;\n  uint8_t outputThreshold;\n};\n\n///////////////////////////////////////////////////////////////////////////////\nstruct Network\n{\n  std::vector<Network> neurons;\n};\n\n///////////////////////////////////////////////////////////////////////////////\nstruct MyFactory : public Codec<Network, Genotype>\n{\n  Network decode(const Genotype&) const throw(std::invalid_argument) override { }\n  Genotype encode(const Network&) const override { };\n};\n\n///////////////////////////////////////////////////////////////////////////////\nstruct MyFitness : FitnessFunction<Network, Genotype>\n{\n  Fitness calculate(const Population<Network, Genotype>&) override { }\n};\n\n\n///////////////////////////////////////////////////////////////////////////////\nstruct Survival : public SurvivalPolicy<Network, Genotype>\n{\n  Population<Network, Genotype>\n          selectSurvivors (Population<Network, Genotype>&& ancestors,\n                           Population<Network, Genotype>&& offspring) override { }\n};\n\n///////////////////////////////////////////////////////////////////////////////\nint main(void)\n{\n  std::vector<gene::coding::dna::Chromosome> chromosomes;\n  gene::coding::dna::Genotype g(std::move(chromosomes));\n\n  BaseMutation<Network> mutation(0.10, 423);\n  ConstantMutationRate<Network> mutationRate(0.20);\n  SimpleCrossover crossover(1245);\n\n  MyFactory factory;\n  MyFitness fitness;\n  Survival survival;\n/*\n  GeneticAlgorithm<Individual, Genotype> (factory,\n                                          fitness,\n                                          mutation,\n                                          mutationRate,\n                                          attraction,\n                                          crossover,\n                                          survival);\n*/  return 0;\n}\n", "meta": {"hexsha": "ebd237a7dd10a5e7193aa481f8d0279b613036cd", "size": 2164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test.cpp", "max_stars_repo_name": "noe/gene", "max_stars_repo_head_hexsha": "f57e5027a16309c091e363b4264a857f2fe736f7", "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/test.cpp", "max_issues_repo_name": "noe/gene", "max_issues_repo_head_hexsha": "f57e5027a16309c091e363b4264a857f2fe736f7", "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/test.cpp", "max_forks_repo_name": "noe/gene", "max_forks_repo_head_hexsha": "f57e5027a16309c091e363b4264a857f2fe736f7", "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": 30.0555555556, "max_line_length": 82, "alphanum_fraction": 0.4810536044, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.151170757890131}}
{"text": "#ifndef BOOST_PREPROCESSOR_REPEAT_FROM_TO_HPP\n#define BOOST_PREPROCESSOR_REPEAT_FROM_TO_HPP\n\n/* Copyright (C) 2002\n * Housemarque Oy\n * http://www.housemarque.com\n *\n * Permission to copy, use, modify, sell and distribute this software is\n * granted provided this copyright notice appears in all copies. This\n * software is provided \"as is\" without express or implied warranty, and\n * with no claim as to its suitability for any purpose.\n *\n * See http://www.boost.org for most recent version.\n */\n\n#include <boost/preprocessor/repeat.hpp>\n#include <boost/preprocessor/arithmetic/sub.hpp>\n#include <boost/preprocessor/arithmetic/add.hpp>\n\n/** <p>Repeats the macro <code>MACRO(INDEX,DATA)</code> for <code>INDEX = [FIRST,LAST)</code>.</p>\n\n<p>In other words, expands to the sequence:</p>\n\n<pre>\n  MACRO(FIRST,DATA) MACRO(BOOST_PP_INC(FIRST),DATA) ... MACRO(BOOST_PP_DEC(LAST),DATA)\n</pre>\n\n<p>For example,</p>\n\n<pre>\n  #define TEST(INDEX,DATA) DATA(INDEX);\n  BOOST_PP_REPEAT_FROM_TO(4,7,TEST,X)\n</pre>\n\n<p>expands to:</p>\n\n<pre>\n  X(4); X(5); X(6);\n</pre>\n\n<h3>Uses</h3>\n<ul>\n  <li>BOOST_PP_REPEAT()</li>\n</ul>\n\n<h3>Test</h3>\n<ul>\n  <li><a href=\"../../test/repeat_test.cpp\">repeat_test.cpp</a></li>\n</ul>\n*/\n#define BOOST_PP_REPEAT_FROM_TO(FIRST,LAST,MACRO,DATA) BOOST_PP_REPEAT(BOOST_PP_SUB(LAST,FIRST),BOOST_PP_REPEAT_FROM_TO_F,(FIRST,MACRO,DATA))\n#define BOOST_PP_REPEAT_FROM_TO_F(I,SMP) BOOST_PP_TUPLE_ELEM(3,1,SMP)(BOOST_PP_ADD(I,BOOST_PP_TUPLE_ELEM(3,0,SMP)),BOOST_PP_TUPLE_ELEM(3,2,SMP))\n#endif\n", "meta": {"hexsha": "40f9ee106c0aee0a0f4a563f113fa522a3e74f11", "size": 1501, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/preprocessor/repeat_from_to.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "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": "vegastrike/boost/1_28/boost/preprocessor/repeat_from_to.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_28/boost/preprocessor/repeat_from_to.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["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.7962962963, "max_line_length": 144, "alphanum_fraction": 0.7295136576, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.1510587597957258}}
{"text": "//----------------------------------------------------------------------------\n// Copyright (C) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the Server Side Public License, version 1,\n// as published by the author.\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// Server Side Public License for more details.\n//\n// You should have received a copy of the Server Side Public License\n// along with this program. If not, see\n// <https://github.com/NilFoundation/plugin/blob/master/LICENSE_1_0.txt>.\n//----------------------------------------------------------------------------\n\n#define BOOST_TEST_MODULE drg_compound_test\n\n#include <boost/test/data/monomorphic.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <nil/filecoin/storage/proofs/porep/drg/compound.hpp>\n\nusing namespace nil::filecoin;\n\ntemplate<typename MerkleTreeType>\nvoid drgporep_test_compound() {\n\n    const auto rng = XorShiftRng::from_seed(crate::TEST_SEED);\n\n    const auto nodes = 8;\n    const auto degree = BASE_DEGREE;\n    const std::vector<auto> challenges = {1, 3};\n\n    const auto replica_id : Fr = Fr::random(rng);\n    std::vector<std::uint8_t> data = (0..nodes).flat_map(| _ | fr_into_bytes(&Fr::random(rng))).collect();\n\n    // MT for original data is always named tree-d, and it will be\n    // referenced later in the process as such.\n    const auto cache_dir = tempfile::tempdir();\n    const auto config = StoreConfig(cache_dir.path(), cache_key::CommDTree.to_string(),\n                                   default_rows_to_discard(nodes, BINARY_ARITY), );\n\n    // Generate a replica path.\n    const auto replica_path = cache_dir.path().join(\"replica-path\");\n    auto mmapped_data = setup_replica(&data, &replica_path);\n\n    const auto setup_params = compound_proof::SetupParams {\n        vanilla_params : drg::SetupParams {\n            drg : drg::DrgParams {\n                nodes,\n                degree,\n                expansion_degree : 0,\n                porep_id : [32; 32],\n            },\n            private : false,\n            challenges_count : 2,\n        },\n        partitions : None,\n        priority : false,\n    };\n\n    const auto public_params =\n        drg_porep_compound<typename MerkleTreeType::hash_type, BucketGraph<typename MerkleTreeType::hash_type>>::setup(&setup_params).expect(\"setup failed\");\n\n    const auto data_tree : Option<BinaryMerkleTree<typename MerkleTreeType::hash_type>> = None;\n    const auto(tau, aux) = drg::DrgPoRep::<typename MerkleTreeType::hash_type, BucketGraph<_>>::replicate(\n                        &public_params.vanilla_params, &replica_id.into(), (mmapped_data).into(), data_tree,\n                        config, replica_path.clone(), )\n                        .expect(\"failed to replicate\");\n\n    const auto public_inputs = drg::PublicInputs:: <typename MerkleTreeType::hash_type::digest_type > {\n        replica_id : Some(replica_id.into()),\n        challenges,\n        tau : Some(tau),\n    };\n    const auto private_inputs = drg::PrivateInputs {\n        tree_d : &aux.tree_d,\n        tree_r : &aux.tree_r,\n        tree_r_config_rows_to_discard : default_rows_to_discard(nodes, BINARY_ARITY),\n    };\n\n    // This duplication is necessary so public_params don't outlive public_inputs and private_inputs.\n    const auto setup_params = compound_proof::SetupParams {\n        vanilla_params : drg::SetupParams {\n            drg : drg::DrgParams {\n                nodes,\n                degree,\n                expansion_degree : 0,\n                porep_id : [32; 32],\n            },\n            private : false,\n            challenges_count : 2,\n        },\n        partitions : None,\n        priority : false,\n    };\n\n    const auto public_params =\n        drg_porep_compound<typename MerkleTreeType::hash_type, BucketGraph<typename MerkleTreeType::hash_type>>::setup(&setup_params).expect(\"setup failed\");\n\n    const auto(circuit, inputs) =\n        drg_porep_compound<typename MerkleTreeType::hash_type, _>::circuit_for_test(&public_params, &public_inputs, &private_inputs, )\n            ;\n\n    auto cs = TestConstraintSystem();\n\n    circuit.synthesize(cs).expect(\"failed to synthesize test circuit\");\n    assert(cs.is_satisfied());\n    assert(cs.verify(&inputs));\n\n    const auto blank_circuit =\n        <drg_porep_compound<_, _> as CompoundProof<_, _>>::blank_circuit(&public_params.vanilla_params, );\n\n    auto cs_blank = MetricCS();\n    blank_circuit.synthesize(cs_blank).expect(\"failed to synthesize blank circuit\");\n\n    const auto a = cs_blank.pretty_print_list();\n    const auto b = cs.pretty_print_list();\n\n    for (i, (a, b)) in a.chunks(100).zip(b.chunks(100)).enumerate() {\n        BOOST_ASSERT_MSG(a == b, std::format(\"failed at chunk %d\", i));\n    }\n\n\n    const auto gparams = drg_porep_compound<typename MerkleTreeType::hash_type>::groth_params(Some(rng), &public_params.vanilla_params, )\n                      .expect(\"failed to get groth params\");\n\n    const auto proof = drg_porep_compound<typename MerkleTreeType::hash_type>::prove(&public_params, &public_inputs, &private_inputs, &gparams, )\n                    .expect(\"failed while proving\");\n\n    const auto verified = drg_porep_compound<typename MerkleTreeType::hash_type>::verify(&public_params, &public_inputs, &proof, &NoRequirements, )\n                       .expect(\"failed while verifying\");\n\n    assert(verified);\n\n    cache_dir.close().expect(\"Failed to remove cache dir\");\n}\n\nBOOST_AUTO_TEST_SUITE(drg_compound_test_suite)\n\nBOOST_AUTO_TEST_CASE(test_drgporep_compound_pedersen) {\n    drgporep_test_compound<BinaryMerkleTree<PedersenHasher>>();\n}\n\nBOOST_AUTO_TEST_CASE(test_drgporep_compound_poseidon) {\n    drgporep_test_compound<BinaryMerkleTree<PoseidonHasher>>();\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "2b66fddce16cac91e32d50dd45d8559eb648f09f", "size": 6006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/storage/test/porep/drg/compound.cpp", "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/test/porep/drg/compound.cpp", "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/test/porep/drg/compound.cpp", "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": 39.5131578947, "max_line_length": 157, "alphanum_fraction": 0.6545121545, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.1508295753203797}}
{"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\n#ifndef BOOST_SIMD_FUNCTION_SIMD_ASIN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIMD_ASIN_HPP_INCLUDED\n\n#include <boost/simd/function/scalar/asin.hpp>\n#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>\n#include <boost/simd/arch/common/simd/function/asin.hpp>\n\n#endif\n", "meta": {"hexsha": "119a6c734222d8aea7708da019e2f75426bf2412", "size": 669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/simd/asin.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/simd/asin.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/simd/asin.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.1666666667, "max_line_length": 100, "alphanum_fraction": 0.5605381166, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.15062353161979936}}
{"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#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <vw/Core/Debugging.h>\n#include <vw/Math/Geometry.h>\n#include <vw/Math/RANSAC.h>\n#include <vw/Math/Vector.h>\n#include <vw/Image/Algorithms.h>\n#include <vw/Image/EdgeExtension.h>\n#include <vw/Image/Manipulation.h>\n#include <vw/Image/MaskViews.h>\n#include <vw/Image/Transform.h>\n#include <vw/InterestPoint/InterestData.h>\n#include <vw/Stereo/CorrelationView.h>\n#include <vw/Stereo/CostFunctions.h>\n#include <vw/Stereo/PreFilter.h>\n#include <vw/Stereo/DisparityMap.h>\n#include <vw/Cartography/GeoReferenceUtils.h>\n\n#include <boost/program_options.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/path.hpp>\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nusing namespace vw;\nusing namespace vw::stereo;\n\n\nint main( int argc, char *argv[] ) {\n\n  std::string left_file_name, right_file_name;\n  float log;\n  int32 h_corr_min, h_corr_max;\n  int32 v_corr_min, v_corr_max;\n  int32 xkernel, ykernel;\n  int   lrthresh;\n  int   min_lr_level;\n  int   nThreads;\n  int   tile_size;\n  int   collar_size;\n  int   sgm_filter_size;\n  int   max_pyramid_levels;\n  int   cost_mode;\n  int   stereo_algorithm;\n  bool  found_alignment = false;\n  int   blob_filter_area;\n  Matrix3x3 alignment;\n  float mask_value;\n  int   filter_radius;\n  int   mem_limit_gb;\n\n  po::options_description desc(\"Options\");\n  desc.add_options()\n    (\"help,h\", \"Display this help message\")\n    (\"left\",       po::value(&left_file_name),                 \"Explicitly specify the \\\"left\\\" input file\")\n    (\"right\",      po::value(&right_file_name),                \"Explicitly specify the \\\"right\\\" input file\")\n    (\"log\",        po::value(&log)->default_value(1.4),        \"Apply LOG filter with the given sigma, or 0 to disable\")\n    (\"h-corr-min\", po::value(&h_corr_min)->default_value(-30), \"Minimum horizontal disparity\")\n    (\"h-corr-max\", po::value(&h_corr_max)->default_value( 30), \"Maximum horizontal disparity\")\n    (\"v-corr-min\", po::value(&v_corr_min)->default_value(-5),  \"Minimum vertical disparity\")\n    (\"v-corr-max\", po::value(&v_corr_max)->default_value(5),   \"Maximum vertical disparity\")\n    (\"xkernel\",    po::value(&xkernel)->default_value(15),     \"Horizontal correlation kernel size\")\n    (\"ykernel\",    po::value(&ykernel)->default_value(15),     \"Vertical correlation kernel size\")\n    (\"lrthresh\",   po::value(&lrthresh)->default_value(2),     \"Left/right correspondence threshold\")\n    (\"min-lr-level\",    po::value(&min_lr_level)->default_value(1),     \"Min level to check L/R correspondence at (SGM only).\")\n    (\"filter-radius\",      po::value(&filter_radius)->default_value(5), \"Disp filtering radius\")\n    (\"cost-mode\",          po::value(&cost_mode)->default_value(0), \n                        \"0 - Abs difference; 1 - Sq Difference; 2 - NormXCorr; 3 - Census; 4 - Ternary Census\")\n    (\"stereo-algorithm\",   po::value(&stereo_algorithm)->default_value(0), \n                    \"Choose the stereo algorithm: 0=BM, 1=SGM, 2=MGM, 3=FinalMGM\")\n    //(\"affine-subpix\", \"Enable affine adaptive sub-pixel correlation (slower, but more accurate)\") // TODO: Unused!\n    (\"blob-filter-area\",   po::value(&blob_filter_area)->default_value(0),     \"Filter blobs of this size.\")\n    (\"threads\",            po::value(&nThreads)->default_value(0),    \"Manually specify the number of threads\")\n    (\"tile-size\",          po::value(&tile_size)->default_value(0),   \"Manually specify the tile size\")\n    (\"collar-size\",        po::value(&collar_size)->default_value(0), \"Specify a collar size\")\n    (\"max-mem-GB\",         po::value(&mem_limit_gb)->default_value(0), \"Specify the maximum memory size\")\n    (\"sgm-filter-size\",    po::value(&sgm_filter_size)->default_value(0), \"Filter SGM subpixel results with this size\")\n    (\"mask-value\",         po::value(&mask_value)->default_value(-32768), \"Specify a mask value\")\n    (\"max-pyramid-levels\", po::value(&max_pyramid_levels)->default_value(5),\n      \"Limit the maximum number of pyramid levels\")\n    (\"debug\",      \"Write out debugging images\")\n    ;\n  po::positional_options_description p;\n  p.add(\"left\", 1);\n  p.add(\"right\", 1);\n\n  po::variables_map vm;\n  try {\n    po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );\n    po::notify( vm );\n  } catch (const po::error& e) {\n    std::cout << \"An error occurred while parsing command line arguments.\\n\";\n    std::cout << \"\\t\" << e.what() << \"\\n\\n\";\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  if( vm.count(\"help\") ) {\n    vw_out() << desc << std::endl;\n    return 1;\n  }\n\n  if( vm.count(\"left\") != 1 || vm.count(\"right\") != 1 ) {\n    vw_out() << \"Error: Must specify one (and only one) left and right input file!\" << std::endl;\n    vw_out() << desc << std::endl;\n    return 1;\n  }\n\n  if (nThreads > 0)\n    vw::vw_settings().set_default_num_threads(nThreads);\n  if (tile_size > 0)\n    vw::vw_settings().set_default_tile_size(tile_size);\n\n  // If the user provided a match file, use it to align the images.\n  std::string match_filename = fs::path( left_file_name ).replace_extension().string() + \"__\" +\n                               fs::path( right_file_name ).stem().string() + \".match\";\n  if ( fs::exists( match_filename ) ) {\n    vw_out() << \"Found a match file. Using it to pre-align images.\\n\";\n    std::vector<ip::InterestPoint> matched_ip1, matched_ip2;\n    ip::read_binary_match_file( match_filename,\n                                matched_ip1, matched_ip2 );\n    std::vector<Vector3> ransac_ip1 = ip::iplist_to_vectorlist(matched_ip1);\n    std::vector<Vector3> ransac_ip2 = ip::iplist_to_vectorlist(matched_ip2);\n    vw::math::RandomSampleConsensus<vw::math::HomographyFittingFunctor, vw::math::InterestPointErrorMetric> \n        ransac( vw::math::HomographyFittingFunctor(), vw::math::InterestPointErrorMetric(), 100, 30, ransac_ip1.size()/2, true );\n    alignment = ransac( ransac_ip2, ransac_ip1 );\n\n    DiskImageView<PixelGray<float> > right_disk_image( right_file_name );\n    right_file_name = \"aligned_right.tif\";\n    write_image( right_file_name, transform(right_disk_image, HomographyTransform(alignment)),\n                 TerminalProgressCallback( \"tools.correlate\", \"Aligning: \") );\n    found_alignment = true;\n  }\n\n  // Load input images\n  DiskImageView<PixelGray<float> > left_disk_image (left_file_name );\n  DiskImageView<PixelGray<float> > right_disk_image(right_file_name );\n  int cols = std::min(left_disk_image.cols(),right_disk_image.cols());\n  int rows = std::min(left_disk_image.rows(),right_disk_image.rows());\n  ImageViewRef<PixelGray<float> > left  = edge_extend(left_disk_image, 0,0,cols,rows);\n  ImageViewRef<PixelGray<float> > right = edge_extend(right_disk_image,0,0,cols,rows);\n\n  // Set up masks\n  ImageView<uint8> left_mask  = constant_view( uint8(255), left );\n  ImageView<uint8> right_mask = constant_view( uint8(255), right);\n  if (vm.count(\"mask-value\")) {\n    left_mask  = apply_mask(copy_mask(left_mask,  create_mask(left,  mask_value)), 0);\n    right_mask = apply_mask(copy_mask(right_mask, create_mask(right, mask_value)), 0);\n    \n    write_image(\"correlate_left_mask.tif\", left_mask);\n    write_image(\"correlate_right_mask.tif\", right_mask);\n  }\n\n  bool write_debug_images = (vm.count(\"debug\"));\n\n  // TODO: Hook up to options!\n  SemiGlobalMatcher::SgmSubpixelMode sgm_subpixel_mode = SemiGlobalMatcher::SUBPIXEL_LC_BLEND;\n  Vector2i sgm_search_buffer(4,2);\n  size_t memory_limit_mb = 1024*5;\n  if (mem_limit_gb > 0)\n    memory_limit_mb = mem_limit_gb * 1024;\n\n  ImageViewRef<PixelMask<Vector2f> > disparity_map;\n  int corr_timeout = 0;\n  double seconds_per_op = 0.0;\n  BBox2i search_range(Vector2i(h_corr_min, v_corr_min), \n                      Vector2i(h_corr_max, v_corr_max));\n  Vector2i kernel_size(xkernel, ykernel);\n  std::cout << \"Correlate max search range = \" << search_range << std::endl;\n  disparity_map =\n    stereo::pyramid_correlate( left,      right,\n                               left_mask, right_mask,\n                               stereo::PREFILTER_LOG, log,\n                               search_range, kernel_size,\n                               static_cast<vw::stereo::CostFunctionType>(cost_mode), \n                               corr_timeout, seconds_per_op,\n                               lrthresh, min_lr_level,\n                               filter_radius, max_pyramid_levels, \n                               static_cast<vw::stereo::CorrelationAlgorithm>(stereo_algorithm), \n                               collar_size,\n                               sgm_subpixel_mode,\n                               sgm_search_buffer,\n                               memory_limit_mb,\n                               blob_filter_area,\n                               write_debug_images);\n\n  // TODO: Call the code used in stereo_fltr!\n\n/*\n\n// TODO: Debug code for experimenting with disparity filtering code.\n  int texture_smooth_range = 15;\n  float texture_max_percentage = 0.85;\n  int max_kernel_size = 13;\n\n  std::cout << \"Generating texture image...\\n\";\n  ImageView<float> texture_image;\n  ImageView<float> leftR = left;\n  float max_texture = texture_measure(leftR, texture_image, texture_smooth_range);\n  write_image( \"texture_image.tif\", texture_image );\n\n  std::cout << \"Rasterizing disparity image...\\n\";\n  ImageView<PixelMask<Vector2f> > disparity_map_raster = disparity_map;\n  //disparity_map.rasterize(disparity_map_raster, bounding_box(disparity_map));\n  \n  std::cout << \"Filtering disparity image...\\n\";\n  ImageView<PixelMask<Vector2f> > disparity_map_filtered;\n  texture_preserving_disparity_filter(disparity_map_raster, disparity_map_filtered, texture_image, \n                                      texture_max_percentage*max_texture, max_kernel_size);\n  \n  write_image( \"texture_filtered_disp.tif\", disparity_map_filtered );\n  //write_image( \"subpixel_disp.tif\", disparity );\n  //write_image( \"subpixel_deltas.tif\", deltas );\n  \n  std::cout << \"Done!\\n\";\n\n\n*/\n\n  //ImageViewRef<PixelMask<Vector2f> > result = pixel_cast<PixelMask<Vector2f> >(disparity_map);\n  if ( found_alignment )\n    disparity_map = transform_disparities(disparity_map, HomographyTransform(alignment) );\n\n  // Actually invoke the raster\n  {\n    vw::Timer corr_timer(\"Correlation Time\");\n    cartography::GdalWriteOptions geo_opt;\n    geo_opt.raster_tile_size = Vector2i(1024, 1024);\n    if (stereo_algorithm == VW_CORRELATION_BM) {\n      block_write_gdal_image(\"disparity.tif\", disparity_map, geo_opt);\n    }\n    else { // SGM/MGM needs to be rasterized in a single tile.\n      ImageView<PixelMask<Vector2f> > result = disparity_map;\n      block_write_gdal_image(\"disparity.tif\", result, geo_opt);\n    }\n  }\n\n  //// Write disparity debug images\n  //DiskImageView<PixelMask<Vector2i> > solution(\"disparity.tif\");\n  //BBox2 disp_range = get_disparity_range(solution);\n  //std::cout << \"Found disparity range: \" << disp_range << \"\\n\";\n\n  // Are these working properly?\n  //write_image( \"x_disparity.tif\",\n  //             channel_cast<uint8>(apply_mask(copy_mask(clamp(normalize(select_channel(solution,0), \n  //                                 disp_range.min().x(), disp_range.max().x(),0,255)),solution))) );\n  //write_image( \"y_disparity.tif\",\n  //             channel_cast<uint8>(apply_mask(copy_mask(clamp(normalize(select_channel(solution,1), \n  //                                 disp_range.min().y(), disp_range.max().y(),0,255)),solution))) );\n\n  return 0;\n}\n", "meta": {"hexsha": "7014fb27da2e4da8f04166fa5d4bc744ff1e77ed", "size": 12307, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/tools/correlate.cc", "max_stars_repo_name": "lucasz93/visionworkbench", "max_stars_repo_head_hexsha": "1784572beda475e6770384f5cf34b578a320da51", "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/vw/tools/correlate.cc", "max_issues_repo_name": "lucasz93/visionworkbench", "max_issues_repo_head_hexsha": "1784572beda475e6770384f5cf34b578a320da51", "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/tools/correlate.cc", "max_forks_repo_name": "lucasz93/visionworkbench", "max_forks_repo_head_hexsha": "1784572beda475e6770384f5cf34b578a320da51", "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.7527272727, "max_line_length": 129, "alphanum_fraction": 0.6675875518, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.1505796973942263}}
{"text": "#include <string>\n\n#include <boost/lexical_cast.hpp>\n\n#include <crypto++/aes.h>\n#include <crypto++/ccm.h>\n#include <crypto++/cryptlib.h>\n#include <crypto++/filters.h>\n#include <crypto++/hex.h>\n\n#include \"ccrypt.hpp\"\n//#include \"error.hpp\"\n#include \"errlogger.hpp\"\n\nusing namespace std;\nusing CryptoPP::AES;\nusing CryptoPP::CBC_Mode;\nusing CryptoPP::Exception;\nusing CryptoPP::HexDecoder;\nusing CryptoPP::HexEncoder;\nusing CryptoPP::StreamTransformationFilter;\nusing CryptoPP::StringSink;\nusing CryptoPP::StringSource;\nusing namespace CCrypt;\n\nunsigned char EncDec::key[] = { 0x23, 0x56, 0x31, 0x76, 0x61, 0x4d, 0x61, 0x72, 0x61, 0x6c, 0x3a, 0x2d, 0x2a, 0x2f, 0x2e, 0x3f };\nunsigned char EncDec::iv[] = { 0x38, 0x34, 0x32, 0x34, 0x33, 0x30, 0x31, 0x30, 0x34, 0x33, 0x35, 0x39, 0x32, 0x34, 0x2e, 0x34 };\n\nconst string EncDec::Encrypt(const string& plainText) {\n    string cipher, encoded;\n\n    try {\n        CBC_Mode<AES>::Encryption enc;\n        enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));\n\n        cipher.clear();\n        StringSource(plainText, true, new StreamTransformationFilter(enc, new StringSink(cipher)));\n\n        encoded.clear();\n        StringSource(cipher, true, new HexEncoder(new StringSink(encoded)));\n    }\n    catch(CryptoPP::Exception& ex) {\n        SAAIIR::ErrLogger::LogError((\"Encrypt :  \" + boost::lexical_cast<string>(ex.what())).c_str());\n        //throw Error(ex.what());\n    }\n\n    return encoded;\n}\n\nconst string EncDec::Decrypt(const string& cipherText) {\n    string cipher, recovered;\n\n    try {\n        CBC_Mode<AES>::Decryption dec;\n        dec.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));\n\n        cipher.clear();\n        StringSource(cipherText, true, new HexDecoder(new StringSink(cipher)));\n\n        recovered.clear();\n        StringSource s(cipher, true, new StreamTransformationFilter(dec, new StringSink(recovered)));\n    }\n    catch(CryptoPP::Exception& ex) {\n        SAAIIR::ErrLogger::LogError((\"Decrypt :  \" + boost::lexical_cast<string>(ex.what())).c_str());\n        //throw Error(ex.what());\n    }\n\n    return recovered;\n}\n", "meta": {"hexsha": "14a49a0752a332e49fa02c9360a25e21e7e5dce6", "size": 2078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "website/src/ccrypt.cpp", "max_stars_repo_name": "Wt-Works/saai.ir", "max_stars_repo_head_hexsha": "18b9e75616300994c8d5034f766b6e91c6a48c16", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-28T01:24:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T01:24:22.000Z", "max_issues_repo_path": "website/src/ccrypt.cpp", "max_issues_repo_name": "Wt-Works/saai.ir", "max_issues_repo_head_hexsha": "18b9e75616300994c8d5034f766b6e91c6a48c16", "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": "website/src/ccrypt.cpp", "max_forks_repo_name": "Wt-Works/saai.ir", "max_forks_repo_head_hexsha": "18b9e75616300994c8d5034f766b6e91c6a48c16", "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": 29.6857142857, "max_line_length": 129, "alphanum_fraction": 0.6684311838, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.15055468977514738}}
{"text": "/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * 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, 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 * @brief IronBee --- CLIPP Split Modifier Implementation\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n */\n\n#include \"split_modifier.hpp\"\n\n#include <clipp/random_support.hpp>\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#if __has_warning(\"-Wunused-local-typedef\")\n#pragma clang diagnostic ignored \"-Wunused-local-typedef\"\n#endif\n#endif\n#include <boost/bind.hpp>\n#include <boost/foreach.hpp>\n#include <boost/make_shared.hpp>\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n#include <ctime>\n\nusing boost::bind;\nusing namespace std;\n\nnamespace IronBee {\nnamespace CLIPP {\n\n// Split Data\n\nstruct SplitDataModifier::State\n{\n    //! Distribution of targets.\n    distribution_t distribution;\n};\n\nSplitDataModifier::SplitDataModifier(size_t n) :\n    m_state(new State())\n{\n    m_state->distribution = bind(constant_distribution, n);\n}\n\nbool SplitDataModifier::operator()(Input::input_p& input)\n{\n    if (! input) {\n        return true;\n    }\n\n    BOOST_FOREACH(Input::Transaction& tx, input->connection.transactions) {\n        Input::event_p event;\n        for (\n            Input::event_list_t::iterator i = tx.events.begin();\n            i != tx.events.end();\n            ++i\n        ) {\n            event = *i;\n            Input::event_list_t::iterator at = boost::next(i);\n            if (\n                event->which == Input::REQUEST_BODY ||\n                event->which == Input::RESPONSE_BODY ||\n                event->which == Input::CONNECTION_DATA_IN ||\n                event->which == Input::CONNECTION_DATA_OUT\n            ) {\n                double post_delay = event->post_delay;\n                event->post_delay = 0;\n\n\n                Input::DataEvent* new_event =\n                    dynamic_cast<Input::DataEvent*>(event.get());\n                if (! new_event) {\n                    throw logic_error(\"Event had type/which mismatch.\");\n                }\n\n                Input::Buffer original = new_event->data;\n\n                while (original.length > 0) {\n                    size_t length = min(\n                        original.length,\n                        m_state->distribution()\n                    );\n\n                    new_event->data = Input::Buffer(original.data, length);\n                    original.data += length;\n                    original.length -= length;\n\n                    if (original.length > 0) {\n                        new_event = new Input::DataEvent(event->which);\n                        tx.events.insert(at, Input::event_p(new_event));\n                    }\n                }\n\n                i = boost::prior(at);\n                (*i)->post_delay = post_delay;\n            }\n        }\n    }\n\n    return true;\n}\n\nSplitDataModifier SplitDataModifier::uniform(\n    unsigned int min,\n    unsigned int max\n)\n{\n    if (min > max) {\n        throw runtime_error(\"Min must be less than or equal to max.\");\n    }\n    if (min == 0 || max == 0) {\n        throw runtime_error(\"Min and max must be positive.\");\n    }\n    SplitDataModifier mod;\n    mod.m_state->distribution = make_random_distribution(\n        boost::random::uniform_int_distribution<>(min, max)\n    );\n    return mod;\n}\n\nSplitDataModifier SplitDataModifier::binomial(unsigned int t, double p)\n{\n    if (t == 0 || p <= 0) {\n        throw runtime_error(\"t and p must be positive.\");\n    }\n    if (p > 1) {\n        throw runtime_error(\"p must be less than or equal to 1.\");\n    }\n    SplitDataModifier mod;\n    mod.m_state->distribution = make_random_distribution(\n        boost::random::binomial_distribution<>(t, p)\n    );\n    return mod;\n}\n\nSplitDataModifier SplitDataModifier::geometric(double p)\n{\n    if (p < 0 || p >= 1) {\n        throw runtime_error(\"p must be in [0,1)\");\n    }\n    SplitDataModifier mod;\n    mod.m_state->distribution = make_random_distribution(\n        boost::random::geometric_distribution<>(p)\n    );\n    return mod;\n}\n\nSplitDataModifier SplitDataModifier::poisson(double mean)\n{\n    SplitDataModifier mod;\n    mod.m_state->distribution = make_random_distribution(\n        boost::random::poisson_distribution<>(mean)\n    );\n    return mod;\n}\n\n// SplitHeader\n\nstruct SplitHeaderModifier::State\n{\n    //! Distribution of targets.\n    distribution_t distribution;\n};\n\nSplitHeaderModifier::SplitHeaderModifier(size_t n) :\n    m_state(new State())\n{\n    m_state->distribution = bind(constant_distribution, n);\n}\n\nbool SplitHeaderModifier::operator()(Input::input_p& input)\n{\n    if (! input) {\n        return true;\n    }\n\n    BOOST_FOREACH(Input::Transaction& tx, input->connection.transactions) {\n        Input::event_p event;\n        for (\n            Input::event_list_t::iterator i = tx.events.begin();\n            i != tx.events.end();\n            ++i\n        ) {\n            event = *i;\n            Input::event_list_t::iterator at = boost::next(i);\n            if (\n                event->which == Input::REQUEST_HEADER ||\n                event->which == Input::RESPONSE_HEADER\n            ) {\n                double post_delay = event->post_delay;\n                event->post_delay = 0;\n\n                Input::HeaderEvent* new_event =\n                    dynamic_cast<Input::HeaderEvent*>(event.get());\n                if (! new_event) {\n                    throw logic_error(\"Event had type/which mismatch.\");\n                }\n\n                Input::header_list_t original = new_event->headers;\n                Input::header_list_t::const_iterator original_i =\n                    original.begin();\n                size_t original_remaining = original.size();\n\n                while (original_remaining > 0) {\n                    size_t length = min(\n                        original_remaining,\n                        m_state->distribution()\n                    );\n\n                    new_event->headers.clear();\n                    Input::header_list_t::const_iterator original_j =\n                        boost::next(original_i, length);\n                    copy(\n                        original_i, original_j,\n                        back_inserter(new_event->headers)\n                    );\n                    original_i = original_j;\n                    original_remaining -= length;\n\n                    if (original_remaining > 0) {\n                        new_event = new Input::HeaderEvent(event->which);\n                        tx.events.insert(at, Input::event_p(new_event));\n                    }\n                }\n\n                i = boost::prior(at);\n                (*i)->post_delay = post_delay;\n            }\n        }\n    }\n\n    return true;\n}\n\nSplitHeaderModifier SplitHeaderModifier::uniform(\n    unsigned int min,\n    unsigned int max\n)\n{\n    if (min > max) {\n        throw runtime_error(\"Min must be less than or equal to max.\");\n    }\n    if (min == 0 || max == 0) {\n        throw runtime_error(\"Min and max must be positive.\");\n    }\n    SplitHeaderModifier mod;\n    mod.m_state->distribution = make_random_distribution(\n        boost::random::uniform_int_distribution<>(min, max)\n    );\n    return mod;\n}\n\nSplitHeaderModifier SplitHeaderModifier::binomial(unsigned int t, double p)\n{\n    if (t == 0 || p <= 0) {\n        throw runtime_error(\"t and p must be positive.\");\n    }\n    if (p > 1) {\n        throw runtime_error(\"p must be less than or equal to 1.\");\n    }\n    SplitHeaderModifier mod;\n    mod.m_state->distribution = make_random_distribution(\n        boost::random::binomial_distribution<>(t, p)\n    );\n    return mod;\n}\n\nSplitHeaderModifier SplitHeaderModifier::geometric(double p)\n{\n    if (p < 0 || p >= 1) {\n        throw runtime_error(\"p must be in [0,1)\");\n    }\n    SplitHeaderModifier mod;\n    mod.m_state->distribution = make_random_distribution(\n        boost::random::geometric_distribution<>(p)\n    );\n    return mod;\n}\n\nSplitHeaderModifier SplitHeaderModifier::poisson(double mean)\n{\n    SplitHeaderModifier mod;\n    mod.m_state->distribution = make_random_distribution(\n        boost::random::poisson_distribution<>(mean)\n    );\n    return mod;\n}\n\n} // CLIPP\n} // IronBee\n", "meta": {"hexsha": "21a0c9133ea73b58fc7cdb15ad81516264a75d01", "size": 8933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clipp/split_modifier.cpp", "max_stars_repo_name": "b1v1r/ironbee", "max_stars_repo_head_hexsha": "97b453afd9c3dc70342c6183a875bde22c9c4a76", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 148.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T01:53:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T20:48:12.000Z", "max_issues_repo_path": "clipp/split_modifier.cpp", "max_issues_repo_name": "ErikHendriks/ironbee", "max_issues_repo_head_hexsha": "97b453afd9c3dc70342c6183a875bde22c9c4a76", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-03-09T15:50:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-10T19:23:06.000Z", "max_forks_repo_path": "clipp/split_modifier.cpp", "max_forks_repo_name": "ErikHendriks/ironbee", "max_forks_repo_head_hexsha": "97b453afd9c3dc70342c6183a875bde22c9c4a76", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2015-03-08T22:45:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T13:47:59.000Z", "avg_line_length": 28.8161290323, "max_line_length": 78, "alphanum_fraction": 0.5702451584, "num_tokens": 1859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.2751297357103299, "lm_q1q2_score": 0.15042392325828102}}
{"text": "\r\n//  Copyright (c) 2011 John Maddock\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_MP_BIG_LANCZOS\r\n#define BOOST_MP_BIG_LANCZOS\r\n\r\n#include <boost/math/bindings/detail/big_lanczos.hpp>\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace lanczos{\r\n\r\ntemplate <class T, class Policy>\r\nstruct lanczos;\r\n\r\ntemplate<class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, class Policy>\r\nstruct lanczos<multiprecision::number<Backend, ExpressionTemplates>, Policy>\r\n{\r\n   typedef typename boost::math::policies::precision<multiprecision::number<Backend, ExpressionTemplates>, Policy>::type precision_type;\r\n   typedef typename mpl::if_c<\r\n      precision_type::value <= 73,\r\n      lanczos13UDT,\r\n      typename mpl::if_c<\r\n         precision_type::value <= 122,\r\n         lanczos22UDT,\r\n         undefined_lanczos\r\n      >::type\r\n   >::type type;\r\n};\r\n\r\n} // namespace lanczos\r\n\r\n}} // namespaces\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "4331a06951e568b45de68eb3ece11cd9009231bd", "size": 1097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/multiprecision/detail/big_lanczos.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/multiprecision/detail/big_lanczos.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/multiprecision/detail/big_lanczos.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 27.425, "max_line_length": 137, "alphanum_fraction": 0.7119416591, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.15042391350953957}}
{"text": "/**\n * Copyright (c) 2017 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#include <algorithm>\n\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include \"math/math.hpp\"\n#include \"math/geometry.hpp\"\n#include \"math/transform.hpp\"\n#include \"imgproc/scanconversion.hpp\"\n#include \"imgproc/binterpolate.hpp\"\n\n#include \"geometry/faceclip.hpp\"\n#include \"geometry/pointindex.hpp\"\n#include \"imgproc/uvpack.hpp\"\n\n#include \"geometry/mesh.hpp\"\n#include \"geometry/meshop.hpp\"\n\n#include \"tileset.hpp\"\n#include \"merge.hpp\"\n#include \"io.hpp\"\n\n#include \"geometry/binmesh.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace va = vtslibs;\nnamespace fs = boost::filesystem;\n\n#ifndef BUILDSYS_CUSTOMER_BUILD\n//#define DEBUG 1 // save debug images\n#endif\n\nnamespace cv {\n\n// comparison operators on cv::Point2 and cv::Point3 for va::PointIndex\ntemplate<typename T>\ninline bool operator< (const Point_<T> &lhs, const Point_<T> &rhs)\n{\n    if (lhs.x != rhs.x) return lhs.x < rhs.x;\n    return lhs.y < rhs.y;\n}\n\ntemplate<typename T>\ninline bool operator< (const Point3_<T> &lhs, const Point3_<T> &rhs)\n{\n    if (lhs.x != rhs.x) return lhs.x < rhs.x;\n    if (lhs.y != rhs.y) return lhs.y < rhs.y;\n    return lhs.z < rhs.z;\n}\n\n} // namespace cv\n\nnamespace vtslibs { namespace vts0 {\n\nnamespace {\n\nconst auto QBufferCvType = CV_16S;\ntypedef signed short QBufferCType;\n\ndouble triangleArea(const math::Point3 &a, const math::Point3 &b,\n                    const math::Point3 &c)\n{\n    return norm_2(math::crossProduct(b - a, c - a)) * 0.5;\n}\n\n//! Returns a trasformation from tile local coordinates to qbuffer coordinates.\n//!\nmath::Matrix4 tileToBuffer(const math::Size2f &tileSize, int bufferSize)\n{\n    math::Matrix4 trafo(ublas::identity_matrix<double>(4));\n    trafo(0,0) = double(bufferSize) / tileSize.width;\n    trafo(1,1) = double(bufferSize) / tileSize.height;\n    trafo(0,3) = trafo(1,3) = double(bufferSize) / 2;\n    return trafo;\n}\n\n//! \"Draws\" all faces of a tile into the qbuffer, i.e., stores the tile's index\n//! everywhere its mesh lies.\n//!\nvoid rasterizeTile(const Tile &tile, const math::Matrix4 &trafo,\n                   int index, cv::Mat &qbuffer)\n{\n    std::vector<imgproc::Scanline> scanlines;\n\n    // draw all faces into the qbuffer\n    for (const auto face : tile.mesh.facets)\n    {\n        cv::Point3f tri[3];\n        for (int i = 0; i < 3; i++) {\n            auto pt(transform(trafo, tile.mesh.vertices[face.v[i]]));\n            tri[i] = {float(pt(0)), float(pt(1)), float(pt(2))};\n        }\n\n        scanlines.clear();\n        imgproc::scanConvertTriangle(tri, 0, qbuffer.rows, scanlines);\n\n        for (const auto& sl : scanlines) {\n            imgproc::processScanline(sl, 0, qbuffer.cols,\n                [&](int x, int y, float)\n                    {\n                        qbuffer.at<QBufferCType>(y, x) = index;\n                    } );\n        }\n    }\n}\n\n//! Calculates tile Inverse Geometry Coarseness, defined as the ratio of mesh area and area\n//! of the covered tile part\n//!\ndouble tileInvGeometryCoarseness(const Tile &tile\n                                 , const math::Size2f &tileSize)\n{\n    // calculate the total area of the faces in both the XYZ and UV spaces\n    double xyzArea(0);\n    const Mesh &mesh(tile.mesh);\n\n    //clip mesh to the tile extents\n    geometry::opencv::ClipTriangle::list triangles;\n    for(auto &face : mesh.facets){\n        triangles.emplace_back( 0, 0,\n                                mesh.vertices[face.v[0]],\n                                mesh.vertices[face.v[1]],\n                                mesh.vertices[face.v[2]],\n                                math::Point2(0,0),\n                                math::Point2(0,0),\n                                math::Point2(0,0));\n    }\n\n    //cut small border of the tile to get rid of the skirts\n    double eps = 0.0001;\n    math::Size2f halfsize(0.5*tileSize.width - tileSize.width*eps\n                          , 0.5*tileSize.height - tileSize.height*eps);\n\n    geometry::opencv::ClipPlane planes[4];\n    planes[0] = {+1.,  0., 0., halfsize.width};\n    planes[1] = {-1.,  0., 0., halfsize.width};\n    planes[2] = { 0., +1., 0., halfsize.height};\n    planes[3] = { 0., -1., 0., halfsize.height};\n\n    for (int i = 0; i < 4; i++) {\n        triangles = geometry::opencv::clipTriangles(triangles, planes[i]);\n    }\n\n    //compute the mesh area from clipped triangles\n    for (const auto &face : triangles)\n    {\n        xyzArea += triangleArea(\n            math::Point3(face.pos[0].x, face.pos[0].y, face.pos[0].z),\n            math::Point3(face.pos[1].x, face.pos[1].y, face.pos[1].z),\n            math::Point3(face.pos[2].x, face.pos[2].y, face.pos[2].z));\n    }\n\n    const int cBSize(512);\n    cv::Mat cbuffer(cBSize, cBSize, CV_32S, cv::Scalar(0));\n\n    math::Matrix4 trafo(tileToBuffer(tileSize, cBSize));\n    rasterizeTile(tile, trafo,1, cbuffer);\n    double coveredArea = static_cast<double>(cv::countNonZero(cbuffer))\n                            /(cBSize*cBSize);\n\n    return coveredArea ? xyzArea/coveredArea : 0;\n}\n\n//! Returns true if x and y are valid column and row indices, respectively.\n//!\nbool validMatPos(int x, int y, const cv::Mat &mat)\n{\n    return x >= 0 && x < mat.cols && y >= 0 && y < mat.rows;\n}\n\n//! Adjusts x and y so that they are valid column and row indices, respectively.\n//!\nvoid clampMatPos(int &x, int &y, const cv::Mat &mat)\n{\n    if (x < 0) x = 0;\n    else if (x >= mat.cols) x = mat.cols-1;\n\n    if (y < 0) y = 0;\n    else if (y >= mat.rows) y = mat.rows-1;\n}\n\ntemplate <int Steps, int Radius>\nvoid close(cv::Mat &mat)\n{\n    auto element\n        (cv::getStructuringElement\n         (cv::MORPH_RECT, { 1 + 2 * Radius, 1 + 2 * Radius }));\n    cv::Mat tmp(mat.size(), mat.type());\n    cv::morphologyEx(mat, tmp, cv::MORPH_CLOSE, element\n                     , { -1, -1 }, Steps, cv::BORDER_REPLICATE);\n    swap(mat, tmp);\n}\n\n//! Returns true if at least one element in the area of the qbuffer\n//! corresponding to the given face belongs to tile number 'index'.\n//!\nbool faceCovered(const Mesh &mesh, const Mesh::Facet &face,\n                 const math::Matrix4 &trafo, int index,\n                 const cv::Mat/*<QBufferCType>*/ &qbuffer)\n{\n    cv::Point3f tri[3];\n    for (int i = 0; i < 3; i++) {\n        auto pt(transform(trafo, mesh.vertices[face.v[i]]));\n        tri[i] = {float(pt(0)), float(pt(1)), float(pt(2))};\n    }\n\n    std::vector<imgproc::Scanline> scanlines;\n    imgproc::scanConvertTriangle(tri, 0, qbuffer.rows, scanlines);\n\n    for (const auto& sl : scanlines) {\n        bool covered(false);\n        imgproc::processScanline(sl, 0, qbuffer.cols, [&](int x, int y, float)\n        {\n            if (qbuffer.at<QBufferCType>(y, x) == index) {\n                covered = true;\n            }\n        });\n        if (covered) { return true; }\n    }\n\n    // do one more check in case the triangle is thinner than one pixel\n    for (int i = 0; i < 3; i++) {\n        int x(round(tri[i].x)), y(round(tri[i].y));\n        clampMatPos(x, y, qbuffer);\n        if (qbuffer.at<QBufferCType>(y, x) == index) { return true; }\n    }\n\n    return false;\n}\n\n//! Draws a face into a matrix. Used to mark useful areas of an atlas.\n//!\nvoid markFace(const geometry::opencv::ClipTriangle &face\n              , cv::Mat/*<char>*/ &mat)\n{\n    cv::Point3f tri[3];\n    for (int i = 0; i < 3; i++) {\n        tri[i] = {face.uv[i].x, face.uv[i].y, 0};\n\n        // make sure the vertices are always marked\n        int x(round(tri[i].x)), y(round(tri[i].y));\n        if (validMatPos(x, y, mat)) {\n            mat.at<char>(y, x) = 1;\n        }\n    }\n\n    std::vector<imgproc::Scanline> scanlines;\n    imgproc::scanConvertTriangle(tri, 0, mat.rows, scanlines);\n\n    for (const auto& sl : scanlines) {\n        imgproc::processScanline(sl, 0, mat.cols,\n            [&](int x, int y, float){ mat.at<char>(y, x) = 1; } );\n    }\n}\n\n//! A wrapper for cv::findContours to solve for the 1-pixel border that the cv\n//! function ignores.\n//!\nvoid findContours(const cv::Mat &mat,\n                  std::vector<std::vector<cv::Point> > &contours)\n{\n    cv::Mat tmp(mat.rows + 2, mat.cols + 2, mat.type(), cv::Scalar(0));\n    cv::Rect rect(1, 1, mat.cols, mat.rows);\n    mat.copyTo(cv::Mat(tmp, rect));\n\n    cv::findContours(tmp, contours, cv::RETR_EXTERNAL\n                     , cv::CHAIN_APPROX_NONE\n                     , cv::Point(-1, -1));\n}\n\n//! Clips faces to tile boundaries.\n//!\nvoid clipFaces(geometry::opencv::ClipTriangle::list &faces\n               , const math::Size2f &tileSize)\n{\n    math::Size2f ts2(tileSize.width / 2.0, tileSize.height / 2.0);\n\n    geometry::opencv::ClipPlane planes[4] = {\n        { 1.,  0., 0., ts2.width},\n        {-1.,  0., 0., ts2.width},\n        { 0.,  1., 0., ts2.height},\n        { 0., -1., 0., ts2.height}\n    };\n\n    for (int i = 0; i < 4; i++) {\n        faces = clipTriangles(faces, planes[i]);\n    }\n}\n\n//! Convert from normalized to pixel-based texture coordinates.\n//!\nimgproc::UVCoord denormalizeUV(const math::Point3d &uv, cv::Size texSize)\n{\n    return {float(uv(0) * texSize.width),\n            //float(texSize.height-1 - uv(1)*texSize.height)\n            float((1.0 - uv(1)) * texSize.height)};\n}\n\n//! Convert from pixel-based to normalized texture coordinates.\n//!\nmath::Point3d normalizeUV(const imgproc::UVCoord &uv, cv::Size texSize)\n{\n    return {double(uv.x) / texSize.width,\n            //(texSize.height-1 - double(uv.y)) / texSize.height,\n            1.0 - double(uv.y) / texSize.height,\n            0.0};\n}\n\n\n// helpers to convert between math points and cv points\ncv::Point3d vertex(const math::Point3d &v)\n    { return {v(0), v(1), v(2)}; }\n\nmath::Point3d vertex(const cv::Point3d &v)\n    { return {v.x, v.y, v.z}; }    \n\ncv::Point2d tCoord(const math::Point2 &t)\n    { return { t(0), t(1)}; }\n\nmath::Point2 tCoord(const cv::Point2d &t)\n    { return {t.x, t.y}; }        \n\n//! Calculate a bounding rectangle of a list of points in the UV space.\n//!\nimgproc::UVRect makeRect(const std::vector<cv::Point> &points)\n{\n    imgproc::UVRect rect;\n    for (const auto &pt : points) {\n        rect.update(imgproc::UVCoord(pt.x, pt.y));\n    }\n    return rect;\n}\n\n//! Finds a UV rectangle containing the given face.\n//!\nunsigned findRect(const geometry::opencv::ClipTriangle &face\n                  , const std::vector<imgproc::UVRect> &rects)\n{\n    const auto &pt(face.uv[0]);\n    for (unsigned i = 0; i < rects.size(); i++)\n    {\n        const imgproc::UVRect &r(rects[i]);\n        const float safety(0.51);\n\n        if (pt.x > (r.min.x - safety) && pt.x < (r.max.x + safety) &&\n            pt.y > (r.min.y - safety) && pt.y < (r.max.y + safety))\n        {\n            return i;\n        }\n    }\n    LOGONCE(err2) << \"Rectangle not found (pt = \" << pt << \").\";\n    return 0;\n}\n\n//! Copies a rectangle from one atlas to another (src -> dst).\n//!\nvoid copyRect(const imgproc::UVRect &rect, const cv::Mat &src, cv::Mat &dst)\n{\n    for (int y = 0; y < rect.height(); y++)\n    for (int x = 0; x < rect.width(); x++)\n    {\n        int sx(rect.x() + x), sy(rect.y() + y);\n        clampMatPos(sx, sy, src);\n\n        int dx(rect.packX + x), dy(rect.packY + y);\n        if (!validMatPos(dx, dy, dst)) continue;\n\n        dst.at<cv::Vec3b>(dy, dx) = src.at<cv::Vec3b>(sy, sx);\n    }\n}\n\n//! Returns a trasformation of the (2x larger) fallback tile so that its given\n//! quadrant aligns with tile of size `tileSize`.\n//!\nmath::Matrix4 quadrantTransform(const math::Size2f &tileSize, int fallbackQuad)\n{\n    math::Matrix4 trafo(ublas::identity_matrix<double>(4));\n    math::Size2f shift(tileSize.width / 2.0, tileSize.height / 2.0);\n\n    switch (fallbackQuad) {\n    case 0: trafo(0,3) = +shift.width, trafo(1,3) = +shift.height; break;\n    case 1: trafo(0,3) = -shift.width, trafo(1,3) = +shift.height; break;\n    case 2: trafo(0,3) = +shift.width, trafo(1,3) = -shift.height; break;\n    case 3: trafo(0,3) = -shift.width, trafo(1,3) = -shift.height; break;\n    }\n    return trafo;\n}\n\nmath::Matrix4 tileTransform(const math::Size2f &dstTileSize\n                            , const math::Point2 dst\n                            , const math::Size2f &srcTileSize\n                            , const math::Point2 src)\n{\n    math::Matrix4 trafo(ublas::identity_matrix<double>(4));\n\n    math::Size2f shiftSrc(srcTileSize.width / 2.0, srcTileSize.height / 2.0);\n    math::Size2f shiftDst(dstTileSize.width / 2.0, dstTileSize.height / 2.0);\n\n    math::Point2 quadrantShift(src - dst);\n\n    trafo(0,3) = shiftSrc.width+quadrantShift(0)-shiftDst.width;\n    trafo(1,3) = shiftSrc.height+quadrantShift(1)-shiftDst.height;\n\n    return trafo;\n}\n\nMergeInput::list sortMergeInput(const MergeInput::list &mergeInput\n                                , const math::Size2f &tileSize)\n{\n    /** Sorts via coarseness. Geometry-based coarsness is computed in lazy way.\n     */\n    struct TileSortInfo {\n        std::size_t id;\n        double coarseness;\n\n        TileSortInfo(std::size_t id, const Tile &tile\n                     , const math::Size2f &tileSize)\n            : id(id), coarseness(tile.metanode.coarseness)\n            , tile_(&tile), tileSize_(tileSize)\n            , invGeometryCoarseness_(-1)\n        {}\n\n        double invGeometryCoarseness() const {\n            if (invGeometryCoarseness_ < 0) {\n                invGeometryCoarseness_\n                    = tileInvGeometryCoarseness(*tile_, tileSize_);\n            }\n            return invGeometryCoarseness_;\n        }\n\n    private:\n        const Tile *tile_;\n        math::Size2f tileSize_;\n        mutable double invGeometryCoarseness_;\n    };\n\n    std::vector<TileSortInfo> sortingInfos;\n    bool sortinvGeometryCoarseness = false;\n    for (unsigned i = 0; i < mergeInput.size(); ++i) {\n        if (mergeInput[i].tile().metanode.coarseness < 0){\n            sortinvGeometryCoarseness = true;\n        }\n        sortingInfos.emplace_back(i, mergeInput[i].tile(), tileSize);\n    }\n\n    auto compareCoarseness\n        ([](const TileSortInfo &a, const TileSortInfo &b) -> bool\n    {\n        // tiles with lower coarseness comes last\n        if (a.coarseness > b.coarseness) {\n            return true;\n        } else if (a.coarseness < b.coarseness) {\n            return false;\n        }\n\n        // fallback if coarsenesses aren't set or are equal\n        return (a.invGeometryCoarseness() < b.invGeometryCoarseness());\n    });\n\n    auto compareinvGeometryCoarseness\n        ([](const TileSortInfo &a, const TileSortInfo &b) -> bool\n    {\n        // tiles with higher geometry quality comes last\n        return (a.invGeometryCoarseness() < b.invGeometryCoarseness());\n    });\n\n    if (sortinvGeometryCoarseness){\n        std::sort(sortingInfos.begin(), sortingInfos.end()\n                  , compareinvGeometryCoarseness);\n    } else{\n        std::sort(sortingInfos.begin(), sortingInfos.end()\n                  , compareCoarseness);\n    }\n\n    MergeInput::list result;\n    for (const auto &tq : sortingInfos) {\n        result.push_back(mergeInput[tq.id]);\n    }\n\n    return result;\n}\n\nMesh removeDuplicateVertexes(geometry::opencv::ClipTriangle::list & faces\n                             , cv::Size atlasSize)\n{\n    Mesh result;\n    geometry::PointIndex<geometry::opencv::ClipTriangle::Point> vindex;\n    geometry::PointIndex<geometry::opencv::ClipTriangle::TCoord> tindex;\n\n    for (const auto &face1 : faces)\n    {\n        result.facets.emplace_back();\n        Mesh::Facet &face2(result.facets.back());\n\n        for (int i = 0; i < 3; i++) {\n            face2.v[i] = vindex.assign(face1.pos[i]);\n            if (unsigned(face2.v[i]) >= result.vertices.size()) {\n                result.vertices.push_back(vertex(face1.pos[i]));\n            }\n\n            face2.t[i] = tindex.assign(face1.uv[i]);\n            if (unsigned(face2.t[i]) >= result.texcoords.size()) {\n                auto uv(normalizeUV(face1.uv[i], atlasSize));\n                result.texcoords.push_back(uv);\n            }\n        }\n    }\n\n    return result;\n}\n\n\nAtlas mergeAtlases( const std::vector<Atlas*> & atlases\n                  , geometry::opencv::ClipTriangle::list & faces\n                    , float inflate = 0)\n{\n    std::vector<cv::Mat> marks;\n    cv::Size safety(1, 1);\n\n    for(uint i=0; i<atlases.size(); ++i){\n        marks.emplace_back(atlases[i]->size() + safety, CV_8U, cv::Scalar(0));\n    }\n    for (const geometry::opencv::ClipTriangle &face : faces) {\n        markFace(face, marks[face.id1]);       \n    }\n\n    // determine UV rectangles that will get repacked\n    std::vector<std::vector<imgproc::UVRect> > rects;\n    for (const auto &m : marks)\n    {\n        std::vector<std::vector<cv::Point> > contours;\n        findContours(m, contours);\n\n        // add one UVRect for each connected component in the mark matrix\n        rects.emplace_back();\n        for (const auto& c : contours) {\n            rects.back().push_back(makeRect(c));\n        }\n\n#if DEBUG\n        cv::Mat dbg(m.size(), CV_8UC3, cv::Scalar(0,0,0));\n        for (const auto &c : contours) {\n            cv::Vec3b color(rand() % 256, rand() % 256, rand() % 256);\n            for (const cv::Point &pt : c) {\n                dbg.at<cv::Vec3b>(pt.y, pt.x) = color;\n            }\n        }\n        static int idx = 0;\n        auto filename(str(boost::format(\"merge%03d.png\") % (idx++)));\n        cv::imwrite(filename, dbg);\n#endif\n    }\n\n    // recalculate the rectangles directly from face UVs for subpixel precision\n    for (auto &face : faces) {\n        face.id2 = findRect(face, rects[face.id1]);\n    }\n    for (auto &rlist : rects) {\n        for (auto &r : rlist)\n            r.clear();\n    }\n    for (const auto &face : faces) {\n        for (int i = 0; i < 3; i++)\n            rects[face.id1][face.id2].update(face.uv[i]);\n    }\n\n    //inflate rectangles\n    if(inflate>0){\n        for (auto &rlist : rects) {\n            for (auto &r : rlist)\n                r.inflate(inflate);\n        }\n    }\n\n    // pack the rectangles\n    imgproc::RectPacker packer;\n    for (auto &rlist : rects) {\n        for (auto &r : rlist)\n            packer.addRect(&r);\n    }\n    packer.pack();\n\n    // copy rectangles to final atlas\n    cv::Mat atlas(packer.height(), packer.width(), CV_8UC3, cv::Scalar(0,0,0));\n    for (unsigned i = 0; i < atlases.size(); i++) {\n        for (const auto &rect : rects[i]) {\n            // TODO: mask out pixels that are not needed!\n            copyRect(rect, *atlases[i], atlas);\n        }\n    }\n\n    // adjust face UVs to point to the new atlas\n    for (auto &face : faces) {\n        for (int i = 0; i < 3; i++)\n            rects[face.id1][face.id2].adjustUV(face.uv[i]);\n    }\n\n    return atlas;\n}\n\nint sameIndices(const cv::Mat &qbuffer)\n{\n    int index = -1;\n    for (auto it = qbuffer.begin<QBufferCType>();\n         it != qbuffer.end<QBufferCType>(); ++it)\n    {\n        const auto value(*it);\n        if (value < 0) { continue; }\n        if (value != index) {\n            if (index < 0) {\n                index = value;\n            } else {\n                return -1;\n            }\n        }\n    }\n    return index;\n}\n\n//! Returns true if 'qbuffer' contains at least one element equal to 'index'.\n//!\nbool haveIndices(const cv::Mat &qbuffer, int index)\n{\n    for (auto it = qbuffer.begin<QBufferCType>();\n         it != qbuffer.end<QBufferCType>(); ++it)\n    {\n        if (*it == index) return true;\n    }\n    return false;\n}\n\n//! Bilinearly upsamples the specified quadrant of the fallback tile heightmap.\n//!\nvoid getFallbackHeightmap(const Tile &fallback, int fallbackQuad,\n                          float heightmap[MetaNode::HMSize][MetaNode::HMSize])\n{\n    const int hms(MetaNode::HMSize);\n\n    double x(0.), y(0.);\n    if (fallbackQuad & 1) x += double(hms - 1)*0.5;\n    if (fallbackQuad & 2) y += double(hms - 1)*0.5;\n\n    for (int i = 0; i < hms; i++)\n    for (int j = 0; j < hms; j++)\n    {\n        math::Point2 point(x + 0.5*j, y + 0.5*i);\n        heightmap[i][j] = 0;\n        imgproc::bilinearInterpolate(\n                   (float*) fallback.metanode.heightmap, hms, hms, hms, 1,\n                   point, &heightmap[i][j]);\n    }\n}\n\nMergeInput clipQuad( const MergeInput & mergeInput, int fallbackQuad\n                     , const math::Size2f &tileSize)\n{\n\n    math::Matrix4 shift = quadrantTransform(tileSize, fallbackQuad);\n    const Tile &tile(mergeInput.tile());\n    const Mesh &mesh(tile.mesh);\n    cv::Size asize(tile.atlas.size());\n    asize.width *= 2;\n    asize.height *= 2;\n\n    geometry::opencv::ClipTriangle::list faces;\n    for (unsigned j = 0; j < mesh.facets.size(); j++) {\n        const Mesh::Facet &face(mesh.facets[j]);\n        faces.emplace_back(0,0,\n                vertex(transform(shift,mesh.vertices[face.v[0]])),\n                vertex(transform(shift,mesh.vertices[face.v[1]])),\n                vertex(transform(shift,mesh.vertices[face.v[2]])),\n                denormalizeUV(mesh.texcoords[face.t[0]], asize),\n                denormalizeUV(mesh.texcoords[face.t[1]], asize),\n                denormalizeUV(mesh.texcoords[face.t[2]], asize));\n    }\n    clipFaces(faces, tileSize); \n    \n    Atlas atlas(asize.height, asize.width, tile.atlas.type());\n    cv::resize( tile.atlas, atlas, atlas.size()\n              , 0, 0, cv::INTER_LANCZOS4);\n\n\n    std::vector<Atlas*> usedAtlases;\n    usedAtlases.push_back(&atlas);\n    \n    Tile resultTile;\n    resultTile.atlas = mergeAtlases(usedAtlases, faces, 2);\n    resultTile.mesh = removeDuplicateVertexes(faces, resultTile.atlas.size());\n    resultTile.metanode = tile.metanode;\n    getFallbackHeightmap(tile, fallbackQuad, resultTile.metanode.heightmap);\n\n    return { resultTile, &mergeInput.tileSet()\n           , mergeInput.tileId(), mergeInput.srcFaceCount() };\n}\n\n} // namespace\n\n//! Merges several tiles. The process has four phases:\n//!\n//! 1. AncestorTiles are clipped and transformed according to 'quad'.\n//!    The meshes of all tiles are rasterized into a buffer which determines \n//!    the source of geometry at each point of the result. The tiles are \n//!    rasterized from worst to best (in terms of their geometry quality). \n//!    This means that the best tile will be complete in the result and only \n//!    the remaining space will be filled with other tiles.\n//!\n//! 2. Faces that will appear in the output are collected, according to the\n//!    contents of the buffer. A face from a tile is used if at least one\n//!    underlying element of the qbuffer indicates that the tile should be used\n//!    at that place.\n//!\n//! 3. Pixels in atlases that are needed by the collected faces are marked.\n//!    Rectangles that cover the marked areas are identified and then repacked\n//!    into a single new atlas.\n//!\n//! 4. The isolated faces are converted into a standard mesh with vertices and\n//!    texture vertices that don't repeat.\n//!\nMergedTile merge( const TileId &tileId, const math::Size2f &tileSize\n                , const MergeInput::list &mergeInput\n                , int quad\n                , const MergeInput::list &ancestorTiles\n                , MergeInput::list &incidentTiles)\n{\n    LOG(info2)<<\"Merging tile \"<<tileId<<\" from \"<<mergeInput.size()<<\" sets\";\n\n    // sort tiles by quality\n    auto sortedMergeInput = sortMergeInput(mergeInput, tileSize);\n    // create qbuffer, rasterize meshes in increasing order of quality\n    const int QBSize(512);\n    cv::Mat qbuffer(QBSize, QBSize, QBufferCvType, cv::Scalar(-1));\n    math::Matrix4 trafo(tileToBuffer(tileSize, QBSize));\n\n    std::set<const TileSet*> mergedTileSetMap;\n    for (const auto &mi : sortedMergeInput) {\n        mergedTileSetMap.insert(&mi.tileSet());\n    }\n\n    incidentTiles.clear();\n    //clip and repack ancestor tiles\n    for (const auto &fb : ancestorTiles){\n        if (mergedTileSetMap.find(&fb.tileSet()) == mergedTileSetMap.end()) {\n            MergeInput mi = clipQuad(fb, quad, tileSize);\n            if (!mi.tile().mesh.facets.empty()) {\n                incidentTiles.push_back(mi);\n            }\n        }\n    }\n    incidentTiles.insert(incidentTiles.end(), sortedMergeInput.begin()\n                         , sortedMergeInput.end());\n\n    for (uint i = 0; i<incidentTiles.size(); ++i) {\n        rasterizeTile(incidentTiles[i].tile(), trafo, i, qbuffer);\n    }\n\n    // close small areas of bad stuff with good stuff\n    close<1, 6>(qbuffer);\n\n    int index(sameIndices(qbuffer));\n    if (index > -1) {\n        return { incidentTiles[index].tile(), incidentTiles[index].tileSet() };\n    }\n\n    std::vector<Atlas*> usedAtlases;\n    geometry::opencv::ClipTriangle::list mergedFaces;\n    const int hms(MetaNode::HMSize);\n    float minGsd = std::numeric_limits<float>::max();\n    float heightmap[hms][hms];\n    cv::Mat hmask(hms, hms, CV_32S, cv::Scalar(0));\n\n    // result tile\n    MergedTile result;\n\n    for(int i=incidentTiles.size() - 1; i>=0; --i) {\n        if(haveIndices(qbuffer,i)){\n\n            const Tile &tile(incidentTiles[i].tile());\n            cv::Size asize(tile.atlas.size());\n\n            geometry::Obj mesh = tile.mesh;\n\n            //refine mesh if necessary\n            if (incidentTiles[i].srcFaceCount() > tile.mesh.facets.size()) {\n                // tile has been clipped -> refine\n                auto cmesh = *geometry::asMesh(mesh);\n                auto rmesh(geometry::refine( cmesh\n                                       , incidentTiles[i].srcFaceCount()));\n                mesh = geometry::asObj(rmesh);\n            }\n\n            usedAtlases.emplace_back(&incidentTiles[i].tile().atlas);\n            for (unsigned j = 0; j < mesh.facets.size(); j++) {\n                const Mesh::Facet &face(mesh.facets[j]);\n                if (faceCovered(mesh, face, trafo, i, qbuffer)) {\n                    mergedFaces.emplace_back(usedAtlases.size()-1,0,\n                            vertex(mesh.vertices[face.v[0]]),\n                            vertex(mesh.vertices[face.v[1]]),\n                            vertex(mesh.vertices[face.v[2]]),\n                            denormalizeUV(mesh.texcoords[face.t[0]], asize),\n                            denormalizeUV(mesh.texcoords[face.t[1]], asize),\n                            denormalizeUV(mesh.texcoords[face.t[2]], asize) );\n                }\n            }\n\n            //update metadata\n            minGsd = std::min(tile.metanode.gsd, minGsd);\n            for (int c = 0; c < hms; c++)\n            for (int r = 0; r < hms; r++)\n            {\n                int what = qbuffer.at<QBufferCType>( c * (QBSize-1) / hms\n                                                     , r * (QBSize-1) / hms);\n                if(what==i || hmask.at<int>(c,r)==0){\n                    hmask.at<int>(c,r)=1;\n                    heightmap[c][r] = tile.metanode.heightmap[c][r];\n                }\n            }\n\n            // remember tile's set as origin of this tile\n            result.sources.push_back(&incidentTiles[i].tileSet());\n        }\n    }\n\n    // almost done\n    result.atlas = mergeAtlases(usedAtlases, mergedFaces);\n    result.mesh = removeDuplicateVertexes(mergedFaces, result.atlas.size());\n\n    if(sortedMergeInput.size()>0){\n        result.metanode = sortedMergeInput.front().tile().metanode;\n    }\n\n    result.metanode.gsd = minGsd;\n    //coarseness is not used after merge - set to invalid value\n    result.metanode.coarseness = -1;\n\n    // copy heightmap\n    std::copy(&heightmap[0][0], &heightmap[hms - 1][hms]\n              , &result.metanode.heightmap[0][0]);\n\n    return result;\n}\n\nboost::optional<double> MergedTile::pixelSize() const\n{\n    // pixel size is valid only when tile is from single source and has valid\n    // pixelsize\n    if (singleSource() && metanode.exists()) {\n        return metanode.pixelSize[0][0];\n    }\n    return boost::none;\n}\n\n} } // namespace vtslibs::vts0\n", "meta": {"hexsha": "26bcc37525a1062b24782f995adb4171b6613bf4", "size": 29013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vts-libs/vts0/merge.cpp", "max_stars_repo_name": "melowntech/vts-libs", "max_stars_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-20T01:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T06:54:51.000Z", "max_issues_repo_path": "vts-libs/vts0/merge.cpp", "max_issues_repo_name": "melowntech/vts-libs", "max_issues_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T15:21:29.000Z", "max_forks_repo_path": "vts-libs/vts0/merge.cpp", "max_forks_repo_name": "melowntech/vts-libs", "max_forks_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:10:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:10:07.000Z", "avg_line_length": 32.9318955732, "max_line_length": 91, "alphanum_fraction": 0.5872539896, "num_tokens": 7817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.15042390944561018}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/DataBox/PrefixHelpers.hpp\"\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Evolution/DgSubcell/Tags/Inactive.hpp\"\n#include \"Evolution/DgSubcell/Tags/Mesh.hpp\"\n#include \"Evolution/DgSubcell/Tags/NeighborData.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/FiniteDifference/Reconstructor.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/Tags.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Tags.hpp\"\n#include \"PointwiseFunctions/Hydro/Tags.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// \\cond\nclass DataVector;\ntemplate <size_t Dim>\nclass Direction;\ntemplate <size_t Dim>\nclass Element;\ntemplate <size_t Dim>\nclass ElementId;\nnamespace EquationsOfState {\ntemplate <bool IsRelativistic, size_t ThermodynamicDim>\nclass EquationOfState;\n}  // namespace EquationsOfState\ntemplate <size_t Dim>\nclass Mesh;\nnamespace gsl {\ntemplate <typename T>\nclass not_null;\n}  // namespace gsl\nnamespace PUP {\nclass er;\n}  // namespace PUP\ntemplate <typename TagsList>\nclass Variables;\n/// \\endcond\n\nnamespace grmhd::ValenciaDivClean::fd {\n/*!\n * \\brief Monotised central reconstruction. See\n * ::fd::reconstruction::monotised_central() for details.\n */\nclass MonotisedCentralPrim : public Reconstructor {\n private:\n  using prims_to_reconstruct_tags =\n      tmpl::list<hydro::Tags::RestMassDensity<DataVector>,\n                 hydro::Tags::Pressure<DataVector>,\n                 hydro::Tags::LorentzFactorTimesSpatialVelocity<DataVector, 3>,\n                 hydro::Tags::MagneticField<DataVector, 3>,\n                 hydro::Tags::DivergenceCleaningField<DataVector>>;\n\n public:\n  static constexpr size_t dim = 3;\n\n  using options = tmpl::list<>;\n  static constexpr Options::String help{\n      \"Monotised central reconstruction scheme using primitive variables.\"};\n\n  MonotisedCentralPrim() = default;\n  MonotisedCentralPrim(MonotisedCentralPrim&&) = default;\n  MonotisedCentralPrim& operator=(MonotisedCentralPrim&&) = default;\n  MonotisedCentralPrim(const MonotisedCentralPrim&) = default;\n  MonotisedCentralPrim& operator=(const MonotisedCentralPrim&) = default;\n  ~MonotisedCentralPrim() override = default;\n\n  explicit MonotisedCentralPrim(CkMigrateMessage* msg);\n\n  WRAPPED_PUPable_decl_base_template(Reconstructor, MonotisedCentralPrim);\n\n  auto get_clone() const -> std::unique_ptr<Reconstructor> override;\n\n  void pup(PUP::er& p) override;\n\n  size_t ghost_zone_size() const override { return 2; }\n\n  using reconstruction_argument_tags = tmpl::list<\n      ::Tags::Variables<hydro::grmhd_tags<DataVector>>,\n      hydro::Tags::EquationOfStateBase, domain::Tags::Element<dim>,\n      evolution::dg::subcell::Tags::NeighborDataForReconstruction<dim>,\n      evolution::dg::subcell::Tags::Mesh<dim>>;\n\n  template <size_t ThermodynamicDim, typename TagsList>\n  void reconstruct(\n      gsl::not_null<std::array<Variables<TagsList>, dim>*> vars_on_lower_face,\n      gsl::not_null<std::array<Variables<TagsList>, dim>*> vars_on_upper_face,\n      const Variables<hydro::grmhd_tags<DataVector>>& volume_prims,\n      const EquationsOfState::EquationOfState<true, ThermodynamicDim>& eos,\n      const Element<dim>& element,\n      const FixedHashMap<\n          maximum_number_of_neighbors(dim),\n          std::pair<Direction<dim>, ElementId<dim>>, std::vector<double>,\n          boost::hash<std::pair<Direction<dim>, ElementId<dim>>>>&\n          neighbor_data,\n      const Mesh<dim>& subcell_mesh) const;\n\n  /// Called by an element doing DG when the neighbor is doing subcell.\n  template <size_t ThermodynamicDim, typename TagsList>\n  void reconstruct_fd_neighbor(\n      gsl::not_null<Variables<TagsList>*> vars_on_face,\n      const Variables<hydro::grmhd_tags<DataVector>>& subcell_volume_prims,\n      const EquationsOfState::EquationOfState<true, ThermodynamicDim>& eos,\n      const Element<dim>& element,\n      const FixedHashMap<\n          maximum_number_of_neighbors(dim),\n          std::pair<Direction<dim>, ElementId<dim>>, std::vector<double>,\n          boost::hash<std::pair<Direction<dim>, ElementId<dim>>>>&\n          neighbor_data,\n      const Mesh<dim>& subcell_mesh,\n      const Direction<dim> direction_to_reconstruct) const;\n};\n\nbool operator==(const MonotisedCentralPrim& /*lhs*/,\n                const MonotisedCentralPrim& /*rhs*/);\n\nbool operator!=(const MonotisedCentralPrim& lhs,\n                const MonotisedCentralPrim& rhs);\n}  // namespace grmhd::ValenciaDivClean::fd\n", "meta": {"hexsha": "2c72838a35a070e0752ad2e6164022e6b6466d50", "size": 4869, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/GrMhd/ValenciaDivClean/FiniteDifference/MonotisedCentral.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/Evolution/Systems/GrMhd/ValenciaDivClean/FiniteDifference/MonotisedCentral.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/Evolution/Systems/GrMhd/ValenciaDivClean/FiniteDifference/MonotisedCentral.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": 36.0666666667, "max_line_length": 86, "alphanum_fraction": 0.7383446293, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2845760163515857, "lm_q1q2_score": 0.15006163557972502}}
{"text": "/*\n * Copyright 2021 IBM Corporation\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 <SPL/Runtime/Common/RuntimeDebugAspect.h>\n#include <SPL/Runtime/ProcessingElement/ElasticThreadAdapter.h>\n#include <TRC/DistilleryDebug.h>\n\n#include <boost/thread/thread.hpp>\n\n#include <cmath>\n#include <fstream>\n\nusing namespace SPL;\n\nconst int32_t NOISE_LIMIT = 5;\nconst double THROUGHPUT_TOLERANCE = 0.05;\nconst double MAX_USAGE = 0.8;\nconst double LOAD_CHANGE_SENSITIVITY = 0.2;\n\nElasticThreadAdapter::ElasticThreadAdapter()\n  : _belowLevel(0)\n  , _currLevel(0)\n  , _aboveLevel(0)\n  , _minLevel(0)\n  , _maxLevel(0)\n  , _time(0)\n  , _noiseDetector(NOISE_LIMIT)\n  , _changeSensitivity(THROUGHPUT_TOLERANCE)\n{\n    APPTRC(L_INFO, \"ElasticThreadAdapter: throughput change tolerance: \" << _changeSensitivity,\n           SPL_PE_DBG);\n}\n\nvoid ElasticThreadAdapter::initialize(uint32_t minThreads,\n                                      uint32_t maxThreads,\n                                      uint32_t activeThreads)\n{\n    _threadInfos.clear();\n\n    // we're assuming that the PE did sanity checks on these values already\n    _minLevel = minThreads;\n    _currLevel = activeThreads;\n    _maxLevel = maxThreads;\n    _belowLevel = activeThreads / 2;\n    _aboveLevel = activeThreads * 2;\n\n    // 0 counts as a level, starts at 1\n    for (uint32_t i = 0; i < _aboveLevel + 1; ++i) {\n        _threadInfos.push_back(ThreadInfo());\n    }\n\n    // for the \"out of bounds\" levels, say they are trusted, but have zero throughput\n    for (uint32_t i = 0; i < _minLevel; ++i) {\n        _threadInfos.at(i).trusted = true;\n        _threadInfos.at(i).firstThroughput = 0;\n        _threadInfos.at(i).lastThroughput = 0;\n    }\n\n    for (uint32_t i = _maxLevel; i < _aboveLevel + 1; ++i) {\n        _threadInfos.at(i).trusted = true;\n        _threadInfos.at(i).firstThroughput = 0;\n        _threadInfos.at(i).lastThroughput = 0;\n    }\n}\n\nElasticThreadAdapter::~ElasticThreadAdapter() {}\n\nElasticThreadAdapter::LoadChange ElasticThreadAdapter::pingNoiseDetector(\n  ElasticThreadAdapter::LoadChange direction)\n{\n    if (_noiseDetector > 0) {\n        _noiseDetector--;\n        APPTRC(L_DEBUG, \"set off noise detector, \" << _noiseDetector << \" remaining.\", SPL_PE_DBG);\n        return PotentialNoise;\n    } else {\n        return direction;\n    }\n}\n\nElasticThreadAdapter::LoadChange ElasticThreadAdapter::checkForChangeInLoadBasedOnThroughput(\n  double throughput)\n{\n    // Obviously, if t=0, we can't have a load change. But why t=1? The reason is that the\n    // first throughput sample tends to be too high. It counts all of the queues filling up\n    // as real throughput, but that's much higher than our steady-state throughput.\n    if (_time == 0 || _time == 1) {\n        return UnknownLoadChange;\n    }\n\n    if (!_threadInfos.at(_currLevel).trusted) {\n        return UnknownLoadChange;\n    }\n\n    ThreadInfo* ti = &_threadInfos.at(_currLevel);\n\n    // we were were here the last time, but throughput changed\n    if (ti->lastTime == _time - 1) {\n        double oldThroughput = ti->firstThroughput;\n        double throughputDiff = throughput - oldThroughput;\n        if (throughputDiff < 0.0) {\n            if (-throughputDiff > LOAD_CHANGE_SENSITIVITY * throughput) {\n                APPTRC(L_DEBUG, \"less load\", SPL_PE_DBG);\n                return pingNoiseDetector(LessLoad);\n            }\n        } else {\n            if (throughputDiff > LOAD_CHANGE_SENSITIVITY * oldThroughput) {\n                APPTRC(L_DEBUG, \"more load\", SPL_PE_DBG);\n                return pingNoiseDetector(MoreLoad);\n            }\n        }\n    }\n\n    _noiseDetector = NOISE_LIMIT;\n    return UnknownLoadChange;\n}\n\nvoid ElasticThreadAdapter::untrustOtherData(double throughput)\n{\n    APPTRC(L_DEBUG, \"change in throughput, untrusting all the data\", SPL_PE_DBG);\n    for (size_t i = _minLevel; i < _threadInfos.size(); ++i) {\n        _threadInfos.at(i).trusted = false;\n    }\n}\n\nvoid ElasticThreadAdapter::untrustAbove()\n{\n    for (size_t i = _currLevel + 1; i < _threadInfos.size(); ++i) {\n        _threadInfos.at(i).trusted = false;\n    }\n}\n\nvoid ElasticThreadAdapter::untrustLevel(uint32_t level, double t)\n{\n    _threadInfos.at(level).firstThroughput = t;\n    _threadInfos.at(level).lastTime = _time;\n}\n\nbool ElasticThreadAdapter::trustBelow()\n{\n    if (_currLevel == _minLevel) {\n        return false;\n    }\n    if (_threadInfos.at(_belowLevel).trusted) {\n        APPTRC(L_DEBUG, \"trust below\", SPL_PE_DBG);\n    }\n    return _threadInfos.at(_belowLevel).trusted;\n}\n\nbool ElasticThreadAdapter::trustAbove()\n{\n    if (_currLevel == _threadInfos.size() - 1) {\n        return false;\n    }\n    if (_threadInfos.at(_aboveLevel).trusted) {\n        APPTRC(L_DEBUG, \"trust above; \" << _aboveLevel, SPL_PE_DBG);\n    }\n    return _threadInfos.at(_aboveLevel).trusted;\n}\n\nbool ElasticThreadAdapter::improvementTrendBelow(double throughput)\n{\n    if (_currLevel == 1) {\n        return false;\n    }\n\n    ThreadInfo& pci = _threadInfos.at(_belowLevel);\n    if (!pci.trusted) {\n        return false;\n    }\n\n    if ((throughput > pci.lastThroughput) &&\n        (throughput - pci.lastThroughput) > _changeSensitivity * pci.lastThroughput) {\n        APPTRC(L_DEBUG, \"improvement trend below: \" << pci.lastThroughput << \" -> \" << throughput,\n               SPL_PE_DBG);\n        return true;\n    }\n\n    return false;\n}\n\nbool ElasticThreadAdapter::improvementTrendAbove(double throughput)\n{\n    ThreadInfo& nci = _threadInfos.at(_aboveLevel);\n    if (!nci.trusted) {\n        return false;\n    }\n\n    if ((nci.lastThroughput > throughput) &&\n        (nci.lastThroughput - throughput) > _changeSensitivity * throughput) {\n        APPTRC(L_DEBUG, \"improvement trend above: \" << throughput << \" -> \" << nci.lastThroughput,\n               SPL_PE_DBG);\n        return true;\n    }\n    return false;\n}\n\nvoid ElasticThreadAdapter::decreaseLevel()\n{\n    if (_currLevel > _minLevel) {\n        APPTRC(L_DEBUG, \"decreasing level\", SPL_PE_DBG);\n        if (_currLevel > 3) {\n            _aboveLevel = _currLevel;\n            uint32_t belowPow2 =\n              static_cast<uint32_t>(::exp2(std::ceil(::log2(static_cast<double>(_currLevel)) - 1)));\n            uint32_t abovePow2 = belowPow2 * 2;\n            uint32_t pow2Counter = belowPow2 / 2;\n            uint32_t oldLevel = _currLevel;\n            for (uint32_t i = abovePow2 - (belowPow2 / 2); i > belowPow2; i -= pow2Counter) {\n                if (i <= _minLevel) {\n                    _currLevel = _minLevel;\n                    break;\n                }\n                _currLevel = i;\n                pow2Counter = std::max(1u, pow2Counter / 2);\n                if (i < oldLevel && !_threadInfos.at(i).trusted) {\n                    _belowLevel = belowPow2;\n                    break;\n                }\n            }\n\n            if (_currLevel == belowPow2 + 1) {\n                if (!_threadInfos.at(belowPow2 + 1).trusted) {\n                    if (belowPow2 >= _minLevel) {\n                        _belowLevel = belowPow2;\n                        _currLevel = belowPow2 + 1;\n                    } else {\n                        _belowLevel = _minLevel - 1;\n                        _currLevel = _minLevel;\n                    }\n                } else {\n                    if (belowPow2 >= _minLevel) {\n                        _belowLevel = belowPow2 / 2;\n                        _currLevel = belowPow2;\n                    } else {\n                        _belowLevel = _minLevel - 1;\n                        _currLevel = _minLevel;\n                    }\n                }\n            }\n        } else if (_currLevel == 3) {\n            if (_minLevel <= 2) {\n                _belowLevel = 1;\n                _currLevel = 2;\n                _aboveLevel = 3;\n            }\n        } else { // _currLevel must be 2\n            if (_minLevel == 1) {\n                _belowLevel = 0;\n                _currLevel = 1;\n                _aboveLevel = 2;\n            }\n        }\n    }\n}\n\nvoid ElasticThreadAdapter::increaseLevel()\n{\n    if (_currLevel < _maxLevel) {\n        APPTRC(L_DEBUG, \"increasing level\", SPL_PE_DBG);\n        _belowLevel = _currLevel;\n        uint32_t abovePow2 =\n          2 * static_cast<uint32_t>(::exp2(std::floor(::log2(static_cast<double>(_currLevel)))));\n\n        if (_threadInfos.at(_aboveLevel).trusted) {\n            // if we trust the level above, then we must have been allowed to visit it before, which\n            // means it must be under our maxLevel, so we don't need to check maxLevel\n            _currLevel = _aboveLevel;\n            if (abovePow2 > _threadInfos.size()) {\n                _aboveLevel = abovePow2;\n            } else if (abovePow2 == _aboveLevel) {\n                _aboveLevel = abovePow2 * 2;\n            } else {\n                for (uint32_t i = _currLevel + 1; i < abovePow2 + 1; ++i) {\n                    _aboveLevel = i;\n                    if (_threadInfos.at(i).trusted) {\n                        break;\n                    }\n                }\n            }\n        } else if (_currLevel > 2) {\n            if (abovePow2 <= _maxLevel) {\n                _currLevel = abovePow2;\n                _aboveLevel = abovePow2 * 2;\n            } else {\n                _currLevel = _maxLevel;\n                _aboveLevel = _maxLevel + 1;\n            }\n        } else {\n            if (_currLevel * 2 <= _maxLevel) {\n                _currLevel = _currLevel * 2;\n                _aboveLevel = _aboveLevel * 2;\n            } else {\n                _currLevel = _maxLevel;\n                _aboveLevel = _maxLevel + 1;\n            }\n        }\n\n        if (_aboveLevel >= _threadInfos.size()) {\n            while (_threadInfos.size() < _aboveLevel + 1) {\n                _threadInfos.push_back(ThreadInfo());\n            }\n        }\n    }\n}\n\nElasticThreadAdapter::CPUStat ElasticThreadAdapter::getCPUStat()\n{\n    std::ifstream stat(\"/proc/stat\");\n    if (!stat) {\n        APPTRC(L_ERROR, \"error opening /proc/stat\", SPL_PE_DBG);\n        return CPUStat();\n    }\n\n    std::string cpu;\n    CPUStat usage;\n    stat >> cpu >> usage;\n    if (!stat) {\n        APPTRC(L_ERROR, \"error reading /proc/stat\", SPL_PE_DBG);\n        return CPUStat();\n    }\n    return usage;\n}\n\nbool ElasticThreadAdapter::isCPUUsageAcceptable()\n{\n    CPUStat currStat = getCPUStat();\n    if (currStat.isDefault()) {\n        // error reading /proc/stat, assume the worst\n        return false;\n    }\n\n    if (_lastStat.isDefault()) {\n        _lastStat = currStat;\n        // say no until we get some data\n        return false;\n    }\n\n    CPUStat diff = currStat - _lastStat;\n    _lastStat = currStat;\n    APPTRC(L_DEBUG, \"cpu usage: \" << diff.usage(), SPL_PE_DBG);\n    return diff.usage() <= MAX_USAGE;\n}\n\nuint32_t ElasticThreadAdapter::calculateThreads(double throughput, bool& loadChanged)\n{\n    switch (checkForChangeInLoadBasedOnThroughput(throughput)) {\n        case PotentialNoise:\n            return _currLevel;\n        case LessLoad:\n        case MoreLoad:\n            loadChanged = true;\n            _noiseDetector = NOISE_LIMIT;\n            untrustOtherData(throughput);\n            _time = 0;\n            return _currLevel;\n            break;\n        default:;\n    }\n\n    // update info for the current channel\n    ThreadInfo& ti = _threadInfos.at(_currLevel);\n    ti.lastTime = _time++;\n    ti.lastThroughput = throughput;\n    if (!ti.trusted) {\n        ti.firstThroughput = throughput;\n    }\n    ti.trusted = true;\n\n    if (((improvementTrendBelow(throughput) && !trustAbove()) ||\n         improvementTrendAbove(throughput) || (_currLevel == _minLevel && !trustAbove()))) {\n        if (isCPUUsageAcceptable()) {\n            increaseLevel();\n        }\n    } else if (!trustBelow() || !improvementTrendBelow(throughput)) {\n        decreaseLevel();\n    }\n\n    return _currLevel;\n}\n", "meta": {"hexsha": "439a33779bfe92205a6d2e37dfd31c89507bc2b2", "size": 12289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/SPL/Runtime/ProcessingElement/ElasticThreadAdapter.cpp", "max_stars_repo_name": "IBMStreams/OSStreams", "max_stars_repo_head_hexsha": "c6287bd9ec4323f567d2faf59125baba8604e1db", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-02-19T20:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T05:11:50.000Z", "max_issues_repo_path": "src/cpp/SPL/Runtime/ProcessingElement/ElasticThreadAdapter.cpp", "max_issues_repo_name": "xguerin/openstreams", "max_issues_repo_head_hexsha": "7000370b81a7f8778db283b2ba9f9ead984b7439", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T01:17:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-08T14:56:34.000Z", "max_forks_repo_path": "src/cpp/SPL/Runtime/ProcessingElement/ElasticThreadAdapter.cpp", "max_forks_repo_name": "IBMStreams/OSStreams", "max_forks_repo_head_hexsha": "c6287bd9ec4323f567d2faf59125baba8604e1db", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T18:43:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T14:18:16.000Z", "avg_line_length": 31.2697201018, "max_line_length": 100, "alphanum_fraction": 0.5829603711, "num_tokens": 3071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.15006163238021644}}
{"text": "/* (c) 2016, 2021 FFF Services. For details refers to LICENSE.txt */\n#include <graphene/chain/decent_evaluator.hpp>\n#include <graphene/chain/protocol/decent.hpp>\n#include <graphene/chain/hardfork.hpp>\n#include <graphene/chain/database.hpp>\n#include <graphene/chain/seeder_object.hpp>\n#include <graphene/chain/exceptions.hpp>\n#include <graphene/chain/hardfork.hpp>\n#include <graphene/chain/account_object.hpp>\n#include <graphene/chain/asset_object.hpp>\n#include <graphene/chain/buying_object.hpp>\n#include <graphene/chain/seeder_object.hpp>\n#include <graphene/chain/content_object.hpp>\n#include <graphene/chain/subscription_object.hpp>\n#include <graphene/chain/seeding_statistics_object.hpp>\n#include <graphene/chain/transaction_detail_object.hpp>\n\n#include <decent/encrypt/custodyutils.hpp>\n#include <decent/encrypt/encryptionutils.hpp>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace graphene { namespace chain {\n\nnamespace {\n\nstatic decent::encrypt::CustodyUtils _custody_utils;\n\nvoid content_payout(database& db, asset paid_price_after_exchange, const content_object& content){\n   if( content.co_authors.empty() )\n      db.adjust_balance( content.author, paid_price_after_exchange );\n   else\n   {\n      asset price = paid_price_after_exchange;\n      boost::multiprecision::int128_t price_for_co_author;\n      for( auto const &element : content.co_authors )\n      {\n         price_for_co_author = ( paid_price_after_exchange.amount.value * element.second ) / 10000ll ;\n         db.adjust_balance( element.first, asset( static_cast<share_type>(price_for_co_author), price.asset_id) );\n         price.amount -= price_for_co_author;\n      }\n\n      if( price.amount != 0 ) {\n         FC_ASSERT( price.amount > 0 );\n         db.adjust_balance(content.author, price);\n      }\n   }\n};\n\n}\n\noperation_result set_publishing_manager_evaluator::do_evaluate( const operation_type& o )\n{try{\n   for( const auto id : o.to )\n      FC_ASSERT (db().find_object(id), \"Account does not exist\");\n   FC_ASSERT( o.from == account_id_type(15) , \"This operation is permitted only to DECENT account\");\n\n   return void_result();\n}FC_CAPTURE_AND_RETHROW( (o) ) }\n\noperation_result set_publishing_manager_evaluator::do_apply( const operation_type& o )\n{try{\n   for( auto to_id : o.to )\n   {\n      const account_object& to_acc = to_id(db());\n\n      if( o.can_create_publishers == true ) {\n         db().modify<account_object>(to_acc, [](account_object &ao) {\n              ao.rights_to_publish.is_publishing_manager = true;\n\n         });\n         return void_result();\n      }\n      else\n      {\n         for( const account_id_type& publisher : to_acc.rights_to_publish.publishing_rights_forwarded )\n         {\n            auto& publisher_acc = db().get<account_object>(publisher);\n            db().modify<account_object>( publisher_acc, [&](account_object& ao){\n                 ao.rights_to_publish.publishing_rights_received.erase( publisher );\n            });\n         }\n         db().modify<account_object>(to_acc, [](account_object& ao){\n              ao.rights_to_publish.is_publishing_manager = false;\n              ao.rights_to_publish.publishing_rights_forwarded.clear();\n         });\n      }\n   }\n\n   return void_result();\n}FC_CAPTURE_AND_RETHROW( (o) ) }\n\noperation_result set_publishing_right_evaluator::do_evaluate( const operation_type& o )\n{try{\n    const auto& from_acc = db().get<account_object>(o.from);\n    for( const auto id : o.to )\n       FC_ASSERT (db().find_object(id), \"Account does not exist\");\n    FC_ASSERT( from_acc.rights_to_publish.is_publishing_manager, \"Account does not have permission to give publishing rights\" );\n\n    return void_result();\n}FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result set_publishing_right_evaluator::do_apply( const operation_type& o )\n   {try{\n      const auto& from_acc = db().get<account_object>(o.from);\n\n      for( const account_id_type& element : o.to )\n      {\n         const auto& to_acc = db().get<account_object>( element );\n\n         if(o.is_publisher)\n         {\n            db().modify<account_object>(from_acc, [&](account_object& ao){\n                 ao.rights_to_publish.publishing_rights_forwarded.insert( element );\n            });\n            db().modify<account_object>(to_acc,[&](account_object& ao){\n                 ao.rights_to_publish.publishing_rights_received.insert( o.from );\n            });\n         } else {\n            db().modify<account_object>(from_acc, [&](account_object& ao){\n                 ao.rights_to_publish.publishing_rights_forwarded.erase( element );\n            });\n            db().modify<account_object>(to_acc,[&](account_object& ao){\n                 ao.rights_to_publish.publishing_rights_received.erase( o.from );\n            });\n         }\n      }\n\n      return void_result();\n      }FC_CAPTURE_AND_RETHROW( (o) )\n   }\n\n   operation_result content_submit_evaluator::do_evaluate(const operation_type& o )\n   {try{\n      FC_ASSERT( (db().head_block_time() > HARDFORK_4_TIME) || (o.co_authors.size() <= 10) );\n\n      if( o.key_parts.size() == 0 ) //simplified content\n         FC_ASSERT(db().head_block_time() > HARDFORK_2_TIME);\n\n      db().get<account_object>(o.author);\n      //Submission rights feature is disabled\n      //FC_ASSERT( !author_account.rights_to_publish.publishing_rights_received.empty(), \"Author does not have permission to publish a content\" );\n\n      if( !o.co_authors.empty() )\n      {\n         // sum of basis points\n         uint32_t sum_of_splits = 0;\n\n         for( auto const &element : o.co_authors )\n         {\n            // test whether co-autors exist\n            const auto& idx = db().get_index_type<account_index>().indices().get<graphene::db::by_id>();\n            auto itr = idx.find(element.first);\n            FC_ASSERT (itr != idx.end() , \"Account ${account} doesn't exist.\", ( \"account\", element.first ) );\n            sum_of_splits += element.second;\n         }\n\n         // author can have unassigned payout split value.\n         // In such a case, missing value is automatically calculated, and equals to remaining available basis points\n         // test whether the author is included as co-author\n         auto it = o.co_authors.find( o.author );\n\n         // if author is not included in co_authors map\n         if( it == o.co_authors.end() )\n         {\n            FC_ASSERT( sum_of_splits < 10000, \"Sum of splits exceeds allowed limit ( no remaining basis points for author's payout split ).\" );\n         }\n            // if author is included in co_authors map\n         else\n         {\n            FC_ASSERT( sum_of_splits == 10000, \"Sum of splits doesn't have required value ( 10000 basis points).\" );\n         }\n      }\n\n      const auto& idx_asset = db().get_index_type<asset_index>().indices().get<graphene::db::by_id>();\n      for( const auto& element : o.price )\n      {\n         const auto& itr_asset = idx_asset.find( element.price.asset_id );\n         FC_ASSERT( itr_asset != idx_asset.end(), \"Asset ${a} does not exist\",(\"a\",element.price) );\n         FC_ASSERT( RegionCodes::s_mapCodeToName.count( element.region ) , \"Invalid region code\" );\n      }\n\n      FC_ASSERT( db().head_block_time() <= o.expiration);\n      fc::microseconds duration = (o.expiration - db().head_block_time() );\n      uint32_t days = static_cast<uint32_t>(duration.to_seconds() / 3600 / 24);\n      FC_ASSERT( days != 0, \"time to expiration has to be at least one day\" );\n\n      auto& idx = db().get_index_type<seeder_index>().indices().get<by_seeder>();\n\n      const auto& content_idx = db().get_index_type<content_index>().indices().get<by_URI>();\n      auto content_itr = content_idx.find( o.URI );\n      if( content_itr != content_idx.end() ) // is resubmit?\n      {\n         is_resubmit = true;\n         FC_ASSERT( content_itr->author == o.author );\n         FC_ASSERT( content_itr->size == o.size );\n         FC_ASSERT( content_itr->_hash == o.hash );\n         FC_ASSERT( content_itr->quorum == o.quorum );\n         FC_ASSERT( content_itr->key_parts.size() == o.seeders.size() );\n         for( const auto& element : content_itr->key_parts )\n         {\n            FC_ASSERT( std::find(o.seeders.begin(), o.seeders.end(), element.first ) != o.seeders.end() );\n         }\n         if( content_itr->cd.valid() )\n         {\n            FC_ASSERT( *(content_itr->cd) == *(o.cd) );\n            FC_ASSERT( content_itr->expiration == o.expiration ); // expiration can not be changed for non CDN submit\n         }\n         else\n         {\n            FC_ASSERT( (db().head_block_time() > HARDFORK_4_TIME) || (content_itr->expiration == o.expiration) );\n         }\n\n         /* Resubmit that changes other stuff is not supported.\n         for ( auto &p : o.seeders ) //check if seeders exist and accumulate their prices\n         {\n            auto itr = idx.find( p );\n            FC_ASSERT( itr != idx.end(), \"seeder does not exist\" );\n\n            auto itr2 = content_itr->key_parts.begin();\n            while( itr2 != content_itr->key_parts.end() )\n            {\n               if( itr2->first == p )\n               {\n                  break;\n               }\n               itr2++;\n            }\n            if( itr2 == content_itr->key_parts.end() )\n               FC_ASSERT( itr->free_space > o.size ); // only newly added seeders are tested against free space\n\n            total_price_per_day += itr-> price.amount * o.size;\n         }\n         FC_ASSERT( days * total_price_per\n         for ( auto &p : o.seeders ) //check if seeders exist and accumulate their prices\n         {\n            auto itr = idx.find( p );\n            FC_ASSERT( itr != idx.end(), \"seeder does not exist\" );\n\n            auto itr2 = content_itr->key_parts.begin();\n            while( itr2 != content_itr->key_parts.end() )\n            {\n               if( itr2->first == p )\n               {\n                  break;\n               }\n               itr2++;\n            }\n            if( itr2 == content_itr->key_parts.end() )\n               FC_ASSERT( itr->free_space > o.size ); // only newly added seeders are tested against free space\n\n            total_price_per_day += itr-> price.amount * o.size;\n         }\n         FC_ASSERT( days * total_price_per_day <= o.publishing_fee + content_itr->publishing_fee_escrow );*/\n      } else\n      {\n         asset total_price_per_day;\n         for ( const auto &p : o.seeders ) //check if seeders exist and accumulate their prices\n         {\n            const auto& itr = idx.find( p );\n            FC_ASSERT( itr != idx.end(), \"seeder does not exist\" );\n            FC_ASSERT( itr->free_space > o.size );\n            total_price_per_day += itr-> price.amount * o.size;\n         }\n         FC_ASSERT( days * total_price_per_day <= o.publishing_fee );\n      }\n\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result content_submit_evaluator::do_apply(const operation_type& o)\n   {try{\n      graphene::chain::ContentObjectPropertyManager synopsis_parser(o.synopsis);\n      std::string title = synopsis_parser.get<graphene::chain::ContentObjectTitle>();\n\n      operation_result result;\n      if( is_resubmit )\n      {\n         auto& content_idx = db().get_index_type<content_index>().indices().get<by_URI>();\n         const auto& content_itr = content_idx.find( o.URI );\n\n         graphene::chain::ContentObjectPropertyManager old_synopsis_parser(content_itr->synopsis);\n         std::string old_title = old_synopsis_parser.get<graphene::chain::ContentObjectTitle>();\n         auto& transaction_detail_idx = db().get_index_type<transaction_detail_index>().indices().get<by_description>();\n         const auto& transaction_detail_itr = transaction_detail_idx.find( old_title );\n\n         db().modify<transaction_detail_object>(*transaction_detail_itr,[&](transaction_detail_object& tdo) {\n            tdo.m_str_description = title;\n            tdo.m_timestamp = db().head_block_time();\n         });\n\n         db().modify<content_object>(*content_itr,[&](content_object& co) {\n                                        std::map<uint32_t, asset> prices;\n                                        for (auto const& item : o.price)\n                                        {\n                                           prices[item.region] = item.price;\n                                        }\n\n                                        auto it_no_regions = prices.find(RegionCodes::OO_none);\n                                        if (it_no_regions != prices.end())\n                                           co.price.SetSimplePrice(it_no_regions->second);\n                                        else\n                                        {\n                                           // clearing the region code list first\n                                           co.price.ClearPrices();\n                                           for (auto const& price_item : prices)\n                                           {\n                                              co.price.SetRegionPrice(price_item.first, price_item.second);\n                                           }\n                                        }\n\n                                        co.synopsis = o.synopsis;\n                                        co.co_authors = o.co_authors;\n                                        /*\n                                        co.publishing_fee_escrow += o.publishing_fee;\n                                        auto itr1 = o.seeders.begin();\n                                        auto itr2 = o.key_parts.begin();\n                                        co.key_parts.clear();\n                                        co.last_proof.clear();\n                                        while ( itr1 != o.seeders.end() && itr2 != o.key_parts.end() )\n                                        {\n                                           co.key_parts.emplace(std::make_pair( *itr1, *itr2 ));\n                                           itr1++;\n                                           itr2++;\n                                        }\n                                        co.quorum = o.quorum;*/\n                                        if( !co.cd.valid() )\n                                        {\n                                          co.expiration = o.expiration;\n                                        }\n                                     });\n      }\n      else\n      {\n         const auto& content = db().create<content_object>([&](content_object& co)\n                                     {  //create new content object and store all values from the operation\n                                        co.author = o.author;\n                                        co.co_authors = o.co_authors;\n                                        std::map<uint32_t, asset> prices;\n                                        for (auto const& item : o.price)\n                                        {\n                                           prices[item.region] = item.price;\n                                        }\n\n                                        auto it_no_regions = prices.find(RegionCodes::OO_none);\n                                        if (it_no_regions != prices.end())\n                                           co.price.SetSimplePrice(it_no_regions->second);\n                                        else\n                                        {\n                                           for (auto const& price_item : prices)\n                                           {\n                                              co.price.SetRegionPrice(price_item.first, price_item.second);\n                                           }\n                                        }\n\n                                        co.size = o.size;\n                                        co.synopsis = o.synopsis;\n                                        co.URI = o.URI;\n                                        co.publishing_fee_escrow = o.publishing_fee;\n                                        auto itr1 = o.seeders.begin();\n                                        auto itr2 = o.key_parts.begin();\n                                        while ( itr1 != o.seeders.end() && itr2 != o.key_parts.end() )\n                                        {\n                                           co.key_parts.emplace(std::make_pair( *itr1, *itr2 ));\n                                           itr1++;\n                                           itr2++;\n                                        }\n                                        co._hash = o.hash;\n                                        co.cd = o.cd;\n                                        co.quorum = o.quorum;\n                                        co.expiration = o.expiration;\n                                        co.created = db().head_block_time();\n                                        co.times_bought = 0;\n                                        co.AVG_rating = 0;\n                                        co.num_of_ratings = 0;\n                                     });\n\n         result = content.id;\n         db().adjust_balance(o.author,-o.publishing_fee);  //pay the escrow from author's account\n         auto& idx = db().get_index_type<seeder_index>().indices().get<by_seeder>();\n         // Reserve the space on seeder's boxes\n         // TODO_DECENT - we should better reserve the disk space after the first PoC\n         for ( const auto &p : o.seeders )\n         {\n            const auto& itr = idx.find( p );\n            db().modify<seeder_object>( *itr, [&](seeder_object& so)\n            {\n               so.free_space -= o.size;\n            });\n            db().modify<content_object>(content, [&](content_object& co){\n               co.seeder_price.emplace(std::make_pair(p, itr->price.amount));\n            });\n         }\n\n         const auto& idx2 = db().get_index_type<seeding_statistics_index>().indices().get<by_seeder>();\n         for( const auto& element : o.seeders )\n         {\n            const auto& stats = idx2.find( element );\n            db().modify<seeding_statistics_object>( *stats, [](seeding_statistics_object& so){\n               so.total_content_requested_to_seed += 1;\n            });\n         }\n\n         auto& d = db();\n         db().create<transaction_detail_object>([&o, &title, &d](transaction_detail_object& obj)\n                                                {\n                                                   obj.m_operation_type = (uint8_t)transaction_detail_object::content_submit;\n\n                                                   obj.m_from_account = o.author;\n                                                   obj.m_to_account = account_id_type();\n                                                   obj.m_transaction_amount = o.publishing_fee;\n                                                   obj.m_transaction_fee = o.fee;\n                                                   obj.m_str_description = title;\n                                                   obj.m_timestamp = d.head_block_time();\n                                                });\n      }\n\n      return result;\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result content_cancellation_evaluator::do_evaluate(const operation_type& o)\n   {\n      try {\n         auto& idx = db().get_index_type<content_index>().indices().get<by_URI>();\n         const auto& content_itr = idx.find( o.URI );\n         FC_ASSERT( content_itr != idx.end() );\n         FC_ASSERT( o.author == content_itr->author );\n         FC_ASSERT( content_itr->expiration > db().head_block_time() );\n         FC_ASSERT( !content_itr->is_blocked );\n\n         return void_result();\n      }FC_CAPTURE_AND_RETHROW((o))\n   }\n\n   operation_result content_cancellation_evaluator::do_apply(const operation_type& o)\n   {\n      try {\n         auto& idx = db().get_index_type<content_index>().indices().get<by_URI>();\n         const auto& content_itr = idx.find( o.URI );\n         db().modify<content_object>(*content_itr, [&](content_object &content_obj) {\n            content_obj.is_blocked = true;\n            if( content_obj.expiration > db().head_block_time() + (24 * 60 * 60) )\n               content_obj.expiration = db().head_block_time() + (24 * 60 * 60);\n         });\n\n         return void_result();\n      }FC_CAPTURE_AND_RETHROW((o))\n   }\n\n   operation_result request_to_buy_evaluator::do_evaluate(const operation_type& o )\n   {try{\n      database& d = db();\n\n      auto& idx = d.get_index_type<content_index>().indices().get<by_URI>();\n      const auto& content = idx.find( o.URI );\n      FC_ASSERT( content != idx.end() );\n      FC_ASSERT( o.price <= d.get_balance( o.consumer, o.price.asset_id ) );\n      FC_ASSERT( content->expiration > db().head_block_time() );\n\n      fc::optional<asset> content_price_got = content->price.GetPrice(o.region_code_from);\n\n      FC_ASSERT( content_price_got.valid(), \"content is not available for this region\" );\n      content_price = *content_price_got;\n\n      FC_ASSERT( !content->is_blocked , \"content has been canceled\" );\n\n      auto &range = d.get_index_type<subscription_index>().indices().get<by_from_to>();\n      const auto &subscription = range.find(boost::make_tuple(o.consumer, content->author));\n\n      /// Check whether subscription exists. If so, consumer doesn't need pay for content\n      if (subscription != range.end() && subscription->expiration > d.head_block_time() ) {\n         is_subscriber = true;\n         return void_result();\n      }\n      FC_ASSERT( d.are_assets_exchangeable( o.price.asset_id(d), content_price.asset_id(d) ), \"price for the content and price of the content are not exchangeable\");\n\n      /*\n       * Case 1: paid in some asset, price in the same asset\n       * Case 2: paid in DCT, price in MIA\n       * Case 3: paid in DCT, price in UIA\n       * Case 4: paid in UIA, price in DCT\n       * Case 5: paid in UIA, price in MIA\n       */\n\n      paid_price = o.price;\n\n      if( content_price.asset_id == o.price.asset_id ){ // no need to convert\n         paid_price_after_conversion = paid_price;\n         FC_ASSERT(paid_price_after_conversion >= content_price );\n         return void_result();\n      }\n\n      asset paid_price_in_dct;\n      FC_ASSERT( paid_price.asset_id(d).can_convert(paid_price, paid_price_in_dct, d) && paid_price_in_dct.asset_id == asset_id_type() );\n      FC_ASSERT( content_price.asset_id(d).can_convert(paid_price_in_dct, paid_price_after_conversion, d), \"cannot convert ${f} to ${t}\");\n      FC_ASSERT( paid_price_after_conversion.asset_id == content_price.asset_id );\n      FC_ASSERT( paid_price_after_conversion >= content_price );\n\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result request_to_buy_evaluator::do_apply(const operation_type& o )\n   {try{\n      database& d = db();\n\n      const auto& idx = d.get_index_type<content_index>().indices().get<by_URI>();\n      const auto& content = idx.find( o.URI );\n\n      if( is_subscriber ) //if it is subscription, price is ignored\n      {\n         paid_price = asset( 0 );\n         paid_price_after_conversion = asset( 0 );\n      }\n\n      if( content_price.asset_id == o.price.asset_id ){ // no need to convert\n         paid_price_after_conversion = paid_price;\n      }else {\n         asset paid_price_in_dct = paid_price.asset_id(d).convert(paid_price, d);\n         paid_price_after_conversion = content_price.asset_id(d).convert(paid_price_in_dct, d);\n      }\n\n      bool delivered = false;\n      asset escrow = paid_price_after_conversion;\n      if( content->key_parts.size() == 0 ){ //simplified content buying\n         delivered = true;\n         escrow = asset(0);\n      }\n\n      const auto& object = db().create<buying_object>([&](buying_object& bo)\n                                                      { //create new buying object\n                                                         bo.consumer = o.consumer;\n                                                         bo.URI = o.URI;\n                                                         bo.expiration_time = d.head_block_time() + 24*3600;\n                                                         bo.pubKey = o.pubKey;\n\n                                                         bo.price = escrow; // escrow, will be reset to zero\n                                                         bo.paid_price_before_exchange = paid_price;\n                                                         bo.paid_price_after_exchange = paid_price_after_conversion;\n\n                                                         bo.synopsis = content->synopsis;\n                                                         bo.size = content->size;\n                                                         bo.created = content->created;\n                                                         bo.delivered = delivered;\n                                                         bo.region_code_from = o.region_code_from;\n                                                         bo.expiration_or_delivery_time = db().head_block_time();\n                                                      });\n\n      d.adjust_balance( o.consumer, -paid_price );\n      if(delivered) {\n         content_payout(d, paid_price_after_conversion, *content);\n         d.modify<content_object>( *content, []( content_object& co ){ co.times_bought++; });\n\n         finish_buying_operation op;\n         op.author = content->author;\n         op.co_authors = content->co_authors;\n         op.payout = paid_price_after_conversion;\n         op.consumer = object.consumer;\n         op.buying = object.id;\n\n         db().push_applied_operation(op);\n      }\n      const auto& idx2 = d.get_index_type<seeding_statistics_index>().indices().get<by_seeder>();\n      for( auto& element : content->key_parts )\n      {\n         const auto& stats = idx2.find( element.first );\n         d.modify<seeding_statistics_object>( *stats, [](seeding_statistics_object& so){\n            so.missed_delivered_keys++;\n         });\n      }\n\n      db().create<transaction_detail_object>([&](transaction_detail_object& obj)\n                                             {\n                                                obj.m_operation_type = (uint8_t)transaction_detail_object::content_buy;\n\n                                                const auto& idx = d.get_index_type<content_index>().indices().get<by_URI>();\n                                                auto itr = idx.find(o.URI);\n                                                if (itr != idx.end())\n                                                {\n                                                   obj.m_from_account = itr->author;\n                                                   graphene::chain::ContentObjectPropertyManager synopsis_parser(itr->synopsis);\n                                                   obj.m_str_description = synopsis_parser.get<graphene::chain::ContentObjectTitle>();\n                                                }\n\n                                                obj.m_to_account = o.consumer;\n                                                obj.m_transaction_amount = paid_price;\n                                                obj.m_transaction_fee = o.fee;\n                                                obj.m_timestamp = d.head_block_time();\n                                             });\n\n      return object.id;\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result deliver_keys_evaluator::do_evaluate(const operation_type& o )\n   {try{\n      const auto& buying = db().get<buying_object>(o.buying);\n      auto& idx = db().get_index_type<content_index>().indices().get<by_URI>();\n\n      const auto& content = idx.find( buying.URI );\n      FC_ASSERT( content != idx.end() );\n\n      auto& sidx = db().get_index_type<seeder_index>().indices().get<by_seeder>();\n      const auto& seeder = sidx.find(o.seeder);\n\n      const auto& seeder_pubKey = seeder->pubKey;\n      const auto& buyer_pubKey = buying.pubKey;\n      const auto& firstK = content->key_parts.at( o.seeder );\n      const auto& secondK = o.key;\n      const auto& proof = o.proof;\n      if(!(db().get_node_properties().skip_flags&db().skip_undo_history_check)) {\n         FC_ASSERT(decent::encrypt::verify_delivery_proof(proof, firstK, secondK, seeder_pubKey, buyer_pubKey));\n      }\n\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result deliver_keys_evaluator::do_apply(const operation_type& o )\n   {try{\n      //start with getting the buying and content objects...\n      const auto& buying = db().get<buying_object>(o.buying);\n      bool expired = ( buying.expiration_time < db().head_block_time() );\n      auto& idx = db().get_index_type<content_index>().indices().get<by_URI>();\n      const auto& content = idx.find( buying.URI );\n      bool delivered;\n      // if the response (key particle) has not been seen before, note it\n      if( std::find(buying.seeders_answered.begin(), buying.seeders_answered.end(), o.seeder) == buying.seeders_answered.end() )\n      {\n         db().modify<buying_object>(buying, [&](buying_object& bo){\n            bo.seeders_answered.push_back( o.seeder );\n            bo.key_particles.push_back( decent::encrypt::Ciphertext(o.key) );\n         });\n\n         const auto& idx2 = db().get_index_type<seeding_statistics_index>().indices().get<by_seeder>();\n         const auto& stats = idx2.find( o.seeder );\n         db().modify<seeding_statistics_object>( *stats, [](seeding_statistics_object& so){\n            so.missed_delivered_keys--;\n            so.total_delivered_keys++;\n         } );\n      }\n      delivered = buying.seeders_answered.size() >= content->quorum;\n      //if the content has already been delivered or expired, just note the key particles and go on\n      if( buying.delivered || buying.expired )\n         return void_result();\n      //The content just has been successfuly delivered, take care of the payment\n      if( delivered )\n      {\n         db().modify<content_object>( *content, []( content_object& co ){ co.times_bought++; });\n\n         content_payout(db(), buying.paid_price_after_exchange, *content);\n\n         db().modify<buying_object>(buying, [&](buying_object& bo){\n              bo.price.amount = 0;\n              bo.delivered = true;\n              bo.expiration_or_delivery_time = db().head_block_time();\n         });\n\n         finish_buying_operation op;\n         op.author = content->author;\n         op.co_authors = content->co_authors;\n         op.payout = buying.paid_price_after_exchange;\n         op.consumer = buying.consumer;\n         op.buying = buying.id;\n\n         db().push_applied_operation(op);\n      } else if (expired) //the content just expired, clean up\n      {\n         db().buying_expire(buying);\n      }\n\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result leave_rating_evaluator::do_evaluate(const operation_type& o )\n   {try{\n      //check in buying history if the object exists\n      auto& idx = db().get_index_type<content_index>().indices().get<by_URI>();\n      const auto& content = idx.find( o.URI );\n      auto& bidx = db().get_index_type<buying_index>().indices().get<by_consumer_URI>();\n      const auto& bo = bidx.find( std::make_tuple(o.consumer, o.URI) );\n      FC_ASSERT( content != idx.end() && bo != bidx.end() );\n      FC_ASSERT( bo->delivered, \"not delivered\" );\n      FC_ASSERT( !bo->rated_or_commented, \"already rated or commented\" );\n\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result leave_rating_evaluator::do_apply(const operation_type& o )\n   {try{\n      //adjust content statistics\n      auto& bidx = db().get_index_type<buying_index>().indices().get<by_consumer_URI>();\n      const auto& bo = bidx.find( std::make_tuple(o.consumer, o.URI) );\n      auto& idx = db().get_index_type<content_index>().indices().get<by_URI>();\n      const auto& content = idx.find( o.URI );\n\n      db().modify<buying_object>( *bo, [&]( buying_object& b ){\n           b.rated_or_commented = true;\n           b.rating = static_cast<uint32_t>(o.rating);\n           b.comment = o.comment;\n      });\n\n      db().modify<content_object> ( *content, [&](content_object& co){\n           co.AVG_rating = (co.AVG_rating * co.num_of_ratings + static_cast<uint32_t>(o.rating) * 1000) / (co.num_of_ratings + 1);\n           co.num_of_ratings++;\n      });\n\n      auto& d = db();\n      db().create<transaction_detail_object>([&o, &d](transaction_detail_object& obj)\n                                             {\n                                                obj.m_operation_type = (uint8_t)transaction_detail_object::content_rate;\n\n                                                const auto& idx = d.get_index_type<content_index>().indices().get<by_URI>();\n                                                auto itr = idx.find(o.URI);\n                                                if (itr != idx.end())\n                                                {\n                                                   obj.m_to_account = itr->author;\n\n                                                   graphene::chain::ContentObjectPropertyManager synopsis_parser(itr->synopsis);\n                                                   obj.m_str_description = synopsis_parser.get<graphene::chain::ContentObjectTitle>();\n                                                }\n\n                                                obj.m_from_account = o.consumer;\n\n                                                obj.m_transaction_amount = asset();\n                                                obj.m_transaction_fee = o.fee;\n                                                obj.m_str_description = std::to_string(o.rating) + \" (\" + obj.m_str_description + \")\";\n                                                obj.m_timestamp = d.head_block_time();\n                                             });\n\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result ready_to_publish_obsolete_evaluator::do_evaluate(const operation_type& o)\n   {try{\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result ready_to_publish_obsolete_evaluator::do_apply(const operation_type& o)\n   {try{\n      auto& idx = db().get_index_type<seeder_index>().indices().get<by_seeder>();\n      const auto& sor = idx.find( o.seeder );\n      operation_result result;\n      if( sor == idx.end() ) { //this is initial publish request\n         const seeding_statistics_object &sso = db().create<seeding_statistics_object>([&o](seeding_statistics_object &sso) {\n              sso.seeder = o.seeder;\n              sso.total_upload = 0;\n         });\n         result = sso.id;\n         db().create<seeder_object>([&](seeder_object& so) {\n              so.seeder = o.seeder;\n              so.free_space = o.space;\n              so.pubKey = o.pubKey;\n              so.price = asset(o.price_per_MByte);\n              so.expiration = db().head_block_time() + DECENT_RTP_VALIDITY;\n              so.ipfs_ID = o.ipfs_ID;\n              so.stats = sso.id;\n         });\n      } else\n      { //this is republish case\n         db().modify<seeder_object>(*sor,[&](seeder_object &so) {\n            so.free_space = o.space;\n            so.price = asset(o.price_per_MByte);\n            so.pubKey = o.pubKey;\n            so.expiration = db().head_block_time() + 24 * 3600;\n            so.ipfs_ID = o.ipfs_ID;\n\n         });\n      }\n\n      return result;\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result ready_to_publish_evaluator::do_evaluate(const operation_type& o )\n   {try{\n      FC_ASSERT(db().head_block_time() >= HARDFORK_1_TIME );\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result ready_to_publish_evaluator::do_apply(const operation_type& o )\n   {try{\n      auto& idx = db().get_index_type<seeder_index>().indices().get<by_seeder>();\n      const auto& sor = idx.find( o.seeder );\n      operation_result result;\n      if( sor == idx.end() ) { //this is initial publish request\n         const seeding_statistics_object &sso = db().create<seeding_statistics_object>([&o](seeding_statistics_object &sso) {\n              sso.seeder = o.seeder;\n              sso.total_upload = 0;\n         });\n         result = sso.id;\n         db().create<seeder_object>([&](seeder_object& so) {\n              so.seeder = o.seeder;\n              so.free_space = o.space;\n              so.pubKey = o.pubKey;\n              so.price = asset(o.price_per_MByte);\n              so.expiration = db().head_block_time() + DECENT_RTP_VALIDITY;\n              so.ipfs_ID = o.ipfs_ID;\n              so.stats = sso.id;\n              if( o.region_code.valid() )\n                 so.region_code = *o.region_code;\n              else\n                 so.region_code = \"\";\n         });\n      } else\n      { //this is republish case\n         db().modify<seeder_object>(*sor,[&](seeder_object &so) {\n              so.free_space = o.space;\n              so.price = asset(o.price_per_MByte);\n              so.pubKey = o.pubKey;\n              so.expiration = db().head_block_time() + 24 * 3600;\n              so.ipfs_ID = o.ipfs_ID;\n\n              if( o.region_code.valid() )\n                 so.region_code = *o.region_code;\n              else\n                 so.region_code = \"\";\n         });\n      }\n\n      return result;\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result proof_of_custody_evaluator::do_evaluate(const operation_type& o )\n   {try{\n      auto& idx = db().get_index_type<content_index>().indices().get<by_URI>();\n      const auto& content = idx.find( o.URI );\n      FC_ASSERT( content != idx.end(), \"content not found\" );\n      FC_ASSERT( content->expiration > db().head_block_time(), \"content expired\" );\n      //verify that the seed is not too old...\n      if (o.proof.valid() )\n      {\n         auto& proof = *o.proof;\n         fc::ripemd160 bid = db().get_block_id_for_num(proof.reference_block);\n         FC_ASSERT(bid == proof.seed,\"Block ID does not match; wrong chain?\");\n         FC_ASSERT(db().head_block_num() <= proof.reference_block + 6,\"Block reference is too old\");\n      }\n      //\n      FC_ASSERT( content->cd.valid() == o.proof.valid() );\n\n      if(!(db().get_node_properties().skip_flags&db().skip_validate)) {\n         FC_ASSERT( !(content->cd.valid() ) || _custody_utils.verify_by_miner( *(content->cd), *(o.proof) ) == 0, \"Invalid proof of custody\" );\n      }\n      //ilog(\"proof_of_custody OK\");\n\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result proof_of_custody_evaluator::do_apply(const operation_type& o )\n   {try{\n      //get the seeder and content\n      auto& idx = db().get_index_type<content_index>().indices().get<by_URI>();\n      const auto& content = idx.find( o.URI );\n      const auto& sidx = db().get_index_type<seeder_index>().indices().get<by_seeder>();\n      const auto& sitr = sidx.find(o.seeder);\n      FC_ASSERT(sitr!=sidx.end(), \"seeder not found\");\n      const seeder_object& seeder = *sitr;\n\n      auto last_proof = content->last_proof.find( o.seeder );\n      if( last_proof == content->last_proof.end() ) //initial PoR\n      {\n         //the initial proof, no payments yet\n         db().modify<content_object>(*content, [&](content_object& co){\n              co.last_proof.emplace(std::make_pair(o.seeder, db().head_block_time()));\n         });\n\n         const auto& idx2 = db().get_index_type<seeding_statistics_index>().indices().get<by_seeder>();\n         const auto& stats = idx2.find( o.seeder );\n         db().modify<seeding_statistics_object>( *stats, [&content](seeding_statistics_object& so){\n            so.total_content_seeded += ( content->size * 1000 * 1000 ) / content->key_parts.size();\n            so.num_of_content_seeded++;\n            if( so.total_content_requested_to_seed > 0 )\n               so.total_content_requested_to_seed -= 1;\n         });\n      }else{\n         const auto& idx2 = db().get_index_type<seeding_statistics_index>().indices().get<by_seeder>();\n         const auto& stats = idx2.find( o.seeder );\n         db().modify<seeding_statistics_object>( *stats, [](seeding_statistics_object& so){\n            so.num_of_pors++;\n         });\n         //recurrent PoR, calculate payment\n         //the PoR shall be ideally broadcasted once per 24h. if the seeder pushes them too often, he is penalized by a\n         // loss factor equal to one forth of the time remaining to 24h. E.g. by pushing it in 12h he is penalized by\n         // loss = (12/24)/4 = 12,5%; if it is pushed in 18h (i.e. 6 hours prematurely) the loss = (6/24)/4=6,25%.\n         fc::microseconds diff = db().head_block_time() - last_proof->second;\n         if( diff > fc::days( 1 ) )\n            diff = fc::days( 1 ) ;\n         uint64_t ratio = 10000 * diff.count() / fc::days( 1 ).count();\n         uint64_t loss = ( 10000 - ratio ) / 4;\n         uint64_t total_reward_ratio = ( ratio * ( 10000 - loss ) ) / 10000;\n         asset reward(0);\n         if (db().head_block_num() > 404727) {\n            const auto& itr = content->seeder_price.find(o.seeder);\n            FC_ASSERT(itr != content->seeder_price.end());\n            reward.amount = itr->second * total_reward_ratio * content->size / 10000;\n         }\n         else\n            reward.amount = seeder.price.amount * total_reward_ratio * content->size / 10000 ;\n         //Fix due to block halt at #404726\n         if( db().head_block_num() > 404727 && reward.amount > content->publishing_fee_escrow.amount ) {\n            reward.amount = std::max(int64_t(0), content->publishing_fee_escrow.amount.value );\n         }\n         //take care of the payment\n         db().modify<content_object>( *content, [&] (content_object& co ){\n            co.last_proof[o.seeder] = db().head_block_time();\n            co.publishing_fee_escrow -= reward;\n         });\n         db().adjust_balance(seeder.seeder, reward );\n         pay_seeder_operation op;\n         op.author = content->author;\n         op.seeder = seeder.seeder;\n         op.payout = reward;\n         db().push_applied_operation(op);\n      }\n\n      return void_result();\n   }FC_CAPTURE_AND_RETHROW( (o) ) }\n\n   operation_result report_stats_evaluator::do_evaluate(const operation_type& o)\n   {\n\t   try {\n         for (const auto& item : o.stats)\n         {\n            FC_ASSERT( db().find_object(item.first), \"Invalid seeder account specified.\" );\n         }\n\t   }FC_CAPTURE_AND_RETHROW((o))\n\n      return void_result();\n   }\n\n   operation_result report_stats_evaluator::do_apply(const operation_type& o)\n   {\n      try {\n         auto& idx = db().get_index_type<seeding_statistics_index>().indices().get<by_seeder>();\n         for (const auto& item : o.stats)\n         {\n            const auto &so = idx.find(item.first);\n            db().modify<seeding_statistics_object>(*so, [&item](seeding_statistics_object &sso) {\n               sso.total_upload += item.second;\n            });\n         }\n      }FC_CAPTURE_AND_RETHROW((o))\n\n      return void_result();\n   }\n\n}} // graphene::chain\n", "meta": {"hexsha": "25069f2ea3880653c6914c5a76b417a955fbfdf1", "size": 42915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/decent_evaluator.cpp", "max_stars_repo_name": "f3chain/fff", "max_stars_repo_head_hexsha": "707bb1f0791206fe8f1ed9d610c1b6efa34d8bab", "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": "libraries/chain/decent_evaluator.cpp", "max_issues_repo_name": "f3chain/fff", "max_issues_repo_head_hexsha": "707bb1f0791206fe8f1ed9d610c1b6efa34d8bab", "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": "libraries/chain/decent_evaluator.cpp", "max_forks_repo_name": "f3chain/fff", "max_forks_repo_head_hexsha": "707bb1f0791206fe8f1ed9d610c1b6efa34d8bab", "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.4608050847, "max_line_length": 165, "alphanum_fraction": 0.5438191774, "num_tokens": 9145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.15006162918070792}}
{"text": "/*\n *\n *    data: 2019-5-20\n *    auther : Ma Mengyu@National University of Defense Technology\n *    e-mail : mamengyu10@nudt.edu.cn\n *    description :\n *    Multi-Thread Visualization Server\n *    run :\n *\n */\n\n#include <ogrsf_frmts.h>\n#include <ogr_p.h>\n#include \"crow.h\"\n#include <cpl_conv.h>\n#include <cpl_string.h>\n#include \"Redis.h\"\n#include <stdio.h>\n#include <cstring>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <dirent.h>\n#include <omp.h>\n#include <sys/time.h>\n#include <regex.h>\n#include <math.h>\n#include <stdlib.h>\n#include <png.h>\n#include <stdlib.h>\n#include <stack>\n#include <signal.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/index/rtree.hpp>\n#include <boost/foreach.hpp>\n#include <boost/interprocess/managed_mapped_file.hpp>\n#define MAX_NODE_SIZE\t8\n#define MAX_DOUBLE\t1000000000\n\nnamespace bg\t= boost::geometry;\nnamespace bgi\t= boost::geometry::index;\nnamespace bgm\t= boost::geometry::model;\nnamespace bi\t= boost::interprocess;\n\nusing namespace std;\n#define TILE_SIZE\t256\n#define L\t\t20037508.34\n\n\n/**\n * @brief Startup parameters\n */\nclass HiVisionPara\n{\npublic:\n\tchar\t*shpPath\t= NULL;         /* Path of the input shapefiles */\n\tchar\t*indexPath\t= NULL;         /* Path to store the spatial indexes */\n\tchar\t*patternPath\t= NULL;         /* Path of the input patterns */\n\tchar\t*redisHost\t= NULL;         /* Host IP of Redis */\n\tint\tredisPort\t= 6379;         /* Host Port of Redis */\n\tint\tservicePort\t= 10080;        /* Port of the HiVision service */\n};\nHiVisionPara hvpara;\n\n\n/**\n * @brief Split a string into a list where each word is a list item\n * @param argv          Input string\n * @param result[]  Output Word list\n * @param flag          Separator used to split the string\n * @param count         Output Word list length\n *\n */\nvoid GetList( char* argv, char* result[], char* flag, int & count )\n{\n\tchar\t* string = strdup( argv );\n\tchar\t* p;\n\tint\ti = 0;\n\twhile ( (p = strsep( &string, flag ) ) != NULL )\n\t{\n\t\tresult[i] = p;\n\t\ti++;\n\t}\n\tresult[i]\t= string;\n\tcount\t\t= i;\n}\n\n\n/**\n * @brief Create Spatial Indexes and Write Dataset meta-data for Linestring Datasets\n * @param shpFile       Input Linestring shpfile path\n * @param outIndex      Output spatial index path\n * @param redishost     Host IP of Redis\n * @param rediskey      Data id\n * @param redisport     Host Port of Redis\n *\n */\nbool Linestring( char* shpFile, char* outIndex, char* redishost, char* rediskey, int redisport )\n{\n\t/* Record the running time of the program */\n\tstruct timeval\tt1, t2;\n\tdouble\t\ttimeuse;\n\tgettimeofday( &t1, NULL );\n\n\t/* Init */\n\ttypedef bgm::d2::point_xy<double>\t\t\t\t\t\t\t\tpoint;\n\ttypedef bgm::segment<point>\t\t\t\t\t\t\t\t\tsegment;\n\ttypedef bgi::quadratic<MAX_NODE_SIZE>\t\t\t\t\t\t\t\tparams;\n\ttypedef bgi::indexable<segment>\t\t\t\t\t\t\t\t\tindexable_segment;\n\ttypedef bgi::equal_to<segment>\t\t\t\t\t\t\t\t\tequal_to_segment;\n\ttypedef bi::allocator<segment, bi::managed_mapped_file::segment_manager>\t\t\tallocator_segment;\n\ttypedef bgi::rtree<segment, params, indexable_segment, equal_to_segment, allocator_segment>\trtree_segment;\n\tlong\tsize\t= 300000; /* Max size (MB) of the spatial index mapped file */\n\tdouble\tminXOut = MAX_DOUBLE, minYOut = MAX_DOUBLE, maxXout = -1 * MAX_DOUBLE, maxYOut = -1 * MAX_DOUBLE;\n\tCPLSetConfigOption( \"GDAL_FILENAME_IS_UTF8\", \"NO\" );\n\tCPLSetConfigOption( \"SHAPE_ENCODING\", \"UTF-8\" );\n\n\t/* Check whether the dataset has been registered */\n\tfstream f;\n\tf.open( outIndex, ios::in );\n\tif ( f )\n\t{\n\t\tprintf( \"[ERROR] Dataset already registered! shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tf.close();\n\tremove( outIndex );\n\n\t/* Connect redis */\n\tRedis *redis = new Redis();\n\tif ( !redis->connect( redishost, redisport ) )\n\t{\n\t\tprintf( \"[ERROR] connect redis error! shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\n\t/* Read shpfile */\n\tGDALAllRegister();\n\tOGRRegisterAll();\n\tOGRLayer\t* shpLayer;\n\tOGRFeature\t*shpFeature;\n\tGDALDataset\t* shpDS;\n\tshpDS = (GDALDataset *) GDALOpenEx( shpFile, GDAL_OF_VECTOR, NULL, NULL, NULL );\n\tif ( shpDS == NULL )\n\t{\n\t\tprintf( \"[ERROR] Open shpFile failed. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tshpLayer = shpDS->GetLayer( 0 );\n\tif ( shpLayer == NULL )\n\t{\n\t\tprintf( \"[ERROR] Open shpFile failed. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tOGREnvelope env;\n\tif ( shpLayer->GetExtent( &env ) != 0 )\n\t{\n\t\tprintf( \"[ERROR] Get extent failed. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tminXOut = minXOut < env.MinX ? minXOut : env.MinX;\n\tminYOut = minYOut < env.MinY ? minYOut : env.MinY;\n\tmaxXout = maxXout > env.MaxX ? maxXout : env.MaxX;\n\tmaxYOut = maxYOut > env.MaxY ? maxYOut : env.MaxY;\n\tshpLayer->ResetReading();\n\n\t/* Create coordinate transformation to the Web Mercator projection */\n\tOGRSpatialReference\t* fRef;\n\tOGRSpatialReference\ttRef;\n\tfRef = shpLayer->GetSpatialRef();\n\tif ( fRef == NULL )\n\t{\n\t\tprintf( \"[ERROR] No SpatialRef. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\ttRef.importFromEPSG( 3857 );\n\tOGRCoordinateTransformation *coordTrans;\n\tcoordTrans = OGRCreateCoordinateTransformation( fRef, &tRef );\n\n\t/* Write Dataset meta-data to redis */\n\tcoordTrans->Transform( 1, &minXOut, &minYOut );\n\tcoordTrans->Transform( 1, &maxXout, &maxYOut );\n\tchar * tmp = new char[256];\n\tsprintf( tmp, \"%lf,%lf,%lf,%lf\", minXOut, minYOut, maxXout, maxYOut );\n\tredis->set( rediskey, tmp );\n\n\t/* Create spatial index */\n\tbi::managed_mapped_file file( bi::create_only, outIndex, size * 1024 * 1024 );\n\tallocator_segment\talloc( file.get_segment_manager() );\n\trtree_segment\t\t* rtree_ptr = file.construct<rtree_segment>( \"rtree\" ) ( params(), indexable_segment(), equal_to_segment(), alloc );\n\tdouble\t\t\tpx0, py0, px1, py1;\n\twhile ( (shpFeature = shpLayer->GetNextFeature() ) != NULL )\n\t{\n\t\tif ( shpFeature == NULL )\n\t\t\tcontinue;\n\t\tOGRGeometry *poGeometry = shpFeature->GetGeometryRef();\n\t\tif ( poGeometry == NULL )\n\t\t\tcontinue;\n\t\tint eType = wkbFlatten( poGeometry->getGeometryType() );\n\t\tif ( eType == wkbLineString )\n\t\t{\n\t\t\tOGRLineString\t* pOGRLineString\t= (OGRLineString *) poGeometry;\n\t\t\tint\t\tpointCount\t\t= pOGRLineString->getNumPoints();\n\t\t\tpx0\t= pOGRLineString->getX( 0 );\n\t\t\tpy0\t= pOGRLineString->getY( 0 );\n\t\t\tcoordTrans->Transform( 1, &px0, &py0 );\n\t\t\tfor ( int i = 1; i < pointCount; i++ )\n\t\t\t{\n\t\t\t\tpx1\t= pOGRLineString->getX( i );\n\t\t\t\tpy1\t= pOGRLineString->getY( i );\n\t\t\t\tcoordTrans->Transform( 1, &px1, &py1 );\n\t\t\t\trtree_ptr->insert( segment( point( px0, py0 ), point( px1, py1 ) ) );\n\t\t\t\tpx0\t= px1;\n\t\t\t\tpy0\t= py1;\n\t\t\t}\n\t\t}else if ( eType == wkbMultiLineString )\n\t\t{\n\t\t\tOGRMultiLineString\t* pOGRMultiLineString\t= (OGRMultiLineString *) poGeometry;\n\t\t\tint\t\t\tlineCount\t\t= pOGRMultiLineString->getNumGeometries();\n\t\t\tfor ( int j = 0; j < lineCount; j++ )\n\t\t\t{\n\t\t\t\tOGRLineString\t* pOGRLineString\t= (OGRLineString *) pOGRMultiLineString->getGeometryRef( j );\n\t\t\t\tint\t\tpointCount\t\t= pOGRLineString->getNumPoints();\n\t\t\t\tpx0\t= pOGRLineString->getX( 0 );\n\t\t\t\tpy0\t= pOGRLineString->getY( 0 );\n\t\t\t\tcoordTrans->Transform( 1, &px0, &py0 );\n\t\t\t\tfor ( int i = 1; i < pointCount; i++ )\n\t\t\t\t{\n\t\t\t\t\tpx1\t= pOGRLineString->getX( i );\n\t\t\t\t\tpy1\t= pOGRLineString->getY( i );\n\t\t\t\t\tcoordTrans->Transform( 1, &px1, &py1 );\n\t\t\t\t\trtree_ptr->insert( segment( point( px0, py0 ), point( px1, py1 ) ) );\n\t\t\t\t\tpx0\t= px1;\n\t\t\t\t\tpy0\t= py1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( rtree_ptr->size() < 1 )\n\t{\n\t\tprintf( \"[ERROR] No feature found. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\tremove( outIndex );\n\t\treturn(false);\n\t}\n\n\t/* Shrink the spatial index file to minimize the space waste */\n\tbi::managed_mapped_file::shrink_to_fit( outIndex );\n\n\t/* Write process log */\n\tgettimeofday( &t2, NULL );\n\ttimeuse = t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) / 1000000.0;\n\tprintf( \"[DONE] %s Use Time:%f\\n\", outIndex, timeuse );\n\n\treturn(true);\n}\n\n\n/**\n * @brief Create Spatial Indexes and Write Dataset meta-data for Point Datasets\n * @param shpFile       Input Point shpfile path\n * @param outIndex      Output spatial index path\n * @param redishost     Host IP of Redis\n * @param rediskey      Data id\n * @param redisport     Host Port of Redis\n *\n */\nbool Point( char* shpFile, char* outIndex, char* redishost, char* rediskey, int redisport )\n{\n\t/* Record the running time of the program */\n\tstruct timeval\tt1, t2;\n\tdouble\t\ttimeuse;\n\tgettimeofday( &t1, NULL );\n\n\t/* Init */\n\ttypedef bgm::d2::point_xy<double>\t\t\t\t\t\tpoint;\n\ttypedef bgi::quadratic<MAX_NODE_SIZE>\t\t\t\t\t\tparams_t;\n\ttypedef bgi::indexable<point>\t\t\t\t\t\t\tindexable_t;\n\ttypedef bgi::equal_to<point>\t\t\t\t\t\t\tequal_to_t;\n\ttypedef bi::allocator<point, bi::managed_mapped_file::segment_manager>\t\tallocator_t;\n\ttypedef bgi::rtree<point, params_t, indexable_t, equal_to_t, allocator_t>\trtree_t;\n\tlong\tsize\t= 300000; /* Max size (MB) of the spatial index mapped file */\n\tdouble\tminXOut = MAX_DOUBLE, minYOut = MAX_DOUBLE, maxXout = -1 * MAX_DOUBLE, maxYOut = -1 * MAX_DOUBLE;\n\tCPLSetConfigOption( \"GDAL_FILENAME_IS_UTF8\", \"NO\" );\n\tCPLSetConfigOption( \"SHAPE_ENCODING\", \"UTF-8\" );\n\n\t/* Check whether the dataset has been registered */\n\tfstream f;\n\tf.open( outIndex, ios::in );\n\tif ( f )\n\t{\n\t\tprintf( \"[ERROR] Dataset already registered! shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tf.close();\n\tremove( outIndex );\n\n\t/* Connect redis */\n\tRedis *redis = new Redis();\n\tif ( !redis->connect( redishost, redisport ) )\n\t{\n\t\tprintf( \"[ERROR] connect redis error!\\n\" );\n\t\treturn(false);\n\t}\n\n\t/* Read shpfile */\n\tOGRRegisterAll();\n\tOGRLayer\t* shpLayer;\n\tOGRFeature\t*shpFeature;\n\tGDALDataset\t* shpDS;\n\tshpDS = (GDALDataset *) GDALOpenEx( shpFile, GDAL_OF_VECTOR, NULL, NULL, NULL );\n\tif ( shpDS == NULL )\n\t{\n\t\tprintf( \"[ERROR] Open shpFile failed. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tshpLayer = shpDS->GetLayer( 0 );\n\tif ( shpLayer == NULL )\n\t{\n\t\tprintf( \"[ERROR] Open shpFile failed. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tOGREnvelope env;\n\tif ( shpLayer->GetExtent( &env ) != 0 )\n\t{\n\t\tprintf( \"[ERROR] Get extent failed. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tminXOut = minXOut < env.MinX ? minXOut : env.MinX;\n\tminYOut = minYOut < env.MinY ? minYOut : env.MinY;\n\tmaxXout = maxXout > env.MaxX ? maxXout : env.MaxX;\n\tmaxYOut = maxYOut > env.MaxY ? maxYOut : env.MaxY;\n\tshpLayer->ResetReading();\n\n\t/* Create coordinate transformation to the Web Mercator projection */\n\tOGRSpatialReference\t* fRef;\n\tOGRSpatialReference\ttRef;\n\tfRef = shpLayer->GetSpatialRef();\n\tif ( fRef == NULL )\n\t{\n\t\tprintf( \"[ERROR] No SpatialRef. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\ttRef.importFromEPSG( 3857 );\n\tOGRCoordinateTransformation *coordTrans;\n\tcoordTrans = OGRCreateCoordinateTransformation( fRef, &tRef );\n\n\t/* Write Dataset meta-data to redis */\n\tcoordTrans->Transform( 1, &minXOut, &minYOut );\n\tcoordTrans->Transform( 1, &maxXout, &maxYOut );\n\tchar * tmp = new char[256];\n\tsprintf( tmp, \"%lf,%lf,%lf,%lf\", minXOut, minYOut, maxXout, maxYOut );\n\tredis->set( rediskey, tmp );\n\n\t/* Create spatial index */\n\tbi::managed_mapped_file file( bi::create_only, outIndex, size * 1024 * 1024 );\n\tallocator_t\t\talloc( file.get_segment_manager() );\n\trtree_t\t\t\t* rtree_ptr = file.find_or_construct<rtree_t>( \"rtree\" ) ( params_t(), indexable_t(), equal_to_t(), alloc );\n\tdouble\t\t\tpx0, py0;\n\twhile ( (shpFeature = shpLayer->GetNextFeature() ) != NULL )\n\t{\n\t\tif ( shpFeature == NULL )\n\t\t\tcontinue;\n\t\tOGRGeometry *poGeometry = shpFeature->GetGeometryRef();\n\t\tif ( poGeometry == NULL )\n\t\t\tcontinue;\n\t\tint eType = wkbFlatten( poGeometry->getGeometryType() );\n\t\tif ( eType == wkbPoint )\n\t\t{\n\t\t\tOGRPoint* pOGRPoint = (OGRPoint *) poGeometry;\n\t\t\tpx0\t= pOGRPoint->getX();\n\t\t\tpy0\t= pOGRPoint->getY();\n\t\t\tcoordTrans->Transform( 1, &px0, &py0 );\n\t\t\trtree_ptr->insert( point( px0, py0 ) );\n\t\t}else if ( eType == wkbMultiPoint )\n\t\t{\n\t\t\tOGRMultiPoint\t* pOGRMultiPoint\t= (OGRMultiPoint *) poGeometry;\n\t\t\tint\t\tpointCount\t\t= pOGRMultiPoint->getNumGeometries();\n\t\t\tfor ( int j = 0; j < pointCount; j++ )\n\t\t\t{\n\t\t\t\tOGRPoint* pOGRPoint = (OGRPoint *) pOGRMultiPoint->getGeometryRef( j );\n\t\t\t\tpx0\t= pOGRPoint->getX();\n\t\t\t\tpy0\t= pOGRPoint->getY();\n\t\t\t\tcoordTrans->Transform( 1, &px0, &py0 );\n\t\t\t\trtree_ptr->insert( point( px0, py0 ) );\n\t\t\t}\n\t\t}\n\t}\n\tif ( rtree_ptr->size() < 1 )\n\t{\n\t\tprintf( \"[ERROR] No feature found. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\tremove( outIndex );\n\t\treturn(false);\n\t}\n\n\t/* Shrink the spatial index file to minimize the space waste */\n\tbi::managed_mapped_file::shrink_to_fit( outIndex );\n\n\t/* Write process log */\n\tgettimeofday( &t2, NULL );\n\ttimeuse = t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) / 1000000.0;\n\tprintf( \"[DONE] %s Use Time:%f\\n\", outIndex, timeuse );\n\treturn(true);\n}\n\n\n/**\n * @brief Create Spatial Indexes and Write Dataset meta-data for Polygon Datasets\n * @param shpFile       Input Polygon shpfile path\n * @param outIndex      Output spatial index path\n * @param redishost     host IP of Redis\n * @param rediskey      Data id\n * @param redisport     host Port of Redis\n *\n */\nbool Polygon( char* shpFile, char* outIndex, char* redishost, char* rediskey, int redisport )\n{\n\t/* Record the running time of the program */\n\tstruct timeval\tt1, t2;\n\tdouble\t\ttimeuse;\n\tgettimeofday( &t1, NULL );\n\n\t/* Init */\n\ttypedef bgm::d2::point_xy<double>\t\t\t\t\t\t\t\t\tpoint;\n\ttypedef bgm::box<point>\t\t\t\t\t\t\t\t\t\t\tbox;\n\ttypedef bgm::segment<point>\t\t\t\t\t\t\t\t\t\tsegment;\n\ttypedef boost::tuple<segment, unsigned long, bool>\t\t\t\t\t\t\tpolygon_segment;\n\ttypedef std::pair<box, unsigned long>\t\t\t\t\t\t\t\t\tpolygon_box;\n\ttypedef bgi::quadratic<MAX_NODE_SIZE>\t\t\t\t\t\t\t\t\tparams;\n\ttypedef bgi::indexable<polygon_segment>\t\t\t\t\t\t\t\t\tindexable_segment;\n\ttypedef bgi::equal_to<polygon_segment>\t\t\t\t\t\t\t\t\tequal_to_segment;\n\ttypedef bi::allocator<polygon_segment, bi::managed_mapped_file::segment_manager>\t\t\tallocator_segment;\n\ttypedef bgi::rtree<polygon_segment, params, indexable_segment, equal_to_segment, allocator_segment>\trtree_segment;\n\ttypedef bgi::indexable<polygon_box>\t\t\t\t\t\t\t\t\tindexable_box;\n\ttypedef bgi::equal_to<polygon_box>\t\t\t\t\t\t\t\t\tequal_to_box;\n\ttypedef bi::allocator<polygon_box, bi::managed_mapped_file::segment_manager>\t\t\t\tallocator_box;\n\ttypedef bgi::rtree<polygon_box, params, indexable_box, equal_to_box, allocator_box>\t\t\trtree_box;\n\tchar\t* outMBRIndex\t= new char[256];        /* Output spatial index MBR path */\n\tlong\tsize\t\t= 300000;               /* Max size (MB) of the spatial index mapped file */\n\tdouble\ttolerance\t= 0.00001;\n\tdouble\tminXOut\t\t= MAX_DOUBLE, minYOut = MAX_DOUBLE, maxXout = -1 * MAX_DOUBLE, maxYOut = -1 * MAX_DOUBLE;\n\tCPLSetConfigOption( \"GDAL_FILENAME_IS_UTF8\", \"NO\" );\n\tCPLSetConfigOption( \"SHAPE_ENCODING\", \"UTF-8\" );\n\n\t/* Check whether the dataset has been registered */\n\tfstream f;\n\tf.open( outIndex, ios::in );\n\tif ( f )\n\t{\n\t\tprintf( \"[ERROR] Dataset already registered! shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tf.close();\n\tsprintf( outMBRIndex, \"%s_mbr\", outIndex );\n\tremove( outIndex );\n\tremove( outMBRIndex );\n\n\t/* Connect redis */\n\tRedis *redis = new Redis();\n\tif ( !redis->connect( redishost, redisport ) )\n\t{\n\t\tprintf( \"[ERROR] connect redis error! shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\n\t/* Read shpfile */\n\tOGRRegisterAll();\n\tOGRLayer\t* shpLayer;\n\tOGRFeature\t*shpFeature;\n\tGDALDataset\t* shpDS;\n\tshpDS = (GDALDataset *) GDALOpenEx( shpFile, GDAL_OF_VECTOR, NULL, NULL, NULL );\n\tif ( shpDS == NULL )\n\t{\n\t\tprintf( \"[ERROR] Open shpFile failed. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tshpLayer = shpDS->GetLayer( 0 );\n\tif ( shpLayer == NULL )\n\t{\n\t\tprintf( \"[ERROR] No such layer. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tOGREnvelope env;\n\tif ( shpLayer->GetExtent( &env ) != 0 )\n\t{\n\t\tprintf( \"[ERROR] Get extent failed. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\tminXOut = minXOut < env.MinX ? minXOut : env.MinX;\n\tminYOut = minYOut < env.MinY ? minYOut : env.MinY;\n\tmaxXout = maxXout > env.MaxX ? maxXout : env.MaxX;\n\tmaxYOut = maxYOut > env.MaxY ? maxYOut : env.MaxY;\n\tshpLayer->ResetReading();\n\n\t/* Create Coordinate Transformation to the Web Mercator projection */\n\tOGRSpatialReference\t* fRef;\n\tOGRSpatialReference\ttRef;\n\tfRef = shpLayer->GetSpatialRef();\n\tif ( fRef == NULL )\n\t{\n\t\tprintf( \"[ERROR] No SpatialRef. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\treturn(false);\n\t}\n\n\ttRef.importFromEPSG( 3857 );\n\tOGRCoordinateTransformation *coordTrans;\n\tcoordTrans = OGRCreateCoordinateTransformation( fRef, &tRef );\n\n\t/* Write Dataset meta-data to redis */\n\tcoordTrans->Transform( 1, &minXOut, &minYOut );\n\tcoordTrans->Transform( 1, &maxXout, &maxYOut );\n\tchar * tmp = new char[256];\n\tsprintf( tmp, \"%lf,%lf,%lf,%lf\", minXOut, minYOut, maxXout, maxYOut );\n\tredis->set( rediskey, tmp );\n\n\t/* Create spatial index */\n\tbi::managed_mapped_file file( bi::create_only, outIndex, size * 1024 * 1024 );\n\tallocator_segment\talloc( file.get_segment_manager() );\n\trtree_segment\t\t* rtree_ptr = file.construct<rtree_segment>( \"rtree\" ) ( params(), indexable_segment(), equal_to_segment(), alloc );\n\tbi::managed_mapped_file filembr( bi::create_only, outMBRIndex, size * 128 * 1024 );\n\tallocator_segment\talloc_mbr( filembr.get_segment_manager() );\n\trtree_box\t\t* rtree_ptr_mbr = filembr.construct<rtree_box>( \"rtree\" ) ( params(), indexable_box(), equal_to_box(), alloc_mbr );\n\tunsigned long\t\tpolygonID\t= 0;\n\tdouble\t\t\tpx0, py0, px1, py1;\n\tdouble\t\t\tchange;\n\tdouble\t\t\tminx, miny, maxx, maxy;\n\twhile ( (shpFeature = shpLayer->GetNextFeature() ) != NULL )\n\t{\n\t\tif ( shpFeature == NULL )\n\t\t\tcontinue;\n\t\tOGRGeometry *poGeometry = shpFeature->GetGeometryRef();\n\t\tif ( poGeometry == NULL )\n\t\t\tcontinue;\n\t\tint eType = wkbFlatten( poGeometry->getGeometryType() );\n\t\tif ( eType == wkbPolygon )\n\t\t{\n\t\t\tOGRPolygon\t* pOGRPolygon\t= (OGRPolygon *) poGeometry;\n\t\t\tOGRLinearRing\t*pLinearRing\t= pOGRPolygon->getExteriorRing();\n\t\t\tif ( pLinearRing == NULL )\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint pointCount = pLinearRing->getNumPoints();\n\t\t\tpx0\t= pLinearRing->getX( 0 );\n\t\t\tpy0\t= pLinearRing->getY( 0 );\n\t\t\tchange\t= py0 - pLinearRing->getY( pointCount - 2 );\n\t\t\tcoordTrans->Transform( 1, &px0, &py0 );\n\t\t\tminx\t= px0;\n\t\t\tmaxx\t= px0;\n\t\t\tminy\t= py0;\n\t\t\tmaxy\t= py0;\n\t\t\tfor ( int i = 1; i < pointCount; i++ )\n\t\t\t{\n\t\t\t\tpx1\t= pLinearRing->getX( i );\n\t\t\t\tpy1\t= pLinearRing->getY( i );\n\t\t\t\tcoordTrans->Transform( 1, &px1, &py1 );\n\t\t\t\tminx\t= minx < px1 ? minx : px1;\n\t\t\t\tminy\t= miny < py1 ? miny : py1;\n\t\t\t\tmaxx\t= maxx > px1 ? maxx : px1;\n\t\t\t\tmaxy\t= maxy > py1 ? maxy : py1;\n\t\t\t\tif ( fabs( py1 - py0 ) < tolerance )\n\t\t\t\t{\n\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0, py0 ), point( px1, py1 ) ), polygonID, false ) );\n\t\t\t\t}else if ( change * (py0 - py1) < 0 )\n\t\t\t\t{\n\t\t\t\t\tif ( py0 > py1 )\n\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0 - tolerance * (px1 - px0) / (py1 - py0), py0 - tolerance ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\telse\n\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0 + tolerance * (px1 - px0) / (py1 - py0), py0 + tolerance ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t}else\n\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0, py0 ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\tpx0\t= px1;\n\t\t\t\tpy0\t= py1;\n\t\t\t\tchange\t= py1 - py0;\n\t\t\t}\n\n\t\t\tint innerCount = pOGRPolygon->getNumInteriorRings();\n\t\t\tfor ( int j = 0; j < innerCount; j++ )\n\t\t\t{\n\t\t\t\tpLinearRing\t= pOGRPolygon->getInteriorRing( j );\n\t\t\t\tpointCount\t= pLinearRing->getNumPoints();\n\t\t\t\tpx0\t\t= pLinearRing->getX( 0 );\n\t\t\t\tpy0\t\t= pLinearRing->getY( 0 );\n\t\t\t\tchange\t\t= py0 - pLinearRing->getY( pointCount - 2 );\n\t\t\t\tcoordTrans->Transform( 1, &px0, &py0 );\n\t\t\t\tminx\t= minx < px0 ? minx : px0;\n\t\t\t\tminy\t= miny < py0 ? miny : py0;\n\t\t\t\tmaxx\t= maxx > px0 ? maxx : px0;\n\t\t\t\tmaxy\t= maxy > py0 ? maxy : py0;\n\t\t\t\tfor ( int i = 1; i < pointCount; i++ )\n\t\t\t\t{\n\t\t\t\t\tpx1\t= pLinearRing->getX( i );\n\t\t\t\t\tpy1\t= pLinearRing->getY( i );\n\t\t\t\t\tcoordTrans->Transform( 1, &px1, &py1 );\n\t\t\t\t\tminx\t= minx < px1 ? minx : px1;\n\t\t\t\t\tminy\t= miny < py1 ? miny : py1;\n\t\t\t\t\tmaxx\t= maxx > px1 ? maxx : px1;\n\t\t\t\t\tmaxy\t= maxy > py1 ? maxy : py1;\n\t\t\t\t\tif ( fabs( py1 - py0 ) < tolerance )\n\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0, py0 ), point( px1, py1 ) ), polygonID, false ) );\n\t\t\t\t\telse if ( change * (py0 - py1) < 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( py0 > py1 )\n\t\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0 - tolerance * (px1 - px0) / (py1 - py0), py0 - tolerance ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0 + tolerance * (px1 - px0) / (py1 - py0), py0 + tolerance ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\t}else\n\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0, py0 ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\tpx0\t= px1;\n\t\t\t\t\tpy0\t= py1;\n\t\t\t\t\tchange\t= py1 - py0;\n\t\t\t\t}\n\t\t\t}\n\t\t\trtree_ptr_mbr->insert( std::make_pair( box( point( minx, miny ), point( maxx, maxy ) ), polygonID ) );\n\t\t\tpolygonID++;\n\t\t}else if ( eType == wkbMultiPolygon )\n\t\t{\n\t\t\tOGRMultiPolygon * pOGRMultiPolygon\t= (OGRMultiPolygon *) poGeometry;\n\t\t\tint\t\tpolygonCount\t\t= pOGRMultiPolygon->getNumGeometries();\n\t\t\tfor ( int k = 0; k < polygonCount; k++ )\n\t\t\t{\n\t\t\t\tOGRPolygon\t* pOGRPolygon\t= (OGRPolygon *) pOGRMultiPolygon->getGeometryRef( k );\n\t\t\t\tOGRLinearRing\t*pLinearRing\t= pOGRPolygon->getExteriorRing();\n\t\t\t\tif ( pLinearRing == NULL )\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tint pointCount = pLinearRing->getNumPoints();\n\t\t\t\tpx0\t= pLinearRing->getX( 0 );\n\t\t\t\tpy0\t= pLinearRing->getY( 0 );\n\t\t\t\tchange\t= py0 - pLinearRing->getY( pointCount - 2 );\n\t\t\t\tcoordTrans->Transform( 1, &px0, &py0 );\n\t\t\t\tminx\t= px0;\n\t\t\t\tmaxx\t= px0;\n\t\t\t\tminy\t= py0;\n\t\t\t\tmaxy\t= py0;\n\t\t\t\tfor ( int i = 1; i < pointCount; i++ )\n\t\t\t\t{\n\t\t\t\t\tpx1\t= pLinearRing->getX( i );\n\t\t\t\t\tpy1\t= pLinearRing->getY( i );\n\t\t\t\t\tcoordTrans->Transform( 1, &px1, &py1 );\n\t\t\t\t\tminx\t= minx < px1 ? minx : px1;\n\t\t\t\t\tminy\t= miny < py1 ? miny : py1;\n\t\t\t\t\tmaxx\t= maxx > px1 ? maxx : px1;\n\t\t\t\t\tmaxy\t= maxy > py1 ? maxy : py1;\n\t\t\t\t\tif ( fabs( py1 - py0 ) < tolerance )\n\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0, py0 ), point( px1, py1 ) ), polygonID, false ) );\n\t\t\t\t\telse if ( change * (py0 - py1) < 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( py0 > py1 )\n\t\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0 - tolerance * (px1 - px0) / (py1 - py0), py0 - tolerance ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0 + tolerance * (px1 - px0) / (py1 - py0), py0 + tolerance ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\t}else\n\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0, py0 ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\tpx0\t= px1;\n\t\t\t\t\tpy0\t= py1;\n\t\t\t\t\tchange\t= py1 - py0;\n\t\t\t\t}\n\n\t\t\t\tint innerCount = pOGRPolygon->getNumInteriorRings();\n\t\t\t\tfor ( int j = 0; j < innerCount; j++ )\n\t\t\t\t{\n\t\t\t\t\tpLinearRing\t= pOGRPolygon->getInteriorRing( j );\n\t\t\t\t\tpointCount\t= pLinearRing->getNumPoints();\n\t\t\t\t\tpx0\t\t= pLinearRing->getX( 0 );\n\t\t\t\t\tpy0\t\t= pLinearRing->getY( 0 );\n\t\t\t\t\tchange\t\t= py0 - pLinearRing->getY( pointCount - 2 );\n\t\t\t\t\tcoordTrans->Transform( 1, &px0, &py0 );\n\t\t\t\t\tminx\t= minx < px0 ? minx : px0;\n\t\t\t\t\tminy\t= miny < py0 ? miny : py0;\n\t\t\t\t\tmaxx\t= maxx > px0 ? maxx : px0;\n\t\t\t\t\tmaxy\t= maxy > py0 ? maxy : py0;\n\t\t\t\t\tfor ( int i = 1; i < pointCount; i++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tpx1\t= pLinearRing->getX( i );\n\t\t\t\t\t\tpy1\t= pLinearRing->getY( i );\n\t\t\t\t\t\tcoordTrans->Transform( 1, &px1, &py1 );\n\t\t\t\t\t\tminx\t= minx < px1 ? minx : px1;\n\t\t\t\t\t\tminy\t= miny < py1 ? miny : py1;\n\t\t\t\t\t\tmaxx\t= maxx > px1 ? maxx : px1;\n\t\t\t\t\t\tmaxy\t= maxy > py1 ? maxy : py1;\n\t\t\t\t\t\tif ( fabs( py1 - py0 ) < tolerance )\n\t\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0, py0 ), point( px1, py1 ) ), polygonID, false ) );\n\t\t\t\t\t\telse if ( change * (py0 - py1) < 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( py0 > py1 )\n\t\t\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0 - tolerance * (px1 - px0) / (py1 - py0), py0 - tolerance ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0 + tolerance * (px1 - px0) / (py1 - py0), py0 + tolerance ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\t\t}else\n\t\t\t\t\t\t\trtree_ptr->insert( boost::make_tuple( segment( point( px0, py0 ), point( px1, py1 ) ), polygonID, true ) );\n\t\t\t\t\t\tpx0\t= px1;\n\t\t\t\t\t\tpy0\t= py1;\n\t\t\t\t\t\tchange\t= py1 - py0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trtree_ptr_mbr->insert( std::make_pair( box( point( minx, miny ), point( maxx, maxy ) ), polygonID ) );\n\t\t\t\tpolygonID++;\n\t\t\t}\n\t\t}\n\t}\n\tif ( rtree_ptr->size() < 1 )\n\t{\n\t\tprintf( \"[ERROR] No feature found. shpFile:%s outIndex:%s\\n\", shpFile, outIndex );\n\t\tremove( outIndex );\n\t\tremove( outMBRIndex );\n\t\treturn(false);\n\t}\n\n\t/* Shrink the spatial index file to minimize the space waste */\n\tbi::managed_mapped_file::shrink_to_fit( outIndex );\n\tbi::managed_mapped_file::shrink_to_fit( outMBRIndex );\n\n\t/* Write process log */\n\tgettimeofday( &t2, NULL );\n\ttimeuse = t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) / 1000000.0;\n\tprintf( \"[DONE] %s Use Time:%f\\n\", outIndex, timeuse );\n\treturn(true);\n}\n\n\nclass ServerLogHandler : public crow::ILogHandler {\npublic:\n\tvoid log( std::string /*message*/, crow::LogLevel /*level*/ ) override\n\t{\n\t}\n};\n\nstruct ServerMiddleware\n{\n\tstd::string message;\n\n\tServerMiddleware()\n\t{\n\t\tmessage = \"foo\";\n\t}\n\n\n\tvoid setMessage( std::string newMsg )\n\t{\n\t\tmessage = newMsg;\n\t}\n\n\n\tstruct context\n\t{\n\t};\n\n\tvoid before_handle( crow::request & /*req*/, crow::response & /*res*/, context & /*ctx*/ )\n\t{\n\t\tCROW_LOG_DEBUG << \" - MESSAGE: \" << message;\n\t}\n\n\n\tvoid after_handle( crow::request & /*req*/, crow::response & /*res*/, context & /*ctx*/ )\n\t{\n\t\t/* no-op */\n\t}\n};\n\n\n/**\n * @brief HiVision service main function\n * @param nArgc         Input parameters copunt\n * @param papszArgv Input startup parameters\n *\n */\nint main( int nArgc, char ** papszArgv )\n{\n\thvpara.shpPath\t\t= papszArgv[1];         /* Path of the input shapefiles */\n\thvpara.indexPath\t= papszArgv[2];         /* Path to store the spatial indexes */\n\thvpara.patternPath\t= papszArgv[3];         /* Path of the input patterns */\n\thvpara.redisHost\t= papszArgv[4];         /* Host IP of Redis */\n\thvpara.redisPort\t= atoi( papszArgv[5] ); /* Host Port of Redis */\n\thvpara.servicePort\t= atoi( papszArgv[6] ); /* Port of the HiVision services */\n\n\tcrow::App<ServerMiddleware> app;\n\n\n\t/**\n\t * Vector Data Registration Service\n\t * http://hostIP:servicePort/HiVision/add/{shapefile_name}/{id}/{type}\n\t * Point: type=0\n\t * LineString: type=1\n\t * Polygon: type=2\n\t */\n\tCROW_ROUTE( app, \"/HiVision/add/<string>/<string>/<int>\" ).name( \"HiVisionAdd\" )\n\t\t([] (const crow::request & req, crow::response & res, string shp, string appid, int type) {\n\t\t\tchar* redisHost = hvpara.redisHost;\n\t\t\tint redisPort = hvpara.redisPort;\n\t\t\tchar* shpPath = hvpara.shpPath;\n\t\t\tchar* indexPath = hvpara.indexPath;\n\t\t\ttry{\n\t\t\t\tchar * tmp1 = new char[256];\n\t\t\t\tchar * tmp2 = new char[256];\n\t\t\t\tchar * tmp3 = new char[256];\n\t\t\t\tif ( type < 3 )\n\t\t\t\t{\n\t\t\t\t\tsprintf( tmp1, \"%s/%s.shp\", shpPath, shp.c_str() );\n\t\t\t\t\tfstream f;\n\t\t\t\t\tf.open( tmp1, ios::in );\n\t\t\t\t\tif ( !f )\n\t\t\t\t\t{\n\t\t\t\t\t\tres.write( \"[ERROR] Dataset not found!\" );\n\t\t\t\t\t\tthrow \"Dataset not found!\";\n\t\t\t\t\t}\n\t\t\t\t\tf.close();\n\t\t\t\t}else{\n\t\t\t\t\tsprintf( tmp1, \"%s\", shp.c_str() );\n\t\t\t\t}\n\t\t\t\tif ( type == 0 ) /* type=0 Register point dataset */\n\t\t\t\t{\n\t\t\t\t\tsprintf( tmp2, \"%sp%s\", indexPath, appid.c_str() );\n\t\t\t\t\tsprintf( tmp3, \"p%s\", appid.c_str() );\n\t\t\t\t\tif ( Point( tmp1, tmp2, redisHost, tmp3, redisPort ) )\n\t\t\t\t\t\tres.write( \"[DONE] Register done!\" );\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow \"Failed\";\n\t\t\t\t}else if ( type == 1 ) /* type=1  Register LineString dataset */\n\t\t\t\t{\n\t\t\t\t\tsprintf( tmp2, \"%sl%s\", indexPath, appid.c_str() );\n\t\t\t\t\tsprintf( tmp3, \"l%s\", appid.c_str() );\n\t\t\t\t\tif ( Linestring( tmp1, tmp2, redisHost, tmp3, redisPort ) )\n\t\t\t\t\t\tres.write( \"[DONE] Register done!\" );\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow \"Failed\";\n\t\t\t\t}else if ( type == 2 ) /* type=2 Register Polygon dataset */\n\t\t\t\t{\n\t\t\t\t\tsprintf( tmp2, \"%sa%s\", indexPath, appid.c_str() );\n\t\t\t\t\tsprintf( tmp3, \"a%s\", appid.c_str() );\n\t\t\t\t\tif ( Polygon( tmp1, tmp2, redisHost, tmp3, redisPort ) )\n\t\t\t\t\t\tres.write( \"[DONE] Register done!\" );\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow \"Failed\";\n\t\t\t\t}else{\n\t\t\t\t\tres.write( \"[ERROR] Wrong type!\" );\n\t\t\t\t}\n\t\t\t\tres.end();\n\t\t\t}\n\t\t\tcatch ( const char* msg )\n\t\t\t{\n\t\t\t\tres.write( \"[ERROR] Register failed\" );\n\t\t\t\tres.end();\n\t\t\t}\n\t\t} );\n\n\n\t/**\n\t * Vector Data Visualization WMTS (Scattor Plot)\n\t * http://hostIP:servicePort/HiVision/{id}/{R}/{G}/{B}/{A}/{z}/{x}/{y}.png\n\t * Point: type=0\n\t * LineString: type=1\n\t * Polygon: type=2\n\t */\n\tCROW_ROUTE( app, \"/HiVision/<string>/<int>/<int>/<int>/<double>/<int>/<int>/<int>.png\" ).name( \"HiVision\" )\n\t\t([] (const crow::request & req, crow::response & res, string appid, int R, int G, int B, double AD, int z, int x, int y) {\n\t\t\tchar* redisHost = hvpara.redisHost;\n\t\t\tint redisPort = hvpara.redisPort;\n\t\t\tstd::ostringstream os;\n\t\t\tRedis *redis = new Redis();\n\t\t\tif ( !redis->connect( redisHost, redisPort ) )\n\t\t\t{\n\t\t\t\tprintf( \"connect redis error!\\n\" );\n\t\t\t}\n\t\t\tint A = AD * 64;\n\t\t\tint AH = AD * 256;\n\t\t\tint Ax = (1 - AD) * 64;\n\t\t\tint Ay = -64;\n\t\t\tchar* key = new char[32];\n\t\t\tchar* newkey = new char[32];\n\t\t\tvector<char> pos;\n\t\t\tlong size;\n\t\t\tpng_bytep * row_pointers = (png_bytep *) malloc( 256 * sizeof(png_bytep) );\n\t\t\tfor ( int i = 0; i < TILE_SIZE; i++ )\n\t\t\t\trow_pointers[i] = (png_bytep) malloc( 1024 );\n\n\t                /* Generate tiles */\n\t\t\ttry{\n\t\t\t\tchar * tmp = new char[256];\n\t\t\t\tint count;\n\t\t\t\tchar* bbox[8];\n\t\t\t\tsprintf( tmp, \"%s\", redis->get( appid ).c_str() );\n\t\t\t\tGetList( tmp, bbox, (char *) \",\", count );\n\t\t\t\tdouble minx = atof( bbox[0] );\n\t\t\t\tdouble miny = atof( bbox[1] );\n\t\t\t\tdouble maxx = atof( bbox[2] );\n\t\t\t\tdouble maxy = atof( bbox[3] );\n\t\t\t\tdouble tile_minx = ( (256 * x + 0.5) / (128 << z) - 1) * L;\n\t\t\t\tdouble tile_miny = (1 - (256 * y + 255.5) / (128 << z) ) * L;\n\t\t\t\tdouble tile_maxx = ( (256 * x + 255.5) / (128 << z) - 1) * L;\n\t\t\t\tdouble tile_maxy = (1 - (256 * y - 0.5) / (128 << z) ) * L;\n\t\t\t\tdelete tmp;\n\n\t                        /* Filter out tiles that are not in the spatial scope of data MBRs */\n\t\t\t\tif ( tile_minx < maxx && tile_miny < maxy && tile_maxx > minx && tile_maxy > miny )\n\t\t\t\t{\n\t\t\t\t\tsprintf( key, \"%s/%d/%d/%d\", appid.c_str(), z, x, y );\n\t\t\t\t\tchar (*buffer_area)[TILE_SIZE] = (char(*)[TILE_SIZE])malloc( TILE_SIZE * TILE_SIZE );\n\n\t                        /* Filter out tiles that are previously processed and the visualization results that are still preserved in the Result Pool */\n\t\t\t\t\tif ( !redis->zget( key, (char *) buffer_area ) )\n\t\t\t\t\t{\n\t                        /* Create new tasks in the Task Pool */\n\t\t\t\t\t\tmemset( newkey, 0, 32 );\n\t\t\t\t\t\tredisContext* rc = redisConnect( redisHost, redisPort );\n\t\t\t\t\t\tredisReply* reply = (redisReply *) redisCommand( rc, \"subscribe HiVisiontiles\" );\n\t\t\t\t\t\tredis->lpush( \"HiVisiontasklist\", key );\n\t\t\t\t\t\twhile ( strcmp( newkey, key ) != 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( redisGetReply( rc, (void * *) &reply ) == REDIS_OK && reply->type == REDIS_REPLY_ARRAY )\n\t\t\t\t\t\t\t\tsprintf( newkey, \"%s\", reply->element[2]->str );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tredis->zget( key, (char *) buffer_area );\n\t\t\t\t\t\tfreeReplyObject( reply );\n\t\t\t\t\t\tredisFree( rc );\n\t\t\t\t\t}\n\n\t                                /* collect results from Result Pool and render tiles according the given styles */\n\t\t\t\t\tpng_structp png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );\n\t\t\t\t\tpng_infop info_ptr = png_create_info_struct( png_ptr );\n\t\t\t\t\tFILE *temp_png = tmpfile();\n\t\t\t\t\tpng_init_io( png_ptr, temp_png );\n\t\t\t\t\tpng_set_IHDR( png_ptr, info_ptr, TILE_SIZE, TILE_SIZE, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE );\n\t\t\t\t\tpng_write_info( png_ptr, info_ptr );\n\t\t\t\t\tfor ( int i = 0; i < TILE_SIZE; i++ )\n\t\t\t\t\t\tfor ( int j = 0; j < TILE_SIZE; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( buffer_area[i][j] > 4 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = R;     /* red */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = G; /* green */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = B; /* blue */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = AH + Ax * (buffer_area[i][j] - 4) - 1;\n\t\t\t\t\t\t\t}else if ( buffer_area[i][j] > 0 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = R;     /* red */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = G; /* green */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = B; /* blue */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = buffer_area[i][j] * A - 1;\n\t\t\t\t\t\t\t}else if ( buffer_area[i][j] < 0 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = R;     /* red */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = G; /* green */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = B; /* blue */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = buffer_area[i][j] * Ay - 1;\n\t\t\t\t\t\t\t}else  {\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = 0;     /* red */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = 0; /* green */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = 0; /* blue */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tfree( buffer_area );\n\t\t\t\t\tpng_write_image( png_ptr, row_pointers );\n\t\t\t\t\tpng_write_end( png_ptr, NULL );\n\t\t\t\t\tfseek( temp_png, 0, SEEK_END );\n\t\t\t\t\tsize = ftell( temp_png );\n\t\t\t\t\trewind( temp_png );\n\t\t\t\t\tpos.resize( size );\n\t\t\t\t\tfread( &pos[0], 1, size, temp_png );\n\t\t\t\t\tfclose( temp_png );\n\t\t\t\t\tstring pos_tostr = string( pos.begin(), pos.end() );\n\t\t\t\t\tres.write( pos_tostr );\n\t\t\t\t\tres.set_header( \"Content-Type\", \"image/png\" );\n\t\t\t\t\tres.set_header( \"Access-Control-Allow-Origin\", \"*\" );\n\t\t\t\t}else\n\t\t\t\t\tthrow \"Tile out range!\";\n\t\t\t\tredis->freeredis();\n\t\t\t\tdelete key;\n\t\t\t\tdelete newkey;\n\t\t\t\tfor ( int j = 0; j < 256; j++ )\n\t\t\t\t\tfree( row_pointers[j] );\n\t\t\t\tfree( row_pointers );\n\t\t\t\tres.end();\n\t\t\t}\n\t\t\tcatch ( const char* msg )\n\t\t\t{\n\t\t\t\tredis->freeredis();\n\t\t\t\tdelete key;\n\t\t\t\tdelete newkey;\n\n\t\t\t\tfor ( int j = 0; j < 256; j++ )\n\t\t\t\t\tfree( row_pointers[j] );\n\t\t\t\tfree( row_pointers );\n\t\t\t\tres.code = 500;\n\t\t\t\tos << \"ERROR: \" << msg << \"\\n\";\n\t\t\t\tres.write( os.str() );\n\t\t\t\tres.set_header( \"Content-Type\", \"text/html\" );\n\t\t\t\tres.end();\n\t\t\t}\n\t\t} );\n\n\n\t/**\n\t * Vector Data Visualization WMTS (Patterns Filling for Polygon Objects)\n\t * http://hostIP:servicePort/HiVision/{id}/{R}/{G}/{B}/{pattern_id}/{A}/{z}/{x}/{y}.png\n\t */\n\tCROW_ROUTE( app, \"/HiVision/<string>/<int>/<int>/<int>/<string>/<double>/<int>/<int>/<int>.png\" ).name( \"HiVision\" )\n\t\t([] (const crow::request & req, crow::response & res, string appid, int R, int G, int B, string pattern, double AD, int z, int x, int y) {\n\t                /* Init */\n\t\t\tchar* redisHost = hvpara.redisHost;\n\t\t\tint redisPort = hvpara.redisPort;\n\t\t\tstd::ostringstream os;\n\t\t\tRedis *redis = new Redis();\n\t\t\tif ( !redis->connect( redisHost, redisPort ) )\n\t\t\t{\n\t\t\t\tprintf( \"connect redis error!\\n\" );\n\t\t\t}\n\t\t\tint A = AD * 64;\n\t\t\tint AH = AD * 256;\n\t\t\tint Ax = (1 - AD) * 64;\n\t\t\tint Ay = -64;\n\t\t\tchar* key = new char[32];\n\t\t\tchar* newkey = new char[32];\n\t\t\tvector<char> pos;\n\t\t\tlong size;\n\t\t\tFILE *pic_fp;\n\t\t\tpng_structp png_ptr, pattern_png_ptr;\n\t\t\tpng_infop info_ptr, pattern_info_ptr;\n\t\t\tpattern_png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, 0, 0, 0 );\n\t\t\tpattern_info_ptr = png_create_info_struct( pattern_png_ptr );\n\t\t\tsetjmp( png_jmpbuf( pattern_png_ptr ) );\n\t\t\tpng_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, 0, 0, 0 );\n\t\t\tinfo_ptr = png_create_info_struct( png_ptr );\n\t\t\tsetjmp( png_jmpbuf( png_ptr ) );\n\t\t\tpng_bytep * row_pointers = (png_bytep *) malloc( 256 * sizeof(png_bytep) );\n\t\t\tfor ( int i = 0; i < TILE_SIZE; i++ )\n\t\t\t\trow_pointers[i] = (png_bytep) malloc( 1024 );\n\t                /* Generate tiles */\n\t\t\ttry{\n\t\t\t\tchar * pngfile = new char[256];\n\t\t\t\tsprintf( pngfile, \"%s%s.png\", hvpara.patternPath, pattern.c_str() );\n\t\t\t\tpic_fp = fopen( pngfile, \"rb\" );\n\t\t\t\tif ( pic_fp == NULL )\n\t\t\t\t\tthrow \"Open pattern file failed!\";\n\t\t\t\trewind( pic_fp );\n\t\t\t\tpng_init_io( pattern_png_ptr, pic_fp );\n\t\t\t\tpng_read_png( pattern_png_ptr, pattern_info_ptr, PNG_TRANSFORM_EXPAND, 0 );\n\t\t\t\tint pattern_width, pattern_height;\n\t\t\t\tpng_bytep* pattern_row_pointers;\n\t\t\t\tpattern_row_pointers = png_get_rows( pattern_png_ptr, pattern_info_ptr );\n\t\t\t\tpattern_width = png_get_image_width( pattern_png_ptr, pattern_info_ptr );\n\t\t\t\tpattern_height = png_get_image_height( pattern_png_ptr, pattern_info_ptr );\n\t\t\t\tchar * tmp = new char[256];\n\t\t\t\tint count;\n\t\t\t\tchar* bbox[8];\n\t\t\t\tsprintf( tmp, \"%s\", redis->get( appid ).c_str() );\n\t\t\t\tGetList( tmp, bbox, (char *) \",\", count );\n\t\t\t\tdouble minx = atof( bbox[0] );\n\t\t\t\tdouble miny = atof( bbox[1] );\n\t\t\t\tdouble maxx = atof( bbox[2] );\n\t\t\t\tdouble maxy = atof( bbox[3] );\n\t\t\t\tdouble tile_minx = ( (256 * x + 0.5) / (128 << z) - 1) * L;\n\t\t\t\tdouble tile_miny = (1 - (256 * y + 255.5) / (128 << z) ) * L;\n\t\t\t\tdouble tile_maxx = ( (256 * x + 255.5) / (128 << z) - 1) * L;\n\t\t\t\tdouble tile_maxy = (1 - (256 * y - 0.5) / (128 << z) ) * L;\n\t\t\t\tdelete tmp;\n\t\t\t\tif ( tile_minx < maxx && tile_miny < maxy && tile_maxx > minx && tile_maxy > miny )     /* Filter out tiles that are not in the spatial scope of data MBRs */\n\t\t\t\t{\n\t\t\t\t\tsprintf( key, \"%s/%d/%d/%d\", appid.c_str(), z, x, y );\n\t\t\t\t\tchar (*buffer_area)[TILE_SIZE] = (char(*)[TILE_SIZE])malloc( TILE_SIZE * TILE_SIZE );\n\t\t\t\t\tif ( !redis->zget( key, (char *) buffer_area ) )                                /* Filter out tiles that are previously processed and the visualization results that are still preserved in the Result Pool */\n\t\t\t\t\t{\n\t                                                                                                                /* Create new tasks in the Task Pool */\n\t\t\t\t\t\tmemset( newkey, 0, 32 );\n\t\t\t\t\t\tredisContext* rc = redisConnect( redisHost, redisPort );\n\t\t\t\t\t\tredisReply* reply = (redisReply *) redisCommand( rc, \"subscribe HiVisiontiles\" );\n\t\t\t\t\t\tredis->lpush( \"HiVisiontasklist\", key );\n\t\t\t\t\t\twhile ( strcmp( newkey, key ) != 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( redisGetReply( rc, (void * *) &reply ) == REDIS_OK && reply->type == REDIS_REPLY_ARRAY )\n\t\t\t\t\t\t\t\tsprintf( newkey, \"%s\", reply->element[2]->str );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tredis->zget( key, (char *) buffer_area );\n\t\t\t\t\t\tfreeReplyObject( reply );\n\t\t\t\t\t\tredisFree( rc );\n\t\t\t\t\t}\n\t                                /* collect results from Result Pool and render tiles according the given styles */\n\t\t\t\t\tpng_structp png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );\n\t\t\t\t\tpng_infop info_ptr = png_create_info_struct( png_ptr );\n\t\t\t\t\tFILE *temp_png = tmpfile();\n\t\t\t\t\tpng_init_io( png_ptr, temp_png );\n\t\t\t\t\tpng_set_IHDR( png_ptr, info_ptr, TILE_SIZE, TILE_SIZE, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE );\n\t\t\t\t\tpng_write_info( png_ptr, info_ptr );\n\t\t\t\t\tfor ( int i = 0; i < TILE_SIZE; i++ )\n\t\t\t\t\t\tfor ( int j = 0; j < TILE_SIZE; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( buffer_area[i][j] > 4 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = R;\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = G;\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = B;\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = AH + Ax * (buffer_area[i][j] - 4) - 1;\n\t\t\t\t\t\t\t}else if ( buffer_area[i][j] == 4 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = pattern_row_pointers[(i + 256 * y) % pattern_height][4 * ( (j + 256 * x) % pattern_width)];\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = pattern_row_pointers[(i + 256 * y) % pattern_height][4 * ( (j + 256 * x) % pattern_width) + 1];\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = pattern_row_pointers[(i + 256 * y) % pattern_height][4 * ( (j + 256 * x) % pattern_width) + 2];\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = pattern_row_pointers[(i + 256 * y) % pattern_height][4 * ( (j + 256 * x) % pattern_width) + 3];;\n\t\t\t\t\t\t\t}else if ( buffer_area[i][j] > 0 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = R;     /* red */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = G; /* green */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = B; /* blue */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = buffer_area[i][j] * A - 1;\n\t\t\t\t\t\t\t}else if ( buffer_area[i][j] < 0 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = R;     /* red */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = G; /* green */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = B; /* blue */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = buffer_area[i][j] * Ay - 1;\n\t\t\t\t\t\t\t}else  {\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j] = 0;     /* red */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 1] = 0; /* green */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 2] = 0; /* blue */\n\t\t\t\t\t\t\t\trow_pointers[i][4 * j + 3] = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tfree( buffer_area );\n\t\t\t\t\tpng_write_image( png_ptr, row_pointers );\n\t\t\t\t\tpng_write_end( png_ptr, NULL );\n\t\t\t\t\tfseek( temp_png, 0, SEEK_END );\n\t\t\t\t\tsize = ftell( temp_png );\n\t\t\t\t\trewind( temp_png );\n\t\t\t\t\tpos.resize( size );\n\t\t\t\t\tfread( &pos[0], 1, size, temp_png );\n\t\t\t\t\tfclose( temp_png );\n\t\t\t\t\tstring pos_tostr = string( pos.begin(), pos.end() );\n\t\t\t\t\tres.write( pos_tostr );\n\t\t\t\t\tres.set_header( \"Content-Type\", \"image/png\" );\n\t\t\t\t\tres.set_header( \"Access-Control-Allow-Origin\", \"*\" );\n\t\t\t\t}else\n\t\t\t\t\tthrow \"Tile out range!\";\n\t\t\t\tredis->freeredis();\n\t\t\t\tdelete key;\n\t\t\t\tdelete newkey;\n\t\t\t\tpng_destroy_read_struct( &png_ptr, &info_ptr, 0 );\n\t\t\t\tpng_destroy_read_struct( &pattern_png_ptr, &pattern_info_ptr, 0 );\n\t\t\t\tfclose( pic_fp );\n\t\t\t\tfor ( int j = 0; j < 256; j++ )\n\t\t\t\t\tfree( row_pointers[j] );\n\t\t\t\tfree( row_pointers );\n\t\t\t\tres.end();\n\t\t\t}\n\t\t\tcatch ( const char* msg )\n\t\t\t{\n\t\t\t\tredis->freeredis();\n\t\t\t\tdelete key;\n\t\t\t\tdelete newkey;\n\t\t\t\tpng_destroy_read_struct( &png_ptr, &info_ptr, 0 );\n\t\t\t\tfclose( pic_fp );\n\t\t\t\tfor ( int j = 0; j < 256; j++ )\n\t\t\t\t\tfree( row_pointers[j] );\n\t\t\t\tfree( row_pointers );\n\t\t\t\tres.code = 500;\n\t\t\t\tos << \"ERROR: \" << msg << \"\\n\";\n\t\t\t\tres.write( os.str() );\n\t\t\t\tres.set_header( \"Content-Type\", \"text/html\" );\n\t\t\t\tres.end();\n\t\t\t}\n\t\t} );\n\n\tapp.port( hvpara.servicePort )\n\t.multithreaded()\n\t.run();\n}\n\n\n", "meta": {"hexsha": "4f22f80a6f53ae9a18c5bbb6d60e26b917266e57", "size": 41727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HiVision_code/src/server.cpp", "max_stars_repo_name": "MemoryMmy/HiVision", "max_stars_repo_head_hexsha": "cbdd9e3fc8459da8487ab80010d0567733fd3ef9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T01:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:27:52.000Z", "max_issues_repo_path": "HiVision_code/src/server.cpp", "max_issues_repo_name": "MemoryMmy/HiVision", "max_issues_repo_head_hexsha": "cbdd9e3fc8459da8487ab80010d0567733fd3ef9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-03-26T04:21:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-12T05:22:02.000Z", "max_forks_repo_path": "HiVision_code/src/server.cpp", "max_forks_repo_name": "MemoryMmy/HiVision", "max_forks_repo_head_hexsha": "cbdd9e3fc8459da8487ab80010d0567733fd3ef9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-13T17:49:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T14:29:52.000Z", "avg_line_length": 35.5728900256, "max_line_length": 211, "alphanum_fraction": 0.6135116352, "num_tokens": 13394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.15003553605536696}}
{"text": "#include \"Mesh.h\"\n#include <igl/per_vertex_normals.h>\n#include <igl/polygon_mesh_to_triangle_mesh.h>\n#include <igl/per_face_normals.h>\n#include <igl/draw_mesh.h>\n#include <Eigen/Geometry>\n\nvoid Mesh::draw_and_cache()\n{\n  using namespace Eigen;\n  using namespace igl;\n  if(wireframe || show_weights)\n  {\n    glPushAttrib(GL_POLYGON_BIT);\n    glPushAttrib(GL_ENABLE_BIT);\n    glPushAttrib(GL_LIGHTING_BIT);\n    glPushAttrib(GL_LINE_BIT);\n    if(wireframe)\n    {\n      glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);\n    }\n    glEnable(GL_COLOR_MATERIAL);\n    if(show_weights)\n    {\n      glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT);\n      glColor3f(0.1,0.1,0.1);\n      glColorMaterial(GL_FRONT_AND_BACK,GL_SPECULAR);\n      glColor3f(0.4,0.4,0.4);\n    }else\n    {\n      glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT);\n      glColor3f(0.,0,0);\n      glColorMaterial(GL_FRONT_AND_BACK,GL_SPECULAR);\n      glColor3f(0.,0,0);\n    }\n    glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);\n    if(wireframe)\n    {\n      glColor3f(0,0,0);\n    }\n    if(!glIsList(dl) || stale)\n    {\n      assert(V.rows() == U.rows());\n      if(show_weights && W.cols()>0)\n      {\n        per_vertex_normals(U,F,N);\n        C.resize(V.rows(),3);\n        for(size_t v = 0;v<V.rows();v++)\n        {\n          C(v,0) = 1;\n          double w = 0;\n          for(size_t selected_weight : selected_weights)\n          {\n            w+=W(v,selected_weight);\n          }\n          C(v,1) = 1.-w;\n          C(v,2) = 1.-w;\n        }\n      }\n      if(glIsList(dl))\n      {\n        glDeleteLists(dl,1);\n      }\n      dl = glGenLists(1);\n      glNewList(dl,GL_COMPILE_AND_EXECUTE);\n      if(show_weights)\n      {\n        draw_mesh(U,F,N,C);\n      }else\n      { \n        draw_mesh(U,Q,N);\n      }\n      glEndList();\n    }else\n    {\n      glCallList(dl);\n    }\n    glPopAttrib();\n    glPopAttrib();\n    glPopAttrib();\n    glPopAttrib();\n  } else\n  {\n\n    if(!glIsBuffer(ibo))\n    {\n      T.resize(Q.rows()*2,3);\n      Matrix<GLuint,Dynamic,Dynamic,RowMajor> TCT(T.rows(),3);\n      for(int q=0;q<Q.rows();q++)\n      {\n        T(q*2+0,0) = Q(q,0);\n        T(q*2+0,1) = Q(q,1);\n        T(q*2+0,2) = Q(q,2);\n        T(q*2+1,0) = Q(q,0);\n        T(q*2+1,1) = Q(q,2);\n        T(q*2+1,2) = Q(q,3)==-1?Q(q,2):Q(q,3);\n      }\n      T1 = Q.leftCols(3).eval();\n      for(int f=0;f<T.rows();f++)\n      {\n        for(int c = 0;c<3;c++)\n        {\n          TCT(f,c) = f*3+c;\n        }\n      }\n      UCT.resize(3*T.rows(),3);\n      NCT.resize(3*T.rows(),3);\n      glGenBuffers(1,&ibo);\n      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,ibo);\n      glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(GLuint)*TCT.size(),TCT.data(),GL_STATIC_DRAW);\n      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);\n      glGenBuffers(1,&vbo);\n      glGenBuffers(1,&nbo);\n    }\n\n    const int Trows = T.rows();\n#   pragma omp parallel for if (Trows>10000)\n    for(int f=0;f<Trows;f+=2)\n    {\n      for(int c = 0;c<3;c++)\n      {\n        UCT.row(f*3+c) = U.row(T(f,c)).cast<float>();\n        UCT.row((f+1)*3+c) = U.row(T(f+1,c)).cast<float>();\n      }\n      Matrix<float,1,3,RowMajor> v1 = UCT.row(f*3+1)-UCT.row(f*3+0);\n      Matrix<float,1,3,RowMajor> v2 = UCT.row(f*3+2)-UCT.row(f*3+0);\n      Matrix<float,1,3,RowMajor> n = v1.cross(v2);\n      for(int c = 0;c<3;c++)\n      {\n        for(int d = 0;d<3;d++)\n        {\n          const float nd = n(d);\n          NCT(f*3+c,d) = nd;\n          NCT((f+1)*3+c,d) = nd;\n        }\n      }\n    }\n\n      glEnableClientState(GL_VERTEX_ARRAY);\n      glBindBuffer(GL_ARRAY_BUFFER,vbo);\n      glBufferData(GL_ARRAY_BUFFER,sizeof(float)*UCT.size(),UCT.data(),GL_DYNAMIC_DRAW);\n      glVertexPointer(3,GL_FLOAT,0,0);\n      glEnableClientState(GL_NORMAL_ARRAY);\n      glBindBuffer(GL_ARRAY_BUFFER,nbo);\n      glBufferData(GL_ARRAY_BUFFER,sizeof(float)*NCT.size(),NCT.data(),GL_DYNAMIC_DRAW);\n      glNormalPointer(GL_FLOAT,0,0);\n      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,ibo);\n      glDrawElements(GL_TRIANGLES,T.size(),GL_UNSIGNED_INT,0);\n      glBindBuffer(GL_ARRAY_BUFFER,0);\n    }\n\n  stale = false;\n}\n", "meta": {"hexsha": "9c05e24f542f9d19369106a0e31007c4a28ed3d7", "size": 4032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "subdivgui/Mesh.cpp", "max_stars_repo_name": "CraGL/SubdivisionSkinning", "max_stars_repo_head_hexsha": "c593a7a4e38a49716e9d3981824871a7b6c29324", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2017-03-29T00:14:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T15:44:44.000Z", "max_issues_repo_path": "subdivgui/Mesh.cpp", "max_issues_repo_name": "Myzhencai/SubdivisionSkinning", "max_issues_repo_head_hexsha": "c593a7a4e38a49716e9d3981824871a7b6c29324", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T21:48:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-08T21:48:11.000Z", "max_forks_repo_path": "subdivgui/Mesh.cpp", "max_forks_repo_name": "Myzhencai/SubdivisionSkinning", "max_forks_repo_head_hexsha": "c593a7a4e38a49716e9d3981824871a7b6c29324", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T17:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-28T18:00:26.000Z", "avg_line_length": 26.1818181818, "max_line_length": 96, "alphanum_fraction": 0.5553075397, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.15003553605536693}}
